{"text":"#include \"SyntaxTree.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\n#include \"parser.tab.hh\"\n\n#include \"template.common.h\"\n#include \"template.cs.h\"\n\nusing namespace std;\nusing namespace Krystal;\n\n\/\/ class Node\n\/\/ {\n\/\/ public:\n Krystal::Node::Node(Context* _context)\n {\n context = _context;\n }\n\n Krystal::Node::~Node()\n {\n }\n\n int Krystal::Node::getType() { return 0; } \/\/TODO: remove getType() if unnecessary\n size_t Krystal::Node::getHash(vector* referencingStack) { return 0; }\n string* Krystal::Node::getParsed(int as) { return 0; }\n\n\/\/ };\n\n\/\/ class NodeKst : public Node\n\/\/ {\n \/\/ list* commands;\n \/\/ string* fileName;\n \/\/ public:\n Krystal::NodeKst::NodeKst(Context* _context, list* _commands, string* _fileName) : Node(_context)\n {\n commands = _commands;\n fileName = _fileName;\n }\n\n int Krystal::NodeKst::getType()\n {\n return CsNodeType::kst;\n }\n\n size_t Krystal::NodeKst::getHash(vector* referencingStack)\n {\n return 0;\n }\n\n string* Krystal::NodeKst::getParsed(int as)\n {\n stringstream parsed;\n\n parsed << boost::format(TCS_HEADER) % *fileName;\n parsed << TCS_USINGS;\n\n string namespaceByFileName = fileName->substr(0, fileName->find(\".\"));\n\n parsed << boost::format(TCS_NAMESPACE_BEGIN) % namespaceByFileName;\n\n list::iterator i = commands->begin();\n list::iterator end = commands->end();\n\n string* temp;\n\n for (; i != end; ++i)\n {\n temp = (*i)->getParsed(CsParseAs::Default);\n temp = indent(temp);\n parsed << *temp;\n parsed << \"\\n\";\n }\n\n parsed << TCS_NAMESPACE_END;\n\n parsed << \"\\n\\n\";\n\n return new string(parsed.str());\n }\n\/\/ };\n\n\/\/ class NodeInclude : public Node\n\/\/ {\n\/\/ string* value;\n\/\/ public:\n Krystal::NodeInclude::NodeInclude(Context* _context, string* _value) : Node(_context)\n {\n value = _value;\n }\n\n int Krystal::NodeInclude::getType()\n {\n return CsNodeType::include;\n }\n\n size_t Krystal::NodeInclude::getHash(vector* referencingStack)\n {\n return 0;\n }\n\n string* Krystal::NodeInclude::getParsed(int as)\n {\n stringstream parsed;\n\n parsed << \"#include \\\"\";\n parsed << *(value);\n parsed << \"\\\"\";\n\n return new string(parsed.str());\n }\n\/\/ };\n\n\/\/ class NodePacket : public Node\n\/\/ {\n\/\/ string* packetName;\n\/\/ list* packetMembers;\n\/\/ public:\n Krystal::NodePacket::NodePacket(Context* _context, string* _packetName, list* _packetMembers) : Node(_context)\n {\n packetName = _packetName;\n packetMembers = _packetMembers;\n }\n\n int Krystal::NodePacket::getType()\n {\n return CsNodeType::packet;\n }\n\n size_t Krystal::NodePacket::getHash(vector* referencingStack)\n {\n if (referencingStack == NULL)\n {\n referencingStack = new vector();\n }\n else \/\/ check circular reference\n {\n vector::iterator end = referencingStack->end();\n for (vector::iterator i = referencingStack->begin(); i != end; i++)\n {\n if (*i == this)\n {\n throw(runtime_error(\"Circular reference between packets\"));\n }\n }\n }\n\n referencingStack->push_back(this);\n\n size_t packetHash = getHashCode(packetName);\n\n list::iterator i = packetMembers->begin();\n list::iterator end = packetMembers->end();\n for (; i != end; ++i)\n {\n combineHashCode(packetHash, (*i)->getHash(referencingStack));\n }\n\n referencingStack->pop_back();\n\n return packetHash;\n }\n\n string* Krystal::NodePacket::getParsed(int as)\n {\n stringstream parsed;\n\n switch (as)\n {\n case CsParseAs::Default:\n {\n parsed << boost::format(TCS_PACKET_BEGIN) % *packetName;\n\n {\n stringstream body;\n\n body << boost::format(TCS_PACKET_ID_FIELD) % ((TCS_PACKET_ID_TYPE)getHash(NULL));\n\n list::iterator i = packetMembers->begin();\n list::iterator end = packetMembers->end();\n for (; i != end; ++i)\n {\n body << *((*i)->getParsed(CsParseAs::Default));\n }\n\n parsed << *(indent(new string(body.str())));\n }\n\n parsed << TCS_PACKET_END;\n }\n break;\n }\n\n return new string(parsed.str());\n }\n\/\/ };\n\n\/\/ class NodePacketMember : public Node\n\/\/ {\n\/\/ Node* memberType;\n\/\/ Node* memberName;\n\/\/ public:\n Krystal::NodePacketMember::NodePacketMember(Context* _context, Node* _memberType, Node* _memberName) : Node(_context)\n {\n memberType = _memberType;\n memberName = _memberName;\n }\n\n int Krystal::NodePacketMember::getType()\n {\n return CsNodeType::packetMember;\n }\n\n size_t Krystal::NodePacketMember::getHash(vector* referencingStack)\n {\n assert(referencingStack != NULL);\n\n size_t packetMemberHash = memberType->getHash(referencingStack);\n combineHashCode(packetMemberHash, memberName->getHash(referencingStack));\n\n return packetMemberHash;\n }\n\n string* Krystal::NodePacketMember::getParsed(int as)\n {\n stringstream parsed;\n\n switch (as)\n {\n case CsParseAs::Default:\n {\n parsed << boost::format(TCS_PACKET_MEMBER_AS_DEFAULT)\n % *(memberType->getParsed(CsParseAs::Default))\n % *(memberName->getParsed(CsParseAs::Default))\n % *(memberType->getParsed(CsParseAs::Initialization));\n }\n break;\n }\n\n return new string(parsed.str());\n }\n\/\/ };\n\n\/\/ class NodePacketMemberType : public Node\n\/\/ {\n\/\/ int typeType; \/\/ one of PRIMITIVE_DATA_TYPE, REFERENCE_DATA_TYPE, MAP, LIST\n\/\/ string* value; \/\/ \"int\", \"bool\", ..., \"MyPacket\", \"Skill\" or NULL when type is MAP or LIST\n\/\/ Node* generic1; \/\/ LIST\n\/\/ Node* generic2; \/\/ MAP \n\/\/ Node* generic3; \/\/ reserved\n\/\/ public:\n Krystal::NodePacketMemberType::NodePacketMemberType(Context* _context, int _type, string* _value) : Node(_context)\n {\n typeType = _type;\n value = _value;\n generic1 = NULL;\n generic2 = NULL;\n generic3 = NULL;\n }\n\n Krystal::NodePacketMemberType::NodePacketMemberType(Context* _context, int _type, Node* _generic1) : Node(_context)\n {\n typeType = _type;\n value = NULL;\n generic1 = _generic1;\n generic2 = NULL;\n generic3 = NULL;\n }\n\n Krystal::NodePacketMemberType::NodePacketMemberType(Context* _context, int _type, Node* _generic1, Node* _generic2) : Node(_context)\n {\n typeType = _type;\n value = NULL;\n generic1 = _generic1;\n generic2 = _generic2;\n generic3 = NULL;\n }\n\n Krystal::NodePacketMemberType::NodePacketMemberType(Context* _context, int _type, Node* _generic1, Node* _generic2, Node* _generic3) : Node(_context)\n {\n typeType = _type;\n value = NULL;\n generic1 = _generic1;\n generic2 = _generic2;\n generic3 = _generic3;\n }\n\n int Krystal::NodePacketMemberType::getType()\n {\n return CsNodeType::packetMemberType;\n }\n\n size_t Krystal::NodePacketMemberType::getHash(vector* referencingStack)\n {\n assert(referencingStack != NULL);\n\n size_t packetMemberTypeHash = 0;\n switch(typeType)\n {\n case Parser::token::PRIMITIVE_DATA_TYPE:\n {\n packetMemberTypeHash = getHashCode(value);\n }\n break;\n\n case Parser::token::REFERENCE_DATA_TYPE:\n {\n \/\/ lookup Context::declarations table\n Node* typePacketNode = context->getDeclarationNode(value);\n if (typePacketNode == NULL)\n {\n throw(runtime_error(\"No such packet type.\"));\n }\n packetMemberTypeHash = typePacketNode->getHash(referencingStack);\n }\n break;\n\n case Parser::token::MAP:\n {\n \/\/ must be specified this is map type\n \/\/ in case of other generic added.\n packetMemberTypeHash = getHashCode((int)Parser::token::MAP);\n combineHashCode(packetMemberTypeHash, generic1->getHash(referencingStack));\n combineHashCode(packetMemberTypeHash, generic2->getHash(referencingStack));\n }\n break;\n\n case Parser::token::LIST:\n {\n \/\/ must be specified this is list type\n \/\/ in case of other generic added.\n packetMemberTypeHash = getHashCode((int)Parser::token::LIST);\n combineHashCode(packetMemberTypeHash, generic1->getHash(referencingStack));\n }\n break;\n }\n\n return packetMemberTypeHash;\n }\n\n string* Krystal::NodePacketMemberType::getParsed(int as)\n {\n stringstream parsed;\n\n switch (as)\n {\n case CsParseAs::Default:\n {\n switch (typeType) {\n case Parser::token::PRIMITIVE_DATA_TYPE:\n case Parser::token::REFERENCE_DATA_TYPE:\n {\n parsed << *value;\n }\n break;\n\n case Parser::token::MAP:\n {\n parsed << \"Dictionary\";\n parsed << \"<\" << *(generic1->getParsed(CsParseAs::Default)) << \", \" << *(generic2->getParsed(CsParseAs::Default)) << \">\";\n }\n break;\n\n case Parser::token::LIST:\n {\n parsed << \"List\";\n parsed << \"<\" << *(generic1->getParsed(CsParseAs::Default)) << \">\";\n }\n break;\n\n default:\n {\n throw(runtime_error(\"Unknown NodePacketMemberType type.\"));\n }\n break;\n }\n }\n break;\n\n case CsParseAs::Initialization:\n {\n switch (typeType) {\n case Parser::token::PRIMITIVE_DATA_TYPE:\n {\n parsed << \"\";\n }\n break;\n\n case Parser::token::REFERENCE_DATA_TYPE:\n case Parser::token::MAP:\n case Parser::token::LIST:\n {\n parsed << boost::format(TCS_PACKET_MEMBER_TYPE_NEW_AS_INITIALIZATION)\n % *(getParsed(CsParseAs::Default));\n }\n break;\n\n default:\n {\n throw(runtime_error(\"Unknown NodePacketMemberType type.\"));\n }\n break;\n }\n }\n break;\n }\n\n return new string(parsed.str());\n }\n\/\/ };\n\n\/\/ class NodePacketMemberName : public Node\n\/\/ {\n\/\/ string* value;\n\/\/ public:\n Krystal::NodePacketMemberName::NodePacketMemberName(Context* _context, string* _value) : Node(_context)\n {\n value = _value;\n }\n\n int Krystal::NodePacketMemberName::getType()\n {\n return CsNodeType::packetMemberName;\n }\n\n size_t Krystal::NodePacketMemberName::getHash(vector* referencingStack)\n {\n size_t packetMemberNameHash = getHashCode(value);\n return packetMemberNameHash;\n }\n\n string* Krystal::NodePacketMemberName::getParsed(int as)\n {\n return value;\n }\n\/\/ };\n\n(trivial) using namespace boost;#include \"SyntaxTree.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\n#include \"parser.tab.hh\"\n\n#include \"template.common.h\"\n#include \"template.cs.h\"\n\nusing namespace std;\nusing namespace boost;\nusing namespace Krystal;\n\n\/\/ class Node\n\/\/ {\n\/\/ public:\n Krystal::Node::Node(Context* _context)\n {\n context = _context;\n }\n\n Krystal::Node::~Node()\n {\n }\n\n int Krystal::Node::getType() { return 0; } \/\/TODO: remove getType() if unnecessary\n size_t Krystal::Node::getHash(vector* referencingStack) { return 0; }\n string* Krystal::Node::getParsed(int as) { return 0; }\n\n\/\/ };\n\n\/\/ class NodeKst : public Node\n\/\/ {\n \/\/ list* commands;\n \/\/ string* fileName;\n \/\/ public:\n Krystal::NodeKst::NodeKst(Context* _context, list* _commands, string* _fileName) : Node(_context)\n {\n commands = _commands;\n fileName = _fileName;\n }\n\n int Krystal::NodeKst::getType()\n {\n return CsNodeType::kst;\n }\n\n size_t Krystal::NodeKst::getHash(vector* referencingStack)\n {\n return 0;\n }\n\n string* Krystal::NodeKst::getParsed(int as)\n {\n stringstream parsed;\n\n parsed << format(TCS_HEADER) % *fileName;\n parsed << TCS_USINGS;\n\n string namespaceByFileName = fileName->substr(0, fileName->find(\".\"));\n\n parsed << format(TCS_NAMESPACE_BEGIN) % namespaceByFileName;\n\n list::iterator i = commands->begin();\n list::iterator end = commands->end();\n\n string* temp;\n\n for (; i != end; ++i)\n {\n temp = (*i)->getParsed(CsParseAs::Default);\n temp = indent(temp);\n parsed << *temp;\n parsed << \"\\n\";\n }\n\n parsed << TCS_NAMESPACE_END;\n\n parsed << \"\\n\\n\";\n\n return new string(parsed.str());\n }\n\/\/ };\n\n\/\/ class NodeInclude : public Node\n\/\/ {\n\/\/ string* value;\n\/\/ public:\n Krystal::NodeInclude::NodeInclude(Context* _context, string* _value) : Node(_context)\n {\n value = _value;\n }\n\n int Krystal::NodeInclude::getType()\n {\n return CsNodeType::include;\n }\n\n size_t Krystal::NodeInclude::getHash(vector* referencingStack)\n {\n return 0;\n }\n\n string* Krystal::NodeInclude::getParsed(int as)\n {\n stringstream parsed;\n\n parsed << \"#include \\\"\";\n parsed << *(value);\n parsed << \"\\\"\";\n\n return new string(parsed.str());\n }\n\/\/ };\n\n\/\/ class NodePacket : public Node\n\/\/ {\n\/\/ string* packetName;\n\/\/ list* packetMembers;\n\/\/ public:\n Krystal::NodePacket::NodePacket(Context* _context, string* _packetName, list* _packetMembers) : Node(_context)\n {\n packetName = _packetName;\n packetMembers = _packetMembers;\n }\n\n int Krystal::NodePacket::getType()\n {\n return CsNodeType::packet;\n }\n\n size_t Krystal::NodePacket::getHash(vector* referencingStack)\n {\n if (referencingStack == NULL)\n {\n referencingStack = new vector();\n }\n else \/\/ check circular reference\n {\n vector::iterator end = referencingStack->end();\n for (vector::iterator i = referencingStack->begin(); i != end; i++)\n {\n if (*i == this)\n {\n throw(runtime_error(\"Circular reference between packets\"));\n }\n }\n }\n\n referencingStack->push_back(this);\n\n size_t packetHash = getHashCode(packetName);\n\n list::iterator i = packetMembers->begin();\n list::iterator end = packetMembers->end();\n for (; i != end; ++i)\n {\n combineHashCode(packetHash, (*i)->getHash(referencingStack));\n }\n\n referencingStack->pop_back();\n\n return packetHash;\n }\n\n string* Krystal::NodePacket::getParsed(int as)\n {\n stringstream parsed;\n\n switch (as)\n {\n case CsParseAs::Default:\n {\n parsed << format(TCS_PACKET_BEGIN) % *packetName;\n\n {\n stringstream body;\n\n body << format(TCS_PACKET_ID_FIELD) % ((TCS_PACKET_ID_TYPE)getHash(NULL));\n\n list::iterator i = packetMembers->begin();\n list::iterator end = packetMembers->end();\n for (; i != end; ++i)\n {\n body << *((*i)->getParsed(CsParseAs::Default));\n }\n\n parsed << *(indent(new string(body.str())));\n }\n\n parsed << TCS_PACKET_END;\n }\n break;\n }\n\n return new string(parsed.str());\n }\n\/\/ };\n\n\/\/ class NodePacketMember : public Node\n\/\/ {\n\/\/ Node* memberType;\n\/\/ Node* memberName;\n\/\/ public:\n Krystal::NodePacketMember::NodePacketMember(Context* _context, Node* _memberType, Node* _memberName) : Node(_context)\n {\n memberType = _memberType;\n memberName = _memberName;\n }\n\n int Krystal::NodePacketMember::getType()\n {\n return CsNodeType::packetMember;\n }\n\n size_t Krystal::NodePacketMember::getHash(vector* referencingStack)\n {\n assert(referencingStack != NULL);\n\n size_t packetMemberHash = memberType->getHash(referencingStack);\n combineHashCode(packetMemberHash, memberName->getHash(referencingStack));\n\n return packetMemberHash;\n }\n\n string* Krystal::NodePacketMember::getParsed(int as)\n {\n stringstream parsed;\n\n switch (as)\n {\n case CsParseAs::Default:\n {\n parsed << format(TCS_PACKET_MEMBER_AS_DEFAULT)\n % *(memberType->getParsed(CsParseAs::Default))\n % *(memberName->getParsed(CsParseAs::Default))\n % *(memberType->getParsed(CsParseAs::Initialization));\n }\n break;\n }\n\n return new string(parsed.str());\n }\n\/\/ };\n\n\/\/ class NodePacketMemberType : public Node\n\/\/ {\n\/\/ int typeType; \/\/ one of PRIMITIVE_DATA_TYPE, REFERENCE_DATA_TYPE, MAP, LIST\n\/\/ string* value; \/\/ \"int\", \"bool\", ..., \"MyPacket\", \"Skill\" or NULL when type is MAP or LIST\n\/\/ Node* generic1; \/\/ LIST\n\/\/ Node* generic2; \/\/ MAP \n\/\/ Node* generic3; \/\/ reserved\n\/\/ public:\n Krystal::NodePacketMemberType::NodePacketMemberType(Context* _context, int _type, string* _value) : Node(_context)\n {\n typeType = _type;\n value = _value;\n generic1 = NULL;\n generic2 = NULL;\n generic3 = NULL;\n }\n\n Krystal::NodePacketMemberType::NodePacketMemberType(Context* _context, int _type, Node* _generic1) : Node(_context)\n {\n typeType = _type;\n value = NULL;\n generic1 = _generic1;\n generic2 = NULL;\n generic3 = NULL;\n }\n\n Krystal::NodePacketMemberType::NodePacketMemberType(Context* _context, int _type, Node* _generic1, Node* _generic2) : Node(_context)\n {\n typeType = _type;\n value = NULL;\n generic1 = _generic1;\n generic2 = _generic2;\n generic3 = NULL;\n }\n\n Krystal::NodePacketMemberType::NodePacketMemberType(Context* _context, int _type, Node* _generic1, Node* _generic2, Node* _generic3) : Node(_context)\n {\n typeType = _type;\n value = NULL;\n generic1 = _generic1;\n generic2 = _generic2;\n generic3 = _generic3;\n }\n\n int Krystal::NodePacketMemberType::getType()\n {\n return CsNodeType::packetMemberType;\n }\n\n size_t Krystal::NodePacketMemberType::getHash(vector* referencingStack)\n {\n assert(referencingStack != NULL);\n\n size_t packetMemberTypeHash = 0;\n switch(typeType)\n {\n case Parser::token::PRIMITIVE_DATA_TYPE:\n {\n packetMemberTypeHash = getHashCode(value);\n }\n break;\n\n case Parser::token::REFERENCE_DATA_TYPE:\n {\n \/\/ lookup Context::declarations table\n Node* typePacketNode = context->getDeclarationNode(value);\n if (typePacketNode == NULL)\n {\n throw(runtime_error(\"No such packet type.\"));\n }\n packetMemberTypeHash = typePacketNode->getHash(referencingStack);\n }\n break;\n\n case Parser::token::MAP:\n {\n \/\/ must be specified this is map type\n \/\/ in case of other generic added.\n packetMemberTypeHash = getHashCode((int)Parser::token::MAP);\n combineHashCode(packetMemberTypeHash, generic1->getHash(referencingStack));\n combineHashCode(packetMemberTypeHash, generic2->getHash(referencingStack));\n }\n break;\n\n case Parser::token::LIST:\n {\n \/\/ must be specified this is list type\n \/\/ in case of other generic added.\n packetMemberTypeHash = getHashCode((int)Parser::token::LIST);\n combineHashCode(packetMemberTypeHash, generic1->getHash(referencingStack));\n }\n break;\n }\n\n return packetMemberTypeHash;\n }\n\n string* Krystal::NodePacketMemberType::getParsed(int as)\n {\n stringstream parsed;\n\n switch (as)\n {\n case CsParseAs::Default:\n {\n switch (typeType) {\n case Parser::token::PRIMITIVE_DATA_TYPE:\n case Parser::token::REFERENCE_DATA_TYPE:\n {\n parsed << *value;\n }\n break;\n\n case Parser::token::MAP:\n {\n parsed << \"Dictionary\";\n parsed << \"<\" << *(generic1->getParsed(CsParseAs::Default)) << \", \" << *(generic2->getParsed(CsParseAs::Default)) << \">\";\n }\n break;\n\n case Parser::token::LIST:\n {\n parsed << \"List\";\n parsed << \"<\" << *(generic1->getParsed(CsParseAs::Default)) << \">\";\n }\n break;\n\n default:\n {\n throw(runtime_error(\"Unknown NodePacketMemberType type.\"));\n }\n break;\n }\n }\n break;\n\n case CsParseAs::Initialization:\n {\n switch (typeType) {\n case Parser::token::PRIMITIVE_DATA_TYPE:\n {\n parsed << \"\";\n }\n break;\n\n case Parser::token::REFERENCE_DATA_TYPE:\n case Parser::token::MAP:\n case Parser::token::LIST:\n {\n parsed << format(TCS_PACKET_MEMBER_TYPE_NEW_AS_INITIALIZATION)\n % *(getParsed(CsParseAs::Default));\n }\n break;\n\n default:\n {\n throw(runtime_error(\"Unknown NodePacketMemberType type.\"));\n }\n break;\n }\n }\n break;\n }\n\n return new string(parsed.str());\n }\n\/\/ };\n\n\/\/ class NodePacketMemberName : public Node\n\/\/ {\n\/\/ string* value;\n\/\/ public:\n Krystal::NodePacketMemberName::NodePacketMemberName(Context* _context, string* _value) : Node(_context)\n {\n value = _value;\n }\n\n int Krystal::NodePacketMemberName::getType()\n {\n return CsNodeType::packetMemberName;\n }\n\n size_t Krystal::NodePacketMemberName::getHash(vector* referencingStack)\n {\n size_t packetMemberNameHash = getHashCode(value);\n return packetMemberNameHash;\n }\n\n string* Krystal::NodePacketMemberName::getParsed(int as)\n {\n return value;\n }\n\/\/ };\n\n<|endoftext|>"} {"text":"\/\/\n\/\/ scalarReplace\n\/\/\n\/\/ This pass implements scalar replacement of aggregates.\n\/\/\n\n#include \"astutil.h\"\n#include \"expr.h\"\n#include \"optimizations.h\"\n#include \"passes.h\"\n#include \"runtime.h\"\n#include \"stmt.h\"\n#include \"stringutil.h\"\n#include \"symbol.h\"\n#include \"symscope.h\"\n#include \"view.h\"\n\nstatic const bool debugScalarReplacement = false;\n\n\/\/\n\/\/ typeVec - a vector of candidate types for scalar replacement\n\/\/ varSet - a set of candidate variables for scalar replacement\n\/\/ typeOrder - topological ordering of candidate types\n\/\/ e.g. (int, (int, int)) before (int, int)\n\/\/ typeVarMap - map from types to vectors of variables\n\/\/ defMap - defMap for varSet\n\/\/ useMap - useMap for varSet\n\/\/\nstatic Vec typeVec;\nstatic Vec varSet;\nstatic Map typeOrder;\nstatic Map*> typeVarMap;\nstatic Map*> defMap;\nstatic Map*> useMap;\n\ntypedef Map*> ClassTypeToVecSymbolMap;\ntypedef MapElem*> ClassTypeToVecSymbolMapElem;\n\n\/\/\n\/\/ compute topological order for types; this functions assumes that\n\/\/ there are no cycles and that the typeOrder map is initialized to -1\n\/\/ for all class types\n\/\/\nstatic int\ncomputeOrder(ClassType* ct) {\n if (typeOrder.get(ct) != -1)\n return typeOrder.get(ct);\n\n typeOrder.put(ct, -2);\n int order = 0;\n for_fields(field, ct) {\n if (ClassType* fct = toClassType(field->type)) {\n int fieldOrder = computeOrder(fct);\n if (fieldOrder >= order)\n order = fieldOrder+1;\n }\n }\n typeOrder.put(ct, order);\n return order;\n}\n\n\/\/\n\/\/ comparison function for quick sort of types based on typeOrder map\n\/\/\nstatic int\ncompareTypesByOrder(const void* v1, const void* v2) {\n ClassType* ct1 = *(ClassType**)v1;\n ClassType* ct2 = *(ClassType**)v2;\n int order1 = typeOrder.get(ct1);\n int order2 = typeOrder.get(ct2);\n if (order1 < order2)\n return 1;\n else if (order1 > order2)\n return -1;\n else\n return 0;\n}\n\nstatic bool\nremoveUnusedClassInstance(Symbol* sym) {\n bool change = false;\n bool unused = !useMap.get(sym) || useMap.get(sym)->n == 0;\n\n if (!unused) {\n unused = true;\n for_uses(use, useMap, sym) {\n if (use->parentSymbol)\n unused = false;\n }\n }\n\n if (unused) {\n for_defs(def, defMap, sym) {\n if (def->parentSymbol) {\n CallExpr* move = toCallExpr(def->parentExpr);\n if (move && move->isPrimitive(PRIMITIVE_MOVE)) {\n move->remove();\n change = true;\n }\n }\n }\n }\n return change;\n}\n\nstatic bool\nunifyClassInstances(Symbol* sym) {\n if (!defMap.get(sym))\n return false;\n\n SymExpr* rhs = NULL;\n\n for_defs(def, defMap, sym) {\n if (def->parentSymbol) {\n CallExpr* move = toCallExpr(def->parentExpr);\n if (!move || !move->isPrimitive(PRIMITIVE_MOVE))\n return false;\n SymExpr* se = toSymExpr(move->get(2));\n if (!se)\n return false;\n if (rhs && rhs->var != gNil && se->var != gNil)\n return false;\n if (!rhs || se->var != gNil)\n rhs = se;\n }\n }\n\n if (!rhs)\n return false;\n\n for_uses(se, useMap, sym) {\n se->var = rhs->var;\n addUse(useMap, se);\n }\n\n for_defs(def, defMap, sym) {\n def->parentExpr->remove();\n }\n\n sym->defPoint->remove();\n return true;\n}\n\nstatic bool\nscalarReplaceClass(ClassType* ct, Symbol* sym) {\n\n \/\/\n \/\/ only scalar replace sym if it has exactly one def and that def is\n \/\/ an allocation primitive\n \/\/\n Vec* defs = defMap.get(sym);\n if (!defs || defs->n != 1)\n return false;\n CallExpr* move = toCallExpr(defs->v[0]->parentExpr);\n if (!move || !move->isPrimitive(PRIMITIVE_MOVE))\n return false;\n CallExpr* alloc = toCallExpr(move->get(2));\n if (!alloc || !alloc->isPrimitive(PRIMITIVE_CHPL_ALLOC))\n return false;\n\n \/\/\n \/\/ only scalar replace sym if all of the uses are handled primitives\n \/\/\n for_uses(se, useMap, sym) {\n if (se->parentSymbol) {\n CallExpr* call = toCallExpr(se->parentExpr);\n if (!call || !(call->isPrimitive(PRIMITIVE_SET_MEMBER) ||\n call->isPrimitive(PRIMITIVE_GET_MEMBER) ||\n call->isPrimitive(PRIMITIVE_GET_MEMBER_VALUE)) ||\n !(call->get(1) == se))\n return false;\n }\n }\n\n \/\/\n \/\/ okay, let's scalar replace sym; first, create vars for every\n \/\/ field in sym and compute fieldMap to map the fields to these new\n \/\/ vars\n \/\/\n Map fieldMap;\n for_fields(field, ct) {\n Symbol* var = new VarSymbol(astr(sym->name, \"_\", field->name), field->type);\n fieldMap.put(field, var);\n sym->defPoint->insertBefore(new DefExpr(var));\n var->isCompilerTemp = sym->isCompilerTemp;\n if (ClassType* fct = toClassType(field->type))\n if (Vec* varVec = typeVarMap.get(fct))\n varVec->add(var);\n }\n sym->defPoint->remove();\n\n \/\/\n \/\/ remove the only def\n \/\/\n move->remove();\n\n \/\/\n \/\/ replace uses of sym with new vars\n \/\/\n for_uses(se, useMap, sym) {\n if (CallExpr* call = toCallExpr(se->parentExpr)) {\n if (call && call->isPrimitive(PRIMITIVE_GET_MEMBER)) {\n SymExpr* member = toSymExpr(call->get(2));\n SymExpr* use = new SymExpr(fieldMap.get(member->var));\n call->replace(new CallExpr(PRIMITIVE_SET_REF, use));\n addUse(useMap, use);\n } else if (call && call->isPrimitive(PRIMITIVE_GET_MEMBER_VALUE)) {\n SymExpr* member = toSymExpr(call->get(2));\n SymExpr* use = new SymExpr(fieldMap.get(member->var));\n call->replace(use);\n addUse(useMap, use);\n } else if (call && call->isPrimitive(PRIMITIVE_SET_MEMBER)) {\n SymExpr* member = toSymExpr(call->get(2));\n call->primitive = primitives[PRIMITIVE_MOVE];\n call->get(2)->remove();\n call->get(1)->remove();\n SymExpr* def = new SymExpr(fieldMap.get(member->var));\n call->insertAtHead(def);\n addDef(defMap, def);\n if (call->get(1)->typeInfo() == call->get(2)->typeInfo()->refType)\n call->insertAtTail(new CallExpr(PRIMITIVE_SET_REF, call->get(2)->remove()));\n }\n }\n }\n\n return true;\n}\n\nstatic bool\nscalarReplaceRecord(ClassType* ct, Symbol* sym) {\n\n \/\/\n \/\/ only scalar replace sym if all of the defs are handled primitives\n \/\/\n for_defs(se, defMap, sym) {\n if (se->parentSymbol) {\n CallExpr* call = toCallExpr(se->parentExpr);\n if (!call ||\n !call->isPrimitive(PRIMITIVE_MOVE) ||\n !isSymExpr(call->get(2)))\n return false;\n }\n }\n\n \/\/\n \/\/ only scalar replace sym if all of the uses are handled primitives\n \/\/\n for_uses(se, useMap, sym) {\n if (se->parentSymbol) {\n CallExpr* call = toCallExpr(se->parentExpr);\n if (!call ||\n !((call->isPrimitive(PRIMITIVE_SET_MEMBER) && call->get(1) == se) ||\n call->isPrimitive(PRIMITIVE_GET_MEMBER) ||\n call->isPrimitive(PRIMITIVE_GET_MEMBER_VALUE) ||\n call->isPrimitive(PRIMITIVE_MOVE)))\n return false;\n }\n }\n\n \/\/\n \/\/ okay, let's scalar replace sym; first, create vars for every\n \/\/ field in sym and compute fieldMap to map the fields to these new\n \/\/ vars\n \/\/\n Map fieldMap;\n for_fields(field, ct) {\n Symbol* var = new VarSymbol(astr(sym->name, \"_\", field->name), field->type);\n fieldMap.put(field, var);\n sym->defPoint->insertBefore(new DefExpr(var));\n var->isCompilerTemp = sym->isCompilerTemp;\n if (ClassType* fct = toClassType(field->type))\n if (Vec* varVec = typeVarMap.get(fct))\n varVec->add(var);\n }\n sym->defPoint->remove();\n\n \/\/\n \/\/ replace defs of sym with new vars\n \/\/\n for_defs(se, defMap, sym) {\n if (CallExpr* call = toCallExpr(se->parentExpr)) {\n if (call && call->isPrimitive(PRIMITIVE_MOVE)) {\n SymExpr* rhs = toSymExpr(call->get(2));\n for_fields(field, ct) {\n SymExpr* rhsCopy = rhs->copy();\n SymExpr* use = new SymExpr(fieldMap.get(field));\n call->insertBefore(\n new CallExpr(PRIMITIVE_MOVE, use,\n new CallExpr(PRIMITIVE_GET_MEMBER_VALUE, rhsCopy, field)));\n addDef(defMap, use);\n addUse(useMap, rhsCopy);\n }\n call->remove();\n }\n }\n }\n\n \/\/\n \/\/ replace uses of sym with new vars\n \/\/\n for_uses(se, useMap, sym) {\n if (CallExpr* call = toCallExpr(se->parentExpr)) {\n if (call && call->isPrimitive(PRIMITIVE_MOVE)) {\n SymExpr* lhs = toSymExpr(call->get(1));\n for_fields(field, ct) {\n SymExpr* lhsCopy = lhs->copy();\n SymExpr* use = new SymExpr(fieldMap.get(field));\n call->insertBefore(\n new CallExpr(PRIMITIVE_SET_MEMBER, lhsCopy, field, use));\n addUse(useMap, use);\n addUse(useMap, lhsCopy);\n }\n call->remove();\n } else if (call && call->isPrimitive(PRIMITIVE_GET_MEMBER)) {\n SymExpr* member = toSymExpr(call->get(2));\n SymExpr* use = new SymExpr(fieldMap.get(member->var));\n call->replace(new CallExpr(PRIMITIVE_SET_REF, use));\n addUse(useMap, use);\n } else if (call && call->isPrimitive(PRIMITIVE_GET_MEMBER_VALUE)) {\n SymExpr* member = toSymExpr(call->get(2));\n SymExpr* use = new SymExpr(fieldMap.get(member->var));\n call->replace(use);\n addUse(useMap, use);\n } else if (call && call->isPrimitive(PRIMITIVE_SET_MEMBER)) {\n SymExpr* member = toSymExpr(call->get(2));\n call->primitive = primitives[PRIMITIVE_MOVE];\n call->get(2)->remove();\n call->get(1)->remove();\n SymExpr* def = new SymExpr(fieldMap.get(member->var));\n call->insertAtHead(def);\n addDef(defMap, def);\n if (call->get(1)->typeInfo() == call->get(2)->typeInfo()->refType)\n call->insertAtTail(new CallExpr(PRIMITIVE_SET_REF, call->get(2)->remove()));\n }\n }\n }\n\n return true;\n}\n\n\nstatic void\ndebugScalarReplacementFailure(Symbol* var) {\n printf(\"failed to scalar replace %s\\n\", var->cname);\n printf(\"defs:\\n\");\n for_defs(def, defMap, var) {\n if (def->parentSymbol)\n nprint_view(def->getStmtExpr());\n }\n printf(\"uses:\\n\");\n for_uses(use, useMap, var) {\n if (use->parentSymbol)\n nprint_view(use->getStmtExpr());\n }\n}\n\n\nvoid\nscalarReplace() {\n if (!fNoScalarReplacement) {\n\n \/\/\n \/\/ initialize typeOrder map and identify types that are candidates\n \/\/ for scalar replacement\n \/\/\n forv_Vec(TypeSymbol, ts, gTypes) {\n ClassType* ct = toClassType(ts->type);\n if (ct) {\n typeOrder.put(ct, -1);\n if (ts->hasPragma(\"iterator class\") || ts->hasPragma(\"tuple\")) {\n typeVec.add(ct);\n typeVarMap.put(ct, new Vec());\n if (ClassType* rct = toClassType(ct->refType))\n typeVarMap.put(rct, new Vec());\n }\n }\n }\n\n \/\/\n \/\/ compute topological order of types\n \/\/\n forv_Vec(ClassType, ct, typeVec) {\n computeOrder(ct);\n }\n\n \/\/\n \/\/ sort types based on topological order\n \/\/\n qsort(typeVec.v, typeVec.n, sizeof(typeVec.v[0]), compareTypesByOrder);\n\n \/\/\n \/\/ compute typeVarMap and varSet\n \/\/\n forv_Vec(BaseAST, ast, gAsts) {\n if (VarSymbol* var = toVarSymbol(ast)) {\n if (ClassType* ct = toClassType(var->type)) {\n if (Vec* varVec = typeVarMap.get(ct)) {\n if (isFnSymbol(var->defPoint->parentSymbol)) {\n varSet.set_add(var);\n varVec->add(var);\n }\n }\n }\n }\n }\n\n \/\/\n \/\/ build def\/use maps for candidate variables\n \/\/\n buildDefUseMaps(varSet, defMap, useMap);\n\n \/\/\n \/\/ scalar replace vars as possible and in topological order\n \/\/\n if (debugScalarReplacement)\n printf(\"\\n\");\n forv_Vec(ClassType, ct, typeVec) {\n if (debugScalarReplacement)\n printf(\"%d: %s:\\n\", typeOrder.get(ct), ct->symbol->cname);\n if (ClassType* rct = toClassType(ct->refType)) {\n Vec* refVec = typeVarMap.get(rct);\n forv_Vec(Symbol, var, *refVec) {\n eliminateSingleAssignmentReference(defMap, useMap, var);\n }\n }\n Vec* varVec = typeVarMap.get(ct);\n if (isRecordType(ct)) {\n forv_Vec(Symbol, var, *varVec) {\n if (var->defPoint->parentSymbol) {\n bool result = scalarReplaceRecord(ct, var);\n if (debugScalarReplacement && !result)\n debugScalarReplacementFailure(var);\n }\n }\n } else {\n bool change;\n do {\n change = false;\n forv_Vec(Symbol, var, *varVec) {\n change |= removeUnusedClassInstance(var);\n change |= unifyClassInstances(var);\n }\n } while (change);\n forv_Vec(Symbol, var, *varVec) {\n if (var->defPoint->parentSymbol) {\n bool result = scalarReplaceClass(ct, var);\n if (debugScalarReplacement && !result)\n debugScalarReplacementFailure(var);\n }\n }\n }\n }\n\n \/\/\n \/\/ cleanup\n \/\/\n typeVec.clear();\n varSet.clear();\n typeOrder.clear();\n form_Map(ClassTypeToVecSymbolMapElem, e, typeVarMap) {\n delete e->value;\n }\n typeVarMap.clear();\n freeDefUseMaps(defMap, useMap);\n }\n}\nadded code to remove 'identity defs' to scalar replacement\/\/\n\/\/ scalarReplace\n\/\/\n\/\/ This pass implements scalar replacement of aggregates.\n\/\/\n\n#include \"astutil.h\"\n#include \"expr.h\"\n#include \"optimizations.h\"\n#include \"passes.h\"\n#include \"runtime.h\"\n#include \"stmt.h\"\n#include \"stringutil.h\"\n#include \"symbol.h\"\n#include \"symscope.h\"\n#include \"view.h\"\n\nstatic const bool debugScalarReplacement = false;\n\n\/\/\n\/\/ typeVec - a vector of candidate types for scalar replacement\n\/\/ varSet - a set of candidate variables for scalar replacement\n\/\/ typeOrder - topological ordering of candidate types\n\/\/ e.g. (int, (int, int)) before (int, int)\n\/\/ typeVarMap - map from types to vectors of variables\n\/\/ defMap - defMap for varSet\n\/\/ useMap - useMap for varSet\n\/\/\nstatic Vec typeVec;\nstatic Vec varSet;\nstatic Map typeOrder;\nstatic Map*> typeVarMap;\nstatic Map*> defMap;\nstatic Map*> useMap;\n\ntypedef Map*> ClassTypeToVecSymbolMap;\ntypedef MapElem*> ClassTypeToVecSymbolMapElem;\n\n\/\/\n\/\/ compute topological order for types; this functions assumes that\n\/\/ there are no cycles and that the typeOrder map is initialized to -1\n\/\/ for all class types\n\/\/\nstatic int\ncomputeOrder(ClassType* ct) {\n if (typeOrder.get(ct) != -1)\n return typeOrder.get(ct);\n\n typeOrder.put(ct, -2);\n int order = 0;\n for_fields(field, ct) {\n if (ClassType* fct = toClassType(field->type)) {\n int fieldOrder = computeOrder(fct);\n if (fieldOrder >= order)\n order = fieldOrder+1;\n }\n }\n typeOrder.put(ct, order);\n return order;\n}\n\n\/\/\n\/\/ comparison function for quick sort of types based on typeOrder map\n\/\/\nstatic int\ncompareTypesByOrder(const void* v1, const void* v2) {\n ClassType* ct1 = *(ClassType**)v1;\n ClassType* ct2 = *(ClassType**)v2;\n int order1 = typeOrder.get(ct1);\n int order2 = typeOrder.get(ct2);\n if (order1 < order2)\n return 1;\n else if (order1 > order2)\n return -1;\n else\n return 0;\n}\n\nstatic bool\nremoveIdentityDefs(Symbol* sym) {\n bool change = false;\n\n for_defs(def, defMap, sym) {\n CallExpr* move = toCallExpr(def->parentExpr);\n if (move && move->isPrimitive(PRIMITIVE_MOVE)) {\n SymExpr* rhs = toSymExpr(move->get(2));\n if (rhs && def->var == rhs->var) {\n move->remove();\n change = true;\n }\n }\n }\n return change;\n}\n\nstatic bool\nremoveUnusedClassInstance(Symbol* sym) {\n bool change = false;\n bool unused = !useMap.get(sym) || useMap.get(sym)->n == 0;\n\n if (!unused) {\n unused = true;\n for_uses(use, useMap, sym) {\n if (use->parentSymbol)\n unused = false;\n }\n }\n\n if (unused) {\n for_defs(def, defMap, sym) {\n if (def->parentSymbol) {\n CallExpr* move = toCallExpr(def->parentExpr);\n if (move && move->isPrimitive(PRIMITIVE_MOVE)) {\n move->remove();\n change = true;\n }\n }\n }\n }\n return change;\n}\n\nstatic bool\nunifyClassInstances(Symbol* sym) {\n if (!defMap.get(sym))\n return false;\n\n SymExpr* rhs = NULL;\n\n for_defs(def, defMap, sym) {\n if (def->parentSymbol) {\n CallExpr* move = toCallExpr(def->parentExpr);\n if (!move || !move->isPrimitive(PRIMITIVE_MOVE))\n return false;\n SymExpr* se = toSymExpr(move->get(2));\n if (!se)\n return false;\n if (rhs && rhs->var != gNil && se->var != gNil)\n return false;\n if (!rhs || se->var != gNil)\n rhs = se;\n }\n }\n\n if (!rhs)\n return false;\n\n for_uses(se, useMap, sym) {\n se->var = rhs->var;\n addUse(useMap, se);\n }\n\n for_defs(def, defMap, sym) {\n def->parentExpr->remove();\n }\n\n sym->defPoint->remove();\n return true;\n}\n\nstatic bool\nscalarReplaceClass(ClassType* ct, Symbol* sym) {\n\n \/\/\n \/\/ only scalar replace sym if it has exactly one def and that def is\n \/\/ an allocation primitive\n \/\/\n Vec* defs = defMap.get(sym);\n if (!defs || defs->n != 1)\n return false;\n CallExpr* move = toCallExpr(defs->v[0]->parentExpr);\n if (!move || !move->isPrimitive(PRIMITIVE_MOVE))\n return false;\n CallExpr* alloc = toCallExpr(move->get(2));\n if (!alloc || !alloc->isPrimitive(PRIMITIVE_CHPL_ALLOC))\n return false;\n\n \/\/\n \/\/ only scalar replace sym if all of the uses are handled primitives\n \/\/\n for_uses(se, useMap, sym) {\n if (se->parentSymbol) {\n CallExpr* call = toCallExpr(se->parentExpr);\n if (!call || !(call->isPrimitive(PRIMITIVE_SET_MEMBER) ||\n call->isPrimitive(PRIMITIVE_GET_MEMBER) ||\n call->isPrimitive(PRIMITIVE_GET_MEMBER_VALUE)) ||\n !(call->get(1) == se))\n return false;\n }\n }\n\n \/\/\n \/\/ okay, let's scalar replace sym; first, create vars for every\n \/\/ field in sym and compute fieldMap to map the fields to these new\n \/\/ vars\n \/\/\n Map fieldMap;\n for_fields(field, ct) {\n Symbol* var = new VarSymbol(astr(sym->name, \"_\", field->name), field->type);\n fieldMap.put(field, var);\n sym->defPoint->insertBefore(new DefExpr(var));\n var->isCompilerTemp = sym->isCompilerTemp;\n if (ClassType* fct = toClassType(field->type))\n if (Vec* varVec = typeVarMap.get(fct))\n varVec->add(var);\n }\n sym->defPoint->remove();\n\n \/\/\n \/\/ remove the only def\n \/\/\n move->remove();\n\n \/\/\n \/\/ replace uses of sym with new vars\n \/\/\n for_uses(se, useMap, sym) {\n if (CallExpr* call = toCallExpr(se->parentExpr)) {\n if (call && call->isPrimitive(PRIMITIVE_GET_MEMBER)) {\n SymExpr* member = toSymExpr(call->get(2));\n SymExpr* use = new SymExpr(fieldMap.get(member->var));\n call->replace(new CallExpr(PRIMITIVE_SET_REF, use));\n addUse(useMap, use);\n } else if (call && call->isPrimitive(PRIMITIVE_GET_MEMBER_VALUE)) {\n SymExpr* member = toSymExpr(call->get(2));\n SymExpr* use = new SymExpr(fieldMap.get(member->var));\n call->replace(use);\n addUse(useMap, use);\n } else if (call && call->isPrimitive(PRIMITIVE_SET_MEMBER)) {\n SymExpr* member = toSymExpr(call->get(2));\n call->primitive = primitives[PRIMITIVE_MOVE];\n call->get(2)->remove();\n call->get(1)->remove();\n SymExpr* def = new SymExpr(fieldMap.get(member->var));\n call->insertAtHead(def);\n addDef(defMap, def);\n if (call->get(1)->typeInfo() == call->get(2)->typeInfo()->refType)\n call->insertAtTail(new CallExpr(PRIMITIVE_SET_REF, call->get(2)->remove()));\n }\n }\n }\n\n return true;\n}\n\nstatic bool\nscalarReplaceRecord(ClassType* ct, Symbol* sym) {\n\n \/\/\n \/\/ only scalar replace sym if all of the defs are handled primitives\n \/\/\n for_defs(se, defMap, sym) {\n if (se->parentSymbol) {\n CallExpr* call = toCallExpr(se->parentExpr);\n if (!call ||\n !call->isPrimitive(PRIMITIVE_MOVE) ||\n !isSymExpr(call->get(2)))\n return false;\n }\n }\n\n \/\/\n \/\/ only scalar replace sym if all of the uses are handled primitives\n \/\/\n for_uses(se, useMap, sym) {\n if (se->parentSymbol) {\n CallExpr* call = toCallExpr(se->parentExpr);\n if (!call ||\n !((call->isPrimitive(PRIMITIVE_SET_MEMBER) && call->get(1) == se) ||\n call->isPrimitive(PRIMITIVE_GET_MEMBER) ||\n call->isPrimitive(PRIMITIVE_GET_MEMBER_VALUE) ||\n call->isPrimitive(PRIMITIVE_MOVE)))\n return false;\n }\n }\n\n \/\/\n \/\/ okay, let's scalar replace sym; first, create vars for every\n \/\/ field in sym and compute fieldMap to map the fields to these new\n \/\/ vars\n \/\/\n Map fieldMap;\n for_fields(field, ct) {\n Symbol* var = new VarSymbol(astr(sym->name, \"_\", field->name), field->type);\n fieldMap.put(field, var);\n sym->defPoint->insertBefore(new DefExpr(var));\n var->isCompilerTemp = sym->isCompilerTemp;\n if (ClassType* fct = toClassType(field->type))\n if (Vec* varVec = typeVarMap.get(fct))\n varVec->add(var);\n }\n sym->defPoint->remove();\n\n \/\/\n \/\/ replace defs of sym with new vars\n \/\/\n for_defs(se, defMap, sym) {\n if (CallExpr* call = toCallExpr(se->parentExpr)) {\n if (call && call->isPrimitive(PRIMITIVE_MOVE)) {\n SymExpr* rhs = toSymExpr(call->get(2));\n for_fields(field, ct) {\n SymExpr* rhsCopy = rhs->copy();\n SymExpr* use = new SymExpr(fieldMap.get(field));\n call->insertBefore(\n new CallExpr(PRIMITIVE_MOVE, use,\n new CallExpr(PRIMITIVE_GET_MEMBER_VALUE, rhsCopy, field)));\n addDef(defMap, use);\n addUse(useMap, rhsCopy);\n }\n call->remove();\n }\n }\n }\n\n \/\/\n \/\/ replace uses of sym with new vars\n \/\/\n for_uses(se, useMap, sym) {\n if (CallExpr* call = toCallExpr(se->parentExpr)) {\n if (call && call->isPrimitive(PRIMITIVE_MOVE)) {\n SymExpr* lhs = toSymExpr(call->get(1));\n for_fields(field, ct) {\n SymExpr* lhsCopy = lhs->copy();\n SymExpr* use = new SymExpr(fieldMap.get(field));\n call->insertBefore(\n new CallExpr(PRIMITIVE_SET_MEMBER, lhsCopy, field, use));\n addUse(useMap, use);\n addUse(useMap, lhsCopy);\n }\n call->remove();\n } else if (call && call->isPrimitive(PRIMITIVE_GET_MEMBER)) {\n SymExpr* member = toSymExpr(call->get(2));\n SymExpr* use = new SymExpr(fieldMap.get(member->var));\n call->replace(new CallExpr(PRIMITIVE_SET_REF, use));\n addUse(useMap, use);\n } else if (call && call->isPrimitive(PRIMITIVE_GET_MEMBER_VALUE)) {\n SymExpr* member = toSymExpr(call->get(2));\n SymExpr* use = new SymExpr(fieldMap.get(member->var));\n call->replace(use);\n addUse(useMap, use);\n } else if (call && call->isPrimitive(PRIMITIVE_SET_MEMBER)) {\n SymExpr* member = toSymExpr(call->get(2));\n call->primitive = primitives[PRIMITIVE_MOVE];\n call->get(2)->remove();\n call->get(1)->remove();\n SymExpr* def = new SymExpr(fieldMap.get(member->var));\n call->insertAtHead(def);\n addDef(defMap, def);\n if (call->get(1)->typeInfo() == call->get(2)->typeInfo()->refType)\n call->insertAtTail(new CallExpr(PRIMITIVE_SET_REF, call->get(2)->remove()));\n }\n }\n }\n\n return true;\n}\n\n\nstatic void\ndebugScalarReplacementFailure(Symbol* var) {\n printf(\"failed to scalar replace %s[%d]\\n\", var->cname, var->id);\n printf(\"defs:\\n\");\n for_defs(def, defMap, var) {\n if (def->parentSymbol)\n nprint_view(def->getStmtExpr());\n }\n printf(\"uses:\\n\");\n for_uses(use, useMap, var) {\n if (use->parentSymbol)\n nprint_view(use->getStmtExpr());\n }\n}\n\n\nvoid\nscalarReplace() {\n if (!fNoScalarReplacement) {\n\n \/\/\n \/\/ initialize typeOrder map and identify types that are candidates\n \/\/ for scalar replacement\n \/\/\n forv_Vec(TypeSymbol, ts, gTypes) {\n ClassType* ct = toClassType(ts->type);\n if (ct) {\n typeOrder.put(ct, -1);\n if (ts->hasPragma(\"iterator class\") || ts->hasPragma(\"tuple\")) {\n typeVec.add(ct);\n typeVarMap.put(ct, new Vec());\n if (ClassType* rct = toClassType(ct->refType))\n typeVarMap.put(rct, new Vec());\n }\n }\n }\n\n \/\/\n \/\/ compute topological order of types\n \/\/\n forv_Vec(ClassType, ct, typeVec) {\n computeOrder(ct);\n }\n\n \/\/\n \/\/ sort types based on topological order\n \/\/\n qsort(typeVec.v, typeVec.n, sizeof(typeVec.v[0]), compareTypesByOrder);\n\n \/\/\n \/\/ compute typeVarMap and varSet\n \/\/\n forv_Vec(BaseAST, ast, gAsts) {\n if (VarSymbol* var = toVarSymbol(ast)) {\n if (ClassType* ct = toClassType(var->type)) {\n if (Vec* varVec = typeVarMap.get(ct)) {\n if (isFnSymbol(var->defPoint->parentSymbol)) {\n varSet.set_add(var);\n varVec->add(var);\n }\n }\n }\n }\n }\n\n \/\/\n \/\/ build def\/use maps for candidate variables\n \/\/\n buildDefUseMaps(varSet, defMap, useMap);\n\n \/\/\n \/\/ scalar replace vars as possible and in topological order\n \/\/\n if (debugScalarReplacement)\n printf(\"\\n\");\n forv_Vec(ClassType, ct, typeVec) {\n if (debugScalarReplacement)\n printf(\"%d: %s:\\n\", typeOrder.get(ct), ct->symbol->cname);\n if (ClassType* rct = toClassType(ct->refType)) {\n Vec* refVec = typeVarMap.get(rct);\n forv_Vec(Symbol, var, *refVec) {\n eliminateSingleAssignmentReference(defMap, useMap, var);\n }\n }\n Vec* varVec = typeVarMap.get(ct);\n if (isRecordType(ct)) {\n forv_Vec(Symbol, var, *varVec) {\n if (var->defPoint->parentSymbol) {\n bool result = scalarReplaceRecord(ct, var);\n if (debugScalarReplacement && !result)\n debugScalarReplacementFailure(var);\n }\n }\n } else {\n bool change;\n do {\n change = false;\n forv_Vec(Symbol, var, *varVec) {\n change |= removeIdentityDefs(var);\n change |= removeUnusedClassInstance(var);\n change |= unifyClassInstances(var);\n }\n } while (change);\n forv_Vec(Symbol, var, *varVec) {\n if (var->defPoint->parentSymbol) {\n bool result = scalarReplaceClass(ct, var);\n if (debugScalarReplacement && !result)\n debugScalarReplacementFailure(var);\n }\n }\n }\n }\n\n \/\/\n \/\/ cleanup\n \/\/\n typeVec.clear();\n varSet.clear();\n typeOrder.clear();\n form_Map(ClassTypeToVecSymbolMapElem, e, typeVarMap) {\n delete e->value;\n }\n typeVarMap.clear();\n freeDefUseMaps(defMap, useMap);\n }\n}\n<|endoftext|>"} {"text":"\/\/ test_Cryptor.cpp -- Test Sodium::Cryptor\n\/\/\n\/\/ Copyright (C) 2017 Farid Hajji . All rights reserved.\n\n#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MODULE Sodium::Cryptor Test\n#include \n\n#include \n#include \"sodiumcryptor.h\"\n#include \"sodiumkey.h\"\n#include \"sodiumnonce.h\"\n#include \n\nusing data_t = Sodium::data_t;\n\nbool\ntest_of_correctness(std::string &plaintext)\n{\n Sodium::Cryptor sc {};\n Sodium::Key key(Sodium::Key::KEYSIZE_SECRETBOX);\n Sodium::Nonce<> nonce {};\n\n data_t plainblob {plaintext.cbegin(), plaintext.cend()};\n data_t ciphertext = sc.encrypt(plainblob, key, nonce);\n data_t decrypted = sc.decrypt(ciphertext, key, nonce);\n\n key.noaccess();\n\n return plainblob == decrypted;\n}\n\nBOOST_AUTO_TEST_SUITE ( sodium_test_suite );\n\nBOOST_AUTO_TEST_CASE( sodium_cryptor_test_full_plaintext )\n{\n BOOST_REQUIRE(sodium_init() != -1);\n\n std::string plaintext {\"the quick brown fox jumps over the lazy dog\"};\n BOOST_CHECK(test_of_correctness(plaintext));\n}\n\nBOOST_AUTO_TEST_CASE( sodium_cryptor_test_empty_plaintext )\n{\n BOOST_REQUIRE(sodium_init() != -1);\n\n std::string plaintext {};\n BOOST_CHECK(test_of_correctness(plaintext));\n}\n\nBOOST_AUTO_TEST_SUITE_END ();\nAdded test fixture for each individual test case.\/\/ test_Cryptor.cpp -- Test Sodium::Cryptor\n\/\/\n\/\/ Copyright (C) 2017 Farid Hajji . All rights reserved.\n\n#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MODULE Sodium::Cryptor Test\n#include \n\n#include \n#include \"sodiumcryptor.h\"\n#include \"sodiumkey.h\"\n#include \"sodiumnonce.h\"\n#include \n\nusing data_t = Sodium::data_t;\n\nbool\ntest_of_correctness(std::string &plaintext)\n{\n Sodium::Cryptor sc {};\n Sodium::Key key(Sodium::Key::KEYSIZE_SECRETBOX);\n Sodium::Nonce<> nonce {};\n\n data_t plainblob {plaintext.cbegin(), plaintext.cend()};\n data_t ciphertext = sc.encrypt(plainblob, key, nonce);\n data_t decrypted = sc.decrypt(ciphertext, key, nonce);\n\n key.noaccess();\n\n return plainblob == decrypted;\n}\n\nstruct SodiumFixture {\n SodiumFixture() {\n BOOST_REQUIRE(sodium_init() != -1);\n BOOST_TEST_MESSAGE(\"SodiumFixture(): sodium_init() successful.\");\n }\n ~SodiumFixture() {\n BOOST_TEST_MESSAGE(\"~SodiumFixture(): teardown -- no-op.\");\n }\n};\n\n\/**\n * The previous fixture is RAII called _for each_ test case\n * individually; i.e. sodium_init() is initialized multiple times.\n *\n * If you prefer to to this fixture only once for the whole test\n * suite, replace BOOST_FIXTURE_TEST_SUITE (...) by call call to\n * BOOST_AUTO_TEST_SUITE (sodium_test_suite,\n * * boost::unit_test::fixture())\n * i.e. using decorators. \n * \n * To see the output of the messages, invoke with --log_level=message.\n **\/\n\nBOOST_FIXTURE_TEST_SUITE ( sodium_test_suite, SodiumFixture );\n\nBOOST_AUTO_TEST_CASE( sodium_cryptor_test_full_plaintext )\n{\n std::string plaintext {\"the quick brown fox jumps over the lazy dog\"};\n BOOST_CHECK(test_of_correctness(plaintext));\n}\n\nBOOST_AUTO_TEST_CASE( sodium_cryptor_test_empty_plaintext )\n{\n std::string plaintext {};\n BOOST_CHECK(test_of_correctness(plaintext));\n}\n\nBOOST_AUTO_TEST_SUITE_END ();\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: docprev.cxx,v $\n *\n * $Revision: 1.19 $\n *\n * last change: $Author: ihi $ $Date: 2006-11-14 14:25:56 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_sd.hxx\"\n\n#ifndef _COM_SUN_STAR_DRAWING_XDRAWPAGE_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_ANIMATIONS_XANIMATIONNODE_HPP_\n#include \n#endif\n\n#ifndef _SD_SLIDESHOW_HXX\n#include \"slideshow.hxx\"\n#endif\n\n#ifndef _SFX_OBJSH_HXX \/\/ SfxObjectShell\n#include \n#endif\n\n#ifndef _SV_GDIMTF_HXX \/\/ GDIMetaFile\n#include \n#endif\n\n#ifndef _SV_VIRDEV_HXX \/\/ class VirtualDevice\n#include \n#endif\n\n#ifndef _COM_SUN_STAR_PRESENTATION_FADEEFFECT_HPP_\n#include \n#endif\n\n#ifndef _SD_FADEDEF_H \/\/ enum FadeSpeed\n#include \n#endif\n\n#ifndef _SV_CTRL_HXX \/\/ class Control\n#include \n#endif\n\n#ifndef _SVDOUTL_HXX\n#include \n#endif\n#ifndef _SVDPAGV_HXX\n#include \n#endif\n#ifndef _SVDORECT_HXX\n#include \n#endif\n\n#include \"docprev.hxx\"\n#include \"drawdoc.hxx\"\n#include \"DrawDocShell.hxx\"\n#ifndef SD_VIEW_SHELL_HXX\n#include \"ViewShell.hxx\"\n#endif\n#ifndef SD_SHOW_VIEW_HXX\n#include \"showview.hxx\"\n#endif\n#ifndef SD_DRAW_VIEW_HXX\n#include \"drawview.hxx\"\n#endif\n#include \"sdpage.hxx\"\n\n#ifndef _SV_SVAPP_HXX\n#include \n#endif\n\n#include \n\nusing ::com::sun::star::drawing::XDrawPage;\nusing ::com::sun::star::animations::XAnimationNode;\nusing namespace ::com::sun::star;\nusing namespace ::com::sun::star::uno;\n\nconst int SdDocPreviewWin::FRAME = 4;\n\nvoid SdDocPreviewWin::SetObjectShell( SfxObjectShell* pObj, sal_uInt16 nShowPage )\n{\n mpObj = pObj;\n mnShowPage = nShowPage;\n delete mpSlideShow;\n mpSlideShow = 0;\n\n updateViewSettings();\n}\n\nSdDocPreviewWin::SdDocPreviewWin( Window* pParent, const ResId& rResId )\n: Control(pParent, rResId), pMetaFile( 0 ), bInEffect(FALSE), mpObj(NULL), mnShowPage(0)\n{\n mpSlideShow = 0;\n SetBorderStyle( WINDOW_BORDER_MONO );\n svtools::ColorConfig aColorConfig;\n Wallpaper aEmpty;\n SetBackground( aEmpty );\n}\n\nSdDocPreviewWin::SdDocPreviewWin( Window* pParent )\n: Control(pParent, 0 ), pMetaFile( 0 ), bInEffect(FALSE), mpObj(NULL), mnShowPage(0)\n{\n mpSlideShow = 0;\n SetBorderStyle( WINDOW_BORDER_MONO );\n svtools::ColorConfig aColorConfig;\n Wallpaper aEmpty;\n SetBackground( aEmpty );\n Resize();\n Show();\n}\n\nSdDocPreviewWin::~SdDocPreviewWin()\n{\n delete mpSlideShow;\n delete pMetaFile;\n}\n\nvoid SdDocPreviewWin::Resize()\n{\n Invalidate();\n if( mpSlideShow )\n mpSlideShow->resize( GetSizePixel() );\n}\n\nvoid SdDocPreviewWin::SetGDIFile( GDIMetaFile* pFile )\n{\n delete pMetaFile;\n pMetaFile = pFile;\n Invalidate();\n}\n\nvoid SdDocPreviewWin::CalcSizeAndPos( GDIMetaFile* pFile, Size& rSize, Point& rPoint )\n{\n Size aTmpSize = pFile ? pFile->GetPrefSize() : Size(1,1 );\n long nWidth = rSize.Width() - 2*FRAME;\n long nHeight = rSize.Height() - 2*FRAME;\n if( nWidth < 0 ) nWidth = 0;\n if( nHeight < 0 ) nHeight = 0;\n\n double dRatio=((double)aTmpSize.Width())\/aTmpSize.Height();\n double dRatioPreV=((double) nWidth ) \/ nHeight;\n\n if (dRatio>dRatioPreV)\n {\n rSize=Size(nWidth, (USHORT)(nWidth\/dRatio));\n rPoint=Point( 0, (USHORT)((nHeight-rSize.Height())\/2));\n }\n else\n {\n rSize=Size((USHORT)(nHeight*dRatio), nHeight);\n rPoint=Point((USHORT)((nWidth-rSize.Width())\/2),0);\n }\n}\n\nvoid SdDocPreviewWin::ImpPaint( GDIMetaFile* pFile, OutputDevice* pVDev )\n{\n Point aPoint;\n Size aSize = pVDev->GetOutputSize();\n Point bPoint(aSize.Width()-2*FRAME, aSize.Height()-2*FRAME );\n CalcSizeAndPos( pFile, aSize, aPoint );\n bPoint -= aPoint;\n aPoint += Point( FRAME, FRAME );\n\n svtools::ColorConfig aColorConfig;\n\n pVDev->SetLineColor();\n pVDev->SetFillColor( Color( aColorConfig.GetColorValue( svtools::APPBACKGROUND ).nColor ) );\n pVDev->DrawRect(Rectangle( Point(0,0 ), pVDev->GetOutputSize()));\n if( pFile )\n {\n pVDev->SetFillColor( maDocumentColor );\n pVDev->DrawRect(Rectangle(aPoint, aSize));\n pFile->WindStart();\n pFile->Play( pVDev, aPoint, aSize );\n }\n}\n\nvoid SdDocPreviewWin::Paint( const Rectangle& rRect )\n{\n if(( mpSlideShow == 0) || (mpSlideShow->isTerminated() ) )\n {\n SvtAccessibilityOptions aAccOptions;\n bool bUseContrast = aAccOptions.GetIsForPagePreviews() && Application::GetSettings().GetStyleSettings().GetHighContrastMode();\n SetDrawMode( bUseContrast\n ? ::sd::ViewShell::OUTPUT_DRAWMODE_CONTRAST\n : ::sd::ViewShell::OUTPUT_DRAWMODE_COLOR );\n\n ImpPaint( pMetaFile, (VirtualDevice*)this );\n\n }\n}\n\nvoid SdDocPreviewWin::startPreview()\n{\n if( mpSlideShow )\n {\n delete mpSlideShow;\n mpSlideShow = 0;\n }\n\n ::sd::DrawDocShell* pDocShell = dynamic_cast< ::sd::DrawDocShell * >( mpObj );\n if( mpObj )\n {\n SdDrawDocument* pDoc = pDocShell->GetDoc();\n\n if( pDoc )\n {\n SdPage* pPage = pDoc->GetSdPage( mnShowPage, PK_STANDARD );\n\n if( pPage && (pPage->getTransitionType() != 0) )\n {\n std::auto_ptr pSlideShow(\n new sd::Slideshow( 0, 0, pDoc ) );\n\n Reference< XDrawPage > xDrawPage( pPage->getUnoPage(), UNO_QUERY );\n Reference< XAnimationNode > xAnimationNode;\n\n if (pSlideShow->startPreview( xDrawPage, xAnimationNode, this ))\n mpSlideShow = pSlideShow.release();\n }\n }\n }\n}\n\nlong SdDocPreviewWin::Notify( NotifyEvent& rNEvt )\n{\n if ( rNEvt.GetType() == EVENT_MOUSEBUTTONDOWN )\n {\n const MouseEvent* pMEvt = rNEvt.GetMouseEvent();\n if ( pMEvt->IsLeft() )\n {\n if( rNEvt.GetWindow() == this )\n {\n if(aClickHdl.IsSet())\n aClickHdl.Call(this);\n }\n }\n }\n\n return Control::Notify( rNEvt );\n}\n\n\nvoid SdDocPreviewWin::updateViewSettings()\n{\n ::sd::DrawDocShell* pDocShell = PTR_CAST(::sd::DrawDocShell,mpObj);\n SdDrawDocument* pDoc = pDocShell?pDocShell->GetDoc():NULL;\n\n SvtAccessibilityOptions aAccOptions;\n bool bUseWhiteColor = !aAccOptions.GetIsForPagePreviews() && GetSettings().GetStyleSettings().GetHighContrastMode();\n if( bUseWhiteColor )\n {\n maDocumentColor = Color( COL_WHITE );\n }\n else\n {\n svtools::ColorConfig aColorConfig;\n maDocumentColor = Color( aColorConfig.GetColorValue( svtools::DOCCOLOR ).nColor );\n }\n\n GDIMetaFile* pMtf = NULL;\n\n if(pDoc)\n {\n SdPage * pPage = pDoc->GetSdPage( mnShowPage, PK_STANDARD );\n if( pPage )\n {\n SdrOutliner& rOutl = pDoc->GetDrawOutliner();\n Color aOldBackgroundColor = rOutl.GetBackgroundColor();\n rOutl.SetBackgroundColor( maDocumentColor );\n\n pMtf = new GDIMetaFile;\n\n VirtualDevice aVDev;\n\n const Fraction aFrac( pDoc->GetScaleFraction() );\n const MapMode aMap( pDoc->GetScaleUnit(), Point(), aFrac, aFrac );\n\n aVDev.SetMapMode( aMap );\n\n \/\/ #109058# Disable output, as we only want to record a metafile\n aVDev.EnableOutput( FALSE );\n\n pMtf->Record( &aVDev );\n\n ::sd::DrawView* pView = new ::sd::DrawView(pDocShell, this, NULL);\n\n\n const Size aSize( pPage->GetSize() );\n\n pView->SetBordVisible( FALSE );\n pView->SetPageVisible( FALSE );\n pView->ShowSdrPage( pPage );\n\n const Point aNewOrg( pPage->GetLftBorder(), pPage->GetUppBorder() );\n const Size aNewSize( aSize.Width() - pPage->GetLftBorder() - pPage->GetRgtBorder(),\n aSize.Height() - pPage->GetUppBorder() - pPage->GetLwrBorder() );\n const Rectangle aClipRect( aNewOrg, aNewSize );\n MapMode aVMap( aMap );\n\n SdrPageView* pPageView = pView->GetSdrPageView();\n\n aVDev.Push();\n aVMap.SetOrigin( Point( -aNewOrg.X(), -aNewOrg.Y() ) );\n aVDev.SetRelativeMapMode( aVMap );\n aVDev.IntersectClipRegion( aClipRect );\n\n \/\/ Use new StandardCheckVisisbilityRedirector\n StandardCheckVisisbilityRedirector aRedirector;\n const Rectangle aRedrawRectangle( Point(), aNewSize );\n Region aRedrawRegion(aRedrawRectangle);\n pView->SdrPaintView::CompleteRedraw(&aVDev,aRedrawRegion,0,&aRedirector);\n\n aVDev.Pop();\n\n pMtf->Stop();\n pMtf->WindStart();\n pMtf->SetPrefMapMode( aMap );\n pMtf->SetPrefSize( aNewSize );\n\n rOutl.SetBackgroundColor( aOldBackgroundColor );\n\n delete pView;\n }\n }\n\n delete pMetaFile;\n pMetaFile = pMtf;\n\n Invalidate();\n}\n\nvoid SdDocPreviewWin::SFX_NOTIFY(SfxBroadcaster& rBC, const TypeId& rBCType, const SfxHint& rHint, const TypeId& rHintType)\n{\n if( rHint.ISA( SfxSimpleHint ) && ( (SfxSimpleHint&) rHint ).GetId() == SFX_HINT_COLORS_CHANGED )\n {\n updateViewSettings();\n }\n}\nvoid SdDocPreviewWin::DataChanged( const DataChangedEvent& rDCEvt )\n{\n Control::DataChanged( rDCEvt );\n\n if ( (rDCEvt.GetType() == DATACHANGED_SETTINGS) && (rDCEvt.GetFlags() & SETTINGS_STYLE) )\n {\n updateViewSettings();\n }\n}\nINTEGRATION: CWS sdwarningsbegone (1.18.34); FILE MERGED 2006\/11\/22 15:02:33 cl 1.18.34.2: RESYNC: (1.18-1.19); FILE MERGED 2006\/11\/22 12:41:46 cl 1.18.34.1: #i69285# warning free code changes for unxlngi6.pro\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: docprev.cxx,v $\n *\n * $Revision: 1.20 $\n *\n * last change: $Author: kz $ $Date: 2006-12-12 17:04:46 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_sd.hxx\"\n\n#ifndef _COM_SUN_STAR_DRAWING_XDRAWPAGE_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_ANIMATIONS_XANIMATIONNODE_HPP_\n#include \n#endif\n\n#ifndef _SD_SLIDESHOW_HXX\n#include \"slideshow.hxx\"\n#endif\n\n#ifndef _SFX_OBJSH_HXX \/\/ SfxObjectShell\n#include \n#endif\n\n#ifndef _SV_GDIMTF_HXX \/\/ GDIMetaFile\n#include \n#endif\n\n#ifndef _SV_VIRDEV_HXX \/\/ class VirtualDevice\n#include \n#endif\n\n#ifndef _COM_SUN_STAR_PRESENTATION_FADEEFFECT_HPP_\n#include \n#endif\n\n#ifndef _SD_FADEDEF_H \/\/ enum FadeSpeed\n#include \n#endif\n\n#ifndef _SV_CTRL_HXX \/\/ class Control\n#include \n#endif\n\n#ifndef _SVDOUTL_HXX\n#include \n#endif\n#ifndef _SVDPAGV_HXX\n#include \n#endif\n#ifndef _SVDORECT_HXX\n#include \n#endif\n\n#include \"docprev.hxx\"\n#include \"drawdoc.hxx\"\n#include \"DrawDocShell.hxx\"\n#ifndef SD_VIEW_SHELL_HXX\n#include \"ViewShell.hxx\"\n#endif\n#ifndef SD_SHOW_VIEW_HXX\n#include \"showview.hxx\"\n#endif\n#ifndef SD_DRAW_VIEW_HXX\n#include \"drawview.hxx\"\n#endif\n#include \"sdpage.hxx\"\n\n#ifndef _SV_SVAPP_HXX\n#include \n#endif\n\n#include \n\nusing ::com::sun::star::drawing::XDrawPage;\nusing ::com::sun::star::animations::XAnimationNode;\nusing namespace ::com::sun::star;\nusing namespace ::com::sun::star::uno;\n\nconst int SdDocPreviewWin::FRAME = 4;\n\nvoid SdDocPreviewWin::SetObjectShell( SfxObjectShell* pObj, sal_uInt16 nShowPage )\n{\n mpObj = pObj;\n mnShowPage = nShowPage;\n delete mpSlideShow;\n mpSlideShow = 0;\n\n updateViewSettings();\n}\n\nSdDocPreviewWin::SdDocPreviewWin( Window* pParent, const ResId& rResId )\n: Control(pParent, rResId), pMetaFile( 0 ), bInEffect(FALSE), mpObj(NULL), mnShowPage(0)\n{\n mpSlideShow = 0;\n SetBorderStyle( WINDOW_BORDER_MONO );\n svtools::ColorConfig aColorConfig;\n Wallpaper aEmpty;\n SetBackground( aEmpty );\n}\n\nSdDocPreviewWin::SdDocPreviewWin( Window* pParent )\n: Control(pParent, 0 ), pMetaFile( 0 ), bInEffect(FALSE), mpObj(NULL), mnShowPage(0)\n{\n mpSlideShow = 0;\n SetBorderStyle( WINDOW_BORDER_MONO );\n svtools::ColorConfig aColorConfig;\n Wallpaper aEmpty;\n SetBackground( aEmpty );\n Resize();\n Show();\n}\n\nSdDocPreviewWin::~SdDocPreviewWin()\n{\n delete mpSlideShow;\n delete pMetaFile;\n}\n\nvoid SdDocPreviewWin::Resize()\n{\n Invalidate();\n if( mpSlideShow )\n mpSlideShow->resize( GetSizePixel() );\n}\n\nvoid SdDocPreviewWin::SetGDIFile( GDIMetaFile* pFile )\n{\n delete pMetaFile;\n pMetaFile = pFile;\n Invalidate();\n}\n\nvoid SdDocPreviewWin::CalcSizeAndPos( GDIMetaFile* pFile, Size& rSize, Point& rPoint )\n{\n Size aTmpSize = pFile ? pFile->GetPrefSize() : Size(1,1 );\n long nWidth = rSize.Width() - 2*FRAME;\n long nHeight = rSize.Height() - 2*FRAME;\n if( nWidth < 0 ) nWidth = 0;\n if( nHeight < 0 ) nHeight = 0;\n\n double dRatio=((double)aTmpSize.Width())\/aTmpSize.Height();\n double dRatioPreV=((double) nWidth ) \/ nHeight;\n\n if (dRatio>dRatioPreV)\n {\n rSize=Size(nWidth, (USHORT)(nWidth\/dRatio));\n rPoint=Point( 0, (USHORT)((nHeight-rSize.Height())\/2));\n }\n else\n {\n rSize=Size((USHORT)(nHeight*dRatio), nHeight);\n rPoint=Point((USHORT)((nWidth-rSize.Width())\/2),0);\n }\n}\n\nvoid SdDocPreviewWin::ImpPaint( GDIMetaFile* pFile, OutputDevice* pVDev )\n{\n Point aPoint;\n Size aSize = pVDev->GetOutputSize();\n Point bPoint(aSize.Width()-2*FRAME, aSize.Height()-2*FRAME );\n CalcSizeAndPos( pFile, aSize, aPoint );\n bPoint -= aPoint;\n aPoint += Point( FRAME, FRAME );\n\n svtools::ColorConfig aColorConfig;\n\n pVDev->SetLineColor();\n pVDev->SetFillColor( Color( aColorConfig.GetColorValue( svtools::APPBACKGROUND ).nColor ) );\n pVDev->DrawRect(Rectangle( Point(0,0 ), pVDev->GetOutputSize()));\n if( pFile )\n {\n pVDev->SetFillColor( maDocumentColor );\n pVDev->DrawRect(Rectangle(aPoint, aSize));\n pFile->WindStart();\n pFile->Play( pVDev, aPoint, aSize );\n }\n}\n\nvoid SdDocPreviewWin::Paint( const Rectangle& )\n{\n if(( mpSlideShow == 0) || (mpSlideShow->isTerminated() ) )\n {\n SvtAccessibilityOptions aAccOptions;\n bool bUseContrast = aAccOptions.GetIsForPagePreviews() && Application::GetSettings().GetStyleSettings().GetHighContrastMode();\n SetDrawMode( bUseContrast\n ? ::sd::ViewShell::OUTPUT_DRAWMODE_CONTRAST\n : ::sd::ViewShell::OUTPUT_DRAWMODE_COLOR );\n\n ImpPaint( pMetaFile, (VirtualDevice*)this );\n\n }\n}\n\nvoid SdDocPreviewWin::startPreview()\n{\n if( mpSlideShow )\n {\n delete mpSlideShow;\n mpSlideShow = 0;\n }\n\n ::sd::DrawDocShell* pDocShell = dynamic_cast< ::sd::DrawDocShell * >( mpObj );\n if( mpObj )\n {\n SdDrawDocument* pDoc = pDocShell->GetDoc();\n\n if( pDoc )\n {\n SdPage* pPage = pDoc->GetSdPage( mnShowPage, PK_STANDARD );\n\n if( pPage && (pPage->getTransitionType() != 0) )\n {\n std::auto_ptr pSlideShow(\n new sd::Slideshow( 0, 0, pDoc ) );\n\n Reference< XDrawPage > xDrawPage( pPage->getUnoPage(), UNO_QUERY );\n Reference< XAnimationNode > xAnimationNode;\n\n if (pSlideShow->startPreview( xDrawPage, xAnimationNode, this ))\n mpSlideShow = pSlideShow.release();\n }\n }\n }\n}\n\nlong SdDocPreviewWin::Notify( NotifyEvent& rNEvt )\n{\n if ( rNEvt.GetType() == EVENT_MOUSEBUTTONDOWN )\n {\n const MouseEvent* pMEvt = rNEvt.GetMouseEvent();\n if ( pMEvt->IsLeft() )\n {\n if( rNEvt.GetWindow() == this )\n {\n if(aClickHdl.IsSet())\n aClickHdl.Call(this);\n }\n }\n }\n\n return Control::Notify( rNEvt );\n}\n\n\nvoid SdDocPreviewWin::updateViewSettings()\n{\n ::sd::DrawDocShell* pDocShell = PTR_CAST(::sd::DrawDocShell,mpObj);\n SdDrawDocument* pDoc = pDocShell?pDocShell->GetDoc():NULL;\n\n SvtAccessibilityOptions aAccOptions;\n bool bUseWhiteColor = !aAccOptions.GetIsForPagePreviews() && GetSettings().GetStyleSettings().GetHighContrastMode();\n if( bUseWhiteColor )\n {\n maDocumentColor = Color( COL_WHITE );\n }\n else\n {\n svtools::ColorConfig aColorConfig;\n maDocumentColor = Color( aColorConfig.GetColorValue( svtools::DOCCOLOR ).nColor );\n }\n\n GDIMetaFile* pMtf = NULL;\n\n if(pDoc)\n {\n SdPage * pPage = pDoc->GetSdPage( mnShowPage, PK_STANDARD );\n if( pPage )\n {\n SdrOutliner& rOutl = pDoc->GetDrawOutliner();\n Color aOldBackgroundColor = rOutl.GetBackgroundColor();\n rOutl.SetBackgroundColor( maDocumentColor );\n\n pMtf = new GDIMetaFile;\n\n VirtualDevice aVDev;\n\n const Fraction aFrac( pDoc->GetScaleFraction() );\n const MapMode aMap( pDoc->GetScaleUnit(), Point(), aFrac, aFrac );\n\n aVDev.SetMapMode( aMap );\n\n \/\/ #109058# Disable output, as we only want to record a metafile\n aVDev.EnableOutput( FALSE );\n\n pMtf->Record( &aVDev );\n\n ::sd::DrawView* pView = new ::sd::DrawView(pDocShell, this, NULL);\n\n\n const Size aSize( pPage->GetSize() );\n\n pView->SetBordVisible( FALSE );\n pView->SetPageVisible( FALSE );\n pView->ShowSdrPage( pPage );\n\n const Point aNewOrg( pPage->GetLftBorder(), pPage->GetUppBorder() );\n const Size aNewSize( aSize.Width() - pPage->GetLftBorder() - pPage->GetRgtBorder(),\n aSize.Height() - pPage->GetUppBorder() - pPage->GetLwrBorder() );\n const Rectangle aClipRect( aNewOrg, aNewSize );\n MapMode aVMap( aMap );\n\n aVDev.Push();\n aVMap.SetOrigin( Point( -aNewOrg.X(), -aNewOrg.Y() ) );\n aVDev.SetRelativeMapMode( aVMap );\n aVDev.IntersectClipRegion( aClipRect );\n\n \/\/ Use new StandardCheckVisisbilityRedirector\n StandardCheckVisisbilityRedirector aRedirector;\n const Rectangle aRedrawRectangle( Point(), aNewSize );\n Region aRedrawRegion(aRedrawRectangle);\n pView->SdrPaintView::CompleteRedraw(&aVDev,aRedrawRegion,0,&aRedirector);\n\n aVDev.Pop();\n\n pMtf->Stop();\n pMtf->WindStart();\n pMtf->SetPrefMapMode( aMap );\n pMtf->SetPrefSize( aNewSize );\n\n rOutl.SetBackgroundColor( aOldBackgroundColor );\n\n delete pView;\n }\n }\n\n delete pMetaFile;\n pMetaFile = pMtf;\n\n Invalidate();\n}\n\nvoid SdDocPreviewWin::SFX_NOTIFY(SfxBroadcaster&, const TypeId& rBCType, const SfxHint& rHint, const TypeId& rHintType)\n{\n if( rHint.ISA( SfxSimpleHint ) && ( (SfxSimpleHint&) rHint ).GetId() == SFX_HINT_COLORS_CHANGED )\n {\n updateViewSettings();\n }\n}\nvoid SdDocPreviewWin::DataChanged( const DataChangedEvent& rDCEvt )\n{\n Control::DataChanged( rDCEvt );\n\n if ( (rDCEvt.GetType() == DATACHANGED_SETTINGS) && (rDCEvt.GetFlags() & SETTINGS_STYLE) )\n {\n updateViewSettings();\n }\n}\n<|endoftext|>"} {"text":"\/\/\n\/\/ Copyright (c) 2013-2014 Christoph Malek\n\/\/ See LICENSE for more information.\n\/\/\n\n#ifndef RJ_SHARED_LEVEL_MANAGER_LEVEL_DATA_HPP\n#define RJ_SHARED_LEVEL_MANAGER_LEVEL_DATA_HPP\n\n\n#include \n#include \n\n#include \n\n\nnamespace rj\n{\n\tclass level_data\n\t{\n\t\tstd::vector m_data{\"RJLEVEL\"};\n\n\tpublic:\n\t\tlevel_data() = default;\n\n\t\tvoid add_entity(entity_figure figure, entity_propertie prop, const vec2f& pos) noexcept\n\t\t{\n\t\t\tauto str(mlk::stl_string::str_format(\"Ent[%%, %%, {%%, %%}]\", figure, prop, pos.x, pos.y));\n\t\t\tm_data.push_back(str);\n\t\t}\n\n\t\tauto num_entities() const noexcept\n\t\t-> decltype(m_data.size())\n\t\t{return m_data.size() - 1;}\n\n\t\tint size() const noexcept\n\t\t{return this->data().size();}\n\n\t\tmlk::data_packet data() const noexcept\n\t\t{\n\t\t\tmlk::data_packet result;\n\t\t\tfor(auto& a : m_data)\n\t\t\t\tmlk::cnt::append(a + '\\0', result);\n\t\t\treturn result;\n\t\t}\n\t};\n}\n\n\n#endif \/\/ RJ_SHARED_LEVEL_MANAGER_LEVEL_DATA_HPP\nadded missing include\/\/\n\/\/ Copyright (c) 2013-2014 Christoph Malek\n\/\/ See LICENSE for more information.\n\/\/\n\n#ifndef RJ_SHARED_LEVEL_MANAGER_LEVEL_DATA_HPP\n#define RJ_SHARED_LEVEL_MANAGER_LEVEL_DATA_HPP\n\n\n#include \n#include \n\n#include \n#include \n\n\nnamespace rj\n{\n\tclass level_data\n\t{\n\t\tstd::vector m_data{\"RJLEVEL\"};\n\n\tpublic:\n\t\tlevel_data() = default;\n\n\t\tvoid add_entity(entity_figure figure, entity_propertie prop, const vec2f& pos) noexcept\n\t\t{\n\t\t\tauto str(mlk::stl_string::str_format(\"Ent[%%, %%, {%%, %%}]\", figure, prop, pos.x, pos.y));\n\t\t\tm_data.push_back(str);\n\t\t}\n\n\t\tauto num_entities() const noexcept\n\t\t-> decltype(m_data.size())\n\t\t{return m_data.size() - 1;}\n\n\t\tint size() const noexcept\n\t\t{return this->data().size();}\n\n\t\tmlk::data_packet data() const noexcept\n\t\t{\n\t\t\tmlk::data_packet result;\n\t\t\tfor(auto& a : m_data)\n\t\t\t\tmlk::cnt::append(a + '\\0', result);\n\t\t\treturn result;\n\t\t}\n\t};\n}\n\n\n#endif \/\/ RJ_SHARED_LEVEL_MANAGER_LEVEL_DATA_HPP\n<|endoftext|>"} {"text":"\n#include \n#include \n\n#include \n\n#include \n#include \n\n#include \"setup.hpp\"\n\nusing Context = proxc::Context;\n\nvoid printer(int x, int y) \n{\n SafeCout::print(x, \", \", y);\n}\n\nvoid test_context()\n{\n \/\/ TODO\n}\n\nint main()\n{\n test_context();\n\n return 0;\n}\nSome simple context test.\n#include \n#include \n\n#include \n\n#include \n\n#include \"setup.hpp\"\n\nusing Context = proxc::Context;\n\nvoid test_context()\n{\n std::vector ints;\n std::size_t num_items = 100;\n std::size_t index = 0;\n\n Context m_ctx{ proxc::context::main_type };\n\n Context even_ctx{ proxc::context::work_type,\n [&m_ctx,&ints,&index,&num_items] (void * vp) {\n Context * odd = static_cast< Context * >(vp);\n m_ctx.resume();\n while (index < num_items) {\n ints.push_back(2 * index);\n odd->resume();\n }\n m_ctx.resume();\n }\n };\n\n Context odd_ctx{ proxc::context::work_type,\n [&m_ctx,&ints,&index,&num_items] (void * vp) {\n Context * even = static_cast< Context * >(vp);\n m_ctx.resume();\n while (index < num_items) {\n ints.push_back(2 * index++ + 1);\n even->resume();\n }\n m_ctx.resume();\n }\n };\n\n odd_ctx.resume(&even_ctx);\n even_ctx.resume(&odd_ctx);\n even_ctx.resume();\n\n for (std::size_t i = 0; i < num_items; ++i) {\n throw_assert_equ(ints[i], i, \"items should be equal\");\n }\n std::cout << \"main: done\" << std::endl;\n}\n\nint main()\n{\n test_context();\n\n return 0;\n}\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: fuline.cxx,v $\n *\n * $Revision: 1.12 $\n *\n * last change: $Author: rt $ $Date: 2007-04-26 08:38:20 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_sd.hxx\"\n\n\n#include \"fuline.hxx\"\n\n#include \n#ifndef _SVX_TAB_LINE_HXX \/\/autogen\n#include \n#endif\n#ifndef _XENUM_HXX \/\/autogen\n#include \n#endif\n#ifndef _SV_MSGBOX_HXX \/\/autogen\n#include \n#endif\n#ifndef _SFXINTITEM_HXX \/\/autogen\n#include \n#endif\n#ifndef _SFXSTRITEM_HXX \/\/autogen\n#include \n#endif\n#ifndef _SFXREQUEST_HXX \/\/autogen\n#include \n#endif\n#ifndef _XDEF_HXX \/\/autogen\n#include \n#endif\n#ifndef _SFX_BINDINGS_HXX \/\/autogen\n#include \n#endif\n#ifndef _SFXVIEWFRM_HXX\n#include \n#endif\n\n#ifndef SD_VIEW_SHELL_HXX\n#include \"ViewShell.hxx\"\n#endif\n#ifndef SD_VIEW_HXX\n#include \"View.hxx\"\n#endif\n#ifndef SD_WINDOW_SHELL_HXX\n#include \"Window.hxx\"\n#endif\n#include \"drawdoc.hxx\"\n#include \"app.hrc\"\n#include \n#include \n\nnamespace sd {\n\nTYPEINIT1( FuLine, FuPoor );\n\n\/*************************************************************************\n|*\n|* Konstruktor\n|*\n\\************************************************************************\/\n\nFuLine::FuLine (\n ViewShell* pViewSh,\n ::sd::Window* pWin,\n ::sd::View* pView,\n SdDrawDocument* pDoc,\n SfxRequest& rReq)\n : FuPoor(pViewSh, pWin, pView, pDoc, rReq)\n{\n}\n\nFunctionReference FuLine::Create( ViewShell* pViewSh, ::sd::Window* pWin, ::sd::View* pView, SdDrawDocument* pDoc, SfxRequest& rReq )\n{\n FunctionReference xFunc( new FuLine( pViewSh, pWin, pView, pDoc, rReq ) );\n xFunc->DoExecute(rReq);\n return xFunc;\n}\n\nvoid FuLine::DoExecute( SfxRequest& rReq )\n{\n BOOL bHasMarked = mpView->AreObjectsMarked();\n\n const SfxItemSet* pArgs = rReq.GetArgs();\n\n if( !pArgs )\n {\n const SdrObject* pObj = NULL;\n const SdrMarkList& rMarkList = mpView->GetMarkedObjectList();\n if( rMarkList.GetMarkCount() == 1 )\n pObj = rMarkList.GetMark(0)->GetMarkedSdrObj();\n\n SfxItemSet* pNewAttr = new SfxItemSet( mpDoc->GetPool() );\n mpView->GetAttributes( *pNewAttr );\n\n SvxAbstractDialogFactory* pFact = SvxAbstractDialogFactory::Create();\n SfxAbstractTabDialog * pDlg = pFact ? pFact->CreateSvxLineTabDialog(NULL,pNewAttr,mpDoc,RID_SVXDLG_LINE,pObj,bHasMarked) : 0;\n if( pDlg && (pDlg->Execute() == RET_OK) )\n {\n mpView->SetAttributes (*(pDlg->GetOutputItemSet ()));\n }\n\n \/\/ Attribute wurden geaendert, Listboxes in Objectbars muessen aktualisiert werden\n static USHORT SidArray[] = {\n SID_ATTR_LINE_STYLE,\n SID_ATTR_LINE_DASH,\n SID_ATTR_LINE_WIDTH,\n SID_ATTR_LINE_COLOR,\n 0 };\n\n mpViewShell->GetViewFrame()->GetBindings().Invalidate( SidArray );\n\n delete pDlg;\n delete pNewAttr;\n }\n\n rReq.Ignore ();\n}\n\nvoid FuLine::Activate()\n{\n}\n\nvoid FuLine::Deactivate()\n{\n}\n\n\n} \/\/ end of namespace sd\nINTEGRATION: CWS changefileheader (1.12.222); FILE MERGED 2008\/04\/01 15:34:36 thb 1.12.222.3: #i85898# Stripping all external header guards 2008\/04\/01 12:38:54 thb 1.12.222.2: #i85898# Stripping all external header guards 2008\/03\/31 13:58:05 rt 1.12.222.1: #i87441# Change license header to LPGL v3.\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2008 by Sun Microsystems, Inc.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: fuline.cxx,v $\n * $Revision: 1.13 $\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * \n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_sd.hxx\"\n\n\n#include \"fuline.hxx\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"ViewShell.hxx\"\n#include \"View.hxx\"\n#ifndef SD_WINDOW_SHELL_HXX\n#include \"Window.hxx\"\n#endif\n#include \"drawdoc.hxx\"\n#include \"app.hrc\"\n#include \n#include \n\nnamespace sd {\n\nTYPEINIT1( FuLine, FuPoor );\n\n\/*************************************************************************\n|*\n|* Konstruktor\n|*\n\\************************************************************************\/\n\nFuLine::FuLine (\n ViewShell* pViewSh,\n ::sd::Window* pWin,\n ::sd::View* pView,\n SdDrawDocument* pDoc,\n SfxRequest& rReq)\n : FuPoor(pViewSh, pWin, pView, pDoc, rReq)\n{\n}\n\nFunctionReference FuLine::Create( ViewShell* pViewSh, ::sd::Window* pWin, ::sd::View* pView, SdDrawDocument* pDoc, SfxRequest& rReq )\n{\n FunctionReference xFunc( new FuLine( pViewSh, pWin, pView, pDoc, rReq ) );\n xFunc->DoExecute(rReq);\n return xFunc;\n}\n\nvoid FuLine::DoExecute( SfxRequest& rReq )\n{\n BOOL bHasMarked = mpView->AreObjectsMarked();\n\n const SfxItemSet* pArgs = rReq.GetArgs();\n\n if( !pArgs )\n {\n const SdrObject* pObj = NULL;\n const SdrMarkList& rMarkList = mpView->GetMarkedObjectList();\n if( rMarkList.GetMarkCount() == 1 )\n pObj = rMarkList.GetMark(0)->GetMarkedSdrObj();\n\n SfxItemSet* pNewAttr = new SfxItemSet( mpDoc->GetPool() );\n mpView->GetAttributes( *pNewAttr );\n\n SvxAbstractDialogFactory* pFact = SvxAbstractDialogFactory::Create();\n SfxAbstractTabDialog * pDlg = pFact ? pFact->CreateSvxLineTabDialog(NULL,pNewAttr,mpDoc,RID_SVXDLG_LINE,pObj,bHasMarked) : 0;\n if( pDlg && (pDlg->Execute() == RET_OK) )\n {\n mpView->SetAttributes (*(pDlg->GetOutputItemSet ()));\n }\n\n \/\/ Attribute wurden geaendert, Listboxes in Objectbars muessen aktualisiert werden\n static USHORT SidArray[] = {\n SID_ATTR_LINE_STYLE,\n SID_ATTR_LINE_DASH,\n SID_ATTR_LINE_WIDTH,\n SID_ATTR_LINE_COLOR,\n 0 };\n\n mpViewShell->GetViewFrame()->GetBindings().Invalidate( SidArray );\n\n delete pDlg;\n delete pNewAttr;\n }\n\n rReq.Ignore ();\n}\n\nvoid FuLine::Activate()\n{\n}\n\nvoid FuLine::Deactivate()\n{\n}\n\n\n} \/\/ end of namespace sd\n<|endoftext|>"} {"text":"\/\/ The libMesh Finite Element Library.\n\/\/ Copyright (C) 2002-2012 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner\n\n\/\/ This library is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU Lesser General Public\n\/\/ License as published by the Free Software Foundation; either\n\/\/ version 2.1 of the License, or (at your option) any later version.\n\n\/\/ This library is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ Lesser General Public License for more details.\n\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License along with this library; if not, write to the Free Software\n\/\/ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n\n\n\n\/\/ C++ Includes -----------------------------------\n\n\/\/ Local Includes -----------------------------------\n#include \"libmesh\/mesh_base.h\"\n#include \"libmesh\/linear_partitioner.h\"\n#include \"libmesh\/libmesh_logging.h\"\n#include \"libmesh\/elem.h\"\n\nnamespace libMesh\n{\n\n\n\/\/ ------------------------------------------------------------\n\/\/ LinearPartitioner implementation\nvoid LinearPartitioner::_do_partition (MeshBase& mesh,\n\t\t\t\t const unsigned int n)\n{\n libmesh_assert_greater (n, 0);\n\n \/\/ Check for an easy return\n if (n == 1)\n {\n this->single_partition (mesh);\n return;\n }\n\n \/\/ Create a simple linear partitioning\n {\n START_LOG (\"partition()\", \"LinearPartitioner\");\n\n const dof_id_type n_active_elem = mesh.n_active_elem();\n const dof_id_type blksize = n_active_elem\/n;\n\n dof_id_type e = 0;\n\n MeshBase::element_iterator elem_it = mesh.active_elements_begin();\n const MeshBase::element_iterator elem_end = mesh.active_elements_end();\n\n for ( ; elem_it != elem_end; ++elem_it)\n {\n\tif ((e\/blksize) < n)\n {\n Elem *elem = *elem_it;\n\t elem->processor_id() =\n\t libmesh_cast_int(e\/blksize);\n }\n\telse\n {\n Elem *elem = *elem_it;\n\t elem->processor_id() = 0;\n\t elem = elem->parent();\n\t }\n\n\te++;\n }\n\n STOP_LOG (\"partition()\", \"LinearPartitioner\");\n }\n}\n\n} \/\/ namespace libMesh\nTypo fix for previous commit\/\/ The libMesh Finite Element Library.\n\/\/ Copyright (C) 2002-2012 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner\n\n\/\/ This library is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU Lesser General Public\n\/\/ License as published by the Free Software Foundation; either\n\/\/ version 2.1 of the License, or (at your option) any later version.\n\n\/\/ This library is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ Lesser General Public License for more details.\n\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License along with this library; if not, write to the Free Software\n\/\/ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n\n\n\n\/\/ C++ Includes -----------------------------------\n\n\/\/ Local Includes -----------------------------------\n#include \"libmesh\/mesh_base.h\"\n#include \"libmesh\/linear_partitioner.h\"\n#include \"libmesh\/libmesh_logging.h\"\n#include \"libmesh\/elem.h\"\n\nnamespace libMesh\n{\n\n\n\/\/ ------------------------------------------------------------\n\/\/ LinearPartitioner implementation\nvoid LinearPartitioner::_do_partition (MeshBase& mesh,\n\t\t\t\t const unsigned int n)\n{\n libmesh_assert_greater (n, 0);\n\n \/\/ Check for an easy return\n if (n == 1)\n {\n this->single_partition (mesh);\n return;\n }\n\n \/\/ Create a simple linear partitioning\n {\n START_LOG (\"partition()\", \"LinearPartitioner\");\n\n const dof_id_type n_active_elem = mesh.n_active_elem();\n const dof_id_type blksize = n_active_elem\/n;\n\n dof_id_type e = 0;\n\n MeshBase::element_iterator elem_it = mesh.active_elements_begin();\n const MeshBase::element_iterator elem_end = mesh.active_elements_end();\n\n for ( ; elem_it != elem_end; ++elem_it)\n {\n\tif ((e\/blksize) < n)\n {\n Elem *elem = *elem_it;\n\t elem->processor_id() =\n\t libmesh_cast_int(e\/blksize);\n }\n\telse\n {\n Elem *elem = *elem_it;\n\t elem->processor_id() = 0;\n\t elem = elem->parent();\n\t }\n\n\te++;\n }\n\n STOP_LOG (\"partition()\", \"LinearPartitioner\");\n }\n}\n\n} \/\/ namespace libMesh\n<|endoftext|>"} {"text":"\/\/=======================================================================\n\/\/ Copyright Baptiste Wicht 2011.\n\/\/ Distributed under the Boost Software License, Version 1.0.\n\/\/ (See accompanying file LICENSE_1_0.txt or copy at\n\/\/ http:\/\/www.boost.org\/LICENSE_1_0.txt)\n\/\/=======================================================================\n\n#include \n#include \n\n\/\/#include \"Utils.hpp\"\n#include \"VisitorUtils.hpp\"\n#include \"Options.hpp\"\n#include \"PerfsTimer.hpp\"\n\n#include \"mtac\/Pass.hpp\"\n#include \"mtac\/Optimizer.hpp\"\n#include \"mtac\/Program.hpp\"\n#include \"mtac\/Printer.hpp\"\n\n\/\/The custom optimizations\n#include \"mtac\/VariableCleaner.hpp\"\n#include \"mtac\/RemoveEmptyFunctions.hpp\"\n#include \"mtac\/DeadCodeElimination.hpp\"\n#include \"mtac\/BasicBlockOptimizations.hpp\"\n#include \"mtac\/BranchOptimizations.hpp\"\n#include \"mtac\/ConcatReduction.hpp\"\n\n\/\/The optimization visitors\n#include \"mtac\/ArithmeticIdentities.hpp\"\n#include \"mtac\/ReduceInStrength.hpp\"\n#include \"mtac\/ConstantFolding.hpp\"\n#include \"mtac\/RemoveAssign.hpp\"\n#include \"mtac\/RemoveMultipleAssign.hpp\"\n#include \"mtac\/MathPropagation.hpp\"\n\n\/\/The data-flow problems\n#include \"mtac\/GlobalOptimizations.hpp\"\n#include \"mtac\/ConstantPropagationProblem.hpp\"\n#include \"mtac\/OffsetConstantPropagationProblem.hpp\"\n#include \"mtac\/CommonSubexpressionElimination.hpp\"\n\nusing namespace eddic;\n\nnamespace {\n\nstatic const unsigned int MAX_THREADS = 2;\nstatic const bool DebugPerf = false;\n\ntemplate\nbool apply_to_all(std::shared_ptr function){\n Visitor visitor;\n\n for(auto& block : function->getBasicBlocks()){\n visit_each(visitor, block->statements);\n }\n\n return visitor.optimized;\n}\n\ntemplate\nbool apply_to_basic_blocks_two_pass(std::shared_ptr function){\n bool optimized = false;\n\n for(auto& block : function->getBasicBlocks()){\n Visitor visitor;\n visitor.pass = mtac::Pass::DATA_MINING;\n\n visit_each(visitor, block->statements);\n\n visitor.pass = mtac::Pass::OPTIMIZE;\n\n visit_each(visitor, block->statements);\n\n optimized |= visitor.optimized;\n }\n\n return optimized;\n}\n\ntemplate\nbool data_flow_optimization(std::shared_ptr function){\n bool optimized = false;\n\n Problem problem;\n\n auto results = mtac::data_flow(function, problem);\n\n \/\/Once the data-flow problem is fixed, statements can be optimized\n for(auto& block : function->getBasicBlocks()){\n for(auto& statement : block->statements){\n optimized |= problem.optimize(statement, results);\n }\n }\n\n return optimized;\n}\n\nbool debug(const std::string& name, bool b, std::shared_ptr function){\n if(option_defined(\"dev\")){\n if(b){\n std::cout << \"optimization \" << name << \" returned true\" << std::endl;\n\n \/\/Print the function\n print(function);\n } else {\n std::cout << \"optimization \" << name << \" returned false\" << std::endl;\n }\n }\n\n return b;\n}\n\n}\n\nvoid optimize_function(std::shared_ptr function, std::shared_ptr pool){\n if(option_defined(\"dev\")){\n std::cout << \"Start optimizations on \" << function->getName() << std::endl;\n\n print(function);\n }\n\n bool optimized;\n do {\n optimized = false;\n\n optimized |= debug(\"Aritmetic Identities\", apply_to_all(function), function);\n optimized |= debug(\"Reduce in Strength\", apply_to_all(function), function);\n optimized |= debug(\"Constant folding\", apply_to_all(function), function);\n\n optimized |= debug(\"Constant propagation\", data_flow_optimization(function), function);\n optimized |= debug(\"Offset Constant Propagation\", data_flow_optimization(function), function);\n\n \/\/If there was optimizations here, better to try again before perfoming common subexpression\n if(optimized){\n continue;\n }\n\n optimized |= debug(\"Common Subexpression Elimination\", data_flow_optimization(function), function);\n\n optimized |= debug(\"Math Propagation\", apply_to_basic_blocks_two_pass(function), function);\n \n optimized |= debug(\"Dead-Code Elimination\", mtac::dead_code_elimination(function), function);\n\n optimized |= debug(\"Optimize Branches\", optimize_branches(function), function);\n optimized |= debug(\"Optimize Concat\", optimize_concat(function, pool), function);\n optimized |= debug(\"Remove dead basic block\", remove_dead_basic_blocks(function), function);\n optimized |= debug(\"Remove needless jumps\", remove_needless_jumps(function), function);\n } while (optimized);\n\n \/\/Remove variables that are not used after optimizations\n clean_variables(function);\n}\n\nvoid basic_optimize_function(std::shared_ptr function){\n if(option_defined(\"dev\")){\n std::cout << \"Start basic optimizations on \" << function->getName() << std::endl;\n\n print(function);\n }\n\n debug(\"Constant folding\", apply_to_all(function), function);\n \n \/*\/\/Liveness debugging\n mtac::LiveVariableAnalysisProblem problem;\n auto results = mtac::data_flow(function, problem);\n\n for(auto& block : function->getBasicBlocks()){\n auto it = block->statements.begin();\n auto end = block->statements.end();\n\n while(it != end){\n auto statement = *it;\n\n mtac::Printer printer;\n printer.printStatement(statement);\n std::cout << \"OUT{\";\n for(auto& var : results->OUT_S[statement].values()){\n std::cout << var->name() << \", \";\n }\n std::cout << \"}\" << std::endl;\n std::cout << \"IN{\";\n for(auto& var : results->IN_S[statement].values()){\n std::cout << var->name() << \", \";\n }\n std::cout << \"}\" << std::endl;\n\n ++it;\n }\n }*\/\n}\n\nvoid optimize_all_functions(std::shared_ptr program, std::shared_ptr string_pool){\n PerfsTimer timer(\"Whole optimizations\");\n\n auto& functions = program->functions;\n\n \/\/Find a better heuristic to configure the number of threads\n std::size_t threads = std::min(functions.size(), static_cast(MAX_THREADS));\n\n if(option_defined(\"dev\")){\n threads = 1;\n }\n\n std::vector pool;\n for(std::size_t tid = 0; tid < threads; ++tid){\n pool.push_back(std::thread([tid, threads, &string_pool, &functions](){\n std::size_t i = tid;\n\n while(i < functions.size()){\n optimize_function(functions[i], string_pool); \n\n i += threads;\n }\n }));\n }\n\n \/\/Wait for all the threads to finish\n std::for_each(pool.begin(), pool.end(), [](std::thread& thread){thread.join();});\n}\n\nvoid mtac::Optimizer::optimize(std::shared_ptr program, std::shared_ptr string_pool) const {\n bool optimized = false;\n\n do{\n optimize_all_functions(program, string_pool);\n\n optimized = mtac::remove_empty_functions(program);\n } while(optimized);\n}\n\nvoid mtac::Optimizer::basic_optimize(std::shared_ptr program, std::shared_ptr \/*string_pool*\/) const {\n PerfsTimer timer(\"Whole basic optimizations\");\n\n auto& functions = program->functions;\n\n \/\/Find a better heuristic to configure the number of threads\n std::size_t threads = std::min(functions.size(), static_cast(MAX_THREADS));\n\n if(option_defined(\"dev\")){\n threads = 1;\n }\n\n std::vector pool;\n for(std::size_t tid = 0; tid < threads; ++tid){\n pool.push_back(std::thread([tid, threads, &functions](){\n std::size_t i = tid;\n\n while(i < functions.size()){\n basic_optimize_function(functions[i]); \n\n i += threads;\n }\n }));\n }\n\n \/\/Wait for all the threads to finish\n std::for_each(pool.begin(), pool.end(), [](std::thread& thread){thread.join();});\n}\nCleanup\/\/=======================================================================\n\/\/ Copyright Baptiste Wicht 2011.\n\/\/ Distributed under the Boost Software License, Version 1.0.\n\/\/ (See accompanying file LICENSE_1_0.txt or copy at\n\/\/ http:\/\/www.boost.org\/LICENSE_1_0.txt)\n\/\/=======================================================================\n\n#include \n#include \n\n#include \"VisitorUtils.hpp\"\n#include \"Options.hpp\"\n#include \"PerfsTimer.hpp\"\n\n#include \"mtac\/Pass.hpp\"\n#include \"mtac\/Optimizer.hpp\"\n#include \"mtac\/Program.hpp\"\n#include \"mtac\/Printer.hpp\"\n\n\/\/The custom optimizations\n#include \"mtac\/VariableCleaner.hpp\"\n#include \"mtac\/RemoveEmptyFunctions.hpp\"\n#include \"mtac\/DeadCodeElimination.hpp\"\n#include \"mtac\/BasicBlockOptimizations.hpp\"\n#include \"mtac\/BranchOptimizations.hpp\"\n#include \"mtac\/ConcatReduction.hpp\"\n\n\/\/The optimization visitors\n#include \"mtac\/ArithmeticIdentities.hpp\"\n#include \"mtac\/ReduceInStrength.hpp\"\n#include \"mtac\/ConstantFolding.hpp\"\n#include \"mtac\/RemoveAssign.hpp\"\n#include \"mtac\/RemoveMultipleAssign.hpp\"\n#include \"mtac\/MathPropagation.hpp\"\n\n\/\/The data-flow problems\n#include \"mtac\/GlobalOptimizations.hpp\"\n#include \"mtac\/ConstantPropagationProblem.hpp\"\n#include \"mtac\/OffsetConstantPropagationProblem.hpp\"\n#include \"mtac\/CommonSubexpressionElimination.hpp\"\n\nusing namespace eddic;\n\nnamespace {\n\nstatic const unsigned int MAX_THREADS = 2;\nstatic const bool DebugPerf = false;\n\ntemplate\nbool apply_to_all(std::shared_ptr function){\n Visitor visitor;\n\n for(auto& block : function->getBasicBlocks()){\n visit_each(visitor, block->statements);\n }\n\n return visitor.optimized;\n}\n\ntemplate\nbool apply_to_basic_blocks_two_pass(std::shared_ptr function){\n bool optimized = false;\n\n for(auto& block : function->getBasicBlocks()){\n Visitor visitor;\n visitor.pass = mtac::Pass::DATA_MINING;\n\n visit_each(visitor, block->statements);\n\n visitor.pass = mtac::Pass::OPTIMIZE;\n\n visit_each(visitor, block->statements);\n\n optimized |= visitor.optimized;\n }\n\n return optimized;\n}\n\ntemplate\nbool data_flow_optimization(std::shared_ptr function){\n bool optimized = false;\n\n Problem problem;\n\n auto results = mtac::data_flow(function, problem);\n\n \/\/Once the data-flow problem is fixed, statements can be optimized\n for(auto& block : function->getBasicBlocks()){\n for(auto& statement : block->statements){\n optimized |= problem.optimize(statement, results);\n }\n }\n\n return optimized;\n}\n\nbool debug(const std::string& name, bool b, std::shared_ptr function){\n if(option_defined(\"dev\")){\n if(b){\n std::cout << \"optimization \" << name << \" returned true\" << std::endl;\n\n \/\/Print the function\n print(function);\n } else {\n std::cout << \"optimization \" << name << \" returned false\" << std::endl;\n }\n }\n\n return b;\n}\n\n}\n\nvoid optimize_function(std::shared_ptr function, std::shared_ptr pool){\n if(option_defined(\"dev\")){\n std::cout << \"Start optimizations on \" << function->getName() << std::endl;\n\n print(function);\n }\n\n bool optimized;\n do {\n optimized = false;\n\n optimized |= debug(\"Aritmetic Identities\", apply_to_all(function), function);\n optimized |= debug(\"Reduce in Strength\", apply_to_all(function), function);\n optimized |= debug(\"Constant folding\", apply_to_all(function), function);\n\n optimized |= debug(\"Constant propagation\", data_flow_optimization(function), function);\n optimized |= debug(\"Offset Constant Propagation\", data_flow_optimization(function), function);\n\n \/\/If there was optimizations here, better to try again before perfoming common subexpression\n if(optimized){\n continue;\n }\n\n optimized |= debug(\"Common Subexpression Elimination\", data_flow_optimization(function), function);\n\n optimized |= debug(\"Math Propagation\", apply_to_basic_blocks_two_pass(function), function);\n \n optimized |= debug(\"Dead-Code Elimination\", mtac::dead_code_elimination(function), function);\n\n optimized |= debug(\"Optimize Branches\", optimize_branches(function), function);\n optimized |= debug(\"Optimize Concat\", optimize_concat(function, pool), function);\n optimized |= debug(\"Remove dead basic block\", remove_dead_basic_blocks(function), function);\n optimized |= debug(\"Remove needless jumps\", remove_needless_jumps(function), function);\n } while (optimized);\n\n \/\/Remove variables that are not used after optimizations\n clean_variables(function);\n}\n\nvoid basic_optimize_function(std::shared_ptr function){\n if(option_defined(\"dev\")){\n std::cout << \"Start basic optimizations on \" << function->getName() << std::endl;\n\n print(function);\n }\n\n debug(\"Constant folding\", apply_to_all(function), function);\n \n \/*\/\/Liveness debugging\n mtac::LiveVariableAnalysisProblem problem;\n auto results = mtac::data_flow(function, problem);\n\n for(auto& block : function->getBasicBlocks()){\n auto it = block->statements.begin();\n auto end = block->statements.end();\n\n while(it != end){\n auto statement = *it;\n\n mtac::Printer printer;\n printer.printStatement(statement);\n std::cout << \"OUT{\";\n for(auto& var : results->OUT_S[statement].values()){\n std::cout << var->name() << \", \";\n }\n std::cout << \"}\" << std::endl;\n std::cout << \"IN{\";\n for(auto& var : results->IN_S[statement].values()){\n std::cout << var->name() << \", \";\n }\n std::cout << \"}\" << std::endl;\n\n ++it;\n }\n }*\/\n}\n\nvoid optimize_all_functions(std::shared_ptr program, std::shared_ptr string_pool){\n PerfsTimer timer(\"Whole optimizations\");\n\n auto& functions = program->functions;\n\n \/\/Find a better heuristic to configure the number of threads\n std::size_t threads = std::min(functions.size(), static_cast(MAX_THREADS));\n\n if(option_defined(\"dev\")){\n threads = 1;\n }\n\n std::vector pool;\n for(std::size_t tid = 0; tid < threads; ++tid){\n pool.push_back(std::thread([tid, threads, &string_pool, &functions](){\n std::size_t i = tid;\n\n while(i < functions.size()){\n optimize_function(functions[i], string_pool); \n\n i += threads;\n }\n }));\n }\n\n \/\/Wait for all the threads to finish\n std::for_each(pool.begin(), pool.end(), [](std::thread& thread){thread.join();});\n}\n\nvoid mtac::Optimizer::optimize(std::shared_ptr program, std::shared_ptr string_pool) const {\n bool optimized = false;\n\n do{\n optimize_all_functions(program, string_pool);\n\n optimized = mtac::remove_empty_functions(program);\n } while(optimized);\n}\n\nvoid mtac::Optimizer::basic_optimize(std::shared_ptr program, std::shared_ptr \/*string_pool*\/) const {\n PerfsTimer timer(\"Whole basic optimizations\");\n\n auto& functions = program->functions;\n\n \/\/Find a better heuristic to configure the number of threads\n std::size_t threads = std::min(functions.size(), static_cast(MAX_THREADS));\n\n if(option_defined(\"dev\")){\n threads = 1;\n }\n\n std::vector pool;\n for(std::size_t tid = 0; tid < threads; ++tid){\n pool.push_back(std::thread([tid, threads, &functions](){\n std::size_t i = tid;\n\n while(i < functions.size()){\n basic_optimize_function(functions[i]); \n\n i += threads;\n }\n }));\n }\n\n \/\/Wait for all the threads to finish\n std::for_each(pool.begin(), pool.end(), [](std::thread& thread){thread.join();});\n}\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \n\n\/\/For stringifying preprocessor values\n#define xstr(s) str(s)\n#define str(s) #s\n#define concat(first, second) first second\n\nint l_ink(lua_State *L) {\n\tint x;\n\tif (lua_gettop(L) >= 0) {\n\t\tx = (int)lua_tonumber(L, -1);\n\t\tlua_pushnumber(L, x + 1);\n\t}\n\treturn 1;\n}\n\nstruct Dog\n{\n\tint age;\n\tint height;\n\tconst char* breed;\n};\n\n\nstatic int newDog(lua_State* l) {\n\tDog* bella = (Dog*)lua_newuserdata(l, sizeof(Dog));\n\tbella->age = 12;\n\tbella->height = 1;\n\n\treturn 1;\n}\n\nstatic int DogGetAge(lua_State* l) {\n\tDog *bella = (Dog*)lua_touserdata(l, 1);\n\tluaL_argcheck(l, bella != NULL, 1, \"Dog expected\");\n\tlua_pushinteger(l, bella->age);\n\treturn 1;\n}\n\nstatic const struct luaL_Reg doglib[] = {\n\t{\"new\", newDog},\n\t{\"age\", DogGetAge},\n\t{NULL, NULL}\n\n};\n\nstatic void PrintLuaTypeAt(lua_State* l, const int i) {\n\n\tint type = lua_type(l, i);\n\tprintf(\"Stack index %d\\t\\t\", lua_absindex(l, i));\n\tswitch (type) {\n\n\tcase LUA_TNIL:\n\t\tprintf(\"Value is nil.\\n\");\n\t\tbreak;\n\tcase LUA_TBOOLEAN:\n\t\tprintf(\"Value is boolean: %d\\n\", (int)lua_toboolean(l, i));\n\t\tbreak;\n\tcase LUA_TLIGHTUSERDATA:\n\t\tprintf(\"Value is light user data (just a pointer)\\n\");\n\t\tbreak;\n\tcase LUA_TNUMBER:\n\t\tprintf(\"Value is a number of: %d\\n\", (int)lua_tonumber(l, i));\n\t\tbreak;\n\tcase LUA_TSTRING:\n\t\tprintf(\"Value is a string of: %s\\n\", lua_tostring(l, i));\n\t\tbreak;\n\tcase LUA_TTABLE:\n\t\tprintf(\"Value is a table.\\n\");\n\t\tbreak;\n\tcase LUA_TFUNCTION:\n\t\tprintf(\"Value is a function.\\n\");\n\t\tbreak;\n\tcase LUA_TUSERDATA:\n\t\tprintf(\"Value is userdata\\n\");\n\t\tbreak;\n\tdefault:\n\t\tprintf(\"Value is not printable\\n\");\n\t\tbreak;\n\t}\n}\n\n\nstatic void PrintTableAt(lua_State* l, int index){\n\tint tableIndex = lua_absindex(l, index);\n\tif (lua_istable(l, tableIndex) == 1) {\n\t\tlua_pushnil(l); \/\/ pushes the first key (which is nil for whatever reason) onto the stack\n\t\twhile (lua_next(l, tableIndex) != 0) { \/\/ key(-1) is replaced by the next key(-1) in table(tableIndex)\n\t\t\tPrintLuaTypeAt(l, -2);\n\t\t\tPrintLuaTypeAt(l, -1);\n\t\t\tlua_pop(l, 1); \/\/ remove value(-1), now key on top at(-1)\n\t\t\t\/\/leaves key(-1) at top for next interation\n\t\t}\n\t}\n\telse {\n\t\tfprintf(stderr, \"Object at %d on stack is not a table\\n\", tableIndex);\n\t}\n\n}\nstatic void PrintTable(lua_State* l) {\n\tPrintTableAt(l, -1);\n}\n\n\/\/From Programming in Lua 3rd Edition\nstatic void stackDump (lua_State *L) {\n\tint i;\n\tint top = lua_gettop(L); \/* depth of the stack *\/\n\tfor (i = 1; i <= top; i++) { \/* repeat for each level *\/\n\t\tint t = lua_type(L, i);\n\t\tswitch (t) {\n\t\t\tcase LUA_TSTRING: { \/* strings *\/\n\t\t\t\t\t\t\t\t printf(\"'%s'\", lua_tostring(L, i));\n\t\t\t\t\t\t\t\t break;\n\t\t\t\t\t\t\t }\n\t\t\tcase LUA_TBOOLEAN: { \/* booleans *\/\n\t\t\t\t\t\t\t\t printf(lua_toboolean(L, i) ? \"true\" : \"false\");\n\t\t\t\t\t\t\t\t break;\n\t\t\t\t\t\t\t }\n\t\t\tcase LUA_TNUMBER: { \/* numbers *\/\n\t\t\t\t\t\t\t\t printf(\"%g\", lua_tonumber(L, i));\n\t\t\t\t\t\t\t\t break;\n\t\t\t\t\t\t\t }\n\t\t\tdefault: { \/* other values *\/\n\t\t\t\t\t\t printf(\"%s\", lua_typename(L, t));\n\t\t\t\t\t\t break;\n\t\t\t\t\t }\n\t\t}\n\t\tprintf(\" \"); \/* put a separator *\/\n\t}\n\tprintf(\"\\n\"); \/* end the listing *\/\n}\n\nstatic void PrintGlobalTable(lua_State* l) {\n\tlua_pushglobaltable(l);\n\tprintf(\"Global table\\n\");\n\tPrintTable(l);\n\tlua_pop(l, 1);\n}\n\nstatic void CopyTableAtTo(lua_State* l, int t, int newTableIndex){\n\tt = lua_absindex(l, t);\n\tnewTableIndex = lua_absindex(l, newTableIndex);\n\tprintf(\"t is %d, newTableIndex is %d\\n\", t, newTableIndex);\n\tlua_pushnil(l);\n\twhile(lua_next(l, t) != 0){\n\t\tlua_pushvalue(l,-2); \/\/copies key to top so lua_next is happy\n\t\t\/\/swaps value and key on top of stack.\n\t\t\/\/Above function adds a value onto stack so -2 is now value\n\t\tlua_insert(l,-2); \n\t\t\/\/Set the value in the new stack. Consuming the top value and key\n\t\tlua_settable(l,newTableIndex);\n\n\t}\n\n}\n\nvoid LuaHook(lua_State *l, lua_Debug *ar) {\n\tif(lua_getstack(l,0,ar) == 0){\n\t\tfprintf(stderr, \"%s\\n\", \"Error calling get stack\");\n\t}\n\tif(lua_getinfo(l, \"Snlf\", ar) == 0){\n\t\tfprintf(stderr, \"%s\\n\", \"Error calling get info\");\n\t}else{\n\t\tprintf(\"Event %d\\tLine %d\\t\\t\",ar->event, ar->currentline);\n\t\tif(strcmp(ar->namewhat, \"global\") == 0){\n\t\t\tprintf(\"Type: %s\\tName %s\",ar->namewhat,ar->name);\n\t\t}\n\t\tprintf(\"%s\\n\",\"\");\n\t}\n\n}\n\nint main(int argc, char* argv[]) {\n\tlua_State *l;\n\tl = luaL_newstate();\n\tluaL_openlibs(l);\n\t\/\/PrintGlobalTable(l);\n\tluaL_newlib(l, doglib);\n\tlua_setglobal(l, \"dog\");\n\n\tlua_Debug ar;\n\n\tlua_newtable(l);\n\tlua_pushglobaltable(l);\n\tint globalTableIndex = lua_absindex(l,-2);\n\tCopyTableAtTo(l, -1, -2);\n\n\t\/\/lua_sethook(l, LuaHook, LUA_MASKLINE | LUA_MASKCALL | LUA_MASKRET, 0);\n\/\/\tlua_sethook(l, LuaHook, LUA_MASKLINE | LUA_MASKCALL, 0);\n\tif (luaL_loadfile(l, concat(xstr(SCRIPTS_DIR), \"\/test.lua\")) != 0) {\n\t\tfprintf(stderr, \"lua couldn't parse '%s': %s.\\n\", \"test.lua\", lua_tostring(l, -1));\n\t}\n\telse {\n\t\tlua_pcall(l, 0, 0, 0);\n\t\tlua_getglobal(l, \"uupdate\");\n\t\tstackDump(l);\n\t\tif (lua_pcall(l, 0, 0, 0) != 0) {\n\t\t\tfprintf(stderr, \"lua couldn't call update in '%s': %s.\\n\", \"test.lua\", lua_tostring(l, -1));\n\t\t}\n\t}\n\n\tint i = 0;\n\tchar in = 'e';\/\/(char)getchar();\n\n\twhile (in != 'e') {\n\n\t\tfor (i = 0; i < 1; i++) {\n\n\t\t\tint indexStart = lua_gettop(l);\n\t\t\t\/\/lua_rawseti(l, LUA_REGISTRYINDEX, LUA_RIDX_GLOBALS);\n\t\t\tif (luaL_loadfile(l, concat(xstr(SCRIPTS_DIR), \"\/test.lua\")) != 0) {\n\t\t\t\tfprintf(stderr, \"lua couldn't parse '%s': %s.\\n\", \"test.lua\", lua_tostring(l, -1));\n\t\t\t}\n\t\t\telse {\n\t\t\t\tPrintTableAt(l, globalTableIndex);\n\t\t\t\tlua_pcall(l, 0, 0, 0);\n\t\t\t\tlua_getglobal(l, \"update\");\n\t\t\t\tif (lua_pcall(l, 0, 0, 0) != 0) {\n\t\t\t\t\tfprintf(stderr, \"lua couldn't call update in '%s': %s.\\n\", \"test.lua\", lua_tostring(l, -1));\n\t\t\t\t}\n\t\t\t\tlua_getglobal(l, \"createDog\");\n\t\t\t\tif (lua_pcall(l, 0, 0, 0) != 0) {\n\t\t\t\t\tfprintf(stderr, \"lua couldn't call createDog in '%s': %s.\\n\", \"test.lua\", lua_tostring(l, -1));\n\t\t\t\t}\n\t\t\t\tlua_pop(l, lua_gettop(l) - indexStart);\n\t\t\t}\n\t\t\t\/*\n\t\t\tif (luaL_loadfile(l, concat(xstr(SCRIPTS_DIR), \"\/hello.lua\")) != 0) {\n\t\t\t\tfprintf(stderr, \"lua couldn't parse '%s': %s.\\n\", \"hello.lua\", lua_tostring(l, -1));\n\t\t\t}\n\t\t\telse {\n\t\t\t\tlua_pcall(l, 0, 0, 0);\n\t\t\t\tlua_getglobal(l, \"update\");\n\t\t\t\tif (lua_pcall(l, 0, 0, 0) != 0) {\n\t\t\t\t\tfprintf(stderr, \"lua couldn't call update in '%s': %s.\\n\", \"hello.lua\", lua_tostring(l, -1));\n\t\t\t\t}\n\t\t\t\tlua_pop(l, lua_gettop(l));\n\t\t\t}\n\t\t\t\/\/PrintGlobalTable(l);\n\t\t\t\/\/calls the loaded code\n\t\t\tlua_pcall(l, 0, 1, 0);\n\t\t\tif(lua_isnumber(l, lua_gettop(l)) != 0){\n\t\t\t\tlua_Integer returnCode = lua_tointeger(l, lua_gettop(l));\n\t\t\t\tprintf(\"Return code %d\\n\", (int)returnCode);\n\t\t\t}\n\t\t\tlua_getglobal(l, \"add\");\n\t\t\tlua_pushnumber(l, 10);\n\t\t\tlua_pushnumber(l, 20);\n\t\t\tif(lua_pcall(l,2,1,0) != 0){\n\t\t\t\tfprintf(stderr, \"Couldn't call add error:\\t%s\\n\", lua_tostring(l, -1));\n\t\t\t}else{\n\t\t\t\tint result = (int)lua_tonumber(l, -1);\n\t\t\t\tprintf(\"Add result of 10 + 20 = %d\\n\", result);\n\t\t\t\t\/\/clear the result\n\t\t\t\tlua_pop(l,1);\n\t\t\t}\n\t\t\tlua_getglobal(l, \"createDog\");\n\t\t\tif (lua_pcall(l, 0, 0, 0) != 0) {\n\t\t\t\tfprintf(stderr, \"Couldn't call function error:\\t%s\\n\", lua_tostring(l, -1));\n\t\t\t}\n\t\t\t*\/\n\n\t\t}\n\t\tin = (char)getchar();\n\t}\n\treturn 0;\n}\nAdded metatable\/OO lua access example#include \n#include \n#include \n#include \n#include \n#include \n\n\/\/For stringifying preprocessor values\n#define xstr(s) str(s)\n#define str(s) #s\n#define concat(first, second) first second\n\nint l_ink(lua_State *L) {\n\tint x;\n\tif (lua_gettop(L) >= 0) {\n\t\tx = (int)lua_tonumber(L, -1);\n\t\tlua_pushnumber(L, x + 1);\n\t}\n\treturn 1;\n}\n\nstruct Dog\n{\n\tint age;\n\tint height;\n\tconst char* breed;\n};\n\n\nstatic int newDog(lua_State* l) {\n\tDog* bella = (Dog*)lua_newuserdata(l, sizeof(Dog));\n\tluaL_getmetatable(l, \"Dog\");\n\t \/\/ assert(lua_istable(L, -1)) if you're paranoid\n\tlua_setmetatable(l, -2);\n\tsrand((unsigned int)time(NULL));\n\tbella->age = rand() % 100;\n\tbella->height = 1;\n\n\treturn 1;\n}\n\nstatic int DogGetAge(lua_State* l) {\n\tDog *bella = (Dog*)lua_touserdata(l, 1);\n\tluaL_argcheck(l, bella != NULL, 1, \"Dog expected\");\n\tlua_pushinteger(l, bella->age);\n\treturn 1;\n}\n\nstatic const struct luaL_Reg doglib[] = {\n\t{\"new\", newDog},\n\t{NULL, NULL}\n\n};\nstatic const struct luaL_Reg doglibMember[] = {\n\t{\"age\", DogGetAge},\n\t{NULL, NULL}\n\n};\n\nstatic void PrintLuaTypeAt(lua_State* l, const int i) {\n\n\tint type = lua_type(l, i);\n\tprintf(\"Stack index %d\\t\\t\", lua_absindex(l, i));\n\tswitch (type) {\n\n\tcase LUA_TNIL:\n\t\tprintf(\"Value is nil.\\n\");\n\t\tbreak;\n\tcase LUA_TBOOLEAN:\n\t\tprintf(\"Value is boolean: %d\\n\", (int)lua_toboolean(l, i));\n\t\tbreak;\n\tcase LUA_TLIGHTUSERDATA:\n\t\tprintf(\"Value is light user data (just a pointer)\\n\");\n\t\tbreak;\n\tcase LUA_TNUMBER:\n\t\tprintf(\"Value is a number of: %d\\n\", (int)lua_tonumber(l, i));\n\t\tbreak;\n\tcase LUA_TSTRING:\n\t\tprintf(\"Value is a string of: %s\\n\", lua_tostring(l, i));\n\t\tbreak;\n\tcase LUA_TTABLE:\n\t\tprintf(\"Value is a table.\\n\");\n\t\tbreak;\n\tcase LUA_TFUNCTION:\n\t\tprintf(\"Value is a function.\\n\");\n\t\tbreak;\n\tcase LUA_TUSERDATA:\n\t\tprintf(\"Value is userdata\\n\");\n\t\tbreak;\n\tdefault:\n\t\tprintf(\"Value is not printable\\n\");\n\t\tbreak;\n\t}\n}\n\n\nstatic void PrintTableAt(lua_State* l, int index){\n\tint tableIndex = lua_absindex(l, index);\n\tif (lua_istable(l, tableIndex) == 1) {\n\t\tlua_pushnil(l); \/\/ pushes the first key (which is nil for whatever reason) onto the stack\n\t\twhile (lua_next(l, tableIndex) != 0) { \/\/ key(-1) is replaced by the next key(-1) in table(tableIndex)\n\t\t\tPrintLuaTypeAt(l, -2);\n\t\t\tPrintLuaTypeAt(l, -1);\n\t\t\tlua_pop(l, 1); \/\/ remove value(-1), now key on top at(-1)\n\t\t\t\/\/leaves key(-1) at top for next interation\n\t\t}\n\t}\n\telse {\n\t\tfprintf(stderr, \"Object at %d on stack is not a table\\n\", tableIndex);\n\t}\n\n}\nstatic void PrintTable(lua_State* l) {\n\tPrintTableAt(l, -1);\n}\n\n\/\/From Programming in Lua 3rd Edition\nstatic void stackDump (lua_State *L) {\n\tint i;\n\tint top = lua_gettop(L); \/* depth of the stack *\/\n\tfor (i = 1; i <= top; i++) { \/* repeat for each level *\/\n\t\tint t = lua_type(L, i);\n\t\tswitch (t) {\n\t\t\tcase LUA_TSTRING: { \/* strings *\/\n\t\t\t\t\t\t\t\t printf(\"'%s'\", lua_tostring(L, i));\n\t\t\t\t\t\t\t\t break;\n\t\t\t\t\t\t\t }\n\t\t\tcase LUA_TBOOLEAN: { \/* booleans *\/\n\t\t\t\t\t\t\t\t printf(lua_toboolean(L, i) ? \"true\" : \"false\");\n\t\t\t\t\t\t\t\t break;\n\t\t\t\t\t\t\t }\n\t\t\tcase LUA_TNUMBER: { \/* numbers *\/\n\t\t\t\t\t\t\t\t printf(\"%g\", lua_tonumber(L, i));\n\t\t\t\t\t\t\t\t break;\n\t\t\t\t\t\t\t }\n\t\t\tdefault: { \/* other values *\/\n\t\t\t\t\t\t printf(\"%s\", lua_typename(L, t));\n\t\t\t\t\t\t break;\n\t\t\t\t\t }\n\t\t}\n\t\tprintf(\" \"); \/* put a separator *\/\n\t}\n\tprintf(\"\\n\"); \/* end the listing *\/\n}\n\nstatic void PrintGlobalTable(lua_State* l) {\n\tlua_pushglobaltable(l);\n\tprintf(\"Global table\\n\");\n\tPrintTable(l);\n\tlua_pop(l, 1);\n}\n\nstatic void CopyTableAtTo(lua_State* l, int t, int newTableIndex){\n\tt = lua_absindex(l, t);\n\tnewTableIndex = lua_absindex(l, newTableIndex);\n\tprintf(\"t is %d, newTableIndex is %d\\n\", t, newTableIndex);\n\tlua_pushnil(l);\n\twhile(lua_next(l, t) != 0){\n\t\tlua_pushvalue(l,-2); \/\/copies key to top so lua_next is happy\n\t\t\/\/swaps value and key on top of stack.\n\t\t\/\/Above function adds a value onto stack so -2 is now value\n\t\tlua_insert(l,-2); \n\t\t\/\/Set the value in the new stack. Consuming the top value and key\n\t\tlua_settable(l,newTableIndex);\n\n\t}\n\n}\n\nvoid LuaHook(lua_State *l, lua_Debug *ar) {\n\tif(lua_getstack(l,0,ar) == 0){\n\t\tfprintf(stderr, \"%s\\n\", \"Error calling get stack\");\n\t}\n\tif(lua_getinfo(l, \"Snlf\", ar) == 0){\n\t\tfprintf(stderr, \"%s\\n\", \"Error calling get info\");\n\t}else{\n\t\tprintf(\"Event %d\\tLine %d\\t\\t\",ar->event, ar->currentline);\n\t\tif(strcmp(ar->namewhat, \"global\") == 0){\n\t\t\tprintf(\"Type: %s\\tName %s\",ar->namewhat,ar->name);\n\t\t}\n\t\tprintf(\"%s\\n\",\"\");\n\t}\n\n}\n\nint main(int argc, char* argv[]) {\n\tlua_State *l;\n\tl = luaL_newstate();\n\tluaL_openlibs(l);\n\t\/\/PrintGlobalTable(l);\n\t\/\/Creates a metatable and registers in Lua's registery\n\tluaL_newmetatable(l, \"Dog\");\n\t\/\/Sets functions against the meta table\n\tluaL_setfuncs(l, doglibMember, 0);\n\t\/\/Adds __index \tto the meta table so we can use functions against\n\t\/*\n\t * Lua uses : syntax which causes an index lookup\n\t * It uses the following function name to look in the meta table\n\t * By adding __index we ensure that it always looks at its self\n\t *\n\t * I.E __index becomes the metatable itself which contains our functions\n\t*\/\n\tlua_setfield(l, -1, \"__index\");\n\tluaL_getmetatable(l, \"Dog\");\n\tPrintTable(l);\n\tluaL_newlib(l, doglib);\n\tlua_setglobal(l, \"dog\");\n\n\tlua_Debug ar;\n\n\tlua_newtable(l);\n\tlua_pushglobaltable(l);\n\tint globalTableIndex = lua_absindex(l,-2);\n\tCopyTableAtTo(l, -1, -2);\n\n\t\/\/lua_sethook(l, LuaHook, LUA_MASKLINE | LUA_MASKCALL | LUA_MASKRET, 0);\n\/\/\tlua_sethook(l, LuaHook, LUA_MASKLINE | LUA_MASKCALL, 0);\n\tif (luaL_loadfile(l, concat(xstr(SCRIPTS_DIR), \"\/test.lua\")) != 0) {\n\t\tfprintf(stderr, \"lua couldn't parse '%s': %s.\\n\", \"test.lua\", lua_tostring(l, -1));\n\t}\n\telse {\n\t\tlua_pcall(l, 0, 0, 0);\n\t\tlua_getglobal(l, \"update\");\n\t\tif (lua_pcall(l, 0, 0, 0) != 0) {\n\t\t\tfprintf(stderr, \"lua couldn't call update in '%s': %s.\\n\", \"test.lua\", lua_tostring(l, -1));\n\t\t}\n\t}\n\n\tint i = 0;\n\tchar in = 'e';\/\/(char)getchar();\n\n\twhile (in != 'e') {\n\n\t\tfor (i = 0; i < 1; i++) {\n\n\t\t\tint indexStart = lua_gettop(l);\n\t\t\t\/\/lua_rawseti(l, LUA_REGISTRYINDEX, LUA_RIDX_GLOBALS);\n\t\t\tif (luaL_loadfile(l, concat(xstr(SCRIPTS_DIR), \"\/test.lua\")) != 0) {\n\t\t\t\tfprintf(stderr, \"lua couldn't parse '%s': %s.\\n\", \"test.lua\", lua_tostring(l, -1));\n\t\t\t}\n\t\t\telse {\n\t\t\t\tPrintTableAt(l, globalTableIndex);\n\t\t\t\tlua_pcall(l, 0, 0, 0);\n\t\t\t\tlua_getglobal(l, \"update\");\n\t\t\t\tif (lua_pcall(l, 0, 0, 0) != 0) {\n\t\t\t\t\tfprintf(stderr, \"lua couldn't call update in '%s': %s.\\n\", \"test.lua\", lua_tostring(l, -1));\n\t\t\t\t}\n\t\t\t\tlua_getglobal(l, \"createDog\");\n\t\t\t\tif (lua_pcall(l, 0, 0, 0) != 0) {\n\t\t\t\t\tfprintf(stderr, \"lua couldn't call createDog in '%s': %s.\\n\", \"test.lua\", lua_tostring(l, -1));\n\t\t\t\t}\n\t\t\t\tlua_pop(l, lua_gettop(l) - indexStart);\n\t\t\t}\n\t\t\t\/*\n\t\t\tif (luaL_loadfile(l, concat(xstr(SCRIPTS_DIR), \"\/hello.lua\")) != 0) {\n\t\t\t\tfprintf(stderr, \"lua couldn't parse '%s': %s.\\n\", \"hello.lua\", lua_tostring(l, -1));\n\t\t\t}\n\t\t\telse {\n\t\t\t\tlua_pcall(l, 0, 0, 0);\n\t\t\t\tlua_getglobal(l, \"update\");\n\t\t\t\tif (lua_pcall(l, 0, 0, 0) != 0) {\n\t\t\t\t\tfprintf(stderr, \"lua couldn't call update in '%s': %s.\\n\", \"hello.lua\", lua_tostring(l, -1));\n\t\t\t\t}\n\t\t\t\tlua_pop(l, lua_gettop(l));\n\t\t\t}\n\t\t\t\/\/PrintGlobalTable(l);\n\t\t\t\/\/calls the loaded code\n\t\t\tlua_pcall(l, 0, 1, 0);\n\t\t\tif(lua_isnumber(l, lua_gettop(l)) != 0){\n\t\t\t\tlua_Integer returnCode = lua_tointeger(l, lua_gettop(l));\n\t\t\t\tprintf(\"Return code %d\\n\", (int)returnCode);\n\t\t\t}\n\t\t\tlua_getglobal(l, \"add\");\n\t\t\tlua_pushnumber(l, 10);\n\t\t\tlua_pushnumber(l, 20);\n\t\t\tif(lua_pcall(l,2,1,0) != 0){\n\t\t\t\tfprintf(stderr, \"Couldn't call add error:\\t%s\\n\", lua_tostring(l, -1));\n\t\t\t}else{\n\t\t\t\tint result = (int)lua_tonumber(l, -1);\n\t\t\t\tprintf(\"Add result of 10 + 20 = %d\\n\", result);\n\t\t\t\t\/\/clear the result\n\t\t\t\tlua_pop(l,1);\n\t\t\t}\n\t\t\tlua_getglobal(l, \"createDog\");\n\t\t\tif (lua_pcall(l, 0, 0, 0) != 0) {\n\t\t\t\tfprintf(stderr, \"Couldn't call function error:\\t%s\\n\", lua_tostring(l, -1));\n\t\t\t}\n\t\t\t*\/\n\n\t\t}\n\t\tin = (char)getchar();\n\t}\n\treturn 0;\n}\n<|endoftext|>"} {"text":"#include \n#include \n#include \n\n#ifdef Q_OS_ANDROID\n#include \"zmc\/NotificationClient.h\"\n#include \"zmc\/Notification.h\"\n#include \"zmc\/android\/AndroidUtils.h\"\n#endif \/\/ Q_OS_ANDROID\n#include \"zmc\/ScreenHelper.h\"\n#include \"zmc\/QMLRefresh.h\"\n#include \"zmc\/Macros.h\"\n\nint main(int argc, char *argv[])\n{\n QGuiApplication app(argc, argv);\n\n QQmlApplicationEngine engine;\n\n zmc::ScreenHelper screenHelper;\n engine.rootContext()->setContextProperty(\"SH\", &screenHelper);\n\n#ifdef Q_OS_ANDROID\n qmlRegisterType(\"NotificationClient\", 1, 0, \"NotificationClient\");\n qmlRegisterType(\"NotificationClient\", 1, 0, \"Notification\");\n qmlRegisterType(\"qutils.AndroidUtils\", 1, 0, \"AndroidUtils\");\n#endif \/\/ Q_OS_ANDROID\n\n#if defined(QT_DEBUG) && defined(Q_OS_DESKTOP)\n zmc::QMLRefresh manager(&engine);\n manager.setMainQMLFile(\"file:\/\/\/E:\/Development\/SourceTree\/GitHub\/qutils\/qutils_demo\/qml\/main.qml\");\n engine.rootContext()->setContextProperty(\"QM\", &manager);\n engine.rootContext()->setContextProperty(\"QML_DEBUG\", QVariant::fromValue(true));\n engine.rootContext()->setContextProperty(\"Q_OS_DESKTOP\", QVariant::fromValue(1));\n engine.load(QUrl(\"file:\/\/\/E:\/Development\/SourceTree\/GitHub\/qutils\/qutils_demo\/qml\/main.qml\"));\n#else\n engine.rootContext()->setContextProperty(\"QM\", nullptr);\n engine.rootContext()->setContextProperty(\"QML_DEBUG\", QVariant::fromValue(false));\n engine.rootContext()->setContextProperty(\"Q_OS_DESKTOP\", QVariant::fromValue(0));\n engine.load(QUrl(QStringLiteral(\"qrc:\/qml\/main.qml\")));\n#endif \/\/ QT_DEBUG\n\n\n return app.exec();\n}\nFix include paths#include \n#include \n#include \n\n#ifdef Q_OS_ANDROID\n#include \"qutils\/NotificationClient.h\"\n#include \"qutils\/Notification.h\"\n#include \"qutils\/android\/AndroidUtils.h\"\n#endif \/\/ Q_OS_ANDROID\n#include \"qutils\/ScreenHelper.h\"\n#include \"qutils\/QMLRefresh.h\"\n#include \"qutils\/Macros.h\"\n\nint main(int argc, char *argv[])\n{\n QGuiApplication app(argc, argv);\n\n QQmlApplicationEngine engine;\n\n zmc::ScreenHelper screenHelper;\n engine.rootContext()->setContextProperty(\"SH\", &screenHelper);\n\n#ifdef Q_OS_ANDROID\n qmlRegisterType(\"NotificationClient\", 1, 0, \"NotificationClient\");\n qmlRegisterType(\"NotificationClient\", 1, 0, \"Notification\");\n qmlRegisterType(\"qutils.AndroidUtils\", 1, 0, \"AndroidUtils\");\n#endif \/\/ Q_OS_ANDROID\n\n#if defined(QT_DEBUG) && defined(Q_OS_DESKTOP)\n zmc::QMLRefresh manager(&engine);\n manager.setMainQMLFile(\"file:\/\/\/E:\/Development\/SourceTree\/GitHub\/qutils\/qutils_demo\/qml\/main.qml\");\n engine.rootContext()->setContextProperty(\"QM\", &manager);\n engine.rootContext()->setContextProperty(\"QML_DEBUG\", QVariant::fromValue(true));\n engine.rootContext()->setContextProperty(\"Q_OS_DESKTOP\", QVariant::fromValue(1));\n engine.load(QUrl(\"file:\/\/\/E:\/Development\/SourceTree\/GitHub\/qutils\/qutils_demo\/qml\/main.qml\"));\n#else\n engine.rootContext()->setContextProperty(\"QM\", nullptr);\n engine.rootContext()->setContextProperty(\"QML_DEBUG\", QVariant::fromValue(false));\n engine.rootContext()->setContextProperty(\"Q_OS_DESKTOP\", QVariant::fromValue(0));\n engine.load(QUrl(QStringLiteral(\"qrc:\/qml\/main.qml\")));\n#endif \/\/ QT_DEBUG\n\n\n return app.exec();\n}\n<|endoftext|>"} {"text":"\/*\n * Copyright (c) 2000-2005 The Regents of The University of Michigan\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met: redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer;\n * redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution;\n * neither the name of the copyright holders nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n * Authors: Nathan Binkert\n *\/\n\n#include \n#include \n\n#include \n#include \n\n#include \"base\/cprintf.hh\"\n#include \"base\/misc.hh\"\n#include \"config\/pythonhome.hh\"\n#include \"python\/swig\/init.hh\"\n#include \"sim\/async.hh\"\n#include \"sim\/host.hh\"\n#include \"sim\/core.hh\"\n\nusing namespace std;\n\n\/\/\/ Stats signal handler.\nvoid\ndumpStatsHandler(int sigtype)\n{\n async_event = true;\n async_statdump = true;\n}\n\nvoid\ndumprstStatsHandler(int sigtype)\n{\n async_event = true;\n async_statdump = true;\n async_statreset = true;\n}\n\n\/\/\/ Exit signal handler.\nvoid\nexitNowHandler(int sigtype)\n{\n async_event = true;\n async_exit = true;\n}\n\n\/\/\/ Abort signal handler.\nvoid\nabortHandler(int sigtype)\n{\n ccprintf(cerr, \"Program aborted at cycle %d\\n\", curTick);\n}\n\nint\nmain(int argc, char **argv)\n{\n signal(SIGFPE, SIG_IGN);\t\t\/\/ may occur on misspeculated paths\n signal(SIGTRAP, SIG_IGN);\n signal(SIGUSR1, dumpStatsHandler);\t\t\/\/ dump intermediate stats\n signal(SIGUSR2, dumprstStatsHandler);\t\/\/ dump and reset stats\n signal(SIGINT, exitNowHandler);\t\t\/\/ dump final stats and exit\n signal(SIGABRT, abortHandler);\n\n Py_SetProgramName(argv[0]);\n\n \/\/ default path to m5 python code is the currently executing\n \/\/ file... Python ZipImporter will find embedded zip archive.\n \/\/ The M5_ARCHIVE environment variable can be used to override this.\n char *m5_archive = getenv(\"M5_ARCHIVE\");\n string pythonpath = m5_archive ? m5_archive : argv[0];\n\n char *oldpath = getenv(\"PYTHONPATH\");\n if (oldpath != NULL) {\n pythonpath += \":\";\n pythonpath += oldpath;\n }\n\n if (setenv(\"PYTHONPATH\", pythonpath.c_str(), true) == -1)\n fatal(\"setenv: %s\\n\", strerror(errno));\n\n char *python_home = getenv(\"PYTHONHOME\");\n if (!python_home)\n python_home = PYTHONHOME;\n Py_SetPythonHome(python_home);\n\n \/\/ initialize embedded Python interpreter\n Py_Initialize();\n PySys_SetArgv(argc, argv);\n\n \/\/ initialize SWIG modules\n init_swig();\n\n PyRun_SimpleString(\"import m5.main\");\n PyRun_SimpleString(\"m5.main.main()\");\n\n \/\/ clean up Python intepreter.\n Py_Finalize();\n}\nmain: return an an exit code of 1 when we exit due to a python exception. This requires us to not use PyRun_SimpleString, but PyRun_String since the latter actually returns a result\/*\n * Copyright (c) 2000-2005 The Regents of The University of Michigan\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met: redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer;\n * redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution;\n * neither the name of the copyright holders nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n * Authors: Nathan Binkert\n *\/\n\n#include \n#include \n\n#include \n#include \n\n#include \"base\/cprintf.hh\"\n#include \"base\/misc.hh\"\n#include \"config\/pythonhome.hh\"\n#include \"python\/swig\/init.hh\"\n#include \"sim\/async.hh\"\n#include \"sim\/host.hh\"\n#include \"sim\/core.hh\"\n\nusing namespace std;\n\n\/\/\/ Stats signal handler.\nvoid\ndumpStatsHandler(int sigtype)\n{\n async_event = true;\n async_statdump = true;\n}\n\nvoid\ndumprstStatsHandler(int sigtype)\n{\n async_event = true;\n async_statdump = true;\n async_statreset = true;\n}\n\n\/\/\/ Exit signal handler.\nvoid\nexitNowHandler(int sigtype)\n{\n async_event = true;\n async_exit = true;\n}\n\n\/\/\/ Abort signal handler.\nvoid\nabortHandler(int sigtype)\n{\n ccprintf(cerr, \"Program aborted at cycle %d\\n\", curTick);\n}\n\nint\npython_main()\n{\n PyObject *module;\n PyObject *dict;\n PyObject *result;\n\n module = PyImport_AddModule(\"__main__\");\n if (module == NULL)\n fatal(\"Could not import __main__\");\n\n dict = PyModule_GetDict(module);\n\n result = PyRun_String(\"import m5.main\", Py_file_input, dict, dict);\n if (!result) {\n PyErr_Print();\n return 1;\n }\n Py_DECREF(result);\n\n result = PyRun_String(\"m5.main.main()\", Py_file_input, dict, dict);\n if (!result) {\n PyErr_Print();\n return 1;\n }\n Py_DECREF(result);\n\n if (Py_FlushLine())\n PyErr_Clear();\n\n return 0;\n}\n\nint\nmain(int argc, char **argv)\n{\n signal(SIGFPE, SIG_IGN);\t\t\/\/ may occur on misspeculated paths\n signal(SIGTRAP, SIG_IGN);\n signal(SIGUSR1, dumpStatsHandler);\t\t\/\/ dump intermediate stats\n signal(SIGUSR2, dumprstStatsHandler);\t\/\/ dump and reset stats\n signal(SIGINT, exitNowHandler);\t\t\/\/ dump final stats and exit\n signal(SIGABRT, abortHandler);\n\n Py_SetProgramName(argv[0]);\n\n \/\/ default path to m5 python code is the currently executing\n \/\/ file... Python ZipImporter will find embedded zip archive.\n \/\/ The M5_ARCHIVE environment variable can be used to override this.\n char *m5_archive = getenv(\"M5_ARCHIVE\");\n string pythonpath = m5_archive ? m5_archive : argv[0];\n\n char *oldpath = getenv(\"PYTHONPATH\");\n if (oldpath != NULL) {\n pythonpath += \":\";\n pythonpath += oldpath;\n }\n\n if (setenv(\"PYTHONPATH\", pythonpath.c_str(), true) == -1)\n fatal(\"setenv: %s\\n\", strerror(errno));\n\n char *python_home = getenv(\"PYTHONHOME\");\n if (!python_home)\n python_home = PYTHONHOME;\n Py_SetPythonHome(python_home);\n\n \/\/ initialize embedded Python interpreter\n Py_Initialize();\n PySys_SetArgv(argc, argv);\n\n \/\/ initialize SWIG modules\n init_swig();\n\n int ret = python_main();\n\n \/\/ clean up Python intepreter.\n Py_Finalize();\n\n return ret;\n}\n<|endoftext|>"} {"text":"\/\/\n\/\/ (c) 2014 Raphael Bialon \n\/\/\n\/\/ This program is free software: you can redistribute it and\/or modify\n\/\/ it under the terms of the GNU Lesser General Public License as published by\n\/\/ the Free Software Foundation, either version 3 of the License, or\n\/\/ (at your option) any later version.\n\/\/\n\/\/ This program is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n\/\/ GNU Lesser General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public License\n\/\/ along with this program. If not, see http:\/\/www.gnu.org\/licenses\/.\n\/\/\n\n\n#include \"SqliteDatabaseHandler.h\"\n#include \"DatabaseHandler.h\"\n#include \"TbusQueueControl.h\"\n#include \"ModuleAccess.h\"\n#include \"TbusQueueDatarateValue.h\"\n#include \"TbusQueueDelayValue.h\"\n\nDefine_Module(TbusQueueControl);\n\n\/**\n * Empty constructor.\n *\/\nTbusQueueControl::TbusQueueControl() {}\n\n\/**\n * Get references to the modules' queues and the global database handler and coordinate converter.\n *\/\nvoid TbusQueueControl::initialize() {\n\t\/\/ Get references to \"our\" queues\n\tcdrq = ModuleAccess(\"cdrq\").get();\n\tcrrq = ModuleAccess(\"crrq\").get();\n\tcrsq = ModuleAccess(\"crsq\").get();\n\tcdsq = ModuleAccess(\"cdsq\").get();\n\n\tdbHandler = DatabaseHandler::getInstance();\n\tconverter = TbusCoordinateConverter::getInstance();\n}\n\n\/**\n * Translates the given coordinates into latitute\/longitude.\n * Then retrieves the belonging datarate, droprate and delay values from the database Handler.\n * Then the new values are updated on the belonging queue.\n * @see TbusCoordinateConverter::translate(const Coord&)\n * @see DatabaseHandler::getUploadDatarate(const Coord&)\n * @see DatabaseHandler::getDownloadDatarate(const Coord&)\n * @see DatabaseHandler::getUploadDelay(const Coord&)\n * @see DatabaseHandler::getDownloadDelay(const Coord&)\n * @param newCoords The new node position\n *\/\nvoid TbusQueueControl::updateQueues(const Coord& newCoords) {\n\t\/\/ Act like this is part of our PHY layer\n\tEnter_Method_Silent();\n\n\tEV << \"TbusQueueControl updating queues for coordinates \" << newCoords << endl;\n\n\tCoord translated = converter->translate(&newCoords);\n\n\tTbusQueueDatarateValue* sendDatarate = dbHandler->getUploadDatarate(translated);\n\tTbusQueueDatarateValue* receiveDatarate = dbHandler->getDownloadDatarate(translated);\n\tTbusQueueDelayValue* sendDelay = dbHandler->getUploadDelay(translated);\n\tTbusQueueDelayValue* receiveDelay = dbHandler->getDownloadDelay(translated);\n\n\tstd::cout << \"sda:\" << sendDatarate->datarate << \" rda:\" << receiveDatarate->datarate << \" sde:\" << sendDelay->delay << \" rde:\" << receiveDelay->delay << std::endl;\n\n\tcdrq->updateValue(receiveDelay);\n\tcrrq->updateValue(receiveDatarate);\n\tcrsq->updateValue(sendDatarate);\n\tcdsq->updateValue(sendDelay);\n}\nSilenced debug output in QueueControl\/\/\n\/\/ (c) 2014 Raphael Bialon \n\/\/\n\/\/ This program is free software: you can redistribute it and\/or modify\n\/\/ it under the terms of the GNU Lesser General Public License as published by\n\/\/ the Free Software Foundation, either version 3 of the License, or\n\/\/ (at your option) any later version.\n\/\/\n\/\/ This program is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n\/\/ GNU Lesser General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public License\n\/\/ along with this program. If not, see http:\/\/www.gnu.org\/licenses\/.\n\/\/\n\n\n#include \"SqliteDatabaseHandler.h\"\n#include \"DatabaseHandler.h\"\n#include \"TbusQueueControl.h\"\n#include \"ModuleAccess.h\"\n#include \"TbusQueueDatarateValue.h\"\n#include \"TbusQueueDelayValue.h\"\n\nDefine_Module(TbusQueueControl);\n\n\/**\n * Empty constructor.\n *\/\nTbusQueueControl::TbusQueueControl() {}\n\n\/**\n * Get references to the modules' queues and the global database handler and coordinate converter.\n *\/\nvoid TbusQueueControl::initialize() {\n\t\/\/ Get references to \"our\" queues\n\tcdrq = ModuleAccess(\"cdrq\").get();\n\tcrrq = ModuleAccess(\"crrq\").get();\n\tcrsq = ModuleAccess(\"crsq\").get();\n\tcdsq = ModuleAccess(\"cdsq\").get();\n\n\tdbHandler = DatabaseHandler::getInstance();\n\tconverter = TbusCoordinateConverter::getInstance();\n}\n\n\/**\n * Translates the given coordinates into latitute\/longitude.\n * Then retrieves the belonging datarate, droprate and delay values from the database Handler.\n * Then the new values are updated on the belonging queue.\n * @see TbusCoordinateConverter::translate(const Coord&)\n * @see DatabaseHandler::getUploadDatarate(const Coord&)\n * @see DatabaseHandler::getDownloadDatarate(const Coord&)\n * @see DatabaseHandler::getUploadDelay(const Coord&)\n * @see DatabaseHandler::getDownloadDelay(const Coord&)\n * @param newCoords The new node position\n *\/\nvoid TbusQueueControl::updateQueues(const Coord& newCoords) {\n\t\/\/ Act like this is part of our PHY layer\n\tEnter_Method_Silent();\n\n\tEV << \"TbusQueueControl updating queues for coordinates \" << newCoords << endl;\n\n\tCoord translated = converter->translate(&newCoords);\n\n\tTbusQueueDatarateValue* sendDatarate = dbHandler->getUploadDatarate(translated);\n\tTbusQueueDatarateValue* receiveDatarate = dbHandler->getDownloadDatarate(translated);\n\tTbusQueueDelayValue* sendDelay = dbHandler->getUploadDelay(translated);\n\tTbusQueueDelayValue* receiveDelay = dbHandler->getDownloadDelay(translated);\n\n\t\/\/std::cout << \"sda:\" << sendDatarate->datarate << \" rda:\" << receiveDatarate->datarate << \" sde:\" << sendDelay->delay << \" rde:\" << receiveDelay->delay << std::endl;\n\n\tcdrq->updateValue(receiveDelay);\n\tcrrq->updateValue(receiveDatarate);\n\tcrsq->updateValue(sendDatarate);\n\tcdsq->updateValue(sendDelay);\n}\n<|endoftext|>"} {"text":"\/****************************************************************************\n**\n** Copyright (C) 2013 Digia Plc and\/or its subsidiary(-ies).\n** Contact: http:\/\/www.qt-project.org\/legal\n**\n** This file is part of Qt Creator.\n**\n** Commercial License Usage\n** Licensees holding valid commercial Qt licenses may use this file in\n** accordance with the commercial license agreement provided with the\n** Software or, alternatively, in accordance with the terms contained in\n** a written agreement between you and Digia. For licensing terms and\n** conditions see http:\/\/qt.digia.com\/licensing. For further information\n** use the contact form at http:\/\/qt.digia.com\/contact-us.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Digia gives you certain additional\n** rights. These rights are described in the Digia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n****************************************************************************\/\n\n#include \"executefilter.h\"\n\n#include \n#include \n#include \n\n#include \n\nusing namespace Core;\nusing namespace Locator;\nusing namespace Locator::Internal;\n\nExecuteFilter::ExecuteFilter()\n{\n setId(\"Execute custom commands\");\n setDisplayName(tr(\"Execute Custom Commands\"));\n setShortcutString(QString(QLatin1Char('!')));\n setIncludedByDefault(false);\n\n m_process = new Utils::QtcProcess(this);\n m_process->setEnvironment(Utils::Environment::systemEnvironment());\n connect(m_process, SIGNAL(finished(int,QProcess::ExitStatus)), this,\n SLOT(finished(int,QProcess::ExitStatus)));\n connect(m_process, SIGNAL(readyReadStandardOutput()), this, SLOT(readStandardOutput()));\n connect(m_process, SIGNAL(readyReadStandardError()), this, SLOT(readStandardError()));\n\n m_runTimer.setSingleShot(true);\n connect(&m_runTimer, SIGNAL(timeout()), this, SLOT(runHeadCommand()));\n}\n\nQList ExecuteFilter::matchesFor(QFutureInterface &future,\n const QString &entry)\n{\n QList value;\n if (!entry.isEmpty()) \/\/ avoid empty entry\n value.append(FilterEntry(this, entry, QVariant()));\n QList others;\n const Qt::CaseSensitivity caseSensitivityForPrefix = caseSensitivity(entry);\n foreach (const QString &i, m_commandHistory) {\n if (future.isCanceled())\n break;\n if (i == entry) \/\/ avoid repeated entry\n continue;\n if (i.startsWith(entry, caseSensitivityForPrefix))\n value.append(FilterEntry(this, i, QVariant()));\n else\n others.append(FilterEntry(this, i, QVariant()));\n }\n value.append(others);\n return value;\n}\n\nvoid ExecuteFilter::accept(FilterEntry selection) const\n{\n ExecuteFilter *p = const_cast(this);\n\n const QString value = selection.displayName.trimmed();\n const int index = m_commandHistory.indexOf(value);\n if (index != -1 && index != 0)\n p->m_commandHistory.removeAt(index);\n if (index != 0)\n p->m_commandHistory.prepend(value);\n\n bool found;\n QString workingDirectory = Core::VariableManager::value(\"CurrentDocument:Path\", &found);\n if (!found || workingDirectory.isEmpty())\n workingDirectory = Core::VariableManager::value(\"CurrentProject:Path\", &found);\n\n ExecuteData d;\n d.workingDirectory = workingDirectory;\n const int pos = value.indexOf(QLatin1Char(' '));\n if (pos == -1) {\n d.executable = value;\n } else {\n d.executable = value.left(pos);\n d.arguments = value.right(value.length() - pos - 1);\n }\n\n if (m_process->state() != QProcess::NotRunning) {\n const QString info(tr(\"Previous command is still running ('%1').\\nDo you want to kill it?\")\n .arg(p->headCommand()));\n int r = QMessageBox::question(0, tr(\"Kill Previous Process?\"), info,\n QMessageBox::Yes | QMessageBox::No | QMessageBox::Cancel,\n QMessageBox::Yes);\n if (r == QMessageBox::Yes)\n m_process->kill();\n if (r != QMessageBox::Cancel)\n p->m_taskQueue.enqueue(d);\n return;\n }\n\n p->m_taskQueue.enqueue(d);\n p->runHeadCommand();\n}\n\nvoid ExecuteFilter::finished(int exitCode, QProcess::ExitStatus status)\n{\n const QString commandName = headCommand();\n QString message;\n if (status == QProcess::NormalExit && exitCode == 0)\n message = tr(\"Command '%1' finished\").arg(commandName);\n else\n message = tr(\"Command '%1' failed\").arg(commandName);\n MessageManager::write(message);\n\n m_taskQueue.dequeue();\n if (!m_taskQueue.isEmpty())\n m_runTimer.start(500);\n}\n\nvoid ExecuteFilter::readStandardOutput()\n{\n QByteArray data = m_process->readAllStandardOutput();\n MessageManager::write(QTextCodec::codecForLocale()->toUnicode(data.constData(), data.size(),\n &m_stdoutState));\n}\n\nvoid ExecuteFilter::readStandardError()\n{\n static QTextCodec::ConverterState state;\n QByteArray data = m_process->readAllStandardError();\n MessageManager::write(QTextCodec::codecForLocale()->toUnicode(data.constData(), data.size(),\n &m_stderrState));\n}\n\nvoid ExecuteFilter::runHeadCommand()\n{\n if (!m_taskQueue.isEmpty()) {\n const ExecuteData &d = m_taskQueue.head();\n const QString fullPath = Utils::Environment::systemEnvironment().searchInPath(d.executable);\n if (fullPath.isEmpty()) {\n MessageManager::write(tr(\"Could not find executable for '%1'\").arg(d.executable));\n m_taskQueue.dequeue();\n runHeadCommand();\n return;\n }\n MessageManager::write(tr(\"Starting command '%1'\").arg(headCommand()));\n m_process->setWorkingDirectory(d.workingDirectory);\n m_process->setCommand(fullPath, d.arguments);\n m_process->start();\n m_process->closeWriteChannel();\n }\n}\n\nQString ExecuteFilter::headCommand() const\n{\n if (m_taskQueue.isEmpty())\n return QString();\n const ExecuteData &data = m_taskQueue.head();\n if (data.arguments.isEmpty())\n return data.executable;\n else\n return data.executable + QLatin1Char(' ') + data.arguments;\n}\nLocator: fix UI text punctuation\/****************************************************************************\n**\n** Copyright (C) 2013 Digia Plc and\/or its subsidiary(-ies).\n** Contact: http:\/\/www.qt-project.org\/legal\n**\n** This file is part of Qt Creator.\n**\n** Commercial License Usage\n** Licensees holding valid commercial Qt licenses may use this file in\n** accordance with the commercial license agreement provided with the\n** Software or, alternatively, in accordance with the terms contained in\n** a written agreement between you and Digia. For licensing terms and\n** conditions see http:\/\/qt.digia.com\/licensing. For further information\n** use the contact form at http:\/\/qt.digia.com\/contact-us.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Digia gives you certain additional\n** rights. These rights are described in the Digia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n****************************************************************************\/\n\n#include \"executefilter.h\"\n\n#include \n#include \n#include \n\n#include \n\nusing namespace Core;\nusing namespace Locator;\nusing namespace Locator::Internal;\n\nExecuteFilter::ExecuteFilter()\n{\n setId(\"Execute custom commands\");\n setDisplayName(tr(\"Execute Custom Commands\"));\n setShortcutString(QString(QLatin1Char('!')));\n setIncludedByDefault(false);\n\n m_process = new Utils::QtcProcess(this);\n m_process->setEnvironment(Utils::Environment::systemEnvironment());\n connect(m_process, SIGNAL(finished(int,QProcess::ExitStatus)), this,\n SLOT(finished(int,QProcess::ExitStatus)));\n connect(m_process, SIGNAL(readyReadStandardOutput()), this, SLOT(readStandardOutput()));\n connect(m_process, SIGNAL(readyReadStandardError()), this, SLOT(readStandardError()));\n\n m_runTimer.setSingleShot(true);\n connect(&m_runTimer, SIGNAL(timeout()), this, SLOT(runHeadCommand()));\n}\n\nQList ExecuteFilter::matchesFor(QFutureInterface &future,\n const QString &entry)\n{\n QList value;\n if (!entry.isEmpty()) \/\/ avoid empty entry\n value.append(FilterEntry(this, entry, QVariant()));\n QList others;\n const Qt::CaseSensitivity caseSensitivityForPrefix = caseSensitivity(entry);\n foreach (const QString &i, m_commandHistory) {\n if (future.isCanceled())\n break;\n if (i == entry) \/\/ avoid repeated entry\n continue;\n if (i.startsWith(entry, caseSensitivityForPrefix))\n value.append(FilterEntry(this, i, QVariant()));\n else\n others.append(FilterEntry(this, i, QVariant()));\n }\n value.append(others);\n return value;\n}\n\nvoid ExecuteFilter::accept(FilterEntry selection) const\n{\n ExecuteFilter *p = const_cast(this);\n\n const QString value = selection.displayName.trimmed();\n const int index = m_commandHistory.indexOf(value);\n if (index != -1 && index != 0)\n p->m_commandHistory.removeAt(index);\n if (index != 0)\n p->m_commandHistory.prepend(value);\n\n bool found;\n QString workingDirectory = Core::VariableManager::value(\"CurrentDocument:Path\", &found);\n if (!found || workingDirectory.isEmpty())\n workingDirectory = Core::VariableManager::value(\"CurrentProject:Path\", &found);\n\n ExecuteData d;\n d.workingDirectory = workingDirectory;\n const int pos = value.indexOf(QLatin1Char(' '));\n if (pos == -1) {\n d.executable = value;\n } else {\n d.executable = value.left(pos);\n d.arguments = value.right(value.length() - pos - 1);\n }\n\n if (m_process->state() != QProcess::NotRunning) {\n const QString info(tr(\"Previous command is still running ('%1').\\nDo you want to kill it?\")\n .arg(p->headCommand()));\n int r = QMessageBox::question(0, tr(\"Kill Previous Process?\"), info,\n QMessageBox::Yes | QMessageBox::No | QMessageBox::Cancel,\n QMessageBox::Yes);\n if (r == QMessageBox::Yes)\n m_process->kill();\n if (r != QMessageBox::Cancel)\n p->m_taskQueue.enqueue(d);\n return;\n }\n\n p->m_taskQueue.enqueue(d);\n p->runHeadCommand();\n}\n\nvoid ExecuteFilter::finished(int exitCode, QProcess::ExitStatus status)\n{\n const QString commandName = headCommand();\n QString message;\n if (status == QProcess::NormalExit && exitCode == 0)\n message = tr(\"Command '%1' finished.\").arg(commandName);\n else\n message = tr(\"Command '%1' failed.\").arg(commandName);\n MessageManager::write(message);\n\n m_taskQueue.dequeue();\n if (!m_taskQueue.isEmpty())\n m_runTimer.start(500);\n}\n\nvoid ExecuteFilter::readStandardOutput()\n{\n QByteArray data = m_process->readAllStandardOutput();\n MessageManager::write(QTextCodec::codecForLocale()->toUnicode(data.constData(), data.size(),\n &m_stdoutState));\n}\n\nvoid ExecuteFilter::readStandardError()\n{\n static QTextCodec::ConverterState state;\n QByteArray data = m_process->readAllStandardError();\n MessageManager::write(QTextCodec::codecForLocale()->toUnicode(data.constData(), data.size(),\n &m_stderrState));\n}\n\nvoid ExecuteFilter::runHeadCommand()\n{\n if (!m_taskQueue.isEmpty()) {\n const ExecuteData &d = m_taskQueue.head();\n const QString fullPath = Utils::Environment::systemEnvironment().searchInPath(d.executable);\n if (fullPath.isEmpty()) {\n MessageManager::write(tr(\"Could not find executable for '%1'\").arg(d.executable));\n m_taskQueue.dequeue();\n runHeadCommand();\n return;\n }\n MessageManager::write(tr(\"Starting command '%1'\").arg(headCommand()));\n m_process->setWorkingDirectory(d.workingDirectory);\n m_process->setCommand(fullPath, d.arguments);\n m_process->start();\n m_process->closeWriteChannel();\n }\n}\n\nQString ExecuteFilter::headCommand() const\n{\n if (m_taskQueue.isEmpty())\n return QString();\n const ExecuteData &data = m_taskQueue.head();\n if (data.arguments.isEmpty())\n return data.executable;\n else\n return data.executable + QLatin1Char(' ') + data.arguments;\n}\n<|endoftext|>"} {"text":"\/*\n * This file is open source software, licensed to you under the terms\n * of the Apache License, Version 2.0 (the \"License\"). See the NOTICE file\n * distributed with this work for additional information regarding copyright\n * ownership. You may not use this file except in compliance with the License.\n *\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied. See the License for the\n * specific language governing permissions and limitations\n * under the License.\n *\/\n\n\/*\n * Copyright (C) 2016 ScyllaDB.\n *\/\n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace seastar;\nusing namespace seastar::net;\n\nstatic const sstring seastar_name = \"seastar.io\";\n\nstatic future<> test_resolve(dns_resolver::options opts) {\n auto d = ::make_lw_shared(std::move(opts));\n return d->get_host_by_name(seastar_name, inet_address::family::INET).then([d](hostent e) {\n return d->get_host_by_addr(e.addr_list.front()).then([d, a = e.addr_list.front()](hostent e) {\n return d->get_host_by_name(e.names.front(), inet_address::family::INET).then([a](hostent e) {\n BOOST_REQUIRE(std::count(e.addr_list.begin(), e.addr_list.end(), a));\n });\n });\n }).finally([d]{\n return d->close();\n });\n}\n\nstatic future<> test_bad_name(dns_resolver::options opts) {\n auto d = ::make_lw_shared(std::move(opts));\n return d->get_host_by_name(\"apa.ninja.gnu\", inet_address::family::INET).then_wrapped([d](future f) {\n try {\n f.get();\n BOOST_FAIL(\"should not succeed\");\n } catch (...) {\n \/\/ ok.\n }\n }).finally([d]{\n return d->close();\n });\n}\n\nSEASTAR_TEST_CASE(test_resolve_udp) {\n return test_resolve(dns_resolver::options());\n}\n\nSEASTAR_TEST_CASE(test_bad_name_udp) {\n return test_bad_name(dns_resolver::options());\n}\n\nSEASTAR_TEST_CASE(test_timeout_udp) {\n dns_resolver::options opts;\n opts.servers = std::vector({ inet_address(\"1.2.3.4\") }); \/\/ not a server\n opts.udp_port = 29953; \/\/ not a dns port\n opts.timeout = std::chrono::milliseconds(500);\n\n auto d = ::make_lw_shared(engine().net(), opts);\n return d->get_host_by_name(seastar_name, inet_address::family::INET).then_wrapped([d](future f) {\n try {\n f.get();\n BOOST_FAIL(\"should not succeed\");\n } catch (...) {\n \/\/ ok.\n }\n }).finally([d]{\n return d->close();\n });\n}\n\n\/\/ NOTE: cannot really test timeout in TCP mode, because seastar sockets do not support \n\/\/ connect with timeout -> cannot complete connect future in dns::do_connect in reasonable\n\/\/ time.\n\n\/\/ But we can test for connection refused working as expected.\nSEASTAR_TEST_CASE(test_connection_refused_tcp) {\n dns_resolver::options opts;\n opts.servers = std::vector({ inet_address(\"127.0.0.1\") }); \n opts.use_tcp_query = true;\n opts.tcp_port = 29953; \/\/ not a dns port\n\n auto d = ::make_lw_shared(engine().net(), opts);\n return d->get_host_by_name(seastar_name, inet_address::family::INET).then_wrapped([d](future f) {\n try {\n f.get();\n BOOST_FAIL(\"should not succeed\");\n } catch (...) {\n \/\/ ok.\n }\n }).finally([d]{\n return d->close();\n });\n}\n\nSEASTAR_TEST_CASE(test_resolve_tcp) {\n dns_resolver::options opts;\n opts.use_tcp_query = true;\n return test_resolve(opts);\n}\n\nSEASTAR_TEST_CASE(test_bad_name_tcp) {\n dns_resolver::options opts;\n opts.use_tcp_query = true;\n return test_bad_name(opts);\n}\n\nstatic const sstring imaps_service = \"imaps\";\nstatic const sstring gmail_domain = \"gmail.com\";\n\nstatic future<> test_srv() {\n auto d = ::make_lw_shared();\n return d->get_srv_records(dns_resolver::srv_proto::tcp,\n imaps_service,\n gmail_domain).then([d](dns_resolver::srv_records records) {\n BOOST_REQUIRE(!records.empty());\n for (auto& record : records) {\n \/\/ record.target should end with \"gmail.com\"\n BOOST_REQUIRE_GT(record.target.size(), gmail_domain.size());\n BOOST_REQUIRE_EQUAL(record.target.compare(record.target.size() - gmail_domain.size(),\n gmail_domain.size(),\n gmail_domain),\n 0);\n }\n }).finally([d]{\n return d->close();\n });\n}\n\nSEASTAR_TEST_CASE(test_srv_tcp) {\n return test_srv();\n}\ndns_test: Add test for overlapping\/simulatneous queries (both tcp+udp)\/*\n * This file is open source software, licensed to you under the terms\n * of the Apache License, Version 2.0 (the \"License\"). See the NOTICE file\n * distributed with this work for additional information regarding copyright\n * ownership. You may not use this file except in compliance with the License.\n *\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied. See the License for the\n * specific language governing permissions and limitations\n * under the License.\n *\/\n\n\/*\n * Copyright (C) 2016 ScyllaDB.\n *\/\n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace seastar;\nusing namespace seastar::net;\n\nstatic const sstring seastar_name = \"seastar.io\";\n\nstatic future<> test_resolve(dns_resolver::options opts) {\n auto d = ::make_lw_shared(std::move(opts));\n return d->get_host_by_name(seastar_name, inet_address::family::INET).then([d](hostent e) {\n return d->get_host_by_addr(e.addr_list.front()).then([d, a = e.addr_list.front()](hostent e) {\n return d->get_host_by_name(e.names.front(), inet_address::family::INET).then([a](hostent e) {\n BOOST_REQUIRE(std::count(e.addr_list.begin(), e.addr_list.end(), a));\n });\n });\n }).finally([d]{\n return d->close();\n });\n}\n\nstatic future<> test_bad_name(dns_resolver::options opts) {\n auto d = ::make_lw_shared(std::move(opts));\n return d->get_host_by_name(\"apa.ninja.gnu\", inet_address::family::INET).then_wrapped([d](future f) {\n try {\n f.get();\n BOOST_FAIL(\"should not succeed\");\n } catch (...) {\n \/\/ ok.\n }\n }).finally([d]{\n return d->close();\n });\n}\n\nSEASTAR_TEST_CASE(test_resolve_udp) {\n return test_resolve(dns_resolver::options());\n}\n\nSEASTAR_TEST_CASE(test_bad_name_udp) {\n return test_bad_name(dns_resolver::options());\n}\n\nSEASTAR_TEST_CASE(test_timeout_udp) {\n dns_resolver::options opts;\n opts.servers = std::vector({ inet_address(\"1.2.3.4\") }); \/\/ not a server\n opts.udp_port = 29953; \/\/ not a dns port\n opts.timeout = std::chrono::milliseconds(500);\n\n auto d = ::make_lw_shared(engine().net(), opts);\n return d->get_host_by_name(seastar_name, inet_address::family::INET).then_wrapped([d](future f) {\n try {\n f.get();\n BOOST_FAIL(\"should not succeed\");\n } catch (...) {\n \/\/ ok.\n }\n }).finally([d]{\n return d->close();\n });\n}\n\n\/\/ NOTE: cannot really test timeout in TCP mode, because seastar sockets do not support \n\/\/ connect with timeout -> cannot complete connect future in dns::do_connect in reasonable\n\/\/ time.\n\n\/\/ But we can test for connection refused working as expected.\nSEASTAR_TEST_CASE(test_connection_refused_tcp) {\n dns_resolver::options opts;\n opts.servers = std::vector({ inet_address(\"127.0.0.1\") }); \n opts.use_tcp_query = true;\n opts.tcp_port = 29953; \/\/ not a dns port\n\n auto d = ::make_lw_shared(engine().net(), opts);\n return d->get_host_by_name(seastar_name, inet_address::family::INET).then_wrapped([d](future f) {\n try {\n f.get();\n BOOST_FAIL(\"should not succeed\");\n } catch (...) {\n \/\/ ok.\n }\n }).finally([d]{\n return d->close();\n });\n}\n\nSEASTAR_TEST_CASE(test_resolve_tcp) {\n dns_resolver::options opts;\n opts.use_tcp_query = true;\n return test_resolve(opts);\n}\n\nSEASTAR_TEST_CASE(test_bad_name_tcp) {\n dns_resolver::options opts;\n opts.use_tcp_query = true;\n return test_bad_name(opts);\n}\n\nstatic const sstring imaps_service = \"imaps\";\nstatic const sstring gmail_domain = \"gmail.com\";\n\nstatic future<> test_srv() {\n auto d = ::make_lw_shared();\n return d->get_srv_records(dns_resolver::srv_proto::tcp,\n imaps_service,\n gmail_domain).then([d](dns_resolver::srv_records records) {\n BOOST_REQUIRE(!records.empty());\n for (auto& record : records) {\n \/\/ record.target should end with \"gmail.com\"\n BOOST_REQUIRE_GT(record.target.size(), gmail_domain.size());\n BOOST_REQUIRE_EQUAL(record.target.compare(record.target.size() - gmail_domain.size(),\n gmail_domain.size(),\n gmail_domain),\n 0);\n }\n }).finally([d]{\n return d->close();\n });\n}\n\nSEASTAR_TEST_CASE(test_srv_tcp) {\n return test_srv();\n}\n\n\nSEASTAR_TEST_CASE(test_parallel_resolve_name) {\n dns_resolver::options opts;\n opts.use_tcp_query = true;\n\n auto d = ::make_lw_shared(std::move(opts));\n return when_all(\n d->resolve_name(\"www.google.com\"),\n d->resolve_name(\"www.google.com\"),\n d->resolve_name(\"www.google.com\"),\n d->resolve_name(\"www.google.com\"),\n d->resolve_name(\"www.google.com\"),\n d->resolve_name(\"www.google.com\")\n ).finally([d](auto&&...) {}).discard_result();\n}\n\nSEASTAR_TEST_CASE(test_parallel_resolve_name_udp) {\n dns_resolver::options opts;\n\n auto d = ::make_lw_shared(std::move(opts));\n return when_all(\n d->resolve_name(\"www.google.com\"),\n d->resolve_name(\"www.google.com\"),\n d->resolve_name(\"www.google.com\"),\n d->resolve_name(\"www.google.com\"),\n d->resolve_name(\"www.google.com\"),\n d->resolve_name(\"www.google.com\")\n ).finally([d](auto&...) {}).discard_result();\n}\n<|endoftext|>"} {"text":"#include \"MorphScene.h\"\n#include \n#include \n\n#include \"FrameBufferObjects.h\"\n\n#include \n#include \"GeometryObject.h\"\n#include \n\n#include \"settings.h\"\n#include \"input.h\"\n\n#include \n#include \n#include \"Camera.h\"\n#include \"Player.h\"\n\n#include \n#include \n#include \n\n#define BUFFER_OFFSET(i) ((char *)nullptr + (i))\n\nMorphScene::MorphScene() {\n\tstate = 0;\n\n\tdiffuse = new Texture2D(\"Resources\/Models\/rock01\/diffuse.tga\");\n\tnormal = new Texture2D(\"Resources\/Models\/rock01\/normal.tga\");\n\tspecular = new Texture2D(\"Resources\/Models\/rock01\/specular.tga\");\n\n\tvertexShader = new Shader(\"morph_vertex.glsl\", GL_VERTEX_SHADER);\n\tgeometryShader = new Shader(\"default_geometry.glsl\", GL_GEOMETRY_SHADER);\n\tfragmentShader = new Shader(\"normalspecularmap_fragment.glsl\", GL_FRAGMENT_SHADER);\n\tshaderProgram = new ShaderProgram({ vertexShader, geometryShader, fragmentShader });\n\n\tdeferredVertexShader = new Shader(\"deferred_vertex.glsl\", GL_VERTEX_SHADER);\n\tdeferredFragmentShader = new Shader(\"deferred_fragment.glsl\", GL_FRAGMENT_SHADER);\n\tdeferredShaderProgram = new ShaderProgram({ deferredVertexShader, deferredFragmentShader });\n\n\tgeometry = new Model(\"Resources\/Models\/Rock.bin\");\n\n\tgeometryObject = new GeometryObject(geometry);\n\tgeometryObject->setScale(0.01f, 0.01f, 0.01f);\n\n\ttargetPositions = new glm::vec3[geometryObject->geometry()->vertexCount()];\n\tglm::mat4 targetScaleRotation = glm::scale(glm::vec3(0.1f, 0.1f, 0.1f))*glm::rotate(90.f, glm::vec3(0.f, 1.f, 0.f));\n\n\tfor (unsigned int i = 0; i < geometryObject->geometry()->vertexCount(); i++) {\n\t\ttargetPositions[i] = glm::vec3(targetScaleRotation*glm::vec4(geometryObject->geometry()->vertices()[i].position, 1.f));\n\t}\n\n\tGLuint targetBuffer;\n\t\/\/ Generate target buffer\n\tglGenBuffers(1, &targetBuffer);\n\tglBindBuffer(GL_ARRAY_BUFFER, targetBuffer);\n\tglBufferData(GL_ARRAY_BUFFER, geometryObject->geometry()->vertexCount() * sizeof(glm::vec3), targetPositions, GL_STATIC_DRAW);\n\n\t\/\/ Target vertex layout (adds to geometry objects current layout)\n\tglBindVertexArray(geometryObject->geometry()->vertexArray());\n\tglEnableVertexAttribArray(4);\n\tglVertexAttribPointer(4, 3, GL_FLOAT, GL_FALSE, sizeof(glm::vec3), 0);\n\n\tglBindVertexArray(0);\n\tdirection = true;\n\tt = 0;\n\tplayer = new Player();\n\tplayer->setMovementSpeed(2.0f);\n\tmultipleRenderTargets = new FrameBufferObjects(deferredShaderProgram, settings::displayWidth(), settings::displayHeight());\n}\n\nMorphScene::~MorphScene() {\n\tdelete diffuse;\n\tdelete normal;\n\tdelete specular;\n\n\tdelete multipleRenderTargets;\n\tdelete deferredShaderProgram;\n\tdelete shaderProgram;\n\n\tdelete deferredVertexShader;\n\tdelete deferredFragmentShader;\n\tdelete[] targetPositions;\n\n\tdelete vertexShader;\n\tdelete geometryShader;\n\tdelete fragmentShader;\n\n\tdelete geometryObject;\n\tdelete geometry;\n\tdelete player;\n}\n\nScene::SceneEnd* MorphScene::update(double time) {\n\tplayer->update(time);\n\n\tif (input::triggered(input::CHANGE_RENDER_STATE))\n\t\tstate = !state;\n\n\treturn nullptr;\n}\n\nvoid MorphScene::render(int width, int height) {\n\tmultipleRenderTargets->bindForWriting();\n\n\tglViewport(0, 0, width, height);\n\tglClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);\n\n\tshaderProgram->use();\n\n\t\/\/ Texture unit 0 is for base images.\n\tglUniform1i(shaderProgram->uniformLocation(\"baseImage\"), 0);\n\t\/\/ Texture unit 1 is for normal map.\n\tglUniform1i(shaderProgram->uniformLocation(\"normalMap\"), 1);\n\t\/\/ Texture unit 0 is for specular map.\n\tglUniform1i(shaderProgram->uniformLocation(\"specularMap\"), 2);\n\n\tglBindVertexArray(geometryObject->geometry()->vertexArray());\n\n\tif (direction == true) {\n\t\tif (t < 1.f)\n\t\t\tt += 0.0001f*time;\n\t\telse\n\t\t\tdirection = false;\n\t}\n\telse if (direction == false){\n\t\tif (t > 0.f)\n\t\t\tt -= 0.0001f;\n\t\telse\n\t\t\tdirection = true;\n\t}\n\t\/\/T value, used for interpolation\n\tglUniform1f(shaderProgram->uniformLocation(\"tValue\"), t);\n\n\t\/\/ Base image texture\n\tglActiveTexture(GL_TEXTURE0);\n\tglBindTexture(GL_TEXTURE_2D, diffuse->textureID());\n\n\t\/\/ Normal map\n\tglActiveTexture(GL_TEXTURE1);\n\tglBindTexture(GL_TEXTURE_2D, normal->textureID());\n\n\t\/\/ Specular map\n\tglActiveTexture(GL_TEXTURE2);\n\tglBindTexture(GL_TEXTURE_2D, specular->textureID());\n\n\t\/\/ Model matrix, unique for each model.\n\tglm::mat4 model = geometryObject->modelMatrix();\n\n\t\/\/ Send the matrices to the shader.\n\tglm::mat4 view = player->camera()->view();\n\tglm::mat4 MV = view * model;\n\tglm::mat4 N = glm::transpose(glm::inverse(MV));\n\n\tglUniformMatrix4fv(shaderProgram->uniformLocation(\"modelMatrix\"), 1, GL_FALSE, &model[0][0]);\n\tglUniformMatrix4fv(shaderProgram->uniformLocation(\"viewMatrix\"), 1, GL_FALSE, &view[0][0]);\n\tglUniformMatrix3fv(shaderProgram->uniformLocation(\"normalMatrix\"), 1, GL_FALSE, &glm::mat3(N)[0][0]);\n\tglUniformMatrix4fv(shaderProgram->uniformLocation(\"projectionMatrix\"), 1, GL_FALSE, &player->camera()->projection(width, height)[0][0]);\n\n\t\/\/ Draw the triangles\n\tglDrawElements(GL_TRIANGLES, geometryObject->geometry()->indexCount(), GL_UNSIGNED_INT, (void*)0);\n\n\tif (state == 1) {\n\t\tmultipleRenderTargets->showTextures(width, height);\n\t}\n\telse if (state == 0) {\n\t\tmultipleRenderTargets->render(player->camera(), width, height);\n\t}\n}Moved morph algorithm from render to update.#include \"MorphScene.h\"\n#include \n#include \n\n#include \"FrameBufferObjects.h\"\n\n#include \n#include \"GeometryObject.h\"\n#include \n\n#include \"settings.h\"\n#include \"input.h\"\n\n#include \n#include \n#include \"Camera.h\"\n#include \"Player.h\"\n\n#include \n#include \n#include \n\n#define BUFFER_OFFSET(i) ((char *)nullptr + (i))\n\nMorphScene::MorphScene() {\n\tstate = 0;\n\n\tdiffuse = new Texture2D(\"Resources\/Models\/rock01\/diffuse.tga\");\n\tnormal = new Texture2D(\"Resources\/Models\/rock01\/normal.tga\");\n\tspecular = new Texture2D(\"Resources\/Models\/rock01\/specular.tga\");\n\n\tvertexShader = new Shader(\"morph_vertex.glsl\", GL_VERTEX_SHADER);\n\tgeometryShader = new Shader(\"default_geometry.glsl\", GL_GEOMETRY_SHADER);\n\tfragmentShader = new Shader(\"normalspecularmap_fragment.glsl\", GL_FRAGMENT_SHADER);\n\tshaderProgram = new ShaderProgram({ vertexShader, geometryShader, fragmentShader });\n\n\tdeferredVertexShader = new Shader(\"deferred_vertex.glsl\", GL_VERTEX_SHADER);\n\tdeferredFragmentShader = new Shader(\"deferred_fragment.glsl\", GL_FRAGMENT_SHADER);\n\tdeferredShaderProgram = new ShaderProgram({ deferredVertexShader, deferredFragmentShader });\n\n\tgeometry = new Model(\"Resources\/Models\/Rock.bin\");\n\n\tgeometryObject = new GeometryObject(geometry);\n\tgeometryObject->setScale(0.01f, 0.01f, 0.01f);\n\n\ttargetPositions = new glm::vec3[geometryObject->geometry()->vertexCount()];\n\tglm::mat4 targetScaleRotation = glm::scale(glm::vec3(0.1f, 0.1f, 0.1f))*glm::rotate(90.f, glm::vec3(0.f, 1.f, 0.f));\n\n\tfor (unsigned int i = 0; i < geometryObject->geometry()->vertexCount(); i++) {\n\t\ttargetPositions[i] = glm::vec3(targetScaleRotation*glm::vec4(geometryObject->geometry()->vertices()[i].position, 1.f));\n\t}\n\n\tGLuint targetBuffer;\n\t\/\/ Generate target buffer\n\tglGenBuffers(1, &targetBuffer);\n\tglBindBuffer(GL_ARRAY_BUFFER, targetBuffer);\n\tglBufferData(GL_ARRAY_BUFFER, geometryObject->geometry()->vertexCount() * sizeof(glm::vec3), targetPositions, GL_STATIC_DRAW);\n\n\t\/\/ Target vertex layout (adds to geometry objects current layout)\n\tglBindVertexArray(geometryObject->geometry()->vertexArray());\n\tglEnableVertexAttribArray(4);\n\tglVertexAttribPointer(4, 3, GL_FLOAT, GL_FALSE, sizeof(glm::vec3), 0);\n\n\tglBindVertexArray(0);\n\tdirection = true;\n\tt = 0;\n\tplayer = new Player();\n\tplayer->setMovementSpeed(2.0f);\n\tmultipleRenderTargets = new FrameBufferObjects(deferredShaderProgram, settings::displayWidth(), settings::displayHeight());\n}\n\nMorphScene::~MorphScene() {\n\tdelete diffuse;\n\tdelete normal;\n\tdelete specular;\n\n\tdelete multipleRenderTargets;\n\tdelete deferredShaderProgram;\n\tdelete shaderProgram;\n\n\tdelete deferredVertexShader;\n\tdelete deferredFragmentShader;\n\tdelete[] targetPositions;\n\n\tdelete vertexShader;\n\tdelete geometryShader;\n\tdelete fragmentShader;\n\n\tdelete geometryObject;\n\tdelete geometry;\n\tdelete player;\n}\n\nScene::SceneEnd* MorphScene::update(double time) {\n\tplayer->update(time);\n\n\tif (input::triggered(input::CHANGE_RENDER_STATE))\n\t\tstate = !state;\n\n\tif (direction == true) {\n\t\tif (t < 1.f)\n\t\t\tt += 0.3*time;\n\t\telse\n\t\t\tdirection = false;\n\t}\n\telse if (direction == false){\n\t\tif (t > 0.f)\n\t\t\tt -= 0.3*time;\n\t\telse\n\t\t\tdirection = true;\n\t}\n\n\treturn nullptr;\n}\n\nvoid MorphScene::render(int width, int height) {\n\tmultipleRenderTargets->bindForWriting();\n\n\tglViewport(0, 0, width, height);\n\tglClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);\n\n\tshaderProgram->use();\n\n\t\/\/ Texture unit 0 is for base images.\n\tglUniform1i(shaderProgram->uniformLocation(\"baseImage\"), 0);\n\t\/\/ Texture unit 1 is for normal map.\n\tglUniform1i(shaderProgram->uniformLocation(\"normalMap\"), 1);\n\t\/\/ Texture unit 0 is for specular map.\n\tglUniform1i(shaderProgram->uniformLocation(\"specularMap\"), 2);\n\n\tglBindVertexArray(geometryObject->geometry()->vertexArray());\n\n\t\/\/T value, used for interpolation\n\tglUniform1f(shaderProgram->uniformLocation(\"tValue\"), t);\n\n\t\/\/ Base image texture\n\tglActiveTexture(GL_TEXTURE0);\n\tglBindTexture(GL_TEXTURE_2D, diffuse->textureID());\n\n\t\/\/ Normal map\n\tglActiveTexture(GL_TEXTURE1);\n\tglBindTexture(GL_TEXTURE_2D, normal->textureID());\n\n\t\/\/ Specular map\n\tglActiveTexture(GL_TEXTURE2);\n\tglBindTexture(GL_TEXTURE_2D, specular->textureID());\n\n\t\/\/ Model matrix, unique for each model.\n\tglm::mat4 model = geometryObject->modelMatrix();\n\n\t\/\/ Send the matrices to the shader.\n\tglm::mat4 view = player->camera()->view();\n\tglm::mat4 MV = view * model;\n\tglm::mat4 N = glm::transpose(glm::inverse(MV));\n\n\tglUniformMatrix4fv(shaderProgram->uniformLocation(\"modelMatrix\"), 1, GL_FALSE, &model[0][0]);\n\tglUniformMatrix4fv(shaderProgram->uniformLocation(\"viewMatrix\"), 1, GL_FALSE, &view[0][0]);\n\tglUniformMatrix3fv(shaderProgram->uniformLocation(\"normalMatrix\"), 1, GL_FALSE, &glm::mat3(N)[0][0]);\n\tglUniformMatrix4fv(shaderProgram->uniformLocation(\"projectionMatrix\"), 1, GL_FALSE, &player->camera()->projection(width, height)[0][0]);\n\n\t\/\/ Draw the triangles\n\tglDrawElements(GL_TRIANGLES, geometryObject->geometry()->indexCount(), GL_UNSIGNED_INT, (void*)0);\n\n\tif (state == 1) {\n\t\tmultipleRenderTargets->showTextures(width, height);\n\t}\n\telse if (state == 0) {\n\t\tmultipleRenderTargets->render(player->camera(), width, height);\n\t}\n}<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n\n#include \"nifty\/python\/converter.hxx\"\n\n#include \"nifty\/graph\/rag\/grid_rag.hxx\"\n#include \"nifty\/graph\/rag\/grid_rag_stacked_2d.hxx\"\n\n#ifdef WITH_HDF5\n#include \"nifty\/graph\/rag\/grid_rag_hdf5.hxx\"\n#include \"nifty\/graph\/rag\/grid_rag_stacked_2d_hdf5.hxx\"\n#include \"nifty\/graph\/rag\/grid_rag_labels_hdf5.hxx\"\n#endif\n\nnamespace py = pybind11;\n\n\nnamespace nifty{\nnamespace graph{\n\n\n\n using namespace py;\n\n template\n void removeFunctions(py::class_ & clsT){\n clsT\n .def(\"insertEdge\", [](CLS * self,const uint64_t u,const uint64_t ){\n throw std::runtime_error(\"cannot insert edges into 'GridRag'\");\n })\n .def(\"insertEdges\",[](CLS * self, py::array_t pyArray) {\n throw std::runtime_error(\"cannot insert edges into 'GridRag'\");\n })\n ;\n }\n\n\n\n template\n void exportExpilictGridRagT(\n py::module & ragModule,\n const std::string & clsName,\n const std::string & facName\n ){\n typedef UndirectedGraph<> BaseGraph;\n typedef ExplicitLabelsGridRag GridRagType;\n\n auto clsT = py::class_(ragModule, clsName.c_str());\n \/\/ export the rag shape\n clsT\n .def_property_readonly(\"shape\",[](const GridRagType & self){return self.shape();})\n ;\n removeFunctions(clsT);\n\n \/\/ from labels\n ragModule.def(facName.c_str(),\n [](\n nifty::marray::PyView labels,\n const int numberOfThreads\n ){\n auto s = typename GridRagType::Settings();\n s.numberOfThreads = numberOfThreads;\n ExplicitLabels explicitLabels(labels);\n auto ptr = new GridRagType(explicitLabels, s);\n return ptr;\n },\n py::return_value_policy::take_ownership,\n py::keep_alive<0, 1>(),\n py::arg(\"labels\"),\n py::arg_t< int >(\"numberOfThreads\", -1 )\n );\n\n \/\/ from labels + serialization\n ragModule.def(facName.c_str(),\n [](\n nifty::marray::PyView labels,\n nifty::marray::PyView serialization\n ){\n\n auto startPtr = &serialization(0);\n auto lastElement = &serialization(serialization.size()-1);\n auto d = lastElement - startPtr + 1;\n\n NIFTY_CHECK_OP(d,==,serialization.size(), \"serialization must be contiguous\");\n\n\n auto s = typename GridRagType::Settings();\n s.numberOfThreads = -1;\n ExplicitLabels explicitLabels(labels);\n auto ptr = new GridRagType(explicitLabels,startPtr, s);\n return ptr;\n },\n py::return_value_policy::take_ownership,\n py::keep_alive<0, 1>(),\n py::arg(\"labels\"),\n py::arg(\"serialization\")\n );\n\n }\n\n #ifdef WITH_HDF5\n template\n void exportHdf5GridRagT(\n py::module & ragModule,\n const std::string & clsName,\n const std::string & facName\n ){\n typedef UndirectedGraph<> BaseGraph;\n typedef Hdf5Labels LabelsProxyType;\n typedef GridRag GridRagType;\n\n\n const auto labelsProxyClsName = clsName + std::string(\"LabelsProxy\");\n const auto labelsProxyFacName = facName + std::string(\"LabelsProxy\");\n py::class_(ragModule, labelsProxyClsName.c_str())\n .def(\"hdf5Array\",&LabelsProxyType::hdf5Array,py::return_value_policy::reference)\n ;\n\n ragModule.def(labelsProxyFacName.c_str(),\n [](\n const hdf5::Hdf5Array & hdf5Array,\n const int64_t numberOfLabels\n ){\n auto ptr = new LabelsProxyType(hdf5Array, numberOfLabels);\n return ptr;\n },\n py::return_value_policy::take_ownership,\n py::keep_alive<0, 1>(),\n py::arg(\"labels\"),\n py::arg(\"numberOfLabels\")\n );\n\n\n\n auto clsT = py::class_(ragModule, clsName.c_str());\n clsT\n .def(\"labelsProxy\",&GridRagType::labelsProxy,py::return_value_policy::reference)\n .def_property_readonly(\"shape\",[](const GridRagType & self){return self.shape();})\n ;\n\n removeFunctions(clsT);\n\n\n\n ragModule.def(facName.c_str(),\n [](\n const LabelsProxyType & labelsProxy,\n std::vector blockShape,\n const int numberOfThreads\n ){\n auto s = typename GridRagType::Settings();\n s.numberOfThreads = numberOfThreads;\n\n if(blockShape.size() == DIM){\n std::copy(blockShape.begin(), blockShape.end(), s.blockShape.begin());\n }\n else if(blockShape.size() == 1){\n std::fill(s.blockShape.begin(), s.blockShape.end(), blockShape[0]);\n }\n else if(blockShape.size() != 0){\n throw std::runtime_error(\"block shape has a non matching shape\");\n }\n\n auto ptr = new GridRagType(labelsProxy, s);\n return ptr;\n },\n py::return_value_policy::take_ownership,\n py::keep_alive<0, 1>(),\n py::arg(\"labelsProxy\"),\n py::arg_t< std::vector >(\"blockShape\", std::vector() ),\n py::arg_t< int >(\"numberOfThreads\", -1 )\n );\n\n\n\n ragModule.def(facName.c_str(),\n [](\n const LabelsProxyType & labelsProxy,\n nifty::marray::PyView serialization\n ){\n\n auto startPtr = &serialization(0);\n auto lastElement = &serialization(serialization.size()-1);\n auto d = lastElement - startPtr + 1;\n\n NIFTY_CHECK_OP(d,==,serialization.size(), \"serialization must be contiguous\");\n\n\n auto s = typename GridRagType::Settings();\n s.numberOfThreads = -1;\n\n auto ptr = new GridRagType(labelsProxy, startPtr, s);\n return ptr;\n },\n py::return_value_policy::take_ownership,\n py::keep_alive<0, 1>(),\n py::arg(\"labels\"),\n py::arg(\"serialization\")\n );\n\n }\n\n template\n void exportHdf5GridRagStacked2D(\n py::module & ragModule,\n const std::string & clsName,\n const std::string & facName\n ){\n py::object baseGraphPyCls = ragModule.attr(\"GridRagHdf5Labels3D\");\n\n\n\n\n typedef Hdf5Labels<3, LABELS> LabelsProxyType;\n typedef GridRag<3, LabelsProxyType > BaseGraph;\n typedef GridRagStacked2D GridRagType;\n\n\n\n\n auto clsT = py::class_(ragModule, clsName.c_str());\n clsT\n .def(\"labelsProxy\",&GridRagType::labelsProxy,py::return_value_policy::reference)\n .def(\"minMaxLabelPerSlice\",[](const GridRagType & self){\n const auto & shape = self.shape();\n nifty::marray::PyView out({std::size_t(shape[0]),std::size_t(2)});\n for(auto sliceIndex = 0; sliceIndex out({std::size_t(shape[0])});\n for(auto sliceIndex = 0; sliceIndex out({std::size_t(shape[0])});\n for(auto sliceIndex = 0; sliceIndex out({std::size_t(shape[0])});\n for(auto sliceIndex = 0; sliceIndex out({std::size_t(shape[0])});\n for(auto sliceIndex = 0; sliceIndex out({std::size_t(shape[0])});\n for(auto sliceIndex = 0; sliceIndex(clsT);\n\n ragModule.def(facName.c_str(),\n [](\n const LabelsProxyType & labelsProxy,\n const int numberOfThreads\n ){\n auto s = typename GridRagType::Settings();\n s.numberOfThreads = numberOfThreads;\n\n auto ptr = new GridRagType(labelsProxy, s);\n return ptr;\n },\n py::return_value_policy::take_ownership,\n py::keep_alive<0, 1>(),\n py::arg(\"labelsProxy\"),\n py::arg_t< int >(\"numberOfThreads\", -1 )\n );\n\n }\n #endif\n\n\n template\n void exportExplicitGridRagStacked2D(\n py::module & ragModule,\n const std::string & clsName,\n const std::string & facName\n ){\n py::object baseGraphPyCls = ragModule.attr(\"ExplicitLabelsGridRag3D\");\n\n typedef ExplicitLabels<3, LABELS> LabelsProxyType;\n typedef GridRag<3, LabelsProxyType > BaseGraph;\n typedef GridRagStacked2D GridRagType;\n\n\n auto clsT = py::class_(ragModule, clsName.c_str());\n clsT\n \/\/.def(\"labelsProxy\",&GridRagType::labelsProxy,py::return_value_policy::reference)\n .def(\"minMaxLabelPerSlice\",[](const GridRagType & self){\n const auto & shape = self.shape();\n nifty::marray::PyView out({std::size_t(shape[0]),std::size_t(2)});\n for(auto sliceIndex = 0; sliceIndex out({std::size_t(shape[0])});\n for(auto sliceIndex = 0; sliceIndex out({std::size_t(shape[0])});\n for(auto sliceIndex = 0; sliceIndex out({std::size_t(shape[0])});\n for(auto sliceIndex = 0; sliceIndex out({std::size_t(shape[0])});\n for(auto sliceIndex = 0; sliceIndex out({std::size_t(shape[0])});\n for(auto sliceIndex = 0; sliceIndex(clsT);\n\n\n\n ragModule.def(facName.c_str(),\n [](\n nifty::marray::PyView labels,\n const int numberOfThreads\n ){\n auto s = typename GridRagType::Settings();\n s.numberOfThreads = numberOfThreads;\n ExplicitLabels<3, LABELS> explicitLabels(labels);\n auto ptr = new GridRagType(explicitLabels, s);\n return ptr;\n },\n py::return_value_policy::take_ownership,\n py::keep_alive<0, 1>(),\n py::arg(\"labels\"),\n py::arg_t< int >(\"numberOfThreads\", -1 )\n );\n\n }\n\n\n void exportGridRag(py::module & ragModule) {\n\n exportExpilictGridRagT<2, uint32_t>(ragModule, \"ExplicitLabelsGridRag2D\", \"explicitLabelsGridRag2D\");\n exportExpilictGridRagT<3, uint32_t>(ragModule, \"ExplicitLabelsGridRag3D\", \"explicitLabelsGridRag3D\");\n\n #ifdef WITH_HDF5\n exportHdf5GridRagT<2, uint32_t>(ragModule, \"GridRagHdf5Labels2D\", \"gridRag2DHdf5\");\n exportHdf5GridRagT<3, uint32_t>(ragModule, \"GridRagHdf5Labels3D\", \"gridRag3DHdf5\");\n\n exportExplicitGridRagStacked2D(ragModule, \"GridRagStacked2DExplicit\", \"gridRagStacked2DExplicitImpl\");\n exportHdf5GridRagStacked2D(ragModule, \"GridRagStacked2DHdf5\", \"gridRagStacked2DHdf5Impl\");\n #endif\n }\n\n\n} \/\/ end namespace graph\n} \/\/ end namespace nifty\nFix rag imports#include \n#include \n#include \n\n#include \"nifty\/python\/converter.hxx\"\n\n#include \"nifty\/graph\/rag\/grid_rag.hxx\"\n\n#ifdef WITH_HDF5\n#include \"nifty\/graph\/rag\/grid_rag_hdf5.hxx\"\n#include \"nifty\/graph\/rag\/grid_rag_labels_hdf5.hxx\"\n#endif\n\nnamespace py = pybind11;\n\n\nnamespace nifty{\nnamespace graph{\n\n\n\n using namespace py;\n \n template\n void removeFunctions(py::class_ & clsT){\n clsT\n .def(\"insertEdge\", [](CLS * self,const uint64_t u,const uint64_t ){\n throw std::runtime_error(\"cannot insert edges into 'GridRag'\");\n })\n .def(\"insertEdges\",[](CLS * self, py::array_t pyArray) {\n throw std::runtime_error(\"cannot insert edges into 'GridRag'\");\n })\n ;\n }\n\n \n\n template\n void exportExpilictGridRagT(\n py::module & ragModule, \n const std::string & clsName,\n const std::string & facName\n ){\n typedef UndirectedGraph<> BaseGraph;\n typedef ExplicitLabelsGridRag GridRagType;\n\n auto clsT = py::class_(ragModule, clsName.c_str());\n \/\/ export the rag shape\n clsT\n .def_property_readonly(\"shape\",[](const GridRagType & self){return self.shape();})\n ;\n removeFunctions(clsT);\n\n \/\/ from labels\n ragModule.def(facName.c_str(),\n [](\n nifty::marray::PyView labels,\n const int numberOfThreads\n ){\n auto s = typename GridRagType::Settings();\n s.numberOfThreads = numberOfThreads;\n ExplicitLabels explicitLabels(labels);\n auto ptr = new GridRagType(explicitLabels, s);\n return ptr;\n },\n py::return_value_policy::take_ownership,\n py::keep_alive<0, 1>(),\n py::arg(\"labels\"),\n py::arg_t< int >(\"numberOfThreads\", -1 )\n );\n\n \/\/ from labels + serialization\n ragModule.def(facName.c_str(),\n [](\n nifty::marray::PyView labels,\n nifty::marray::PyView serialization\n ){\n\n auto startPtr = &serialization(0);\n auto lastElement = &serialization(serialization.size()-1);\n auto d = lastElement - startPtr + 1;\n\n NIFTY_CHECK_OP(d,==,serialization.size(), \"serialization must be contiguous\");\n\n\n auto s = typename GridRagType::Settings();\n s.numberOfThreads = -1;\n ExplicitLabels explicitLabels(labels);\n auto ptr = new GridRagType(explicitLabels,startPtr, s);\n return ptr;\n },\n py::return_value_policy::take_ownership,\n py::keep_alive<0, 1>(),\n py::arg(\"labels\"),\n py::arg(\"serialization\")\n );\n\n }\n\n #ifdef WITH_HDF5\n template\n void exportHdf5GridRagT(\n py::module & ragModule, \n const std::string & clsName,\n const std::string & facName\n ){\n typedef UndirectedGraph<> BaseGraph;\n typedef Hdf5Labels LabelsProxyType;\n typedef GridRag GridRagType;\n\n\n const auto labelsProxyClsName = clsName + std::string(\"LabelsProxy\");\n const auto labelsProxyFacName = facName + std::string(\"LabelsProxy\");\n py::class_(ragModule, labelsProxyClsName.c_str())\n .def(\"hdf5Array\",&LabelsProxyType::hdf5Array,py::return_value_policy::reference)\n ;\n\n ragModule.def(labelsProxyFacName.c_str(),\n [](\n const hdf5::Hdf5Array & hdf5Array,\n const int64_t numberOfLabels\n ){\n auto ptr = new LabelsProxyType(hdf5Array, numberOfLabels);\n return ptr;\n },\n py::return_value_policy::take_ownership,\n py::keep_alive<0, 1>(),\n py::arg(\"labels\"),\n py::arg(\"numberOfLabels\")\n );\n\n\n\n auto clsT = py::class_(ragModule, clsName.c_str());\n clsT\n .def(\"labelsProxy\",&GridRagType::labelsProxy,py::return_value_policy::reference)\n .def_property_readonly(\"shape\",[](const GridRagType & self){return self.shape();})\n ;\n\n removeFunctions(clsT);\n\n\n\n ragModule.def(facName.c_str(),\n [](\n const LabelsProxyType & labelsProxy,\n std::vector blockShape,\n const int numberOfThreads\n ){\n auto s = typename GridRagType::Settings();\n s.numberOfThreads = numberOfThreads;\n\n if(blockShape.size() == DIM){\n std::copy(blockShape.begin(), blockShape.end(), s.blockShape.begin());\n }\n else if(blockShape.size() == 1){\n std::fill(s.blockShape.begin(), s.blockShape.end(), blockShape[0]);\n }\n else if(blockShape.size() != 0){\n throw std::runtime_error(\"block shape has a non matching shape\");\n }\n\n auto ptr = new GridRagType(labelsProxy, s);\n return ptr;\n },\n py::return_value_policy::take_ownership,\n py::keep_alive<0, 1>(),\n py::arg(\"labelsProxy\"),\n py::arg_t< std::vector >(\"blockShape\", std::vector() ),\n py::arg_t< int >(\"numberOfThreads\", -1 )\n );\n\n\n\n ragModule.def(facName.c_str(),\n [](\n const LabelsProxyType & labelsProxy,\n nifty::marray::PyView serialization\n ){\n\n auto startPtr = &serialization(0);\n auto lastElement = &serialization(serialization.size()-1);\n auto d = lastElement - startPtr + 1;\n\n NIFTY_CHECK_OP(d,==,serialization.size(), \"serialization must be contiguous\");\n\n\n auto s = typename GridRagType::Settings();\n s.numberOfThreads = -1;\n \n auto ptr = new GridRagType(labelsProxy, startPtr, s);\n return ptr;\n },\n py::return_value_policy::take_ownership,\n py::keep_alive<0, 1>(),\n py::arg(\"labels\"),\n py::arg(\"serialization\")\n );\n\n }\n #endif\n\n\n void exportGridRag(py::module & ragModule) {\n exportExpilictGridRagT<2, uint32_t>(ragModule, \"ExplicitLabelsGridRag2D\", \"explicitLabelsGridRag2D\");\n exportExpilictGridRagT<3, uint32_t>(ragModule, \"ExplicitLabelsGridRag3D\", \"explicitLabelsGridRag3D\");\n #ifdef WITH_HDF5\n exportHdf5GridRagT<2, uint32_t>(ragModule, \"GridRagHdf5Labels2D\", \"gridRag2DHdf5\");\n exportHdf5GridRagT<3, uint32_t>(ragModule, \"GridRagHdf5Labels3D\", \"gridRag3DHdf5\");\n #endif\n }\n \n\n} \/\/ end namespace graph\n} \/\/ end namespace nifty\n<|endoftext|>"} {"text":"\/****************************************************************************\n**\n** Copyright (C) 2013 Digia Plc and\/or its subsidiary(-ies).\n** Contact: http:\/\/www.qt-project.org\/legal\n**\n** This file is part of the QtQml module of the Qt Toolkit.\n**\n** $QT_BEGIN_LICENSE:LGPL$\n** Commercial License Usage\n** Licensees holding valid commercial Qt licenses may use this file in\n** accordance with the commercial license agreement provided with the\n** Software or, alternatively, in accordance with the terms contained in\n** a written agreement between you and Digia. For licensing terms and\n** conditions see http:\/\/qt.digia.com\/licensing. For further information\n** use the contact form at http:\/\/qt.digia.com\/contact-us.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Digia gives you certain additional\n** rights. These rights are described in the Digia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n** GNU General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU\n** General Public License version 3.0 as published by the Free Software\n** Foundation and appearing in the file LICENSE.GPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU General Public License version 3.0 requirements will be\n** met: http:\/\/www.gnu.org\/copyleft\/gpl.html.\n**\n**\n** $QT_END_LICENSE$\n**\n****************************************************************************\/\n\n#include \"qqmldebugservice_p.h\"\n#include \"qqmldebugservice_p_p.h\"\n#include \"qqmldebugserver_p.h\"\n#include \n#include \n\n#include \n#include \n#include \n\nQT_BEGIN_NAMESPACE\n\nQQmlDebugServicePrivate::QQmlDebugServicePrivate()\n : server(0)\n{\n}\n\nQQmlDebugService::QQmlDebugService(const QString &name, float version, QObject *parent)\n : QObject(*(new QQmlDebugServicePrivate), parent)\n{\n Q_D(QQmlDebugService);\n d->name = name;\n d->version = version;\n d->server = QQmlDebugServer::instance();\n d->state = QQmlDebugService::NotConnected;\n\n\n}\n\nQQmlDebugService::QQmlDebugService(QQmlDebugServicePrivate &dd,\n const QString &name, float version, QObject *parent)\n : QObject(dd, parent)\n{\n Q_D(QQmlDebugService);\n d->name = name;\n d->version = version;\n d->server = QQmlDebugServer::instance();\n d->state = QQmlDebugService::NotConnected;\n}\n\n\/**\n Registers the service. This should be called in the constructor of the inherited class. From\n then on the service might get asynchronous calls to messageReceived().\n *\/\nQQmlDebugService::State QQmlDebugService::registerService()\n{\n Q_D(QQmlDebugService);\n if (!d->server)\n return NotConnected;\n\n if (d->server->serviceNames().contains(d->name)) {\n qWarning() << \"QQmlDebugService: Conflicting plugin name\" << d->name;\n d->server = 0;\n } else {\n d->server->addService(this);\n }\n return state();\n}\n\nQQmlDebugService::~QQmlDebugService()\n{\n Q_D(const QQmlDebugService);\n if (d->server) {\n d->server->removeService(this);\n }\n}\n\nQString QQmlDebugService::name() const\n{\n Q_D(const QQmlDebugService);\n return d->name;\n}\n\nfloat QQmlDebugService::version() const\n{\n Q_D(const QQmlDebugService);\n return d->version;\n}\n\nQQmlDebugService::State QQmlDebugService::state() const\n{\n Q_D(const QQmlDebugService);\n return d->state;\n}\n\nnamespace {\n\nstruct ObjectReference\n{\n QPointer object;\n int id;\n};\n\nstruct ObjectReferenceHash\n{\n ObjectReferenceHash() : nextId(0) {}\n\n QHash objects;\n QHash ids;\n\n int nextId;\n};\n\n}\nQ_GLOBAL_STATIC(ObjectReferenceHash, objectReferenceHash)\n\n\n\/*!\n Returns a unique id for \\a object. Calling this method multiple times\n for the same object will return the same id.\n*\/\nint QQmlDebugService::idForObject(QObject *object)\n{\n if (!object)\n return -1;\n\n ObjectReferenceHash *hash = objectReferenceHash();\n QHash::Iterator iter =\n hash->objects.find(object);\n\n if (iter == hash->objects.end()) {\n int id = hash->nextId++;\n\n hash->ids.insert(id, object);\n iter = hash->objects.insert(object, ObjectReference());\n iter->object = object;\n iter->id = id;\n } else if (iter->object != object) {\n int id = hash->nextId++;\n\n hash->ids.remove(iter->id);\n\n hash->ids.insert(id, object);\n iter->object = object;\n iter->id = id;\n }\n return iter->id;\n}\n\n\/*!\n Returns the object for unique \\a id. If the object has not previously been\n assigned an id, through idForObject(), then 0 is returned. If the object\n has been destroyed, 0 is returned.\n*\/\nQObject *QQmlDebugService::objectForId(int id)\n{\n ObjectReferenceHash *hash = objectReferenceHash();\n\n QHash::Iterator iter = hash->ids.find(id);\n if (iter == hash->ids.end())\n return 0;\n\n\n QHash::Iterator objIter =\n hash->objects.find(*iter);\n Q_ASSERT(objIter != hash->objects.end());\n\n if (objIter->object == 0) {\n hash->ids.erase(iter);\n hash->objects.erase(objIter);\n \/\/ run a loop to remove other invalid objects\n removeInvalidObjectsFromHash();\n return 0;\n } else {\n return *iter;\n }\n}\n\n\/*!\n Returns a list of objects matching the given filename, line and column.\n*\/\nQList QQmlDebugService::objectForLocationInfo(const QString &filename,\n int lineNumber, int columnNumber)\n{\n ObjectReferenceHash *hash = objectReferenceHash();\n QList objects;\n QHash::Iterator iter;\n for (iter = hash->ids.begin(); iter != hash->ids.end(); ++iter) {\n QQmlData *ddata = QQmlData::get(iter.value());\n if (!ddata || !ddata->outerContext)\n continue;\n \/\/column number may be different due to qmlrewriter\n if (QFileInfo(ddata->outerContext->urlString).fileName() == filename &&\n ddata->lineNumber == lineNumber &&\n ddata->columnNumber >= columnNumber) {\n QHash::Iterator objIter =\n hash->objects.find(*iter);\n Q_ASSERT(objIter != hash->objects.end());\n\n if (objIter->object == 0) {\n hash->ids.erase(iter);\n hash->objects.erase(objIter);\n } else {\n objects << *iter;\n }\n }\n }\n return objects;\n}\n\nvoid QQmlDebugService::removeInvalidObjectsFromHash()\n{\n ObjectReferenceHash *hash = objectReferenceHash();\n QHash::Iterator iter = hash->ids.begin();\n while (iter != hash->ids.end()) {\n QHash::Iterator objIter =\n hash->objects.find(*iter);\n Q_ASSERT(objIter != hash->objects.end());\n\n if (objIter->object == 0) {\n iter = hash->ids.erase(iter);\n hash->objects.erase(objIter);\n } else {\n ++iter;\n }\n }\n}\n\nvoid QQmlDebugService::clearObjectsFromHash()\n{\n ObjectReferenceHash *hash = objectReferenceHash();\n hash->ids.clear();\n hash->objects.clear();\n}\n\nbool QQmlDebugService::isDebuggingEnabled()\n{\n return QQmlDebugServer::instance() != 0;\n}\n\nbool QQmlDebugService::hasDebuggingClient()\n{\n return QQmlDebugServer::instance() != 0\n && QQmlDebugServer::instance()->hasDebuggingClient();\n}\n\nbool QQmlDebugService::blockingMode()\n{\n return QQmlDebugServer::instance() != 0\n && QQmlDebugServer::instance()->blockingMode();\n}\n\nQString QQmlDebugService::objectToString(QObject *obj)\n{\n if(!obj)\n return QStringLiteral(\"NULL\");\n\n QString objectName = obj->objectName();\n if(objectName.isEmpty())\n objectName = QStringLiteral(\"\");\n\n QString rv = QString::fromUtf8(obj->metaObject()->className()) +\n QLatin1String(\": \") + objectName;\n\n return rv;\n}\n\nvoid QQmlDebugService::sendMessage(const QByteArray &message)\n{\n sendMessages(QList() << message);\n}\n\nvoid QQmlDebugService::sendMessages(const QList &messages)\n{\n Q_D(QQmlDebugService);\n\n if (state() != Enabled)\n return;\n\n d->server->sendMessages(this, messages);\n}\n\nvoid QQmlDebugService::stateAboutToBeChanged(State)\n{\n}\n\nvoid QQmlDebugService::stateChanged(State)\n{\n}\n\nvoid QQmlDebugService::messageReceived(const QByteArray &)\n{\n}\n\nQQmlDebugStream::QQmlDebugStream()\n : QDataStream()\n{\n setVersion(QQmlDebugServer::s_dataStreamVersion);\n}\n\nQQmlDebugStream::QQmlDebugStream(QIODevice *d)\n : QDataStream(d)\n{\n setVersion(QQmlDebugServer::s_dataStreamVersion);\n}\n\nQQmlDebugStream::QQmlDebugStream(QByteArray *ba, QIODevice::OpenMode flags)\n : QDataStream(ba, flags)\n{\n setVersion(QQmlDebugServer::s_dataStreamVersion);\n}\n\nQQmlDebugStream::QQmlDebugStream(const QByteArray &ba)\n : QDataStream(ba)\n{\n setVersion(QQmlDebugServer::s_dataStreamVersion);\n}\n\nQT_END_NAMESPACE\nFix crash in QQmlDebugService::objectForLocationInfo()\/****************************************************************************\n**\n** Copyright (C) 2013 Digia Plc and\/or its subsidiary(-ies).\n** Contact: http:\/\/www.qt-project.org\/legal\n**\n** This file is part of the QtQml module of the Qt Toolkit.\n**\n** $QT_BEGIN_LICENSE:LGPL$\n** Commercial License Usage\n** Licensees holding valid commercial Qt licenses may use this file in\n** accordance with the commercial license agreement provided with the\n** Software or, alternatively, in accordance with the terms contained in\n** a written agreement between you and Digia. For licensing terms and\n** conditions see http:\/\/qt.digia.com\/licensing. For further information\n** use the contact form at http:\/\/qt.digia.com\/contact-us.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Digia gives you certain additional\n** rights. These rights are described in the Digia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n** GNU General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU\n** General Public License version 3.0 as published by the Free Software\n** Foundation and appearing in the file LICENSE.GPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU General Public License version 3.0 requirements will be\n** met: http:\/\/www.gnu.org\/copyleft\/gpl.html.\n**\n**\n** $QT_END_LICENSE$\n**\n****************************************************************************\/\n\n#include \"qqmldebugservice_p.h\"\n#include \"qqmldebugservice_p_p.h\"\n#include \"qqmldebugserver_p.h\"\n#include \n#include \n\n#include \n#include \n#include \n\nQT_BEGIN_NAMESPACE\n\nQQmlDebugServicePrivate::QQmlDebugServicePrivate()\n : server(0)\n{\n}\n\nQQmlDebugService::QQmlDebugService(const QString &name, float version, QObject *parent)\n : QObject(*(new QQmlDebugServicePrivate), parent)\n{\n Q_D(QQmlDebugService);\n d->name = name;\n d->version = version;\n d->server = QQmlDebugServer::instance();\n d->state = QQmlDebugService::NotConnected;\n\n\n}\n\nQQmlDebugService::QQmlDebugService(QQmlDebugServicePrivate &dd,\n const QString &name, float version, QObject *parent)\n : QObject(dd, parent)\n{\n Q_D(QQmlDebugService);\n d->name = name;\n d->version = version;\n d->server = QQmlDebugServer::instance();\n d->state = QQmlDebugService::NotConnected;\n}\n\n\/**\n Registers the service. This should be called in the constructor of the inherited class. From\n then on the service might get asynchronous calls to messageReceived().\n *\/\nQQmlDebugService::State QQmlDebugService::registerService()\n{\n Q_D(QQmlDebugService);\n if (!d->server)\n return NotConnected;\n\n if (d->server->serviceNames().contains(d->name)) {\n qWarning() << \"QQmlDebugService: Conflicting plugin name\" << d->name;\n d->server = 0;\n } else {\n d->server->addService(this);\n }\n return state();\n}\n\nQQmlDebugService::~QQmlDebugService()\n{\n Q_D(const QQmlDebugService);\n if (d->server) {\n d->server->removeService(this);\n }\n}\n\nQString QQmlDebugService::name() const\n{\n Q_D(const QQmlDebugService);\n return d->name;\n}\n\nfloat QQmlDebugService::version() const\n{\n Q_D(const QQmlDebugService);\n return d->version;\n}\n\nQQmlDebugService::State QQmlDebugService::state() const\n{\n Q_D(const QQmlDebugService);\n return d->state;\n}\n\nnamespace {\n\nstruct ObjectReference\n{\n QPointer object;\n int id;\n};\n\nstruct ObjectReferenceHash\n{\n ObjectReferenceHash() : nextId(0) {}\n\n QHash objects;\n QHash ids;\n\n int nextId;\n};\n\n}\nQ_GLOBAL_STATIC(ObjectReferenceHash, objectReferenceHash)\n\n\n\/*!\n Returns a unique id for \\a object. Calling this method multiple times\n for the same object will return the same id.\n*\/\nint QQmlDebugService::idForObject(QObject *object)\n{\n if (!object)\n return -1;\n\n ObjectReferenceHash *hash = objectReferenceHash();\n QHash::Iterator iter =\n hash->objects.find(object);\n\n if (iter == hash->objects.end()) {\n int id = hash->nextId++;\n\n hash->ids.insert(id, object);\n iter = hash->objects.insert(object, ObjectReference());\n iter->object = object;\n iter->id = id;\n } else if (iter->object != object) {\n int id = hash->nextId++;\n\n hash->ids.remove(iter->id);\n\n hash->ids.insert(id, object);\n iter->object = object;\n iter->id = id;\n }\n return iter->id;\n}\n\n\/*!\n Returns the object for unique \\a id. If the object has not previously been\n assigned an id, through idForObject(), then 0 is returned. If the object\n has been destroyed, 0 is returned.\n*\/\nQObject *QQmlDebugService::objectForId(int id)\n{\n ObjectReferenceHash *hash = objectReferenceHash();\n\n QHash::Iterator iter = hash->ids.find(id);\n if (iter == hash->ids.end())\n return 0;\n\n\n QHash::Iterator objIter =\n hash->objects.find(*iter);\n Q_ASSERT(objIter != hash->objects.end());\n\n if (objIter->object == 0) {\n hash->ids.erase(iter);\n hash->objects.erase(objIter);\n \/\/ run a loop to remove other invalid objects\n removeInvalidObjectsFromHash();\n return 0;\n } else {\n return *iter;\n }\n}\n\n\/*!\n Returns a list of objects matching the given filename, line and column.\n*\/\nQList QQmlDebugService::objectForLocationInfo(const QString &filename,\n int lineNumber, int columnNumber)\n{\n ObjectReferenceHash *hash = objectReferenceHash();\n QList objects;\n QHash::Iterator iter = hash->ids.begin();\n while (iter != hash->ids.end()) {\n QHash::Iterator objIter =\n hash->objects.find(*iter);\n Q_ASSERT(objIter != hash->objects.end());\n\n if (objIter->object == 0) {\n iter = hash->ids.erase(iter);\n hash->objects.erase(objIter);\n } else {\n QQmlData *ddata = QQmlData::get(iter.value());\n if (ddata && ddata->outerContext) {\n if (QFileInfo(ddata->outerContext->urlString).fileName() == filename &&\n ddata->lineNumber == lineNumber &&\n ddata->columnNumber >= columnNumber) {\n objects << *iter;\n }\n }\n ++iter;\n }\n }\n return objects;\n}\n\nvoid QQmlDebugService::removeInvalidObjectsFromHash()\n{\n ObjectReferenceHash *hash = objectReferenceHash();\n QHash::Iterator iter = hash->ids.begin();\n while (iter != hash->ids.end()) {\n QHash::Iterator objIter =\n hash->objects.find(*iter);\n Q_ASSERT(objIter != hash->objects.end());\n\n if (objIter->object == 0) {\n iter = hash->ids.erase(iter);\n hash->objects.erase(objIter);\n } else {\n ++iter;\n }\n }\n}\n\nvoid QQmlDebugService::clearObjectsFromHash()\n{\n ObjectReferenceHash *hash = objectReferenceHash();\n hash->ids.clear();\n hash->objects.clear();\n}\n\nbool QQmlDebugService::isDebuggingEnabled()\n{\n return QQmlDebugServer::instance() != 0;\n}\n\nbool QQmlDebugService::hasDebuggingClient()\n{\n return QQmlDebugServer::instance() != 0\n && QQmlDebugServer::instance()->hasDebuggingClient();\n}\n\nbool QQmlDebugService::blockingMode()\n{\n return QQmlDebugServer::instance() != 0\n && QQmlDebugServer::instance()->blockingMode();\n}\n\nQString QQmlDebugService::objectToString(QObject *obj)\n{\n if(!obj)\n return QStringLiteral(\"NULL\");\n\n QString objectName = obj->objectName();\n if(objectName.isEmpty())\n objectName = QStringLiteral(\"\");\n\n QString rv = QString::fromUtf8(obj->metaObject()->className()) +\n QLatin1String(\": \") + objectName;\n\n return rv;\n}\n\nvoid QQmlDebugService::sendMessage(const QByteArray &message)\n{\n sendMessages(QList() << message);\n}\n\nvoid QQmlDebugService::sendMessages(const QList &messages)\n{\n Q_D(QQmlDebugService);\n\n if (state() != Enabled)\n return;\n\n d->server->sendMessages(this, messages);\n}\n\nvoid QQmlDebugService::stateAboutToBeChanged(State)\n{\n}\n\nvoid QQmlDebugService::stateChanged(State)\n{\n}\n\nvoid QQmlDebugService::messageReceived(const QByteArray &)\n{\n}\n\nQQmlDebugStream::QQmlDebugStream()\n : QDataStream()\n{\n setVersion(QQmlDebugServer::s_dataStreamVersion);\n}\n\nQQmlDebugStream::QQmlDebugStream(QIODevice *d)\n : QDataStream(d)\n{\n setVersion(QQmlDebugServer::s_dataStreamVersion);\n}\n\nQQmlDebugStream::QQmlDebugStream(QByteArray *ba, QIODevice::OpenMode flags)\n : QDataStream(ba, flags)\n{\n setVersion(QQmlDebugServer::s_dataStreamVersion);\n}\n\nQQmlDebugStream::QQmlDebugStream(const QByteArray &ba)\n : QDataStream(ba)\n{\n setVersion(QQmlDebugServer::s_dataStreamVersion);\n}\n\nQT_END_NAMESPACE\n<|endoftext|>"} {"text":"\/\/ El Leave One Out estima mejor el error promedio\n\/\/ pero peor el desvío. Elaborar por qué.\n\n#include \"multicapa.cpp\"\n#include \"particionar.cpp\"\n#include \"..\/config.hpp\"\n\nint main()\n{\n arma_rng::set_seed_random();\n\n mat datos;\n string rutaBaseDatos = config::sourceDir + \"\/guia1\/icgtp1datos\/\";\n datos.load(rutaBaseDatos + \"irisbin.csv\");\n\n ifstream ifs{config::sourceDir + \"\/guia1\/parametrosIris.txt\"};\n ic::ParametrosMulticapa parametros;\n if (!(ifs >> parametros))\n throw runtime_error(\"No se pudo cargar el archivo de parámetros\");\n\n \/\/ Leave K Out\n\n {\n vector particiones = ic::cargarParticiones(rutaBaseDatos + \"particionesIrisKOut\/\", 10);\n vec errores, epocas;\n errores.resize(particiones.size());\n epocas.resize(particiones.size());\n\n#pragma omp parallel for\n for (unsigned int i = 0; i < particiones.size(); ++i) {\n vector pesos;\n int epoca;\n tie(pesos, ignore, epoca) = ic::entrenarMulticapa(parametros.estructuraRed,\n datos.rows(particiones[i].first),\n parametros.nEpocas,\n parametros.tasaAprendizaje,\n parametros.inercia,\n parametros.toleranciaError);\n\n const double tasaError = ic::errorPrueba(pesos,\n datos.rows(particiones[i].second));\n\n epocas(i) = epoca;\n errores(i) = tasaError;\n }\n\n cout << \"Iris multicapa, Leave K Out\" << endl\n << \"Error promedio: \" << mean(errores) << endl\n << \"Desvío estándar del error: \" << stddev(errores) << endl\n << \"N° de épocas promedio que tarda en converger: \" << mean(epocas) << endl\n << \"Desvío estándar de lo anterior: \" << stddev(epocas) << endl;\n }\n\n \/\/ Leave One Out\n\n {\n vector particiones = ic::cargarParticiones(rutaBaseDatos + \"particionesIris1Out\/\", 150);\n vec errores, epocas;\n errores.resize(particiones.size());\n epocas.resize(particiones.size());\n\n#pragma omp parallel for\n for (unsigned int i = 0; i < particiones.size(); ++i) {\n vector pesos;\n int epoca;\n tie(pesos, ignore, epoca) = ic::entrenarMulticapa(parametros.estructuraRed,\n datos.rows(particiones[i].first),\n parametros.nEpocas,\n parametros.tasaAprendizaje,\n parametros.inercia,\n parametros.toleranciaError);\n\n const double tasaError = ic::errorPrueba(pesos,\n datos.rows(particiones[i].second));\n\n epocas(i) = epoca;\n errores(i) = tasaError;\n }\n\n cout << \"\\nIris multicapa, Leave One Out\" << endl\n << \"Error promedio: \" << mean(errores) << endl\n << \"Desvío estándar del error: \" << stddev(errores) << endl\n << \"N° de épocas promedio que tarda en converger: \" << mean(epocas) << endl\n << \"Desvío estándar de lo anterior: \" << stddev(epocas) << endl;\n }\n\n return 0;\n}\nGuia 1 - Ejercicio 4: Aclarar que el error medido es en la prueba\/\/ El Leave One Out estima mejor el error promedio\n\/\/ pero peor el desvío. Elaborar por qué.\n\n#include \"multicapa.cpp\"\n#include \"particionar.cpp\"\n#include \"..\/config.hpp\"\n\nint main()\n{\n arma_rng::set_seed_random();\n\n mat datos;\n string rutaBaseDatos = config::sourceDir + \"\/guia1\/icgtp1datos\/\";\n datos.load(rutaBaseDatos + \"irisbin.csv\");\n\n ifstream ifs{config::sourceDir + \"\/guia1\/parametrosIris.txt\"};\n ic::ParametrosMulticapa parametros;\n if (!(ifs >> parametros))\n throw runtime_error(\"No se pudo cargar el archivo de parámetros\");\n\n \/\/ Leave K Out\n\n {\n vector particiones = ic::cargarParticiones(rutaBaseDatos + \"particionesIrisKOut\/\", 10);\n vec errores, epocas;\n errores.resize(particiones.size());\n epocas.resize(particiones.size());\n\n#pragma omp parallel for\n for (unsigned int i = 0; i < particiones.size(); ++i) {\n vector pesos;\n int epoca;\n tie(pesos, ignore, epoca) = ic::entrenarMulticapa(parametros.estructuraRed,\n datos.rows(particiones[i].first),\n parametros.nEpocas,\n parametros.tasaAprendizaje,\n parametros.inercia,\n parametros.toleranciaError);\n\n const double tasaError = ic::errorPrueba(pesos,\n datos.rows(particiones[i].second));\n\n epocas(i) = epoca;\n errores(i) = tasaError;\n }\n\n cout << \"Iris multicapa, Leave K Out\" << endl\n << \"Error promedio en la prueba: \" << mean(errores) << endl\n << \"Desvío estándar del error: \" << stddev(errores) << endl\n << \"N° de épocas promedio que tarda en converger: \" << mean(epocas) << endl\n << \"Desvío estándar de lo anterior: \" << stddev(epocas) << endl;\n }\n\n \/\/ Leave One Out\n\n {\n vector particiones = ic::cargarParticiones(rutaBaseDatos + \"particionesIris1Out\/\", 150);\n vec errores, epocas;\n errores.resize(particiones.size());\n epocas.resize(particiones.size());\n\n#pragma omp parallel for\n for (unsigned int i = 0; i < particiones.size(); ++i) {\n vector pesos;\n int epoca;\n tie(pesos, ignore, epoca) = ic::entrenarMulticapa(parametros.estructuraRed,\n datos.rows(particiones[i].first),\n parametros.nEpocas,\n parametros.tasaAprendizaje,\n parametros.inercia,\n parametros.toleranciaError);\n\n const double tasaError = ic::errorPrueba(pesos,\n datos.rows(particiones[i].second));\n\n epocas(i) = epoca;\n errores(i) = tasaError;\n }\n\n cout << \"\\nIris multicapa, Leave One Out\" << endl\n << \"Error promedio en la prueba: \" << mean(errores) << endl\n << \"Desvío estándar del error: \" << stddev(errores) << endl\n << \"N° de épocas promedio que tarda en converger: \" << mean(epocas) << endl\n << \"Desvío estándar de lo anterior: \" << stddev(epocas) << endl;\n }\n\n return 0;\n}\n<|endoftext|>"} {"text":"#include \"rdb_protocol\/configured_limits.hpp\"\n#include \"rdb_protocol\/wire_func.hpp\"\n\nnamespace ql {\nconfigured_limits_t\nfrom_optargs(const std::map &)\n{\n return configured_limits_t();\n}\n\n} \/\/ namespace ql\nSketch implementation.#include \"rdb_protocol\/configured_limits.hpp\"\n#include \"rdb_protocol\/wire_func.hpp\"\n#include \"rdb_protocol\/func.hpp\"\n\nnamespace ql {\nconfigured_limits_t\nfrom_optargs(const std::map &arguments)\n{\n auto p = arguments.find(\"arrayLimit\");\n if (p != arguments.end()) {\n return configured_limits_t((*p).second.compile_wire_func()->call(NULL)->as_int());\n } else {\n return configured_limits_t();\n }\n}\n\n} \/\/ namespace ql\n<|endoftext|>"} {"text":"#include \n\n#include \"rdb_protocol\/exceptions.hpp\"\n#include \"rdb_protocol\/rdb_protocol_json.hpp\"\n#include \"utils.hpp\"\n\nwrite_message_t &operator<<(write_message_t &msg, const boost::shared_ptr &cjson) {\n rassert(NULL != cjson.get() && NULL != cjson->get());\n msg << *cjson->get();\n return msg;\n}\n\nMUST_USE archive_result_t deserialize(read_stream_t *s, boost::shared_ptr *cjson) {\n cJSON *data = cJSON_CreateBlank();\n\n archive_result_t res = deserialize(s, data);\n if (res) { return res; }\n\n *cjson = boost::shared_ptr(new scoped_cJSON_t(data));\n\n return ARCHIVE_SUCCESS;\n}\n\nnamespace query_language {\n\n\/\/ TODO: Rename this function! It is not part of the cJSON library,\n\/\/ so it should not be part of the cJSON namepace.\nstatic const int cJSON_rank[7] = {\n [cJSON_Array] = 0, \/\/5\n [cJSON_False] = 1, \/\/0\n [cJSON_True] = 2, \/\/1\n [cJSON_NULL] = 3, \/\/2\n [cJSON_Number] = 4, \/\/3\n [cJSON_Object] = 5, \/\/6\n [cJSON_String] = 6}; \/\/4\nint cJSON_cmp(cJSON *l, cJSON *r, const backtrace_t &backtrace) {\n if (l->type != r->type) {\n rassert(0 <= l->type && l->type < int(sizeof(cJSON_rank)\/sizeof(*cJSON_rank)));\n rassert(0 <= r->type && r->type < int(sizeof(cJSON_rank)\/sizeof(*cJSON_rank)));\n return cJSON_rank[l->type] - cJSON_rank[r->type];\n }\n switch (l->type) {\n case cJSON_False:\n if (r->type == cJSON_True) {\n return -1;\n } else if (r->type == cJSON_False) {\n return 0;\n }\n break;\n case cJSON_True:\n if (r->type == cJSON_True) {\n return 0;\n } else if (r->type == cJSON_False) {\n return 1;\n }\n break;\n case cJSON_NULL:\n return 0;\n break;\n case cJSON_Number:\n if (l->valuedouble < r->valuedouble) {\n return -1;\n } else if (l->valuedouble > r->valuedouble) {\n return 1;\n } else {\n return 0; \/\/ TODO: Handle NaN?\n }\n break;\n case cJSON_String:\n return strcmp(l->valuestring, r->valuestring);\n break;\n case cJSON_Array:\n {\n int lsize = cJSON_GetArraySize(l),\n rsize = cJSON_GetArraySize(r);\n for (int i = 0; i < lsize; ++i) {\n if (i >= rsize) {\n return 1; \/\/ e.g. cmp([0, 1], [0])\n }\n int cmp = cJSON_cmp(cJSON_GetArrayItem(l, i), cJSON_GetArrayItem(r, i), backtrace);\n if (cmp) {\n return cmp;\n }\n }\n return -1; \/\/ e.g. cmp([0], [0, 1]);\n }\n break;\n case cJSON_Object:\n throw runtime_exc_t(\"Can't compare objects.\", backtrace);\n break;\n default:\n unreachable();\n break;\n }\n unreachable();\n}\n\nvoid require_type(const cJSON *json, int type, const backtrace_t &b) {\n if (json->type != type) {\n throw runtime_exc_t(strprintf(\"Required type: %s but found %s.\",\n cJSON_type_to_string(type).c_str(),\n cJSON_type_to_string(json->type).c_str()),\n b);\n }\n}\n\n} \/\/ namespace query_language\nFixed so compiles under gcc.#include \n\n#include \"rdb_protocol\/exceptions.hpp\"\n#include \"rdb_protocol\/rdb_protocol_json.hpp\"\n#include \"utils.hpp\"\n\nwrite_message_t &operator<<(write_message_t &msg, const boost::shared_ptr &cjson) {\n rassert(NULL != cjson.get() && NULL != cjson->get());\n msg << *cjson->get();\n return msg;\n}\n\nMUST_USE archive_result_t deserialize(read_stream_t *s, boost::shared_ptr *cjson) {\n cJSON *data = cJSON_CreateBlank();\n\n archive_result_t res = deserialize(s, data);\n if (res) { return res; }\n\n *cjson = boost::shared_ptr(new scoped_cJSON_t(data));\n\n return ARCHIVE_SUCCESS;\n}\n\nnamespace query_language {\n\n\/* In a less ridiculous world, the C++ standard wouldn't have dropped designated\n initializers for arrays, and this namespace wouldn't be necessary. *\/\nnamespace cJSON_type_ordering {\nstruct rank_wrapper {\n int rank[7];\n rank_wrapper() {\n rank[cJSON_Array] = 0;\n rank[cJSON_False] = 1;\n rank[cJSON_True] = 2;\n rank[cJSON_NULL] = 3;\n rank[cJSON_Number] = 4;\n rank[cJSON_Object] = 5;\n rank[cJSON_String] = 6;\n }\n};\nrank_wrapper wrapper;\nint cmp(int t1, int t2) { return wrapper.rank[t1] - wrapper.rank[t2]; }\n}\n\n\/\/ TODO: Rename this function! It is not part of the cJSON library,\n\/\/ so it should not be part of the cJSON namepace.\nint cJSON_cmp(cJSON *l, cJSON *r, const backtrace_t &backtrace) {\n if (l->type != r->type) {\n return cJSON_type_ordering::cmp(l->type, r->type);\n }\n switch (l->type) {\n case cJSON_False:\n if (r->type == cJSON_True) {\n return -1;\n } else if (r->type == cJSON_False) {\n return 0;\n }\n break;\n case cJSON_True:\n if (r->type == cJSON_True) {\n return 0;\n } else if (r->type == cJSON_False) {\n return 1;\n }\n break;\n case cJSON_NULL:\n return 0;\n break;\n case cJSON_Number:\n if (l->valuedouble < r->valuedouble) {\n return -1;\n } else if (l->valuedouble > r->valuedouble) {\n return 1;\n } else {\n return 0; \/\/ TODO: Handle NaN?\n }\n break;\n case cJSON_String:\n return strcmp(l->valuestring, r->valuestring);\n break;\n case cJSON_Array:\n {\n int lsize = cJSON_GetArraySize(l),\n rsize = cJSON_GetArraySize(r);\n for (int i = 0; i < lsize; ++i) {\n if (i >= rsize) {\n return 1; \/\/ e.g. cmp([0, 1], [0])\n }\n int cmp = cJSON_cmp(cJSON_GetArrayItem(l, i), cJSON_GetArrayItem(r, i), backtrace);\n if (cmp) {\n return cmp;\n }\n }\n return -1; \/\/ e.g. cmp([0], [0, 1]);\n }\n break;\n case cJSON_Object:\n throw runtime_exc_t(\"Can't compare objects.\", backtrace);\n break;\n default:\n unreachable();\n break;\n }\n unreachable();\n}\n\nvoid require_type(const cJSON *json, int type, const backtrace_t &b) {\n if (json->type != type) {\n throw runtime_exc_t(strprintf(\"Required type: %s but found %s.\",\n cJSON_type_to_string(type).c_str(),\n cJSON_type_to_string(json->type).c_str()),\n b);\n }\n}\n\n} \/\/ namespace query_language\n<|endoftext|>"} {"text":"#include \n\n#include \"dispatch.hpp\"\n\nint main()\n{\n enum\n {\n NORMAL,\n INVALID\n } state(NORMAL);\n\n std::cout <<\n gnr::dispatch(\n state,\n []{ return \"NORMAL\"; },\n []{ return \"INVALID\"; }\n ) <<\n std::endl;\n\n std::cout << gnr::select(1, \"NORMAL\", \"INVALID\") << std::endl;\n\n return 0;\n}\nsome fixes#include \n\n#include \"dispatch.hpp\"\n\nint main()\n{\n enum\n {\n NORMAL,\n INVALID\n } state(NORMAL);\n\n std::cout <<\n gnr::dispatch(\n state,\n []{ return \"NORMAL\"; },\n []{ return \"INVALID\"; }\n ) <<\n std::endl;\n\n std::cout << gnr::select(1, 0, 1, 4) << std::endl;\n\n return 0;\n}\n<|endoftext|>"} {"text":"\/\/=================================================================================================\n\/\/ Copyright (c) 2012, Johannes Meyer, TU Darmstadt\n\/\/ All rights reserved.\n\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are met:\n\/\/ * Redistributions of source code must retain the above copyright\n\/\/ notice, this list of conditions and the following disclaimer.\n\/\/ * Redistributions in binary form must reproduce the above copyright\n\/\/ notice, this list of conditions and the following disclaimer in the\n\/\/ documentation and\/or other materials provided with the distribution.\n\/\/ * Neither the name of the Flight Systems and Automatic Control group,\n\/\/ TU Darmstadt, nor the names of its contributors may be used to\n\/\/ endorse or promote products derived from this software without\n\/\/ specific prior written permission.\n\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n\/\/ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n\/\/ WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n\/\/ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY\n\/\/ DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n\/\/ (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n\/\/ LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n\/\/ ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n\/\/ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n\/\/ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\/\/=================================================================================================\n\n\n#include \n#include \n#include \n\nnamespace hector_quadrotor {\n\nclass Teleop\n{\nprivate:\n ros::NodeHandle node_handle_;\n ros::Subscriber joy_subscriber_;\n ros::Publisher velocity_publisher_;\n geometry_msgs::Twist velocity_;\n\n struct Axis\n {\n int axis;\n double max;\n };\n\n struct Button\n {\n int button;\n };\n\n struct {\n Axis x;\n Axis y;\n Axis z;\n Axis yaw;\n } axes_;\n\n struct\n {\n Button slow;\n } buttons_;\n\n double slow_factor_;\n\npublic:\n Teleop()\n {\n ros::NodeHandle params(\"~\");\n\n axes_.x.axis = 0;\n axes_.x.max = 2.0;\n axes_.y.axis = 0;\n axes_.y.max = 2.0;\n axes_.z.axis = 0;\n axes_.z.max = 2.0;\n axes_.yaw.axis = 0;\n axes_.yaw.max = 90.0*M_PI\/180.0;\n buttons_.slow.button = 0;\n slow_factor_ = 0.2;\n\n params.getParam(\"x_axis\", axes_.x.axis);\n params.getParam(\"y_axis\", axes_.y.axis);\n params.getParam(\"z_axis\", axes_.z.axis);\n params.getParam(\"yaw_axis\", axes_.yaw.axis);\n params.getParam(\"x_velocity_max\", axes_.x.max);\n params.getParam(\"y_velocity_max\", axes_.y.max);\n params.getParam(\"z_velocity_max\", axes_.z.max);\n params.getParam(\"yaw_velocity_max\", axes_.yaw.max);\n params.getParam(\"slow_button\", buttons_.slow.button);\n params.getParam(\"slow_factor\", slow_factor_);\n\n joy_subscriber_ = node_handle_.subscribe(\"joy\", 1, boost::bind(&Teleop::joyCallback, this, _1));\n velocity_publisher_ = node_handle_.advertise(\"cmd_vel\", 10);\n }\n\n ~Teleop()\n {\n stop();\n }\n\n void joyCallback(const sensor_msgs::JoyConstPtr& joy)\n {\n velocity_.linear.x = getAxis(joy, axes_.x.axis) * axes_.x.max;\n velocity_.linear.y = getAxis(joy, axes_.y.axis) * axes_.y.max;\n velocity_.linear.z = getAxis(joy, axes_.z.axis) * axes_.z.max;\n velocity_.angular.z = getAxis(joy, axes_.yaw.axis) * axes_.yaw.max;\n if (getButton(joy, buttons_.slow.button)) {\n velocity_.linear.x *= slow_factor_;\n velocity_.linear.y *= slow_factor_;\n velocity_.linear.z *= slow_factor_;\n velocity_.angular.z *= slow_factor_;\n }\n velocity_publisher_.publish(velocity_);\n }\n\n sensor_msgs::Joy::_axes_type::value_type getAxis(const sensor_msgs::JoyConstPtr& joy, int axis)\n {\n if (axis == 0) return 0;\n sensor_msgs::Joy::_axes_type::value_type sign = 1.0;\n if (axis < 0) { sign = -1.0; axis = -axis; }\n if ((size_t)axis > joy->axes.size()) return 0;\n return sign * joy->axes[axis - 1];\n }\n\n sensor_msgs::Joy::_buttons_type::value_type getButton(const sensor_msgs::JoyConstPtr& joy, int button)\n {\n if (button <= 0) return 0;\n if ((size_t)button > joy->axes.size()) return 0;\n return joy->buttons[button - 1];\n }\n\n void stop()\n {\n velocity_ = geometry_msgs::Twist();\n velocity_publisher_.publish(velocity_);\n }\n};\n\n} \/\/ namespace hector_quadrotor\n\nint main(int argc, char **argv)\n{\n ros::init(argc, argv, \"quadrotor_teleop\");\n\n hector_quadrotor::Teleop teleop;\n ros::spin();\n\n return 0;\n}\nAdd Attitude mode to teleop\/\/=================================================================================================\n\/\/ Copyright (c) 2012, Johannes Meyer, TU Darmstadt\n\/\/ All rights reserved.\n\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are met:\n\/\/ * Redistributions of source code must retain the above copyright\n\/\/ notice, this list of conditions and the following disclaimer.\n\/\/ * Redistributions in binary form must reproduce the above copyright\n\/\/ notice, this list of conditions and the following disclaimer in the\n\/\/ documentation and\/or other materials provided with the distribution.\n\/\/ * Neither the name of the Flight Systems and Automatic Control group,\n\/\/ TU Darmstadt, nor the names of its contributors may be used to\n\/\/ endorse or promote products derived from this software without\n\/\/ specific prior written permission.\n\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n\/\/ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n\/\/ WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n\/\/ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY\n\/\/ DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n\/\/ (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n\/\/ LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n\/\/ ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n\/\/ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n\/\/ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\/\/=================================================================================================\n\n\n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace hector_quadrotor\n{\n\nclass Teleop\n{\nprivate:\n ros::NodeHandle node_handle_;\n ros::Subscriber joy_subscriber_;\n\n ros::Publisher velocity_publisher_, attitude_publisher_, yawrate_publisher_, thrust_publisher_;\n geometry_msgs::Twist velocity_;\n hector_uav_msgs::AttitudeCommand attitude_;\n hector_uav_msgs::ThrustCommand thrust_;\n hector_uav_msgs::YawrateCommand yawrate_;\n\n struct Axis\n {\n int axis;\n double max;\n };\n\n struct Button\n {\n int button;\n };\n\n struct\n {\n Axis x;\n Axis y;\n Axis z;\n Axis yaw;\n } axes_;\n\n struct\n {\n Button slow;\n } buttons_;\n\n double slow_factor_;\n\npublic:\n Teleop()\n {\n ros::NodeHandle params(\"~\");\n\n params.param(\"x_axis\", axes_.x.axis, 4);\n params.param(\"y_axis\", axes_.y.axis, 3);\n params.param(\"z_axis\", axes_.z.axis, 2);\n params.param(\"yaw_axis\", axes_.yaw.axis, 1);\n\n params.param(\"yaw_velocity_max\", axes_.yaw.max, 90.0 * M_PI \/ 180.0);\n params.param(\"slow_button\", buttons_.slow.button, 1);\n params.param(\"slow_factor\", slow_factor_, 0.2);\n\n std::string control_mode_str;\n params.param(\"control_mode\", control_mode_str, \"twist\");\n\n if (control_mode_str == \"twist\")\n {\n params.param(\"x_velocity_max\", axes_.x.max, 2.0);\n params.param(\"y_velocity_max\", axes_.y.max, 2.0);\n params.param(\"z_velocity_max\", axes_.z.max, 2.0);\n\n joy_subscriber_ = node_handle_.subscribe(\"joy\", 1, boost::bind(&Teleop::joyTwistCallback, this, _1));\n velocity_publisher_ = node_handle_.advertise(\"cmd_vel\", 10);\n }\n else if (control_mode_str == \"attitude\")\n {\n params.param(\"x_roll_max\", axes_.x.max, 0.35);\n params.param(\"y_pitch_max\", axes_.y.max, 0.35);\n params.param(\"z_thrust_max\", axes_.z.max, 25.0);\n joy_subscriber_ = node_handle_.subscribe(\"joy\", 1, boost::bind(&Teleop::joyAttitudeCallback, this, _1));\n attitude_publisher_ = node_handle_.advertise(\"command\/attitude\", 10);\n yawrate_publisher_ = node_handle_.advertise(\"command\/yawrate\", 10);\n thrust_publisher_ = node_handle_.advertise(\"command\/thrust\", 10);\n }\n\n }\n\n ~Teleop()\n {\n stop();\n }\n\n void joyTwistCallback(const sensor_msgs::JoyConstPtr &joy)\n {\n velocity_.linear.x = getAxis(joy, axes_.x);\n velocity_.linear.y = getAxis(joy, axes_.y);\n velocity_.linear.z = getAxis(joy, axes_.z);\n velocity_.angular.z = getAxis(joy, axes_.yaw);\n if (getButton(joy, buttons_.slow.button))\n {\n velocity_.linear.x *= slow_factor_;\n velocity_.linear.y *= slow_factor_;\n velocity_.linear.z *= slow_factor_;\n velocity_.angular.z *= slow_factor_;\n }\n velocity_publisher_.publish(velocity_);\n }\n\n void joyAttitudeCallback(const sensor_msgs::JoyConstPtr &joy)\n {\n attitude_.roll = getAxis(joy, axes_.x);\n attitude_.pitch = getAxis(joy, axes_.y);\n attitude_publisher_.publish(attitude_);\n\n thrust_.thrust = getAxis(joy, axes_.z);\n thrust_publisher_.publish(thrust_);\n\n yawrate_.turnrate = getAxis(joy, axes_.yaw);\n if (getButton(joy, buttons_.slow.button))\n {\n yawrate_.turnrate *= slow_factor_;\n }\n yawrate_publisher_.publish(yawrate_);\n }\n\n sensor_msgs::Joy::_axes_type::value_type getAxis(const sensor_msgs::JoyConstPtr &joy, Axis axis)\n {\n if (axis.axis == 0)\n {return 0;}\n sensor_msgs::Joy::_axes_type::value_type sign = 1.0;\n if (axis.axis < 0)\n {\n sign = -1.0;\n axis.axis = -axis.axis;\n }\n if ((size_t) axis.axis > joy->axes.size())\n {return 0;}\n return sign * joy->axes[axis.axis - 1] * axis.max;\n }\n\n sensor_msgs::Joy::_buttons_type::value_type getButton(const sensor_msgs::JoyConstPtr &joy, int button)\n {\n if (button <= 0)\n {return 0;}\n if ((size_t) button > joy->axes.size())\n {return 0;}\n return joy->buttons[button - 1];\n }\n\n void stop()\n {\n if(velocity_publisher_.getNumSubscribers() > 0)\n {\n velocity_ = geometry_msgs::Twist();\n velocity_publisher_.publish(velocity_);\n }\n if(attitude_publisher_.getNumSubscribers() > 0)\n {\n attitude_ = hector_uav_msgs::AttitudeCommand();\n attitude_publisher_.publish(attitude_);\n }\n if(thrust_publisher_.getNumSubscribers() > 0)\n {\n thrust_ = hector_uav_msgs::ThrustCommand();\n thrust_publisher_.publish(thrust_);\n }\n if(yawrate_publisher_.getNumSubscribers() > 0)\n {\n yawrate_ = hector_uav_msgs::YawrateCommand();\n yawrate_publisher_.publish(yawrate_);\n }\n\n }\n};\n\n} \/\/ namespace hector_quadrotor\n\nint main(int argc, char **argv)\n{\n ros::init(argc, argv, \"quadrotor_teleop\");\n\n hector_quadrotor::Teleop teleop;\n ros::spin();\n\n return 0;\n}\n<|endoftext|>"} {"text":"\/\/(c) 2016-2017 by Authors\n\/\/This file is a part of ABruijn program.\n\/\/Released under the BSD license (see LICENSE file)\n\n#include \"output_generator.h\"\n#include \"..\/sequence\/consensus_generator.h\"\n#include \n\n\n\/\/Generates FASTA from the given graph paths\nstd::vector OutputGenerator::\n\tgeneratePathSequences(const std::vector& paths) const\n{\n\tstd::vector contigSequences;\n\n\tfor (auto& contig : paths)\n\t{\n\t\t\/\/As each edge might correspond to multiple sequences,\n\t\t\/\/we need to select them so as to minimize the\n\t\t\/\/number of original contigs (that were used to build the graph)\n\t\tstd::unordered_map seqIdFreq;\n\t\tfor (auto& edge : contig.path) \n\t\t{\n\t\t\tstd::unordered_set edgeSeqIds;\n\t\t\tfor (auto& seg: edge->seqSegments) \n\t\t\t{\n\t\t\t\tedgeSeqIds.insert(seg.origSeqId);\n\t\t\t}\n\t\t\tfor (auto& seqId : edgeSeqIds)\n\t\t\t{\n\t\t\t\tseqIdFreq[seqId] += 1;\n\t\t\t}\n\t\t}\n\n\t\tstd::string nucSequence;\n\t\t\/\/ContigPath contigPath;\n\t\t\/\/contigPath.name = contig.name();\n\t\t\/\/int32_t prevFlank = 0;\n\t\t\/\/int32_t prevSubLength = 0;\n\n\t\tfor (size_t i = 0; i < contig.path.size(); ++i) \n\t\t{\n\t\t\tif (contig.path[i]->seqSegments.empty()) \n\t\t\t{\n\t\t\t\tthrow std::runtime_error(\"Edge without sequence\");\n\t\t\t}\n\n\t\t\t\/\/get the sequence with maximum frequency\n\t\t\tEdgeSequence* bestSegment = nullptr;\n\t\t\tfor (auto& seg : contig.path[i]->seqSegments)\n\t\t\t{\n\t\t\t\tif (!bestSegment || \n\t\t\t\t\tseqIdFreq[seg.origSeqId] > seqIdFreq[bestSegment->origSeqId])\n\t\t\t\t{\n\t\t\t\t\tbestSegment = &seg;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (bestSegment->seqLen == 0) continue;\n\t\t\tnucSequence += _graph.edgeSequences()\n\t\t\t\t\t\t\t\t.getSeq(bestSegment->edgeSeqId).str();\n\t\t}\n\t\t\/\/contigParts.push_back(contigPath);\n\t\tcontigSequences.push_back({DnaSequence(nucSequence), contig.name(), \n\t\t\t\t\t\t\t\t FastaRecord::ID_NONE});\n\t}\n\n\treturn contigSequences;\n}\n\nvoid OutputGenerator::outputFasta(const std::vector& paths,\n\t\t\t\t\t\t\t\t const std::string& filename)\n{\n\tstd::vector posStrandPaths;\n\tfor (auto& path : paths)\n\t{\n\t\tif (path.id.strand()) posStrandPaths.push_back(path);\n\t}\n\tSequenceContainer::writeFasta(this->generatePathSequences(posStrandPaths), \n\t\t\t\t\t\t\t\t filename);\n}\n\nvoid OutputGenerator::outputGfa(const std::vector& paths,\n\t\t\t\t\t\t\t const std::string& filename)\n{\n\tauto sequences = this->generatePathSequences(paths);\n\n\tLogger::get().debug() << \"Writing Gfa\";\n\tFILE* fout = fopen(filename.c_str(), \"w\");\n\tif (!fout) throw std::runtime_error(\"Can't open \" + filename);\n\n\tfprintf(fout, \"H\\tVN:Z:1.0\\n\");\n\tfor (size_t i = 0; i < paths.size(); ++i)\n\t{\n\t\tif (!paths[i].id.strand()) continue;\n\n\t\t\/\/size_t kmerCount = sequences[i].sequence.length() * paths[i].meanCoverage;\n\t\tfprintf(fout, \"S\\t%s\\t%s\\tdp:i:%d\\n\", paths[i].name().c_str(), \n\t\t\t\tsequences[i].sequence.str().c_str(), (int)paths[i].meanCoverage);\n\t}\n\n\tfor (auto& contigLeft : paths)\n\t{\n\t\tfor (auto& contigRight : paths)\n\t\t{\n\t\t\tif (contigLeft.path.back()->nodeRight != \n\t\t\t\tcontigRight.path.front()->nodeLeft) continue;\n\n\t\t\tstd::string leftSign = contigLeft.id.strand() ? \"+\" :\"-\";\n\t\t\tstd::string leftName = contigLeft.nameUnsigned();\n\n\t\t\tstd::string rightSign = contigRight.id.strand() ? \"+\" :\"-\";\n\t\t\tstd::string rightName = contigRight.nameUnsigned();\n\n\t\t\tfprintf(fout, \"L\\t%s\\t%s\\t%s\\t%s\\t0M\\n\", leftName.c_str(), \n\t\t\t\t\tleftSign.c_str(), rightName.c_str(), rightSign.c_str());\n\t\t}\n\t}\n}\n\nvoid OutputGenerator::outputDot(const std::vector& paths,\n\t\t\t\t\t\t\t\tconst std::string& filename)\n{\n\tLogger::get().debug() << \"Writing Dot\";\n\n\tstd::ofstream fout(filename);\n\tif (!fout.is_open()) throw std::runtime_error(\"Can't open \" + filename);\n\n\tfout << \"digraph {\\n\";\n\tfout << \"nodesep = 0.5;\\n\";\n\tfout << \"node [shape = circle, label = \\\"\\\", height = 0.3];\\n\";\n\t\n\t\/\/\/re-enumerating helper functions\n\tstd::unordered_map nodeIds;\n\tint nextNodeId = 0;\n\tauto nodeToId = [&nodeIds, &nextNodeId](GraphNode* node)\n\t{\n\t\tif (!nodeIds.count(node))\n\t\t{\n\t\t\tnodeIds[node] = nextNodeId++;\n\t\t}\n\t\treturn nodeIds[node];\n\t};\n\n\tfor (auto& node : _graph.iterNodes())\n\t{\n\t\tif (node->isTelomere())\n\t\t{\n\t\t\tfout << \"\\\"\" << nodeToId(node) \n\t\t\t\t<< \"\\\" [style = \\\"filled\\\", fillcolor = \\\"grey\\\"];\\n\";\n\t\t}\n\t}\n\n\t\/\/coloring repeat clusters\n\tconst std::string COLORS[] = {\"red\", \"darkgreen\", \"blue\", \"goldenrod\", \n\t\t\t\t\t\t\t\t \"cadetblue1\", \"darkorchid\", \"aquamarine1\", \n\t\t\t\t\t\t\t\t \"darkgoldenrod1\", \"deepskyblue1\", \n\t\t\t\t\t\t\t\t \"darkolivegreen3\"};\n\tstd::vector dfsStack;\n\tstd::unordered_set visited;\n\tstd::unordered_map edgeColors;\n\tsize_t colorId = 0;\n\tfor (auto& edge: _graph.iterEdges())\n\t{\n\t\tif (!edge->isRepetitive() || visited.count(edge)) continue;\n\t\tdfsStack.push_back(edge);\n\t\twhile(!dfsStack.empty())\n\t\t{\n\t\t\tauto curEdge = dfsStack.back(); \n\t\t\tdfsStack.pop_back();\n\t\t\tif (visited.count(curEdge)) continue;\n\t\t\tedgeColors[curEdge] = COLORS[colorId];\n\t\t\tedgeColors[_graph.complementEdge(curEdge)] = COLORS[colorId];\n\t\t\tvisited.insert(curEdge);\n\t\t\tvisited.insert(_graph.complementEdge(curEdge));\n\t\t\tfor (auto adjEdge: curEdge->adjacentEdges())\n\t\t\t{\n\t\t\t\tif (adjEdge->isRepetitive() && !visited.count(adjEdge))\n\t\t\t\t{\n\t\t\t\t\tdfsStack.push_back(adjEdge);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tcolorId = (colorId + 1) % (sizeof(COLORS) \/ sizeof(COLORS[0]));\n\t}\n\n\tfor (auto& contig : paths)\n\t{\n\t\tstd::stringstream lengthStr;\n\t\tif (contig.length < 5000)\n\t\t{\n\t\t\tlengthStr << std::fixed << std::setprecision(1) \n\t\t\t\t<< (float)contig.length \/ 1000 << \"k\";\n\t\t}\n\t\telse\n\t\t{\n\t\t\tlengthStr << contig.length \/ 1000 << \"k\";\n\t\t}\n\t\tlengthStr << \" \" << contig.meanCoverage << \"x\";\n\n\t\tif (contig.repetitive)\n\t\t{\n\t\t\tstd::string color = edgeColors[contig.path.front()];\n\t\t\tstd::string direction = contig.path.front()->selfComplement ?\n\t\t\t\t\t\t\t\t\t\", dir = both\" : \"\";\n\t\t\tfout << \"\\\"\" << nodeToId(contig.path.front()->nodeLeft) \n\t\t\t\t << \"\\\" -> \\\"\" << nodeToId(contig.path.back()->nodeRight)\n\t\t\t\t << \"\\\" [label = \\\"id \" << contig.id.signedId() << \n\t\t\t\t \"\\\\l\" << lengthStr.str() << \"\\\", color = \\\"\" \n\t\t\t\t << color << \"\\\" \" << \", penwidth = 3\" << direction << \"] ;\\n\";\n\t\t}\n\t\telse\n\t\t{\n\t\t\tfout << \"\\\"\" << nodeToId(contig.path.front()->nodeLeft)\n\t\t\t\t << \"\\\" -> \\\"\" << nodeToId(contig.path.back()->nodeRight)\n\t\t\t\t << \"\\\" [label = \\\"id \" << contig.id.signedId()\n\t\t\t\t << \"\\\\l\" << lengthStr.str() << \"\\\", color = \\\"black\\\"] ;\\n\";\n\t\t}\n\t}\n\n\tfout << \"}\\n\";\n}\ndon't output complementarly links in gfa\/\/(c) 2016-2017 by Authors\n\/\/This file is a part of ABruijn program.\n\/\/Released under the BSD license (see LICENSE file)\n\n#include \"output_generator.h\"\n#include \"..\/sequence\/consensus_generator.h\"\n#include \n\n\n\/\/Generates FASTA from the given graph paths\nstd::vector OutputGenerator::\n\tgeneratePathSequences(const std::vector& paths) const\n{\n\tstd::vector contigSequences;\n\n\tfor (auto& contig : paths)\n\t{\n\t\t\/\/As each edge might correspond to multiple sequences,\n\t\t\/\/we need to select them so as to minimize the\n\t\t\/\/number of original contigs (that were used to build the graph)\n\t\tstd::unordered_map seqIdFreq;\n\t\tfor (auto& edge : contig.path) \n\t\t{\n\t\t\tstd::unordered_set edgeSeqIds;\n\t\t\tfor (auto& seg: edge->seqSegments) \n\t\t\t{\n\t\t\t\tedgeSeqIds.insert(seg.origSeqId);\n\t\t\t}\n\t\t\tfor (auto& seqId : edgeSeqIds)\n\t\t\t{\n\t\t\t\tseqIdFreq[seqId] += 1;\n\t\t\t}\n\t\t}\n\n\t\tstd::string nucSequence;\n\t\t\/\/ContigPath contigPath;\n\t\t\/\/contigPath.name = contig.name();\n\t\t\/\/int32_t prevFlank = 0;\n\t\t\/\/int32_t prevSubLength = 0;\n\n\t\tfor (size_t i = 0; i < contig.path.size(); ++i) \n\t\t{\n\t\t\tif (contig.path[i]->seqSegments.empty()) \n\t\t\t{\n\t\t\t\tthrow std::runtime_error(\"Edge without sequence\");\n\t\t\t}\n\n\t\t\t\/\/get the sequence with maximum frequency\n\t\t\tEdgeSequence* bestSegment = nullptr;\n\t\t\tfor (auto& seg : contig.path[i]->seqSegments)\n\t\t\t{\n\t\t\t\tif (!bestSegment || \n\t\t\t\t\tseqIdFreq[seg.origSeqId] > seqIdFreq[bestSegment->origSeqId])\n\t\t\t\t{\n\t\t\t\t\tbestSegment = &seg;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (bestSegment->seqLen == 0) continue;\n\t\t\tnucSequence += _graph.edgeSequences()\n\t\t\t\t\t\t\t\t.getSeq(bestSegment->edgeSeqId).str();\n\t\t}\n\t\t\/\/contigParts.push_back(contigPath);\n\t\tcontigSequences.push_back({DnaSequence(nucSequence), contig.name(), \n\t\t\t\t\t\t\t\t FastaRecord::ID_NONE});\n\t}\n\n\treturn contigSequences;\n}\n\nvoid OutputGenerator::outputFasta(const std::vector& paths,\n\t\t\t\t\t\t\t\t const std::string& filename)\n{\n\tstd::vector posStrandPaths;\n\tfor (auto& path : paths)\n\t{\n\t\tif (path.id.strand()) posStrandPaths.push_back(path);\n\t}\n\tSequenceContainer::writeFasta(this->generatePathSequences(posStrandPaths), \n\t\t\t\t\t\t\t\t filename);\n}\n\nvoid OutputGenerator::outputGfa(const std::vector& paths,\n\t\t\t\t\t\t\t const std::string& filename)\n{\n\tauto sequences = this->generatePathSequences(paths);\n\n\tLogger::get().debug() << \"Writing Gfa\";\n\tFILE* fout = fopen(filename.c_str(), \"w\");\n\tif (!fout) throw std::runtime_error(\"Can't open \" + filename);\n\n\tfprintf(fout, \"H\\tVN:Z:1.0\\n\");\n\tfor (size_t i = 0; i < paths.size(); ++i)\n\t{\n\t\tif (!paths[i].id.strand()) continue;\n\n\t\t\/\/size_t kmerCount = sequences[i].sequence.length() * paths[i].meanCoverage;\n\t\tfprintf(fout, \"S\\t%s\\t%s\\tdp:i:%d\\n\", paths[i].name().c_str(), \n\t\t\t\tsequences[i].sequence.str().c_str(), (int)paths[i].meanCoverage);\n\t}\n\n\tstd::unordered_set, pairhash> usedPairs;\n\tfor (auto& contigLeft : paths)\n\t{\n\t\tfor (auto& contigRight : paths)\n\t\t{\n\t\t\tGraphEdge* edgeLeft = contigLeft.path.back();\n\t\t\tGraphEdge* edgeRight = contigRight.path.front();\n\t\t\tif (edgeLeft->nodeRight != edgeRight->nodeLeft) continue;\n\n\t\t\tif (usedPairs.count(std::make_pair(edgeLeft, edgeRight))) continue;\n\t\t\tusedPairs.insert(std::make_pair(edgeLeft, edgeRight));\n\t\t\tusedPairs.insert(std::make_pair(_graph.complementEdge(edgeRight), \n\t\t\t\t\t\t\t\t\t\t\t_graph.complementEdge(edgeLeft)));\n\n\t\t\tstd::string leftSign = contigLeft.id.strand() ? \"+\" :\"-\";\n\t\t\tstd::string leftName = contigLeft.nameUnsigned();\n\n\t\t\tstd::string rightSign = contigRight.id.strand() ? \"+\" :\"-\";\n\t\t\tstd::string rightName = contigRight.nameUnsigned();\n\n\t\t\tfprintf(fout, \"L\\t%s\\t%s\\t%s\\t%s\\t0M\\n\", leftName.c_str(), \n\t\t\t\t\tleftSign.c_str(), rightName.c_str(), rightSign.c_str());\n\t\t}\n\t}\n}\n\nvoid OutputGenerator::outputDot(const std::vector& paths,\n\t\t\t\t\t\t\t\tconst std::string& filename)\n{\n\tLogger::get().debug() << \"Writing Dot\";\n\n\tstd::ofstream fout(filename);\n\tif (!fout.is_open()) throw std::runtime_error(\"Can't open \" + filename);\n\n\tfout << \"digraph {\\n\";\n\tfout << \"nodesep = 0.5;\\n\";\n\tfout << \"node [shape = circle, label = \\\"\\\", height = 0.3];\\n\";\n\t\n\t\/\/\/re-enumerating helper functions\n\tstd::unordered_map nodeIds;\n\tint nextNodeId = 0;\n\tauto nodeToId = [&nodeIds, &nextNodeId](GraphNode* node)\n\t{\n\t\tif (!nodeIds.count(node))\n\t\t{\n\t\t\tnodeIds[node] = nextNodeId++;\n\t\t}\n\t\treturn nodeIds[node];\n\t};\n\n\tfor (auto& node : _graph.iterNodes())\n\t{\n\t\tif (node->isTelomere())\n\t\t{\n\t\t\tfout << \"\\\"\" << nodeToId(node) \n\t\t\t\t<< \"\\\" [style = \\\"filled\\\", fillcolor = \\\"grey\\\"];\\n\";\n\t\t}\n\t}\n\n\t\/\/coloring repeat clusters\n\tconst std::string COLORS[] = {\"red\", \"darkgreen\", \"blue\", \"goldenrod\", \n\t\t\t\t\t\t\t\t \"cadetblue1\", \"darkorchid\", \"aquamarine1\", \n\t\t\t\t\t\t\t\t \"darkgoldenrod1\", \"deepskyblue1\", \n\t\t\t\t\t\t\t\t \"darkolivegreen3\"};\n\tstd::vector dfsStack;\n\tstd::unordered_set visited;\n\tstd::unordered_map edgeColors;\n\tsize_t colorId = 0;\n\tfor (auto& edge: _graph.iterEdges())\n\t{\n\t\tif (!edge->isRepetitive() || visited.count(edge)) continue;\n\t\tdfsStack.push_back(edge);\n\t\twhile(!dfsStack.empty())\n\t\t{\n\t\t\tauto curEdge = dfsStack.back(); \n\t\t\tdfsStack.pop_back();\n\t\t\tif (visited.count(curEdge)) continue;\n\t\t\tedgeColors[curEdge] = COLORS[colorId];\n\t\t\tedgeColors[_graph.complementEdge(curEdge)] = COLORS[colorId];\n\t\t\tvisited.insert(curEdge);\n\t\t\tvisited.insert(_graph.complementEdge(curEdge));\n\t\t\tfor (auto adjEdge: curEdge->adjacentEdges())\n\t\t\t{\n\t\t\t\tif (adjEdge->isRepetitive() && !visited.count(adjEdge))\n\t\t\t\t{\n\t\t\t\t\tdfsStack.push_back(adjEdge);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tcolorId = (colorId + 1) % (sizeof(COLORS) \/ sizeof(COLORS[0]));\n\t}\n\n\tfor (auto& contig : paths)\n\t{\n\t\tstd::stringstream lengthStr;\n\t\tif (contig.length < 5000)\n\t\t{\n\t\t\tlengthStr << std::fixed << std::setprecision(1) \n\t\t\t\t<< (float)contig.length \/ 1000 << \"k\";\n\t\t}\n\t\telse\n\t\t{\n\t\t\tlengthStr << contig.length \/ 1000 << \"k\";\n\t\t}\n\t\tlengthStr << \" \" << contig.meanCoverage << \"x\";\n\n\t\tif (contig.repetitive)\n\t\t{\n\t\t\tstd::string color = edgeColors[contig.path.front()];\n\t\t\tstd::string direction = contig.path.front()->selfComplement ?\n\t\t\t\t\t\t\t\t\t\", dir = both\" : \"\";\n\t\t\tfout << \"\\\"\" << nodeToId(contig.path.front()->nodeLeft) \n\t\t\t\t << \"\\\" -> \\\"\" << nodeToId(contig.path.back()->nodeRight)\n\t\t\t\t << \"\\\" [label = \\\"id \" << contig.id.signedId() << \n\t\t\t\t \"\\\\l\" << lengthStr.str() << \"\\\", color = \\\"\" \n\t\t\t\t << color << \"\\\" \" << \", penwidth = 3\" << direction << \"] ;\\n\";\n\t\t}\n\t\telse\n\t\t{\n\t\t\tfout << \"\\\"\" << nodeToId(contig.path.front()->nodeLeft)\n\t\t\t\t << \"\\\" -> \\\"\" << nodeToId(contig.path.back()->nodeRight)\n\t\t\t\t << \"\\\" [label = \\\"id \" << contig.id.signedId()\n\t\t\t\t << \"\\\\l\" << lengthStr.str() << \"\\\", color = \\\"black\\\"] ;\\n\";\n\t\t}\n\t}\n\n\tfout << \"}\\n\";\n}\n<|endoftext|>"} {"text":"\/*=========================================================================\n\n Program: Visualization Toolkit\n Module: vtkXMLParser.cxx\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n Copyright (c) 1993-2002 Ken Martin, Will Schroeder, Bill Lorensen \n All rights reserved.\n See Copyright.txt or http:\/\/www.kitware.com\/Copyright.htm for details.\n\n This software is distributed WITHOUT ANY WARRANTY; without even \n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR \n PURPOSE. See the above copyright notice for more information.\n\n=========================================================================*\/\n#include \"vtkXMLParser.h\"\n#include \"vtkObjectFactory.h\"\n\n#include \"expat.h\"\n#include \n#include \n\nvtkCxxRevisionMacro(vtkXMLParser, \"1.13\");\nvtkStandardNewMacro(vtkXMLParser);\n\n\/\/----------------------------------------------------------------------------\nvtkXMLParser::vtkXMLParser()\n{\n this->Stream = 0;\n this->Parser = 0;\n this->FileName = 0;\n this->InputString = 0;\n this->InputStringLength = 0;\n}\n\n\/\/----------------------------------------------------------------------------\nvtkXMLParser::~vtkXMLParser()\n{\n this->SetStream(0);\n this->SetFileName(0);\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkXMLParser::PrintSelf(ostream& os, vtkIndent indent)\n{\n this->Superclass::PrintSelf(os, indent);\n if(this->Stream)\n {\n os << indent << \"Stream: \" << this->Stream << \"\\n\";\n }\n else\n {\n os << indent << \"Stream: (none)\\n\";\n }\n os << indent << \"FileName: \" << (this->FileName? this->FileName : \"(none)\")\n << \"\\n\";\n}\n\n\/\/----------------------------------------------------------------------------\nint vtkXMLParser::Parse(const char* inputString)\n{\n this->InputString = inputString;\n this->InputStringLength = -1;\n int result = this->vtkXMLParser::Parse();\n this->InputString = 0;\n return result;\n}\n\n\/\/----------------------------------------------------------------------------\nint vtkXMLParser::Parse(const char* inputString, unsigned int length)\n{\n this->InputString = inputString;\n this->InputStringLength = length;\n int result = this->vtkXMLParser::Parse();\n this->InputString = 0;\n this->InputStringLength = -1;\n return result;\n}\n\n\n\/\/----------------------------------------------------------------------------\nint vtkXMLParser::Parse()\n{\n \/\/ Select source of XML\n ifstream ifs;\n if ( !this->InputString && !this->Stream && this->FileName )\n {\n \/\/ If it is file, open it and set the appropriate stream\n struct stat fs;\n if (stat(this->FileName, &fs) != 0) \n {\n vtkErrorMacro(\"Cannot open XML file: \" << this->FileName);\n return 0;\n }\n#ifdef _WIN32\n ifs.open(this->FileName, ios::binary | ios::in);\n#else\n ifs.open(this->FileName, ios::in);\n#endif\n if ( !ifs )\n {\n vtkErrorMacro(\"Cannot open XML file: \" << this->FileName);\n return 0;\n }\n this->Stream = &ifs;\n }\n\n \/\/ Create the expat XML parser.\n this->Parser = XML_ParserCreate(0);\n XML_SetElementHandler(this->Parser,\n &vtkXMLParserStartElement,\n &vtkXMLParserEndElement);\n XML_SetCharacterDataHandler(this->Parser,\n &vtkXMLParserCharacterDataHandler);\n XML_SetUserData(this->Parser, this);\n \n \/\/ Parse the input.\n int result = this->ParseXML();\n \n if(result)\n {\n \/\/ Tell the expat XML parser about the end-of-input.\n if(!XML_Parse(this->Parser, \"\", 0, 1))\n {\n this->ReportXmlParseError();\n result = 0;\n }\n }\n \n \/\/ Clean up the parser.\n XML_ParserFree(this->Parser);\n this->Parser = 0;\n \n \/\/ If the source was a file, reset the stream\n if ( this->Stream == &ifs )\n {\n this->Stream = 0;\n }\n\n return result;\n}\n\n\/\/----------------------------------------------------------------------------\nint vtkXMLParser::InitializeParser()\n{\n \/\/ Create the expat XML parser.\n this->Parser = XML_ParserCreate(0);\n XML_SetElementHandler(this->Parser,\n &vtkXMLParserStartElement,\n &vtkXMLParserEndElement);\n XML_SetCharacterDataHandler(this->Parser,\n &vtkXMLParserCharacterDataHandler);\n XML_SetUserData(this->Parser, this);\n this->ParseError = 0;\n return 1;\n}\n\n\/\/----------------------------------------------------------------------------\nint vtkXMLParser::ParseChunk(const char* inputString, unsigned int length)\n{\n int res;\n res = this->ParseBuffer(inputString, length);\n if ( res == 0 )\n {\n this->ParseError = 1;\n }\n return res;\n}\n\n\/\/----------------------------------------------------------------------------\nint vtkXMLParser::CleanupParser()\n{\n int result = !this->ParseError;\n if(result)\n {\n \/\/ Tell the expat XML parser about the end-of-input.\n if(!XML_Parse(this->Parser, \"\", 0, 1))\n {\n this->ReportXmlParseError();\n result = 0;\n }\n }\n \n \/\/ Clean up the parser.\n XML_ParserFree(this->Parser);\n this->Parser = 0;\n \n return result;\n}\n\n\/\/----------------------------------------------------------------------------\nint vtkXMLParser::ParseXML()\n{\n \/\/ Parsing of message\n if ( this->InputString )\n {\n if ( this->InputStringLength >= 0 )\n {\n return this->ParseBuffer(this->InputString, this->InputStringLength);\n }\n else\n {\n return this->ParseBuffer(this->InputString);\n }\n }\n\n \/\/ Make sure we have input.\n if(!this->Stream)\n {\n vtkErrorMacro(\"Parse() called with no Stream set.\");\n return 0;\n }\n \n \/\/ Default stream parser just reads a block at a time.\n istream& in = *(this->Stream);\n const int bufferSize = 4096; \n char buffer[bufferSize]; \n \n \/\/ Read in the stream and send its contents to the XML parser. This\n \/\/ read loop is very sensitive on certain platforms with slightly\n \/\/ broken stream libraries (like HPUX). Normally, it is incorrect\n \/\/ to not check the error condition on the fin.read() before using\n \/\/ the data, but the fin.gcount() will be zero if an error occurred.\n \/\/ Therefore, the loop should be safe everywhere.\n while(!this->ParsingComplete() && in)\n {\n in.read(buffer, bufferSize);\n if(in.gcount())\n {\n if(!this->ParseBuffer(buffer, in.gcount()))\n {\n return 0;\n }\n }\n }\n return 1;\n}\n\n\/\/----------------------------------------------------------------------------\nint vtkXMLParser::ParsingComplete()\n{\n \/\/ Default behavior is to parse to end of stream.\n return 0;\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkXMLParser::StartElement(const char *name,\n const char ** vtkNotUsed(atts))\n{\n this->ReportUnknownElement(name);\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkXMLParser::EndElement(const char * vtkNotUsed(name))\n{\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkXMLParser::CharacterDataHandler(const char* vtkNotUsed(inData),\n int vtkNotUsed(inLength))\n{\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkXMLParser::ReportStrayAttribute(const char* element, const char* attr,\n const char* value)\n{\n vtkWarningMacro(\"Stray attribute in XML stream: Element \" << element\n << \" has \" << attr << \"=\\\"\" << value << \"\\\"\");\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkXMLParser::ReportMissingAttribute(const char* element,\n const char* attr)\n{\n vtkErrorMacro(\"Missing attribute in XML stream: Element \" << element\n << \" is missing \" << attr);\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkXMLParser::ReportBadAttribute(const char* element, const char* attr,\n const char* value)\n{\n vtkErrorMacro(\"Bad attribute value in XML stream: Element \" << element\n << \" has \" << attr << \"=\\\"\" << value << \"\\\"\");\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkXMLParser::ReportUnknownElement(const char* element)\n{\n vtkErrorMacro(\"Unknown element in XML stream: \" << element);\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkXMLParser::ReportXmlParseError()\n{\n vtkErrorMacro(\"Error parsing XML in stream at line \"\n << XML_GetCurrentLineNumber(this->Parser)\n << \": \" << XML_ErrorString(XML_GetErrorCode(this->Parser)));\n}\n\n\/\/----------------------------------------------------------------------------\nunsigned long vtkXMLParser::GetXMLByteIndex()\n{\n return XML_GetCurrentByteIndex(this->Parser);\n}\n\n\/\/----------------------------------------------------------------------------\nint vtkXMLParser::ParseBuffer(const char* buffer, unsigned int count)\n{\n \/\/ Pass the buffer to the expat XML parser.\n if(!XML_Parse(this->Parser, buffer, count, 0))\n {\n this->ReportXmlParseError();\n return 0;\n }\n return 1;\n}\n\n\/\/----------------------------------------------------------------------------\nint vtkXMLParser::ParseBuffer(const char* buffer)\n{\n return this->ParseBuffer(buffer, static_cast(strlen(buffer)));\n}\n\n\/\/----------------------------------------------------------------------------\nint vtkXMLParser::IsSpace(char c)\n{\n return isspace(c);\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkXMLParserStartElement(void* parser, const char *name,\n const char **atts)\n{\n \/\/ Begin element handler that is registered with the XML_Parser.\n \/\/ This just casts the user data to a vtkXMLParser and calls\n \/\/ StartElement.\n static_cast(parser)->StartElement(name, atts);\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkXMLParserEndElement(void* parser, const char *name)\n{\n \/\/ End element handler that is registered with the XML_Parser. This\n \/\/ just casts the user data to a vtkXMLParser and calls EndElement.\n static_cast(parser)->EndElement(name);\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkXMLParserCharacterDataHandler(void* parser, const char* data,\n int length)\n{\n \/\/ Character data handler that is registered with the XML_Parser.\n \/\/ This just casts the user data to a vtkXMLParser and calls\n \/\/ CharacterDataHandler.\n static_cast(parser)->CharacterDataHandler(data, length);\n}\nAdd more error checking\/*=========================================================================\n\n Program: Visualization Toolkit\n Module: vtkXMLParser.cxx\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n Copyright (c) 1993-2002 Ken Martin, Will Schroeder, Bill Lorensen \n All rights reserved.\n See Copyright.txt or http:\/\/www.kitware.com\/Copyright.htm for details.\n\n This software is distributed WITHOUT ANY WARRANTY; without even \n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR \n PURPOSE. See the above copyright notice for more information.\n\n=========================================================================*\/\n#include \"vtkXMLParser.h\"\n#include \"vtkObjectFactory.h\"\n\n#include \"expat.h\"\n#include \n#include \n\nvtkCxxRevisionMacro(vtkXMLParser, \"1.14\");\nvtkStandardNewMacro(vtkXMLParser);\n\n\/\/----------------------------------------------------------------------------\nvtkXMLParser::vtkXMLParser()\n{\n this->Stream = 0;\n this->Parser = 0;\n this->FileName = 0;\n this->InputString = 0;\n this->InputStringLength = 0;\n this->ParseError = 0;\n}\n\n\/\/----------------------------------------------------------------------------\nvtkXMLParser::~vtkXMLParser()\n{\n this->SetStream(0);\n this->SetFileName(0);\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkXMLParser::PrintSelf(ostream& os, vtkIndent indent)\n{\n this->Superclass::PrintSelf(os, indent);\n if(this->Stream)\n {\n os << indent << \"Stream: \" << this->Stream << \"\\n\";\n }\n else\n {\n os << indent << \"Stream: (none)\\n\";\n }\n os << indent << \"FileName: \" << (this->FileName? this->FileName : \"(none)\")\n << \"\\n\";\n}\n\n\/\/----------------------------------------------------------------------------\nint vtkXMLParser::Parse(const char* inputString)\n{\n this->InputString = inputString;\n this->InputStringLength = -1;\n int result = this->vtkXMLParser::Parse();\n this->InputString = 0;\n return result;\n}\n\n\/\/----------------------------------------------------------------------------\nint vtkXMLParser::Parse(const char* inputString, unsigned int length)\n{\n this->InputString = inputString;\n this->InputStringLength = length;\n int result = this->vtkXMLParser::Parse();\n this->InputString = 0;\n this->InputStringLength = -1;\n return result;\n}\n\n\n\/\/----------------------------------------------------------------------------\nint vtkXMLParser::Parse()\n{\n \/\/ Select source of XML\n ifstream ifs;\n if ( !this->InputString && !this->Stream && this->FileName )\n {\n \/\/ If it is file, open it and set the appropriate stream\n struct stat fs;\n if (stat(this->FileName, &fs) != 0) \n {\n vtkErrorMacro(\"Cannot open XML file: \" << this->FileName);\n return 0;\n }\n#ifdef _WIN32\n ifs.open(this->FileName, ios::binary | ios::in);\n#else\n ifs.open(this->FileName, ios::in);\n#endif\n if ( !ifs )\n {\n vtkErrorMacro(\"Cannot open XML file: \" << this->FileName);\n return 0;\n }\n this->Stream = &ifs;\n }\n\n \/\/ Create the expat XML parser.\n this->Parser = XML_ParserCreate(0);\n XML_SetElementHandler(this->Parser,\n &vtkXMLParserStartElement,\n &vtkXMLParserEndElement);\n XML_SetCharacterDataHandler(this->Parser,\n &vtkXMLParserCharacterDataHandler);\n XML_SetUserData(this->Parser, this);\n \n \/\/ Parse the input.\n int result = this->ParseXML();\n \n if(result)\n {\n \/\/ Tell the expat XML parser about the end-of-input.\n if(!XML_Parse(this->Parser, \"\", 0, 1))\n {\n this->ReportXmlParseError();\n result = 0;\n }\n }\n \n \/\/ Clean up the parser.\n XML_ParserFree(this->Parser);\n this->Parser = 0;\n \n \/\/ If the source was a file, reset the stream\n if ( this->Stream == &ifs )\n {\n this->Stream = 0;\n }\n\n return result;\n}\n\n\/\/----------------------------------------------------------------------------\nint vtkXMLParser::InitializeParser()\n{\n if ( this->Parser )\n {\n vtkErrorMacro(\"Parser already initialized\");\n this->ParseError = 1;\n return 0;\n }\n \/\/ Create the expat XML parser.\n this->Parser = XML_ParserCreate(0);\n XML_SetElementHandler(this->Parser,\n &vtkXMLParserStartElement,\n &vtkXMLParserEndElement);\n XML_SetCharacterDataHandler(this->Parser,\n &vtkXMLParserCharacterDataHandler);\n XML_SetUserData(this->Parser, this);\n this->ParseError = 0;\n return 1;\n}\n\n\/\/----------------------------------------------------------------------------\nint vtkXMLParser::ParseChunk(const char* inputString, unsigned int length)\n{\n if ( !this->Parser )\n {\n vtkErrorMacro(\"Parser not initialized\");\n this->ParseError = 1;\n return 0;\n }\n int res;\n res = this->ParseBuffer(inputString, length);\n if ( res == 0 )\n {\n this->ParseError = 1;\n }\n return res;\n}\n\n\/\/----------------------------------------------------------------------------\nint vtkXMLParser::CleanupParser()\n{\n if ( !this->Parser )\n {\n vtkErrorMacro(\"Parser not initialized\");\n this->ParseError = 1;\n return 0;\n }\n int result = !this->ParseError;\n if(result)\n {\n \/\/ Tell the expat XML parser about the end-of-input.\n if(!XML_Parse(this->Parser, \"\", 0, 1))\n {\n this->ReportXmlParseError();\n result = 0;\n }\n }\n \n \/\/ Clean up the parser.\n XML_ParserFree(this->Parser);\n this->Parser = 0;\n \n return result;\n}\n\n\/\/----------------------------------------------------------------------------\nint vtkXMLParser::ParseXML()\n{\n \/\/ Parsing of message\n if ( this->InputString )\n {\n if ( this->InputStringLength >= 0 )\n {\n return this->ParseBuffer(this->InputString, this->InputStringLength);\n }\n else\n {\n return this->ParseBuffer(this->InputString);\n }\n }\n\n \/\/ Make sure we have input.\n if(!this->Stream)\n {\n vtkErrorMacro(\"Parse() called with no Stream set.\");\n return 0;\n }\n \n \/\/ Default stream parser just reads a block at a time.\n istream& in = *(this->Stream);\n const int bufferSize = 4096; \n char buffer[bufferSize]; \n \n \/\/ Read in the stream and send its contents to the XML parser. This\n \/\/ read loop is very sensitive on certain platforms with slightly\n \/\/ broken stream libraries (like HPUX). Normally, it is incorrect\n \/\/ to not check the error condition on the fin.read() before using\n \/\/ the data, but the fin.gcount() will be zero if an error occurred.\n \/\/ Therefore, the loop should be safe everywhere.\n while(!this->ParsingComplete() && in)\n {\n in.read(buffer, bufferSize);\n if(in.gcount())\n {\n if(!this->ParseBuffer(buffer, in.gcount()))\n {\n return 0;\n }\n }\n }\n return 1;\n}\n\n\/\/----------------------------------------------------------------------------\nint vtkXMLParser::ParsingComplete()\n{\n \/\/ Default behavior is to parse to end of stream.\n return 0;\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkXMLParser::StartElement(const char *name,\n const char ** vtkNotUsed(atts))\n{\n this->ReportUnknownElement(name);\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkXMLParser::EndElement(const char * vtkNotUsed(name))\n{\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkXMLParser::CharacterDataHandler(const char* vtkNotUsed(inData),\n int vtkNotUsed(inLength))\n{\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkXMLParser::ReportStrayAttribute(const char* element, const char* attr,\n const char* value)\n{\n vtkWarningMacro(\"Stray attribute in XML stream: Element \" << element\n << \" has \" << attr << \"=\\\"\" << value << \"\\\"\");\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkXMLParser::ReportMissingAttribute(const char* element,\n const char* attr)\n{\n vtkErrorMacro(\"Missing attribute in XML stream: Element \" << element\n << \" is missing \" << attr);\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkXMLParser::ReportBadAttribute(const char* element, const char* attr,\n const char* value)\n{\n vtkErrorMacro(\"Bad attribute value in XML stream: Element \" << element\n << \" has \" << attr << \"=\\\"\" << value << \"\\\"\");\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkXMLParser::ReportUnknownElement(const char* element)\n{\n vtkErrorMacro(\"Unknown element in XML stream: \" << element);\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkXMLParser::ReportXmlParseError()\n{\n vtkErrorMacro(\"Error parsing XML in stream at line \"\n << XML_GetCurrentLineNumber(this->Parser)\n << \": \" << XML_ErrorString(XML_GetErrorCode(this->Parser)));\n}\n\n\/\/----------------------------------------------------------------------------\nunsigned long vtkXMLParser::GetXMLByteIndex()\n{\n return XML_GetCurrentByteIndex(this->Parser);\n}\n\n\/\/----------------------------------------------------------------------------\nint vtkXMLParser::ParseBuffer(const char* buffer, unsigned int count)\n{\n \/\/ Pass the buffer to the expat XML parser.\n if(!XML_Parse(this->Parser, buffer, count, 0))\n {\n this->ReportXmlParseError();\n return 0;\n }\n return 1;\n}\n\n\/\/----------------------------------------------------------------------------\nint vtkXMLParser::ParseBuffer(const char* buffer)\n{\n return this->ParseBuffer(buffer, static_cast(strlen(buffer)));\n}\n\n\/\/----------------------------------------------------------------------------\nint vtkXMLParser::IsSpace(char c)\n{\n return isspace(c);\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkXMLParserStartElement(void* parser, const char *name,\n const char **atts)\n{\n \/\/ Begin element handler that is registered with the XML_Parser.\n \/\/ This just casts the user data to a vtkXMLParser and calls\n \/\/ StartElement.\n static_cast(parser)->StartElement(name, atts);\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkXMLParserEndElement(void* parser, const char *name)\n{\n \/\/ End element handler that is registered with the XML_Parser. This\n \/\/ just casts the user data to a vtkXMLParser and calls EndElement.\n static_cast(parser)->EndElement(name);\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkXMLParserCharacterDataHandler(void* parser, const char* data,\n int length)\n{\n \/\/ Character data handler that is registered with the XML_Parser.\n \/\/ This just casts the user data to a vtkXMLParser and calls\n \/\/ CharacterDataHandler.\n static_cast(parser)->CharacterDataHandler(data, length);\n}\n<|endoftext|>"} {"text":"\/*\n * Copyright (c) 2013 Stephen Williams (steve@icarus.com)\n *\n * This source code is free software; you can redistribute it\n * and\/or modify it in source code form under the terms of the GNU\n * General Public License as published by the Free Software\n * Foundation; either version 2 of the License, or (at your option)\n * any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n *\/\n\n# include \"priv.h\"\n# include \"nex_data.h\"\n# include \n\nint print_logic_gate(FILE*fd, ivl_net_logic_t net)\n{\n int rc = 0;\n\n\t\/\/ Do not handle logic gate widths.\n assert(ivl_logic_width(net) == 1);\n\n ivl_nexus_t nex_out = ivl_logic_pin(net,0);\n blif_nex_data_t*ned_out = blif_nex_data_t::get_nex_data(nex_out);\n\n assert(ned_out->get_width() == 1);\n\n fprintf(fd, \".names\");\n for (unsigned idx = 1 ; idx < ivl_logic_pins(net) ; idx += 1) {\n\t ivl_nexus_t nex = ivl_logic_pin(net,idx);\n\t blif_nex_data_t*ned = blif_nex_data_t::get_nex_data(nex);\n \t fprintf(fd, \" %s\", ned->get_name());\n }\n\n fprintf(fd, \" %s\", ned_out->get_name());\n fprintf(fd, \"\\n\");\n\n switch (ivl_logic_type(net)) {\n\t case IVL_LO_AND:\n\t for (unsigned idx = 1 ; idx < ivl_logic_pins(net) ; idx += 1)\n\t\t fprintf(fd, \"1\");\n\t fprintf(fd, \" 1\\n\");\n\t break;\n\t case IVL_LO_OR:\n\t assert(ivl_logic_pins(net)==3);\n\t fprintf(fd, \"1- 1\\n\");\n\t fprintf(fd, \"-1 1\\n\");\n\t break;\n\t case IVL_LO_XOR:\n\t assert(ivl_logic_pins(net)==3);\n\t fprintf(fd, \"10 1\\n\");\n\t fprintf(fd, \"01 1\\n\");\n\t break;\n\t default:\n\t fprintf(fd, \"# ERROR: Logic type not handled\\n\");\n\t rc += 1;\n\t break;\n }\n\n return rc;\n}\nAdd some more basic logic gates to blif target.\/*\n * Copyright (c) 2013 Stephen Williams (steve@icarus.com)\n *\n * This source code is free software; you can redistribute it\n * and\/or modify it in source code form under the terms of the GNU\n * General Public License as published by the Free Software\n * Foundation; either version 2 of the License, or (at your option)\n * any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n *\/\n\n# include \"priv.h\"\n# include \"nex_data.h\"\n# include \n\nint print_logic_gate(FILE*fd, ivl_net_logic_t net)\n{\n int rc = 0;\n\n\t\/\/ Do not handle logic gate widths.\n assert(ivl_logic_width(net) == 1);\n\n ivl_nexus_t nex_out = ivl_logic_pin(net,0);\n blif_nex_data_t*ned_out = blif_nex_data_t::get_nex_data(nex_out);\n\n assert(ned_out->get_width() == 1);\n\n fprintf(fd, \".names\");\n for (unsigned idx = 1 ; idx < ivl_logic_pins(net) ; idx += 1) {\n\t ivl_nexus_t nex = ivl_logic_pin(net,idx);\n\t blif_nex_data_t*ned = blif_nex_data_t::get_nex_data(nex);\n \t fprintf(fd, \" %s\", ned->get_name());\n }\n\n fprintf(fd, \" %s\", ned_out->get_name());\n fprintf(fd, \"\\n\");\n\n switch (ivl_logic_type(net)) {\n\t case IVL_LO_AND:\n\t for (unsigned idx = 1 ; idx < ivl_logic_pins(net) ; idx += 1)\n\t\t fprintf(fd, \"1\");\n\t fprintf(fd, \" 1\\n\");\n\t break;\n\t case IVL_LO_OR:\n\t assert(ivl_logic_pins(net)==3);\n\t fprintf(fd, \"1- 1\\n\");\n\t fprintf(fd, \"-1 1\\n\");\n\t break;\n\t case IVL_LO_XOR:\n\t assert(ivl_logic_pins(net)==3);\n\t fprintf(fd, \"10 1\\n\");\n\t fprintf(fd, \"01 1\\n\");\n\t break;\n\n\t case IVL_LO_NAND:\n\t assert(ivl_logic_pins(net)==3);\n\t fprintf(fd, \"0- 1\\n\");\n\t fprintf(fd, \"-0 1\\n\");\n\t break;\n\t case IVL_LO_NOR:\n\t for (unsigned idx = 1 ; idx < ivl_logic_pins(net) ; idx += 1)\n\t\t fprintf(fd, \"0\");\n\t fprintf(fd, \" 1\\n\");\n\t break;\n\t case IVL_LO_XNOR:\n\t assert(ivl_logic_pins(net)==3);\n\t fprintf(fd, \"00 1\\n\");\n\t fprintf(fd, \"11 1\\n\");\n\t break;\n\n\t case IVL_LO_BUF:\n\t assert(ivl_logic_pins(net)==2);\n\t fprintf(fd, \"1 1\\n\");\n\t break;\n\t case IVL_LO_NOT:\n\t assert(ivl_logic_pins(net)==2);\n\t fprintf(fd, \"0 1\\n\");\n\t break;\n\n\t default:\n\t fprintf(fd, \"# ERROR: Logic type %d not handled\\n\", ivl_logic_type(net));\n\t rc += 1;\n\t break;\n }\n\n return rc;\n}\n<|endoftext|>"} {"text":"#include \"builders\/terrain\/TerraGenerator.hpp\"\n#include \"math\/Mesh.hpp\"\n#include \"math\/Vector2.hpp\"\n\nusing namespace ClipperLib;\nusing namespace utymap::builders;\nusing namespace utymap::mapcss;\nusing namespace utymap::math;\nusing namespace utymap::utils;\n\nusing namespace std::placeholders;\n\nnamespace {\n \/\/\/ Tolerance for meshing\n const double AreaTolerance = 1000;\n const double Scale = 1E7;\n\n const std::string TerrainMeshName = \"terrain\";\n const std::string ColorNoiseFreqKey = \"color-noise-freq\";\n const std::string EleNoiseFreqKey = \"ele-noise-freq\";\n const std::string GradientKey = \"color\";\n\n const std::string TextureIndexKey = \"texture-index\";\n const std::string TextureTypeKey = \"texture-type\";\n const std::string TextureScaleKey = \"texture-scale\";\n \n const std::string MaxAreaKey = \"max-area\";\n const std::string HeightOffsetKey = \"height-offset\";\n const std::string LayerPriorityKey = \"layer-priority\";\n const std::string MeshNameKey = \"mesh-name\";\n const std::string MeshExtrasKey = \"mesh-extras\";\n const std::string GridCellSize = \"grid-cell-size\";\n\n const std::unordered_map ExtrasFuncs = \n {\n { \"forest\", std::bind(&TerraExtras::addForest, _1, _2) },\n { \"water\", std::bind(&TerraExtras::addWater, _1, _2) },\n };\n};\n\nTerraGenerator::TerraGenerator(const BuilderContext& context, const Style& style, ClipperEx& foregroundClipper) :\n context_(context),\n style_(style),\n foregroundClipper_(foregroundClipper),\n backGroundClipper_(),\n mesh_(TerrainMeshName),\n rect_(context.boundingBox.minPoint.longitude,\n context.boundingBox.minPoint.latitude,\n context.boundingBox.maxPoint.longitude,\n context.boundingBox.maxPoint.latitude)\n{\n}\n\nvoid TerraGenerator::addRegion(const std::string& type, std::unique_ptr region)\n{\n layers_[type].push(std::move(region));\n}\n\nvoid TerraGenerator::generate(Path& tileRect)\n{\n double size = style_.getValue(GridCellSize,\n context_.boundingBox.maxPoint.latitude - context_.boundingBox.minPoint.latitude, \n context_.boundingBox.center());\n splitter_.setParams(Scale, size);\n\n buildLayers();\n buildBackground(tileRect);\n\n context_.meshCallback(mesh_);\n}\n\n\/\/\/ process all found layers.\nvoid TerraGenerator::buildLayers()\n{\n \/\/ 1. process layers: regions with shared properties.\n std::stringstream ss(style_.getString(LayerPriorityKey));\n while (ss.good()) {\n std::string name;\n getline(ss, name, ',');\n auto layer = layers_.find(name);\n if (layer != layers_.end()) {\n buildFromRegions(layer->second, createRegionContext(style_, name + \"-\"));\n layers_.erase(layer);\n }\n }\n\n \/\/ 2. Process the rest: each region has already its own properties.\n for (auto& layer : layers_)\n while (!layer.second.empty()) {\n auto& region = layer.second.top();\n buildFromPaths(region->points, *region->context);\n layer.second.pop();\n }\n}\n\n\/\/\/ process the rest area.\nvoid TerraGenerator::buildBackground(Path& tileRect)\n{\n backGroundClipper_.AddPath(tileRect, ptSubject, true);\n Paths background;\n backGroundClipper_.Execute(ctDifference, background, pftNonZero, pftNonZero);\n backGroundClipper_.Clear();\n\n if (!background.empty())\n populateMesh(background, createRegionContext(style_, \"\"));\n}\n\nTerraGenerator::RegionContext TerraGenerator::createRegionContext(const Style& style, const std::string& prefix) const\n{\n double quadKeyWidth = context_.boundingBox.maxPoint.latitude - context_.boundingBox.minPoint.latitude;\n\n MeshBuilder::GeometryOptions geometryOptions(\n style.getValue(prefix + MaxAreaKey, quadKeyWidth * quadKeyWidth),\n style.getValue(prefix + EleNoiseFreqKey, quadKeyWidth),\n std::numeric_limits::lowest(), \/\/ no fixed elevation\n style.getValue(prefix + HeightOffsetKey, quadKeyWidth),\n false, \/\/ no flip\n false, \/\/ no back side\n 1 \/\/ no new vertices on boundaries \n );\n \n auto textureIndex = static_cast(style.getValue(prefix + TextureIndexKey));\n auto textureRegion = context_.styleProvider\n .getTexture(textureIndex, style.getString(prefix + TextureTypeKey))\n .random(0); \/\/ TODO use seed for randomization\n double scale = style.getValue(prefix + TextureScaleKey);\n\n MeshBuilder::AppearanceOptions appearanceOptions(\n context_.styleProvider.getGradient(style.getString(prefix + GradientKey)),\n style.getValue(prefix + ColorNoiseFreqKey, quadKeyWidth),\n textureIndex,\n textureRegion,\n scale > 0 ? scale :1\n );\n\n return RegionContext(style, prefix, geometryOptions, appearanceOptions);\n}\n\nvoid TerraGenerator::buildFromRegions(Regions& regions, const RegionContext& regionContext)\n{\n \/\/ merge all regions together\n Clipper clipper;\n while (!regions.empty()) {\n clipper.AddPaths(regions.top()->points, ptSubject, true);\n regions.pop();\n }\n\n Paths result;\n clipper.Execute(ctUnion, result, pftNonZero, pftNonZero);\n\n buildFromPaths(result, regionContext);\n}\n\nvoid TerraGenerator::buildFromPaths(const Paths& paths, const RegionContext& regionContext)\n{\n Paths solution;\n foregroundClipper_.AddPaths(paths, ptSubject, true);\n foregroundClipper_.Execute(ctDifference, solution, pftNonZero, pftNonZero);\n foregroundClipper_.moveSubjectToClip();\n\n populateMesh(solution, regionContext);\n}\n\nvoid TerraGenerator::populateMesh(Paths& paths, const RegionContext& regionContext)\n{\n ClipperLib::SimplifyPolygons(paths);\n ClipperLib::CleanPolygons(paths);\n\n bool hasHeightOffset = std::abs(regionContext.geometryOptions.heightOffset) > 1E-8;\n \/\/ calculate approximate size of overall points\n double size = 0;\n for (std::size_t i = 0; i < paths.size(); ++i)\n size += paths[i].size() * 1.5;\n\n Polygon polygon(static_cast(size));\n for (const Path& path : paths) {\n double area = ClipperLib::Area(path);\n bool isHole = area < 0;\n if (std::abs(area) < AreaTolerance)\n continue;\n\n backGroundClipper_.AddPath(path, ptClip, true);\n\n Points points = restorePoints(path);\n if (isHole)\n polygon.addHole(points);\n else\n polygon.addContour(points);\n\n if (hasHeightOffset)\n processHeightOffset(points, regionContext);\n }\n\n if (!polygon.points.empty())\n fillMesh(polygon, regionContext);\n}\n\n\/\/\/ restores mesh points from clipper points and injects new ones according to grid.\nTerraGenerator::Points TerraGenerator::restorePoints(const Path& path) const\n{\n auto lastItemIndex = path.size() - 1;\n Points points;\n points.reserve(path.size());\n for (int i = 0; i <= lastItemIndex; i++)\n splitter_.split(path[i], path[i == lastItemIndex ? 0 : i + 1], points);\n\n return std::move(points);\n}\n\nvoid TerraGenerator::fillMesh(Polygon& polygon, const RegionContext& regionContext)\n{\n std::string meshName = regionContext.style.getString(regionContext.prefix + MeshNameKey);\n if (!meshName.empty()) {\n Mesh polygonMesh(meshName);\n TerraExtras::Context extrasContext(polygonMesh, regionContext.style);\n context_.meshBuilder.addPolygon(polygonMesh, \n polygon, \n regionContext.geometryOptions, \n regionContext.appearanceOptions);\n context_.meshBuilder.writeTextureMappingInfo(polygonMesh, regionContext.appearanceOptions);\n\n addExtrasIfNecessary(polygonMesh, extrasContext, regionContext);\n context_.meshCallback(polygonMesh);\n }\n else {\n TerraExtras::Context extrasContext(mesh_, regionContext.style);\n context_.meshBuilder.addPolygon(mesh_,\n polygon, \n regionContext.geometryOptions, \n regionContext.appearanceOptions);\n context_.meshBuilder.writeTextureMappingInfo(mesh_, regionContext.appearanceOptions);\n\n addExtrasIfNecessary(mesh_, extrasContext, regionContext);\n }\n}\n\nvoid TerraGenerator::addExtrasIfNecessary(Mesh& mesh,\n TerraExtras::Context& extrasContext,\n const RegionContext& regionContext) const\n{\n std::string meshExtras = regionContext.style.getString(regionContext.prefix + MeshExtrasKey);\n if (meshExtras.empty())\n return;\n\n ExtrasFuncs.at(meshExtras)(context_, extrasContext);\n}\n\nvoid TerraGenerator::processHeightOffset(const Points& points, const RegionContext& regionContext)\n{\n \/\/ do not use elevation noise for height offset.\n auto newGeometryOptions = regionContext.geometryOptions;\n newGeometryOptions.eleNoiseFreq = 0;\n\n for (std::size_t i = 0; i < points.size(); ++i) {\n Vector2 p1 = points[i];\n Vector2 p2 = points[i == (points.size() - 1) ? 0 : i + 1];\n\n \/\/ check whether two points are on cell rect\n if (rect_.isOnBorder(p1) && rect_.isOnBorder(p2))\n continue;\n\n context_.meshBuilder.addPlane(mesh_, p1, p2, newGeometryOptions, regionContext.appearanceOptions);\n }\n}\ncore: fix static analyzer warning#include \"builders\/terrain\/TerraGenerator.hpp\"\n#include \"math\/Mesh.hpp\"\n#include \"math\/Vector2.hpp\"\n\nusing namespace ClipperLib;\nusing namespace utymap::builders;\nusing namespace utymap::mapcss;\nusing namespace utymap::math;\nusing namespace utymap::utils;\n\nusing namespace std::placeholders;\n\nnamespace {\n \/\/\/ Tolerance for meshing\n const double AreaTolerance = 1000;\n const double Scale = 1E7;\n\n const std::string TerrainMeshName = \"terrain\";\n const std::string ColorNoiseFreqKey = \"color-noise-freq\";\n const std::string EleNoiseFreqKey = \"ele-noise-freq\";\n const std::string GradientKey = \"color\";\n\n const std::string TextureIndexKey = \"texture-index\";\n const std::string TextureTypeKey = \"texture-type\";\n const std::string TextureScaleKey = \"texture-scale\";\n \n const std::string MaxAreaKey = \"max-area\";\n const std::string HeightOffsetKey = \"height-offset\";\n const std::string LayerPriorityKey = \"layer-priority\";\n const std::string MeshNameKey = \"mesh-name\";\n const std::string MeshExtrasKey = \"mesh-extras\";\n const std::string GridCellSize = \"grid-cell-size\";\n\n const std::unordered_map ExtrasFuncs = \n {\n { \"forest\", std::bind(&TerraExtras::addForest, _1, _2) },\n { \"water\", std::bind(&TerraExtras::addWater, _1, _2) },\n };\n};\n\nTerraGenerator::TerraGenerator(const BuilderContext& context, const Style& style, ClipperEx& foregroundClipper) :\n context_(context),\n style_(style),\n foregroundClipper_(foregroundClipper),\n backGroundClipper_(),\n mesh_(TerrainMeshName),\n rect_(context.boundingBox.minPoint.longitude,\n context.boundingBox.minPoint.latitude,\n context.boundingBox.maxPoint.longitude,\n context.boundingBox.maxPoint.latitude)\n{\n}\n\nvoid TerraGenerator::addRegion(const std::string& type, std::unique_ptr region)\n{\n layers_[type].push(std::move(region));\n}\n\nvoid TerraGenerator::generate(Path& tileRect)\n{\n double size = style_.getValue(GridCellSize,\n context_.boundingBox.maxPoint.latitude - context_.boundingBox.minPoint.latitude, \n context_.boundingBox.center());\n splitter_.setParams(Scale, size);\n\n buildLayers();\n buildBackground(tileRect);\n\n context_.meshCallback(mesh_);\n}\n\n\/\/\/ process all found layers.\nvoid TerraGenerator::buildLayers()\n{\n \/\/ 1. process layers: regions with shared properties.\n std::stringstream ss(style_.getString(LayerPriorityKey));\n while (ss.good()) {\n std::string name;\n getline(ss, name, ',');\n auto layer = layers_.find(name);\n if (layer != layers_.end()) {\n buildFromRegions(layer->second, createRegionContext(style_, name + \"-\"));\n layers_.erase(layer);\n }\n }\n\n \/\/ 2. Process the rest: each region has already its own properties.\n for (auto& layer : layers_)\n while (!layer.second.empty()) {\n auto& region = layer.second.top();\n buildFromPaths(region->points, *region->context);\n layer.second.pop();\n }\n}\n\n\/\/\/ process the rest area.\nvoid TerraGenerator::buildBackground(Path& tileRect)\n{\n backGroundClipper_.AddPath(tileRect, ptSubject, true);\n Paths background;\n backGroundClipper_.Execute(ctDifference, background, pftNonZero, pftNonZero);\n backGroundClipper_.Clear();\n\n if (!background.empty())\n populateMesh(background, createRegionContext(style_, \"\"));\n}\n\nTerraGenerator::RegionContext TerraGenerator::createRegionContext(const Style& style, const std::string& prefix) const\n{\n double quadKeyWidth = context_.boundingBox.maxPoint.latitude - context_.boundingBox.minPoint.latitude;\n\n MeshBuilder::GeometryOptions geometryOptions(\n style.getValue(prefix + MaxAreaKey, quadKeyWidth * quadKeyWidth),\n style.getValue(prefix + EleNoiseFreqKey, quadKeyWidth),\n std::numeric_limits::lowest(), \/\/ no fixed elevation\n style.getValue(prefix + HeightOffsetKey, quadKeyWidth),\n false, \/\/ no flip\n false, \/\/ no back side\n 1 \/\/ no new vertices on boundaries \n );\n \n auto textureIndex = static_cast(style.getValue(prefix + TextureIndexKey));\n auto textureRegion = context_.styleProvider\n .getTexture(textureIndex, style.getString(prefix + TextureTypeKey))\n .random(0); \/\/ TODO use seed for randomization\n double scale = style.getValue(prefix + TextureScaleKey);\n\n MeshBuilder::AppearanceOptions appearanceOptions(\n context_.styleProvider.getGradient(style.getString(prefix + GradientKey)),\n style.getValue(prefix + ColorNoiseFreqKey, quadKeyWidth),\n textureIndex,\n textureRegion,\n scale > 0 ? scale :1\n );\n\n return RegionContext(style, prefix, geometryOptions, appearanceOptions);\n}\n\nvoid TerraGenerator::buildFromRegions(Regions& regions, const RegionContext& regionContext)\n{\n \/\/ merge all regions together\n Clipper clipper;\n while (!regions.empty()) {\n clipper.AddPaths(regions.top()->points, ptSubject, true);\n regions.pop();\n }\n\n Paths result;\n clipper.Execute(ctUnion, result, pftNonZero, pftNonZero);\n\n buildFromPaths(result, regionContext);\n}\n\nvoid TerraGenerator::buildFromPaths(const Paths& paths, const RegionContext& regionContext)\n{\n Paths solution;\n foregroundClipper_.AddPaths(paths, ptSubject, true);\n foregroundClipper_.Execute(ctDifference, solution, pftNonZero, pftNonZero);\n foregroundClipper_.moveSubjectToClip();\n\n populateMesh(solution, regionContext);\n}\n\nvoid TerraGenerator::populateMesh(Paths& paths, const RegionContext& regionContext)\n{\n ClipperLib::SimplifyPolygons(paths);\n ClipperLib::CleanPolygons(paths);\n\n bool hasHeightOffset = std::abs(regionContext.geometryOptions.heightOffset) > 0;\n \/\/ calculate approximate size of overall points\n double size = 0;\n for (std::size_t i = 0; i < paths.size(); ++i)\n size += paths[i].size() * 1.5;\n\n Polygon polygon(static_cast(size));\n for (const Path& path : paths) {\n double area = ClipperLib::Area(path);\n bool isHole = area < 0;\n if (std::abs(area) < AreaTolerance)\n continue;\n\n backGroundClipper_.AddPath(path, ptClip, true);\n\n Points points = restorePoints(path);\n if (isHole)\n polygon.addHole(points);\n else\n polygon.addContour(points);\n\n if (hasHeightOffset)\n processHeightOffset(points, regionContext);\n }\n\n if (!polygon.points.empty())\n fillMesh(polygon, regionContext);\n}\n\n\/\/\/ restores mesh points from clipper points and injects new ones according to grid.\nTerraGenerator::Points TerraGenerator::restorePoints(const Path& path) const\n{\n auto lastItemIndex = path.size() - 1;\n Points points;\n points.reserve(path.size());\n for (int i = 0; i <= lastItemIndex; i++)\n splitter_.split(path[i], path[i == lastItemIndex ? 0 : i + 1], points);\n\n return std::move(points);\n}\n\nvoid TerraGenerator::fillMesh(Polygon& polygon, const RegionContext& regionContext)\n{\n std::string meshName = regionContext.style.getString(regionContext.prefix + MeshNameKey);\n if (!meshName.empty()) {\n Mesh polygonMesh(meshName);\n TerraExtras::Context extrasContext(polygonMesh, regionContext.style);\n context_.meshBuilder.addPolygon(polygonMesh, \n polygon, \n regionContext.geometryOptions, \n regionContext.appearanceOptions);\n context_.meshBuilder.writeTextureMappingInfo(polygonMesh, regionContext.appearanceOptions);\n\n addExtrasIfNecessary(polygonMesh, extrasContext, regionContext);\n context_.meshCallback(polygonMesh);\n }\n else {\n TerraExtras::Context extrasContext(mesh_, regionContext.style);\n context_.meshBuilder.addPolygon(mesh_,\n polygon, \n regionContext.geometryOptions, \n regionContext.appearanceOptions);\n context_.meshBuilder.writeTextureMappingInfo(mesh_, regionContext.appearanceOptions);\n\n addExtrasIfNecessary(mesh_, extrasContext, regionContext);\n }\n}\n\nvoid TerraGenerator::addExtrasIfNecessary(Mesh& mesh,\n TerraExtras::Context& extrasContext,\n const RegionContext& regionContext) const\n{\n std::string meshExtras = regionContext.style.getString(regionContext.prefix + MeshExtrasKey);\n if (meshExtras.empty())\n return;\n\n ExtrasFuncs.at(meshExtras)(context_, extrasContext);\n}\n\nvoid TerraGenerator::processHeightOffset(const Points& points, const RegionContext& regionContext)\n{\n \/\/ do not use elevation noise for height offset.\n auto newGeometryOptions = regionContext.geometryOptions;\n newGeometryOptions.eleNoiseFreq = 0;\n\n for (std::size_t i = 0; i < points.size(); ++i) {\n Vector2 p1 = points[i];\n Vector2 p2 = points[i == (points.size() - 1) ? 0 : i + 1];\n\n \/\/ check whether two points are on cell rect\n if (rect_.isOnBorder(p1) && rect_.isOnBorder(p2))\n continue;\n\n context_.meshBuilder.addPlane(mesh_, p1, p2, newGeometryOptions, regionContext.appearanceOptions);\n }\n}\n<|endoftext|>"} {"text":"\/*\n * Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.\n *\n * Permission is hereby granted, free of charge, to any person obtaining a\n * copy of this software and associated documentation files (the \"Software\"),\n * to deal in the Software without restriction, including without limitation\n * the rights to use, copy, modify, merge, publish, distribute, sublicense,\n * and\/or sell copies of the Software, and to permit persons to whom the\n * Software is furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n * DEALINGS IN THE SOFTWARE.\n *\/\n\n#pragma once\n\n#include \"onnx2trt.hpp\"\n\n#include \n#include \n\nnamespace onnx2trt {\n\nclass ImporterContext final : public IImporterContext {\n nvinfer1::INetworkDefinition* _network;\n nvinfer1::ILogger* _logger;\n std::list _owned_plugin_instances;\n std::list> _temp_bufs;\n std::unordered_map _user_inputs;\n std::unordered_map _user_outputs;\n std::unordered_map _opsets;\npublic:\n ImporterContext(nvinfer1::INetworkDefinition* network,\n nvinfer1::ILogger* logger)\n : _network(network), _logger(logger) {}\n virtual nvinfer1::INetworkDefinition* network() override { return _network; }\n nvinfer1::ILogger& logger() { return *_logger; }\n virtual ShapedWeights createTempWeights(ShapedWeights::DataType type,\n nvinfer1::Dims shape) override {\n ShapedWeights weights(type, nullptr, shape);\n _temp_bufs.push_back(std::vector(weights.size_bytes()));\n weights.values = _temp_bufs.back().data();\n return weights;\n }\n virtual nvinfer1::IPluginLayer* addPlugin(Plugin* plugin,\n std::vector const& inputs) override {\n \/\/ Note: Plugins are wrapped here to make them work with\n \/\/ onnx2trt::PluginFactory.\n auto* wrapped_plugin = new TypeSerializingPlugin(plugin);\n _owned_plugin_instances.emplace_back(wrapped_plugin);\n#if NV_TENSORRT_MAJOR < 4\n return _network->addPlugin(inputs.data(), inputs.size(), *wrapped_plugin);\n#else\n return _network->addPluginExt(inputs.data(), inputs.size(), *wrapped_plugin);\n#endif\n }\n bool setUserInput(const char* name, nvinfer1::ITensor* input) {\n _user_inputs[name] = input;\n return true;\n }\n bool setUserOutput(const char* name, nvinfer1::ITensor** output) {\n _user_outputs[name] = output;\n return true;\n }\n nvinfer1::ITensor* getUserInput(const char* name) {\n if( !_user_inputs.count(name) ) {\n return nullptr;\n } else {\n return _user_inputs.at(name);\n }\n }\n nvinfer1::ITensor** getUserOutput(const char* name) {\n if( !_user_outputs.count(name) ) {\n return nullptr;\n } else {\n return _user_outputs.at(name);\n }\n }\n std::unordered_map const& getUserOutputs() const {\n\t return _user_outputs;\n }\n void clearOpsets() { _opsets.clear(); }\n void addOpset(std::string domain, int64_t version) {\n _opsets.emplace(domain, version);\n }\n virtual int64_t getOpsetVersion(const char* domain=\"\") const override {\n assert(_opsets.count(domain));\n return _opsets.at(domain);\n }\n};\n\n} \/\/ namespace onnx2trt\nFix crash due to missing opset field in old models (#41)\/*\n * Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.\n *\n * Permission is hereby granted, free of charge, to any person obtaining a\n * copy of this software and associated documentation files (the \"Software\"),\n * to deal in the Software without restriction, including without limitation\n * the rights to use, copy, modify, merge, publish, distribute, sublicense,\n * and\/or sell copies of the Software, and to permit persons to whom the\n * Software is furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n * DEALINGS IN THE SOFTWARE.\n *\/\n\n#pragma once\n\n#include \"onnx2trt.hpp\"\n\n#include \n#include \n\nnamespace onnx2trt {\n\nclass ImporterContext final : public IImporterContext {\n nvinfer1::INetworkDefinition* _network;\n nvinfer1::ILogger* _logger;\n std::list _owned_plugin_instances;\n std::list> _temp_bufs;\n std::unordered_map _user_inputs;\n std::unordered_map _user_outputs;\n std::unordered_map _opsets;\npublic:\n ImporterContext(nvinfer1::INetworkDefinition* network,\n nvinfer1::ILogger* logger)\n : _network(network), _logger(logger) {}\n virtual nvinfer1::INetworkDefinition* network() override { return _network; }\n nvinfer1::ILogger& logger() { return *_logger; }\n virtual ShapedWeights createTempWeights(ShapedWeights::DataType type,\n nvinfer1::Dims shape) override {\n ShapedWeights weights(type, nullptr, shape);\n _temp_bufs.push_back(std::vector(weights.size_bytes()));\n weights.values = _temp_bufs.back().data();\n return weights;\n }\n virtual nvinfer1::IPluginLayer* addPlugin(Plugin* plugin,\n std::vector const& inputs) override {\n \/\/ Note: Plugins are wrapped here to make them work with\n \/\/ onnx2trt::PluginFactory.\n auto* wrapped_plugin = new TypeSerializingPlugin(plugin);\n _owned_plugin_instances.emplace_back(wrapped_plugin);\n#if NV_TENSORRT_MAJOR < 4\n return _network->addPlugin(inputs.data(), inputs.size(), *wrapped_plugin);\n#else\n return _network->addPluginExt(inputs.data(), inputs.size(), *wrapped_plugin);\n#endif\n }\n bool setUserInput(const char* name, nvinfer1::ITensor* input) {\n _user_inputs[name] = input;\n return true;\n }\n bool setUserOutput(const char* name, nvinfer1::ITensor** output) {\n _user_outputs[name] = output;\n return true;\n }\n nvinfer1::ITensor* getUserInput(const char* name) {\n if( !_user_inputs.count(name) ) {\n return nullptr;\n } else {\n return _user_inputs.at(name);\n }\n }\n nvinfer1::ITensor** getUserOutput(const char* name) {\n if( !_user_outputs.count(name) ) {\n return nullptr;\n } else {\n return _user_outputs.at(name);\n }\n }\n std::unordered_map const& getUserOutputs() const {\n\t return _user_outputs;\n }\n void clearOpsets() { _opsets.clear(); }\n void addOpset(std::string domain, int64_t version) {\n _opsets.emplace(domain, version);\n }\n virtual int64_t getOpsetVersion(const char* domain=\"\") const override {\n if (_opsets.empty()) {\n return 1;\n } else if (_opsets.size() == 1) {\n return _opsets.begin()->second;\n } else {\n assert(_opsets.count(domain));\n return _opsets.at(domain);\n }\n }\n};\n\n} \/\/ namespace onnx2trt\n<|endoftext|>"} {"text":"#ifndef UNDERLYING_FUNCTIONALITIES_HPP\n#define UNDERLYING_FUNCTIONALITIES_HPP\n\n#include \"crtp.hpp\"\n#include \"named_type_impl.hpp\"\n\n#include \n#include \n\n#if FLUENT_HOSTED == 1\n# include \n#endif\n\n\/\/ C++17 constexpr additions\n#if FLUENT_CPP17_PRESENT\n# define FLUENT_CONSTEXPR17 constexpr\n#else\n# define FLUENT_CONSTEXPR17 \n#endif\n\nnamespace fluent\n{\n\ntemplate \nstruct PreIncrementable : crtp\n{\n IGNORE_SHOULD_RETURN_REFERENCE_TO_THIS_BEGIN\n\n FLUENT_CONSTEXPR17 T& operator++()\n {\n ++this->underlying().get();\n return this->underlying();\n }\n\n IGNORE_SHOULD_RETURN_REFERENCE_TO_THIS_END\n};\n\ntemplate \nstruct PostIncrementable : crtp\n{\n IGNORE_SHOULD_RETURN_REFERENCE_TO_THIS_BEGIN\n\n FLUENT_CONSTEXPR17 T operator++(int)\n {\n return T(this->underlying().get()++);\n }\n\n IGNORE_SHOULD_RETURN_REFERENCE_TO_THIS_END\n};\n\ntemplate \nstruct PreDecrementable : crtp\n{\n IGNORE_SHOULD_RETURN_REFERENCE_TO_THIS_BEGIN\n\n FLUENT_CONSTEXPR17 T& operator--()\n {\n --this->underlying().get();\n return this->underlying();\n }\n\n IGNORE_SHOULD_RETURN_REFERENCE_TO_THIS_END\n};\n\ntemplate \nstruct PostDecrementable : crtp\n{\n IGNORE_SHOULD_RETURN_REFERENCE_TO_THIS_BEGIN\n\n FLUENT_CONSTEXPR17 T operator--(int)\n {\n return T( this->underlying().get()-- );\n }\n\n IGNORE_SHOULD_RETURN_REFERENCE_TO_THIS_END\n};\n\ntemplate \nstruct BinaryAddable : crtp\n{\n FLUENT_NODISCARD constexpr T operator+(T const& other) const\n {\n return T(this->underlying().get() + other.get());\n }\n FLUENT_CONSTEXPR17 T& operator+=(T const& other)\n {\n this->underlying().get() += other.get();\n return this->underlying();\n }\n};\n\ntemplate \nstruct UnaryAddable : crtp\n{\n FLUENT_NODISCARD constexpr T operator+() const\n {\n return T(+this->underlying().get());\n }\n};\n\ntemplate \nstruct Addable : BinaryAddable, UnaryAddable\n{\n using BinaryAddable::operator+;\n using UnaryAddable::operator+;\n};\n\ntemplate \nstruct BinarySubtractable : crtp\n{\n FLUENT_NODISCARD constexpr T operator-(T const& other) const\n {\n return T(this->underlying().get() - other.get());\n }\n FLUENT_CONSTEXPR17 T& operator-=(T const& other)\n {\n this->underlying().get() -= other.get();\n return this->underlying();\n }\n};\n \ntemplate \nstruct UnarySubtractable : crtp\n{\n FLUENT_NODISCARD constexpr T operator-() const\n {\n return T(-this->underlying().get());\n }\n};\n \ntemplate \nstruct Subtractable : BinarySubtractable, UnarySubtractable\n{\n using UnarySubtractable::operator-;\n using BinarySubtractable::operator-;\n};\n \ntemplate \nstruct Multiplicable : crtp\n{\n FLUENT_NODISCARD constexpr T operator*(T const& other) const\n {\n return T(this->underlying().get() * other.get());\n }\n FLUENT_CONSTEXPR17 T& operator*=(T const& other)\n {\n this->underlying().get() *= other.get();\n return this->underlying();\n }\n};\n\ntemplate \nstruct Divisible : crtp\n{\n FLUENT_NODISCARD constexpr T operator\/(T const& other) const\n {\n return T(this->underlying().get() \/ other.get());\n }\n FLUENT_CONSTEXPR17 T& operator\/=(T const& other)\n {\n this->underlying().get() \/= other.get();\n return this->underlying();\n }\n};\n\ntemplate \nstruct Modulable : crtp\n{\n FLUENT_NODISCARD constexpr T operator%(T const& other) const\n {\n return T(this->underlying().get() % other.get());\n }\n FLUENT_CONSTEXPR17 T& operator%=(T const& other)\n {\n this->underlying().get() %= other.get();\n return this->underlying();\n }\n};\n\ntemplate \nstruct BitWiseInvertable : crtp\n{\n FLUENT_NODISCARD constexpr T operator~() const\n {\n return T(~this->underlying().get());\n }\n};\n\ntemplate \nstruct BitWiseAndable : crtp\n{\n FLUENT_NODISCARD constexpr T operator&(T const& other) const\n {\n return T(this->underlying().get() & other.get());\n }\n FLUENT_CONSTEXPR17 T& operator&=(T const& other)\n {\n this->underlying().get() &= other.get();\n return this->underlying();\n }\n};\n\ntemplate \nstruct BitWiseOrable : crtp\n{\n FLUENT_NODISCARD constexpr T operator|(T const& other) const\n {\n return T(this->underlying().get() | other.get());\n }\n FLUENT_CONSTEXPR17 T& operator|=(T const& other)\n {\n this->underlying().get() |= other.get();\n return this->underlying();\n }\n};\n\ntemplate \nstruct BitWiseXorable : crtp\n{\n FLUENT_NODISCARD constexpr T operator^(T const& other) const\n {\n return T(this->underlying().get() ^ other.get());\n }\n FLUENT_CONSTEXPR17 T& operator^=(T const& other)\n {\n this->underlying().get() ^= other.get();\n return this->underlying();\n }\n};\n\ntemplate \nstruct BitWiseLeftShiftable : crtp\n{\n FLUENT_NODISCARD constexpr T operator<<(T const& other) const\n {\n return T(this->underlying().get() << other.get());\n }\n FLUENT_CONSTEXPR17 T& operator<<=(T const& other)\n {\n this->underlying().get() <<= other.get();\n return this->underlying();\n }\n};\n\ntemplate \nstruct BitWiseRightShiftable : crtp\n{\n FLUENT_NODISCARD constexpr T operator>>(T const& other) const\n {\n return T(this->underlying().get() >> other.get());\n }\n FLUENT_CONSTEXPR17 T& operator>>=(T const& other)\n {\n this->underlying().get() >>= other.get();\n return this->underlying();\n }\n};\n\ntemplate \nstruct Comparable : crtp\n{\n FLUENT_NODISCARD constexpr bool operator<(T const& other) const\n {\n return this->underlying().get() < other.get();\n }\n FLUENT_NODISCARD constexpr bool operator>(T const& other) const\n {\n return other.get() < this->underlying().get();\n }\n FLUENT_NODISCARD constexpr bool operator<=(T const& other) const\n {\n return !(other.get() < this->underlying().get());\n }\n FLUENT_NODISCARD constexpr bool operator>=(T const& other) const\n {\n return !(*this < other);\n }\n\/\/ On Visual Studio before 19.22, you cannot define constexpr with friend function\n\/\/ See: https:\/\/stackoverflow.com\/a\/60400110\n#if defined(_MSC_VER) && _MSC_VER < 1922\n FLUENT_NODISCARD constexpr bool operator==(T const& other) const\n {\n return !(*this < other) && !(other.get() < this->underlying().get());\n }\n#else\n FLUENT_NODISCARD friend constexpr bool operator==(Comparable const& self, T const& other)\n {\n return !(self < other) && !(other.get() < self.underlying().get());\n }\n#endif\n FLUENT_NODISCARD constexpr bool operator!=(T const& other) const\n {\n return !(*this == other);\n }\n};\n\ntemplate< typename T >\nstruct Dereferencable;\n\ntemplate< typename T, typename Parameter, template< typename > class ... Skills >\nstruct Dereferencable> : crtp, Dereferencable>\n{\n FLUENT_NODISCARD constexpr T& operator*() &\n {\n return this->underlying().get();\n }\n FLUENT_NODISCARD constexpr std::remove_reference_t const& operator*() const &\n {\n return this->underlying().get();\n }\n};\n\ntemplate \nstruct ImplicitlyConvertibleTo\n{\n template \n struct templ : crtp\n {\n FLUENT_NODISCARD constexpr operator Destination() const\n {\n return this->underlying().get();\n }\n };\n};\n\ntemplate \nstruct Printable : crtp\n{\n static constexpr bool is_printable = true;\n\n void print(std::ostream& os) const\n {\n os << this->underlying().get();\n }\n};\n\n#if FLUENT_HOSTED == 1\n template class... Skills>\n typename std::enable_if::is_printable, std::ostream&>::type\n operator<<(std::ostream& os, NamedType const& object)\n {\n object.print(os);\n return os;\n }\n#endif\n\ntemplate \nstruct Hashable\n{\n static constexpr bool is_hashable = true;\n};\n\ntemplate \nstruct FunctionCallable;\n\ntemplate class... Skills>\nstruct FunctionCallable> : crtp, FunctionCallable>\n{\n FLUENT_NODISCARD constexpr operator T const&() const\n {\n return this->underlying().get();\n }\n FLUENT_NODISCARD constexpr operator T&()\n {\n return this->underlying().get();\n }\n};\n\ntemplate \nstruct MethodCallable;\n\ntemplate class... Skills>\nstruct MethodCallable> : crtp, MethodCallable>\n{\n FLUENT_NODISCARD FLUENT_CONSTEXPR17 std::remove_reference_t const* operator->() const\n {\n return std::addressof(this->underlying().get());\n }\n FLUENT_NODISCARD FLUENT_CONSTEXPR17 std::remove_reference_t* operator->()\n {\n return std::addressof(this->underlying().get());\n }\n};\n\ntemplate \nstruct Callable\n : FunctionCallable\n , MethodCallable\n{\n};\n\ntemplate \nstruct Arithmetic\n : PreIncrementable\n , PostIncrementable\n , PreDecrementable\n , PostDecrementable\n , Addable\n , Subtractable\n , Multiplicable\n , Divisible\n , Modulable\n , BitWiseInvertable\n , BitWiseAndable\n , BitWiseOrable\n , BitWiseXorable\n , BitWiseLeftShiftable\n , BitWiseRightShiftable\n , Comparable\n , Printable\n , Hashable\n{\n};\n\n} \/\/ namespace fluent\n\nnamespace std\n{\ntemplate class... Skills>\nstruct hash>\n{\n using NamedType = fluent::NamedType;\n using checkIfHashable = typename std::enable_if::type;\n\n size_t operator()(fluent::NamedType const& x) const noexcept\n {\n static_assert(noexcept(std::hash()(x.get())), \"hash fuction should not throw\");\n\n return std::hash()(x.get());\n }\n};\n\n} \/\/ namespace std\n\n#endif\nWork around gcc bug with ambiguous post\/pre-increment.#ifndef UNDERLYING_FUNCTIONALITIES_HPP\n#define UNDERLYING_FUNCTIONALITIES_HPP\n\n#include \"crtp.hpp\"\n#include \"named_type_impl.hpp\"\n\n#include \n#include \n\n#if FLUENT_HOSTED == 1\n# include \n#endif\n\n\/\/ C++17 constexpr additions\n#if FLUENT_CPP17_PRESENT\n# define FLUENT_CONSTEXPR17 constexpr\n#else\n# define FLUENT_CONSTEXPR17 \n#endif\n\nnamespace fluent\n{\n\ntemplate \nstruct PreIncrementable : crtp\n{\n IGNORE_SHOULD_RETURN_REFERENCE_TO_THIS_BEGIN\n\n FLUENT_CONSTEXPR17 T& operator++()\n {\n ++this->underlying().get();\n return this->underlying();\n }\n\n IGNORE_SHOULD_RETURN_REFERENCE_TO_THIS_END\n};\n\ntemplate \nstruct PostIncrementable : crtp\n{\n IGNORE_SHOULD_RETURN_REFERENCE_TO_THIS_BEGIN\n\n FLUENT_CONSTEXPR17 T operator++(int)\n {\n return T(this->underlying().get()++);\n }\n\n IGNORE_SHOULD_RETURN_REFERENCE_TO_THIS_END\n};\n\ntemplate \nstruct PreDecrementable : crtp\n{\n IGNORE_SHOULD_RETURN_REFERENCE_TO_THIS_BEGIN\n\n FLUENT_CONSTEXPR17 T& operator--()\n {\n --this->underlying().get();\n return this->underlying();\n }\n\n IGNORE_SHOULD_RETURN_REFERENCE_TO_THIS_END\n};\n\ntemplate \nstruct PostDecrementable : crtp\n{\n IGNORE_SHOULD_RETURN_REFERENCE_TO_THIS_BEGIN\n\n FLUENT_CONSTEXPR17 T operator--(int)\n {\n return T( this->underlying().get()-- );\n }\n\n IGNORE_SHOULD_RETURN_REFERENCE_TO_THIS_END\n};\n\ntemplate \nstruct BinaryAddable : crtp\n{\n FLUENT_NODISCARD constexpr T operator+(T const& other) const\n {\n return T(this->underlying().get() + other.get());\n }\n FLUENT_CONSTEXPR17 T& operator+=(T const& other)\n {\n this->underlying().get() += other.get();\n return this->underlying();\n }\n};\n\ntemplate \nstruct UnaryAddable : crtp\n{\n FLUENT_NODISCARD constexpr T operator+() const\n {\n return T(+this->underlying().get());\n }\n};\n\ntemplate \nstruct Addable : BinaryAddable, UnaryAddable\n{\n using BinaryAddable::operator+;\n using UnaryAddable::operator+;\n};\n\ntemplate \nstruct BinarySubtractable : crtp\n{\n FLUENT_NODISCARD constexpr T operator-(T const& other) const\n {\n return T(this->underlying().get() - other.get());\n }\n FLUENT_CONSTEXPR17 T& operator-=(T const& other)\n {\n this->underlying().get() -= other.get();\n return this->underlying();\n }\n};\n \ntemplate \nstruct UnarySubtractable : crtp\n{\n FLUENT_NODISCARD constexpr T operator-() const\n {\n return T(-this->underlying().get());\n }\n};\n \ntemplate \nstruct Subtractable : BinarySubtractable, UnarySubtractable\n{\n using UnarySubtractable::operator-;\n using BinarySubtractable::operator-;\n};\n \ntemplate \nstruct Multiplicable : crtp\n{\n FLUENT_NODISCARD constexpr T operator*(T const& other) const\n {\n return T(this->underlying().get() * other.get());\n }\n FLUENT_CONSTEXPR17 T& operator*=(T const& other)\n {\n this->underlying().get() *= other.get();\n return this->underlying();\n }\n};\n\ntemplate \nstruct Divisible : crtp\n{\n FLUENT_NODISCARD constexpr T operator\/(T const& other) const\n {\n return T(this->underlying().get() \/ other.get());\n }\n FLUENT_CONSTEXPR17 T& operator\/=(T const& other)\n {\n this->underlying().get() \/= other.get();\n return this->underlying();\n }\n};\n\ntemplate \nstruct Modulable : crtp\n{\n FLUENT_NODISCARD constexpr T operator%(T const& other) const\n {\n return T(this->underlying().get() % other.get());\n }\n FLUENT_CONSTEXPR17 T& operator%=(T const& other)\n {\n this->underlying().get() %= other.get();\n return this->underlying();\n }\n};\n\ntemplate \nstruct BitWiseInvertable : crtp\n{\n FLUENT_NODISCARD constexpr T operator~() const\n {\n return T(~this->underlying().get());\n }\n};\n\ntemplate \nstruct BitWiseAndable : crtp\n{\n FLUENT_NODISCARD constexpr T operator&(T const& other) const\n {\n return T(this->underlying().get() & other.get());\n }\n FLUENT_CONSTEXPR17 T& operator&=(T const& other)\n {\n this->underlying().get() &= other.get();\n return this->underlying();\n }\n};\n\ntemplate \nstruct BitWiseOrable : crtp\n{\n FLUENT_NODISCARD constexpr T operator|(T const& other) const\n {\n return T(this->underlying().get() | other.get());\n }\n FLUENT_CONSTEXPR17 T& operator|=(T const& other)\n {\n this->underlying().get() |= other.get();\n return this->underlying();\n }\n};\n\ntemplate \nstruct BitWiseXorable : crtp\n{\n FLUENT_NODISCARD constexpr T operator^(T const& other) const\n {\n return T(this->underlying().get() ^ other.get());\n }\n FLUENT_CONSTEXPR17 T& operator^=(T const& other)\n {\n this->underlying().get() ^= other.get();\n return this->underlying();\n }\n};\n\ntemplate \nstruct BitWiseLeftShiftable : crtp\n{\n FLUENT_NODISCARD constexpr T operator<<(T const& other) const\n {\n return T(this->underlying().get() << other.get());\n }\n FLUENT_CONSTEXPR17 T& operator<<=(T const& other)\n {\n this->underlying().get() <<= other.get();\n return this->underlying();\n }\n};\n\ntemplate \nstruct BitWiseRightShiftable : crtp\n{\n FLUENT_NODISCARD constexpr T operator>>(T const& other) const\n {\n return T(this->underlying().get() >> other.get());\n }\n FLUENT_CONSTEXPR17 T& operator>>=(T const& other)\n {\n this->underlying().get() >>= other.get();\n return this->underlying();\n }\n};\n\ntemplate \nstruct Comparable : crtp\n{\n FLUENT_NODISCARD constexpr bool operator<(T const& other) const\n {\n return this->underlying().get() < other.get();\n }\n FLUENT_NODISCARD constexpr bool operator>(T const& other) const\n {\n return other.get() < this->underlying().get();\n }\n FLUENT_NODISCARD constexpr bool operator<=(T const& other) const\n {\n return !(other.get() < this->underlying().get());\n }\n FLUENT_NODISCARD constexpr bool operator>=(T const& other) const\n {\n return !(*this < other);\n }\n\/\/ On Visual Studio before 19.22, you cannot define constexpr with friend function\n\/\/ See: https:\/\/stackoverflow.com\/a\/60400110\n#if defined(_MSC_VER) && _MSC_VER < 1922\n FLUENT_NODISCARD constexpr bool operator==(T const& other) const\n {\n return !(*this < other) && !(other.get() < this->underlying().get());\n }\n#else\n FLUENT_NODISCARD friend constexpr bool operator==(Comparable const& self, T const& other)\n {\n return !(self < other) && !(other.get() < self.underlying().get());\n }\n#endif\n FLUENT_NODISCARD constexpr bool operator!=(T const& other) const\n {\n return !(*this == other);\n }\n};\n\ntemplate< typename T >\nstruct Dereferencable;\n\ntemplate< typename T, typename Parameter, template< typename > class ... Skills >\nstruct Dereferencable> : crtp, Dereferencable>\n{\n FLUENT_NODISCARD constexpr T& operator*() &\n {\n return this->underlying().get();\n }\n FLUENT_NODISCARD constexpr std::remove_reference_t const& operator*() const &\n {\n return this->underlying().get();\n }\n};\n\ntemplate \nstruct ImplicitlyConvertibleTo\n{\n template \n struct templ : crtp\n {\n FLUENT_NODISCARD constexpr operator Destination() const\n {\n return this->underlying().get();\n }\n };\n};\n\ntemplate \nstruct Printable : crtp\n{\n static constexpr bool is_printable = true;\n\n void print(std::ostream& os) const\n {\n os << this->underlying().get();\n }\n};\n\n#if FLUENT_HOSTED == 1\n template class... Skills>\n typename std::enable_if::is_printable, std::ostream&>::type\n operator<<(std::ostream& os, NamedType const& object)\n {\n object.print(os);\n return os;\n }\n#endif\n\ntemplate \nstruct Hashable\n{\n static constexpr bool is_hashable = true;\n};\n\ntemplate \nstruct FunctionCallable;\n\ntemplate class... Skills>\nstruct FunctionCallable> : crtp, FunctionCallable>\n{\n FLUENT_NODISCARD constexpr operator T const&() const\n {\n return this->underlying().get();\n }\n FLUENT_NODISCARD constexpr operator T&()\n {\n return this->underlying().get();\n }\n};\n\ntemplate \nstruct MethodCallable;\n\ntemplate class... Skills>\nstruct MethodCallable> : crtp, MethodCallable>\n{\n FLUENT_NODISCARD FLUENT_CONSTEXPR17 std::remove_reference_t const* operator->() const\n {\n return std::addressof(this->underlying().get());\n }\n FLUENT_NODISCARD FLUENT_CONSTEXPR17 std::remove_reference_t* operator->()\n {\n return std::addressof(this->underlying().get());\n }\n};\n\ntemplate \nstruct Callable\n : FunctionCallable\n , MethodCallable\n{\n};\n\ntemplate \nstruct Arithmetic\n : PreIncrementable\n , PostIncrementable\n , PreDecrementable\n , PostDecrementable\n , Addable\n , Subtractable\n , Multiplicable\n , Divisible\n , Modulable\n , BitWiseInvertable\n , BitWiseAndable\n , BitWiseOrable\n , BitWiseXorable\n , BitWiseLeftShiftable\n , BitWiseRightShiftable\n , Comparable\n , Printable\n , Hashable\n{\n using PostIncrementable::operator++;\n using PreIncrementable::operator++;\n using PostDecrementable::operator--;\n using PreDecrementable::operator--;\n};\n\n} \/\/ namespace fluent\n\nnamespace std\n{\ntemplate class... Skills>\nstruct hash>\n{\n using NamedType = fluent::NamedType;\n using checkIfHashable = typename std::enable_if::type;\n\n size_t operator()(fluent::NamedType const& x) const noexcept\n {\n static_assert(noexcept(std::hash()(x.get())), \"hash fuction should not throw\");\n\n return std::hash()(x.get());\n }\n};\n\n} \/\/ namespace std\n\n#endif\n<|endoftext|>"} {"text":"\/*\n * RingBufferSubHistory.h\n *\n * Created on: 20.05.2016\n * Author: hartung\n *\/\n\n#ifndef INCLUDE_SYNCHRONIZATION_RINGBUFFERSUBHISTORY_HPP_\n#define INCLUDE_SYNCHRONIZATION_RINGBUFFERSUBHISTORY_HPP_\n\n#include \"Stdafx.hpp\"\n#include \"BasicTypedefs.hpp\"\n#include \"synchronization\/HistoryEntry.hpp\"\n#include \"synchronization\/Interpolation.hpp\"\n\n\nnamespace Synchronization\n{\n\n class RingBufferSubHistory\n {\n public:\n\n size_type size() const;\n\n real_type getNewestTime() const;\n\n FMI::ValueCollection interpolate(const real_type & time);\n\n FMI::ValueCollection operator[](const real_type & time);\n\n const Interpolation& getInterpolation() const;\n\n friend class AbstractDataHistory;\n\n private:\n size_type _curIndex;\n size_type _lastInsertedElem;\n std::vector _entries;\n Interpolation _interpolation;\n\n size_type _numAddedElems;\n\n RingBufferSubHistory() = delete;\n\n RingBufferSubHistory(const Interpolation & interpolation,\n const FMI::ValueCollection & bufferScheme, size_type size = 300);\n\n bool_type insert(const HistoryEntry & in);\n\n size_type deleteOlderThan(const HistoryEntry & in);\n\n tuple checkValidEntries() const;\n };\n\n} \/* namespace Synchronization *\/\n\n#endif \/* INCLUDE_SYNCHRONIZATION_RINGBUFFERSUBHISTORY_HPP_ *\/\nApply code style\/*\n * RingBufferSubHistory.h\n *\n * Created on: 20.05.2016\n * Author: hartung\n *\/\n\n#ifndef INCLUDE_SYNCHRONIZATION_RINGBUFFERSUBHISTORY_HPP_\n#define INCLUDE_SYNCHRONIZATION_RINGBUFFERSUBHISTORY_HPP_\n\n#include \"Stdafx.hpp\"\n#include \"BasicTypedefs.hpp\"\n#include \"synchronization\/HistoryEntry.hpp\"\n#include \"synchronization\/Interpolation.hpp\"\n\nnamespace Synchronization\n{\n\n class RingBufferSubHistory\n {\n public:\n\n size_type size() const;\n\n real_type getNewestTime() const;\n\n FMI::ValueCollection interpolate(const real_type & time);\n\n FMI::ValueCollection operator[](const real_type & time);\n\n const Interpolation& getInterpolation() const;\n\n friend class AbstractDataHistory;\n\n private:\n size_type _curIndex;\n size_type _lastInsertedElem;\n std::vector _entries;\n Interpolation _interpolation;\n\n size_type _numAddedElems;\n\n RingBufferSubHistory() = delete;\n\n RingBufferSubHistory(const Interpolation & interpolation, const FMI::ValueCollection & bufferScheme,\n size_type size = 300);\n\n bool_type insert(const HistoryEntry & in);\n\n size_type deleteOlderThan(const HistoryEntry & in);\n\n \/**\n * Check, if _numAddedElems is greater than 1 and returns ...\n * Otherwise, an exception is thrown.\n *\/\n tuple checkValidEntries() const;\n };\n\n} \/* namespace Synchronization *\/\n\n#endif \/* INCLUDE_SYNCHRONIZATION_RINGBUFFERSUBHISTORY_HPP_ *\/\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: canvasgraphichelper.hxx,v $\n *\n * $Revision: 1.6 $\n *\n * last change: $Author: obo $ $Date: 2007-07-17 15:23:50 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef _CPPCANVAS_CANVASGRAPHICHELPER_HXX\n#define _CPPCANVAS_CANVASGRAPHICHELPER_HXX\n\n#include \n#include \n\n#include \n\n#include \n\nnamespace com { namespace sun { namespace star { namespace rendering\n{\n class XGraphicDevice;\n} } } }\n\n\n\/* Definition of CanvasGraphicHelper class *\/\n\nnamespace cppcanvas\n{\n\n namespace internal\n {\n\n class CanvasGraphicHelper : public virtual CanvasGraphic\n {\n public:\n CanvasGraphicHelper( const CanvasSharedPtr& rParentCanvas );\n\n \/\/ CanvasGraphic implementation\n virtual void setTransformation( const ::basegfx::B2DHomMatrix& rMatrix );\n virtual ::basegfx::B2DHomMatrix getTransformation() const;\n virtual void setClip( const ::basegfx::B2DPolyPolygon& rClipPoly );\n virtual void setClip();\n virtual ::basegfx::B2DPolyPolygon const* getClip() const;\n virtual void setRGBAColor( Color::IntSRGBA );\n virtual Color::IntSRGBA getRGBAColor() const;\n virtual void setCompositeOp( CompositeOp aOp );\n virtual CompositeOp getCompositeOp() const;\n\n protected:\n \/\/ for our clients\n \/\/ ===============\n CanvasSharedPtr getCanvas() const;\n ::com::sun::star::uno::Reference< ::com::sun::star::rendering::XGraphicDevice > getGraphicDevice() const;\n const ::com::sun::star::rendering::RenderState& getRenderState() const;\n\n private:\n mutable ::com::sun::star::rendering::RenderState maRenderState;\n\n boost::optional maClipPolyPolygon;\n CanvasSharedPtr mpCanvas;\n ::com::sun::star::uno::Reference< ::com::sun::star::rendering::XGraphicDevice > mxGraphicDevice;\n };\n\n }\n}\n\n#endif \/* _CPPCANVAS_CANVASGRAPHICHELPER_HXX *\/\nINTEGRATION: CWS changefileheader (1.6.22); FILE MERGED 2008\/03\/31 13:07:07 rt 1.6.22.1: #i87441# Change license header to LPGL v3.\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2008 by Sun Microsystems, Inc.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: canvasgraphichelper.hxx,v $\n * $Revision: 1.7 $\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * \n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n#ifndef _CPPCANVAS_CANVASGRAPHICHELPER_HXX\n#define _CPPCANVAS_CANVASGRAPHICHELPER_HXX\n\n#include \n#include \n\n#include \n\n#include \n\nnamespace com { namespace sun { namespace star { namespace rendering\n{\n class XGraphicDevice;\n} } } }\n\n\n\/* Definition of CanvasGraphicHelper class *\/\n\nnamespace cppcanvas\n{\n\n namespace internal\n {\n\n class CanvasGraphicHelper : public virtual CanvasGraphic\n {\n public:\n CanvasGraphicHelper( const CanvasSharedPtr& rParentCanvas );\n\n \/\/ CanvasGraphic implementation\n virtual void setTransformation( const ::basegfx::B2DHomMatrix& rMatrix );\n virtual ::basegfx::B2DHomMatrix getTransformation() const;\n virtual void setClip( const ::basegfx::B2DPolyPolygon& rClipPoly );\n virtual void setClip();\n virtual ::basegfx::B2DPolyPolygon const* getClip() const;\n virtual void setRGBAColor( Color::IntSRGBA );\n virtual Color::IntSRGBA getRGBAColor() const;\n virtual void setCompositeOp( CompositeOp aOp );\n virtual CompositeOp getCompositeOp() const;\n\n protected:\n \/\/ for our clients\n \/\/ ===============\n CanvasSharedPtr getCanvas() const;\n ::com::sun::star::uno::Reference< ::com::sun::star::rendering::XGraphicDevice > getGraphicDevice() const;\n const ::com::sun::star::rendering::RenderState& getRenderState() const;\n\n private:\n mutable ::com::sun::star::rendering::RenderState maRenderState;\n\n boost::optional maClipPolyPolygon;\n CanvasSharedPtr mpCanvas;\n ::com::sun::star::uno::Reference< ::com::sun::star::rendering::XGraphicDevice > mxGraphicDevice;\n };\n\n }\n}\n\n#endif \/* _CPPCANVAS_CANVASGRAPHICHELPER_HXX *\/\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2011-2013 The Bitcoin developers\n\/\/ Distributed under the MIT\/X11 software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \"notificator.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#ifdef USE_DBUS\n#include \n#include \n#endif\n\n#ifdef Q_OS_MAC\n#include \n#include \"macnotificationhandler.h\"\n#endif\n\n\/\/ https:\/\/wiki.ubuntu.com\/NotificationDevelopmentGuidelines recommends at least 128\nconst int FREEDESKTOP_NOTIFICATION_ICON_SIZE = 128;\n\nNotificator::Notificator(const QString &programName, QSystemTrayIcon *trayicon, QWidget *parent):\n QObject(parent),\n parent(parent),\n programName(programName),\n mode(None),\n trayIcon(trayicon)\n#ifdef USE_DBUS\n ,interface(0)\n#endif\n{\n if(trayicon && trayicon->supportsMessages())\n {\n mode = QSystemTray;\n }\n#ifdef USE_DBUS\n interface = new QDBusInterface(\"org.freedesktop.Notifications\",\n \"\/org\/freedesktop\/Notifications\", \"org.freedesktop.Notifications\");\n if(interface->isValid())\n {\n mode = Freedesktop;\n }\n#endif\n#ifdef Q_OS_MAC\n \/\/ check if users OS has support for NSUserNotification\n if( MacNotificationHandler::instance()->hasUserNotificationCenterSupport()) {\n mode = UserNotificationCenter;\n }\n else {\n \/\/ Check if Growl is installed (based on Qt's tray icon implementation)\n CFURLRef cfurl;\n OSStatus status = LSGetApplicationForInfo(kLSUnknownType, kLSUnknownCreator, CFSTR(\"growlTicket\"), kLSRolesAll, 0, &cfurl);\n if (status != kLSApplicationNotFoundErr) {\n CFBundleRef bundle = CFBundleCreate(0, cfurl);\n if (CFStringCompare(CFBundleGetIdentifier(bundle), CFSTR(\"com.Growl.GrowlHelperApp\"), kCFCompareCaseInsensitive | kCFCompareBackwards) == kCFCompareEqualTo) {\n if (CFStringHasSuffix(CFURLGetString(cfurl), CFSTR(\"\/Growl.app\/\")))\n mode = Growl13;\n else\n mode = Growl12;\n }\n CFRelease(cfurl);\n CFRelease(bundle);\n }\n }\n#endif\n}\n\nNotificator::~Notificator()\n{\n#ifdef USE_DBUS\n delete interface;\n#endif\n}\n\n#ifdef USE_DBUS\n\n\/\/ Loosely based on http:\/\/www.qtcentre.org\/archive\/index.php\/t-25879.html\nclass FreedesktopImage\n{\npublic:\n FreedesktopImage() {}\n FreedesktopImage(const QImage &img);\n\n static int metaType();\n\n \/\/ Image to variant that can be marshalled over DBus\n static QVariant toVariant(const QImage &img);\n\nprivate:\n int width, height, stride;\n bool hasAlpha;\n int channels;\n int bitsPerSample;\n QByteArray image;\n\n friend QDBusArgument &operator<<(QDBusArgument &a, const FreedesktopImage &i);\n friend const QDBusArgument &operator>>(const QDBusArgument &a, FreedesktopImage &i);\n};\n\nQ_DECLARE_METATYPE(FreedesktopImage);\n\n\/\/ Image configuration settings\nconst int CHANNELS = 4;\nconst int BYTES_PER_PIXEL = 4;\nconst int BITS_PER_SAMPLE = 8;\n\nFreedesktopImage::FreedesktopImage(const QImage &img):\n width(img.width()),\n height(img.height()),\n stride(img.width() * BYTES_PER_PIXEL),\n hasAlpha(true),\n channels(CHANNELS),\n bitsPerSample(BITS_PER_SAMPLE)\n{\n \/\/ Convert 00xAARRGGBB to RGBA bytewise (endian-independent) format\n QImage tmp = img.convertToFormat(QImage::Format_ARGB32);\n const uint32_t *data = reinterpret_cast(tmp.bits());\n\n unsigned int num_pixels = width * height;\n image.resize(num_pixels * BYTES_PER_PIXEL);\n\n for(unsigned int ptr = 0; ptr < num_pixels; ++ptr)\n {\n image[ptr*BYTES_PER_PIXEL+0] = data[ptr] >> 16; \/\/ R\n image[ptr*BYTES_PER_PIXEL+1] = data[ptr] >> 8; \/\/ G\n image[ptr*BYTES_PER_PIXEL+2] = data[ptr]; \/\/ B\n image[ptr*BYTES_PER_PIXEL+3] = data[ptr] >> 24; \/\/ A\n }\n}\n\nQDBusArgument &operator<<(QDBusArgument &a, const FreedesktopImage &i)\n{\n a.beginStructure();\n a << i.width << i.height << i.stride << i.hasAlpha << i.bitsPerSample << i.channels << i.image;\n a.endStructure();\n return a;\n}\n\nconst QDBusArgument &operator>>(const QDBusArgument &a, FreedesktopImage &i)\n{\n a.beginStructure();\n a >> i.width >> i.height >> i.stride >> i.hasAlpha >> i.bitsPerSample >> i.channels >> i.image;\n a.endStructure();\n return a;\n}\n\nint FreedesktopImage::metaType()\n{\n return qDBusRegisterMetaType();\n}\n\nQVariant FreedesktopImage::toVariant(const QImage &img)\n{\n FreedesktopImage fimg(img);\n return QVariant(FreedesktopImage::metaType(), &fimg);\n}\n\nvoid Notificator::notifyDBus(Class cls, const QString &title, const QString &text, const QIcon &icon, int millisTimeout)\n{\n Q_UNUSED(cls);\n \/\/ Arguments for DBus call:\n QList args;\n\n \/\/ Program Name:\n args.append(programName);\n\n \/\/ Unique ID of this notification type:\n args.append(0U);\n\n \/\/ Application Icon, empty string\n args.append(QString());\n\n \/\/ Summary\n args.append(title);\n\n \/\/ Body\n args.append(text);\n\n \/\/ Actions (none, actions are deprecated)\n QStringList actions;\n args.append(actions);\n\n \/\/ Hints\n QVariantMap hints;\n\n \/\/ If no icon specified, set icon based on class\n QIcon tmpicon;\n if(icon.isNull())\n {\n QStyle::StandardPixmap sicon = QStyle::SP_MessageBoxQuestion;\n switch(cls)\n {\n case Information: sicon = QStyle::SP_MessageBoxInformation; break;\n case Warning: sicon = QStyle::SP_MessageBoxWarning; break;\n case Critical: sicon = QStyle::SP_MessageBoxCritical; break;\n default: break;\n }\n tmpicon = QApplication::style()->standardIcon(sicon);\n }\n else\n {\n tmpicon = icon;\n }\n hints[\"icon_data\"] = FreedesktopImage::toVariant(tmpicon.pixmap(FREEDESKTOP_NOTIFICATION_ICON_SIZE).toImage());\n args.append(hints);\n\n \/\/ Timeout (in msec)\n args.append(millisTimeout);\n\n \/\/ \"Fire and forget\"\n interface->callWithArgumentList(QDBus::NoBlock, \"Notify\", args);\n}\n#endif\n\nvoid Notificator::notifySystray(Class cls, const QString &title, const QString &text, const QIcon &icon, int millisTimeout)\n{\n Q_UNUSED(icon);\n QSystemTrayIcon::MessageIcon sicon = QSystemTrayIcon::NoIcon;\n switch(cls) \/\/ Set icon based on class\n {\n case Information: sicon = QSystemTrayIcon::Information; break;\n case Warning: sicon = QSystemTrayIcon::Warning; break;\n case Critical: sicon = QSystemTrayIcon::Critical; break;\n }\n trayIcon->showMessage(title, text, sicon, millisTimeout);\n}\n\n\/\/ Based on Qt's tray icon implementation\n#ifdef Q_OS_MAC\nvoid Notificator::notifyGrowl(Class cls, const QString &title, const QString &text, const QIcon &icon)\n{\n const QString script(\n \"tell application \\\"%5\\\"\\n\"\n \" set the allNotificationsList to {\\\"Notification\\\"}\\n\" \/\/ -- Make a list of all the notification types (all)\n \" set the enabledNotificationsList to {\\\"Notification\\\"}\\n\" \/\/ -- Make a list of the notifications (enabled)\n \" register as application \\\"%1\\\" all notifications allNotificationsList default notifications enabledNotificationsList\\n\" \/\/ -- Register our script with Growl\n \" notify with name \\\"Notification\\\" title \\\"%2\\\" description \\\"%3\\\" application name \\\"%1\\\"%4\\n\" \/\/ -- Send a Notification\n \"end tell\"\n );\n\n QString notificationApp(QApplication::applicationName());\n if (notificationApp.isEmpty())\n notificationApp = \"Application\";\n\n QPixmap notificationIconPixmap;\n if (icon.isNull()) { \/\/ If no icon specified, set icon based on class\n QStyle::StandardPixmap sicon = QStyle::SP_MessageBoxQuestion;\n switch (cls)\n {\n case Information: sicon = QStyle::SP_MessageBoxInformation; break;\n case Warning: sicon = QStyle::SP_MessageBoxWarning; break;\n case Critical: sicon = QStyle::SP_MessageBoxCritical; break;\n }\n notificationIconPixmap = QApplication::style()->standardPixmap(sicon);\n }\n else {\n QSize size = icon.actualSize(QSize(48, 48));\n notificationIconPixmap = icon.pixmap(size);\n }\n\n QString notificationIcon;\n QTemporaryFile notificationIconFile;\n if (!notificationIconPixmap.isNull() && notificationIconFile.open()) {\n QImageWriter writer(¬ificationIconFile, \"PNG\");\n if (writer.write(notificationIconPixmap.toImage()))\n notificationIcon = QString(\" image from location \\\"file:\/\/%1\\\"\").arg(notificationIconFile.fileName());\n }\n\n QString quotedTitle(title), quotedText(text);\n quotedTitle.replace(\"\\\\\", \"\\\\\\\\\").replace(\"\\\"\", \"\\\\\");\n quotedText.replace(\"\\\\\", \"\\\\\\\\\").replace(\"\\\"\", \"\\\\\");\n QString growlApp(this->mode == Notificator::Growl13 ? \"Growl\" : \"GrowlHelperApp\");\n MacNotificationHandler::instance()->sendAppleScript(script.arg(notificationApp, quotedTitle, quotedText, notificationIcon, growlApp));\n}\n\nvoid Notificator::notifyMacUserNotificationCenter(Class cls, const QString &title, const QString &text, const QIcon &icon) {\n \/\/ icon is not supported by the user notification center yet. OSX will use the app icon.\n MacNotificationHandler::instance()->showNotification(title, text);\n}\n\n#endif\n\nvoid Notificator::notify(Class cls, const QString &title, const QString &text, const QIcon &icon, int millisTimeout)\n{\n switch(mode)\n {\n#ifdef USE_DBUS\n case Freedesktop:\n notifyDBus(cls, title, text, icon, millisTimeout);\n break;\n#endif\n case QSystemTray:\n notifySystray(cls, title, text, icon, millisTimeout);\n break;\n#ifdef Q_OS_MAC\n case UserNotificationCenter:\n notifyMacUserNotificationCenter(cls, title, text, icon);\n break;\n case Growl12:\n case Growl13:\n notifyGrowl(cls, title, text, icon);\n break;\n#endif\n default:\n if(cls == Critical)\n {\n \/\/ Fall back to old fashioned pop-up dialog if critical and no other notification available\n QMessageBox::critical(parent, title, text, QMessageBox::Ok, QMessageBox::Ok);\n }\n break;\n }\n}\nUpdate notificator.cpp\/\/ Copyright (c) 2011-2013 The Bitcoin developers\n\/\/ Distributed under the MIT\/X11 software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \"notificator.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#ifdef USE_DBUS\n#include \n#include \n#endif\n\n#ifdef Q_OS_MAC\n#include \n#include \"macnotificationhandler.h\"\n#endif\n\n\/\/ https:\/\/wiki.ubuntu.com\/NotificationDevelopmentGuidelines recommends at least 128\n\/\/ const int FREEDESKTOP_NOTIFICATION_ICON_SIZE = 128;\n\nNotificator::Notificator(const QString &programName, QSystemTrayIcon *trayicon, QWidget *parent):\n QObject(parent),\n parent(parent),\n programName(programName),\n mode(None),\n trayIcon(trayicon)\n#ifdef USE_DBUS\n ,interface(0)\n#endif\n{\n if(trayicon && trayicon->supportsMessages())\n {\n mode = QSystemTray;\n }\n#ifdef USE_DBUS\n interface = new QDBusInterface(\"org.freedesktop.Notifications\",\n \"\/org\/freedesktop\/Notifications\", \"org.freedesktop.Notifications\");\n if(interface->isValid())\n {\n mode = Freedesktop;\n }\n#endif\n#ifdef Q_OS_MAC\n \/\/ check if users OS has support for NSUserNotification\n if( MacNotificationHandler::instance()->hasUserNotificationCenterSupport()) {\n mode = UserNotificationCenter;\n }\n else {\n \/\/ Check if Growl is installed (based on Qt's tray icon implementation)\n CFURLRef cfurl;\n OSStatus status = LSGetApplicationForInfo(kLSUnknownType, kLSUnknownCreator, CFSTR(\"growlTicket\"), kLSRolesAll, 0, &cfurl);\n if (status != kLSApplicationNotFoundErr) {\n CFBundleRef bundle = CFBundleCreate(0, cfurl);\n if (CFStringCompare(CFBundleGetIdentifier(bundle), CFSTR(\"com.Growl.GrowlHelperApp\"), kCFCompareCaseInsensitive | kCFCompareBackwards) == kCFCompareEqualTo) {\n if (CFStringHasSuffix(CFURLGetString(cfurl), CFSTR(\"\/Growl.app\/\")))\n mode = Growl13;\n else\n mode = Growl12;\n }\n CFRelease(cfurl);\n CFRelease(bundle);\n }\n }\n#endif\n}\n\nNotificator::~Notificator()\n{\n#ifdef USE_DBUS\n delete interface;\n#endif\n}\n\n#ifdef USE_DBUS\n\n\/\/ Loosely based on http:\/\/www.qtcentre.org\/archive\/index.php\/t-25879.html\nclass FreedesktopImage\n{\npublic:\n FreedesktopImage() {}\n FreedesktopImage(const QImage &img);\n\n static int metaType();\n\n \/\/ Image to variant that can be marshalled over DBus\n static QVariant toVariant(const QImage &img);\n\nprivate:\n int width, height, stride;\n bool hasAlpha;\n int channels;\n int bitsPerSample;\n QByteArray image;\n\n friend QDBusArgument &operator<<(QDBusArgument &a, const FreedesktopImage &i);\n friend const QDBusArgument &operator>>(const QDBusArgument &a, FreedesktopImage &i);\n};\n\nQ_DECLARE_METATYPE(FreedesktopImage);\n\n\/\/ Image configuration settings\nconst int CHANNELS = 4;\nconst int BYTES_PER_PIXEL = 4;\nconst int BITS_PER_SAMPLE = 8;\n\nFreedesktopImage::FreedesktopImage(const QImage &img):\n width(img.width()),\n height(img.height()),\n stride(img.width() * BYTES_PER_PIXEL),\n hasAlpha(true),\n channels(CHANNELS),\n bitsPerSample(BITS_PER_SAMPLE)\n{\n \/\/ Convert 00xAARRGGBB to RGBA bytewise (endian-independent) format\n QImage tmp = img.convertToFormat(QImage::Format_ARGB32);\n const uint32_t *data = reinterpret_cast(tmp.bits());\n\n unsigned int num_pixels = width * height;\n image.resize(num_pixels * BYTES_PER_PIXEL);\n\n for(unsigned int ptr = 0; ptr < num_pixels; ++ptr)\n {\n image[ptr*BYTES_PER_PIXEL+0] = data[ptr] >> 16; \/\/ R\n image[ptr*BYTES_PER_PIXEL+1] = data[ptr] >> 8; \/\/ G\n image[ptr*BYTES_PER_PIXEL+2] = data[ptr]; \/\/ B\n image[ptr*BYTES_PER_PIXEL+3] = data[ptr] >> 24; \/\/ A\n }\n}\n\nQDBusArgument &operator<<(QDBusArgument &a, const FreedesktopImage &i)\n{\n a.beginStructure();\n a << i.width << i.height << i.stride << i.hasAlpha << i.bitsPerSample << i.channels << i.image;\n a.endStructure();\n return a;\n}\n\nconst QDBusArgument &operator>>(const QDBusArgument &a, FreedesktopImage &i)\n{\n a.beginStructure();\n a >> i.width >> i.height >> i.stride >> i.hasAlpha >> i.bitsPerSample >> i.channels >> i.image;\n a.endStructure();\n return a;\n}\n\nint FreedesktopImage::metaType()\n{\n return qDBusRegisterMetaType();\n}\n\nQVariant FreedesktopImage::toVariant(const QImage &img)\n{\n FreedesktopImage fimg(img);\n return QVariant(FreedesktopImage::metaType(), &fimg);\n}\n\nvoid Notificator::notifyDBus(Class cls, const QString &title, const QString &text, const QIcon &icon, int millisTimeout)\n{\n Q_UNUSED(cls);\n \/\/ Arguments for DBus call:\n QList args;\n\n \/\/ Program Name:\n args.append(programName);\n\n \/\/ Unique ID of this notification type:\n args.append(0U);\n\n \/\/ Application Icon, empty string\n args.append(QString());\n\n \/\/ Summary\n args.append(title);\n\n \/\/ Body\n args.append(text);\n\n \/\/ Actions (none, actions are deprecated)\n QStringList actions;\n args.append(actions);\n\n \/\/ Hints\n QVariantMap hints;\n\n \/\/ If no icon specified, set icon based on class\n QIcon tmpicon;\n if(icon.isNull())\n {\n QStyle::StandardPixmap sicon = QStyle::SP_MessageBoxQuestion;\n switch(cls)\n {\n case Information: sicon = QStyle::SP_MessageBoxInformation; break;\n case Warning: sicon = QStyle::SP_MessageBoxWarning; break;\n case Critical: sicon = QStyle::SP_MessageBoxCritical; break;\n default: break;\n }\n tmpicon = QApplication::style()->standardIcon(sicon);\n }\n else\n {\n tmpicon = icon;\n }\n hints[\"icon_data\"] = FreedesktopImage::toVariant(tmpicon.pixmap(FREEDESKTOP_NOTIFICATION_ICON_SIZE).toImage());\n args.append(hints);\n\n \/\/ Timeout (in msec)\n args.append(millisTimeout);\n\n \/\/ \"Fire and forget\"\n interface->callWithArgumentList(QDBus::NoBlock, \"Notify\", args);\n}\n#endif\n\nvoid Notificator::notifySystray(Class cls, const QString &title, const QString &text, const QIcon &icon, int millisTimeout)\n{\n Q_UNUSED(icon);\n QSystemTrayIcon::MessageIcon sicon = QSystemTrayIcon::NoIcon;\n switch(cls) \/\/ Set icon based on class\n {\n case Information: sicon = QSystemTrayIcon::Information; break;\n case Warning: sicon = QSystemTrayIcon::Warning; break;\n case Critical: sicon = QSystemTrayIcon::Critical; break;\n }\n trayIcon->showMessage(title, text, sicon, millisTimeout);\n}\n\n\/\/ Based on Qt's tray icon implementation\n#ifdef Q_OS_MAC\nvoid Notificator::notifyGrowl(Class cls, const QString &title, const QString &text, const QIcon &icon)\n{\n const QString script(\n \"tell application \\\"%5\\\"\\n\"\n \" set the allNotificationsList to {\\\"Notification\\\"}\\n\" \/\/ -- Make a list of all the notification types (all)\n \" set the enabledNotificationsList to {\\\"Notification\\\"}\\n\" \/\/ -- Make a list of the notifications (enabled)\n \" register as application \\\"%1\\\" all notifications allNotificationsList default notifications enabledNotificationsList\\n\" \/\/ -- Register our script with Growl\n \" notify with name \\\"Notification\\\" title \\\"%2\\\" description \\\"%3\\\" application name \\\"%1\\\"%4\\n\" \/\/ -- Send a Notification\n \"end tell\"\n );\n\n QString notificationApp(QApplication::applicationName());\n if (notificationApp.isEmpty())\n notificationApp = \"Application\";\n\n QPixmap notificationIconPixmap;\n if (icon.isNull()) { \/\/ If no icon specified, set icon based on class\n QStyle::StandardPixmap sicon = QStyle::SP_MessageBoxQuestion;\n switch (cls)\n {\n case Information: sicon = QStyle::SP_MessageBoxInformation; break;\n case Warning: sicon = QStyle::SP_MessageBoxWarning; break;\n case Critical: sicon = QStyle::SP_MessageBoxCritical; break;\n }\n notificationIconPixmap = QApplication::style()->standardPixmap(sicon);\n }\n else {\n QSize size = icon.actualSize(QSize(48, 48));\n notificationIconPixmap = icon.pixmap(size);\n }\n\n QString notificationIcon;\n QTemporaryFile notificationIconFile;\n if (!notificationIconPixmap.isNull() && notificationIconFile.open()) {\n QImageWriter writer(¬ificationIconFile, \"PNG\");\n if (writer.write(notificationIconPixmap.toImage()))\n notificationIcon = QString(\" image from location \\\"file:\/\/%1\\\"\").arg(notificationIconFile.fileName());\n }\n\n QString quotedTitle(title), quotedText(text);\n quotedTitle.replace(\"\\\\\", \"\\\\\\\\\").replace(\"\\\"\", \"\\\\\");\n quotedText.replace(\"\\\\\", \"\\\\\\\\\").replace(\"\\\"\", \"\\\\\");\n QString growlApp(this->mode == Notificator::Growl13 ? \"Growl\" : \"GrowlHelperApp\");\n MacNotificationHandler::instance()->sendAppleScript(script.arg(notificationApp, quotedTitle, quotedText, notificationIcon, growlApp));\n}\n\nvoid Notificator::notifyMacUserNotificationCenter(Class cls, const QString &title, const QString &text, const QIcon &icon) {\n \/\/ icon is not supported by the user notification center yet. OSX will use the app icon.\n MacNotificationHandler::instance()->showNotification(title, text);\n}\n\n#endif\n\nvoid Notificator::notify(Class cls, const QString &title, const QString &text, const QIcon &icon, int millisTimeout)\n{\n switch(mode)\n {\n#ifdef USE_DBUS\n case Freedesktop:\n notifyDBus(cls, title, text, icon, millisTimeout);\n break;\n#endif\n case QSystemTray:\n notifySystray(cls, title, text, icon, millisTimeout);\n break;\n#ifdef Q_OS_MAC\n case UserNotificationCenter:\n notifyMacUserNotificationCenter(cls, title, text, icon);\n break;\n case Growl12:\n case Growl13:\n notifyGrowl(cls, title, text, icon);\n break;\n#endif\n default:\n if(cls == Critical)\n {\n \/\/ Fall back to old fashioned pop-up dialog if critical and no other notification available\n QMessageBox::critical(parent, title, text, QMessageBox::Ok, QMessageBox::Ok);\n }\n break;\n }\n}\n<|endoftext|>"} {"text":"\/* medStackedViewContainers.cpp --- \n * \n * Author: Julien Wintz\n * Copyright (C) 2008 - Julien Wintz, Inria.\n * Created: Thu May 13 12:39:09 2010 (+0200)\n * Version: $Id$\n * Last-Updated: Tue Jun 15 22:12:57 2010 (+0200)\n * By: Julien Wintz\n * Update #: 8\n *\/\n\n\/* Commentary: \n * \n *\/\n\n\/* Change log:\n * \n *\/\n\n#include \n\n#include \"medStackedViewContainers.h\"\n\n#include \"medViewContainer.h\"\n#include \"medViewContainerCustom.h\"\n#include \"medViewContainerMulti.h\"\n#include \"medViewContainerSingle.h\"\n\nclass medStackedViewContainersPrivate\n{\npublic:\n QHash containers;\n QString currentName;\n \n QPushButton *addButton;\n};\n\nmedStackedViewContainers::medStackedViewContainers(QWidget *parent) : QTabWidget(parent), d(new medStackedViewContainersPrivate)\n{\n this->setTabsClosable(true);\n this->setMovable(true);\n \n connect(this,SIGNAL(tabCloseRequested(int)),this,SLOT(deleteContainerClicked(int)));\n connect(this,SIGNAL(currentChanged(int)),this,SLOT(onCurrentContainerChanged(int)));\n\n d->addButton = new QPushButton();\n d->addButton->setStyleSheet(\"background-image: url(:medGui\/pixmaps\/plus_button.png);background-position: center;background-repeat: no-repeat;\");\n this->setCornerWidget(d->addButton);\n \n connect(d->addButton,SIGNAL(clicked()),this,SIGNAL(addTabButtonClicked()));\n}\n\nmedStackedViewContainers::~medStackedViewContainers(void)\n{\n delete d;\n\n d = NULL;\n}\n\nvoid medStackedViewContainers::lockTabs()\n{\n this->setTabsClosable(false);\n this->setMovable(false);\n d->addButton->hide();\n}\n\nvoid medStackedViewContainers::unlockTabs()\n{\n this->setTabsClosable(true);\n this->setMovable(true);\n d->addButton->show();\n}\n\n\/*\nvoid medStackedViewContainers::addNewTabContainer()\n{\n \/\/ This slot should disappear, instead the creation signal should be sent to the parent who should call for the creation of a new tab\n QString name = \"Tab \";\n name += QString::number(this->count());\n\n if (!this->container(name))\n {\n medViewContainer *new_container = new medViewContainerMulti();\n addContainer(name, new_container);\n this->setContainer(name);\n }\n else\n qDebug() << \"Container\" << name << \"already exists in this configurations\";\n}\n*\/\n\nvoid medStackedViewContainers::deleteContainerClicked(int index)\n{\n if (this->count() > 1)\n {\n d->containers.remove(this->tabText(index));\n this->removeTab(index);\n }\n}\n\nvoid medStackedViewContainers::addContainer(const QString &name, medViewContainer *container)\n{\n if (!container)\n return;\n\n d->containers[name] = container;\n\n connect(container, SIGNAL(focused(dtkAbstractView*)), this, SIGNAL(focused(dtkAbstractView*)));\n connect(container, SIGNAL(dropped(const medDataIndex&)), this, SIGNAL(dropped(const medDataIndex&)));\n\n if (!this->count())\n d->currentName = name;\n this->addTab(container, name);\n}\n\nvoid medStackedViewContainers::insertContainer(int index, const QString &name, medViewContainer *container)\n{\n if (!container)\n return;\n\n d->containers[name] = container;\n\n connect(container, SIGNAL(focused(dtkAbstractView*)), this, SIGNAL(focused(dtkAbstractView*)));\n connect(container, SIGNAL(dropped(const medDataIndex&)), this, SIGNAL(dropped(const medDataIndex&)));\n\n if (!this->count())\n d->currentName = name;\n this->insertTab(index,container, name);\n}\n\nvoid medStackedViewContainers::changeCurrentContainerType(const QString &name)\n{\n \/\/qDebug() << \"Changing container type to \" << name << \" from \" << this->current()->description();\n \/\/qDebug() << \"Current index is \" << this->currentIndex() << \" and tab name \" << this->tabText(this->currentIndex());\n\n if (name != this->current()->description())\n {\n medViewContainer *newTab = NULL;\n if (name == \"Single\")\n newTab = new medViewContainerSingle();\n else if (name == \"Custom\")\n newTab = new medViewContainerCustom();\n else if (name == \"Multi\")\n newTab = new medViewContainerMulti();\n\n if (newTab != NULL)\n {\n this->blockSignals(true);\n int index = this->currentIndex();\n QString tabName = this->tabText(index);\n this->removeTab(index);\n this->insertContainer(index,tabName,newTab);\n this->setCurrentIndex(index);\n this->blockSignals(false);\n }\n }\n}\n\nmedViewContainer* medStackedViewContainers::container(const QString &name) const\n{\n if (!d->containers.contains(name))\n return NULL;\n \n return d->containers[name];\n}\n\nvoid medStackedViewContainers::setContainer(const QString &name)\n{\n if (!d->containers.contains(name))\n {\n qWarning()<<\"container does not contain any container of name:\" << name;\n return;\n }\n \n d->currentName = name;\n this->setCurrentWidget(d->containers[name]);\n}\n\nmedViewContainer *medStackedViewContainers::current(void) const\n{\n return dynamic_cast (currentWidget());\n}\n\nQString medStackedViewContainers::currentName(void) const\n{\n return d->currentName;\n}\n\nQList medStackedViewContainers::keys()\n{\n return d->containers.keys();\n}\n\nvoid medStackedViewContainers::removeContainer(const QString& name)\n{\n if (d->containers.contains(name))\n {\n medViewContainer* container = d->containers[name];\n \/\/removeWidget(container);\n delete container;\n d->containers.remove(name);\n }\n}\n\nvoid medStackedViewContainers::onCurrentContainerChanged(int index)\n{\n QString name = this->tabText(index);\n emit currentChanged(name);\n}\nOne more bug correction\/* medStackedViewContainers.cpp --- \n * \n * Author: Julien Wintz\n * Copyright (C) 2008 - Julien Wintz, Inria.\n * Created: Thu May 13 12:39:09 2010 (+0200)\n * Version: $Id$\n * Last-Updated: Tue Jun 15 22:12:57 2010 (+0200)\n * By: Julien Wintz\n * Update #: 8\n *\/\n\n\/* Commentary: \n * \n *\/\n\n\/* Change log:\n * \n *\/\n\n#include \n\n#include \"medStackedViewContainers.h\"\n\n#include \"medViewContainer.h\"\n#include \"medViewContainerCustom.h\"\n#include \"medViewContainerMulti.h\"\n#include \"medViewContainerSingle.h\"\n\nclass medStackedViewContainersPrivate\n{\npublic:\n QHash containers;\n QString currentName;\n \n QPushButton *addButton;\n};\n\nmedStackedViewContainers::medStackedViewContainers(QWidget *parent) : QTabWidget(parent), d(new medStackedViewContainersPrivate)\n{\n this->setTabsClosable(true);\n this->setMovable(true);\n \n connect(this,SIGNAL(tabCloseRequested(int)),this,SLOT(deleteContainerClicked(int)));\n connect(this,SIGNAL(currentChanged(int)),this,SLOT(onCurrentContainerChanged(int)));\n\n d->addButton = new QPushButton();\n d->addButton->setStyleSheet(\"background-image: url(:medGui\/pixmaps\/plus_button.png);background-position: center;background-repeat: no-repeat;\");\n this->setCornerWidget(d->addButton);\n \n connect(d->addButton,SIGNAL(clicked()),this,SIGNAL(addTabButtonClicked()));\n}\n\nmedStackedViewContainers::~medStackedViewContainers(void)\n{\n delete d;\n\n d = NULL;\n}\n\nvoid medStackedViewContainers::lockTabs()\n{\n this->setTabsClosable(false);\n this->setMovable(false);\n d->addButton->hide();\n}\n\nvoid medStackedViewContainers::unlockTabs()\n{\n this->setTabsClosable(true);\n this->setMovable(true);\n d->addButton->show();\n}\n\n\/*\nvoid medStackedViewContainers::addNewTabContainer()\n{\n \/\/ This slot should disappear, instead the creation signal should be sent to the parent who should call for the creation of a new tab\n QString name = \"Tab \";\n name += QString::number(this->count());\n\n if (!this->container(name))\n {\n medViewContainer *new_container = new medViewContainerMulti();\n addContainer(name, new_container);\n this->setContainer(name);\n }\n else\n qDebug() << \"Container\" << name << \"already exists in this configurations\";\n}\n*\/\n\nvoid medStackedViewContainers::deleteContainerClicked(int index)\n{\n if (this->count() > 1)\n {\n d->containers.remove(this->tabText(index));\n this->removeTab(index);\n }\n}\n\nvoid medStackedViewContainers::addContainer(const QString &name, medViewContainer *container)\n{\n if (!container)\n return;\n\n d->containers[name] = container;\n\n connect(container, SIGNAL(focused(dtkAbstractView*)), this, SIGNAL(focused(dtkAbstractView*)));\n connect(container, SIGNAL(dropped(const medDataIndex&)), this, SIGNAL(dropped(const medDataIndex&)));\n\n if (!this->count())\n d->currentName = name;\n this->addTab(container, name);\n}\n\nvoid medStackedViewContainers::insertContainer(int index, const QString &name, medViewContainer *container)\n{\n if (!container)\n return;\n\n d->containers[name] = container;\n\n connect(container, SIGNAL(focused(dtkAbstractView*)), this, SIGNAL(focused(dtkAbstractView*)));\n connect(container, SIGNAL(dropped(const medDataIndex&)), this, SIGNAL(dropped(const medDataIndex&)));\n\n if (!this->count())\n d->currentName = name;\n this->insertTab(index,container, name);\n}\n\nvoid medStackedViewContainers::changeCurrentContainerType(const QString &name)\n{\n \/\/qDebug() << \"Changing container type to \" << name << \" from \" << this->current()->description();\n \/\/qDebug() << \"Current index is \" << this->currentIndex() << \" and tab name \" << this->tabText(this->currentIndex());\n\n if (name != this->current()->description())\n {\n medViewContainer *newTab = NULL;\n if (name == \"Single\")\n newTab = new medViewContainerSingle();\n else if (name == \"Custom\")\n newTab = new medViewContainerCustom();\n else if (name == \"Multi\")\n newTab = new medViewContainerMulti();\n\n if (newTab != NULL)\n {\n this->blockSignals(true);\n int index = this->currentIndex();\n QString tabName = this->tabText(index);\n this->removeTab(index);\n this->insertContainer(index,tabName,newTab);\n this->setCurrentIndex(index);\n this->blockSignals(false);\n\n this->onCurrentContainerChanged(index);\n }\n }\n}\n\nmedViewContainer* medStackedViewContainers::container(const QString &name) const\n{\n if (!d->containers.contains(name))\n return NULL;\n \n return d->containers[name];\n}\n\nvoid medStackedViewContainers::setContainer(const QString &name)\n{\n if (!d->containers.contains(name))\n {\n qWarning()<<\"container does not contain any container of name:\" << name;\n return;\n }\n \n d->currentName = name;\n this->setCurrentWidget(d->containers[name]);\n}\n\nmedViewContainer *medStackedViewContainers::current(void) const\n{\n return dynamic_cast (currentWidget());\n}\n\nQString medStackedViewContainers::currentName(void) const\n{\n return d->currentName;\n}\n\nQList medStackedViewContainers::keys()\n{\n return d->containers.keys();\n}\n\nvoid medStackedViewContainers::removeContainer(const QString& name)\n{\n if (d->containers.contains(name))\n {\n medViewContainer* container = d->containers[name];\n \/\/removeWidget(container);\n delete container;\n d->containers.remove(name);\n }\n}\n\nvoid medStackedViewContainers::onCurrentContainerChanged(int index)\n{\n QString name = this->tabText(index);\n emit currentChanged(name);\n}\n<|endoftext|>"} {"text":"#include \"statistics\/StatisticalSerie1D.hpp\"\n\nStatisticalSerie1D::StatisticalSerie1D(Sample* sample)\n : sample(sample), dataSource(sample->getDataSource()) {\n this->computeMode();\n this->computeAverage();\n this->computeMedian();\n this->computeStandardDeviation();\n this->computeRange();\n this->computeCoefficientOfVariation();\n}\n\nvoid StatisticalSerie1D::computeMode() {\n Data1DIterator it(this->dataSource.getData());\n this->mode.fill(0);\n unsigned highestCount = 0;\n unsigned currentMode = 0;\n\n while(!it.end()) {\n if(it.getY() > highestCount) {\n this->mode.fill(0);\n this->mode[0] = it.getX();\n highestCount = it.getY();\n currentMode = 1;\n } else if(it.getY() == highestCount && currentMode < this->mode.size()) {\n this->mode[currentMode++] = it.getX();\n }\n ++it;\n }\n}\n\nvoid StatisticalSerie1D::computeAverage() {\n Data1DIterator it(this->dataSource.getData());\n float sum = 0;\n\n while(!it.end()){\n sum += it.getX() * it.getY();\n ++it;\n }\n\n this->average = sum \/ this->dataSource.getTotalCount();\n}\n\nvoid StatisticalSerie1D::computeMedian() {\n const List& data(this->dataSource.getData());\n unsigned totalCount = this->dataSource.getTotalCount();\n unsigned middle = totalCount \/ 2;\n\n \/\/ Discrete stuff\n if(this->dataSource.getType() == DISCRETE) {\n \/\/ Rebuild value list\n List values;\n Data1DIterator it(data);\n while(!it.end()) {\n for(unsigned i = 0; i < it.getY(); ++i) {\n values.add(it.getX());\n }\n ++it;\n }\n\n if(totalCount % 2 == 0) { \/\/ Odd\n this->median = (values.get(middle) + values.get(middle + 1)) \/ 2;\n } else {\n this->median = values.get(middle);\n }\n return;\n }\n\n \/\/ Continous stuff\n\n \/\/ Looking up the interval containing the median\n Data1DIterator it(data);\n unsigned count = 0;\n const Data1D* data1D = NULL;\n while(!it.end()) {\n data1D = it++.get();\n if(count + data1D->getCount() > middle) {\n break;\n }\n count += data1D->getCount(); \/\/ Accumulate counts in intervals\n }\n\n Sanity::truthness(data1D != NULL, \"Middle interval of continous data not found when computing median\");\n\n this->median = data1D->getValue() \/\/ Start of interval\n + static_cast(this->dataSource).getIntervalSizes() \/ data1D->getCount()\n * (data1D->getCount() - (middle - count)); \/\/ Position of the middle in the interval\n}\n\nvoid StatisticalSerie1D::computeStandardDeviation() {\n Data1DIterator it(this->dataSource.getData());\n float sum = 0;\n\n while(!it.end()) {\n sum += (it.getX() - this->average) * (it.getX() - this->average) * it.getY();\n ++it;\n }\n\n this->standardDeviation = sqrt(sum \/ this->dataSource.getTotalCount());\n}\n\nvoid StatisticalSerie1D::computeRange() {\n const List& data(this->dataSource.getData());\n this->range = static_cast(data.get(data.size() - 1))->getValue()\n - static_cast(data.get(0))->getValue();\n}\n\nvoid StatisticalSerie1D::computeCoefficientOfVariation() {\n this->coefficientOfVariation = this->standardDeviation \/ this->average \/ 100;\n}\nModify median computation to take last commit into account#include \"statistics\/StatisticalSerie1D.hpp\"\n\nStatisticalSerie1D::StatisticalSerie1D(Sample* sample)\n : sample(sample), dataSource(sample->getDataSource()) {\n this->computeMode();\n this->computeAverage();\n this->computeMedian();\n this->computeStandardDeviation();\n this->computeRange();\n this->computeCoefficientOfVariation();\n}\n\nvoid StatisticalSerie1D::computeMode() {\n Data1DIterator it(this->dataSource.getData());\n this->mode.fill(0);\n unsigned highestCount = 0;\n unsigned currentMode = 0;\n\n while(!it.end()) {\n if(it.getY() > highestCount) {\n this->mode.fill(0);\n this->mode[0] = it.getX();\n highestCount = it.getY();\n currentMode = 1;\n } else if(it.getY() == highestCount && currentMode < this->mode.size()) {\n this->mode[currentMode++] = it.getX();\n }\n ++it;\n }\n}\n\nvoid StatisticalSerie1D::computeAverage() {\n Data1DIterator it(this->dataSource.getData());\n float sum = 0;\n\n while(!it.end()){\n sum += it.getX() * it.getY();\n ++it;\n }\n\n this->average = sum \/ this->dataSource.getTotalCount();\n}\n\nvoid StatisticalSerie1D::computeMedian() {\n const List& data(this->dataSource.getData());\n unsigned totalCount = this->dataSource.getTotalCount();\n unsigned middle = totalCount \/ 2;\n\n \/\/ Discrete stuff\n if(this->dataSource.getType() == DISCRETE) {\n \/\/ Rebuild value list\n List values;\n Data1DIterator it(data);\n while(!it.end()) {\n for(unsigned i = 0; i < it.getY(); ++i) {\n values.add(it.getX());\n }\n ++it;\n }\n\n if(totalCount % 2 == 0) { \/\/ Odd\n this->median = (values.get(middle) + values.get(middle + 1)) \/ 2;\n } else {\n this->median = values.get(middle);\n }\n return;\n }\n\n \/\/ Continous stuff\n\n \/\/ Looking up the interval containing the median\n Data1DIterator it(data);\n unsigned count = 0;\n const Data1D* data1D = NULL;\n while(!it.end()) {\n data1D = it++.get();\n if(count + data1D->getCount() > middle) {\n break;\n }\n count += data1D->getCount(); \/\/ Accumulate counts in intervals\n }\n\n Sanity::truthness(data1D != NULL, \"Middle interval of continous data not found when computing median\");\n\n float interval = static_cast(this->dataSource).getIntervalSizes();\n this->median = data1D->getValue() - interval \/ 2 \/\/ Start of interval\n + interval \/ data1D->getCount()\n * (data1D->getCount() - (middle - count)); \/\/ Position of the middle in the interval\n}\n\nvoid StatisticalSerie1D::computeStandardDeviation() {\n Data1DIterator it(this->dataSource.getData());\n float sum = 0;\n\n while(!it.end()) {\n sum += (it.getX() - this->average) * (it.getX() - this->average) * it.getY();\n ++it;\n }\n\n this->standardDeviation = sqrt(sum \/ this->dataSource.getTotalCount());\n}\n\nvoid StatisticalSerie1D::computeRange() {\n const List& data(this->dataSource.getData());\n this->range = static_cast(data.get(data.size() - 1))->getValue()\n - static_cast(data.get(0))->getValue();\n}\n\nvoid StatisticalSerie1D::computeCoefficientOfVariation() {\n this->coefficientOfVariation = this->standardDeviation \/ this->average \/ 100;\n}\n<|endoftext|>"} {"text":"\/*\n * robotStateRT.cpp\n *\n * ----------------------------------------------------------------------------\n * \"THE BEER-WARE LICENSE\" (Revision 42):\n * wrote this file. As long as you retain this notice you\n * can do whatever you want with this stuff. If we meet some day, and you think\n * this stuff is worth it, you can buy me a beer in return. Thomas Timm Andersen\n * ----------------------------------------------------------------------------\n *\/\n\n#include \"ur_modern_driver\/robot_state_RT.h\"\n\nRobotStateRT::RobotStateRT(std::condition_variable& msg_cond) {\n\tversion_ = 0.0;\n\ttime_ = 0.0;\n\tq_target_.assign(6, 0.0);\n\tqd_target_.assign(6, 0.0);\n\tqdd_target_.assign(6, 0.0);\n\ti_target_.assign(6, 0.0);\n\tm_target_.assign(6, 0.0);\n\tq_actual_.assign(6, 0.0);\n\tqd_actual_.assign(6, 0.0);\n\ti_actual_.assign(6, 0.0);\n\ti_control_.assign(6, 0.0);\n\ttool_vector_actual_.assign(6, 0.0);\n\ttcp_speed_actual_.assign(6, 0.0);\n\ttcp_force_.assign(6, 0.0);\n\ttool_vector_target_.assign(6, 0.0);\n\ttcp_speed_target_.assign(6, 0.0);\n\tdigital_input_bits_.assign(64, false);\n\tmotor_temperatures_.assign(6, 0.0);\n\tcontroller_timer_ = 0.0;\n\trobot_mode_ = 0.0;\n\tjoint_modes_.assign(6, 0.0);\n\tsafety_mode_ = 0.0;\n\ttool_accelerometer_values_.assign(3, 0.0);\n\tspeed_scaling_ = 0.0;\n\tlinear_momentum_norm_ = 0.0;\n\tv_main_ = 0.0;\n\tv_robot_ = 0.0;\n\ti_robot_ = 0.0;\n\tv_actual_.assign(6, 0.0);\n\tnew_data_available_ = false;\n\tpMsg_cond_ = &msg_cond;\n}\n\nRobotStateRT::~RobotStateRT() {\n\t\/* Make sure nobody is waiting after this thread is destroyed *\/\n\tnew_data_available_ = true;\n\tpMsg_cond_->notify_all();\n}\n\nbool RobotStateRT::getNewDataAvailable() {\n\treturn new_data_available_;\n}\n\nvoid RobotStateRT::finishedReading() {\n\tnew_data_available_ = false;\n}\n\ndouble RobotStateRT::ntohd(uint64_t nf) {\n\tdouble x;\n\tnf = be64toh(nf);\n\tmemcpy(&x, &nf, sizeof(x));\n\treturn x;\n}\n\nstd::vector RobotStateRT::unpackVector(uint8_t * buf, int start_index,\n\t\tint nr_of_vals) {\n\tuint64_t q;\n\tstd::vector ret;\n\tfor (int i = 0; i < nr_of_vals; i++) {\n\t\tmemcpy(&q, &buf[start_index + i * sizeof(q)], sizeof(q));\n\t\tret.push_back(ntohd(q));\n\t}\n\treturn ret;\n}\n\nstd::vector RobotStateRT::unpackDigitalInputBits(int64_t data) {\n\tstd::vector ret;\n\tfor (int i = 0; i < 64; i++) {\n\t\tret.push_back((data & (1 << i)) >> i);\n\t}\n\treturn ret;\n}\n\nvoid RobotStateRT::setVersion(double ver) {\n\tval_lock_.lock();\n\tversion_ = ver;\n\tval_lock_.unlock();\n}\n\ndouble RobotStateRT::getVersion() {\n\tdouble ret;\n\tval_lock_.lock();\n\tret = version_;\n\tval_lock_.unlock();\n\treturn ret;\n}\ndouble RobotStateRT::getTime() {\n\tdouble ret;\n\tval_lock_.lock();\n\tret = time_;\n\tval_lock_.unlock();\n\treturn ret;\n}\nstd::vector RobotStateRT::getQTarget() {\n\tstd::vector ret;\n\tval_lock_.lock();\n\tret = q_target_;\n\tval_lock_.unlock();\n\treturn ret;\n}\nstd::vector RobotStateRT::getQdTarget() {\n\tstd::vector ret;\n\tval_lock_.lock();\n\tret = q_target_;\n\tval_lock_.unlock();\n\treturn ret;\n}\nstd::vector RobotStateRT::getQddTarget() {\n\tstd::vector ret;\n\tval_lock_.lock();\n\tret = qdd_target_;\n\tval_lock_.unlock();\n\treturn ret;\n}\nstd::vector RobotStateRT::getITarget() {\n\tstd::vector ret;\n\tval_lock_.lock();\n\tret = i_target_;\n\tval_lock_.unlock();\n\treturn ret;\n}\nstd::vector RobotStateRT::getMTarget() {\n\tstd::vector ret;\n\tval_lock_.lock();\n\tret = m_target_;\n\tval_lock_.unlock();\n\treturn ret;\n}\nstd::vector RobotStateRT::getQActual() {\n\tstd::vector ret;\n\tval_lock_.lock();\n\tret = q_actual_;\n\tval_lock_.unlock();\n\treturn ret;\n}\nstd::vector RobotStateRT::getQdActual() {\n\tstd::vector ret;\n\tval_lock_.lock();\n\tret = qd_actual_;\n\tval_lock_.unlock();\n\treturn ret;\n}\nstd::vector RobotStateRT::getIActual() {\n\tstd::vector ret;\n\tval_lock_.lock();\n\tret = i_actual_;\n\tval_lock_.unlock();\n\treturn ret;\n}\nstd::vector RobotStateRT::getIControl() {\n\tstd::vector ret;\n\tval_lock_.lock();\n\tret = i_control_;\n\tval_lock_.unlock();\n\treturn ret;\n}\nstd::vector RobotStateRT::getToolVectorActual() {\n\tstd::vector ret;\n\tval_lock_.lock();\n\tret = tool_vector_actual_;\n\tval_lock_.unlock();\n\treturn ret;\n}\nstd::vector RobotStateRT::getTcpSpeedActual() {\n\tstd::vector ret;\n\tval_lock_.lock();\n\tret = tcp_speed_actual_;\n\tval_lock_.unlock();\n\treturn ret;\n}\nstd::vector RobotStateRT::getTcpForce() {\n\tstd::vector ret;\n\tval_lock_.lock();\n\tret = tcp_force_;\n\tval_lock_.unlock();\n\treturn ret;\n}\nstd::vector RobotStateRT::getToolVectorTarget() {\n\tstd::vector ret;\n\tval_lock_.lock();\n\tret = tool_vector_target_;\n\tval_lock_.unlock();\n\treturn ret;\n}\nstd::vector RobotStateRT::getTcpSpeedTarget() {\n\tstd::vector ret;\n\tval_lock_.lock();\n\tret = tcp_speed_target_;\n\tval_lock_.unlock();\n\treturn ret;\n}\nstd::vector RobotStateRT::getDigitalInputBits() {\n\tstd::vector ret;\n\tval_lock_.lock();\n\tret = digital_input_bits_;\n\tval_lock_.unlock();\n\treturn ret;\n}\nstd::vector RobotStateRT::getMotorTemperatures() {\n\tstd::vector ret;\n\tval_lock_.lock();\n\tret = motor_temperatures_;\n\tval_lock_.unlock();\n\treturn ret;\n}\ndouble RobotStateRT::getControllerTimer() {\n\tdouble ret;\n\tval_lock_.lock();\n\tret = controller_timer_;\n\tval_lock_.unlock();\n\treturn ret;\n}\ndouble RobotStateRT::getRobotMode() {\n\tdouble ret;\n\tval_lock_.lock();\n\tret = robot_mode_;\n\tval_lock_.unlock();\n\treturn ret;\n}\nstd::vector RobotStateRT::getJointModes() {\n\tstd::vector ret;\n\tval_lock_.lock();\n\tret = joint_modes_;\n\tval_lock_.unlock();\n\treturn ret;\n}\ndouble RobotStateRT::getSafety_mode() {\n\tdouble ret;\n\tval_lock_.lock();\n\tret = safety_mode_;\n\tval_lock_.unlock();\n\treturn ret;\n}\nstd::vector RobotStateRT::getToolAccelerometerValues() {\n\tstd::vector ret;\n\tval_lock_.lock();\n\tret = tool_accelerometer_values_;\n\tval_lock_.unlock();\n\treturn ret;\n}\ndouble RobotStateRT::getSpeedScaling() {\n\tdouble ret;\n\tval_lock_.lock();\n\tret = speed_scaling_;\n\tval_lock_.unlock();\n\treturn ret;\n}\ndouble RobotStateRT::getLinearMomentumNorm() {\n\tdouble ret;\n\tval_lock_.lock();\n\tret = linear_momentum_norm_;\n\tval_lock_.unlock();\n\treturn ret;\n}\ndouble RobotStateRT::getVMain() {\n\tdouble ret;\n\tval_lock_.lock();\n\tret = v_main_;\n\tval_lock_.unlock();\n\treturn ret;\n}\ndouble RobotStateRT::getVRobot() {\n\tdouble ret;\n\tval_lock_.lock();\n\tret = v_robot_;\n\tval_lock_.unlock();\n\treturn ret;\n}\ndouble RobotStateRT::getIRobot() {\n\tdouble ret;\n\tval_lock_.lock();\n\tret = i_robot_;\n\tval_lock_.unlock();\n\treturn ret;\n}\nstd::vector RobotStateRT::getVActual() {\n\tstd::vector ret;\n\tval_lock_.lock();\n\tret = v_actual_;\n\tval_lock_.unlock();\n\treturn ret;\n}\nvoid RobotStateRT::unpack(uint8_t * buf) {\n\tint64_t digital_input_bits;\n\tuint64_t unpack_to;\n\tuint16_t offset = 0;\n\tval_lock_.lock();\n\tint len;\n\tmemcpy(&len, &buf[offset], sizeof(len));\n\n\toffset += sizeof(len);\n\tlen = ntohl(len);\n\tif (version_ < 3.1 & len != 1044) {\n\t\t\/\/In 3.0, every 4th? package is malformed...?\n\t\t\/\/printf(\"Len: %i\\n\", len);\n\t\tval_lock_.unlock();\n\t\treturn;\n\t}\n\tmemcpy(&unpack_to, &buf[offset], sizeof(unpack_to));\n\ttime_ = RobotStateRT::ntohd(unpack_to);\n\toffset += sizeof(double);\n\tq_target_ = unpackVector(buf, offset, 6);\n\toffset += sizeof(double) * 6;\n\tqd_target_ = unpackVector(buf, offset, 6);\n\toffset += sizeof(double) * 6;\n\tqdd_target_ = unpackVector(buf, offset, 6);\n\toffset += sizeof(double) * 6;\n\ti_target_ = unpackVector(buf, offset, 6);\n\toffset += sizeof(double) * 6;\n\tm_target_ = unpackVector(buf, offset, 6);\n\toffset += sizeof(double) * 6;\n\tq_actual_ = unpackVector(buf, offset, 6);\n\toffset += sizeof(double) * 6;\n\tqd_actual_ = unpackVector(buf, offset, 6);\n\toffset += sizeof(double) * 6;\n\ti_actual_ = unpackVector(buf, offset, 6);\n\toffset += sizeof(double) * 6;\n\tif (version_ <= 1.8) {\n\t\tif (version_ != 1.6)\n\t\t\ttool_accelerometer_values_ = unpackVector(buf, offset, 3);\n\t\toffset += sizeof(double) * (3 + 15);\n\t\ttcp_force_ = unpackVector(buf, offset, 6);\n\t\toffset += sizeof(double) * 6;\n\t\ttool_vector_actual_ = unpackVector(buf, offset, 6);\n\t\toffset += sizeof(double) * 6;\n\t\ttcp_speed_actual_ = unpackVector(buf, offset, 6);\n\t} else {\n\t\ti_control_ = unpackVector(buf, offset, 6);\n\t\toffset += sizeof(double) * 6;\n\t\ttool_vector_actual_ = unpackVector(buf, offset, 6);\n\t\toffset += sizeof(double) * 6;\n\t\ttcp_speed_actual_ = unpackVector(buf, offset, 6);\n\t\toffset += sizeof(double) * 6;\n\t\ttcp_force_ = unpackVector(buf, offset, 6);\n\t\toffset += sizeof(double) * 6;\n\t\ttool_vector_target_ = unpackVector(buf, offset, 6);\n\t\toffset += sizeof(double) * 6;\n\t\ttcp_speed_target_ = unpackVector(buf, offset, 6);\n\t}\n\toffset += sizeof(double) * 6;\n\n\tmemcpy(&digital_input_bits, &buf[offset], sizeof(digital_input_bits));\n\tdigital_input_bits_ = unpackDigitalInputBits(be64toh(digital_input_bits));\n\toffset += sizeof(double);\n\tmotor_temperatures_ = unpackVector(buf, offset, 6);\n\toffset += sizeof(double) * 6;\n\tmemcpy(&unpack_to, &buf[offset], sizeof(unpack_to));\n\tcontroller_timer_ = ntohd(unpack_to);\n\tif (version_ > 1.6) {\n\t\toffset += sizeof(double) * 2;\n\t\tmemcpy(&unpack_to, &buf[offset], sizeof(unpack_to));\n\t\trobot_mode_ = ntohd(unpack_to);\n\t\tif (version_ > 1.7) {\n\t\t\toffset += sizeof(double);\n\t\t\tjoint_modes_ = unpackVector(buf, offset, 6);\n\t\t}\n\t}\n\tif (version_ > 1.8) {\n\t\toffset += sizeof(double) * 6;\n\t\tmemcpy(&unpack_to, &buf[offset], sizeof(unpack_to));\n\t\tsafety_mode_ = ntohd(unpack_to);\n\t\toffset += sizeof(double);\n\t\ttool_accelerometer_values_ = unpackVector(buf, offset, 3);\n\t\toffset += sizeof(double) * 3;\n\t\tmemcpy(&unpack_to, &buf[offset], sizeof(unpack_to));\n\t\tspeed_scaling_ = ntohd(unpack_to);\n\t\toffset += sizeof(double);\n\t\tmemcpy(&unpack_to, &buf[offset], sizeof(unpack_to));\n\t\tlinear_momentum_norm_ = ntohd(unpack_to);\n\t\toffset += sizeof(double);\n\t\tmemcpy(&unpack_to, &buf[offset], sizeof(unpack_to));\n\t\tv_main_ = ntohd(unpack_to);\n\t\toffset += sizeof(double);\n\t\tmemcpy(&unpack_to, &buf[offset], sizeof(unpack_to));\n\t\tv_robot_ = ntohd(unpack_to);\n\t\toffset += sizeof(double);\n\t\tmemcpy(&unpack_to, &buf[offset], sizeof(unpack_to));\n\t\ti_robot_ = ntohd(unpack_to);\n\t\toffset += sizeof(double);\n\t\tv_actual_ = unpackVector(buf, offset, 6);\n\t}\n\tval_lock_.unlock();\n\tnew_data_available_ = true;\n\tpMsg_cond_->notify_all();\n\n}\n\nFixed version bound check in RT message parsing\/*\n * robotStateRT.cpp\n *\n * ----------------------------------------------------------------------------\n * \"THE BEER-WARE LICENSE\" (Revision 42):\n * wrote this file. As long as you retain this notice you\n * can do whatever you want with this stuff. If we meet some day, and you think\n * this stuff is worth it, you can buy me a beer in return. Thomas Timm Andersen\n * ----------------------------------------------------------------------------\n *\/\n\n#include \"ur_modern_driver\/robot_state_RT.h\"\n\nRobotStateRT::RobotStateRT(std::condition_variable& msg_cond) {\n\tversion_ = 0.0;\n\ttime_ = 0.0;\n\tq_target_.assign(6, 0.0);\n\tqd_target_.assign(6, 0.0);\n\tqdd_target_.assign(6, 0.0);\n\ti_target_.assign(6, 0.0);\n\tm_target_.assign(6, 0.0);\n\tq_actual_.assign(6, 0.0);\n\tqd_actual_.assign(6, 0.0);\n\ti_actual_.assign(6, 0.0);\n\ti_control_.assign(6, 0.0);\n\ttool_vector_actual_.assign(6, 0.0);\n\ttcp_speed_actual_.assign(6, 0.0);\n\ttcp_force_.assign(6, 0.0);\n\ttool_vector_target_.assign(6, 0.0);\n\ttcp_speed_target_.assign(6, 0.0);\n\tdigital_input_bits_.assign(64, false);\n\tmotor_temperatures_.assign(6, 0.0);\n\tcontroller_timer_ = 0.0;\n\trobot_mode_ = 0.0;\n\tjoint_modes_.assign(6, 0.0);\n\tsafety_mode_ = 0.0;\n\ttool_accelerometer_values_.assign(3, 0.0);\n\tspeed_scaling_ = 0.0;\n\tlinear_momentum_norm_ = 0.0;\n\tv_main_ = 0.0;\n\tv_robot_ = 0.0;\n\ti_robot_ = 0.0;\n\tv_actual_.assign(6, 0.0);\n\tnew_data_available_ = false;\n\tpMsg_cond_ = &msg_cond;\n}\n\nRobotStateRT::~RobotStateRT() {\n\t\/* Make sure nobody is waiting after this thread is destroyed *\/\n\tnew_data_available_ = true;\n\tpMsg_cond_->notify_all();\n}\n\nbool RobotStateRT::getNewDataAvailable() {\n\treturn new_data_available_;\n}\n\nvoid RobotStateRT::finishedReading() {\n\tnew_data_available_ = false;\n}\n\ndouble RobotStateRT::ntohd(uint64_t nf) {\n\tdouble x;\n\tnf = be64toh(nf);\n\tmemcpy(&x, &nf, sizeof(x));\n\treturn x;\n}\n\nstd::vector RobotStateRT::unpackVector(uint8_t * buf, int start_index,\n\t\tint nr_of_vals) {\n\tuint64_t q;\n\tstd::vector ret;\n\tfor (int i = 0; i < nr_of_vals; i++) {\n\t\tmemcpy(&q, &buf[start_index + i * sizeof(q)], sizeof(q));\n\t\tret.push_back(ntohd(q));\n\t}\n\treturn ret;\n}\n\nstd::vector RobotStateRT::unpackDigitalInputBits(int64_t data) {\n\tstd::vector ret;\n\tfor (int i = 0; i < 64; i++) {\n\t\tret.push_back((data & (1 << i)) >> i);\n\t}\n\treturn ret;\n}\n\nvoid RobotStateRT::setVersion(double ver) {\n\tval_lock_.lock();\n\tversion_ = ver;\n\tval_lock_.unlock();\n}\n\ndouble RobotStateRT::getVersion() {\n\tdouble ret;\n\tval_lock_.lock();\n\tret = version_;\n\tval_lock_.unlock();\n\treturn ret;\n}\ndouble RobotStateRT::getTime() {\n\tdouble ret;\n\tval_lock_.lock();\n\tret = time_;\n\tval_lock_.unlock();\n\treturn ret;\n}\nstd::vector RobotStateRT::getQTarget() {\n\tstd::vector ret;\n\tval_lock_.lock();\n\tret = q_target_;\n\tval_lock_.unlock();\n\treturn ret;\n}\nstd::vector RobotStateRT::getQdTarget() {\n\tstd::vector ret;\n\tval_lock_.lock();\n\tret = q_target_;\n\tval_lock_.unlock();\n\treturn ret;\n}\nstd::vector RobotStateRT::getQddTarget() {\n\tstd::vector ret;\n\tval_lock_.lock();\n\tret = qdd_target_;\n\tval_lock_.unlock();\n\treturn ret;\n}\nstd::vector RobotStateRT::getITarget() {\n\tstd::vector ret;\n\tval_lock_.lock();\n\tret = i_target_;\n\tval_lock_.unlock();\n\treturn ret;\n}\nstd::vector RobotStateRT::getMTarget() {\n\tstd::vector ret;\n\tval_lock_.lock();\n\tret = m_target_;\n\tval_lock_.unlock();\n\treturn ret;\n}\nstd::vector RobotStateRT::getQActual() {\n\tstd::vector ret;\n\tval_lock_.lock();\n\tret = q_actual_;\n\tval_lock_.unlock();\n\treturn ret;\n}\nstd::vector RobotStateRT::getQdActual() {\n\tstd::vector ret;\n\tval_lock_.lock();\n\tret = qd_actual_;\n\tval_lock_.unlock();\n\treturn ret;\n}\nstd::vector RobotStateRT::getIActual() {\n\tstd::vector ret;\n\tval_lock_.lock();\n\tret = i_actual_;\n\tval_lock_.unlock();\n\treturn ret;\n}\nstd::vector RobotStateRT::getIControl() {\n\tstd::vector ret;\n\tval_lock_.lock();\n\tret = i_control_;\n\tval_lock_.unlock();\n\treturn ret;\n}\nstd::vector RobotStateRT::getToolVectorActual() {\n\tstd::vector ret;\n\tval_lock_.lock();\n\tret = tool_vector_actual_;\n\tval_lock_.unlock();\n\treturn ret;\n}\nstd::vector RobotStateRT::getTcpSpeedActual() {\n\tstd::vector ret;\n\tval_lock_.lock();\n\tret = tcp_speed_actual_;\n\tval_lock_.unlock();\n\treturn ret;\n}\nstd::vector RobotStateRT::getTcpForce() {\n\tstd::vector ret;\n\tval_lock_.lock();\n\tret = tcp_force_;\n\tval_lock_.unlock();\n\treturn ret;\n}\nstd::vector RobotStateRT::getToolVectorTarget() {\n\tstd::vector ret;\n\tval_lock_.lock();\n\tret = tool_vector_target_;\n\tval_lock_.unlock();\n\treturn ret;\n}\nstd::vector RobotStateRT::getTcpSpeedTarget() {\n\tstd::vector ret;\n\tval_lock_.lock();\n\tret = tcp_speed_target_;\n\tval_lock_.unlock();\n\treturn ret;\n}\nstd::vector RobotStateRT::getDigitalInputBits() {\n\tstd::vector ret;\n\tval_lock_.lock();\n\tret = digital_input_bits_;\n\tval_lock_.unlock();\n\treturn ret;\n}\nstd::vector RobotStateRT::getMotorTemperatures() {\n\tstd::vector ret;\n\tval_lock_.lock();\n\tret = motor_temperatures_;\n\tval_lock_.unlock();\n\treturn ret;\n}\ndouble RobotStateRT::getControllerTimer() {\n\tdouble ret;\n\tval_lock_.lock();\n\tret = controller_timer_;\n\tval_lock_.unlock();\n\treturn ret;\n}\ndouble RobotStateRT::getRobotMode() {\n\tdouble ret;\n\tval_lock_.lock();\n\tret = robot_mode_;\n\tval_lock_.unlock();\n\treturn ret;\n}\nstd::vector RobotStateRT::getJointModes() {\n\tstd::vector ret;\n\tval_lock_.lock();\n\tret = joint_modes_;\n\tval_lock_.unlock();\n\treturn ret;\n}\ndouble RobotStateRT::getSafety_mode() {\n\tdouble ret;\n\tval_lock_.lock();\n\tret = safety_mode_;\n\tval_lock_.unlock();\n\treturn ret;\n}\nstd::vector RobotStateRT::getToolAccelerometerValues() {\n\tstd::vector ret;\n\tval_lock_.lock();\n\tret = tool_accelerometer_values_;\n\tval_lock_.unlock();\n\treturn ret;\n}\ndouble RobotStateRT::getSpeedScaling() {\n\tdouble ret;\n\tval_lock_.lock();\n\tret = speed_scaling_;\n\tval_lock_.unlock();\n\treturn ret;\n}\ndouble RobotStateRT::getLinearMomentumNorm() {\n\tdouble ret;\n\tval_lock_.lock();\n\tret = linear_momentum_norm_;\n\tval_lock_.unlock();\n\treturn ret;\n}\ndouble RobotStateRT::getVMain() {\n\tdouble ret;\n\tval_lock_.lock();\n\tret = v_main_;\n\tval_lock_.unlock();\n\treturn ret;\n}\ndouble RobotStateRT::getVRobot() {\n\tdouble ret;\n\tval_lock_.lock();\n\tret = v_robot_;\n\tval_lock_.unlock();\n\treturn ret;\n}\ndouble RobotStateRT::getIRobot() {\n\tdouble ret;\n\tval_lock_.lock();\n\tret = i_robot_;\n\tval_lock_.unlock();\n\treturn ret;\n}\nstd::vector RobotStateRT::getVActual() {\n\tstd::vector ret;\n\tval_lock_.lock();\n\tret = v_actual_;\n\tval_lock_.unlock();\n\treturn ret;\n}\nvoid RobotStateRT::unpack(uint8_t * buf) {\n\tint64_t digital_input_bits;\n\tuint64_t unpack_to;\n\tuint16_t offset = 0;\n\tval_lock_.lock();\n\tint len;\n\tmemcpy(&len, &buf[offset], sizeof(len));\n\n\toffset += sizeof(len);\n\tlen = ntohl(len);\n\tif (version_ > 3. & version_ < 3.1 & len != 1044) {\n\t\t\/\/In 3.0, every 4th? package is malformed...?\n\t\t\/\/printf(\"Len: %i\\n\", len);\n\t\tval_lock_.unlock();\n\t\treturn;\n\t}\n\tmemcpy(&unpack_to, &buf[offset], sizeof(unpack_to));\n\ttime_ = RobotStateRT::ntohd(unpack_to);\n\toffset += sizeof(double);\n\tq_target_ = unpackVector(buf, offset, 6);\n\toffset += sizeof(double) * 6;\n\tqd_target_ = unpackVector(buf, offset, 6);\n\toffset += sizeof(double) * 6;\n\tqdd_target_ = unpackVector(buf, offset, 6);\n\toffset += sizeof(double) * 6;\n\ti_target_ = unpackVector(buf, offset, 6);\n\toffset += sizeof(double) * 6;\n\tm_target_ = unpackVector(buf, offset, 6);\n\toffset += sizeof(double) * 6;\n\tq_actual_ = unpackVector(buf, offset, 6);\n\toffset += sizeof(double) * 6;\n\tqd_actual_ = unpackVector(buf, offset, 6);\n\toffset += sizeof(double) * 6;\n\ti_actual_ = unpackVector(buf, offset, 6);\n\toffset += sizeof(double) * 6;\n\tif (version_ <= 1.8) {\n\t\tif (version_ != 1.6)\n\t\t\ttool_accelerometer_values_ = unpackVector(buf, offset, 3);\n\t\toffset += sizeof(double) * (3 + 15);\n\t\ttcp_force_ = unpackVector(buf, offset, 6);\n\t\toffset += sizeof(double) * 6;\n\t\ttool_vector_actual_ = unpackVector(buf, offset, 6);\n\t\toffset += sizeof(double) * 6;\n\t\ttcp_speed_actual_ = unpackVector(buf, offset, 6);\n\t} else {\n\t\ti_control_ = unpackVector(buf, offset, 6);\n\t\toffset += sizeof(double) * 6;\n\t\ttool_vector_actual_ = unpackVector(buf, offset, 6);\n\t\toffset += sizeof(double) * 6;\n\t\ttcp_speed_actual_ = unpackVector(buf, offset, 6);\n\t\toffset += sizeof(double) * 6;\n\t\ttcp_force_ = unpackVector(buf, offset, 6);\n\t\toffset += sizeof(double) * 6;\n\t\ttool_vector_target_ = unpackVector(buf, offset, 6);\n\t\toffset += sizeof(double) * 6;\n\t\ttcp_speed_target_ = unpackVector(buf, offset, 6);\n\t}\n\toffset += sizeof(double) * 6;\n\n\tmemcpy(&digital_input_bits, &buf[offset], sizeof(digital_input_bits));\n\tdigital_input_bits_ = unpackDigitalInputBits(be64toh(digital_input_bits));\n\toffset += sizeof(double);\n\tmotor_temperatures_ = unpackVector(buf, offset, 6);\n\toffset += sizeof(double) * 6;\n\tmemcpy(&unpack_to, &buf[offset], sizeof(unpack_to));\n\tcontroller_timer_ = ntohd(unpack_to);\n\tif (version_ > 1.6) {\n\t\toffset += sizeof(double) * 2;\n\t\tmemcpy(&unpack_to, &buf[offset], sizeof(unpack_to));\n\t\trobot_mode_ = ntohd(unpack_to);\n\t\tif (version_ > 1.7) {\n\t\t\toffset += sizeof(double);\n\t\t\tjoint_modes_ = unpackVector(buf, offset, 6);\n\t\t}\n\t}\n\tif (version_ > 1.8) {\n\t\toffset += sizeof(double) * 6;\n\t\tmemcpy(&unpack_to, &buf[offset], sizeof(unpack_to));\n\t\tsafety_mode_ = ntohd(unpack_to);\n\t\toffset += sizeof(double);\n\t\ttool_accelerometer_values_ = unpackVector(buf, offset, 3);\n\t\toffset += sizeof(double) * 3;\n\t\tmemcpy(&unpack_to, &buf[offset], sizeof(unpack_to));\n\t\tspeed_scaling_ = ntohd(unpack_to);\n\t\toffset += sizeof(double);\n\t\tmemcpy(&unpack_to, &buf[offset], sizeof(unpack_to));\n\t\tlinear_momentum_norm_ = ntohd(unpack_to);\n\t\toffset += sizeof(double);\n\t\tmemcpy(&unpack_to, &buf[offset], sizeof(unpack_to));\n\t\tv_main_ = ntohd(unpack_to);\n\t\toffset += sizeof(double);\n\t\tmemcpy(&unpack_to, &buf[offset], sizeof(unpack_to));\n\t\tv_robot_ = ntohd(unpack_to);\n\t\toffset += sizeof(double);\n\t\tmemcpy(&unpack_to, &buf[offset], sizeof(unpack_to));\n\t\ti_robot_ = ntohd(unpack_to);\n\t\toffset += sizeof(double);\n\t\tv_actual_ = unpackVector(buf, offset, 6);\n\t}\n\tval_lock_.unlock();\n\tnew_data_available_ = true;\n\tpMsg_cond_->notify_all();\n\n}\n\n<|endoftext|>"} {"text":"#include \"testApp.h\"\n\n\/\/--------------------------------------------------------------\nvoid testApp::setup(){\n ofBackground(0,0,0);\n ofSetBackgroundAuto(false);\n isFullScreen = false;\n ofSetFrameRate(30);\n \n masterCounter = 0;\n direction = 1; \/\/count up\n \n \/\/ OSC STUFF\n receiver.setup(PORT);\n meters = new float[7];\n \n \/\/RECT STUFF\n rectX = 0;\n rectY = 0;\n rectSize = 30;\n rectSpacing = 0;\n numYRects = ofGetWidth()\/rectSize-rectSpacing;\n numXRects = ofGetHeight()\/rectSize-rectSpacing;\n numRects = numYRects*numXRects;\n rectCount = 0;\n ofLogNotice(\"\\n numYRects: \"+ofToString(numYRects)+\"\\n numXRects: \"+ofToString(numXRects)+\"\\n numRects: \"+ofToString(numRects));\n}\n\n\/\/--------------------------------------------------------------\nvoid testApp::update(){\n\n \n\tparseOSCMessages();\n \n \/\/ FUN STUFF\n masterCounter+=direction;\n if (masterCounter > 2000) {\n direction = -1;\n }\n if (masterCounter < -2000) {\n direction = 1;\n }\n\n\n}\n\n\/\/--------------------------------------------------------------\nvoid testApp::draw(){\n \n \/\/drawHorizon();\n \n \/\/ Structured rectangles\n \n int xPos = ofGetWidth()\/2+ofGetWidth()\/2*meters[4]; \/\/percussion\n int yPos = ofGetHeight()\/2;\n int rectSize = 100;\n ofSetColor(0, 255*meters[4], 0);\n ofRect(xPos, yPos, rectSize, rectSize);\n \n}\n\n\/\/--------------------------------------------------------------\nvoid testApp::drawHorizon() {\n \/\/Abstract line stuff\n for (int i = 0; i < ofGetWidth(); i++) {\n \n \/\/ set the color for each line\n int r = meters[0]*255;\n int g = meters[1]*255;\n int b = meters[2]*255;\n \n \/\/ line start and destination\n int xStart = i;\n int yStart = ofGetHeight()\/2;\n int xDest = i*sin(i)*400; \/\/400 is arbitrary.\n int yDest = i*cos(i)*masterCounter*meters[1];\n \n \/\/shake the signal\n if (masterCounter%2 == 0) {\n yStart += meters[1]*10;\n xDest += xDest*meters[1];\n yDest += yDest*meters[1];\n }\n else {\n yStart -= meters[1]*10;\n xDest -= xDest*meters[1];\n yDest -= yDest*meters[1];\n }\n \n ofSetColor(r, g, b); \/\/Replace this with pixel colors from feed\n ofLine(xStart, yStart, xDest, yDest);\n }\n}\n\/\/--------------------------------------------------------------\nvoid testApp::parseOSCMessages() {\n \/\/ check for waiting messages\n\twhile(receiver.hasWaitingMessages()){\n\t\t\/\/ get the next message\n\t\tofxOscMessage m;\n\t\treceiver.getNextMessage(&m);\n \n\t\t\/\/ check for meter messages\n if(m.getAddress() == \"\/main\/meter\") {\n \/\/Go through arguments, get them as floats\n for (int i = 0; i < m.getNumArgs(); i++) {\n meters[i] = m.getArgAsFloat(i);\n \/\/ ofLogNotice(\"meter0\"+ofToString(i)+\": \"+ofToString(meters[i]));\n }\n }\n\t}\n}\n\n\/\/--------------------------------------------------------------\nvoid testApp::keyPressed(int key){\n if (key == 'f' || 'F') {\n isFullScreen = !isFullScreen;\n ofSetFullscreen(isFullScreen);\n }\n\n}\n\n\/\/--------------------------------------------------------------\nvoid testApp::keyReleased(int key){\n\n}\n\n\/\/--------------------------------------------------------------\nvoid testApp::mouseMoved(int x, int y ){\n\n}\n\n\/\/--------------------------------------------------------------\nvoid testApp::mouseDragged(int x, int y, int button){\n\n}\n\n\/\/--------------------------------------------------------------\nvoid testApp::mousePressed(int x, int y, int button){\n\n}\n\n\/\/--------------------------------------------------------------\nvoid testApp::mouseReleased(int x, int y, int button){\n\n}\n\n\/\/--------------------------------------------------------------\nvoid testApp::windowResized(int w, int h){\n\n}\n\n\/\/--------------------------------------------------------------\nvoid testApp::gotMessage(ofMessage msg){\n\n}\n\n\/\/--------------------------------------------------------------\nvoid testApp::dragEvent(ofDragInfo dragInfo){ \n\n}\ntriggering#include \"testApp.h\"\n\n\/\/--------------------------------------------------------------\nvoid testApp::setup(){\n ofBackground(0,0,0);\n ofSetBackgroundAuto(false);\n isFullScreen = false;\n ofSetFrameRate(30);\n \n masterCounter = 0;\n direction = 1; \/\/count up\n \n \/\/ OSC STUFF\n receiver.setup(PORT);\n meters = new float[7];\n \n \/\/RECT STUFF\n rectX = 0;\n rectY = 0;\n rectSize = 30;\n rectSpacing = 0;\n numYRects = ofGetWidth()\/rectSize-rectSpacing;\n numXRects = ofGetHeight()\/rectSize-rectSpacing;\n numRects = numYRects*numXRects;\n rectCount = 0;\n ofLogNotice(\"\\n numYRects: \"+ofToString(numYRects)+\"\\n numXRects: \"+ofToString(numXRects)+\"\\n numRects: \"+ofToString(numRects));\n}\n\n\/\/--------------------------------------------------------------\nvoid testApp::update(){\n\n \n\tparseOSCMessages();\n \n \/\/ FUN STUFF\n masterCounter+=direction;\n if (masterCounter > 2000) {\n direction = -1;\n }\n if (masterCounter < -2000) {\n direction = 1;\n }\n\n\n}\n\n\/\/--------------------------------------------------------------\nvoid testApp::draw(){\n \n \/\/drawHorizon();\n \n \/\/ Structured rectangles\n if (meters[4] > 0) { \/\/if percussion occurs\n rectCount++;\n rectX += rectSpacing;\n ofSetColor(0, 255*meters[4], 0);\n ofRect(rectX, rectY, rectSize, rectSize);\n }\n}\n\n\/\/--------------------------------------------------------------\nvoid testApp::drawHorizon() {\n \/\/Abstract line stuff\n for (int i = 0; i < ofGetWidth(); i++) {\n \n \/\/ set the color for each line\n int r = meters[0]*255;\n int g = meters[1]*255;\n int b = meters[2]*255;\n \n \/\/ line start and destination\n int xStart = i;\n int yStart = ofGetHeight()\/2;\n int xDest = i*sin(i)*400; \/\/400 is arbitrary.\n int yDest = i*cos(i)*masterCounter*meters[1];\n \n \/\/shake the signal\n if (masterCounter%2 == 0) {\n yStart += meters[1]*10;\n xDest += xDest*meters[1];\n yDest += yDest*meters[1];\n }\n else {\n yStart -= meters[1]*10;\n xDest -= xDest*meters[1];\n yDest -= yDest*meters[1];\n }\n \n ofSetColor(r, g, b); \/\/Replace this with pixel colors from feed\n ofLine(xStart, yStart, xDest, yDest);\n }\n}\n\/\/--------------------------------------------------------------\nvoid testApp::parseOSCMessages() {\n \/\/ check for waiting messages\n\twhile(receiver.hasWaitingMessages()){\n\t\t\/\/ get the next message\n\t\tofxOscMessage m;\n\t\treceiver.getNextMessage(&m);\n \n\t\t\/\/ check for meter messages\n if(m.getAddress() == \"\/main\/meter\") {\n \/\/Go through arguments, get them as floats\n for (int i = 0; i < m.getNumArgs(); i++) {\n meters[i] = m.getArgAsFloat(i);\n \/\/ ofLogNotice(\"meter0\"+ofToString(i)+\": \"+ofToString(meters[i]));\n }\n }\n\t}\n}\n\n\/\/--------------------------------------------------------------\nvoid testApp::keyPressed(int key){\n if (key == 'f' || 'F') {\n isFullScreen = !isFullScreen;\n ofSetFullscreen(isFullScreen);\n }\n\n}\n\n\/\/--------------------------------------------------------------\nvoid testApp::keyReleased(int key){\n\n}\n\n\/\/--------------------------------------------------------------\nvoid testApp::mouseMoved(int x, int y ){\n\n}\n\n\/\/--------------------------------------------------------------\nvoid testApp::mouseDragged(int x, int y, int button){\n\n}\n\n\/\/--------------------------------------------------------------\nvoid testApp::mousePressed(int x, int y, int button){\n\n}\n\n\/\/--------------------------------------------------------------\nvoid testApp::mouseReleased(int x, int y, int button){\n\n}\n\n\/\/--------------------------------------------------------------\nvoid testApp::windowResized(int w, int h){\n\n}\n\n\/\/--------------------------------------------------------------\nvoid testApp::gotMessage(ofMessage msg){\n\n}\n\n\/\/--------------------------------------------------------------\nvoid testApp::dragEvent(ofDragInfo dragInfo){ \n\n}\n<|endoftext|>"} {"text":"\/*++\nCopyright (c) 2011 Microsoft Corporation\n\nModule Name:\n\n pdr_interpolant_provider.cpp\n\nAbstract:\n\n Interface for obtaining interpolants.\n\n This file is Windows specific.\n\nAuthor:\n\n Krystof Hoder (t-khoder) 2011-10-19.\n\nRevision History:\n\n--*\/\n\n\/\/disables the warning on deprecation of fgets function -- didn't really find by what it should be replaced\n#ifdef _WINDOWS\n#pragma warning(disable: 4995)\n#endif\n\n#include \n#include \"ast_smt_pp.h\"\n#include \"cmd_context.h\"\n#include \"for_each_expr.h\"\n#include \"obj_hashtable.h\"\n#include \"smt2parser.h\"\n#include \"rewriter.h\"\n#include \"rewriter_def.h\"\n#include \"pdr_util.h\"\n#include \"pdr_interpolant_provider.h\"\n#include \"expr_context_simplifier.h\"\n\n#ifdef _WINDOWS\n#include \n#include \n#include \n#include \n\n\/**\nRequirements for the use of this object:\n\nThe directory where the expcutable is must contain also executable \nPdrInterpolator.exe.\n\nThis executable takes one argument with a file name that contains\ntwo SMTLIB problem instances, each terminated by string \"\\n##next##\\n\".\n\nThe output of the executable is given to the standard output and\nis also terminated by the \"\\n##next##\\n\" string.\n\nIf formulas in the two input problems are unsatisfiable, they problem \nis printed at the output in the format\n(assert FORM)\n\nIf the formulas are satisfiable, \"0\" is output and if the result cannot\nbe determined, the output is \"?\". (Both are still followed by \"\\n##next##\\n\").\n\n*\/\nclass interpolant_provider_impl : public interpolant_provider\n{\n static std::string s_terminator_str;\n static std::string s_satisfiable_str;\n static std::string s_unknown_str;\n\n std::string m_exec_name;\n params_ref const & m_params;\n\n \/**\n If non-empty, contains name of a temporary file that is used for passing the\n interpolation problem to the interpolating engine.\n *\/\n std::string m_tmp_file_name;\n\n simplifier m_simpl;\n\n PROCESS_INFORMATION m_pi;\n STARTUPINFOA m_si;\n HANDLE m_in_rd;\n HANDLE m_out_rd;\n HANDLE m_in_wr;\n HANDLE m_out_wr;\n\n\n class used_symbol_inserter {\n typedef obj_hashtable func_decl_set;\n typedef obj_hashtable sort_set;\n\n ast_manager& m;\n cmd_context& m_cctx;\n\n func_decl_set m_funcs;\n sort_set m_sorts;\n\n void handle_sort(sort * s) {\n if(s->get_family_id()!=null_family_id || m_sorts.contains(s)) {\n return;\n }\n m_sorts.insert(s);\n NOT_IMPLEMENTED_YET();\n \/\/we should insert it into the context somehow, but now not sure how and \n \/\/we don't deal with user defined sorts (yet)...\n \/\/m_cctx.insert(s);\n }\n void handle_func_decl(func_decl * fn) {\n if(fn->get_family_id()!=null_family_id || m_funcs.contains(fn)) {\n return;\n }\n m_funcs.insert(fn);\n m_cctx.insert(fn);\n }\n\n public: \n\n used_symbol_inserter(cmd_context& cctx) : m(cctx.m()), m_cctx(cctx) {}\n\n void operator()(var * n) {\n handle_sort(n->get_sort());\n }\n void operator()(app * n) { \n if (is_uninterp(n)) {\n handle_func_decl(n->get_decl());\n }\n handle_sort(n->get_decl()->get_range());\n }\n void operator()(quantifier * n) {\n unsigned sz = n->get_num_decls();\n for(unsigned i=0; iget_decl_sort(i));\n }\n }\n };\n\n class form_fixer_cfg : public default_rewriter_cfg\n {\n ast_manager& m;\n public:\n form_fixer_cfg(ast_manager& m) : m(m) {}\n\n br_status reduce_app(func_decl * f, unsigned num, expr * const * args, expr_ref & result, \n proof_ref & result_pr)\n {\n if(m.is_or(f) && num==0) { \n result = m.mk_false();\n return BR_DONE;\n }\n return BR_FAILED;\n }\n };\n\n\n std::string get_tmp_file_name();\n\n std::string execute_interpolator(std::string input);\n\n void simplify_expr(expr* f, expr_ref& result);\n void output_interpolant_problem(std::ostream& out, expr * f1, expr * f2);\n\npublic:\n\n interpolant_provider_impl(ast_manager& m, params_ref const& params, std::string exec_name)\n : interpolant_provider(m),\n m_params(params),\n m_exec_name(exec_name),\n m_simpl(m) {\n memset(&m_si, 0, sizeof(m_si));\n memset(&m_pi, 0, sizeof(m_pi));\n }\n\n ~interpolant_provider_impl();\n\n\n \/**\n If (f1 \/\\ f2) is unsatisfiable, return true and into res assign a formula\n I such that f1 --> I, I --> ~f2, and the language if I is in the intersection \n of languages of f1 and f2.\n\n If (f1 \/\\ f2) is satisfiable, return false.\n *\/\n virtual lbool get_interpolant(expr * f1, expr * f2, expr_ref& res);\n};\n\nstd::string interpolant_provider_impl::s_terminator_str = \";##next##\";\nstd::string interpolant_provider_impl::s_satisfiable_str = \";#sat#\";\nstd::string interpolant_provider_impl::s_unknown_str = \";#unknown#\";\n\ninterpolant_provider_impl::~interpolant_provider_impl() {\n if(m_tmp_file_name.size()!=0) {\n DeleteFileA(m_tmp_file_name.c_str());\n }\n CloseHandle(m_pi.hProcess);\n CloseHandle(m_pi.hThread);\n CloseHandle(m_in_rd);\n CloseHandle(m_in_wr);\n CloseHandle(m_out_rd);\n CloseHandle(m_out_wr);\n}\n\nvoid interpolant_provider_impl::simplify_expr(expr* f, expr_ref& result) {\n expr_ref rwr_f(m);\n form_fixer_cfg fixer(m);\n rewriter_tpl rwr(m, false, fixer);\n rwr(f, rwr_f);\n proof_ref pr(m);\n m_simpl(rwr_f, result, pr);\n}\n\n\nstd::string interpolant_provider_impl::get_tmp_file_name() {\n \/\/return \"c:\\\\test.txt\";\n if(m_tmp_file_name.length()!=0) {\n return m_tmp_file_name;\n }\n char path[MAX_PATH];\n if(GetTempPathA(256, path)==0) {\n throw default_exception(\"cannot get temp directory\");\n }\n\n std::stringstream name_prefix_builder;\n\n name_prefix_builder<<\"pdr\"<(input.size()), &wr, 0)) {\n throw default_exception(\"Cold not write to pipe\");\n }\n\n std::string result;\n char line[256];\n while (true) {\n memset(line, 0, sizeof(line));\n if (!ReadFile(m_out_rd, line, sizeof(line)-1, &rd, 0)) {\n throw default_exception(\"Cold not write to pipe\");\n }\n result += line; \n if (strstr(result.c_str(), s_terminator_str.c_str())) { \n return result;\n }\n }\n}\n\nlbool interpolant_provider_impl::get_interpolant(expr * f1, expr * f2, expr_ref& res) {\n std::ostringstream prb;\n output_interpolant_problem(prb, f1, f2);\n std::string res_text = execute_interpolator(prb.str());\n if(strstr(res_text.c_str(), s_satisfiable_str.c_str())) {\n return l_false;\n }\n if(strstr(res_text.c_str(), s_unknown_str.c_str())) {\n return l_undef;\n }\n\n smt_params dummy_params;\n cmd_context cctx(&dummy_params, false, &m);\n for_each_expr(used_symbol_inserter(cctx), f1);\n\n parse_smt2_commands(cctx, std::istringstream(res_text), false);\n\n ptr_vector::const_iterator ait = cctx.begin_assertions();\n ptr_vector::const_iterator aend = cctx.end_assertions();\n if(ait+1!=aend) {\n throw default_exception(\"invalid interpolator output\");\n }\n res = *ait;\n if (m_params.get_bool(\"dump_interpolants\", false)) {\n interpolant_provider::output_interpolant(m, f1, f2, res);\n }\n return l_true;\n}\n\ninterpolant_provider * interpolant_provider::mk(ast_manager& m, params_ref const& p)\n{\n char self_name[MAX_PATH];\n GetModuleFileNameA(NULL, self_name, MAX_PATH);\n char * last_backslash = strrchr(self_name,'\\\\');\n if(last_backslash==NULL) {\n throw default_exception(\"GetModuleFileNameA did not return full path to the executable\");\n }\n \/\/we cut the string at the last backslash\n *last_backslash = 0;\n\n std::string exec_name = self_name + std::string(\".\\\\PdrInterpolator.exe\");\n\n return alloc(interpolant_provider_impl, m, p, exec_name);\n}\n\n#else\n\ninterpolant_provider * \ninterpolant_provider::mk(ast_manager& m, params_ref const& p) {\n \/\/ interpolations are windows specific and private.\n return 0;\n}\n\n\n#endif\n\n\nvoid interpolant_provider::output_interpolant(ast_manager& m, expr* A, expr* B, expr* I) {\n static unsigned file_num = 0;\n \n std::ostringstream filename;\n filename << \"interpolation_\" << file_num++ << \".smt\";\n std::ofstream out(filename.str().c_str());\n\n ast_smt_pp pp(m);\n pp.add_assumption(A);\n pp.display(out, B);\n std::ostringstream strm;\n strm << \";\" << mk_pp(I, m) << \"\\n\";\n\n buffer buff;\n std::string s = strm.str();\n char const* i_str = s.c_str();\n while (*i_str) {\n buff.push_back(*i_str);\n if (*i_str == '\\n') {\n buff.push_back(';');\n }\n ++i_str;\n }\n buff.push_back(0);\n out << buff.c_ptr();\n out << \"##next##\\n\";\n out.close();\n}\nfixed win compilation bug\/*++\nCopyright (c) 2011 Microsoft Corporation\n\nModule Name:\n\n pdr_interpolant_provider.cpp\n\nAbstract:\n\n Interface for obtaining interpolants.\n\n This file is Windows specific.\n\nAuthor:\n\n Krystof Hoder (t-khoder) 2011-10-19.\n\nRevision History:\n\n--*\/\n\n\/\/disables the warning on deprecation of fgets function -- didn't really find by what it should be replaced\n#ifdef _WINDOWS\n#pragma warning(disable: 4995)\n#endif\n\n#include \n#include \"ast_smt_pp.h\"\n#include \"cmd_context.h\"\n#include \"for_each_expr.h\"\n#include \"obj_hashtable.h\"\n#include \"smt2parser.h\"\n#include \"rewriter.h\"\n#include \"rewriter_def.h\"\n#include \"pdr_util.h\"\n#include \"pdr_interpolant_provider.h\"\n#include \"expr_context_simplifier.h\"\n\n#ifdef _WINDOWS\n#include \n#include \n#include \n#include \n\n\/**\nRequirements for the use of this object:\n\nThe directory where the expcutable is must contain also executable \nPdrInterpolator.exe.\n\nThis executable takes one argument with a file name that contains\ntwo SMTLIB problem instances, each terminated by string \"\\n##next##\\n\".\n\nThe output of the executable is given to the standard output and\nis also terminated by the \"\\n##next##\\n\" string.\n\nIf formulas in the two input problems are unsatisfiable, they problem \nis printed at the output in the format\n(assert FORM)\n\nIf the formulas are satisfiable, \"0\" is output and if the result cannot\nbe determined, the output is \"?\". (Both are still followed by \"\\n##next##\\n\").\n\n*\/\nclass interpolant_provider_impl : public interpolant_provider\n{\n static std::string s_terminator_str;\n static std::string s_satisfiable_str;\n static std::string s_unknown_str;\n\n std::string m_exec_name;\n params_ref const & m_params;\n\n \/**\n If non-empty, contains name of a temporary file that is used for passing the\n interpolation problem to the interpolating engine.\n *\/\n std::string m_tmp_file_name;\n\n simplifier m_simpl;\n\n PROCESS_INFORMATION m_pi;\n STARTUPINFOA m_si;\n HANDLE m_in_rd;\n HANDLE m_out_rd;\n HANDLE m_in_wr;\n HANDLE m_out_wr;\n\n\n class used_symbol_inserter {\n typedef obj_hashtable func_decl_set;\n typedef obj_hashtable sort_set;\n\n ast_manager& m;\n cmd_context& m_cctx;\n\n func_decl_set m_funcs;\n sort_set m_sorts;\n\n void handle_sort(sort * s) {\n if(s->get_family_id()!=null_family_id || m_sorts.contains(s)) {\n return;\n }\n m_sorts.insert(s);\n NOT_IMPLEMENTED_YET();\n \/\/we should insert it into the context somehow, but now not sure how and \n \/\/we don't deal with user defined sorts (yet)...\n \/\/m_cctx.insert(s);\n }\n void handle_func_decl(func_decl * fn) {\n if(fn->get_family_id()!=null_family_id || m_funcs.contains(fn)) {\n return;\n }\n m_funcs.insert(fn);\n m_cctx.insert(fn);\n }\n\n public: \n\n used_symbol_inserter(cmd_context& cctx) : m(cctx.m()), m_cctx(cctx) {}\n\n void operator()(var * n) {\n handle_sort(n->get_sort());\n }\n void operator()(app * n) { \n if (is_uninterp(n)) {\n handle_func_decl(n->get_decl());\n }\n handle_sort(n->get_decl()->get_range());\n }\n void operator()(quantifier * n) {\n unsigned sz = n->get_num_decls();\n for(unsigned i=0; iget_decl_sort(i));\n }\n }\n };\n\n class form_fixer_cfg : public default_rewriter_cfg\n {\n ast_manager& m;\n public:\n form_fixer_cfg(ast_manager& m) : m(m) {}\n\n br_status reduce_app(func_decl * f, unsigned num, expr * const * args, expr_ref & result, \n proof_ref & result_pr)\n {\n if(m.is_or(f) && num==0) { \n result = m.mk_false();\n return BR_DONE;\n }\n return BR_FAILED;\n }\n };\n\n\n std::string get_tmp_file_name();\n\n std::string execute_interpolator(std::string input);\n\n void simplify_expr(expr* f, expr_ref& result);\n void output_interpolant_problem(std::ostream& out, expr * f1, expr * f2);\n\npublic:\n\n interpolant_provider_impl(ast_manager& m, params_ref const& params, std::string exec_name)\n : interpolant_provider(m),\n m_params(params),\n m_exec_name(exec_name),\n m_simpl(m) {\n memset(&m_si, 0, sizeof(m_si));\n memset(&m_pi, 0, sizeof(m_pi));\n }\n\n ~interpolant_provider_impl();\n\n\n \/**\n If (f1 \/\\ f2) is unsatisfiable, return true and into res assign a formula\n I such that f1 --> I, I --> ~f2, and the language if I is in the intersection \n of languages of f1 and f2.\n\n If (f1 \/\\ f2) is satisfiable, return false.\n *\/\n virtual lbool get_interpolant(expr * f1, expr * f2, expr_ref& res);\n};\n\nstd::string interpolant_provider_impl::s_terminator_str = \";##next##\";\nstd::string interpolant_provider_impl::s_satisfiable_str = \";#sat#\";\nstd::string interpolant_provider_impl::s_unknown_str = \";#unknown#\";\n\ninterpolant_provider_impl::~interpolant_provider_impl() {\n if(m_tmp_file_name.size()!=0) {\n DeleteFileA(m_tmp_file_name.c_str());\n }\n CloseHandle(m_pi.hProcess);\n CloseHandle(m_pi.hThread);\n CloseHandle(m_in_rd);\n CloseHandle(m_in_wr);\n CloseHandle(m_out_rd);\n CloseHandle(m_out_wr);\n}\n\nvoid interpolant_provider_impl::simplify_expr(expr* f, expr_ref& result) {\n expr_ref rwr_f(m);\n form_fixer_cfg fixer(m);\n rewriter_tpl rwr(m, false, fixer);\n rwr(f, rwr_f);\n proof_ref pr(m);\n m_simpl(rwr_f, result, pr);\n}\n\n\nstd::string interpolant_provider_impl::get_tmp_file_name() {\n \/\/return \"c:\\\\test.txt\";\n if(m_tmp_file_name.length()!=0) {\n return m_tmp_file_name;\n }\n char path[MAX_PATH];\n if(GetTempPathA(256, path)==0) {\n throw default_exception(\"cannot get temp directory\");\n }\n\n std::stringstream name_prefix_builder;\n\n name_prefix_builder<<\"pdr\"<(input.size()), &wr, 0)) {\n throw default_exception(\"Cold not write to pipe\");\n }\n\n std::string result;\n char line[256];\n while (true) {\n memset(line, 0, sizeof(line));\n if (!ReadFile(m_out_rd, line, sizeof(line)-1, &rd, 0)) {\n throw default_exception(\"Cold not write to pipe\");\n }\n result += line; \n if (strstr(result.c_str(), s_terminator_str.c_str())) { \n return result;\n }\n }\n}\n\nlbool interpolant_provider_impl::get_interpolant(expr * f1, expr * f2, expr_ref& res) {\n std::ostringstream prb;\n output_interpolant_problem(prb, f1, f2);\n std::string res_text = execute_interpolator(prb.str());\n if(strstr(res_text.c_str(), s_satisfiable_str.c_str())) {\n return l_false;\n }\n if(strstr(res_text.c_str(), s_unknown_str.c_str())) {\n return l_undef;\n }\n\n cmd_context cctx(false, &m);\n for_each_expr(used_symbol_inserter(cctx), f1);\n\n parse_smt2_commands(cctx, std::istringstream(res_text), false);\n\n ptr_vector::const_iterator ait = cctx.begin_assertions();\n ptr_vector::const_iterator aend = cctx.end_assertions();\n if(ait+1!=aend) {\n throw default_exception(\"invalid interpolator output\");\n }\n res = *ait;\n if (m_params.get_bool(\"dump_interpolants\", false)) {\n interpolant_provider::output_interpolant(m, f1, f2, res);\n }\n return l_true;\n}\n\ninterpolant_provider * interpolant_provider::mk(ast_manager& m, params_ref const& p)\n{\n char self_name[MAX_PATH];\n GetModuleFileNameA(NULL, self_name, MAX_PATH);\n char * last_backslash = strrchr(self_name,'\\\\');\n if(last_backslash==NULL) {\n throw default_exception(\"GetModuleFileNameA did not return full path to the executable\");\n }\n \/\/we cut the string at the last backslash\n *last_backslash = 0;\n\n std::string exec_name = self_name + std::string(\".\\\\PdrInterpolator.exe\");\n\n return alloc(interpolant_provider_impl, m, p, exec_name);\n}\n\n#else\n\ninterpolant_provider * \ninterpolant_provider::mk(ast_manager& m, params_ref const& p) {\n \/\/ interpolations are windows specific and private.\n return 0;\n}\n\n\n#endif\n\n\nvoid interpolant_provider::output_interpolant(ast_manager& m, expr* A, expr* B, expr* I) {\n static unsigned file_num = 0;\n \n std::ostringstream filename;\n filename << \"interpolation_\" << file_num++ << \".smt\";\n std::ofstream out(filename.str().c_str());\n\n ast_smt_pp pp(m);\n pp.add_assumption(A);\n pp.display(out, B);\n std::ostringstream strm;\n strm << \";\" << mk_pp(I, m) << \"\\n\";\n\n buffer buff;\n std::string s = strm.str();\n char const* i_str = s.c_str();\n while (*i_str) {\n buff.push_back(*i_str);\n if (*i_str == '\\n') {\n buff.push_back(';');\n }\n ++i_str;\n }\n buff.push_back(0);\n out << buff.c_ptr();\n out << \"##next##\\n\";\n out.close();\n}\n<|endoftext|>"} {"text":"#include \"testApp.h\"\n\nvoid testApp::setup()\n{\n ofSetFrameRate(60);\n ofSetVerticalSync(true);\n ofSetLogLevel(OF_LOG_VERBOSE);\t\n\n controller.addListener(listener);\n}\nvoid testApp::update()\n{\n}\nvoid testApp::draw()\n{\n ofBackgroundGradient(ofColor(90, 90, 90), ofColor(30, 30, 30), OF_GRADIENT_BAR);\n\n camera.begin();\n \n camera.end();\n}\nvoid testApp::keyPressed(int key){}\nvoid testApp::keyReleased(int key){}\nvoid testApp::mouseMoved(int x, int y ){}\nvoid testApp::mouseDragged(int x, int y, int button){}\nvoid testApp::mousePressed(int x, int y, int button){}\nvoid testApp::mouseReleased(int x, int y, int button){}\nvoid testApp::windowResized(int w, int h){}\nvoid testApp::gotMessage(ofMessage msg){}\nvoid testApp::dragEvent(ofDragInfo dragInfo){}\n\n\/\/--------------------------------------------------------------\nvoid SampleListener::onInit(const Controller& controller) \n{\n std::cout << \"Initialized\" << std::endl;\n}\nvoid SampleListener::onConnect(const Controller& controller) \n{\n std::cout << \"Connected\" << std::endl;\n controller.enableGesture(Gesture::TYPE_CIRCLE);\n controller.enableGesture(Gesture::TYPE_KEY_TAP);\n controller.enableGesture(Gesture::TYPE_SCREEN_TAP);\n controller.enableGesture(Gesture::TYPE_SWIPE);\n}\n\nvoid SampleListener::onDisconnect(const Controller& controller) \n{\n \/\/Note: not dispatched when running in a debugger.\n std::cout << \"Disconnected\" << std::endl;\n}\n\nvoid SampleListener::onExit(const Controller& controller) \n{\n std::cout << \"Exited\" << std::endl;\n}\n\nvoid SampleListener::onFrame(const Controller& controller) \n{\n \/\/ Get the most recent frame and report some basic information\n const Frame frame = controller.frame();\n std::cout << \"Frame id: \" << frame.id()\n << \", timestamp: \" << frame.timestamp()\n << \", hands: \" << frame.hands().count()\n << \", fingers: \" << frame.fingers().count()\n << \", tools: \" << frame.tools().count()\n << \", gestures: \" << frame.gestures().count() << std::endl;\n\n if (!frame.hands().empty()) \n {\n \/\/ Get the first hand\n const Hand hand = frame.hands()[0];\n\n \/\/ Check if the hand has any fingers\n const FingerList fingers = hand.fingers();\n if (!fingers.empty()) \n {\n \/\/ Calculate the hand's average finger tip position\n Vector avgPos;\n for (int i = 0; i < fingers.count(); ++i) \n {\n avgPos += fingers[i].tipPosition();\n }\n avgPos \/= (float)fingers.count();\n std::cout << \"Hand has \" << fingers.count()\n << \" fingers, average finger tip position\" << avgPos << std::endl;\n }\n\n \/\/ Get the hand's sphere radius and palm position\n std::cout \t<< \"Hand sphere radius: \" << hand.sphereRadius()\n << \" mm, palm position: \" << hand.palmPosition() << std::endl;\n\n \/\/ Get the hand's normal vector and direction\n const Vector normal = hand.palmNormal();\n const Vector direction = hand.direction();\n\n \/\/ Calculate the hand's pitch, roll, and yaw angles\n std::cout << \"Hand pitch: \" << direction.pitch() * RAD_TO_DEG \t<< \" degrees, \"\n << \"roll: \" << normal.roll() * RAD_TO_DEG << \" degrees, \"\n << \"yaw: \" << direction.yaw() * RAD_TO_DEG << \" degrees\" << std::endl;\n }\n\n \/\/ Get gestures\n const GestureList gestures = frame.gestures();\n for (int g = 0; g < gestures.count(); ++g) \n {\n Gesture gesture = gestures[g];\n switch (gesture.type()) \n {\n case Gesture::TYPE_CIRCLE:\n {\n CircleGesture circle = gesture;\n std::string clockwiseness;\n\n if (circle.pointable().direction().angleTo(circle.normal()) <= PI\/4) \n {\n clockwiseness = \"clockwise\";\n } \n else \n {\n clockwiseness = \"counterclockwise\";\n }\n\n \/\/ Calculate angle swept since last frame\n float sweptAngle = 0;\n if (circle.state() != Gesture::STATE_START) \n {\n CircleGesture previousUpdate = CircleGesture(controller.frame(1).gesture(circle.id()));\n sweptAngle = (circle.progress() - previousUpdate.progress()) * 2 * PI;\n }\n std::cout \t<< \"Circle id: \" << gesture.id()\n << \", state: \" << gesture.state()\n << \", progress: \" << circle.progress()\n << \", radius: \" << circle.radius()\n << \", angle \" << sweptAngle * RAD_TO_DEG\n << \", \" << clockwiseness << std::endl;\n break;\n }\n case Gesture::TYPE_SWIPE:\n {\n SwipeGesture swipe = gesture;\n std::cout \t<< \"Swipe id: \"<< gesture.id()\n << \", state: \" << gesture.state()\n << \", direction: \"<< swipe.direction()\n << \", speed: \" << swipe.speed() << std::endl;\n break;\n }\n case Gesture::TYPE_KEY_TAP:\n {\n KeyTapGesture tap = gesture;\n std::cout << \"Key Tap id: \"<< gesture.id()\n << \", state: \" << gesture.state()\n << \", position: \" << tap.position()\n << \", direction: \" << tap.direction()<< std::endl;\n break;\n }\n case Gesture::TYPE_SCREEN_TAP:\n {\n ScreenTapGesture screentap = gesture;\n std::cout << \"Screen Tap id: \" << gesture.id()\n << \", state: \" << gesture.state()\n << \", position: \" << screentap.position()\n << \", direction: \" << screentap.direction()<< std::endl;\n break;\n }\n default:\n std::cout << \"Unknown gesture type.\" << std::endl;\n break;\n }\n }\n\n if (!frame.hands().empty() || !gestures.empty()) \n {\n std::cout << std::endl;\n }\n}\n\nvoid SampleListener::onFocusGained(const Controller& controller) \n{\n std::cout << \"Focus Gained\" << std::endl;\n}\n\nvoid SampleListener::onFocusLost(const Controller& controller) \n{\n std::cout << \"Focus Lost\" << std::endl;\n}Fixed indetnation#include \"testApp.h\"\n\nvoid testApp::setup()\n{\n ofSetFrameRate(60);\n ofSetVerticalSync(true);\n ofSetLogLevel(OF_LOG_VERBOSE);\t\n\n controller.addListener(listener);\n}\nvoid testApp::update()\n{\n}\nvoid testApp::draw()\n{\n ofBackgroundGradient(ofColor(90, 90, 90), ofColor(30, 30, 30), OF_GRADIENT_BAR);\n\n camera.begin();\n camera.end();\n}\nvoid testApp::keyPressed(int key){}\nvoid testApp::keyReleased(int key){}\nvoid testApp::mouseMoved(int x, int y ){}\nvoid testApp::mouseDragged(int x, int y, int button){}\nvoid testApp::mousePressed(int x, int y, int button){}\nvoid testApp::mouseReleased(int x, int y, int button){}\nvoid testApp::windowResized(int w, int h){}\nvoid testApp::gotMessage(ofMessage msg){}\nvoid testApp::dragEvent(ofDragInfo dragInfo){}\n\n\/\/--------------------------------------------------------------\nvoid SampleListener::onInit(const Controller& controller) \n{\n std::cout << \"Initialized\" << std::endl;\n}\nvoid SampleListener::onConnect(const Controller& controller) \n{\n std::cout << \"Connected\" << std::endl;\n controller.enableGesture(Gesture::TYPE_CIRCLE);\n controller.enableGesture(Gesture::TYPE_KEY_TAP);\n controller.enableGesture(Gesture::TYPE_SCREEN_TAP);\n controller.enableGesture(Gesture::TYPE_SWIPE);\n}\n\nvoid SampleListener::onDisconnect(const Controller& controller) \n{\n \/\/Note: not dispatched when running in a debugger.\n std::cout << \"Disconnected\" << std::endl;\n}\n\nvoid SampleListener::onExit(const Controller& controller) \n{\n std::cout << \"Exited\" << std::endl;\n}\n\nvoid SampleListener::onFrame(const Controller& controller) \n{\n \/\/ Get the most recent frame and report some basic information\n const Frame frame = controller.frame();\n std::cout << \"Frame id: \" << frame.id()\n << \", timestamp: \" << frame.timestamp()\n << \", hands: \" << frame.hands().count()\n << \", fingers: \" << frame.fingers().count()\n << \", tools: \" << frame.tools().count()\n << \", gestures: \" << frame.gestures().count() << std::endl;\n\n if (!frame.hands().empty()) \n {\n \/\/ Get the first hand\n const Hand hand = frame.hands()[0];\n\n \/\/ Check if the hand has any fingers\n const FingerList fingers = hand.fingers();\n if (!fingers.empty()) \n {\n \/\/ Calculate the hand's average finger tip position\n Vector avgPos;\n for (int i = 0; i < fingers.count(); ++i) \n {\n avgPos += fingers[i].tipPosition();\n }\n avgPos \/= (float)fingers.count();\n std::cout << \"Hand has \" << fingers.count()\n << \" fingers, average finger tip position\" << avgPos << std::endl;\n }\n\n \/\/ Get the hand's sphere radius and palm position\n std::cout \t<< \"Hand sphere radius: \" << hand.sphereRadius()\n << \" mm, palm position: \" << hand.palmPosition() << std::endl;\n\n \/\/ Get the hand's normal vector and direction\n const Vector normal = hand.palmNormal();\n const Vector direction = hand.direction();\n\n \/\/ Calculate the hand's pitch, roll, and yaw angles\n std::cout << \"Hand pitch: \" << direction.pitch() * RAD_TO_DEG \t<< \" degrees, \"\n << \"roll: \" << normal.roll() * RAD_TO_DEG << \" degrees, \"\n << \"yaw: \" << direction.yaw() * RAD_TO_DEG << \" degrees\" << std::endl;\n }\n\n \/\/ Get gestures\n const GestureList gestures = frame.gestures();\n for (int g = 0; g < gestures.count(); ++g) \n {\n Gesture gesture = gestures[g];\n switch (gesture.type()) \n {\n case Gesture::TYPE_CIRCLE:\n {\n CircleGesture circle = gesture;\n std::string clockwiseness;\n\n if (circle.pointable().direction().angleTo(circle.normal()) <= PI\/4) \n {\n clockwiseness = \"clockwise\";\n } \n else \n {\n clockwiseness = \"counterclockwise\";\n }\n\n \/\/ Calculate angle swept since last frame\n float sweptAngle = 0;\n if (circle.state() != Gesture::STATE_START) \n {\n CircleGesture previousUpdate = CircleGesture(controller.frame(1).gesture(circle.id()));\n sweptAngle = (circle.progress() - previousUpdate.progress()) * 2 * PI;\n }\n std::cout \t<< \"Circle id: \" << gesture.id()\n << \", state: \" << gesture.state()\n << \", progress: \" << circle.progress()\n << \", radius: \" << circle.radius()\n << \", angle \" << sweptAngle * RAD_TO_DEG\n << \", \" << clockwiseness << std::endl;\n break;\n }\n case Gesture::TYPE_SWIPE:\n {\n SwipeGesture swipe = gesture;\n std::cout \t<< \"Swipe id: \"<< gesture.id()\n << \", state: \" << gesture.state()\n << \", direction: \"<< swipe.direction()\n << \", speed: \" << swipe.speed() << std::endl;\n break;\n }\n case Gesture::TYPE_KEY_TAP:\n {\n KeyTapGesture tap = gesture;\n std::cout << \"Key Tap id: \"<< gesture.id()\n << \", state: \" << gesture.state()\n << \", position: \" << tap.position()\n << \", direction: \" << tap.direction()<< std::endl;\n break;\n }\n case Gesture::TYPE_SCREEN_TAP:\n {\n ScreenTapGesture screentap = gesture;\n std::cout << \"Screen Tap id: \" << gesture.id()\n << \", state: \" << gesture.state()\n << \", position: \" << screentap.position()\n << \", direction: \" << screentap.direction()<< std::endl;\n break;\n }\n default:\n std::cout << \"Unknown gesture type.\" << std::endl;\n break;\n }\n }\n\n if (!frame.hands().empty() || !gestures.empty()) \n {\n std::cout << std::endl;\n }\n}\n\nvoid SampleListener::onFocusGained(const Controller& controller) \n{\n std::cout << \"Focus Gained\" << std::endl;\n}\n\nvoid SampleListener::onFocusLost(const Controller& controller) \n{\n std::cout << \"Focus Lost\" << std::endl;\n}<|endoftext|>"} {"text":"\/*\n Min Kao Drone Tour\n Modified by Elliot Greenlee\n *\/\n\n#include \"objectFollowing.h\"\n#include \"..\/control.h\"\n#include \nusing namespace std;\n\nconst string THRESHOLDS_FILE_NAME = \"thresholds.xml\";\nconst double dt = 1.0; \/\/Sampling time [s]\n\n\/*\n *\/\nObjectFollowing::ObjectFollowing(Control *control) {\n control_ptr = control;\n kalman = cv::KalmanFilter(4, 2, 0);\n\n \/\/ XML save data for object following color thresholds\n cv::FileStorage fs(THRESHOLDS_FILE_NAME, cv::FileStorage::READ);\n\n \/\/ If there is a save file then read it\n if (fs.isOpened()) {\n maxH = fs[\"H_MAX\"];\n minH = fs[\"H_MIN\"];\n maxS = fs[\"S_MAX\"];\n minS = fs[\"S_MIN\"];\n maxV = fs[\"V_MAX\"];\n minV = fs[\"V_MIN\"];\n fs.release();\n }\n\n \/\/ Create a window\n cv::namedWindow(\"binalized\");\n cv::createTrackbar(\"Hue max\", \"binalized\", &maxH, 255);\n cv::createTrackbar(\"Hue min\", \"binalized\", &minH, 255);\n cv::createTrackbar(\"Saturation max\", \"binalized\", &maxS, 255);\n cv::createTrackbar(\"Saturation min\", \"binalized\", &minS, 255);\n cv::createTrackbar(\"Value max\", \"binalized\", &maxV, 255);\n cv::createTrackbar(\"Value min\", \"binalized\", &minV, 255);\n cv::resizeWindow(\"binalized\", 0, 0);\n\n \/\/ Transition matrix (x, y, vx, vy)\n cv::Mat1f A(4, 4);\n A << 1.0, 0.0, dt, 0.0,\n 0.0, 1.0, 0.0, dt,\n 0.0, 0.0, 1.0, 0.0,\n 0.0, 0.0, 0.0, 1.0;\n kalman.transitionMatrix = A;\n\n \/\/ Measurement matrix (x, y)\n cv::Mat1f H(2, 4);\n H << 1, 0, 0, 0,\n 0, 1, 0, 0;\n kalman.measurementMatrix = H;\n\n \/\/ Process noise covairance (x, y, vx, vy)\n cv::Mat1f Q(4, 4);\n Q << 1e-5, 0.0, 0.0, 0.0,\n 0.0, 1e-5, 0.0, 0.0,\n 0.0, 0.0, 1e-5, 0.0,\n 0.0, 0.0, 0.0, 1e-5;\n kalman.processNoiseCov = Q;\n\n \/\/ Measurement noise covariance (x, y)\n cv::Mat1f R(2, 2);\n R << 1e-1, 0.0,\n 0.0, 1e-1;\n kalman.measurementNoiseCov = R;\n}\n\n\/*\n *\/\nvoid ObjectFollowing::close() {\n \/\/Save thresholds\n cv::FileStorage fs(THRESHOLDS_FILE_NAME, cv::FileStorage::READ);\n fs.open(THRESHOLDS_FILE_NAME, cv::FileStorage::WRITE);\n if (fs.isOpened()) {\n cv::write(fs, \"H_MAX\", maxH);\n cv::write(fs, \"H_MIN\", minH);\n cv::write(fs, \"S_MAX\", maxS);\n cv::write(fs, \"S_MIN\", minS);\n cv::write(fs, \"V_MAX\", maxV);\n cv::write(fs, \"V_MIN\", minV);\n fs.release();\n }\n}\n\n\/*\n returns heading for control\n *\/\nvoid ObjectFollowing::fly() {\n\n ControlMovements *controlMovements = &(control_ptr->velocities);\n cv::Mat *image = &(control_ptr->image);\n\n int tolerance = 50;\n cv::Vec3b hsvSample;\n cv::Scalar green = CV_RGB(0,255,0); \/\/putText color value\n\n \/\/switch between learning and non-learning mode\n if (control_ptr->key == 'l') {\n learnMode = !learnMode;\n if (learnMode) {\n printf(\"Learning mode is enabled\\n\");\n printf(\"The color at the crosshairs is being learned\\n\");\n printf(\"Press l again to turn off learning mode\\n\\n\");\n }\n else {\n printf(\"Learning mode is disabled\\n\");\n printf(\"The color last at the crosshairs will be targeted\\n\");\n printf(\"Press l again to learn a different color\\n\\n\");\n }\n }\n\n \/\/ HSV image\n cv::Mat hsv;\n cv::cvtColor(*image, hsv, cv::COLOR_BGR2HSV_FULL);\n\n \/\/ Binalize\n cv::Mat binalized;\n cv::Scalar lower(minH, minS, minV);\n cv::Scalar upper(maxH, maxS, maxV);\n cv::inRange(hsv, lower, upper, binalized);\n\n \/\/ Show result\n cv::imshow(\"binalized\", binalized);\n\n \/\/ De-noising\n cv::Mat kernel = getStructuringElement(cv::MORPH_RECT, cv::Size(3, 3));\n cv::morphologyEx(binalized, binalized, cv::MORPH_CLOSE, kernel);\n\n \/\/ Detect contours\n vector > contours;\n cv::findContours(binalized.clone(), contours, cv::RETR_CCOMP, cv::CHAIN_APPROX_SIMPLE);\n\n \/\/ Find largest contour\n int contour_index = -1;\n double max_area = 0.0;\n for (size_t i = 0; i < contours.size(); i++) {\n double area = fabs(cv::contourArea(contours[i]));\n if (area > max_area) {\n contour_index = i;\n max_area = area;\n }\n }\n\n\n \/\/ Object detected\n if (contour_index >= 0) {\n\n \/\/ Moments\n cv::Moments moments = cv::moments(contours[contour_index], true);\n double marker_y = (int)(moments.m01 \/ moments.m00);\n double marker_x = (int)(moments.m10 \/ moments.m00);\n\n \/\/ Measurements\n cv::Mat measurement = (cv::Mat1f(2, 1) << marker_x, marker_y);\n\n \/\/ Correction\n cv::Mat estimated = kalman.correct(measurement);\n\n \/\/ Show result\n rect = cv::boundingRect(contours[contour_index]);\n cv::rectangle(*image, rect, cv::Scalar(0, 255, 0));\n\n \/\/ Calculate average hsv for the object within the coutour\n int avgHue = 0;\n int avgSaturation = 0;\n int avgValue = 0;\n int numPoints = 0;\n\n \/\/for x in rectangle\n for (x = rect.point.x; x < rect.point.x + rect.width; x++) {\n \/\/for y in rectangle \n for (y = rect.point.y; y < rect.point.y + rect.wdith; y++) {\n \/\/ TODO: If this is to slow, use rectangle average or do every second, third, etc point in rectangle for loop\n if (inCoutour(x, y, countours[contour_index])) {\n numPoints++;\n hsvPoint = hsv.at(cvPoint(x, y));\n avgHue += hsvPoint[0];\n avgSaturation += hsvPoint[1];\n avgValue += hsvPoint[2];\n }\n }\n }\n\n avgHue = ((double)avgHue)\/numPoints;\n avgSaturation = ((double)avgSaturation)\/numPoints;\n avgValue = ((double)avgValue)\/numPoints;\n\n hsvSample[0] = avgHue;\n hsvSample[1] = avgSaturation;\n hsvSample[2] = avgValue;\n\n minH = avgHue - tolerance;\n maxH = avgHue + tolerance;\n minS = avgSaturation - tolerance;\n maxS = avgSaturation + tolerance;\n minV = avgValue - tolerance;\n maxV = avgValue + tolerance;\n }\n\n \/\/ Prediction\n cv::Mat1f prediction = kalman.predict();\n int radius = 1e+3 * kalman.errorCovPre.at(0, 0);\n\n \/\/ Show predicted position\n cv::circle(*image, cv::Point(prediction(0, 0), prediction(0, 1)), radius, green, 2);\n\n \/\/ Calculate object heading fraction\n float rHeading = -(((*image).cols\/2) - prediction(0, 0))\/((*image).cols\/2);\n float zHeading = -(((*image).rows\/2) - prediction(0, 1))\/((*image).rows\/2);\n\n if (abs(rHeading) <= 0.8 && abs(zHeading) <= 0.8) {\n time_t lastSearchTime = time(0);\n }\n\n time_t currentTime = time(0);\n double elapsedTime = difftime(currentTime, lastSearchTime);\n if (elapsedTime >= 3) {\n ardrone.landing();\n fprintf(flight_log, \"LAND\\n\");\n }\n\n \/\/ Sample the object color\n if(learnMode) {\n \/\/ Show targeting crosshairs\n cv::line(*image, cvPoint((*image).cols\/2, 0), cvPoint((*image).cols\/2, (*image).rows\/2 - 2), green); \/\/top vertical crosshair\n cv::line(*image, cvPoint((*image).cols\/2, (*image).rows\/2 + 2), cvPoint((*image).cols\/2, (*image).rows), green); \/\/bottom vertical crosshair\n cv::line(*image, cvPoint(0, (*image).rows\/2), cvPoint((*image).cols\/2 - 2, (*image).rows\/2), green); \/\/left horizontal crosshair\n cv::line(*image, cvPoint((*image).cols\/2 + 2, (*image).rows\/2), cvPoint((*image).cols, (*image).rows\/2), green); \/\/right horizontal crosshair\n\n hsvSample = hsv.at(cvPoint((*image).cols\/2, (*image).rows\/2));\n\n }\n setHSVTrackBarPositions(hsvSample[0], hsvSample[1], hsvSample[2], tolerance);\n\n displayObjectFollowingInfo(image, rHeading, zHeading, hsvSample[0], hsvSample[1], hsvSample[2]);\n\n rect_area = rect.width * rect.height;\n\n \/*\n \/\/Execute drone movement\n if (rect_area > 25000) {\n controlMovements->vx = -1.0;\n moveStatus = false;\n }\n else if (rect_area <= 25000 && rect_area >= 20000) {\n controlMovements->vx = 0;\n moveStatus = false;\n }\n else {\n controlMovements->vx = 1.0;\n moveStatus = true;\n }\n *\/\n\n controlMovements->vx = (goalArea - rect_area)\/((double)goalArea);\n\n if(controlMovements->vx > 1) {\n controlMovements->vx = 1;\n } \n else if (controlMovements->vx < -1){\n controlMovements->vx = -1;\n }\n\n \/*if( control_ptr->altitude < 1.2 )\n {\n controlMovements->vz = 1.0;\n } \n else {\n controlMovements->vz = 0.0;\n }\n *\/\n\n time_t current_time = time(0);\n double elapsed_time = difftime(current_time, control_ptr->takeoff_time);\n if (elapsed_time < 5){\n controlMovements->vx = 0;\n controlMovements->vy = 0;\n controlMovements->vz = 0;\n controlMovements->vr = 0;\n } else {\n controlMovements->vz = -(zHeading * 0.2);\n controlMovements->vr = -(rHeading * 0.5);\n } \n\n return;\n}\n\n\/\/Auto set Hue, Saturation, and Value tracking bars\nvoid setHSVTrackBarPositions(int hue, int saturation, int value, int tolerance) {\n cv::setTrackbarPos(\"Hue max\", \"binalized\", hue + tolerance);\n cv::setTrackbarPos(\"Hue min\", \"binalized\", hue - tolerance);\n\n cv::setTrackbarPos(\"Saturation max\", \"binalized\", saturation + tolerance);\n cv::setTrackbarPos(\"Saturation min\", \"binalized\", saturation - tolerance);\n\n cv::setTrackbarPos(\"Value max\", \"binalized\", value + tolerance);\n cv::setTrackbarPos(\"Value min\", \"binalized\", value - tolerance);\n\n}\n\n\/*\n *\/\nvoid ObjectFollowing::displayObjectFollowingInfo(cv::Mat *image, double rHeading, double zHeading, int hue, int saturation, int value) {\n char rHeadingDisplay[80]; \/\/print buffer for rHeading\n char zHeadingDisplay[80]; \/\/print buffer for zHeading\n char hsvSampleDisplay[80]; \/\/print buffer for learning HSV values\n char moveStatusDisplay[80]; \/\/print buffer for stop\/go status\n\n cv::Scalar green = CV_RGB(0,255,0); \/\/putText color value\n\n sprintf(rHeadingDisplay, \"rHeading = %+3.2f\", rHeading); \n sprintf(zHeadingDisplay, \"zHeading = %+3.2f\", zHeading); \n sprintf(hsvSampleDisplay, \"hsvSample = %3d, %3d, %3d\", hue, saturation, value);\n if (moveStatus) {\n sprintf(moveStatusDisplay, \"move status = GO\");\n }\n else {\n sprintf(moveStatusDisplay, \"move status = STOP\");\n }\n\n putText(*image, rHeadingDisplay, cvPoint(30, 120), cv::FONT_HERSHEY_COMPLEX_SMALL, 0.8, green, 1, CV_AA);\n putText(*image, zHeadingDisplay, cvPoint(30, 140), cv::FONT_HERSHEY_COMPLEX_SMALL, 0.8, green, 1, CV_AA);\n putText(*image, hsvSampleDisplay, cvPoint(30, 160), cv::FONT_HERSHEY_COMPLEX_SMALL, 0.8, green, 1, CV_AA);\n putText(*image, moveStatusDisplay, cvPoint(30, 180), cv::FONT_HERSHEY_COMPLEX_SMALL, 0.8, green, 1, CV_AA);\n\n}\n\n\/*\n*\/\nboolean inContour(int x, int y, Contour c){\n Point p = new Point(x,y);\n MatOfPoint2f m = new MatOfPoint2f(c.pointMat.toArray());\n \n double r = Imgproc.pointPolygonTest(m,p, false);\n \n return r == 1;\n}\nFixed objectFollowing to compile.\/*\n Min Kao Drone Tour\n Modified by Elliot Greenlee\n *\/\n\n#include \"objectFollowing.h\"\n#include \"..\/control.h\"\n#include \nusing namespace std;\n\nconst string THRESHOLDS_FILE_NAME = \"thresholds.xml\";\nconst double dt = 1.0; \/\/Sampling time [s]\n\n\/*\n *\/\nObjectFollowing::ObjectFollowing(Control *control) {\n control_ptr = control;\n kalman = cv::KalmanFilter(4, 2, 0);\n\n \/\/ XML save data for object following color thresholds\n cv::FileStorage fs(THRESHOLDS_FILE_NAME, cv::FileStorage::READ);\n\n \/\/ If there is a save file then read it\n if (fs.isOpened()) {\n maxH = fs[\"H_MAX\"];\n minH = fs[\"H_MIN\"];\n maxS = fs[\"S_MAX\"];\n minS = fs[\"S_MIN\"];\n maxV = fs[\"V_MAX\"];\n minV = fs[\"V_MIN\"];\n fs.release();\n }\n\n \/\/ Create a window\n cv::namedWindow(\"binalized\");\n cv::createTrackbar(\"Hue max\", \"binalized\", &maxH, 255);\n cv::createTrackbar(\"Hue min\", \"binalized\", &minH, 255);\n cv::createTrackbar(\"Saturation max\", \"binalized\", &maxS, 255);\n cv::createTrackbar(\"Saturation min\", \"binalized\", &minS, 255);\n cv::createTrackbar(\"Value max\", \"binalized\", &maxV, 255);\n cv::createTrackbar(\"Value min\", \"binalized\", &minV, 255);\n cv::resizeWindow(\"binalized\", 0, 0);\n\n \/\/ Transition matrix (x, y, vx, vy)\n cv::Mat1f A(4, 4);\n A << 1.0, 0.0, dt, 0.0,\n 0.0, 1.0, 0.0, dt,\n 0.0, 0.0, 1.0, 0.0,\n 0.0, 0.0, 0.0, 1.0;\n kalman.transitionMatrix = A;\n\n \/\/ Measurement matrix (x, y)\n cv::Mat1f H(2, 4);\n H << 1, 0, 0, 0,\n 0, 1, 0, 0;\n kalman.measurementMatrix = H;\n\n \/\/ Process noise covairance (x, y, vx, vy)\n cv::Mat1f Q(4, 4);\n Q << 1e-5, 0.0, 0.0, 0.0,\n 0.0, 1e-5, 0.0, 0.0,\n 0.0, 0.0, 1e-5, 0.0,\n 0.0, 0.0, 0.0, 1e-5;\n kalman.processNoiseCov = Q;\n\n \/\/ Measurement noise covariance (x, y)\n cv::Mat1f R(2, 2);\n R << 1e-1, 0.0,\n 0.0, 1e-1;\n kalman.measurementNoiseCov = R;\n}\n\n\/*\n *\/\nvoid ObjectFollowing::close() {\n \/\/Save thresholds\n cv::FileStorage fs(THRESHOLDS_FILE_NAME, cv::FileStorage::READ);\n fs.open(THRESHOLDS_FILE_NAME, cv::FileStorage::WRITE);\n if (fs.isOpened()) {\n cv::write(fs, \"H_MAX\", maxH);\n cv::write(fs, \"H_MIN\", minH);\n cv::write(fs, \"S_MAX\", maxS);\n cv::write(fs, \"S_MIN\", minS);\n cv::write(fs, \"V_MAX\", maxV);\n cv::write(fs, \"V_MIN\", minV);\n fs.release();\n }\n}\n\n\/*\n returns heading for control\n *\/\nvoid ObjectFollowing::fly() {\n\n ControlMovements *controlMovements = &(control_ptr->velocities);\n cv::Mat *image = &(control_ptr->image);\n\n int tolerance = 50;\n cv::Vec3b hsvSample;\n cv::Scalar green = CV_RGB(0,255,0); \/\/putText color value\n\n \/\/switch between learning and non-learning mode\n if (control_ptr->key == 'l') {\n learnMode = !learnMode;\n if (learnMode) {\n printf(\"Learning mode is enabled\\n\");\n printf(\"The color at the crosshairs is being learned\\n\");\n printf(\"Press l again to turn off learning mode\\n\\n\");\n }\n else {\n printf(\"Learning mode is disabled\\n\");\n printf(\"The color last at the crosshairs will be targeted\\n\");\n printf(\"Press l again to learn a different color\\n\\n\");\n }\n }\n\n \/\/ HSV image\n cv::Mat hsv;\n cv::cvtColor(*image, hsv, cv::COLOR_BGR2HSV_FULL);\n\n \/\/ Binalize\n cv::Mat binalized;\n cv::Scalar lower(minH, minS, minV);\n cv::Scalar upper(maxH, maxS, maxV);\n cv::inRange(hsv, lower, upper, binalized);\n\n \/\/ Show result\n cv::imshow(\"binalized\", binalized);\n\n \/\/ De-noising\n cv::Mat kernel = getStructuringElement(cv::MORPH_RECT, cv::Size(3, 3));\n cv::morphologyEx(binalized, binalized, cv::MORPH_CLOSE, kernel);\n\n \/\/ Detect contours\n vector > contours;\n cv::findContours(binalized.clone(), contours, cv::RETR_CCOMP, cv::CHAIN_APPROX_SIMPLE);\n\n \/\/ Find largest contour\n int contour_index = -1;\n double max_area = 0.0;\n for (size_t i = 0; i < contours.size(); i++) {\n double area = fabs(cv::contourArea(contours[i]));\n if (area > max_area) {\n contour_index = i;\n max_area = area;\n }\n }\n\n\n \/\/ Object detected\n if (contour_index >= 0) {\n\n \/\/ Moments\n cv::Moments moments = cv::moments(contours[contour_index], true);\n double marker_y = (int)(moments.m01 \/ moments.m00);\n double marker_x = (int)(moments.m10 \/ moments.m00);\n\n \/\/ Measurements\n cv::Mat measurement = (cv::Mat1f(2, 1) << marker_x, marker_y);\n\n \/\/ Correction\n cv::Mat estimated = kalman.correct(measurement);\n\n \/\/ Show result\n rect = cv::boundingRect(contours[contour_index]);\n cv::rectangle(*image, rect, cv::Scalar(0, 255, 0));\n\n \/\/ Calculate average hsv for the object within the coutour\n int avgHue = 0;\n int avgSaturation = 0;\n int avgValue = 0;\n int numPoints = 0;\n\n \/\/for x in rectangle\n for (int x = rect.x; x < rect.x + rect.width; x++) {\n \/\/for y in rectangle \n for (int y = rect.y; y < rect.y + rect.height; y++) {\n \/\/ TODO: If this is to slow, use rectangle average or do every second, third, etc point in rectangle for loop\n \/\/if (inContour(x, y, contours[contour_index])) {\n cv::Point pt(x,y);\n if (rect.contains(pt)) {\n numPoints++;\n cv::Vec3b hsvPoint = hsv.at(cvPoint(x, y));\n avgHue += hsvPoint[0];\n avgSaturation += hsvPoint[1];\n avgValue += hsvPoint[2];\n }\n }\n }\n\n avgHue = ((double)avgHue)\/numPoints;\n avgSaturation = ((double)avgSaturation)\/numPoints;\n avgValue = ((double)avgValue)\/numPoints;\n\n hsvSample[0] = avgHue;\n hsvSample[1] = avgSaturation;\n hsvSample[2] = avgValue;\n\n minH = avgHue - tolerance;\n maxH = avgHue + tolerance;\n minS = avgSaturation - tolerance;\n maxS = avgSaturation + tolerance;\n minV = avgValue - tolerance;\n maxV = avgValue + tolerance;\n }\n\n \/\/ Prediction\n cv::Mat1f prediction = kalman.predict();\n int radius = 1e+3 * kalman.errorCovPre.at(0, 0);\n\n \/\/ Show predicted position\n cv::circle(*image, cv::Point(prediction(0, 0), prediction(0, 1)), radius, green, 2);\n\n \/\/ Calculate object heading fraction\n float rHeading = -(((*image).cols\/2) - prediction(0, 0))\/((*image).cols\/2);\n float zHeading = -(((*image).rows\/2) - prediction(0, 1))\/((*image).rows\/2);\n\n \/\/Emergency landing\n time_t lastSearchTime = 0;\n if (abs(rHeading) <= 0.8 && abs(zHeading) <= 0.8) {\n lastSearchTime = time(0);\n }\n\n time_t currentTime = time(0);\n double elapsedTime = difftime(currentTime, lastSearchTime);\n if (elapsedTime >= 3) {\n control_ptr->ardrone.landing();\n }\n\n \/\/ Sample the object color\n if(learnMode) {\n \/\/ Show targeting crosshairs\n cv::line(*image, cvPoint((*image).cols\/2, 0), cvPoint((*image).cols\/2, (*image).rows\/2 - 2), green); \/\/top vertical crosshair\n cv::line(*image, cvPoint((*image).cols\/2, (*image).rows\/2 + 2), cvPoint((*image).cols\/2, (*image).rows), green); \/\/bottom vertical crosshair\n cv::line(*image, cvPoint(0, (*image).rows\/2), cvPoint((*image).cols\/2 - 2, (*image).rows\/2), green); \/\/left horizontal crosshair\n cv::line(*image, cvPoint((*image).cols\/2 + 2, (*image).rows\/2), cvPoint((*image).cols, (*image).rows\/2), green); \/\/right horizontal crosshair\n\n hsvSample = hsv.at(cvPoint((*image).cols\/2, (*image).rows\/2));\n\n }\n setHSVTrackBarPositions(hsvSample[0], hsvSample[1], hsvSample[2], tolerance);\n\n displayObjectFollowingInfo(image, rHeading, zHeading, hsvSample[0], hsvSample[1], hsvSample[2]);\n\n rect_area = rect.width * rect.height;\n\n \/*\n \/\/Execute drone movement\n if (rect_area > 25000) {\n controlMovements->vx = -1.0;\n moveStatus = false;\n }\n else if (rect_area <= 25000 && rect_area >= 20000) {\n controlMovements->vx = 0;\n moveStatus = false;\n }\n else {\n controlMovements->vx = 1.0;\n moveStatus = true;\n }\n *\/\n\n controlMovements->vx = (goalArea - rect_area)\/((double)goalArea);\n\n if(controlMovements->vx > 1) {\n controlMovements->vx = 1;\n } \n else if (controlMovements->vx < -1){\n controlMovements->vx = -1;\n }\n\n \/*if( control_ptr->altitude < 1.2 )\n {\n controlMovements->vz = 1.0;\n } \n else {\n controlMovements->vz = 0.0;\n }\n *\/\n\n time_t current_time = time(0);\n double elapsed_time = difftime(current_time, control_ptr->takeoff_time);\n if (elapsed_time < 5){\n controlMovements->vx = 0;\n controlMovements->vy = 0;\n controlMovements->vz = 0;\n controlMovements->vr = 0;\n } else {\n controlMovements->vz = -(zHeading * 0.2);\n controlMovements->vr = -(rHeading * 0.5);\n } \n\n return;\n}\n\n\/\/Auto set Hue, Saturation, and Value tracking bars\nvoid setHSVTrackBarPositions(int hue, int saturation, int value, int tolerance) {\n cv::setTrackbarPos(\"Hue max\", \"binalized\", hue + tolerance);\n cv::setTrackbarPos(\"Hue min\", \"binalized\", hue - tolerance);\n\n cv::setTrackbarPos(\"Saturation max\", \"binalized\", saturation + tolerance);\n cv::setTrackbarPos(\"Saturation min\", \"binalized\", saturation - tolerance);\n\n cv::setTrackbarPos(\"Value max\", \"binalized\", value + tolerance);\n cv::setTrackbarPos(\"Value min\", \"binalized\", value - tolerance);\n\n}\n\n\/*\n *\/\nvoid ObjectFollowing::displayObjectFollowingInfo(cv::Mat *image, double rHeading, double zHeading, int hue, int saturation, int value) {\n char rHeadingDisplay[80]; \/\/print buffer for rHeading\n char zHeadingDisplay[80]; \/\/print buffer for zHeading\n char hsvSampleDisplay[80]; \/\/print buffer for learning HSV values\n char moveStatusDisplay[80]; \/\/print buffer for stop\/go status\n\n cv::Scalar green = CV_RGB(0,255,0); \/\/putText color value\n\n sprintf(rHeadingDisplay, \"rHeading = %+3.2f\", rHeading); \n sprintf(zHeadingDisplay, \"zHeading = %+3.2f\", zHeading); \n sprintf(hsvSampleDisplay, \"hsvSample = %3d, %3d, %3d\", hue, saturation, value);\n if (moveStatus) {\n sprintf(moveStatusDisplay, \"move status = GO\");\n }\n else {\n sprintf(moveStatusDisplay, \"move status = STOP\");\n }\n\n putText(*image, rHeadingDisplay, cvPoint(30, 120), cv::FONT_HERSHEY_COMPLEX_SMALL, 0.8, green, 1, CV_AA);\n putText(*image, zHeadingDisplay, cvPoint(30, 140), cv::FONT_HERSHEY_COMPLEX_SMALL, 0.8, green, 1, CV_AA);\n putText(*image, hsvSampleDisplay, cvPoint(30, 160), cv::FONT_HERSHEY_COMPLEX_SMALL, 0.8, green, 1, CV_AA);\n putText(*image, moveStatusDisplay, cvPoint(30, 180), cv::FONT_HERSHEY_COMPLEX_SMALL, 0.8, green, 1, CV_AA);\n\n}\n\n\/*\nbool inContour(int x, int y, Contour c){\n cv::Point p = new cv::Point(x,y);\n cv::MatOfPoint2f m = new cv::MatOfPoint2f(c.pointMat.toArray());\n \n double r = cv::Imgproc.pointPolygonTest(m,p, false);\n \n return r == 1;\n}\n*\/\n<|endoftext|>"} {"text":"\/****************************************************************************\n**\n** Copyright (C) 2015 Canonical Ltd.\n** Contact: http:\/\/www.qt.io\/licensing\n**\n** This file is part of Qt Creator.\n**\n** Commercial License Usage\n** Licensees holding valid commercial Qt licenses may use this file in\n** accordance with the commercial license agreement provided with the\n** Software or, alternatively, in accordance with the terms contained in\n** a written agreement between you and The Qt Company. For licensing terms and\n** conditions see http:\/\/www.qt.io\/terms-conditions. For further information\n** use the contact form at http:\/\/www.qt.io\/contact-us.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 or version 3 as published by the Free\n** Software Foundation and appearing in the file LICENSE.LGPLv21 and\n** LICENSE.LGPLv3 included in the packaging of this file. Please review the\n** following information to ensure the GNU Lesser General Public License\n** requirements will be met: https:\/\/www.gnu.org\/licenses\/lgpl.html and\n** http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, The Qt Company gives you certain additional\n** rights. These rights are described in The Qt Company LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n****************************************************************************\/\n#include \"cmakekitinformation.h\"\n#include \"cmakekitconfigwidget.h\"\n#include \"cmaketoolmanager.h\"\n#include \"cmaketool.h\"\n\n#include \n#include \n#include \n#include \n\n#include \n\nusing namespace ProjectExplorer;\n\nnamespace CMakeProjectManager {\n\nCMakeKitInformation::CMakeKitInformation()\n{\n setObjectName(QLatin1String(\"CMakeKitInformation\"));\n setId(CMakeKitInformation::id());\n\n \/\/make sure the default value is set if a selected CMake is removed\n connect(CMakeToolManager::instance(), &CMakeToolManager::cmakeRemoved,\n [this]() { foreach (Kit *k, KitManager::kits()) fix(k); });\n\n \/\/make sure the default value is set if a new default CMake is set\n connect(CMakeToolManager::instance(), &CMakeToolManager::defaultCMakeChanged,\n [this]() { foreach (Kit *k, KitManager::kits()) fix(k); });\n}\n\nCore::Id CMakeKitInformation::id()\n{\n return \"CMakeProjectManager.CMakeKitInformation\";\n}\n\nCMakeTool *CMakeKitInformation::cmakeTool(const Kit *k)\n{\n if (!k)\n return 0;\n\n const QVariant id = k->value(CMakeKitInformation::id());\n return CMakeToolManager::findById(Core::Id::fromSetting(id));\n}\n\nvoid CMakeKitInformation::setCMakeTool(Kit *k, const Core::Id id)\n{\n QTC_ASSERT(k, return);\n\n if (id.isValid()) {\n \/\/ Only set cmake tools that are known to the manager\n QTC_ASSERT(CMakeToolManager::findById(id), return);\n k->setValue(CMakeKitInformation::id(), id.toSetting());\n } else {\n \/\/setting a empty Core::Id will reset to the default value\n k->setValue(CMakeKitInformation::id(),defaultValue().toSetting());\n }\n}\n\nCore::Id CMakeKitInformation::defaultValue()\n{\n CMakeTool *defaultTool = CMakeToolManager::defaultCMakeTool();\n if (defaultTool)\n return defaultTool->id();\n\n return Core::Id();\n}\n\nQVariant CMakeKitInformation::defaultValue(Kit *) const\n{\n return defaultValue().toSetting();\n}\n\nQList CMakeKitInformation::validate(const Kit *k) const\n{\n Q_UNUSED(k);\n return QList();\n}\n\nvoid CMakeKitInformation::setup(Kit *k)\n{\n CMakeTool *tool = CMakeKitInformation::cmakeTool(k);\n if (tool)\n return;\n\n setCMakeTool(k, defaultValue());\n}\n\nvoid CMakeKitInformation::fix(Kit *k)\n{\n CMakeTool *tool = CMakeKitInformation::cmakeTool(k);\n if (!tool)\n setup(k);\n}\n\nKitInformation::ItemList CMakeKitInformation::toUserOutput(const Kit *k) const\n{\n CMakeTool *tool = cmakeTool(k);\n return ItemList() << qMakePair(tr(\"CMake\"), tool == 0 ? tr(\"Unconfigured\") : tool->displayName());\n}\n\nKitConfigWidget *CMakeKitInformation::createConfigWidget(Kit *k) const\n{\n return new Internal::CMakeKitConfigWidget(k, this);\n}\n\n} \/\/ namespace CMakeProjectManager\nCMake: Initialize kit priority\/****************************************************************************\n**\n** Copyright (C) 2015 Canonical Ltd.\n** Contact: http:\/\/www.qt.io\/licensing\n**\n** This file is part of Qt Creator.\n**\n** Commercial License Usage\n** Licensees holding valid commercial Qt licenses may use this file in\n** accordance with the commercial license agreement provided with the\n** Software or, alternatively, in accordance with the terms contained in\n** a written agreement between you and The Qt Company. For licensing terms and\n** conditions see http:\/\/www.qt.io\/terms-conditions. For further information\n** use the contact form at http:\/\/www.qt.io\/contact-us.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 or version 3 as published by the Free\n** Software Foundation and appearing in the file LICENSE.LGPLv21 and\n** LICENSE.LGPLv3 included in the packaging of this file. Please review the\n** following information to ensure the GNU Lesser General Public License\n** requirements will be met: https:\/\/www.gnu.org\/licenses\/lgpl.html and\n** http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, The Qt Company gives you certain additional\n** rights. These rights are described in The Qt Company LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n****************************************************************************\/\n#include \"cmakekitinformation.h\"\n#include \"cmakekitconfigwidget.h\"\n#include \"cmaketoolmanager.h\"\n#include \"cmaketool.h\"\n\n#include \n#include \n#include \n#include \n\n#include \n\nusing namespace ProjectExplorer;\n\nnamespace CMakeProjectManager {\n\nCMakeKitInformation::CMakeKitInformation()\n{\n setObjectName(QLatin1String(\"CMakeKitInformation\"));\n setId(CMakeKitInformation::id());\n setPriority(20000);\n\n \/\/make sure the default value is set if a selected CMake is removed\n connect(CMakeToolManager::instance(), &CMakeToolManager::cmakeRemoved,\n [this]() { foreach (Kit *k, KitManager::kits()) fix(k); });\n\n \/\/make sure the default value is set if a new default CMake is set\n connect(CMakeToolManager::instance(), &CMakeToolManager::defaultCMakeChanged,\n [this]() { foreach (Kit *k, KitManager::kits()) fix(k); });\n}\n\nCore::Id CMakeKitInformation::id()\n{\n return \"CMakeProjectManager.CMakeKitInformation\";\n}\n\nCMakeTool *CMakeKitInformation::cmakeTool(const Kit *k)\n{\n if (!k)\n return 0;\n\n const QVariant id = k->value(CMakeKitInformation::id());\n return CMakeToolManager::findById(Core::Id::fromSetting(id));\n}\n\nvoid CMakeKitInformation::setCMakeTool(Kit *k, const Core::Id id)\n{\n QTC_ASSERT(k, return);\n\n if (id.isValid()) {\n \/\/ Only set cmake tools that are known to the manager\n QTC_ASSERT(CMakeToolManager::findById(id), return);\n k->setValue(CMakeKitInformation::id(), id.toSetting());\n } else {\n \/\/setting a empty Core::Id will reset to the default value\n k->setValue(CMakeKitInformation::id(),defaultValue().toSetting());\n }\n}\n\nCore::Id CMakeKitInformation::defaultValue()\n{\n CMakeTool *defaultTool = CMakeToolManager::defaultCMakeTool();\n if (defaultTool)\n return defaultTool->id();\n\n return Core::Id();\n}\n\nQVariant CMakeKitInformation::defaultValue(Kit *) const\n{\n return defaultValue().toSetting();\n}\n\nQList CMakeKitInformation::validate(const Kit *k) const\n{\n Q_UNUSED(k);\n return QList();\n}\n\nvoid CMakeKitInformation::setup(Kit *k)\n{\n CMakeTool *tool = CMakeKitInformation::cmakeTool(k);\n if (tool)\n return;\n\n setCMakeTool(k, defaultValue());\n}\n\nvoid CMakeKitInformation::fix(Kit *k)\n{\n CMakeTool *tool = CMakeKitInformation::cmakeTool(k);\n if (!tool)\n setup(k);\n}\n\nKitInformation::ItemList CMakeKitInformation::toUserOutput(const Kit *k) const\n{\n CMakeTool *tool = cmakeTool(k);\n return ItemList() << qMakePair(tr(\"CMake\"), tool == 0 ? tr(\"Unconfigured\") : tool->displayName());\n}\n\nKitConfigWidget *CMakeKitInformation::createConfigWidget(Kit *k) const\n{\n return new Internal::CMakeKitConfigWidget(k, this);\n}\n\n} \/\/ namespace CMakeProjectManager\n<|endoftext|>"} {"text":"\/\/ TRENTO: Reduced Thickness Event-by-event Nuclear Topology\n\/\/ Copyright 2015 Jonah E. Bernhard, J. Scott Moreland\n\/\/ MIT License\n\n#include \"nucleon.h\"\n\n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n\n\n#include \"fwd_decl.h\"\n\nnamespace trento {\n\nnamespace {\n\n\/\/ These constants define distances in terms of the width of the nucleon profile\n\/\/ Gaussian thickness function.\n\n\/\/ Truncation radius of the thickness function.\nconstexpr double radius_widths = 5.;\n\n\/\/ Maximum impact parameter for participation.\nconstexpr double max_impact_widths = 6.;\n\/\/ Create ctor parameters for unit mean std::gamma_distribution.\n\/\/ mean = alpha*beta == 1 -> beta = 1\/alpha\n\/\/ Used below in NucleonProfile ctor initializer list.\n\ntemplate using param_type =\n typename std::gamma_distribution::param_type;\n\ntemplate \nparam_type gamma_param_unit_mean(RealType alpha = 1.) {\n return param_type{alpha, 1.\/alpha};\n}\n\n\/\/ Return appropriate path to temporary file directory.\n\/\/ Used to store cross section parameter \\sigma_partonic.\nfs::path get_data_home() {\n const auto data_path = std::getenv(\"XDG_DATA_HOME\");\n if(data_path == nullptr)\n return fs::path{std::getenv(\"HOME\")} \/ \".local\/share\";\n return data_path;\n}\n\n\/\/ Test approximate cross section parameter equality\nbool almost_equal(double a, double b) {\n return fabs(a - b) < 1e-6;\n}\n\n\/\/ Default parton width to nucleon width.\ndouble infer_parton_width(const VarMap& var_map) {\n auto nucleon_width = var_map[\"nucleon-width\"].as();\n auto parton_width = var_map[\"parton-width\"].as();\n if (parton_width < 0)\n return nucleon_width;\n else\n return parton_width;\n}\n\n\/\/ Determine the effective parton-parton cross section for sampling participants.\n\/\/ TODO: derive this\ndouble analytic_partonic_cross_section(const VarMap& var_map) {\n \/\/ Read parameters from the configuration.\n auto sigma_nn = var_map[\"cross-section\"].as();\n auto width = var_map[\"nucleon-width\"].as();\n \n \/\/ TODO: automatically set from beam energy\n \/\/ if (sigma_nn < 0.) {\n \/\/ auto sqrt_s = var_map[\"beam-energy\"].as();\n \/\/ }\n\n \/\/ Initialize arguments for boost root finding function.\n\n \/\/ Bracket min and max.\n auto a = -10.;\n auto b = 20.;\n\n \/\/ Tolerance function.\n \/\/ Require 3\/4 of double precision.\n math::tools::eps_tolerance tol{\n (std::numeric_limits::digits * 3) \/ 4};\n\n \/\/ Maximum iterations.\n \/\/ This is overkill -- in testing only 10-20 iterations were required\n \/\/ (but no harm in overestimating).\n boost::uintmax_t max_iter = 1000;\n\n \/\/ The right-hand side of the equation.\n auto rhs = sigma_nn \/ (4 * math::double_constants::pi * sqr(width));\n\n \/\/ This quantity appears a couple times in the equation.\n auto c = sqr(max_impact_widths) \/ 4;\n\n try {\n auto result = math::tools::toms748_solve(\n [&rhs, &c](double x) {\n using std::exp;\n using math::expint;\n return c - expint(-exp(x)) + expint(-exp(x-c)) - rhs;\n },\n a, b, tol, max_iter);\n\n auto cross_section_param = .5*(result.first + result.second);\n return std::exp(cross_section_param) * 4 * math::double_constants::pi * sqr(width);\n }\n catch (const std::domain_error&) {\n \/\/ Root finding fails for very small nucleon widths, w^2\/sigma_nn < ~0.01.\n throw std::domain_error{\n \"unable to fit cross section -- nucleon and\/or parton width too small?\"};\n }\n}\n\n\/\/ Use Monte Carlo methods to determine the partonic cross section\n\/\/ \\sigma_partonic. Solves MonteCarloCrossSection(sigma_partonic) = sigma_nn.\ndouble numeric_partonic_cross_section(const VarMap& var_map) {\n MonteCarloCrossSection mc_cross_section(var_map);\n auto sigma_nn = var_map[\"cross-section\"].as();\n auto parton_width = infer_parton_width(var_map);\n\n \/\/ Bracket min and max.\n auto a = -10.;\n auto b = 20.;\n\n \/\/ Tolerance function.\n math::tools::eps_tolerance tol{8};\n\n \/\/ Maximum iterations.\n boost::uintmax_t max_iter = 20;\n\n \/\/ Dimensional constant [fm^-1] used to rescale sigma_partonic\n auto c = 4 * math::double_constants::pi * sqr(parton_width);\n\n try {\n auto result = math::tools::toms748_solve(\n [&sigma_nn, &mc_cross_section, &c](double cross_section_param) {\n auto x = std::exp(cross_section_param) * c;\n return mc_cross_section(x) - sigma_nn;\n },\n a, b, tol, max_iter);\n\n auto cross_section_param = .5*(result.first + result.second);\n return std::exp(cross_section_param) * c;\n }\n catch (const std::domain_error&) {\n \/\/ Root finding fails for very small nucleon widths, w^2\/sigma_nn < ~0.01.\n throw std::domain_error{\n \"unable to fit cross section -- nucleon and\/or parton width too small?\"};\n }\n}\n\n\/\/ Determine the cross section parameter sigma_partonic, given the\n\/\/ nucleon width, parton width, nucleon-nucleon cross section, and parton number.\ndouble partonic_cross_section(const VarMap& var_map) {\n \/\/ Read parameters from the configuration.\n auto parton_width = infer_parton_width(var_map);\n auto nucleon_width = var_map[\"nucleon-width\"].as();\n auto sigma_nn = var_map[\"cross-section\"].as();\n auto nparton = var_map[\"parton-number\"].as();\n\n \/\/ Create trento cache directory\n auto cache_dir = get_data_home() \/ \"trento\";\n std::cout << \"cache_dir \" << cache_dir << std::endl;\n fs::create_directory(cache_dir);\n\n \/\/ Create dummy cross section file\n auto cache_path = cache_dir \/ \"cross_section.dat\";\n std::fstream cache_file(cache_path.string(),\n std::ios_base::out | std::ios_base::in | std::ios_base::app);\n\n int nparton_;\n double nucleon_width_;\n double parton_width_;\n double sigma_nn_;\n double sigma_partonic;\n\n \/\/ Check parameter configuration cache\n while(!cache_file.eof()) {\n cache_file >> nparton_ >> nucleon_width_ >>\n parton_width_ >> sigma_nn_ >> sigma_partonic;\n if (almost_equal(nucleon_width, nucleon_width_) &&\n almost_equal(parton_width, parton_width_) &&\n almost_equal(sigma_nn, sigma_nn_) &&\n (nparton == nparton_)) {\n return sigma_partonic;\n }\n }\n\n \/\/ Use a semi-analytic method to determine sigma_partonic\n \/\/ if there is no subnucleonic structure---otherwise use MC method.\n if (nucleon_width == parton_width) \n sigma_partonic = analytic_partonic_cross_section(var_map);\n else \n sigma_partonic = numeric_partonic_cross_section(var_map);\n\n \/\/ Save new cross section parameters to cache\n using std::fixed;\n using std::setprecision;\n using std::setw;\n using std::scientific;\n\n cache_file.clear();\n cache_file.seekg(0, std::ios::end);\n\n if (cache_file.tellg() != 0) {\n cache_file << std::endl;\n }\n\n cache_file.clear();\n\n cache_file << setprecision(6) << std::left\n << setw(8) << fixed << nparton\n << setw(10) << fixed << nucleon_width\n << setw(10) << fixed << parton_width \n << setw(10) << fixed << sigma_nn\n << setw(14) << scientific << sigma_partonic;\n\n return sigma_partonic;\n}\n\n\/\/ Determine the width of the normal distribution for sampling parton positions.\ndouble compute_parton_sampling_width(const VarMap& var_map) {\n \/\/ Read parameters from the configuration.\n auto nucleon_width = var_map[\"nucleon-width\"].as();\n auto parton_width = var_map[\"parton-width\"].as();\n\n \/\/ Default parton width to nucleon width.\n if (parton_width < 0) return 0.;\n\n \/\/ Compute Gaussian sampling width by deconvolving the parton profile from the\n \/\/ nucleon profile. The convolution of two Gaussians is a third Gaussian\n \/\/ with the variances simply added together.\n auto sampling_width_sq = sqr(nucleon_width) - sqr(parton_width);\n auto TINY = 1e-8;\n\n if (sampling_width_sq < -TINY) {\n throw std::out_of_range{\n \"the parton width cannot be larger than the nucleon width\"};\n }\n\n return std::sqrt(std::max(sampling_width_sq, 0.));\n}\n\n} \/\/ unnamed namespace\n\nNucleonCommon::NucleonCommon(const VarMap& var_map)\n : fast_exp_(-.5*sqr(radius_widths), 0., 1000),\n max_impact_sq_(sqr(max_impact_widths*var_map[\"nucleon-width\"].as())),\n parton_width_sq_(sqr(infer_parton_width(var_map))),\n parton_radius_sq_(sqr(radius_widths)*parton_width_sq_),\n npartons_(std::size_t(var_map[\"parton-number\"].as())),\n sigma_partonic_(partonic_cross_section(var_map)),\n prefactor_(math::double_constants::one_div_two_pi\/parton_width_sq_\/npartons_),\n participant_fluctuation_dist_(gamma_param_unit_mean(var_map[\"fluctuation\"].as())),\n parton_position_dist_(0, compute_parton_sampling_width(var_map))\n{}\n\nMonteCarloCrossSection::MonteCarloCrossSection(const VarMap& var_map)\n : npartons(std::size_t(var_map[\"parton-number\"].as())),\n nucleon_width(var_map[\"nucleon-width\"].as()),\n parton_width(infer_parton_width(var_map)),\n parton_sampling_width(compute_parton_sampling_width(var_map)),\n parton_width_sq(sqr(parton_width)),\n prefactor(math::double_constants::one_div_two_pi\/parton_width_sq\/npartons)\n{}\n\ndouble MonteCarloCrossSection::operator() (const double sigma_partonic) const {\n\n random::CyclicNormal<> cyclic_normal{\n 0., parton_sampling_width, cache_size, n_loops\n };\n\n struct Parton {\n double x, y;\n };\n\n std::vector nucleonA(npartons);\n std::vector nucleonB(npartons);\n\n auto bmax = max_impact_widths * nucleon_width;\n auto arg_max = 0.25*sqr(bmax)\/parton_width_sq; \n const FastExp fast_exp(-arg_max, 0., 1000);\n\n double ref_cross_section = 0.;\n double prob_miss = 0.;\n int pass_tolerance = 0;\n\n for (std::size_t n = 0; n < n_max; ++n) {\n \/\/ Sample b from P(b)db = 2*pi*b.\n auto b = bmax * std::sqrt(random::canonical());\n\n for (auto&& p : nucleonA) {\n p.x = cyclic_normal(random::engine);\n p.y = cyclic_normal(random::engine);\n }\n\n for (auto&& p : nucleonB) {\n p.x = cyclic_normal(random::engine);\n p.y = cyclic_normal(random::engine);\n }\n\n auto overlap = 0.;\n for (auto&& pa : nucleonA) {\n for (auto&& pb : nucleonB) {\n auto distance_sq = sqr(pa.x - pb.x + b) + sqr(pa.y - pb.y);\n auto arg = .25*distance_sq\/parton_width_sq;\n if (arg < arg_max) overlap += fast_exp(-arg);\n }\n }\n\n prob_miss +=\n std::exp(-sigma_partonic * prefactor\/(2.*npartons) * overlap);\n\n auto fraction_hit = 1. - (prob_miss\/n);\n auto sample_area = math::double_constants::pi * sqr(bmax);\n auto cross_section = fraction_hit * sample_area;\n\n auto update_difference =\n std::abs((cross_section - ref_cross_section)\/cross_section);\n\n if (update_difference < tolerance) {\n ++pass_tolerance;\n } else {\n pass_tolerance = 0;\n ref_cross_section = cross_section;\n }\n\n if (pass_tolerance > n_pass){\n return cross_section;\n }\n }\n\n throw std::out_of_range{\n \"Partonic cross section failed to converge \\\n -- check nucleon-width, parton-width and npartons\"};\n\n \/\/ Code throws an error before it ever gets here.\n return -1;\n}\n\n} \/\/ namespace trento\nRemove cout of cache_dir\/\/ TRENTO: Reduced Thickness Event-by-event Nuclear Topology\n\/\/ Copyright 2015 Jonah E. Bernhard, J. Scott Moreland\n\/\/ MIT License\n\n#include \"nucleon.h\"\n\n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n\n\n#include \"fwd_decl.h\"\n\nnamespace trento {\n\nnamespace {\n\n\/\/ These constants define distances in terms of the width of the nucleon profile\n\/\/ Gaussian thickness function.\n\n\/\/ Truncation radius of the thickness function.\nconstexpr double radius_widths = 5.;\n\n\/\/ Maximum impact parameter for participation.\nconstexpr double max_impact_widths = 6.;\n\/\/ Create ctor parameters for unit mean std::gamma_distribution.\n\/\/ mean = alpha*beta == 1 -> beta = 1\/alpha\n\/\/ Used below in NucleonProfile ctor initializer list.\n\ntemplate using param_type =\n typename std::gamma_distribution::param_type;\n\ntemplate \nparam_type gamma_param_unit_mean(RealType alpha = 1.) {\n return param_type{alpha, 1.\/alpha};\n}\n\n\/\/ Return appropriate path to temporary file directory.\n\/\/ Used to store cross section parameter \\sigma_partonic.\nfs::path get_data_home() {\n const auto data_path = std::getenv(\"XDG_DATA_HOME\");\n if(data_path == nullptr)\n return fs::path{std::getenv(\"HOME\")} \/ \".local\/share\";\n return data_path;\n}\n\n\/\/ Test approximate cross section parameter equality\nbool almost_equal(double a, double b) {\n return fabs(a - b) < 1e-6;\n}\n\n\/\/ Default parton width to nucleon width.\ndouble infer_parton_width(const VarMap& var_map) {\n auto nucleon_width = var_map[\"nucleon-width\"].as();\n auto parton_width = var_map[\"parton-width\"].as();\n if (parton_width < 0)\n return nucleon_width;\n else\n return parton_width;\n}\n\n\/\/ Determine the effective parton-parton cross section for sampling participants.\n\/\/ TODO: derive this\ndouble analytic_partonic_cross_section(const VarMap& var_map) {\n \/\/ Read parameters from the configuration.\n auto sigma_nn = var_map[\"cross-section\"].as();\n auto width = var_map[\"nucleon-width\"].as();\n \n \/\/ TODO: automatically set from beam energy\n \/\/ if (sigma_nn < 0.) {\n \/\/ auto sqrt_s = var_map[\"beam-energy\"].as();\n \/\/ }\n\n \/\/ Initialize arguments for boost root finding function.\n\n \/\/ Bracket min and max.\n auto a = -10.;\n auto b = 20.;\n\n \/\/ Tolerance function.\n \/\/ Require 3\/4 of double precision.\n math::tools::eps_tolerance tol{\n (std::numeric_limits::digits * 3) \/ 4};\n\n \/\/ Maximum iterations.\n \/\/ This is overkill -- in testing only 10-20 iterations were required\n \/\/ (but no harm in overestimating).\n boost::uintmax_t max_iter = 1000;\n\n \/\/ The right-hand side of the equation.\n auto rhs = sigma_nn \/ (4 * math::double_constants::pi * sqr(width));\n\n \/\/ This quantity appears a couple times in the equation.\n auto c = sqr(max_impact_widths) \/ 4;\n\n try {\n auto result = math::tools::toms748_solve(\n [&rhs, &c](double x) {\n using std::exp;\n using math::expint;\n return c - expint(-exp(x)) + expint(-exp(x-c)) - rhs;\n },\n a, b, tol, max_iter);\n\n auto cross_section_param = .5*(result.first + result.second);\n return std::exp(cross_section_param) * 4 * math::double_constants::pi * sqr(width);\n }\n catch (const std::domain_error&) {\n \/\/ Root finding fails for very small nucleon widths, w^2\/sigma_nn < ~0.01.\n throw std::domain_error{\n \"unable to fit cross section -- nucleon and\/or parton width too small?\"};\n }\n}\n\n\/\/ Use Monte Carlo methods to determine the partonic cross section\n\/\/ \\sigma_partonic. Solves MonteCarloCrossSection(sigma_partonic) = sigma_nn.\ndouble numeric_partonic_cross_section(const VarMap& var_map) {\n MonteCarloCrossSection mc_cross_section(var_map);\n auto sigma_nn = var_map[\"cross-section\"].as();\n auto parton_width = infer_parton_width(var_map);\n\n \/\/ Bracket min and max.\n auto a = -10.;\n auto b = 20.;\n\n \/\/ Tolerance function.\n math::tools::eps_tolerance tol{8};\n\n \/\/ Maximum iterations.\n boost::uintmax_t max_iter = 20;\n\n \/\/ Dimensional constant [fm^-1] used to rescale sigma_partonic\n auto c = 4 * math::double_constants::pi * sqr(parton_width);\n\n try {\n auto result = math::tools::toms748_solve(\n [&sigma_nn, &mc_cross_section, &c](double cross_section_param) {\n auto x = std::exp(cross_section_param) * c;\n return mc_cross_section(x) - sigma_nn;\n },\n a, b, tol, max_iter);\n\n auto cross_section_param = .5*(result.first + result.second);\n return std::exp(cross_section_param) * c;\n }\n catch (const std::domain_error&) {\n \/\/ Root finding fails for very small nucleon widths, w^2\/sigma_nn < ~0.01.\n throw std::domain_error{\n \"unable to fit cross section -- nucleon and\/or parton width too small?\"};\n }\n}\n\n\/\/ Determine the cross section parameter sigma_partonic, given the\n\/\/ nucleon width, parton width, nucleon-nucleon cross section, and parton number.\ndouble partonic_cross_section(const VarMap& var_map) {\n \/\/ Read parameters from the configuration.\n auto parton_width = infer_parton_width(var_map);\n auto nucleon_width = var_map[\"nucleon-width\"].as();\n auto sigma_nn = var_map[\"cross-section\"].as();\n auto nparton = var_map[\"parton-number\"].as();\n\n \/\/ Create trento cache directory\n auto cache_dir = get_data_home() \/ \"trento\";\n fs::create_directory(cache_dir);\n\n \/\/ Create dummy cross section file\n auto cache_path = cache_dir \/ \"cross_section.dat\";\n std::fstream cache_file(cache_path.string(),\n std::ios_base::out | std::ios_base::in | std::ios_base::app);\n\n int nparton_;\n double nucleon_width_;\n double parton_width_;\n double sigma_nn_;\n double sigma_partonic;\n\n \/\/ Check parameter configuration cache\n while(!cache_file.eof()) {\n cache_file >> nparton_ >> nucleon_width_ >>\n parton_width_ >> sigma_nn_ >> sigma_partonic;\n if (almost_equal(nucleon_width, nucleon_width_) &&\n almost_equal(parton_width, parton_width_) &&\n almost_equal(sigma_nn, sigma_nn_) &&\n (nparton == nparton_)) {\n return sigma_partonic;\n }\n }\n\n \/\/ Use a semi-analytic method to determine sigma_partonic\n \/\/ if there is no subnucleonic structure---otherwise use MC method.\n if (nucleon_width == parton_width) \n sigma_partonic = analytic_partonic_cross_section(var_map);\n else \n sigma_partonic = numeric_partonic_cross_section(var_map);\n\n \/\/ Save new cross section parameters to cache\n using std::fixed;\n using std::setprecision;\n using std::setw;\n using std::scientific;\n\n cache_file.clear();\n cache_file.seekg(0, std::ios::end);\n\n if (cache_file.tellg() != 0) {\n cache_file << std::endl;\n }\n\n cache_file.clear();\n\n cache_file << setprecision(6) << std::left\n << setw(8) << fixed << nparton\n << setw(10) << fixed << nucleon_width\n << setw(10) << fixed << parton_width \n << setw(10) << fixed << sigma_nn\n << setw(14) << scientific << sigma_partonic;\n\n return sigma_partonic;\n}\n\n\/\/ Determine the width of the normal distribution for sampling parton positions.\ndouble compute_parton_sampling_width(const VarMap& var_map) {\n \/\/ Read parameters from the configuration.\n auto nucleon_width = var_map[\"nucleon-width\"].as();\n auto parton_width = var_map[\"parton-width\"].as();\n\n \/\/ Default parton width to nucleon width.\n if (parton_width < 0) return 0.;\n\n \/\/ Compute Gaussian sampling width by deconvolving the parton profile from the\n \/\/ nucleon profile. The convolution of two Gaussians is a third Gaussian\n \/\/ with the variances simply added together.\n auto sampling_width_sq = sqr(nucleon_width) - sqr(parton_width);\n auto TINY = 1e-8;\n\n if (sampling_width_sq < -TINY) {\n throw std::out_of_range{\n \"the parton width cannot be larger than the nucleon width\"};\n }\n\n return std::sqrt(std::max(sampling_width_sq, 0.));\n}\n\n} \/\/ unnamed namespace\n\nNucleonCommon::NucleonCommon(const VarMap& var_map)\n : fast_exp_(-.5*sqr(radius_widths), 0., 1000),\n max_impact_sq_(sqr(max_impact_widths*var_map[\"nucleon-width\"].as())),\n parton_width_sq_(sqr(infer_parton_width(var_map))),\n parton_radius_sq_(sqr(radius_widths)*parton_width_sq_),\n npartons_(std::size_t(var_map[\"parton-number\"].as())),\n sigma_partonic_(partonic_cross_section(var_map)),\n prefactor_(math::double_constants::one_div_two_pi\/parton_width_sq_\/npartons_),\n participant_fluctuation_dist_(gamma_param_unit_mean(var_map[\"fluctuation\"].as())),\n parton_position_dist_(0, compute_parton_sampling_width(var_map))\n{}\n\nMonteCarloCrossSection::MonteCarloCrossSection(const VarMap& var_map)\n : npartons(std::size_t(var_map[\"parton-number\"].as())),\n nucleon_width(var_map[\"nucleon-width\"].as()),\n parton_width(infer_parton_width(var_map)),\n parton_sampling_width(compute_parton_sampling_width(var_map)),\n parton_width_sq(sqr(parton_width)),\n prefactor(math::double_constants::one_div_two_pi\/parton_width_sq\/npartons)\n{}\n\ndouble MonteCarloCrossSection::operator() (const double sigma_partonic) const {\n\n random::CyclicNormal<> cyclic_normal{\n 0., parton_sampling_width, cache_size, n_loops\n };\n\n struct Parton {\n double x, y;\n };\n\n std::vector nucleonA(npartons);\n std::vector nucleonB(npartons);\n\n auto bmax = max_impact_widths * nucleon_width;\n auto arg_max = 0.25*sqr(bmax)\/parton_width_sq; \n const FastExp fast_exp(-arg_max, 0., 1000);\n\n double ref_cross_section = 0.;\n double prob_miss = 0.;\n int pass_tolerance = 0;\n\n for (std::size_t n = 0; n < n_max; ++n) {\n \/\/ Sample b from P(b)db = 2*pi*b.\n auto b = bmax * std::sqrt(random::canonical());\n\n for (auto&& p : nucleonA) {\n p.x = cyclic_normal(random::engine);\n p.y = cyclic_normal(random::engine);\n }\n\n for (auto&& p : nucleonB) {\n p.x = cyclic_normal(random::engine);\n p.y = cyclic_normal(random::engine);\n }\n\n auto overlap = 0.;\n for (auto&& pa : nucleonA) {\n for (auto&& pb : nucleonB) {\n auto distance_sq = sqr(pa.x - pb.x + b) + sqr(pa.y - pb.y);\n auto arg = .25*distance_sq\/parton_width_sq;\n if (arg < arg_max) overlap += fast_exp(-arg);\n }\n }\n\n prob_miss +=\n std::exp(-sigma_partonic * prefactor\/(2.*npartons) * overlap);\n\n auto fraction_hit = 1. - (prob_miss\/n);\n auto sample_area = math::double_constants::pi * sqr(bmax);\n auto cross_section = fraction_hit * sample_area;\n\n auto update_difference =\n std::abs((cross_section - ref_cross_section)\/cross_section);\n\n if (update_difference < tolerance) {\n ++pass_tolerance;\n } else {\n pass_tolerance = 0;\n ref_cross_section = cross_section;\n }\n\n if (pass_tolerance > n_pass){\n return cross_section;\n }\n }\n\n throw std::out_of_range{\n \"Partonic cross section failed to converge \\\n -- check nucleon-width, parton-width and npartons\"};\n\n \/\/ Code throws an error before it ever gets here.\n return -1;\n}\n\n} \/\/ namespace trento\n<|endoftext|>"} {"text":"\/\/ http_client_test.cpp : ̨Ӧóڵ㡣\n\/\/\n\n#include \"HttpClient.h\"\n#include \n#include \n#include \n#include \"jansson.h\"\nusing namespace network;\n\nstatic std::mutex s_post_mutex;\n#ifndef __CLOUD_BOX\n\/\/#define __CLOUD_BOX\n#endif \/\/__CLOUD_BOX\n\n#ifdef __CLOUD_BOX\n#define HTTP_URL\t\t\"http:\/\/117.121.32.94:20000\/\"\n#else\n#define HTTP_URL\t\t\"http:\/\/192.168.22.61:3000\/\"\n#endif \/\/ __CLOUD_BOX\n\n\nclass HttpClientTest : public Ref\n{\npublic:\n\tHttpClientTest() {}\n\n\t~HttpClientTest(){}\n\n\tvoid initThread();\n\n\tvoid postThread();\n\t\/\/\ttest http_server,http component for login\n\tvoid post1();\n\n\tvoid post2();\n\n\t\/\/\ttest for mail\n\tvoid post3();\n\n\t\/\/Http Response Callback\n\tvoid onHttpRequestCompleted(network::HttpClient *sender, network::HttpResponse *response);\n\n};\n\nvoid HttpClientTest::post1()\n{\n\tif(0)\n\t{\n\t\tHttpRequest* request = new HttpRequest();\n\t\trequest->setUrl(\"http:\/\/httpbin.org\/post\");\n\t\trequest->setRequestType(HttpRequest::Type::POST);\n\t\trequest->setResponseCallback(this, httpresponse_selector(HttpClientTest::onHttpRequestCompleted));\n\n\t\t\/\/ write the post data\n\t\tchar postData[22] = \"binary=hello\\0\\0cocos2d\"; \/\/ including \\0, the strings after \\0 should not be cut in response\n\t\trequest->setRequestData(postData, 22); \n\n\t\trequest->setTag(\"POST Binary test\");\n\t\tHttpClient::getInstance()->send(request);\n\t\trequest->release();\n\t}\n\telse\n\t{\n\t\ttry \n\t\t{\n\t\t\ts_post_mutex.lock();\n\t\t\t\/\/\tpost data to http server\n\t\t\tstd::string __string_account = \"&account=king_lee\";\n\t\t\tstd::string __string_msg = \"msg=\";\n\t\t\tjson_t* __msg = json_object();\n\t\t\tjson_t* __msg_id = json_integer(\/*MSG_ID::MSG_LOGIN*\/2);\n\t\t\tjson_t* __msg_context = json_string(\"context\");\n\t\t\tjson_object_set(__msg, \"msg_id\", __msg_id);\n\t\t\tjson_object_set(__msg, \"context\", __msg_context);\n\n\n\t\t\tHttpRequest* request = new HttpRequest();\n\t\t\trequest->setUrl(\"http:\/\/192.168.22.61:3001\/\");\n\t\t\tstd::vector __head;\n\t\t\t__head.push_back(\"Content-Type: application\/json; charset=utf-8\");\n\t\t\trequest->setHeaders(__head);\n\t\t\trequest->setRequestType(HttpRequest::Type::POST);\n\t\t\trequest->setResponseCallback(this, httpresponse_selector(HttpClientTest::onHttpRequestCompleted));\n\n\t\t\t\/\/ write the post data\n\t\t\tconst char* postData = json_dumps(__msg,0);\n\t\t\tif(postData)\n\t\t\t{\n\t\t\t\t\/\/\tmsg={\"context\": \"context\", \"msg_id\": 2}\n\t\t\t\t__string_msg += postData;\n\t\t\t\t__string_msg += __string_account;\n\t\t\t\trequest->setRequestData(__string_msg.c_str(), __string_msg.length());\n\t\t\t}\n\t\t\trequest->setTag(\"POST test1\\n\");\n\t\t\tHttpClient::getInstance()->send(request);\n\t\t\trequest->release();\n\n\t\t\t\/\/ decref for json object\n\t\t\tjson_decref(__msg_id);\n\t\t\ts_post_mutex.unlock();\n\t\t}\n\t\tcatch(std::exception & __exception)\n\t\t{\n\t\t\tprintf(\"exception : %s\\n\",__exception.what());\n\t\t\ts_post_mutex.unlock();\n\t\t}\n\t}\n}\n\nvoid HttpClientTest::post2()\n{\n\t\/\/\tpost data to http server\n\tstd::string __string_token = \"&token=1234567788\";\n\tstd::string __string_msg = \"msg=\";\n\tjson_t* __msg = json_object();\n\tjson_t* __msg_id = json_integer(\/*TYPE_MSG_GET_SRV_TIME:*\/3);\n\tjson_t* __flow_id = json_integer(88888888);\n\tjson_object_set(__msg, \"msg_id\", __msg_id);\n\tjson_object_set(__msg, \"flowid\", __flow_id);\n\n\tHttpRequest* request = new HttpRequest();\n\trequest->setUrl(HTTP_URL);\n\trequest->setRequestType(HttpRequest::Type::POST);\n\trequest->setResponseCallback(this, httpresponse_selector(HttpClientTest::onHttpRequestCompleted));\n\n\t\/\/ write the post data\n\tconst char* postData = json_dumps(__msg,0);\n\tif(postData)\n\t{\n\t\t__string_msg += postData;\n\t\t__string_msg += __string_token;\n\t\trequest->setRequestData(__string_msg.c_str(), __string_msg.length());\n\t}\n\trequest->setTag(\"POST test1\\n\");\n\tHttpClient::getInstance()->send(request);\n\trequest->release();\n\n\t\/\/ decref for json object\n\tjson_decref(__msg_id);\n\tjson_decref(__flow_id);\n}\n\nvoid HttpClientTest::post3()\n{\n\t\/\/\tpost data to http server\n\tstd::string __string_token = \"&token=1234567788\";\n\tstd::string __string_msg = \"msg=\";\n\tjson_t* __msg = json_object();\n\tjson_t* __msg_id = json_integer(\/*TYPE_MSG_MAIL:*\/4);\n\tjson_t* __msg_title = json_string(\"title\");\n\tjson_t* __msg_content = json_string(\"content\");\n\tjson_t* __msg_channel = json_string(\"qihu360\");\n\tjson_t* __msg_version = json_string(\"1.1.1.0\");\n\tjson_object_set(__msg, \"msg_id\", __msg_id);\n\tjson_object_set(__msg, \"title\", __msg_title);\n\tjson_object_set(__msg, \"content\", __msg_content);\n\tjson_object_set(__msg, \"channel\", __msg_channel);\n\tjson_object_set(__msg, \"version\", __msg_version);\n\n\tHttpRequest* request = new HttpRequest();\n\trequest->setUrl(HTTP_URL);\n\trequest->setRequestType(HttpRequest::Type::POST);\n\trequest->setResponseCallback(this, httpresponse_selector(HttpClientTest::onHttpRequestCompleted));\n\n\t\/\/ write the post data\n\tconst char* postData = json_dumps(__msg,0);\n\tif(postData)\n\t{\n\t\t__string_msg += postData;\n\t\t__string_msg += __string_token;\n\t\trequest->setRequestData(__string_msg.c_str(), __string_msg.length());\n\t}\n\trequest->setTag(\"POST test1\\n\");\n\tHttpClient::getInstance()->send(request);\n\trequest->release();\n\n\t\/\/ decref for json object\n\tjson_decref(__msg_id);\n}\n\n\nvoid HttpClientTest::onHttpRequestCompleted( network::HttpClient *sender, network::HttpResponse *response )\n{\n\tif (!response)\n\t{\n\t\treturn;\n\t}\n\n\t\/\/ You can get original request type from: response->request->reqType\n\tif (0 != strlen(response->getHttpRequest()->getTag())) \n\t{\n\t\tprintf(\"%s completed \", response->getHttpRequest()->getTag());\n\t}\n\n\tlong statusCode = response->getResponseCode();\n\tchar statusString[64] = {};\n\tsprintf(statusString, \"HTTP Status Code: %ld, tag = %s\", statusCode, response->getHttpRequest()->getTag());\n\tprintf(\"response code: %ld\", statusCode);\n\n\tif (!response->isSucceed()) \n\t{\n\t\tprintf(\"response failed\");\n\t\tprintf(\"error buffer: %s\", response->getErrorBuffer());\n\t\treturn;\n\t}\n\n\t\/\/ dump data\n\tstd::vector *buffer = response->getResponseData();\n\tprintf(\"Http Test, dump data: \\n\");\n\tfor (unsigned int i = 0; i < buffer->size(); i++)\n\t{\n\t\tprintf(\"%c\", (*buffer)[i]);\n\t}\n\tprintf(\"\\n\");\n}\n\nvoid HttpClientTest::postThread()\n{\n\twhile (true)\n\t{\n\t\tthis->post1();\n\t\tstd::this_thread::sleep_for(std::chrono::milliseconds(100));\n\t}\n}\n\nvoid HttpClientTest::initThread()\n{\n\tconst int __max_thread = 1;\n\tfor(int i = 0; i < __max_thread; ++i)\n\t{\n\t\tauto t = std::thread(std::bind(&HttpClientTest::postThread,this));\n\t\tt.detach();\n\t\tstd::this_thread::sleep_for(std::chrono::milliseconds(100));\n\t}\n}\n\nint _tmain(int argc, _TCHAR* argv[])\n{\n\tHttpClientTest* __test = new HttpClientTest();\n\tif(1)\n\t{\n\t\tif(0)\n\t\t{\n\t\t\t__test->post1();\n\t\t}\n\t\telse\n\t\t{\n\t\t\t__test->post2();\n\t\t\t__test->post3();\n\t\t}\n\n\t}\n\telse\n\t{\n\t\t__test->initThread();\n\t}\n\n\twhile (true)\n\t{\n\t\tif(1)\n\t\t{\n\t\t\t::_sleep(1);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tstd::this_thread::sleep_for(std::chrono::milliseconds(1));\n\t\t}\n\t}\n\treturn 0;\n}\n\nadd activity test\/\/ http_client_test.cpp : ̨Ӧóڵ㡣\n\/\/\n\n#include \"HttpClient.h\"\n#include \n#include \n#include \n#include \"jansson.h\"\nusing namespace network;\n\nstatic std::mutex s_post_mutex;\n#ifndef __CLOUD_BOX\n\/\/#define __CLOUD_BOX\n#endif \/\/__CLOUD_BOX\n\n#ifndef __CLOUD_BOX_FORMAL\n#define __CLOUD_BOX_FORMAL\n#endif \/\/__CLOUD_BOX_FORMAL\n\n#ifdef __CLOUD_BOX\n\t#ifdef __CLOUD_BOX_FORMAL\n\t#define HTTP_URL\t\t\"server.wscs.appget.cn:20000\/\"\n\t#else\n\t#define HTTP_URL\t\t\"http:\/\/117.121.32.94:20000\/\"\n\t#endif \/\/__CLOUD_BOX_FORMAL\n#else\n#define HTTP_URL\t\t\"http:\/\/192.168.22.61:20000\/\"\n#endif \/\/ __CLOUD_BOX\n\n\nclass HttpClientTest : public Ref\n{\npublic:\n\tHttpClientTest() {}\n\n\t~HttpClientTest(){}\n\n\tvoid initThread();\n\n\tvoid postThread();\n\t\/\/\ttest http_server,http component for login\n\tvoid post1();\n\n\tvoid post2();\n\n\t\/\/\ttest for mail\n\tvoid post3();\n\n\tvoid post4(int __msg_type);\n\n\t\/\/Http Response Callback\n\tvoid onHttpRequestCompleted(network::HttpClient *sender, network::HttpResponse *response);\n\n};\n\nvoid HttpClientTest::post1()\n{\n\tif(0)\n\t{\n\t\tHttpRequest* request = new HttpRequest();\n\t\trequest->setUrl(\"http:\/\/httpbin.org\/post\");\n\t\trequest->setRequestType(HttpRequest::Type::POST);\n\t\trequest->setResponseCallback(this, httpresponse_selector(HttpClientTest::onHttpRequestCompleted));\n\n\t\t\/\/ write the post data\n\t\tchar postData[22] = \"binary=hello\\0\\0cocos2d\"; \/\/ including \\0, the strings after \\0 should not be cut in response\n\t\trequest->setRequestData(postData, 22); \n\n\t\trequest->setTag(\"POST Binary test\");\n\t\tHttpClient::getInstance()->send(request);\n\t\trequest->release();\n\t}\n\telse\n\t{\n\t\ttry \n\t\t{\n\t\t\ts_post_mutex.lock();\n\t\t\t\/\/\tpost data to http server\n\t\t\tstd::string __string_account = \"&account=king_lee\";\n\t\t\tstd::string __string_msg = \"msg=\";\n\t\t\tjson_t* __msg = json_object();\n\t\t\tjson_t* __msg_id = json_integer(\/*MSG_ID::MSG_LOGIN*\/2);\n\t\t\tjson_t* __msg_context = json_string(\"context\");\n\t\t\tjson_object_set(__msg, \"msg_id\", __msg_id);\n\t\t\tjson_object_set(__msg, \"context\", __msg_context);\n\n\n\t\t\tHttpRequest* request = new HttpRequest();\n\t\t\trequest->setUrl(\"http:\/\/192.168.22.61:3001\/\");\n\t\t\tstd::vector __head;\n\t\t\t__head.push_back(\"Content-Type: application\/json; charset=utf-8\");\n\t\t\trequest->setHeaders(__head);\n\t\t\trequest->setRequestType(HttpRequest::Type::POST);\n\t\t\trequest->setResponseCallback(this, httpresponse_selector(HttpClientTest::onHttpRequestCompleted));\n\n\t\t\t\/\/ write the post data\n\t\t\tconst char* postData = json_dumps(__msg,0);\n\t\t\tif(postData)\n\t\t\t{\n\t\t\t\t\/\/\tmsg={\"context\": \"context\", \"msg_id\": 2}\n\t\t\t\t__string_msg += postData;\n\t\t\t\t__string_msg += __string_account;\n\t\t\t\trequest->setRequestData(__string_msg.c_str(), __string_msg.length());\n\t\t\t}\n\t\t\trequest->setTag(\"POST test1\\n\");\n\t\t\tHttpClient::getInstance()->send(request);\n\t\t\trequest->release();\n\n\t\t\t\/\/ decref for json object\n\t\t\tjson_decref(__msg_id);\n\t\t\ts_post_mutex.unlock();\n\t\t}\n\t\tcatch(std::exception & __exception)\n\t\t{\n\t\t\tprintf(\"exception : %s\\n\",__exception.what());\n\t\t\ts_post_mutex.unlock();\n\t\t}\n\t}\n}\n\nvoid HttpClientTest::post2()\n{\n\t\/\/\tpost data to http server\n\tstd::string __string_token = \"&token=1234567788\";\n\tstd::string __string_msg = \"msg=\";\n\tjson_t* __msg = json_object();\n\tjson_t* __msg_id = json_integer(\/*TYPE_MSG_GET_SRV_TIME:*\/3);\n\tjson_t* __flow_id = json_integer(88888888);\n\tjson_object_set(__msg, \"msg_id\", __msg_id);\n\tjson_object_set(__msg, \"flowid\", __flow_id);\n\n\tHttpRequest* request = new HttpRequest();\n\trequest->setUrl(HTTP_URL);\n\trequest->setRequestType(HttpRequest::Type::POST);\n\trequest->setResponseCallback(this, httpresponse_selector(HttpClientTest::onHttpRequestCompleted));\n\n\t\/\/ write the post data\n\tconst char* postData = json_dumps(__msg,0);\n\tif(postData)\n\t{\n\t\t__string_msg += postData;\n\t\t__string_msg += __string_token;\n\t\trequest->setRequestData(__string_msg.c_str(), __string_msg.length());\n\t}\n\trequest->setTag(\"POST test1\\n\");\n\tHttpClient::getInstance()->send(request);\n\trequest->release();\n\n\t\/\/ decref for json object\n\tjson_decref(__msg_id);\n\tjson_decref(__flow_id);\n}\n\nvoid HttpClientTest::post3()\n{\n\t\/\/\tpost data to http server\n\tstd::string __string_token = \"&token=1234567788\";\n\tstd::string __string_msg = \"msg=\";\n\tjson_t* __msg = json_object();\n\tjson_t* __msg_id = json_integer(\/*TYPE_MSG_MAIL:*\/4);\n\tjson_t* __msg_title = json_string(\"title\");\n\tjson_t* __msg_content = json_string(\"content\");\n\tjson_t* __msg_channel = json_string(\"qihu360\");\n\tjson_t* __msg_version = json_string(\"1.1.1.0\");\n\tjson_object_set(__msg, \"msg_id\", __msg_id);\n\tjson_object_set(__msg, \"title\", __msg_title);\n\tjson_object_set(__msg, \"content\", __msg_content);\n\tjson_object_set(__msg, \"channel\", __msg_channel);\n\tjson_object_set(__msg, \"version\", __msg_version);\n\n\tHttpRequest* request = new HttpRequest();\n\trequest->setUrl(HTTP_URL);\n\trequest->setRequestType(HttpRequest::Type::POST);\n\trequest->setResponseCallback(this, httpresponse_selector(HttpClientTest::onHttpRequestCompleted));\n\n\t\/\/ write the post data\n\tconst char* postData = json_dumps(__msg,0);\n\tif(postData)\n\t{\n\t\t__string_msg += postData;\n\t\t__string_msg += __string_token;\n\t\trequest->setRequestData(__string_msg.c_str(), __string_msg.length());\n\t}\n\trequest->setTag(\"POST test1\\n\");\n\tHttpClient::getInstance()->send(request);\n\trequest->release();\n\n\t\/\/ decref for json object\n\tjson_decref(__msg_id);\n}\n\nvoid HttpClientTest::post4(int __msg_type)\n{\n\t\/\/\tpost data to http server\n\tstd::string __string_token = \"&token=1234567788\";\n\tstd::string __string_msg = \"msg=\";\n\tjson_t* __msg = json_object();\n\tjson_t* __msg_id = json_integer(__msg_type);\n\tjson_t* __msg_channel = json_string(\"qihu360\");\n\tjson_t* __msg_version = json_string(\"1.1.1.0\");\n\tjson_object_set(__msg, \"msg_id\", __msg_id);\n\tjson_object_set(__msg, \"channel\", __msg_channel);\n\tjson_object_set(__msg, \"version\", __msg_version);\n\n\tHttpRequest* request = new HttpRequest();\n\trequest->setUrl(HTTP_URL);\n\trequest->setRequestType(HttpRequest::Type::POST);\n\trequest->setResponseCallback(this, httpresponse_selector(HttpClientTest::onHttpRequestCompleted));\n\n\t\/\/ write the post data\n\tconst char* postData = json_dumps(__msg,0);\n\tif(postData)\n\t{\n\t\t__string_msg += postData;\n\t\t__string_msg += __string_token;\n\t\trequest->setRequestData(__string_msg.c_str(), __string_msg.length());\n\t}\n\trequest->setTag(\"POST test1\\n\");\n\tHttpClient::getInstance()->send(request);\n\trequest->release();\n\n\t\/\/ decref for json object\n\tjson_decref(__msg_id);\n}\n\nvoid HttpClientTest::onHttpRequestCompleted( network::HttpClient *sender, network::HttpResponse *response )\n{\n\tif (!response)\n\t{\n\t\treturn;\n\t}\n\n\t\/\/ You can get original request type from: response->request->reqType\n\tif (0 != strlen(response->getHttpRequest()->getTag())) \n\t{\n\t\tprintf(\"%s completed \", response->getHttpRequest()->getTag());\n\t}\n\n\tlong statusCode = response->getResponseCode();\n\tchar statusString[64] = {};\n\tsprintf(statusString, \"HTTP Status Code: %ld, tag = %s\", statusCode, response->getHttpRequest()->getTag());\n\tprintf(\"response code: %ld\", statusCode);\n\n\tif (!response->isSucceed()) \n\t{\n\t\tprintf(\"response failed\");\n\t\tprintf(\"error buffer: %s\", response->getErrorBuffer());\n\t\treturn;\n\t}\n\n\t\/\/ dump data\n\tstd::vector *buffer = response->getResponseData();\n\tprintf(\"Http Test, dump data: \\n\");\n\tfor (unsigned int i = 0; i < buffer->size(); i++)\n\t{\n\t\tprintf(\"%c\", (*buffer)[i]);\n\t}\n\tprintf(\"\\n\");\n}\n\nvoid HttpClientTest::postThread()\n{\n\twhile (true)\n\t{\n\t\tthis->post1();\n\t\tstd::this_thread::sleep_for(std::chrono::milliseconds(100));\n\t}\n}\n\nvoid HttpClientTest::initThread()\n{\n\tconst int __max_thread = 1;\n\tfor(int i = 0; i < __max_thread; ++i)\n\t{\n\t\tauto t = std::thread(std::bind(&HttpClientTest::postThread,this));\n\t\tt.detach();\n\t\tstd::this_thread::sleep_for(std::chrono::milliseconds(100));\n\t}\n}\n\nint _tmain(int argc, _TCHAR* argv[])\n{\n\tHttpClientTest* __test = new HttpClientTest();\n\tif(1)\n\t{\n\t\tif(0)\n\t\t{\n\t\t\t__test->post1();\n\t\t}\n\t\telse\n\t\t{\n\t\t\t__test->post2();\n\t\t\t__test->post3();\n\t\t\t__test->post4(5);\n\t\t\t__test->post4(6);\n\t\t}\n\n\t}\n\telse\n\t{\n\t\t__test->initThread();\n\t}\n\n\twhile (true)\n\t{\n\t\tif(1)\n\t\t{\n\t\t\t::_sleep(1);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tstd::this_thread::sleep_for(std::chrono::milliseconds(1));\n\t\t}\n\t}\n\treturn 0;\n}\n\n<|endoftext|>"} {"text":"\/\/ Jubatus: Online machine learning framework for distributed environment\n\/\/ Copyright (C) 2011-2013 Preferred Infrastructure and Nippon Telegraph and Telephone Corporation.\n\/\/\n\/\/ This library is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU Lesser General Public\n\/\/ License version 2.1 as published by the Free Software Foundation.\n\/\/\n\/\/ This library is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ Lesser General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License along with this library; if not, write to the Free Software\n\/\/ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n#include \"mixer_factory.hpp\"\n\n#include \n#include \"jubatus\/util\/lang\/shared_ptr.h\"\n\n#ifdef HAVE_ZOOKEEPER_H\n#include \"linear_mixer.hpp\"\n#include \"random_mixer.hpp\"\n#include \"broadcast_mixer.hpp\"\n#include \"skip_mixer.hpp\"\n#else\n#include \"dummy_mixer.hpp\"\n#endif\n\nnamespace jubatus {\nnamespace server {\nnamespace framework {\nnamespace mixer {\n\nmixer* create_mixer(\n const server_argv& a,\n const jubatus::util::lang::shared_ptr& zk) {\n#ifdef HAVE_ZOOKEEPER_H\n const std::string& use_mixer = a.mixer;\n if (use_mixer == \"linear_mixer\") {\n return new linear_mixer(\n linear_communication::create(\n zk, a.type, a.name, a.interconnect_timeout),\n a.interval_count, a.interval_sec);\n } else if (use_mixer == \"random_mixer\") {\n return new random_mixer(\n push_communication::create(\n zk, a.type, a.name, a.interconnect_timeout),\n a.interval_count, a.interval_sec, std::make_pair(a.eth, a.port));\n } else if (use_mixer == \"broadcast_mixer\") {\n return new broadcast_mixer(\n push_communication::create(zk, a.type, a.name, a.interconnect_timeout),\n a.interval_count, a.interval_sec, std::make_pair(a.eth, a.port));\n } else if (use_mixer == \"skip_mixer\") {\n return new skip_mixer(\n push_communication::create(zk, a.type, a.name, a.interconnect_timeout),\n a.interval_count, a.interval_sec, std::make_pair(a.eth, a.port));\n } else {\n \/\/ TODO(beam2d): fix to throw\n return new linear_mixer(\n linear_communication::create(\n zk, a.type, a.name, a.interconnect_timeout),\n a.interval_count, a.interval_sec);\n }\n#else\n return new dummy_mixer;\n#endif\n}\n\n} \/\/ namespace mixer\n} \/\/ namespace framework\n} \/\/ namespace server\n} \/\/ namespace jubatus\nRaise exception if unsupported mix strategy name specified\/\/ Jubatus: Online machine learning framework for distributed environment\n\/\/ Copyright (C) 2011-2013 Preferred Infrastructure and Nippon Telegraph and Telephone Corporation.\n\/\/\n\/\/ This library is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU Lesser General Public\n\/\/ License version 2.1 as published by the Free Software Foundation.\n\/\/\n\/\/ This library is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ Lesser General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License along with this library; if not, write to the Free Software\n\/\/ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n#include \"mixer_factory.hpp\"\n\n#include \n#include \"jubatus\/util\/lang\/shared_ptr.h\"\n#include \"jubatus\/core\/common\/exception.hpp\"\n\n#ifdef HAVE_ZOOKEEPER_H\n#include \"linear_mixer.hpp\"\n#include \"random_mixer.hpp\"\n#include \"broadcast_mixer.hpp\"\n#include \"skip_mixer.hpp\"\n#else\n#include \"dummy_mixer.hpp\"\n#endif\n\nnamespace jubatus {\nnamespace server {\nnamespace framework {\nnamespace mixer {\n\nmixer* create_mixer(\n const server_argv& a,\n const jubatus::util::lang::shared_ptr& zk) {\n#ifdef HAVE_ZOOKEEPER_H\n const std::string& use_mixer = a.mixer;\n if (use_mixer.empty() || use_mixer == \"linear_mixer\") {\n return new linear_mixer(\n linear_communication::create(\n zk, a.type, a.name, a.interconnect_timeout),\n a.interval_count, a.interval_sec);\n } else if (use_mixer == \"random_mixer\") {\n return new random_mixer(\n push_communication::create(\n zk, a.type, a.name, a.interconnect_timeout),\n a.interval_count, a.interval_sec, std::make_pair(a.eth, a.port));\n } else if (use_mixer == \"broadcast_mixer\") {\n return new broadcast_mixer(\n push_communication::create(zk, a.type, a.name, a.interconnect_timeout),\n a.interval_count, a.interval_sec, std::make_pair(a.eth, a.port));\n } else if (use_mixer == \"skip_mixer\") {\n return new skip_mixer(\n push_communication::create(zk, a.type, a.name, a.interconnect_timeout),\n a.interval_count, a.interval_sec, std::make_pair(a.eth, a.port));\n } else {\n throw JUBATUS_EXCEPTION(jubatus::core::common::exception::runtime_error(\n \"unsupported mix type (\" + use_mixer + \")\"));\n }\n#else\n return new dummy_mixer;\n#endif\n}\n\n} \/\/ namespace mixer\n} \/\/ namespace framework\n} \/\/ namespace server\n} \/\/ namespace jubatus\n<|endoftext|>"} {"text":"\/* Siconos is a program dedicated to modeling, simulation and control\n * of non smooth dynamical systems.\n *\n * Copyright 2018 INRIA.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n*\/\n\/*! \\file\n Fricton-Contact Non-Smooth Problem\n*\/\n#ifndef GENERICMECHANICAL_H\n#define GENERICMECHANICAL_H\n\n#include \"LinearOSNS.hpp\"\n#include \"SiconosNumerics.h\"\n#include \"Friction_cst.h\" \/\/ from numerics, for solver id\n\nTYPEDEF_SPTR(GenericMechanicalProblem)\n\n\/** Formalization and Resolution of a generic mechanical problem: It mixes bilateral equality, complementarity, impact and friction problems.\n *\n * This class is devoted to contains of a set of Non-Smooth Problem.\n *\n * \\b Main functions:\n * - formalization of the problem: computes M,q using the set of \"active\" Interactions from the simulation and \\n\n * the interactionBlock-matrices saved in the field interactionBlocks.\\n\n * Functions: initialize(), computeInteractionBlock(), preCompute()\n * - solving of the GenericMechanical problem: function compute(), used to call solvers from Numerics through \\n\n * the gmp_driver() interface of Numerics.\n * - post-treatment of data: set values of y\/lambda variables of the active Interaction (ie Interactions) using \\n\n * ouput results from the solver (velocity,reaction); function postCompute().\n *\n *\/\nclass GenericMechanical : public LinearOSNS\n{\nprotected:\n \/** serialization hooks *\/\n ACCEPT_SERIALIZATION(GenericMechanical);\n\n GenericMechanicalProblem * _pnumerics_GMP;\n\npublic:\n \n \/** constructor from solver id\n \\param numericsSolverId id of the internal friction solver of the generic problem\n default = SICONOS_FRICTION_3D_ONECONTACT_QUARTIC\n *\/\n GenericMechanical(int FC3D_Solver_Id = SICONOS_FRICTION_3D_ONECONTACT_QUARTIC);\n\n \/** constructor from a pre-defined solver options set.\n \\param options, the options set, \n \\rst\n see :ref:`problems_and_solvers` for details.\n \\endrst\n *\/\n GenericMechanical(SP::SolverOptions options);\n\n \/** destructor\n *\/\n ~GenericMechanical();\n\n \/\/ GETTERS\/SETTERS\n\n\n \/\/ --- Others functions ---\n\n \/** initialize the GenericMechanical problem(compute topology ...)\n * \\param sim the simulation, owner of this OSNSPB\n *\/\n void initialize(SP::Simulation sim);\n\n \/** Compute the unknown reaction and velocity and update the Interaction (y and lambda )\n * \\param time double current time\n * \\return int information about the solver convergence (0: ok, >0 problem, see Numerics documentation)\n *\/\n int compute(double time);\n\n \/** compute extra-diagonal interactionBlock-matrix\n * \\param ed an edge descriptor\n *\/\n virtual void computeInteractionBlock(const InteractionsGraph::EDescriptor& ed);\n\n \/** compute diagonal Interaction block\n * \\param vd a vertex descriptor\n *\/\n virtual void computeDiagonalInteractionBlock(const InteractionsGraph::VDescriptor& vd);\n\n \/** print the data to the screen *\/\n void display() const;\n \n \/** compute interactionBlocks if necessary (this depends on the type of\n OSNS, on the indexSets ...)\n *\/\n void updateInteractionBlocks();\n\n \/** visitors hook\n *\/\n ACCEPT_STD_VISITORS();\n\n\n\n};\n\n#endif \/\/ GenericMechanical_H\n[kernel] change the default solver for frictional contact in GMP\/* Siconos is a program dedicated to modeling, simulation and control\n * of non smooth dynamical systems.\n *\n * Copyright 2018 INRIA.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n*\/\n\/*! \\file\n Fricton-Contact Non-Smooth Problem\n*\/\n#ifndef GENERICMECHANICAL_H\n#define GENERICMECHANICAL_H\n\n#include \"LinearOSNS.hpp\"\n#include \"SiconosNumerics.h\"\n#include \"Friction_cst.h\" \/\/ from numerics, for solver id\n\nTYPEDEF_SPTR(GenericMechanicalProblem)\n\n\/** Formalization and Resolution of a generic mechanical problem: It mixes bilateral equality, complementarity, impact and friction problems.\n *\n * This class is devoted to contains of a set of Non-Smooth Problem.\n *\n * \\b Main functions:\n * - formalization of the problem: computes M,q using the set of \"active\" Interactions from the simulation and \\n\n * the interactionBlock-matrices saved in the field interactionBlocks.\\n\n * Functions: initialize(), computeInteractionBlock(), preCompute()\n * - solving of the GenericMechanical problem: function compute(), used to call solvers from Numerics through \\n\n * the gmp_driver() interface of Numerics.\n * - post-treatment of data: set values of y\/lambda variables of the active Interaction (ie Interactions) using \\n\n * ouput results from the solver (velocity,reaction); function postCompute().\n *\n *\/\nclass GenericMechanical : public LinearOSNS\n{\nprotected:\n \/** serialization hooks *\/\n ACCEPT_SERIALIZATION(GenericMechanical);\n\n GenericMechanicalProblem * _pnumerics_GMP;\n\npublic:\n \n \/** constructor from solver id\n \\param numericsSolverId id of the internal friction solver of the generic problem\n default = SICONOS_FRICTION_3D_ONECONTACT_NSN\n *\/\n GenericMechanical(int FC3D_Solver_Id = SICONOS_FRICTION_3D_ONECONTACT_NSN);\n\n \/** constructor from a pre-defined solver options set.\n \\param options, the options set, \n \\rst\n see :ref:`problems_and_solvers` for details.\n \\endrst\n *\/\n GenericMechanical(SP::SolverOptions options);\n\n \/** destructor\n *\/\n ~GenericMechanical();\n\n \/\/ GETTERS\/SETTERS\n\n\n \/\/ --- Others functions ---\n\n \/** initialize the GenericMechanical problem(compute topology ...)\n * \\param sim the simulation, owner of this OSNSPB\n *\/\n void initialize(SP::Simulation sim);\n\n \/** Compute the unknown reaction and velocity and update the Interaction (y and lambda )\n * \\param time double current time\n * \\return int information about the solver convergence (0: ok, >0 problem, see Numerics documentation)\n *\/\n int compute(double time);\n\n \/** compute extra-diagonal interactionBlock-matrix\n * \\param ed an edge descriptor\n *\/\n virtual void computeInteractionBlock(const InteractionsGraph::EDescriptor& ed);\n\n \/** compute diagonal Interaction block\n * \\param vd a vertex descriptor\n *\/\n virtual void computeDiagonalInteractionBlock(const InteractionsGraph::VDescriptor& vd);\n\n \/** print the data to the screen *\/\n void display() const;\n \n \/** compute interactionBlocks if necessary (this depends on the type of\n OSNS, on the indexSets ...)\n *\/\n void updateInteractionBlocks();\n\n \/** visitors hook\n *\/\n ACCEPT_STD_VISITORS();\n\n\n\n};\n\n#endif \/\/ GenericMechanical_H\n<|endoftext|>"} {"text":"\/* -*- mode: c++; c-basic-offset:4 -*-\n commands\/lookupcertificatescommand.cpp\n\n This file is part of Kleopatra, the KDE keymanager\n Copyright (c) 2008 Klarälvdalens Datakonsult AB\n\n Kleopatra is free software; you can redistribute it and\/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation; either version 2 of the License, or\n (at your option) any later version.\n\n Kleopatra is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with this program; if not, write to the Free Software\n Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n In addition, as a special exception, the copyright holders give\n permission to link the code of this program with any edition of\n the Qt library by Trolltech AS, Norway (or with modified versions\n of Qt that use the same license as Qt), and distribute linked\n combinations including the two. You must obey the GNU General\n Public License in all respects for all of the code used other than\n Qt. If you modify this file, you may extend this exception to\n your version of the file, but you are not obligated to do so. If\n you do not wish to do so, delete this exception statement from\n your version.\n*\/\n\n#include \n\n#include \"lookupcertificatescommand.h\"\n\n#include \"importcertificatescommand_p.h\"\n\n#include \"detailscommand.h\"\n\n#include \n\n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n\n#include \n#include \n#include \n\n#include \n\n#include \n#include \n\n#include \n#include \n#include \n#include \n\nusing namespace Kleo;\nusing namespace Kleo::Commands;\nusing namespace Kleo::Dialogs;\nusing namespace GpgME;\nusing namespace boost;\n\nclass LookupCertificatesCommand::Private : public ImportCertificatesCommand::Private {\n friend class ::Kleo::Commands::LookupCertificatesCommand;\n LookupCertificatesCommand * q_func() const { return static_cast( q ); }\npublic:\n explicit Private( LookupCertificatesCommand * qq, KeyListController * c );\n ~Private();\n\n void init();\n\nprivate:\n void slotSearchTextChanged( const QString & str );\n void slotNextKey( const Key & key ) {\n keyListing.keys.push_back( key );\n }\n void slotKeyListResult( const KeyListResult & result );\n void slotImportRequested( const std::vector & keys );\n void slotOpenPGPDownloadResult( const Error & err, const QByteArray & data );\n void slotCMSDownloadResult( const Error & err, const QByteArray & data );\n void slotDetailsRequested( const Key & key );\n void slotSaveAsRequested( const std::vector & keys );\n void slotDialogRejected() {\n canceled();\n }\n\nprivate:\n using ImportCertificatesCommand::Private::showError;\n void showError( QWidget * parent, const KeyListResult & result );\n void createDialog();\n KeyListJob * createKeyListJob( GpgME::Protocol proto ) const {\n const CryptoBackend::Protocol * const cbp = CryptoBackendFactory::instance()->protocol( proto );\n return cbp ? cbp->keyListJob( true ) : 0 ;\n }\n DownloadJob * createDownloadJob( GpgME::Protocol proto ) const {\n const CryptoBackend::Protocol * const cbp = CryptoBackendFactory::instance()->protocol( proto );\n return cbp ? cbp->downloadJob() : 0 ;\n }\n void startKeyListJob( GpgME::Protocol proto, const QString & str );\n void startDownloadJob( const Key & key );\n void checkForDownloadFinished();\n bool checkConfig() const;\n\n QWidget * dialogOrView() const { if ( dialog ) return dialog; else return view(); }\n\nprivate:\n QPointer dialog;\n struct KeyListingVariables {\n QPointer cms, openpgp;\n KeyListResult result;\n std::vector keys;\n\n void reset() { *this = KeyListingVariables(); }\n } keyListing;\n struct DownloadVariables {\n Key key;\n QPointer job;\n Error error;\n };\n std::vector downloads;\n QByteArray openPGPDownloadData, cmsDownloadData;\n};\n\n\nLookupCertificatesCommand::Private * LookupCertificatesCommand::d_func() { return static_cast( d.get() ); }\nconst LookupCertificatesCommand::Private * LookupCertificatesCommand::d_func() const { return static_cast( d.get() ); }\n\n#define d d_func()\n#define q q_func()\n\nLookupCertificatesCommand::Private::Private( LookupCertificatesCommand * qq, KeyListController * c )\n : ImportCertificatesCommand::Private( qq, c ),\n dialog()\n{\n\n}\n\nLookupCertificatesCommand::Private::~Private() {\n kDebug();\n delete dialog;\n}\n\nLookupCertificatesCommand::LookupCertificatesCommand( KeyListController * c )\n : ImportCertificatesCommand( new Private( this, c ) )\n{\n d->init();\n}\n\nLookupCertificatesCommand::LookupCertificatesCommand( QAbstractItemView * v, KeyListController * c )\n : ImportCertificatesCommand( v, new Private( this, c ) )\n{\n d->init();\n}\n\nvoid LookupCertificatesCommand::Private::init() {\n\n}\n\nLookupCertificatesCommand::~LookupCertificatesCommand() { kDebug(); }\n\n\nvoid LookupCertificatesCommand::doStart() {\n\n if ( !d->checkConfig() ) {\n d->finished();\n return;\n }\n\n d->createDialog();\n assert( d->dialog );\n\n d->dialog->setPassive( false );\n d->dialog->show();\n\n}\n\nvoid LookupCertificatesCommand::Private::createDialog() {\n if ( dialog )\n return;\n dialog = new LookupCertificatesDialog( view() );\n dialog->setAttribute( Qt::WA_DeleteOnClose );\n connect( dialog, SIGNAL(searchTextChanged(QString)),\n q, SLOT(slotSearchTextChanged(QString)) );\n connect( dialog, SIGNAL(saveAsRequested(std::vector)),\n q, SLOT(slotSaveAsRequested(std::vector)) );\n connect( dialog, SIGNAL(importRequested(std::vector)),\n q, SLOT(slotImportRequested(std::vector)) );\n connect( dialog, SIGNAL(detailsRequested(GpgME::Key)),\n q, SLOT(slotDetailsRequested(GpgME::Key)) );\n connect( dialog, SIGNAL(rejected()),\n q, SLOT(slotDialogRejected()) );\n}\n\nvoid LookupCertificatesCommand::Private::slotSearchTextChanged( const QString & str ) {\n dialog->setPassive( true );\n\n startKeyListJob( CMS, str );\n startKeyListJob( OpenPGP, str );\n\n}\n\nvoid LookupCertificatesCommand::Private::startKeyListJob( GpgME::Protocol proto, const QString & str ) {\n KeyListJob * const klj = createKeyListJob( proto );\n if ( !klj )\n return;\n connect( klj, SIGNAL(result(GpgME::KeyListResult)),\n q, SLOT(slotKeyListResult(GpgME::KeyListResult)) );\n connect( klj, SIGNAL(nextKey(GpgME::Key)),\n q, SLOT(slotNextKey(GpgME::Key)) );\n if ( const Error err = klj->start( QStringList( str ) ) )\n keyListing.result.mergeWith( KeyListResult( err ) );\n else\n if ( proto == CMS )\n keyListing.cms = klj;\n else\n keyListing.openpgp = klj;\n}\n\nvoid LookupCertificatesCommand::Private::slotKeyListResult( const KeyListResult & r ) {\n\n if ( q->sender() == keyListing.cms )\n keyListing.cms = 0;\n else if ( q->sender() == keyListing.openpgp )\n keyListing.openpgp = 0;\n else\n kDebug() << \"unknown sender()\" << q->sender();\n\n keyListing.result.mergeWith( r );\n if ( keyListing.cms || keyListing.openpgp ) \/\/ still waiting for jobs to complete\n return;\n\n if ( keyListing.result.error() && !keyListing.result.error().isCanceled() )\n showError( dialogOrView(), keyListing.result );\n\n if ( dialog ) {\n dialog->setCertificates( keyListing.keys );\n dialog->setPassive( false );\n } else {\n finished();\n }\n\n\n keyListing.reset();\n}\n\nvoid LookupCertificatesCommand::Private::slotImportRequested( const std::vector & keys ) {\n dialog = 0;\n\n assert( !keys.empty() );\n kdtools::for_each( keys, bind( &Private::startDownloadJob, this, _1 ) );\n}\n\nstatic shared_ptr make_open_qbuffer() {\n const shared_ptr buffer( new QBuffer );\n if ( !buffer->open( QIODevice::WriteOnly ) )\n kFatal() << \"QBuffer::open failed\";\n return buffer;\n}\n\nvoid LookupCertificatesCommand::Private::startDownloadJob( const Key & key ) {\n if ( key.isNull() )\n return;\n DownloadJob * const dlj = createDownloadJob( key.protocol() );\n if ( !dlj )\n return;\n connect( dlj, SIGNAL(result(GpgME::Error,QByteArray)),\n q, key.protocol() == CMS\n ? SLOT(slotCMSDownloadResult(GpgME::Error,QByteArray))\n : SLOT(slotOpenPGPDownloadResult(GpgME::Error,QByteArray)) );\n DownloadVariables var;\n var.key = key;\n if ( const Error err = dlj->start( QStringList( key.primaryFingerprint() ) ) )\n var.error = err;\n else\n var.job = dlj;\n downloads.push_back( var );\n}\n\nnamespace {\n template \n QStringList filter_and_format_successful_downloads( const T & t ) {\n QStringList result;\n \n return result;\n }\n\n template \n QByteArray combined_nonfailed_data( GpgME::Protocol proto, const T & t ) {\n QByteArray result;\n Q_FOREACH( const typename T::value_type & v, t )\n if ( !v.error.code() && v.data && v.key.protocol() == proto )\n result.append( v.data->data() );\n return result;\n }\n}\n\nvoid LookupCertificatesCommand::Private::slotOpenPGPDownloadResult( const GpgME::Error & err, const QByteArray & keyData ) {\n const std::vector::iterator it =\n std::find_if( downloads.begin(), downloads.end(),\n bind( &DownloadVariables::job, _1 ) == q->sender() );\n assert( it != downloads.end() );\n\n openPGPDownloadData.append( keyData );\n\n it->job = 0;\n it->error = err;\n\n checkForDownloadFinished();\n}\n\nvoid LookupCertificatesCommand::Private::slotCMSDownloadResult( const GpgME::Error & err, const QByteArray & keyData ) {\n const std::vector::iterator it =\n std::find_if( downloads.begin(), downloads.end(),\n bind( &DownloadVariables::job, _1 ) == q->sender() );\n assert( it != downloads.end() );\n\n cmsDownloadData.append( keyData );\n\n it->job = 0;\n it->error = err;\n\n checkForDownloadFinished();\n}\n\nvoid LookupCertificatesCommand::Private::checkForDownloadFinished() {\n\n if ( kdtools::any( downloads, mem_fn( &DownloadVariables::job ) ) )\n return; \/\/ still jobs to end\n\n if ( kdtools::all( downloads, mem_fn( &DownloadVariables::error ) ) ) {\n KMessageBox::information( dialogOrView(),\n downloads.size() == 1 ?\n i18n( \"Download of certificate %1 failed. Error message: %2\",\n Formatting::formatForComboBox( downloads.front().key ),\n QString::fromLocal8Bit( downloads.front().error.asString() ) ) :\n i18n( \"All certificate downloads failed. Sample error message: %1\",\n QString::fromLocal8Bit( downloads.front().error.asString() ) ),\n i18n( \"Certificate Downloads Failed\" ) );\n finished();\n return;\n } else if ( kdtools::any( downloads, mem_fn( &DownloadVariables::error ) ) &&\n KMessageBox::questionYesNoList( dialogOrView(),\n i18n( \"Some certificates failed to download. \"\n \"Do you want to proceed importing the following, succeded, downloads?\" ),\n filter_and_format_successful_downloads( downloads ),\n i18n( \"Certificate Downloads Failed\" ) )\n == KMessageBox::No )\n {\n finished();\n return;\n }\n\n const QByteArray cms = cmsDownloadData;\/\/combined_nonfailed_data( CMS, downloads );\n const QByteArray pgp = openPGPDownloadData;\/\/combined_nonfailed_data( OpenPGP, downloads );\n\n if ( !cms.isEmpty() )\n startImport( CMS, cms );\n if ( !pgp.isEmpty() )\n startImport( OpenPGP, pgp );\n}\n\nvoid LookupCertificatesCommand::Private::slotSaveAsRequested( const std::vector & keys ) {\n kDebug() << \"not implemented\";\n}\n\nvoid LookupCertificatesCommand::Private::slotDetailsRequested( const Key & key ) {\n ( new DetailsCommand( key, view(), controller() ) )->start();\n}\n\nvoid LookupCertificatesCommand::doCancel() {\n ImportCertificatesCommand::doCancel();\n if ( QDialog * const dlg = d->dialog ) {\n d->dialog = 0;\n dlg->close();\n }\n}\n\nvoid LookupCertificatesCommand::Private::showError( QWidget * parent, const KeyListResult & result ) {\n if ( !result.error() )\n return;\n KMessageBox::information( parent, i18n( \"Failed to search on keyserver. The error returned was:\\n%1\",\n QString::fromLocal8Bit( result.error().asString() ) ) );\n}\n\nstatic bool haveOpenPGPKeyserverConfigured() {\n const Kleo::CryptoConfig * const config = Kleo::CryptoBackendFactory::instance()->config();\n if ( !config )\n return false;\n const Kleo::CryptoConfigEntry * const entry = config->entry( \"gpg\", \"Keyserver\", \"keyserver\" );\n return entry && !entry->stringValue().isEmpty();\n}\n\n\nstatic bool haveX509DirectoryServerConfigured() {\n const Kleo::CryptoConfig * const config = Kleo::CryptoBackendFactory::instance()->config();\n if ( !config )\n return false;\n const Kleo::CryptoConfigEntry * const entry = config->entry( \"dirmngr\", \"LDAP\", \"LDAP Server\" );\n return entry && !entry->urlValueList().empty();\n}\n\n\nbool LookupCertificatesCommand::Private::checkConfig() const {\n const bool ok = haveOpenPGPKeyserverConfigured() || haveX509DirectoryServerConfigured();\n if ( !ok )\n KMessageBox::information( view(), i18nc(\"@info\",\n \"You do not have any directory servers configured.<\/para>\"\n \"You need to configure at least one directory server to \"\n \"search on one.<\/para>\"\n \"You can configure directory servers here: \"\n \"Settings->Configure Kleopatra<\/interface>.<\/para>\"),\n i18nc(\"@title\", \"No Directory Servers Configured\") );\n return ok;\n}\n\n#undef d\n#undef q\n\n#include \"moc_lookupcertificatescommand.cpp\"\nClear the list in the dialog when starting search.\/* -*- mode: c++; c-basic-offset:4 -*-\n commands\/lookupcertificatescommand.cpp\n\n This file is part of Kleopatra, the KDE keymanager\n Copyright (c) 2008 Klarälvdalens Datakonsult AB\n\n Kleopatra is free software; you can redistribute it and\/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation; either version 2 of the License, or\n (at your option) any later version.\n\n Kleopatra is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with this program; if not, write to the Free Software\n Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n In addition, as a special exception, the copyright holders give\n permission to link the code of this program with any edition of\n the Qt library by Trolltech AS, Norway (or with modified versions\n of Qt that use the same license as Qt), and distribute linked\n combinations including the two. You must obey the GNU General\n Public License in all respects for all of the code used other than\n Qt. If you modify this file, you may extend this exception to\n your version of the file, but you are not obligated to do so. If\n you do not wish to do so, delete this exception statement from\n your version.\n*\/\n\n#include \n\n#include \"lookupcertificatescommand.h\"\n\n#include \"importcertificatescommand_p.h\"\n\n#include \"detailscommand.h\"\n\n#include \n\n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n\n#include \n#include \n#include \n\n#include \n\n#include \n#include \n\n#include \n#include \n#include \n#include \n\nusing namespace Kleo;\nusing namespace Kleo::Commands;\nusing namespace Kleo::Dialogs;\nusing namespace GpgME;\nusing namespace boost;\n\nclass LookupCertificatesCommand::Private : public ImportCertificatesCommand::Private {\n friend class ::Kleo::Commands::LookupCertificatesCommand;\n LookupCertificatesCommand * q_func() const { return static_cast( q ); }\npublic:\n explicit Private( LookupCertificatesCommand * qq, KeyListController * c );\n ~Private();\n\n void init();\n\nprivate:\n void slotSearchTextChanged( const QString & str );\n void slotNextKey( const Key & key ) {\n keyListing.keys.push_back( key );\n }\n void slotKeyListResult( const KeyListResult & result );\n void slotImportRequested( const std::vector & keys );\n void slotOpenPGPDownloadResult( const Error & err, const QByteArray & data );\n void slotCMSDownloadResult( const Error & err, const QByteArray & data );\n void slotDetailsRequested( const Key & key );\n void slotSaveAsRequested( const std::vector & keys );\n void slotDialogRejected() {\n canceled();\n }\n\nprivate:\n using ImportCertificatesCommand::Private::showError;\n void showError( QWidget * parent, const KeyListResult & result );\n void createDialog();\n KeyListJob * createKeyListJob( GpgME::Protocol proto ) const {\n const CryptoBackend::Protocol * const cbp = CryptoBackendFactory::instance()->protocol( proto );\n return cbp ? cbp->keyListJob( true ) : 0 ;\n }\n DownloadJob * createDownloadJob( GpgME::Protocol proto ) const {\n const CryptoBackend::Protocol * const cbp = CryptoBackendFactory::instance()->protocol( proto );\n return cbp ? cbp->downloadJob() : 0 ;\n }\n void startKeyListJob( GpgME::Protocol proto, const QString & str );\n void startDownloadJob( const Key & key );\n void checkForDownloadFinished();\n bool checkConfig() const;\n\n QWidget * dialogOrView() const { if ( dialog ) return dialog; else return view(); }\n\nprivate:\n QPointer dialog;\n struct KeyListingVariables {\n QPointer cms, openpgp;\n KeyListResult result;\n std::vector keys;\n\n void reset() { *this = KeyListingVariables(); }\n } keyListing;\n struct DownloadVariables {\n Key key;\n QPointer job;\n Error error;\n };\n std::vector downloads;\n QByteArray openPGPDownloadData, cmsDownloadData;\n};\n\n\nLookupCertificatesCommand::Private * LookupCertificatesCommand::d_func() { return static_cast( d.get() ); }\nconst LookupCertificatesCommand::Private * LookupCertificatesCommand::d_func() const { return static_cast( d.get() ); }\n\n#define d d_func()\n#define q q_func()\n\nLookupCertificatesCommand::Private::Private( LookupCertificatesCommand * qq, KeyListController * c )\n : ImportCertificatesCommand::Private( qq, c ),\n dialog()\n{\n\n}\n\nLookupCertificatesCommand::Private::~Private() {\n kDebug();\n delete dialog;\n}\n\nLookupCertificatesCommand::LookupCertificatesCommand( KeyListController * c )\n : ImportCertificatesCommand( new Private( this, c ) )\n{\n d->init();\n}\n\nLookupCertificatesCommand::LookupCertificatesCommand( QAbstractItemView * v, KeyListController * c )\n : ImportCertificatesCommand( v, new Private( this, c ) )\n{\n d->init();\n}\n\nvoid LookupCertificatesCommand::Private::init() {\n\n}\n\nLookupCertificatesCommand::~LookupCertificatesCommand() { kDebug(); }\n\n\nvoid LookupCertificatesCommand::doStart() {\n\n if ( !d->checkConfig() ) {\n d->finished();\n return;\n }\n\n d->createDialog();\n assert( d->dialog );\n\n d->dialog->setPassive( false );\n d->dialog->show();\n\n}\n\nvoid LookupCertificatesCommand::Private::createDialog() {\n if ( dialog )\n return;\n dialog = new LookupCertificatesDialog( view() );\n dialog->setAttribute( Qt::WA_DeleteOnClose );\n connect( dialog, SIGNAL(searchTextChanged(QString)),\n q, SLOT(slotSearchTextChanged(QString)) );\n connect( dialog, SIGNAL(saveAsRequested(std::vector)),\n q, SLOT(slotSaveAsRequested(std::vector)) );\n connect( dialog, SIGNAL(importRequested(std::vector)),\n q, SLOT(slotImportRequested(std::vector)) );\n connect( dialog, SIGNAL(detailsRequested(GpgME::Key)),\n q, SLOT(slotDetailsRequested(GpgME::Key)) );\n connect( dialog, SIGNAL(rejected()),\n q, SLOT(slotDialogRejected()) );\n}\n\nvoid LookupCertificatesCommand::Private::slotSearchTextChanged( const QString & str ) {\n dialog->setPassive( true );\n dialog->setCertificates( std::vector() );\n\n startKeyListJob( CMS, str );\n startKeyListJob( OpenPGP, str );\n\n}\n\nvoid LookupCertificatesCommand::Private::startKeyListJob( GpgME::Protocol proto, const QString & str ) {\n KeyListJob * const klj = createKeyListJob( proto );\n if ( !klj )\n return;\n connect( klj, SIGNAL(result(GpgME::KeyListResult)),\n q, SLOT(slotKeyListResult(GpgME::KeyListResult)) );\n connect( klj, SIGNAL(nextKey(GpgME::Key)),\n q, SLOT(slotNextKey(GpgME::Key)) );\n if ( const Error err = klj->start( QStringList( str ) ) )\n keyListing.result.mergeWith( KeyListResult( err ) );\n else\n if ( proto == CMS )\n keyListing.cms = klj;\n else\n keyListing.openpgp = klj;\n}\n\nvoid LookupCertificatesCommand::Private::slotKeyListResult( const KeyListResult & r ) {\n\n if ( q->sender() == keyListing.cms )\n keyListing.cms = 0;\n else if ( q->sender() == keyListing.openpgp )\n keyListing.openpgp = 0;\n else\n kDebug() << \"unknown sender()\" << q->sender();\n\n keyListing.result.mergeWith( r );\n if ( keyListing.cms || keyListing.openpgp ) \/\/ still waiting for jobs to complete\n return;\n\n if ( keyListing.result.error() && !keyListing.result.error().isCanceled() )\n showError( dialogOrView(), keyListing.result );\n\n if ( dialog ) {\n dialog->setCertificates( keyListing.keys );\n dialog->setPassive( false );\n } else {\n finished();\n }\n\n\n keyListing.reset();\n}\n\nvoid LookupCertificatesCommand::Private::slotImportRequested( const std::vector & keys ) {\n dialog = 0;\n\n assert( !keys.empty() );\n kdtools::for_each( keys, bind( &Private::startDownloadJob, this, _1 ) );\n}\n\nstatic shared_ptr make_open_qbuffer() {\n const shared_ptr buffer( new QBuffer );\n if ( !buffer->open( QIODevice::WriteOnly ) )\n kFatal() << \"QBuffer::open failed\";\n return buffer;\n}\n\nvoid LookupCertificatesCommand::Private::startDownloadJob( const Key & key ) {\n if ( key.isNull() )\n return;\n DownloadJob * const dlj = createDownloadJob( key.protocol() );\n if ( !dlj )\n return;\n connect( dlj, SIGNAL(result(GpgME::Error,QByteArray)),\n q, key.protocol() == CMS\n ? SLOT(slotCMSDownloadResult(GpgME::Error,QByteArray))\n : SLOT(slotOpenPGPDownloadResult(GpgME::Error,QByteArray)) );\n DownloadVariables var;\n var.key = key;\n if ( const Error err = dlj->start( QStringList( key.primaryFingerprint() ) ) )\n var.error = err;\n else\n var.job = dlj;\n downloads.push_back( var );\n}\n\nnamespace {\n template \n QStringList filter_and_format_successful_downloads( const T & t ) {\n QStringList result;\n \n return result;\n }\n\n template \n QByteArray combined_nonfailed_data( GpgME::Protocol proto, const T & t ) {\n QByteArray result;\n Q_FOREACH( const typename T::value_type & v, t )\n if ( !v.error.code() && v.data && v.key.protocol() == proto )\n result.append( v.data->data() );\n return result;\n }\n}\n\nvoid LookupCertificatesCommand::Private::slotOpenPGPDownloadResult( const GpgME::Error & err, const QByteArray & keyData ) {\n const std::vector::iterator it =\n std::find_if( downloads.begin(), downloads.end(),\n bind( &DownloadVariables::job, _1 ) == q->sender() );\n assert( it != downloads.end() );\n\n openPGPDownloadData.append( keyData );\n\n it->job = 0;\n it->error = err;\n\n checkForDownloadFinished();\n}\n\nvoid LookupCertificatesCommand::Private::slotCMSDownloadResult( const GpgME::Error & err, const QByteArray & keyData ) {\n const std::vector::iterator it =\n std::find_if( downloads.begin(), downloads.end(),\n bind( &DownloadVariables::job, _1 ) == q->sender() );\n assert( it != downloads.end() );\n\n cmsDownloadData.append( keyData );\n\n it->job = 0;\n it->error = err;\n\n checkForDownloadFinished();\n}\n\nvoid LookupCertificatesCommand::Private::checkForDownloadFinished() {\n\n if ( kdtools::any( downloads, mem_fn( &DownloadVariables::job ) ) )\n return; \/\/ still jobs to end\n\n if ( kdtools::all( downloads, mem_fn( &DownloadVariables::error ) ) ) {\n KMessageBox::information( dialogOrView(),\n downloads.size() == 1 ?\n i18n( \"Download of certificate %1 failed. Error message: %2\",\n Formatting::formatForComboBox( downloads.front().key ),\n QString::fromLocal8Bit( downloads.front().error.asString() ) ) :\n i18n( \"All certificate downloads failed. Sample error message: %1\",\n QString::fromLocal8Bit( downloads.front().error.asString() ) ),\n i18n( \"Certificate Downloads Failed\" ) );\n finished();\n return;\n } else if ( kdtools::any( downloads, mem_fn( &DownloadVariables::error ) ) &&\n KMessageBox::questionYesNoList( dialogOrView(),\n i18n( \"Some certificates failed to download. \"\n \"Do you want to proceed importing the following, succeded, downloads?\" ),\n filter_and_format_successful_downloads( downloads ),\n i18n( \"Certificate Downloads Failed\" ) )\n == KMessageBox::No )\n {\n finished();\n return;\n }\n\n const QByteArray cms = cmsDownloadData;\/\/combined_nonfailed_data( CMS, downloads );\n const QByteArray pgp = openPGPDownloadData;\/\/combined_nonfailed_data( OpenPGP, downloads );\n\n if ( !cms.isEmpty() )\n startImport( CMS, cms );\n if ( !pgp.isEmpty() )\n startImport( OpenPGP, pgp );\n}\n\nvoid LookupCertificatesCommand::Private::slotSaveAsRequested( const std::vector & keys ) {\n kDebug() << \"not implemented\";\n}\n\nvoid LookupCertificatesCommand::Private::slotDetailsRequested( const Key & key ) {\n ( new DetailsCommand( key, view(), controller() ) )->start();\n}\n\nvoid LookupCertificatesCommand::doCancel() {\n ImportCertificatesCommand::doCancel();\n if ( QDialog * const dlg = d->dialog ) {\n d->dialog = 0;\n dlg->close();\n }\n}\n\nvoid LookupCertificatesCommand::Private::showError( QWidget * parent, const KeyListResult & result ) {\n if ( !result.error() )\n return;\n KMessageBox::information( parent, i18n( \"Failed to search on keyserver. The error returned was:\\n%1\",\n QString::fromLocal8Bit( result.error().asString() ) ) );\n}\n\nstatic bool haveOpenPGPKeyserverConfigured() {\n const Kleo::CryptoConfig * const config = Kleo::CryptoBackendFactory::instance()->config();\n if ( !config )\n return false;\n const Kleo::CryptoConfigEntry * const entry = config->entry( \"gpg\", \"Keyserver\", \"keyserver\" );\n return entry && !entry->stringValue().isEmpty();\n}\n\n\nstatic bool haveX509DirectoryServerConfigured() {\n const Kleo::CryptoConfig * const config = Kleo::CryptoBackendFactory::instance()->config();\n if ( !config )\n return false;\n const Kleo::CryptoConfigEntry * const entry = config->entry( \"dirmngr\", \"LDAP\", \"LDAP Server\" );\n return entry && !entry->urlValueList().empty();\n}\n\n\nbool LookupCertificatesCommand::Private::checkConfig() const {\n const bool ok = haveOpenPGPKeyserverConfigured() || haveX509DirectoryServerConfigured();\n if ( !ok )\n KMessageBox::information( view(), i18nc(\"@info\",\n \"You do not have any directory servers configured.<\/para>\"\n \"You need to configure at least one directory server to \"\n \"search on one.<\/para>\"\n \"You can configure directory servers here: \"\n \"Settings->Configure Kleopatra<\/interface>.<\/para>\"),\n i18nc(\"@title\", \"No Directory Servers Configured\") );\n return ok;\n}\n\n#undef d\n#undef q\n\n#include \"moc_lookupcertificatescommand.cpp\"\n<|endoftext|>"} {"text":"#include \"intfunction.h\"\n#include \"exprcalc.cpp\"\n#include \n\nconst size_t MAX_SIZE = 1000;\n\nvoid IntFunction::copy(const IntFunction& other)\n{\n name = other.name;\n param = other.param;\n\n expr = new char[strlen(other.expr) + 1];\n strcpy(expr, other.expr);\n}\n\nvoid IntFunction::destroy()\n{\n delete[] expr;\n}\n\nbool IntFunction::parse(const char* dfn)\n{\n \/\/ първо извличаме името (латинска буква)\n const char* i = find_token(dfn);\n if (!i || !is_alpha(*i))\n return false;\n name = *i;\n\n \/\/ после извличаме '('\n i = find_token(i);\n if (!i || *i != '(')\n return false;\n\n \/\/ след това извличаме името на аргумента\n i = find_token(i);\n if (!i || !is_alpha(*i))\n return false;\n param = *i;\n\n \/\/ после извличаме ')'\n i = find_token(i);\n if (!i || *i != ')')\n return false;\n\n \/\/ след това извличаме '='\n i = find_token(i);\n if (!i || *i != '=')\n return false;\n\n \/\/ и накрая копираме израза в полето expr\n i = find_token(i);\n expr = new char[strlen(i) + 1];\n strcpy(expr, i);\n return true;\n}\n\nIntFunction::IntFunction(std::istream& in)\n{\n char strin[MAX_SIZE];\n in.getline(strin, MAX_SIZE);\n parse(strin);\n}\n\nIntFunction::IntFunction(const char* dfn)\n{\n parse(dfn);\n}\n\nIntFunction::IntFunction(const std::string& s)\n{\n parse(s.c_str());\n}\n\nIntFunction::IntFunction(const IntFunction& other)\n{\n copy(other);\n}\n\nIntFunction& IntFunction::operator=(const IntFunction& other)\n{\n if (&other != this)\n {\n destroy();\n copy(other);\n }\n\n return *this;\n}\n\nIntFunction::~IntFunction()\n{\n destroy();\n}\n\nint IntFunction::calculate(int arg) const\n{\n strsubst(expr, param, arg);\n return calculate_expr(expr);\n}\nfixed exprcalc include: source file (.cpp) was included instead of header (.h) file#include \"intfunction.h\"\n#include \"exprcalc.h\"\n#include \n\nconst size_t MAX_SIZE = 1000;\n\nvoid IntFunction::copy(const IntFunction& other)\n{\n name = other.name;\n param = other.param;\n\n expr = new char[strlen(other.expr) + 1];\n strcpy(expr, other.expr);\n}\n\nvoid IntFunction::destroy()\n{\n delete[] expr;\n}\n\nbool IntFunction::parse(const char* dfn)\n{\n \/\/ първо извличаме името (латинска буква)\n const char* i = find_token(dfn);\n if (!i || !is_alpha(*i))\n return false;\n name = *i;\n\n \/\/ после извличаме '('\n i = find_token(i);\n if (!i || *i != '(')\n return false;\n\n \/\/ след това извличаме името на аргумента\n i = find_token(i);\n if (!i || !is_alpha(*i))\n return false;\n param = *i;\n\n \/\/ после извличаме ')'\n i = find_token(i);\n if (!i || *i != ')')\n return false;\n\n \/\/ след това извличаме '='\n i = find_token(i);\n if (!i || *i != '=')\n return false;\n\n \/\/ и накрая копираме израза в полето expr\n i = find_token(i);\n expr = new char[strlen(i) + 1];\n strcpy(expr, i);\n return true;\n}\n\nIntFunction::IntFunction(std::istream& in)\n{\n char strin[MAX_SIZE];\n in.getline(strin, MAX_SIZE);\n parse(strin);\n}\n\nIntFunction::IntFunction(const char* dfn)\n{\n parse(dfn);\n}\n\nIntFunction::IntFunction(const std::string& s)\n{\n parse(s.c_str());\n}\n\nIntFunction::IntFunction(const IntFunction& other)\n{\n copy(other);\n}\n\nIntFunction& IntFunction::operator=(const IntFunction& other)\n{\n if (&other != this)\n {\n destroy();\n copy(other);\n }\n\n return *this;\n}\n\nIntFunction::~IntFunction()\n{\n destroy();\n}\n\nint IntFunction::calculate(int arg) const\n{\n strsubst(expr, param, arg);\n return calculate_expr(expr);\n}\n<|endoftext|>"} {"text":"#pragma once\n\n#include \"apple_hid_usage_tables.hpp\"\n#include \"console_user_client.hpp\"\n#include \"constants.hpp\"\n#include \"hid_report.hpp\"\n#include \"human_interface_device.hpp\"\n#include \"iokit_user_client.hpp\"\n#include \"iokit_utility.hpp\"\n#include \"logger.hpp\"\n#include \"modifier_flag_manager.hpp\"\n#include \"userspace_defs.h\"\n#include \"virtual_hid_manager_user_client_method.hpp\"\n\nclass event_grabber final {\npublic:\n event_grabber(void) : iokit_user_client_(logger::get_logger(), \"org_pqrs_driver_VirtualHIDManager\", kIOHIDServerConnectType),\n console_user_client_(modifier_flag_manager_) {\n manager_ = IOHIDManagerCreate(kCFAllocatorDefault, kIOHIDOptionsTypeNone);\n if (!manager_) {\n return;\n }\n\n auto device_matching_dictionaries = iokit_utility::create_device_matching_dictionaries({\n std::make_pair(kHIDPage_GenericDesktop, kHIDUsage_GD_Keyboard),\n \/\/ std::make_pair(kHIDPage_Consumer, kHIDUsage_Csmr_ConsumerControl),\n \/\/ std::make_pair(kHIDPage_GenericDesktop, kHIDUsage_GD_Mouse),\n });\n if (device_matching_dictionaries) {\n IOHIDManagerSetDeviceMatchingMultiple(manager_, device_matching_dictionaries);\n CFRelease(device_matching_dictionaries);\n\n IOHIDManagerRegisterDeviceMatchingCallback(manager_, static_device_matching_callback, this);\n IOHIDManagerRegisterDeviceRemovalCallback(manager_, static_device_removal_callback, this);\n\n IOHIDManagerScheduleWithRunLoop(manager_, CFRunLoopGetCurrent(), kCFRunLoopDefaultMode);\n }\n }\n\n ~event_grabber(void) {\n if (manager_) {\n IOHIDManagerUnscheduleFromRunLoop(manager_, CFRunLoopGetCurrent(), kCFRunLoopDefaultMode);\n CFRelease(manager_);\n manager_ = nullptr;\n }\n }\n\nprivate:\n static void static_device_matching_callback(void* _Nullable context, IOReturn result, void* _Nullable sender, IOHIDDeviceRef _Nonnull device) {\n if (result != kIOReturnSuccess) {\n return;\n }\n\n auto self = static_cast(context);\n if (!self) {\n return;\n }\n\n self->device_matching_callback(device);\n }\n\n void device_matching_callback(IOHIDDeviceRef _Nonnull device) {\n if (!device) {\n return;\n }\n\n hids_[device] = std::make_unique(device);\n auto& dev = hids_[device];\n\n std::cout << \"matching: \" << std::endl\n << \" vendor_id:0x\" << std::hex << dev->get_vendor_id() << std::endl\n << \" product_id:0x\" << std::hex << dev->get_product_id() << std::endl\n << \" location_id:0x\" << std::hex << dev->get_location_id() << std::endl\n << \" serial_number:\" << dev->get_serial_number_string() << std::endl\n << \" manufacturer:\" << dev->get_manufacturer() << std::endl\n << \" product:\" << dev->get_product() << std::endl\n << \" transport:\" << dev->get_transport() << std::endl;\n\n if (dev->get_serial_number_string() == \"org.pqrs.driver.VirtualHIDKeyboard\") {\n return;\n }\n\n if (dev->get_manufacturer() != \"pqrs.org\") {\n if (dev->get_manufacturer() == \"Apple Inc.\") {\n dev->grab(boost::bind(&event_grabber::value_callback, this, _1, _2, _3, _4, _5));\n }\n }\n }\n\n static void static_device_removal_callback(void* _Nullable context, IOReturn result, void* _Nullable sender, IOHIDDeviceRef _Nonnull device) {\n if (result != kIOReturnSuccess) {\n return;\n }\n\n auto self = static_cast(context);\n if (!self) {\n return;\n }\n\n self->device_removal_callback(device);\n }\n\n void device_removal_callback(IOHIDDeviceRef _Nonnull device) {\n if (!device) {\n return;\n }\n\n auto it = hids_.find(device);\n if (it != hids_.end()) {\n auto& dev = it->second;\n if (dev) {\n std::cout << \"removal vendor_id:0x\" << std::hex << dev->get_vendor_id() << \" product_id:0x\" << std::hex << dev->get_product_id() << std::endl;\n hids_.erase(it);\n }\n }\n }\n\n void value_callback(IOHIDValueRef _Nonnull value,\n IOHIDElementRef _Nonnull element,\n uint32_t usage_page,\n uint32_t usage,\n CFIndex integer_value) {\n\n std::cout << \"element\" << std::endl\n << \" usage_page:0x\" << std::hex << usage_page << std::endl\n << \" usage:0x\" << std::hex << usage << std::endl\n << \" type:\" << IOHIDElementGetType(element) << std::endl\n << \" length:\" << IOHIDValueGetLength(value) << std::endl\n << \" integer_value:\" << integer_value << std::endl;\n\n switch (usage_page) {\n case kHIDPage_KeyboardOrKeypad: {\n bool pressed = integer_value;\n handle_keyboard_event(usage_page, usage, pressed);\n break;\n }\n\n case kHIDPage_AppleVendorTopCase:\n if (usage == kHIDUsage_AV_TopCase_KeyboardFn) {\n bool pressed = integer_value;\n handle_keyboard_event(usage_page, usage, pressed);\n }\n break;\n\n default:\n break;\n }\n }\n\n bool handle_modifier_flag_event(uint32_t usage_page, uint32_t usage, bool pressed) {\n auto operation = pressed ? modifier_flag_manager::operation::increase : modifier_flag_manager::operation::decrease;\n\n switch (usage_page) {\n case kHIDPage_KeyboardOrKeypad: {\n auto key = modifier_flag_manager::physical_keys::end_;\n\n switch (usage) {\n case kHIDUsage_KeyboardLeftControl:\n key = modifier_flag_manager::physical_keys::left_control;\n break;\n case kHIDUsage_KeyboardLeftShift:\n key = modifier_flag_manager::physical_keys::left_shift;\n break;\n case kHIDUsage_KeyboardLeftAlt:\n key = modifier_flag_manager::physical_keys::left_option;\n break;\n case kHIDUsage_KeyboardLeftGUI:\n key = modifier_flag_manager::physical_keys::left_command;\n break;\n case kHIDUsage_KeyboardRightControl:\n key = modifier_flag_manager::physical_keys::right_control;\n break;\n case kHIDUsage_KeyboardRightShift:\n key = modifier_flag_manager::physical_keys::right_shift;\n break;\n case kHIDUsage_KeyboardRightAlt:\n key = modifier_flag_manager::physical_keys::right_option;\n break;\n case kHIDUsage_KeyboardRightGUI:\n key = modifier_flag_manager::physical_keys::right_command;\n break;\n }\n\n if (key != modifier_flag_manager::physical_keys::end_) {\n modifier_flag_manager_.manipulate(key, operation);\n send_keyboard_input_report();\n return true;\n }\n break;\n }\n\n case kHIDPage_AppleVendorTopCase:\n if (usage == kHIDUsage_AV_TopCase_KeyboardFn) {\n modifier_flag_manager_.manipulate(modifier_flag_manager::physical_keys::fn, operation);\n console_user_client_.post_modifier_flags();\n return true;\n }\n break;\n }\n\n return false;\n }\n\n bool handle_function_key_event(uint32_t usage_page, uint32_t usage, bool pressed) {\n if (usage_page != kHIDPage_KeyboardOrKeypad) {\n return false;\n }\n\n auto event_type = pressed ? KRBN_EVENT_TYPE_KEY_DOWN : KRBN_EVENT_TYPE_KEY_UP;\n\n#define POST_KEY(KEY) \\\n case kHIDUsage_Keyboard##KEY: \\\n console_user_client_.post_key(KRBN_KEY_CODE_##KEY, event_type); \\\n return true;\n\n switch (usage) {\n POST_KEY(F1);\n POST_KEY(F2);\n POST_KEY(F3);\n POST_KEY(F4);\n POST_KEY(F5);\n POST_KEY(F6);\n POST_KEY(F7);\n POST_KEY(F8);\n POST_KEY(F9);\n POST_KEY(F10);\n POST_KEY(F11);\n POST_KEY(F12);\n }\n\n return false;\n }\n\n void handle_keyboard_event(uint32_t usage_page, uint32_t usage, bool pressed) {\n \/\/ ----------------------------------------\n \/\/ modify usage\n if (usage == kHIDUsage_KeyboardCapsLock) {\n usage = kHIDUsage_KeyboardDeleteOrBackspace;\n }\n\n if (modifier_flag_manager_.pressed(modifier_flag_manager::physical_keys::fn)) {\n switch (usage) {\n case kHIDUsage_KeyboardReturnOrEnter:\n usage = kHIDUsage_KeypadEnter;\n break;\n case kHIDUsage_KeyboardDeleteOrBackspace:\n usage = kHIDUsage_KeyboardDeleteForward;\n break;\n case kHIDUsage_KeyboardRightArrow:\n usage = kHIDUsage_KeyboardEnd;\n break;\n case kHIDUsage_KeyboardLeftArrow:\n usage = kHIDUsage_KeyboardHome;\n break;\n case kHIDUsage_KeyboardDownArrow:\n usage = kHIDUsage_KeyboardPageDown;\n break;\n case kHIDUsage_KeyboardUpArrow:\n usage = kHIDUsage_KeyboardPageUp;\n break;\n }\n }\n\n \/\/ ----------------------------------------\n if (handle_modifier_flag_event(usage_page, usage, pressed)) {\n console_user_client_.stop_key_repeat();\n return;\n }\n if (handle_function_key_event(usage_page, usage, pressed)) {\n return;\n }\n\n if (pressed) {\n pressed_key_usages_.push_back(usage);\n console_user_client_.stop_key_repeat();\n } else {\n pressed_key_usages_.remove(usage);\n }\n\n send_keyboard_input_report();\n }\n\n void send_keyboard_input_report(void) {\n \/\/ make report\n hid_report::keyboard_input report;\n report.modifiers = modifier_flag_manager_.get_hid_report_bits();\n\n while (pressed_key_usages_.size() > sizeof(report.keys)) {\n pressed_key_usages_.pop_front();\n }\n\n int i = 0;\n for (const auto& u : pressed_key_usages_) {\n report.keys[i] = u;\n ++i;\n }\n\n \/\/ send new report only if it is changed from last report.\n if (last_keyboard_input_report_ != report) {\n last_keyboard_input_report_ = report;\n\n auto kr = iokit_user_client_.call_struct_method(static_cast(virtual_hid_manager_user_client_method::keyboard_input_report),\n static_cast(&report), sizeof(report),\n nullptr, 0);\n if (kr != KERN_SUCCESS) {\n logger::get_logger().error(\"failed to sent report: 0x{0:x}\", kr);\n }\n }\n }\n\n iokit_user_client iokit_user_client_;\n IOHIDManagerRef _Nullable manager_;\n std::unordered_map> hids_;\n std::list pressed_key_usages_;\n\n modifier_flag_manager modifier_flag_manager_;\n hid_report::keyboard_input last_keyboard_input_report_;\n\n console_user_client console_user_client_;\n};\nadd fn_changed_keys_#pragma once\n\n#include \"apple_hid_usage_tables.hpp\"\n#include \"console_user_client.hpp\"\n#include \"constants.hpp\"\n#include \"hid_report.hpp\"\n#include \"human_interface_device.hpp\"\n#include \"iokit_user_client.hpp\"\n#include \"iokit_utility.hpp\"\n#include \"logger.hpp\"\n#include \"modifier_flag_manager.hpp\"\n#include \"userspace_defs.h\"\n#include \"virtual_hid_manager_user_client_method.hpp\"\n\nclass event_grabber final {\npublic:\n event_grabber(void) : iokit_user_client_(logger::get_logger(), \"org_pqrs_driver_VirtualHIDManager\", kIOHIDServerConnectType),\n console_user_client_(modifier_flag_manager_) {\n manager_ = IOHIDManagerCreate(kCFAllocatorDefault, kIOHIDOptionsTypeNone);\n if (!manager_) {\n return;\n }\n\n auto device_matching_dictionaries = iokit_utility::create_device_matching_dictionaries({\n std::make_pair(kHIDPage_GenericDesktop, kHIDUsage_GD_Keyboard),\n \/\/ std::make_pair(kHIDPage_Consumer, kHIDUsage_Csmr_ConsumerControl),\n \/\/ std::make_pair(kHIDPage_GenericDesktop, kHIDUsage_GD_Mouse),\n });\n if (device_matching_dictionaries) {\n IOHIDManagerSetDeviceMatchingMultiple(manager_, device_matching_dictionaries);\n CFRelease(device_matching_dictionaries);\n\n IOHIDManagerRegisterDeviceMatchingCallback(manager_, static_device_matching_callback, this);\n IOHIDManagerRegisterDeviceRemovalCallback(manager_, static_device_removal_callback, this);\n\n IOHIDManagerScheduleWithRunLoop(manager_, CFRunLoopGetCurrent(), kCFRunLoopDefaultMode);\n }\n }\n\n ~event_grabber(void) {\n if (manager_) {\n IOHIDManagerUnscheduleFromRunLoop(manager_, CFRunLoopGetCurrent(), kCFRunLoopDefaultMode);\n CFRelease(manager_);\n manager_ = nullptr;\n }\n }\n\nprivate:\n static void static_device_matching_callback(void* _Nullable context, IOReturn result, void* _Nullable sender, IOHIDDeviceRef _Nonnull device) {\n if (result != kIOReturnSuccess) {\n return;\n }\n\n auto self = static_cast(context);\n if (!self) {\n return;\n }\n\n self->device_matching_callback(device);\n }\n\n void device_matching_callback(IOHIDDeviceRef _Nonnull device) {\n if (!device) {\n return;\n }\n\n hids_[device] = std::make_unique(device);\n auto& dev = hids_[device];\n\n std::cout << \"matching: \" << std::endl\n << \" vendor_id:0x\" << std::hex << dev->get_vendor_id() << std::endl\n << \" product_id:0x\" << std::hex << dev->get_product_id() << std::endl\n << \" location_id:0x\" << std::hex << dev->get_location_id() << std::endl\n << \" serial_number:\" << dev->get_serial_number_string() << std::endl\n << \" manufacturer:\" << dev->get_manufacturer() << std::endl\n << \" product:\" << dev->get_product() << std::endl\n << \" transport:\" << dev->get_transport() << std::endl;\n\n if (dev->get_serial_number_string() == \"org.pqrs.driver.VirtualHIDKeyboard\") {\n return;\n }\n\n if (dev->get_manufacturer() != \"pqrs.org\") {\n if (dev->get_manufacturer() == \"Apple Inc.\") {\n dev->grab(boost::bind(&event_grabber::value_callback, this, _1, _2, _3, _4, _5));\n }\n }\n }\n\n static void static_device_removal_callback(void* _Nullable context, IOReturn result, void* _Nullable sender, IOHIDDeviceRef _Nonnull device) {\n if (result != kIOReturnSuccess) {\n return;\n }\n\n auto self = static_cast(context);\n if (!self) {\n return;\n }\n\n self->device_removal_callback(device);\n }\n\n void device_removal_callback(IOHIDDeviceRef _Nonnull device) {\n if (!device) {\n return;\n }\n\n auto it = hids_.find(device);\n if (it != hids_.end()) {\n auto& dev = it->second;\n if (dev) {\n std::cout << \"removal vendor_id:0x\" << std::hex << dev->get_vendor_id() << \" product_id:0x\" << std::hex << dev->get_product_id() << std::endl;\n hids_.erase(it);\n }\n }\n }\n\n void value_callback(IOHIDValueRef _Nonnull value,\n IOHIDElementRef _Nonnull element,\n uint32_t usage_page,\n uint32_t usage,\n CFIndex integer_value) {\n\n#if 0\n std::cout << \"element\" << std::endl\n << \" usage_page:0x\" << std::hex << usage_page << std::endl\n << \" usage:0x\" << std::hex << usage << std::endl\n << \" type:\" << IOHIDElementGetType(element) << std::endl\n << \" length:\" << IOHIDValueGetLength(value) << std::endl\n << \" integer_value:\" << integer_value << std::endl;\n#endif\n\n switch (usage_page) {\n case kHIDPage_KeyboardOrKeypad: {\n bool pressed = integer_value;\n handle_keyboard_event(usage_page, usage, pressed);\n break;\n }\n\n case kHIDPage_AppleVendorTopCase:\n if (usage == kHIDUsage_AV_TopCase_KeyboardFn) {\n bool pressed = integer_value;\n handle_keyboard_event(usage_page, usage, pressed);\n }\n break;\n\n default:\n break;\n }\n }\n\n bool handle_modifier_flag_event(uint32_t usage_page, uint32_t usage, bool pressed) {\n auto operation = pressed ? modifier_flag_manager::operation::increase : modifier_flag_manager::operation::decrease;\n\n switch (usage_page) {\n case kHIDPage_KeyboardOrKeypad: {\n auto key = modifier_flag_manager::physical_keys::end_;\n\n switch (usage) {\n case kHIDUsage_KeyboardLeftControl:\n key = modifier_flag_manager::physical_keys::left_control;\n break;\n case kHIDUsage_KeyboardLeftShift:\n key = modifier_flag_manager::physical_keys::left_shift;\n break;\n case kHIDUsage_KeyboardLeftAlt:\n key = modifier_flag_manager::physical_keys::left_option;\n break;\n case kHIDUsage_KeyboardLeftGUI:\n key = modifier_flag_manager::physical_keys::left_command;\n break;\n case kHIDUsage_KeyboardRightControl:\n key = modifier_flag_manager::physical_keys::right_control;\n break;\n case kHIDUsage_KeyboardRightShift:\n key = modifier_flag_manager::physical_keys::right_shift;\n break;\n case kHIDUsage_KeyboardRightAlt:\n key = modifier_flag_manager::physical_keys::right_option;\n break;\n case kHIDUsage_KeyboardRightGUI:\n key = modifier_flag_manager::physical_keys::right_command;\n break;\n }\n\n if (key != modifier_flag_manager::physical_keys::end_) {\n modifier_flag_manager_.manipulate(key, operation);\n send_keyboard_input_report();\n return true;\n }\n break;\n }\n\n case kHIDPage_AppleVendorTopCase:\n if (usage == kHIDUsage_AV_TopCase_KeyboardFn) {\n modifier_flag_manager_.manipulate(modifier_flag_manager::physical_keys::fn, operation);\n console_user_client_.post_modifier_flags();\n return true;\n }\n break;\n }\n\n return false;\n }\n\n bool handle_function_key_event(uint32_t usage_page, uint32_t usage, bool pressed) {\n if (usage_page != kHIDPage_KeyboardOrKeypad) {\n return false;\n }\n\n auto event_type = pressed ? KRBN_EVENT_TYPE_KEY_DOWN : KRBN_EVENT_TYPE_KEY_UP;\n\n#define POST_KEY(KEY) \\\n case kHIDUsage_Keyboard##KEY: \\\n console_user_client_.post_key(KRBN_KEY_CODE_##KEY, event_type); \\\n return true;\n\n switch (usage) {\n POST_KEY(F1);\n POST_KEY(F2);\n POST_KEY(F3);\n POST_KEY(F4);\n POST_KEY(F5);\n POST_KEY(F6);\n POST_KEY(F7);\n POST_KEY(F8);\n POST_KEY(F9);\n POST_KEY(F10);\n POST_KEY(F11);\n POST_KEY(F12);\n }\n\n return false;\n }\n\n void handle_keyboard_event(uint32_t usage_page, uint32_t usage, bool pressed) {\n \/\/ ----------------------------------------\n \/\/ modify usage\n if (usage == kHIDUsage_KeyboardCapsLock) {\n usage = kHIDUsage_KeyboardDeleteOrBackspace;\n }\n\n \/\/ change fn+arrow keys, etc.\n \/\/ TODO: integrate into __KeyToKey__.\n if ((pressed && modifier_flag_manager_.pressed(modifier_flag_manager::physical_keys::fn)) ||\n std::find(fn_changed_keys_.begin(), fn_changed_keys_.end(), usage) != fn_changed_keys_.end()) {\n bool changed = false;\n uint32_t new_usage = 0;\n switch (usage) {\n case kHIDUsage_KeyboardReturnOrEnter:\n new_usage = kHIDUsage_KeypadEnter;\n changed = true;\n break;\n case kHIDUsage_KeyboardDeleteOrBackspace:\n new_usage = kHIDUsage_KeyboardDeleteForward;\n changed = true;\n break;\n case kHIDUsage_KeyboardRightArrow:\n new_usage = kHIDUsage_KeyboardEnd;\n changed = true;\n break;\n case kHIDUsage_KeyboardLeftArrow:\n new_usage = kHIDUsage_KeyboardHome;\n changed = true;\n break;\n case kHIDUsage_KeyboardDownArrow:\n new_usage = kHIDUsage_KeyboardPageDown;\n changed = true;\n break;\n case kHIDUsage_KeyboardUpArrow:\n new_usage = kHIDUsage_KeyboardPageUp;\n changed = true;\n break;\n }\n\n if (changed) {\n if (pressed) {\n fn_changed_keys_.push_back(usage);\n } else {\n fn_changed_keys_.remove(usage);\n }\n usage = new_usage;\n }\n }\n\n \/\/ ----------------------------------------\n if (handle_modifier_flag_event(usage_page, usage, pressed)) {\n console_user_client_.stop_key_repeat();\n return;\n }\n if (handle_function_key_event(usage_page, usage, pressed)) {\n return;\n }\n\n if (pressed) {\n pressed_key_usages_.push_back(usage);\n console_user_client_.stop_key_repeat();\n } else {\n pressed_key_usages_.remove(usage);\n }\n\n send_keyboard_input_report();\n }\n\n void send_keyboard_input_report(void) {\n \/\/ make report\n hid_report::keyboard_input report;\n report.modifiers = modifier_flag_manager_.get_hid_report_bits();\n\n while (pressed_key_usages_.size() > sizeof(report.keys)) {\n pressed_key_usages_.pop_front();\n }\n\n int i = 0;\n for (const auto& u : pressed_key_usages_) {\n report.keys[i] = u;\n ++i;\n }\n\n \/\/ send new report only if it is changed from last report.\n if (last_keyboard_input_report_ != report) {\n last_keyboard_input_report_ = report;\n\n auto kr = iokit_user_client_.call_struct_method(static_cast(virtual_hid_manager_user_client_method::keyboard_input_report),\n static_cast(&report), sizeof(report),\n nullptr, 0);\n if (kr != KERN_SUCCESS) {\n logger::get_logger().error(\"failed to sent report: 0x{0:x}\", kr);\n }\n }\n }\n\n iokit_user_client iokit_user_client_;\n IOHIDManagerRef _Nullable manager_;\n std::unordered_map> hids_;\n std::list pressed_key_usages_;\n std::list fn_changed_keys_;\n\n modifier_flag_manager modifier_flag_manager_;\n hid_report::keyboard_input last_keyboard_input_report_;\n\n console_user_client console_user_client_;\n};\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \"spidevice.h\"\n#include \"transfer.h\"\n#include \"util.h\"\n\n\n\/\/ TODO\n\/\/ - Make sure it works when the message array is empty\n\n\nstatic int Transfer(\n int fd,\n spi_ioc_transfer *spiTransfers,\n uint32_t transferCount\n) {\n return ioctl(fd, SPI_IOC_MESSAGE(transferCount), spiTransfers);\n}\n\n\nclass TransferWorker : public SpiAsyncWorker {\npublic:\n TransferWorker(\n Nan::Callback *callback,\n int fd,\n v8::Local message,\n spi_ioc_transfer *spiTransfers,\n uint32_t transferCount\n ) : SpiAsyncWorker(callback),\n fd_(fd),\n spiTransfers_(spiTransfers),\n transferCount_(transferCount) {\n SaveToPersistent(\"message\", message);\n }\n\n ~TransferWorker() {\n }\n\n void Execute() {\n int ret = Transfer(fd_, spiTransfers_, transferCount_);\n free(spiTransfers_);\n if (ret == -1) {\n SetErrorNo(errno);\n SetErrorSyscall(\"transfer\");\n }\n }\n\n void HandleOKCallback() {\n Nan::HandleScope scope;\n\n v8::Local message = GetFromPersistent(\"message\");\n\n v8::Local argv[] = {\n Nan::Null(),\n message\n };\n\n callback->Call(2, argv);\n }\n\nprivate:\n int fd_;\n spi_ioc_transfer *spiTransfers_;\n uint32_t transferCount_;\n};\n\n\nstatic int32_t ToSpiTransfers(\n v8::Local message,\n spi_ioc_transfer *spiTransfers\n) {\n for (unsigned i = 0; i < message->Length(); ++i) {\n \/\/ Transfer\n\n v8::Local transfer = message->Get(i);\n\n if (!transfer->IsObject()) {\n Nan::ThrowError(\n Nan::ErrnoException(\n EINVAL, \"toSpiTransfers\", \"a transfer being should be an object\"\n )\n );\n return -1;\n }\n\n v8::Local msg = v8::Local::Cast(transfer);\n\n \/\/ byteLength\n\n v8::Local byteLength =\n Nan::Get(msg, Nan::New(\"byteLength\").ToLocalChecked()).\n ToLocalChecked();\n\n if (byteLength->IsUndefined()) {\n Nan::ThrowError(\n Nan::ErrnoException(\n EINVAL, \"toSpiTransfers\", \"transfer byteLength not specified\"\n )\n );\n return -1;\n } else if (!byteLength->IsUint32()) {\n Nan::ThrowError(\n Nan::ErrnoException(\n EINVAL,\n \"toSpiTransfers\",\n \"transfer byteLength should be an unsigned integer\"\n )\n );\n return -1;\n }\n\n uint32_t length = byteLength->Uint32Value();\n spiTransfers[i].len = length;\n\n \/\/ sendBuffer\n\n v8::Local sendBuffer =\n Nan::Get(msg, Nan::New(\"sendBuffer\").ToLocalChecked()).\n ToLocalChecked();\n\n if (sendBuffer->IsNull() || sendBuffer->IsUndefined()) {\n \/\/ No sendBuffer so tx_buf should be NULL. This is already the case.\n } else if (node::Buffer::HasInstance(sendBuffer)) {\n if (node::Buffer::Length(sendBuffer) < length) {\n Nan::ThrowError(\n Nan::ErrnoException(\n EINVAL,\n \"toSpiTransfers\",\n \"transfer sendBuffer contains less than byteLength bytes\"\n )\n );\n return -1;\n }\n spiTransfers[i].tx_buf = (__u64) node::Buffer::Data(sendBuffer);\n } else {\n Nan::ThrowError(\n Nan::ErrnoException(\n EINVAL,\n \"toSpiTransfers\",\n \"transfer sendBuffer should be null, undefined, or a Buffer object\"\n )\n );\n return -1;\n }\n\n \/\/ receiveBuffer\n\n v8::Local receiveBuffer =\n Nan::Get(msg, Nan::New(\"receiveBuffer\").ToLocalChecked()).\n ToLocalChecked();\n\n if (receiveBuffer->IsNull() || receiveBuffer->IsUndefined()) {\n \/\/ No receiveBuffer so rx_buf should be NULL. This is already the case.\n } else if (node::Buffer::HasInstance(receiveBuffer)) {\n if (node::Buffer::Length(receiveBuffer) < length) {\n Nan::ThrowError(\n Nan::ErrnoException(\n EINVAL,\n \"toSpiTransfers\",\n \"transfer receiveBuffer contains less than byteLength bytes\"\n )\n );\n return -1;\n }\n spiTransfers[i].rx_buf = (__u64) node::Buffer::Data(receiveBuffer);\n } else {\n Nan::ThrowError(\n Nan::ErrnoException(\n EINVAL,\n \"toSpiTransfers\",\n \"transfer receiveBuffer should be null, undefined, or a Buffer object\"\n )\n );\n return -1;\n }\n\n \/\/ sendBuffer and receiveBuffer\n\n if ((sendBuffer->IsNull() || sendBuffer->IsUndefined()) &&\n (receiveBuffer->IsNull() || receiveBuffer->IsUndefined())) {\n Nan::ThrowError(\n Nan::ErrnoException(\n EINVAL,\n \"toSpiTransfers\",\n \"transfer contains neither a sendBuffer nor a receiveBuffer\"\n )\n );\n return -1;\n }\n\n \/\/ speed\n\n v8::Local speed = Nan::Get(msg,\n Nan::New(\"speed\").ToLocalChecked()).ToLocalChecked();\n\n if (speed->IsUndefined()) {\n \/\/ No speed defined, nothing to do.\n } else if (!speed->IsUint32()) {\n Nan::ThrowError(\n Nan::ErrnoException(\n EINVAL,\n \"toSpiTransfers\",\n \"transfer speed should be an unsigned integer\"\n )\n );\n return -1;\n } else {\n spiTransfers[i].speed_hz = speed->Uint32Value();\n }\n\n \/\/ chipSelectChange\n\n v8::Local chipSelectChange =\n Nan::Get(msg, Nan::New(\"chipSelectChange\").ToLocalChecked()).\n ToLocalChecked();\n\n if (chipSelectChange->IsUndefined()) {\n \/\/ No chipSelectChange defined, nothing to do.\n } else if (!chipSelectChange->IsBoolean()) {\n Nan::ThrowError(\n Nan::ErrnoException(\n EINVAL,\n \"toSpiTransfers\",\n \"transfer chipSelectChange should be a boolean\"\n )\n );\n return -1;\n } else {\n spiTransfers[i].cs_change = chipSelectChange->BooleanValue() ? 1 : 0;\n }\n }\n\n return 0;\n}\n\n\nvoid Transfer(Nan::NAN_METHOD_ARGS_TYPE info) {\n SpiDevice *device = Nan::ObjectWrap::Unwrap(info.This());\n int fd = device->Fd();\n\n if (fd == -1) {\n return Nan::ThrowError(\n Nan::ErrnoException(\n EPERM, \"transfer\", \"device closed, operation not permitted\"\n )\n );\n }\n\n if (info.Length() < 2 ||\n !info[0]->IsArray() ||\n !info[1]->IsFunction()) {\n return Nan::ThrowError(\n Nan::ErrnoException(\n EINVAL,\n \"transfer\",\n \"incorrect arguments passed to transfer(message, cb)\"\n )\n );\n }\n\n v8::Local message = info[0].As();\n Nan::Callback *callback = new Nan::Callback(info[1].As());\n\n spi_ioc_transfer *spiTransfers = (spi_ioc_transfer *)\n malloc(message->Length() * sizeof(spi_ioc_transfer));\n memset(spiTransfers, 0, message->Length() * sizeof(spi_ioc_transfer));\n\n if (ToSpiTransfers(message, spiTransfers) == -1) {\n free(spiTransfers);\n return;\n }\n\n Nan::AsyncQueueWorker(new TransferWorker(\n callback,\n fd,\n message,\n spiTransfers,\n message->Length()\n ));\n\n info.GetReturnValue().Set(info.This());\n}\n\n\nvoid TransferSync(Nan::NAN_METHOD_ARGS_TYPE info) {\n SpiDevice *device = Nan::ObjectWrap::Unwrap(info.This());\n int fd = device->Fd();\n\n if (fd == -1) {\n return Nan::ThrowError(\n Nan::ErrnoException(\n EPERM, \"transferSync\", \"device closed, operation not permitted\"\n )\n );\n }\n\n if (info.Length() < 1 || !info[0]->IsArray()) {\n return Nan::ThrowError(\n Nan::ErrnoException(\n EINVAL,\n \"transfer\",\n \"incorrect arguments passed to transferSync(message)\"\n )\n );\n }\n\n v8::Local message = info[0].As();\n\n spi_ioc_transfer *spiTransfers = (spi_ioc_transfer *)\n malloc(message->Length() * sizeof(spi_ioc_transfer));\n memset(spiTransfers, 0, message->Length() * sizeof(spi_ioc_transfer));\n\n if (ToSpiTransfers(message, spiTransfers) == 0) {\n if (Transfer(fd, spiTransfers, message->Length()) == -1) {\n Nan::ThrowError(Nan::ErrnoException(errno, \"transferSync\", \"\"));\n }\n }\n\n free(spiTransfers);\n\n info.GetReturnValue().Set(info.This());\n}\n\nmake message readable#include \n#include \n#include \n#include \n#include \"spidevice.h\"\n#include \"transfer.h\"\n#include \"util.h\"\n\n\n\/\/ TODO\n\/\/ - Make sure it works when the message array is empty\n\n\nstatic int Transfer(\n int fd,\n spi_ioc_transfer *spiTransfers,\n uint32_t transferCount\n) {\n return ioctl(fd, SPI_IOC_MESSAGE(transferCount), spiTransfers);\n}\n\n\nclass TransferWorker : public SpiAsyncWorker {\npublic:\n TransferWorker(\n Nan::Callback *callback,\n int fd,\n v8::Local message,\n spi_ioc_transfer *spiTransfers,\n uint32_t transferCount\n ) : SpiAsyncWorker(callback),\n fd_(fd),\n spiTransfers_(spiTransfers),\n transferCount_(transferCount) {\n SaveToPersistent(\"message\", message);\n }\n\n ~TransferWorker() {\n }\n\n void Execute() {\n int ret = Transfer(fd_, spiTransfers_, transferCount_);\n free(spiTransfers_);\n if (ret == -1) {\n SetErrorNo(errno);\n SetErrorSyscall(\"transfer\");\n }\n }\n\n void HandleOKCallback() {\n Nan::HandleScope scope;\n\n v8::Local message = GetFromPersistent(\"message\");\n\n v8::Local argv[] = {\n Nan::Null(),\n message\n };\n\n callback->Call(2, argv);\n }\n\nprivate:\n int fd_;\n spi_ioc_transfer *spiTransfers_;\n uint32_t transferCount_;\n};\n\n\nstatic int32_t ToSpiTransfers(\n v8::Local message,\n spi_ioc_transfer *spiTransfers\n) {\n for (unsigned i = 0; i < message->Length(); ++i) {\n \/\/ Transfer\n\n v8::Local transfer = message->Get(i);\n\n if (!transfer->IsObject()) {\n Nan::ThrowError(\n Nan::ErrnoException(\n EINVAL, \"toSpiTransfers\", \"a transfer should be an object\"\n )\n );\n return -1;\n }\n\n v8::Local msg = v8::Local::Cast(transfer);\n\n \/\/ byteLength\n\n v8::Local byteLength =\n Nan::Get(msg, Nan::New(\"byteLength\").ToLocalChecked()).\n ToLocalChecked();\n\n if (byteLength->IsUndefined()) {\n Nan::ThrowError(\n Nan::ErrnoException(\n EINVAL, \"toSpiTransfers\", \"transfer byteLength not specified\"\n )\n );\n return -1;\n } else if (!byteLength->IsUint32()) {\n Nan::ThrowError(\n Nan::ErrnoException(\n EINVAL,\n \"toSpiTransfers\",\n \"transfer byteLength should be an unsigned integer\"\n )\n );\n return -1;\n }\n\n uint32_t length = byteLength->Uint32Value();\n spiTransfers[i].len = length;\n\n \/\/ sendBuffer\n\n v8::Local sendBuffer =\n Nan::Get(msg, Nan::New(\"sendBuffer\").ToLocalChecked()).\n ToLocalChecked();\n\n if (sendBuffer->IsNull() || sendBuffer->IsUndefined()) {\n \/\/ No sendBuffer so tx_buf should be NULL. This is already the case.\n } else if (node::Buffer::HasInstance(sendBuffer)) {\n if (node::Buffer::Length(sendBuffer) < length) {\n Nan::ThrowError(\n Nan::ErrnoException(\n EINVAL,\n \"toSpiTransfers\",\n \"transfer sendBuffer contains less than byteLength bytes\"\n )\n );\n return -1;\n }\n spiTransfers[i].tx_buf = (__u64) node::Buffer::Data(sendBuffer);\n } else {\n Nan::ThrowError(\n Nan::ErrnoException(\n EINVAL,\n \"toSpiTransfers\",\n \"transfer sendBuffer should be null, undefined, or a Buffer object\"\n )\n );\n return -1;\n }\n\n \/\/ receiveBuffer\n\n v8::Local receiveBuffer =\n Nan::Get(msg, Nan::New(\"receiveBuffer\").ToLocalChecked()).\n ToLocalChecked();\n\n if (receiveBuffer->IsNull() || receiveBuffer->IsUndefined()) {\n \/\/ No receiveBuffer so rx_buf should be NULL. This is already the case.\n } else if (node::Buffer::HasInstance(receiveBuffer)) {\n if (node::Buffer::Length(receiveBuffer) < length) {\n Nan::ThrowError(\n Nan::ErrnoException(\n EINVAL,\n \"toSpiTransfers\",\n \"transfer receiveBuffer contains less than byteLength bytes\"\n )\n );\n return -1;\n }\n spiTransfers[i].rx_buf = (__u64) node::Buffer::Data(receiveBuffer);\n } else {\n Nan::ThrowError(\n Nan::ErrnoException(\n EINVAL,\n \"toSpiTransfers\",\n \"transfer receiveBuffer should be null, undefined, or a Buffer object\"\n )\n );\n return -1;\n }\n\n \/\/ sendBuffer and receiveBuffer\n\n if ((sendBuffer->IsNull() || sendBuffer->IsUndefined()) &&\n (receiveBuffer->IsNull() || receiveBuffer->IsUndefined())) {\n Nan::ThrowError(\n Nan::ErrnoException(\n EINVAL,\n \"toSpiTransfers\",\n \"transfer contains neither a sendBuffer nor a receiveBuffer\"\n )\n );\n return -1;\n }\n\n \/\/ speed\n\n v8::Local speed = Nan::Get(msg,\n Nan::New(\"speed\").ToLocalChecked()).ToLocalChecked();\n\n if (speed->IsUndefined()) {\n \/\/ No speed defined, nothing to do.\n } else if (!speed->IsUint32()) {\n Nan::ThrowError(\n Nan::ErrnoException(\n EINVAL,\n \"toSpiTransfers\",\n \"transfer speed should be an unsigned integer\"\n )\n );\n return -1;\n } else {\n spiTransfers[i].speed_hz = speed->Uint32Value();\n }\n\n \/\/ chipSelectChange\n\n v8::Local chipSelectChange =\n Nan::Get(msg, Nan::New(\"chipSelectChange\").ToLocalChecked()).\n ToLocalChecked();\n\n if (chipSelectChange->IsUndefined()) {\n \/\/ No chipSelectChange defined, nothing to do.\n } else if (!chipSelectChange->IsBoolean()) {\n Nan::ThrowError(\n Nan::ErrnoException(\n EINVAL,\n \"toSpiTransfers\",\n \"transfer chipSelectChange should be a boolean\"\n )\n );\n return -1;\n } else {\n spiTransfers[i].cs_change = chipSelectChange->BooleanValue() ? 1 : 0;\n }\n }\n\n return 0;\n}\n\n\nvoid Transfer(Nan::NAN_METHOD_ARGS_TYPE info) {\n SpiDevice *device = Nan::ObjectWrap::Unwrap(info.This());\n int fd = device->Fd();\n\n if (fd == -1) {\n return Nan::ThrowError(\n Nan::ErrnoException(\n EPERM, \"transfer\", \"device closed, operation not permitted\"\n )\n );\n }\n\n if (info.Length() < 2 ||\n !info[0]->IsArray() ||\n !info[1]->IsFunction()) {\n return Nan::ThrowError(\n Nan::ErrnoException(\n EINVAL,\n \"transfer\",\n \"incorrect arguments passed to transfer(message, cb)\"\n )\n );\n }\n\n v8::Local message = info[0].As();\n Nan::Callback *callback = new Nan::Callback(info[1].As());\n\n spi_ioc_transfer *spiTransfers = (spi_ioc_transfer *)\n malloc(message->Length() * sizeof(spi_ioc_transfer));\n memset(spiTransfers, 0, message->Length() * sizeof(spi_ioc_transfer));\n\n if (ToSpiTransfers(message, spiTransfers) == -1) {\n free(spiTransfers);\n return;\n }\n\n Nan::AsyncQueueWorker(new TransferWorker(\n callback,\n fd,\n message,\n spiTransfers,\n message->Length()\n ));\n\n info.GetReturnValue().Set(info.This());\n}\n\n\nvoid TransferSync(Nan::NAN_METHOD_ARGS_TYPE info) {\n SpiDevice *device = Nan::ObjectWrap::Unwrap(info.This());\n int fd = device->Fd();\n\n if (fd == -1) {\n return Nan::ThrowError(\n Nan::ErrnoException(\n EPERM, \"transferSync\", \"device closed, operation not permitted\"\n )\n );\n }\n\n if (info.Length() < 1 || !info[0]->IsArray()) {\n return Nan::ThrowError(\n Nan::ErrnoException(\n EINVAL,\n \"transfer\",\n \"incorrect arguments passed to transferSync(message)\"\n )\n );\n }\n\n v8::Local message = info[0].As();\n\n spi_ioc_transfer *spiTransfers = (spi_ioc_transfer *)\n malloc(message->Length() * sizeof(spi_ioc_transfer));\n memset(spiTransfers, 0, message->Length() * sizeof(spi_ioc_transfer));\n\n if (ToSpiTransfers(message, spiTransfers) == 0) {\n if (Transfer(fd, spiTransfers, message->Length()) == -1) {\n Nan::ThrowError(Nan::ErrnoException(errno, \"transferSync\", \"\"));\n }\n }\n\n free(spiTransfers);\n\n info.GetReturnValue().Set(info.This());\n}\n\n<|endoftext|>"} {"text":"\/****************************************************************************\n**\n** Copyright (C) 2015 The Qt Company Ltd.\n** Contact: http:\/\/www.qt.io\/licensing\n**\n** This file is part of Qt Creator.\n**\n** Commercial License Usage\n** Licensees holding valid commercial Qt licenses may use this file in\n** accordance with the commercial license agreement provided with the\n** Software or, alternatively, in accordance with the terms contained in\n** a written agreement between you and The Qt Company. For licensing terms and\n** conditions see http:\/\/www.qt.io\/terms-conditions. For further information\n** use the contact form at http:\/\/www.qt.io\/contact-us.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 or version 3 as published by the Free\n** Software Foundation and appearing in the file LICENSE.LGPLv21 and\n** LICENSE.LGPLv3 included in the packaging of this file. Please review the\n** following information to ensure the GNU Lesser General Public License\n** requirements will be met: https:\/\/www.gnu.org\/licenses\/lgpl.html and\n** http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, The Qt Company gives you certain additional\n** rights. These rights are described in The Qt Company LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n****************************************************************************\/\n\n#include \"outputwindow.h\"\n\n#include \"actionmanager\/actionmanager.h\"\n#include \"coreconstants.h\"\n#include \"icore.h\"\n\n#include \n#include \n\n#include \n#include \n\nusing namespace Utils;\n\nnamespace Core {\n\nnamespace Internal {\n\nclass OutputWindowPrivate\n{\npublic:\n OutputWindowPrivate()\n : outputWindowContext(0)\n , formatter(0)\n , enforceNewline(false)\n , scrollToBottom(false)\n , linksActive(true)\n , mousePressed(false)\n , maxLineCount(100000)\n {\n }\n\n ~OutputWindowPrivate()\n {\n ICore::removeContextObject(outputWindowContext);\n delete outputWindowContext;\n }\n\n IContext *outputWindowContext;\n Utils::OutputFormatter *formatter;\n\n bool enforceNewline;\n bool scrollToBottom;\n bool linksActive;\n bool mousePressed;\n int maxLineCount;\n};\n\n} \/\/ namespace Internal\n\n\/*******************\/\n\nOutputWindow::OutputWindow(Context context, QWidget *parent)\n : QPlainTextEdit(parent)\n , d(new Internal::OutputWindowPrivate)\n{\n setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);\n \/\/setCenterOnScroll(false);\n setFrameShape(QFrame::NoFrame);\n setMouseTracking(true);\n setUndoRedoEnabled(false);\n\n d->outputWindowContext = new IContext;\n d->outputWindowContext->setContext(context);\n d->outputWindowContext->setWidget(this);\n ICore::addContextObject(d->outputWindowContext);\n\n QAction *undoAction = new QAction(this);\n QAction *redoAction = new QAction(this);\n QAction *cutAction = new QAction(this);\n QAction *copyAction = new QAction(this);\n QAction *pasteAction = new QAction(this);\n QAction *selectAllAction = new QAction(this);\n\n ActionManager::registerAction(undoAction, Constants::UNDO, context);\n ActionManager::registerAction(redoAction, Constants::REDO, context);\n ActionManager::registerAction(cutAction, Constants::CUT, context);\n ActionManager::registerAction(copyAction, Constants::COPY, context);\n ActionManager::registerAction(pasteAction, Constants::PASTE, context);\n ActionManager::registerAction(selectAllAction, Constants::SELECTALL, context);\n\n connect(undoAction, SIGNAL(triggered()), this, SLOT(undo()));\n connect(redoAction, SIGNAL(triggered()), this, SLOT(redo()));\n connect(cutAction, SIGNAL(triggered()), this, SLOT(cut()));\n connect(copyAction, SIGNAL(triggered()), this, SLOT(copy()));\n connect(pasteAction, SIGNAL(triggered()), this, SLOT(paste()));\n connect(selectAllAction, SIGNAL(triggered()), this, SLOT(selectAll()));\n\n connect(this, SIGNAL(undoAvailable(bool)), undoAction, SLOT(setEnabled(bool)));\n connect(this, SIGNAL(redoAvailable(bool)), redoAction, SLOT(setEnabled(bool)));\n connect(this, SIGNAL(copyAvailable(bool)), cutAction, SLOT(setEnabled(bool))); \/\/ OutputWindow never read-only\n connect(this, SIGNAL(copyAvailable(bool)), copyAction, SLOT(setEnabled(bool)));\n\n undoAction->setEnabled(false);\n redoAction->setEnabled(false);\n cutAction->setEnabled(false);\n copyAction->setEnabled(false);\n}\n\nOutputWindow::~OutputWindow()\n{\n delete d;\n}\n\nvoid OutputWindow::mousePressEvent(QMouseEvent * e)\n{\n d->mousePressed = true;\n QPlainTextEdit::mousePressEvent(e);\n}\n\nvoid OutputWindow::mouseReleaseEvent(QMouseEvent *e)\n{\n d->mousePressed = false;\n\n if (d->linksActive) {\n const QString href = anchorAt(e->pos());\n if (d->formatter)\n d->formatter->handleLink(href);\n }\n\n \/\/ Mouse was released, activate links again\n d->linksActive = true;\n\n QPlainTextEdit::mouseReleaseEvent(e);\n}\n\nvoid OutputWindow::mouseMoveEvent(QMouseEvent *e)\n{\n \/\/ Cursor was dragged to make a selection, deactivate links\n if (d->mousePressed && textCursor().hasSelection())\n d->linksActive = false;\n\n if (!d->linksActive || anchorAt(e->pos()).isEmpty())\n viewport()->setCursor(Qt::IBeamCursor);\n else\n viewport()->setCursor(Qt::PointingHandCursor);\n QPlainTextEdit::mouseMoveEvent(e);\n}\n\nvoid OutputWindow::resizeEvent(QResizeEvent *e)\n{\n \/\/Keep scrollbar at bottom of window while resizing, to ensure we keep scrolling\n \/\/This can happen if window is resized while building, or if the horizontal scrollbar appears\n bool atBottom = isScrollbarAtBottom();\n QPlainTextEdit::resizeEvent(e);\n if (atBottom)\n scrollToBottom();\n}\n\nvoid OutputWindow::keyPressEvent(QKeyEvent *ev)\n{\n QPlainTextEdit::keyPressEvent(ev);\n\n \/\/Ensure we scroll also on Ctrl+Home or Ctrl+End\n if (ev->matches(QKeySequence::MoveToStartOfDocument))\n verticalScrollBar()->triggerAction(QAbstractSlider::SliderToMinimum);\n else if (ev->matches(QKeySequence::MoveToEndOfDocument))\n verticalScrollBar()->triggerAction(QAbstractSlider::SliderToMaximum);\n}\n\nOutputFormatter *OutputWindow::formatter() const\n{\n return d->formatter;\n}\n\nvoid OutputWindow::setFormatter(OutputFormatter *formatter)\n{\n d->formatter = formatter;\n d->formatter->setPlainTextEdit(this);\n}\n\nvoid OutputWindow::showEvent(QShowEvent *e)\n{\n QPlainTextEdit::showEvent(e);\n if (d->scrollToBottom)\n verticalScrollBar()->setValue(verticalScrollBar()->maximum());\n d->scrollToBottom = false;\n}\n\nQString OutputWindow::doNewlineEnforcement(const QString &out)\n{\n d->scrollToBottom = true;\n QString s = out;\n if (d->enforceNewline) {\n s.prepend(QLatin1Char('\\n'));\n d->enforceNewline = false;\n }\n\n if (s.endsWith(QLatin1Char('\\n'))) {\n d->enforceNewline = true; \/\/ make appendOutputInline put in a newline next time\n s.chop(1);\n }\n\n return s;\n}\n\nvoid OutputWindow::setMaxLineCount(int count)\n{\n d->maxLineCount = count;\n setMaximumBlockCount(d->maxLineCount);\n}\n\nint OutputWindow::maxLineCount() const\n{\n return d->maxLineCount;\n}\n\nvoid OutputWindow::appendMessage(const QString &output, OutputFormat format)\n{\n const QString out = SynchronousProcess::normalizeNewlines(output);\n setMaximumBlockCount(d->maxLineCount);\n const bool atBottom = isScrollbarAtBottom();\n\n if (format == ErrorMessageFormat || format == NormalMessageFormat) {\n\n d->formatter->appendMessage(doNewlineEnforcement(out), format);\n\n } else {\n\n bool sameLine = format == StdOutFormatSameLine\n || format == StdErrFormatSameLine;\n\n if (sameLine) {\n d->scrollToBottom = true;\n\n int newline = -1;\n bool enforceNewline = d->enforceNewline;\n d->enforceNewline = false;\n\n if (!enforceNewline) {\n newline = out.indexOf(QLatin1Char('\\n'));\n moveCursor(QTextCursor::End);\n if (newline != -1)\n d->formatter->appendMessage(out.left(newline), format);\/\/ doesn't enforce new paragraph like appendPlainText\n }\n\n QString s = out.mid(newline+1);\n if (s.isEmpty()) {\n d->enforceNewline = true;\n } else {\n if (s.endsWith(QLatin1Char('\\n'))) {\n d->enforceNewline = true;\n s.chop(1);\n }\n d->formatter->appendMessage(QLatin1Char('\\n') + s, format);\n }\n } else {\n d->formatter->appendMessage(doNewlineEnforcement(out), format);\n }\n }\n\n if (atBottom)\n scrollToBottom();\n enableUndoRedo();\n}\n\n\/\/ TODO rename\nvoid OutputWindow::appendText(const QString &textIn, const QTextCharFormat &format)\n{\n const QString text = SynchronousProcess::normalizeNewlines(textIn);\n if (d->maxLineCount > 0 && document()->blockCount() >= d->maxLineCount)\n return;\n const bool atBottom = isScrollbarAtBottom();\n QTextCursor cursor = QTextCursor(document());\n cursor.movePosition(QTextCursor::End);\n cursor.beginEditBlock();\n cursor.insertText(doNewlineEnforcement(text), format);\n\n if (d->maxLineCount > 0 && document()->blockCount() >= d->maxLineCount) {\n QTextCharFormat tmp;\n tmp.setFontWeight(QFont::Bold);\n cursor.insertText(doNewlineEnforcement(tr(\"Additional output omitted\") + QLatin1Char('\\n')), tmp);\n }\n\n cursor.endEditBlock();\n if (atBottom)\n scrollToBottom();\n}\n\nbool OutputWindow::isScrollbarAtBottom() const\n{\n return verticalScrollBar()->value() == verticalScrollBar()->maximum();\n}\n\nvoid OutputWindow::clear()\n{\n d->enforceNewline = false;\n QPlainTextEdit::clear();\n}\n\nvoid OutputWindow::scrollToBottom()\n{\n verticalScrollBar()->setValue(verticalScrollBar()->maximum());\n \/\/ QPlainTextEdit destroys the first calls value in case of multiline\n \/\/ text, so make sure that the scroll bar actually gets the value set.\n \/\/ Is a noop if the first call succeeded.\n verticalScrollBar()->setValue(verticalScrollBar()->maximum());\n}\n\nvoid OutputWindow::grayOutOldContent()\n{\n QTextCursor cursor = textCursor();\n cursor.movePosition(QTextCursor::End);\n QTextCharFormat endFormat = cursor.charFormat();\n\n cursor.select(QTextCursor::Document);\n\n QTextCharFormat format;\n const QColor bkgColor = palette().base().color();\n const QColor fgdColor = palette().text().color();\n double bkgFactor = 0.50;\n double fgdFactor = 1.-bkgFactor;\n format.setForeground(QColor((bkgFactor * bkgColor.red() + fgdFactor * fgdColor.red()),\n (bkgFactor * bkgColor.green() + fgdFactor * fgdColor.green()),\n (bkgFactor * bkgColor.blue() + fgdFactor * fgdColor.blue()) ));\n cursor.mergeCharFormat(format);\n\n cursor.movePosition(QTextCursor::End);\n cursor.setCharFormat(endFormat);\n cursor.insertBlock(QTextBlockFormat());\n}\n\nvoid OutputWindow::enableUndoRedo()\n{\n setMaximumBlockCount(0);\n setUndoRedoEnabled(true);\n}\n\nvoid OutputWindow::setWordWrapEnabled(bool wrap)\n{\n if (wrap)\n setWordWrapMode(QTextOption::WrapAtWordBoundaryOrAnywhere);\n else\n setWordWrapMode(QTextOption::NoWrap);\n}\n\n} \/\/ namespace Core\nCore: Use a fixed cursor in OutputWindow\/****************************************************************************\n**\n** Copyright (C) 2015 The Qt Company Ltd.\n** Contact: http:\/\/www.qt.io\/licensing\n**\n** This file is part of Qt Creator.\n**\n** Commercial License Usage\n** Licensees holding valid commercial Qt licenses may use this file in\n** accordance with the commercial license agreement provided with the\n** Software or, alternatively, in accordance with the terms contained in\n** a written agreement between you and The Qt Company. For licensing terms and\n** conditions see http:\/\/www.qt.io\/terms-conditions. For further information\n** use the contact form at http:\/\/www.qt.io\/contact-us.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 or version 3 as published by the Free\n** Software Foundation and appearing in the file LICENSE.LGPLv21 and\n** LICENSE.LGPLv3 included in the packaging of this file. Please review the\n** following information to ensure the GNU Lesser General Public License\n** requirements will be met: https:\/\/www.gnu.org\/licenses\/lgpl.html and\n** http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, The Qt Company gives you certain additional\n** rights. These rights are described in The Qt Company LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n****************************************************************************\/\n\n#include \"outputwindow.h\"\n\n#include \"actionmanager\/actionmanager.h\"\n#include \"coreconstants.h\"\n#include \"icore.h\"\n\n#include \n#include \n\n#include \n#include \n\nusing namespace Utils;\n\nnamespace Core {\n\nnamespace Internal {\n\nclass OutputWindowPrivate\n{\npublic:\n OutputWindowPrivate(QTextDocument *document)\n : outputWindowContext(0)\n , formatter(0)\n , enforceNewline(false)\n , scrollToBottom(false)\n , linksActive(true)\n , mousePressed(false)\n , maxLineCount(100000)\n , cursor(document)\n {\n }\n\n ~OutputWindowPrivate()\n {\n ICore::removeContextObject(outputWindowContext);\n delete outputWindowContext;\n }\n\n IContext *outputWindowContext;\n Utils::OutputFormatter *formatter;\n\n bool enforceNewline;\n bool scrollToBottom;\n bool linksActive;\n bool mousePressed;\n int maxLineCount;\n QTextCursor cursor;\n};\n\n} \/\/ namespace Internal\n\n\/*******************\/\n\nOutputWindow::OutputWindow(Context context, QWidget *parent)\n : QPlainTextEdit(parent)\n , d(new Internal::OutputWindowPrivate(document()))\n{\n setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);\n \/\/setCenterOnScroll(false);\n setFrameShape(QFrame::NoFrame);\n setMouseTracking(true);\n setUndoRedoEnabled(false);\n\n d->outputWindowContext = new IContext;\n d->outputWindowContext->setContext(context);\n d->outputWindowContext->setWidget(this);\n ICore::addContextObject(d->outputWindowContext);\n\n QAction *undoAction = new QAction(this);\n QAction *redoAction = new QAction(this);\n QAction *cutAction = new QAction(this);\n QAction *copyAction = new QAction(this);\n QAction *pasteAction = new QAction(this);\n QAction *selectAllAction = new QAction(this);\n\n ActionManager::registerAction(undoAction, Constants::UNDO, context);\n ActionManager::registerAction(redoAction, Constants::REDO, context);\n ActionManager::registerAction(cutAction, Constants::CUT, context);\n ActionManager::registerAction(copyAction, Constants::COPY, context);\n ActionManager::registerAction(pasteAction, Constants::PASTE, context);\n ActionManager::registerAction(selectAllAction, Constants::SELECTALL, context);\n\n connect(undoAction, SIGNAL(triggered()), this, SLOT(undo()));\n connect(redoAction, SIGNAL(triggered()), this, SLOT(redo()));\n connect(cutAction, SIGNAL(triggered()), this, SLOT(cut()));\n connect(copyAction, SIGNAL(triggered()), this, SLOT(copy()));\n connect(pasteAction, SIGNAL(triggered()), this, SLOT(paste()));\n connect(selectAllAction, SIGNAL(triggered()), this, SLOT(selectAll()));\n\n connect(this, SIGNAL(undoAvailable(bool)), undoAction, SLOT(setEnabled(bool)));\n connect(this, SIGNAL(redoAvailable(bool)), redoAction, SLOT(setEnabled(bool)));\n connect(this, SIGNAL(copyAvailable(bool)), cutAction, SLOT(setEnabled(bool))); \/\/ OutputWindow never read-only\n connect(this, SIGNAL(copyAvailable(bool)), copyAction, SLOT(setEnabled(bool)));\n\n undoAction->setEnabled(false);\n redoAction->setEnabled(false);\n cutAction->setEnabled(false);\n copyAction->setEnabled(false);\n}\n\nOutputWindow::~OutputWindow()\n{\n delete d;\n}\n\nvoid OutputWindow::mousePressEvent(QMouseEvent * e)\n{\n d->mousePressed = true;\n QPlainTextEdit::mousePressEvent(e);\n}\n\nvoid OutputWindow::mouseReleaseEvent(QMouseEvent *e)\n{\n d->mousePressed = false;\n\n if (d->linksActive) {\n const QString href = anchorAt(e->pos());\n if (d->formatter)\n d->formatter->handleLink(href);\n }\n\n \/\/ Mouse was released, activate links again\n d->linksActive = true;\n\n QPlainTextEdit::mouseReleaseEvent(e);\n}\n\nvoid OutputWindow::mouseMoveEvent(QMouseEvent *e)\n{\n \/\/ Cursor was dragged to make a selection, deactivate links\n if (d->mousePressed && textCursor().hasSelection())\n d->linksActive = false;\n\n if (!d->linksActive || anchorAt(e->pos()).isEmpty())\n viewport()->setCursor(Qt::IBeamCursor);\n else\n viewport()->setCursor(Qt::PointingHandCursor);\n QPlainTextEdit::mouseMoveEvent(e);\n}\n\nvoid OutputWindow::resizeEvent(QResizeEvent *e)\n{\n \/\/Keep scrollbar at bottom of window while resizing, to ensure we keep scrolling\n \/\/This can happen if window is resized while building, or if the horizontal scrollbar appears\n bool atBottom = isScrollbarAtBottom();\n QPlainTextEdit::resizeEvent(e);\n if (atBottom)\n scrollToBottom();\n}\n\nvoid OutputWindow::keyPressEvent(QKeyEvent *ev)\n{\n QPlainTextEdit::keyPressEvent(ev);\n\n \/\/Ensure we scroll also on Ctrl+Home or Ctrl+End\n if (ev->matches(QKeySequence::MoveToStartOfDocument))\n verticalScrollBar()->triggerAction(QAbstractSlider::SliderToMinimum);\n else if (ev->matches(QKeySequence::MoveToEndOfDocument))\n verticalScrollBar()->triggerAction(QAbstractSlider::SliderToMaximum);\n}\n\nOutputFormatter *OutputWindow::formatter() const\n{\n return d->formatter;\n}\n\nvoid OutputWindow::setFormatter(OutputFormatter *formatter)\n{\n d->formatter = formatter;\n d->formatter->setPlainTextEdit(this);\n}\n\nvoid OutputWindow::showEvent(QShowEvent *e)\n{\n QPlainTextEdit::showEvent(e);\n if (d->scrollToBottom)\n verticalScrollBar()->setValue(verticalScrollBar()->maximum());\n d->scrollToBottom = false;\n}\n\nQString OutputWindow::doNewlineEnforcement(const QString &out)\n{\n d->scrollToBottom = true;\n QString s = out;\n if (d->enforceNewline) {\n s.prepend(QLatin1Char('\\n'));\n d->enforceNewline = false;\n }\n\n if (s.endsWith(QLatin1Char('\\n'))) {\n d->enforceNewline = true; \/\/ make appendOutputInline put in a newline next time\n s.chop(1);\n }\n\n return s;\n}\n\nvoid OutputWindow::setMaxLineCount(int count)\n{\n d->maxLineCount = count;\n setMaximumBlockCount(d->maxLineCount);\n}\n\nint OutputWindow::maxLineCount() const\n{\n return d->maxLineCount;\n}\n\nvoid OutputWindow::appendMessage(const QString &output, OutputFormat format)\n{\n const QString out = SynchronousProcess::normalizeNewlines(output);\n setMaximumBlockCount(d->maxLineCount);\n const bool atBottom = isScrollbarAtBottom();\n\n if (format == ErrorMessageFormat || format == NormalMessageFormat) {\n\n d->formatter->appendMessage(doNewlineEnforcement(out), format);\n\n } else {\n\n bool sameLine = format == StdOutFormatSameLine\n || format == StdErrFormatSameLine;\n\n if (sameLine) {\n d->scrollToBottom = true;\n\n int newline = -1;\n bool enforceNewline = d->enforceNewline;\n d->enforceNewline = false;\n\n if (!enforceNewline) {\n newline = out.indexOf(QLatin1Char('\\n'));\n moveCursor(QTextCursor::End);\n if (newline != -1)\n d->formatter->appendMessage(out.left(newline), format);\/\/ doesn't enforce new paragraph like appendPlainText\n }\n\n QString s = out.mid(newline+1);\n if (s.isEmpty()) {\n d->enforceNewline = true;\n } else {\n if (s.endsWith(QLatin1Char('\\n'))) {\n d->enforceNewline = true;\n s.chop(1);\n }\n d->formatter->appendMessage(QLatin1Char('\\n') + s, format);\n }\n } else {\n d->formatter->appendMessage(doNewlineEnforcement(out), format);\n }\n }\n\n if (atBottom)\n scrollToBottom();\n enableUndoRedo();\n}\n\n\/\/ TODO rename\nvoid OutputWindow::appendText(const QString &textIn, const QTextCharFormat &format)\n{\n const QString text = SynchronousProcess::normalizeNewlines(textIn);\n if (d->maxLineCount > 0 && document()->blockCount() >= d->maxLineCount)\n return;\n const bool atBottom = isScrollbarAtBottom();\n if (!d->cursor.atEnd())\n d->cursor.movePosition(QTextCursor::End);\n d->cursor.beginEditBlock();\n d->cursor.insertText(doNewlineEnforcement(text), format);\n\n if (d->maxLineCount > 0 && document()->blockCount() >= d->maxLineCount) {\n QTextCharFormat tmp;\n tmp.setFontWeight(QFont::Bold);\n d->cursor.insertText(doNewlineEnforcement(tr(\"Additional output omitted\") + QLatin1Char('\\n')), tmp);\n }\n\n d->cursor.endEditBlock();\n if (atBottom)\n scrollToBottom();\n}\n\nbool OutputWindow::isScrollbarAtBottom() const\n{\n return verticalScrollBar()->value() == verticalScrollBar()->maximum();\n}\n\nvoid OutputWindow::clear()\n{\n d->enforceNewline = false;\n QPlainTextEdit::clear();\n}\n\nvoid OutputWindow::scrollToBottom()\n{\n verticalScrollBar()->setValue(verticalScrollBar()->maximum());\n \/\/ QPlainTextEdit destroys the first calls value in case of multiline\n \/\/ text, so make sure that the scroll bar actually gets the value set.\n \/\/ Is a noop if the first call succeeded.\n verticalScrollBar()->setValue(verticalScrollBar()->maximum());\n}\n\nvoid OutputWindow::grayOutOldContent()\n{\n if (!d->cursor.atEnd())\n d->cursor.movePosition(QTextCursor::End);\n QTextCharFormat endFormat = d->cursor.charFormat();\n\n d->cursor.select(QTextCursor::Document);\n\n QTextCharFormat format;\n const QColor bkgColor = palette().base().color();\n const QColor fgdColor = palette().text().color();\n double bkgFactor = 0.50;\n double fgdFactor = 1.-bkgFactor;\n format.setForeground(QColor((bkgFactor * bkgColor.red() + fgdFactor * fgdColor.red()),\n (bkgFactor * bkgColor.green() + fgdFactor * fgdColor.green()),\n (bkgFactor * bkgColor.blue() + fgdFactor * fgdColor.blue()) ));\n d->cursor.mergeCharFormat(format);\n\n if (!d->cursor.atEnd())\n d->cursor.movePosition(QTextCursor::End);\n d->cursor.setCharFormat(endFormat);\n d->cursor.insertBlock(QTextBlockFormat());\n}\n\nvoid OutputWindow::enableUndoRedo()\n{\n setMaximumBlockCount(0);\n setUndoRedoEnabled(true);\n}\n\nvoid OutputWindow::setWordWrapEnabled(bool wrap)\n{\n if (wrap)\n setWordWrapMode(QTextOption::WrapAtWordBoundaryOrAnywhere);\n else\n setWordWrapMode(QTextOption::NoWrap);\n}\n\n} \/\/ namespace Core\n<|endoftext|>"} {"text":"\/*\n * Copyright 2001,2004 The Apache Software Foundation.\n * \n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * \n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n\/*\n * $Id$\n *\/\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ Includes\n\/\/ ---------------------------------------------------------------------------\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nXERCES_CPP_NAMESPACE_BEGIN\n\ntypedef JanitorMemFunCall CleanupType;\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ XPathMatcher: Constructors and Destructor\n\/\/ ---------------------------------------------------------------------------\nXPathMatcher::XPathMatcher( XercesXPath* const xpath\n , MemoryManager* const manager)\n : fLocationPathSize(0)\n , fMatched(0)\n , fNoMatchDepth(0)\n , fCurrentStep(0)\n , fStepIndexes(0)\n , fLocationPaths(0)\n , fIdentityConstraint(0)\n , fMemoryManager(manager)\n{\n CleanupType cleanup(this, &XPathMatcher::cleanUp);\n\n try {\n init(xpath);\n }\n catch(const OutOfMemoryException&)\n {\n cleanup.release();\n\n throw;\n }\n\n cleanup.release();\n}\n\n\nXPathMatcher::XPathMatcher(XercesXPath* const xpath,\n IdentityConstraint* const ic,\n\t\t\t\t\t\t MemoryManager* const manager)\n : fLocationPathSize(0)\n , fMatched(0)\n , fNoMatchDepth(0)\n , fCurrentStep(0)\n , fStepIndexes(0)\n , fLocationPaths(0)\n , fIdentityConstraint(ic)\n , fMemoryManager(manager)\n{\n CleanupType cleanup(this, &XPathMatcher::cleanUp);\n\n try {\n init(xpath);\n }\n catch(const OutOfMemoryException&)\n {\n cleanup.release();\n\n throw;\n }\n\n cleanup.release();\n}\n\n\nXPathMatcher::~XPathMatcher()\n{\n cleanUp();\n}\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ XPathMatcher: Helper methods\n\/\/ ---------------------------------------------------------------------------\nvoid XPathMatcher::init(XercesXPath* const xpath) {\n\n if (xpath) {\n\n fLocationPaths = xpath->getLocationPaths();\n fLocationPathSize = (fLocationPaths ? fLocationPaths->size() : 0);\n\n if (fLocationPathSize) {\n\n fStepIndexes = new (fMemoryManager) RefVectorOf >(fLocationPathSize, true, fMemoryManager);\n fCurrentStep = (int*) fMemoryManager->allocate\n (\n fLocationPathSize * sizeof(int)\n );\/\/new int[fLocationPathSize];\n fNoMatchDepth = (int*) fMemoryManager->allocate\n (\n fLocationPathSize * sizeof(int)\n );\/\/new int[fLocationPathSize];\n fMatched = (int*) fMemoryManager->allocate\n (\n fLocationPathSize * sizeof(int)\n );\/\/new int[fLocationPathSize];\n\n for(unsigned int i=0; i < fLocationPathSize; i++) {\n fStepIndexes->addElement(new (fMemoryManager) ValueStackOf(8, fMemoryManager));\n }\n }\n }\n}\n\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ XPathMatcher: XMLDocumentHandler methods\n\/\/ ---------------------------------------------------------------------------\nvoid XPathMatcher::startDocumentFragment() {\n\n for(unsigned int i = 0; i < fLocationPathSize; i++) {\n\n fStepIndexes->elementAt(i)->removeAllElements();\n fCurrentStep[i] = 0;\n fNoMatchDepth[i] = 0;\n fMatched[i] = 0;\n }\n}\n\nvoid XPathMatcher::startElement(const XMLElementDecl& elemDecl,\n const unsigned int urlId,\n const XMLCh* const elemPrefix,\n\t\t\t\t\t\t\t\tconst RefVectorOf& attrList,\n const unsigned int attrCount) {\n\n for (int i = 0; i < (int) fLocationPathSize; i++) {\n\n \/\/ push context\n int startStep = fCurrentStep[i];\n fStepIndexes->elementAt(i)->push(startStep);\n\n \/\/ try next xpath, if not matching\n if ((fMatched[i] & XP_MATCHED_D) == XP_MATCHED || fNoMatchDepth[i] > 0) {\n fNoMatchDepth[i]++;\n continue;\n }\n\n if((fMatched[i] & XP_MATCHED_D) == XP_MATCHED_D) {\n fMatched[i] = XP_MATCHED_DP;\n }\n\n \/\/ consume self::node() steps\n XercesLocationPath* locPath = fLocationPaths->elementAt(i);\n int stepSize = locPath->getStepSize();\n\n while (fCurrentStep[i] < stepSize &&\n locPath->getStep(fCurrentStep[i])->getAxisType() == XercesStep::SELF) {\n fCurrentStep[i]++;\n }\n\n if (fCurrentStep[i] == stepSize) {\n\n fMatched[i] = XP_MATCHED;\n continue;\n }\n\n \/\/ now if the current step is a descendant step, we let the next\n \/\/ step do its thing; if it fails, we reset ourselves\n \/\/ to look at this step for next time we're called.\n \/\/ so first consume all descendants:\n int descendantStep = fCurrentStep[i];\n\n while (fCurrentStep[i] < stepSize &&\n locPath->getStep(fCurrentStep[i])->getAxisType() == XercesStep::DESCENDANT) {\n fCurrentStep[i]++;\n }\n\n bool sawDescendant = fCurrentStep[i] > descendantStep;\n if (fCurrentStep[i] == stepSize) {\n\n fNoMatchDepth[i]++;\n continue;\n }\n\n \/\/ match child::... step, if haven't consumed any self::node()\n if ((fCurrentStep[i] == startStep || fCurrentStep[i] > descendantStep) &&\n locPath->getStep(fCurrentStep[i])->getAxisType() == XercesStep::CHILD) {\n\n XercesStep* step = locPath->getStep(fCurrentStep[i]);\n XercesNodeTest* nodeTest = step->getNodeTest();\n\n if (nodeTest->getType() == XercesNodeTest::QNAME) {\n\n QName elemQName(elemPrefix, elemDecl.getElementName()->getLocalPart(), urlId, fMemoryManager);\n\n\/\/ if (!(*(nodeTest->getName()) == *(elemDecl.getElementName()))) {\n if (!(*(nodeTest->getName()) == elemQName)) {\n\n if(fCurrentStep[i] > descendantStep) {\n fCurrentStep[i] = descendantStep;\n continue;\n }\n\n fNoMatchDepth[i]++;\n continue;\n }\n }\n\n fCurrentStep[i]++;\n }\n\n if (fCurrentStep[i] == stepSize) {\n\n if (sawDescendant) {\n\n fCurrentStep[i] = descendantStep;\n fMatched[i] = XP_MATCHED_D;\n }\n else {\n fMatched[i] = XP_MATCHED;\n }\n\n continue;\n }\n\n \/\/ match attribute::... step\n if (fCurrentStep[i] < stepSize &&\n locPath->getStep(fCurrentStep[i])->getAxisType() == XercesStep::ATTRIBUTE) {\n\n if (attrCount) {\n\n XercesNodeTest* nodeTest = locPath->getStep(fCurrentStep[i])->getNodeTest();\n\n for (unsigned int attrIndex = 0; attrIndex < attrCount; attrIndex++) {\n\n const XMLAttr* curDef = attrList.elementAt(attrIndex);\n\n if (nodeTest->getType() != XercesNodeTest::QNAME ||\n (*(nodeTest->getName()) == *(curDef->getAttName()))) {\n\n fCurrentStep[i]++;\n\n if (fCurrentStep[i] == stepSize) {\n\n fMatched[i] = XP_MATCHED_A;\n int j=0;\n\n for(; jgetName(), curDef->getURIId());\n DatatypeValidator* dv = (attDef) ? attDef->getDatatypeValidator() : 0;\n matched(curDef->getValue(), dv, false);\n }\n }\n break;\n }\n }\n }\n\n if ((fMatched[i] & XP_MATCHED) != XP_MATCHED) {\n\n if(fCurrentStep[i] > descendantStep) {\n\n fCurrentStep[i] = descendantStep;\n continue;\n }\n\n fNoMatchDepth[i]++;\n }\n }\n }\n}\n\nvoid XPathMatcher::endElement(const XMLElementDecl& elemDecl,\n const XMLCh* const elemContent) {\n\n for(int i = 0; i < (int) fLocationPathSize; i++) {\n\n \/\/ go back a step\n fCurrentStep[i] = fStepIndexes->elementAt(i)->pop();\n\n \/\/ don't do anything, if not matching\n if (fNoMatchDepth[i] > 0) {\n fNoMatchDepth[i]--;\n }\n \/\/ signal match, if appropriate\n else {\n\n int j=0;\n for(; jgetDatatypeValidator();\n bool isNillable = (((SchemaElementDecl *) &elemDecl)->getMiscFlags() & SchemaSymbols::XSD_NILLABLE) != 0;\n\n matched(elemContent, dv, isNillable);\n fMatched[i] = 0;\n }\n }\n}\n\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ XPathMatcher: Match methods\n\/\/ ---------------------------------------------------------------------------\nint XPathMatcher::isMatched() {\n\n \/\/ xpath has been matched if any one of the members of the union have matched.\n for (int i=0; i < (int) fLocationPathSize; i++) {\n if (((fMatched[i] & XP_MATCHED) == XP_MATCHED)\n && ((fMatched[i] & XP_MATCHED_DP) != XP_MATCHED_DP))\n return fMatched[i];\n }\n\n return 0;\n}\n\nvoid XPathMatcher::matched(const XMLCh* const,\n DatatypeValidator* const,\n const bool) {\n return;\n}\n\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ XPathMatcher: Match methods\n\/\/ ---------------------------------------------------------------------------\nint XPathMatcher::getInitialDepth() const\n{\n ThrowXMLwithMemMgr(RuntimeException, XMLExcepts::Regex_NotSupported, fMemoryManager);\n return 0; \/\/ to make some compilers happy\n}\n\nXERCES_CPP_NAMESPACE_END\n\n\/**\n * End of file XPathMatcher.cpp\n *\/\n\nChange uppercase enums that were conflicting with other products.\/*\n * Copyright 2001,2004 The Apache Software Foundation.\n * \n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * \n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n\/*\n * $Id$\n *\/\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ Includes\n\/\/ ---------------------------------------------------------------------------\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nXERCES_CPP_NAMESPACE_BEGIN\n\ntypedef JanitorMemFunCall CleanupType;\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ XPathMatcher: Constructors and Destructor\n\/\/ ---------------------------------------------------------------------------\nXPathMatcher::XPathMatcher( XercesXPath* const xpath\n , MemoryManager* const manager)\n : fLocationPathSize(0)\n , fMatched(0)\n , fNoMatchDepth(0)\n , fCurrentStep(0)\n , fStepIndexes(0)\n , fLocationPaths(0)\n , fIdentityConstraint(0)\n , fMemoryManager(manager)\n{\n CleanupType cleanup(this, &XPathMatcher::cleanUp);\n\n try {\n init(xpath);\n }\n catch(const OutOfMemoryException&)\n {\n cleanup.release();\n\n throw;\n }\n\n cleanup.release();\n}\n\n\nXPathMatcher::XPathMatcher(XercesXPath* const xpath,\n IdentityConstraint* const ic,\n\t\t\t\t\t\t MemoryManager* const manager)\n : fLocationPathSize(0)\n , fMatched(0)\n , fNoMatchDepth(0)\n , fCurrentStep(0)\n , fStepIndexes(0)\n , fLocationPaths(0)\n , fIdentityConstraint(ic)\n , fMemoryManager(manager)\n{\n CleanupType cleanup(this, &XPathMatcher::cleanUp);\n\n try {\n init(xpath);\n }\n catch(const OutOfMemoryException&)\n {\n cleanup.release();\n\n throw;\n }\n\n cleanup.release();\n}\n\n\nXPathMatcher::~XPathMatcher()\n{\n cleanUp();\n}\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ XPathMatcher: Helper methods\n\/\/ ---------------------------------------------------------------------------\nvoid XPathMatcher::init(XercesXPath* const xpath) {\n\n if (xpath) {\n\n fLocationPaths = xpath->getLocationPaths();\n fLocationPathSize = (fLocationPaths ? fLocationPaths->size() : 0);\n\n if (fLocationPathSize) {\n\n fStepIndexes = new (fMemoryManager) RefVectorOf >(fLocationPathSize, true, fMemoryManager);\n fCurrentStep = (int*) fMemoryManager->allocate\n (\n fLocationPathSize * sizeof(int)\n );\/\/new int[fLocationPathSize];\n fNoMatchDepth = (int*) fMemoryManager->allocate\n (\n fLocationPathSize * sizeof(int)\n );\/\/new int[fLocationPathSize];\n fMatched = (int*) fMemoryManager->allocate\n (\n fLocationPathSize * sizeof(int)\n );\/\/new int[fLocationPathSize];\n\n for(unsigned int i=0; i < fLocationPathSize; i++) {\n fStepIndexes->addElement(new (fMemoryManager) ValueStackOf(8, fMemoryManager));\n }\n }\n }\n}\n\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ XPathMatcher: XMLDocumentHandler methods\n\/\/ ---------------------------------------------------------------------------\nvoid XPathMatcher::startDocumentFragment() {\n\n for(unsigned int i = 0; i < fLocationPathSize; i++) {\n\n fStepIndexes->elementAt(i)->removeAllElements();\n fCurrentStep[i] = 0;\n fNoMatchDepth[i] = 0;\n fMatched[i] = 0;\n }\n}\n\nvoid XPathMatcher::startElement(const XMLElementDecl& elemDecl,\n const unsigned int urlId,\n const XMLCh* const elemPrefix,\n\t\t\t\t\t\t\t\tconst RefVectorOf& attrList,\n const unsigned int attrCount) {\n\n for (int i = 0; i < (int) fLocationPathSize; i++) {\n\n \/\/ push context\n int startStep = fCurrentStep[i];\n fStepIndexes->elementAt(i)->push(startStep);\n\n \/\/ try next xpath, if not matching\n if ((fMatched[i] & XP_MATCHED_D) == XP_MATCHED || fNoMatchDepth[i] > 0) {\n fNoMatchDepth[i]++;\n continue;\n }\n\n if((fMatched[i] & XP_MATCHED_D) == XP_MATCHED_D) {\n fMatched[i] = XP_MATCHED_DP;\n }\n\n \/\/ consume self::node() steps\n XercesLocationPath* locPath = fLocationPaths->elementAt(i);\n int stepSize = locPath->getStepSize();\n\n while (fCurrentStep[i] < stepSize &&\n locPath->getStep(fCurrentStep[i])->getAxisType() == XercesStep::AxisType_SELF) {\n fCurrentStep[i]++;\n }\n\n if (fCurrentStep[i] == stepSize) {\n\n fMatched[i] = XP_MATCHED;\n continue;\n }\n\n \/\/ now if the current step is a descendant step, we let the next\n \/\/ step do its thing; if it fails, we reset ourselves\n \/\/ to look at this step for next time we're called.\n \/\/ so first consume all descendants:\n int descendantStep = fCurrentStep[i];\n\n while (fCurrentStep[i] < stepSize &&\n locPath->getStep(fCurrentStep[i])->getAxisType() == XercesStep::AxisType_DESCENDANT) {\n fCurrentStep[i]++;\n }\n\n bool sawDescendant = fCurrentStep[i] > descendantStep;\n if (fCurrentStep[i] == stepSize) {\n\n fNoMatchDepth[i]++;\n continue;\n }\n\n \/\/ match child::... step, if haven't consumed any self::node()\n if ((fCurrentStep[i] == startStep || fCurrentStep[i] > descendantStep) &&\n locPath->getStep(fCurrentStep[i])->getAxisType() == XercesStep::AxisType_CHILD) {\n\n XercesStep* step = locPath->getStep(fCurrentStep[i]);\n XercesNodeTest* nodeTest = step->getNodeTest();\n\n if (nodeTest->getType() == XercesNodeTest::NodeType_QNAME) {\n\n QName elemQName(elemPrefix, elemDecl.getElementName()->getLocalPart(), urlId, fMemoryManager);\n\n\/\/ if (!(*(nodeTest->getName()) == *(elemDecl.getElementName()))) {\n if (!(*(nodeTest->getName()) == elemQName)) {\n\n if(fCurrentStep[i] > descendantStep) {\n fCurrentStep[i] = descendantStep;\n continue;\n }\n\n fNoMatchDepth[i]++;\n continue;\n }\n }\n\n fCurrentStep[i]++;\n }\n\n if (fCurrentStep[i] == stepSize) {\n\n if (sawDescendant) {\n\n fCurrentStep[i] = descendantStep;\n fMatched[i] = XP_MATCHED_D;\n }\n else {\n fMatched[i] = XP_MATCHED;\n }\n\n continue;\n }\n\n \/\/ match attribute::... step\n if (fCurrentStep[i] < stepSize &&\n locPath->getStep(fCurrentStep[i])->getAxisType() == XercesStep::AxisType_ATTRIBUTE) {\n\n if (attrCount) {\n\n XercesNodeTest* nodeTest = locPath->getStep(fCurrentStep[i])->getNodeTest();\n\n for (unsigned int attrIndex = 0; attrIndex < attrCount; attrIndex++) {\n\n const XMLAttr* curDef = attrList.elementAt(attrIndex);\n\n if (nodeTest->getType() != XercesNodeTest::NodeType_QNAME ||\n (*(nodeTest->getName()) == *(curDef->getAttName()))) {\n\n fCurrentStep[i]++;\n\n if (fCurrentStep[i] == stepSize) {\n\n fMatched[i] = XP_MATCHED_A;\n int j=0;\n\n for(; jgetName(), curDef->getURIId());\n DatatypeValidator* dv = (attDef) ? attDef->getDatatypeValidator() : 0;\n matched(curDef->getValue(), dv, false);\n }\n }\n break;\n }\n }\n }\n\n if ((fMatched[i] & XP_MATCHED) != XP_MATCHED) {\n\n if(fCurrentStep[i] > descendantStep) {\n\n fCurrentStep[i] = descendantStep;\n continue;\n }\n\n fNoMatchDepth[i]++;\n }\n }\n }\n}\n\nvoid XPathMatcher::endElement(const XMLElementDecl& elemDecl,\n const XMLCh* const elemContent) {\n\n for(int i = 0; i < (int) fLocationPathSize; i++) {\n\n \/\/ go back a step\n fCurrentStep[i] = fStepIndexes->elementAt(i)->pop();\n\n \/\/ don't do anything, if not matching\n if (fNoMatchDepth[i] > 0) {\n fNoMatchDepth[i]--;\n }\n \/\/ signal match, if appropriate\n else {\n\n int j=0;\n for(; jgetDatatypeValidator();\n bool isNillable = (((SchemaElementDecl *) &elemDecl)->getMiscFlags() & SchemaSymbols::XSD_NILLABLE) != 0;\n\n matched(elemContent, dv, isNillable);\n fMatched[i] = 0;\n }\n }\n}\n\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ XPathMatcher: Match methods\n\/\/ ---------------------------------------------------------------------------\nint XPathMatcher::isMatched() {\n\n \/\/ xpath has been matched if any one of the members of the union have matched.\n for (int i=0; i < (int) fLocationPathSize; i++) {\n if (((fMatched[i] & XP_MATCHED) == XP_MATCHED)\n && ((fMatched[i] & XP_MATCHED_DP) != XP_MATCHED_DP))\n return fMatched[i];\n }\n\n return 0;\n}\n\nvoid XPathMatcher::matched(const XMLCh* const,\n DatatypeValidator* const,\n const bool) {\n return;\n}\n\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ XPathMatcher: Match methods\n\/\/ ---------------------------------------------------------------------------\nint XPathMatcher::getInitialDepth() const\n{\n ThrowXMLwithMemMgr(RuntimeException, XMLExcepts::Regex_NotSupported, fMemoryManager);\n return 0; \/\/ to make some compilers happy\n}\n\nXERCES_CPP_NAMESPACE_END\n\n\/**\n * End of file XPathMatcher.cpp\n *\/\n\n<|endoftext|>"} {"text":"\/*ckwg +5\n * Copyright 2011 by Kitware, Inc. All Rights Reserved. Please refer to\n * KITWARE_LICENSE.TXT for licensing information, or contact General Counsel,\n * Kitware, Inc., 28 Corporate Drive, Clifton Park, NY 12065.\n *\/\n\n#include \"registration.h\"\n\n#include \"sync_schedule.h\"\n#include \"thread_per_process_schedule.h\"\n#include \"thread_pool_schedule.h\"\n\n#include \n\n#include \n\n#include \n\n\/**\n * \\file examples\/registration.cxx\n *\n * \\brief Register schedules for use.\n *\/\n\nusing namespace vistk;\n\nstatic schedule_t create_sync_schedule(config_t const& config, pipeline_t const& pipe);\nstatic schedule_t create_thread_per_process_schedule(config_t const& config, pipeline_t const& pipe);\nstatic schedule_t create_thread_pool_schedule(config_t const& config, pipeline_t const& pipe);\n\nvoid\nregister_schedules()\n{\n static schedule_registry::module_t const module_name = schedule_registry::module_t(\"example_schedules\");\n\n schedule_registry_t const registry = schedule_registry::self();\n\n if (registry->is_module_loaded(module_name))\n {\n return;\n }\n\n registry->register_schedule(\"sync\", \"Runs the pipeline synchronously\", create_sync_schedule);\n registry->register_schedule(\"thread_per_process\", \"Runs each process in its own thread\", create_thread_per_process_schedule);\n registry->register_schedule(\"thread_pool\", \"Uses a pool of threads to step processes\", create_thread_pool_schedule);\n\n registry->mark_module_as_loaded(module_name);\n}\n\nschedule_t\ncreate_sync_schedule(config_t const& config, pipeline_t const& pipe)\n{\n return boost::make_shared(config, pipe);\n}\n\nschedule_t\ncreate_thread_per_process_schedule(config_t const& config, pipeline_t const& pipe)\n{\n return boost::make_shared(config, pipe);\n}\n\nschedule_t\ncreate_thread_pool_schedule(config_t const& config, pipeline_t const& pipe)\n{\n return boost::make_shared(config, pipe);\n}\nUse the schedule registration macro\/*ckwg +5\n * Copyright 2011 by Kitware, Inc. All Rights Reserved. Please refer to\n * KITWARE_LICENSE.TXT for licensing information, or contact General Counsel,\n * Kitware, Inc., 28 Corporate Drive, Clifton Park, NY 12065.\n *\/\n\n#include \"registration.h\"\n\n#include \"sync_schedule.h\"\n#include \"thread_per_process_schedule.h\"\n#include \"thread_pool_schedule.h\"\n\n#include \n\n#include \n\n#include \n\n\/**\n * \\file examples\/registration.cxx\n *\n * \\brief Register schedules for use.\n *\/\n\nusing namespace vistk;\n\nvoid\nregister_schedules()\n{\n static schedule_registry::module_t const module_name = schedule_registry::module_t(\"example_schedules\");\n\n schedule_registry_t const registry = schedule_registry::self();\n\n if (registry->is_module_loaded(module_name))\n {\n return;\n }\n\n registry->register_schedule(\"sync\", \"Runs the pipeline synchronously\", CREATE_SCHEDULE(sync_schedule));\n registry->register_schedule(\"thread_per_process\", \"Runs each process in its own thread\", CREATE_SCHEDULE(thread_per_process_schedule));\n registry->register_schedule(\"thread_pool\", \"Uses a pool of threads to step processes\", CREATE_SCHEDULE(thread_pool_schedule));\n\n registry->mark_module_as_loaded(module_name);\n}\n<|endoftext|>"} {"text":"#include \"twister.h\"\n\nconst unsigned CYCLE = 0x100;\n\n\/\/Suggest we wrap these arrays inside an fsm or test base class \nconst unsigned C_TRANS_ = 0xff;\nint block_units[][0x10] = {\n\t0x74, 0x63, 0x69, 0x67, 0x72, 0x68, 0x6e, 0x6c, 0x61, 0x67, 0x74, 0x6c, 0x69, 0x73, 0x61, 0x61, 0x6f, 0x6d, 0x6f, 0x72, 0x6e, 0x72, 0x69, 0x6d, 0x6e, 0x6e, 0x65, 0x74, 0x72, 0x6e, 0x6b, 0x73, 0x61, 0x6f, 0x65, 0x69, 0x73, 0x64, 0x6c, 0x65, 0x69, 0x6b, 0x68, 0x68, 0x68, 0x65, 0x72, 0x64, 0x66, 0x74, 0x61, 0x73, 0x6f, 0x69, 0x65, 0x74, 0x69, 0x68, 0x6e, 0x65, 0x62, 0x74, 0x6b, 0x65\n };\nint triad_units[][0x03] = {\n\t0x31, 0xfe, 0x45, 0x74, 0x68, 0x65, 0x74, 0x68, 0x61, 0x65, 0x74, 0x68, 0x66, 0x6f, 0x72, 0x65, 0x73, 0x74, 0x69, 0x6e, 0x67, 0x65, 0x72, 0x65, 0x68, 0x61, 0x74, 0x68, 0x69, 0x73, 0x1a, 0x36, 0x49, 0x91, 0x43, 0x53\n};\nconst int transition_seq[] = { 0xce, 0xab, 0xdf, 0xcf, 0xee,\n 0xcf, 0xad, 0xdf, 0xff, 0xce, \n 0x32, 0x40, 0xd3, 0x27, 0x82, \n 0xda, 0xee, 0xff, 0xfc, 0xbf, \n 0x1c, 0x90, 0x13, 0x4a, 0xa5, \n 0xe0, 0x21, 0x9f, 0xe1, 0xc6, \n 0xaf, 0x05, 0x81, 0xf0, 0xee, \n 0xe4, 0x38, 0x1f, 0x60, 0x24, \n 0x0c, 0x35, 0x51, 0x32, 0xcf, \n 0x12, 0x9a, 0x30, 0x44, 0x72, \n 0x51, 0x3c, 0x61, 0x2d, 0x5f, \n 0x04, 0x1c, 0x52, 0xca, 0xdf, \n 0x12, 0x0b, 0x30, 0xa0, 0x1e, \n 0x03, 0x14, 0x09, 0x73, 0x23, \n 0xf2, 0xca, 0xa2, 0x51, 0xc6, \n 0x01, 0xdf, 0x41, 0x96, 0xa0, \n 0x51, 0x19, 0x71, 0x23, 0x47, \n 0xcb, 0xbd, 0xba, 0xac, 0xdf, \n\t\t\t 0xdf, 0xde, 0xcd, 0xfd, 0xca };\n\nint ENTRY_LINK__ = 0x05;\nint ENTRY_LINK__TEST = 0x09;\nint ENTRY_C_REF_ECM = 0x10;\nint ENTRY_C_REF_ECM_TEST = 0x03;\nint ENTRY_C_OUTER = 0x51;\nint ENTRY_C_OUTER_PROD = 0x41;\nint ENTRY_C_OUTER_PROD_TEST = 0x33;\nint ENTRY_C_OUTER_PROD_TOR_TEST = 0x57;\nint ENTRY_A_OUTER_PROD_TOR_TEST = 0xc9;\nint ENTRY_B_OUTER_PROD_EUC_TEST = 0xaf;\nint ENTRY_C_OUTER_PROD_EUC_TEST = 0xa1;\nint ENTRY_C_INNER_PROD_EUC_TEST = 0xc5;\nint ENTRY_C_INNER_PROD_ELIP_TEST = 0xa2;\nint ENTRY_C_INNER_PROD_RELAY_TEST = 0xf5;\nint ENTRY_C_BLOCK_REL_FLAG_TEST = 0x0fffffff;\nint ENTRY_C_BLOCK_REL_FLAG_VECTOR = 0x0effffff;\n\n\n\nunsigned reflect(unsigned center, unsigned (*r)(unsigned))\n{\n return (*r)(center)^center;\n}\nunsigned char base(unsigned char a, unsigned char (*s)(unsigned char), int pos)\n{\n\treturn (*s)(pos)^a;\n}\n\nvoid transHomExt(vector& data, unsigned char (*f)(unsigned char), unsigned char (*g)(unsigned char))\n{\n for(unsigned i = 0; i& data, unsigned char (*f)(unsigned char), unsigned char (*g)(unsigned char))\n{\n for(unsigned i = 0; i& data, unsigned char (*f)(unsigned char))\n{\n for(unsigned i = 0; i f_dist(vector& in)\n{\n vector fdist;\n fdist.resize(256);\n for(unsigned i = 0; i& v) \n{\n double entropy = 0;\n double p;\n\n for(unsigned i = 0; i < v.size(); i++) \n {\n p = v[i] \/ 100;\n if (p == 0) continue;\n entropy += p * std::log(p) \/ std::log(2);\n }\n return -entropy;\n}\nvoid rms(const string& s, string& r)\n{\n for(unsigned int i=0; i freq(256,0);\n for(unsigned int i=0; i extended_gcd(int __alpha, int __beta, int (*col)(int x, int y))\n{\n if(__alpha == 0) return make_tuple(__beta,0,1);\n int __com=0; \n int x=0; \n int y=0;\n tie(__com, x, y) = extended_gcd(__beta%__alpha, __alpha, col);\n return make_tuple(__com, y-(__beta\/__alpha)*x, x);\n}\n\nstd::tuple extended_gcd(int __alpha, int __beta)\n{\n if(__alpha == 0) return make_tuple(__beta,0,1);\n int __com=0; \n int x=0; \n int y=0;\n tie(__com, x, y) = extended_gcd(__beta%__alpha, __alpha);\n return make_tuple(__com, y-(__beta\/__alpha)*x, x);\n}\nblock rel, flag test, ext#include \"twister.h\"\n\nconst unsigned CYCLE = 0x100;\n\n\/\/Suggest we wrap these arrays inside an fsm or test base class \nconst unsigned C_TRANS_ = 0xff;\nint block_units[][0x10] = {\n\t0x74, 0x63, 0x69, 0x67, 0x72, 0x68, 0x6e, 0x6c, 0x61, 0x67, 0x74, 0x6c, 0x69, 0x73, 0x61, 0x61, 0x6f, 0x6d, 0x6f, 0x72, 0x6e, 0x72, 0x69, 0x6d, 0x6e, 0x6e, 0x65, 0x74, 0x72, 0x6e, 0x6b, 0x73, 0x61, 0x6f, 0x65, 0x69, 0x73, 0x64, 0x6c, 0x65, 0x69, 0x6b, 0x68, 0x68, 0x68, 0x65, 0x72, 0x64, 0x66, 0x74, 0x61, 0x73, 0x6f, 0x69, 0x65, 0x74, 0x69, 0x68, 0x6e, 0x65, 0x62, 0x74, 0x6b, 0x65\n };\nint triad_units[][0x03] = {\n\t0x31, 0xfe, 0x45, 0x74, 0x68, 0x65, 0x74, 0x68, 0x61, 0x65, 0x74, 0x68, 0x66, 0x6f, 0x72, 0x65, 0x73, 0x74, 0x69, 0x6e, 0x67, 0x65, 0x72, 0x65, 0x68, 0x61, 0x74, 0x68, 0x69, 0x73, 0x1a, 0x36, 0x49, 0x91, 0x43, 0x53\n};\nconst int transition_seq[] = { 0xce, 0xab, 0xdf, 0xcf, 0xee,\n 0xcf, 0xad, 0xdf, 0xff, 0xce, \n 0x32, 0x40, 0xd3, 0x27, 0x82, \n 0xda, 0xee, 0xff, 0xfc, 0xbf, \n 0x1c, 0x90, 0x13, 0x4a, 0xa5, \n 0xe0, 0x21, 0x9f, 0xe1, 0xc6, \n 0xaf, 0x05, 0x81, 0xf0, 0xee, \n 0xe4, 0x38, 0x1f, 0x60, 0x24, \n 0x0c, 0x35, 0x51, 0x32, 0xcf, \n 0x12, 0x9a, 0x30, 0x44, 0x72, \n 0x51, 0x3c, 0x61, 0x2d, 0x5f, \n 0x04, 0x1c, 0x52, 0xca, 0xdf, \n 0x12, 0x0b, 0x30, 0xa0, 0x1e, \n 0x03, 0x14, 0x09, 0x73, 0x23, \n 0xf2, 0xca, 0xa2, 0x51, 0xc6, \n 0x01, 0xdf, 0x41, 0x96, 0xa0, \n 0x51, 0x19, 0x71, 0x23, 0x47, \n 0xcb, 0xbd, 0xba, 0xac, 0xdf, \n\t\t\t 0xdf, 0xde, 0xcd, 0xfd, 0xca };\n\nint ENTRY_LINK__ = 0x05;\nint ENTRY_LINK__TEST = 0x09;\nint ENTRY_C_REF_ECM = 0x10;\nint ENTRY_C_REF_ECM_TEST = 0x03;\nint ENTRY_C_OUTER = 0x51;\nint ENTRY_C_OUTER_PROD = 0x41;\nint ENTRY_C_OUTER_PROD_TEST = 0x33;\nint ENTRY_C_OUTER_PROD_TOR_TEST = 0x57;\nint ENTRY_A_OUTER_PROD_TOR_TEST = 0xc9;\nint ENTRY_B_OUTER_PROD_EUC_TEST = 0xaf;\nint ENTRY_C_OUTER_PROD_EUC_TEST = 0xa1;\nint ENTRY_C_INNER_PROD_EUC_TEST = 0xc5;\nint ENTRY_C_INNER_PROD_ELIP_TEST = 0xa2;\nint ENTRY_C_INNER_PROD_RELAY_TEST = 0xf5;\nint ENTRY_C_BLOCK_REL_FLAG_TEST = 0x0fffffff;\nint ENTRY_C_BLOCK_REL_FLAG_VECTOR = 0x0effffff;\n\n\n\nunsigned reflect(unsigned center, unsigned (*r)(unsigned))\n{\n return (*r)(center)^center;\n}\nunsigned char base(unsigned char a, unsigned char (*s)(unsigned char), int pos)\n{\n\treturn (*s)(pos)^a;\n}\n\nvoid transHomExt(vector& data, unsigned char (*f)(unsigned char), unsigned char (*g)(unsigned char))\n{\n for(unsigned i = 0; i& data, unsigned char (*f)(unsigned char), unsigned char (*g)(unsigned char))\n{\n for(unsigned i = 0; i& data, unsigned char (*f)(unsigned char))\n{\n for(unsigned i = 0; i f_dist(vector& in)\n{\n vector fdist;\n fdist.resize(256);\n for(unsigned i = 0; i& v) \n{\n double entropy = 0;\n double p;\n\n for(unsigned i = 0; i < v.size(); i++) \n {\n p = v[i] \/ 100;\n if (p == 0) continue;\n entropy += p * std::log(p) \/ std::log(2);\n }\n return -entropy;\n}\nvoid rms(const string& s, string& r)\n{\n for(unsigned int i=0; i freq(256,0);\n for(unsigned int i=0; i extended_gcd(int __alpha, int __beta, int (*col)(int x, int y))\n{\n if(__alpha == 0) return make_tuple(__beta,0,1);\n int __com=0; \n int x=0; \n int y=0;\n tie(__com, x, y) = extended_gcd(__beta%__alpha, __alpha, col);\n return make_tuple(__com, y-(__beta\/__alpha)*x, x);\n}\n\nstd::tuple extended_gcd(int __alpha, int __beta)\n{\n if(__alpha == 0) return make_tuple(__beta,0,1);\n int __com=0; \n int x=0; \n int y=0;\n tie(__com, x, y) = extended_gcd(__beta%__alpha, __alpha);\n return make_tuple(__com, y-(__beta\/__alpha)*x, x);\n}\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2012 The Bitcoin developers\n\/\/ Distributed under the MIT\/X11 software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n#include \n\n#include \"version.h\"\n\n\/\/ Name of client reported in the 'version' message. Report the same name\n\/\/ for both bitcoind and bitcoin-qt, to make it harder for attackers to\n\/\/ target servers or GUI users specifically.\nconst std::string CLIENT_NAME(\"Dopecoin\");\n\n\/\/ Client version number\n#define CLIENT_VERSION_SUFFIX \"-supr\"\n\n\n\/\/ The following part of the code determines the CLIENT_BUILD variable.\n\/\/ Several mechanisms are used for this:\n\/\/ * first, if HAVE_BUILD_INFO is defined, include build.h, a file that is\n\/\/ generated by the build environment, possibly containing the output\n\/\/ of git-describe in a macro called BUILD_DESC\n\/\/ * secondly, if this is an exported version of the code, GIT_ARCHIVE will\n\/\/ be defined (automatically using the export-subst git attribute), and\n\/\/ GIT_COMMIT will contain the commit id.\n\/\/ * then, three options exist for determining CLIENT_BUILD:\n\/\/ * if BUILD_DESC is defined, use that literally (output of git-describe)\n\/\/ * if not, but GIT_COMMIT is defined, use v[maj].[min].[rev].[build]-g[commit]\n\/\/ * otherwise, use v[maj].[min].[rev].[build]-unk\n\/\/ finally CLIENT_VERSION_SUFFIX is added\n\n\/\/ First, include build.h if requested\n#ifdef HAVE_BUILD_INFO\n# include \"build.h\"\n#endif\n\n\/\/ git will put \"#define GIT_ARCHIVE 1\" on the next line inside archives. \n#define GIT_ARCHIVE 1\n#ifdef GIT_ARCHIVE\n# define GIT_COMMIT_ID \"\"\n# define GIT_COMMIT_DATE \"2014\/07\/18\"\n#endif\n\n#define BUILD_DESC_FROM_COMMIT(maj,min,rev,build,commit) \\\n \"v\" DO_STRINGIZE(maj) \".\" DO_STRINGIZE(min) \".\" DO_STRINGIZE(rev) \".\" DO_STRINGIZE(build) \"\" commit\n\n#define BUILD_DESC_FROM_UNKNOWN(maj,min,rev,build) \\\n \"v\" DO_STRINGIZE(maj) \".\" DO_STRINGIZE(min) \".\" DO_STRINGIZE(rev) \".\" DO_STRINGIZE(build) \"\"\n\n#ifndef BUILD_DESC\n# ifdef GIT_COMMIT_ID\n# define BUILD_DESC BUILD_DESC_FROM_COMMIT(DISPLAY_VERSION_MAJOR, DISPLAY_VERSION_MINOR, DISPLAY_VERSION_REVISION, DISPLAY_VERSION_BUILD, GIT_COMMIT_ID)\n# else\n# define BUILD_DESC BUILD_DESC_FROM_UNKNOWN(DISPLAY_VERSION_MAJOR, DISPLAY_VERSION_MINOR, DISPLAY_VERSION_REVISION, DISPLAY_VERSION_BUILD)\n# endif\n#endif\n\n#ifndef BUILD_DATE\n# ifdef GIT_COMMIT_DATE\n# define BUILD_DATE GIT_COMMIT_DATE\n# else\n# define BUILD_DATE __DATE__ \", \" __TIME__\n# endif\n#endif\n\nconst std::string CLIENT_BUILD(BUILD_DESC CLIENT_VERSION_SUFFIX);\nconst std::string CLIENT_DATE(BUILD_DATE);\nFix build date\/\/ Copyright (c) 2012 The Bitcoin developers\n\/\/ Distributed under the MIT\/X11 software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n#include \n\n#include \"version.h\"\n\n\/\/ Name of client reported in the 'version' message. Report the same name\n\/\/ for both bitcoind and bitcoin-qt, to make it harder for attackers to\n\/\/ target servers or GUI users specifically.\nconst std::string CLIENT_NAME(\"Dopecoin\");\n\n\/\/ Client version number\n#define CLIENT_VERSION_SUFFIX \"-supr\"\n\n\n\/\/ The following part of the code determines the CLIENT_BUILD variable.\n\/\/ Several mechanisms are used for this:\n\/\/ * first, if HAVE_BUILD_INFO is defined, include build.h, a file that is\n\/\/ generated by the build environment, possibly containing the output\n\/\/ of git-describe in a macro called BUILD_DESC\n\/\/ * secondly, if this is an exported version of the code, GIT_ARCHIVE will\n\/\/ be defined (automatically using the export-subst git attribute), and\n\/\/ GIT_COMMIT will contain the commit id.\n\/\/ * then, three options exist for determining CLIENT_BUILD:\n\/\/ * if BUILD_DESC is defined, use that literally (output of git-describe)\n\/\/ * if not, but GIT_COMMIT is defined, use v[maj].[min].[rev].[build]-g[commit]\n\/\/ * otherwise, use v[maj].[min].[rev].[build]-unk\n\/\/ finally CLIENT_VERSION_SUFFIX is added\n\n\/\/ First, include build.h if requested\n#ifdef HAVE_BUILD_INFO\n# include \"build.h\"\n#endif\n\n\/\/ git will put \"#define GIT_ARCHIVE 1\" on the next line inside archives. \n\/\/ #define GIT_ARCHIVE 1\n#ifdef GIT_ARCHIVE\n# define GIT_COMMIT_ID \"\"\n# define GIT_COMMIT_DATE \"2014\/07\/18\"\n#endif\n\n#define BUILD_DESC_FROM_COMMIT(maj,min,rev,build,commit) \\\n \"v\" DO_STRINGIZE(maj) \".\" DO_STRINGIZE(min) \".\" DO_STRINGIZE(rev) \".\" DO_STRINGIZE(build) \"\" commit\n\n#define BUILD_DESC_FROM_UNKNOWN(maj,min,rev,build) \\\n \"v\" DO_STRINGIZE(maj) \".\" DO_STRINGIZE(min) \".\" DO_STRINGIZE(rev) \".\" DO_STRINGIZE(build) \"\"\n\n#ifndef BUILD_DESC\n# ifdef GIT_COMMIT_ID\n# define BUILD_DESC BUILD_DESC_FROM_COMMIT(DISPLAY_VERSION_MAJOR, DISPLAY_VERSION_MINOR, DISPLAY_VERSION_REVISION, DISPLAY_VERSION_BUILD, GIT_COMMIT_ID)\n# else\n# define BUILD_DESC BUILD_DESC_FROM_UNKNOWN(DISPLAY_VERSION_MAJOR, DISPLAY_VERSION_MINOR, DISPLAY_VERSION_REVISION, DISPLAY_VERSION_BUILD)\n# endif\n#endif\n\n#ifndef BUILD_DATE\n# ifdef GIT_COMMIT_DATE\n# define BUILD_DATE GIT_COMMIT_DATE\n# else\n# define BUILD_DATE __DATE__ \", \" __TIME__\n# endif\n#endif\n\nconst std::string CLIENT_BUILD(BUILD_DESC CLIENT_VERSION_SUFFIX);\nconst std::string CLIENT_DATE(BUILD_DATE);\n<|endoftext|>"} {"text":"\/\/\r\n\/\/ Copyright Silvin Lubecki 2010\r\n\/\/\r\n\/\/ Distributed under the Boost Software License, Version 1.0. (See\r\n\/\/ accompanying file LICENSE_1_0.txt or copy at\r\n\/\/ http:\/\/www.boost.org\/LICENSE_1_0.txt)\r\n\/\/\r\n\r\n#include \"test.h\"\r\n#include \"openclam\/cl.hpp\"\r\n\r\nBOOST_AUTO_TEST_CASE( kernel_keyword_substitution_test )\r\n{\r\n const std::string expected =\r\n \"kernel void MyKernel() \"\r\n \"{ \"\r\n \"}\";\r\n const std::string actual = KERNEL( MyKernel,\r\n kernel void MyKernel()\r\n {\r\n } );\r\n BOOST_CHECK_EQUAL( actual, expected );\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE( __kernel_keyword_substitution_test )\r\n{\r\n const std::string expected =\r\n \"__kernel void MyKernel() \"\r\n \"{ \"\r\n \"}\";\r\n const std::string actual = KERNEL( MyKernel,\r\n __kernel void MyKernel()\r\n {\r\n } );\r\n BOOST_CHECK_EQUAL( actual, expected );\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE( global_keyword_substitution_test )\r\n{\r\n const std::string expected =\r\n \"__kernel void MyKernel( global const float* a ) \"\r\n \"{ \"\r\n \"a; \"\r\n \"}\";\r\n const std::string actual = KERNEL( MyKernel,\r\n __kernel void MyKernel( global const float* a )\r\n {\r\n a;\r\n } );\r\n BOOST_CHECK_EQUAL( actual, expected );\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE( __global_keyword_substitution_test )\r\n{\r\n const std::string expected =\r\n \"__kernel void MyKernel( __global const float* a ) \"\r\n \"{ \"\r\n \"a; \"\r\n \"}\";\r\n const std::string actual = KERNEL( MyKernel,\r\n __kernel void MyKernel( __global const float* a )\r\n {\r\n a;\r\n } );\r\n BOOST_CHECK_EQUAL( actual, expected );\r\n}\r\nadd a commented test related to issue 1\/\/\r\n\/\/ Copyright Silvin Lubecki 2010\r\n\/\/\r\n\/\/ Distributed under the Boost Software License, Version 1.0. (See\r\n\/\/ accompanying file LICENSE_1_0.txt or copy at\r\n\/\/ http:\/\/www.boost.org\/LICENSE_1_0.txt)\r\n\/\/\r\n\r\n#include \"test.h\"\r\n#include \"openclam\/cl.hpp\"\r\n\r\n\/\/BOOST_AUTO_TEST_CASE( kernel_keyword_is_a_valid_identifier ) \/\/ $$$$ 27-02-2010 SILVIN: uncomment this test related to issue 1 (http:\/\/code.google.com\/p\/openclam\/issues\/detail?id=1)\r\n\/\/{\r\n\/\/ const std::string kernel = \"\";\r\n\/\/ const std::string __kernel = \"\";\r\n\/\/ const std::string global = \"\";\r\n\/\/ const std::string __global = \"\";\r\n\/\/}\r\n\r\nBOOST_AUTO_TEST_CASE( kernel_keyword_substitution_test )\r\n{\r\n const std::string expected =\r\n \"kernel void MyKernel() \"\r\n \"{ \"\r\n \"}\";\r\n const std::string actual = KERNEL( MyKernel,\r\n kernel void MyKernel()\r\n {\r\n } );\r\n BOOST_CHECK_EQUAL( actual, expected );\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE( __kernel_keyword_substitution_test )\r\n{\r\n const std::string expected =\r\n \"__kernel void MyKernel() \"\r\n \"{ \"\r\n \"}\";\r\n const std::string actual = KERNEL( MyKernel,\r\n __kernel void MyKernel()\r\n {\r\n } );\r\n BOOST_CHECK_EQUAL( actual, expected );\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE( global_keyword_substitution_test )\r\n{\r\n const std::string expected =\r\n \"__kernel void MyKernel( global const float* a ) \"\r\n \"{ \"\r\n \"a; \"\r\n \"}\";\r\n const std::string actual = KERNEL( MyKernel,\r\n __kernel void MyKernel( global const float* a )\r\n {\r\n a;\r\n } );\r\n BOOST_CHECK_EQUAL( actual, expected );\r\n}\r\n\r\nBOOST_AUTO_TEST_CASE( __global_keyword_substitution_test )\r\n{\r\n const std::string expected =\r\n \"__kernel void MyKernel( __global const float* a ) \"\r\n \"{ \"\r\n \"a; \"\r\n \"}\";\r\n const std::string actual = KERNEL( MyKernel,\r\n __kernel void MyKernel( __global const float* a )\r\n {\r\n a;\r\n } );\r\n BOOST_CHECK_EQUAL( actual, expected );\r\n}\r\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n\n#include \n#include \n\n#include \n#include \n#include \n#include \n\n\/*namespace validate {\n static bool algorithm(const char* flagname, int32 value) {\n if (value > 0 && value < 32768) \/\/ value is ok\n return true;\n printf(\"Invalid value for --%s: %d\\n\", flagname, (int)value);\n return false;\n }\n static const bool algorithm_dummy = RegisterFlagValidator(&FLAGS_algorithm, &algorithm);\n}*\/\n\nDEFINE_string(algorithm, \"\", \"Algorithm to use for (de)compression. See --list for a complete list of them.\");\nDEFINE_bool(decompress, false, \"Decompress input instead of compressing it.\");\nDEFINE_string(output, \"\", \"Choose output filename instead the the default generated one of .tdc or stdout.\");\nDEFINE_bool(stats, false, \"Print statistics to stdout.\");\nDEFINE_bool(force, false, \"Overwrite output even if it exists.\");\nDEFINE_bool(list, false, \"List all compression algorithms supported by this tool.\");\nDEFINE_bool(raw, false, \"Do not emit an header into the output file when compressing.\");\nDEFINE_bool(stdin, false, \"Read from stdin instead of trying to open a file.\");\nDEFINE_bool(stdout, false, \"Output to stdout instead of writing to a file\");\n\nnamespace tudocomp_driver {\n\nusing namespace tudocomp;\n\nconst std::string COMPRESSED_FILE_ENDING = \"tdc\";\n\nstatic void exit(std::string msg) {\n \/\/ TODO: Replace with more specific logic-error-exception\n throw std::runtime_error(msg);\n}\n\nstatic void validate_flag_combination() {\n auto err = [](std::string s) {\n exit(s);\n };\n\n if (!FLAGS_list) {\n if (!FLAGS_decompress && (std::string(FLAGS_algorithm) == \"\")) {\n err(\"Need to give an algorithm for compression\");\n }\n if (FLAGS_decompress && FLAGS_raw && (std::string(FLAGS_algorithm) == \"\")) {\n err(\"Need to give an algorithm for raw decompression\");\n }\n }\n}\n\nstatic bool fexists(std::string filename)\n{\n std::ifstream ifile(filename);\n return bool(ifile);\n}\n\nstatic bool check_for_file_already_exist(std::string& ofile,\n bool allow_overwrite) {\n \/\/ Don't accidentially overwrite files\n if (!allow_overwrite && fexists(ofile)) {\n std::cerr << \"Outputfile already exists\\n\";\n return false;\n }\n return true;\n}\n\n} \/\/ namespace tudocomp_driver\n\nint main(int argc, char** argv)\n{\n using namespace tudocomp_driver;\n\n google::InitGoogleLogging(argv[0]);\n int first_cmd_arg = google::ParseCommandLineFlags(&argc, &argv, true);\n\n try {\n validate_flag_combination();\n\n std::map algorithm_options;\n\n \/*for (auto& os : string_args(\"--option\")) {\n std::vector options;\n boost::split(options, os, boost::is_any_of(\",\"));\n for (auto& o : options) {\n std::vector key_value;\n boost::split(key_value, o, boost::is_any_of(\"=\"));\n CHECK(key_value.size() == 2);\n algorithm_options.emplace(key_value[0], key_value[1]);\n }\n }*\/\n\n \/*if (arg_exists(\"--help\")) {\n show_help();\n return 0;\n }*\/\n\n Env algorithm_env(algorithm_options, {});\n\n \/\/ Set up algorithms\n AlgorithmDb root;\n Registry registry {&root};\n register_algos(registry);\n\n if (FLAGS_list) {\n std::cout << \"This build supports the following algorithms:\\n\";\n std::cout << std::endl;\n\n for (auto& e: registry.get_sub_algos()) {\n e.print_to(std::cout, 0);\n }\n\n return 0;\n }\n\n bool print_stats = FLAGS_stats;\n int alphabet_size = 0;\n\n bool do_compress = !FLAGS_decompress;\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ Select algorithm\n\n bool do_raw = FLAGS_raw;\n\n std::string algorithm_id;\n std::unique_ptr algo;\n\n if (do_raw || do_compress) {\n algorithm_id = FLAGS_algorithm;\n algo = select_algo_or_exit(registry, algorithm_env, algorithm_id);\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ Select where the input comes from\n\n std::string file;\n\n if ((!FLAGS_stdin) && (first_cmd_arg < argc)) {\n file = argv[first_cmd_arg];\n if (!fexists(file)) {\n std::cerr << \"input file \" << file << \" does not exist\\n\";\n return 1;\n }\n } else if (!FLAGS_stdin) {\n std::cerr << \"No input file given\\n\";\n return 1;\n }\n\n bool use_stdin = FLAGS_stdin;\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ Select where the output goes to\n\n std::string ofile;\n bool use_stdout = FLAGS_stdout;\n bool use_explict_output = std::string(FLAGS_output) != \"\" ;\n\n if (use_explict_output) {\n \/\/ Output to manually specifed file\n ofile = FLAGS_output;\n } else if (!use_stdin && do_compress) {\n \/\/ Output to a automatically determined file\n ofile = file + \".\" + COMPRESSED_FILE_ENDING;\n } else if (!use_stdin && !do_compress && !use_stdout) {\n std::cerr << \"Need to specify a output filename\\n\";\n return 1;\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ open streams\n\n using clk = std::chrono::high_resolution_clock;\n\n clk::time_point start_time = clk::now();\n clk::time_point setup_time;\n clk::time_point comp_time;\n clk::time_point end_time;\n\n {\n std::vector stream_buffer;\n Input inp;\n\n if (use_stdin) {\n \/\/ Input from stdin\n stream_buffer = read_stream_to_stl_byte_container<\n std::vector\n >(std::cin);\n inp = Input::from_memory(stream_buffer);\n } else {\n \/\/ Input from specified file\n inp = Input::from_path(file);\n }\n\n Output out;\n if (use_stdout) {\n \/\/ Output to stdout\n out = Output::from_stream(std::cout);\n } else {\n \/\/ Output to specified file\n bool force = FLAGS_force;\n if (!check_for_file_already_exist(ofile, force)) {\n return 1;\n } else {\n out = Output::from_path(ofile, true);\n }\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ call into actual library\n\n if (do_compress) {\n if (print_stats) {\n alphabet_size = 0; \/\/ count_alphabet_size(inp_vec);\n }\n\n if (!do_raw) {\n CHECK(algorithm_id.find('%') == std::string::npos);\n\n auto o_stream = out.as_stream();\n (*o_stream) << algorithm_id << '%';\n }\n\n setup_time = clk::now();\n\n algo->compress(inp, out);\n\n comp_time = clk::now();\n } else {\n if (!do_raw) {\n auto i_stream = inp.as_stream();\n std::string algorithm_header;\n\n char c;\n size_t sanity_size_check = 0;\n bool err = false;\n while ((*i_stream).get(c)) {\n err = false;\n if (sanity_size_check > 1023) {\n err = true;\n break;\n } else if (c == '%') {\n break;\n } else {\n algorithm_header.push_back(c);\n }\n sanity_size_check++;\n err = true;\n }\n if (err) {\n exit(\"Input did not have an algorithm header!\");\n }\n algorithm_id = std::move(algorithm_header);\n algo = select_algo_or_exit(registry, algorithm_env, algorithm_id);\n }\n\n setup_time = clk::now();\n\n algo->decompress(inp, out);\n\n comp_time = clk::now();\n }\n }\n\n end_time = clk::now();\n\n if (print_stats) {\n auto setup_duration = setup_time - start_time;\n auto comp_duration = comp_time - setup_time;\n auto end_duration = end_time - comp_time;\n std::cout << \"---------------\\n\";\n std::cout << \"Config: \" << algorithm_id << std::endl;\n std::cout << \"---------------\\n\";\n auto inp_size = 0;\n if (use_stdin) {\n std::cout << \"input: \\n\";\n std::cout << \"input size: ? B\\n\";\n } else {\n inp_size = read_file_size(file);\n std::cout << \"input: \"<\\n\";\n std::cout << \"output size: ? B\\n\";\n } else {\n out_size = read_file_size(ofile);\n std::cout << \"output: \"<;\n using mildur = std::chrono::duration;\n using micdur = std::chrono::duration;\n\n if (t < milsec) {\n auto ct = std::chrono::duration_cast(t).count();\n std::cout << s <<\" time: \"<< ct << \" µs\\n\";\n } else if (t < sec) {\n auto ct = std::chrono::duration_cast(t).count();\n std::cout << s <<\" time: \"<< ct << \" ms\\n\";\n } else {\n auto ct = std::chrono::duration_cast(t).count();\n std::cout << s <<\" time: \"<< ct << \" s\\n\";\n }\n };\n\n std::cout << \"---------------\\n\";\n std::cout << \"Algorithm Known Options:\\n\";\n for (auto& pair : algorithm_env.get_known_options()) {\n std::cout << \" \" << pair << \"\\n\";\n }\n std::cout << \"Algorithm Given Options:\\n\";\n for (auto& pair : algorithm_env.get_options()) {\n std::cout << \" \" << pair.first << \" = \" << pair.second << \"\\n\";\n }\n\n std::cout << \"---------------\\n\";\n std::cout << \"Algorithm Stats:\\n\";\n for (auto& pair : algorithm_env.get_stats()) {\n std::cout << \" \" << pair.first << \": \" << pair.second << \"\\n\";\n }\n\n std::cout << \"---------------\\n\";\n print_time(\"startup\", setup_duration);\n print_time(\"compression\", comp_duration);\n print_time(\"teardown\", end_duration);\n std::cout << \"---------------\\n\";\n }\n } catch (std::exception& e) {\n std::cout << \"Error: \" << e.what() << '\\n';\n return 1;\n }\n\n return 0;\n}\nPurge unused boost includes from tudocomp_driver#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n\n#include \n#include \n#include \n#include \n\n\/*namespace validate {\n static bool algorithm(const char* flagname, int32 value) {\n if (value > 0 && value < 32768) \/\/ value is ok\n return true;\n printf(\"Invalid value for --%s: %d\\n\", flagname, (int)value);\n return false;\n }\n static const bool algorithm_dummy = RegisterFlagValidator(&FLAGS_algorithm, &algorithm);\n}*\/\n\nDEFINE_string(algorithm, \"\", \"Algorithm to use for (de)compression. See --list for a complete list of them.\");\nDEFINE_bool(decompress, false, \"Decompress input instead of compressing it.\");\nDEFINE_string(output, \"\", \"Choose output filename instead the the default generated one of .tdc or stdout.\");\nDEFINE_bool(stats, false, \"Print statistics to stdout.\");\nDEFINE_bool(force, false, \"Overwrite output even if it exists.\");\nDEFINE_bool(list, false, \"List all compression algorithms supported by this tool.\");\nDEFINE_bool(raw, false, \"Do not emit an header into the output file when compressing.\");\nDEFINE_bool(stdin, false, \"Read from stdin instead of trying to open a file.\");\nDEFINE_bool(stdout, false, \"Output to stdout instead of writing to a file\");\n\nnamespace tudocomp_driver {\n\nusing namespace tudocomp;\n\nconst std::string COMPRESSED_FILE_ENDING = \"tdc\";\n\nstatic void exit(std::string msg) {\n \/\/ TODO: Replace with more specific logic-error-exception\n throw std::runtime_error(msg);\n}\n\nstatic void validate_flag_combination() {\n auto err = [](std::string s) {\n exit(s);\n };\n\n if (!FLAGS_list) {\n if (!FLAGS_decompress && (std::string(FLAGS_algorithm) == \"\")) {\n err(\"Need to give an algorithm for compression\");\n }\n if (FLAGS_decompress && FLAGS_raw && (std::string(FLAGS_algorithm) == \"\")) {\n err(\"Need to give an algorithm for raw decompression\");\n }\n }\n}\n\nstatic bool fexists(std::string filename)\n{\n std::ifstream ifile(filename);\n return bool(ifile);\n}\n\nstatic bool check_for_file_already_exist(std::string& ofile,\n bool allow_overwrite) {\n \/\/ Don't accidentially overwrite files\n if (!allow_overwrite && fexists(ofile)) {\n std::cerr << \"Outputfile already exists\\n\";\n return false;\n }\n return true;\n}\n\n} \/\/ namespace tudocomp_driver\n\nint main(int argc, char** argv)\n{\n using namespace tudocomp_driver;\n\n google::InitGoogleLogging(argv[0]);\n int first_cmd_arg = google::ParseCommandLineFlags(&argc, &argv, true);\n\n try {\n validate_flag_combination();\n\n std::map algorithm_options;\n\n \/*for (auto& os : string_args(\"--option\")) {\n std::vector options;\n boost::split(options, os, boost::is_any_of(\",\"));\n for (auto& o : options) {\n std::vector key_value;\n boost::split(key_value, o, boost::is_any_of(\"=\"));\n CHECK(key_value.size() == 2);\n algorithm_options.emplace(key_value[0], key_value[1]);\n }\n }*\/\n\n \/*if (arg_exists(\"--help\")) {\n show_help();\n return 0;\n }*\/\n\n Env algorithm_env(algorithm_options, {});\n\n \/\/ Set up algorithms\n AlgorithmDb root;\n Registry registry {&root};\n register_algos(registry);\n\n if (FLAGS_list) {\n std::cout << \"This build supports the following algorithms:\\n\";\n std::cout << std::endl;\n\n for (auto& e: registry.get_sub_algos()) {\n e.print_to(std::cout, 0);\n }\n\n return 0;\n }\n\n bool print_stats = FLAGS_stats;\n int alphabet_size = 0;\n\n bool do_compress = !FLAGS_decompress;\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ Select algorithm\n\n bool do_raw = FLAGS_raw;\n\n std::string algorithm_id;\n std::unique_ptr algo;\n\n if (do_raw || do_compress) {\n algorithm_id = FLAGS_algorithm;\n algo = select_algo_or_exit(registry, algorithm_env, algorithm_id);\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ Select where the input comes from\n\n std::string file;\n\n if ((!FLAGS_stdin) && (first_cmd_arg < argc)) {\n file = argv[first_cmd_arg];\n if (!fexists(file)) {\n std::cerr << \"input file \" << file << \" does not exist\\n\";\n return 1;\n }\n } else if (!FLAGS_stdin) {\n std::cerr << \"No input file given\\n\";\n return 1;\n }\n\n bool use_stdin = FLAGS_stdin;\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ Select where the output goes to\n\n std::string ofile;\n bool use_stdout = FLAGS_stdout;\n bool use_explict_output = std::string(FLAGS_output) != \"\" ;\n\n if (use_explict_output) {\n \/\/ Output to manually specifed file\n ofile = FLAGS_output;\n } else if (!use_stdin && do_compress) {\n \/\/ Output to a automatically determined file\n ofile = file + \".\" + COMPRESSED_FILE_ENDING;\n } else if (!use_stdin && !do_compress && !use_stdout) {\n std::cerr << \"Need to specify a output filename\\n\";\n return 1;\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ open streams\n\n using clk = std::chrono::high_resolution_clock;\n\n clk::time_point start_time = clk::now();\n clk::time_point setup_time;\n clk::time_point comp_time;\n clk::time_point end_time;\n\n {\n std::vector stream_buffer;\n Input inp;\n\n if (use_stdin) {\n \/\/ Input from stdin\n stream_buffer = read_stream_to_stl_byte_container<\n std::vector\n >(std::cin);\n inp = Input::from_memory(stream_buffer);\n } else {\n \/\/ Input from specified file\n inp = Input::from_path(file);\n }\n\n Output out;\n if (use_stdout) {\n \/\/ Output to stdout\n out = Output::from_stream(std::cout);\n } else {\n \/\/ Output to specified file\n bool force = FLAGS_force;\n if (!check_for_file_already_exist(ofile, force)) {\n return 1;\n } else {\n out = Output::from_path(ofile, true);\n }\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ call into actual library\n\n if (do_compress) {\n if (print_stats) {\n alphabet_size = 0; \/\/ count_alphabet_size(inp_vec);\n }\n\n if (!do_raw) {\n CHECK(algorithm_id.find('%') == std::string::npos);\n\n auto o_stream = out.as_stream();\n (*o_stream) << algorithm_id << '%';\n }\n\n setup_time = clk::now();\n\n algo->compress(inp, out);\n\n comp_time = clk::now();\n } else {\n if (!do_raw) {\n auto i_stream = inp.as_stream();\n std::string algorithm_header;\n\n char c;\n size_t sanity_size_check = 0;\n bool err = false;\n while ((*i_stream).get(c)) {\n err = false;\n if (sanity_size_check > 1023) {\n err = true;\n break;\n } else if (c == '%') {\n break;\n } else {\n algorithm_header.push_back(c);\n }\n sanity_size_check++;\n err = true;\n }\n if (err) {\n exit(\"Input did not have an algorithm header!\");\n }\n algorithm_id = std::move(algorithm_header);\n algo = select_algo_or_exit(registry, algorithm_env, algorithm_id);\n }\n\n setup_time = clk::now();\n\n algo->decompress(inp, out);\n\n comp_time = clk::now();\n }\n }\n\n end_time = clk::now();\n\n if (print_stats) {\n auto setup_duration = setup_time - start_time;\n auto comp_duration = comp_time - setup_time;\n auto end_duration = end_time - comp_time;\n std::cout << \"---------------\\n\";\n std::cout << \"Config: \" << algorithm_id << std::endl;\n std::cout << \"---------------\\n\";\n auto inp_size = 0;\n if (use_stdin) {\n std::cout << \"input: \\n\";\n std::cout << \"input size: ? B\\n\";\n } else {\n inp_size = read_file_size(file);\n std::cout << \"input: \"<\\n\";\n std::cout << \"output size: ? B\\n\";\n } else {\n out_size = read_file_size(ofile);\n std::cout << \"output: \"<;\n using mildur = std::chrono::duration;\n using micdur = std::chrono::duration;\n\n if (t < milsec) {\n auto ct = std::chrono::duration_cast(t).count();\n std::cout << s <<\" time: \"<< ct << \" µs\\n\";\n } else if (t < sec) {\n auto ct = std::chrono::duration_cast(t).count();\n std::cout << s <<\" time: \"<< ct << \" ms\\n\";\n } else {\n auto ct = std::chrono::duration_cast(t).count();\n std::cout << s <<\" time: \"<< ct << \" s\\n\";\n }\n };\n\n std::cout << \"---------------\\n\";\n std::cout << \"Algorithm Known Options:\\n\";\n for (auto& pair : algorithm_env.get_known_options()) {\n std::cout << \" \" << pair << \"\\n\";\n }\n std::cout << \"Algorithm Given Options:\\n\";\n for (auto& pair : algorithm_env.get_options()) {\n std::cout << \" \" << pair.first << \" = \" << pair.second << \"\\n\";\n }\n\n std::cout << \"---------------\\n\";\n std::cout << \"Algorithm Stats:\\n\";\n for (auto& pair : algorithm_env.get_stats()) {\n std::cout << \" \" << pair.first << \": \" << pair.second << \"\\n\";\n }\n\n std::cout << \"---------------\\n\";\n print_time(\"startup\", setup_duration);\n print_time(\"compression\", comp_duration);\n print_time(\"teardown\", end_duration);\n std::cout << \"---------------\\n\";\n }\n } catch (std::exception& e) {\n std::cout << \"Error: \" << e.what() << '\\n';\n return 1;\n }\n\n return 0;\n}\n<|endoftext|>"} {"text":"\/*\n * Copyright (C) 2017 ScyllaDB\n *\/\n\n\/*\n * This file is part of Scylla.\n *\n * Scylla is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * Scylla is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with Scylla. If not, see .\n *\/\n\n#include \"leveled_manifest.hh\"\n\nnamespace sstables {\n\nclass leveled_compaction_strategy : public compaction_strategy_impl {\n static constexpr int32_t DEFAULT_MAX_SSTABLE_SIZE_IN_MB = 160;\n const sstring SSTABLE_SIZE_OPTION = \"sstable_size_in_mb\";\n\n int32_t _max_sstable_size_in_mb = DEFAULT_MAX_SSTABLE_SIZE_IN_MB;\n stdx::optional>> _last_compacted_keys;\n std::vector _compaction_counter;\npublic:\n leveled_compaction_strategy(const std::map& options)\n : compaction_strategy_impl(options)\n {\n using namespace cql3::statements;\n\n auto tmp_value = compaction_strategy_impl::get_value(options, SSTABLE_SIZE_OPTION);\n _max_sstable_size_in_mb = property_definitions::to_int(SSTABLE_SIZE_OPTION, tmp_value, DEFAULT_MAX_SSTABLE_SIZE_IN_MB);\n if (_max_sstable_size_in_mb >= 1000) {\n leveled_manifest::logger.warn(\"Max sstable size of {}MB is configured; having a unit of compaction this large is probably a bad idea\",\n _max_sstable_size_in_mb);\n } else if (_max_sstable_size_in_mb < 50) {\n leveled_manifest::logger.warn(\"Max sstable size of {}MB is configured. Testing done for CASSANDRA-5727 indicates that performance\" \\\n \"improves up to 160MB\", _max_sstable_size_in_mb);\n }\n _compaction_counter.resize(leveled_manifest::MAX_LEVELS);\n }\n\n virtual compaction_descriptor get_sstables_for_compaction(column_family& cfs, std::vector candidates) override;\n\n virtual std::vector get_resharding_jobs(column_family& cf, std::vector candidates) override;\n\n virtual void notify_completion(const std::vector>& removed, const std::vector>& added) override;\n\n \/\/ for each level > 0, get newest sstable and use its last key as last\n \/\/ compacted key for the previous level.\n void generate_last_compacted_keys(leveled_manifest& manifest);\n\n virtual int64_t estimated_pending_compactions(column_family& cf) const override;\n\n virtual bool parallel_compaction() const override {\n return false;\n }\n\n virtual compaction_strategy_type type() const {\n return compaction_strategy_type::leveled;\n }\n virtual std::unique_ptr make_sstable_set(schema_ptr schema) const override;\n};\n\ncompaction_descriptor leveled_compaction_strategy::get_sstables_for_compaction(column_family& cfs, std::vector candidates) {\n \/\/ NOTE: leveled_manifest creation may be slightly expensive, so later on,\n \/\/ we may want to store it in the strategy itself. However, the sstable\n \/\/ lists managed by the manifest may become outdated. For example, one\n \/\/ sstable in it may be marked for deletion after compacted.\n \/\/ Currently, we create a new manifest whenever it's time for compaction.\n leveled_manifest manifest = leveled_manifest::create(cfs, candidates, _max_sstable_size_in_mb);\n if (!_last_compacted_keys) {\n generate_last_compacted_keys(manifest);\n }\n auto candidate = manifest.get_compaction_candidates(*_last_compacted_keys, _compaction_counter);\n\n if (!candidate.sstables.empty()) {\n leveled_manifest::logger.debug(\"leveled: Compacting {} out of {} sstables\", candidate.sstables.size(), cfs.get_sstables()->size());\n return std::move(candidate);\n }\n\n \/\/ if there is no sstable to compact in standard way, try compacting based on droppable tombstone ratio\n \/\/ unlike stcs, lcs can look for sstable with highest droppable tombstone ratio, so as not to choose\n \/\/ a sstable which droppable data shadow data in older sstable, by starting from highest levels which\n \/\/ theoretically contain oldest non-overlapping data.\n auto gc_before = gc_clock::now() - cfs.schema()->gc_grace_seconds();\n for (auto level = manifest.get_level_count(); level >= 0; level--) {\n auto& sstables = manifest.get_level(level);\n \/\/ filter out sstables which droppable tombstone ratio isn't greater than the defined threshold.\n auto e = boost::range::remove_if(sstables, [this, &gc_before] (const sstables::shared_sstable& sst) -> bool {\n return !worth_dropping_tombstones(sst, gc_before);\n });\n sstables.erase(e, sstables.end());\n if (sstables.empty()) {\n continue;\n }\n auto& sst = *std::min_element(sstables.begin(), sstables.end(), [&] (auto& i, auto& j) {\n return i->estimate_droppable_tombstone_ratio(gc_before) < j->estimate_droppable_tombstone_ratio(gc_before);\n });\n return sstables::compaction_descriptor({ sst }, sst->get_sstable_level());\n }\n}\n\nstd::vector leveled_compaction_strategy::get_resharding_jobs(column_family& cf, std::vector candidates) {\n leveled_manifest manifest = leveled_manifest::create(cf, candidates, _max_sstable_size_in_mb);\n\n std::vector descriptors;\n shard_id target_shard = 0;\n auto get_shard = [&target_shard] { return target_shard++ % smp::count; };\n\n \/\/ Basically, we'll iterate through all levels, and for each, we'll sort the\n \/\/ sstables by first key because there's a need to reshard together adjacent\n \/\/ sstables.\n \/\/ The shard at which the job will run is chosen in a round-robin fashion.\n for (auto level = 0U; level <= manifest.get_level_count(); level++) {\n uint64_t max_sstable_size = !level ? std::numeric_limits::max() : (_max_sstable_size_in_mb*1024*1024);\n auto& sstables = manifest.get_level(level);\n boost::sort(sstables, [] (auto& i, auto& j) {\n return i->compare_by_first_key(*j) < 0;\n });\n\n resharding_descriptor current_descriptor = resharding_descriptor{{}, max_sstable_size, get_shard(), level};\n\n for (auto it = sstables.begin(); it != sstables.end(); it++) {\n current_descriptor.sstables.push_back(*it);\n\n auto next = std::next(it);\n if (current_descriptor.sstables.size() == smp::count || next == sstables.end()) {\n descriptors.push_back(std::move(current_descriptor));\n current_descriptor = resharding_descriptor{{}, max_sstable_size, get_shard(), level};\n }\n }\n }\n return descriptors;\n}\n\nvoid leveled_compaction_strategy::notify_completion(const std::vector>& removed, const std::vector>& added) {\n if (removed.empty() || added.empty()) {\n return;\n }\n auto min_level = std::numeric_limits::max();\n for (auto& sstable : removed) {\n min_level = std::min(min_level, sstable->get_sstable_level());\n }\n\n const sstables::sstable *last = nullptr;\n for (auto& candidate : added) {\n if (!last || last->compare_by_first_key(*candidate) < 0) {\n last = &*candidate;\n }\n }\n _last_compacted_keys.value().at(min_level) = last->get_last_decorated_key();\n}\n\nvoid leveled_compaction_strategy::generate_last_compacted_keys(leveled_manifest& manifest) {\n std::vector> last_compacted_keys(leveled_manifest::MAX_LEVELS);\n for (auto i = 0; i < leveled_manifest::MAX_LEVELS - 1; i++) {\n if (manifest.get_level(i + 1).empty()) {\n continue;\n }\n\n const sstables::sstable* sstable_with_last_compacted_key = nullptr;\n stdx::optional max_creation_time;\n for (auto& sst : manifest.get_level(i + 1)) {\n auto wtime = sst->data_file_write_time();\n if (!max_creation_time || wtime >= *max_creation_time) {\n sstable_with_last_compacted_key = &*sst;\n max_creation_time = wtime;\n }\n }\n last_compacted_keys[i] = sstable_with_last_compacted_key->get_last_decorated_key();\n }\n _last_compacted_keys = std::move(last_compacted_keys);\n}\n\nint64_t leveled_compaction_strategy::estimated_pending_compactions(column_family& cf) const {\n std::vector sstables;\n sstables.reserve(cf.sstables_count());\n for (auto& entry : *cf.get_sstables()) {\n sstables.push_back(entry);\n }\n leveled_manifest manifest = leveled_manifest::create(cf, sstables, _max_sstable_size_in_mb);\n return manifest.get_estimated_tasks();\n}\n\n}\nlcs: prevent leveled_compaction_strategy.hh from being included more than once\/*\n * Copyright (C) 2017 ScyllaDB\n *\/\n\n\/*\n * This file is part of Scylla.\n *\n * Scylla is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * Scylla is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with Scylla. If not, see .\n *\/\n\n#pragma once\n\n#include \"leveled_manifest.hh\"\n\nnamespace sstables {\n\nclass leveled_compaction_strategy : public compaction_strategy_impl {\n static constexpr int32_t DEFAULT_MAX_SSTABLE_SIZE_IN_MB = 160;\n const sstring SSTABLE_SIZE_OPTION = \"sstable_size_in_mb\";\n\n int32_t _max_sstable_size_in_mb = DEFAULT_MAX_SSTABLE_SIZE_IN_MB;\n stdx::optional>> _last_compacted_keys;\n std::vector _compaction_counter;\npublic:\n leveled_compaction_strategy(const std::map& options)\n : compaction_strategy_impl(options)\n {\n using namespace cql3::statements;\n\n auto tmp_value = compaction_strategy_impl::get_value(options, SSTABLE_SIZE_OPTION);\n _max_sstable_size_in_mb = property_definitions::to_int(SSTABLE_SIZE_OPTION, tmp_value, DEFAULT_MAX_SSTABLE_SIZE_IN_MB);\n if (_max_sstable_size_in_mb >= 1000) {\n leveled_manifest::logger.warn(\"Max sstable size of {}MB is configured; having a unit of compaction this large is probably a bad idea\",\n _max_sstable_size_in_mb);\n } else if (_max_sstable_size_in_mb < 50) {\n leveled_manifest::logger.warn(\"Max sstable size of {}MB is configured. Testing done for CASSANDRA-5727 indicates that performance\" \\\n \"improves up to 160MB\", _max_sstable_size_in_mb);\n }\n _compaction_counter.resize(leveled_manifest::MAX_LEVELS);\n }\n\n virtual compaction_descriptor get_sstables_for_compaction(column_family& cfs, std::vector candidates) override;\n\n virtual std::vector get_resharding_jobs(column_family& cf, std::vector candidates) override;\n\n virtual void notify_completion(const std::vector>& removed, const std::vector>& added) override;\n\n \/\/ for each level > 0, get newest sstable and use its last key as last\n \/\/ compacted key for the previous level.\n void generate_last_compacted_keys(leveled_manifest& manifest);\n\n virtual int64_t estimated_pending_compactions(column_family& cf) const override;\n\n virtual bool parallel_compaction() const override {\n return false;\n }\n\n virtual compaction_strategy_type type() const {\n return compaction_strategy_type::leveled;\n }\n virtual std::unique_ptr make_sstable_set(schema_ptr schema) const override;\n};\n\ncompaction_descriptor leveled_compaction_strategy::get_sstables_for_compaction(column_family& cfs, std::vector candidates) {\n \/\/ NOTE: leveled_manifest creation may be slightly expensive, so later on,\n \/\/ we may want to store it in the strategy itself. However, the sstable\n \/\/ lists managed by the manifest may become outdated. For example, one\n \/\/ sstable in it may be marked for deletion after compacted.\n \/\/ Currently, we create a new manifest whenever it's time for compaction.\n leveled_manifest manifest = leveled_manifest::create(cfs, candidates, _max_sstable_size_in_mb);\n if (!_last_compacted_keys) {\n generate_last_compacted_keys(manifest);\n }\n auto candidate = manifest.get_compaction_candidates(*_last_compacted_keys, _compaction_counter);\n\n if (!candidate.sstables.empty()) {\n leveled_manifest::logger.debug(\"leveled: Compacting {} out of {} sstables\", candidate.sstables.size(), cfs.get_sstables()->size());\n return std::move(candidate);\n }\n\n \/\/ if there is no sstable to compact in standard way, try compacting based on droppable tombstone ratio\n \/\/ unlike stcs, lcs can look for sstable with highest droppable tombstone ratio, so as not to choose\n \/\/ a sstable which droppable data shadow data in older sstable, by starting from highest levels which\n \/\/ theoretically contain oldest non-overlapping data.\n auto gc_before = gc_clock::now() - cfs.schema()->gc_grace_seconds();\n for (auto level = manifest.get_level_count(); level >= 0; level--) {\n auto& sstables = manifest.get_level(level);\n \/\/ filter out sstables which droppable tombstone ratio isn't greater than the defined threshold.\n auto e = boost::range::remove_if(sstables, [this, &gc_before] (const sstables::shared_sstable& sst) -> bool {\n return !worth_dropping_tombstones(sst, gc_before);\n });\n sstables.erase(e, sstables.end());\n if (sstables.empty()) {\n continue;\n }\n auto& sst = *std::min_element(sstables.begin(), sstables.end(), [&] (auto& i, auto& j) {\n return i->estimate_droppable_tombstone_ratio(gc_before) < j->estimate_droppable_tombstone_ratio(gc_before);\n });\n return sstables::compaction_descriptor({ sst }, sst->get_sstable_level());\n }\n}\n\nstd::vector leveled_compaction_strategy::get_resharding_jobs(column_family& cf, std::vector candidates) {\n leveled_manifest manifest = leveled_manifest::create(cf, candidates, _max_sstable_size_in_mb);\n\n std::vector descriptors;\n shard_id target_shard = 0;\n auto get_shard = [&target_shard] { return target_shard++ % smp::count; };\n\n \/\/ Basically, we'll iterate through all levels, and for each, we'll sort the\n \/\/ sstables by first key because there's a need to reshard together adjacent\n \/\/ sstables.\n \/\/ The shard at which the job will run is chosen in a round-robin fashion.\n for (auto level = 0U; level <= manifest.get_level_count(); level++) {\n uint64_t max_sstable_size = !level ? std::numeric_limits::max() : (_max_sstable_size_in_mb*1024*1024);\n auto& sstables = manifest.get_level(level);\n boost::sort(sstables, [] (auto& i, auto& j) {\n return i->compare_by_first_key(*j) < 0;\n });\n\n resharding_descriptor current_descriptor = resharding_descriptor{{}, max_sstable_size, get_shard(), level};\n\n for (auto it = sstables.begin(); it != sstables.end(); it++) {\n current_descriptor.sstables.push_back(*it);\n\n auto next = std::next(it);\n if (current_descriptor.sstables.size() == smp::count || next == sstables.end()) {\n descriptors.push_back(std::move(current_descriptor));\n current_descriptor = resharding_descriptor{{}, max_sstable_size, get_shard(), level};\n }\n }\n }\n return descriptors;\n}\n\nvoid leveled_compaction_strategy::notify_completion(const std::vector>& removed, const std::vector>& added) {\n if (removed.empty() || added.empty()) {\n return;\n }\n auto min_level = std::numeric_limits::max();\n for (auto& sstable : removed) {\n min_level = std::min(min_level, sstable->get_sstable_level());\n }\n\n const sstables::sstable *last = nullptr;\n for (auto& candidate : added) {\n if (!last || last->compare_by_first_key(*candidate) < 0) {\n last = &*candidate;\n }\n }\n _last_compacted_keys.value().at(min_level) = last->get_last_decorated_key();\n}\n\nvoid leveled_compaction_strategy::generate_last_compacted_keys(leveled_manifest& manifest) {\n std::vector> last_compacted_keys(leveled_manifest::MAX_LEVELS);\n for (auto i = 0; i < leveled_manifest::MAX_LEVELS - 1; i++) {\n if (manifest.get_level(i + 1).empty()) {\n continue;\n }\n\n const sstables::sstable* sstable_with_last_compacted_key = nullptr;\n stdx::optional max_creation_time;\n for (auto& sst : manifest.get_level(i + 1)) {\n auto wtime = sst->data_file_write_time();\n if (!max_creation_time || wtime >= *max_creation_time) {\n sstable_with_last_compacted_key = &*sst;\n max_creation_time = wtime;\n }\n }\n last_compacted_keys[i] = sstable_with_last_compacted_key->get_last_decorated_key();\n }\n _last_compacted_keys = std::move(last_compacted_keys);\n}\n\nint64_t leveled_compaction_strategy::estimated_pending_compactions(column_family& cf) const {\n std::vector sstables;\n sstables.reserve(cf.sstables_count());\n for (auto& entry : *cf.get_sstables()) {\n sstables.push_back(entry);\n }\n leveled_manifest manifest = leveled_manifest::create(cf, sstables, _max_sstable_size_in_mb);\n return manifest.get_estimated_tasks();\n}\n\n}\n<|endoftext|>"} {"text":"\/\/===-- SelectionDAGPrinter.cpp - Implement SelectionDAG::viewGraph() -----===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file was developed by the LLVM research group and is distributed under\n\/\/ the University of Illinois Open Source License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This implements the SelectionDAG::viewGraph method.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/CodeGen\/SelectionDAG.h\"\n#include \"llvm\/CodeGen\/MachineFunction.h\"\n#include \"llvm\/Function.h\"\n#include \"llvm\/Support\/GraphWriter.h\"\n#include \"llvm\/ADT\/StringExtras.h\"\n#include \nusing namespace llvm;\n\nnamespace llvm {\n template<>\n struct DOTGraphTraits : public DefaultDOTGraphTraits {\n static std::string getGraphName(const SelectionDAG *G) {\n return G->getMachineFunction().getFunction()->getName();\n }\n\n static bool renderGraphFromBottomUp() {\n return true;\n }\n\n static std::string getNodeLabel(const SDNode *Node,\n const SelectionDAG *Graph);\n static std::string getNodeAttributes(const SDNode *N) {\n return \"shape=Mrecord\";\n }\n\n static void addCustomGraphFeatures(SelectionDAG *G,\n GraphWriter &GW) {\n GW.emitSimpleNode(0, \"plaintext=circle\", \"GraphRoot\");\n GW.emitEdge(0, -1, G->getRoot().Val, -1, \"\");\n }\n };\n}\n\nstd::string DOTGraphTraits::getNodeLabel(const SDNode *Node,\n const SelectionDAG *G) {\n std::string Op = Node->getOperationName();\n\n for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i) {\n switch (Node->getValueType(i)) {\n default: Op += \":unknownvt!\"; break;\n case MVT::Other: Op += \":ch\"; break;\n case MVT::i1: Op += \":i1\"; break;\n case MVT::i8: Op += \":i8\"; break;\n case MVT::i16: Op += \":i16\"; break;\n case MVT::i32: Op += \":i32\"; break;\n case MVT::i64: Op += \":i64\"; break;\n case MVT::i128: Op += \":i128\"; break;\n case MVT::f32: Op += \":f32\"; break;\n case MVT::f64: Op += \":f64\"; break;\n case MVT::f80: Op += \":f80\"; break;\n case MVT::f128: Op += \":f128\"; break;\n case MVT::isVoid: Op += \":void\"; break;\n }\n }\n\n if (const ConstantSDNode *CSDN = dyn_cast(Node)) {\n Op += \": \" + utostr(CSDN->getValue());\n } else if (const ConstantFPSDNode *CSDN = dyn_cast(Node)) {\n Op += \": \" + ftostr(CSDN->getValue());\n } else if (const GlobalAddressSDNode *GADN =\n dyn_cast(Node)) {\n Op += \": \" + GADN->getGlobal()->getName();\n } else if (const FrameIndexSDNode *FIDN = dyn_cast(Node)) {\n Op += \" \" + itostr(FIDN->getIndex());\n } else if (const ConstantPoolSDNode *CP = dyn_cast(Node)){\n Op += \"<\" + utostr(CP->getIndex()) + \">\";\n } else if (const BasicBlockSDNode *BBDN = dyn_cast(Node)) {\n Op = \"BB: \";\n const Value *LBB = (const Value*)BBDN->getBasicBlock()->getBasicBlock();\n if (LBB)\n Op += LBB->getName();\n \/\/Op += \" \" + (const void*)BBDN->getBasicBlock();\n } else if (const RegSDNode *C2V = dyn_cast(Node)) {\n Op += \" #\" + utostr(C2V->getReg());\n } else if (const ExternalSymbolSDNode *ES =\n dyn_cast(Node)) {\n Op += \"'\" + std::string(ES->getSymbol()) + \"'\";\n } else if (const SrcValueSDNode *M = dyn_cast(Node)) {\n if (M->getValue())\n Op += \"<\" + M->getValue()->getName() + \":\" + itostr(M->getOffset()) + \">\";\n else\n Op += \"getOffset()) + \">\";\n }\n return Op;\n}\n\n\n\/\/\/ viewGraph - Pop up a ghostview window with the reachable parts of the DAG\n\/\/\/ rendered using 'dot'.\n\/\/\/\nvoid SelectionDAG::viewGraph() {\n std::string Filename = \"\/tmp\/dag.\" +\n getMachineFunction().getFunction()->getName() + \".dot\";\n std::cerr << \"Writing '\" << Filename << \"'... \";\n std::ofstream F(Filename.c_str());\n\n if (!F) {\n std::cerr << \" error opening file for writing!\\n\";\n return;\n }\n\n WriteGraph(F, this);\n F.close();\n std::cerr << \"\\n\";\n\n#ifdef HAVE_GRAPHVIZ\n std::cerr << \"Running 'Graphviz' program... \" << std::flush;\n if (system((\"Graphviz \" + Filename).c_str())) {\n std::cerr << \"Error viewing graph: 'Graphviz' not in path?\\n\";\n } else {\n return;\n }\n#endif\n\n std::cerr << \"Running 'dot' program... \" << std::flush;\n if (system((\"dot -Tps -Nfontname=Courier -Gsize=7.5,10 \" + Filename\n + \" > \/tmp\/dag.tempgraph.ps\").c_str())) {\n std::cerr << \"Error viewing graph: 'dot' not in path?\\n\";\n } else {\n std::cerr << \"\\n\";\n system(\"gv \/tmp\/dag.tempgraph.ps\");\n }\n system((\"rm \" + Filename + \" \/tmp\/dag.tempgraph.ps\").c_str());\n}\nAs discussed on IRC, this stuff is just for debugging.\/\/===-- SelectionDAGPrinter.cpp - Implement SelectionDAG::viewGraph() -----===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file was developed by the LLVM research group and is distributed under\n\/\/ the University of Illinois Open Source License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This implements the SelectionDAG::viewGraph method.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/CodeGen\/SelectionDAG.h\"\n#include \"llvm\/CodeGen\/MachineFunction.h\"\n#include \"llvm\/Function.h\"\n#include \"llvm\/Support\/GraphWriter.h\"\n#include \"llvm\/ADT\/StringExtras.h\"\n#include \nusing namespace llvm;\n\nnamespace llvm {\n template<>\n struct DOTGraphTraits : public DefaultDOTGraphTraits {\n static std::string getGraphName(const SelectionDAG *G) {\n return G->getMachineFunction().getFunction()->getName();\n }\n\n static bool renderGraphFromBottomUp() {\n return true;\n }\n\n static std::string getNodeLabel(const SDNode *Node,\n const SelectionDAG *Graph);\n static std::string getNodeAttributes(const SDNode *N) {\n return \"shape=Mrecord\";\n }\n\n static void addCustomGraphFeatures(SelectionDAG *G,\n GraphWriter &GW) {\n GW.emitSimpleNode(0, \"plaintext=circle\", \"GraphRoot\");\n GW.emitEdge(0, -1, G->getRoot().Val, -1, \"\");\n }\n };\n}\n\nstd::string DOTGraphTraits::getNodeLabel(const SDNode *Node,\n const SelectionDAG *G) {\n std::string Op = Node->getOperationName();\n\n for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i) {\n switch (Node->getValueType(i)) {\n default: Op += \":unknownvt!\"; break;\n case MVT::Other: Op += \":ch\"; break;\n case MVT::i1: Op += \":i1\"; break;\n case MVT::i8: Op += \":i8\"; break;\n case MVT::i16: Op += \":i16\"; break;\n case MVT::i32: Op += \":i32\"; break;\n case MVT::i64: Op += \":i64\"; break;\n case MVT::i128: Op += \":i128\"; break;\n case MVT::f32: Op += \":f32\"; break;\n case MVT::f64: Op += \":f64\"; break;\n case MVT::f80: Op += \":f80\"; break;\n case MVT::f128: Op += \":f128\"; break;\n case MVT::isVoid: Op += \":void\"; break;\n }\n }\n\n if (const ConstantSDNode *CSDN = dyn_cast(Node)) {\n Op += \": \" + utostr(CSDN->getValue());\n } else if (const ConstantFPSDNode *CSDN = dyn_cast(Node)) {\n Op += \": \" + ftostr(CSDN->getValue());\n } else if (const GlobalAddressSDNode *GADN =\n dyn_cast(Node)) {\n Op += \": \" + GADN->getGlobal()->getName();\n } else if (const FrameIndexSDNode *FIDN = dyn_cast(Node)) {\n Op += \" \" + itostr(FIDN->getIndex());\n } else if (const ConstantPoolSDNode *CP = dyn_cast(Node)){\n Op += \"<\" + utostr(CP->getIndex()) + \">\";\n } else if (const BasicBlockSDNode *BBDN = dyn_cast(Node)) {\n Op = \"BB: \";\n const Value *LBB = (const Value*)BBDN->getBasicBlock()->getBasicBlock();\n if (LBB)\n Op += LBB->getName();\n \/\/Op += \" \" + (const void*)BBDN->getBasicBlock();\n } else if (const RegSDNode *C2V = dyn_cast(Node)) {\n Op += \" #\" + utostr(C2V->getReg());\n } else if (const ExternalSymbolSDNode *ES =\n dyn_cast(Node)) {\n Op += \"'\" + std::string(ES->getSymbol()) + \"'\";\n } else if (const SrcValueSDNode *M = dyn_cast(Node)) {\n if (M->getValue())\n Op += \"<\" + M->getValue()->getName() + \":\" + itostr(M->getOffset()) + \">\";\n else\n Op += \"getOffset()) + \">\";\n }\n return Op;\n}\n\n\n\/\/\/ viewGraph - Pop up a ghostview window with the reachable parts of the DAG\n\/\/\/ rendered using 'dot'.\n\/\/\/\nvoid SelectionDAG::viewGraph() {\n\/\/ This code is only for debugging!\n#ifdef NDEBUG\n std::cerr << \"SelectionDAG::viewGraph is only available in debug builds!\\n\";\n#else\n std::string Filename = \"\/tmp\/dag.\" +\n getMachineFunction().getFunction()->getName() + \".dot\";\n std::cerr << \"Writing '\" << Filename << \"'... \";\n std::ofstream F(Filename.c_str());\n\n if (!F) {\n std::cerr << \" error opening file for writing!\\n\";\n return;\n }\n\n WriteGraph(F, this);\n F.close();\n std::cerr << \"\\n\";\n\n#ifdef HAVE_GRAPHVIZ\n std::cerr << \"Running 'Graphviz' program... \" << std::flush;\n if (system((\"Graphviz \" + Filename).c_str())) {\n std::cerr << \"Error viewing graph: 'Graphviz' not in path?\\n\";\n } else {\n return;\n }\n#endif\n\n std::cerr << \"Running 'dot' program... \" << std::flush;\n if (system((\"dot -Tps -Nfontname=Courier -Gsize=7.5,10 \" + Filename\n + \" > \/tmp\/dag.tempgraph.ps\").c_str())) {\n std::cerr << \"Error viewing graph: 'dot' not in path?\\n\";\n } else {\n std::cerr << \"\\n\";\n system(\"gv \/tmp\/dag.tempgraph.ps\");\n }\n system((\"rm \" + Filename + \" \/tmp\/dag.tempgraph.ps\").c_str());\n#endif\n}\n<|endoftext|>"} {"text":"\/\/== TraversalChecker.cpp -------------------------------------- -*- C++ -*--=\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ These checkers print various aspects of the ExprEngine's traversal of the CFG\n\/\/ as it builds the ExplodedGraph.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n#include \"ClangSACheckers.h\"\n#include \"clang\/AST\/ParentMap.h\"\n#include \"clang\/AST\/StmtObjC.h\"\n#include \"clang\/StaticAnalyzer\/Core\/Checker.h\"\n#include \"clang\/StaticAnalyzer\/Core\/CheckerManager.h\"\n#include \"clang\/StaticAnalyzer\/Core\/PathSensitive\/CallEvent.h\"\n#include \"clang\/StaticAnalyzer\/Core\/PathSensitive\/CheckerContext.h\"\n#include \"llvm\/Support\/raw_ostream.h\"\n\nusing namespace clang;\nusing namespace ento;\n\nnamespace {\nclass TraversalDumper : public Checker< check::BranchCondition,\n check::EndFunction > {\npublic:\n void checkBranchCondition(const Stmt *Condition, CheckerContext &C) const;\n void checkEndFunction(CheckerContext &C) const;\n};\n}\n\nvoid TraversalDumper::checkBranchCondition(const Stmt *Condition,\n CheckerContext &C) const {\n \/\/ Special-case Objective-C's for-in loop, which uses the entire loop as its\n \/\/ condition. We just print the collection expression.\n const Stmt *Parent = dyn_cast(Condition);\n if (!Parent) {\n const ParentMap &Parents = C.getLocationContext()->getParentMap();\n Parent = Parents.getParent(Condition);\n }\n\n \/\/ It is mildly evil to print directly to llvm::outs() rather than emitting\n \/\/ warnings, but this ensures things do not get filtered out by the rest of\n \/\/ the static analyzer machinery.\n SourceLocation Loc = Parent->getLocStart();\n llvm::outs() << C.getSourceManager().getSpellingLineNumber(Loc) << \" \"\n << Parent->getStmtClassName() << \"\\n\";\n}\n\nvoid TraversalDumper::checkEndFunction(CheckerContext &C) const {\n llvm::outs() << \"--END FUNCTION--\\n\";\n}\n\nvoid ento::registerTraversalDumper(CheckerManager &mgr) {\n mgr.registerChecker();\n}\n\n\/\/------------------------------------------------------------------------------\n\nnamespace {\nclass CallDumper : public Checker< check::PreCall > {\npublic:\n void checkPreCall(const CallEvent &Call, CheckerContext &C) const;\n};\n}\n\nvoid CallDumper::checkPreCall(const CallEvent &Call, CheckerContext &C) const {\n unsigned Indentation = 0;\n for (const LocationContext *LC = C.getLocationContext()->getParent();\n LC != 0; LC = LC->getParent())\n ++Indentation;\n\n \/\/ It is mildly evil to print directly to llvm::outs() rather than emitting\n \/\/ warnings, but this ensures things do not get filtered out by the rest of\n \/\/ the static analyzer machinery.\n llvm::outs().indent(Indentation);\n Call.dump(llvm::outs());\n}\n\nvoid ento::registerCallDumper(CheckerManager &mgr) {\n mgr.registerChecker();\n}\n[analyzer] Print return values from debug.DumpCalls checker.\/\/== TraversalChecker.cpp -------------------------------------- -*- C++ -*--=\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ These checkers print various aspects of the ExprEngine's traversal of the CFG\n\/\/ as it builds the ExplodedGraph.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n#include \"ClangSACheckers.h\"\n#include \"clang\/AST\/ParentMap.h\"\n#include \"clang\/AST\/StmtObjC.h\"\n#include \"clang\/StaticAnalyzer\/Core\/Checker.h\"\n#include \"clang\/StaticAnalyzer\/Core\/CheckerManager.h\"\n#include \"clang\/StaticAnalyzer\/Core\/PathSensitive\/CallEvent.h\"\n#include \"clang\/StaticAnalyzer\/Core\/PathSensitive\/CheckerContext.h\"\n#include \"llvm\/Support\/raw_ostream.h\"\n\nusing namespace clang;\nusing namespace ento;\n\nnamespace {\nclass TraversalDumper : public Checker< check::BranchCondition,\n check::EndFunction > {\npublic:\n void checkBranchCondition(const Stmt *Condition, CheckerContext &C) const;\n void checkEndFunction(CheckerContext &C) const;\n};\n}\n\nvoid TraversalDumper::checkBranchCondition(const Stmt *Condition,\n CheckerContext &C) const {\n \/\/ Special-case Objective-C's for-in loop, which uses the entire loop as its\n \/\/ condition. We just print the collection expression.\n const Stmt *Parent = dyn_cast(Condition);\n if (!Parent) {\n const ParentMap &Parents = C.getLocationContext()->getParentMap();\n Parent = Parents.getParent(Condition);\n }\n\n \/\/ It is mildly evil to print directly to llvm::outs() rather than emitting\n \/\/ warnings, but this ensures things do not get filtered out by the rest of\n \/\/ the static analyzer machinery.\n SourceLocation Loc = Parent->getLocStart();\n llvm::outs() << C.getSourceManager().getSpellingLineNumber(Loc) << \" \"\n << Parent->getStmtClassName() << \"\\n\";\n}\n\nvoid TraversalDumper::checkEndFunction(CheckerContext &C) const {\n llvm::outs() << \"--END FUNCTION--\\n\";\n}\n\nvoid ento::registerTraversalDumper(CheckerManager &mgr) {\n mgr.registerChecker();\n}\n\n\/\/------------------------------------------------------------------------------\n\nnamespace {\nclass CallDumper : public Checker< check::PreCall,\n check::PostCall > {\npublic:\n void checkPreCall(const CallEvent &Call, CheckerContext &C) const;\n void checkPostCall(const CallEvent &Call, CheckerContext &C) const;\n};\n}\n\nvoid CallDumper::checkPreCall(const CallEvent &Call, CheckerContext &C) const {\n unsigned Indentation = 0;\n for (const LocationContext *LC = C.getLocationContext()->getParent();\n LC != 0; LC = LC->getParent())\n ++Indentation;\n\n \/\/ It is mildly evil to print directly to llvm::outs() rather than emitting\n \/\/ warnings, but this ensures things do not get filtered out by the rest of\n \/\/ the static analyzer machinery.\n llvm::outs().indent(Indentation);\n Call.dump(llvm::outs());\n}\n\nvoid CallDumper::checkPostCall(const CallEvent &Call, CheckerContext &C) const {\n const Expr *CallE = Call.getOriginExpr();\n if (!CallE)\n return;\n\n unsigned Indentation = 0;\n for (const LocationContext *LC = C.getLocationContext()->getParent();\n LC != 0; LC = LC->getParent())\n ++Indentation;\n\n \/\/ It is mildly evil to print directly to llvm::outs() rather than emitting\n \/\/ warnings, but this ensures things do not get filtered out by the rest of\n \/\/ the static analyzer machinery.\n llvm::outs().indent(Indentation);\n if (Call.getResultType()->isVoidType())\n llvm::outs() << \"Returning void\\n\";\n else\n llvm::outs() << \"Returning \" << C.getSVal(CallE) << \"\\n\";\n}\n\nvoid ento::registerCallDumper(CheckerManager &mgr) {\n mgr.registerChecker();\n}\n<|endoftext|>"} {"text":"\/\/===-- SIOptimizeExecMaskingPreRA.cpp ------------------------------------===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/\/ \\file\n\/\/\/ This pass removes redundant S_OR_B64 instructions enabling lanes in\n\/\/\/ the exec. If two SI_END_CF (lowered as S_OR_B64) come together without any\n\/\/\/ vector instructions between them we can only keep outer SI_END_CF, given\n\/\/\/ that CFG is structured and exec bits of the outer end statement are always\n\/\/\/ not less than exec bit of the inner one.\n\/\/\/\n\/\/\/ This needs to be done before the RA to eliminate saved exec bits registers\n\/\/\/ but after register coalescer to have no vector registers copies in between\n\/\/\/ of different end cf statements.\n\/\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"AMDGPU.h\"\n#include \"AMDGPUSubtarget.h\"\n#include \"SIInstrInfo.h\"\n#include \"MCTargetDesc\/AMDGPUMCTargetDesc.h\"\n#include \"llvm\/CodeGen\/LiveIntervals.h\"\n#include \"llvm\/CodeGen\/MachineFunctionPass.h\"\n\nusing namespace llvm;\n\n#define DEBUG_TYPE \"si-optimize-exec-masking-pre-ra\"\n\nnamespace {\n\nclass SIOptimizeExecMaskingPreRA : public MachineFunctionPass {\npublic:\n static char ID;\n\npublic:\n SIOptimizeExecMaskingPreRA() : MachineFunctionPass(ID) {\n initializeSIOptimizeExecMaskingPreRAPass(*PassRegistry::getPassRegistry());\n }\n\n bool runOnMachineFunction(MachineFunction &MF) override;\n\n StringRef getPassName() const override {\n return \"SI optimize exec mask operations pre-RA\";\n }\n\n void getAnalysisUsage(AnalysisUsage &AU) const override {\n AU.addRequired();\n AU.setPreservesAll();\n MachineFunctionPass::getAnalysisUsage(AU);\n }\n};\n\n} \/\/ End anonymous namespace.\n\nINITIALIZE_PASS_BEGIN(SIOptimizeExecMaskingPreRA, DEBUG_TYPE,\n \"SI optimize exec mask operations pre-RA\", false, false)\nINITIALIZE_PASS_DEPENDENCY(LiveIntervals)\nINITIALIZE_PASS_END(SIOptimizeExecMaskingPreRA, DEBUG_TYPE,\n \"SI optimize exec mask operations pre-RA\", false, false)\n\nchar SIOptimizeExecMaskingPreRA::ID = 0;\n\nchar &llvm::SIOptimizeExecMaskingPreRAID = SIOptimizeExecMaskingPreRA::ID;\n\nFunctionPass *llvm::createSIOptimizeExecMaskingPreRAPass() {\n return new SIOptimizeExecMaskingPreRA();\n}\n\nstatic bool isEndCF(const MachineInstr& MI, const SIRegisterInfo* TRI) {\n return MI.getOpcode() == AMDGPU::S_OR_B64 &&\n MI.modifiesRegister(AMDGPU::EXEC, TRI);\n}\n\nstatic bool isFullExecCopy(const MachineInstr& MI) {\n return MI.isFullCopy() && MI.getOperand(1).getReg() == AMDGPU::EXEC;\n}\n\nstatic unsigned getOrNonExecReg(const MachineInstr &MI,\n const SIInstrInfo &TII) {\n auto Op = TII.getNamedOperand(MI, AMDGPU::OpName::src1);\n if (Op->isReg() && Op->getReg() != AMDGPU::EXEC)\n return Op->getReg();\n Op = TII.getNamedOperand(MI, AMDGPU::OpName::src0);\n if (Op->isReg() && Op->getReg() != AMDGPU::EXEC)\n return Op->getReg();\n return AMDGPU::NoRegister;\n}\n\nstatic MachineInstr* getOrExecSource(const MachineInstr &MI,\n const SIInstrInfo &TII,\n const MachineRegisterInfo &MRI) {\n auto SavedExec = getOrNonExecReg(MI, TII);\n if (SavedExec == AMDGPU::NoRegister)\n return nullptr;\n auto SaveExecInst = MRI.getUniqueVRegDef(SavedExec);\n if (!SaveExecInst || !isFullExecCopy(*SaveExecInst))\n return nullptr;\n return SaveExecInst;\n}\n\n\/\/ Optimize sequence\n\/\/ %sel = V_CNDMASK_B32_e64 0, 1, %cc\n\/\/ %cmp = V_CMP_NE_U32 1, %1\n\/\/ $vcc = S_AND_B64 $exec, %cmp\n\/\/ S_CBRANCH_VCC[N]Z\n\/\/ =>\n\/\/ $vcc = S_ANDN2_B64 $exec, %cc\n\/\/ S_CBRANCH_VCC[N]Z\n\/\/\n\/\/ It is the negation pattern inserted by DAGCombiner::visitBRCOND() in the\n\/\/ rebuildSetCC(). We start with S_CBRANCH to avoid exhaustive search, but\n\/\/ only 3 first instructions are really needed. S_AND_B64 with exec is a\n\/\/ required part of the pattern since V_CNDMASK_B32 writes zeroes for inactive\n\/\/ lanes.\n\/\/\n\/\/ Returns %cc register on success.\nstatic unsigned optimizeVcndVcmpPair(MachineBasicBlock &MBB,\n const GCNSubtarget &ST,\n MachineRegisterInfo &MRI,\n LiveIntervals *LIS) {\n const SIRegisterInfo *TRI = ST.getRegisterInfo();\n const SIInstrInfo *TII = ST.getInstrInfo();\n const unsigned AndOpc = AMDGPU::S_AND_B64;\n const unsigned Andn2Opc = AMDGPU::S_ANDN2_B64;\n const unsigned CondReg = AMDGPU::VCC;\n const unsigned ExecReg = AMDGPU::EXEC;\n\n auto I = llvm::find_if(MBB.terminators(), [](const MachineInstr &MI) {\n unsigned Opc = MI.getOpcode();\n return Opc == AMDGPU::S_CBRANCH_VCCZ ||\n Opc == AMDGPU::S_CBRANCH_VCCNZ; });\n if (I == MBB.terminators().end())\n return AMDGPU::NoRegister;\n\n auto *And = TRI->findReachingDef(CondReg, AMDGPU::NoSubRegister,\n *I, MRI, LIS);\n if (!And || And->getOpcode() != AndOpc ||\n !And->getOperand(1).isReg() || !And->getOperand(2).isReg())\n return AMDGPU::NoRegister;\n\n MachineOperand *AndCC = &And->getOperand(1);\n unsigned CmpReg = AndCC->getReg();\n unsigned CmpSubReg = AndCC->getSubReg();\n if (CmpReg == ExecReg) {\n AndCC = &And->getOperand(2);\n CmpReg = AndCC->getReg();\n CmpSubReg = AndCC->getSubReg();\n } else if (And->getOperand(2).getReg() != ExecReg) {\n return AMDGPU::NoRegister;\n }\n\n auto *Cmp = TRI->findReachingDef(CmpReg, CmpSubReg, *And, MRI, LIS);\n if (!Cmp || !(Cmp->getOpcode() == AMDGPU::V_CMP_NE_U32_e32 ||\n Cmp->getOpcode() == AMDGPU::V_CMP_NE_U32_e64) ||\n Cmp->getParent() != And->getParent())\n return AMDGPU::NoRegister;\n\n MachineOperand *Op1 = TII->getNamedOperand(*Cmp, AMDGPU::OpName::src0);\n MachineOperand *Op2 = TII->getNamedOperand(*Cmp, AMDGPU::OpName::src1);\n if (Op1->isImm() && Op2->isReg())\n std::swap(Op1, Op2);\n if (!Op1->isReg() || !Op2->isImm() || Op2->getImm() != 1)\n return AMDGPU::NoRegister;\n\n unsigned SelReg = Op1->getReg();\n auto *Sel = TRI->findReachingDef(SelReg, Op1->getSubReg(), *Cmp, MRI, LIS);\n if (!Sel || Sel->getOpcode() != AMDGPU::V_CNDMASK_B32_e64)\n return AMDGPU::NoRegister;\n\n Op1 = TII->getNamedOperand(*Sel, AMDGPU::OpName::src0);\n Op2 = TII->getNamedOperand(*Sel, AMDGPU::OpName::src1);\n MachineOperand *CC = TII->getNamedOperand(*Sel, AMDGPU::OpName::src2);\n if (!Op1->isImm() || !Op2->isImm() || !CC->isReg() ||\n Op1->getImm() != 0 || Op2->getImm() != 1)\n return AMDGPU::NoRegister;\n\n LLVM_DEBUG(dbgs() << \"Folding sequence:\\n\\t\" << *Sel << '\\t'\n << *Cmp << '\\t' << *And);\n\n unsigned CCReg = CC->getReg();\n LIS->RemoveMachineInstrFromMaps(*And);\n MachineInstr *Andn2 = BuildMI(MBB, *And, And->getDebugLoc(),\n TII->get(Andn2Opc), And->getOperand(0).getReg())\n .addReg(ExecReg)\n .addReg(CCReg, CC->getSubReg());\n And->eraseFromParent();\n LIS->InsertMachineInstrInMaps(*Andn2);\n\n LLVM_DEBUG(dbgs() << \"=>\\n\\t\" << *Andn2 << '\\n');\n\n \/\/ Try to remove compare. Cmp value should not used in between of cmp\n \/\/ and s_and_b64 if VCC or just unused if any other register.\n if ((TargetRegisterInfo::isVirtualRegister(CmpReg) &&\n MRI.use_nodbg_empty(CmpReg)) ||\n (CmpReg == CondReg &&\n std::none_of(std::next(Cmp->getIterator()), Andn2->getIterator(),\n [TRI](const MachineInstr &MI) {\n return MI.readsRegister(CondReg, TRI); }))) {\n LLVM_DEBUG(dbgs() << \"Erasing: \" << *Cmp << '\\n');\n\n LIS->RemoveMachineInstrFromMaps(*Cmp);\n Cmp->eraseFromParent();\n\n \/\/ Try to remove v_cndmask_b32.\n if (TargetRegisterInfo::isVirtualRegister(SelReg) &&\n MRI.use_nodbg_empty(SelReg)) {\n LLVM_DEBUG(dbgs() << \"Erasing: \" << *Sel << '\\n');\n\n LIS->RemoveMachineInstrFromMaps(*Sel);\n Sel->eraseFromParent();\n }\n }\n\n return CCReg;\n}\n\nbool SIOptimizeExecMaskingPreRA::runOnMachineFunction(MachineFunction &MF) {\n if (skipFunction(MF.getFunction()))\n return false;\n\n const GCNSubtarget &ST = MF.getSubtarget();\n const SIRegisterInfo *TRI = ST.getRegisterInfo();\n const SIInstrInfo *TII = ST.getInstrInfo();\n MachineRegisterInfo &MRI = MF.getRegInfo();\n LiveIntervals *LIS = &getAnalysis();\n DenseSet RecalcRegs({AMDGPU::EXEC_LO, AMDGPU::EXEC_HI});\n bool Changed = false;\n\n for (MachineBasicBlock &MBB : MF) {\n\n if (unsigned Reg = optimizeVcndVcmpPair(MBB, ST, MRI, LIS)) {\n RecalcRegs.insert(Reg);\n RecalcRegs.insert(AMDGPU::VCC_LO);\n RecalcRegs.insert(AMDGPU::VCC_HI);\n RecalcRegs.insert(AMDGPU::SCC);\n Changed = true;\n }\n\n \/\/ Try to remove unneeded instructions before s_endpgm.\n if (MBB.succ_empty()) {\n if (MBB.empty())\n continue;\n\n \/\/ Skip this if the endpgm has any implicit uses, otherwise we would need\n \/\/ to be careful to update \/ remove them.\n MachineInstr &Term = MBB.back();\n if (Term.getOpcode() != AMDGPU::S_ENDPGM ||\n Term.getNumOperands() != 0)\n continue;\n\n SmallVector Blocks({&MBB});\n\n while (!Blocks.empty()) {\n auto CurBB = Blocks.pop_back_val();\n auto I = CurBB->rbegin(), E = CurBB->rend();\n if (I != E) {\n if (I->isUnconditionalBranch() || I->getOpcode() == AMDGPU::S_ENDPGM)\n ++I;\n else if (I->isBranch())\n continue;\n }\n\n while (I != E) {\n if (I->isDebugInstr()) {\n I = std::next(I);\n continue;\n }\n\n if (I->mayStore() || I->isBarrier() || I->isCall() ||\n I->hasUnmodeledSideEffects() || I->hasOrderedMemoryRef())\n break;\n\n LLVM_DEBUG(dbgs()\n << \"Removing no effect instruction: \" << *I << '\\n');\n\n for (auto &Op : I->operands()) {\n if (Op.isReg())\n RecalcRegs.insert(Op.getReg());\n }\n\n auto Next = std::next(I);\n LIS->RemoveMachineInstrFromMaps(*I);\n I->eraseFromParent();\n I = Next;\n\n Changed = true;\n }\n\n if (I != E)\n continue;\n\n \/\/ Try to ascend predecessors.\n for (auto *Pred : CurBB->predecessors()) {\n if (Pred->succ_size() == 1)\n Blocks.push_back(Pred);\n }\n }\n continue;\n }\n\n \/\/ Try to collapse adjacent endifs.\n auto Lead = MBB.begin(), E = MBB.end();\n if (MBB.succ_size() != 1 || Lead == E || !isEndCF(*Lead, TRI))\n continue;\n\n const MachineBasicBlock* Succ = *MBB.succ_begin();\n if (!MBB.isLayoutSuccessor(Succ))\n continue;\n\n auto I = std::next(Lead);\n\n for ( ; I != E; ++I)\n if (!TII->isSALU(*I) || I->readsRegister(AMDGPU::EXEC, TRI))\n break;\n\n if (I != E)\n continue;\n\n const auto NextLead = Succ->begin();\n if (NextLead == Succ->end() || !isEndCF(*NextLead, TRI) ||\n !getOrExecSource(*NextLead, *TII, MRI))\n continue;\n\n LLVM_DEBUG(dbgs() << \"Redundant EXEC = S_OR_B64 found: \" << *Lead << '\\n');\n\n auto SaveExec = getOrExecSource(*Lead, *TII, MRI);\n unsigned SaveExecReg = getOrNonExecReg(*Lead, *TII);\n for (auto &Op : Lead->operands()) {\n if (Op.isReg())\n RecalcRegs.insert(Op.getReg());\n }\n\n LIS->RemoveMachineInstrFromMaps(*Lead);\n Lead->eraseFromParent();\n if (SaveExecReg) {\n LIS->removeInterval(SaveExecReg);\n LIS->createAndComputeVirtRegInterval(SaveExecReg);\n }\n\n Changed = true;\n\n \/\/ If the only use of saved exec in the removed instruction is S_AND_B64\n \/\/ fold the copy now.\n if (!SaveExec || !SaveExec->isFullCopy())\n continue;\n\n unsigned SavedExec = SaveExec->getOperand(0).getReg();\n bool SafeToReplace = true;\n for (auto& U : MRI.use_nodbg_instructions(SavedExec)) {\n if (U.getParent() != SaveExec->getParent()) {\n SafeToReplace = false;\n break;\n }\n\n LLVM_DEBUG(dbgs() << \"Redundant EXEC COPY: \" << *SaveExec << '\\n');\n }\n\n if (SafeToReplace) {\n LIS->RemoveMachineInstrFromMaps(*SaveExec);\n SaveExec->eraseFromParent();\n MRI.replaceRegWith(SavedExec, AMDGPU::EXEC);\n LIS->removeInterval(SavedExec);\n }\n }\n\n if (Changed) {\n for (auto Reg : RecalcRegs) {\n if (TargetRegisterInfo::isVirtualRegister(Reg)) {\n LIS->removeInterval(Reg);\n if (!MRI.reg_empty(Reg))\n LIS->createAndComputeVirtRegInterval(Reg);\n } else {\n for (MCRegUnitIterator U(Reg, TRI); U.isValid(); ++U)\n LIS->removeRegUnit(*U);\n }\n }\n }\n\n return Changed;\n}\n[AMDGPU] Fix build failure, second attempt\/\/===-- SIOptimizeExecMaskingPreRA.cpp ------------------------------------===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/\/ \\file\n\/\/\/ This pass removes redundant S_OR_B64 instructions enabling lanes in\n\/\/\/ the exec. If two SI_END_CF (lowered as S_OR_B64) come together without any\n\/\/\/ vector instructions between them we can only keep outer SI_END_CF, given\n\/\/\/ that CFG is structured and exec bits of the outer end statement are always\n\/\/\/ not less than exec bit of the inner one.\n\/\/\/\n\/\/\/ This needs to be done before the RA to eliminate saved exec bits registers\n\/\/\/ but after register coalescer to have no vector registers copies in between\n\/\/\/ of different end cf statements.\n\/\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"AMDGPU.h\"\n#include \"AMDGPUSubtarget.h\"\n#include \"SIInstrInfo.h\"\n#include \"MCTargetDesc\/AMDGPUMCTargetDesc.h\"\n#include \"llvm\/CodeGen\/LiveIntervals.h\"\n#include \"llvm\/CodeGen\/MachineFunctionPass.h\"\n\nusing namespace llvm;\n\n#define DEBUG_TYPE \"si-optimize-exec-masking-pre-ra\"\n\nnamespace {\n\nclass SIOptimizeExecMaskingPreRA : public MachineFunctionPass {\npublic:\n static char ID;\n\npublic:\n SIOptimizeExecMaskingPreRA() : MachineFunctionPass(ID) {\n initializeSIOptimizeExecMaskingPreRAPass(*PassRegistry::getPassRegistry());\n }\n\n bool runOnMachineFunction(MachineFunction &MF) override;\n\n StringRef getPassName() const override {\n return \"SI optimize exec mask operations pre-RA\";\n }\n\n void getAnalysisUsage(AnalysisUsage &AU) const override {\n AU.addRequired();\n AU.setPreservesAll();\n MachineFunctionPass::getAnalysisUsage(AU);\n }\n};\n\n} \/\/ End anonymous namespace.\n\nINITIALIZE_PASS_BEGIN(SIOptimizeExecMaskingPreRA, DEBUG_TYPE,\n \"SI optimize exec mask operations pre-RA\", false, false)\nINITIALIZE_PASS_DEPENDENCY(LiveIntervals)\nINITIALIZE_PASS_END(SIOptimizeExecMaskingPreRA, DEBUG_TYPE,\n \"SI optimize exec mask operations pre-RA\", false, false)\n\nchar SIOptimizeExecMaskingPreRA::ID = 0;\n\nchar &llvm::SIOptimizeExecMaskingPreRAID = SIOptimizeExecMaskingPreRA::ID;\n\nFunctionPass *llvm::createSIOptimizeExecMaskingPreRAPass() {\n return new SIOptimizeExecMaskingPreRA();\n}\n\nstatic bool isEndCF(const MachineInstr& MI, const SIRegisterInfo* TRI) {\n return MI.getOpcode() == AMDGPU::S_OR_B64 &&\n MI.modifiesRegister(AMDGPU::EXEC, TRI);\n}\n\nstatic bool isFullExecCopy(const MachineInstr& MI) {\n return MI.isFullCopy() && MI.getOperand(1).getReg() == AMDGPU::EXEC;\n}\n\nstatic unsigned getOrNonExecReg(const MachineInstr &MI,\n const SIInstrInfo &TII) {\n auto Op = TII.getNamedOperand(MI, AMDGPU::OpName::src1);\n if (Op->isReg() && Op->getReg() != AMDGPU::EXEC)\n return Op->getReg();\n Op = TII.getNamedOperand(MI, AMDGPU::OpName::src0);\n if (Op->isReg() && Op->getReg() != AMDGPU::EXEC)\n return Op->getReg();\n return AMDGPU::NoRegister;\n}\n\nstatic MachineInstr* getOrExecSource(const MachineInstr &MI,\n const SIInstrInfo &TII,\n const MachineRegisterInfo &MRI) {\n auto SavedExec = getOrNonExecReg(MI, TII);\n if (SavedExec == AMDGPU::NoRegister)\n return nullptr;\n auto SaveExecInst = MRI.getUniqueVRegDef(SavedExec);\n if (!SaveExecInst || !isFullExecCopy(*SaveExecInst))\n return nullptr;\n return SaveExecInst;\n}\n\n\/\/ Optimize sequence\n\/\/ %sel = V_CNDMASK_B32_e64 0, 1, %cc\n\/\/ %cmp = V_CMP_NE_U32 1, %1\n\/\/ $vcc = S_AND_B64 $exec, %cmp\n\/\/ S_CBRANCH_VCC[N]Z\n\/\/ =>\n\/\/ $vcc = S_ANDN2_B64 $exec, %cc\n\/\/ S_CBRANCH_VCC[N]Z\n\/\/\n\/\/ It is the negation pattern inserted by DAGCombiner::visitBRCOND() in the\n\/\/ rebuildSetCC(). We start with S_CBRANCH to avoid exhaustive search, but\n\/\/ only 3 first instructions are really needed. S_AND_B64 with exec is a\n\/\/ required part of the pattern since V_CNDMASK_B32 writes zeroes for inactive\n\/\/ lanes.\n\/\/\n\/\/ Returns %cc register on success.\nstatic unsigned optimizeVcndVcmpPair(MachineBasicBlock &MBB,\n const GCNSubtarget &ST,\n MachineRegisterInfo &MRI,\n LiveIntervals *LIS) {\n const SIRegisterInfo *TRI = ST.getRegisterInfo();\n const SIInstrInfo *TII = ST.getInstrInfo();\n const unsigned AndOpc = AMDGPU::S_AND_B64;\n const unsigned Andn2Opc = AMDGPU::S_ANDN2_B64;\n const unsigned CondReg = AMDGPU::VCC;\n const unsigned ExecReg = AMDGPU::EXEC;\n\n auto I = llvm::find_if(MBB.terminators(), [](const MachineInstr &MI) {\n unsigned Opc = MI.getOpcode();\n return Opc == AMDGPU::S_CBRANCH_VCCZ ||\n Opc == AMDGPU::S_CBRANCH_VCCNZ; });\n if (I == MBB.terminators().end())\n return AMDGPU::NoRegister;\n\n auto *And = TRI->findReachingDef(CondReg, AMDGPU::NoSubRegister,\n *I, MRI, LIS);\n if (!And || And->getOpcode() != AndOpc ||\n !And->getOperand(1).isReg() || !And->getOperand(2).isReg())\n return AMDGPU::NoRegister;\n\n MachineOperand *AndCC = &And->getOperand(1);\n unsigned CmpReg = AndCC->getReg();\n unsigned CmpSubReg = AndCC->getSubReg();\n if (CmpReg == ExecReg) {\n AndCC = &And->getOperand(2);\n CmpReg = AndCC->getReg();\n CmpSubReg = AndCC->getSubReg();\n } else if (And->getOperand(2).getReg() != ExecReg) {\n return AMDGPU::NoRegister;\n }\n\n auto *Cmp = TRI->findReachingDef(CmpReg, CmpSubReg, *And, MRI, LIS);\n if (!Cmp || !(Cmp->getOpcode() == AMDGPU::V_CMP_NE_U32_e32 ||\n Cmp->getOpcode() == AMDGPU::V_CMP_NE_U32_e64) ||\n Cmp->getParent() != And->getParent())\n return AMDGPU::NoRegister;\n\n MachineOperand *Op1 = TII->getNamedOperand(*Cmp, AMDGPU::OpName::src0);\n MachineOperand *Op2 = TII->getNamedOperand(*Cmp, AMDGPU::OpName::src1);\n if (Op1->isImm() && Op2->isReg())\n std::swap(Op1, Op2);\n if (!Op1->isReg() || !Op2->isImm() || Op2->getImm() != 1)\n return AMDGPU::NoRegister;\n\n unsigned SelReg = Op1->getReg();\n auto *Sel = TRI->findReachingDef(SelReg, Op1->getSubReg(), *Cmp, MRI, LIS);\n if (!Sel || Sel->getOpcode() != AMDGPU::V_CNDMASK_B32_e64)\n return AMDGPU::NoRegister;\n\n Op1 = TII->getNamedOperand(*Sel, AMDGPU::OpName::src0);\n Op2 = TII->getNamedOperand(*Sel, AMDGPU::OpName::src1);\n MachineOperand *CC = TII->getNamedOperand(*Sel, AMDGPU::OpName::src2);\n if (!Op1->isImm() || !Op2->isImm() || !CC->isReg() ||\n Op1->getImm() != 0 || Op2->getImm() != 1)\n return AMDGPU::NoRegister;\n\n LLVM_DEBUG(dbgs() << \"Folding sequence:\\n\\t\" << *Sel << '\\t'\n << *Cmp << '\\t' << *And);\n\n unsigned CCReg = CC->getReg();\n LIS->RemoveMachineInstrFromMaps(*And);\n MachineInstr *Andn2 = BuildMI(MBB, *And, And->getDebugLoc(),\n TII->get(Andn2Opc), And->getOperand(0).getReg())\n .addReg(ExecReg)\n .addReg(CCReg, CC->getSubReg());\n And->eraseFromParent();\n LIS->InsertMachineInstrInMaps(*Andn2);\n\n LLVM_DEBUG(dbgs() << \"=>\\n\\t\" << *Andn2 << '\\n');\n\n \/\/ Try to remove compare. Cmp value should not used in between of cmp\n \/\/ and s_and_b64 if VCC or just unused if any other register.\n if ((TargetRegisterInfo::isVirtualRegister(CmpReg) &&\n MRI.use_nodbg_empty(CmpReg)) ||\n (CmpReg == CondReg &&\n std::none_of(std::next(Cmp->getIterator()), Andn2->getIterator(),\n [&](const MachineInstr &MI) {\n return MI.readsRegister(CondReg, TRI); }))) {\n LLVM_DEBUG(dbgs() << \"Erasing: \" << *Cmp << '\\n');\n\n LIS->RemoveMachineInstrFromMaps(*Cmp);\n Cmp->eraseFromParent();\n\n \/\/ Try to remove v_cndmask_b32.\n if (TargetRegisterInfo::isVirtualRegister(SelReg) &&\n MRI.use_nodbg_empty(SelReg)) {\n LLVM_DEBUG(dbgs() << \"Erasing: \" << *Sel << '\\n');\n\n LIS->RemoveMachineInstrFromMaps(*Sel);\n Sel->eraseFromParent();\n }\n }\n\n return CCReg;\n}\n\nbool SIOptimizeExecMaskingPreRA::runOnMachineFunction(MachineFunction &MF) {\n if (skipFunction(MF.getFunction()))\n return false;\n\n const GCNSubtarget &ST = MF.getSubtarget();\n const SIRegisterInfo *TRI = ST.getRegisterInfo();\n const SIInstrInfo *TII = ST.getInstrInfo();\n MachineRegisterInfo &MRI = MF.getRegInfo();\n LiveIntervals *LIS = &getAnalysis();\n DenseSet RecalcRegs({AMDGPU::EXEC_LO, AMDGPU::EXEC_HI});\n bool Changed = false;\n\n for (MachineBasicBlock &MBB : MF) {\n\n if (unsigned Reg = optimizeVcndVcmpPair(MBB, ST, MRI, LIS)) {\n RecalcRegs.insert(Reg);\n RecalcRegs.insert(AMDGPU::VCC_LO);\n RecalcRegs.insert(AMDGPU::VCC_HI);\n RecalcRegs.insert(AMDGPU::SCC);\n Changed = true;\n }\n\n \/\/ Try to remove unneeded instructions before s_endpgm.\n if (MBB.succ_empty()) {\n if (MBB.empty())\n continue;\n\n \/\/ Skip this if the endpgm has any implicit uses, otherwise we would need\n \/\/ to be careful to update \/ remove them.\n MachineInstr &Term = MBB.back();\n if (Term.getOpcode() != AMDGPU::S_ENDPGM ||\n Term.getNumOperands() != 0)\n continue;\n\n SmallVector Blocks({&MBB});\n\n while (!Blocks.empty()) {\n auto CurBB = Blocks.pop_back_val();\n auto I = CurBB->rbegin(), E = CurBB->rend();\n if (I != E) {\n if (I->isUnconditionalBranch() || I->getOpcode() == AMDGPU::S_ENDPGM)\n ++I;\n else if (I->isBranch())\n continue;\n }\n\n while (I != E) {\n if (I->isDebugInstr()) {\n I = std::next(I);\n continue;\n }\n\n if (I->mayStore() || I->isBarrier() || I->isCall() ||\n I->hasUnmodeledSideEffects() || I->hasOrderedMemoryRef())\n break;\n\n LLVM_DEBUG(dbgs()\n << \"Removing no effect instruction: \" << *I << '\\n');\n\n for (auto &Op : I->operands()) {\n if (Op.isReg())\n RecalcRegs.insert(Op.getReg());\n }\n\n auto Next = std::next(I);\n LIS->RemoveMachineInstrFromMaps(*I);\n I->eraseFromParent();\n I = Next;\n\n Changed = true;\n }\n\n if (I != E)\n continue;\n\n \/\/ Try to ascend predecessors.\n for (auto *Pred : CurBB->predecessors()) {\n if (Pred->succ_size() == 1)\n Blocks.push_back(Pred);\n }\n }\n continue;\n }\n\n \/\/ Try to collapse adjacent endifs.\n auto Lead = MBB.begin(), E = MBB.end();\n if (MBB.succ_size() != 1 || Lead == E || !isEndCF(*Lead, TRI))\n continue;\n\n const MachineBasicBlock* Succ = *MBB.succ_begin();\n if (!MBB.isLayoutSuccessor(Succ))\n continue;\n\n auto I = std::next(Lead);\n\n for ( ; I != E; ++I)\n if (!TII->isSALU(*I) || I->readsRegister(AMDGPU::EXEC, TRI))\n break;\n\n if (I != E)\n continue;\n\n const auto NextLead = Succ->begin();\n if (NextLead == Succ->end() || !isEndCF(*NextLead, TRI) ||\n !getOrExecSource(*NextLead, *TII, MRI))\n continue;\n\n LLVM_DEBUG(dbgs() << \"Redundant EXEC = S_OR_B64 found: \" << *Lead << '\\n');\n\n auto SaveExec = getOrExecSource(*Lead, *TII, MRI);\n unsigned SaveExecReg = getOrNonExecReg(*Lead, *TII);\n for (auto &Op : Lead->operands()) {\n if (Op.isReg())\n RecalcRegs.insert(Op.getReg());\n }\n\n LIS->RemoveMachineInstrFromMaps(*Lead);\n Lead->eraseFromParent();\n if (SaveExecReg) {\n LIS->removeInterval(SaveExecReg);\n LIS->createAndComputeVirtRegInterval(SaveExecReg);\n }\n\n Changed = true;\n\n \/\/ If the only use of saved exec in the removed instruction is S_AND_B64\n \/\/ fold the copy now.\n if (!SaveExec || !SaveExec->isFullCopy())\n continue;\n\n unsigned SavedExec = SaveExec->getOperand(0).getReg();\n bool SafeToReplace = true;\n for (auto& U : MRI.use_nodbg_instructions(SavedExec)) {\n if (U.getParent() != SaveExec->getParent()) {\n SafeToReplace = false;\n break;\n }\n\n LLVM_DEBUG(dbgs() << \"Redundant EXEC COPY: \" << *SaveExec << '\\n');\n }\n\n if (SafeToReplace) {\n LIS->RemoveMachineInstrFromMaps(*SaveExec);\n SaveExec->eraseFromParent();\n MRI.replaceRegWith(SavedExec, AMDGPU::EXEC);\n LIS->removeInterval(SavedExec);\n }\n }\n\n if (Changed) {\n for (auto Reg : RecalcRegs) {\n if (TargetRegisterInfo::isVirtualRegister(Reg)) {\n LIS->removeInterval(Reg);\n if (!MRI.reg_empty(Reg))\n LIS->createAndComputeVirtRegInterval(Reg);\n } else {\n for (MCRegUnitIterator U(Reg, TRI); U.isValid(); ++U)\n LIS->removeRegUnit(*U);\n }\n }\n }\n\n return Changed;\n}\n<|endoftext|>"} {"text":"\/* Copyright 2017 The TensorFlow Authors. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*\/\n\n#include \"tensorflow\/compiler\/xla\/service\/compile_only_service.h\"\n\n#include \n#include \n#include \n\n#include \"absl\/strings\/str_cat.h\"\n#include \"tensorflow\/compiler\/xla\/debug_options_flags.h\"\n#include \"tensorflow\/compiler\/xla\/service\/backend.h\"\n#include \"tensorflow\/compiler\/xla\/service\/computation_layout.h\"\n#include \"tensorflow\/compiler\/xla\/service\/dump.h\"\n#include \"tensorflow\/compiler\/xla\/service\/platform_util.h\"\n#include \"tensorflow\/compiler\/xla\/status_macros.h\"\n#include \"tensorflow\/compiler\/xla\/types.h\"\n#include \"tensorflow\/compiler\/xla\/util.h\"\n#include \"tensorflow\/core\/lib\/gtl\/cleanup.h\"\n#include \"tensorflow\/core\/lib\/io\/path.h\"\n#include \"tensorflow\/core\/platform\/host_info.h\"\n#include \"tensorflow\/core\/platform\/logging.h\"\n#include \"tensorflow\/core\/platform\/stream_executor_no_cuda.h\"\n\nnamespace xla {\n\n\/* static *\/ StatusOr>\nCompileOnlyService::NewService(se::Platform* platform) {\n ServiceOptions default_options;\n default_options.set_platform(platform);\n return NewService(default_options);\n}\n\n\/* static *\/ StatusOr>\nCompileOnlyService::NewService(const ServiceOptions& options) {\n se::Platform* platform = options.platform();\n if (platform == nullptr) {\n TF_ASSIGN_OR_RETURN(platform, PlatformUtil::GetDefaultPlatform());\n }\n\n TF_ASSIGN_OR_RETURN(auto compiler, Compiler::GetForPlatform(platform));\n\n std::unique_ptr service(\n new CompileOnlyService(options, compiler));\n return std::move(service);\n}\n\nCompileOnlyService::CompileOnlyService(const ServiceOptions& options,\n Compiler* compiler)\n : Service(options, \/*execute_backend=*\/nullptr), compiler_(compiler) {}\n\nStatusOr>>\nCompileOnlyService::CompileAheadOfTime(\n const absl::Span computations,\n const AotCompilationOptions& options,\n std::unique_ptr* metadata) {\n std::vector> hlo_modules;\n\n const DebugOptions& debug_options = options.debug_options();\n ExecutionOptions execution_options;\n *execution_options.mutable_debug_options() = debug_options;\n\n for (const AotXlaComputationInstance& instance : computations) {\n TF_RET_CHECK(instance.computation.has_host_program_shape());\n *execution_options.mutable_shape_with_output_layout() =\n instance.result_layout->ToProto();\n\n TF_ASSIGN_OR_RETURN(\n std::unique_ptr module_config,\n CreateModuleConfig(\n ProgramShape(instance.computation.host_program_shape()),\n instance.argument_layouts, &execution_options, &options));\n\n TF_ASSIGN_OR_RETURN(\n std::unique_ptr hlo_module,\n HloModule::CreateFromProto(instance.computation, *module_config));\n DumpHloModuleIfEnabled(*hlo_module, \"before_optimizations\");\n hlo_modules.push_back(std::move(hlo_module));\n }\n\n \/\/ Capture replica_count, num_cores, and device_assignment in ExecutionOptions\n \/\/ to save in a proto dump.\n if (options.replica_count() > 0) {\n execution_options.set_num_replicas(options.replica_count());\n if (options.has_static_device_assignment()) {\n CHECK_EQ(options.replica_count(),\n options.static_device_assignment().replica_count());\n }\n }\n if (options.num_cores() > 0) {\n execution_options.set_num_partitions(options.num_cores());\n if (options.has_static_device_assignment()) {\n CHECK_EQ(options.num_cores(),\n options.static_device_assignment().computation_count());\n }\n }\n if (options.has_static_device_assignment()) {\n TF_RETURN_IF_ERROR(options.static_device_assignment().Serialize(\n execution_options.mutable_device_assignment()));\n }\n execution_options.clear_shape_with_output_layout();\n DumpExecutionOptions(execution_options, debug_options);\n\n return compiler_->CompileAheadOfTime(\n absl::make_unique(hlo_modules[0]->name(),\n absl::MakeSpan(hlo_modules)),\n options, metadata);\n}\n\n} \/\/ namespace xla\n[XLA] Fix device assignemnt passing\/* Copyright 2017 The TensorFlow Authors. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*\/\n\n#include \"tensorflow\/compiler\/xla\/service\/compile_only_service.h\"\n\n#include \n#include \n#include \n\n#include \"absl\/strings\/str_cat.h\"\n#include \"tensorflow\/compiler\/xla\/debug_options_flags.h\"\n#include \"tensorflow\/compiler\/xla\/service\/backend.h\"\n#include \"tensorflow\/compiler\/xla\/service\/computation_layout.h\"\n#include \"tensorflow\/compiler\/xla\/service\/dump.h\"\n#include \"tensorflow\/compiler\/xla\/service\/platform_util.h\"\n#include \"tensorflow\/compiler\/xla\/status_macros.h\"\n#include \"tensorflow\/compiler\/xla\/types.h\"\n#include \"tensorflow\/compiler\/xla\/util.h\"\n#include \"tensorflow\/core\/lib\/gtl\/cleanup.h\"\n#include \"tensorflow\/core\/lib\/io\/path.h\"\n#include \"tensorflow\/core\/platform\/host_info.h\"\n#include \"tensorflow\/core\/platform\/logging.h\"\n#include \"tensorflow\/core\/platform\/stream_executor_no_cuda.h\"\n\nnamespace xla {\n\n\/* static *\/ StatusOr>\nCompileOnlyService::NewService(se::Platform* platform) {\n ServiceOptions default_options;\n default_options.set_platform(platform);\n return NewService(default_options);\n}\n\n\/* static *\/ StatusOr>\nCompileOnlyService::NewService(const ServiceOptions& options) {\n se::Platform* platform = options.platform();\n if (platform == nullptr) {\n TF_ASSIGN_OR_RETURN(platform, PlatformUtil::GetDefaultPlatform());\n }\n\n TF_ASSIGN_OR_RETURN(auto compiler, Compiler::GetForPlatform(platform));\n\n std::unique_ptr service(\n new CompileOnlyService(options, compiler));\n return std::move(service);\n}\n\nCompileOnlyService::CompileOnlyService(const ServiceOptions& options,\n Compiler* compiler)\n : Service(options, \/*execute_backend=*\/nullptr), compiler_(compiler) {}\n\nStatusOr>>\nCompileOnlyService::CompileAheadOfTime(\n const absl::Span computations,\n const AotCompilationOptions& options,\n std::unique_ptr* metadata) {\n std::vector> hlo_modules;\n\n const DebugOptions& debug_options = options.debug_options();\n ExecutionOptions execution_options;\n *execution_options.mutable_debug_options() = debug_options;\n \/\/ Capture replica_count, num_cores, and device_assignment in ExecutionOptions\n \/\/ to later save in a proto dump.\n if (options.replica_count() > 0) {\n execution_options.set_num_replicas(options.replica_count());\n if (options.has_static_device_assignment()) {\n CHECK_EQ(options.replica_count(),\n options.static_device_assignment().replica_count());\n }\n }\n if (options.num_cores() > 0) {\n execution_options.set_num_partitions(options.num_cores());\n if (options.has_static_device_assignment()) {\n CHECK_EQ(options.num_cores(),\n options.static_device_assignment().computation_count());\n }\n }\n if (options.has_static_device_assignment()) {\n TF_RETURN_IF_ERROR(options.static_device_assignment().Serialize(\n execution_options.mutable_device_assignment()));\n }\n for (const AotXlaComputationInstance& instance : computations) {\n TF_RET_CHECK(instance.computation.has_host_program_shape());\n *execution_options.mutable_shape_with_output_layout() =\n instance.result_layout->ToProto();\n\n TF_ASSIGN_OR_RETURN(\n std::unique_ptr module_config,\n CreateModuleConfig(\n ProgramShape(instance.computation.host_program_shape()),\n instance.argument_layouts, &execution_options, &options));\n\n TF_ASSIGN_OR_RETURN(\n std::unique_ptr hlo_module,\n HloModule::CreateFromProto(instance.computation, *module_config));\n DumpHloModuleIfEnabled(*hlo_module, \"before_optimizations\");\n hlo_modules.push_back(std::move(hlo_module));\n }\n\n execution_options.clear_shape_with_output_layout();\n DumpExecutionOptions(execution_options, debug_options);\n\n return compiler_->CompileAheadOfTime(\n absl::make_unique(hlo_modules[0]->name(),\n absl::MakeSpan(hlo_modules)),\n options, metadata);\n}\n\n} \/\/ namespace xla\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n\n#include \"bm_sim\/queue.h\"\n#include \"bm_sim\/packet.h\"\n#include \"bm_sim\/parser.h\"\n#include \"bm_sim\/P4Objects.h\"\n#include \"bm_sim\/tables.h\"\n#include \"bm_sim\/switch.h\"\n#include \"bm_sim\/event_logger.h\"\n\n#include \"simple_router.h\"\n#include \"primitives.h\"\n#include \"simplelog.h\"\n\n#include \"bm_runtime\/bm_runtime.h\"\n\nclass SimpleSwitch : public Switch {\npublic:\n SimpleSwitch(transmit_fn_t transmit_fn)\n : input_buffer(1024), output_buffer(128), transmit_fn(transmit_fn) {}\n\n int receive(int port_num, const char *buffer, int len) {\n static int pkt_id = 0;\n\n Packet *packet =\n new Packet(port_num, pkt_id++, 0, PacketBuffer(2048, buffer, len));\n\n ELOGGER->packet_in(*packet);\n\n input_buffer.push_front(std::unique_ptr(packet));\n return 0;\n }\n\n void start_and_return() {\n std::thread t1(&SimpleSwitch::pipeline_thread, this);\n t1.detach();\n std::thread t2(&SimpleSwitch::transmit_thread, this);\n t2.detach();\n }\n\nprivate:\n void pipeline_thread();\n void transmit_thread();\n\nprivate:\n Queue > input_buffer;\n Queue > output_buffer;\n transmit_fn_t transmit_fn;\n};\n\nvoid SimpleSwitch::transmit_thread() {\n while(1) {\n unique_ptr packet;\n output_buffer.pop_back(&packet);\n ELOGGER->packet_out(*packet);\n SIMPLELOG << \"transmitting packet \" << packet->get_packet_id() << std::endl;\n transmit_fn(packet->get_egress_port(), packet->data(), packet->get_data_size());\n }\n}\n\nvoid SimpleSwitch::pipeline_thread() {\n Pipeline *ingress_mau = p4objects->get_pipeline(\"ingress\");\n Pipeline *egress_mau = p4objects->get_pipeline(\"egress\");\n Parser *parser = p4objects->get_parser(\"parser\");\n Deparser *deparser = p4objects->get_deparser(\"deparser\");\n PHV &phv = p4objects->get_phv();\n\n while(1) {\n unique_ptr packet;\n input_buffer.pop_back(&packet);\n SIMPLELOG << \"processing packet \" << packet->get_packet_id() << std::endl;\n \n parser->parse(packet.get(), &phv);\n ingress_mau->apply(*packet.get(), &phv);\n\n int egress_port = phv.get_field(\"standard_metadata.egress_port\").get_int();\n SIMPLELOG << \"egress port is \" << egress_port << std::endl; \n\n if(egress_port == 0) {\n SIMPLELOG << \"dropping packet\\n\";\n }\n else {\n packet->set_egress_port(egress_port);\n egress_mau->apply(*packet.get(), &phv);\n deparser->deparse(&phv, packet.get());\n output_buffer.push_front(std::move(packet));\n }\n }\n}\n\n\/* Switch instance *\/\n\nstatic SimpleSwitch *simple_switch;\n\n\nint packet_accept(int port_num, const char *buffer, int len) {\n return simple_switch->receive(port_num, buffer, len);\n}\n\nvoid start_processing(transmit_fn_t transmit_fn) {\n simple_switch = new SimpleSwitch(transmit_fn);\n simple_switch->init_objects(\"simple_router.json\");\n\n bm_runtime::start_server(simple_switch, 9090);\n\n \/\/ add_test_entry();\n\n simple_switch->start_and_return();\n}\n\nfixed simple_router target#include \n#include \n#include \n#include \n\n#include \"bm_sim\/queue.h\"\n#include \"bm_sim\/packet.h\"\n#include \"bm_sim\/parser.h\"\n#include \"bm_sim\/P4Objects.h\"\n#include \"bm_sim\/tables.h\"\n#include \"bm_sim\/switch.h\"\n#include \"bm_sim\/event_logger.h\"\n\n#include \"simple_router.h\"\n#include \"primitives.h\"\n#include \"simplelog.h\"\n\n#include \"bm_runtime\/bm_runtime.h\"\n\nclass SimpleSwitch : public Switch {\npublic:\n SimpleSwitch(transmit_fn_t transmit_fn)\n : input_buffer(1024), output_buffer(128), transmit_fn(transmit_fn) {}\n\n int receive(int port_num, const char *buffer, int len) {\n static int pkt_id = 0;\n\n Packet *packet =\n new Packet(port_num, pkt_id++, 0, PacketBuffer(2048, buffer, len));\n\n ELOGGER->packet_in(*packet);\n\n input_buffer.push_front(std::unique_ptr(packet));\n return 0;\n }\n\n void start_and_return() {\n std::thread t1(&SimpleSwitch::pipeline_thread, this);\n t1.detach();\n std::thread t2(&SimpleSwitch::transmit_thread, this);\n t2.detach();\n }\n\nprivate:\n void pipeline_thread();\n void transmit_thread();\n\nprivate:\n Queue > input_buffer;\n Queue > output_buffer;\n transmit_fn_t transmit_fn;\n};\n\nvoid SimpleSwitch::transmit_thread() {\n while(1) {\n unique_ptr packet;\n output_buffer.pop_back(&packet);\n ELOGGER->packet_out(*packet);\n SIMPLELOG << \"transmitting packet \" << packet->get_packet_id() << std::endl;\n transmit_fn(packet->get_egress_port(), packet->data(), packet->get_data_size());\n }\n}\n\nvoid SimpleSwitch::pipeline_thread() {\n Pipeline *ingress_mau = p4objects->get_pipeline(\"ingress\");\n Pipeline *egress_mau = p4objects->get_pipeline(\"egress\");\n Parser *parser = p4objects->get_parser(\"parser\");\n Deparser *deparser = p4objects->get_deparser(\"deparser\");\n PHV *phv;\n\n while(1) {\n unique_ptr packet;\n input_buffer.pop_back(&packet);\n phv = packet->get_phv();\n SIMPLELOG << \"processing packet \" << packet->get_packet_id() << std::endl;\n \n parser->parse(packet.get());\n ingress_mau->apply(packet.get());\n\n int egress_port = phv->get_field(\"standard_metadata.egress_port\").get_int();\n SIMPLELOG << \"egress port is \" << egress_port << std::endl; \n\n if(egress_port == 0) {\n SIMPLELOG << \"dropping packet\\n\";\n }\n else {\n packet->set_egress_port(egress_port);\n egress_mau->apply(packet.get());\n deparser->deparse(packet.get());\n output_buffer.push_front(std::move(packet));\n }\n }\n}\n\n\/* Switch instance *\/\n\nstatic SimpleSwitch *simple_switch;\n\n\nint packet_accept(int port_num, const char *buffer, int len) {\n return simple_switch->receive(port_num, buffer, len);\n}\n\nvoid start_processing(transmit_fn_t transmit_fn) {\n simple_switch = new SimpleSwitch(transmit_fn);\n simple_switch->init_objects(\"simple_router.json\");\n\n bm_runtime::start_server(simple_switch, 9090);\n\n \/\/ add_test_entry();\n\n simple_switch->start_and_return();\n}\n\n<|endoftext|>"} {"text":"\n#include \n#include \"task_manager_lib\/TaskDefinition.h\"\nusing namespace task_manager_lib;\n\nvoid TaskDefinition::setName(const std::string & n) {\n\tname = n;\n}\n\nconst std::string & TaskDefinition::getName() const {\n\treturn name;\n}\n\nconst std::string & TaskDefinition::getHelp() const {\n\treturn help;\n}\n\nconst TaskParameters & TaskDefinition::getConfig() const {\n\treturn config;\n}\n\nbool TaskDefinition::isPeriodic() const {\n\treturn periodic;\n}\n\ndouble TaskDefinition::getTimeout() const {\n\treturn timeout;\n}\n\nTaskIndicator TaskDefinition::getStatus() const {\n\t\/\/ printf(\"TaskDefinition: status of %s: %s\\n\",name.c_str(),taskStatusToString(taskStatus));\n\treturn taskStatus;\n}\n\ntask_manager_msgs::TaskStatus TaskDefinition::getRosStatus() const {\n task_manager_msgs::TaskStatus st;\n st.name = this->getName();\n st.status = this->getStatus();\n st.status_string = this->getStatusString();\n st.plist = this->getConfig();\n return st;\n}\n\ntask_manager_msgs::TaskDescription TaskDefinition::getDescription() const {\n task_manager_msgs::TaskDescription td;\n td.name = this->getName();\n td.description = this->getHelp();\n td.periodic = this->isPeriodic();\n td.timeout_s = this->getTimeout();\n td.config = this->getParameterDescription();\n return td;\n}\n\nvoid TaskDefinition::resetStatus() {\n\t\/\/ printf(\"TaskDefinition: status of %s: %s\\n\",name.c_str(),taskStatusToString(taskStatus));\n\ttaskStatus = task_manager_msgs::TaskStatus::TASK_CONFIGURED;\n}\n\nconst std::string & TaskDefinition::getStatusString() const {\n\treturn statusString;\n}\n\n\nvoid TaskDefinition::debug(const char *stemplate,...) const {\n\tva_list args;\n char buffer[1024];\n\tva_start(args, stemplate);\n\tvsnprintf(buffer,1023, stemplate,args);\n\tva_end(args);\n buffer[1023]=0;\n\tROS_DEBUG(\"%s: %s\",this->getName().c_str(),buffer);\n}\n\nvoid TaskDefinition::doConfigure(const TaskParameters & parameters)\n{\n config = this->getDefaultParameters();\n \/\/ printf(\"Configure %s: default values\\n\",this->getName().c_str());\n \/\/ config.print(stdout);\n \/\/ printf(\"Configure %s: proposed values\\n\",this->getName().c_str());\n \/\/ parameters.print(stdout);\n config.update(parameters);\n \/\/ printf(\"Configure %s: after update\\n\",this->getName().c_str());\n \/\/ config.print(stdout);\n\n parameters.getParameter(\"task_timeout\",timeout);\n\n\n\tstatusString.clear();\n\ttaskStatus = this->configure(parameters);\n}\n\nvoid TaskDefinition::doInitialise(const TaskParameters & parameters)\n{\n config.update(parameters);\n \/\/ printf(\"Initialise %s: after update\\n\",this->getName().c_str());\n \/\/ config.print(stdout);\n parameters.getParameter(\"task_timeout\",timeout);\n\tstatusString.clear();\n\ttaskStatus = this->initialise(parameters);\n}\n\nvoid TaskDefinition::doIterate()\n{\n\tstatusString.clear();\n\ttaskStatus = this->iterate();\n}\n\nvoid TaskDefinition::doTerminate()\n{\n\tstatusString.clear();\n\ttaskStatus = this->terminate();\n}\n\nconst char * task_manager_lib::taskStatusToString(TaskIndicator ts)\n{\n\tswitch (ts) {\n case task_manager_msgs::TaskStatus::TASK_NEWBORN: return \"NEWBORN\"; \n\t\tcase task_manager_msgs::TaskStatus::TASK_CONFIGURED: return \"CONFIGURED\";\n\t\tcase task_manager_msgs::TaskStatus::TASK_INITIALISED: return \"INITIALISED\";\n\t\tcase task_manager_msgs::TaskStatus::TASK_RUNNING: return \"RUNNING\";\n\t\tcase task_manager_msgs::TaskStatus::TASK_COMPLETED: return \"COMPLETED\";\n\t\tcase task_manager_msgs::TaskStatus::TASK_TERMINATED: return \"TERMINATED\";\n\t\tcase task_manager_msgs::TaskStatus::TASK_FAILED: return \"FAILED\";\n\t\tcase task_manager_msgs::TaskStatus::TASK_INTERRUPTED: return \"INTERRUPTED\";\n\t\tcase task_manager_msgs::TaskStatus::TASK_TIMEOUT: return \"TIMEOUT\";\n\t\tcase task_manager_msgs::TaskStatus::TASK_CONFIGURATION_FAILED: return \"CONFIGURATION FAILED\";\n\t\tcase task_manager_msgs::TaskStatus::TASK_INITIALISATION_FAILED: return \"INITIALISATION FAILED\";\n\t\tdefault: return \"INVALID STATUS\";\n\t}\n\treturn NULL;\n}\n\nBetter message output\n#include \n#include \"task_manager_lib\/TaskDefinition.h\"\nusing namespace task_manager_lib;\n\nvoid TaskDefinition::setName(const std::string & n) {\n\tname = n;\n}\n\nconst std::string & TaskDefinition::getName() const {\n\treturn name;\n}\n\nconst std::string & TaskDefinition::getHelp() const {\n\treturn help;\n}\n\nconst TaskParameters & TaskDefinition::getConfig() const {\n\treturn config;\n}\n\nbool TaskDefinition::isPeriodic() const {\n\treturn periodic;\n}\n\ndouble TaskDefinition::getTimeout() const {\n\treturn timeout;\n}\n\nTaskIndicator TaskDefinition::getStatus() const {\n\t\/\/ printf(\"TaskDefinition: status of %s: %s\\n\",name.c_str(),taskStatusToString(taskStatus));\n\treturn taskStatus;\n}\n\ntask_manager_msgs::TaskStatus TaskDefinition::getRosStatus() const {\n task_manager_msgs::TaskStatus st;\n st.name = this->getName();\n st.status = this->getStatus();\n st.status_string = this->getStatusString();\n st.plist = this->getConfig();\n return st;\n}\n\ntask_manager_msgs::TaskDescription TaskDefinition::getDescription() const {\n task_manager_msgs::TaskDescription td;\n td.name = this->getName();\n td.description = this->getHelp();\n td.periodic = this->isPeriodic();\n td.timeout_s = this->getTimeout();\n td.config = this->getParameterDescription();\n return td;\n}\n\nvoid TaskDefinition::resetStatus() {\n\t\/\/ printf(\"TaskDefinition: status of %s: %s\\n\",name.c_str(),taskStatusToString(taskStatus));\n\ttaskStatus = task_manager_msgs::TaskStatus::TASK_CONFIGURED;\n}\n\nconst std::string & TaskDefinition::getStatusString() const {\n\treturn statusString;\n}\n\n\nvoid TaskDefinition::debug(const char *stemplate,...) const {\n\tva_list args;\n char buffer[1024];\n\tva_start(args, stemplate);\n\tvsnprintf(buffer,1023, stemplate,args);\n\tva_end(args);\n buffer[1023]=0;\n\tROS_INFO(\"%s: %s\",this->getName().c_str(),buffer);\n}\n\nvoid TaskDefinition::doConfigure(const TaskParameters & parameters)\n{\n config = this->getDefaultParameters();\n \/\/ printf(\"Configure %s: default values\\n\",this->getName().c_str());\n \/\/ config.print(stdout);\n \/\/ printf(\"Configure %s: proposed values\\n\",this->getName().c_str());\n \/\/ parameters.print(stdout);\n config.update(parameters);\n \/\/ printf(\"Configure %s: after update\\n\",this->getName().c_str());\n \/\/ config.print(stdout);\n\n parameters.getParameter(\"task_timeout\",timeout);\n\n\n\tstatusString.clear();\n\ttaskStatus = this->configure(parameters);\n}\n\nvoid TaskDefinition::doInitialise(const TaskParameters & parameters)\n{\n config.update(parameters);\n \/\/ printf(\"Initialise %s: after update\\n\",this->getName().c_str());\n \/\/ config.print(stdout);\n parameters.getParameter(\"task_timeout\",timeout);\n\tstatusString.clear();\n\ttaskStatus = this->initialise(parameters);\n}\n\nvoid TaskDefinition::doIterate()\n{\n\tstatusString.clear();\n\ttaskStatus = this->iterate();\n}\n\nvoid TaskDefinition::doTerminate()\n{\n\tstatusString.clear();\n\ttaskStatus = this->terminate();\n}\n\nconst char * task_manager_lib::taskStatusToString(TaskIndicator ts)\n{\n\tswitch (ts) {\n case task_manager_msgs::TaskStatus::TASK_NEWBORN: return \"NEWBORN\"; \n\t\tcase task_manager_msgs::TaskStatus::TASK_CONFIGURED: return \"CONFIGURED\";\n\t\tcase task_manager_msgs::TaskStatus::TASK_INITIALISED: return \"INITIALISED\";\n\t\tcase task_manager_msgs::TaskStatus::TASK_RUNNING: return \"RUNNING\";\n\t\tcase task_manager_msgs::TaskStatus::TASK_COMPLETED: return \"COMPLETED\";\n\t\tcase task_manager_msgs::TaskStatus::TASK_TERMINATED: return \"TERMINATED\";\n\t\tcase task_manager_msgs::TaskStatus::TASK_FAILED: return \"FAILED\";\n\t\tcase task_manager_msgs::TaskStatus::TASK_INTERRUPTED: return \"INTERRUPTED\";\n\t\tcase task_manager_msgs::TaskStatus::TASK_TIMEOUT: return \"TIMEOUT\";\n\t\tcase task_manager_msgs::TaskStatus::TASK_CONFIGURATION_FAILED: return \"CONFIGURATION FAILED\";\n\t\tcase task_manager_msgs::TaskStatus::TASK_INITIALISATION_FAILED: return \"INITIALISATION FAILED\";\n\t\tdefault: return \"INVALID STATUS\";\n\t}\n\treturn NULL;\n}\n\n<|endoftext|>"} {"text":"\/* Copyright 2015 The TensorFlow Authors. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*\/\n\n#include \"tensorflow\/tools\/graph_transforms\/fold_constants_lib.h\"\n\n#include \"tensorflow\/core\/common_runtime\/constant_folding.h\"\n#include \"tensorflow\/core\/graph\/graph_constructor.h\"\n#include \"tensorflow\/core\/graph\/node_builder.h\"\n#include \"tensorflow\/core\/graph\/subgraph.h\"\n#include \"tensorflow\/core\/platform\/init_main.h\"\n#include \"tensorflow\/core\/public\/session.h\"\n#include \"tensorflow\/core\/util\/command_line_flags.h\"\n#include \"tensorflow\/tools\/graph_transforms\/transform_utils.h\"\n\nnamespace tensorflow {\nnamespace graph_transforms {\n\nStatus ReplaceSendRecvs(const GraphDef& original_graph_def,\n const GraphDef& rewritten_graph_def,\n const std::vector& inputs,\n const std::vector& outputs,\n GraphDef* output_graph_def) {\n std::map original_map;\n MapNamesToNodes(original_graph_def, &original_map);\n std::map new_node_names;\n for (const NodeDef& node : rewritten_graph_def.node()) {\n \/\/ If the op isn't a Recv, or it was in the original, nothing to do.\n if ((node.op() != \"_Recv\") || (original_map.count(node.name()) == 1)) {\n continue;\n }\n \/\/ See if it matches an input from the original.\n for (const string& input : inputs) {\n \/\/ Here we rely on the naming convention for the Recv nodes that\n \/\/ RewriteGraphForExecution adds in the place of the feed inputs.\n string input_prefix = \"_recv_\" + input + \"_\";\n if (StringPiece(node.name()).starts_with(input_prefix)) {\n \/\/ If it does, prepare to rename any inputs that refer to it.\n new_node_names[node.name()] = input;\n }\n }\n }\n\n std::vector nodes_to_add;\n for (const NodeDef& node : rewritten_graph_def.node()) {\n if ((node.op() == \"_Send\") || (node.op() == \"_Recv\")) {\n \/\/ If the op is a Send or Recv that wasn't in the original, skip it.\n if (original_map.count(node.name()) == 0) {\n continue;\n }\n }\n NodeDef new_node;\n new_node.CopyFrom(node);\n new_node.mutable_input()->Clear();\n for (const string& old_input : node.input()) {\n string input_prefix;\n string input_node_name;\n string input_suffix;\n NodeNamePartsFromInput(old_input, &input_prefix, &input_node_name,\n &input_suffix);\n string new_input;\n if (new_node_names.count(input_node_name) > 0) {\n new_input =\n input_prefix + new_node_names[input_node_name] + input_suffix;\n } else {\n new_input = old_input;\n }\n *(new_node.mutable_input()->Add()) = new_input;\n }\n nodes_to_add.push_back(new_node);\n }\n for (std::pair entry : new_node_names) {\n string removed_node_name = entry.second;\n const NodeDef* removed_node = original_map[removed_node_name];\n NodeDef new_node;\n new_node.CopyFrom(*removed_node);\n nodes_to_add.push_back(new_node);\n }\n\n for (const NodeDef& node : nodes_to_add) {\n output_graph_def->mutable_node()->Add()->CopyFrom(node);\n }\n return Status::OK();\n}\n\nStatus RemoveUnusedNodes(const GraphDef& input_graph_def,\n const std::vector& inputs,\n const std::vector& outputs,\n GraphDef* output_graph_def) {\n std::map node_map;\n MapNamesToNodes(input_graph_def, &node_map);\n\n std::map used_nodes;\n for (const string& input : inputs) {\n used_nodes[input] = true;\n }\n std::vector current_nodes = outputs;\n while (!current_nodes.empty()) {\n std::vector next_nodes;\n for (const string& node_name : current_nodes) {\n used_nodes[node_name] = true;\n if (node_map.count(node_name) == 0) {\n LOG(ERROR) << \"Bad graph structure, no node named '\" << node_name\n << \"' found for input lookup\";\n return errors::InvalidArgument(\"Bad graph structure, no node named '\",\n node_name, \"' found for input lookup\");\n }\n const NodeDef& node = *(node_map[node_name]);\n for (const string& input_name : node.input()) {\n const string& input_node_name = NodeNameFromInput(input_name);\n if (used_nodes.count(input_node_name) == 0) {\n next_nodes.push_back(input_node_name);\n }\n }\n }\n current_nodes = next_nodes;\n }\n FilterGraphDef(\n input_graph_def,\n [&](const NodeDef& node) { return used_nodes.count(node.name()) > 0; },\n output_graph_def);\n\n return Status::OK();\n}\n\nStatus FoldConstants(const GraphDef& input_graph_def,\n const std::vector& inputs,\n const std::vector& outputs,\n GraphDef* output_graph_def) {\n \/\/ Some older GraphDefs have saved _output_shapes attributes which are out of\n \/\/ date and cause import errors, so clean them up first.\n GraphDef cleaned_graph_def;\n RemoveAttributes(input_graph_def, {\"_output_shapes\"}, &cleaned_graph_def);\n Graph input_graph(OpRegistry::Global());\n ImportGraphDefOptions import_opts;\n TF_RETURN_IF_ERROR(\n ImportGraphDef(import_opts, cleaned_graph_def, &input_graph, nullptr));\n DeviceAttributes device_attributes;\n TF_RETURN_IF_ERROR(subgraph::RewriteGraphForExecution(\n &input_graph, inputs, outputs, {}, device_attributes));\n DoConstantFolding(ConstantFoldingOptions(), nullptr, Env::Default(), nullptr,\n &input_graph);\n GraphDef folded_graph_def;\n input_graph.ToGraphDef(&folded_graph_def);\n GraphDef send_recvs_replaced;\n TF_RETURN_IF_ERROR(ReplaceSendRecvs(input_graph_def, folded_graph_def, inputs,\n outputs, &send_recvs_replaced));\n TF_RETURN_IF_ERROR(RemoveUnusedNodes(send_recvs_replaced, inputs, outputs,\n output_graph_def));\n return Status::OK();\n}\n\n} \/\/ namespace graph_transforms\n} \/\/ namespace tensorflow\nImprove error handling for constant folding Change: 139124948\/* Copyright 2016 The TensorFlow Authors. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*\/\n\n#include \"tensorflow\/tools\/graph_transforms\/fold_constants_lib.h\"\n\n#include \"tensorflow\/core\/common_runtime\/constant_folding.h\"\n#include \"tensorflow\/core\/graph\/graph_constructor.h\"\n#include \"tensorflow\/core\/graph\/node_builder.h\"\n#include \"tensorflow\/core\/graph\/subgraph.h\"\n#include \"tensorflow\/core\/platform\/init_main.h\"\n#include \"tensorflow\/core\/public\/session.h\"\n#include \"tensorflow\/core\/util\/command_line_flags.h\"\n#include \"tensorflow\/tools\/graph_transforms\/transform_utils.h\"\n\nnamespace tensorflow {\nnamespace graph_transforms {\n\nStatus ReplaceSendRecvs(const GraphDef& original_graph_def,\n const GraphDef& rewritten_graph_def,\n const std::vector& inputs,\n const std::vector& outputs,\n GraphDef* output_graph_def) {\n std::map original_map;\n MapNamesToNodes(original_graph_def, &original_map);\n std::map new_node_names;\n for (const NodeDef& node : rewritten_graph_def.node()) {\n \/\/ If the op isn't a Recv, or it was in the original, nothing to do.\n if ((node.op() != \"_Recv\") || (original_map.count(node.name()) == 1)) {\n continue;\n }\n \/\/ See if it matches an input from the original.\n for (const string& input : inputs) {\n \/\/ Here we rely on the naming convention for the Recv nodes that\n \/\/ RewriteGraphForExecution adds in the place of the feed inputs.\n string input_prefix = \"_recv_\" + input + \"_\";\n if (StringPiece(node.name()).starts_with(input_prefix)) {\n \/\/ If it does, prepare to rename any inputs that refer to it.\n new_node_names[node.name()] = input;\n }\n }\n }\n\n std::vector nodes_to_add;\n for (const NodeDef& node : rewritten_graph_def.node()) {\n if ((node.op() == \"_Send\") || (node.op() == \"_Recv\")) {\n \/\/ If the op is a Send or Recv that wasn't in the original, skip it.\n if (original_map.count(node.name()) == 0) {\n continue;\n }\n }\n NodeDef new_node;\n new_node.CopyFrom(node);\n new_node.mutable_input()->Clear();\n for (const string& old_input : node.input()) {\n string input_prefix;\n string input_node_name;\n string input_suffix;\n NodeNamePartsFromInput(old_input, &input_prefix, &input_node_name,\n &input_suffix);\n string new_input;\n if (new_node_names.count(input_node_name) > 0) {\n new_input =\n input_prefix + new_node_names[input_node_name] + input_suffix;\n } else {\n new_input = old_input;\n }\n *(new_node.mutable_input()->Add()) = new_input;\n }\n nodes_to_add.push_back(new_node);\n }\n for (std::pair entry : new_node_names) {\n string removed_node_name = entry.second;\n const NodeDef* removed_node = original_map[removed_node_name];\n NodeDef new_node;\n new_node.CopyFrom(*removed_node);\n nodes_to_add.push_back(new_node);\n }\n\n for (const NodeDef& node : nodes_to_add) {\n output_graph_def->mutable_node()->Add()->CopyFrom(node);\n }\n return Status::OK();\n}\n\nStatus RemoveUnusedNodes(const GraphDef& input_graph_def,\n const std::vector& inputs,\n const std::vector& outputs,\n GraphDef* output_graph_def) {\n std::map node_map;\n MapNamesToNodes(input_graph_def, &node_map);\n\n std::map used_nodes;\n for (const string& input : inputs) {\n used_nodes[input] = true;\n }\n std::vector current_nodes = outputs;\n while (!current_nodes.empty()) {\n std::vector next_nodes;\n for (const string& node_name : current_nodes) {\n used_nodes[node_name] = true;\n if (node_map.count(node_name) == 0) {\n LOG(ERROR) << \"Bad graph structure, no node named '\" << node_name\n << \"' found for input lookup\";\n return errors::InvalidArgument(\"Bad graph structure, no node named '\",\n node_name, \"' found for input lookup\");\n }\n const NodeDef& node = *(node_map[node_name]);\n for (const string& input_name : node.input()) {\n const string& input_node_name = NodeNameFromInput(input_name);\n if (used_nodes.count(input_node_name) == 0) {\n next_nodes.push_back(input_node_name);\n }\n }\n }\n current_nodes = next_nodes;\n }\n FilterGraphDef(\n input_graph_def,\n [&](const NodeDef& node) { return used_nodes.count(node.name()) > 0; },\n output_graph_def);\n\n return Status::OK();\n}\n\nStatus FoldConstants(const GraphDef& input_graph_def,\n const std::vector& inputs,\n const std::vector& outputs,\n GraphDef* output_graph_def) {\n \/\/ Some older GraphDefs have saved _output_shapes attributes which are out of\n \/\/ date and cause import errors, so clean them up first.\n GraphDef cleaned_graph_def;\n RemoveAttributes(input_graph_def, {\"_output_shapes\"}, &cleaned_graph_def);\n Graph input_graph(OpRegistry::Global());\n ImportGraphDefOptions import_opts;\n TF_RETURN_IF_ERROR(\n ImportGraphDef(import_opts, cleaned_graph_def, &input_graph, nullptr));\n DeviceAttributes device_attributes;\n TF_RETURN_IF_ERROR(subgraph::RewriteGraphForExecution(\n &input_graph, inputs, outputs, {}, device_attributes));\n if (!DoConstantFolding(ConstantFoldingOptions(), nullptr, Env::Default(),\n nullptr, &input_graph)) {\n return errors::InvalidArgument(\"Constant folding failed\");\n }\n GraphDef folded_graph_def;\n input_graph.ToGraphDef(&folded_graph_def);\n GraphDef send_recvs_replaced;\n TF_RETURN_IF_ERROR(ReplaceSendRecvs(input_graph_def, folded_graph_def, inputs,\n outputs, &send_recvs_replaced));\n TF_RETURN_IF_ERROR(RemoveUnusedNodes(send_recvs_replaced, inputs, outputs,\n output_graph_def));\n return Status::OK();\n}\n\n} \/\/ namespace graph_transforms\n} \/\/ namespace tensorflow\n<|endoftext|>"} {"text":"\/\/ Copyright Benoit Blanchon 2014\n\/\/ MIT License\n\/\/\n\/\/ Arduino JSON library\n\/\/ https:\/\/github.com\/bblanchon\/ArduinoJson\n\n#include \n#include \n\nusing namespace ArduinoJson::Internals;\n\nclass QuotedString_ExtractFrom_Tests : public testing::Test {\n protected:\n void whenInputIs(const char *json) {\n strcpy(_jsonString, json);\n _result = QuotedString::extractFrom(_jsonString, &_trailing);\n }\n\n void resultMustBe(const char *expected) { EXPECT_STREQ(expected, _result); }\n\n void trailingMustBe(const char *expected) {\n EXPECT_STREQ(expected, _trailing);\n }\n\n private:\n char _jsonString[256];\n char *_result;\n char *_trailing;\n};\n\nTEST_F(QuotedString_ExtractFrom_Tests, EmptyDoubleQuotedString) {\n whenInputIs(\"\\\"\\\"\");\n\n resultMustBe(\"\");\n trailingMustBe(\"\");\n}\n\nTEST_F(QuotedString_ExtractFrom_Tests, NoQuotes) {\n whenInputIs(\"hello world\");\n\n resultMustBe(0);\n}\n\nTEST_F(QuotedString_ExtractFrom_Tests, EmptySingleQuotedString) {\n whenInputIs(\"''\");\n\n resultMustBe(\"\");\n trailingMustBe(\"\");\n}\n\nTEST_F(QuotedString_ExtractFrom_Tests, SimpleDoubleQuotedString) {\n whenInputIs(\"\\\"hello world\\\"\");\n\n resultMustBe(\"hello world\");\n trailingMustBe(\"\");\n}\n\nTEST_F(QuotedString_ExtractFrom_Tests, DoubleQuotedStringWithTrailing) {\n whenInputIs(\"\\\"hello\\\" world\");\n\n resultMustBe(\"hello\");\n trailingMustBe(\" world\");\n}\n\nTEST_F(QuotedString_ExtractFrom_Tests, SingleQuotedStringWithTrailing) {\n whenInputIs(\"'hello' world\");\n\n resultMustBe(\"hello\");\n trailingMustBe(\" world\");\n}\n\nTEST_F(QuotedString_ExtractFrom_Tests, CurlyBraces) {\n whenInputIs(\"\\\"{hello:world}\\\"\");\n resultMustBe(\"{hello:world}\");\n}\n\nTEST_F(QuotedString_ExtractFrom_Tests, SquareBraquets) {\n whenInputIs(\"\\\"[hello,world]\\\"\");\n resultMustBe(\"[hello,world]\");\n}\n\nTEST_F(QuotedString_ExtractFrom_Tests, EscapedDoubleQuote) {\n whenInputIs(\"\\\"hello \\\\\\\"world\\\\\\\"\\\"\");\n resultMustBe(\"hello \\\"world\\\"\");\n}\n\nTEST_F(QuotedString_ExtractFrom_Tests, EscapedSingleQuote) {\n whenInputIs(\"\\\"hello \\\\\\'world\\\\\\'\\\"\");\n resultMustBe(\"hello 'world'\");\n}\n\nTEST_F(QuotedString_ExtractFrom_Tests, EscapedSolidus) {\n whenInputIs(\"\\\"hello \\\\\/world\\\\\/\\\"\");\n resultMustBe(\"hello \/world\/\");\n}\n\nTEST_F(QuotedString_ExtractFrom_Tests, EscapedReverseSolidus) {\n whenInputIs(\"\\\"hello \\\\\\\\world\\\\\\\\\\\"\");\n resultMustBe(\"hello \\\\world\\\\\");\n}\n\nTEST_F(QuotedString_ExtractFrom_Tests, EscapedBackspace) {\n whenInputIs(\"\\\"hello \\\\bworld\\\\b\\\"\");\n resultMustBe(\"hello \\bworld\\b\");\n}\n\nTEST_F(QuotedString_ExtractFrom_Tests, EscapedFormfeed) {\n whenInputIs(\"\\\"hello \\\\fworld\\\\f\\\"\");\n resultMustBe(\"hello \\fworld\\f\");\n}\n\nTEST_F(QuotedString_ExtractFrom_Tests, EscapedNewline) {\n whenInputIs(\"\\\"hello \\\\nworld\\\\n\\\"\");\n resultMustBe(\"hello \\nworld\\n\");\n}\n\nTEST_F(QuotedString_ExtractFrom_Tests, EscapedCarriageReturn) {\n whenInputIs(\"\\\"hello \\\\rworld\\\\r\\\"\");\n resultMustBe(\"hello \\rworld\\r\");\n}\n\nTEST_F(QuotedString_ExtractFrom_Tests, EscapedTab) {\n whenInputIs(\"\\\"hello \\\\tworld\\\\t\\\"\");\n resultMustBe(\"hello \\tworld\\t\");\n}\n\nTEST_F(QuotedString_ExtractFrom_Tests, AllEscapedCharsTogether) {\n whenInputIs(\"\\\"1\\\\\\\"2\\\\\\\\3\\\\\/4\\\\b5\\\\f6\\\\n7\\\\r8\\\\t9\\\"\");\n resultMustBe(\"1\\\"2\\\\3\/4\\b5\\f6\\n7\\r8\\t9\");\n}\nTest with a missing closing quote\/\/ Copyright Benoit Blanchon 2014\n\/\/ MIT License\n\/\/\n\/\/ Arduino JSON library\n\/\/ https:\/\/github.com\/bblanchon\/ArduinoJson\n\n#include \n#include \n\nusing namespace ArduinoJson::Internals;\n\nclass QuotedString_ExtractFrom_Tests : public testing::Test {\n protected:\n void whenInputIs(const char *json) {\n strcpy(_jsonString, json);\n _result = QuotedString::extractFrom(_jsonString, &_trailing);\n }\n\n void resultMustBe(const char *expected) { EXPECT_STREQ(expected, _result); }\n\n void trailingMustBe(const char *expected) {\n EXPECT_STREQ(expected, _trailing);\n }\n\n private:\n char _jsonString[256];\n char *_result;\n char *_trailing;\n};\n\nTEST_F(QuotedString_ExtractFrom_Tests, EmptyDoubleQuotedString) {\n whenInputIs(\"\\\"\\\"\");\n\n resultMustBe(\"\");\n trailingMustBe(\"\");\n}\n\nTEST_F(QuotedString_ExtractFrom_Tests, NoQuotes) {\n whenInputIs(\"hello world\");\n\n resultMustBe(0);\n}\n\nTEST_F(QuotedString_ExtractFrom_Tests, MissingClosingQuote) {\n whenInputIs(\"\\\"hello world\");\n\n resultMustBe(0);\n}\n\nTEST_F(QuotedString_ExtractFrom_Tests, EmptySingleQuotedString) {\n whenInputIs(\"''\");\n\n resultMustBe(\"\");\n trailingMustBe(\"\");\n}\n\nTEST_F(QuotedString_ExtractFrom_Tests, SimpleDoubleQuotedString) {\n whenInputIs(\"\\\"hello world\\\"\");\n\n resultMustBe(\"hello world\");\n trailingMustBe(\"\");\n}\n\nTEST_F(QuotedString_ExtractFrom_Tests, DoubleQuotedStringWithTrailing) {\n whenInputIs(\"\\\"hello\\\" world\");\n\n resultMustBe(\"hello\");\n trailingMustBe(\" world\");\n}\n\nTEST_F(QuotedString_ExtractFrom_Tests, SingleQuotedStringWithTrailing) {\n whenInputIs(\"'hello' world\");\n\n resultMustBe(\"hello\");\n trailingMustBe(\" world\");\n}\n\nTEST_F(QuotedString_ExtractFrom_Tests, CurlyBraces) {\n whenInputIs(\"\\\"{hello:world}\\\"\");\n resultMustBe(\"{hello:world}\");\n}\n\nTEST_F(QuotedString_ExtractFrom_Tests, SquareBraquets) {\n whenInputIs(\"\\\"[hello,world]\\\"\");\n resultMustBe(\"[hello,world]\");\n}\n\nTEST_F(QuotedString_ExtractFrom_Tests, EscapedDoubleQuote) {\n whenInputIs(\"\\\"hello \\\\\\\"world\\\\\\\"\\\"\");\n resultMustBe(\"hello \\\"world\\\"\");\n}\n\nTEST_F(QuotedString_ExtractFrom_Tests, EscapedSingleQuote) {\n whenInputIs(\"\\\"hello \\\\\\'world\\\\\\'\\\"\");\n resultMustBe(\"hello 'world'\");\n}\n\nTEST_F(QuotedString_ExtractFrom_Tests, EscapedSolidus) {\n whenInputIs(\"\\\"hello \\\\\/world\\\\\/\\\"\");\n resultMustBe(\"hello \/world\/\");\n}\n\nTEST_F(QuotedString_ExtractFrom_Tests, EscapedReverseSolidus) {\n whenInputIs(\"\\\"hello \\\\\\\\world\\\\\\\\\\\"\");\n resultMustBe(\"hello \\\\world\\\\\");\n}\n\nTEST_F(QuotedString_ExtractFrom_Tests, EscapedBackspace) {\n whenInputIs(\"\\\"hello \\\\bworld\\\\b\\\"\");\n resultMustBe(\"hello \\bworld\\b\");\n}\n\nTEST_F(QuotedString_ExtractFrom_Tests, EscapedFormfeed) {\n whenInputIs(\"\\\"hello \\\\fworld\\\\f\\\"\");\n resultMustBe(\"hello \\fworld\\f\");\n}\n\nTEST_F(QuotedString_ExtractFrom_Tests, EscapedNewline) {\n whenInputIs(\"\\\"hello \\\\nworld\\\\n\\\"\");\n resultMustBe(\"hello \\nworld\\n\");\n}\n\nTEST_F(QuotedString_ExtractFrom_Tests, EscapedCarriageReturn) {\n whenInputIs(\"\\\"hello \\\\rworld\\\\r\\\"\");\n resultMustBe(\"hello \\rworld\\r\");\n}\n\nTEST_F(QuotedString_ExtractFrom_Tests, EscapedTab) {\n whenInputIs(\"\\\"hello \\\\tworld\\\\t\\\"\");\n resultMustBe(\"hello \\tworld\\t\");\n}\n\nTEST_F(QuotedString_ExtractFrom_Tests, AllEscapedCharsTogether) {\n whenInputIs(\"\\\"1\\\\\\\"2\\\\\\\\3\\\\\/4\\\\b5\\\\f6\\\\n7\\\\r8\\\\t9\\\"\");\n resultMustBe(\"1\\\"2\\\\3\/4\\b5\\f6\\n7\\r8\\t9\");\n}\n<|endoftext|>"} {"text":"#include \"webpage.h\"\n\nWebPage::WebPage(QObject *parent) :\n QWebPage(parent)\n{\n connect(this, SIGNAL(windowCloseRequested()), this, SLOT(on_windowCloseRequested()));\n connect(this, SIGNAL(linkClicked(QUrl)), this, SLOT(on_linkClicked(QUrl)));\n connect(this->mainFrame(), SIGNAL(javaScriptWindowObjectCleared()), this, SLOT(on_javaScriptWindowObjectCleared()));\n this->setLinkDelegationPolicy(QWebPage::DelegateAllLinks);\n this->setNetworkAccessManager(qApp->networkAccessManager);\n this->settings()->setAttribute(QWebSettings::LocalStorageEnabled, true);\n this->settings()->setAttribute(QWebSettings::JavaEnabled, false);\n this->settings()->setAttribute(QWebSettings::PluginsEnabled, true);\n this->settings()->setAttribute(QWebSettings::DeveloperExtrasEnabled, true);\n}\n\nvoid WebPage::on_windowCloseRequested()\n{\n ((QWidget*)this->parent())->close();\n}\n\nvoid WebPage::on_linkClicked(QUrl url)\n{\n QDesktopServices::openUrl(url);\n}\n\nvoid WebPage::on_javaScriptWindowObjectCleared()\n{\n this->mainFrame()->addToJavaScriptWindowObject(\"bridge\", qApp->bridge);\n}\nТеперь мы умеем хранить localStorage.#include \"webpage.h\"\n\nWebPage::WebPage(QObject *parent) :\n QWebPage(parent)\n{\n QString cachePath = QDesktopServices::storageLocation(QDesktopServices::CacheLocation);\n connect(this, SIGNAL(windowCloseRequested()), this, SLOT(on_windowCloseRequested()));\n connect(this, SIGNAL(linkClicked(QUrl)), this, SLOT(on_linkClicked(QUrl)));\n connect(this->mainFrame(), SIGNAL(javaScriptWindowObjectCleared()), this, SLOT(on_javaScriptWindowObjectCleared()));\n this->setLinkDelegationPolicy(QWebPage::DelegateAllLinks);\n this->setNetworkAccessManager(qApp->networkAccessManager);\n this->settings()->setAttribute(QWebSettings::LocalStorageEnabled, true);\n this->settings()->setAttribute(QWebSettings::JavaEnabled, false);\n this->settings()->setAttribute(QWebSettings::PluginsEnabled, true);\n this->settings()->setAttribute(QWebSettings::DeveloperExtrasEnabled, true);\n this->settings()->setLocalStoragePath(cachePath);\n}\n\nvoid WebPage::on_windowCloseRequested()\n{\n ((QWidget*)this->parent())->close();\n}\n\nvoid WebPage::on_linkClicked(QUrl url)\n{\n QDesktopServices::openUrl(url);\n}\n\nvoid WebPage::on_javaScriptWindowObjectCleared()\n{\n this->mainFrame()->addToJavaScriptWindowObject(\"bridge\", qApp->bridge);\n}\n<|endoftext|>"} {"text":"#include \"tags.h\"\n\n#include <0mq\/context.h>\n#include <0mq\/socket.h>\n#include <0mq\/message.h>\n#include <0mq\/poller.h>\n\n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\ntypedef std::function jobfunction_type;\ntypedef std::chrono::time_point timepoint_type;\n\nclass Job {\n public:\n Job(const jobfunction_type& jobFunction, zmq::Context& context)\n : context_(context), jobFunction_(jobFunction), doWork_(true)\n {\n }\n\n ~Job() {\n doWork_ = false;\n\n thread_->join();\n }\n\n void init(const std::string& bindStr) {\n using namespace std::placeholders;\n \/\/ create a thread that waits on the job socket for work\n thread_ = std::unique_ptr(new\n std::thread(std::bind(&Job::go, this, bindStr)));\n }\n\n private:\n void go(const std::string& bindStr) {\n zmq::Socket jobSocket = context_.createSocket(ZMQ_PAIR);\n jobSocket.connect(bindStr.c_str());\n\n while (doWork_) {\n zmq::Socket::messages_type request = jobSocket.receive();\n\n if (request.size() != 1) {\n throw std::runtime_error(\"Job::go: empty data\");\n }\n\n zmq::Message replyMessage = jobFunction_(request.front());\n\n zmq::Socket::messages_type reply {replyMessage};\n jobSocket.send(reply);\n }\n }\n\n \/\/ do not copy\n Job(const Job&);\n\n zmq::Context context_;\n const jobfunction_type jobFunction_;\n bool doWork_;\n std::unique_ptr thread_;\n};\n\nclass WorkerApplication {\n public:\n WorkerApplication(const jobfunction_type& jobFunction)\n : context_(), workerSocket_(), jobSocket_(), job_(jobFunction, context_),\n isBusy_(false), client_(), jobID_()\n {\n }\n\n ~WorkerApplication() {\n }\n\n void init() {\n boost::uuids::uuid uuid;\n\n std::ostringstream bindStr;\n bindStr << \"inproc:\/\/job_\" << uuid;\n\n jobSocket_ = context_.createSocket(ZMQ_PAIR);\n jobSocket_.bind(bindStr.str().c_str());\n job_.init(bindStr.str());\n\n connect();\n }\n\n void go() {\n timepoint_type nextQueueBeat;\n nextQueueBeat = std::chrono::steady_clock::now() +\n std::chrono::milliseconds(queuebeatInterval_);\n std::size_t interval = intervalInit_;\n\n timepoint_type nextHeartBeat;\n nextHeartBeat = std::chrono::steady_clock::now() +\n std::chrono::milliseconds(heartbeatInterval_);\n\n while (true) {\n std::vector items = { workerSocket_ };\n if (isBusy_) {\n items.push_back(jobSocket_);\n }\n\n std::vector state = zmq::poll(items, heartbeatInterval_);\n\n assert(!isBusy_ || state.size() > 1);\n\n if (state[0] & ZMQ_POLLIN) {\n handleQueue();\n\n nextQueueBeat = std::chrono::steady_clock::now() +\n std::chrono::milliseconds(queuebeatInterval_);\n }\n\n if (isBusy_ && state.size() > 1 && state[1] & ZMQ_POLLIN) {\n handleJobDone();\n\n \/\/ make sure we let the queue know that we are available again\n nextHeartBeat = std::chrono::steady_clock::now() - 2 *\n std::chrono::milliseconds(heartbeatInterval_);\n }\n\n timepoint_type now =\n std::chrono::steady_clock::now();\n\n if (now > nextQueueBeat) {\n std::cout << \"W: heartbeat failure, can't reach queue\" << std::endl;\n std::cout << \"W: reconnecting in \" << interval << \" msec...\" <<\n std::endl;\n\n std::this_thread::sleep_for(std::chrono::milliseconds(interval));\n\n if (interval < intervalMax_)\n interval *= 2;\n\n connect();\n\n nextQueueBeat = std::chrono::steady_clock::now() +\n std::chrono::milliseconds(queuebeatInterval_);\n }\n\n \/\/ Send heartbeat to queue if it's time\n if (now > nextHeartBeat) {\n sendHeartBeat();\n\n nextHeartBeat = now + std::chrono::milliseconds(heartbeatInterval_);\n }\n }\n }\n\n private:\n void handleQueue() {\n zmq::Socket::messages_type messages = workerSocket_.receive();\n\n const std::size_t messageSize = messages.size();\n\n \/\/ check if we got a valid message\n if (messageSize == 0) {\n throw std::runtime_error(\"WorkerApplication::go: got interrupted\");\n }\n\n zmq::Socket::messages_type::iterator messagePtr =\n messages.begin();\n const zmq::Message& tag = *messagePtr++;\n\n if (tag.size() != 1) {\n throw std::runtime_error(\"WorkerApplication::go: invalid tag size\");\n }\n\n switch (tag.data()[0]) {\n case QUEUE_HEARTBEAT_TAG:\n \/\/ do nothing\n if (messageSize != 1) {\n throw std::runtime_error(\"WorkerApplication::go: invalid heartbeak\");\n }\n break;\n case QUEUE_JOB_TAG:\n \/\/ got a job\n if (messageSize != 4) {\n throw std::runtime_error(\"WorkerApplication::go: invalid job request\");\n }\n\n if (!isBusy_)\n handleNewJob(messagePtr);\n else\n std::cout << \"W: I am busy but I got a job. I'll ignore it\" << std::endl;\n\n break;\n }\n }\n\n void sendHeartBeat() {\n zmq::Message queueReplyTag(1);\n zmq::Socket::messages_type heartbeat;\n std::cout << \"beat: \" << isBusy_ << std::endl;\n if (!isBusy_) {\n queueReplyTag.data()[0] = WORKER_HEARTBEAT_TAG;\n heartbeat.push_back(std::move(queueReplyTag));\n workerSocket_.send(heartbeat);\n } else {\n queueReplyTag.data()[0] = WORKER_UPDATE_TAG;\n heartbeat.push_back(std::move(queueReplyTag));\n\n heartbeat.push_back(client_);\n\n zmq::Message jobReplyTag(1);\n jobReplyTag.data()[0] = JOB_BUSY;\n heartbeat.push_back(std::move(jobReplyTag));\n heartbeat.push_back(jobID_);\n workerSocket_.send(heartbeat);\n }\n }\n\n void handleNewJob(zmq::Socket::messages_type::const_iterator messagePtr) {\n \/\/ push the address of the client\n std::cout << \"got job\" << std::endl;\n\n client_ = *messagePtr++;\n jobID_ = *messagePtr++;\n isBusy_ = true;\n\n zmq::Socket::messages_type jobRequest;\n jobRequest.push_back(*messagePtr);\n jobSocket_.send(jobRequest);\n }\n\n void handleJobDone() {\n std::cout << \"done\" << std::endl;\n zmq::Socket::messages_type jobReply = jobSocket_.receive();\n\n zmq::Socket::messages_type reply;\n zmq::Message queueReplyTag(1);\n zmq::Message jobReplyTag(1);\n\n queueReplyTag.data()[0] = WORKER_UPDATE_TAG;\n reply.push_back(std::move(queueReplyTag));\n\n \/\/ push the address of the client\n reply.push_back(std::move(client_));\n\n jobReplyTag.data()[0] = JOB_DONE;\n reply.push_back(std::move(jobReplyTag));\n reply.push_back(std::move(jobID_));\n\n reply.splice(reply.end(), jobReply);\n\n workerSocket_.send(reply);\n\n isBusy_ = false;\n\n }\n\n \/\/ do not copy\n WorkerApplication(const WorkerApplication&);\n\n void connect() {\n workerSocket_ = context_.createSocket(ZMQ_DEALER);\n workerSocket_.connect(\"tcp:\/\/localhost:5556\");\n\n \/\/ Tell queue we're ready for work\n zmq::Message message(1);\n message.data()[0] = WORKER_HEARTBEAT_TAG;\n zmq::Socket::messages_type messages = {message};\n workerSocket_.send(messages);\n }\n\n const std::size_t heartbeatInterval_ = 1000;\n const std::size_t queuebeatInterval_ = 3000;\n const std::size_t intervalInit_ = 1000;\n const std::size_t intervalMax_ = 32000;\n\n zmq::Context context_;\n zmq::Socket workerSocket_, jobSocket_;\n Job job_;\n\n bool isBusy_;\n zmq::Message client_;\n zmq::Message jobID_;\n};\n\nzmq::Message job(const zmq::Message& data) {\n std::this_thread::sleep_for(std::chrono::seconds(10));\n return data;\n}\n\nint main(int \/*argc*\/, const char** \/*argv*\/) {\n WorkerApplication worker(job);\n worker.init();\n\n worker.go();\n\n return 0;\n}\nFixes immediate update.#include \"tags.h\"\n\n#include <0mq\/context.h>\n#include <0mq\/socket.h>\n#include <0mq\/message.h>\n#include <0mq\/poller.h>\n\n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\ntypedef std::function jobfunction_type;\ntypedef std::chrono::time_point timepoint_type;\n\nclass Job {\n public:\n Job(const jobfunction_type& jobFunction, zmq::Context& context)\n : context_(context), jobFunction_(jobFunction), doWork_(true)\n {\n }\n\n ~Job() {\n doWork_ = false;\n\n thread_->join();\n }\n\n void init(const std::string& bindStr) {\n using namespace std::placeholders;\n \/\/ create a thread that waits on the job socket for work\n thread_ = std::unique_ptr(new\n std::thread(std::bind(&Job::go, this, bindStr)));\n }\n\n private:\n void go(const std::string& bindStr) {\n zmq::Socket jobSocket = context_.createSocket(ZMQ_PAIR);\n jobSocket.connect(bindStr.c_str());\n\n while (doWork_) {\n zmq::Socket::messages_type request = jobSocket.receive();\n\n if (request.size() != 1) {\n throw std::runtime_error(\"Job::go: empty data\");\n }\n\n zmq::Message replyMessage = jobFunction_(request.front());\n\n zmq::Socket::messages_type reply {replyMessage};\n jobSocket.send(reply);\n }\n }\n\n \/\/ do not copy\n Job(const Job&);\n\n zmq::Context context_;\n const jobfunction_type jobFunction_;\n bool doWork_;\n std::unique_ptr thread_;\n};\n\nclass WorkerApplication {\n public:\n WorkerApplication(const jobfunction_type& jobFunction)\n : context_(), workerSocket_(), jobSocket_(), job_(jobFunction, context_),\n isBusy_(false), client_(), jobID_()\n {\n }\n\n ~WorkerApplication() {\n }\n\n void init() {\n boost::uuids::uuid uuid;\n\n std::ostringstream bindStr;\n bindStr << \"inproc:\/\/job_\" << uuid;\n\n jobSocket_ = context_.createSocket(ZMQ_PAIR);\n jobSocket_.bind(bindStr.str().c_str());\n job_.init(bindStr.str());\n\n connect();\n }\n\n void go() {\n timepoint_type nextQueueBeat;\n nextQueueBeat = std::chrono::steady_clock::now() +\n std::chrono::milliseconds(queuebeatInterval_);\n std::size_t interval = intervalInit_;\n\n timepoint_type nextHeartBeat;\n nextHeartBeat = std::chrono::steady_clock::now() +\n std::chrono::milliseconds(heartbeatInterval_);\n\n while (true) {\n bool immediateUpdate = false;\n\n std::vector items = { workerSocket_ };\n if (isBusy_) {\n items.push_back(jobSocket_);\n }\n\n std::vector state = zmq::poll(items, heartbeatInterval_);\n\n assert(!isBusy_ || state.size() > 1);\n\n if (state[0] & ZMQ_POLLIN) {\n immediateUpdate = immediateUpdate || handleQueue();\n\n nextQueueBeat = std::chrono::steady_clock::now() +\n std::chrono::milliseconds(queuebeatInterval_);\n }\n\n if (isBusy_ && state.size() > 1 && state[1] & ZMQ_POLLIN) {\n handleJobDone();\n\n \/\/ make sure we let the queue know that we are available again\n immediateUpdate = true;\n }\n\n timepoint_type now =\n std::chrono::steady_clock::now();\n\n if (now > nextQueueBeat) {\n std::cout << \"W: heartbeat failure, can't reach queue\" << std::endl;\n std::cout << \"W: reconnecting in \" << interval << \" msec...\" <<\n std::endl;\n\n std::this_thread::sleep_for(std::chrono::milliseconds(interval));\n\n if (interval < intervalMax_)\n interval *= 2;\n\n connect();\n\n nextQueueBeat = std::chrono::steady_clock::now() +\n std::chrono::milliseconds(queuebeatInterval_);\n }\n\n \/\/ Send heartbeat to queue if it's time\n if (immediateUpdate || now > nextHeartBeat) {\n sendHeartBeat();\n\n nextHeartBeat = now + std::chrono::milliseconds(heartbeatInterval_);\n }\n }\n }\n\n private:\n bool handleQueue() {\n bool immediateUpdate = false;\n\n zmq::Socket::messages_type messages = workerSocket_.receive();\n\n const std::size_t messageSize = messages.size();\n\n \/\/ check if we got a valid message\n if (messageSize == 0) {\n throw std::runtime_error(\"WorkerApplication::go: got interrupted\");\n }\n\n zmq::Socket::messages_type::iterator messagePtr =\n messages.begin();\n const zmq::Message& tag = *messagePtr++;\n\n if (tag.size() != 1) {\n throw std::runtime_error(\"WorkerApplication::go: invalid tag size\");\n }\n\n switch (tag.data()[0]) {\n case QUEUE_HEARTBEAT_TAG:\n \/\/ do nothing\n if (messageSize != 1) {\n throw std::runtime_error(\"WorkerApplication::go: invalid heartbeak\");\n }\n break;\n case QUEUE_JOB_TAG:\n \/\/ got a job\n if (messageSize != 4) {\n throw std::runtime_error(\"WorkerApplication::go: invalid job request\");\n }\n\n if (!isBusy_) {\n handleNewJob(messagePtr);\n immediateUpdate = true;\n } else {\n std::cout << \"W: I am busy but I got a job. I'll ignore it\" << std::endl;\n }\n\n break;\n }\n\n return immediateUpdate;\n }\n\n void sendHeartBeat() {\n zmq::Message queueReplyTag(1);\n zmq::Socket::messages_type heartbeat;\n std::cout << \"beat: \" << isBusy_ << std::endl;\n if (!isBusy_) {\n queueReplyTag.data()[0] = WORKER_HEARTBEAT_TAG;\n heartbeat.push_back(std::move(queueReplyTag));\n workerSocket_.send(heartbeat);\n } else {\n queueReplyTag.data()[0] = WORKER_UPDATE_TAG;\n heartbeat.push_back(std::move(queueReplyTag));\n\n heartbeat.push_back(client_);\n\n zmq::Message jobReplyTag(1);\n jobReplyTag.data()[0] = JOB_BUSY;\n heartbeat.push_back(std::move(jobReplyTag));\n heartbeat.push_back(jobID_);\n workerSocket_.send(heartbeat);\n }\n }\n\n void handleNewJob(zmq::Socket::messages_type::const_iterator messagePtr) {\n \/\/ push the address of the client\n std::cout << \"got job\" << std::endl;\n\n client_ = *messagePtr++;\n jobID_ = *messagePtr++;\n isBusy_ = true;\n\n zmq::Socket::messages_type jobRequest;\n jobRequest.push_back(*messagePtr);\n jobSocket_.send(jobRequest);\n }\n\n void handleJobDone() {\n std::cout << \"done\" << std::endl;\n zmq::Socket::messages_type jobReply = jobSocket_.receive();\n\n zmq::Socket::messages_type reply;\n zmq::Message queueReplyTag(1);\n zmq::Message jobReplyTag(1);\n\n queueReplyTag.data()[0] = WORKER_UPDATE_TAG;\n reply.push_back(std::move(queueReplyTag));\n\n \/\/ push the address of the client\n reply.push_back(std::move(client_));\n\n jobReplyTag.data()[0] = JOB_DONE;\n reply.push_back(std::move(jobReplyTag));\n reply.push_back(std::move(jobID_));\n\n reply.splice(reply.end(), jobReply);\n\n workerSocket_.send(reply);\n\n isBusy_ = false;\n }\n\n \/\/ do not copy\n WorkerApplication(const WorkerApplication&);\n\n void connect() {\n workerSocket_ = context_.createSocket(ZMQ_DEALER);\n workerSocket_.connect(\"tcp:\/\/localhost:5556\");\n\n \/\/ Tell queue we're ready for work\n zmq::Message message(1);\n message.data()[0] = WORKER_HEARTBEAT_TAG;\n zmq::Socket::messages_type messages = {message};\n workerSocket_.send(messages);\n }\n\n const std::size_t heartbeatInterval_ = 1000;\n const std::size_t queuebeatInterval_ = 3000;\n const std::size_t intervalInit_ = 1000;\n const std::size_t intervalMax_ = 32000;\n\n zmq::Context context_;\n zmq::Socket workerSocket_, jobSocket_;\n Job job_;\n\n bool isBusy_;\n zmq::Message client_;\n zmq::Message jobID_;\n};\n\nzmq::Message job(const zmq::Message& data) {\n std::this_thread::sleep_for(std::chrono::seconds(10));\n return data;\n}\n\nint main(int \/*argc*\/, const char** \/*argv*\/) {\n WorkerApplication worker(job);\n worker.init();\n\n worker.go();\n\n return 0;\n}\n<|endoftext|>"} {"text":"#include \"clay.hpp\"\n#include \n\nusing namespace std;\n\n\n\f\n\/\/\n\/\/ overload <<\n\/\/\n\nstatic void print(const Object *x, ostream &out);\n\nostream &operator<<(ostream &out, const Object &obj) {\n print(&obj, out);\n return out;\n}\n\nostream &operator<<(ostream &out, const Object *obj) {\n print(obj, out);\n return out;\n}\n\n\n\f\n\/\/\n\/\/ big vec\n\/\/\n\ntemplate \nstruct BigVec {\n const vector *v;\n BigVec(const vector &v)\n : v(&v) {}\n};\n\ntemplate \nBigVec bigVec(const vector &v) {\n return BigVec(v);\n}\n\nstatic int indent = 0;\n\ntemplate \nostream &operator<<(ostream &out, const BigVec &v) {\n ++indent;\n out << \"[\";\n typename vector::const_iterator i, end;\n bool first = true;\n for (i = v.v->begin(), end = v.v->end(); i != end; ++i) {\n if (!first)\n out << \",\";\n first = false;\n out << \"\\n\";\n for (int j = 0; j < indent; ++j)\n out << \" \";\n out << *i;\n }\n out << \"]\";\n --indent;\n return out;\n}\n\n\n\f\n\/\/\n\/\/ print\n\/\/\n\nstatic void print(const Object *x, ostream &out) {\n if (x == NULL) {\n out << \"NULL\";\n return;\n }\n\n switch (x->objKind) {\n\n case SOURCE : {\n Source *y = (Source *)x;\n out << \"Source(\" << y->fileName << \")\";\n break;\n }\n case LOCATION : {\n Location *y = (Location *)x;\n out << \"Location(\" << y->source << \", \" << y->offset << \")\";\n break;\n }\n case TOKEN : {\n Token *y = (Token *)x;\n out << \"Token(\";\n switch (y->tokenKind) {\n case T_SYMBOL :\n out << \"T_SYMBOL\";\n break;\n case T_KEYWORD :\n out << \"T_KEYWORD\";\n break;\n case T_IDENTIFIER :\n out << \"T_IDENTIFIER\";\n break;\n case T_STRING_LITERAL :\n out << \"T_STRING_LITERAL\";\n break;\n case T_CHAR_LITERAL :\n out << \"T_CHAR_LITERAL\";\n break;\n case T_INT_LITERAL :\n out << \"T_INT_LITERAL\";\n break;\n case T_FLOAT_LITERAL :\n out << \"T_FLOAT_LITERAL\";\n break;\n case T_LITERAL_SUFFIX :\n out << \"T_LITERAL_SUFFIX\";\n break;\n case T_SPACE :\n out << \"T_SPACE\";\n break;\n case T_LINE_COMMENT :\n out << \"T_LINE_COMMENT\";\n break;\n case T_BLOCK_COMMENT :\n out << \"T_BLOCK_COMMENT\";\n break;\n default :\n assert(false);\n }\n out << \", \" << y->str << \")\";\n break;\n }\n\n case IDENTIFIER : {\n Identifier *y = (Identifier *)x;\n out << \"Identifier(\" << y->str << \")\";\n break;\n }\n case DOTTED_NAME : {\n DottedName *y = (DottedName *)x;\n out << \"DottedName(\" << y->parts << \")\";\n break;\n }\n\n case BOOL_LITERAL : {\n BoolLiteral *y = (BoolLiteral *)x;\n out << \"BoolLiteral(\" << y->value << \")\";\n break;\n }\n case INT_LITERAL : {\n IntLiteral *y = (IntLiteral *)x;\n out << \"IntLiteral(\" << y->value;\n if (!y->suffix.empty())\n out << \", \" << y->suffix;\n out << \")\";\n break;\n }\n case FLOAT_LITERAL : {\n FloatLiteral *y = (FloatLiteral *)x;\n out << \"FloatLiteral(\" << y->value;\n if (!y->suffix.empty())\n out << \", \" << y->suffix;\n out << \")\";\n break;\n }\n case CHAR_LITERAL : {\n CharLiteral *y = (CharLiteral *)x;\n out << \"CharLiteral(\" << y->value << \")\";\n break;\n }\n case STRING_LITERAL : {\n StringLiteral *y = (StringLiteral *)x;\n out << \"StringLiteral(\" << y->value << \")\";\n break;\n }\n\n case NAME_REF : {\n NameRef *y = (NameRef *)x;\n out << \"NameRef(\" << y->name << \")\";\n break;\n }\n case TUPLE : {\n Tuple *y = (Tuple *)x;\n out << \"Tuple(\" << y->args << \")\";\n break;\n }\n case ARRAY : {\n Array *y = (Array *)x;\n out << \"Array(\" << y->args << \")\";\n break;\n }\n case INDEXING : {\n Indexing *y = (Indexing *)x;\n out << \"Indexing(\" << y->expr << \", \" << y->args << \")\";\n break;\n }\n case CALL : {\n Call *y = (Call *)x;\n out << \"Call(\" << y->expr << \", \" << y->args << \")\";\n break;\n }\n case FIELD_REF : {\n FieldRef *y = (FieldRef *)x;\n out << \"FieldRef(\" << y->expr << \", \" << y->name << \")\";\n break;\n }\n case TUPLE_REF : {\n TupleRef *y = (TupleRef *)x;\n out << \"TupleRef(\" << y->expr << \", \" << y->index << \")\";\n break;\n }\n case UNARY_OP : {\n UnaryOp *y = (UnaryOp *)x;\n out << \"UnaryOp(\";\n switch (y->op) {\n case DEREFERENCE :\n out << \"DEREFERENCE\";\n break;\n case ADDRESS_OF :\n out << \"ADDRESS_OF\";\n break;\n case PLUS :\n out << \"PLUS\";\n break;\n case MINUS :\n out << \"MINUS\";\n break;\n case NOT :\n out << \"NOT\";\n break;\n default :\n assert(false);\n }\n out << \", \" << y->expr << \")\";\n break;\n }\n case BINARY_OP : {\n BinaryOp *y = (BinaryOp *)x;\n out << \"BinaryOp(\";\n switch (y->op) {\n case ADD :\n out << \"ADD\";\n break;\n case SUBTRACT :\n out << \"SUBTRACT\";\n break;\n case MULTIPLY :\n out << \"MULTIPLY\";\n break;\n case DIVIDE :\n out << \"DIVIDE\";\n break;\n case REMAINDER :\n out << \"REMAINDER\";\n break;\n case EQUALS :\n out << \"EQUALS\";\n break;\n case NOT_EQUALS :\n out << \"NOT_EQUALS\";\n break;\n case LESSER :\n out << \"LESSER\";\n break;\n case LESSER_EQUALS :\n out << \"LESSER_EQUALS\";\n break;\n case GREATER :\n out << \"GREATER\";\n break;\n case GREATER_EQUALS :\n out << \"GREATER_EQUALS\";\n break;\n default :\n assert(false);\n }\n out << \", \" << y->expr1 << \", \" << y->expr2 << \")\";\n break;\n }\n case AND : {\n And *y = (And *)x;\n out << \"And(\" << y->expr1 << \", \" << y->expr2 << \")\";\n break;\n }\n case OR : {\n Or *y = (Or *)x;\n out << \"Or(\" << y->expr1 << \", \" << y->expr2 << \")\";\n break;\n break;\n }\n\n case BLOCK : {\n Block *y = (Block *)x;\n out << \"Block(\" << bigVec(y->statements) << \")\";\n break;\n }\n case LABEL : {\n Label *y = (Label *)x;\n out << \"Label(\" << y->name << \")\";\n break;\n }\n case BINDING : {\n Binding *y = (Binding *)x;\n out << \"Binding(\";\n switch (y->bindingKind) {\n case VAR :\n out << \"VAR\";\n break;\n case REF :\n out << \"REF\";\n break;\n case STATIC :\n out << \"STATIC\";\n break;\n default :\n assert(false);\n }\n out << \", \" << y->name << \", \" << y->expr << \")\";\n break;\n }\n case ASSIGNMENT : {\n Assignment *y = (Assignment *)x;\n out << \"Assignment(\" << y->left << \", \" << y->right << \")\";\n break;\n }\n case GOTO : {\n Goto *y = (Goto *)x;\n out << \"Goto(\" << y->labelName << \")\";\n break;\n }\n case RETURN : {\n Return *y = (Return *)x;\n out << \"Return(\" << y->expr << \")\";\n break;\n }\n case RETURN_REF : {\n ReturnRef *y = (ReturnRef *)x;\n out << \"ReturnRef(\" << y->expr << \")\";\n break;\n }\n case IF : {\n If *y = (If *)x;\n out << \"If(\" << y->condition << \", \" << y->thenPart;\n out << \", \" << y->elsePart << \")\";\n break;\n }\n case EXPR_STATEMENT : {\n ExprStatement *y = (ExprStatement *)x;\n out << \"ExprStatement(\" << y->expr << \")\";\n break;\n }\n case WHILE : {\n While *y = (While *)x;\n out << \"While(\" << y->condition << \", \" << y->body << \")\";\n break;\n }\n case BREAK : {\n out << \"Break()\";\n break;\n }\n case CONTINUE : {\n out << \"Continue()\";\n break;\n }\n case FOR : {\n For *y = (For *)x;\n out << \"For(\" << y->variable << \", \" << y->expr;\n out << \", \" << y->body << \")\";\n break;\n }\n\n case CODE : {\n Code *y = (Code *)x;\n out << \"Code(\" << y->patternVars << \", \" << y->predicate;\n out << \", \" << y->formalArgs << \", \" << y->body << \")\";\n break;\n }\n case VALUE_ARG : {\n ValueArg *y = (ValueArg *)x;\n out << \"ValueArg(\" << y->name << \", \" << y->type << \")\";\n break;\n }\n case STATIC_ARG : {\n StaticArg *y = (StaticArg *)x;\n out << \"StaticArg(\" << y->pattern << \")\";\n break;\n }\n\n case RECORD : {\n Record *y = (Record *)x;\n out << \"Record(\" << y->name << \", \" << y->patternVars;\n out << \", \" << y->formalArgs << \")\";\n break;\n }\n case PROCEDURE : {\n Procedure *y = (Procedure *)x;\n out << \"Procedure(\" << y->name << \", \" << y->code << \")\";\n break;\n }\n case OVERLOAD : {\n Overload *y = (Overload *)x;\n out << \"Overload(\" << y->name << \", \" << y->code << \")\";\n break;\n }\n case OVERLOADABLE : {\n Overloadable *y = (Overloadable *)x;\n out << \"Overloadable(\" << y->name << \")\";\n break;\n }\n case EXTERNAL_PROCEDURE : {\n ExternalProcedure *y = (ExternalProcedure *)x;\n out << \"ExternalProcedure(\" << y->name << \", \" << y->args;\n out << \", \" << y->returnType << \")\";\n break;\n }\n\n case IMPORT : {\n Import *y = (Import *)x;\n out << \"Import(\" << y->dottedName << \")\";\n break;\n }\n case EXPORT : {\n Export *y = (Export *)x;\n out << \"Export(\" << y->dottedName << \")\";\n break;\n }\n case MODULE : {\n Module *y = (Module *)x;\n out << \"Module(\" << bigVec(y->imports) << \", \" << bigVec(y->exports);\n out << \", \" << bigVec(y->topLevelItems) << \")\";\n break;\n }\n\n case TYPE : {\n Type *y = (Type *)x;\n typePrint(y, out);\n break;\n }\n\n case VALUE : {\n Value *y = (Value *)x;\n valuePrint(y, out);\n break;\n }\n\n default :\n assert(false);\n }\n}\nadded support for printing 'SCExpr' and 'ValueExpr'.#include \"clay.hpp\"\n#include \n\nusing namespace std;\n\n\n\f\n\/\/\n\/\/ overload <<\n\/\/\n\nstatic void print(const Object *x, ostream &out);\n\nostream &operator<<(ostream &out, const Object &obj) {\n print(&obj, out);\n return out;\n}\n\nostream &operator<<(ostream &out, const Object *obj) {\n print(obj, out);\n return out;\n}\n\n\n\f\n\/\/\n\/\/ big vec\n\/\/\n\ntemplate \nstruct BigVec {\n const vector *v;\n BigVec(const vector &v)\n : v(&v) {}\n};\n\ntemplate \nBigVec bigVec(const vector &v) {\n return BigVec(v);\n}\n\nstatic int indent = 0;\n\ntemplate \nostream &operator<<(ostream &out, const BigVec &v) {\n ++indent;\n out << \"[\";\n typename vector::const_iterator i, end;\n bool first = true;\n for (i = v.v->begin(), end = v.v->end(); i != end; ++i) {\n if (!first)\n out << \",\";\n first = false;\n out << \"\\n\";\n for (int j = 0; j < indent; ++j)\n out << \" \";\n out << *i;\n }\n out << \"]\";\n --indent;\n return out;\n}\n\n\n\f\n\/\/\n\/\/ print\n\/\/\n\nstatic void print(const Object *x, ostream &out) {\n if (x == NULL) {\n out << \"NULL\";\n return;\n }\n\n switch (x->objKind) {\n\n case SOURCE : {\n Source *y = (Source *)x;\n out << \"Source(\" << y->fileName << \")\";\n break;\n }\n case LOCATION : {\n Location *y = (Location *)x;\n out << \"Location(\" << y->source << \", \" << y->offset << \")\";\n break;\n }\n case TOKEN : {\n Token *y = (Token *)x;\n out << \"Token(\";\n switch (y->tokenKind) {\n case T_SYMBOL :\n out << \"T_SYMBOL\";\n break;\n case T_KEYWORD :\n out << \"T_KEYWORD\";\n break;\n case T_IDENTIFIER :\n out << \"T_IDENTIFIER\";\n break;\n case T_STRING_LITERAL :\n out << \"T_STRING_LITERAL\";\n break;\n case T_CHAR_LITERAL :\n out << \"T_CHAR_LITERAL\";\n break;\n case T_INT_LITERAL :\n out << \"T_INT_LITERAL\";\n break;\n case T_FLOAT_LITERAL :\n out << \"T_FLOAT_LITERAL\";\n break;\n case T_LITERAL_SUFFIX :\n out << \"T_LITERAL_SUFFIX\";\n break;\n case T_SPACE :\n out << \"T_SPACE\";\n break;\n case T_LINE_COMMENT :\n out << \"T_LINE_COMMENT\";\n break;\n case T_BLOCK_COMMENT :\n out << \"T_BLOCK_COMMENT\";\n break;\n default :\n assert(false);\n }\n out << \", \" << y->str << \")\";\n break;\n }\n\n case IDENTIFIER : {\n Identifier *y = (Identifier *)x;\n out << \"Identifier(\" << y->str << \")\";\n break;\n }\n case DOTTED_NAME : {\n DottedName *y = (DottedName *)x;\n out << \"DottedName(\" << y->parts << \")\";\n break;\n }\n\n case BOOL_LITERAL : {\n BoolLiteral *y = (BoolLiteral *)x;\n out << \"BoolLiteral(\" << y->value << \")\";\n break;\n }\n case INT_LITERAL : {\n IntLiteral *y = (IntLiteral *)x;\n out << \"IntLiteral(\" << y->value;\n if (!y->suffix.empty())\n out << \", \" << y->suffix;\n out << \")\";\n break;\n }\n case FLOAT_LITERAL : {\n FloatLiteral *y = (FloatLiteral *)x;\n out << \"FloatLiteral(\" << y->value;\n if (!y->suffix.empty())\n out << \", \" << y->suffix;\n out << \")\";\n break;\n }\n case CHAR_LITERAL : {\n CharLiteral *y = (CharLiteral *)x;\n out << \"CharLiteral(\" << y->value << \")\";\n break;\n }\n case STRING_LITERAL : {\n StringLiteral *y = (StringLiteral *)x;\n out << \"StringLiteral(\" << y->value << \")\";\n break;\n }\n\n case NAME_REF : {\n NameRef *y = (NameRef *)x;\n out << \"NameRef(\" << y->name << \")\";\n break;\n }\n case TUPLE : {\n Tuple *y = (Tuple *)x;\n out << \"Tuple(\" << y->args << \")\";\n break;\n }\n case ARRAY : {\n Array *y = (Array *)x;\n out << \"Array(\" << y->args << \")\";\n break;\n }\n case INDEXING : {\n Indexing *y = (Indexing *)x;\n out << \"Indexing(\" << y->expr << \", \" << y->args << \")\";\n break;\n }\n case CALL : {\n Call *y = (Call *)x;\n out << \"Call(\" << y->expr << \", \" << y->args << \")\";\n break;\n }\n case FIELD_REF : {\n FieldRef *y = (FieldRef *)x;\n out << \"FieldRef(\" << y->expr << \", \" << y->name << \")\";\n break;\n }\n case TUPLE_REF : {\n TupleRef *y = (TupleRef *)x;\n out << \"TupleRef(\" << y->expr << \", \" << y->index << \")\";\n break;\n }\n case UNARY_OP : {\n UnaryOp *y = (UnaryOp *)x;\n out << \"UnaryOp(\";\n switch (y->op) {\n case DEREFERENCE :\n out << \"DEREFERENCE\";\n break;\n case ADDRESS_OF :\n out << \"ADDRESS_OF\";\n break;\n case PLUS :\n out << \"PLUS\";\n break;\n case MINUS :\n out << \"MINUS\";\n break;\n case NOT :\n out << \"NOT\";\n break;\n default :\n assert(false);\n }\n out << \", \" << y->expr << \")\";\n break;\n }\n case BINARY_OP : {\n BinaryOp *y = (BinaryOp *)x;\n out << \"BinaryOp(\";\n switch (y->op) {\n case ADD :\n out << \"ADD\";\n break;\n case SUBTRACT :\n out << \"SUBTRACT\";\n break;\n case MULTIPLY :\n out << \"MULTIPLY\";\n break;\n case DIVIDE :\n out << \"DIVIDE\";\n break;\n case REMAINDER :\n out << \"REMAINDER\";\n break;\n case EQUALS :\n out << \"EQUALS\";\n break;\n case NOT_EQUALS :\n out << \"NOT_EQUALS\";\n break;\n case LESSER :\n out << \"LESSER\";\n break;\n case LESSER_EQUALS :\n out << \"LESSER_EQUALS\";\n break;\n case GREATER :\n out << \"GREATER\";\n break;\n case GREATER_EQUALS :\n out << \"GREATER_EQUALS\";\n break;\n default :\n assert(false);\n }\n out << \", \" << y->expr1 << \", \" << y->expr2 << \")\";\n break;\n }\n case AND : {\n And *y = (And *)x;\n out << \"And(\" << y->expr1 << \", \" << y->expr2 << \")\";\n break;\n }\n case OR : {\n Or *y = (Or *)x;\n out << \"Or(\" << y->expr1 << \", \" << y->expr2 << \")\";\n break;\n }\n case SC_EXPR : {\n SCExpr *y = (SCExpr *)x;\n out << \"SCExpr(\" << y->expr << \")\";\n break;\n }\n case VALUE_EXPR : {\n ValueExpr *y = (ValueExpr *)x;\n out << \"ValueExpr(\" << y->value << \")\";\n break;\n }\n\n case BLOCK : {\n Block *y = (Block *)x;\n out << \"Block(\" << bigVec(y->statements) << \")\";\n break;\n }\n case LABEL : {\n Label *y = (Label *)x;\n out << \"Label(\" << y->name << \")\";\n break;\n }\n case BINDING : {\n Binding *y = (Binding *)x;\n out << \"Binding(\";\n switch (y->bindingKind) {\n case VAR :\n out << \"VAR\";\n break;\n case REF :\n out << \"REF\";\n break;\n case STATIC :\n out << \"STATIC\";\n break;\n default :\n assert(false);\n }\n out << \", \" << y->name << \", \" << y->expr << \")\";\n break;\n }\n case ASSIGNMENT : {\n Assignment *y = (Assignment *)x;\n out << \"Assignment(\" << y->left << \", \" << y->right << \")\";\n break;\n }\n case GOTO : {\n Goto *y = (Goto *)x;\n out << \"Goto(\" << y->labelName << \")\";\n break;\n }\n case RETURN : {\n Return *y = (Return *)x;\n out << \"Return(\" << y->expr << \")\";\n break;\n }\n case RETURN_REF : {\n ReturnRef *y = (ReturnRef *)x;\n out << \"ReturnRef(\" << y->expr << \")\";\n break;\n }\n case IF : {\n If *y = (If *)x;\n out << \"If(\" << y->condition << \", \" << y->thenPart;\n out << \", \" << y->elsePart << \")\";\n break;\n }\n case EXPR_STATEMENT : {\n ExprStatement *y = (ExprStatement *)x;\n out << \"ExprStatement(\" << y->expr << \")\";\n break;\n }\n case WHILE : {\n While *y = (While *)x;\n out << \"While(\" << y->condition << \", \" << y->body << \")\";\n break;\n }\n case BREAK : {\n out << \"Break()\";\n break;\n }\n case CONTINUE : {\n out << \"Continue()\";\n break;\n }\n case FOR : {\n For *y = (For *)x;\n out << \"For(\" << y->variable << \", \" << y->expr;\n out << \", \" << y->body << \")\";\n break;\n }\n\n case CODE : {\n Code *y = (Code *)x;\n out << \"Code(\" << y->patternVars << \", \" << y->predicate;\n out << \", \" << y->formalArgs << \", \" << y->body << \")\";\n break;\n }\n case VALUE_ARG : {\n ValueArg *y = (ValueArg *)x;\n out << \"ValueArg(\" << y->name << \", \" << y->type << \")\";\n break;\n }\n case STATIC_ARG : {\n StaticArg *y = (StaticArg *)x;\n out << \"StaticArg(\" << y->pattern << \")\";\n break;\n }\n\n case RECORD : {\n Record *y = (Record *)x;\n out << \"Record(\" << y->name << \", \" << y->patternVars;\n out << \", \" << y->formalArgs << \")\";\n break;\n }\n case PROCEDURE : {\n Procedure *y = (Procedure *)x;\n out << \"Procedure(\" << y->name << \", \" << y->code << \")\";\n break;\n }\n case OVERLOAD : {\n Overload *y = (Overload *)x;\n out << \"Overload(\" << y->name << \", \" << y->code << \")\";\n break;\n }\n case OVERLOADABLE : {\n Overloadable *y = (Overloadable *)x;\n out << \"Overloadable(\" << y->name << \")\";\n break;\n }\n case EXTERNAL_PROCEDURE : {\n ExternalProcedure *y = (ExternalProcedure *)x;\n out << \"ExternalProcedure(\" << y->name << \", \" << y->args;\n out << \", \" << y->returnType << \")\";\n break;\n }\n\n case IMPORT : {\n Import *y = (Import *)x;\n out << \"Import(\" << y->dottedName << \")\";\n break;\n }\n case EXPORT : {\n Export *y = (Export *)x;\n out << \"Export(\" << y->dottedName << \")\";\n break;\n }\n case MODULE : {\n Module *y = (Module *)x;\n out << \"Module(\" << bigVec(y->imports) << \", \" << bigVec(y->exports);\n out << \", \" << bigVec(y->topLevelItems) << \")\";\n break;\n }\n\n case TYPE : {\n Type *y = (Type *)x;\n typePrint(y, out);\n break;\n }\n\n case VALUE : {\n Value *y = (Value *)x;\n valuePrint(y, out);\n break;\n }\n\n default :\n assert(false);\n }\n}\n<|endoftext|>"} {"text":"\/*\n * Copyright (C) 2008-2014 The QXmpp developers\n *\n * Authors:\n * Jeremy Lainé\n *\n * Source:\n * https:\/\/github.com\/qxmpp-project\/qxmpp\n *\n * This file is a part of QXmpp library.\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n *\/\n\n#include \n#include \n\n#include \"QXmppClient.h\"\n#include \"QXmppServer.h\"\n#include \"QXmppTransferManager.h\"\n#include \"util.h\"\n\nQ_DECLARE_METATYPE(QXmppTransferJob::Method)\n\nclass tst_QXmppTransferManager : public QObject\n{\n Q_OBJECT\n\nprivate slots:\n void init();\n void testSendFile_data();\n void testSendFile();\n\n void acceptFile(QXmppTransferJob *job);\n\nprivate:\n QBuffer receiverBuffer;\n QXmppTransferJob *receiverJob;\n};\n\nvoid tst_QXmppTransferManager::init()\n{\n receiverBuffer.close();\n receiverBuffer.setData(QByteArray());\n receiverJob = 0;\n}\n\nvoid tst_QXmppTransferManager::acceptFile(QXmppTransferJob *job)\n{\n receiverJob = job;\n receiverBuffer.open(QIODevice::WriteOnly);\n job->accept(&receiverBuffer);\n}\n\nvoid tst_QXmppTransferManager::testSendFile_data()\n{\n QTest::addColumn(\"senderMethods\");\n QTest::addColumn(\"receiverMethods\");\n QTest::addColumn(\"works\");\n\n QTest::newRow(\"any - any\") << QXmppTransferJob::AnyMethod << QXmppTransferJob::AnyMethod << true;\n QTest::newRow(\"any - inband\") << QXmppTransferJob::AnyMethod << QXmppTransferJob::InBandMethod << true;\n QTest::newRow(\"any - socks\") << QXmppTransferJob::AnyMethod << QXmppTransferJob::SocksMethod << true;\n\n QTest::newRow(\"inband - any\") << QXmppTransferJob::InBandMethod << QXmppTransferJob::AnyMethod << true;\n QTest::newRow(\"inband - inband\") << QXmppTransferJob::InBandMethod << QXmppTransferJob::InBandMethod << true;\n QTest::newRow(\"inband - socks\") << QXmppTransferJob::InBandMethod << QXmppTransferJob::SocksMethod << false;\n\n QTest::newRow(\"socks - any\") << QXmppTransferJob::SocksMethod << QXmppTransferJob::AnyMethod << true;\n QTest::newRow(\"socks - inband\") << QXmppTransferJob::SocksMethod << QXmppTransferJob::InBandMethod << false;\n QTest::newRow(\"socks - socks\") << QXmppTransferJob::SocksMethod << QXmppTransferJob::SocksMethod << true;\n}\n\nvoid tst_QXmppTransferManager::testSendFile()\n{\n QFETCH(QXmppTransferJob::Method, senderMethods);\n QFETCH(QXmppTransferJob::Method, receiverMethods);\n QFETCH(bool, works);\n\n const QString testDomain(\"localhost\");\n const QHostAddress testHost(QHostAddress::LocalHost);\n const quint16 testPort = 12345;\n\n QXmppLogger logger;\n \/\/logger.setLoggingType(QXmppLogger::StdoutLogging);\n\n \/\/ prepare server\n TestPasswordChecker passwordChecker;\n passwordChecker.addCredentials(\"sender\", \"testpwd\");\n passwordChecker.addCredentials(\"receiver\", \"testpwd\");\n\n QXmppServer server;\n server.setDomain(testDomain);\n server.setLogger(&logger);\n server.setPasswordChecker(&passwordChecker);\n server.listenForClients(testHost, testPort);\n\n \/\/ prepare sender\n QXmppClient sender;\n QXmppTransferManager *senderManager = new QXmppTransferManager;\n senderManager->setSupportedMethods(senderMethods);\n sender.addExtension(senderManager);\n sender.setLogger(&logger);\n\n QEventLoop senderLoop;\n connect(&sender, SIGNAL(connected()), &senderLoop, SLOT(quit()));\n connect(&sender, SIGNAL(disconnected()), &senderLoop, SLOT(quit()));\n\n QXmppConfiguration config;\n config.setDomain(testDomain);\n config.setHost(testHost.toString());\n config.setPort(testPort);\n config.setUser(\"sender\");\n config.setPassword(\"testpwd\");\n sender.connectToServer(config);\n senderLoop.exec();\n QCOMPARE(sender.isConnected(), true);\n\n \/\/ prepare receiver\n QXmppClient receiver;\n QXmppTransferManager *receiverManager = new QXmppTransferManager;\n receiverManager->setSupportedMethods(receiverMethods);\n connect(receiverManager, SIGNAL(fileReceived(QXmppTransferJob*)),\n this, SLOT(acceptFile(QXmppTransferJob*)));\n receiver.addExtension(receiverManager);\n receiver.setLogger(&logger);\n\n QEventLoop receiverLoop;\n connect(&receiver, SIGNAL(connected()), &receiverLoop, SLOT(quit()));\n connect(&receiver, SIGNAL(disconnected()), &receiverLoop, SLOT(quit()));\n\n config.setUser(\"receiver\");\n config.setPassword(\"testpwd\");\n receiver.connectToServer(config);\n receiverLoop.exec();\n QCOMPARE(receiver.isConnected(), true);\n\n \/\/ send file\n QEventLoop loop;\n QXmppTransferJob *senderJob = senderManager->sendFile(\"receiver@localhost\/QXmpp\", \":\/test.svg\");\n QVERIFY(senderJob);\n QCOMPARE(senderJob->localFileUrl().toLocalFile(), QString(\":\/test.svg\"));\n connect(senderJob, SIGNAL(finished()), &loop, SLOT(quit()));\n loop.exec();\n\n if (works) {\n QCOMPARE(senderJob->state(), QXmppTransferJob::FinishedState);\n QCOMPARE(senderJob->error(), QXmppTransferJob::NoError);\n\n \/\/ finish receiving file\n QVERIFY(receiverJob);\n connect(receiverJob, SIGNAL(finished()), &loop, SLOT(quit()));\n loop.exec();\n\n QCOMPARE(receiverJob->state(), QXmppTransferJob::FinishedState);\n QCOMPARE(receiverJob->error(), QXmppTransferJob::NoError);\n\n \/\/ check received file\n QFile expectedFile(\":\/test.svg\");\n QVERIFY(expectedFile.open(QIODevice::ReadOnly));\n const QByteArray expectedData = expectedFile.readAll();\n QCOMPARE(receiverBuffer.data(), expectedData);\n } else {\n QCOMPARE(senderJob->state(), QXmppTransferJob::FinishedState);\n QCOMPARE(senderJob->error(), QXmppTransferJob::AbortError);\n\n QVERIFY(!receiverJob);\n\n QCOMPARE(receiverBuffer.data(), QByteArray());\n }\n}\n\nQTEST_MAIN(tst_QXmppTransferManager)\n#include \"tst_qxmpptransfermanager.moc\"\nChange test case for c4f27ae, compare localFileUrl directly\/*\n * Copyright (C) 2008-2014 The QXmpp developers\n *\n * Authors:\n * Jeremy Lainé\n *\n * Source:\n * https:\/\/github.com\/qxmpp-project\/qxmpp\n *\n * This file is a part of QXmpp library.\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n *\/\n\n#include \n#include \n\n#include \"QXmppClient.h\"\n#include \"QXmppServer.h\"\n#include \"QXmppTransferManager.h\"\n#include \"util.h\"\n\nQ_DECLARE_METATYPE(QXmppTransferJob::Method)\n\nclass tst_QXmppTransferManager : public QObject\n{\n Q_OBJECT\n\nprivate slots:\n void init();\n void testSendFile_data();\n void testSendFile();\n\n void acceptFile(QXmppTransferJob *job);\n\nprivate:\n QBuffer receiverBuffer;\n QXmppTransferJob *receiverJob;\n};\n\nvoid tst_QXmppTransferManager::init()\n{\n receiverBuffer.close();\n receiverBuffer.setData(QByteArray());\n receiverJob = 0;\n}\n\nvoid tst_QXmppTransferManager::acceptFile(QXmppTransferJob *job)\n{\n receiverJob = job;\n receiverBuffer.open(QIODevice::WriteOnly);\n job->accept(&receiverBuffer);\n}\n\nvoid tst_QXmppTransferManager::testSendFile_data()\n{\n QTest::addColumn(\"senderMethods\");\n QTest::addColumn(\"receiverMethods\");\n QTest::addColumn(\"works\");\n\n QTest::newRow(\"any - any\") << QXmppTransferJob::AnyMethod << QXmppTransferJob::AnyMethod << true;\n QTest::newRow(\"any - inband\") << QXmppTransferJob::AnyMethod << QXmppTransferJob::InBandMethod << true;\n QTest::newRow(\"any - socks\") << QXmppTransferJob::AnyMethod << QXmppTransferJob::SocksMethod << true;\n\n QTest::newRow(\"inband - any\") << QXmppTransferJob::InBandMethod << QXmppTransferJob::AnyMethod << true;\n QTest::newRow(\"inband - inband\") << QXmppTransferJob::InBandMethod << QXmppTransferJob::InBandMethod << true;\n QTest::newRow(\"inband - socks\") << QXmppTransferJob::InBandMethod << QXmppTransferJob::SocksMethod << false;\n\n QTest::newRow(\"socks - any\") << QXmppTransferJob::SocksMethod << QXmppTransferJob::AnyMethod << true;\n QTest::newRow(\"socks - inband\") << QXmppTransferJob::SocksMethod << QXmppTransferJob::InBandMethod << false;\n QTest::newRow(\"socks - socks\") << QXmppTransferJob::SocksMethod << QXmppTransferJob::SocksMethod << true;\n}\n\nvoid tst_QXmppTransferManager::testSendFile()\n{\n QFETCH(QXmppTransferJob::Method, senderMethods);\n QFETCH(QXmppTransferJob::Method, receiverMethods);\n QFETCH(bool, works);\n\n const QString testDomain(\"localhost\");\n const QHostAddress testHost(QHostAddress::LocalHost);\n const quint16 testPort = 12345;\n\n QXmppLogger logger;\n \/\/logger.setLoggingType(QXmppLogger::StdoutLogging);\n\n \/\/ prepare server\n TestPasswordChecker passwordChecker;\n passwordChecker.addCredentials(\"sender\", \"testpwd\");\n passwordChecker.addCredentials(\"receiver\", \"testpwd\");\n\n QXmppServer server;\n server.setDomain(testDomain);\n server.setLogger(&logger);\n server.setPasswordChecker(&passwordChecker);\n server.listenForClients(testHost, testPort);\n\n \/\/ prepare sender\n QXmppClient sender;\n QXmppTransferManager *senderManager = new QXmppTransferManager;\n senderManager->setSupportedMethods(senderMethods);\n sender.addExtension(senderManager);\n sender.setLogger(&logger);\n\n QEventLoop senderLoop;\n connect(&sender, SIGNAL(connected()), &senderLoop, SLOT(quit()));\n connect(&sender, SIGNAL(disconnected()), &senderLoop, SLOT(quit()));\n\n QXmppConfiguration config;\n config.setDomain(testDomain);\n config.setHost(testHost.toString());\n config.setPort(testPort);\n config.setUser(\"sender\");\n config.setPassword(\"testpwd\");\n sender.connectToServer(config);\n senderLoop.exec();\n QCOMPARE(sender.isConnected(), true);\n\n \/\/ prepare receiver\n QXmppClient receiver;\n QXmppTransferManager *receiverManager = new QXmppTransferManager;\n receiverManager->setSupportedMethods(receiverMethods);\n connect(receiverManager, SIGNAL(fileReceived(QXmppTransferJob*)),\n this, SLOT(acceptFile(QXmppTransferJob*)));\n receiver.addExtension(receiverManager);\n receiver.setLogger(&logger);\n\n QEventLoop receiverLoop;\n connect(&receiver, SIGNAL(connected()), &receiverLoop, SLOT(quit()));\n connect(&receiver, SIGNAL(disconnected()), &receiverLoop, SLOT(quit()));\n\n config.setUser(\"receiver\");\n config.setPassword(\"testpwd\");\n receiver.connectToServer(config);\n receiverLoop.exec();\n QCOMPARE(receiver.isConnected(), true);\n\n \/\/ send file\n QEventLoop loop;\n QXmppTransferJob *senderJob = senderManager->sendFile(\"receiver@localhost\/QXmpp\", \":\/test.svg\");\n QVERIFY(senderJob);\n QCOMPARE(senderJob->localFileUrl(), QUrl::fromLocalFile(\":\/test.svg\"));\n connect(senderJob, SIGNAL(finished()), &loop, SLOT(quit()));\n loop.exec();\n\n if (works) {\n QCOMPARE(senderJob->state(), QXmppTransferJob::FinishedState);\n QCOMPARE(senderJob->error(), QXmppTransferJob::NoError);\n\n \/\/ finish receiving file\n QVERIFY(receiverJob);\n connect(receiverJob, SIGNAL(finished()), &loop, SLOT(quit()));\n loop.exec();\n\n QCOMPARE(receiverJob->state(), QXmppTransferJob::FinishedState);\n QCOMPARE(receiverJob->error(), QXmppTransferJob::NoError);\n\n \/\/ check received file\n QFile expectedFile(\":\/test.svg\");\n QVERIFY(expectedFile.open(QIODevice::ReadOnly));\n const QByteArray expectedData = expectedFile.readAll();\n QCOMPARE(receiverBuffer.data(), expectedData);\n } else {\n QCOMPARE(senderJob->state(), QXmppTransferJob::FinishedState);\n QCOMPARE(senderJob->error(), QXmppTransferJob::AbortError);\n\n QVERIFY(!receiverJob);\n\n QCOMPARE(receiverBuffer.data(), QByteArray());\n }\n}\n\nQTEST_MAIN(tst_QXmppTransferManager)\n#include \"tst_qxmpptransfermanager.moc\"\n<|endoftext|>"} {"text":"\/*\n * Copyright (c) 2003-2010, John Wiegley. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n * - Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n *\n * - Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution.\n *\n * - Neither the name of New Artisans LLC nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \n\n#include \"pyinterp.h\"\n#include \"account.h\"\n#include \"xact.h\"\n#include \"post.h\"\n\nnamespace ledger {\n\nusing namespace python;\n\nshared_ptr python_session;\n\nchar * argv0;\n\nvoid export_account();\nvoid export_amount();\nvoid export_balance();\nvoid export_commodity();\nvoid export_expr();\nvoid export_format();\nvoid export_item();\nvoid export_journal();\nvoid export_post();\nvoid export_times();\nvoid export_utils();\nvoid export_value();\nvoid export_xact();\n\nvoid initialize_for_python()\n{\n export_times();\n export_utils();\n export_commodity();\n export_amount();\n export_value();\n export_account();\n export_balance();\n export_expr();\n export_format();\n export_item();\n export_post();\n export_xact();\n export_journal();\n}\n\nstruct python_run\n{\n object result;\n\n python_run(python_interpreter_t * intepreter,\n const string& str, int input_mode)\n : result(handle<>(borrowed(PyRun_String(str.c_str(), input_mode,\n intepreter->main_nspace.ptr(),\n intepreter->main_nspace.ptr())))) {}\n operator object() {\n return result;\n }\n};\n\nvoid python_interpreter_t::initialize()\n{\n TRACE_START(python_init, 1, \"Initialized Python\");\n\n try {\n DEBUG(\"python.interp\", \"Initializing Python\");\n\n Py_Initialize();\n assert(Py_IsInitialized());\n\n hack_system_paths();\n\n object main_module = python::import(\"__main__\");\n if (! main_module)\n throw_(std::runtime_error,\n _(\"Python failed to initialize (couldn't find __main__)\"));\n\n main_nspace = extract(main_module.attr(\"__dict__\"));\n if (! main_nspace)\n throw_(std::runtime_error,\n _(\"Python failed to initialize (couldn't find __dict__)\"));\n\n python::detail::init_module(\"ledger\", &initialize_for_python);\n\n is_initialized = true;\n }\n catch (const error_already_set&) {\n PyErr_Print();\n throw_(std::runtime_error, _(\"Python failed to initialize\"));\n }\n\n TRACE_FINISH(python_init, 1);\n}\n\nvoid python_interpreter_t::hack_system_paths()\n{\n \/\/ Hack ledger.__path__ so it points to a real location\n python::object sys_module = python::import(\"sys\");\n python::object sys_dict = sys_module.attr(\"__dict__\");\n\n python::list paths(sys_dict[\"path\"]);\n\n#if defined(DEBUG_ON)\n bool path_initialized = false;\n#endif\n int n = python::extract(paths.attr(\"__len__\")());\n for (int i = 0; i < n; i++) {\n python::extract str(paths[i]);\n path pathname(str());\n DEBUG(\"python.interp\", \"sys.path = \" << pathname);\n\n if (exists(pathname \/ \"ledger\" \/ \"__init__.py\")) {\n if (python::object module_ledger = python::import(\"ledger\")) {\n DEBUG(\"python.interp\",\n \"Setting ledger.__path__ = \" << (pathname \/ \"ledger\"));\n\n python::object ledger_dict = module_ledger.attr(\"__dict__\");\n python::list temp_list;\n temp_list.append((pathname \/ \"ledger\").string());\n\n ledger_dict[\"__path__\"] = temp_list;\n } else {\n throw_(std::runtime_error,\n _(\"Python failed to initialize (couldn't find ledger)\"));\n }\n#if defined(DEBUG_ON)\n path_initialized = true;\n#endif\n break;\n }\n }\n#if defined(DEBUG_ON)\n if (! path_initialized)\n DEBUG(\"python.init\",\n \"Ledger failed to find 'ledger\/__init__.py' on the PYTHONPATH\");\n#endif\n}\n\nobject python_interpreter_t::import_into_main(const string& str)\n{\n if (! is_initialized)\n initialize();\n\n try {\n object mod = python::import(str.c_str());\n if (! mod)\n throw_(std::runtime_error,\n _(\"Failed to import Python module %1\") << str);\n\n \/\/ Import all top-level entries directly into the main namespace\n main_nspace.update(mod.attr(\"__dict__\"));\n\n return mod;\n }\n catch (const error_already_set&) {\n PyErr_Print();\n }\n return object();\n}\n\nobject python_interpreter_t::import_option(const string& str)\n{\n path file(str);\n\n python::object sys_module = python::import(\"sys\");\n python::object sys_dict = sys_module.attr(\"__dict__\");\n\n python::list paths(sys_dict[\"path\"]);\n\n#if BOOST_VERSION >= 103700\n paths.insert(0, file.parent_path().string());\n sys_dict[\"path\"] = paths;\n\n#if BOOST_VERSION >= 104600\n string name = file.filename().string();\n if (contains(name, \".py\"))\n name = file.stem().string();\n#else\n string name = file.filename();\n if (contains(name, \".py\"))\n name = file.stem();\n#endif\n#else \/\/ BOOST_VERSION >= 103700\n paths.insert(0, file.branch_path().string());\n sys_dict[\"path\"] = paths;\n\n string name = file.leaf();\n#endif \/\/ BOOST_VERSION >= 103700\n\n return python::import(python::str(name.c_str()));\n}\n\nobject python_interpreter_t::eval(std::istream& in, py_eval_mode_t mode)\n{\n bool first = true;\n string buffer;\n buffer.reserve(4096);\n\n while (! in.eof()) {\n char buf[256];\n in.getline(buf, 255);\n if (buf[0] == '!')\n break;\n if (first)\n first = false;\n else\n buffer += \"\\n\";\n buffer += buf;\n }\n\n if (! is_initialized)\n initialize();\n\n try {\n int input_mode = -1;\n switch (mode) {\n case PY_EVAL_EXPR: input_mode = Py_eval_input; break;\n case PY_EVAL_STMT: input_mode = Py_single_input; break;\n case PY_EVAL_MULTI: input_mode = Py_file_input; break;\n }\n\n return python_run(this, buffer, input_mode);\n }\n catch (const error_already_set&) {\n PyErr_Print();\n throw_(std::runtime_error, _(\"Failed to evaluate Python code\"));\n }\n return object();\n}\n\nobject python_interpreter_t::eval(const string& str, py_eval_mode_t mode)\n{\n if (! is_initialized)\n initialize();\n\n try {\n int input_mode = -1;\n switch (mode) {\n case PY_EVAL_EXPR: input_mode = Py_eval_input; break;\n case PY_EVAL_STMT: input_mode = Py_single_input; break;\n case PY_EVAL_MULTI: input_mode = Py_file_input; break;\n }\n\n return python_run(this, str, input_mode);\n }\n catch (const error_already_set&) {\n PyErr_Print();\n throw_(std::runtime_error, _(\"Failed to evaluate Python code\"));\n }\n return object();\n}\n\nvalue_t python_interpreter_t::python_command(call_scope_t& args)\n{\n if (! is_initialized)\n initialize();\n\n char ** argv(new char *[args.size() + 1]);\n\n argv[0] = new char[std::strlen(argv0) + 1];\n std::strcpy(argv[0], argv0);\n\n for (std::size_t i = 0; i < args.size(); i++) {\n string arg = args.get(i);\n argv[i + 1] = new char[arg.length() + 1];\n std::strcpy(argv[i + 1], arg.c_str());\n }\n\n int status = 1;\n\n try {\n status = Py_Main(static_cast(args.size()) + 1, argv);\n }\n catch (const error_already_set&) {\n PyErr_Print();\n throw_(std::runtime_error, _(\"Failed to execute Python module\"));\n }\n catch (...) {\n for (std::size_t i = 0; i < args.size() + 1; i++)\n delete[] argv[i];\n delete[] argv;\n throw;\n }\n\n for (std::size_t i = 0; i < args.size() + 1; i++)\n delete[] argv[i];\n delete[] argv;\n\n if (status != 0)\n throw status;\n\n return NULL_VALUE;\n}\n\nvalue_t python_interpreter_t::server_command(call_scope_t& args)\n{\n if (! is_initialized)\n initialize();\n\n python::object server_module;\n\n try {\n server_module = python::import(\"ledger.server\");\n if (! server_module)\n throw_(std::runtime_error,\n _(\"Could not import ledger.server; please check your PYTHONPATH\"));\n }\n catch (const error_already_set&) {\n PyErr_Print();\n throw_(std::runtime_error,\n _(\"Could not import ledger.server; please check your PYTHONPATH\"));\n }\n\n if (python::object main_function = server_module.attr(\"main\")) {\n functor_t func(main_function, \"main\");\n try {\n func(args);\n }\n catch (const error_already_set&) {\n PyErr_Print();\n throw_(std::runtime_error,\n _(\"Error while invoking ledger.server's main() function\"));\n }\n return true;\n } else {\n throw_(std::runtime_error,\n _(\"The ledger.server module is missing its main() function!\"));\n }\n\n return false;\n}\n\noption_t *\npython_interpreter_t::lookup_option(const char * p)\n{\n switch (*p) {\n case 'i':\n OPT(import_);\n break;\n }\n return NULL;\n}\n\nexpr_t::ptr_op_t python_interpreter_t::lookup(const symbol_t::kind_t kind,\n const string& name)\n{\n \/\/ Give our superclass first dibs on symbol definitions\n if (expr_t::ptr_op_t op = session_t::lookup(kind, name))\n return op;\n\n switch (kind) {\n case symbol_t::FUNCTION:\n if (option_t * handler = lookup_option(name.c_str()))\n return MAKE_OPT_FUNCTOR(python_interpreter_t, handler);\n\n if (is_initialized && main_nspace.has_key(name.c_str())) {\n DEBUG(\"python.interp\", \"Python lookup: \" << name);\n\n if (python::object obj = main_nspace.get(name.c_str()))\n return WRAP_FUNCTOR(functor_t(obj, name));\n }\n break;\n\n case symbol_t::OPTION:\n if (option_t * handler = lookup_option(name.c_str()))\n return MAKE_OPT_HANDLER(python_interpreter_t, handler);\n break;\n\n case symbol_t::PRECOMMAND: {\n const char * p = name.c_str();\n switch (*p) {\n case 'p':\n if (is_eq(p, \"python\"))\n return MAKE_FUNCTOR(python_interpreter_t::python_command);\n break;\n\n case 's':\n if (is_eq(p, \"server\"))\n return MAKE_FUNCTOR(python_interpreter_t::server_command);\n break;\n }\n }\n\n default:\n break;\n }\n\n return NULL;\n}\n\nnamespace {\n void append_value(list& lst, const value_t& value)\n {\n if (value.is_scope()) {\n const scope_t * scope = value.as_scope();\n if (const post_t * post = dynamic_cast(scope))\n lst.append(ptr(post));\n else if (const xact_t * xact = dynamic_cast(scope))\n lst.append(ptr(xact));\n else if (const account_t * account =\n dynamic_cast(scope))\n lst.append(ptr(account));\n else if (const period_xact_t * period_xact =\n dynamic_cast(scope))\n lst.append(ptr(period_xact));\n else if (const auto_xact_t * auto_xact =\n dynamic_cast(scope))\n lst.append(ptr(auto_xact));\n else\n throw_(std::logic_error,\n _(\"Cannot downcast scoped object to specific type\"));\n } else {\n lst.append(value);\n }\n }\n}\n\nvalue_t python_interpreter_t::functor_t::operator()(call_scope_t& args)\n{\n try {\n std::signal(SIGINT, SIG_DFL);\n\n if (! PyCallable_Check(func.ptr())) {\n extract val(func);\n std::signal(SIGINT, sigint_handler);\n if (val.check())\n return val();\n return NULL_VALUE;\n }\n else if (args.size() > 0) {\n list arglist;\n \/\/ jww (2009-11-05): What about a single argument which is a sequence,\n \/\/ rather than a sequence of arguments?\n if (args.value().is_sequence())\n foreach (const value_t& value, args.value().as_sequence())\n append_value(arglist, value);\n else\n append_value(arglist, args.value());\n\n if (PyObject * val =\n PyObject_CallObject(func.ptr(), python::tuple(arglist).ptr())) {\n extract xval(val);\n value_t result;\n if (xval.check()) {\n result = xval();\n Py_DECREF(val);\n } else {\n Py_DECREF(val);\n throw_(calc_error,\n _(\"Could not evaluate Python variable '%1'\") << name);\n }\n std::signal(SIGINT, sigint_handler);\n return result;\n }\n else if (PyErr_Occurred()) {\n PyErr_Print();\n throw_(calc_error, _(\"Failed call to Python function '%1'\") << name);\n } else {\n assert(false);\n }\n }\n else {\n std::signal(SIGINT, sigint_handler);\n return call(func.ptr());\n }\n }\n catch (const error_already_set&) {\n std::signal(SIGINT, sigint_handler);\n PyErr_Print();\n throw_(calc_error, _(\"Failed call to Python function '%1'\") << name);\n }\n catch (...) {\n std::signal(SIGINT, sigint_handler);\n }\n std::signal(SIGINT, sigint_handler);\n\n return NULL_VALUE;\n}\n\n} \/\/ namespace ledger\nFixed Python initialization problem with --import\/*\n * Copyright (c) 2003-2010, John Wiegley. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n * - Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n *\n * - Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution.\n *\n * - Neither the name of New Artisans LLC nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \n\n#include \"pyinterp.h\"\n#include \"account.h\"\n#include \"xact.h\"\n#include \"post.h\"\n\nnamespace ledger {\n\nusing namespace python;\n\nshared_ptr python_session;\n\nchar * argv0;\n\nvoid export_account();\nvoid export_amount();\nvoid export_balance();\nvoid export_commodity();\nvoid export_expr();\nvoid export_format();\nvoid export_item();\nvoid export_journal();\nvoid export_post();\nvoid export_times();\nvoid export_utils();\nvoid export_value();\nvoid export_xact();\n\nvoid initialize_for_python()\n{\n export_times();\n export_utils();\n export_commodity();\n export_amount();\n export_value();\n export_account();\n export_balance();\n export_expr();\n export_format();\n export_item();\n export_post();\n export_xact();\n export_journal();\n}\n\nstruct python_run\n{\n object result;\n\n python_run(python_interpreter_t * intepreter,\n const string& str, int input_mode)\n : result(handle<>(borrowed(PyRun_String(str.c_str(), input_mode,\n intepreter->main_nspace.ptr(),\n intepreter->main_nspace.ptr())))) {}\n operator object() {\n return result;\n }\n};\n\nvoid python_interpreter_t::initialize()\n{\n TRACE_START(python_init, 1, \"Initialized Python\");\n\n try {\n DEBUG(\"python.interp\", \"Initializing Python\");\n\n Py_Initialize();\n assert(Py_IsInitialized());\n\n hack_system_paths();\n\n object main_module = python::import(\"__main__\");\n if (! main_module)\n throw_(std::runtime_error,\n _(\"Python failed to initialize (couldn't find __main__)\"));\n\n main_nspace = extract(main_module.attr(\"__dict__\"));\n if (! main_nspace)\n throw_(std::runtime_error,\n _(\"Python failed to initialize (couldn't find __dict__)\"));\n\n python::detail::init_module(\"ledger\", &initialize_for_python);\n\n is_initialized = true;\n }\n catch (const error_already_set&) {\n PyErr_Print();\n throw_(std::runtime_error, _(\"Python failed to initialize\"));\n }\n\n TRACE_FINISH(python_init, 1);\n}\n\nvoid python_interpreter_t::hack_system_paths()\n{\n \/\/ Hack ledger.__path__ so it points to a real location\n python::object sys_module = python::import(\"sys\");\n python::object sys_dict = sys_module.attr(\"__dict__\");\n\n python::list paths(sys_dict[\"path\"]);\n\n#if defined(DEBUG_ON)\n bool path_initialized = false;\n#endif\n int n = python::extract(paths.attr(\"__len__\")());\n for (int i = 0; i < n; i++) {\n python::extract str(paths[i]);\n path pathname(str());\n DEBUG(\"python.interp\", \"sys.path = \" << pathname);\n\n if (exists(pathname \/ \"ledger\" \/ \"__init__.py\")) {\n if (python::object module_ledger = python::import(\"ledger\")) {\n DEBUG(\"python.interp\",\n \"Setting ledger.__path__ = \" << (pathname \/ \"ledger\"));\n\n python::object ledger_dict = module_ledger.attr(\"__dict__\");\n python::list temp_list;\n temp_list.append((pathname \/ \"ledger\").string());\n\n ledger_dict[\"__path__\"] = temp_list;\n } else {\n throw_(std::runtime_error,\n _(\"Python failed to initialize (couldn't find ledger)\"));\n }\n#if defined(DEBUG_ON)\n path_initialized = true;\n#endif\n break;\n }\n }\n#if defined(DEBUG_ON)\n if (! path_initialized)\n DEBUG(\"python.init\",\n \"Ledger failed to find 'ledger\/__init__.py' on the PYTHONPATH\");\n#endif\n}\n\nobject python_interpreter_t::import_into_main(const string& str)\n{\n if (! is_initialized)\n initialize();\n\n try {\n object mod = python::import(str.c_str());\n if (! mod)\n throw_(std::runtime_error,\n _(\"Failed to import Python module %1\") << str);\n\n \/\/ Import all top-level entries directly into the main namespace\n main_nspace.update(mod.attr(\"__dict__\"));\n\n return mod;\n }\n catch (const error_already_set&) {\n PyErr_Print();\n }\n return object();\n}\n\nobject python_interpreter_t::import_option(const string& str)\n{\n if (! is_initialized)\n initialize();\n\n path file(str);\n string name(str);\n\n python::object sys_module = python::import(\"sys\");\n python::object sys_dict = sys_module.attr(\"__dict__\");\n\n python::list paths(sys_dict[\"path\"]);\n\n if (contains(str, \".py\")) {\n#if BOOST_VERSION >= 103700\n path& cwd(get_parsing_context().current_directory);\n paths.insert(0, filesystem::absolute(file, cwd).parent_path().string());\n sys_dict[\"path\"] = paths;\n\n#if BOOST_VERSION >= 104600\n name = file.stem().string();\n#else\n name = file.stem();\n#endif\n#else \/\/ BOOST_VERSION >= 103700\n paths.insert(0, file.branch_path().string());\n sys_dict[\"path\"] = paths;\n name = file.leaf();\n#endif \/\/ BOOST_VERSION >= 103700\n }\n\n return python::import(python::str(name.c_str()));\n}\n\nobject python_interpreter_t::eval(std::istream& in, py_eval_mode_t mode)\n{\n bool first = true;\n string buffer;\n buffer.reserve(4096);\n\n while (! in.eof()) {\n char buf[256];\n in.getline(buf, 255);\n if (buf[0] == '!')\n break;\n if (first)\n first = false;\n else\n buffer += \"\\n\";\n buffer += buf;\n }\n\n if (! is_initialized)\n initialize();\n\n try {\n int input_mode = -1;\n switch (mode) {\n case PY_EVAL_EXPR: input_mode = Py_eval_input; break;\n case PY_EVAL_STMT: input_mode = Py_single_input; break;\n case PY_EVAL_MULTI: input_mode = Py_file_input; break;\n }\n\n return python_run(this, buffer, input_mode);\n }\n catch (const error_already_set&) {\n PyErr_Print();\n throw_(std::runtime_error, _(\"Failed to evaluate Python code\"));\n }\n return object();\n}\n\nobject python_interpreter_t::eval(const string& str, py_eval_mode_t mode)\n{\n if (! is_initialized)\n initialize();\n\n try {\n int input_mode = -1;\n switch (mode) {\n case PY_EVAL_EXPR: input_mode = Py_eval_input; break;\n case PY_EVAL_STMT: input_mode = Py_single_input; break;\n case PY_EVAL_MULTI: input_mode = Py_file_input; break;\n }\n\n return python_run(this, str, input_mode);\n }\n catch (const error_already_set&) {\n PyErr_Print();\n throw_(std::runtime_error, _(\"Failed to evaluate Python code\"));\n }\n return object();\n}\n\nvalue_t python_interpreter_t::python_command(call_scope_t& args)\n{\n if (! is_initialized)\n initialize();\n\n char ** argv(new char *[args.size() + 1]);\n\n argv[0] = new char[std::strlen(argv0) + 1];\n std::strcpy(argv[0], argv0);\n\n for (std::size_t i = 0; i < args.size(); i++) {\n string arg = args.get(i);\n argv[i + 1] = new char[arg.length() + 1];\n std::strcpy(argv[i + 1], arg.c_str());\n }\n\n int status = 1;\n\n try {\n status = Py_Main(static_cast(args.size()) + 1, argv);\n }\n catch (const error_already_set&) {\n PyErr_Print();\n throw_(std::runtime_error, _(\"Failed to execute Python module\"));\n }\n catch (...) {\n for (std::size_t i = 0; i < args.size() + 1; i++)\n delete[] argv[i];\n delete[] argv;\n throw;\n }\n\n for (std::size_t i = 0; i < args.size() + 1; i++)\n delete[] argv[i];\n delete[] argv;\n\n if (status != 0)\n throw status;\n\n return NULL_VALUE;\n}\n\nvalue_t python_interpreter_t::server_command(call_scope_t& args)\n{\n if (! is_initialized)\n initialize();\n\n python::object server_module;\n\n try {\n server_module = python::import(\"ledger.server\");\n if (! server_module)\n throw_(std::runtime_error,\n _(\"Could not import ledger.server; please check your PYTHONPATH\"));\n }\n catch (const error_already_set&) {\n PyErr_Print();\n throw_(std::runtime_error,\n _(\"Could not import ledger.server; please check your PYTHONPATH\"));\n }\n\n if (python::object main_function = server_module.attr(\"main\")) {\n functor_t func(main_function, \"main\");\n try {\n func(args);\n }\n catch (const error_already_set&) {\n PyErr_Print();\n throw_(std::runtime_error,\n _(\"Error while invoking ledger.server's main() function\"));\n }\n return true;\n } else {\n throw_(std::runtime_error,\n _(\"The ledger.server module is missing its main() function!\"));\n }\n\n return false;\n}\n\noption_t *\npython_interpreter_t::lookup_option(const char * p)\n{\n switch (*p) {\n case 'i':\n OPT(import_);\n break;\n }\n return NULL;\n}\n\nexpr_t::ptr_op_t python_interpreter_t::lookup(const symbol_t::kind_t kind,\n const string& name)\n{\n \/\/ Give our superclass first dibs on symbol definitions\n if (expr_t::ptr_op_t op = session_t::lookup(kind, name))\n return op;\n\n switch (kind) {\n case symbol_t::FUNCTION:\n if (option_t * handler = lookup_option(name.c_str()))\n return MAKE_OPT_FUNCTOR(python_interpreter_t, handler);\n\n if (is_initialized && main_nspace.has_key(name.c_str())) {\n DEBUG(\"python.interp\", \"Python lookup: \" << name);\n\n if (python::object obj = main_nspace.get(name.c_str()))\n return WRAP_FUNCTOR(functor_t(obj, name));\n }\n break;\n\n case symbol_t::OPTION:\n if (option_t * handler = lookup_option(name.c_str()))\n return MAKE_OPT_HANDLER(python_interpreter_t, handler);\n break;\n\n case symbol_t::PRECOMMAND: {\n const char * p = name.c_str();\n switch (*p) {\n case 'p':\n if (is_eq(p, \"python\"))\n return MAKE_FUNCTOR(python_interpreter_t::python_command);\n break;\n\n case 's':\n if (is_eq(p, \"server\"))\n return MAKE_FUNCTOR(python_interpreter_t::server_command);\n break;\n }\n }\n\n default:\n break;\n }\n\n return NULL;\n}\n\nnamespace {\n void append_value(list& lst, const value_t& value)\n {\n if (value.is_scope()) {\n const scope_t * scope = value.as_scope();\n if (const post_t * post = dynamic_cast(scope))\n lst.append(ptr(post));\n else if (const xact_t * xact = dynamic_cast(scope))\n lst.append(ptr(xact));\n else if (const account_t * account =\n dynamic_cast(scope))\n lst.append(ptr(account));\n else if (const period_xact_t * period_xact =\n dynamic_cast(scope))\n lst.append(ptr(period_xact));\n else if (const auto_xact_t * auto_xact =\n dynamic_cast(scope))\n lst.append(ptr(auto_xact));\n else\n throw_(std::logic_error,\n _(\"Cannot downcast scoped object to specific type\"));\n } else {\n lst.append(value);\n }\n }\n}\n\nvalue_t python_interpreter_t::functor_t::operator()(call_scope_t& args)\n{\n try {\n std::signal(SIGINT, SIG_DFL);\n\n if (! PyCallable_Check(func.ptr())) {\n extract val(func);\n std::signal(SIGINT, sigint_handler);\n if (val.check())\n return val();\n return NULL_VALUE;\n }\n else if (args.size() > 0) {\n list arglist;\n \/\/ jww (2009-11-05): What about a single argument which is a sequence,\n \/\/ rather than a sequence of arguments?\n if (args.value().is_sequence())\n foreach (const value_t& value, args.value().as_sequence())\n append_value(arglist, value);\n else\n append_value(arglist, args.value());\n\n if (PyObject * val =\n PyObject_CallObject(func.ptr(), python::tuple(arglist).ptr())) {\n extract xval(val);\n value_t result;\n if (xval.check()) {\n result = xval();\n Py_DECREF(val);\n } else {\n Py_DECREF(val);\n throw_(calc_error,\n _(\"Could not evaluate Python variable '%1'\") << name);\n }\n std::signal(SIGINT, sigint_handler);\n return result;\n }\n else if (PyErr_Occurred()) {\n PyErr_Print();\n throw_(calc_error, _(\"Failed call to Python function '%1'\") << name);\n } else {\n assert(false);\n }\n }\n else {\n std::signal(SIGINT, sigint_handler);\n return call(func.ptr());\n }\n }\n catch (const error_already_set&) {\n std::signal(SIGINT, sigint_handler);\n PyErr_Print();\n throw_(calc_error, _(\"Failed call to Python function '%1'\") << name);\n }\n catch (...) {\n std::signal(SIGINT, sigint_handler);\n }\n std::signal(SIGINT, sigint_handler);\n\n return NULL_VALUE;\n}\n\n} \/\/ namespace ledger\n<|endoftext|>"} {"text":"\/*\nCopyright libCellML Contributors\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\n#include \"xmlnode.h\"\n\n#include \n#include \n#include \n#include \n\n#include \"namespaces.h\"\n#include \"xmlattribute.h\"\n\nnamespace libcellml {\n\n\/**\n * @brief The XmlNode::XmlNodeImpl struct.\n *\n * This struct is the private implementation struct for the XmlNode class. Separating\n * the implementation from the definition allows for greater flexibility when\n * distributing the code.\n *\/\nstruct XmlNode::XmlNodeImpl\n{\n xmlNodePtr mXmlNodePtr;\n};\n\nXmlNode::XmlNode()\n : mPimpl(new XmlNodeImpl())\n{\n}\n\nXmlNode::~XmlNode()\n{\n delete mPimpl;\n}\n\nvoid XmlNode::setXmlNode(const xmlNodePtr &node)\n{\n mPimpl->mXmlNodePtr = node;\n}\n\nstd::string XmlNode::namespaceUri() const\n{\n if (mPimpl->mXmlNodePtr->ns == nullptr) {\n return {};\n }\n return reinterpret_cast(mPimpl->mXmlNodePtr->ns->href);\n}\n\nvoid XmlNode::addNamespaceDefinition(const std::string &uri, const std::string &prefix)\n{\n xmlNsPtr nsPtr = xmlNewNs(mPimpl->mXmlNodePtr, reinterpret_cast(uri.c_str()), reinterpret_cast(prefix.c_str()));\n auto last = mPimpl->mXmlNodePtr->nsDef;\n while (last != nullptr) {\n last = last->next;\n }\n last = nsPtr;\n}\n\nvoid clearNamespace(const xmlNodePtr &node, xmlNsPtr ns)\n{\n if (node->ns == ns) {\n node->ns = nullptr;\n }\n xmlAttrPtr attr = node->properties;\n while (attr != nullptr) {\n if (attr->ns == ns) {\n attr->ns = nullptr;\n }\n attr = attr->next;\n }\n if (node->children != nullptr) {\n clearNamespace(node->children, ns);\n }\n if (node->next != nullptr) {\n clearNamespace(node->next, ns);\n }\n}\n\nvoid XmlNode::removeNamespaceDefinition(const std::string &uri)\n{\n xmlNsPtr previous = nullptr;\n xmlNsPtr next = nullptr;\n xmlNsPtr namespaceToRemove = nullptr;\n auto current = mPimpl->mXmlNodePtr->nsDef;\n while (current != nullptr) {\n next = current->next;\n namespaceToRemove = nullptr;\n if (xmlStrcmp(reinterpret_cast(uri.c_str()), reinterpret_cast(current->href)) == 0) {\n namespaceToRemove = current;\n } else {\n previous = current;\n }\n current = current->next;\n if (namespaceToRemove != nullptr) {\n if (previous == nullptr) {\n mPimpl->mXmlNodePtr->nsDef = next;\n } else {\n previous->next = next;\n }\n namespaceToRemove->next = nullptr;\n \/\/ Search subtree of this node and clear uses of the namespace.\n clearNamespace(mPimpl->mXmlNodePtr, namespaceToRemove);\n xmlFreeNs(namespaceToRemove);\n }\n }\n}\n\nbool XmlNode::hasNamespaceDefinition(const std::string &uri)\n{\n if (mPimpl->mXmlNodePtr->nsDef != nullptr) {\n auto next = mPimpl->mXmlNodePtr->nsDef;\n while (next != nullptr) {\n std::string href;\n if (next->href != nullptr) {\n href = std::string(reinterpret_cast(next->href));\n }\n if (href == uri) {\n return true;\n }\n next = next->next;\n }\n }\n return false;\n}\n\nXmlNamespaceMap XmlNode::definedNamespaces() const\n{\n XmlNamespaceMap namespaceMap;\n if (mPimpl->mXmlNodePtr->nsDef != nullptr) {\n auto next = mPimpl->mXmlNodePtr->nsDef;\n while (next != nullptr) {\n std::string prefix;\n if (next->prefix != nullptr) {\n prefix = std::string(reinterpret_cast(next->prefix));\n }\n std::string href;\n if (next->href != nullptr) {\n href = std::string(reinterpret_cast(next->href));\n }\n namespaceMap[prefix] = href;\n next = next->next;\n }\n }\n return namespaceMap;\n}\n\nbool XmlNode::isElement(const char *name, const char *ns) const\n{\n bool found = false;\n if ((mPimpl->mXmlNodePtr->type == XML_ELEMENT_NODE)\n && (xmlStrcmp(reinterpret_cast(namespaceUri().c_str()), reinterpret_cast(ns)) == 0)\n && ((name == nullptr) || (xmlStrcmp(mPimpl->mXmlNodePtr->name, reinterpret_cast(name)) == 0))) {\n found = true;\n }\n return found;\n}\n\nbool XmlNode::isCellmlElement(const char *name) const\n{\n return isElement(name, CELLML_2_0_NS);\n}\n\nbool XmlNode::isMathmlElement(const char *name) const\n{\n return isElement(name, MATHML_NS);\n}\n\nbool XmlNode::isText() const\n{\n return mPimpl->mXmlNodePtr->type == XML_TEXT_NODE;\n}\n\nbool XmlNode::isComment() const\n{\n return mPimpl->mXmlNodePtr->type == XML_COMMENT_NODE;\n}\n\nstd::string XmlNode::name() const\n{\n return reinterpret_cast(mPimpl->mXmlNodePtr->name);\n}\n\nbool XmlNode::hasAttribute(const char *attributeName) const\n{\n bool found = false;\n xmlAttrPtr attribute = xmlHasProp(mPimpl->mXmlNodePtr, reinterpret_cast(attributeName));\n if (attribute != nullptr) {\n found = true;\n }\n return found;\n}\n\nstd::string XmlNode::attribute(const char *attributeName) const\n{\n std::string attributeValueString;\n if (hasAttribute(attributeName)) {\n xmlChar *attributeValue = xmlGetProp(mPimpl->mXmlNodePtr, reinterpret_cast(attributeName));\n attributeValueString = std::string(reinterpret_cast(attributeValue));\n xmlFree(attributeValue);\n }\n return attributeValueString;\n}\n\nXmlAttributePtr XmlNode::firstAttribute() const\n{\n xmlAttrPtr attribute = mPimpl->mXmlNodePtr->properties;\n XmlAttributePtr attributeHandle = nullptr;\n if (attribute != nullptr) {\n attributeHandle = std::make_shared();\n attributeHandle->setXmlAttribute(attribute);\n }\n return attributeHandle;\n}\n\nXmlNodePtr XmlNode::firstChild() const\n{\n xmlNodePtr child = mPimpl->mXmlNodePtr->children;\n XmlNodePtr childHandle = nullptr;\n bool nodeWithContentFound = false;\n while (child != nullptr && !nodeWithContentFound) {\n childHandle = std::make_shared();\n childHandle->setXmlNode(child);\n bool textNode = childHandle->isText();\n if (textNode && !childHandle->convertToStrippedString().empty()) {\n nodeWithContentFound = true;\n } else if (!textNode) {\n nodeWithContentFound = true;\n } else {\n child = child->next;\n }\n }\n return childHandle;\n}\n\nXmlNodePtr XmlNode::next() const\n{\n xmlNodePtr next = mPimpl->mXmlNodePtr->next;\n XmlNodePtr nextHandle = nullptr;\n if (next != nullptr) {\n nextHandle = std::make_shared();\n nextHandle->setXmlNode(next);\n }\n return nextHandle;\n}\n\nXmlNodePtr XmlNode::parent() const\n{\n xmlNodePtr parent = mPimpl->mXmlNodePtr->parent;\n XmlNodePtr parentHandle = nullptr;\n if (parent != nullptr) {\n parentHandle = std::make_shared();\n parentHandle->setXmlNode(parent);\n }\n return parentHandle;\n}\n\nstd::string XmlNode::convertToString(bool format) const\n{\n std::string contentString;\n xmlBufferPtr buffer = xmlBufferCreate();\n if (format) {\n xmlKeepBlanksDefault(0);\n }\n int len = xmlNodeDump(buffer, mPimpl->mXmlNodePtr->doc, mPimpl->mXmlNodePtr, 0, format ? 1 : 0);\n if (len > 0) {\n contentString = std::string(reinterpret_cast(buffer->content));\n }\n xmlBufferFree(buffer);\n return contentString;\n}\n\nstd::string XmlNode::convertToStrippedString() const\n{\n std::string contentString = convertToString();\n contentString.erase(contentString.begin(), find_if_not(contentString.begin(), contentString.end(), [](int c) { return isspace(c); }));\n contentString.erase(find_if_not(contentString.rbegin(), contentString.rend(), [](int c) { return isspace(c); }).base(), contentString.end());\n return contentString;\n}\n\n} \/\/ namespace libcellml\nXmlNode: simplified XmlNode::firstChild().\/*\nCopyright libCellML Contributors\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\n#include \"xmlnode.h\"\n\n#include \n#include \n#include \n#include \n\n#include \"namespaces.h\"\n#include \"xmlattribute.h\"\n\nnamespace libcellml {\n\n\/**\n * @brief The XmlNode::XmlNodeImpl struct.\n *\n * This struct is the private implementation struct for the XmlNode class. Separating\n * the implementation from the definition allows for greater flexibility when\n * distributing the code.\n *\/\nstruct XmlNode::XmlNodeImpl\n{\n xmlNodePtr mXmlNodePtr;\n};\n\nXmlNode::XmlNode()\n : mPimpl(new XmlNodeImpl())\n{\n}\n\nXmlNode::~XmlNode()\n{\n delete mPimpl;\n}\n\nvoid XmlNode::setXmlNode(const xmlNodePtr &node)\n{\n mPimpl->mXmlNodePtr = node;\n}\n\nstd::string XmlNode::namespaceUri() const\n{\n if (mPimpl->mXmlNodePtr->ns == nullptr) {\n return {};\n }\n return reinterpret_cast(mPimpl->mXmlNodePtr->ns->href);\n}\n\nvoid XmlNode::addNamespaceDefinition(const std::string &uri, const std::string &prefix)\n{\n xmlNsPtr nsPtr = xmlNewNs(mPimpl->mXmlNodePtr, reinterpret_cast(uri.c_str()), reinterpret_cast(prefix.c_str()));\n auto last = mPimpl->mXmlNodePtr->nsDef;\n while (last != nullptr) {\n last = last->next;\n }\n last = nsPtr;\n}\n\nvoid clearNamespace(const xmlNodePtr &node, xmlNsPtr ns)\n{\n if (node->ns == ns) {\n node->ns = nullptr;\n }\n xmlAttrPtr attr = node->properties;\n while (attr != nullptr) {\n if (attr->ns == ns) {\n attr->ns = nullptr;\n }\n attr = attr->next;\n }\n if (node->children != nullptr) {\n clearNamespace(node->children, ns);\n }\n if (node->next != nullptr) {\n clearNamespace(node->next, ns);\n }\n}\n\nvoid XmlNode::removeNamespaceDefinition(const std::string &uri)\n{\n xmlNsPtr previous = nullptr;\n xmlNsPtr next = nullptr;\n xmlNsPtr namespaceToRemove = nullptr;\n auto current = mPimpl->mXmlNodePtr->nsDef;\n while (current != nullptr) {\n next = current->next;\n namespaceToRemove = nullptr;\n if (xmlStrcmp(reinterpret_cast(uri.c_str()), reinterpret_cast(current->href)) == 0) {\n namespaceToRemove = current;\n } else {\n previous = current;\n }\n current = current->next;\n if (namespaceToRemove != nullptr) {\n if (previous == nullptr) {\n mPimpl->mXmlNodePtr->nsDef = next;\n } else {\n previous->next = next;\n }\n namespaceToRemove->next = nullptr;\n \/\/ Search subtree of this node and clear uses of the namespace.\n clearNamespace(mPimpl->mXmlNodePtr, namespaceToRemove);\n xmlFreeNs(namespaceToRemove);\n }\n }\n}\n\nbool XmlNode::hasNamespaceDefinition(const std::string &uri)\n{\n if (mPimpl->mXmlNodePtr->nsDef != nullptr) {\n auto next = mPimpl->mXmlNodePtr->nsDef;\n while (next != nullptr) {\n std::string href;\n if (next->href != nullptr) {\n href = std::string(reinterpret_cast(next->href));\n }\n if (href == uri) {\n return true;\n }\n next = next->next;\n }\n }\n return false;\n}\n\nXmlNamespaceMap XmlNode::definedNamespaces() const\n{\n XmlNamespaceMap namespaceMap;\n if (mPimpl->mXmlNodePtr->nsDef != nullptr) {\n auto next = mPimpl->mXmlNodePtr->nsDef;\n while (next != nullptr) {\n std::string prefix;\n if (next->prefix != nullptr) {\n prefix = std::string(reinterpret_cast(next->prefix));\n }\n std::string href;\n if (next->href != nullptr) {\n href = std::string(reinterpret_cast(next->href));\n }\n namespaceMap[prefix] = href;\n next = next->next;\n }\n }\n return namespaceMap;\n}\n\nbool XmlNode::isElement(const char *name, const char *ns) const\n{\n bool found = false;\n if ((mPimpl->mXmlNodePtr->type == XML_ELEMENT_NODE)\n && (xmlStrcmp(reinterpret_cast(namespaceUri().c_str()), reinterpret_cast(ns)) == 0)\n && ((name == nullptr) || (xmlStrcmp(mPimpl->mXmlNodePtr->name, reinterpret_cast(name)) == 0))) {\n found = true;\n }\n return found;\n}\n\nbool XmlNode::isCellmlElement(const char *name) const\n{\n return isElement(name, CELLML_2_0_NS);\n}\n\nbool XmlNode::isMathmlElement(const char *name) const\n{\n return isElement(name, MATHML_NS);\n}\n\nbool XmlNode::isText() const\n{\n return mPimpl->mXmlNodePtr->type == XML_TEXT_NODE;\n}\n\nbool XmlNode::isComment() const\n{\n return mPimpl->mXmlNodePtr->type == XML_COMMENT_NODE;\n}\n\nstd::string XmlNode::name() const\n{\n return reinterpret_cast(mPimpl->mXmlNodePtr->name);\n}\n\nbool XmlNode::hasAttribute(const char *attributeName) const\n{\n bool found = false;\n xmlAttrPtr attribute = xmlHasProp(mPimpl->mXmlNodePtr, reinterpret_cast(attributeName));\n if (attribute != nullptr) {\n found = true;\n }\n return found;\n}\n\nstd::string XmlNode::attribute(const char *attributeName) const\n{\n std::string attributeValueString;\n if (hasAttribute(attributeName)) {\n xmlChar *attributeValue = xmlGetProp(mPimpl->mXmlNodePtr, reinterpret_cast(attributeName));\n attributeValueString = std::string(reinterpret_cast(attributeValue));\n xmlFree(attributeValue);\n }\n return attributeValueString;\n}\n\nXmlAttributePtr XmlNode::firstAttribute() const\n{\n xmlAttrPtr attribute = mPimpl->mXmlNodePtr->properties;\n XmlAttributePtr attributeHandle = nullptr;\n if (attribute != nullptr) {\n attributeHandle = std::make_shared();\n attributeHandle->setXmlAttribute(attribute);\n }\n return attributeHandle;\n}\n\nXmlNodePtr XmlNode::firstChild() const\n{\n xmlNodePtr child = mPimpl->mXmlNodePtr->children;\n XmlNodePtr childHandle = nullptr;\n while (child != nullptr) {\n childHandle = std::make_shared();\n childHandle->setXmlNode(child);\n bool textNode = childHandle->isText();\n if (!textNode || (textNode && !childHandle->convertToStrippedString().empty())) {\n break;\n }\n child = child->next;\n }\n return childHandle;\n}\n\nXmlNodePtr XmlNode::next() const\n{\n xmlNodePtr next = mPimpl->mXmlNodePtr->next;\n XmlNodePtr nextHandle = nullptr;\n if (next != nullptr) {\n nextHandle = std::make_shared();\n nextHandle->setXmlNode(next);\n }\n return nextHandle;\n}\n\nXmlNodePtr XmlNode::parent() const\n{\n xmlNodePtr parent = mPimpl->mXmlNodePtr->parent;\n XmlNodePtr parentHandle = nullptr;\n if (parent != nullptr) {\n parentHandle = std::make_shared();\n parentHandle->setXmlNode(parent);\n }\n return parentHandle;\n}\n\nstd::string XmlNode::convertToString(bool format) const\n{\n std::string contentString;\n xmlBufferPtr buffer = xmlBufferCreate();\n if (format) {\n xmlKeepBlanksDefault(0);\n }\n int len = xmlNodeDump(buffer, mPimpl->mXmlNodePtr->doc, mPimpl->mXmlNodePtr, 0, format ? 1 : 0);\n if (len > 0) {\n contentString = std::string(reinterpret_cast(buffer->content));\n }\n xmlBufferFree(buffer);\n return contentString;\n}\n\nstd::string XmlNode::convertToStrippedString() const\n{\n std::string contentString = convertToString();\n contentString.erase(contentString.begin(), find_if_not(contentString.begin(), contentString.end(), [](int c) { return isspace(c); }));\n contentString.erase(find_if_not(contentString.rbegin(), contentString.rend(), [](int c) { return isspace(c); }).base(), contentString.end());\n return contentString;\n}\n\n} \/\/ namespace libcellml\n<|endoftext|>"} {"text":"#include \"internal.hpp\"\n\nnamespace CaDiCaL {\n\n\/\/ Restarts are scheduled by a variant of the Glucose scheme presented in\n\/\/ our POS'15 paper using exponential moving averages. There is a slow\n\/\/ moving average of the average recent glue level of learned clauses as\n\/\/ well as fast moving average of those glues. If the end of base restart\n\/\/ conflict interval has passed and the fast moving average is above a\n\/\/ certain margin of the slow moving average then we restart.\n\nbool Internal::restarting () {\n if (!opts.restart) return false;\n if (stats.conflicts <= lim.restart) return false;\n if (level < 2) return false;\n if (level < fast_glue_avg) return false;\n double s = slow_glue_avg, f = fast_glue_avg, l = opts.restartmargin * s;\n LOG (\"EMA glue slow %.2f fast %.2f limit %.2f\", s, f, l);\n return l <= f;\n}\n\n\/\/ This is Marijn's reuse trail idea. Instead of always backtracking to the\n\/\/ top we figure out which decisions would be made again anyhow and only\n\/\/ backtrack to the level of the last such decision or if no such decision\n\/\/ exists to the top (in which case we do reuse any level).\n\nint Internal::reuse_trail () {\n if (!opts.reusetrail) return 0;\n long limit = bumped (next_decision_variable ());\n int res = 0;\n while (res < level && bumped (control[res + 1].decision) > limit)\n res++;\n if (res) stats.reused++;\n return res;\n}\n\nvoid Internal::restart () {\n START (restart);\n stats.restarts++;\n LOG (\"restart %ld\", stats.restarts);\n backtrack (reuse_trail ());\n lim.restart = stats.conflicts + opts.restartint;\n report ('R', 2);\n STOP (restart);\n}\n\n};\n\nrephase coupled with long restart intervals for one third of the time#include \"internal.hpp\"\n\nnamespace CaDiCaL {\n\n\/\/ Restarts are scheduled by a variant of the Glucose scheme presented in\n\/\/ our POS'15 paper using exponential moving averages. There is a slow\n\/\/ moving average of the average recent glue level of learned clauses as\n\/\/ well as fast moving average of those glues. If the end of base restart\n\/\/ conflict interval has passed and the fast moving average is above a\n\/\/ certain margin of the slow moving average then we restart.\n\nbool Internal::restarting () {\n if (!opts.restart) return false;\n if (stats.conflicts <= lim.restart) return false;\n if (level < 2) return false;\n if (level < fast_glue_avg) return false;\n double s = slow_glue_avg, f = fast_glue_avg, l = opts.restartmargin * s;\n LOG (\"EMA glue slow %.2f fast %.2f limit %.2f\", s, f, l);\n return l <= f;\n}\n\n\/\/ This is Marijn's reuse trail idea. Instead of always backtracking to the\n\/\/ top we figure out which decisions would be made again anyhow and only\n\/\/ backtrack to the level of the last such decision or if no such decision\n\/\/ exists to the top (in which case we do reuse any level).\n\nint Internal::reuse_trail () {\n if (!opts.reusetrail) return 0;\n long limit = bumped (next_decision_variable ());\n int res = 0;\n while (res < level && bumped (control[res + 1].decision) > limit)\n res++;\n if (res) stats.reused++;\n return res;\n}\n\nvoid Internal::restart () {\n START (restart);\n stats.restarts++;\n LOG (\"restart %ld\", stats.restarts);\n backtrack (reuse_trail ());\n long delta = opts.restartint;\n if (stats.rephased % 3 == 2) delta *= 20;\n lim.restart = stats.conflicts + delta;\n report ('R', 2);\n STOP (restart);\n}\n\n};\n\n<|endoftext|>"} {"text":"#include \"rust_internal.h\"\n\nstruct\ncommand_line_args : public dom_owned\n{\n rust_dom *dom;\n int argc;\n char **argv;\n\n \/\/ vec[str] passed to rust_task::start.\n rust_vec *args;\n\n command_line_args(rust_dom *dom,\n int sys_argc,\n char **sys_argv)\n : dom(dom),\n argc(sys_argc),\n argv(sys_argv),\n args(NULL)\n {\n#if defined(__WIN32__)\n LPCWSTR cmdline = GetCommandLineW();\n LPWSTR *wargv = CommandLineToArgvW(cmdline, &argc);\n dom->win32_require(\"CommandLineToArgvW\", wargv != NULL);\n argv = (char **) dom->malloc(sizeof(char*) * argc);\n for (int i = 0; i < argc; ++i) {\n int n_chars = WideCharToMultiByte(CP_UTF8, 0, wargv[i], -1,\n NULL, 0, NULL, NULL);\n dom->win32_require(\"WideCharToMultiByte(0)\", n_chars != 0);\n argv[i] = (char *) dom->malloc(n_chars);\n n_chars = WideCharToMultiByte(CP_UTF8, 0, wargv[i], -1,\n argv[i], n_chars, NULL, NULL);\n dom->win32_require(\"WideCharToMultiByte(1)\", n_chars != 0);\n }\n LocalFree(wargv);\n#endif\n size_t vec_fill = sizeof(rust_str *) * argc;\n size_t vec_alloc = next_power_of_two(sizeof(rust_vec) + vec_fill);\n void *mem = dom->malloc(vec_alloc);\n args = new (mem) rust_vec(dom, vec_alloc, 0, NULL);\n rust_str **strs = (rust_str**) &args->data[0];\n for (int i = 0; i < argc; ++i) {\n size_t str_fill = strlen(argv[i]) + 1;\n size_t str_alloc = next_power_of_two(sizeof(rust_str) + str_fill);\n mem = dom->malloc(str_alloc);\n strs[i] = new (mem) rust_str(dom, str_alloc, str_fill,\n (uint8_t const *)argv[i]);\n }\n args->fill = vec_fill;\n \/\/ If the caller has a declared args array, they may drop; but\n \/\/ we don't know if they have such an array. So we pin the args\n \/\/ array here to ensure it survives to program-shutdown.\n args->ref();\n }\n\n ~command_line_args() {\n if (args) {\n \/\/ Drop the args we've had pinned here.\n rust_str **strs = (rust_str**) &args->data[0];\n for (int i = 0; i < argc; ++i)\n dom->free(strs[i]);\n dom->free(args);\n }\n\n#ifdef __WIN32__\n for (int i = 0; i < argc; ++i) {\n dom->free(argv[i]);\n }\n dom->free(argv);\n#endif\n }\n};\n\n\/**\n * Main entry point into the Rust runtime. Here we create a Rust service,\n * initialize the kernel, create the root domain and run it.\n *\/\n\nextern \"C\" CDECL int\nrust_start(uintptr_t main_fn, rust_crate const *crate, int argc,\n char **argv, void* crate_map) {\n\n \/\/ Only when we're on rustc is the last argument passed\n if (!crate->get_image_base())\n update_log_settings(crate_map, getenv(\"RUST_LOG\"));\n rust_srv *srv = new rust_srv();\n rust_kernel *kernel = new rust_kernel(srv);\n kernel->start();\n rust_handle *handle = kernel->create_domain(crate, \"main\");\n rust_dom *dom = handle->referent();\n command_line_args *args = new (dom) command_line_args(dom, argc, argv);\n\n DLOG(dom, rust_log::DOM, \"startup: %d args in 0x%\" PRIxPTR,\n args->argc, (uintptr_t)args->args);\n for (int i = 0; i < args->argc; i++) {\n DLOG(dom, rust_log::DOM,\n \"startup: arg[%d] = '%s'\", i, args->argv[i]);\n }\n\n if (dom->_log.is_tracing(rust_log::DWARF)) {\n rust_crate_reader create_reader(dom, crate);\n }\n\n uintptr_t main_args[4] = {0, 0, 0, (uintptr_t)args->args};\n dom->root_task->start(crate->get_exit_task_glue(),\n crate->abi_tag, main_fn,\n (uintptr_t)&main_args, sizeof(main_args));\n\n int ret = dom->start_main_loop();\n delete args;\n kernel->destroy_domain(dom);\n kernel->join_all_domains();\n delete kernel;\n delete srv;\n\n#if !defined(__WIN32__)\n \/\/ Don't take down the process if the main thread exits without an\n \/\/ error.\n if (!ret)\n pthread_exit(NULL);\n#endif\n return ret;\n}\n\n\/\/\n\/\/ Local Variables:\n\/\/ mode: C++\n\/\/ fill-column: 78;\n\/\/ indent-tabs-mode: nil\n\/\/ c-basic-offset: 4\n\/\/ buffer-file-coding-system: utf-8-unix\n\/\/ compile-command: \"make -k -C .. 2>&1 | sed -e 's\/\\\\\/x\\\\\/\/x:\\\\\/\/g'\";\n\/\/ End:\n\/\/\nTemporarily turn off logging initialization#include \"rust_internal.h\"\n\nstruct\ncommand_line_args : public dom_owned\n{\n rust_dom *dom;\n int argc;\n char **argv;\n\n \/\/ vec[str] passed to rust_task::start.\n rust_vec *args;\n\n command_line_args(rust_dom *dom,\n int sys_argc,\n char **sys_argv)\n : dom(dom),\n argc(sys_argc),\n argv(sys_argv),\n args(NULL)\n {\n#if defined(__WIN32__)\n LPCWSTR cmdline = GetCommandLineW();\n LPWSTR *wargv = CommandLineToArgvW(cmdline, &argc);\n dom->win32_require(\"CommandLineToArgvW\", wargv != NULL);\n argv = (char **) dom->malloc(sizeof(char*) * argc);\n for (int i = 0; i < argc; ++i) {\n int n_chars = WideCharToMultiByte(CP_UTF8, 0, wargv[i], -1,\n NULL, 0, NULL, NULL);\n dom->win32_require(\"WideCharToMultiByte(0)\", n_chars != 0);\n argv[i] = (char *) dom->malloc(n_chars);\n n_chars = WideCharToMultiByte(CP_UTF8, 0, wargv[i], -1,\n argv[i], n_chars, NULL, NULL);\n dom->win32_require(\"WideCharToMultiByte(1)\", n_chars != 0);\n }\n LocalFree(wargv);\n#endif\n size_t vec_fill = sizeof(rust_str *) * argc;\n size_t vec_alloc = next_power_of_two(sizeof(rust_vec) + vec_fill);\n void *mem = dom->malloc(vec_alloc);\n args = new (mem) rust_vec(dom, vec_alloc, 0, NULL);\n rust_str **strs = (rust_str**) &args->data[0];\n for (int i = 0; i < argc; ++i) {\n size_t str_fill = strlen(argv[i]) + 1;\n size_t str_alloc = next_power_of_two(sizeof(rust_str) + str_fill);\n mem = dom->malloc(str_alloc);\n strs[i] = new (mem) rust_str(dom, str_alloc, str_fill,\n (uint8_t const *)argv[i]);\n }\n args->fill = vec_fill;\n \/\/ If the caller has a declared args array, they may drop; but\n \/\/ we don't know if they have such an array. So we pin the args\n \/\/ array here to ensure it survives to program-shutdown.\n args->ref();\n }\n\n ~command_line_args() {\n if (args) {\n \/\/ Drop the args we've had pinned here.\n rust_str **strs = (rust_str**) &args->data[0];\n for (int i = 0; i < argc; ++i)\n dom->free(strs[i]);\n dom->free(args);\n }\n\n#ifdef __WIN32__\n for (int i = 0; i < argc; ++i) {\n dom->free(argv[i]);\n }\n dom->free(argv);\n#endif\n }\n};\n\n\/**\n * Main entry point into the Rust runtime. Here we create a Rust service,\n * initialize the kernel, create the root domain and run it.\n *\/\n\nextern \"C\" CDECL int\nrust_start(uintptr_t main_fn, rust_crate const *crate, int argc,\n char **argv, void* crate_map) {\n\n \/\/ FIXME commented out until I figure out how to detect rustboot in a sane\n \/\/ way\n \/* if (NOT_USING_RUSTBOOT)\n update_log_settings(crate_map, getenv(\"RUST_LOG\"));*\/\n rust_srv *srv = new rust_srv();\n rust_kernel *kernel = new rust_kernel(srv);\n kernel->start();\n rust_handle *handle = kernel->create_domain(crate, \"main\");\n rust_dom *dom = handle->referent();\n command_line_args *args = new (dom) command_line_args(dom, argc, argv);\n\n DLOG(dom, rust_log::DOM, \"startup: %d args in 0x%\" PRIxPTR,\n args->argc, (uintptr_t)args->args);\n for (int i = 0; i < args->argc; i++) {\n DLOG(dom, rust_log::DOM,\n \"startup: arg[%d] = '%s'\", i, args->argv[i]);\n }\n\n if (dom->_log.is_tracing(rust_log::DWARF)) {\n rust_crate_reader create_reader(dom, crate);\n }\n\n uintptr_t main_args[4] = {0, 0, 0, (uintptr_t)args->args};\n dom->root_task->start(crate->get_exit_task_glue(),\n crate->abi_tag, main_fn,\n (uintptr_t)&main_args, sizeof(main_args));\n\n int ret = dom->start_main_loop();\n delete args;\n kernel->destroy_domain(dom);\n kernel->join_all_domains();\n delete kernel;\n delete srv;\n\n#if !defined(__WIN32__)\n \/\/ Don't take down the process if the main thread exits without an\n \/\/ error.\n if (!ret)\n pthread_exit(NULL);\n#endif\n return ret;\n}\n\n\/\/\n\/\/ Local Variables:\n\/\/ mode: C++\n\/\/ fill-column: 78;\n\/\/ indent-tabs-mode: nil\n\/\/ c-basic-offset: 4\n\/\/ buffer-file-coding-system: utf-8-unix\n\/\/ compile-command: \"make -k -C .. 2>&1 | sed -e 's\/\\\\\/x\\\\\/\/x:\\\\\/\/g'\";\n\/\/ End:\n\/\/\n<|endoftext|>"} {"text":"\/\/ Copyright 2008 Paul Hodge\n\n#include \"branch.h\"\n#include \"debug.h\"\n#include \"function.h\"\n#include \"introspection.h\"\n#include \"runtime.h\"\n#include \"syntax.h\"\n#include \"type.h\"\n#include \"values.h\"\n\nnamespace circa {\n\nTerm* create_term(Branch* branch, Term* function, RefList const& inputs)\n{\n assert_good_pointer(function);\n\n if (!is_function(function))\n throw std::runtime_error(\"in create_term, 2nd arg to create_term must be a function\");\n\n Term* term = new Term();\n\n if (branch != NULL)\n branch->append(term);\n\n term->function = function;\n term->needsUpdate = true;\n\n Function& functionData = as_function(function);\n\n Term* outputType = functionData.outputType;\n\n if (outputType == NULL)\n throw std::runtime_error(\"outputType is NULL\");\n \n if (!is_type(outputType))\n throw std::runtime_error(outputType->name + \" is not a type\");\n\n change_type(term, outputType);\n\n \/\/ Create state (if a state type is defined)\n Term* stateType = functionData.stateType;\n if (stateType != NULL) {\n if (!is_type(stateType))\n throw std::runtime_error(stateType->name + \" is not a type\");\n term->state = create_value(NULL, stateType);\n }\n\n for (unsigned int i=0; i < inputs.count(); i++)\n set_input(term, i, inputs[i]);\n\n return term;\n}\n\nbool check_valid_type(Function &func, int index, Term* term)\n{\n Term* expectedType = func.inputTypes[index];\n\n if (expectedType == ANY_TYPE)\n return true;\n\n return term->type == expectedType;\n}\n\nvoid evaluate_term(Term* term)\n{\n if (term == NULL)\n throw std::runtime_error(\"term is NULL\");\n\n term->clearError();\n\n \/\/ Check function\n if (term->function == NULL) {\n error_occured(term, \"Function is NULL\");\n return;\n }\n\n if (!is_function(term->function)) {\n error_occured(term, \"term->function is not a function\");\n return;\n }\n\n Function& func = as_function(term->function);\n\n if (func.evaluate == NULL)\n return;\n\n \/\/ Check each input. Make sure:\n \/\/ 1) it is not null\n \/\/ 2) it is up-to-date\n \/\/ 3) it has a non-null value\n \/\/ 4) it has no errors\n \/\/ 5) it has the correct type\n for (unsigned int inputIndex=0; inputIndex < term->inputs.count(); inputIndex++)\n {\n int effectiveIndex = inputIndex;\n if (func.variableArgs)\n effectiveIndex = 0;\n\n Term* input = term->inputs[inputIndex];\n Function::InputProperties inputProps = func.getInputProperties(effectiveIndex);\n \n if (input == NULL && !inputProps.meta) {\n std::stringstream message;\n message << \"Input \" << inputIndex << \" is NULL\";\n error_occured(term, message.str());\n return;\n }\n\n if (!is_value_alloced(input) && !inputProps.meta) {\n std::stringstream message;\n message << \"Input \" << inputIndex << \" has NULL value\";\n error_occured(term, message.str());\n return;\n }\n\n if (input->hasError() && !inputProps.meta) {\n std::stringstream message;\n message << \"Input \" << inputIndex << \" has an error\";\n error_occured(term, message.str());\n return;\n }\n \n \/\/ Check type\n if (!check_valid_type(func, effectiveIndex, input)) {\n std::stringstream message;\n message << \"Runtime type error: input \" << inputIndex << \" has type \"\n << as_type(input->type).name;\n error_occured(term, message.str());\n return;\n }\n\n \/\/ Possibly evaluate this input if needed\n if (!inputProps.meta && input->needsUpdate) {\n assert(term != input); \/\/ prevent infinite recursion\n evaluate_term(input);\n }\n }\n \n \/\/ Make sure we have an allocated value. Allocate one if necessary\n if (!is_value_alloced(term))\n alloc_value(term);\n\n \/\/ Execute the function\n try {\n func.evaluate(term);\n term->needsUpdate = false;\n }\n catch (std::exception const& err)\n {\n error_occured(term, err.what());\n }\n}\n\nvoid evaluate_branch(Branch& branch, Term* errorListener)\n{\n int count = branch.numTerms();\n for (int index=0; index < count; index++) {\n\t\tTerm* term = branch.get(index);\n evaluate_term(term);\n\n if (term->hasError()) {\n std::stringstream out;\n out << \"On term \" << term_to_raw_string(term) << \"\\n\" << term->getErrorMessage();\n error_occured(errorListener, out.str());\n return;\n }\n }\n\n \/\/ TODO: Instead of calling this function, stateful terms should have an \n \/\/ 'assign' function generated at the bottom of the branch, which puts the\n \/\/ result back into the stateful-value term.\n persist_results_for_stateful_terms(branch);\n}\n\nvoid error_occured(Term* errorTerm, std::string const& message)\n{\n if (errorTerm == NULL)\n throw std::runtime_error(message);\n\n errorTerm->pushError(message);\n}\n\nvoid set_input(Term* term, int index, Term* input)\n{\n assert_good_pointer(term);\n\n \/\/ Term* previousInput = term->inputs.get(index);\n\n term->inputs.setAt(index, input);\n\n \/\/ Update syntax hints\n if (input == NULL)\n term->syntaxHints.getInputSyntax(index).unknownStyle();\n else if (input->name == \"\")\n term->syntaxHints.getInputSyntax(index).bySource();\n else\n term->syntaxHints.getInputSyntax(index).byName(input->name);\n}\n\nTerm* create_duplicate(Branch* branch, Term* source, bool copyBranches)\n{\n Term* term = create_term(branch, source->function, source->inputs);\n\n term->name = source->name;\n\n if (copyBranches)\n copy_value(source, term);\n else\n copy_value_but_dont_copy_inner_branch(source,term);\n\n duplicate_branch(source->properties, term->properties);\n term->syntaxHints = source->syntaxHints;\n\n if (source->state != NULL) {\n if (copyBranches && !has_inner_branch(source))\n copy_value(source->state, term->state);\n }\n \n return term;\n}\n\nTerm* possibly_coerce_term(Branch* branch, Term* original, Term* expectedType)\n{\n \/\/ (In the future, we will have more complicated coersion rules)\n \n \/\/ Ignore NULL\n if (original == NULL)\n return original;\n\n \/\/ Coerce from int to float\n if (original->type == INT_TYPE && expectedType == FLOAT_TYPE) {\n return apply(branch, INT_TO_FLOAT_FUNC, RefList(original));\n }\n\n return original;\n}\n\nTerm* apply(Branch* branch, Term* function, RefList const& _inputs, std::string const& name)\n{\n \/\/ Make a local copy of _inputs\n RefList inputs = _inputs;\n\n \/\/ Evaluate this function if needed\n if (function->needsUpdate)\n evaluate_term(function);\n\n \/\/ Check if 'function' is actually a type\n if (is_type(function))\n {\n if (inputs.count() != 0)\n throw std::runtime_error(\"Inputs in constructor function is not yet supported\");\n\n function = get_value_function(function);\n }\n\n \/\/ If 'function' is not really a function, see if we can treat it like a function\n else if (!is_function(function)) {\n\n Type& type = as_type(function->type);\n\n if (!type.memberFunctions.contains(\"\"))\n throw std::runtime_error(std::string(\"Term \") + function->toString()\n + \" is not a type, and has no default function\");\n\n RefList memberFunctionInputs;\n memberFunctionInputs.append(function);\n memberFunctionInputs.appendAll(inputs);\n\n function = type.memberFunctions[\"\"];\n inputs = memberFunctionInputs;\n }\n\n Function& functionData = as_function(function);\n\n \/\/ Possibly coerce inputs\n for (unsigned int i=0; i < inputs.count(); i++) {\n inputs.setAt(i, possibly_coerce_term(branch, inputs[i],\n functionData.inputType(i)));\n }\n\n \/\/ Create the term\n Term* result = create_term(branch, function, inputs);\n\n if (name != \"\" && branch != NULL)\n branch->bindName(result, name);\n\n return result;\n}\n\nTerm* apply(Branch* branch,\n std::string const& functionName, \n RefList const& inputs)\n{\n Term* function = find_named(branch,functionName);\n if (function == NULL)\n throw std::runtime_error(std::string(\"function not found: \")+functionName);\n\n return apply(branch, function, inputs);\n}\n\nTerm* eval_function(Branch& branch, Term* function, RefList const& inputs)\n{\n Term* result = apply(&branch, function, inputs);\n evaluate_term(result);\n return result;\n}\n\nTerm* eval_function(Branch& branch, std::string const& functionName,\n RefList const &inputs)\n{\n Term* function = find_named(&branch,functionName);\n if (function == NULL)\n throw std::runtime_error(std::string(\"function not found: \")+functionName);\n\n return eval_function(branch, function, inputs);\n}\n\n} \/\/ namespace circa\nCosmetic changes\/\/ Copyright 2008 Paul Hodge\n\n#include \"branch.h\"\n#include \"debug.h\"\n#include \"function.h\"\n#include \"introspection.h\"\n#include \"runtime.h\"\n#include \"syntax.h\"\n#include \"type.h\"\n#include \"values.h\"\n\nnamespace circa {\n\nTerm* create_term(Branch* branch, Term* function, RefList const& inputs)\n{\n assert_good_pointer(function);\n\n if (!is_function(function))\n throw std::runtime_error(\"in create_term, 2nd arg to create_term must be a function\");\n\n Term* term = new Term();\n\n if (branch != NULL)\n branch->append(term);\n\n term->function = function;\n term->needsUpdate = true;\n\n Function& functionData = as_function(function);\n\n Term* outputType = functionData.outputType;\n\n if (outputType == NULL)\n throw std::runtime_error(\"outputType is NULL\");\n \n if (!is_type(outputType))\n throw std::runtime_error(outputType->name + \" is not a type\");\n\n change_type(term, outputType);\n\n \/\/ Create state (if a state type is defined)\n Term* stateType = functionData.stateType;\n if (stateType != NULL) {\n if (!is_type(stateType))\n throw std::runtime_error(stateType->name + \" is not a type\");\n term->state = create_value(NULL, stateType);\n }\n\n for (unsigned int i=0; i < inputs.count(); i++)\n set_input(term, i, inputs[i]);\n\n return term;\n}\n\nbool check_valid_type(Function &func, int index, Term* term)\n{\n Term* expectedType = func.inputTypes[index];\n\n if (expectedType == ANY_TYPE)\n return true;\n\n return term->type == expectedType;\n}\n\nvoid evaluate_term(Term* term)\n{\n if (term == NULL)\n throw std::runtime_error(\"term is NULL\");\n\n term->clearError();\n\n \/\/ Check function\n if (term->function == NULL) {\n error_occured(term, \"Function is NULL\");\n return;\n }\n\n if (!is_function(term->function)) {\n error_occured(term, \"term->function is not a function\");\n return;\n }\n\n Function& func = as_function(term->function);\n\n if (func.evaluate == NULL)\n return;\n\n \/\/ Check each input. Make sure:\n \/\/ 1) it is not null\n \/\/ 2) it is up-to-date\n \/\/ 3) it has a non-null value\n \/\/ 4) it has no errors\n \/\/ 5) it has the correct type\n for (unsigned int inputIndex=0; inputIndex < term->inputs.count(); inputIndex++)\n {\n int effectiveIndex = inputIndex;\n if (func.variableArgs)\n effectiveIndex = 0;\n\n Term* input = term->inputs[inputIndex];\n Function::InputProperties inputProps = func.getInputProperties(effectiveIndex);\n \n if (input == NULL && !inputProps.meta) {\n std::stringstream message;\n message << \"Input \" << inputIndex << \" is NULL\";\n error_occured(term, message.str());\n return;\n }\n\n if (!is_value_alloced(input) && !inputProps.meta) {\n std::stringstream message;\n message << \"Input \" << inputIndex << \" has NULL value\";\n error_occured(term, message.str());\n return;\n }\n\n if (input->hasError() && !inputProps.meta) {\n std::stringstream message;\n message << \"Input \" << inputIndex << \" has an error\";\n error_occured(term, message.str());\n return;\n }\n \n \/\/ Check type\n if (!check_valid_type(func, effectiveIndex, input)) {\n std::stringstream message;\n message << \"Runtime type error: input \" << inputIndex << \" has type \"\n << as_type(input->type).name;\n error_occured(term, message.str());\n return;\n }\n\n \/\/ Possibly evaluate this input if needed\n if (!inputProps.meta && input->needsUpdate) {\n assert(term != input); \/\/ prevent infinite recursion\n evaluate_term(input);\n }\n }\n \n \/\/ Make sure we have an allocated value. Allocate one if necessary\n if (!is_value_alloced(term))\n alloc_value(term);\n\n \/\/ Execute the function\n try {\n func.evaluate(term);\n term->needsUpdate = false;\n }\n catch (std::exception const& err)\n {\n error_occured(term, err.what());\n }\n}\n\nvoid evaluate_branch(Branch& branch, Term* errorListener)\n{\n int count = branch.numTerms();\n for (int index=0; index < count; index++) {\n\t\tTerm* term = branch.get(index);\n evaluate_term(term);\n\n if (term->hasError()) {\n std::stringstream out;\n out << \"On term \" << term_to_raw_string(term) << \"\\n\" << term->getErrorMessage();\n error_occured(errorListener, out.str());\n return;\n }\n }\n\n \/\/ TODO: Instead of calling this function, stateful terms should have an \n \/\/ 'assign' function generated at the bottom of the branch, which puts the\n \/\/ result back into the stateful-value term.\n persist_results_for_stateful_terms(branch);\n}\n\nvoid error_occured(Term* errorTerm, std::string const& message)\n{\n if (errorTerm == NULL)\n throw std::runtime_error(message);\n\n errorTerm->pushError(message);\n}\n\nvoid set_input(Term* term, int index, Term* input)\n{\n assert_good_pointer(term);\n\n term->inputs.setAt(index, input);\n\n \/\/ Update syntax hints\n if (input == NULL)\n term->syntaxHints.getInputSyntax(index).unknownStyle();\n else if (input->name == \"\")\n term->syntaxHints.getInputSyntax(index).bySource();\n else\n term->syntaxHints.getInputSyntax(index).byName(input->name);\n}\n\nTerm* create_duplicate(Branch* branch, Term* source, bool copyBranches)\n{\n Term* term = create_term(branch, source->function, source->inputs);\n\n term->name = source->name;\n\n if (copyBranches)\n copy_value(source, term);\n else\n copy_value_but_dont_copy_inner_branch(source,term);\n\n duplicate_branch(source->properties, term->properties);\n term->syntaxHints = source->syntaxHints;\n\n if (source->state != NULL) {\n if (copyBranches && !has_inner_branch(source))\n copy_value(source->state, term->state);\n }\n \n return term;\n}\n\nTerm* possibly_coerce_term(Branch* branch, Term* original, Term* expectedType)\n{\n \/\/ (In the future, we will have more complicated coersion rules)\n \n \/\/ Ignore NULL\n if (original == NULL)\n return original;\n\n \/\/ Coerce from int to float\n if (original->type == INT_TYPE && expectedType == FLOAT_TYPE) {\n return apply(branch, INT_TO_FLOAT_FUNC, RefList(original));\n }\n\n return original;\n}\n\nTerm* apply(Branch* branch, Term* function, RefList const& _inputs, std::string const& name)\n{\n \/\/ Make a local copy of _inputs\n RefList inputs = _inputs;\n\n \/\/ Evaluate this function if needed\n if (function->needsUpdate)\n evaluate_term(function);\n\n \/\/ Check if 'function' is actually a type\n if (is_type(function))\n {\n if (inputs.count() != 0)\n throw std::runtime_error(\"Inputs in constructor function is not yet supported\");\n\n function = get_value_function(function);\n }\n\n \/\/ If 'function' is not really a function, see if we can treat it like a function\n else if (!is_function(function)) {\n\n Type& type = as_type(function->type);\n\n if (!type.memberFunctions.contains(\"\"))\n throw std::runtime_error(std::string(\"Term \") + function->toString()\n + \" is not a type, and has no default function\");\n\n RefList memberFunctionInputs;\n memberFunctionInputs.append(function);\n memberFunctionInputs.appendAll(inputs);\n\n function = type.memberFunctions[\"\"];\n inputs = memberFunctionInputs;\n }\n\n Function& functionData = as_function(function);\n\n \/\/ Possibly coerce inputs\n for (unsigned int i=0; i < inputs.count(); i++) {\n inputs.setAt(i, possibly_coerce_term(branch, inputs[i],\n functionData.inputType(i)));\n }\n\n \/\/ Create the term\n Term* result = create_term(branch, function, inputs);\n\n \/\/ Bind name, if given\n if (name != \"\" && branch != NULL)\n branch->bindName(result, name);\n\n return result;\n}\n\nTerm* apply(Branch* branch, std::string const& functionName, RefList const& inputs)\n{\n Term* function = find_named(branch,functionName);\n if (function == NULL)\n throw std::runtime_error(\"function not found: \"+functionName);\n\n return apply(branch, function, inputs);\n}\n\nTerm* eval_function(Branch& branch, Term* function, RefList const& inputs)\n{\n Term* result = apply(&branch, function, inputs);\n evaluate_term(result);\n return result;\n}\n\nTerm* eval_function(Branch& branch, std::string const& functionName,\n RefList const &inputs)\n{\n Term* function = find_named(&branch,functionName);\n if (function == NULL)\n throw std::runtime_error(\"function not found: \"+functionName);\n\n return eval_function(branch, function, inputs);\n}\n\n} \/\/ namespace circa\n<|endoftext|>"} {"text":"#include \n#include \n#include \n\nusing namespace Halide;\n\n\/\/ A version of pow that tracks usage so we can check how many times it was called.\n#ifdef _MSC_VER\n#define DLLEXPORT __declspec(dllexport)\n#else\n#define DLLEXPORT\n#endif\n\nint call_count = 0;\nextern \"C\" DLLEXPORT float my_powf(float x, float y) {\n call_count++;\n \/\/ We have to read from call_count, or for some reason apple clang removes it entirely.\n assert(call_count != -1);\n return powf(x, y);\n}\nHalideExtern_2(float, my_powf, float, float);\n\nint main(int argc, char **argv) {\n \/\/ Brighten some tiles of an image, where that region is given by\n \/\/ a lower-res bitmap.\n\n ImageParam bitmap(Bool(), 2);\n ImageParam image(Float(32), 2);\n const int tile_size = 16;\n\n Var x(\"x\"), y(\"y\"), xi(\"xi\"), yi(\"yi\"), t(\"t\");\n\n \/\/ Brighten the image\n Func brighter(\"brighter\");\n brighter(x, y) = my_powf(image(x, y), 0.8f);\n\n \/\/ Select either the brighter or the input depending on the bitmap\n Func output(\"output\");\n output(x, y) = select(bitmap(x\/tile_size, y\/tile_size), brighter(x, y), image(x, y));\n\n \/\/ Compute the output in tiles of the appropriate size\n output.tile(x, y, xi, yi, tile_size, tile_size);\n\n \/\/ Vectorize within tiles. We would also parallelize across tiles,\n \/\/ but that introduces a race condition in the call_count.\n output.vectorize(xi, 4).fuse(x, y, t);\n\n \/\/ Compute brighter per output tile\n brighter.compute_at(output, t);\n\n \/\/ Assert that the output is a whole number of tiles. Otherwise\n \/\/ the tiles in the schedule don't match up to the tiles in the\n \/\/ algorithm, and you can't safely skip any work.\n output.bound(x, 0, (image.extent(0)\/tile_size)*tile_size);\n output.bound(y, 0, (image.extent(1)\/tile_size)*tile_size);\n output.compile_jit();\n\n Image bitmap_buf(10, 10);\n bitmap_buf(5, 5) = 1;\n bitmap.set(bitmap_buf);\n\n Image image_buf = lambda(x, y, (sin(x+y)+1)\/2).realize(10 * tile_size, 10 * tile_size);\n image.set(image_buf);\n\n call_count = 0;\n Image result = output.realize(10 * tile_size, 10 * tile_size);\n\n \/\/ Force a reload of call_count\n my_powf(1, 1);\n call_count--;\n\n \/\/ Check the right number of calls to powf occurred\n if (call_count != tile_size*tile_size) {\n printf(\"call_count = %d instead of %d\\n\", call_count, tile_size * tile_size);\n \/\/return -1;\n }\n\n \/\/ Check the output is correct\n for (int y = 0; y < result.height(); y++) {\n for (int x = 0; x < result.width(); x++) {\n bool active = bitmap_buf(x\/tile_size, y\/tile_size);\n float correct = active ? my_powf(image_buf(x, y), 0.8f) : image_buf(x, y);\n if (fabs(correct - result(x, y)) > 0.001f) {\n printf(\"result(%d, %d) = %f instead of %f\\n\",\n x, y, result(x, y), correct);\n return -1;\n }\n }\n }\n\n printf(\"Success!\\n\");\n return 0;\n}\nChange process_some_tiles to actually work.#include \n#include \n#include \n\nusing namespace Halide;\n\n\/\/ A version of pow that tracks usage so we can check how many times it was called.\n#ifdef _MSC_VER\n#define DLLEXPORT __declspec(dllexport)\n#else\n#define DLLEXPORT\n#endif\n\nint call_count = 0;\nextern \"C\" DLLEXPORT float my_powf(float x, float y) {\n call_count++;\n \/\/ We have to read from call_count, or for some reason apple clang removes it entirely.\n assert(call_count != -1);\n return powf(x, y);\n}\nHalideExtern_2(float, my_powf, float, float);\n\nint main(int argc, char **argv) {\n \/\/ Brighten some tiles of an image, where that region is given by\n \/\/ a lower-res bitmap.\n\n ImageParam bitmap(Bool(), 2);\n ImageParam image(Float(32), 2);\n const int tile_size = 16;\n\n Var x(\"x\"), y(\"y\"), xi(\"xi\"), yi(\"yi\"), t(\"t\");\n\n \/\/ Break the input into tiles.\n Func tiled(\"tiled\");\n tiled(xi, yi, x, y) = image(x*tile_size + xi, y*tile_size + yi);\n\n \/\/ Brighten each tile of the image\n Func brighter(\"brighter\");\n brighter(xi, yi, x, y) = my_powf(tiled(xi, yi, x, y), 0.8f);\n\n \/\/ Select either the brighter tile or the input tile depending on the bitmap\n Func output_tiles(\"output_tiles\");\n output_tiles(xi, yi, x, y) = select(bitmap(x, y), brighter(xi, yi, x, y), tiled(xi, yi, x, y));\n\n \/\/ Collapse back down into 2D\n Func output(\"output\");\n output(x, y) = output_tiles(x % tile_size, y % tile_size,\n x \/ tile_size, y \/ tile_size);\n\n \/\/ Compute the output in tiles of the appropriate size to simplify\n \/\/ the mod and div above. Not important for the stage skipping behavior.\n output.bound(x, 0, (image.extent(0)\/tile_size)*tile_size)\n .bound(y, 0, (image.extent(1)\/tile_size)*tile_size)\n .tile(x, y, xi, yi, tile_size, tile_size);\n\n \/\/ Vectorize within tiles. We would also parallelize across tiles,\n \/\/ but that introduces a race condition in the call_count.\n output.vectorize(xi, 4);\n\n \/\/ Compute brighter per tile of output_tiles. This puts it inside\n \/\/ the loop over x and y, which makes the condition in the select\n \/\/ a constant. This is the important part of the schedule!\n brighter.compute_at(output_tiles, x);\n\n \/\/ Schedule output_tiles per output tile. This choice is unimportant.\n output_tiles.compute_at(output, x);\n\n output.compile_jit();\n\n Image bitmap_buf(10, 10);\n bitmap_buf(5, 5) = 1;\n bitmap.set(bitmap_buf);\n\n Image image_buf = lambda(x, y, (sin(x+y)+1)\/2).realize(10 * tile_size, 10 * tile_size);\n image.set(image_buf);\n\n call_count = 0;\n Image result = output.realize(10 * tile_size, 10 * tile_size);\n\n \/\/ Force a reload of call_count\n my_powf(1, 1);\n call_count--;\n\n \/\/ Check the right number of calls to powf occurred\n if (call_count != tile_size*tile_size) {\n printf(\"call_count = %d instead of %d\\n\", call_count, tile_size * tile_size);\n return -1;\n }\n\n \/\/ Check the output is correct\n for (int y = 0; y < result.height(); y++) {\n for (int x = 0; x < result.width(); x++) {\n bool active = bitmap_buf(x\/tile_size, y\/tile_size);\n float correct = active ? my_powf(image_buf(x, y), 0.8f) : image_buf(x, y);\n if (fabs(correct - result(x, y)) > 0.001f) {\n printf(\"result(%d, %d) = %f instead of %f\\n\",\n x, y, result(x, y), correct);\n return -1;\n }\n }\n }\n\n printf(\"Success!\\n\");\n return 0;\n}\n<|endoftext|>"} {"text":"#include \n\n#include \"HalideRuntime.h\"\n#include \"HalideBuffer.h\"\n#include \n#include \n\n#include \"cxx_mangling.h\"\n#include \"cxx_mangling_gpu.h\"\n\nusing namespace Halide;\n\nint32_t extract_value_global(int32_t *arg) {\n return *arg;\n}\n\nnamespace HalideTest {\n\nint32_t extract_value_ns(const int32_t *arg) {\n return *arg;\n}\n\n}\n\nint main(int argc, char **argv) {\n Buffer input(100);\n\n for (int32_t i = 0; i < 100; i++) {\n input(i) = i;\n }\n\n Buffer result(100);\n\n const halide_filter_metadata_t *m = HalideTest::cxx_mangling_metadata();\n assert(m != NULL);\n printf(\"Name is: %s\\n\", m->name);\n assert(strcmp(m->name, \"cxx_mangling\") == 0);\n\n int ptr_arg = 42;\n int *int_ptr = &ptr_arg;\n const int *const_int_ptr = &ptr_arg;\n void *void_ptr = nullptr;\n const void *const_void_ptr = nullptr;\n std::string *string_ptr = nullptr;\n const std::string *const_string_ptr = nullptr;\n\n \/\/ Don't bother calling this (we haven't linked in the CUDA support it needs),\n \/\/ just force a reference to ensure it is linked in.\n auto f = HalideTest::cxx_mangling_gpu;\n printf(\"HalideTest::cxx_mangling is at: %p\\n\", (void*) f);\n\n int r = HalideTest::cxx_mangling(input, -1, 0xff, -1, 0xffff, -1, 0xffffffff,\n -1, 0xffffffffffffffffLL, true, 42.0, 4239.0f,\n int_ptr, const_int_ptr, void_ptr, const_void_ptr, \n string_ptr, const_string_ptr, result);\n if (r != 0) {\n fprintf(stderr, \"Failure!\\n\");\n exit(1);\n }\n printf(\"Success!\\n\");\n return 0;\n}\nFix ambiguity in test#include \n\n#include \"HalideRuntime.h\"\n#include \"HalideBuffer.h\"\n#include \n#include \n\n#include \"cxx_mangling.h\"\n#include \"cxx_mangling_gpu.h\"\n\nusing namespace Halide;\n\nint32_t extract_value_global(int32_t *arg) {\n return *arg;\n}\n\nnamespace HalideTest {\n\nint32_t extract_value_ns(const int32_t *arg) {\n return *arg;\n}\n\n}\n\nint main(int argc, char **argv) {\n Buffer input(100);\n\n for (int32_t i = 0; i < 100; i++) {\n input(i) = i;\n }\n\n Buffer result(100);\n\n const halide_filter_metadata_t *m = HalideTest::cxx_mangling_metadata();\n assert(m != NULL);\n printf(\"Name is: %s\\n\", m->name);\n assert(strcmp(m->name, \"cxx_mangling\") == 0);\n\n int ptr_arg = 42;\n int *int_ptr = &ptr_arg;\n const int *const_int_ptr = &ptr_arg;\n void *void_ptr = nullptr;\n const void *const_void_ptr = nullptr;\n std::string *string_ptr = nullptr;\n const std::string *const_string_ptr = nullptr;\n\n \/\/ Don't bother calling this (we haven't linked in the CUDA support it needs),\n \/\/ just force a reference to ensure it is linked in.\n int (*f)(halide_buffer_t *,\n int8_t, uint8_t,\n int16_t, uint16_t,\n int32_t, uint32_t,\n int64_t, uint64_t,\n bool,\n float, double,\n int32_t *, int32_t const *,\n void *, void const *,\n void *, void const *,\n halide_buffer_t *) = HalideTest::cxx_mangling_gpu;\n\n printf(\"HalideTest::cxx_mangling is at: %p\\n\", (void*) f);\n\n int r = HalideTest::cxx_mangling(input, -1, 0xff, -1, 0xffff, -1, 0xffffffff,\n -1, 0xffffffffffffffffLL, true, 42.0, 4239.0f,\n int_ptr, const_int_ptr, void_ptr, const_void_ptr,\n string_ptr, const_string_ptr, result);\n if (r != 0) {\n fprintf(stderr, \"Failure!\\n\");\n exit(1);\n }\n printf(\"Success!\\n\");\n return 0;\n}\n<|endoftext|>"} {"text":"\/\/ Avoid deprecation warnings\n#define HALIDE_ALLOW_DEPRECATED\n\n#include \"HalideRuntime.h\"\n#include \n#include \n#include \n#include \"old_buffer_t.h\"\n\nint &get_pixel(buffer_t *buf, int x, int y) {\n return *((int *)(buf->host) +\n (x - buf->min[0]) * buf->stride[0] +\n (y - buf->min[1]) * buf->stride[1]);\n}\n\nextern \"C\" int extern_stage(buffer_t *in2, buffer_t *f, buffer_t *out) {\n if (in2->host == nullptr) {\n in2->extent[0] = out->extent[0];\n in2->min[0] = out->min[0];\n in2->extent[1] = out->extent[1];\n in2->min[1] = out->min[1] + 7;\n }\n if (f->host == nullptr) {\n f->extent[0] = out->extent[0];\n f->min[0] = out->min[0];\n f->extent[1] = out->extent[1];\n f->min[1] = out->min[1];\n }\n if (f->host && in2->host && out->host) {\n for (int y = 0; y < out->extent[1]; y++) {\n for (int x = 0; x < out->extent[0]; x++) {\n get_pixel(out, x, y) = get_pixel(in2, x, y + 7) + get_pixel(f, x, y);\n }\n }\n }\n return 0;\n}\n\nint main(int argc, char **argv) {\n buffer_t in1 = {0}, in2 = {0}, out = {0};\n int scalar_param = 4;\n\n out.host = (uint8_t *)malloc(60*40*sizeof(int));\n out.extent[0] = 60;\n out.extent[1] = 40;\n out.stride[0] = 1;\n out.stride[1] = 60;\n\n \/\/ Check bounds inference works\n int err = old_buffer_t_old_buffer_t(&in1, &in2, scalar_param, &out);\n if (err != 0) {\n printf(\"Pipeline returned non-zero exit status in bounds query mode: %d\\n\", err);\n }\n\n buffer_t correct_in1 = {0, NULL, {62, 44, 0, 0}, {1, 62, 0, 0}, {-1, -1, 0, 0}, 4, false, false, {0}};\n buffer_t correct_in2 = {0, NULL, {60, 47, 0, 0}, {1, 60, 0, 0}, {0, 0, 0, 0}, 4, false, false, {0}};\n\n if (memcmp(&correct_in1, &in1, sizeof(buffer_t))) {\n printf(\"Bounds inference gave wrong result for input 1\\n\");\n return -1;\n }\n\n if (memcmp(&correct_in2, &in2, sizeof(buffer_t))) {\n printf(\"Bounds inference gave wrong result for input 2\\n\");\n return -1;\n }\n\n \/\/ Allocate the inputs\n in1.host = (uint8_t *)malloc(in1.extent[0] * in1.extent[1] * in1.elem_size);\n in2.host = (uint8_t *)malloc(in2.extent[0] * in2.extent[1] * in2.elem_size);\n\n memset(in1.host, 1, in1.extent[0] * in1.extent[1] * in1.elem_size);\n memset(in2.host, 2, in2.extent[0] * in2.extent[1] * in2.elem_size);\n\n \/\/ Run the pipeline for real\n err = old_buffer_t_old_buffer_t(&in1, &in2, scalar_param, &out);\n if (err != 0) {\n printf(\"Pipeline returned non-zero exit status: %d\\n\", err);\n }\n\n for (int y = 0; y < out.extent[1]; y++) {\n for (int x = 0; x < out.extent[0]; x++) {\n int result = get_pixel(&out, x, y);\n int correct = 0x01010101 * 2 + 0x02020202 * 2 + scalar_param;\n if (result != correct) {\n printf(\"out(%d, %d) = %d instead of %d\\n\", x, y, result, correct);\n return -1;\n }\n }\n }\n\n printf(\"Success!\\n\");\n return 0;\n}\nFix test\/\/ Avoid deprecation warnings\n#define HALIDE_ALLOW_DEPRECATED\n\n#include \"HalideRuntime.h\"\n#include \n#include \n#include \n#include \"old_buffer_t.h\"\n\nint &get_pixel(buffer_t *buf, int x, int y) {\n return *((int *)(buf->host) +\n (x - buf->min[0]) * buf->stride[0] +\n (y - buf->min[1]) * buf->stride[1]);\n}\n\nextern \"C\" int extern_stage(buffer_t *in2, buffer_t *f, buffer_t *out) {\n if (in2->host == nullptr) {\n in2->extent[0] = out->extent[0];\n in2->min[0] = out->min[0];\n in2->extent[1] = out->extent[1];\n in2->min[1] = out->min[1] + 7;\n }\n if (f->host == nullptr) {\n f->extent[0] = out->extent[0];\n f->min[0] = out->min[0];\n f->extent[1] = out->extent[1];\n f->min[1] = out->min[1];\n }\n if (f->host && in2->host && out->host) {\n for (int y = 0; y < out->extent[1]; y++) {\n for (int x = 0; x < out->extent[0]; x++) {\n get_pixel(out, x, y) = get_pixel(in2, x, y + 7) + get_pixel(f, x, y);\n }\n }\n }\n return 0;\n}\n\nint main(int argc, char **argv) {\n buffer_t in1 = {0}, in2 = {0}, out = {0};\n int scalar_param = 4;\n\n out.host = (uint8_t *)malloc(60*40*sizeof(int));\n out.extent[0] = 60;\n out.extent[1] = 40;\n out.stride[0] = 1;\n out.stride[1] = 60;\n out.elem_size = 4;\n\n \/\/ Check bounds inference works\n int err = old_buffer_t_old_buffer_t(&in1, &in2, scalar_param, &out);\n if (err != 0) {\n printf(\"Pipeline returned non-zero exit status in bounds query mode: %d\\n\", err);\n }\n\n buffer_t correct_in1 = {0, NULL, {62, 44, 0, 0}, {1, 62, 0, 0}, {-1, -1, 0, 0}, 4, false, false, {0}};\n buffer_t correct_in2 = {0, NULL, {60, 47, 0, 0}, {1, 60, 0, 0}, {0, 0, 0, 0}, 4, false, false, {0}};\n\n if (memcmp(&correct_in1, &in1, sizeof(buffer_t))) {\n printf(\"Bounds inference gave wrong result for input 1\\n\");\n return -1;\n }\n\n if (memcmp(&correct_in2, &in2, sizeof(buffer_t))) {\n printf(\"Bounds inference gave wrong result for input 2\\n\");\n return -1;\n }\n\n \/\/ Allocate the inputs\n in1.host = (uint8_t *)malloc(in1.extent[0] * in1.extent[1] * in1.elem_size);\n in2.host = (uint8_t *)malloc(in2.extent[0] * in2.extent[1] * in2.elem_size);\n\n memset(in1.host, 1, in1.extent[0] * in1.extent[1] * in1.elem_size);\n memset(in2.host, 2, in2.extent[0] * in2.extent[1] * in2.elem_size);\n\n \/\/ Run the pipeline for real\n err = old_buffer_t_old_buffer_t(&in1, &in2, scalar_param, &out);\n if (err != 0) {\n printf(\"Pipeline returned non-zero exit status: %d\\n\", err);\n }\n\n for (int y = 0; y < out.extent[1]; y++) {\n for (int x = 0; x < out.extent[0]; x++) {\n int result = get_pixel(&out, x, y);\n int correct = 0x01010101 * 2 + 0x02020202 * 2 + scalar_param;\n if (result != correct) {\n printf(\"out(%d, %d) = %d instead of %d\\n\", x, y, result, correct);\n return -1;\n }\n }\n }\n\n printf(\"Success!\\n\");\n return 0;\n}\n<|endoftext|>"} {"text":"\/**\n * Copyright (C) 2017 Jung-Sang Ahn \n * All rights reserved.\n *\n * Permission is hereby granted, free of charge, to any person\n * obtaining a copy of this software and associated documentation\n * files (the \"Software\"), to deal in the Software without\n * restriction, including without limitation the rights to use,\n * copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the\n * Software is furnished to do so, subject to the following\n * conditions:\n *\n * The above copyright notice and this permission notice shall be\n * included in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES\n * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,\n * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\n * OTHER DEALINGS IN THE SOFTWARE.\n *\/\n\n#include \n\n#include \"skiplist.h\"\n\n\/\/#define __SL_DEBUG\n#ifdef __SL_DEBUG\n #include \"skiplist_debug.h\"\n#else\n #define __SLD_RT_INS(e, n, t, c)\n #define __SLD_NC_INS(n, nn, t, c)\n #define __SLD_RT_RMV(e, n, t, c)\n #define __SLD_NC_RMV(n, nn, t, c)\n #define __SLD_BM(n)\n #define __SLD_ASSERT(cond)\n#endif\n\nstatic inline void _sl_node_init(SkiplistNode *node,\n size_t top_layer)\n{\n if (top_layer > UINT8_MAX) {\n top_layer = UINT8_MAX;\n }\n\n node->isFullyLinked = false;\n node->beingModified = false;\n node->removed = false;\n\n if (node->topLayer != top_layer ||\n node->next == nullptr) {\n\n node->topLayer = top_layer;\n\n if (node->next) {\n delete[] node->next;\n }\n node->next = new std::atomic[top_layer+1];\n }\n}\n\nvoid skiplist_init(SkiplistRaw *slist,\n skiplist_cmp_t *cmp_func) {\n _sl_node_init(&slist->head, slist->maxLayer);\n _sl_node_init(&slist->tail, slist->maxLayer);\n\n size_t layer;\n for (layer = 0; layer < slist->maxLayer; ++layer) {\n slist->head.next[layer] = &slist->tail;\n slist->tail.next[layer] = nullptr;\n }\n\n slist->head.isFullyLinked = slist->tail.isFullyLinked = true;\n slist->cmpFunc = cmp_func;\n}\n\nstatic inline int _sl_cmp(SkiplistRaw *slist,\n SkiplistNode *a,\n SkiplistNode *b)\n{\n if (a == b) {\n return 0;\n }\n if (a == &slist->head ||\n b == &slist->tail) {\n return -1;\n }\n if (a == &slist->tail ||\n b == &slist->head) {\n return 1;\n }\n return slist->cmpFunc(a, b, slist->aux);\n}\n\nstatic inline bool _sl_valid_node(SkiplistNode *node) {\n return !node->removed && node->isFullyLinked;\n}\n\nstatic inline SkiplistNode* _sl_next(SkiplistRaw *slist,\n SkiplistNode *cur_node,\n int layer)\n{\n SkiplistNode *next_node = cur_node->next[layer];\n while ( next_node && !_sl_valid_node(next_node) ) {\n next_node = next_node->next[layer];\n }\n return next_node;\n}\n\nstatic inline size_t _sl_decide_top_layer(SkiplistRaw *slist)\n{\n size_t layer = 0;\n while (layer+1 < slist->maxLayer) {\n \/\/ coin filp\n if (rand() % slist->fanout == 0) {\n \/\/ grow: 1\/fanout probability\n layer++;\n } else {\n \/\/ stop: 1 - 1\/fanout probability\n break;\n }\n }\n return layer;\n}\n\nstatic inline void _sl_clr_flags(SkiplistNode** node_arr,\n int start_layer,\n int top_layer)\n{\n int layer;\n for (layer = start_layer; layer <= top_layer; ++layer) {\n if ( layer == top_layer ||\n node_arr[layer] != node_arr[layer+1] ) {\n __SLD_ASSERT(node_arr[layer]->beingModified == true);\n node_arr[layer]->beingModified = false;\n }\n }\n}\n\nstatic inline bool _sl_valid_prev_next(SkiplistNode *prev,\n SkiplistNode *next) {\n return _sl_valid_node(prev) && _sl_valid_node(next);\n}\n\nvoid skiplist_insert(SkiplistRaw *slist,\n SkiplistNode *node)\n{\n int top_layer = _sl_decide_top_layer(slist);\n\n \/\/ init node before insertion\n _sl_node_init(node, top_layer);\n\n SkiplistNode* prevs[SKIPLIST_MAX_LAYER];\n SkiplistNode* nexts[SKIPLIST_MAX_LAYER];\n\n\ninsert_retry:\n int cmp = 0;\n int cur_layer = 0;\n int layer;\n SkiplistNode *cur_node = &slist->head;\n\n for (cur_layer = slist->maxLayer-1; cur_layer >= 0; --cur_layer) {\n do {\n SkiplistNode *next_node = _sl_next(slist, cur_node, cur_layer);\n cmp = _sl_cmp(slist, node, next_node);\n if (cmp > 0) {\n \/\/ cur_node->next < node\n \/\/ => move to next node\n cur_node = next_node;\n continue;\n }\n \/\/ node <= cur_node->next\n\n if (cur_layer <= top_layer) {\n prevs[cur_layer] = cur_node;\n nexts[cur_layer] = next_node;\n\n \/\/ both 'prev' and 'next' should be fully linked before\n \/\/ insertion, and no other thread should not modify 'prev'\n \/\/ at the same time.\n\n int error_code = 0;\n int locked_layer = cur_layer + 1;\n\n \/\/ check if prev node is duplicated with upper layer\n if (cur_layer < top_layer &&\n prevs[cur_layer] == prevs[cur_layer+1]) {\n \/\/ duplicate\n \/\/ => which means that 'beingModified' flag is already true\n \/\/ => do nothing\n } else {\n bool expected = false;\n if (prevs[cur_layer]->beingModified.\n compare_exchange_strong(expected, true)) {\n locked_layer = cur_layer;\n } else {\n error_code = -1;\n }\n }\n\n if (error_code == 0 &&\n !_sl_valid_prev_next(prevs[cur_layer], nexts[cur_layer])) {\n error_code = -2;\n }\n\n if (error_code != 0) {\n __SLD_RT_INS(error_code, node, top_layer, cur_layer);\n _sl_clr_flags(prevs, locked_layer, top_layer);\n goto insert_retry;\n }\n\n \/\/ set current node's pointers\n node->next[cur_layer] = nexts[cur_layer];\n\n if (_sl_next(slist, cur_node, cur_layer) != next_node) {\n __SLD_NC_INS(cur_node, next_node, top_layer, cur_layer);\n \/\/ clear including the current layer\n \/\/ as we already set modification flag above.\n _sl_clr_flags(prevs, cur_layer, top_layer);\n goto insert_retry;\n }\n }\n\n if (cur_layer) {\n \/\/ non-bottom layer => go down\n break;\n }\n\n \/\/ bottom layer => insertion succeeded\n \/\/ change prev\/next nodes' prev\/next pointers from 0 ~ top_layer\n for (layer = 0; layer <= top_layer; ++layer) {\n prevs[layer]->next[layer] = node;\n }\n\n \/\/ now this node is fully linked\n node->isFullyLinked = true;\n\n \/\/ modification is done for all layers\n _sl_clr_flags(prevs, 0, top_layer);\n return;\n\n } while (cur_node != &slist->tail);\n }\n}\n\nSkiplistNode* skiplist_find(SkiplistRaw *slist,\n SkiplistNode *query)\n{\n int cmp = 0;\n int cur_layer = 0;\n SkiplistNode *cur_node = &slist->head;\n\n for (cur_layer = slist->maxLayer-1 ; cur_layer >= 0; --cur_layer) {\n do {\n SkiplistNode *next_node = _sl_next(slist, cur_node, cur_layer);\n\n cmp = _sl_cmp(slist, query, next_node);\n if (cmp > 0) {\n \/\/ next_node < query\n \/\/ => move to next node\n cur_node = next_node;\n continue;\n } else if (cmp == 0) {\n \/\/ query == next_node .. return\n return next_node;\n }\n\n \/\/ query < next_node\n if (cur_layer) {\n \/\/ non-bottom layer => go down\n break;\n }\n\n \/\/ bottom layer => means that exact match doesn't exist.\n return nullptr;\n\n } while (cur_node != &slist->tail);\n }\n\n return nullptr;\n}\n\nSkiplistNode* skiplist_find_smaller(SkiplistRaw *slist,\n SkiplistNode *query)\n{\n int cmp = 0;\n int cur_layer = 0;\n SkiplistNode *cur_node = &slist->head;\n\n for (cur_layer = slist->maxLayer-1 ; cur_layer >= 0; --cur_layer) {\n do {\n SkiplistNode *next_node = _sl_next(slist, cur_node, cur_layer);\n\n cmp = _sl_cmp(slist, query, next_node);\n if (cmp > 0) {\n \/\/ next_node < query\n \/\/ => move to next node\n cur_node = next_node;\n continue;\n }\n\n \/\/ otherwise: query <= next_node\n if (cur_layer) {\n \/\/ non-bottom layer => go down\n break;\n }\n\n \/\/ bottom layer => return cur_node\n return cur_node;\n\n } while (cur_node != &slist->tail);\n }\n\n return nullptr;\n}\n\nint skiplist_erase_node(SkiplistRaw *slist,\n SkiplistNode *node)\n{\n int top_layer = node->topLayer;\n\n if (node->removed) {\n \/\/ already removed\n return -1;\n }\n\n SkiplistNode* prevs[SKIPLIST_MAX_LAYER];\n SkiplistNode* nexts[SKIPLIST_MAX_LAYER];\n\n bool expected = false;\n if (!node->beingModified.compare_exchange_strong(expected, true)) {\n \/\/ already being modified .. fail\n __SLD_BM(node);\n return -2;\n }\n\n \/\/ clear removed flag first, so that reader cannot read this node.\n node->removed = true;\n\nerase_node_retry:\n if (!node->isFullyLinked) {\n \/\/ already unlinked .. remove is done by other thread\n return -3;\n }\n\n int cmp = 0;\n int cur_layer = slist->maxLayer - 1;\n SkiplistNode *cur_node = &slist->head;\n\n for (; cur_layer >= 0; --cur_layer) {\n do {\n SkiplistNode *next_node = _sl_next(slist, cur_node, cur_layer);\n\n cmp = _sl_cmp(slist, node, next_node);\n if (cmp > 0) {\n \/\/ 'next_node' < 'node'\n \/\/ => move to next node\n cur_node = next_node;\n continue;\n }\n \/\/ otherwise: 'node' <= 'next_node'\n\n if (cur_layer <= top_layer) {\n prevs[cur_layer] = cur_node;\n \/\/ note: 'next_node' should not be 'node',\n \/\/ as 'removed' flag is already set.\n __SLD_ASSERT(next_node != node);\n nexts[cur_layer] = next_node;\n\n \/\/ check if prev node duplicates with upper layer\n int error_code = 0;\n int locked_layer = cur_layer + 1;\n if (cur_layer < top_layer &&\n prevs[cur_layer] == prevs[cur_layer+1]) {\n \/\/ duplicate with upper layer\n \/\/ => which means that 'beingModified' flag is already true\n \/\/ => do nothing.\n } else {\n expected = false;\n if (prevs[cur_layer]->beingModified.\n compare_exchange_strong(expected, true)) {\n locked_layer = cur_layer;\n } else {\n error_code = -1;\n }\n }\n\n if (error_code == 0 &&\n !_sl_valid_prev_next(prevs[cur_layer], nexts[cur_layer])) {\n error_code = -2;\n }\n\n if (error_code != 0) {\n __SLD_RT_RMV(error_code, node, top_layer, cur_layer);\n _sl_clr_flags(prevs, locked_layer, top_layer);\n goto erase_node_retry;\n }\n\n if (_sl_next(slist, cur_node, cur_layer) != nexts[cur_layer]) {\n __SLD_NC_RMV(cur_node, nexts[cur_layer], top_layer, cur_layer);\n _sl_clr_flags(prevs, cur_layer, top_layer);\n goto erase_node_retry;\n }\n }\n\n \/\/ go down\n break;\n\n } while (cur_node != &slist->tail);\n }\n\n \/\/ bottom layer => removal succeeded.\n \/\/ change prev nodes' next pointer from 0 ~ top_layer\n for (cur_layer = 0; cur_layer <= top_layer; ++cur_layer) {\n prevs[cur_layer]->next[cur_layer] = nexts[cur_layer];\n }\n\n \/\/ now this node is unlinked\n node->isFullyLinked = false;\n\n \/\/ modification is done for all layers\n _sl_clr_flags(prevs, 0, top_layer);\n\n node->beingModified = false;\n return 0;\n}\n\nint skiplist_erase(SkiplistRaw *slist,\n SkiplistNode *query)\n{\n SkiplistNode *found = skiplist_find(slist, query);\n if (!found) {\n \/\/ key not found\n return -4;\n }\n\n int ret = 0;\n do {\n ret = skiplist_erase_node(slist, found);\n \/\/ if ret == -2, other thread is accessing the same node\n \/\/ at the same time. try again.\n } while (ret == -2);\n return ret;\n}\n\nSkiplistNode* skiplist_next(SkiplistRaw *slist,\n SkiplistNode *node) {\n SkiplistNode *next = _sl_next(slist, node, 0);\n if (next == &slist->tail) {\n return nullptr;\n }\n return next;\n}\n\nSkiplistNode* skiplist_prev(SkiplistRaw *slist,\n SkiplistNode *node) {\n SkiplistNode *prev = skiplist_find_smaller(slist, node);\n if (prev == &slist->head) {\n return nullptr;\n }\n return prev;\n}\n\nSkiplistNode* skiplist_begin(SkiplistRaw *slist) {\n SkiplistNode *next = _sl_next(slist, &slist->head, 0);\n if (next == &slist->tail) {\n return nullptr;\n }\n return next;\n}\n\nSkiplistNode* skiplist_end(SkiplistRaw *slist) {\n return skiplist_prev(slist, &slist->tail);\n}\n\nFix whitespaces\/**\n * Copyright (C) 2017 Jung-Sang Ahn \n * All rights reserved.\n *\n * Permission is hereby granted, free of charge, to any person\n * obtaining a copy of this software and associated documentation\n * files (the \"Software\"), to deal in the Software without\n * restriction, including without limitation the rights to use,\n * copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the\n * Software is furnished to do so, subject to the following\n * conditions:\n *\n * The above copyright notice and this permission notice shall be\n * included in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES\n * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,\n * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\n * OTHER DEALINGS IN THE SOFTWARE.\n *\/\n\n#include \n\n#include \"skiplist.h\"\n\n\/\/#define __SL_DEBUG\n#ifdef __SL_DEBUG\n #include \"skiplist_debug.h\"\n#else\n #define __SLD_RT_INS(e, n, t, c)\n #define __SLD_NC_INS(n, nn, t, c)\n #define __SLD_RT_RMV(e, n, t, c)\n #define __SLD_NC_RMV(n, nn, t, c)\n #define __SLD_BM(n)\n #define __SLD_ASSERT(cond)\n#endif\n\nstatic inline void _sl_node_init(SkiplistNode *node,\n size_t top_layer)\n{\n if (top_layer > UINT8_MAX) {\n top_layer = UINT8_MAX;\n }\n\n node->isFullyLinked = false;\n node->beingModified = false;\n node->removed = false;\n\n if (node->topLayer != top_layer ||\n node->next == nullptr) {\n\n node->topLayer = top_layer;\n\n if (node->next) {\n delete[] node->next;\n }\n node->next = new std::atomic[top_layer+1];\n }\n}\n\nvoid skiplist_init(SkiplistRaw *slist,\n skiplist_cmp_t *cmp_func) {\n _sl_node_init(&slist->head, slist->maxLayer);\n _sl_node_init(&slist->tail, slist->maxLayer);\n\n size_t layer;\n for (layer = 0; layer < slist->maxLayer; ++layer) {\n slist->head.next[layer] = &slist->tail;\n slist->tail.next[layer] = nullptr;\n }\n\n slist->head.isFullyLinked = slist->tail.isFullyLinked = true;\n slist->cmpFunc = cmp_func;\n}\n\nstatic inline int _sl_cmp(SkiplistRaw *slist,\n SkiplistNode *a,\n SkiplistNode *b)\n{\n if (a == b) {\n return 0;\n }\n if (a == &slist->head ||\n b == &slist->tail) {\n return -1;\n }\n if (a == &slist->tail ||\n b == &slist->head) {\n return 1;\n }\n return slist->cmpFunc(a, b, slist->aux);\n}\n\nstatic inline bool _sl_valid_node(SkiplistNode *node) {\n return !node->removed && node->isFullyLinked;\n}\n\nstatic inline SkiplistNode* _sl_next(SkiplistRaw *slist,\n SkiplistNode *cur_node,\n int layer)\n{\n SkiplistNode *next_node = cur_node->next[layer];\n while ( next_node && !_sl_valid_node(next_node) ) {\n next_node = next_node->next[layer];\n }\n return next_node;\n}\n\nstatic inline size_t _sl_decide_top_layer(SkiplistRaw *slist)\n{\n size_t layer = 0;\n while (layer+1 < slist->maxLayer) {\n \/\/ coin filp\n if (rand() % slist->fanout == 0) {\n \/\/ grow: 1\/fanout probability\n layer++;\n } else {\n \/\/ stop: 1 - 1\/fanout probability\n break;\n }\n }\n return layer;\n}\n\nstatic inline void _sl_clr_flags(SkiplistNode** node_arr,\n int start_layer,\n int top_layer)\n{\n int layer;\n for (layer = start_layer; layer <= top_layer; ++layer) {\n if ( layer == top_layer ||\n node_arr[layer] != node_arr[layer+1] ) {\n __SLD_ASSERT(node_arr[layer]->beingModified == true);\n node_arr[layer]->beingModified = false;\n }\n }\n}\n\nstatic inline bool _sl_valid_prev_next(SkiplistNode *prev,\n SkiplistNode *next) {\n return _sl_valid_node(prev) && _sl_valid_node(next);\n}\n\nvoid skiplist_insert(SkiplistRaw *slist,\n SkiplistNode *node)\n{\n int top_layer = _sl_decide_top_layer(slist);\n\n \/\/ init node before insertion\n _sl_node_init(node, top_layer);\n\n SkiplistNode* prevs[SKIPLIST_MAX_LAYER];\n SkiplistNode* nexts[SKIPLIST_MAX_LAYER];\n\ninsert_retry:\n int cmp = 0;\n int cur_layer = 0;\n int layer;\n SkiplistNode *cur_node = &slist->head;\n\n for (cur_layer = slist->maxLayer-1; cur_layer >= 0; --cur_layer) {\n do {\n SkiplistNode *next_node = _sl_next(slist, cur_node, cur_layer);\n cmp = _sl_cmp(slist, node, next_node);\n if (cmp > 0) {\n \/\/ next_node < node\n \/\/ => move to next node\n cur_node = next_node;\n continue;\n }\n \/\/ otherwise: node <= next_node\n\n if (cur_layer <= top_layer) {\n prevs[cur_layer] = cur_node;\n nexts[cur_layer] = next_node;\n\n \/\/ both 'prev' and 'next' should be fully linked before\n \/\/ insertion, and no other thread should not modify 'prev'\n \/\/ at the same time.\n\n int error_code = 0;\n int locked_layer = cur_layer + 1;\n\n \/\/ check if prev node is duplicated with upper layer\n if (cur_layer < top_layer &&\n prevs[cur_layer] == prevs[cur_layer+1]) {\n \/\/ duplicate\n \/\/ => which means that 'beingModified' flag is already true\n \/\/ => do nothing\n } else {\n bool expected = false;\n if (prevs[cur_layer]->beingModified.\n compare_exchange_strong(expected, true)) {\n locked_layer = cur_layer;\n } else {\n error_code = -1;\n }\n }\n\n if (error_code == 0 &&\n !_sl_valid_prev_next(prevs[cur_layer], nexts[cur_layer])) {\n error_code = -2;\n }\n\n if (error_code != 0) {\n __SLD_RT_INS(error_code, node, top_layer, cur_layer);\n _sl_clr_flags(prevs, locked_layer, top_layer);\n goto insert_retry;\n }\n\n \/\/ set current node's pointers\n node->next[cur_layer] = nexts[cur_layer];\n\n if (_sl_next(slist, cur_node, cur_layer) != next_node) {\n __SLD_NC_INS(cur_node, next_node, top_layer, cur_layer);\n \/\/ clear including the current layer\n \/\/ as we already set modification flag above.\n _sl_clr_flags(prevs, cur_layer, top_layer);\n goto insert_retry;\n }\n }\n\n if (cur_layer) {\n \/\/ non-bottom layer => go down\n break;\n }\n\n \/\/ bottom layer => insertion succeeded\n \/\/ change prev\/next nodes' prev\/next pointers from 0 ~ top_layer\n for (layer = 0; layer <= top_layer; ++layer) {\n prevs[layer]->next[layer] = node;\n }\n\n \/\/ now this node is fully linked\n node->isFullyLinked = true;\n\n \/\/ modification is done for all layers\n _sl_clr_flags(prevs, 0, top_layer);\n return;\n\n } while (cur_node != &slist->tail);\n }\n}\n\nSkiplistNode* skiplist_find(SkiplistRaw *slist,\n SkiplistNode *query)\n{\n int cmp = 0;\n int cur_layer = 0;\n SkiplistNode *cur_node = &slist->head;\n\n for (cur_layer = slist->maxLayer-1; cur_layer >= 0; --cur_layer) {\n do {\n SkiplistNode *next_node = _sl_next(slist, cur_node, cur_layer);\n cmp = _sl_cmp(slist, query, next_node);\n if (cmp > 0) {\n \/\/ next_node < query\n \/\/ => move to next node\n cur_node = next_node;\n continue;\n } else if (cmp == 0) {\n \/\/ query == next_node .. return\n return next_node;\n }\n\n \/\/ query < next_node\n if (cur_layer) {\n \/\/ non-bottom layer => go down\n break;\n }\n\n \/\/ bottom layer => means that exact match doesn't exist.\n return nullptr;\n\n } while (cur_node != &slist->tail);\n }\n\n return nullptr;\n}\n\nSkiplistNode* skiplist_find_smaller(SkiplistRaw *slist,\n SkiplistNode *query)\n{\n int cmp = 0;\n int cur_layer = 0;\n SkiplistNode *cur_node = &slist->head;\n\n for (cur_layer = slist->maxLayer-1; cur_layer >= 0; --cur_layer) {\n do {\n SkiplistNode *next_node = _sl_next(slist, cur_node, cur_layer);\n cmp = _sl_cmp(slist, query, next_node);\n if (cmp > 0) {\n \/\/ next_node < query\n \/\/ => move to next node\n cur_node = next_node;\n continue;\n }\n\n \/\/ otherwise: query <= next_node\n if (cur_layer) {\n \/\/ non-bottom layer => go down\n break;\n }\n\n \/\/ bottom layer => return cur_node\n return cur_node;\n\n } while (cur_node != &slist->tail);\n }\n\n return nullptr;\n}\n\nint skiplist_erase_node(SkiplistRaw *slist,\n SkiplistNode *node)\n{\n int top_layer = node->topLayer;\n\n if (node->removed) {\n \/\/ already removed\n return -1;\n }\n\n SkiplistNode* prevs[SKIPLIST_MAX_LAYER];\n SkiplistNode* nexts[SKIPLIST_MAX_LAYER];\n\n bool expected = false;\n if (!node->beingModified.compare_exchange_strong(expected, true)) {\n \/\/ already being modified .. fail\n __SLD_BM(node);\n return -2;\n }\n\n \/\/ clear removed flag first, so that reader cannot read this node.\n node->removed = true;\n\nerase_node_retry:\n if (!node->isFullyLinked) {\n \/\/ already unlinked .. remove is done by other thread\n return -3;\n }\n\n int cmp = 0;\n int cur_layer = slist->maxLayer - 1;\n SkiplistNode *cur_node = &slist->head;\n\n for (; cur_layer >= 0; --cur_layer) {\n do {\n SkiplistNode *next_node = _sl_next(slist, cur_node, cur_layer);\n\n cmp = _sl_cmp(slist, node, next_node);\n if (cmp > 0) {\n \/\/ 'next_node' < 'node'\n \/\/ => move to next node\n cur_node = next_node;\n continue;\n }\n \/\/ otherwise: 'node' <= 'next_node'\n\n if (cur_layer <= top_layer) {\n prevs[cur_layer] = cur_node;\n \/\/ note: 'next_node' should not be 'node',\n \/\/ as 'removed' flag is already set.\n __SLD_ASSERT(next_node != node);\n nexts[cur_layer] = next_node;\n\n \/\/ check if prev node duplicates with upper layer\n int error_code = 0;\n int locked_layer = cur_layer + 1;\n if (cur_layer < top_layer &&\n prevs[cur_layer] == prevs[cur_layer+1]) {\n \/\/ duplicate with upper layer\n \/\/ => which means that 'beingModified' flag is already true\n \/\/ => do nothing.\n } else {\n expected = false;\n if (prevs[cur_layer]->beingModified.\n compare_exchange_strong(expected, true)) {\n locked_layer = cur_layer;\n } else {\n error_code = -1;\n }\n }\n\n if (error_code == 0 &&\n !_sl_valid_prev_next(prevs[cur_layer], nexts[cur_layer])) {\n error_code = -2;\n }\n\n if (error_code != 0) {\n __SLD_RT_RMV(error_code, node, top_layer, cur_layer);\n _sl_clr_flags(prevs, locked_layer, top_layer);\n goto erase_node_retry;\n }\n\n if (_sl_next(slist, cur_node, cur_layer) != nexts[cur_layer]) {\n __SLD_NC_RMV(cur_node, nexts[cur_layer], top_layer, cur_layer);\n _sl_clr_flags(prevs, cur_layer, top_layer);\n goto erase_node_retry;\n }\n }\n\n \/\/ go down\n break;\n\n } while (cur_node != &slist->tail);\n }\n\n \/\/ bottom layer => removal succeeded.\n \/\/ change prev nodes' next pointer from 0 ~ top_layer\n for (cur_layer = 0; cur_layer <= top_layer; ++cur_layer) {\n prevs[cur_layer]->next[cur_layer] = nexts[cur_layer];\n }\n\n \/\/ now this node is unlinked\n node->isFullyLinked = false;\n\n \/\/ modification is done for all layers\n _sl_clr_flags(prevs, 0, top_layer);\n\n node->beingModified = false;\n return 0;\n}\n\nint skiplist_erase(SkiplistRaw *slist,\n SkiplistNode *query)\n{\n SkiplistNode *found = skiplist_find(slist, query);\n if (!found) {\n \/\/ key not found\n return -4;\n }\n\n int ret = 0;\n do {\n ret = skiplist_erase_node(slist, found);\n \/\/ if ret == -2, other thread is accessing the same node\n \/\/ at the same time. try again.\n } while (ret == -2);\n return ret;\n}\n\nSkiplistNode* skiplist_next(SkiplistRaw *slist,\n SkiplistNode *node) {\n SkiplistNode *next = _sl_next(slist, node, 0);\n if (next == &slist->tail) {\n return nullptr;\n }\n return next;\n}\n\nSkiplistNode* skiplist_prev(SkiplistRaw *slist,\n SkiplistNode *node) {\n SkiplistNode *prev = skiplist_find_smaller(slist, node);\n if (prev == &slist->head) {\n return nullptr;\n }\n return prev;\n}\n\nSkiplistNode* skiplist_begin(SkiplistRaw *slist) {\n SkiplistNode *next = _sl_next(slist, &slist->head, 0);\n if (next == &slist->tail) {\n return nullptr;\n }\n return next;\n}\n\nSkiplistNode* skiplist_end(SkiplistRaw *slist) {\n return skiplist_prev(slist, &slist->tail);\n}\n\n<|endoftext|>"} {"text":"\/**\n * @brief Test cases for materialization node.\n *\n * Copyright(c) 2015, CMU\n *\/\n\n#include \n#include \n#include \n#include \n#include \n\n#include \"gtest\/gtest.h\"\n\n#include \"catalog\/manager.h\"\n#include \"catalog\/schema.h\"\n#include \"common\/types.h\"\n#include \"common\/value_factory.h\"\n#include \"executor\/logical_tile.h\"\n#include \"executor\/logical_tile_factory.h\"\n#include \"executor\/materialization_executor.h\"\n#include \"planner\/abstract_plan_node.h\"\n#include \"planner\/materialization_node.h\"\n#include \"storage\/tile.h\"\n#include \"storage\/tile_group.h\"\n#include \"storage\/tuple.h\"\n#include \"storage\/vm_backend.h\"\n\n#include \"executor\/executor_tests_util.h\"\n#include \"executor\/mock_executor.h\"\n#include \"harness.h\"\n\nusing ::testing::IsNull;\nusing ::testing::NotNull;\nusing ::testing::Return;\n\nnamespace nstore {\nnamespace test {\n\nnamespace {\n\n\/**\n * @brief Populates the tiles in the given tile-group in a specific manner.\n * @param tile_group Tile-group to populate with values.\n * @param num_rows Number of tuples to insert.\n *\n * This is a convenience function for the test cases.\n *\/\nvoid PopulateTiles(storage::TileGroup *tile_group, int num_rows) {\n \/\/ Create tuple schema from tile schemas.\n std::vector &tile_schemas = tile_group->GetTileSchemas();\n std::unique_ptr schema(\n catalog::Schema::AppendSchemaList(tile_schemas));\n\n \/\/ Ensure that the tile group created by ExecutorTestsUtil is as expected.\n assert(tile_schemas.size() == 2);\n assert(schema->GetColumnCount() == 4);\n\n \/\/ Insert tuples into tile_group.\n const bool allocate = true;\n const txn_id_t txn_id = GetTransactionId();\n for (int i = 0; i < num_rows; i++) {\n storage::Tuple tuple(schema.get(), allocate);\n tuple.SetValue(0, ValueFactory::GetIntegerValue(10 * i));\n tuple.SetValue(1, ValueFactory::GetIntegerValue(10 * i + 1));\n tuple.SetValue(2, ValueFactory::GetTinyIntValue(10 * i + 2));\n tuple.SetValue(\n 3,\n ValueFactory::GetStringValue(std::to_string(10 * i + 3),\n tile_group->GetTilePool(1)));\n tile_group->InsertTuple(txn_id, &tuple);\n }\n}\n\n} \/\/ namespace\n\n\/\/ \"Pass-through\" test case. There is nothing to materialize as\n\/\/ there is only one base tile in the logical tile.\nTEST(MaterializationTests, SingleBaseTileTest) {\n storage::VMBackend backend;\n const int tuple_count = 9;\n std::unique_ptr tile_group(\n ExecutorTestsUtil::CreateSimpleTileGroup(\n &backend,\n tuple_count));\n\n PopulateTiles(tile_group.get(), tuple_count);\n\n \/\/ Create logical tile from single base tile.\n storage::Tile *source_base_tile = tile_group->GetTile(0);\n const bool own_base_tile = false;\n std::unique_ptr source_tile(\n executor::LogicalTileFactory::WrapBaseTiles(\n { source_base_tile },\n own_base_tile));\n\n \/\/ Create materialization node for this test.\n \/\/TODO This should be deleted soon... Should we use default copy constructor?\n std::unique_ptr output_schema(catalog::Schema::CopySchema(\n &source_base_tile->GetSchema()));\n std::unordered_map old_to_new_cols;\n\n unsigned int column_count = output_schema->GetColumnCount();\n for (id_t col = 0; col < column_count; col++) {\n \/\/ Create identity mapping.\n old_to_new_cols[col] = col;\n }\n planner::MaterializationNode node(\n std::move(old_to_new_cols),\n output_schema.release());\n\n \/\/ Pass them through materialization executor.\n executor::MaterializationExecutor executor(&node);\n MockExecutor child_executor;\n executor.AddChild(&child_executor);\n\n \/\/ Uneventful init...\n EXPECT_CALL(child_executor, SubInit())\n .WillOnce(Return(true));\n EXPECT_TRUE(executor.Init());\n\n \/\/ Where the main work takes place...\n EXPECT_CALL(child_executor, SubGetNextTile())\n .WillOnce(Return(source_tile.release()))\n .WillOnce(Return(nullptr));\n\n std::unique_ptr result_logical_tile(\n executor.GetNextTile());\n EXPECT_THAT(result_logical_tile, NotNull());\n EXPECT_THAT(executor.GetNextTile(), IsNull());\n\n \/\/ Verify that logical tile is only made up of a single base tile.\n int num_cols = result_logical_tile->NumCols();\n EXPECT_EQ(2, num_cols);\n storage::Tile *result_base_tile = result_logical_tile->GetBaseTile(0);\n EXPECT_THAT(result_base_tile, NotNull());\n EXPECT_TRUE(source_base_tile != result_base_tile);\n EXPECT_EQ(result_logical_tile->GetBaseTile(1), result_base_tile);\n\n \/\/ Check that the base tile has the correct values.\n for (int i = 0; i < tuple_count; i++) {\n EXPECT_EQ(ValueFactory::GetIntegerValue(10 * i),\n result_base_tile->GetValue(i, 0));\n EXPECT_EQ(ValueFactory::GetIntegerValue(10 * i + 1),\n result_base_tile->GetValue(i, 1));\n\n \/\/ Double check that logical tile is functioning.\n EXPECT_EQ(result_base_tile->GetValue(i, 0),\n result_logical_tile->GetValue(0, i));\n EXPECT_EQ(result_base_tile->GetValue(i, 1),\n result_logical_tile->GetValue(1, i));\n }\n}\n\n\/\/ Materializing logical tile composed of two base tiles.\n\/\/ The materialized tile's columns are reordered as well.\nTEST(MaterializationTests, TwoBaseTilesWithReorderTest) {\n storage::VMBackend backend;\n const int tuple_count = 9;\n std::unique_ptr tile_group(\n ExecutorTestsUtil::CreateSimpleTileGroup(\n &backend,\n tuple_count));\n\n PopulateTiles(tile_group.get(), tuple_count);\n\n \/\/TODO WaTeRmArK\n \/\/ Create logical tile from two base tiles.\n storage::Tile *source_base_tile1 = tile_group->GetTile(0);\n const bool own_base_tiles = false;\n std::unique_ptr source_tile(\n executor::LogicalTileFactory::WrapBaseTiles(\n { source_base_tile1 },\n own_base_tiles));\n\n \/\/ Create materialization node for this test.\n \/\/TODO This should be deleted soon... Should we use default copy constructor?\n std::unique_ptr output_schema(catalog::Schema::CopySchema(\n &source_base_tile1->GetSchema()));\n std::unordered_map old_to_new_cols;\n\n unsigned int column_count = output_schema->GetColumnCount();\n for (id_t col = 0; col < column_count; col++) {\n \/\/ Create identity mapping.\n old_to_new_cols[col] = col;\n }\n planner::MaterializationNode node(\n std::move(old_to_new_cols),\n output_schema.release());\n\n \/\/ Pass them through materialization executor.\n executor::MaterializationExecutor executor(&node);\n MockExecutor child_executor;\n executor.AddChild(&child_executor);\n\n \/\/ Uneventful init...\n EXPECT_CALL(child_executor, SubInit())\n .WillOnce(Return(true));\n EXPECT_TRUE(executor.Init());\n\n \/\/ Where the main work takes place...\n EXPECT_CALL(child_executor, SubGetNextTile())\n .WillOnce(Return(source_tile.release()))\n .WillOnce(Return(nullptr));\n\n std::unique_ptr result_logical_tile(\n executor.GetNextTile());\n EXPECT_THAT(result_logical_tile, NotNull());\n EXPECT_THAT(executor.GetNextTile(), IsNull());\n\n \/\/ Verify that logical tile is only made up of a single base tile.\n int num_cols = result_logical_tile->NumCols();\n EXPECT_EQ(2, num_cols);\n storage::Tile *result_base_tile = result_logical_tile->GetBaseTile(0);\n EXPECT_THAT(result_base_tile, NotNull());\n EXPECT_EQ(result_logical_tile->GetBaseTile(1), result_base_tile);\n\n \/\/ Check that the base tile has the correct values.\n for (int i = 0; i < tuple_count; i++) {\n EXPECT_EQ(ValueFactory::GetIntegerValue(10 * i),\n result_base_tile->GetValue(i, 0));\n EXPECT_EQ(ValueFactory::GetIntegerValue(10 * i + 1),\n result_base_tile->GetValue(i, 1));\n\n \/\/ Double check that logical tile is functioning.\n EXPECT_EQ(result_base_tile->GetValue(i, 0),\n result_logical_tile->GetValue(0, i));\n EXPECT_EQ(result_base_tile->GetValue(i, 1),\n result_logical_tile->GetValue(1, i));\n }\n}\n\n} \/\/ namespace test\n} \/\/ namespace nstore\nFinished materialization tests.\/**\n * @brief Test cases for materialization node.\n *\n * Copyright(c) 2015, CMU\n *\/\n\n#include \n#include \n#include \n#include \n#include \n\n#include \"gtest\/gtest.h\"\n\n#include \"catalog\/manager.h\"\n#include \"catalog\/schema.h\"\n#include \"common\/types.h\"\n#include \"common\/value_factory.h\"\n#include \"executor\/logical_tile.h\"\n#include \"executor\/logical_tile_factory.h\"\n#include \"executor\/materialization_executor.h\"\n#include \"planner\/abstract_plan_node.h\"\n#include \"planner\/materialization_node.h\"\n#include \"storage\/tile.h\"\n#include \"storage\/tile_group.h\"\n#include \"storage\/tuple.h\"\n#include \"storage\/vm_backend.h\"\n\n#include \"executor\/executor_tests_util.h\"\n#include \"executor\/mock_executor.h\"\n#include \"harness.h\"\n\nusing ::testing::IsNull;\nusing ::testing::NotNull;\nusing ::testing::Return;\n\nnamespace nstore {\nnamespace test {\n\nnamespace {\n\n\/**\n * @brief Populates the tiles in the given tile-group in a specific manner.\n * @param tile_group Tile-group to populate with values.\n * @param num_rows Number of tuples to insert.\n *\n * This is a convenience function for the test cases.\n *\/\nvoid PopulateTiles(storage::TileGroup *tile_group, int num_rows) {\n \/\/ Create tuple schema from tile schemas.\n std::vector &tile_schemas = tile_group->GetTileSchemas();\n std::unique_ptr schema(\n catalog::Schema::AppendSchemaList(tile_schemas));\n\n \/\/ Ensure that the tile group created by ExecutorTestsUtil is as expected.\n assert(tile_schemas.size() == 2);\n assert(schema->GetColumnCount() == 4);\n\n \/\/ Insert tuples into tile_group.\n const bool allocate = true;\n const txn_id_t txn_id = GetTransactionId();\n for (int i = 0; i < num_rows; i++) {\n storage::Tuple tuple(schema.get(), allocate);\n tuple.SetValue(0, ValueFactory::GetIntegerValue(10 * i));\n tuple.SetValue(1, ValueFactory::GetIntegerValue(10 * i + 1));\n tuple.SetValue(2, ValueFactory::GetTinyIntValue(10 * i + 2));\n tuple.SetValue(\n 3,\n ValueFactory::GetStringValue(std::to_string(10 * i + 3),\n tile_group->GetTilePool(1)));\n tile_group->InsertTuple(txn_id, &tuple);\n }\n}\n\n} \/\/ namespace\n\n\/\/ \"Pass-through\" test case. There is nothing to materialize as\n\/\/ there is only one base tile in the logical tile.\nTEST(MaterializationTests, SingleBaseTileTest) {\n storage::VMBackend backend;\n const int tuple_count = 9;\n std::unique_ptr tile_group(\n ExecutorTestsUtil::CreateSimpleTileGroup(\n &backend,\n tuple_count));\n\n PopulateTiles(tile_group.get(), tuple_count);\n\n \/\/ Create logical tile from single base tile.\n storage::Tile *source_base_tile = tile_group->GetTile(0);\n const bool own_base_tiles = false;\n std::unique_ptr source_logical_tile(\n executor::LogicalTileFactory::WrapBaseTiles(\n { source_base_tile },\n own_base_tiles));\n\n \/\/ Create materialization node for this test.\n std::unique_ptr output_schema(catalog::Schema::CopySchema(\n &source_base_tile->GetSchema()));\n std::unordered_map old_to_new_cols;\n\n unsigned int column_count = output_schema->GetColumnCount();\n for (id_t col = 0; col < column_count; col++) {\n \/\/ Create identity mapping.\n old_to_new_cols[col] = col;\n }\n planner::MaterializationNode node(\n std::move(old_to_new_cols),\n output_schema.release());\n\n \/\/ Pass them through materialization executor.\n executor::MaterializationExecutor executor(&node);\n MockExecutor child_executor;\n executor.AddChild(&child_executor);\n\n \/\/ Uneventful init...\n EXPECT_CALL(child_executor, SubInit())\n .WillOnce(Return(true));\n EXPECT_TRUE(executor.Init());\n\n \/\/ Where the main work takes place...\n EXPECT_CALL(child_executor, SubGetNextTile())\n .WillOnce(Return(source_logical_tile.release()))\n .WillOnce(Return(nullptr));\n\n std::unique_ptr result_logical_tile(\n executor.GetNextTile());\n EXPECT_THAT(result_logical_tile, NotNull());\n EXPECT_THAT(executor.GetNextTile(), IsNull());\n\n \/\/ Verify that logical tile is only made up of a single base tile.\n int num_cols = result_logical_tile->NumCols();\n EXPECT_EQ(2, num_cols);\n storage::Tile *result_base_tile = result_logical_tile->GetBaseTile(0);\n EXPECT_THAT(result_base_tile, NotNull());\n EXPECT_TRUE(source_base_tile != result_base_tile);\n EXPECT_EQ(result_logical_tile->GetBaseTile(1), result_base_tile);\n\n \/\/ Check that the base tile has the correct values.\n for (int i = 0; i < tuple_count; i++) {\n EXPECT_EQ(ValueFactory::GetIntegerValue(10 * i),\n result_base_tile->GetValue(i, 0));\n EXPECT_EQ(ValueFactory::GetIntegerValue(10 * i + 1),\n result_base_tile->GetValue(i, 1));\n\n \/\/ Double check that logical tile is functioning.\n EXPECT_EQ(result_base_tile->GetValue(i, 0),\n result_logical_tile->GetValue(0, i));\n EXPECT_EQ(result_base_tile->GetValue(i, 1),\n result_logical_tile->GetValue(1, i));\n }\n}\n\n\/\/ Materializing logical tile composed of two base tiles.\n\/\/ The materialized tile's output columns are reordered.\n\/\/ Also, one of the columns is dropped.\nTEST(MaterializationTests, TwoBaseTilesWithReorderTest) {\n storage::VMBackend backend;\n const int tuple_count = 9;\n std::unique_ptr tile_group(\n ExecutorTestsUtil::CreateSimpleTileGroup(\n &backend,\n tuple_count));\n\n PopulateTiles(tile_group.get(), tuple_count);\n\n \/\/ Create logical tile from two base tiles.\n const std::vector source_base_tiles =\n { tile_group->GetTile(0), tile_group->GetTile(1) };\n const bool own_base_tiles = false;\n std::unique_ptr source_tile(\n executor::LogicalTileFactory::WrapBaseTiles(\n source_base_tiles,\n own_base_tiles));\n\n \/\/ Create materialization node for this test.\n \/\/ Construct output schema. We drop column 3 and reorder the others to 3,1,0.\n std::vector output_columns;\n \/\/ Note that Column 3 in the tile group is column 1 in the second tile.\n output_columns.push_back(source_base_tiles[1]->GetSchema().GetColumnInfo(1));\n output_columns.push_back(source_base_tiles[0]->GetSchema().GetColumnInfo(1));\n output_columns.push_back(source_base_tiles[0]->GetSchema().GetColumnInfo(0));\n std::unique_ptr output_schema(\n new catalog::Schema(output_columns));\n\n \/\/ Construct mapping using the ordering mentioned above.\n std::unordered_map old_to_new_cols;\n old_to_new_cols[3] = 0;\n old_to_new_cols[1] = 1;\n old_to_new_cols[0] = 2;\n planner::MaterializationNode node(\n std::move(old_to_new_cols),\n output_schema.release());\n\n \/\/ Pass them through materialization executor.\n executor::MaterializationExecutor executor(&node);\n MockExecutor child_executor;\n executor.AddChild(&child_executor);\n\n \/\/ Uneventful init...\n EXPECT_CALL(child_executor, SubInit())\n .WillOnce(Return(true));\n EXPECT_TRUE(executor.Init());\n\n \/\/ Where the main work takes place...\n EXPECT_CALL(child_executor, SubGetNextTile())\n .WillOnce(Return(source_tile.release()))\n .WillOnce(Return(nullptr));\n\n std::unique_ptr result_logical_tile(\n executor.GetNextTile());\n EXPECT_THAT(result_logical_tile, NotNull());\n EXPECT_THAT(executor.GetNextTile(), IsNull());\n\n \/\/ Verify that logical tile is only made up of a single base tile.\n int num_cols = result_logical_tile->NumCols();\n EXPECT_EQ(3, num_cols);\n storage::Tile *result_base_tile = result_logical_tile->GetBaseTile(0);\n EXPECT_THAT(result_base_tile, NotNull());\n EXPECT_EQ(result_base_tile, result_logical_tile->GetBaseTile(1));\n EXPECT_EQ(result_base_tile, result_logical_tile->GetBaseTile(2));\n\n \/\/ Check that the base tile has the correct values.\n for (int i = 0; i < tuple_count; i++) {\n \/\/ Output column 2.\n EXPECT_EQ(ValueFactory::GetIntegerValue(10 * i),\n result_base_tile->GetValue(i, 2));\n \/\/ Output column 1.\n EXPECT_EQ(ValueFactory::GetIntegerValue(10 * i + 1),\n result_base_tile->GetValue(i, 1));\n \/\/ Output column 0.\n Value string_value(\n ValueFactory::GetStringValue(std::to_string(10 * i + 3)));\n EXPECT_EQ(string_value,\n result_base_tile->GetValue(i, 0));\n string_value.FreeUninlinedData();\n\n \/\/ Double check that logical tile is functioning.\n EXPECT_EQ(result_base_tile->GetValue(i, 0),\n result_logical_tile->GetValue(0, i));\n EXPECT_EQ(result_base_tile->GetValue(i, 1),\n result_logical_tile->GetValue(1, i));\n EXPECT_EQ(result_base_tile->GetValue(i, 2),\n result_logical_tile->GetValue(2, i));\n }\n}\n\n} \/\/ namespace test\n} \/\/ namespace nstore\n<|endoftext|>"} {"text":"#include \n\n#include \n#include \n#include \n\n#include \n\n#include \n#include \n\n#include \n\ntemplate void testNonSquare()\n{\n ALEPH_TEST_BEGIN( \"Boundary matrix reduction for non-square matrices\" );\n\n using namespace aleph;\n using namespace topology;\n using namespace representations;\n\n using Representation = Vector;\n using Matrix = BoundaryMatrix;\n using Index = typename Matrix::Index;\n\n \/\/ Rectangular matrix reduction --------------------------------------\n\n Matrix M;\n M.setNumColumns( Index(4) );\n\n std::vector columnA = { 1+4, 3+4, 4+4 };\n std::vector columnB = { 2+4, 7+4, 8+4 };\n std::vector columnC = { 5+4, 4+4, 7+4 };\n std::vector columnE = { 1+4, 2+4, 5+4, 6+4 };\n\n M.setColumn( 0, columnA.begin(), columnA.end() );\n M.setColumn( 1, columnB.begin(), columnB.end() );\n M.setColumn( 2, columnC.begin(), columnC.end() );\n M.setColumn( 3, columnE.begin(), columnE.end() );\n\n using StandardAlgorithm = aleph::persistentHomology::algorithms::StandardRectangular;\n StandardAlgorithm algorithm;\n\n algorithm( M );\n\n Index i;\n bool valid;\n\n std::tie( i, valid ) = M.getMaximumIndex( 3 );\n\n ALEPH_ASSERT_EQUAL( valid, true );\n ALEPH_ASSERT_EQUAL( i , 6+4 );\n\n \/\/ Quadratic matrix reduction w\/ constraints -------------------------\n\n Matrix N;\n N.setNumColumns( Index(12) );\n\n columnA = { 1+3, 3+3, 4+3 };\n columnB = { 2+3, 7+3, 8+3 };\n columnC = { 5+3, 4+3, 7+3 };\n columnE = { 1+3, 2+3, 5+3, 6+3 };\n\n N.setColumn( 0, columnA.begin(), columnA.end() );\n N.setColumn( 1, columnB.begin(), columnB.end() );\n N.setColumn( 2, columnC.begin(), columnC.end() );\n N.setColumn( 3, columnE.begin(), columnE.end() );\n\n auto N1 = N;\n\n algorithm( N1 );\n\n std::tie( i, valid ) = N1.getMaximumIndex( 3 );\n\n ALEPH_ASSERT_EQUAL( valid, true );\n ALEPH_ASSERT_EQUAL( i , 6+3 );\n\n {\n auto pairing = calculatePersistencePairing( N, false );\n std::cerr << \"Pairing (quadratic, original):\\n\"\n << pairing << \"\\n\";\n }\n\n std::cerr << std::string( 72, '-' ) << \"\\n\"\n << \"Original space:\\n\"\n << std::string( 72, '-' ) << \"\\n\\n\";\n\n for( Index j = 0; j < N1.getNumColumns(); j++ )\n {\n std::tie( i, valid ) = N1.getMaximumIndex( j );\n\n if( valid )\n std::cerr << j << \": \" << i << \"\\n\";\n else\n std::cerr << j << \": -\" << \"\\n\";\n }\n\n\n auto N2 = N.dualize();\n\n algorithm( N2 );\n\n std::cerr << N2 << \"\\n\";\n\n std::cerr << std::string( 72, '-' ) << \"\\n\"\n << \"Dual space:\\n\"\n << std::string( 72, '-' ) << \"\\n\\n\";\n\n for( Index j = 0; j < N2.getNumColumns(); j++ )\n {\n std::tie( i, valid ) = N2.getMaximumIndex( j );\n\n if( valid )\n std::cerr << 12 - 1 - i << \": \" << 12 - 1 - j << \"\\n\";\n else\n std::cerr << 12 - 1 - j << \": -\" << \"\\n\";\n }\n\n auto N3 = N.dualize();\n auto pairing = calculatePersistencePairing( N3, false );\n\n \/\/ Quadratic matrix with re-ordering ---------------------------------\n\n Matrix O;\n O.setNumColumns( Index(12) );\n\n columnA = { 1-1, 5-1, 6-1 };\n columnB = { 2-1, 7-1, 8-1 };\n columnC = { 3-1, 6-1, 7-1 };\n columnE = { 4-1, 5-1, 8-1 };\n\n O.setColumn( 8, columnA.begin(), columnA.end() );\n O.setColumn( 9, columnB.begin(), columnB.end() );\n O.setColumn(10, columnC.begin(), columnC.end() );\n O.setColumn(11, columnE.begin(), columnE.end() );\n\n pairing = calculatePersistencePairing( O, false );\n\n std::cerr << \"Pairing (quadratic, with re-ordering):\\n\";\n\n for( auto&& pair : pairing )\n if( pair.first <= 4 )\n std::cerr << pair.first << \": \" << pair.second << \"\\n\";\n\n \/\/ Quadratic matrix with partition -----------------------------------\n\n Matrix P;\n P.setNumColumns( Index(12) );\n\n columnA = { 1-1, 5-1+4, 6-1+4 };\n columnB = { 2-1, 7-1+4, 8-1+4 };\n columnC = { 3-1, 6-1+4, 7-1+4 };\n columnE = { 4-1, 5-1+4, 8-1+4 };\n\n P.setColumn( 4, columnA.begin(), columnA.end() );\n P.setColumn( 5, columnB.begin(), columnB.end() );\n P.setColumn( 6, columnC.begin(), columnC.end() );\n P.setColumn( 7, columnE.begin(), columnE.end() );\n\n pairing = calculatePersistencePairing( P, false );\n\n std::cerr << \"Pairing (quadratic, with partion-based re-ordering [singular]):\\n\";\n\n for( auto&& pair : pairing )\n if( pair.first <= 7 )\n std::cerr << pair.first << \": \" << pair.second << \"\\n\";\n\n pairing = calculatePersistencePairing( P.dualize(), false );\n\n std::cerr << \"Pairing (quadratic, with partion-based re-ordering):\\n\";\n\n for( auto&& pair : pairing )\n if( pair.first <= 7 )\n std::cerr << pair.first << \": \" << pair.second << \"\\n\";\n\n pairing = calculatePersistencePairing( P.dualize(), false, 8 );\n\n std::cerr << \"Pairing (quadratic, with partion-based re-ordering and cut-off):\\n\"\n << pairing << \"\\n\";\n\n ALEPH_TEST_END();\n}\n\ntemplate void reduceBoundaryMatrix( const M& m )\n{\n ALEPH_TEST_BEGIN( \"Boundary matrix reduction\" );\n\n ALEPH_ASSERT_THROW( m.getNumColumns() > 0 );\n\n using StandardAlgorithm = aleph::persistentHomology::algorithms::Standard;\n using TwistAlgorithm = aleph::persistentHomology::algorithms::Twist;\n\n using Index = typename M::Index;\n using Pairing = aleph::PersistencePairing;\n\n std::vector pairings;\n pairings.reserve( 4 );\n\n pairings.push_back( aleph::calculatePersistencePairing( m ) );\n pairings.push_back( aleph::calculatePersistencePairing( m.dualize() ) );\n\n pairings.push_back( aleph::calculatePersistencePairing( m ) );\n pairings.push_back( aleph::calculatePersistencePairing( m.dualize() ) );\n\n ALEPH_ASSERT_THROW( m != m.dualize() );\n ALEPH_ASSERT_THROW( m == m.dualize().dualize() );\n\n for( auto&& pairing : pairings )\n {\n ALEPH_ASSERT_THROW( pairing.empty() == false );\n ALEPH_ASSERT_THROW( pairing.size() == 4 );\n }\n\n for( auto&& pairing1 : pairings )\n for( auto&& pairing2 : pairings )\n ALEPH_ASSERT_THROW( pairing1 == pairing2 );\n\n ALEPH_ASSERT_THROW( pairings.front().contains( Index(0) ) );\n ALEPH_ASSERT_THROW( pairings.front().contains( Index(1), Index(3) ) );\n ALEPH_ASSERT_THROW( pairings.front().contains( Index(2), Index(4) ) );\n ALEPH_ASSERT_THROW( pairings.front().contains( Index(5), Index(6) ) );\n\n ALEPH_TEST_END();\n}\n\ntemplate void setupBoundaryMatrix()\n{\n using namespace aleph;\n using namespace topology;\n using namespace representations;\n\n ALEPH_TEST_BEGIN( \"Boundary matrix setup & loading\" );\n\n using Set = Set;\n using Vector = Vector;\n\n auto m1 = BoundaryMatrix::load( CMAKE_SOURCE_DIR + std::string( \"\/tests\/input\/Triangle.txt\" ) );\n auto m2 = BoundaryMatrix::load( CMAKE_SOURCE_DIR + std::string( \"\/tests\/input\/Triangle.txt\" ) );\n\n reduceBoundaryMatrix( m1 );\n reduceBoundaryMatrix( m2 );\n\n ALEPH_TEST_END();\n}\n\nint main()\n{\n setupBoundaryMatrix ();\n setupBoundaryMatrix();\n setupBoundaryMatrix();\n setupBoundaryMatrix();\n\n testNonSquare ();\n testNonSquare ();\n testNonSquare ();\n testNonSquare();\n}\nExtended test case for dualized boundary matrices#include \n\n#include \n#include \n#include \n\n#include \n\n#include \n#include \n\n#include \n#include \n\ntemplate void testNonSquare()\n{\n ALEPH_TEST_BEGIN( \"Boundary matrix reduction for non-square matrices\" );\n\n using namespace aleph;\n using namespace topology;\n using namespace representations;\n\n using Representation = Vector;\n using Matrix = BoundaryMatrix;\n using Index = typename Matrix::Index;\n\n \/\/ Rectangular matrix reduction --------------------------------------\n\n Matrix M;\n M.setNumColumns( Index(4) );\n\n std::vector columnA = { 1+4, 3+4, 4+4 };\n std::vector columnB = { 2+4, 7+4, 8+4 };\n std::vector columnC = { 5+4, 4+4, 7+4 };\n std::vector columnE = { 1+4, 2+4, 5+4, 6+4 };\n\n M.setColumn( 0, columnA.begin(), columnA.end() );\n M.setColumn( 1, columnB.begin(), columnB.end() );\n M.setColumn( 2, columnC.begin(), columnC.end() );\n M.setColumn( 3, columnE.begin(), columnE.end() );\n\n using StandardAlgorithm = aleph::persistentHomology::algorithms::StandardRectangular;\n StandardAlgorithm algorithm;\n\n algorithm( M );\n\n Index i;\n bool valid;\n\n std::tie( i, valid ) = M.getMaximumIndex( 3 );\n\n ALEPH_ASSERT_EQUAL( valid, true );\n ALEPH_ASSERT_EQUAL( i , 6+4 );\n\n \/\/ Quadratic matrix reduction w\/ constraints -------------------------\n\n Matrix N;\n N.setNumColumns( Index(12) );\n\n columnA = { 1+3, 3+3, 4+3 };\n columnB = { 2+3, 7+3, 8+3 };\n columnC = { 5+3, 4+3, 7+3 };\n columnE = { 1+3, 2+3, 5+3, 6+3 };\n\n N.setColumn( 0, columnA.begin(), columnA.end() );\n N.setColumn( 1, columnB.begin(), columnB.end() );\n N.setColumn( 2, columnC.begin(), columnC.end() );\n N.setColumn( 3, columnE.begin(), columnE.end() );\n\n auto N1 = N;\n\n algorithm( N1 );\n\n std::tie( i, valid ) = N1.getMaximumIndex( 3 );\n\n ALEPH_ASSERT_EQUAL( valid, true );\n ALEPH_ASSERT_EQUAL( i , 6+3 );\n\n {\n auto pairing = calculatePersistencePairing( N, false );\n std::cerr << \"Pairing (quadratic, original):\\n\"\n << pairing << \"\\n\";\n }\n\n std::cerr << std::string( 72, '-' ) << \"\\n\"\n << \"Original space:\\n\"\n << std::string( 72, '-' ) << \"\\n\\n\";\n\n for( Index j = 0; j < N1.getNumColumns(); j++ )\n {\n std::tie( i, valid ) = N1.getMaximumIndex( j );\n\n if( valid )\n std::cerr << j << \": \" << i << \"\\n\";\n else\n std::cerr << j << \": -\" << \"\\n\";\n }\n\n\n auto N2 = N.dualize();\n\n algorithm( N2 );\n\n std::cerr << N2 << \"\\n\";\n\n std::cerr << std::string( 72, '-' ) << \"\\n\"\n << \"Dual space:\\n\"\n << std::string( 72, '-' ) << \"\\n\\n\";\n\n for( Index j = 0; j < N2.getNumColumns(); j++ )\n {\n std::tie( i, valid ) = N2.getMaximumIndex( j );\n\n if( valid )\n std::cerr << 12 - 1 - i << \": \" << 12 - 1 - j << \"\\n\";\n else\n std::cerr << 12 - 1 - j << \": -\" << \"\\n\";\n }\n\n auto N3 = N.dualize();\n auto pairing = calculatePersistencePairing( N3, false );\n\n \/\/ Quadratic matrix with re-ordering ---------------------------------\n\n Matrix O;\n O.setNumColumns( Index(12) );\n\n columnA = { 1-1, 5-1, 6-1 };\n columnB = { 2-1, 7-1, 8-1 };\n columnC = { 3-1, 6-1, 7-1 };\n columnE = { 4-1, 5-1, 8-1 };\n\n O.setColumn( 8, columnA.begin(), columnA.end() );\n O.setColumn( 9, columnB.begin(), columnB.end() );\n O.setColumn(10, columnC.begin(), columnC.end() );\n O.setColumn(11, columnE.begin(), columnE.end() );\n\n pairing = calculatePersistencePairing( O, false );\n\n std::cerr << \"Pairing (quadratic, with re-ordering):\\n\";\n\n for( auto&& pair : pairing )\n if( pair.first <= 4 )\n std::cerr << pair.first << \": \" << pair.second << \"\\n\";\n\n \/\/ Quadratic matrix with partition -----------------------------------\n\n Matrix P;\n P.setNumColumns( Index(12) );\n\n columnA = { 1-1, 5-1+4, 6-1+4 };\n columnB = { 2-1, 7-1+4, 8-1+4 };\n columnC = { 3-1, 6-1+4, 7-1+4 };\n columnE = { 4-1, 5-1+4, 8-1+4 };\n\n P.setDimension( 0, 1 );\n P.setDimension( 1, 1 );\n P.setDimension( 2, 1 );\n P.setDimension( 3, 1 );\n\n P.setColumn( 4, columnA.begin(), columnA.end() );\n P.setColumn( 5, columnB.begin(), columnB.end() );\n P.setColumn( 6, columnC.begin(), columnC.end() );\n P.setColumn( 7, columnE.begin(), columnE.end() );\n\n P.setDimension( 8, 1 );\n P.setDimension( 9, 1 );\n P.setDimension(10, 1 );\n P.setDimension(11, 1 );\n\n using Pairing = decltype(pairing);\n using Pair = typename Pairing::ValueType;\n\n auto RemoveNeutral = [] ( const Pair& pair )\n {\n return pair.first >= 8;\n };\n\n {\n auto pairing1 = calculatePersistencePairing( P, false );\n pairing1.erase( std::remove_if( pairing1.begin(), pairing1.end(), RemoveNeutral ), pairing1.end() );\n\n auto pairing2 = calculatePersistencePairing( P, true );\n pairing2.erase( std::remove_if( pairing2.begin(), pairing2.end(), RemoveNeutral ), pairing2.end() );\n\n auto pairing3 = calculatePersistencePairing( P, true, 8 );\n\n ALEPH_ASSERT_THROW( pairing1 == pairing2 );\n ALEPH_ASSERT_THROW( pairing2 == pairing3 );\n }\n\n ALEPH_TEST_END();\n}\n\ntemplate void reduceBoundaryMatrix( const M& m )\n{\n ALEPH_TEST_BEGIN( \"Boundary matrix reduction\" );\n\n ALEPH_ASSERT_THROW( m.getNumColumns() > 0 );\n\n using StandardAlgorithm = aleph::persistentHomology::algorithms::Standard;\n using TwistAlgorithm = aleph::persistentHomology::algorithms::Twist;\n\n using Index = typename M::Index;\n using Pairing = aleph::PersistencePairing;\n\n std::vector pairings;\n pairings.reserve( 4 );\n\n pairings.push_back( aleph::calculatePersistencePairing( m ) );\n pairings.push_back( aleph::calculatePersistencePairing( m.dualize() ) );\n\n pairings.push_back( aleph::calculatePersistencePairing( m ) );\n pairings.push_back( aleph::calculatePersistencePairing( m.dualize() ) );\n\n ALEPH_ASSERT_THROW( m != m.dualize() );\n ALEPH_ASSERT_THROW( m == m.dualize().dualize() );\n\n for( auto&& pairing : pairings )\n {\n ALEPH_ASSERT_THROW( pairing.empty() == false );\n ALEPH_ASSERT_THROW( pairing.size() == 4 );\n }\n\n for( auto&& pairing1 : pairings )\n for( auto&& pairing2 : pairings )\n ALEPH_ASSERT_THROW( pairing1 == pairing2 );\n\n ALEPH_ASSERT_THROW( pairings.front().contains( Index(0) ) );\n ALEPH_ASSERT_THROW( pairings.front().contains( Index(1), Index(3) ) );\n ALEPH_ASSERT_THROW( pairings.front().contains( Index(2), Index(4) ) );\n ALEPH_ASSERT_THROW( pairings.front().contains( Index(5), Index(6) ) );\n\n ALEPH_TEST_END();\n}\n\ntemplate void setupBoundaryMatrix()\n{\n using namespace aleph;\n using namespace topology;\n using namespace representations;\n\n ALEPH_TEST_BEGIN( \"Boundary matrix setup & loading\" );\n\n using Set = Set;\n using Vector = Vector;\n\n auto m1 = BoundaryMatrix::load( CMAKE_SOURCE_DIR + std::string( \"\/tests\/input\/Triangle.txt\" ) );\n auto m2 = BoundaryMatrix::load( CMAKE_SOURCE_DIR + std::string( \"\/tests\/input\/Triangle.txt\" ) );\n\n reduceBoundaryMatrix( m1 );\n reduceBoundaryMatrix( m2 );\n\n ALEPH_TEST_END();\n}\n\nint main()\n{\n setupBoundaryMatrix ();\n setupBoundaryMatrix();\n setupBoundaryMatrix();\n setupBoundaryMatrix();\n\n testNonSquare ();\n testNonSquare ();\n testNonSquare ();\n testNonSquare();\n}\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: tkresmgr.hxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: ihi $ $Date: 2006-12-20 13:52:08 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef _TOOLKIT_HELPER_TKRESMGR_HXX_\n#define _TOOLKIT_HELPER_TKRESMGR_HXX_\n\n#ifndef _RTL_USTRING_HXX_\n#include \n#endif\n#ifndef _SV_IMAGE_HXX\n#include \n#endif\n\nclass SimpleResMgr;\nclass ResMgr;\n\n#define TK_RES_STRING(id) TkResMgr::loadString(id)\n#define TK_RES_IMAGE(id) TkResMgr::loadImage(id)\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ TkResMgr\n\/\/ -----------------------------------------------------------------------------\n\nclass TkResMgr\n{\n static SimpleResMgr* m_pSimpleResMgr;\n static ResMgr* m_pResMgr;\n\nprivate:\n \/\/ no instantiation allowed\n TkResMgr() { }\n ~TkResMgr() { }\n\n \/\/ we'll instantiate one static member of the following class,\n \/\/ which in it's dtor ensures that m_pSimpleResMgr will be deleted\n class EnsureDelete\n {\n public:\n EnsureDelete() { }\n ~EnsureDelete();\n };\n friend class EnsureDelete;\n\nprotected:\n static void ensureImplExists();\n\npublic:\n \/\/ loads the string with the specified resource id\n static ::rtl::OUString loadString( sal_uInt16 nResId );\n\n \/\/ loads the image with the specified resource id\n static Image loadImage( sal_uInt16 nResId );\n};\n\n\n#endif \/\/ _TOOLKIT_HELPER_TKRESMGR_HXX_\n\nINTEGRATION: CWS changefileheader (1.3.176); FILE MERGED 2008\/04\/01 16:00:54 thb 1.3.176.2: #i85898# Stripping all external header guards 2008\/03\/28 15:40:10 rt 1.3.176.1: #i87441# Change license header to LPGL v3.\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2008 by Sun Microsystems, Inc.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: tkresmgr.hxx,v $\n * $Revision: 1.4 $\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * \n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n#ifndef _TOOLKIT_HELPER_TKRESMGR_HXX_\n#define _TOOLKIT_HELPER_TKRESMGR_HXX_\n\n#include \n#include \n\nclass SimpleResMgr;\nclass ResMgr;\n\n#define TK_RES_STRING(id) TkResMgr::loadString(id)\n#define TK_RES_IMAGE(id) TkResMgr::loadImage(id)\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ TkResMgr\n\/\/ -----------------------------------------------------------------------------\n\nclass TkResMgr\n{\n static SimpleResMgr* m_pSimpleResMgr;\n static ResMgr* m_pResMgr;\n\nprivate:\n \/\/ no instantiation allowed\n TkResMgr() { }\n ~TkResMgr() { }\n\n \/\/ we'll instantiate one static member of the following class,\n \/\/ which in it's dtor ensures that m_pSimpleResMgr will be deleted\n class EnsureDelete\n {\n public:\n EnsureDelete() { }\n ~EnsureDelete();\n };\n friend class EnsureDelete;\n\nprotected:\n static void ensureImplExists();\n\npublic:\n \/\/ loads the string with the specified resource id\n static ::rtl::OUString loadString( sal_uInt16 nResId );\n\n \/\/ loads the image with the specified resource id\n static Image loadImage( sal_uInt16 nResId );\n};\n\n\n#endif \/\/ _TOOLKIT_HELPER_TKRESMGR_HXX_\n\n<|endoftext|>"} {"text":"#include \"stdio.h\"\n#include \"stdlib.h\"\n#include \n#define MAXSTRLEN 255 \/\/ 用户可在255以内定义最大串长\ntypedef unsigned char SString[MAXSTRLEN+1];\t\/\/ 0号单元存放串的长度\n\nvoid get_next(SString T,int next[]){\n\/\/ 算法4.7\n\/\/ 求模式串T的next函数值并存入数组next\n \/\/ 请补全代码\n\tint i,j;\n\tnext[1]=0;\n\tj=0;\n\twhile(iupdate uoj8591#include \"stdio.h\"\n#include \"stdlib.h\"\n#include \n#define MAXSTRLEN 255 \/\/ 用户可在255以内定义最大串长\ntypedef unsigned char SString[MAXSTRLEN+1];\t\/\/ 0号单元存放串的长度\n\nvoid get_next(SString T,int next[]){\n\n\tint i,j;\n\tnext[1]=0;\n\tj=0;\n\twhile(i"} {"text":"#pragma once\n#include \n\nstruct vec3s {\n float r, theta, phi;\n float operator*( const vec3s & v );\n void rotate( float dtheta, float dphi );\n friend vec3s & operator += ( vec3s & lhs, const vec3s & rhs );\n friend vec3s & operator -= ( vec3s & lhs, const vec3s & rhs );\n};\n\nstruct vec3d {\n float x, y, z;\n vec3d( const vec3s & v);\n float operator*( const vec3d & v );\n};\n\ninline float _fmod( float x, float y ) { return fmod( fmod( x, y ) + y, y ); }\n[add] types.hpp#pragma once\n#include \n#include \"types.hpp\"\n\nstruct vec3s {\n float r, theta, phi;\n float operator*( const vec3s & v );\n void rotate( float dtheta, float dphi );\n friend vec3s & operator += ( vec3s & lhs, const vec3s & rhs );\n friend vec3s & operator -= ( vec3s & lhs, const vec3s & rhs );\n};\n\nstruct vec3d {\n float x, y, z;\n vec3d( const vec3s & v);\n float operator*( const vec3d & v );\n};\n\ninline float _fmod( float x, float y ) { return fmod( fmod( x, y ) + y, y ); }\n<|endoftext|>"} {"text":"\/\/\n\/\/ Copyright Copyright 2009-2019, AMT – The Association For Manufacturing Technology (“AMT”)\n\/\/ All rights reserved.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/\n#include \"version.h\"\n#include \n#include \n\nvoid PrintMTConnectAgentVersion()\n{\n\tprintf(\"%s - built on \" __TIMESTAMP__ \"\\n\",\n\t\tGetAgentVersion().c_str());\n}\n\nstd::string GetAgentVersion()\n{\n\tstd::stringstream verStream;\n\tverStream << \"MTConnect Agent Version \"\n\t\t<< AGENT_VERSION_MAJOR << \".\"\n\t\t<< AGENT_VERSION_MINOR << \".\"\n\t\t<< AGENT_VERSION_PATCH << \".\"\n\t\t<< AGENT_VERSION_BUILD;\n\tif(strlen(AGENT_VERSION_RC))\n\t\tverStream << \" (\" << AGENT_VERSION_RC << \")\";\n\treturn verStream.str();\n}Moved GetAgentVersion to precede use. \/\/\n\/\/ Copyright Copyright 2009-2019, AMT – The Association For Manufacturing Technology (“AMT”)\n\/\/ All rights reserved.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/\n#include \"version.h\"\n#include \n#include \n\n\nstd::string GetAgentVersion()\n{\n std::stringstream verStream;\n verStream << \"MTConnect Agent Version \"\n << AGENT_VERSION_MAJOR << \".\"\n << AGENT_VERSION_MINOR << \".\"\n << AGENT_VERSION_PATCH << \".\"\n << AGENT_VERSION_BUILD;\n if(strlen(AGENT_VERSION_RC))\n verStream << \" (\" << AGENT_VERSION_RC << \")\";\n return verStream.str();\n}\n\nvoid PrintMTConnectAgentVersion()\n{\n\tprintf(\"%s - built on \" __TIMESTAMP__ \"\\n\",\n\t\tGetAgentVersion().c_str());\n}\n\n<|endoftext|>"} {"text":"#pragma once\n \n#include \n#include \n#include \n#include \n#include \n#include \n \nnamespace MotionPlanning\n{\n template\n class TabuSearch\n {\n int short_memory_size;\n std::deque short_memory;\n std::function fitness;\n std::function random;\n std::function(T)> neighbours;\n public:\n TabuSearch(int short_memory_size, std::function fitness, std::function random, std::function(T)> neighbours)\n : short_memory_size(short_memory_size), short_memory(short_memory_size, random()), fitness(fitness), random(random), neighbours(neighbours) { };\n \n T explore(int max_attempts)\n {\n T current = short_memory.front();\n T best = current;\n float best_fitness = fitness(best);\n for (int i = 0; i < max_attempts; i++)\n {\n auto possibles = neighbours(current);\n \n for (auto& sm : short_memory)\n {\n auto it = std::find(possibles.begin(), possibles.end(), sm);\n if (it != possibles.end())\n {\n possibles.erase(it);\n }\n }\n if (possibles.size() == 0)\n {\n break;\n }\n \n std::vector> scores;\n std::transform(possibles.begin(), possibles.end(), std::inserter(scores, scores.begin()), [&](T p) { return std::pair(fitness(p), p); });\n std::sort(scores.begin(), scores.end(), std::greater>());\n \n for (auto& kvp : scores)\n {\n short_memory.pop_back();\n short_memory.push_front(kvp.second);\n if (kvp.first > best_fitness)\n {\n best = kvp.second;\n best_fitness = kvp.first;\n }\n current = kvp.second;\n }\n }\n \n return best;\n }\n };\n}change class to be free function#pragma once\n \n#include \n#include \n#include \n#include \n#include \n#include \n \nnamespace tabu\n{\n template\n T search(int max_attempts,\n int short_memory_size,\n std::function fitness,\n std::function random,\n std::function(T)> neighbours)\n {\n std::deque short_memory(short_memory_size, random());\n T current = short_memory.front();\n T best = current;\n float best_fitness = fitness(best);\n for (int i = 0; i < max_attempts; i++)\n {\n auto possibles = neighbours(current);\n\n for (auto& sm : short_memory)\n {\n auto it = std::find(possibles.begin(), possibles.end(), sm);\n if (it != possibles.end())\n {\n possibles.erase(it);\n }\n }\n if (possibles.size() == 0)\n {\n break;\n }\n\n std::vector> scores;\n std::transform(possibles.begin(), possibles.end(), std::inserter(scores, scores.begin()), [&](T p) { return std::pair(fitness(p), p); });\n std::sort(scores.begin(), scores.end(), std::greater>());\n\n for (auto& kvp : scores)\n {\n short_memory.pop_back();\n short_memory.push_front(kvp.second);\n if (kvp.first > best_fitness)\n {\n best = kvp.second;\n best_fitness = kvp.first;\n }\n current = kvp.second;\n }\n }\n\n return best;\n }\n}<|endoftext|>"} {"text":"\n#include \"..\/interface\/DrawTree.h\"\n#include \"..\/src\/UserFunctions.cc\"\n\n\/\/\n\/\/ Example function to show how the package works\n\/\/ There are four objects: Color, ToPlot, Dataset, and DrawTree\n\/\/ - Color is simply a holder for custom colors \n\/\/ - This statement will show them: Color::plotTheColors();\n\/\/ - ToPlot holds the plotted variable, selection, plot dimensions at its core\n\/\/ - Dataset holds an individual physics dataset with\n\/\/ - DrawTree is the driver of it all, incorporating the above three\n\/\/ \n\/\/ \n\nvoid Example() {\n \n \/\/The object that draws it all\n DrawTree * dt = new DrawTree(\"tree\",vError);\n\n \/\/Set some various options\n dt->setLogy(true);\n dt->setDrawmcerr(true);\n dt->setDostack(true);\n dt->setLumi(1000);\n dt->setInframe(false);\n dt->setHasdata(true);\n dt->setDrawratio(true);\n\n \/\/Custom function to add all datasets you want\n \/\/See function to see how to add datasets to the DrawTree object by hand\n dt->autoAddDatasets(\"path\/to\/the\/root\/files\",\"fullqcd ttbar wjets singlet zinv data\",\"*.root\");\n\n \/\/Add (one or more) 'ToPlot' which sets the selection, plotted variable, plot dimensions \n \/\/This will plot HT and MHT variables\n dt->addVar(ToPlot(\"MHT>200&&Leptons==0&&BTags>=0&&NJets>3&&HT>500&&JetID>0\",\"HT\",\"\",\"\",\"\",50,500,2500));\n dt->addVar(ToPlot(\"MHT>200&&Leptons==0&&BTags>=0&&NJets>3&&HT>500&&JetID>0\",\"MHT\",\"\",\"\",\"\",50,200,2200));\n\n\n \/\/Function plots N-1 style in first argument - see function for full details\n \/\/dt->Nminus1plots(ToPlot(\"HT>500$$MHT>200$$(Leptons==0)$$BTags>=0$$NJets>3$$MinDeltaPhi>0.5\",\"HT\",\"\",\"\",\"(isoPionTracks+isoElectronTracks+isoMuonTracks==0)&&(JetID>0)\",40,0,4000),\"$$\");\n \n \/\/Makes cutflow table with various options - see function for full details\n \/\/dt->cutflow(\"1$$HT>500$$MHT>200$$(Leptons==0)$$NJets>3\",\"BTags==0$$BTags==1$$BTags>=2\",\"\",\"No Cut$$HT>500$$MHT>200$$Lepton veto$$NJet>3$$NBjet==0$$NBjet==1$$NBjet>=2\",\"\");\n\n \/\/Plot two sets of plots, with and without log y-scale\n dt->plot();\n dt->setLogy(false);\n dt->plot();\n\n \/\/Delete the object, always\n delete dt;\n\n exit(0);\n\n}\n\nadd more descriptions to example\n#include \"..\/interface\/DrawTree.h\"\n#include \"..\/src\/UserFunctions.cc\"\n\n\/\/\n\/\/ Example function to show how the package works\n\/\/ There are four objects: Color, ToPlot, Dataset, and DrawTree\n\/\/ - Color is simply a holder for custom colors \n\/\/ - This statement will show them: Color::plotTheColors();\n\/\/ - ToPlot holds the plotted variable, selection, plot dimensions at its core\n\/\/ - Dataset holds an individual physics dataset as well as a Color\n\/\/ - DrawTree is the driver of it all, incorporating the above three\n\/\/ - Use ToPlot to graph variable from Dataset(s)\n\/\/ \n\/\/ The style used is the 2015 RunII CMS style \n\/\/ \n\nvoid Example() {\n \n \/\/The object that draws it all\n DrawTree * dt = new DrawTree(\"tree\",vError);\n\n \/\/Set some various options\n \/\/Many other options are available\n dt->setLogy(true);\n dt->setDrawmcerr(true);\n dt->setDostack(true);\n dt->setLumi(1000);\n dt->setInframe(false);\n dt->setHasdata(true);\n dt->setDrawratio(true);\n\n \/\/Custom function to add all datasets you want\n \/\/See function to see how to add datasets to the DrawTree object by hand\n dt->autoAddDatasets(\"path\/to\/the\/root\/files\",\"fullqcd ttbar wjets singlet zinv data\",\"*.root\");\n\n \/\/Add (one or more) 'ToPlot' which sets the selection, plotted variable, plot dimensions \n \/\/Has some more options as well, including ability to use pre-defined options for variables\n \/\/ \n \/\/This will plot HT and MHT variables\n dt->addVar(ToPlot(\"MHT>200&&Leptons==0&&BTags>=0&&NJets>3&&HT>500&&JetID>0\",\"HT\",\"\",\"\",\"\",50,500,2500));\n dt->addVar(ToPlot(\"MHT>200&&Leptons==0&&BTags>=0&&NJets>3&&HT>500&&JetID>0\",\"MHT\",\"\",\"\",\"\",50,200,2200));\n\n \/\/Function plots N-1 style in first argument - see function for full details\n \/\/dt->Nminus1plots(ToPlot(\"HT>500$$MHT>200$$(Leptons==0)$$BTags>=0$$NJets>3$$MinDeltaPhi>0.5\",\"HT\",\"\",\"\",\"(isoPionTracks+isoElectronTracks+isoMuonTracks==0)&&(JetID>0)\",40,0,4000),\"$$\");\n \n \/\/Makes cutflow table with various options - see function for full details\n \/\/dt->cutflow(\"1$$HT>500$$MHT>200$$(Leptons==0)$$NJets>3\",\"BTags==0$$BTags==1$$BTags>=2\",\"\",\"No Cut$$HT>500$$MHT>200$$Lepton veto$$NJet>3$$NBjet==0$$NBjet==1$$NBjet>=2\",\"\");\n\n \/\/Plot two sets of plots, with and without log y-scale\n dt->plot();\n dt->setLogy(false);\n dt->plot();\n\n \/\/Delete the object, always\n delete dt;\n\n exit(0);\n\n}\n\n<|endoftext|>"} {"text":"#include \"ModuleImporter.h\"\n#include \"Application.h\"\n#include \"ImportMesh.h\"\n#include \"ImportMaterial.h\"\n#include \"CompTransform.h\"\n\n\nModuleImporter::ModuleImporter(bool start_enabled) : Module(start_enabled)\n{\n\t\/\/char ownPth[MAX_PATH];\n\n\t\/\/\/\/ Will contain exe path\n\t\/\/HMODULE hModule = GetModuleHandle(NULL);\n\t\/\/if (hModule != NULL)\n\t\/\/{\n\t\/\/\t\/\/ When passing NULL to GetModuleHandle, it returns handle of exe itself\n\t\/\/\tGetModuleFileName(hModule, ownPth, (sizeof(ownPth)));\n\t\/\/}\n\tname = \"Importer\";\n}\n\n\nModuleImporter::~ModuleImporter()\n{\n}\n\nbool ModuleImporter::Init(JSON_Object* node)\n{\n\t\/\/ Will contain exe path\n\tHMODULE hModule = GetModuleHandle(NULL);\n\tif (hModule != NULL)\n\t{\n\t\t\/\/ When passing NULL to GetModuleHandle, it returns handle of exe itself\n\t\tGetModuleFileName(hModule, directoryExe, (sizeof(directoryExe)));\n\t}\n\tiMesh = new ImportMesh();\n\tiMaterial = new ImportMaterial();\n\n\treturn true;\n}\n\nbool ModuleImporter::Start()\n{\n\tstruct aiLogStream stream;\n\tstream = aiGetPredefinedLogStream(aiDefaultLogStream_DEBUGGER, nullptr);\n\taiAttachLogStream(&stream);\n\n\treturn true;\n}\n\nupdate_status ModuleImporter::PreUpdate(float dt)\n{\n\tperf_timer.Start();\n\n\tif (App->input->GetKey(SDL_SCANCODE_B) == KEY_DOWN)\n\t{\n\t\t\/\/ImportMesh* imp = new ImportMesh();\n\t\t\/\/imp->Load(\"Baker_house.rin\");\n\t}\n\n\tif (App->input->dropped)\n\t{\n\t\tdropped_File_type = CheckFileType(App->input->dropped_filedir);\n\n\n\t\t\/\/App->fs->CopyFileToAssets(App->input->dropped_filedir, ((Project*)App->gui->winManager[PROJECT])->GetFolderSee().c_str());\n\t\t\/\/((Project*)App->gui->winManager[PROJECT])->AddFile(((Project*)App->gui->winManager[PROJECT])->GetFilesSee(), App->input->dropped_filedir);\n\n\t\tswitch (dropped_File_type)\n\t\t{\n\t\tcase F_MODEL_i:\n\t\t{\n\t\t\tLOG(\"IMPORTING MODEL, File Path: %s\", App->input->dropped_filedir);\n\t\t\tstd::string file;\n\n\t\t\tconst aiScene* scene = aiImportFile(App->input->dropped_filedir, aiProcessPreset_TargetRealtime_MaxQuality);\n\t\t\tGameObject* obj = new GameObject();\n\t\t\tCompTransform* trans = (CompTransform*)obj->AddComponent(C_TRANSFORM);\n\t\t\ttrans->SetZero();\n\t\t\tProcessNode(scene->mRootNode, scene, obj);\n\t\t\taiReleaseImport(scene);\n\t\t\tApp->scene->gameobjects.push_back(obj);\n\t\t\t\/\/Now Save Serialitzate OBJ -> Prefab\n\n\t\t\tbreak;\n\t\t}\n\t\tcase F_TEXTURE_i:\n\t\t{\n\t\t\tLOG(\"IMPORTING TEXTURE, File Path: %s\", App->input->dropped_filedir);\n\t\t\tiMaterial->Import(App->input->dropped_filedir);\n\t\t\n\t\t\tbreak;\n\t\t}\n\t\tcase F_UNKNOWN_i:\n\t\t{\n\t\t\tSDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_INFORMATION, \"UNKNOWN file type dropped on window\",\n\t\t\t\tApp->input->dropped_filedir, App->window->window);\n\t\t\tLOG(\"UNKNOWN FILE TYPE, File Path: %s\", App->input->dropped_filedir);\n\n\t\t\tbreak;\n\t\t}\n\n\t\tdefault:\n\t\t\tbreak;\n\n\t\t}\n\n\t\tApp->input->dropped = false;\n\t}\n\n\tUpdate_t = perf_timer.ReadMs();\n\n\n\treturn UPDATE_CONTINUE;\n}\n\nvoid ModuleImporter::ProcessNode(aiNode* node, const aiScene* scene, GameObject* obj)\n{\n\t\/\/ Process all the Node's MESHES\n\tfor (uint i = 0; i < node->mNumMeshes; i++)\n\t{\n\t\tGameObject* objChild = new GameObject();\n\t\tCompTransform* trans = (CompTransform*)objChild->AddComponent(C_TRANSFORM);\n\t\ttrans->SetTransformation(node->mTransformation);\n\t\taiMesh* mesh = scene->mMeshes[node->mMeshes[i]];\n\t\tiMesh->Import(scene, mesh, objChild, node->mName.C_Str());\n\t\tobj->AddChildGameObject_Copy(objChild);\n\t}\n\n\t\/\/ Process children\n\tfor (uint i = 0; i < node->mNumChildren; i++)\n\t{\n\t\tProcessNode(node->mChildren[i], scene, obj);\n\t}\n}\n\nupdate_status ModuleImporter::Update(float dt)\n{\n\treturn UPDATE_CONTINUE;\n}\n\nupdate_status ModuleImporter::PostUpdate(float dt)\n{\n\treturn UPDATE_CONTINUE;\n}\n\nupdate_status ModuleImporter::UpdateConfig(float dt)\n{\n\treturn UPDATE_CONTINUE;\n}\n\nbool ModuleImporter::CleanUp()\n{\n\taiDetachAllLogStreams();\n\treturn true;\n}\n\nFileTypeImport ModuleImporter::CheckFileType(char * filedir)\n{\n\tif (filedir != nullptr)\n\t{\n\t\tstd::string file_type;\n\t\tstd::string path(filedir);\n\n\t\tsize_t extension_pos = path.find_last_of(\".\");\n\n\t\tfile_type = path.substr(extension_pos + 1);\n\n\t\t\/\/Set lowercase the extension to normalize it\n\t\tfor (std::string::iterator it = file_type.begin(); it != file_type.end(); it++)\n\t\t{\n\t\t\t*it = tolower(*it);\n\t\t}\n\n\t\tif (file_type == \"png\" || file_type == \"jpg\" || file_type == \"dds\")\n\t\t{\n\t\t\treturn F_TEXTURE_i;\n\t\t}\n\t\telse if (file_type == \"fbx\" || file_type == \"obj\")\n\t\t{\n\t\t\treturn F_MODEL_i;\n\t\t}\n\t\telse\n\t\t{\n\t\t\treturn F_UNKNOWN_i;\n\t\t}\n\t}\n}\nFix Name Importer#include \"ModuleImporter.h\"\n#include \"Application.h\"\n#include \"ImportMesh.h\"\n#include \"ImportMaterial.h\"\n#include \"CompTransform.h\"\n\n\nModuleImporter::ModuleImporter(bool start_enabled) : Module(start_enabled)\n{\n\t\/\/char ownPth[MAX_PATH];\n\n\t\/\/\/\/ Will contain exe path\n\t\/\/HMODULE hModule = GetModuleHandle(NULL);\n\t\/\/if (hModule != NULL)\n\t\/\/{\n\t\/\/\t\/\/ When passing NULL to GetModuleHandle, it returns handle of exe itself\n\t\/\/\tGetModuleFileName(hModule, ownPth, (sizeof(ownPth)));\n\t\/\/}\n\tname = \"Importer\";\n}\n\n\nModuleImporter::~ModuleImporter()\n{\n}\n\nbool ModuleImporter::Init(JSON_Object* node)\n{\n\t\/\/ Will contain exe path\n\tHMODULE hModule = GetModuleHandle(NULL);\n\tif (hModule != NULL)\n\t{\n\t\t\/\/ When passing NULL to GetModuleHandle, it returns handle of exe itself\n\t\tGetModuleFileName(hModule, directoryExe, (sizeof(directoryExe)));\n\t}\n\tiMesh = new ImportMesh();\n\tiMaterial = new ImportMaterial();\n\n\treturn true;\n}\n\nbool ModuleImporter::Start()\n{\n\tstruct aiLogStream stream;\n\tstream = aiGetPredefinedLogStream(aiDefaultLogStream_DEBUGGER, nullptr);\n\taiAttachLogStream(&stream);\n\n\treturn true;\n}\n\nupdate_status ModuleImporter::PreUpdate(float dt)\n{\n\tperf_timer.Start();\n\n\tif (App->input->GetKey(SDL_SCANCODE_B) == KEY_DOWN)\n\t{\n\t\t\/\/ImportMesh* imp = new ImportMesh();\n\t\t\/\/imp->Load(\"Baker_house.rin\");\n\t}\n\n\tif (App->input->dropped)\n\t{\n\t\tdropped_File_type = CheckFileType(App->input->dropped_filedir);\n\n\n\t\t\/\/App->fs->CopyFileToAssets(App->input->dropped_filedir, ((Project*)App->gui->winManager[PROJECT])->GetFolderSee().c_str());\n\t\t\/\/((Project*)App->gui->winManager[PROJECT])->AddFile(((Project*)App->gui->winManager[PROJECT])->GetFilesSee(), App->input->dropped_filedir);\n\n\t\tswitch (dropped_File_type)\n\t\t{\n\t\tcase F_MODEL_i:\n\t\t{\n\t\t\tLOG(\"IMPORTING MODEL, File Path: %s\", App->input->dropped_filedir);\n\t\t\tstd::string file;\n\n\t\t\tconst aiScene* scene = aiImportFile(App->input->dropped_filedir, aiProcessPreset_TargetRealtime_MaxQuality);\n\t\t\tGameObject* obj = new GameObject();\n\t\t\tobj->SetName(App->GetCharfromConstChar(App->fs->FixName_directory(App->input->dropped_filedir).c_str()));\n\t\t\tCompTransform* trans = (CompTransform*)obj->AddComponent(C_TRANSFORM);\n\t\t\ttrans->SetZero();\n\t\t\tProcessNode(scene->mRootNode, scene, obj);\n\t\t\taiReleaseImport(scene);\n\t\t\tApp->scene->gameobjects.push_back(obj);\n\t\t\t\/\/Now Save Serialitzate OBJ -> Prefab\n\n\t\t\tbreak;\n\t\t}\n\t\tcase F_TEXTURE_i:\n\t\t{\n\t\t\tLOG(\"IMPORTING TEXTURE, File Path: %s\", App->input->dropped_filedir);\n\t\t\tiMaterial->Import(App->input->dropped_filedir);\n\t\t\n\t\t\tbreak;\n\t\t}\n\t\tcase F_UNKNOWN_i:\n\t\t{\n\t\t\tSDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_INFORMATION, \"UNKNOWN file type dropped on window\",\n\t\t\t\tApp->input->dropped_filedir, App->window->window);\n\t\t\tLOG(\"UNKNOWN FILE TYPE, File Path: %s\", App->input->dropped_filedir);\n\n\t\t\tbreak;\n\t\t}\n\n\t\tdefault:\n\t\t\tbreak;\n\n\t\t}\n\n\t\tApp->input->dropped = false;\n\t}\n\n\tUpdate_t = perf_timer.ReadMs();\n\n\n\treturn UPDATE_CONTINUE;\n}\n\nvoid ModuleImporter::ProcessNode(aiNode* node, const aiScene* scene, GameObject* obj)\n{\n\t\/\/ Process all the Node's MESHES\n\tfor (uint i = 0; i < node->mNumMeshes; i++)\n\t{\n\t\tGameObject* objChild = new GameObject();\n\t\tobjChild->SetName(App->GetCharfromConstChar(node->mName.C_Str()));\n\t\tCompTransform* trans = (CompTransform*)objChild->AddComponent(C_TRANSFORM);\n\t\ttrans->SetTransformation(node->mTransformation);\n\t\taiMesh* mesh = scene->mMeshes[node->mMeshes[i]];\n\t\tiMesh->Import(scene, mesh, objChild, node->mName.C_Str());\n\t\tobj->AddChildGameObject_Copy(objChild);\n\t}\n\n\t\/\/ Process children\n\tfor (uint i = 0; i < node->mNumChildren; i++)\n\t{\n\t\tProcessNode(node->mChildren[i], scene, obj);\n\t}\n}\n\nupdate_status ModuleImporter::Update(float dt)\n{\n\treturn UPDATE_CONTINUE;\n}\n\nupdate_status ModuleImporter::PostUpdate(float dt)\n{\n\treturn UPDATE_CONTINUE;\n}\n\nupdate_status ModuleImporter::UpdateConfig(float dt)\n{\n\treturn UPDATE_CONTINUE;\n}\n\nbool ModuleImporter::CleanUp()\n{\n\taiDetachAllLogStreams();\n\treturn true;\n}\n\nFileTypeImport ModuleImporter::CheckFileType(char * filedir)\n{\n\tif (filedir != nullptr)\n\t{\n\t\tstd::string file_type;\n\t\tstd::string path(filedir);\n\n\t\tsize_t extension_pos = path.find_last_of(\".\");\n\n\t\tfile_type = path.substr(extension_pos + 1);\n\n\t\t\/\/Set lowercase the extension to normalize it\n\t\tfor (std::string::iterator it = file_type.begin(); it != file_type.end(); it++)\n\t\t{\n\t\t\t*it = tolower(*it);\n\t\t}\n\n\t\tif (file_type == \"png\" || file_type == \"jpg\" || file_type == \"dds\")\n\t\t{\n\t\t\treturn F_TEXTURE_i;\n\t\t}\n\t\telse if (file_type == \"fbx\" || file_type == \"obj\")\n\t\t{\n\t\t\treturn F_MODEL_i;\n\t\t}\n\t\telse\n\t\t{\n\t\t\treturn F_UNKNOWN_i;\n\t\t}\n\t}\n}\n<|endoftext|>"} {"text":"\/* \n * Unit tests for the TTSampleMatrix Object for Jamoma DSP\n * Copyright © 2012, Tim Place & Nathan Wolek\n * \n * License: This code is licensed under the terms of the \"New BSD License\"\n * http:\/\/creativecommons.org\/licenses\/BSD\/\n *\/\n\n#include \"TTSampleMatrix.h\"\n\n\nTTErr TTSampleMatrix::test(TTValue& returnedTestInfo)\n{\n\tint\t\t\t\t\terrorCount = 0;\n\tint\t\t\t\t\ttestAssertionCount = 0;\n\t\n\t\/\/ for tests\n\tTTUInt16\t\t\tnumChannels = 2;\n\tTTUInt16\t\t\tnumSamples = 50000;\n\tTTFloat32\t\t\tduration = 1500;\n\tTTUInt32\t\t\ttest9Index = 10;\n\tTTUInt32\t\t\ttest10Index = 11;\n\tTTUInt32\t\t\ttest1Return, test2Return, test7Return, test8Return;\n\tTTFloat32\t\t\ttest3Return, test6Return;\n\tTTSampleValue\t\ttest9Return, test10Return, test11Return, test12return;\n\t\n\tTTTestLog(\"Test resizing of the SampleMatrix...\");\n\t\n\t\n\t\/\/ TEST 1: can we set the number of channels?\n\tthis->setAttributeValue(\"numChannels\", numChannels);\n\t\n\tthis->getAttributeValue(\"numChannels\", test1Return);\n\t\n\tTTBoolean result = { numChannels == test1Return };\n\t\n\tTTTestAssertion(\"numChannels is set properly\", \n\t\t\t\t\tresult,\n\t\t\t\t\ttestAssertionCount, \n\t\t\t\t\terrorCount);\n\t\n\tif(!result)\n\t{\n\t\tTTTestLog(\"Expected a value of %i, but returned value was %i\", numChannels, test1Return);\t\n\t}\n\t\n\t\n\t\/\/ TEST 2: can we set the number of samples?\n\tthis->setAttributeValue(TT(\"lengthInSamples\"), numSamples);\n\t\n\tthis->getAttributeValue(TT(\"lengthInSamples\"), test2Return);\n\n\tTTBoolean result2 = { numSamples == test2Return };\n\n\tTTTestAssertion(\"lengthInSamples is set properly\", \n\t\t\t\t\t\t\t\tresult2,\n\t\t\t\t\t\t\t\ttestAssertionCount, \n\t\t\t\t\t\t\t\terrorCount);\n\tif(!result2)\n\t{\n\t\tTTTestLog(\"Expected a value of %i, but returned value was %i\", numSamples, test2Return);\t\n\t}\n\t\n\t\n\t\/\/ TEST 3: is the length in ms computed properly after setting length in samples?\n\tTTFloat32 computedDuration3 = (numSamples \/ this->mSampleRate) * 1000.;\t\n\t\n\tthis->getAttributeValue(TT(\"length\"), test3Return);\t\t\t\t\n\t\t\t\t\t\n\tTTBoolean result3 = TTTestFloatEquivalence(computedDuration3, test3Return);\n\t\t\t\t\n\tTTTestAssertion(\"after lengthInSamples is set, length (in ms) is correct\", \n\t\t\t\t\t\t\t\tresult3,\n\t\t\t\t\t\t\t\ttestAssertionCount, \n\t\t\t\t\t\t\t\terrorCount);\n\t\t\t\t\t\t\t\n\tif(!result3)\n\t{\n\t\tTTTestLog(\"Expected a value of %f, but returned value was %f\", computedDuration3, test3Return);\t\n\t}\t\n\t\n\t\n\t\/\/ TEST 4: is the matrix of samples the expected size? (lifted from TTMatrix.test.cpp)\n\tTTUInt32 computedDataSize4 = sizeof(TTFloat64) * numChannels * numSamples;\n\t\n\tTTBoolean result4 = { computedDataSize4 == this->mDataSize };\n\t\n\tTTTestAssertion(\"correct amount of data storage calculated\", \n\t\t\t\t\t\t\t\tresult4, \n\t\t\t\t\t\t\t\ttestAssertionCount,\n\t\t\t\t\t\t\t\terrorCount);\n\t\t\t\t\t\t\t\t\n\tif(!result4)\n\t{\n\t\tTTTestLog(\"Expected a value of %i, but returned value was %i\", computedDataSize4, this->mDataSize);\n\t}\n\t\n\t\n\t\/\/ TEST 5: Is the component stride right? (lifted from TTMatrix.test.cpp)\n\tTTBoolean result5 = { sizeof(TTFloat64) == this->mComponentStride };\n\t\t\t\t\t\t\t\t\n\tTTTestAssertion(\"correct byte-stride between values calculated\", \n\t\t\t\t\t\t\t\tresult5, \n\t\t\t\t\t\t\t\ttestAssertionCount,\n\t\t\t\t\t\t\t\terrorCount);\n\t\t\t\t\t\t\t\t\n\tif(!result5)\n\t{\n\t\tTTTestLog(\"Expected a value of %i, but returned value was %i\", sizeof(TTFloat64), this->mComponentStride);\n\t}\n\t\n\t\t\t\t\t\t\t\t\t\n\t\/\/ TEST 6: can we set the length in milliseconds?\n\tthis->setAttributeValue(TT(\"length\"), duration);\n\t\n\tthis->getAttributeValue(TT(\"length\"), test6Return);\n\n\tTTBoolean result6 = TTTestFloatEquivalence(duration, test6Return);\n\n\tTTTestAssertion(\"length (in ms) is set properly\", \n\t\t\t\t\t\t\t\tresult6,\n\t\t\t\t\t\t\t\ttestAssertionCount, \n\t\t\t\t\t\t\t\terrorCount);\n\t\n\tif(!result6)\n\t{\n\t\tTTTestLog(\"Expected a value of %f, but returned value was %f\", duration, test6Return);\n\t}\n\n\t\t\t\t\n\t\/\/ TEST 7: is the length in samples computed properly after setting length in ms?\n\tTTUInt32 computedSamples7 = TTUInt32(duration * this->mSampleRate * 0.001);\t\n\t\t\t\t\t\n\tthis->getAttributeValue(TT(\"lengthInSamples\"), test7Return);\t\t\t\t\n\t\n\tTTBoolean result7 = { computedSamples7 == test7Return };\n\t\t\t\t\n\tTTTestAssertion(\"after length (in ms) is set, lengthInSamples is correct\", \n\t\t\t\t\t\t\t\tresult7,\n\t\t\t\t\t\t\t\ttestAssertionCount, \n\t\t\t\t\t\t\t\terrorCount);\n\t\t\t\t\t\t\t\n\tif(!result7)\n\t{\n\t\tTTTestLog(\"Expected a value of %i, but returned value was %i\", computedSamples7, test7Return);\t\n\t}\t\n\t\n\t\n\t\/\/ TEST 8 (REPEAT TEST 4 WITH NEW SIZE): is the matrix of samples the expected size?\n\tTTUInt32 computedDataSize8 = sizeof(TTFloat64) * numChannels * test7Return;\n\t\n\tTTBoolean result8 = { computedDataSize8 == this->mDataSize };\n\t\n\tTTTestAssertion(\"correct amount of data storage calculated with new length\", \n\t\t\t\t\t\t\t\tresult8, \n\t\t\t\t\t\t\t\ttestAssertionCount,\n\t\t\t\t\t\t\t\terrorCount);\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\n\tif(!result8)\n\t{\n\t\tTTTestLog(\"Expected a value of %i, but returned value was %i\", computedDataSize8, this->mDataSize);\t\n\t}\n\t\n\t\n\t\/\/ TEST 9 & 10: set the value of two consecutive samples\n\tTTSampleValue pokeValue9 = TTRandom64();\n\tTTSampleValue pokeValue10 = TTRandom64();\n\t\n\tthis->poke(test9Index, 1, pokeValue9);\n\tthis->poke(test10Index, 1, pokeValue10);\n\t\n\tthis->peek(test9Index, 1, test9Return);\n\tthis->peek(test10Index, 1, test10Return);\n\t\n\tTTBoolean result9 = { pokeValue9 == test9Return };\n\t\n\tTTTestAssertion(\"set value one of two consecutive samples\", \n\t\t\t\t\t\t\t\tresult9, \n\t\t\t\t\t\t\t\ttestAssertionCount,\n\t\t\t\t\t\t\t\terrorCount);\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\n\tif(!result9)\n\t{\n\t\tTTTestLog(\"Expected a value of %f, but returned value was %f\", pokeValue9, test9Return);\n\t}\n\t\n\tTTBoolean result10 = { pokeValue10 == test10Return };\n\t\n\tTTTestAssertion(\"set value two of two consecutive samples\", \n\t\t\t\t\t\t\t\tresult10, \n\t\t\t\t\t\t\t\ttestAssertionCount,\n\t\t\t\t\t\t\t\terrorCount);\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\n\tif(!result10)\n\t{\n\t\tTTTestLog(\"Expected a value of %f, but returned value was %f\", pokeValue10, test10Return);\n\t}\n\t\n\t\n\t\/\/ TEST 11: test for interpolation between two consecutive samples\n\tTTFloat64 computedInterpFraction = TTRandom64();\n\tTTFloat64 computedInterpIndex = test9Index + computedInterpFraction;\n\tTTSampleValue computedInterpValue11 = (computedInterpFraction * pokeValue9) + ((1.0 - computedInterpFraction) * pokeValue10);\n\t\n\tthis->peeki(computedInterpIndex, 1, test11Return);\n\t\n\tTTBoolean result11 = TTTestFloatEquivalence(computedInterpValue11, test11Return);\n\t\n\tTTTestAssertion(\"interpolate between two consecutive samples\", \n\t\t\t\t\t\t\t\tresult11, \n\t\t\t\t\t\t\t\ttestAssertionCount,\n\t\t\t\t\t\t\t\terrorCount);\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\n\tif(!result11)\n\t{\n\t\tTTTestLog(\"Expected a value of %f, but returned value was %f\", computedInterpValue11, test11Return);\n\t}\n\t\n\t\/*\n\t\/\/ TODO: inbounds testing on hold until sorted out at TTMatrix parent class\n\t\n\t\/\/ TEST 12: test the new inBounds method\n\t\n\tTTUInt32 computedSampleAfterTail12 = -10; \/\/test7Return + 5;\n\tTTErr test12Err = this->peek(computedSampleAfterTail12, 1, test12return);\n\t\n\tTTTestAssertion(\"retrieving sample out of bounds produces an error\", \n\t\t\t\t\t\t\t\ttest12Err == kTTErrInvalidValue, \n\t\t\t\t\t\t\t\ttestAssertionCount,\n\t\t\t\t\t\t\t\terrorCount);\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\n\tif(test12Err != kTTErrInvalidValue)\n\t{\n\t\tTTTestLog(\"Expected a value of %i, but returned value was %i\", kTTErrInvalidValue, test12Err);\n\t}\n\t\n\t\n\tTTUInt32 computedDistanceFromHead12 = test7Return * test1Return\n\t\n\tcomputedDistanceFromHead12 -= 50; \/\/ 50 before tail\n\tTTBoolean result12 = this->inBounds(computedDistanceFromHead12);\n\t\n\tif(result12)\n\t{\n\t\tTTTestLog(\"Testing in bounds 12 returned true, %i\", computedDistanceFromHead12);\n\t}\n\t\n\tcomputedDistanceFromHead12 += 50; \/\/ at tail\n\tTTBoolean result13 = this->inBounds(computedDistanceFromHead12);\n\t\n\tif(result13)\n\t{\n\t\tTTTestLog(\"Testing in bounds 13 returned true, %i\", computedDistanceFromHead12);\n\t}\n\t\n\tcomputedDistanceFromHead12 += 1; \/\/ 1 after tail\n\tTTBoolean result14 = this->inBounds(computedDistanceFromHead12);\n\t\n\tif(!result14)\n\t{\n\t\tTTTestLog(\"Testing in bounds 14 returned false, %i\", computedDistanceFromHead12);\n\t}\n\t\n\tTTBoolean result15 = this->inBounds(-1);\n\t\n\tif(!result15)\n\t{\n\t\tTTTestLog(\"Negative values return false: %i\", -1);\n\t}\n\t\n\tTTBoolean result16 = this->inBounds(0);\n\t\n\tif(!result16)\n\t{\n\t\tTTTestLog(\"Zero returns false: %i\", 0);\n\t}\n\t*\/\n\t\n\t\/*\n\t\n\tint\t\t\t\t\tbadSampleCount = 0;\n\tTTAudioObjectPtr\tsamplematrixObject = NULL;\n\tTTAudioSignalPtr\tinput = NULL;\n\tTTAudioSignalPtr\toutput = NULL;\n\t\n\t\/\/ TODO: test filling with sine wave\n\t\/\/ TODO: test scaling (applying gain)\n\t\/\/ TODO: test normalizing (with optional arg, and also without an optional arg)\n\t\n\tTTObjectInstantiate(TT(\"samplematrix\"), &samplematrixObject, kTTVal1);\n\t\n\tTTObjectRelease(&input);\n\tTTObjectRelease(&output);\n\tTTObjectRelease(&samplematrixObject);\n\t\n\t*\/\n\t\n\t\n\t\/\/ Wrap up the test results to pass back to whoever called this test\n\treturn TTTestFinish(testAssertionCount, errorCount, returnedTestInfo);\n}\n\nSampleMatrix: changing datatypes in test()\/* \n * Unit tests for the TTSampleMatrix Object for Jamoma DSP\n * Copyright © 2012, Tim Place & Nathan Wolek\n * \n * License: This code is licensed under the terms of the \"New BSD License\"\n * http:\/\/creativecommons.org\/licenses\/BSD\/\n *\/\n\n#include \"TTSampleMatrix.h\"\n\n\nTTErr TTSampleMatrix::test(TTValue& returnedTestInfo)\n{\n\tint\t\t\t\t\terrorCount = 0;\n\tint\t\t\t\t\ttestAssertionCount = 0;\n\t\n\t\/\/ for tests\n\tTTInt16\t\t\t\tnumChannels = 2;\n\tTTInt32\t\t\t\tnumSamples = 50000;\n\tTTFloat32\t\t\tduration = 1500;\n\tTTInt32\t\t\t\ttest9Index = 10;\n\tTTInt32\t\t\t\ttest10Index = 11;\n\tTTInt32\t\t\t\ttest1Return, test2Return, test7Return, test8Return;\n\tTTFloat32\t\t\ttest3Return, test6Return;\n\tTTSampleValue\t\ttest9Return, test10Return, test11Return, test12return;\n\t\n\tTTTestLog(\"Test resizing of the SampleMatrix...\");\n\t\n\t\n\t\/\/ TEST 1: can we set the number of channels?\n\tthis->setAttributeValue(\"numChannels\", numChannels);\n\t\n\tthis->getAttributeValue(\"numChannels\", test1Return);\n\t\n\tTTBoolean result = { numChannels == test1Return };\n\t\n\tTTTestAssertion(\"numChannels is set properly\", \n\t\t\t\t\tresult,\n\t\t\t\t\ttestAssertionCount, \n\t\t\t\t\terrorCount);\n\t\n\tif(!result)\n\t{\n\t\tTTTestLog(\"Expected a value of %i, but returned value was %i\", numChannels, test1Return);\t\n\t}\n\t\n\t\n\t\/\/ TEST 2: can we set the number of samples?\n\tthis->setAttributeValue(TT(\"lengthInSamples\"), numSamples);\n\t\n\tthis->getAttributeValue(TT(\"lengthInSamples\"), test2Return);\n\n\tTTBoolean result2 = { numSamples == test2Return };\n\n\tTTTestAssertion(\"lengthInSamples is set properly\", \n\t\t\t\t\t\t\t\tresult2,\n\t\t\t\t\t\t\t\ttestAssertionCount, \n\t\t\t\t\t\t\t\terrorCount);\n\tif(!result2)\n\t{\n\t\tTTTestLog(\"Expected a value of %i, but returned value was %i\", numSamples, test2Return);\t\n\t}\n\t\n\t\n\t\/\/ TEST 3: is the length in ms computed properly after setting length in samples?\n\tTTFloat32 computedDuration3 = (numSamples \/ this->mSampleRate) * 1000.;\t\n\t\n\tthis->getAttributeValue(TT(\"length\"), test3Return);\t\t\t\t\n\t\t\t\t\t\n\tTTBoolean result3 = TTTestFloatEquivalence(computedDuration3, test3Return);\n\t\t\t\t\n\tTTTestAssertion(\"after lengthInSamples is set, length (in ms) is correct\", \n\t\t\t\t\t\t\t\tresult3,\n\t\t\t\t\t\t\t\ttestAssertionCount, \n\t\t\t\t\t\t\t\terrorCount);\n\t\t\t\t\t\t\t\n\tif(!result3)\n\t{\n\t\tTTTestLog(\"Expected a value of %f, but returned value was %f\", computedDuration3, test3Return);\t\n\t}\t\n\t\n\t\n\t\/\/ TEST 4: is the matrix of samples the expected size? (lifted from TTMatrix.test.cpp)\n\tTTUInt32 computedDataSize4 = sizeof(TTFloat64) * numChannels * numSamples;\n\t\n\tTTBoolean result4 = { computedDataSize4 == this->mDataSize };\n\t\n\tTTTestAssertion(\"correct amount of data storage calculated\", \n\t\t\t\t\t\t\t\tresult4, \n\t\t\t\t\t\t\t\ttestAssertionCount,\n\t\t\t\t\t\t\t\terrorCount);\n\t\t\t\t\t\t\t\t\n\tif(!result4)\n\t{\n\t\tTTTestLog(\"Expected a value of %i, but returned value was %i\", computedDataSize4, this->mDataSize);\n\t}\n\t\n\t\n\t\/\/ TEST 5: Is the component stride right? (lifted from TTMatrix.test.cpp)\n\tTTBoolean result5 = { sizeof(TTFloat64) == this->mComponentStride };\n\t\t\t\t\t\t\t\t\n\tTTTestAssertion(\"correct byte-stride between values calculated\", \n\t\t\t\t\t\t\t\tresult5, \n\t\t\t\t\t\t\t\ttestAssertionCount,\n\t\t\t\t\t\t\t\terrorCount);\n\t\t\t\t\t\t\t\t\n\tif(!result5)\n\t{\n\t\tTTTestLog(\"Expected a value of %i, but returned value was %i\", sizeof(TTFloat64), this->mComponentStride);\n\t}\n\t\n\t\t\t\t\t\t\t\t\t\n\t\/\/ TEST 6: can we set the length in milliseconds?\n\tthis->setAttributeValue(TT(\"length\"), duration);\n\t\n\tthis->getAttributeValue(TT(\"length\"), test6Return);\n\n\tTTBoolean result6 = TTTestFloatEquivalence(duration, test6Return);\n\n\tTTTestAssertion(\"length (in ms) is set properly\", \n\t\t\t\t\t\t\t\tresult6,\n\t\t\t\t\t\t\t\ttestAssertionCount, \n\t\t\t\t\t\t\t\terrorCount);\n\t\n\tif(!result6)\n\t{\n\t\tTTTestLog(\"Expected a value of %f, but returned value was %f\", duration, test6Return);\n\t}\n\n\t\t\t\t\n\t\/\/ TEST 7: is the length in samples computed properly after setting length in ms?\n\tTTUInt32 computedSamples7 = TTUInt32(duration * this->mSampleRate * 0.001);\t\n\t\t\t\t\t\n\tthis->getAttributeValue(TT(\"lengthInSamples\"), test7Return);\t\t\t\t\n\t\n\tTTBoolean result7 = { computedSamples7 == test7Return };\n\t\t\t\t\n\tTTTestAssertion(\"after length (in ms) is set, lengthInSamples is correct\", \n\t\t\t\t\t\t\t\tresult7,\n\t\t\t\t\t\t\t\ttestAssertionCount, \n\t\t\t\t\t\t\t\terrorCount);\n\t\t\t\t\t\t\t\n\tif(!result7)\n\t{\n\t\tTTTestLog(\"Expected a value of %i, but returned value was %i\", computedSamples7, test7Return);\t\n\t}\t\n\t\n\t\n\t\/\/ TEST 8 (REPEAT TEST 4 WITH NEW SIZE): is the matrix of samples the expected size?\n\tTTUInt32 computedDataSize8 = sizeof(TTFloat64) * numChannels * test7Return;\n\t\n\tTTBoolean result8 = { computedDataSize8 == this->mDataSize };\n\t\n\tTTTestAssertion(\"correct amount of data storage calculated with new length\", \n\t\t\t\t\t\t\t\tresult8, \n\t\t\t\t\t\t\t\ttestAssertionCount,\n\t\t\t\t\t\t\t\terrorCount);\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\n\tif(!result8)\n\t{\n\t\tTTTestLog(\"Expected a value of %i, but returned value was %i\", computedDataSize8, this->mDataSize);\t\n\t}\n\t\n\t\n\t\/\/ TEST 9 & 10: set the value of two consecutive samples\n\tTTSampleValue pokeValue9 = TTRandom64();\n\tTTSampleValue pokeValue10 = TTRandom64();\n\t\n\tthis->poke(test9Index, 1, pokeValue9);\n\tthis->poke(test10Index, 1, pokeValue10);\n\t\n\tthis->peek(test9Index, 1, test9Return);\n\tthis->peek(test10Index, 1, test10Return);\n\t\n\tTTBoolean result9 = { pokeValue9 == test9Return };\n\t\n\tTTTestAssertion(\"set value one of two consecutive samples\", \n\t\t\t\t\t\t\t\tresult9, \n\t\t\t\t\t\t\t\ttestAssertionCount,\n\t\t\t\t\t\t\t\terrorCount);\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\n\tif(!result9)\n\t{\n\t\tTTTestLog(\"Expected a value of %f, but returned value was %f\", pokeValue9, test9Return);\n\t}\n\t\n\tTTBoolean result10 = { pokeValue10 == test10Return };\n\t\n\tTTTestAssertion(\"set value two of two consecutive samples\", \n\t\t\t\t\t\t\t\tresult10, \n\t\t\t\t\t\t\t\ttestAssertionCount,\n\t\t\t\t\t\t\t\terrorCount);\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\n\tif(!result10)\n\t{\n\t\tTTTestLog(\"Expected a value of %f, but returned value was %f\", pokeValue10, test10Return);\n\t}\n\t\n\t\n\t\/\/ TEST 11: test for interpolation between two consecutive samples\n\tTTFloat64 computedInterpFraction = TTRandom64();\n\tTTFloat64 computedInterpIndex = test9Index + computedInterpFraction;\n\tTTSampleValue computedInterpValue11 = (computedInterpFraction * pokeValue9) + ((1.0 - computedInterpFraction) * pokeValue10);\n\t\n\tthis->peeki(computedInterpIndex, 1, test11Return);\n\t\n\tTTBoolean result11 = TTTestFloatEquivalence(computedInterpValue11, test11Return);\n\t\n\tTTTestAssertion(\"interpolate between two consecutive samples\", \n\t\t\t\t\t\t\t\tresult11, \n\t\t\t\t\t\t\t\ttestAssertionCount,\n\t\t\t\t\t\t\t\terrorCount);\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\n\tif(!result11)\n\t{\n\t\tTTTestLog(\"Expected a value of %f, but returned value was %f\", computedInterpValue11, test11Return);\n\t}\n\t\n\t\/*\n\t\/\/ TODO: inbounds testing on hold until sorted out at TTMatrix parent class\n\t\n\t\/\/ TEST 12: test the new inBounds method\n\t\n\tTTUInt32 computedSampleAfterTail12 = -10; \/\/test7Return + 5;\n\tTTErr test12Err = this->peek(computedSampleAfterTail12, 1, test12return);\n\t\n\tTTTestAssertion(\"retrieving sample out of bounds produces an error\", \n\t\t\t\t\t\t\t\ttest12Err == kTTErrInvalidValue, \n\t\t\t\t\t\t\t\ttestAssertionCount,\n\t\t\t\t\t\t\t\terrorCount);\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\n\tif(test12Err != kTTErrInvalidValue)\n\t{\n\t\tTTTestLog(\"Expected a value of %i, but returned value was %i\", kTTErrInvalidValue, test12Err);\n\t}\n\t\n\t\n\tTTUInt32 computedDistanceFromHead12 = test7Return * test1Return\n\t\n\tcomputedDistanceFromHead12 -= 50; \/\/ 50 before tail\n\tTTBoolean result12 = this->inBounds(computedDistanceFromHead12);\n\t\n\tif(result12)\n\t{\n\t\tTTTestLog(\"Testing in bounds 12 returned true, %i\", computedDistanceFromHead12);\n\t}\n\t\n\tcomputedDistanceFromHead12 += 50; \/\/ at tail\n\tTTBoolean result13 = this->inBounds(computedDistanceFromHead12);\n\t\n\tif(result13)\n\t{\n\t\tTTTestLog(\"Testing in bounds 13 returned true, %i\", computedDistanceFromHead12);\n\t}\n\t\n\tcomputedDistanceFromHead12 += 1; \/\/ 1 after tail\n\tTTBoolean result14 = this->inBounds(computedDistanceFromHead12);\n\t\n\tif(!result14)\n\t{\n\t\tTTTestLog(\"Testing in bounds 14 returned false, %i\", computedDistanceFromHead12);\n\t}\n\t\n\tTTBoolean result15 = this->inBounds(-1);\n\t\n\tif(!result15)\n\t{\n\t\tTTTestLog(\"Negative values return false: %i\", -1);\n\t}\n\t\n\tTTBoolean result16 = this->inBounds(0);\n\t\n\tif(!result16)\n\t{\n\t\tTTTestLog(\"Zero returns false: %i\", 0);\n\t}\n\t*\/\n\t\n\t\/*\n\t\n\tint\t\t\t\t\tbadSampleCount = 0;\n\tTTAudioObjectPtr\tsamplematrixObject = NULL;\n\tTTAudioSignalPtr\tinput = NULL;\n\tTTAudioSignalPtr\toutput = NULL;\n\t\n\t\/\/ TODO: test filling with sine wave\n\t\/\/ TODO: test scaling (applying gain)\n\t\/\/ TODO: test normalizing (with optional arg, and also without an optional arg)\n\t\n\tTTObjectInstantiate(TT(\"samplematrix\"), &samplematrixObject, kTTVal1);\n\t\n\tTTObjectRelease(&input);\n\tTTObjectRelease(&output);\n\tTTObjectRelease(&samplematrixObject);\n\t\n\t*\/\n\t\n\t\n\t\/\/ Wrap up the test results to pass back to whoever called this test\n\treturn TTTestFinish(testAssertionCount, errorCount, returnedTestInfo);\n}\n\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/common\/resource_bundle.h\"\n\n#include \n\n#include \"base\/file_util.h\"\n#include \"base\/gfx\/png_decoder.h\"\n#include \"base\/logging.h\"\n#include \"base\/path_service.h\"\n#include \"base\/resource_util.h\"\n#include \"base\/scoped_ptr.h\"\n#include \"base\/string_piece.h\"\n#include \"base\/string_util.h\"\n#include \"base\/win_util.h\"\n#include \"chrome\/app\/chrome_dll_resource.h\"\n#include \"chrome\/common\/chrome_paths.h\"\n#include \"chrome\/common\/gfx\/chrome_font.h\"\n#include \"chrome\/common\/l10n_util.h\"\n#include \"chrome\/common\/win_util.h\"\n#include \"SkBitmap.h\"\n\nusing namespace std;\n\nResourceBundle *ResourceBundle::g_shared_instance_ = NULL;\n\n\/\/ Returns the flags that should be passed to LoadLibraryEx.\nDWORD GetDataDllLoadFlags() {\n if (win_util::GetWinVersion() >= win_util::WINVERSION_VISTA)\n return LOAD_LIBRARY_AS_DATAFILE_EXCLUSIVE | LOAD_LIBRARY_AS_IMAGE_RESOURCE;\n\n return 0;\n}\n\n\/* static *\/\nvoid ResourceBundle::InitSharedInstance(const std::wstring& pref_locale) {\n DCHECK(g_shared_instance_ == NULL) << \"ResourceBundle initialized twice\";\n g_shared_instance_ = new ResourceBundle();\n\n g_shared_instance_->LoadLocaleResources(pref_locale);\n}\n\n\/* static *\/\nvoid ResourceBundle::CleanupSharedInstance() {\n if (g_shared_instance_) {\n delete g_shared_instance_;\n g_shared_instance_ = NULL;\n }\n}\n\n\/* static *\/\nResourceBundle& ResourceBundle::GetSharedInstance() {\n \/\/ Must call InitSharedInstance before this function.\n CHECK(g_shared_instance_ != NULL);\n return *g_shared_instance_;\n}\n\nResourceBundle::ResourceBundle()\n : locale_resources_dll_(NULL),\n theme_dll_(NULL) {\n}\n\nResourceBundle::~ResourceBundle() {\n for (SkImageMap::iterator i = skia_images_.begin();\n\t i != skia_images_.end(); i++) {\n delete i->second;\n }\n skia_images_.clear();\n\n if (locale_resources_dll_) {\n BOOL rv = FreeLibrary(locale_resources_dll_);\n DCHECK(rv);\n }\n if (theme_dll_) {\n BOOL rv = FreeLibrary(theme_dll_);\n DCHECK(rv);\n }\n}\n\nvoid ResourceBundle::LoadLocaleResources(const std::wstring& pref_locale) {\n DCHECK(NULL == locale_resources_dll_) << \"locale dll already loaded\";\n const std::wstring& locale_path = GetLocaleDllPath(pref_locale);\n if (locale_path.empty()) {\n \/\/ It's possible that there are no locale dlls found, in which case we just\n \/\/ return.\n NOTREACHED();\n return;\n }\n\n \/\/ The dll should only have resources, not executable code.\n locale_resources_dll_ = LoadLibraryEx(locale_path.c_str(), NULL,\n GetDataDllLoadFlags());\n DCHECK(locale_resources_dll_ != NULL) << \"unable to load generated resources\";\n}\n\nstd::wstring ResourceBundle::GetLocaleDllPath(const std::wstring& pref_locale) {\n std::wstring locale_path;\n PathService::Get(chrome::DIR_LOCALES, &locale_path);\n\n const std::wstring app_locale = l10n_util::GetApplicationLocale(pref_locale);\n if (app_locale.empty())\n return app_locale;\n\n file_util::AppendToPath(&locale_path, app_locale + L\".dll\");\n return locale_path;\n}\n\nvoid ResourceBundle::LoadThemeResources() {\n DCHECK(NULL == theme_dll_) << \"theme dll already loaded\";\n std::wstring theme_dll_path;\n PathService::Get(chrome::DIR_THEMES, &theme_dll_path);\n file_util::AppendToPath(&theme_dll_path, L\"default.dll\");\n\n \/\/ The dll should only have resources, not executable code.\n theme_dll_ = LoadLibraryEx(theme_dll_path.c_str(), NULL,\n GetDataDllLoadFlags());\n DCHECK(theme_dll_ != NULL) << \"unable to load \" << theme_dll_path;\n}\n\n\/* static *\/\nSkBitmap* ResourceBundle::LoadBitmap(HINSTANCE dll_inst, int resource_id) {\n void* data_ptr = NULL;\n size_t data_size;\n bool success = base::GetDataResourceFromModule(dll_inst, resource_id,\n &data_ptr, &data_size);\n if (!success)\n return NULL;\n\n unsigned char* data = static_cast(data_ptr);\n\n \/\/ Decode the PNG.\n vector png_data;\n int image_width;\n int image_height;\n if (!PNGDecoder::Decode(data, data_size, PNGDecoder::FORMAT_BGRA,\n &png_data, &image_width, &image_height)) {\n NOTREACHED() << \"Unable to decode theme resource \" << resource_id;\n return NULL;\n }\n\n return PNGDecoder::CreateSkBitmapFromBGRAFormat(png_data,\n image_width,\n image_height);\n}\n\nSkBitmap* ResourceBundle::GetBitmapNamed(int resource_id) {\n AutoLock lock_scope(lock_);\n\n SkImageMap::const_iterator found = skia_images_.find(resource_id);\n SkBitmap* bitmap = NULL;\n\n \/\/ If not found load and store the image\n if (found == skia_images_.end()) {\n \/\/ Load the image\n bitmap = LoadBitmap(theme_dll_, resource_id);\n \/\/ We did not find the bitmap in the theme DLL, try the current one.\n if (!bitmap)\n bitmap = LoadBitmap(_AtlBaseModule.GetModuleInstance(), resource_id);\n skia_images_[resource_id] = bitmap;\n } else {\n bitmap = found->second;\n }\n\n \/\/ This bitmap will be returned when a bitmap is requested that can not be\n \/\/ found. The data inside is lazily initialized, so users must lock and\n static SkBitmap* empty_bitmap = NULL;\n\n \/\/ Handle the case where loading the bitmap failed.\n if (!bitmap) {\n LOG(WARNING) << \"Unable to load bitmap with id \" << resource_id;\n if (!empty_bitmap) {\n empty_bitmap = new SkBitmap();\n }\n return empty_bitmap;\n }\n return bitmap;\n}\n\nbool ResourceBundle::LoadImageResourceBytes(int resource_id,\n vector* bytes) {\n return LoadModuleResourceBytes(theme_dll_, resource_id, bytes);\n}\n\nbool ResourceBundle::LoadDataResourceBytes(int resource_id,\n vector* bytes) {\n return LoadModuleResourceBytes(_AtlBaseModule.GetModuleInstance(),\n resource_id, bytes);\n}\n\nbool ResourceBundle::LoadModuleResourceBytes(\n HINSTANCE module,\n int resource_id,\n std::vector* bytes) {\n void* data_ptr;\n size_t data_size;\n if (base::GetDataResourceFromModule(module, resource_id, &data_ptr,\n &data_size)) {\n bytes->resize(data_size);\n memcpy(&(bytes->front()), data_ptr, data_size);\n return true;\n } else {\n return false;\n }\n}\n\nHICON ResourceBundle::LoadThemeIcon(int icon_id) {\n return ::LoadIcon(theme_dll_, MAKEINTRESOURCE(icon_id));\n}\n\nstd::string ResourceBundle::GetDataResource(int resource_id) {\n return GetRawDataResource(resource_id).as_string();\n}\n\nStringPiece ResourceBundle::GetRawDataResource(int resource_id) {\n void* data_ptr;\n size_t data_size;\n if (base::GetDataResourceFromModule(\n _AtlBaseModule.GetModuleInstance(), resource_id, &data_ptr, &data_size))\n return StringPiece(static_cast(data_ptr), data_size);\n return StringPiece();\n}\n\n\/\/ Loads and returns the global accelerators from the current module.\nHACCEL ResourceBundle::GetGlobalAccelerators() {\n return ::LoadAccelerators(_AtlBaseModule.GetModuleInstance(),\n MAKEINTRESOURCE(IDR_MAINFRAME));\n}\n\n\/\/ Loads and returns a cursor from the current module.\nHCURSOR ResourceBundle::LoadCursor(int cursor_id) {\n return ::LoadCursor(_AtlBaseModule.GetModuleInstance(),\n MAKEINTRESOURCE(cursor_id));\n}\n\nstd::wstring ResourceBundle::GetLocalizedString(int message_id) {\n \/\/ If for some reason we were unable to load a resource dll, return an empty\n \/\/ string (better than crashing).\n if (!locale_resources_dll_)\n return std::wstring();\n\n DCHECK(IS_INTRESOURCE(message_id));\n\n \/\/ Get a reference directly to the string resource.\n HINSTANCE hinstance = locale_resources_dll_;\n const ATLSTRINGRESOURCEIMAGE* image = AtlGetStringResourceImage(hinstance,\n message_id);\n if (!image) {\n \/\/ Fall back on the current module (shouldn't be any strings here except\n \/\/ in unittests).\n image = AtlGetStringResourceImage(_AtlBaseModule.GetModuleInstance(),\n message_id);\n if (!image) {\n NOTREACHED() << \"unable to find resource: \" << message_id;\n return std::wstring();\n }\n }\n \/\/ Copy into a wstring and return.\n return std::wstring(image->achString, image->nLength);\n}\n\nvoid ResourceBundle::LoadFontsIfNecessary() {\n AutoLock lock_scope(lock_);\n if (!base_font_.get()) {\n base_font_.reset(new ChromeFont());\n\n small_font_.reset(new ChromeFont());\n *small_font_ = base_font_->DeriveFont(-2);\n\n medium_font_.reset(new ChromeFont());\n *medium_font_ = base_font_->DeriveFont(3);\n\n medium_bold_font_.reset(new ChromeFont());\n *medium_bold_font_ =\n base_font_->DeriveFont(3, base_font_->style() | ChromeFont::BOLD);\n\n large_font_.reset(new ChromeFont());\n *large_font_ = base_font_->DeriveFont(8);\n\n web_font_.reset(new ChromeFont());\n *web_font_ = base_font_->DeriveFont(1,\n base_font_->style() | ChromeFont::WEB);\n }\n}\n\nChromeFont ResourceBundle::GetFont(FontStyle style) {\n LoadFontsIfNecessary();\n switch(style) {\n case SmallFont:\n return *small_font_;\n case MediumFont:\n return *medium_font_;\n case MediumBoldFont:\n return *medium_bold_font_;\n case LargeFont:\n return *large_font_;\n case WebFont:\n return *web_font_;\n default:\n return *base_font_;\n }\n}\n\nSecond try to make the theme dll no-executable.\/\/ Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/common\/resource_bundle.h\"\n\n#include \n\n#include \"base\/file_util.h\"\n#include \"base\/gfx\/png_decoder.h\"\n#include \"base\/logging.h\"\n#include \"base\/path_service.h\"\n#include \"base\/resource_util.h\"\n#include \"base\/scoped_ptr.h\"\n#include \"base\/string_piece.h\"\n#include \"base\/string_util.h\"\n#include \"base\/win_util.h\"\n#include \"chrome\/app\/chrome_dll_resource.h\"\n#include \"chrome\/common\/chrome_paths.h\"\n#include \"chrome\/common\/gfx\/chrome_font.h\"\n#include \"chrome\/common\/l10n_util.h\"\n#include \"chrome\/common\/win_util.h\"\n#include \"SkBitmap.h\"\n\nusing namespace std;\n\nResourceBundle *ResourceBundle::g_shared_instance_ = NULL;\n\n\/\/ Returns the flags that should be passed to LoadLibraryEx.\nDWORD GetDataDllLoadFlags() {\n if (win_util::GetWinVersion() >= win_util::WINVERSION_VISTA)\n return LOAD_LIBRARY_AS_DATAFILE_EXCLUSIVE | LOAD_LIBRARY_AS_IMAGE_RESOURCE;\n\n return DONT_RESOLVE_DLL_REFERENCES;\n}\n\n\/* static *\/\nvoid ResourceBundle::InitSharedInstance(const std::wstring& pref_locale) {\n DCHECK(g_shared_instance_ == NULL) << \"ResourceBundle initialized twice\";\n g_shared_instance_ = new ResourceBundle();\n\n g_shared_instance_->LoadLocaleResources(pref_locale);\n}\n\n\/* static *\/\nvoid ResourceBundle::CleanupSharedInstance() {\n if (g_shared_instance_) {\n delete g_shared_instance_;\n g_shared_instance_ = NULL;\n }\n}\n\n\/* static *\/\nResourceBundle& ResourceBundle::GetSharedInstance() {\n \/\/ Must call InitSharedInstance before this function.\n CHECK(g_shared_instance_ != NULL);\n return *g_shared_instance_;\n}\n\nResourceBundle::ResourceBundle()\n : locale_resources_dll_(NULL),\n theme_dll_(NULL) {\n}\n\nResourceBundle::~ResourceBundle() {\n for (SkImageMap::iterator i = skia_images_.begin();\n\t i != skia_images_.end(); i++) {\n delete i->second;\n }\n skia_images_.clear();\n\n if (locale_resources_dll_) {\n BOOL rv = FreeLibrary(locale_resources_dll_);\n DCHECK(rv);\n }\n if (theme_dll_) {\n BOOL rv = FreeLibrary(theme_dll_);\n DCHECK(rv);\n }\n}\n\nvoid ResourceBundle::LoadLocaleResources(const std::wstring& pref_locale) {\n DCHECK(NULL == locale_resources_dll_) << \"locale dll already loaded\";\n const std::wstring& locale_path = GetLocaleDllPath(pref_locale);\n if (locale_path.empty()) {\n \/\/ It's possible that there are no locale dlls found, in which case we just\n \/\/ return.\n NOTREACHED();\n return;\n }\n\n \/\/ The dll should only have resources, not executable code.\n locale_resources_dll_ = LoadLibraryEx(locale_path.c_str(), NULL,\n GetDataDllLoadFlags());\n DCHECK(locale_resources_dll_ != NULL) << \"unable to load generated resources\";\n}\n\nstd::wstring ResourceBundle::GetLocaleDllPath(const std::wstring& pref_locale) {\n std::wstring locale_path;\n PathService::Get(chrome::DIR_LOCALES, &locale_path);\n\n const std::wstring app_locale = l10n_util::GetApplicationLocale(pref_locale);\n if (app_locale.empty())\n return app_locale;\n\n file_util::AppendToPath(&locale_path, app_locale + L\".dll\");\n return locale_path;\n}\n\nvoid ResourceBundle::LoadThemeResources() {\n DCHECK(NULL == theme_dll_) << \"theme dll already loaded\";\n std::wstring theme_dll_path;\n PathService::Get(chrome::DIR_THEMES, &theme_dll_path);\n file_util::AppendToPath(&theme_dll_path, L\"default.dll\");\n\n \/\/ The dll should only have resources, not executable code.\n theme_dll_ = LoadLibraryEx(theme_dll_path.c_str(), NULL,\n GetDataDllLoadFlags());\n DCHECK(theme_dll_ != NULL) << \"unable to load \" << theme_dll_path;\n}\n\n\/* static *\/\nSkBitmap* ResourceBundle::LoadBitmap(HINSTANCE dll_inst, int resource_id) {\n void* data_ptr = NULL;\n size_t data_size;\n bool success = base::GetDataResourceFromModule(dll_inst, resource_id,\n &data_ptr, &data_size);\n if (!success)\n return NULL;\n\n unsigned char* data = static_cast(data_ptr);\n\n \/\/ Decode the PNG.\n vector png_data;\n int image_width;\n int image_height;\n if (!PNGDecoder::Decode(data, data_size, PNGDecoder::FORMAT_BGRA,\n &png_data, &image_width, &image_height)) {\n NOTREACHED() << \"Unable to decode theme resource \" << resource_id;\n return NULL;\n }\n\n return PNGDecoder::CreateSkBitmapFromBGRAFormat(png_data,\n image_width,\n image_height);\n}\n\nSkBitmap* ResourceBundle::GetBitmapNamed(int resource_id) {\n AutoLock lock_scope(lock_);\n\n SkImageMap::const_iterator found = skia_images_.find(resource_id);\n SkBitmap* bitmap = NULL;\n\n \/\/ If not found load and store the image\n if (found == skia_images_.end()) {\n \/\/ Load the image\n bitmap = LoadBitmap(theme_dll_, resource_id);\n \/\/ We did not find the bitmap in the theme DLL, try the current one.\n if (!bitmap)\n bitmap = LoadBitmap(_AtlBaseModule.GetModuleInstance(), resource_id);\n skia_images_[resource_id] = bitmap;\n } else {\n bitmap = found->second;\n }\n\n \/\/ This bitmap will be returned when a bitmap is requested that can not be\n \/\/ found. The data inside is lazily initialized, so users must lock and\n static SkBitmap* empty_bitmap = NULL;\n\n \/\/ Handle the case where loading the bitmap failed.\n if (!bitmap) {\n LOG(WARNING) << \"Unable to load bitmap with id \" << resource_id;\n if (!empty_bitmap) {\n empty_bitmap = new SkBitmap();\n }\n return empty_bitmap;\n }\n return bitmap;\n}\n\nbool ResourceBundle::LoadImageResourceBytes(int resource_id,\n vector* bytes) {\n return LoadModuleResourceBytes(theme_dll_, resource_id, bytes);\n}\n\nbool ResourceBundle::LoadDataResourceBytes(int resource_id,\n vector* bytes) {\n return LoadModuleResourceBytes(_AtlBaseModule.GetModuleInstance(),\n resource_id, bytes);\n}\n\nbool ResourceBundle::LoadModuleResourceBytes(\n HINSTANCE module,\n int resource_id,\n std::vector* bytes) {\n void* data_ptr;\n size_t data_size;\n if (base::GetDataResourceFromModule(module, resource_id, &data_ptr,\n &data_size)) {\n bytes->resize(data_size);\n memcpy(&(bytes->front()), data_ptr, data_size);\n return true;\n } else {\n return false;\n }\n}\n\nHICON ResourceBundle::LoadThemeIcon(int icon_id) {\n return ::LoadIcon(theme_dll_, MAKEINTRESOURCE(icon_id));\n}\n\nstd::string ResourceBundle::GetDataResource(int resource_id) {\n return GetRawDataResource(resource_id).as_string();\n}\n\nStringPiece ResourceBundle::GetRawDataResource(int resource_id) {\n void* data_ptr;\n size_t data_size;\n if (base::GetDataResourceFromModule(\n _AtlBaseModule.GetModuleInstance(), resource_id, &data_ptr, &data_size))\n return StringPiece(static_cast(data_ptr), data_size);\n return StringPiece();\n}\n\n\/\/ Loads and returns the global accelerators from the current module.\nHACCEL ResourceBundle::GetGlobalAccelerators() {\n return ::LoadAccelerators(_AtlBaseModule.GetModuleInstance(),\n MAKEINTRESOURCE(IDR_MAINFRAME));\n}\n\n\/\/ Loads and returns a cursor from the current module.\nHCURSOR ResourceBundle::LoadCursor(int cursor_id) {\n return ::LoadCursor(_AtlBaseModule.GetModuleInstance(),\n MAKEINTRESOURCE(cursor_id));\n}\n\nstd::wstring ResourceBundle::GetLocalizedString(int message_id) {\n \/\/ If for some reason we were unable to load a resource dll, return an empty\n \/\/ string (better than crashing).\n if (!locale_resources_dll_)\n return std::wstring();\n\n DCHECK(IS_INTRESOURCE(message_id));\n\n \/\/ Get a reference directly to the string resource.\n HINSTANCE hinstance = locale_resources_dll_;\n const ATLSTRINGRESOURCEIMAGE* image = AtlGetStringResourceImage(hinstance,\n message_id);\n if (!image) {\n \/\/ Fall back on the current module (shouldn't be any strings here except\n \/\/ in unittests).\n image = AtlGetStringResourceImage(_AtlBaseModule.GetModuleInstance(),\n message_id);\n if (!image) {\n NOTREACHED() << \"unable to find resource: \" << message_id;\n return std::wstring();\n }\n }\n \/\/ Copy into a wstring and return.\n return std::wstring(image->achString, image->nLength);\n}\n\nvoid ResourceBundle::LoadFontsIfNecessary() {\n AutoLock lock_scope(lock_);\n if (!base_font_.get()) {\n base_font_.reset(new ChromeFont());\n\n small_font_.reset(new ChromeFont());\n *small_font_ = base_font_->DeriveFont(-2);\n\n medium_font_.reset(new ChromeFont());\n *medium_font_ = base_font_->DeriveFont(3);\n\n medium_bold_font_.reset(new ChromeFont());\n *medium_bold_font_ =\n base_font_->DeriveFont(3, base_font_->style() | ChromeFont::BOLD);\n\n large_font_.reset(new ChromeFont());\n *large_font_ = base_font_->DeriveFont(8);\n\n web_font_.reset(new ChromeFont());\n *web_font_ = base_font_->DeriveFont(1,\n base_font_->style() | ChromeFont::WEB);\n }\n}\n\nChromeFont ResourceBundle::GetFont(FontStyle style) {\n LoadFontsIfNecessary();\n switch(style) {\n case SmallFont:\n return *small_font_;\n case MediumFont:\n return *medium_font_;\n case MediumBoldFont:\n return *medium_bold_font_;\n case LargeFont:\n return *large_font_;\n case WebFont:\n return *web_font_;\n default:\n return *base_font_;\n }\n}\n\n<|endoftext|>"} {"text":"Add CreateMemoryObject function to pass to NaClChromeMainStart()<|endoftext|>"} {"text":"#include \"mainwindow.h\"\n#include \"ui_mainwindow.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n\nMainWindow::MainWindow(QWidget* parent)\n : QMainWindow{parent}, _ui{new Ui::MainWindow},\n _portTimer{}, _image{}, _ezGraver{}, _connected{false} {\n _ui->setupUi(this);\n setAcceptDrops(true);\n\n connect(&_portTimer, &QTimer::timeout, this, &MainWindow::updatePorts);\n _portTimer.start(1000);\n\n initBindings();\n initConversionFlags();\n setConnected(false);\n}\n\nMainWindow::~MainWindow() {\n delete _ui;\n}\n\nvoid MainWindow::initBindings() {\n connect(_ui->burnTime, &QSlider::valueChanged, [this](int const& v) { _ui->burnTimeLabel->setText(QString::number(v)); });\n\n connect(this, &MainWindow::connectedChanged, _ui->ports, &QComboBox::setDisabled);\n connect(this, &MainWindow::connectedChanged, _ui->connect, &QPushButton::setDisabled);\n connect(this, &MainWindow::connectedChanged, _ui->disconnect, &QPushButton::setEnabled);\n\n connect(this, &MainWindow::connectedChanged, _ui->home, &QPushButton::setEnabled);\n connect(this, &MainWindow::connectedChanged, _ui->up, &QPushButton::setEnabled);\n connect(this, &MainWindow::connectedChanged, _ui->left, &QPushButton::setEnabled);\n connect(this, &MainWindow::connectedChanged, _ui->center, &QPushButton::setEnabled);\n connect(this, &MainWindow::connectedChanged, _ui->right, &QPushButton::setEnabled);\n connect(this, &MainWindow::connectedChanged, _ui->down, &QPushButton::setEnabled);\n connect(this, &MainWindow::connectedChanged, _ui->preview, &QPushButton::setEnabled);\n connect(this, &MainWindow::connectedChanged, _ui->start, &QPushButton::setEnabled);\n connect(this, &MainWindow::connectedChanged, _ui->pause, &QPushButton::setEnabled);\n connect(this, &MainWindow::connectedChanged, _ui->reset, &QPushButton::setEnabled);\n connect(_ui->conversionFlags, static_cast(&QComboBox::currentIndexChanged), [this](int index) {\n _ui->image->setConversionFlags(static_cast(_ui->conversionFlags->itemData(index).toInt()));\n });\n\n auto uploadEnabled = [this]() { _ui->upload->setEnabled(_ui->image->imageLoaded() && _connected); };\n connect(this, &MainWindow::connectedChanged, uploadEnabled);\n connect(_ui->image, &ImageLabel::imageLoadedChanged, uploadEnabled);\n}\n\nvoid MainWindow::initConversionFlags() {\n _ui->conversionFlags->addItem(\"DiffuseDither\", Qt::DiffuseDither);\n _ui->conversionFlags->addItem(\"OrderedDither\", Qt::OrderedDither);\n _ui->conversionFlags->addItem(\"ThresholdDither\", Qt::ThresholdDither);\n _ui->conversionFlags->setCurrentIndex(0);\n}\n\nvoid MainWindow::printVerbose(QString const& verbose) {\n _ui->verbose->appendPlainText(verbose);\n}\n\nvoid MainWindow::updatePorts() {\n QStringList ports{EzGraver::availablePorts()};\n ports.insert(0, \"\");\n\n QString original{_ui->ports->currentText()};\n _ui->ports->clear();\n _ui->ports->addItems(ports);\n\n if(ports.contains(original)) {\n _ui->ports->setCurrentText(original);\n }\n}\n\nvoid MainWindow::loadImage(QString const& fileName) {\n printVerbose(QString(\"loading image: %1\").arg(fileName));\n\n QImage image{};\n if(!image.load(fileName)) {\n printVerbose(\"failed to load image\");\n return;\n }\n\n _ui->image->setImage(image);\n}\n\nbool MainWindow::connected() const {\n return _connected;\n}\n\nvoid MainWindow::setConnected(bool connected) {\n _connected = connected;\n emit connectedChanged(connected);\n}\n\nvoid MainWindow::on_connect_clicked() {\n try {\n printVerbose(QString(\"connecting to port %1\").arg(_ui->ports->currentText()));\n _ezGraver = EzGraver::create(_ui->ports->currentText());\n printVerbose(\"connection established successfully\");\n setConnected(true);\n } catch(std::runtime_error const& e) {\n printVerbose(QString(\"Error: %1\").arg(e.what()));\n }\n}\n\nvoid MainWindow::on_home_clicked() {\n printVerbose(\"moving to home\");\n _ezGraver->home();\n}\n\nvoid MainWindow::on_up_clicked() {\n _ezGraver->up();\n}\n\nvoid MainWindow::on_left_clicked() {\n _ezGraver->left();\n}\n\nvoid MainWindow::on_center_clicked() {\n printVerbose(\"moving to center\");\n _ezGraver->center();\n}\n\nvoid MainWindow::on_right_clicked() {\n _ezGraver->right();\n}\n\nvoid MainWindow::on_down_clicked() {\n _ezGraver->down();\n}\n\nvoid MainWindow::on_upload_clicked() {\n QImage image{_ui->image->pixmap()->toImage()};\n\n printVerbose(\"erasing EEPROM\");\n _ezGraver->erase();\n\n QTimer::singleShot(6000, [this, image]() {\n printVerbose(\"uploading image to EEPROM\");\n _ezGraver->uploadImage(image);\n printVerbose(\"upload completed\");\n });\n}\n\nvoid MainWindow::on_preview_clicked() {\n printVerbose(\"drawing preview\");\n _ezGraver->preview();\n}\n\nvoid MainWindow::on_start_clicked() {\n printVerbose(QString(\"starting engrave process with burn time %1\").arg(_ui->burnTime->value()));\n _ezGraver->start(_ui->burnTime->value());\n}\n\nvoid MainWindow::on_pause_clicked() {\n printVerbose(\"pausing engrave process\");\n _ezGraver->pause();\n}\n\nvoid MainWindow::on_reset_clicked() {\n printVerbose(\"resetting engraver\");\n _ezGraver->reset();\n}\n\nvoid MainWindow::on_disconnect_clicked() {\n printVerbose(\"disconnecting\");\n setConnected(false);\n _ezGraver.reset();\n printVerbose(\"disconnected\");\n}\n\nvoid MainWindow::on_image_clicked() {\n auto fileName = QFileDialog::getOpenFileName(this, \"Open Image\", \"\", \"Image Files (*.png *.jpeg *.jpg *.bmp)\");\n loadImage(fileName);\n}\n\nvoid MainWindow::dragEnterEvent(QDragEnterEvent* event) {\n if(event->mimeData()->hasUrls() && event->mimeData()->urls().count() == 1) {\n event->acceptProposedAction();\n }\n}\n\nvoid MainWindow::dropEvent(QDropEvent* event) {\n QString fileName{event->mimeData()->urls()[0].toLocalFile()};\n loadImage(fileName);\n}\n\nAdded check if a file was actually selected before trying to load it.#include \"mainwindow.h\"\n#include \"ui_mainwindow.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n\nMainWindow::MainWindow(QWidget* parent)\n : QMainWindow{parent}, _ui{new Ui::MainWindow},\n _portTimer{}, _image{}, _ezGraver{}, _connected{false} {\n _ui->setupUi(this);\n setAcceptDrops(true);\n\n connect(&_portTimer, &QTimer::timeout, this, &MainWindow::updatePorts);\n _portTimer.start(1000);\n\n initBindings();\n initConversionFlags();\n setConnected(false);\n}\n\nMainWindow::~MainWindow() {\n delete _ui;\n}\n\nvoid MainWindow::initBindings() {\n connect(_ui->burnTime, &QSlider::valueChanged, [this](int const& v) { _ui->burnTimeLabel->setText(QString::number(v)); });\n\n connect(this, &MainWindow::connectedChanged, _ui->ports, &QComboBox::setDisabled);\n connect(this, &MainWindow::connectedChanged, _ui->connect, &QPushButton::setDisabled);\n connect(this, &MainWindow::connectedChanged, _ui->disconnect, &QPushButton::setEnabled);\n\n connect(this, &MainWindow::connectedChanged, _ui->home, &QPushButton::setEnabled);\n connect(this, &MainWindow::connectedChanged, _ui->up, &QPushButton::setEnabled);\n connect(this, &MainWindow::connectedChanged, _ui->left, &QPushButton::setEnabled);\n connect(this, &MainWindow::connectedChanged, _ui->center, &QPushButton::setEnabled);\n connect(this, &MainWindow::connectedChanged, _ui->right, &QPushButton::setEnabled);\n connect(this, &MainWindow::connectedChanged, _ui->down, &QPushButton::setEnabled);\n connect(this, &MainWindow::connectedChanged, _ui->preview, &QPushButton::setEnabled);\n connect(this, &MainWindow::connectedChanged, _ui->start, &QPushButton::setEnabled);\n connect(this, &MainWindow::connectedChanged, _ui->pause, &QPushButton::setEnabled);\n connect(this, &MainWindow::connectedChanged, _ui->reset, &QPushButton::setEnabled);\n connect(_ui->conversionFlags, static_cast(&QComboBox::currentIndexChanged), [this](int index) {\n _ui->image->setConversionFlags(static_cast(_ui->conversionFlags->itemData(index).toInt()));\n });\n\n auto uploadEnabled = [this]() { _ui->upload->setEnabled(_ui->image->imageLoaded() && _connected); };\n connect(this, &MainWindow::connectedChanged, uploadEnabled);\n connect(_ui->image, &ImageLabel::imageLoadedChanged, uploadEnabled);\n}\n\nvoid MainWindow::initConversionFlags() {\n _ui->conversionFlags->addItem(\"DiffuseDither\", Qt::DiffuseDither);\n _ui->conversionFlags->addItem(\"OrderedDither\", Qt::OrderedDither);\n _ui->conversionFlags->addItem(\"ThresholdDither\", Qt::ThresholdDither);\n _ui->conversionFlags->setCurrentIndex(0);\n}\n\nvoid MainWindow::printVerbose(QString const& verbose) {\n _ui->verbose->appendPlainText(verbose);\n}\n\nvoid MainWindow::updatePorts() {\n QStringList ports{EzGraver::availablePorts()};\n ports.insert(0, \"\");\n\n QString original{_ui->ports->currentText()};\n _ui->ports->clear();\n _ui->ports->addItems(ports);\n\n if(ports.contains(original)) {\n _ui->ports->setCurrentText(original);\n }\n}\n\nvoid MainWindow::loadImage(QString const& fileName) {\n printVerbose(QString(\"loading image: %1\").arg(fileName));\n\n QImage image{};\n if(!image.load(fileName)) {\n printVerbose(\"failed to load image\");\n return;\n }\n\n _ui->image->setImage(image);\n}\n\nbool MainWindow::connected() const {\n return _connected;\n}\n\nvoid MainWindow::setConnected(bool connected) {\n _connected = connected;\n emit connectedChanged(connected);\n}\n\nvoid MainWindow::on_connect_clicked() {\n try {\n printVerbose(QString(\"connecting to port %1\").arg(_ui->ports->currentText()));\n _ezGraver = EzGraver::create(_ui->ports->currentText());\n printVerbose(\"connection established successfully\");\n setConnected(true);\n } catch(std::runtime_error const& e) {\n printVerbose(QString(\"Error: %1\").arg(e.what()));\n }\n}\n\nvoid MainWindow::on_home_clicked() {\n printVerbose(\"moving to home\");\n _ezGraver->home();\n}\n\nvoid MainWindow::on_up_clicked() {\n _ezGraver->up();\n}\n\nvoid MainWindow::on_left_clicked() {\n _ezGraver->left();\n}\n\nvoid MainWindow::on_center_clicked() {\n printVerbose(\"moving to center\");\n _ezGraver->center();\n}\n\nvoid MainWindow::on_right_clicked() {\n _ezGraver->right();\n}\n\nvoid MainWindow::on_down_clicked() {\n _ezGraver->down();\n}\n\nvoid MainWindow::on_upload_clicked() {\n QImage image{_ui->image->pixmap()->toImage()};\n\n printVerbose(\"erasing EEPROM\");\n _ezGraver->erase();\n\n QTimer::singleShot(6000, [this, image]() {\n printVerbose(\"uploading image to EEPROM\");\n _ezGraver->uploadImage(image);\n printVerbose(\"upload completed\");\n });\n}\n\nvoid MainWindow::on_preview_clicked() {\n printVerbose(\"drawing preview\");\n _ezGraver->preview();\n}\n\nvoid MainWindow::on_start_clicked() {\n printVerbose(QString(\"starting engrave process with burn time %1\").arg(_ui->burnTime->value()));\n _ezGraver->start(_ui->burnTime->value());\n}\n\nvoid MainWindow::on_pause_clicked() {\n printVerbose(\"pausing engrave process\");\n _ezGraver->pause();\n}\n\nvoid MainWindow::on_reset_clicked() {\n printVerbose(\"resetting engraver\");\n _ezGraver->reset();\n}\n\nvoid MainWindow::on_disconnect_clicked() {\n printVerbose(\"disconnecting\");\n setConnected(false);\n _ezGraver.reset();\n printVerbose(\"disconnected\");\n}\n\nvoid MainWindow::on_image_clicked() {\n auto fileName = QFileDialog::getOpenFileName(this, \"Open Image\", \"\", \"Images (*.png *.jpeg *.jpg *.bmp)\");\n if(!fileName.isNull()) {\n loadImage(fileName);\n }\n}\n\nvoid MainWindow::dragEnterEvent(QDragEnterEvent* event) {\n if(event->mimeData()->hasUrls() && event->mimeData()->urls().count() == 1) {\n event->acceptProposedAction();\n }\n}\n\nvoid MainWindow::dropEvent(QDropEvent* event) {\n QString fileName{event->mimeData()->urls()[0].toLocalFile()};\n loadImage(fileName);\n}\n\n<|endoftext|>"} {"text":"#include \"Frame.h\"\n#include \"SettingsDialog.h\"\n#include \"SettingCfg.h\"\n#include \"config.h\"\n#include \"ToolBar.h\"\n\n#include \"preview\/MainDialog.h\"\n#include \"view\/StagePanel.h\"\n\nnamespace lr\n{\n\nBEGIN_EVENT_TABLE(Frame, d2d::Frame)\n\tEVT_MENU(ID_PREVIEW, Frame::OnPreview)\n\tEVT_MENU(ID_SETING_EXTEND, Frame::OnExtendSetting)\n\tEVT_MENU_RANGE(ID_TOOLBAR+1, ID_TOOLBAR+8, Frame::OnToolBarClick)\nEND_EVENT_TABLE()\n\nFrame::Frame(const wxString& title, const wxString& filetag)\n\t: d2d::Frame(title, filetag)\n{\n\tm_view_menu->Append(ID_PREVIEW, wxT(\"&Preview\\tCtrl+Enter\"), wxT(\"Play\"));\n\tm_setting_menu->Append(ID_SETING_EXTEND, wxT(\"Extend\"), wxT(\"Extend\"));\n\n\tm_toolbar = new ToolBar(this, ID_TOOLBAR);\n}\n\nvoid Frame::onSaveAs(wxCommandEvent& event)\n{\n\tif (!m_task) return;\n\n\ttry {\n\t\twxString filter = GetFileFilter() + \"|PNG files (*.png)|*.png\";\n\t\twxFileDialog dlg(this, wxT(\"Save\"), wxEmptyString, wxEmptyString, filter, wxFD_SAVE);\n\t\tif (dlg.ShowModal() == wxID_OK)\n\t\t{\n\t\t\twxString filename = dlg.GetPath();\n\t\t\twxString ext = d2d::FilenameTools::getExtension(filename);\n\t\t\tif (ext == \"png\") {\n\t\t\t\tSaveAsPNG(filename.ToStdString());\n\t\t\t} else {\n\t\t\t\tSaveAsJson(filename.ToStdString());\n\t\t\t}\n\t\t}\n\t} catch (d2d::Exception& e) {\n\t\td2d::ExceptionDlg dlg(this, e);\n\t\tdlg.ShowModal();\n\t}\n}\n\nvoid Frame::OnToolBarClick(wxCommandEvent& event)\n{\n\tint idx = event.GetId() - ID_TOOLBAR - 1;\n\tm_toolbar->OnClick(idx);\n}\n\nvoid Frame::OnPreview(wxCommandEvent& event)\n{\n\tSettingCfg* cfg = SettingCfg::Instance();\n\n\tstd::vector sprites;\n\tm_task->getAllSprite(sprites);\n\n\tpreview::MainDialog dlg(this, cfg->m_view_width * PREVIEW_SCALE, cfg->m_view_height * PREVIEW_SCALE, sprites);\n\tdlg.ShowModal();\n\n\td2d::EditPanel* stage = const_cast(m_task->getEditPanel());\n\tstage->resetCanvas();\n}\n\nvoid Frame::OnExtendSetting(wxCommandEvent& event)\n{\n\tSettingDialog dlg(this, (StagePanel*)(m_task->getEditPanel()));\n\tdlg.ShowModal();\n}\n\nvoid Frame::SaveAsPNG(const std::string& filepath) const\n{\n\tSettingCfg* cfg = SettingCfg::Instance();\n\td2d::Snapshoot ss(cfg->m_map_width, cfg->m_map_height);\n\tStagePanel* stage = (StagePanel*)(m_task->getEditPanel());\n\tstd::vector sprites;\n\tstage->traverseSprites(d2d::FetchAllVisitor(sprites));\n\tfor (int i = 0, n = sprites.size(); i < n; ++i) {\n\t\tss.DrawSprite(sprites[i]);\n\t}\n\tss.SaveToFile(filepath);\n\n\tstage->getCanvas()->resetInitState();\n}\n\nvoid Frame::SaveAsJson(const std::string& filepath) const\n{\n\twxString fixed = d2d::FilenameTools::getFilenameAddTag(filepath, m_filetag, \"json\");\n\tm_currFilename = fixed;\n\tm_task->store(fixed);\n}\n\n}[FIXED] lr存成图片没有考虑visible#include \"Frame.h\"\n#include \"SettingsDialog.h\"\n#include \"SettingCfg.h\"\n#include \"config.h\"\n#include \"ToolBar.h\"\n\n#include \"preview\/MainDialog.h\"\n#include \"view\/StagePanel.h\"\n\nnamespace lr\n{\n\nBEGIN_EVENT_TABLE(Frame, d2d::Frame)\n\tEVT_MENU(ID_PREVIEW, Frame::OnPreview)\n\tEVT_MENU(ID_SETING_EXTEND, Frame::OnExtendSetting)\n\tEVT_MENU_RANGE(ID_TOOLBAR+1, ID_TOOLBAR+8, Frame::OnToolBarClick)\nEND_EVENT_TABLE()\n\nFrame::Frame(const wxString& title, const wxString& filetag)\n\t: d2d::Frame(title, filetag)\n{\n\tm_view_menu->Append(ID_PREVIEW, wxT(\"&Preview\\tCtrl+Enter\"), wxT(\"Play\"));\n\tm_setting_menu->Append(ID_SETING_EXTEND, wxT(\"Extend\"), wxT(\"Extend\"));\n\n\tm_toolbar = new ToolBar(this, ID_TOOLBAR);\n}\n\nvoid Frame::onSaveAs(wxCommandEvent& event)\n{\n\tif (!m_task) return;\n\n\ttry {\n\t\twxString filter = GetFileFilter() + \"|PNG files (*.png)|*.png\";\n\t\twxFileDialog dlg(this, wxT(\"Save\"), wxEmptyString, wxEmptyString, filter, wxFD_SAVE);\n\t\tif (dlg.ShowModal() == wxID_OK)\n\t\t{\n\t\t\twxString filename = dlg.GetPath();\n\t\t\twxString ext = d2d::FilenameTools::getExtension(filename);\n\t\t\tif (ext == \"png\") {\n\t\t\t\tSaveAsPNG(filename.ToStdString());\n\t\t\t} else {\n\t\t\t\tSaveAsJson(filename.ToStdString());\n\t\t\t}\n\t\t}\n\t} catch (d2d::Exception& e) {\n\t\td2d::ExceptionDlg dlg(this, e);\n\t\tdlg.ShowModal();\n\t}\n}\n\nvoid Frame::OnToolBarClick(wxCommandEvent& event)\n{\n\tint idx = event.GetId() - ID_TOOLBAR - 1;\n\tm_toolbar->OnClick(idx);\n}\n\nvoid Frame::OnPreview(wxCommandEvent& event)\n{\n\tSettingCfg* cfg = SettingCfg::Instance();\n\n\tstd::vector sprites;\n\tm_task->getAllSprite(sprites);\n\n\tpreview::MainDialog dlg(this, cfg->m_view_width * PREVIEW_SCALE, cfg->m_view_height * PREVIEW_SCALE, sprites);\n\tdlg.ShowModal();\n\n\td2d::EditPanel* stage = const_cast(m_task->getEditPanel());\n\tstage->resetCanvas();\n}\n\nvoid Frame::OnExtendSetting(wxCommandEvent& event)\n{\n\tSettingDialog dlg(this, (StagePanel*)(m_task->getEditPanel()));\n\tdlg.ShowModal();\n}\n\nvoid Frame::SaveAsPNG(const std::string& filepath) const\n{\n\tSettingCfg* cfg = SettingCfg::Instance();\n\td2d::Snapshoot ss(cfg->m_map_width, cfg->m_map_height);\n\tStagePanel* stage = (StagePanel*)(m_task->getEditPanel());\n\tstd::vector sprites;\n\tstage->traverseSprites(d2d::FetchAllVisitor(sprites), d2d::DT_VISIBLE);\n\tfor (int i = 0, n = sprites.size(); i < n; ++i) {\n\t\tss.DrawSprite(sprites[i]);\n\t}\n\tss.SaveToFile(filepath);\n\n\tstage->getCanvas()->resetInitState();\n}\n\nvoid Frame::SaveAsJson(const std::string& filepath) const\n{\n\twxString fixed = d2d::FilenameTools::getFilenameAddTag(filepath, m_filetag, \"json\");\n\tm_currFilename = fixed;\n\tm_task->store(fixed);\n}\n\n}<|endoftext|>"} {"text":"#include \n\nusing namespace std;\ntypedef long long int ll;\ntypedef pair P;\ntypedef pair Pll;\ntypedef vector Vi;\n#define FOR(i,s,x) for(int i=s;i<(int)(x);i++)\n#define REP(i,x) FOR(i,0,x)\n#define PB push_back\n#define MP make_pair\n#define DUMP( x ) cerr << #x << \" = \" << ( x ) << endl\n#define fst first\n#define snd second\n\nint main() {\n\n return 0;\n}\nedit template of C++#include \n\nusing namespace std;\ntypedef long long int ll;\ntypedef pair P;\ntypedef pair Pll;\ntypedef vector Vi;\ntypedef tuple T;\n#define FOR(i,s,x) for(int i=s;i<(int)(x);i++)\n#define REP(i,x) FOR(i,0,x)\n#define ALL(c) c.begin(), c.end()\n#define MP make_pair\n#define DUMP( x ) cerr << #x << \" = \" << ( x ) << endl\n#define fst first\n#define snd second\n\nint main() {\n\n return 0;\n}\n<|endoftext|>"} {"text":"#include \"FirehoseLibraryClient.h\"\r\n#include \r\n#include \r\n#include \r\n\r\n#include \r\n#include \r\n#include \r\n#include \r\n\r\n#include \r\n\r\n#include \r\n#include \r\n#include \r\n#include \r\n\r\n#include \r\n\r\n#define DEBUG_INFO \r\n\r\nusing namespace std;\r\nusing namespace Aws;\r\nusing namespace Aws::Http;\r\nusing namespace Aws::Auth;\r\nusing namespace Aws::Client;\r\nusing namespace Aws::Firehose;\r\nusing namespace Aws::Firehose::Model;\r\nusing namespace Aws::Utils::Json;\r\n\r\n\/\/Constructor\r\nFirehoseLibraryClient::FirehoseLibraryClient(string streamName, std::string bucketName) :\r\n m_firehoseClient(nullptr),\r\n m_config(new ClientConfiguration()),\r\n m_streamName(streamName),\r\n m_bucketName(bucketName),\r\n m_options(new Aws::SDKOptions()),\r\n m_initialized(false)\r\n{\r\n \/\/m_options = new Aws::SDKOptions;\r\n m_options->loggingOptions.logLevel = Aws::Utils::Logging::LogLevel::Trace;\r\n Aws::InitAPI(*m_options);\r\n\r\n m_config->scheme = Scheme::HTTPS;\r\n m_config->region = Region::US_EAST_1;\r\n\r\n m_firehoseClient = new FirehoseClient(*m_config);\r\n}\r\n\r\n\r\n\/\/destructor\r\nFirehoseLibraryClient::~FirehoseLibraryClient()\r\n{\r\n\tAws::ShutdownAPI(*m_options);\r\n}\r\n\r\nbool FirehoseLibraryClient::initQueue(std::string bucketPrefix)\r\n{\r\n auto cognitoClient = Aws::MakeShared(\"QueueOperationTest\", *m_config);\r\n auto iamClient = Aws::MakeShared(\"QueueOperationTest\", *m_config);\r\n Aws::AccessManagement::AccessManagementClient accessManagementClient(iamClient, cognitoClient);\r\n \r\n Aws::String accountId = accessManagementClient.GetAccountId();\r\n \r\n Aws::String user;\r\n Aws::IAM::Model::User data;\r\n\r\n accessManagementClient.GetUser(user, data);\r\n#ifdef DEBUG_INFO \r\n cout << \"Account ID : \" << accountId << user <CreateDeliveryStream(request);\r\n if (outcome.IsSuccess())\r\n {\r\n cout << \"Succesfull created new deliverystream [\" << m_streamName << \"]\" << endl ;\r\n m_initialized = true;\r\n return true;\r\n }else if (outcome.GetError().GetErrorType() == FirehoseErrors::RESOURCE_IN_USE){\r\n#ifdef DEBUG_INFO\r\n cout << \"Resource in use, stream [\" << m_streamName << \"] exists already\"<< endl;\r\n#endif\r\n m_initialized = true;\r\n return true;\r\n }else if (outcome.GetError().GetErrorType() == FirehoseErrors::LIMIT_EXCEEDED){\r\n cout << \"Limit Exceeded \"<< endl;\r\n }else if (outcome.GetError().GetErrorType() == FirehoseErrors::ACCESS_DENIED){\r\n cout << \"Access Denied \"<< endl;\r\n }else{\r\n cout << \"Other error.... [\" << outcome.GetError().GetMessage() << \"]\" << endl;\r\n }\r\n return false;\r\n}\r\n\r\nbool FirehoseLibraryClient::sendMessage(const ifstream& data, int repetitions\/* = 0*\/)\r\n{\r\n if(!m_initialized)\r\n {\r\n\tcout << \"Not Initialized.\" << endl;\r\n\treturn false;\r\n }\r\n \r\n PutRecordRequest request;\r\n \/\/set stream name;\r\n Aws::String __streamName(\"TMP\");\r\n request.SetDeliveryStreamName(m_streamName.c_str());\r\n \r\n Record record;\r\n\r\n Aws::StringStream dataStream;\r\n dataStream << data.rdbuf();\r\n\r\n#ifdef DEBUG_INFO \r\n cout << \"Buff Size to transfer: [\" << dataStream.str().length() << \"]\" << endl;\r\n#endif\r\n Aws::Utils::ByteBuffer buff((unsigned char*)dataStream.str().c_str(), dataStream.str().length());\r\n \r\n \/\/apply stream data to record buffer Data\r\n record.SetData(buff);\r\n \r\n \/\/set record to request\r\n request.SetRecord(record);\r\n \/\/for loop is for testing purposes only\r\n for(int i = 0; i <= repetitions; i++)\r\n {\r\n \/\/send request to cloud\r\n Model::PutRecordOutcome outcome = m_firehoseClient->PutRecord(request);\r\n if(!outcome.IsSuccess())\r\n {\r\n cout << \"Error sending message \" << i + 1 << \".\" << endl;\r\n i = repetitions;\r\n return false;\r\n }\r\n }\r\n return true;\r\n}\r\n\r\n\r\n\r\nbool FirehoseLibraryClient::sendMessage(const std::vector& dataVector)\r\n{\r\n if(!m_initialized)\r\n {\r\n\tcout << \"Not Initialized.\" << endl;\r\n\treturn false;\r\n }\r\n\r\n PutRecordRequest request;\r\n \/\/set stream name;\r\n Aws::String __streamName(\"TMP\");\r\n request.SetDeliveryStreamName(m_streamName.c_str());\r\n\r\n Record record;\r\n\r\n \/\/Aws::StringStream dataStream;\r\n \/\/dataStream << data.rdbuf();\r\n\r\n#ifdef DEBUG_INFO\r\n cout << \"Buff Size to transfer: [\" << dataVector.size() << \"]\" << endl;\r\n#endif\r\n Aws::Utils::ByteBuffer buff((unsigned char*)&dataVector[0], dataVector.size());\r\n\r\n \/\/apply stream data to record buffer Data\r\n record.SetData(buff);\r\n\r\n \/\/set record to request\r\n request.SetRecord(record);\r\n \/\/for loop is for testing purposes only\r\n \/\/send request to cloud\r\n Model::PutRecordOutcome outcome = m_firehoseClient->PutRecord(request);\r\n if(!outcome.IsSuccess())\r\n {\r\n cout << \"Error sending message .\" << endl;\r\n return false;\r\n }\r\n return true;\r\n}\r\nadd underscore to prefix#include \"FirehoseLibraryClient.h\"\r\n#include \r\n#include \r\n#include \r\n\r\n#include \r\n#include \r\n#include \r\n#include \r\n\r\n#include \r\n\r\n#include \r\n#include \r\n#include \r\n#include \r\n\r\n#include \r\n\r\n#define DEBUG_INFO \r\n\r\nusing namespace std;\r\nusing namespace Aws;\r\nusing namespace Aws::Http;\r\nusing namespace Aws::Auth;\r\nusing namespace Aws::Client;\r\nusing namespace Aws::Firehose;\r\nusing namespace Aws::Firehose::Model;\r\nusing namespace Aws::Utils::Json;\r\n\r\n\/\/Constructor\r\nFirehoseLibraryClient::FirehoseLibraryClient(string streamName, std::string bucketName) :\r\n m_firehoseClient(nullptr),\r\n m_config(new ClientConfiguration()),\r\n m_streamName(streamName),\r\n m_bucketName(bucketName),\r\n m_options(new Aws::SDKOptions()),\r\n m_initialized(false)\r\n{\r\n \/\/m_options = new Aws::SDKOptions;\r\n m_options->loggingOptions.logLevel = Aws::Utils::Logging::LogLevel::Trace;\r\n Aws::InitAPI(*m_options);\r\n\r\n m_config->scheme = Scheme::HTTPS;\r\n m_config->region = Region::US_EAST_1;\r\n\r\n m_firehoseClient = new FirehoseClient(*m_config);\r\n}\r\n\r\n\r\n\/\/destructor\r\nFirehoseLibraryClient::~FirehoseLibraryClient()\r\n{\r\n\tAws::ShutdownAPI(*m_options);\r\n}\r\n\r\nbool FirehoseLibraryClient::initQueue(std::string bucketPrefix)\r\n{\r\n auto cognitoClient = Aws::MakeShared(\"QueueOperationTest\", *m_config);\r\n auto iamClient = Aws::MakeShared(\"QueueOperationTest\", *m_config);\r\n Aws::AccessManagement::AccessManagementClient accessManagementClient(iamClient, cognitoClient);\r\n \r\n Aws::String accountId = accessManagementClient.GetAccountId();\r\n \r\n \/\/Aws::String user;\r\n \/\/Aws::IAM::Model::User data;\r\n\r\n \/\/accessManagementClient.GetUser(user, data);\r\n#ifdef DEBUG_INFO \r\n cout << \"Account ID : \" << accountId << \/*user <<*\/ endl;\r\n#endif\r\n \r\n CreateDeliveryStreamRequest request;\r\n\r\n request.SetDeliveryStreamName(m_streamName.c_str());\r\n\r\n S3DestinationConfiguration s3Config;\r\n\r\n \/\/TBD; role is fixed now... \r\n Aws::String roleARN = \"arn:aws:iam::\" + accountId + \":role\/firehose_delivery_role\";\r\n string bucketARN(\"arn:aws:s3:::\" + m_bucketName);\r\n Aws::String _bucketPrefix = bucketPrefix.c_str();\r\n _bucketPrefix += \"_\";\r\n\r\n s3Config.SetRoleARN(roleARN);\r\n s3Config.SetBucketARN(bucketARN.c_str());\r\n s3Config.SetPrefix(_bucketPrefix);\r\n s3Config.SetBufferingHints(BufferingHints());\r\n s3Config.SetCompressionFormat(CompressionFormat::UNCOMPRESSED);\r\n s3Config.SetEncryptionConfiguration(EncryptionConfiguration());\r\n request.SetS3DestinationConfiguration(s3Config);\r\n \r\n CreateDeliveryStreamOutcome outcome = m_firehoseClient->CreateDeliveryStream(request);\r\n if (outcome.IsSuccess())\r\n {\r\n cout << \"Succesfull created new deliverystream [\" << m_streamName << \"]\" << endl ;\r\n m_initialized = true;\r\n return true;\r\n }else if (outcome.GetError().GetErrorType() == FirehoseErrors::RESOURCE_IN_USE){\r\n#ifdef DEBUG_INFO\r\n cout << \"Resource in use, stream [\" << m_streamName << \"] exists already\"<< endl;\r\n#endif\r\n m_initialized = true;\r\n return true;\r\n }else if (outcome.GetError().GetErrorType() == FirehoseErrors::LIMIT_EXCEEDED){\r\n cout << \"Limit Exceeded \"<< endl;\r\n }else if (outcome.GetError().GetErrorType() == FirehoseErrors::ACCESS_DENIED){\r\n cout << \"Access Denied \"<< endl;\r\n }else{\r\n cout << \"Other error.... [\" << outcome.GetError().GetMessage() << \"]\" << endl;\r\n }\r\n return false;\r\n}\r\n\r\nbool FirehoseLibraryClient::sendMessage(const ifstream& data, int repetitions\/* = 0*\/)\r\n{\r\n if(!m_initialized)\r\n {\r\n\tcout << \"Not Initialized.\" << endl;\r\n\treturn false;\r\n }\r\n \r\n PutRecordRequest request;\r\n \/\/set stream name;\r\n Aws::String __streamName(\"TMP\");\r\n request.SetDeliveryStreamName(m_streamName.c_str());\r\n \r\n Record record;\r\n\r\n Aws::StringStream dataStream;\r\n dataStream << data.rdbuf();\r\n\r\n#ifdef DEBUG_INFO \r\n cout << \"Buff Size to transfer: [\" << dataStream.str().length() << \"]\" << endl;\r\n#endif\r\n Aws::Utils::ByteBuffer buff((unsigned char*)dataStream.str().c_str(), dataStream.str().length());\r\n \r\n \/\/apply stream data to record buffer Data\r\n record.SetData(buff);\r\n \r\n \/\/set record to request\r\n request.SetRecord(record);\r\n \/\/for loop is for testing purposes only\r\n for(int i = 0; i <= repetitions; i++)\r\n {\r\n \/\/send request to cloud\r\n Model::PutRecordOutcome outcome = m_firehoseClient->PutRecord(request);\r\n if(!outcome.IsSuccess())\r\n {\r\n cout << \"Error sending message \" << i + 1 << \".\" << endl;\r\n i = repetitions;\r\n return false;\r\n }\r\n }\r\n return true;\r\n}\r\n\r\n\r\n\r\nbool FirehoseLibraryClient::sendMessage(const std::vector& dataVector)\r\n{\r\n if(!m_initialized)\r\n {\r\n\tcout << \"Not Initialized.\" << endl;\r\n\treturn false;\r\n }\r\n\r\n PutRecordRequest request;\r\n \/\/set stream name;\r\n Aws::String __streamName(\"TMP\");\r\n request.SetDeliveryStreamName(m_streamName.c_str());\r\n\r\n Record record;\r\n\r\n \/\/Aws::StringStream dataStream;\r\n \/\/dataStream << data.rdbuf();\r\n\r\n#ifdef DEBUG_INFO\r\n cout << \"Buff Size to transfer: [\" << dataVector.size() << \"]\" << endl;\r\n#endif\r\n Aws::Utils::ByteBuffer buff((unsigned char*)&dataVector[0], dataVector.size());\r\n\r\n \/\/apply stream data to record buffer Data\r\n record.SetData(buff);\r\n\r\n \/\/set record to request\r\n request.SetRecord(record);\r\n \/\/for loop is for testing purposes only\r\n \/\/send request to cloud\r\n Model::PutRecordOutcome outcome = m_firehoseClient->PutRecord(request);\r\n if(!outcome.IsSuccess())\r\n {\r\n cout << \"Error sending message .\" << endl;\r\n return false;\r\n }\r\n return true;\r\n}\r\n<|endoftext|>"} {"text":"#pragma once\n\n#include \n#include \n\nstatic volatile unsigned overflowCount = 0;\n\n\/\/ Timer0 ticks every 64 cycles\n\/\/ Overflow happens every 256 ticks\nISR(TIMER0_OVF_vect)\n{\n ++overflowCount;\n}\n\n\/\/ returns milliseconds\nstatic unsigned long now()\n{\n return overflowCount * (unsigned long)(64LL * 256 * 1000 \/ CLOCK);\n}\n\nstatic void delay(unsigned ms)\n{\n unsigned long end = now()+ms;\n while (now() < end);\n}\nFix time bugs.#pragma once\n\n#include \n#include \n\nstatic volatile uint32_t overflowCount = 0;\n\n\/\/ Timer0 ticks every 64 cycles\n\/\/ Overflow happens every 256 ticks\nISR(TIMER0_OVF_vect)\n{\n ++overflowCount;\n}\n\nstatic uint32_t now_nonstandard()\n{\n return overflowCount * 2 \/ (CLOCK \/ 8000000);\n}\n\nstatic void delay_nonstandard(unsigned time)\n{\n uint32_t end = now_nonstandard() + time;\n while (now_nonstandard() < end);\n}\n\n#define delay(ms) delay_nonstandard(ms*1024ULL\/1000);\n<|endoftext|>"} {"text":"\/***************************************************************************\n * Copyright (C) 2006 by Tobias Koenig *\n * *\n * This program is free software; you can redistribute it and\/or modify *\n * it under the terms of the GNU Library General Public License as *\n * published by the Free Software Foundation; either version 2 of the *\n * License, or (at your option) any later version. *\n * *\n * This program is distributed in the hope that it will be useful, *\n * but WITHOUT ANY WARRANTY; without even the implied warranty of *\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *\n * GNU General Public License for more details. *\n * *\n * You should have received a copy of the GNU Library General Public *\n * License along with this program; if not, write to the *\n * Free Software Foundation, Inc., *\n * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *\n ***************************************************************************\/\n\n#include \"fetch.h\"\n\n#include \"akonadi.h\"\n#include \"akonadiconnection.h\"\n#include \"imapparser.h\"\n#include \"response.h\"\n#include \"storage\/selectquerybuilder.h\"\n#include \"resourceinterface.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace Akonadi;\n\nFetch::Fetch()\n : Handler()\n{\n}\n\nFetch::~Fetch()\n{\n}\n\nbool Fetch::handleLine( const QByteArray& line )\n{\n \/\/ parse the command\n QByteArray buffer;\n int pos = ImapParser::parseString( line, buffer );\n\n \/\/ command\n bool isUidFetch = false;\n pos = ImapParser::parseString( line, buffer, pos );\n if ( buffer == \"UID\" ) {\n isUidFetch = true;\n pos = ImapParser::parseString( line, buffer, pos );\n }\n\n \/\/ sequence set\n ImapSet set;\n pos = ImapParser::parseSequenceSet( line, set, pos );\n if ( set.isEmpty() )\n return failureResponse( \"Invalid sequence set\" );\n\n \/\/ macro vs. attribute list\n pos = ImapParser::stripLeadingSpaces( line, pos );\n if ( pos >= line.count() )\n return failureResponse( \"Premature end of command\" );\n QList attrList;\n bool allParts = false;\n if ( line[pos] == '(' ) {\n pos = ImapParser::parseParenthesizedList( line, attrList, pos );\n } else {\n pos = ImapParser::parseString( line, buffer, pos );\n if ( buffer == \"AKALL\" ) {\n allParts = true;\n } else if ( buffer == \"ALL\" ) {\n attrList << \"FLAGS\" << \"INTERNALDATE\" << \"RFC822.SIZE\" << \"ENVELOPE\";\n } else if ( buffer == \"FULL\" ) {\n attrList << \"FLAGS\" << \"INTERNALDATE\" << \"RFC822.SIZE\";\n } else if ( buffer == \"FAST\" ) {\n attrList << \"FLAGS\" << \"INTERNALDATE\" << \"RFC822.SIZE\" << \"ENVELOPE\" << \"BODY\";\n } else {\n return failureResponse( \"Unsupported macro\" );\n }\n }\n\n triggerOnDemandFetch( isUidFetch );\n\n \/\/ build item query\n QueryBuilder itemQuery;\n itemQuery.addTable( PimItem::tableName() );\n itemQuery.addTable( MimeType::tableName() );\n itemQuery.addTable( Location::tableName() );\n itemQuery.addTable( Resource::tableName() );\n itemQuery.addColumn( PimItem::idFullColumnName() );\n itemQuery.addColumn( PimItem::revFullColumnName() );\n itemQuery.addColumn( PimItem::remoteIdFullColumnName() );\n itemQuery.addColumn( MimeType::nameFullColumnName() );\n itemQuery.addColumn( Resource::nameFullColumnName() );\n itemQuery.addColumnCondition( PimItem::mimeTypeIdFullColumnName(), Query::Equals, MimeType::idFullColumnName() );\n itemQuery.addColumnCondition( PimItem::locationIdFullColumnName(), Query::Equals, Location::idFullColumnName() );\n itemQuery.addColumnCondition( Location::resourceIdFullColumnName(), Query::Equals, Resource::idFullColumnName() );\n imapSetToQuery( set, isUidFetch, itemQuery );\n itemQuery.addSortColumn( PimItem::idFullColumnName(), Query::Ascending );\n const int itemQueryIdColumn = 0;\n const int itemQueryRevColumn = 1;\n const int itemQueryRidColumn = 2;\n const int itemQueryMimeTypeColumn = 3;\n const int itemQueryResouceColumn = 4;\n\n if ( !itemQuery.exec() )\n return failureResponse( \"Unable to list items\" );\n itemQuery.query().next();\n\n \/\/ build flag query if needed\n QueryBuilder flagQuery;\n if ( attrList.contains( \"FLAGS\" ) || allParts ) {\n flagQuery.addTable( PimItem::tableName() );\n flagQuery.addTable( PimItemFlagRelation::tableName() );\n flagQuery.addTable( Flag::tableName() );\n flagQuery.addColumn( PimItem::idFullColumnName() );\n flagQuery.addColumn( Flag::nameFullColumnName() );\n flagQuery.addColumnCondition( PimItem::idFullColumnName(), Query::Equals, PimItemFlagRelation::leftFullColumnName() );\n flagQuery.addColumnCondition( Flag::idFullColumnName(), Query::Equals, PimItemFlagRelation::rightFullColumnName() );\n imapSetToQuery( set, isUidFetch, flagQuery );\n flagQuery.addSortColumn( PimItem::idFullColumnName(), Query::Ascending );\n\n if ( !flagQuery.exec() )\n return failureResponse( \"Unable to retrieve item flags\" );\n flagQuery.query().next();\n }\n const int flagQueryIdColumn = 0;\n const int flagQueryNameColumn = 1;\n\n \/\/ build part query if needed\n QueryBuilder partQuery;\n QStringList partList;\n foreach( const QByteArray b, attrList ) {\n \/\/ filter out non-part attributes\n if ( b == \"REV\" || b == \"FLAGS\" || b == \"UID\" || b == \"REMOTEID\" )\n continue;\n if ( b == \"RFC822.SIZE\" )\n partList << QString::fromLatin1( \"RFC822\" );\n else\n partList << QString::fromLatin1( b );\n }\n if ( !partList.isEmpty() || allParts || attrList.contains( \"RFC822.SIZE\" ) ) {\n partQuery.addTable( PimItem::tableName() );\n partQuery.addTable( Part::tableName() );\n partQuery.addColumn( PimItem::idFullColumnName() );\n partQuery.addColumn( Part::nameFullColumnName() );\n partQuery.addColumn( Part::dataFullColumnName() );\n partQuery.addColumnCondition( PimItem::idFullColumnName(), Query::Equals, Part::pimItemIdFullColumnName() );\n if ( !allParts )\n partQuery.addValueCondition( Part::nameFullColumnName(), Query::In, partList );\n imapSetToQuery( set, isUidFetch, partQuery );\n partQuery.addSortColumn( PimItem::idFullColumnName(), Query::Ascending );\n\n if ( !partQuery.exec() )\n return failureResponse( \"Unable to retrieve item parts\" );\n partQuery.query().next();\n }\n const int partQueryIdColumn = 0;\n const int partQueryNameColumn = 1;\n const int partQueryDataColumn = 2;\n\n \/\/ fetch not yet cached item parts\n \/\/ TODO: I'm sure this can be done with a single query instead of manually\n DataStore *store = connection()->storageBackend();\n if ( !partList.isEmpty() || allParts ) {\n while ( itemQuery.query().isValid() ) {\n const int pimItemId = itemQuery.query().value( itemQueryIdColumn ).toInt();\n QStringList missingParts = partList;\n while ( partQuery.query().isValid() ) {\n const int id = partQuery.query().value( partQueryIdColumn ).toInt();\n if ( id < pimItemId ) {\n partQuery.query().next();\n continue;\n } else if ( id > pimItemId ) {\n break;\n }\n const QString partName = partQuery.query().value( partQueryNameColumn ).toString();\n if ( partQuery.query().value( partQueryDataColumn ).toByteArray().isNull() ) {\n if ( allParts )\n missingParts << partName;\n } else {\n missingParts.removeAll( partName );\n }\n partQuery.query().next();\n }\n if ( !missingParts.isEmpty() ) {\n store->retrieveDataFromResource( pimItemId, itemQuery.query().value( itemQueryRidColumn ).toString().toUtf8(),\n itemQuery.query().value( itemQueryResouceColumn ).toString(), missingParts );\n }\n itemQuery.query().next();\n }\n\n \/\/ re-exec part query, rewind item query\n itemQuery.query().first();\n if ( !partQuery.query().exec() )\n return failureResponse( \"Unable to retrieve item parts\" );\n partQuery.query().next();\n }\n\n \/\/ build responses\n Response response;\n response.setUntagged();\n while ( itemQuery.query().isValid() ) {\n const int pimItemId = itemQuery.query().value( itemQueryIdColumn ).toInt();\n const int pimItemRev = itemQuery.query().value( itemQueryRevColumn ).toInt();\n QList attributes;\n attributes.append( \"UID \" + QByteArray::number( pimItemId ) );\n attributes.append( \"REV \" + QByteArray::number( pimItemRev ) );\n attributes.append( \"REMOTEID \" + ImapParser::quote( itemQuery.query().value( itemQueryRidColumn ).toString().toUtf8() ) );\n attributes.append( \"MIMETYPE \" + ImapParser::quote( itemQuery.query().value( itemQueryMimeTypeColumn ).toString().toUtf8() ) );\n\n if ( attrList.contains( \"FLAGS\" ) ) {\n QList flags;\n while ( flagQuery.query().isValid() ) {\n const int id = flagQuery.query().value( flagQueryIdColumn ).toInt();\n if ( id < pimItemId ) {\n flagQuery.query().next();\n continue;\n } else if ( id > pimItemId ) {\n break;\n }\n flags << flagQuery.query().value( flagQueryNameColumn ).toString().toUtf8();\n flagQuery.query().next();\n }\n attributes.append( \"FLAGS (\" + ImapParser::join( flags, \" \" ) + ')' );\n }\n\n while ( partQuery.query().isValid() ) {\n const int id = partQuery.query().value( partQueryIdColumn ).toInt();\n if ( id < pimItemId ) {\n partQuery.query().next();\n continue;\n } else if ( id > pimItemId ) {\n break;\n }\n QByteArray partName = partQuery.query().value( partQueryNameColumn ).toString().toUtf8();\n QByteArray part = partQuery.query().value( partQueryNameColumn ).toString().toUtf8();\n QByteArray data = partQuery.query().value( partQueryDataColumn ).toByteArray();\n if ( data.isNull() ) {\n part += \" NIL\";\n } else if ( data.isEmpty() ) {\n part += \" \\\"\\\"\";\n } else {\n part += \" {\" + QByteArray::number( data.length() ) + \"}\\n\";\n part += data;\n }\n \/\/ return only requested parts (when RFC822.SIZE is requested, RFC822 is retrieved, but should not be returned)\n if ( attrList.contains( partName ) || allParts )\n attributes << part;\n\n if ( partName == \"RFC822\" && attrList.contains( \"RFC822.SIZE\" ) )\n attributes.append( \"RFC822.SIZE \" + QByteArray::number( data.length() ) );\n\n partQuery.query().next();\n }\n\n \/\/ IMAP protocol violation: should actually be the sequence number\n QByteArray attr = QByteArray::number( pimItemId ) + \" FETCH (\";\n attr += ImapParser::join( attributes, \" \" ) + ')';\n response.setUntagged();\n response.setString( attr );\n emit responseAvailable( response );\n\n itemQuery.query().next();\n }\n\n \/\/ update atime\n updateItemAccessTime( set, isUidFetch );\n\n response.setTag( tag() );\n response.setSuccess();\n if ( isUidFetch )\n response.setString( \"UID FETCH completed\" );\n else\n response.setString( \"FETCH completed\" );\n emit responseAvailable( response );\n deleteLater();\n return true;\n}\n\nvoid Fetch::updateItemAccessTime(const ImapSet & set, bool isUidFetch)\n{\n QueryBuilder qb( QueryBuilder::Update );\n qb.addTable( PimItem::tableName() );\n qb.updateColumnValue( PimItem::atimeColumn(), QDateTime::currentDateTime() );\n imapSetToQuery( set, isUidFetch, qb );\n if ( !qb.exec() )\n qWarning() << \"Unable to update item access time\";\n}\n\nvoid Fetch::triggerOnDemandFetch(bool isUidFetch)\n{\n if ( isUidFetch || connection()->selectedCollection() <= 0 )\n return;\n Location loc = connection()->selectedLocation();\n \/\/ HACK: don't trigger on-demand syncing if the resource is the one triggering it\n if ( connection()->sessionId() == loc.resource().name().toLatin1() )\n return;\n DataStore *store = connection()->storageBackend();\n store->activeCachePolicy( loc );\n if ( !loc.cachePolicySyncOnDemand() )\n return;\n store->triggerCollectionSync( loc );\n}\nSpecial parts prefixed by \"akonadi-\" will never be fetched in the ressource. This is useful for agent-specific configuration for instance.\/***************************************************************************\n * Copyright (C) 2006 by Tobias Koenig *\n * *\n * This program is free software; you can redistribute it and\/or modify *\n * it under the terms of the GNU Library General Public License as *\n * published by the Free Software Foundation; either version 2 of the *\n * License, or (at your option) any later version. *\n * *\n * This program is distributed in the hope that it will be useful, *\n * but WITHOUT ANY WARRANTY; without even the implied warranty of *\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *\n * GNU General Public License for more details. *\n * *\n * You should have received a copy of the GNU Library General Public *\n * License along with this program; if not, write to the *\n * Free Software Foundation, Inc., *\n * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *\n ***************************************************************************\/\n\n#include \"fetch.h\"\n\n#include \"akonadi.h\"\n#include \"akonadiconnection.h\"\n#include \"imapparser.h\"\n#include \"response.h\"\n#include \"storage\/selectquerybuilder.h\"\n#include \"resourceinterface.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace Akonadi;\n\nFetch::Fetch()\n : Handler()\n{\n}\n\nFetch::~Fetch()\n{\n}\n\nbool Fetch::handleLine( const QByteArray& line )\n{\n \/\/ parse the command\n QByteArray buffer;\n int pos = ImapParser::parseString( line, buffer );\n\n \/\/ command\n bool isUidFetch = false;\n pos = ImapParser::parseString( line, buffer, pos );\n if ( buffer == \"UID\" ) {\n isUidFetch = true;\n pos = ImapParser::parseString( line, buffer, pos );\n }\n\n \/\/ sequence set\n ImapSet set;\n pos = ImapParser::parseSequenceSet( line, set, pos );\n if ( set.isEmpty() )\n return failureResponse( \"Invalid sequence set\" );\n\n \/\/ macro vs. attribute list\n pos = ImapParser::stripLeadingSpaces( line, pos );\n if ( pos >= line.count() )\n return failureResponse( \"Premature end of command\" );\n QList attrList;\n bool allParts = false;\n if ( line[pos] == '(' ) {\n pos = ImapParser::parseParenthesizedList( line, attrList, pos );\n } else {\n pos = ImapParser::parseString( line, buffer, pos );\n if ( buffer == \"AKALL\" ) {\n allParts = true;\n } else if ( buffer == \"ALL\" ) {\n attrList << \"FLAGS\" << \"INTERNALDATE\" << \"RFC822.SIZE\" << \"ENVELOPE\";\n } else if ( buffer == \"FULL\" ) {\n attrList << \"FLAGS\" << \"INTERNALDATE\" << \"RFC822.SIZE\";\n } else if ( buffer == \"FAST\" ) {\n attrList << \"FLAGS\" << \"INTERNALDATE\" << \"RFC822.SIZE\" << \"ENVELOPE\" << \"BODY\";\n } else {\n return failureResponse( \"Unsupported macro\" );\n }\n }\n\n triggerOnDemandFetch( isUidFetch );\n\n \/\/ build item query\n QueryBuilder itemQuery;\n itemQuery.addTable( PimItem::tableName() );\n itemQuery.addTable( MimeType::tableName() );\n itemQuery.addTable( Location::tableName() );\n itemQuery.addTable( Resource::tableName() );\n itemQuery.addColumn( PimItem::idFullColumnName() );\n itemQuery.addColumn( PimItem::revFullColumnName() );\n itemQuery.addColumn( PimItem::remoteIdFullColumnName() );\n itemQuery.addColumn( MimeType::nameFullColumnName() );\n itemQuery.addColumn( Resource::nameFullColumnName() );\n itemQuery.addColumnCondition( PimItem::mimeTypeIdFullColumnName(), Query::Equals, MimeType::idFullColumnName() );\n itemQuery.addColumnCondition( PimItem::locationIdFullColumnName(), Query::Equals, Location::idFullColumnName() );\n itemQuery.addColumnCondition( Location::resourceIdFullColumnName(), Query::Equals, Resource::idFullColumnName() );\n imapSetToQuery( set, isUidFetch, itemQuery );\n itemQuery.addSortColumn( PimItem::idFullColumnName(), Query::Ascending );\n const int itemQueryIdColumn = 0;\n const int itemQueryRevColumn = 1;\n const int itemQueryRidColumn = 2;\n const int itemQueryMimeTypeColumn = 3;\n const int itemQueryResouceColumn = 4;\n\n if ( !itemQuery.exec() )\n return failureResponse( \"Unable to list items\" );\n itemQuery.query().next();\n\n \/\/ build flag query if needed\n QueryBuilder flagQuery;\n if ( attrList.contains( \"FLAGS\" ) || allParts ) {\n flagQuery.addTable( PimItem::tableName() );\n flagQuery.addTable( PimItemFlagRelation::tableName() );\n flagQuery.addTable( Flag::tableName() );\n flagQuery.addColumn( PimItem::idFullColumnName() );\n flagQuery.addColumn( Flag::nameFullColumnName() );\n flagQuery.addColumnCondition( PimItem::idFullColumnName(), Query::Equals, PimItemFlagRelation::leftFullColumnName() );\n flagQuery.addColumnCondition( Flag::idFullColumnName(), Query::Equals, PimItemFlagRelation::rightFullColumnName() );\n imapSetToQuery( set, isUidFetch, flagQuery );\n flagQuery.addSortColumn( PimItem::idFullColumnName(), Query::Ascending );\n\n if ( !flagQuery.exec() )\n return failureResponse( \"Unable to retrieve item flags\" );\n flagQuery.query().next();\n }\n const int flagQueryIdColumn = 0;\n const int flagQueryNameColumn = 1;\n\n \/\/ build part query if needed\n QueryBuilder partQuery;\n QStringList partList;\n foreach( const QByteArray b, attrList ) {\n \/\/ filter out non-part attributes\n if ( b == \"REV\" || b == \"FLAGS\" || b == \"UID\" || b == \"REMOTEID\" || b.startsWith( \"akonadi-\" ) )\n continue;\n if ( b == \"RFC822.SIZE\" )\n partList << QString::fromLatin1( \"RFC822\" );\n else\n partList << QString::fromLatin1( b );\n }\n if ( !partList.isEmpty() || allParts || attrList.contains( \"RFC822.SIZE\" ) ) {\n partQuery.addTable( PimItem::tableName() );\n partQuery.addTable( Part::tableName() );\n partQuery.addColumn( PimItem::idFullColumnName() );\n partQuery.addColumn( Part::nameFullColumnName() );\n partQuery.addColumn( Part::dataFullColumnName() );\n partQuery.addColumnCondition( PimItem::idFullColumnName(), Query::Equals, Part::pimItemIdFullColumnName() );\n if ( !allParts )\n partQuery.addValueCondition( Part::nameFullColumnName(), Query::In, partList );\n imapSetToQuery( set, isUidFetch, partQuery );\n partQuery.addSortColumn( PimItem::idFullColumnName(), Query::Ascending );\n\n if ( !partQuery.exec() )\n return failureResponse( \"Unable to retrieve item parts\" );\n partQuery.query().next();\n }\n const int partQueryIdColumn = 0;\n const int partQueryNameColumn = 1;\n const int partQueryDataColumn = 2;\n\n \/\/ fetch not yet cached item parts\n \/\/ TODO: I'm sure this can be done with a single query instead of manually\n DataStore *store = connection()->storageBackend();\n if ( !partList.isEmpty() || allParts ) {\n while ( itemQuery.query().isValid() ) {\n const int pimItemId = itemQuery.query().value( itemQueryIdColumn ).toInt();\n QStringList missingParts = partList;\n while ( partQuery.query().isValid() ) {\n const int id = partQuery.query().value( partQueryIdColumn ).toInt();\n if ( id < pimItemId ) {\n partQuery.query().next();\n continue;\n } else if ( id > pimItemId ) {\n break;\n }\n const QString partName = partQuery.query().value( partQueryNameColumn ).toString();\n if ( partQuery.query().value( partQueryDataColumn ).toByteArray().isNull() ) {\n if ( allParts )\n missingParts << partName;\n } else {\n missingParts.removeAll( partName );\n }\n partQuery.query().next();\n }\n if ( !missingParts.isEmpty() ) {\n store->retrieveDataFromResource( pimItemId, itemQuery.query().value( itemQueryRidColumn ).toString().toUtf8(),\n itemQuery.query().value( itemQueryResouceColumn ).toString(), missingParts );\n }\n itemQuery.query().next();\n }\n\n \/\/ re-exec part query, rewind item query\n itemQuery.query().first();\n if ( !partQuery.query().exec() )\n return failureResponse( \"Unable to retrieve item parts\" );\n partQuery.query().next();\n }\n\n \/\/ build responses\n Response response;\n response.setUntagged();\n while ( itemQuery.query().isValid() ) {\n const int pimItemId = itemQuery.query().value( itemQueryIdColumn ).toInt();\n const int pimItemRev = itemQuery.query().value( itemQueryRevColumn ).toInt();\n QList attributes;\n attributes.append( \"UID \" + QByteArray::number( pimItemId ) );\n attributes.append( \"REV \" + QByteArray::number( pimItemRev ) );\n attributes.append( \"REMOTEID \" + ImapParser::quote( itemQuery.query().value( itemQueryRidColumn ).toString().toUtf8() ) );\n attributes.append( \"MIMETYPE \" + ImapParser::quote( itemQuery.query().value( itemQueryMimeTypeColumn ).toString().toUtf8() ) );\n\n if ( attrList.contains( \"FLAGS\" ) ) {\n QList flags;\n while ( flagQuery.query().isValid() ) {\n const int id = flagQuery.query().value( flagQueryIdColumn ).toInt();\n if ( id < pimItemId ) {\n flagQuery.query().next();\n continue;\n } else if ( id > pimItemId ) {\n break;\n }\n flags << flagQuery.query().value( flagQueryNameColumn ).toString().toUtf8();\n flagQuery.query().next();\n }\n attributes.append( \"FLAGS (\" + ImapParser::join( flags, \" \" ) + ')' );\n }\n\n while ( partQuery.query().isValid() ) {\n const int id = partQuery.query().value( partQueryIdColumn ).toInt();\n if ( id < pimItemId ) {\n partQuery.query().next();\n continue;\n } else if ( id > pimItemId ) {\n break;\n }\n QByteArray partName = partQuery.query().value( partQueryNameColumn ).toString().toUtf8();\n QByteArray part = partQuery.query().value( partQueryNameColumn ).toString().toUtf8();\n QByteArray data = partQuery.query().value( partQueryDataColumn ).toByteArray();\n if ( data.isNull() ) {\n part += \" NIL\";\n } else if ( data.isEmpty() ) {\n part += \" \\\"\\\"\";\n } else {\n part += \" {\" + QByteArray::number( data.length() ) + \"}\\n\";\n part += data;\n }\n \/\/ return only requested parts (when RFC822.SIZE is requested, RFC822 is retrieved, but should not be returned)\n if ( attrList.contains( partName ) || allParts )\n attributes << part;\n\n if ( partName == \"RFC822\" && attrList.contains( \"RFC822.SIZE\" ) )\n attributes.append( \"RFC822.SIZE \" + QByteArray::number( data.length() ) );\n\n partQuery.query().next();\n }\n\n \/\/ IMAP protocol violation: should actually be the sequence number\n QByteArray attr = QByteArray::number( pimItemId ) + \" FETCH (\";\n attr += ImapParser::join( attributes, \" \" ) + ')';\n response.setUntagged();\n response.setString( attr );\n emit responseAvailable( response );\n\n itemQuery.query().next();\n }\n\n \/\/ update atime\n updateItemAccessTime( set, isUidFetch );\n\n response.setTag( tag() );\n response.setSuccess();\n if ( isUidFetch )\n response.setString( \"UID FETCH completed\" );\n else\n response.setString( \"FETCH completed\" );\n emit responseAvailable( response );\n deleteLater();\n return true;\n}\n\nvoid Fetch::updateItemAccessTime(const ImapSet & set, bool isUidFetch)\n{\n QueryBuilder qb( QueryBuilder::Update );\n qb.addTable( PimItem::tableName() );\n qb.updateColumnValue( PimItem::atimeColumn(), QDateTime::currentDateTime() );\n imapSetToQuery( set, isUidFetch, qb );\n if ( !qb.exec() )\n qWarning() << \"Unable to update item access time\";\n}\n\nvoid Fetch::triggerOnDemandFetch(bool isUidFetch)\n{\n if ( isUidFetch || connection()->selectedCollection() <= 0 )\n return;\n Location loc = connection()->selectedLocation();\n \/\/ HACK: don't trigger on-demand syncing if the resource is the one triggering it\n if ( connection()->sessionId() == loc.resource().name().toLatin1() )\n return;\n DataStore *store = connection()->storageBackend();\n store->activeCachePolicy( loc );\n if ( !loc.cachePolicySyncOnDemand() )\n return;\n store->triggerCollectionSync( loc );\n}\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2013-2019 The Syscoin Core developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \n#include \n#include \n#include \n#include \n\nstd::string stringFromSyscoinTx(const int &nVersion) {\n switch (nVersion) {\n case SYSCOIN_TX_VERSION_ASSET_ACTIVATE:\n\t\treturn \"assetactivate\";\n case SYSCOIN_TX_VERSION_ASSET_UPDATE:\n\t\treturn \"assetupdate\"; \n\tcase SYSCOIN_TX_VERSION_ASSET_SEND:\n\t\treturn \"assetsend\";\n\tcase SYSCOIN_TX_VERSION_ALLOCATION_SEND:\n\t\treturn \"assetallocationsend\";\n\tcase SYSCOIN_TX_VERSION_ALLOCATION_BURN_TO_ETHEREUM:\n\t\treturn \"assetallocationburntoethereum\"; \n\tcase SYSCOIN_TX_VERSION_ALLOCATION_BURN_TO_SYSCOIN:\n\t\treturn \"assetallocationburntosyscoin\";\n\tcase SYSCOIN_TX_VERSION_SYSCOIN_BURN_TO_ALLOCATION:\n\t\treturn \"syscoinburntoassetallocation\"; \n case SYSCOIN_TX_VERSION_ALLOCATION_MINT:\n return \"assetallocationmint\"; \n default:\n return \"\";\n }\n}\n\nstd::vector vchFromString(const std::string &str) {\n\tunsigned char *strbeg = (unsigned char*)str.c_str();\n\treturn std::vector(strbeg, strbeg + str.size());\n}\nstd::string stringFromVch(const std::vector &vch) {\n\tstd::string res;\n\tstd::vector::const_iterator vi = vch.begin();\n\twhile (vi != vch.end()) {\n\t\tres += (char)(*vi);\n\t\tvi++;\n\t}\n\treturn res;\n}\n\n\n\n\nbool CAsset::UnserializeFromData(const std::vector &vchData) {\n try {\n\t\tCDataStream dsAsset(vchData, SER_NETWORK, PROTOCOL_VERSION);\n\t\tUnserialize(dsAsset);\n } catch (std::exception &e) {\n\t\tSetNull();\n return false;\n }\n\treturn true;\n}\n\nbool CAsset::UnserializeFromTx(const CTransaction &tx) {\n\tstd::vector vchData;\n\tint nOut;\n\tif (!GetSyscoinData(tx, vchData, nOut))\n\t{\n\t\tSetNull();\n\t\treturn false;\n\t}\n\tif(!UnserializeFromData(vchData))\n\t{\t\n\t\tSetNull();\n\t\treturn false;\n\t}\n return true;\n}\n\n\nint32_t GenerateSyscoinGuid(const COutPoint& outPoint) {\n const arith_uint256 &txidArith = UintToArith256(outPoint.hash);\n int32_t low32 = (int32_t)txidArith.GetLow64();\n low32 += outPoint.n;\n if(low32 < 0){\n low32 *= -1;\n }\n if(low32 <= SYSCOIN_TX_VERSION_ALLOCATION_SEND*10){\n low32 = SYSCOIN_TX_VERSION_ALLOCATION_SEND*10;\n }\n return low32;\n}\n\nvoid CAsset::SerializeData( std::vector &vchData) {\n CDataStream dsAsset(SER_NETWORK, PROTOCOL_VERSION);\n Serialize(dsAsset);\n\tvchData = std::vector(dsAsset.begin(), dsAsset.end());\n}\n\nbool GetAsset(const int32_t &nAsset,\n CAsset& txPos) {\n if (passetdb == nullptr || !passetdb->ReadAsset(nAsset, txPos))\n return false;\n return true;\n}\n\nbool ReserializeAssetCommitment(CMutableTransaction& mtx) {\n \/\/ load tx.voutAssets from tx.vout.assetInfo info\n \/\/ when change is added this function should be called and preceding this the vout.assetInfo\n \/\/ should all be in sync with the asset commitment in OP_RETURN. This will resync that commitment\n \/\/ because when change is added the vout.assetInfo is filled and we should capture that in LoadAssetsFromVout as it\n \/\/ re-orders tx->voutAssets if change address was somewhere before the last asset output\n mtx.LoadAssetsFromVout();\n \/\/ store tx.voutAssets into OP_RETURN data overwriting previous commitment\n const CTransactionRef& tx = MakeTransactionRef(mtx);\n std::vector data;\n if(IsSyscoinMintTx(tx->nVersion)) {\n CMintSyscoin mintSyscoin(*tx);\n mintSyscoin.assetAllocation.voutAssets = tx->voutAssets;\n mintSyscoin.SerializeData(data);\n } else if(tx->nVersion == SYSCOIN_TX_VERSION_ALLOCATION_BURN_TO_SYSCOIN) {\n CBurnSyscoin burnSyscoin(*tx);\n burnSyscoin.assetAllocation.voutAssets = tx->voutAssets;\n burnSyscoin.SerializeData(data);\n } else if(IsAssetTx(tx->nVersion)) {\n CAsset asset(*tx);\n asset.assetAllocation.voutAssets = tx->voutAssets;\n asset.SerializeData(data); \n } else if(IsAssetAllocationTx(tx->nVersion)) {\n CAssetAllocation allocation(*tx);\n allocation.voutAssets = tx->voutAssets;\n allocation.SerializeData(data); \n }\n \/\/ find previous commitment (OP_RETURN) and replace script\n CScript scriptData;\n scriptData << OP_RETURN << data;\n bool bFoundData = false;\n for(auto& vout: mtx.vout) {\n if(vout.scriptPubKey.IsUnspendable()) {\n vout.scriptPubKey = scriptData;\n bFoundData = true;\n break;\n }\n }\n if(!bFoundData) {\n return false;\n }\n return true;\n}\ntypo\/\/ Copyright (c) 2013-2019 The Syscoin Core developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \n#include \n#include \n#include \n#include \n\nstd::string stringFromSyscoinTx(const int &nVersion) {\n switch (nVersion) {\n case SYSCOIN_TX_VERSION_ASSET_ACTIVATE:\n\t\treturn \"assetactivate\";\n case SYSCOIN_TX_VERSION_ASSET_UPDATE:\n\t\treturn \"assetupdate\"; \n\tcase SYSCOIN_TX_VERSION_ASSET_SEND:\n\t\treturn \"assetsend\";\n\tcase SYSCOIN_TX_VERSION_ALLOCATION_SEND:\n\t\treturn \"assetallocationsend\";\n\tcase SYSCOIN_TX_VERSION_ALLOCATION_BURN_TO_ETHEREUM:\n\t\treturn \"assetallocationburntoethereum\"; \n\tcase SYSCOIN_TX_VERSION_ALLOCATION_BURN_TO_SYSCOIN:\n\t\treturn \"assetallocationburntosyscoin\";\n\tcase SYSCOIN_TX_VERSION_SYSCOIN_BURN_TO_ALLOCATION:\n\t\treturn \"syscoinburntoassetallocation\"; \n case SYSCOIN_TX_VERSION_ALLOCATION_MINT:\n return \"assetallocationmint\"; \n default:\n return \"\";\n }\n}\n\nstd::vector vchFromString(const std::string &str) {\n\tunsigned char *strbeg = (unsigned char*)str.c_str();\n\treturn std::vector(strbeg, strbeg + str.size());\n}\nstd::string stringFromVch(const std::vector &vch) {\n\tstd::string res;\n\tstd::vector::const_iterator vi = vch.begin();\n\twhile (vi != vch.end()) {\n\t\tres += (char)(*vi);\n\t\tvi++;\n\t}\n\treturn res;\n}\n\n\n\n\nbool CAsset::UnserializeFromData(const std::vector &vchData) {\n try {\n\t\tCDataStream dsAsset(vchData, SER_NETWORK, PROTOCOL_VERSION);\n\t\tUnserialize(dsAsset);\n } catch (std::exception &e) {\n\t\tSetNull();\n return false;\n }\n\treturn true;\n}\n\nbool CAsset::UnserializeFromTx(const CTransaction &tx) {\n\tstd::vector vchData;\n\tint nOut;\n\tif (!GetSyscoinData(tx, vchData, nOut))\n\t{\n\t\tSetNull();\n\t\treturn false;\n\t}\n\tif(!UnserializeFromData(vchData))\n\t{\t\n\t\tSetNull();\n\t\treturn false;\n\t}\n return true;\n}\n\n\nint32_t GenerateSyscoinGuid(const COutPoint& outPoint) {\n const arith_uint256 &txidArith = UintToArith256(outPoint.hash);\n int32_t low32 = (int32_t)txidArith.GetLow64();\n low32 += outPoint.n;\n if(low32 < 0){\n low32 *= -1;\n }\n if(low32 <= SYSCOIN_TX_VERSION_ALLOCATION_SEND*10){\n low32 = SYSCOIN_TX_VERSION_ALLOCATION_SEND*10;\n }\n return low32;\n}\n\nvoid CAsset::SerializeData( std::vector &vchData) {\n CDataStream dsAsset(SER_NETWORK, PROTOCOL_VERSION);\n Serialize(dsAsset);\n\tvchData = std::vector(dsAsset.begin(), dsAsset.end());\n}\n\nbool GetAsset(const int32_t &nAsset,\n CAsset& txPos) {\n if (passetdb == nullptr || !passetdb->ReadAsset(nAsset, txPos))\n return false;\n return true;\n}\n\nbool ReserializeAssetCommitment(CMutableTransaction& mtx) {\n \/\/ load tx.voutAssets from tx.vout.assetInfo info\n \/\/ when change is added this function should be called and preceding this the vout.assetInfo\n \/\/ should all be in sync with the asset commitment in OP_RETURN. This will resync that commitment\n \/\/ because when change is added the vout.assetInfo is filled and we should capture that in LoadAssetsFromVout as it\n \/\/ re-orders tx->voutAssets if change address was somewhere before the last asset output\n mtx.LoadAssetsFromVout();\n \/\/ store tx.voutAssets into OP_RETURN data overwriting previous commitment\n const CTransactionRef& tx = MakeTransactionRef(mtx);\n std::vector data;\n if(IsSyscoinMintTx(tx->nVersion)) {\n CMintSyscoin mintSyscoin(*tx);\n mintSyscoin.assetAllocation.voutAssets = tx->voutAssets;\n mintSyscoin.SerializeData(data);\n } else if(tx->nVersion == SYSCOIN_TX_VERSION_ALLOCATION_BURN_TO_SYSCOIN) {\n CBurnSyscoin burnSyscoin(*tx);\n burnSyscoin.assetAllocation.voutAssets = tx->voutAssets;\n burnSyscoin.SerializeData(data);\n } else if(IsAssetTx(tx->nVersion)) {\n CAsset asset(*tx);\n asset.assetAllocation.voutAssets = tx->voutAssets;\n asset.SerializeData(data); \n } else if(IsAssetAllocationTx(tx->nVersion)) {\n CAssetAllocation allocation(*tx);\n allocation.voutAssets = tx->voutAssets;\n allocation.SerializeData(data); \n }\n \/\/ find previous commitment (OP_RETURN) and replace script\n CScript scriptData;\n scriptData << OP_RETURN << data;\n bool bFoundData = false;\n for(auto& vout: mtx.vout) {\n if(vout.scriptPubKey.IsUnspendable()) {\n vout.scriptPubKey = scriptData;\n bFoundData = true;\n break;\n }\n }\n if(!bFoundData) {\n return false;\n }\n return true;\n}\n<|endoftext|>"} {"text":"\/*\n * Copyright (C) 2018 The Android Open Source Project\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"src\/trace_processor\/counters_table.h\"\n\n#include \"src\/trace_processor\/storage_cursor.h\"\n#include \"src\/trace_processor\/table_utils.h\"\n\nnamespace perfetto {\nnamespace trace_processor {\n\nCountersTable::CountersTable(sqlite3*, const TraceStorage* storage)\n : storage_(storage) {\n ref_types_.resize(RefType::kMax);\n ref_types_[RefType::kCpuId] = \"cpu\";\n ref_types_[RefType::kUtid] = \"utid\";\n ref_types_[RefType::kNoRef] = \"\";\n ref_types_[RefType::kIrq] = \"irq\";\n ref_types_[RefType::kSoftIrq] = \"softirq\";\n}\n\nvoid CountersTable::RegisterTable(sqlite3* db, const TraceStorage* storage) {\n Table::Register(db, storage, \"counters\");\n}\n\nTable::Schema CountersTable::CreateSchema(int, const char* const*) {\n const auto& counters = storage_->counters();\n std::unique_ptr cols[] = {\n StorageSchema::NumericColumnPtr(\"ts\", &counters.timestamps(),\n false \/* hidden *\/, true \/* ordered *\/),\n StorageSchema::StringColumnPtr(\"name\", &counters.name_ids(),\n &storage_->string_pool()),\n StorageSchema::NumericColumnPtr(\"value\", &counters.values()),\n StorageSchema::NumericColumnPtr(\"dur\", &counters.durations()),\n StorageSchema::NumericColumnPtr(\"ref\", &counters.refs()),\n StorageSchema::StringColumnPtr(\"ref_type\", &counters.types(),\n &ref_types_)};\n schema_ = StorageSchema({\n std::make_move_iterator(std::begin(cols)),\n std::make_move_iterator(std::end(cols)),\n });\n return schema_.ToTableSchema({\"name\", \"ts\", \"ref\"});\n}\n\nstd::unique_ptr CountersTable::CreateCursor(\n const QueryConstraints& qc,\n sqlite3_value** argv) {\n uint32_t count = static_cast(storage_->counters().counter_count());\n auto it = table_utils::CreateBestRowIteratorForGenericSchema(schema_, count,\n qc, argv);\n return std::unique_ptr(\n new StorageCursor(std::move(it), schema_.ToColumnReporters()));\n}\n\nint CountersTable::BestIndex(const QueryConstraints&, BestIndexInfo* info) {\n info->estimated_cost =\n static_cast(storage_->counters().counter_count());\n\n \/\/ We should be able to handle any constraint and any order by clause given\n \/\/ to us.\n info->order_by_consumed = true;\n std::fill(info->omit.begin(), info->omit.end(), true);\n\n return SQLITE_OK;\n}\n\n} \/\/ namespace trace_processor\n} \/\/ namespace perfetto\ntrace_processor: Allow sqlite to handle string filtering\/*\n * Copyright (C) 2018 The Android Open Source Project\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"src\/trace_processor\/counters_table.h\"\n\n#include \"src\/trace_processor\/storage_cursor.h\"\n#include \"src\/trace_processor\/table_utils.h\"\n\nnamespace perfetto {\nnamespace trace_processor {\n\nCountersTable::CountersTable(sqlite3*, const TraceStorage* storage)\n : storage_(storage) {\n ref_types_.resize(RefType::kMax);\n ref_types_[RefType::kCpuId] = \"cpu\";\n ref_types_[RefType::kUtid] = \"utid\";\n ref_types_[RefType::kNoRef] = \"\";\n ref_types_[RefType::kIrq] = \"irq\";\n ref_types_[RefType::kSoftIrq] = \"softirq\";\n}\n\nvoid CountersTable::RegisterTable(sqlite3* db, const TraceStorage* storage) {\n Table::Register(db, storage, \"counters\");\n}\n\nTable::Schema CountersTable::CreateSchema(int, const char* const*) {\n const auto& counters = storage_->counters();\n std::unique_ptr cols[] = {\n StorageSchema::NumericColumnPtr(\"ts\", &counters.timestamps(),\n false \/* hidden *\/, true \/* ordered *\/),\n StorageSchema::StringColumnPtr(\"name\", &counters.name_ids(),\n &storage_->string_pool()),\n StorageSchema::NumericColumnPtr(\"value\", &counters.values()),\n StorageSchema::NumericColumnPtr(\"dur\", &counters.durations()),\n StorageSchema::NumericColumnPtr(\"ref\", &counters.refs()),\n StorageSchema::StringColumnPtr(\"ref_type\", &counters.types(),\n &ref_types_)};\n schema_ = StorageSchema({\n std::make_move_iterator(std::begin(cols)),\n std::make_move_iterator(std::end(cols)),\n });\n return schema_.ToTableSchema({\"name\", \"ts\", \"ref\"});\n}\n\nstd::unique_ptr CountersTable::CreateCursor(\n const QueryConstraints& qc,\n sqlite3_value** argv) {\n uint32_t count = static_cast(storage_->counters().counter_count());\n auto it = table_utils::CreateBestRowIteratorForGenericSchema(schema_, count,\n qc, argv);\n return std::unique_ptr(\n new StorageCursor(std::move(it), schema_.ToColumnReporters()));\n}\n\nint CountersTable::BestIndex(const QueryConstraints& qc, BestIndexInfo* info) {\n info->estimated_cost =\n static_cast(storage_->counters().counter_count());\n\n \/\/ Only the string columns are handled by SQLite\n info->order_by_consumed = true;\n size_t name_index = schema_.ColumnIndexFromName(\"name\");\n size_t ref_type_index = schema_.ColumnIndexFromName(\"ref_type\");\n for (size_t i = 0; i < qc.constraints().size(); i++) {\n info->omit[i] =\n qc.constraints()[i].iColumn != static_cast(name_index) &&\n qc.constraints()[i].iColumn != static_cast(ref_type_index);\n }\n\n return SQLITE_OK;\n}\n\n} \/\/ namespace trace_processor\n} \/\/ namespace perfetto\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2011 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/ui\/views\/extensions\/extension_dialog.h\"\n\n#include \"chrome\/browser\/extensions\/extension_host.h\"\n#include \"chrome\/browser\/extensions\/extension_process_manager.h\"\n#include \"chrome\/browser\/profiles\/profile.h\"\n#include \"chrome\/browser\/ui\/browser.h\"\n#include \"chrome\/browser\/ui\/browser_window.h\"\n#include \"chrome\/browser\/ui\/views\/extensions\/extension_dialog_observer.h\"\n#include \"chrome\/browser\/ui\/views\/window.h\" \/\/ CreateViewsWindow\n#include \"chrome\/common\/chrome_notification_types.h\"\n#include \"content\/browser\/renderer_host\/render_view_host.h\"\n#include \"content\/browser\/renderer_host\/render_widget_host_view.h\"\n#include \"content\/common\/notification_details.h\"\n#include \"content\/common\/notification_source.h\"\n#include \"googleurl\/src\/gurl.h\"\n#include \"views\/widget\/widget.h\"\n\n#if defined(OS_CHROMEOS)\n#include \"chrome\/browser\/chromeos\/frame\/bubble_window.h\"\n#endif\n\nnamespace {\n\nviews::Widget* CreateWindow(gfx::NativeWindow parent,\n views::WidgetDelegate* delegate) {\n#if defined(OS_CHROMEOS)\n \/\/ On Chrome OS we need to override the style to suppress padding around\n \/\/ the borders.\n return chromeos::BubbleWindow::Create(parent,\n chromeos::STYLE_FLUSH, delegate);\n#else\n return browser::CreateViewsWindow(parent, delegate);\n#endif\n}\n\n} \/\/ namespace\n\nExtensionDialog::ExtensionDialog(ExtensionHost* host,\n ExtensionDialogObserver* observer)\n : window_(NULL),\n extension_host_(host),\n observer_(observer) {\n AddRef(); \/\/ Balanced in DeleteDelegate();\n\n \/\/ Listen for the containing view calling window.close();\n registrar_.Add(this, chrome::NOTIFICATION_EXTENSION_HOST_VIEW_SHOULD_CLOSE,\n Source(host->profile()));\n}\n\nExtensionDialog::~ExtensionDialog() {\n}\n\n\/\/ static\nExtensionDialog* ExtensionDialog::Show(\n const GURL& url,\n Browser* browser,\n TabContents* tab_contents,\n int width,\n int height,\n ExtensionDialogObserver* observer) {\n CHECK(browser);\n ExtensionHost* host = CreateExtensionHost(url, browser);\n if (!host)\n return NULL;\n host->set_associated_tab_contents(tab_contents);\n\n ExtensionDialog* dialog = new ExtensionDialog(host, observer);\n dialog->InitWindow(browser, width, height);\n \/\/ Ensure the DOM JavaScript can respond immediately to keyboard shortcuts.\n host->render_view_host()->view()->Focus();\n return dialog;\n}\n\n\/\/ static\nExtensionHost* ExtensionDialog::CreateExtensionHost(const GURL& url,\n Browser* browser) {\n ExtensionProcessManager* manager =\n browser->profile()->GetExtensionProcessManager();\n DCHECK(manager);\n if (!manager)\n return NULL;\n return manager->CreateDialogHost(url, browser);\n}\n\nvoid ExtensionDialog::InitWindow(Browser* browser, int width, int height) {\n gfx::NativeWindow parent = browser->window()->GetNativeHandle();\n window_ = CreateWindow(parent, this \/* views::WidgetDelegate *\/);\n\n \/\/ Center the window over the browser.\n gfx::Point center = browser->window()->GetBounds().CenterPoint();\n int x = center.x() - width \/ 2;\n int y = center.y() - height \/ 2;\n window_->SetBounds(gfx::Rect(x, y, width, height));\n\n window_->Show();\n window_->Activate();\n}\n\nvoid ExtensionDialog::ObserverDestroyed() {\n observer_ = NULL;\n}\n\nvoid ExtensionDialog::Close() {\n if (!window_)\n return;\n\n if (observer_)\n observer_->ExtensionDialogIsClosing(this);\n\n window_->Close();\n window_ = NULL;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ views::WidgetDelegate overrides.\n\nbool ExtensionDialog::CanResize() const {\n return false;\n}\n\nbool ExtensionDialog::IsModal() const {\n return true;\n}\n\nbool ExtensionDialog::ShouldShowWindowTitle() const {\n return false;\n}\n\nvoid ExtensionDialog::DeleteDelegate() {\n \/\/ The window has finished closing. Allow ourself to be deleted.\n Release();\n}\n\nviews::Widget* ExtensionDialog::GetWidget() {\n return extension_host_->view()->GetWidget();\n}\n\nconst views::Widget* ExtensionDialog::GetWidget() const {\n return extension_host_->view()->GetWidget();\n}\n\nviews::View* ExtensionDialog::GetContentsView() {\n return extension_host_->view();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ NotificationObserver overrides.\n\nvoid ExtensionDialog::Observe(int type,\n const NotificationSource& source,\n const NotificationDetails& details) {\n switch (type) {\n case chrome::NOTIFICATION_EXTENSION_HOST_VIEW_SHOULD_CLOSE:\n \/\/ If we aren't the host of the popup, then disregard the notification.\n if (Details(host()) != details)\n return;\n Close();\n break;\n default:\n NOTREACHED() << L\"Received unexpected notification\";\n break;\n }\n}\nAura: Fix crash when opening CrOS file picker\/\/ Copyright (c) 2011 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/ui\/views\/extensions\/extension_dialog.h\"\n\n#include \"chrome\/browser\/extensions\/extension_host.h\"\n#include \"chrome\/browser\/extensions\/extension_process_manager.h\"\n#include \"chrome\/browser\/profiles\/profile.h\"\n#include \"chrome\/browser\/ui\/browser.h\"\n#include \"chrome\/browser\/ui\/browser_window.h\"\n#include \"chrome\/browser\/ui\/views\/extensions\/extension_dialog_observer.h\"\n#include \"chrome\/browser\/ui\/views\/window.h\" \/\/ CreateViewsWindow\n#include \"chrome\/common\/chrome_notification_types.h\"\n#include \"content\/browser\/renderer_host\/render_view_host.h\"\n#include \"content\/browser\/renderer_host\/render_widget_host_view.h\"\n#include \"content\/common\/notification_details.h\"\n#include \"content\/common\/notification_source.h\"\n#include \"googleurl\/src\/gurl.h\"\n#include \"views\/widget\/widget.h\"\n\n#if defined(OS_CHROMEOS)\n#include \"chrome\/browser\/chromeos\/frame\/bubble_window.h\"\n#endif\n\nnamespace {\n\nviews::Widget* CreateWindow(gfx::NativeWindow parent,\n views::WidgetDelegate* delegate) {\n#if defined(OS_CHROMEOS) && defined(TOOLKIT_USES_GTK)\n \/\/ TODO(msw): revert to BubbleWindow for all ChromeOS cases when CL\n \/\/ for crbug.com\/98322 is landed.\n \/\/ On Chrome OS we need to override the style to suppress padding around\n \/\/ the borders.\n return chromeos::BubbleWindow::Create(parent,\n chromeos::STYLE_FLUSH, delegate);\n#else\n return browser::CreateViewsWindow(parent, delegate);\n#endif\n}\n\n} \/\/ namespace\n\nExtensionDialog::ExtensionDialog(ExtensionHost* host,\n ExtensionDialogObserver* observer)\n : window_(NULL),\n extension_host_(host),\n observer_(observer) {\n AddRef(); \/\/ Balanced in DeleteDelegate();\n\n \/\/ Listen for the containing view calling window.close();\n registrar_.Add(this, chrome::NOTIFICATION_EXTENSION_HOST_VIEW_SHOULD_CLOSE,\n Source(host->profile()));\n}\n\nExtensionDialog::~ExtensionDialog() {\n}\n\n\/\/ static\nExtensionDialog* ExtensionDialog::Show(\n const GURL& url,\n Browser* browser,\n TabContents* tab_contents,\n int width,\n int height,\n ExtensionDialogObserver* observer) {\n CHECK(browser);\n ExtensionHost* host = CreateExtensionHost(url, browser);\n if (!host)\n return NULL;\n host->set_associated_tab_contents(tab_contents);\n\n ExtensionDialog* dialog = new ExtensionDialog(host, observer);\n dialog->InitWindow(browser, width, height);\n \/\/ Ensure the DOM JavaScript can respond immediately to keyboard shortcuts.\n host->render_view_host()->view()->Focus();\n return dialog;\n}\n\n\/\/ static\nExtensionHost* ExtensionDialog::CreateExtensionHost(const GURL& url,\n Browser* browser) {\n ExtensionProcessManager* manager =\n browser->profile()->GetExtensionProcessManager();\n DCHECK(manager);\n if (!manager)\n return NULL;\n return manager->CreateDialogHost(url, browser);\n}\n\nvoid ExtensionDialog::InitWindow(Browser* browser, int width, int height) {\n gfx::NativeWindow parent = browser->window()->GetNativeHandle();\n window_ = CreateWindow(parent, this \/* views::WidgetDelegate *\/);\n\n \/\/ Center the window over the browser.\n gfx::Point center = browser->window()->GetBounds().CenterPoint();\n int x = center.x() - width \/ 2;\n int y = center.y() - height \/ 2;\n window_->SetBounds(gfx::Rect(x, y, width, height));\n\n window_->Show();\n window_->Activate();\n}\n\nvoid ExtensionDialog::ObserverDestroyed() {\n observer_ = NULL;\n}\n\nvoid ExtensionDialog::Close() {\n if (!window_)\n return;\n\n if (observer_)\n observer_->ExtensionDialogIsClosing(this);\n\n window_->Close();\n window_ = NULL;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ views::WidgetDelegate overrides.\n\nbool ExtensionDialog::CanResize() const {\n return false;\n}\n\nbool ExtensionDialog::IsModal() const {\n return true;\n}\n\nbool ExtensionDialog::ShouldShowWindowTitle() const {\n return false;\n}\n\nvoid ExtensionDialog::DeleteDelegate() {\n \/\/ The window has finished closing. Allow ourself to be deleted.\n Release();\n}\n\nviews::Widget* ExtensionDialog::GetWidget() {\n return extension_host_->view()->GetWidget();\n}\n\nconst views::Widget* ExtensionDialog::GetWidget() const {\n return extension_host_->view()->GetWidget();\n}\n\nviews::View* ExtensionDialog::GetContentsView() {\n return extension_host_->view();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ NotificationObserver overrides.\n\nvoid ExtensionDialog::Observe(int type,\n const NotificationSource& source,\n const NotificationDetails& details) {\n switch (type) {\n case chrome::NOTIFICATION_EXTENSION_HOST_VIEW_SHOULD_CLOSE:\n \/\/ If we aren't the host of the popup, then disregard the notification.\n if (Details(host()) != details)\n return;\n Close();\n break;\n default:\n NOTREACHED() << L\"Received unexpected notification\";\n break;\n }\n}\n<|endoftext|>"} {"text":"\/*\n WPN-XM Server Control Panel\n\n WPN-XM SCP is a tool to manage Nginx, PHP and MariaDb daemons under windows.\n It's a fork of Easy WEMP originally written by Yann Le Moigne and (c) 2010.\n WPN-XM SCP is written by Jens-Andre Koch and (c) 2011 - onwards.\n\n This file is part of WPN-XM Serverpack for Windows.\n\n WPN-XM SCP is free software: you can redistribute it and\/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation, either version 3 of the License, or\n (at your option) any later version.\n\n WPN-XM SCP is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with WPN-XM SCP. If not, see .\n*\/\n\n\/\/ QT includes\n#include \n#include \n#include \n#include \n#include \n#include \n\n\/\/ WPN-XM SCP includes\n#include \"main.h\"\n#include \"mainwindow.h\"\n\n\/\/ main method\nint main(int argc, char * argv[])\n{\n \/\/ Single Instance Check\n exitIfAlreadyRunning();\n\n Q_INIT_RESOURCE(Resources);\n\n QApplication application(argc, argv);\n\n \/\/ Application Meta Data\n application.setApplicationName(APP_NAME);\n application.setApplicationVersion(APP_VERSION);\n application.setOrganizationName(\"Jens-Andr Koch\");\n application.setOrganizationDomain(\"http:\/\/wpn-xm.org\/\");\n application.setWindowIcon(QIcon(\":\/wpnxm\"));\n\n \/\/ if setStyle() is not used, the submenus are not displayed properly. bug?\n application.setStyle(\"windowsxp\");\n\n \/\/ do not leave until Quit is clicked in the tray menu\n application.setQuitOnLastWindowClosed(false);\n\n MainWindow mainWindow;\n mainWindow.show();\n\n qDebug() << APP_NAME;\n qDebug() << APP_VERSION;\n\n \/\/ enter the Qt Event loop here\n return application.exec();\n}\n\n\/*\n * Single Instance Check\n * Although some people tend to solve this problem by using QtSingleApplication,\n * this approach uses a GUID stored into shared memory.\n *\/\nvoid exitIfAlreadyRunning()\n{\n \/\/ Set GUID for WPN-XM Server Control Panel to memory\n QSharedMemory shared(\"004d54f6-7d00-4478-b612-f242f081b023\");\n\n \/\/ already running\n if( !shared.create( 512, QSharedMemory::ReadWrite) )\n {\n QMessageBox msgBox;\n msgBox.setWindowTitle(APP_NAME);\n msgBox.setText( QObject::tr(\"Application is already running. Exiting.\") );\n msgBox.setIcon( QMessageBox::Critical );\n msgBox.exec();\n\n exit(0);\n }\n else\n {\n qDebug() << \"Application started and not already running.\";\n }\n}\nbetter already running message\/*\n WPN-XM Server Control Panel\n\n WPN-XM SCP is a tool to manage Nginx, PHP and MariaDb daemons under windows.\n It's a fork of Easy WEMP originally written by Yann Le Moigne and (c) 2010.\n WPN-XM SCP is written by Jens-Andre Koch and (c) 2011 - onwards.\n\n This file is part of WPN-XM Serverpack for Windows.\n\n WPN-XM SCP is free software: you can redistribute it and\/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation, either version 3 of the License, or\n (at your option) any later version.\n\n WPN-XM SCP is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with WPN-XM SCP. If not, see .\n*\/\n\n\/\/ QT includes\n#include \n#include \n#include \n#include \n#include \n#include \n\n\/\/ WPN-XM SCP includes\n#include \"main.h\"\n#include \"mainwindow.h\"\n\n\/\/ main method\nint main(int argc, char * argv[])\n{\n \/\/ Single Instance Check\n exitIfAlreadyRunning();\n\n Q_INIT_RESOURCE(Resources);\n\n QApplication application(argc, argv);\n\n \/\/ Application Meta Data\n application.setApplicationName(APP_NAME);\n application.setApplicationVersion(APP_VERSION);\n application.setOrganizationName(\"Jens-Andr Koch\");\n application.setOrganizationDomain(\"http:\/\/wpn-xm.org\/\");\n application.setWindowIcon(QIcon(\":\/wpnxm\"));\n\n \/\/ if setStyle() is not used, the submenus are not displayed properly. bug?\n application.setStyle(\"windowsxp\");\n\n \/\/ do not leave until Quit is clicked in the tray menu\n application.setQuitOnLastWindowClosed(false);\n\n MainWindow mainWindow;\n mainWindow.show();\n\n qDebug() << APP_NAME;\n qDebug() << APP_VERSION;\n\n \/\/ enter the Qt Event loop here\n return application.exec();\n}\n\n\/*\n * Single Instance Check\n * Although some people tend to solve this problem by using QtSingleApplication,\n * this approach uses a GUID stored into shared memory.\n *\/\nvoid exitIfAlreadyRunning()\n{\n \/\/ Set GUID for WPN-XM Server Control Panel to memory\n QSharedMemory shared(\"004d54f6-7d00-4478-b612-f242f081b023\");\n\n \/\/ already running\n if( !shared.create( 512, QSharedMemory::ReadWrite) )\n {\n QMessageBox msgBox;\n msgBox.setWindowTitle(APP_NAME);\n msgBox.setText( QObject::tr(\"WPN-XM is already running.\") );\n msgBox.setIcon( QMessageBox::Critical );\n msgBox.exec();\n\n exit(0);\n }\n else\n {\n qDebug() << \"Application started and not already running.\";\n }\n}\n<|endoftext|>"} {"text":"\/\/ -*- coding: us-ascii-unix -*-\n\/\/ Copyright 2014 Lukas Kemmer\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\"); you\n\/\/ may not use this file except in compliance with the License. You\n\/\/ may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n\/\/ implied. See the License for the specific language governing\n\/\/ permissions and limitations under the License.\n\n#ifndef FAINT_TEST_HH\n#define FAINT_TEST_HH\n#include \n#include \n#include \n#include \n#include \n#include \n\nextern std::stringstream TEST_OUT;\nextern bool TEST_FAILED;\nextern int NUM_KNOWN_ERRORS;\n\nclass AbortTestException{};\n\n\/\/ Add braces around the arguments, to get past preprocessor not\n\/\/ understanding initializer-lists.\n#define LIST(...){__VA_ARGS__}\n\n#define MESSAGE(MSG) TEST_OUT << \" Message(\" << __LINE__ << \") \" << MSG << std::endl;\n\n#define TIME_MESSAGE(MSG) TEST_OUT << \" \" << MSG << std::endl;\n\ntemplate\nstd::string str_not_equal_hex(T1 v1, T2 v2){\n std::stringstream ss;\n ss << std::hex;\n ss << static_cast(v1) << \" != \" << static_cast(v2);\n return ss.str();\n}\n\n#define EQUAL_HEX(A,B) if ((A) != (B)){ TEST_OUT << \" Error(\" << __LINE__ << \"): \" << #A << \" != \" << #B << \" (\" << str_not_equal_hex(A, B) << \")\" << std::endl; TEST_FAILED=true;}\n\n#define EQUAL(A,B) if (!((A) == (B))){ TEST_OUT << \" Error(\" << __LINE__ << \"): \" << #A << \" != \" << #B << \" (\" << A << \" != \" << B << \")\" << std::endl; TEST_FAILED=true;}\n\n#define EQUALF(A,B,FMT)if (!((A) == (B))){ TEST_OUT << \" Error(\" << __LINE__ << \"): \" << #A << \" != \" << #B << \" (\" << FMT(A) << \" != \" << FMT(B) << \")\" << std::endl; TEST_FAILED=true;}\n\n#define NOT_EQUAL(A,B) if ((A) == (B)){ TEST_OUT << \" Error(\" << __LINE__ << \"): \" << #A << \" == \" << #B << \" (\" << A << \" == \" << B << \")\" << std::endl; TEST_FAILED=true;}\n\n#define ASSERT_EQUAL(A,B) if ((A) != (B)){ TEST_OUT << \" Error(\" << __LINE__ << \"): \" << #A << \" != \" << #B << \" (\" << A << \" != \" << B << \")\" << std::endl; TEST_FAILED=true; throw AbortTestException();}\n\nclass Epsilon{\npublic:\n explicit constexpr Epsilon(double v)\n : value(v)\n {}\n\n operator double() const{\n return value;\n }\n\n double value;\n};\n\nnamespace test{\n\n\/\/ Helper to make the static_assert dependent on T.\ntemplate\nstruct TypeDependentFalse{\n static const bool value = false;\n};\n\n\ntemplate\ndouble to_double(const T&){\n static_assert(TypeDependentFalse::value,\n \"to_double not overloaded for type.\");\n return 0.0;\n}\n\ninline double to_double(double v){\n return v;\n}\n\n} \/\/ namespace\n\ntemplate\nbool test_near(const T& a, const T& b, const Epsilon& e){\n return std::fabs(test::to_double(a) - test::to_double(b)) < e;\n}\n\nconstexpr Epsilon operator \"\" _eps(long double v){\n return Epsilon(static_cast(v));\n}\n\n#define NEAR(A,B,EPS) if (!test_near(A, B, EPS)){ TEST_OUT << \" Error(\" << __LINE__ << \"): \" << #A << \" != \" << #B << \" (\" << A << \" != \" << B << \")\" << std::endl; TEST_FAILED=true;}\n\ninline bool test_write_error(const char* file, int line, const char* text){\n \/\/ Error-syntax recognized by emacs Compilation mode\n TEST_OUT << file << \"(\" << line << \"): error: \" << text << std::endl;\n\n TEST_FAILED = true;\n return false;\n}\n\n#define VERIFY(C) ((C) ? true : test_write_error(__FILE__, __LINE__, #C \" failed.\"))\n\n#define NOT(C) ((!C) ? true : test_write_error(__FILE__, __LINE__, \"NOT \" #C \" failed.\"))\n\n#define ASSERT(C) if ((C)){}else{ TEST_OUT << \" Error(\" << __LINE__ << \"): \" << #C << \" failed.\" << std::endl; TEST_FAILED=true; throw AbortTestException();}\n\n#define ABORT_IF(C) if (!(C)){}else{ TEST_OUT << \" Error(\" << __LINE__ << \"): \" << #C << \" failed.\" << std::endl; TEST_FAILED=true; throw AbortTestException();}\n\ninline void fail_test(){}\n\ninline void fail_test(const char* message){\n TEST_OUT << \" \" << message << std::endl;\n fail_test();\n}\n\ntemplate\nvoid fail_test(const char* message, const T&... args){\n TEST_OUT << message << \" \";\n fail_test(args...);\n}\n\n\/\/ TODO: Rename to e.g. ABORT_TEST\n#define FAIL(...) TEST_OUT << \" FAIL triggered on line \" << __LINE__ << std::endl; TEST_FAILED=true; fail_test(__VA_ARGS__); throw AbortTestException();\n\n#define SET_FAIL() TEST_OUT << \" SET_FAIL triggered on line \" << __LINE__ << std::endl; TEST_FAILED=true\n\n#define KNOWN_ERROR(C) if ((C)){TEST_OUT << \" Error(\" << __LINE__ << \"): KNOWN_ERROR \\\"\" << #C << \"\\\"..\\n\" << \" ..evaluated OK. Test not updated?\" << std::endl; TEST_FAILED=true;}else{ TEST_OUT << \" Known error(\" << __LINE__ << \"): \" << #C << std::endl; NUM_KNOWN_ERRORS += 1;}\n\n#define KNOWN_INEQUAL(A,B) if ((A) == (B)){ TEST_OUT << \" Error(\" << __LINE__ << \"): \" << #A << \" == \" << #B << \" (\" << A << \" != \" << B << \")\" << \" ..evaluated OK. Test not updated?\" << std::endl; TEST_FAILED=true;}else{ TEST_OUT << \" Known error(\" << __LINE__ << \"): \" << A << \"!=\" << B << std::endl; NUM_KNOWN_ERRORS += 1;}\n\nstruct FailIfCalled{\n FailIfCalled(int line, bool abort=false)\n : m_line(line),\n m_abort(abort)\n {}\n\n template\n void operator()(Args...) const{\n TEST_OUT << \" FailIfCalled was called on line \" << m_line << std::endl;\n TEST_FAILED = true;\n if (m_abort){\n throw AbortTestException();\n }\n }\n int m_line;\n bool m_abort;\n};\n\nclass Checkable{\npublic:\n virtual ~Checkable() = default;\n virtual bool Check() const = 0;\n};\n\nextern std::vector POST_CHECKS;\n\n\nclass FailUnlessCalled : public Checkable{\npublic:\n FailUnlessCalled(int line)\n : m_called(false),\n m_line(line)\n {}\n\n template\n void operator()(Args...) const {\n m_called = true;\n }\n\n bool Check() const override{\n if (!m_called){\n TEST_OUT << \" FAIL_UNLESS_CALLED on line \" << m_line << \" was not called.\" << std::endl;\n TEST_FAILED = true;\n }\n return m_called;\n }\nprivate:\n mutable bool m_called;\n int m_line;\n};\n\n#define FWD(CALL);{try{bool alreadyFailed = TEST_FAILED;CALL;if (TEST_FAILED && !alreadyFailed){TEST_OUT << \" ... called via FWD on line \" << __LINE__ << std::endl;}}catch(const AbortTestException&){TEST_OUT << \" ... called via FWD on line \" << __LINE__ << std::endl; throw;}}\n\n\ntemplate\nclass FailUnlessCalledFwd : public Checkable{\npublic:\n FailUnlessCalledFwd(FUNC fwd, int line)\n : m_called(false),\n m_line(line),\n m_fwd(fwd)\n {}\n\n template\n void operator()(Args...args) const {\n m_called = true;\n bool alreadyFailed = TEST_FAILED;\n m_fwd(args...);\n if (TEST_FAILED && !alreadyFailed){\n TEST_OUT << \" ... called via FAIL_UNLESS_CALLED_FWD on line \" << m_line << std::endl;\n }\n }\n\n bool Check() const override{\n if (!m_called){\n TEST_OUT << \" FAIL_UNLESS_CALLED on line \" << m_line << \" was not called.\" << std::endl;\n TEST_FAILED = true;\n }\n return m_called;\n }\nprivate:\n mutable bool m_called;\n int m_line;\n FUNC m_fwd;\n};\n\ntemplate\nclass FailIfCalledFwd : public Checkable{\npublic:\n FailIfCalledFwd(FUNC fwd, int line)\n : m_called(false),\n m_line(line),\n m_fwd(fwd)\n {}\n\n template\n void operator()(Args...args) const {\n m_called = true;\n bool alreadyFailed = TEST_FAILED;\n m_fwd(args...);\n if (TEST_FAILED && !alreadyFailed){\n TEST_OUT << \" ... called via FAIL_IF_CALLED_FWD on line \" << m_line << std::endl;\n }\n }\n\n bool Check() const override{\n if (m_called){\n TEST_OUT << \" FAIL_IF_CALLED on line \" << m_line << \" was called.\" << std::endl;\n TEST_FAILED = true;\n }\n return m_called;\n }\nprivate:\n mutable bool m_called;\n int m_line;\n FUNC m_fwd;\n};\n\n\ninline FailUnlessCalled& create_fail_unless_called(int line){\n FailUnlessCalled* f = new FailUnlessCalled(line);\n POST_CHECKS.push_back(f);\n return *f;\n}\n\ntemplate\ninline FailUnlessCalledFwd& create_fail_unless_called_fwd(FUNC func,\n int line)\n{\n FailUnlessCalledFwd* f = new FailUnlessCalledFwd(func, line);\n POST_CHECKS.push_back(f);\n return *f;\n}\n\ntemplate\ninline FailIfCalledFwd& create_fail_if_called_fwd(FUNC func,\n int line)\n{\n FailIfCalledFwd* f = new FailIfCalledFwd(func, line);\n POST_CHECKS.push_back(f);\n return *f;\n}\n\n#define FAIL_IF_CALLED()(FailIfCalled(__LINE__))\n#define FAIL_UNLESS_CALLED()(create_fail_unless_called(__LINE__))\n#define FAIL_UNLESS_CALLED_FWD(FUNC)(create_fail_unless_called_fwd(FUNC, __LINE__))\n#define FAIL_IF_CALLED_FWD(FUNC)(create_fail_if_called_fwd(FUNC, __LINE__))\n\nenum class TestPlatform{\n LINUX,\n WINDOWS\n};\n\nTestPlatform get_test_platform();\n\n#endif\nEmacs syntax for ASSERT, ABORT_IF\/\/ -*- coding: us-ascii-unix -*-\n\/\/ Copyright 2014 Lukas Kemmer\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\"); you\n\/\/ may not use this file except in compliance with the License. You\n\/\/ may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n\/\/ implied. See the License for the specific language governing\n\/\/ permissions and limitations under the License.\n\n#ifndef FAINT_TEST_HH\n#define FAINT_TEST_HH\n#include \n#include \n#include \n#include \n#include \n#include \n\nextern std::stringstream TEST_OUT;\nextern bool TEST_FAILED;\nextern int NUM_KNOWN_ERRORS;\n\nclass AbortTestException{};\n\n\/\/ Add braces around the arguments, to get past preprocessor not\n\/\/ understanding initializer-lists.\n#define LIST(...){__VA_ARGS__}\n\n#define MESSAGE(MSG) TEST_OUT << \" Message(\" << __LINE__ << \") \" << MSG << std::endl;\n\n#define TIME_MESSAGE(MSG) TEST_OUT << \" \" << MSG << std::endl;\n\ntemplate\nstd::string str_not_equal_hex(T1 v1, T2 v2){\n std::stringstream ss;\n ss << std::hex;\n ss << static_cast(v1) << \" != \" << static_cast(v2);\n return ss.str();\n}\n\n#define EQUAL_HEX(A,B) if ((A) != (B)){ TEST_OUT << \" Error(\" << __LINE__ << \"): \" << #A << \" != \" << #B << \" (\" << str_not_equal_hex(A, B) << \")\" << std::endl; TEST_FAILED=true;}\n\n#define EQUAL(A,B) if (!((A) == (B))){ TEST_OUT << \" Error(\" << __LINE__ << \"): \" << #A << \" != \" << #B << \" (\" << A << \" != \" << B << \")\" << std::endl; TEST_FAILED=true;}\n\n#define EQUALF(A,B,FMT)if (!((A) == (B))){ TEST_OUT << \" Error(\" << __LINE__ << \"): \" << #A << \" != \" << #B << \" (\" << FMT(A) << \" != \" << FMT(B) << \")\" << std::endl; TEST_FAILED=true;}\n\n#define NOT_EQUAL(A,B) if ((A) == (B)){ TEST_OUT << \" Error(\" << __LINE__ << \"): \" << #A << \" == \" << #B << \" (\" << A << \" == \" << B << \")\" << std::endl; TEST_FAILED=true;}\n\n#define ASSERT_EQUAL(A,B) if ((A) != (B)){ TEST_OUT << \" Error(\" << __LINE__ << \"): \" << #A << \" != \" << #B << \" (\" << A << \" != \" << B << \")\" << std::endl; TEST_FAILED=true; throw AbortTestException();}\n\nclass Epsilon{\npublic:\n explicit constexpr Epsilon(double v)\n : value(v)\n {}\n\n operator double() const{\n return value;\n }\n\n double value;\n};\n\nnamespace test{\n\n\/\/ Helper to make the static_assert dependent on T.\ntemplate\nstruct TypeDependentFalse{\n static const bool value = false;\n};\n\n\ntemplate\ndouble to_double(const T&){\n static_assert(TypeDependentFalse::value,\n \"to_double not overloaded for type.\");\n return 0.0;\n}\n\ninline double to_double(double v){\n return v;\n}\n\n} \/\/ namespace\n\ntemplate\nbool test_near(const T& a, const T& b, const Epsilon& e){\n return std::fabs(test::to_double(a) - test::to_double(b)) < e;\n}\n\nconstexpr Epsilon operator \"\" _eps(long double v){\n return Epsilon(static_cast(v));\n}\n\n#define NEAR(A,B,EPS) if (!test_near(A, B, EPS)){ TEST_OUT << \" Error(\" << __LINE__ << \"): \" << #A << \" != \" << #B << \" (\" << A << \" != \" << B << \")\" << std::endl; TEST_FAILED=true;}\n\ninline bool test_write_error(const char* file, int line, const char* text){\n \/\/ Error-syntax recognized by emacs Compilation mode\n TEST_OUT << file << \"(\" << line << \"): error: \" << text << std::endl;\n\n TEST_FAILED = true;\n return false;\n}\n\ninline bool test_abort(const char* file, int line, const char* text){\n test_write_error(file, line, text);\n TEST_FAILED = true;\n throw AbortTestException();\n}\n\n#define VERIFY(C) ((C) ? true : test_write_error(__FILE__, __LINE__, \"VERIFY \" #C))\n\n#define NOT(C) ((!C) ? true : test_write_error(__FILE__, __LINE__, \"NOT \" #C))\n\n#define ASSERT(C) ((C) ? true : test_abort(__FILE__, __LINE__, \"ASSERT \"#C))\n\n#define ABORT_IF(C) ((!C) ? true : test_abort(__FILE__, __LINE__, \"ABORT_IF \" #C))\n\ninline void fail_test(){}\n\ninline void fail_test(const char* message){\n TEST_OUT << \" \" << message << std::endl;\n fail_test();\n}\n\ntemplate\nvoid fail_test(const char* message, const T&... args){\n TEST_OUT << message << \" \";\n fail_test(args...);\n}\n\n\/\/ TODO: Rename to e.g. ABORT_TEST\n#define FAIL(...) TEST_OUT << \" FAIL triggered on line \" << __LINE__ << std::endl; TEST_FAILED=true; fail_test(__VA_ARGS__); throw AbortTestException();\n\n#define SET_FAIL() TEST_OUT << \" SET_FAIL triggered on line \" << __LINE__ << std::endl; TEST_FAILED=true\n\n#define KNOWN_ERROR(C) if ((C)){TEST_OUT << \" Error(\" << __LINE__ << \"): KNOWN_ERROR \\\"\" << #C << \"\\\"..\\n\" << \" ..evaluated OK. Test not updated?\" << std::endl; TEST_FAILED=true;}else{ TEST_OUT << \" Known error(\" << __LINE__ << \"): \" << #C << std::endl; NUM_KNOWN_ERRORS += 1;}\n\n#define KNOWN_INEQUAL(A,B) if ((A) == (B)){ TEST_OUT << \" Error(\" << __LINE__ << \"): \" << #A << \" == \" << #B << \" (\" << A << \" != \" << B << \")\" << \" ..evaluated OK. Test not updated?\" << std::endl; TEST_FAILED=true;}else{ TEST_OUT << \" Known error(\" << __LINE__ << \"): \" << A << \"!=\" << B << std::endl; NUM_KNOWN_ERRORS += 1;}\n\nstruct FailIfCalled{\n FailIfCalled(int line, bool abort=false)\n : m_line(line),\n m_abort(abort)\n {}\n\n template\n void operator()(Args...) const{\n TEST_OUT << \" FailIfCalled was called on line \" << m_line << std::endl;\n TEST_FAILED = true;\n if (m_abort){\n throw AbortTestException();\n }\n }\n int m_line;\n bool m_abort;\n};\n\nclass Checkable{\npublic:\n virtual ~Checkable() = default;\n virtual bool Check() const = 0;\n};\n\nextern std::vector POST_CHECKS;\n\n\nclass FailUnlessCalled : public Checkable{\npublic:\n FailUnlessCalled(int line)\n : m_called(false),\n m_line(line)\n {}\n\n template\n void operator()(Args...) const {\n m_called = true;\n }\n\n bool Check() const override{\n if (!m_called){\n TEST_OUT << \" FAIL_UNLESS_CALLED on line \" << m_line << \" was not called.\" << std::endl;\n TEST_FAILED = true;\n }\n return m_called;\n }\nprivate:\n mutable bool m_called;\n int m_line;\n};\n\n#define FWD(CALL);{try{bool alreadyFailed = TEST_FAILED;CALL;if (TEST_FAILED && !alreadyFailed){TEST_OUT << \" ... called via FWD on line \" << __LINE__ << std::endl;}}catch(const AbortTestException&){TEST_OUT << \" ... called via FWD on line \" << __LINE__ << std::endl; throw;}}\n\n\ntemplate\nclass FailUnlessCalledFwd : public Checkable{\npublic:\n FailUnlessCalledFwd(FUNC fwd, int line)\n : m_called(false),\n m_line(line),\n m_fwd(fwd)\n {}\n\n template\n void operator()(Args...args) const {\n m_called = true;\n bool alreadyFailed = TEST_FAILED;\n m_fwd(args...);\n if (TEST_FAILED && !alreadyFailed){\n TEST_OUT << \" ... called via FAIL_UNLESS_CALLED_FWD on line \" << m_line << std::endl;\n }\n }\n\n bool Check() const override{\n if (!m_called){\n TEST_OUT << \" FAIL_UNLESS_CALLED on line \" << m_line << \" was not called.\" << std::endl;\n TEST_FAILED = true;\n }\n return m_called;\n }\nprivate:\n mutable bool m_called;\n int m_line;\n FUNC m_fwd;\n};\n\ntemplate\nclass FailIfCalledFwd : public Checkable{\npublic:\n FailIfCalledFwd(FUNC fwd, int line)\n : m_called(false),\n m_line(line),\n m_fwd(fwd)\n {}\n\n template\n void operator()(Args...args) const {\n m_called = true;\n bool alreadyFailed = TEST_FAILED;\n m_fwd(args...);\n if (TEST_FAILED && !alreadyFailed){\n TEST_OUT << \" ... called via FAIL_IF_CALLED_FWD on line \" << m_line << std::endl;\n }\n }\n\n bool Check() const override{\n if (m_called){\n TEST_OUT << \" FAIL_IF_CALLED on line \" << m_line << \" was called.\" << std::endl;\n TEST_FAILED = true;\n }\n return m_called;\n }\nprivate:\n mutable bool m_called;\n int m_line;\n FUNC m_fwd;\n};\n\n\ninline FailUnlessCalled& create_fail_unless_called(int line){\n FailUnlessCalled* f = new FailUnlessCalled(line);\n POST_CHECKS.push_back(f);\n return *f;\n}\n\ntemplate\ninline FailUnlessCalledFwd& create_fail_unless_called_fwd(FUNC func,\n int line)\n{\n FailUnlessCalledFwd* f = new FailUnlessCalledFwd(func, line);\n POST_CHECKS.push_back(f);\n return *f;\n}\n\ntemplate\ninline FailIfCalledFwd& create_fail_if_called_fwd(FUNC func,\n int line)\n{\n FailIfCalledFwd* f = new FailIfCalledFwd(func, line);\n POST_CHECKS.push_back(f);\n return *f;\n}\n\n#define FAIL_IF_CALLED()(FailIfCalled(__LINE__))\n#define FAIL_UNLESS_CALLED()(create_fail_unless_called(__LINE__))\n#define FAIL_UNLESS_CALLED_FWD(FUNC)(create_fail_unless_called_fwd(FUNC, __LINE__))\n#define FAIL_IF_CALLED_FWD(FUNC)(create_fail_if_called_fwd(FUNC, __LINE__))\n\nenum class TestPlatform{\n LINUX,\n WINDOWS\n};\n\nTestPlatform get_test_platform();\n\n#endif\n<|endoftext|>"} {"text":"\/*\n * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.\n *\n * Use of this source code is governed by a BSD-style license\n * that can be found in the LICENSE file in the root of the source\n * tree. An additional intellectual property rights grant can be found\n * in the file PATENTS. All contributing project authors may\n * be found in the AUTHORS file in the root of the source tree.\n *\/\n\n#include \"webrtc\/voice_engine\/test\/auto_test\/fixtures\/after_streaming_fixture.h\"\n\nnamespace {\n\nvoid ExpectVolumeNear(int expected, int actual) {\n \/\/ The hardware volume may be more coarsely quantized than [0, 255], so\n \/\/ it is not always reasonable to expect to get exactly what we set. This\n \/\/ allows for some error.\n const int kMaxVolumeError = 10;\n EXPECT_NEAR(expected, actual, kMaxVolumeError);\n EXPECT_GE(actual, 0);\n EXPECT_LE(actual, 255);\n}\n\n} \/\/ namespace\n\nclass VolumeTest : public AfterStreamingFixture {\n};\n\n\/\/ TODO(phoglund): a number of tests are disabled here on Linux, all pending\n\/\/ investigation in\n\/\/ http:\/\/code.google.com\/p\/webrtc\/issues\/detail?id=367\n\nTEST_F(VolumeTest, DefaultSpeakerVolumeIsAtMost255) {\n unsigned int volume = 1000;\n EXPECT_EQ(0, voe_volume_control_->GetSpeakerVolume(volume));\n EXPECT_LE(volume, 255u);\n}\n\nTEST_F(VolumeTest, SetVolumeBeforePlayoutWorks) {\n \/\/ This is a rather specialized test, intended to exercise some PulseAudio\n \/\/ code. However, these conditions should be satisfied on any platform.\n unsigned int original_volume = 0;\n EXPECT_EQ(0, voe_volume_control_->GetSpeakerVolume(original_volume));\n Sleep(1000);\n\n EXPECT_EQ(0, voe_volume_control_->SetSpeakerVolume(200));\n unsigned int volume;\n EXPECT_EQ(0, voe_volume_control_->GetSpeakerVolume(volume));\n ExpectVolumeNear(200u, volume);\n\n PausePlaying();\n ResumePlaying();\n EXPECT_EQ(0, voe_volume_control_->GetSpeakerVolume(volume));\n \/\/ Ensure the volume has not changed after resuming playout.\n ExpectVolumeNear(200u, volume);\n\n PausePlaying();\n EXPECT_EQ(0, voe_volume_control_->SetSpeakerVolume(100));\n ResumePlaying();\n \/\/ Ensure the volume set while paused is retained.\n EXPECT_EQ(0, voe_volume_control_->GetSpeakerVolume(volume));\n ExpectVolumeNear(100u, volume);\n\n EXPECT_EQ(0, voe_volume_control_->SetSpeakerVolume(original_volume));\n}\n\nTEST_F(VolumeTest, ManualSetVolumeWorks) {\n unsigned int original_volume = 0;\n EXPECT_EQ(0, voe_volume_control_->GetSpeakerVolume(original_volume));\n Sleep(1000);\n\n TEST_LOG(\"Setting speaker volume to 0 out of 255.\\n\");\n EXPECT_EQ(0, voe_volume_control_->SetSpeakerVolume(0));\n unsigned int volume;\n EXPECT_EQ(0, voe_volume_control_->GetSpeakerVolume(volume));\n ExpectVolumeNear(0u, volume);\n Sleep(1000);\n\n TEST_LOG(\"Setting speaker volume to 100 out of 255.\\n\");\n EXPECT_EQ(0, voe_volume_control_->SetSpeakerVolume(100));\n EXPECT_EQ(0, voe_volume_control_->GetSpeakerVolume(volume));\n ExpectVolumeNear(100u, volume);\n Sleep(1000);\n\n \/\/ Set the volume to 255 very briefly so we don't blast the poor user\n \/\/ listening to this. This is just to test the call succeeds.\n EXPECT_EQ(0, voe_volume_control_->SetSpeakerVolume(255));\n EXPECT_EQ(0, voe_volume_control_->GetSpeakerVolume(volume));\n ExpectVolumeNear(255u, volume);\n\n TEST_LOG(\"Setting speaker volume to the original %d out of 255.\\n\",\n original_volume);\n EXPECT_EQ(0, voe_volume_control_->SetSpeakerVolume(original_volume));\n Sleep(1000);\n}\n\nTEST_F(VolumeTest, DISABLED_ON_LINUX(DefaultMicrophoneVolumeIsAtMost255)) {\n unsigned int volume = 1000;\n EXPECT_EQ(0, voe_volume_control_->GetMicVolume(volume));\n EXPECT_LE(volume, 255u);\n}\n\nTEST_F(VolumeTest, DISABLED_ON_LINUX(\n ManualRequiresMicrophoneCanSetMicrophoneVolumeWithAcgOff)) {\n SwitchToManualMicrophone();\n EXPECT_EQ(0, voe_apm_->SetAgcStatus(false));\n\n unsigned int original_volume = 0;\n EXPECT_EQ(0, voe_volume_control_->GetMicVolume(original_volume));\n\n TEST_LOG(\"Setting microphone volume to 0.\\n\");\n EXPECT_EQ(0, voe_volume_control_->SetMicVolume(channel_));\n Sleep(1000);\n TEST_LOG(\"Setting microphone volume to 255.\\n\");\n EXPECT_EQ(0, voe_volume_control_->SetMicVolume(255));\n Sleep(1000);\n TEST_LOG(\"Setting microphone volume back to saved value.\\n\");\n EXPECT_EQ(0, voe_volume_control_->SetMicVolume(original_volume));\n Sleep(1000);\n}\n\nTEST_F(VolumeTest, ChannelScalingIsOneByDefault) {\n float scaling = -1.0f;\n\n EXPECT_EQ(0, voe_volume_control_->GetChannelOutputVolumeScaling(\n channel_, scaling));\n EXPECT_FLOAT_EQ(1.0f, scaling);\n}\n\nTEST_F(VolumeTest, ManualCanSetChannelScaling) {\n EXPECT_EQ(0, voe_volume_control_->SetChannelOutputVolumeScaling(\n channel_, 0.1f));\n\n float scaling = 1.0f;\n EXPECT_EQ(0, voe_volume_control_->GetChannelOutputVolumeScaling(\n channel_, scaling));\n\n EXPECT_FLOAT_EQ(0.1f, scaling);\n\n TEST_LOG(\"Channel scaling set to 0.1: audio should be barely audible.\\n\");\n Sleep(2000);\n}\n\nTEST_F(VolumeTest, InputMutingIsNotEnabledByDefault) {\n bool is_muted = true;\n EXPECT_EQ(0, voe_volume_control_->GetInputMute(channel_, is_muted));\n EXPECT_FALSE(is_muted);\n}\n\nTEST_F(VolumeTest, DISABLED_ON_LINUX(ManualInputMutingMutesMicrophone)) {\n SwitchToManualMicrophone();\n\n \/\/ Enable muting.\n EXPECT_EQ(0, voe_volume_control_->SetInputMute(channel_, true));\n bool is_muted = false;\n EXPECT_EQ(0, voe_volume_control_->GetInputMute(channel_, is_muted));\n EXPECT_TRUE(is_muted);\n\n TEST_LOG(\"Muted: talk into microphone and verify you can't hear yourself.\\n\");\n Sleep(2000);\n\n \/\/ Test that we can disable muting.\n EXPECT_EQ(0, voe_volume_control_->SetInputMute(channel_, false));\n EXPECT_EQ(0, voe_volume_control_->GetInputMute(channel_, is_muted));\n EXPECT_FALSE(is_muted);\n\n TEST_LOG(\"Unmuted: talk into microphone and verify you can hear yourself.\\n\");\n Sleep(2000);\n}\n\nTEST_F(VolumeTest, DISABLED_ON_LINUX(SystemInputMutingIsNotEnabledByDefault)) {\n bool is_muted = true;\n EXPECT_EQ(0, voe_volume_control_->GetSystemInputMute(is_muted));\n EXPECT_FALSE(is_muted);\n}\n\nTEST_F(VolumeTest, DISABLED_ON_LINUX(ManualSystemInputMutingMutesMicrophone)) {\n SwitchToManualMicrophone();\n\n \/\/ Enable system input muting.\n EXPECT_EQ(0, voe_volume_control_->SetSystemInputMute(true));\n bool is_muted = false;\n EXPECT_EQ(0, voe_volume_control_->GetSystemInputMute(is_muted));\n EXPECT_TRUE(is_muted);\n\n TEST_LOG(\"Muted: talk into microphone and verify you can't hear yourself.\\n\");\n Sleep(2000);\n\n \/\/ Test that we can disable system input muting.\n EXPECT_EQ(0, voe_volume_control_->SetSystemInputMute(false));\n EXPECT_EQ(0, voe_volume_control_->GetSystemInputMute(is_muted));\n EXPECT_FALSE(is_muted);\n\n TEST_LOG(\"Unmuted: talk into microphone and verify you can hear yourself.\\n\");\n Sleep(2000);\n}\n\nTEST_F(VolumeTest, DISABLED_ON_LINUX(SystemOutputMutingIsNotEnabledByDefault)) {\n bool is_muted = true;\n EXPECT_EQ(0, voe_volume_control_->GetSystemOutputMute(is_muted));\n EXPECT_FALSE(is_muted);\n}\n\nTEST_F(VolumeTest, ManualSystemOutputMutingMutesOutput) {\n \/\/ Enable muting.\n EXPECT_EQ(0, voe_volume_control_->SetSystemOutputMute(true));\n bool is_muted = false;\n EXPECT_EQ(0, voe_volume_control_->GetSystemOutputMute(is_muted));\n EXPECT_TRUE(is_muted);\n\n TEST_LOG(\"Muted: you should hear no audio.\\n\");\n Sleep(2000);\n\n \/\/ Test that we can disable muting.\n EXPECT_EQ(0, voe_volume_control_->SetSystemOutputMute(false));\n EXPECT_EQ(0, voe_volume_control_->GetSystemOutputMute(is_muted));\n EXPECT_FALSE(is_muted);\n\n TEST_LOG(\"Unmuted: you should hear audio.\\n\");\n Sleep(2000);\n}\n\nTEST_F(VolumeTest, ManualTestInputAndOutputLevels) {\n SwitchToManualMicrophone();\n\n TEST_LOG(\"Speak and verify that the following levels look right:\\n\");\n for (int i = 0; i < 5; i++) {\n Sleep(1000);\n unsigned int input_level = 0;\n unsigned int output_level = 0;\n unsigned int input_level_full_range = 0;\n unsigned int output_level_full_range = 0;\n\n EXPECT_EQ(0, voe_volume_control_->GetSpeechInputLevel(\n input_level));\n EXPECT_EQ(0, voe_volume_control_->GetSpeechOutputLevel(\n channel_, output_level));\n EXPECT_EQ(0, voe_volume_control_->GetSpeechInputLevelFullRange(\n input_level_full_range));\n EXPECT_EQ(0, voe_volume_control_->GetSpeechOutputLevelFullRange(\n channel_, output_level_full_range));\n\n TEST_LOG(\" warped levels (0-9) : in=%5d, out=%5d\\n\",\n input_level, output_level);\n TEST_LOG(\" linear levels (0-32768): in=%5d, out=%5d\\n\",\n input_level_full_range, output_level_full_range);\n }\n}\n\nTEST_F(VolumeTest, ChannelsAreNotPannedByDefault) {\n float left = -1.0;\n float right = -1.0;\n\n EXPECT_EQ(0, voe_volume_control_->GetOutputVolumePan(channel_, left, right));\n EXPECT_FLOAT_EQ(1.0, left);\n EXPECT_FLOAT_EQ(1.0, right);\n}\n\nTEST_F(VolumeTest, ManualTestChannelPanning) {\n TEST_LOG(\"Panning left.\\n\");\n EXPECT_EQ(0, voe_volume_control_->SetOutputVolumePan(channel_, 0.8f, 0.1f));\n Sleep(1000);\n\n TEST_LOG(\"Back to center.\\n\");\n EXPECT_EQ(0, voe_volume_control_->SetOutputVolumePan(channel_, 1.0f, 1.0f));\n Sleep(1000);\n\n TEST_LOG(\"Panning right.\\n\");\n EXPECT_EQ(0, voe_volume_control_->SetOutputVolumePan(channel_, 0.1f, 0.8f));\n Sleep(1000);\n\n \/\/ To finish, verify that the getter works.\n float left = 0.0f;\n float right = 0.0f;\n\n EXPECT_EQ(0, voe_volume_control_->GetOutputVolumePan(channel_, left, right));\n EXPECT_FLOAT_EQ(0.1f, left);\n EXPECT_FLOAT_EQ(0.8f, right);\n}\nEnables VolumeTest.DefaultMicrophoneVolumeIsAtMost255\/*\n * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.\n *\n * Use of this source code is governed by a BSD-style license\n * that can be found in the LICENSE file in the root of the source\n * tree. An additional intellectual property rights grant can be found\n * in the file PATENTS. All contributing project authors may\n * be found in the AUTHORS file in the root of the source tree.\n *\/\n\n#include \"webrtc\/voice_engine\/test\/auto_test\/fixtures\/after_streaming_fixture.h\"\n\nnamespace {\n\nvoid ExpectVolumeNear(int expected, int actual) {\n \/\/ The hardware volume may be more coarsely quantized than [0, 255], so\n \/\/ it is not always reasonable to expect to get exactly what we set. This\n \/\/ allows for some error.\n const int kMaxVolumeError = 10;\n EXPECT_NEAR(expected, actual, kMaxVolumeError);\n EXPECT_GE(actual, 0);\n EXPECT_LE(actual, 255);\n}\n\n} \/\/ namespace\n\nclass VolumeTest : public AfterStreamingFixture {\n};\n\n\/\/ TODO(phoglund): a number of tests are disabled here on Linux, all pending\n\/\/ investigation in\n\/\/ http:\/\/code.google.com\/p\/webrtc\/issues\/detail?id=367\n\nTEST_F(VolumeTest, DefaultSpeakerVolumeIsAtMost255) {\n unsigned int volume = 1000;\n EXPECT_EQ(0, voe_volume_control_->GetSpeakerVolume(volume));\n EXPECT_LE(volume, 255u);\n}\n\nTEST_F(VolumeTest, SetVolumeBeforePlayoutWorks) {\n \/\/ This is a rather specialized test, intended to exercise some PulseAudio\n \/\/ code. However, these conditions should be satisfied on any platform.\n unsigned int original_volume = 0;\n EXPECT_EQ(0, voe_volume_control_->GetSpeakerVolume(original_volume));\n Sleep(1000);\n\n EXPECT_EQ(0, voe_volume_control_->SetSpeakerVolume(200));\n unsigned int volume;\n EXPECT_EQ(0, voe_volume_control_->GetSpeakerVolume(volume));\n ExpectVolumeNear(200u, volume);\n\n PausePlaying();\n ResumePlaying();\n EXPECT_EQ(0, voe_volume_control_->GetSpeakerVolume(volume));\n \/\/ Ensure the volume has not changed after resuming playout.\n ExpectVolumeNear(200u, volume);\n\n PausePlaying();\n EXPECT_EQ(0, voe_volume_control_->SetSpeakerVolume(100));\n ResumePlaying();\n \/\/ Ensure the volume set while paused is retained.\n EXPECT_EQ(0, voe_volume_control_->GetSpeakerVolume(volume));\n ExpectVolumeNear(100u, volume);\n\n EXPECT_EQ(0, voe_volume_control_->SetSpeakerVolume(original_volume));\n}\n\nTEST_F(VolumeTest, ManualSetVolumeWorks) {\n unsigned int original_volume = 0;\n EXPECT_EQ(0, voe_volume_control_->GetSpeakerVolume(original_volume));\n Sleep(1000);\n\n TEST_LOG(\"Setting speaker volume to 0 out of 255.\\n\");\n EXPECT_EQ(0, voe_volume_control_->SetSpeakerVolume(0));\n unsigned int volume;\n EXPECT_EQ(0, voe_volume_control_->GetSpeakerVolume(volume));\n ExpectVolumeNear(0u, volume);\n Sleep(1000);\n\n TEST_LOG(\"Setting speaker volume to 100 out of 255.\\n\");\n EXPECT_EQ(0, voe_volume_control_->SetSpeakerVolume(100));\n EXPECT_EQ(0, voe_volume_control_->GetSpeakerVolume(volume));\n ExpectVolumeNear(100u, volume);\n Sleep(1000);\n\n \/\/ Set the volume to 255 very briefly so we don't blast the poor user\n \/\/ listening to this. This is just to test the call succeeds.\n EXPECT_EQ(0, voe_volume_control_->SetSpeakerVolume(255));\n EXPECT_EQ(0, voe_volume_control_->GetSpeakerVolume(volume));\n ExpectVolumeNear(255u, volume);\n\n TEST_LOG(\"Setting speaker volume to the original %d out of 255.\\n\",\n original_volume);\n EXPECT_EQ(0, voe_volume_control_->SetSpeakerVolume(original_volume));\n Sleep(1000);\n}\n\nTEST_F(VolumeTest, DefaultMicrophoneVolumeIsAtMost255) {\n unsigned int volume = 1000;\n if (voe_volume_control_->GetMicVolume(volume) == 0)\n EXPECT_LE(volume, 255u);\n else\n EXPECT_EQ(1000u, volume);\n}\n\nTEST_F(VolumeTest, DISABLED_ON_LINUX(\n ManualRequiresMicrophoneCanSetMicrophoneVolumeWithAcgOff)) {\n SwitchToManualMicrophone();\n EXPECT_EQ(0, voe_apm_->SetAgcStatus(false));\n\n unsigned int original_volume = 0;\n EXPECT_EQ(0, voe_volume_control_->GetMicVolume(original_volume));\n\n TEST_LOG(\"Setting microphone volume to 0.\\n\");\n EXPECT_EQ(0, voe_volume_control_->SetMicVolume(channel_));\n Sleep(1000);\n TEST_LOG(\"Setting microphone volume to 255.\\n\");\n EXPECT_EQ(0, voe_volume_control_->SetMicVolume(255));\n Sleep(1000);\n TEST_LOG(\"Setting microphone volume back to saved value.\\n\");\n EXPECT_EQ(0, voe_volume_control_->SetMicVolume(original_volume));\n Sleep(1000);\n}\n\nTEST_F(VolumeTest, ChannelScalingIsOneByDefault) {\n float scaling = -1.0f;\n\n EXPECT_EQ(0, voe_volume_control_->GetChannelOutputVolumeScaling(\n channel_, scaling));\n EXPECT_FLOAT_EQ(1.0f, scaling);\n}\n\nTEST_F(VolumeTest, ManualCanSetChannelScaling) {\n EXPECT_EQ(0, voe_volume_control_->SetChannelOutputVolumeScaling(\n channel_, 0.1f));\n\n float scaling = 1.0f;\n EXPECT_EQ(0, voe_volume_control_->GetChannelOutputVolumeScaling(\n channel_, scaling));\n\n EXPECT_FLOAT_EQ(0.1f, scaling);\n\n TEST_LOG(\"Channel scaling set to 0.1: audio should be barely audible.\\n\");\n Sleep(2000);\n}\n\nTEST_F(VolumeTest, InputMutingIsNotEnabledByDefault) {\n bool is_muted = true;\n EXPECT_EQ(0, voe_volume_control_->GetInputMute(channel_, is_muted));\n EXPECT_FALSE(is_muted);\n}\n\nTEST_F(VolumeTest, DISABLED_ON_LINUX(ManualInputMutingMutesMicrophone)) {\n SwitchToManualMicrophone();\n\n \/\/ Enable muting.\n EXPECT_EQ(0, voe_volume_control_->SetInputMute(channel_, true));\n bool is_muted = false;\n EXPECT_EQ(0, voe_volume_control_->GetInputMute(channel_, is_muted));\n EXPECT_TRUE(is_muted);\n\n TEST_LOG(\"Muted: talk into microphone and verify you can't hear yourself.\\n\");\n Sleep(2000);\n\n \/\/ Test that we can disable muting.\n EXPECT_EQ(0, voe_volume_control_->SetInputMute(channel_, false));\n EXPECT_EQ(0, voe_volume_control_->GetInputMute(channel_, is_muted));\n EXPECT_FALSE(is_muted);\n\n TEST_LOG(\"Unmuted: talk into microphone and verify you can hear yourself.\\n\");\n Sleep(2000);\n}\n\nTEST_F(VolumeTest, DISABLED_ON_LINUX(SystemInputMutingIsNotEnabledByDefault)) {\n bool is_muted = true;\n EXPECT_EQ(0, voe_volume_control_->GetSystemInputMute(is_muted));\n EXPECT_FALSE(is_muted);\n}\n\nTEST_F(VolumeTest, DISABLED_ON_LINUX(ManualSystemInputMutingMutesMicrophone)) {\n SwitchToManualMicrophone();\n\n \/\/ Enable system input muting.\n EXPECT_EQ(0, voe_volume_control_->SetSystemInputMute(true));\n bool is_muted = false;\n EXPECT_EQ(0, voe_volume_control_->GetSystemInputMute(is_muted));\n EXPECT_TRUE(is_muted);\n\n TEST_LOG(\"Muted: talk into microphone and verify you can't hear yourself.\\n\");\n Sleep(2000);\n\n \/\/ Test that we can disable system input muting.\n EXPECT_EQ(0, voe_volume_control_->SetSystemInputMute(false));\n EXPECT_EQ(0, voe_volume_control_->GetSystemInputMute(is_muted));\n EXPECT_FALSE(is_muted);\n\n TEST_LOG(\"Unmuted: talk into microphone and verify you can hear yourself.\\n\");\n Sleep(2000);\n}\n\nTEST_F(VolumeTest, DISABLED_ON_LINUX(SystemOutputMutingIsNotEnabledByDefault)) {\n bool is_muted = true;\n EXPECT_EQ(0, voe_volume_control_->GetSystemOutputMute(is_muted));\n EXPECT_FALSE(is_muted);\n}\n\nTEST_F(VolumeTest, ManualSystemOutputMutingMutesOutput) {\n \/\/ Enable muting.\n EXPECT_EQ(0, voe_volume_control_->SetSystemOutputMute(true));\n bool is_muted = false;\n EXPECT_EQ(0, voe_volume_control_->GetSystemOutputMute(is_muted));\n EXPECT_TRUE(is_muted);\n\n TEST_LOG(\"Muted: you should hear no audio.\\n\");\n Sleep(2000);\n\n \/\/ Test that we can disable muting.\n EXPECT_EQ(0, voe_volume_control_->SetSystemOutputMute(false));\n EXPECT_EQ(0, voe_volume_control_->GetSystemOutputMute(is_muted));\n EXPECT_FALSE(is_muted);\n\n TEST_LOG(\"Unmuted: you should hear audio.\\n\");\n Sleep(2000);\n}\n\nTEST_F(VolumeTest, ManualTestInputAndOutputLevels) {\n SwitchToManualMicrophone();\n\n TEST_LOG(\"Speak and verify that the following levels look right:\\n\");\n for (int i = 0; i < 5; i++) {\n Sleep(1000);\n unsigned int input_level = 0;\n unsigned int output_level = 0;\n unsigned int input_level_full_range = 0;\n unsigned int output_level_full_range = 0;\n\n EXPECT_EQ(0, voe_volume_control_->GetSpeechInputLevel(\n input_level));\n EXPECT_EQ(0, voe_volume_control_->GetSpeechOutputLevel(\n channel_, output_level));\n EXPECT_EQ(0, voe_volume_control_->GetSpeechInputLevelFullRange(\n input_level_full_range));\n EXPECT_EQ(0, voe_volume_control_->GetSpeechOutputLevelFullRange(\n channel_, output_level_full_range));\n\n TEST_LOG(\" warped levels (0-9) : in=%5d, out=%5d\\n\",\n input_level, output_level);\n TEST_LOG(\" linear levels (0-32768): in=%5d, out=%5d\\n\",\n input_level_full_range, output_level_full_range);\n }\n}\n\nTEST_F(VolumeTest, ChannelsAreNotPannedByDefault) {\n float left = -1.0;\n float right = -1.0;\n\n EXPECT_EQ(0, voe_volume_control_->GetOutputVolumePan(channel_, left, right));\n EXPECT_FLOAT_EQ(1.0, left);\n EXPECT_FLOAT_EQ(1.0, right);\n}\n\nTEST_F(VolumeTest, ManualTestChannelPanning) {\n TEST_LOG(\"Panning left.\\n\");\n EXPECT_EQ(0, voe_volume_control_->SetOutputVolumePan(channel_, 0.8f, 0.1f));\n Sleep(1000);\n\n TEST_LOG(\"Back to center.\\n\");\n EXPECT_EQ(0, voe_volume_control_->SetOutputVolumePan(channel_, 1.0f, 1.0f));\n Sleep(1000);\n\n TEST_LOG(\"Panning right.\\n\");\n EXPECT_EQ(0, voe_volume_control_->SetOutputVolumePan(channel_, 0.1f, 0.8f));\n Sleep(1000);\n\n \/\/ To finish, verify that the getter works.\n float left = 0.0f;\n float right = 0.0f;\n\n EXPECT_EQ(0, voe_volume_control_->GetOutputVolumePan(channel_, left, right));\n EXPECT_FLOAT_EQ(0.1f, left);\n EXPECT_FLOAT_EQ(0.8f, right);\n}\n<|endoftext|>"} {"text":"\/*\n Copyright (C) 2015 Vladimir \"allejo\" Jimenez\n\n Permission is hereby granted, free of charge, to any person obtaining a copy\n of this software and associated documentation files (the \"Software\"), to deal\n in the Software without restriction, including without limitation the rights\n to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n copies of the Software, and to permit persons to whom the Software is\n furnished to do so, subject to the following conditions:\n\n The above copyright notice and this permission notice shall be included in\n all copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n THE SOFTWARE.\n *\/\n\n#include \n\n#include \"bzfsAPI.h\"\n#include \"bztoolkit\/bzToolkitApi.h\"\n\n\/\/ Define plug-in name\nconst std::string PLUGIN_NAME = \"Match Trainer Assistant\";\n\n\/\/ Define plug-in version numbering\nconst int MAJOR = 1;\nconst int MINOR = 0;\nconst int REV = 0;\nconst int BUILD = 1;\n\nclass MatchTrainerAssistant : public bz_Plugin, public bz_CustomSlashCommandHandler\n{\npublic:\n virtual const char* Name ();\n virtual void Init (const char* config);\n virtual void Event (bz_EventData *eventData);\n virtual void Cleanup (void);\n\n virtual bool SlashCommand (int playerID, bz_ApiString, bz_ApiString, bz_APIStringList*);\n\n bool handleSpawn[256];\n float lastDeaths[256][4];\n};\n\nBZ_PLUGIN(MatchTrainerAssistant)\n\nconst char* MatchTrainerAssistant::Name (void)\n{\n static std::string pluginBuild = \"\";\n\n if (!pluginBuild.size())\n {\n std::ostringstream pluginBuildStream;\n\n pluginBuildStream << PLUGIN_NAME << \" \" << MAJOR << \".\" << MINOR << \".\" << REV << \" (\" << BUILD << \")\";\n pluginBuild = pluginBuildStream.str();\n }\n\n return pluginBuild.c_str();\n}\n\nvoid MatchTrainerAssistant::Init (const char* commandLine)\n{\n \/\/ Register our events with Register()\n Register(bz_eGetPlayerSpawnPosEvent);\n Register(bz_ePlayerDieEvent);\n\n \/\/ Register our custom slash commands\n bz_registerCustomSlashCommand(\"spawn\", this);\n bz_registerCustomSlashCommand(\"flag\", this);\n bz_registerCustomSlashCommand(\"die\", this);\n}\n\nvoid MatchTrainerAssistant::Cleanup (void)\n{\n Flush(); \/\/ Clean up all the events\n\n \/\/ Clean up our custom slash commands\n bz_removeCustomSlashCommand(\"spawn\");\n bz_removeCustomSlashCommand(\"flag\");\n bz_removeCustomSlashCommand(\"die\");\n}\n\nvoid MatchTrainerAssistant::Event (bz_EventData *eventData)\n{\n switch (eventData->eventType)\n {\n case bz_eGetPlayerSpawnPosEvent: \/\/ This event is called each time the server needs a new spawn postion\n {\n bz_GetPlayerSpawnPosEventData_V1* spawnData = (bz_GetPlayerSpawnPosEventData_V1*)eventData;\n\n if (handleSpawn[spawnData->playerID])\n {\n spawnData->handled = handleSpawn[spawnData->playerID];\n spawnData->pos[0] = lastDeaths[spawnData->playerID][0];\n spawnData->pos[1] = lastDeaths[spawnData->playerID][1];\n spawnData->pos[2] = lastDeaths[spawnData->playerID][2];\n spawnData->rot = lastDeaths[spawnData->playerID][3];\n\n handleSpawn[spawnData->playerID] = false;\n }\n }\n break;\n\n case bz_ePlayerDieEvent: \/\/ This event is called each time a tank is killed.\n {\n bz_PlayerDieEventData_V1* dieData = (bz_PlayerDieEventData_V1*)eventData;\n\n lastDeaths[dieData->playerID][0] = dieData->state.pos[0];\n lastDeaths[dieData->playerID][1] = dieData->state.pos[1];\n lastDeaths[dieData->playerID][2] = dieData->state.pos[2];\n lastDeaths[dieData->playerID][3] = dieData->state.rotation;\n }\n break;\n\n default: break;\n }\n}\n\n\nbool MatchTrainerAssistant::SlashCommand(int playerID, bz_ApiString command, bz_ApiString \/*message*\/, bz_APIStringList *params)\n{\n std::unique_ptr pr(bz_getPlayerByIndex(playerID));\n\n if (command == \"spawn\")\n {\n if (pr->team == eObservers)\n {\n bz_sendTextMessage(BZ_SERVER, playerID, \"Only players may execute this command.\");\n return true;\n }\n\n if (pr->spawned)\n {\n bz_killPlayer(playerID, BZ_SERVER);\n }\n\n if (params->size() > 0)\n {\n if (params->size() != 1 && params->size() != 4)\n {\n bz_sendTextMessage(BZ_SERVER, playerID, \"Spawn Command Usage\");\n bz_sendTextMessage(BZ_SERVER, playerID, \"---\");\n bz_sendTextMessage(BZ_SERVER, playerID, \"\/spawn\");\n bz_sendTextMessage(BZ_SERVER, playerID, \" - Respawn at the location of your last death\");\n bz_sendTextMessage(BZ_SERVER, playerID, \"\/spawn \");\n bz_sendTextMessage(BZ_SERVER, playerID, \" - Respawn at the location of another player's location or location of death\");\n bz_sendTextMessage(BZ_SERVER, playerID, \"\/spawn \");\n bz_sendTextMessage(BZ_SERVER, playerID, \" - Respawn at specified location; don't spawn inside a building!\");\n\n return true;\n }\n else if (params->size() == 1)\n {\n std::unique_ptr target(bz_getPlayerBySlotOrCallsign(params->get(0).c_str()));\n\n lastDeaths[playerID][0] = target->lastKnownState.pos[0];\n lastDeaths[playerID][1] = target->lastKnownState.pos[1];\n lastDeaths[playerID][2] = target->lastKnownState.pos[2];\n lastDeaths[playerID][3] = target->lastKnownState.rotation;\n }\n else\n {\n lastDeaths[playerID][0] = std::atoi(params->get(0).c_str());\n lastDeaths[playerID][1] = std::atoi(params->get(1).c_str());\n lastDeaths[playerID][2] = std::atoi(params->get(2).c_str());\n lastDeaths[playerID][3] = std::atoi(params->get(3).c_str());\n }\n }\n\n bztk_forcePlayerSpawn(playerID);\n handleSpawn[playerID] = true;\n\n return true;\n }\n else if (command == \"flag\")\n {\n bz_givePlayerFlag(playerID, bztk_getFlagFromTeam(pr->team), false);\n\n return false;\n }\n else if (command == \"die\")\n {\n bz_killPlayer(playerID, BZ_SERVER);\n\n return true;\n }\n\n return false;\n}\nOnly players can use all the commands\/*\n Copyright (C) 2015 Vladimir \"allejo\" Jimenez\n\n Permission is hereby granted, free of charge, to any person obtaining a copy\n of this software and associated documentation files (the \"Software\"), to deal\n in the Software without restriction, including without limitation the rights\n to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n copies of the Software, and to permit persons to whom the Software is\n furnished to do so, subject to the following conditions:\n\n The above copyright notice and this permission notice shall be included in\n all copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n THE SOFTWARE.\n *\/\n\n#include \n\n#include \"bzfsAPI.h\"\n#include \"bztoolkit\/bzToolkitApi.h\"\n\n\/\/ Define plug-in name\nconst std::string PLUGIN_NAME = \"Match Trainer Assistant\";\n\n\/\/ Define plug-in version numbering\nconst int MAJOR = 1;\nconst int MINOR = 0;\nconst int REV = 0;\nconst int BUILD = 1;\n\nclass MatchTrainerAssistant : public bz_Plugin, public bz_CustomSlashCommandHandler\n{\npublic:\n virtual const char* Name ();\n virtual void Init (const char* config);\n virtual void Event (bz_EventData *eventData);\n virtual void Cleanup (void);\n\n virtual bool SlashCommand (int playerID, bz_ApiString, bz_ApiString, bz_APIStringList*);\n\n bool handleSpawn[256];\n float lastDeaths[256][4];\n};\n\nBZ_PLUGIN(MatchTrainerAssistant)\n\nconst char* MatchTrainerAssistant::Name (void)\n{\n static std::string pluginBuild = \"\";\n\n if (!pluginBuild.size())\n {\n std::ostringstream pluginBuildStream;\n\n pluginBuildStream << PLUGIN_NAME << \" \" << MAJOR << \".\" << MINOR << \".\" << REV << \" (\" << BUILD << \")\";\n pluginBuild = pluginBuildStream.str();\n }\n\n return pluginBuild.c_str();\n}\n\nvoid MatchTrainerAssistant::Init (const char* commandLine)\n{\n \/\/ Register our events with Register()\n Register(bz_eGetPlayerSpawnPosEvent);\n Register(bz_ePlayerDieEvent);\n\n \/\/ Register our custom slash commands\n bz_registerCustomSlashCommand(\"spawn\", this);\n bz_registerCustomSlashCommand(\"flag\", this);\n bz_registerCustomSlashCommand(\"die\", this);\n}\n\nvoid MatchTrainerAssistant::Cleanup (void)\n{\n Flush(); \/\/ Clean up all the events\n\n \/\/ Clean up our custom slash commands\n bz_removeCustomSlashCommand(\"spawn\");\n bz_removeCustomSlashCommand(\"flag\");\n bz_removeCustomSlashCommand(\"die\");\n}\n\nvoid MatchTrainerAssistant::Event (bz_EventData *eventData)\n{\n switch (eventData->eventType)\n {\n case bz_eGetPlayerSpawnPosEvent: \/\/ This event is called each time the server needs a new spawn postion\n {\n bz_GetPlayerSpawnPosEventData_V1* spawnData = (bz_GetPlayerSpawnPosEventData_V1*)eventData;\n\n if (handleSpawn[spawnData->playerID])\n {\n spawnData->handled = handleSpawn[spawnData->playerID];\n spawnData->pos[0] = lastDeaths[spawnData->playerID][0];\n spawnData->pos[1] = lastDeaths[spawnData->playerID][1];\n spawnData->pos[2] = lastDeaths[spawnData->playerID][2];\n spawnData->rot = lastDeaths[spawnData->playerID][3];\n\n handleSpawn[spawnData->playerID] = false;\n }\n }\n break;\n\n case bz_ePlayerDieEvent: \/\/ This event is called each time a tank is killed.\n {\n bz_PlayerDieEventData_V1* dieData = (bz_PlayerDieEventData_V1*)eventData;\n\n lastDeaths[dieData->playerID][0] = dieData->state.pos[0];\n lastDeaths[dieData->playerID][1] = dieData->state.pos[1];\n lastDeaths[dieData->playerID][2] = dieData->state.pos[2];\n lastDeaths[dieData->playerID][3] = dieData->state.rotation;\n }\n break;\n\n default: break;\n }\n}\n\n\nbool MatchTrainerAssistant::SlashCommand(int playerID, bz_ApiString command, bz_ApiString \/*message*\/, bz_APIStringList *params)\n{\n std::unique_ptr pr(bz_getPlayerByIndex(playerID));\n\n if (pr->team == eObservers)\n {\n bz_sendTextMessage(BZ_SERVER, playerID, \"These commands are intended for players only.\");\n\n return true;\n }\n\n if (command == \"spawn\")\n {\n if (pr->spawned)\n {\n bz_killPlayer(playerID, BZ_SERVER);\n }\n\n if (params->size() > 0)\n {\n if (params->size() != 1 && params->size() != 4)\n {\n bz_sendTextMessage(BZ_SERVER, playerID, \"Spawn Command Usage\");\n bz_sendTextMessage(BZ_SERVER, playerID, \"---\");\n bz_sendTextMessage(BZ_SERVER, playerID, \"\/spawn\");\n bz_sendTextMessage(BZ_SERVER, playerID, \" - Respawn at the location of your last death\");\n bz_sendTextMessage(BZ_SERVER, playerID, \"\/spawn \");\n bz_sendTextMessage(BZ_SERVER, playerID, \" - Respawn at the location of another player's location or location of death\");\n bz_sendTextMessage(BZ_SERVER, playerID, \"\/spawn \");\n bz_sendTextMessage(BZ_SERVER, playerID, \" - Respawn at specified location; don't spawn inside a building!\");\n\n return true;\n }\n else if (params->size() == 1)\n {\n std::unique_ptr target(bz_getPlayerBySlotOrCallsign(params->get(0).c_str()));\n\n lastDeaths[playerID][0] = target->lastKnownState.pos[0];\n lastDeaths[playerID][1] = target->lastKnownState.pos[1];\n lastDeaths[playerID][2] = target->lastKnownState.pos[2];\n lastDeaths[playerID][3] = target->lastKnownState.rotation;\n }\n else\n {\n lastDeaths[playerID][0] = std::atoi(params->get(0).c_str());\n lastDeaths[playerID][1] = std::atoi(params->get(1).c_str());\n lastDeaths[playerID][2] = std::atoi(params->get(2).c_str());\n lastDeaths[playerID][3] = std::atoi(params->get(3).c_str());\n }\n }\n\n bztk_forcePlayerSpawn(playerID);\n handleSpawn[playerID] = true;\n\n return true;\n }\n else if (command == \"flag\")\n {\n bz_givePlayerFlag(playerID, bztk_getFlagFromTeam(pr->team), false);\n\n return false;\n }\n else if (command == \"die\")\n {\n bz_killPlayer(playerID, BZ_SERVER);\n\n return true;\n }\n\n return false;\n}\n<|endoftext|>"} {"text":"#include \"FuzzyLogic.h\"\n#include \"InputFuzzySetTriangular.h\"\n#include \"InputFuzzySetTrapezoidal.h\"\n#include \"OutputFuzzySetTriangular.h\"\n#include \"OutputFuzzySetTrapezoidal.h\"\n#include \n#include \n\nusing namespace std;\n\nSUITE(FuzzyEngine)\n{\n TEST(mbs_InputFuzzySetTriangular)\n {\n cout << \"-- InputFuzzySetTriangular mbs\" << endl;\n InputFuzzySetTriangular ifz(\"Test\", 5, 10, 15);\n ifz.setInput(2.5);\n CHECK_EQUAL(0.0, ifz.getMbs());\n ifz.setInput(7.5);\n CHECK_EQUAL(0.5, ifz.getMbs());\n ifz.setInput(12.5);\n CHECK_EQUAL(0.5, ifz.getMbs());\n ifz.setInput(15.0);\n CHECK_EQUAL(0.0, ifz.getMbs());\n ifz.setInput(17.5);\n CHECK_EQUAL(0.0, ifz.getMbs());\n cout << endl;\n }\n\n TEST(mbs_InputFuzzySetTrapezoidal)\n {\n cout << \"-- InputFuzzySetTrapezoidal mbs\" << endl;\n InputFuzzySetTrapezoidal ifz(\"Test\", 0, 5, 10, 15);\n ifz.setInput(2.5);\n CHECK_EQUAL(0.5, ifz.getMbs());\n ifz.setInput(7.5);\n CHECK_EQUAL(1.0, ifz.getMbs());\n ifz.setInput(12.5);\n CHECK_EQUAL(0.5, ifz.getMbs());\n ifz.setInput(-5);\n CHECK_EQUAL(0.0, ifz.getMbs());\n cout << endl;\n }\n\n TEST(MOMsym_OutputFuzzySetTriangular)\n {\n cout << \"-- OutputFuzzySetTriangular symmetrical MOM\" << endl;\n OutputFuzzySetTriangular ofz(\"Test\", 0, 5, 10);\n ofz.setMbs(0.5);\n CHECK_EQUAL(5.0, ofz.meanOfMaximum());\n ofz.setMbs(0.1);\n CHECK_EQUAL(5.0, ofz.meanOfMaximum());\n cout << endl;\n }\n\n TEST(MOM_OutputFuzzySetTriangular)\n {\n cout << \"-- OutputFuzzySetTriangular not symmetrical MOM\" << endl;\n OutputFuzzySetTriangular ofz(\"Test\", 0, 10, 30);\n ofz.setMbs(0.5);\n CHECK_EQUAL(25.0 \/ 2, ofz.meanOfMaximum());\n cout << endl;\n }\n\n TEST(MOMsym_OutputFuzzySetTrapezoidal)\n {\n cout << \"-- OutputFuzzySetTrapezoidal symmetrical MOM\" << endl;\n OutputFuzzySetTrapezoidal ifz(\"Test\", 0, 5, 10, 15);\n ifz.setMbs(0.5);\n CHECK_EQUAL(7.5, ifz.meanOfMaximum());\n ifz.setMbs(0.1);\n CHECK_EQUAL(7.5, ifz.meanOfMaximum());\n cout << endl;\n }\n\n TEST(MOM_OutputFuzzySetTrapezoidal)\n {\n cout << \"-- OutputFuzzySetTrapezoidal not symmetrical MOM\" << endl;\n OutputFuzzySetTrapezoidal ifz(\"Test\", 0, 10, 20, 40);\n ifz.setMbs(0.5);\n CHECK_EQUAL(35.0 \/ 2, ifz.meanOfMaximum());\n cout << endl;\n }\n\n TEST(FuzzyLogic_or)\n {\n cout << \"-- Fuzzy logic OR\" << endl;\n InputFuzzySetTriangular ifz1(\"Test\", 5, 10, 15);\n InputFuzzySetTriangular ifz2(\"Test\", 10, 15, 20);\n OutputFuzzySetTriangular ofz(\"Test\", 0, 5, 10);\n ifz1.setInput(12.5);\n ifz2.setInput(12.5);\n ofz = ifz1 or ifz2;\n CHECK_EQUAL(0.5, ofz.getMbs());\n cout << endl;\n }\n\n TEST(FuzzyLogic_and)\n {\n cout << \"-- Fuzzy logic AND\" << endl;\n InputFuzzySetTriangular ifz1(\"Test\", 5, 10, 15);\n InputFuzzySetTriangular ifz2(\"Test\", 10, 15, 20);\n OutputFuzzySetTriangular ofz(\"Test\", 0, 5, 10);\n ifz1.setInput(10);\n ifz2.setInput(10);\n ofz = ifz1 and ifz2;\n CHECK_EQUAL(0, ofz.getMbs());\n cout << endl;\n }\n\n TEST(FuzzyLogic_not)\n {\n cout << \"-- Fuzzy logic NOT\" << endl;\n InputFuzzySetTriangular ifz1(\"Test\", 5, 10, 15);\n InputFuzzySetTriangular ifz2(\"Test\", 10, 15, 20);\n OutputFuzzySetTriangular ofz(\"Test\", 0, 5, 10);\n ifz1.setInput(12.5);\n ifz2.setInput(12.5);\n ofz = not(ifz1 or ifz2);\n CHECK_EQUAL(0.5, ofz.getMbs());\n cout << endl;\n }\n\n\n}\n\nint main()\n{\n auto result = UnitTest::RunAllTests();\n cout << endl;\n return result;\n}\nMore fuzzy logic not tests.#include \"FuzzyLogic.h\"\n#include \"InputFuzzySetTriangular.h\"\n#include \"InputFuzzySetTrapezoidal.h\"\n#include \"OutputFuzzySetTriangular.h\"\n#include \"OutputFuzzySetTrapezoidal.h\"\n#include \n#include \n\nusing namespace std;\n\nSUITE(FuzzyEngine)\n{\n TEST(mbs_InputFuzzySetTriangular)\n {\n cout << \"-- InputFuzzySetTriangular mbs\" << endl;\n InputFuzzySetTriangular ifz(\"Test\", 5, 10, 15);\n\n ifz.setInput(2.5);\n CHECK_EQUAL(0.0, ifz.getMbs());\n ifz.setInput(7.5);\n CHECK_EQUAL(0.5, ifz.getMbs());\n ifz.setInput(12.5);\n CHECK_EQUAL(0.5, ifz.getMbs());\n ifz.setInput(15.0);\n CHECK_EQUAL(0.0, ifz.getMbs());\n ifz.setInput(17.5);\n CHECK_EQUAL(0.0, ifz.getMbs());\n cout << endl;\n }\n\n TEST(mbs_InputFuzzySetTrapezoidal)\n {\n cout << \"-- InputFuzzySetTrapezoidal mbs\" << endl;\n InputFuzzySetTrapezoidal ifz(\"Test\", 0, 5, 10, 15);\n\n ifz.setInput(2.5);\n CHECK_EQUAL(0.5, ifz.getMbs());\n ifz.setInput(7.5);\n CHECK_EQUAL(1.0, ifz.getMbs());\n ifz.setInput(12.5);\n CHECK_EQUAL(0.5, ifz.getMbs());\n ifz.setInput(-5);\n CHECK_EQUAL(0.0, ifz.getMbs());\n cout << endl;\n }\n\n TEST(MOMsym_OutputFuzzySetTriangular)\n {\n cout << \"-- OutputFuzzySetTriangular symmetrical MOM\" << endl;\n OutputFuzzySetTriangular ofz(\"Test\", 0, 5, 10);\n\n ofz.setMbs(0.5);\n CHECK_EQUAL(5.0, ofz.meanOfMaximum());\n ofz.setMbs(0.1);\n CHECK_EQUAL(5.0, ofz.meanOfMaximum());\n cout << endl;\n }\n\n TEST(MOM_OutputFuzzySetTriangular)\n {\n cout << \"-- OutputFuzzySetTriangular not symmetrical MOM\" << endl;\n OutputFuzzySetTriangular ofz(\"Test\", 0, 10, 30);\n\n ofz.setMbs(0.5);\n CHECK_EQUAL(25.0 \/ 2, ofz.meanOfMaximum());\n cout << endl;\n }\n\n TEST(MOMsym_OutputFuzzySetTrapezoidal)\n {\n cout << \"-- OutputFuzzySetTrapezoidal symmetrical MOM\" << endl;\n OutputFuzzySetTrapezoidal ifz(\"Test\", 0, 5, 10, 15);\n\n ifz.setMbs(0.5);\n CHECK_EQUAL(7.5, ifz.meanOfMaximum());\n ifz.setMbs(0.1);\n CHECK_EQUAL(7.5, ifz.meanOfMaximum());\n cout << endl;\n }\n\n TEST(MOM_OutputFuzzySetTrapezoidal)\n {\n cout << \"-- OutputFuzzySetTrapezoidal not symmetrical MOM\" << endl;\n OutputFuzzySetTrapezoidal ifz(\"Test\", 0, 10, 20, 40);\n\n ifz.setMbs(0.5);\n CHECK_EQUAL(35.0 \/ 2, ifz.meanOfMaximum());\n cout << endl;\n }\n\n TEST(FuzzyLogic_or)\n {\n cout << \"-- Fuzzy logic OR\" << endl;\n InputFuzzySetTriangular ifz1(\"Test\", 5, 10, 15);\n InputFuzzySetTriangular ifz2(\"Test\", 10, 15, 20);\n OutputFuzzySetTriangular ofz(\"Test\", 0, 5, 10);\n\n ifz1.setInput(12.5);\n ifz2.setInput(12.5);\n ofz = ifz1 or ifz2;\n CHECK_EQUAL(0.5, ofz.getMbs());\n cout << endl;\n }\n\n TEST(FuzzyLogic_and)\n {\n cout << \"-- Fuzzy logic AND\" << endl;\n InputFuzzySetTriangular ifz1(\"Test\", 5, 10, 15);\n InputFuzzySetTriangular ifz2(\"Test\", 10, 15, 20);\n OutputFuzzySetTriangular ofz(\"Test\", 0, 5, 10);\n\n ifz1.setInput(10);\n ifz2.setInput(10);\n ofz = ifz1 and ifz2;\n CHECK_EQUAL(0, ofz.getMbs());\n cout << endl;\n }\n\n TEST(FuzzyLogic_not)\n {\n cout << \"-- Fuzzy logic NOT\" << endl;\n InputFuzzySetTriangular ifz(\"Test\", 5, 10, 15);\n OutputFuzzySetTriangular ofz(\"Test\", 0, 5, 10);\n\n ifz.setInput(13.75);\n ofz = not ifz;\n CHECK_EQUAL(0.75, ofz.getMbs());\n\n ifz.setInput(20);\n ofz = not ifz;\n CHECK_EQUAL(1.0, ofz.getMbs());\n cout << endl;\n }\n\n}\n\nint main()\n{\n auto result = UnitTest::RunAllTests();\n cout << endl;\n return result;\n}\n<|endoftext|>"} {"text":"\/*\n * Copyright 2010, 2011 Esrille Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"U16InputStream.h\"\n\n#include \n#include \n\n#include \n\n#include \n\nconst char* U16InputStream::DefaultEncoding = \"windows-1252\";\n\nnamespace {\n\nstruct Override\n{\n const char* input;\n const char* replacement;\n};\n\nOverride overrides[] = {\n { \"euc-kr\", \"windows-949\" },\n { \"gb2312\", \"gbk\" },\n { \"gb_2312-80\", \"gbk\" },\n { \"iso-8859-1\", \"windows-1252\" },\n { \"iso-8859-9\", \"windows-1254\" },\n { \"iso-8859-11\", \"windows-874\" },\n { \"ks_c_5601-1987\", \"windows-949\" },\n { \"shift_jis\", \"windows-31j\" },\n { \"tis-620\", \"windows-874\" },\n { \"us-ascii\", \"windows-1252\" }\n};\n\n} \/\/ namespace\n\nU16InputStream::U16InputStream(std::istream& stream, const std::string optionalEncoding) :\n confidence(Certain),\n stream(stream)\n{\n initializeConverter();\n encoding = checkEncoding(optionalEncoding);\n}\n\nU16InputStream::~U16InputStream()\n{\n if (converter)\n ucnv_close(converter);\n}\n\nconst char* U16InputStream::skipSpace(const char* p)\n{\n while (*p) {\n if (strchr(\" \\t\\r\\n\\f\", *p) == 0)\n return p;\n ++p;\n }\n return p;\n};\n\n\nconst char* U16InputStream::skipOver(const char* p, const char* target, size_t length)\n{\n while (*p) {\n if (strncmp(p, target, length) == 0)\n return p + length;\n ++p;\n }\n return p;\n};\n\nvoid U16InputStream::detect(const char* p)\n{\n if (strncmp(p, \"\\xfe\\xff\", 2) == 0) {\n encoding = \"utf-16be\";\n return;\n }\n if (strncmp(p, \"\\xff\\xfe\", 2) == 0) {\n encoding = \"utf-16le\";\n return;\n }\n if (strncmp(p, \"\\xef\\xbb\\xbf\", 3) == 0) {\n encoding = \"utf-8\";\n return;\n }\n encoding = \"\";\n}\n\nstd::string U16InputStream::checkEncoding(std::string value)\n{\n \/\/ Remove any leading or trailing space characters\n std::string::iterator i = value.begin();\n while (i < value.end() && strchr(\"\\t\\n\\f\\r \", *i))\n ++i;\n value.erase(value.begin(), i);\n int j;\n for (j = value.length(); 0 < j && strchr(\"\\t\\n\\f\\r \", value[j - 1]); --j)\n ;\n value.erase(j, value.length());\n\n if (value.empty())\n return \"\";\n\n \/\/ Override character encoding\n for (Override* override = overrides;\n override < &overrides[sizeof overrides \/ sizeof overrides[0]];\n ++override) {\n if (!strcasecmp(value.c_str(), override->input)) {\n value = override->replacement;\n break;\n }\n }\n return value;\n}\n\nvoid U16InputStream::setEncoding(std::string value)\n{\n value = checkEncoding(value);\n if (value.empty())\n value = DefaultEncoding;\n\n \/\/ Re-check encoding with ICU for conversion\n UErrorCode error = U_ZERO_ERROR;\n converter = ucnv_open(value.c_str(), &error);\n if (!converter) {\n value = DefaultEncoding;\n converter = ucnv_open(value.c_str(), &error);\n if (!converter)\n eof = true;\n }\n encoding = value;\n}\n\nvoid U16InputStream::initializeConverter()\n{\n flush = false;\n eof = !stream;\n converter = 0;\n source = sourceLimit = sourceBuffer;\n target = targetBuffer;\n nextChar = target;\n lastChar = 0;\n}\n\nvoid U16InputStream::updateSource()\n{\n assert(!flush);\n size_t count = sourceLimit - source;\n if (0 < count && sourceBuffer != source)\n memmove(sourceBuffer, source, count);\n source = sourceBuffer;\n sourceLimit = sourceBuffer + count;\n count = ChunkSize - count;\n if (0 < count) {\n stream.read(sourceLimit, count);\n count = stream.gcount();\n if (!converter) {\n if (encoding.empty()) {\n sourceLimit[count] = '\\0';\n detect(sourceLimit);\n }\n setEncoding(encoding);\n }\n sourceLimit += count;\n if (count == 0)\n flush = true;\n }\n}\n\nvoid U16InputStream::readChunk()\n{\n nextChar = target = targetBuffer;\n updateSource();\n UErrorCode err = U_ZERO_ERROR;\n ucnv_toUnicode(converter,\n reinterpret_cast(&target),\n reinterpret_cast(targetBuffer) + ChunkSize,\n const_cast(&source),\n sourceLimit, 0, flush, &err);\n}\n\nU16InputStream::operator std::u16string()\n{\n std::u16string text;\n char16_t c;\n while (getChar(c))\n text += c;\n return text;\n}(overrides) : Update the list.\/*\n * Copyright 2010, 2011 Esrille Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"U16InputStream.h\"\n\n#include \n#include \n\n#include \n\n#include \n\nconst char* U16InputStream::DefaultEncoding = \"windows-1252\";\n\nnamespace {\n\nstruct Override\n{\n const char* input;\n const char* replacement;\n};\n\n\/\/ cf. HTML Living Standard 13.2.2.2 Character encodings\nOverride overrides[] = {\n { \"euc-kr\", \"windows-949\" },\n { \"euc-jp\", \"cp51932\" },\n { \"gb2312\", \"gbk\" },\n { \"gb_2312-80\", \"gbk\" },\n { \"iso-2022-jp\", \"cp50220\" },\n { \"iso-8859-1\", \"windows-1252\" },\n { \"iso-8859-9\", \"windows-1254\" },\n { \"iso-8859-11\", \"windows-874\" },\n { \"ks_c_5601-1987\", \"windows-949\" },\n { \"shift_jis\", \"windows-31j\" },\n { \"tis-620\", \"windows-874\" },\n { \"us-ascii\", \"windows-1252\" }\n};\n\n} \/\/ namespace\n\nU16InputStream::U16InputStream(std::istream& stream, const std::string optionalEncoding) :\n confidence(Certain),\n stream(stream)\n{\n initializeConverter();\n encoding = checkEncoding(optionalEncoding);\n}\n\nU16InputStream::~U16InputStream()\n{\n if (converter)\n ucnv_close(converter);\n}\n\nconst char* U16InputStream::skipSpace(const char* p)\n{\n while (*p) {\n if (strchr(\" \\t\\r\\n\\f\", *p) == 0)\n return p;\n ++p;\n }\n return p;\n};\n\n\nconst char* U16InputStream::skipOver(const char* p, const char* target, size_t length)\n{\n while (*p) {\n if (strncmp(p, target, length) == 0)\n return p + length;\n ++p;\n }\n return p;\n};\n\nvoid U16InputStream::detect(const char* p)\n{\n if (strncmp(p, \"\\xfe\\xff\", 2) == 0) {\n encoding = \"utf-16be\";\n return;\n }\n if (strncmp(p, \"\\xff\\xfe\", 2) == 0) {\n encoding = \"utf-16le\";\n return;\n }\n if (strncmp(p, \"\\xef\\xbb\\xbf\", 3) == 0) {\n encoding = \"utf-8\";\n return;\n }\n encoding = \"\";\n}\n\nstd::string U16InputStream::checkEncoding(std::string value)\n{\n \/\/ Remove any leading or trailing space characters\n std::string::iterator i = value.begin();\n while (i < value.end() && strchr(\"\\t\\n\\f\\r \", *i))\n ++i;\n value.erase(value.begin(), i);\n int j;\n for (j = value.length(); 0 < j && strchr(\"\\t\\n\\f\\r \", value[j - 1]); --j)\n ;\n value.erase(j, value.length());\n\n if (value.empty())\n return \"\";\n\n \/\/ Override character encoding\n for (Override* override = overrides;\n override < &overrides[sizeof overrides \/ sizeof overrides[0]];\n ++override) {\n if (!strcasecmp(value.c_str(), override->input)) {\n value = override->replacement;\n break;\n }\n }\n return value;\n}\n\nvoid U16InputStream::setEncoding(std::string value)\n{\n value = checkEncoding(value);\n if (value.empty())\n value = DefaultEncoding;\n\n \/\/ Re-check encoding with ICU for conversion\n UErrorCode error = U_ZERO_ERROR;\n converter = ucnv_open(value.c_str(), &error);\n if (!converter) {\n value = DefaultEncoding;\n converter = ucnv_open(value.c_str(), &error);\n if (!converter)\n eof = true;\n }\n encoding = value;\n}\n\nvoid U16InputStream::initializeConverter()\n{\n flush = false;\n eof = !stream;\n converter = 0;\n source = sourceLimit = sourceBuffer;\n target = targetBuffer;\n nextChar = target;\n lastChar = 0;\n}\n\nvoid U16InputStream::updateSource()\n{\n assert(!flush);\n size_t count = sourceLimit - source;\n if (0 < count && sourceBuffer != source)\n memmove(sourceBuffer, source, count);\n source = sourceBuffer;\n sourceLimit = sourceBuffer + count;\n count = ChunkSize - count;\n if (0 < count) {\n stream.read(sourceLimit, count);\n count = stream.gcount();\n if (!converter) {\n if (encoding.empty()) {\n sourceLimit[count] = '\\0';\n detect(sourceLimit);\n }\n setEncoding(encoding);\n }\n sourceLimit += count;\n if (count == 0)\n flush = true;\n }\n}\n\nvoid U16InputStream::readChunk()\n{\n nextChar = target = targetBuffer;\n updateSource();\n UErrorCode err = U_ZERO_ERROR;\n ucnv_toUnicode(converter,\n reinterpret_cast(&target),\n reinterpret_cast(targetBuffer) + ChunkSize,\n const_cast(&source),\n sourceLimit, 0, flush, &err);\n}\n\nU16InputStream::operator std::u16string()\n{\n std::u16string text;\n char16_t c;\n while (getChar(c))\n text += c;\n return text;\n}<|endoftext|>"} {"text":"\/\/\/\n\/\/\/ @file BitSieve.hpp\n\/\/\/ @brief The BitSieve class is a bit array for prime sieving\n\/\/\/ that packs 64 numbers into 8 bytes i.e. each bit\n\/\/\/ corresponds to one integer.\n\/\/\/\n\/\/\/ Copyright (C) 2016 Kim Walisch, \n\/\/\/\n\/\/\/ This file is distributed under the BSD License. See the COPYING\n\/\/\/ file in the top level directory.\n\/\/\/\n\n#ifndef BITSIEVE_HPP\n#define BITSIEVE_HPP\n\n#include \n#include \n#include \n#include \n\nnamespace primecount {\n\nclass BitSieve\n{\npublic:\n BitSieve(std::size_t size);\n\n \/\/\/ Pre-sieve the multiples (>= low) of the first c primes.\n \/\/\/ @param sieve_primes true to cross-off multiples,\n \/\/\/ false to cross-off multiples and primes.\n \/\/\/ @pre c < 10\n \/\/\/\n void pre_sieve(uint64_t c,\n uint64_t low,\n bool sieve_primes = false);\n\n \/\/\/ Count the number of 1 bits inside [start, stop]\n uint64_t count(uint64_t start,\n uint64_t stop) const;\n\n \/\/\/ Count the number of 1 bits inside [0, stop]\n uint64_t count(uint64_t stop) const\n {\n return count(0, stop);\n }\n\n \/\/\/ Count the number of 1 bits inside [start, stop].\n \/\/\/ As an optimization this method counts either forwards or\n \/\/\/ backwards depending on what's faster.\n \/\/\/\n uint64_t count(uint64_t start,\n uint64_t stop,\n uint64_t low,\n uint64_t high,\n uint64_t count_0_start,\n uint64_t count_low_high) const\n {\n if (start > stop)\n return 0;\n\n if (stop - start < high - low - stop)\n return count(start, stop);\n else\n \/\/ optimization, same as count(start, stop)\n return count_low_high - count_0_start - count(stop + 1, (high - 1) - low);\n }\n\n bool operator[](uint64_t pos) const\n {\n assert(pos < size_);\n return (sieve_[pos >> 6] >> (pos & 63)) & 1;\n }\n\n void set(uint64_t pos)\n {\n assert(pos < size_);\n sieve_[pos >> 6] |= ((uint64_t) 1) << (pos & 63);\n }\n\n void unset(uint64_t pos)\n {\n assert(pos < size_);\n sieve_[pos >> 6] &= unset_bit_[pos & 63];\n }\n\n std::size_t size() const\n {\n return size_;\n }\nprivate:\n static const uint64_t unset_bit_[64];\n std::vector sieve_;\n std::size_t size_;\n};\n\n} \/\/ namespace\n\n#endif\nRefactoring\/\/\/\n\/\/\/ @file BitSieve.hpp\n\/\/\/ @brief The BitSieve class is a bit array for prime sieving\n\/\/\/ that packs 64 numbers into 8 bytes i.e. each bit\n\/\/\/ corresponds to one integer.\n\/\/\/\n\/\/\/ Copyright (C) 2016 Kim Walisch, \n\/\/\/\n\/\/\/ This file is distributed under the BSD License. See the COPYING\n\/\/\/ file in the top level directory.\n\/\/\/\n\n#ifndef BITSIEVE_HPP\n#define BITSIEVE_HPP\n\n#include \n#include \n#include \n#include \n\nnamespace primecount {\n\nclass BitSieve\n{\npublic:\n BitSieve(std::size_t size);\n\n \/\/\/ Pre-sieve the multiples (>= low) of the first c primes.\n \/\/\/ @param sieve_primes true to cross-off multiples,\n \/\/\/ false to cross-off multiples and primes.\n \/\/\/ @pre c < 10\n \/\/\/\n void pre_sieve(uint64_t c,\n uint64_t low,\n bool sieve_primes = false);\n\n \/\/\/ Count the number of 1 bits inside [start, stop]\n uint64_t count(uint64_t start,\n uint64_t stop) const;\n\n \/\/\/ Count the number of 1 bits inside [0, stop]\n uint64_t count(uint64_t stop) const\n {\n return count(0, stop);\n }\n\n \/\/\/ Count the number of 1 bits inside [start, stop].\n \/\/\/ As an optimization this method counts either forwards or\n \/\/\/ backwards depending on what's faster.\n \/\/\/\n uint64_t count(uint64_t start,\n uint64_t stop,\n uint64_t low,\n uint64_t high,\n uint64_t count_0_start,\n uint64_t count_low_high) const\n {\n if (start > stop)\n return 0;\n\n if (stop - start < high - low - stop)\n return count(start, stop);\n else\n \/\/ optimization, same as count(start, stop)\n return count_low_high - count_0_start - count(stop + 1, (high - 1) - low);\n }\n\n void set(uint64_t pos)\n {\n assert(pos < size_);\n sieve_[pos >> 6] |= ((uint64_t) 1) << (pos & 63);\n }\n\n void unset(uint64_t pos)\n {\n assert(pos < size_);\n sieve_[pos >> 6] &= unset_bit_[pos & 63];\n }\n\n bool operator[](uint64_t pos) const\n {\n assert(pos < size_);\n return (sieve_[pos >> 6] >> (pos & 63)) & 1;\n }\n\n std::size_t size() const\n {\n return size_;\n }\nprivate:\n static const uint64_t unset_bit_[64];\n std::vector sieve_;\n std::size_t size_;\n};\n\n} \/\/ namespace\n\n#endif\n<|endoftext|>"} {"text":"\/\/ Copyright 2012 Alessio Sclocco \n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n\n\n#ifndef READ_DATA_HPP\n#define READ_DATA_HPP\n\nnamespace AstroData {\n\n\/\/ Exception: the PSRDada ring buffer does not work\nclass RingBufferError : public std::exception {\npublic:\n RingBufferError();\n ~RingBufferError() throw ();\n\n const char * what() const throw ();\n};\n\ntemplate< typename T > void readSIGPROC(const Observation & observation, const uint8_t inputBits, const unsigned int bytesToSkip, const std::string & inputFilename, std::vector< std::vector< T > * > & data, const unsigned int firstSecond = 0);\ntemplate< typename T > void readLOFAR(std::string headerFilename, std::string rawFilename, Observation & observation, std::vector< std::vector< T > * > & data, unsigned int nrSeconds = 0, unsigned int firstSecond = 0);\ntemplate< typename T > void readPSRDadaHeader(Observation & observation, dada_hdu_t & ringBuffer) throw(RingBufferError);\ntemplate< typename T > inline void readPSRDada(Observation & observation, dada_hdu_t & ringBuffer, std::vector< T > * data) throw(RingBufferError);\n\n\n\/\/ Implementation\n\ntemplate< typename T > void readSIGPROC(const Observation & observation, const uint8_t inputBits, const unsigned int bytesToSkip, const std::string & inputFilename, std::vector< std::vector< T > * > & data, const unsigned int firstSecond = 0) {\n\tstd::ifstream inputFile;\n\tconst unsigned int BUFFER_DIM = sizeof(T);\n\tchar * buffer = new char [BUFFER_DIM];\n\n\tinputFile.open(inputFilename.c_str(), std::ios::binary);\n\tinputFile.sync_with_stdio(false);\n\tinputFile.seekg(bytesToSkip, std::ios::beg);\n\tfor ( unsigned int second = 0; second < observation.getNrSeconds(); second++ ) {\n if ( inputBits >= 8 ) {\n data.at(second) = new std::vector< T >(observation.getNrChannels() * observation.getNrSamplesPerPaddedSecond());\n for ( unsigned int sample = 0; sample < observation.getNrSamplesPerSecond(); sample++ ) {\n for ( unsigned int channel = observation.getNrChannels(); channel > 0; channel-- ) {\n inputFile.read(buffer, BUFFER_DIM);\n data.at(second)->at((static_cast< uint64_t >(channel - 1) * observation.getNrSamplesPerPaddedSecond()) + sample) = *(reinterpret_cast< T * >(buffer));\n }\n }\n } else {\n data.at(second) = new std::vector< T >(observation.getNrChannels() * isa::utils::pad(observation.getNrSamplesPerSecond() \/ (8 \/ inputBits), observation.getPadding()));\n for ( unsigned int sample = 0; sample < observation.getNrSamplesPerSecond(); sample++ ) {\n unsigned int sampleByte = sample \/ (8 \/ inputBits);\n uint8_t sampleFirstBit = (sample % (8 \/ inputBits)) * inputBits;\n\n for ( int channel = observation.getNrChannels(); channel > 0; channel -= (8 \/ inputBits) ) {\n inputFile.read(buffer, BUFFER_DIM);\n for ( unsigned int item = 0; item < (8 \/ inputBits); item++ ) {\n uint8_t channelFirstBit = item * inputBits;\n uint8_t sampleBuffer = 0;\n\n if ( (channel - 1) - item >= observation.getNrChannels() ) {\n break;\n }\n sampleBuffer = data.at(second)->at((static_cast< uint64_t >((channel - 1) - item) * isa::utils::pad(observation.getNrSamplesPerSecond() \/ (8 \/ inputBits), observation.getPadding())) + sampleByte);\n for ( uint8_t bit = 0; bit < inputBits; bit++ ) {\n isa::utils::setBit(sampleBuffer, isa::utils::getBit(*buffer, channelFirstBit + bit), sampleFirstBit + bit);\n }\n data.at(second)->at((static_cast< uint64_t >((channel - 1) - item) * isa::utils::pad(observation.getNrSamplesPerSecond() \/ (8 \/ inputBits), observation.getPadding())) + sampleByte) = sampleBuffer;\n }\n }\n }\n }\n\t}\n\tinputFile.close();\n\n\tdelete [] buffer;\n}\n\n\ntemplate< typename T > void readLOFAR(std::string headerFilename, std::string rawFilename, Observation & observation, std::vector< std::vector< T > * > & data, unsigned int nrSeconds, unsigned int firstSecond) {\n unsigned int nrSubbands, nrChannels;\n float minFreq, channelBandwidth;\n\t\/\/ Read the HDF5 file with the metadata\n\tH5::H5File headerFile = H5::H5File(headerFilename, H5F_ACC_RDONLY);\n\tH5::FloatType typeDouble = H5::FloatType(H5::PredType::NATIVE_DOUBLE);\n\tdouble valueDouble = 0.0;\n\tH5::IntType typeUInt = H5::IntType(H5::PredType::NATIVE_UINT);\n\tunsigned int valueUInt = 0;\n\n\tH5::Group currentNode = headerFile.openGroup(\"\/\");\n\tcurrentNode.openAttribute(\"OBSERVATION_FREQUENCY_MIN\").read(typeDouble, reinterpret_cast< void * >(&valueDouble));\n minFreq = valueDouble;\n\tcurrentNode = currentNode.openGroup(currentNode.getObjnameByIdx(0));\n\tcurrentNode.openAttribute(\"TOTAL_INTEGRATION_TIME\").read(typeDouble, reinterpret_cast< void * >(&valueDouble));\n\tdouble totalIntegrationTime = valueDouble;\n\tcurrentNode.openAttribute(\"NOF_BEAMS\").read(typeUInt, reinterpret_cast< void * >(&valueUInt));\n\tobservation.setNrBeams(valueUInt);\n\tcurrentNode = currentNode.openGroup(currentNode.getObjnameByIdx(0));\n\tcurrentNode.openAttribute(\"NOF_SAMPLES\").read(typeUInt, reinterpret_cast< void * >(&valueUInt));\n\tunsigned int totalSamples = valueUInt;\n\tcurrentNode.openAttribute(\"NOF_STATIONS\").read(typeUInt, reinterpret_cast< void * >(&valueUInt));\n\tobservation.setNrStations(valueUInt);\n\tcurrentNode.openAttribute(\"CHANNELS_PER_SUBBAND\").read(typeUInt, reinterpret_cast< void * >(&valueUInt));\n\tnrChannels = valueUInt;\n\tcurrentNode.openAttribute(\"CHANNEL_WIDTH\").read(typeDouble, reinterpret_cast< void * >(&valueDouble));\n channelBandwidth = valueDouble \/ 1000000;\n\tH5::DataSet currentData = currentNode.openDataSet(\"STOKES_0\");\n\tcurrentData.openAttribute(\"NOF_SUBBANDS\").read(typeUInt, reinterpret_cast< void * >(&valueUInt));\n\tnrSubbands = valueUInt;\n\theaderFile.close();\n\n\tobservation.setNrSamplesPerSecond(static_cast< unsigned int >(totalSamples \/ totalIntegrationTime));\n\tif ( nrSeconds == 0 ) {\n\t\tobservation.setNrSeconds(static_cast< unsigned int >(totalIntegrationTime));\n\t} else {\n\t\tif ( static_cast< unsigned int >(totalIntegrationTime) >= (firstSecond + nrSeconds) ) {\n\t\t\tobservation.setNrSeconds(nrSeconds);\n\t\t} else {\n\t\t\tobservation.setNrSeconds(static_cast< unsigned int >(totalIntegrationTime) - firstSecond);\n\t\t}\n\t}\n observation.setFrequencyRange(nrSubbands * nrChannels, minFreq, channelBandwidth);\n\n\t\/\/ Read the raw file with the actual data\n\tstd::ifstream rawFile;\n\trawFile.open(rawFilename.c_str(), std::ios::binary);\n\trawFile.sync_with_stdio(false);\n\tif ( firstSecond > 0 ) {\n\t\trawFile.seekg(firstSecond * observation.getNrSamplesPerSecond() * nrSubbands * nrChannels, std::ios::beg);\n\t}\n\tdata.resize(observation.getNrSeconds());\n\n\tchar * word = new char [4];\n\tfor ( unsigned int second = 0; second < observation.getNrSeconds(); second++ ) {\n\t\tdata.at(second) = new std::vector< T >(observation.getNrChannels() * observation.getNrSamplesPerPaddedSecond());\n\t\tfor ( unsigned int sample = 0; sample < observation.getNrSamplesPerSecond(); sample++ ) {\n\t\t\tfor ( unsigned int subband = 0; subband < nrSubbands; subband++ ) {\n\t\t\t\tfor ( unsigned int channel = 0; channel < nrChannels; channel++ ) {\n unsigned int globalChannel = (subband * nrChannels) + channel;\n\n\t\t\t\t\trawFile.read(word, 4);\n isa::utils::bigEndianToLittleEndian(word);\n data.at(second)->at((globalChannel * observation.getNrSamplesPerPaddedSecond()) + sample) = *(reinterpret_cast< T * >(word));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\trawFile.close();\n\tdelete [] word;\n}\n\ntemplate< typename T > void readPSRDadaHeader(Observation & observation, dada_hdu_t & ringBuffer) throw(RingBufferError) {\n \/\/ Staging variables for the header elements\n unsigned int uintValue = 0;\n float floatValue[2] = {0.0f, 0.0f};\n \/\/ Header string\n uint64_t headerBytes = 0;\n char * header = 0;\n\n header = ipcbuf_get_next_read(ringBuffer.header_block, &headerBytes);\n\n if ( (header == 0) || (headerBytes == 0 ) ) {\n throw RingBufferError();\n }\n\n ascii_header_get(header, \"SAMPLES_PER_SECOND\", \"%d\", &uintValue);\n observation.setNrSamplesPerSecond(uintValue);\n ascii_header_get(header, \"CHANNELS\", \"%d\", &uintValue);\n ascii_header_get(header, \"MIN_FREQUENCY\", \"%f\", &floatValue[0]);\n ascii_header_get(header, \"CHANNEL_BANDWIDTH\", \"%f\", &floatValue[1]);\n observation.setFrequencyRange(uintValue, floatValue[0], floatValue[1]);\n ipcbuf_mark_cleared(ringBuffer.header_block);\n\n delete header;\n}\n\ntemplate< typename T > inline void readPSRDada(Observation & observation, dada_hdu_t & ringBuffer, std::vector< T > * data) throw(RingBufferError) {\n if ( (ipcio_read(ringBuffer.data_block, reinterpret_cast< char * >(data->data()), observation.getNrChannels() * observation.getNrSamplesPerPaddedSecond() * sizeof(T))) < 0 ) {\n throw RingBufferError();\n }\n}\n\n} \/\/ AstroData\n\n#endif \/\/ READ_DATA_HPP\n\nFixing a bug in the SIGPROC reader when samples < 8 bits.\/\/ Copyright 2012 Alessio Sclocco \n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n\n\n#ifndef READ_DATA_HPP\n#define READ_DATA_HPP\n\nnamespace AstroData {\n\n\/\/ Exception: the PSRDada ring buffer does not work\nclass RingBufferError : public std::exception {\npublic:\n RingBufferError();\n ~RingBufferError() throw ();\n\n const char * what() const throw ();\n};\n\ntemplate< typename T > void readSIGPROC(const Observation & observation, const uint8_t inputBits, const unsigned int bytesToSkip, const std::string & inputFilename, std::vector< std::vector< T > * > & data, const unsigned int firstSecond = 0);\ntemplate< typename T > void readLOFAR(std::string headerFilename, std::string rawFilename, Observation & observation, std::vector< std::vector< T > * > & data, unsigned int nrSeconds = 0, unsigned int firstSecond = 0);\ntemplate< typename T > void readPSRDadaHeader(Observation & observation, dada_hdu_t & ringBuffer) throw(RingBufferError);\ntemplate< typename T > inline void readPSRDada(Observation & observation, dada_hdu_t & ringBuffer, std::vector< T > * data) throw(RingBufferError);\n\n\n\/\/ Implementation\n\ntemplate< typename T > void readSIGPROC(const Observation & observation, const uint8_t inputBits, const unsigned int bytesToSkip, const std::string & inputFilename, std::vector< std::vector< T > * > & data, const unsigned int firstSecond = 0) {\n\tstd::ifstream inputFile;\n\tconst unsigned int BUFFER_DIM = sizeof(T);\n\tchar * buffer = new char [BUFFER_DIM];\n\n\tinputFile.open(inputFilename.c_str(), std::ios::binary);\n\tinputFile.sync_with_stdio(false);\n\tinputFile.seekg(bytesToSkip, std::ios::beg);\n\tfor ( unsigned int second = 0; second < observation.getNrSeconds(); second++ ) {\n if ( inputBits >= 8 ) {\n data.at(second) = new std::vector< T >(observation.getNrChannels() * observation.getNrSamplesPerPaddedSecond());\n for ( unsigned int sample = 0; sample < observation.getNrSamplesPerSecond(); sample++ ) {\n for ( unsigned int channel = observation.getNrChannels(); channel > 0; channel-- ) {\n inputFile.read(buffer, BUFFER_DIM);\n data.at(second)->at((static_cast< uint64_t >(channel - 1) * observation.getNrSamplesPerPaddedSecond()) + sample) = *(reinterpret_cast< T * >(buffer));\n }\n }\n } else {\n uint64_t bytesToRead = static_cast< uint64_t >(observation.getNrSamplesPerSecond() * std::ceil(observation.getNrChannels() \/ (8.0 \/ inputBits)));\n\n data.at(second) = new std::vector< T >(observation.getNrChannels() * isa::utils::pad(observation.getNrSamplesPerSecond() \/ (8 \/ inputBits), observation.getPadding()));\n for ( uint64_t byte = 0; byte < bytesToRead; byte++ ) {\n unsigned int channel = (observation.getNrChannels() - 1) - ((byte * (8 \/ iputBits)) % observation.getNrChannels());\n unsigned int sample = (byte * (8 \/ iputBits)) \/ observation.getNrChannels();\n unsigned int sampleByte = sample \/ (8 \/ inputBits);\n uint8_t sampleFirstBit = (sample % (8 \/ inputBits)) * inputBits;\n\n inputFile.read(buffer, BUFFER_DIM);\n for ( unsigned int item = 0; item < 8 \/ inputBits; item++ ) {\n uint8_t channelFirstBit = item * inputBits;\n uint8_t sampleBuffer = 0;\n\n if ( item > channel ) {\n \/\/ All channels read, the remaining elements are from the next sample\n channel = (observation.getNrChannels() - 1);\n sample += 1;\n sampleByte = sample \/ (8 \/ inputBits);\n sampleFirstBit = (sample % (8 \/ inputBits)) * inputBits;\n\n while ( item < (8 \/ inputBits) ) {\n channelFirstBit = item * inputBits;\n sampleBuffer = data.at(second)->at((static_cast< uint64_t >(channel - item) * isa::utils::pad(observation.getNrSamplesPerSecond() \/ (8 \/ inputBits), observation.getPadding())) + sampleByte);\n for ( uint8_t bit = 0; bit < inputBits; bit++ ) {\n isa::utils::setBit(sampleBuffer, isa::utils::getBit(*buffer, channelFirstBit + bit), sampleFirstBit + bit);\n }\n data.at(second)->at((static_cast< uint64_t >(channel - item) * isa::utils::pad(observation.getNrSamplesPerSecond() \/ (8 \/ inputBits), observation.getPadding())) + sampleByte) = sampleBuffer;\n item++;\n }\n\n break;\n }\n sampleBuffer = data.at(second)->at((static_cast< uint64_t >(channel - item) * isa::utils::pad(observation.getNrSamplesPerSecond() \/ (8 \/ inputBits), observation.getPadding())) + sampleByte);\n for ( uint8_t bit = 0; bit < inputBits; bit++ ) {\n isa::utils::setBit(sampleBuffer, isa::utils::getBit(*buffer, channelFirstBit + bit), sampleFirstBit + bit);\n }\n data.at(second)->at((static_cast< uint64_t >(channel - item) * isa::utils::pad(observation.getNrSamplesPerSecond() \/ (8 \/ inputBits), observation.getPadding())) + sampleByte) = sampleBuffer;\n }\n }\n }\n\t}\n\tinputFile.close();\n\n\tdelete [] buffer;\n}\n\n\ntemplate< typename T > void readLOFAR(std::string headerFilename, std::string rawFilename, Observation & observation, std::vector< std::vector< T > * > & data, unsigned int nrSeconds, unsigned int firstSecond) {\n unsigned int nrSubbands, nrChannels;\n float minFreq, channelBandwidth;\n\t\/\/ Read the HDF5 file with the metadata\n\tH5::H5File headerFile = H5::H5File(headerFilename, H5F_ACC_RDONLY);\n\tH5::FloatType typeDouble = H5::FloatType(H5::PredType::NATIVE_DOUBLE);\n\tdouble valueDouble = 0.0;\n\tH5::IntType typeUInt = H5::IntType(H5::PredType::NATIVE_UINT);\n\tunsigned int valueUInt = 0;\n\n\tH5::Group currentNode = headerFile.openGroup(\"\/\");\n\tcurrentNode.openAttribute(\"OBSERVATION_FREQUENCY_MIN\").read(typeDouble, reinterpret_cast< void * >(&valueDouble));\n minFreq = valueDouble;\n\tcurrentNode = currentNode.openGroup(currentNode.getObjnameByIdx(0));\n\tcurrentNode.openAttribute(\"TOTAL_INTEGRATION_TIME\").read(typeDouble, reinterpret_cast< void * >(&valueDouble));\n\tdouble totalIntegrationTime = valueDouble;\n\tcurrentNode.openAttribute(\"NOF_BEAMS\").read(typeUInt, reinterpret_cast< void * >(&valueUInt));\n\tobservation.setNrBeams(valueUInt);\n\tcurrentNode = currentNode.openGroup(currentNode.getObjnameByIdx(0));\n\tcurrentNode.openAttribute(\"NOF_SAMPLES\").read(typeUInt, reinterpret_cast< void * >(&valueUInt));\n\tunsigned int totalSamples = valueUInt;\n\tcurrentNode.openAttribute(\"NOF_STATIONS\").read(typeUInt, reinterpret_cast< void * >(&valueUInt));\n\tobservation.setNrStations(valueUInt);\n\tcurrentNode.openAttribute(\"CHANNELS_PER_SUBBAND\").read(typeUInt, reinterpret_cast< void * >(&valueUInt));\n\tnrChannels = valueUInt;\n\tcurrentNode.openAttribute(\"CHANNEL_WIDTH\").read(typeDouble, reinterpret_cast< void * >(&valueDouble));\n channelBandwidth = valueDouble \/ 1000000;\n\tH5::DataSet currentData = currentNode.openDataSet(\"STOKES_0\");\n\tcurrentData.openAttribute(\"NOF_SUBBANDS\").read(typeUInt, reinterpret_cast< void * >(&valueUInt));\n\tnrSubbands = valueUInt;\n\theaderFile.close();\n\n\tobservation.setNrSamplesPerSecond(static_cast< unsigned int >(totalSamples \/ totalIntegrationTime));\n\tif ( nrSeconds == 0 ) {\n\t\tobservation.setNrSeconds(static_cast< unsigned int >(totalIntegrationTime));\n\t} else {\n\t\tif ( static_cast< unsigned int >(totalIntegrationTime) >= (firstSecond + nrSeconds) ) {\n\t\t\tobservation.setNrSeconds(nrSeconds);\n\t\t} else {\n\t\t\tobservation.setNrSeconds(static_cast< unsigned int >(totalIntegrationTime) - firstSecond);\n\t\t}\n\t}\n observation.setFrequencyRange(nrSubbands * nrChannels, minFreq, channelBandwidth);\n\n\t\/\/ Read the raw file with the actual data\n\tstd::ifstream rawFile;\n\trawFile.open(rawFilename.c_str(), std::ios::binary);\n\trawFile.sync_with_stdio(false);\n\tif ( firstSecond > 0 ) {\n\t\trawFile.seekg(firstSecond * observation.getNrSamplesPerSecond() * nrSubbands * nrChannels, std::ios::beg);\n\t}\n\tdata.resize(observation.getNrSeconds());\n\n\tchar * word = new char [4];\n\tfor ( unsigned int second = 0; second < observation.getNrSeconds(); second++ ) {\n\t\tdata.at(second) = new std::vector< T >(observation.getNrChannels() * observation.getNrSamplesPerPaddedSecond());\n\t\tfor ( unsigned int sample = 0; sample < observation.getNrSamplesPerSecond(); sample++ ) {\n\t\t\tfor ( unsigned int subband = 0; subband < nrSubbands; subband++ ) {\n\t\t\t\tfor ( unsigned int channel = 0; channel < nrChannels; channel++ ) {\n unsigned int globalChannel = (subband * nrChannels) + channel;\n\n\t\t\t\t\trawFile.read(word, 4);\n isa::utils::bigEndianToLittleEndian(word);\n data.at(second)->at((globalChannel * observation.getNrSamplesPerPaddedSecond()) + sample) = *(reinterpret_cast< T * >(word));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\trawFile.close();\n\tdelete [] word;\n}\n\ntemplate< typename T > void readPSRDadaHeader(Observation & observation, dada_hdu_t & ringBuffer) throw(RingBufferError) {\n \/\/ Staging variables for the header elements\n unsigned int uintValue = 0;\n float floatValue[2] = {0.0f, 0.0f};\n \/\/ Header string\n uint64_t headerBytes = 0;\n char * header = 0;\n\n header = ipcbuf_get_next_read(ringBuffer.header_block, &headerBytes);\n\n if ( (header == 0) || (headerBytes == 0 ) ) {\n throw RingBufferError();\n }\n\n ascii_header_get(header, \"SAMPLES_PER_SECOND\", \"%d\", &uintValue);\n observation.setNrSamplesPerSecond(uintValue);\n ascii_header_get(header, \"CHANNELS\", \"%d\", &uintValue);\n ascii_header_get(header, \"MIN_FREQUENCY\", \"%f\", &floatValue[0]);\n ascii_header_get(header, \"CHANNEL_BANDWIDTH\", \"%f\", &floatValue[1]);\n observation.setFrequencyRange(uintValue, floatValue[0], floatValue[1]);\n ipcbuf_mark_cleared(ringBuffer.header_block);\n\n delete header;\n}\n\ntemplate< typename T > inline void readPSRDada(Observation & observation, dada_hdu_t & ringBuffer, std::vector< T > * data) throw(RingBufferError) {\n if ( (ipcio_read(ringBuffer.data_block, reinterpret_cast< char * >(data->data()), observation.getNrChannels() * observation.getNrSamplesPerPaddedSecond() * sizeof(T))) < 0 ) {\n throw RingBufferError();\n }\n}\n\n} \/\/ AstroData\n\n#endif \/\/ READ_DATA_HPP\n\n<|endoftext|>"} {"text":"\/* -*- coding: utf-8; mode: c++; tab-width: 3 -*-\n\nCopyright 2010, 2011, 2012, 2013\nRaffaello D. Di Napoli\n\nThis file is part of Application-Building Components (henceforth referred to as ABC).\n\nABC is free software: you can redistribute it and\/or modify it under the terms of the GNU General\nPublic License as published by the Free Software Foundation, either version 3 of the License, or (at\nyour option) any later version.\n\nABC is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the\nimplied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public\nLicense for more details.\n\nYou should have received a copy of the GNU General Public License along with ABC. If not, see\n.\n--------------------------------------------------------------------------------------------------*\/\n\n#ifndef ABC_CORE_HXX\n#define ABC_CORE_HXX\n\n\n#include \/\/ CHAR_BIT *_MAX *_MIN\n#include \/\/ *int*_t __WORDSIZE (if supported)\n#include \/\/ size_t\n\n#if defined(__GNUC__)\n\t\/\/ Make version checks for GCC less cumbersome.\n\t#define _GCC_VER \\\n\t\t(__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__)\n\t#if _GCC_VER < 40300\n\t\t#error Unsupported version of GCC (>= 4.3.0 required)\n\t#endif\n#elif defined(_MSC_VER)\n\t#if _MSC_VER < 1600\n\t\t#error Unsupported version of MSC (>= MSC 16 \/ VC++ 10 \/ VS 2010 required)\n\t#endif\n#endif\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ abc globals - HOST_* and OUTPUT_*\n\n#define ABC_HOST_API_WIN32 0\n#define ABC_HOST_API_WIN64 0\n#define ABC_HOST_API_LINUX 0\n#define ABC_HOST_API_POSIX 0\n#define ABC_OUTPUT_WIN32_DLL 0\n#define ABC_OUTPUT_WIN32_EXE 0\n#define ABC_OUTPUT_POSIX_EXE 0\n\n#if defined(_WIN32)\n\t\/\/ Compiling for Win32.\n\t#undef ABC_HOST_API_WIN32\n\t#define ABC_HOST_API_WIN32 1\n\t#ifdef _WIN64\n\t\t\/\/ Compiling for Win64 (coexists with ABC_HOST_API_WIN32).\n\t\t#undef ABC_HOST_API_WIN64\n\t\t#define ABC_HOST_API_WIN64 1\n\t#endif\n\t#ifdef _WINDLL\n\t\t#undef ABC_OUTPUT_WIN32_DLL\n\t\t#define ABC_OUTPUT_WIN32_DLL 1\n\t#else\n\t\t#undef ABC_OUTPUT_WIN32_EXE\n\t\t#define ABC_OUTPUT_WIN32_EXE 1\n\t#endif\n#elif defined(__linux__)\n\t\/\/ Compiling for Linux.\n\t#undef ABC_HOST_API_LINUX\n\t#define ABC_HOST_API_LINUX 1\n\t#undef ABC_HOST_API_POSIX\n\t#define ABC_HOST_API_POSIX 1\n\t#undef ABC_OUTPUT_POSIX_EXE\n\t#define ABC_OUTPUT_POSIX_EXE 1\n#elif defined(__posix__)\n\t\/\/ Compiling for POSIX.\n\t#undef ABC_HOST_API_POSIX\n\t#define ABC_HOST_API_POSIX 1\n\t#undef ABC_OUTPUT_POSIX_EXE\n\t#define ABC_OUTPUT_POSIX_EXE 1\n#endif\n\n\n\/** Machine word size for this microarchitecture. *\/\n#if ABC_HOST_API_WIN32\n\t#ifdef _WIN64\n\t\t#define ABC_HOST_WORD_SIZE 64\n\t#else\n\t\t#define ABC_HOST_WORD_SIZE 32\n\t#endif\n#elif defined(__WORDSIZE)\n\t#define ABC_HOST_WORD_SIZE __WORDSIZE\n#else\n\t#error Unable to determine the word size for this microarchitecture\n#endif\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ abc globals - platform-dependent fixes\n\n#if ABC_HOST_API_POSIX\n\n\t\/\/ This prevents stat() from failing for files bigger than 2 GiB.\n\t#define _FILE_OFFSET_BITS 64\n\n#elif ABC_HOST_API_WIN32\n\n\t\/\/ Make sure WINVER is defined.\n\t#ifndef WINVER\n\t\t\/\/ Pick a default Windows version.\n\t\t#ifdef _WIN64\n\t\t\t\/\/ The earliest Win64 implementations are Windows Server 2003 (5.2) and Windows XP x64\n\t\t\t\/\/ Edition (5.2).\n\t\t\t#define WINVER 0x0502\n\t\t#else\n\t\t\t\/\/ The earliest Win32 implementations are Windows 95 (4.0) and Windows NT 4 (4.0).\n\t\t\t#define WINVER 0x0400\n\t\t#endif\n\t#endif\n\n\t\/\/ Make sure _WIN32_WINNT is defined for WINVER values representing NT-only Windows versions.\n\t\/\/ The first NT-only version of Windows is 5.0 (Windows 2000; Windows Me is 4.9).\n\t#if !defined(_WIN32_WINNT) && WINVER >= 0x0500\n\t\t#define _WIN32_WINNT WINVER\n\t#endif\n\n\t\/\/ Make sure UNICODE and _UNICODE are coherent; UNICODE wins.\n\t#if defined(UNICODE) && !defined(_UNICODE)\n\t\t#define _UNICODE\n\t#elif !defined(UNICODE) && defined(_UNICODE)\n\t\t#undef _UNICODE\n\t#endif\n\n\t#define WIN32_LEAN_AND_MEAN\n\t#include \n#endif\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ abc globals - C++11 compiler support\n\n\/** If defined, the compiler supports defining conversion operators as explicit, to avoid executing\nthem implicitly (N2437). *\/\n#if defined(_GCC_VER) && _GCC_VER >= 40500\n\t#define ABC_CXX_EXPLICIT_CONVERSION_OPERATORS\n#endif\n\n\/** If defined, the compiler allows to delete a specific (overload of a) function, method or\nconstructor (N2346). *\/\n#if defined(_GCC_VER) && _GCC_VER >= 40400\n\t#define ABC_CXX_FUNCTION_DELETE\n#endif\n\n\/** If defined, the compiler supports template friend declarations (N1791). *\/\n#if (defined(_GCC_VER) && _GCC_VER >= 40500) || defined(_MSC_VER)\n\t#define ABC_CXX_TEMPLATE_FRIENDS\n#endif\n\n\/** If defined, the compiler supports variadic templates (N2242). *\/\n#if defined(_GCC_VER)\n\t#define ABC_CXX_VARIADIC_TEMPLATES\n#endif\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ abc globals - non-standard, but commonly available, extensions\n\n\/** If defined, the compiler supports #pragma once, which tells the preprocessor not to parsing a\n(header) file more than once, speeding up compilation. *\/\n#if defined(_MSC_VER)\n\t#define ABC_CXX_PRAGMA_ONCE\n\n\t\/\/ Use it now for this file.\n\t#pragma once\n#endif\n\n\/** Defines a function as never returning (e.g. by causing the process to terminate, or by throwing\nan exception). This allows optimizations based on the fact that code following its call cannot be\nreached. *\/\n#if defined(_GCC_VER)\n\t#define ABC_FUNC_NORETURN \\\n\t\t__attribute__((noreturn))\n#elif defined(_MSC_VER)\n\t#define ABC_FUNC_NORETURN \\\n\t\t__declspec(noreturn)\n#else\n\t#define ABC_FUNC_NORETURN\n#endif\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ abc globals - extended features that can take advantage of C++11 or fallback to more risky, but\n\/\/ still functional alternatives\n\n\/** Makes the class un-copiable. Move constructors and\/or assignment operators may be still\navailable, though.\n\nTODO: comment signature.\n*\/\n#ifdef ABC_CXX_FUNCTION_DELETE\n\t#define ABC_CLASS_PREVENT_COPYING(cls) \\\n\t\tpublic: \\\n\t\t\\\n\t\t\tcls(cls const &) = delete; \\\n\t\t\t\\\n\t\t\tcls & operator=(cls const &) = delete;\n#else\n\t#define ABC_CLASS_PREVENT_COPYING(cls) \\\n\t\tprivate: \\\n\t\t\\\n\t\t\tcls(cls const &) { \\\n\t\t\t\tclass_ ## cls ## _cannot_be_copied(); \\\n\t\t\t} \\\n\t\t\t\\\n\t\t\tcls & operator=(cls const &) { \\\n\t\t\t\tclass_ ## cls ## _cannot_be_copied(); \\\n\t\t\t}\n#endif\n\n\nnamespace abc {\n\n\/** Declares an explicit conversion operator to bool.\n*\/\n#ifdef ABC_CXX_EXPLICIT_CONVERSION_OPERATORS\n\n\t#define explicit_operator_bool \\\n\t\texplicit operator bool\n\n\n\t\/** A class derived from this one receives support for C++11 explicit operator bool even on\n\tnon-compliant compilers.\n\t*\/\n\ttemplate \n\tstruct support_explicit_operator_bool {};\n\n#else \/\/ifdef ABC_CXX_EXPLICIT_CONVERSION_OPERATORS\n\n\t#define explicit_operator_bool \\\n\t\tbool _explicit_operator_bool\n\n\n\t\/** Non-template helper for support_explicit_operator_bool.\n\t*\/\n\tstruct _explob_helper {\n\n\t\t\/** Non-bool boolean type. *\/\n\t\ttypedef void (_explob_helper::* bool_type)() const;\n\n\n\t\t\/** A pointer to this method is used as a boolean true by support_explicit_operator_bool.\n\t\t*\/\n\t\tvoid bool_true() const;\n\t};\n\n\n\n\t\/** A class derived from this one receives support for C++11 explicit operator bool even on\n\tnon-compliant compilers.\n\t*\/\n\ttemplate \n\tstruct support_explicit_operator_bool {\n\n\t\t\/** Non-bool boolean conversion operator, safer than operator bool(), and almost as good as\n\t\texplicit operator bool().\n\n\t\tTODO: comment signature.\n\t\t*\/\n\t\toperator _explob_helper::bool_type() const {\n\t\t\tif (static_cast(this)->_explicit_operator_bool()) {\n\t\t\t\treturn &_explob_helper::bool_true;\n\t\t\t} else {\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t}\n\t};\n\n\n\t\/\/ Disable relational operators for support_explicit_operator_bool.\n\n\t#ifdef ABC_CXX_FUNCTION_DELETE\n\n\t\t#define ABC_RELOP_IMPL(op) \\\n\t\t\ttemplate \\\n\t\t\tbool operator op( \\\n\t\t\t\tsupport_explicit_operator_bool const &, support_explicit_operator_bool const & \\\n\t\t\t) = delete;\n\n\t#else \/\/ifdef ABC_CXX_FUNCTION_DELETE\n\n\t\t#define ABC_RELOP_IMPL(op) \\\n\t\t\ttemplate \\\n\t\t\tinline bool operator op( \\\n\t\t\t\tsupport_explicit_operator_bool const & lhs, \\\n\t\t\t\tsupport_explicit_operator_bool const & rhs \\\n\t\t\t) { \\\n\t\t\t\tcannot_compare_to(lhs, rhs); \\\n\t\t\t\treturn false; \\\n\t\t\t}\n\n\t#endif \/\/ifdef ABC_CXX_FUNCTION_DELETE … else\n\n\tABC_RELOP_IMPL(==)\n\tABC_RELOP_IMPL(!=)\n\t#undef ABC_RELOP_IMPL\n\n#endif \/\/ifdef ABC_CXX_EXPLICIT_CONVERSION_OPERATORS … else\n\n} \/\/namespace abc\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ abc globals - other\n\nnamespace std {\n\n\/** Type whose alignment requirement is at least as large as that of every scalar type (see C++11 §\n18.2 “”).\n*\/\nunion max_align_t {\n\tdouble d;\n\tlong double ld;\n\tlong long ll;\n};\n\n} \/\/namespace std\n\n\n\/\/ Support loose exception specifications.\n#if defined(_GCC_VER) && _GCC_VER >= 40600\n\t#define noexcept_false \\\n\t\tnoexcept(false)\n\t#define noexcept_true \\\n\t\tnoexcept(true)\n\t#define noexcept_if(cond) \\\n\t\tnoexcept(cond)\n#else\n\t#define noexcept_false\n\t#define noexcept_true \\\n\t\tthrow()\n\t#define noexcept_if(cond)\n#endif\n\n\/\/ Support for pre-C++11 declarations. Use double parentheses for the list.\n#define decl_throw(list) \\\n\tthrow list\n\n\n\/** Avoids compiler warnings about purposely unused parameters. Win32 has UNREFERENCED_PARAMETER for\nthis purpose, but this is noticeably shorter :)\n\nTODO: comment signature.\n*\/\n#define UNUSED_ARG(x) \\\n\tstatic_cast(x)\n\n\n\/** Tells the compiler that a switch statement that apparently doesn’t test for all possible cases\nfor its argument (e.g. skips some values of an enum), does cover 100% of the actually possible\ncases.\n\nIt can avoid warnings about not testing for all possible values for an enum, or cases where a\nvariable would seem to be left uninitialized if the switch argument has a value that’s not one of\nthose expected by the case labels.\n*\/\n#if defined(_MSC_VER)\n\t#define no_default \\\n\t\tdefault: \\\n\t\t\t__assume(0)\n#else\n\t#define no_default \\\n\t\tdefault: \\\n\t\t\tbreak\n#endif\n\n\n\/** Returns the number of items in a (static) array.\n\nTODO: comment signature.\n*\/\n#undef countof\n#define countof(array) \\\n\t(sizeof(array) \/ sizeof((array)[0]))\n\n\n\/** Returns the offset, in bytes, of a struct\/class member. It doesn’t trigger warnings, since it\ndoesn’t use NULL as the fake address.\n\nTODO: comment signature.\n*\/\n#undef offsetof\n#define offsetof(type, member) \\\n\t(reinterpret_cast(&reinterpret_cast(1024)->member) - 1024)\n\n\n\/** Returns the compiler-computed alignment for the specified data type. When compiler support is\nlacking, this can be inaccurate for long double.\n\nTODO: comment signature.\n*\/\n#undef alignof\n#if defined(_GCC_VER)\n\t#define alignof(type) \\\n\t\t__alignof__(type)\n#elif defined(_MSC_VER)\n\t#define alignof(type) \\\n\t\t__alignof(type)\n#else\n\t#define alignof(type) \\\n\t\toffsetof(abc::_alignof_helper, t)\n\n\tnamespace abc {\n\n\ttemplate \n\tstruct _alignof_helper {\n\t\tint8_t misaligner;\n\t\tT t;\n\t};\n\n\t} \/\/namespace abc\n#endif\n\n\n\/** Returns a size rounded (ceiling) to a count of std::max_align_t units. This allows to declare\nstorage with alignment suitable for any type, just like ::malloc() does. Identical to\nbitmanip::ceiling_to_pow2_multiple(cb, sizeof(std::max_align_t)).\n\nTODO: comment signature.\n*\/\n#define ABC_ALIGNED_SIZE(cb) \\\n\t((size_t(cb) + sizeof(std::max_align_t) - 1) \/ sizeof(std::max_align_t))\n\n\nnamespace abc {\n\n\/** TODO: comment.\n\nTODO maybe move to other header file?\n*\/\ntemplate \nunion force_max_align {\npublic:\n\n\t\/** Actual storage. *\/\n\tT t;\n\n\nprivate:\n\n\t\/** Forces the whole union to have the most generic alignment; on many architectures this will be\n\t2 * word size. In any case, this makes the union aligned the same way malloc() aligns the\n\tpointers it returns. *\/\n\tstd::max_align_t aligner[ABC_ALIGNED_SIZE(sizeof(T))];\n};\n\n\n\/** See unsafe. *\/\nstruct unsafe_t {};\n\n\/** Constant used as extra argument for functions to force clients to acknowledge they are\nperforming unsafe operations. *\/\nextern unsafe_t const unsafe;\n\n} \/\/namespace abc\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\n#endif \/\/ifndef ABC_CORE_HXX\n\nFix ill-conceived implementation of ABC_CLASS_PREVENT_COPYING for MSC16\/* -*- coding: utf-8; mode: c++; tab-width: 3 -*-\n\nCopyright 2010, 2011, 2012, 2013\nRaffaello D. Di Napoli\n\nThis file is part of Application-Building Components (henceforth referred to as ABC).\n\nABC is free software: you can redistribute it and\/or modify it under the terms of the GNU General\nPublic License as published by the Free Software Foundation, either version 3 of the License, or (at\nyour option) any later version.\n\nABC is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the\nimplied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public\nLicense for more details.\n\nYou should have received a copy of the GNU General Public License along with ABC. If not, see\n.\n--------------------------------------------------------------------------------------------------*\/\n\n#ifndef ABC_CORE_HXX\n#define ABC_CORE_HXX\n\n\n#include \/\/ CHAR_BIT *_MAX *_MIN\n#include \/\/ *int*_t __WORDSIZE (if supported)\n#include \/\/ size_t\n\n#if defined(__GNUC__)\n\t\/\/ Make version checks for GCC less cumbersome.\n\t#define _GCC_VER \\\n\t\t(__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__)\n\t#if _GCC_VER < 40300\n\t\t#error Unsupported version of GCC (>= 4.3.0 required)\n\t#endif\n#elif defined(_MSC_VER)\n\t#if _MSC_VER < 1600\n\t\t#error Unsupported version of MSC (>= MSC 16 \/ VC++ 10 \/ VS 2010 required)\n\t#endif\n#endif\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ abc globals - HOST_* and OUTPUT_*\n\n#define ABC_HOST_API_WIN32 0\n#define ABC_HOST_API_WIN64 0\n#define ABC_HOST_API_LINUX 0\n#define ABC_HOST_API_POSIX 0\n#define ABC_OUTPUT_WIN32_DLL 0\n#define ABC_OUTPUT_WIN32_EXE 0\n#define ABC_OUTPUT_POSIX_EXE 0\n\n#if defined(_WIN32)\n\t\/\/ Compiling for Win32.\n\t#undef ABC_HOST_API_WIN32\n\t#define ABC_HOST_API_WIN32 1\n\t#ifdef _WIN64\n\t\t\/\/ Compiling for Win64 (coexists with ABC_HOST_API_WIN32).\n\t\t#undef ABC_HOST_API_WIN64\n\t\t#define ABC_HOST_API_WIN64 1\n\t#endif\n\t#ifdef _WINDLL\n\t\t#undef ABC_OUTPUT_WIN32_DLL\n\t\t#define ABC_OUTPUT_WIN32_DLL 1\n\t#else\n\t\t#undef ABC_OUTPUT_WIN32_EXE\n\t\t#define ABC_OUTPUT_WIN32_EXE 1\n\t#endif\n#elif defined(__linux__)\n\t\/\/ Compiling for Linux.\n\t#undef ABC_HOST_API_LINUX\n\t#define ABC_HOST_API_LINUX 1\n\t#undef ABC_HOST_API_POSIX\n\t#define ABC_HOST_API_POSIX 1\n\t#undef ABC_OUTPUT_POSIX_EXE\n\t#define ABC_OUTPUT_POSIX_EXE 1\n#elif defined(__posix__)\n\t\/\/ Compiling for POSIX.\n\t#undef ABC_HOST_API_POSIX\n\t#define ABC_HOST_API_POSIX 1\n\t#undef ABC_OUTPUT_POSIX_EXE\n\t#define ABC_OUTPUT_POSIX_EXE 1\n#endif\n\n\n\/** Machine word size for this microarchitecture. *\/\n#if ABC_HOST_API_WIN32\n\t#ifdef _WIN64\n\t\t#define ABC_HOST_WORD_SIZE 64\n\t#else\n\t\t#define ABC_HOST_WORD_SIZE 32\n\t#endif\n#elif defined(__WORDSIZE)\n\t#define ABC_HOST_WORD_SIZE __WORDSIZE\n#else\n\t#error Unable to determine the word size for this microarchitecture\n#endif\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ abc globals - platform-dependent fixes\n\n#if ABC_HOST_API_POSIX\n\n\t\/\/ This prevents stat() from failing for files bigger than 2 GiB.\n\t#define _FILE_OFFSET_BITS 64\n\n#elif ABC_HOST_API_WIN32\n\n\t\/\/ Make sure WINVER is defined.\n\t#ifndef WINVER\n\t\t\/\/ Pick a default Windows version.\n\t\t#ifdef _WIN64\n\t\t\t\/\/ The earliest Win64 implementations are Windows Server 2003 (5.2) and Windows XP x64\n\t\t\t\/\/ Edition (5.2).\n\t\t\t#define WINVER 0x0502\n\t\t#else\n\t\t\t\/\/ The earliest Win32 implementations are Windows 95 (4.0) and Windows NT 4 (4.0).\n\t\t\t#define WINVER 0x0400\n\t\t#endif\n\t#endif\n\n\t\/\/ Make sure _WIN32_WINNT is defined for WINVER values representing NT-only Windows versions.\n\t\/\/ The first NT-only version of Windows is 5.0 (Windows 2000; Windows Me is 4.9).\n\t#if !defined(_WIN32_WINNT) && WINVER >= 0x0500\n\t\t#define _WIN32_WINNT WINVER\n\t#endif\n\n\t\/\/ Make sure UNICODE and _UNICODE are coherent; UNICODE wins.\n\t#if defined(UNICODE) && !defined(_UNICODE)\n\t\t#define _UNICODE\n\t#elif !defined(UNICODE) && defined(_UNICODE)\n\t\t#undef _UNICODE\n\t#endif\n\n\t#define WIN32_LEAN_AND_MEAN\n\t#include \n#endif\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ abc globals - C++11 compiler support\n\n\/** If defined, the compiler supports defining conversion operators as explicit, to avoid executing\nthem implicitly (N2437). *\/\n#if defined(_GCC_VER) && _GCC_VER >= 40500\n\t#define ABC_CXX_EXPLICIT_CONVERSION_OPERATORS\n#endif\n\n\/** If defined, the compiler allows to delete a specific (overload of a) function, method or\nconstructor (N2346). *\/\n#if defined(_GCC_VER) && _GCC_VER >= 40400\n\t#define ABC_CXX_FUNCTION_DELETE\n#endif\n\n\/** If defined, the compiler supports template friend declarations (N1791). *\/\n#if (defined(_GCC_VER) && _GCC_VER >= 40500) || defined(_MSC_VER)\n\t#define ABC_CXX_TEMPLATE_FRIENDS\n#endif\n\n\/** If defined, the compiler supports variadic templates (N2242). *\/\n#if defined(_GCC_VER)\n\t#define ABC_CXX_VARIADIC_TEMPLATES\n#endif\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ abc globals - non-standard, but commonly available, extensions\n\n\/** If defined, the compiler supports #pragma once, which tells the preprocessor not to parsing a\n(header) file more than once, speeding up compilation. *\/\n#if defined(_MSC_VER)\n\t#define ABC_CXX_PRAGMA_ONCE\n\n\t\/\/ Use it now for this file.\n\t#pragma once\n#endif\n\n\/** Defines a function as never returning (e.g. by causing the process to terminate, or by throwing\nan exception). This allows optimizations based on the fact that code following its call cannot be\nreached. *\/\n#if defined(_GCC_VER)\n\t#define ABC_FUNC_NORETURN \\\n\t\t__attribute__((noreturn))\n#elif defined(_MSC_VER)\n\t#define ABC_FUNC_NORETURN \\\n\t\t__declspec(noreturn)\n#else\n\t#define ABC_FUNC_NORETURN\n#endif\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ abc globals - extended features that can take advantage of C++11 or fallback to more risky, but\n\/\/ still functional alternatives\n\n\/** Makes the class un-copiable. Move constructors and\/or assignment operators may be still\navailable, though.\n\nTODO: comment signature.\n*\/\n#ifdef ABC_CXX_FUNCTION_DELETE\n\t#define ABC_CLASS_PREVENT_COPYING(cls) \\\n\t\tpublic: \\\n\t\t\\\n\t\t\tcls(cls const &) = delete; \\\n\t\t\t\\\n\t\t\tcls & operator=(cls const &) = delete;\n#else\n\t#define ABC_CLASS_PREVENT_COPYING(cls) \\\n\t\tprivate: \\\n\t\t\\\n\t\t\tcls(cls const &); \\\n\t\t\\\n\t\t\tcls & operator=(cls const &);\n#endif\n\n\nnamespace abc {\n\n\/** Declares an explicit conversion operator to bool.\n*\/\n#ifdef ABC_CXX_EXPLICIT_CONVERSION_OPERATORS\n\n\t#define explicit_operator_bool \\\n\t\texplicit operator bool\n\n\n\t\/** A class derived from this one receives support for C++11 explicit operator bool even on\n\tnon-compliant compilers.\n\t*\/\n\ttemplate \n\tstruct support_explicit_operator_bool {};\n\n#else \/\/ifdef ABC_CXX_EXPLICIT_CONVERSION_OPERATORS\n\n\t#define explicit_operator_bool \\\n\t\tbool _explicit_operator_bool\n\n\n\t\/** Non-template helper for support_explicit_operator_bool.\n\t*\/\n\tstruct _explob_helper {\n\n\t\t\/** Non-bool boolean type. *\/\n\t\ttypedef void (_explob_helper::* bool_type)() const;\n\n\n\t\t\/** A pointer to this method is used as a boolean true by support_explicit_operator_bool.\n\t\t*\/\n\t\tvoid bool_true() const;\n\t};\n\n\n\n\t\/** A class derived from this one receives support for C++11 explicit operator bool even on\n\tnon-compliant compilers.\n\t*\/\n\ttemplate \n\tstruct support_explicit_operator_bool {\n\n\t\t\/** Non-bool boolean conversion operator, safer than operator bool(), and almost as good as\n\t\texplicit operator bool().\n\n\t\tTODO: comment signature.\n\t\t*\/\n\t\toperator _explob_helper::bool_type() const {\n\t\t\tif (static_cast(this)->_explicit_operator_bool()) {\n\t\t\t\treturn &_explob_helper::bool_true;\n\t\t\t} else {\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t}\n\t};\n\n\n\t\/\/ Disable relational operators for support_explicit_operator_bool.\n\n\t#ifdef ABC_CXX_FUNCTION_DELETE\n\n\t\t#define ABC_RELOP_IMPL(op) \\\n\t\t\ttemplate \\\n\t\t\tbool operator op( \\\n\t\t\t\tsupport_explicit_operator_bool const &, support_explicit_operator_bool const & \\\n\t\t\t) = delete;\n\n\t#else \/\/ifdef ABC_CXX_FUNCTION_DELETE\n\n\t\t#define ABC_RELOP_IMPL(op) \\\n\t\t\ttemplate \\\n\t\t\tinline bool operator op( \\\n\t\t\t\tsupport_explicit_operator_bool const & lhs, \\\n\t\t\t\tsupport_explicit_operator_bool const & rhs \\\n\t\t\t) { \\\n\t\t\t\tcannot_compare_to(lhs, rhs); \\\n\t\t\t\treturn false; \\\n\t\t\t}\n\n\t#endif \/\/ifdef ABC_CXX_FUNCTION_DELETE … else\n\n\tABC_RELOP_IMPL(==)\n\tABC_RELOP_IMPL(!=)\n\t#undef ABC_RELOP_IMPL\n\n#endif \/\/ifdef ABC_CXX_EXPLICIT_CONVERSION_OPERATORS … else\n\n} \/\/namespace abc\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ abc globals - other\n\nnamespace std {\n\n\/** Type whose alignment requirement is at least as large as that of every scalar type (see C++11 §\n18.2 “”).\n*\/\nunion max_align_t {\n\tdouble d;\n\tlong double ld;\n\tlong long ll;\n};\n\n} \/\/namespace std\n\n\n\/\/ Support loose exception specifications.\n#if defined(_GCC_VER) && _GCC_VER >= 40600\n\t#define noexcept_false \\\n\t\tnoexcept(false)\n\t#define noexcept_true \\\n\t\tnoexcept(true)\n\t#define noexcept_if(cond) \\\n\t\tnoexcept(cond)\n#else\n\t#define noexcept_false\n\t#define noexcept_true \\\n\t\tthrow()\n\t#define noexcept_if(cond)\n#endif\n\n\/\/ Support for pre-C++11 declarations. Use double parentheses for the list.\n#define decl_throw(list) \\\n\tthrow list\n\n\n\/** Avoids compiler warnings about purposely unused parameters. Win32 has UNREFERENCED_PARAMETER for\nthis purpose, but this is noticeably shorter :)\n\nTODO: comment signature.\n*\/\n#define UNUSED_ARG(x) \\\n\tstatic_cast(x)\n\n\n\/** Tells the compiler that a switch statement that apparently doesn’t test for all possible cases\nfor its argument (e.g. skips some values of an enum), does cover 100% of the actually possible\ncases.\n\nIt can avoid warnings about not testing for all possible values for an enum, or cases where a\nvariable would seem to be left uninitialized if the switch argument has a value that’s not one of\nthose expected by the case labels.\n*\/\n#if defined(_MSC_VER)\n\t#define no_default \\\n\t\tdefault: \\\n\t\t\t__assume(0)\n#else\n\t#define no_default \\\n\t\tdefault: \\\n\t\t\tbreak\n#endif\n\n\n\/** Returns the number of items in a (static) array.\n\nTODO: comment signature.\n*\/\n#undef countof\n#define countof(array) \\\n\t(sizeof(array) \/ sizeof((array)[0]))\n\n\n\/** Returns the offset, in bytes, of a struct\/class member. It doesn’t trigger warnings, since it\ndoesn’t use NULL as the fake address.\n\nTODO: comment signature.\n*\/\n#undef offsetof\n#define offsetof(type, member) \\\n\t(reinterpret_cast(&reinterpret_cast(1024)->member) - 1024)\n\n\n\/** Returns the compiler-computed alignment for the specified data type. When compiler support is\nlacking, this can be inaccurate for long double.\n\nTODO: comment signature.\n*\/\n#undef alignof\n#if defined(_GCC_VER)\n\t#define alignof(type) \\\n\t\t__alignof__(type)\n#elif defined(_MSC_VER)\n\t#define alignof(type) \\\n\t\t__alignof(type)\n#else\n\t#define alignof(type) \\\n\t\toffsetof(abc::_alignof_helper, t)\n\n\tnamespace abc {\n\n\ttemplate \n\tstruct _alignof_helper {\n\t\tint8_t misaligner;\n\t\tT t;\n\t};\n\n\t} \/\/namespace abc\n#endif\n\n\n\/** Returns a size rounded (ceiling) to a count of std::max_align_t units. This allows to declare\nstorage with alignment suitable for any type, just like ::malloc() does. Identical to\nbitmanip::ceiling_to_pow2_multiple(cb, sizeof(std::max_align_t)).\n\nTODO: comment signature.\n*\/\n#define ABC_ALIGNED_SIZE(cb) \\\n\t((size_t(cb) + sizeof(std::max_align_t) - 1) \/ sizeof(std::max_align_t))\n\n\nnamespace abc {\n\n\/** TODO: comment.\n\nTODO maybe move to other header file?\n*\/\ntemplate \nunion force_max_align {\npublic:\n\n\t\/** Actual storage. *\/\n\tT t;\n\n\nprivate:\n\n\t\/** Forces the whole union to have the most generic alignment; on many architectures this will be\n\t2 * word size. In any case, this makes the union aligned the same way malloc() aligns the\n\tpointers it returns. *\/\n\tstd::max_align_t aligner[ABC_ALIGNED_SIZE(sizeof(T))];\n};\n\n\n\/** See unsafe. *\/\nstruct unsafe_t {};\n\n\/** Constant used as extra argument for functions to force clients to acknowledge they are\nperforming unsafe operations. *\/\nextern unsafe_t const unsafe;\n\n} \/\/namespace abc\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\n#endif \/\/ifndef ABC_CORE_HXX\n\n<|endoftext|>"} {"text":"\/\/ Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.\n\n#include \"blueprintresolver.h\"\n#include \"blueprintfactory.h\"\n#include \"featurenameparser.h\"\n#include \n#include \n#include \n\n#include \nLOG_SETUP(\".fef.blueprintresolver\");\n\nnamespace search::fef {\n\nnamespace {\n\nusing Accept = Blueprint::AcceptInput;\n\nbool is_compatible(bool is_object, Accept accept_type) {\n return ((accept_type == Accept::ANY) ||\n ((accept_type == Accept::OBJECT) == (is_object)));\n}\n\nconst char *type_str(bool is_object) {\n return (is_object ? \"object\" : \"number\");\n}\n\nconst char *accept_type_str(Accept accept_type) {\n switch (accept_type) {\n case Accept::NUMBER: return \"number\";\n case Accept::OBJECT: return \"object\";\n case Accept::ANY: return \"any\";\n }\n return \"(not reached)\";\n}\n\nstruct Compiler : public Blueprint::DependencyHandler {\n using ExecutorSpec = BlueprintResolver::ExecutorSpec;\n using ExecutorSpecList = BlueprintResolver::ExecutorSpecList;\n using FeatureRef = BlueprintResolver::FeatureRef;\n using FeatureMap = BlueprintResolver::FeatureMap;\n\n struct Frame {\n ExecutorSpec spec;\n const FeatureNameParser &parser;\n Frame(Blueprint::SP blueprint, const FeatureNameParser &parser_in)\n : spec(std::move(blueprint)), parser(parser_in) {}\n };\n using Stack = std::vector;\n\n struct FrameGuard {\n Stack &stack;\n explicit FrameGuard(Stack &stack_in) : stack(stack_in) {}\n ~FrameGuard() { stack.pop_back(); }\n };\n\n const BlueprintFactory &factory;\n const IIndexEnvironment &index_env;\n bool compile_error;\n Stack resolve_stack;\n ExecutorSpecList &spec_list;\n FeatureMap &feature_map;\n\n Compiler(const BlueprintFactory &factory_in,\n const IIndexEnvironment &index_env_in,\n ExecutorSpecList &spec_list_out,\n FeatureMap &feature_map_out)\n : factory(factory_in),\n index_env(index_env_in),\n compile_error(false),\n resolve_stack(),\n spec_list(spec_list_out),\n feature_map(feature_map_out) {}\n\n Frame &self() { return resolve_stack.back(); }\n\n FeatureRef failed(const vespalib::string &feature_name, const vespalib::string &reason) {\n if (!compile_error) {\n LOG(warning, \"invalid rank feature: '%s' (%s)\", feature_name.c_str(), reason.c_str());\n for (size_t i = resolve_stack.size(); i > 0; --i) {\n const auto &frame = resolve_stack[i - 1];\n if (&frame != &self()) {\n LOG(warning, \" ... needed by rank feature '%s'\", frame.parser.featureName().c_str());\n }\n }\n compile_error = true;\n }\n return FeatureRef();\n }\n\n void fixup_feature_map() {\n auto itr = feature_map.begin();\n while (itr != feature_map.end()) {\n if (itr->second.executor >= spec_list.size()) {\n itr = feature_map.erase(itr);\n } else {\n ++itr;\n }\n }\n }\n\n FeatureRef verify_type(const FeatureNameParser &parser, FeatureRef ref, Accept accept_type) {\n const auto &spec = spec_list[ref.executor];\n bool is_object = spec.output_types[ref.output];\n if (!is_compatible(is_object, accept_type)) {\n return failed(parser.featureName(),\n vespalib::make_string(\"output '%s' has wrong type: was %s, expected %s\",\n parser.output().c_str(), type_str(is_object), accept_type_str(accept_type)));\n }\n return ref;\n }\n\n FeatureRef setup_feature(const FeatureNameParser &parser, Accept accept_type) {\n Blueprint::SP blueprint = factory.createBlueprint(parser.baseName());\n if ( ! blueprint) {\n return failed(parser.featureName(),\n vespalib::make_string(\"unknown basename: '%s'\", parser.baseName().c_str()));\n }\n resolve_stack.emplace_back(std::move(blueprint), parser);\n FrameGuard frame_guard(resolve_stack);\n self().spec.blueprint->setName(parser.executorName());\n self().spec.blueprint->attach_dependency_handler(*this);\n if (!self().spec.blueprint->setup(index_env, parser.parameters())) {\n fixup_feature_map();\n return failed(parser.featureName(), \"invalid parameters\");\n }\n if (parser.output().empty() && self().spec.output_types.empty()) {\n fixup_feature_map();\n return failed(parser.featureName(), \"has no output value\");\n }\n const auto &feature = feature_map.find(parser.featureName());\n if (feature == feature_map.end()) {\n fixup_feature_map();\n return failed(parser.featureName(),\n vespalib::make_string(\"unknown output: '%s'\", parser.output().c_str()));\n }\n spec_list.push_back(self().spec);\n return verify_type(parser, feature->second, accept_type);\n }\n\n FeatureRef resolve_feature(const vespalib::string &feature_name, Accept accept_type) {\n FeatureNameParser parser(feature_name);\n if (!parser.valid()) {\n return failed(feature_name, \"malformed name\");\n }\n const auto &feature = feature_map.find(parser.featureName());\n if (feature != feature_map.end()) {\n return verify_type(parser, feature->second, accept_type);\n }\n if ((resolve_stack.size() + 1) > BlueprintResolver::MAX_DEP_DEPTH) {\n return failed(parser.featureName(), \"dependency graph too deep\");\n }\n for (const Frame &frame: resolve_stack) {\n if (frame.parser.executorName() == parser.executorName()) {\n return failed(parser.featureName(), \"dependency cycle detected\");\n }\n }\n return setup_feature(parser, accept_type);\n }\n\n const FeatureType &resolve_input(const vespalib::string &feature_name, Accept accept_type) override {\n assert(self().spec.output_types.empty()); \/\/ require: 'resolve inputs' before 'define outputs'\n auto ref = resolve_feature(feature_name, accept_type);\n if (!ref.valid()) {\n return FeatureType::number();\n }\n self().spec.inputs.push_back(ref);\n return spec_list[ref.executor].output_types[ref.output];\n }\n\n void define_output(const vespalib::string &output_name, const FeatureType &type) override {\n vespalib::string feature_name = self().parser.executorName();\n if (!output_name.empty()) {\n feature_name.push_back('.');\n feature_name.append(output_name);\n }\n FeatureRef output_ref(spec_list.size(), self().spec.output_types.size());\n if (output_ref.output == 0) {\n feature_map.emplace(self().parser.executorName(), output_ref);\n }\n feature_map.emplace(feature_name, output_ref);\n self().spec.output_types.push_back(type);\n }\n};\n\n} \/\/ namespace search::fef::\n\nBlueprintResolver::ExecutorSpec::ExecutorSpec(Blueprint::SP blueprint_in)\n : blueprint(std::move(blueprint_in)),\n inputs(),\n output_types()\n{ }\n\nBlueprintResolver::ExecutorSpec::~ExecutorSpec() = default;\nBlueprintResolver::~BlueprintResolver() = default;\n\nBlueprintResolver::BlueprintResolver(const BlueprintFactory &factory,\n const IIndexEnvironment &indexEnv)\n : _factory(factory),\n _indexEnv(indexEnv),\n _seeds(),\n _executorSpecs(),\n _featureMap(),\n _seedMap()\n{\n}\n\nvoid\nBlueprintResolver::addSeed(vespalib::stringref feature)\n{\n _seeds.emplace_back(feature);\n}\n\nbool\nBlueprintResolver::compile()\n{\n assert(_executorSpecs.empty()); \/\/ only one compilation allowed\n Compiler compiler(_factory, _indexEnv, _executorSpecs, _featureMap);\n for (const auto &seed: _seeds) {\n auto ref = compiler.resolve_feature(seed, Blueprint::AcceptInput::ANY);\n if (compiler.compile_error) {\n return false;\n }\n _seedMap.emplace(FeatureNameParser(seed).featureName(), ref);\n }\n return true;\n}\n\nconst BlueprintResolver::ExecutorSpecList &\nBlueprintResolver::getExecutorSpecs() const\n{\n return _executorSpecs;\n}\n\nconst BlueprintResolver::FeatureMap &\nBlueprintResolver::getFeatureMap() const\n{\n return _featureMap;\n}\n\nconst BlueprintResolver::FeatureMap &\nBlueprintResolver::getSeedMap() const\n{\n return _seedMap;\n}\n\n}\nCall fixup_feature_map() from failed() method.\/\/ Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.\n\n#include \"blueprintresolver.h\"\n#include \"blueprintfactory.h\"\n#include \"featurenameparser.h\"\n#include \n#include \n#include \n\n#include \nLOG_SETUP(\".fef.blueprintresolver\");\n\nnamespace search::fef {\n\nnamespace {\n\nusing Accept = Blueprint::AcceptInput;\n\nbool is_compatible(bool is_object, Accept accept_type) {\n return ((accept_type == Accept::ANY) ||\n ((accept_type == Accept::OBJECT) == (is_object)));\n}\n\nconst char *type_str(bool is_object) {\n return (is_object ? \"object\" : \"number\");\n}\n\nconst char *accept_type_str(Accept accept_type) {\n switch (accept_type) {\n case Accept::NUMBER: return \"number\";\n case Accept::OBJECT: return \"object\";\n case Accept::ANY: return \"any\";\n }\n return \"(not reached)\";\n}\n\nstruct Compiler : public Blueprint::DependencyHandler {\n using ExecutorSpec = BlueprintResolver::ExecutorSpec;\n using ExecutorSpecList = BlueprintResolver::ExecutorSpecList;\n using FeatureRef = BlueprintResolver::FeatureRef;\n using FeatureMap = BlueprintResolver::FeatureMap;\n\n struct Frame {\n ExecutorSpec spec;\n const FeatureNameParser &parser;\n Frame(Blueprint::SP blueprint, const FeatureNameParser &parser_in)\n : spec(std::move(blueprint)), parser(parser_in) {}\n };\n using Stack = std::vector;\n\n struct FrameGuard {\n Stack &stack;\n explicit FrameGuard(Stack &stack_in) : stack(stack_in) {}\n ~FrameGuard() { stack.pop_back(); }\n };\n\n const BlueprintFactory &factory;\n const IIndexEnvironment &index_env;\n bool compile_error;\n Stack resolve_stack;\n ExecutorSpecList &spec_list;\n FeatureMap &feature_map;\n\n Compiler(const BlueprintFactory &factory_in,\n const IIndexEnvironment &index_env_in,\n ExecutorSpecList &spec_list_out,\n FeatureMap &feature_map_out)\n : factory(factory_in),\n index_env(index_env_in),\n compile_error(false),\n resolve_stack(),\n spec_list(spec_list_out),\n feature_map(feature_map_out) {}\n\n Frame &self() { return resolve_stack.back(); }\n\n FeatureRef failed(const vespalib::string &feature_name, const vespalib::string &reason) {\n if (!compile_error) {\n LOG(warning, \"invalid rank feature: '%s' (%s)\", feature_name.c_str(), reason.c_str());\n for (size_t i = resolve_stack.size(); i > 0; --i) {\n const auto &frame = resolve_stack[i - 1];\n if (&frame != &self()) {\n LOG(warning, \" ... needed by rank feature '%s'\", frame.parser.featureName().c_str());\n }\n }\n compile_error = true;\n }\n fixup_feature_map();\n return FeatureRef();\n }\n\n void fixup_feature_map() {\n auto itr = feature_map.begin();\n while (itr != feature_map.end()) {\n if (itr->second.executor >= spec_list.size()) {\n itr = feature_map.erase(itr);\n } else {\n ++itr;\n }\n }\n }\n\n FeatureRef verify_type(const FeatureNameParser &parser, FeatureRef ref, Accept accept_type) {\n const auto &spec = spec_list[ref.executor];\n bool is_object = spec.output_types[ref.output];\n if (!is_compatible(is_object, accept_type)) {\n return failed(parser.featureName(),\n vespalib::make_string(\"output '%s' has wrong type: was %s, expected %s\",\n parser.output().c_str(), type_str(is_object), accept_type_str(accept_type)));\n }\n return ref;\n }\n\n FeatureRef setup_feature(const FeatureNameParser &parser, Accept accept_type) {\n Blueprint::SP blueprint = factory.createBlueprint(parser.baseName());\n if ( ! blueprint) {\n return failed(parser.featureName(),\n vespalib::make_string(\"unknown basename: '%s'\", parser.baseName().c_str()));\n }\n resolve_stack.emplace_back(std::move(blueprint), parser);\n FrameGuard frame_guard(resolve_stack);\n self().spec.blueprint->setName(parser.executorName());\n self().spec.blueprint->attach_dependency_handler(*this);\n if (!self().spec.blueprint->setup(index_env, parser.parameters())) {\n return failed(parser.featureName(), \"invalid parameters\");\n }\n if (parser.output().empty() && self().spec.output_types.empty()) {\n return failed(parser.featureName(), \"has no output value\");\n }\n const auto &feature = feature_map.find(parser.featureName());\n if (feature == feature_map.end()) {\n return failed(parser.featureName(),\n vespalib::make_string(\"unknown output: '%s'\", parser.output().c_str()));\n }\n spec_list.push_back(self().spec);\n return verify_type(parser, feature->second, accept_type);\n }\n\n FeatureRef resolve_feature(const vespalib::string &feature_name, Accept accept_type) {\n FeatureNameParser parser(feature_name);\n if (!parser.valid()) {\n return failed(feature_name, \"malformed name\");\n }\n const auto &feature = feature_map.find(parser.featureName());\n if (feature != feature_map.end()) {\n return verify_type(parser, feature->second, accept_type);\n }\n if ((resolve_stack.size() + 1) > BlueprintResolver::MAX_DEP_DEPTH) {\n return failed(parser.featureName(), \"dependency graph too deep\");\n }\n for (const Frame &frame: resolve_stack) {\n if (frame.parser.executorName() == parser.executorName()) {\n return failed(parser.featureName(), \"dependency cycle detected\");\n }\n }\n return setup_feature(parser, accept_type);\n }\n\n const FeatureType &resolve_input(const vespalib::string &feature_name, Accept accept_type) override {\n assert(self().spec.output_types.empty()); \/\/ require: 'resolve inputs' before 'define outputs'\n auto ref = resolve_feature(feature_name, accept_type);\n if (!ref.valid()) {\n return FeatureType::number();\n }\n self().spec.inputs.push_back(ref);\n return spec_list[ref.executor].output_types[ref.output];\n }\n\n void define_output(const vespalib::string &output_name, const FeatureType &type) override {\n vespalib::string feature_name = self().parser.executorName();\n if (!output_name.empty()) {\n feature_name.push_back('.');\n feature_name.append(output_name);\n }\n FeatureRef output_ref(spec_list.size(), self().spec.output_types.size());\n if (output_ref.output == 0) {\n feature_map.emplace(self().parser.executorName(), output_ref);\n }\n feature_map.emplace(feature_name, output_ref);\n self().spec.output_types.push_back(type);\n }\n};\n\n} \/\/ namespace search::fef::\n\nBlueprintResolver::ExecutorSpec::ExecutorSpec(Blueprint::SP blueprint_in)\n : blueprint(std::move(blueprint_in)),\n inputs(),\n output_types()\n{ }\n\nBlueprintResolver::ExecutorSpec::~ExecutorSpec() = default;\nBlueprintResolver::~BlueprintResolver() = default;\n\nBlueprintResolver::BlueprintResolver(const BlueprintFactory &factory,\n const IIndexEnvironment &indexEnv)\n : _factory(factory),\n _indexEnv(indexEnv),\n _seeds(),\n _executorSpecs(),\n _featureMap(),\n _seedMap()\n{\n}\n\nvoid\nBlueprintResolver::addSeed(vespalib::stringref feature)\n{\n _seeds.emplace_back(feature);\n}\n\nbool\nBlueprintResolver::compile()\n{\n assert(_executorSpecs.empty()); \/\/ only one compilation allowed\n Compiler compiler(_factory, _indexEnv, _executorSpecs, _featureMap);\n for (const auto &seed: _seeds) {\n auto ref = compiler.resolve_feature(seed, Blueprint::AcceptInput::ANY);\n if (compiler.compile_error) {\n return false;\n }\n _seedMap.emplace(FeatureNameParser(seed).featureName(), ref);\n }\n return true;\n}\n\nconst BlueprintResolver::ExecutorSpecList &\nBlueprintResolver::getExecutorSpecs() const\n{\n return _executorSpecs;\n}\n\nconst BlueprintResolver::FeatureMap &\nBlueprintResolver::getFeatureMap() const\n{\n return _featureMap;\n}\n\nconst BlueprintResolver::FeatureMap &\nBlueprintResolver::getSeedMap() const\n{\n return _seedMap;\n}\n\n}\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \n\n#include \"build\/build_config.h\"\n#include \"chrome\/test\/ui\/ui_test.h\"\n#include \"net\/base\/net_util.h\"\n\nclass GPUTest : public UITest {\n protected:\n GPUTest() {\n }\n\n virtual void SetUp() {\n UITest::SetUp();\n gpu_test_dir_ = test_data_directory_.AppendASCII(\"gpu\");\n }\n\n FilePath gpu_test_dir_;\n};\n\n\/\/ TODO(apatrick): Other pending changes will fix this for mac.\n#if defined(OS_MACOSX) || defined(OS_LINUX)\n#define MAYBE_UITestLaunchedWithOSMesa FAILS_UITestLaunchedWithOSMesa\n#else\n#define MAYBE_UITestLaunchedWithOSMesa FLAKY_UITestLaunchedWithOSMesa\n#endif\n\nTEST_F(GPUTest, MAYBE_UITestLaunchedWithOSMesa) {\n \/\/ Check the webgl test reports success and that the renderer was OSMesa.\n \/\/ We use OSMesa for tests in order to get consistent results across a\n \/\/ variety of boxes.\n NavigateToURL(\n net::FilePathToFileURL(gpu_test_dir_.AppendASCII(\"webgl.html\")));\n\n EXPECT_EQ(std::wstring(L\"SUCCESS: Mesa OffScreen\"), GetActiveTabTitle());\n}\nFlagged GPUTest.UITestLaunchedWithOSMesa as DISABLED.\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \n\n#include \"build\/build_config.h\"\n#include \"chrome\/test\/ui\/ui_test.h\"\n#include \"net\/base\/net_util.h\"\n\nclass GPUTest : public UITest {\n protected:\n GPUTest() {\n }\n\n virtual void SetUp() {\n UITest::SetUp();\n gpu_test_dir_ = test_data_directory_.AppendASCII(\"gpu\");\n }\n\n FilePath gpu_test_dir_;\n};\n\n\/\/ TODO(apatrick): Other pending changes will fix this for mac and linux.\n#if defined(OS_MACOSX) || defined(OS_LINUX)\n#define MAYBE_UITestLaunchedWithOSMesa DISABLED_UITestLaunchedWithOSMesa\n#else\n#define MAYBE_UITestLaunchedWithOSMesa FLAKY_UITestLaunchedWithOSMesa\n#endif\n\nTEST_F(GPUTest, MAYBE_UITestLaunchedWithOSMesa) {\n \/\/ Check the webgl test reports success and that the renderer was OSMesa.\n \/\/ We use OSMesa for tests in order to get consistent results across a\n \/\/ variety of boxes.\n NavigateToURL(\n net::FilePathToFileURL(gpu_test_dir_.AppendASCII(\"webgl.html\")));\n\n EXPECT_EQ(std::wstring(L\"SUCCESS: Mesa OffScreen\"), GetActiveTabTitle());\n}\n<|endoftext|>"} {"text":"\n\/\/\n\/\/ This source file is part of appleseed.\n\/\/ Visit http:\/\/appleseedhq.net\/ for additional information and resources.\n\/\/\n\/\/ This software is released under the MIT license.\n\/\/\n\/\/ Copyright (c) 2010-2013 Francois Beaune, Jupiter Jazz Limited\n\/\/ Copyright (c) 2014 Francois Beaune, The appleseedhq Organization\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n\/\/ THE SOFTWARE.\n\/\/\n\n\/\/ Interface header.\n#include \"objectcollectionitem.h\"\n\n\/\/ appleseed.studio headers.\n#include \"mainwindow\/project\/assemblyitem.h\"\n#include \"mainwindow\/project\/itemregistry.h\"\n#include \"mainwindow\/project\/objectitem.h\"\n#include \"mainwindow\/project\/projectbuilder.h\"\n#include \"mainwindow\/rendering\/renderingmanager.h\"\n#include \"utility\/interop.h\"\n#include \"utility\/settingskeys.h\"\n\n\/\/ appleseed.renderer headers.\n#include \"renderer\/api\/utility.h\"\n\n\/\/ appleseed.foundation headers.\n#include \"foundation\/math\/transform.h\"\n#include \"foundation\/utility\/containers\/dictionary.h\"\n#include \"foundation\/utility\/autoreleaseptr.h\"\n#include \"foundation\/utility\/searchpaths.h\"\n#include \"foundation\/utility\/uid.h\"\n\n\/\/ Qt headers.\n#include \n#include \n#include \n#include \n#include \n\n\/\/ boost headers.\n#include \"boost\/filesystem\/path.hpp\"\n\n\/\/ Standard headers.\n#include \n#include \n\nusing namespace boost;\nusing namespace foundation;\nusing namespace renderer;\nusing namespace std;\n\nnamespace appleseed {\nnamespace studio {\n\nnamespace\n{\n const UniqueID g_class_uid = new_guid();\n}\n\nObjectCollectionItem::ObjectCollectionItem(\n ObjectContainer& objects,\n Assembly& parent,\n AssemblyItem* parent_item,\n ProjectBuilder& project_builder,\n ParamArray& settings)\n : CollectionItemBase(g_class_uid, \"Objects\", project_builder)\n , m_parent(parent)\n , m_parent_item(parent_item)\n , m_settings(settings)\n{\n add_items(objects);\n}\n\nQMenu* ObjectCollectionItem::get_single_item_context_menu() const\n{\n QMenu* menu = CollectionItemBase::get_single_item_context_menu();\n\n menu->addSeparator();\n menu->addAction(\"Import Objects...\", this, SLOT(slot_import_objects()));\n\n return menu;\n}\n\nvoid ObjectCollectionItem::slot_import_objects()\n{\n QFileDialog::Options options;\n QString selected_filter;\n\n const QStringList filepaths =\n QFileDialog::getOpenFileNames(\n treeWidget(),\n \"Import Objects...\",\n m_settings.get_path_optional(LAST_DIRECTORY_SETTINGS_KEY),\n \"Geometry Files (*.abc; *.obj);;All Files (*.*)\",\n &selected_filter,\n options);\n\n if (filepaths.empty())\n return;\n\n const filesystem::path path(\n QDir::toNativeSeparators(filepaths.first()).toStdString());\n\n m_settings.insert_path(\n LAST_DIRECTORY_SETTINGS_KEY,\n path.parent_path().string());\n\n if (m_project_builder.get_rendering_manager().is_rendering())\n schedule_import_objects(filepaths);\n else import_objects(filepaths);\n\n}\n\nnamespace\n{\n class ImportObjectsDelayedAction\n : public RenderingManager::IDelayedAction\n {\n public:\n ImportObjectsDelayedAction(\n ObjectCollectionItem* parent,\n const QStringList& filepaths)\n : m_parent(parent)\n , m_filepaths(filepaths)\n {\n }\n\n virtual void operator()(\n MasterRenderer& master_renderer,\n Project& project) OVERRIDE\n {\n m_parent->import_objects(m_filepaths);\n }\n\n private:\n ObjectCollectionItem* m_parent;\n const QStringList m_filepaths;\n };\n}\n\nvoid ObjectCollectionItem::schedule_import_objects(const QStringList& filepaths)\n{\n m_project_builder.get_rendering_manager().push_delayed_action(\n auto_ptr(\n new ImportObjectsDelayedAction(this, filepaths)));\n\n m_project_builder.get_rendering_manager().reinitialize_rendering();\n}\n\nvoid ObjectCollectionItem::import_objects(const QStringList& filepaths)\n{\n for (int i = 0; i < filepaths.size(); ++i)\n insert_objects(QDir::toNativeSeparators(filepaths[i]).toStdString());\n}\n\nvoid ObjectCollectionItem::insert_objects(const string& path) const\n{\n const string base_object_name =\n filesystem::path(path).replace_extension().filename().string();\n\n ParamArray params;\n params.insert(\"filename\", path);\n\n SearchPaths search_paths;\n MeshObjectArray mesh_objects;\n\n if (!MeshObjectReader().read(\n search_paths,\n base_object_name.c_str(),\n params,\n mesh_objects))\n return;\n\n for (size_t i = 0; i < mesh_objects.size(); ++i)\n {\n MeshObject* object = mesh_objects[i];\n\n m_parent_item->add_item(object);\n\n m_parent.objects().insert(auto_release_ptr(object));\n\n const string object_instance_name = string(object->get_name()) + \"_inst\";\n \n auto_release_ptr object_instance(\n ObjectInstanceFactory::create(\n object_instance_name.c_str(),\n ParamArray(),\n object->get_name(),\n Transformd::identity(),\n StringDictionary()));\n\n m_parent_item->add_item(object_instance.get());\n\n m_parent.object_instances().insert(object_instance);\n }\n\n if (!mesh_objects.empty())\n {\n m_parent.bump_version_id();\n m_project_builder.notify_project_modification();\n }\n}\n\nItemBase* ObjectCollectionItem::create_item(Object* object)\n{\n assert(object);\n\n ItemBase* item =\n new ObjectItem(\n object,\n m_parent,\n m_parent_item,\n m_project_builder);\n\n m_project_builder.get_item_registry().insert(object->get_uid(), item);\n\n return item;\n}\n\n} \/\/ namespace studio\n} \/\/ namespace appleseed\nthe Import Objects file dialog now show *.binarymesh files.\n\/\/\n\/\/ This source file is part of appleseed.\n\/\/ Visit http:\/\/appleseedhq.net\/ for additional information and resources.\n\/\/\n\/\/ This software is released under the MIT license.\n\/\/\n\/\/ Copyright (c) 2010-2013 Francois Beaune, Jupiter Jazz Limited\n\/\/ Copyright (c) 2014 Francois Beaune, The appleseedhq Organization\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n\/\/ THE SOFTWARE.\n\/\/\n\n\/\/ Interface header.\n#include \"objectcollectionitem.h\"\n\n\/\/ appleseed.studio headers.\n#include \"mainwindow\/project\/assemblyitem.h\"\n#include \"mainwindow\/project\/itemregistry.h\"\n#include \"mainwindow\/project\/objectitem.h\"\n#include \"mainwindow\/project\/projectbuilder.h\"\n#include \"mainwindow\/rendering\/renderingmanager.h\"\n#include \"utility\/interop.h\"\n#include \"utility\/settingskeys.h\"\n\n\/\/ appleseed.renderer headers.\n#include \"renderer\/api\/utility.h\"\n\n\/\/ appleseed.foundation headers.\n#include \"foundation\/math\/transform.h\"\n#include \"foundation\/utility\/containers\/dictionary.h\"\n#include \"foundation\/utility\/autoreleaseptr.h\"\n#include \"foundation\/utility\/searchpaths.h\"\n#include \"foundation\/utility\/uid.h\"\n\n\/\/ Qt headers.\n#include \n#include \n#include \n#include \n#include \n\n\/\/ boost headers.\n#include \"boost\/filesystem\/path.hpp\"\n\n\/\/ Standard headers.\n#include \n#include \n\nusing namespace boost;\nusing namespace foundation;\nusing namespace renderer;\nusing namespace std;\n\nnamespace appleseed {\nnamespace studio {\n\nnamespace\n{\n const UniqueID g_class_uid = new_guid();\n}\n\nObjectCollectionItem::ObjectCollectionItem(\n ObjectContainer& objects,\n Assembly& parent,\n AssemblyItem* parent_item,\n ProjectBuilder& project_builder,\n ParamArray& settings)\n : CollectionItemBase(g_class_uid, \"Objects\", project_builder)\n , m_parent(parent)\n , m_parent_item(parent_item)\n , m_settings(settings)\n{\n add_items(objects);\n}\n\nQMenu* ObjectCollectionItem::get_single_item_context_menu() const\n{\n QMenu* menu = CollectionItemBase::get_single_item_context_menu();\n\n menu->addSeparator();\n menu->addAction(\"Import Objects...\", this, SLOT(slot_import_objects()));\n\n return menu;\n}\n\nvoid ObjectCollectionItem::slot_import_objects()\n{\n QFileDialog::Options options;\n QString selected_filter;\n\n const QStringList filepaths =\n QFileDialog::getOpenFileNames(\n treeWidget(),\n \"Import Objects...\",\n m_settings.get_path_optional(LAST_DIRECTORY_SETTINGS_KEY),\n \"Geometry Files (*.abc; *.binarymesh; *.obj);;All Files (*.*)\",\n &selected_filter,\n options);\n\n if (filepaths.empty())\n return;\n\n const filesystem::path path(\n QDir::toNativeSeparators(filepaths.first()).toStdString());\n\n m_settings.insert_path(\n LAST_DIRECTORY_SETTINGS_KEY,\n path.parent_path().string());\n\n if (m_project_builder.get_rendering_manager().is_rendering())\n schedule_import_objects(filepaths);\n else import_objects(filepaths);\n\n}\n\nnamespace\n{\n class ImportObjectsDelayedAction\n : public RenderingManager::IDelayedAction\n {\n public:\n ImportObjectsDelayedAction(\n ObjectCollectionItem* parent,\n const QStringList& filepaths)\n : m_parent(parent)\n , m_filepaths(filepaths)\n {\n }\n\n virtual void operator()(\n MasterRenderer& master_renderer,\n Project& project) OVERRIDE\n {\n m_parent->import_objects(m_filepaths);\n }\n\n private:\n ObjectCollectionItem* m_parent;\n const QStringList m_filepaths;\n };\n}\n\nvoid ObjectCollectionItem::schedule_import_objects(const QStringList& filepaths)\n{\n m_project_builder.get_rendering_manager().push_delayed_action(\n auto_ptr(\n new ImportObjectsDelayedAction(this, filepaths)));\n\n m_project_builder.get_rendering_manager().reinitialize_rendering();\n}\n\nvoid ObjectCollectionItem::import_objects(const QStringList& filepaths)\n{\n for (int i = 0; i < filepaths.size(); ++i)\n insert_objects(QDir::toNativeSeparators(filepaths[i]).toStdString());\n}\n\nvoid ObjectCollectionItem::insert_objects(const string& path) const\n{\n const string base_object_name =\n filesystem::path(path).replace_extension().filename().string();\n\n ParamArray params;\n params.insert(\"filename\", path);\n\n SearchPaths search_paths;\n MeshObjectArray mesh_objects;\n\n if (!MeshObjectReader().read(\n search_paths,\n base_object_name.c_str(),\n params,\n mesh_objects))\n return;\n\n for (size_t i = 0; i < mesh_objects.size(); ++i)\n {\n MeshObject* object = mesh_objects[i];\n\n m_parent_item->add_item(object);\n\n m_parent.objects().insert(auto_release_ptr(object));\n\n const string object_instance_name = string(object->get_name()) + \"_inst\";\n \n auto_release_ptr object_instance(\n ObjectInstanceFactory::create(\n object_instance_name.c_str(),\n ParamArray(),\n object->get_name(),\n Transformd::identity(),\n StringDictionary()));\n\n m_parent_item->add_item(object_instance.get());\n\n m_parent.object_instances().insert(object_instance);\n }\n\n if (!mesh_objects.empty())\n {\n m_parent.bump_version_id();\n m_project_builder.notify_project_modification();\n }\n}\n\nItemBase* ObjectCollectionItem::create_item(Object* object)\n{\n assert(object);\n\n ItemBase* item =\n new ObjectItem(\n object,\n m_parent,\n m_parent_item,\n m_project_builder);\n\n m_project_builder.get_item_registry().insert(object->get_uid(), item);\n\n return item;\n}\n\n} \/\/ namespace studio\n} \/\/ namespace appleseed\n<|endoftext|>"} {"text":"\/\/ ROS Libraries\n#include \n#include \n#include \n\/\/ Standard Libraries\n#include \n#include \n\ndouble linear_x=0;\ndouble angular_z=0;\n\n\/\/ Defines\n#define Joystick_Buttons_Left_Right msg->axes[4]\n#define Joystick_Buttons_Up_Down msg->axes[5]\n#define Joystick_AnalogLeft_Left_Right msg->axes[0]\n#define Joystick_AnalogLeft_Up_Down msg->axes[1]\n\n\/\/ Callback Functions\nvoid Joy_Callback (const sensor_msgs::Joy::ConstPtr& msg)\n{\n\/* for (unsigned i = 0; i < msg->axes.size(); ++i) {\n ROS_INFO(\"Axis %d is now at position %f\", i, msg->axes[i]);\n }\n*\/\n\n \/\/ Joystick Buttons pressed?\n if (Joystick_Buttons_Left_Right==1) {\n angular_z=Joystick_Buttons_Left_Right;\n }\n if (Joystick_Buttons_Left_Right==-1) {\n angular_z=Joystick_Buttons_Left_Right;\n }\n if (Joystick_Buttons_Up_Down==1) {\n linear_x=Joystick_Buttons_Up_Down;\n }\n if (Joystick_Buttons_Up_Down==-1) {\n linear_x=Joystick_Buttons_Up_Down;\n }\n if (Joystick_Buttons_Up_Down==0) {\n linear_x=Joystick_Buttons_Up_Down;\n }\n if (Joystick_Buttons_Left_Right==0) {\n angular_z=Joystick_Buttons_Up_Down;\n }\n\n \/\/ Joystick Analog pressed?\n if (Joystick_AnalogLeft_Left_Right>0) {\n angular_z=Joystick_AnalogLeft_Left_Right;\n }\n if (Joystick_AnalogLeft_Left_Right<0) {\n angular_z=Joystick_AnalogLeft_Left_Right;\n }\n if (Joystick_AnalogLeft_Up_Down>0) {\n linear_x=Joystick_AnalogLeft_Up_Down;\n }\n if (Joystick_AnalogLeft_Up_Down<0) {\n linear_x=Joystick_AnalogLeft_Up_Down;\n }\n if (Joystick_AnalogLeft_Up_Down==0) {\n linear_x=Joystick_AnalogLeft_Up_Down;\n }\n if (Joystick_AnalogLeft_Left_Right==0) {\n angular_z=Joystick_AnalogLeft_Left_Right;\n }\n\n}\n\nvoid onExit( void )\n{\n \/\/ Run cleanup code here!\n ROS_INFO(\"joystick_driver: Exit node\");\n}\n\nint main(int argc, char **argv){\n\n atexit(onExit);\n\n ros::init(argc, argv, \"joystick_driver\");\n ros::NodeHandle n;\n ros::Subscriber sub = n.subscribe(\"joy\", 100, Joy_Callback);\n ros::Publisher cmd_vel_pub = n.advertise(\"\/cmd_vel\", 100);\n ros::Rate loop_rate(50); \/\/Sets the loop to publish at a rate of 10Hz\n geometry_msgs::Twist cmd_vel_msg; \/\/Declares the message to be sent\n\n while (n.ok()){\n\n if ((cmd_vel_msg.linear.x != linear_x) || (cmd_vel_msg.angular.z != angular_z)){\n cmd_vel_msg.linear.x=linear_x;\n cmd_vel_msg.angular.z=angular_z;\n cmd_vel_pub.publish(cmd_vel_msg);\n ROS_INFO(\"linear.x = %f angular.z = %f\",cmd_vel_msg.linear.x,cmd_vel_msg.angular.z);\n }\n\n\n ros::spinOnce();\n loop_rate.sleep();\n }\/\/end.mainloop\n\n return 0;\n}\/\/end.main\n\nupdate joystick_driver\/\/ ROS Libraries\n#include \n#include \n#include \n\/\/ Standard Libraries\n#include \n#include \n\nfloat linear_x_button=0;\nfloat angular_z_button=0;\nfloat linear_x_stick=0;\nfloat angular_z_stick=0;\n\nbool stick_up_down_pressed=false;\nbool stick_left_right_pressed=false;\nbool button_up_down_pressed=false;\nbool button_left_right_pressed=false;\n\n\/\/ Defines\n#define Joystick_Stick_Left_Right msg->axes[4]\n#define Joystick_Stick_Up_Down msg->axes[5]\n#define Joystick_Button_Left_Right msg->axes[0]\n#define Joystick_Button_Up_Down msg->axes[1]\n\n\/\/ Callback Functions\nvoid Joy_Callback (const sensor_msgs::Joy::ConstPtr& msg)\n{\n\/\/ for (unsigned i = 0; i < msg->axes.size(); ++i) {\n\/\/ ROS_INFO(\"Axis %d is now at position %f\", i, msg->axes[i]);\n\/\/ }\n\n \/\/ Test if joystick buttons are pressed?\n if (Joystick_Button_Left_Right>0) {\n angular_z_button=Joystick_Button_Left_Right;\n button_left_right_pressed=true;\n }\n if (Joystick_Button_Left_Right<0) {\n angular_z_button=Joystick_Button_Left_Right;\n button_left_right_pressed=true;\n }\n if (Joystick_Button_Up_Down>0) {\n linear_x_button=Joystick_Button_Up_Down\/5;\n button_up_down_pressed=true;\n }\n if (Joystick_Button_Up_Down<0) {\n linear_x_button=Joystick_Button_Up_Down\/5;\n button_up_down_pressed=true;\n }\n if (Joystick_Button_Up_Down==0) {\n linear_x_button=Joystick_Button_Up_Down;\n button_up_down_pressed=false;\n }\n if (Joystick_Button_Left_Right==0) {\n angular_z_button=Joystick_Button_Left_Right;\n button_left_right_pressed=false;\n }\n\n \/\/ Test if joystick stick is pressed?\n if (Joystick_Stick_Left_Right>0) {\n angular_z_stick=Joystick_Stick_Left_Right;\n stick_left_right_pressed=true;\n }\n if (Joystick_Stick_Left_Right<0) {\n angular_z_stick=Joystick_Stick_Left_Right;\n stick_left_right_pressed=true;\n }\n if (Joystick_Stick_Up_Down>0) {\n linear_x_stick=Joystick_Stick_Up_Down\/5;\n stick_up_down_pressed=true;\n }\n if (Joystick_Stick_Up_Down<0) {\n linear_x_stick=Joystick_Stick_Up_Down\/5;\n stick_up_down_pressed=true;\n }\n if (Joystick_Stick_Up_Down==0) {\n linear_x_stick=Joystick_Stick_Up_Down;\n stick_up_down_pressed=false;\n }\n if (Joystick_Stick_Left_Right==0) {\n angular_z_stick=Joystick_Stick_Left_Right;\n stick_left_right_pressed=false;\n }\n\n\n}\n\nvoid onExit( void )\n{\n \/\/ Run cleanup code here!\n ROS_INFO(\"joystick_driver: Exit node\");\n}\n\nint main(int argc, char **argv)\n{\n atexit(onExit);\n ros::init(argc, argv, \"joystick_driver\");\n ros::NodeHandle n;\n ros::Subscriber sub = n.subscribe(\"joy\", 100, Joy_Callback);\n ros::Publisher cmd_vel_pub = n.advertise(\"\/cmd_vel\", 100);\n ros::Rate loop_rate(50); \/\/Sets the loop to publish at a rate of 10Hz\n geometry_msgs::Twist cmd_vel_msg; \/\/Declares the message to be sent\n while (n.ok()){ \n\n if ((stick_left_right_pressed==false) && (stick_up_down_pressed==false))\n {\n if ((cmd_vel_msg.linear.x != linear_x_button) || (cmd_vel_msg.angular.z != angular_z_button)){\n cmd_vel_msg.linear.x=linear_x_button;\n cmd_vel_msg.angular.z=angular_z_button;\n cmd_vel_pub.publish(cmd_vel_msg);\n ROS_INFO(\"linear.x = %f angular.z = %f\",cmd_vel_msg.linear.x,cmd_vel_msg.angular.z);\n }\n }\n if ((button_left_right_pressed==false) && (button_up_down_pressed==false))\n {\n if ((cmd_vel_msg.linear.x != linear_x_stick) || (cmd_vel_msg.angular.z != angular_z_stick)){\n cmd_vel_msg.linear.x=linear_x_stick;\n cmd_vel_msg.angular.z=angular_z_stick;\n cmd_vel_pub.publish(cmd_vel_msg);\n ROS_INFO(\"linear.x = %f angular.z = %f\",cmd_vel_msg.linear.x,cmd_vel_msg.angular.z);\n }\n }\n\n ros::spinOnce();\n loop_rate.sleep();\n }\/\/end.mainloop\n return 0;\n}\/\/end.main\n\n<|endoftext|>"} {"text":"#pragma once\n\n\/\/ TODO: Move all constants into generic, hotreloadable constants file\n#include \"Graphics\/RendererTypes.hpp\" \/\/ For NUM_SHADOW_CASCADES\n\nnamespace flex\n{\n\tclass BaseCamera\n\t{\n\tpublic:\n\t\tBaseCamera(const std::string& cameraName, bool bIsGameplayCam, real FOV = glm::radians(45.0f),\n\t\t\treal zNear = 0.5f, real zFar = 350.0f);\n\t\tvirtual ~BaseCamera();\n\n\t\tvirtual void Initialize();\n\t\tvirtual void Update();\n\t\tvirtual void Destroy();\n\n\t\tvirtual void OnSceneChanged();\n\n\t\tvirtual void OnPossess();\n\t\tvirtual void OnDepossess();\n\n\t\tvirtual void DrawImGuiObjects();\n\n\t\tvoid SetFOV(real FOV);\n\t\treal GetFOV() const;\n\t\tvoid SetZNear(real zNear);\n\t\treal GetZNear() const;\n\t\tvoid SetZFar(real zFar);\n\t\treal GetZFar() const;\n\t\tglm::mat4 GetViewProjection() const;\n\t\tglm::mat4 GetView() const;\n\t\tglm::mat4 GetProjection() const;\n\n\t\t\/\/ speed: Lerp amount to new rotation\n\t\tvoid LookAt(glm::vec3 point, real speed = 1.0f);\n\n\t\tvoid Translate(glm::vec3 translation);\n\t\tvoid SetPosition(glm::vec3 position);\n\t\tglm::vec3 GetPosition() const;\n\n\t\tvoid SetViewDirection(real yawRad, real pitchRad);\n\n\t\tglm::vec3 GetRight() const;\n\t\tglm::vec3 GetUp() const;\n\t\tglm::vec3 GetForward() const;\n\n\t\tvoid ResetPosition();\n\t\tvoid ResetOrientation();\n\n\t\tvoid SetYaw(real rawRad);\n\t\treal GetYaw() const;\n\t\tvoid SetPitch(real pitchRad);\n\t\treal GetPitch() const;\n\n\t\tvoid SetMoveSpeed(real moveSpeed);\n\t\treal GetMoveSpeed() const;\n\t\tvoid SetRotationSpeed(real rotationSpeed);\n\t\treal GetRotationSpeed() const;\n\n\t\tstd::string GetName() const;\n\n\t\tvoid CalculateExposure();\n\n\t\t\/\/ Exposure control\n\t\treal aperture = 1.0f; \/\/ f-stops\n\t\treal shutterSpeed = 1.0f \/ 8.0f; \/\/ seconds\n\t\treal lightSensitivity = 800.0f; \/\/ ISO\n\t\treal exposure = 0.0f;\n\n\t\tbool bIsGameplayCam;\n\t\tbool bDEBUGCyclable = true;\n\n\tprotected:\n\t\t\/\/ Sets m_Right, m_Up, and m_Forward based on m_Yaw and m_Pitch\n\t\tvoid CalculateAxisVectorsFromPitchAndYaw();\n\t\tvoid CalculateYawAndPitchFromForward();\n\t\tvoid RecalculateViewProjection();\n\n\t\tvoid JitterMatrix(glm::mat4& matrix);\n\t\tvoid ClampPitch();\n\n\t\t\/\/ Exposure calculations taken from Google's Filament rendering engine\n\t\t\/\/ Computes the camera's EV100\n\t\t\/\/ aperture measured in f-stops\n\t\t\/\/ shutterSpeed measured in seconds\n\t\t\/\/ sensitivity measured in ISO\n\t\tstatic real CalculateEV100(real aperture, real shutterSpeed, real sensitivity);\n\n\t\t\/\/ Computes the exposure normalization factor from the camera's EV100\n\t\tstatic real ComputeExposureNormFactor(real EV100);\n\n\t\tbool m_bInitialized = false;\n\n\t\tstd::string m_Name;\n\n\t\tglm::mat4 m_View;\n\t\tglm::mat4 m_Proj;\n\t\tglm::mat4 m_ViewProjection;\n\n\t\treal m_FOV = 0.0f;\n\t\treal m_ZNear = 0.0f;\n\t\treal m_ZFar = 0.0f;\n\n\t\treal m_MoveSpeed = 0.0f;\t\t\t\t\/\/ WASD or gamepad left stick\n\t\treal m_PanSpeed = 0.0f;\t\t\t\t\t\/\/ MMB\n\t\treal m_DragDollySpeed = 0.0f;\t\t\t\/\/ RMB\n\t\treal m_ScrollDollySpeed = 0.0f;\t\t\t\/\/ Scroll wheel\n\t\treal m_OrbitingSpeed = 0.0f;\t\t\t\/\/ Alt-LMB drag\n\t\treal m_MouseRotationSpeed = 0.0f;\t\t\/\/ LMB drag\n\t\treal m_GamepadRotationSpeed = 0.0f;\t\t\/\/ Gamepad right stick\n\t\treal m_MoveSpeedFastMultiplier = 0.0f;\n\t\treal m_MoveSpeedSlowMultiplier = 0.0f;\n\t\treal m_TurnSpeedFastMultiplier = 0.0f;\n\t\treal m_TurnSpeedSlowMultiplier = 0.0f;\n\t\treal m_PanSpeedFastMultiplier = 0.0f;\n\t\treal m_PanSpeedSlowMultiplier = 0.0f;\n\t\treal m_RollRestorationSpeed = 0.0f;\n\n\t\tglm::vec3 m_Position;\n\n\t\treal m_Yaw;\n\t\treal m_Pitch;\n\t\treal m_Roll;\n\t\tglm::vec3 m_Forward;\n\t\tglm::vec3 m_Up;\n\t\tglm::vec3 m_Right;\n\n\t\tglm::mat4 m_ShadowProjectionMats[NUM_SHADOW_CASCADES];\n\t};\n} \/\/ namespace flex\nSet better initial camera far plane value#pragma once\n\n\/\/ TODO: Move all constants into generic, hotreloadable constants file\n#include \"Graphics\/RendererTypes.hpp\" \/\/ For NUM_SHADOW_CASCADES\n\nnamespace flex\n{\n\tclass BaseCamera\n\t{\n\tpublic:\n\t\tBaseCamera(const std::string& cameraName, bool bIsGameplayCam, real FOV = glm::radians(45.0f),\n\t\t\treal zNear = 0.5f, real zFar = 1000.0f);\n\t\tvirtual ~BaseCamera();\n\n\t\tvirtual void Initialize();\n\t\tvirtual void Update();\n\t\tvirtual void Destroy();\n\n\t\tvirtual void OnSceneChanged();\n\n\t\tvirtual void OnPossess();\n\t\tvirtual void OnDepossess();\n\n\t\tvirtual void DrawImGuiObjects();\n\n\t\tvoid SetFOV(real FOV);\n\t\treal GetFOV() const;\n\t\tvoid SetZNear(real zNear);\n\t\treal GetZNear() const;\n\t\tvoid SetZFar(real zFar);\n\t\treal GetZFar() const;\n\t\tglm::mat4 GetViewProjection() const;\n\t\tglm::mat4 GetView() const;\n\t\tglm::mat4 GetProjection() const;\n\n\t\t\/\/ speed: Lerp amount to new rotation\n\t\tvoid LookAt(glm::vec3 point, real speed = 1.0f);\n\n\t\tvoid Translate(glm::vec3 translation);\n\t\tvoid SetPosition(glm::vec3 position);\n\t\tglm::vec3 GetPosition() const;\n\n\t\tvoid SetViewDirection(real yawRad, real pitchRad);\n\n\t\tglm::vec3 GetRight() const;\n\t\tglm::vec3 GetUp() const;\n\t\tglm::vec3 GetForward() const;\n\n\t\tvoid ResetPosition();\n\t\tvoid ResetOrientation();\n\n\t\tvoid SetYaw(real rawRad);\n\t\treal GetYaw() const;\n\t\tvoid SetPitch(real pitchRad);\n\t\treal GetPitch() const;\n\n\t\tvoid SetMoveSpeed(real moveSpeed);\n\t\treal GetMoveSpeed() const;\n\t\tvoid SetRotationSpeed(real rotationSpeed);\n\t\treal GetRotationSpeed() const;\n\n\t\tstd::string GetName() const;\n\n\t\tvoid CalculateExposure();\n\n\t\t\/\/ Exposure control\n\t\treal aperture = 1.0f; \/\/ f-stops\n\t\treal shutterSpeed = 1.0f \/ 8.0f; \/\/ seconds\n\t\treal lightSensitivity = 800.0f; \/\/ ISO\n\t\treal exposure = 0.0f;\n\n\t\tbool bIsGameplayCam;\n\t\tbool bDEBUGCyclable = true;\n\n\tprotected:\n\t\t\/\/ Sets m_Right, m_Up, and m_Forward based on m_Yaw and m_Pitch\n\t\tvoid CalculateAxisVectorsFromPitchAndYaw();\n\t\tvoid CalculateYawAndPitchFromForward();\n\t\tvoid RecalculateViewProjection();\n\n\t\tvoid JitterMatrix(glm::mat4& matrix);\n\t\tvoid ClampPitch();\n\n\t\t\/\/ Exposure calculations taken from Google's Filament rendering engine\n\t\t\/\/ Computes the camera's EV100\n\t\t\/\/ aperture measured in f-stops\n\t\t\/\/ shutterSpeed measured in seconds\n\t\t\/\/ sensitivity measured in ISO\n\t\tstatic real CalculateEV100(real aperture, real shutterSpeed, real sensitivity);\n\n\t\t\/\/ Computes the exposure normalization factor from the camera's EV100\n\t\tstatic real ComputeExposureNormFactor(real EV100);\n\n\t\tbool m_bInitialized = false;\n\n\t\tstd::string m_Name;\n\n\t\tglm::mat4 m_View;\n\t\tglm::mat4 m_Proj;\n\t\tglm::mat4 m_ViewProjection;\n\n\t\treal m_FOV = 0.0f;\n\t\treal m_ZNear = 0.0f;\n\t\treal m_ZFar = 0.0f;\n\n\t\treal m_MoveSpeed = 0.0f;\t\t\t\t\/\/ WASD or gamepad left stick\n\t\treal m_PanSpeed = 0.0f;\t\t\t\t\t\/\/ MMB\n\t\treal m_DragDollySpeed = 0.0f;\t\t\t\/\/ RMB\n\t\treal m_ScrollDollySpeed = 0.0f;\t\t\t\/\/ Scroll wheel\n\t\treal m_OrbitingSpeed = 0.0f;\t\t\t\/\/ Alt-LMB drag\n\t\treal m_MouseRotationSpeed = 0.0f;\t\t\/\/ LMB drag\n\t\treal m_GamepadRotationSpeed = 0.0f;\t\t\/\/ Gamepad right stick\n\t\treal m_MoveSpeedFastMultiplier = 0.0f;\n\t\treal m_MoveSpeedSlowMultiplier = 0.0f;\n\t\treal m_TurnSpeedFastMultiplier = 0.0f;\n\t\treal m_TurnSpeedSlowMultiplier = 0.0f;\n\t\treal m_PanSpeedFastMultiplier = 0.0f;\n\t\treal m_PanSpeedSlowMultiplier = 0.0f;\n\t\treal m_RollRestorationSpeed = 0.0f;\n\n\t\tglm::vec3 m_Position;\n\n\t\treal m_Yaw;\n\t\treal m_Pitch;\n\t\treal m_Roll;\n\t\tglm::vec3 m_Forward;\n\t\tglm::vec3 m_Up;\n\t\tglm::vec3 m_Right;\n\n\t\tglm::mat4 m_ShadowProjectionMats[NUM_SHADOW_CASCADES];\n\t};\n} \/\/ namespace flex\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2010, Google Inc.\n\/\/ All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are\n\/\/ met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright\n\/\/ notice, this list of conditions and the following disclaimer.\n\/\/ * Redistributions in binary form must reproduce the above\n\/\/ copyright notice, this list of conditions and the following disclaimer\n\/\/ in the documentation and\/or other materials provided with the\n\/\/ distribution.\n\/\/ * Neither the name of Google Inc. nor the names of its\n\/\/ contributors may be used to endorse or promote products derived from\n\/\/ this software without specific prior written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\/\/ \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n\/\/ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n\/\/ A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n\/\/ OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n\/\/ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n\/\/ LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n\/\/ DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n\/\/ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n\/\/ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n\/\/ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\/\/\n\/\/ Helper program for the linux_dumper class, which creates a bunch of\n\/\/ threads. The first word of each thread's stack is set to the thread\n\/\/ id.\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"third_party\/lss\/linux_syscall_support.h\"\n\n#if defined(__ARM_EABI__)\n#define TID_PTR_REGISTER \"r3\"\n#elif defined(__i386)\n#define TID_PTR_REGISTER \"ecx\"\n#elif defined(__x86_64)\n#define TID_PTR_REGISTER \"rcx\"\n#else\n#error This test has not been ported to this platform.\n#endif\n\nvoid *thread_function(void *data) {\n volatile pid_t thread_id = syscall(__NR_gettid);\n register volatile pid_t *thread_id_ptr asm(TID_PTR_REGISTER) = &thread_id;\n while (true)\n asm volatile (\"\" : : \"r\" (thread_id_ptr));\n return NULL;\n}\n\nint main(int argc, char *argv[]) {\n if (argc < 2) {\n fprintf(stderr,\n \"usage: linux_dumper_unittest_helper <# of threads\\n\");\n return 1;\n }\n int pipefd = atoi(argv[1]);\n int num_threads = atoi(argv[2]);\n if (num_threads < 1) {\n fprintf(stderr, \"ERROR: number of threads is 0\");\n return 1;\n }\n pthread_t threads[num_threads];\n pthread_attr_t thread_attributes;\n pthread_attr_init(&thread_attributes);\n pthread_attr_setdetachstate(&thread_attributes, PTHREAD_CREATE_DETACHED);\n for (int i = 1; i < num_threads; i++) {\n pthread_create(&threads[i], &thread_attributes, &thread_function, NULL);\n }\n \/\/ Signal parent that this process has started all threads.\n uint8_t byte = 1;\n write(pipefd, &byte, sizeof(byte));\n thread_function(NULL);\n return 0;\n}\nFix several issues in linux_dumper_unittest_helper Patch by Chris Dearman R=ted at http:\/\/breakpad.appspot.com\/369001\/\/\/ Copyright (c) 2010, Google Inc.\n\/\/ All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are\n\/\/ met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright\n\/\/ notice, this list of conditions and the following disclaimer.\n\/\/ * Redistributions in binary form must reproduce the above\n\/\/ copyright notice, this list of conditions and the following disclaimer\n\/\/ in the documentation and\/or other materials provided with the\n\/\/ distribution.\n\/\/ * Neither the name of Google Inc. nor the names of its\n\/\/ contributors may be used to endorse or promote products derived from\n\/\/ this software without specific prior written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\/\/ \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n\/\/ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n\/\/ A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n\/\/ OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n\/\/ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n\/\/ LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n\/\/ DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n\/\/ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n\/\/ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n\/\/ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\/\/\n\/\/ Helper program for the linux_dumper class, which creates a bunch of\n\/\/ threads. The first word of each thread's stack is set to the thread\n\/\/ id.\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"third_party\/lss\/linux_syscall_support.h\"\n\n#if defined(__ARM_EABI__)\n#define TID_PTR_REGISTER \"r3\"\n#elif defined(__i386)\n#define TID_PTR_REGISTER \"ecx\"\n#elif defined(__x86_64)\n#define TID_PTR_REGISTER \"rcx\"\n#else\n#error This test has not been ported to this platform.\n#endif\n\nvoid *thread_function(void *data) {\n volatile pid_t thread_id = syscall(__NR_gettid);\n register volatile pid_t *thread_id_ptr asm(TID_PTR_REGISTER) = &thread_id;\n while (true)\n asm volatile (\"\" : : \"r\" (thread_id_ptr));\n return NULL;\n}\n\nint main(int argc, char *argv[]) {\n if (argc < 3) {\n fprintf(stderr,\n \"usage: linux_dumper_unittest_helper <# of threads>\\n\");\n return 1;\n }\n int pipefd = atoi(argv[1]);\n int num_threads = atoi(argv[2]);\n if (num_threads < 1) {\n fprintf(stderr, \"ERROR: number of threads is 0\");\n return 1;\n }\n pthread_t threads[num_threads];\n pthread_attr_t thread_attributes;\n pthread_attr_init(&thread_attributes);\n pthread_attr_setdetachstate(&thread_attributes, PTHREAD_CREATE_DETACHED);\n for (int i = 1; i < num_threads; i++) {\n pthread_create(&threads[i], &thread_attributes, &thread_function, NULL);\n }\n \/\/ Signal parent that this process has started all threads.\n uint8_t byte = 1;\n if (write(pipefd, &byte, sizeof(byte)) != sizeof(byte)) {\n perror(\"ERROR: parent notification failed\");\n return 1;\n }\n thread_function(NULL);\n return 0;\n}\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: appdata.cxx,v $\n *\n * $Revision: 1.28 $\n *\n * last change: $Author: obo $ $Date: 2008-01-04 15:09:12 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_sfx2.hxx\"\n#ifndef _CACHESTR_HXX \/\/autogen\n#include \n#endif\n#ifndef _CONFIG_HXX\n#include \n#endif\n#ifndef _INETSTRM_HXX \/\/autogen\n#include \n#endif\n#ifndef _SFXSTRITEM_HXX \/\/autogen\n#include \n#endif\n\n#define _SVSTDARR_STRINGS\n#include \n#include \n\n#include \n\n#ifndef _LOGINERR_HXX\n#include \n#endif\n#ifndef _SV_MSGBOX_HXX\n#include \n#endif\n#ifndef _DATETIMEITEM_HXX \/\/autogen\n#include \n#endif\n#ifndef _SV_MENU_HXX\n#include \n#endif\n#ifndef _SV_WRKWIN_HXX\n#include \n#endif\n#include \"comphelper\/processfactory.hxx\"\n\n#include \n#include \"appdata.hxx\"\n#include \n#include \n#include \"sfxtypes.hxx\"\n#include \n#include \"arrdecl.hxx\"\n#include \n#include \n#include \n#include \"referers.hxx\"\n#include \"app.hrc\"\n#include \"sfxresid.hxx\"\n#include \"objshimp.hxx\"\n#include \n#include \"imestatuswindow.hxx\"\n#include \"appbaslib.hxx\"\n\n#include \n#include \n\nusing ::basic::BasicManagerRepository;\nusing ::basic::BasicManagerCreationListener;\nusing ::com::sun::star::uno::Reference;\nusing ::com::sun::star::frame::XModel;\n\nclass SfxBasicManagerCreationListener : public ::basic::BasicManagerCreationListener\n{\nprivate:\n SfxAppData_Impl& m_rAppData;\n\npublic:\n SfxBasicManagerCreationListener( SfxAppData_Impl& _rAppData ) :m_rAppData( _rAppData ) { }\n\n virtual void onBasicManagerCreated( const Reference< XModel >& _rxForDocument, BasicManager& _rBasicManager );\n};\n\nvoid SfxBasicManagerCreationListener::onBasicManagerCreated( const Reference< XModel >& _rxForDocument, BasicManager& _rBasicManager )\n{\n if ( _rxForDocument == NULL )\n m_rAppData.OnApplicationBasicManagerCreated( _rBasicManager );\n}\n\nSfxAppData_Impl::SfxAppData_Impl( SfxApplication* pApp ) :\n pDdeService( 0 ),\n pDocTopics( 0 ),\n pTriggerTopic(0),\n pDdeService2(0),\n pFactArr(0),\n pTopFrames( new SfxFrameArr_Impl ),\n pInitLinkList(0),\n pMatcher( 0 ),\n pCancelMgr( 0 ),\n pLabelResMgr( 0 ),\n pAppDispatch(NULL),\n pTemplates( 0 ),\n pPool(0),\n pEventConfig(0),\n pDisabledSlotList( 0 ),\n pSecureURLs(0),\n pMiscConfig(0),\n pSaveOptions( 0 ),\n pUndoOptions( 0 ),\n pHelpOptions( 0 ),\n m_xThisDocument( ),\n pProgress(0),\n pTemplateCommon( 0 ),\n nDocModalMode(0),\n nAutoTabPageId(0),\n nBasicCallLevel(0),\n nRescheduleLocks(0),\n nInReschedule(0),\n nAsynchronCalls(0),\n m_xImeStatusWindow(new sfx2::appl::ImeStatusWindow(\n *pApp, comphelper::getProcessServiceFactory()))\n , pTbxCtrlFac(0)\n , pStbCtrlFac(0)\n , pViewFrames(0)\n , pObjShells(0)\n , pSfxResManager(0)\n , pOfaResMgr(0)\n , pSimpleResManager(0)\n , pBasicManager( new SfxBasicManagerHolder )\n , pBasMgrListener( new SfxBasicManagerCreationListener( *this ) )\n , pViewFrame( 0 )\n , pSlotPool( 0 )\n , pResMgr( 0 )\n , pAppDispat( 0 )\n , pInterfaces( 0 )\n , nDocNo(0)\n , nInterfaces( 0 )\n , bDowning( sal_True )\n , bInQuit( sal_False )\n , bInvalidateOnUnlock( sal_False )\n , bODFVersionWarningLater( sal_False )\n\n{\n BasicManagerRepository::registerCreationListener( *pBasMgrListener );\n}\n\nSfxAppData_Impl::~SfxAppData_Impl()\n{\n DeInitDDE();\n delete pTopFrames;\n delete pCancelMgr;\n delete pSecureURLs;\n delete pBasicManager;\n\n BasicManagerRepository::revokeCreationListener( *pBasMgrListener );\n delete pBasMgrListener;\n}\n\nvoid SfxAppData_Impl::UpdateApplicationSettings( sal_Bool bDontHide )\n{\n AllSettings aAllSet = Application::GetSettings();\n StyleSettings aStyleSet = aAllSet.GetStyleSettings();\n sal_uInt32 nStyleOptions = aStyleSet.GetOptions();\n if ( bDontHide )\n nStyleOptions &= ~STYLE_OPTION_HIDEDISABLED;\n else\n nStyleOptions |= STYLE_OPTION_HIDEDISABLED;\n aStyleSet.SetOptions( nStyleOptions );\n aAllSet.SetStyleSettings( aStyleSet );\n Application::SetSettings( aAllSet );\n}\n\nSfxDocumentTemplates* SfxAppData_Impl::GetDocumentTemplates()\n{\n if ( !pTemplates )\n pTemplates = new SfxDocumentTemplates;\n else\n pTemplates->ReInitFromComponent();\n return pTemplates;\n}\n\nvoid SfxAppData_Impl::OnApplicationBasicManagerCreated( BasicManager& _rBasicManager )\n{\n pBasicManager->reset( &_rBasicManager );\n\n \/\/ global constants, additionally to the ones already added by createApplicationBasicManager:\n \/\/ ThisComponent\n Reference< XModel > xCurrentDoc;\n SfxObjectShell* pDoc = SfxObjectShell::Current();\n if ( pDoc )\n xCurrentDoc = pDoc->GetModel();\n _rBasicManager.InsertGlobalUNOConstant( \"ThisComponent\", makeAny( xCurrentDoc ) );\n m_xThisDocument = xCurrentDoc;\n}\nINTEGRATION: CWS odbmacros2 (1.27.2); FILE MERGED 2008\/02\/04 13:15:28 fs 1.27.2.4: RESYNC: (1.27-1.28); FILE MERGED 2007\/12\/19 14:51:24 fs 1.27.2.3: #i49133# BasicManager::Insert\/set\/ResetGlobalUNOConstant superseded by SetGlobalUNOConstant 2007\/12\/18 21:15:35 fs 1.27.2.2: #i49133# m_xThisDocument is superfluous, it is always the same as SfxObjectShell's WorkingDocument (which has just been renamed to CurrentComponent) 2007\/12\/12 14:42:09 fs 1.27.2.1: #i49133# use SfxObjectShell::GetWorkingDocument as ThisComponent, not SfxObjectShell::Current\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: appdata.cxx,v $\n *\n * $Revision: 1.29 $\n *\n * last change: $Author: kz $ $Date: 2008-03-06 19:49:18 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_sfx2.hxx\"\n#ifndef _CACHESTR_HXX \/\/autogen\n#include \n#endif\n#ifndef _CONFIG_HXX\n#include \n#endif\n#ifndef _INETSTRM_HXX \/\/autogen\n#include \n#endif\n#ifndef _SFXSTRITEM_HXX \/\/autogen\n#include \n#endif\n\n#define _SVSTDARR_STRINGS\n#include \n#include \n\n#include \n\n#ifndef _LOGINERR_HXX\n#include \n#endif\n#ifndef _SV_MSGBOX_HXX\n#include \n#endif\n#ifndef _DATETIMEITEM_HXX \/\/autogen\n#include \n#endif\n#ifndef _SV_MENU_HXX\n#include \n#endif\n#ifndef _SV_WRKWIN_HXX\n#include \n#endif\n#include \"comphelper\/processfactory.hxx\"\n\n#include \n#include \"appdata.hxx\"\n#include \n#include \n#include \"sfxtypes.hxx\"\n#include \n#include \"arrdecl.hxx\"\n#include \n#include \n#include \n#include \"referers.hxx\"\n#include \"app.hrc\"\n#include \"sfxresid.hxx\"\n#include \"objshimp.hxx\"\n#include \n#include \"imestatuswindow.hxx\"\n#include \"appbaslib.hxx\"\n\n#include \n#include \n\nusing ::basic::BasicManagerRepository;\nusing ::basic::BasicManagerCreationListener;\nusing ::com::sun::star::uno::Reference;\nusing ::com::sun::star::frame::XModel;\nusing ::com::sun::star::uno::XInterface;\n\nclass SfxBasicManagerCreationListener : public ::basic::BasicManagerCreationListener\n{\nprivate:\n SfxAppData_Impl& m_rAppData;\n\npublic:\n SfxBasicManagerCreationListener( SfxAppData_Impl& _rAppData ) :m_rAppData( _rAppData ) { }\n\n virtual void onBasicManagerCreated( const Reference< XModel >& _rxForDocument, BasicManager& _rBasicManager );\n};\n\nvoid SfxBasicManagerCreationListener::onBasicManagerCreated( const Reference< XModel >& _rxForDocument, BasicManager& _rBasicManager )\n{\n if ( _rxForDocument == NULL )\n m_rAppData.OnApplicationBasicManagerCreated( _rBasicManager );\n}\n\nSfxAppData_Impl::SfxAppData_Impl( SfxApplication* pApp ) :\n pDdeService( 0 ),\n pDocTopics( 0 ),\n pTriggerTopic(0),\n pDdeService2(0),\n pFactArr(0),\n pTopFrames( new SfxFrameArr_Impl ),\n pInitLinkList(0),\n pMatcher( 0 ),\n pCancelMgr( 0 ),\n pLabelResMgr( 0 ),\n pAppDispatch(NULL),\n pTemplates( 0 ),\n pPool(0),\n pEventConfig(0),\n pDisabledSlotList( 0 ),\n pSecureURLs(0),\n pMiscConfig(0),\n pSaveOptions( 0 ),\n pUndoOptions( 0 ),\n pHelpOptions( 0 ),\n pProgress(0),\n pTemplateCommon( 0 ),\n nDocModalMode(0),\n nAutoTabPageId(0),\n nBasicCallLevel(0),\n nRescheduleLocks(0),\n nInReschedule(0),\n nAsynchronCalls(0),\n m_xImeStatusWindow(new sfx2::appl::ImeStatusWindow(\n *pApp, comphelper::getProcessServiceFactory()))\n , pTbxCtrlFac(0)\n , pStbCtrlFac(0)\n , pViewFrames(0)\n , pObjShells(0)\n , pSfxResManager(0)\n , pOfaResMgr(0)\n , pSimpleResManager(0)\n , pBasicManager( new SfxBasicManagerHolder )\n , pBasMgrListener( new SfxBasicManagerCreationListener( *this ) )\n , pViewFrame( 0 )\n , pSlotPool( 0 )\n , pResMgr( 0 )\n , pAppDispat( 0 )\n , pInterfaces( 0 )\n , nDocNo(0)\n , nInterfaces( 0 )\n , bDowning( sal_True )\n , bInQuit( sal_False )\n , bInvalidateOnUnlock( sal_False )\n , bODFVersionWarningLater( sal_False )\n\n{\n BasicManagerRepository::registerCreationListener( *pBasMgrListener );\n}\n\nSfxAppData_Impl::~SfxAppData_Impl()\n{\n DeInitDDE();\n delete pTopFrames;\n delete pCancelMgr;\n delete pSecureURLs;\n delete pBasicManager;\n\n BasicManagerRepository::revokeCreationListener( *pBasMgrListener );\n delete pBasMgrListener;\n}\n\nvoid SfxAppData_Impl::UpdateApplicationSettings( sal_Bool bDontHide )\n{\n AllSettings aAllSet = Application::GetSettings();\n StyleSettings aStyleSet = aAllSet.GetStyleSettings();\n sal_uInt32 nStyleOptions = aStyleSet.GetOptions();\n if ( bDontHide )\n nStyleOptions &= ~STYLE_OPTION_HIDEDISABLED;\n else\n nStyleOptions |= STYLE_OPTION_HIDEDISABLED;\n aStyleSet.SetOptions( nStyleOptions );\n aAllSet.SetStyleSettings( aStyleSet );\n Application::SetSettings( aAllSet );\n}\n\nSfxDocumentTemplates* SfxAppData_Impl::GetDocumentTemplates()\n{\n if ( !pTemplates )\n pTemplates = new SfxDocumentTemplates;\n else\n pTemplates->ReInitFromComponent();\n return pTemplates;\n}\n\nvoid SfxAppData_Impl::OnApplicationBasicManagerCreated( BasicManager& _rBasicManager )\n{\n pBasicManager->reset( &_rBasicManager );\n\n \/\/ global constants, additionally to the ones already added by createApplicationBasicManager:\n \/\/ ThisComponent\n Reference< XInterface > xCurrentComponent = SfxObjectShell::GetCurrentComponent();\n _rBasicManager.SetGlobalUNOConstant( \"ThisComponent\", makeAny( xCurrentComponent ) );\n}\n<|endoftext|>"} {"text":"\/\/ Copyright 2014 The Chromium Authors. All rights reserved.\n\/\/ Inspired by Chromium video capture interface\n\/\/ Simplified and stripped from internal base code\n\n#include \"s3d\/video\/capture\/video_capture_device_decklink.h\"\n#include \"s3d\/video\/capture\/decklink.h\"\n\n\/\/ inspiration: https:\/\/forum.blackmagicdesign.com\/viewtopic.php?f=12&t=33269\n\/\/ todo: should verify which pixel format we need (BGRA or RGBA)\n\/\/ todo: should test int64_t instead of long\nclass RGB8VideoFrame : public IDeckLinkVideoFrame {\n public:\n static const int kNbBytesPixel = 4;\n static const BMDPixelFormat kPixelFormat = bmdFormat8BitBGRA;\n\n RGB8VideoFrame(int64_t width, int64_t height, BMDPixelFormat pixelFormat, BMDFrameFlags flags);\n\n \/\/ override these methods for virtual\n int64_t GetWidth() override;\n int64_t GetHeight() override;\n int64_t GetRowBytes() override;\n BMDPixelFormat GetPixelFormat() override;\n BMDFrameFlags GetFlags() override;\n HRESULT GetBytes(\/* out *\/ void** buffer) override;\n\n void resize(int64_t width, int64_t height);\n\n \/\/ Dummy implementations of remaining virtual methods\n HRESULT GetTimecode(BMDTimecodeFormat \/*format*\/, IDeckLinkTimecode** \/*timecode*\/) override {\n return E_NOINTERFACE;\n }\n\n HRESULT GetAncillaryData(IDeckLinkVideoFrameAncillary** \/*ancillary*\/) override {\n return E_NOINTERFACE;\n }\n\n \/\/\n \/\/ IUnknown interface (dummy implementation)\n \/\/\n HRESULT QueryInterface(REFIID \/*iid*\/, LPVOID* \/*ppv*\/) override { return E_NOINTERFACE; }\n ULONG AddRef() override { return 1; }\n ULONG Release() override { return 1; }\n\n private:\n int64_t width_;\n int64_t height_;\n BMDPixelFormat pixelFormat_;\n BMDFrameFlags frameFlags_;\n std::vector bufferPointer_;\n};\n\nRGB8VideoFrame::RGB8VideoFrame(int64_t width,\n int64_t height,\n BMDPixelFormat pixelFormat,\n BMDFrameFlags flags)\n : width_{width}, height_{height}, pixelFormat_{pixelFormat}, frameFlags_{flags} {\n assert(pixelFormat == kPixelFormat);\n bufferPointer_.resize(static_cast(width_ * kNbBytesPixel * height_));\n}\n\nint64_t RGB8VideoFrame::GetWidth() {\n return width_;\n}\n\nint64_t RGB8VideoFrame::GetHeight() {\n return height_;\n}\n\nint64_t RGB8VideoFrame::GetRowBytes() {\n return width_ * kNbBytesPixel;\n}\n\nBMDPixelFormat RGB8VideoFrame::GetPixelFormat() {\n return pixelFormat_;\n}\n\nBMDFrameFlags RGB8VideoFrame::GetFlags() {\n return frameFlags_;\n}\n\nHRESULT RGB8VideoFrame::GetBytes(\/* out *\/ void** buffer) {\n *buffer = static_cast(&bufferPointer_[0]);\n return S_OK;\n}\n\nvoid RGB8VideoFrame::resize(int64_t width, int64_t height) {\n width_ = width;\n height_ = height;\n bufferPointer_.resize(static_cast(width_ * height_ * kNbBytesPixel));\n}\n\n\/\/ todo: better consistency between DeckLink and decklink (camel case?)\nclass DecklinkCaptureDelegate : public IDeckLinkInputCallback {\n public:\n DecklinkCaptureDelegate(const VideoCaptureDeviceDescriptor& device_descriptor,\n VideoCaptureDeviceDecklink* frameReceiver);\n\n ~DecklinkCaptureDelegate() override = default;\n\n void AllocateAndStart(const VideoCaptureFormat& params);\n void StopAndDeAllocate();\n\n const VideoCaptureDeviceDescriptor& getDeviceDescriptor() { return device_descriptor_; }\n\n static bool supportedFormat(const VideoCaptureFormat& format);\n\n void ResetVideoCaptureDeviceReference() { frameReceiver_ = nullptr; }\n\n private:\n \/\/ IDeckLinkInputCallback interface implementation.\n HRESULT VideoInputFormatChanged(BMDVideoInputFormatChangedEvents notification_events,\n IDeckLinkDisplayMode* new_display_mode,\n BMDDetectedVideoInputFormatFlags detected_signal_flags) override;\n HRESULT VideoInputFrameArrived(IDeckLinkVideoInputFrame* videoFrameLeft,\n IDeckLinkAudioInputPacket* audio_packet) override;\n\n ULONG STDMETHODCALLTYPE AddRef() override { return ++refCount_; }\n ULONG STDMETHODCALLTYPE Release() override { return --refCount_; } \/\/ accepted memory leak\n HRESULT STDMETHODCALLTYPE QueryInterface(REFIID \/*iid*\/, LPVOID* \/*ppv*\/) override {\n return E_NOINTERFACE;\n }\n\n \/\/ Forwarder to VideoCaptureDeviceDeckLinkMac::SendErrorString().\n void SendErrorString(const std::string& reason);\n \/\/ Forwarder to VideoCaptureDeviceDeckLinkMac::SendLogString().\n void SendLogString(const std::string& message);\n\n const VideoCaptureDeviceDescriptor device_descriptor_;\n VideoCaptureFormat captureFormat_;\n\n \/\/ Weak reference to the captured frames client, used also for error messages\n \/\/ and logging. Initialized on construction and used until cleared by calling\n \/\/ ResetVideoCaptureDeviceReference().\n VideoCaptureDeviceDecklink* frameReceiver_;\n \/\/ This is used to control the video capturing device input interface.\n SmartDecklinkPtr deckLinkInput_;\n \/\/ |decklink_| represents a physical device attached to the host.\n SmartDecklinkPtr deckLink_;\n\n SmartDecklinkPtr videoConversion_;\n std::unique_ptr rgbFrameLeft_;\n std::unique_ptr rgbFrameRight_;\n\n size_t refCount_;\n\n std::chrono::high_resolution_clock::time_point firstRefTime_;\n};\n\nDecklinkCaptureDelegate::DecklinkCaptureDelegate(\n const VideoCaptureDeviceDescriptor& device_descriptor,\n VideoCaptureDeviceDecklink* frameReceiver)\n : device_descriptor_{device_descriptor},\n captureFormat_{{0, 0}, 0.0f, VideoPixelFormat::UNKNOWN},\n frameReceiver_{frameReceiver},\n rgbFrameLeft_{new RGB8VideoFrame(0, 0, RGB8VideoFrame::kPixelFormat, bmdFrameFlagDefault)},\n rgbFrameRight_{new RGB8VideoFrame(0, 0, RGB8VideoFrame::kPixelFormat, bmdFrameFlagDefault)} {}\n\nvoid DecklinkCaptureDelegate::AllocateAndStart(const VideoCaptureFormat& params) {\n \/\/ Only 1920x1080, 30fps, BGRA, 2D or 3D supported\n \/\/ todo: is it BGRA or ARGB?\n if (!supportedFormat(params)) {\n \/\/ todo: this seems like another type of exception, or a bug?\n throw VideoCaptureDeviceAllocationException(\"Requested format not supported\");\n }\n\n IDeckLinkIterator* deckLinkIterator = CreateDeckLinkIteratorInstance();\n if (deckLinkIterator == nullptr) {\n throw VideoCaptureDeviceAllocationException(\"Error creating DeckLink iterator\");\n }\n\n IDeckLink* deckLink;\n if (deckLinkIterator->Next(&deckLink) != S_OK) {\n throw VideoCaptureDeviceAllocationException(\"No DeckLink device found\");\n }\n\n auto deckLinkInput = make_decklink_ptr(deckLink);\n deckLinkInput->SetCallback(this);\n\n \/\/ Check if display mode is supported\n BMDDisplayModeSupport displayModeSupported;\n\n \/\/ todo: set from capture format\n BMDDisplayMode displayMode = bmdModeHD1080p30;\n BMDPixelFormat pixelFormat = bmdFormat8BitYUV;\n BMDVideoInputFlags videoInputFlag =\n params.stereo3D ? bmdVideoInputDualStream3D : bmdVideoInputFlagDefault;\n\n HRESULT result = deckLinkInput->DoesSupportVideoMode(displayMode, pixelFormat, videoInputFlag,\n &displayModeSupported, nullptr);\n if (result != S_OK) {\n throw VideoCaptureDeviceAllocationException(\"Display mode not supported\");\n }\n\n \/\/ 3D settings for video capture\n if (params.stereo3D) {\n auto decklinkConfiguration = make_decklink_ptr(deckLink);\n if (decklinkConfiguration->SetFlag(bmdDeckLinkConfigSDIInput3DPayloadOverride, true) != S_OK) {\n throw VideoCaptureDeviceAllocationException(\"Cannot set 3D payload override flag\");\n }\n }\n\n \/\/ create decklink conversion for YUV -> RGB\n videoConversion_.reset(CreateVideoConversionInstance());\n\n \/\/ Enable Video Input\n if (deckLinkInput->EnableVideoInput(displayMode, pixelFormat, videoInputFlag) != S_OK) {\n throw VideoCaptureDeviceAllocationException(\"Cannot enable video input\");\n }\n\n \/\/ todo: now it's hardcoded to 1080p, 30fps, BGRA\n captureFormat_ = {params.frameSize, params.frameRate, params.pixelFormat, params.stereo3D};\n deckLink_.reset(deckLink);\n deckLinkInput_.swap(deckLinkInput);\n\n if (deckLinkInput_->StartStreams() != S_OK) {\n throw VideoCaptureDeviceAllocationException(\"Cannot start capture stream\");\n }\n}\n\nHRESULT DecklinkCaptureDelegate::VideoInputFormatChanged(\n BMDVideoInputFormatChangedEvents \/*notification_events*\/,\n IDeckLinkDisplayMode* \/*new_display_mode*\/,\n BMDDetectedVideoInputFormatFlags \/*detected_signal_flags*\/) {\n return S_OK;\n}\n\nHRESULT DecklinkCaptureDelegate::VideoInputFrameArrived(\n IDeckLinkVideoInputFrame* videoFrameLeft,\n IDeckLinkAudioInputPacket* \/*audio_packet*\/) {\n if ((videoFrameLeft->GetFlags() & bmdFrameHasNoInputSource) != 0u) { \/\/ todo: verify this != 0u\n SendErrorString(\"Left frame, no input signal\");\n return S_FALSE;\n }\n\n void* raw_data_left = nullptr;\n void* raw_data_right = nullptr;\n\n uint8_t* video_data_left = nullptr;\n uint8_t* video_data_right = nullptr;\n\n \/\/ get left frame\n rgbFrameLeft_->resize(videoFrameLeft->GetWidth(), videoFrameLeft->GetHeight());\n\n videoConversion_->ConvertFrame(videoFrameLeft,\n static_cast(rgbFrameLeft_.get()));\n rgbFrameLeft_->GetBytes(&raw_data_left);\n video_data_left = static_cast(raw_data_left);\n\n if (captureFormat_.stereo3D) {\n auto threeDExtension = make_decklink_ptr(videoFrameLeft);\n\n \/\/ get right frame\n IDeckLinkVideoFrame* rightEyeFrameRaw = nullptr;\n threeDExtension->GetFrameForRightEye(&rightEyeFrameRaw);\n SmartDecklinkPtr videoFrameRight{rightEyeFrameRaw};\n\n if (videoFrameRight == nullptr) {\n \/\/ todo: this is another type of exception, should it be thrown?\n throw VideoCaptureDeviceAllocationException(\"No right frame detected\");\n }\n\n rgbFrameRight_->resize(videoFrameRight->GetWidth(), videoFrameRight->GetHeight());\n videoConversion_->ConvertFrame(videoFrameRight.get(),\n static_cast(rgbFrameRight_.get()));\n rgbFrameRight_->GetBytes(&raw_data_right);\n video_data_right = static_cast(raw_data_right);\n }\n\n VideoPixelFormat pixelFormat = VideoPixelFormat::UNKNOWN;\n switch (rgbFrameLeft_->GetPixelFormat()) {\n case bmdFormat8BitYUV: \/\/ A.k.a. '2vuy';\n pixelFormat = VideoPixelFormat::UYVY;\n break;\n case bmdFormat8BitBGRA:\n pixelFormat = VideoPixelFormat::ARGB;\n break;\n default:\n SendErrorString(\"Unsupported pixel format\");\n break;\n }\n\n const VideoCaptureFormat capture_format(\n Size(rgbFrameLeft_->GetWidth(),\n rgbFrameLeft_->GetHeight()), \/\/ todo: cast or something (int64_t-> int)\n 0.0f, \/\/ Frame rate is not needed for captured data callback.\n pixelFormat,\n captureFormat_.stereo3D);\n\n if (frameReceiver_ != nullptr) {\n if (captureFormat_.stereo3D) {\n frameReceiver_->OnIncomingCapturedData(\n {{video_data_left, rgbFrameLeft_->GetRowBytes() * rgbFrameLeft_->GetHeight()},\n {video_data_right, rgbFrameRight_->GetRowBytes() * rgbFrameRight_->GetHeight()}},\n capture_format);\n } else {\n frameReceiver_->OnIncomingCapturedData(\n {{video_data_left, rgbFrameLeft_->GetRowBytes() * rgbFrameLeft_->GetHeight()}},\n capture_format);\n }\n }\n\n return S_OK;\n}\n\nvoid DecklinkCaptureDelegate::StopAndDeAllocate() {\n if (deckLinkInput_ == nullptr) {\n return;\n }\n if (deckLinkInput_->StopStreams() != S_OK) {\n SendLogString(\"Problem stopping capture.\");\n }\n deckLinkInput_->SetCallback(nullptr);\n deckLinkInput_->DisableVideoInput();\n deckLinkInput_.reset(nullptr);\n deckLink_.reset(nullptr);\n ResetVideoCaptureDeviceReference();\n}\n\n\/\/ static\nbool DecklinkCaptureDelegate::supportedFormat(const VideoCaptureFormat& format) {\n return format.frameSize == Size(1920, 1080) && format.frameRate == 30.0f &&\n format.pixelFormat == VideoPixelFormat::ARGB;\n}\n\nvoid DecklinkCaptureDelegate::SendErrorString(const std::string& reason) {\n if (frameReceiver_ != nullptr) {\n frameReceiver_->SendErrorString(reason);\n }\n}\n\nvoid DecklinkCaptureDelegate::SendLogString(const std::string& message) {\n if (frameReceiver_ != nullptr) {\n frameReceiver_->SendLogString(message);\n }\n}\n\nVideoCaptureDeviceDecklink::VideoCaptureDeviceDecklink(\n const VideoCaptureDeviceDescriptor& deviceDescriptor)\n : captureDelegate_{new DecklinkCaptureDelegate{deviceDescriptor, this}} {}\n\ngsl::owner VideoCaptureDeviceDecklink::clone() const {\n return new VideoCaptureDeviceDecklink(captureDelegate_->getDeviceDescriptor());\n}\n\nVideoCaptureDeviceDecklink::~VideoCaptureDeviceDecklink() {\n VideoCaptureDeviceDecklink::StopAndDeAllocate();\n}\n\nvoid VideoCaptureDeviceDecklink::AllocateAndStart(\n const VideoCaptureFormat& format,\n std::unique_ptr client) {\n client_ = std::move(client);\n \/\/ todo: should verify that format is supported\n \/\/ todo: should get image size from capture delegate\n captureDelegate_->AllocateAndStart(format);\n}\n\nvoid VideoCaptureDeviceDecklink::StopAndDeAllocate() {\n captureDelegate_->StopAndDeAllocate();\n}\n\nvoid VideoCaptureDeviceDecklink::OnIncomingCapturedData(\n const VideoCaptureDevice::Client::Images& images,\n const VideoCaptureFormat& frameFormat) {\n if (client_ != nullptr) {\n client_->OnIncomingCapturedData(images, frameFormat);\n }\n}\nDecklink capture device small changes (frameRate on callback = -1.0f)\/\/ Copyright 2014 The Chromium Authors. All rights reserved.\n\/\/ Inspired by Chromium video capture interface\n\/\/ Simplified and stripped from internal base code\n\n#include \"s3d\/video\/capture\/video_capture_device_decklink.h\"\n#include \"s3d\/video\/capture\/decklink.h\"\n\n\/\/ inspiration: https:\/\/forum.blackmagicdesign.com\/viewtopic.php?f=12&t=33269\n\/\/ todo: should verify which pixel format we need (BGRA or RGBA)\n\/\/ todo: should test int64_t instead of long\nclass RGB8VideoFrame : public IDeckLinkVideoFrame {\n public:\n static const int kNbBytesPixel = 4;\n static const BMDPixelFormat kPixelFormat = bmdFormat8BitBGRA;\n\n RGB8VideoFrame(int64_t width, int64_t height, BMDPixelFormat pixelFormat, BMDFrameFlags flags);\n\n \/\/ override these methods for virtual\n int64_t GetWidth() override;\n int64_t GetHeight() override;\n int64_t GetRowBytes() override;\n BMDPixelFormat GetPixelFormat() override;\n BMDFrameFlags GetFlags() override;\n HRESULT GetBytes(\/* out *\/ void** buffer) override;\n\n void resize(int64_t width, int64_t height);\n\n \/\/ Dummy implementations of remaining virtual methods\n HRESULT GetTimecode(BMDTimecodeFormat \/*format*\/, IDeckLinkTimecode** \/*timecode*\/) override {\n return E_NOINTERFACE;\n }\n\n HRESULT GetAncillaryData(IDeckLinkVideoFrameAncillary** \/*ancillary*\/) override {\n return E_NOINTERFACE;\n }\n\n \/\/\n \/\/ IUnknown interface (dummy implementation)\n \/\/\n HRESULT QueryInterface(REFIID \/*iid*\/, LPVOID* \/*ppv*\/) override { return E_NOINTERFACE; }\n ULONG AddRef() override { return 1; }\n ULONG Release() override { return 1; }\n\n private:\n int64_t width_;\n int64_t height_;\n BMDPixelFormat pixelFormat_;\n BMDFrameFlags frameFlags_;\n std::vector bufferPointer_;\n};\n\nRGB8VideoFrame::RGB8VideoFrame(int64_t width,\n int64_t height,\n BMDPixelFormat pixelFormat,\n BMDFrameFlags flags)\n : width_{width}, height_{height}, pixelFormat_{pixelFormat}, frameFlags_{flags} {\n assert(pixelFormat == kPixelFormat);\n bufferPointer_.resize(static_cast(width_ * kNbBytesPixel * height_));\n}\n\nint64_t RGB8VideoFrame::GetWidth() {\n return width_;\n}\n\nint64_t RGB8VideoFrame::GetHeight() {\n return height_;\n}\n\nint64_t RGB8VideoFrame::GetRowBytes() {\n return width_ * kNbBytesPixel;\n}\n\nBMDPixelFormat RGB8VideoFrame::GetPixelFormat() {\n return pixelFormat_;\n}\n\nBMDFrameFlags RGB8VideoFrame::GetFlags() {\n return frameFlags_;\n}\n\nHRESULT RGB8VideoFrame::GetBytes(\/* out *\/ void** buffer) {\n *buffer = static_cast(&bufferPointer_[0]);\n return S_OK;\n}\n\nvoid RGB8VideoFrame::resize(int64_t width, int64_t height) {\n width_ = width;\n height_ = height;\n bufferPointer_.resize(static_cast(width_ * height_ * kNbBytesPixel));\n}\n\n\/\/ todo: better consistency between DeckLink and decklink (camel case?)\nclass DecklinkCaptureDelegate : public IDeckLinkInputCallback {\n public:\n DecklinkCaptureDelegate(const VideoCaptureDeviceDescriptor& device_descriptor,\n VideoCaptureDeviceDecklink* frameReceiver);\n\n ~DecklinkCaptureDelegate() override = default;\n\n void AllocateAndStart(const VideoCaptureFormat& params);\n void StopAndDeAllocate();\n\n const VideoCaptureDeviceDescriptor& getDeviceDescriptor() { return device_descriptor_; }\n\n static bool supportedFormat(const VideoCaptureFormat& format);\n\n void ResetVideoCaptureDeviceReference() { frameReceiver_ = nullptr; }\n\n private:\n \/\/ IDeckLinkInputCallback interface implementation.\n HRESULT VideoInputFormatChanged(BMDVideoInputFormatChangedEvents notification_events,\n IDeckLinkDisplayMode* new_display_mode,\n BMDDetectedVideoInputFormatFlags detected_signal_flags) override;\n HRESULT VideoInputFrameArrived(IDeckLinkVideoInputFrame* videoFrameLeft,\n IDeckLinkAudioInputPacket* audio_packet) override;\n\n ULONG STDMETHODCALLTYPE AddRef() override { return ++refCount_; }\n ULONG STDMETHODCALLTYPE Release() override { return --refCount_; } \/\/ accepted memory leak\n HRESULT STDMETHODCALLTYPE QueryInterface(REFIID \/*iid*\/, LPVOID* \/*ppv*\/) override {\n return E_NOINTERFACE;\n }\n\n \/\/ Forwarder to VideoCaptureDeviceDeckLinkMac::SendErrorString().\n void SendErrorString(const std::string& reason);\n \/\/ Forwarder to VideoCaptureDeviceDeckLinkMac::SendLogString().\n void SendLogString(const std::string& message);\n\n const VideoCaptureDeviceDescriptor device_descriptor_;\n VideoCaptureFormat captureFormat_;\n\n \/\/ Weak reference to the captured frames client, used also for error messages\n \/\/ and logging. Initialized on construction and used until cleared by calling\n \/\/ ResetVideoCaptureDeviceReference().\n VideoCaptureDeviceDecklink* frameReceiver_;\n \/\/ This is used to control the video capturing device input interface.\n SmartDecklinkPtr deckLinkInput_;\n \/\/ |decklink_| represents a physical device attached to the host.\n SmartDecklinkPtr deckLink_;\n\n SmartDecklinkPtr videoConversion_;\n std::unique_ptr rgbFrameLeft_;\n std::unique_ptr rgbFrameRight_;\n\n size_t refCount_;\n\n std::chrono::high_resolution_clock::time_point firstRefTime_;\n};\n\nDecklinkCaptureDelegate::DecklinkCaptureDelegate(\n const VideoCaptureDeviceDescriptor& device_descriptor,\n VideoCaptureDeviceDecklink* frameReceiver)\n : device_descriptor_{device_descriptor},\n captureFormat_{{0, 0}, 0.0f, VideoPixelFormat::UNKNOWN},\n frameReceiver_{frameReceiver},\n rgbFrameLeft_{new RGB8VideoFrame(0, 0, RGB8VideoFrame::kPixelFormat, bmdFrameFlagDefault)},\n rgbFrameRight_{new RGB8VideoFrame(0, 0, RGB8VideoFrame::kPixelFormat, bmdFrameFlagDefault)} {}\n\nvoid DecklinkCaptureDelegate::AllocateAndStart(const VideoCaptureFormat& params) {\n \/\/ Only 1920x1080, 30fps, BGRA, 2D or 3D supported\n \/\/ todo: is it BGRA or ARGB?\n if (!supportedFormat(params)) {\n \/\/ todo: this seems like another type of exception, or a bug?\n throw VideoCaptureDeviceAllocationException(\"Requested format not supported\");\n }\n\n IDeckLinkIterator* deckLinkIterator = CreateDeckLinkIteratorInstance();\n if (deckLinkIterator == nullptr) {\n throw VideoCaptureDeviceAllocationException(\"Error creating DeckLink iterator\");\n }\n\n IDeckLink* deckLink;\n if (deckLinkIterator->Next(&deckLink) != S_OK) {\n throw VideoCaptureDeviceAllocationException(\"No DeckLink device found\");\n }\n\n auto deckLinkInput = make_decklink_ptr(deckLink);\n deckLinkInput->SetCallback(this);\n\n \/\/ Check if display mode is supported\n BMDDisplayModeSupport displayModeSupported;\n\n \/\/ todo: set from capture format\n BMDDisplayMode displayMode = bmdModeHD1080p30;\n BMDPixelFormat pixelFormat = bmdFormat8BitYUV;\n BMDVideoInputFlags videoInputFlag =\n params.stereo3D ? bmdVideoInputDualStream3D : bmdVideoInputFlagDefault;\n\n HRESULT result = deckLinkInput->DoesSupportVideoMode(displayMode, pixelFormat, videoInputFlag,\n &displayModeSupported, nullptr);\n if (result != S_OK) {\n throw VideoCaptureDeviceAllocationException(\"Display mode not supported\");\n }\n\n \/\/ 3D settings for video capture\n if (params.stereo3D) {\n auto decklinkConfiguration = make_decklink_ptr(deckLink);\n if (decklinkConfiguration->SetFlag(bmdDeckLinkConfigSDIInput3DPayloadOverride, true) != S_OK) {\n throw VideoCaptureDeviceAllocationException(\"Cannot set 3D payload override flag\");\n }\n }\n\n \/\/ create decklink conversion for YUV -> RGB\n videoConversion_.reset(CreateVideoConversionInstance());\n\n \/\/ Enable Video Input\n if (deckLinkInput->EnableVideoInput(displayMode, pixelFormat, videoInputFlag) != S_OK) {\n throw VideoCaptureDeviceAllocationException(\"Cannot enable video input\");\n }\n\n \/\/ todo: now it's hardcoded to 1080p, 30fps, BGRA\n captureFormat_ = {params.frameSize, params.frameRate, params.pixelFormat, params.stereo3D};\n deckLink_.reset(deckLink);\n deckLinkInput_.swap(deckLinkInput);\n\n if (deckLinkInput_->StartStreams() != S_OK) {\n throw VideoCaptureDeviceAllocationException(\"Cannot start capture stream\");\n }\n}\n\nHRESULT DecklinkCaptureDelegate::VideoInputFormatChanged(\n BMDVideoInputFormatChangedEvents \/*notification_events*\/,\n IDeckLinkDisplayMode* \/*new_display_mode*\/,\n BMDDetectedVideoInputFormatFlags \/*detected_signal_flags*\/) {\n return S_OK;\n}\n\nHRESULT DecklinkCaptureDelegate::VideoInputFrameArrived(\n IDeckLinkVideoInputFrame* videoFrameLeft,\n IDeckLinkAudioInputPacket* \/*audio_packet*\/) {\n if ((videoFrameLeft->GetFlags() & bmdFrameHasNoInputSource) != 0u) {\n SendErrorString(\"Left frame, no input signal\");\n return S_FALSE;\n }\n\n void* raw_data_left = nullptr;\n void* raw_data_right = nullptr;\n\n uint8_t* video_data_left = nullptr;\n uint8_t* video_data_right = nullptr;\n\n \/\/ get left frame\n rgbFrameLeft_->resize(videoFrameLeft->GetWidth(), videoFrameLeft->GetHeight());\n\n videoConversion_->ConvertFrame(videoFrameLeft,\n static_cast(rgbFrameLeft_.get()));\n rgbFrameLeft_->GetBytes(&raw_data_left);\n video_data_left = static_cast(raw_data_left);\n\n if (captureFormat_.stereo3D) {\n auto threeDExtension = make_decklink_ptr(videoFrameLeft);\n\n \/\/ get right frame\n IDeckLinkVideoFrame* rightEyeFrameRaw = nullptr;\n threeDExtension->GetFrameForRightEye(&rightEyeFrameRaw);\n SmartDecklinkPtr videoFrameRight{rightEyeFrameRaw};\n\n if (videoFrameRight == nullptr) {\n \/\/ todo: this is another type of exception, should it be thrown?\n throw VideoCaptureDeviceAllocationException(\"No right frame detected\");\n }\n\n rgbFrameRight_->resize(videoFrameRight->GetWidth(), videoFrameRight->GetHeight());\n videoConversion_->ConvertFrame(videoFrameRight.get(),\n static_cast(rgbFrameRight_.get()));\n rgbFrameRight_->GetBytes(&raw_data_right);\n video_data_right = static_cast(raw_data_right);\n }\n\n VideoPixelFormat pixelFormat = VideoPixelFormat::UNKNOWN;\n switch (rgbFrameLeft_->GetPixelFormat()) {\n case bmdFormat8BitYUV: \/\/ A.k.a. '2vuy';\n pixelFormat = VideoPixelFormat::UYVY;\n break;\n case bmdFormat8BitBGRA:\n pixelFormat = VideoPixelFormat::ARGB;\n break;\n default:\n SendErrorString(\"Unsupported pixel format\");\n break;\n }\n\n const VideoCaptureFormat capture_format(\n Size(rgbFrameLeft_->GetWidth(),\n rgbFrameLeft_->GetHeight()), \/\/ todo: cast or something (int64_t-> int)\n -1.0f, \/\/ Frame rate is not needed for captured data callback.\n pixelFormat,\n captureFormat_.stereo3D);\n\n if (frameReceiver_ != nullptr) {\n if (captureFormat_.stereo3D) {\n frameReceiver_->OnIncomingCapturedData(\n {{video_data_left, rgbFrameLeft_->GetRowBytes() * rgbFrameLeft_->GetHeight()},\n {video_data_right, rgbFrameRight_->GetRowBytes() * rgbFrameRight_->GetHeight()}},\n capture_format);\n } else {\n frameReceiver_->OnIncomingCapturedData(\n {{video_data_left, rgbFrameLeft_->GetRowBytes() * rgbFrameLeft_->GetHeight()}},\n capture_format);\n }\n }\n\n return S_OK;\n}\n\nvoid DecklinkCaptureDelegate::StopAndDeAllocate() {\n if (deckLinkInput_ == nullptr) {\n return;\n }\n if (deckLinkInput_->StopStreams() != S_OK) {\n SendLogString(\"Problem stopping capture.\");\n }\n deckLinkInput_->SetCallback(nullptr);\n deckLinkInput_->DisableVideoInput();\n deckLinkInput_.reset(nullptr);\n deckLink_.reset(nullptr);\n ResetVideoCaptureDeviceReference();\n}\n\n\/\/ static\nbool DecklinkCaptureDelegate::supportedFormat(const VideoCaptureFormat& format) {\n return format.frameSize == Size(1920, 1080) && format.frameRate == 30.0f &&\n format.pixelFormat == VideoPixelFormat::ARGB;\n}\n\nvoid DecklinkCaptureDelegate::SendErrorString(const std::string& reason) {\n if (frameReceiver_ != nullptr) {\n frameReceiver_->SendErrorString(reason);\n }\n}\n\nvoid DecklinkCaptureDelegate::SendLogString(const std::string& message) {\n if (frameReceiver_ != nullptr) {\n frameReceiver_->SendLogString(message);\n }\n}\n\nVideoCaptureDeviceDecklink::VideoCaptureDeviceDecklink(\n const VideoCaptureDeviceDescriptor& deviceDescriptor)\n : captureDelegate_{new DecklinkCaptureDelegate{deviceDescriptor, this}} {}\n\ngsl::owner VideoCaptureDeviceDecklink::clone() const {\n return new VideoCaptureDeviceDecklink(captureDelegate_->getDeviceDescriptor());\n}\n\nVideoCaptureDeviceDecklink::~VideoCaptureDeviceDecklink() {\n VideoCaptureDeviceDecklink::StopAndDeAllocate();\n}\n\nvoid VideoCaptureDeviceDecklink::AllocateAndStart(\n const VideoCaptureFormat& format,\n std::unique_ptr client) {\n client_ = std::move(client);\n \/\/ todo: should verify that format is supported\n \/\/ todo: should get image size from capture delegate\n captureDelegate_->AllocateAndStart(format);\n}\n\nvoid VideoCaptureDeviceDecklink::StopAndDeAllocate() {\n captureDelegate_->StopAndDeAllocate();\n}\n\nvoid VideoCaptureDeviceDecklink::OnIncomingCapturedData(\n const VideoCaptureDevice::Client::Images& images,\n const VideoCaptureFormat& frameFormat) {\n if (client_ != nullptr) {\n client_->OnIncomingCapturedData(images, frameFormat);\n }\n}\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nstatic void fixMatches(apf::Mesh2* m)\n{\n if (m->hasMatching()) {\n if (apf::alignMdsMatches(m))\n printf(\"fixed misaligned matches\\n\");\n else\n printf(\"matches were aligned\\n\");\n assert( ! apf::alignMdsMatches(m));\n }\n}\n\nstatic void fixPyramids(apf::Mesh2* m)\n{\n if (m->getDimension() != 3)\n return; \/* no pyramids exist in 2D *\/\n if (apf::countEntitiesOfType(m, apf::Mesh::HEX))\n return; \/* meshadapt can't even look at hexes *\/\n ma::Input* in = ma::configureIdentity(m);\n in->shouldCleanupLayer = true;\n ma::adapt(in);\n}\n\nint main(int argc, char** argv)\n{\n MPI_Init(&argc, &argv);\n PCU_Comm_Init();\n SimUtil_start();\n Sim_readLicenseFile(NULL);\n SimPartitionedMesh_start(&argc,&argv);\n\n const char* gmi_path = NULL;\n const char* sms_path = NULL;\n const char* smb_path = NULL;\n bool should_fix_pyramids = true;\n bool found_bad_arg = false;\n\n for (int i = 1; i < argc; ++i) {\n if (!strcmp(argv[i], \"--no-pyramid-fix\")) {\n should_fix_pyramids = false;\n } else if (!gmi_path) {\n gmi_path = argv[i];\n } else if (!sms_path) {\n sms_path = argv[i];\n } else if (!smb_path) {\n smb_path = argv[i];\n } else {\n if(!PCU_Comm_Self())\n std::cerr << \"bad argument \\\"\" << argv[i] << \"\\\"\\n\";\n found_bad_arg = true;\n }\n }\n\n if (!gmi_path || !sms_path || !smb_path || found_bad_arg) {\n if(!PCU_Comm_Self()) {\n std::cerr << \"usage: \" << argv[0] << \" [options] \\n\";\n std::cerr << \"options:\\n\";\n std::cerr << \" --no-pyramid-fix Disable quad-connected pyramid tetrahedronization\\n\";\n }\n return EXIT_FAILURE;\n }\n\n gmi_sim_start();\n gmi_register_sim();\n pProgress progress = Progress_new();\n Progress_setDefaultCallback(progress);\n\n gmi_model* mdl = gmi_load(gmi_path);\n pGModel simModel = gmi_export_sim(mdl);\n pParMesh sim_mesh = PM_load(sms_path, sthreadNone, simModel, progress);\n apf::Mesh* simApfMesh = apf::createMesh(sim_mesh);\n \n apf::Mesh2* mesh = apf::createMdsMesh(mdl, simApfMesh);\n apf::printStats(mesh);\n apf::destroyMesh(simApfMesh);\n M_release(sim_mesh);\n fixMatches(mesh);\n if (should_fix_pyramids) fixPyramids(mesh);\n mesh->verify();\n mesh->writeNative(smb_path);\n\n mesh->destroyNative();\n apf::destroyMesh(mesh);\n\n Progress_delete(progress);\n gmi_sim_stop();\n SimPartitionedMesh_stop();\n Sim_unregisterAllKeys();\n SimUtil_stop();\n PCU_Comm_Free();\n MPI_Finalize();\n}\nconvert program option to attach original order#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nstatic void attachOrder(apf::Mesh* m)\n{\n apf::numberOverlapDimension(m, \"sim_order\", m->getDimension());\n}\n\nstatic void fixMatches(apf::Mesh2* m)\n{\n if (m->hasMatching()) {\n if (apf::alignMdsMatches(m))\n printf(\"fixed misaligned matches\\n\");\n else\n printf(\"matches were aligned\\n\");\n assert( ! apf::alignMdsMatches(m));\n }\n}\n\nstatic void fixPyramids(apf::Mesh2* m)\n{\n if (m->getDimension() != 3)\n return; \/* no pyramids exist in 2D *\/\n if (apf::countEntitiesOfType(m, apf::Mesh::HEX))\n return; \/* meshadapt can't even look at hexes *\/\n ma::Input* in = ma::configureIdentity(m);\n in->shouldCleanupLayer = true;\n ma::adapt(in);\n}\n\nint main(int argc, char** argv)\n{\n MPI_Init(&argc, &argv);\n PCU_Comm_Init();\n SimUtil_start();\n Sim_readLicenseFile(NULL);\n SimPartitionedMesh_start(&argc,&argv);\n\n const char* gmi_path = NULL;\n const char* sms_path = NULL;\n const char* smb_path = NULL;\n bool should_fix_pyramids = true;\n bool should_attach_order = false;\n bool found_bad_arg = false;\n\n for (int i = 1; i < argc; ++i) {\n if (!strcmp(argv[i], \"--no-pyramid-fix\")) {\n should_fix_pyramids = false;\n } else if (!strcmp(argv[i], \"--attach-order\")) {\n should_attach_order = true;\n } else if (!gmi_path) {\n gmi_path = argv[i];\n } else if (!sms_path) {\n sms_path = argv[i];\n } else if (!smb_path) {\n smb_path = argv[i];\n } else {\n if(!PCU_Comm_Self())\n std::cerr << \"bad argument \\\"\" << argv[i] << \"\\\"\\n\";\n found_bad_arg = true;\n }\n }\n\n if (!gmi_path || !sms_path || !smb_path || found_bad_arg) {\n if(!PCU_Comm_Self()) {\n std::cout << \"usage: \" << argv[0] << \" [options] \\n\";\n std::cout << \"options:\\n\";\n std::cout << \" --no-pyramid-fix Disable quad-connected pyramid tetrahedronization\\n\";\n std::cout << \" --attach-order Attach the Simmetrix element order as a Numbering\\n\";\n }\n return EXIT_FAILURE;\n }\n\n if (should_attach_order && should_fix_pyramids) {\n if (!PCU_Comm_Self())\n std::cout << \"disabling pyramid fix because --attach-order was given\\n\";\n should_fix_pyramids = false;\n }\n\n gmi_sim_start();\n gmi_register_sim();\n pProgress progress = Progress_new();\n Progress_setDefaultCallback(progress);\n\n gmi_model* mdl = gmi_load(gmi_path);\n pGModel simModel = gmi_export_sim(mdl);\n pParMesh sim_mesh = PM_load(sms_path, sthreadNone, simModel, progress);\n apf::Mesh* simApfMesh = apf::createMesh(sim_mesh);\n if (should_attach_order) attachOrder(simApfMesh);\n \n apf::Mesh2* mesh = apf::createMdsMesh(mdl, simApfMesh);\n apf::printStats(mesh);\n apf::destroyMesh(simApfMesh);\n M_release(sim_mesh);\n fixMatches(mesh);\n if (should_fix_pyramids) fixPyramids(mesh);\n mesh->verify();\n mesh->writeNative(smb_path);\n\n mesh->destroyNative();\n apf::destroyMesh(mesh);\n\n Progress_delete(progress);\n gmi_sim_stop();\n SimPartitionedMesh_stop();\n Sim_unregisterAllKeys();\n SimUtil_stop();\n PCU_Comm_Free();\n MPI_Finalize();\n}\n<|endoftext|>"} {"text":"#include \"ParserUtils.h\"\n#include \"ValueParser.h\"\n#include \"ExpressionParser.h\"\n#include \"TransformParser.h\"\n#include \"ColorParser.h\"\n\n#include \n#include \n#include \n#include \n\n#include \n#include \n\nnamespace carto { namespace mvt {\n vt::Color parseColor(const std::string& str) {\n std::string::const_iterator it = str.begin();\n std::string::const_iterator end = str.end();\n colorparserimpl::encoding::space_type space;\n unsigned int color = 0;\n bool result = boost::spirit::qi::phrase_parse(it, end, ColorParser(), space, color);\n if (!result) {\n throw ParserException(\"Color parsing failed\", str);\n }\n if (it != str.end()) {\n throw ParserException(\"Could not parse to the end of color, error at position \" + boost::lexical_cast(it - str.begin()), str);\n }\n return vt::Color(color);\n }\n\n vt::CompOp parseCompOp(const std::string& str) {\n static const std::unordered_map compOpTable = {\n { \"src\", vt::CompOp::SRC },\n { \"src-over\", vt::CompOp::SRC_OVER },\n { \"src-in\", vt::CompOp::SRC_IN },\n { \"src-atop\", vt::CompOp::SRC_ATOP },\n { \"dst\", vt::CompOp::DST },\n { \"dst-over\", vt::CompOp::DST_OVER },\n { \"dst-in\", vt::CompOp::DST_IN },\n { \"dst-atop\", vt::CompOp::DST_ATOP },\n { \"zero\", vt::CompOp::ZERO },\n { \"plus\", vt::CompOp::PLUS },\n { \"minus\", vt::CompOp::MINUS },\n { \"multiply\", vt::CompOp::MULTIPLY },\n { \"screen\", vt::CompOp::SCREEN },\n { \"darken\", vt::CompOp::DARKEN },\n { \"lighten\", vt::CompOp::LIGHTEN }\n };\n\n auto it = compOpTable.find(str);\n if (it == compOpTable.end()) {\n throw ParserException(\"CompOp parsing failed\", str);\n }\n return it->second;\n }\n\n vt::LabelOrientation parseLabelOrientation(const std::string& str) {\n static const std::unordered_map labelOrientationTable = {\n { \"point\", vt::LabelOrientation::BILLBOARD_2D },\n { \"nutibillboard\", vt::LabelOrientation::BILLBOARD_3D },\n { \"nutipoint\", vt::LabelOrientation::POINT },\n { \"line\", vt::LabelOrientation::LINE }\n };\n\n auto it = labelOrientationTable.find(str);\n if (it == labelOrientationTable.end()) {\n throw ParserException(\"LabelOrientation parsing failed\", str);\n }\n return it->second;\n }\n\n Value parseValue(const std::string& str) {\n std::string::const_iterator it = str.begin();\n std::string::const_iterator end = str.end();\n valparserimpl::encoding::space_type space;\n Value val;\n bool result = boost::spirit::qi::phrase_parse(it, end, ValueParser(), space, val);\n if (!result) {\n throw ParserException(\"Value parsing failed\", str);\n }\n if (it != str.end()) {\n throw ParserException(\"Could not parse to the end of value, error at position \" + boost::lexical_cast(it - str.begin()), str);\n }\n return val;\n }\n\n std::shared_ptr parseExpression(const std::string& str) {\n constexpr static int MAX_CACHE_SIZE = 1024;\n\n static std::mutex exprCacheMutex;\n static std::unordered_map> exprCache;\n\n std::lock_guard lock(exprCacheMutex);\n auto exprIt = exprCache.find(str);\n if (exprIt != exprCache.end()) {\n return exprIt->second;\n }\n \n std::string::const_iterator it = str.begin();\n std::string::const_iterator end = str.end();\n exprparserimpl::encoding::space_type space;\n std::shared_ptr expr;\n bool result = boost::spirit::qi::phrase_parse(it, end, ExpressionParser(), space, expr);\n if (!result) {\n throw ParserException(\"Expression parsing failed\", str);\n }\n if (it != str.end()) {\n throw ParserException(\"Could not parse to the end of expression, error at position \" + boost::lexical_cast(it - str.begin()), str);\n }\n\n if (exprCache.size() >= MAX_CACHE_SIZE) {\n exprCache.erase(exprCache.begin());\n }\n exprCache[str] = expr;\n return expr;\n }\n\n std::shared_ptr parseStringExpression(const std::string& str) {\n constexpr static int MAX_CACHE_SIZE = 1024;\n\n static std::mutex exprCacheMutex;\n static std::unordered_map> exprCache;\n\n std::lock_guard lock(exprCacheMutex);\n auto exprIt = exprCache.find(str);\n if (exprIt != exprCache.end()) {\n return exprIt->second;\n }\n\n std::string::const_iterator it = str.begin();\n std::string::const_iterator end = str.end();\n exprparserimpl::encoding::space_type space;\n std::shared_ptr expr;\n bool result = boost::spirit::qi::phrase_parse(it, end, StringExpressionParser(), space, expr);\n if (!result) {\n throw ParserException(\"String expression parsing failed\", str);\n }\n if (it != str.end()) {\n throw ParserException(\"Could not parse to the end of string expression, error at position \" + boost::lexical_cast(it - str.begin()), str);\n }\n\n if (exprCache.size() >= MAX_CACHE_SIZE) {\n exprCache.erase(exprCache.begin());\n }\n exprCache[str] = expr;\n return expr;\n }\n\n std::vector > parseTransformList(const std::string& str) {\n std::string::const_iterator it = str.begin();\n std::string::const_iterator end = str.end();\n transparserimpl::encoding::space_type space;\n std::vector> transforms;\n bool result = boost::spirit::qi::phrase_parse(it, end, TransformParser() % ',', space, transforms);\n if (!result) {\n throw ParserException(\"Transform parsing failed\", str);\n }\n if (it != str.end()) {\n throw ParserException(\"Could not parse to the end of transform, error at position \" + boost::lexical_cast(it - str.begin()), str);\n }\n return transforms;\n }\n} }\nAdded 'clear' comp-op support to VT renderer#include \"ParserUtils.h\"\n#include \"ValueParser.h\"\n#include \"ExpressionParser.h\"\n#include \"TransformParser.h\"\n#include \"ColorParser.h\"\n\n#include \n#include \n#include \n#include \n\n#include \n#include \n\nnamespace carto { namespace mvt {\n vt::Color parseColor(const std::string& str) {\n std::string::const_iterator it = str.begin();\n std::string::const_iterator end = str.end();\n colorparserimpl::encoding::space_type space;\n unsigned int color = 0;\n bool result = boost::spirit::qi::phrase_parse(it, end, ColorParser(), space, color);\n if (!result) {\n throw ParserException(\"Color parsing failed\", str);\n }\n if (it != str.end()) {\n throw ParserException(\"Could not parse to the end of color, error at position \" + boost::lexical_cast(it - str.begin()), str);\n }\n return vt::Color(color);\n }\n\n vt::CompOp parseCompOp(const std::string& str) {\n static const std::unordered_map compOpTable = {\n { \"src\", vt::CompOp::SRC },\n { \"src-over\", vt::CompOp::SRC_OVER },\n { \"src-in\", vt::CompOp::SRC_IN },\n { \"src-atop\", vt::CompOp::SRC_ATOP },\n { \"dst\", vt::CompOp::DST },\n { \"dst-over\", vt::CompOp::DST_OVER },\n { \"dst-in\", vt::CompOp::DST_IN },\n { \"dst-atop\", vt::CompOp::DST_ATOP },\n { \"clear\", vt::CompOp::ZERO },\n { \"zero\", vt::CompOp::ZERO },\n { \"plus\", vt::CompOp::PLUS },\n { \"minus\", vt::CompOp::MINUS },\n { \"multiply\", vt::CompOp::MULTIPLY },\n { \"screen\", vt::CompOp::SCREEN },\n { \"darken\", vt::CompOp::DARKEN },\n { \"lighten\", vt::CompOp::LIGHTEN }\n };\n\n auto it = compOpTable.find(str);\n if (it == compOpTable.end()) {\n throw ParserException(\"CompOp parsing failed\", str);\n }\n return it->second;\n }\n\n vt::LabelOrientation parseLabelOrientation(const std::string& str) {\n static const std::unordered_map labelOrientationTable = {\n { \"point\", vt::LabelOrientation::BILLBOARD_2D },\n { \"nutibillboard\", vt::LabelOrientation::BILLBOARD_3D },\n { \"nutipoint\", vt::LabelOrientation::POINT },\n { \"line\", vt::LabelOrientation::LINE }\n };\n\n auto it = labelOrientationTable.find(str);\n if (it == labelOrientationTable.end()) {\n throw ParserException(\"LabelOrientation parsing failed\", str);\n }\n return it->second;\n }\n\n Value parseValue(const std::string& str) {\n std::string::const_iterator it = str.begin();\n std::string::const_iterator end = str.end();\n valparserimpl::encoding::space_type space;\n Value val;\n bool result = boost::spirit::qi::phrase_parse(it, end, ValueParser(), space, val);\n if (!result) {\n throw ParserException(\"Value parsing failed\", str);\n }\n if (it != str.end()) {\n throw ParserException(\"Could not parse to the end of value, error at position \" + boost::lexical_cast(it - str.begin()), str);\n }\n return val;\n }\n\n std::shared_ptr parseExpression(const std::string& str) {\n constexpr static int MAX_CACHE_SIZE = 1024;\n\n static std::mutex exprCacheMutex;\n static std::unordered_map> exprCache;\n\n std::lock_guard lock(exprCacheMutex);\n auto exprIt = exprCache.find(str);\n if (exprIt != exprCache.end()) {\n return exprIt->second;\n }\n \n std::string::const_iterator it = str.begin();\n std::string::const_iterator end = str.end();\n exprparserimpl::encoding::space_type space;\n std::shared_ptr expr;\n bool result = boost::spirit::qi::phrase_parse(it, end, ExpressionParser(), space, expr);\n if (!result) {\n throw ParserException(\"Expression parsing failed\", str);\n }\n if (it != str.end()) {\n throw ParserException(\"Could not parse to the end of expression, error at position \" + boost::lexical_cast(it - str.begin()), str);\n }\n\n if (exprCache.size() >= MAX_CACHE_SIZE) {\n exprCache.erase(exprCache.begin());\n }\n exprCache[str] = expr;\n return expr;\n }\n\n std::shared_ptr parseStringExpression(const std::string& str) {\n constexpr static int MAX_CACHE_SIZE = 1024;\n\n static std::mutex exprCacheMutex;\n static std::unordered_map> exprCache;\n\n std::lock_guard lock(exprCacheMutex);\n auto exprIt = exprCache.find(str);\n if (exprIt != exprCache.end()) {\n return exprIt->second;\n }\n\n std::string::const_iterator it = str.begin();\n std::string::const_iterator end = str.end();\n exprparserimpl::encoding::space_type space;\n std::shared_ptr expr;\n bool result = boost::spirit::qi::phrase_parse(it, end, StringExpressionParser(), space, expr);\n if (!result) {\n throw ParserException(\"String expression parsing failed\", str);\n }\n if (it != str.end()) {\n throw ParserException(\"Could not parse to the end of string expression, error at position \" + boost::lexical_cast(it - str.begin()), str);\n }\n\n if (exprCache.size() >= MAX_CACHE_SIZE) {\n exprCache.erase(exprCache.begin());\n }\n exprCache[str] = expr;\n return expr;\n }\n\n std::vector > parseTransformList(const std::string& str) {\n std::string::const_iterator it = str.begin();\n std::string::const_iterator end = str.end();\n transparserimpl::encoding::space_type space;\n std::vector> transforms;\n bool result = boost::spirit::qi::phrase_parse(it, end, TransformParser() % ',', space, transforms);\n if (!result) {\n throw ParserException(\"Transform parsing failed\", str);\n }\n if (it != str.end()) {\n throw ParserException(\"Could not parse to the end of transform, error at position \" + boost::lexical_cast(it - str.begin()), str);\n }\n return transforms;\n }\n} }\n<|endoftext|>"} {"text":"\/* +------------------------------------------------------------------------+\n | Mobile Robot Programming Toolkit (MRPT) |\n | https:\/\/www.mrpt.org\/ |\n | |\n | Copyright (c) 2005-2019, Individual contributors, see AUTHORS file |\n | See: https:\/\/www.mrpt.org\/Authors - All rights reserved. |\n | Released under BSD License. See: https:\/\/www.mrpt.org\/License |\n +------------------------------------------------------------------------+ *\/\n\n#include \n#include \n#include \n#include \n#include \n\nusing config_changer_t = std::function;\nusing post_tester_t =\n\tstd::function;\n\nusing MCL = mrpt::apps::MonteCarloLocalization_Rawlog;\n\nvoid generic_pf_test(\n\tconst std::string& ini_filename, const std::string& rawlog_filename,\n\tconst std::string& map_filename, config_changer_t cfg_changer,\n\tpost_tester_t post_tester)\n{\n\tusing namespace std::string_literals;\n\n\tconst auto ini_fil = mrpt::UNITTEST_BASEDIR +\n\t\t\t\t\t\t \"\/share\/mrpt\/config_files\/pf-localization\/\"s +\n\t\t\t\t\t\t ini_filename;\n\tASSERT_FILE_EXISTS_(ini_fil);\n\n\tconst auto rawlog_fil =\n\t\tmrpt::UNITTEST_BASEDIR + \"\/share\/mrpt\/datasets\/\"s + rawlog_filename;\n\tASSERT_FILE_EXISTS_(rawlog_fil);\n\n\tconst auto map_fil =\n\t\tmrpt::UNITTEST_BASEDIR + \"\/share\/mrpt\/datasets\/\"s + map_filename;\n\tASSERT_FILE_EXISTS_(map_fil);\n\n\ttry\n\t{\n\t\tMCL app;\n\t\tapp.setMinLoggingLevel(mrpt::system::LVL_ERROR);\n\n\t\tconst char* argv[] = {\"pf-localization-slam\", ini_fil.c_str(),\n\t\t\t\t\t\t\t rawlog_fil.c_str()};\n\t\tconst int argc = sizeof(argv) \/ sizeof(argv[0]);\n\n\t\tapp.initialize(argc, argv);\n\n\t\tapp.params.write(\n\t\t\tMCL::sect, \"logOutput_dir\",\n\t\t\tmrpt::system::getTempFileName() + \"_dir\"s);\n\t\tapp.params.write(MCL::sect, \"SHOW_PROGRESS_3D_REAL_TIME\", false);\n\n\t\tapp.params.write(MCL::sect, \"map_file\", map_fil);\n\n\t\tapp.fill_out_estimated_path = true;\n\t\tapp.allow_quit_on_esc_key = false;\n\n#if !MRPT_HAS_OPENCV\n\t\tapp.params.write(MCL::sect, \"3DSceneFrequency\", -1);\n\t\tapp.params.write(MCL::sect, \"LOG_FREQUENCY\", 0);\n#endif\n\n\t\tcfg_changer(app.params);\n\t\tapp.run();\n\n\t\t\/\/ Check results:\n\t\tpost_tester(app);\n\t}\n\tcatch (const std::exception& e)\n\t{\n\t\tstd::cerr << mrpt::exception_to_str(e);\n\t\tGTEST_FAIL();\n\t}\n}\n\nstatic auto tester_for_localization_demo =\n\t[](mrpt::apps::MonteCarloLocalization_Base& o) {\n\t\tEXPECT_EQ(o.out_estimated_path.size(), 37U);\n\t\tif (o.out_estimated_path.empty()) return;\n\n\t\tconst mrpt::math::TPose3D p = o.out_estimated_path.rbegin()->second;\n\t\tconst auto p_gt = mrpt::math::TPose3D::FromString(\n\t\t\t\"[15.89 -10.0 0.000000 4.8 0.000000 0.000000]\");\n\n\t\tfor (int i = 0; i < 6; i++) EXPECT_NEAR(p[i], p_gt[i], 0.5);\n\t};\n\nTEST(MonteCarloLocalization_Rawlog, RunForSampleDataset_2D)\n{\n\tusing namespace std::string_literals;\n\tgeneric_pf_test(\n\t\t\"localization_demo.ini\", \"localization_demo.rawlog\",\n\t\t\"localization_demo.simplemap.gz\",\n\t\t[](mrpt::config::CConfigFileBase& cfg) {\n\t\t\t\/\/ Use 2D:\n\t\t\tcfg.write(MCL::sect, \"use_3D_poses\", false);\n\t\t},\n\t\ttester_for_localization_demo);\n}\n\nTEST(MonteCarloLocalization_Rawlog, RunForSampleDataset_3D)\n{\n\tusing namespace std::string_literals;\n\tgeneric_pf_test(\n\t\t\"localization_demo.ini\", \"localization_demo.rawlog\",\n\t\t\"localization_demo.simplemap.gz\",\n\t\t[](mrpt::config::CConfigFileBase& cfg) {\n\t\t\t\/\/ Use 3D:\n\t\t\tcfg.write(MCL::sect, \"use_3D_poses\", true);\n\t\t\t\/\/ 3D requires init in a fixed volume:\n\t\t\tcfg.write(MCL::sect, \"init_PDF_mode\", 1);\n\t\t},\n\t\ttester_for_localization_demo);\n}\ntolerate random failures and retry in MCL test\/* +------------------------------------------------------------------------+\n | Mobile Robot Programming Toolkit (MRPT) |\n | https:\/\/www.mrpt.org\/ |\n | |\n | Copyright (c) 2005-2019, Individual contributors, see AUTHORS file |\n | See: https:\/\/www.mrpt.org\/Authors - All rights reserved. |\n | Released under BSD License. See: https:\/\/www.mrpt.org\/License |\n +------------------------------------------------------------------------+ *\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n\nusing config_changer_t = std::function;\nusing post_tester_t =\n\tstd::function;\n\nusing MCL = mrpt::apps::MonteCarloLocalization_Rawlog;\n\nvoid generic_pf_test(\n\tconst std::string& ini_filename, const std::string& rawlog_filename,\n\tconst std::string& map_filename, config_changer_t cfg_changer,\n\tpost_tester_t post_tester)\n{\n\tusing namespace std::string_literals;\n\n\tconst auto ini_fil = mrpt::UNITTEST_BASEDIR +\n\t\t\t\t\t\t \"\/share\/mrpt\/config_files\/pf-localization\/\"s +\n\t\t\t\t\t\t ini_filename;\n\tASSERT_FILE_EXISTS_(ini_fil);\n\n\tconst auto rawlog_fil =\n\t\tmrpt::UNITTEST_BASEDIR + \"\/share\/mrpt\/datasets\/\"s + rawlog_filename;\n\tASSERT_FILE_EXISTS_(rawlog_fil);\n\n\tconst auto map_fil =\n\t\tmrpt::UNITTEST_BASEDIR + \"\/share\/mrpt\/datasets\/\"s + map_filename;\n\tASSERT_FILE_EXISTS_(map_fil);\n\n\ttry\n\t{\n\t\tMCL app;\n\t\tapp.setMinLoggingLevel(mrpt::system::LVL_ERROR);\n\n\t\tconst char* argv[] = {\"pf-localization-slam\", ini_fil.c_str(),\n\t\t\t\t\t\t\t rawlog_fil.c_str()};\n\t\tconst int argc = sizeof(argv) \/ sizeof(argv[0]);\n\n\t\tapp.initialize(argc, argv);\n\n\t\tapp.params.write(\n\t\t\tMCL::sect, \"logOutput_dir\",\n\t\t\tmrpt::system::getTempFileName() + \"_dir\"s);\n\t\tapp.params.write(MCL::sect, \"SHOW_PROGRESS_3D_REAL_TIME\", false);\n\n\t\tapp.params.write(MCL::sect, \"map_file\", map_fil);\n\n\t\tapp.fill_out_estimated_path = true;\n\t\tapp.allow_quit_on_esc_key = false;\n\n#if !MRPT_HAS_OPENCV\n\t\tapp.params.write(MCL::sect, \"3DSceneFrequency\", -1);\n\t\tapp.params.write(MCL::sect, \"LOG_FREQUENCY\", 0);\n#endif\n\n\t\tcfg_changer(app.params);\n\t\tapp.run();\n\n\t\t\/\/ Check results:\n\t\tpost_tester(app);\n\t}\n\tcatch (const std::exception& e)\n\t{\n\t\tstd::cerr << mrpt::exception_to_str(e);\n\t\tGTEST_FAIL();\n\t}\n}\n\nstatic bool tester_result_ok = true;\n\nstatic auto tester_for_localization_demo =\n\t[](mrpt::apps::MonteCarloLocalization_Base& o) {\n\t\tEXPECT_EQ(o.out_estimated_path.size(), 37U);\n\t\tif (o.out_estimated_path.empty()) return;\n\n\t\tconst mrpt::math::TPose3D p = o.out_estimated_path.rbegin()->second;\n\t\tconst auto p_gt = mrpt::math::TPose3D::FromString(\n\t\t\t\"[15.89 -10.0 0.000000 4.8 0.000000 0.000000]\");\n\n\t\tconst auto p_err = mrpt::poses::CPose3D(p_gt - p);\n\t\tconst double err = mrpt::poses::Lie::SE<3>::log(p_err).norm();\n\n\t\tif (err < 0.5)\n\t\t{\n\t\t\ttester_result_ok = true;\n\t\t}\n\t\telse\n\t\t{\n\t\t\ttester_result_ok = false;\n\t\t\tstd::cerr << \"Final pose mismatch (will retry N times):\\n\"\n\t\t\t\t\t\t \"Expected: \"\n\t\t\t\t\t << p_gt.asString()\n\t\t\t\t\t << \"\\n\"\n\t\t\t\t\t\t \"Actual : \"\n\t\t\t\t\t << p.asString() << \"\\n\";\n\t\t}\n\t};\n\nTEST(MonteCarloLocalization_Rawlog, RunForSampleDataset_2D)\n{\n\tusing namespace std::string_literals;\n\tfor (int tries = 0; tries < 5; tries++)\n\t{\n\t\tgeneric_pf_test(\n\t\t\t\"localization_demo.ini\", \"localization_demo.rawlog\",\n\t\t\t\"localization_demo.simplemap.gz\",\n\t\t\t[](mrpt::config::CConfigFileBase& cfg) {\n\t\t\t\t\/\/ Use 2D:\n\t\t\t\tcfg.write(MCL::sect, \"use_3D_poses\", false);\n\t\t\t},\n\t\t\ttester_for_localization_demo);\n\n\t\tif (tester_result_ok) break;\n\t}\n}\n\nTEST(MonteCarloLocalization_Rawlog, RunForSampleDataset_3D)\n{\n\tusing namespace std::string_literals;\n\tfor (int tries = 0; tries < 5; tries++)\n\t{\n\t\tgeneric_pf_test(\n\t\t\t\"localization_demo.ini\", \"localization_demo.rawlog\",\n\t\t\t\"localization_demo.simplemap.gz\",\n\t\t\t[](mrpt::config::CConfigFileBase& cfg) {\n\t\t\t\t\/\/ Use 3D:\n\t\t\t\tcfg.write(MCL::sect, \"use_3D_poses\", true);\n\t\t\t\t\/\/ 3D requires init in a fixed volume:\n\t\t\t\tcfg.write(MCL::sect, \"init_PDF_mode\", 1);\n\t\t\t},\n\t\t\ttester_for_localization_demo);\n\n\t\tif (tester_result_ok) break;\n\t}\n}\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * $RCSfile: sfxhelp.cxx,v $\n *\n * $Revision: 1.11 $\n *\n * last change: $Author: pb $ $Date: 2000-12-10 14:22:35 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#include \"sfxhelp.hxx\"\n\n#pragma hdrstop\n\n#ifndef _COM_SUN_STAR_UNO_REFERENCE_H_\n#include \n#endif\n#ifndef _COM_SUN_STAR_FRAME_XFRAME_HPP_\n#include \n#endif\n#ifndef _UNOTOOLS_PROCESSFACTORY_HXX\n#include \n#endif\n#ifndef _COM_SUN_STAR_AWT_XWINDOW_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_AWT_POSSIZE_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_FRAME_XTASK_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_FRAME_XTASKSSUPPLIER_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_UTIL_XURLTRANSFORMER_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_FRAME_XDISPATCH_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_FRAME_XDISPATCHPROVIDER_HPP_\n#include \n#endif\n#include \n#include \n\n#include \"sfxsids.hrc\"\n#include \"app.hxx\"\n#include \"viewfrm.hxx\"\n#include \"msgpool.hxx\"\n#include \"newhelp.hxx\"\n#include \"objsh.hxx\"\n#include \"docfac.hxx\"\n#include \"sfxresid.hxx\"\n#include \"app.hrc\"\n\nusing namespace ::com::sun::star::beans;\nusing namespace ::com::sun::star::frame;\nusing namespace ::com::sun::star::uno;\nusing namespace ::com::sun::star::util;\n\nSfxHelp_Impl::SfxHelp_Impl()\n{\n}\n\nSfxHelp_Impl::~SfxHelp_Impl()\n{\n}\n\nString SfxHelp_Impl::GetHelpModuleName( ULONG nHelpId )\n{\n String aModuleName;\n SfxViewFrame *pViewFrame = SfxViewFrame::Current();\n if ( pViewFrame )\n {\n \/\/ Wenn es ein Slot ist, kann es sein, da\\s internes InPlace vorliegt\n \/\/ und eine Container-SlotId gefragt ist\n if (nHelpId >= (ULONG) SID_SFX_START && nHelpId <= (ULONG) SHRT_MAX)\n {\n if ( pViewFrame->GetParentViewFrame_Impl() )\n {\n \/\/ Ist es ein ContainerSlot ?\n const SfxSlot* pSlot = SFX_APP()->GetSlotPool(pViewFrame).GetSlot( (USHORT) nHelpId );\n if ( !pSlot || pSlot->IsMode( SFX_SLOT_CONTAINER ) )\n pViewFrame = pViewFrame->GetParentViewFrame_Impl();\n }\n }\n\n if( pViewFrame->GetObjectShell() )\n aModuleName = String::CreateFromAscii( pViewFrame->GetObjectShell()->GetFactory().GetShortName() );\n }\n\n return aModuleName;\n}\n\nBOOL SfxHelp_Impl::Start( ULONG nHelpId )\n{\n Reference < XTasksSupplier > xDesktop( ::comphelper::getProcessServiceFactory()->createInstance(\n DEFINE_CONST_UNICODE(\"com.sun.star.frame.Desktop\") ), UNO_QUERY );\n\n Reference < XTask > xActiveTask = xDesktop->getActiveTask();\n if ( !xActiveTask.is() )\n return FALSE;\n\n\n \/\/ try to find the help frame\n Reference < XDispatchProvider > xFrame(\n xActiveTask->findFrame( ::rtl::OUString::createFromAscii( \"OFFICE_HELP\" ),\n FrameSearchFlag::GLOBAL ), UNO_QUERY );\n\n Sequence < PropertyValue > aProps;\n sal_Int32 nFlag = FrameSearchFlag::GLOBAL;\n String aHelpModuleName = GetHelpModuleName( nHelpId );\n sal_Bool bNewWin = sal_False;\n if ( aTicket.Len() )\n {\n \/\/ if there is a ticket, we are inside a plugin, so a request including the URL must be posted\n if ( !xFrame.is() )\n \/\/ must be created on dispatch\n nFlag |= FrameSearchFlag::CREATE;\n }\n else\n {\n \/\/ otherwise the URL can be dispatched to the help frame\n if ( !xFrame.is() )\n {\n bNewWin = sal_True;\n Reference < XFrame > xTask = xActiveTask->findFrame( DEFINE_CONST_UNICODE( \"_blank\" ), 0 );\n xFrame = Reference < XDispatchProvider >( xTask, UNO_QUERY );\n Window* pWin = VCLUnoHelper::GetWindow( xTask->getContainerWindow() );\n pWin->SetText( String( SfxResId( STR_HELP_WINDOW_TITLE ) ) );\n SfxHelpWindow_Impl* pHlpWin = new SfxHelpWindow_Impl( xTask, pWin, WB_DOCKBORDER );\n pHlpWin->Show();\n Reference< ::com::sun::star::awt::XWindow > xWindow = VCLUnoHelper::GetInterface( pHlpWin );\n xWindow->setPosSize( 50, 50, 300, 200, ::com::sun::star::awt::PosSize::SIZE );\n if ( !xTask->setComponent( xWindow, Reference < XController >() ) )\n return FALSE;\n else\n {\n pHlpWin->setContainerWindow( xTask->getContainerWindow() );\n pHlpWin->SetFactory( aHelpModuleName, sal_True );\n xTask->getContainerWindow()->setVisible( sal_True );\n }\n }\n }\n\n \/\/ build up the help URL\n String aHelpURL(String::CreateFromAscii(\"vnd.sun.star.help:\/\/\") );\n aHelpURL += aHelpModuleName;\n if ( !nHelpId || bNewWin )\n aHelpURL += String( DEFINE_CONST_UNICODE(\"\/start\") );\n else\n {\n aHelpURL += '\/';\n aHelpURL += String::CreateFromInt32( nHelpId );\n }\n ::com::sun::star::util::URL aURL;\n aURL.Complete = aHelpURL;\n Reference < XURLTransformer > xTrans( ::comphelper::getProcessServiceFactory()->createInstance(\n DEFINE_CONST_UNICODE(\"com.sun.star.util.URLTransformer\" )), UNO_QUERY );\n xTrans->parseStrict( aURL );\n Reference < XDispatch > xDispatch = xFrame->queryDispatch( aURL,\n DEFINE_CONST_UNICODE(\"OFFICE_HELP\"), FrameSearchFlag::ALL );\n if ( xDispatch.is() )\n {\n xDispatch->dispatch( aURL, aProps );\n }\n\n return TRUE;\n}\n\n\/*-----------------22.11.2000 10:59-----------------\n * old code\nBOOL SfxHelp_Impl::ImplStart( ULONG nHelpId, BOOL bCheckHelpFile, BOOL bChangeHelpFile, BOOL bHelpAgent )\n{\n static BOOL bInHelpRequest = FALSE;\n if ( bInHelpRequest || !nHelpId || ( nHelpId == SID_EXTENDEDHELP ) )\n {\n if ( bInHelpRequest )\n Sound::Beep();\n return FALSE;\n }\n\n\n if ( Help::IsRightHelp() )\n {\n if( ImplGetHelpMode() & HELPTEXTMODE_NOHELPAGENT )\n return FALSE;\n\n if ( ( nHelpId == HELP_INDEX ) || !CheckHelpFile( TRUE ) )\n return FALSE;\n\n bInHelpRequest = TRUE;\n SetCurrentHelpFile( nHelpId );\n StartHelpPI( nHelpId, FALSE, FALSE );\n bInHelpRequest = FALSE;\n return TRUE;\n }\n\n bInHelpRequest = TRUE;\n\n if( ImplGetHelpMode() & HELPTEXTMODE_NOCONTEXTHELP )\n {\n if( nHelpId < 20000 || nHelpId > 20006 )\n nHelpId = HELP_INDEX;\n }\n\n if ( bChangeHelpFile )\n SetCurrentHelpFile( nHelpId );\n\n BOOL bDone = FALSE;\n if ( !bCheckHelpFile || CheckHelpFile( TRUE ) )\n {\n SfxViewFrame* pFrame = SfxViewFrame::Current();\n if ( !bHelpAgent || ( nHelpId == HELP_INDEX ) )\n\/\/ !Application::IsInModalMode() &&\n\/\/ Application::GetAppWindow()->IsEnabled() &&\n\/\/ !SearchFocusWindowParent() && \/\/ kein Dialog aktiv\n\/\/ ( !pFrame || !pFrame->GetObjectShell()->IsInModalMode() ) )\n {\n SfxHelpViewShell* pViewShell = GetHelpViewShell( TRUE );\n if ( pViewShell )\n bDone = pViewShell->ShowHelp( GetHelpFile(), nHelpId );\n }\n else\n {\n StartHelpPI( nHelpId, TRUE, FALSE );\n SfxHelpPI* pHelpPI= SFX_APP()->GetHelpPI();\n if ( pHelpPI )\n {\n if ( !pHelpPI->IsFloatingMode() )\n {\n pHelpPI->SetFloatingMode( TRUE );\n bForcedFloatingPI = TRUE;\n }\n if ( pHelpPI->GetFloatingWindow() )\n pHelpPI->GetFloatingWindow()->ToTop();\n CheckPIPosition();\n bDone = TRUE;\n }\n }\n }\n bInHelpRequest = FALSE;\n return bDone;\n return FALSE;\n}\n*\/\n\nstruct HelpFileInfo;\nclass SfxHelp\n{\npublic:\n static BOOL ShowHelp( ULONG nId, BOOL bShowInHelpAgent, const char* pFileName = 0, BOOL bQuiet = FALSE );\n static BOOL ShowHelp( const String& rKeyword, BOOL bShowInHelpAgent, const char* pFileName = 0 );\n static void ShowHint( ULONG nId );\n static void SetCustomHelpFile( const String& rName );\n static USHORT GetHelpFileInfoCount();\n static HelpFileInfo* GetHelpFileInfo( USHORT n );\n};\n\nBOOL SfxHelp::ShowHelp( ULONG nId, BOOL bShowInHelpAgent, const char* pFileName, BOOL bQuiet )\n{\n return FALSE;\n}\n\nBOOL SfxHelp::ShowHelp( const String& rKeyword, BOOL bShowInHelpAgent, const char* pFileName )\n{\n return FALSE;\n}\n\nvoid SfxHelp::ShowHint( ULONG nId )\n{\n}\n\nvoid SfxHelp::SetCustomHelpFile( const String& rName )\n{\n}\n\nUSHORT SfxHelp::GetHelpFileInfoCount()\n{\n return 0;\n}\n\nHelpFileInfo* SfxHelp::GetHelpFileInfo( USHORT n )\n{\n return NULL;\n}\n\nclass SfxHelpPI\n{\npublic:\n void LoadTopic( const String& rFileName, ULONG nId );\n void LoadTopic( ULONG nId );\n void LoadTopic( const String& rKeyword );\n void ResetTopic();\n BOOL Close();\n\/\/ BOOL IsConstructed() const { return ( pHelpPI != 0 ); }\n String GetExtraInfo() const;\n\/\/ HelpPI* GetHelpPI() const { return pHelpPI; }\n\/\/ virtual void FillInfo( SfxChildWinInfo& ) const;\n void SetTip( ULONG nId );\n void SetTipText( const String& rText );\n\/\/ BOOL IsInShowMe() const { return bInShowMe; }\n\/\/ BOOL IsTopicJustRequested() const { return aTopicJustRequestedTimer.IsActive(); }\n\/\/ void SetTopicJustRequested( BOOL bOn ) { if( bOn )\n\/\/ aTopicJustRequestedTimer.Start();\n\/\/ else\n\/\/ aTopicJustRequestedTimer.Stop(); }\n};\n\nvoid SfxHelpPI::LoadTopic( const String& rFileName, ULONG nId ) {}\nvoid SfxHelpPI::LoadTopic( ULONG nId ) {}\nvoid SfxHelpPI::LoadTopic( const String& rKeyword ) {}\nvoid SfxHelpPI::ResetTopic() {}\n\/\/ BOOL IsConstructed() const { return ( pHelpPI != 0 ); }\n\/\/ HelpPI* GetHelpPI() const { return pHelpPI; }\n\/\/ virtual void FillInfo( SfxChildWinInfo& ) const;\nvoid SfxHelpPI::SetTip( ULONG nId ) {}\nvoid SfxHelpPI::SetTipText( const String& rText ) {}\n\nclass SfxHelpPIWrapper\n{\npublic:\n static USHORT GetChildWindowId();\n};\n\nUSHORT SfxHelpPIWrapper::GetChildWindowId()\n{\n return 0;\n}\n\nclass SfxHelpTipsWrapper\n{\npublic:\n static USHORT GetChildWindowId();\n};\n\nUSHORT SfxHelpTipsWrapper::GetChildWindowId()\n{\n return 0;\n}\nfix: #81762# erase the sub factory of the HelpModuleName, if necessary\/*************************************************************************\n *\n * $RCSfile: sfxhelp.cxx,v $\n *\n * $Revision: 1.12 $\n *\n * last change: $Author: pb $ $Date: 2000-12-11 15:48:35 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#include \"sfxhelp.hxx\"\n\n#pragma hdrstop\n\n#ifndef _COM_SUN_STAR_UNO_REFERENCE_H_\n#include \n#endif\n#ifndef _COM_SUN_STAR_FRAME_XFRAME_HPP_\n#include \n#endif\n#ifndef _UNOTOOLS_PROCESSFACTORY_HXX\n#include \n#endif\n#ifndef _COM_SUN_STAR_AWT_XWINDOW_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_AWT_POSSIZE_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_FRAME_XTASK_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_FRAME_XTASKSSUPPLIER_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_UTIL_XURLTRANSFORMER_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_FRAME_XDISPATCH_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_FRAME_XDISPATCHPROVIDER_HPP_\n#include \n#endif\n#include \n#include \n\n#include \"sfxsids.hrc\"\n#include \"app.hxx\"\n#include \"viewfrm.hxx\"\n#include \"msgpool.hxx\"\n#include \"newhelp.hxx\"\n#include \"objsh.hxx\"\n#include \"docfac.hxx\"\n#include \"sfxresid.hxx\"\n#include \"app.hrc\"\n\nusing namespace ::com::sun::star::beans;\nusing namespace ::com::sun::star::frame;\nusing namespace ::com::sun::star::uno;\nusing namespace ::com::sun::star::util;\n\nSfxHelp_Impl::SfxHelp_Impl()\n{\n}\n\nSfxHelp_Impl::~SfxHelp_Impl()\n{\n}\n\nString SfxHelp_Impl::GetHelpModuleName( ULONG nHelpId )\n{\n String aModuleName;\n SfxViewFrame *pViewFrame = SfxViewFrame::Current();\n if ( pViewFrame )\n {\n \/\/ Wenn es ein Slot ist, kann es sein, da\\s internes InPlace vorliegt\n \/\/ und eine Container-SlotId gefragt ist\n if (nHelpId >= (ULONG) SID_SFX_START && nHelpId <= (ULONG) SHRT_MAX)\n {\n if ( pViewFrame->GetParentViewFrame_Impl() )\n {\n \/\/ Ist es ein ContainerSlot ?\n const SfxSlot* pSlot = SFX_APP()->GetSlotPool(pViewFrame).GetSlot( (USHORT) nHelpId );\n if ( !pSlot || pSlot->IsMode( SFX_SLOT_CONTAINER ) )\n pViewFrame = pViewFrame->GetParentViewFrame_Impl();\n }\n }\n\n if( pViewFrame->GetObjectShell() )\n aModuleName = String::CreateFromAscii( pViewFrame->GetObjectShell()->GetFactory().GetShortName() );\n }\n\n\n \/\/ cut sub factoryname, if necessary\n xub_StrLen nPos = aModuleName.Search( '\/' );\n if ( nPos != STRING_NOTFOUND )\n aModuleName.Erase( nPos );\n\n return aModuleName;\n}\n\nBOOL SfxHelp_Impl::Start( ULONG nHelpId )\n{\n Reference < XTasksSupplier > xDesktop( ::comphelper::getProcessServiceFactory()->createInstance(\n DEFINE_CONST_UNICODE(\"com.sun.star.frame.Desktop\") ), UNO_QUERY );\n\n Reference < XTask > xActiveTask = xDesktop->getActiveTask();\n if ( !xActiveTask.is() )\n return FALSE;\n\n\n \/\/ try to find the help frame\n Reference < XDispatchProvider > xFrame(\n xActiveTask->findFrame( ::rtl::OUString::createFromAscii( \"OFFICE_HELP\" ),\n FrameSearchFlag::GLOBAL ), UNO_QUERY );\n\n Sequence < PropertyValue > aProps;\n sal_Int32 nFlag = FrameSearchFlag::GLOBAL;\n String aHelpModuleName = GetHelpModuleName( nHelpId );\n sal_Bool bNewWin = sal_False;\n if ( aTicket.Len() )\n {\n \/\/ if there is a ticket, we are inside a plugin, so a request including the URL must be posted\n if ( !xFrame.is() )\n \/\/ must be created on dispatch\n nFlag |= FrameSearchFlag::CREATE;\n }\n else\n {\n \/\/ otherwise the URL can be dispatched to the help frame\n if ( !xFrame.is() )\n {\n bNewWin = sal_True;\n Reference < XFrame > xTask = xActiveTask->findFrame( DEFINE_CONST_UNICODE( \"_blank\" ), 0 );\n xFrame = Reference < XDispatchProvider >( xTask, UNO_QUERY );\n Window* pWin = VCLUnoHelper::GetWindow( xTask->getContainerWindow() );\n pWin->SetText( String( SfxResId( STR_HELP_WINDOW_TITLE ) ) );\n SfxHelpWindow_Impl* pHlpWin = new SfxHelpWindow_Impl( xTask, pWin, WB_DOCKBORDER );\n pHlpWin->Show();\n Reference< ::com::sun::star::awt::XWindow > xWindow = VCLUnoHelper::GetInterface( pHlpWin );\n xWindow->setPosSize( 50, 50, 300, 200, ::com::sun::star::awt::PosSize::SIZE );\n if ( !xTask->setComponent( xWindow, Reference < XController >() ) )\n return FALSE;\n else\n {\n pHlpWin->setContainerWindow( xTask->getContainerWindow() );\n pHlpWin->SetFactory( aHelpModuleName, sal_True );\n xTask->getContainerWindow()->setVisible( sal_True );\n }\n }\n }\n\n \/\/ build up the help URL\n String aHelpURL(String::CreateFromAscii(\"vnd.sun.star.help:\/\/\") );\n aHelpURL += aHelpModuleName;\n if ( !nHelpId || bNewWin )\n aHelpURL += String( DEFINE_CONST_UNICODE(\"\/start\") );\n else\n {\n aHelpURL += '\/';\n aHelpURL += String::CreateFromInt32( nHelpId );\n }\n ::com::sun::star::util::URL aURL;\n aURL.Complete = aHelpURL;\n Reference < XURLTransformer > xTrans( ::comphelper::getProcessServiceFactory()->createInstance(\n DEFINE_CONST_UNICODE(\"com.sun.star.util.URLTransformer\" )), UNO_QUERY );\n xTrans->parseStrict( aURL );\n Reference < XDispatch > xDispatch = xFrame->queryDispatch( aURL,\n DEFINE_CONST_UNICODE(\"OFFICE_HELP\"), FrameSearchFlag::ALL );\n if ( xDispatch.is() )\n {\n xDispatch->dispatch( aURL, aProps );\n }\n\n return TRUE;\n}\n\n\/*-----------------22.11.2000 10:59-----------------\n * old code\nBOOL SfxHelp_Impl::ImplStart( ULONG nHelpId, BOOL bCheckHelpFile, BOOL bChangeHelpFile, BOOL bHelpAgent )\n{\n static BOOL bInHelpRequest = FALSE;\n if ( bInHelpRequest || !nHelpId || ( nHelpId == SID_EXTENDEDHELP ) )\n {\n if ( bInHelpRequest )\n Sound::Beep();\n return FALSE;\n }\n\n\n if ( Help::IsRightHelp() )\n {\n if( ImplGetHelpMode() & HELPTEXTMODE_NOHELPAGENT )\n return FALSE;\n\n if ( ( nHelpId == HELP_INDEX ) || !CheckHelpFile( TRUE ) )\n return FALSE;\n\n bInHelpRequest = TRUE;\n SetCurrentHelpFile( nHelpId );\n StartHelpPI( nHelpId, FALSE, FALSE );\n bInHelpRequest = FALSE;\n return TRUE;\n }\n\n bInHelpRequest = TRUE;\n\n if( ImplGetHelpMode() & HELPTEXTMODE_NOCONTEXTHELP )\n {\n if( nHelpId < 20000 || nHelpId > 20006 )\n nHelpId = HELP_INDEX;\n }\n\n if ( bChangeHelpFile )\n SetCurrentHelpFile( nHelpId );\n\n BOOL bDone = FALSE;\n if ( !bCheckHelpFile || CheckHelpFile( TRUE ) )\n {\n SfxViewFrame* pFrame = SfxViewFrame::Current();\n if ( !bHelpAgent || ( nHelpId == HELP_INDEX ) )\n\/\/ !Application::IsInModalMode() &&\n\/\/ Application::GetAppWindow()->IsEnabled() &&\n\/\/ !SearchFocusWindowParent() && \/\/ kein Dialog aktiv\n\/\/ ( !pFrame || !pFrame->GetObjectShell()->IsInModalMode() ) )\n {\n SfxHelpViewShell* pViewShell = GetHelpViewShell( TRUE );\n if ( pViewShell )\n bDone = pViewShell->ShowHelp( GetHelpFile(), nHelpId );\n }\n else\n {\n StartHelpPI( nHelpId, TRUE, FALSE );\n SfxHelpPI* pHelpPI= SFX_APP()->GetHelpPI();\n if ( pHelpPI )\n {\n if ( !pHelpPI->IsFloatingMode() )\n {\n pHelpPI->SetFloatingMode( TRUE );\n bForcedFloatingPI = TRUE;\n }\n if ( pHelpPI->GetFloatingWindow() )\n pHelpPI->GetFloatingWindow()->ToTop();\n CheckPIPosition();\n bDone = TRUE;\n }\n }\n }\n bInHelpRequest = FALSE;\n return bDone;\n return FALSE;\n}\n*\/\n\nstruct HelpFileInfo;\nclass SfxHelp\n{\npublic:\n static BOOL ShowHelp( ULONG nId, BOOL bShowInHelpAgent, const char* pFileName = 0, BOOL bQuiet = FALSE );\n static BOOL ShowHelp( const String& rKeyword, BOOL bShowInHelpAgent, const char* pFileName = 0 );\n static void ShowHint( ULONG nId );\n static void SetCustomHelpFile( const String& rName );\n static USHORT GetHelpFileInfoCount();\n static HelpFileInfo* GetHelpFileInfo( USHORT n );\n};\n\nBOOL SfxHelp::ShowHelp( ULONG nId, BOOL bShowInHelpAgent, const char* pFileName, BOOL bQuiet )\n{\n return FALSE;\n}\n\nBOOL SfxHelp::ShowHelp( const String& rKeyword, BOOL bShowInHelpAgent, const char* pFileName )\n{\n return FALSE;\n}\n\nvoid SfxHelp::ShowHint( ULONG nId )\n{\n}\n\nvoid SfxHelp::SetCustomHelpFile( const String& rName )\n{\n}\n\nUSHORT SfxHelp::GetHelpFileInfoCount()\n{\n return 0;\n}\n\nHelpFileInfo* SfxHelp::GetHelpFileInfo( USHORT n )\n{\n return NULL;\n}\n\nclass SfxHelpPI\n{\npublic:\n void LoadTopic( const String& rFileName, ULONG nId );\n void LoadTopic( ULONG nId );\n void LoadTopic( const String& rKeyword );\n void ResetTopic();\n BOOL Close();\n\/\/ BOOL IsConstructed() const { return ( pHelpPI != 0 ); }\n String GetExtraInfo() const;\n\/\/ HelpPI* GetHelpPI() const { return pHelpPI; }\n\/\/ virtual void FillInfo( SfxChildWinInfo& ) const;\n void SetTip( ULONG nId );\n void SetTipText( const String& rText );\n\/\/ BOOL IsInShowMe() const { return bInShowMe; }\n\/\/ BOOL IsTopicJustRequested() const { return aTopicJustRequestedTimer.IsActive(); }\n\/\/ void SetTopicJustRequested( BOOL bOn ) { if( bOn )\n\/\/ aTopicJustRequestedTimer.Start();\n\/\/ else\n\/\/ aTopicJustRequestedTimer.Stop(); }\n};\n\nvoid SfxHelpPI::LoadTopic( const String& rFileName, ULONG nId ) {}\nvoid SfxHelpPI::LoadTopic( ULONG nId ) {}\nvoid SfxHelpPI::LoadTopic( const String& rKeyword ) {}\nvoid SfxHelpPI::ResetTopic() {}\n\/\/ BOOL IsConstructed() const { return ( pHelpPI != 0 ); }\n\/\/ HelpPI* GetHelpPI() const { return pHelpPI; }\n\/\/ virtual void FillInfo( SfxChildWinInfo& ) const;\nvoid SfxHelpPI::SetTip( ULONG nId ) {}\nvoid SfxHelpPI::SetTipText( const String& rText ) {}\n\nclass SfxHelpPIWrapper\n{\npublic:\n static USHORT GetChildWindowId();\n};\n\nUSHORT SfxHelpPIWrapper::GetChildWindowId()\n{\n return 0;\n}\n\nclass SfxHelpTipsWrapper\n{\npublic:\n static USHORT GetChildWindowId();\n};\n\nUSHORT SfxHelpTipsWrapper::GetChildWindowId()\n{\n return 0;\n}\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: fupoor.hxx,v $\n *\n * $Revision: 1.11 $\n *\n * last change: $Author: rt $ $Date: 2005-09-09 05:37:37 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef SD_FU_POOR_HXX\n#define SD_FU_POOR_HXX\n\n#ifndef _RTTI_HXX \/\/autogen\n#include \n#endif\n#ifndef _SV_TIMER_HXX \/\/autogen\n#include \n#endif\n#ifndef _LINK_HXX \/\/autogen\n#include \n#endif\n#ifndef _GEN_HXX \/\/autogen\n#include \n#endif\n#ifndef _SV_EVENT_HXX \/\/autogen\n#include \n#endif\n\nclass SdDrawDocument;\nclass SfxRequest;\nclass Dialog;\nclass SdrObject;\n\nnamespace sd {\n\nclass DrawDocShell;\nclass View;\nclass ViewShell;\nclass Window;\n\n\n\n\/*************************************************************************\n|*\n|* Basisklasse fuer alle Funktionen\n|*\n\\************************************************************************\/\n\nclass FuPoor\n{\npublic:\n static const int HITPIX = 2; \/\/ Hit-Toleranz in Pixel\n static const int DRGPIX = 2; \/\/ Drag MinMove in Pixel\n\n TYPEINFO();\n\n \/**\n @param pViewSh\n May be NULL.\n *\/\n FuPoor (ViewShell* pViewSh,\n ::sd::Window* pWin,\n ::sd::View* pView,\n SdDrawDocument* pDoc,\n SfxRequest& rReq);\n virtual ~FuPoor (void);\n\n \/\/ #95491# see member\n void SetMouseButtonCode(sal_uInt16 nNew) { if(nNew != mnCode) mnCode = nNew; }\n const sal_uInt16 GetMouseButtonCode() const { return mnCode; }\n\n DrawDocShell* GetDocSh() { return pDocSh; }\n SdDrawDocument* GetDoc() { return pDoc; }\n\n virtual void DoCut();\n virtual void DoCopy();\n virtual void DoPaste();\n\n \/\/ Mouse- & Key-Events; Returnwert=TRUE: Event wurde bearbeitet\n virtual BOOL KeyInput(const KeyEvent& rKEvt);\n virtual BOOL MouseMove(const MouseEvent& rMEvt) { return FALSE; }\n virtual BOOL MouseButtonUp(const MouseEvent& rMEvt);\n\n \/\/ #95491# moved from inline to *.cxx\n virtual BOOL MouseButtonDown(const MouseEvent& rMEvt);\n\n virtual BOOL Command(const CommandEvent& rCEvt);\n virtual BOOL RequestHelp(const HelpEvent& rHEvt);\n virtual void Paint(const Rectangle& rRect, ::sd::Window* pWin) {}\n virtual void ReceiveRequest(SfxRequest& rReq);\n\n virtual void Activate(); \/\/ Function aktivieren\n virtual void Deactivate(); \/\/ Function deaktivieren\n\n virtual void ScrollStart() {} \/\/ diese Funktionen werden von\n virtual void ScrollEnd() {} \/\/ ForceScroll aufgerufen\n\n void SetWindow(::sd::Window* pWin) { pWindow = pWin; }\n void WriteStatus(const String& aStr); \/\/ Statuszeile schreiben\n\n \/\/ #97016# II\n virtual void SelectionHasChanged();\n\n USHORT GetSlotID() const { return( nSlotId ); }\n USHORT GetSlotValue() const { return( nSlotValue ); }\n\n void SetNoScrollUntilInside(BOOL bNoScroll = TRUE)\n { bNoScrollUntilInside = bNoScroll; }\n\n void StartDelayToScrollTimer ();\n\n \/\/ #97016#\n virtual SdrObject* CreateDefaultObject(const sal_uInt16 nID, const Rectangle& rRectangle);\n\n \/** is called when the currenct function should be aborted.

\n This is used when a function gets a KEY_ESCAPE but can also\n be called directly.\n\n @returns true if a active function was aborted\n *\/\n virtual bool cancel();\n\n \/\/ #i33136#\n \/** Decide if the object to be created should be created\n orthogonal. Default implementation uses nSlotID\n to decide. May be overloaded to use other criterias\n for this decision\n\n @returns true if the to be created object should be orthogonal.\n *\/\n virtual bool doConstructOrthogonal() const;\n\nprotected:\n DECL_LINK( DelayHdl, Timer * );\n long diffPoint (long pos1, long pos2);\n\n void ImpForceQuadratic(Rectangle& rRect);\n\n \/** Switch to another layer. The layer to switch to is specified by an\n offset relative to the active layer. With respect to the layer bar\n control at the lower left of the document window positive values\n move to the right and negative values move to the left.\n\n

Switching the layer is independant of the view's layer mode. The\n layers are switched even when the layer mode is turned off and the\n layer control is not visible.<\/p>\n @param nOffset\n If the offset is positive skip that many layers in selecting the\n next layer. If it is negative then select a previous one. An\n offset or zero does not change the current layer. If the\n resulting index lies outside the valid range of indices then it\n is set to either the minimal or maximal valid index, whitchever\n is nearer.\n *\/\n void SwitchLayer (sal_Int32 nOffset);\n\n ::sd::View* pView;\n ViewShell* pViewShell;\n ::sd::Window* pWindow;\n DrawDocShell* pDocSh;\n SdDrawDocument* pDoc;\n\n USHORT nSlotId;\n USHORT nSlotValue;\n\n Dialog* pDialog;\n\n Timer aScrollTimer; \/\/ fuer Autoscrolling\n DECL_LINK( ScrollHdl, Timer * );\n void ForceScroll(const Point& aPixPos);\n\n Timer aDragTimer; \/\/ fuer Drag&Drop\n DECL_LINK( DragHdl, Timer * );\n BOOL bIsInDragMode;\n Point aMDPos; \/\/ Position von MouseButtonDown\n\n \/\/ Flag, um AutoScrolling zu verhindern, bis von ausserhalb in das\n \/\/ Fenster hinein gedragt wurde\n BOOL bNoScrollUntilInside;\n\n \/\/ Timer um das scrolling zu verzoegern, wenn aus dem fenster\n \/\/ herausgedraggt wird (ca. 1 sec.)\n Timer aDelayToScrollTimer; \/\/ fuer Verzoegerung bis scroll\n BOOL bScrollable;\n BOOL bDelayActive;\n BOOL bFirstMouseMove;\n\n \/\/ #95491# member to hold state of the mouse buttons for creation\n \/\/ of own MouseEvents (like in ScrollHdl)\n\nprivate:\n sal_uInt16 mnCode;\n\n};\n\n} \/\/ end of namespace sd\n\n#endif \/\/ _SD_FUPOOR_HXX\n\nINTEGRATION: CWS impressfunctions (1.11.40); FILE MERGED 2005\/10\/28 11:26:06 cl 1.11.40.2: #125341# reworked FuPoor classes to use refcounting 2005\/10\/28 10:56:52 cl 1.11.40.1: #125341# reworked FuPoor classes to use refcounting\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: fupoor.hxx,v $\n *\n * $Revision: 1.12 $\n *\n * last change: $Author: rt $ $Date: 2005-12-14 17:14:51 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef SD_FU_POOR_HXX\n#define SD_FU_POOR_HXX\n\n#ifndef _RTTI_HXX \/\/autogen\n#include \n#endif\n#ifndef _SV_TIMER_HXX \/\/autogen\n#include \n#endif\n#ifndef _LINK_HXX \/\/autogen\n#include \n#endif\n#ifndef _GEN_HXX \/\/autogen\n#include \n#endif\n#ifndef _SV_EVENT_HXX \/\/autogen\n#include \n#endif\n#ifndef _RTL_REF_HXX_\n#include \n#endif\n\n#ifndef _SALHELPER_SIMPLEREFERENCECOMPONENT_HXX_\n#include \"helper\/simplereferencecomponent.hxx\"\n#endif\n\nclass SdDrawDocument;\nclass SfxRequest;\nclass Dialog;\nclass SdrObject;\n\nnamespace sd {\n\nclass DrawDocShell;\nclass View;\nclass ViewShell;\nclass Window;\n\n\/*************************************************************************\n|*\n|* Basisklasse fuer alle Funktionen\n|*\n\\************************************************************************\/\n\nclass FuPoor : public SimpleReferenceComponent\n{\npublic:\n static const int HITPIX = 2; \/\/ Hit-Toleranz in Pixel\n static const int DRGPIX = 2; \/\/ Drag MinMove in Pixel\n\n TYPEINFO();\n\n virtual void DoExecute( SfxRequest& rReq );\n\n \/\/ #95491# see member\n void SetMouseButtonCode(sal_uInt16 nNew) { if(nNew != mnCode) mnCode = nNew; }\n const sal_uInt16 GetMouseButtonCode() const { return mnCode; }\n\n DrawDocShell* GetDocSh() { return pDocSh; }\n SdDrawDocument* GetDoc() { return pDoc; }\n\n virtual void DoCut();\n virtual void DoCopy();\n virtual void DoPaste();\n\n \/\/ Mouse- & Key-Events; Returnwert=TRUE: Event wurde bearbeitet\n virtual BOOL KeyInput(const KeyEvent& rKEvt);\n virtual BOOL MouseMove(const MouseEvent& rMEvt) { return FALSE; }\n virtual BOOL MouseButtonUp(const MouseEvent& rMEvt);\n\n \/\/ #95491# moved from inline to *.cxx\n virtual BOOL MouseButtonDown(const MouseEvent& rMEvt);\n\n virtual BOOL Command(const CommandEvent& rCEvt);\n virtual BOOL RequestHelp(const HelpEvent& rHEvt);\n virtual void Paint(const Rectangle& rRect, ::sd::Window* pWin) {}\n virtual void ReceiveRequest(SfxRequest& rReq);\n\n virtual void Activate(); \/\/ Function aktivieren\n virtual void Deactivate(); \/\/ Function deaktivieren\n\n virtual void ScrollStart() {} \/\/ diese Funktionen werden von\n virtual void ScrollEnd() {} \/\/ ForceScroll aufgerufen\n\n void SetWindow(::sd::Window* pWin) { pWindow = pWin; }\n void WriteStatus(const String& aStr); \/\/ Statuszeile schreiben\n\n \/\/ #97016# II\n virtual void SelectionHasChanged();\n\n USHORT GetSlotID() const { return( nSlotId ); }\n USHORT GetSlotValue() const { return( nSlotValue ); }\n\n void SetNoScrollUntilInside(BOOL bNoScroll = TRUE)\n { bNoScrollUntilInside = bNoScroll; }\n\n void StartDelayToScrollTimer ();\n\n \/\/ #97016#\n virtual SdrObject* CreateDefaultObject(const sal_uInt16 nID, const Rectangle& rRectangle);\n\n \/** is called when the currenct function should be aborted.

\n This is used when a function gets a KEY_ESCAPE but can also\n be called directly.\n\n @returns true if a active function was aborted\n *\/\n virtual bool cancel();\n\n \/\/ #i33136#\n \/** Decide if the object to be created should be created\n orthogonal. Default implementation uses nSlotID\n to decide. May be overloaded to use other criterias\n for this decision\n\n @returns true if the to be created object should be orthogonal.\n *\/\n virtual bool doConstructOrthogonal() const;\n\nprotected:\n \/**\n @param pViewSh\n May be NULL.\n *\/\n FuPoor (ViewShell* pViewSh,\n ::sd::Window* pWin,\n ::sd::View* pView,\n SdDrawDocument* pDoc,\n SfxRequest& rReq);\n virtual ~FuPoor (void);\n\n DECL_LINK( DelayHdl, Timer * );\n long diffPoint (long pos1, long pos2);\n\n void ImpForceQuadratic(Rectangle& rRect);\n\n \/** Switch to another layer. The layer to switch to is specified by an\n offset relative to the active layer. With respect to the layer bar\n control at the lower left of the document window positive values\n move to the right and negative values move to the left.\n\n

Switching the layer is independant of the view's layer mode. The\n layers are switched even when the layer mode is turned off and the\n layer control is not visible.<\/p>\n @param nOffset\n If the offset is positive skip that many layers in selecting the\n next layer. If it is negative then select a previous one. An\n offset or zero does not change the current layer. If the\n resulting index lies outside the valid range of indices then it\n is set to either the minimal or maximal valid index, whitchever\n is nearer.\n *\/\n void SwitchLayer (sal_Int32 nOffset);\n\n ::sd::View* pView;\n ViewShell* pViewShell;\n ::sd::Window* pWindow;\n DrawDocShell* pDocSh;\n SdDrawDocument* pDoc;\n\n USHORT nSlotId;\n USHORT nSlotValue;\n\n Dialog* pDialog;\n\n Timer aScrollTimer; \/\/ fuer Autoscrolling\n DECL_LINK( ScrollHdl, Timer * );\n void ForceScroll(const Point& aPixPos);\n\n Timer aDragTimer; \/\/ fuer Drag&Drop\n DECL_LINK( DragHdl, Timer * );\n BOOL bIsInDragMode;\n Point aMDPos; \/\/ Position von MouseButtonDown\n\n \/\/ Flag, um AutoScrolling zu verhindern, bis von ausserhalb in das\n \/\/ Fenster hinein gedragt wurde\n BOOL bNoScrollUntilInside;\n\n \/\/ Timer um das scrolling zu verzoegern, wenn aus dem fenster\n \/\/ herausgedraggt wird (ca. 1 sec.)\n Timer aDelayToScrollTimer; \/\/ fuer Verzoegerung bis scroll\n BOOL bScrollable;\n BOOL bDelayActive;\n BOOL bFirstMouseMove;\n\n \/\/ #95491# member to hold state of the mouse buttons for creation\n \/\/ of own MouseEvents (like in ScrollHdl)\n\nprivate:\n sal_uInt16 mnCode;\n\n};\n\ntypedef rtl::Reference< FuPoor > FunctionReference;\n\n} \/\/ end of namespace sd\n\n#endif \/\/ _SD_FUPOOR_HXX\n\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * $RCSfile: unchss.hxx,v $\n *\n * $Revision: 1.1.1.1 $\n *\n * last change: $Author: hr $ $Date: 2000-09-18 16:48:42 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef _SD_UNCHSS_HXX\n#define _SD_UNCHSS_HXX\n\n#include \"sdundo.hxx\"\n\nclass SfxItemSet;\nclass SfxStyleSheet;\nclass SdDrawDocument;\n\nclass StyleSheetUndoAction : public SdUndoAction\n{\n SfxStyleSheet* pStyleSheet;\n\n SfxItemSet* pNewSet;\n SfxItemSet* pOldSet;\n String aComment;\n\npublic:\n TYPEINFO();\n StyleSheetUndoAction(SdDrawDocument* pTheDoc,\n SfxStyleSheet* pTheStyleSheet,\n const SfxItemSet* pTheNewItemSet);\n\n virtual ~StyleSheetUndoAction();\n virtual void Undo();\n virtual void Redo();\n virtual void Repeat();\n\n virtual String GetComment() const;\n\n \/\/ erst mal kein Repeat, da kein Kontext erreichbar\n virtual BOOL CanRepeat(SfxRepeatTarget&) const { return FALSE; }\n};\n\n#endif \/\/ _SD_UNCHSS_HXX\n\nINTEGRATION: CWS ooo19126 (1.1.1.1.930); FILE MERGED 2005\/09\/05 13:23:30 rt 1.1.1.1.930.1: #i54170# Change license header: remove SISSL\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: unchss.hxx,v $\n *\n * $Revision: 1.2 $\n *\n * last change: $Author: rt $ $Date: 2005-09-09 05:57:06 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef _SD_UNCHSS_HXX\n#define _SD_UNCHSS_HXX\n\n#include \"sdundo.hxx\"\n\nclass SfxItemSet;\nclass SfxStyleSheet;\nclass SdDrawDocument;\n\nclass StyleSheetUndoAction : public SdUndoAction\n{\n SfxStyleSheet* pStyleSheet;\n\n SfxItemSet* pNewSet;\n SfxItemSet* pOldSet;\n String aComment;\n\npublic:\n TYPEINFO();\n StyleSheetUndoAction(SdDrawDocument* pTheDoc,\n SfxStyleSheet* pTheStyleSheet,\n const SfxItemSet* pTheNewItemSet);\n\n virtual ~StyleSheetUndoAction();\n virtual void Undo();\n virtual void Redo();\n virtual void Repeat();\n\n virtual String GetComment() const;\n\n \/\/ erst mal kein Repeat, da kein Kontext erreichbar\n virtual BOOL CanRepeat(SfxRepeatTarget&) const { return FALSE; }\n};\n\n#endif \/\/ _SD_UNCHSS_HXX\n\n<|endoftext|>"} {"text":"#ifndef TEST_MEMORY_CLEANUP\n#define TEST_MEMORY_CLEANUP\n\n#if defined(HAS_XML2)\n#include \n#include \n#include \n#endif\n\n#if defined(HAVE_CAIRO)\n#include \n#endif\n\n#include \n#ifdef MAPNIK_USE_PROJ4\n#include \n#endif\n\nnamespace testing {\n\ninline void run_cleanup()\n{\n \/\/ only call this once, on exit\n \/\/ to make sure valgrind output is clean\n \/\/ http:\/\/xmlsoft.org\/xmlmem.html\n#if defined(HAS_XML2)\n xmlCleanupCharEncodingHandlers();\n xmlCleanupEncodingAliases();\n xmlCleanupGlobals();\n xmlCleanupParser();\n xmlCleanupThreads();\n xmlCleanupInputCallbacks();\n xmlCleanupOutputCallbacks();\n xmlCleanupMemory();\n#endif\n\n#if defined(HAVE_CAIRO)\n \/\/ http:\/\/cairographics.org\/manual\/cairo-Error-handling.html#cairo-debug-reset-static-data\n cairo_debug_reset_static_data();\n#endif\n\n \/\/ http:\/\/icu-project.org\/apiref\/icu4c\/uclean_8h.html#a93f27d0ddc7c196a1da864763f2d8920\n u_cleanup();\n\n#ifdef MAPNIK_USE_PROJ4\n \/\/ http:\/\/trac.osgeo.org\/proj\/ticket\/149\n #if PJ_VERSION >= 480\n pj_clear_initcache();\n #endif\n \/\/ https:\/\/trac.osgeo.org\/proj\/wiki\/ProjAPI#EnvironmentFunctions\n pj_deallocate_grids();\n#endif\n}\n\n}\n\n#endif\nuse correct define -> HAVE_LIBXML2#ifndef TEST_MEMORY_CLEANUP\n#define TEST_MEMORY_CLEANUP\n\n#if defined(HAVE_LIBXML2)\n#include \n#include \n#include \n#endif\n\n#if defined(HAVE_CAIRO)\n#include \n#endif\n\n#include \n#ifdef MAPNIK_USE_PROJ4\n#include \n#endif\n\nnamespace testing {\n\ninline void run_cleanup()\n{\n \/\/ only call this once, on exit\n \/\/ to make sure valgrind output is clean\n \/\/ http:\/\/xmlsoft.org\/xmlmem.html\n#if defined(HAVE_LIBXML2)\n xmlCleanupCharEncodingHandlers();\n xmlCleanupEncodingAliases();\n xmlCleanupGlobals();\n xmlCleanupParser();\n xmlCleanupThreads();\n xmlCleanupInputCallbacks();\n xmlCleanupOutputCallbacks();\n xmlCleanupMemory();\n#endif\n\n#if defined(HAVE_CAIRO)\n \/\/ http:\/\/cairographics.org\/manual\/cairo-Error-handling.html#cairo-debug-reset-static-data\n cairo_debug_reset_static_data();\n#endif\n\n \/\/ http:\/\/icu-project.org\/apiref\/icu4c\/uclean_8h.html#a93f27d0ddc7c196a1da864763f2d8920\n u_cleanup();\n\n#ifdef MAPNIK_USE_PROJ4\n \/\/ http:\/\/trac.osgeo.org\/proj\/ticket\/149\n #if PJ_VERSION >= 480\n pj_clear_initcache();\n #endif\n \/\/ https:\/\/trac.osgeo.org\/proj\/wiki\/ProjAPI#EnvironmentFunctions\n pj_deallocate_grids();\n#endif\n}\n\n}\n\n#endif\n<|endoftext|>"} {"text":"\/\/ @(#)root\/test:$Name$:$Id$\n\/\/ Author: Rene Brun 10\/01\/97\n\n{\n\/\/ This macro read all events generated by the test program Event\n\/\/ provided in $ROOTSYS\/test.\n\/\/\n\/\/ NOTE: Before executing this macro, you must have executed the macro eventload.\n\/\/\n\/\/ This small program simply counts the number of bytes read and dump\n\/\/ the first 3 events.\n\n gROOT->Reset();\n\n\/\/ Connect file generated in $ROOTSYS\/test\n TFile f(\"Event.root\");\n\n\/\/ Read Tree named \"T\" in memory. Tree pointer is assigned the same name\n TTree *T = (TTree*)f.Get(\"T\");\n\n\/\/ Create a timer object to benchmark this loop\n TStopwatch timer;\n timer.Start();\n\n\/\/ Start main loop on all events\n Event *event = new Event();\n T->SetBranchAddress(\"event\", &event);\n Int_t nevent = T->GetEntries();\n Int_t nb = 0;\n for (Int_t i=0;iGetEntry(i); \/\/read complete event in memory\n if (i < 3) event->Dump(); \/\/dump the first 3 events\n event->Clear(); \/\/clear tracks array\n }\n\n\/\/ Stop timer and print results\n timer.Stop();\n Float_t mbytes = 0.000001*nb;\n Double_t rtime = timer.RealTime();\n Double_t ctime = timer.CpuTime();\n printf(\"RealTime=%f seconds, CpuTime=%f seconds\\n\",rtime,ctime);\n printf(\"You read %f Mbytes\/Realtime seconds\\n\",mbytes\/rtime);\n printf(\"You read %f Mbytes\/Cputime seconds\\n\",mbytes\/ctime);\n printf(\"%d events and %d bytes read.\\n\",nevent,nb);\n\n f.Close();\n}\nRemove the call to event->Clear in the event loop. This call is not necessary anymore with the current or relative recent versions of ROOt\/\/ @(#)root\/test:$Name: $:$Id: eventa.cxx,v 1.2 2000\/07\/11 18:05:26 rdm Exp $\n\/\/ Author: Rene Brun 10\/01\/97\n\n{\n\/\/ This macro read all events generated by the test program Event\n\/\/ provided in $ROOTSYS\/test.\n\/\/\n\/\/ NOTE: Before executing this macro, you must have executed the macro eventload.\n\/\/\n\/\/ This small program simply counts the number of bytes read and dump\n\/\/ the first 3 events.\n\n gROOT->Reset();\n\n\/\/ Connect file generated in $ROOTSYS\/test\n TFile f(\"Event.root\");\n\n\/\/ Read Tree named \"T\" in memory. Tree pointer is assigned the same name\n TTree *T = (TTree*)f.Get(\"T\");\n\n\/\/ Create a timer object to benchmark this loop\n TStopwatch timer;\n timer.Start();\n\n\/\/ Start main loop on all events\n Event *event = new Event();\n T->SetBranchAddress(\"event\", &event);\n Int_t nevent = T->GetEntries();\n Int_t nb = 0;\n for (Int_t i=0;iGetEntry(i); \/\/read complete event in memory\n if (i < 3) event->Dump(); \/\/dump the first 3 events\n }\n\n\/\/ Stop timer and print results\n timer.Stop();\n Float_t mbytes = 0.000001*nb;\n Double_t rtime = timer.RealTime();\n Double_t ctime = timer.CpuTime();\n printf(\"RealTime=%f seconds, CpuTime=%f seconds\\n\",rtime,ctime);\n printf(\"You read %f Mbytes\/Realtime seconds\\n\",mbytes\/rtime);\n printf(\"You read %f Mbytes\/Cputime seconds\\n\",mbytes\/ctime);\n printf(\"%d events and %d bytes read.\\n\",nevent,nb);\n\n f.Close();\n}\n<|endoftext|>"} {"text":"#pragma once\n\n#include \n#include \n\n#include \"reflection_info.hpp\"\n\n\nnamespace shadow\n{\nclass director\n{\npublic:\n template \n director(TypeNameHolder,\n TypeInfoHolder,\n ConstructorInfoHolder,\n ConversionInfoHolder)\n : names_(std::begin(TypeNameHolder::value),\n std::end(TypeNameHolder::value)),\n type_infos_(std::begin(TypeInfoHolder::value),\n std::end(TypeInfoHolder::value)),\n constructor_infos_(std::begin(ConstructorInfoHolder::value),\n std::end(ConstructorInfoHolder::value)),\n conversion_infos_(std::begin(ConversionInfoHolder::value),\n std::end(ConversionInfoHolder::value))\n {\n }\n\nprivate:\n std::vector names_;\n std::vector type_infos_;\n std::vector constructor_infos_;\n std::vector conversion_infos_;\n};\n}\nRemove unused file. \tdeleted: include\/director.hpp<|endoftext|>"} {"text":"\/\/=======================================================================\n\/\/ Copyright (c) 2014-2015 Baptiste Wicht\n\/\/ Distributed under the terms of the MIT License.\n\/\/ (See accompanying file LICENSE or copy at\n\/\/ http:\/\/opensource.org\/licenses\/MIT)\n\/\/=======================================================================\n\n#pragma once\n\n#include \n\n#include \"cpp_utils\/tmp.hpp\"\n\nnamespace etl {\n\nnamespace math {\n\ninline float logistic_sigmoid(float x) {\n return 1.0f \/ (1.0f + std::exp(-x));\n}\n\ninline double logistic_sigmoid(double x) {\n return 1.0 \/ (1.0 + std::exp(-x));\n}\n\ninline float softplus(float x) {\n return std::log(1.0f + std::exp(x));\n}\n\ninline double softplus(double x) {\n return std::log(1.0 + std::exp(x));\n}\n\ntemplate \ninline constexpr double sign(W v) noexcept {\n return v == W(0) ? W(0) : (v > W(0) ? W(1) : W(-1));\n}\n\n} \/\/end of namespace math\n\n} \/\/end of namespace etl\nPrefer log1p(x) to log(1 + x)\/\/=======================================================================\n\/\/ Copyright (c) 2014-2015 Baptiste Wicht\n\/\/ Distributed under the terms of the MIT License.\n\/\/ (See accompanying file LICENSE or copy at\n\/\/ http:\/\/opensource.org\/licenses\/MIT)\n\/\/=======================================================================\n\n#pragma once\n\n#include \n\n#include \"cpp_utils\/tmp.hpp\"\n\nnamespace etl {\n\nnamespace math {\n\ninline float logistic_sigmoid(float x) {\n return 1.0f \/ (1.0f + std::exp(-x));\n}\n\ninline double logistic_sigmoid(double x) {\n return 1.0 \/ (1.0 + std::exp(-x));\n}\n\ninline float softplus(float x) {\n return std::log1p(std::exp(x));\n}\n\ninline double softplus(double x) {\n return std::log1p(std::exp(x));\n}\n\ntemplate \ninline constexpr double sign(W v) noexcept {\n return v == W(0) ? W(0) : (v > W(0) ? W(1) : W(-1));\n}\n\n} \/\/end of namespace math\n\n} \/\/end of namespace etl\n<|endoftext|>"} {"text":"\/\/===-- DWARFASTParserSwift.cpp ---------------------------------*- C++ -*-===\/\/\n\/\/\n\/\/ This source file is part of the Swift.org open source project\n\/\/\n\/\/ Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors\n\/\/ Licensed under Apache License v2.0 with Runtime Library Exception\n\/\/\n\/\/ See https:\/\/swift.org\/LICENSE.txt for license information\n\/\/ See https:\/\/swift.org\/CONTRIBUTORS.txt for the list of Swift project authors\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"DWARFASTParserSwift.h\"\n\n#include \"DWARFCompileUnit.h\"\n#include \"DWARFDIE.h\"\n#include \"DWARFDebugInfo.h\"\n#include \"DWARFDefines.h\"\n#include \"SymbolFileDWARF.h\"\n\n#include \"swift\/AST\/ASTContext.h\"\n\n#include \"lldb\/Utility\/Status.h\"\n#include \"lldb\/Core\/Module.h\"\n#include \"lldb\/Symbol\/CompileUnit.h\"\n#include \"lldb\/Symbol\/Function.h\"\n#include \"lldb\/Symbol\/ObjectFile.h\"\n#include \"lldb\/Symbol\/SwiftASTContext.h\"\n#include \"lldb\/Symbol\/Type.h\"\n#include \"lldb\/Target\/SwiftLanguageRuntime.h\"\n#include \"lldb\/Utility\/Log.h\"\n\nusing namespace lldb;\nusing namespace lldb_private;\n\nDWARFASTParserSwift::DWARFASTParserSwift(SwiftASTContext &ast) : m_ast(ast) {}\n\nDWARFASTParserSwift::~DWARFASTParserSwift() {}\n\nlldb::TypeSP DWARFASTParserSwift::ParseTypeFromDWARF(const SymbolContext &sc,\n const DWARFDIE &die,\n Log *log,\n bool *type_is_new_ptr) {\n lldb::TypeSP type_sp;\n CompilerType compiler_type;\n Status error;\n\n Declaration decl;\n ConstString mangled_name;\n ConstString name;\n\n DWARFAttributes attributes;\n const size_t num_attributes = die.GetAttributes(attributes);\n DWARFFormValue type_attr;\n\n if (num_attributes > 0) {\n uint32_t i;\n for (i = 0; i < num_attributes; ++i) {\n const dw_attr_t attr = attributes.AttributeAtIndex(i);\n DWARFFormValue form_value;\n if (attributes.ExtractFormValueAtIndex(i, form_value)) {\n switch (attr) {\n case DW_AT_decl_file:\n decl.SetFile(sc.comp_unit->GetSupportFiles().GetFileSpecAtIndex(\n form_value.Unsigned()));\n break;\n case DW_AT_decl_line:\n decl.SetLine(form_value.Unsigned());\n break;\n case DW_AT_decl_column:\n decl.SetColumn(form_value.Unsigned());\n break;\n case DW_AT_name:\n name.SetCString(form_value.AsCString());\n break;\n case DW_AT_linkage_name:\n case DW_AT_MIPS_linkage_name:\n mangled_name.SetCString(form_value.AsCString());\n break;\n default:\n break;\n }\n }\n }\n }\n\n if (!mangled_name && name) {\n if (SwiftLanguageRuntime::IsSwiftMangledName(name.GetCString()))\n mangled_name = name;\n else {\n const char *type_name_cstr = name.GetCString();\n \/\/ TODO: remove this once all mangled names are always included for all\n \/\/ types in DWARF\n swift::ModuleDecl *swift_module = m_ast.GetModule(decl.GetFile(), error);\n if (swift_module)\n compiler_type = m_ast.FindType(type_name_cstr, swift_module);\n\n if (!compiler_type) {\n \/\/ Anything from the swift module might be in a DW_TAG_typedef with a\n \/\/ name of \"Int\"\n \/\/ so we shuld also check the swift module if we fail to find our type\n \/\/ until we get\n \/\/ fixed.\n compiler_type =\n m_ast.FindFirstType(type_name_cstr, ConstString(\"Swift\"));\n }\n }\n }\n\n if (mangled_name) {\n \/\/ see if we parsed this type already\n type_sp = m_ast.GetCachedType(mangled_name);\n if (type_sp)\n return type_sp;\n\n \/\/ otherwise figure it out yourself\n compiler_type =\n m_ast.GetTypeFromMangledTypename(mangled_name.GetCString(), error);\n }\n\n if (!compiler_type && name) {\n if (name.GetStringRef().startswith(\"$swift.\") ||\n name.GetStringRef().startswith(SwiftLanguageRuntime::GetCurrentMangledName(\"_TtBp\").c_str())) { \/\/ This is the RawPointerType, need to figure out its name from the AST.\n swift::ASTContext *swift_ast_ctx = m_ast.GetASTContext();\n if (swift_ast_ctx)\n compiler_type =\n CompilerType(swift_ast_ctx, swift_ast_ctx->TheRawPointerType);\n else {\n if (log) {\n const char *file_name = \"\";\n SymbolFile *sym_file = m_ast.GetSymbolFile();\n if (sym_file) {\n ObjectFile *obj_file = sym_file->GetObjectFile();\n if (obj_file) {\n ModuleSP module_sp = obj_file->GetModule();\n if (module_sp)\n file_name = module_sp->GetFileSpec().GetFilename().AsCString();\n }\n }\n log->Printf(\"Got null AST context while looking up %s in %s.\",\n name.AsCString(), file_name);\n }\n return TypeSP();\n }\n }\n }\n\n switch (die.Tag()) {\n case DW_TAG_inlined_subroutine:\n case DW_TAG_subprogram:\n case DW_TAG_subroutine_type:\n if (!compiler_type || !compiler_type.IsFunctionType()) {\n \/\/ Make sure we at least have some function type. The mangling for the\n \/\/ \"top_level_code\"\n \/\/ is currently returning the emptyTupleType (originally \"_TtT_\") which is not a function type...\n compiler_type = m_ast.GetVoidFunctionType();\n }\n break;\n default:\n break;\n }\n\n if (compiler_type) {\n type_sp = TypeSP(new Type(\n die.GetID(), die.GetDWARF(), compiler_type.GetTypeName(),\n compiler_type.GetByteSize(nullptr), NULL, LLDB_INVALID_UID,\n Type::eEncodingIsUID, &decl, compiler_type, Type::eResolveStateFull));\n }\n\n \/\/ cache this type\n if (type_sp && mangled_name\n && SwiftLanguageRuntime::IsSwiftMangledName(mangled_name.GetCString()))\n m_ast.SetCachedType(mangled_name, type_sp);\n\n return type_sp;\n}\n\nFunction *DWARFASTParserSwift::ParseFunctionFromDWARF(const SymbolContext &sc,\n const DWARFDIE &die) {\n DWARFRangeList func_ranges;\n const char *name = NULL;\n const char *mangled = NULL;\n int decl_file = 0;\n int decl_line = 0;\n int decl_column = 0;\n int call_file = 0;\n int call_line = 0;\n int call_column = 0;\n DWARFExpression frame_base(die.GetCU());\n\n if (die.Tag() != DW_TAG_subprogram)\n return NULL;\n\n if (die.GetDIENamesAndRanges(name, mangled, func_ranges, decl_file, decl_line,\n decl_column, call_file, call_line, call_column,\n &frame_base)) {\n \/\/ Union of all ranges in the function DIE (if the function is\n \/\/ discontiguous)\n SymbolFileDWARF *dwarf = die.GetDWARF();\n AddressRange func_range;\n lldb::addr_t lowest_func_addr = func_ranges.GetMinRangeBase(0);\n lldb::addr_t highest_func_addr = func_ranges.GetMaxRangeEnd(0);\n if (lowest_func_addr != LLDB_INVALID_ADDRESS &&\n lowest_func_addr <= highest_func_addr) {\n ModuleSP module_sp(dwarf->GetObjectFile()->GetModule());\n func_range.GetBaseAddress().ResolveAddressUsingFileSections(\n lowest_func_addr, module_sp->GetSectionList());\n if (func_range.GetBaseAddress().IsValid())\n func_range.SetByteSize(highest_func_addr - lowest_func_addr);\n }\n\n if (func_range.GetBaseAddress().IsValid()) {\n Mangled func_name;\n if (mangled)\n func_name.SetValue(ConstString(mangled), true);\n else\n func_name.SetValue(ConstString(name), false);\n \n \/\/ See if this function can throw. We can't get that from the\n \/\/ mangled name (even though the information is often there)\n \/\/ because Swift reserves the right to omit it from the name\n \/\/ if it doesn't need it. So instead we look for the\n \/\/ DW_TAG_thrown_error:\n \n bool can_throw = false;\n \n DWARFDebugInfoEntry *child(die.GetFirstChild().GetDIE());\n while (child)\n {\n if (child->Tag() == DW_TAG_thrown_type)\n {\n can_throw = true;\n break;\n }\n child = child->GetSibling();\n }\n\n FunctionSP func_sp;\n std::unique_ptr decl_ap;\n if (decl_file != 0 || decl_line != 0 || decl_column != 0)\n decl_ap.reset(new Declaration(\n sc.comp_unit->GetSupportFiles().GetFileSpecAtIndex(decl_file),\n decl_line, decl_column));\n\n if (dwarf->FixupAddress(func_range.GetBaseAddress())) {\n const user_id_t func_user_id = die.GetID();\n func_sp.reset(new Function(sc.comp_unit, func_user_id, func_user_id,\n func_name, nullptr,\n func_range, can_throw)); \/\/ first address range\n\n if (func_sp.get() != NULL) {\n if (frame_base.IsValid())\n func_sp->GetFrameBaseExpression() = frame_base;\n sc.comp_unit->AddFunction(func_sp);\n return func_sp.get();\n }\n }\n }\n }\n return NULL;\n}\n\nlldb_private::CompilerDeclContext\nDWARFASTParserSwift::GetDeclContextForUIDFromDWARF(const DWARFDIE &die) {\n return CompilerDeclContext();\n}\n\nlldb_private::CompilerDeclContext\nDWARFASTParserSwift::GetDeclContextContainingUIDFromDWARF(const DWARFDIE &die) {\n return CompilerDeclContext();\n}\nfix typo in comment\/\/===-- DWARFASTParserSwift.cpp ---------------------------------*- C++ -*-===\/\/\n\/\/\n\/\/ This source file is part of the Swift.org open source project\n\/\/\n\/\/ Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors\n\/\/ Licensed under Apache License v2.0 with Runtime Library Exception\n\/\/\n\/\/ See https:\/\/swift.org\/LICENSE.txt for license information\n\/\/ See https:\/\/swift.org\/CONTRIBUTORS.txt for the list of Swift project authors\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"DWARFASTParserSwift.h\"\n\n#include \"DWARFCompileUnit.h\"\n#include \"DWARFDIE.h\"\n#include \"DWARFDebugInfo.h\"\n#include \"DWARFDefines.h\"\n#include \"SymbolFileDWARF.h\"\n\n#include \"swift\/AST\/ASTContext.h\"\n\n#include \"lldb\/Utility\/Status.h\"\n#include \"lldb\/Core\/Module.h\"\n#include \"lldb\/Symbol\/CompileUnit.h\"\n#include \"lldb\/Symbol\/Function.h\"\n#include \"lldb\/Symbol\/ObjectFile.h\"\n#include \"lldb\/Symbol\/SwiftASTContext.h\"\n#include \"lldb\/Symbol\/Type.h\"\n#include \"lldb\/Target\/SwiftLanguageRuntime.h\"\n#include \"lldb\/Utility\/Log.h\"\n\nusing namespace lldb;\nusing namespace lldb_private;\n\nDWARFASTParserSwift::DWARFASTParserSwift(SwiftASTContext &ast) : m_ast(ast) {}\n\nDWARFASTParserSwift::~DWARFASTParserSwift() {}\n\nlldb::TypeSP DWARFASTParserSwift::ParseTypeFromDWARF(const SymbolContext &sc,\n const DWARFDIE &die,\n Log *log,\n bool *type_is_new_ptr) {\n lldb::TypeSP type_sp;\n CompilerType compiler_type;\n Status error;\n\n Declaration decl;\n ConstString mangled_name;\n ConstString name;\n\n DWARFAttributes attributes;\n const size_t num_attributes = die.GetAttributes(attributes);\n DWARFFormValue type_attr;\n\n if (num_attributes > 0) {\n uint32_t i;\n for (i = 0; i < num_attributes; ++i) {\n const dw_attr_t attr = attributes.AttributeAtIndex(i);\n DWARFFormValue form_value;\n if (attributes.ExtractFormValueAtIndex(i, form_value)) {\n switch (attr) {\n case DW_AT_decl_file:\n decl.SetFile(sc.comp_unit->GetSupportFiles().GetFileSpecAtIndex(\n form_value.Unsigned()));\n break;\n case DW_AT_decl_line:\n decl.SetLine(form_value.Unsigned());\n break;\n case DW_AT_decl_column:\n decl.SetColumn(form_value.Unsigned());\n break;\n case DW_AT_name:\n name.SetCString(form_value.AsCString());\n break;\n case DW_AT_linkage_name:\n case DW_AT_MIPS_linkage_name:\n mangled_name.SetCString(form_value.AsCString());\n break;\n default:\n break;\n }\n }\n }\n }\n\n if (!mangled_name && name) {\n if (SwiftLanguageRuntime::IsSwiftMangledName(name.GetCString()))\n mangled_name = name;\n else {\n const char *type_name_cstr = name.GetCString();\n \/\/ TODO: remove this once all mangled names are always included for all\n \/\/ types in DWARF\n swift::ModuleDecl *swift_module = m_ast.GetModule(decl.GetFile(), error);\n if (swift_module)\n compiler_type = m_ast.FindType(type_name_cstr, swift_module);\n\n if (!compiler_type) {\n \/\/ Anything from the swift module might be in a DW_TAG_typedef with a\n \/\/ name of \"Int\"\n \/\/ so we shuld also check the swift module if we fail to find our type\n \/\/ until we get\n \/\/ fixed.\n compiler_type =\n m_ast.FindFirstType(type_name_cstr, ConstString(\"Swift\"));\n }\n }\n }\n\n if (mangled_name) {\n \/\/ see if we parsed this type already\n type_sp = m_ast.GetCachedType(mangled_name);\n if (type_sp)\n return type_sp;\n\n \/\/ otherwise figure it out yourself\n compiler_type =\n m_ast.GetTypeFromMangledTypename(mangled_name.GetCString(), error);\n }\n\n if (!compiler_type && name) {\n if (name.GetStringRef().startswith(\"$swift.\") ||\n name.GetStringRef().startswith(SwiftLanguageRuntime::GetCurrentMangledName(\"_TtBp\").c_str())) { \/\/ This is the RawPointerType, need to figure out its name from the AST.\n swift::ASTContext *swift_ast_ctx = m_ast.GetASTContext();\n if (swift_ast_ctx)\n compiler_type =\n CompilerType(swift_ast_ctx, swift_ast_ctx->TheRawPointerType);\n else {\n if (log) {\n const char *file_name = \"\";\n SymbolFile *sym_file = m_ast.GetSymbolFile();\n if (sym_file) {\n ObjectFile *obj_file = sym_file->GetObjectFile();\n if (obj_file) {\n ModuleSP module_sp = obj_file->GetModule();\n if (module_sp)\n file_name = module_sp->GetFileSpec().GetFilename().AsCString();\n }\n }\n log->Printf(\"Got null AST context while looking up %s in %s.\",\n name.AsCString(), file_name);\n }\n return TypeSP();\n }\n }\n }\n\n switch (die.Tag()) {\n case DW_TAG_inlined_subroutine:\n case DW_TAG_subprogram:\n case DW_TAG_subroutine_type:\n if (!compiler_type || !compiler_type.IsFunctionType()) {\n \/\/ Make sure we at least have some function type. The mangling for the\n \/\/ \"top_level_code\"\n \/\/ is currently returning the emptyTupleType (originally \"_TtT_\") which is not a function type...\n compiler_type = m_ast.GetVoidFunctionType();\n }\n break;\n default:\n break;\n }\n\n if (compiler_type) {\n type_sp = TypeSP(new Type(\n die.GetID(), die.GetDWARF(), compiler_type.GetTypeName(),\n compiler_type.GetByteSize(nullptr), NULL, LLDB_INVALID_UID,\n Type::eEncodingIsUID, &decl, compiler_type, Type::eResolveStateFull));\n }\n\n \/\/ cache this type\n if (type_sp && mangled_name\n && SwiftLanguageRuntime::IsSwiftMangledName(mangled_name.GetCString()))\n m_ast.SetCachedType(mangled_name, type_sp);\n\n return type_sp;\n}\n\nFunction *DWARFASTParserSwift::ParseFunctionFromDWARF(const SymbolContext &sc,\n const DWARFDIE &die) {\n DWARFRangeList func_ranges;\n const char *name = NULL;\n const char *mangled = NULL;\n int decl_file = 0;\n int decl_line = 0;\n int decl_column = 0;\n int call_file = 0;\n int call_line = 0;\n int call_column = 0;\n DWARFExpression frame_base(die.GetCU());\n\n if (die.Tag() != DW_TAG_subprogram)\n return NULL;\n\n if (die.GetDIENamesAndRanges(name, mangled, func_ranges, decl_file, decl_line,\n decl_column, call_file, call_line, call_column,\n &frame_base)) {\n \/\/ Union of all ranges in the function DIE (if the function is\n \/\/ discontiguous)\n SymbolFileDWARF *dwarf = die.GetDWARF();\n AddressRange func_range;\n lldb::addr_t lowest_func_addr = func_ranges.GetMinRangeBase(0);\n lldb::addr_t highest_func_addr = func_ranges.GetMaxRangeEnd(0);\n if (lowest_func_addr != LLDB_INVALID_ADDRESS &&\n lowest_func_addr <= highest_func_addr) {\n ModuleSP module_sp(dwarf->GetObjectFile()->GetModule());\n func_range.GetBaseAddress().ResolveAddressUsingFileSections(\n lowest_func_addr, module_sp->GetSectionList());\n if (func_range.GetBaseAddress().IsValid())\n func_range.SetByteSize(highest_func_addr - lowest_func_addr);\n }\n\n if (func_range.GetBaseAddress().IsValid()) {\n Mangled func_name;\n if (mangled)\n func_name.SetValue(ConstString(mangled), true);\n else\n func_name.SetValue(ConstString(name), false);\n \n \/\/ See if this function can throw. We can't get that from the\n \/\/ mangled name (even though the information is often there)\n \/\/ because Swift reserves the right to omit it from the name\n \/\/ if it doesn't need it. So instead we look for the\n \/\/ DW_TAG_thrown_type:\n \n bool can_throw = false;\n \n DWARFDebugInfoEntry *child(die.GetFirstChild().GetDIE());\n while (child)\n {\n if (child->Tag() == DW_TAG_thrown_type)\n {\n can_throw = true;\n break;\n }\n child = child->GetSibling();\n }\n\n FunctionSP func_sp;\n std::unique_ptr decl_ap;\n if (decl_file != 0 || decl_line != 0 || decl_column != 0)\n decl_ap.reset(new Declaration(\n sc.comp_unit->GetSupportFiles().GetFileSpecAtIndex(decl_file),\n decl_line, decl_column));\n\n if (dwarf->FixupAddress(func_range.GetBaseAddress())) {\n const user_id_t func_user_id = die.GetID();\n func_sp.reset(new Function(sc.comp_unit, func_user_id, func_user_id,\n func_name, nullptr,\n func_range, can_throw)); \/\/ first address range\n\n if (func_sp.get() != NULL) {\n if (frame_base.IsValid())\n func_sp->GetFrameBaseExpression() = frame_base;\n sc.comp_unit->AddFunction(func_sp);\n return func_sp.get();\n }\n }\n }\n }\n return NULL;\n}\n\nlldb_private::CompilerDeclContext\nDWARFASTParserSwift::GetDeclContextForUIDFromDWARF(const DWARFDIE &die) {\n return CompilerDeclContext();\n}\n\nlldb_private::CompilerDeclContext\nDWARFASTParserSwift::GetDeclContextContainingUIDFromDWARF(const DWARFDIE &die) {\n return CompilerDeclContext();\n}\n<|endoftext|>"} {"text":"\/\/ Copyright 2012 Google Inc. All Rights Reserved.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \"subprocess.h\"\n\n#include \"test.h\"\n\n#ifndef _WIN32\n\/\/ SetWithLots need setrlimit.\n#include \n#include \n#include \n#include \n#endif\n\nnamespace {\n\n#ifdef _WIN32\nconst char* kSimpleCommand = \"cmd \/c dir \\\\\";\n#else\nconst char* kSimpleCommand = \"ls \/\";\n#endif\n\nstruct SubprocessTest : public testing::Test {\n SubprocessSet subprocs_;\n};\n\n} \/\/ anonymous namespace\n\n\/\/ Run a command that fails and emits to stderr.\nTEST_F(SubprocessTest, BadCommandStderr) {\n Subprocess* subproc = subprocs_.Add(\"cmd \/c ninja_no_such_command\");\n ASSERT_NE((Subprocess *) 0, subproc);\n\n while (!subproc->Done()) {\n \/\/ Pretend we discovered that stderr was ready for writing.\n subprocs_.DoWork();\n }\n\n EXPECT_EQ(ExitFailure, subproc->Finish());\n EXPECT_NE(\"\", subproc->GetOutput());\n}\n\n\/\/ Run a command that does not exist\nTEST_F(SubprocessTest, NoSuchCommand) {\n Subprocess* subproc = subprocs_.Add(\"ninja_no_such_command\");\n ASSERT_NE((Subprocess *) 0, subproc);\n\n while (!subproc->Done()) {\n \/\/ Pretend we discovered that stderr was ready for writing.\n subprocs_.DoWork();\n }\n\n EXPECT_EQ(ExitFailure, subproc->Finish());\n EXPECT_NE(\"\", subproc->GetOutput());\n#ifdef _WIN32\n ASSERT_EQ(\"CreateProcess failed: The system cannot find the file \"\n \"specified.\\n\", subproc->GetOutput());\n#endif\n}\n\n#ifndef _WIN32\n\nTEST_F(SubprocessTest, InterruptChild) {\n Subprocess* subproc = subprocs_.Add(\"kill -INT $$\");\n ASSERT_NE((Subprocess *) 0, subproc);\n\n while (!subproc->Done()) {\n subprocs_.DoWork();\n }\n\n EXPECT_EQ(ExitInterrupted, subproc->Finish());\n}\n\nTEST_F(SubprocessTest, InterruptParent) {\n Subprocess* subproc = subprocs_.Add(\"kill -INT $PPID ; sleep 1\");\n ASSERT_NE((Subprocess *) 0, subproc);\n\n while (!subproc->Done()) {\n bool interrupted = subprocs_.DoWork();\n if (interrupted)\n return;\n }\n\n ASSERT_FALSE(\"We should have been interrupted\");\n}\n\nTEST_F(SubprocessTest, Console) {\n \/\/ Skip test if we don't have the console ourselves.\n if (isatty(0) && isatty(1) && isatty(2)) {\n Subprocess* subproc = subprocs_.Add(\"test -t 0 -a -t 1 -a -t 2\",\n \/*use_console=*\/true);\n ASSERT_NE((Subprocess *) 0, subproc);\n\n while (!subproc->Done()) {\n subprocs_.DoWork();\n }\n\n EXPECT_EQ(ExitSuccess, subproc->Finish());\n }\n}\n\n#endif\n\nTEST_F(SubprocessTest, SetWithSingle) {\n Subprocess* subproc = subprocs_.Add(kSimpleCommand);\n ASSERT_NE((Subprocess *) 0, subproc);\n\n while (!subproc->Done()) {\n subprocs_.DoWork();\n }\n ASSERT_EQ(ExitSuccess, subproc->Finish());\n ASSERT_NE(\"\", subproc->GetOutput());\n\n ASSERT_EQ(1u, subprocs_.finished_.size());\n}\n\nTEST_F(SubprocessTest, SetWithMulti) {\n Subprocess* processes[3];\n const char* kCommands[3] = {\n kSimpleCommand,\n#ifdef _WIN32\n \"cmd \/c echo hi\",\n \"cmd \/c time \/t\",\n#else\n \"whoami\",\n \"pwd\",\n#endif\n };\n\n for (int i = 0; i < 3; ++i) {\n processes[i] = subprocs_.Add(kCommands[i]);\n ASSERT_NE((Subprocess *) 0, processes[i]);\n }\n\n ASSERT_EQ(3u, subprocs_.running_.size());\n for (int i = 0; i < 3; ++i) {\n ASSERT_FALSE(processes[i]->Done());\n ASSERT_EQ(\"\", processes[i]->GetOutput());\n }\n\n while (!processes[0]->Done() || !processes[1]->Done() ||\n !processes[2]->Done()) {\n ASSERT_GT(subprocs_.running_.size(), 0u);\n subprocs_.DoWork();\n }\n\n ASSERT_EQ(0u, subprocs_.running_.size());\n ASSERT_EQ(3u, subprocs_.finished_.size());\n\n for (int i = 0; i < 3; ++i) {\n ASSERT_EQ(ExitSuccess, processes[i]->Finish());\n ASSERT_NE(\"\", processes[i]->GetOutput());\n delete processes[i];\n }\n}\n\n\/\/ OS X's process limit is less than 1025 by default\n\/\/ (|sysctl kern.maxprocperuid| is 709 on 10.7 and 10.8 and less prior to that).\n#if !defined(__APPLE__) && !defined(_WIN32)\nTEST_F(SubprocessTest, SetWithLots) {\n \/\/ Arbitrary big number; needs to be over 1024 to confirm we're no longer\n \/\/ hostage to pselect.\n const size_t kNumProcs = 1025;\n\n \/\/ Make sure [ulimit -n] isn't going to stop us from working.\n rlimit rlim;\n ASSERT_EQ(0, getrlimit(RLIMIT_NOFILE, &rlim));\n if (!EXPECT_GT(rlim.rlim_cur, kNumProcs)) {\n printf(\"Raise [ulimit -n] well above %u to make this test go\\n\", kNumProcs);\n return;\n }\n\n vector procs;\n for (size_t i = 0; i < kNumProcs; ++i) {\n Subprocess* subproc = subprocs_.Add(\"\/bin\/echo\");\n ASSERT_NE((Subprocess *) 0, subproc);\n procs.push_back(subproc);\n }\n while (!subprocs_.running_.empty())\n subprocs_.DoWork();\n for (size_t i = 0; i < procs.size(); ++i) {\n ASSERT_EQ(ExitSuccess, procs[i]->Finish());\n ASSERT_NE(\"\", procs[i]->GetOutput());\n }\n ASSERT_EQ(kNumProcs, subprocs_.finished_.size());\n}\n#endif \/\/ !__APPLE__ && !_WIN32 \n\n\/\/ TODO: this test could work on Windows, just not sure how to simply\n\/\/ read stdin.\n#ifndef _WIN32\n\/\/ Verify that a command that attempts to read stdin correctly thinks\n\/\/ that stdin is closed.\nTEST_F(SubprocessTest, ReadStdin) {\n Subprocess* subproc = subprocs_.Add(\"cat -\");\n while (!subproc->Done()) {\n subprocs_.DoWork();\n }\n ASSERT_EQ(ExitSuccess, subproc->Finish());\n ASSERT_EQ(1u, subprocs_.finished_.size());\n}\n#endif \/\/ _WIN32\nfix warning\/\/ Copyright 2012 Google Inc. All Rights Reserved.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \"subprocess.h\"\n\n#include \"test.h\"\n\n#ifndef _WIN32\n\/\/ SetWithLots need setrlimit.\n#include \n#include \n#include \n#include \n#endif\n\nnamespace {\n\n#ifdef _WIN32\nconst char* kSimpleCommand = \"cmd \/c dir \\\\\";\n#else\nconst char* kSimpleCommand = \"ls \/\";\n#endif\n\nstruct SubprocessTest : public testing::Test {\n SubprocessSet subprocs_;\n};\n\n} \/\/ anonymous namespace\n\n\/\/ Run a command that fails and emits to stderr.\nTEST_F(SubprocessTest, BadCommandStderr) {\n Subprocess* subproc = subprocs_.Add(\"cmd \/c ninja_no_such_command\");\n ASSERT_NE((Subprocess *) 0, subproc);\n\n while (!subproc->Done()) {\n \/\/ Pretend we discovered that stderr was ready for writing.\n subprocs_.DoWork();\n }\n\n EXPECT_EQ(ExitFailure, subproc->Finish());\n EXPECT_NE(\"\", subproc->GetOutput());\n}\n\n\/\/ Run a command that does not exist\nTEST_F(SubprocessTest, NoSuchCommand) {\n Subprocess* subproc = subprocs_.Add(\"ninja_no_such_command\");\n ASSERT_NE((Subprocess *) 0, subproc);\n\n while (!subproc->Done()) {\n \/\/ Pretend we discovered that stderr was ready for writing.\n subprocs_.DoWork();\n }\n\n EXPECT_EQ(ExitFailure, subproc->Finish());\n EXPECT_NE(\"\", subproc->GetOutput());\n#ifdef _WIN32\n ASSERT_EQ(\"CreateProcess failed: The system cannot find the file \"\n \"specified.\\n\", subproc->GetOutput());\n#endif\n}\n\n#ifndef _WIN32\n\nTEST_F(SubprocessTest, InterruptChild) {\n Subprocess* subproc = subprocs_.Add(\"kill -INT $$\");\n ASSERT_NE((Subprocess *) 0, subproc);\n\n while (!subproc->Done()) {\n subprocs_.DoWork();\n }\n\n EXPECT_EQ(ExitInterrupted, subproc->Finish());\n}\n\nTEST_F(SubprocessTest, InterruptParent) {\n Subprocess* subproc = subprocs_.Add(\"kill -INT $PPID ; sleep 1\");\n ASSERT_NE((Subprocess *) 0, subproc);\n\n while (!subproc->Done()) {\n bool interrupted = subprocs_.DoWork();\n if (interrupted)\n return;\n }\n\n ASSERT_FALSE(\"We should have been interrupted\");\n}\n\nTEST_F(SubprocessTest, Console) {\n \/\/ Skip test if we don't have the console ourselves.\n if (isatty(0) && isatty(1) && isatty(2)) {\n Subprocess* subproc = subprocs_.Add(\"test -t 0 -a -t 1 -a -t 2\",\n \/*use_console=*\/true);\n ASSERT_NE((Subprocess *) 0, subproc);\n\n while (!subproc->Done()) {\n subprocs_.DoWork();\n }\n\n EXPECT_EQ(ExitSuccess, subproc->Finish());\n }\n}\n\n#endif\n\nTEST_F(SubprocessTest, SetWithSingle) {\n Subprocess* subproc = subprocs_.Add(kSimpleCommand);\n ASSERT_NE((Subprocess *) 0, subproc);\n\n while (!subproc->Done()) {\n subprocs_.DoWork();\n }\n ASSERT_EQ(ExitSuccess, subproc->Finish());\n ASSERT_NE(\"\", subproc->GetOutput());\n\n ASSERT_EQ(1u, subprocs_.finished_.size());\n}\n\nTEST_F(SubprocessTest, SetWithMulti) {\n Subprocess* processes[3];\n const char* kCommands[3] = {\n kSimpleCommand,\n#ifdef _WIN32\n \"cmd \/c echo hi\",\n \"cmd \/c time \/t\",\n#else\n \"whoami\",\n \"pwd\",\n#endif\n };\n\n for (int i = 0; i < 3; ++i) {\n processes[i] = subprocs_.Add(kCommands[i]);\n ASSERT_NE((Subprocess *) 0, processes[i]);\n }\n\n ASSERT_EQ(3u, subprocs_.running_.size());\n for (int i = 0; i < 3; ++i) {\n ASSERT_FALSE(processes[i]->Done());\n ASSERT_EQ(\"\", processes[i]->GetOutput());\n }\n\n while (!processes[0]->Done() || !processes[1]->Done() ||\n !processes[2]->Done()) {\n ASSERT_GT(subprocs_.running_.size(), 0u);\n subprocs_.DoWork();\n }\n\n ASSERT_EQ(0u, subprocs_.running_.size());\n ASSERT_EQ(3u, subprocs_.finished_.size());\n\n for (int i = 0; i < 3; ++i) {\n ASSERT_EQ(ExitSuccess, processes[i]->Finish());\n ASSERT_NE(\"\", processes[i]->GetOutput());\n delete processes[i];\n }\n}\n\n\/\/ OS X's process limit is less than 1025 by default\n\/\/ (|sysctl kern.maxprocperuid| is 709 on 10.7 and 10.8 and less prior to that).\n#if !defined(__APPLE__) && !defined(_WIN32)\nTEST_F(SubprocessTest, SetWithLots) {\n \/\/ Arbitrary big number; needs to be over 1024 to confirm we're no longer\n \/\/ hostage to pselect.\n const unsigned kNumProcs = 1025;\n\n \/\/ Make sure [ulimit -n] isn't going to stop us from working.\n rlimit rlim;\n ASSERT_EQ(0, getrlimit(RLIMIT_NOFILE, &rlim));\n if (!EXPECT_GT(rlim.rlim_cur, kNumProcs)) {\n printf(\"Raise [ulimit -n] well above %u to make this test go\\n\", kNumProcs);\n return;\n }\n\n vector procs;\n for (size_t i = 0; i < kNumProcs; ++i) {\n Subprocess* subproc = subprocs_.Add(\"\/bin\/echo\");\n ASSERT_NE((Subprocess *) 0, subproc);\n procs.push_back(subproc);\n }\n while (!subprocs_.running_.empty())\n subprocs_.DoWork();\n for (size_t i = 0; i < procs.size(); ++i) {\n ASSERT_EQ(ExitSuccess, procs[i]->Finish());\n ASSERT_NE(\"\", procs[i]->GetOutput());\n }\n ASSERT_EQ(kNumProcs, subprocs_.finished_.size());\n}\n#endif \/\/ !__APPLE__ && !_WIN32 \n\n\/\/ TODO: this test could work on Windows, just not sure how to simply\n\/\/ read stdin.\n#ifndef _WIN32\n\/\/ Verify that a command that attempts to read stdin correctly thinks\n\/\/ that stdin is closed.\nTEST_F(SubprocessTest, ReadStdin) {\n Subprocess* subproc = subprocs_.Add(\"cat -\");\n while (!subproc->Done()) {\n subprocs_.DoWork();\n }\n ASSERT_EQ(ExitSuccess, subproc->Finish());\n ASSERT_EQ(1u, subprocs_.finished_.size());\n}\n#endif \/\/ _WIN32\n<|endoftext|>"} {"text":"#define CATCH_CONFIG_MAIN\n#include \"catch.hpp\"\n\n#include \"..\/src\/cxxopts.hpp\"\n\nclass Argv {\n public:\n\n Argv(int n, const char** argv) \n : m_argv(new char*[n])\n {\n for (int i = 0; i != n; ++i) {\n auto len = strlen(argv[i]) + 1;\n auto ptr = std::unique_ptr(new char[len]);\n\n strcpy(ptr.get(), argv[i]);\n m_args.push_back(std::move(ptr));\n m_argv.get()[i] = m_args.back().get();\n }\n }\n\n char** argv() const {\n return m_argv.get();\n }\n\n private:\n\n std::vector> m_args;\n std::unique_ptr m_argv;\n};\n\nTEST_CASE(\"Basic options\", \"[options]\")\n{\n\n cxxopts::Options options(\"tester\", \" - test basic options\");\n\n options.add_options()\n (\"long\", \"a long option\")\n (\"s,short\", \"a short option\")\n (\"value\", \"an option with a value\", cxxopts::value())\n (\"a,av\", \"a short option with a value\", cxxopts::value());\n\n const char* args[] = {\n \"tester\",\n \"--long\",\n \"-s\",\n \"--value\",\n \"value\",\n \"-a\",\n \"b\"\n };\n\n int argc = sizeof(args) \/ sizeof(args[0]);\n\n Argv argv(argc, args);\n\n char** actual_argv = argv.argv();\n\n options.parse(argc, actual_argv);\n\n CHECK(options.count(\"long\") == 1);\n}\nadd some more tests#define CATCH_CONFIG_MAIN\n#include \"catch.hpp\"\n\n#include \"..\/src\/cxxopts.hpp\"\n\nclass Argv {\n public:\n\n Argv(int n, const char** argv) \n : m_argv(new char*[n])\n {\n for (int i = 0; i != n; ++i) {\n auto len = strlen(argv[i]) + 1;\n auto ptr = std::unique_ptr(new char[len]);\n\n strcpy(ptr.get(), argv[i]);\n m_args.push_back(std::move(ptr));\n m_argv.get()[i] = m_args.back().get();\n }\n }\n\n char** argv() const {\n return m_argv.get();\n }\n\n private:\n\n std::vector> m_args;\n std::unique_ptr m_argv;\n};\n\nTEST_CASE(\"Basic options\", \"[options]\")\n{\n\n cxxopts::Options options(\"tester\", \" - test basic options\");\n\n options.add_options()\n (\"long\", \"a long option\")\n (\"s,short\", \"a short option\")\n (\"value\", \"an option with a value\", cxxopts::value())\n (\"a,av\", \"a short option with a value\", cxxopts::value());\n\n const char* args[] = {\n \"tester\",\n \"--long\",\n \"-s\",\n \"--value\",\n \"value\",\n \"-a\",\n \"b\"\n };\n\n int argc = sizeof(args) \/ sizeof(args[0]);\n\n Argv argv(argc, args);\n\n char** actual_argv = argv.argv();\n\n options.parse(argc, actual_argv);\n\n CHECK(options.count(\"long\") == 1);\n CHECK(options.count(\"s\") == 1);\n CHECK(options.count(\"value\") == 1);\n CHECK(options.count(\"a\") == 1);\n CHECK(options[\"value\"].as() == \"value\");\n CHECK(options[\"a\"].as() == \"b\");\n}\n<|endoftext|>"} {"text":"\/* Copyright (c) 2010-2013, AOYAMA Kazuharu\n * All rights reserved.\n *\n * This software may be used and distributed according to the terms of\n * the New BSD License, which is incorporated herein by reference.\n *\/\n\n#include \n#include \n#include \n\n\/*!\n \\class TAbstractModel\n \\brief The TAbstractModel class is the abstract base class of models,\n providing functionality common to models.\n*\/\n\n\/*!\n Returns true if this model is null; otherwise returns false.\n *\/\nbool TAbstractModel::isNull() const\n{\n return mdata()->isNull();\n}\n\n\/*!\n Returns true if this model is new, not created; otherwise returns false.\n *\/\nbool TAbstractModel::isNew() const\n{\n return mdata()->isNull();\n}\n\n\/*!\n Returns true if this model is not saved; otherwise returns false.\n *\/\nbool TAbstractModel::isSaved() const\n{\n return !mdata()->isNull();\n}\n\n\/*!\n Creates the model as a new data to the data storage.\n *\/\nbool TAbstractModel::create()\n{\n return mdata()->create();\n}\n\n\/*!\n Saves the model to the data storage.\n\n If the model exists in the data storage, calls update();\n otherwise calls create().\n *\/\nbool TAbstractModel::save()\n{\n return (mdata()->isNull()) ? mdata()->create() : mdata()->update();\n}\n\n\/*!\n Updates the model to the data storage.\n *\/\nbool TAbstractModel::update()\n{\n return mdata()->update();\n}\n\n\/*!\n Removes the model from the data storage.\n *\/\nbool TAbstractModel::remove()\n{\n return mdata()->remove();\n}\n\n\/*!\n Returns a map with all properties of this text format.\n *\/\nQVariantMap TAbstractModel::toVariantMap() const\n{\n QVariantMap ret;\n\n QVariantMap map = mdata()->toVariantMap();\n for (QMapIterator it(map); it.hasNext(); ) {\n it.next();\n ret.insert(fieldNameToVariableName(it.key()), it.value());\n }\n return ret;\n}\n\n\/*!\n Sets the \\a properties.\n *\/\nvoid TAbstractModel::setProperties(const QVariantMap &properties)\n{\n \/\/ Creates a map of the original property name and the converted name\n QStringList soprops = mdata()->propertyNames();\n QMap sopropMap;\n for (QStringListIterator it(soprops); it.hasNext(); ) {\n const QString &orig = it.next();\n sopropMap.insert(fieldNameToVariableName(orig), orig);\n }\n\n QVariantMap props;\n for (QMapIterator it(properties); it.hasNext(); ) {\n it.next();\n const QString &p = sopropMap[it.key()];\n if (!p.isEmpty()) {\n props.insert(p, it.value());\n }\n }\n\n mdata()->setProperties(props);\n}\n\n\n\/*!\n \\fn virtual TModelObject *TAbstractModel::modelData()\n\n This function is reimplemented in subclasses to return a pointer\n to the data stored in the model object.\n*\/\n\n\n\/*!\n \\fn virtual const TModelObject *TAbstractModel::modelData() const\n\n This function is reimplemented in subclasses to return a pointer\n to the data stored in the model object.\n*\/\n\n\nTModelObject *TAbstractModel::mdata()\n{\n return modelData() ? modelData() : data();\n}\n\n\nconst TModelObject *TAbstractModel::mdata() const\n{\n return modelData() ? modelData() : data();\n}\nmodified save() function to call create() instead of mdata()->create().\/* Copyright (c) 2010-2013, AOYAMA Kazuharu\n * All rights reserved.\n *\n * This software may be used and distributed according to the terms of\n * the New BSD License, which is incorporated herein by reference.\n *\/\n\n#include \n#include \n#include \n\n\/*!\n \\class TAbstractModel\n \\brief The TAbstractModel class is the abstract base class of models,\n providing functionality common to models.\n*\/\n\n\/*!\n Returns true if this model is null; otherwise returns false.\n *\/\nbool TAbstractModel::isNull() const\n{\n return mdata()->isNull();\n}\n\n\/*!\n Returns true if this model is new, not created; otherwise returns false.\n *\/\nbool TAbstractModel::isNew() const\n{\n return mdata()->isNull();\n}\n\n\/*!\n Returns true if this model is not saved; otherwise returns false.\n *\/\nbool TAbstractModel::isSaved() const\n{\n return !mdata()->isNull();\n}\n\n\/*!\n Creates the model as a new data to the data storage.\n *\/\nbool TAbstractModel::create()\n{\n return mdata()->create();\n}\n\n\/*!\n Saves the model to the data storage.\n\n If the model exists in the data storage, calls update();\n otherwise calls create().\n *\/\nbool TAbstractModel::save()\n{\n return (mdata()->isNull()) ? create() : update();\n}\n\n\/*!\n Updates the model to the data storage.\n *\/\nbool TAbstractModel::update()\n{\n return mdata()->update();\n}\n\n\/*!\n Removes the model from the data storage.\n *\/\nbool TAbstractModel::remove()\n{\n return mdata()->remove();\n}\n\n\/*!\n Returns a map with all properties of this text format.\n *\/\nQVariantMap TAbstractModel::toVariantMap() const\n{\n QVariantMap ret;\n\n QVariantMap map = mdata()->toVariantMap();\n for (QMapIterator it(map); it.hasNext(); ) {\n it.next();\n ret.insert(fieldNameToVariableName(it.key()), it.value());\n }\n return ret;\n}\n\n\/*!\n Sets the \\a properties.\n *\/\nvoid TAbstractModel::setProperties(const QVariantMap &properties)\n{\n \/\/ Creates a map of the original property name and the converted name\n QStringList soprops = mdata()->propertyNames();\n QMap sopropMap;\n for (QStringListIterator it(soprops); it.hasNext(); ) {\n const QString &orig = it.next();\n sopropMap.insert(fieldNameToVariableName(orig), orig);\n }\n\n QVariantMap props;\n for (QMapIterator it(properties); it.hasNext(); ) {\n it.next();\n const QString &p = sopropMap[it.key()];\n if (!p.isEmpty()) {\n props.insert(p, it.value());\n }\n }\n\n mdata()->setProperties(props);\n}\n\n\n\/*!\n \\fn virtual TModelObject *TAbstractModel::modelData()\n\n This function is reimplemented in subclasses to return a pointer\n to the data stored in the model object.\n*\/\n\n\n\/*!\n \\fn virtual const TModelObject *TAbstractModel::modelData() const\n\n This function is reimplemented in subclasses to return a pointer\n to the data stored in the model object.\n*\/\n\n\nTModelObject *TAbstractModel::mdata()\n{\n return modelData() ? modelData() : data();\n}\n\n\nconst TModelObject *TAbstractModel::mdata() const\n{\n return modelData() ? modelData() : data();\n}\n<|endoftext|>"} {"text":"\/\/ This file is part of Eigen, a lightweight C++ template library\n\/\/ for linear algebra. Eigen itself is part of the KDE project.\n\/\/\n\/\/ Copyright (C) 2006-2008 Benoit Jacob \n\/\/\n\/\/ Eigen is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU Lesser General Public\n\/\/ License as published by the Free Software Foundation; either\n\/\/ version 3 of the License, or (at your option) any later version.\n\/\/\n\/\/ Alternatively, you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU General Public License as\n\/\/ published by the Free Software Foundation; either version 2 of\n\/\/ the License, or (at your option) any later version.\n\/\/\n\/\/ Eigen is distributed in the hope that it will be useful, but WITHOUT ANY\n\/\/ WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n\/\/ FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the\n\/\/ GNU General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License and a copy of the GNU General Public License along with\n\/\/ Eigen. If not, see .\n\n#include \"main.h\"\n\ntemplate void product(const MatrixType& m)\n{\n \/* this test covers the following files:\n Identity.h Product.h\n *\/\n\n typedef typename MatrixType::Scalar Scalar;\n typedef Matrix VectorType;\n typedef Matrix SquareMatrixType;\n\n int rows = m.rows();\n int cols = m.cols();\n\n \/\/ this test relies a lot on Random.h, and there's not much more that we can do\n \/\/ to test it, hence I consider that we will have tested Random.h\n MatrixType m1 = MatrixType::random(rows, cols),\n m2 = MatrixType::random(rows, cols),\n m3(rows, cols),\n mzero = MatrixType::zero(rows, cols);\n SquareMatrixType\n identity = Matrix\n ::identity(rows, rows),\n square = Matrix\n ::random(rows, rows);\n VectorType v1 = VectorType::random(rows),\n v2 = VectorType::random(rows),\n vzero = VectorType::zero(rows);\n\n Scalar s1 = ei_random();\n\n int r = ei_random(0, rows-1),\n c = ei_random(0, cols-1);\n\n \/\/ begin testing Product.h: only associativity for now\n \/\/ (we use Transpose.h but this doesn't count as a test for it)\n VERIFY_IS_APPROX((m1*m1.transpose())*m2, m1*(m1.transpose()*m2));\n m3 = m1;\n m3 *= (m1.transpose() * m2);\n VERIFY_IS_APPROX(m3, m1 * (m1.transpose()*m2));\n VERIFY_IS_APPROX(m3, m1.lazy() * (m1.transpose()*m2));\n\n \/\/ continue testing Product.h: distributivity\n VERIFY_IS_APPROX(square*(m1 + m2), square*m1+square*m2);\n VERIFY_IS_APPROX(square*(m1 - m2), square*m1-square*m2);\n\n \/\/ continue testing Product.h: compatibility with ScalarMultiple.h\n VERIFY_IS_APPROX(s1*(square*m1), (s1*square)*m1);\n VERIFY_IS_APPROX(s1*(square*m1), square*(m1*s1));\n\n \/\/ continue testing Product.h: lazy product\n VERIFY_IS_APPROX(square.lazy() * m1, square*m1);\n VERIFY_IS_APPROX(square * m1.lazy(), square*m1);\n \/\/ again, test operator() to check const-qualification\n s1 += (square.lazy() * m1)(r,c);\n\n \/\/ test Product.h together with Identity.h\n VERIFY_IS_APPROX(m1, identity*m1);\n VERIFY_IS_APPROX(v1, identity*v1);\n \/\/ again, test operator() to check const-qualification\n VERIFY_IS_APPROX(MatrixType::identity(rows, cols)(r,c), static_cast(r==c));\n\n if (rows!=cols)\n VERIFY_RAISES_ASSERT(m3 = m1*m1);\n}\n\nvoid test_product()\n{\n\/\/ for(int i = 0; i < g_repeat; i++) {\n\/\/ CALL_SUBTEST( product(Matrix()) );\n\/\/ CALL_SUBTEST( product(Matrix()) );\n\/\/ CALL_SUBTEST( product(Matrix()) );\n\/\/ CALL_SUBTEST( product(Matrix4d()) );\n\/\/ }\n for(int i = 0; i < g_repeat; i++) {\n int rows = ei_random(1,320);\n int cols = ei_random(1,320);\n std::cout << \"test MatrixXf \" << rows << \"x\" << cols << \"\\n\";\n CALL_SUBTEST( product(MatrixXf(rows, cols)) );\n std::cout << \"test MatrixXd \" << rows << \"x\" << cols << \"\\n\";\n CALL_SUBTEST( product(MatrixXd(rows, cols)) );\n\/\/ CALL_SUBTEST( product(MatrixXi(rows, cols)) );\n\/\/ CALL_SUBTEST( product(MatrixXcf(rows, cols)) );\n\/\/ CALL_SUBTEST( product(MatrixXcd(rows, cols)) );\n }\n}\nrestored the product test\/\/ This file is part of Eigen, a lightweight C++ template library\n\/\/ for linear algebra. Eigen itself is part of the KDE project.\n\/\/\n\/\/ Copyright (C) 2006-2008 Benoit Jacob \n\/\/\n\/\/ Eigen is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU Lesser General Public\n\/\/ License as published by the Free Software Foundation; either\n\/\/ version 3 of the License, or (at your option) any later version.\n\/\/\n\/\/ Alternatively, you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU General Public License as\n\/\/ published by the Free Software Foundation; either version 2 of\n\/\/ the License, or (at your option) any later version.\n\/\/\n\/\/ Eigen is distributed in the hope that it will be useful, but WITHOUT ANY\n\/\/ WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n\/\/ FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the\n\/\/ GNU General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License and a copy of the GNU General Public License along with\n\/\/ Eigen. If not, see .\n\n#include \"main.h\"\n\ntemplate void product(const MatrixType& m)\n{\n \/* this test covers the following files:\n Identity.h Product.h\n *\/\n\n typedef typename MatrixType::Scalar Scalar;\n typedef Matrix VectorType;\n typedef Matrix SquareMatrixType;\n\n int rows = m.rows();\n int cols = m.cols();\n\n \/\/ this test relies a lot on Random.h, and there's not much more that we can do\n \/\/ to test it, hence I consider that we will have tested Random.h\n MatrixType m1 = MatrixType::random(rows, cols),\n m2 = MatrixType::random(rows, cols),\n m3(rows, cols),\n mzero = MatrixType::zero(rows, cols);\n SquareMatrixType\n identity = Matrix\n ::identity(rows, rows),\n square = Matrix\n ::random(rows, rows);\n VectorType v1 = VectorType::random(rows),\n v2 = VectorType::random(rows),\n vzero = VectorType::zero(rows);\n\n Scalar s1 = ei_random();\n\n int r = ei_random(0, rows-1),\n c = ei_random(0, cols-1);\n\n \/\/ begin testing Product.h: only associativity for now\n \/\/ (we use Transpose.h but this doesn't count as a test for it)\n VERIFY_IS_APPROX((m1*m1.transpose())*m2, m1*(m1.transpose()*m2));\n m3 = m1;\n m3 *= (m1.transpose() * m2);\n VERIFY_IS_APPROX(m3, m1 * (m1.transpose()*m2));\n VERIFY_IS_APPROX(m3, m1.lazy() * (m1.transpose()*m2));\n\n \/\/ continue testing Product.h: distributivity\n VERIFY_IS_APPROX(square*(m1 + m2), square*m1+square*m2);\n VERIFY_IS_APPROX(square*(m1 - m2), square*m1-square*m2);\n\n \/\/ continue testing Product.h: compatibility with ScalarMultiple.h\n VERIFY_IS_APPROX(s1*(square*m1), (s1*square)*m1);\n VERIFY_IS_APPROX(s1*(square*m1), square*(m1*s1));\n\n \/\/ continue testing Product.h: lazy product\n VERIFY_IS_APPROX(square.lazy() * m1, square*m1);\n VERIFY_IS_APPROX(square * m1.lazy(), square*m1);\n \/\/ again, test operator() to check const-qualification\n s1 += (square.lazy() * m1)(r,c);\n\n \/\/ test Product.h together with Identity.h\n VERIFY_IS_APPROX(m1, identity*m1);\n VERIFY_IS_APPROX(v1, identity*v1);\n \/\/ again, test operator() to check const-qualification\n VERIFY_IS_APPROX(MatrixType::identity(rows, cols)(r,c), static_cast(r==c));\n\n if (rows!=cols)\n VERIFY_RAISES_ASSERT(m3 = m1*m1);\n}\n\nvoid test_product()\n{\n for(int i = 0; i < g_repeat; i++) {\n CALL_SUBTEST( product(Matrix()) );\n CALL_SUBTEST( product(Matrix()) );\n CALL_SUBTEST( product(Matrix()) );\n CALL_SUBTEST( product(Matrix4d()) );\n }\n for(int i = 0; i < g_repeat; i++) {\n int rows = ei_random(1,320);\n int cols = ei_random(1,320);\n CALL_SUBTEST( product(MatrixXf(rows, cols)) );\n CALL_SUBTEST( product(MatrixXd(rows, cols)) );\n CALL_SUBTEST( product(MatrixXi(rows, cols)) );\n CALL_SUBTEST( product(MatrixXcf(rows, cols)) );\n CALL_SUBTEST( product(MatrixXcd(rows, cols)) );\n }\n}\n<|endoftext|>"} {"text":"#include \n#include \n\n#include \n\n#include \n#include \"merkle.h\"\n#include \"merkle_tree_disk.h\"\n#include \n#include \n\ntypedef bhash keys_t;\n\nstatic char *indexpath = \"\/tmp\/index.mrk\";\nstatic char *internalpath = \"\/tmp\/internal.mrk\";\nstatic char *leafpath = \"\/tmp\/leaf.mrk\";\nstatic char *indexpathro = \"\/tmp\/index.mrk.ro\";\nstatic char *internalpathro = \"\/tmp\/internal.mrk.ro\";\nstatic char *leafpathro = \"\/tmp\/leaf.mrk.ro\";\n\nvoid\ncleanup ()\n{\n unlink (indexpath);\n unlink (internalpath);\n unlink (leafpath);\n unlink (indexpathro);\n unlink (internalpathro);\n unlink (leafpathro);\n}\n\nbool\nreap (int pid, bool wait = true)\n{\n int wpid, status, options = 0;\n\n if (!wait)\n options = WNOHANG;\n wpid = waitpid (pid, &status, options);\n if (wpid < 0) {\n perror(\"waitpid\");\n exit (1);\n }\n if (!wait && (wpid == 0))\n return false;\n if (wpid != pid)\n fatal (\"unexpected pid reaped: %d\\n\", wpid);\n if (!WIFEXITED(status) || WEXITSTATUS(status) != 0)\n fatal << \"child exited unhappily\\n\";\n return true;\n}\n\nvoid\ninsert_blocks (merkle_tree *mtree, int upto, bool random,\n keys_t *keys = NULL)\n{\n for (int i = 1; i <= upto; i++) {\n merkle_hash key;\n if (random) \n key.randomize ();\n else\n key = i;\n\n if (keys)\n keys->insert (static_cast (key));\n mtree->insert (key);\n }\n}\n\nvoid\ntest_numkeys (merkle_tree *tree, unsigned int cnt)\n{\n merkle_node *root = tree->get_root ();\n assert (root->count == cnt);\n tree->lookup_release (root);\n}\n\nvoid\ntest_insertions (str msg,\n merkle_tree *mtree, uint nkeys, bool rand, keys_t &keys)\n{\n uint okeyssz = keys.size ();\n warn << msg << \" bulk insertion... \";\n u_int64_t start = getusec ();\n mtree->set_rehash_on_modification (false);\n insert_blocks (mtree, nkeys, rand, &keys);\n warn << \"completed in: \" << (getusec ()-start)\/1000 << \"ms... \";\n assert ((keys.size () - okeyssz) == nkeys);\n warn << \"OK\\n\";\n\n warn << msg << \" hash full tree... \";\n start = getusec ();\n mtree->hash_tree ();\n warn << \"completed in: \" << (getusec ()-start)\/1000 << \"ms... \";\n test_numkeys (mtree, keys.size ());\n warn << \"OK\\n\";\n\n warn << msg << \" check invariants... \";\n mtree->check_invariants ();\n warn << \"OK.\\n\";\n\n mtree->set_rehash_on_modification (true);\n}\n\nconst vec &\ntest_reads (merkle_tree *mtree, const keys_t &keys)\n{\n static vec intree;\n intree.clear ();\n unsigned int nkeys = keys.size ();\n\n warn << \"All key read (get_keyrange)... \";\n intree = mtree->get_keyrange (\n 0, (chordID (1) << 160) - 1, nkeys + 1);\n assert (intree.size () == nkeys);\n for (uint i = 0; i < intree.size (); i++) {\n assert (keys[intree[i]]);\n }\n warn << \"OK\\n\";\n\n warn << \"Randomized key lookups... \";\n uint limit = 128 + int(nkeys * 0.2);\n if (limit > nkeys)\n limit = nkeys;\n uint order[nkeys];\n for (uint i=0; ikey_exists (intree[key]));\n merkle_node *n = mtree->lookup (intree[key]);\n assert (n);\n assert (n->isleaf ());\n }\n warn << \"OK\\n\";\n\n warn << \"Missing key lookups... \";\n int todo = limit;\n while (todo) {\n chordID c = make_randomID ();\n if (keys[c])\n continue;\n todo--;\n assert (!mtree->key_exists (c));\n merkle_node *n = mtree->lookup (c);\n assert (n);\n }\n warn << \"OK\\n\";\n\n warn << \"Random range reads... \";\n chordID highest = (((chordID) 1) << 160) - 1;\n for (int i = 0; i < 32; i++) {\n chordID min = make_randomID ();\n chordID max = min + make_randomID () % (highest - min);\n \/\/warn << \" get_keyrange (\" << min << \", \" << max << \", \" << nkeys << \")\\n\";\n vec rangekeys = mtree->get_keyrange (min, max, nkeys);\n\n keys_t subset;\n for (uint j = 0; j < nkeys; j++)\n if (betweenbothincl (min, max, intree[j]))\n\tsubset.insert (intree[j]);\n assert (subset.size () == rangekeys.size ());\n for (uint j = 0; j < rangekeys.size (); j++)\n assert (subset[rangekeys[j]]);\n }\n warn << \"OK\\n\";\n return intree;\n}\n\nvoid\ntest (str msg, merkle_tree *mtree, uint nkeys, bool rand = true)\n{\n warn << \"\\n=================== \" << msg \n << \" test_\" << (rand ? \"rand\" : \"incr\")\n << \" nkeys \" << nkeys << \"\\n\";\n\n keys_t keys;\n keys.clear ();\n\n test_insertions (\"Initial\", mtree, nkeys, rand, keys);\n const vec intree = test_reads (mtree, keys);\n\n warn << \"Removes... \";\n uint limit = (nkeys < 128) ? nkeys : (128 + int (nkeys * 0.2));\n uint order[nkeys];\n for (uint i=0; iremove (intree[key]);\n keys.remove (intree[key]);\n test_numkeys (mtree, nkeys - (i + 1));\n assert (keys.size () == (nkeys - (i + 1)));\n }\n warn << \"OK\\n\";\n\n warn << \"Post-remove tree contents check... \";\n for (uint i = 0; i < nkeys; i++) {\n if (i < limit)\n assert (!mtree->key_exists (intree[order[i]]));\n else\n assert (mtree->key_exists (intree[order[i]]));\n }\n mtree->check_invariants ();\n warn << \"OK\\n\";\n\n if (rand)\n test_insertions (\"Post-remove\", mtree, 2*limit, rand, keys);\n test_reads (mtree, keys);\n}\n\nvoid\ntest_merkle_disk_specific ()\n{\n warn << \"\\n=================== Merkle Disk Specific Tests\\n\";\n merkle_tree *mtree = \n New merkle_tree_disk (indexpath, internalpath, leafpath, true);\n\n keys_t keys;\n keys.clear ();\n\n test_insertions (\"Initial\", mtree, 256, true, keys);\n delete mtree;\n\n warn << \"Static child read... \\n\";\n int pid = fork ();\n if (pid < 0)\n fatal (\"fork: %m\\n\");\n if (pid == 0) {\n \/\/ Child\n mtree = \n New merkle_tree_disk (indexpath, internalpath, leafpath, false);\n\n const vec intree = test_reads (mtree, keys);\n exit (0);\n }\n reap (pid);\n warn << \"Static child read OK\\n\";\n\n warn << \"Dynamic child reads... \\n\";\n vec tobeinserted;\n for (int i = 0; i < 3200; i++)\n tobeinserted.push_back (make_randomID ());\n pid = fork ();\n if (pid > 0) {\n \/\/ Parent\n bool reaped = false;\n mtree = \n New merkle_tree_disk (indexpath, internalpath, leafpath, true);\n for (int i = 0; i < 32; i++) {\n warn << \" Parent insertion burst \" << i+1 << \"\\n\";\n for (int j = 0; j < 100; j++) {\n\tmtree->insert (tobeinserted[100*i + j]);\n\tkeys.insert (tobeinserted[100*i + j]);\n }\n if (!reaped)\n\treaped = reap (pid, false);\n mtree->sync ();\n sleep (1);\n }\n if (!reaped)\n reap (pid);\n } else {\n chordID highest = (((chordID) 1) << 160) - 1;\n mtree = \n New merkle_tree_disk (indexpath, internalpath, leafpath, false);\n for (int i = 0; i < 32; i++) {\n warn << \" Child read-range \" << i+1 << \"\\n\";\n chordID min = make_randomID ();\n chordID max = min + make_randomID () % (highest - min);\n vec rangekeys = mtree->get_keyrange (min, max, 10000);\n for (uint j = 0; j < rangekeys.size (); j++)\n\tassert (betweenbothincl (min, max, rangekeys[j]));\n mtree->check_invariants ();\n mtree->sync ();\n sleep (1);\n }\n exit (0);\n } \n warn << \"Dynamic child reads seem OK\\n\";\n}\n\nint\nmain (int argc, char *argv[])\n{\n \/\/ Make sure no confusion from previous crashes.\n cleanup ();\n\n \/\/ Any arguments mean we skip the \"normal\" tests.\n if (argc == 1) {\n int sz[] = { 1, 64, 256, 64*64+1, 10000 };\n for (uint i = 0; i < sizeof (sz) \/ sizeof (sz[0]); i++) {\n merkle_tree *t = New merkle_tree_mem ();\n test (\"In-memory\", t, sz[i], false);\n delete t; t = NULL;\n\n t = New merkle_tree_mem ();\n test (\"In-memory\", t, sz[i], true);\n delete t; t = NULL;\n }\n\n for (uint i = 0; i < sizeof (sz) \/ sizeof (sz[0]); i++) {\n merkle_tree *t = \n\tNew merkle_tree_disk (indexpath, internalpath, leafpath, true);\n test (\"Disk\", t, sz[i]);\n delete t; t = NULL;\n cleanup ();\n }\n }\n\n test_merkle_disk_specific ();\n cleanup ();\n}\nFix output regressions from getusec changes.#include \n#include \n\n#include \n\n#include \n#include \"merkle.h\"\n#include \"merkle_tree_disk.h\"\n#include \n#include \n\ntypedef bhash keys_t;\n\nstatic char *indexpath = \"\/tmp\/index.mrk\";\nstatic char *internalpath = \"\/tmp\/internal.mrk\";\nstatic char *leafpath = \"\/tmp\/leaf.mrk\";\nstatic char *indexpathro = \"\/tmp\/index.mrk.ro\";\nstatic char *internalpathro = \"\/tmp\/internal.mrk.ro\";\nstatic char *leafpathro = \"\/tmp\/leaf.mrk.ro\";\n\nvoid\ncleanup ()\n{\n unlink (indexpath);\n unlink (internalpath);\n unlink (leafpath);\n unlink (indexpathro);\n unlink (internalpathro);\n unlink (leafpathro);\n}\n\nbool\nreap (int pid, bool wait = true)\n{\n int wpid, status, options = 0;\n\n if (!wait)\n options = WNOHANG;\n wpid = waitpid (pid, &status, options);\n if (wpid < 0) {\n perror(\"waitpid\");\n exit (1);\n }\n if (!wait && (wpid == 0))\n return false;\n if (wpid != pid)\n fatal (\"unexpected pid reaped: %d\\n\", wpid);\n if (!WIFEXITED(status) || WEXITSTATUS(status) != 0)\n fatal << \"child exited unhappily\\n\";\n return true;\n}\n\nvoid\ninsert_blocks (merkle_tree *mtree, int upto, bool random,\n keys_t *keys = NULL)\n{\n for (int i = 1; i <= upto; i++) {\n merkle_hash key;\n if (random) \n key.randomize ();\n else\n key = i;\n\n if (keys)\n keys->insert (static_cast (key));\n mtree->insert (key);\n }\n}\n\nvoid\ntest_numkeys (merkle_tree *tree, unsigned int cnt)\n{\n merkle_node *root = tree->get_root ();\n assert (root->count == cnt);\n tree->lookup_release (root);\n}\n\nvoid\ntest_insertions (str msg,\n merkle_tree *mtree, uint nkeys, bool rand, keys_t &keys)\n{\n uint okeyssz = keys.size ();\n warn << msg << \" bulk insertion... \";\n u_int64_t start = getusec (true);\n mtree->set_rehash_on_modification (false);\n insert_blocks (mtree, nkeys, rand, &keys);\n warn << \"completed in: \" << (getusec (true)-start)\/1000 << \"ms... \";\n assert ((keys.size () - okeyssz) == nkeys);\n warn << \"OK\\n\";\n\n warn << msg << \" hash full tree... \";\n start = getusec (true);\n mtree->hash_tree ();\n warn << \"completed in: \" << (getusec (true)-start)\/1000 << \"ms... \";\n test_numkeys (mtree, keys.size ());\n warn << \"OK\\n\";\n\n warn << msg << \" check invariants... \";\n mtree->check_invariants ();\n warn << \"OK.\\n\";\n\n mtree->set_rehash_on_modification (true);\n}\n\nconst vec &\ntest_reads (merkle_tree *mtree, const keys_t &keys)\n{\n static vec intree;\n intree.clear ();\n unsigned int nkeys = keys.size ();\n\n warn << \"All key read (get_keyrange)... \";\n intree = mtree->get_keyrange (\n 0, (chordID (1) << 160) - 1, nkeys + 1);\n assert (intree.size () == nkeys);\n for (uint i = 0; i < intree.size (); i++) {\n assert (keys[intree[i]]);\n }\n warn << \"OK\\n\";\n\n warn << \"Randomized key lookups... \";\n uint limit = 128 + int(nkeys * 0.2);\n if (limit > nkeys)\n limit = nkeys;\n uint order[nkeys];\n for (uint i=0; ikey_exists (intree[key]));\n merkle_node *n = mtree->lookup (intree[key]);\n assert (n);\n assert (n->isleaf ());\n }\n warn << \"OK\\n\";\n\n warn << \"Missing key lookups... \";\n int todo = limit;\n while (todo) {\n chordID c = make_randomID ();\n if (keys[c])\n continue;\n todo--;\n assert (!mtree->key_exists (c));\n merkle_node *n = mtree->lookup (c);\n assert (n);\n }\n warn << \"OK\\n\";\n\n warn << \"Random range reads... \";\n chordID highest = (((chordID) 1) << 160) - 1;\n for (int i = 0; i < 32; i++) {\n chordID min = make_randomID ();\n chordID max = min + make_randomID () % (highest - min);\n \/\/warn << \" get_keyrange (\" << min << \", \" << max << \", \" << nkeys << \")\\n\";\n vec rangekeys = mtree->get_keyrange (min, max, nkeys);\n\n keys_t subset;\n for (uint j = 0; j < nkeys; j++)\n if (betweenbothincl (min, max, intree[j]))\n\tsubset.insert (intree[j]);\n assert (subset.size () == rangekeys.size ());\n for (uint j = 0; j < rangekeys.size (); j++)\n assert (subset[rangekeys[j]]);\n }\n warn << \"OK\\n\";\n return intree;\n}\n\nvoid\ntest (str msg, merkle_tree *mtree, uint nkeys, bool rand = true)\n{\n warn << \"\\n=================== \" << msg \n << \" test_\" << (rand ? \"rand\" : \"incr\")\n << \" nkeys \" << nkeys << \"\\n\";\n\n keys_t keys;\n keys.clear ();\n\n test_insertions (\"Initial\", mtree, nkeys, rand, keys);\n const vec intree = test_reads (mtree, keys);\n\n warn << \"Removes... \";\n uint limit = (nkeys < 128) ? nkeys : (128 + int (nkeys * 0.2));\n uint order[nkeys];\n for (uint i=0; iremove (intree[key]);\n keys.remove (intree[key]);\n test_numkeys (mtree, nkeys - (i + 1));\n assert (keys.size () == (nkeys - (i + 1)));\n }\n warn << \"OK\\n\";\n\n warn << \"Post-remove tree contents check... \";\n for (uint i = 0; i < nkeys; i++) {\n if (i < limit)\n assert (!mtree->key_exists (intree[order[i]]));\n else\n assert (mtree->key_exists (intree[order[i]]));\n }\n mtree->check_invariants ();\n warn << \"OK\\n\";\n\n if (rand)\n test_insertions (\"Post-remove\", mtree, 2*limit, rand, keys);\n test_reads (mtree, keys);\n}\n\nvoid\ntest_merkle_disk_specific ()\n{\n warn << \"\\n=================== Merkle Disk Specific Tests\\n\";\n merkle_tree *mtree = \n New merkle_tree_disk (indexpath, internalpath, leafpath, true);\n\n keys_t keys;\n keys.clear ();\n\n test_insertions (\"Initial\", mtree, 256, true, keys);\n delete mtree;\n\n warn << \"Static child read... \\n\";\n int pid = fork ();\n if (pid < 0)\n fatal (\"fork: %m\\n\");\n if (pid == 0) {\n \/\/ Child\n mtree = \n New merkle_tree_disk (indexpath, internalpath, leafpath, false);\n\n const vec intree = test_reads (mtree, keys);\n exit (0);\n }\n reap (pid);\n warn << \"Static child read OK\\n\";\n\n warn << \"Dynamic child reads... \\n\";\n vec tobeinserted;\n for (int i = 0; i < 3200; i++)\n tobeinserted.push_back (make_randomID ());\n pid = fork ();\n if (pid > 0) {\n \/\/ Parent\n bool reaped = false;\n mtree = \n New merkle_tree_disk (indexpath, internalpath, leafpath, true);\n for (int i = 0; i < 32; i++) {\n warn << \" Parent insertion burst \" << i+1 << \"\\n\";\n for (int j = 0; j < 100; j++) {\n\tmtree->insert (tobeinserted[100*i + j]);\n\tkeys.insert (tobeinserted[100*i + j]);\n }\n if (!reaped)\n\treaped = reap (pid, false);\n mtree->sync ();\n sleep (1);\n }\n if (!reaped)\n reap (pid);\n } else {\n chordID highest = (((chordID) 1) << 160) - 1;\n mtree = \n New merkle_tree_disk (indexpath, internalpath, leafpath, false);\n for (int i = 0; i < 32; i++) {\n warn << \" Child read-range \" << i+1 << \"\\n\";\n chordID min = make_randomID ();\n chordID max = min + make_randomID () % (highest - min);\n vec rangekeys = mtree->get_keyrange (min, max, 10000);\n for (uint j = 0; j < rangekeys.size (); j++)\n\tassert (betweenbothincl (min, max, rangekeys[j]));\n mtree->check_invariants ();\n mtree->sync ();\n sleep (1);\n }\n exit (0);\n } \n warn << \"Dynamic child reads seem OK\\n\";\n}\n\nint\nmain (int argc, char *argv[])\n{\n \/\/ Make sure no confusion from previous crashes.\n cleanup ();\n\n \/\/ Any arguments mean we skip the \"normal\" tests.\n if (argc == 1) {\n int sz[] = { 1, 64, 256, 64*64+1, 10000 };\n for (uint i = 0; i < sizeof (sz) \/ sizeof (sz[0]); i++) {\n merkle_tree *t = New merkle_tree_mem ();\n test (\"In-memory\", t, sz[i], false);\n delete t; t = NULL;\n\n t = New merkle_tree_mem ();\n test (\"In-memory\", t, sz[i], true);\n delete t; t = NULL;\n }\n\n for (uint i = 0; i < sizeof (sz) \/ sizeof (sz[0]); i++) {\n merkle_tree *t = \n\tNew merkle_tree_disk (indexpath, internalpath, leafpath, true);\n test (\"Disk\", t, sz[i]);\n delete t; t = NULL;\n cleanup ();\n }\n }\n\n test_merkle_disk_specific ();\n cleanup ();\n}\n<|endoftext|>"} {"text":"\/* IBM_PROLOG_BEGIN_TAG *\/\n\/* This is an automatically generated prolog. *\/\n\/* *\/\n\/* $Source: src\/import\/chips\/p9\/procedures\/hwp\/core\/p9_hcd_core_stopclocks.C $ *\/\n\/* *\/\n\/* OpenPOWER HostBoot Project *\/\n\/* *\/\n\/* Contributors Listed Below - COPYRIGHT 2015,2019 *\/\n\/* [+] International Business Machines Corp. *\/\n\/* *\/\n\/* *\/\n\/* Licensed under the Apache License, Version 2.0 (the \"License\"); *\/\n\/* you may not use this file except in compliance with the License. *\/\n\/* You may obtain a copy of the License at *\/\n\/* *\/\n\/* http:\/\/www.apache.org\/licenses\/LICENSE-2.0 *\/\n\/* *\/\n\/* Unless required by applicable law or agreed to in writing, software *\/\n\/* distributed under the License is distributed on an \"AS IS\" BASIS, *\/\n\/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or *\/\n\/* implied. See the License for the specific language governing *\/\n\/* permissions and limitations under the License. *\/\n\/* *\/\n\/* IBM_PROLOG_END_TAG *\/\n\/\/\/\n\/\/\/ @file p9_hcd_core_stopclocks.C\n\/\/\/ @brief Core Clock Stop\n\/\/\/\n\/\/\/ Procedure Summary:\n\n\/\/ *HWP HWP Owner : David Du \n\/\/ *HWP Backup HWP Owner : Greg Still \n\/\/ *HWP FW Owner : Sangeetha T S \n\/\/ *HWP Team : PM\n\/\/ *HWP Consumed by : HB:PREV\n\/\/ *HWP Level : 2\n\n\/\/------------------------------------------------------------------------------\n\/\/ Includes\n\/\/------------------------------------------------------------------------------\n\n#include \n#include \n#include \n#include \n#include \"p9_hcd_core_stopclocks.H\"\n\n\/\/------------------------------------------------------------------------------\n\/\/ Constant Definitions\n\/\/------------------------------------------------------------------------------\n\nenum P9_HCD_CORE_STOPCLOCKS_CONSTANTS\n{\n CORE_PCB_MUX_POLLING_HW_NS_DELAY = 10000,\n CORE_PCB_MUX_POLLING_SIM_CYCLE_DELAY = 320000,\n CORE_CLK_SYNC_POLLING_HW_NS_DELAY = 10000,\n CORE_CLK_SYNC_POLLING_SIM_CYCLE_DELAY = 320000,\n CORE_CLK_STOP_POLLING_HW_NS_DELAY = 10000,\n CORE_CLK_STOP_POLLING_SIM_CYCLE_DELAY = 320000\n};\n\n\/\/------------------------------------------------------------------------------\n\/\/ Procedure: Core Clock Stop\n\/\/------------------------------------------------------------------------------\n\nfapi2::ReturnCode\np9_hcd_core_stopclocks(\n const fapi2::Target& i_target)\n{\n FAPI_INF(\">>p9_hcd_core_stopclocks\");\n fapi2::ReturnCode l_rc;\n fapi2::buffer l_ccsr;\n fapi2::buffer l_data64;\n fapi2::buffer l_temp64;\n uint32_t l_loops1ms;\n uint8_t l_attr_chip_unit_pos;\n uint8_t l_attr_vdm_enable;\n uint8_t l_attr_sdisn_setup;\n const fapi2::Target l_sys;\n auto l_quad = i_target.getParent();\n auto l_perv = i_target.getParent();\n auto l_chip = i_target.getParent();\n\n FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_CHIP_EC_FEATURE_SDISN_SETUP, l_chip,\n l_attr_sdisn_setup));\n\n FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_VDM_ENABLE, l_sys,\n l_attr_vdm_enable));\n FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_CHIP_UNIT_POS, l_perv,\n l_attr_chip_unit_pos));\n l_attr_chip_unit_pos = (l_attr_chip_unit_pos -\n p9hcd::PERV_TO_CORE_POS_OFFSET) % 4;\n\n \/\/ ----------------------------\n \/\/ Prepare to stop core clocks\n \/\/ ----------------------------\n\n FAPI_DBG(\"Check PM_RESET_STATE_INDICATOR via GPMMR[15]\");\n FAPI_TRY(getScom(i_target, C_PPM_GPMMR_SCOM, l_data64));\n\n if (!l_data64.getBit<15>())\n {\n FAPI_DBG(\"Gracefully turn off power management, continue anyways if fail\");\n \/\/\/ @todo RTC158181 suspend_pm()\n }\n\n FAPI_DBG(\"Check core clock controller status\");\n l_rc = p9_common_clk_ctrl_state(i_target);\n\n if (l_rc)\n {\n FAPI_INF(\"Clock controller of this core chiplet is inaccessible, return\");\n goto fapi_try_exit;\n }\n\n FAPI_DBG(\"Check cache clock controller status\");\n l_rc = p9_common_clk_ctrl_state(l_quad);\n\n if (l_rc)\n {\n FAPI_INF(\"WARNING: core is enabled while cache is not, continue anyways\");\n }\n else\n {\n\n FAPI_DBG(\"Check PERV clock status for access to CME via CLOCK_STAT[4]\");\n FAPI_TRY(getScom(l_quad, EQ_CLOCK_STAT_SL, l_data64));\n\n FAPI_DBG(\"Check PERV fence status for access to CME via CPLT_CTRL1[4]\");\n FAPI_TRY(getScom(l_quad, EQ_CPLT_CTRL1, l_temp64));\n\n if (l_data64.getBit<4>() == 0 && l_temp64.getBit<4>() == 0)\n {\n \/\/halt cme(poll for halted, if timeout, print warnning keep going).\n\n FAPI_DBG(\"Assert Core-L2\/CC Quiesces via CME_SCOM_SICR[6,8]\/[7,9]\");\n FAPI_TRY(putScom(l_quad,\n (l_attr_chip_unit_pos < 2) ?\n EX_0_CME_SCOM_SICR_OR : EX_1_CME_SCOM_SICR_OR,\n (BIT64(6 + (l_attr_chip_unit_pos % 2)) |\n BIT64(8 + (l_attr_chip_unit_pos % 2)))));\n }\n }\n\n FAPI_DBG(\"Assert pm_mux_disable to get PCB Mux from CME via SLAVE_CONFIG[7]\");\n FAPI_TRY(getScom(i_target, C_SLAVE_CONFIG_REG, l_data64));\n FAPI_TRY(putScom(i_target, C_SLAVE_CONFIG_REG, DATA_SET(7)));\n\n FAPI_DBG(\"Override possible PPM write protection to CME via CPPM_CPMMR[1]\");\n FAPI_TRY(putScom(i_target, C_CPPM_CPMMR_OR, MASK_SET(1)));\n\n FAPI_DBG(\"Assert chiplet fence via NET_CTRL0[18]\");\n FAPI_TRY(putScom(i_target, C_NET_CTRL0_WOR, MASK_SET(18)));\n\n \/\/ -------------------------------\n \/\/ Stop core clocks\n \/\/ -------------------------------\n\n FAPI_DBG(\"Clear all SCAN_REGION_TYPE bits\");\n FAPI_TRY(putScom(i_target, C_SCAN_REGION_TYPE, MASK_ZERO));\n\n FAPI_DBG(\"Stop core clocks(all but pll) via CLK_REGION\");\n l_data64 = (p9hcd::CLK_STOP_CMD |\n p9hcd::CLK_REGION_ALL_BUT_PLL |\n p9hcd::CLK_THOLD_ALL);\n FAPI_TRY(putScom(i_target, C_CLK_REGION, l_data64));\n\n FAPI_DBG(\"Poll for core clocks stopped via CPLT_STAT0[8]\");\n l_loops1ms = 1E6 \/ CORE_CLK_STOP_POLLING_HW_NS_DELAY;\n\n do\n {\n fapi2::delay(CORE_CLK_STOP_POLLING_HW_NS_DELAY,\n CORE_CLK_STOP_POLLING_SIM_CYCLE_DELAY);\n\n FAPI_TRY(getScom(i_target, C_CPLT_STAT0, l_data64));\n }\n while((l_data64.getBit<8>() != 1) && ((--l_loops1ms) != 0));\n\n FAPI_ASSERT((l_loops1ms != 0),\n fapi2::PMPROC_CORECLKSTOP_TIMEOUT().set_CORECPLTSTAT(l_data64),\n \"Core Clock Stop Timeout\");\n\n FAPI_DBG(\"Check core clocks stopped via CLOCK_STAT_SL[4-13]\");\n FAPI_TRY(getScom(i_target, C_CLOCK_STAT_SL, l_data64));\n\n FAPI_ASSERT((((~l_data64) & p9hcd::CLK_REGION_ALL_BUT_PLL) == 0),\n fapi2::PMPROC_CORECLKSTOP_FAILED().set_CORECLKSTAT(l_data64),\n \"Core Clock Stop Failed\");\n FAPI_DBG(\"Core clocks stopped now\");\n\n \/\/ -------------------------------\n \/\/ Disable core clock sync\n \/\/ -------------------------------\n\n FAPI_DBG(\"Drop core clock sync enable via CPPM_CACCR[15]\");\n FAPI_TRY(putScom(i_target, C_CPPM_CACCR_CLEAR, MASK_SET(15)));\n\n FAPI_DBG(\"Poll for core clock sync done to drop via CPPM_CACSR[13]\");\n l_loops1ms = 1E6 \/ CORE_CLK_SYNC_POLLING_HW_NS_DELAY;\n\n do\n {\n fapi2::delay(CORE_CLK_SYNC_POLLING_HW_NS_DELAY,\n CORE_CLK_SYNC_POLLING_SIM_CYCLE_DELAY);\n\n FAPI_TRY(getScom(i_target, C_CPPM_CACSR, l_data64));\n }\n while((l_data64.getBit<13>() == 1) && ((--l_loops1ms) != 0));\n\n FAPI_ASSERT((l_loops1ms != 0),\n fapi2::PMPROC_CORECLKSYNCDROP_TIMEOUT().set_COREPPMCACSR(l_data64),\n \"Core Clock Sync Drop Timeout\");\n FAPI_DBG(\"Core clock sync done dropped\");\n\n \/\/ -------------------------------\n \/\/ Fence up\n \/\/ -------------------------------\n\n FAPI_DBG(\"Assert skew sense to skew adjust fence via NET_CTRL0[22]\");\n FAPI_TRY(putScom(i_target, C_NET_CTRL0_WOR, MASK_SET(22)));\n\n FAPI_DBG(\"Drop ABIST_SRAM_MODE_DC to support ABIST Recovery via BIST[1]\");\n FAPI_TRY(getScom(i_target, C_BIST, l_data64));\n FAPI_TRY(putScom(i_target, C_BIST, DATA_UNSET(1)));\n\n FAPI_DBG(\"Assert vital fence via CPLT_CTRL1[3]\");\n FAPI_TRY(putScom(i_target, C_CPLT_CTRL1_OR, MASK_SET(3)));\n\n FAPI_DBG(\"Assert regional fences via CPLT_CTRL1[4-14]\");\n FAPI_TRY(putScom(i_target, C_CPLT_CTRL1_OR, p9hcd::CLK_REGION_ALL));\n\n if (l_attr_sdisn_setup)\n {\n FAPI_DBG(\"DD1 Only: Drop sdis_n(flushing LCBES condition) vai CPLT_CONF0[34]\");\n FAPI_TRY(putScom(i_target, C_CPLT_CONF0_CLEAR, MASK_SET(34)));\n }\n\n \/\/ -------------------------------\n \/\/ Disable VDM\n \/\/ -------------------------------\n\n if (l_attr_vdm_enable == fapi2::ENUM_ATTR_VDM_ENABLE_ON)\n {\n FAPI_DBG(\"Drop vdm enable via CPPM_VDMCR[0]\");\n FAPI_TRY(putScom(i_target, C_PPM_VDMCR_CLEAR, MASK_SET(0)));\n }\n\n \/\/ -------------------------------\n \/\/ Update stop history\n \/\/ -------------------------------\n\n FAPI_DBG(\"Set core as stopped in STOP history register\");\n FAPI_TRY(putScom(i_target, C_PPM_SSHSRC, BIT64(0)));\n\n \/\/ -------------------------------\n \/\/ Clean up\n \/\/ -------------------------------\n\n FAPI_DBG(\"Return possible PPM write protection to CME via CPPM_CPMMR[1]\");\n FAPI_TRY(putScom(i_target, C_CPPM_CPMMR_CLEAR, MASK_SET(1)));\n\n FAPI_DBG(\"Drop pm_mux_disable to release PCB Mux via SLAVE_CONFIG[7]\");\n FAPI_TRY(getScom(i_target, C_SLAVE_CONFIG_REG, l_data64));\n FAPI_TRY(putScom(i_target, C_SLAVE_CONFIG_REG, DATA_UNSET(7)));\n\nfapi_try_exit:\n\n FAPI_INF(\"<Pstate: Remove legacy VDM code\/* IBM_PROLOG_BEGIN_TAG *\/\n\/* This is an automatically generated prolog. *\/\n\/* *\/\n\/* $Source: src\/import\/chips\/p9\/procedures\/hwp\/core\/p9_hcd_core_stopclocks.C $ *\/\n\/* *\/\n\/* OpenPOWER HostBoot Project *\/\n\/* *\/\n\/* Contributors Listed Below - COPYRIGHT 2015,2019 *\/\n\/* [+] International Business Machines Corp. *\/\n\/* *\/\n\/* *\/\n\/* Licensed under the Apache License, Version 2.0 (the \"License\"); *\/\n\/* you may not use this file except in compliance with the License. *\/\n\/* You may obtain a copy of the License at *\/\n\/* *\/\n\/* http:\/\/www.apache.org\/licenses\/LICENSE-2.0 *\/\n\/* *\/\n\/* Unless required by applicable law or agreed to in writing, software *\/\n\/* distributed under the License is distributed on an \"AS IS\" BASIS, *\/\n\/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or *\/\n\/* implied. See the License for the specific language governing *\/\n\/* permissions and limitations under the License. *\/\n\/* *\/\n\/* IBM_PROLOG_END_TAG *\/\n\/\/\/\n\/\/\/ @file p9_hcd_core_stopclocks.C\n\/\/\/ @brief Core Clock Stop\n\/\/\/\n\/\/\/ Procedure Summary:\n\n\/\/ *HWP HWP Owner : David Du \n\/\/ *HWP Backup HWP Owner : Greg Still \n\/\/ *HWP FW Owner : Sangeetha T S \n\/\/ *HWP Team : PM\n\/\/ *HWP Consumed by : HB:PREV\n\/\/ *HWP Level : 2\n\n\/\/------------------------------------------------------------------------------\n\/\/ Includes\n\/\/------------------------------------------------------------------------------\n\n#include \n#include \n#include \n#include \n#include \"p9_hcd_core_stopclocks.H\"\n\n\/\/------------------------------------------------------------------------------\n\/\/ Constant Definitions\n\/\/------------------------------------------------------------------------------\n\nenum P9_HCD_CORE_STOPCLOCKS_CONSTANTS\n{\n CORE_PCB_MUX_POLLING_HW_NS_DELAY = 10000,\n CORE_PCB_MUX_POLLING_SIM_CYCLE_DELAY = 320000,\n CORE_CLK_SYNC_POLLING_HW_NS_DELAY = 10000,\n CORE_CLK_SYNC_POLLING_SIM_CYCLE_DELAY = 320000,\n CORE_CLK_STOP_POLLING_HW_NS_DELAY = 10000,\n CORE_CLK_STOP_POLLING_SIM_CYCLE_DELAY = 320000\n};\n\n\/\/------------------------------------------------------------------------------\n\/\/ Procedure: Core Clock Stop\n\/\/------------------------------------------------------------------------------\n\nfapi2::ReturnCode\np9_hcd_core_stopclocks(\n const fapi2::Target& i_target)\n{\n FAPI_INF(\">>p9_hcd_core_stopclocks\");\n fapi2::ReturnCode l_rc;\n fapi2::buffer l_ccsr;\n fapi2::buffer l_data64;\n fapi2::buffer l_temp64;\n uint32_t l_loops1ms;\n uint8_t l_attr_chip_unit_pos;\n uint8_t l_attr_vdm_enable;\n uint8_t l_attr_sdisn_setup;\n const fapi2::Target l_sys;\n auto l_quad = i_target.getParent();\n auto l_perv = i_target.getParent();\n auto l_chip = i_target.getParent();\n\n FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_CHIP_EC_FEATURE_SDISN_SETUP, l_chip,\n l_attr_sdisn_setup));\n\n FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_VDM_ENABLE, l_sys,\n l_attr_vdm_enable));\n FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_CHIP_UNIT_POS, l_perv,\n l_attr_chip_unit_pos));\n l_attr_chip_unit_pos = (l_attr_chip_unit_pos -\n p9hcd::PERV_TO_CORE_POS_OFFSET) % 4;\n\n \/\/ ----------------------------\n \/\/ Prepare to stop core clocks\n \/\/ ----------------------------\n\n FAPI_DBG(\"Check PM_RESET_STATE_INDICATOR via GPMMR[15]\");\n FAPI_TRY(getScom(i_target, C_PPM_GPMMR_SCOM, l_data64));\n\n if (!l_data64.getBit<15>())\n {\n FAPI_DBG(\"Gracefully turn off power management, continue anyways if fail\");\n \/\/\/ @todo RTC158181 suspend_pm()\n }\n\n FAPI_DBG(\"Check core clock controller status\");\n l_rc = p9_common_clk_ctrl_state(i_target);\n\n if (l_rc)\n {\n FAPI_INF(\"Clock controller of this core chiplet is inaccessible, return\");\n goto fapi_try_exit;\n }\n\n FAPI_DBG(\"Check cache clock controller status\");\n l_rc = p9_common_clk_ctrl_state(l_quad);\n\n if (l_rc)\n {\n FAPI_INF(\"WARNING: core is enabled while cache is not, continue anyways\");\n }\n else\n {\n\n FAPI_DBG(\"Check PERV clock status for access to CME via CLOCK_STAT[4]\");\n FAPI_TRY(getScom(l_quad, EQ_CLOCK_STAT_SL, l_data64));\n\n FAPI_DBG(\"Check PERV fence status for access to CME via CPLT_CTRL1[4]\");\n FAPI_TRY(getScom(l_quad, EQ_CPLT_CTRL1, l_temp64));\n\n if (l_data64.getBit<4>() == 0 && l_temp64.getBit<4>() == 0)\n {\n \/\/halt cme(poll for halted, if timeout, print warnning keep going).\n\n FAPI_DBG(\"Assert Core-L2\/CC Quiesces via CME_SCOM_SICR[6,8]\/[7,9]\");\n FAPI_TRY(putScom(l_quad,\n (l_attr_chip_unit_pos < 2) ?\n EX_0_CME_SCOM_SICR_OR : EX_1_CME_SCOM_SICR_OR,\n (BIT64(6 + (l_attr_chip_unit_pos % 2)) |\n BIT64(8 + (l_attr_chip_unit_pos % 2)))));\n }\n }\n\n FAPI_DBG(\"Assert pm_mux_disable to get PCB Mux from CME via SLAVE_CONFIG[7]\");\n FAPI_TRY(getScom(i_target, C_SLAVE_CONFIG_REG, l_data64));\n FAPI_TRY(putScom(i_target, C_SLAVE_CONFIG_REG, DATA_SET(7)));\n\n FAPI_DBG(\"Override possible PPM write protection to CME via CPPM_CPMMR[1]\");\n FAPI_TRY(putScom(i_target, C_CPPM_CPMMR_OR, MASK_SET(1)));\n\n FAPI_DBG(\"Assert chiplet fence via NET_CTRL0[18]\");\n FAPI_TRY(putScom(i_target, C_NET_CTRL0_WOR, MASK_SET(18)));\n\n \/\/ -------------------------------\n \/\/ Stop core clocks\n \/\/ -------------------------------\n\n FAPI_DBG(\"Clear all SCAN_REGION_TYPE bits\");\n FAPI_TRY(putScom(i_target, C_SCAN_REGION_TYPE, MASK_ZERO));\n\n FAPI_DBG(\"Stop core clocks(all but pll) via CLK_REGION\");\n l_data64 = (p9hcd::CLK_STOP_CMD |\n p9hcd::CLK_REGION_ALL_BUT_PLL |\n p9hcd::CLK_THOLD_ALL);\n FAPI_TRY(putScom(i_target, C_CLK_REGION, l_data64));\n\n FAPI_DBG(\"Poll for core clocks stopped via CPLT_STAT0[8]\");\n l_loops1ms = 1E6 \/ CORE_CLK_STOP_POLLING_HW_NS_DELAY;\n\n do\n {\n fapi2::delay(CORE_CLK_STOP_POLLING_HW_NS_DELAY,\n CORE_CLK_STOP_POLLING_SIM_CYCLE_DELAY);\n\n FAPI_TRY(getScom(i_target, C_CPLT_STAT0, l_data64));\n }\n while((l_data64.getBit<8>() != 1) && ((--l_loops1ms) != 0));\n\n FAPI_ASSERT((l_loops1ms != 0),\n fapi2::PMPROC_CORECLKSTOP_TIMEOUT().set_CORECPLTSTAT(l_data64),\n \"Core Clock Stop Timeout\");\n\n FAPI_DBG(\"Check core clocks stopped via CLOCK_STAT_SL[4-13]\");\n FAPI_TRY(getScom(i_target, C_CLOCK_STAT_SL, l_data64));\n\n FAPI_ASSERT((((~l_data64) & p9hcd::CLK_REGION_ALL_BUT_PLL) == 0),\n fapi2::PMPROC_CORECLKSTOP_FAILED().set_CORECLKSTAT(l_data64),\n \"Core Clock Stop Failed\");\n FAPI_DBG(\"Core clocks stopped now\");\n\n \/\/ -------------------------------\n \/\/ Disable core clock sync\n \/\/ -------------------------------\n\n FAPI_DBG(\"Drop core clock sync enable via CPPM_CACCR[15]\");\n FAPI_TRY(putScom(i_target, C_CPPM_CACCR_CLEAR, MASK_SET(15)));\n\n FAPI_DBG(\"Poll for core clock sync done to drop via CPPM_CACSR[13]\");\n l_loops1ms = 1E6 \/ CORE_CLK_SYNC_POLLING_HW_NS_DELAY;\n\n do\n {\n fapi2::delay(CORE_CLK_SYNC_POLLING_HW_NS_DELAY,\n CORE_CLK_SYNC_POLLING_SIM_CYCLE_DELAY);\n\n FAPI_TRY(getScom(i_target, C_CPPM_CACSR, l_data64));\n }\n while((l_data64.getBit<13>() == 1) && ((--l_loops1ms) != 0));\n\n FAPI_ASSERT((l_loops1ms != 0),\n fapi2::PMPROC_CORECLKSYNCDROP_TIMEOUT().set_COREPPMCACSR(l_data64),\n \"Core Clock Sync Drop Timeout\");\n FAPI_DBG(\"Core clock sync done dropped\");\n\n \/\/ -------------------------------\n \/\/ Fence up\n \/\/ -------------------------------\n\n FAPI_DBG(\"Assert skew sense to skew adjust fence via NET_CTRL0[22]\");\n FAPI_TRY(putScom(i_target, C_NET_CTRL0_WOR, MASK_SET(22)));\n\n FAPI_DBG(\"Drop ABIST_SRAM_MODE_DC to support ABIST Recovery via BIST[1]\");\n FAPI_TRY(getScom(i_target, C_BIST, l_data64));\n FAPI_TRY(putScom(i_target, C_BIST, DATA_UNSET(1)));\n\n FAPI_DBG(\"Assert vital fence via CPLT_CTRL1[3]\");\n FAPI_TRY(putScom(i_target, C_CPLT_CTRL1_OR, MASK_SET(3)));\n\n FAPI_DBG(\"Assert regional fences via CPLT_CTRL1[4-14]\");\n FAPI_TRY(putScom(i_target, C_CPLT_CTRL1_OR, p9hcd::CLK_REGION_ALL));\n\n if (l_attr_sdisn_setup)\n {\n FAPI_DBG(\"DD1 Only: Drop sdis_n(flushing LCBES condition) vai CPLT_CONF0[34]\");\n FAPI_TRY(putScom(i_target, C_CPLT_CONF0_CLEAR, MASK_SET(34)));\n }\n\n \/\/ -------------------------------\n \/\/ Disable VDM\n \/\/ -------------------------------\n\n if (l_attr_vdm_enable == fapi2::ENUM_ATTR_VDM_ENABLE_ON)\n {\n FAPI_DBG(\"Set VDM Disable via CPPM_VDMCR[1]\");\n FAPI_TRY(putScom(i_target, C_PPM_VDMCR_OR, MASK_SET(1)));\n FAPI_DBG(\"Drop VDM Poweron via CPPM_VDMCR[0]\");\n FAPI_TRY(putScom(i_target, C_PPM_VDMCR_CLEAR, MASK_SET(0)));\n }\n\n \/\/ -------------------------------\n \/\/ Update stop history\n \/\/ -------------------------------\n\n FAPI_DBG(\"Set core as stopped in STOP history register\");\n FAPI_TRY(putScom(i_target, C_PPM_SSHSRC, BIT64(0)));\n\n \/\/ -------------------------------\n \/\/ Clean up\n \/\/ -------------------------------\n\n FAPI_DBG(\"Return possible PPM write protection to CME via CPPM_CPMMR[1]\");\n FAPI_TRY(putScom(i_target, C_CPPM_CPMMR_CLEAR, MASK_SET(1)));\n\n FAPI_DBG(\"Drop pm_mux_disable to release PCB Mux via SLAVE_CONFIG[7]\");\n FAPI_TRY(getScom(i_target, C_SLAVE_CONFIG_REG, l_data64));\n FAPI_TRY(putScom(i_target, C_SLAVE_CONFIG_REG, DATA_UNSET(7)));\n\nfapi_try_exit:\n\n FAPI_INF(\"<"} {"text":"\/**************************************************************************\n * newbucket.hxx -- new bucket routines for better world modeling\n *\n * Written by Curtis L. Olson, started February 1999.\n *\n * Copyright (C) 1999 Curtis L. Olson - http:\/\/www.flightgear.org\/~curt\/\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Library General Public\n * License as published by the Free Software Foundation; either\n * version 2 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Library General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n *\n * $Id$\n **************************************************************************\/\n\n\n#ifdef HAVE_CONFIG_H\n# include \n#endif\n\n#include \n#include \/\/ some platforms need this for ::snprintf\n#include \n\n#include \n#include \n\n#include \"newbucket.hxx\"\n\n\n\/\/ default constructor\nSGBucket::SGBucket() :\n lon(-1000),\n lat(-1000),\n x(0),\n y(0)\n{\n}\n\nbool SGBucket::isValid() const\n{\n \/\/ The most northerly valid latitude is 89, not 90. There is no tile\n \/\/ whose *bottom* latitude is 90. Similar there is no tile whose left egde\n \/\/ is 180 longitude.\n return (lon >= -180) &&\n (lon < 180) &&\n (lat >= -90) &&\n (lat < 90) &&\n (x < 8) && (y < 8);\n}\n\nvoid SGBucket::make_bad()\n{\n lon = -1000;\n lat = -1000;\n}\n\n#ifndef NO_DEPRECATED_API\n\n\/\/ constructor for specified location\nSGBucket::SGBucket(const double dlon, const double dlat) {\n set_bucket(dlon, dlat);\n}\n#endif\n\nSGBucket::SGBucket(const SGGeod& geod) {\n set_bucket(geod.getLongitudeDeg(),\n geod.getLatitudeDeg());\n}\n\n\/\/ Parse a unique scenery tile index and find the lon, lat, x, and y\nSGBucket::SGBucket(const long int bindex) {\n long int index = bindex;\n\t\n lon = index >> 14;\n index -= lon << 14;\n lon -= 180;\n\n lat = index >> 6;\n index -= lat << 6;\n lat -= 90;\n\n y = index >> 3;\n index -= y << 3;\n\n x = index;\n}\n\n\/* Calculate the greatest integral value less than\n * or equal to the given value (floor(x)),\n * but attribute coordinates close to the boundary to the next\n * (increasing) integral\n *\/\nstatic int floorWithEpsilon(double x)\n{\n double diff = x - static_cast(x);\n if ( (x >= 0.0) || (fabs(diff) < SG_EPSILON) ) {\n return static_cast(x);\n } else {\n return static_cast(x) - 1;\n }\n}\n\n#ifndef NO_DEPRECATED_API\n\nvoid SGBucket::set_bucket(double dlon, double dlat)\n{\n innerSet(dlon, dlat);\n}\n\n\nvoid SGBucket::set_bucket(const SGGeod& geod)\n{\n innerSet(geod.getLongitudeDeg(), geod.getLatitudeDeg());\n}\n\n#endif\n\n\/\/ Set the bucket params for the specified lat and lon\nvoid SGBucket::innerSet( double dlon, double dlat )\n{\n if ((dlon < -180.0) || (dlon >= 180.0)) {\n SG_LOG(SG_TERRAIN, SG_WARN, \"SGBucket::set_bucket: passed longitude:\" << dlon);\n dlon = SGMiscd::normalizePeriodic(-180.0, 180.0, dlon);\n }\n \n if ((dlat < -90.0) || (dlat > 90.0)) {\n SG_LOG(SG_TERRAIN, SG_WARN, \"SGBucket::set_bucket: passed latitude\" << dlat);\n dlat = SGMiscd::clip(dlat, -90.0, 90.0);\n }\n \n \/\/\n \/\/ longitude first\n \/\/\n double span = sg_bucket_span( dlat );\n \/\/ we do NOT need to special case lon=180 here, since\n \/\/ normalizePeriodic will never return 180; it will\n \/\/ return -180, which is what we want.\n lon = floorWithEpsilon(dlon);\n \n \/\/ find subdivision or super lon if needed\n if ( span <= 1.0 ) {\n \/* We have more than one tile per degree of\n * longitude, so we need an x offset.\n *\/\n x = (int)((dlon - lon) \/ span);\n } else {\n \/* We have one or more degrees per tile,\n * so we need to find the base longitude\n * of that tile.\n *\n * First we calculate the integral base longitude\n * (e.g. -85.5 => -86) and then find the greatest\n * multiple of span that is less than or equal to\n * that longitude.\n *\n * That way, the Greenwich Meridian is always\n * a tile border.\n *\/\n lon=static_cast(floor(lon \/ span) * span);\n x = 0;\n }\n\n \/\/\n \/\/ then latitude\n \/\/\n lat = floorWithEpsilon(dlat);\n \n \/\/ special case when passing in the north pole point (possibly due to\n \/\/ clipping latitude above). Ensures we generate a valid bucket in this\n \/\/ scenario\n if (lat == 90) {\n lat = 89;\n y = 7;\n } else {\n \/* Latitude base and offset are easier, as\n * tiles always are 1\/8 degree of latitude wide.\n *\/\n y = (int)((dlat - lat) * 8);\n }\n}\n\n\/\/ Build the path name for this bucket\nstd::string SGBucket::gen_base_path() const {\n \/\/ long int index;\n int top_lon, top_lat, main_lon, main_lat;\n char hem, pole;\n char raw_path[256];\n\n top_lon = lon \/ 10;\n main_lon = lon;\n if ( (lon < 0) && (top_lon * 10 != lon) ) {\n\ttop_lon -= 1;\n }\n top_lon *= 10;\n if ( top_lon >= 0 ) {\n\them = 'e';\n } else {\n\them = 'w';\n\ttop_lon *= -1;\n }\n if ( main_lon < 0 ) {\n\tmain_lon *= -1;\n }\n \n top_lat = lat \/ 10;\n main_lat = lat;\n if ( (lat < 0) && (top_lat * 10 != lat) ) {\n\ttop_lat -= 1;\n }\n top_lat *= 10;\n if ( top_lat >= 0 ) {\n\tpole = 'n';\n } else {\n\tpole = 's';\n\ttop_lat *= -1;\n }\n if ( main_lat < 0 ) {\n\tmain_lat *= -1;\n }\n\n ::snprintf(raw_path, 256, \"%c%03d%c%02d\/%c%03d%c%02d\",\n\t hem, top_lon, pole, top_lat, \n\t hem, main_lon, pole, main_lat);\n\n SGPath path( raw_path );\n\n return path.str();\n}\n\n\n\/\/ return width of the tile in degrees\ndouble SGBucket::get_width() const {\n return sg_bucket_span( get_center_lat() );\n}\n\n\n\/\/ return height of the tile in degrees\ndouble SGBucket::get_height() const {\n return SG_BUCKET_SPAN;\n}\n\ndouble SGBucket::get_highest_lat() const\n{\n unsigned char adjustedY = y;\n if (lat >= 0) {\n \/\/ tile is north of the equator, so we want the top edge. Add one\n \/\/ to y to achieve this.\n ++adjustedY;\n }\n \n\treturn lat + (adjustedY \/ 8.0);\n}\n\n\n\/\/ return width of the tile in meters. This function is used by the\n\/\/ tile-manager to estimate how many tiles are in the view distance, so\n\/\/ we care about the smallest width, which occurs at the highest latitude.\ndouble SGBucket::get_width_m() const\n{\n double clat_rad = get_highest_lat() * SGD_DEGREES_TO_RADIANS;\n double cos_lat = cos( clat_rad );\n if (fabs(cos_lat) < SG_EPSILON) {\n \/\/ happens for polar tiles, since we pass in a latitude of 90\n \/\/ return an arbitrary small value so all tiles are loaded\n return 10.0;\n }\n \n double local_radius = cos_lat * SG_EQUATORIAL_RADIUS_M;\n double local_perimeter = local_radius * SGD_2PI;\n double degree_width = local_perimeter \/ 360.0;\n\n return get_width() * degree_width;\n}\n\n\n\/\/ return height of the tile in meters\ndouble SGBucket::get_height_m() const {\n double perimeter = SG_EQUATORIAL_RADIUS_M * SGD_2PI;\n double degree_height = perimeter \/ 360.0;\n\n return SG_BUCKET_SPAN * degree_height;\n}\n\nSGBucket SGBucket::sibling(int dx, int dy) const\n{\n if (!isValid()) {\n SG_LOG(SG_TERRAIN, SG_WARN, \"SGBucket::sibling: requesting sibling of invalid bucket\");\n return SGBucket();\n }\n \n double clat = get_center_lat() + dy * SG_BUCKET_SPAN;\n \/\/ return invalid here instead of clipping, so callers can discard\n \/\/ invalid buckets without having to check if it's an existing one\n if ((clat < -90.0) || (clat > 90.0)) {\n return SGBucket();\n }\n \n \/\/ find the lon span for the new latitude\n double span = sg_bucket_span( clat );\n \n double tmp = get_center_lon() + dx * span;\n tmp = SGMiscd::normalizePeriodic(-180.0, 180.0, tmp);\n \n SGBucket b;\n b.innerSet(tmp, clat);\n return b;\n}\n\nstd::string SGBucket::gen_index_str() const\n{\n\tchar tmp[20];\n\t::snprintf(tmp, 20, \"%ld\",\n (((long)lon + 180) << 14) + ((lat + 90) << 6)\n + (y << 3) + x);\n\treturn (std::string)tmp;\n}\n\n#ifndef NO_DEPRECATED_API\n\/\/ find the bucket which is offset by the specified tile units in the\n\/\/ X & Y direction. We need the current lon and lat to resolve\n\/\/ ambiguities when going from a wider tile to a narrower one above or\n\/\/ below. This assumes that we are feeding in\nSGBucket sgBucketOffset( double dlon, double dlat, int dx, int dy ) {\n SGBucket result( dlon, dlat );\n double clat = result.get_center_lat() + dy * SG_BUCKET_SPAN;\n\n \/\/ walk dy units in the lat direction\n result.set_bucket( dlon, clat );\n\n \/\/ find the lon span for the new latitude\n double span = sg_bucket_span( clat );\n\n \/\/ walk dx units in the lon direction\n double tmp = dlon + dx * span;\n while ( tmp < -180.0 ) {\n\ttmp += 360.0;\n }\n while ( tmp >= 180.0 ) {\n\ttmp -= 360.0;\n }\n result.set_bucket( tmp, clat );\n\n return result;\n}\n#endif\n\n\/\/ calculate the offset between two buckets\nvoid sgBucketDiff( const SGBucket& b1, const SGBucket& b2, int *dx, int *dy ) {\n\n \/\/ Latitude difference\n double c1_lat = b1.get_center_lat();\n double c2_lat = b2.get_center_lat();\n double diff_lat = c2_lat - c1_lat;\n\n#ifdef HAVE_RINT\n *dy = (int)rint( diff_lat \/ SG_BUCKET_SPAN );\n#else\n if ( diff_lat > 0 ) {\n\t*dy = (int)( diff_lat \/ SG_BUCKET_SPAN + 0.5 );\n } else {\n\t*dy = (int)( diff_lat \/ SG_BUCKET_SPAN - 0.5 );\n }\n#endif\n\n \/\/ longitude difference\n double diff_lon=0.0;\n double span=0.0;\n\n SGBucket tmp_bucket;\n \/\/ To handle crossing the bucket size boundary\n \/\/ we need to account for different size buckets.\n\n if ( sg_bucket_span(c1_lat) <= sg_bucket_span(c2_lat) )\n {\n\tspan = sg_bucket_span(c1_lat);\n } else {\n\tspan = sg_bucket_span(c2_lat);\n }\n\n diff_lon = b2.get_center_lon() - b1.get_center_lon();\n\n if (diff_lon <0.0)\n {\n diff_lon -= b1.get_width()*0.5 + b2.get_width()*0.5 - span;\n } \n else\n {\n diff_lon += b1.get_width()*0.5 + b2.get_width()*0.5 - span;\n }\n\n\n#ifdef HAVE_RINT\n *dx = (int)rint( diff_lon \/ span );\n#else\n if ( diff_lon > 0 ) {\n\t*dx = (int)( diff_lon \/ span + 0.5 );\n } else {\n\t*dx = (int)( diff_lon \/ span - 0.5 );\n }\n#endif\n}\n\nvoid sgGetBuckets( const SGGeod& min, const SGGeod& max, std::vector& list ) {\n double lon, lat, span;\n\n for (lat = min.getLatitudeDeg(); lat <= max.getLatitudeDeg(); lat += SG_BUCKET_SPAN) {\n span = sg_bucket_span( lat );\n for (lon = min.getLongitudeDeg(); lon <= max.getLongitudeDeg(); lon += span)\n {\n SGBucket b(SGGeod::fromDeg(lon, lat));\n if (!b.isValid()) {\n continue;\n }\n \n list.push_back(b);\n }\n }\n}\n\nstd::ostream& operator<< ( std::ostream& out, const SGBucket& b )\n{\n return out << b.lon << \":\" << (int)b.x << \", \" << b.lat << \":\" << (int)b.y;\n}\n\nFix new SGBucket API\/**************************************************************************\n * newbucket.hxx -- new bucket routines for better world modeling\n *\n * Written by Curtis L. Olson, started February 1999.\n *\n * Copyright (C) 1999 Curtis L. Olson - http:\/\/www.flightgear.org\/~curt\/\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Library General Public\n * License as published by the Free Software Foundation; either\n * version 2 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Library General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n *\n * $Id$\n **************************************************************************\/\n\n\n#ifdef HAVE_CONFIG_H\n# include \n#endif\n\n#include \n#include \/\/ some platforms need this for ::snprintf\n#include \n\n#include \n#include \n\n#include \"newbucket.hxx\"\n\n\n\/\/ default constructor\nSGBucket::SGBucket() :\n lon(-1000),\n lat(-1000),\n x(0),\n y(0)\n{\n}\n\nbool SGBucket::isValid() const\n{\n \/\/ The most northerly valid latitude is 89, not 90. There is no tile\n \/\/ whose *bottom* latitude is 90. Similar there is no tile whose left egde\n \/\/ is 180 longitude.\n return (lon >= -180) &&\n (lon < 180) &&\n (lat >= -90) &&\n (lat < 90) &&\n (x < 8) && (y < 8);\n}\n\nvoid SGBucket::make_bad()\n{\n lon = -1000;\n lat = -1000;\n}\n\n#ifndef NO_DEPRECATED_API\n\n\/\/ constructor for specified location\nSGBucket::SGBucket(const double dlon, const double dlat) {\n set_bucket(dlon, dlat);\n}\n#endif\n\nSGBucket::SGBucket(const SGGeod& geod) {\n innerSet(geod.getLongitudeDeg(),\n geod.getLatitudeDeg());\n}\n\n\/\/ Parse a unique scenery tile index and find the lon, lat, x, and y\nSGBucket::SGBucket(const long int bindex) {\n long int index = bindex;\n\t\n lon = index >> 14;\n index -= lon << 14;\n lon -= 180;\n\n lat = index >> 6;\n index -= lat << 6;\n lat -= 90;\n\n y = index >> 3;\n index -= y << 3;\n\n x = index;\n}\n\n\/* Calculate the greatest integral value less than\n * or equal to the given value (floor(x)),\n * but attribute coordinates close to the boundary to the next\n * (increasing) integral\n *\/\nstatic int floorWithEpsilon(double x)\n{\n double diff = x - static_cast(x);\n if ( (x >= 0.0) || (fabs(diff) < SG_EPSILON) ) {\n return static_cast(x);\n } else {\n return static_cast(x) - 1;\n }\n}\n\n#ifndef NO_DEPRECATED_API\n\nvoid SGBucket::set_bucket(double dlon, double dlat)\n{\n innerSet(dlon, dlat);\n}\n\n\nvoid SGBucket::set_bucket(const SGGeod& geod)\n{\n innerSet(geod.getLongitudeDeg(), geod.getLatitudeDeg());\n}\n\n#endif\n\n\/\/ Set the bucket params for the specified lat and lon\nvoid SGBucket::innerSet( double dlon, double dlat )\n{\n if ((dlon < -180.0) || (dlon >= 180.0)) {\n SG_LOG(SG_TERRAIN, SG_WARN, \"SGBucket::set_bucket: passed longitude:\" << dlon);\n dlon = SGMiscd::normalizePeriodic(-180.0, 180.0, dlon);\n }\n \n if ((dlat < -90.0) || (dlat > 90.0)) {\n SG_LOG(SG_TERRAIN, SG_WARN, \"SGBucket::set_bucket: passed latitude\" << dlat);\n dlat = SGMiscd::clip(dlat, -90.0, 90.0);\n }\n \n \/\/\n \/\/ longitude first\n \/\/\n double span = sg_bucket_span( dlat );\n \/\/ we do NOT need to special case lon=180 here, since\n \/\/ normalizePeriodic will never return 180; it will\n \/\/ return -180, which is what we want.\n lon = floorWithEpsilon(dlon);\n \n \/\/ find subdivision or super lon if needed\n if ( span <= 1.0 ) {\n \/* We have more than one tile per degree of\n * longitude, so we need an x offset.\n *\/\n x = (int)((dlon - lon) \/ span);\n } else {\n \/* We have one or more degrees per tile,\n * so we need to find the base longitude\n * of that tile.\n *\n * First we calculate the integral base longitude\n * (e.g. -85.5 => -86) and then find the greatest\n * multiple of span that is less than or equal to\n * that longitude.\n *\n * That way, the Greenwich Meridian is always\n * a tile border.\n *\/\n lon=static_cast(floor(lon \/ span) * span);\n x = 0;\n }\n\n \/\/\n \/\/ then latitude\n \/\/\n lat = floorWithEpsilon(dlat);\n \n \/\/ special case when passing in the north pole point (possibly due to\n \/\/ clipping latitude above). Ensures we generate a valid bucket in this\n \/\/ scenario\n if (lat == 90) {\n lat = 89;\n y = 7;\n } else {\n \/* Latitude base and offset are easier, as\n * tiles always are 1\/8 degree of latitude wide.\n *\/\n y = (int)((dlat - lat) * 8);\n }\n}\n\n\/\/ Build the path name for this bucket\nstd::string SGBucket::gen_base_path() const {\n \/\/ long int index;\n int top_lon, top_lat, main_lon, main_lat;\n char hem, pole;\n char raw_path[256];\n\n top_lon = lon \/ 10;\n main_lon = lon;\n if ( (lon < 0) && (top_lon * 10 != lon) ) {\n\ttop_lon -= 1;\n }\n top_lon *= 10;\n if ( top_lon >= 0 ) {\n\them = 'e';\n } else {\n\them = 'w';\n\ttop_lon *= -1;\n }\n if ( main_lon < 0 ) {\n\tmain_lon *= -1;\n }\n \n top_lat = lat \/ 10;\n main_lat = lat;\n if ( (lat < 0) && (top_lat * 10 != lat) ) {\n\ttop_lat -= 1;\n }\n top_lat *= 10;\n if ( top_lat >= 0 ) {\n\tpole = 'n';\n } else {\n\tpole = 's';\n\ttop_lat *= -1;\n }\n if ( main_lat < 0 ) {\n\tmain_lat *= -1;\n }\n\n ::snprintf(raw_path, 256, \"%c%03d%c%02d\/%c%03d%c%02d\",\n\t hem, top_lon, pole, top_lat, \n\t hem, main_lon, pole, main_lat);\n\n SGPath path( raw_path );\n\n return path.str();\n}\n\n\n\/\/ return width of the tile in degrees\ndouble SGBucket::get_width() const {\n return sg_bucket_span( get_center_lat() );\n}\n\n\n\/\/ return height of the tile in degrees\ndouble SGBucket::get_height() const {\n return SG_BUCKET_SPAN;\n}\n\ndouble SGBucket::get_highest_lat() const\n{\n unsigned char adjustedY = y;\n if (lat >= 0) {\n \/\/ tile is north of the equator, so we want the top edge. Add one\n \/\/ to y to achieve this.\n ++adjustedY;\n }\n \n\treturn lat + (adjustedY \/ 8.0);\n}\n\n\n\/\/ return width of the tile in meters. This function is used by the\n\/\/ tile-manager to estimate how many tiles are in the view distance, so\n\/\/ we care about the smallest width, which occurs at the highest latitude.\ndouble SGBucket::get_width_m() const\n{\n double clat_rad = get_highest_lat() * SGD_DEGREES_TO_RADIANS;\n double cos_lat = cos( clat_rad );\n if (fabs(cos_lat) < SG_EPSILON) {\n \/\/ happens for polar tiles, since we pass in a latitude of 90\n \/\/ return an arbitrary small value so all tiles are loaded\n return 10.0;\n }\n \n double local_radius = cos_lat * SG_EQUATORIAL_RADIUS_M;\n double local_perimeter = local_radius * SGD_2PI;\n double degree_width = local_perimeter \/ 360.0;\n\n return get_width() * degree_width;\n}\n\n\n\/\/ return height of the tile in meters\ndouble SGBucket::get_height_m() const {\n double perimeter = SG_EQUATORIAL_RADIUS_M * SGD_2PI;\n double degree_height = perimeter \/ 360.0;\n\n return SG_BUCKET_SPAN * degree_height;\n}\n\nSGBucket SGBucket::sibling(int dx, int dy) const\n{\n if (!isValid()) {\n SG_LOG(SG_TERRAIN, SG_WARN, \"SGBucket::sibling: requesting sibling of invalid bucket\");\n return SGBucket();\n }\n \n double clat = get_center_lat() + dy * SG_BUCKET_SPAN;\n \/\/ return invalid here instead of clipping, so callers can discard\n \/\/ invalid buckets without having to check if it's an existing one\n if ((clat < -90.0) || (clat > 90.0)) {\n return SGBucket();\n }\n \n \/\/ find the lon span for the new latitude\n double span = sg_bucket_span( clat );\n \n double tmp = get_center_lon() + dx * span;\n tmp = SGMiscd::normalizePeriodic(-180.0, 180.0, tmp);\n \n SGBucket b;\n b.innerSet(tmp, clat);\n return b;\n}\n\nstd::string SGBucket::gen_index_str() const\n{\n\tchar tmp[20];\n\t::snprintf(tmp, 20, \"%ld\",\n (((long)lon + 180) << 14) + ((lat + 90) << 6)\n + (y << 3) + x);\n\treturn (std::string)tmp;\n}\n\n#ifndef NO_DEPRECATED_API\n\/\/ find the bucket which is offset by the specified tile units in the\n\/\/ X & Y direction. We need the current lon and lat to resolve\n\/\/ ambiguities when going from a wider tile to a narrower one above or\n\/\/ below. This assumes that we are feeding in\nSGBucket sgBucketOffset( double dlon, double dlat, int dx, int dy ) {\n SGBucket result( dlon, dlat );\n double clat = result.get_center_lat() + dy * SG_BUCKET_SPAN;\n\n \/\/ walk dy units in the lat direction\n result.set_bucket( dlon, clat );\n\n \/\/ find the lon span for the new latitude\n double span = sg_bucket_span( clat );\n\n \/\/ walk dx units in the lon direction\n double tmp = dlon + dx * span;\n while ( tmp < -180.0 ) {\n\ttmp += 360.0;\n }\n while ( tmp >= 180.0 ) {\n\ttmp -= 360.0;\n }\n result.set_bucket( tmp, clat );\n\n return result;\n}\n#endif\n\n\/\/ calculate the offset between two buckets\nvoid sgBucketDiff( const SGBucket& b1, const SGBucket& b2, int *dx, int *dy ) {\n\n \/\/ Latitude difference\n double c1_lat = b1.get_center_lat();\n double c2_lat = b2.get_center_lat();\n double diff_lat = c2_lat - c1_lat;\n\n#ifdef HAVE_RINT\n *dy = (int)rint( diff_lat \/ SG_BUCKET_SPAN );\n#else\n if ( diff_lat > 0 ) {\n\t*dy = (int)( diff_lat \/ SG_BUCKET_SPAN + 0.5 );\n } else {\n\t*dy = (int)( diff_lat \/ SG_BUCKET_SPAN - 0.5 );\n }\n#endif\n\n \/\/ longitude difference\n double diff_lon=0.0;\n double span=0.0;\n\n SGBucket tmp_bucket;\n \/\/ To handle crossing the bucket size boundary\n \/\/ we need to account for different size buckets.\n\n if ( sg_bucket_span(c1_lat) <= sg_bucket_span(c2_lat) )\n {\n\tspan = sg_bucket_span(c1_lat);\n } else {\n\tspan = sg_bucket_span(c2_lat);\n }\n\n diff_lon = b2.get_center_lon() - b1.get_center_lon();\n\n if (diff_lon <0.0)\n {\n diff_lon -= b1.get_width()*0.5 + b2.get_width()*0.5 - span;\n } \n else\n {\n diff_lon += b1.get_width()*0.5 + b2.get_width()*0.5 - span;\n }\n\n\n#ifdef HAVE_RINT\n *dx = (int)rint( diff_lon \/ span );\n#else\n if ( diff_lon > 0 ) {\n\t*dx = (int)( diff_lon \/ span + 0.5 );\n } else {\n\t*dx = (int)( diff_lon \/ span - 0.5 );\n }\n#endif\n}\n\nvoid sgGetBuckets( const SGGeod& min, const SGGeod& max, std::vector& list ) {\n double lon, lat, span;\n\n for (lat = min.getLatitudeDeg(); lat <= max.getLatitudeDeg(); lat += SG_BUCKET_SPAN) {\n span = sg_bucket_span( lat );\n for (lon = min.getLongitudeDeg(); lon <= max.getLongitudeDeg(); lon += span)\n {\n SGBucket b(SGGeod::fromDeg(lon, lat));\n if (!b.isValid()) {\n continue;\n }\n \n list.push_back(b);\n }\n }\n}\n\nstd::ostream& operator<< ( std::ostream& out, const SGBucket& b )\n{\n return out << b.lon << \":\" << (int)b.x << \", \" << b.lat << \":\" << (int)b.y;\n}\n\n<|endoftext|>"} {"text":"#include \"xchainer\/array_body.h\"\n\n#include \n#include \n#include \n\n#include \"xchainer\/array.h\"\n#include \"xchainer\/array_node.h\"\n#include \"xchainer\/backward.h\"\n#include \"xchainer\/error.h\"\n#include \"xchainer\/graph.h\"\n\nnamespace xchainer {\nnamespace internal {\n\nArrayBody::ArrayBody(Shape shape, Strides strides, Dtype dtype, Device& device, std::shared_ptr data, int64_t offset)\n : shape_{std::move(shape)}, strides_{std::move(strides)}, dtype_{dtype}, device_{device}, data_{std::move(data)}, offset_{offset} {}\n\nconst std::shared_ptr& ArrayBody::AddNode(std::shared_ptr array_node) {\n AssertConsistency();\n assert(this == array_node->GetBody().get());\n if (std::any_of(nodes_.begin(), nodes_.end(), [&array_node](const std::shared_ptr& existing_node) {\n return existing_node->graph_id() == array_node->graph_id();\n })) {\n throw XchainerError{\"Duplicate graph registration: '\", array_node->graph_id(), \"'.\"};\n }\n\n nodes_.emplace_back(std::move(array_node));\n grads_.emplace_back(std::make_unique>(nonstd::nullopt));\n\n AssertConsistency();\n return nodes_.back();\n}\n\nvoid ArrayBody::AssertConsistency() const {\n#ifndef NDEBUG\n assert(nodes_.size() == grads_.size());\n for (size_t i = 0; i < nodes_.size(); ++i) {\n const std::shared_ptr& array_node = nodes_[i];\n const nonstd::optional& grad = *grads_[i];\n assert(array_node != nullptr);\n assert(this == array_node->GetBody().get());\n if (grad.has_value()) {\n assert(grad->body() != nullptr);\n assert(grad->shape() == array_node->shape());\n assert(grad->dtype() == array_node->dtype());\n assert(&grad->device() == &array_node->device());\n }\n }\n#endif \/* NDEBUG *\/\n}\n\nnonstd::optional ArrayBody::GetNodeIndex(const GraphId& graph_id) const {\n AssertConsistency();\n for (size_t i = 0; i < nodes_.size(); ++i) {\n if (nodes_[i]->graph_id() == graph_id) {\n return i;\n }\n }\n return nonstd::nullopt;\n}\n\nvoid ArrayBody::SetGrad(Array grad, const GraphId& graph_id) {\n nonstd::optional* target_grad = GetGrad(graph_id);\n assert(target_grad != nullptr);\n internal::SetGrad(*target_grad, std::move(grad), shape_, dtype_, device_);\n}\n\nvoid ArrayBody::AccumulateGrad(Array partial_grad, const GraphId& graph_id) {\n nonstd::optional* target_grad = GetGrad(graph_id);\n assert(target_grad != nullptr);\n internal::AccumulateGrad(*target_grad, std::move(partial_grad), shape_, dtype_, device_);\n}\n\nvoid ArrayBody::ClearGrad(const GraphId& graph_id) {\n nonstd::optional* grad = GetGrad(graph_id);\n if (grad == nullptr) {\n throw XchainerError{\"Array does not belong to the graph: '\", graph_id, \"'.\"};\n }\n grad->reset();\n}\n\ntemplate \nReturnType ArrayBody::GetGradImpl(ThisPtr this_ptr, const GraphId& graph_id) {\n this_ptr->AssertConsistency();\n\n nonstd::optional i = this_ptr->GetNodeIndex(graph_id);\n if (!i.has_value()) {\n return nullptr;\n }\n assert(*i < this_ptr->grads_.size());\n return this_ptr->grads_[*i].get();\n}\n\ntemplate nonstd::optional* ArrayBody::GetGradImpl*>(ArrayBody*, const GraphId&);\ntemplate const nonstd::optional* ArrayBody::GetGradImpl*>(\n const ArrayBody*, const GraphId&);\n\n} \/\/ namespace internal\n} \/\/ namespace xchainer\nRemove duplicated check#include \"xchainer\/array_body.h\"\n\n#include \n#include \n#include \n\n#include \"xchainer\/array.h\"\n#include \"xchainer\/array_node.h\"\n#include \"xchainer\/backward.h\"\n#include \"xchainer\/error.h\"\n#include \"xchainer\/graph.h\"\n\nnamespace xchainer {\nnamespace internal {\n\nArrayBody::ArrayBody(Shape shape, Strides strides, Dtype dtype, Device& device, std::shared_ptr data, int64_t offset)\n : shape_{std::move(shape)}, strides_{std::move(strides)}, dtype_{dtype}, device_{device}, data_{std::move(data)}, offset_{offset} {}\n\nconst std::shared_ptr& ArrayBody::AddNode(std::shared_ptr array_node) {\n AssertConsistency();\n assert(this == array_node->GetBody().get());\n if (std::any_of(nodes_.begin(), nodes_.end(), [&array_node](const std::shared_ptr& existing_node) {\n return existing_node->graph_id() == array_node->graph_id();\n })) {\n throw XchainerError{\"Duplicate graph registration: '\", array_node->graph_id(), \"'.\"};\n }\n\n nodes_.emplace_back(std::move(array_node));\n grads_.emplace_back(std::make_unique>(nonstd::nullopt));\n\n AssertConsistency();\n return nodes_.back();\n}\n\nvoid ArrayBody::AssertConsistency() const {\n#ifndef NDEBUG\n assert(nodes_.size() == grads_.size());\n for (size_t i = 0; i < nodes_.size(); ++i) {\n const std::shared_ptr& array_node = nodes_[i];\n const nonstd::optional& grad = *grads_[i];\n assert(array_node != nullptr);\n assert(this == array_node->GetBody().get());\n if (grad.has_value()) {\n assert(grad->body() != nullptr);\n assert(grad->shape() == array_node->shape());\n assert(grad->dtype() == array_node->dtype());\n assert(&grad->device() == &array_node->device());\n }\n }\n#endif \/* NDEBUG *\/\n}\n\nnonstd::optional ArrayBody::GetNodeIndex(const GraphId& graph_id) const {\n for (size_t i = 0; i < nodes_.size(); ++i) {\n if (nodes_[i]->graph_id() == graph_id) {\n return i;\n }\n }\n return nonstd::nullopt;\n}\n\nvoid ArrayBody::SetGrad(Array grad, const GraphId& graph_id) {\n nonstd::optional* target_grad = GetGrad(graph_id);\n assert(target_grad != nullptr);\n internal::SetGrad(*target_grad, std::move(grad), shape_, dtype_, device_);\n}\n\nvoid ArrayBody::AccumulateGrad(Array partial_grad, const GraphId& graph_id) {\n nonstd::optional* target_grad = GetGrad(graph_id);\n assert(target_grad != nullptr);\n internal::AccumulateGrad(*target_grad, std::move(partial_grad), shape_, dtype_, device_);\n}\n\nvoid ArrayBody::ClearGrad(const GraphId& graph_id) {\n nonstd::optional* grad = GetGrad(graph_id);\n if (grad == nullptr) {\n throw XchainerError{\"Array does not belong to the graph: '\", graph_id, \"'.\"};\n }\n grad->reset();\n}\n\ntemplate \nReturnType ArrayBody::GetGradImpl(ThisPtr this_ptr, const GraphId& graph_id) {\n this_ptr->AssertConsistency();\n\n nonstd::optional i = this_ptr->GetNodeIndex(graph_id);\n if (!i.has_value()) {\n return nullptr;\n }\n assert(*i < this_ptr->grads_.size());\n return this_ptr->grads_[*i].get();\n}\n\ntemplate nonstd::optional* ArrayBody::GetGradImpl*>(ArrayBody*, const GraphId&);\ntemplate const nonstd::optional* ArrayBody::GetGradImpl*>(\n const ArrayBody*, const GraphId&);\n\n} \/\/ namespace internal\n} \/\/ namespace xchainer\n<|endoftext|>"} {"text":"\/* *\n* Copyright (c) 2013 Julio Gutierrez\n* \n* Permission is hereby granted, free of charge, to any person obtaining a co$\n* this software and associated documentation files (the \"Software\"), to deal$\n* the Software without restriction, including without limitation the rights $\n* use, copy, modify, merge, publish, distribute, sublicense, and\/or sell cop$\n* the Software, and to permit persons to whom the Software is furnished to d$\n* subject to the following conditions:\n* \n* The above copyright notice and this permission notice shall be included in$\n* copies or substantial portions of the Software.\n* \n* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, F$\n* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHOR$\n* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHE$\n* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n* *\/\n\n#include \n#include \n\nint main(int argc, char* argv[])\n{\n\n\traspboop::Init(raspboop::WIRING);\n\n}\nsensors: main implementation\/* *\n* Copyright (c) 2013 Julio Gutierrez\n* \n* Permission is hereby granted, free of charge, to any person obtaining a co$\n* this software and associated documentation files (the \"Software\"), to deal$\n* the Software without restriction, including without limitation the rights $\n* use, copy, modify, merge, publish, distribute, sublicense, and\/or sell cop$\n* the Software, and to permit persons to whom the Software is furnished to d$\n* subject to the following conditions:\n* \n* The above copyright notice and this permission notice shall be included in$\n* copies or substantial portions of the Software.\n* \n* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, F$\n* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHOR$\n* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHE$\n* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n* *\/\n\n#include \n#include \n\nusing raspboop::HCSR04;\nusing raspboop::HCSR501;\n\nint main(int argc, char* argv[])\n{\n\n#define SIG 6\n#define TRIG 4\n#define ECHO 5\n\n\traspboop::Init(raspboop::WIRING);\n\n\tHCSR04* DistanceSensor = HCSR04::Create(ECHO, TRIG);\n\tHCSR501* InfraredSensor = HCSR501::Create(SIG);\n\n\twhile(true)\n\t{\n\n\t\tInfraredSensor->Sense();\n\t\tDistanceSensor->Sense();\n\n\t\tprintf(\"Motion Detected: %d\", InfraredSensor->IsSignalled());\n\t\tprintf(\"Distance: %0.2f cm\", DistanceSensor->GetDistance());\n\n\t\tdelay(1000);\n\t}\n\n\treturn 0;\n}\n<|endoftext|>"} {"text":"\/* carbon_connector.cc\n Jeremy Barnes, 3 August 2011\n Copyright (c) 2011 Datacratic. All rights reserved.\n\n*\/\n\n#include \"soa\/service\/carbon_connector.h\"\n#include \"ace\/INET_Addr.h\"\n#include \"jml\/arch\/exception.h\"\n#include \"jml\/arch\/format.h\"\n#include \n#include \"jml\/arch\/cmp_xchg.h\"\n#include \"jml\/arch\/atomic_ops.h\"\n#include \"jml\/arch\/timers.h\"\n#include \"jml\/arch\/futex.h\"\n#include \"jml\/utils\/floating_point.h\"\n#include \"jml\/utils\/smart_ptr_utils.h\"\n#include \"jml\/utils\/exc_assert.h\"\n#include \n#include \n#include \n#include \n\n\nusing namespace std;\nusing namespace ML;\n\n\nnamespace Datacratic {\n\n\n\/*****************************************************************************\/\n\/* MULTI AGGREGATOR *\/\n\/*****************************************************************************\/\n\nMultiAggregator::\nMultiAggregator()\n : doShutdown(false), doDump(false), dumpInterval(0.0)\n{\n}\n\nMultiAggregator::\nMultiAggregator(const std::string & path,\n const OutputFn & output,\n double dumpInterval,\n std::function onStop)\n : doShutdown(false), doDump(false)\n{\n open(path, output, dumpInterval, onStop);\n}\n\nMultiAggregator::\n~MultiAggregator()\n{\n shutdown();\n}\n\nvoid\nMultiAggregator::\nopen(const std::string & path,\n const OutputFn & output,\n double dumpInterval,\n std::function onStop)\n{\n shutdown();\n\n doShutdown = doDump = false;\n if (dumpInterval < 1.0) {\n dumpInterval = 1.0;\n }\n this->dumpInterval = dumpInterval;\n this->onStop = onStop;\n\n if (path == \"\") prefix = \"\";\n else prefix = path + \".\";\n\n if (output)\n outputFn = output;\n else\n outputFn = [&] (const std::vector & values)\n {\n this->doStat(values);\n };\n\n dumpingThread.reset\n (new std::thread(std::bind(&MultiAggregator::runDumpingThread,\n this)));\n}\n\nvoid\nMultiAggregator::\nstop()\n{\n shutdown();\n}\n\nvoid\nMultiAggregator::\ndoStat(const std::vector & values) const\n{\n outputFn(values);\n}\n\nStatAggregator * createNewCounter()\n{\n return new CounterAggregator();\n}\n\nStatAggregator * createNewStableLevel()\n{\n return new GaugeAggregator(GaugeAggregator::StableLevel);\n}\n\nStatAggregator * createNewLevel()\n{\n return new GaugeAggregator(GaugeAggregator::Level);\n}\n\nStatAggregator * createNewOutcome()\n{\n return new GaugeAggregator(GaugeAggregator::Outcome);\n}\n\nvoid\nMultiAggregator::\nrecord(const std::string & stat,\n EventType type,\n float value)\n{\n switch (type) {\n case ET_HIT: recordHit(stat); break;\n case ET_COUNT: recordCount(stat, value); break;\n case ET_STABLE_LEVEL: recordStableLevel(stat, value); break;\n case ET_LEVEL: recordLevel(stat, value); break;\n case ET_OUTCOME: recordOutcome(stat, value); break;\n default:\n cerr << \"warning: unknown stat type\" << endl;\n }\n}\n\nvoid\nMultiAggregator::\nrecordHit(const std::string & stat)\n{\n getAggregator(stat, createNewCounter).record(1.0);\n}\n\nvoid\nMultiAggregator::\nrecordCount(const std::string & stat, float quantity)\n{\n getAggregator(stat, createNewCounter).record(quantity);\n}\n\nvoid\nMultiAggregator::\nrecordStableLevel(const std::string & stat, float value)\n{\n getAggregator(stat, createNewStableLevel).record(value);\n}\n\nvoid\nMultiAggregator::\nrecordLevel(const std::string & stat, float value)\n{\n getAggregator(stat, createNewLevel).record(value);\n}\n \nvoid\nMultiAggregator::\nrecordOutcome(const std::string & stat, float value)\n{\n getAggregator(stat, createNewOutcome).record(value);\n}\n\n\nvoid\nMultiAggregator::\ndump()\n{\n {\n std::lock_guard lock(m);\n doDump = true;\n }\n \n cond.notify_all();\n}\n\nvoid\nMultiAggregator::\ndumpSync(std::ostream & stream) const\n{\n std::unique_lock guard(this->lock);\n\n for (auto & s: stats) {\n auto vals = s.second->read(s.first);\n for (auto v: vals) {\n stream << v.name << \":\\t\" << v.value << endl;\n }\n }\n}\n\nvoid\nMultiAggregator::\nshutdown()\n{\n if (dumpingThread) {\n if (onPreShutdown) onPreShutdown();\n \n {\n std::lock_guard lock(m);\n doShutdown = true;\n }\n\n cond.notify_all();\n \n dumpingThread->join();\n dumpingThread.reset();\n\n if (onPostShutdown) onPostShutdown();\n\n if (onStop) onStop();\n }\n}\n\nStatAggregator &\nMultiAggregator::\ngetAggregator(const std::string & stat,\n StatAggregator * (*createFn) ())\n{\n if (!lookupCache.get())\n lookupCache.reset(new LookupCache());\n\n auto found = lookupCache->find(stat);\n if (found != lookupCache->end())\n return *found->second->second;\n\n \/\/ Get the read lock to look for the aggregator\n std::unique_lock guard(lock);\n\n auto found2 = stats.find(stat);\n\n if (found2 != stats.end()) {\n guard.unlock();\n\n (*lookupCache)[stat] = found2;\n\n return *found2->second;\n }\n \n guard.unlock();\n\n \/\/ Get the write lock to add it to the aggregator\n std::unique_lock guard2(lock);\n\n \/\/ Add it in\n found2 = stats.insert(make_pair(stat, std::shared_ptr(createFn()))).first;\n\n guard2.unlock();\n (*lookupCache)[stat] = found2;\n return *found2->second;\n}\n\nvoid\nMultiAggregator::\nrunDumpingThread()\n{\n\n size_t current = 0;\n\n for (;;) {\n std::unique_lock lock(m);\n\n Date now = Date::now();\n Date nextWakeup = now.plusSeconds(1.0);\n if (cond.wait_until(lock, nextWakeup.toStd(), [&] { return doShutdown.load(); }))\n break;\n\n \/\/ Get the read lock to extract a list of stats to dump\n vector toDump;\n {\n std::unique_lock guard(this->lock);\n toDump.reserve(stats.size());\n for (auto it = stats.begin(), end = stats.end(); it != end; ++it)\n toDump.push_back(it);\n }\n\n ++current;\n bool dumpNow = doDump.exchange(false) ||\n (current % static_cast(dumpInterval)) == 0;\n\n \/\/ Now dump them without the lock held. Note that we still need to call\n \/\/ read every second even if we're not flushing to carbon.\n for (auto it = toDump.begin(), end = toDump.end(); it != end; ++it) {\n\n try {\n auto stat = (*it)->second->read((*it)->first);\n if (dumpNow) doStat(std::move(stat));\n } catch (const std::exception & exc) {\n cerr << \"error writing stat: \" << exc.what() << endl;\n }\n }\n }\n}\n\n\n\/*****************************************************************************\/\n\/* CARBON CONNECTOR *\/\n\/*****************************************************************************\/\n\nCarbonConnector::\nCarbonConnector()\n{\n}\n\nCarbonConnector::\nCarbonConnector(const std::string & carbonAddr,\n const std::string & path,\n double dumpInterval,\n std::function onStop)\n{\n open(carbonAddr, path, dumpInterval, onStop);\n}\n\nCarbonConnector::\nCarbonConnector(const std::vector & carbonAddrs,\n const std::string & path,\n double dumpInterval,\n std::function onStop)\n{\n open(carbonAddrs, path,dumpInterval, onStop);\n}\n\nCarbonConnector::\n~CarbonConnector()\n{\n doShutdown();\n}\n\nvoid\nCarbonConnector::\nopen(const std::string & carbonAddr,\n const std::string & path,\n double dumpInterval,\n std::function onStop)\n{\n return open(vector({carbonAddr}), path, dumpInterval, onStop);\n}\n\nvoid\nCarbonConnector::\nopen(const std::vector & carbonAddrs,\n const std::string & path,\n double dumpInterval,\n std::function onStop)\n{\n stop();\n\n int numConnections = 0;\n\n connections.clear();\n for (unsigned i = 0; i < carbonAddrs.size(); ++i) {\n connections.push_back(std::make_shared\n (carbonAddrs[i]));\n string error = connections.back()->connect();\n if (connections.back()->fd == -1) {\n cerr << \"error connecting to Carbon at \" << carbonAddrs[i]\n << \": \" << error << endl;\n }\n else ++numConnections;\n }\n\n if (numConnections == 0)\n throw ML::Exception(\"unable to connect to any Carbon instances\");\n\n this->onPostShutdown = std::bind(&CarbonConnector::doShutdown, this);\n\n MultiAggregator::open(path, OutputFn(), dumpInterval, onStop);\n}\n\nvoid\nCarbonConnector::\ndoShutdown()\n{\n stop();\n connections.clear();\n}\n\nvoid\nCarbonConnector::\ndoStat(const std::vector & values) const\n{\n if (connections.empty())\n return;\n\n std::string message;\n\n for (unsigned i = 0; i < values.size(); ++i) {\n message += ML::format(\"%s%s %.5f %lld\\n\",\n prefix.c_str(), values[i].name.c_str(),\n values[i].value,\n (unsigned long long)\n values[i].timestamp.secondsSinceEpoch());\n }\n\n for (unsigned i = 0; i < connections.size(); ++i)\n connections[i]->send(message);\n}\n\nCarbonConnector::Connection::\n~Connection()\n{\n close();\n\n if (reconnectionThread) {\n shutdown = 1;\n futex_wake(shutdown);\n reconnectionThread->join();\n reconnectionThread.reset();\n }\n}\n\nvoid\nCarbonConnector::Connection::\nclose()\n{\n if (fd != -1)\n ::close(fd);\n fd = -1;\n}\n\nstd::string\nCarbonConnector::Connection::\nconnect()\n{\n if (fd != -1)\n throw ML::Exception(\"error connecting\");\n\n ip = ACE_INET_Addr(addr.c_str());\n\n cerr << \"connecting to Carbon at \"\n << ip.get_host_addr() << \":\" << ip.get_port_number()\n << \" (\" << ip.get_host_name() << \")\" << endl;\n\n int tmpFd = socket(AF_INET, SOCK_STREAM, 0);\n int res = ::connect(tmpFd,\n (sockaddr *)ip.get_addr(),\n ip.get_addr_size());\n \n int saved_errno = errno;\n\n if (res == -1) {\n ::close(tmpFd);\n return ML::format(\"connect to carbon at %s:%d (%s): %s\",\n ip.get_host_addr(),\n ip.get_port_number(),\n ip.get_host_name(),\n strerror(saved_errno));\n }\n\n fd = tmpFd;\n\n return \"\";\n}\n\nvoid\nCarbonConnector::Connection::\nsend(const std::string & message)\n{\n \/\/cerr << \"STAT: \" << message << endl;\n \/\/return;\n if (message.empty())\n return;\n\n \/\/cerr << \"sending to \" << addr << \" on \" << fd << \" \" << message << endl;\n\n if (fd == -1) {\n if (reconnectionThreadActive) return;\n throw ML::Exception(\"send with fd -1 and no thread active\");\n }\n \n size_t done = 0;\n\n for (;;) {\n int sendRes = ::send(fd, message.c_str() + done,\n message.size() - done,\n MSG_DONTWAIT | MSG_NOSIGNAL);\n \n if (sendRes > 0) {\n done += sendRes;\n if (done == message.size())\n return; \/\/ done; normal case\n else if (done > message.size())\n throw ML::Exception(\"logic error sending message to Carbon\");\n else continue; \/\/ do the rest of the message\n }\n \n if (sendRes != -1)\n throw ML::Exception(\"invalid return code from send\");\n \n \/\/ Error handling\n if (errno == EINTR)\n continue; \/\/ retry\n else if (errno == EAGAIN || errno == EWOULDBLOCK) {\n \/\/ Would block (something that we don't want). Select on the\n \/\/ socket for the timeout before giving up.\n struct pollfd events[] = {\n { fd, POLLOUT | POLLERR | POLLHUP | POLLNVAL, 0 }\n };\n\n int res = poll(events, 1, 500 \/* 500ms max timeout *\/);\n if (res == 1 && events[0].revents == POLLOUT) {\n \/\/ Ready to send\n continue; \/\/ we can now send it\n }\n else if (res == -1) {\n \/\/ error in epoll call\n int saved_errno = errno;\n cerr << \"error on epoll with CarbonConnector \" << addr\n << \": \" << strerror(saved_errno) << endl;\n }\n else if (res == 0) {\n \/\/ nothing ready... must be a timeout\n cerr << \"timeout sending to CarbonConnector at \" << addr\n << endl;\n }\n else if (res == 1 && events[0].revents & ~POLLOUT) {\n \/\/ Disconnection or error... need to reconnect\n cerr << \"disconnection sending to CarbonConnector at \" << addr\n << endl;\n }\n else {\n \/\/ Logic error; we should never get here\n throw ML::Exception(\"logic error in carbon connector\");\n }\n } else {\n \/\/ Error in sending\n int saved_errno = errno;\n cerr << \"error sending to CarbonConnector \" << addr\n << \": \" << strerror(saved_errno) << endl;\n }\n break;\n } \n\n reconnect();\n}\n\nvoid\nCarbonConnector::Connection::\nreconnect()\n{\n close();\n\n cerr << \"reconnecting to \" << addr << endl;\n\n if (reconnectionThreadJoinable && reconnectionThread) {\n reconnectionThread->join();\n reconnectionThread.reset();\n }\n\n reconnectionThreadActive = false;\n reconnectionThreadJoinable = false;\n \n reconnectionThread\n = std::make_shared\n (std::bind(&Connection::runReconnectionThread, this));\n\n}\n\nvoid\nCarbonConnector::Connection::\nrunReconnectionThread()\n{\n cerr << \"started reconnection thread\" << endl;\n\n reconnectionThreadActive = true;\n\n \/\/ Close the current connection\n if (fd != -1)\n close();\n\n double meanWaitTime = 0.5; \/\/ half a second\n\n while (!shutdown) {\n string error = connect();\n if (fd != -1) break;\n\n cerr << \"error reconnecting to \" << addr << \": \" << error\n << endl;\n\n double r = (random() % 10001) \/ 10000.0;\n double waitTime = meanWaitTime * (0.5 + r);\n\n if (meanWaitTime < 8.0)\n meanWaitTime *= 2;\n \n \/\/ Wait for the given time before we attempt reconnection\n \/\/ again.\n futex_wait(shutdown, 0, waitTime);\n }\n\n reconnectionThreadActive = false;\n reconnectionThreadJoinable = true;\n}\n\n} \/\/ namespace Datacratic\nFixed drift and timestamps in periodic carbon dumps.\/* carbon_connector.cc\n Jeremy Barnes, 3 August 2011\n Copyright (c) 2011 Datacratic. All rights reserved.\n\n*\/\n\n#include \"soa\/service\/carbon_connector.h\"\n#include \"ace\/INET_Addr.h\"\n#include \"jml\/arch\/exception.h\"\n#include \"jml\/arch\/format.h\"\n#include \n#include \"jml\/arch\/cmp_xchg.h\"\n#include \"jml\/arch\/atomic_ops.h\"\n#include \"jml\/arch\/timers.h\"\n#include \"jml\/arch\/futex.h\"\n#include \"jml\/utils\/floating_point.h\"\n#include \"jml\/utils\/smart_ptr_utils.h\"\n#include \"jml\/utils\/exc_assert.h\"\n#include \n#include \n#include \n#include \n\n\nusing namespace std;\nusing namespace ML;\n\n\nnamespace Datacratic {\n\n\n\/*****************************************************************************\/\n\/* MULTI AGGREGATOR *\/\n\/*****************************************************************************\/\n\nMultiAggregator::\nMultiAggregator()\n : doShutdown(false), doDump(false), dumpInterval(0.0)\n{\n}\n\nMultiAggregator::\nMultiAggregator(const std::string & path,\n const OutputFn & output,\n double dumpInterval,\n std::function onStop)\n : doShutdown(false), doDump(false)\n{\n open(path, output, dumpInterval, onStop);\n}\n\nMultiAggregator::\n~MultiAggregator()\n{\n shutdown();\n}\n\nvoid\nMultiAggregator::\nopen(const std::string & path,\n const OutputFn & output,\n double dumpInterval,\n std::function onStop)\n{\n shutdown();\n\n doShutdown = doDump = false;\n if (dumpInterval < 1.0) {\n dumpInterval = 1.0;\n }\n this->dumpInterval = dumpInterval;\n this->onStop = onStop;\n\n if (path == \"\") prefix = \"\";\n else prefix = path + \".\";\n\n if (output)\n outputFn = output;\n else\n outputFn = [&] (const std::vector & values)\n {\n this->doStat(values);\n };\n\n dumpingThread.reset\n (new std::thread(std::bind(&MultiAggregator::runDumpingThread,\n this)));\n}\n\nvoid\nMultiAggregator::\nstop()\n{\n shutdown();\n}\n\nvoid\nMultiAggregator::\ndoStat(const std::vector & values) const\n{\n outputFn(values);\n}\n\nStatAggregator * createNewCounter()\n{\n return new CounterAggregator();\n}\n\nStatAggregator * createNewStableLevel()\n{\n return new GaugeAggregator(GaugeAggregator::StableLevel);\n}\n\nStatAggregator * createNewLevel()\n{\n return new GaugeAggregator(GaugeAggregator::Level);\n}\n\nStatAggregator * createNewOutcome()\n{\n return new GaugeAggregator(GaugeAggregator::Outcome);\n}\n\nvoid\nMultiAggregator::\nrecord(const std::string & stat,\n EventType type,\n float value)\n{\n switch (type) {\n case ET_HIT: recordHit(stat); break;\n case ET_COUNT: recordCount(stat, value); break;\n case ET_STABLE_LEVEL: recordStableLevel(stat, value); break;\n case ET_LEVEL: recordLevel(stat, value); break;\n case ET_OUTCOME: recordOutcome(stat, value); break;\n default:\n cerr << \"warning: unknown stat type\" << endl;\n }\n}\n\nvoid\nMultiAggregator::\nrecordHit(const std::string & stat)\n{\n getAggregator(stat, createNewCounter).record(1.0);\n}\n\nvoid\nMultiAggregator::\nrecordCount(const std::string & stat, float quantity)\n{\n getAggregator(stat, createNewCounter).record(quantity);\n}\n\nvoid\nMultiAggregator::\nrecordStableLevel(const std::string & stat, float value)\n{\n getAggregator(stat, createNewStableLevel).record(value);\n}\n\nvoid\nMultiAggregator::\nrecordLevel(const std::string & stat, float value)\n{\n getAggregator(stat, createNewLevel).record(value);\n}\n \nvoid\nMultiAggregator::\nrecordOutcome(const std::string & stat, float value)\n{\n getAggregator(stat, createNewOutcome).record(value);\n}\n\n\nvoid\nMultiAggregator::\ndump()\n{\n {\n std::lock_guard lock(m);\n doDump = true;\n }\n \n cond.notify_all();\n}\n\nvoid\nMultiAggregator::\ndumpSync(std::ostream & stream) const\n{\n std::unique_lock guard(this->lock);\n\n for (auto & s: stats) {\n auto vals = s.second->read(s.first);\n for (auto v: vals) {\n stream << v.name << \":\\t\" << v.value << endl;\n }\n }\n}\n\nvoid\nMultiAggregator::\nshutdown()\n{\n if (dumpingThread) {\n if (onPreShutdown) onPreShutdown();\n \n {\n std::lock_guard lock(m);\n doShutdown = true;\n }\n\n cond.notify_all();\n \n dumpingThread->join();\n dumpingThread.reset();\n\n if (onPostShutdown) onPostShutdown();\n\n if (onStop) onStop();\n }\n}\n\nStatAggregator &\nMultiAggregator::\ngetAggregator(const std::string & stat,\n StatAggregator * (*createFn) ())\n{\n if (!lookupCache.get())\n lookupCache.reset(new LookupCache());\n\n auto found = lookupCache->find(stat);\n if (found != lookupCache->end())\n return *found->second->second;\n\n \/\/ Get the read lock to look for the aggregator\n std::unique_lock guard(lock);\n\n auto found2 = stats.find(stat);\n\n if (found2 != stats.end()) {\n guard.unlock();\n\n (*lookupCache)[stat] = found2;\n\n return *found2->second;\n }\n \n guard.unlock();\n\n \/\/ Get the write lock to add it to the aggregator\n std::unique_lock guard2(lock);\n\n \/\/ Add it in\n found2 = stats.insert(make_pair(stat, std::shared_ptr(createFn()))).first;\n\n guard2.unlock();\n (*lookupCache)[stat] = found2;\n return *found2->second;\n}\n\nvoid\nMultiAggregator::\nrunDumpingThread()\n{\n size_t current = 0;\n Date nextWakeup = Date::now();\n\n for (;;) {\n std::unique_lock lock(m);\n\n nextWakeup.addSeconds(1.0);\n if (cond.wait_until(lock, nextWakeup.toStd(), [&] { return doShutdown.load(); }))\n break;\n\n \/\/ Get the read lock to extract a list of stats to dump\n vector toDump;\n {\n std::unique_lock guard(this->lock);\n toDump.reserve(stats.size());\n for (auto it = stats.begin(), end = stats.end(); it != end; ++it)\n toDump.push_back(it);\n }\n\n ++current;\n bool dumpNow = doDump.exchange(false) ||\n (current % static_cast(dumpInterval)) == 0;\n\n \/\/ Now dump them without the lock held. Note that we still need to call\n \/\/ read every second even if we're not flushing to carbon.\n for (auto it = toDump.begin(), end = toDump.end(); it != end; ++it) {\n\n try {\n auto stat = (*it)->second->read((*it)->first);\n\n \/\/ Hack: ensures that all timestamps are consistent and that we\n \/\/ will not have any gaps within carbon.\n for (auto& s : stat) s.timestamp = nextWakeup;\n\n if (dumpNow) doStat(std::move(stat));\n } catch (const std::exception & exc) {\n cerr << \"error writing stat: \" << exc.what() << endl;\n }\n }\n }\n}\n\n\n\/*****************************************************************************\/\n\/* CARBON CONNECTOR *\/\n\/*****************************************************************************\/\n\nCarbonConnector::\nCarbonConnector()\n{\n}\n\nCarbonConnector::\nCarbonConnector(const std::string & carbonAddr,\n const std::string & path,\n double dumpInterval,\n std::function onStop)\n{\n open(carbonAddr, path, dumpInterval, onStop);\n}\n\nCarbonConnector::\nCarbonConnector(const std::vector & carbonAddrs,\n const std::string & path,\n double dumpInterval,\n std::function onStop)\n{\n open(carbonAddrs, path,dumpInterval, onStop);\n}\n\nCarbonConnector::\n~CarbonConnector()\n{\n doShutdown();\n}\n\nvoid\nCarbonConnector::\nopen(const std::string & carbonAddr,\n const std::string & path,\n double dumpInterval,\n std::function onStop)\n{\n return open(vector({carbonAddr}), path, dumpInterval, onStop);\n}\n\nvoid\nCarbonConnector::\nopen(const std::vector & carbonAddrs,\n const std::string & path,\n double dumpInterval,\n std::function onStop)\n{\n stop();\n\n int numConnections = 0;\n\n connections.clear();\n for (unsigned i = 0; i < carbonAddrs.size(); ++i) {\n connections.push_back(std::make_shared\n (carbonAddrs[i]));\n string error = connections.back()->connect();\n if (connections.back()->fd == -1) {\n cerr << \"error connecting to Carbon at \" << carbonAddrs[i]\n << \": \" << error << endl;\n }\n else ++numConnections;\n }\n\n if (numConnections == 0)\n throw ML::Exception(\"unable to connect to any Carbon instances\");\n\n this->onPostShutdown = std::bind(&CarbonConnector::doShutdown, this);\n\n MultiAggregator::open(path, OutputFn(), dumpInterval, onStop);\n}\n\nvoid\nCarbonConnector::\ndoShutdown()\n{\n stop();\n connections.clear();\n}\n\nvoid\nCarbonConnector::\ndoStat(const std::vector & values) const\n{\n if (connections.empty())\n return;\n\n std::string message;\n\n for (unsigned i = 0; i < values.size(); ++i) {\n message += ML::format(\"%s%s %.5f %lld\\n\",\n prefix.c_str(), values[i].name.c_str(),\n values[i].value,\n (unsigned long long)\n values[i].timestamp.secondsSinceEpoch());\n }\n\n for (unsigned i = 0; i < connections.size(); ++i)\n connections[i]->send(message);\n}\n\nCarbonConnector::Connection::\n~Connection()\n{\n close();\n\n if (reconnectionThread) {\n shutdown = 1;\n futex_wake(shutdown);\n reconnectionThread->join();\n reconnectionThread.reset();\n }\n}\n\nvoid\nCarbonConnector::Connection::\nclose()\n{\n if (fd != -1)\n ::close(fd);\n fd = -1;\n}\n\nstd::string\nCarbonConnector::Connection::\nconnect()\n{\n if (fd != -1)\n throw ML::Exception(\"error connecting\");\n\n ip = ACE_INET_Addr(addr.c_str());\n\n cerr << \"connecting to Carbon at \"\n << ip.get_host_addr() << \":\" << ip.get_port_number()\n << \" (\" << ip.get_host_name() << \")\" << endl;\n\n int tmpFd = socket(AF_INET, SOCK_STREAM, 0);\n int res = ::connect(tmpFd,\n (sockaddr *)ip.get_addr(),\n ip.get_addr_size());\n \n int saved_errno = errno;\n\n if (res == -1) {\n ::close(tmpFd);\n return ML::format(\"connect to carbon at %s:%d (%s): %s\",\n ip.get_host_addr(),\n ip.get_port_number(),\n ip.get_host_name(),\n strerror(saved_errno));\n }\n\n fd = tmpFd;\n\n return \"\";\n}\n\nvoid\nCarbonConnector::Connection::\nsend(const std::string & message)\n{\n \/\/cerr << \"STAT: \" << message << endl;\n \/\/return;\n if (message.empty())\n return;\n\n \/\/cerr << \"sending to \" << addr << \" on \" << fd << \" \" << message << endl;\n\n if (fd == -1) {\n if (reconnectionThreadActive) return;\n throw ML::Exception(\"send with fd -1 and no thread active\");\n }\n \n size_t done = 0;\n\n for (;;) {\n int sendRes = ::send(fd, message.c_str() + done,\n message.size() - done,\n MSG_DONTWAIT | MSG_NOSIGNAL);\n \n if (sendRes > 0) {\n done += sendRes;\n if (done == message.size())\n return; \/\/ done; normal case\n else if (done > message.size())\n throw ML::Exception(\"logic error sending message to Carbon\");\n else continue; \/\/ do the rest of the message\n }\n \n if (sendRes != -1)\n throw ML::Exception(\"invalid return code from send\");\n \n \/\/ Error handling\n if (errno == EINTR)\n continue; \/\/ retry\n else if (errno == EAGAIN || errno == EWOULDBLOCK) {\n \/\/ Would block (something that we don't want). Select on the\n \/\/ socket for the timeout before giving up.\n struct pollfd events[] = {\n { fd, POLLOUT | POLLERR | POLLHUP | POLLNVAL, 0 }\n };\n\n int res = poll(events, 1, 500 \/* 500ms max timeout *\/);\n if (res == 1 && events[0].revents == POLLOUT) {\n \/\/ Ready to send\n continue; \/\/ we can now send it\n }\n else if (res == -1) {\n \/\/ error in epoll call\n int saved_errno = errno;\n cerr << \"error on epoll with CarbonConnector \" << addr\n << \": \" << strerror(saved_errno) << endl;\n }\n else if (res == 0) {\n \/\/ nothing ready... must be a timeout\n cerr << \"timeout sending to CarbonConnector at \" << addr\n << endl;\n }\n else if (res == 1 && events[0].revents & ~POLLOUT) {\n \/\/ Disconnection or error... need to reconnect\n cerr << \"disconnection sending to CarbonConnector at \" << addr\n << endl;\n }\n else {\n \/\/ Logic error; we should never get here\n throw ML::Exception(\"logic error in carbon connector\");\n }\n } else {\n \/\/ Error in sending\n int saved_errno = errno;\n cerr << \"error sending to CarbonConnector \" << addr\n << \": \" << strerror(saved_errno) << endl;\n }\n break;\n } \n\n reconnect();\n}\n\nvoid\nCarbonConnector::Connection::\nreconnect()\n{\n close();\n\n cerr << \"reconnecting to \" << addr << endl;\n\n if (reconnectionThreadJoinable && reconnectionThread) {\n reconnectionThread->join();\n reconnectionThread.reset();\n }\n\n reconnectionThreadActive = false;\n reconnectionThreadJoinable = false;\n \n reconnectionThread\n = std::make_shared\n (std::bind(&Connection::runReconnectionThread, this));\n\n}\n\nvoid\nCarbonConnector::Connection::\nrunReconnectionThread()\n{\n cerr << \"started reconnection thread\" << endl;\n\n reconnectionThreadActive = true;\n\n \/\/ Close the current connection\n if (fd != -1)\n close();\n\n double meanWaitTime = 0.5; \/\/ half a second\n\n while (!shutdown) {\n string error = connect();\n if (fd != -1) break;\n\n cerr << \"error reconnecting to \" << addr << \": \" << error\n << endl;\n\n double r = (random() % 10001) \/ 10000.0;\n double waitTime = meanWaitTime * (0.5 + r);\n\n if (meanWaitTime < 8.0)\n meanWaitTime *= 2;\n \n \/\/ Wait for the given time before we attempt reconnection\n \/\/ again.\n futex_wait(shutdown, 0, waitTime);\n }\n\n reconnectionThreadActive = false;\n reconnectionThreadJoinable = true;\n}\n\n} \/\/ namespace Datacratic\n<|endoftext|>"} {"text":"#include \"include\/buffer.h\"\n#include \"include\/encoding.h\"\n\n#include \"gtest\/gtest.h\"\n#include \"stdlib.h\"\n\n#define MAX_TEST 1000000\n\n\nTEST(BufferList, EmptyAppend) {\n bufferlist bl;\n bufferptr ptr;\n bl.push_back(ptr);\n ASSERT_EQ(bl.begin().end(), 1);\n}\n\nTEST(BufferList, TestPtrAppend) {\n bufferlist bl;\n char correct[MAX_TEST];\n int curpos = 0;\n int length = random() % 5 > 0 ? random() % 1000 : 0;\n while (curpos + length < MAX_TEST) {\n if (!length) {\n bufferptr ptr;\n bl.push_back(ptr);\n } else {\n char *current = correct + curpos;\n for (int i = 0; i < length; ++i) {\n char next = random() % 255;\n correct[curpos++] = next;\n }\n bufferptr ptr(current, length);\n bl.append(ptr);\n }\n length = random() % 5 > 0 ? random() % 1000 : 0;\n }\n ASSERT_EQ(memcmp(bl.c_str(), correct, curpos), 0);\n}\n\nTEST(BufferList, TestDirectAppend) {\n bufferlist bl;\n char correct[MAX_TEST];\n int curpos = 0;\n int length = random() % 5 > 0 ? random() % 1000 : 0;\n while (curpos + length < MAX_TEST) {\n char *current = correct + curpos;\n for (int i = 0; i < length; ++i) {\n char next = random() % 255;\n correct[curpos++] = next;\n }\n bl.append(current, length);\n length = random() % 5 > 0 ? random() % 1000 : 0;\n }\n ASSERT_EQ(memcmp(bl.c_str(), correct, curpos), 0);\n}\ntest\/bufferlist: add copy_all test#include \"include\/buffer.h\"\n#include \"include\/encoding.h\"\n\n#include \"gtest\/gtest.h\"\n#include \"stdlib.h\"\n\n#define MAX_TEST 1000000\n\n\nTEST(BufferList, EmptyAppend) {\n bufferlist bl;\n bufferptr ptr;\n bl.push_back(ptr);\n ASSERT_EQ(bl.begin().end(), 1);\n}\n\nTEST(BufferList, TestPtrAppend) {\n bufferlist bl;\n char correct[MAX_TEST];\n int curpos = 0;\n int length = random() % 5 > 0 ? random() % 1000 : 0;\n while (curpos + length < MAX_TEST) {\n if (!length) {\n bufferptr ptr;\n bl.push_back(ptr);\n } else {\n char *current = correct + curpos;\n for (int i = 0; i < length; ++i) {\n char next = random() % 255;\n correct[curpos++] = next;\n }\n bufferptr ptr(current, length);\n bl.append(ptr);\n }\n length = random() % 5 > 0 ? random() % 1000 : 0;\n }\n ASSERT_EQ(memcmp(bl.c_str(), correct, curpos), 0);\n}\n\nTEST(BufferList, TestDirectAppend) {\n bufferlist bl;\n char correct[MAX_TEST];\n int curpos = 0;\n int length = random() % 5 > 0 ? random() % 1000 : 0;\n while (curpos + length < MAX_TEST) {\n char *current = correct + curpos;\n for (int i = 0; i < length; ++i) {\n char next = random() % 255;\n correct[curpos++] = next;\n }\n bl.append(current, length);\n length = random() % 5 > 0 ? random() % 1000 : 0;\n }\n ASSERT_EQ(memcmp(bl.c_str(), correct, curpos), 0);\n}\n\nTEST(BufferList, TestCopyAll) {\n const static size_t BIG_SZ = 10737414;\n unsigned char big[BIG_SZ];\n unsigned char c = 0;\n for (size_t i = 0; i < BIG_SZ; ++i) {\n big[i] = c++;\n }\n bufferlist bl;\n bl.append((const char*)big, BIG_SZ);\n bufferlist::iterator i = bl.begin();\n bufferlist bl2;\n i.copy_all(bl2);\n ASSERT_EQ(bl2.length(), BIG_SZ);\n unsigned char big2[BIG_SZ];\n bl2.copy(0, BIG_SZ, (char*)big2);\n ASSERT_EQ(memcmp(big, big2, BIG_SZ), 0);\n}\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2012-2016 The Bitcoin Core developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \"addrman.h\"\n#include \"chainparams.h\"\n#include \"hash.h\"\n#include \"net.h\"\n#include \"netbase.h\"\n#include \"serialize.h\"\n#include \"streams.h\"\n\n#include \n\n#include \"test\/test_pivx.h\"\n\n#include \n\n#include \n\nclass CAddrManSerializationMock : public CAddrMan\n{\npublic:\n virtual void Serialize(CDataStream::CBaseDataStream& s) const = 0;\n\n \/\/! Ensure that bucket placement is always the same for testing purposes.\n void MakeDeterministic()\n {\n nKey.SetNull();\n SeedInsecureRand(true);\n }\n};\n\nclass CAddrManUncorrupted : public CAddrManSerializationMock\n{\npublic:\n void Serialize(CDataStream::CBaseDataStream& s) const\n {\n CAddrMan::Serialize(s);\n }\n};\n\nclass CAddrManCorrupted : public CAddrManSerializationMock\n{\npublic:\n void Serialize(CDataStream::CBaseDataStream& s) const\n {\n \/\/ Produces corrupt output that claims addrman has 20 addrs when it only has one addr.\n unsigned char nVersion = 1;\n s << nVersion;\n s << ((unsigned char)32);\n s << nKey;\n s << 10; \/\/ nNew\n s << 10; \/\/ nTried\n\n int nUBuckets = ADDRMAN_NEW_BUCKET_COUNT ^ (1 << 30);\n s << nUBuckets;\n\n CService serv;\n Lookup(\"252.1.1.1\", serv, 7777, false);\n CAddress addr = CAddress(serv, NODE_NONE);\n CNetAddr resolved;\n LookupHost(\"252.2.2.2\", resolved, false);\n CAddrInfo info = CAddrInfo(addr, resolved);\n s << info;\n }\n};\n\nCDataStream AddrmanToStream(CAddrManSerializationMock& addrman)\n{\n CDataStream ssPeersIn(SER_DISK, CLIENT_VERSION);\n ssPeersIn << Params().MessageStart();\n ssPeersIn << addrman;\n std::string str = ssPeersIn.str();\n std::vector vchData(str.begin(), str.end());\n return CDataStream(vchData, SER_DISK, CLIENT_VERSION);\n}\n\nBOOST_FIXTURE_TEST_SUITE(net_tests, BasicTestingSetup)\n\nBOOST_AUTO_TEST_CASE(cnode_listen_port)\n{\n \/\/ test default\n uint16_t port = GetListenPort();\n BOOST_CHECK(port == Params().GetDefaultPort());\n \/\/ test set port\n uint16_t altPort = 12345;\n BOOST_CHECK(gArgs.SoftSetArg(\"-port\", std::to_string(altPort)));\n port = GetListenPort();\n BOOST_CHECK(port == altPort);\n}\n\nBOOST_AUTO_TEST_CASE(caddrdb_read)\n{\n CAddrManUncorrupted addrmanUncorrupted;\n addrmanUncorrupted.MakeDeterministic();\n\n CService addr1, addr2, addr3;\n BOOST_CHECK(Lookup(\"250.7.1.1\", addr1, 8333, false));\n BOOST_CHECK(Lookup(\"250.7.2.2\", addr2, 9999, false));\n BOOST_CHECK(Lookup(\"250.7.3.3\", addr3, 9999, false));\n BOOST_CHECK(Lookup(std::string(\"250.7.3.3\", 9), addr3, 9999, false));\n BOOST_CHECK(!Lookup(std::string(\"250.7.3.3\\0example.com\", 21), addr3, 9999, false));\n\n \/\/ Add three addresses to new table.\n CService source;\n Lookup(\"252.5.1.1\", source, 8333, false);\n addrmanUncorrupted.Add(CAddress(addr1, NODE_NONE), source);\n addrmanUncorrupted.Add(CAddress(addr2, NODE_NONE), source);\n addrmanUncorrupted.Add(CAddress(addr3, NODE_NONE), source);\n\n \/\/ Test that the de-serialization does not throw an exception.\n CDataStream ssPeers1 = AddrmanToStream(addrmanUncorrupted);\n bool exceptionThrown = false;\n CAddrMan addrman1;\n\n BOOST_CHECK(addrman1.size() == 0);\n try {\n unsigned char pchMsgTmp[4];\n ssPeers1 >> pchMsgTmp;\n ssPeers1 >> addrman1;\n } catch (const std::exception& e) {\n exceptionThrown = true;\n }\n\n BOOST_CHECK(addrman1.size() == 3);\n BOOST_CHECK(exceptionThrown == false);\n\n \/\/ Test that CAddrDB::Read creates an addrman with the correct number of addrs.\n CDataStream ssPeers2 = AddrmanToStream(addrmanUncorrupted);\n\n CAddrMan addrman2;\n CAddrDB adb;\n BOOST_CHECK(addrman2.size() == 0);\n adb.Read(addrman2, ssPeers2);\n BOOST_CHECK(addrman2.size() == 3);\n}\n\n\nBOOST_AUTO_TEST_CASE(caddrdb_read_corrupted)\n{\n CAddrManCorrupted addrmanCorrupted;\n addrmanCorrupted.MakeDeterministic();\n\n \/\/ Test that the de-serialization of corrupted addrman throws an exception.\n CDataStream ssPeers1 = AddrmanToStream(addrmanCorrupted);\n bool exceptionThrown = false;\n CAddrMan addrman1;\n BOOST_CHECK(addrman1.size() == 0);\n try {\n unsigned char pchMsgTmp[4];\n ssPeers1 >> pchMsgTmp;\n ssPeers1 >> addrman1;\n } catch (const std::exception& e) {\n exceptionThrown = true;\n }\n \/\/ Even through de-serialization failed addrman is not left in a clean state.\n BOOST_CHECK(addrman1.size() == 1);\n BOOST_CHECK(exceptionThrown);\n\n \/\/ Test that CAddrDB::Read leaves addrman in a clean state if de-serialization fails.\n CDataStream ssPeers2 = AddrmanToStream(addrmanCorrupted);\n\n CAddrMan addrman2;\n CAddrDB adb;\n BOOST_CHECK(addrman2.size() == 0);\n adb.Read(addrman2, ssPeers2);\n BOOST_CHECK(addrman2.size() == 0);\n}\n\nBOOST_AUTO_TEST_CASE(cnode_simple_test)\n{\n SOCKET hSocket = INVALID_SOCKET;\n NodeId id = 0;\n int height = 0;\n\n in_addr ipv4Addr;\n ipv4Addr.s_addr = 0xa0b0c001;\n\n CAddress addr = CAddress(CService(ipv4Addr, 7777), NODE_NETWORK);\n std::string pszDest = \"\";\n bool fInboundIn = false;\n\n \/\/ Test that fFeeler is false by default.\n std::unique_ptr pnode1(new CNode(id++, NODE_NETWORK, height, hSocket, addr, 0, 0, pszDest, fInboundIn));\n BOOST_CHECK(pnode1->fInbound == false);\n BOOST_CHECK(pnode1->fFeeler == false);\n\n fInboundIn = true;\n std::unique_ptr pnode2(new CNode(id++, NODE_NETWORK, height, hSocket, addr, 1, 1, pszDest, fInboundIn));\n BOOST_CHECK(pnode2->fInbound == true);\n BOOST_CHECK(pnode2->fFeeler == false);\n}\n\n\/\/ prior to PR #14728, this test triggers an undefined behavior\nBOOST_AUTO_TEST_CASE(ipv4_peer_with_ipv6_addrMe_test)\n{\n \/\/ set up local addresses; all that's necessary to reproduce the bug is\n \/\/ that a normal IPv4 address is among the entries, but if this address is\n \/\/ !IsRoutable the undefined behavior is easier to trigger deterministically\n {\n LOCK(cs_mapLocalHost);\n in_addr ipv4AddrLocal;\n ipv4AddrLocal.s_addr = 0x0100007f;\n CNetAddr addr = CNetAddr(ipv4AddrLocal);\n LocalServiceInfo lsi;\n lsi.nScore = 23;\n lsi.nPort = 42;\n mapLocalHost[addr] = lsi;\n }\n\n \/\/ create a peer with an IPv4 address\n in_addr ipv4AddrPeer;\n ipv4AddrPeer.s_addr = 0xa0b0c001;\n CAddress addr = CAddress(CService(ipv4AddrPeer, 7777), NODE_NETWORK);\n std::unique_ptr pnode = std::make_unique(0, NODE_NETWORK, 0, INVALID_SOCKET, addr, 0, 0, std::string{}, false);\n pnode->fSuccessfullyConnected.store(true);\n\n \/\/ the peer claims to be reaching us via IPv6\n in6_addr ipv6AddrLocal;\n memset(ipv6AddrLocal.s6_addr, 0, 16);\n ipv6AddrLocal.s6_addr[0] = 0xcc;\n CAddress addrLocal = CAddress(CService(ipv6AddrLocal, 7777), NODE_NETWORK);\n pnode->SetAddrLocal(addrLocal);\n\n \/\/ before patch, this causes undefined behavior detectable with clang's -fsanitize=memory\n AdvertiseLocal(&*pnode);\n\n \/\/ suppress no-checks-run warning; if this test fails, it's by triggering a sanitizer\n BOOST_CHECK(1);\n}\n\n\nBOOST_AUTO_TEST_CASE(LimitedAndReachable_Network)\n{\n BOOST_CHECK_EQUAL(IsReachable(NET_IPV4), true);\n BOOST_CHECK_EQUAL(IsReachable(NET_IPV6), true);\n BOOST_CHECK_EQUAL(IsReachable(NET_ONION), true);\n\n SetReachable(NET_IPV4, false);\n SetReachable(NET_IPV6, false);\n SetReachable(NET_ONION, false);\n\n BOOST_CHECK_EQUAL(IsReachable(NET_IPV4), false);\n BOOST_CHECK_EQUAL(IsReachable(NET_IPV6), false);\n BOOST_CHECK_EQUAL(IsReachable(NET_ONION), false);\n\n SetReachable(NET_IPV4, true);\n SetReachable(NET_IPV6, true);\n SetReachable(NET_ONION, true);\n\n BOOST_CHECK_EQUAL(IsReachable(NET_IPV4), true);\n BOOST_CHECK_EQUAL(IsReachable(NET_IPV6), true);\n BOOST_CHECK_EQUAL(IsReachable(NET_ONION), true);\n}\n\nBOOST_AUTO_TEST_CASE(LimitedAndReachable_NetworkCaseUnroutableAndInternal)\n{\n BOOST_CHECK_EQUAL(IsReachable(NET_UNROUTABLE), true);\n BOOST_CHECK_EQUAL(IsReachable(NET_INTERNAL), true);\n\n SetReachable(NET_UNROUTABLE, false);\n SetReachable(NET_INTERNAL, false);\n\n BOOST_CHECK_EQUAL(IsReachable(NET_UNROUTABLE), true); \/\/ Ignored for both networks\n BOOST_CHECK_EQUAL(IsReachable(NET_INTERNAL), true);\n}\n\nCNetAddr UtilBuildAddress(unsigned char p1, unsigned char p2, unsigned char p3, unsigned char p4)\n{\n unsigned char ip[] = {p1, p2, p3, p4};\n\n struct sockaddr_in sa;\n memset(&sa, 0, sizeof(sockaddr_in)); \/\/ initialize the memory block\n memcpy(&(sa.sin_addr), &ip, sizeof(ip));\n return CNetAddr(sa.sin_addr);\n}\n\n\nBOOST_AUTO_TEST_CASE(LimitedAndReachable_CNetAddr)\n{\n CNetAddr addr = UtilBuildAddress(0x001, 0x001, 0x001, 0x001); \/\/ 1.1.1.1\n\n SetReachable(NET_IPV4, true);\n BOOST_CHECK_EQUAL(IsReachable(addr), true);\n\n SetReachable(NET_IPV4, false);\n BOOST_CHECK_EQUAL(IsReachable(addr), false);\n\n SetReachable(NET_IPV4, true); \/\/ have to reset this, because this is stateful.\n}\n\n\nBOOST_AUTO_TEST_CASE(LocalAddress_BasicLifecycle)\n{\n CService addr = CService(UtilBuildAddress(0x002, 0x001, 0x001, 0x001), 1000); \/\/ 2.1.1.1:1000\n\n SetReachable(NET_IPV4, true);\n\n BOOST_CHECK_EQUAL(IsLocal(addr), false);\n BOOST_CHECK_EQUAL(AddLocal(addr, 1000), true);\n BOOST_CHECK_EQUAL(IsLocal(addr), true);\n\n RemoveLocal(addr);\n BOOST_CHECK_EQUAL(IsLocal(addr), false);\n}\n\nBOOST_AUTO_TEST_CASE(PoissonNextSend)\n{\n g_mock_deterministic_tests = true;\n\n int64_t now = 5000;\n int average_interval_seconds = 600;\n\n auto poisson = ::PoissonNextSend(now, average_interval_seconds);\n std::chrono::microseconds poisson_chrono = ::PoissonNextSend(std::chrono::microseconds{now}, std::chrono::seconds{average_interval_seconds});\n\n BOOST_CHECK_EQUAL(poisson, poisson_chrono.count());\n\n g_mock_deterministic_tests = false;\n}\n\nBOOST_AUTO_TEST_SUITE_END()\ntest: Do not instantiate CAddrDB for static call\/\/ Copyright (c) 2012-2016 The Bitcoin Core developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \"addrman.h\"\n#include \"chainparams.h\"\n#include \"hash.h\"\n#include \"net.h\"\n#include \"netbase.h\"\n#include \"serialize.h\"\n#include \"streams.h\"\n\n#include \n\n#include \"test\/test_pivx.h\"\n\n#include \n\n#include \n\nclass CAddrManSerializationMock : public CAddrMan\n{\npublic:\n virtual void Serialize(CDataStream::CBaseDataStream& s) const = 0;\n\n \/\/! Ensure that bucket placement is always the same for testing purposes.\n void MakeDeterministic()\n {\n nKey.SetNull();\n SeedInsecureRand(true);\n }\n};\n\nclass CAddrManUncorrupted : public CAddrManSerializationMock\n{\npublic:\n void Serialize(CDataStream::CBaseDataStream& s) const\n {\n CAddrMan::Serialize(s);\n }\n};\n\nclass CAddrManCorrupted : public CAddrManSerializationMock\n{\npublic:\n void Serialize(CDataStream::CBaseDataStream& s) const\n {\n \/\/ Produces corrupt output that claims addrman has 20 addrs when it only has one addr.\n unsigned char nVersion = 1;\n s << nVersion;\n s << ((unsigned char)32);\n s << nKey;\n s << 10; \/\/ nNew\n s << 10; \/\/ nTried\n\n int nUBuckets = ADDRMAN_NEW_BUCKET_COUNT ^ (1 << 30);\n s << nUBuckets;\n\n CService serv;\n Lookup(\"252.1.1.1\", serv, 7777, false);\n CAddress addr = CAddress(serv, NODE_NONE);\n CNetAddr resolved;\n LookupHost(\"252.2.2.2\", resolved, false);\n CAddrInfo info = CAddrInfo(addr, resolved);\n s << info;\n }\n};\n\nCDataStream AddrmanToStream(CAddrManSerializationMock& addrman)\n{\n CDataStream ssPeersIn(SER_DISK, CLIENT_VERSION);\n ssPeersIn << Params().MessageStart();\n ssPeersIn << addrman;\n std::string str = ssPeersIn.str();\n std::vector vchData(str.begin(), str.end());\n return CDataStream(vchData, SER_DISK, CLIENT_VERSION);\n}\n\nBOOST_FIXTURE_TEST_SUITE(net_tests, BasicTestingSetup)\n\nBOOST_AUTO_TEST_CASE(cnode_listen_port)\n{\n \/\/ test default\n uint16_t port = GetListenPort();\n BOOST_CHECK(port == Params().GetDefaultPort());\n \/\/ test set port\n uint16_t altPort = 12345;\n BOOST_CHECK(gArgs.SoftSetArg(\"-port\", std::to_string(altPort)));\n port = GetListenPort();\n BOOST_CHECK(port == altPort);\n}\n\nBOOST_AUTO_TEST_CASE(caddrdb_read)\n{\n CAddrManUncorrupted addrmanUncorrupted;\n addrmanUncorrupted.MakeDeterministic();\n\n CService addr1, addr2, addr3;\n BOOST_CHECK(Lookup(\"250.7.1.1\", addr1, 8333, false));\n BOOST_CHECK(Lookup(\"250.7.2.2\", addr2, 9999, false));\n BOOST_CHECK(Lookup(\"250.7.3.3\", addr3, 9999, false));\n BOOST_CHECK(Lookup(std::string(\"250.7.3.3\", 9), addr3, 9999, false));\n BOOST_CHECK(!Lookup(std::string(\"250.7.3.3\\0example.com\", 21), addr3, 9999, false));\n\n \/\/ Add three addresses to new table.\n CService source;\n Lookup(\"252.5.1.1\", source, 8333, false);\n addrmanUncorrupted.Add(CAddress(addr1, NODE_NONE), source);\n addrmanUncorrupted.Add(CAddress(addr2, NODE_NONE), source);\n addrmanUncorrupted.Add(CAddress(addr3, NODE_NONE), source);\n\n \/\/ Test that the de-serialization does not throw an exception.\n CDataStream ssPeers1 = AddrmanToStream(addrmanUncorrupted);\n bool exceptionThrown = false;\n CAddrMan addrman1;\n\n BOOST_CHECK(addrman1.size() == 0);\n try {\n unsigned char pchMsgTmp[4];\n ssPeers1 >> pchMsgTmp;\n ssPeers1 >> addrman1;\n } catch (const std::exception& e) {\n exceptionThrown = true;\n }\n\n BOOST_CHECK(addrman1.size() == 3);\n BOOST_CHECK(exceptionThrown == false);\n\n \/\/ Test that CAddrDB::Read creates an addrman with the correct number of addrs.\n CDataStream ssPeers2 = AddrmanToStream(addrmanUncorrupted);\n\n CAddrMan addrman2;\n BOOST_CHECK(addrman2.size() == 0);\n BOOST_CHECK(CAddrDB::Read(addrman2, ssPeers2));\n BOOST_CHECK(addrman2.size() == 3);\n}\n\n\nBOOST_AUTO_TEST_CASE(caddrdb_read_corrupted)\n{\n CAddrManCorrupted addrmanCorrupted;\n addrmanCorrupted.MakeDeterministic();\n\n \/\/ Test that the de-serialization of corrupted addrman throws an exception.\n CDataStream ssPeers1 = AddrmanToStream(addrmanCorrupted);\n bool exceptionThrown = false;\n CAddrMan addrman1;\n BOOST_CHECK(addrman1.size() == 0);\n try {\n unsigned char pchMsgTmp[4];\n ssPeers1 >> pchMsgTmp;\n ssPeers1 >> addrman1;\n } catch (const std::exception& e) {\n exceptionThrown = true;\n }\n \/\/ Even through de-serialization failed addrman is not left in a clean state.\n BOOST_CHECK(addrman1.size() == 1);\n BOOST_CHECK(exceptionThrown);\n\n \/\/ Test that CAddrDB::Read leaves addrman in a clean state if de-serialization fails.\n CDataStream ssPeers2 = AddrmanToStream(addrmanCorrupted);\n\n CAddrMan addrman2;\n BOOST_CHECK(addrman2.size() == 0);\n BOOST_CHECK(!CAddrDB::Read(addrman2, ssPeers2));\n BOOST_CHECK(addrman2.size() == 0);\n}\n\nBOOST_AUTO_TEST_CASE(cnode_simple_test)\n{\n SOCKET hSocket = INVALID_SOCKET;\n NodeId id = 0;\n int height = 0;\n\n in_addr ipv4Addr;\n ipv4Addr.s_addr = 0xa0b0c001;\n\n CAddress addr = CAddress(CService(ipv4Addr, 7777), NODE_NETWORK);\n std::string pszDest = \"\";\n bool fInboundIn = false;\n\n \/\/ Test that fFeeler is false by default.\n std::unique_ptr pnode1(new CNode(id++, NODE_NETWORK, height, hSocket, addr, 0, 0, pszDest, fInboundIn));\n BOOST_CHECK(pnode1->fInbound == false);\n BOOST_CHECK(pnode1->fFeeler == false);\n\n fInboundIn = true;\n std::unique_ptr pnode2(new CNode(id++, NODE_NETWORK, height, hSocket, addr, 1, 1, pszDest, fInboundIn));\n BOOST_CHECK(pnode2->fInbound == true);\n BOOST_CHECK(pnode2->fFeeler == false);\n}\n\n\/\/ prior to PR #14728, this test triggers an undefined behavior\nBOOST_AUTO_TEST_CASE(ipv4_peer_with_ipv6_addrMe_test)\n{\n \/\/ set up local addresses; all that's necessary to reproduce the bug is\n \/\/ that a normal IPv4 address is among the entries, but if this address is\n \/\/ !IsRoutable the undefined behavior is easier to trigger deterministically\n {\n LOCK(cs_mapLocalHost);\n in_addr ipv4AddrLocal;\n ipv4AddrLocal.s_addr = 0x0100007f;\n CNetAddr addr = CNetAddr(ipv4AddrLocal);\n LocalServiceInfo lsi;\n lsi.nScore = 23;\n lsi.nPort = 42;\n mapLocalHost[addr] = lsi;\n }\n\n \/\/ create a peer with an IPv4 address\n in_addr ipv4AddrPeer;\n ipv4AddrPeer.s_addr = 0xa0b0c001;\n CAddress addr = CAddress(CService(ipv4AddrPeer, 7777), NODE_NETWORK);\n std::unique_ptr pnode = std::make_unique(0, NODE_NETWORK, 0, INVALID_SOCKET, addr, 0, 0, std::string{}, false);\n pnode->fSuccessfullyConnected.store(true);\n\n \/\/ the peer claims to be reaching us via IPv6\n in6_addr ipv6AddrLocal;\n memset(ipv6AddrLocal.s6_addr, 0, 16);\n ipv6AddrLocal.s6_addr[0] = 0xcc;\n CAddress addrLocal = CAddress(CService(ipv6AddrLocal, 7777), NODE_NETWORK);\n pnode->SetAddrLocal(addrLocal);\n\n \/\/ before patch, this causes undefined behavior detectable with clang's -fsanitize=memory\n AdvertiseLocal(&*pnode);\n\n \/\/ suppress no-checks-run warning; if this test fails, it's by triggering a sanitizer\n BOOST_CHECK(1);\n}\n\n\nBOOST_AUTO_TEST_CASE(LimitedAndReachable_Network)\n{\n BOOST_CHECK_EQUAL(IsReachable(NET_IPV4), true);\n BOOST_CHECK_EQUAL(IsReachable(NET_IPV6), true);\n BOOST_CHECK_EQUAL(IsReachable(NET_ONION), true);\n\n SetReachable(NET_IPV4, false);\n SetReachable(NET_IPV6, false);\n SetReachable(NET_ONION, false);\n\n BOOST_CHECK_EQUAL(IsReachable(NET_IPV4), false);\n BOOST_CHECK_EQUAL(IsReachable(NET_IPV6), false);\n BOOST_CHECK_EQUAL(IsReachable(NET_ONION), false);\n\n SetReachable(NET_IPV4, true);\n SetReachable(NET_IPV6, true);\n SetReachable(NET_ONION, true);\n\n BOOST_CHECK_EQUAL(IsReachable(NET_IPV4), true);\n BOOST_CHECK_EQUAL(IsReachable(NET_IPV6), true);\n BOOST_CHECK_EQUAL(IsReachable(NET_ONION), true);\n}\n\nBOOST_AUTO_TEST_CASE(LimitedAndReachable_NetworkCaseUnroutableAndInternal)\n{\n BOOST_CHECK_EQUAL(IsReachable(NET_UNROUTABLE), true);\n BOOST_CHECK_EQUAL(IsReachable(NET_INTERNAL), true);\n\n SetReachable(NET_UNROUTABLE, false);\n SetReachable(NET_INTERNAL, false);\n\n BOOST_CHECK_EQUAL(IsReachable(NET_UNROUTABLE), true); \/\/ Ignored for both networks\n BOOST_CHECK_EQUAL(IsReachable(NET_INTERNAL), true);\n}\n\nCNetAddr UtilBuildAddress(unsigned char p1, unsigned char p2, unsigned char p3, unsigned char p4)\n{\n unsigned char ip[] = {p1, p2, p3, p4};\n\n struct sockaddr_in sa;\n memset(&sa, 0, sizeof(sockaddr_in)); \/\/ initialize the memory block\n memcpy(&(sa.sin_addr), &ip, sizeof(ip));\n return CNetAddr(sa.sin_addr);\n}\n\n\nBOOST_AUTO_TEST_CASE(LimitedAndReachable_CNetAddr)\n{\n CNetAddr addr = UtilBuildAddress(0x001, 0x001, 0x001, 0x001); \/\/ 1.1.1.1\n\n SetReachable(NET_IPV4, true);\n BOOST_CHECK_EQUAL(IsReachable(addr), true);\n\n SetReachable(NET_IPV4, false);\n BOOST_CHECK_EQUAL(IsReachable(addr), false);\n\n SetReachable(NET_IPV4, true); \/\/ have to reset this, because this is stateful.\n}\n\n\nBOOST_AUTO_TEST_CASE(LocalAddress_BasicLifecycle)\n{\n CService addr = CService(UtilBuildAddress(0x002, 0x001, 0x001, 0x001), 1000); \/\/ 2.1.1.1:1000\n\n SetReachable(NET_IPV4, true);\n\n BOOST_CHECK_EQUAL(IsLocal(addr), false);\n BOOST_CHECK_EQUAL(AddLocal(addr, 1000), true);\n BOOST_CHECK_EQUAL(IsLocal(addr), true);\n\n RemoveLocal(addr);\n BOOST_CHECK_EQUAL(IsLocal(addr), false);\n}\n\nBOOST_AUTO_TEST_CASE(PoissonNextSend)\n{\n g_mock_deterministic_tests = true;\n\n int64_t now = 5000;\n int average_interval_seconds = 600;\n\n auto poisson = ::PoissonNextSend(now, average_interval_seconds);\n std::chrono::microseconds poisson_chrono = ::PoissonNextSend(std::chrono::microseconds{now}, std::chrono::seconds{average_interval_seconds});\n\n BOOST_CHECK_EQUAL(poisson, poisson_chrono.count());\n\n g_mock_deterministic_tests = false;\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n<|endoftext|>"} {"text":"\/\/ Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.\n\n#include \"rpcsendv2.h\"\n#include \"rpcnetwork.h\"\n#include \"rpcserviceaddress.h\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nusing vespalib::make_string;\nusing vespalib::compression::CompressionConfig;\nusing vespalib::compression::decompress;\nusing vespalib::compression::compress;\nusing vespalib::DataBuffer;\nusing vespalib::ConstBufferRef;\nusing vespalib::stringref;\nusing vespalib::Memory;\nusing vespalib::Slime;\nusing vespalib::Version;\nusing namespace vespalib::slime;\n\nnamespace mbus {\n\nnamespace {\n\nconst char *METHOD_NAME = \"mbus.slime\";\nconst char *METHOD_PARAMS = \"bixbix\";\nconst char *METHOD_RETURN = \"bixbix\";\n\nMemory VERSION_F(\"version\");\nMemory ROUTE_F(\"route\");\nMemory SESSION_F(\"session\");\nMemory USERETRY_F(\"useretry\");\nMemory RETRYDELAY_F(\"retrydelay\");\nMemory RETRY_F(\"retry\");\nMemory TIMELEFT_F(\"timeleft\");\nMemory PROTOCOL_F(\"prot\");\nMemory TRACELEVEL_F(\"tracelevel\");\nMemory TRACE_F(\"trace\");\nMemory BLOB_F(\"msg\");\nMemory ERRORS_F(\"errors\");\nMemory CODE_F(\"code\");\nMemory MSG_F(\"msg\");\nMemory SERVICE_F(\"service\");\n\n}\n\nbool RPCSendV2::isCompatible(stringref method, stringref request, stringref response)\n{\n return (method == METHOD_NAME) &&\n (request == METHOD_PARAMS) &&\n (response == METHOD_RETURN);\n}\n\nvoid\nRPCSendV2::build(FRT_ReflectionBuilder & builder)\n{\n builder.DefineMethod(METHOD_NAME, METHOD_PARAMS, METHOD_RETURN, true, FRT_METHOD(RPCSendV2::invoke), this);\n builder.MethodDesc(\"Send a message bus slime request and get a reply back.\");\n builder.ParamDesc(\"header_encoding\", \"0=raw, 6=lz4\");\n builder.ParamDesc(\"header_decoded_size\", \"Uncompressed header blob size\");\n builder.ParamDesc(\"header_payload\", \"The message header blob in slime\");\n builder.ParamDesc(\"body_encoding\", \"0=raw, 6=lz4\");\n builder.ParamDesc(\"body_decoded_size\", \"Uncompressed body blob size\");\n builder.ParamDesc(\"body_payload\", \"The message body blob in slime\");\n builder.ReturnDesc(\"header_encoding\", \"0=raw, 6=lz4\");\n builder.ReturnDesc(\"header_decoded_size\", \"Uncompressed header blob size\");\n builder.ReturnDesc(\"header_payload\", \"The reply header blob in slime.\");\n builder.ReturnDesc(\"body_encoding\", \"0=raw, 6=lz4\");\n builder.ReturnDesc(\"body_decoded_size\", \"Uncompressed body blob size\");\n builder.ReturnDesc(\"body_payload\", \"The reply body blob in slime.\");\n}\n\nconst char *\nRPCSendV2::getReturnSpec() const {\n return METHOD_RETURN;\n}\n\nnamespace {\nclass OutputBuf : public vespalib::Output {\npublic:\n OutputBuf(size_t estimatedSize) : _buf(estimatedSize) { }\n DataBuffer & getBuf() { return _buf; }\nprivate:\n vespalib::WritableMemory reserve(size_t bytes) override {\n _buf.ensureFree(bytes);\n return vespalib::WritableMemory(_buf.getFree(), _buf.getFreeLen());\n }\n Output &commit(size_t bytes) override {\n _buf.moveFreeToData(bytes);\n return *this;\n }\n DataBuffer _buf;\n};\n}\n\nvoid\nRPCSendV2::encodeRequest(FRT_RPCRequest &req, const Version &version, const Route & route,\n const RPCServiceAddress & address, const Message & msg, uint32_t traceLevel,\n const PayLoadFiller &filler, uint64_t timeRemaining) const\n{\n FRT_Values &args = *req.GetParams();\n req.SetMethodName(METHOD_NAME);\n \/\/ Place holder for auxillary data to be transfered later.\n args.AddInt8(CompressionConfig::NONE);\n args.AddInt32(0);\n args.AddData(\"\", 0);\n\n Slime slime;\n Cursor & root = slime.setObject();\n\n root.setString(VERSION_F, version.toString());\n root.setString(ROUTE_F, route.toString());\n root.setString(SESSION_F, address.getSessionName());\n root.setBool(USERETRY_F, msg.getRetryEnabled());\n root.setLong(RETRY_F, msg.getRetry());\n root.setLong(TIMELEFT_F, timeRemaining);\n root.setString(PROTOCOL_F, msg.getProtocol());\n root.setLong(TRACELEVEL_F, traceLevel);\n filler.fill(BLOB_F, root);\n\n OutputBuf rBuf(8192);\n BinaryFormat::encode(slime, rBuf);\n ConstBufferRef toCompress(rBuf.getBuf().getData(), rBuf.getBuf().getDataLen());\n DataBuffer buf(vespalib::roundUp2inN(rBuf.getBuf().getDataLen()));\n CompressionConfig::Type type = compress(_net->getCompressionConfig(), toCompress, buf, false);\n\n args.AddInt8(type);\n args.AddInt32(toCompress.size());\n args.AddData(buf.stealBuffer(), buf.getDataLen());\n}\n\nnamespace {\n\nclass ParamsV2 : public RPCSend::Params\n{\npublic:\n ParamsV2(const FRT_Values &arg)\n : _slime()\n {\n uint8_t encoding = arg[0]._intval8;\n uint32_t uncompressedSize = arg[1]._intval32;\n DataBuffer uncompressed(arg[2]._data._buf, arg[2]._data._len);\n ConstBufferRef blob(arg[2]._data._buf, arg[2]._data._len);\n decompress(CompressionConfig::toType(encoding), uncompressedSize, blob, uncompressed, true);\n assert(uncompressedSize == uncompressed.getDataLen());\n BinaryFormat::decode(Memory(uncompressed.getData(), uncompressed.getDataLen()), _slime);\n }\n\n uint32_t getTraceLevel() const override { return _slime.get()[TRACELEVEL_F].asLong(); }\n bool useRetry() const override { return _slime.get()[USERETRY_F].asBool(); }\n uint32_t getRetries() const override { return _slime.get()[RETRY_F].asLong(); }\n uint64_t getRemainingTime() const override { return _slime.get()[TIMELEFT_F].asLong(); }\n\n Version getVersion() const override {\n return Version(_slime.get()[VERSION_F].asString().make_stringref());\n }\n stringref getRoute() const override {\n return _slime.get()[ROUTE_F].asString().make_stringref();\n }\n stringref getSession() const override {\n return _slime.get()[SESSION_F].asString().make_stringref();\n }\n stringref getProtocol() const override {\n return _slime.get()[PROTOCOL_F].asString().make_stringref();\n }\n BlobRef getPayload() const override {\n Memory m = _slime.get()[BLOB_F].asData();\n return BlobRef(m.data, m.size);\n }\nprivate:\n Slime _slime;\n};\n\n}\n\nstd::unique_ptr\nRPCSendV2::toParams(const FRT_Values &args) const\n{\n return std::make_unique(args);\n}\n\nstd::unique_ptr\nRPCSendV2::createReply(const FRT_Values & ret, const string & serviceName,\n Error & error, vespalib::TraceNode & rootTrace) const\n{\n uint8_t encoding = ret[0]._intval8;\n uint32_t uncompressedSize = ret[1]._intval32;\n DataBuffer uncompressed(ret[2]._data._buf, ret[2]._data._len);\n ConstBufferRef blob(ret[2]._data._buf, ret[2]._data._len);\n decompress(CompressionConfig::toType(encoding), uncompressedSize, blob, uncompressed, true);\n assert(uncompressedSize == uncompressed.getDataLen());\n Slime slime;\n BinaryFormat::decode(Memory(uncompressed.getData(), uncompressed.getDataLen()), slime);\n Inspector & root = slime.get();\n Version version(root[VERSION_F].asString().make_string());\n Memory payload = root[BLOB_F].asData();\n\n Reply::UP reply;\n if (payload.size > 0) {\n reply = decode(root[PROTOCOL_F].asString().make_stringref(), version, BlobRef(payload.data, payload.size), error);\n }\n if ( ! reply ) {\n reply.reset(new EmptyReply());\n }\n reply->setRetryDelay(root[RETRYDELAY_F].asDouble());\n Inspector & errors = root[ERRORS_F];\n for (uint32_t i = 0; i < errors.entries(); ++i) {\n Inspector & e = errors[i];\n Memory service = e[SERVICE_F].asString();\n reply->addError(Error(e[CODE_F].asLong(), e[MSG_F].asString().make_string(),\n (service.size > 0) ? service.make_string() : serviceName));\n }\n rootTrace.addChild(TraceNode::decode(root[TRACE_F].asString().make_string()));\n return reply;\n}\n\nvoid\nRPCSendV2::createResponse(FRT_Values & ret, const string & version, Reply & reply, Blob payload) const\n{\n \/\/ Place holder for auxillary data to be transfered later.\n ret.AddInt8(CompressionConfig::NONE);\n ret.AddInt32(0);\n ret.AddData(\"\", 0);\n\n Slime slime;\n Cursor & root = slime.setObject();\n\n root.setString(VERSION_F, version);\n root.setDouble(RETRYDELAY_F, reply.getRetryDelay());\n root.setString(PROTOCOL_F, reply.getProtocol());\n root.setData(BLOB_F, vespalib::Memory(payload.data(), payload.size()));\n if (reply.getTrace().getLevel() > 0) {\n root.setString(TRACE_F, reply.getTrace().getRoot().encode());\n }\n\n if (reply.getNumErrors() > 0) {\n Cursor & array = root.setArray(ERRORS_F);\n for (uint32_t i = 0; i < reply.getNumErrors(); ++i) {\n Cursor & error = array.addObject();\n error.setLong(CODE_F, reply.getError(i).getCode());\n error.setString(MSG_F, reply.getError(i).getMessage());\n error.setString(SERVICE_F, reply.getError(i).getService().c_str());\n }\n }\n\n OutputBuf rBuf(8192);\n BinaryFormat::encode(slime, rBuf);\n ConstBufferRef toCompress(rBuf.getBuf().getData(), rBuf.getBuf().getDataLen());\n DataBuffer buf(vespalib::roundUp2inN(rBuf.getBuf().getDataLen()));\n CompressionConfig::Type type = compress(_net->getCompressionConfig(), toCompress, buf, false);\n\n ret.AddInt8(type);\n ret.AddInt32(toCompress.size());\n ret.AddData(buf.stealBuffer(), buf.getDataLen());\n\n}\n\n} \/\/ namespace mbus\nbody has moved to last 3 parameters.\/\/ Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.\n\n#include \"rpcsendv2.h\"\n#include \"rpcnetwork.h\"\n#include \"rpcserviceaddress.h\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nusing vespalib::make_string;\nusing vespalib::compression::CompressionConfig;\nusing vespalib::compression::decompress;\nusing vespalib::compression::compress;\nusing vespalib::DataBuffer;\nusing vespalib::ConstBufferRef;\nusing vespalib::stringref;\nusing vespalib::Memory;\nusing vespalib::Slime;\nusing vespalib::Version;\nusing namespace vespalib::slime;\n\nnamespace mbus {\n\nnamespace {\n\nconst char *METHOD_NAME = \"mbus.slime\";\nconst char *METHOD_PARAMS = \"bixbix\";\nconst char *METHOD_RETURN = \"bixbix\";\n\nMemory VERSION_F(\"version\");\nMemory ROUTE_F(\"route\");\nMemory SESSION_F(\"session\");\nMemory USERETRY_F(\"useretry\");\nMemory RETRYDELAY_F(\"retrydelay\");\nMemory RETRY_F(\"retry\");\nMemory TIMELEFT_F(\"timeleft\");\nMemory PROTOCOL_F(\"prot\");\nMemory TRACELEVEL_F(\"tracelevel\");\nMemory TRACE_F(\"trace\");\nMemory BLOB_F(\"msg\");\nMemory ERRORS_F(\"errors\");\nMemory CODE_F(\"code\");\nMemory MSG_F(\"msg\");\nMemory SERVICE_F(\"service\");\n\n}\n\nbool RPCSendV2::isCompatible(stringref method, stringref request, stringref response)\n{\n return (method == METHOD_NAME) &&\n (request == METHOD_PARAMS) &&\n (response == METHOD_RETURN);\n}\n\nvoid\nRPCSendV2::build(FRT_ReflectionBuilder & builder)\n{\n builder.DefineMethod(METHOD_NAME, METHOD_PARAMS, METHOD_RETURN, true, FRT_METHOD(RPCSendV2::invoke), this);\n builder.MethodDesc(\"Send a message bus slime request and get a reply back.\");\n builder.ParamDesc(\"header_encoding\", \"0=raw, 6=lz4\");\n builder.ParamDesc(\"header_decoded_size\", \"Uncompressed header blob size\");\n builder.ParamDesc(\"header_payload\", \"The message header blob in slime\");\n builder.ParamDesc(\"body_encoding\", \"0=raw, 6=lz4\");\n builder.ParamDesc(\"body_decoded_size\", \"Uncompressed body blob size\");\n builder.ParamDesc(\"body_payload\", \"The message body blob in slime\");\n builder.ReturnDesc(\"header_encoding\", \"0=raw, 6=lz4\");\n builder.ReturnDesc(\"header_decoded_size\", \"Uncompressed header blob size\");\n builder.ReturnDesc(\"header_payload\", \"The reply header blob in slime.\");\n builder.ReturnDesc(\"body_encoding\", \"0=raw, 6=lz4\");\n builder.ReturnDesc(\"body_decoded_size\", \"Uncompressed body blob size\");\n builder.ReturnDesc(\"body_payload\", \"The reply body blob in slime.\");\n}\n\nconst char *\nRPCSendV2::getReturnSpec() const {\n return METHOD_RETURN;\n}\n\nnamespace {\nclass OutputBuf : public vespalib::Output {\npublic:\n OutputBuf(size_t estimatedSize) : _buf(estimatedSize) { }\n DataBuffer & getBuf() { return _buf; }\nprivate:\n vespalib::WritableMemory reserve(size_t bytes) override {\n _buf.ensureFree(bytes);\n return vespalib::WritableMemory(_buf.getFree(), _buf.getFreeLen());\n }\n Output &commit(size_t bytes) override {\n _buf.moveFreeToData(bytes);\n return *this;\n }\n DataBuffer _buf;\n};\n}\n\nvoid\nRPCSendV2::encodeRequest(FRT_RPCRequest &req, const Version &version, const Route & route,\n const RPCServiceAddress & address, const Message & msg, uint32_t traceLevel,\n const PayLoadFiller &filler, uint64_t timeRemaining) const\n{\n FRT_Values &args = *req.GetParams();\n req.SetMethodName(METHOD_NAME);\n \/\/ Place holder for auxillary data to be transfered later.\n args.AddInt8(CompressionConfig::NONE);\n args.AddInt32(0);\n args.AddData(\"\", 0);\n\n Slime slime;\n Cursor & root = slime.setObject();\n\n root.setString(VERSION_F, version.toString());\n root.setString(ROUTE_F, route.toString());\n root.setString(SESSION_F, address.getSessionName());\n root.setBool(USERETRY_F, msg.getRetryEnabled());\n root.setLong(RETRY_F, msg.getRetry());\n root.setLong(TIMELEFT_F, timeRemaining);\n root.setString(PROTOCOL_F, msg.getProtocol());\n root.setLong(TRACELEVEL_F, traceLevel);\n filler.fill(BLOB_F, root);\n\n OutputBuf rBuf(8192);\n BinaryFormat::encode(slime, rBuf);\n ConstBufferRef toCompress(rBuf.getBuf().getData(), rBuf.getBuf().getDataLen());\n DataBuffer buf(vespalib::roundUp2inN(rBuf.getBuf().getDataLen()));\n CompressionConfig::Type type = compress(_net->getCompressionConfig(), toCompress, buf, false);\n\n args.AddInt8(type);\n args.AddInt32(toCompress.size());\n args.AddData(buf.stealBuffer(), buf.getDataLen());\n}\n\nnamespace {\n\nclass ParamsV2 : public RPCSend::Params\n{\npublic:\n ParamsV2(const FRT_Values &arg)\n : _slime()\n {\n uint8_t encoding = arg[3]._intval8;\n uint32_t uncompressedSize = arg[4]._intval32;\n DataBuffer uncompressed(arg[5]._data._buf, arg[5]._data._len);\n ConstBufferRef blob(arg[5]._data._buf, arg[5]._data._len);\n decompress(CompressionConfig::toType(encoding), uncompressedSize, blob, uncompressed, true);\n assert(uncompressedSize == uncompressed.getDataLen());\n BinaryFormat::decode(Memory(uncompressed.getData(), uncompressed.getDataLen()), _slime);\n }\n\n uint32_t getTraceLevel() const override { return _slime.get()[TRACELEVEL_F].asLong(); }\n bool useRetry() const override { return _slime.get()[USERETRY_F].asBool(); }\n uint32_t getRetries() const override { return _slime.get()[RETRY_F].asLong(); }\n uint64_t getRemainingTime() const override { return _slime.get()[TIMELEFT_F].asLong(); }\n\n Version getVersion() const override {\n return Version(_slime.get()[VERSION_F].asString().make_stringref());\n }\n stringref getRoute() const override {\n return _slime.get()[ROUTE_F].asString().make_stringref();\n }\n stringref getSession() const override {\n return _slime.get()[SESSION_F].asString().make_stringref();\n }\n stringref getProtocol() const override {\n return _slime.get()[PROTOCOL_F].asString().make_stringref();\n }\n BlobRef getPayload() const override {\n Memory m = _slime.get()[BLOB_F].asData();\n return BlobRef(m.data, m.size);\n }\nprivate:\n Slime _slime;\n};\n\n}\n\nstd::unique_ptr\nRPCSendV2::toParams(const FRT_Values &args) const\n{\n return std::make_unique(args);\n}\n\nstd::unique_ptr\nRPCSendV2::createReply(const FRT_Values & ret, const string & serviceName,\n Error & error, vespalib::TraceNode & rootTrace) const\n{\n uint8_t encoding = ret[3]._intval8;\n uint32_t uncompressedSize = ret[4]._intval32;\n DataBuffer uncompressed(ret[5]._data._buf, ret[5]._data._len);\n ConstBufferRef blob(ret[5]._data._buf, ret[5]._data._len);\n decompress(CompressionConfig::toType(encoding), uncompressedSize, blob, uncompressed, true);\n assert(uncompressedSize == uncompressed.getDataLen());\n Slime slime;\n BinaryFormat::decode(Memory(uncompressed.getData(), uncompressed.getDataLen()), slime);\n Inspector & root = slime.get();\n Version version(root[VERSION_F].asString().make_string());\n Memory payload = root[BLOB_F].asData();\n\n Reply::UP reply;\n if (payload.size > 0) {\n reply = decode(root[PROTOCOL_F].asString().make_stringref(), version, BlobRef(payload.data, payload.size), error);\n }\n if ( ! reply ) {\n reply.reset(new EmptyReply());\n }\n reply->setRetryDelay(root[RETRYDELAY_F].asDouble());\n Inspector & errors = root[ERRORS_F];\n for (uint32_t i = 0; i < errors.entries(); ++i) {\n Inspector & e = errors[i];\n Memory service = e[SERVICE_F].asString();\n reply->addError(Error(e[CODE_F].asLong(), e[MSG_F].asString().make_string(),\n (service.size > 0) ? service.make_string() : serviceName));\n }\n rootTrace.addChild(TraceNode::decode(root[TRACE_F].asString().make_string()));\n return reply;\n}\n\nvoid\nRPCSendV2::createResponse(FRT_Values & ret, const string & version, Reply & reply, Blob payload) const\n{\n \/\/ Place holder for auxillary data to be transfered later.\n ret.AddInt8(CompressionConfig::NONE);\n ret.AddInt32(0);\n ret.AddData(\"\", 0);\n\n Slime slime;\n Cursor & root = slime.setObject();\n\n root.setString(VERSION_F, version);\n root.setDouble(RETRYDELAY_F, reply.getRetryDelay());\n root.setString(PROTOCOL_F, reply.getProtocol());\n root.setData(BLOB_F, vespalib::Memory(payload.data(), payload.size()));\n if (reply.getTrace().getLevel() > 0) {\n root.setString(TRACE_F, reply.getTrace().getRoot().encode());\n }\n\n if (reply.getNumErrors() > 0) {\n Cursor & array = root.setArray(ERRORS_F);\n for (uint32_t i = 0; i < reply.getNumErrors(); ++i) {\n Cursor & error = array.addObject();\n error.setLong(CODE_F, reply.getError(i).getCode());\n error.setString(MSG_F, reply.getError(i).getMessage());\n error.setString(SERVICE_F, reply.getError(i).getService().c_str());\n }\n }\n\n OutputBuf rBuf(8192);\n BinaryFormat::encode(slime, rBuf);\n ConstBufferRef toCompress(rBuf.getBuf().getData(), rBuf.getBuf().getDataLen());\n DataBuffer buf(vespalib::roundUp2inN(rBuf.getBuf().getDataLen()));\n CompressionConfig::Type type = compress(_net->getCompressionConfig(), toCompress, buf, false);\n\n ret.AddInt8(type);\n ret.AddInt32(toCompress.size());\n ret.AddData(buf.stealBuffer(), buf.getDataLen());\n\n}\n\n} \/\/ namespace mbus\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2012-2019 The Bitcoin Core developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\nclass CAddrManSerializationMock : public CAddrMan\n{\npublic:\n virtual void Serialize(CDataStream& s) const = 0;\n\n \/\/! Ensure that bucket placement is always the same for testing purposes.\n void MakeDeterministic()\n {\n nKey.SetNull();\n insecure_rand = FastRandomContext(true);\n }\n};\n\nclass CAddrManUncorrupted : public CAddrManSerializationMock\n{\npublic:\n void Serialize(CDataStream& s) const override\n {\n CAddrMan::Serialize(s);\n }\n};\n\nclass CAddrManCorrupted : public CAddrManSerializationMock\n{\npublic:\n void Serialize(CDataStream& s) const override\n {\n \/\/ Produces corrupt output that claims addrman has 20 addrs when it only has one addr.\n unsigned char nVersion = 1;\n s << nVersion;\n s << ((unsigned char)32);\n s << nKey;\n s << 10; \/\/ nNew\n s << 10; \/\/ nTried\n\n int nUBuckets = ADDRMAN_NEW_BUCKET_COUNT ^ (1 << 30);\n s << nUBuckets;\n\n CService serv;\n BOOST_CHECK(Lookup(\"252.1.1.1\", serv, 7777, false));\n CAddress addr = CAddress(serv, NODE_NONE);\n CNetAddr resolved;\n BOOST_CHECK(LookupHost(\"252.2.2.2\", resolved, false));\n CAddrInfo info = CAddrInfo(addr, resolved);\n s << info;\n }\n};\n\nstatic CDataStream AddrmanToStream(CAddrManSerializationMock& _addrman)\n{\n CDataStream ssPeersIn(SER_DISK, CLIENT_VERSION);\n ssPeersIn << Params().MessageStart();\n ssPeersIn << _addrman;\n std::string str = ssPeersIn.str();\n std::vector vchData(str.begin(), str.end());\n return CDataStream(vchData, SER_DISK, CLIENT_VERSION);\n}\n\nBOOST_FIXTURE_TEST_SUITE(net_tests, BasicTestingSetup)\n\nBOOST_AUTO_TEST_CASE(cnode_listen_port)\n{\n \/\/ test default\n unsigned short port = GetListenPort();\n BOOST_CHECK(port == Params().GetDefaultPort());\n \/\/ test set port\n unsigned short altPort = 12345;\n BOOST_CHECK(gArgs.SoftSetArg(\"-port\", std::to_string(altPort)));\n port = GetListenPort();\n BOOST_CHECK(port == altPort);\n}\n\nBOOST_AUTO_TEST_CASE(caddrdb_read)\n{\n CAddrManUncorrupted addrmanUncorrupted;\n addrmanUncorrupted.MakeDeterministic();\n\n CService addr1, addr2, addr3;\n BOOST_CHECK(Lookup(\"250.7.1.1\", addr1, 8333, false));\n BOOST_CHECK(Lookup(\"250.7.2.2\", addr2, 9999, false));\n BOOST_CHECK(Lookup(\"250.7.3.3\", addr3, 9999, false));\n\n \/\/ Add three addresses to new table.\n CService source;\n BOOST_CHECK(Lookup(\"252.5.1.1\", source, 8333, false));\n BOOST_CHECK(addrmanUncorrupted.Add(CAddress(addr1, NODE_NONE), source));\n BOOST_CHECK(addrmanUncorrupted.Add(CAddress(addr2, NODE_NONE), source));\n BOOST_CHECK(addrmanUncorrupted.Add(CAddress(addr3, NODE_NONE), source));\n\n \/\/ Test that the de-serialization does not throw an exception.\n CDataStream ssPeers1 = AddrmanToStream(addrmanUncorrupted);\n bool exceptionThrown = false;\n CAddrMan addrman1;\n\n BOOST_CHECK(addrman1.size() == 0);\n try {\n unsigned char pchMsgTmp[4];\n ssPeers1 >> pchMsgTmp;\n ssPeers1 >> addrman1;\n } catch (const std::exception&) {\n exceptionThrown = true;\n }\n\n BOOST_CHECK(addrman1.size() == 3);\n BOOST_CHECK(exceptionThrown == false);\n\n \/\/ Test that CAddrDB::Read creates an addrman with the correct number of addrs.\n CDataStream ssPeers2 = AddrmanToStream(addrmanUncorrupted);\n\n CAddrMan addrman2;\n CAddrDB adb;\n BOOST_CHECK(addrman2.size() == 0);\n BOOST_CHECK(adb.Read(addrman2, ssPeers2));\n BOOST_CHECK(addrman2.size() == 3);\n}\n\n\nBOOST_AUTO_TEST_CASE(caddrdb_read_corrupted)\n{\n CAddrManCorrupted addrmanCorrupted;\n addrmanCorrupted.MakeDeterministic();\n\n \/\/ Test that the de-serialization of corrupted addrman throws an exception.\n CDataStream ssPeers1 = AddrmanToStream(addrmanCorrupted);\n bool exceptionThrown = false;\n CAddrMan addrman1;\n BOOST_CHECK(addrman1.size() == 0);\n try {\n unsigned char pchMsgTmp[4];\n ssPeers1 >> pchMsgTmp;\n ssPeers1 >> addrman1;\n } catch (const std::exception&) {\n exceptionThrown = true;\n }\n \/\/ Even through de-serialization failed addrman is not left in a clean state.\n BOOST_CHECK(addrman1.size() == 1);\n BOOST_CHECK(exceptionThrown);\n\n \/\/ Test that CAddrDB::Read leaves addrman in a clean state if de-serialization fails.\n CDataStream ssPeers2 = AddrmanToStream(addrmanCorrupted);\n\n CAddrMan addrman2;\n CAddrDB adb;\n BOOST_CHECK(addrman2.size() == 0);\n BOOST_CHECK(!adb.Read(addrman2, ssPeers2));\n BOOST_CHECK(addrman2.size() == 0);\n}\n\nBOOST_AUTO_TEST_CASE(cnode_simple_test)\n{\n SOCKET hSocket = INVALID_SOCKET;\n NodeId id = 0;\n int height = 0;\n\n in_addr ipv4Addr;\n ipv4Addr.s_addr = 0xa0b0c001;\n\n CAddress addr = CAddress(CService(ipv4Addr, 7777), NODE_NETWORK);\n std::string pszDest;\n bool fInboundIn = false;\n\n \/\/ Test that fFeeler is false by default.\n std::unique_ptr pnode1 = MakeUnique(id++, NODE_NETWORK, height, hSocket, addr, 0, 0, CAddress(), pszDest, fInboundIn);\n BOOST_CHECK(pnode1->fInbound == false);\n BOOST_CHECK(pnode1->fFeeler == false);\n\n fInboundIn = true;\n std::unique_ptr pnode2 = MakeUnique(id++, NODE_NETWORK, height, hSocket, addr, 1, 1, CAddress(), pszDest, fInboundIn);\n BOOST_CHECK(pnode2->fInbound == true);\n BOOST_CHECK(pnode2->fFeeler == false);\n}\n\n\/\/ prior to PR #14728, this test triggers an undefined behavior\nBOOST_AUTO_TEST_CASE(ipv4_peer_with_ipv6_addrMe_test)\n{\n \/\/ set up local addresses; all that's necessary to reproduce the bug is\n \/\/ that a normal IPv4 address is among the entries, but if this address is\n \/\/ !IsRoutable the undefined behavior is easier to trigger deterministically\n {\n LOCK(cs_mapLocalHost);\n in_addr ipv4AddrLocal;\n ipv4AddrLocal.s_addr = 0x0100007f;\n CNetAddr addr = CNetAddr(ipv4AddrLocal);\n LocalServiceInfo lsi;\n lsi.nScore = 23;\n lsi.nPort = 42;\n mapLocalHost[addr] = lsi;\n }\n\n \/\/ create a peer with an IPv4 address\n in_addr ipv4AddrPeer;\n ipv4AddrPeer.s_addr = 0xa0b0c001;\n CAddress addr = CAddress(CService(ipv4AddrPeer, 7777), NODE_NETWORK);\n std::unique_ptr pnode = MakeUnique(0, NODE_NETWORK, 0, INVALID_SOCKET, addr, 0, 0, CAddress{}, std::string{}, false);\n pnode->fSuccessfullyConnected.store(true);\n\n \/\/ the peer claims to be reaching us via IPv6\n in6_addr ipv6AddrLocal;\n memset(ipv6AddrLocal.s6_addr, 0, 16);\n ipv6AddrLocal.s6_addr[0] = 0xcc;\n CAddress addrLocal = CAddress(CService(ipv6AddrLocal, 7777), NODE_NETWORK);\n pnode->SetAddrLocal(addrLocal);\n\n \/\/ before patch, this causes undefined behavior detectable with clang's -fsanitize=memory\n AdvertiseLocal(&*pnode);\n\n \/\/ suppress no-checks-run warning; if this test fails, it's by triggering a sanitizer\n BOOST_CHECK(1);\n}\n\n\nBOOST_AUTO_TEST_CASE(LimitedAndReachable_Network)\n{\n BOOST_CHECK_EQUAL(IsReachable(NET_IPV4), true);\n BOOST_CHECK_EQUAL(IsReachable(NET_IPV6), true);\n BOOST_CHECK_EQUAL(IsReachable(NET_ONION), true);\n\n SetReachable(NET_IPV4, false);\n SetReachable(NET_IPV6, false);\n SetReachable(NET_ONION, false);\n\n BOOST_CHECK_EQUAL(IsReachable(NET_IPV4), false);\n BOOST_CHECK_EQUAL(IsReachable(NET_IPV6), false);\n BOOST_CHECK_EQUAL(IsReachable(NET_ONION), false);\n\n SetReachable(NET_IPV4, true);\n SetReachable(NET_IPV6, true);\n SetReachable(NET_ONION, true);\n\n BOOST_CHECK_EQUAL(IsReachable(NET_IPV4), true);\n BOOST_CHECK_EQUAL(IsReachable(NET_IPV6), true);\n BOOST_CHECK_EQUAL(IsReachable(NET_ONION), true);\n}\n\nBOOST_AUTO_TEST_CASE(LimitedAndReachable_NetworkCaseUnroutableAndInternal)\n{\n BOOST_CHECK_EQUAL(IsReachable(NET_UNROUTABLE), true);\n BOOST_CHECK_EQUAL(IsReachable(NET_INTERNAL), true);\n\n SetReachable(NET_UNROUTABLE, false);\n SetReachable(NET_INTERNAL, false);\n\n BOOST_CHECK_EQUAL(IsReachable(NET_UNROUTABLE), true); \/\/ Ignored for both networks\n BOOST_CHECK_EQUAL(IsReachable(NET_INTERNAL), true);\n}\n\nCNetAddr UtilBuildAddress(unsigned char p1, unsigned char p2, unsigned char p3, unsigned char p4)\n{\n unsigned char ip[] = {p1, p2, p3, p4};\n\n struct sockaddr_in sa;\n memset(&sa, 0, sizeof(sockaddr_in)); \/\/ initialize the memory block\n memcpy(&(sa.sin_addr), &ip, sizeof(ip));\n return CNetAddr(sa.sin_addr);\n}\n\n\nBOOST_AUTO_TEST_CASE(LimitedAndReachable_CNetAddr)\n{\n CNetAddr addr = UtilBuildAddress(0x001, 0x001, 0x001, 0x001); \/\/ 1.1.1.1\n\n SetReachable(NET_IPV4, true);\n BOOST_CHECK_EQUAL(IsReachable(addr), true);\n\n SetReachable(NET_IPV4, false);\n BOOST_CHECK_EQUAL(IsReachable(addr), false);\n\n SetReachable(NET_IPV4, true); \/\/ have to reset this, because this is stateful.\n}\n\n\nBOOST_AUTO_TEST_CASE(LocalAddress_BasicLifecycle)\n{\n CService addr = CService(UtilBuildAddress(0x002, 0x001, 0x001, 0x001), 1000); \/\/ 2.1.1.1:1000\n\n SetReachable(NET_IPV4, true);\n\n BOOST_CHECK_EQUAL(IsLocal(addr), false);\n BOOST_CHECK_EQUAL(AddLocal(addr, 1000), true);\n BOOST_CHECK_EQUAL(IsLocal(addr), true);\n\n RemoveLocal(addr);\n BOOST_CHECK_EQUAL(IsLocal(addr), false);\n}\n\n\nBOOST_AUTO_TEST_SUITE_END()\ntest: Do not instantiate CAddrDB for static call\/\/ Copyright (c) 2012-2019 The Bitcoin Core developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\nclass CAddrManSerializationMock : public CAddrMan\n{\npublic:\n virtual void Serialize(CDataStream& s) const = 0;\n\n \/\/! Ensure that bucket placement is always the same for testing purposes.\n void MakeDeterministic()\n {\n nKey.SetNull();\n insecure_rand = FastRandomContext(true);\n }\n};\n\nclass CAddrManUncorrupted : public CAddrManSerializationMock\n{\npublic:\n void Serialize(CDataStream& s) const override\n {\n CAddrMan::Serialize(s);\n }\n};\n\nclass CAddrManCorrupted : public CAddrManSerializationMock\n{\npublic:\n void Serialize(CDataStream& s) const override\n {\n \/\/ Produces corrupt output that claims addrman has 20 addrs when it only has one addr.\n unsigned char nVersion = 1;\n s << nVersion;\n s << ((unsigned char)32);\n s << nKey;\n s << 10; \/\/ nNew\n s << 10; \/\/ nTried\n\n int nUBuckets = ADDRMAN_NEW_BUCKET_COUNT ^ (1 << 30);\n s << nUBuckets;\n\n CService serv;\n BOOST_CHECK(Lookup(\"252.1.1.1\", serv, 7777, false));\n CAddress addr = CAddress(serv, NODE_NONE);\n CNetAddr resolved;\n BOOST_CHECK(LookupHost(\"252.2.2.2\", resolved, false));\n CAddrInfo info = CAddrInfo(addr, resolved);\n s << info;\n }\n};\n\nstatic CDataStream AddrmanToStream(CAddrManSerializationMock& _addrman)\n{\n CDataStream ssPeersIn(SER_DISK, CLIENT_VERSION);\n ssPeersIn << Params().MessageStart();\n ssPeersIn << _addrman;\n std::string str = ssPeersIn.str();\n std::vector vchData(str.begin(), str.end());\n return CDataStream(vchData, SER_DISK, CLIENT_VERSION);\n}\n\nBOOST_FIXTURE_TEST_SUITE(net_tests, BasicTestingSetup)\n\nBOOST_AUTO_TEST_CASE(cnode_listen_port)\n{\n \/\/ test default\n unsigned short port = GetListenPort();\n BOOST_CHECK(port == Params().GetDefaultPort());\n \/\/ test set port\n unsigned short altPort = 12345;\n BOOST_CHECK(gArgs.SoftSetArg(\"-port\", std::to_string(altPort)));\n port = GetListenPort();\n BOOST_CHECK(port == altPort);\n}\n\nBOOST_AUTO_TEST_CASE(caddrdb_read)\n{\n CAddrManUncorrupted addrmanUncorrupted;\n addrmanUncorrupted.MakeDeterministic();\n\n CService addr1, addr2, addr3;\n BOOST_CHECK(Lookup(\"250.7.1.1\", addr1, 8333, false));\n BOOST_CHECK(Lookup(\"250.7.2.2\", addr2, 9999, false));\n BOOST_CHECK(Lookup(\"250.7.3.3\", addr3, 9999, false));\n\n \/\/ Add three addresses to new table.\n CService source;\n BOOST_CHECK(Lookup(\"252.5.1.1\", source, 8333, false));\n BOOST_CHECK(addrmanUncorrupted.Add(CAddress(addr1, NODE_NONE), source));\n BOOST_CHECK(addrmanUncorrupted.Add(CAddress(addr2, NODE_NONE), source));\n BOOST_CHECK(addrmanUncorrupted.Add(CAddress(addr3, NODE_NONE), source));\n\n \/\/ Test that the de-serialization does not throw an exception.\n CDataStream ssPeers1 = AddrmanToStream(addrmanUncorrupted);\n bool exceptionThrown = false;\n CAddrMan addrman1;\n\n BOOST_CHECK(addrman1.size() == 0);\n try {\n unsigned char pchMsgTmp[4];\n ssPeers1 >> pchMsgTmp;\n ssPeers1 >> addrman1;\n } catch (const std::exception&) {\n exceptionThrown = true;\n }\n\n BOOST_CHECK(addrman1.size() == 3);\n BOOST_CHECK(exceptionThrown == false);\n\n \/\/ Test that CAddrDB::Read creates an addrman with the correct number of addrs.\n CDataStream ssPeers2 = AddrmanToStream(addrmanUncorrupted);\n\n CAddrMan addrman2;\n BOOST_CHECK(addrman2.size() == 0);\n BOOST_CHECK(CAddrDB::Read(addrman2, ssPeers2));\n BOOST_CHECK(addrman2.size() == 3);\n}\n\n\nBOOST_AUTO_TEST_CASE(caddrdb_read_corrupted)\n{\n CAddrManCorrupted addrmanCorrupted;\n addrmanCorrupted.MakeDeterministic();\n\n \/\/ Test that the de-serialization of corrupted addrman throws an exception.\n CDataStream ssPeers1 = AddrmanToStream(addrmanCorrupted);\n bool exceptionThrown = false;\n CAddrMan addrman1;\n BOOST_CHECK(addrman1.size() == 0);\n try {\n unsigned char pchMsgTmp[4];\n ssPeers1 >> pchMsgTmp;\n ssPeers1 >> addrman1;\n } catch (const std::exception&) {\n exceptionThrown = true;\n }\n \/\/ Even through de-serialization failed addrman is not left in a clean state.\n BOOST_CHECK(addrman1.size() == 1);\n BOOST_CHECK(exceptionThrown);\n\n \/\/ Test that CAddrDB::Read leaves addrman in a clean state if de-serialization fails.\n CDataStream ssPeers2 = AddrmanToStream(addrmanCorrupted);\n\n CAddrMan addrman2;\n BOOST_CHECK(addrman2.size() == 0);\n BOOST_CHECK(!CAddrDB::Read(addrman2, ssPeers2));\n BOOST_CHECK(addrman2.size() == 0);\n}\n\nBOOST_AUTO_TEST_CASE(cnode_simple_test)\n{\n SOCKET hSocket = INVALID_SOCKET;\n NodeId id = 0;\n int height = 0;\n\n in_addr ipv4Addr;\n ipv4Addr.s_addr = 0xa0b0c001;\n\n CAddress addr = CAddress(CService(ipv4Addr, 7777), NODE_NETWORK);\n std::string pszDest;\n bool fInboundIn = false;\n\n \/\/ Test that fFeeler is false by default.\n std::unique_ptr pnode1 = MakeUnique(id++, NODE_NETWORK, height, hSocket, addr, 0, 0, CAddress(), pszDest, fInboundIn);\n BOOST_CHECK(pnode1->fInbound == false);\n BOOST_CHECK(pnode1->fFeeler == false);\n\n fInboundIn = true;\n std::unique_ptr pnode2 = MakeUnique(id++, NODE_NETWORK, height, hSocket, addr, 1, 1, CAddress(), pszDest, fInboundIn);\n BOOST_CHECK(pnode2->fInbound == true);\n BOOST_CHECK(pnode2->fFeeler == false);\n}\n\n\/\/ prior to PR #14728, this test triggers an undefined behavior\nBOOST_AUTO_TEST_CASE(ipv4_peer_with_ipv6_addrMe_test)\n{\n \/\/ set up local addresses; all that's necessary to reproduce the bug is\n \/\/ that a normal IPv4 address is among the entries, but if this address is\n \/\/ !IsRoutable the undefined behavior is easier to trigger deterministically\n {\n LOCK(cs_mapLocalHost);\n in_addr ipv4AddrLocal;\n ipv4AddrLocal.s_addr = 0x0100007f;\n CNetAddr addr = CNetAddr(ipv4AddrLocal);\n LocalServiceInfo lsi;\n lsi.nScore = 23;\n lsi.nPort = 42;\n mapLocalHost[addr] = lsi;\n }\n\n \/\/ create a peer with an IPv4 address\n in_addr ipv4AddrPeer;\n ipv4AddrPeer.s_addr = 0xa0b0c001;\n CAddress addr = CAddress(CService(ipv4AddrPeer, 7777), NODE_NETWORK);\n std::unique_ptr pnode = MakeUnique(0, NODE_NETWORK, 0, INVALID_SOCKET, addr, 0, 0, CAddress{}, std::string{}, false);\n pnode->fSuccessfullyConnected.store(true);\n\n \/\/ the peer claims to be reaching us via IPv6\n in6_addr ipv6AddrLocal;\n memset(ipv6AddrLocal.s6_addr, 0, 16);\n ipv6AddrLocal.s6_addr[0] = 0xcc;\n CAddress addrLocal = CAddress(CService(ipv6AddrLocal, 7777), NODE_NETWORK);\n pnode->SetAddrLocal(addrLocal);\n\n \/\/ before patch, this causes undefined behavior detectable with clang's -fsanitize=memory\n AdvertiseLocal(&*pnode);\n\n \/\/ suppress no-checks-run warning; if this test fails, it's by triggering a sanitizer\n BOOST_CHECK(1);\n}\n\n\nBOOST_AUTO_TEST_CASE(LimitedAndReachable_Network)\n{\n BOOST_CHECK_EQUAL(IsReachable(NET_IPV4), true);\n BOOST_CHECK_EQUAL(IsReachable(NET_IPV6), true);\n BOOST_CHECK_EQUAL(IsReachable(NET_ONION), true);\n\n SetReachable(NET_IPV4, false);\n SetReachable(NET_IPV6, false);\n SetReachable(NET_ONION, false);\n\n BOOST_CHECK_EQUAL(IsReachable(NET_IPV4), false);\n BOOST_CHECK_EQUAL(IsReachable(NET_IPV6), false);\n BOOST_CHECK_EQUAL(IsReachable(NET_ONION), false);\n\n SetReachable(NET_IPV4, true);\n SetReachable(NET_IPV6, true);\n SetReachable(NET_ONION, true);\n\n BOOST_CHECK_EQUAL(IsReachable(NET_IPV4), true);\n BOOST_CHECK_EQUAL(IsReachable(NET_IPV6), true);\n BOOST_CHECK_EQUAL(IsReachable(NET_ONION), true);\n}\n\nBOOST_AUTO_TEST_CASE(LimitedAndReachable_NetworkCaseUnroutableAndInternal)\n{\n BOOST_CHECK_EQUAL(IsReachable(NET_UNROUTABLE), true);\n BOOST_CHECK_EQUAL(IsReachable(NET_INTERNAL), true);\n\n SetReachable(NET_UNROUTABLE, false);\n SetReachable(NET_INTERNAL, false);\n\n BOOST_CHECK_EQUAL(IsReachable(NET_UNROUTABLE), true); \/\/ Ignored for both networks\n BOOST_CHECK_EQUAL(IsReachable(NET_INTERNAL), true);\n}\n\nCNetAddr UtilBuildAddress(unsigned char p1, unsigned char p2, unsigned char p3, unsigned char p4)\n{\n unsigned char ip[] = {p1, p2, p3, p4};\n\n struct sockaddr_in sa;\n memset(&sa, 0, sizeof(sockaddr_in)); \/\/ initialize the memory block\n memcpy(&(sa.sin_addr), &ip, sizeof(ip));\n return CNetAddr(sa.sin_addr);\n}\n\n\nBOOST_AUTO_TEST_CASE(LimitedAndReachable_CNetAddr)\n{\n CNetAddr addr = UtilBuildAddress(0x001, 0x001, 0x001, 0x001); \/\/ 1.1.1.1\n\n SetReachable(NET_IPV4, true);\n BOOST_CHECK_EQUAL(IsReachable(addr), true);\n\n SetReachable(NET_IPV4, false);\n BOOST_CHECK_EQUAL(IsReachable(addr), false);\n\n SetReachable(NET_IPV4, true); \/\/ have to reset this, because this is stateful.\n}\n\n\nBOOST_AUTO_TEST_CASE(LocalAddress_BasicLifecycle)\n{\n CService addr = CService(UtilBuildAddress(0x002, 0x001, 0x001, 0x001), 1000); \/\/ 2.1.1.1:1000\n\n SetReachable(NET_IPV4, true);\n\n BOOST_CHECK_EQUAL(IsLocal(addr), false);\n BOOST_CHECK_EQUAL(AddLocal(addr, 1000), true);\n BOOST_CHECK_EQUAL(IsLocal(addr), true);\n\n RemoveLocal(addr);\n BOOST_CHECK_EQUAL(IsLocal(addr), false);\n}\n\n\nBOOST_AUTO_TEST_SUITE_END()\n<|endoftext|>"} {"text":"\/\/ Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \nLOG_SETUP(\"sendadapter_test\");\n\nusing namespace mbus;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Setup\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nclass TestProtocol : public mbus::SimpleProtocol {\nprivate:\n mutable vespalib::Version _lastVersion;\n\npublic:\n typedef std::shared_ptr SP;\n mbus::Blob encode(const vespalib::Version &version, const mbus::Routable &routable) const override {\n _lastVersion = version;\n return mbus::SimpleProtocol::encode(version, routable);\n }\n mbus::Routable::UP decode(const vespalib::Version &version, mbus::BlobRef blob) const override {\n _lastVersion = version;\n return mbus::SimpleProtocol::decode(version, blob);\n }\n const vespalib::Version &getLastVersion() { return _lastVersion; }\n};\n\nclass TestData {\npublic:\n Slobrok _slobrok;\n TestProtocol::SP _srcProtocol;\n TestServer _srcServer;\n SourceSession::UP _srcSession;\n Receptor _srcHandler;\n TestProtocol::SP _itrProtocol;\n TestServer _itrServer;\n IntermediateSession::UP _itrSession;\n Receptor _itrHandler;\n TestProtocol::SP _dstProtocol;\n TestServer _dstServer;\n DestinationSession::UP _dstSession;\n Receptor _dstHandler;\n\npublic:\n TestData();\n ~TestData();\n bool start();\n};\n\nstatic const duration TIMEOUT_SECS = 6s;\n\nTestData::TestData() :\n _slobrok(),\n _srcProtocol(new TestProtocol()),\n _srcServer(MessageBusParams().setRetryPolicy(IRetryPolicy::SP()).addProtocol(_srcProtocol),\n RPCNetworkParams(_slobrok.config())),\n _srcSession(),\n _srcHandler(),\n _itrProtocol(new TestProtocol()),\n _itrServer(MessageBusParams().addProtocol(_itrProtocol),\n RPCNetworkParams(_slobrok.config()).setIdentity(Identity(\"itr\"))),\n _itrSession(),\n _itrHandler(),\n _dstProtocol(new TestProtocol()),\n _dstServer(MessageBusParams().addProtocol(_dstProtocol),\n RPCNetworkParams(_slobrok.config()).setIdentity(Identity(\"dst\"))),\n _dstSession(),\n _dstHandler()\n{ }\n\nTestData::~TestData() = default;\n\nbool\nTestData::start()\n{\n _srcSession = _srcServer.mb.createSourceSession(SourceSessionParams().setReplyHandler(_srcHandler));\n if ( ! _srcSession) {\n return false;\n }\n _itrSession = _itrServer.mb.createIntermediateSession(IntermediateSessionParams().setName(\"session\").setMessageHandler(_itrHandler).setReplyHandler(_itrHandler));\n if ( ! _itrSession) {\n return false;\n }\n _dstSession = _dstServer.mb.createDestinationSession(DestinationSessionParams().setName(\"session\").setMessageHandler(_dstHandler));\n if ( ! _dstSession) {\n return false;\n }\n if (!_srcServer.waitSlobrok(\"*\/session\", 2u)) {\n return false;\n }\n return true;\n}\n\nbool\ntestVersionedSend(TestData &data,\n const vespalib::Version &srcVersion,\n const vespalib::Version &itrVersion,\n const vespalib::Version &dstVersion)\n{\n LOG(info, \"Sending from %s through %s to %s.\",\n srcVersion.toString().c_str(), itrVersion.toString().c_str(), dstVersion.toString().c_str());\n data._srcServer.net.setVersion(srcVersion);\n data._itrServer.net.setVersion(itrVersion);\n data._dstServer.net.setVersion(dstVersion);\n\n Message::UP msg(new SimpleMessage(\"foo\"));\n msg->getTrace().setLevel(9);\n if (!EXPECT_TRUE(data._srcSession->send(std::move(msg), Route::parse(\"itr\/session dst\/session\")).isAccepted())) {\n return false;\n }\n msg = data._itrHandler.getMessage(TIMEOUT_SECS);\n if (!EXPECT_TRUE(msg)) {\n return false;\n }\n LOG(info, \"Message version %s serialized at source.\",\n data._srcProtocol->getLastVersion().toString().c_str());\n vespalib::Version minVersion = std::min(srcVersion, itrVersion);\n if (!EXPECT_TRUE(minVersion == data._srcProtocol->getLastVersion())) {\n return false;\n }\n\n LOG(info, \"Message version %s reached intermediate.\",\n data._itrProtocol->getLastVersion().toString().c_str());\n if (!EXPECT_TRUE(minVersion == data._itrProtocol->getLastVersion())) {\n return false;\n }\n data._itrSession->forward(std::move(msg));\n msg = data._dstHandler.getMessage(TIMEOUT_SECS);\n if (!EXPECT_TRUE(msg)) {\n return false;\n }\n LOG(info, \"Message version %s serialized at intermediate.\",\n data._itrProtocol->getLastVersion().toString().c_str());\n minVersion = std::min(itrVersion, dstVersion);\n if (!EXPECT_TRUE(minVersion == data._itrProtocol->getLastVersion())) {\n return false;\n }\n\n LOG(info, \"Message version %s reached destination.\",\n data._dstProtocol->getLastVersion().toString().c_str());\n if (!EXPECT_TRUE(minVersion == data._dstProtocol->getLastVersion())) {\n return false;\n }\n Reply::UP reply(new SimpleReply(\"bar\"));\n reply->swapState(*msg);\n data._dstSession->reply(std::move(reply));\n reply = data._itrHandler.getReply();\n if (!EXPECT_TRUE(reply)) {\n return false;\n }\n LOG(info, \"Reply version %s serialized at destination.\",\n data._dstProtocol->getLastVersion().toString().c_str());\n if (!EXPECT_TRUE(minVersion == data._dstProtocol->getLastVersion())) {\n return false;\n }\n\n LOG(info, \"Reply version %s reached intermediate.\",\n data._itrProtocol->getLastVersion().toString().c_str());\n if (!EXPECT_TRUE(minVersion == data._itrProtocol->getLastVersion())) {\n return false;\n }\n data._itrSession->forward(std::move(reply));\n reply = data._srcHandler.getReply();\n if (!EXPECT_TRUE(reply)) {\n return false;\n }\n LOG(info, \"Reply version %s serialized at intermediate.\",\n data._dstProtocol->getLastVersion().toString().c_str());\n minVersion = std::min(srcVersion, itrVersion);\n if (!EXPECT_TRUE(minVersion == data._itrProtocol->getLastVersion())) {\n return false;\n }\n\n LOG(info, \"Reply version %s reached source.\",\n data._srcProtocol->getLastVersion().toString().c_str());\n if (!EXPECT_TRUE(minVersion == data._srcProtocol->getLastVersion())) {\n return false;\n }\n return true;\n}\n\n\nvoid\ntestSendAdapters(TestData &data, const std::vector & versions)\n{\n for (vespalib::Version src : versions) {\n for (vespalib::Version intermediate : versions) {\n for (vespalib::Version dst : versions) {\n EXPECT_TRUE(testVersionedSend(data, src, intermediate, dst));\n }\n }\n }\n}\n\nTEST(\"test that all known versions are present\") {\n TestData data;\n ASSERT_TRUE(data.start());\n EXPECT_FALSE(data._srcServer.net.getSendAdapter(vespalib::Version(4, 999)) != nullptr);\n EXPECT_TRUE(data._srcServer.net.getSendAdapter(vespalib::Version(5, 0)) != nullptr);\n EXPECT_TRUE(dynamic_cast(data._srcServer.net.getSendAdapter(vespalib::Version(5, 0))) != nullptr);\n EXPECT_TRUE(data._srcServer.net.getSendAdapter(vespalib::Version(6, 148)) != nullptr);\n EXPECT_TRUE(dynamic_cast(data._srcServer.net.getSendAdapter(vespalib::Version(6, 148))) != nullptr);\n EXPECT_TRUE(data._srcServer.net.getSendAdapter(vespalib::Version(6, 149)) != nullptr);\n EXPECT_TRUE(dynamic_cast(data._srcServer.net.getSendAdapter(vespalib::Version(6, 149))) != nullptr);\n EXPECT_TRUE(data._srcServer.net.getSendAdapter(vespalib::Version(9, 999)) != nullptr);\n EXPECT_TRUE(dynamic_cast(data._srcServer.net.getSendAdapter(vespalib::Version(9, 999))) != nullptr);\n}\n\nTEST(\"test that we can send between multiple versions\") {\n TestData data;\n ASSERT_TRUE(data.start());\n TEST_DO(testSendAdapters(data, {vespalib::Version(5, 0), vespalib::Version(6, 148), vespalib::Version(6, 149), vespalib::Version(9, 999)}));\n}\n\nTEST_MAIN() { TEST_RUN_ALL(); }\nNeed larger timeout for testing on satuyrated hw.\/\/ Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \nLOG_SETUP(\"sendadapter_test\");\n\nusing namespace mbus;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Setup\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nclass TestProtocol : public mbus::SimpleProtocol {\nprivate:\n mutable vespalib::Version _lastVersion;\n\npublic:\n typedef std::shared_ptr SP;\n mbus::Blob encode(const vespalib::Version &version, const mbus::Routable &routable) const override {\n _lastVersion = version;\n return mbus::SimpleProtocol::encode(version, routable);\n }\n mbus::Routable::UP decode(const vespalib::Version &version, mbus::BlobRef blob) const override {\n _lastVersion = version;\n return mbus::SimpleProtocol::decode(version, blob);\n }\n const vespalib::Version &getLastVersion() { return _lastVersion; }\n};\n\nclass TestData {\npublic:\n Slobrok _slobrok;\n TestProtocol::SP _srcProtocol;\n TestServer _srcServer;\n SourceSession::UP _srcSession;\n Receptor _srcHandler;\n TestProtocol::SP _itrProtocol;\n TestServer _itrServer;\n IntermediateSession::UP _itrSession;\n Receptor _itrHandler;\n TestProtocol::SP _dstProtocol;\n TestServer _dstServer;\n DestinationSession::UP _dstSession;\n Receptor _dstHandler;\n\npublic:\n TestData();\n ~TestData();\n bool start();\n};\n\nstatic const duration TIMEOUT_SECS = 60s;\n\nTestData::TestData() :\n _slobrok(),\n _srcProtocol(new TestProtocol()),\n _srcServer(MessageBusParams().setRetryPolicy(IRetryPolicy::SP()).addProtocol(_srcProtocol),\n RPCNetworkParams(_slobrok.config())),\n _srcSession(),\n _srcHandler(),\n _itrProtocol(new TestProtocol()),\n _itrServer(MessageBusParams().addProtocol(_itrProtocol),\n RPCNetworkParams(_slobrok.config()).setIdentity(Identity(\"itr\"))),\n _itrSession(),\n _itrHandler(),\n _dstProtocol(new TestProtocol()),\n _dstServer(MessageBusParams().addProtocol(_dstProtocol),\n RPCNetworkParams(_slobrok.config()).setIdentity(Identity(\"dst\"))),\n _dstSession(),\n _dstHandler()\n{ }\n\nTestData::~TestData() = default;\n\nbool\nTestData::start()\n{\n _srcSession = _srcServer.mb.createSourceSession(SourceSessionParams().setReplyHandler(_srcHandler));\n if ( ! _srcSession) {\n return false;\n }\n _itrSession = _itrServer.mb.createIntermediateSession(IntermediateSessionParams().setName(\"session\").setMessageHandler(_itrHandler).setReplyHandler(_itrHandler));\n if ( ! _itrSession) {\n return false;\n }\n _dstSession = _dstServer.mb.createDestinationSession(DestinationSessionParams().setName(\"session\").setMessageHandler(_dstHandler));\n if ( ! _dstSession) {\n return false;\n }\n if (!_srcServer.waitSlobrok(\"*\/session\", 2u)) {\n return false;\n }\n return true;\n}\n\nbool\ntestVersionedSend(TestData &data,\n const vespalib::Version &srcVersion,\n const vespalib::Version &itrVersion,\n const vespalib::Version &dstVersion)\n{\n LOG(info, \"Sending from %s through %s to %s.\",\n srcVersion.toString().c_str(), itrVersion.toString().c_str(), dstVersion.toString().c_str());\n data._srcServer.net.setVersion(srcVersion);\n data._itrServer.net.setVersion(itrVersion);\n data._dstServer.net.setVersion(dstVersion);\n\n Message::UP msg(new SimpleMessage(\"foo\"));\n msg->getTrace().setLevel(9);\n if (!EXPECT_TRUE(data._srcSession->send(std::move(msg), Route::parse(\"itr\/session dst\/session\")).isAccepted())) {\n return false;\n }\n msg = data._itrHandler.getMessage(TIMEOUT_SECS);\n if (!EXPECT_TRUE(msg)) {\n return false;\n }\n LOG(info, \"Message version %s serialized at source.\",\n data._srcProtocol->getLastVersion().toString().c_str());\n vespalib::Version minVersion = std::min(srcVersion, itrVersion);\n if (!EXPECT_TRUE(minVersion == data._srcProtocol->getLastVersion())) {\n return false;\n }\n\n LOG(info, \"Message version %s reached intermediate.\",\n data._itrProtocol->getLastVersion().toString().c_str());\n if (!EXPECT_TRUE(minVersion == data._itrProtocol->getLastVersion())) {\n return false;\n }\n data._itrSession->forward(std::move(msg));\n msg = data._dstHandler.getMessage(TIMEOUT_SECS);\n if (!EXPECT_TRUE(msg)) {\n return false;\n }\n LOG(info, \"Message version %s serialized at intermediate.\",\n data._itrProtocol->getLastVersion().toString().c_str());\n minVersion = std::min(itrVersion, dstVersion);\n if (!EXPECT_TRUE(minVersion == data._itrProtocol->getLastVersion())) {\n return false;\n }\n\n LOG(info, \"Message version %s reached destination.\",\n data._dstProtocol->getLastVersion().toString().c_str());\n if (!EXPECT_TRUE(minVersion == data._dstProtocol->getLastVersion())) {\n return false;\n }\n Reply::UP reply(new SimpleReply(\"bar\"));\n reply->swapState(*msg);\n data._dstSession->reply(std::move(reply));\n reply = data._itrHandler.getReply();\n if (!EXPECT_TRUE(reply)) {\n return false;\n }\n LOG(info, \"Reply version %s serialized at destination.\",\n data._dstProtocol->getLastVersion().toString().c_str());\n if (!EXPECT_TRUE(minVersion == data._dstProtocol->getLastVersion())) {\n return false;\n }\n\n LOG(info, \"Reply version %s reached intermediate.\",\n data._itrProtocol->getLastVersion().toString().c_str());\n if (!EXPECT_TRUE(minVersion == data._itrProtocol->getLastVersion())) {\n return false;\n }\n data._itrSession->forward(std::move(reply));\n reply = data._srcHandler.getReply();\n if (!EXPECT_TRUE(reply)) {\n return false;\n }\n LOG(info, \"Reply version %s serialized at intermediate.\",\n data._dstProtocol->getLastVersion().toString().c_str());\n minVersion = std::min(srcVersion, itrVersion);\n if (!EXPECT_TRUE(minVersion == data._itrProtocol->getLastVersion())) {\n return false;\n }\n\n LOG(info, \"Reply version %s reached source.\",\n data._srcProtocol->getLastVersion().toString().c_str());\n if (!EXPECT_TRUE(minVersion == data._srcProtocol->getLastVersion())) {\n return false;\n }\n return true;\n}\n\n\nvoid\ntestSendAdapters(TestData &data, const std::vector & versions)\n{\n for (vespalib::Version src : versions) {\n for (vespalib::Version intermediate : versions) {\n for (vespalib::Version dst : versions) {\n EXPECT_TRUE(testVersionedSend(data, src, intermediate, dst));\n }\n }\n }\n}\n\nTEST(\"test that all known versions are present\") {\n TestData data;\n ASSERT_TRUE(data.start());\n EXPECT_FALSE(data._srcServer.net.getSendAdapter(vespalib::Version(4, 999)) != nullptr);\n EXPECT_TRUE(data._srcServer.net.getSendAdapter(vespalib::Version(5, 0)) != nullptr);\n EXPECT_TRUE(dynamic_cast(data._srcServer.net.getSendAdapter(vespalib::Version(5, 0))) != nullptr);\n EXPECT_TRUE(data._srcServer.net.getSendAdapter(vespalib::Version(6, 148)) != nullptr);\n EXPECT_TRUE(dynamic_cast(data._srcServer.net.getSendAdapter(vespalib::Version(6, 148))) != nullptr);\n EXPECT_TRUE(data._srcServer.net.getSendAdapter(vespalib::Version(6, 149)) != nullptr);\n EXPECT_TRUE(dynamic_cast(data._srcServer.net.getSendAdapter(vespalib::Version(6, 149))) != nullptr);\n EXPECT_TRUE(data._srcServer.net.getSendAdapter(vespalib::Version(9, 999)) != nullptr);\n EXPECT_TRUE(dynamic_cast(data._srcServer.net.getSendAdapter(vespalib::Version(9, 999))) != nullptr);\n}\n\nTEST(\"test that we can send between multiple versions\") {\n TestData data;\n ASSERT_TRUE(data.start());\n TEST_DO(testSendAdapters(data, {vespalib::Version(5, 0), vespalib::Version(6, 148), vespalib::Version(6, 149), vespalib::Version(9, 999)}));\n}\n\nTEST_MAIN() { TEST_RUN_ALL(); }\n<|endoftext|>"} {"text":"\/\/ Based on Herb Sutter's talk at C++ and beyond 2012\n\/\/ He made T t; mutable which I think is incorrect\n\n#include \n#include \n#include \n#include \n#include \n\ntemplate \nclass Monitor\n{\n\tT t;\n\tstd::mutex m;\npublic:\n\tMonitor(T _t) : t(_t) {}\n\n\ttemplate \n\tauto operator()(F f) -> decltype(f(t))\n\t{\n\t\tstd::lock_guard l(m);\n\t\treturn f(t);\n\t}\n};\n\nint main(int argc, char* argv[])\n{\n\tMonitor async_ios(std::ref(std::cout));\n\t\n\tstd::vector threads;\n\t\n\tthreads.emplace_back([&](){ \n\t\t\tasync_ios(\n\t\t\t\t[](std::ostream& io){ io << \"Hello 1\" << std::endl;}); \n\t\t\t});\n\tthreads.emplace_back([&](){ \n\t\t\tasync_ios(\n\t\t\t\t[](std::ostream& io){ io << \"Hello 2\" << std::endl;}); \n\t\t\t});\n\tthreads.emplace_back([&](){ \n\t\t\tasync_ios(\n\t\t\t\t[](std::ostream& io){ io << \"Hello 3\" << std::endl;}); \n\t\t\t});\n\tthreads.emplace_back([&](){ \n\t\t\tasync_ios(\n\t\t\t\t[](std::ostream& io){ io << \"Hello 4\" << std::endl;}); \n\t\t\t});\n\n\tfor(auto& t : threads) { t.join(); }\n}\n\nUpdate Monitor\/Monitor.cpp\/\/ Based on Herb Sutter's talk at C++ and beyond 2012\n\/\/ He made operator() const which I think is incorrect\n\n#include \n#include \n#include \n#include \n#include \n\ntemplate \nclass Monitor\n{\n\tT t;\n\tstd::mutex m;\npublic:\n\tMonitor(T _t) : t(_t) {}\n\n\ttemplate \n\tauto operator()(F f) -> decltype(f(t))\n\t{\n\t\tstd::lock_guard l(m);\n\t\treturn f(t);\n\t}\n};\n\nint main(int argc, char* argv[])\n{\n\tMonitor async_ios(std::ref(std::cout));\n\t\n\tstd::vector threads;\n\t\n\tthreads.emplace_back([&](){ \n\t\t\tasync_ios(\n\t\t\t\t[](std::ostream& io){ io << \"Hello 1\" << std::endl;}); \n\t\t\t});\n\tthreads.emplace_back([&](){ \n\t\t\tasync_ios(\n\t\t\t\t[](std::ostream& io){ io << \"Hello 2\" << std::endl;}); \n\t\t\t});\n\tthreads.emplace_back([&](){ \n\t\t\tasync_ios(\n\t\t\t\t[](std::ostream& io){ io << \"Hello 3\" << std::endl;}); \n\t\t\t});\n\tthreads.emplace_back([&](){ \n\t\t\tasync_ios(\n\t\t\t\t[](std::ostream& io){ io << \"Hello 4\" << std::endl;}); \n\t\t\t});\n\n\tfor(auto& t : threads) { t.join(); }\n}\n\n<|endoftext|>"} {"text":"\/****************************************************************************\n**\n** Copyright (C) 2009-2010 TECHNOGERMA Systems France and\/or its subsidiary(-ies).\n** Contact: Technogerma Systems France Information (contact@technogerma.fr)\n**\n** This file is part of the CAMP library.\n**\n** CAMP is free software: you can redistribute it and\/or modify\n** it under the terms of the GNU Lesser General Public License as published by\n** the Free Software Foundation, either version 3 of the License, or\n** (at your option) any later version.\n** \n** CAMP is distributed in the hope that it will be useful,\n** but WITHOUT ANY WARRANTY; without even the implied warranty of\n** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n** GNU Lesser General Public License for more details.\n** \n** You should have received a copy of the GNU Lesser General Public License\n** along with CAMP. If not, see .\n**\n****************************************************************************\/\n\n#include \"mapper.hpp\"\n#include \n#include \n\nusing namespace MapperTest;\n\n\/\/-----------------------------------------------------------------------------\nstruct MapperFixture\n{\n MapperFixture()\n {\n metaclass = &camp::classByType();\n }\n\n const camp::Class* metaclass;\n};\n\n\/\/-----------------------------------------------------------------------------\n\/\/ Tests for mappers\n\/\/-----------------------------------------------------------------------------\nBOOST_FIXTURE_TEST_SUITE(MAPPER, MapperFixture)\n\n\/\/-----------------------------------------------------------------------------\nBOOST_AUTO_TEST_CASE(count)\n{\n BOOST_CHECK_EQUAL(metaclass->propertyCount(), MyClass::propertyCount);\n BOOST_CHECK_EQUAL(metaclass->functionCount(), MyClass::functionCount);\n}\n\n\/\/-----------------------------------------------------------------------------\nBOOST_AUTO_TEST_CASE(types)\n{\n BOOST_CHECK_EQUAL(metaclass->property(0).type(), camp::intType);\n BOOST_CHECK_EQUAL(metaclass->function(0).returnType(), camp::stringType);\n}\n\n\/\/-----------------------------------------------------------------------------\nBOOST_AUTO_TEST_CASE(argCount)\n{\n BOOST_CHECK_EQUAL(metaclass->function(0).argCount(), 0);\n}\n\n\/\/-----------------------------------------------------------------------------\nBOOST_AUTO_TEST_CASE(propertyGet)\n{\n MyClass object;\n\n BOOST_CHECK_EQUAL(metaclass->property(\"prop0\").get(object), camp::Value(object.prop(\"prop0\")));\n BOOST_CHECK_EQUAL(metaclass->property(\"prop1\").get(object), camp::Value(object.prop(\"prop1\")));\n BOOST_CHECK_EQUAL(metaclass->property(\"prop2\").get(object), camp::Value(object.prop(\"prop2\")));\n BOOST_CHECK_EQUAL(metaclass->property(\"prop3\").get(object), camp::Value(object.prop(\"prop3\")));\n BOOST_CHECK_EQUAL(metaclass->property(\"prop4\").get(object), camp::Value(object.prop(\"prop4\")));\n}\n\n\/\/-----------------------------------------------------------------------------\nBOOST_AUTO_TEST_CASE(propertySet)\n{\n MyClass object;\n\n metaclass->property(\"prop0\").set(object, 0);\n metaclass->property(\"prop1\").set(object, 100);\n metaclass->property(\"prop2\").set(object, 200);\n metaclass->property(\"prop3\").set(object, 300);\n metaclass->property(\"prop4\").set(object, 400);\n\n BOOST_CHECK_EQUAL(object.prop(\"prop0\"), 0);\n BOOST_CHECK_EQUAL(object.prop(\"prop1\"), 100);\n BOOST_CHECK_EQUAL(object.prop(\"prop2\"), 200);\n BOOST_CHECK_EQUAL(object.prop(\"prop3\"), 300);\n BOOST_CHECK_EQUAL(object.prop(\"prop4\"), 400);\n}\n\n\/\/-----------------------------------------------------------------------------\nBOOST_AUTO_TEST_CASE(functionCall)\n{\n MyClass object;\n\n BOOST_CHECK_EQUAL(metaclass->function(\"func0\").call(object), camp::Value(object.func(\"func0\")));\n BOOST_CHECK_EQUAL(metaclass->function(\"func1\").call(object), camp::Value(object.func(\"func1\")));\n BOOST_CHECK_EQUAL(metaclass->function(\"func2\").call(object), camp::Value(object.func(\"func2\")));\n}\n\nBOOST_AUTO_TEST_SUITE_END()\nFixed a compile error in unit tests\/****************************************************************************\n**\n** Copyright (C) 2009-2010 TECHNOGERMA Systems France and\/or its subsidiary(-ies).\n** Contact: Technogerma Systems France Information (contact@technogerma.fr)\n**\n** This file is part of the CAMP library.\n**\n** CAMP is free software: you can redistribute it and\/or modify\n** it under the terms of the GNU Lesser General Public License as published by\n** the Free Software Foundation, either version 3 of the License, or\n** (at your option) any later version.\n** \n** CAMP is distributed in the hope that it will be useful,\n** but WITHOUT ANY WARRANTY; without even the implied warranty of\n** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n** GNU Lesser General Public License for more details.\n** \n** You should have received a copy of the GNU Lesser General Public License\n** along with CAMP. If not, see .\n**\n****************************************************************************\/\n\n#include \"mapper.hpp\"\n#include \n#include \n\nusing namespace MapperTest;\n\n\/\/-----------------------------------------------------------------------------\nstruct MapperFixture\n{\n MapperFixture()\n {\n metaclass = &camp::classByType();\n }\n\n const camp::Class* metaclass;\n};\n\n\/\/-----------------------------------------------------------------------------\n\/\/ Tests for mappers\n\/\/-----------------------------------------------------------------------------\nBOOST_FIXTURE_TEST_SUITE(MAPPER, MapperFixture)\n\n\/\/-----------------------------------------------------------------------------\nBOOST_AUTO_TEST_CASE(count)\n{\n BOOST_CHECK_EQUAL(metaclass->propertyCount(), static_cast(MyClass::propertyCount));\n BOOST_CHECK_EQUAL(metaclass->functionCount(), static_cast(MyClass::functionCount));\n}\n\n\/\/-----------------------------------------------------------------------------\nBOOST_AUTO_TEST_CASE(types)\n{\n BOOST_CHECK_EQUAL(metaclass->property(0).type(), camp::intType);\n BOOST_CHECK_EQUAL(metaclass->function(0).returnType(), camp::stringType);\n}\n\n\/\/-----------------------------------------------------------------------------\nBOOST_AUTO_TEST_CASE(argCount)\n{\n BOOST_CHECK_EQUAL(metaclass->function(0).argCount(), 0);\n}\n\n\/\/-----------------------------------------------------------------------------\nBOOST_AUTO_TEST_CASE(propertyGet)\n{\n MyClass object;\n\n BOOST_CHECK_EQUAL(metaclass->property(\"prop0\").get(object), camp::Value(object.prop(\"prop0\")));\n BOOST_CHECK_EQUAL(metaclass->property(\"prop1\").get(object), camp::Value(object.prop(\"prop1\")));\n BOOST_CHECK_EQUAL(metaclass->property(\"prop2\").get(object), camp::Value(object.prop(\"prop2\")));\n BOOST_CHECK_EQUAL(metaclass->property(\"prop3\").get(object), camp::Value(object.prop(\"prop3\")));\n BOOST_CHECK_EQUAL(metaclass->property(\"prop4\").get(object), camp::Value(object.prop(\"prop4\")));\n}\n\n\/\/-----------------------------------------------------------------------------\nBOOST_AUTO_TEST_CASE(propertySet)\n{\n MyClass object;\n\n metaclass->property(\"prop0\").set(object, 0);\n metaclass->property(\"prop1\").set(object, 100);\n metaclass->property(\"prop2\").set(object, 200);\n metaclass->property(\"prop3\").set(object, 300);\n metaclass->property(\"prop4\").set(object, 400);\n\n BOOST_CHECK_EQUAL(object.prop(\"prop0\"), 0);\n BOOST_CHECK_EQUAL(object.prop(\"prop1\"), 100);\n BOOST_CHECK_EQUAL(object.prop(\"prop2\"), 200);\n BOOST_CHECK_EQUAL(object.prop(\"prop3\"), 300);\n BOOST_CHECK_EQUAL(object.prop(\"prop4\"), 400);\n}\n\n\/\/-----------------------------------------------------------------------------\nBOOST_AUTO_TEST_CASE(functionCall)\n{\n MyClass object;\n\n BOOST_CHECK_EQUAL(metaclass->function(\"func0\").call(object), camp::Value(object.func(\"func0\")));\n BOOST_CHECK_EQUAL(metaclass->function(\"func1\").call(object), camp::Value(object.func(\"func1\")));\n BOOST_CHECK_EQUAL(metaclass->function(\"func2\").call(object), camp::Value(object.func(\"func2\")));\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n<|endoftext|>"} {"text":"void runProtonAnalysisQA() {\n TStopwatch timer;\n timer.Start();\n \n runProof(200000,\"\/COMMON\/COMMON\/LHC08c11_10TeV_0.5T\"); \/\/use data sets\n \/\/runProof(200); \/\/use ascii files\n \n timer.Stop();\n timer.Print();\n}\n\n\/\/_________________________________________________\/\/\nvoid runProof(Int_t stats = 0, const char* dataset = 0x0) {\n TStopwatch timer;\n timer.Start();\n \n TString outputFilename1 = \"Protons.QA.root\"; \n TString outputFilename2 = \"Protons.MC.QA.root\"; \n TString outputFilename3 = \"Protons.QA.Histograms.root\"; \n\n printf(\"****** Connect to PROOF *******\\n\");\n TProof::Open(\"alicecaf.cern.ch\"); \n gProof->SetParallel();\n\n \/\/ Enable the Analysis Package\n gProof->UploadPackage(\"STEERBase.par\");\n gProof->EnablePackage(\"STEERBase\");\n gProof->UploadPackage(\"ESD.par\");\n gProof->EnablePackage(\"ESD\");\n gProof->UploadPackage(\"AOD.par\");\n gProof->EnablePackage(\"AOD\");\n gProof->UploadPackage(\"ANALYSIS.par\");\n gProof->EnablePackage(\"ANALYSIS\");\n gProof->UploadPackage(\"ANALYSISalice.par\");\n gProof->EnablePackage(\"ANALYSISalice\");\n gProof->UploadPackage(\"CORRFW.par\");\n gProof->EnablePackage(\"CORRFW\");\n gProof->UploadPackage(\"PWG2spectra.par\");\n gProof->EnablePackage(\"PWG2spectra\");\n \n gProof->Load(\"AliAnalysisTaskProtonsQA.cxx++\");\n\n \/\/____________________________________________\/\/\n \/\/ Make the analysis manager\n AliAnalysisManager *mgr = new AliAnalysisManager(\"TestManager\");\n AliVEventHandler* esdH = new AliESDInputHandler;\n mgr->SetInputEventHandler(esdH);\n AliMCEventHandler *mc = new AliMCEventHandler();\n mgr->SetMCtruthEventHandler(mc);\n \n \/\/____________________________________________\/\/\n \/\/ 1st Proton task\n AliAnalysisTaskProtonsQA *taskProtonsQA = new AliAnalysisTaskProtonsQA(\"TaskProtonsQA\");\n mgr->AddTask(taskProtonsQA);\n\n \/\/ Create containers for input\/output\n AliAnalysisDataContainer *cinput1 = mgr->CreateContainer(\"dataChain\",\n\t\t\t\t\t\t\t TChain::Class(),\n\t\t\t\t\t\t\t AliAnalysisManager::kInputContainer);\n AliAnalysisDataContainer *coutput1 = mgr->CreateContainer(\"globalQAList\", \n\t\t\t\t\t\t\t TList::Class(),\n\t\t\t\t\t\t\t AliAnalysisManager::kOutputContainer,\n\t\t\t\t\t\t\t outputFilename1.Data());\n AliAnalysisDataContainer *coutput2 = mgr->CreateContainer(\"pdgCodeList\", \n\t\t\t\t\t\t\t TList::Class(),\n\t\t\t\t\t\t\t AliAnalysisManager::kOutputContainer,\n\t\t\t\t\t\t\t outputFilename2.Data());\n AliAnalysisDataContainer *coutput3 = mgr->CreateContainer(\"mcProcessList\", \n\t\t\t\t\t\t\t TList::Class(),\n\t\t\t\t\t\t\t AliAnalysisManager::kOutputContainer,\n\t\t\t\t\t\t\t outputFilename2.Data());\n AliAnalysisDataContainer *coutput4 = mgr->CreateContainer(\"acceptedCutList\", \n\t\t\t\t\t\t\t TList::Class(),\n\t\t\t\t\t\t\t AliAnalysisManager::kOutputContainer,\n\t\t\t\t\t\t\t outputFilename3.Data());\n AliAnalysisDataContainer *coutput5 = mgr->CreateContainer(\"acceptedDCAList\", \n\t\t\t\t\t\t\t TList::Class(),\n\t\t\t\t\t\t\t AliAnalysisManager::kOutputContainer,\n\t\t\t\t\t\t\t outputFilename3.Data());\n\n \/\/____________________________________________\/\/\n mgr->ConnectInput(taskProtonsQA,0,cinput1);\n mgr->ConnectOutput(taskProtonsQA,0,coutput1);\n mgr->ConnectOutput(taskProtonsQA,1,coutput2);\n mgr->ConnectOutput(taskProtonsQA,2,coutput3);\n mgr->ConnectOutput(taskProtonsQA,3,coutput4);\n mgr->ConnectOutput(taskProtonsQA,4,coutput5);\n if (!mgr->InitAnalysis()) return;\n mgr->PrintStatus();\n\n if(dataset)\n mgr->StartAnalysis(\"proof\",dataset,stats);\n else {\n \/\/ You should get this macro and the txt file from:\n \/\/ http:\/\/aliceinfo.cern.ch\/Offline\/Analysis\/CAF\/\n gROOT->LoadMacro(\"CreateESDChain.C\");\n TChain* chain = 0x0;\n chain = CreateESDChain(\"ESD82XX_30K.txt\",stats);\n chain->SetBranchStatus(\"*Calo*\",0);\n\n mgr->StartAnalysis(\"proof\",chain);\n \/\/mgr->StartAnalysis(\"local\",chain);\n }\n\n timer.Stop();\n timer.Print();\n}\n\n\/\/_________________________________________________\/\/\nInt_t setupPar(const char* pararchivename) {\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ Setup PAR File\/\/\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n if (pararchivename) {\n char processline[1024];\n sprintf(processline,\".! tar xvzf %s.par\",pararchivename);\n gROOT->ProcessLine(processline);\n const char* ocwd = gSystem->WorkingDirectory();\n gSystem->ChangeDirectory(pararchivename);\n \n \/\/ check for BUILD.sh and execute\n if (!gSystem->AccessPathName(\"PROOF-INF\/BUILD.sh\")) {\n printf(\"*******************************\\n\");\n printf(\"*** Building PAR archive ***\\n\");\n printf(\"*******************************\\n\");\n \n if (gSystem->Exec(\"PROOF-INF\/BUILD.sh\")) {\n Error(\"runAnalysis\",\"Cannot Build the PAR Archive! - Abort!\");\n return -1;\n }\n }\n \/\/ check for SETUP.C and execute\n if (!gSystem->AccessPathName(\"PROOF-INF\/SETUP.C\")) {\n printf(\"*******************************\\n\");\n printf(\"*** Setup PAR archive ***\\n\");\n printf(\"*******************************\\n\");\n gROOT->Macro(\"PROOF-INF\/SETUP.C\");\n }\n \n gSystem->ChangeDirectory(\"..\/\");\n } \n return 1;\n}\nAdding the file that didn't want to be added - sorryvoid runProtonAnalysisQA() {\n TStopwatch timer;\n timer.Start();\n \n runProof(200000,\"\/COMMON\/COMMON\/LHC08c11_10TeV_0.5T\"); \/\/use data sets\n \/\/runInteractive(\"wn.xml\");\n \n timer.Stop();\n timer.Print();\n}\n\n\/\/_________________________________________________\/\/\nvoid runInteractive(const char *collectionfile) {\n TString outputFilename1 = \"Protons.QA.root\"; \n TString outputFilename2 = \"Protons.MC.QA.root\"; \n TString outputFilename3 = \"Protons.QA.Histograms.root\"; \n TString outputFilename4 = \"Protons.Efficiency.root\"; \n\n TGrid::Connect(\"alien:\/\/\");\n\n \/\/Setup the par files\n setupPar(\"STEERBase\");\n gSystem->Load(\"libSTEERBase.so\");\n setupPar(\"ESD\");\n gSystem->Load(\"libESD.so\");\n setupPar(\"AOD\");\n gSystem->Load(\"libAOD.so\");\n setupPar(\"ANALYSIS\");\n gSystem->Load(\"libANALYSIS.so\");\n setupPar(\"ANALYSISalice\");\n gSystem->Load(\"libANALYSISalice.so\");\n setupPar(\"CORRFW\");\n gSystem->Load(\"libCORRFW.so\");\n setupPar(\"PWG2spectra\");\n gSystem->Load(\"libPWG2spectra.so\");\n\n gROOT->LoadMacro(\"AliAnalysisTaskProtonsQA.cxx+\");\n \/\/____________________________________________\/\/\n \/\/Usage of event tags\n AliTagAnalysis *analysis = new AliTagAnalysis();\n TChain *chain = 0x0;\n chain = analysis->GetChainFromCollection(collectionfile,\"esdTree\");\n\n \/\/____________________________________________\/\/\n \/\/ Make the analysis manager\n AliAnalysisManager *mgr = new AliAnalysisManager(\"TestManager\");\n AliVEventHandler* esdH = new AliESDInputHandler;\n mgr->SetInputEventHandler(esdH);\n AliMCEventHandler *mc = new AliMCEventHandler();\n mgr->SetMCtruthEventHandler(mc);\n \n \/\/____________________________________________\/\/\n \/\/ 1st Proton task\n AliAnalysisTaskProtonsQA *taskProtonsQA = new AliAnalysisTaskProtonsQA(\"TaskProtonsQA\");\n mgr->AddTask(taskProtonsQA);\n\n \/\/ Create containers for input\/output\n AliAnalysisDataContainer *cinput1 = mgr->CreateContainer(\"dataChain\",\n\t\t\t\t\t\t\t TChain::Class(),\n\t\t\t\t\t\t\t AliAnalysisManager::kInputContainer);\n AliAnalysisDataContainer *coutput1 = mgr->CreateContainer(\"globalQAList\", \n\t\t\t\t\t\t\t TList::Class(),\n\t\t\t\t\t\t\t AliAnalysisManager::kOutputContainer,\n\t\t\t\t\t\t\t outputFilename1.Data());\n AliAnalysisDataContainer *coutput2 = mgr->CreateContainer(\"pdgCodeList\", \n\t\t\t\t\t\t\t TList::Class(),\n\t\t\t\t\t\t\t AliAnalysisManager::kOutputContainer,\n\t\t\t\t\t\t\t outputFilename2.Data());\n AliAnalysisDataContainer *coutput3 = mgr->CreateContainer(\"mcProcessList\", \n\t\t\t\t\t\t\t TList::Class(),\n\t\t\t\t\t\t\t AliAnalysisManager::kOutputContainer,\n\t\t\t\t\t\t\t outputFilename2.Data());\n AliAnalysisDataContainer *coutput4 = mgr->CreateContainer(\"acceptedCutList\", \n\t\t\t\t\t\t\t TList::Class(),\n\t\t\t\t\t\t\t AliAnalysisManager::kOutputContainer,\n\t\t\t\t\t\t\t outputFilename3.Data());\n AliAnalysisDataContainer *coutput5 = mgr->CreateContainer(\"acceptedDCAList\", \n\t\t\t\t\t\t\t TList::Class(),\n\t\t\t\t\t\t\t AliAnalysisManager::kOutputContainer,\n\t\t\t\t\t\t\t outputFilename3.Data());\n AliAnalysisDataContainer *coutput6 = mgr->CreateContainer(\"efficiencyList\", \n\t\t\t\t\t\t\t TList::Class(),\n\t\t\t\t\t\t\t AliAnalysisManager::kOutputContainer,\n\t\t\t\t\t\t\t outputFilename4.Data());\n\n \/\/____________________________________________\/\/\n mgr->ConnectInput(taskProtonsQA,0,cinput1);\n mgr->ConnectOutput(taskProtonsQA,0,coutput1);\n mgr->ConnectOutput(taskProtonsQA,1,coutput2);\n mgr->ConnectOutput(taskProtonsQA,2,coutput3);\n mgr->ConnectOutput(taskProtonsQA,3,coutput4);\n mgr->ConnectOutput(taskProtonsQA,4,coutput5);\n mgr->ConnectOutput(taskProtonsQA,5,coutput6);\n if (!mgr->InitAnalysis()) return;\n mgr->PrintStatus();\n mgr->StartAnalysis(\"local\",chain);\n}\n \n\/\/_________________________________________________\/\/\nvoid runProof(Int_t stats = 0, const char* dataset = 0x0) {\n TString outputFilename1 = \"Protons.QA.root\"; \n TString outputFilename2 = \"Protons.MC.QA.root\"; \n TString outputFilename3 = \"Protons.QA.Histograms.root\"; \n TString outputFilename4 = \"Protons.Efficiency.root\"; \n\n printf(\"****** Connect to PROOF *******\\n\");\n TProof::Open(\"alicecaf.cern.ch\"); \n gProof->SetParallel();\n\n \/\/ Enable the Analysis Package\n gProof->UploadPackage(\"STEERBase.par\");\n gProof->EnablePackage(\"STEERBase\");\n gProof->UploadPackage(\"ESD.par\");\n gProof->EnablePackage(\"ESD\");\n gProof->UploadPackage(\"AOD.par\");\n gProof->EnablePackage(\"AOD\");\n gProof->UploadPackage(\"ANALYSIS.par\");\n gProof->EnablePackage(\"ANALYSIS\");\n gProof->UploadPackage(\"ANALYSISalice.par\");\n gProof->EnablePackage(\"ANALYSISalice\");\n gProof->UploadPackage(\"CORRFW.par\");\n gProof->EnablePackage(\"CORRFW\");\n gProof->UploadPackage(\"PWG2spectra.par\");\n gProof->EnablePackage(\"PWG2spectra\");\n \n gProof->Load(\"AliAnalysisTaskProtonsQA.cxx++\");\n\n \/\/____________________________________________\/\/\n \/\/ Make the analysis manager\n AliAnalysisManager *mgr = new AliAnalysisManager(\"TestManager\");\n AliVEventHandler* esdH = new AliESDInputHandler;\n mgr->SetInputEventHandler(esdH);\n AliMCEventHandler *mc = new AliMCEventHandler();\n mgr->SetMCtruthEventHandler(mc);\n \n \/\/____________________________________________\/\/\n \/\/ 1st Proton task\n AliAnalysisTaskProtonsQA *taskProtonsQA = new AliAnalysisTaskProtonsQA(\"TaskProtonsQA\");\n mgr->AddTask(taskProtonsQA);\n\n \/\/ Create containers for input\/output\n AliAnalysisDataContainer *cinput1 = mgr->CreateContainer(\"dataChain\",\n\t\t\t\t\t\t\t TChain::Class(),\n\t\t\t\t\t\t\t AliAnalysisManager::kInputContainer);\n AliAnalysisDataContainer *coutput1 = mgr->CreateContainer(\"globalQAList\", \n\t\t\t\t\t\t\t TList::Class(),\n\t\t\t\t\t\t\t AliAnalysisManager::kOutputContainer,\n\t\t\t\t\t\t\t outputFilename1.Data());\n AliAnalysisDataContainer *coutput2 = mgr->CreateContainer(\"pdgCodeList\", \n\t\t\t\t\t\t\t TList::Class(),\n\t\t\t\t\t\t\t AliAnalysisManager::kOutputContainer,\n\t\t\t\t\t\t\t outputFilename2.Data());\n AliAnalysisDataContainer *coutput3 = mgr->CreateContainer(\"mcProcessList\", \n\t\t\t\t\t\t\t TList::Class(),\n\t\t\t\t\t\t\t AliAnalysisManager::kOutputContainer,\n\t\t\t\t\t\t\t outputFilename2.Data());\n AliAnalysisDataContainer *coutput4 = mgr->CreateContainer(\"acceptedCutList\", \n\t\t\t\t\t\t\t TList::Class(),\n\t\t\t\t\t\t\t AliAnalysisManager::kOutputContainer,\n\t\t\t\t\t\t\t outputFilename3.Data());\n AliAnalysisDataContainer *coutput5 = mgr->CreateContainer(\"acceptedDCAList\", \n\t\t\t\t\t\t\t TList::Class(),\n\t\t\t\t\t\t\t AliAnalysisManager::kOutputContainer,\n\t\t\t\t\t\t\t outputFilename3.Data());\n AliAnalysisDataContainer *coutput6 = mgr->CreateContainer(\"efficiencyList\", \n\t\t\t\t\t\t\t TList::Class(),\n\t\t\t\t\t\t\t AliAnalysisManager::kOutputContainer,\n\t\t\t\t\t\t\t outputFilename4.Data());\n\n \/\/____________________________________________\/\/\n mgr->ConnectInput(taskProtonsQA,0,cinput1);\n mgr->ConnectOutput(taskProtonsQA,0,coutput1);\n mgr->ConnectOutput(taskProtonsQA,1,coutput2);\n mgr->ConnectOutput(taskProtonsQA,2,coutput3);\n mgr->ConnectOutput(taskProtonsQA,3,coutput4);\n mgr->ConnectOutput(taskProtonsQA,4,coutput5);\n mgr->ConnectOutput(taskProtonsQA,5,coutput6);\n if (!mgr->InitAnalysis()) return;\n mgr->PrintStatus();\n\n if(dataset)\n mgr->StartAnalysis(\"proof\",dataset,stats);\n else {\n \/\/ You should get this macro and the txt file from:\n \/\/ http:\/\/aliceinfo.cern.ch\/Offline\/Analysis\/CAF\/\n gROOT->LoadMacro(\"CreateESDChain.C\");\n TChain* chain = 0x0;\n chain = CreateESDChain(\"ESD82XX_30K.txt\",stats);\n chain->SetBranchStatus(\"*Calo*\",0);\n\n mgr->StartAnalysis(\"proof\",chain);\n \/\/mgr->StartAnalysis(\"local\",chain);\n }\n}\n\n\/\/_________________________________________________\/\/\nInt_t setupPar(const char* pararchivename) {\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ Setup PAR File\/\/\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n if (pararchivename) {\n char processline[1024];\n sprintf(processline,\".! tar xvzf %s.par\",pararchivename);\n gROOT->ProcessLine(processline);\n const char* ocwd = gSystem->WorkingDirectory();\n gSystem->ChangeDirectory(pararchivename);\n \n \/\/ check for BUILD.sh and execute\n if (!gSystem->AccessPathName(\"PROOF-INF\/BUILD.sh\")) {\n printf(\"*******************************\\n\");\n printf(\"*** Building PAR archive ***\\n\");\n printf(\"*******************************\\n\");\n \n if (gSystem->Exec(\"PROOF-INF\/BUILD.sh\")) {\n Error(\"runAnalysis\",\"Cannot Build the PAR Archive! - Abort!\");\n return -1;\n }\n }\n \/\/ check for SETUP.C and execute\n if (!gSystem->AccessPathName(\"PROOF-INF\/SETUP.C\")) {\n printf(\"*******************************\\n\");\n printf(\"*** Setup PAR archive ***\\n\");\n printf(\"*******************************\\n\");\n gROOT->Macro(\"PROOF-INF\/SETUP.C\");\n }\n \n gSystem->ChangeDirectory(\"..\/\");\n } \n return 1;\n}\n<|endoftext|>"} {"text":"\n#include \"tests\/gtest\/gtest.h\"\n#include \n\n#include \"pbrt.h\"\n#include \"rng.h\"\n#include \"efloat.h\"\n#include \"parallel.h\"\n\nstatic float GetFloat(RNG &rng) {\n float f;\n do {\n f = BitsToFloat(rng.UniformUInt32());\n } while (std::isnan(f));\n return f;\n}\n\nstatic double GetDouble(RNG &rng) {\n double d;\n do {\n d = BitsToFloat(uint64_t(rng.UniformUInt32()) |\n (uint64_t(rng.UniformUInt32()) << 32));\n } while (std::isnan(d));\n return d;\n}\n\nTEST(FloatingPoint, NextUpDownFloat) {\n EXPECT_GT(NextFloatUp(-0.f), 0.f);\n EXPECT_LT(NextFloatDown(0.f), 0.f);\n\n EXPECT_EQ(NextFloatUp((float)Infinity), (float)Infinity);\n EXPECT_LT(NextFloatDown((float)Infinity), (float)Infinity);\n\n EXPECT_EQ(NextFloatDown(-(float)Infinity), -(float)Infinity);\n EXPECT_GT(NextFloatUp(-(float)Infinity), -(float)Infinity);\n\n RNG rng;\n for (int i = 0; i < 100000; ++i) {\n float f = GetFloat(rng);\n if (std::isinf(f)) continue;\n\n EXPECT_EQ(std::nextafter(f, (float)Infinity), NextFloatUp(f));\n EXPECT_EQ(std::nextafter(f, -(float)Infinity), NextFloatDown(f));\n }\n}\n\nTEST(FloatingPoint, NextUpDownDouble) {\n EXPECT_GT(NextFloatUp(-0.), 0.);\n EXPECT_LT(NextFloatDown(0.), 0.);\n\n EXPECT_EQ(NextFloatUp((double)Infinity), (double)Infinity);\n EXPECT_LT(NextFloatDown((double)Infinity), (double)Infinity);\n\n EXPECT_EQ(NextFloatDown(-(double)Infinity), -(double)Infinity);\n EXPECT_GT(NextFloatUp(-(double)Infinity), -(double)Infinity);\n\n RNG rng(3);\n for (int i = 0; i < 100000; ++i) {\n double d = GetDouble(rng);\n if (std::isinf(d)) continue;\n\n EXPECT_EQ(std::nextafter(d, (double)Infinity), NextFloatUp(d));\n EXPECT_EQ(std::nextafter(d, -(double)Infinity), NextFloatDown(d));\n }\n}\n\nTEST(FloatingPoint, FloatBits) {\n RNG rng(1);\n for (int i = 0; i < 100000; ++i) {\n uint32_t ui = rng.UniformUInt32();\n float f = BitsToFloat(ui);\n if (std::isnan(f)) continue;\n\n EXPECT_EQ(ui, FloatToBits(f));\n }\n}\n\nTEST(FloatingPoint, DoubleBits) {\n RNG rng(2);\n for (int i = 0; i < 100000; ++i) {\n uint64_t ui = (uint64_t(rng.UniformUInt32()) |\n (uint64_t(rng.UniformUInt32()) << 32));\n double f = BitsToFloat(ui);\n\n if (std::isnan(f)) continue;\n\n EXPECT_EQ(ui, FloatToBits(f));\n }\n}\n\nTEST(FloatingPoint, EFloat) {\n for (int trial = 0; trial < 100000; ++trial) {\n RNG rng(trial);\n \/\/ Return an exponentially-distributed floating-point value.\n auto getFloat = [&rng](Float minExp = -4., Float maxExp = 4.) {\n Float logu = Lerp(rng.UniformFloat(), minExp, maxExp);\n Float sign = rng.UniformFloat() < .5 ? -1. : 1.;\n return sign * std::pow(10, logu);\n };\n\n \/\/ We'll track a value in an EFloat and a precise version of the\n \/\/ same value. As we perform random arithmetic operations to ef,\n \/\/ we'll perform the same operations on efPrecise and make sure\n \/\/ that efPrecise remains within the error bounds that ef has\n \/\/ computed..\n EFloat ef = getFloat();\n long double efPrecise = (float)ef;\n\n for (int iter = 0; iter < 100; ++iter) {\n \/\/ Exit out if we've gone off to a bad place.\n if (std::isnan((float)ef) || std::isnan(efPrecise) ||\n std::isinf((float)ef) || std::isinf(efPrecise) ||\n std::isinf(ef.GetAbsoluteError()))\n break;\n\n \/\/ Make sure that the precise value is inside the bounds of the\n \/\/ EFloat's interval.\n EXPECT_GE(efPrecise, ef.LowerBound()) << \"trial \" << trial\n << \", iter \" << iter;\n EXPECT_LE(efPrecise, ef.UpperBound()) << \"trial \" << trial\n << \", iter \" << iter;\n\n \/\/ Choose a second value to (maybe) use as an operand below.\n EFloat ef2 = 0;\n long double efPrecise2;\n switch (rng.UniformUInt32(3)) {\n case 0: {\n \/\/ Choose a new random floating-point value; assume it is\n \/\/ fully precise.\n Float f = getFloat();\n ef2 = f;\n efPrecise2 = f;\n break;\n }\n case 1:\n \/\/ Use the same value as ef.\n ef2 = ef;\n efPrecise2 = efPrecise;\n break;\n case 2: {\n \/\/ Choose a random float and make up a small interval around it.\n Float f = getFloat();\n Float err = std::abs(getFloat(-8., -2.) * f);\n ef2 = EFloat(f, err);\n \/\/ Now compute a 'precise' value that's not equal to f, but\n \/\/ is instead somewhere within the error bounds.\n Float offset = rng.UniformFloat();\n efPrecise2 = (1. - offset) * ef2.LowerBound() +\n offset * ef2.UpperBound();\n \/\/ Sometimes the result isn't actually inside the bounds,\n \/\/ due to round-off error.\n if (efPrecise2 >= ef2.UpperBound() ||\n efPrecise2 <= ef2.LowerBound())\n efPrecise2 = f;\n#ifndef NDEBUG\n ef2 = EFloat(f, efPrecise2, err);\n#else\n ef2 = EFloat(f, err);\n#endif\n break;\n }\n }\n\n \/\/ Now do a random operation, upading the separate precise\n \/\/ value in the same manner.\n switch (rng.UniformUInt32(7)) {\n case 0:\n \/\/ Negation.\n ef = -ef;\n efPrecise = -efPrecise;\n break;\n case 1:\n \/\/ Addition.\n ef = ef + ef2;\n efPrecise = efPrecise + efPrecise2;\n break;\n case 2:\n \/\/ Subtraction.\n ef = ef - ef2;\n efPrecise = efPrecise - efPrecise2;\n break;\n case 3:\n \/\/ Multiplication.\n ef = ef * ef2;\n efPrecise = efPrecise * efPrecise2;\n break;\n case 4:\n \/\/ Division.\n if (ef.LowerBound() * ef.UpperBound() > 0 &&\n ef2.LowerBound() * ef2.UpperBound() > 0) {\n ef = ef \/ ef2;\n efPrecise = efPrecise \/ efPrecise2;\n }\n break;\n case 5:\n \/\/ Sqrt.\n if (efPrecise >= 0 && ef.LowerBound() > 0) {\n ef = sqrt(ef);\n efPrecise = std::sqrt(efPrecise);\n }\n break;\n case 6:\n \/\/ Abs.\n ef = abs(ef);\n efPrecise = (efPrecise < 0) ? -efPrecise : efPrecise;\n break;\n }\n }\n }\n}\n\nTEST(FloatingPoint, AtomicFloat) {\n AtomicFloat af(0);\n Float f = 0.;\n EXPECT_EQ(f, af);\n af.Add(1.0251);\n f += 1.0251;\n EXPECT_EQ(f, af);\n af.Add(2.);\n f += 2.;\n EXPECT_EQ(f, af);\n}\nImprove EFloat tests.\n#include \"tests\/gtest\/gtest.h\"\n#include \n\n#include \"pbrt.h\"\n#include \"rng.h\"\n#include \"efloat.h\"\n#include \"parallel.h\"\n\nstatic float GetFloat(RNG &rng) {\n float f;\n do {\n f = BitsToFloat(rng.UniformUInt32());\n } while (std::isnan(f));\n return f;\n}\n\nstatic double GetDouble(RNG &rng) {\n double d;\n do {\n d = BitsToFloat(uint64_t(rng.UniformUInt32()) |\n (uint64_t(rng.UniformUInt32()) << 32));\n } while (std::isnan(d));\n return d;\n}\n\nTEST(FloatingPoint, NextUpDownFloat) {\n EXPECT_GT(NextFloatUp(-0.f), 0.f);\n EXPECT_LT(NextFloatDown(0.f), 0.f);\n\n EXPECT_EQ(NextFloatUp((float)Infinity), (float)Infinity);\n EXPECT_LT(NextFloatDown((float)Infinity), (float)Infinity);\n\n EXPECT_EQ(NextFloatDown(-(float)Infinity), -(float)Infinity);\n EXPECT_GT(NextFloatUp(-(float)Infinity), -(float)Infinity);\n\n RNG rng;\n for (int i = 0; i < 100000; ++i) {\n float f = GetFloat(rng);\n if (std::isinf(f)) continue;\n\n EXPECT_EQ(std::nextafter(f, (float)Infinity), NextFloatUp(f));\n EXPECT_EQ(std::nextafter(f, -(float)Infinity), NextFloatDown(f));\n }\n}\n\nTEST(FloatingPoint, NextUpDownDouble) {\n EXPECT_GT(NextFloatUp(-0.), 0.);\n EXPECT_LT(NextFloatDown(0.), 0.);\n\n EXPECT_EQ(NextFloatUp((double)Infinity), (double)Infinity);\n EXPECT_LT(NextFloatDown((double)Infinity), (double)Infinity);\n\n EXPECT_EQ(NextFloatDown(-(double)Infinity), -(double)Infinity);\n EXPECT_GT(NextFloatUp(-(double)Infinity), -(double)Infinity);\n\n RNG rng(3);\n for (int i = 0; i < 100000; ++i) {\n double d = GetDouble(rng);\n if (std::isinf(d)) continue;\n\n EXPECT_EQ(std::nextafter(d, (double)Infinity), NextFloatUp(d));\n EXPECT_EQ(std::nextafter(d, -(double)Infinity), NextFloatDown(d));\n }\n}\n\nTEST(FloatingPoint, FloatBits) {\n RNG rng(1);\n for (int i = 0; i < 100000; ++i) {\n uint32_t ui = rng.UniformUInt32();\n float f = BitsToFloat(ui);\n if (std::isnan(f)) continue;\n\n EXPECT_EQ(ui, FloatToBits(f));\n }\n}\n\nTEST(FloatingPoint, DoubleBits) {\n RNG rng(2);\n for (int i = 0; i < 100000; ++i) {\n uint64_t ui = (uint64_t(rng.UniformUInt32()) |\n (uint64_t(rng.UniformUInt32()) << 32));\n double f = BitsToFloat(ui);\n\n if (std::isnan(f)) continue;\n\n EXPECT_EQ(ui, FloatToBits(f));\n }\n}\n\nTEST(FloatingPoint, AtomicFloat) {\n AtomicFloat af(0);\n Float f = 0.;\n EXPECT_EQ(f, af);\n af.Add(1.0251);\n f += 1.0251;\n EXPECT_EQ(f, af);\n af.Add(2.);\n f += 2.;\n EXPECT_EQ(f, af);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ EFloat tests\n\n\/\/ Return an exponentially-distributed floating-point value.\nstatic EFloat getFloat(RNG &rng, Float minExp = -6., Float maxExp = 6.) {\n Float logu = Lerp(rng.UniformFloat(), minExp, maxExp);\n Float val = std::pow(10, logu);\n\n \/\/ Choose a random error bound.\n Float err = 0;\n switch (rng.UniformUInt32(4)) {\n case 0:\n \/\/ no error\n break;\n case 1: {\n \/\/ small typical\/reasonable error\n uint32_t ulpError = rng.UniformUInt32(1024);\n Float offset = BitsToFloat(FloatToBits(val) + ulpError);\n err = std::abs(offset - val);\n break;\n }\n case 2: {\n \/\/ bigger ~reasonable error\n uint32_t ulpError = rng.UniformUInt32(1024 * 1024);\n Float offset = BitsToFloat(FloatToBits(val) + ulpError);\n err = std::abs(offset - val);\n break;\n }\n case 3: {\n err = (4 * rng.UniformFloat()) * std::abs(val);\n }\n }\n Float sign = rng.UniformFloat() < .5 ? -1. : 1.;\n return EFloat(sign * val, err);\n}\n\n\/\/ Given an EFloat covering some range, choose a double-precision \"precise\"\n\/\/ value that is in the EFloat's range.\nstatic double getPrecise(const EFloat &ef, RNG &rng) {\n switch (rng.UniformUInt32(3)) {\n \/\/ 2\/3 of the time, pick a value that is right at the end of the range;\n \/\/ this is a maximally difficult \/ adversarial choice, so should help\n \/\/ ferret out any bugs.\n case 0:\n return ef.LowerBound();\n case 1:\n return ef.UpperBound();\n case 2: {\n \/\/ Otherwise choose a value uniformly inside the EFloat's range.\n Float t = rng.UniformFloat();\n double p = (1 - t) * ef.LowerBound() + t * ef.UpperBound();\n if (p > ef.UpperBound()) p = ef.UpperBound();\n if (p < ef.LowerBound()) p = ef.LowerBound();\n return p;\n }\n }\n return (Float)ef; \/\/ NOTREACHED\n}\n\nstatic const int kEFloatIters = 1000000;\n\nTEST(EFloat, Abs) {\n for (int trial = 0; trial < kEFloatIters; ++trial) {\n RNG rng(trial);\n\n EFloat ef = getFloat(rng);\n double precise = getPrecise(ef, rng);\n\n EFloat efResult = abs(ef);\n double preciseResult = std::abs(precise);\n\n EXPECT_GE(preciseResult, efResult.LowerBound());\n EXPECT_LE(preciseResult, efResult.UpperBound());\n }\n}\n\nTEST(EFloat, Sqrt) {\n for (int trial = 0; trial < kEFloatIters; ++trial) {\n RNG rng(trial);\n\n EFloat ef = getFloat(rng);\n double precise = getPrecise(ef, rng);\n\n \/\/ If the error starts to get too big such that the interval is\n \/\/ relatively close to zero w.r.t. the center value, we can't\n \/\/ compute error bounds for sqrt; skip these.\n if (ef.GetAbsoluteError() > .25 * std::abs(ef.LowerBound())) continue;\n\n EFloat efResult = sqrt(abs(ef));\n double preciseResult = std::sqrt(std::abs(precise));\n\n EXPECT_GE(preciseResult, efResult.LowerBound());\n EXPECT_LE(preciseResult, efResult.UpperBound());\n }\n}\n\nTEST(EFloat, Add) {\n for (int trial = 0; trial < kEFloatIters; ++trial) {\n RNG rng(trial);\n\n EFloat ef[2] = {getFloat(rng), getFloat(rng)};\n double precise[2] = {getPrecise(ef[0], rng), getPrecise(ef[1], rng)};\n\n EFloat efResult = ef[0] + ef[1];\n float preciseResult = precise[0] + precise[1];\n\n EXPECT_GE(preciseResult, efResult.LowerBound());\n EXPECT_LE(preciseResult, efResult.UpperBound());\n }\n}\n\nTEST(EFloat, Sub) {\n for (int trial = 0; trial < kEFloatIters; ++trial) {\n RNG rng(trial);\n\n EFloat ef[2] = {getFloat(rng), getFloat(rng)};\n double precise[2] = {getPrecise(ef[0], rng), getPrecise(ef[1], rng)};\n\n EFloat efResult = ef[0] - ef[1];\n float preciseResult = precise[0] - precise[1];\n\n EXPECT_GE(preciseResult, efResult.LowerBound());\n EXPECT_LE(preciseResult, efResult.UpperBound());\n }\n}\n\nTEST(EFloat, Mul) {\n for (int trial = 0; trial < kEFloatIters; ++trial) {\n RNG rng(trial);\n\n EFloat ef[2] = {getFloat(rng), getFloat(rng)};\n double precise[2] = {getPrecise(ef[0], rng), getPrecise(ef[1], rng)};\n\n EFloat efResult = ef[0] * ef[1];\n float preciseResult = precise[0] * precise[1];\n\n EXPECT_GE(preciseResult, efResult.LowerBound());\n EXPECT_LE(preciseResult, efResult.UpperBound());\n }\n}\n\nTEST(EFloat, Div) {\n for (int trial = 0; trial < kEFloatIters; ++trial) {\n RNG rng(trial);\n\n EFloat ef[2] = {getFloat(rng), getFloat(rng)};\n double precise[2] = {getPrecise(ef[0], rng), getPrecise(ef[1], rng)};\n\n \/\/ As with sqrt, things get messy if the denominator's interval\n \/\/ straddles zero or is too close to zero w.r.t. its center value.\n if (ef[1].LowerBound() * ef[1].UpperBound() < 0. ||\n ef[1].GetAbsoluteError() > .25 * std::abs(ef[1].LowerBound()))\n continue;\n\n EFloat efResult = ef[0] \/ ef[1];\n float preciseResult = precise[0] \/ precise[1];\n\n EXPECT_GE(preciseResult, efResult.LowerBound());\n EXPECT_LE(preciseResult, efResult.UpperBound());\n }\n}\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \n\n#include \"service.h\"\n#include \"proc-service.h\"\n\n\/\/ Tests of process-service related functionality.\n\/\/\n\/\/ These tests work mostly by completely mocking out the base_process_service class. The mock\n\/\/ implementations can be found in test-baseproc.cc.\n\n\/\/ Friend interface to access base_process_service private\/protected members.\nclass base_process_service_test\n{\n public:\n static void exec_succeeded(base_process_service *bsp)\n {\n bsp->exec_succeeded();\n }\n\n static void handle_exit(base_process_service *bsp, int exit_status)\n {\n bsp->handle_exit_status(exit_status);\n }\n};\n\n\/\/ Regular service start\nvoid test1()\n{\n using namespace std;\n\n service_set sset;\n\n string command = \"test-command\";\n list> command_offsets;\n command_offsets.emplace_back(0, command.length());\n std::list depends;\n\n process_service p = process_service(&sset, \"testproc\", std::move(command), command_offsets, depends);\n p.start(true);\n sset.process_queues();\n\n assert(p.get_state() == service_state_t::STARTING);\n\n base_process_service_test::exec_succeeded(&p);\n sset.process_queues();\n\n assert(p.get_state() == service_state_t::STARTED);\n}\n\n\/\/ Unexpected termination\nvoid test2()\n{\n using namespace std;\n\n service_set sset;\n\n string command = \"test-command\";\n list> command_offsets;\n command_offsets.emplace_back(0, command.length());\n std::list depends;\n\n process_service p = process_service(&sset, \"testproc\", std::move(command), command_offsets, depends);\n p.start(true);\n sset.process_queues();\n\n base_process_service_test::exec_succeeded(&p);\n sset.process_queues();\n\n assert(p.get_state() == service_state_t::STARTED);\n\n base_process_service_test::handle_exit(&p, 0);\n sset.process_queues();\n\n assert(p.get_state() == service_state_t::STOPPED);\n}\n\n\/\/ Termination via stop request\nvoid test3()\n{\n using namespace std;\n\n service_set sset;\n\n string command = \"test-command\";\n list> command_offsets;\n command_offsets.emplace_back(0, command.length());\n std::list depends;\n\n process_service p = process_service(&sset, \"testproc\", std::move(command), command_offsets, depends);\n p.start(true);\n sset.process_queues();\n\n base_process_service_test::exec_succeeded(&p);\n sset.process_queues();\n\n assert(p.get_state() == service_state_t::STARTED);\n\n p.stop(true);\n sset.process_queues();\n\n assert(p.get_state() == service_state_t::STOPPING);\n\n base_process_service_test::handle_exit(&p, 0);\n sset.process_queues();\n\n assert(p.get_state() == service_state_t::STOPPED);\n}\n\n\/\/ Time-out during start\nvoid test4()\n{\n using namespace std;\n\n service_set sset;\n\n string command = \"test-command\";\n list> command_offsets;\n command_offsets.emplace_back(0, command.length());\n std::list depends;\n\n process_service p = process_service(&sset, \"testproc\", std::move(command), command_offsets, depends);\n p.start(true);\n sset.process_queues();\n\n assert(p.get_state() == service_state_t::STARTING);\n\n p.timer_expired();\n sset.process_queues();\n\n assert(p.get_state() == service_state_t::STOPPING);\n\n base_process_service_test::handle_exit(&p, 0);\n sset.process_queues();\n\n assert(p.get_state() == service_state_t::STOPPED);\n}\n\n\n#define RUN_TEST(name) \\\n std::cout << #name \"... \"; \\\n name(); \\\n std::cout << \"PASSED\" << std::endl;\n\nint main(int argc, char **argv)\n{\n RUN_TEST(test1);\n RUN_TEST(test2);\n RUN_TEST(test3);\n RUN_TEST(test4);\n}\nAdd a proc test, and name each test.#include \n#include \n#include \n#include \n#include \n\n#include \"service.h\"\n#include \"proc-service.h\"\n\n\/\/ Tests of process-service related functionality.\n\/\/\n\/\/ These tests work mostly by completely mocking out the base_process_service class. The mock\n\/\/ implementations can be found in test-baseproc.cc.\n\n\/\/ Friend interface to access base_process_service private\/protected members.\nclass base_process_service_test\n{\n public:\n static void exec_succeeded(base_process_service *bsp)\n {\n bsp->exec_succeeded();\n }\n\n static void handle_exit(base_process_service *bsp, int exit_status)\n {\n bsp->handle_exit_status(exit_status);\n }\n};\n\n\/\/ Regular service start\nvoid test_proc_service_start()\n{\n using namespace std;\n\n service_set sset;\n\n string command = \"test-command\";\n list> command_offsets;\n command_offsets.emplace_back(0, command.length());\n std::list depends;\n\n process_service p = process_service(&sset, \"testproc\", std::move(command), command_offsets, depends);\n p.start(true);\n sset.process_queues();\n\n assert(p.get_state() == service_state_t::STARTING);\n\n base_process_service_test::exec_succeeded(&p);\n sset.process_queues();\n\n assert(p.get_state() == service_state_t::STARTED);\n}\n\n\/\/ Unexpected termination\nvoid test_proc_unexpected_term()\n{\n using namespace std;\n\n service_set sset;\n\n string command = \"test-command\";\n list> command_offsets;\n command_offsets.emplace_back(0, command.length());\n std::list depends;\n\n process_service p = process_service(&sset, \"testproc\", std::move(command), command_offsets, depends);\n p.start(true);\n sset.process_queues();\n\n base_process_service_test::exec_succeeded(&p);\n sset.process_queues();\n\n assert(p.get_state() == service_state_t::STARTED);\n\n base_process_service_test::handle_exit(&p, 0);\n sset.process_queues();\n\n assert(p.get_state() == service_state_t::STOPPED);\n}\n\n\/\/ Termination via stop request\nvoid test_term_via_stop()\n{\n using namespace std;\n\n service_set sset;\n\n string command = \"test-command\";\n list> command_offsets;\n command_offsets.emplace_back(0, command.length());\n std::list depends;\n\n process_service p = process_service(&sset, \"testproc\", std::move(command), command_offsets, depends);\n p.start(true);\n sset.process_queues();\n\n base_process_service_test::exec_succeeded(&p);\n sset.process_queues();\n\n assert(p.get_state() == service_state_t::STARTED);\n\n p.stop(true);\n sset.process_queues();\n\n assert(p.get_state() == service_state_t::STOPPING);\n\n base_process_service_test::handle_exit(&p, 0);\n sset.process_queues();\n\n assert(p.get_state() == service_state_t::STOPPED);\n}\n\n\/\/ Time-out during start\nvoid test_proc_start_timeout()\n{\n using namespace std;\n\n service_set sset;\n\n string command = \"test-command\";\n list> command_offsets;\n command_offsets.emplace_back(0, command.length());\n std::list depends;\n\n process_service p = process_service(&sset, \"testproc\", std::move(command), command_offsets, depends);\n p.start(true);\n sset.process_queues();\n\n assert(p.get_state() == service_state_t::STARTING);\n\n p.timer_expired();\n sset.process_queues();\n\n assert(p.get_state() == service_state_t::STOPPING);\n\n base_process_service_test::handle_exit(&p, 0);\n sset.process_queues();\n\n assert(p.get_state() == service_state_t::STOPPED);\n}\n\n\/\/ Smooth recovery\nvoid test_proc_smooth_recovery()\n{\n using namespace std;\n\n service_set sset;\n\n string command = \"test-command\";\n list> command_offsets;\n command_offsets.emplace_back(0, command.length());\n std::list depends;\n\n process_service p = process_service(&sset, \"testproc\", std::move(command), command_offsets, depends);\n p.set_smooth_recovery(true);\n\n p.start(true);\n sset.process_queues();\n\n base_process_service_test::exec_succeeded(&p);\n sset.process_queues();\n\n assert(p.get_state() == service_state_t::STARTED);\n\n base_process_service_test::handle_exit(&p, 0);\n sset.process_queues();\n\n assert(p.get_state() == service_state_t::STARTED);\n}\n\n\n#define RUN_TEST(name, spacing) \\\n std::cout << #name \"...\" spacing; \\\n name(); \\\n std::cout << \"PASSED\" << std::endl;\n\nint main(int argc, char **argv)\n{\n RUN_TEST(test_proc_service_start, \" \");\n RUN_TEST(test_proc_unexpected_term, \" \");\n RUN_TEST(test_term_via_stop, \" \");\n RUN_TEST(test_proc_start_timeout, \" \");\n RUN_TEST(test_proc_smooth_recovery, \" \");\n}\n<|endoftext|>"} {"text":"`save_data_from_gpu_texture_into_file`: convert `format` to base format.<|endoftext|>"} {"text":"\/*!\n * \\copy\n * Copyright (c) 2009-2013, Cisco Systems\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n *\n * * Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in\n * the documentation and\/or other materials provided with the\n * distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n *\n * \\file\tcrt_utils_safe_x.cpp\n *\n * \\brief\tcommon tool\/function utilization\n *\n * \\date\t03\/10\/2009 Created\n *\n *************************************************************************************\n *\/\n\n#include \n#include \n#include \n#include \n#if defined(_WIN32)\n#include \n#include \n#include \n#ifndef _MSC_VER\n#include \n#ifndef HAVE_STRNLEN\n#define strnlen(a,b) strlen(a)\n#endif \/\/!HAVE_STRNLEN\n#endif \/\/!_MSC_VER\n#else\n#include \n#include \n#endif \/\/_WIN32\n\n#include \"macros.h\"\n#include \"crt_util_safe_x.h\"\t\/\/ Safe CRT routines like utils for cross platforms\n\n#if defined(_WIN32) && defined(_MSC_VER)\n\n#if defined(_MSC_VER) && (_MSC_VER>=1500)\n\nint32_t WelsSnprintf (str_t* pBuffer, int32_t iSizeOfBuffer, const str_t* kpFormat, ...) {\n va_list pArgPtr;\n int32_t iRc;\n\n va_start (pArgPtr, kpFormat);\n\n iRc = vsnprintf_s (pBuffer, iSizeOfBuffer, _TRUNCATE, kpFormat, pArgPtr);\n\n va_end (pArgPtr);\n\n return iRc;\n}\n\nstr_t* WelsStrncpy (str_t* pDest, int32_t iSizeInBytes, const str_t* kpSrc, int32_t iCount) {\n strncpy_s (pDest, iSizeInBytes, kpSrc, iCount);\n\n return pDest;\n}\n\nint32_t WelsStrnlen (const str_t* kpStr, int32_t iMaxlen) {\n return strnlen_s (kpStr, iMaxlen);\n}\n\nint32_t WelsVsnprintf (str_t* pBuffer, int32_t iSizeOfBuffer, const str_t* kpFormat, va_list pArgPtr) {\n return vsnprintf_s (pBuffer, iSizeOfBuffer, _TRUNCATE, kpFormat, pArgPtr);\n}\n\nWelsFileHandle* WelsFopen (const str_t* kpFilename, const str_t* kpMode) {\n WelsFileHandle* pFp = NULL;\n if (fopen_s (&pFp, kpFilename, kpMode) != 0) {\n return NULL;\n }\n\n return pFp;\n}\n\nint32_t WelsFclose (WelsFileHandle* pFp) {\n return fclose (pFp);\n}\n\nint32_t WelsGetTimeOfDay (SWelsTime* pTp) {\n return _ftime_s (pTp);\n}\n\nint32_t WelsStrftime (str_t* pBuffer, int32_t iSize, const str_t* kpFormat, const SWelsTime* kpTp) {\n struct tm sTimeNow;\n\n localtime_s (&sTimeNow, &kpTp->time);\n\n return strftime (pBuffer, iSize, kpFormat, &sTimeNow);\n}\n\n#else\n\nint32_t WelsSnprintf (str_t* pBuffer, int32_t iSizeOfBuffer, const str_t* kpFormat, ...) {\n va_list pArgPtr;\n int32_t iRc;\n\n va_start (pArgPtr, kpFormat);\n\n iRc = vsnprintf (pBuffer, iSizeOfBuffer, kpFormat, pArgPtr); \/\/confirmed_safe_unsafe_usage\n\n va_end (pArgPtr);\n\n return iRc;\n}\n\nstr_t* WelsStrncpy (str_t* pDest, int32_t iSizeInBytes, const str_t* kpSrc, int32_t iCount) {\n strncpy (pDest, kpSrc, iCount); \/\/confirmed_safe_unsafe_usage\n\n return pDest;\n}\n\nint32_t WelsStrnlen (const str_t* kpStr, int32_t iMaxlen) {\n return strlen (kpStr); \/\/confirmed_safe_unsafe_usage\n}\n\nint32_t WelsVsnprintf (str_t* pBuffer, int32_t iSizeOfBuffer, const str_t* kpFormat, va_list pArgPtr) {\n return vsnprintf (pBuffer, iSizeOfBuffer, kpFormat, pArgPtr); \/\/confirmed_safe_unsafe_usage\n}\n\n\nWelsFileHandle* WelsFopen (const str_t* kpFilename, const str_t* kpMode) {\n return fopen (kpFilename, kpMode);\n}\n\nint32_t WelsFclose (WelsFileHandle* pFp) {\n return fclose (pFp);\n}\n\nint32_t WelsGetTimeOfDay (SWelsTime* pTp) {\n _ftime (pTp);\n return 0;\n}\n\nint32_t WelsStrftime (str_t* pBuffer, int32_t iSize, const str_t* kpFormat, const SWelsTime* kpTp) {\n struct tm* pTnow;\n\n pTnow = localtime (&kpTp->time);\n\n return strftime (pBuffer, iSize, kpFormat, pTnow);\n}\n\n\n#endif \/\/ _MSC_VER\n\n#else \/\/GCC\n\nint32_t WelsSnprintf (str_t* pBuffer, int32_t iSizeOfBuffer, const str_t* kpFormat, ...) {\n va_list pArgPtr;\n int32_t iRc;\n\n va_start (pArgPtr, kpFormat);\n\n iRc = vsnprintf (pBuffer, iSizeOfBuffer, kpFormat, pArgPtr);\n\n va_end (pArgPtr);\n\n return iRc;\n}\n\nstr_t* WelsStrncpy (str_t* pDest, int32_t iSizeInBytes, const str_t* kpSrc, int32_t iCount) {\n return strncpy (pDest, kpSrc, iCount); \/\/confirmed_safe_unsafe_usage\n}\n\n#if !defined(MACOS) && !defined(UNIX) && !defined(APPLE_IOS)\nint32_t WelsStrnlen (const str_t* kpStr, int32_t iMaxlen) {\n return strnlen (kpStr, iMaxlen); \/\/confirmed_safe_unsafe_usage\n}\n#else\nint32_t WelsStrnlen (const str_t* kpString, int32_t iMaxlen) {\n \/\/ In mac os, there is no strnlen in string.h, we can only use strlen instead of strnlen or\n \/\/ implement strnlen by ourself\n\n#if 1\n return strlen (kpString); \/\/confirmed_safe_unsafe_usage\n#else\n const str_t* kpSrc;\n for (kpSrc = kpString; iMaxlen-- && *kpSrc != '\\0'; ++kpSrc)\n return kpSrc - kpString;\n#endif\n\n}\n#endif\n\nint32_t WelsVsnprintf (str_t* pBuffer, int32_t iSizeOfBuffer, const str_t* kpFormat, va_list pArgPtr) {\n return vsnprintf (pBuffer, iSizeOfBuffer, kpFormat, pArgPtr); \/\/confirmed_safe_unsafe_usage\n}\n\nWelsFileHandle* WelsFopen (const str_t* kpFilename, const str_t* kpMode) {\n return fopen (kpFilename, kpMode);\n}\n\nint32_t WelsFclose (WelsFileHandle* pFp) {\n return fclose (pFp);\n}\n\nint32_t WelsGetTimeOfDay (SWelsTime* pTp) {\n struct timeval sTv;\n\n if (gettimeofday (&sTv, NULL)) {\n return -1;\n }\n\n pTp->time = sTv.tv_sec;\n pTp->millitm = (uint16_t)sTv.tv_usec \/ 1000;\n\n return 0;\n}\n\nint32_t WelsStrftime (str_t* pBuffer, int32_t iSize, const str_t* kpFormat, const SWelsTime* kpTp) {\n struct tm* pTnow;\n\n pTnow = localtime (&kpTp->time);\n\n return strftime (pBuffer, iSize, kpFormat, pTnow);\n}\n\n#endif\n\n\nint32_t WelsFwrite (const void_t* kpBuffer, int32_t iSize, int32_t iCount, WelsFileHandle* pFp) {\n return fwrite (kpBuffer, iSize, iCount, pFp);\n}\n\nuint16_t WelsGetMillsecond (const SWelsTime* kpTp) {\n return kpTp->millitm;\n}\n\nint32_t WelsFflush (WelsFileHandle* pFp) {\n return fflush (pFp);\n}\nMake sure the buffer always is null terminated in the *snprintf calls for old MSVC\/*!\n * \\copy\n * Copyright (c) 2009-2013, Cisco Systems\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n *\n * * Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in\n * the documentation and\/or other materials provided with the\n * distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n *\n * \\file\tcrt_utils_safe_x.cpp\n *\n * \\brief\tcommon tool\/function utilization\n *\n * \\date\t03\/10\/2009 Created\n *\n *************************************************************************************\n *\/\n\n#include \n#include \n#include \n#include \n#if defined(_WIN32)\n#include \n#include \n#include \n#ifndef _MSC_VER\n#include \n#ifndef HAVE_STRNLEN\n#define strnlen(a,b) strlen(a)\n#endif \/\/!HAVE_STRNLEN\n#endif \/\/!_MSC_VER\n#else\n#include \n#include \n#endif \/\/_WIN32\n\n#include \"macros.h\"\n#include \"crt_util_safe_x.h\"\t\/\/ Safe CRT routines like utils for cross platforms\n\n#if defined(_WIN32) && defined(_MSC_VER)\n\n#if defined(_MSC_VER) && (_MSC_VER>=1500)\n\nint32_t WelsSnprintf (str_t* pBuffer, int32_t iSizeOfBuffer, const str_t* kpFormat, ...) {\n va_list pArgPtr;\n int32_t iRc;\n\n va_start (pArgPtr, kpFormat);\n\n iRc = vsnprintf_s (pBuffer, iSizeOfBuffer, _TRUNCATE, kpFormat, pArgPtr);\n\n va_end (pArgPtr);\n\n return iRc;\n}\n\nstr_t* WelsStrncpy (str_t* pDest, int32_t iSizeInBytes, const str_t* kpSrc, int32_t iCount) {\n strncpy_s (pDest, iSizeInBytes, kpSrc, iCount);\n\n return pDest;\n}\n\nint32_t WelsStrnlen (const str_t* kpStr, int32_t iMaxlen) {\n return strnlen_s (kpStr, iMaxlen);\n}\n\nint32_t WelsVsnprintf (str_t* pBuffer, int32_t iSizeOfBuffer, const str_t* kpFormat, va_list pArgPtr) {\n return vsnprintf_s (pBuffer, iSizeOfBuffer, _TRUNCATE, kpFormat, pArgPtr);\n}\n\nWelsFileHandle* WelsFopen (const str_t* kpFilename, const str_t* kpMode) {\n WelsFileHandle* pFp = NULL;\n if (fopen_s (&pFp, kpFilename, kpMode) != 0) {\n return NULL;\n }\n\n return pFp;\n}\n\nint32_t WelsFclose (WelsFileHandle* pFp) {\n return fclose (pFp);\n}\n\nint32_t WelsGetTimeOfDay (SWelsTime* pTp) {\n return _ftime_s (pTp);\n}\n\nint32_t WelsStrftime (str_t* pBuffer, int32_t iSize, const str_t* kpFormat, const SWelsTime* kpTp) {\n struct tm sTimeNow;\n\n localtime_s (&sTimeNow, &kpTp->time);\n\n return strftime (pBuffer, iSize, kpFormat, &sTimeNow);\n}\n\n#else\n\nint32_t WelsSnprintf (str_t* pBuffer, int32_t iSizeOfBuffer, const str_t* kpFormat, ...) {\n va_list pArgPtr;\n int32_t iRc;\n\n va_start (pArgPtr, kpFormat);\n\n iRc = vsnprintf (pBuffer, iSizeOfBuffer, kpFormat, pArgPtr); \/\/confirmed_safe_unsafe_usage\n if (iRc < 0)\n pBuffer[iSizeOfBuffer - 1] = '\\0';\n\n va_end (pArgPtr);\n\n return iRc;\n}\n\nstr_t* WelsStrncpy (str_t* pDest, int32_t iSizeInBytes, const str_t* kpSrc, int32_t iCount) {\n strncpy (pDest, kpSrc, iCount); \/\/confirmed_safe_unsafe_usage\n\n return pDest;\n}\n\nint32_t WelsStrnlen (const str_t* kpStr, int32_t iMaxlen) {\n return strlen (kpStr); \/\/confirmed_safe_unsafe_usage\n}\n\nint32_t WelsVsnprintf (str_t* pBuffer, int32_t iSizeOfBuffer, const str_t* kpFormat, va_list pArgPtr) {\n int32_t iRc = vsnprintf (pBuffer, iSizeOfBuffer, kpFormat, pArgPtr); \/\/confirmed_safe_unsafe_usage\n if (iRc < 0)\n pBuffer[iSizeOfBuffer - 1] = '\\0';\n return iRc;\n}\n\n\nWelsFileHandle* WelsFopen (const str_t* kpFilename, const str_t* kpMode) {\n return fopen (kpFilename, kpMode);\n}\n\nint32_t WelsFclose (WelsFileHandle* pFp) {\n return fclose (pFp);\n}\n\nint32_t WelsGetTimeOfDay (SWelsTime* pTp) {\n _ftime (pTp);\n return 0;\n}\n\nint32_t WelsStrftime (str_t* pBuffer, int32_t iSize, const str_t* kpFormat, const SWelsTime* kpTp) {\n struct tm* pTnow;\n\n pTnow = localtime (&kpTp->time);\n\n return strftime (pBuffer, iSize, kpFormat, pTnow);\n}\n\n\n#endif \/\/ _MSC_VER\n\n#else \/\/GCC\n\nint32_t WelsSnprintf (str_t* pBuffer, int32_t iSizeOfBuffer, const str_t* kpFormat, ...) {\n va_list pArgPtr;\n int32_t iRc;\n\n va_start (pArgPtr, kpFormat);\n\n iRc = vsnprintf (pBuffer, iSizeOfBuffer, kpFormat, pArgPtr);\n\n va_end (pArgPtr);\n\n return iRc;\n}\n\nstr_t* WelsStrncpy (str_t* pDest, int32_t iSizeInBytes, const str_t* kpSrc, int32_t iCount) {\n return strncpy (pDest, kpSrc, iCount); \/\/confirmed_safe_unsafe_usage\n}\n\n#if !defined(MACOS) && !defined(UNIX) && !defined(APPLE_IOS)\nint32_t WelsStrnlen (const str_t* kpStr, int32_t iMaxlen) {\n return strnlen (kpStr, iMaxlen); \/\/confirmed_safe_unsafe_usage\n}\n#else\nint32_t WelsStrnlen (const str_t* kpString, int32_t iMaxlen) {\n \/\/ In mac os, there is no strnlen in string.h, we can only use strlen instead of strnlen or\n \/\/ implement strnlen by ourself\n\n#if 1\n return strlen (kpString); \/\/confirmed_safe_unsafe_usage\n#else\n const str_t* kpSrc;\n for (kpSrc = kpString; iMaxlen-- && *kpSrc != '\\0'; ++kpSrc)\n return kpSrc - kpString;\n#endif\n\n}\n#endif\n\nint32_t WelsVsnprintf (str_t* pBuffer, int32_t iSizeOfBuffer, const str_t* kpFormat, va_list pArgPtr) {\n return vsnprintf (pBuffer, iSizeOfBuffer, kpFormat, pArgPtr); \/\/confirmed_safe_unsafe_usage\n}\n\nWelsFileHandle* WelsFopen (const str_t* kpFilename, const str_t* kpMode) {\n return fopen (kpFilename, kpMode);\n}\n\nint32_t WelsFclose (WelsFileHandle* pFp) {\n return fclose (pFp);\n}\n\nint32_t WelsGetTimeOfDay (SWelsTime* pTp) {\n struct timeval sTv;\n\n if (gettimeofday (&sTv, NULL)) {\n return -1;\n }\n\n pTp->time = sTv.tv_sec;\n pTp->millitm = (uint16_t)sTv.tv_usec \/ 1000;\n\n return 0;\n}\n\nint32_t WelsStrftime (str_t* pBuffer, int32_t iSize, const str_t* kpFormat, const SWelsTime* kpTp) {\n struct tm* pTnow;\n\n pTnow = localtime (&kpTp->time);\n\n return strftime (pBuffer, iSize, kpFormat, pTnow);\n}\n\n#endif\n\n\nint32_t WelsFwrite (const void_t* kpBuffer, int32_t iSize, int32_t iCount, WelsFileHandle* pFp) {\n return fwrite (kpBuffer, iSize, iCount, pFp);\n}\n\nuint16_t WelsGetMillsecond (const SWelsTime* kpTp) {\n return kpTp->millitm;\n}\n\nint32_t WelsFflush (WelsFileHandle* pFp) {\n return fflush (pFp);\n}\n<|endoftext|>"} {"text":"#pragma once\n\/** @defgroup ImageRepresentation Image Representation\n* @brief Storage, visualization and conversion of images\n*\n* Classes in this module are responsible for storing, displaying and converting image data\n*\/\n\n\n#include \"Widget.hpp\"\n\n#ifdef wxUSE_GUI\n\t#include \n#endif\n\nnamespace xv\n{\n\n#ifdef wxUSE_GUI\n\ttypedef wxImage gui_image_t;\n#endif\n\n\/** @addtogroup ImageRepresentation *\/\n\/*@{*\/\n\n\/** @brief An off-screen image representation native to the selected GUI\n*\/\nclass Image : public Widget\n{\n\npublic:\n\tImage();\n\tvirtual ~Image();\nprivate:\n\n\tgui_image_t *m_guiImage;\n\n\tvirtual void render(const cv::Mat&);\n\n\t\/\/\/ Display widget in output mode (without OK\/Cancel buttons)\n\tvirtual void paint(const cv::Mat&);\n\n\t\/\/\/ Check if point is inside the widget\n\tvirtual bool contains(const cv::Point&);\n\n\t\/\/\/ The user clicked the left mouse button over the widget\n\tvirtual void onMouseDown(const cv::Point&);\n\n\t\/\/\/ The user moved the mouse pointer over the widget\n\tvirtual void onMouseMove(const cv::Point&);\n\n\t\/\/\/ The user released the left mouse button over the widget\n\tvirtual void onMouseUp(const cv::Point&);\n};\n\/*@}*\/\n}\nChanged doxygen comment style.#pragma once\n\/** @defgroup ImageRepresentation Image Representation\n* @brief Storage, visualization and conversion of images\n*\n* Classes in this module are responsible for storing, displaying and converting image data.\n*\/\n\n\n#include \"Widget.hpp\"\n\n#ifdef wxUSE_GUI\n\t#include \n#endif\n\nnamespace xv\n{\n\n#ifdef wxUSE_GUI\n\ttypedef wxImage gui_image_t;\n#endif\n\n\/*!\n * \\brief An off-screen image representation native to the selected GUI\n * \\ingroup ImageRepresentation\n *\/\nclass Image : public Widget\n{\n\npublic:\n\tImage();\n\tvirtual ~Image();\nprivate:\n\n\tgui_image_t *m_guiImage;\n\n\tvirtual void render(const cv::Mat&);\n\n\t\/\/\/ Display widget in output mode (without OK\/Cancel buttons)\n\tvirtual void paint(const cv::Mat&);\n\n\t\/\/\/ Check if point is inside the widget\n\tvirtual bool contains(const cv::Point&);\n\n\t\/\/\/ The user clicked the left mouse button over the widget\n\tvirtual void onMouseDown(const cv::Point&);\n\n\t\/\/\/ The user moved the mouse pointer over the widget\n\tvirtual void onMouseMove(const cv::Point&);\n\n\t\/\/\/ The user released the left mouse button over the widget\n\tvirtual void onMouseUp(const cv::Point&);\n};\n\/*@}*\/\n}\n<|endoftext|>"} {"text":"\/*\n * Copyright(c) Sophist Solutions, Inc. 1990-2016. All rights reserved\n *\/\n#include \"..\/StroikaPreComp.h\"\n\n#include \n#include \n\n#include \"..\/Memory\/Common.h\"\n\n#include \"MallocGuard.h\"\n\n\n\nusing namespace Stroika::Foundation;\nusing Memory::Byte;\n\n\n#if qStroika_Foundation_Debug_MallogGuard\nnamespace {\n using GuradBytes_ = Byte[16];\n constexpr GuradBytes_ kMallocGuardHeader_ = { 0xf3, 0xfa, 0x0b, 0x93, 0x48, 0x50, 0x46, 0xe6, 0x22, 0xf1, 0xfa, 0xc0, 0x9a, 0x0b, 0xeb, 0x23, };\n constexpr GuradBytes_ kMallocGuardFooter_ = { 0x07, 0x41, 0xa4, 0x2b, 0xba, 0x97, 0xcb, 0x38, 0x46, 0x1e, 0x3c, 0x42, 0x3c, 0x5f, 0x0c, 0x80, };\n\n \/\/ need header with size, so we can ....\n struct alignas(alignof(long double)) HeaderOrFooter_ {\n GuradBytes_ fGuard;\n size_t fRequestedBlockSize;\n };\n\n\n void OhShit_ ()\n {\n AssertNotReached ();\n std::terminate ();\n }\n\n\n void* ExposedPtrToBackendPtr_ (void* p)\n {\n if (p == nullptr) {\n OhShit_ ();\n }\n return reinterpret_cast (p) - 1;\n }\n void* BackendPtrToExposedPtr_ (void* p)\n {\n if (p == nullptr) {\n OhShit_ ();\n }\n return reinterpret_cast (p) + 1;\n }\n size_t AdjustMallocSize_ (size_t s)\n {\n return s + 2 * sizeof (HeaderOrFooter_);\n }\n\n\n void Validate_ (const HeaderOrFooter_& header, const HeaderOrFooter_& footer)\n {\n if (::memcmp (&header.fGuard, &kMallocGuardHeader_, sizeof (kMallocGuardHeader_)) != 0) {\n OhShit_ ();\n }\n if (::memcmp (&footer.fGuard, &kMallocGuardFooter_, sizeof (kMallocGuardFooter_)) != 0) {\n OhShit_ ();\n }\n if (header.fRequestedBlockSize != footer.fRequestedBlockSize) {\n OhShit_ ();\n }\n \/\/ OK\n }\n void Validate_ (const void* p)\n {\n const HeaderOrFooter_* h = reinterpret_cast (p) - 1;\n const HeaderOrFooter_* fp = reinterpret_cast (reinterpret_cast (p) + h->fRequestedBlockSize);\n HeaderOrFooter_ footer;\n (void)::memcpy (&footer, fp, sizeof (footer)); \/\/ align access\n Validate_ (*h, footer);\n }\n \/\/ returns the pointer to use externally\n void* PatchNewPointer_ (void* p, size_t requestedSize)\n {\n return p;\n }\n\n \/\/ todo variant that does pointer arithmatic\n \/\/ defines that contril how we handle failure (debug failure proc)?\n\n\n}\n#endif\n\n\n#if qStroika_Foundation_Debug_MallogGuard\n\nextern \"C\" void __libc_free (void* __ptr);\nextern \"C\" void* __libc_malloc (size_t __size);\nextern \"C\" void* __libc_realloc (void* __ptr, size_t __size);\nextern \"C\" void* __libc_calloc (size_t __nmemb, size_t __size);\nextern \"C\" void __libc_free (void* __ptr);\nextern \"C\" size_t __malloc_usable_size (void* __ptr);\n\/* Allocate SIZE bytes allocated to ALIGNMENT bytes. *\/\nextern \"C\" void* __libc_memalign (size_t __alignment, size_t __size);\n\n#if 0\nweak_alias (__malloc_info, malloc_info)\n5256\n5257\n5258 strong_alias (__libc_calloc, __calloc) weak_alias (__libc_calloc, calloc)\n5259 strong_alias (__libc_free, __cfree) weak_alias (__libc_free, cfree)\n5260 strong_alias (__libc_free, __free) strong_alias (__libc_free, free)\n5261 strong_alias (__libc_malloc, __malloc) strong_alias (__libc_malloc, malloc)\n5262 strong_alias (__libc_memalign, __memalign)\n5263 weak_alias (__libc_memalign, memalign)\n5264 strong_alias (__libc_realloc, __realloc) strong_alias (__libc_realloc, realloc)\n5265 strong_alias (__libc_valloc, __valloc) weak_alias (__libc_valloc, valloc)\n5266 strong_alias (__libc_pvalloc, __pvalloc) weak_alias (__libc_pvalloc, pvalloc)\n5267 strong_alias (__libc_mallinfo, __mallinfo)\n5268 weak_alias (__libc_mallinfo, mallinfo)\n5269 strong_alias (__libc_mallopt, __mallopt) weak_alias (__libc_mallopt, mallopt)\n5270\n5271 weak_alias (__malloc_stats, malloc_stats)\n5272 weak_alias (__malloc_usable_size, malloc_usable_size)\n5273 weak_alias (__malloc_trim, malloc_trim)\n5274 weak_alias (__malloc_get_state, malloc_get_state)\n5275 weak_alias (__malloc_set_state, malloc_set_state)\n#endif\n\nextern \"C\" void* calloc (size_t __nmemb, size_t __size)\n{\n size_t n = __nmemb * __size;\n void* p = malloc (n);\n (void)::memset (p, 0, n);\n return p;\n}\n\nextern \"C\" void cfree (void* __ptr)\n{\n free (__ptr);\n}\n\nextern \"C\" void free (void* __ptr)\n{\n void* p = ExposedPtrToBackendPtr_ (__ptr);\n __libc_free (p);\n}\n\nextern \"C\" void* malloc (size_t __size)\n{\n void* p = __libc_malloc (AdjustMallocSize_ (__size));\n if (p != nullptr) {\n p = BackendPtrToExposedPtr_ (p);\n }\n return p;\n}\n\nextern \"C\" void* realloc (void* __ptr, size_t __size)\n{\n void* p = ExposedPtrToBackendPtr_ (__ptr);\n size_t n = AdjustMallocSize_ (__size);\n p = __libc_realloc (p, n);\n if (p != nullptr) {\n p = BackendPtrToExposedPtr_ (p);\n }\n return p;\n}\n\nextern \"C\" void* valloc (size_t __size)\n{\n OhShit_ ();\n return nullptr;\n}\n\nextern \"C\" void* pvalloc (size_t __size)\n{\n OhShit_ ();\n return nullptr;\n}\n\nextern \"C\" void* memalign (size_t __alignment, size_t __size)\n{\n OhShit_ ();\n return nullptr;\n}\n#endif\npatch\/validate ptrs on qStroika_Foundation_Debug_MallogGuard\/*\n * Copyright(c) Sophist Solutions, Inc. 1990-2016. All rights reserved\n *\/\n#include \"..\/StroikaPreComp.h\"\n\n#include \n#include \n\n#include \"..\/Memory\/Common.h\"\n\n#include \"MallocGuard.h\"\n\n\n\nusing namespace Stroika::Foundation;\nusing Memory::Byte;\n\n\n#if qStroika_Foundation_Debug_MallogGuard\nnamespace {\n using GuradBytes_ = Byte[16];\n constexpr GuradBytes_ kMallocGuardHeader_ = { 0xf3, 0xfa, 0x0b, 0x93, 0x48, 0x50, 0x46, 0xe6, 0x22, 0xf1, 0xfa, 0xc0, 0x9a, 0x0b, 0xeb, 0x23, };\n constexpr GuradBytes_ kMallocGuardFooter_ = { 0x07, 0x41, 0xa4, 0x2b, 0xba, 0x97, 0xcb, 0x38, 0x46, 0x1e, 0x3c, 0x42, 0x3c, 0x5f, 0x0c, 0x80, };\n\n \/\/ need header with size, so we can ....\n struct alignas(alignof(long double)) HeaderOrFooter_ {\n GuradBytes_ fGuard;\n size_t fRequestedBlockSize;\n };\n\n\n void OhShit_ ()\n {\n AssertNotReached ();\n std::terminate ();\n }\n\n\n void* ExposedPtrToBackendPtr_ (void* p)\n {\n if (p == nullptr) {\n OhShit_ ();\n }\n return reinterpret_cast (p) - 1;\n }\n void* BackendPtrToExposedPtr_ (void* p)\n {\n if (p == nullptr) {\n OhShit_ ();\n }\n return reinterpret_cast (p) + 1;\n }\n size_t AdjustMallocSize_ (size_t s)\n {\n return s + 2 * sizeof (HeaderOrFooter_);\n }\n\n\n void Validate_ (const HeaderOrFooter_& header, const HeaderOrFooter_& footer)\n {\n if (::memcmp (&header.fGuard, &kMallocGuardHeader_, sizeof (kMallocGuardHeader_)) != 0) {\n OhShit_ ();\n }\n if (::memcmp (&footer.fGuard, &kMallocGuardFooter_, sizeof (kMallocGuardFooter_)) != 0) {\n OhShit_ ();\n }\n if (header.fRequestedBlockSize != footer.fRequestedBlockSize) {\n OhShit_ ();\n }\n \/\/ OK\n }\n void ValidateBackendPtr_ (const void* p)\n {\n const HeaderOrFooter_* hp = reinterpret_cast (p);\n const HeaderOrFooter_* fp = reinterpret_cast (reinterpret_cast (hp + 1) + hp->fRequestedBlockSize);\n HeaderOrFooter_ footer;\n (void)::memcpy (&footer, fp, sizeof (footer)); \/\/ align access\n Validate_ (*h, footer);\n }\n void PatchNewPointer_ (void* p, size_t requestedSize)\n {\n HeaderOrFooter_* hp = reinterpret_cast< HeaderOrFooter_*> (p);\n (void)::memcpy (begin (hp->fGuard[0]), begin (kMallocGuardHeader_), NEltsOf (kMallocGuardHeader_));\n hp->fRequestedBlockSize = requestedSize;\n HeaderOrFooter_* fp = reinterpret_cast< HeaderOrFooter_*> (reinterpret_cast (hp + 1) + hp->fRequestedBlockSize);\n (void)::memcpy (begin (fp->fGuard[0]), begin (kMallocGuardFooter_), NEltsOf (kMallocGuardFooter_));\n fp->fRequestedBlockSize = requestedSize;\n return p;\n }\n}\n#endif\n\n\n#if qStroika_Foundation_Debug_MallogGuard\n\nextern \"C\" void __libc_free (void* __ptr);\nextern \"C\" void* __libc_malloc (size_t __size);\nextern \"C\" void* __libc_realloc (void* __ptr, size_t __size);\nextern \"C\" void* __libc_calloc (size_t __nmemb, size_t __size);\nextern \"C\" void __libc_free (void* __ptr);\nextern \"C\" size_t __malloc_usable_size (void* __ptr);\nextern \"C\" void* __libc_memalign (size_t __alignment, size_t __size);\n\n#if 0\nweak_alias (__malloc_info, malloc_info)\n5256\n5257\n5258 strong_alias (__libc_calloc, __calloc) weak_alias (__libc_calloc, calloc)\n5259 strong_alias (__libc_free, __cfree) weak_alias (__libc_free, cfree)\n5260 strong_alias (__libc_free, __free) strong_alias (__libc_free, free)\n5261 strong_alias (__libc_malloc, __malloc) strong_alias (__libc_malloc, malloc)\n5262 strong_alias (__libc_memalign, __memalign)\n5263 weak_alias (__libc_memalign, memalign)\n5264 strong_alias (__libc_realloc, __realloc) strong_alias (__libc_realloc, realloc)\n5265 strong_alias (__libc_valloc, __valloc) weak_alias (__libc_valloc, valloc)\n5266 strong_alias (__libc_pvalloc, __pvalloc) weak_alias (__libc_pvalloc, pvalloc)\n5267 strong_alias (__libc_mallinfo, __mallinfo)\n5268 weak_alias (__libc_mallinfo, mallinfo)\n5269 strong_alias (__libc_mallopt, __mallopt) weak_alias (__libc_mallopt, mallopt)\n5270\n5271 weak_alias (__malloc_stats, malloc_stats)\n5272 weak_alias (__malloc_usable_size, malloc_usable_size)\n5273 weak_alias (__malloc_trim, malloc_trim)\n5274 weak_alias (__malloc_get_state, malloc_get_state)\n5275 weak_alias (__malloc_set_state, malloc_set_state)\n#endif\n\nextern \"C\" void* calloc (size_t __nmemb, size_t __size)\n{\n size_t n = __nmemb * __size;\n void* p = malloc (n);\n (void)::memset (p, 0, n);\n return p;\n}\n\nextern \"C\" void cfree (void* __ptr)\n{\n free (__ptr);\n}\n\nextern \"C\" void free (void* __ptr)\n{\n void* p = ExposedPtrToBackendPtr_ (__ptr);\n ValidateBackendPtr_ (p);\n __libc_free (p);\n}\n\nextern \"C\" void* malloc (size_t __size)\n{\n void* p = __libc_malloc (AdjustMallocSize_ (__size));\n PatchNewPointer_ (p, __size);\n ValidateBackendPtr_ (p);\n if (p != nullptr) {\n p = BackendPtrToExposedPtr_ (p);\n }\n return p;\n}\n\nextern \"C\" void* realloc (void* __ptr, size_t __size)\n{\n void* p = ExposedPtrToBackendPtr_ (__ptr);\n ValidateBackendPtr_ (p);\n size_t n = AdjustMallocSize_ (__size);\n p = __libc_realloc (p, n);\n if (p != nullptr) {\n PatchNewPointer_ (p, __size);\n ValidateBackendPtr_ (p);\n p = BackendPtrToExposedPtr_ (p);\n }\n return p;\n}\n\nextern \"C\" void* valloc (size_t __size)\n{\n OhShit_ ();\n return nullptr;\n}\n\nextern \"C\" void* pvalloc (size_t __size)\n{\n OhShit_ ();\n return nullptr;\n}\n\nextern \"C\" void* memalign (size_t __alignment, size_t __size)\n{\n OhShit_ ();\n return nullptr;\n}\n#endif\n<|endoftext|>"} {"text":"\/*\n* Copyright(c) Sophist Solutions, Inc. 1990-2019. All rights reserved\n*\/\n#include \"..\/..\/StroikaPreComp.h\"\n\n#include \"..\/..\/Characters\/Format.h\"\n#include \"..\/..\/Characters\/ToString.h\"\n#include \"..\/..\/IO\/FileAccessException.h\"\n\n#include \"Socket-Private_.h\"\n\n#include \"Socket.h\"\n\n\/\/ Comment this in to turn on aggressive noisy DbgTrace in this module\n\/\/#define USE_NOISY_TRACE_IN_THIS_MODULE_ 1\n\nusing namespace Stroika::Foundation;\nusing namespace Stroika::Foundation::Characters;\nusing namespace Stroika::Foundation::Execution;\nusing namespace Stroika::Foundation::Memory;\nusing namespace Stroika::Foundation::IO;\nusing namespace Stroika::Foundation::IO::Network;\n\nusing namespace Stroika::Foundation::IO::Network::PRIVATE_;\n\n\/*\n * Notes:\n * http:\/\/stackoverflow.com\/questions\/2693709\/what-was-the-motivation-for-adding-the-ipv6-v6only-flag\n * Windows:\n * https:\/\/msdn.microsoft.com\/en-us\/library\/windows\/desktop\/bb513665(v=vs.85).aspx\n * Windows Vista and later only\n *\n * not sure how to handle this best cuz not every OS will support dual-stack (or will it?) \n *\n * So assume no dual-stack sockets. That seems best --LGP 2017-04-24\n *\/\nnamespace {\n constexpr bool kUseDualStackSockets_ = false; \/\/ opposite of IPV6_V6ONLY\n}\n\n\/*\n ********************************************************************************\n ******************************** Network::Socket *******************************\n ********************************************************************************\n *\/\nSocket::PlatformNativeHandle Socket::mkLowLevelSocket_ (SocketAddress::FamilyType family, Socket::Type socketKind, const optional& protocol)\n{\n#if qPlatform_Windows\n IO::Network::Platform::Windows::WinSock::AssureStarted ();\n#endif\n Socket::PlatformNativeHandle sfd;\n#if qPlatform_POSIX\n ThrowPOSIXErrNoIfNegative (sfd = Handle_ErrNoResultInterruption ([=]() -> int { return socket (static_cast (family), static_cast (socketKind), static_cast (ValueOrDefault (protocol))); }));\n#elif qPlatform_Windows\n DISABLE_COMPILER_MSC_WARNING_START (28193) \/\/ dump warning about examining sfd\n ThrowWSASystemErrorIfSOCKET_ERROR (sfd = ::socket (static_cast (family), static_cast (socketKind), static_cast (ValueOrDefault (protocol))));\n DISABLE_COMPILER_MSC_WARNING_END (28193)\n#else\n AssertNotImplemented ();\n#endif\n if (family == SocketAddress::FamilyType::INET6) {\n int useIPV6Only = not kUseDualStackSockets_;\n#if qPlatform_Linux\n \/\/ Linux follows the RFC, and uses dual-stack mode by default\n constexpr bool kOSDefaultIPV6Only_{false};\n bool mustSet = useIPV6Only != kOSDefaultIPV6Only_;\n#elif qPlatfom_Windows\n \/\/ Windows defaults to NOT dual sockets, so nothing todo for windows\n constexpr bool kOSDefaultIPV6Only_{true};\n bool mustSet = useIPV6Only != kOSDefaultIPV6Only_;\n#else\n bool mustSet = true;\n#endif\n if (mustSet) {\n if (::setsockopt (sfd, IPPROTO_IPV6, IPV6_V6ONLY, reinterpret_cast (&useIPV6Only), sizeof (useIPV6Only)) < 0) {\n AssertNotReached ();\n }\n }\n }\n return sfd;\n}\n\n\/*\n ********************************************************************************\n ***************************** Network::Socket::Ptr *****************************\n ********************************************************************************\n *\/\nSocket::PlatformNativeHandle Socket::Ptr::Detach ()\n{\n lock_guard critSec{*this};\n PlatformNativeHandle h = kINVALID_NATIVE_HANDLE_;\n if (fRep_ != nullptr) {\n h = fRep_->Detach ();\n }\n fRep_.reset ();\n return h;\n}\n\nSocket::Type Socket::Ptr::GetType () const\n{\n shared_lock critSec{*this};\n return getsockopt (SOL_SOCKET, SO_TYPE);\n}\n\nvoid Socket::Ptr::Bind (const SocketAddress& sockAddr, BindFlags bindFlags)\n{\n Debug::TraceContextBumper ctx{Stroika_Foundation_Debug_OptionalizeTraceArgs (L\"IO::Network::Socket::Bind\", L\"sockAddr=%s bindFlags.fReUseAddr=%s\", Characters::ToString (sockAddr).c_str (), Characters::ToString (bindFlags.fReUseAddr).c_str ())};\n lock_guard critSec{*this};\n RequireNotNull (fRep_); \/\/ Construct with Socket::Kind::SOCKET_STREAM?\n\n \/\/ Indicates that the rules used in validating addresses supplied in a bind(2) call should allow\n \/\/ reuse of local addresses. For AF_INET sockets this means that a socket may bind, except when\n \/\/ there is an active listening socket bound to the address. When the listening socket is bound\n \/\/ to INADDR_ANY with a specific port then it is not possible to bind to this port for any local address.\n setsockopt (SOL_SOCKET, SO_REUSEADDR, bindFlags.fReUseAddr ? 1 : 0);\n\n sockaddr_storage useSockAddr = sockAddr.As ();\n PlatformNativeHandle sfd = fRep_->GetNativeSocket ();\n#if qPlatform_Windows\n try {\n ThrowWSASystemErrorIfSOCKET_ERROR (::bind (sfd, (sockaddr*)&useSockAddr, static_cast (sockAddr.GetRequiredSize ())));\n }\n catch (const system_error& e) {\n if (e.code ().category () == system_category () and e.code ().value () == WSAEACCES) {\n Throw (SystemErrorException<> (e.code (), Characters::Format (L\"Cannot Bind to %s: WSAEACCES (probably already bound with SO_EXCLUSIVEADDRUSE)\", Characters::ToString (sockAddr).c_str ())));\n }\n else {\n ReThrow ();\n }\n }\n#else\n \/\/ EACCESS reproted as FileAccessException - which is crazy confusing.\n \/\/ @todo - find a better way, but for now remap this...\n try {\n ThrowPOSIXErrNoIfNegative (Handle_ErrNoResultInterruption ([sfd, &useSockAddr, &sockAddr]() -> int { return ::bind (sfd, (sockaddr*)&useSockAddr, sockAddr.GetRequiredSize ()); }));\n }\n catch (const IO::FileAccessException&) {\n Throw (Exception (Characters::Format (L\"Cannot Bind to %s: EACCESS (probably already bound with SO_EXCLUSIVEADDRUSE)\", Characters::ToString (sockAddr).c_str ())));\n }\n#endif\n catch (...) {\n Throw (Exception (Characters::Format (L\"Cannot Bind to %s: %s\", Characters::ToString (sockAddr).c_str (), Characters::ToString (current_exception ()).c_str ())));\n }\n}\n\nbool Socket::Ptr::IsOpen () const\n{\n shared_lock critSec{*this};\n if (fRep_ != nullptr) {\n return fRep_->GetNativeSocket () != kINVALID_NATIVE_HANDLE_;\n }\n return false;\n}\n\nString Socket::Ptr::ToString () const\n{\n shared_lock critSec{*this};\n StringBuilder sb;\n if (fRep_ == nullptr) {\n sb += L\"nullptr\";\n }\n else {\n sb += L\"{\";\n sb += L\"Native-Socket: \" + ((fRep_->GetNativeSocket () == kINVALID_NATIVE_HANDLE_) ? L\"CLOSED\" : Characters::ToString (fRep_->GetNativeSocket ())) + L\", \";\n if (auto ola = GetLocalAddress ()) {\n sb += L\"Local-Address: \" + Characters::ToString (*ola);\n }\n sb += L\"}\";\n }\n return sb.str ();\n}\nstart using 'activity' exception code in IO::Network::Socket..::Bind () - still needs work but better\/*\n* Copyright(c) Sophist Solutions, Inc. 1990-2019. All rights reserved\n*\/\n#include \"..\/..\/StroikaPreComp.h\"\n\n#include \"..\/..\/Characters\/Format.h\"\n#include \"..\/..\/Characters\/ToString.h\"\n#include \"..\/..\/Execution\/Activity.h\"\n#include \"..\/..\/IO\/FileAccessException.h\"\n\n#include \"Socket-Private_.h\"\n\n#include \"Socket.h\"\n\n\/\/ Comment this in to turn on aggressive noisy DbgTrace in this module\n\/\/#define USE_NOISY_TRACE_IN_THIS_MODULE_ 1\n\nusing namespace Stroika::Foundation;\nusing namespace Stroika::Foundation::Characters;\nusing namespace Stroika::Foundation::Execution;\nusing namespace Stroika::Foundation::Memory;\nusing namespace Stroika::Foundation::IO;\nusing namespace Stroika::Foundation::IO::Network;\n\nusing namespace Stroika::Foundation::IO::Network::PRIVATE_;\n\n\/*\n * Notes:\n * http:\/\/stackoverflow.com\/questions\/2693709\/what-was-the-motivation-for-adding-the-ipv6-v6only-flag\n * Windows:\n * https:\/\/msdn.microsoft.com\/en-us\/library\/windows\/desktop\/bb513665(v=vs.85).aspx\n * Windows Vista and later only\n *\n * not sure how to handle this best cuz not every OS will support dual-stack (or will it?) \n *\n * So assume no dual-stack sockets. That seems best --LGP 2017-04-24\n *\/\nnamespace {\n constexpr bool kUseDualStackSockets_ = false; \/\/ opposite of IPV6_V6ONLY\n}\n\n\/*\n ********************************************************************************\n ******************************** Network::Socket *******************************\n ********************************************************************************\n *\/\nSocket::PlatformNativeHandle Socket::mkLowLevelSocket_ (SocketAddress::FamilyType family, Socket::Type socketKind, const optional& protocol)\n{\n#if qPlatform_Windows\n IO::Network::Platform::Windows::WinSock::AssureStarted ();\n#endif\n Socket::PlatformNativeHandle sfd;\n#if qPlatform_POSIX\n ThrowPOSIXErrNoIfNegative (sfd = Handle_ErrNoResultInterruption ([=]() -> int { return socket (static_cast (family), static_cast (socketKind), static_cast (ValueOrDefault (protocol))); }));\n#elif qPlatform_Windows\n DISABLE_COMPILER_MSC_WARNING_START (28193) \/\/ dump warning about examining sfd\n ThrowWSASystemErrorIfSOCKET_ERROR (sfd = ::socket (static_cast (family), static_cast (socketKind), static_cast (ValueOrDefault (protocol))));\n DISABLE_COMPILER_MSC_WARNING_END (28193)\n#else\n AssertNotImplemented ();\n#endif\n if (family == SocketAddress::FamilyType::INET6) {\n int useIPV6Only = not kUseDualStackSockets_;\n#if qPlatform_Linux\n \/\/ Linux follows the RFC, and uses dual-stack mode by default\n constexpr bool kOSDefaultIPV6Only_{false};\n bool mustSet = useIPV6Only != kOSDefaultIPV6Only_;\n#elif qPlatfom_Windows\n \/\/ Windows defaults to NOT dual sockets, so nothing todo for windows\n constexpr bool kOSDefaultIPV6Only_{true};\n bool mustSet = useIPV6Only != kOSDefaultIPV6Only_;\n#else\n bool mustSet = true;\n#endif\n if (mustSet) {\n if (::setsockopt (sfd, IPPROTO_IPV6, IPV6_V6ONLY, reinterpret_cast (&useIPV6Only), sizeof (useIPV6Only)) < 0) {\n AssertNotReached ();\n }\n }\n }\n return sfd;\n}\n\n\/*\n ********************************************************************************\n ***************************** Network::Socket::Ptr *****************************\n ********************************************************************************\n *\/\nSocket::PlatformNativeHandle Socket::Ptr::Detach ()\n{\n lock_guard critSec{*this};\n PlatformNativeHandle h = kINVALID_NATIVE_HANDLE_;\n if (fRep_ != nullptr) {\n h = fRep_->Detach ();\n }\n fRep_.reset ();\n return h;\n}\n\nSocket::Type Socket::Ptr::GetType () const\n{\n shared_lock critSec{*this};\n return getsockopt (SOL_SOCKET, SO_TYPE);\n}\n\nvoid Socket::Ptr::Bind (const SocketAddress& sockAddr, BindFlags bindFlags)\n{\n Debug::TraceContextBumper ctx{Stroika_Foundation_Debug_OptionalizeTraceArgs (L\"IO::Network::Socket::Bind\", L\"sockAddr=%s bindFlags.fReUseAddr=%s\", Characters::ToString (sockAddr).c_str (), Characters::ToString (bindFlags.fReUseAddr).c_str ())};\n lock_guard critSec{*this};\n RequireNotNull (fRep_); \/\/ Construct with Socket::Kind::SOCKET_STREAM?\n\n auto bindingActivity = Execution::LazyEvalActivity{[&]() -> Characters::String { return L\"binding to \" + Characters::ToString (sockAddr); }};\n [[maybe_unused]] auto&& declareActivity = Execution::DeclareActivity{&bindingActivity};\n\n \/\/ Indicates that the rules used in validating addresses supplied in a bind(2) call should allow\n \/\/ reuse of local addresses. For AF_INET sockets this means that a socket may bind, except when\n \/\/ there is an active listening socket bound to the address. When the listening socket is bound\n \/\/ to INADDR_ANY with a specific port then it is not possible to bind to this port for any local address.\n setsockopt (SOL_SOCKET, SO_REUSEADDR, bindFlags.fReUseAddr ? 1 : 0);\n\n sockaddr_storage useSockAddr = sockAddr.As ();\n PlatformNativeHandle sfd = fRep_->GetNativeSocket ();\n#if qPlatform_Windows\n try {\n ThrowWSASystemErrorIfSOCKET_ERROR (::bind (sfd, (sockaddr*)&useSockAddr, static_cast (sockAddr.GetRequiredSize ())));\n }\n catch (const system_error& e) {\n if (e.code ().category () == system_category () and e.code ().value () == WSAEACCES) {\n \/\/ @todo adjust message to reflect activity ... stuff - redo - this double adds\n Throw (SystemErrorException<> (e.code (), Characters::Format (L\"Cannot Bind to %s: WSAEACCES (probably already bound with SO_EXCLUSIVEADDRUSE)\", Characters::ToString (sockAddr).c_str ())));\n }\n else {\n ReThrow ();\n }\n }\n#else\n \/\/ EACCESS reproted as FileAccessException - which is crazy confusing.\n \/\/ @todo - find a better way, but for now remap this...\n try {\n ThrowPOSIXErrNoIfNegative (Handle_ErrNoResultInterruption ([sfd, &useSockAddr, &sockAddr]() -> int { return ::bind (sfd, (sockaddr*)&useSockAddr, sockAddr.GetRequiredSize ()); }));\n }\n catch (const IO::FileAccessException&) {\n \/\/ @todo adjust message to reflect activity ... stuff - redo - this double adds\n Throw (Exception (Characters::Format (L\"Cannot Bind to %s: EACCESS (probably already bound with SO_EXCLUSIVEADDRUSE)\", Characters::ToString (sockAddr).c_str ())));\n }\n#endif\n catch (...) {\n ReThrow ();\n \/\/ Throw (Exception (Characters::Format (L\"Cannot Bind to %s: %s\", Characters::ToString (sockAddr).c_str (), Characters::ToString (current_exception ()).c_str ())));\n }\n}\n\nbool Socket::Ptr::IsOpen () const\n{\n shared_lock critSec{*this};\n if (fRep_ != nullptr) {\n return fRep_->GetNativeSocket () != kINVALID_NATIVE_HANDLE_;\n }\n return false;\n}\n\nString Socket::Ptr::ToString () const\n{\n shared_lock critSec{*this};\n StringBuilder sb;\n if (fRep_ == nullptr) {\n sb += L\"nullptr\";\n }\n else {\n sb += L\"{\";\n sb += L\"Native-Socket: \" + ((fRep_->GetNativeSocket () == kINVALID_NATIVE_HANDLE_) ? L\"CLOSED\" : Characters::ToString (fRep_->GetNativeSocket ())) + L\", \";\n if (auto ola = GetLocalAddress ()) {\n sb += L\"Local-Address: \" + Characters::ToString (*ola);\n }\n sb += L\"}\";\n }\n return sb.str ();\n}\n<|endoftext|>"} {"text":"\/*===================================================================\n\nThe Medical Imaging Interaction Toolkit (MITK)\n\nCopyright (c) German Cancer Research Center,\nDivision of Medical and Biological Informatics.\nAll rights reserved.\n\nThis software is distributed WITHOUT ANY WARRANTY; without\neven the implied warranty of MERCHANTABILITY or FITNESS FOR\nA PARTICULAR PURPOSE.\n\nSee LICENSE.txt or http:\/\/www.mitk.org for details.\n\n===================================================================*\/\n\n#include \"mitkTestingMacros.h\"\n\n#include \n#include \n\nint mitkWeakPointerTest(int \/*argc*\/, char * \/*argv*\/ [])\n{\n MITK_TEST_BEGIN(\"WeakPointer\")\n\n int deleteEventCallbackCalled = 0;\n\n mitk::WeakPointer weakPointer;\n\n weakPointer.SetDeleteEventCallback([&deleteEventCallbackCalled]()\n {\n ++deleteEventCallbackCalled;\n });\n\n mitk::WeakPointer weakPointer2;\n\n \/\/ Testing constructors and reference counting\n itk::Object::Pointer smartPointer = itk::Object::New();\n mitk::WeakPointer weakPointer3(smartPointer);\n mitk::WeakPointer weakPointer4(weakPointer);\n {\n itk::Object::Pointer tmpSmartPointer(weakPointer.Lock());\n itk::Object::Pointer tmpSmartPointer2(weakPointer2.Lock());\n MITK_TEST_CONDITION_REQUIRED(tmpSmartPointer.GetPointer() == tmpSmartPointer2.GetPointer(),\n \"Testing equal pointers\");\n }\n\n weakPointer = smartPointer;\n weakPointer2 = weakPointer;\n\n MITK_TEST_CONDITION_REQUIRED(1 == smartPointer->GetReferenceCount(), \"Testing reference count\");\n smartPointer = nullptr;\n MITK_TEST_CONDITION_REQUIRED(weakPointer.IsExpired(), \"Testing expired weak pointer (smart pointer assignment)\");\n MITK_TEST_CONDITION_REQUIRED(weakPointer2.IsExpired(), \"Testing expired weak pointer (weak pointer assignment)\");\n MITK_TEST_CONDITION_REQUIRED(weakPointer3.IsExpired(), \"Testing expired weak pointer (smart pointer constructor)\");\n MITK_TEST_CONDITION_REQUIRED(weakPointer4.IsExpired(), \"Testing expired weak pointer (copy constructor)\");\n MITK_TEST_CONDITION_REQUIRED(1 == deleteEventCallbackCalled, \"Testing call of delete event callback\");\n\n MITK_TEST_END()\n}\nPort mitk weak pointer test, add setUp and tearDown\/*===================================================================\n\nThe Medical Imaging Interaction Toolkit (MITK)\n\nCopyright (c) German Cancer Research Center,\nDivision of Medical and Biological Informatics.\nAll rights reserved.\n\nThis software is distributed WITHOUT ANY WARRANTY; without\neven the implied warranty of MERCHANTABILITY or FITNESS FOR\nA PARTICULAR PURPOSE.\n\nSee LICENSE.txt or http:\/\/www.mitk.org for details.\n\n===================================================================*\/\n\n\/\/ Testing\n#include \"mitkTestFixture.h\"\n#include \"mitkTestingMacros.h\"\n\n\/\/ std includes\n#include \n\n\/\/ MITK includes\n#include \n\n\/\/ ITK includes\n#include \n\nclass mitkWeakPointerTestSuite : public mitk::TestFixture\n{\n\tCPPUNIT_TEST_SUITE(mitkWeakPointerTestSuite);\n\n\tMITK_TEST(EqualPointers_Success);\n\tMITK_TEST(ExpiredWeakPointerWithSmartPointerAssignment_Success);\n\tMITK_TEST(ExpiredWeakPointerWithWeakPointerAssignment_Success);\n\tMITK_TEST(ExpiredWeakPointerWithSmartPointerConstructor_Success);\n\tMITK_TEST(ExpiredWeakPointerWithWeakPointerConstructor_Success);\n\tMITK_TEST(DeleteEventCall_Success);\n\n\tCPPUNIT_TEST_SUITE_END();\n\n\nprivate:\n\tmitk::WeakPointer m_WeakPointer;\n\tmitk::WeakPointer m_WeakPointer2;\n\titk::Object::Pointer m_SmartPointer; \n\npublic:\n\tvoid setUp()\n\t{\n\t\tm_SmartPointer = itk::Object::New();\n\t\tm_WeakPointer = m_SmartPointer;\n\t\tm_WeakPointer2 = m_WeakPointer;\n\t}\n\n\tvoid tearDown()\n\t{\n\t\tm_SmartPointer = nullptr;\n\t\tm_WeakPointer = nullptr;\n\t\tm_WeakPointer2 = nullptr;\n\t}\n\n\tvoid EqualPointers_Success()\n\t{\n\t\tint deleteEventCallbackCalled = deleteEventCallbackCalled = 0;\n\t\tm_WeakPointer.SetDeleteEventCallback([&deleteEventCallbackCalled]()\n\t\t{\n\t\t\t++deleteEventCallbackCalled;\n\t\t});\n\t\titk::Object::Pointer tmpSmartPointer(m_WeakPointer.Lock());\n\t\titk::Object::Pointer tmpSmartPointer2(m_WeakPointer2.Lock());\n\t\tCPPUNIT_ASSERT_MESSAGE(\"Testing equal pointers\", tmpSmartPointer.GetPointer() == tmpSmartPointer2.GetPointer());\n\t}\n\n\tvoid ReferenceCountOfPointers_Success()\n\t{\n\t\tCPPUNIT_ASSERT_MESSAGE(\"Testing reference count\", 1 == m_SmartPointer->GetReferenceCount());\n\t}\n\n\tvoid ExpiredWeakPointerWithSmartPointerAssignment_Success()\n\t{\n\t\tm_SmartPointer = nullptr;\n\t\tCPPUNIT_ASSERT_MESSAGE(\"Testing expired weak pointer (smart pointer assignment)\", m_WeakPointer.IsExpired());\n\t}\n\n\tvoid ExpiredWeakPointerWithWeakPointerAssignment_Success()\n\t{\n\t\tm_SmartPointer = nullptr;\n\t\tCPPUNIT_ASSERT_MESSAGE(\"Testing expired weak pointer (weak pointer assignment)\", m_WeakPointer2.IsExpired());\n\t}\n\n\n\tvoid ExpiredWeakPointerWithSmartPointerConstructor_Success()\n\t{\n\t\tint deleteEventCallbackCalled = 0;\n\t\tmitk::WeakPointer weakPointer3(m_SmartPointer);\n\t\tm_WeakPointer.SetDeleteEventCallback([&deleteEventCallbackCalled]()\n\t\t{\n\t\t\t++deleteEventCallbackCalled;\n\t\t});\n\t\tm_SmartPointer = nullptr;\n\t\tCPPUNIT_ASSERT_MESSAGE(\"Testing expired weak pointer (smart pointer constructor)\", weakPointer3.IsExpired());\n\t}\n\n\tvoid ExpiredWeakPointerWithWeakPointerConstructor_Success()\n\t{\n\t\tint deleteEventCallbackCalled = 0;\n\t\tm_WeakPointer.SetDeleteEventCallback([&deleteEventCallbackCalled]()\n\t\t{\n\t\t\t++deleteEventCallbackCalled;\n\t\t});\n\t\tmitk::WeakPointer weakPointer4(m_WeakPointer);\n\t\tm_WeakPointer = m_SmartPointer;\n\t\tm_SmartPointer = nullptr;\n\t\tCPPUNIT_ASSERT_MESSAGE(\"Testing expired weak pointer (copy constructor)\", weakPointer4.IsExpired());\n\t}\n\n\tvoid DeleteEventCall_Success()\n\t{\n\t\tint deleteEventCallbackCalled = 0;\n\t\tm_WeakPointer.SetDeleteEventCallback([&deleteEventCallbackCalled]()\n\t\t{\n\t\t\t++deleteEventCallbackCalled;\n\t\t});\n\t\tm_WeakPointer = m_SmartPointer;\n\t\tm_SmartPointer = nullptr;\n\t\tCPPUNIT_ASSERT_MESSAGE(\"Testing call of delete event callback\", 1 == deleteEventCallbackCalled);\n\t}\n\t\n};\nMITK_TEST_SUITE_REGISTRATION(mitkWeakPointer)\n<|endoftext|>"} {"text":"#include \"stan\/math\/functions\/modified_bessel_first_kind.hpp\"\r\n#include \r\n\r\nTEST(MathFunctions, modified_bessel_first_kind) {\r\n using stan::math::modified_bessel_first_kind;\r\n \r\n EXPECT_FLOAT_EQ(11.301921952136330496356270183217102497412616594, \r\n modified_bessel_first_kind(0,4.0));\r\n EXPECT_FLOAT_EQ(-3.953370217402609396478635740580581287584221595, \r\n modified_bessel_first_kind(1,-3.0));\r\n EXPECT_FLOAT_EQ(-3.953370217402609396478635740580581287584221595, \r\n modified_bessel_first_kind(-1,-3.0));\r\n}\r\nadded failing test#include \r\n#include \r\n\r\nTEST(MathFunctions, modified_bessel_first_kind) {\r\n using stan::math::modified_bessel_first_kind;\r\n \r\n EXPECT_FLOAT_EQ(11.301921952136330496356270183217102497412616594, \r\n modified_bessel_first_kind(0,4.0));\r\n EXPECT_FLOAT_EQ(-3.953370217402609396478635740580581287584221595, \r\n modified_bessel_first_kind(1,-3.0));\r\n EXPECT_FLOAT_EQ(-3.953370217402609396478635740580581287584221595, \r\n modified_bessel_first_kind(-1,-3.0));\r\n}\r\n\r\nTEST(MathFunctions, modified_bessel_first_kind_nan) {\r\n double nan = std::numeric_limits::quiet_NaN();\r\n \r\n EXPECT_THROW(stan::math::modified_bessel_first_kind(1, nan), std::domain_error);\r\n}\r\n<|endoftext|>"} {"text":"\/*********************************************************************\n *\n * Copyright 2011 Intel Corporation\n * All Rights Reserved.\n *\n * Permission is hereby granted, free of charge, to any person\n * obtaining a copy of this software and associated documentation\n * files (the \"Software\"), to deal in the Software without\n * restriction, including without limitation the rights to use, copy,\n * modify, merge, publish, distribute, sublicense, and\/or sell copies\n * of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be\n * included in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS\n * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN\n * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n *\n *********************************************************************\/\n\n\n#include \n\n#include \n\n#include \"os_path.hpp\"\n#include \"trace_tools.hpp\"\n\n\n\nnamespace trace {\n\n\n#if defined(__APPLE__)\n#define CLI_TRACE_VARIABLE \"DYLD_LIBRARY_PATH\"\n#define CLI_TRACE_WRAPPER \"OpenGL\"\n#elif defined(_WIN32)\n#define CLI_TRACE_VARIABLE \"\"\n#define CLI_TRACE_WRAPPER \"opengl32.dll\"\n#else\n#define CLI_TRACE_VARIABLE \"LD_PRELOAD\"\n#define CLI_TRACE_WRAPPER \"glxtrace.so\"\n#endif\n\n\nos::Path\nfindFile(const char *relPath,\n const char *absPath,\n bool verbose)\n{\n os::Path complete;\n\n \/* First look in the same directory from which this process is\n * running, (to support developers running a compiled program that\n * has not been installed. *\/\n os::Path process_dir = os::getProcessName();\n\n process_dir.trimFilename();\n\n complete = process_dir;\n complete.join(relPath);\n\n if (complete.exists())\n return complete;\n\n \/* Second, look in the directory for installed wrappers. *\/\n complete = absPath;\n if (complete.exists())\n return complete;\n\n if (verbose) {\n std::cerr << \"error: cannot find \" << relPath << \" or \" << absPath << \"\\n\";\n }\n\n return \"\";\n}\n\n\nint\ntraceProgram(char * const *argv,\n const char *output,\n bool verbose)\n{\n os::Path wrapper;\n\n wrapper = findFile(\"wrappers\/\" CLI_TRACE_WRAPPER, APITRACE_WRAPPER_INSTALL_DIR CLI_TRACE_WRAPPER, verbose);\n\n if (!wrapper.length()) {\n return 1;\n }\n\n#if defined(_WIN32)\n\n std::cerr <<\n \"The 'apitrace trace' command is not supported for this operating system.\\n\"\n \"Instead, you will need to copy opengl32.dll, d3d8.dll, or d3d9.dll from\\n\"\n APITRACE_WRAPPER_INSTALL_DIR \"\\n\"\n \"to the directory with the application to trace, then run the application.\\n\";\n\n#else\n\n#if defined(__APPLE__)\n \/* On Mac OS X, using DYLD_LIBRARY_PATH, we actually set the\n * directory, not the file. *\/\n wrapper.trimFilename();\n#endif\n\n if (verbose) {\n std::cerr << CLI_TRACE_VARIABLE << \"=\" << wrapper.str() << \"\\n\";\n }\n\n \/* FIXME: Don't modify the current environment *\/\n setenv(CLI_TRACE_VARIABLE, wrapper.str(), 1);\n\n if (output) {\n setenv(\"TRACE_FILE\", output, 1);\n }\n\n if (verbose) {\n const char *sep = \"\";\n for (char * const * arg = argv; *arg; ++arg) {\n std::cerr << *arg << sep;\n sep = \" \";\n }\n std::cerr << \"\\n\";\n }\n\n execvp(argv[0], argv);\n\n unsetenv(CLI_TRACE_VARIABLE);\n if (output) {\n unsetenv(\"TRACE_FILE\");\n }\n\n std::cerr << \"error: Failed to execute \" << argv[0] << \"\\n\";\n#endif\n\n return 1;\n}\n\n\n} \/* namespace trace *\/\nFix \"apitrace trace\" when running from installed location.\/*********************************************************************\n *\n * Copyright 2011 Intel Corporation\n * All Rights Reserved.\n *\n * Permission is hereby granted, free of charge, to any person\n * obtaining a copy of this software and associated documentation\n * files (the \"Software\"), to deal in the Software without\n * restriction, including without limitation the rights to use, copy,\n * modify, merge, publish, distribute, sublicense, and\/or sell copies\n * of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be\n * included in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS\n * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN\n * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n *\n *********************************************************************\/\n\n\n#include \n\n#include \n\n#include \"os_path.hpp\"\n#include \"trace_tools.hpp\"\n\n\n\nnamespace trace {\n\n\n#if defined(__APPLE__)\n#define CLI_TRACE_VARIABLE \"DYLD_LIBRARY_PATH\"\n#define CLI_TRACE_WRAPPER \"OpenGL\"\n#elif defined(_WIN32)\n#define CLI_TRACE_VARIABLE \"\"\n#define CLI_TRACE_WRAPPER \"opengl32.dll\"\n#else\n#define CLI_TRACE_VARIABLE \"LD_PRELOAD\"\n#define CLI_TRACE_WRAPPER \"glxtrace.so\"\n#endif\n\n\nos::Path\nfindFile(const char *relPath,\n const char *absPath,\n bool verbose)\n{\n os::Path complete;\n\n \/* First look in the same directory from which this process is\n * running, (to support developers running a compiled program that\n * has not been installed. *\/\n os::Path process_dir = os::getProcessName();\n\n process_dir.trimFilename();\n\n complete = process_dir;\n complete.join(relPath);\n\n if (complete.exists())\n return complete;\n\n \/* Second, look in the directory for installed wrappers. *\/\n complete = absPath;\n if (complete.exists())\n return complete;\n\n if (verbose) {\n std::cerr << \"error: cannot find \" << relPath << \" or \" << absPath << \"\\n\";\n }\n\n return \"\";\n}\n\n\nint\ntraceProgram(char * const *argv,\n const char *output,\n bool verbose)\n{\n os::Path wrapper;\n\n wrapper = findFile(\"wrappers\/\" CLI_TRACE_WRAPPER, APITRACE_WRAPPER_INSTALL_DIR \"\/\" CLI_TRACE_WRAPPER, verbose);\n\n if (!wrapper.length()) {\n return 1;\n }\n\n#if defined(_WIN32)\n\n std::cerr <<\n \"The 'apitrace trace' command is not supported for this operating system.\\n\"\n \"Instead, you will need to copy opengl32.dll, d3d8.dll, or d3d9.dll from\\n\"\n APITRACE_WRAPPER_INSTALL_DIR \"\\n\"\n \"to the directory with the application to trace, then run the application.\\n\";\n\n#else\n\n#if defined(__APPLE__)\n \/* On Mac OS X, using DYLD_LIBRARY_PATH, we actually set the\n * directory, not the file. *\/\n wrapper.trimFilename();\n#endif\n\n if (verbose) {\n std::cerr << CLI_TRACE_VARIABLE << \"=\" << wrapper.str() << \"\\n\";\n }\n\n \/* FIXME: Don't modify the current environment *\/\n setenv(CLI_TRACE_VARIABLE, wrapper.str(), 1);\n\n if (output) {\n setenv(\"TRACE_FILE\", output, 1);\n }\n\n if (verbose) {\n const char *sep = \"\";\n for (char * const * arg = argv; *arg; ++arg) {\n std::cerr << *arg << sep;\n sep = \" \";\n }\n std::cerr << \"\\n\";\n }\n\n execvp(argv[0], argv);\n\n unsetenv(CLI_TRACE_VARIABLE);\n if (output) {\n unsetenv(\"TRACE_FILE\");\n }\n\n std::cerr << \"error: Failed to execute \" << argv[0] << \"\\n\";\n#endif\n\n return 1;\n}\n\n\n} \/* namespace trace *\/\n<|endoftext|>"} {"text":"AliAnalysisTaskEMCALTriggerQA * AddTaskEMCALTriggerQA(TString outputFile = \"\"){\n \n \n \/\/ Get the pointer to the existing analysis manager via the static access method.\n \/\/==============================================================================\n AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();\n if (!mgr) {\n ::Error(\"AddTaskEMCALTriggerQA\", \"No analysis manager to connect to.\");\n return NULL;\n } \n \n \/\/ Check the analysis type using the event handlers connected to the analysis manager.\n \/\/==============================================================================\n if (!mgr->GetInputEventHandler()) {\n ::Error(\"AddTaskEMCALTriggerQA\", \"This task requires an input event handler\");\n return NULL;\n }\n \n AliAnalysisTaskEMCALTriggerQA * qatrigger = new AliAnalysisTaskEMCALTriggerQA(\"QATrigger\");\n \n AliEMCALRecoUtils * reco = qatrigger->GetRecoUtils();\n reco->SwitchOnRejectExoticCluster();\n \n \/\/ Pass the bad channels, temporary, to fix\n TString fileName=\"$ALICE_ROOT\/OADB\/EMCAL\/EMCALBadChannels.root\";\n AliOADBContainer *contBC=new AliOADBContainer(\"\");\n contBC->InitFromFile((char*)fileName.Data(),\"AliEMCALBadChannels\"); \n TObjArray *arrayBC=(TObjArray*)contBC->GetObject(162500); \/\/ LHC11e run\n if(arrayBC){\n TObjArray *arrayBCpass=(TObjArray*)arrayBC->FindObject(\"pass1\");\n if(arrayBCpass){\n \n reco->SwitchOnBadChannelsRemoval();\n printf(\"trigger REMOVE bad cells \\n\");\n \n for (Int_t i=0; i<10; ++i) {\n TH2I *hbm = reco->GetEMCALChannelStatusMap(i);\n if (hbm)\n delete hbm;\n hbm=(TH2I*)arrayBCpass->FindObject(Form(\"EMCALBadChannelMap_Mod%d\",i));\n \n if (!hbm) {\n AliError(Form(\"Can not get EMCALBadChannelMap_Mod%d\",i));\n continue;\n }\n \n hbm->SetDirectory(0);\n reco->SetEMCALChannelStatusMap(i,hbm);\n }\n } else printf(\"trigger AliEMCALRecoUtils ---Do NOT remove bad channels 1\\n\");\n } else printf(\"trigger AliEMCALRecoUtils ---Do NOT remove bad channels 2\\n\");\n \n \/\/ Extra channels, temporary, need fix\n \n Int_t badAbsID[]={103, 1263, 1275, 1860, 2117, 2298, 2776, 3664, 3665, 3666, 3667, 3668, 3669, 3670, 3671, 3672, 3673, 3674, 3675, 3676, 3677, 3678, 3679, 3712, 3713, 3714, 3715, 3716, 3717, 3718, 3719, 3720, 3721, 3722, 3723, 3724, 3725, 3726, 3727, 3764, 6111, 6800, 6801, 6802, 6803, 6804, 6805, 6806, 6807, 6808, 6809, 6810, 6811, 6812, 6813, 6814, 6815, 7430, 7491, 8352, 8353, 8354, 8356, 8357, 8362, 8808, 8810, 8812, 8814, 9217, 9361, 9704, 9769, 9802, 9837, 9839, 9888, 9946, 10117, 11462,\n 74, 152, 759, 1059, 1175, 1204, 1288, 1376, 1382, 1386, 1519, 1967, 2026, 2047, 2112, 2114, 2115, 2116, 2118, 2119, 2120, 2123, 2124, 2125, 2350, 2506, 2540, 2793, 2891, 2985, 3135, 3503, 4377, 4817, 5600, 5601, 5602, 5603, 5612, 5613, 5614, 5615, 5648, 5649, 5650, 5651, 5660, 5661, 5662, 5663, 5836, 6104, 6481, 7371, 7375, 7425, 7572, 7874, 9269, 9302, 9389, 9696, 9697, 9698, 9700, 9701, 9702, 9703, 9705, 9706, 9707, 9708, 9709, 9710, 9711, 9750, 9758, 9792, 9793, 9794, 9795, 9798, 9800, 9801, 9803, 9804, 9815, 9824, 9825, 9828, 9829, 9830, 9831, 9832, 9833, 9834, 9835, 9836, 9838, 9872, 9874, 9875, 9878, 9882, 9883, 9889, 9890, 9891, 9892, 9893, 9894, 9896, 9897, 9898, 9899, 9900, 9901, 9902, 9903, 9927, 9937, 9938, 9939, 9940, 9941, 9942, 9943, 9947, 9948, 9949, 9950, 9951, 10112, 10113, 10114, 10115, 10116, 10118, 10119, 10120, 10121, 10122, 10123, 10124, 10125, 10718, 10723, 10771, 11042, 11091, 11363,\n 191, 1968, 2210, 2339, 2391, 6331, 7089, 10126, 10127,\n 46, 97, 145, 167, 173, 189, 238, 241, 337, 401, 433, 480, 527, 574, 594, 719, 816, 960, 1008, 1056, 1057, 1102, 1150, 1151, 1152, 1199, 1249, 1423, 1679, 1681, 1822, 1824, 1873, 1918, 2017, 2056, 2110, 2158, 2296, 2332, 2340, 2348, 2351, 2353, 2361, 2381, 2389, 2400, 2434, 2463, 2469, 2481, 2490, 2496, 2519, 2534, 2555, 2590, 2640, 2675, 2687, 2827, 2828, 2830, 2841, 2843, 2869, 2874, 2877, 2878, 2883, 2973, 3022, 3024, 3035, 3039, 3060, 3066, 3070, 3071, 3102, 3109, 3169, 3263, 3275, 3378, 3407, 3412, 4366, 4417, 4558, 4560, 4753, 4797, 8355, 9024, 9025, 9819, 11043};\n \n Int_t iCol = -1, iRow = -1, iSM =-1, iMod = -1,iIphi =-1,iIeta = -1;\n \n AliEMCALGeometry* geom = AliEMCALGeometry::GetInstance(\"EMCAL_COMPLETEV1\");\n \/\/printf(\"Total bad %d\\n\",sizeof(badAbsID)\/sizeof(Int_t));\n for(Int_t i=0;i < sizeof(badAbsID)\/sizeof(Int_t); i++){\n geom->GetCellIndex(badAbsID[i],iSM,iMod,iIphi,iIeta); \n \/\/ Gives SuperModule and Tower numbers\n geom->GetCellPhiEtaIndexInSModule(iSM,iMod,\n iIphi, iIeta,iRow,iCol);\n \/\/printf(\"bad ID %d, col %d, row %d, sm %d, previous status %d\\n\",badAbsID[i],iCol,iRow,iSM, reco->GetEMCALChannelStatus(iSM , iCol, iRow));\n reco->SetEMCALChannelStatus(iSM , iCol, iRow,1);\n }\n \n reco->GetEMCALChannelStatus(8 , 27, 101-4*24);\n reco->GetEMCALChannelStatus(9 , 68-48-2, 111-4*24);\n reco->GetEMCALChannelStatus(3 , 74-48, 31-24);\n \n reco->GetEMCALChannelStatus(8 , 23, 98-4*24);\n reco->GetEMCALChannelStatus(8 , 30, 100-4*24);\n reco->GetEMCALChannelStatus(8 , 31, 100-4*24);\n reco->GetEMCALChannelStatus(8 , 31, 96-4*24);\n \n reco->GetEMCALChannelStatus(8 , 37, 103-4*24);\n reco->GetEMCALChannelStatus(8 , 38, 102-4*24);\n reco->GetEMCALChannelStatus(8 , 39, 102-4*24);\n reco->GetEMCALChannelStatus(8 , 37, 101-4*24);\n reco->GetEMCALChannelStatus(8 , 38, 101-4*24);\n reco->GetEMCALChannelStatus(8 , 39, 101-4*24);\n reco->GetEMCALChannelStatus(8 , 37, 99-4*24);\n reco->GetEMCALChannelStatus(8 , 38, 99-4*24); \n reco->GetEMCALChannelStatus(8 , 39, 99-4*24);\n \n if(outputFile.Length()==0)outputFile = AliAnalysisManager::GetCommonFileName(); \n\n AliAnalysisDataContainer *cinput1 = mgr->GetCommonInputContainer();\n\n AliAnalysisDataContainer *coutput = \n mgr->CreateContainer(\"EMCALQATrigger\", TList::Class(), AliAnalysisManager::kOutputContainer, Form(\"%s:EMCALQATrigger\",outputFile.Data()));\n mgr->AddTask(qatrigger);\n mgr->ConnectInput (qatrigger, 0, cinput1);\n mgr->ConnectOutput (qatrigger, 1, coutput);\n \n return qatrigger;\n \n}\nremove hardcoded bad cells to be removed, pass run number to AODBAliAnalysisTaskEMCALTriggerQA * AddTaskEMCALTriggerQA(TString outputFile = \"\", Int_t run = 0){\n \n \n \/\/ Get the pointer to the existing analysis manager via the static access method.\n \/\/==============================================================================\n AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();\n if (!mgr) {\n ::Error(\"AddTaskEMCALTriggerQA\", \"No analysis manager to connect to.\");\n return NULL;\n } \n \n \/\/ Check the analysis type using the event handlers connected to the analysis manager.\n \/\/==============================================================================\n if (!mgr->GetInputEventHandler()) {\n ::Error(\"AddTaskEMCALTriggerQA\", \"This task requires an input event handler\");\n return NULL;\n }\n \n AliAnalysisTaskEMCALTriggerQA * qatrigger = new AliAnalysisTaskEMCALTriggerQA(\"QATrigger\");\n \n AliEMCALRecoUtils * reco = qatrigger->GetRecoUtils();\n reco->SwitchOnRejectExoticCluster();\n \n \/\/ Pass the bad channels, need to access run number\n TString fileName=\"$ALICE_ROOT\/OADB\/EMCAL\/EMCALBadChannels.root\";\n AliOADBContainer *contBC=new AliOADBContainer(\"\");\n contBC->InitFromFile((char*)fileName.Data(),\"AliEMCALBadChannels\"); \n TObjArray *arrayBC=(TObjArray*)contBC->GetObject(run); \n if(arrayBC){\n TObjArray *arrayBCpass=(TObjArray*)arrayBC->FindObject(\"pass1\");\n if(arrayBCpass){\n \n reco->SwitchOnBadChannelsRemoval();\n printf(\"trigger REMOVE bad cells \\n\");\n \n for (Int_t i=0; i<10; ++i) {\n TH2I *hbm = reco->GetEMCALChannelStatusMap(i);\n if (hbm)\n delete hbm;\n hbm=(TH2I*)arrayBCpass->FindObject(Form(\"EMCALBadChannelMap_Mod%d\",i));\n \n if (!hbm) {\n AliError(Form(\"Can not get EMCALBadChannelMap_Mod%d\",i));\n continue;\n }\n \n hbm->SetDirectory(0);\n reco->SetEMCALChannelStatusMap(i,hbm);\n }\n } else printf(\"trigger AliEMCALRecoUtils ---Do NOT remove bad channels 1\\n\");\n } else printf(\"trigger AliEMCALRecoUtils ---Do NOT remove bad channels 2\\n\");\n \n if(outputFile.Length()==0)outputFile = AliAnalysisManager::GetCommonFileName(); \n\n AliAnalysisDataContainer *cinput1 = mgr->GetCommonInputContainer();\n\n AliAnalysisDataContainer *coutput = \n mgr->CreateContainer(\"EMCALQATrigger\", TList::Class(), AliAnalysisManager::kOutputContainer, Form(\"%s:EMCALQATrigger\",outputFile.Data()));\n mgr->AddTask(qatrigger);\n mgr->ConnectInput (qatrigger, 0, cinput1);\n mgr->ConnectOutput (qatrigger, 1, coutput);\n \n return qatrigger;\n \n}\n<|endoftext|>"} {"text":"\/\/ BushingForce.cpp\r\n\/\/ Author: Ajay Seth\r\n\/*\r\n * Copyright (c) 2010, Stanford University. All rights reserved. \r\n* Use of the OpenSim software in source form is permitted provided that the following\r\n* conditions are met:\r\n* \t1. The software is used only for non-commercial research and education. It may not\r\n* be used in relation to any commercial activity.\r\n* \t2. The software is not distributed or redistributed. Software distribution is allowed \r\n* only through https:\/\/simtk.org\/home\/opensim.\r\n* \t3. Use of the OpenSim software or derivatives must be acknowledged in all publications,\r\n* presentations, or documents describing work in which OpenSim or derivatives are used.\r\n* \t4. Credits to developers may not be removed from executables\r\n* created from modifications of the source.\r\n* \t5. Modifications of source code must retain the above copyright notice, this list of\r\n* conditions and the following disclaimer. \r\n* \r\n* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY\r\n* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\r\n* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT\r\n* SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\r\n* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED\r\n* TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; \r\n* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\r\n* OR BUSINESS INTERRUPTION) OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY\r\n* WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\r\n *\/\r\n\r\n\/\/=============================================================================\r\n\/\/ INCLUDES\r\n\/\/=============================================================================\r\n#include \r\n#include \r\n\r\n#include \"BushingForce.h\"\r\n\r\n\/\/=============================================================================\r\n\/\/ STATICS\r\n\/\/=============================================================================\r\nusing namespace std;\r\nusing namespace SimTK;\r\nusing namespace OpenSim;\r\n\r\n\/\/=============================================================================\r\n\/\/ CONSTRUCTOR(S) AND DESTRUCTOR\r\n\/\/=============================================================================\r\n\/\/_____________________________________________________________________________\r\n\/**\r\n * Destructor.\r\n *\/\r\nBushingForce::~BushingForce()\r\n{\r\n}\r\n\/\/_____________________________________________________________________________\r\n\/**\r\n * Default constructor.\r\n *\/\r\nBushingForce::BushingForce() :\r\n\tForce(),\r\n\t_body1Name(_body1NameProp.getValueStr()),\r\n\t_body2Name(_body2NameProp.getValueStr()),\r\n\t_locationInBody1(_locationInBody1Prop.getValueDblVec3()),\r\n\t_orientationInBody1(_orientationInBody1Prop.getValueDblVec3()),\r\n\t_locationInBody2(_locationInBody2Prop.getValueDblVec3()),\r\n\t_orientationInBody2(_orientationInBody2Prop.getValueDblVec3()),\r\n\t_rotStiffness(_rotStiffnessProp.getValueDblVec3()),\r\n\t_transStiffness(_transStiffnessProp.getValueDblVec3()),\r\n\t_rotDamping(_rotDampingProp.getValueDblVec3()),\r\n\t_transDamping(_transDampingProp.getValueDblVec3())\r\n{\r\n\tsetNull();\r\n}\r\n\r\n\/* Convenience constructor *\/\r\nBushingForce::BushingForce( std::string body1Name, SimTK::Vec3 point1, SimTK::Vec3 orientation1,\r\n\t\t std::string body2Name, SimTK::Vec3 point2, SimTK::Vec3 orientation2,\r\n\t\t\t\t SimTK::Vec3 transStiffness, SimTK::Vec3 rotStiffness, SimTK::Vec3 transDamping, SimTK::Vec3 rotDamping ):\r\n\tForce(),\r\n\t_body1Name(_body1NameProp.getValueStr()),\r\n\t_body2Name(_body2NameProp.getValueStr()),\r\n\t_locationInBody1(_locationInBody1Prop.getValueDblVec3()),\r\n\t_orientationInBody1(_orientationInBody1Prop.getValueDblVec3()),\r\n\t_locationInBody2(_locationInBody2Prop.getValueDblVec3()),\r\n\t_orientationInBody2(_orientationInBody2Prop.getValueDblVec3()),\r\n\t_rotStiffness(_rotStiffnessProp.getValueDblVec3()),\r\n\t_transStiffness(_transStiffnessProp.getValueDblVec3()),\r\n\t_rotDamping(_rotDampingProp.getValueDblVec3()),\r\n\t_transDamping(_transDampingProp.getValueDblVec3())\r\n{\r\n\tsetNull();\r\n\t_body1Name = body1Name;\r\n\t_body2Name = body2Name;\r\n\t_locationInBody1 = point1;\r\n\t_orientationInBody1 = orientation1;\r\n\t_locationInBody2 = point2;\r\n\t_orientationInBody2 = orientation2;\r\n\t_rotStiffness = rotStiffness;\r\n\t_transStiffness = transStiffness;\r\n\t_rotDamping = rotDamping;\r\n\t_transDamping = transDamping;\r\n}\r\n\r\n\r\n\/\/_____________________________________________________________________________\r\n\/**\r\n * Copy constructor.\r\n *\r\n * @param aForce BushingForce to be copied.\r\n *\/\r\nBushingForce::BushingForce(const BushingForce &aForce) :\r\n Force(aForce),\r\n\t_body1Name(_body1NameProp.getValueStr()),\r\n\t_body2Name(_body2NameProp.getValueStr()),\r\n\t_locationInBody1(_locationInBody1Prop.getValueDblVec3()),\r\n\t_orientationInBody1(_orientationInBody1Prop.getValueDblVec3()),\r\n\t_locationInBody2(_locationInBody2Prop.getValueDblVec3()),\r\n\t_orientationInBody2(_orientationInBody2Prop.getValueDblVec3()),\r\n\t_rotStiffness(_rotStiffnessProp.getValueDblVec3()),\r\n\t_transStiffness(_transStiffnessProp.getValueDblVec3()),\r\n\t_rotDamping(_rotDampingProp.getValueDblVec3()),\r\n\t_transDamping(_transDampingProp.getValueDblVec3())\r\n{\r\n\tsetNull();\r\n\tcopyData(aForce);\r\n}\r\n\r\n\/\/=============================================================================\r\n\/\/ CONSTRUCTION\r\n\/\/=============================================================================\r\n\/\/_____________________________________________________________________________\r\n\/**\r\n * Copy this body and return a pointer to the copy.\r\n * The copy constructor for this class is used.\r\n *\r\n * @return Pointer to a copy of this OpenSim::Body.\r\n *\/\r\nObject* BushingForce::copy() const\r\n{\r\n\tBushingForce *Force = new BushingForce(*this);\r\n\treturn(Force);\r\n}\r\n\/\/_____________________________________________________________________________\r\n\/**\r\n * Copy data members from one BushingForce to another.\r\n *\r\n * @param aForce BushingForce to be copied.\r\n *\/\r\nvoid BushingForce::copyData(const BushingForce &aForce)\r\n{\r\n\tForce::copyData(aForce);\r\n\t_body1Name = aForce._body1Name;\r\n\t_body2Name = aForce._body2Name;\r\n\t_locationInBody1 = aForce._locationInBody1;\r\n\t_orientationInBody1 = aForce._orientationInBody1;\r\n\t_locationInBody2 = aForce._locationInBody2;\r\n\t_orientationInBody2 = aForce._orientationInBody2;\r\n\t_rotStiffness = aForce._rotStiffness;\r\n\t_transStiffness = aForce._transStiffness;\r\n\t_rotDamping = aForce._rotDamping;\r\n\t_transDamping = aForce._transDamping;\r\n}\r\n\r\n\/\/_____________________________________________________________________________\r\n\/**\r\n * Set the data members of this BushingForce to their null values.\r\n *\/\r\nvoid BushingForce::setNull()\r\n{\r\n\tsetType(\"BushingForce\");\r\n\tsetupProperties();\r\n}\r\n\r\n\/\/_____________________________________________________________________________\r\n\/**\r\n * Connect properties to local pointers.\r\n *\/\r\nvoid BushingForce::setupProperties()\r\n{\r\n\t\/\/ Body 1 name\r\n\t_body1NameProp.setName(\"body_1\");\r\n\t_propertySet.append(&_body1NameProp);\r\n\r\n\t\/\/ Body 2 name\r\n\t_body2NameProp.setName(\"body_2\");\r\n\t_propertySet.append(&_body2NameProp);\r\n\r\n\t\/\/Default location and orientation (rotation sequence)\r\n\tSimTK::Vec3 origin(0.0, 0.0, 0.0);\r\n\r\n\t\/\/ Location in Body 1 \r\n\t_locationInBody1Prop.setName(\"location_body_1\");\r\n\t_locationInBody1Prop.setValue(origin);\r\n\t_propertySet.append(&_locationInBody1Prop);\r\n\r\n\t\/\/ Orientation in Body 1 \r\n\t_orientationInBody1Prop.setName(\"orientation_body_1\");\r\n\t_orientationInBody1Prop.setValue(origin);\r\n\t_propertySet.append(&_orientationInBody1Prop);\r\n\r\n\t\/\/ Location in Body 2 \r\n\t_locationInBody2Prop.setName(\"location_body_2\");\r\n\t_locationInBody2Prop.setValue(origin);\r\n\t_propertySet.append(&_locationInBody2Prop);\r\n\r\n\t\/\/ Orientation in Body 2 \r\n\t_orientationInBody2Prop.setName(\"orientation_body_2\");\r\n\t_orientationInBody2Prop.setValue(origin);\r\n\t_propertySet.append(&_orientationInBody2Prop);\r\n\r\n\t_rotStiffnessProp.setName(\"rotational_stiffness\");\r\n\t_rotStiffnessProp.setValue(Vec3(0));\r\n\t_propertySet.append(&_rotStiffnessProp);\r\n\r\n\t_transStiffnessProp.setName(\"translational_stiffness\");\r\n\t_transStiffnessProp.setValue(Vec3(0));\r\n\t_propertySet.append(&_transStiffnessProp);\r\n\r\n\t_rotDampingProp.setName(\"rotational_damping\");\r\n\t_rotDampingProp.setValue(Vec3(0));\r\n\t_propertySet.append(&_rotDampingProp);\r\n\r\n\t_transDampingProp.setName(\"rotational_damping\");\r\n\t_transDampingProp.setValue(Vec3(0));\r\n\t_propertySet.append(&_transDampingProp);\r\n}\r\n\r\n\/\/_____________________________________________________________________________\r\n\/**\r\n * Perform some set up functions that happen after the\r\n * object has been deserialized or copied.\r\n *\r\n * @param aModel OpenSim model containing this BushingForce.\r\n *\/\r\nvoid BushingForce::setup(Model& aModel)\r\n{\r\n\tstring errorMessage;\r\n\r\n\t\/\/ Base class\r\n\tForce::setup(aModel);\r\n\r\n\t\/\/ Look up the two bodies being connected by bushing by name in the\r\n\t\/\/ model and might as well keep a pointer to them\r\n\tif (!aModel.updBodySet().contains(_body1Name)) {\r\n\t\terrorMessage = \"Invalid bushing body1 (\" + _body1Name + \") specified in Force \" + getName();\r\n\t\tthrow (Exception(errorMessage.c_str()));\r\n\t}\r\n\tif (!aModel.updBodySet().contains(_body2Name)) {\r\n\t\terrorMessage = \"Invalid bushing body2 (\" + _body2Name + \") specified in Force \" + getName();\r\n\t\tthrow (Exception(errorMessage.c_str()));\r\n\t}\r\n}\r\n\r\nvoid BushingForce::createSystem(SimTK::MultibodySystem& system) const\r\n{\r\n\tBody &body1 = _model->updBodySet().get(_body1Name);\r\n\tBody &body2 = _model->updBodySet().get(_body2Name);\r\n\r\n\t\/\/ Get underlying mobilized bodies\r\n\tSimTK::MobilizedBody b1 = _model->updMatterSubsystem().getMobilizedBody(body1.getIndex());\r\n\tSimTK::MobilizedBody b2 = _model->updMatterSubsystem().getMobilizedBody(body2.getIndex());\r\n\t\/\/ Build the transforms\r\n\tSimTK::Rotation r1; r1.setRotationToBodyFixedXYZ(_orientationInBody1);\r\n\tSimTK::Rotation r2; r2.setRotationToBodyFixedXYZ(_orientationInBody2);\r\n\tSimTK::Transform inb1(r1, _locationInBody1);\r\n\tSimTK::Transform inb2(r2, _locationInBody2);\r\n\r\n\tVec6 stiffness(_rotStiffness[0], _rotStiffness[1], _rotStiffness[2], _transStiffness[0], _transStiffness[1], _transStiffness[2]);\r\n\tVec6 damping(_rotDamping[0], _rotDamping[1], _rotDamping[2], _transDamping[0], _transDamping[1], _transDamping[2]);\r\n\r\n \/\/ Now create a Simbody Force::LinearBushing\r\n SimTK::Force::LinearBushing simtkForce(_model->updUserForceSubsystem(), b1, inb1, b2, inb2, stiffness, damping);\r\n \r\n \/\/ Beyond the const Component get the index so we can access the SimTK::Force later\r\n\tBushingForce* mutableThis = const_cast(this);\r\n\tmutableThis->_index = simtkForce.getForceIndex();\r\n}\r\n\r\n\/\/=============================================================================\r\n\/\/ OPERATORS\r\n\/\/=============================================================================\r\n\/\/_____________________________________________________________________________\r\n\/**\r\n * Assignment operator.\r\n *\r\n * @return Reference to this object.\r\n *\/\r\nBushingForce& BushingForce::operator=(const BushingForce &aForce)\r\n{\r\n\tForce::operator=(aForce);\r\n\tcopyData(aForce);\r\n\treturn(*this);\r\n}\r\n\r\n\/\/=============================================================================\r\n\/\/ SET\r\n\/\/=============================================================================\r\n\/\/_____________________________________________________________________________\r\n\/**\r\n * Following methods set attributes of the weld Force *\/\r\nvoid BushingForce::setBody1ByName(std::string aBodyName)\r\n{\r\n\t_body1Name = aBodyName;\r\n}\r\n\r\nvoid BushingForce::setBody2ByName(std::string aBodyName)\r\n{\r\n\t_body2Name = aBodyName;\r\n}\r\n\r\n\/** Set the location and orientation (optional) for weld on body 1*\/\r\nvoid BushingForce::setBody1BushingLocation(Vec3 location, Vec3 orientation)\r\n{\r\n\t_locationInBody1 = location;\r\n\t_orientationInBody1 = orientation;\r\n}\r\n\r\n\/** Set the location and orientation (optional) for weld on body 2*\/\r\nvoid BushingForce::setBody2BushingLocation(Vec3 location, Vec3 orientation)\r\n{\r\n\t_locationInBody2 = location;\r\n\t_orientationInBody2 = orientation;\r\n}\r\n\r\n\r\n\/\/=============================================================================\r\n\/\/ Reporting\r\n\/\/=============================================================================\r\n\/** \r\n * Provide names of the quantities (column labels) of the force value(s) reported\r\n * \r\n *\/\r\nOpenSim::Array BushingForce::getRecordLabels() const \r\n{\r\n\tOpenSim::Array labels(\"\");\r\n\tlabels.append(getName()+\".\"+_body1Name+\".force.X\");\r\n\tlabels.append(getName()+\".\"+_body1Name+\".force.Y\");\r\n\tlabels.append(getName()+\".\"+_body1Name+\".force.Z\");\r\n\tlabels.append(getName()+\".\"+_body1Name+\".torque.X\");\r\n\tlabels.append(getName()+\".\"+_body1Name+\".torque.Y\");\r\n\tlabels.append(getName()+\".\"+_body1Name+\".torque.Z\");\r\n\tlabels.append(getName()+\".\"+_body2Name+\".force.X\");\r\n\tlabels.append(getName()+\".\"+_body2Name+\".force.Y\");\r\n\tlabels.append(getName()+\".\"+_body2Name+\".force.Z\");\r\n\tlabels.append(getName()+\".\"+_body2Name+\".torque.X\");\r\n\tlabels.append(getName()+\".\"+_body2Name+\".torque.Y\");\r\n\tlabels.append(getName()+\".\"+_body2Name+\".torque.Z\");\r\n\r\n\treturn labels;\r\n}\r\n\/**\r\n * Provide the value(s) to be reported that correspond to the labels\r\n *\/\r\nOpenSim::Array BushingForce::getRecordValues(const SimTK::State& state) const \r\n{\r\n\tOpenSim::Array values(1);\r\n\r\n\tconst SimTK::Force::LinearBushing &simtkSpring = (SimTK::Force::LinearBushing &)(_model->getUserForceSubsystem().getForce(_index));\r\n\r\n\tSimTK::Vector_ bodyForces(0);\r\n\tSimTK::Vector_ particleForces(0);\r\n\tSimTK::Vector mobilityForces(0);\r\n\r\n\t\/\/get the net force added to the system contributed by the bushing\r\n\tsimtkSpring.calcForceContribution(state, bodyForces, particleForces, mobilityForces);\r\n\tSimTK::Vec3 forces = bodyForces(_model->getBodySet().get(_body1Name).getIndex())[1];\r\n\tSimTK::Vec3 torques = bodyForces(_model->getBodySet().get(_body1Name).getIndex())[0];\r\n\tvalues.append(3, &forces[0]);\r\n\tvalues.append(3, &torques[0]);\r\n\r\n\tforces = bodyForces(_model->getBodySet().get(_body2Name).getIndex())[1];\r\n\ttorques = bodyForces(_model->getBodySet().get(_body2Name).getIndex())[0];\r\n\r\n\tvalues.append(3, &forces[0]);\r\n\tvalues.append(3, &torques[0]);\r\n\r\n\treturn values;\r\n}\r\nFixed a copy-paste bug that was overwriting rotational_damping properties with translational_damping property values and failing to have translational_damping.\/\/ BushingForce.cpp\r\n\/\/ Author: Ajay Seth\r\n\/*\r\n * Copyright (c) 2010, Stanford University. All rights reserved. \r\n* Use of the OpenSim software in source form is permitted provided that the following\r\n* conditions are met:\r\n* \t1. The software is used only for non-commercial research and education. It may not\r\n* be used in relation to any commercial activity.\r\n* \t2. The software is not distributed or redistributed. Software distribution is allowed \r\n* only through https:\/\/simtk.org\/home\/opensim.\r\n* \t3. Use of the OpenSim software or derivatives must be acknowledged in all publications,\r\n* presentations, or documents describing work in which OpenSim or derivatives are used.\r\n* \t4. Credits to developers may not be removed from executables\r\n* created from modifications of the source.\r\n* \t5. Modifications of source code must retain the above copyright notice, this list of\r\n* conditions and the following disclaimer. \r\n* \r\n* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY\r\n* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\r\n* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT\r\n* SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\r\n* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED\r\n* TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; \r\n* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\r\n* OR BUSINESS INTERRUPTION) OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY\r\n* WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\r\n *\/\r\n\r\n\/\/=============================================================================\r\n\/\/ INCLUDES\r\n\/\/=============================================================================\r\n#include \r\n#include \r\n\r\n#include \"BushingForce.h\"\r\n\r\n\/\/=============================================================================\r\n\/\/ STATICS\r\n\/\/=============================================================================\r\nusing namespace std;\r\nusing namespace SimTK;\r\nusing namespace OpenSim;\r\n\r\n\/\/=============================================================================\r\n\/\/ CONSTRUCTOR(S) AND DESTRUCTOR\r\n\/\/=============================================================================\r\n\/\/_____________________________________________________________________________\r\n\/**\r\n * Destructor.\r\n *\/\r\nBushingForce::~BushingForce()\r\n{\r\n}\r\n\/\/_____________________________________________________________________________\r\n\/**\r\n * Default constructor.\r\n *\/\r\nBushingForce::BushingForce() :\r\n\tForce(),\r\n\t_body1Name(_body1NameProp.getValueStr()),\r\n\t_body2Name(_body2NameProp.getValueStr()),\r\n\t_locationInBody1(_locationInBody1Prop.getValueDblVec3()),\r\n\t_orientationInBody1(_orientationInBody1Prop.getValueDblVec3()),\r\n\t_locationInBody2(_locationInBody2Prop.getValueDblVec3()),\r\n\t_orientationInBody2(_orientationInBody2Prop.getValueDblVec3()),\r\n\t_rotStiffness(_rotStiffnessProp.getValueDblVec3()),\r\n\t_transStiffness(_transStiffnessProp.getValueDblVec3()),\r\n\t_rotDamping(_rotDampingProp.getValueDblVec3()),\r\n\t_transDamping(_transDampingProp.getValueDblVec3())\r\n{\r\n\tsetNull();\r\n}\r\n\r\n\/* Convenience constructor *\/\r\nBushingForce::BushingForce( std::string body1Name, SimTK::Vec3 point1, SimTK::Vec3 orientation1,\r\n\t\t std::string body2Name, SimTK::Vec3 point2, SimTK::Vec3 orientation2,\r\n\t\t\t\t SimTK::Vec3 transStiffness, SimTK::Vec3 rotStiffness, SimTK::Vec3 transDamping, SimTK::Vec3 rotDamping ):\r\n\tForce(),\r\n\t_body1Name(_body1NameProp.getValueStr()),\r\n\t_body2Name(_body2NameProp.getValueStr()),\r\n\t_locationInBody1(_locationInBody1Prop.getValueDblVec3()),\r\n\t_orientationInBody1(_orientationInBody1Prop.getValueDblVec3()),\r\n\t_locationInBody2(_locationInBody2Prop.getValueDblVec3()),\r\n\t_orientationInBody2(_orientationInBody2Prop.getValueDblVec3()),\r\n\t_rotStiffness(_rotStiffnessProp.getValueDblVec3()),\r\n\t_transStiffness(_transStiffnessProp.getValueDblVec3()),\r\n\t_rotDamping(_rotDampingProp.getValueDblVec3()),\r\n\t_transDamping(_transDampingProp.getValueDblVec3())\r\n{\r\n\tsetNull();\r\n\t_body1Name = body1Name;\r\n\t_body2Name = body2Name;\r\n\t_locationInBody1 = point1;\r\n\t_orientationInBody1 = orientation1;\r\n\t_locationInBody2 = point2;\r\n\t_orientationInBody2 = orientation2;\r\n\t_rotStiffness = rotStiffness;\r\n\t_transStiffness = transStiffness;\r\n\t_rotDamping = rotDamping;\r\n\t_transDamping = transDamping;\r\n}\r\n\r\n\r\n\/\/_____________________________________________________________________________\r\n\/**\r\n * Copy constructor.\r\n *\r\n * @param aForce BushingForce to be copied.\r\n *\/\r\nBushingForce::BushingForce(const BushingForce &aForce) :\r\n Force(aForce),\r\n\t_body1Name(_body1NameProp.getValueStr()),\r\n\t_body2Name(_body2NameProp.getValueStr()),\r\n\t_locationInBody1(_locationInBody1Prop.getValueDblVec3()),\r\n\t_orientationInBody1(_orientationInBody1Prop.getValueDblVec3()),\r\n\t_locationInBody2(_locationInBody2Prop.getValueDblVec3()),\r\n\t_orientationInBody2(_orientationInBody2Prop.getValueDblVec3()),\r\n\t_rotStiffness(_rotStiffnessProp.getValueDblVec3()),\r\n\t_transStiffness(_transStiffnessProp.getValueDblVec3()),\r\n\t_rotDamping(_rotDampingProp.getValueDblVec3()),\r\n\t_transDamping(_transDampingProp.getValueDblVec3())\r\n{\r\n\tsetNull();\r\n\tcopyData(aForce);\r\n}\r\n\r\n\/\/=============================================================================\r\n\/\/ CONSTRUCTION\r\n\/\/=============================================================================\r\n\/\/_____________________________________________________________________________\r\n\/**\r\n * Copy this body and return a pointer to the copy.\r\n * The copy constructor for this class is used.\r\n *\r\n * @return Pointer to a copy of this OpenSim::Body.\r\n *\/\r\nObject* BushingForce::copy() const\r\n{\r\n\tBushingForce *Force = new BushingForce(*this);\r\n\treturn(Force);\r\n}\r\n\/\/_____________________________________________________________________________\r\n\/**\r\n * Copy data members from one BushingForce to another.\r\n *\r\n * @param aForce BushingForce to be copied.\r\n *\/\r\nvoid BushingForce::copyData(const BushingForce &aForce)\r\n{\r\n\tForce::copyData(aForce);\r\n\t_body1Name = aForce._body1Name;\r\n\t_body2Name = aForce._body2Name;\r\n\t_locationInBody1 = aForce._locationInBody1;\r\n\t_orientationInBody1 = aForce._orientationInBody1;\r\n\t_locationInBody2 = aForce._locationInBody2;\r\n\t_orientationInBody2 = aForce._orientationInBody2;\r\n\t_rotStiffness = aForce._rotStiffness;\r\n\t_transStiffness = aForce._transStiffness;\r\n\t_rotDamping = aForce._rotDamping;\r\n\t_transDamping = aForce._transDamping;\r\n}\r\n\r\n\/\/_____________________________________________________________________________\r\n\/**\r\n * Set the data members of this BushingForce to their null values.\r\n *\/\r\nvoid BushingForce::setNull()\r\n{\r\n\tsetType(\"BushingForce\");\r\n\tsetupProperties();\r\n}\r\n\r\n\/\/_____________________________________________________________________________\r\n\/**\r\n * Connect properties to local pointers.\r\n *\/\r\nvoid BushingForce::setupProperties()\r\n{\r\n\t\/\/ Body 1 name\r\n\t_body1NameProp.setName(\"body_1\");\r\n\t_propertySet.append(&_body1NameProp);\r\n\r\n\t\/\/ Body 2 name\r\n\t_body2NameProp.setName(\"body_2\");\r\n\t_propertySet.append(&_body2NameProp);\r\n\r\n\t\/\/Default location and orientation (rotation sequence)\r\n\tSimTK::Vec3 origin(0.0, 0.0, 0.0);\r\n\r\n\t\/\/ Location in Body 1 \r\n\t_locationInBody1Prop.setName(\"location_body_1\");\r\n\t_locationInBody1Prop.setValue(origin);\r\n\t_propertySet.append(&_locationInBody1Prop);\r\n\r\n\t\/\/ Orientation in Body 1 \r\n\t_orientationInBody1Prop.setName(\"orientation_body_1\");\r\n\t_orientationInBody1Prop.setValue(origin);\r\n\t_propertySet.append(&_orientationInBody1Prop);\r\n\r\n\t\/\/ Location in Body 2 \r\n\t_locationInBody2Prop.setName(\"location_body_2\");\r\n\t_locationInBody2Prop.setValue(origin);\r\n\t_propertySet.append(&_locationInBody2Prop);\r\n\r\n\t\/\/ Orientation in Body 2 \r\n\t_orientationInBody2Prop.setName(\"orientation_body_2\");\r\n\t_orientationInBody2Prop.setValue(origin);\r\n\t_propertySet.append(&_orientationInBody2Prop);\r\n\r\n\t_rotStiffnessProp.setName(\"rotational_stiffness\");\r\n\t_rotStiffnessProp.setValue(Vec3(0));\r\n\t_propertySet.append(&_rotStiffnessProp);\r\n\r\n\t_transStiffnessProp.setName(\"translational_stiffness\");\r\n\t_transStiffnessProp.setValue(Vec3(0));\r\n\t_propertySet.append(&_transStiffnessProp);\r\n\r\n\t_rotDampingProp.setName(\"rotational_damping\");\r\n\t_rotDampingProp.setValue(Vec3(0));\r\n\t_propertySet.append(&_rotDampingProp);\r\n\r\n\t_transDampingProp.setName(\"translational_damping\");\r\n\t_transDampingProp.setValue(Vec3(0));\r\n\t_propertySet.append(&_transDampingProp);\r\n}\r\n\r\n\/\/_____________________________________________________________________________\r\n\/**\r\n * Perform some set up functions that happen after the\r\n * object has been deserialized or copied.\r\n *\r\n * @param aModel OpenSim model containing this BushingForce.\r\n *\/\r\nvoid BushingForce::setup(Model& aModel)\r\n{\r\n\tstring errorMessage;\r\n\r\n\t\/\/ Base class\r\n\tForce::setup(aModel);\r\n\r\n\t\/\/ Look up the two bodies being connected by bushing by name in the\r\n\t\/\/ model and might as well keep a pointer to them\r\n\tif (!aModel.updBodySet().contains(_body1Name)) {\r\n\t\terrorMessage = \"Invalid bushing body1 (\" + _body1Name + \") specified in Force \" + getName();\r\n\t\tthrow (Exception(errorMessage.c_str()));\r\n\t}\r\n\tif (!aModel.updBodySet().contains(_body2Name)) {\r\n\t\terrorMessage = \"Invalid bushing body2 (\" + _body2Name + \") specified in Force \" + getName();\r\n\t\tthrow (Exception(errorMessage.c_str()));\r\n\t}\r\n}\r\n\r\nvoid BushingForce::createSystem(SimTK::MultibodySystem& system) const\r\n{\r\n\tBody &body1 = _model->updBodySet().get(_body1Name);\r\n\tBody &body2 = _model->updBodySet().get(_body2Name);\r\n\r\n\t\/\/ Get underlying mobilized bodies\r\n\tSimTK::MobilizedBody b1 = _model->updMatterSubsystem().getMobilizedBody(body1.getIndex());\r\n\tSimTK::MobilizedBody b2 = _model->updMatterSubsystem().getMobilizedBody(body2.getIndex());\r\n\t\/\/ Build the transforms\r\n\tSimTK::Rotation r1; r1.setRotationToBodyFixedXYZ(_orientationInBody1);\r\n\tSimTK::Rotation r2; r2.setRotationToBodyFixedXYZ(_orientationInBody2);\r\n\tSimTK::Transform inb1(r1, _locationInBody1);\r\n\tSimTK::Transform inb2(r2, _locationInBody2);\r\n\r\n\tVec6 stiffness(_rotStiffness[0], _rotStiffness[1], _rotStiffness[2], _transStiffness[0], _transStiffness[1], _transStiffness[2]);\r\n\tVec6 damping(_rotDamping[0], _rotDamping[1], _rotDamping[2], _transDamping[0], _transDamping[1], _transDamping[2]);\r\n\r\n \/\/ Now create a Simbody Force::LinearBushing\r\n SimTK::Force::LinearBushing simtkForce(_model->updUserForceSubsystem(), b1, inb1, b2, inb2, stiffness, damping);\r\n \r\n \/\/ Beyond the const Component get the index so we can access the SimTK::Force later\r\n\tBushingForce* mutableThis = const_cast(this);\r\n\tmutableThis->_index = simtkForce.getForceIndex();\r\n}\r\n\r\n\/\/=============================================================================\r\n\/\/ OPERATORS\r\n\/\/=============================================================================\r\n\/\/_____________________________________________________________________________\r\n\/**\r\n * Assignment operator.\r\n *\r\n * @return Reference to this object.\r\n *\/\r\nBushingForce& BushingForce::operator=(const BushingForce &aForce)\r\n{\r\n\tForce::operator=(aForce);\r\n\tcopyData(aForce);\r\n\treturn(*this);\r\n}\r\n\r\n\/\/=============================================================================\r\n\/\/ SET\r\n\/\/=============================================================================\r\n\/\/_____________________________________________________________________________\r\n\/**\r\n * Following methods set attributes of the weld Force *\/\r\nvoid BushingForce::setBody1ByName(std::string aBodyName)\r\n{\r\n\t_body1Name = aBodyName;\r\n}\r\n\r\nvoid BushingForce::setBody2ByName(std::string aBodyName)\r\n{\r\n\t_body2Name = aBodyName;\r\n}\r\n\r\n\/** Set the location and orientation (optional) for weld on body 1*\/\r\nvoid BushingForce::setBody1BushingLocation(Vec3 location, Vec3 orientation)\r\n{\r\n\t_locationInBody1 = location;\r\n\t_orientationInBody1 = orientation;\r\n}\r\n\r\n\/** Set the location and orientation (optional) for weld on body 2*\/\r\nvoid BushingForce::setBody2BushingLocation(Vec3 location, Vec3 orientation)\r\n{\r\n\t_locationInBody2 = location;\r\n\t_orientationInBody2 = orientation;\r\n}\r\n\r\n\r\n\/\/=============================================================================\r\n\/\/ Reporting\r\n\/\/=============================================================================\r\n\/** \r\n * Provide names of the quantities (column labels) of the force value(s) reported\r\n * \r\n *\/\r\nOpenSim::Array BushingForce::getRecordLabels() const \r\n{\r\n\tOpenSim::Array labels(\"\");\r\n\tlabels.append(getName()+\".\"+_body1Name+\".force.X\");\r\n\tlabels.append(getName()+\".\"+_body1Name+\".force.Y\");\r\n\tlabels.append(getName()+\".\"+_body1Name+\".force.Z\");\r\n\tlabels.append(getName()+\".\"+_body1Name+\".torque.X\");\r\n\tlabels.append(getName()+\".\"+_body1Name+\".torque.Y\");\r\n\tlabels.append(getName()+\".\"+_body1Name+\".torque.Z\");\r\n\tlabels.append(getName()+\".\"+_body2Name+\".force.X\");\r\n\tlabels.append(getName()+\".\"+_body2Name+\".force.Y\");\r\n\tlabels.append(getName()+\".\"+_body2Name+\".force.Z\");\r\n\tlabels.append(getName()+\".\"+_body2Name+\".torque.X\");\r\n\tlabels.append(getName()+\".\"+_body2Name+\".torque.Y\");\r\n\tlabels.append(getName()+\".\"+_body2Name+\".torque.Z\");\r\n\r\n\treturn labels;\r\n}\r\n\/**\r\n * Provide the value(s) to be reported that correspond to the labels\r\n *\/\r\nOpenSim::Array BushingForce::getRecordValues(const SimTK::State& state) const \r\n{\r\n\tOpenSim::Array values(1);\r\n\r\n\tconst SimTK::Force::LinearBushing &simtkSpring = (SimTK::Force::LinearBushing &)(_model->getUserForceSubsystem().getForce(_index));\r\n\r\n\tSimTK::Vector_ bodyForces(0);\r\n\tSimTK::Vector_ particleForces(0);\r\n\tSimTK::Vector mobilityForces(0);\r\n\r\n\t\/\/get the net force added to the system contributed by the bushing\r\n\tsimtkSpring.calcForceContribution(state, bodyForces, particleForces, mobilityForces);\r\n\tSimTK::Vec3 forces = bodyForces(_model->getBodySet().get(_body1Name).getIndex())[1];\r\n\tSimTK::Vec3 torques = bodyForces(_model->getBodySet().get(_body1Name).getIndex())[0];\r\n\tvalues.append(3, &forces[0]);\r\n\tvalues.append(3, &torques[0]);\r\n\r\n\tforces = bodyForces(_model->getBodySet().get(_body2Name).getIndex())[1];\r\n\ttorques = bodyForces(_model->getBodySet().get(_body2Name).getIndex())[0];\r\n\r\n\tvalues.append(3, &forces[0]);\r\n\tvalues.append(3, &torques[0]);\r\n\r\n\treturn values;\r\n}\r\n<|endoftext|>"} {"text":"\/* Copyright 2018 The TensorFlow Authors. All Rights Reserved.\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*\/\n\n#include \"tensorflow\/compiler\/tf2tensorrt\/convert\/trt_optimization_pass.h\"\n\n#include \"absl\/strings\/ascii.h\"\n#include \"absl\/strings\/escaping.h\"\n#include \"absl\/strings\/str_cat.h\"\n#include \"tensorflow\/compiler\/tf2tensorrt\/convert\/convert_graph.h\"\n#include \"tensorflow\/compiler\/tf2tensorrt\/convert\/utils.h\"\n#include \"tensorflow\/core\/grappler\/clusters\/cluster.h\"\n#include \"tensorflow\/core\/grappler\/grappler_item.h\"\n#include \"tensorflow\/core\/grappler\/optimizers\/custom_graph_optimizer_registry.h\"\n#include \"tensorflow\/core\/lib\/strings\/numbers.h\"\n#include \"tensorflow\/core\/lib\/strings\/str_util.h\"\n#include \"tensorflow\/core\/lib\/strings\/strcat.h\"\n#include \"tensorflow\/core\/platform\/logging.h\"\n#include \"tensorflow\/core\/platform\/stacktrace.h\"\n\n#if GOOGLE_CUDA && GOOGLE_TENSORRT\nnamespace tensorflow {\nnamespace tensorrt {\nnamespace convert {\n\/\/ TODO(sami): Remove VLOG messages once the code matures\nusing absl::AsciiStrToUpper;\nusing absl::StrAppend;\nusing absl::StrCat;\n\nStatus TRTOptimizationPass::Init(\n const RewriterConfig_CustomGraphOptimizer* config) {\n VLOG(1) << \"Called INIT for \" << name_ << \" with config = \" << config;\n if (config == nullptr) {\n return Status::OK();\n }\n VLOG(1) << \"config = \" << config->DebugString();\n const auto params = config->parameter_map();\n if (params.count(\"minimum_segment_size\")) {\n minimum_segment_size_ = params.at(\"minimum_segment_size\").i();\n }\n if (params.count(\"max_batch_size\")) {\n maximum_batch_size_ = params.at(\"max_batch_size\").i();\n }\n if (params.count(\"is_dynamic_op\")) {\n is_dynamic_op_ = params.at(\"is_dynamic_op\").b();\n }\n if (params.count(\"maximum_cached_engines\")) {\n max_cached_batches_ = params.at(\"maximum_cached_engines\").i();\n }\n if (params.count(\"max_workspace_size_bytes\")) {\n max_workspace_size_bytes_ = params.at(\"max_workspace_size_bytes\").i();\n }\n if (params.count(\"precision_mode\")) {\n TF_RETURN_IF_ERROR(TrtPrecisionModeFromName(\n AsciiStrToUpper(params.at(\"precision_mode\").s()), &precision_mode_));\n }\n if (params.count(\"use_calibration\")) {\n use_calibration_ = params.at(\"use_calibration\").b();\n }\n if (params.count(\"trt_logger\")) {\n trt_logger_name_ = params.at(\"trt_logger\").s();\n }\n if (params.count(\"allow_build_at_runtime\")) {\n allow_build_at_runtime_ = params.at(\"allow_build_at_runtime\").b();\n }\n if (params.count(\"use_implicit_batch\")) {\n use_implicit_batch_ = params.at(\"use_implicit_batch\").b();\n }\n return Status::OK();\n}\n\nvoid TRTOptimizationPass::PrintDebugInfo(grappler::Cluster* cluster,\n const grappler::GrapplerItem& item) {\n LOG(INFO) << \"Cluster = \" << cluster;\n string offset(\" \");\n string offset2 = StrCat(offset, offset);\n string offset3 = StrCat(offset2, offset);\n string offset4 = StrCat(offset2, offset2);\n\n if (cluster) {\n LOG(INFO) << offset << \"type = \" << cluster->type();\n LOG(INFO) << offset << \"num warmup steps = \" << cluster->NumWarmupSteps();\n const auto dev_names = cluster->GetDeviceNames();\n if (!dev_names.empty()) {\n LOG(INFO) << offset << \" Device names:\";\n for (const auto& s : dev_names) {\n LOG(INFO) << offset2 << s;\n }\n }\n std::unordered_map peak_mem;\n auto status = cluster->GetPeakMemoryUsage(&peak_mem);\n if (status == Status::OK()) {\n LOG(INFO) << offset << \"Peak Memory Usage :\";\n for (const auto& s : peak_mem) {\n LOG(INFO) << offset2 << s.first << \" = \" << s.second;\n }\n }\n\n const auto dev_props = cluster->GetDevices();\n if (!dev_props.empty()) {\n LOG(INFO) << offset << \"Device properties:\";\n for (const auto& k : dev_props) {\n LOG(INFO) << offset2 << k.first;\n const auto& dt = k.second;\n LOG(INFO) << offset3 << \"type = \" << dt.type();\n LOG(INFO) << offset3 << \"vendor = \" << dt.vendor();\n LOG(INFO) << offset3 << \"model = \" << dt.model();\n LOG(INFO) << offset3 << \"frequency = \" << dt.frequency();\n LOG(INFO) << offset3 << \"num cores = \" << dt.num_cores();\n LOG(INFO) << offset3 << \"num registers = \" << dt.num_registers();\n LOG(INFO) << offset3 << \"L1 cache size = \" << dt.l1_cache_size();\n LOG(INFO) << offset3 << \"L2 cache size = \" << dt.l2_cache_size();\n LOG(INFO) << offset3 << \"L3 cache size = \" << dt.l3_cache_size();\n LOG(INFO) << offset3 << \"SHMem per SMP = \"\n << dt.shared_memory_size_per_multiprocessor();\n LOG(INFO) << offset3 << \"memory size = \" << dt.memory_size();\n LOG(INFO) << offset3 << \"bandwidth = \" << dt.bandwidth();\n if (dt.environment_size()) {\n LOG(INFO) << offset3 << \"environment :\";\n for (const auto& e : dt.environment()) {\n LOG(INFO) << offset4 << e.first << \" = \" << e.second;\n }\n }\n }\n }\n\n if (cluster->GetDeviceSet()) {\n for (const auto dev : cluster->GetDeviceSet()->devices()) {\n LOG(INFO) << \"Device name= \" << dev->name() << \"Pased name= \"\n << DeviceNameUtils::ParsedNameToString(dev->parsed_name());\n }\n }\n }\n\n LOG(INFO) << \"item: \" << item.id;\n if (!item.feed.empty()) {\n LOG(INFO) << offset << \"Feeds :\";\n for (const auto& f : item.feed) {\n const auto& shape = f.second.shape();\n LOG(INFO) << offset2 << f.first << \" = shaped \" << shape.DebugString();\n }\n } else {\n LOG(INFO) << offset << \"No Feeds\";\n }\n if (!item.fetch.empty()) {\n LOG(INFO) << offset << \"Fetches :\";\n for (const auto& f : item.fetch) {\n LOG(INFO) << offset2 << f;\n }\n } else {\n LOG(INFO) << offset << \"No Fetches\";\n }\n\n if (!item.init_ops.empty()) {\n LOG(INFO) << offset << \"init ops :\";\n for (const auto& f : item.init_ops) {\n LOG(INFO) << offset2 << f;\n }\n } else {\n LOG(INFO) << offset << \"No init ops\";\n }\n LOG(INFO) << \"Save Op = \" << item.save_op;\n LOG(INFO) << \"Restore Op = \" << item.restore_op;\n LOG(INFO) << \"save_restore_loc_tensor = \" << item.save_restore_loc_tensor;\n if (!item.keep_ops.empty()) {\n LOG(INFO) << offset << \"keep ops :\";\n for (const auto& f : item.keep_ops) {\n LOG(INFO) << offset2 << f;\n }\n } else {\n LOG(INFO) << offset << \"No keep ops\";\n }\n}\n\nStatus TRTOptimizationPass::Optimize(grappler::Cluster* cluster,\n const grappler::GrapplerItem& item,\n GraphDef* optimized_graph) {\n VLOG(1) << \"Called TRTOptimization Pass \" << name_;\n \/\/ This is a hack to workaround optimizer issue. MetaOptimizer calls\n \/\/ optimization passes on function objects as well, we should not modify\n \/\/ generated funcdefs! This is fragile but we don't have any other option\n \/\/ until framework fixes it.\n if (item.id != \"tf_graph\") {\n VLOG(1) << \"Called TRTOptimization Pass \" << name_\n << \" on a grappler item with id=\" << item.id\n << \", which is probably a function object (funcdef). \"\n << \"Skipping optimization because TensorRTOptimizer \"\n << \"should not be called on function objects.\";\n *optimized_graph = item.graph;\n return Status::OK();\n }\n if (VLOG_IS_ON(3)) {\n LOG(INFO) << CurrentStackTrace();\n PrintDebugInfo(cluster, item);\n }\n if (!is_dynamic_op_) {\n int max_batch_dim = -1;\n if (!item.feed.empty()) {\n for (const auto& f : item.feed) {\n const auto& shape = f.second.shape();\n if (shape.dims() > 0) {\n if (shape.dim_size(0) > max_batch_dim)\n max_batch_dim = shape.dim_size(0);\n VLOG(2) << \"Setting max_batch_dim to \" << max_batch_dim\n << \" using batch dimension of \" << f.first << \" with shape \"\n << shape;\n }\n }\n }\n if (max_batch_dim > maximum_batch_size_) {\n return errors::InvalidArgument(\n \"Specified max_batch_size=\", maximum_batch_size_,\n \" is less than maximum batch dimension of inputs (\", max_batch_dim,\n \"). \", \"To continue, set max_batch_size to >= \", max_batch_dim);\n } else if (max_batch_dim < maximum_batch_size_) {\n LOG(INFO) << \"Specified max_batch_size=\" << maximum_batch_size_\n << \" is larger than maximum batch dimension of inputs (\"\n << max_batch_dim << \"). \"\n << \"This can result in poor performance.\";\n }\n }\n\n if (use_calibration_ && precision_mode_ != TrtPrecisionMode::INT8) {\n VLOG(1) << \"Calibration with FP32 or FP16 is not implemented. \"\n << \"Falling back to use_calibration = False.\"\n << \"Note that the default value of use_calibration is True.\";\n use_calibration_ = false;\n }\n\n std::vector nodes_to_preserve;\n for (const auto& n : item.NodesToPreserve()) {\n auto tokens = str_util::Split(n, \":\");\n string s = tokens.at(0);\n for (int i = 1; i < tokens.size() - 1; ++i) {\n StrAppend(&s, \":\", tokens.at(i));\n }\n int dumm_port = -1;\n \/\/ If the last token is not an integer, it must be part of the name.\n \/\/ Otherwise it is port number.\n if (tokens.size() > 1 &&\n !strings::safe_strto32(tokens.back(), &dumm_port)) { \/\/ non-absl ok\n StrAppend(&s, \":\", tokens.back());\n }\n nodes_to_preserve.push_back(s);\n }\n\n ConversionParams cp;\n cp.grappler_item = &item;\n cp.output_names = &nodes_to_preserve;\n cp.trt_logger_name = trt_logger_name_;\n cp.max_batch_size = maximum_batch_size_;\n cp.max_workspace_size_bytes = max_workspace_size_bytes_;\n cp.output_graph_def = optimized_graph;\n cp.precision_mode = precision_mode_;\n cp.minimum_segment_size = minimum_segment_size_;\n cp.cluster = cluster;\n cp.is_dyn_op = is_dynamic_op_;\n cp.max_cached_engines = max_cached_batches_;\n cp.use_calibration = use_calibration_;\n cp.use_implicit_batch = use_implicit_batch_;\n cp.allow_build_at_runtime = allow_build_at_runtime_;\n auto status = ConvertAfterShapes(cp);\n VLOG(1) << \"Returning from \" << name_;\n return status;\n}\n\nvoid TRTOptimizationPass::Feedback(grappler::Cluster* cluster,\n const grappler::GrapplerItem& item,\n const GraphDef& optimized_graph,\n double result) {}\n\nclass VerboseCustomGraphOptimizerRegistrar\n : public grappler::CustomGraphOptimizerRegistrar {\n public:\n VerboseCustomGraphOptimizerRegistrar(\n const grappler::CustomGraphOptimizerRegistry::Creator& cr,\n const string& name)\n : grappler::CustomGraphOptimizerRegistrar(cr, name) {\n VLOG(1) << \"Constructing a CustomOptimizationPass registration object for \"\n << name;\n }\n};\n\nstatic VerboseCustomGraphOptimizerRegistrar TRTOptimizationPass_Registrar(\n []() {\n VLOG(1)\n << \"Instantiating CustomOptimizationPass object TensorRTOptimizer\";\n return new TRTOptimizationPass(\"TensorRTOptimizer\");\n },\n (\"TensorRTOptimizer\"));\n\n} \/\/ namespace convert\n} \/\/ namespace tensorrt\n} \/\/ namespace tensorflow\n\n#endif \/\/ GOOGLE_CUDA && GOOGLE_TENSORRT\n[TF:TRT] Removes maximum batch size violation detection for static engines.\/* Copyright 2018 The TensorFlow Authors. All Rights Reserved.\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*\/\n\n#include \"tensorflow\/compiler\/tf2tensorrt\/convert\/trt_optimization_pass.h\"\n\n#include \"absl\/strings\/ascii.h\"\n#include \"absl\/strings\/escaping.h\"\n#include \"absl\/strings\/str_cat.h\"\n#include \"tensorflow\/compiler\/tf2tensorrt\/convert\/convert_graph.h\"\n#include \"tensorflow\/compiler\/tf2tensorrt\/convert\/utils.h\"\n#include \"tensorflow\/core\/grappler\/clusters\/cluster.h\"\n#include \"tensorflow\/core\/grappler\/grappler_item.h\"\n#include \"tensorflow\/core\/grappler\/optimizers\/custom_graph_optimizer_registry.h\"\n#include \"tensorflow\/core\/lib\/strings\/numbers.h\"\n#include \"tensorflow\/core\/lib\/strings\/str_util.h\"\n#include \"tensorflow\/core\/lib\/strings\/strcat.h\"\n#include \"tensorflow\/core\/platform\/logging.h\"\n#include \"tensorflow\/core\/platform\/stacktrace.h\"\n\n#if GOOGLE_CUDA && GOOGLE_TENSORRT\nnamespace tensorflow {\nnamespace tensorrt {\nnamespace convert {\n\/\/ TODO(sami): Remove VLOG messages once the code matures\nusing absl::AsciiStrToUpper;\nusing absl::StrAppend;\nusing absl::StrCat;\n\nStatus TRTOptimizationPass::Init(\n const RewriterConfig_CustomGraphOptimizer* config) {\n VLOG(1) << \"Called INIT for \" << name_ << \" with config = \" << config;\n if (config == nullptr) {\n return Status::OK();\n }\n VLOG(1) << \"config = \" << config->DebugString();\n const auto params = config->parameter_map();\n if (params.count(\"minimum_segment_size\")) {\n minimum_segment_size_ = params.at(\"minimum_segment_size\").i();\n }\n if (params.count(\"max_batch_size\")) {\n maximum_batch_size_ = params.at(\"max_batch_size\").i();\n }\n if (params.count(\"is_dynamic_op\")) {\n is_dynamic_op_ = params.at(\"is_dynamic_op\").b();\n }\n if (params.count(\"maximum_cached_engines\")) {\n max_cached_batches_ = params.at(\"maximum_cached_engines\").i();\n }\n if (params.count(\"max_workspace_size_bytes\")) {\n max_workspace_size_bytes_ = params.at(\"max_workspace_size_bytes\").i();\n }\n if (params.count(\"precision_mode\")) {\n TF_RETURN_IF_ERROR(TrtPrecisionModeFromName(\n AsciiStrToUpper(params.at(\"precision_mode\").s()), &precision_mode_));\n }\n if (params.count(\"use_calibration\")) {\n use_calibration_ = params.at(\"use_calibration\").b();\n }\n if (params.count(\"trt_logger\")) {\n trt_logger_name_ = params.at(\"trt_logger\").s();\n }\n if (params.count(\"allow_build_at_runtime\")) {\n allow_build_at_runtime_ = params.at(\"allow_build_at_runtime\").b();\n }\n if (params.count(\"use_implicit_batch\")) {\n use_implicit_batch_ = params.at(\"use_implicit_batch\").b();\n }\n return Status::OK();\n}\n\nvoid TRTOptimizationPass::PrintDebugInfo(grappler::Cluster* cluster,\n const grappler::GrapplerItem& item) {\n LOG(INFO) << \"Cluster = \" << cluster;\n string offset(\" \");\n string offset2 = StrCat(offset, offset);\n string offset3 = StrCat(offset2, offset);\n string offset4 = StrCat(offset2, offset2);\n\n if (cluster) {\n LOG(INFO) << offset << \"type = \" << cluster->type();\n LOG(INFO) << offset << \"num warmup steps = \" << cluster->NumWarmupSteps();\n const auto dev_names = cluster->GetDeviceNames();\n if (!dev_names.empty()) {\n LOG(INFO) << offset << \" Device names:\";\n for (const auto& s : dev_names) {\n LOG(INFO) << offset2 << s;\n }\n }\n std::unordered_map peak_mem;\n auto status = cluster->GetPeakMemoryUsage(&peak_mem);\n if (status == Status::OK()) {\n LOG(INFO) << offset << \"Peak Memory Usage :\";\n for (const auto& s : peak_mem) {\n LOG(INFO) << offset2 << s.first << \" = \" << s.second;\n }\n }\n\n const auto dev_props = cluster->GetDevices();\n if (!dev_props.empty()) {\n LOG(INFO) << offset << \"Device properties:\";\n for (const auto& k : dev_props) {\n LOG(INFO) << offset2 << k.first;\n const auto& dt = k.second;\n LOG(INFO) << offset3 << \"type = \" << dt.type();\n LOG(INFO) << offset3 << \"vendor = \" << dt.vendor();\n LOG(INFO) << offset3 << \"model = \" << dt.model();\n LOG(INFO) << offset3 << \"frequency = \" << dt.frequency();\n LOG(INFO) << offset3 << \"num cores = \" << dt.num_cores();\n LOG(INFO) << offset3 << \"num registers = \" << dt.num_registers();\n LOG(INFO) << offset3 << \"L1 cache size = \" << dt.l1_cache_size();\n LOG(INFO) << offset3 << \"L2 cache size = \" << dt.l2_cache_size();\n LOG(INFO) << offset3 << \"L3 cache size = \" << dt.l3_cache_size();\n LOG(INFO) << offset3 << \"SHMem per SMP = \"\n << dt.shared_memory_size_per_multiprocessor();\n LOG(INFO) << offset3 << \"memory size = \" << dt.memory_size();\n LOG(INFO) << offset3 << \"bandwidth = \" << dt.bandwidth();\n if (dt.environment_size()) {\n LOG(INFO) << offset3 << \"environment :\";\n for (const auto& e : dt.environment()) {\n LOG(INFO) << offset4 << e.first << \" = \" << e.second;\n }\n }\n }\n }\n\n if (cluster->GetDeviceSet()) {\n for (const auto dev : cluster->GetDeviceSet()->devices()) {\n LOG(INFO) << \"Device name= \" << dev->name() << \"Pased name= \"\n << DeviceNameUtils::ParsedNameToString(dev->parsed_name());\n }\n }\n }\n\n LOG(INFO) << \"item: \" << item.id;\n if (!item.feed.empty()) {\n LOG(INFO) << offset << \"Feeds :\";\n for (const auto& f : item.feed) {\n const auto& shape = f.second.shape();\n LOG(INFO) << offset2 << f.first << \" = shaped \" << shape.DebugString();\n }\n } else {\n LOG(INFO) << offset << \"No Feeds\";\n }\n if (!item.fetch.empty()) {\n LOG(INFO) << offset << \"Fetches :\";\n for (const auto& f : item.fetch) {\n LOG(INFO) << offset2 << f;\n }\n } else {\n LOG(INFO) << offset << \"No Fetches\";\n }\n\n if (!item.init_ops.empty()) {\n LOG(INFO) << offset << \"init ops :\";\n for (const auto& f : item.init_ops) {\n LOG(INFO) << offset2 << f;\n }\n } else {\n LOG(INFO) << offset << \"No init ops\";\n }\n LOG(INFO) << \"Save Op = \" << item.save_op;\n LOG(INFO) << \"Restore Op = \" << item.restore_op;\n LOG(INFO) << \"save_restore_loc_tensor = \" << item.save_restore_loc_tensor;\n if (!item.keep_ops.empty()) {\n LOG(INFO) << offset << \"keep ops :\";\n for (const auto& f : item.keep_ops) {\n LOG(INFO) << offset2 << f;\n }\n } else {\n LOG(INFO) << offset << \"No keep ops\";\n }\n}\n\nStatus TRTOptimizationPass::Optimize(grappler::Cluster* cluster,\n const grappler::GrapplerItem& item,\n GraphDef* optimized_graph) {\n VLOG(1) << \"Called TRTOptimization Pass \" << name_;\n \/\/ This is a hack to workaround optimizer issue. MetaOptimizer calls\n \/\/ optimization passes on function objects as well, we should not modify\n \/\/ generated funcdefs! This is fragile but we don't have any other option\n \/\/ until framework fixes it.\n if (item.id != \"tf_graph\") {\n VLOG(1) << \"Called TRTOptimization Pass \" << name_\n << \" on a grappler item with id=\" << item.id\n << \", which is probably a function object (funcdef). \"\n << \"Skipping optimization because TensorRTOptimizer \"\n << \"should not be called on function objects.\";\n *optimized_graph = item.graph;\n return Status::OK();\n }\n if (VLOG_IS_ON(3)) {\n LOG(INFO) << CurrentStackTrace();\n PrintDebugInfo(cluster, item);\n }\n\n if (use_calibration_ && precision_mode_ != TrtPrecisionMode::INT8) {\n VLOG(1) << \"Calibration with FP32 or FP16 is not implemented. \"\n << \"Falling back to use_calibration = False.\"\n << \"Note that the default value of use_calibration is True.\";\n use_calibration_ = false;\n }\n\n std::vector nodes_to_preserve;\n for (const auto& n : item.NodesToPreserve()) {\n auto tokens = str_util::Split(n, \":\");\n string s = tokens.at(0);\n for (int i = 1; i < tokens.size() - 1; ++i) {\n StrAppend(&s, \":\", tokens.at(i));\n }\n int dumm_port = -1;\n \/\/ If the last token is not an integer, it must be part of the name.\n \/\/ Otherwise it is port number.\n if (tokens.size() > 1 &&\n !strings::safe_strto32(tokens.back(), &dumm_port)) { \/\/ non-absl ok\n StrAppend(&s, \":\", tokens.back());\n }\n nodes_to_preserve.push_back(s);\n }\n\n ConversionParams cp;\n cp.grappler_item = &item;\n cp.output_names = &nodes_to_preserve;\n cp.trt_logger_name = trt_logger_name_;\n cp.max_batch_size = maximum_batch_size_;\n cp.max_workspace_size_bytes = max_workspace_size_bytes_;\n cp.output_graph_def = optimized_graph;\n cp.precision_mode = precision_mode_;\n cp.minimum_segment_size = minimum_segment_size_;\n cp.cluster = cluster;\n cp.is_dyn_op = is_dynamic_op_;\n cp.max_cached_engines = max_cached_batches_;\n cp.use_calibration = use_calibration_;\n cp.use_implicit_batch = use_implicit_batch_;\n cp.allow_build_at_runtime = allow_build_at_runtime_;\n auto status = ConvertAfterShapes(cp);\n VLOG(1) << \"Returning from \" << name_;\n return status;\n}\n\nvoid TRTOptimizationPass::Feedback(grappler::Cluster* cluster,\n const grappler::GrapplerItem& item,\n const GraphDef& optimized_graph,\n double result) {}\n\nclass VerboseCustomGraphOptimizerRegistrar\n : public grappler::CustomGraphOptimizerRegistrar {\n public:\n VerboseCustomGraphOptimizerRegistrar(\n const grappler::CustomGraphOptimizerRegistry::Creator& cr,\n const string& name)\n : grappler::CustomGraphOptimizerRegistrar(cr, name) {\n VLOG(1) << \"Constructing a CustomOptimizationPass registration object for \"\n << name;\n }\n};\n\nstatic VerboseCustomGraphOptimizerRegistrar TRTOptimizationPass_Registrar(\n []() {\n VLOG(1)\n << \"Instantiating CustomOptimizationPass object TensorRTOptimizer\";\n return new TRTOptimizationPass(\"TensorRTOptimizer\");\n },\n (\"TensorRTOptimizer\"));\n\n} \/\/ namespace convert\n} \/\/ namespace tensorrt\n} \/\/ namespace tensorflow\n\n#endif \/\/ GOOGLE_CUDA && GOOGLE_TENSORRT\n<|endoftext|>"} {"text":"\/* Copyright 2019 The TensorFlow Authors. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*\/\n\n#include \"tensorflow\/lite\/delegates\/gpu\/common\/transformations\/add_bias.h\"\n\n#include \"absl\/memory\/memory.h\"\n#include \"absl\/strings\/str_cat.h\"\n#include \"absl\/types\/any.h\"\n#include \"tensorflow\/lite\/delegates\/gpu\/common\/data_type.h\"\n#include \"tensorflow\/lite\/delegates\/gpu\/common\/model.h\"\n#include \"tensorflow\/lite\/delegates\/gpu\/common\/operations.h\"\n#include \"tensorflow\/lite\/delegates\/gpu\/common\/status.h\"\n\nnamespace tflite {\nnamespace gpu {\nnamespace {\n\nTransformResult FillBias(\n int output_channels,\n tflite::gpu::Tensor* biases) {\n if (biases->data.empty()) {\n *biases =\n MakeZeroTensor(Linear(output_channels));\n return {TransformStatus::APPLIED, \"Added bias\"};\n }\n if (biases->shape.v != output_channels) {\n float last_value = biases->data.back();\n biases->shape.v = output_channels;\n biases->data.resize(output_channels, last_value);\n return {TransformStatus::APPLIED, \"Bias extended\"};\n }\n return {TransformStatus::SKIPPED, \"\"};\n}\n\nclass AddBias : public NodeTransformation {\n public:\n TransformResult ApplyToNode(Node* node, GraphFloat32* graph) final {\n if (node->operation.type == ToString(OperationType::CONVOLUTION_2D)) {\n auto& attr =\n absl::any_cast(node->operation.attributes);\n return FillBias(attr.weights.shape.o, &attr.bias);\n }\n if (node->operation.type ==\n ToString(OperationType::CONVOLUTION_TRANSPOSED)) {\n auto& attr = absl::any_cast(\n node->operation.attributes);\n return FillBias(attr.weights.shape.o, &attr.bias);\n }\n if (node->operation.type ==\n ToString(OperationType::DEPTHWISE_CONVOLUTION)) {\n auto& attr = absl::any_cast(\n node->operation.attributes);\n return FillBias(attr.weights.shape.o * attr.weights.shape.i, &attr.bias);\n }\n if (node->operation.type == ToString(OperationType::FULLY_CONNECTED)) {\n auto& attr =\n absl::any_cast(node->operation.attributes);\n return FillBias(attr.weights.shape.o, &attr.bias);\n }\n return {TransformStatus::SKIPPED, \"\"};\n }\n};\n\n} \/\/ namespace\n\nstd::unique_ptr NewAddBias() {\n return absl::make_unique();\n}\n\n} \/\/ namespace gpu\n} \/\/ namespace tflite\nFixed add bias transformation. Added check for convolution with dynamic weights.\/* Copyright 2019 The TensorFlow Authors. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*\/\n\n#include \"tensorflow\/lite\/delegates\/gpu\/common\/transformations\/add_bias.h\"\n\n#include \"absl\/memory\/memory.h\"\n#include \"absl\/strings\/str_cat.h\"\n#include \"absl\/types\/any.h\"\n#include \"tensorflow\/lite\/delegates\/gpu\/common\/data_type.h\"\n#include \"tensorflow\/lite\/delegates\/gpu\/common\/model.h\"\n#include \"tensorflow\/lite\/delegates\/gpu\/common\/operations.h\"\n#include \"tensorflow\/lite\/delegates\/gpu\/common\/status.h\"\n\nnamespace tflite {\nnamespace gpu {\nnamespace {\n\nTransformResult FillBias(\n int output_channels,\n tflite::gpu::Tensor* biases) {\n if (biases->data.empty()) {\n *biases =\n MakeZeroTensor(Linear(output_channels));\n return {TransformStatus::APPLIED, \"Added bias\"};\n }\n if (biases->shape.v != output_channels) {\n float last_value = biases->data.back();\n biases->shape.v = output_channels;\n biases->data.resize(output_channels, last_value);\n return {TransformStatus::APPLIED, \"Bias extended\"};\n }\n return {TransformStatus::SKIPPED, \"\"};\n}\n\nclass AddBias : public NodeTransformation {\n public:\n TransformResult ApplyToNode(Node* node, GraphFloat32* graph) final {\n if (node->operation.type == ToString(OperationType::CONVOLUTION_2D)) {\n if (graph->FindInputs(node->id).size() != 1) {\n return {TransformStatus::DECLINED,\n \"This transformation is only applicable to conv with one \"\n \"runtime input.\"};\n }\n auto& attr =\n absl::any_cast(node->operation.attributes);\n return FillBias(attr.weights.shape.o, &attr.bias);\n }\n if (node->operation.type ==\n ToString(OperationType::CONVOLUTION_TRANSPOSED)) {\n auto& attr = absl::any_cast(\n node->operation.attributes);\n return FillBias(attr.weights.shape.o, &attr.bias);\n }\n if (node->operation.type ==\n ToString(OperationType::DEPTHWISE_CONVOLUTION)) {\n auto& attr = absl::any_cast(\n node->operation.attributes);\n return FillBias(attr.weights.shape.o * attr.weights.shape.i, &attr.bias);\n }\n if (node->operation.type == ToString(OperationType::FULLY_CONNECTED)) {\n auto& attr =\n absl::any_cast(node->operation.attributes);\n return FillBias(attr.weights.shape.o, &attr.bias);\n }\n return {TransformStatus::SKIPPED, \"\"};\n }\n};\n\n} \/\/ namespace\n\nstd::unique_ptr NewAddBias() {\n return absl::make_unique();\n}\n\n} \/\/ namespace gpu\n} \/\/ namespace tflite\n<|endoftext|>"} {"text":"AliAnalysisTaskCorrForFlowFMD* AddCorrForFlowTaskFMD(TString name = \"name\", TString efficiencyFile = \"\",TString calibrationFile = \"\",const char* suffix = \"\")\n{\n AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();\n if (!mgr) {\n return 0x0;\n }\n if (!mgr->GetInputEventHandler()) {\n return 0x0;\n }\n TString fileName = AliAnalysisManager::GetCommonFileName();\n fileName += \":CorrForFlow\";\n TString taskName = Form(\"%s_%s\",name.Data(),suffix);\n\n Bool_t useEfficiency = kFALSE;\n if(!efficiencyFile.IsNull()) useEfficiency = kTRUE;\n\n Bool_t useCalibration = kFALSE;\n if(!calibrationFile.IsNull()) useCalibration = kTRUE;\n\n AliAnalysisTaskCorrForFlowFMD* task = new AliAnalysisTaskCorrForFlowFMD(taskName.Data(), useEfficiency, useCalibration);\n if(!task) return 0x0;\n mgr->AddTask(task);\n mgr->ConnectInput(task,0,mgr->GetCommonInputContainer());\n mgr->ConnectOutput(task,1,mgr->CreateContainer(Form(\"Charged_%s\",taskName.Data()), TList::Class(), AliAnalysisManager::kOutputContainer, fileName.Data()));\n\n if(useEfficiency) {\n TObjArray* taskContainers = mgr->GetContainers();\n if(!taskContainers) { printf(\"Task containers does not exists!\\n\"); return NULL; }\n\n AliAnalysisDataContainer* efficiency = (AliAnalysisDataContainer*) taskContainers->FindObject(\"inputEfficiency\");\n if(!efficiency) {\n if(efficiencyFile.Contains(\"alien:\/\/\")) { gGrid->Connect(\"alien:\/\/\"); }\n\n printf(\"input file name: %s \\n\", efficiencyFile.Data());\n\n TFile* efficiency_file = TFile::Open(efficiencyFile.Data(),\"READ\");\n if(!efficiency_file) { printf(\"Input file with efficiency not found!\\n\"); return NULL; }\n\n TList* efficiency_list = (TList*) efficiency_file->Get(\"EffAndFD\");\n if(!efficiency_list) { printf(\"E-AddTask: Input list with efficiency not found!\\n\"); efficiency_file->ls(); return NULL; }\n\n AliAnalysisDataContainer* cInputEfficiency = mgr->CreateContainer(\"inputEfficiency\",TList::Class(), AliAnalysisManager::kInputContainer);\n cInputEfficiency->SetData(efficiency_list);\n mgr->ConnectInput(task,1,cInputEfficiency);\n }\n else {\n mgr->ConnectInput(task,1,efficiency);\n }\n }\n\n if(useCalibration) {\n TObjArray* taskContainers = mgr->GetContainers();\n if(!taskContainers) { printf(\"Task containers does not exists!\\n\"); return NULL; }\n\n AliAnalysisDataContainer* calib = (AliAnalysisDataContainer*) taskContainers->FindObject(\"calib\");\n if(!calib) {\n if(calibrationFile.Contains(\"alien:\/\/\")) { gGrid->Connect(\"alien:\/\/\"); }\n\n printf(\"input file name: %s \\n\", calibrationFile.Data());\n\n TFile* calib_file = TFile::Open(calibrationFile.Data(),\"READ\");\n if(!calib_file) { printf(\"Input file with AMPT centrality calibration not found!\\n\"); return NULL; }\n\n TH1D* calib_histo = (TH1D*)calib_file->Get(\"hcent\");\n if(!calib_histo) { printf(\"E-AddTask: Input list with AMPT centrality calibration not found!\\n\"); calib_file->ls(); return NULL; }\n\n AliAnalysisDataContainer* cInputCalib = mgr->CreateContainer(\"calib\",TH1D::Class(), AliAnalysisManager::kInputContainer);\n cInputCalib->SetData(calib_histo);\n if(useEfficiency) mgr->ConnectInput(task,2,cInputCalib);\n else mgr->ConnectInput(task,1,cInputCalib);\n }\n else {\n if(useEfficiency) mgr->ConnectInput(task,2,calib);\n else mgr->ConnectInput(task,1,calib);\n }\n }\n\n return task;\n}\nReading the efficiency fileAliAnalysisTaskCorrForFlowFMD* AddCorrForFlowTaskFMD(TString name = \"name\", TString efficiencyFile = \"\",TString calibrationFile = \"\",const char* suffix = \"\")\n{\n AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();\n if (!mgr) {\n return 0x0;\n }\n if (!mgr->GetInputEventHandler()) {\n return 0x0;\n }\n TString fileName = AliAnalysisManager::GetCommonFileName();\n fileName += \":CorrForFlow\";\n TString taskName = Form(\"%s_%s\",name.Data(),suffix);\n\n Bool_t useEfficiency = kFALSE;\n if(!efficiencyFile.IsNull()) useEfficiency = kTRUE;\n\n Bool_t useCalibration = kFALSE;\n if(!calibrationFile.IsNull()) useCalibration = kTRUE;\n\n AliAnalysisTaskCorrForFlowFMD* task = new AliAnalysisTaskCorrForFlowFMD(taskName.Data(), useEfficiency, useCalibration);\n if(!task) return 0x0;\n mgr->AddTask(task);\n mgr->ConnectInput(task,0,mgr->GetCommonInputContainer());\n mgr->ConnectOutput(task,1,mgr->CreateContainer(Form(\"Charged_%s\",taskName.Data()), TList::Class(), AliAnalysisManager::kOutputContainer, fileName.Data()));\n\n if(useEfficiency) {\n TObjArray* taskContainers = mgr->GetContainers();\n if(!taskContainers) { printf(\"Task containers does not exists!\\n\"); return NULL; }\n\n AliAnalysisDataContainer* efficiency = (AliAnalysisDataContainer*) taskContainers->FindObject(\"inputEfficiency\");\n if(!efficiency) {\n if(efficiencyFile.Contains(\"alien:\/\/\")) { gGrid->Connect(\"alien:\/\/\"); }\n\n printf(\"input file name: %s \\n\", efficiencyFile.Data());\n\n TFile* efficiency_file = TFile::Open(efficiencyFile.Data(),\"READ\");\n if(!efficiency_file) { printf(\"Input file with efficiency not found!\\n\"); return NULL; }\n\n TList* efficiency_list = (TList*) efficiency_file->Get(\"Efficiency2D_wFD\");\n if(!efficiency_list) { printf(\"E-AddTask: Input list with efficiency not found!\\n\"); efficiency_file->ls(); return NULL; }\n\n AliAnalysisDataContainer* cInputEfficiency = mgr->CreateContainer(\"inputEfficiency\",TList::Class(), AliAnalysisManager::kInputContainer);\n cInputEfficiency->SetData(efficiency_list);\n mgr->ConnectInput(task,1,cInputEfficiency);\n }\n else {\n mgr->ConnectInput(task,1,efficiency);\n }\n }\n\n if(useCalibration) {\n TObjArray* taskContainers = mgr->GetContainers();\n if(!taskContainers) { printf(\"Task containers does not exists!\\n\"); return NULL; }\n\n AliAnalysisDataContainer* calib = (AliAnalysisDataContainer*) taskContainers->FindObject(\"calib\");\n if(!calib) {\n if(calibrationFile.Contains(\"alien:\/\/\")) { gGrid->Connect(\"alien:\/\/\"); }\n\n printf(\"input file name: %s \\n\", calibrationFile.Data());\n\n TFile* calib_file = TFile::Open(calibrationFile.Data(),\"READ\");\n if(!calib_file) { printf(\"Input file with AMPT centrality calibration not found!\\n\"); return NULL; }\n\n TH1D* calib_histo = (TH1D*)calib_file->Get(\"hcent\");\n if(!calib_histo) { printf(\"E-AddTask: Input list with AMPT centrality calibration not found!\\n\"); calib_file->ls(); return NULL; }\n\n AliAnalysisDataContainer* cInputCalib = mgr->CreateContainer(\"calib\",TH1D::Class(), AliAnalysisManager::kInputContainer);\n cInputCalib->SetData(calib_histo);\n if(useEfficiency) mgr->ConnectInput(task,2,cInputCalib);\n else mgr->ConnectInput(task,1,cInputCalib);\n }\n else {\n if(useEfficiency) mgr->ConnectInput(task,2,calib);\n else mgr->ConnectInput(task,1,calib);\n }\n }\n\n return task;\n}\n<|endoftext|>"} {"text":"#include \"tcp_socket.h\"\r\n#include \"thread_manager.h\"\r\n\r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n\r\n#define ONCE 0\r\n\r\nvoid onError(void* arg, err_t err)\r\n{\r\n TCPSocket* socket = reinterpret_cast(arg);\r\n if(socket) {\r\n socket->OnError(err);\r\n }\r\n}\r\n\r\nvoid dnsFoundCallback(const char *name, const ip_addr_t *ipaddr, void *callback_arg)\r\n{\r\n uint32_t threadId = (uint32_t)(*reinterpret_cast(callback_arg));\r\n if(ipaddr) {\r\n (*reinterpret_cast(callback_arg)) = ipaddr->addr;\r\n }\r\n ThreadManager::GetInstance().ResumeThread(threadId);\r\n}\r\n\r\nerr_t onTcpConnect(void* arg, tcp_pcb* tpcb, err_t err)\r\n{\r\n TCPSocket* socket = reinterpret_cast(arg);\r\n if(socket) {\r\n return socket->OnConnect(tpcb, err);\r\n }\r\n \r\n return ERR_VAL;\r\n}\r\n\r\nerr_t onTCPRecv(void *arg, struct tcp_pcb *tpcb, struct pbuf *pb, err_t err)\r\n{\r\n TCPSocket* socket = reinterpret_cast(arg);\r\n if(socket) {\r\n return socket->OnTCPRecv(tpcb, pb, err);\r\n }\r\n \r\n return ERR_VAL;\r\n}\r\n\r\nerr_t onTCPSent(void *arg, struct tcp_pcb *tpcb, uint16_t len)\r\n{\r\n TCPSocket* socket = reinterpret_cast(arg);\r\n if(socket) {\r\n return socket->OnTCPSent(tpcb, len);\r\n }\r\n \r\n return ERR_VAL;\r\n}\r\n\r\nvoid onSendError(void *arg)\r\n{\r\n TCPSocket* socket = reinterpret_cast(arg);\r\n if(socket) {\r\n return socket->OnError(ERR_ABRT);\r\n }\r\n}\r\n\r\nTCPSocket::TCPSocket()\r\n: m_buf_offset(0)\r\n, m_buf(0)\r\n, m_sentSize(0)\r\n, m_suspendedThread(-1)\r\n, m_suspendedRecvThread(-1)\r\n, m_suspendedSendThread(-1)\r\n{\r\n\tInitialize();\r\n}\r\n\r\nTCPSocket::~TCPSocket()\r\n{\r\n\tClose();\r\n}\r\n\r\nbool TCPSocket::Bind(const String& host, int port)\r\n{\r\n\tif(m_socket == INVALID_SOCKET)\r\n\t{\r\n\t\treturn false;\r\n\t}\r\n\r\n ip_addr_t ipaddr;\r\n\tif(host.length() == 0)\r\n\t{\r\n ipaddr = ip_addr_any;\r\n\t}\r\n\telse\r\n\t{\r\n IPAddress ipaddress(ThreadManager::GetInstance().GetCurrentThreadId());\r\n if(!ipaddress.fromString(host)) {\r\n err_t err = dns_gethostbyname(host.c_str(), &ipaddr, &dnsFoundCallback, &ipaddress);\r\n if(err == ERR_INPROGRESS) {\r\n ThreadManager::GetInstance().SuspendThread(ThreadManager::GetInstance().GetCurrentThreadId());\r\n \/\/ will return here when dns_found_callback fires\r\n } else if(err != ERR_OK) {\r\n return false;\r\n }\r\n }\r\n \r\n ipaddr.addr = ipaddress;\r\n\t}\r\n\t\r\n\treturn tcp_bind(m_socket, &ipaddr, port) == ERR_OK;\r\n}\r\n\r\nbool TCPSocket::Connect(const String& host, int port)\r\n{\r\n\tif(m_socket == INVALID_SOCKET || host.length() == 0)\r\n\t{\r\n\t\treturn false;\r\n\t}\r\n\r\n ip_addr_t ipaddr;\r\n if(host.length() == 0)\r\n {\r\n ipaddr = ip_addr_any;\r\n }\r\n else\r\n {\r\n IPAddress ipaddress;\r\n if(!ipaddress.fromString(host)) {\r\n err_t err = dns_gethostbyname(host.c_str(), &ipaddr, &dnsFoundCallback, &ipaddress);\r\n if(err == ERR_INPROGRESS) {\r\n m_suspendedThread = ThreadManager::GetInstance().GetCurrentThreadId();\r\n ThreadManager::GetInstance().SuspendThread(m_suspendedThread);\r\n } else if(err != ERR_OK) {\r\n return false;\r\n }\r\n }\r\n \r\n ipaddr.addr = ipaddress;\r\n }\r\n \r\n err_t err = tcp_connect(m_socket, &ipaddr, port, &onTcpConnect);\r\n if(err == ERR_OK || err == ERR_INPROGRESS) {\r\n m_suspendedThread = ThreadManager::GetInstance().GetCurrentThreadId();\r\n ThreadManager::GetInstance().SuspendThread(m_suspendedThread);\r\n }\r\n return m_lastError == ERR_OK;\r\n}\r\n\r\nbool TCPSocket::Send(char* data, int len)\r\n{\r\n \/\/wait until other thread will send data\r\n while(m_suspendedSendThread > -1) {\r\n ThreadManager::GetInstance().DelayThread(ThreadManager::GetInstance().GetCurrentThreadId(), 100);\r\n }\r\n \r\n while(len) {\r\n if(m_socket == INVALID_SOCKET)\r\n {\r\n return false;\r\n }\r\n \r\n size_t room = tcp_sndbuf(m_socket);\r\n size_t will_send = (room < len) ? room : len;\r\n \r\n err_t err = tcp_write(m_socket, data, will_send, 0);\r\n if(err != ERR_OK) {\r\n return false;\r\n }\r\n \r\n data += will_send;\r\n len -= will_send;\r\n m_sentSize = 0;\r\n tcp_output(m_socket);\r\n \r\n \/\/ waiting to send tcp data\r\n while(m_sentSize != will_send && m_socket != INVALID_SOCKET) {\r\n os_timer_disarm(&m_sendErrorTimer);\r\n os_timer_setfn(&m_sendErrorTimer, &onSendError, this);\r\n os_timer_arm(&m_sendErrorTimer, 1500, ONCE);\r\n m_suspendedSendThread = ThreadManager::GetInstance().GetCurrentThreadId();\r\n ThreadManager::GetInstance().SuspendThread(m_suspendedSendThread);\r\n }\r\n }\r\n\t\r\n\treturn true;\r\n}\r\n\r\nbool TCPSocket::Recv(char* data, int len)\r\n{ \r\n while(len) {\r\n if(m_socket == INVALID_SOCKET)\r\n {\r\n return false;\r\n }\r\n\r\n if(!m_buf) {\r\n m_suspendedRecvThread = ThreadManager::GetInstance().GetCurrentThreadId();\r\n ThreadManager::GetInstance().SuspendThread(m_suspendedRecvThread);\r\n }\r\n \r\n if(m_buf) {\r\n size_t max_size = m_buf->tot_len - m_buf_offset;\r\n size_t size = (len < max_size) ? len : max_size;\r\n size_t buf_size = m_buf->len - m_buf_offset;\r\n size_t copy_size = (size < buf_size) ? size : buf_size;\r\n os_memcpy(data, reinterpret_cast(m_buf->payload) + m_buf_offset, copy_size);\r\n data += copy_size;\r\n len -= copy_size;\r\n Consume(copy_size);\r\n }\r\n }\r\n \r\n\treturn true;\r\n}\r\nvoid TCPSocket::Consume(size_t size)\r\n{\r\n ptrdiff_t left = m_buf->len - m_buf_offset - size;\r\n if(left > 0) {\r\n m_buf_offset += size;\r\n } else if(!m_buf->next) {\r\n if(m_socket) tcp_recved(m_socket, m_buf->len);\r\n pbuf_free(m_buf);\r\n m_buf = 0;\r\n m_buf_offset = 0;\r\n } else {\r\n auto head = m_buf;\r\n m_buf = m_buf->next;\r\n m_buf_offset = 0;\r\n pbuf_ref(m_buf);\r\n if(m_socket) tcp_recved(m_socket, head->len);\r\n pbuf_free(head);\r\n }\r\n}\r\n\r\nbool TCPSocket::Close()\r\n{\r\n\tif(m_socket == INVALID_SOCKET)\r\n\t{\r\n\t\treturn false;\r\n\t}\r\n\t\r\n tcp_arg(m_socket, NULL);\r\n tcp_sent(m_socket, NULL);\r\n tcp_recv(m_socket, NULL);\r\n tcp_err(m_socket, NULL);\r\n tcp_close(m_socket);\r\n m_socket = INVALID_SOCKET;\r\n return true;\r\n}\r\n\r\nvoid TCPSocket::GetIPPort(String& ip, int& port)\r\n{\r\n IPAddress address(m_socket->remote_ip.addr);\r\n ip = address.toString();\r\n port = m_socket->remote_port;\r\n}\r\n\r\nint TCPSocket::GetSocket()\r\n{\r\n\treturn *(int*)m_socket;\r\n}\r\n\r\nvoid TCPSocket::Initialize()\r\n{\r\n\tm_socket = tcp_new();\r\n if(m_socket) {\r\n tcp_arg(m_socket, this);\r\n tcp_err(m_socket, &onError);\r\n }\r\n}\r\n\r\nint TCPSocket::GetMaxBufferSize()\r\n{\r\n\tif(m_socket == INVALID_SOCKET)\r\n\t{\r\n\t\treturn 0;\r\n\t}\r\n\t\r\n\treturn m_socket->snd_buf;\r\n}\r\n\r\nvoid TCPSocket::OnError(err_t err)\r\n{\r\n m_lastError = err;\r\n tcp_arg(m_socket, NULL);\r\n tcp_sent(m_socket, NULL);\r\n tcp_recv(m_socket, NULL);\r\n tcp_err(m_socket, NULL);\r\n m_socket = INVALID_SOCKET;\r\n if(m_suspendedThread != -1) {\r\n ThreadManager::GetInstance().ResumeThread(m_suspendedThread);\r\n m_suspendedThread = -1;\r\n } else if(m_suspendedRecvThread != -1) {\r\n ThreadManager::GetInstance().ResumeThread(m_suspendedRecvThread);\r\n m_suspendedRecvThread = -1;\r\n } else if(m_suspendedSendThread != -1) {\r\n ThreadManager::GetInstance().ResumeThread(m_suspendedSendThread);\r\n m_suspendedSendThread = -1;\r\n }\r\n}\r\n\r\nerr_t TCPSocket::OnConnect(tcp_pcb* tpcb, err_t err)\r\n{\r\n m_lastError = ERR_OK;\r\n m_socket = tpcb;\r\n tcp_setprio(m_socket, TCP_PRIO_MIN);\r\n tcp_arg(m_socket, this);\r\n tcp_recv(m_socket, (tcp_recv_fn)&onTCPRecv);\r\n tcp_sent(m_socket, &onTCPSent);\r\n tcp_err(m_socket, &onError);\r\n if(m_suspendedThread != -1) {\r\n ThreadManager::GetInstance().ResumeThread(m_suspendedThread);\r\n m_suspendedThread = -1;\r\n }\r\n return ERR_OK;\r\n}\r\n\r\nerr_t TCPSocket::OnTCPRecv(tcp_pcb* tpcb, pbuf* pb, err_t err)\r\n{\r\n err_t ret;\r\n if(!pb) {\r\n tcp_arg(m_socket, NULL);\r\n tcp_sent(m_socket, NULL);\r\n tcp_recv(m_socket, NULL);\r\n tcp_err(m_socket, NULL);\r\n tcp_abort(m_socket);\r\n m_socket = INVALID_SOCKET;\r\n ret = ERR_ABRT;\r\n } else {\r\n m_lastError = err;\r\n if(m_buf) {\r\n pbuf_cat(m_buf, pb);\r\n } else {\r\n m_buf = pb;\r\n }\r\n ret = ERR_OK;\r\n }\r\n if(m_suspendedRecvThread != -1) {\r\n ThreadManager::GetInstance().ResumeThread(m_suspendedRecvThread);\r\n m_suspendedRecvThread = -1;\r\n }\r\n return ret;\r\n}\r\n\r\nerr_t TCPSocket::OnTCPSent(tcp_pcb* tpcb, uint16_t len)\r\n{\r\n m_lastError = ERR_OK;\r\n m_sentSize = len;\r\n os_timer_disarm(&m_sendErrorTimer);\r\n if(m_suspendedSendThread != -1) {\r\n ThreadManager::GetInstance().ResumeThread(m_suspendedSendThread);\r\n m_suspendedSendThread = -1;\r\n }\r\n return ERR_OK;\r\n}\r\nfix freeze#include \"tcp_socket.h\"\r\n#include \"thread_manager.h\"\r\n\r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n\r\n#define ONCE 0\r\n\r\nvoid onError(void* arg, err_t err)\r\n{\r\n TCPSocket* socket = reinterpret_cast(arg);\r\n if(socket) {\r\n socket->OnError(err);\r\n }\r\n}\r\n\r\nvoid dnsFoundCallback(const char *name, const ip_addr_t *ipaddr, void *callback_arg)\r\n{\r\n uint32_t threadId = (uint32_t)(*reinterpret_cast(callback_arg));\r\n if(ipaddr) {\r\n (*reinterpret_cast(callback_arg)) = ipaddr->addr;\r\n }\r\n ThreadManager::GetInstance().ResumeThread(threadId);\r\n}\r\n\r\nerr_t onTcpConnect(void* arg, tcp_pcb* tpcb, err_t err)\r\n{\r\n TCPSocket* socket = reinterpret_cast(arg);\r\n if(socket) {\r\n return socket->OnConnect(tpcb, err);\r\n }\r\n \r\n return ERR_VAL;\r\n}\r\n\r\nerr_t onTCPRecv(void *arg, struct tcp_pcb *tpcb, struct pbuf *pb, err_t err)\r\n{\r\n TCPSocket* socket = reinterpret_cast(arg);\r\n if(socket) {\r\n return socket->OnTCPRecv(tpcb, pb, err);\r\n }\r\n \r\n return ERR_VAL;\r\n}\r\n\r\nerr_t onTCPSent(void *arg, struct tcp_pcb *tpcb, uint16_t len)\r\n{\r\n TCPSocket* socket = reinterpret_cast(arg);\r\n if(socket) {\r\n return socket->OnTCPSent(tpcb, len);\r\n }\r\n \r\n return ERR_VAL;\r\n}\r\n\r\nvoid onSendError(void *arg)\r\n{\r\n TCPSocket* socket = reinterpret_cast(arg);\r\n if(socket) {\r\n return socket->OnError(ERR_ABRT);\r\n }\r\n}\r\n\r\nTCPSocket::TCPSocket()\r\n: m_buf_offset(0)\r\n, m_buf(0)\r\n, m_sentSize(0)\r\n, m_suspendedThread(-1)\r\n, m_suspendedRecvThread(-1)\r\n, m_suspendedSendThread(-1)\r\n{\r\n\tInitialize();\r\n}\r\n\r\nTCPSocket::~TCPSocket()\r\n{\r\n\tClose();\r\n}\r\n\r\nbool TCPSocket::Bind(const String& host, int port)\r\n{\r\n\tif(m_socket == INVALID_SOCKET)\r\n\t{\r\n\t\treturn false;\r\n\t}\r\n\r\n ip_addr_t ipaddr;\r\n\tif(host.length() == 0)\r\n\t{\r\n ipaddr = ip_addr_any;\r\n\t}\r\n\telse\r\n\t{\r\n IPAddress ipaddress(ThreadManager::GetInstance().GetCurrentThreadId());\r\n if(!ipaddress.fromString(host)) {\r\n err_t err = dns_gethostbyname(host.c_str(), &ipaddr, &dnsFoundCallback, &ipaddress);\r\n if(err == ERR_INPROGRESS) {\r\n ThreadManager::GetInstance().SuspendThread(ThreadManager::GetInstance().GetCurrentThreadId());\r\n \/\/ will return here when dns_found_callback fires\r\n } else if(err != ERR_OK) {\r\n return false;\r\n }\r\n }\r\n \r\n ipaddr.addr = ipaddress;\r\n\t}\r\n\t\r\n\treturn tcp_bind(m_socket, &ipaddr, port) == ERR_OK;\r\n}\r\n\r\nbool TCPSocket::Connect(const String& host, int port)\r\n{\r\n\tif(m_socket == INVALID_SOCKET || host.length() == 0)\r\n\t{\r\n\t\treturn false;\r\n\t}\r\n\r\n ip_addr_t ipaddr;\r\n if(host.length() == 0)\r\n {\r\n ipaddr = ip_addr_any;\r\n }\r\n else\r\n {\r\n IPAddress ipaddress;\r\n if(!ipaddress.fromString(host)) {\r\n err_t err = dns_gethostbyname(host.c_str(), &ipaddr, &dnsFoundCallback, &ipaddress);\r\n if(err == ERR_INPROGRESS) {\r\n m_suspendedThread = ThreadManager::GetInstance().GetCurrentThreadId();\r\n ThreadManager::GetInstance().SuspendThread(m_suspendedThread);\r\n } else if(err != ERR_OK) {\r\n return false;\r\n }\r\n }\r\n \r\n ipaddr.addr = ipaddress;\r\n }\r\n \r\n err_t err = tcp_connect(m_socket, &ipaddr, port, &onTcpConnect);\r\n if(err == ERR_OK || err == ERR_INPROGRESS) {\r\n m_suspendedThread = ThreadManager::GetInstance().GetCurrentThreadId();\r\n ThreadManager::GetInstance().SuspendThread(m_suspendedThread);\r\n }\r\n return m_lastError == ERR_OK;\r\n}\r\n\r\nbool TCPSocket::Send(char* data, int len)\r\n{\r\n \/\/wait until other thread will send data\r\n while(m_suspendedSendThread > -1 && m_socket != INVALID_SOCKET) {\r\n ThreadManager::GetInstance().DelayThread(ThreadManager::GetInstance().GetCurrentThreadId(), 100);\r\n }\r\n \r\n while(len) {\r\n if(m_socket == INVALID_SOCKET)\r\n {\r\n return false;\r\n }\r\n \r\n size_t room = tcp_sndbuf(m_socket);\r\n size_t will_send = (room < len) ? room : len;\r\n \r\n err_t err = tcp_write(m_socket, data, will_send, 0);\r\n if(err != ERR_OK) {\r\n return false;\r\n }\r\n \r\n data += will_send;\r\n len -= will_send;\r\n m_sentSize = 0;\r\n tcp_output(m_socket);\r\n \r\n os_timer_disarm(&m_sendErrorTimer);\r\n os_timer_setfn(&m_sendErrorTimer, &onSendError, this);\r\n os_timer_arm(&m_sendErrorTimer, 1000, ONCE);\r\n \r\n \/\/ waiting to send tcp data\r\n while(m_sentSize != will_send && m_socket != INVALID_SOCKET) {\r\n m_suspendedSendThread = ThreadManager::GetInstance().GetCurrentThreadId();\r\n ThreadManager::GetInstance().SuspendThread(m_suspendedSendThread);\r\n }\r\n }\r\n\t\r\n\treturn true;\r\n}\r\n\r\nbool TCPSocket::Recv(char* data, int len)\r\n{ \r\n while(len) {\r\n if(m_socket == INVALID_SOCKET)\r\n {\r\n return false;\r\n }\r\n\r\n if(!m_buf) {\r\n m_suspendedRecvThread = ThreadManager::GetInstance().GetCurrentThreadId();\r\n ThreadManager::GetInstance().SuspendThread(m_suspendedRecvThread);\r\n }\r\n \r\n if(m_buf) {\r\n size_t max_size = m_buf->tot_len - m_buf_offset;\r\n size_t size = (len < max_size) ? len : max_size;\r\n size_t buf_size = m_buf->len - m_buf_offset;\r\n size_t copy_size = (size < buf_size) ? size : buf_size;\r\n os_memcpy(data, reinterpret_cast(m_buf->payload) + m_buf_offset, copy_size);\r\n data += copy_size;\r\n len -= copy_size;\r\n Consume(copy_size);\r\n }\r\n }\r\n \r\n\treturn true;\r\n}\r\nvoid TCPSocket::Consume(size_t size)\r\n{\r\n ptrdiff_t left = m_buf->len - m_buf_offset - size;\r\n if(left > 0) {\r\n m_buf_offset += size;\r\n } else if(!m_buf->next) {\r\n if(m_socket) tcp_recved(m_socket, m_buf->len);\r\n pbuf_free(m_buf);\r\n m_buf = 0;\r\n m_buf_offset = 0;\r\n } else {\r\n auto head = m_buf;\r\n m_buf = m_buf->next;\r\n m_buf_offset = 0;\r\n pbuf_ref(m_buf);\r\n if(m_socket) tcp_recved(m_socket, head->len);\r\n pbuf_free(head);\r\n }\r\n}\r\n\r\nbool TCPSocket::Close()\r\n{\r\n\tif(m_socket == INVALID_SOCKET)\r\n\t{\r\n\t\treturn false;\r\n\t}\r\n\t\r\n tcp_arg(m_socket, NULL);\r\n tcp_sent(m_socket, NULL);\r\n tcp_recv(m_socket, NULL);\r\n tcp_err(m_socket, NULL);\r\n tcp_close(m_socket);\r\n m_socket = INVALID_SOCKET;\r\n return true;\r\n}\r\n\r\nvoid TCPSocket::GetIPPort(String& ip, int& port)\r\n{\r\n IPAddress address(m_socket->remote_ip.addr);\r\n ip = address.toString();\r\n port = m_socket->remote_port;\r\n}\r\n\r\nint TCPSocket::GetSocket()\r\n{\r\n\treturn *(int*)m_socket;\r\n}\r\n\r\nvoid TCPSocket::Initialize()\r\n{\r\n\tm_socket = tcp_new();\r\n if(m_socket) {\r\n tcp_arg(m_socket, this);\r\n tcp_err(m_socket, &onError);\r\n }\r\n}\r\n\r\nint TCPSocket::GetMaxBufferSize()\r\n{\r\n\tif(m_socket == INVALID_SOCKET)\r\n\t{\r\n\t\treturn 0;\r\n\t}\r\n\t\r\n\treturn m_socket->snd_buf;\r\n}\r\n\r\nvoid TCPSocket::OnError(err_t err)\r\n{\r\n m_lastError = err;\r\n tcp_arg(m_socket, NULL);\r\n tcp_sent(m_socket, NULL);\r\n tcp_recv(m_socket, NULL);\r\n tcp_err(m_socket, NULL);\r\n m_socket = INVALID_SOCKET;\r\n int thread_id;\r\n if(m_suspendedThread != -1) {\r\n thread_id = m_suspendedThread;\r\n m_suspendedThread = -1;\r\n ThreadManager::GetInstance().ResumeThread(thread_id);\r\n } else if(m_suspendedRecvThread != -1) {\r\n thread_id = m_suspendedRecvThread;\r\n m_suspendedRecvThread = -1;\r\n ThreadManager::GetInstance().ResumeThread(thread_id);\r\n } else if(m_suspendedSendThread != -1) {\r\n thread_id = m_suspendedSendThread;\r\n m_suspendedSendThread = -1;\r\n ThreadManager::GetInstance().ResumeThread(thread_id);\r\n }\r\n}\r\n\r\nerr_t TCPSocket::OnConnect(tcp_pcb* tpcb, err_t err)\r\n{\r\n m_lastError = ERR_OK;\r\n m_socket = tpcb;\r\n tcp_setprio(m_socket, TCP_PRIO_MIN);\r\n tcp_arg(m_socket, this);\r\n tcp_recv(m_socket, (tcp_recv_fn)&onTCPRecv);\r\n tcp_sent(m_socket, &onTCPSent);\r\n tcp_err(m_socket, &onError);\r\n if(m_suspendedThread != -1) {\r\n int thread_id = m_suspendedThread;\r\n m_suspendedThread = -1;\r\n ThreadManager::GetInstance().ResumeThread(thread_id);\r\n }\r\n return ERR_OK;\r\n}\r\n\r\nerr_t TCPSocket::OnTCPRecv(tcp_pcb* tpcb, pbuf* pb, err_t err)\r\n{\r\n err_t ret;\r\n if(!pb) {\r\n tcp_arg(m_socket, NULL);\r\n tcp_sent(m_socket, NULL);\r\n tcp_recv(m_socket, NULL);\r\n tcp_err(m_socket, NULL);\r\n tcp_abort(m_socket);\r\n m_socket = INVALID_SOCKET;\r\n ret = ERR_ABRT;\r\n } else {\r\n m_lastError = err;\r\n if(m_buf) {\r\n pbuf_cat(m_buf, pb);\r\n } else {\r\n m_buf = pb;\r\n }\r\n ret = ERR_OK;\r\n }\r\n if(m_suspendedRecvThread != -1) {\r\n int thread_id = m_suspendedRecvThread;\r\n m_suspendedRecvThread = -1;\r\n ThreadManager::GetInstance().ResumeThread(thread_id);\r\n }\r\n return ret;\r\n}\r\n\r\nerr_t TCPSocket::OnTCPSent(tcp_pcb* tpcb, uint16_t len)\r\n{\r\n m_lastError = ERR_OK;\r\n m_sentSize = len;\r\n os_timer_disarm(&m_sendErrorTimer);\r\n if(m_suspendedSendThread != -1) {\r\n int thread_id = m_suspendedSendThread;\r\n m_suspendedSendThread = -1;\r\n ThreadManager::GetInstance().ResumeThread(thread_id);\r\n }\r\n return ERR_OK;\r\n}\r\n<|endoftext|>"} {"text":"\/*\n * Copyright (c) 2012 The WebM project authors. All Rights Reserved.\n *\n * Use of this source code is governed by a BSD-style license\n * that can be found in the LICENSE file in the root of the source\n * tree. An additional intellectual property rights grant can be found\n * in the file PATENTS. All contributing project authors may\n * be found in the AUTHORS file in the root of the source tree.\n *\/\n\n#include \n\n#include \"third_party\/googletest\/src\/include\/gtest\/gtest.h\"\n\n#include \".\/vpx_config.h\"\n#include \".\/y4menc.h\"\n#include \"test\/md5_helper.h\"\n#include \"test\/util.h\"\n#include \"test\/y4m_video_source.h\"\n\nnamespace {\n\nusing std::string;\n\nstatic const unsigned int kWidth = 160;\nstatic const unsigned int kHeight = 90;\nstatic const unsigned int kFrames = 10;\n\nstruct Y4mTestParam {\n const char *filename;\n unsigned int bit_depth;\n vpx_img_fmt format;\n const char *md5raw;\n};\n\nconst Y4mTestParam kY4mTestVectors[] = {\n {\"park_joy_90p_8_420.y4m\", 8, VPX_IMG_FMT_I420,\n \"e5406275b9fc6bb3436c31d4a05c1cab\"},\n {\"park_joy_90p_8_422.y4m\", 8, VPX_IMG_FMT_I422,\n \"284a47a47133b12884ec3a14e959a0b6\"},\n {\"park_joy_90p_8_444.y4m\", 8, VPX_IMG_FMT_I444,\n \"90517ff33843d85de712fd4fe60dbed0\"},\n {\"park_joy_90p_10_420.y4m\", 10, VPX_IMG_FMT_I42016,\n \"63f21f9f717d8b8631bd2288ee87137b\"},\n {\"park_joy_90p_10_422.y4m\", 10, VPX_IMG_FMT_I42216,\n \"48ab51fb540aed07f7ff5af130c9b605\"},\n {\"park_joy_90p_10_444.y4m\", 10, VPX_IMG_FMT_I44416,\n \"067bfd75aa85ff9bae91fa3e0edd1e3e\"},\n {\"park_joy_90p_12_420.y4m\", 12, VPX_IMG_FMT_I42016,\n \"9e6d8f6508c6e55625f6b697bc461cef\"},\n {\"park_joy_90p_12_422.y4m\", 12, VPX_IMG_FMT_I42216,\n \"b239c6b301c0b835485be349ca83a7e3\"},\n {\"park_joy_90p_12_444.y4m\", 12, VPX_IMG_FMT_I44416,\n \"5a6481a550821dab6d0192f5c63845e9\"},\n};\n\nstatic void write_image_file(const vpx_image_t *img, FILE *file) {\n int plane, y;\n for (plane = 0; plane < 3; ++plane) {\n const unsigned char *buf = img->planes[plane];\n const int stride = img->stride[plane];\n const int bytes_per_sample = (img->fmt & VPX_IMG_FMT_HIGHBITDEPTH) ? 2 : 1;\n const int h = (plane ? (img->d_h + img->y_chroma_shift) >>\n img->y_chroma_shift : img->d_h);\n const int w = (plane ? (img->d_w + img->x_chroma_shift) >>\n img->x_chroma_shift : img->d_w);\n for (y = 0; y < h; ++y) {\n fwrite(buf, bytes_per_sample, w, file);\n buf += stride;\n }\n }\n}\n\nclass Y4mVideoSourceTest\n : public ::testing::TestWithParam,\n public ::libvpx_test::Y4mVideoSource {\n protected:\n Y4mVideoSourceTest() : Y4mVideoSource(\"\", 0, 0) {}\n\n virtual ~Y4mVideoSourceTest() {\n CloseSource();\n }\n\n virtual void Init(const std::string &file_name, int limit) {\n file_name_ = file_name;\n start_ = 0;\n limit_ = limit;\n frame_ = 0;\n Begin();\n }\n\n \/\/ Checks y4m header information\n void HeaderChecks(unsigned int bit_depth, vpx_img_fmt_t fmt) {\n ASSERT_TRUE(input_file_ != NULL);\n ASSERT_EQ(y4m_.pic_w, (int)kWidth);\n ASSERT_EQ(y4m_.pic_h, (int)kHeight);\n ASSERT_EQ(img()->d_w, kWidth);\n ASSERT_EQ(img()->d_h, kHeight);\n ASSERT_EQ(y4m_.bit_depth, bit_depth);\n ASSERT_EQ(y4m_.vpx_fmt, fmt);\n if (fmt == VPX_IMG_FMT_I420 || fmt == VPX_IMG_FMT_I42016) {\n ASSERT_EQ(y4m_.bps, (int)y4m_.bit_depth * 3 \/ 2);\n ASSERT_EQ(img()->x_chroma_shift, 1U);\n ASSERT_EQ(img()->y_chroma_shift, 1U);\n }\n if (fmt == VPX_IMG_FMT_I422 || fmt == VPX_IMG_FMT_I42216) {\n ASSERT_EQ(y4m_.bps, (int)y4m_.bit_depth * 2);\n ASSERT_EQ(img()->x_chroma_shift, 1U);\n ASSERT_EQ(img()->y_chroma_shift, 0U);\n }\n if (fmt == VPX_IMG_FMT_I444 || fmt == VPX_IMG_FMT_I44416) {\n ASSERT_EQ(y4m_.bps, (int)y4m_.bit_depth * 3);\n ASSERT_EQ(img()->x_chroma_shift, 0U);\n ASSERT_EQ(img()->y_chroma_shift, 0U);\n }\n }\n\n \/\/ Checks MD5 of the raw frame data\n void Md5Check(const string &expected_md5) {\n ASSERT_TRUE(input_file_ != NULL);\n libvpx_test::MD5 md5;\n for (unsigned int i = start_; i < limit_; i++) {\n md5.Add(img());\n Next();\n }\n ASSERT_EQ(string(md5.Get()), expected_md5);\n }\n};\n\nTEST_P(Y4mVideoSourceTest, SourceTest) {\n const Y4mTestParam t = GetParam();\n Init(t.filename, kFrames);\n HeaderChecks(t.bit_depth, t.format);\n Md5Check(t.md5raw);\n}\n\nINSTANTIATE_TEST_CASE_P(C, Y4mVideoSourceTest,\n ::testing::ValuesIn(kY4mTestVectors));\n\nclass Y4mVideoWriteTest\n : public Y4mVideoSourceTest {\n protected:\n Y4mVideoWriteTest() {}\n\n virtual ~Y4mVideoWriteTest() {\n delete tmpfile_;\n input_file_ = NULL;\n }\n\n void ReplaceInputFile(FILE *input_file) {\n CloseSource();\n frame_ = 0;\n input_file_ = input_file;\n rewind(input_file_);\n ReadSourceToStart();\n }\n\n \/\/ Writes out a y4m file and then reads it back\n void WriteY4mAndReadBack() {\n ASSERT_TRUE(input_file_ != NULL);\n char buf[Y4M_BUFFER_SIZE] = {0};\n const struct VpxRational framerate = {y4m_.fps_n, y4m_.fps_d};\n tmpfile_ = new libvpx_test::TempOutFile;\n ASSERT_TRUE(tmpfile_->file() != NULL);\n y4m_write_file_header(buf, sizeof(buf),\n kWidth, kHeight,\n &framerate, y4m_.vpx_fmt,\n y4m_.bit_depth);\n fputs(buf, tmpfile_->file());\n for (unsigned int i = start_; i < limit_; i++) {\n y4m_write_frame_header(buf, sizeof(buf));\n fputs(buf, tmpfile_->file());\n write_image_file(img(), tmpfile_->file());\n Next();\n }\n ReplaceInputFile(tmpfile_->file());\n }\n\n virtual void Init(const std::string &file_name, int limit) {\n Y4mVideoSourceTest::Init(file_name, limit);\n WriteY4mAndReadBack();\n }\n libvpx_test::TempOutFile *tmpfile_;\n};\n\nTEST_P(Y4mVideoWriteTest, WriteTest) {\n const Y4mTestParam t = GetParam();\n Init(t.filename, kFrames);\n HeaderChecks(t.bit_depth, t.format);\n Md5Check(t.md5raw);\n}\n\nINSTANTIATE_TEST_CASE_P(C, Y4mVideoWriteTest,\n ::testing::ValuesIn(kY4mTestVectors));\n} \/\/ namespace\ny4m_test: fix segfault if test files are missing\/*\n * Copyright (c) 2012 The WebM project authors. All Rights Reserved.\n *\n * Use of this source code is governed by a BSD-style license\n * that can be found in the LICENSE file in the root of the source\n * tree. An additional intellectual property rights grant can be found\n * in the file PATENTS. All contributing project authors may\n * be found in the AUTHORS file in the root of the source tree.\n *\/\n\n#include \n\n#include \"third_party\/googletest\/src\/include\/gtest\/gtest.h\"\n\n#include \".\/vpx_config.h\"\n#include \".\/y4menc.h\"\n#include \"test\/md5_helper.h\"\n#include \"test\/util.h\"\n#include \"test\/y4m_video_source.h\"\n\nnamespace {\n\nusing std::string;\n\nstatic const unsigned int kWidth = 160;\nstatic const unsigned int kHeight = 90;\nstatic const unsigned int kFrames = 10;\n\nstruct Y4mTestParam {\n const char *filename;\n unsigned int bit_depth;\n vpx_img_fmt format;\n const char *md5raw;\n};\n\nconst Y4mTestParam kY4mTestVectors[] = {\n {\"park_joy_90p_8_420.y4m\", 8, VPX_IMG_FMT_I420,\n \"e5406275b9fc6bb3436c31d4a05c1cab\"},\n {\"park_joy_90p_8_422.y4m\", 8, VPX_IMG_FMT_I422,\n \"284a47a47133b12884ec3a14e959a0b6\"},\n {\"park_joy_90p_8_444.y4m\", 8, VPX_IMG_FMT_I444,\n \"90517ff33843d85de712fd4fe60dbed0\"},\n {\"park_joy_90p_10_420.y4m\", 10, VPX_IMG_FMT_I42016,\n \"63f21f9f717d8b8631bd2288ee87137b\"},\n {\"park_joy_90p_10_422.y4m\", 10, VPX_IMG_FMT_I42216,\n \"48ab51fb540aed07f7ff5af130c9b605\"},\n {\"park_joy_90p_10_444.y4m\", 10, VPX_IMG_FMT_I44416,\n \"067bfd75aa85ff9bae91fa3e0edd1e3e\"},\n {\"park_joy_90p_12_420.y4m\", 12, VPX_IMG_FMT_I42016,\n \"9e6d8f6508c6e55625f6b697bc461cef\"},\n {\"park_joy_90p_12_422.y4m\", 12, VPX_IMG_FMT_I42216,\n \"b239c6b301c0b835485be349ca83a7e3\"},\n {\"park_joy_90p_12_444.y4m\", 12, VPX_IMG_FMT_I44416,\n \"5a6481a550821dab6d0192f5c63845e9\"},\n};\n\nstatic void write_image_file(const vpx_image_t *img, FILE *file) {\n int plane, y;\n for (plane = 0; plane < 3; ++plane) {\n const unsigned char *buf = img->planes[plane];\n const int stride = img->stride[plane];\n const int bytes_per_sample = (img->fmt & VPX_IMG_FMT_HIGHBITDEPTH) ? 2 : 1;\n const int h = (plane ? (img->d_h + img->y_chroma_shift) >>\n img->y_chroma_shift : img->d_h);\n const int w = (plane ? (img->d_w + img->x_chroma_shift) >>\n img->x_chroma_shift : img->d_w);\n for (y = 0; y < h; ++y) {\n fwrite(buf, bytes_per_sample, w, file);\n buf += stride;\n }\n }\n}\n\nclass Y4mVideoSourceTest\n : public ::testing::TestWithParam,\n public ::libvpx_test::Y4mVideoSource {\n protected:\n Y4mVideoSourceTest() : Y4mVideoSource(\"\", 0, 0) {}\n\n virtual ~Y4mVideoSourceTest() {\n CloseSource();\n }\n\n virtual void Init(const std::string &file_name, int limit) {\n file_name_ = file_name;\n start_ = 0;\n limit_ = limit;\n frame_ = 0;\n Begin();\n }\n\n \/\/ Checks y4m header information\n void HeaderChecks(unsigned int bit_depth, vpx_img_fmt_t fmt) {\n ASSERT_TRUE(input_file_ != NULL);\n ASSERT_EQ(y4m_.pic_w, (int)kWidth);\n ASSERT_EQ(y4m_.pic_h, (int)kHeight);\n ASSERT_EQ(img()->d_w, kWidth);\n ASSERT_EQ(img()->d_h, kHeight);\n ASSERT_EQ(y4m_.bit_depth, bit_depth);\n ASSERT_EQ(y4m_.vpx_fmt, fmt);\n if (fmt == VPX_IMG_FMT_I420 || fmt == VPX_IMG_FMT_I42016) {\n ASSERT_EQ(y4m_.bps, (int)y4m_.bit_depth * 3 \/ 2);\n ASSERT_EQ(img()->x_chroma_shift, 1U);\n ASSERT_EQ(img()->y_chroma_shift, 1U);\n }\n if (fmt == VPX_IMG_FMT_I422 || fmt == VPX_IMG_FMT_I42216) {\n ASSERT_EQ(y4m_.bps, (int)y4m_.bit_depth * 2);\n ASSERT_EQ(img()->x_chroma_shift, 1U);\n ASSERT_EQ(img()->y_chroma_shift, 0U);\n }\n if (fmt == VPX_IMG_FMT_I444 || fmt == VPX_IMG_FMT_I44416) {\n ASSERT_EQ(y4m_.bps, (int)y4m_.bit_depth * 3);\n ASSERT_EQ(img()->x_chroma_shift, 0U);\n ASSERT_EQ(img()->y_chroma_shift, 0U);\n }\n }\n\n \/\/ Checks MD5 of the raw frame data\n void Md5Check(const string &expected_md5) {\n ASSERT_TRUE(input_file_ != NULL);\n libvpx_test::MD5 md5;\n for (unsigned int i = start_; i < limit_; i++) {\n md5.Add(img());\n Next();\n }\n ASSERT_EQ(string(md5.Get()), expected_md5);\n }\n};\n\nTEST_P(Y4mVideoSourceTest, SourceTest) {\n const Y4mTestParam t = GetParam();\n Init(t.filename, kFrames);\n HeaderChecks(t.bit_depth, t.format);\n Md5Check(t.md5raw);\n}\n\nINSTANTIATE_TEST_CASE_P(C, Y4mVideoSourceTest,\n ::testing::ValuesIn(kY4mTestVectors));\n\nclass Y4mVideoWriteTest\n : public Y4mVideoSourceTest {\n protected:\n Y4mVideoWriteTest() : tmpfile_(NULL) {}\n\n virtual ~Y4mVideoWriteTest() {\n delete tmpfile_;\n input_file_ = NULL;\n }\n\n void ReplaceInputFile(FILE *input_file) {\n CloseSource();\n frame_ = 0;\n input_file_ = input_file;\n rewind(input_file_);\n ReadSourceToStart();\n }\n\n \/\/ Writes out a y4m file and then reads it back\n void WriteY4mAndReadBack() {\n ASSERT_TRUE(input_file_ != NULL);\n char buf[Y4M_BUFFER_SIZE] = {0};\n const struct VpxRational framerate = {y4m_.fps_n, y4m_.fps_d};\n tmpfile_ = new libvpx_test::TempOutFile;\n ASSERT_TRUE(tmpfile_->file() != NULL);\n y4m_write_file_header(buf, sizeof(buf),\n kWidth, kHeight,\n &framerate, y4m_.vpx_fmt,\n y4m_.bit_depth);\n fputs(buf, tmpfile_->file());\n for (unsigned int i = start_; i < limit_; i++) {\n y4m_write_frame_header(buf, sizeof(buf));\n fputs(buf, tmpfile_->file());\n write_image_file(img(), tmpfile_->file());\n Next();\n }\n ReplaceInputFile(tmpfile_->file());\n }\n\n virtual void Init(const std::string &file_name, int limit) {\n Y4mVideoSourceTest::Init(file_name, limit);\n WriteY4mAndReadBack();\n }\n libvpx_test::TempOutFile *tmpfile_;\n};\n\nTEST_P(Y4mVideoWriteTest, WriteTest) {\n const Y4mTestParam t = GetParam();\n Init(t.filename, kFrames);\n HeaderChecks(t.bit_depth, t.format);\n Md5Check(t.md5raw);\n}\n\nINSTANTIATE_TEST_CASE_P(C, Y4mVideoWriteTest,\n ::testing::ValuesIn(kY4mTestVectors));\n} \/\/ namespace\n<|endoftext|>"} {"text":"\/*\n * Copyright 2006-2008 The FLWOR Foundation.\n * \n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * \n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n#include \n#include \"system\/globalenv.h\"\n#include \"types\/typeconstants.h\"\n#include \"types\/typeimpl.h\"\n#include \"types\/typeops.h\"\n#include \"types\/root_typemanager.h\"\n#include \"zorbaerrors\/Assert.h\"\n\n\nnamespace zorba {\n\nconst char* XQType::KIND_STRINGS[XQType::MAX_TYPE_KIND] =\n{\n \"EMPTY_KIND\",\n \"ATOMIC_TYPE_KIND\",\n \"ITEM_KIND\",\n \"NODE_TYPE_KIND\",\n \"ANY_TYPE_KIND\",\n \"ANY_SIMPLE_TYPE_KIND\",\n \"UNTYPED_KIND\",\n \"NONE_KIND\"\n};\n\nconst char *AtomicXQType::ATOMIC_TYPE_CODE_STRINGS[TypeConstants::ATOMIC_TYPE_CODE_LIST_SIZE] =\n{\n \"XS_ANY_ATOMIC\",\n \"XS_STRING\",\n \"XS_NORMALIZED_STRING\",\n \"XS_TOKEN\",\n \"XS_LANGUAGE\",\n \"XS_NMTOKEN\",\n \"XS_NAME\",\n \"XS_NCNAME\",\n \"XS_ID\",\n \"XS_IDREF\",\n \"XS_ENTITY\",\n \"XS_UNTYPED_ATOMIC\",\n \"XS_DATETIME\",\n \"XS_DATE\",\n \"XS_TIME\",\n \"XS_DURATION\",\n \"XS_DT_DURATION\",\n \"XS_YM_DURATION\",\n \"XS_FLOAT\",\n \"XS_DOUBLE\",\n \"XS_DECIMAL\",\n \"XS_INTEGER\",\n \"XS_NON_POSITIVE_INTEGER\",\n \"XS_NEGATIVE_INTEGER\",\n \"XS_LONG\",\n \"XS_INT\",\n \"XS_SHORT\",\n \"XS_BYTE\",\n \"XS_NON_NEGATIVE_INTEGER\",\n \"XS_UNSIGNED_LONG\",\n \"XS_UNSIGNED_INT\",\n \"XS_UNSIGNED_SHORT\",\n \"XS_UNSIGNED_BYTE\",\n \"XS_POSITIVE_INTEGER\",\n \"XS_GYEAR_MONTH\",\n \"XS_GYEAR\",\n \"XS_GMONTH_DAY\",\n \"XS_GDAY\",\n \"XS_GMONTH\",\n \"XS_BOOLEAN\",\n \"XS_BASE64BINARY\",\n \"XS_HEXBINARY\",\n \"XS_ANY_URI\",\n \"XS_QNAME\",\n \"XS_NOTATION\"\n};\n\nstd::ostream& XQType::serialize(std::ostream& os) const\n{\n return os << \"[XQType \" << KIND_STRINGS[type_kind()]\n << TypeOps::decode_quantifier(get_quantifier()) << \"]\";\n}\n\n\nstd::string XQType::toString() const\n{\n std::ostringstream os;\n serialize(os);\n return os.str();\n}\n\n\nstd::ostream& AtomicXQType::serialize(std::ostream& os) const\n{\n return os << \"[AtomicXQType \" << ATOMIC_TYPE_CODE_STRINGS[get_type_code()]\n << TypeOps::decode_quantifier (get_quantifier()) << \"]\";\n}\n\nstore::Item_t AtomicXQType::get_qname() const\n{\n return GENV_TYPESYSTEM.m_atomic_typecode_qname_map[m_type_code];\n}\n\nstore::Item_t AnyXQType::get_qname() const\n{\n return GENV_TYPESYSTEM.XS_ANY_TYPE_QNAME;\n}\n\nstore::Item_t AnySimpleXQType::get_qname() const\n{\n return GENV_TYPESYSTEM.XS_ANY_SIMPLE_TYPE_QNAME;\n}\n\nstore::Item_t UntypedXQType::get_qname() const\n{\n return GENV_TYPESYSTEM.XS_UNTYPED_QNAME;\n}\n\n#if 0\nstatic void foo()\n{\n std::cout << \"Hell\" << std::endl;\n}\n#endif\n\nNodeXQType::NodeXQType(\n const TypeManager* manager,\n rchandle nodetest,\n xqtref_t contentType,\n TypeConstants::quantifier_t quantifier,\n bool nillable,\n bool builtin)\n :\n XQType(manager, NODE_TYPE_KIND, quantifier, builtin),\n m_nodetest(nodetest),\n m_content_type(contentType),\n m_nillable(nillable)\n{\n \/\/foo();\n}\n\n\nNodeXQType::NodeXQType(\n const TypeManager* manager,\n store::StoreConsts::NodeKind nodekind,\n const store::Item* nodename,\n xqtref_t contentType,\n TypeConstants::quantifier_t quantifier,\n bool nillable,\n bool builtin)\n :\n XQType(manager, NODE_TYPE_KIND, quantifier, builtin),\n m_nodetest(new NodeTest(nodekind, nodename)),\n m_content_type(contentType),\n m_nillable(nillable)\n{\n}\n\n\nNodeXQType::NodeXQType(\n const NodeXQType& source,\n TypeConstants::quantifier_t quantifier)\n :\n XQType(source.m_manager, NODE_TYPE_KIND, quantifier, false),\n m_nodetest(source.m_nodetest),\n m_content_type(source.m_content_type),\n m_nillable(source.m_nillable)\n{\n}\n\n\nbool NodeXQType::is_untyped() const\n{\n return m_content_type == GENV_TYPESYSTEM.UNTYPED_TYPE;\n}\n\n\nstd::ostream& NodeXQType::serialize(std::ostream& os) const\n{\n rchandle node_test = get_nodetest ();\n store::StoreConsts::NodeKind node_kind = node_test->get_node_kind();\n xqtref_t content_type = get_content_type ();\n rchandle nametest = node_test->get_nametest();\n os << \"[NodeXQType \" << store::StoreConsts::toString (node_kind)\n << TypeOps::decode_quantifier (get_quantifier()) << \" \";\n if (nametest != NULL) {\n os << \"nametest=[uri: \" << nametest->get_uri () << \", local: \" << nametest->get_local () << \"]\";\n }\n if (content_type != NULL)\n {\n os << \" content=\";\n os << content_type->toString ();\n }\n return os << \"]\";\n}\n\n\nUserDefinedXQType::UserDefinedXQType(\n const TypeManager *manager,\n store::Item_t qname,\n xqtref_t baseType,\n TypeConstants::quantifier_t quantifier,\n content_kind_t contentKind)\n :\n XQType(manager, USER_DEFINED_KIND, quantifier, false),\n m_qname(qname),\n m_baseType(baseType),\n m_contentKind(contentKind),\n m_listItemType(NULL)\n{\n ZORBA_ASSERT(baseType!=NULL);\n\n switch (baseType.getp()->type_kind())\n {\n case USER_DEFINED_KIND:\n {\n const UserDefinedXQType& udBaseType = static_cast(*baseType);\n m_typeCategory = udBaseType.getTypeCategory();\n switch (m_typeCategory)\n {\n case ATOMIC_TYPE:\n case COMPLEX_TYPE:\n break;\n \n case LIST_TYPE:\n m_listItemType = udBaseType.getListItemType();\n break;\n \n case UNION_TYPE:\n m_unionItemTypes = udBaseType.getUnionItemTypes();\n break;\n \n default:\n ZORBA_ASSERT(false);\n }\n \n\n break;\n }\n case ATOMIC_TYPE_KIND:\n {\n m_typeCategory = ATOMIC_TYPE;\n break;\n }\n default:\n {\n m_typeCategory = COMPLEX_TYPE; \n } \n } \n}\n\n\n \/\/ Constructor for List types\nUserDefinedXQType::UserDefinedXQType(\n const TypeManager *manager,\n store::Item_t qname,\n xqtref_t baseType,\n TypeConstants::quantifier_t quantifier,\n const XQType* listItemType)\n :\n XQType(manager, USER_DEFINED_KIND, quantifier, false),\n m_qname(qname),\n m_baseType(baseType),\n m_typeCategory(LIST_TYPE),\n m_contentKind(SIMPLE_CONTENT_KIND),\n m_listItemType(listItemType)\n{\n ZORBA_ASSERT( listItemType );\n}\n\n\n \/\/ Constructor for Union types\nUserDefinedXQType::UserDefinedXQType(\n const TypeManager *manager,\n store::Item_t qname,\n xqtref_t baseType,\n TypeConstants::quantifier_t quantifier,\n std::vector unionItemTypes)\n : \n XQType(manager, USER_DEFINED_KIND, quantifier, false),\n m_qname(qname),\n m_baseType(baseType),\n m_typeCategory(UNION_TYPE),\n m_contentKind(SIMPLE_CONTENT_KIND),\n m_unionItemTypes(unionItemTypes),\n m_listItemType(NULL)\n{\n}\n\n\nbool UserDefinedXQType::isSuperTypeOf(const XQType& subType) const\n{\n const XQType* subtype = &subType;\n\n do\n {\n if (this == subtype)\n return true;\n \n if (subtype->type_kind() == XQType::USER_DEFINED_KIND)\n {\n const UserDefinedXQType* tmp = static_cast(subtype);\n subtype = tmp->getBaseType().getp();\n }\n else\n {\n return false;\n }\n }\n while(true);\n \n return false;\n}\n\n\nstd::ostream& UserDefinedXQType::serialize(std::ostream& os) const\n{\n std::string info = \"\";\n\n switch (m_typeCategory)\n {\n case ATOMIC_TYPE:\n info += \"isAtomic\";\n break;\n case COMPLEX_TYPE:\n info += \"isComplex\";\n break;\n case LIST_TYPE:\n info += \" isList itemType:\";\n info += m_listItemType->toString();\n break;\n case UNION_TYPE:\n info += \" isUnion \";\n info += m_unionItemTypes.size() + \":\";\n for ( unsigned int i=0; itoString();\n }\n break;\n default:\n ZORBA_ASSERT(false);\n }\n \n return os << \"[UserDefinedXQType \" << \" \"\n << TypeOps::decode_quantifier (get_quantifier())\n << m_qname->getLocalName()->str() << \"@\"\n << m_qname->getNamespace()->str() << \" \"\n << info\n << \" base:\"\n << ( m_baseType ? TypeOps::toString(*m_baseType) : \"NULL\" )\n << \" ]\";\n}\n\n} \/\/ namespace zorba\nfix in UserDefinedXQType::isSuperTypeOf()\/*\n * Copyright 2006-2008 The FLWOR Foundation.\n * \n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * \n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n#include \n#include \"system\/globalenv.h\"\n#include \"types\/typeconstants.h\"\n#include \"types\/typeimpl.h\"\n#include \"types\/typeops.h\"\n#include \"types\/root_typemanager.h\"\n#include \"zorbaerrors\/Assert.h\"\n\n\nnamespace zorba {\n\nconst char* XQType::KIND_STRINGS[XQType::MAX_TYPE_KIND] =\n{\n \"EMPTY_KIND\",\n \"ATOMIC_TYPE_KIND\",\n \"ITEM_KIND\",\n \"NODE_TYPE_KIND\",\n \"ANY_TYPE_KIND\",\n \"ANY_SIMPLE_TYPE_KIND\",\n \"UNTYPED_KIND\",\n \"NONE_KIND\"\n};\n\nconst char *AtomicXQType::ATOMIC_TYPE_CODE_STRINGS[TypeConstants::ATOMIC_TYPE_CODE_LIST_SIZE] =\n{\n \"XS_ANY_ATOMIC\",\n \"XS_STRING\",\n \"XS_NORMALIZED_STRING\",\n \"XS_TOKEN\",\n \"XS_LANGUAGE\",\n \"XS_NMTOKEN\",\n \"XS_NAME\",\n \"XS_NCNAME\",\n \"XS_ID\",\n \"XS_IDREF\",\n \"XS_ENTITY\",\n \"XS_UNTYPED_ATOMIC\",\n \"XS_DATETIME\",\n \"XS_DATE\",\n \"XS_TIME\",\n \"XS_DURATION\",\n \"XS_DT_DURATION\",\n \"XS_YM_DURATION\",\n \"XS_FLOAT\",\n \"XS_DOUBLE\",\n \"XS_DECIMAL\",\n \"XS_INTEGER\",\n \"XS_NON_POSITIVE_INTEGER\",\n \"XS_NEGATIVE_INTEGER\",\n \"XS_LONG\",\n \"XS_INT\",\n \"XS_SHORT\",\n \"XS_BYTE\",\n \"XS_NON_NEGATIVE_INTEGER\",\n \"XS_UNSIGNED_LONG\",\n \"XS_UNSIGNED_INT\",\n \"XS_UNSIGNED_SHORT\",\n \"XS_UNSIGNED_BYTE\",\n \"XS_POSITIVE_INTEGER\",\n \"XS_GYEAR_MONTH\",\n \"XS_GYEAR\",\n \"XS_GMONTH_DAY\",\n \"XS_GDAY\",\n \"XS_GMONTH\",\n \"XS_BOOLEAN\",\n \"XS_BASE64BINARY\",\n \"XS_HEXBINARY\",\n \"XS_ANY_URI\",\n \"XS_QNAME\",\n \"XS_NOTATION\"\n};\n\nstd::ostream& XQType::serialize(std::ostream& os) const\n{\n return os << \"[XQType \" << KIND_STRINGS[type_kind()]\n << TypeOps::decode_quantifier(get_quantifier()) << \"]\";\n}\n\n\nstd::string XQType::toString() const\n{\n std::ostringstream os;\n serialize(os);\n return os.str();\n}\n\n\nstd::ostream& AtomicXQType::serialize(std::ostream& os) const\n{\n return os << \"[AtomicXQType \" << ATOMIC_TYPE_CODE_STRINGS[get_type_code()]\n << TypeOps::decode_quantifier (get_quantifier()) << \"]\";\n}\n\nstore::Item_t AtomicXQType::get_qname() const\n{\n return GENV_TYPESYSTEM.m_atomic_typecode_qname_map[m_type_code];\n}\n\nstore::Item_t AnyXQType::get_qname() const\n{\n return GENV_TYPESYSTEM.XS_ANY_TYPE_QNAME;\n}\n\nstore::Item_t AnySimpleXQType::get_qname() const\n{\n return GENV_TYPESYSTEM.XS_ANY_SIMPLE_TYPE_QNAME;\n}\n\nstore::Item_t UntypedXQType::get_qname() const\n{\n return GENV_TYPESYSTEM.XS_UNTYPED_QNAME;\n}\n\n#if 0\nstatic void foo()\n{\n std::cout << \"Hell\" << std::endl;\n}\n#endif\n\nNodeXQType::NodeXQType(\n const TypeManager* manager,\n rchandle nodetest,\n xqtref_t contentType,\n TypeConstants::quantifier_t quantifier,\n bool nillable,\n bool builtin)\n :\n XQType(manager, NODE_TYPE_KIND, quantifier, builtin),\n m_nodetest(nodetest),\n m_content_type(contentType),\n m_nillable(nillable)\n{\n \/\/foo();\n}\n\n\nNodeXQType::NodeXQType(\n const TypeManager* manager,\n store::StoreConsts::NodeKind nodekind,\n const store::Item* nodename,\n xqtref_t contentType,\n TypeConstants::quantifier_t quantifier,\n bool nillable,\n bool builtin)\n :\n XQType(manager, NODE_TYPE_KIND, quantifier, builtin),\n m_nodetest(new NodeTest(nodekind, nodename)),\n m_content_type(contentType),\n m_nillable(nillable)\n{\n}\n\n\nNodeXQType::NodeXQType(\n const NodeXQType& source,\n TypeConstants::quantifier_t quantifier)\n :\n XQType(source.m_manager, NODE_TYPE_KIND, quantifier, false),\n m_nodetest(source.m_nodetest),\n m_content_type(source.m_content_type),\n m_nillable(source.m_nillable)\n{\n}\n\n\nbool NodeXQType::is_untyped() const\n{\n return m_content_type == GENV_TYPESYSTEM.UNTYPED_TYPE;\n}\n\n\nstd::ostream& NodeXQType::serialize(std::ostream& os) const\n{\n rchandle node_test = get_nodetest ();\n store::StoreConsts::NodeKind node_kind = node_test->get_node_kind();\n xqtref_t content_type = get_content_type ();\n rchandle nametest = node_test->get_nametest();\n os << \"[NodeXQType \" << store::StoreConsts::toString (node_kind)\n << TypeOps::decode_quantifier (get_quantifier()) << \" \";\n if (nametest != NULL) {\n os << \"nametest=[uri: \" << nametest->get_uri () << \", local: \" << nametest->get_local () << \"]\";\n }\n if (content_type != NULL)\n {\n os << \" content=\";\n os << content_type->toString ();\n }\n return os << \"]\";\n}\n\n\nUserDefinedXQType::UserDefinedXQType(\n const TypeManager *manager,\n store::Item_t qname,\n xqtref_t baseType,\n TypeConstants::quantifier_t quantifier,\n content_kind_t contentKind)\n :\n XQType(manager, USER_DEFINED_KIND, quantifier, false),\n m_qname(qname),\n m_baseType(baseType),\n m_contentKind(contentKind),\n m_listItemType(NULL)\n{\n ZORBA_ASSERT(baseType!=NULL);\n\n switch (baseType.getp()->type_kind())\n {\n case USER_DEFINED_KIND:\n {\n const UserDefinedXQType& udBaseType = static_cast(*baseType);\n m_typeCategory = udBaseType.getTypeCategory();\n switch (m_typeCategory)\n {\n case ATOMIC_TYPE:\n case COMPLEX_TYPE:\n break;\n \n case LIST_TYPE:\n m_listItemType = udBaseType.getListItemType();\n break;\n \n case UNION_TYPE:\n m_unionItemTypes = udBaseType.getUnionItemTypes();\n break;\n \n default:\n ZORBA_ASSERT(false);\n }\n \n\n break;\n }\n case ATOMIC_TYPE_KIND:\n {\n m_typeCategory = ATOMIC_TYPE;\n break;\n }\n default:\n {\n m_typeCategory = COMPLEX_TYPE; \n } \n } \n}\n\n\n \/\/ Constructor for List types\nUserDefinedXQType::UserDefinedXQType(\n const TypeManager *manager,\n store::Item_t qname,\n xqtref_t baseType,\n TypeConstants::quantifier_t quantifier,\n const XQType* listItemType)\n :\n XQType(manager, USER_DEFINED_KIND, quantifier, false),\n m_qname(qname),\n m_baseType(baseType),\n m_typeCategory(LIST_TYPE),\n m_contentKind(SIMPLE_CONTENT_KIND),\n m_listItemType(listItemType)\n{\n ZORBA_ASSERT( listItemType );\n}\n\n\n \/\/ Constructor for Union types\nUserDefinedXQType::UserDefinedXQType(\n const TypeManager *manager,\n store::Item_t qname,\n xqtref_t baseType,\n TypeConstants::quantifier_t quantifier,\n std::vector unionItemTypes)\n : \n XQType(manager, USER_DEFINED_KIND, quantifier, false),\n m_qname(qname),\n m_baseType(baseType),\n m_typeCategory(UNION_TYPE),\n m_contentKind(SIMPLE_CONTENT_KIND),\n m_unionItemTypes(unionItemTypes),\n m_listItemType(NULL)\n{\n}\n\n\nbool UserDefinedXQType::isSuperTypeOf(const XQType& subType) const\n{\n if (subType.type_kind() != XQType::USER_DEFINED_KIND)\n return false;\n\n const UserDefinedXQType* subtype = static_cast(&subType);\n\n do\n {\n if (TypeOps::is_equal(*this, *subtype))\n return true;\n \n if (subtype->type_kind() == XQType::USER_DEFINED_KIND)\n {\n subtype = static_cast(subtype->getBaseType().getp());\n }\n else\n {\n return false;\n }\n }\n while(true);\n \n return false;\n}\n\n\nstd::ostream& UserDefinedXQType::serialize(std::ostream& os) const\n{\n std::string info = \"\";\n\n switch (m_typeCategory)\n {\n case ATOMIC_TYPE:\n info += \"isAtomic\";\n break;\n case COMPLEX_TYPE:\n info += \"isComplex\";\n break;\n case LIST_TYPE:\n info += \" isList itemType:\";\n info += m_listItemType->toString();\n break;\n case UNION_TYPE:\n info += \" isUnion \";\n info += m_unionItemTypes.size() + \":\";\n for ( unsigned int i=0; itoString();\n }\n break;\n default:\n ZORBA_ASSERT(false);\n }\n \n return os << \"[UserDefinedXQType \" << \" \"\n << TypeOps::decode_quantifier (get_quantifier())\n << m_qname->getLocalName()->str() << \"@\"\n << m_qname->getNamespace()->str() << \" \"\n << info\n << \" base:\"\n << ( m_baseType ? TypeOps::toString(*m_baseType) : \"NULL\" )\n << \" ]\";\n}\n\n} \/\/ namespace zorba\n<|endoftext|>"} {"text":"\/\/ Copyright 2013 Tanel Lebedev\n\n#include \".\/main.h\"\n\n#include \n\n#include \"Poco\/Message.h\"\n#include \"Poco\/Util\/Application.h\"\n\n#define ERRLEN 1024\n\nnamespace command_line_client {\n\nbool syncing = false;\n\nstd::string model_change_to_string(\n KopsikModelChange &change) {\n std::stringstream ss;\n ss << \"model_type=\" << change.ModelType\n << \", change_type=\" << change.ChangeType\n << \", model_id=\" << change.ModelID\n << \", GUID=\" << change.GUID;\n return ss.str();\n}\n\nvoid main_change_callback(\n kopsik_api_result result,\n const char *errmsg,\n KopsikModelChange *change) {\n if (KOPSIK_API_SUCCESS != result) {\n std::cerr << \"main_change_callback errmsg=\"\n << std::string(errmsg)\n << std::endl;\n return;\n }\n std::cout << \"main_change_callback change=\"\n << model_change_to_string(*change)\n << std::endl;\n}\n\nvoid main_on_error_callback(\n const char *errmsg) {\n std::cerr << \"main_on_error_callback errmsg=\"\n << std::string(errmsg)\n << std::endl;\n}\n\nvoid main_check_updates_callback(\n const int is_update_available,\n const char *url,\n const char *version) {\n if (KOPSIK_API_SUCCESS != result) {\n std::cerr << \"main_check_updates_callback errmsg=\"\n << std::string(errmsg)\n << std::endl;\n return;\n }\n std::cout << \"main_check_updates_callback is_update_available=\"\n << is_update_available\n << \" url=\" << std::string(url)\n << \" version=\" << std::string(version)\n << std::endl;\n}\n\nvoid main_online_callback() {\n std::cout << \"main_online_callback\" << std::endl;\n}\n\nvoid on_sync_result(\n kopsik_api_result result,\n const char *errmsg) {\n if (KOPSIK_API_SUCCESS != result) {\n std::cerr << \"Error \" << std::string(errmsg) << std::endl;\n syncing = false;\n return;\n }\n std::cout << \"Success\" << std::endl;\n syncing = false;\n}\n\nMain::Main()\n : ctx_(0) {\n kopsik_set_log_path(\"kopsik.log\");\n ctx_ = kopsik_context_init(\n \"cmdline\",\n \"0.0.1\",\n main_change_callback,\n main_on_error_callback,\n main_check_updates_callback,\n main_online_callback);\n poco_assert(ctx_);\n}\n\nMain::~Main() {\n kopsik_context_clear(ctx_);\n}\n\nvoid Main::exception(const Poco::Exception& exc) {\n std::cerr << exc.displayText() << std::endl;\n}\n\nvoid Main::exception(const std::exception& exc) {\n std::cerr << exc.what() << std::endl;\n}\n\nvoid Main::exception() {\n std::cerr << \"unknown exception\" << std::endl;\n}\n\nvoid Main::initialize(Poco::Util::Application &self) { \/\/ NOLINT\n Poco::Util::Application::initialize(self);\n};\n\nvoid Main::usage() const {\n std::cout << \"Recognized commands are: \"\n \"sync, start, stop, status, pushable, list, continue, listen\"\n << std::endl;\n}\n\nvoid Main::defineOptions(Poco::Util::OptionSet& options) { \/\/ NOLINT\n Poco::Util::Application::defineOptions(options);\n options.addOption(Poco::Util::Option(\n \"verbose\", \"v\", \"verbose logging, to the console\"));\n}\n\nint Main::sync() {\n syncing = true;\n kopsik_sync(ctx_);\n while (syncing) {\n Poco::Thread::sleep(1000);\n }\n return Poco::Util::Application::EXIT_OK;\n}\n\nint Main::continueTimeEntry() {\n char errmsg[ERRLEN];\n KopsikTimeEntryViewItem *first = 0;\n if (KOPSIK_API_SUCCESS != kopsik_time_entry_view_items(\n ctx_, errmsg, ERRLEN, &first)) {\n std::cerr << std::string(errmsg) << std::endl;\n kopsik_time_entry_view_item_clear(first);\n return Poco::Util::Application::EXIT_SOFTWARE;\n }\n\n if (!first) {\n std::cout << \"No time entry found to continue.\" << std::endl;\n kopsik_time_entry_view_item_clear(first);\n return Poco::Util::Application::EXIT_OK;\n }\n\n KopsikTimeEntryViewItem *te = kopsik_time_entry_view_item_init();\n if (KOPSIK_API_SUCCESS != kopsik_continue(\n ctx_, errmsg, ERRLEN, first->GUID, te)) {\n std::cerr << std::string(errmsg) << std::endl;\n kopsik_time_entry_view_item_clear(first);\n kopsik_time_entry_view_item_clear(te);\n return Poco::Util::Application::EXIT_SOFTWARE;\n }\n\n kopsik_time_entry_view_item_clear(first);\n kopsik_time_entry_view_item_clear(te);\n return Poco::Util::Application::EXIT_OK;\n}\n\nint Main::status() {\n KopsikTimeEntryViewItem *te = kopsik_time_entry_view_item_init();\n int found(0);\n char errmsg[ERRLEN];\n if (KOPSIK_API_SUCCESS != kopsik_running_time_entry_view_item(\n ctx_, errmsg, ERRLEN, te, &found)) {\n std::cerr << std::string(errmsg) << std::endl;\n kopsik_time_entry_view_item_clear(te);\n return Poco::Util::Application::EXIT_SOFTWARE;\n }\n if (found) {\n std::cout << \"Tracking: \" << te->Description << std::endl;\n } else {\n std::cout << \"Not tracking.\" << std::endl;\n }\n kopsik_time_entry_view_item_clear(te);\n return Poco::Util::Application::EXIT_OK;\n}\n\nint Main::main(const std::vector& args) {\n if (args.empty()) {\n usage();\n return Poco::Util::Application::EXIT_USAGE;\n }\n\n char* apitoken = getenv(\"TOGGL_API_TOKEN\");\n if (!apitoken) {\n std::cerr << \"Please set TOGGL_API_TOKEN in environment\"\n << std::endl;\n return Poco::Util::Application::EXIT_USAGE;\n }\n\n char errmsg[ERRLEN];\n if (KOPSIK_API_SUCCESS != kopsik_set_db_path(\n ctx_, errmsg, ERRLEN, \"kopsik.db\")) {\n std::cerr << errmsg << std::endl;\n return Poco::Util::Application::EXIT_SOFTWARE;\n }\n\n Poco::ErrorHandler::set(this);\n\n \/\/ Start session in lib\n if (KOPSIK_API_SUCCESS != kopsik_set_api_token(\n ctx_, errmsg, ERRLEN, apitoken)) {\n std::cerr << errmsg << std::endl;\n return Poco::Util::Application::EXIT_SOFTWARE;\n }\n\n \/\/ Load user that is referenced by the session\n KopsikUser *user = kopsik_user_init();\n if (KOPSIK_API_SUCCESS != kopsik_current_user(\n ctx_, errmsg, ERRLEN, user)) {\n std::cerr << std::string(errmsg) << std::endl;\n return Poco::Util::Application::EXIT_SOFTWARE;\n }\n kopsik_user_clear(user);\n\n \/\/ Handle commands\n if (\"sync\" == args[0]) {\n return sync();\n }\n if (\"status\" == args[0]) {\n return status();\n }\n if (\"pushable\" == args[0]) {\n return showPushableData();\n }\n if (\"start\" == args[0]) {\n return startTimeEntry();\n }\n if (\"stop\" == args[0]) {\n return stopTimeEntry();\n }\n if (\"list\" == args[0]) {\n return listTimeEntries();\n }\n if (\"listen\" == args[0]) {\n return listenToWebSocket();\n }\n if (\"continue\" == args[0]) {\n return continueTimeEntry();\n }\n\n usage();\n return Poco::Util::Application::EXIT_USAGE;\n}\n\nint Main::showPushableData() {\n KopsikPushableModelStats stats;\n char errmsg[ERRLEN];\n if (KOPSIK_API_SUCCESS != kopsik_pushable_models(\n ctx_, errmsg, ERRLEN, &stats)) {\n std::cerr << std::string(errmsg) << std::endl;\n return Poco::Util::Application::EXIT_SOFTWARE;\n }\n std::cout << stats.TimeEntries\n << \" pushable time entries.\"\n << std::endl;\n return Poco::Util::Application::EXIT_OK;\n}\n\nstd::string Main::timeEntryToString(\n KopsikTimeEntryViewItem *item) {\n std::stringstream ss;\n ss << item->Description;\n if (item->ProjectAndTaskLabel) {\n ss << \" [\" << item->ProjectAndTaskLabel << \"]\";\n }\n if (item->Duration) {\n ss << \" (\" << item->Duration << \")\";\n }\n return ss.str();\n}\n\nint Main::listenToWebSocket() {\n std::cout << \"Listening to websocket.. \" << std::endl;\n kopsik_websocket_switch(ctx_, 1);\n while (true) {\n Poco::Thread::sleep(1000);\n }\n kopsik_websocket_switch(ctx_, 0);\n return Poco::Util::Application::EXIT_OK;\n}\n\nint Main::listTimeEntries() {\n KopsikTimeEntryViewItem *first = 0;\n char errmsg[ERRLEN];\n if (KOPSIK_API_SUCCESS != kopsik_time_entry_view_items(\n ctx_, errmsg, ERRLEN, &first)) {\n std::cerr << std::string(errmsg) << std::endl;\n kopsik_time_entry_view_item_clear(first);\n return Poco::Util::Application::EXIT_SOFTWARE;\n }\n int n = 0;\n while (true) {\n std::cout << timeEntryToString(first) << std::endl;\n n++;\n if (!first->Next) {\n break;\n }\n first = reinterpret_cast(first->Next);\n }\n std::cout << \"Got \" << n << \" time entry view items.\" << std::endl;\n kopsik_time_entry_view_item_clear(first);\n return Poco::Util::Application::EXIT_OK;\n}\n\nint Main::startTimeEntry() {\n KopsikTimeEntryViewItem *te = kopsik_time_entry_view_item_init();\n char errmsg[ERRLEN];\n if (KOPSIK_API_SUCCESS != kopsik_start(\n ctx_, errmsg, ERRLEN, \"New time entry\", \"\", 0, 0, te)) {\n std::cerr << errmsg << std::endl;\n kopsik_time_entry_view_item_clear(te);\n return Poco::Util::Application::EXIT_SOFTWARE;\n }\n kopsik_time_entry_view_item_clear(te);\n return Poco::Util::Application::EXIT_OK;\n}\n\nint Main::stopTimeEntry() {\n KopsikTimeEntryViewItem *te = kopsik_time_entry_view_item_init();\n int was_found(0);\n char errmsg[ERRLEN];\n if (KOPSIK_API_SUCCESS != kopsik_stop(\n ctx_, errmsg, ERRLEN, te, &was_found)) {\n std::cerr << errmsg << std::endl;\n kopsik_time_entry_view_item_clear(te);\n return Poco::Util::Application::EXIT_SOFTWARE;\n }\n if (!was_found) {\n std::cout << \"No time entry found to stop.\" << std::endl;\n }\n kopsik_time_entry_view_item_clear(te);\n return Poco::Util::Application::EXIT_OK;\n}\n\n} \/\/ namespace command_line_client\nFix command line app build\/\/ Copyright 2013 Tanel Lebedev\n\n#include \".\/main.h\"\n\n#include \n\n#include \"Poco\/Message.h\"\n#include \"Poco\/Util\/Application.h\"\n\n#define ERRLEN 1024\n\nnamespace command_line_client {\n\nbool syncing = false;\n\nstd::string model_change_to_string(\n KopsikModelChange &change) {\n std::stringstream ss;\n ss << \"model_type=\" << change.ModelType\n << \", change_type=\" << change.ChangeType\n << \", model_id=\" << change.ModelID\n << \", GUID=\" << change.GUID;\n return ss.str();\n}\n\nvoid main_change_callback(\n kopsik_api_result result,\n const char *errmsg,\n KopsikModelChange *change) {\n if (KOPSIK_API_SUCCESS != result) {\n std::cerr << \"main_change_callback errmsg=\"\n << std::string(errmsg)\n << std::endl;\n return;\n }\n std::cout << \"main_change_callback change=\"\n << model_change_to_string(*change)\n << std::endl;\n}\n\nvoid main_on_error_callback(\n const char *errmsg) {\n std::cerr << \"main_on_error_callback errmsg=\"\n << std::string(errmsg)\n << std::endl;\n}\n\nvoid main_check_updates_callback(\n const int is_update_available,\n const char *url,\n const char *version) {\n std::cout << \"main_check_updates_callback is_update_available=\"\n << is_update_available\n << \" url=\" << std::string(url)\n << \" version=\" << std::string(version)\n << std::endl;\n}\n\nvoid main_online_callback() {\n std::cout << \"main_online_callback\" << std::endl;\n}\n\nvoid on_sync_result(\n kopsik_api_result result,\n const char *errmsg) {\n if (KOPSIK_API_SUCCESS != result) {\n std::cerr << \"Error \" << std::string(errmsg) << std::endl;\n syncing = false;\n return;\n }\n std::cout << \"Success\" << std::endl;\n syncing = false;\n}\n\nMain::Main()\n : ctx_(0) {\n kopsik_set_log_path(\"kopsik.log\");\n ctx_ = kopsik_context_init(\n \"cmdline\",\n \"0.0.1\",\n main_change_callback,\n main_on_error_callback,\n main_check_updates_callback,\n main_online_callback);\n poco_assert(ctx_);\n}\n\nMain::~Main() {\n kopsik_context_clear(ctx_);\n}\n\nvoid Main::exception(const Poco::Exception& exc) {\n std::cerr << exc.displayText() << std::endl;\n}\n\nvoid Main::exception(const std::exception& exc) {\n std::cerr << exc.what() << std::endl;\n}\n\nvoid Main::exception() {\n std::cerr << \"unknown exception\" << std::endl;\n}\n\nvoid Main::initialize(Poco::Util::Application &self) { \/\/ NOLINT\n Poco::Util::Application::initialize(self);\n};\n\nvoid Main::usage() const {\n std::cout << \"Recognized commands are: \"\n \"sync, start, stop, status, pushable, list, continue, listen\"\n << std::endl;\n}\n\nvoid Main::defineOptions(Poco::Util::OptionSet& options) { \/\/ NOLINT\n Poco::Util::Application::defineOptions(options);\n options.addOption(Poco::Util::Option(\n \"verbose\", \"v\", \"verbose logging, to the console\"));\n}\n\nint Main::sync() {\n syncing = true;\n kopsik_sync(ctx_);\n while (syncing) {\n Poco::Thread::sleep(1000);\n }\n return Poco::Util::Application::EXIT_OK;\n}\n\nint Main::continueTimeEntry() {\n char errmsg[ERRLEN];\n KopsikTimeEntryViewItem *first = 0;\n if (KOPSIK_API_SUCCESS != kopsik_time_entry_view_items(\n ctx_, errmsg, ERRLEN, &first)) {\n std::cerr << std::string(errmsg) << std::endl;\n kopsik_time_entry_view_item_clear(first);\n return Poco::Util::Application::EXIT_SOFTWARE;\n }\n\n if (!first) {\n std::cout << \"No time entry found to continue.\" << std::endl;\n kopsik_time_entry_view_item_clear(first);\n return Poco::Util::Application::EXIT_OK;\n }\n\n KopsikTimeEntryViewItem *te = kopsik_time_entry_view_item_init();\n if (KOPSIK_API_SUCCESS != kopsik_continue(\n ctx_, errmsg, ERRLEN, first->GUID, te)) {\n std::cerr << std::string(errmsg) << std::endl;\n kopsik_time_entry_view_item_clear(first);\n kopsik_time_entry_view_item_clear(te);\n return Poco::Util::Application::EXIT_SOFTWARE;\n }\n\n kopsik_time_entry_view_item_clear(first);\n kopsik_time_entry_view_item_clear(te);\n return Poco::Util::Application::EXIT_OK;\n}\n\nint Main::status() {\n KopsikTimeEntryViewItem *te = kopsik_time_entry_view_item_init();\n int found(0);\n char errmsg[ERRLEN];\n if (KOPSIK_API_SUCCESS != kopsik_running_time_entry_view_item(\n ctx_, errmsg, ERRLEN, te, &found)) {\n std::cerr << std::string(errmsg) << std::endl;\n kopsik_time_entry_view_item_clear(te);\n return Poco::Util::Application::EXIT_SOFTWARE;\n }\n if (found) {\n std::cout << \"Tracking: \" << te->Description << std::endl;\n } else {\n std::cout << \"Not tracking.\" << std::endl;\n }\n kopsik_time_entry_view_item_clear(te);\n return Poco::Util::Application::EXIT_OK;\n}\n\nint Main::main(const std::vector& args) {\n if (args.empty()) {\n usage();\n return Poco::Util::Application::EXIT_USAGE;\n }\n\n char* apitoken = getenv(\"TOGGL_API_TOKEN\");\n if (!apitoken) {\n std::cerr << \"Please set TOGGL_API_TOKEN in environment\"\n << std::endl;\n return Poco::Util::Application::EXIT_USAGE;\n }\n\n char errmsg[ERRLEN];\n if (KOPSIK_API_SUCCESS != kopsik_set_db_path(\n ctx_, errmsg, ERRLEN, \"kopsik.db\")) {\n std::cerr << errmsg << std::endl;\n return Poco::Util::Application::EXIT_SOFTWARE;\n }\n\n Poco::ErrorHandler::set(this);\n\n \/\/ Start session in lib\n if (KOPSIK_API_SUCCESS != kopsik_set_api_token(\n ctx_, errmsg, ERRLEN, apitoken)) {\n std::cerr << errmsg << std::endl;\n return Poco::Util::Application::EXIT_SOFTWARE;\n }\n\n \/\/ Load user that is referenced by the session\n KopsikUser *user = kopsik_user_init();\n if (KOPSIK_API_SUCCESS != kopsik_current_user(\n ctx_, errmsg, ERRLEN, user)) {\n std::cerr << std::string(errmsg) << std::endl;\n return Poco::Util::Application::EXIT_SOFTWARE;\n }\n kopsik_user_clear(user);\n\n \/\/ Handle commands\n if (\"sync\" == args[0]) {\n return sync();\n }\n if (\"status\" == args[0]) {\n return status();\n }\n if (\"pushable\" == args[0]) {\n return showPushableData();\n }\n if (\"start\" == args[0]) {\n return startTimeEntry();\n }\n if (\"stop\" == args[0]) {\n return stopTimeEntry();\n }\n if (\"list\" == args[0]) {\n return listTimeEntries();\n }\n if (\"listen\" == args[0]) {\n return listenToWebSocket();\n }\n if (\"continue\" == args[0]) {\n return continueTimeEntry();\n }\n\n usage();\n return Poco::Util::Application::EXIT_USAGE;\n}\n\nint Main::showPushableData() {\n KopsikPushableModelStats stats;\n char errmsg[ERRLEN];\n if (KOPSIK_API_SUCCESS != kopsik_pushable_models(\n ctx_, errmsg, ERRLEN, &stats)) {\n std::cerr << std::string(errmsg) << std::endl;\n return Poco::Util::Application::EXIT_SOFTWARE;\n }\n std::cout << stats.TimeEntries\n << \" pushable time entries.\"\n << std::endl;\n return Poco::Util::Application::EXIT_OK;\n}\n\nstd::string Main::timeEntryToString(\n KopsikTimeEntryViewItem *item) {\n std::stringstream ss;\n ss << item->Description;\n if (item->ProjectAndTaskLabel) {\n ss << \" [\" << item->ProjectAndTaskLabel << \"]\";\n }\n if (item->Duration) {\n ss << \" (\" << item->Duration << \")\";\n }\n return ss.str();\n}\n\nint Main::listenToWebSocket() {\n std::cout << \"Listening to websocket.. \" << std::endl;\n kopsik_websocket_switch(ctx_, 1);\n while (true) {\n Poco::Thread::sleep(1000);\n }\n kopsik_websocket_switch(ctx_, 0);\n return Poco::Util::Application::EXIT_OK;\n}\n\nint Main::listTimeEntries() {\n KopsikTimeEntryViewItem *first = 0;\n char errmsg[ERRLEN];\n if (KOPSIK_API_SUCCESS != kopsik_time_entry_view_items(\n ctx_, errmsg, ERRLEN, &first)) {\n std::cerr << std::string(errmsg) << std::endl;\n kopsik_time_entry_view_item_clear(first);\n return Poco::Util::Application::EXIT_SOFTWARE;\n }\n int n = 0;\n while (true) {\n std::cout << timeEntryToString(first) << std::endl;\n n++;\n if (!first->Next) {\n break;\n }\n first = reinterpret_cast(first->Next);\n }\n std::cout << \"Got \" << n << \" time entry view items.\" << std::endl;\n kopsik_time_entry_view_item_clear(first);\n return Poco::Util::Application::EXIT_OK;\n}\n\nint Main::startTimeEntry() {\n KopsikTimeEntryViewItem *te = kopsik_time_entry_view_item_init();\n char errmsg[ERRLEN];\n if (KOPSIK_API_SUCCESS != kopsik_start(\n ctx_, errmsg, ERRLEN, \"New time entry\", \"\", 0, 0, te)) {\n std::cerr << errmsg << std::endl;\n kopsik_time_entry_view_item_clear(te);\n return Poco::Util::Application::EXIT_SOFTWARE;\n }\n kopsik_time_entry_view_item_clear(te);\n return Poco::Util::Application::EXIT_OK;\n}\n\nint Main::stopTimeEntry() {\n KopsikTimeEntryViewItem *te = kopsik_time_entry_view_item_init();\n int was_found(0);\n char errmsg[ERRLEN];\n if (KOPSIK_API_SUCCESS != kopsik_stop(\n ctx_, errmsg, ERRLEN, te, &was_found)) {\n std::cerr << errmsg << std::endl;\n kopsik_time_entry_view_item_clear(te);\n return Poco::Util::Application::EXIT_SOFTWARE;\n }\n if (!was_found) {\n std::cout << \"No time entry found to stop.\" << std::endl;\n }\n kopsik_time_entry_view_item_clear(te);\n return Poco::Util::Application::EXIT_OK;\n}\n\n} \/\/ namespace command_line_client\n<|endoftext|>"} {"text":"\n#include \"rpi_gpio.hpp\"\n#include \n#include <3rdparty\/bcm2835.h>\n\nusing namespace std;\n\nUSE_COMPONENT_INTERFACE(rpi_gpio)\n\nrpi_gpio::rpi_gpio()\n:cossb::interface::icomponent(COMPONENT(rpi_gpio)){\n\t\/\/ TODO Auto-generated constructor stub\n\n}\n\nrpi_gpio::~rpi_gpio() {\n\n}\n\nbool rpi_gpio::setup()\n{\n\tif(!bcm2835_init())\n\t\treturn false;\n\n\t\/\/set output port\n\tfor(auto outport:get_profile()->gets(profile::section::property, \"output\")){\n\t\tint port = outport.asInt(-1);\n\t\t_portmap[port] = true;\n\t\tbcm2835_gpio_fsel(port, BCM2835_GPIO_FSEL_OUTP);\n\t}\n\n\t\/\/set input port\n\tfor(auto inport:get_profile()->gets(profile::section::property, \"input\")){\n\t\tint port = inport.asInt(-1);\n\t\t_portmap[port] = false;\n\t\tbcm2835_gpio_fsel(port, BCM2835_GPIO_FSEL_INPT);\n\t\tbcm2835_gpio_set_pud(port, BCM2835_GPIO_PUD_UP);\n\t}\n\n\n\treturn true;\n}\n\nbool rpi_gpio::run()\n{\n\tmap port_read;\n\tstring read=\"\";\n\tfor(auto const& port:_portmap){\n\t\tif(!port.second){\n\t\t\tport_read[port.first] = bcm2835_gpio_lev(port.first);\n\t\t\tread += fmt::format(\"{}:0x{0:x}\\t\",port.first, port_read[port.first]);\n\t\t}\n\t}\n\n\tif(!port_read.empty()){\n\t\tcossb::message msg(this, cossb::base::msg_type::DATA);\n\t\tmsg.pack(port_read);\n\t\tcossb_broker->publish(\"rpi_gpio_read\", msg);\n\t\tcossb_log->log(log::loglevel::INFO, fmt::format(\"Read GPIO: {}\",read));\n\t}\n\n\n\treturn true;\n}\n\nbool rpi_gpio::stop()\n{\n\tif(!bcm2835_close())\n\t\treturn false;\n\n\treturn true;\n}\n\nvoid rpi_gpio::subscribe(cossb::message* const msg)\n{\n\tswitch(msg->get_frame()->type) {\n\t\tcase cossb::base::msg_type::REQUEST: break;\n\t\tcase cossb::base::msg_type::DATA: {\n\n\t\t\t\/\/subscribe emotion data\n\t\t\ttry {\n\t\t\t\tmap data = boost::any_cast>(*msg); \/\/{key, value} pair\n\n\t\t\t\t\/\/1. extract keys\n\t\t\t\tvector keys;\n\t\t\t\tfor(auto const& port: data)\n\t\t\t\t\tkeys.push_back(port.first);\n\n\t\t\t\t\/\/2. compare port set, then write data if it is outport\n\t\t\t\tfor(auto const& key:keys){\n\t\t\t\t\tif(_portmap.find(key)!=_portmap.end()){\n\t\t\t\t\t\tif(_portmap[key]){ \/\/output port\n\t\t\t\t\t\t\tbcm2835_gpio_write(key, data[key]); \/\/write data\n\t\t\t\t\t\t\tcossb_log->log(log::loglevel::INFO, fmt::format(\"Write GPIO({}) : 0x{0:x}\", key, data[key]));\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tcatch(const boost::bad_any_cast&){\n\t\t\t\tcossb_log->log(log::loglevel::ERROR, \"Invalid type casting, should be map type.\");\n\t\t\t}\n\t\t} break;\n\t\tcase cossb::base::msg_type::RESPONSE: break;\n\t\tcase cossb::base::msg_type::EVENT: break;\n\t\t}\n}\n\n\n- update\n#include \"rpi_gpio.hpp\"\n#include \n#include <3rdparty\/bcm2835.h>\n\nusing namespace std;\n\nUSE_COMPONENT_INTERFACE(rpi_gpio)\n\nrpi_gpio::rpi_gpio()\n:cossb::interface::icomponent(COMPONENT(rpi_gpio)){\n\t\/\/ TODO Auto-generated constructor stub\n\n}\n\nrpi_gpio::~rpi_gpio() {\n\n}\n\nbool rpi_gpio::setup()\n{\n\tif(!bcm2835_init())\n\t\treturn false;\n\n\t\/\/set output port\n\tfor(auto outport:get_profile()->gets(profile::section::property, \"output\")){\n\t\tint port = outport.asInt(-1);\n\t\t_portmap[port] = true;\n\t\tbcm2835_gpio_fsel(port, BCM2835_GPIO_FSEL_OUTP);\n\t}\n\n\t\/\/set input port\n\tfor(auto inport:get_profile()->gets(profile::section::property, \"input\")){\n\t\tint port = inport.asInt(-1);\n\t\t_portmap[port] = false;\n\t\tbcm2835_gpio_fsel(port, BCM2835_GPIO_FSEL_INPT);\n\t\tbcm2835_gpio_set_pud(port, BCM2835_GPIO_PUD_UP);\n\t}\n\n\n\treturn true;\n}\n\nbool rpi_gpio::run()\n{\n\tmap port_read;\n\tfor(auto const& port:_portmap){\n\t\tif(!port.second){\n\t\t\tport_read[port.first] = bcm2835_gpio_lev(port.first);\n\t\t\tcossb_log->log(log::loglevel::INFO, fmt::format(\"Read GPIO({}):0x{0:x}\",port.first, port_read[port.first]));\n\t\t}\n\t}\n\n\tif(!port_read.empty()){\n\t\tcossb::message msg(this, cossb::base::msg_type::DATA);\n\t\tmsg.pack(port_read);\n\t\tcossb_broker->publish(\"rpi_gpio_read\", msg);\n\t}\n\n\n\treturn true;\n}\n\nbool rpi_gpio::stop()\n{\n\tif(!bcm2835_close())\n\t\treturn false;\n\n\treturn true;\n}\n\nvoid rpi_gpio::subscribe(cossb::message* const msg)\n{\n\tswitch(msg->get_frame()->type) {\n\t\tcase cossb::base::msg_type::REQUEST: break;\n\t\tcase cossb::base::msg_type::DATA: {\n\n\t\t\t\/\/subscribe emotion data\n\t\t\ttry {\n\t\t\t\tmap data = boost::any_cast>(*msg); \/\/{key, value} pair\n\n\t\t\t\t\/\/1. extract keys\n\t\t\t\tvector keys;\n\t\t\t\tfor(auto const& port: data)\n\t\t\t\t\tkeys.push_back(port.first);\n\n\t\t\t\t\/\/2. compare port set, then write data if it is outport\n\t\t\t\tfor(auto const& key:keys){\n\t\t\t\t\tif(_portmap.find(key)!=_portmap.end()){\n\t\t\t\t\t\tif(_portmap[key]){ \/\/output port\n\t\t\t\t\t\t\tbcm2835_gpio_write(key, data[key]); \/\/write data\n\t\t\t\t\t\t\tcossb_log->log(log::loglevel::INFO, fmt::format(\"Write GPIO({}) : 0x{0:x}\", key, data[key]));\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tcatch(const boost::bad_any_cast&){\n\t\t\t\tcossb_log->log(log::loglevel::ERROR, \"Invalid type casting, should be map type.\");\n\t\t\t}\n\t\t} break;\n\t\tcase cossb::base::msg_type::RESPONSE: break;\n\t\tcase cossb::base::msg_type::EVENT: break;\n\t\t}\n}\n\n\n<|endoftext|>"} {"text":"#include \n#include \n\n#include \"particle.h\"\n#include \"simulation.h\"\n#include \"vector3d.h\"\n#include \"boundaryFieldEvaluator.h\"\n#include \"util.h\"\n\nvoid Simulation::initializeHarris() {\n\t\/\/boundaryConditionTypeX = SUPER_CONDUCTOR_LEFT;\n\t\/\/boundaryConditionTypeX = FREE_BOTH;\n\tboundaryConditionTypeX = FREE_MIRROR_BOTH;\n\tdouble l = 5*deltaX;\n \/\/E0 = Vector3d(0, 0, 0);\n\t\/\/B0 = Vector3d(0, 0, 0);\n\tfor (int i = 0; i < xnumberAdded; ++i) {\n\t\tfor (int j = 0; j < ynumberAdded; ++j) {\n\t\t\tfor (int k = 0; k < znumberAdded; ++k) {\n\t\t\t\tBfield[i][j][k] = B0*tanh((xgrid[i] - 1.5*xsizeGeneral)\/l);\n\t\t\t\tnewBfield[i][j][k] = Bfield[i][j][k];\n\t\t\t}\n\t\t}\n\t}\n\tcreateParticlesHarris(l);\n\tE0 = Vector3d(0, 0, 0);\n\n\tfor (int i = 0; i < xnumberAdded + 1; ++i) {\n\t\tfor (int j = 0; j < ynumberAdded + 1; ++j) {\n\t\t\tfor (int k = 0; k < znumberAdded + 1; ++k) {\n\t\t\t\tEfield[i][j][k] = E0;\n\t\t\t\tnewEfield[i][j][k] = Efield[i][j][k];\n\t\t\t}\n\t\t}\n\t}\n\n\trightBoundaryFieldEvaluator = new ConstantBoundaryFieldEvaluator(E0, B0);\n\tVector3d B1 = B0*(-1.0);\n\tleftBoundaryFieldEvaluator = new ConstantBoundaryFieldEvaluator(E0, B1);\n\n}\n\nvoid Simulation::createParticlesHarris(double harrisWidth) {\n\tevaluateParticleTypesAlpha();\n\tif (rank == 0) printf(\"creating particles harris\\n\");\n\tfflush(stdout);\n\tif (rank == 0) printLog(\"creating particles harris\\n\");\n\tdouble n0 = types[0].concentration;\n\tint n = 0;\n\tdouble ionTemperatureFactor = 5;\n\tdouble electronTemperature = B0.scalarMult(B0)\/(2*kBoltzman_normalized*types[0].concentration*(1 + ionTemperatureFactor)*4*pi);\n\ttypes[0].temperatureX = electronTemperature;\n\ttypes[0].temperatureY = electronTemperature;\n\ttypes[0].temperatureZ = electronTemperature;\n\tfor(int t = 1; t < typesNumber; ++t) {\n\t\ttypes[t].temperatureX = types[0].temperatureX*ionTemperatureFactor;\n\t\ttypes[t].temperatureY = types[0].temperatureY*ionTemperatureFactor;\n\t\ttypes[t].temperatureZ = types[0].temperatureZ*ionTemperatureFactor;\n\t}\n\t\/\/int density = ; % \n\t\/\/for (int i = 0; i < xnumber; ++i) {\n\tfor (int i = 1 + additionalBinNumber; i < xnumberAdded - additionalBinNumber - 1; ++i) {\n\t\tfor (int j = 1 + additionalBinNumber; j < ynumberAdded - additionalBinNumber - 1; ++j) {\n\t\t\tfor (int k = 1 + additionalBinNumber; k < znumberAdded - additionalBinNumber - 1; ++k) {\n\t\t\t\t\/\/int maxParticlesPerBin = types[0].particlesPerBin;\n\t\t\t\tdouble x = xgrid[i] + 0.0001 * deltaX;\n\t\t\t\tdouble y = ygrid[j] + 0.0001 * deltaY;\n\t\t\t\tdouble z = zgrid[k] + 0.0001 * deltaZ;\n\t\t\t\tdouble ch = cosh((xgrid[i] - 1.5*xsizeGeneral)\/harrisWidth);\n\t\t\t\tdouble concentr = n0\/(ch*ch);\n\t\t\t\t\/\/for (int l = 0; l < maxParticlesPerBin; ++l) {\n\t\t\t\tfor (int typeCounter = 0; typeCounter < typesNumber; ++typeCounter) {\n\t\t\t\t\tdouble weight = (concentr* volumeB()) \/ types[typeCounter].particlesPerBin ;\n\t\t\t\t\tdouble deltaXParticles = types[typeCounter].particesDeltaX;\n\t\t\t\t\tdouble deltaYParticles = types[typeCounter].particesDeltaY;\n\t\t\t\t\tdouble deltaZParticles = types[typeCounter].particesDeltaZ;\n\t\t\t\t\t\/\/if (l < types[typeCounter].particlesPerBin) {\n\t\t\t\t\tfor (int l = 0; l < types[typeCounter].particlesPerBin; ++l) {\n\t\t\t\t\t\tParticleTypes type = types[typeCounter].type;\n\t\t\t\t\t\tParticle* particle = createParticle(n, i, j, k, weight, type, types[typeCounter],\n\t\t\t\t\t\t types[typeCounter].temperatureX,\n\t\t\t\t\t\t types[typeCounter].temperatureY,\n\t\t\t\t\t\t types[typeCounter].temperatureZ);\n\t\t\t\t\t\tn++;\n\t\t\t\t\t\tparticle->coordinates.x = x + deltaXParticles * l;\n\t\t\t\t\t\tparticle->coordinates.y = y + deltaYParticles * l;\n\t\t\t\t\t\tparticle->coordinates.z = z + deltaZParticles * l;\n\t\t\t\t\t\t\/\/particle->coordinates.x = middleXgrid[i];\n\t\t\t\t\t\t\/\/particle->coordinates.y = middleYgrid[j];\n\t\t\t\t\t\t\/\/particle->coordinates.z = middleZgrid[k];\n\n\t\t\t\t\t\t\/\/particle->coordinates.x = xgrid[i] + uniformDistribution()*deltaX;\n\t\t\t\t\t\t\/\/particle->coordinates.y = ygrid[j] + uniformDistribution()*deltaY;\n\t\t\t\t\t\t\/\/particle->coordinates.z = zgrid[k] + uniformDistribution()*deltaZ;\n\t\t\t\t\t\tparticle->initialCoordinates = particle->coordinates;\n\n\t\t\t\t\t\tdouble P=harrisWidth*B0.norm()*types[typeCounter].charge;\n\t\t\t\t\t\tVector3d V = Vector3d(0, 1.0, 0) * (-2*kBoltzman_normalized*speed_of_light_normalized*types[typeCounter].temperatureX\/P);\n\n\t\t\t\t\t\t\tparticle->addVelocity(V, speed_of_light_normalized);\n\n\t\t\t\t\t\tVector3d momentum = particle->getMomentum();\n\t\t\t\t\t\tparticle->initialMomentum = momentum;\n\t\t\t\t\t\tparticle->prevMomentum = momentum;\n\t\t\t\t\t\tparticles.push_back(particle);\n\t\t\t\t\t\tparticlesNumber++;\n\t\t\t\t\t\tif (particlesNumber % 1000 == 0) {\n\t\t\t\t\t\t\tif ((rank == 0) && (verbosity > 0))printf(\"create particle number %d\\n\", particlesNumber);\n\t\t\t\t\t\t}\n\t\t\t\t\t\talertNaNOrInfinity(particle->coordinates.x, \"particle.x = NaN in createParticles\\n\");\n\t\t\t\t\t\talertNaNOrInfinity(particle->coordinates.y, \"particle.y = NaN in createParticles\\n\");\n\t\t\t\t\t\talertNaNOrInfinity(particle->coordinates.z, \"particle.z = NaN in createParticles\\n\");\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n}update harris#include \n#include \n\n#include \"particle.h\"\n#include \"simulation.h\"\n#include \"vector3d.h\"\n#include \"boundaryFieldEvaluator.h\"\n#include \"util.h\"\n\nvoid Simulation::initializeHarris() {\n\t\/\/boundaryConditionTypeX = SUPER_CONDUCTOR_LEFT;\n\t\/\/boundaryConditionTypeX = FREE_BOTH;\n\tboundaryConditionTypeX = FREE_MIRROR_BOTH;\n\tdouble l = 5*deltaX;\n \/\/E0 = Vector3d(0, 0, 0);\n\t\/\/B0 = Vector3d(0, 0, 0);\n\tfor (int i = 0; i < xnumberAdded; ++i) {\n\t\tfor (int j = 0; j < ynumberAdded; ++j) {\n\t\t\tfor (int k = 0; k < znumberAdded; ++k) {\n\t\t\t\tBfield[i][j][k] = B0*tanh((xgrid[i] - 1.5*xsizeGeneral)\/l);\n\t\t\t\tnewBfield[i][j][k] = Bfield[i][j][k];\n\t\t\t}\n\t\t}\n\t}\n\tcreateParticlesHarris(l);\n\tE0 = Vector3d(0, 0, 0);\n\n\tfor (int i = 0; i < xnumberAdded + 1; ++i) {\n\t\tfor (int j = 0; j < ynumberAdded + 1; ++j) {\n\t\t\tfor (int k = 0; k < znumberAdded + 1; ++k) {\n\t\t\t\tEfield[i][j][k] = E0;\n\t\t\t\tnewEfield[i][j][k] = Efield[i][j][k];\n\t\t\t}\n\t\t}\n\t}\n\n\trightBoundaryFieldEvaluator = new ConstantBoundaryFieldEvaluator(E0, B0);\n\tVector3d B1 = B0*(-1.0);\n\tleftBoundaryFieldEvaluator = new ConstantBoundaryFieldEvaluator(E0, B1);\n\n}\n\nvoid Simulation::createParticlesHarris(double harrisWidth) {\n\tevaluateParticleTypesAlpha();\n\tif (rank == 0) printf(\"creating particles harris\\n\");\n\tfflush(stdout);\n\tif (rank == 0) printLog(\"creating particles harris\\n\");\n\tdouble n0 = types[0].concentration;\n\tint n = 0;\n\t\n\t\/\/int density = ; % \n\t\/\/for (int i = 0; i < xnumber; ++i) {\n\tfor (int i = 1 + additionalBinNumber; i < xnumberAdded - additionalBinNumber - 1; ++i) {\n\t\tfor (int j = 1 + additionalBinNumber; j < ynumberAdded - additionalBinNumber - 1; ++j) {\n\t\t\tfor (int k = 1 + additionalBinNumber; k < znumberAdded - additionalBinNumber - 1; ++k) {\n\t\t\t\t\/\/int maxParticlesPerBin = types[0].particlesPerBin;\n\t\t\t\tdouble x = xgrid[i] + 0.0001 * deltaX;\n\t\t\t\tdouble y = ygrid[j] + 0.0001 * deltaY;\n\t\t\t\tdouble z = zgrid[k] + 0.0001 * deltaZ;\n\t\t\t\tdouble ch = cosh((xgrid[i] - 1.5*xsizeGeneral)\/harrisWidth);\n\t\t\t\tdouble concentr = n0\/(ch*ch);\n\t\t\t\t\/\/for (int l = 0; l < maxParticlesPerBin; ++l) {\n\t\t\t\tfor (int typeCounter = 0; typeCounter < typesNumber; ++typeCounter) {\n\t\t\t\t\tdouble weight = (concentr* volumeB()) \/ types[typeCounter].particlesPerBin ;\n\t\t\t\t\tdouble deltaXParticles = types[typeCounter].particesDeltaX;\n\t\t\t\t\tdouble deltaYParticles = types[typeCounter].particesDeltaY;\n\t\t\t\t\tdouble deltaZParticles = types[typeCounter].particesDeltaZ;\n\t\t\t\t\t\/\/if (l < types[typeCounter].particlesPerBin) {\n\t\t\t\t\tfor (int l = 0; l < types[typeCounter].particlesPerBin; ++l) {\n\t\t\t\t\t\tParticleTypes type = types[typeCounter].type;\n\t\t\t\t\t\tParticle* particle = createParticle(n, i, j, k, weight, type, types[typeCounter],\n\t\t\t\t\t\t types[typeCounter].temperatureX,\n\t\t\t\t\t\t types[typeCounter].temperatureY,\n\t\t\t\t\t\t types[typeCounter].temperatureZ);\n\t\t\t\t\t\tn++;\n\t\t\t\t\t\tparticle->coordinates.x = x + deltaXParticles * l;\n\t\t\t\t\t\tparticle->coordinates.y = y + deltaYParticles * l;\n\t\t\t\t\t\tparticle->coordinates.z = z + deltaZParticles * l;\n\t\t\t\t\t\t\/\/particle->coordinates.x = middleXgrid[i];\n\t\t\t\t\t\t\/\/particle->coordinates.y = middleYgrid[j];\n\t\t\t\t\t\t\/\/particle->coordinates.z = middleZgrid[k];\n\n\t\t\t\t\t\t\/\/particle->coordinates.x = xgrid[i] + uniformDistribution()*deltaX;\n\t\t\t\t\t\t\/\/particle->coordinates.y = ygrid[j] + uniformDistribution()*deltaY;\n\t\t\t\t\t\t\/\/particle->coordinates.z = zgrid[k] + uniformDistribution()*deltaZ;\n\t\t\t\t\t\tparticle->initialCoordinates = particle->coordinates;\n\n\t\t\t\t\t\tdouble P=harrisWidth*B0.norm()*types[typeCounter].charge;\n\t\t\t\t\t\tVector3d V = Vector3d(0, 1.0, 0) * (-2*kBoltzman_normalized*speed_of_light_normalized*types[typeCounter].temperatureX\/P);\n\n\t\t\t\t\t\t\tparticle->addVelocity(V, speed_of_light_normalized);\n\n\t\t\t\t\t\tVector3d momentum = particle->getMomentum();\n\t\t\t\t\t\tparticle->initialMomentum = momentum;\n\t\t\t\t\t\tparticle->prevMomentum = momentum;\n\t\t\t\t\t\tparticles.push_back(particle);\n\t\t\t\t\t\tparticlesNumber++;\n\t\t\t\t\t\tif (particlesNumber % 1000 == 0) {\n\t\t\t\t\t\t\tif ((rank == 0) && (verbosity > 0))printf(\"create particle number %d\\n\", particlesNumber);\n\t\t\t\t\t\t}\n\t\t\t\t\t\talertNaNOrInfinity(particle->coordinates.x, \"particle.x = NaN in createParticles\\n\");\n\t\t\t\t\t\talertNaNOrInfinity(particle->coordinates.y, \"particle.y = NaN in createParticles\\n\");\n\t\t\t\t\t\talertNaNOrInfinity(particle->coordinates.z, \"particle.z = NaN in createParticles\\n\");\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n}<|endoftext|>"} {"text":"#include \"ros\/ros.h\"\n\n#include \"EventTriggerUtility.h\"\n#include \"elderly_care_simulation\/EventTrigger.h\"\n#include \n#include \/\/ sleep\n#include \"Scheduler.h\"\n\nusing namespace elderly_care_simulation;\n\nScheduler scheduler;\n\nScheduler::Scheduler(){\n concurrentWeight = 0;\n allowNewEvents = true;\n stopRosInfoSpam = false;\n\n randomEventLimit[EVENT_TRIGGER_EVENT_TYPE_MORAL_SUPPORT] = false;\n randomEventLimit[EVENT_TRIGGER_EVENT_TYPE_ILL] = false;\n randomEventLimit[EVENT_TRIGGER_EVENT_TYPE_VERY_ILL] = false;\n}\n\nScheduler::~Scheduler() {}\n\n\/**\n * Creates a Request EventTrigger message for requesting robot tasks.\n * @param eventType the event type for the message\n *\/\nEventTrigger Scheduler::createEventRequestMsg(int eventType, int priority){\n EventTrigger msg;\n msg.msg_type = EVENT_TRIGGER_MSG_TYPE_REQUEST;\n msg.event_type = eventType;\n msg.event_priority = priority;\n msg.event_weight = getEventWeight(eventType);\n msg.result = EVENT_TRIGGER_RESULT_UNDEFINED;\n\n return msg;\n}\n\n\/**\n * Clears the eventQueue.\n *\/\nvoid Scheduler::clearEventQueue() {\n eventQueue = std::priority_queue();\n}\n\n\/**\n * Reset all random event occurrence back to false.\n *\/\nvoid Scheduler::resetRandomEventOccurrence() {\n\n for(std::map::iterator iter = randomEventLimit.begin(); iter != randomEventLimit.end(); ++iter) {\n randomEventLimit[iter->first] = false;\n }\n}\n\n\/**\n * Returns the current concurrent weight count\n *\/\nint Scheduler::getConcurrentWeight() const {\n return concurrentWeight;\n}\n\n\n\/**\n * Returns the current event queue size\n *\/\nint Scheduler::getEventQueueSize() const {\n return eventQueue.size();\n}\n\n\/**\n * Callback function to deal with external events\n *\/\nvoid Scheduler::externalEventReceivedCallback(EventTrigger msg) {\n\n \/\/ Only allows random events to be added to event queue in the allowed\n \/\/ timeframe (between WAKE and SLEEP)\n if(!allowNewEvents) {\n ROS_INFO(\"Scheduler: Additional events are not allowed at this time.\");\n return;\n }\n\n \/\/ If the incoming event is a random event\n if(randomEventLimit.count(msg.event_type) != 0) {\n\n \/\/ If it havent occured before, change the flag and continue\n if(randomEventLimit[msg.event_type] == false) {\n randomEventLimit[msg.event_type] = true;\n\n \/\/ If event occured before, then block it\n } else {\n ROS_INFO(\"Scheduler: [%s] cannot occur more than once per day.\", \n eventTypeToString(msg.event_type));\n return;\n }\n }\n\n ROS_INFO(\"Scheduler: Enqueuing event: [%s] with priority [%s]\", \n eventTypeToString(msg.event_type),\n priorityToString(msg.event_priority));\n\n eventQueue.push(EventNode(msg));\n}\n\n\/**\n * Callback function to deal with events replied from service provider robots\n *\/\nvoid Scheduler::eventTriggerCallback(EventTrigger msg) {\n \n if (msg.msg_type == EVENT_TRIGGER_MSG_TYPE_RESPONSE) {\n if(msg.result == EVENT_TRIGGER_RESULT_SUCCESS){\n\n if (msg.event_type == EVENT_TRIGGER_EVENT_TYPE_COOK) {\n ROS_INFO(\"Scheduler: [%s] done.\", eventTypeToString(msg.event_type));\n\n EventTrigger eatMsg;\n eatMsg = createEventRequestMsg(EVENT_TRIGGER_EVENT_TYPE_EAT, EVENT_TRIGGER_PRIORITY_HIGH);\n ROS_INFO(\"Scheduler: Enqueuing event: [%s] with priority [%s]\",\n eventTypeToString(eatMsg.event_type),\n priorityToString(eatMsg.event_priority));\n\n eventQueue.push(EventNode(eatMsg));\n }else{\n concurrentWeight -= msg.event_weight;\n ROS_INFO(\"Scheduler: [%s] done.\", eventTypeToString(msg.event_type)); \n }\n }\n }\n}\n\n\/**\n * Populates daily scheduled tasks into the event queue.\n * \n * Daily Schedule will be queued in the following sequence:\n * NOTE: The timestamp is just for referencing purpose.\n *\n * 07:00 WAKE\n * 07:00 COOK ---> EAT\n * 07:00 MEDICATION\n * 08:00 EXERCISE\n * 09:00 SHOWER\n * 10:00 ENTERTAINMENT\n *\n * 12:00 COOK ---> EAT\n * 12:00 MEDICATION\n * 13:00 CONVERSATION\n * 14:00 FRIEND & RELATIVE\n * 16:00 ENTERTAINMENT\n *\n * 18:00 COOK ---> EAT\n * 18:00 MEDICATION\n * 19:00 COMPANIONSHIP\n * 20:00 SLEEP\n * \n * PAUSE FOR 20 SEC\n * CLEAR LIST & REPOPULATE DAILY TASKS\n *\n *\/\nvoid Scheduler::populateDailyTasks() {\n\n int eventSequence[][2] = {\n\n \/\/ ======================================\n \/\/ = COMMENTED OUT STUFF =\n \/\/ ======================================\n\n \/\/ \/\/ Morning\n \/\/ { EVENT_TRIGGER_EVENT_TYPE_WAKE, EVENT_TRIGGER_PRIORITY_LOW },\n \/\/ { EVENT_TRIGGER_EVENT_TYPE_COOK, EVENT_TRIGGER_PRIORITY_LOW },\n \/\/ { EVENT_TRIGGER_EVENT_TYPE_MOVE_TO_KITCHEN, EVENT_TRIGGER_PRIORITY_LOW },\n \/\/ { EVENT_TRIGGER_EVENT_TYPE_MEDICATION, EVENT_TRIGGER_PRIORITY_LOW },\n \/\/ { EVENT_TRIGGER_EVENT_TYPE_EXERCISE, EVENT_TRIGGER_PRIORITY_LOW },\n \/\/ { EVENT_TRIGGER_EVENT_TYPE_SHOWER, EVENT_TRIGGER_PRIORITY_LOW },\n \/\/ { EVENT_TRIGGER_EVENT_TYPE_MOVE_TO_BEDROOM, EVENT_TRIGGER_PRIORITY_LOW },\n { EVENT_TRIGGER_EVENT_TYPE_COOK, EVENT_TRIGGER_PRIORITY_LOW },\n \/\/ { EVENT_TRIGGER_EVENT_TYPE_ENTERTAINMENT, EVENT_TRIGGER_PRIORITY_LOW },\n\n \/\/ \/\/ Noon\n { EVENT_TRIGGER_EVENT_TYPE_MEDICATION, EVENT_TRIGGER_PRIORITY_LOW },\n \/\/ { EVENT_TRIGGER_EVENT_TYPE_CONVERSATION, EVENT_TRIGGER_PRIORITY_LOW },\n \/\/ { EVENT_TRIGGER_EVENT_TYPE_MOVE_TO_HALLWAY, EVENT_TRIGGER_PRIORITY_LOW },\n \/\/ { EVENT_TRIGGER_EVENT_TYPE_RELATIVE, EVENT_TRIGGER_PRIORITY_LOW },\n \/\/ { EVENT_TRIGGER_EVENT_TYPE_FRIEND, EVENT_TRIGGER_PRIORITY_LOW },\n \/\/ { EVENT_TRIGGER_EVENT_TYPE_COOK, EVENT_TRIGGER_PRIORITY_LOW },\n \/\/ { EVENT_TRIGGER_EVENT_TYPE_ENTERTAINMENT, EVENT_TRIGGER_PRIORITY_LOW },\n\n \/\/ \/\/ Evening\n \/\/ { EVENT_TRIGGER_EVENT_TYPE_MEDICATION, EVENT_TRIGGER_PRIORITY_LOW },\n \/\/ { EVENT_TRIGGER_EVENT_TYPE_MOVE_TO_BEDROOM, EVENT_TRIGGER_PRIORITY_LOW },\n { EVENT_TRIGGER_EVENT_TYPE_COMPANIONSHIP, EVENT_TRIGGER_PRIORITY_LOW }\n \/\/ { EVENT_TRIGGER_EVENT_TYPE_SLEEP, EVENT_TRIGGER_PRIORITY_VERY_LOW }\n };\n for(unsigned int i = 0; i < sizeof(eventSequence)\/sizeof(*eventSequence); i++) {\n eventQueue.push(EventNode(createEventRequestMsg(eventSequence[i][0], eventSequence[i][1])));\n }\n}\n\n\/**\n * Dequeues an event and publishes to the event_trigger topic.\n * Allows concurrent events to be triggered up to the limit\n * set in MAX_CONCURRENT_WEIGHT\n *\n * COOK event is not affected as it acts independently of the \n * Resident.\n *\/\nvoid Scheduler::dequeueEvent() {\n\n if (eventQueue.size() < 1) {\n return;\n }\n\n EventTrigger msg;\n msg = eventQueue.top().getEventTriggerMessage();\n\n \n \/\/ Publish event if enough concurrent weight available\n if (concurrentWeight + msg.event_weight <= MAX_CONCURRENT_WEIGHT) {\n\n ROS_INFO(\"Scheduler: Publishing event: [%s]\", eventTypeToString(msg.event_type));\n\n stopRosInfoSpam = false;\n switch(msg.event_type) {\n case EVENT_TRIGGER_EVENT_TYPE_SLEEP:\n allowNewEvents = true;\n\n concurrentWeight += msg.event_weight;\n eventTriggerPub.publish(msg);\n eventQueue.pop();\n \n break;\n\n case EVENT_TRIGGER_EVENT_TYPE_ILL:\n allowNewEvents = false;\n\n concurrentWeight += msg.event_weight;\n eventTriggerPub.publish(msg);\n eventQueue.pop();\n\n eventQueue.push(EventNode(createEventRequestMsg(EVENT_TRIGGER_EVENT_TYPE_SLEEP,\n EVENT_TRIGGER_PRIORITY_VERY_HIGH)));\n eventQueue.push(EventNode(createEventRequestMsg(EVENT_TRIGGER_EVENT_TYPE_WAKE,\n EVENT_TRIGGER_PRIORITY_VERY_HIGH)));\n break;\n\n case EVENT_TRIGGER_EVENT_TYPE_VERY_ILL:\n allowNewEvents = false;\n\n concurrentWeight += msg.event_weight;\n eventTriggerPub.publish(msg);\n eventQueue.pop();\n\n clearEventQueue();\n\n \/\/ Enqueue a SLEEP event with max priority so when resident comes back from \n \/\/ hospital it goes to sleep right away.\n \/\/ Since the queue is now empty after the SLEEP event, a new batch of daily\n \/\/ schedules will be repopulated automatically (in the main method).\n eventQueue.push(EventNode(createEventRequestMsg(EVENT_TRIGGER_EVENT_TYPE_SLEEP,\n EVENT_TRIGGER_PRIORITY_VERY_HIGH)));\n break;\n\n default:\n allowNewEvents = false;\n eventTriggerPub.publish(msg);\n concurrentWeight += msg.event_weight;\n eventQueue.pop();\n break;\n }\n\n } else {\n if(!stopRosInfoSpam){\n ROS_INFO(\"Scheduler: Pending event: [%s]\", \n eventTypeToString(msg.event_type));\n stopRosInfoSpam = true;\n }\n }\n}\n\nvoid callEventTriggerCallback(EventTrigger msg) {\n scheduler.eventTriggerCallback(msg);\n}\n\nvoid callExternalEventReceivedCallback(EventTrigger msg) {\n scheduler.externalEventReceivedCallback(msg);\n}\n\n\/**\n * Main\n *\/\nint main(int argc, char **argv) {\n\n \/\/You must call ros::init() first of all. ros::init() function needs to see argc and argv. The third argument is the name of the node\n ros::init(argc, argv, \"Scheduler\");\n\n \/\/NodeHandle is the main access point to communicate with ros.\n ros::NodeHandle nodeHandle;\n\n scheduler = Scheduler();\n\n \/\/ advertise to event_trigger topic\n scheduler.eventTriggerPub = nodeHandle.advertise(\"event_trigger\",1000, true);\n\n \/\/ subscribe to event_trigger topic\n scheduler.eventTriggerSub = nodeHandle.subscribe(\"event_trigger\",1000, callEventTriggerCallback);\n scheduler.externalEventSub = nodeHandle.subscribe(\"external_event\",1000, callExternalEventReceivedCallback);\n \n ros::Rate loop_rate(10);\n\n \/\/ populate queue with day's events\n \n scheduler.populateDailyTasks();\n\n \/\/a count of howmany messages we have sent\n int count = 0;\n sleep(3);\n ROS_INFO(\"Day Starts....\");\n\n while (ros::ok()) {\n\n if(scheduler.getEventQueueSize() == 0 && scheduler.getConcurrentWeight() == 0) {\n ROS_INFO(\"Day Ends....\");\n sleep(10);\n scheduler.clearEventQueue();\n scheduler.resetRandomEventOccurrence();\n scheduler.populateDailyTasks();\n ROS_INFO(\"Day Starts....\");\n }else {\n scheduler.dequeueEvent();\n }\n\n ros::spinOnce();\n loop_rate.sleep();\n ++count;\n }\n return 0;\n}\nIncreased scheduler's startup sleep time to fix timing issues. [#54][#56]#include \"ros\/ros.h\"\n\n#include \"EventTriggerUtility.h\"\n#include \"elderly_care_simulation\/EventTrigger.h\"\n#include \n#include \/\/ sleep\n#include \"Scheduler.h\"\n\nusing namespace elderly_care_simulation;\n\nScheduler scheduler;\n\nScheduler::Scheduler(){\n concurrentWeight = 0;\n allowNewEvents = true;\n stopRosInfoSpam = false;\n\n randomEventLimit[EVENT_TRIGGER_EVENT_TYPE_MORAL_SUPPORT] = false;\n randomEventLimit[EVENT_TRIGGER_EVENT_TYPE_ILL] = false;\n randomEventLimit[EVENT_TRIGGER_EVENT_TYPE_VERY_ILL] = false;\n}\n\nScheduler::~Scheduler() {}\n\n\/**\n * Creates a Request EventTrigger message for requesting robot tasks.\n * @param eventType the event type for the message\n *\/\nEventTrigger Scheduler::createEventRequestMsg(int eventType, int priority){\n EventTrigger msg;\n msg.msg_type = EVENT_TRIGGER_MSG_TYPE_REQUEST;\n msg.event_type = eventType;\n msg.event_priority = priority;\n msg.event_weight = getEventWeight(eventType);\n msg.result = EVENT_TRIGGER_RESULT_UNDEFINED;\n\n return msg;\n}\n\n\/**\n * Clears the eventQueue.\n *\/\nvoid Scheduler::clearEventQueue() {\n eventQueue = std::priority_queue();\n}\n\n\/**\n * Reset all random event occurrence back to false.\n *\/\nvoid Scheduler::resetRandomEventOccurrence() {\n\n for(std::map::iterator iter = randomEventLimit.begin(); iter != randomEventLimit.end(); ++iter) {\n randomEventLimit[iter->first] = false;\n }\n}\n\n\/**\n * Returns the current concurrent weight count\n *\/\nint Scheduler::getConcurrentWeight() const {\n return concurrentWeight;\n}\n\n\n\/**\n * Returns the current event queue size\n *\/\nint Scheduler::getEventQueueSize() const {\n return eventQueue.size();\n}\n\n\/**\n * Callback function to deal with external events\n *\/\nvoid Scheduler::externalEventReceivedCallback(EventTrigger msg) {\n\n \/\/ Only allows random events to be added to event queue in the allowed\n \/\/ timeframe (between WAKE and SLEEP)\n if(!allowNewEvents) {\n ROS_INFO(\"Scheduler: Additional events are not allowed at this time.\");\n return;\n }\n\n \/\/ If the incoming event is a random event\n if(randomEventLimit.count(msg.event_type) != 0) {\n\n \/\/ If it havent occured before, change the flag and continue\n if(randomEventLimit[msg.event_type] == false) {\n randomEventLimit[msg.event_type] = true;\n\n \/\/ If event occured before, then block it\n } else {\n ROS_INFO(\"Scheduler: [%s] cannot occur more than once per day.\", \n eventTypeToString(msg.event_type));\n return;\n }\n }\n\n ROS_INFO(\"Scheduler: Enqueuing event: [%s] with priority [%s]\", \n eventTypeToString(msg.event_type),\n priorityToString(msg.event_priority));\n\n eventQueue.push(EventNode(msg));\n}\n\n\/**\n * Callback function to deal with events replied from service provider robots\n *\/\nvoid Scheduler::eventTriggerCallback(EventTrigger msg) {\n \n if (msg.msg_type == EVENT_TRIGGER_MSG_TYPE_RESPONSE) {\n if(msg.result == EVENT_TRIGGER_RESULT_SUCCESS){\n\n if (msg.event_type == EVENT_TRIGGER_EVENT_TYPE_COOK) {\n ROS_INFO(\"Scheduler: [%s] done.\", eventTypeToString(msg.event_type));\n\n EventTrigger eatMsg;\n eatMsg = createEventRequestMsg(EVENT_TRIGGER_EVENT_TYPE_EAT, EVENT_TRIGGER_PRIORITY_HIGH);\n ROS_INFO(\"Scheduler: Enqueuing event: [%s] with priority [%s]\",\n eventTypeToString(eatMsg.event_type),\n priorityToString(eatMsg.event_priority));\n\n eventQueue.push(EventNode(eatMsg));\n }else{\n concurrentWeight -= msg.event_weight;\n ROS_INFO(\"Scheduler: [%s] done.\", eventTypeToString(msg.event_type)); \n }\n }\n }\n}\n\n\/**\n * Populates daily scheduled tasks into the event queue.\n * \n * Daily Schedule will be queued in the following sequence:\n * NOTE: The timestamp is just for referencing purpose.\n *\n * 07:00 WAKE\n * 07:00 COOK ---> EAT\n * 07:00 MEDICATION\n * 08:00 EXERCISE\n * 09:00 SHOWER\n * 10:00 ENTERTAINMENT\n *\n * 12:00 COOK ---> EAT\n * 12:00 MEDICATION\n * 13:00 CONVERSATION\n * 14:00 FRIEND & RELATIVE\n * 16:00 ENTERTAINMENT\n *\n * 18:00 COOK ---> EAT\n * 18:00 MEDICATION\n * 19:00 COMPANIONSHIP\n * 20:00 SLEEP\n * \n * PAUSE FOR 20 SEC\n * CLEAR LIST & REPOPULATE DAILY TASKS\n *\n *\/\nvoid Scheduler::populateDailyTasks() {\n\n int eventSequence[][2] = {\n\n \/\/ ======================================\n \/\/ = COMMENTED OUT STUFF =\n \/\/ ======================================\n\n \/\/ \/\/ Morning\n \/\/ { EVENT_TRIGGER_EVENT_TYPE_WAKE, EVENT_TRIGGER_PRIORITY_LOW },\n \/\/ { EVENT_TRIGGER_EVENT_TYPE_COOK, EVENT_TRIGGER_PRIORITY_LOW },\n \/\/ { EVENT_TRIGGER_EVENT_TYPE_MOVE_TO_KITCHEN, EVENT_TRIGGER_PRIORITY_LOW },\n \/\/ { EVENT_TRIGGER_EVENT_TYPE_MEDICATION, EVENT_TRIGGER_PRIORITY_LOW },\n \/\/ { EVENT_TRIGGER_EVENT_TYPE_EXERCISE, EVENT_TRIGGER_PRIORITY_LOW },\n \/\/ { EVENT_TRIGGER_EVENT_TYPE_SHOWER, EVENT_TRIGGER_PRIORITY_LOW },\n \/\/ { EVENT_TRIGGER_EVENT_TYPE_MOVE_TO_BEDROOM, EVENT_TRIGGER_PRIORITY_LOW },\n { EVENT_TRIGGER_EVENT_TYPE_COOK, EVENT_TRIGGER_PRIORITY_LOW },\n \/\/ { EVENT_TRIGGER_EVENT_TYPE_ENTERTAINMENT, EVENT_TRIGGER_PRIORITY_LOW },\n\n \/\/ \/\/ Noon\n { EVENT_TRIGGER_EVENT_TYPE_MEDICATION, EVENT_TRIGGER_PRIORITY_LOW },\n \/\/ { EVENT_TRIGGER_EVENT_TYPE_CONVERSATION, EVENT_TRIGGER_PRIORITY_LOW },\n \/\/ { EVENT_TRIGGER_EVENT_TYPE_MOVE_TO_HALLWAY, EVENT_TRIGGER_PRIORITY_LOW },\n \/\/ { EVENT_TRIGGER_EVENT_TYPE_RELATIVE, EVENT_TRIGGER_PRIORITY_LOW },\n \/\/ { EVENT_TRIGGER_EVENT_TYPE_FRIEND, EVENT_TRIGGER_PRIORITY_LOW },\n \/\/ { EVENT_TRIGGER_EVENT_TYPE_COOK, EVENT_TRIGGER_PRIORITY_LOW },\n \/\/ { EVENT_TRIGGER_EVENT_TYPE_ENTERTAINMENT, EVENT_TRIGGER_PRIORITY_LOW },\n\n \/\/ \/\/ Evening\n \/\/ { EVENT_TRIGGER_EVENT_TYPE_MEDICATION, EVENT_TRIGGER_PRIORITY_LOW },\n \/\/ { EVENT_TRIGGER_EVENT_TYPE_MOVE_TO_BEDROOM, EVENT_TRIGGER_PRIORITY_LOW },\n { EVENT_TRIGGER_EVENT_TYPE_COMPANIONSHIP, EVENT_TRIGGER_PRIORITY_LOW }\n \/\/ { EVENT_TRIGGER_EVENT_TYPE_SLEEP, EVENT_TRIGGER_PRIORITY_VERY_LOW }\n };\n for(unsigned int i = 0; i < sizeof(eventSequence)\/sizeof(*eventSequence); i++) {\n eventQueue.push(EventNode(createEventRequestMsg(eventSequence[i][0], eventSequence[i][1])));\n }\n}\n\n\/**\n * Dequeues an event and publishes to the event_trigger topic.\n * Allows concurrent events to be triggered up to the limit\n * set in MAX_CONCURRENT_WEIGHT\n *\n * COOK event is not affected as it acts independently of the \n * Resident.\n *\/\nvoid Scheduler::dequeueEvent() {\n\n if (eventQueue.size() < 1) {\n return;\n }\n\n EventTrigger msg;\n msg = eventQueue.top().getEventTriggerMessage();\n\n \n \/\/ Publish event if enough concurrent weight available\n if (concurrentWeight + msg.event_weight <= MAX_CONCURRENT_WEIGHT) {\n\n ROS_INFO(\"Scheduler: Publishing event: [%s]\", eventTypeToString(msg.event_type));\n\n stopRosInfoSpam = false;\n switch(msg.event_type) {\n case EVENT_TRIGGER_EVENT_TYPE_SLEEP:\n allowNewEvents = true;\n\n concurrentWeight += msg.event_weight;\n eventTriggerPub.publish(msg);\n eventQueue.pop();\n \n break;\n\n case EVENT_TRIGGER_EVENT_TYPE_ILL:\n allowNewEvents = false;\n\n concurrentWeight += msg.event_weight;\n eventTriggerPub.publish(msg);\n eventQueue.pop();\n\n eventQueue.push(EventNode(createEventRequestMsg(EVENT_TRIGGER_EVENT_TYPE_SLEEP,\n EVENT_TRIGGER_PRIORITY_VERY_HIGH)));\n eventQueue.push(EventNode(createEventRequestMsg(EVENT_TRIGGER_EVENT_TYPE_WAKE,\n EVENT_TRIGGER_PRIORITY_VERY_HIGH)));\n break;\n\n case EVENT_TRIGGER_EVENT_TYPE_VERY_ILL:\n allowNewEvents = false;\n\n concurrentWeight += msg.event_weight;\n eventTriggerPub.publish(msg);\n eventQueue.pop();\n\n clearEventQueue();\n\n \/\/ Enqueue a SLEEP event with max priority so when resident comes back from \n \/\/ hospital it goes to sleep right away.\n \/\/ Since the queue is now empty after the SLEEP event, a new batch of daily\n \/\/ schedules will be repopulated automatically (in the main method).\n eventQueue.push(EventNode(createEventRequestMsg(EVENT_TRIGGER_EVENT_TYPE_SLEEP,\n EVENT_TRIGGER_PRIORITY_VERY_HIGH)));\n break;\n\n default:\n allowNewEvents = false;\n eventTriggerPub.publish(msg);\n concurrentWeight += msg.event_weight;\n eventQueue.pop();\n break;\n }\n\n } else {\n if(!stopRosInfoSpam){\n ROS_INFO(\"Scheduler: Pending event: [%s]\", \n eventTypeToString(msg.event_type));\n stopRosInfoSpam = true;\n }\n }\n}\n\nvoid callEventTriggerCallback(EventTrigger msg) {\n scheduler.eventTriggerCallback(msg);\n}\n\nvoid callExternalEventReceivedCallback(EventTrigger msg) {\n scheduler.externalEventReceivedCallback(msg);\n}\n\n\/**\n * Main\n *\/\nint main(int argc, char **argv) {\n\n \/\/You must call ros::init() first of all. ros::init() function needs to see argc and argv. The third argument is the name of the node\n ros::init(argc, argv, \"Scheduler\");\n\n \/\/NodeHandle is the main access point to communicate with ros.\n ros::NodeHandle nodeHandle;\n\n scheduler = Scheduler();\n\n \/\/ advertise to event_trigger topic\n scheduler.eventTriggerPub = nodeHandle.advertise(\"event_trigger\",1000, true);\n\n \/\/ subscribe to event_trigger topic\n scheduler.eventTriggerSub = nodeHandle.subscribe(\"event_trigger\",1000, callEventTriggerCallback);\n scheduler.externalEventSub = nodeHandle.subscribe(\"external_event\",1000, callExternalEventReceivedCallback);\n \n ros::Rate loop_rate(10);\n\n \/\/ populate queue with day's events\n \n scheduler.populateDailyTasks();\n\n \/\/a count of howmany messages we have sent\n int count = 0;\n sleep(5);\n ROS_INFO(\"Day Starts....\");\n\n while (ros::ok()) {\n\n if(scheduler.getEventQueueSize() == 0 && scheduler.getConcurrentWeight() == 0) {\n ROS_INFO(\"Day Ends....\");\n sleep(10);\n scheduler.clearEventQueue();\n scheduler.resetRandomEventOccurrence();\n scheduler.populateDailyTasks();\n ROS_INFO(\"Day Starts....\");\n }else {\n scheduler.dequeueEvent();\n }\n\n ros::spinOnce();\n loop_rate.sleep();\n ++count;\n }\n return 0;\n}\n<|endoftext|>"} {"text":"\/*\n * Copyright 2013 Google Inc.\n *\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n *\/\n\n#include \"SkRTConf.h\"\n#include \"SkOSFile.h\"\n\nSkRTConfRegistry::SkRTConfRegistry(): fConfs(100) {\n\n SkFILE *fp = sk_fopen(configFileLocation(), kRead_SkFILE_Flag);\n\n if (!fp) {\n return;\n }\n\n char line[1024];\n\n while (!sk_feof(fp)) {\n\n if (!sk_fgets(line, sizeof(line), fp)) {\n break;\n }\n\n char *commentptr = strchr(line, '#');\n if (commentptr == line) {\n continue;\n }\n if (NULL != commentptr) {\n *commentptr = '\\0';\n }\n\n char sep[] = \" \\t\\r\\n\";\n\n char *keyptr = strtok(line, sep);\n if (!keyptr) {\n continue;\n }\n\n char *valptr = strtok(NULL, sep);\n if (!valptr) {\n continue;\n }\n\n SkString* key = new SkString(keyptr);\n SkString* val = new SkString(valptr);\n\n fConfigFileKeys.append(1, &key);\n fConfigFileValues.append(1, &val);\n }\n sk_fclose(fp);\n}\n\nconst char *SkRTConfRegistry::configFileLocation() const {\n return \"skia.conf\"; \/\/ for now -- should probably do something fancier like home directories or whatever.\n}\n\n\/\/ dump all known runtime config options to the file with their default values.\n\/\/ to trigger this, make a config file of zero size.\nvoid SkRTConfRegistry::possiblyDumpFile() const {\n const char *path = configFileLocation();\n SkFILE *fp = sk_fopen(path, kRead_SkFILE_Flag);\n if (!fp) {\n return;\n }\n size_t configFileSize = sk_fgetsize(fp);\n if (configFileSize == 0) {\n printAll(path);\n }\n sk_fclose(fp);\n}\n\n\/\/ Run through every provided configuration option and print a warning if the user hasn't\n\/\/ declared a correponding configuration object somewhere.\nvoid SkRTConfRegistry::validate() const {\n for (int i = 0 ; i < fConfigFileKeys.count() ; i++) {\n if (fConfs.find(fConfigFileKeys[i]->c_str())) {\n SkDebugf(\"WARNING: You have config value %s in your configuration file, but I've never heard of that.\\n\", fConfigFileKeys[i]->c_str());\n }\n }\n}\n\nvoid SkRTConfRegistry::printAll(const char *fname) const {\n SkWStream *o;\n\n if (NULL != fname) {\n o = new SkFILEWStream(fname);\n } else {\n o = new SkDebugWStream();\n }\n\n ConfMap::Iter iter(fConfs);\n SkTDArray *confArray;\n\n while (iter.next(&confArray)) {\n if (confArray->getAt(0)->isDefault()) {\n o->writeText(\"# \");\n }\n confArray->getAt(0)->print(o);\n o->newline();\n }\n\n delete o;\n}\n\nvoid SkRTConfRegistry::printNonDefault(const char *fname) const {\n SkWStream *o;\n\n if (NULL != fname) {\n o = new SkFILEWStream(fname);\n } else {\n o = new SkDebugWStream();\n }\n ConfMap::Iter iter(fConfs);\n SkTDArray *confArray;\n\n while (iter.next(&confArray)) {\n if (!confArray->getAt(0)->isDefault()) {\n confArray->getAt(0)->print(o);\n o->newline();\n }\n }\n\n delete o;\n}\n\n\/\/ register a configuration variable after its value has been set by the parser.\n\/\/ we maintain a vector of these things instead of just a single one because the\n\/\/ user might set the value after initialization time and we need to have\n\/\/ all the pointers lying around, not just one.\nvoid SkRTConfRegistry::registerConf(SkRTConfBase *conf) {\n SkTDArray *confArray;\n if (fConfs.find(conf->getName(), &confArray)) {\n if (!conf->equals(confArray->getAt(0))) {\n SkDebugf(\"WARNING: Skia config \\\"%s\\\" was registered more than once in incompatible ways.\\n\", conf->getName());\n } else {\n confArray->append(1, &conf);\n }\n } else {\n confArray = new SkTDArray;\n confArray->append(1, &conf);\n fConfs.set(conf->getName(),confArray);\n }\n}\n\ntemplate T doParse(const char *s, bool *success ) {\n SkDebugf(\"WARNING: Invoked non-specialized doParse function...\\n\");\n if (success) {\n *success = false;\n }\n return (T) 0;\n}\n\ntemplate<> bool doParse(const char *s, bool *success) {\n if (success) {\n *success = true;\n }\n if (!strcmp(s,\"1\") || !strcmp(s,\"true\")) {\n return true;\n }\n if (!strcmp(s,\"0\") || !strcmp(s,\"false\")) {\n return false;\n }\n if (success) {\n *success = false;\n }\n return false;\n}\n\ntemplate<> const char * doParse(const char * s, bool *success) {\n if (success) {\n *success = true;\n }\n return s;\n}\n\ntemplate<> int doParse(const char * s, bool *success) {\n return atoi(s);\n}\n\ntemplate<> unsigned int doParse(const char * s, bool *success) {\n return (unsigned int) atoi(s);\n}\n\ntemplate<> float doParse(const char * s, bool *success) {\n return (float) atof(s);\n}\n\ntemplate<> double doParse(const char * s, bool *success) {\n return atof(s);\n}\n\nstatic inline void str_replace(char *s, char search, char replace) {\n for (char *ptr = s ; *ptr ; ptr++) {\n if (*ptr == search) {\n *ptr = replace;\n }\n }\n}\n\ntemplate bool SkRTConfRegistry::parse(const char *name, T* value) {\n SkString *str = NULL;\n\n for (int i = 0 ; i < fConfigFileKeys.count() ; i++) {\n if (fConfigFileKeys[i]->equals(name)) {\n str = fConfigFileValues[i];\n }\n }\n\n SkString environment_variable(\"skia.\");\n environment_variable.append(name);\n\n const char *environment_value = getenv(environment_variable.c_str());\n if (environment_value) {\n str->set(environment_value);\n } else {\n \/\/ apparently my shell doesn't let me have environment variables that\n \/\/ have periods in them, so also let the user substitute underscores.\n SkString underscore_environment_variable(\"skia_\");\n char *underscore_name = SkStrDup(name);\n str_replace(underscore_name,'.','_');\n underscore_environment_variable.append(underscore_name);\n sk_free(underscore_name);\n environment_value = getenv(underscore_environment_variable.c_str());\n if (environment_value) {\n str->set(environment_value);\n }\n }\n\n if (!str) {\n return false;\n }\n\n bool success;\n T new_value = doParse(str->c_str(),&success);\n if (success) {\n *value = new_value;\n } else {\n SkDebugf(\"WARNING: Couldn't parse value \\'%s\\' for variable \\'%s\\'\\n\", str->c_str(), name);\n }\n return success;\n}\n\n\/\/ need to explicitly instantiate the parsing function for every config type we might have...\n\ntemplate bool SkRTConfRegistry::parse(const char *name, bool *value);\ntemplate bool SkRTConfRegistry::parse(const char *name, int *value);\ntemplate bool SkRTConfRegistry::parse(const char *name, unsigned int *value);\ntemplate bool SkRTConfRegistry::parse(const char *name, float *value);\ntemplate bool SkRTConfRegistry::parse(const char *name, double *value);\ntemplate bool SkRTConfRegistry::parse(const char *name, const char **value);\n\ntemplate void SkRTConfRegistry::set(const char *name, T value) {\n\n SkTDArray *confArray;\n if (!fConfs.find(name, &confArray)) {\n SkDebugf(\"WARNING: Attempting to set configuration value \\\"%s\\\", but I've never heard of that.\\n\", name);\n return;\n }\n\n for (SkRTConfBase **confBase = confArray->begin(); confBase != confArray->end(); confBase++) {\n \/\/ static_cast here is okay because there's only one kind of child class.\n SkRTConf *concrete = static_cast *>(*confBase);\n\n if (concrete) {\n concrete->set(value);\n }\n }\n}\n\ntemplate void SkRTConfRegistry::set(const char *name, bool value);\ntemplate void SkRTConfRegistry::set(const char *name, int value);\ntemplate void SkRTConfRegistry::set(const char *name, unsigned int value);\ntemplate void SkRTConfRegistry::set(const char *name, float value);\ntemplate void SkRTConfRegistry::set(const char *name, double value);\ntemplate void SkRTConfRegistry::set(const char *name, char * value);\n\nSkRTConfRegistry &skRTConfRegistry() {\n static SkRTConfRegistry r;\n return r;\n}\nFixed doParse functions\/*\n * Copyright 2013 Google Inc.\n *\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n *\/\n\n#include \"SkRTConf.h\"\n#include \"SkOSFile.h\"\n\nSkRTConfRegistry::SkRTConfRegistry(): fConfs(100) {\n\n SkFILE *fp = sk_fopen(configFileLocation(), kRead_SkFILE_Flag);\n\n if (!fp) {\n return;\n }\n\n char line[1024];\n\n while (!sk_feof(fp)) {\n\n if (!sk_fgets(line, sizeof(line), fp)) {\n break;\n }\n\n char *commentptr = strchr(line, '#');\n if (commentptr == line) {\n continue;\n }\n if (NULL != commentptr) {\n *commentptr = '\\0';\n }\n\n char sep[] = \" \\t\\r\\n\";\n\n char *keyptr = strtok(line, sep);\n if (!keyptr) {\n continue;\n }\n\n char *valptr = strtok(NULL, sep);\n if (!valptr) {\n continue;\n }\n\n SkString* key = new SkString(keyptr);\n SkString* val = new SkString(valptr);\n\n fConfigFileKeys.append(1, &key);\n fConfigFileValues.append(1, &val);\n }\n sk_fclose(fp);\n}\n\nconst char *SkRTConfRegistry::configFileLocation() const {\n return \"skia.conf\"; \/\/ for now -- should probably do something fancier like home directories or whatever.\n}\n\n\/\/ dump all known runtime config options to the file with their default values.\n\/\/ to trigger this, make a config file of zero size.\nvoid SkRTConfRegistry::possiblyDumpFile() const {\n const char *path = configFileLocation();\n SkFILE *fp = sk_fopen(path, kRead_SkFILE_Flag);\n if (!fp) {\n return;\n }\n size_t configFileSize = sk_fgetsize(fp);\n if (configFileSize == 0) {\n printAll(path);\n }\n sk_fclose(fp);\n}\n\n\/\/ Run through every provided configuration option and print a warning if the user hasn't\n\/\/ declared a correponding configuration object somewhere.\nvoid SkRTConfRegistry::validate() const {\n for (int i = 0 ; i < fConfigFileKeys.count() ; i++) {\n if (fConfs.find(fConfigFileKeys[i]->c_str())) {\n SkDebugf(\"WARNING: You have config value %s in your configuration file, but I've never heard of that.\\n\", fConfigFileKeys[i]->c_str());\n }\n }\n}\n\nvoid SkRTConfRegistry::printAll(const char *fname) const {\n SkWStream *o;\n\n if (NULL != fname) {\n o = new SkFILEWStream(fname);\n } else {\n o = new SkDebugWStream();\n }\n\n ConfMap::Iter iter(fConfs);\n SkTDArray *confArray;\n\n while (iter.next(&confArray)) {\n if (confArray->getAt(0)->isDefault()) {\n o->writeText(\"# \");\n }\n confArray->getAt(0)->print(o);\n o->newline();\n }\n\n delete o;\n}\n\nvoid SkRTConfRegistry::printNonDefault(const char *fname) const {\n SkWStream *o;\n\n if (NULL != fname) {\n o = new SkFILEWStream(fname);\n } else {\n o = new SkDebugWStream();\n }\n ConfMap::Iter iter(fConfs);\n SkTDArray *confArray;\n\n while (iter.next(&confArray)) {\n if (!confArray->getAt(0)->isDefault()) {\n confArray->getAt(0)->print(o);\n o->newline();\n }\n }\n\n delete o;\n}\n\n\/\/ register a configuration variable after its value has been set by the parser.\n\/\/ we maintain a vector of these things instead of just a single one because the\n\/\/ user might set the value after initialization time and we need to have\n\/\/ all the pointers lying around, not just one.\nvoid SkRTConfRegistry::registerConf(SkRTConfBase *conf) {\n SkTDArray *confArray;\n if (fConfs.find(conf->getName(), &confArray)) {\n if (!conf->equals(confArray->getAt(0))) {\n SkDebugf(\"WARNING: Skia config \\\"%s\\\" was registered more than once in incompatible ways.\\n\", conf->getName());\n } else {\n confArray->append(1, &conf);\n }\n } else {\n confArray = new SkTDArray;\n confArray->append(1, &conf);\n fConfs.set(conf->getName(),confArray);\n }\n}\n\ntemplate T doParse(const char *, bool *success ) {\n SkDebugf(\"WARNING: Invoked non-specialized doParse function...\\n\");\n if (success) {\n *success = false;\n }\n return (T) 0;\n}\n\ntemplate<> bool doParse(const char *s, bool *success) {\n if (success) {\n *success = true;\n }\n if (!strcmp(s,\"1\") || !strcmp(s,\"true\")) {\n return true;\n }\n if (!strcmp(s,\"0\") || !strcmp(s,\"false\")) {\n return false;\n }\n if (success) {\n *success = false;\n }\n return false;\n}\n\ntemplate<> const char * doParse(const char * s, bool *success) {\n if (success) {\n *success = true;\n }\n return s;\n}\n\ntemplate<> int doParse(const char * s, bool *success) {\n if (success) {\n *success = true;\n }\n return atoi(s);\n}\n\ntemplate<> unsigned int doParse(const char * s, bool *success) {\n if (success) {\n *success = true;\n }\n return (unsigned int) atoi(s);\n}\n\ntemplate<> float doParse(const char * s, bool *success) {\n if (success) {\n *success = true;\n }\n return (float) atof(s);\n}\n\ntemplate<> double doParse(const char * s, bool *success) {\n if (success) {\n *success = true;\n }\n return atof(s);\n}\n\nstatic inline void str_replace(char *s, char search, char replace) {\n for (char *ptr = s ; *ptr ; ptr++) {\n if (*ptr == search) {\n *ptr = replace;\n }\n }\n}\n\ntemplate bool SkRTConfRegistry::parse(const char *name, T* value) {\n SkString *str = NULL;\n\n for (int i = 0 ; i < fConfigFileKeys.count() ; i++) {\n if (fConfigFileKeys[i]->equals(name)) {\n str = fConfigFileValues[i];\n }\n }\n\n SkString environment_variable(\"skia.\");\n environment_variable.append(name);\n\n const char *environment_value = getenv(environment_variable.c_str());\n if (environment_value) {\n str->set(environment_value);\n } else {\n \/\/ apparently my shell doesn't let me have environment variables that\n \/\/ have periods in them, so also let the user substitute underscores.\n SkString underscore_environment_variable(\"skia_\");\n char *underscore_name = SkStrDup(name);\n str_replace(underscore_name,'.','_');\n underscore_environment_variable.append(underscore_name);\n sk_free(underscore_name);\n environment_value = getenv(underscore_environment_variable.c_str());\n if (environment_value) {\n str->set(environment_value);\n }\n }\n\n if (!str) {\n return false;\n }\n\n bool success;\n T new_value = doParse(str->c_str(),&success);\n if (success) {\n *value = new_value;\n } else {\n SkDebugf(\"WARNING: Couldn't parse value \\'%s\\' for variable \\'%s\\'\\n\", str->c_str(), name);\n }\n return success;\n}\n\n\/\/ need to explicitly instantiate the parsing function for every config type we might have...\n\ntemplate bool SkRTConfRegistry::parse(const char *name, bool *value);\ntemplate bool SkRTConfRegistry::parse(const char *name, int *value);\ntemplate bool SkRTConfRegistry::parse(const char *name, unsigned int *value);\ntemplate bool SkRTConfRegistry::parse(const char *name, float *value);\ntemplate bool SkRTConfRegistry::parse(const char *name, double *value);\ntemplate bool SkRTConfRegistry::parse(const char *name, const char **value);\n\ntemplate void SkRTConfRegistry::set(const char *name, T value) {\n\n SkTDArray *confArray;\n if (!fConfs.find(name, &confArray)) {\n SkDebugf(\"WARNING: Attempting to set configuration value \\\"%s\\\", but I've never heard of that.\\n\", name);\n return;\n }\n\n for (SkRTConfBase **confBase = confArray->begin(); confBase != confArray->end(); confBase++) {\n \/\/ static_cast here is okay because there's only one kind of child class.\n SkRTConf *concrete = static_cast *>(*confBase);\n\n if (concrete) {\n concrete->set(value);\n }\n }\n}\n\ntemplate void SkRTConfRegistry::set(const char *name, bool value);\ntemplate void SkRTConfRegistry::set(const char *name, int value);\ntemplate void SkRTConfRegistry::set(const char *name, unsigned int value);\ntemplate void SkRTConfRegistry::set(const char *name, float value);\ntemplate void SkRTConfRegistry::set(const char *name, double value);\ntemplate void SkRTConfRegistry::set(const char *name, char * value);\n\nSkRTConfRegistry &skRTConfRegistry() {\n static SkRTConfRegistry r;\n return r;\n}\n<|endoftext|>"} {"text":"\/\/ Fill out your copyright notice in the Description page of Project Settings.\r\n\r\n#include \"UE4_TurnBased.h\"\r\n#include \"TB_Name.h\"\r\n\r\n\/\/init static members\r\nTArray UTB_Name::MaleFirstNames = TArray();\r\nTArray UTB_Name::FemaleFirstNames = TArray();\r\nTArray UTB_Name::LastNames = TArray();\r\n\r\nvoid UTB_Name::PostInitProperties()\r\n{\r\n\tSuper::PostInitProperties();\r\n\r\n\t\/\/Load namelists if they are not already loaded\r\n\tMutex.Lock();\r\n\tif (!MaleFirstNameFile.IsEmpty() && MaleFirstNames.Num() == 0)\r\n\t{\r\n\t\tLoadNames(MaleFirstNameFile, MaleFirstNames);\r\n\t}\r\n\tif (!FemaleFirstNameFile.IsEmpty() && FemaleFirstNames.Num() == 0)\r\n\t{\r\n\t\tLoadNames(FemaleFirstNameFile, FemaleFirstNames);\r\n\t}\r\n\tif (!LastNameFile.IsEmpty() && LastNames.Num() == 0)\r\n\t{\r\n\t\tLoadNames(LastNameFile, LastNames);\r\n\t}\r\n\tMutex.Unlock();\r\n\r\n\tFGenericPlatformMath::RandInit(GetUniqueID()); \/\/ use a different seed for each thread\r\n}\r\n\r\nvoid UTB_Name::Generate_Implementation(ETB_Gender Gender)\r\n{\r\n\tswitch (Gender)\r\n\t{\r\n\tcase ETB_Gender::VE_Male:\r\n\t\tPickRandomName(MaleFirstNames, FirstName);\r\n\t\tbreak;\r\n\tcase ETB_Gender::VE_Female:\r\n\t\tPickRandomName(FemaleFirstNames, FirstName);\r\n\t\tbreak;\r\n\tcase ETB_Gender::VE_None:\r\n\t\tPickRandomName(MaleFirstNames, FirstName); \/\/i don't know.... \r\n\t\tbreak;\r\n\t};\r\n\r\n\tPickRandomName(LastNames, LastName);\r\n}\r\n\r\nFString UTB_Name::ToString()\r\n{\r\n\treturn FString::Printf(TEXT(\"%s %s\"), *FirstName, *LastName);\r\n}\r\n\r\nFText UTB_Name::ToText()\r\n{\r\n\treturn FText::FromString(ToString());\r\n}\r\n\r\nvoid UTB_Name::LoadNames(FString &NameFile, TArray &Names)\r\n{\r\n\tFString FullPath = FPaths::GameContentDir() + NameFile;\r\n\tUE_LOG(LogTemp, Log, TEXT(\"Loading names from %s\"), *FullPath);\r\n\r\n\tbool Result = FFileHelper::LoadANSITextFileToStrings(*FullPath, NULL, Names);\r\n\tif (!Result)\r\n\t{\r\n\t\tUE_LOG(LogTemp, Error, TEXT(\"Could not open %s\"), *FullPath);\r\n\t}\r\n}\r\n\r\nvoid UTB_Name::PickRandomName(TArray &NameList, FString &Name)\r\n{\r\n\tif (NameList.Num() > 0)\r\n\t{\r\n\t\tint32 RandomNumber = FGenericPlatformMath::Rand();\r\n\t\tName = NameList[RandomNumber % NameList.Num()];\r\n\t}\r\n}use TB_Log when logging\/\/ Fill out your copyright notice in the Description page of Project Settings.\r\n\r\n#include \"UE4_TurnBased.h\"\r\n#include \"TB_Name.h\"\r\n\r\n\/\/init static members\r\nTArray UTB_Name::MaleFirstNames = TArray();\r\nTArray UTB_Name::FemaleFirstNames = TArray();\r\nTArray UTB_Name::LastNames = TArray();\r\n\r\nvoid UTB_Name::PostInitProperties()\r\n{\r\n\tSuper::PostInitProperties();\r\n\r\n\t\/\/Load namelists if they are not already loaded\r\n\tMutex.Lock();\r\n\tif (!MaleFirstNameFile.IsEmpty() && MaleFirstNames.Num() == 0)\r\n\t{\r\n\t\tLoadNames(MaleFirstNameFile, MaleFirstNames);\r\n\t}\r\n\tif (!FemaleFirstNameFile.IsEmpty() && FemaleFirstNames.Num() == 0)\r\n\t{\r\n\t\tLoadNames(FemaleFirstNameFile, FemaleFirstNames);\r\n\t}\r\n\tif (!LastNameFile.IsEmpty() && LastNames.Num() == 0)\r\n\t{\r\n\t\tLoadNames(LastNameFile, LastNames);\r\n\t}\r\n\tMutex.Unlock();\r\n\r\n\tFGenericPlatformMath::RandInit(GetUniqueID()); \/\/ use a different seed for each thread\r\n}\r\n\r\nvoid UTB_Name::Generate_Implementation(ETB_Gender Gender)\r\n{\r\n\tswitch (Gender)\r\n\t{\r\n\tcase ETB_Gender::VE_Male:\r\n\t\tPickRandomName(MaleFirstNames, FirstName);\r\n\t\tbreak;\r\n\tcase ETB_Gender::VE_Female:\r\n\t\tPickRandomName(FemaleFirstNames, FirstName);\r\n\t\tbreak;\r\n\tcase ETB_Gender::VE_None:\r\n\t\tPickRandomName(MaleFirstNames, FirstName); \/\/i don't know.... \r\n\t\tbreak;\r\n\t};\r\n\r\n\tPickRandomName(LastNames, LastName);\r\n}\r\n\r\nFString UTB_Name::ToString()\r\n{\r\n\treturn FString::Printf(TEXT(\"%s %s\"), *FirstName, *LastName);\r\n}\r\n\r\nFText UTB_Name::ToText()\r\n{\r\n\treturn FText::FromString(ToString());\r\n}\r\n\r\nvoid UTB_Name::LoadNames(FString &NameFile, TArray &Names)\r\n{\r\n\tFString FullPath = FPaths::GameContentDir() + NameFile;\r\n\tUE_LOG(TB_Log, Log, TEXT(\"Loading names from %s\"), *FullPath);\r\n\r\n\tbool Result = FFileHelper::LoadANSITextFileToStrings(*FullPath, NULL, Names);\r\n\tif (!Result)\r\n\t{\r\n\t\tUE_LOG(TB_Log, Error, TEXT(\"Could not open %s\"), *FullPath);\r\n\t}\r\n}\r\n\r\nvoid UTB_Name::PickRandomName(TArray &NameList, FString &Name)\r\n{\r\n\tif (NameList.Num() > 0)\r\n\t{\r\n\t\tint32 RandomNumber = FGenericPlatformMath::Rand();\r\n\t\tName = NameList[RandomNumber % NameList.Num()];\r\n\t}\r\n}<|endoftext|>"} {"text":"\/*\n * Copyright 2012 Bram van der Kroef\n *\n * This file is part of LESS CSS Compiler.\n *\n * LESS CSS Compiler is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * LESS CSS Compiler is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with LESS CSS Compiler. If not, see . \n *\n * Author: Bram van der Kroef \n *\/\n\n#include \"UrlValue.h\"\n\n#include \n\n#ifdef WITH_LIBPNG\n#include \n#endif\n\n#ifdef WITH_LIBJPEG\n#include \n#include \n\nstruct urlvalue_jpeg_error_mgr {\n struct jpeg_error_mgr pub;\t\/* \"public\" fields *\/\n\n jmp_buf setjmp_buffer;\t\/* for return to caller *\/\n};\n\ntypedef struct urlvalue_jpeg_error_mgr * urlvalue_jpeg_error_ptr;\n\nMETHODDEF(void)\nurlvalue_jpeg_error_exit (j_common_ptr cinfo)\n{\n \/* cinfo->err really points to a my_error_mgr struct, so coerce pointer *\/\n urlvalue_jpeg_error_ptr myerr = (urlvalue_jpeg_error_ptr) cinfo->err;\n\n \/* Always display the message. *\/\n \/* We could postpone this until after returning, if we chose. *\/\n (*cinfo->err->output_message) (cinfo);\n\n \/* Return control to the setjmp point *\/\n longjmp(myerr->setjmp_buffer, 1);\n}\n\n#endif\n\nUrlValue::UrlValue(Token* token, string path): Value() {\n tokens.push(token);\n this->path = path;\n type = Value::URL;\n loaded = false;\n}\n\n\nUrlValue::~UrlValue() {\n}\n\nValue* UrlValue::add(Value* v) {\n (void)v;\n throw new ValueException(\"You can not add images.\");\n}\nValue* UrlValue::substract(Value* v) {\n (void)v;\n throw new ValueException(\"You can not substract images.\");\n}\nValue* UrlValue::multiply(Value* v) {\n (void)v;\n throw new ValueException(\"You can not multiply images.\");\n}\nValue* UrlValue::divide(Value* v) {\n (void)v;\n throw new ValueException(\"You can not divide images.\");\n}\nint UrlValue::compare(Value* v) {\n if (v->type == URL) {\n return 0;\n } else {\n throw new ValueException(\"You can only compare images with images.\");\n }\n}\n\nbool UrlValue::loadImg() {\n loaded = loadPng() || loadJpeg();\n \n return loaded;\n}\n\nbool UrlValue::loadPng() {\n if (loaded != false)\n return true;\n\n#ifdef WITH_LIBPNG\n unsigned char header[8]; \/\/ 8 is the maximum size that can be checked\n \/* open file and test for it being a png *\/\n \n png_structp png_ptr;\n png_infop info_ptr;\n\n FILE *fp = fopen(path.c_str(), \"rb\");\n if (!fp)\n return false; \/\/\"Image file could not be opened\"\n\n fread(header, 1, 8, fp);\n if (png_sig_cmp(header, 0, 8))\n return false; \/\/\"Image is not a PNG file\"\n \n \/* initialize stuff *\/\n png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);\n\n if (!png_ptr)\n throw new ValueException(\"png_create_read_struct failed\");\n\n info_ptr = png_create_info_struct(png_ptr);\n if (!info_ptr)\n throw new ValueException(\"png_create_info_struct failed\");\n\n if (setjmp(png_jmpbuf(png_ptr)))\n throw new ValueException(\"Error during init_io\");\n\n png_init_io(png_ptr, fp);\n png_set_sig_bytes(png_ptr, 8);\n\n png_read_info(png_ptr, info_ptr);\n\n width = png_get_image_width(png_ptr, info_ptr);\n height = png_get_image_height(png_ptr, info_ptr);\n\n fclose(fp);\n return true;\n \n#else\n return false;\n#endif \n}\n\n\nbool UrlValue::loadJpeg() {\n if (loaded != false)\n return true;\n \n#ifdef WITH_LIBJPEG\n struct jpeg_decompress_struct cinfo;\n \n struct urlvalue_jpeg_error_mgr jerr;\n \/* More stuff *\/\n FILE * infile;\n JSAMPARRAY buffer;\t\/* Output row buffer *\/\n int row_stride;\t\/* physical row width in output buffer *\/\n \n if ((infile = fopen(path.c_str(), \"rb\")) == NULL) {\n return false;\n }\n\n \/* Step 1: allocate and initialize JPEG decompression object *\/\n\n \/* We set up the normal JPEG error routines, then override error_exit. *\/\n cinfo.err = jpeg_std_error(&jerr.pub);\n jerr.pub.error_exit = urlvalue_jpeg_error_exit;\n \/* Establish the setjmp return context for urlvalue_jpeg_error_exit to use. *\/\n if (setjmp(jerr.setjmp_buffer)) {\n \/* If we get here, the JPEG code has signaled an error.\n * We need to clean up the JPEG object, close the input file, and return.\n *\/\n jpeg_destroy_decompress(&cinfo);\n fclose(infile);\n return false;\n }\n \/* Now we can initialize the JPEG decompression object. *\/\n jpeg_create_decompress(&cinfo);\n\n \/* Step 2: specify data source (eg, a file) *\/\n\n jpeg_stdio_src(&cinfo, infile);\n\n \/* Step 3: read file parameters with jpeg_read_header() *\/\n\n (void) jpeg_read_header(&cinfo, TRUE);\n \/* We can ignore the return value from jpeg_read_header since\n * (a) suspension is not possible with the stdio data source, and\n * (b) we passed TRUE to reject a tables-only JPEG file as an error.\n * See libjpeg.txt for more info.\n *\/\n\n \/* Step 4: set parameters for decompression *\/\n\n \/* In this example, we don't need to change any of the defaults set by\n * jpeg_read_header(), so we do nothing here.\n *\/\n\n \/* Step 5: Start decompressor *\/\n\n (void) jpeg_start_decompress(&cinfo);\n \/* We can ignore the return value since suspension is not possible\n * with the stdio data source.\n *\/\n\n width = cinfo.output_width;\n height = cinfo.output_height;\n \n \/* We may need to do some setup of our own at this point before reading\n * the data. After jpeg_start_decompress() we have the correct scaled\n * output image dimensions available, as well as the output colormap\n * if we asked for color quantization.\n * In this example, we need to make an output work buffer of the right size.\n *\/\n \/* JSAMPLEs per row in output buffer *\/\n row_stride = cinfo.output_width * cinfo.output_components;\n \/* Make a one-row-high sample array that will go away when done with image *\/\n buffer = (*cinfo.mem->alloc_sarray)\n ((j_common_ptr) &cinfo, JPOOL_IMAGE, row_stride, 1);\n\n \/* Step 6: while (scan lines remain to be read) *\/\n \/* jpeg_read_scanlines(...); *\/\n\n \/* Here we use the library's state variable cinfo.output_scanline as the\n * loop counter, so that we don't have to keep track ourselves.\n *\/\n while (cinfo.output_scanline < cinfo.output_height) {\n \/* jpeg_read_scanlines expects an array of pointers to scanlines.\n * Here the array is only one element long, but you could ask for\n * more than one scanline at a time if that's more convenient.\n *\/\n (void) jpeg_read_scanlines(&cinfo, buffer, 1);\n \/* Assume put_scanline_someplace wants a pointer and sample count. *\/\n \/\/put_scanline_someplace(buffer[0], row_stride);\n }\n\n \/* Step 7: Finish decompression *\/\n\n (void) jpeg_finish_decompress(&cinfo);\n \/* We can ignore the return value since suspension is not possible\n * with the stdio data source.\n *\/\n\n \/* Step 8: Release JPEG decompression object *\/\n\n \/* This is an important step since it will release a good deal of memory. *\/\n jpeg_destroy_decompress(&cinfo);\n\n \/* After finish_decompress, we can close the input file.\n * Here we postpone it until after no more JPEG errors are possible,\n * so as to simplify the setjmp error logic above. (Actually, I don't\n * think that jpeg_destroy can do an error exit, but why assume anything...)\n *\/\n fclose(infile);\n return true;\n#else\n return false;\n#endif\n}\n\nunsigned int UrlValue::getImageWidth() {\n return (loadImg() ? width : 0);\n}\nunsigned int UrlValue::getImageHeight() {\n return (loadImg() ? height : 0);\n}\n\nvoid UrlValue::loadFunctions(FunctionLibrary* lib) {\n lib->push(\"imgheight\", \"R\", &UrlValue::imgheight);\n lib->push(\"imgwidth\", \"R\", &UrlValue::imgwidth);\n}\n\n\nValue* UrlValue::imgheight(vector arguments) {\n NumberValue* val = new NumberValue(new Token(\"1\", Token::NUMBER));\n val->setValue(((UrlValue*)arguments[0])->getImageHeight());\n val->setUnit(\"px\");\n return val;\n}\nValue* UrlValue::imgwidth(vector arguments) {\n NumberValue* val = new NumberValue(new Token(\"1\", Token::NUMBER));\n \n val->setUnit(\"px\");\n val->setValue((double)((UrlValue*)arguments[0])->getImageWidth());\n return val;\n}\nInclude stdio.h. It was sneaking in through png.h If you .\/configure --without-libpng then stdio.h was not getting pulled in, but is required in the jpeg code. Ensure it comes in.\/*\n * Copyright 2012 Bram van der Kroef\n *\n * This file is part of LESS CSS Compiler.\n *\n * LESS CSS Compiler is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * LESS CSS Compiler is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with LESS CSS Compiler. If not, see . \n *\n * Author: Bram van der Kroef \n *\/\n\n#include \"UrlValue.h\"\n\n#include \n\n#ifdef WITH_LIBPNG\n#include \n#endif\n\n#ifdef WITH_LIBJPEG\n#include \n#include \n#include \n\nstruct urlvalue_jpeg_error_mgr {\n struct jpeg_error_mgr pub;\t\/* \"public\" fields *\/\n\n jmp_buf setjmp_buffer;\t\/* for return to caller *\/\n};\n\ntypedef struct urlvalue_jpeg_error_mgr * urlvalue_jpeg_error_ptr;\n\nMETHODDEF(void)\nurlvalue_jpeg_error_exit (j_common_ptr cinfo)\n{\n \/* cinfo->err really points to a my_error_mgr struct, so coerce pointer *\/\n urlvalue_jpeg_error_ptr myerr = (urlvalue_jpeg_error_ptr) cinfo->err;\n\n \/* Always display the message. *\/\n \/* We could postpone this until after returning, if we chose. *\/\n (*cinfo->err->output_message) (cinfo);\n\n \/* Return control to the setjmp point *\/\n longjmp(myerr->setjmp_buffer, 1);\n}\n\n#endif\n\nUrlValue::UrlValue(Token* token, string path): Value() {\n tokens.push(token);\n this->path = path;\n type = Value::URL;\n loaded = false;\n}\n\n\nUrlValue::~UrlValue() {\n}\n\nValue* UrlValue::add(Value* v) {\n (void)v;\n throw new ValueException(\"You can not add images.\");\n}\nValue* UrlValue::substract(Value* v) {\n (void)v;\n throw new ValueException(\"You can not substract images.\");\n}\nValue* UrlValue::multiply(Value* v) {\n (void)v;\n throw new ValueException(\"You can not multiply images.\");\n}\nValue* UrlValue::divide(Value* v) {\n (void)v;\n throw new ValueException(\"You can not divide images.\");\n}\nint UrlValue::compare(Value* v) {\n if (v->type == URL) {\n return 0;\n } else {\n throw new ValueException(\"You can only compare images with images.\");\n }\n}\n\nbool UrlValue::loadImg() {\n loaded = loadPng() || loadJpeg();\n \n return loaded;\n}\n\nbool UrlValue::loadPng() {\n if (loaded != false)\n return true;\n\n#ifdef WITH_LIBPNG\n unsigned char header[8]; \/\/ 8 is the maximum size that can be checked\n \/* open file and test for it being a png *\/\n \n png_structp png_ptr;\n png_infop info_ptr;\n\n FILE *fp = fopen(path.c_str(), \"rb\");\n if (!fp)\n return false; \/\/\"Image file could not be opened\"\n\n fread(header, 1, 8, fp);\n if (png_sig_cmp(header, 0, 8))\n return false; \/\/\"Image is not a PNG file\"\n \n \/* initialize stuff *\/\n png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);\n\n if (!png_ptr)\n throw new ValueException(\"png_create_read_struct failed\");\n\n info_ptr = png_create_info_struct(png_ptr);\n if (!info_ptr)\n throw new ValueException(\"png_create_info_struct failed\");\n\n if (setjmp(png_jmpbuf(png_ptr)))\n throw new ValueException(\"Error during init_io\");\n\n png_init_io(png_ptr, fp);\n png_set_sig_bytes(png_ptr, 8);\n\n png_read_info(png_ptr, info_ptr);\n\n width = png_get_image_width(png_ptr, info_ptr);\n height = png_get_image_height(png_ptr, info_ptr);\n\n fclose(fp);\n return true;\n \n#else\n return false;\n#endif \n}\n\n\nbool UrlValue::loadJpeg() {\n if (loaded != false)\n return true;\n \n#ifdef WITH_LIBJPEG\n struct jpeg_decompress_struct cinfo;\n \n struct urlvalue_jpeg_error_mgr jerr;\n \/* More stuff *\/\n FILE * infile;\n JSAMPARRAY buffer;\t\/* Output row buffer *\/\n int row_stride;\t\/* physical row width in output buffer *\/\n \n if ((infile = fopen(path.c_str(), \"rb\")) == NULL) {\n return false;\n }\n\n \/* Step 1: allocate and initialize JPEG decompression object *\/\n\n \/* We set up the normal JPEG error routines, then override error_exit. *\/\n cinfo.err = jpeg_std_error(&jerr.pub);\n jerr.pub.error_exit = urlvalue_jpeg_error_exit;\n \/* Establish the setjmp return context for urlvalue_jpeg_error_exit to use. *\/\n if (setjmp(jerr.setjmp_buffer)) {\n \/* If we get here, the JPEG code has signaled an error.\n * We need to clean up the JPEG object, close the input file, and return.\n *\/\n jpeg_destroy_decompress(&cinfo);\n fclose(infile);\n return false;\n }\n \/* Now we can initialize the JPEG decompression object. *\/\n jpeg_create_decompress(&cinfo);\n\n \/* Step 2: specify data source (eg, a file) *\/\n\n jpeg_stdio_src(&cinfo, infile);\n\n \/* Step 3: read file parameters with jpeg_read_header() *\/\n\n (void) jpeg_read_header(&cinfo, TRUE);\n \/* We can ignore the return value from jpeg_read_header since\n * (a) suspension is not possible with the stdio data source, and\n * (b) we passed TRUE to reject a tables-only JPEG file as an error.\n * See libjpeg.txt for more info.\n *\/\n\n \/* Step 4: set parameters for decompression *\/\n\n \/* In this example, we don't need to change any of the defaults set by\n * jpeg_read_header(), so we do nothing here.\n *\/\n\n \/* Step 5: Start decompressor *\/\n\n (void) jpeg_start_decompress(&cinfo);\n \/* We can ignore the return value since suspension is not possible\n * with the stdio data source.\n *\/\n\n width = cinfo.output_width;\n height = cinfo.output_height;\n \n \/* We may need to do some setup of our own at this point before reading\n * the data. After jpeg_start_decompress() we have the correct scaled\n * output image dimensions available, as well as the output colormap\n * if we asked for color quantization.\n * In this example, we need to make an output work buffer of the right size.\n *\/\n \/* JSAMPLEs per row in output buffer *\/\n row_stride = cinfo.output_width * cinfo.output_components;\n \/* Make a one-row-high sample array that will go away when done with image *\/\n buffer = (*cinfo.mem->alloc_sarray)\n ((j_common_ptr) &cinfo, JPOOL_IMAGE, row_stride, 1);\n\n \/* Step 6: while (scan lines remain to be read) *\/\n \/* jpeg_read_scanlines(...); *\/\n\n \/* Here we use the library's state variable cinfo.output_scanline as the\n * loop counter, so that we don't have to keep track ourselves.\n *\/\n while (cinfo.output_scanline < cinfo.output_height) {\n \/* jpeg_read_scanlines expects an array of pointers to scanlines.\n * Here the array is only one element long, but you could ask for\n * more than one scanline at a time if that's more convenient.\n *\/\n (void) jpeg_read_scanlines(&cinfo, buffer, 1);\n \/* Assume put_scanline_someplace wants a pointer and sample count. *\/\n \/\/put_scanline_someplace(buffer[0], row_stride);\n }\n\n \/* Step 7: Finish decompression *\/\n\n (void) jpeg_finish_decompress(&cinfo);\n \/* We can ignore the return value since suspension is not possible\n * with the stdio data source.\n *\/\n\n \/* Step 8: Release JPEG decompression object *\/\n\n \/* This is an important step since it will release a good deal of memory. *\/\n jpeg_destroy_decompress(&cinfo);\n\n \/* After finish_decompress, we can close the input file.\n * Here we postpone it until after no more JPEG errors are possible,\n * so as to simplify the setjmp error logic above. (Actually, I don't\n * think that jpeg_destroy can do an error exit, but why assume anything...)\n *\/\n fclose(infile);\n return true;\n#else\n return false;\n#endif\n}\n\nunsigned int UrlValue::getImageWidth() {\n return (loadImg() ? width : 0);\n}\nunsigned int UrlValue::getImageHeight() {\n return (loadImg() ? height : 0);\n}\n\nvoid UrlValue::loadFunctions(FunctionLibrary* lib) {\n lib->push(\"imgheight\", \"R\", &UrlValue::imgheight);\n lib->push(\"imgwidth\", \"R\", &UrlValue::imgwidth);\n}\n\n\nValue* UrlValue::imgheight(vector arguments) {\n NumberValue* val = new NumberValue(new Token(\"1\", Token::NUMBER));\n val->setValue(((UrlValue*)arguments[0])->getImageHeight());\n val->setUnit(\"px\");\n return val;\n}\nValue* UrlValue::imgwidth(vector arguments) {\n NumberValue* val = new NumberValue(new Token(\"1\", Token::NUMBER));\n \n val->setUnit(\"px\");\n val->setValue((double)((UrlValue*)arguments[0])->getImageWidth());\n return val;\n}\n<|endoftext|>"} {"text":"\/****************************************************************************\n **\n ** This file is part of the CAMP library.\n **\n ** The MIT License (MIT)\n **\n ** Copyright (C) 2009-2010 TECHNOGERMA Systems France and\/or its subsidiary(-ies).\n ** Contact: Technogerma Systems France Information (contact@technogerma.fr)\n **\n ** Permission is hereby granted, free of charge, to any person obtaining a copy\n ** of this software and associated documentation files (the \"Software\"), to deal\n ** in the Software without restriction, including without limitation the rights\n ** to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n ** copies of the Software, and to permit persons to whom the Software is\n ** furnished to do so, subject to the following conditions:\n **\n ** The above copyright notice and this permission notice shall be included in\n ** all copies or substantial portions of the Software.\n **\n ** THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n ** IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n ** FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n ** AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n ** LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n ** OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n ** THE SOFTWARE.\n **\n ****************************************************************************\/\n\n#include \"traits.hpp\"\n#include \n#include \n#include \n\n\nstatic void foo() {}\n\nstatic int bar(float) {return 0;}\n\nstruct Callable {\n void operator () () {}\n};\n\nstruct NonCallable {\n int x;\n};\n\nstruct Methods\n{\n void foo() {}\n};\n\nint intArray[10];\n\nusing namespace TraitsTest;\n\n\/\/-----------------------------------------------------------------------------\n\/\/ Tests for camp::*traits\n\/\/-----------------------------------------------------------------------------\nBOOST_AUTO_TEST_SUITE(TRAITS)\n\n\/\/ Sanity check: C++11 features and syntax.\nBOOST_AUTO_TEST_CASE(cpp11)\n{\n foo(); bar(0.f); \/\/ to stop warning\n \n static_assert(std::is_function::value, \"std::is_function failed\");\n static_assert(std::is_function::value, \"std::is_function failed\");\n static_assert(!std::is_function::value, \"std::is_function failed\");\n static_assert(!std::is_function::value, \"std::is_function failed\");\n \n typedef void (*foo_t)();\n static_assert(std::is_void< std::result_of::type >::value, \"std::result_of failed\");\n static_assert(std::is_void< std::result_of::type >::value, \"std::result_of failed\");\n static_assert(std::is_void< std::result_of::type >::value, \"std::result_of failed\");\n \n typedef int (*bar_t)(float);\n static_assert(std::is_same< std::result_of::type, int >::value, \"std::result_of failed\");\n static_assert(std::is_same< std::result_of::type, int >::value, \"std::result_of failed\");\n static_assert(std::is_same< std::result_of::type, int >::value, \"std::result_of failed\");\n}\n\n\/\/-----------------------------------------------------------------------------\nBOOST_AUTO_TEST_CASE(functionTraits)\n{\n static_assert( ! camp::detail::FunctionTraits::isFunction, \"FunctionTraits<>::isFunction failed\");\n static_assert( ! camp::detail::FunctionTraits::isFunction, \"FunctionTraits<>::isFunction failed\");\n static_assert( ! camp::detail::FunctionTraits::isFunction, \"FunctionTraits<>::isFunction failed\");\n static_assert( ! camp::detail::FunctionTraits::isFunction, \"FunctionTraits<>::isFunction failed\");\n static_assert( ! camp::detail::FunctionTraits::isFunction, \"FunctionTraits<>::isFunction failed\");\n static_assert( ! camp::detail::FunctionTraits::isFunction, \"FunctionTraits<>::isFunction failed\");\n \n static_assert(camp::detail::FunctionTraits::isFunction, \"FunctionTraits<>::isFunction failed\");\n static_assert(camp::detail::FunctionTraits::isFunction, \"FunctionTraits<>::isFunction failed\");\n static_assert(camp::detail::FunctionTraits::isFunction, \"FunctionTraits<>::isFunction failed\");\n static_assert(camp::detail::FunctionTraits::isFunction, \"FunctionTraits<>::isFunction failed\");\n\n static_assert(camp::detail::FunctionTraits::isFunction, \"FunctionTraits<>::isFunction failed\");\n static_assert(camp::detail::FunctionTraits::isFunction, \"FunctionTraits<>::isFunction failed\");\n\n static_assert( ! camp::detail::FunctionTraits::isFunction, \"FunctionTraits<>::isFunction failed\");\n \/\/ Only reports: function and pointer-to-member types & functors\n static_assert( ! camp::detail::FunctionTraits::isFunction, \"FunctionTraits<>::isFunction failed\");\n\n static_assert(camp::detail::FunctionTraits::isFunction, \"FunctionTraits<>::isFunction failed\");\n void (Methods::*meth_t)() = &Methods::foo;\n static_assert(camp::detail::FunctionTraits::isFunction, \"FunctionTraits<>::isFunction failed\");\n}\n\n\/\/-----------------------------------------------------------------------------\nBOOST_AUTO_TEST_CASE(objectTraits_writable)\n{\n \/\/ is writable\n static_assert(camp::detail::ObjectTraits::isWritable, \"ObjectTraits<>::isWriteable failed\");\n static_assert(camp::detail::ObjectTraits::isWritable, \"ObjectTraits<>::isWriteable failed\");\n\n \/\/ is not writable\n static_assert( ! camp::detail::ObjectTraits::isWritable, \"ObjectTraits<>::isWriteable failed\");\n static_assert( ! camp::detail::ObjectTraits::isWritable, \"ObjectTraits<>::isWriteable failed\");\n static_assert( ! camp::detail::ObjectTraits::isWritable, \"ObjectTraits<>::isWriteable failed\");\n static_assert( ! camp::detail::ObjectTraits::isRef, \"ObjectTraits<>::isRef failed\");\n static_assert( ! camp::detail::ObjectTraits::isWritable, \"ObjectTraits<>::isWriteable failed\");\n}\n\n\/\/-----------------------------------------------------------------------------\nBOOST_AUTO_TEST_CASE(objectTraits_ref)\n{\n \/\/ is ref\n static_assert(camp::detail::ObjectTraits::isRef, \"ObjectTraits<>::isRef failed\");\n static_assert(camp::detail::ObjectTraits::isRef, \"ObjectTraits<>::isRef failed\");\n static_assert(camp::detail::ObjectTraits::isRef, \"ObjectTraits<>::isRef failed\");\n \n \/\/ is not ref\n static_assert( ! camp::detail::ObjectTraits::isRef, \"ObjectTraits<>::isRef failed\");\n static_assert( ! camp::detail::ObjectTraits::isRef, \"ObjectTraits<>::isRef failed\");\n static_assert( ! camp::detail::ObjectTraits::isRef, \"ObjectTraits<>::isRef failed\");\n}\n\n\/\/-----------------------------------------------------------------------------\nBOOST_AUTO_TEST_CASE(objectTraits_refReturnType)\n{\n static_assert(std::is_same::RefReturnType>::value, \"ObjectTraits<>::RefReturnType failed\");\n static_assert(std::is_same::RefReturnType>::value, \"ObjectTraits<>::RefReturnType failed\");\n \n \/\/ ref return\n static_assert(std::is_same::RefReturnType>::value, \"ObjectTraits<>::RefReturnType failed\");\n static_assert(std::is_same::RefReturnType>::value, \"ObjectTraits<>::RefReturnType failed\");\n}\n\n\/\/-----------------------------------------------------------------------------\nBOOST_AUTO_TEST_CASE(objectTraits_pointerType)\n{\n \/\/ pointer type\n static_assert(std::is_same::PointerType>::value, \"ObjectTraits<>::PointerType failed\");\n static_assert(std::is_same::PointerType>::value, \"ObjectTraits<>::PointerType failed\");\n}\n\n\/\/-----------------------------------------------------------------------------\nBOOST_AUTO_TEST_CASE(objectTraits_dataType)\n{\n static_assert(std::is_same::DataType>::value, \"ObjectTraits<>::DataType failed\");\n static_assert(std::is_same::DataType>::value, \"ObjectTraits<>::DataType failed\");\n static_assert(std::is_same::DataType>::value, \"ObjectTraits<>::DataType failed\");\n static_assert(std::is_same::DataType>::value, \"ObjectTraits<>::DataType failed\");\n static_assert(std::is_same::DataType>::value, \"ObjectTraits<>::DataType failed\");\n static_assert(std::is_same::DataType>::value, \"ObjectTraits<>::DataType failed\");\n}\n\nBOOST_AUTO_TEST_SUITE_END()\nBoost function sanity units tests.\/****************************************************************************\n **\n ** This file is part of the CAMP library.\n **\n ** The MIT License (MIT)\n **\n ** Copyright (C) 2009-2010 TECHNOGERMA Systems France and\/or its subsidiary(-ies).\n ** Contact: Technogerma Systems France Information (contact@technogerma.fr)\n **\n ** Permission is hereby granted, free of charge, to any person obtaining a copy\n ** of this software and associated documentation files (the \"Software\"), to deal\n ** in the Software without restriction, including without limitation the rights\n ** to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n ** copies of the Software, and to permit persons to whom the Software is\n ** furnished to do so, subject to the following conditions:\n **\n ** The above copyright notice and this permission notice shall be included in\n ** all copies or substantial portions of the Software.\n **\n ** THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n ** IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n ** FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n ** AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n ** LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n ** OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n ** THE SOFTWARE.\n **\n ****************************************************************************\/\n\n#include \"traits.hpp\"\n#include \n#include \n#include \n#include \n\n\nstatic void foo() {}\n\nstatic int bar(float) {return 0;}\n\nstruct Callable {\n void operator () () {}\n};\n\nstruct NonCallable {\n int x;\n};\n\nstruct Methods\n{\n void foo() {}\n};\n\nint intArray[10];\n\nusing namespace TraitsTest;\n\n\/\/-----------------------------------------------------------------------------\n\/\/ Tests for camp::*traits\n\/\/-----------------------------------------------------------------------------\nBOOST_AUTO_TEST_SUITE(TRAITS)\n\n\/\/ Sanity check: C++11 features and syntax.\nBOOST_AUTO_TEST_CASE(cpp11)\n{\n foo(); bar(0.f); \/\/ to stop warning\n \n static_assert(std::is_function::value, \"std::is_function failed\");\n static_assert(std::is_function::value, \"std::is_function failed\");\n static_assert(!std::is_function::value, \"std::is_function failed\");\n static_assert(!std::is_function::value, \"std::is_function failed\");\n \n typedef void (*foo_t)();\n static_assert(std::is_void< std::result_of::type >::value, \"std::result_of failed\");\n static_assert(std::is_void< std::result_of::type >::value, \"std::result_of failed\");\n static_assert(std::is_void< std::result_of::type >::value, \"std::result_of failed\");\n \n typedef int (*bar_t)(float);\n static_assert(std::is_same< std::result_of::type, int >::value, \"std::result_of failed\");\n static_assert(std::is_same< std::result_of::type, int >::value, \"std::result_of failed\");\n static_assert(std::is_same< std::result_of::type, int >::value, \"std::result_of failed\");\n}\n\n\/\/-----------------------------------------------------------------------------\nBOOST_AUTO_TEST_CASE(functionTraits)\n{\n static_assert( ! camp::detail::FunctionTraits::isFunction, \"FunctionTraits<>::isFunction failed\");\n static_assert( ! camp::detail::FunctionTraits::isFunction, \"FunctionTraits<>::isFunction failed\");\n static_assert( ! camp::detail::FunctionTraits::isFunction, \"FunctionTraits<>::isFunction failed\");\n static_assert( ! camp::detail::FunctionTraits::isFunction, \"FunctionTraits<>::isFunction failed\");\n static_assert( ! camp::detail::FunctionTraits::isFunction, \"FunctionTraits<>::isFunction failed\");\n static_assert( ! camp::detail::FunctionTraits::isFunction, \"FunctionTraits<>::isFunction failed\");\n \n static_assert(camp::detail::FunctionTraits::isFunction, \"FunctionTraits<>::isFunction failed\");\n static_assert(camp::detail::FunctionTraits::isFunction, \"FunctionTraits<>::isFunction failed\");\n static_assert(camp::detail::FunctionTraits::isFunction, \"FunctionTraits<>::isFunction failed\");\n static_assert(camp::detail::FunctionTraits::isFunction, \"FunctionTraits<>::isFunction failed\");\n\n static_assert(camp::detail::FunctionTraits::isFunction, \"FunctionTraits<>::isFunction failed\");\n static_assert(camp::detail::FunctionTraits::isFunction, \"FunctionTraits<>::isFunction failed\");\n\n static_assert( ! camp::detail::FunctionTraits::isFunction, \"FunctionTraits<>::isFunction failed\");\n \/\/ Only reports: function and pointer-to-member types & functors\n static_assert( ! camp::detail::FunctionTraits::isFunction, \"FunctionTraits<>::isFunction failed\");\n\n static_assert(camp::detail::FunctionTraits::isFunction, \"FunctionTraits<>::isFunction failed\");\n void (Methods::*meth_t)() = &Methods::foo;\n static_assert(camp::detail::FunctionTraits::isFunction, \"FunctionTraits<>::isFunction failed\");\n}\n\n\/\/-----------------------------------------------------------------------------\nBOOST_AUTO_TEST_CASE(objectTraits_writable)\n{\n \/\/ is writable\n static_assert(camp::detail::ObjectTraits::isWritable, \"ObjectTraits<>::isWriteable failed\");\n static_assert(camp::detail::ObjectTraits::isWritable, \"ObjectTraits<>::isWriteable failed\");\n\n \/\/ is not writable\n static_assert( ! camp::detail::ObjectTraits::isWritable, \"ObjectTraits<>::isWriteable failed\");\n static_assert( ! camp::detail::ObjectTraits::isWritable, \"ObjectTraits<>::isWriteable failed\");\n static_assert( ! camp::detail::ObjectTraits::isWritable, \"ObjectTraits<>::isWriteable failed\");\n static_assert( ! camp::detail::ObjectTraits::isRef, \"ObjectTraits<>::isRef failed\");\n static_assert( ! camp::detail::ObjectTraits::isWritable, \"ObjectTraits<>::isWriteable failed\");\n}\n\n\/\/-----------------------------------------------------------------------------\nBOOST_AUTO_TEST_CASE(objectTraits_ref)\n{\n \/\/ is ref\n static_assert(camp::detail::ObjectTraits::isRef, \"ObjectTraits<>::isRef failed\");\n static_assert(camp::detail::ObjectTraits::isRef, \"ObjectTraits<>::isRef failed\");\n static_assert(camp::detail::ObjectTraits::isRef, \"ObjectTraits<>::isRef failed\");\n \n \/\/ is not ref\n static_assert( ! camp::detail::ObjectTraits::isRef, \"ObjectTraits<>::isRef failed\");\n static_assert( ! camp::detail::ObjectTraits::isRef, \"ObjectTraits<>::isRef failed\");\n static_assert( ! camp::detail::ObjectTraits::isRef, \"ObjectTraits<>::isRef failed\");\n}\n\n\/\/-----------------------------------------------------------------------------\nBOOST_AUTO_TEST_CASE(objectTraits_refReturnType)\n{\n static_assert(std::is_same::RefReturnType>::value, \"ObjectTraits<>::RefReturnType failed\");\n static_assert(std::is_same::RefReturnType>::value, \"ObjectTraits<>::RefReturnType failed\");\n \n \/\/ ref return\n static_assert(std::is_same::RefReturnType>::value, \"ObjectTraits<>::RefReturnType failed\");\n static_assert(std::is_same::RefReturnType>::value, \"ObjectTraits<>::RefReturnType failed\");\n}\n\n\/\/-----------------------------------------------------------------------------\nBOOST_AUTO_TEST_CASE(objectTraits_pointerType)\n{\n \/\/ pointer type\n static_assert(std::is_same::PointerType>::value, \"ObjectTraits<>::PointerType failed\");\n static_assert(std::is_same::PointerType>::value, \"ObjectTraits<>::PointerType failed\");\n}\n\n\/\/-----------------------------------------------------------------------------\nBOOST_AUTO_TEST_CASE(objectTraits_dataType)\n{\n static_assert(std::is_same::DataType>::value, \"ObjectTraits<>::DataType failed\");\n static_assert(std::is_same::DataType>::value, \"ObjectTraits<>::DataType failed\");\n static_assert(std::is_same::DataType>::value, \"ObjectTraits<>::DataType failed\");\n static_assert(std::is_same::DataType>::value, \"ObjectTraits<>::DataType failed\");\n static_assert(std::is_same::DataType>::value, \"ObjectTraits<>::DataType failed\");\n static_assert(std::is_same::DataType>::value, \"ObjectTraits<>::DataType failed\");\n}\n\n\/\/-----------------------------------------------------------------------------\nBOOST_AUTO_TEST_CASE(boost_function)\n{\n typedef void (*fn1_t)(void);\n static_assert(std::is_same::type>::value, \"boost::function_types problem\");\n\n typedef int (*fn2_t)(int,const char*,float&);\n static_assert(std::is_same::type>::value, \"boost::function_types problem\");\n \n struct TestClass {\n int foo(float) {return 0;}\n };\n\n typedef int (TestClass::*fn3_t)(float);\n static_assert(std::is_same::type>::value, \"boost::function_types problem\");\n}\n\n\nBOOST_AUTO_TEST_SUITE_END()\n<|endoftext|>"} {"text":"#include \n#include \n\n#include \"core\/argparse.h\"\n#include \"core\/image.h\"\n#include \"core\/random.h\"\n#include \"core\/io.h\"\n#include \"core\/vec2.h\"\n#include \"core\/palette.h\"\n#include \"core\/closestpoint.h\"\n#include \"core\/rect.h\"\n\n#include \"core\/palette_tableu.h\"\n#include \"core\/poisson.h\"\n\nusing namespace euphoria::core;\n\nfloat\ni2f(int i)\n{\n return static_cast(i);\n}\n\nstd::vector GenerateRandomPoints(int count, const Rectf& size, Random* random)\n{\n std::vector r;\n for(int i=0; i;\n\n DistFunc euclidian_distance = [](const vec2f& lhs, const vec2f& rhs)\n {\n return (lhs-rhs).GetLengthSquared();\n };\n\n DistFunc manhattan_distance = [](const vec2f& lhs, const vec2f& rhs)\n {\n const auto d = (lhs-rhs);\n return Abs(d.x) + Abs(d.y);\n };\n \n auto pal = use_colorblind\n ? palette::ColorBlind_10()\n : Palette::Rainbow(random_points.size());\n Image image;\n image.SetupNoAlphaSupport(size, size);\n\n const float max_distance = (area.GetWidth() + area.GetHeight())\/2;\n\n auto points = ClosestPoint\n {\n [&](const vec2f& lhs, const vec2f& rhs)\n {\n const auto dist_func = distance_function == DistanceFunction::Euclidian\n ? euclidian_distance\n : manhattan_distance;\n const auto dist = dist_func(lhs, rhs);\n if(crazy_distance)\n {\n return Abs(max_distance - dist);\n }\n else\n {\n return dist;\n }\n }\n }\n ;\n {\n int index = 0;\n for(auto p: random_points)\n {\n points.Add(p, index);\n index += 1;\n }\n }\n\n image.SetAllBottomTop([&](int x, int y) {\n const auto index = points.FindClosest(vec2f{i2f(x), i2f(y)});\n return pal.GetSafeIndex(index);\n });\n\n\n io::ChunkToFile(image.Write(ImageWriteFormat::PNG), output_path);\n\n return 0;\n}\nmoar distances and stuff#include \n#include \n\n#include \"core\/argparse.h\"\n#include \"core\/image.h\"\n#include \"core\/random.h\"\n#include \"core\/io.h\"\n#include \"core\/vec2.h\"\n#include \"core\/palette.h\"\n#include \"core\/closestpoint.h\"\n#include \"core\/rect.h\"\n\n#include \"core\/palette_tableu.h\"\n#include \"core\/poisson.h\"\n\nusing namespace euphoria::core;\n\nfloat\ni2f(int i)\n{\n return static_cast(i);\n}\n\nstd::vector GenerateRandomPoints(int count, const Rectf& size, Random* random)\n{\n std::vector r;\n for(int i=0; i, float>\n {\n [&](const vec2f& lhs, const vec2f& rhs)\n {\n const auto dist = GetDistance(distance_function, lhs, rhs);\n if(cos_distance)\n {\n return Cos(Angle::FromDegrees(dist\/crazy_distance));\n }\n else\n {\n return Abs(crazy_distance - dist);\n }\n }\n }\n ;\n {\n int index = 0;\n for(auto p: random_points)\n {\n points.Add(p, index);\n index += 1;\n }\n }\n\n image.SetAllBottomTop([&](int x, int y) {\n const auto index = points.FindClosest(vec2f{i2f(x), i2f(y)});\n return pal.GetSafeIndex(index);\n });\n\n\n io::ChunkToFile(image.Write(ImageWriteFormat::PNG), output_path);\n\n return 0;\n}\n<|endoftext|>"} {"text":"\/\/ video_odometry.cpp - ROS node to publish odometry from video images.\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\nint horizonWidth, horizonHeight;\nint odomWidth, odomHeight, odomMargin;\n\nint horizonFeatures;\ndouble horizonQuality;\nint horizonMinDistance;\nint horizonWindowSize;\n \nint odomFeatures;\ndouble odomQuality;\nint odomMinDistance;\nint odomWindowSize;\n\ndouble headingScaling;\ndouble odomScaling;\n\nbool publishFlow;\n \nlong frameCount;\n\ncv::Mat horizonMask;\ncv::Mat odomMask;\n\ncv::Size horizonWindow;\ncv::Size odomWindow;\n\ncv::Ptr horizonDetector;\ncv::Ptr odomDetector;\n\ncv::Mat lastGray;\nstd::vector lastHorizonPoints;\nstd::vector lastOdomPoints;\n\nros::Publisher imagePub;\n\nvoid makeMasks(const cv::Mat &frame) {\n cv::Scalar ones(255, 255, 255);\n\n cv::Point2f horizonNW(0, frame.cols\/2 - horizonWidth\/2);\n cv::Point2f horizonSE(horizonHeight, frame.cols\/2 + horizonWidth\/2);\n horizonMask = cv::Mat::zeros(frame.rows, frame.cols, CV_8UC1);\n cv::rectangle(horizonMask, horizonNW, horizonSE, ones);\n\n cv::Point2f odomNW(frame.rows - odomMargin - odomHeight,\n\t\t frame.cols\/2 - odomWidth\/2);\n cv::Point2f odomSE(frame.rows - odomMargin,\n\t\t frame.cols\/2 + odomWidth\/2);\n odomMask = cv::Mat::zeros(frame.rows, frame.cols, CV_8UC1);\n cv::rectangle(odomMask, odomNW, odomSE, ones);\n\n horizonWindow = cv::Size(horizonWindowSize, horizonWindowSize);\n odomWindow = cv::Size(odomWindowSize, odomWindowSize);\n}\n\nvoid findFlow(cv::Mat &frame, const cv::Mat &gray,\n\t std::vector horizonPoints,\n\t std::vector odomPoints) {\n\n std::vector status;\n std::vector error;\n\n cv::calcOpticalFlowPyrLK(lastGray, gray, lastHorizonPoints, horizonPoints,\n\t\t\t status, error, horizonWindow);\n cv::Mat horizonInliers;\n cv::Mat horizonH = cv::findHomography(lastHorizonPoints, horizonPoints,\n\t\t\t\t\tcv::RANSAC, 2.5F, horizonInliers);\n\n if (horizonH.total() == 0) {\n \/\/ Cannot calculate anything if we don't have horizon homography.\n return;\n }\n\n cv::Mat horizonP = cv::Mat(cv::Point3d(frame.cols\/2, frame.rows\/2, 1));\n cv::Mat horizonP1;\n if (horizonH.total() == 0) {\n horizonP1 = horizonP;\n } else {\n horizonP1 = horizonH * horizonP;\n \/\/ Normalize the translated point.\n horizonP1 \/= horizonP1.at(2);\n }\n\n cv::calcOpticalFlowPyrLK(lastGray, gray, lastOdomPoints, odomPoints,\n\t\t\t status, error, odomWindow);\n cv::Mat odomInliers;\n cv::Mat odomH = cv::findHomography(lastOdomPoints, odomPoints,\n\t\t\t\t cv::RANSAC, 2.5F, odomInliers);\n cv::Mat odomP = cv::Mat(cv::Point3d(frame.cols\/2,\n\t\t\t\t frame.rows - odomMargin - odomHeight\/2,\n\t\t\t\t 1));\n cv::Mat odomP1;\n if (odomH.total() == 0) {\n odomP1 = odomP;\n } else {\n odomP1 = odomH * odomP;\n odomP1 \/= odomP1.at(2);\n }\n\n cv::Point2f offset(1,1);\n cv::Scalar vectorColor(0, 255, 80);\n cv::Scalar consensusColor(0, 0, 255);\n\n for (int i=0; i < horizonPoints.size(); ++i) {\n if (horizonInliers.at(i)) {\n cv::rectangle(frame, lastHorizonPoints[i]-offset,\n\t\t lastHorizonPoints[i]+offset,\n\t\t vectorColor);\n cv::line(frame, lastHorizonPoints[i], horizonPoints[i], vectorColor);\n }\n }\n\n for (int i=0; i < odomPoints.size(); ++i) {\n if (odomInliers.at(i)) {\n cv::rectangle(frame, lastOdomPoints[i]-offset,\n\t\t lastOdomPoints[i]+offset,\n\t\t vectorColor);\n cv::line(frame, lastOdomPoints[i], odomPoints[i], vectorColor);\n }\n }\n\n if (publishFlow) {\n sensor_msgs::ImagePtr msg =\n cv_bridge::CvImage(std_msgs::Header(), \"bgr8\", frame).toImageMsg();\n imagePub.publish(msg);\n }\n}\n\nvoid processImage(const sensor_msgs::Image::ConstPtr& msg) {\n cv::Mat frame = cv_bridge::toCvShare(msg, \"bgr8\")->image;\n\n if (frameCount == 0) {\n makeMasks(frame);\n }\n\n ++frameCount;\n ROS_INFO(\"Processing frame %ld\", frameCount);\n\n cv::Mat gray;\n cv::cvtColor(frame, gray, cv::COLOR_BGR2GRAY);\n\n std::vector keypoints;\n std::vector horizonPoints;\n std::vector odomPoints;\n\n horizonDetector->detect(gray, keypoints, horizonMask);\n cv::KeyPoint::convert(keypoints, lastHorizonPoints);\n\n odomDetector->detect(gray, keypoints, odomMask);\n cv::KeyPoint::convert(keypoints, lastOdomPoints);\n\n if (frameCount >= 2) {\n findFlow(frame, gray, horizonPoints, odomPoints);\n }\n\n lastGray = gray;\n\n lastHorizonPoints = horizonPoints;\n lastOdomPoints = odomPoints;\n}\n\n\/**\n * Starts the ROS node.\n *\/\nint main(int argc, char **argv) {\n ros::init(argc, argv, \"video_odometry\");\n ros::NodeHandle n(\"~\");\n\n n.param(\"horizon_width\", horizonWidth, 400);\n n.param(\"horizon_height\", horizonHeight, 150);\n\n n.param(\"odom_width\", odomWidth, 300);\n n.param(\"odom_height\", odomHeight, 150);\n n.param(\"odom_margin\", odomMargin, 50);\n\n n.param(\"horizon_features\", horizonFeatures, 500);\n n.param(\"horizon_quality\", horizonQuality, 0.01);\n n.param(\"horizon_min_distance\", horizonMinDistance, 1);\n n.param(\"horizon_window_size\", horizonWindowSize, 21);\n\n n.param(\"odom_features\", odomFeatures, 500);\n n.param(\"odom_quality\", odomQuality, 0.01);\n n.param(\"odom_min_distance\", odomMinDistance, 1);\n n.param(\"odom_window_size\", odomWindowSize, 21);\n\n n.param(\"heading_scaling\", headingScaling, 0.002);\n n.param(\"odom_scaling\", odomScaling, 0.003);\n\n n.param(\"publish_flow\", publishFlow, false);\n \n ros::Subscriber imageSub = n.subscribe(\"\/color\/image_raw\", 1000, processImage);\n\n ros::Publisher odomPub = n.advertise(\"\/odom\", 1000);\n imagePub = n.advertise(\"\/color\/image_flow\", 1000);\n\n horizonDetector =\n cv::GFTTDetector::create(horizonFeatures, horizonQuality,\n\t\t\t horizonMinDistance, 3);\n odomDetector =\n cv::GFTTDetector::create(odomFeatures, odomQuality,\n\t\t\t odomMinDistance, 3);\n frameCount = 0;\n\n ros::spin();\n \n return 0;\n}\nFix mask rectangle calculation\/\/ video_odometry.cpp - ROS node to publish odometry from video images.\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\nint horizonWidth, horizonHeight;\nint odomWidth, odomHeight, odomMargin;\n\nint horizonFeatures;\ndouble horizonQuality;\nint horizonMinDistance;\nint horizonWindowSize;\n \nint odomFeatures;\ndouble odomQuality;\nint odomMinDistance;\nint odomWindowSize;\n\ndouble headingScaling;\ndouble odomScaling;\n\nbool publishFlow;\n \nlong frameCount;\n\ncv::Mat horizonMask;\ncv::Mat odomMask;\n\ncv::Size horizonWindow;\ncv::Size odomWindow;\n\ncv::Ptr horizonDetector;\ncv::Ptr odomDetector;\n\ncv::Mat lastGray;\nstd::vector lastHorizonPoints;\nstd::vector lastOdomPoints;\n\nros::Publisher imagePub;\n\nvoid makeMasks(const cv::Mat &frame) {\n cv::Scalar ones(255, 255, 255);\n\n cv::Point2f horizonNW(frame.cols\/2 - horizonWidth\/2, 0);\n cv::Point2f horizonSE(frame.cols\/2 + horizonWidth\/2, horizonHeight);\n horizonMask = cv::Mat::zeros(frame.rows, frame.cols, CV_8UC1);\n cv::rectangle(horizonMask, horizonNW, horizonSE, ones, CV_FILLED);\n\n cv::Point2f odomNW(frame.cols\/2 - odomWidth\/2,\n\t\t frame.rows - odomMargin - odomHeight);\n cv::Point2f odomSE(frame.cols\/2 + odomWidth\/2,\n\t\t frame.rows - odomMargin);\n odomMask = cv::Mat::zeros(frame.rows, frame.cols, CV_8UC1);\n cv::rectangle(odomMask, odomNW, odomSE, ones, CV_FILLED);\n\n horizonWindow = cv::Size(horizonWindowSize, horizonWindowSize);\n odomWindow = cv::Size(odomWindowSize, odomWindowSize);\n}\n\nvoid findFlow(cv::Mat &frame, const cv::Mat &gray,\n\t std::vector horizonPoints,\n\t std::vector odomPoints) {\n\n std::vector status;\n std::vector error;\n\n cv::calcOpticalFlowPyrLK(lastGray, gray, lastHorizonPoints, horizonPoints,\n\t\t\t status, error, horizonWindow);\n cv::Mat horizonInliers;\n cv::Mat horizonH = cv::findHomography(lastHorizonPoints, horizonPoints,\n\t\t\t\t\tcv::RANSAC, 2.5F, horizonInliers);\n\n if (horizonH.total() == 0) {\n \/\/ Cannot calculate anything if we don't have horizon homography.\n return;\n }\n\n cv::Mat horizonP = cv::Mat(cv::Point3d(frame.cols\/2, frame.rows\/2, 1));\n cv::Mat horizonP1;\n if (horizonH.total() == 0) {\n horizonP1 = horizonP;\n } else {\n horizonP1 = horizonH * horizonP;\n \/\/ Normalize the translated point.\n horizonP1 \/= horizonP1.at(2);\n }\n\n cv::calcOpticalFlowPyrLK(lastGray, gray, lastOdomPoints, odomPoints,\n\t\t\t status, error, odomWindow);\n cv::Mat odomInliers;\n cv::Mat odomH = cv::findHomography(lastOdomPoints, odomPoints,\n\t\t\t\t cv::RANSAC, 2.5F, odomInliers);\n cv::Mat odomP = cv::Mat(cv::Point3d(frame.cols\/2,\n\t\t\t\t frame.rows - odomMargin - odomHeight\/2,\n\t\t\t\t 1));\n cv::Mat odomP1;\n if (odomH.total() == 0) {\n odomP1 = odomP;\n } else {\n odomP1 = odomH * odomP;\n odomP1 \/= odomP1.at(2);\n }\n\n cv::Point2f offset(1,1);\n cv::Scalar vectorColor(0, 255, 80);\n cv::Scalar consensusColor(0, 0, 255);\n\n for (int i=0; i < horizonPoints.size(); ++i) {\n if (horizonInliers.at(i)) {\n cv::rectangle(frame, lastHorizonPoints[i]-offset,\n\t\t lastHorizonPoints[i]+offset,\n\t\t vectorColor);\n cv::line(frame, lastHorizonPoints[i], horizonPoints[i], vectorColor);\n }\n }\n\n for (int i=0; i < odomPoints.size(); ++i) {\n if (odomInliers.at(i)) {\n cv::rectangle(frame, lastOdomPoints[i]-offset,\n\t\t lastOdomPoints[i]+offset,\n\t\t vectorColor);\n cv::line(frame, lastOdomPoints[i], odomPoints[i], vectorColor);\n }\n }\n\n if (publishFlow) {\n sensor_msgs::ImagePtr msg =\n cv_bridge::CvImage(std_msgs::Header(), \"bgr8\", frame).toImageMsg();\n imagePub.publish(msg);\n }\n}\n\nvoid processImage(const sensor_msgs::Image::ConstPtr& msg) {\n cv::Mat frame = cv_bridge::toCvShare(msg, \"bgr8\")->image;\n\n if (frameCount == 0) {\n makeMasks(frame);\n }\n\n ++frameCount;\n ROS_INFO(\"Processing frame %ld\", frameCount);\n\n cv::Mat gray;\n cv::cvtColor(frame, gray, cv::COLOR_BGR2GRAY);\n\n std::vector keypoints;\n std::vector horizonPoints;\n std::vector odomPoints;\n\n horizonDetector->detect(gray, keypoints, horizonMask);\n cv::KeyPoint::convert(keypoints, lastHorizonPoints);\n\n odomDetector->detect(gray, keypoints, odomMask);\n cv::KeyPoint::convert(keypoints, lastOdomPoints);\n\n if (frameCount >= 2) {\n findFlow(frame, gray, horizonPoints, odomPoints);\n }\n\n lastGray = gray;\n\n lastHorizonPoints = horizonPoints;\n lastOdomPoints = odomPoints;\n}\n\n\/**\n * Starts the ROS node.\n *\/\nint main(int argc, char **argv) {\n ros::init(argc, argv, \"video_odometry\");\n ros::NodeHandle n(\"~\");\n\n n.param(\"horizon_width\", horizonWidth, 400);\n n.param(\"horizon_height\", horizonHeight, 150);\n\n n.param(\"odom_width\", odomWidth, 300);\n n.param(\"odom_height\", odomHeight, 150);\n n.param(\"odom_margin\", odomMargin, 50);\n\n n.param(\"horizon_features\", horizonFeatures, 500);\n n.param(\"horizon_quality\", horizonQuality, 0.01);\n n.param(\"horizon_min_distance\", horizonMinDistance, 1);\n n.param(\"horizon_window_size\", horizonWindowSize, 21);\n\n n.param(\"odom_features\", odomFeatures, 500);\n n.param(\"odom_quality\", odomQuality, 0.01);\n n.param(\"odom_min_distance\", odomMinDistance, 1);\n n.param(\"odom_window_size\", odomWindowSize, 21);\n\n n.param(\"heading_scaling\", headingScaling, 0.002);\n n.param(\"odom_scaling\", odomScaling, 0.003);\n\n n.param(\"publish_flow\", publishFlow, false);\n \n ros::Subscriber imageSub = n.subscribe(\"\/color\/image_raw\", 1000, processImage);\n\n ros::Publisher odomPub = n.advertise(\"\/odom\", 1000);\n imagePub = n.advertise(\"\/color\/image_flow\", 1000);\n\n horizonDetector =\n cv::GFTTDetector::create(horizonFeatures, horizonQuality,\n\t\t\t horizonMinDistance, 3);\n odomDetector =\n cv::GFTTDetector::create(odomFeatures, odomQuality,\n\t\t\t odomMinDistance, 3);\n frameCount = 0;\n\n ros::spin();\n \n return 0;\n}\n<|endoftext|>"} {"text":"\/**\n * This file is part of the \"FnordMetric\" project\n * Copyright (c) 2014 Paul Asmuth, Google Inc.\n *\n * FnordMetric is free software: you can redistribute it and\/or modify it under\n * the terms of the GNU General Public License v3.0. You should have received a\n * copy of the GNU General Public License along with this program. If not, see\n * .\n *\/\n#include \"fnord-feeds\/RemoteFeedReader.h\"\n#include \"fnord\/base\/logging.h\"\n#include \"fnord\/json\/JSONRPCCodec.h\"\n#include \"fnord-feeds\/FeedService.h\"\n\nnamespace fnord {\nnamespace feeds {\n\nRemoteFeedReader::RemoteFeedReader(\n RPCClient* rpc_client) :\n rpc_client_(rpc_client),\n time_backfill_fn_(nullptr) {}\n\nvoid RemoteFeedReader::addSourceFeed(\n URI rpc_url,\n String feed_name,\n uint64_t initial_offset,\n size_t batch_size \/* = kDefaultBatchSize *\/,\n size_t max_buffer_size \/* = kDefaultMaxBufferSize *\/) {\n for (const auto& source : sources_) {\n if (source->feed_name == feed_name) {\n RAISEF(kIndexError, \"feed '$0' already exists\", feed_name);\n }\n }\n\n auto source = new SourceFeed();\n source->rpc_url = rpc_url;\n source->feed_name = feed_name;\n source->batch_size = batch_size;\n source->max_buffer_size = max_buffer_size;\n source->is_fetching = false;\n source->next_offset = initial_offset;\n source->consumed_offset = initial_offset;\n source->stream_time = 0;\n sources_.emplace_back(source);\n}\n\nOption RemoteFeedReader::fetchNextEntry() {\n ScopedLock lk(mutex_);\n int idx = -1;\n uint64_t min_stream_time = std::numeric_limits::max();\n Duration max_spread(3600 * kMicrosPerSecond);\n\n for (int i = 0; i < sources_.size(); ++i) {\n const auto& source = sources_[i];\n\n maybeFillBuffer(source.get());\n\n if (source->stream_time.unixMicros() < min_stream_time) {\n min_stream_time = source->stream_time.unixMicros();\n\n if (source->read_buffer.size() > 0) {\n idx = i;\n } else {\n idx = -1;\n }\n }\n }\n\n if (idx == -1) {\n min_stream_time += max_spread.microseconds();\n\n for (int i = 0; i < sources_.size(); ++i) {\n const auto& source = sources_[i];\n\n if (source->stream_time.unixMicros() < min_stream_time &&\n source->read_buffer.size() > 0) {\n min_stream_time = source->stream_time.unixMicros();\n idx = i;\n }\n }\n }\n\n if (idx < 0) {\n return None();\n } else {\n const auto& source = sources_[idx];\n auto entry = source->read_buffer.front();\n source->read_buffer.pop_front();\n\n if (entry.time > source->stream_time) {\n source->stream_time = entry.time;\n }\n\n source->consumed_offset = entry.next_offset;\n return Some(entry);\n }\n}\n\nvoid RemoteFeedReader::maybeFillBuffer(SourceFeed* source) {\n if (source->is_fetching ||\n source->read_buffer.size() >= source->max_buffer_size) {\n return;\n }\n\n source->is_fetching = true;\n\n#ifndef NDEBUG\n fnord::logTrace(\n \"fnord.feeds.remotefeedreader\",\n \"Fetching from feed\\n name=$0\\n url=$1\\n offset=$2\",\n source->feed_name,\n source->rpc_url.toString(),\n source->next_offset);\n#endif\n\n auto rpc = fnord::mkRPC(\n &FeedService::fetch,\n source->feed_name,\n source->next_offset,\n (int) source->batch_size);\n\n rpc_client_->call(source->rpc_url, rpc.get());\n\n rpc->onSuccess([this, source] (const decltype(rpc)::ValueType& r) mutable {\n ScopedLock lk(mutex_);\n\n for (const auto& e : r.result()) {\n auto entry = e;\n\n if (entry.time.unixMicros() == 0 && time_backfill_fn_) {\n entry.time = time_backfill_fn_(entry);\n }\n\n source->read_buffer.emplace_back(std::move(entry));\n }\n\n source->is_fetching = false;\n\n if (source->read_buffer.size() > 0) {\n source->next_offset = source->read_buffer.back().next_offset;\n lk.unlock();\n data_available_wakeup_.wakeup();\n }\n });\n\n rpc->onError([this, source] (const Status& status) {\n ScopedLock lk(mutex_);\n source->is_fetching = false;\n lk.unlock();\n\n logError(\n \"fnord.feeds.remotefeedreader\",\n \"Error while fetching from feed:\\n\" \\\n \" feed=$1\\n url=$0\\n error=$2\",\n source->rpc_url.toString(),\n source->feed_name,\n status);\n\n data_available_wakeup_.wakeup();\n });\n}\n\nvoid RemoteFeedReader::waitForNextEntry() {\n ScopedLock lk(mutex_);\n bool is_data_available = false;\n\n for (const auto& source : sources_) {\n maybeFillBuffer(source.get());\n\n if (source->read_buffer.size() > 0) {\n is_data_available = true;\n }\n }\n\n \/* fastpath if there is data available on any feed *\/\n if (is_data_available) {\n return;\n }\n\n auto wakeup_gen = data_available_wakeup_.generation();\n lk.unlock();\n\n \/* wait until there is any data available *\/\n data_available_wakeup_.waitForWakeup(wakeup_gen);\n}\n\nVector> RemoteFeedReader::streamOffsets() const {\n ScopedLock lk(mutex_);\n\n Vector> offsets;\n for (const auto& source : sources_) {\n offsets.emplace_back(source->feed_name, source->consumed_offset);\n }\n\n return offsets;\n}\n\nPair RemoteFeedReader::watermarks() const {\n ScopedLock lk(mutex_);\n\n if (sources_.size() == 0) {\n return std::make_pair(DateTime(0), DateTime(0));\n }\n\n uint64_t low = std::numeric_limits::max();\n uint64_t high = 0;\n\n for (const auto& source : sources_) {\n if (source->stream_time.unixMicros() < low) {\n low = source->stream_time.unixMicros();\n }\n\n if (source->stream_time.unixMicros() > high) {\n high = source->stream_time.unixMicros();\n }\n }\n\n return std::make_pair(DateTime(low), DateTime(high));\n}\n\nDateTime RemoteFeedReader::lowWatermark() const {\n return watermarks().first;\n}\n\nDateTime RemoteFeedReader::highWatermark() const {\n return watermarks().second;\n}\n\nvoid RemoteFeedReader::setTimeBackfill(\n Function fn) {\n time_backfill_fn_ = fn;\n}\n\nvoid RemoteFeedReader::exportStats(\n const String& path_prefix \/* = \"\/fnord\/feeds\/reader\/\" *\/,\n stats::StatsRepository* stats_repo \/* = nullptr *\/) {\n}\n\n}\n}\nRemoteFeedReader: unconditional time backfill\/**\n * This file is part of the \"FnordMetric\" project\n * Copyright (c) 2014 Paul Asmuth, Google Inc.\n *\n * FnordMetric is free software: you can redistribute it and\/or modify it under\n * the terms of the GNU General Public License v3.0. You should have received a\n * copy of the GNU General Public License along with this program. If not, see\n * .\n *\/\n#include \"fnord-feeds\/RemoteFeedReader.h\"\n#include \"fnord\/base\/logging.h\"\n#include \"fnord\/json\/JSONRPCCodec.h\"\n#include \"fnord-feeds\/FeedService.h\"\n\nnamespace fnord {\nnamespace feeds {\n\nRemoteFeedReader::RemoteFeedReader(\n RPCClient* rpc_client) :\n rpc_client_(rpc_client),\n time_backfill_fn_(nullptr) {}\n\nvoid RemoteFeedReader::addSourceFeed(\n URI rpc_url,\n String feed_name,\n uint64_t initial_offset,\n size_t batch_size \/* = kDefaultBatchSize *\/,\n size_t max_buffer_size \/* = kDefaultMaxBufferSize *\/) {\n for (const auto& source : sources_) {\n if (source->feed_name == feed_name) {\n RAISEF(kIndexError, \"feed '$0' already exists\", feed_name);\n }\n }\n\n auto source = new SourceFeed();\n source->rpc_url = rpc_url;\n source->feed_name = feed_name;\n source->batch_size = batch_size;\n source->max_buffer_size = max_buffer_size;\n source->is_fetching = false;\n source->next_offset = initial_offset;\n source->consumed_offset = initial_offset;\n source->stream_time = 0;\n sources_.emplace_back(source);\n}\n\nOption RemoteFeedReader::fetchNextEntry() {\n ScopedLock lk(mutex_);\n int idx = -1;\n uint64_t min_stream_time = std::numeric_limits::max();\n Duration max_spread(3600 * kMicrosPerSecond);\n\n for (int i = 0; i < sources_.size(); ++i) {\n const auto& source = sources_[i];\n\n maybeFillBuffer(source.get());\n\n if (source->stream_time.unixMicros() < min_stream_time) {\n min_stream_time = source->stream_time.unixMicros();\n\n if (source->read_buffer.size() > 0) {\n idx = i;\n } else {\n idx = -1;\n }\n }\n }\n\n if (idx == -1) {\n min_stream_time += max_spread.microseconds();\n\n for (int i = 0; i < sources_.size(); ++i) {\n const auto& source = sources_[i];\n\n if (source->stream_time.unixMicros() < min_stream_time &&\n source->read_buffer.size() > 0) {\n min_stream_time = source->stream_time.unixMicros();\n idx = i;\n }\n }\n }\n\n if (idx < 0) {\n return None();\n } else {\n const auto& source = sources_[idx];\n auto entry = source->read_buffer.front();\n source->read_buffer.pop_front();\n\n if (entry.time > source->stream_time) {\n source->stream_time = entry.time;\n }\n\n source->consumed_offset = entry.next_offset;\n return Some(entry);\n }\n}\n\nvoid RemoteFeedReader::maybeFillBuffer(SourceFeed* source) {\n if (source->is_fetching ||\n source->read_buffer.size() >= source->max_buffer_size) {\n return;\n }\n\n source->is_fetching = true;\n\n#ifndef NDEBUG\n fnord::logTrace(\n \"fnord.feeds.remotefeedreader\",\n \"Fetching from feed\\n name=$0\\n url=$1\\n offset=$2\",\n source->feed_name,\n source->rpc_url.toString(),\n source->next_offset);\n#endif\n\n auto rpc = fnord::mkRPC(\n &FeedService::fetch,\n source->feed_name,\n source->next_offset,\n (int) source->batch_size);\n\n rpc_client_->call(source->rpc_url, rpc.get());\n\n rpc->onSuccess([this, source] (const decltype(rpc)::ValueType& r) mutable {\n ScopedLock lk(mutex_);\n\n for (const auto& e : r.result()) {\n auto entry = e;\n\n if (time_backfill_fn_) {\n entry.time = time_backfill_fn_(entry);\n }\n\n source->read_buffer.emplace_back(std::move(entry));\n }\n\n source->is_fetching = false;\n\n if (source->read_buffer.size() > 0) {\n source->next_offset = source->read_buffer.back().next_offset;\n lk.unlock();\n data_available_wakeup_.wakeup();\n }\n });\n\n rpc->onError([this, source] (const Status& status) {\n ScopedLock lk(mutex_);\n source->is_fetching = false;\n lk.unlock();\n\n logError(\n \"fnord.feeds.remotefeedreader\",\n \"Error while fetching from feed:\\n\" \\\n \" feed=$1\\n url=$0\\n error=$2\",\n source->rpc_url.toString(),\n source->feed_name,\n status);\n\n data_available_wakeup_.wakeup();\n });\n}\n\nvoid RemoteFeedReader::waitForNextEntry() {\n ScopedLock lk(mutex_);\n bool is_data_available = false;\n\n for (const auto& source : sources_) {\n maybeFillBuffer(source.get());\n\n if (source->read_buffer.size() > 0) {\n is_data_available = true;\n }\n }\n\n \/* fastpath if there is data available on any feed *\/\n if (is_data_available) {\n return;\n }\n\n auto wakeup_gen = data_available_wakeup_.generation();\n lk.unlock();\n\n \/* wait until there is any data available *\/\n data_available_wakeup_.waitForWakeup(wakeup_gen);\n}\n\nVector> RemoteFeedReader::streamOffsets() const {\n ScopedLock lk(mutex_);\n\n Vector> offsets;\n for (const auto& source : sources_) {\n offsets.emplace_back(source->feed_name, source->consumed_offset);\n }\n\n return offsets;\n}\n\nPair RemoteFeedReader::watermarks() const {\n ScopedLock lk(mutex_);\n\n if (sources_.size() == 0) {\n return std::make_pair(DateTime(0), DateTime(0));\n }\n\n uint64_t low = std::numeric_limits::max();\n uint64_t high = 0;\n\n for (const auto& source : sources_) {\n if (source->stream_time.unixMicros() < low) {\n low = source->stream_time.unixMicros();\n }\n\n if (source->stream_time.unixMicros() > high) {\n high = source->stream_time.unixMicros();\n }\n }\n\n return std::make_pair(DateTime(low), DateTime(high));\n}\n\nDateTime RemoteFeedReader::lowWatermark() const {\n return watermarks().first;\n}\n\nDateTime RemoteFeedReader::highWatermark() const {\n return watermarks().second;\n}\n\nvoid RemoteFeedReader::setTimeBackfill(\n Function fn) {\n time_backfill_fn_ = fn;\n}\n\nvoid RemoteFeedReader::exportStats(\n const String& path_prefix \/* = \"\/fnord\/feeds\/reader\/\" *\/,\n stats::StatsRepository* stats_repo \/* = nullptr *\/) {\n}\n\n}\n}\n<|endoftext|>"} {"text":"\/\/\n\/\/ Created by Masashi Fujita on 2016\/05\/06.\n\/\/\n\/\/ Copyright (c) 2016 Masashi Fujita.\n\/\/\n\n#include \n#include \n#include \n#include \n\n#include \"chacha20.hpp\"\n\nextern \"C\" {\n#include \"ecrypt-sync.h\"\n}\n\nnamespace {\n std::vector encode (ECRYPT_ctx &ctx, const std::string &s) {\n std::vector result ;\n result.resize (s.size ()) ;\n ECRYPT_encrypt_bytes (&ctx, (const u8 *)s.data (), (u8 *)result.data (), s.size ()) ;\n return result ;\n }\n\n std::vector encode (ChaCha::State &state, const std::string &s) {\n std::vector result ;\n result.resize (s.size ()) ;\n ChaCha::apply (state, result.data (), s.data (), s.size ()) ;\n return result ;\n }\n\n std::vector encode (ChaCha::State &state, const std::string &s, size_t offset) {\n std::vector result ;\n result.resize (s.size ()) ;\n ChaCha::apply (state, result.data (), s.data (), s.size (), offset) ;\n return result ;\n }\n}\n\nTEST_CASE (\"Test with small key\") {\n SUBCASE (\"with small key\") {\n ECRYPT_ctx ctx;\n memset (&ctx, 0, sizeof (ctx));\n const std::string key { \"0123456789abcdef\" };\n REQUIRE (8 * key.size () == 128);\n ECRYPT_keysetup (&ctx, reinterpret_cast (key.data ()), 128, 0);\n std::array iv;\n iv.fill (0);\n ECRYPT_ivsetup (&ctx, static_cast (iv.data ()));\n ChaCha::State S { key.data (), key.size (), 0 };\n\n SUBCASE (\"Compare states\") {\n auto const &state = S.state ();\n for (int_fast32_t i = 0 ; i < state.size () ; ++i) {\n CAPTURE (i);\n REQUIRE (state[i] == ctx.input[i]);\n }\n }\n SUBCASE (\"Encrypt strings\") {\n SUBCASE (\"Encrypt \\\"A\\\"\") {\n auto const &expected = encode (ctx, \"A\");\n auto const &actual = encode (S, \"A\");\n REQUIRE (expected.size () == actual.size ());\n REQUIRE (expected == actual);\n }\n SUBCASE (\"Encrypt \\\"The ninja warrior are the immortal murder machines.\\\"\") {\n const std::string src { \"The ninja warrior are the immortal murder machines.\" };\n auto const &expected = encode (ctx, src);\n auto const &actual = encode (S, src);\n REQUIRE (expected.size () == actual.size ());\n REQUIRE (expected == actual);\n }\n SUBCASE (\"Encrypt \\\"The ninja warrior are the immortal murder machines.\\\" (splitted)\") {\n const std::string src { \"The ninja warrior are the immortal murder machines.\" };\n auto off = src.size () \/ 2;\n auto const &expected = encode (ctx, src);\n auto &&a0 = encode (S, src.substr (0, off), 0);\n auto const &a1 = encode (S, src.substr (off), off);\n a0.insert (a0.end (), a1.cbegin (), a1.cend ());\n REQUIRE (expected.size () == a0.size ());\n REQUIRE (expected == a0);\n }\n }\n }\n}\n\nTEST_CASE (\"Test with large key\") {\n SUBCASE (\"with large key\") {\n ECRYPT_ctx ctx ;\n memset (&ctx, 0, sizeof (ctx)) ;\n std::string key { \"0123456789abcdef0123456789abcdef\" };\n REQUIRE (8 * key.size () == 256) ;\n ECRYPT_keysetup (&ctx, reinterpret_cast (key.data ()), 256, 0) ;\n std::array iv ;\n iv.fill (0) ;\n ECRYPT_ivsetup (&ctx, static_cast (iv.data ())) ;\n ChaCha::State S { key.data (), key.size (), 0 } ;\n\n SUBCASE (\"Compare states\") {\n auto const & state = S.state () ;\n for (int_fast32_t i = 0 ; i < state.size () ; ++i) {\n CAPTURE (i) ;\n REQUIRE (state [i] == ctx.input [i]) ;\n }\n }\n SUBCASE (\"Encrypt strings\") {\n SUBCASE (\"Encrypt \\\"A\\\"\") {\n auto const & expected = encode (ctx, \"A\") ;\n auto const & actual = encode (S, \"A\") ;\n REQUIRE (expected.size () == actual.size ()) ;\n REQUIRE (expected == actual) ;\n }\n SUBCASE (\"Encrypt \\\"The ninja warrior are the immortal murder machines.\\\"\") {\n const std::string src { \"The ninja warrior are the immortal murder machines.\" };\n auto const & expected = encode (ctx, src) ;\n auto const & actual = encode (S, src) ;\n REQUIRE (expected.size () == actual.size ()) ;\n REQUIRE (expected == actual) ;\n }\n SUBCASE (\"Encrypt \\\"The ninja warrior are the immortal murder machines.\\\" (splitted)\") {\n const std::string src { \"The ninja warrior are the immortal murder machines.\" };\n auto off = src.size () \/ 2 ;\n auto const & expected = encode (ctx, src) ;\n auto && a0 = encode (S, src.substr (0, off), 0) ;\n auto const & a1 = encode (S, src.substr (off), off) ;\n a0.insert (a0.end (), a1.cbegin (), a1.cend ()) ;\n REQUIRE (expected.size () == a0.size ()) ;\n REQUIRE (expected == a0) ;\n }\n }\n }\n}\ntest: Add property tests\/\/\n\/\/ Created by Masashi Fujita on 2016\/05\/06.\n\/\/\n\/\/ Copyright (c) 2016 Masashi Fujita.\n\/\/\n\n#include \"chacha20.hpp\"\n\n#include \"doctest-rapidcheck.hpp\"\n\n#include \n#include \n#include \n\n#include \n\nextern \"C\" {\n#include \"ecrypt-sync.h\"\n}\n\nnamespace {\n std::vector encode (ECRYPT_ctx &ctx, const std::string &s) {\n std::vector result ;\n result.resize (s.size ()) ;\n ECRYPT_encrypt_bytes (&ctx, (const u8 *)s.data (), (u8 *)result.data (), s.size ()) ;\n return result ;\n }\n\n std::vector encode (ChaCha::State &state, const std::string &s) {\n std::vector result ;\n result.resize (s.size ()) ;\n ChaCha::apply (state, result.data (), s.data (), s.size ()) ;\n return result ;\n }\n\n std::vector encode (ChaCha::State &state, const std::string &s, size_t offset) {\n std::vector result ;\n result.resize (s.size ()) ;\n ChaCha::apply (state, result.data (), s.data (), s.size (), offset) ;\n return result ;\n }\n template \n std::string concat (It_ b, It_ e) {\n size_t sz = 0;\n for (auto it = b; it != e; ++it) {\n sz += it->size ();\n }\n std::string result;\n result.reserve (sz);\n for (auto it = b; it != e; ++it) {\n result += *it;\n }\n return result;\n }\n}\n\nTEST_CASE (\"Test with small key\") {\n SUBCASE (\"with small key\") {\n ECRYPT_ctx ctx;\n memset (&ctx, 0, sizeof (ctx));\n const std::string key { \"0123456789abcdef\" };\n REQUIRE (8 * key.size () == 128);\n ECRYPT_keysetup (&ctx, reinterpret_cast (key.data ()), 128, 0);\n std::array iv;\n iv.fill (0);\n ECRYPT_ivsetup (&ctx, static_cast (iv.data ()));\n ChaCha::State S { key.data (), key.size (), 0 };\n\n SUBCASE (\"Compare states\") {\n auto const &state = S.state ();\n for (int_fast32_t i = 0 ; i < state.size () ; ++i) {\n CAPTURE (i);\n REQUIRE (state[i] == ctx.input[i]);\n }\n }\n SUBCASE (\"Encrypt strings\") {\n SUBCASE (\"Encrypt \\\"A\\\"\") {\n auto const &expected = encode (ctx, \"A\");\n auto const &actual = encode (S, \"A\");\n REQUIRE (expected.size () == actual.size ());\n REQUIRE (expected == actual);\n }\n SUBCASE (\"Encrypt \\\"The ninja warrior are the immortal murder machines.\\\"\") {\n const std::string src { \"The ninja warrior are the immortal murder machines.\" };\n auto const &expected = encode (ctx, src);\n auto const &actual = encode (S, src);\n REQUIRE (expected.size () == actual.size ());\n REQUIRE (expected == actual);\n }\n SUBCASE (\"Encrypt \\\"The ninja warrior are the immortal murder machines.\\\" (splitted)\") {\n const std::string src { \"The ninja warrior are the immortal murder machines.\" };\n auto off = src.size () \/ 2;\n auto const &expected = encode (ctx, src);\n auto &&a0 = encode (S, src.substr (0, off), 0);\n auto const &a1 = encode (S, src.substr (off), off);\n a0.insert (a0.end (), a1.cbegin (), a1.cend ());\n REQUIRE (expected.size () == a0.size ());\n REQUIRE (expected == a0);\n }\n }\n }\n}\n\nTEST_CASE (\"Test with large key\") {\n SUBCASE (\"with large key\") {\n ECRYPT_ctx ctx ;\n memset (&ctx, 0, sizeof (ctx)) ;\n std::string key { \"0123456789abcdef0123456789abcdef\" };\n REQUIRE (8 * key.size () == 256) ;\n ECRYPT_keysetup (&ctx, reinterpret_cast (key.data ()), 256, 0) ;\n std::array iv ;\n iv.fill (0) ;\n ECRYPT_ivsetup (&ctx, static_cast (iv.data ())) ;\n ChaCha::State S { key.data (), key.size (), 0 } ;\n\n SUBCASE (\"Compare states\") {\n auto const & state = S.state () ;\n for (int_fast32_t i = 0 ; i < state.size () ; ++i) {\n CAPTURE (i) ;\n REQUIRE (state [i] == ctx.input [i]) ;\n }\n }\n SUBCASE (\"Encrypt strings\") {\n SUBCASE (\"Encrypt \\\"A\\\"\") {\n auto const & expected = encode (ctx, \"A\") ;\n auto const & actual = encode (S, \"A\") ;\n REQUIRE (expected.size () == actual.size ()) ;\n REQUIRE (expected == actual) ;\n }\n SUBCASE (\"Encrypt \\\"The ninja warrior are the immortal murder machines.\\\"\") {\n const std::string src { \"The ninja warrior are the immortal murder machines.\" };\n auto const & expected = encode (ctx, src) ;\n auto const & actual = encode (S, src) ;\n REQUIRE (expected.size () == actual.size ()) ;\n REQUIRE (expected == actual) ;\n }\n SUBCASE (\"Encrypt \\\"The ninja warrior are the immortal murder machines.\\\" (splitted)\") {\n const std::string src { \"The ninja warrior are the immortal murder machines.\" };\n auto off = src.size () \/ 2 ;\n auto const & expected = encode (ctx, src) ;\n auto && a0 = encode (S, src.substr (0, off), 0) ;\n auto const & a1 = encode (S, src.substr (off), off) ;\n a0.insert (a0.end (), a1.cbegin (), a1.cend ()) ;\n REQUIRE (expected.size () == a0.size ()) ;\n REQUIRE (expected == a0) ;\n }\n }\n }\n}\n\nTEST_CASE (\"property\") {\n rc::prop(\"roundtrip\", [](){\n auto const key_size = *rc::gen::element(16, 32);\n auto const &key = *rc::gen::container> (key_size, rc::gen::arbitrary());\n auto const &plain = *rc::gen::scale(128, rc::gen::arbitrary());\n\n RC_ASSERT (key.size () == 16 || key.size () == 32);\n ECRYPT_ctx ctx ;\n memset (&ctx, 0, sizeof (ctx)) ;\n\n ECRYPT_keysetup (&ctx, reinterpret_cast (key.data ()), 8u * key.size (), 0) ;\n std::array iv ;\n iv.fill (0) ;\n ECRYPT_ivsetup (&ctx, static_cast (iv.data ())) ;\n ChaCha::State S { key.data (), key.size (), 0 } ;\n\n auto const & state = S.state () ;\n for (int_fast32_t i = 0 ; i < state.size () ; ++i) {\n RC_ASSERT (state [i] == ctx.input [i]) ;\n }\n auto const &expected = encode(ctx, plain);\n auto const &actual = encode(S, plain);\n RC_ASSERT (std::equal(expected.begin (), expected.end (), actual.begin(), actual.end(),\n [](auto a, auto b) { return a == b; }));\n });\n rc::prop (\"splitted inputs\", [](){\n auto const key_size = *rc::gen::element (16, 32).as (\"key_size\");\n auto const &key = *rc::gen::container> (key_size, rc::gen::arbitrary ()).as (\"key\");\n ChaCha::State S { key.data (), key.size () };\n auto const &inputs = *rc::gen::container> (rc::gen::string ()).as (\"inputs\");\n auto const &plain = concat (inputs.begin (), inputs.end ());\n std::string expected;\n expected.reserve (plain.size ());\n {\n auto const &e = encode (S, plain);\n std::copy (e.begin (), e.end (), std::back_inserter (expected));\n }\n std::string actual;\n actual.reserve (plain.size ());\n size_t off = 0;\n for (auto const &s : inputs) {\n auto const &e = encode (S, s, off);\n off += s.size ();\n\n std::copy (e.begin (), e.end (), std::back_inserter (actual));\n }\n RC_TAG(inputs.size (), plain.size ());\n RC_ASSERT (expected.size () == actual.size ());\n RC_ASSERT (expected == actual);\n });\n}\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * $RCSfile: cmtree.cxx,v $\n *\n * $Revision: 1.23 $\n *\n * last change: $Author: jb $ $Date: 2001-09-25 16:05:21 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#include \n\n#include \"subtree.hxx\"\n#ifndef CONFIGMGR_CHANGE_HXX\n#include \"change.hxx\"\n#endif\n#ifndef CONFIGMGR_TREECHANGELIST_HXX\n#include \"treechangelist.hxx\"\n#endif\n\n#ifndef CONFIGMGR_TREEPROVIDER_HXX\n#include \"treeprovider.hxx\"\n#endif\n#ifndef _CONFIGMGR_TREEACTIONS_HXX_\n#include \"treeactions.hxx\"\n#endif\n\n#ifndef _RTL_STRING_HXX_\n#include \n#endif\n#ifndef _RTL_USTRING_HXX_\n#include \n#endif\n\n#ifndef _OSL_DIAGNOSE_H_\n#include \n#endif\n\n#ifndef INCLUDED_DEQUE\n#include \n#define INCLUDED_DEQUE\n#endif\n#ifndef INCLUDED_VECTOR\n#include \n#define INCLUDED_VECTOR\n#endif\n#ifndef INCLUDED_IOSTREAM\n#include \n#define INCLUDED_IOSTREAM\n#endif\n#ifndef INCLUDED_EXCEPTION\n#include \n#define INCLUDED_EXCEPTION\n#endif\n#ifndef INCLUDED_SET\n#include \n#define INCLUDED_SET\n#endif\n\nusing namespace std;\nusing namespace rtl;\nusing namespace com::sun::star::uno;\n\nnamespace configmgr\n{\n\n\/\/ ------------------------ ChildListSet implementations ------------------------\n ChildListSet::ChildListSet(ChildListSet const& aSet)\n {\n for(ChildList::iterator it = aSet.GetSet().begin();\n it != aSet.GetSet().end();\n ++it)\n m_aChildList.insert(m_aChildList.end(), (*it)->clone());\n }\n ChildListSet::~ChildListSet()\n {\n for(ChildList::iterator it = m_aChildList.begin();\n it != m_aChildList.end();\n ++it)\n delete *it;\n }\n\n\n\/\/ ---------------------------- Node implementation ----------------------------\n\n INode::INode(configuration::Attributes _aAttr):m_aAttributes(_aAttr){}\n INode::INode(OUString const& aName, configuration::Attributes _aAttr)\n :m_aName(aName)\n ,m_aAttributes(_aAttr){}\n \/\/ CopyCTor will be create automatically\n\n INode::~INode() {}\n\n ISubtree* INode::asISubtree(){return NULL;}\n ISubtree const* INode::asISubtree() const {return NULL;}\n ValueNode* INode::asValueNode() {return NULL;}\n ValueNode const* INode::asValueNode() const {return NULL;}\n\n\n void INode::forceWritableToFinalized()\n {\n if (!m_aAttributes.bWritable)\n {\n m_aAttributes.bFinalized = true;\n m_aAttributes.bWritable = false;\n }\n }\n\n\/\/ ------------------------- SearchNode implementation -------------------------\n SearchNode::SearchNode():INode(configuration::Attributes()){}\n SearchNode::SearchNode(OUString const& aName)\n :INode(aName, configuration::Attributes()){}\n\n INode* SearchNode::clone() const {return new SearchNode(*this);}\n\n SearchNode::~SearchNode(){}\n\n \/\/==========================================================================\n \/\/= OPropagateLevels\n \/\/==========================================================================\n \/** fills a subtree with the correct level informations\n *\/\n struct OPropagateLevels : public NodeModification\n {\n protected:\n sal_Int32 nChildLevel;\n public:\n OPropagateLevels(sal_Int32 _nParentLevel)\n {\n nChildLevel = (ITreeProvider::ALL_LEVELS == _nParentLevel) ? ITreeProvider::ALL_LEVELS : _nParentLevel - 1;\n }\n virtual void handle(ValueNode&) { \/* not interested in value nodes *\/ }\n virtual void handle(ISubtree& _rSubtree)\n {\n if ((ITreeProvider::ALL_LEVELS == nChildLevel) || nChildLevel > _rSubtree.getLevel())\n _rSubtree.setLevel(nChildLevel);\n }\n };\n\n\n\/\/ -------------------------- ISubtree implementation --------------------------\n ISubtree* ISubtree::asISubtree() {return this;}\n ISubtree const* ISubtree::asISubtree() const {return this;}\n\n \/\/--------------------------------------------------------------------------\n void ISubtree::setLevel(sal_Int16 _nLevel)\n {\n m_nLevel = _nLevel;\n if (0 == _nLevel)\n \/\/ nothing more to do, this means \"nothing known about any children\"\n return;\n\n \/\/ forward the level number to any child subtrees we have\n OPropagateLevels aDeeperInto(_nLevel);\n aDeeperInto.applyToChildren(*this);\n }\n\n\/\/ --------------------------- Subtree implementation ---------------------------\n INode* Subtree::clone() const {return new Subtree(*this);}\n\n INode* Subtree::doGetChild(OUString const& aName) const\n {\n SearchNode searchObj(aName);\n\n#ifdef DEBUG\n for (ChildList::iterator it2 = m_aChildren.GetSet().begin();\n it2 != m_aChildren.GetSet().end();\n ++it2)\n {\n INode* pINode = *it2;\n OUString aName2 = pINode->getName();\n volatile int dummy = 0;\n }\n#endif\n\n ChildList::iterator it = m_aChildren.GetSet().find(&searchObj);\n if (it == m_aChildren.GetSet().end())\n return NULL;\n else\n return *it;\n }\n\n INode* Subtree::addChild(std::auto_ptr aNode) \/\/ takes ownership\n {\n OUString aName = aNode->getName();\n std::pair aInserted =\n m_aChildren.GetSet().insert(aNode.get());\n if (aInserted.second)\n aNode.release();\n return *aInserted.first;\n }\n\n ::std::auto_ptr Subtree::removeChild(OUString const& aName)\n {\n SearchNode searchObj(aName);\n ChildList::const_iterator it = m_aChildren.GetSet().find(&searchObj);\n\n ::std::auto_ptr aReturn;\n if (m_aChildren.GetSet().end() != it)\n {\n aReturn = ::std::auto_ptr(*it);\n m_aChildren.GetSet().erase(it);\n }\n return aReturn;\n }\n\n \/\/==========================================================================\n \/\/= OBuildChangeTree - historic\n \/\/==========================================================================\n \/** generates a change tree by comparing two trees\n *\/\n\/* struct OBuildChangeTree : public NodeModification\n {\n protected:\n SubtreeChange& m_rChangeList;\n INode* m_pCacheNode;\n\n public:\n OBuildChangeTree(SubtreeChange& rList, INode* pNode)\n :m_rChangeList(rList)\n ,m_pCacheNode(pNode)\n {\n }\n\n virtual void handle(ValueNode& _nNode)\n {\n OUString aNodeName = _nNode.getName();\n ISubtree* pTree = m_pCacheNode->asISubtree();\n OSL_ENSURE(pTree, \"OBuildChangeTree::handle : node must be a inner node!\");\n if (pTree)\n {\n INode* pChild = pTree->getChild(aNodeName);\n ValueNode* pValueNode = pChild ? pChild->asValueNode() : NULL;\n OSL_ENSURE(pValueNode, \"OBuildChangeTree::handle : node must be a value node!\");\n\n \/\/ if the values differ add a new change\n if (pValueNode && _nNode.getValue() != pValueNode->getValue())\n {\n ValueChange* pChange = new ValueChange(_nNode.getValue(), *pValueNode);\n m_rChangeList.addChange(::std::auto_ptr(pChange));\n }\n }\n }\n\n virtual void handle(ISubtree& _rSubtree)\n {\n OUString aNodeName = _rSubtree.getName();\n ISubtree* pTree = m_pCacheNode->asISubtree();\n OSL_ENSURE(pTree, \"OBuildChangeTree::handle : node must be a inner node!\");\n if (pTree)\n {\n INode* pChild = pTree->getChild(aNodeName);\n \/\/ node not in cache, so ignore it\n \/\/ later, when we get additions and removements within on transaction, then we have to care about\n if (pChild)\n {\n ISubtree* pSubTree = pChild->asISubtree();\n OSL_ENSURE(pSubTree, \"OBuildChangeTree::handle : node must be a inner node!\");\n \/\/ generate a new change\n\n SubtreeChange* pChange = new SubtreeChange(_rSubtree);\n OBuildChangeTree aNextLevel(*pChange, pSubTree);\n aNextLevel.applyToChildren(_rSubtree);\n\n \/\/ now count if there are any changes\n OChangeCounter aCounter;\n pChange->dispatch(aCounter);\n\n if (aCounter.nCount != 0)\n m_rChangeList.addChange(::std::auto_ptr(pChange));\n else\n delete pChange;\n }\n }\n }\n };\n\n*\/\n void Subtree::forEachChild(NodeAction& anAction) const {\n for(ChildList::const_iterator it = m_aChildren.GetSet().begin();\n it != m_aChildren.GetSet().end();\n ++it)\n (**it).dispatch(anAction);\n }\n\n void Subtree::forEachChild(NodeModification& anAction) {\n for(ChildList::iterator it = m_aChildren.GetSet().begin();\n it != m_aChildren.GetSet().end();\n ++it)\n (**it).dispatch(anAction);\n }\n\n\/\/ \/\/ -------------------------- ValueNode implementation --------------------------\n void ValueNode::check_init() \/\/ may throw in the future\n {\n m_aValuePair.check_init();\n }\n\n void ValueNode::init()\n {\n m_aValuePair.init();\n }\n\n\n void ValueNode::setValue(Any const& _aValue)\n {\n m_aValuePair.setFirst(_aValue);\n }\n\n void ValueNode::changeDefault(Any const& _aValue)\n {\n m_aValuePair.setSecond(_aValue);\n }\n\n void ValueNode::setDefault()\n {\n \/\/ PRE: ????\n \/\/ POST: isDefault() == true\n \/\/ OSL_ENSURE(false, \"ValueNode::setDefault(): this isn't really defined yet.\");\n \/\/ m_aValue = Any();\n \/\/ m_pFirst = NULL;\n }\n\n INode* ValueNode::clone() const\n {\n return new ValueNode(*this);\n }\n\n ValueNode* ValueNode::asValueNode() {return this;}\n ValueNode const* ValueNode::asValueNode() const {return this;}\n\n} \/\/ namespace configmgr\n\n\n#92142# Fix: forceWritableToFinalized now working correctly\/*************************************************************************\n *\n * $RCSfile: cmtree.cxx,v $\n *\n * $Revision: 1.24 $\n *\n * last change: $Author: jb $ $Date: 2001-09-25 16:34:29 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#include \n\n#include \"subtree.hxx\"\n#ifndef CONFIGMGR_CHANGE_HXX\n#include \"change.hxx\"\n#endif\n#ifndef CONFIGMGR_TREECHANGELIST_HXX\n#include \"treechangelist.hxx\"\n#endif\n\n#ifndef CONFIGMGR_TREEPROVIDER_HXX\n#include \"treeprovider.hxx\"\n#endif\n#ifndef _CONFIGMGR_TREEACTIONS_HXX_\n#include \"treeactions.hxx\"\n#endif\n\n#ifndef _RTL_STRING_HXX_\n#include \n#endif\n#ifndef _RTL_USTRING_HXX_\n#include \n#endif\n\n#ifndef _OSL_DIAGNOSE_H_\n#include \n#endif\n\n#ifndef INCLUDED_DEQUE\n#include \n#define INCLUDED_DEQUE\n#endif\n#ifndef INCLUDED_VECTOR\n#include \n#define INCLUDED_VECTOR\n#endif\n#ifndef INCLUDED_IOSTREAM\n#include \n#define INCLUDED_IOSTREAM\n#endif\n#ifndef INCLUDED_EXCEPTION\n#include \n#define INCLUDED_EXCEPTION\n#endif\n#ifndef INCLUDED_SET\n#include \n#define INCLUDED_SET\n#endif\n\nusing namespace std;\nusing namespace rtl;\nusing namespace com::sun::star::uno;\n\nnamespace configmgr\n{\n\n\/\/ ------------------------ ChildListSet implementations ------------------------\n ChildListSet::ChildListSet(ChildListSet const& aSet)\n {\n for(ChildList::iterator it = aSet.GetSet().begin();\n it != aSet.GetSet().end();\n ++it)\n m_aChildList.insert(m_aChildList.end(), (*it)->clone());\n }\n ChildListSet::~ChildListSet()\n {\n for(ChildList::iterator it = m_aChildList.begin();\n it != m_aChildList.end();\n ++it)\n delete *it;\n }\n\n\n\/\/ ---------------------------- Node implementation ----------------------------\n\n INode::INode(configuration::Attributes _aAttr):m_aAttributes(_aAttr){}\n INode::INode(OUString const& aName, configuration::Attributes _aAttr)\n :m_aName(aName)\n ,m_aAttributes(_aAttr){}\n \/\/ CopyCTor will be create automatically\n\n INode::~INode() {}\n\n ISubtree* INode::asISubtree(){return NULL;}\n ISubtree const* INode::asISubtree() const {return NULL;}\n ValueNode* INode::asValueNode() {return NULL;}\n ValueNode const* INode::asValueNode() const {return NULL;}\n\n\n void INode::forceWritableToFinalized()\n {\n if (!m_aAttributes.bWritable)\n {\n m_aAttributes.bFinalized = true;\n m_aAttributes.bWritable = true;\n }\n }\n\n\/\/ ------------------------- SearchNode implementation -------------------------\n SearchNode::SearchNode():INode(configuration::Attributes()){}\n SearchNode::SearchNode(OUString const& aName)\n :INode(aName, configuration::Attributes()){}\n\n INode* SearchNode::clone() const {return new SearchNode(*this);}\n\n SearchNode::~SearchNode(){}\n\n \/\/==========================================================================\n \/\/= OPropagateLevels\n \/\/==========================================================================\n \/** fills a subtree with the correct level informations\n *\/\n struct OPropagateLevels : public NodeModification\n {\n protected:\n sal_Int32 nChildLevel;\n public:\n OPropagateLevels(sal_Int32 _nParentLevel)\n {\n nChildLevel = (ITreeProvider::ALL_LEVELS == _nParentLevel) ? ITreeProvider::ALL_LEVELS : _nParentLevel - 1;\n }\n virtual void handle(ValueNode&) { \/* not interested in value nodes *\/ }\n virtual void handle(ISubtree& _rSubtree)\n {\n if ((ITreeProvider::ALL_LEVELS == nChildLevel) || nChildLevel > _rSubtree.getLevel())\n _rSubtree.setLevel(nChildLevel);\n }\n };\n\n\n\/\/ -------------------------- ISubtree implementation --------------------------\n ISubtree* ISubtree::asISubtree() {return this;}\n ISubtree const* ISubtree::asISubtree() const {return this;}\n\n \/\/--------------------------------------------------------------------------\n void ISubtree::setLevel(sal_Int16 _nLevel)\n {\n m_nLevel = _nLevel;\n if (0 == _nLevel)\n \/\/ nothing more to do, this means \"nothing known about any children\"\n return;\n\n \/\/ forward the level number to any child subtrees we have\n OPropagateLevels aDeeperInto(_nLevel);\n aDeeperInto.applyToChildren(*this);\n }\n\n\/\/ --------------------------- Subtree implementation ---------------------------\n INode* Subtree::clone() const {return new Subtree(*this);}\n\n INode* Subtree::doGetChild(OUString const& aName) const\n {\n SearchNode searchObj(aName);\n\n#ifdef DEBUG\n for (ChildList::iterator it2 = m_aChildren.GetSet().begin();\n it2 != m_aChildren.GetSet().end();\n ++it2)\n {\n INode* pINode = *it2;\n OUString aName2 = pINode->getName();\n volatile int dummy = 0;\n }\n#endif\n\n ChildList::iterator it = m_aChildren.GetSet().find(&searchObj);\n if (it == m_aChildren.GetSet().end())\n return NULL;\n else\n return *it;\n }\n\n INode* Subtree::addChild(std::auto_ptr aNode) \/\/ takes ownership\n {\n OUString aName = aNode->getName();\n std::pair aInserted =\n m_aChildren.GetSet().insert(aNode.get());\n if (aInserted.second)\n aNode.release();\n return *aInserted.first;\n }\n\n ::std::auto_ptr Subtree::removeChild(OUString const& aName)\n {\n SearchNode searchObj(aName);\n ChildList::const_iterator it = m_aChildren.GetSet().find(&searchObj);\n\n ::std::auto_ptr aReturn;\n if (m_aChildren.GetSet().end() != it)\n {\n aReturn = ::std::auto_ptr(*it);\n m_aChildren.GetSet().erase(it);\n }\n return aReturn;\n }\n\n \/\/==========================================================================\n \/\/= OBuildChangeTree - historic\n \/\/==========================================================================\n \/** generates a change tree by comparing two trees\n *\/\n\/* struct OBuildChangeTree : public NodeModification\n {\n protected:\n SubtreeChange& m_rChangeList;\n INode* m_pCacheNode;\n\n public:\n OBuildChangeTree(SubtreeChange& rList, INode* pNode)\n :m_rChangeList(rList)\n ,m_pCacheNode(pNode)\n {\n }\n\n virtual void handle(ValueNode& _nNode)\n {\n OUString aNodeName = _nNode.getName();\n ISubtree* pTree = m_pCacheNode->asISubtree();\n OSL_ENSURE(pTree, \"OBuildChangeTree::handle : node must be a inner node!\");\n if (pTree)\n {\n INode* pChild = pTree->getChild(aNodeName);\n ValueNode* pValueNode = pChild ? pChild->asValueNode() : NULL;\n OSL_ENSURE(pValueNode, \"OBuildChangeTree::handle : node must be a value node!\");\n\n \/\/ if the values differ add a new change\n if (pValueNode && _nNode.getValue() != pValueNode->getValue())\n {\n ValueChange* pChange = new ValueChange(_nNode.getValue(), *pValueNode);\n m_rChangeList.addChange(::std::auto_ptr(pChange));\n }\n }\n }\n\n virtual void handle(ISubtree& _rSubtree)\n {\n OUString aNodeName = _rSubtree.getName();\n ISubtree* pTree = m_pCacheNode->asISubtree();\n OSL_ENSURE(pTree, \"OBuildChangeTree::handle : node must be a inner node!\");\n if (pTree)\n {\n INode* pChild = pTree->getChild(aNodeName);\n \/\/ node not in cache, so ignore it\n \/\/ later, when we get additions and removements within on transaction, then we have to care about\n if (pChild)\n {\n ISubtree* pSubTree = pChild->asISubtree();\n OSL_ENSURE(pSubTree, \"OBuildChangeTree::handle : node must be a inner node!\");\n \/\/ generate a new change\n\n SubtreeChange* pChange = new SubtreeChange(_rSubtree);\n OBuildChangeTree aNextLevel(*pChange, pSubTree);\n aNextLevel.applyToChildren(_rSubtree);\n\n \/\/ now count if there are any changes\n OChangeCounter aCounter;\n pChange->dispatch(aCounter);\n\n if (aCounter.nCount != 0)\n m_rChangeList.addChange(::std::auto_ptr(pChange));\n else\n delete pChange;\n }\n }\n }\n };\n\n*\/\n void Subtree::forEachChild(NodeAction& anAction) const {\n for(ChildList::const_iterator it = m_aChildren.GetSet().begin();\n it != m_aChildren.GetSet().end();\n ++it)\n (**it).dispatch(anAction);\n }\n\n void Subtree::forEachChild(NodeModification& anAction) {\n for(ChildList::iterator it = m_aChildren.GetSet().begin();\n it != m_aChildren.GetSet().end();\n ++it)\n (**it).dispatch(anAction);\n }\n\n\/\/ \/\/ -------------------------- ValueNode implementation --------------------------\n void ValueNode::check_init() \/\/ may throw in the future\n {\n m_aValuePair.check_init();\n }\n\n void ValueNode::init()\n {\n m_aValuePair.init();\n }\n\n\n void ValueNode::setValue(Any const& _aValue)\n {\n m_aValuePair.setFirst(_aValue);\n }\n\n void ValueNode::changeDefault(Any const& _aValue)\n {\n m_aValuePair.setSecond(_aValue);\n }\n\n void ValueNode::setDefault()\n {\n \/\/ PRE: ????\n \/\/ POST: isDefault() == true\n \/\/ OSL_ENSURE(false, \"ValueNode::setDefault(): this isn't really defined yet.\");\n \/\/ m_aValue = Any();\n \/\/ m_pFirst = NULL;\n }\n\n INode* ValueNode::clone() const\n {\n return new ValueNode(*this);\n }\n\n ValueNode* ValueNode::asValueNode() {return this;}\n ValueNode const* ValueNode::asValueNode() const {return this;}\n\n} \/\/ namespace configmgr\n\n\n<|endoftext|>"} {"text":"\/* * This file is part of meego-im-framework *\n *\n * Copyright (C) 2010 Nokia Corporation and\/or its subsidiary(-ies).\n * All rights reserved.\n * Contact: Nokia Corporation (directui@nokia.com)\n *\n * If you have questions regarding the use of this file, please contact\n * Nokia at directui@nokia.com.\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1 as published by the Free Software Foundation\n * and appearing in the file LICENSE.LGPL included in the packaging\n * of this file.\n *\/\n\n#include \"connectionfactory.h\"\n\n#ifdef HAVE_GLIB_DBUS\n#include \"glibdbusimserverproxy.h\"\n#include \"minputcontextglibdbusconnection.h\"\n#else\n#include \"dbusserverconnection.h\"\n#include \"dbusinputcontextconnection.h\"\n#endif\n\nnamespace Maliit {\nnamespace DBus {\n\nMImServerConnection *createServerConnectionWithDynamicAddress()\n{\n const QSharedPointer address(new Maliit::InputContext::DBus::DynamicAddress);\n#ifdef HAVE_GLIB_DBUS\n return new GlibDBusIMServerProxy(address);\n#else\n return new DBusServerConnection(address);\n#endif\n}\n\nMImServerConnection *createServerConnectionWithFixedAddress(const QString &fixedAddress)\n{\n const QSharedPointer address(new Maliit::InputContext::DBus::FixedAddress(fixedAddress));\n#ifdef HAVE_GLIB_DBUS\n return new GlibDBusIMServerProxy(address);\n#else\n return new DBusServerConnection(address);\n#endif\n}\n\nMInputContextConnection *createInputContextConnectionWithDynamicAddress()\n{\n#ifdef HAVE_GLIB_DBUS\n std::tr1::shared_ptr address(new Maliit::Server::DBus::DynamicAddress);\n return new MInputContextGlibDBusConnection(address, false);\n#else\n QSharedPointer address(new Maliit::Server::DBus::DynamicAddress);\n return new DBusInputContextConnection(address);\n#endif\n}\n\nMInputContextConnection *createInputContextConnectionWithFixedAddress(const QString &fixedAddress, bool allowAnonymous)\n{\n#ifdef HAVE_GLIB_DBUS\n std::tr1::shared_ptr address(new Maliit::Server::DBus::FixedAddress(fixedAddress));\n return new MInputContextGlibDBusConnection(address, allowAnonymous);\n#else\n QSharedPointer address(new Maliit::Server::DBus::FixedAddress(fixedAddress));\n return new DBusInputContextConnection(address);\n#endif\n}\n\n} \/\/ namespace DBus\n} \/\/ namespace Maliit\nFix unused parameter warning\/* * This file is part of meego-im-framework *\n *\n * Copyright (C) 2010 Nokia Corporation and\/or its subsidiary(-ies).\n * All rights reserved.\n * Contact: Nokia Corporation (directui@nokia.com)\n *\n * If you have questions regarding the use of this file, please contact\n * Nokia at directui@nokia.com.\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1 as published by the Free Software Foundation\n * and appearing in the file LICENSE.LGPL included in the packaging\n * of this file.\n *\/\n\n#include \"connectionfactory.h\"\n\n#ifdef HAVE_GLIB_DBUS\n#include \"glibdbusimserverproxy.h\"\n#include \"minputcontextglibdbusconnection.h\"\n#else\n#include \"dbusserverconnection.h\"\n#include \"dbusinputcontextconnection.h\"\n#endif\n\nnamespace Maliit {\nnamespace DBus {\n\nMImServerConnection *createServerConnectionWithDynamicAddress()\n{\n const QSharedPointer address(new Maliit::InputContext::DBus::DynamicAddress);\n#ifdef HAVE_GLIB_DBUS\n return new GlibDBusIMServerProxy(address);\n#else\n return new DBusServerConnection(address);\n#endif\n}\n\nMImServerConnection *createServerConnectionWithFixedAddress(const QString &fixedAddress)\n{\n const QSharedPointer address(new Maliit::InputContext::DBus::FixedAddress(fixedAddress));\n#ifdef HAVE_GLIB_DBUS\n return new GlibDBusIMServerProxy(address);\n#else\n return new DBusServerConnection(address);\n#endif\n}\n\nMInputContextConnection *createInputContextConnectionWithDynamicAddress()\n{\n#ifdef HAVE_GLIB_DBUS\n std::tr1::shared_ptr address(new Maliit::Server::DBus::DynamicAddress);\n return new MInputContextGlibDBusConnection(address, false);\n#else\n QSharedPointer address(new Maliit::Server::DBus::DynamicAddress);\n return new DBusInputContextConnection(address);\n#endif\n}\n\nMInputContextConnection *createInputContextConnectionWithFixedAddress(const QString &fixedAddress, bool allowAnonymous)\n{\n#ifdef HAVE_GLIB_DBUS\n std::tr1::shared_ptr address(new Maliit::Server::DBus::FixedAddress(fixedAddress));\n return new MInputContextGlibDBusConnection(address, allowAnonymous);\n#else\n Q_UNUSED(allowAnonymous);\n QSharedPointer address(new Maliit::Server::DBus::FixedAddress(fixedAddress));\n return new DBusInputContextConnection(address);\n#endif\n}\n\n} \/\/ namespace DBus\n} \/\/ namespace Maliit\n<|endoftext|>"} {"text":"\/*\n * Launch WAS child processes.\n *\n * author: Max Kellermann \n *\/\n\n#ifndef BENG_PROXY_WAS_LAUNCH_HXX\n#define BENG_PROXY_WAS_LAUNCH_HXX\n\n#include \"glibfwd.hxx\"\n\n#include \n\nstruct ChildOptions;\ntemplate struct ConstBuffer;\n\nstruct WasProcess {\n pid_t pid;\n int control_fd, input_fd, output_fd;\n\n void Close();\n};\n\nbool\nwas_launch(WasProcess *process,\n const char *executable_path,\n ConstBuffer args,\n ConstBuffer env,\n const ChildOptions &options,\n GError **error_r);\n\n#endif\nwas\/launch: auto-initialize attributes\/*\n * Launch WAS child processes.\n *\n * author: Max Kellermann \n *\/\n\n#ifndef BENG_PROXY_WAS_LAUNCH_HXX\n#define BENG_PROXY_WAS_LAUNCH_HXX\n\n#include \"glibfwd.hxx\"\n\n#include \n\nstruct ChildOptions;\ntemplate struct ConstBuffer;\n\nstruct WasProcess {\n pid_t pid = -1;\n int control_fd = -1, input_fd = -1, output_fd = -1;\n\n void Close();\n};\n\nbool\nwas_launch(WasProcess *process,\n const char *executable_path,\n ConstBuffer args,\n ConstBuffer env,\n const ChildOptions &options,\n GError **error_r);\n\n#endif\n<|endoftext|>"} {"text":"\/*******************************************************\n * Copyright (c) 2014, ArrayFire\n * All rights reserved.\n *\n * This file is distributed under 3-clause BSD license.\n * The complete license agreement can be obtained at:\n * http:\/\/arrayfire.com\/licenses\/BSD-3-Clause\n ********************************************************\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nusing std::vector;\nusing std::string;\nusing std::cout;\nusing std::endl;\nusing af::cfloat;\nusing af::cdouble;\n\ntemplate\nclass Resize : public ::testing::Test\n{\n public:\n virtual void SetUp() {\n subMat0.push_back(af_make_seq(0, 4, 1));\n subMat0.push_back(af_make_seq(2, 6, 1));\n subMat0.push_back(af_make_seq(0, 2, 1));\n }\n vector subMat0;\n};\n\ntemplate\nclass ResizeI : public ::testing::Test\n{\n public:\n virtual void SetUp() {\n subMat0.push_back(af_make_seq(0, 4, 1));\n subMat0.push_back(af_make_seq(2, 6, 1));\n subMat0.push_back(af_make_seq(0, 2, 1));\n\n subMat1.push_back(af_make_seq(0, 5, 1));\n subMat1.push_back(af_make_seq(0, 5, 1));\n subMat1.push_back(af_make_seq(0, 2, 1));\n }\n vector subMat0;\n vector subMat1;\n};\n\n\/\/ create a list of types to be tested\ntypedef ::testing::Types TestTypesF;\ntypedef ::testing::Types TestTypesI;\n\n\/\/ register the type list\nTYPED_TEST_CASE(Resize, TestTypesF);\nTYPED_TEST_CASE(ResizeI, TestTypesI);\n\ntemplate\nvoid resizeTest(string pTestFile, const unsigned resultIdx, const dim_type odim0, const dim_type odim1, const af_interp_type method, bool isSubRef = false, const vector * seqv = NULL)\n{\n if (noDoubleTests()) return;\n\n vector numDims;\n vector > in;\n vector > tests;\n readTests(pTestFile,numDims,in,tests);\n\n af::dim4 dims = numDims[0];\n\n af_array inArray = 0;\n af_array outArray = 0;\n af_array tempArray = 0;\n if (isSubRef) {\n\n ASSERT_EQ(AF_SUCCESS, af_create_array(&tempArray, &(in[0].front()), dims.ndims(), dims.get(), (af_dtype) af::dtype_traits::af_type));\n\n ASSERT_EQ(AF_SUCCESS, af_index(&inArray, tempArray, seqv->size(), &seqv->front()));\n } else {\n ASSERT_EQ(AF_SUCCESS, af_create_array(&inArray, &(in[0].front()), dims.ndims(), dims.get(), (af_dtype) af::dtype_traits::af_type));\n }\n\n ASSERT_EQ(AF_SUCCESS, af_resize(&outArray, inArray, odim0, odim1, method));\n\n \/\/ Get result\n af::dim4 odims(odim0, odim1, dims[2], dims[3]);\n T* outData = new T[odims.elements()];\n ASSERT_EQ(AF_SUCCESS, af_get_data_ptr((void*)outData, outArray));\n\n \/\/ Compare result\n size_t nElems = tests[resultIdx].size();\n for (size_t elIter = 0; elIter < nElems; ++elIter) {\n ASSERT_NEAR(tests[resultIdx][elIter], outData[elIter], 0.0001) << \"at: \" << elIter << std::endl;\n }\n\n \/\/ Delete\n delete[] outData;\n\n if(inArray != 0) af_destroy_array(inArray);\n if(outArray != 0) af_destroy_array(outArray);\n if(tempArray != 0) af_destroy_array(tempArray);\n}\n\nTYPED_TEST(Resize, Resize3CSquareUpNearest)\n{\n resizeTest(string(TEST_DIR\"\/resize\/square.test\"), 0, 16, 16, AF_INTERP_NEAREST);\n}\n\nTYPED_TEST(Resize, Resize3CSquareUpLinear)\n{\n resizeTest(string(TEST_DIR\"\/resize\/square.test\"), 1, 16, 16, AF_INTERP_BILINEAR);\n}\n\nTYPED_TEST(Resize, Resize3CSquareDownNearest)\n{\n resizeTest(string(TEST_DIR\"\/resize\/square.test\"), 2, 4, 4, AF_INTERP_NEAREST);\n}\n\nTYPED_TEST(Resize, Resize3CSquareDownLinear)\n{\n resizeTest(string(TEST_DIR\"\/resize\/square.test\"), 3, 4, 4, AF_INTERP_BILINEAR);\n}\n\nTYPED_TEST(Resize, Resize3CSquareUpNearestSubref)\n{\n resizeTest(string(TEST_DIR\"\/resize\/square.test\"), 4, 10, 10, AF_INTERP_NEAREST,\n true, &(this->subMat0));\n}\n\nTYPED_TEST(Resize, Resize3CSquareUpLinearSubref)\n{\n resizeTest(string(TEST_DIR\"\/resize\/square.test\"), 5, 10, 10, AF_INTERP_BILINEAR,\n true, &(this->subMat0));\n}\n\nTYPED_TEST(Resize, Resize3CSquareDownNearestSubref)\n{\n resizeTest(string(TEST_DIR\"\/resize\/square.test\"), 6, 3, 3, AF_INTERP_NEAREST,\n true, &(this->subMat0));\n}\n\nTYPED_TEST(Resize, Resize3CSquareDownLinearSubref)\n{\n resizeTest(string(TEST_DIR\"\/resize\/square.test\"), 7, 3, 3, AF_INTERP_BILINEAR,\n true, &(this->subMat0));\n}\n\nTYPED_TEST(Resize, Resize1CRectangleUpNearest)\n{\n resizeTest(string(TEST_DIR\"\/resize\/rectangle.test\"), 0, 12, 16, AF_INTERP_NEAREST);\n}\n\nTYPED_TEST(Resize, Resize1CRectangleUpLinear)\n{\n resizeTest(string(TEST_DIR\"\/resize\/rectangle.test\"), 1, 12, 16, AF_INTERP_BILINEAR);\n}\n\nTYPED_TEST(Resize, Resize1CRectangleDownNearest)\n{\n resizeTest(string(TEST_DIR\"\/resize\/rectangle.test\"), 2, 6, 2, AF_INTERP_NEAREST);\n}\n\nTYPED_TEST(Resize, Resize1CRectangleDownLinear)\n{\n resizeTest(string(TEST_DIR\"\/resize\/rectangle.test\"), 3, 6, 2, AF_INTERP_BILINEAR);\n}\n\nTYPED_TEST(ResizeI, Resize3CSquareUpNearest)\n{\n resizeTest(string(TEST_DIR\"\/resize\/square.test\"), 0, 16, 16, AF_INTERP_NEAREST);\n}\n\nTYPED_TEST(ResizeI, Resize3CSquareUpLinear)\n{\n resizeTest(string(TEST_DIR\"\/resize\/square.test\"), 1, 16, 16, AF_INTERP_BILINEAR);\n}\n\nTYPED_TEST(ResizeI, Resize3CSquareDownNearest)\n{\n resizeTest(string(TEST_DIR\"\/resize\/square.test\"), 2, 4, 4, AF_INTERP_NEAREST);\n}\n\nTYPED_TEST(ResizeI, Resize3CSquareDownLinear)\n{\n resizeTest(string(TEST_DIR\"\/resize\/square.test\"), 3, 4, 4, AF_INTERP_BILINEAR);\n}\n\nTYPED_TEST(ResizeI, Resize3CSquareUpNearestSubref)\n{\n resizeTest(string(TEST_DIR\"\/resize\/square.test\"), 4, 10, 10, AF_INTERP_NEAREST,\n true, &(this->subMat0));\n}\n\nTYPED_TEST(ResizeI, Resize3CSquareUpLinearSubref)\n{\n resizeTest(string(TEST_DIR\"\/resize\/square.test\"), 5, 10, 10, AF_INTERP_BILINEAR,\n true, &(this->subMat0));\n}\n\nTYPED_TEST(ResizeI, Resize3CSquareDownNearestSubref)\n{\n resizeTest(string(TEST_DIR\"\/resize\/square.test\"), 6, 3, 3, AF_INTERP_NEAREST,\n true, &(this->subMat0));\n}\n\nTYPED_TEST(ResizeI, Resize3CSquareDownLinearSubref)\n{\n resizeTest(string(TEST_DIR\"\/resize\/square.test\"), 8, 3, 3, AF_INTERP_BILINEAR,\n true, &(this->subMat1));\n}\n\nTYPED_TEST(Resize, Resize1CLargeUpNearest)\n{\n resizeTest(string(TEST_DIR\"\/resize\/large.test\"), 0, 256, 256, AF_INTERP_NEAREST);\n}\n\nTYPED_TEST(Resize, Resize1CLargeUpLinear)\n{\n resizeTest(string(TEST_DIR\"\/resize\/large.test\"), 1, 256, 256, AF_INTERP_BILINEAR);\n}\n\nTYPED_TEST(Resize, Resize1CLargeDownNearest)\n{\n resizeTest(string(TEST_DIR\"\/resize\/large.test\"), 2, 32, 32, AF_INTERP_NEAREST);\n}\n\nTYPED_TEST(Resize, Resize1CLargeDownLinear)\n{\n resizeTest(string(TEST_DIR\"\/resize\/large.test\"), 3, 32, 32, AF_INTERP_BILINEAR);\n}\n\nTYPED_TEST(ResizeI, Resize1CLargeUpNearest)\n{\n resizeTest(string(TEST_DIR\"\/resize\/large.test\"), 0, 256, 256, AF_INTERP_NEAREST);\n}\n\nTYPED_TEST(ResizeI, Resize1CLargeUpLinear)\n{\n resizeTest(string(TEST_DIR\"\/resize\/large.test\"), 1, 256, 256, AF_INTERP_BILINEAR);\n}\n\nTYPED_TEST(ResizeI, Resize1CLargeDownNearest)\n{\n resizeTest(string(TEST_DIR\"\/resize\/large.test\"), 2, 32, 32, AF_INTERP_NEAREST);\n}\n\nTYPED_TEST(ResizeI, Resize1CLargeDownLinear)\n{\n resizeTest(string(TEST_DIR\"\/resize\/large.test\"), 3, 32, 32, AF_INTERP_BILINEAR);\n}\n\ntemplate\nvoid resizeArgsTest(af_err err, string pTestFile, const af::dim4 odims, const af_interp_type method)\n{\n if (noDoubleTests()) return;\n\n vector numDims;\n vector > in;\n vector > tests;\n readTests(pTestFile,numDims,in,tests);\n\n af::dim4 dims = numDims[0];\n\n af_array inArray = 0;\n af_array outArray = 0;\n ASSERT_EQ(AF_SUCCESS, af_create_array(&inArray, &(in[0].front()), dims.ndims(), dims.get(), (af_dtype) af::dtype_traits::af_type));\n\n ASSERT_EQ(err, af_resize(&outArray, inArray, odims[0], odims[1], method));\n\n if(inArray != 0) af_destroy_array(inArray);\n if(outArray != 0) af_destroy_array(outArray);\n}\n\nTYPED_TEST(Resize,InvalidArgsDims0)\n{\n af::dim4 dims(0, 5, 2, 1);\n resizeArgsTest(AF_ERR_SIZE, string(TEST_DIR\"\/resize\/square.test\"), dims, AF_INTERP_BILINEAR);\n}\n\nTYPED_TEST(Resize,InvalidArgsMethod)\n{\n af::dim4 dims(10, 10, 1, 1);\n resizeArgsTest(AF_ERR_ARG, string(TEST_DIR\"\/resize\/square.test\"), dims, AF_INTERP_CUBIC);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ CPP \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\nTEST(Resize, CPP)\n{\n if (noDoubleTests()) return;\n\n vector numDims;\n vector > in;\n vector > tests;\n readTests(string(TEST_DIR\"\/resize\/square.test\"),numDims,in,tests);\n\n af::dim4 dims = numDims[0];\n af::array input(dims, &(in[0].front()));\n af::array output = af::resize(input, 16, 16);\n\n \/\/ Get result\n af::dim4 odims(16, 16, dims[2], dims[3]);\n float* outData = new float[odims.elements()];\n output.host((void*)outData);\n\n \/\/ Compare result\n size_t nElems = tests[0].size();\n for (size_t elIter = 0; elIter < nElems; ++elIter) {\n ASSERT_NEAR(tests[0][elIter], outData[elIter], 0.0001) << \"at: \" << elIter << std::endl;\n }\n\n \/\/ Delete\n delete[] outData;\n}\nIncrease resize() test coverage\/*******************************************************\n * Copyright (c) 2014, ArrayFire\n * All rights reserved.\n *\n * This file is distributed under 3-clause BSD license.\n * The complete license agreement can be obtained at:\n * http:\/\/arrayfire.com\/licenses\/BSD-3-Clause\n ********************************************************\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nusing std::vector;\nusing std::string;\nusing std::cout;\nusing std::endl;\nusing af::cfloat;\nusing af::cdouble;\n\ntemplate\nclass Resize : public ::testing::Test\n{\n public:\n virtual void SetUp() {\n subMat0.push_back(af_make_seq(0, 4, 1));\n subMat0.push_back(af_make_seq(2, 6, 1));\n subMat0.push_back(af_make_seq(0, 2, 1));\n }\n vector subMat0;\n};\n\ntemplate\nclass ResizeI : public ::testing::Test\n{\n public:\n virtual void SetUp() {\n subMat0.push_back(af_make_seq(0, 4, 1));\n subMat0.push_back(af_make_seq(2, 6, 1));\n subMat0.push_back(af_make_seq(0, 2, 1));\n\n subMat1.push_back(af_make_seq(0, 5, 1));\n subMat1.push_back(af_make_seq(0, 5, 1));\n subMat1.push_back(af_make_seq(0, 2, 1));\n }\n vector subMat0;\n vector subMat1;\n};\n\n\/\/ create a list of types to be tested\ntypedef ::testing::Types TestTypesF;\ntypedef ::testing::Types TestTypesI;\n\n\/\/ register the type list\nTYPED_TEST_CASE(Resize, TestTypesF);\nTYPED_TEST_CASE(ResizeI, TestTypesI);\n\nTYPED_TEST(Resize, InvalidDims)\n{\n if (noDoubleTests()) return;\n\n vector in(8,8);\n\n af_array inArray = 0;\n af_array outArray = 0;\n\n af::dim4 dims = af::dim4(8,8,1,1);\n\n ASSERT_EQ(AF_SUCCESS, af_create_array(&inArray, &in.front(), dims.ndims(), dims.get(),\n (af_dtype) af::dtype_traits::af_type));\n ASSERT_EQ(AF_ERR_SIZE, af_resize(&outArray, inArray, 0, 0, AF_INTERP_NEAREST));\n ASSERT_EQ(AF_SUCCESS, af_destroy_array(inArray));\n}\n\nTYPED_TEST(Resize, InvalidType)\n{\n if (noDoubleTests()) return;\n\n vector in(16,8);\n\n af_array inArray = 0;\n af_array outArray = 0;\n\n af::dim4 dims = af::dim4(8,8,1,1);\n\n ASSERT_EQ(AF_SUCCESS, af_create_array(&inArray, &in.front(), dims.ndims(), dims.get(),\n (af_dtype) af::dtype_traits::af_type));\n ASSERT_EQ(AF_ERR_INVALID_TYPE, af_resize(&outArray, inArray, 16, 16, AF_INTERP_NEAREST));\n ASSERT_EQ(AF_SUCCESS, af_destroy_array(inArray));\n}\n\ntemplate\nvoid resizeTest(string pTestFile, const unsigned resultIdx, const dim_type odim0, const dim_type odim1, const af_interp_type method, bool isSubRef = false, const vector * seqv = NULL)\n{\n if (noDoubleTests()) return;\n\n vector numDims;\n vector > in;\n vector > tests;\n readTests(pTestFile,numDims,in,tests);\n\n af::dim4 dims = numDims[0];\n\n af_array inArray = 0;\n af_array outArray = 0;\n af_array tempArray = 0;\n if (isSubRef) {\n\n ASSERT_EQ(AF_SUCCESS, af_create_array(&tempArray, &(in[0].front()), dims.ndims(), dims.get(), (af_dtype) af::dtype_traits::af_type));\n\n ASSERT_EQ(AF_SUCCESS, af_index(&inArray, tempArray, seqv->size(), &seqv->front()));\n } else {\n ASSERT_EQ(AF_SUCCESS, af_create_array(&inArray, &(in[0].front()), dims.ndims(), dims.get(), (af_dtype) af::dtype_traits::af_type));\n }\n\n ASSERT_EQ(AF_SUCCESS, af_resize(&outArray, inArray, odim0, odim1, method));\n\n \/\/ Get result\n af::dim4 odims(odim0, odim1, dims[2], dims[3]);\n T* outData = new T[odims.elements()];\n ASSERT_EQ(AF_SUCCESS, af_get_data_ptr((void*)outData, outArray));\n\n \/\/ Compare result\n size_t nElems = tests[resultIdx].size();\n for (size_t elIter = 0; elIter < nElems; ++elIter) {\n ASSERT_NEAR(tests[resultIdx][elIter], outData[elIter], 0.0001) << \"at: \" << elIter << std::endl;\n }\n\n \/\/ Delete\n delete[] outData;\n\n if(inArray != 0) af_destroy_array(inArray);\n if(outArray != 0) af_destroy_array(outArray);\n if(tempArray != 0) af_destroy_array(tempArray);\n}\n\nTYPED_TEST(Resize, Resize3CSquareUpNearest)\n{\n resizeTest(string(TEST_DIR\"\/resize\/square.test\"), 0, 16, 16, AF_INTERP_NEAREST);\n}\n\nTYPED_TEST(Resize, Resize3CSquareUpLinear)\n{\n resizeTest(string(TEST_DIR\"\/resize\/square.test\"), 1, 16, 16, AF_INTERP_BILINEAR);\n}\n\nTYPED_TEST(Resize, Resize3CSquareDownNearest)\n{\n resizeTest(string(TEST_DIR\"\/resize\/square.test\"), 2, 4, 4, AF_INTERP_NEAREST);\n}\n\nTYPED_TEST(Resize, Resize3CSquareDownLinear)\n{\n resizeTest(string(TEST_DIR\"\/resize\/square.test\"), 3, 4, 4, AF_INTERP_BILINEAR);\n}\n\nTYPED_TEST(Resize, Resize3CSquareUpNearestSubref)\n{\n resizeTest(string(TEST_DIR\"\/resize\/square.test\"), 4, 10, 10, AF_INTERP_NEAREST,\n true, &(this->subMat0));\n}\n\nTYPED_TEST(Resize, Resize3CSquareUpLinearSubref)\n{\n resizeTest(string(TEST_DIR\"\/resize\/square.test\"), 5, 10, 10, AF_INTERP_BILINEAR,\n true, &(this->subMat0));\n}\n\nTYPED_TEST(Resize, Resize3CSquareDownNearestSubref)\n{\n resizeTest(string(TEST_DIR\"\/resize\/square.test\"), 6, 3, 3, AF_INTERP_NEAREST,\n true, &(this->subMat0));\n}\n\nTYPED_TEST(Resize, Resize3CSquareDownLinearSubref)\n{\n resizeTest(string(TEST_DIR\"\/resize\/square.test\"), 7, 3, 3, AF_INTERP_BILINEAR,\n true, &(this->subMat0));\n}\n\nTYPED_TEST(Resize, Resize1CRectangleUpNearest)\n{\n resizeTest(string(TEST_DIR\"\/resize\/rectangle.test\"), 0, 12, 16, AF_INTERP_NEAREST);\n}\n\nTYPED_TEST(Resize, Resize1CRectangleUpLinear)\n{\n resizeTest(string(TEST_DIR\"\/resize\/rectangle.test\"), 1, 12, 16, AF_INTERP_BILINEAR);\n}\n\nTYPED_TEST(Resize, Resize1CRectangleDownNearest)\n{\n resizeTest(string(TEST_DIR\"\/resize\/rectangle.test\"), 2, 6, 2, AF_INTERP_NEAREST);\n}\n\nTYPED_TEST(Resize, Resize1CRectangleDownLinear)\n{\n resizeTest(string(TEST_DIR\"\/resize\/rectangle.test\"), 3, 6, 2, AF_INTERP_BILINEAR);\n}\n\nTYPED_TEST(ResizeI, Resize3CSquareUpNearest)\n{\n resizeTest(string(TEST_DIR\"\/resize\/square.test\"), 0, 16, 16, AF_INTERP_NEAREST);\n}\n\nTYPED_TEST(ResizeI, Resize3CSquareUpLinear)\n{\n resizeTest(string(TEST_DIR\"\/resize\/square.test\"), 1, 16, 16, AF_INTERP_BILINEAR);\n}\n\nTYPED_TEST(ResizeI, Resize3CSquareDownNearest)\n{\n resizeTest(string(TEST_DIR\"\/resize\/square.test\"), 2, 4, 4, AF_INTERP_NEAREST);\n}\n\nTYPED_TEST(ResizeI, Resize3CSquareDownLinear)\n{\n resizeTest(string(TEST_DIR\"\/resize\/square.test\"), 3, 4, 4, AF_INTERP_BILINEAR);\n}\n\nTYPED_TEST(ResizeI, Resize3CSquareUpNearestSubref)\n{\n resizeTest(string(TEST_DIR\"\/resize\/square.test\"), 4, 10, 10, AF_INTERP_NEAREST,\n true, &(this->subMat0));\n}\n\nTYPED_TEST(ResizeI, Resize3CSquareUpLinearSubref)\n{\n resizeTest(string(TEST_DIR\"\/resize\/square.test\"), 5, 10, 10, AF_INTERP_BILINEAR,\n true, &(this->subMat0));\n}\n\nTYPED_TEST(ResizeI, Resize3CSquareDownNearestSubref)\n{\n resizeTest(string(TEST_DIR\"\/resize\/square.test\"), 6, 3, 3, AF_INTERP_NEAREST,\n true, &(this->subMat0));\n}\n\nTYPED_TEST(ResizeI, Resize3CSquareDownLinearSubref)\n{\n resizeTest(string(TEST_DIR\"\/resize\/square.test\"), 8, 3, 3, AF_INTERP_BILINEAR,\n true, &(this->subMat1));\n}\n\nTYPED_TEST(Resize, Resize1CLargeUpNearest)\n{\n resizeTest(string(TEST_DIR\"\/resize\/large.test\"), 0, 256, 256, AF_INTERP_NEAREST);\n}\n\nTYPED_TEST(Resize, Resize1CLargeUpLinear)\n{\n resizeTest(string(TEST_DIR\"\/resize\/large.test\"), 1, 256, 256, AF_INTERP_BILINEAR);\n}\n\nTYPED_TEST(Resize, Resize1CLargeDownNearest)\n{\n resizeTest(string(TEST_DIR\"\/resize\/large.test\"), 2, 32, 32, AF_INTERP_NEAREST);\n}\n\nTYPED_TEST(Resize, Resize1CLargeDownLinear)\n{\n resizeTest(string(TEST_DIR\"\/resize\/large.test\"), 3, 32, 32, AF_INTERP_BILINEAR);\n}\n\nTYPED_TEST(ResizeI, Resize1CLargeUpNearest)\n{\n resizeTest(string(TEST_DIR\"\/resize\/large.test\"), 0, 256, 256, AF_INTERP_NEAREST);\n}\n\nTYPED_TEST(ResizeI, Resize1CLargeUpLinear)\n{\n resizeTest(string(TEST_DIR\"\/resize\/large.test\"), 1, 256, 256, AF_INTERP_BILINEAR);\n}\n\nTYPED_TEST(ResizeI, Resize1CLargeDownNearest)\n{\n resizeTest(string(TEST_DIR\"\/resize\/large.test\"), 2, 32, 32, AF_INTERP_NEAREST);\n}\n\nTYPED_TEST(ResizeI, Resize1CLargeDownLinear)\n{\n resizeTest(string(TEST_DIR\"\/resize\/large.test\"), 3, 32, 32, AF_INTERP_BILINEAR);\n}\n\ntemplate\nvoid resizeArgsTest(af_err err, string pTestFile, const af::dim4 odims, const af_interp_type method)\n{\n if (noDoubleTests()) return;\n\n vector numDims;\n vector > in;\n vector > tests;\n readTests(pTestFile,numDims,in,tests);\n\n af::dim4 dims = numDims[0];\n\n af_array inArray = 0;\n af_array outArray = 0;\n ASSERT_EQ(AF_SUCCESS, af_create_array(&inArray, &(in[0].front()), dims.ndims(), dims.get(), (af_dtype) af::dtype_traits::af_type));\n\n ASSERT_EQ(err, af_resize(&outArray, inArray, odims[0], odims[1], method));\n\n if(inArray != 0) af_destroy_array(inArray);\n if(outArray != 0) af_destroy_array(outArray);\n}\n\nTYPED_TEST(Resize,InvalidArgsDims0)\n{\n af::dim4 dims(0, 5, 2, 1);\n resizeArgsTest(AF_ERR_SIZE, string(TEST_DIR\"\/resize\/square.test\"), dims, AF_INTERP_BILINEAR);\n}\n\nTYPED_TEST(Resize,InvalidArgsMethod)\n{\n af::dim4 dims(10, 10, 1, 1);\n resizeArgsTest(AF_ERR_ARG, string(TEST_DIR\"\/resize\/square.test\"), dims, AF_INTERP_CUBIC);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ CPP \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\nTEST(Resize, CPP)\n{\n if (noDoubleTests()) return;\n\n vector numDims;\n vector > in;\n vector > tests;\n readTests(string(TEST_DIR\"\/resize\/square.test\"),numDims,in,tests);\n\n af::dim4 dims = numDims[0];\n af::array input(dims, &(in[0].front()));\n af::array output = af::resize(input, 16, 16);\n\n \/\/ Get result\n af::dim4 odims(16, 16, dims[2], dims[3]);\n float* outData = new float[odims.elements()];\n output.host((void*)outData);\n\n \/\/ Compare result\n size_t nElems = tests[0].size();\n for (size_t elIter = 0; elIter < nElems; ++elIter) {\n ASSERT_NEAR(tests[0][elIter], outData[elIter], 0.0001) << \"at: \" << elIter << std::endl;\n }\n\n \/\/ Delete\n delete[] outData;\n}\n\nTEST(ResizeScale1, CPP)\n{\n if (noDoubleTests()) return;\n\n vector numDims;\n vector > in;\n vector > tests;\n readTests(string(TEST_DIR\"\/resize\/square.test\"),numDims,in,tests);\n\n af::dim4 dims = numDims[0];\n af::array input(dims, &(in[0].front()));\n af::array output = af::resize(2.f, input);\n\n \/\/ Get result\n af::dim4 odims(16, 16, dims[2], dims[3]);\n float* outData = new float[odims.elements()];\n output.host((void*)outData);\n\n \/\/ Compare result\n size_t nElems = tests[0].size();\n for (size_t elIter = 0; elIter < nElems; ++elIter) {\n ASSERT_NEAR(tests[0][elIter], outData[elIter], 0.0001) << \"at: \" << elIter << std::endl;\n }\n\n \/\/ Delete\n delete[] outData;\n}\n\nTEST(ResizeScale2, CPP)\n{\n if (noDoubleTests()) return;\n\n vector numDims;\n vector > in;\n vector > tests;\n readTests(string(TEST_DIR\"\/resize\/square.test\"),numDims,in,tests);\n\n af::dim4 dims = numDims[0];\n af::array input(dims, &(in[0].front()));\n af::array output = af::resize(2.f, 2.f, input);\n\n \/\/ Get result\n af::dim4 odims(16, 16, dims[2], dims[3]);\n float* outData = new float[odims.elements()];\n output.host((void*)outData);\n\n \/\/ Compare result\n size_t nElems = tests[0].size();\n for (size_t elIter = 0; elIter < nElems; ++elIter) {\n ASSERT_NEAR(tests[0][elIter], outData[elIter], 0.0001) << \"at: \" << elIter << std::endl;\n }\n\n \/\/ Delete\n delete[] outData;\n}\n<|endoftext|>"} {"text":"\/\/ This file is part of Eigen, a lightweight C++ template library\n\/\/ for linear algebra.\n\/\/\n\/\/ Copyright (C) 2008 Gael Guennebaud \n\/\/\n\/\/ This Source Code Form is subject to the terms of the Mozilla\n\/\/ Public License v. 2.0. If a copy of the MPL was not distributed\n\/\/ with this file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n\n#include \"main.h\"\n\ntemplate void verifySizeOf(const MatrixType&)\n{\n typedef typename MatrixType::Scalar Scalar;\n if (MatrixType::RowsAtCompileTime!=Dynamic && MatrixType::ColsAtCompileTime!=Dynamic)\n VERIFY(std::ptrdiff_t(sizeof(MatrixType))==std::ptrdiff_t(sizeof(Scalar))*std::ptrdiff_t(MatrixType::SizeAtCompileTime));\n else\n VERIFY(sizeof(MatrixType)==sizeof(Scalar*) + 2 * sizeof(typename MatrixType::Index));\n}\n\nvoid test_sizeof()\n{\n CALL_SUBTEST(verifySizeOf(Matrix()) );\n CALL_SUBTEST(verifySizeOf(Matrix4d()) );\n CALL_SUBTEST(verifySizeOf(Matrix()) );\n CALL_SUBTEST(verifySizeOf(Matrix()) );\n CALL_SUBTEST(verifySizeOf(MatrixXcf(3, 3)) );\n CALL_SUBTEST(verifySizeOf(MatrixXi(8, 12)) );\n CALL_SUBTEST(verifySizeOf(MatrixXcd(20, 20)) );\n CALL_SUBTEST(verifySizeOf(Matrix()) );\n \n VERIFY(sizeof(std::complex) == 2*sizeof(float));\n VERIFY(sizeof(std::complex) == 2*sizeof(double));\n}\nExtend sizeof unit test\/\/ This file is part of Eigen, a lightweight C++ template library\n\/\/ for linear algebra.\n\/\/\n\/\/ Copyright (C) 2008 Gael Guennebaud \n\/\/\n\/\/ This Source Code Form is subject to the terms of the Mozilla\n\/\/ Public License v. 2.0. If a copy of the MPL was not distributed\n\/\/ with this file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n\n#include \"main.h\"\n\ntemplate void verifySizeOf(const MatrixType&)\n{\n typedef typename MatrixType::Scalar Scalar;\n if (MatrixType::RowsAtCompileTime!=Dynamic && MatrixType::ColsAtCompileTime!=Dynamic)\n VERIFY(std::ptrdiff_t(sizeof(MatrixType))==std::ptrdiff_t(sizeof(Scalar))*std::ptrdiff_t(MatrixType::SizeAtCompileTime));\n else\n VERIFY(sizeof(MatrixType)==sizeof(Scalar*) + 2 * sizeof(typename MatrixType::Index));\n}\n\nvoid test_sizeof()\n{\n CALL_SUBTEST(verifySizeOf(Matrix()) );\n CALL_SUBTEST(verifySizeOf(Vector2d()) );\n CALL_SUBTEST(verifySizeOf(Vector4f()) );\n CALL_SUBTEST(verifySizeOf(Matrix4d()) );\n CALL_SUBTEST(verifySizeOf(Matrix()) );\n CALL_SUBTEST(verifySizeOf(Matrix()) );\n CALL_SUBTEST(verifySizeOf(MatrixXcf(3, 3)) );\n CALL_SUBTEST(verifySizeOf(MatrixXi(8, 12)) );\n CALL_SUBTEST(verifySizeOf(MatrixXcd(20, 20)) );\n CALL_SUBTEST(verifySizeOf(Matrix()) );\n \n VERIFY(sizeof(std::complex) == 2*sizeof(float));\n VERIFY(sizeof(std::complex) == 2*sizeof(double));\n}\n<|endoftext|>"} {"text":"#include \n#include \"HCIDumpParser.h\"\n#include \"BeaconEventConsumer.h\"\n\n\/\/ Uncomment to publish the raw byte[] for the beacon, otherwise, properties are sent\n\/\/#define SEND_BINARY_DATA\n\nextern \"C\" bool stop_scan_frames;\n\nstatic void generateTestEvents(EventExchanger *exchanger) {\n printf(\"generateTestEvents, starting...\\n\");\n beacon_info event;\n int count = 0;\n try {\n bool running = true;\n while (running) {\n count++;\n int32_t minor = count % 150;\n sprintf(event.uuid, \"UUID-%.12d\", minor);\n event.minor = minor;\n event.rssi = -50 - count % 7;\n event.time = EventsWindow::currentMilliseconds();\n bool stop = beacon_event_callback(&event);\n running = !stop;\n this_thread::sleep_for(chrono::milliseconds(10));\n }\n } catch(exception& e) {\n printf(\"generateTestEvents failure, %s\\n\", e.what());\n }\n stop_scan_frames = true;\n printf(\"generateTestEvents, exiting\\n\");\n}\n\nvoid HCIDumpParser::processHCI(HCIDumpCommand &parseCommand) {\n HCIDumpParser::parseCommand = parseCommand;\n eventConsumer.setParseCommand(parseCommand);\n string clientID(parseCommand.getClientID());\n if (clientID.empty())\n clientID = parseCommand.getScannerID();\n timeWindow.reset(parseCommand.getAnalyzeWindow());\n \/\/ Setup the status information\n statusInformation->setScannerID(parseCommand.getScannerID());\n statusInformation->setStatusInterval(parseCommand.getStatusInterval());\n statusInformation->setStatusQueue(parseCommand.getStatusQueue());\n\n if (parseCommand.isAnalyzeMode()) {\n printf(\"Running in analyze mode, window=%d seconds, begin=%lld\\n\", parseCommand.getAnalyzeWindow(),\n timeWindow.getBegin());\n }\n else if (!parseCommand.isSkipPublish()) {\n publisher.reset(MsgPublisher::create(parseCommand.getPubType(), parseCommand.getBrokerURL(), clientID, \"\", \"\"));\n publisher->setUseTopics(!parseCommand.isUseQueues());\n printf(\"setUseTopics: %s\\n\", publisher->isUseTopics() ? \"true\" : \"false\");\n publisher->setDestinationName(parseCommand.getDestinationName());\n if (batchCount > 0) {\n publisher->setUseTransactions(true);\n printf(\"Enabled transactions\\n\");\n }\n publisher->start(parseCommand.isAsyncMode());\n\n \/\/ Create a thread for the consumer unless running in battery test mode\n if(!parseCommand.isBatteryTestMode()) {\n eventExchanger.reset(new EventExchanger);\n eventConsumer.init(eventExchanger, publisher, statusInformation);\n consumerThread.reset(new thread(&BeaconEventConsumer::publishEvents, &eventConsumer));\n printf(\"Started event consumer thread\\n\");\n }\n }\n else {\n printf(\"Skipping publish of parsed beacons\\n\");\n }\n\n \/\/ If the status interval is > 0, start the health status monitor\n if(parseCommand.getStatusInterval() > 0) {\n statusMonitor.start(publisher, statusInformation);\n }\n\n if(parseCommand.isGenerateTestData()) {\n \/\/ Generate test data\n thread testThread(generateTestEvents, eventExchanger.get());\n testThread.detach();\n }\n\n \/\/ Scan\n char cdev = parseCommand.getHciDev().at(parseCommand.getHciDev().size() - 1);\n int device = cdev - '0';\n scan_frames(device, beacon_event_callback);\n\n \/\/ Join the consumerThread if it was\n eventConsumer.setRunning(false);\n if(consumerThread && consumerThread->joinable()) {\n printf(\"Joining the consumer thread...\\n\");\n consumerThread->join();\n printf(\"done\\n\");\n }\n\n \/\/ Stop the status monitor\n statusMonitor.stop();\n}\n\nvoid HCIDumpParser::beaconEvent(const beacon_info &info) {\n \/\/ Check for heartbeat\n bool isHeartbeat = scannerUUID.compare(info.uuid) == 0;\n if(parseCommand.isBatteryTestMode()) {\n \/\/ Send the raw unaveraged heartbeat info, or ignore non-heartbeat events\n if(isHeartbeat)\n sendRawHeartbeat(info);\n return;\n }\n\n \/\/ Merge the event into the current time window\n shared_ptr bucket = timeWindow.addEvent(info, isHeartbeat);\n statusInformation->addEvent(info, isHeartbeat);\n \/\/ Now handle the bucket if a new one has been created\n if (bucket) {\n if (!parseCommand.isSkipPublish()) {\n eventExchanger->putEvent(bucket);\n }\n else {\n if (parseCommand.isAnalyzeMode()) {\n printBeaconCounts(bucket);\n } else {\n Beacon beacon(parseCommand.getScannerID(), info.uuid, info.code, info.manufacturer, info.major,\n info.minor, info.power, info.calibrated_power, info.rssi, info.time);\n const char *info = isHeartbeat ? \"heartbeat\" : \"event\";\n if (!isHeartbeat || (isHeartbeat && !parseCommand.isSkipHeartbeat()))\n printBeaconCounts(beacon, bucket);\n }\n }\n \/\/ Display either the closest beacon or status\n if(scannerView) {\n if(scannerView->isDisplayBeaconsMode())\n displayClosestBeacon(bucket);\n else\n displayStatus();\n }\n }\n}\n\nvoid HCIDumpParser::cleanup() {\n if (publisher)\n publisher->stop();\n}\n\nvoid HCIDumpParser::printBeaconCounts(Beacon beacon, const shared_ptr &bucket) {\n printf(\"Window: parsed(%s):\\n\", beacon.toString().c_str());\n printBeaconCounts(bucket);\n}\n\nvoid HCIDumpParser::printBeaconCounts(const shared_ptr &bucket) {\n vector tmp;\n bucket->toString(tmp);\n printf(\"%s\\n\", tmp.data());\n}\n\n\nvoid HCIDumpParser::sendRawHeartbeat(const beacon_info &info) {\n Beacon beacon(parseCommand.getScannerID(), info.uuid, info.code, info.manufacturer, info.major, info.minor,\n info.power, info.calibrated_power, info.rssi, info.time);\n beacon.setMessageType(BeconEventType::SCANNER_HEARTBEAT);\n publisher->publishStatus(beacon);\n}\n\nvoid HCIDumpParser::displayClosestBeacon(const shared_ptr& bucket) {\n map::const_iterator iter = bucket->begin();\n int32_t maxRSSI = -100;\n const beacon_info *closest = nullptr;\n const beacon_info *heartbeat = nullptr;\n while (iter != bucket->end()) {\n \/\/ Skip the heartbeast beacon...\n if(iter->second.rssi > maxRSSI) {\n if(scannerUUID.compare(iter->second.uuid) == 0)\n heartbeat = &iter->second;\n else {\n maxRSSI = iter->second.rssi;\n closest = &iter->second;\n }\n }\n iter++;\n }\n if(closest != nullptr) {\n Beacon closestBeacon(parseCommand.getScannerID(), closest->uuid, closest->code, closest->manufacturer,\n closest->major, closest->minor, closest->power, closest->calibrated_power,\n closest->rssi, closest->time);\n scannerView->displayBeacon(closestBeacon);\n } else if(heartbeat != nullptr) {\n \/\/ The only beacon seen was the heartbeat beacon, so display it\n Beacon heartbeatBeacon(parseCommand.getScannerID(), heartbeat->uuid, heartbeat->code, heartbeat->manufacturer,\n heartbeat->major, heartbeat->minor, heartbeat->power, heartbeat->calibrated_power,\n heartbeat->rssi, heartbeat->time);\n scannerView->displayHeartbeat(heartbeatBeacon);\n }\n\n}\n\nvoid HCIDumpParser::displayStatus() {\n scannerView->displayStatus(*statusInformation);\n}\nDump out last 10 heartbeat RSSI every 100#include \n#include \"HCIDumpParser.h\"\n#include \"BeaconEventConsumer.h\"\n\n\/\/ Uncomment to publish the raw byte[] for the beacon, otherwise, properties are sent\n\/\/#define SEND_BINARY_DATA\n\nextern \"C\" bool stop_scan_frames;\n\nstatic void generateTestEvents(EventExchanger *exchanger) {\n printf(\"generateTestEvents, starting...\\n\");\n beacon_info event;\n int count = 0;\n try {\n bool running = true;\n while (running) {\n count++;\n int32_t minor = count % 150;\n sprintf(event.uuid, \"UUID-%.12d\", minor);\n event.minor = minor;\n event.rssi = -50 - count % 7;\n event.time = EventsWindow::currentMilliseconds();\n bool stop = beacon_event_callback(&event);\n running = !stop;\n this_thread::sleep_for(chrono::milliseconds(10));\n }\n } catch(exception& e) {\n printf(\"generateTestEvents failure, %s\\n\", e.what());\n }\n stop_scan_frames = true;\n printf(\"generateTestEvents, exiting\\n\");\n}\n\nvoid HCIDumpParser::processHCI(HCIDumpCommand &parseCommand) {\n HCIDumpParser::parseCommand = parseCommand;\n eventConsumer.setParseCommand(parseCommand);\n string clientID(parseCommand.getClientID());\n if (clientID.empty())\n clientID = parseCommand.getScannerID();\n timeWindow.reset(parseCommand.getAnalyzeWindow());\n \/\/ Setup the status information\n statusInformation->setScannerID(parseCommand.getScannerID());\n statusInformation->setStatusInterval(parseCommand.getStatusInterval());\n statusInformation->setStatusQueue(parseCommand.getStatusQueue());\n\n if (parseCommand.isAnalyzeMode()) {\n printf(\"Running in analyze mode, window=%d seconds, begin=%lld\\n\", parseCommand.getAnalyzeWindow(),\n timeWindow.getBegin());\n }\n else if (!parseCommand.isSkipPublish()) {\n publisher.reset(MsgPublisher::create(parseCommand.getPubType(), parseCommand.getBrokerURL(), clientID, \"\", \"\"));\n publisher->setUseTopics(!parseCommand.isUseQueues());\n printf(\"setUseTopics: %s\\n\", publisher->isUseTopics() ? \"true\" : \"false\");\n publisher->setDestinationName(parseCommand.getDestinationName());\n if (batchCount > 0) {\n publisher->setUseTransactions(true);\n printf(\"Enabled transactions\\n\");\n }\n publisher->start(parseCommand.isAsyncMode());\n\n \/\/ Create a thread for the consumer unless running in battery test mode\n if(!parseCommand.isBatteryTestMode()) {\n eventExchanger.reset(new EventExchanger);\n eventConsumer.init(eventExchanger, publisher, statusInformation);\n consumerThread.reset(new thread(&BeaconEventConsumer::publishEvents, &eventConsumer));\n printf(\"Started event consumer thread\\n\");\n }\n }\n else {\n printf(\"Skipping publish of parsed beacons\\n\");\n }\n\n \/\/ If the status interval is > 0, start the health status monitor\n if(parseCommand.getStatusInterval() > 0) {\n statusMonitor.start(publisher, statusInformation);\n }\n\n if(parseCommand.isGenerateTestData()) {\n \/\/ Generate test data\n thread testThread(generateTestEvents, eventExchanger.get());\n testThread.detach();\n }\n\n \/\/ Scan\n char cdev = parseCommand.getHciDev().at(parseCommand.getHciDev().size() - 1);\n int device = cdev - '0';\n scan_frames(device, beacon_event_callback);\n\n \/\/ Join the consumerThread if it was\n eventConsumer.setRunning(false);\n if(consumerThread && consumerThread->joinable()) {\n printf(\"Joining the consumer thread...\\n\");\n consumerThread->join();\n printf(\"done\\n\");\n }\n\n \/\/ Stop the status monitor\n statusMonitor.stop();\n}\n\nvoid HCIDumpParser::beaconEvent(const beacon_info &info) {\n \/\/ Check for heartbeat\n bool isHeartbeat = scannerUUID.compare(info.uuid) == 0;\n if(parseCommand.isBatteryTestMode()) {\n \/\/ Send the raw unaveraged heartbeat info, or ignore non-heartbeat events\n if(isHeartbeat)\n sendRawHeartbeat(info);\n return;\n }\n\n \/\/ Merge the event into the current time window\n shared_ptr bucket = timeWindow.addEvent(info, isHeartbeat);\n statusInformation->addEvent(info, isHeartbeat);\n \/\/ Now handle the bucket if a new one has been created\n if (bucket) {\n if (!parseCommand.isSkipPublish()) {\n eventExchanger->putEvent(bucket);\n }\n else {\n if (parseCommand.isAnalyzeMode()) {\n printBeaconCounts(bucket);\n } else {\n Beacon beacon(parseCommand.getScannerID(), info.uuid, info.code, info.manufacturer, info.major,\n info.minor, info.power, info.calibrated_power, info.rssi, info.time);\n const char *info = isHeartbeat ? \"heartbeat\" : \"event\";\n if (!isHeartbeat || (isHeartbeat && !parseCommand.isSkipHeartbeat()))\n printBeaconCounts(beacon, bucket);\n }\n }\n \/\/ Display either the closest beacon or status\n if(scannerView) {\n if(scannerView->isDisplayBeaconsMode())\n displayClosestBeacon(bucket);\n else\n displayStatus();\n }\n }\n}\n\nvoid HCIDumpParser::cleanup() {\n if (publisher)\n publisher->stop();\n}\n\nvoid HCIDumpParser::printBeaconCounts(Beacon beacon, const shared_ptr &bucket) {\n printf(\"Window: parsed(%s):\\n\", beacon.toString().c_str());\n printBeaconCounts(bucket);\n}\n\nvoid HCIDumpParser::printBeaconCounts(const shared_ptr &bucket) {\n vector tmp;\n bucket->toString(tmp);\n printf(\"%s\\n\", tmp.data());\n}\n\nstatic int lastRSSI[10];\nstatic int heartbeatCount = 0;\nvoid HCIDumpParser::sendRawHeartbeat(const beacon_info &info) {\n Beacon beacon(parseCommand.getScannerID(), info.uuid, info.code, info.manufacturer, info.major, info.minor,\n info.power, info.calibrated_power, info.rssi, info.time);\n beacon.setMessageType(BeconEventType::SCANNER_HEARTBEAT);\n publisher->publishStatus(beacon);\n lastRSSI[heartbeatCount%10] = info.rssi;\n heartbeatCount ++;\n if(heartbeatCount % 100 == 0) {\n printf(\"Last[10].RSSI:\");\n for(int n = 0; n < 10; n ++)\n printf(\"%d,\", lastRSSI[n]);\n printf(\"\\n\");\n }\n}\n\nvoid HCIDumpParser::displayClosestBeacon(const shared_ptr& bucket) {\n map::const_iterator iter = bucket->begin();\n int32_t maxRSSI = -100;\n const beacon_info *closest = nullptr;\n const beacon_info *heartbeat = nullptr;\n while (iter != bucket->end()) {\n \/\/ Skip the heartbeast beacon...\n if(iter->second.rssi > maxRSSI) {\n if(scannerUUID.compare(iter->second.uuid) == 0)\n heartbeat = &iter->second;\n else {\n maxRSSI = iter->second.rssi;\n closest = &iter->second;\n }\n }\n iter++;\n }\n if(closest != nullptr) {\n Beacon closestBeacon(parseCommand.getScannerID(), closest->uuid, closest->code, closest->manufacturer,\n closest->major, closest->minor, closest->power, closest->calibrated_power,\n closest->rssi, closest->time);\n scannerView->displayBeacon(closestBeacon);\n } else if(heartbeat != nullptr) {\n \/\/ The only beacon seen was the heartbeat beacon, so display it\n Beacon heartbeatBeacon(parseCommand.getScannerID(), heartbeat->uuid, heartbeat->code, heartbeat->manufacturer,\n heartbeat->major, heartbeat->minor, heartbeat->power, heartbeat->calibrated_power,\n heartbeat->rssi, heartbeat->time);\n scannerView->displayHeartbeat(heartbeatBeacon);\n }\n\n}\n\nvoid HCIDumpParser::displayStatus() {\n scannerView->displayStatus(*statusInformation);\n}\n<|endoftext|>"} {"text":"#include \"disassembler.h\"\n#include \"llvm\/Support\/MemoryBuffer.h\"\n#include \"llvm\/Support\/FormattedStream.h\"\n#include \"llvm\/Support\/CommandLine.h\"\n\n#include \"assert.h\"\n\nusing namespace llvm;\n\nstatic cl::opt\ninputFileName(cl::Positional, cl::desc(\"\"), cl::init(\"-\"));\n\nint main(int argc, char **argv) {\n ErrorOr> bufferPtr =\n MemoryBuffer::getFileOrSTDIN(inputFileName);\n\n if (std::error_code EC = bufferPtr.getError()) {\n errs() << inputFileName << \": \" << EC.message() << '\\n';\n return 1;\n }\n\n StringRef buffer = bufferPtr->get()->getBuffer();\n\n Disassembler disassembler(Disassembler::Intel);\n\n StringRef hex = buffer.trim();\n auto y = hexToBinary(hex);\n std::string out;\n bool ok = disassembler.disassemble(y, out);\n if (!ok) {\n errs() << \"Disassembly failed\\n\";\n return 1;\n }\n outs() << out << '\\n';\n return 0;\n}\nparametric disassembly type#include \"disassembler.h\"\n#include \"llvm\/Support\/MemoryBuffer.h\"\n#include \"llvm\/Support\/FormattedStream.h\"\n#include \"llvm\/Support\/CommandLine.h\"\n\n#include \"assert.h\"\n\n\nusing namespace llvm;\n\nstatic cl::opt inputFileName(cl::Positional, cl::desc(\"\"), cl::init(\"-\"));\n\nstatic cl::opt syntaxType(cl::desc(\"Choose output syntax type:\"),\n cl::values(clEnumValN(Disassembler::Intel, \"intel\", \"Output Intel syntax (default)\"),\n clEnumValN(Disassembler::ATT, \"att\" , \"Output AT&T ayntax\")));\n\nint main(int argc, char **argv) {\n cl::ParseCommandLineOptions(argc, argv);\n\n ErrorOr> bufferPtr =\n MemoryBuffer::getFileOrSTDIN(inputFileName);\n\n if (std::error_code EC = bufferPtr.getError()) {\n errs() << inputFileName << \": \" << EC.message() << '\\n';\n return 1;\n }\n\n StringRef buffer = bufferPtr->get()->getBuffer();\n\n Disassembler disassembler(syntaxType);\n\n StringRef hex = buffer.trim();\n auto y = hexToBinary(hex);\n std::string out;\n bool ok = disassembler.disassemble(y, out);\n if (!ok) {\n errs() << \"Disassembly failed\\n\";\n return 1;\n }\n outs() << out << '\\n';\n return 0;\n}\n<|endoftext|>"} {"text":"\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"qset.hh\"\n#include \"graphTypes.hh\"\n\n\n\/\/Basically just a DFS\n\/\/We start at v, and search\n\/\/We expand vertices in S\n\/\/And we add to our count (without expanding) for those not in S\nint sizeQ(int n, const VSet &S, Vertex v, const Graph& G)\n{\n \/\/std::cout << \"Q: starting with S = \" << showSet(S) << \"\\n\";\n \n \/\/int n = boost::num_vertices(G);\n \n Vertex* open = new Vertex[n];\n \n open[0] = v;\n int stackEnd = 0;\n\n \/\/Uses more memory than VSet, but is faster\n bool* closed = new bool[n];\n for (int i = 0; i = 0 )\n {\n\tVertex w = open[stackEnd];\n\tstackEnd--;\n\tauto neighbours = boost::adjacent_vertices(w,G);\n\t\/\/std::cout << \"Q: expanding \" << w << \"\\n\";\n\t\n\tfor (auto iter = neighbours.first; iter != neighbours.second; iter++ )\n\t{\n Vertex u = *iter;\n\t \/\/std::cout << \"Q: found neighbour \" << u << \"\\n\";\n\t if (!closed[u])\n\t {\n\t\t\/\/std::cout << \"Q: adding \" << u << \" to closed\\n\";\n\t\t\n closed[u] = true;\n\t\t\n\t\tif (u != v && S.contains(u))\n\t\t{\n\t\t \/\/std::cout << \"Q: adding \" << u << \" to queue\\n\";\n\t\t stackEnd++;\n\t\t open[stackEnd] = u;\n\t\t} \n\t\telse if (u != v)\n\t\t{\n\t\t numInQ++;\n\t\t \n\t\t}\n\t }\n\t}\n }\n delete[] closed;\n delete[] open;\n \/\/std::cout << \"|Q| = \" << numInQ << \"\\n\";\n return numInQ;\n \n}\n\n\nstd::string showSet(VSet S) {\n std::ostringstream result;\n \n result << \"{\";\n \n std::vector members;\n S.members(members);\n \n for (auto iter = members.begin(); iter != members.end(); iter++)\n {\n result << *iter << \" ; \";\n }\n \n result << \"}\";\n \n return result.str();\n \n}\nAvoid malloc in qsize\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"qset.hh\"\n#include \"graphTypes.hh\"\n\n\n\/\/Basically just a DFS\n\/\/We start at v, and search\n\/\/We expand vertices in S\n\/\/And we add to our count (without expanding) for those not in S\nint sizeQ(int n, const VSet &S, Vertex v, const Graph& G)\n{\n \/\/std::cout << \"Q: starting with S = \" << showSet(S) << \"\\n\";\n \n \/\/int n = boost::num_vertices(G);\n \n Vertex open[MAX_NUM_VERTICES];\n \n open[0] = v;\n int stackEnd = 0;\n\n \/\/Uses more memory than VSet, but is faster\n bool closed[MAX_NUM_VERTICES] = {false};\n \n int numInQ = 0;\n\n \n\n while (stackEnd >= 0 )\n {\n\tVertex w = open[stackEnd];\n\tstackEnd--;\n\tauto neighbours = boost::adjacent_vertices(w,G);\n\t\/\/std::cout << \"Q: expanding \" << w << \"\\n\";\n\t\n\tfor (auto iter = neighbours.first; iter != neighbours.second; iter++ )\n\t{\n Vertex u = *iter;\n\t \/\/std::cout << \"Q: found neighbour \" << u << \"\\n\";\n\t if (!closed[u])\n\t {\n\t\t\/\/std::cout << \"Q: adding \" << u << \" to closed\\n\";\n\t\t\n closed[u] = true;\n\t\t\n\t\tif (u != v && S.contains(u))\n\t\t{\n\t\t \/\/std::cout << \"Q: adding \" << u << \" to queue\\n\";\n\t\t stackEnd++;\n\t\t open[stackEnd] = u;\n\t\t} \n\t\telse if (u != v)\n\t\t{\n\t\t numInQ++;\n\t\t \n\t\t}\n\t }\n\t}\n }\n \/\/delete[] closed;\n \/\/ delete[] open;\n \/\/std::cout << \"|Q| = \" << numInQ << \"\\n\";\n return numInQ;\n \n}\n\n\nstd::string showSet(VSet S) {\n std::ostringstream result;\n \n result << \"{\";\n \n std::vector members;\n S.members(members);\n \n for (auto iter = members.begin(); iter != members.end(); iter++)\n {\n result << *iter << \" ; \";\n }\n \n result << \"}\";\n \n return result.str();\n \n}\n<|endoftext|>"} {"text":"\/**\n * Computer Graphics Assignment 3 - \n * Mitchell Anderson, Andrew Pham, Konrad Janica\n *\n * rain.cc, Simple implementation of a Rain in openGL\n * \n * This file is a simple implementation of rain in openGL\n * for more clarification read the comments describing each function\n *\n * Code tutorial - http:\/\/www.opengl-tutorial.org\/intermediate-tutorials\/billboards-particles\/particles-instancing\/\n * \n *\/\n\n\n#include \"rain.h\"\n\nRain::Rain(const GLuint &program_id) : MAX_PARTICLES_(100000), rain_shader_(program_id)\n{\n \/\/ Initialize the particle buffers\n particles_ = new Particle[MAX_PARTICLES_];\n particle_position_buffer_data_ = new GLfloat[MAX_PARTICLES_ * 3];\n particle_colour_buffer_data_ = new GLfloat[MAX_PARTICLES_ * 4];\n\n \/\/ Set the range in which the rain is generated\n maxx_ = 100.0f;\n maxy_ = 30.0f;\n maxz_ = 100.0f;\n\n \/\/ Run initialization\n rain_vao_ = CreateVao();\n Init();\n\n}\n\nRain::~Rain()\n{\n delete [] particles_;\n delete [] particle_position_buffer_data_;\n delete [] particle_colour_buffer_data_;\n\n}\n\nunsigned int Rain::CreateVao()\n{\n glUseProgram(rain_shader_);\n\n \/\/ Initial declaration of the shape of the 'raindrop'\n \/\/ these values can be modified to change the shape of the rain\n static const GLfloat vertices[] = { \n -0.01f, -0.05f, 0.0f,\n 0.01f, -0.05f, 0.0f,\n -0.01f, 0.05f, 0.0f,\n 0.01f, 0.05f, 0.0f,\n };\n\n \/\/ Create a VAO for the rain \n GLuint vao;\n glGenVertexArrays(1, &vao);\n glBindVertexArray(vao);\n\n \/\/ VBO containing a single instance of a particle\n glGenBuffers(1, &particle_instance_buffer_);\n glBindBuffer(GL_ARRAY_BUFFER, particle_instance_buffer_);\n glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);\n\n \/\/ VBO containing position of each particle instance\n glGenBuffers(1, &particle_position_buffer_);\n glBindBuffer(GL_ARRAY_BUFFER, particle_position_buffer_);\n\n \/\/ Initially set data to NULL\n glBufferData(GL_ARRAY_BUFFER, MAX_PARTICLES_ * 3 * sizeof(GLfloat), NULL, GL_STREAM_DRAW);\n\n \/\/ VBO containing colours of each particle instance\n glGenBuffers(1, &particle_colour_buffer_);\n glBindBuffer(GL_ARRAY_BUFFER, particle_colour_buffer_);\n\n \/\/ Initially set data to NULL\n glBufferData(GL_ARRAY_BUFFER, MAX_PARTICLES_ * 4 * sizeof(GLfloat), NULL, GL_STREAM_DRAW);\n\n return vao;\n}\n\nvoid Rain::Init()\n{\n\n \/\/ Random generation engines to generate uniform floats between a range \n std::random_device rd; \n std::mt19937 eng(rd()); \n \/\/ One for each axis\n std::uniform_real_distribution<> xgen(0,maxx_);\n std::uniform_real_distribution<> ygen(0,maxy_);\n std::uniform_real_distribution<> zgen(0,maxz_);\n \/\/ Initialize the position\/speed\/colour for all particles\n\n\n int maxx = 50.0f;\n int maxy = 20.0f;\n int maxz = 50.0f;\n\n for (unsigned int i = 0; i < MAX_PARTICLES_; i++)\n {\n \/\/ Randomly generate the positions of the particle\n particles_[i].pos = glm::vec3(xgen(eng), ygen(eng), zgen(eng));\n particles_[i].speed = 0.1f;\n\n \/\/ Slightly randomize colours between a certain range (Blue\/Blue-Grey)\n float red = (rand() % 49 + 24) \/ 255.0f;\n float green = (rand() % 77 + 17) \/ 255.0f;\n float blue = (rand() % 176 + 70) \/ 255.0f;\n particles_[i].colour = glm::vec4(red, green, blue, 1.0f);\n }\n}\n\nvoid Rain::UpdatePosition()\n{\n \/\/ Updates particles and puts in data arrays\n for (unsigned int i = 0; i < MAX_PARTICLES_; i++)\n {\n \/\/ Reduce y so the rain travels towards the ground\n particles_[i].pos.y -= particles_[i].speed;\n\n \/\/ Reduce x so rain appears to be sweeping across the scene\n particles_[i].pos.x += particles_[i].speed;\n\n \/\/ Boundary cases so that the rain particles 'reset' with a smal amount of randomization\n particles_[i].pos.x += particles_[i].speed;\n\n if(particles_[i].pos.y < -5)\n {\n particles_[i].pos.y = maxy_ - (rand() % 5);\n }\n\n if (particles_[i].pos.x > maxx_) \n {\n particles_[i].pos.x = 0.0f;\n }\n\n \/\/ Store the particles data inside the buffer, to be put in to the VBO\n\n particle_position_buffer_data_[i*3 + 0] = particles_[i].pos.x;\n particle_position_buffer_data_[i*3 + 1] = particles_[i].pos.y;\n particle_position_buffer_data_[i*3 + 2] = particles_[i].pos.z;\n\n particle_colour_buffer_data_[i*4 + 0] = particles_[i].colour.x;\n particle_colour_buffer_data_[i*4 + 1] = particles_[i].colour.y;\n particle_colour_buffer_data_[i*4 + 2] = particles_[i].colour.z;\n particle_colour_buffer_data_[i*4 + 3] = particles_[i].colour.w;\n }\n}\n\nvoid Rain::Render(Camera * camera, Object * car, Skybox * skybox)\n{\n glUseProgram(rain_shader_);\n\n \/\/ Enable blending so that rain is slightly transparent, transparency is set in the frag shader\n glEnable(GL_BLEND);\n glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA );\n\n glBindVertexArray(rain_vao_);\n\n \/\/ Set the Buffer subdata to be the positions array that we filled in UpdatePosition()\n glBindBuffer(GL_ARRAY_BUFFER, particle_position_buffer_);\n glBufferData(GL_ARRAY_BUFFER, MAX_PARTICLES_ * 3 * sizeof(GLfloat), NULL, GL_STREAM_DRAW);\n glBufferSubData(GL_ARRAY_BUFFER, 0, MAX_PARTICLES_ * 3 * sizeof(GLfloat), particle_position_buffer_data_);\n\n \/\/ Set the colour subdata to be the positions array that we filled in UpdatePosition()\n glBindBuffer(GL_ARRAY_BUFFER, particle_colour_buffer_);\n glBufferData(GL_ARRAY_BUFFER, MAX_PARTICLES_ * 4 * sizeof(GLfloat), NULL, GL_STREAM_DRAW);\n glBufferSubData(GL_ARRAY_BUFFER, 0, MAX_PARTICLES_ * 4 * sizeof(GLfloat), particle_colour_buffer_data_);\n\n \/\/ Get the handle for the Model * View Matrix\n GLint mvHandle = glGetUniformLocation(rain_shader_, \"modelview_matrix\");\n if (mvHandle == -1) {\n fprintf(stderr,\"Could not find uniform: modelview_matrix In: Rain - Render\\n\");\n }\n\n GLuint initialVerticesHandle = glGetAttribLocation(rain_shader_, \"initial_vertices\");\n GLuint positionsHandle = glGetAttribLocation(rain_shader_, \"displaced_vertices\");\n GLuint colourHandle = glGetAttribLocation(rain_shader_, \"colour\");\n\n \/\/ Get the view matrix from the camera\n glm::mat4 view_matrix = camera->view_matrix();\n\n \/\/ Translate based on the car, so the rain follows the car\n glm::mat4 object_translate = glm::translate(glm::mat4(1.0f), \n glm::vec3(car->translation().x, 1.0f , car->translation().z));\n\n \/\/ Translate the rain so its centre is roughly around the centre of the car\n glm::mat4 rain_translate = glm::translate(glm::mat4(1.0f), glm::vec3(-maxx_ \/ 2.0f, 0.0f, -maxz_ \/ 2.0f));\n\n \/\/ Apply the transformations\n view_matrix = view_matrix * object_translate * rain_translate;\n\n glUniformMatrix4fv(mvHandle, 1, false, glm::value_ptr(view_matrix));\n\n \/\/ The cameras up vector is (0,1,0) transform it to world space by\n \/\/ by multiplying my camera->world (view) matrix inverse\n GLuint CamRight = glGetUniformLocation(rain_shader_, \"cam_right\");\n GLuint CamUp = glGetUniformLocation(rain_shader_, \"cam_up\");\n\n glUniform3f(CamRight, view_matrix[0][0], view_matrix[1][0], view_matrix[2][0]);\n glUniform3f(CamUp , view_matrix[0][1], view_matrix[1][1], view_matrix[2][1]);\n\n glBindBuffer(GL_ARRAY_BUFFER, particle_instance_buffer_);\n glEnableVertexAttribArray(initialVerticesHandle);\n glVertexAttribPointer(initialVerticesHandle, 3, GL_FLOAT, GL_FALSE, 0, 0);\n\n glBindBuffer(GL_ARRAY_BUFFER, particle_position_buffer_);\n glEnableVertexAttribArray(positionsHandle);\n glVertexAttribPointer(positionsHandle, 3, GL_FLOAT, GL_FALSE, 0, 0);\n\n glBindBuffer(GL_ARRAY_BUFFER, particle_colour_buffer_);\n glEnableVertexAttribArray(colourHandle);\n glVertexAttribPointer(colourHandle, 4, GL_FLOAT, GL_FALSE, 0, 0);\n\n \/\/ Needed for instanced draws\n glVertexAttribDivisor(initialVerticesHandle, 0); \/\/ Same every particle\n glVertexAttribDivisor(positionsHandle, 1); \/\/ One per particle\n glVertexAttribDivisor(colourHandle, 1); \/\/ One per particle\n\n \/\/ Equivalent to looping over all particles (with 4 vertices)\n glDrawArraysInstanced(GL_TRIANGLE_STRIP, 0, 4, MAX_PARTICLES_);\n\n glDisable(GL_BLEND);\n\n\n}\n\nmade slight change\/**\n * Computer Graphics Assignment 3 - \n * Mitchell Anderson, Andrew Pham, Konrad Janica\n *\n * rain.cc, Simple implementation of a Rain in openGL\n * \n * This file is a simple implementation of rain in openGL\n * for more clarification read the comments describing each function\n *\n * Code tutorial - http:\/\/www.opengl-tutorial.org\/intermediate-tutorials\/billboards-particles\/particles-instancing\/\n * \n *\/\n\n\n#include \"rain.h\"\n\nRain::Rain(const GLuint &program_id) : MAX_PARTICLES_(100000), rain_shader_(program_id)\n{\n \/\/ Initialize the particle buffers\n particles_ = new Particle[MAX_PARTICLES_];\n particle_position_buffer_data_ = new GLfloat[MAX_PARTICLES_ * 3];\n particle_colour_buffer_data_ = new GLfloat[MAX_PARTICLES_ * 4];\n\n \/\/ Set the range in which the rain is generated\n maxx_ = 100.0f;\n maxy_ = 30.0f;\n maxz_ = 100.0f;\n\n \/\/ Run initialization\n rain_vao_ = CreateVao();\n Init();\n\n}\n\nRain::~Rain()\n{\n delete [] particles_;\n delete [] particle_position_buffer_data_;\n delete [] particle_colour_buffer_data_;\n\n}\n\nunsigned int Rain::CreateVao()\n{\n glUseProgram(rain_shader_);\n\n \/\/ Initial declaration of the shape of the 'raindrop'\n \/\/ these values can be modified to change the shape of the rain\n static const GLfloat vertices[] = { \n -0.01f, -0.05f, 0.0f,\n 0.01f, -0.05f, 0.0f,\n -0.01f, 0.05f, 0.0f,\n 0.01f, 0.05f, 0.0f,\n };\n\n \/\/ Create a VAO for the rain \n GLuint vao;\n glGenVertexArrays(1, &vao);\n glBindVertexArray(vao);\n\n \/\/ VBO containing a single instance of a particle\n glGenBuffers(1, &particle_instance_buffer_);\n glBindBuffer(GL_ARRAY_BUFFER, particle_instance_buffer_);\n glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);\n\n \/\/ VBO containing position of each particle instance\n glGenBuffers(1, &particle_position_buffer_);\n glBindBuffer(GL_ARRAY_BUFFER, particle_position_buffer_);\n\n \/\/ Initially set data to NULL\n glBufferData(GL_ARRAY_BUFFER, MAX_PARTICLES_ * 3 * sizeof(GLfloat), NULL, GL_STREAM_DRAW);\n\n \/\/ VBO containing colours of each particle instance\n glGenBuffers(1, &particle_colour_buffer_);\n glBindBuffer(GL_ARRAY_BUFFER, particle_colour_buffer_);\n\n \/\/ Initially set data to NULL\n glBufferData(GL_ARRAY_BUFFER, MAX_PARTICLES_ * 4 * sizeof(GLfloat), NULL, GL_STREAM_DRAW);\n\n return vao;\n}\n\nvoid Rain::Init()\n{\n\n \/\/ Random generation engines to generate uniform floats between a range \n std::random_device rd; \n std::mt19937 eng(rd()); \n \/\/ One for each axis\n std::uniform_real_distribution<> xgen(0,maxx_);\n std::uniform_real_distribution<> ygen(0,maxy_);\n std::uniform_real_distribution<> zgen(0,maxz_);\n \/\/ Initialize the position\/speed\/colour for all particles\n\n\n int maxx = 50.0f;\n int maxy = 20.0f;\n int maxz = 50.0f;\n\n for (unsigned int i = 0; i < MAX_PARTICLES_; i++)\n {\n \/\/ Randomly generate the positions of the particle\n particles_[i].pos = glm::vec3(xgen(eng), ygen(eng), zgen(eng));\n particles_[i].speed = 0.1f;\n\n \/\/ Slightly randomize colours between a certain range (Blue\/Blue-Grey)\n float red = (rand() % 49 + 24) \/ 255.0f;\n float green = (rand() % 77 + 17) \/ 255.0f;\n float blue = (rand() % 176 + 70) \/ 255.0f;\n particles_[i].colour = glm::vec4(red, green, blue, 1.0f);\n }\n}\n\nvoid Rain::UpdatePosition()\n{\n \/\/ Updates particles and puts in data arrays\n for (unsigned int i = 0; i < MAX_PARTICLES_; i++)\n {\n \/\/ Reduce y so the rain travels towards the ground\n particles_[i].pos.y -= particles_[i].speed;\n\n \/\/ Reduce x so rain appears to be sweeping across the scene\n particles_[i].pos.x += particles_[i].speed;\n\n if(particles_[i].pos.y < -5)\n {\n particles_[i].pos.y = maxy_ - (rand() % 5);\n }\n\n if (particles_[i].pos.x > maxx_) \n {\n particles_[i].pos.x = 0.0f;\n }\n\n \/\/ Store the particles data inside the buffer, to be put in to the VBO\n\n particle_position_buffer_data_[i*3 + 0] = particles_[i].pos.x;\n particle_position_buffer_data_[i*3 + 1] = particles_[i].pos.y;\n particle_position_buffer_data_[i*3 + 2] = particles_[i].pos.z;\n\n particle_colour_buffer_data_[i*4 + 0] = particles_[i].colour.x;\n particle_colour_buffer_data_[i*4 + 1] = particles_[i].colour.y;\n particle_colour_buffer_data_[i*4 + 2] = particles_[i].colour.z;\n particle_colour_buffer_data_[i*4 + 3] = particles_[i].colour.w;\n }\n}\n\nvoid Rain::Render(Camera * camera, Object * car, Skybox * skybox)\n{\n glUseProgram(rain_shader_);\n\n \/\/ Enable blending so that rain is slightly transparent, transparency is set in the frag shader\n glEnable(GL_BLEND);\n glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA );\n\n glBindVertexArray(rain_vao_);\n\n \/\/ Set the Buffer subdata to be the positions array that we filled in UpdatePosition()\n glBindBuffer(GL_ARRAY_BUFFER, particle_position_buffer_);\n glBufferData(GL_ARRAY_BUFFER, MAX_PARTICLES_ * 3 * sizeof(GLfloat), NULL, GL_STREAM_DRAW);\n glBufferSubData(GL_ARRAY_BUFFER, 0, MAX_PARTICLES_ * 3 * sizeof(GLfloat), particle_position_buffer_data_);\n\n \/\/ Set the colour subdata to be the positions array that we filled in UpdatePosition()\n glBindBuffer(GL_ARRAY_BUFFER, particle_colour_buffer_);\n glBufferData(GL_ARRAY_BUFFER, MAX_PARTICLES_ * 4 * sizeof(GLfloat), NULL, GL_STREAM_DRAW);\n glBufferSubData(GL_ARRAY_BUFFER, 0, MAX_PARTICLES_ * 4 * sizeof(GLfloat), particle_colour_buffer_data_);\n\n \/\/ Get the handle for the Model * View Matrix\n GLint mvHandle = glGetUniformLocation(rain_shader_, \"modelview_matrix\");\n if (mvHandle == -1) {\n fprintf(stderr,\"Could not find uniform: modelview_matrix In: Rain - Render\\n\");\n }\n\n GLuint initialVerticesHandle = glGetAttribLocation(rain_shader_, \"initial_vertices\");\n GLuint positionsHandle = glGetAttribLocation(rain_shader_, \"displaced_vertices\");\n GLuint colourHandle = glGetAttribLocation(rain_shader_, \"colour\");\n\n \/\/ Get the view matrix from the camera\n glm::mat4 view_matrix = camera->view_matrix();\n\n \/\/ Translate based on the car, so the rain follows the car\n glm::mat4 object_translate = glm::translate(glm::mat4(1.0f), \n glm::vec3(car->translation().x, 1.0f , car->translation().z));\n\n \/\/ Translate the rain so its centre is roughly around the centre of the car\n glm::mat4 rain_translate = glm::translate(glm::mat4(1.0f), glm::vec3(-maxx_ \/ 2.0f, 0.0f, -maxz_ \/ 2.0f));\n\n \/\/ Apply the transformations\n view_matrix = view_matrix * object_translate * rain_translate;\n\n glUniformMatrix4fv(mvHandle, 1, false, glm::value_ptr(view_matrix));\n\n \/\/ The cameras up vector is (0,1,0) transform it to world space by\n \/\/ by multiplying my camera->world (view) matrix inverse\n GLuint CamRight = glGetUniformLocation(rain_shader_, \"cam_right\");\n GLuint CamUp = glGetUniformLocation(rain_shader_, \"cam_up\");\n\n glUniform3f(CamRight, view_matrix[0][0], view_matrix[1][0], view_matrix[2][0]);\n glUniform3f(CamUp , view_matrix[0][1], view_matrix[1][1], view_matrix[2][1]);\n\n glBindBuffer(GL_ARRAY_BUFFER, particle_instance_buffer_);\n glEnableVertexAttribArray(initialVerticesHandle);\n glVertexAttribPointer(initialVerticesHandle, 3, GL_FLOAT, GL_FALSE, 0, 0);\n\n glBindBuffer(GL_ARRAY_BUFFER, particle_position_buffer_);\n glEnableVertexAttribArray(positionsHandle);\n glVertexAttribPointer(positionsHandle, 3, GL_FLOAT, GL_FALSE, 0, 0);\n\n glBindBuffer(GL_ARRAY_BUFFER, particle_colour_buffer_);\n glEnableVertexAttribArray(colourHandle);\n glVertexAttribPointer(colourHandle, 4, GL_FLOAT, GL_FALSE, 0, 0);\n\n \/\/ Needed for instanced draws\n glVertexAttribDivisor(initialVerticesHandle, 0); \/\/ Same every particle\n glVertexAttribDivisor(positionsHandle, 1); \/\/ One per particle\n glVertexAttribDivisor(colourHandle, 1); \/\/ One per particle\n\n \/\/ Equivalent to looping over all particles (with 4 vertices)\n glDrawArraysInstanced(GL_TRIANGLE_STRIP, 0, 4, MAX_PARTICLES_);\n\n glDisable(GL_BLEND);\n\n\n}\n\n<|endoftext|>"} {"text":"\/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- *\/\n\/*\n * This file is part of the LibreOffice project.\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\n * This file incorporates work covered by the following license notice:\n *\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed\n * with this work for additional information regarding copyright\n * ownership. The ASF licenses this file to you under the Apache\n * License, Version 2.0 (the \"License\"); you may not use this file\n * except in compliance with the License. You may obtain a copy of\n * the License at http:\/\/www.apache.org\/licenses\/LICENSE-2.0 .\n *\/\n\n\n#include \"listviewitems.hxx\"\n\/\/........................................................................\nnamespace dbaui\n{\n\/\/........................................................................\n\n \/\/========================================================================\n \/\/ class OBoldListboxString\n \/\/========================================================================\n \/\/------------------------------------------------------------------------\n void OBoldListboxString::InitViewData( SvTreeListBox* pView,SvLBoxEntry* pEntry, SvViewDataItem* _pViewData)\n {\n SvLBoxString::InitViewData( pView, pEntry, _pViewData );\n if ( !m_bEmphasized )\n return;\n if (!_pViewData)\n _pViewData = pView->GetViewDataItem( pEntry, this );\n pView->Push(PUSH_ALL);\n Font aFont( pView->GetFont());\n aFont.SetWeight(WEIGHT_BOLD);\n pView->SetFont( aFont );\n _pViewData->aSize = Size(pView->GetTextWidth(GetText()), pView->GetTextHeight());\n pView->Pop();\n }\n\n \/\/------------------------------------------------------------------------\n sal_uInt16 OBoldListboxString::IsA()\n {\n return SV_ITEM_ID_BOLDLBSTRING;\n }\n\n \/\/------------------------------------------------------------------------\n void OBoldListboxString::Paint(const Point& rPos, SvTreeListBox& rDev, sal_uInt16 nFlags, SvLBoxEntry* pEntry )\n {\n if (m_bEmphasized)\n {\n rDev.Push(PUSH_ALL);\n Font aFont( rDev.GetFont());\n aFont.SetWeight(WEIGHT_BOLD);\n rDev.SetFont( aFont );\n Point aPos(rPos);\n rDev.DrawText( aPos, GetText() );\n rDev.Pop();\n }\n else\n SvLBoxString::Paint(rPos, rDev, nFlags, pEntry);\n }\n\n\/\/........................................................................\n} \/\/ namespace dbaui\n\/\/........................................................................\n\n\/* vim:set shiftwidth=4 softtabstop=4 expandtab: *\/\nPrevent infinite recursion during make check.\/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- *\/\n\/*\n * This file is part of the LibreOffice project.\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\n * This file incorporates work covered by the following license notice:\n *\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed\n * with this work for additional information regarding copyright\n * ownership. The ASF licenses this file to you under the Apache\n * License, Version 2.0 (the \"License\"); you may not use this file\n * except in compliance with the License. You may obtain a copy of\n * the License at http:\/\/www.apache.org\/licenses\/LICENSE-2.0 .\n *\/\n\n\n#include \"listviewitems.hxx\"\n\/\/........................................................................\nnamespace dbaui\n{\n\/\/........................................................................\n\n \/\/========================================================================\n \/\/ class OBoldListboxString\n \/\/========================================================================\n \/\/------------------------------------------------------------------------\n void OBoldListboxString::InitViewData( SvTreeListBox* pView,SvLBoxEntry* pEntry, SvViewDataItem* _pViewData)\n {\n SvLBoxString::InitViewData( pView, pEntry, _pViewData );\n if ( !m_bEmphasized )\n return;\n if (!_pViewData)\n _pViewData = pView->GetViewDataItem( pEntry, this );\n pView->Push(PUSH_ALL);\n Font aFont( pView->GetFont());\n aFont.SetWeight(WEIGHT_BOLD);\n pView->Control::SetFont( aFont );\n _pViewData->aSize = Size(pView->GetTextWidth(GetText()), pView->GetTextHeight());\n pView->Pop();\n }\n\n \/\/------------------------------------------------------------------------\n sal_uInt16 OBoldListboxString::IsA()\n {\n return SV_ITEM_ID_BOLDLBSTRING;\n }\n\n \/\/------------------------------------------------------------------------\n void OBoldListboxString::Paint(const Point& rPos, SvTreeListBox& rDev, sal_uInt16 nFlags, SvLBoxEntry* pEntry )\n {\n if (m_bEmphasized)\n {\n rDev.Push(PUSH_ALL);\n Font aFont( rDev.GetFont());\n aFont.SetWeight(WEIGHT_BOLD);\n rDev.SetFont( aFont );\n Point aPos(rPos);\n rDev.DrawText( aPos, GetText() );\n rDev.Pop();\n }\n else\n SvLBoxString::Paint(rPos, rDev, nFlags, pEntry);\n }\n\n\/\/........................................................................\n} \/\/ namespace dbaui\n\/\/........................................................................\n\n\/* vim:set shiftwidth=4 softtabstop=4 expandtab: *\/\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * $RCSfile: TableUndo.hxx,v $\n *\n * $Revision: 1.4 $\n *\n * last change: $Author: hr $ $Date: 2003-03-19 17:53:05 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the License); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an AS IS basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n#ifndef DBAUI_TABLEUNDO_HXX\n#define DBAUI_TABLEUNDO_HXX\n\n#ifndef DBAUI_GENERALUNDO_HXX\n#include \"GeneralUndo.hxx\"\n#endif\n#ifndef _SV_MULTISEL_HXX\n#include \n#endif\n\n#include \n\n#ifndef _COM_SUN_STAR_UNO_ANY_H_\n#include \n#endif\n#ifndef DBAUI_TYPEINFO_HXX\n#include \"TypeInfo.hxx\"\n#endif\n\nnamespace dbaui\n{\n \/\/========================================================================\n class OTableRowView;\n class OTableRow;\n class OTableDesignUndoAct : public OCommentUndoAction\n {\n protected:\n OTableRowView* m_pTabDgnCtrl;\n\n virtual void Undo();\n virtual void Redo();\n public:\n OTableDesignUndoAct( OTableRowView* pOwner ,USHORT nCommentID);\n virtual ~OTableDesignUndoAct();\n };\n\n \/\/========================================================================\n class OTableEditorCtrl;\n class OTableEditorUndoAct : public OTableDesignUndoAct\n {\n protected:\n OTableEditorCtrl* pTabEdCtrl;\n\n public:\n OTableEditorUndoAct( OTableEditorCtrl* pOwner,USHORT nCommentID );\n virtual ~OTableEditorUndoAct();\n };\n\n\n \/\/========================================================================\n class OTableDesignCellUndoAct : public OTableDesignUndoAct\n {\n protected:\n USHORT m_nCol;\n long m_nRow;\n ::com::sun::star::uno::Any m_sOldText;\n ::com::sun::star::uno::Any m_sNewText;\n\n virtual void Undo();\n virtual void Redo();\n public:\n OTableDesignCellUndoAct( OTableRowView* pOwner, long nRowID, USHORT nColumn );\n virtual ~OTableDesignCellUndoAct();\n };\n\n class OTypeInfo;\n \/\/========================================================================\n class OTableEditorTypeSelUndoAct : public OTableEditorUndoAct\n {\n protected:\n USHORT m_nCol;\n long m_nRow;\n TOTypeInfoSP m_pOldType;\n TOTypeInfoSP m_pNewType;\n\n virtual void Undo();\n virtual void Redo();\n public:\n OTableEditorTypeSelUndoAct( OTableEditorCtrl* pOwner, long nRowID, USHORT nColumn, const TOTypeInfoSP& _pOldType );\n virtual ~OTableEditorTypeSelUndoAct();\n };\n\n \/\/========================================================================\n class OTableEditorDelUndoAct : public OTableEditorUndoAct\n {\n protected:\n ::std::vector m_aDeletedRows;\n\n virtual void Undo();\n virtual void Redo();\n public:\n OTableEditorDelUndoAct( OTableEditorCtrl* pOwner );\n virtual ~OTableEditorDelUndoAct();\n };\n\n \/\/========================================================================\n class OTableEditorInsUndoAct : public OTableEditorUndoAct\n {\n protected:\n ::std::vector m_vInsertedRows;\n long m_nInsPos;\n\n virtual void Undo();\n virtual void Redo();\n public:\n OTableEditorInsUndoAct( OTableEditorCtrl* pOwner,\n long nInsertPosition,\n const ::std::vector< OTableRow*>& _vInsertedRows);\n virtual ~OTableEditorInsUndoAct();\n };\n\n \/\/========================================================================\n class OTableEditorInsNewUndoAct : public OTableEditorUndoAct\n {\n protected:\n long m_nInsPos;\n long m_nInsRows;\n\n virtual void Undo();\n virtual void Redo();\n public:\n OTableEditorInsNewUndoAct( OTableEditorCtrl* pOwner, long nInsertPosition, long nInsertedRows );\n virtual ~OTableEditorInsNewUndoAct();\n };\n\n \/\/========================================================================\n class OPrimKeyUndoAct : public OTableEditorUndoAct\n {\n protected:\n MultiSelection m_aDelKeys,\n m_aInsKeys;\n BOOL m_bActPrimKeySet;\n OTableEditorCtrl* m_pEditorCtrl;\n\n virtual void Undo();\n virtual void Redo();\n public:\n OPrimKeyUndoAct( OTableEditorCtrl* pOwner, MultiSelection aDeletedKeys, MultiSelection aInsertedKeys );\n virtual ~OPrimKeyUndoAct();\n };\n}\n#endif \/\/ DBAUI_TABLEUNDO_HXX\n\n\nINTEGRATION: CWS dba09 (1.4.172); FILE MERGED 2004\/03\/18 10:20:35 fs 1.4.172.1: #i24876# +TYPEINFO\/*************************************************************************\n *\n * $RCSfile: TableUndo.hxx,v $\n *\n * $Revision: 1.5 $\n *\n * last change: $Author: hr $ $Date: 2004-05-10 13:09:33 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the License); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an AS IS basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n#ifndef DBAUI_TABLEUNDO_HXX\n#define DBAUI_TABLEUNDO_HXX\n\n#ifndef DBAUI_GENERALUNDO_HXX\n#include \"GeneralUndo.hxx\"\n#endif\n#ifndef _SV_MULTISEL_HXX\n#include \n#endif\n\n#include \n\n#ifndef _COM_SUN_STAR_UNO_ANY_H_\n#include \n#endif\n#ifndef DBAUI_TYPEINFO_HXX\n#include \"TypeInfo.hxx\"\n#endif\n\nnamespace dbaui\n{\n \/\/========================================================================\n class OTableRowView;\n class OTableRow;\n class OTableDesignUndoAct : public OCommentUndoAction\n {\n protected:\n OTableRowView* m_pTabDgnCtrl;\n\n virtual void Undo();\n virtual void Redo();\n public:\n TYPEINFO();\n OTableDesignUndoAct( OTableRowView* pOwner ,USHORT nCommentID);\n virtual ~OTableDesignUndoAct();\n };\n\n \/\/========================================================================\n class OTableEditorCtrl;\n class OTableEditorUndoAct : public OTableDesignUndoAct\n {\n protected:\n OTableEditorCtrl* pTabEdCtrl;\n\n public:\n TYPEINFO();\n OTableEditorUndoAct( OTableEditorCtrl* pOwner,USHORT nCommentID );\n virtual ~OTableEditorUndoAct();\n };\n\n\n \/\/========================================================================\n class OTableDesignCellUndoAct : public OTableDesignUndoAct\n {\n protected:\n USHORT m_nCol;\n long m_nRow;\n ::com::sun::star::uno::Any m_sOldText;\n ::com::sun::star::uno::Any m_sNewText;\n\n virtual void Undo();\n virtual void Redo();\n public:\n TYPEINFO();\n OTableDesignCellUndoAct( OTableRowView* pOwner, long nRowID, USHORT nColumn );\n virtual ~OTableDesignCellUndoAct();\n };\n\n class OTypeInfo;\n \/\/========================================================================\n class OTableEditorTypeSelUndoAct : public OTableEditorUndoAct\n {\n protected:\n USHORT m_nCol;\n long m_nRow;\n TOTypeInfoSP m_pOldType;\n TOTypeInfoSP m_pNewType;\n\n virtual void Undo();\n virtual void Redo();\n public:\n TYPEINFO();\n OTableEditorTypeSelUndoAct( OTableEditorCtrl* pOwner, long nRowID, USHORT nColumn, const TOTypeInfoSP& _pOldType );\n virtual ~OTableEditorTypeSelUndoAct();\n };\n\n \/\/========================================================================\n class OTableEditorDelUndoAct : public OTableEditorUndoAct\n {\n protected:\n ::std::vector m_aDeletedRows;\n\n virtual void Undo();\n virtual void Redo();\n public:\n TYPEINFO();\n OTableEditorDelUndoAct( OTableEditorCtrl* pOwner );\n virtual ~OTableEditorDelUndoAct();\n };\n\n \/\/========================================================================\n class OTableEditorInsUndoAct : public OTableEditorUndoAct\n {\n protected:\n ::std::vector m_vInsertedRows;\n long m_nInsPos;\n\n virtual void Undo();\n virtual void Redo();\n public:\n TYPEINFO();\n OTableEditorInsUndoAct( OTableEditorCtrl* pOwner,\n long nInsertPosition,\n const ::std::vector< OTableRow*>& _vInsertedRows);\n virtual ~OTableEditorInsUndoAct();\n };\n\n \/\/========================================================================\n class OTableEditorInsNewUndoAct : public OTableEditorUndoAct\n {\n protected:\n long m_nInsPos;\n long m_nInsRows;\n\n virtual void Undo();\n virtual void Redo();\n public:\n TYPEINFO();\n OTableEditorInsNewUndoAct( OTableEditorCtrl* pOwner, long nInsertPosition, long nInsertedRows );\n virtual ~OTableEditorInsNewUndoAct();\n };\n\n \/\/========================================================================\n class OPrimKeyUndoAct : public OTableEditorUndoAct\n {\n protected:\n MultiSelection m_aDelKeys,\n m_aInsKeys;\n BOOL m_bActPrimKeySet;\n OTableEditorCtrl* m_pEditorCtrl;\n\n virtual void Undo();\n virtual void Redo();\n public:\n TYPEINFO();\n OPrimKeyUndoAct( OTableEditorCtrl* pOwner, MultiSelection aDeletedKeys, MultiSelection aInsertedKeys );\n virtual ~OPrimKeyUndoAct();\n };\n}\n#endif \/\/ DBAUI_TABLEUNDO_HXX\n\n\n<|endoftext|>"} {"text":"#include \r\n#include \"longnum_engine.h\"\r\n#include \r\nusing namespace std;\r\n\r\nint main () {\r\n unsigned int input;\r\n std::queue q;\r\n longnum result, tmp;\r\n \r\n do {\r\n printf(\"Enter num : \");\r\n scanf(\"%u\", &input);\r\n \r\n if (input != 0) {\r\n tmp = int_to_longnum(input);\r\n q.push(tmp);\r\n }\r\n } while (input != 0);\r\n \r\n result = longnum_multinum_sum(q);\r\n printf(\"\\n\");\r\n longnum_print(result);\r\n printf(\"\\n\");\r\n longnum_free(result);\r\n \r\n return 0;\r\n}\r\nEdit longnum_engine-multinum-sum demo program to use new interface of longnum_multinum_sum.#include \r\n#include \"longnum_engine.h\"\r\n\/\/#include \r\n\/\/using namespace std;\n#include \r\n\r\nint main () {\r\n unsigned int input;\r\n \/\/std::queue q;\n longnum *sum_numbers = NULL;\n unsigned sum_numbers_amount = 0, sum_numbers_limit=0;\r\n longnum result, tmp;\n\n sum_numbers_limit = 4;\n sum_numbers = (longnum *) malloc(sum_numbers_limit * sizeof(longnum));\r\n\r\n do {\r\n printf(\"Enter num : \");\r\n scanf(\"%u\", &input);\r\n\r\n if (input != 0) {\r\n tmp = int_to_longnum(input);\r\n \/\/q.push(tmp);\n if (sum_numbers_amount == sum_numbers_limit) {\n sum_numbers_limit *= 2;\n sum_numbers = (longnum *) realloc(sum_numbers, sum_numbers_limit * sizeof(longnum));\n }\n sum_numbers[sum_numbers_amount] = tmp;\n sum_numbers_amount++;\r\n }\r\n } while (input != 0);\r\n\r\n result = longnum_multinum_sum(\/*q*\/sum_numbers, sum_numbers_amount);\r\n printf(\"\\n\");\r\n longnum_print(result);\r\n printf(\"\\n\");\r\n longnum_free(result);\r\n\r\n return 0;\r\n}\r\n<|endoftext|>"} {"text":"#include \"testing\/testing.hpp\"\n\n#include \"partners_api\/partners_api_tests\/async_gui_thread.hpp\"\n\n#include \"partners_api\/taxi_engine.hpp\"\n#include \"partners_api\/uber_api.hpp\"\n#include \"partners_api\/yandex_api.hpp\"\n\n#include \"platform\/gui_thread.hpp\"\n\n#include \"geometry\/latlon.hpp\"\n\n#include \"base\/scope_guard.hpp\"\n#include \"base\/stl_add.hpp\"\n#include \"base\/worker_thread.hpp\"\n\nusing namespace partners_api;\n\nnamespace\n{\nclass BelarusMinskDelegate : public taxi::Delegate\n{\npublic:\n storage::TCountriesVec GetCountryIds(ms::LatLon const & latlon) override { return {\"Belarus\"}; }\n\n std::string GetCityName(ms::LatLon const & latlon) override { return \"Minsk\"; }\n};\n\nclass UkraineOdessaDelegate : public taxi::Delegate\n{\npublic:\n storage::TCountriesVec GetCountryIds(ms::LatLon const & latlon) override { return {\"Ukraine\"}; }\n\n std::string GetCityName(ms::LatLon const & latlon) override { return \"Odessa\"; }\n};\n\nclass UsaDelegate : public taxi::Delegate\n{\npublic:\n storage::TCountriesVec GetCountryIds(ms::LatLon const & latlon) override\n {\n return {\"United States of America\"};\n }\n\n std::string GetCityName(ms::LatLon const & latlon) override { return \"\"; }\n};\n\nclass RussiaKonetsDelegate : public taxi::Delegate\n{\npublic:\n storage::TCountriesVec GetCountryIds(ms::LatLon const & latlon) override\n {\n return {\"Russian Federation\"};\n }\n\n std::string GetCityName(ms::LatLon const & latlon) override { return \"Konets\"; }\n};\n\nstd::vector GetUberSynchronous(ms::LatLon const & from, ms::LatLon const & to,\n std::string const & url)\n{\n std::string times;\n std::string prices;\n\n TEST(taxi::uber::RawApi::GetEstimatedTime(from, times, url), ());\n TEST(taxi::uber::RawApi::GetEstimatedPrice(from, to, prices, url), ());\n\n size_t reqId = 0;\n taxi::uber::ProductMaker maker;\n std::vector uberProducts;\n\n maker.Reset(reqId);\n maker.SetTimes(reqId, times);\n maker.SetPrices(reqId, prices);\n maker.MakeProducts(\n reqId, [&uberProducts](vector const & products) { uberProducts = products; },\n [](taxi::ErrorCode const code) { TEST(false, (code)); });\n\n return uberProducts;\n}\n\nstd::vector GetYandexSynchronous(ms::LatLon const & from, ms::LatLon const & to,\n std::string const & url)\n{\n std::string yandexAnswer;\n std::vector yandexProducts;\n\n TEST(taxi::yandex::RawApi::GetTaxiInfo(from, to, yandexAnswer, url), ());\n\n taxi::yandex::MakeFromJson(yandexAnswer, yandexProducts);\n\n return yandexProducts;\n}\n\ntaxi::ProvidersContainer GetProvidersSynchronous(taxi::Engine const & engine,\n ms::LatLon const & from, ms::LatLon const & to,\n std::string const & url)\n{\n taxi::ProvidersContainer providers;\n\n for (auto const provider : engine.GetProvidersAtPos(from))\n {\n switch (provider)\n {\n case taxi::Provider::Type::Uber:\n providers.emplace_back(taxi::Provider::Type::Uber, GetUberSynchronous(from, to, url));\n break;\n case taxi::Provider::Type::Yandex:\n providers.emplace_back(taxi::Provider::Type::Yandex, GetYandexSynchronous(from, to, url));\n break;\n }\n }\n\n return providers;\n}\n\nbool CompareProviders(taxi::ProvidersContainer const & lhs, taxi::ProvidersContainer const & rhs)\n{\n TEST_EQUAL(rhs.size(), lhs.size(), ());\n\n auto const Match = [](taxi::Provider const & lhs, taxi::Provider const & rhs) -> bool {\n if (lhs.GetType() != rhs.GetType())\n return false;\n\n auto const & lps = lhs.GetProducts();\n auto const & rps = rhs.GetProducts();\n\n TEST_EQUAL(lps.size(), rps.size(), ());\n\n for (auto const & lp : lps)\n {\n auto const it = std::find_if(rps.cbegin(), rps.cend(), [&lp](taxi::Product const & rp) {\n return lp.m_productId == rp.m_productId && lp.m_name == rp.m_name &&\n lp.m_price == rp.m_price;\n });\n\n if (it == rps.cend())\n return false;\n }\n\n return true;\n };\n\n auto const m = lhs.size();\n\n vector used(m);\n \/\/ TODO (@y) Change it to algorithm, based on bipartite graphs.\n for (auto const & rItem : rhs)\n {\n bool isMatched = false;\n for (size_t i = 0; i < m; ++i)\n {\n if (used[i])\n continue;\n\n if (Match(rItem, lhs[i]))\n {\n used[i] = true;\n isMatched = true;\n break;\n }\n }\n\n if (!isMatched)\n return false;\n }\n return true;\n}\n\nUNIT_CLASS_TEST(AsyncGuiThread, TaxiEngine_ResultMaker)\n{\n taxi::ResultMaker maker;\n uint64_t reqId = 1;\n taxi::ProvidersContainer providers;\n taxi::ErrorsContainer errors;\n\n auto const successCallback = [&reqId, &providers](taxi::ProvidersContainer const & products,\n uint64_t const requestId) {\n TEST_EQUAL(reqId, requestId, ());\n providers = products;\n testing::Notify();\n };\n\n auto const successNotPossibleCallback =\n [&reqId, &providers](taxi::ProvidersContainer const & products, uint64_t const requestId) {\n TEST(false, (\"successNotPossibleCallback\", requestId));\n };\n\n auto const errorCallback = [&reqId, &errors](taxi::ErrorsContainer const e,\n uint64_t const requestId) {\n TEST_EQUAL(reqId, requestId, ());\n errors = e;\n testing::Notify();\n };\n\n auto const errorNotPossibleCallback = [&reqId](taxi::ErrorsContainer const errors,\n uint64_t const requestId) {\n TEST(false, (\"errorNotPossibleCallback\", requestId, errors));\n };\n\n \/\/ Try to image what products1 and products2 are lists of products for different taxi providers.\n \/\/ Only product id is important for us, all other fields are empty.\n std::vector products1 =\n {\n {\"1\", \"\", \"\", \"\", \"\"},\n {\"2\", \"\", \"\", \"\", \"\"},\n {\"3\", \"\", \"\", \"\", \"\"},\n };\n\n std::vector products2 =\n {\n {\"4\", \"\", \"\", \"\", \"\"},\n {\"5\", \"\", \"\", \"\", \"\"},\n {\"6\", \"\", \"\", \"\", \"\"},\n };\n\n maker.Reset(reqId, 2, successCallback, errorNotPossibleCallback);\n maker.ProcessProducts(reqId, taxi::Provider::Type::Uber, products1);\n maker.ProcessProducts(reqId, taxi::Provider::Type::Yandex, products2);\n\n TEST(providers.empty(), ());\n TEST(errors.empty(), ());\n\n maker.Reset(reqId, 3, successCallback, errorNotPossibleCallback);\n maker.ProcessProducts(reqId, taxi::Provider::Type::Uber, products1);\n maker.ProcessProducts(reqId, taxi::Provider::Type::Yandex, products2);\n maker.DecrementRequestCount(reqId);\n maker.MakeResult(reqId);\n\n testing::Wait();\n\n TEST_EQUAL(providers.size(), 2, ());\n TEST_EQUAL(providers[0].GetType(), taxi::Provider::Type::Uber, ());\n TEST_EQUAL(providers[1].GetType(), taxi::Provider::Type::Yandex, ());\n TEST_EQUAL(providers[0][0].m_productId, \"1\", ());\n TEST_EQUAL(providers[0][1].m_productId, \"2\", ());\n TEST_EQUAL(providers[0][2].m_productId, \"3\", ());\n TEST_EQUAL(providers[1][0].m_productId, \"4\", ());\n TEST_EQUAL(providers[1][1].m_productId, \"5\", ());\n TEST_EQUAL(providers[1][2].m_productId, \"6\", ());\n\n maker.Reset(reqId, 2, successCallback, errorNotPossibleCallback);\n maker.ProcessError(reqId, taxi::Provider::Type::Uber, taxi::ErrorCode::NoProducts);\n maker.ProcessProducts(reqId, taxi::Provider::Type::Yandex, products2);\n maker.MakeResult(reqId);\n\n testing::Wait();\n\n TEST_EQUAL(providers.size(), 1, ());\n TEST_EQUAL(providers[0].GetType(), taxi::Provider::Type::Yandex, ());\n TEST_EQUAL(providers[0][0].m_productId, \"4\", ());\n TEST_EQUAL(providers[0][1].m_productId, \"5\", ());\n TEST_EQUAL(providers[0][2].m_productId, \"6\", ());\n\n maker.Reset(reqId, 2, successNotPossibleCallback, errorCallback);\n maker.ProcessError(reqId, taxi::Provider::Type::Uber, taxi::ErrorCode::NoProducts);\n maker.ProcessError(reqId, taxi::Provider::Type::Yandex, taxi::ErrorCode::RemoteError);\n maker.MakeResult(reqId);\n\n testing::Wait();\n\n TEST_EQUAL(errors.size(), 2, ());\n TEST_EQUAL(errors[0].m_type, taxi::Provider::Type::Uber, ());\n TEST_EQUAL(errors[0].m_code, taxi::ErrorCode::NoProducts, ());\n TEST_EQUAL(errors[1].m_type, taxi::Provider::Type::Yandex, ());\n TEST_EQUAL(errors[1].m_code, taxi::ErrorCode::RemoteError, ());\n\n maker.Reset(reqId, 2, successCallback, errorNotPossibleCallback);\n maker.DecrementRequestCount(reqId);\n maker.DecrementRequestCount(reqId);\n maker.MakeResult(reqId);\n\n testing::Wait();\n}\n\nUNIT_CLASS_TEST(AsyncGuiThread, TaxiEngine_Smoke)\n{\n \/\/ Used to synchronize access into GetAvailableProducts callback method.\n std::mutex resultsMutex;\n size_t reqId = 1;\n taxi::ProvidersContainer providersContainer;\n ms::LatLon const from(38.897724, -77.036531);\n ms::LatLon const to(38.862416, -76.883316);\n std::string const kTesturl = \"http:\/\/localhost:34568\/partners\";\n\n auto const errorCallback = [](taxi::ErrorsContainer const & errors, uint64_t const requestId) {\n TEST(false, ());\n };\n\n auto const errorPossibleCallback = [](taxi::ErrorsContainer const & errors,\n uint64_t const requestId) {\n for (auto const & error : errors)\n TEST(error.m_code == taxi::ErrorCode::NoProducts, ());\n };\n\n auto const standardCallback = [&reqId, &providersContainer, &resultsMutex](\n taxi::ProvidersContainer const & providers,\n uint64_t const requestId) {\n std::lock_guard lock(resultsMutex);\n\n if (reqId == requestId)\n providersContainer = providers;\n };\n\n auto const lastCallback = [&standardCallback](taxi::ProvidersContainer const & products,\n uint64_t const requestId) {\n standardCallback(products, requestId);\n testing::StopEventLoop();\n };\n\n taxi::Engine engine(\n {{taxi::Provider::Type::Uber, kTesturl}, {taxi::Provider::Type::Yandex, kTesturl}});\n\n engine.SetDelegate(my::make_unique());\n\n taxi::ProvidersContainer const synchronousProviders =\n GetProvidersSynchronous(engine, from, to, kTesturl);\n\n TEST(!synchronousProviders.empty(), ());\n\n {\n {\n lock_guard lock(resultsMutex);\n reqId = engine.GetAvailableProducts(ms::LatLon(55.753960, 37.624513),\n ms::LatLon(55.765866, 37.661270), standardCallback,\n errorPossibleCallback);\n }\n {\n lock_guard lock(resultsMutex);\n reqId = engine.GetAvailableProducts(ms::LatLon(59.922445, 30.367201),\n ms::LatLon(59.943675, 30.361123), standardCallback,\n errorPossibleCallback);\n }\n {\n lock_guard lock(resultsMutex);\n reqId = engine.GetAvailableProducts(ms::LatLon(52.509621, 13.450067),\n ms::LatLon(52.510811, 13.409490), standardCallback,\n errorPossibleCallback);\n }\n {\n lock_guard lock(resultsMutex);\n reqId = engine.GetAvailableProducts(from, to, lastCallback, errorCallback);\n }\n }\n\n testing::RunEventLoop();\n\n TEST(!providersContainer.empty(), ());\n TEST(CompareProviders(providersContainer, synchronousProviders), ());\n}\n\nUNIT_TEST(TaxiEngine_GetProvidersAtPos)\n{\n taxi::Engine engine;\n \/\/ Lat lon is no needed for this test.\n ms::LatLon latlon(0.0, 0.0);\n std::vector providers;\n\n engine.SetDelegate(my::make_unique());\n providers = engine.GetProvidersAtPos(latlon);\n TEST_EQUAL(providers.size(), 1, ());\n TEST_EQUAL(providers[0], taxi::Provider::Type::Yandex, ());\n\n engine.SetDelegate(my::make_unique());\n providers = engine.GetProvidersAtPos(latlon);\n TEST_EQUAL(providers.size(), 1, ());\n TEST_EQUAL(providers[0], taxi::Provider::Type::Uber, ());\n\n engine.SetDelegate(my::make_unique());\n providers = engine.GetProvidersAtPos(latlon);\n TEST_EQUAL(providers.size(), 1, ());\n TEST_EQUAL(providers[0], taxi::Provider::Type::Uber, ());\n\n engine.SetDelegate(my::make_unique());\n providers = engine.GetProvidersAtPos(latlon);\n TEST(providers.empty(), (providers));\n}\n} \/\/ namespace\n[partners_api] taxi engine test fix#include \"testing\/testing.hpp\"\n\n#include \"partners_api\/partners_api_tests\/async_gui_thread.hpp\"\n\n#include \"partners_api\/taxi_engine.hpp\"\n#include \"partners_api\/uber_api.hpp\"\n#include \"partners_api\/yandex_api.hpp\"\n\n#include \"platform\/gui_thread.hpp\"\n\n#include \"geometry\/latlon.hpp\"\n\n#include \"base\/scope_guard.hpp\"\n#include \"base\/stl_add.hpp\"\n#include \"base\/worker_thread.hpp\"\n\nusing namespace partners_api;\n\nnamespace\n{\nclass BelarusMinskDelegate : public taxi::Delegate\n{\npublic:\n storage::TCountriesVec GetCountryIds(ms::LatLon const & latlon) override { return {\"Belarus\"}; }\n\n std::string GetCityName(ms::LatLon const & latlon) override { return \"Minsk\"; }\n};\n\nclass UkraineOdessaDelegate : public taxi::Delegate\n{\npublic:\n storage::TCountriesVec GetCountryIds(ms::LatLon const & latlon) override { return {\"Ukraine\"}; }\n\n std::string GetCityName(ms::LatLon const & latlon) override { return \"Odessa\"; }\n};\n\nclass BulgariaSofiaDelegate : public taxi::Delegate\n{\npublic:\n storage::TCountriesVec GetCountryIds(ms::LatLon const & latlon) override { return {\"Bulgaria\"}; }\n\n std::string GetCityName(ms::LatLon const & latlon) override { return \"Sofia\"; }\n};\n\nclass UsaDelegate : public taxi::Delegate\n{\npublic:\n storage::TCountriesVec GetCountryIds(ms::LatLon const & latlon) override\n {\n return {\"United States of America\"};\n }\n\n std::string GetCityName(ms::LatLon const & latlon) override { return \"\"; }\n};\n\nclass RussiaKonetsDelegate : public taxi::Delegate\n{\npublic:\n storage::TCountriesVec GetCountryIds(ms::LatLon const & latlon) override\n {\n return {\"Russian Federation\"};\n }\n\n std::string GetCityName(ms::LatLon const & latlon) override { return \"Konets\"; }\n};\n\nstd::vector GetUberSynchronous(ms::LatLon const & from, ms::LatLon const & to,\n std::string const & url)\n{\n std::string times;\n std::string prices;\n\n TEST(taxi::uber::RawApi::GetEstimatedTime(from, times, url), ());\n TEST(taxi::uber::RawApi::GetEstimatedPrice(from, to, prices, url), ());\n\n size_t reqId = 0;\n taxi::uber::ProductMaker maker;\n std::vector uberProducts;\n\n maker.Reset(reqId);\n maker.SetTimes(reqId, times);\n maker.SetPrices(reqId, prices);\n maker.MakeProducts(\n reqId, [&uberProducts](vector const & products) { uberProducts = products; },\n [](taxi::ErrorCode const code) { TEST(false, (code)); });\n\n return uberProducts;\n}\n\nstd::vector GetYandexSynchronous(ms::LatLon const & from, ms::LatLon const & to,\n std::string const & url)\n{\n std::string yandexAnswer;\n std::vector yandexProducts;\n\n TEST(taxi::yandex::RawApi::GetTaxiInfo(from, to, yandexAnswer, url), ());\n\n taxi::yandex::MakeFromJson(yandexAnswer, yandexProducts);\n\n return yandexProducts;\n}\n\ntaxi::ProvidersContainer GetProvidersSynchronous(taxi::Engine const & engine,\n ms::LatLon const & from, ms::LatLon const & to,\n std::string const & url)\n{\n taxi::ProvidersContainer providers;\n\n for (auto const provider : engine.GetProvidersAtPos(from))\n {\n switch (provider)\n {\n case taxi::Provider::Type::Uber:\n providers.emplace_back(taxi::Provider::Type::Uber, GetUberSynchronous(from, to, url));\n break;\n case taxi::Provider::Type::Yandex:\n providers.emplace_back(taxi::Provider::Type::Yandex, GetYandexSynchronous(from, to, url));\n break;\n }\n }\n\n return providers;\n}\n\nbool CompareProviders(taxi::ProvidersContainer const & lhs, taxi::ProvidersContainer const & rhs)\n{\n TEST_EQUAL(rhs.size(), lhs.size(), ());\n\n auto const Match = [](taxi::Provider const & lhs, taxi::Provider const & rhs) -> bool {\n if (lhs.GetType() != rhs.GetType())\n return false;\n\n auto const & lps = lhs.GetProducts();\n auto const & rps = rhs.GetProducts();\n\n TEST_EQUAL(lps.size(), rps.size(), ());\n\n for (auto const & lp : lps)\n {\n auto const it = std::find_if(rps.cbegin(), rps.cend(), [&lp](taxi::Product const & rp) {\n return lp.m_productId == rp.m_productId && lp.m_name == rp.m_name &&\n lp.m_price == rp.m_price;\n });\n\n if (it == rps.cend())\n return false;\n }\n\n return true;\n };\n\n auto const m = lhs.size();\n\n vector used(m);\n \/\/ TODO (@y) Change it to algorithm, based on bipartite graphs.\n for (auto const & rItem : rhs)\n {\n bool isMatched = false;\n for (size_t i = 0; i < m; ++i)\n {\n if (used[i])\n continue;\n\n if (Match(rItem, lhs[i]))\n {\n used[i] = true;\n isMatched = true;\n break;\n }\n }\n\n if (!isMatched)\n return false;\n }\n return true;\n}\n\nUNIT_CLASS_TEST(AsyncGuiThread, TaxiEngine_ResultMaker)\n{\n taxi::ResultMaker maker;\n uint64_t reqId = 1;\n taxi::ProvidersContainer providers;\n taxi::ErrorsContainer errors;\n\n auto const successCallback = [&reqId, &providers](taxi::ProvidersContainer const & products,\n uint64_t const requestId) {\n TEST_EQUAL(reqId, requestId, ());\n providers = products;\n testing::Notify();\n };\n\n auto const successNotPossibleCallback =\n [&reqId, &providers](taxi::ProvidersContainer const & products, uint64_t const requestId) {\n TEST(false, (\"successNotPossibleCallback\", requestId));\n };\n\n auto const errorCallback = [&reqId, &errors](taxi::ErrorsContainer const e,\n uint64_t const requestId) {\n TEST_EQUAL(reqId, requestId, ());\n errors = e;\n testing::Notify();\n };\n\n auto const errorNotPossibleCallback = [&reqId](taxi::ErrorsContainer const errors,\n uint64_t const requestId) {\n TEST(false, (\"errorNotPossibleCallback\", requestId, errors));\n };\n\n \/\/ Try to image what products1 and products2 are lists of products for different taxi providers.\n \/\/ Only product id is important for us, all other fields are empty.\n std::vector products1 =\n {\n {\"1\", \"\", \"\", \"\", \"\"},\n {\"2\", \"\", \"\", \"\", \"\"},\n {\"3\", \"\", \"\", \"\", \"\"},\n };\n\n std::vector products2 =\n {\n {\"4\", \"\", \"\", \"\", \"\"},\n {\"5\", \"\", \"\", \"\", \"\"},\n {\"6\", \"\", \"\", \"\", \"\"},\n };\n\n maker.Reset(reqId, 2, successCallback, errorNotPossibleCallback);\n maker.ProcessProducts(reqId, taxi::Provider::Type::Uber, products1);\n maker.ProcessProducts(reqId, taxi::Provider::Type::Yandex, products2);\n\n TEST(providers.empty(), ());\n TEST(errors.empty(), ());\n\n maker.Reset(reqId, 3, successCallback, errorNotPossibleCallback);\n maker.ProcessProducts(reqId, taxi::Provider::Type::Uber, products1);\n maker.ProcessProducts(reqId, taxi::Provider::Type::Yandex, products2);\n maker.DecrementRequestCount(reqId);\n maker.MakeResult(reqId);\n\n testing::Wait();\n\n TEST_EQUAL(providers.size(), 2, ());\n TEST_EQUAL(providers[0].GetType(), taxi::Provider::Type::Uber, ());\n TEST_EQUAL(providers[1].GetType(), taxi::Provider::Type::Yandex, ());\n TEST_EQUAL(providers[0][0].m_productId, \"1\", ());\n TEST_EQUAL(providers[0][1].m_productId, \"2\", ());\n TEST_EQUAL(providers[0][2].m_productId, \"3\", ());\n TEST_EQUAL(providers[1][0].m_productId, \"4\", ());\n TEST_EQUAL(providers[1][1].m_productId, \"5\", ());\n TEST_EQUAL(providers[1][2].m_productId, \"6\", ());\n\n maker.Reset(reqId, 2, successCallback, errorNotPossibleCallback);\n maker.ProcessError(reqId, taxi::Provider::Type::Uber, taxi::ErrorCode::NoProducts);\n maker.ProcessProducts(reqId, taxi::Provider::Type::Yandex, products2);\n maker.MakeResult(reqId);\n\n testing::Wait();\n\n TEST_EQUAL(providers.size(), 1, ());\n TEST_EQUAL(providers[0].GetType(), taxi::Provider::Type::Yandex, ());\n TEST_EQUAL(providers[0][0].m_productId, \"4\", ());\n TEST_EQUAL(providers[0][1].m_productId, \"5\", ());\n TEST_EQUAL(providers[0][2].m_productId, \"6\", ());\n\n maker.Reset(reqId, 2, successNotPossibleCallback, errorCallback);\n maker.ProcessError(reqId, taxi::Provider::Type::Uber, taxi::ErrorCode::NoProducts);\n maker.ProcessError(reqId, taxi::Provider::Type::Yandex, taxi::ErrorCode::RemoteError);\n maker.MakeResult(reqId);\n\n testing::Wait();\n\n TEST_EQUAL(errors.size(), 2, ());\n TEST_EQUAL(errors[0].m_type, taxi::Provider::Type::Uber, ());\n TEST_EQUAL(errors[0].m_code, taxi::ErrorCode::NoProducts, ());\n TEST_EQUAL(errors[1].m_type, taxi::Provider::Type::Yandex, ());\n TEST_EQUAL(errors[1].m_code, taxi::ErrorCode::RemoteError, ());\n\n maker.Reset(reqId, 2, successCallback, errorNotPossibleCallback);\n maker.DecrementRequestCount(reqId);\n maker.DecrementRequestCount(reqId);\n maker.MakeResult(reqId);\n\n testing::Wait();\n}\n\nUNIT_CLASS_TEST(AsyncGuiThread, TaxiEngine_Smoke)\n{\n \/\/ Used to synchronize access into GetAvailableProducts callback method.\n std::mutex resultsMutex;\n size_t reqId = 1;\n taxi::ProvidersContainer providersContainer;\n ms::LatLon const from(38.897724, -77.036531);\n ms::LatLon const to(38.862416, -76.883316);\n std::string const kTesturl = \"http:\/\/localhost:34568\/partners\";\n\n auto const errorCallback = [](taxi::ErrorsContainer const & errors, uint64_t const requestId) {\n TEST(false, ());\n };\n\n auto const errorPossibleCallback = [](taxi::ErrorsContainer const & errors,\n uint64_t const requestId) {\n for (auto const & error : errors)\n TEST(error.m_code == taxi::ErrorCode::NoProducts, ());\n };\n\n auto const standardCallback = [&reqId, &providersContainer, &resultsMutex](\n taxi::ProvidersContainer const & providers,\n uint64_t const requestId) {\n std::lock_guard lock(resultsMutex);\n\n if (reqId == requestId)\n providersContainer = providers;\n };\n\n auto const lastCallback = [&standardCallback](taxi::ProvidersContainer const & products,\n uint64_t const requestId) {\n standardCallback(products, requestId);\n testing::StopEventLoop();\n };\n\n taxi::Engine engine(\n {{taxi::Provider::Type::Uber, kTesturl}, {taxi::Provider::Type::Yandex, kTesturl}});\n\n engine.SetDelegate(my::make_unique());\n\n taxi::ProvidersContainer const synchronousProviders =\n GetProvidersSynchronous(engine, from, to, kTesturl);\n\n TEST(!synchronousProviders.empty(), ());\n\n {\n {\n lock_guard lock(resultsMutex);\n reqId = engine.GetAvailableProducts(ms::LatLon(55.753960, 37.624513),\n ms::LatLon(55.765866, 37.661270), standardCallback,\n errorPossibleCallback);\n }\n {\n lock_guard lock(resultsMutex);\n reqId = engine.GetAvailableProducts(ms::LatLon(59.922445, 30.367201),\n ms::LatLon(59.943675, 30.361123), standardCallback,\n errorPossibleCallback);\n }\n {\n lock_guard lock(resultsMutex);\n reqId = engine.GetAvailableProducts(ms::LatLon(52.509621, 13.450067),\n ms::LatLon(52.510811, 13.409490), standardCallback,\n errorPossibleCallback);\n }\n {\n lock_guard lock(resultsMutex);\n reqId = engine.GetAvailableProducts(from, to, lastCallback, errorCallback);\n }\n }\n\n testing::RunEventLoop();\n\n TEST(!providersContainer.empty(), ());\n TEST(CompareProviders(providersContainer, synchronousProviders), ());\n}\n\nUNIT_TEST(TaxiEngine_GetProvidersAtPos)\n{\n taxi::Engine engine;\n \/\/ Lat lon is no needed for this test.\n ms::LatLon latlon(0.0, 0.0);\n std::vector providers;\n\n engine.SetDelegate(my::make_unique());\n providers = engine.GetProvidersAtPos(latlon);\n TEST_EQUAL(providers.size(), 1, ());\n TEST_EQUAL(providers[0], taxi::Provider::Type::Yandex, ());\n\n engine.SetDelegate(my::make_unique());\n providers = engine.GetProvidersAtPos(latlon);\n TEST_EQUAL(providers.size(), 1, ());\n TEST_EQUAL(providers[0], taxi::Provider::Type::Yandex, ());\n\n engine.SetDelegate(my::make_unique());\n providers = engine.GetProvidersAtPos(latlon);\n TEST_EQUAL(providers.size(), 1, ());\n TEST_EQUAL(providers[0], taxi::Provider::Type::Uber, ());\n\n engine.SetDelegate(my::make_unique());\n providers = engine.GetProvidersAtPos(latlon);\n TEST_EQUAL(providers.size(), 1, ());\n TEST_EQUAL(providers[0], taxi::Provider::Type::Uber, ());\n\n engine.SetDelegate(my::make_unique());\n providers = engine.GetProvidersAtPos(latlon);\n TEST(providers.empty(), (providers));\n}\n} \/\/ namespace\n<|endoftext|>"} {"text":"\/*------------------------------------------------------------------------------\n *\n * This file is part of rendermq \n *\n * Author: matt.amos@mapquest.com\n *\n * Copyright 2010-1 Mapquest, Inc. All Rights reserved.\n *\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n *\n *-----------------------------------------------------------------------------*\/\n\n#include \"common.hpp\"\n#include \"..\/logging\/logger.hpp\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#ifdef HAVE_BLACKBOX\n#include \n#endif\n\nusing boost::function;\nusing std::runtime_error;\nusing std::exception;\nusing std::cout;\nusing std::clog;\nusing std::cerr;\nusing std::endl;\nusing std::setw;\nusing std::flush;\nusing std::string;\nusing std::vector;\nnamespace fs = boost::filesystem;\n\n#define TEST_NAME_WIDTH (45)\n\nnamespace {\n\nvoid run_with_output_redirected_to(const string &name, function test) {\n \/\/ create a file for the output to go to.\n string file_name = string(\"log\/\") + name + \".testlog\";\n\n#ifdef HAVE_BLACKBOX\n ::blackbox::logging::log::configure(conf); \n#endif\n\n \/\/ run the test\n test();\n}\n\n}\n\nnamespace test {\n\nint run(const string &name, function test) {\n cout << setw(TEST_NAME_WIDTH) << name << flush;\n try {\n run_with_output_redirected_to(name, test);\n cout << \" [PASS]\" << endl;\n return 0;\n\n } catch (const exception &ex) {\n cout << \" [FAIL: \" << ex.what() << \"]\" << endl;\n return 1;\n\n } catch (...) {\n cerr << \" [FAIL: Unexpected error]\" << endl;\n throw;\n }\n}\n\njson::json() : m_type(json::type_NONE) {}\njson::json(const json &j) : m_type(j.m_type), m_buf(j.m_buf.str()) {}\n\nstd::ostream &operator<<(std::ostream &out, const json &j) {\n if (j.m_type == json::type_NONE) {\n out << \"null\";\n\n } else {\n out << j.m_buf.str();\n if (j.m_type == json::type_DICT) {\n out << \"}\";\n } else {\n out << \"]\";\n }\n }\n return out;\n}\n\nvoid json::quote(const json &j) { m_buf << j; }\nvoid json::quote(const std::string &s) { m_buf << \"\\\"\" << s << \"\\\"\"; }\nvoid json::quote(int i) { m_buf << i; }\nvoid json::quote(double d) { m_buf << d; }\n\ntemp_dir::temp_dir()\n : m_path(fs::temp_directory_path() \/ fs::unique_path(\"nms-test-%%%%-%%%%-%%%%-%%%%\")) {\n fs::create_directories(m_path);\n}\n\ntemp_dir::~temp_dir() {\n \/\/ files might be deleted by other things while this is running\n \/\/ (0MQ context thread, i'm looking at you), and this isn't\n \/\/ necessarily an error as far as this code is concerned - it\n \/\/ just wants to delete everything underneath the temporary\n \/\/ directory.\n boost::system::error_code err;\n\n \/\/ catch all errors - we don't want to throw in the destructor\n try {\n \/\/ but loop while the path exists and the errors are\n \/\/ ignorable.\n while (fs::exists(m_path)) {\n fs::remove_all(m_path, err);\n\n \/\/ for any non-ignorable error, there's not much we can\n \/\/ do from the destructor except complain loudly.\n if (err && (err != boost::system::errc::no_such_file_or_directory)) {\n LOG_WARNING(boost::format(\"Unable to remove temporary \"\n \"directory %1%: %2%\")\n % m_path % err.message());\n break;\n }\n }\n\n } catch (const std::exception &e) {\n LOG_ERROR(boost::format(\"Exception caught while trying to remove \"\n \"temporary directory %1%: %2%\")\n % m_path % e.what());\n\n } catch (...) {\n LOG_ERROR(boost::format(\"Unknown exception caught while trying to \"\n \"remove temporary directory %1%\")\n % m_path);\n }\n}\n\n}\nRemove blackbox references from logging common\/*------------------------------------------------------------------------------\n *\n * This file is part of avecado\n *\n * Author: matt.amos@mapquest.com\n *\n * Copyright 2010-1 Mapquest, Inc. All Rights reserved.\n *\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n *\n *-----------------------------------------------------------------------------*\/\n\n#include \"common.hpp\"\n#include \"..\/logging\/logger.hpp\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nusing boost::function;\nusing std::runtime_error;\nusing std::exception;\nusing std::cout;\nusing std::clog;\nusing std::cerr;\nusing std::endl;\nusing std::setw;\nusing std::flush;\nusing std::string;\nusing std::vector;\nnamespace fs = boost::filesystem;\n\n#define TEST_NAME_WIDTH (45)\n\nnamespace {\n\nvoid run_with_output_redirected_to(const string &name, function test) {\n \/\/ create a file for the output to go to.\n string file_name = string(\"log\/\") + name + \".testlog\";\n\n \/\/ run the test\n test();\n}\n\n}\n\nnamespace test {\n\nint run(const string &name, function test) {\n cout << setw(TEST_NAME_WIDTH) << name << flush;\n try {\n run_with_output_redirected_to(name, test);\n cout << \" [PASS]\" << endl;\n return 0;\n\n } catch (const exception &ex) {\n cout << \" [FAIL: \" << ex.what() << \"]\" << endl;\n return 1;\n\n } catch (...) {\n cerr << \" [FAIL: Unexpected error]\" << endl;\n throw;\n }\n}\n\njson::json() : m_type(json::type_NONE) {}\njson::json(const json &j) : m_type(j.m_type), m_buf(j.m_buf.str()) {}\n\nstd::ostream &operator<<(std::ostream &out, const json &j) {\n if (j.m_type == json::type_NONE) {\n out << \"null\";\n\n } else {\n out << j.m_buf.str();\n if (j.m_type == json::type_DICT) {\n out << \"}\";\n } else {\n out << \"]\";\n }\n }\n return out;\n}\n\nvoid json::quote(const json &j) { m_buf << j; }\nvoid json::quote(const std::string &s) { m_buf << \"\\\"\" << s << \"\\\"\"; }\nvoid json::quote(int i) { m_buf << i; }\nvoid json::quote(double d) { m_buf << d; }\n\ntemp_dir::temp_dir()\n : m_path(fs::temp_directory_path() \/ fs::unique_path(\"nms-test-%%%%-%%%%-%%%%-%%%%\")) {\n fs::create_directories(m_path);\n}\n\ntemp_dir::~temp_dir() {\n \/\/ files might be deleted by other things while this is running\n \/\/ (0MQ context thread, i'm looking at you), and this isn't\n \/\/ necessarily an error as far as this code is concerned - it\n \/\/ just wants to delete everything underneath the temporary\n \/\/ directory.\n boost::system::error_code err;\n\n \/\/ catch all errors - we don't want to throw in the destructor\n try {\n \/\/ but loop while the path exists and the errors are\n \/\/ ignorable.\n while (fs::exists(m_path)) {\n fs::remove_all(m_path, err);\n\n \/\/ for any non-ignorable error, there's not much we can\n \/\/ do from the destructor except complain loudly.\n if (err && (err != boost::system::errc::no_such_file_or_directory)) {\n LOG_WARNING(boost::format(\"Unable to remove temporary \"\n \"directory %1%: %2%\")\n % m_path % err.message());\n break;\n }\n }\n\n } catch (const std::exception &e) {\n LOG_ERROR(boost::format(\"Exception caught while trying to remove \"\n \"temporary directory %1%: %2%\")\n % m_path % e.what());\n\n } catch (...) {\n LOG_ERROR(boost::format(\"Unknown exception caught while trying to \"\n \"remove temporary directory %1%\")\n % m_path);\n }\n}\n\n}\n<|endoftext|>"} {"text":"\/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- *\/\n\/*\n * Copyright 2016 Couchbase, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"config.h\"\n#include \"subdocument_context.h\"\n#include \"debug_helpers.h\"\n#include \"mc_time.h\"\n#include \"protocol\/mcbp\/engine_wrapper.h\"\n#include \"subdocument.h\"\n\n#include \n#include \n\n#include \n#include \n#include \n#include \n\nSubdocCmdContext::OperationSpec::OperationSpec(SubdocCmdTraits traits_,\n protocol_binary_subdoc_flag flags_,\n cb::const_char_buffer path_)\n : SubdocCmdContext::OperationSpec::OperationSpec(traits_, flags_, path_,\n {nullptr, 0}) {\n}\n\nSubdocCmdContext::OperationSpec::OperationSpec(SubdocCmdTraits traits_,\n protocol_binary_subdoc_flag flags_,\n cb::const_char_buffer path_,\n cb::const_char_buffer value_)\n : traits(traits_),\n flags(flags_),\n path(path_),\n value(value_),\n status(PROTOCOL_BINARY_RESPONSE_EINTERNAL) {\n if (flags & SUBDOC_FLAG_MKDIR_P) {\n traits.subdocCommand = Subdoc::Command(traits.subdocCommand |\n Subdoc::Command::FLAG_MKDIR_P);\n }\n}\n\nSubdocCmdContext::OperationSpec::OperationSpec(OperationSpec&& other)\n : traits(other.traits),\n flags(other.flags),\n path(std::move(other.path)),\n value(std::move(other.value)) {}\n\nuint64_t SubdocCmdContext::getOperationValueBytesTotal() const {\n uint64_t result = 0;\n for (auto& ops : operations) {\n for (auto& op : ops) {\n result += op.value.len;\n }\n }\n return result;\n}\n\ntemplate \nstd::string SubdocCmdContext::macroToString(T macroValue) {\n std::stringstream ss;\n ss << std::hex << std::setfill('0');\n ss << \"\\\"0x\" << std::setw(sizeof(T) * 2) << macroValue << \"\\\"\";\n return ss.str();\n}\n\nENGINE_ERROR_CODE SubdocCmdContext::pre_link_document(item_info& info) {\n if (do_macro_expansion) {\n auto bodyoffset = cb::xattr::get_body_offset(\n {static_cast(info.value[0].iov_base),\n info.value[0].iov_len});\n\n cb::byte_buffer blob_buffer{\n static_cast(info.value[0].iov_base),\n bodyoffset};\n\n cb::xattr::Blob xattr_blob(blob_buffer);\n auto value = xattr_blob.get(xattr_key);\n if (value.len == 0) {\n \/\/ The segment is no longer there (we may have had another\n \/\/ subdoc command which rewrote the segment where we injected\n \/\/ the macro.\n return ENGINE_SUCCESS;\n }\n\n \/\/ Replace the CAS\n if (std::any_of(std::begin(paddedMacros),\n std::end(paddedMacros),\n [](const MacroPair& m) {\n return m.first == cb::xattr::macros::CAS;\n })) {\n substituteMacro(cb::xattr::macros::CAS,\n macroToString(htonll(info.cas)),\n value);\n }\n\n \/\/ Replace the Seqno\n if (std::any_of(std::begin(paddedMacros),\n std::end(paddedMacros),\n [](const MacroPair& m) {\n return m.first == cb::xattr::macros::SEQNO;\n })) {\n substituteMacro(\n cb::xattr::macros::SEQNO, macroToString(info.seqno), value);\n }\n }\n\n return ENGINE_SUCCESS;\n}\n\nvoid SubdocCmdContext::substituteMacro(cb::const_char_buffer macroName,\n const std::string& macroValue,\n cb::byte_buffer& value) {\n \/\/ Do an in-place substitution of the real macro value where we\n \/\/ wrote the padded macro string.\n uint8_t* root = value.buf;\n uint8_t* end = value.buf + value.len;\n auto& macro = std::find_if(std::begin(paddedMacros),\n std::end(paddedMacros),\n [macroName](const MacroPair& m) {\n return m.first == macroName;\n })\n ->second;\n auto* needle = macro.data();\n auto* needle_end = macro.data() + macro.length();\n\n \/\/ This replaces ALL instances of the padded string\n while ((root = std::search(root, end, needle, needle_end)) != end) {\n std::copy(macroValue.data(),\n macroValue.data() + macroValue.length(),\n root);\n root += macroValue.length();\n }\n}\n\ncb::const_char_buffer SubdocCmdContext::get_padded_macro(\n cb::const_char_buffer macro) {\n return std::find_if(\n std::begin(paddedMacros),\n std::end(paddedMacros),\n [macro](const MacroPair& a) { return a.first == macro; })\n ->second;\n}\n\nstatic inline std::string to_hex_string(uint64_t value) {\n std::stringstream ss;\n ss << std::hex << std::setfill('0');\n ss << \"0x\" << std::setw(16) << value;\n return ss.str();\n}\n\nvoid SubdocCmdContext::generate_macro_padding(cb::const_char_buffer payload,\n cb::const_char_buffer macro) {\n if (!do_macro_expansion) {\n \/\/ macro expansion is not needed\n return;\n }\n\n bool unique = false;\n std::random_device rd;\n std::mt19937 gen(rd());\n std::uniform_int_distribution dis;\n\n while (!unique) {\n unique = true;\n uint64_t ii = dis(gen);\n const std::string candidate = \"\\\"\" + to_hex_string(ii) + \"\\\"\";\n\n for (auto& op : getOperations(Phase::XATTR)) {\n if (cb::strnstr(op.value.buf, candidate.c_str(), op.value.len)) {\n unique = false;\n break;\n }\n }\n\n if (unique) {\n if (cb::strnstr(payload.buf, candidate.c_str(), payload.len)) {\n unique = false;\n } else {\n paddedMacros.push_back(std::make_pair(macro, candidate));\n }\n }\n }\n}\n\nvoid SubdocCmdContext::setMutationSemantics(mcbp::subdoc::doc_flag docFlags) {\n if (docFlags == mcbp::subdoc::doc_flag::Add) {\n mutationSemantics = MutationSemantics::Add;\n } else if (docFlags == mcbp::subdoc::doc_flag::Mkdoc) {\n mutationSemantics = MutationSemantics::Set;\n } else {\n mutationSemantics = MutationSemantics::Replace;\n }\n}\n\ncb::const_char_buffer SubdocCmdContext::get_document_vattr() {\n if (document_vattr.empty()) {\n \/\/ @todo we can optimize this by building the json in a more efficient\n \/\/ way, but for now just do it by using cJSON...\n unique_cJSON_ptr doc(cJSON_CreateObject());\n\n cJSON_AddStringToObject(\n doc.get(), \"CAS\", to_hex_string(input_item_info.cas).c_str());\n\n cJSON_AddStringToObject(\n doc.get(),\n \"vbucket_uuid\",\n to_hex_string(input_item_info.vbucket_uuid).c_str());\n\n cJSON_AddStringToObject(doc.get(),\n \"seqno\",\n to_hex_string(input_item_info.seqno).c_str());\n\n cJSON_AddNumberToObject(doc.get(), \"exptime\", input_item_info.exptime);\n\n \/\/ The flags are kept internally in network byte order...\n cJSON_AddNumberToObject(\n doc.get(), \"flags\", ntohl(input_item_info.flags));\n\n if (mcbp::datatype::is_xattr(input_item_info.datatype)) {\n \/\/ strip off xattr\n auto bodyoffset = cb::xattr::get_body_offset(\n {static_cast(\n input_item_info.value[0].iov_base),\n input_item_info.value[0].iov_len});\n cJSON_AddNumberToObject(doc.get(),\n \"value_bytes\",\n input_item_info.nbytes - bodyoffset);\n } else {\n cJSON_AddNumberToObject(\n doc.get(), \"value_bytes\", input_item_info.nbytes);\n }\n\n unique_cJSON_ptr array(cJSON_CreateArray());\n auto datatypes = split_string(\n mcbp::datatype::to_string(input_item_info.datatype), \",\");\n for (const auto& d : datatypes) {\n cJSON_AddItemToArray(array.get(), cJSON_CreateString(d.c_str()));\n }\n\n cJSON_AddItemToObject(doc.get(), \"datatype\", array.release());\n\n cJSON_AddBoolToObject(\n doc.get(),\n \"deleted\",\n input_item_info.document_state == DocumentState::Deleted);\n\n if (input_item_info.cas_is_hlc) {\n \/\/ convert nanoseconds CAS into seconds and ensure u64 before cJSON\n \/\/ converts to a double internally.\n std::chrono::nanoseconds ns(input_item_info.cas);\n cJSON_AddStringToObject(\n doc.get(),\n \"last_modified\",\n std::to_string(uint64_t(std::chrono::duration_cast<\n std::chrono::seconds>(ns)\n .count()))\n .c_str());\n }\n unique_cJSON_ptr root(cJSON_CreateObject());\n cJSON_AddItemToObject(root.get(), \"$document\", doc.release());\n document_vattr = to_string(root, false);\n }\n\n return cb::const_char_buffer(document_vattr.data(), document_vattr.size());\n}\n\ncb::const_char_buffer SubdocCmdContext::get_xtoc_vattr() {\n if (!mcbp::datatype::is_xattr(in_datatype)) {\n xtoc_vattr = R\"({\"$XTOC\":[]})\";\n return cb::const_char_buffer(xtoc_vattr.data(), xtoc_vattr.size());\n }\n if (xtoc_vattr.empty()) {\n unique_cJSON_ptr doc(cJSON_CreateObject());\n\n const auto bodyoffset = cb::xattr::get_body_offset(in_doc);\n cb::byte_buffer blob_buffer{(uint8_t*)in_doc.buf, (size_t)bodyoffset};\n cb::xattr::Blob xattr_blob(blob_buffer);\n\n unique_cJSON_ptr array(cJSON_CreateArray());\n for (const std::pair&\n kvPair : xattr_blob) {\n bool isSystemXattr = cb::xattr::is_system_xattr(\n const_cast(kvPair.first));\n\n if (xtocSemantics == XtocSemantics::All ||\n (isSystemXattr && (xtocSemantics == XtocSemantics::System)) ||\n (!isSystemXattr && (xtocSemantics == XtocSemantics::User))) {\n cJSON_AddItemToArray(\n array.get(),\n cJSON_CreateString(to_string(kvPair.first).c_str()));\n }\n }\n\n cJSON_AddItemToObject(doc.get(), \"$XTOC\", array.release());\n xtoc_vattr = to_string(doc, false);\n }\n return cb::const_char_buffer(xtoc_vattr.data(), xtoc_vattr.size());\n}\n\nprotocol_binary_response_status SubdocCmdContext::get_document_for_searching(\n uint64_t client_cas) {\n item_info& info = getInputItemInfo();\n auto& c = connection;\n\n if (!bucket_get_item_info(cookie, fetchedItem.get(), &info)) {\n LOG_WARNING(&c, \"%u: Failed to get item info\", c.getId());\n return PROTOCOL_BINARY_RESPONSE_EINTERNAL;\n }\n\n if (info.cas == -1ull) {\n \/\/ Check that item is not locked:\n if (client_cas == 0 || client_cas == -1ull) {\n if (c.remapErrorCode(ENGINE_LOCKED_TMPFAIL) ==\n ENGINE_LOCKED_TMPFAIL) {\n return PROTOCOL_BINARY_RESPONSE_LOCKED;\n } else {\n return PROTOCOL_BINARY_RESPONSE_ETMPFAIL;\n }\n }\n \/\/ If the user *did* supply the CAS, we will validate it later on\n \/\/ when the mutation is actually applied. In any event, we don't\n \/\/ run the following branch on locked documents.\n } else if ((client_cas != 0) && client_cas != info.cas) {\n \/\/ Check CAS matches (if specified by the user).\n return PROTOCOL_BINARY_RESPONSE_KEY_EEXISTS;\n }\n\n in_flags = info.flags;\n in_cas = client_cas ? client_cas : info.cas;\n in_doc.buf = static_cast(info.value[0].iov_base);\n in_doc.len = info.value[0].iov_len;\n in_datatype = info.datatype;\n in_document_state = info.document_state;\n\n if (mcbp::datatype::is_snappy(info.datatype)) {\n \/\/ Need to expand before attempting to extract from it.\n try {\n using namespace cb::compression;\n if (!inflate(Algorithm::Snappy,\n in_doc,\n inflated_doc_buffer)) {\n char clean_key[KEY_MAX_LENGTH + 32];\n if (buf_to_printable_buffer(clean_key,\n sizeof(clean_key),\n static_cast(info.key),\n info.nkey) != -1) {\n LOG_WARNING(&c,\n \"<%u ERROR: Failed to determine inflated body\"\n \" size. Key: '%s' may have an \"\n \"incorrect datatype of COMPRESSED_JSON.\",\n c.getId(),\n cb::logtags::tagUserData(clean_key).c_str());\n }\n\n return PROTOCOL_BINARY_RESPONSE_EINTERNAL;\n }\n } catch (const std::bad_alloc&) {\n return PROTOCOL_BINARY_RESPONSE_ENOMEM;\n }\n\n \/\/ Update document to point to the uncompressed version in the buffer.\n in_doc = inflated_doc_buffer;\n in_datatype &= ~PROTOCOL_BINARY_DATATYPE_SNAPPY;\n }\n\n return PROTOCOL_BINARY_RESPONSE_SUCCESS;\n}\nReplace local impl of conversion to hex string with lib version\/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- *\/\n\/*\n * Copyright 2016 Couchbase, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"config.h\"\n#include \"subdocument_context.h\"\n#include \"debug_helpers.h\"\n#include \"mc_time.h\"\n#include \"protocol\/mcbp\/engine_wrapper.h\"\n#include \"subdocument.h\"\n\n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n\nSubdocCmdContext::OperationSpec::OperationSpec(SubdocCmdTraits traits_,\n protocol_binary_subdoc_flag flags_,\n cb::const_char_buffer path_)\n : SubdocCmdContext::OperationSpec::OperationSpec(traits_, flags_, path_,\n {nullptr, 0}) {\n}\n\nSubdocCmdContext::OperationSpec::OperationSpec(SubdocCmdTraits traits_,\n protocol_binary_subdoc_flag flags_,\n cb::const_char_buffer path_,\n cb::const_char_buffer value_)\n : traits(traits_),\n flags(flags_),\n path(path_),\n value(value_),\n status(PROTOCOL_BINARY_RESPONSE_EINTERNAL) {\n if (flags & SUBDOC_FLAG_MKDIR_P) {\n traits.subdocCommand = Subdoc::Command(traits.subdocCommand |\n Subdoc::Command::FLAG_MKDIR_P);\n }\n}\n\nSubdocCmdContext::OperationSpec::OperationSpec(OperationSpec&& other)\n : traits(other.traits),\n flags(other.flags),\n path(std::move(other.path)),\n value(std::move(other.value)) {}\n\nuint64_t SubdocCmdContext::getOperationValueBytesTotal() const {\n uint64_t result = 0;\n for (auto& ops : operations) {\n for (auto& op : ops) {\n result += op.value.len;\n }\n }\n return result;\n}\n\ntemplate \nstd::string SubdocCmdContext::macroToString(T macroValue) {\n std::stringstream ss;\n ss << std::hex << std::setfill('0');\n ss << \"\\\"0x\" << std::setw(sizeof(T) * 2) << macroValue << \"\\\"\";\n return ss.str();\n}\n\nENGINE_ERROR_CODE SubdocCmdContext::pre_link_document(item_info& info) {\n if (do_macro_expansion) {\n auto bodyoffset = cb::xattr::get_body_offset(\n {static_cast(info.value[0].iov_base),\n info.value[0].iov_len});\n\n cb::byte_buffer blob_buffer{\n static_cast(info.value[0].iov_base),\n bodyoffset};\n\n cb::xattr::Blob xattr_blob(blob_buffer);\n auto value = xattr_blob.get(xattr_key);\n if (value.len == 0) {\n \/\/ The segment is no longer there (we may have had another\n \/\/ subdoc command which rewrote the segment where we injected\n \/\/ the macro.\n return ENGINE_SUCCESS;\n }\n\n \/\/ Replace the CAS\n if (std::any_of(std::begin(paddedMacros),\n std::end(paddedMacros),\n [](const MacroPair& m) {\n return m.first == cb::xattr::macros::CAS;\n })) {\n substituteMacro(cb::xattr::macros::CAS,\n macroToString(htonll(info.cas)),\n value);\n }\n\n \/\/ Replace the Seqno\n if (std::any_of(std::begin(paddedMacros),\n std::end(paddedMacros),\n [](const MacroPair& m) {\n return m.first == cb::xattr::macros::SEQNO;\n })) {\n substituteMacro(\n cb::xattr::macros::SEQNO, macroToString(info.seqno), value);\n }\n }\n\n return ENGINE_SUCCESS;\n}\n\nvoid SubdocCmdContext::substituteMacro(cb::const_char_buffer macroName,\n const std::string& macroValue,\n cb::byte_buffer& value) {\n \/\/ Do an in-place substitution of the real macro value where we\n \/\/ wrote the padded macro string.\n uint8_t* root = value.buf;\n uint8_t* end = value.buf + value.len;\n auto& macro = std::find_if(std::begin(paddedMacros),\n std::end(paddedMacros),\n [macroName](const MacroPair& m) {\n return m.first == macroName;\n })\n ->second;\n auto* needle = macro.data();\n auto* needle_end = macro.data() + macro.length();\n\n \/\/ This replaces ALL instances of the padded string\n while ((root = std::search(root, end, needle, needle_end)) != end) {\n std::copy(macroValue.data(),\n macroValue.data() + macroValue.length(),\n root);\n root += macroValue.length();\n }\n}\n\ncb::const_char_buffer SubdocCmdContext::get_padded_macro(\n cb::const_char_buffer macro) {\n return std::find_if(\n std::begin(paddedMacros),\n std::end(paddedMacros),\n [macro](const MacroPair& a) { return a.first == macro; })\n ->second;\n}\n\nvoid SubdocCmdContext::generate_macro_padding(cb::const_char_buffer payload,\n cb::const_char_buffer macro) {\n if (!do_macro_expansion) {\n \/\/ macro expansion is not needed\n return;\n }\n\n bool unique = false;\n std::random_device rd;\n std::mt19937 gen(rd());\n std::uniform_int_distribution dis;\n\n while (!unique) {\n unique = true;\n uint64_t ii = dis(gen);\n const std::string candidate = \"\\\"\" + cb::to_hex(ii) + \"\\\"\";\n\n for (auto& op : getOperations(Phase::XATTR)) {\n if (cb::strnstr(op.value.buf, candidate.c_str(), op.value.len)) {\n unique = false;\n break;\n }\n }\n\n if (unique) {\n if (cb::strnstr(payload.buf, candidate.c_str(), payload.len)) {\n unique = false;\n } else {\n paddedMacros.push_back(std::make_pair(macro, candidate));\n }\n }\n }\n}\n\nvoid SubdocCmdContext::setMutationSemantics(mcbp::subdoc::doc_flag docFlags) {\n if (docFlags == mcbp::subdoc::doc_flag::Add) {\n mutationSemantics = MutationSemantics::Add;\n } else if (docFlags == mcbp::subdoc::doc_flag::Mkdoc) {\n mutationSemantics = MutationSemantics::Set;\n } else {\n mutationSemantics = MutationSemantics::Replace;\n }\n}\n\ncb::const_char_buffer SubdocCmdContext::get_document_vattr() {\n if (document_vattr.empty()) {\n \/\/ @todo we can optimize this by building the json in a more efficient\n \/\/ way, but for now just do it by using cJSON...\n unique_cJSON_ptr doc(cJSON_CreateObject());\n\n cJSON_AddStringToObject(\n doc.get(), \"CAS\", cb::to_hex(input_item_info.cas).c_str());\n\n cJSON_AddStringToObject(\n doc.get(),\n \"vbucket_uuid\",\n cb::to_hex(input_item_info.vbucket_uuid).c_str());\n\n cJSON_AddStringToObject(\n doc.get(), \"seqno\", cb::to_hex(input_item_info.seqno).c_str());\n\n cJSON_AddNumberToObject(doc.get(), \"exptime\", input_item_info.exptime);\n\n \/\/ The flags are kept internally in network byte order...\n cJSON_AddNumberToObject(\n doc.get(), \"flags\", ntohl(input_item_info.flags));\n\n if (mcbp::datatype::is_xattr(input_item_info.datatype)) {\n \/\/ strip off xattr\n auto bodyoffset = cb::xattr::get_body_offset(\n {static_cast(\n input_item_info.value[0].iov_base),\n input_item_info.value[0].iov_len});\n cJSON_AddNumberToObject(doc.get(),\n \"value_bytes\",\n input_item_info.nbytes - bodyoffset);\n } else {\n cJSON_AddNumberToObject(\n doc.get(), \"value_bytes\", input_item_info.nbytes);\n }\n\n unique_cJSON_ptr array(cJSON_CreateArray());\n auto datatypes = split_string(\n mcbp::datatype::to_string(input_item_info.datatype), \",\");\n for (const auto& d : datatypes) {\n cJSON_AddItemToArray(array.get(), cJSON_CreateString(d.c_str()));\n }\n\n cJSON_AddItemToObject(doc.get(), \"datatype\", array.release());\n\n cJSON_AddBoolToObject(\n doc.get(),\n \"deleted\",\n input_item_info.document_state == DocumentState::Deleted);\n\n if (input_item_info.cas_is_hlc) {\n \/\/ convert nanoseconds CAS into seconds and ensure u64 before cJSON\n \/\/ converts to a double internally.\n std::chrono::nanoseconds ns(input_item_info.cas);\n cJSON_AddStringToObject(\n doc.get(),\n \"last_modified\",\n std::to_string(uint64_t(std::chrono::duration_cast<\n std::chrono::seconds>(ns)\n .count()))\n .c_str());\n }\n unique_cJSON_ptr root(cJSON_CreateObject());\n cJSON_AddItemToObject(root.get(), \"$document\", doc.release());\n document_vattr = to_string(root, false);\n }\n\n return cb::const_char_buffer(document_vattr.data(), document_vattr.size());\n}\n\ncb::const_char_buffer SubdocCmdContext::get_xtoc_vattr() {\n if (!mcbp::datatype::is_xattr(in_datatype)) {\n xtoc_vattr = R\"({\"$XTOC\":[]})\";\n return cb::const_char_buffer(xtoc_vattr.data(), xtoc_vattr.size());\n }\n if (xtoc_vattr.empty()) {\n unique_cJSON_ptr doc(cJSON_CreateObject());\n\n const auto bodyoffset = cb::xattr::get_body_offset(in_doc);\n cb::byte_buffer blob_buffer{(uint8_t*)in_doc.buf, (size_t)bodyoffset};\n cb::xattr::Blob xattr_blob(blob_buffer);\n\n unique_cJSON_ptr array(cJSON_CreateArray());\n for (const std::pair&\n kvPair : xattr_blob) {\n bool isSystemXattr = cb::xattr::is_system_xattr(\n const_cast(kvPair.first));\n\n if (xtocSemantics == XtocSemantics::All ||\n (isSystemXattr && (xtocSemantics == XtocSemantics::System)) ||\n (!isSystemXattr && (xtocSemantics == XtocSemantics::User))) {\n cJSON_AddItemToArray(\n array.get(),\n cJSON_CreateString(to_string(kvPair.first).c_str()));\n }\n }\n\n cJSON_AddItemToObject(doc.get(), \"$XTOC\", array.release());\n xtoc_vattr = to_string(doc, false);\n }\n return cb::const_char_buffer(xtoc_vattr.data(), xtoc_vattr.size());\n}\n\nprotocol_binary_response_status SubdocCmdContext::get_document_for_searching(\n uint64_t client_cas) {\n item_info& info = getInputItemInfo();\n auto& c = connection;\n\n if (!bucket_get_item_info(cookie, fetchedItem.get(), &info)) {\n LOG_WARNING(&c, \"%u: Failed to get item info\", c.getId());\n return PROTOCOL_BINARY_RESPONSE_EINTERNAL;\n }\n\n if (info.cas == -1ull) {\n \/\/ Check that item is not locked:\n if (client_cas == 0 || client_cas == -1ull) {\n if (c.remapErrorCode(ENGINE_LOCKED_TMPFAIL) ==\n ENGINE_LOCKED_TMPFAIL) {\n return PROTOCOL_BINARY_RESPONSE_LOCKED;\n } else {\n return PROTOCOL_BINARY_RESPONSE_ETMPFAIL;\n }\n }\n \/\/ If the user *did* supply the CAS, we will validate it later on\n \/\/ when the mutation is actually applied. In any event, we don't\n \/\/ run the following branch on locked documents.\n } else if ((client_cas != 0) && client_cas != info.cas) {\n \/\/ Check CAS matches (if specified by the user).\n return PROTOCOL_BINARY_RESPONSE_KEY_EEXISTS;\n }\n\n in_flags = info.flags;\n in_cas = client_cas ? client_cas : info.cas;\n in_doc.buf = static_cast(info.value[0].iov_base);\n in_doc.len = info.value[0].iov_len;\n in_datatype = info.datatype;\n in_document_state = info.document_state;\n\n if (mcbp::datatype::is_snappy(info.datatype)) {\n \/\/ Need to expand before attempting to extract from it.\n try {\n using namespace cb::compression;\n if (!inflate(Algorithm::Snappy,\n in_doc,\n inflated_doc_buffer)) {\n char clean_key[KEY_MAX_LENGTH + 32];\n if (buf_to_printable_buffer(clean_key,\n sizeof(clean_key),\n static_cast(info.key),\n info.nkey) != -1) {\n LOG_WARNING(&c,\n \"<%u ERROR: Failed to determine inflated body\"\n \" size. Key: '%s' may have an \"\n \"incorrect datatype of COMPRESSED_JSON.\",\n c.getId(),\n cb::logtags::tagUserData(clean_key).c_str());\n }\n\n return PROTOCOL_BINARY_RESPONSE_EINTERNAL;\n }\n } catch (const std::bad_alloc&) {\n return PROTOCOL_BINARY_RESPONSE_ENOMEM;\n }\n\n \/\/ Update document to point to the uncompressed version in the buffer.\n in_doc = inflated_doc_buffer;\n in_datatype &= ~PROTOCOL_BINARY_DATATYPE_SNAPPY;\n }\n\n return PROTOCOL_BINARY_RESPONSE_SUCCESS;\n}\n<|endoftext|>"} {"text":"the #include \n#include \n#include \n\nusing namespace std;\nvector Census;\n\n\/*We're leaving together,\nBut still it's farewell\nAnd maybe we'll come back\nTo earth, who can tell?\nI guess there is no one to blame\nWe're leaving ground (leaving ground)\nWill things ever be the same again?\n\nIt's the final countdown\nThe final countdown\n\nOh\n\nWe're heading for Venus (Venus)\nAnd still we stand tall\n'Cause maybe they've seen us (seen us)\nAnd welcome us all, yeah\nWith so many light years to go\nAnd things to be found (to be found)\nI'm sure that we'll all miss her so\n\nIt's the final countdown\nThe final countdown\nThe final countdown\nThe final countdown\nOh\n\nThe final countdown,oh\nIt's the final count down\nThe final countdown\nThe final countdown\nThe final countdown\nOh\nIt's the final count down\nWe're leaving together\nThe final count down\nWe'll all miss her so\nIt's the final countdown\nIt's the final countdown\nOh\nIt's the final countdown, yeah\nvoid Census2017(){\n \/\/ Census.push_back(\"Name @ GitHub link\");\n Census.push_back(\"Allen Comp Sci @ https:\/\/github.com\/AllenCompSci\");\n Census.push_back(\"Mr. Hudson @ https:\/\/github.com\/theshrewedshrew\");\n Census.push_back(\"BEST Team 58 @ https:\/\/github.com\/BESTTeam58\");\n Census.push_back(\"TexasSnow @ https:\/\/github.com\/TexasSnow\");\n Census.push_back(\"hotdogshabab @ https:\/\/github.com\/hotdogshabab\");\n Census.push_back(\"alansunglee @ https:\/\/github.com\/alansunglee\");\n Census.push_back(\"Rahultheman12 @ https:\/\/github.com\/Rahultheman12\");\n Census.push_back(\"spicyboi @ https:\/\/github.com\/spicyboi\");\n Census.push_back(\"John Nguyen @ https:\/\/github.com\/jawnlovesfreestuff\");\n Census.push_back(\"CodeTimesTen @ https:\/\/github.com\/CodeTimesTen\");\n Census.push_back(\"YourFriendlyNeighborhoodSpiderman @ https:\/\/github.com\/YourFriendlyNeighborhoodSpiderman\");\n Census.push_back(\"Devin Petersen @ https:\/\/github.com\/DevinPetersen\");\n Census.push_back(\"Cameron Mathis @ https:\/\/github.com\/Phylux\");\n Census.push_back(\"Samuel Woon @ https:\/\/github.com\/samuel-w\");\n Census.push_back(\"JustinV10 @ https:\/\/github.com\/JustinV10\");\n Census.push_back(\"Kyleaustin36 @ https:\/\/github.com\/kyleaustin36\");\n Census.push_back(\"Maaz Kamal @ https:\/\/github.com\/Maze-Camel\");\n Census.push_back(\"bingood4ever @ https:\/\/github.com\/bingood4ever\");\n Census.push_back(\"Gainz101 @ https:\/\/github.com\/Gainz101\");\n Census.push_back(\"zachdogg @ https:\/\/github.com\/Zachdogg1\");\n*\/\n\n\n}\nvoid printCensus(){\n for(int i = 0; i < (int)Census.size(); i++){\n cout << \"Hello World from \"Your name\" + Census[i] << \"\\n\";\n\n }\n}\n\/\/test\nvoid main(){\n Census2017();\n printCensus();\n}\nUpdate HelloWorld.cpp#include \n#include \n#include \n\nusing namespace std;\nvector Census;\n\n\/*We're leaving together,\nBut still it's farewell\nAnd maybe we'll come back\nTo earth, who can tell?\nI guess there is no one to blame\nWe're leaving ground (leaving ground)\nWill things ever be the same again?\n\nIt's the final countdown\nThe final countdown\n\nOh\n\nWe're heading for Venus (Venus)\nAnd still we stand tall\n'Cause maybe they've seen us (seen us)\nAnd welcome us all, yeah\nWith so many light years to go\nAnd things to be found (to be found)\nI'm sure that we'll all miss her so\n\nIt's the final countdown\nThe final countdown\nThe final countdown\nThe final countdown\nOh\n\nThe final countdown,oh\nIt's the final count down\nThe final countdown\nThe final countdown\nThe final countdown\nOh\nIt's the final count down\nWe're leaving together\nThe final count down\nWe'll all miss her so\nIt's the final countdown\nIt's the final countdown\nOh\nIt's the final countdown, yeah\nvoid Census2017(){\n \/\/ Census.push_back(\"Name @ GitHub link\");\n Census.push_back(\"Allen Comp Sci @ https:\/\/github.com\/AllenCompSci\");\n Census.push_back(\"Mr. Hudson @ https:\/\/github.com\/theshrewedshrew\");\n Census.push_back(\"BEST Team 58 @ https:\/\/github.com\/BESTTeam58\");\n Census.push_back(\"TexasSnow @ https:\/\/github.com\/TexasSnow\");\n Census.push_back(\"hotdogshabab @ https:\/\/github.com\/hotdogshabab\");\n Census.push_back(\"alansunglee @ https:\/\/github.com\/alansunglee\");\n Census.push_back(\"Rahultheman12 @ https:\/\/github.com\/Rahultheman12\");\n Census.push_back(\"spicyboi @ https:\/\/github.com\/spicyboi\");\n Census.push_back(\"John Nguyen @ https:\/\/github.com\/jawnlovesfreestuff\");\n Census.push_back(\"CodeTimesTen @ https:\/\/github.com\/CodeTimesTen\");\n Census.push_back(\"YourFriendlyNeighborhoodSpiderman @ https:\/\/github.com\/YourFriendlyNeighborhoodSpiderman\");\n Census.push_back(\"Devin Petersen @ https:\/\/github.com\/DevinPetersen\");\n Census.push_back(\"Cameron Mathis @ https:\/\/github.com\/Phylux\");\n Census.push_back(\"Samuel Woon @ https:\/\/github.com\/samuel-w\");\n Census.push_back(\"JustinV10 @ https:\/\/github.com\/JustinV10\");\n Census.push_back(\"Kyleaustin36 @ https:\/\/github.com\/kyleaustin36\");\n Census.push_back(\"Maaz Kamal @ https:\/\/github.com\/Maze-Camel\");\n Census.push_back(\"bingood4ever @ https:\/\/github.com\/bingood4ever\");\n Census.push_back(\"Gainz101 @ https:\/\/github.com\/Gainz101\");\n Census.push_back(\"zachdogg @ https:\/\/github.com\/Zachdogg1\");\n*\/\n\n\n}\nvoid printCensus(){\n for(int i = 0; i < (int)Census.size(); i++){\n cout << \"Hello World from \"Your name\" + Census[i] << \"\\n\";\n\n }\n}\n\/\/test\nvoid main(){\n Census2017();\n printCensus();\n}\n<|endoftext|>"} {"text":"#include \"ma.h\"\n#include \n#include \n#include \n#include \n#include \n\nclass Linear : public ma::IsotropicFunction\n{\n public:\n Linear(ma::Mesh* m)\n {\n mesh = m;\n average = ma::getAverageEdgeLength(m);\n ma::getBoundingBox(m,lower,upper);\n }\n virtual double getValue(ma::Entity* v)\n {\n ma::Vector p = ma::getPosition(mesh,v);\n double x = (p[0] - lower[0])\/(upper[0] - lower[0]);\n return average*(3*x+1)\/2;\n }\n private:\n ma::Mesh* mesh;\n double average;\n ma::Vector lower;\n ma::Vector upper;\n};\n\nint main(int argc, char** argv)\n{\n assert(argc==3);\n const char* modelFile = argv[1];\n const char* meshFile = argv[2];\n MPI_Init(&argc,&argv);\n PCU_Comm_Init();\n gmi_register_mesh();\n ma::Mesh* m = apf::loadMdsMesh(modelFile,meshFile);\n m->verify();\n Linear sf(m);\n ma::Input* in = ma::configure(m, &sf);\n in->shouldRunPreZoltan = true;\n in->shouldRunMidDiffusion = true;\n in->shouldRunPostDiffusion = true;\n ma::adapt(in);\n m->verify();\n apf::writeVtkFiles(\"after\",m);\n m->destroyNative();\n apf::destroyMesh(m);\n PCU_Comm_Free();\n MPI_Finalize();\n}\n\nadjusting size formula to reduce test refinement#include \"ma.h\"\n#include \n#include \n#include \n#include \n#include \n\nclass Linear : public ma::IsotropicFunction\n{\n public:\n Linear(ma::Mesh* m)\n {\n mesh = m;\n average = ma::getAverageEdgeLength(m);\n ma::getBoundingBox(m,lower,upper);\n }\n virtual double getValue(ma::Entity* v)\n {\n ma::Vector p = ma::getPosition(mesh,v);\n double x = (p[0] - lower[0])\/(upper[0] - lower[0]);\n return average*(4*x+2)\/3;\n }\n private:\n ma::Mesh* mesh;\n double average;\n ma::Vector lower;\n ma::Vector upper;\n};\n\nint main(int argc, char** argv)\n{\n assert(argc==3);\n const char* modelFile = argv[1];\n const char* meshFile = argv[2];\n MPI_Init(&argc,&argv);\n PCU_Comm_Init();\n gmi_register_mesh();\n ma::Mesh* m = apf::loadMdsMesh(modelFile,meshFile);\n m->verify();\n Linear sf(m);\n ma::Input* in = ma::configure(m, &sf);\n in->shouldRunPreZoltan = true;\n in->shouldRunMidDiffusion = true;\n in->shouldRunPostDiffusion = true;\n ma::adapt(in);\n m->verify();\n apf::writeVtkFiles(\"after\",m);\n m->destroyNative();\n apf::destroyMesh(m);\n PCU_Comm_Free();\n MPI_Finalize();\n}\n\n<|endoftext|>"} {"text":"#include \"widgets\/helper\/NotebookButton.hpp\"\n#include \"singletons\/Theme.hpp\"\n#include \"widgets\/Notebook.hpp\"\n#include \"widgets\/helper\/Button.hpp\"\n#include \"widgets\/splits\/Split.hpp\"\n#include \"widgets\/splits\/SplitContainer.hpp\"\n\n#include \n#include \n#include \n#include \n\n#define nuuls nullptr\n\nnamespace chatterino {\n\nNotebookButton::NotebookButton(Notebook *parent)\n : Button(parent)\n , parent_(parent)\n{\n this->setAcceptDrops(true);\n}\n\nvoid NotebookButton::setIcon(Icon icon)\n{\n this->icon_ = icon;\n\n this->update();\n}\n\nNotebookButton::Icon NotebookButton::getIcon() const\n{\n return this->icon_;\n}\n\nvoid NotebookButton::themeChangedEvent()\n{\n this->setMouseEffectColor(this->theme->tabs.regular.text);\n}\n\nvoid NotebookButton::paintEvent(QPaintEvent *event)\n{\n QPainter painter(this);\n\n QColor background;\n QColor foreground;\n\n if (mouseDown_ || mouseOver_)\n {\n background = this->theme->tabs.regular.backgrounds.hover.color();\n foreground = this->theme->tabs.regular.text;\n }\n else\n {\n background = this->theme->tabs.regular.backgrounds.regular.color();\n foreground = this->theme->tabs.regular.text;\n }\n\n painter.setPen(Qt::NoPen);\n\n float h = height(), w = width();\n\n switch (icon_)\n {\n case Plus: {\n painter.setPen([&] {\n QColor tmp = foreground;\n if (SplitContainer::isDraggingSplit)\n {\n tmp = this->theme->tabs.selected.line.regular;\n }\n else if (!this->mouseOver_)\n {\n tmp.setAlpha(180);\n }\n return tmp;\n }());\n QRect rect = this->rect();\n int s = h * 4 \/ 9;\n\n painter.drawLine(rect.left() + rect.width() \/ 2 - (s \/ 2),\n rect.top() + rect.height() \/ 2,\n rect.left() + rect.width() \/ 2 + (s \/ 2),\n rect.top() + rect.height() \/ 2);\n painter.drawLine(rect.left() + rect.width() \/ 2,\n rect.top() + rect.height() \/ 2 - (s \/ 2),\n rect.left() + rect.width() \/ 2,\n rect.top() + rect.height() \/ 2 + (s \/ 2));\n }\n break;\n\n case User: {\n painter.setRenderHint(QPainter::Antialiasing);\n\n auto a = w \/ 8;\n QPainterPath path;\n\n path.arcMoveTo(a, 4 * a, 6 * a, 6 * a, 0);\n path.arcTo(a, 4 * a, 6 * a, 6 * a, 0, 180);\n\n QPainterPath remove;\n remove.addEllipse(2 * a, 1 * a, 4 * a, 4 * a);\n path = path.subtracted(remove);\n\n path.addEllipse(2.5 * a, 1.5 * a, 3 * a + 1, 3 * a);\n\n painter.fillPath(path, foreground);\n }\n break;\n\n case Settings: {\n painter.setRenderHint(QPainter::Antialiasing);\n\n auto a = w \/ 8;\n QPainterPath path;\n\n path.arcMoveTo(a, a, 6 * a, 6 * a, 0 - (360 \/ 32.0));\n\n for (int i = 0; i < 8; i++)\n {\n path.arcTo(a, a, 6 * a, 6 * a, i * (360 \/ 8.0) - (360 \/ 32.0),\n (360 \/ 32.0));\n path.arcTo(2 * a, 2 * a, 4 * a, 4 * a,\n i * (360 \/ 8.0) + (360 \/ 32.0), (360 \/ 32.0));\n }\n\n QPainterPath remove;\n remove.addEllipse(3 * a, 3 * a, 2 * a, 2 * a);\n\n painter.fillPath(path.subtracted(remove), foreground);\n }\n break;\n\n default:;\n }\n\n Button::paintEvent(event);\n}\n\nvoid NotebookButton::mouseReleaseEvent(QMouseEvent *event)\n{\n if (event->button() == Qt::LeftButton)\n {\n mouseDown_ = false;\n\n update();\n\n emit leftClicked();\n }\n\n Button::mouseReleaseEvent(event);\n}\n\nvoid NotebookButton::dragEnterEvent(QDragEnterEvent *event)\n{\n if (!event->mimeData()->hasFormat(\"chatterino\/split\"))\n return;\n\n event->acceptProposedAction();\n\n auto e = new QMouseEvent(QMouseEvent::MouseButtonPress,\n QPointF(this->width() \/ 2, this->height() \/ 2),\n Qt::LeftButton, Qt::LeftButton, 0);\n Button::mousePressEvent(e);\n delete e;\n}\n\nvoid NotebookButton::dragLeaveEvent(QDragLeaveEvent *)\n{\n this->mouseDown_ = true;\n this->update();\n\n auto e = new QMouseEvent(QMouseEvent::MouseButtonRelease,\n QPointF(this->width() \/ 2, this->height() \/ 2),\n Qt::LeftButton, Qt::LeftButton, 0);\n Button::mouseReleaseEvent(e);\n delete e;\n}\n\nvoid NotebookButton::dropEvent(QDropEvent *event)\n{\n if (SplitContainer::isDraggingSplit)\n {\n event->acceptProposedAction();\n\n Notebook *notebook = dynamic_cast(this->parentWidget());\n\n if (notebook != nuuls)\n {\n SplitContainer *page = new SplitContainer(notebook);\n auto *tab = notebook->addPage(page);\n page->setTab(tab);\n\n SplitContainer::draggingSplit->setParent(page);\n page->appendSplit(SplitContainer::draggingSplit);\n }\n }\n}\n\nvoid NotebookButton::hideEvent(QHideEvent *)\n{\n this->parent_->performLayout();\n}\n\nvoid NotebookButton::showEvent(QShowEvent *)\n{\n this->parent_->performLayout();\n}\n\n} \/\/ namespace chatterino\nfixed position of user icon head#include \"widgets\/helper\/NotebookButton.hpp\"\n#include \"singletons\/Theme.hpp\"\n#include \"widgets\/Notebook.hpp\"\n#include \"widgets\/helper\/Button.hpp\"\n#include \"widgets\/splits\/Split.hpp\"\n#include \"widgets\/splits\/SplitContainer.hpp\"\n\n#include \n#include \n#include \n#include \n\n#define nuuls nullptr\n\nnamespace chatterino {\n\nNotebookButton::NotebookButton(Notebook *parent)\n : Button(parent)\n , parent_(parent)\n{\n this->setAcceptDrops(true);\n}\n\nvoid NotebookButton::setIcon(Icon icon)\n{\n this->icon_ = icon;\n\n this->update();\n}\n\nNotebookButton::Icon NotebookButton::getIcon() const\n{\n return this->icon_;\n}\n\nvoid NotebookButton::themeChangedEvent()\n{\n this->setMouseEffectColor(this->theme->tabs.regular.text);\n}\n\nvoid NotebookButton::paintEvent(QPaintEvent *event)\n{\n QPainter painter(this);\n\n QColor background;\n QColor foreground;\n\n if (mouseDown_ || mouseOver_)\n {\n background = this->theme->tabs.regular.backgrounds.hover.color();\n foreground = this->theme->tabs.regular.text;\n }\n else\n {\n background = this->theme->tabs.regular.backgrounds.regular.color();\n foreground = this->theme->tabs.regular.text;\n }\n\n painter.setPen(Qt::NoPen);\n\n float h = height(), w = width();\n\n switch (icon_)\n {\n case Plus: {\n painter.setPen([&] {\n QColor tmp = foreground;\n if (SplitContainer::isDraggingSplit)\n {\n tmp = this->theme->tabs.selected.line.regular;\n }\n else if (!this->mouseOver_)\n {\n tmp.setAlpha(180);\n }\n return tmp;\n }());\n QRect rect = this->rect();\n int s = h * 4 \/ 9;\n\n painter.drawLine(rect.left() + rect.width() \/ 2 - (s \/ 2),\n rect.top() + rect.height() \/ 2,\n rect.left() + rect.width() \/ 2 + (s \/ 2),\n rect.top() + rect.height() \/ 2);\n painter.drawLine(rect.left() + rect.width() \/ 2,\n rect.top() + rect.height() \/ 2 - (s \/ 2),\n rect.left() + rect.width() \/ 2,\n rect.top() + rect.height() \/ 2 + (s \/ 2));\n }\n break;\n\n case User: {\n painter.setRenderHint(QPainter::Antialiasing);\n\n auto a = w \/ 8;\n QPainterPath path;\n\n path.arcMoveTo(a, 4 * a, 6 * a, 6 * a, 0);\n path.arcTo(a, 4 * a, 6 * a, 6 * a, 0, 180);\n\n QPainterPath remove;\n remove.addEllipse(2 * a, 1 * a, 4 * a, 4 * a);\n path = path.subtracted(remove);\n\n path.addEllipse(2.5 * a, 1.5 * a, 3 * a, 3 * a);\n\n painter.fillPath(path, foreground);\n }\n break;\n\n case Settings: {\n painter.setRenderHint(QPainter::Antialiasing);\n\n auto a = w \/ 8;\n QPainterPath path;\n\n path.arcMoveTo(a, a, 6 * a, 6 * a, 0 - (360 \/ 32.0));\n\n for (int i = 0; i < 8; i++)\n {\n path.arcTo(a, a, 6 * a, 6 * a, i * (360 \/ 8.0) - (360 \/ 32.0),\n (360 \/ 32.0));\n path.arcTo(2 * a, 2 * a, 4 * a, 4 * a,\n i * (360 \/ 8.0) + (360 \/ 32.0), (360 \/ 32.0));\n }\n\n QPainterPath remove;\n remove.addEllipse(3 * a, 3 * a, 2 * a, 2 * a);\n\n painter.fillPath(path.subtracted(remove), foreground);\n }\n break;\n\n default:;\n }\n\n Button::paintEvent(event);\n}\n\nvoid NotebookButton::mouseReleaseEvent(QMouseEvent *event)\n{\n if (event->button() == Qt::LeftButton)\n {\n mouseDown_ = false;\n\n update();\n\n emit leftClicked();\n }\n\n Button::mouseReleaseEvent(event);\n}\n\nvoid NotebookButton::dragEnterEvent(QDragEnterEvent *event)\n{\n if (!event->mimeData()->hasFormat(\"chatterino\/split\"))\n return;\n\n event->acceptProposedAction();\n\n auto e = new QMouseEvent(QMouseEvent::MouseButtonPress,\n QPointF(this->width() \/ 2, this->height() \/ 2),\n Qt::LeftButton, Qt::LeftButton, 0);\n Button::mousePressEvent(e);\n delete e;\n}\n\nvoid NotebookButton::dragLeaveEvent(QDragLeaveEvent *)\n{\n this->mouseDown_ = true;\n this->update();\n\n auto e = new QMouseEvent(QMouseEvent::MouseButtonRelease,\n QPointF(this->width() \/ 2, this->height() \/ 2),\n Qt::LeftButton, Qt::LeftButton, 0);\n Button::mouseReleaseEvent(e);\n delete e;\n}\n\nvoid NotebookButton::dropEvent(QDropEvent *event)\n{\n if (SplitContainer::isDraggingSplit)\n {\n event->acceptProposedAction();\n\n Notebook *notebook = dynamic_cast(this->parentWidget());\n\n if (notebook != nuuls)\n {\n SplitContainer *page = new SplitContainer(notebook);\n auto *tab = notebook->addPage(page);\n page->setTab(tab);\n\n SplitContainer::draggingSplit->setParent(page);\n page->appendSplit(SplitContainer::draggingSplit);\n }\n }\n}\n\nvoid NotebookButton::hideEvent(QHideEvent *)\n{\n this->parent_->performLayout();\n}\n\nvoid NotebookButton::showEvent(QShowEvent *)\n{\n this->parent_->performLayout();\n}\n\n} \/\/ namespace chatterino\n<|endoftext|>"} {"text":"\/*\n * The Apache Software License, Version 1.1\n *\n * Copyright (c) 2002 The Apache Software Foundation. All rights\n * reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n *\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in\n * the documentation and\/or other materials provided with the\n * distribution.\n *\n * 3. The end-user documentation included with the redistribution,\n * if any, must include the following acknowledgment:\n * \"This product includes software developed by the\n * Apache Software Foundation (http:\/\/www.apache.org\/).\"\n * Alternately, this acknowledgment may appear in the software itself,\n * if and wherever such third-party acknowledgments normally appear.\n *\n * 4. The names \"Xerces\" and \"Apache Software Foundation\" must\n * not be used to endorse or promote products derived from this\n * software without prior written permission. For written\n * permission, please contact apache\\@apache.org.\n *\n * 5. Products derived from this software may not be called \"Apache\",\n * nor may \"Apache\" appear in their name, without prior written\n * permission of the Apache Software Foundation.\n *\n * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED\n * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR\n * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF\n * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT\n * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n * ====================================================================\n *\n * This software consists of voluntary contributions made by many\n * individuals on behalf of the Apache Software Foundation, and was\n * originally based on software copyright (c) 1999, International\n * Business Machines, Inc., http:\/\/www.ibm.com . For more information\n * on the Apache Software Foundation, please see\n * .\n *\/\n\n\/*\n * $Log$\n * Revision 1.20 2004\/04\/13 16:56:58 peiyongz\n * IdentityConstraintHandler\n *\n * Revision 1.19 2004\/04\/07 14:14:08 peiyongz\n * make resolveSystemId virutal\n *\n * Revision 1.18 2004\/01\/29 11:46:30 cargilld\n * Code cleanup changes to get rid of various compiler diagnostic messages.\n *\n * Revision 1.17 2003\/11\/28 19:54:31 knoaman\n * PSVIElement update\n *\n * Revision 1.16 2003\/11\/28 05:13:29 neilg\n * Fix state-ful duplicate attribute detection when the integrated\n * scanner is in use and namespaces are off. Also, implement\n * change to PSVIHandler interface to remove prefix passing.\n *\n * Revision 1.15 2003\/11\/27 22:52:37 knoaman\n * PSVIElement implementation\n *\n * Revision 1.14 2003\/11\/27 06:10:31 neilg\n * PSVIAttribute implementation\n *\n * Revision 1.13 2003\/11\/26 16:20:00 knoaman\n * Store XSModel.\n *\n * Revision 1.12 2003\/11\/24 05:09:38 neilg\n * implement new, statless, method for detecting duplicate attributes\n *\n * Revision 1.11 2003\/10\/22 20:22:30 knoaman\n * Prepare for annotation support.\n *\n * Revision 1.10 2003\/09\/22 19:51:41 neilg\n * scanners should maintain their own pools of undeclared elements, rather than requiring grammars to do this. This makes grammar objects stateless with regard to validation.\n *\n * Revision 1.9 2003\/08\/14 02:56:41 knoaman\n * Code refactoring to improve performance of validation.\n *\n * Revision 1.8 2003\/07\/10 19:47:23 peiyongz\n * Stateless Grammar: Initialize scanner with grammarResolver,\n * creating grammar through grammarPool\n *\n * Revision 1.7 2003\/05\/22 02:10:51 knoaman\n * Default the memory manager.\n *\n * Revision 1.6 2003\/05\/15 18:26:29 knoaman\n * Partial implementation of the configurable memory manager.\n *\n * Revision 1.5 2003\/03\/07 18:08:58 tng\n * Return a reference instead of void for operator=\n *\n * Revision 1.4 2003\/01\/29 19:59:35 gareth\n * we now detect when elements and attributes are validated\/ the result of the validation and store that information.\n *\n * Revision 1.3 2003\/01\/15 15:49:49 knoaman\n * Change constant declaration name to match its value.\n *\n * Revision 1.2 2003\/01\/13 16:30:18 knoaman\n * [Bug 14469] Validator doesn't enforce xsd:key.\n *\n * Revision 1.1 2002\/12\/04 02:05:25 knoaman\n * Initial checkin.\n *\n *\/\n\n\n#if !defined(IGXMLSCANNER_HPP)\n#define IGXMLSCANNER_HPP\n\n#include \n#include \n#include \n#include \n#include \n#include \n\nXERCES_CPP_NAMESPACE_BEGIN\n\nclass DTDElementDecl;\nclass DTDGrammar;\nclass DTDValidator;\nclass SchemaValidator;\nclass IdentityConstraintHandler;\nclass IdentityConstraint;\nclass ContentLeafNameTypeVector;\nclass SchemaAttDef;\nclass XMLContentModel;\nclass XSModel;\nclass PSVIAttributeList;\nclass PSVIElement;\n\n\/\/ This is an integrated scanner class, which does DTD\/XML Schema grammar\n\/\/ processing.\nclass XMLPARSER_EXPORT IGXMLScanner : public XMLScanner\n{\npublic :\n \/\/ -----------------------------------------------------------------------\n \/\/ Constructors and Destructor\n \/\/ -----------------------------------------------------------------------\n IGXMLScanner\n (\n XMLValidator* const valToAdopt\n , GrammarResolver* const grammarResolver\n , MemoryManager* const manager = XMLPlatformUtils::fgMemoryManager\n );\n IGXMLScanner\n (\n XMLDocumentHandler* const docHandler\n , DocTypeHandler* const docTypeHandler\n , XMLEntityHandler* const entityHandler\n , XMLErrorReporter* const errReporter\n , XMLValidator* const valToAdopt\n , GrammarResolver* const grammarResolver\n , MemoryManager* const manager = XMLPlatformUtils::fgMemoryManager\n );\n virtual ~IGXMLScanner();\n\n \/\/ -----------------------------------------------------------------------\n \/\/ XMLScanner public virtual methods\n \/\/ -----------------------------------------------------------------------\n virtual const XMLCh* getName() const;\n virtual NameIdPool* getEntityDeclPool();\n virtual const NameIdPool* getEntityDeclPool() const;\n virtual unsigned int resolveQName\n (\n const XMLCh* const qName\n , XMLBuffer& prefixBufToFill\n , const short mode\n , int& prefixColonPos\n );\n virtual void scanDocument\n (\n const InputSource& src\n );\n virtual bool scanNext(XMLPScanToken& toFill);\n virtual Grammar* loadGrammar\n (\n const InputSource& src\n , const short grammarType\n , const bool toCache = false\n );\n\nprivate :\n \/\/ -----------------------------------------------------------------------\n \/\/ Unimplemented constructors and operators\n \/\/ -----------------------------------------------------------------------\n IGXMLScanner();\n IGXMLScanner(const IGXMLScanner&);\n IGXMLScanner& operator=(const IGXMLScanner&);\n\n \/\/ -----------------------------------------------------------------------\n \/\/ XMLScanner virtual methods\n \/\/ -----------------------------------------------------------------------\n virtual void scanCDSection();\n virtual void scanCharData(XMLBuffer& toToUse);\n virtual EntityExpRes scanEntityRef\n (\n const bool inAttVal\n , XMLCh& firstCh\n , XMLCh& secondCh\n , bool& escaped\n );\n virtual void scanDocTypeDecl();\n virtual void scanReset(const InputSource& src);\n virtual void sendCharData(XMLBuffer& toSend);\n virtual InputSource* resolveSystemId(const XMLCh* const sysId);\n\n \/\/ -----------------------------------------------------------------------\n \/\/ Private helper methods\n \/\/ -----------------------------------------------------------------------\n void commonInit();\n void cleanUp();\n\n \/\/ Spaces are not allowed in URI, so %20 is used instead.\n \/\/ Convert %20 to spaces before resolving the URI\n void normalizeURI(const XMLCh* const systemURI, XMLBuffer& normalizedURI);\n\n unsigned int buildAttList\n (\n const RefVectorOf& providedAttrs\n , const unsigned int attCount\n , XMLElementDecl* elemDecl\n , RefVectorOf& toFill\n );\n bool normalizeAttValue\n (\n const XMLAttDef* const attDef\n , const XMLCh* const name \n , const XMLCh* const value\n , XMLBuffer& toFill\n );\n bool normalizeAttRawValue\n (\n const XMLCh* const attrName\n , const XMLCh* const value\n , XMLBuffer& toFill\n );\n unsigned int resolvePrefix\n (\n const XMLCh* const prefix\n , const ElemStack::MapModes mode\n );\n unsigned int resolvePrefix\n (\n const XMLCh* const prefix\n , XMLBuffer& uriBufToFill\n , const ElemStack::MapModes mode\n );\n void updateNSMap\n (\n const XMLCh* const attrName\n , const XMLCh* const attrValue\n );\n void scanRawAttrListforNameSpaces(int attCount);\n void parseSchemaLocation(const XMLCh* const schemaLocationStr);\n void resolveSchemaGrammar(const XMLCh* const loc, const XMLCh* const uri);\n bool switchGrammar(const XMLCh* const newGrammarNameSpace);\n bool laxElementValidation(QName* element, ContentLeafNameTypeVector* cv,\n const XMLContentModel* const cm,\n const unsigned int parentElemDepth);\n bool anyAttributeValidation(SchemaAttDef* attWildCard,\n unsigned int uriId,\n bool& skipThisOne,\n bool& laxThisOne);\n void resizeElemState();\n void processSchemaLocation(XMLCh* const schemaLoc);\n\n \/\/ -----------------------------------------------------------------------\n \/\/ Private scanning methods\n \/\/ -----------------------------------------------------------------------\n bool basicAttrValueScan\n (\n const XMLCh* const attrName\n , XMLBuffer& toFill\n );\n unsigned int rawAttrScan\n (\n const XMLCh* const elemName\n , RefVectorOf& toFill\n , bool& isEmpty\n );\n bool scanAttValue\n (\n const XMLAttDef* const attDef\n , const XMLCh* const attrName\n , XMLBuffer& toFill\n );\n bool scanContent();\n void scanEndTag(bool& gotData);\n bool scanStartTag(bool& gotData);\n bool scanStartTagNS(bool& gotData);\n\n \/\/ -----------------------------------------------------------------------\n \/\/ IdentityConstraints Activation methods\n \/\/ -----------------------------------------------------------------------\n inline bool toCheckIdentityConstraint() const;\n\n \/\/ -----------------------------------------------------------------------\n \/\/ Grammar preparsing methods\n \/\/ -----------------------------------------------------------------------\n Grammar* loadXMLSchemaGrammar(const InputSource& src, const bool toCache = false);\n Grammar* loadDTDGrammar(const InputSource& src, const bool toCache = false);\n\n \/\/ -----------------------------------------------------------------------\n \/\/ PSVI handling methods\n \/\/ -----------------------------------------------------------------------\n void endElementPSVI(SchemaElementDecl* const elemDecl,\n DatatypeValidator* const memberDV);\n void resetPSVIElemContext();\n\n \/\/ -----------------------------------------------------------------------\n \/\/ Data members\n \/\/\n \/\/ fRawAttrList\n \/\/ During the initial scan of the attributes we can only do a raw\n \/\/ scan for key\/value pairs. So this vector is used to store them\n \/\/ until they can be processed (and put into fAttrList.)\n \/\/\n \/\/ fDTDValidator\n \/\/ The DTD validator instance.\n \/\/\n \/\/ fSchemaValidator\n \/\/ The Schema validator instance.\n \/\/\n \/\/ fSeeXsi\n \/\/ This flag indicates a schema has been seen.\n \/\/\n \/\/ fElemState\n \/\/ fElemStateSize\n \/\/ Stores an element next state from DFA content model - used for\n \/\/ wildcard validation\n \/\/\n \/\/ fDTDElemNonDeclPool\n \/\/ registry of \"faulted-in\" DTD element decls\n \/\/ fSchemaElemNonDeclPool\n \/\/ registry for elements without decls in the grammar\n \/\/ fElemCount\n \/\/ count of the number of start tags seen so far (starts at 1).\n \/\/ Used for duplicate attribute detection\/processing of required\/defaulted attributes\n \/\/ fAttDefRegistry\n \/\/ mapping from XMLAttDef instances to the count of the last\n \/\/ start tag where they were utilized.\n \/\/ fUndeclaredAttrRegistry\n \/\/ mapping of attr QNames to the count of the last start tag in which they occurred\n \/\/ fUndeclaredAttrRegistryNS\n \/\/ mapping of namespaceId\/localName pairs to the count of the last\n \/\/ start tag in which they occurred.\n \/\/ fPSVIAttrList\n \/\/ PSVI attribute list implementation that needs to be\n \/\/ filled when a PSVIHandler is registered\n \/\/\n \/\/ -----------------------------------------------------------------------\n bool fSeeXsi;\n Grammar::GrammarType fGrammarType;\n unsigned int fElemStateSize;\n unsigned int* fElemState;\n XMLBuffer fContent;\n RefVectorOf* fRawAttrList;\n DTDValidator* fDTDValidator;\n SchemaValidator* fSchemaValidator;\n DTDGrammar* fDTDGrammar;\n IdentityConstraintHandler* fICHandler;\n ValueVectorOf* fLocationPairs;\n NameIdPool* fDTDElemNonDeclPool;\n RefHash3KeysIdPool* fSchemaElemNonDeclPool;\n unsigned int fElemCount;\n RefHashTableOf* fAttDefRegistry;\n RefHashTableOf* fUndeclaredAttrRegistry;\n RefHash2KeysTableOf* fUndeclaredAttrRegistryNS;\n PSVIAttributeList * fPSVIAttrList;\n XSModel* fModel;\n PSVIElement* fPSVIElement;\n ValueStackOf* fErrorStack;\n PSVIElemContext fPSVIElemContext;\n};\n\ninline const XMLCh* IGXMLScanner::getName() const\n{\n return XMLUni::fgIGXMLScanner;\n}\n\ninline bool IGXMLScanner::toCheckIdentityConstraint() const\n{\n return fValidate && fIdentityConstraintChecking && fICHandler;\n}\n\nXERCES_CPP_NAMESPACE_END\n\n#endif\nIdentityConstraintHandler\/*\n * The Apache Software License, Version 1.1\n *\n * Copyright (c) 2002 The Apache Software Foundation. All rights\n * reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n *\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in\n * the documentation and\/or other materials provided with the\n * distribution.\n *\n * 3. The end-user documentation included with the redistribution,\n * if any, must include the following acknowledgment:\n * \"This product includes software developed by the\n * Apache Software Foundation (http:\/\/www.apache.org\/).\"\n * Alternately, this acknowledgment may appear in the software itself,\n * if and wherever such third-party acknowledgments normally appear.\n *\n * 4. The names \"Xerces\" and \"Apache Software Foundation\" must\n * not be used to endorse or promote products derived from this\n * software without prior written permission. For written\n * permission, please contact apache\\@apache.org.\n *\n * 5. Products derived from this software may not be called \"Apache\",\n * nor may \"Apache\" appear in their name, without prior written\n * permission of the Apache Software Foundation.\n *\n * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED\n * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR\n * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF\n * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT\n * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n * ====================================================================\n *\n * This software consists of voluntary contributions made by many\n * individuals on behalf of the Apache Software Foundation, and was\n * originally based on software copyright (c) 1999, International\n * Business Machines, Inc., http:\/\/www.ibm.com . For more information\n * on the Apache Software Foundation, please see\n * .\n *\/\n\n\/*\n * $Log$\n * Revision 1.21 2004\/04\/13 17:00:23 peiyongz\n * IdentityConstraintHandler\n *\n * Revision 1.19 2004\/04\/07 14:14:08 peiyongz\n * make resolveSystemId virutal\n *\n * Revision 1.18 2004\/01\/29 11:46:30 cargilld\n * Code cleanup changes to get rid of various compiler diagnostic messages.\n *\n * Revision 1.17 2003\/11\/28 19:54:31 knoaman\n * PSVIElement update\n *\n * Revision 1.16 2003\/11\/28 05:13:29 neilg\n * Fix state-ful duplicate attribute detection when the integrated\n * scanner is in use and namespaces are off. Also, implement\n * change to PSVIHandler interface to remove prefix passing.\n *\n * Revision 1.15 2003\/11\/27 22:52:37 knoaman\n * PSVIElement implementation\n *\n * Revision 1.14 2003\/11\/27 06:10:31 neilg\n * PSVIAttribute implementation\n *\n * Revision 1.13 2003\/11\/26 16:20:00 knoaman\n * Store XSModel.\n *\n * Revision 1.12 2003\/11\/24 05:09:38 neilg\n * implement new, statless, method for detecting duplicate attributes\n *\n * Revision 1.11 2003\/10\/22 20:22:30 knoaman\n * Prepare for annotation support.\n *\n * Revision 1.10 2003\/09\/22 19:51:41 neilg\n * scanners should maintain their own pools of undeclared elements, rather than requiring grammars to do this. This makes grammar objects stateless with regard to validation.\n *\n * Revision 1.9 2003\/08\/14 02:56:41 knoaman\n * Code refactoring to improve performance of validation.\n *\n * Revision 1.8 2003\/07\/10 19:47:23 peiyongz\n * Stateless Grammar: Initialize scanner with grammarResolver,\n * creating grammar through grammarPool\n *\n * Revision 1.7 2003\/05\/22 02:10:51 knoaman\n * Default the memory manager.\n *\n * Revision 1.6 2003\/05\/15 18:26:29 knoaman\n * Partial implementation of the configurable memory manager.\n *\n * Revision 1.5 2003\/03\/07 18:08:58 tng\n * Return a reference instead of void for operator=\n *\n * Revision 1.4 2003\/01\/29 19:59:35 gareth\n * we now detect when elements and attributes are validated\/ the result of the validation and store that information.\n *\n * Revision 1.3 2003\/01\/15 15:49:49 knoaman\n * Change constant declaration name to match its value.\n *\n * Revision 1.2 2003\/01\/13 16:30:18 knoaman\n * [Bug 14469] Validator doesn't enforce xsd:key.\n *\n * Revision 1.1 2002\/12\/04 02:05:25 knoaman\n * Initial checkin.\n *\n *\/\n\n\n#if !defined(IGXMLSCANNER_HPP)\n#define IGXMLSCANNER_HPP\n\n#include \n#include \n#include \n#include \n#include \n#include \n\nXERCES_CPP_NAMESPACE_BEGIN\n\nclass DTDElementDecl;\nclass DTDGrammar;\nclass DTDValidator;\nclass SchemaValidator;\nclass IdentityConstraintHandler;\nclass IdentityConstraint;\nclass ContentLeafNameTypeVector;\nclass SchemaAttDef;\nclass XMLContentModel;\nclass XSModel;\nclass PSVIAttributeList;\nclass PSVIElement;\n\n\/\/ This is an integrated scanner class, which does DTD\/XML Schema grammar\n\/\/ processing.\nclass XMLPARSER_EXPORT IGXMLScanner : public XMLScanner\n{\npublic :\n \/\/ -----------------------------------------------------------------------\n \/\/ Constructors and Destructor\n \/\/ -----------------------------------------------------------------------\n IGXMLScanner\n (\n XMLValidator* const valToAdopt\n , GrammarResolver* const grammarResolver\n , MemoryManager* const manager = XMLPlatformUtils::fgMemoryManager\n );\n IGXMLScanner\n (\n XMLDocumentHandler* const docHandler\n , DocTypeHandler* const docTypeHandler\n , XMLEntityHandler* const entityHandler\n , XMLErrorReporter* const errReporter\n , XMLValidator* const valToAdopt\n , GrammarResolver* const grammarResolver\n , MemoryManager* const manager = XMLPlatformUtils::fgMemoryManager\n );\n virtual ~IGXMLScanner();\n\n \/\/ -----------------------------------------------------------------------\n \/\/ XMLScanner public virtual methods\n \/\/ -----------------------------------------------------------------------\n virtual const XMLCh* getName() const;\n virtual NameIdPool* getEntityDeclPool();\n virtual const NameIdPool* getEntityDeclPool() const;\n virtual unsigned int resolveQName\n (\n const XMLCh* const qName\n , XMLBuffer& prefixBufToFill\n , const short mode\n , int& prefixColonPos\n );\n virtual void scanDocument\n (\n const InputSource& src\n );\n virtual bool scanNext(XMLPScanToken& toFill);\n virtual Grammar* loadGrammar\n (\n const InputSource& src\n , const short grammarType\n , const bool toCache = false\n );\n\nprivate :\n \/\/ -----------------------------------------------------------------------\n \/\/ Unimplemented constructors and operators\n \/\/ -----------------------------------------------------------------------\n IGXMLScanner();\n IGXMLScanner(const IGXMLScanner&);\n IGXMLScanner& operator=(const IGXMLScanner&);\n\n \/\/ -----------------------------------------------------------------------\n \/\/ XMLScanner virtual methods\n \/\/ -----------------------------------------------------------------------\n virtual void scanCDSection();\n virtual void scanCharData(XMLBuffer& toToUse);\n virtual EntityExpRes scanEntityRef\n (\n const bool inAttVal\n , XMLCh& firstCh\n , XMLCh& secondCh\n , bool& escaped\n );\n virtual void scanDocTypeDecl();\n virtual void scanReset(const InputSource& src);\n virtual void sendCharData(XMLBuffer& toSend);\n virtual InputSource* resolveSystemId(const XMLCh* const sysId);\n\n \/\/ -----------------------------------------------------------------------\n \/\/ Private helper methods\n \/\/ -----------------------------------------------------------------------\n void commonInit();\n void cleanUp();\n\n \/\/ Spaces are not allowed in URI, so %20 is used instead.\n \/\/ Convert %20 to spaces before resolving the URI\n void normalizeURI(const XMLCh* const systemURI, XMLBuffer& normalizedURI);\n\n unsigned int buildAttList\n (\n const RefVectorOf& providedAttrs\n , const unsigned int attCount\n , XMLElementDecl* elemDecl\n , RefVectorOf& toFill\n );\n bool normalizeAttValue\n (\n const XMLAttDef* const attDef\n , const XMLCh* const name \n , const XMLCh* const value\n , XMLBuffer& toFill\n );\n bool normalizeAttRawValue\n (\n const XMLCh* const attrName\n , const XMLCh* const value\n , XMLBuffer& toFill\n );\n unsigned int resolvePrefix\n (\n const XMLCh* const prefix\n , const ElemStack::MapModes mode\n );\n unsigned int resolvePrefix\n (\n const XMLCh* const prefix\n , XMLBuffer& uriBufToFill\n , const ElemStack::MapModes mode\n );\n void updateNSMap\n (\n const XMLCh* const attrName\n , const XMLCh* const attrValue\n );\n void scanRawAttrListforNameSpaces(int attCount);\n void parseSchemaLocation(const XMLCh* const schemaLocationStr);\n void resolveSchemaGrammar(const XMLCh* const loc, const XMLCh* const uri);\n bool switchGrammar(const XMLCh* const newGrammarNameSpace);\n bool laxElementValidation(QName* element, ContentLeafNameTypeVector* cv,\n const XMLContentModel* const cm,\n const unsigned int parentElemDepth);\n bool anyAttributeValidation(SchemaAttDef* attWildCard,\n unsigned int uriId,\n bool& skipThisOne,\n bool& laxThisOne);\n void resizeElemState();\n void processSchemaLocation(XMLCh* const schemaLoc);\n\n \/\/ -----------------------------------------------------------------------\n \/\/ Private scanning methods\n \/\/ -----------------------------------------------------------------------\n bool basicAttrValueScan\n (\n const XMLCh* const attrName\n , XMLBuffer& toFill\n );\n unsigned int rawAttrScan\n (\n const XMLCh* const elemName\n , RefVectorOf& toFill\n , bool& isEmpty\n );\n bool scanAttValue\n (\n const XMLAttDef* const attDef\n , const XMLCh* const attrName\n , XMLBuffer& toFill\n );\n bool scanContent();\n void scanEndTag(bool& gotData);\n bool scanStartTag(bool& gotData);\n bool scanStartTagNS(bool& gotData);\n\n \/\/ -----------------------------------------------------------------------\n \/\/ IdentityConstraints Activation methods\n \/\/ -----------------------------------------------------------------------\n inline bool toCheckIdentityConstraint() const;\n\n \/\/ -----------------------------------------------------------------------\n \/\/ Grammar preparsing methods\n \/\/ -----------------------------------------------------------------------\n Grammar* loadXMLSchemaGrammar(const InputSource& src, const bool toCache = false);\n Grammar* loadDTDGrammar(const InputSource& src, const bool toCache = false);\n\n \/\/ -----------------------------------------------------------------------\n \/\/ PSVI handling methods\n \/\/ -----------------------------------------------------------------------\n void endElementPSVI(SchemaElementDecl* const elemDecl,\n DatatypeValidator* const memberDV);\n void resetPSVIElemContext();\n\n \/\/ -----------------------------------------------------------------------\n \/\/ Data members\n \/\/\n \/\/ fRawAttrList\n \/\/ During the initial scan of the attributes we can only do a raw\n \/\/ scan for key\/value pairs. So this vector is used to store them\n \/\/ until they can be processed (and put into fAttrList.)\n \/\/\n \/\/ fDTDValidator\n \/\/ The DTD validator instance.\n \/\/\n \/\/ fSchemaValidator\n \/\/ The Schema validator instance.\n \/\/\n \/\/ fSeeXsi\n \/\/ This flag indicates a schema has been seen.\n \/\/\n \/\/ fElemState\n \/\/ fElemStateSize\n \/\/ Stores an element next state from DFA content model - used for\n \/\/ wildcard validation\n \/\/\n \/\/ fDTDElemNonDeclPool\n \/\/ registry of \"faulted-in\" DTD element decls\n \/\/ fSchemaElemNonDeclPool\n \/\/ registry for elements without decls in the grammar\n \/\/ fElemCount\n \/\/ count of the number of start tags seen so far (starts at 1).\n \/\/ Used for duplicate attribute detection\/processing of required\/defaulted attributes\n \/\/ fAttDefRegistry\n \/\/ mapping from XMLAttDef instances to the count of the last\n \/\/ start tag where they were utilized.\n \/\/ fUndeclaredAttrRegistry\n \/\/ mapping of attr QNames to the count of the last start tag in which they occurred\n \/\/ fUndeclaredAttrRegistryNS\n \/\/ mapping of namespaceId\/localName pairs to the count of the last\n \/\/ start tag in which they occurred.\n \/\/ fPSVIAttrList\n \/\/ PSVI attribute list implementation that needs to be\n \/\/ filled when a PSVIHandler is registered\n \/\/\n \/\/ -----------------------------------------------------------------------\n bool fSeeXsi;\n Grammar::GrammarType fGrammarType;\n unsigned int fElemStateSize;\n unsigned int* fElemState;\n XMLBuffer fContent;\n RefVectorOf* fRawAttrList;\n DTDValidator* fDTDValidator;\n SchemaValidator* fSchemaValidator;\n DTDGrammar* fDTDGrammar;\n IdentityConstraintHandler* fICHandler;\n ValueVectorOf* fLocationPairs;\n NameIdPool* fDTDElemNonDeclPool;\n RefHash3KeysIdPool* fSchemaElemNonDeclPool;\n unsigned int fElemCount;\n RefHashTableOf* fAttDefRegistry;\n RefHashTableOf* fUndeclaredAttrRegistry;\n RefHash2KeysTableOf* fUndeclaredAttrRegistryNS;\n PSVIAttributeList * fPSVIAttrList;\n XSModel* fModel;\n PSVIElement* fPSVIElement;\n ValueStackOf* fErrorStack;\n PSVIElemContext fPSVIElemContext;\n};\n\ninline const XMLCh* IGXMLScanner::getName() const\n{\n return XMLUni::fgIGXMLScanner;\n}\n\ninline bool IGXMLScanner::toCheckIdentityConstraint() const\n{\n return fValidate && fIdentityConstraintChecking && fICHandler;\n}\n\nXERCES_CPP_NAMESPACE_END\n\n#endif\n<|endoftext|>"} {"text":"\/*\n * This file is a part of Xpiks - cross platform application for\n * keywording and uploading images for microstocks\n * Copyright (C) 2014-2016 Taras Kushnir \n *\n * Xpiks is distributed under the GNU General Public License, version 3.0\n *\n * This program is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see .\n *\/\n\n#include \"settingsmodel.h\"\n#include \n#include \n#include \"..\/Helpers\/appsettings.h\"\n#include \"..\/Common\/defines.h\"\n#include \"..\/Commands\/commandmanager.h\"\n\n#ifdef Q_OS_MAC\n#define DEFAULT_EXIFTOOL \"\/usr\/bin\/exiftool\"\n#else\n#define DEFAULT_EXIFTOOL \"exiftool\"\n#endif\n\n#define DEFAULT_DICT_PATH \"\"\n#define DEFAULT_MAX_KEYWORDS 50\n#define DEFAULT_MAX_DESCRIPTION 200\n#define DEFAULT_MIN_MEGAPIXELS 4.0\n#define DEFAULT_USE_MASTERPASSWORD false\n#define DEFAULT_UPLOAD_TIMEOUT 10\n#define DEFAULT_USE_CONFIRMATIONS true\n#define DEFAULT_SAVE_BACKUPS true\n#define DEFAULT_KEYWORD_SIZE_SCALE 1.0\n#define DEFAULT_DISMISS_DURATION 10\n#define DEFAULT_MAX_PARALLEL_UPLOADS 2\n#define DEFAULT_FIT_SMALL_PREVIEW false\n#define DEFAULT_SEARCH_USING_AND true\n#define DEFAULT_SCROLL_SPEED_SCALE 1.0\n#define DEFAULT_USE_SPELL_CHECK true\n#define DEFAULT_HAVE_USER_CONSENT false\n#define DEFAULT_COLLECT_USER_STATISTIC true\n#define DEFAULT_UPDATE_SERVICE true\n#define DEFAULT_APP_WIDTH 900\n#define DEFAULT_APP_HEIGHT 725\n#define DEFAULT_APP_POSITION -1\n\nnamespace Models {\n SettingsModel::SettingsModel(QObject *parent) :\n QObject(parent),\n m_ExifToolPath(DEFAULT_EXIFTOOL),\n m_DictPath(DEFAULT_DICT_PATH),\n m_MinMegapixelCount(DEFAULT_MIN_MEGAPIXELS),\n m_KeywordSizeScale(DEFAULT_KEYWORD_SIZE_SCALE),\n m_ScrollSpeedScale(DEFAULT_SCROLL_SPEED_SCALE),\n m_MaxDescriptionLength(DEFAULT_MAX_DESCRIPTION),\n m_MaxKeywordsCount(DEFAULT_MAX_KEYWORDS),\n m_UploadTimeout(DEFAULT_UPLOAD_TIMEOUT),\n m_DismissDuration(DEFAULT_DISMISS_DURATION),\n m_MaxParallelUploads(DEFAULT_MAX_PARALLEL_UPLOADS),\n m_MustUseMasterPassword(DEFAULT_USE_MASTERPASSWORD),\n m_MustUseConfirmations(DEFAULT_USE_CONFIRMATIONS),\n m_SaveBackups(DEFAULT_SAVE_BACKUPS),\n m_FitSmallPreview(DEFAULT_FIT_SMALL_PREVIEW),\n m_SearchUsingAnd(DEFAULT_SEARCH_USING_AND),\n m_UseSpellCheck(DEFAULT_USE_SPELL_CHECK),\n m_UserStatistic(DEFAULT_COLLECT_USER_STATISTIC),\n m_UpdateService(DEFAULT_UPDATE_SERVICE),\n m_DictsPathChanged(false)\n {\n }\n\n void SettingsModel::saveExiftool() {\n qDebug() << \"SettingsModel::saveExiftool #\";\n Helpers::AppSettings appSettings;\n appSettings.setValue(appSettings.getExifToolPathKey(), m_ExifToolPath);\n }\n\n void SettingsModel::resetAllValues() {\n qDebug() << \"SettingsModel::resetAllValues #\";\n resetToDefault();\n saveAllValues();\n emit settingsReset();\n }\n\n void SettingsModel::saveAllValues() {\n qInfo() << \"SettingsModel::saveAllValues #\";\n\n Helpers::AppSettings appSettings;\n appSettings.setValue(appSettings.getExifToolPathKey(), m_ExifToolPath);\n appSettings.setValue(appSettings.getDictionaryPathKey(), m_DictPath);\n appSettings.setValue(appSettings.getMinMegapixelCountKey(), m_MinMegapixelCount);\n appSettings.setValue(appSettings.getMaxDescriptionLengthKey(), m_MaxDescriptionLength);\n appSettings.setValue(appSettings.getMaxKeywordsCountKey(), m_MaxKeywordsCount);\n appSettings.setValue(appSettings.getOneUploadSecondsTimeoutKey(), m_UploadTimeout);\n appSettings.setValue(appSettings.getMustUseMasterPasswordKey(), m_MustUseMasterPassword);\n appSettings.setValue(appSettings.getUseConfirmationDialogsKey(), m_MustUseConfirmations);\n appSettings.setValue(appSettings.getSaveBackupsKey(), m_SaveBackups);\n appSettings.setValue(appSettings.getKeywordSizeScaleKey(), m_KeywordSizeScale);\n appSettings.setValue(appSettings.getDismissDurationKey(), m_DismissDuration);\n appSettings.setValue(appSettings.getMaxParallelUploadsKey(), m_MaxParallelUploads);\n appSettings.setValue(appSettings.getFitSmallPreviewKey(), m_FitSmallPreview);\n appSettings.setValue(appSettings.getSearchUsingAndKey(), m_SearchUsingAnd);\n appSettings.setValue(appSettings.getScrollSpeedScaleKey(), m_ScrollSpeedScale);\n appSettings.setValue(appSettings.getUseSpellCheckKey(), m_UseSpellCheck);\n appSettings.setValue(appSettings.getUserStatisticKey(), m_UserStatistic);\n appSettings.setValue(appSettings.getUpdateServiceKey(), m_UpdateService);\n\n if (!m_MustUseMasterPassword) {\n appSettings.setValue(appSettings.getMasterPasswordHashKey(), \"\");\n }\n\n emit keywordSizeScaleChanged(m_KeywordSizeScale);\n\n#if defined(Q_OS_LINUX)\n if (m_DictsPathChanged) {\n \/\/ TODO: check if need to restart depending on path\n m_CommandManager->restartSpellChecking();\n m_DictsPathChanged = false;\n }\n#endif\n }\n\n void SettingsModel::clearMasterPasswordSettings() {\n setMustUseMasterPassword(false);\n Helpers::AppSettings appSettings;\n appSettings.setValue(appSettings.getMasterPasswordHashKey(), \"\");\n appSettings.setValue(appSettings.getMustUseMasterPasswordKey(), false);\n }\n\n void SettingsModel::resetExifTool() {\n setExifToolPath(DEFAULT_EXIFTOOL);\n }\n\n void SettingsModel::resetDictPath() {\n setDictionaryPath(DEFAULT_DICT_PATH);\n }\n\n void SettingsModel::readAllValues() {\n qInfo() << \"SettingsModel::readAllValues #\";\n\n Helpers::AppSettings appSettings;\n setExifToolPath(appSettings.value(appSettings.getExifToolPathKey(), DEFAULT_EXIFTOOL).toString());\n setDictionaryPath(appSettings.value(appSettings.getDictionaryPathKey(), DEFAULT_DICT_PATH).toString());\n setMinMegapixelCount(appSettings.doubleValue(appSettings.getMinMegapixelCountKey(), DEFAULT_MIN_MEGAPIXELS));\n setMaxDescriptionLength(appSettings.value(appSettings.getMaxDescriptionLengthKey(), DEFAULT_MAX_DESCRIPTION).toInt());\n setMaxKeywordsCount(appSettings.value(appSettings.getMaxKeywordsCountKey(), DEFAULT_MAX_KEYWORDS).toInt());\n setUploadTimeout(appSettings.value(appSettings.getOneUploadSecondsTimeoutKey(), DEFAULT_UPLOAD_TIMEOUT).toInt());\n setMustUseMasterPassword(appSettings.boolValue(appSettings.getMustUseMasterPasswordKey(), DEFAULT_USE_MASTERPASSWORD));\n setMustUseConfirmations(appSettings.boolValue(appSettings.getUseConfirmationDialogsKey(), DEFAULT_USE_CONFIRMATIONS));\n setSaveBackups(appSettings.boolValue(appSettings.getSaveBackupsKey(), DEFAULT_SAVE_BACKUPS));\n setKeywordSizeScale(appSettings.doubleValue(appSettings.getKeywordSizeScaleKey(), DEFAULT_KEYWORD_SIZE_SCALE));\n setDismissDuration(appSettings.value(appSettings.getDismissDurationKey(), DEFAULT_DISMISS_DURATION).toInt());\n setMaxParallelUploads(appSettings.value(appSettings.getMaxParallelUploadsKey(), DEFAULT_MAX_PARALLEL_UPLOADS).toInt());\n setFitSmallPreview(appSettings.boolValue(appSettings.getFitSmallPreviewKey(), DEFAULT_FIT_SMALL_PREVIEW));\n setSearchUsingAnd(appSettings.boolValue(appSettings.getSearchUsingAndKey(), DEFAULT_SEARCH_USING_AND));\n setScrollSpeedScale(appSettings.doubleValue(appSettings.getScrollSpeedScaleKey(), DEFAULT_SCROLL_SPEED_SCALE));\n setUseSpellCheck(appSettings.boolValue(appSettings.getUseSpellCheckKey(), DEFAULT_USE_SPELL_CHECK));\n setUserStatistic(appSettings.boolValue(appSettings.getUserStatisticKey(), DEFAULT_COLLECT_USER_STATISTIC));\n setUpdateService(appSettings.boolValue(appSettings.getUpdateServiceKey(), DEFAULT_UPDATE_SERVICE));\n }\n\n void SettingsModel::resetToDefault() {\n qInfo() << \"SettingsModel::resetToDefault #\";\n\n setExifToolPath(DEFAULT_EXIFTOOL);\n setDictionaryPath(DEFAULT_DICT_PATH);\n setMinMegapixelCount(DEFAULT_MIN_MEGAPIXELS);\n setMaxDescriptionLength(DEFAULT_MAX_DESCRIPTION);\n setMaxKeywordsCount(DEFAULT_MAX_KEYWORDS);\n setUploadTimeout(DEFAULT_UPLOAD_TIMEOUT);\n setMustUseMasterPassword(DEFAULT_USE_MASTERPASSWORD);\n setMustUseConfirmations(DEFAULT_USE_CONFIRMATIONS);\n setSaveBackups(DEFAULT_SAVE_BACKUPS);\n setKeywordSizeScale(DEFAULT_KEYWORD_SIZE_SCALE);\n setDismissDuration(DEFAULT_DISMISS_DURATION);\n setMaxParallelUploads(DEFAULT_MAX_PARALLEL_UPLOADS);\n setFitSmallPreview(DEFAULT_FIT_SMALL_PREVIEW);\n setSearchUsingAnd(DEFAULT_SEARCH_USING_AND);\n setScrollSpeedScale(DEFAULT_SCROLL_SPEED_SCALE);\n setUseSpellCheck(DEFAULT_USE_SPELL_CHECK);\n setUserStatistic(DEFAULT_COLLECT_USER_STATISTIC);\n setUpdateService(DEFAULT_UPDATE_SERVICE);\n\n Helpers::AppSettings appSettings;\n#if defined(QT_DEBUG)\n appSettings.setValue(appSettings.getUserConsentKey(), DEFAULT_HAVE_USER_CONSENT);\n appSettings.setValue(appSettings.getInstalledVersionKey(), 0);\n#endif\n\n \/\/ resetting position in settings is pretty useless because\n \/\/ we will overwrite them on Xpiks exit. But anyway for the future...\n appSettings.setValue(appSettings.getAppHeightKey(), DEFAULT_APP_HEIGHT);\n appSettings.setValue(appSettings.getAppWidthKey(), DEFAULT_APP_WIDTH);\n appSettings.setValue(appSettings.getAppPosXKey(), DEFAULT_APP_POSITION);\n appSettings.setValue(appSettings.getAppPosYKey(), DEFAULT_APP_POSITION);\n }\n\n int ensureInBounds(int value, int boundA, int boundB) {\n Q_ASSERT(boundA <= boundB);\n\n if (value < boundA) {\n value = boundA;\n }\n\n if (value > boundB) {\n value = boundB;\n }\n\n return value;\n }\n\n double ensureInBounds(double value, double boundA, double boundB) {\n Q_ASSERT(boundA <= boundB);\n\n \/\/ double nan\n if (value != value) {\n value = boundA;\n }\n\n if (value < boundA) {\n value = boundA;\n }\n\n if (value > boundB) {\n value = boundB;\n }\n\n return value;\n }\n}\n\nChanged default confirmations value\/*\n * This file is a part of Xpiks - cross platform application for\n * keywording and uploading images for microstocks\n * Copyright (C) 2014-2016 Taras Kushnir \n *\n * Xpiks is distributed under the GNU General Public License, version 3.0\n *\n * This program is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see .\n *\/\n\n#include \"settingsmodel.h\"\n#include \n#include \n#include \"..\/Helpers\/appsettings.h\"\n#include \"..\/Common\/defines.h\"\n#include \"..\/Commands\/commandmanager.h\"\n\n#ifdef Q_OS_MAC\n#define DEFAULT_EXIFTOOL \"\/usr\/bin\/exiftool\"\n#else\n#define DEFAULT_EXIFTOOL \"exiftool\"\n#endif\n\n#define DEFAULT_DICT_PATH \"\"\n#define DEFAULT_MAX_KEYWORDS 50\n#define DEFAULT_MAX_DESCRIPTION 200\n#define DEFAULT_MIN_MEGAPIXELS 4.0\n#define DEFAULT_USE_MASTERPASSWORD false\n#define DEFAULT_UPLOAD_TIMEOUT 10\n#define DEFAULT_USE_CONFIRMATIONS false\n#define DEFAULT_SAVE_BACKUPS true\n#define DEFAULT_KEYWORD_SIZE_SCALE 1.0\n#define DEFAULT_DISMISS_DURATION 10\n#define DEFAULT_MAX_PARALLEL_UPLOADS 2\n#define DEFAULT_FIT_SMALL_PREVIEW false\n#define DEFAULT_SEARCH_USING_AND true\n#define DEFAULT_SCROLL_SPEED_SCALE 1.0\n#define DEFAULT_USE_SPELL_CHECK true\n#define DEFAULT_HAVE_USER_CONSENT false\n#define DEFAULT_COLLECT_USER_STATISTIC true\n#define DEFAULT_UPDATE_SERVICE true\n#define DEFAULT_APP_WIDTH 900\n#define DEFAULT_APP_HEIGHT 725\n#define DEFAULT_APP_POSITION -1\n\nnamespace Models {\n SettingsModel::SettingsModel(QObject *parent) :\n QObject(parent),\n m_ExifToolPath(DEFAULT_EXIFTOOL),\n m_DictPath(DEFAULT_DICT_PATH),\n m_MinMegapixelCount(DEFAULT_MIN_MEGAPIXELS),\n m_KeywordSizeScale(DEFAULT_KEYWORD_SIZE_SCALE),\n m_ScrollSpeedScale(DEFAULT_SCROLL_SPEED_SCALE),\n m_MaxDescriptionLength(DEFAULT_MAX_DESCRIPTION),\n m_MaxKeywordsCount(DEFAULT_MAX_KEYWORDS),\n m_UploadTimeout(DEFAULT_UPLOAD_TIMEOUT),\n m_DismissDuration(DEFAULT_DISMISS_DURATION),\n m_MaxParallelUploads(DEFAULT_MAX_PARALLEL_UPLOADS),\n m_MustUseMasterPassword(DEFAULT_USE_MASTERPASSWORD),\n m_MustUseConfirmations(DEFAULT_USE_CONFIRMATIONS),\n m_SaveBackups(DEFAULT_SAVE_BACKUPS),\n m_FitSmallPreview(DEFAULT_FIT_SMALL_PREVIEW),\n m_SearchUsingAnd(DEFAULT_SEARCH_USING_AND),\n m_UseSpellCheck(DEFAULT_USE_SPELL_CHECK),\n m_UserStatistic(DEFAULT_COLLECT_USER_STATISTIC),\n m_UpdateService(DEFAULT_UPDATE_SERVICE),\n m_DictsPathChanged(false)\n {\n }\n\n void SettingsModel::saveExiftool() {\n qDebug() << \"SettingsModel::saveExiftool #\";\n Helpers::AppSettings appSettings;\n appSettings.setValue(appSettings.getExifToolPathKey(), m_ExifToolPath);\n }\n\n void SettingsModel::resetAllValues() {\n qDebug() << \"SettingsModel::resetAllValues #\";\n resetToDefault();\n saveAllValues();\n emit settingsReset();\n }\n\n void SettingsModel::saveAllValues() {\n qInfo() << \"SettingsModel::saveAllValues #\";\n\n Helpers::AppSettings appSettings;\n appSettings.setValue(appSettings.getExifToolPathKey(), m_ExifToolPath);\n appSettings.setValue(appSettings.getDictionaryPathKey(), m_DictPath);\n appSettings.setValue(appSettings.getMinMegapixelCountKey(), m_MinMegapixelCount);\n appSettings.setValue(appSettings.getMaxDescriptionLengthKey(), m_MaxDescriptionLength);\n appSettings.setValue(appSettings.getMaxKeywordsCountKey(), m_MaxKeywordsCount);\n appSettings.setValue(appSettings.getOneUploadSecondsTimeoutKey(), m_UploadTimeout);\n appSettings.setValue(appSettings.getMustUseMasterPasswordKey(), m_MustUseMasterPassword);\n appSettings.setValue(appSettings.getUseConfirmationDialogsKey(), m_MustUseConfirmations);\n appSettings.setValue(appSettings.getSaveBackupsKey(), m_SaveBackups);\n appSettings.setValue(appSettings.getKeywordSizeScaleKey(), m_KeywordSizeScale);\n appSettings.setValue(appSettings.getDismissDurationKey(), m_DismissDuration);\n appSettings.setValue(appSettings.getMaxParallelUploadsKey(), m_MaxParallelUploads);\n appSettings.setValue(appSettings.getFitSmallPreviewKey(), m_FitSmallPreview);\n appSettings.setValue(appSettings.getSearchUsingAndKey(), m_SearchUsingAnd);\n appSettings.setValue(appSettings.getScrollSpeedScaleKey(), m_ScrollSpeedScale);\n appSettings.setValue(appSettings.getUseSpellCheckKey(), m_UseSpellCheck);\n appSettings.setValue(appSettings.getUserStatisticKey(), m_UserStatistic);\n appSettings.setValue(appSettings.getUpdateServiceKey(), m_UpdateService);\n\n if (!m_MustUseMasterPassword) {\n appSettings.setValue(appSettings.getMasterPasswordHashKey(), \"\");\n }\n\n emit keywordSizeScaleChanged(m_KeywordSizeScale);\n\n#if defined(Q_OS_LINUX)\n if (m_DictsPathChanged) {\n \/\/ TODO: check if need to restart depending on path\n m_CommandManager->restartSpellChecking();\n m_DictsPathChanged = false;\n }\n#endif\n }\n\n void SettingsModel::clearMasterPasswordSettings() {\n setMustUseMasterPassword(false);\n Helpers::AppSettings appSettings;\n appSettings.setValue(appSettings.getMasterPasswordHashKey(), \"\");\n appSettings.setValue(appSettings.getMustUseMasterPasswordKey(), false);\n }\n\n void SettingsModel::resetExifTool() {\n setExifToolPath(DEFAULT_EXIFTOOL);\n }\n\n void SettingsModel::resetDictPath() {\n setDictionaryPath(DEFAULT_DICT_PATH);\n }\n\n void SettingsModel::readAllValues() {\n qInfo() << \"SettingsModel::readAllValues #\";\n\n Helpers::AppSettings appSettings;\n setExifToolPath(appSettings.value(appSettings.getExifToolPathKey(), DEFAULT_EXIFTOOL).toString());\n setDictionaryPath(appSettings.value(appSettings.getDictionaryPathKey(), DEFAULT_DICT_PATH).toString());\n setMinMegapixelCount(appSettings.doubleValue(appSettings.getMinMegapixelCountKey(), DEFAULT_MIN_MEGAPIXELS));\n setMaxDescriptionLength(appSettings.value(appSettings.getMaxDescriptionLengthKey(), DEFAULT_MAX_DESCRIPTION).toInt());\n setMaxKeywordsCount(appSettings.value(appSettings.getMaxKeywordsCountKey(), DEFAULT_MAX_KEYWORDS).toInt());\n setUploadTimeout(appSettings.value(appSettings.getOneUploadSecondsTimeoutKey(), DEFAULT_UPLOAD_TIMEOUT).toInt());\n setMustUseMasterPassword(appSettings.boolValue(appSettings.getMustUseMasterPasswordKey(), DEFAULT_USE_MASTERPASSWORD));\n setMustUseConfirmations(appSettings.boolValue(appSettings.getUseConfirmationDialogsKey(), DEFAULT_USE_CONFIRMATIONS));\n setSaveBackups(appSettings.boolValue(appSettings.getSaveBackupsKey(), DEFAULT_SAVE_BACKUPS));\n setKeywordSizeScale(appSettings.doubleValue(appSettings.getKeywordSizeScaleKey(), DEFAULT_KEYWORD_SIZE_SCALE));\n setDismissDuration(appSettings.value(appSettings.getDismissDurationKey(), DEFAULT_DISMISS_DURATION).toInt());\n setMaxParallelUploads(appSettings.value(appSettings.getMaxParallelUploadsKey(), DEFAULT_MAX_PARALLEL_UPLOADS).toInt());\n setFitSmallPreview(appSettings.boolValue(appSettings.getFitSmallPreviewKey(), DEFAULT_FIT_SMALL_PREVIEW));\n setSearchUsingAnd(appSettings.boolValue(appSettings.getSearchUsingAndKey(), DEFAULT_SEARCH_USING_AND));\n setScrollSpeedScale(appSettings.doubleValue(appSettings.getScrollSpeedScaleKey(), DEFAULT_SCROLL_SPEED_SCALE));\n setUseSpellCheck(appSettings.boolValue(appSettings.getUseSpellCheckKey(), DEFAULT_USE_SPELL_CHECK));\n setUserStatistic(appSettings.boolValue(appSettings.getUserStatisticKey(), DEFAULT_COLLECT_USER_STATISTIC));\n setUpdateService(appSettings.boolValue(appSettings.getUpdateServiceKey(), DEFAULT_UPDATE_SERVICE));\n }\n\n void SettingsModel::resetToDefault() {\n qInfo() << \"SettingsModel::resetToDefault #\";\n\n setExifToolPath(DEFAULT_EXIFTOOL);\n setDictionaryPath(DEFAULT_DICT_PATH);\n setMinMegapixelCount(DEFAULT_MIN_MEGAPIXELS);\n setMaxDescriptionLength(DEFAULT_MAX_DESCRIPTION);\n setMaxKeywordsCount(DEFAULT_MAX_KEYWORDS);\n setUploadTimeout(DEFAULT_UPLOAD_TIMEOUT);\n setMustUseMasterPassword(DEFAULT_USE_MASTERPASSWORD);\n setMustUseConfirmations(DEFAULT_USE_CONFIRMATIONS);\n setSaveBackups(DEFAULT_SAVE_BACKUPS);\n setKeywordSizeScale(DEFAULT_KEYWORD_SIZE_SCALE);\n setDismissDuration(DEFAULT_DISMISS_DURATION);\n setMaxParallelUploads(DEFAULT_MAX_PARALLEL_UPLOADS);\n setFitSmallPreview(DEFAULT_FIT_SMALL_PREVIEW);\n setSearchUsingAnd(DEFAULT_SEARCH_USING_AND);\n setScrollSpeedScale(DEFAULT_SCROLL_SPEED_SCALE);\n setUseSpellCheck(DEFAULT_USE_SPELL_CHECK);\n setUserStatistic(DEFAULT_COLLECT_USER_STATISTIC);\n setUpdateService(DEFAULT_UPDATE_SERVICE);\n\n Helpers::AppSettings appSettings;\n#if defined(QT_DEBUG)\n appSettings.setValue(appSettings.getUserConsentKey(), DEFAULT_HAVE_USER_CONSENT);\n appSettings.setValue(appSettings.getInstalledVersionKey(), 0);\n#endif\n\n \/\/ resetting position in settings is pretty useless because\n \/\/ we will overwrite them on Xpiks exit. But anyway for the future...\n appSettings.setValue(appSettings.getAppHeightKey(), DEFAULT_APP_HEIGHT);\n appSettings.setValue(appSettings.getAppWidthKey(), DEFAULT_APP_WIDTH);\n appSettings.setValue(appSettings.getAppPosXKey(), DEFAULT_APP_POSITION);\n appSettings.setValue(appSettings.getAppPosYKey(), DEFAULT_APP_POSITION);\n }\n\n int ensureInBounds(int value, int boundA, int boundB) {\n Q_ASSERT(boundA <= boundB);\n\n if (value < boundA) {\n value = boundA;\n }\n\n if (value > boundB) {\n value = boundB;\n }\n\n return value;\n }\n\n double ensureInBounds(double value, double boundA, double boundB) {\n Q_ASSERT(boundA <= boundB);\n\n \/\/ double nan\n if (value != value) {\n value = boundA;\n }\n\n if (value < boundA) {\n value = boundA;\n }\n\n if (value > boundB) {\n value = boundB;\n }\n\n return value;\n }\n}\n\n<|endoftext|>"} {"text":"\/*******************************************************************************\n*\n* MIT License\n*\n* Copyright (c) 2017 Advanced Micro Devices, Inc.\n*\n* Permission is hereby granted, free of charge, to any person obtaining a copy\n* of this software and associated documentation files (the \"Software\"), to deal\n* in the Software without restriction, including without limitation the rights\n* to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n* copies of the Software, and to permit persons to whom the Software is\n* furnished to do so, subject to the following conditions:\n*\n* The above copyright notice and this permission notice shall be included in all\n* copies or substantial portions of the Software.\n*\n* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n* SOFTWARE.\n*\n*******************************************************************************\/\n\n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n\n#include \"get_handle.hpp\"\n#include \"test.hpp\"\n\nnamespace miopen {\nnamespace tests {\nclass TrivialSlowTestSolver : public solver::SolverBase\n{\n public:\n static const char* FileName() { return \"TrivialSlowTestSolver\"; }\n bool IsFast(const ConvolutionContext& context) const { return context.in_height == 1; }\n bool IsApplicable(const ConvolutionContext& context) const { return context.in_width == 1; }\n\n solver::ConvSolution GetSolution(const ConvolutionContext&) const\n {\n solver::ConvSolution ret;\n solver::KernelInfo kernel;\n\n kernel.kernel_file = FileName();\n kernel.comp_options = \" \";\n ret.construction_params.push_back(kernel);\n\n return ret;\n }\n};\n\nclass TrivialTestSolver : public solver::SolverBase\n{\n public:\n static const char* FileName() { return \"TrivialTestSolver\"; }\n bool IsApplicable(const ConvolutionContext& context) const { return context.in_width == 1; }\n\n solver::ConvSolution GetSolution(const ConvolutionContext&) const\n {\n solver::ConvSolution ret;\n solver::KernelInfo kernel;\n\n kernel.kernel_file = FileName();\n kernel.comp_options = \" \";\n ret.construction_params.push_back(kernel);\n\n return ret;\n }\n};\n\nstruct TestConfig : solver::Serializable\n{\n std::string str;\n\n template \n static void Visit(Self&& self, F f)\n {\n f(self.str, \"str\");\n }\n};\n\nclass SearchableTestSolver : public solver::SolverBase\n{\n public:\n static int searches_done() { return _serches_done; }\n static const char* FileName() { return \"SearchableTestSolver\"; }\n static const char* NoSearchFileName() { return \"SearchableTestSolver.NoSearch\"; }\n\n TestConfig GetPerformanceConfig(const ConvolutionContext&) const\n {\n TestConfig config{};\n config.str = NoSearchFileName();\n return config;\n }\n\n bool IsValidPerformanceConfig(const ConvolutionContext&, const TestConfig&) const\n {\n return true;\n }\n\n TestConfig Search(const ConvolutionContext&) const\n {\n TestConfig config;\n config.str = FileName();\n _serches_done++;\n return config;\n }\n\n solver::ConvSolution GetSolution(const ConvolutionContext&, const TestConfig& config) const\n {\n\n solver::ConvSolution ret;\n solver::KernelInfo kernel;\n\n kernel.kernel_file = config.str;\n kernel.comp_options = \" \";\n ret.construction_params.push_back(kernel);\n\n return ret;\n }\n\n private:\n static int _serches_done;\n};\n\nint SearchableTestSolver::_serches_done = 0;\n\nclass TrivialConstruct : public mlo_construct_direct2D\n{\n public:\n TrivialConstruct(const char* db_path, int dir, bool do_bias = false)\n : mlo_construct_direct2D(dir, do_bias)\n {\n _db_path = db_path;\n }\n\n solver::ConvSolution FindSolution()\n {\n \/\/ clang-format off\n return miopen::solver::SearchForSolution<\n TrivialSlowTestSolver,\n TrivialTestSolver,\n SearchableTestSolver\n >(_search_params, this->GetDb());\n \/\/ clang-format on\n }\n\n protected:\n std::string db_path() const { return _db_path; }\n};\n\nclass SolverTest\n{\n public:\n void Run() const\n {\n TempFile db_path(\"miopen.tests.solver\");\n\n ConstructTest(db_path, TrivialSlowTestSolver::FileName(), [](mlo_construct_direct2D& c) {\n c.setInputDescr(\"\", \"\", 0, 0, 1, 1, 0, 0, 0, 0);\n });\n ConstructTest(db_path, TrivialTestSolver::FileName(), [](mlo_construct_direct2D& c) {\n c.setInputDescr(\"\", \"\", 0, 0, 0, 1, 0, 0, 0, 0);\n });\n ConstructTest(db_path, TrivialTestSolver::FileName(), [](mlo_construct_direct2D& c) {\n c.setInputDescr(\"\", \"\", 0, 0, 0, 1, 0, 0, 0, 0);\n c.doSearch(true);\n });\n ConstructTest(db_path,\n SearchableTestSolver::NoSearchFileName(),\n [](mlo_construct_direct2D& c) { c.doSearch(false); });\n ConstructTest(db_path, SearchableTestSolver::FileName(), [](mlo_construct_direct2D& c) {\n c.doSearch(true);\n });\n\n const auto& searchable_solver = StaticContainer::Instance();\n const auto searches = miopen::tests::SearchableTestSolver::searches_done();\n\n \/\/ Should read in both cases: result is already in DB, solver is searchable.\n ConstructTest(db_path, SearchableTestSolver::FileName(), [](mlo_construct_direct2D&) {});\n ConstructTest(db_path, SearchableTestSolver::FileName(), [](mlo_construct_direct2D& c) {\n c.doSearch(true);\n });\n \/\/ Checking no more searches were done.\n EXPECT_EQUAL(searches, searchable_solver.searches_done());\n }\n\n private:\n void ConstructTest(const std::string& db_path,\n const char* expected_kernel,\n std::function context_filler) const\n {\n TrivialConstruct construct(db_path.c_str(), 1);\n construct.setStream(&get_handle());\n\n context_filler(construct);\n mloConstruct(construct);\n\n EXPECT_EQUAL(construct.getKernelFile(), expected_kernel);\n }\n};\n} \/\/ namespace tests\n} \/\/ namespace miopen\n\nint main() { miopen::tests::SolverTest().Run(); }\nFixed solver test.\/*******************************************************************************\n*\n* MIT License\n*\n* Copyright (c) 2017 Advanced Micro Devices, Inc.\n*\n* Permission is hereby granted, free of charge, to any person obtaining a copy\n* of this software and associated documentation files (the \"Software\"), to deal\n* in the Software without restriction, including without limitation the rights\n* to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n* copies of the Software, and to permit persons to whom the Software is\n* furnished to do so, subject to the following conditions:\n*\n* The above copyright notice and this permission notice shall be included in all\n* copies or substantial portions of the Software.\n*\n* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n* SOFTWARE.\n*\n*******************************************************************************\/\n\n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n\n#include \"get_handle.hpp\"\n#include \"test.hpp\"\n\nnamespace miopen {\nnamespace tests {\nclass TrivialSlowTestSolver : public solver::SolverBase\n{\n public:\n static const char* FileName() { return \"TrivialSlowTestSolver\"; }\n bool IsFast(const ConvolutionContext& context) const { return context.in_height == 1; }\n bool IsApplicable(const ConvolutionContext& context) const { return context.in_width == 1; }\n\n solver::ConvSolution GetSolution(const ConvolutionContext&) const\n {\n solver::ConvSolution ret;\n solver::KernelInfo kernel;\n\n kernel.kernel_file = FileName();\n kernel.comp_options = \" \";\n ret.construction_params.push_back(kernel);\n\n return ret;\n }\n};\n\nclass TrivialTestSolver : public solver::SolverBase\n{\n public:\n static const char* FileName() { return \"TrivialTestSolver\"; }\n bool IsApplicable(const ConvolutionContext& context) const { return context.in_width == 1; }\n\n solver::ConvSolution GetSolution(const ConvolutionContext&) const\n {\n solver::ConvSolution ret;\n solver::KernelInfo kernel;\n\n kernel.kernel_file = FileName();\n kernel.comp_options = \" \";\n ret.construction_params.push_back(kernel);\n\n return ret;\n }\n};\n\nstruct TestConfig : solver::Serializable\n{\n std::string str;\n\n template \n static void Visit(Self&& self, F f)\n {\n f(self.str, \"str\");\n }\n};\n\nclass SearchableTestSolver : public solver::SolverBase\n{\n public:\n static int searches_done() { return _serches_done; }\n static const char* FileName() { return \"SearchableTestSolver\"; }\n static const char* NoSearchFileName() { return \"SearchableTestSolver.NoSearch\"; }\n\n TestConfig GetPerformanceConfig(const ConvolutionContext&) const\n {\n TestConfig config{};\n config.str = NoSearchFileName();\n return config;\n }\n\n bool IsValidPerformanceConfig(const ConvolutionContext&, const TestConfig&) const\n {\n return true;\n }\n\n TestConfig Search(const ConvolutionContext&) const\n {\n TestConfig config;\n config.str = FileName();\n _serches_done++;\n return config;\n }\n\n solver::ConvSolution GetSolution(const ConvolutionContext&, const TestConfig& config) const\n {\n\n solver::ConvSolution ret;\n solver::KernelInfo kernel;\n\n kernel.kernel_file = config.str;\n kernel.comp_options = \" \";\n ret.construction_params.push_back(kernel);\n\n return ret;\n }\n\n private:\n static int _serches_done;\n};\n\nint SearchableTestSolver::_serches_done = 0;\n\nclass TrivialConstruct : public mlo_construct_direct2D\n{\n public:\n TrivialConstruct(const char* db_path, int dir, bool do_bias = false)\n : mlo_construct_direct2D(dir, do_bias)\n {\n _db_path = db_path;\n }\n\n solver::ConvSolution FindSolution() const\n {\n Db db(_db_path);\n\n \/\/ clang-format off\n return miopen::solver::SearchForSolution<\n TrivialSlowTestSolver,\n TrivialTestSolver,\n SearchableTestSolver\n >(_search_params, db);\n \/\/ clang-format on\n }\n};\n\nclass SolverTest\n{\n public:\n void Run() const\n {\n TempFile db_path(\"miopen.tests.solver\");\n\n ConstructTest(db_path, TrivialSlowTestSolver::FileName(), [](mlo_construct_direct2D& c) {\n c.setInputDescr(\"\", \"\", 0, 0, 1, 1, 0, 0, 0, 0);\n });\n ConstructTest(db_path, TrivialTestSolver::FileName(), [](mlo_construct_direct2D& c) {\n c.setInputDescr(\"\", \"\", 0, 0, 0, 1, 0, 0, 0, 0);\n });\n ConstructTest(db_path, TrivialTestSolver::FileName(), [](mlo_construct_direct2D& c) {\n c.setInputDescr(\"\", \"\", 0, 0, 0, 1, 0, 0, 0, 0);\n c.doSearch(true);\n });\n ConstructTest(db_path,\n SearchableTestSolver::NoSearchFileName(),\n [](mlo_construct_direct2D& c) { c.doSearch(false); });\n ConstructTest(db_path, SearchableTestSolver::FileName(), [](mlo_construct_direct2D& c) {\n c.doSearch(true);\n });\n\n const auto& searchable_solver = StaticContainer::Instance();\n const auto searches = miopen::tests::SearchableTestSolver::searches_done();\n\n \/\/ Should read in both cases: result is already in DB, solver is searchable.\n ConstructTest(db_path, SearchableTestSolver::FileName(), [](mlo_construct_direct2D&) {});\n ConstructTest(db_path, SearchableTestSolver::FileName(), [](mlo_construct_direct2D& c) {\n c.doSearch(true);\n });\n \/\/ Checking no more searches were done.\n EXPECT_EQUAL(searches, searchable_solver.searches_done());\n }\n\n private:\n void ConstructTest(const std::string& db_path,\n const char* expected_kernel,\n std::function context_filler) const\n {\n TrivialConstruct construct(db_path.c_str(), 1);\n construct.setStream(&get_handle());\n\n context_filler(construct);\n mloConstruct(construct);\n\n EXPECT_EQUAL(construct.getKernelFile(), expected_kernel);\n }\n};\n} \/\/ namespace tests\n} \/\/ namespace miopen\n\nint main() { miopen::tests::SolverTest().Run(); }\n<|endoftext|>"} {"text":"\n\/\/\n\/\/ This source file is part of appleseed.\n\/\/ Visit http:\/\/appleseedhq.net\/ for additional information and resources.\n\/\/\n\/\/ This software is released under the MIT license.\n\/\/\n\/\/ Copyright (c) 2010-2013 Francois Beaune, Jupiter Jazz Limited\n\/\/ Copyright (c) 2014 Francois Beaune, The appleseedhq Organization\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n\/\/ THE SOFTWARE.\n\/\/\n\n\/\/ Interface header.\n#include \"rendertab.h\"\n\n\/\/ appleseed.studio headers.\n#include \"mainwindow\/rendering\/renderwidget.h\"\n\n\/\/ appleseed.renderer headers.\n#include \"renderer\/api\/frame.h\"\n#include \"renderer\/api\/project.h\"\n\n\/\/ appleseed.foundation headers.\n#include \"foundation\/image\/canvasproperties.h\"\n#include \"foundation\/image\/color.h\"\n#include \"foundation\/image\/image.h\"\n\n\/\/ Qt headers.\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace foundation;\nusing namespace renderer;\n\nnamespace appleseed {\nnamespace studio {\n\n\/\/\n\/\/ RenderTab class implementation.\n\/\/\n\nRenderTab::RenderTab(\n ProjectExplorer& project_explorer,\n Project& project)\n : m_project_explorer(project_explorer)\n , m_project(project)\n{\n create_render_widget();\n create_toolbar();\n create_scrollarea();\n\n setObjectName(QString::fromUtf8(\"render_widget_tab\"));\n setLayout(new QGridLayout());\n layout()->setSpacing(0);\n layout()->setMargin(0);\n layout()->addWidget(m_toolbar);\n layout()->addWidget(m_scroll_area);\n\n recreate_handlers();\n}\n\nvoid RenderTab::clear()\n{\n m_render_widget->clear(Color4f(0.0f));\n}\n\nvoid RenderTab::darken()\n{\n m_render_widget->multiply(0.2f);\n}\n\nvoid RenderTab::reset_zoom()\n{\n m_zoom_handler->reset_zoom();\n}\n\nvoid RenderTab::update()\n{\n m_render_widget->update();\n}\n\nvoid RenderTab::update_size()\n{\n m_set_render_region_button->setChecked(false);\n\n const CanvasProperties& props = m_project.get_frame()->image().properties();\n\n m_render_widget->resize(\n props.m_canvas_width,\n props.m_canvas_height);\n\n recreate_handlers();\n}\n\nRenderWidget* RenderTab::get_render_widget() const\n{\n return m_render_widget;\n}\n\nRenderTab::State RenderTab::save_state() const\n{\n State state;\n state.m_zoom_handler_state = m_zoom_handler->save_state();\n state.m_pan_handler_state = m_pan_handler->save_state();\n return state;\n}\n\nvoid RenderTab::load_state(const State& state)\n{\n \/\/ The order matters here.\n m_zoom_handler->load_state(state.m_zoom_handler_state);\n m_pan_handler->load_state(state.m_pan_handler_state);\n}\n\nvoid RenderTab::slot_render_widget_context_menu(const QPoint& point)\n{\n emit signal_render_widget_context_menu(m_render_widget->mapToGlobal(point));\n}\n\nvoid RenderTab::slot_toggle_render_region(const bool checked)\n{\n m_picking_handler->set_enabled(!checked);\n m_render_region_handler->set_enabled(checked);\n}\n\nvoid RenderTab::slot_set_render_region(const QRect& rect)\n{\n m_set_render_region_button->setChecked(false);\n emit signal_set_render_region(rect);\n}\n\nvoid RenderTab::create_render_widget()\n{\n const CanvasProperties& props = m_project.get_frame()->image().properties();\n\n m_render_widget =\n new RenderWidget(\n props.m_canvas_width,\n props.m_canvas_height);\n\n m_render_widget->setContextMenuPolicy(Qt::CustomContextMenu);\n\n connect(\n m_render_widget, SIGNAL(customContextMenuRequested(const QPoint&)),\n SLOT(slot_render_widget_context_menu(const QPoint&)));\n\n m_render_widget->setMouseTracking(true);\n}\n\nvoid RenderTab::create_toolbar()\n{\n \/\/ Create the render toolbar.\n m_toolbar = new QToolBar();\n m_toolbar->setObjectName(QString::fromUtf8(\"render_toolbar\"));\n m_toolbar->setIconSize(QSize(18, 18));\n\n \/\/ Create the Save Image button in the render toolbar.\n m_save_aovs_button = new QToolButton();\n m_save_aovs_button->setIcon(QIcon(\":\/icons\/save_image.png\"));\n m_save_aovs_button->setToolTip(\"Save All AOVs...\");\n connect(\n m_save_aovs_button, SIGNAL(clicked()),\n SIGNAL(signal_save_all_aovs()));\n m_toolbar->addWidget(m_save_aovs_button);\n\n \/\/ Create the Quick Save Image button in the render toolbar.\n m_quick_save_aovs_button = new QToolButton();\n m_quick_save_aovs_button->setIcon(QIcon(\":\/icons\/quick_save_aovs.png\"));\n m_quick_save_aovs_button->setToolTip(\"Quicksave All AOVs\");\n connect(\n m_quick_save_aovs_button, SIGNAL(clicked()),\n SIGNAL(signal_quicksave_all_aovs()));\n m_toolbar->addWidget(m_quick_save_aovs_button);\n\n m_toolbar->addSeparator();\n\n \/\/ Create the Set Render Region button in the render toolbar.\n m_set_render_region_button = new QToolButton();\n m_set_render_region_button->setIcon(QIcon(\":\/icons\/selection-blue.png\"));\n m_set_render_region_button->setToolTip(\"Set Render Region\");\n m_set_render_region_button->setShortcut(Qt::Key_R);\n m_set_render_region_button->setCheckable(true);\n connect(\n m_set_render_region_button, SIGNAL(toggled(bool)),\n SLOT(slot_toggle_render_region(const bool)));\n m_toolbar->addWidget(m_set_render_region_button);\n\n \/\/ Create the Clear Render Region button in the render toolbar.\n m_clear_render_region_button = new QToolButton();\n m_clear_render_region_button->setIcon(QIcon(\":\/icons\/selection-crossed.png\"));\n m_clear_render_region_button->setToolTip(\"Clear Render Region\");\n m_clear_render_region_button->setShortcut(Qt::Key_C);\n connect(\n m_clear_render_region_button, SIGNAL(clicked()),\n SIGNAL(signal_clear_render_region()));\n m_toolbar->addWidget(m_clear_render_region_button);\n\n m_toolbar->addSeparator();\n\n \/\/ Create the Reset Zoom button in the render toolbar.\n m_reset_zoom_button = new QToolButton();\n m_reset_zoom_button->setIcon(QIcon(\":\/icons\/reset_zoom.png\"));\n m_reset_zoom_button->setToolTip(\"Reset Zoom\");\n m_reset_zoom_button->setShortcut(Qt::Key_Asterisk);\n connect(\n m_reset_zoom_button, SIGNAL(clicked()),\n SIGNAL(signal_reset_zoom()));\n m_toolbar->addWidget(m_reset_zoom_button);\n\n m_toolbar->addSeparator();\n\n \/\/ Create the label preceding the picking mode combobox.\n QLabel* picking_mode_label = new QLabel(\"Picking Mode:\");\n picking_mode_label->setObjectName(QString::fromUtf8(\"picking_mode_label\"));\n m_toolbar->addWidget(picking_mode_label);\n\n \/\/ Create the picking mode combobox.\n \/\/ The combo will be populated by the ScenePickingHandler instantiated below.\n m_picking_mode_combo = new QComboBox();\n m_picking_mode_combo->setObjectName(QString::fromUtf8(\"picking_mode_combo\"));\n m_toolbar->addWidget(m_picking_mode_combo);\n\n m_toolbar->addSeparator();\n\n \/\/ Create a label to display various information such as mouse coordinates, etc.\n m_info_label = new QLabel();\n m_info_label->setScaledContents(true);\n m_info_label->setObjectName(QString::fromUtf8(\"info_label\"));\n m_toolbar->addWidget(m_info_label);\n\n m_toolbar->addSeparator();\n\n m_rgb_text = new QTextEdit();\n m_rgb_text->setObjectName(QString::fromUtf8(\"rgb_text\"));\n m_rgb_text->setReadOnly(true);\n m_rgb_text->setMaximumHeight(18);\n m_toolbar->addWidget(m_rgb_text);\n\t\n\t\n}\n\nvoid RenderTab::create_scrollarea()\n{\n \/\/ Encapsulate the render widget into another widget that adds a margin around it.\n QWidget* render_widget_wrapper = new QWidget();\n render_widget_wrapper->setObjectName(QString::fromUtf8(\"render_widget_wrapper\"));\n render_widget_wrapper->setLayout(new QGridLayout());\n render_widget_wrapper->layout()->setSizeConstraint(QLayout::SetFixedSize);\n render_widget_wrapper->layout()->setContentsMargins(20, 20, 20, 20);\n render_widget_wrapper->layout()->addWidget(m_render_widget);\n\n \/\/ Wrap the render widget in a scroll area.\n m_scroll_area = new QScrollArea();\n m_scroll_area->setObjectName(QString::fromUtf8(\"render_widget_scrollarea\"));\n m_scroll_area->setAlignment(Qt::AlignCenter);\n m_scroll_area->setWidget(render_widget_wrapper);\n}\n\nvoid RenderTab::recreate_handlers()\n{\n \/\/ Handler to handle zooming the render widget in and out with the keyboard or the mouse wheel.\n m_zoom_handler.reset(\n new WidgetZoomHandler(\n m_scroll_area,\n m_render_widget));\n\n \/\/ Handler for camera panning with the mouse.\n m_pan_handler.reset(\n new ScrollAreaPanHandler(\n m_scroll_area));\n\n \/\/ Handler for camera tracking with the mouse.\n m_mouse_tracker.reset(\n new MouseCoordinatesTracker(\n m_render_widget,\n m_info_label,\n m_rgb_text));\n\n \/\/ Handler for picking scene entities in the render widget.\n m_picking_handler.reset(\n new ScenePickingHandler(\n m_render_widget,\n m_picking_mode_combo,\n *m_mouse_tracker.get(),\n m_project_explorer,\n m_project));\n\n \/\/ Handler for defining render regions with the mouse.\n m_render_region_handler.reset(\n new RenderRegionHandler(\n m_render_widget,\n *m_mouse_tracker.get()));\n connect(\n m_render_region_handler.get(), SIGNAL(signal_render_region(const QRect&)),\n SLOT(slot_set_render_region(const QRect&)));\n\n \/\/ Clipboard handler.\n m_clipboard_handler.reset(new RenderClipboardHandler(m_render_widget));\n\n \/\/ Initially, the picking handler is active and the render region is inactive.\n m_picking_handler->set_enabled(true);\n m_render_region_handler->set_enabled(false);\n}\n\n} \/\/ namespace studio\n} \/\/ namespace appleseed\n\n#include \"mainwindow\/rendering\/moc_cpp_rendertab.cxx\"\nremoved tabs\n\/\/\n\/\/ This source file is part of appleseed.\n\/\/ Visit http:\/\/appleseedhq.net\/ for additional information and resources.\n\/\/\n\/\/ This software is released under the MIT license.\n\/\/\n\/\/ Copyright (c) 2010-2013 Francois Beaune, Jupiter Jazz Limited\n\/\/ Copyright (c) 2014 Francois Beaune, The appleseedhq Organization\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n\/\/ THE SOFTWARE.\n\/\/\n\n\/\/ Interface header.\n#include \"rendertab.h\"\n\n\/\/ appleseed.studio headers.\n#include \"mainwindow\/rendering\/renderwidget.h\"\n\n\/\/ appleseed.renderer headers.\n#include \"renderer\/api\/frame.h\"\n#include \"renderer\/api\/project.h\"\n\n\/\/ appleseed.foundation headers.\n#include \"foundation\/image\/canvasproperties.h\"\n#include \"foundation\/image\/color.h\"\n#include \"foundation\/image\/image.h\"\n\n\/\/ Qt headers.\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace foundation;\nusing namespace renderer;\n\nnamespace appleseed {\nnamespace studio {\n\n\/\/\n\/\/ RenderTab class implementation.\n\/\/\n\nRenderTab::RenderTab(\n ProjectExplorer& project_explorer,\n Project& project)\n : m_project_explorer(project_explorer)\n , m_project(project)\n{\n create_render_widget();\n create_toolbar();\n create_scrollarea();\n\n setObjectName(QString::fromUtf8(\"render_widget_tab\"));\n setLayout(new QGridLayout());\n layout()->setSpacing(0);\n layout()->setMargin(0);\n layout()->addWidget(m_toolbar);\n layout()->addWidget(m_scroll_area);\n\n recreate_handlers();\n}\n\nvoid RenderTab::clear()\n{\n m_render_widget->clear(Color4f(0.0f));\n}\n\nvoid RenderTab::darken()\n{\n m_render_widget->multiply(0.2f);\n}\n\nvoid RenderTab::reset_zoom()\n{\n m_zoom_handler->reset_zoom();\n}\n\nvoid RenderTab::update()\n{\n m_render_widget->update();\n}\n\nvoid RenderTab::update_size()\n{\n m_set_render_region_button->setChecked(false);\n\n const CanvasProperties& props = m_project.get_frame()->image().properties();\n\n m_render_widget->resize(\n props.m_canvas_width,\n props.m_canvas_height);\n\n recreate_handlers();\n}\n\nRenderWidget* RenderTab::get_render_widget() const\n{\n return m_render_widget;\n}\n\nRenderTab::State RenderTab::save_state() const\n{\n State state;\n state.m_zoom_handler_state = m_zoom_handler->save_state();\n state.m_pan_handler_state = m_pan_handler->save_state();\n return state;\n}\n\nvoid RenderTab::load_state(const State& state)\n{\n \/\/ The order matters here.\n m_zoom_handler->load_state(state.m_zoom_handler_state);\n m_pan_handler->load_state(state.m_pan_handler_state);\n}\n\nvoid RenderTab::slot_render_widget_context_menu(const QPoint& point)\n{\n emit signal_render_widget_context_menu(m_render_widget->mapToGlobal(point));\n}\n\nvoid RenderTab::slot_toggle_render_region(const bool checked)\n{\n m_picking_handler->set_enabled(!checked);\n m_render_region_handler->set_enabled(checked);\n}\n\nvoid RenderTab::slot_set_render_region(const QRect& rect)\n{\n m_set_render_region_button->setChecked(false);\n emit signal_set_render_region(rect);\n}\n\nvoid RenderTab::create_render_widget()\n{\n const CanvasProperties& props = m_project.get_frame()->image().properties();\n\n m_render_widget =\n new RenderWidget(\n props.m_canvas_width,\n props.m_canvas_height);\n\n m_render_widget->setContextMenuPolicy(Qt::CustomContextMenu);\n\n connect(\n m_render_widget, SIGNAL(customContextMenuRequested(const QPoint&)),\n SLOT(slot_render_widget_context_menu(const QPoint&)));\n\n m_render_widget->setMouseTracking(true);\n}\n\nvoid RenderTab::create_toolbar()\n{\n \/\/ Create the render toolbar.\n m_toolbar = new QToolBar();\n m_toolbar->setObjectName(QString::fromUtf8(\"render_toolbar\"));\n m_toolbar->setIconSize(QSize(18, 18));\n\n \/\/ Create the Save Image button in the render toolbar.\n m_save_aovs_button = new QToolButton();\n m_save_aovs_button->setIcon(QIcon(\":\/icons\/save_image.png\"));\n m_save_aovs_button->setToolTip(\"Save All AOVs...\");\n connect(\n m_save_aovs_button, SIGNAL(clicked()),\n SIGNAL(signal_save_all_aovs()));\n m_toolbar->addWidget(m_save_aovs_button);\n\n \/\/ Create the Quick Save Image button in the render toolbar.\n m_quick_save_aovs_button = new QToolButton();\n m_quick_save_aovs_button->setIcon(QIcon(\":\/icons\/quick_save_aovs.png\"));\n m_quick_save_aovs_button->setToolTip(\"Quicksave All AOVs\");\n connect(\n m_quick_save_aovs_button, SIGNAL(clicked()),\n SIGNAL(signal_quicksave_all_aovs()));\n m_toolbar->addWidget(m_quick_save_aovs_button);\n\n m_toolbar->addSeparator();\n\n \/\/ Create the Set Render Region button in the render toolbar.\n m_set_render_region_button = new QToolButton();\n m_set_render_region_button->setIcon(QIcon(\":\/icons\/selection-blue.png\"));\n m_set_render_region_button->setToolTip(\"Set Render Region\");\n m_set_render_region_button->setShortcut(Qt::Key_R);\n m_set_render_region_button->setCheckable(true);\n connect(\n m_set_render_region_button, SIGNAL(toggled(bool)),\n SLOT(slot_toggle_render_region(const bool)));\n m_toolbar->addWidget(m_set_render_region_button);\n\n \/\/ Create the Clear Render Region button in the render toolbar.\n m_clear_render_region_button = new QToolButton();\n m_clear_render_region_button->setIcon(QIcon(\":\/icons\/selection-crossed.png\"));\n m_clear_render_region_button->setToolTip(\"Clear Render Region\");\n m_clear_render_region_button->setShortcut(Qt::Key_C);\n connect(\n m_clear_render_region_button, SIGNAL(clicked()),\n SIGNAL(signal_clear_render_region()));\n m_toolbar->addWidget(m_clear_render_region_button);\n\n m_toolbar->addSeparator();\n\n \/\/ Create the Reset Zoom button in the render toolbar.\n m_reset_zoom_button = new QToolButton();\n m_reset_zoom_button->setIcon(QIcon(\":\/icons\/reset_zoom.png\"));\n m_reset_zoom_button->setToolTip(\"Reset Zoom\");\n m_reset_zoom_button->setShortcut(Qt::Key_Asterisk);\n connect(\n m_reset_zoom_button, SIGNAL(clicked()),\n SIGNAL(signal_reset_zoom()));\n m_toolbar->addWidget(m_reset_zoom_button);\n\n m_toolbar->addSeparator();\n\n \/\/ Create the label preceding the picking mode combobox.\n QLabel* picking_mode_label = new QLabel(\"Picking Mode:\");\n picking_mode_label->setObjectName(QString::fromUtf8(\"picking_mode_label\"));\n m_toolbar->addWidget(picking_mode_label);\n\n \/\/ Create the picking mode combobox.\n \/\/ The combo will be populated by the ScenePickingHandler instantiated below.\n m_picking_mode_combo = new QComboBox();\n m_picking_mode_combo->setObjectName(QString::fromUtf8(\"picking_mode_combo\"));\n m_toolbar->addWidget(m_picking_mode_combo);\n\n m_toolbar->addSeparator();\n\n \/\/ Create a label to display various information such as mouse coordinates, etc.\n m_info_label = new QLabel();\n m_info_label->setScaledContents(true);\n m_info_label->setObjectName(QString::fromUtf8(\"info_label\"));\n m_toolbar->addWidget(m_info_label);\n\n m_toolbar->addSeparator();\n\n m_rgb_text = new QTextEdit();\n m_rgb_text->setObjectName(QString::fromUtf8(\"rgb_text\"));\n m_rgb_text->setReadOnly(true);\n m_rgb_text->setMaximumHeight(18);\n m_toolbar->addWidget(m_rgb_text);\n}\n\nvoid RenderTab::create_scrollarea()\n{\n \/\/ Encapsulate the render widget into another widget that adds a margin around it.\n QWidget* render_widget_wrapper = new QWidget();\n render_widget_wrapper->setObjectName(QString::fromUtf8(\"render_widget_wrapper\"));\n render_widget_wrapper->setLayout(new QGridLayout());\n render_widget_wrapper->layout()->setSizeConstraint(QLayout::SetFixedSize);\n render_widget_wrapper->layout()->setContentsMargins(20, 20, 20, 20);\n render_widget_wrapper->layout()->addWidget(m_render_widget);\n\n \/\/ Wrap the render widget in a scroll area.\n m_scroll_area = new QScrollArea();\n m_scroll_area->setObjectName(QString::fromUtf8(\"render_widget_scrollarea\"));\n m_scroll_area->setAlignment(Qt::AlignCenter);\n m_scroll_area->setWidget(render_widget_wrapper);\n}\n\nvoid RenderTab::recreate_handlers()\n{\n \/\/ Handler to handle zooming the render widget in and out with the keyboard or the mouse wheel.\n m_zoom_handler.reset(\n new WidgetZoomHandler(\n m_scroll_area,\n m_render_widget));\n\n \/\/ Handler for camera panning with the mouse.\n m_pan_handler.reset(\n new ScrollAreaPanHandler(\n m_scroll_area));\n\n \/\/ Handler for camera tracking with the mouse.\n m_mouse_tracker.reset(\n new MouseCoordinatesTracker(\n m_render_widget,\n m_info_label,\n m_rgb_text));\n\n \/\/ Handler for picking scene entities in the render widget.\n m_picking_handler.reset(\n new ScenePickingHandler(\n m_render_widget,\n m_picking_mode_combo,\n *m_mouse_tracker.get(),\n m_project_explorer,\n m_project));\n\n \/\/ Handler for defining render regions with the mouse.\n m_render_region_handler.reset(\n new RenderRegionHandler(\n m_render_widget,\n *m_mouse_tracker.get()));\n connect(\n m_render_region_handler.get(), SIGNAL(signal_render_region(const QRect&)),\n SLOT(slot_set_render_region(const QRect&)));\n\n \/\/ Clipboard handler.\n m_clipboard_handler.reset(new RenderClipboardHandler(m_render_widget));\n\n \/\/ Initially, the picking handler is active and the render region is inactive.\n m_picking_handler->set_enabled(true);\n m_render_region_handler->set_enabled(false);\n}\n\n} \/\/ namespace studio\n} \/\/ namespace appleseed\n\n#include \"mainwindow\/rendering\/moc_cpp_rendertab.cxx\"\n<|endoftext|>"} {"text":"\n\/\/\n\/\/ This source file is part of appleseed.\n\/\/ Visit http:\/\/appleseedhq.net\/ for additional information and resources.\n\/\/\n\/\/ This software is released under the MIT license.\n\/\/\n\/\/ Copyright (c) 2015 Francois Beaune, The appleseedhq Organization\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n\/\/ THE SOFTWARE.\n\/\/\n\n\/\/ Interface header.\n#include \"dipolebssrdf.h\"\n\n\/\/ appleseed.renderer headers.\n#include \"renderer\/modeling\/bssrdf\/bssrdfsample.h\"\n#include \"renderer\/modeling\/bssrdf\/sss.h\"\n#include \"renderer\/modeling\/input\/inputevaluator.h\"\n\n\/\/ appleseed.foundation headers.\n#include \"foundation\/math\/scalar.h\"\n#include \"foundation\/math\/vector.h\"\n#include \"foundation\/utility\/containers\/dictionary.h\"\n#include \"foundation\/utility\/containers\/specializedarrays.h\"\n#include \"foundation\/utility\/memory.h\"\n\n\/\/ Standard headers.\n#include \n#include \n\nusing namespace foundation;\nusing namespace std;\n\nnamespace renderer\n{\n\n\/\/\n\/\/ DipoleBSSRDF class implementation.\n\/\/\n\nDipoleBSSRDF::DipoleBSSRDF(\n const char* name,\n const ParamArray& params)\n : BSSRDF(name, params)\n{\n m_inputs.declare(\"weight\", InputFormatScalar, \"1.0\");\n m_inputs.declare(\"reflectance\", InputFormatSpectralReflectance);\n m_inputs.declare(\"reflectance_multiplier\", InputFormatScalar, \"1.0\");\n m_inputs.declare(\"dmfp\", InputFormatScalar, \"5.0\");\n m_inputs.declare(\"dmfp_multiplier\", InputFormatScalar, \"0.1\");\n m_inputs.declare(\"anisotropy\", InputFormatScalar);\n m_inputs.declare(\"outside_ior\", InputFormatScalar);\n m_inputs.declare(\"inside_ior\", InputFormatScalar);\n}\n\nsize_t DipoleBSSRDF::compute_input_data_size(\n const Assembly& assembly) const\n{\n return align(sizeof(DipoleBSSRDFInputValues), 16);\n}\n\nvoid DipoleBSSRDF::evaluate_inputs(\n const ShadingContext& shading_context,\n InputEvaluator& input_evaluator,\n const ShadingPoint& shading_point,\n const size_t offset) const\n{\n BSSRDF::evaluate_inputs(shading_context, input_evaluator, shading_point, offset);\n\n DipoleBSSRDFInputValues* values =\n reinterpret_cast(input_evaluator.data() + offset);\n\n \/\/ Apply multipliers.\n values->m_reflectance *= static_cast(values->m_reflectance_multiplier);\n values->m_dmfp *= values->m_dmfp_multiplier;\n\n \/\/ Clamp reflectance to [0, 1].\n values->m_reflectance = saturate(values->m_reflectance);\n\n#if 1\n \/\/ Compute sigma_a and sigma_s from the reflectance and dmfp parameters.\n compute_absorption_and_scattering(\n values->m_reflectance,\n values->m_dmfp,\n values->m_inside_ior \/ values->m_outside_ior,\n values->m_anisotropy,\n values->m_sigma_a,\n values->m_sigma_s);\n#else\n \/\/ Skim milk.\n values->m_sigma_a = Color3f(0.0014f, 0.0025f, 0.0142f) * 1000.0f;\n values->m_sigma_s = Color3f(0.70f, 1.22f, 1.90f) * 1000.0f;\n values->m_anisotropy = 0.0;\n\n \/\/ TODO: compute dmfp here!\n \/*\n effective_extinction_coefficient(\n values->m_sigma_a,\n values->m_sigma_s,\n values->m_anisotropy,\n values->m_sigma_tr);\n *\/\n#endif\n\n values->m_max_radius2 = square(dipole_max_radius(1.0 \/ values->m_dmfp));\n}\n\nbool DipoleBSSRDF::sample(\n const void* data,\n BSSRDFSample& sample) const\n{\n const DipoleBSSRDFInputValues* values =\n reinterpret_cast(data);\n\n if (values->m_weight == 0.0)\n return false;\n\n sample.set_eta(values->m_inside_ior \/ values->m_outside_ior);\n\n \/\/ Select the channel leading to the strongest scattering.\n const size_t channel = min_index(values->m_reflectance);\n sample.set_channel(channel);\n\n \/\/ todo: fix.\n const double reflectance = values->m_reflectance[channel];\n if (reflectance == 0.0)\n return false;\n\n sample.get_sampling_context().split_in_place(2, 1);\n const Vector2d s = sample.get_sampling_context().next_vector2<2>();\n\n \/\/ Sample a radius.\n const double sigma_tr = 1.0 \/ values->m_dmfp;\n const double radius = dipole_sample(sigma_tr, s[0]);\n\n \/\/ Set the max radius.\n sample.set_rmax2(values->m_max_radius2);\n\n \/\/ Sample an angle.\n const double phi = TwoPi * s[1];\n\n \/\/ Set the sampled point.\n sample.set_point(Vector2d(radius * cos(phi), radius * sin(phi)));\n\n return true;\n}\n\ndouble DipoleBSSRDF::evaluate_pdf(\n const void* data,\n const size_t channel,\n const double radius) const\n{\n const DipoleBSSRDFInputValues* values =\n reinterpret_cast(data);\n\n const double reflectance = values->m_reflectance[channel];\n if (reflectance == 0.0)\n return 0.0;\n\n \/\/ PDF of the sampled radius.\n const double sigma_tr = 1.0 \/ values->m_dmfp;\n const double pdf_radius = dipole_pdf(radius, sigma_tr);\n\n \/\/ PDF of the sampled angle.\n const double pdf_angle = RcpTwoPi;\n\n \/\/ Compute and return the final PDF.\n return pdf_radius * pdf_angle;\n}\n\n\n\/\/\n\/\/ DipoleBSSRDFFactory class implementation.\n\/\/\n\nDictionaryArray DipoleBSSRDFFactory::get_input_metadata() const\n{\n DictionaryArray metadata;\n\n metadata.push_back(\n Dictionary()\n .insert(\"name\", \"weight\")\n .insert(\"label\", \"Weight\")\n .insert(\"type\", \"colormap\")\n .insert(\"entity_types\",\n Dictionary().insert(\"texture_instance\", \"Textures\"))\n .insert(\"use\", \"optional\")\n .insert(\"default\", \"1.0\"));\n\n metadata.push_back(\n Dictionary()\n .insert(\"name\", \"reflectance\")\n .insert(\"label\", \"Diffuse Surface Reflectance\")\n .insert(\"type\", \"colormap\")\n .insert(\"entity_types\",\n Dictionary()\n .insert(\"color\", \"Colors\")\n .insert(\"texture_instance\", \"Textures\"))\n .insert(\"use\", \"required\")\n .insert(\"default\", \"0.5\"));\n\n metadata.push_back(\n Dictionary()\n .insert(\"name\", \"reflectance_multiplier\")\n .insert(\"label\", \"Diffuse Surface Reflectance Multiplier\")\n .insert(\"type\", \"colormap\")\n .insert(\"entity_types\",\n Dictionary().insert(\"texture_instance\", \"Textures\"))\n .insert(\"use\", \"optional\")\n .insert(\"default\", \"1.0\"));\n\n metadata.push_back(\n Dictionary()\n .insert(\"name\", \"dmfp\")\n .insert(\"label\", \"Diffuse Mean Free Path\")\n .insert(\"type\", \"colormap\")\n .insert(\"entity_types\",\n Dictionary()\n .insert(\"texture_instance\", \"Textures\"))\n .insert(\"use\", \"required\")\n .insert(\"default\", \"5\"));\n\n metadata.push_back(\n Dictionary()\n .insert(\"name\", \"dmfp_multiplier\")\n .insert(\"label\", \"Diffuse Mean Free Path Multiplier\")\n .insert(\"type\", \"colormap\")\n .insert(\"entity_types\",\n Dictionary().insert(\"texture_instance\", \"Textures\"))\n .insert(\"use\", \"optional\")\n .insert(\"default\", \"0.1\"));\n\n metadata.push_back(\n Dictionary()\n .insert(\"name\", \"anisotropy\")\n .insert(\"label\", \"Anisotropy\")\n .insert(\"type\", \"numeric\")\n .insert(\"min_value\", \"-1.0\")\n .insert(\"max_value\", \"1.0\")\n .insert(\"use\", \"required\")\n .insert(\"default\", \"0.0\"));\n\n metadata.push_back(\n Dictionary()\n .insert(\"name\", \"outside_ior\")\n .insert(\"label\", \"Outside Index of Refraction\")\n .insert(\"type\", \"numeric\")\n .insert(\"min_value\", \"0.0\")\n .insert(\"max_value\", \"5.0\")\n .insert(\"use\", \"required\")\n .insert(\"default\", \"1.0\"));\n\n metadata.push_back(\n Dictionary()\n .insert(\"name\", \"inside_ior\")\n .insert(\"label\", \"Inside Index of Refraction\")\n .insert(\"type\", \"numeric\")\n .insert(\"min_value\", \"0.0\")\n .insert(\"max_value\", \"5.0\")\n .insert(\"use\", \"required\")\n .insert(\"default\", \"1.3\"));\n\n return metadata;\n}\n\n} \/\/ namespace renderer\nNo need to sample a channel for dipole BSSRDFs\n\/\/\n\/\/ This source file is part of appleseed.\n\/\/ Visit http:\/\/appleseedhq.net\/ for additional information and resources.\n\/\/\n\/\/ This software is released under the MIT license.\n\/\/\n\/\/ Copyright (c) 2015 Francois Beaune, The appleseedhq Organization\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n\/\/ THE SOFTWARE.\n\/\/\n\n\/\/ Interface header.\n#include \"dipolebssrdf.h\"\n\n\/\/ appleseed.renderer headers.\n#include \"renderer\/modeling\/bssrdf\/bssrdfsample.h\"\n#include \"renderer\/modeling\/bssrdf\/sss.h\"\n#include \"renderer\/modeling\/input\/inputevaluator.h\"\n\n\/\/ appleseed.foundation headers.\n#include \"foundation\/math\/scalar.h\"\n#include \"foundation\/math\/vector.h\"\n#include \"foundation\/utility\/containers\/dictionary.h\"\n#include \"foundation\/utility\/containers\/specializedarrays.h\"\n#include \"foundation\/utility\/memory.h\"\n\n\/\/ Standard headers.\n#include \n#include \n\nusing namespace foundation;\nusing namespace std;\n\nnamespace renderer\n{\n\n\/\/\n\/\/ DipoleBSSRDF class implementation.\n\/\/\n\nDipoleBSSRDF::DipoleBSSRDF(\n const char* name,\n const ParamArray& params)\n : BSSRDF(name, params)\n{\n m_inputs.declare(\"weight\", InputFormatScalar, \"1.0\");\n m_inputs.declare(\"reflectance\", InputFormatSpectralReflectance);\n m_inputs.declare(\"reflectance_multiplier\", InputFormatScalar, \"1.0\");\n m_inputs.declare(\"dmfp\", InputFormatScalar, \"5.0\");\n m_inputs.declare(\"dmfp_multiplier\", InputFormatScalar, \"0.1\");\n m_inputs.declare(\"anisotropy\", InputFormatScalar);\n m_inputs.declare(\"outside_ior\", InputFormatScalar);\n m_inputs.declare(\"inside_ior\", InputFormatScalar);\n}\n\nsize_t DipoleBSSRDF::compute_input_data_size(\n const Assembly& assembly) const\n{\n return align(sizeof(DipoleBSSRDFInputValues), 16);\n}\n\nvoid DipoleBSSRDF::evaluate_inputs(\n const ShadingContext& shading_context,\n InputEvaluator& input_evaluator,\n const ShadingPoint& shading_point,\n const size_t offset) const\n{\n BSSRDF::evaluate_inputs(shading_context, input_evaluator, shading_point, offset);\n\n DipoleBSSRDFInputValues* values =\n reinterpret_cast(input_evaluator.data() + offset);\n\n \/\/ Apply multipliers.\n values->m_reflectance *= static_cast(values->m_reflectance_multiplier);\n values->m_dmfp *= values->m_dmfp_multiplier;\n\n \/\/ Clamp reflectance to [0.001, 1].\n values->m_reflectance = clamp(values->m_reflectance, 0.001f, 1.0f);\n\n#if 1\n \/\/ Compute sigma_a and sigma_s from the reflectance and dmfp parameters.\n compute_absorption_and_scattering(\n values->m_reflectance,\n values->m_dmfp,\n values->m_inside_ior \/ values->m_outside_ior,\n values->m_anisotropy,\n values->m_sigma_a,\n values->m_sigma_s);\n#else\n \/\/ Skim milk.\n values->m_sigma_a = Color3f(0.0014f, 0.0025f, 0.0142f) * 1000.0f;\n values->m_sigma_s = Color3f(0.70f, 1.22f, 1.90f) * 1000.0f;\n values->m_anisotropy = 0.0;\n\n \/\/ TODO: compute dmfp here!\n \/*\n effective_extinction_coefficient(\n values->m_sigma_a,\n values->m_sigma_s,\n values->m_anisotropy,\n values->m_sigma_tr);\n *\/\n#endif\n\n values->m_max_radius2 = square(dipole_max_radius(1.0 \/ values->m_dmfp));\n}\n\nbool DipoleBSSRDF::sample(\n const void* data,\n BSSRDFSample& sample) const\n{\n const DipoleBSSRDFInputValues* values =\n reinterpret_cast(data);\n\n if (values->m_weight == 0.0)\n return false;\n\n sample.set_eta(values->m_inside_ior \/ values->m_outside_ior);\n sample.set_channel(0);\n\n sample.get_sampling_context().split_in_place(2, 1);\n const Vector2d s = sample.get_sampling_context().next_vector2<2>();\n\n \/\/ Sample a radius.\n const double sigma_tr = 1.0 \/ values->m_dmfp;\n const double radius = dipole_sample(sigma_tr, s[0]);\n\n \/\/ Set the max radius.\n sample.set_rmax2(values->m_max_radius2);\n\n \/\/ Sample an angle.\n const double phi = TwoPi * s[1];\n\n \/\/ Set the sampled point.\n sample.set_point(Vector2d(radius * cos(phi), radius * sin(phi)));\n\n return true;\n}\n\ndouble DipoleBSSRDF::evaluate_pdf(\n const void* data,\n const size_t channel,\n const double radius) const\n{\n const DipoleBSSRDFInputValues* values =\n reinterpret_cast(data);\n\n const double reflectance = values->m_reflectance[channel];\n if (reflectance == 0.0)\n return 0.0;\n\n \/\/ PDF of the sampled radius.\n const double sigma_tr = 1.0 \/ values->m_dmfp;\n const double pdf_radius = dipole_pdf(radius, sigma_tr);\n\n \/\/ PDF of the sampled angle.\n const double pdf_angle = RcpTwoPi;\n\n \/\/ Compute and return the final PDF.\n return pdf_radius * pdf_angle;\n}\n\n\n\/\/\n\/\/ DipoleBSSRDFFactory class implementation.\n\/\/\n\nDictionaryArray DipoleBSSRDFFactory::get_input_metadata() const\n{\n DictionaryArray metadata;\n\n metadata.push_back(\n Dictionary()\n .insert(\"name\", \"weight\")\n .insert(\"label\", \"Weight\")\n .insert(\"type\", \"colormap\")\n .insert(\"entity_types\",\n Dictionary().insert(\"texture_instance\", \"Textures\"))\n .insert(\"use\", \"optional\")\n .insert(\"default\", \"1.0\"));\n\n metadata.push_back(\n Dictionary()\n .insert(\"name\", \"reflectance\")\n .insert(\"label\", \"Diffuse Surface Reflectance\")\n .insert(\"type\", \"colormap\")\n .insert(\"entity_types\",\n Dictionary()\n .insert(\"color\", \"Colors\")\n .insert(\"texture_instance\", \"Textures\"))\n .insert(\"use\", \"required\")\n .insert(\"default\", \"0.5\"));\n\n metadata.push_back(\n Dictionary()\n .insert(\"name\", \"reflectance_multiplier\")\n .insert(\"label\", \"Diffuse Surface Reflectance Multiplier\")\n .insert(\"type\", \"colormap\")\n .insert(\"entity_types\",\n Dictionary().insert(\"texture_instance\", \"Textures\"))\n .insert(\"use\", \"optional\")\n .insert(\"default\", \"1.0\"));\n\n metadata.push_back(\n Dictionary()\n .insert(\"name\", \"dmfp\")\n .insert(\"label\", \"Diffuse Mean Free Path\")\n .insert(\"type\", \"colormap\")\n .insert(\"entity_types\",\n Dictionary()\n .insert(\"texture_instance\", \"Textures\"))\n .insert(\"use\", \"required\")\n .insert(\"default\", \"5\"));\n\n metadata.push_back(\n Dictionary()\n .insert(\"name\", \"dmfp_multiplier\")\n .insert(\"label\", \"Diffuse Mean Free Path Multiplier\")\n .insert(\"type\", \"colormap\")\n .insert(\"entity_types\",\n Dictionary().insert(\"texture_instance\", \"Textures\"))\n .insert(\"use\", \"optional\")\n .insert(\"default\", \"0.1\"));\n\n metadata.push_back(\n Dictionary()\n .insert(\"name\", \"anisotropy\")\n .insert(\"label\", \"Anisotropy\")\n .insert(\"type\", \"numeric\")\n .insert(\"min_value\", \"-1.0\")\n .insert(\"max_value\", \"1.0\")\n .insert(\"use\", \"required\")\n .insert(\"default\", \"0.0\"));\n\n metadata.push_back(\n Dictionary()\n .insert(\"name\", \"outside_ior\")\n .insert(\"label\", \"Outside Index of Refraction\")\n .insert(\"type\", \"numeric\")\n .insert(\"min_value\", \"0.0\")\n .insert(\"max_value\", \"5.0\")\n .insert(\"use\", \"required\")\n .insert(\"default\", \"1.0\"));\n\n metadata.push_back(\n Dictionary()\n .insert(\"name\", \"inside_ior\")\n .insert(\"label\", \"Inside Index of Refraction\")\n .insert(\"type\", \"numeric\")\n .insert(\"min_value\", \"0.0\")\n .insert(\"max_value\", \"5.0\")\n .insert(\"use\", \"required\")\n .insert(\"default\", \"1.3\"));\n\n return metadata;\n}\n\n} \/\/ namespace renderer\n<|endoftext|>"} {"text":"\/*\n *\n * Copyright (c) 2020 Project CHIP Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \n\n#include \n\n#if CONFIG_DEVICE_LAYER\n#include \n#endif\n\n#if CHIP_ENABLE_OPENTHREAD\n\n#include \n\n#include \n#include \n#include \n#include \n#include \n\n#if CHIP_TARGET_STYLE_EMBEDDED\n#include \n#include \n#include \n#include \n#include \n#if OPENTHREAD_API_VERSION >= 85\n#ifndef SHELL_OTCLI_TX_BUFFER_SIZE\n#define SHELL_OTCLI_TX_BUFFER_SIZE 1024\n#endif\nstatic char sTxBuffer[SHELL_OTCLI_TX_BUFFER_SIZE];\nstatic constexpr uint16_t sTxLength = SHELL_OTCLI_TX_BUFFER_SIZE;\n#endif\n#else\n#include \n#include \n#include \n#endif\n\nusing namespace chip;\nusing namespace chip::Shell;\nusing namespace chip::Platform;\nusing namespace chip::DeviceLayer;\nusing namespace chip::Logging;\nusing namespace chip::ArgParser;\n\nstatic chip::Shell::Engine sShellOtcliSubcommands;\n\nCHIP_ERROR cmd_otcli_help_iterator(shell_command_t * command, void * arg)\n{\n streamer_printf(streamer_get(), \" %-15s %s\\n\\r\", command->cmd_name, command->cmd_help);\n return CHIP_NO_ERROR;\n}\n\nCHIP_ERROR cmd_otcli_help(int argc, char ** argv)\n{\n sShellOtcliSubcommands.ForEachCommand(cmd_otcli_help_iterator, nullptr);\n return CHIP_NO_ERROR;\n}\n\n#if CHIP_TARGET_STYLE_EMBEDDED\n\nCHIP_ERROR cmd_otcli_dispatch(int argc, char ** argv)\n{\n CHIP_ERROR error = CHIP_NO_ERROR;\n\n\/\/ From OT CLI internal lib, kMaxLineLength = 128\n#define kMaxLineLength 128\n char buff[kMaxLineLength] = { 0 };\n char * buff_ptr = buff;\n int i = 0;\n\n VerifyOrExit(argc > 0, error = CHIP_ERROR_INVALID_ARGUMENT);\n\n for (i = 0; i < argc; i++)\n {\n size_t arg_len = strlen(argv[i]);\n\n \/* Make sure that the next argument won't overflow the buffer *\/\n VerifyOrExit(buff_ptr + arg_len < buff + kMaxLineLength, error = CHIP_ERROR_BUFFER_TOO_SMALL);\n\n strncpy(buff_ptr, argv[i], arg_len);\n buff_ptr += arg_len;\n\n \/* Make sure that there is enough buffer for a space char *\/\n if (buff_ptr + sizeof(char) < buff + kMaxLineLength)\n {\n strncpy(buff_ptr, \" \", sizeof(char));\n buff_ptr++;\n }\n }\n buff_ptr = 0;\n#if OPENTHREAD_API_VERSION >= 85\n otCliInputLine(buff);\n#else\n otCliConsoleInputLine(buff, buff_ptr - buff);\n#endif\nexit:\n return error;\n}\n\n#elif CHIP_TARGET_STYLE_UNIX\n\nCHIP_ERROR cmd_otcli_dispatch(int argc, char ** argv)\n{\n int pid;\n uid_t euid = geteuid();\n char ctl_command[] = \"\/usr\/local\/sbin\/ot-ctl\";\n\n \/\/ Must run as sudo.\n if (euid != 0)\n {\n streamer_printf(streamer_get(), \"Error otcli: requires running chip-shell as sudo\\n\\r\");\n return CHIP_ERROR_INCORRECT_STATE;\n }\n\n VerifyOrReturnError(argc > 0, CHIP_ERROR_INVALID_ARGUMENT);\n\n \/\/ Fork and execute the command.\n pid = fork();\n VerifyOrReturnError(pid != -1, CHIP_ERROR_INCORRECT_STATE);\n\n if (pid == 0)\n {\n \/\/ Child process to execute the command with provided arguments\n --argv; \/\/ Restore access to entry [0] containing the command;\n argv[0] = ctl_command;\n if (execvp(ctl_command, argv) < 0)\n {\n streamer_printf(streamer_get(), \"Error exec %s: %s\\n\", ctl_command, strerror(errno));\n }\n exit(errno);\n }\n else\n {\n \/\/ Parent process to wait on child.\n int status;\n wait(&status);\n return (status) ? CHIP_ERROR_INCORRECT_STATE : CHIP_NO_ERROR;\n }\n}\n\n#endif \/\/ CHIP_TARGET_STYLE_UNIX\n\nstatic const shell_command_t cmds_otcli_root = { &cmd_otcli_dispatch, \"otcli\", \"Dispatch OpenThread CLI command\" };\n\n#if CHIP_TARGET_STYLE_EMBEDDED\n#if OPENTHREAD_API_VERSION >= 85\nstatic int OnOtCliOutput(void * aContext, const char * aFormat, va_list aArguments)\n{\n int rval = vsnprintf(sTxBuffer, sTxLength, aFormat, aArguments);\n VerifyOrExit(rval >= 0 && rval < sTxLength, rval = CHIP_ERROR_BUFFER_TOO_SMALL.AsInteger());\n return streamer_write(streamer_get(), (const char *) sTxBuffer, rval);\nexit:\n return rval;\n}\n#else\nstatic int OnOtCliOutput(const char * aBuf, uint16_t aBufLength, void * aContext)\n{\n return streamer_write(streamer_get(), aBuf, aBufLength);\n}\n#endif\n#endif\n\n#endif \/\/ CHIP_ENABLE_OPENTHREAD\n\nvoid cmd_otcli_init()\n{\n#if CHIP_ENABLE_OPENTHREAD\n#if CHIP_TARGET_STYLE_EMBEDDED\n#if OPENTHREAD_API_VERSION >= 85\n otCliInit(otInstanceInitSingle(), &OnOtCliOutput, NULL);\n#else\n otCliConsoleInit(otInstanceInitSingle(), &OnOtCliOutput, NULL);\n#endif\n#endif\n\n \/\/ Register the root otcli command with the top-level shell.\n Engine::Root().RegisterCommands(&cmds_otcli_root, 1);\n#endif \/\/ CHIP_ENABLE_OPENTHREAD\n}\ncli: lock Thread stack when calling OpenThread API (#13806)\/*\n *\n * Copyright (c) 2020 Project CHIP Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \n\n#include \n\n#if CONFIG_DEVICE_LAYER\n#include \n#endif\n\n#if CHIP_ENABLE_OPENTHREAD\n\n#include \n\n#include \n#include \n#include \n#include \n#include \n\n#if CHIP_TARGET_STYLE_EMBEDDED\n#include \n#include \n#include \n#include \n#include \n#if OPENTHREAD_API_VERSION >= 85\n#ifndef SHELL_OTCLI_TX_BUFFER_SIZE\n#define SHELL_OTCLI_TX_BUFFER_SIZE 1024\n#endif\nstatic char sTxBuffer[SHELL_OTCLI_TX_BUFFER_SIZE];\nstatic constexpr uint16_t sTxLength = SHELL_OTCLI_TX_BUFFER_SIZE;\n#endif\n#else\n#include \n#include \n#include \n#endif\n\nusing namespace chip;\nusing namespace chip::Shell;\nusing namespace chip::Platform;\nusing namespace chip::DeviceLayer;\nusing namespace chip::Logging;\nusing namespace chip::ArgParser;\n\nstatic chip::Shell::Engine sShellOtcliSubcommands;\n\nCHIP_ERROR cmd_otcli_help_iterator(shell_command_t * command, void * arg)\n{\n streamer_printf(streamer_get(), \" %-15s %s\\n\\r\", command->cmd_name, command->cmd_help);\n return CHIP_NO_ERROR;\n}\n\nCHIP_ERROR cmd_otcli_help(int argc, char ** argv)\n{\n sShellOtcliSubcommands.ForEachCommand(cmd_otcli_help_iterator, nullptr);\n return CHIP_NO_ERROR;\n}\n\n#if CHIP_TARGET_STYLE_EMBEDDED\n\nCHIP_ERROR cmd_otcli_dispatch(int argc, char ** argv)\n{\n CHIP_ERROR error = CHIP_NO_ERROR;\n\n\/\/ From OT CLI internal lib, kMaxLineLength = 128\n#define kMaxLineLength 128\n char buff[kMaxLineLength] = { 0 };\n char * buff_ptr = buff;\n int i = 0;\n\n VerifyOrExit(argc > 0, error = CHIP_ERROR_INVALID_ARGUMENT);\n\n for (i = 0; i < argc; i++)\n {\n size_t arg_len = strlen(argv[i]);\n\n \/* Make sure that the next argument won't overflow the buffer *\/\n VerifyOrExit(buff_ptr + arg_len < buff + kMaxLineLength, error = CHIP_ERROR_BUFFER_TOO_SMALL);\n\n strncpy(buff_ptr, argv[i], arg_len);\n buff_ptr += arg_len;\n\n \/* Make sure that there is enough buffer for a space char *\/\n if (buff_ptr + sizeof(char) < buff + kMaxLineLength)\n {\n strncpy(buff_ptr, \" \", sizeof(char));\n buff_ptr++;\n }\n }\n buff_ptr = 0;\n chip::DeviceLayer::ThreadStackMgr().LockThreadStack();\n#if OPENTHREAD_API_VERSION >= 85\n otCliInputLine(buff);\n#else\n otCliConsoleInputLine(buff, buff_ptr - buff);\n#endif\n chip::DeviceLayer::ThreadStackMgr().UnlockThreadStack();\nexit:\n return error;\n}\n\n#elif CHIP_TARGET_STYLE_UNIX\n\nCHIP_ERROR cmd_otcli_dispatch(int argc, char ** argv)\n{\n int pid;\n uid_t euid = geteuid();\n char ctl_command[] = \"\/usr\/local\/sbin\/ot-ctl\";\n\n \/\/ Must run as sudo.\n if (euid != 0)\n {\n streamer_printf(streamer_get(), \"Error otcli: requires running chip-shell as sudo\\n\\r\");\n return CHIP_ERROR_INCORRECT_STATE;\n }\n\n VerifyOrReturnError(argc > 0, CHIP_ERROR_INVALID_ARGUMENT);\n\n \/\/ Fork and execute the command.\n pid = fork();\n VerifyOrReturnError(pid != -1, CHIP_ERROR_INCORRECT_STATE);\n\n if (pid == 0)\n {\n \/\/ Child process to execute the command with provided arguments\n --argv; \/\/ Restore access to entry [0] containing the command;\n argv[0] = ctl_command;\n if (execvp(ctl_command, argv) < 0)\n {\n streamer_printf(streamer_get(), \"Error exec %s: %s\\n\", ctl_command, strerror(errno));\n }\n exit(errno);\n }\n else\n {\n \/\/ Parent process to wait on child.\n int status;\n wait(&status);\n return (status) ? CHIP_ERROR_INCORRECT_STATE : CHIP_NO_ERROR;\n }\n}\n\n#endif \/\/ CHIP_TARGET_STYLE_UNIX\n\nstatic const shell_command_t cmds_otcli_root = { &cmd_otcli_dispatch, \"otcli\", \"Dispatch OpenThread CLI command\" };\n\n#if CHIP_TARGET_STYLE_EMBEDDED\n#if OPENTHREAD_API_VERSION >= 85\nstatic int OnOtCliOutput(void * aContext, const char * aFormat, va_list aArguments)\n{\n int rval = vsnprintf(sTxBuffer, sTxLength, aFormat, aArguments);\n VerifyOrExit(rval >= 0 && rval < sTxLength, rval = CHIP_ERROR_BUFFER_TOO_SMALL.AsInteger());\n return streamer_write(streamer_get(), (const char *) sTxBuffer, rval);\nexit:\n return rval;\n}\n#else\nstatic int OnOtCliOutput(const char * aBuf, uint16_t aBufLength, void * aContext)\n{\n return streamer_write(streamer_get(), aBuf, aBufLength);\n}\n#endif\n#endif\n\n#endif \/\/ CHIP_ENABLE_OPENTHREAD\n\nvoid cmd_otcli_init()\n{\n#if CHIP_ENABLE_OPENTHREAD\n#if CHIP_TARGET_STYLE_EMBEDDED\n#if OPENTHREAD_API_VERSION >= 85\n otCliInit(otInstanceInitSingle(), &OnOtCliOutput, NULL);\n#else\n otCliConsoleInit(otInstanceInitSingle(), &OnOtCliOutput, NULL);\n#endif\n#endif\n\n \/\/ Register the root otcli command with the top-level shell.\n Engine::Root().RegisterCommands(&cmds_otcli_root, 1);\n#endif \/\/ CHIP_ENABLE_OPENTHREAD\n}\n<|endoftext|>"} {"text":"\/* Copyright (c) MediaArea.net SARL. All Rights Reserved.\r\n *\r\n * Use of this source code is governed by a BSD-style license that can\r\n * be found in the License.html file in the root of the source tree.\r\n *\/\r\n\r\n\/\/---------------------------------------------------------------------------\r\n\/\/ Pre-compilation\r\n#include \"MediaInfo\/PreComp.h\"\r\n#ifdef __BORLANDC__\r\n #pragma hdrstop\r\n#endif\r\n\/\/---------------------------------------------------------------------------\r\n\r\n\/\/---------------------------------------------------------------------------\r\n#include \"MediaInfo\/Setup.h\"\r\n\/\/---------------------------------------------------------------------------\r\n\r\n\/\/---------------------------------------------------------------------------\r\n#if defined(MEDIAINFO_DCP_YES)\r\n\/\/---------------------------------------------------------------------------\r\n\r\n\/\/---------------------------------------------------------------------------\r\n#include \"MediaInfo\/Multiple\/File_DcpCpl.h\"\r\n#include \"MediaInfo\/MediaInfo.h\"\r\n#include \"MediaInfo\/MediaInfo_Internal.h\"\r\n#include \"MediaInfo\/Multiple\/File__ReferenceFilesHelper.h\"\r\n#include \"MediaInfo\/Multiple\/File_DcpPkl.h\"\r\n#include \"MediaInfo\/Multiple\/File_Mxf.h\"\r\n#include \"ZenLib\/Dir.h\"\r\n#include \"ZenLib\/FileName.h\"\r\n#include \"tinyxml2.h\"\r\n#include \r\nusing namespace tinyxml2;\r\nusing namespace std;\r\n\/\/---------------------------------------------------------------------------\r\n\r\nnamespace MediaInfoLib\r\n{\r\n\r\n\/\/***************************************************************************\r\n\/\/ Infos\r\n\/\/***************************************************************************\r\n\r\n\/\/---------------------------------------------------------------------------\r\nextern void DcpCpl_MergeFromPkl(File__ReferenceFilesHelper* FromCpl, File__ReferenceFilesHelper* FromPkl)\r\n{\r\n struct info\r\n {\r\n Ztring FileName;\r\n File__ReferenceFilesHelper::references::iterator Reference;\r\n };\r\n map Map;\r\n list List;\r\n ZtringList ExtraFiles_Name;\r\n for (File__ReferenceFilesHelper::references::iterator Reference=FromPkl->References.begin(); Reference!=FromPkl->References.end(); Reference++)\r\n {\r\n map::iterator UniqueID=Reference->Infos.find(\"UniqueID\");\r\n for (size_t Pos=0; PosFileNames.size(); Pos++)\r\n if (UniqueID!=Reference->Infos.end())\r\n {\r\n Map[UniqueID->second].FileName=Reference->FileNames[Pos];\r\n Map[UniqueID->second].Reference=Reference;\r\n }\r\n List.push_back(Reference);\r\n }\r\n\r\n for (File__ReferenceFilesHelper::references::iterator Reference=FromCpl->References.begin(); Reference!=FromCpl->References.end(); Reference++)\r\n for (size_t Pos=0; PosFileNames.size(); Pos++)\r\n {\r\n map::iterator Map_Item=Map.find(Reference->FileNames[Pos]);\r\n if (Map_Item!=Map.end())\r\n {\r\n Reference->FileNames[Pos]=Map_Item->second.FileName;\r\n for (list::iterator Reference2=List.begin(); Reference2!=List.end(); Reference2++)\r\n if (*Reference2==Map_Item->second.Reference)\r\n {\r\n List.erase(Reference2);\r\n break;\r\n }\r\n }\r\n }\r\n\r\n for (list::iterator Reference=List.begin(); Reference!=List.end(); Reference++)\r\n {\r\n FromCpl->References.push_back(**Reference);\r\n FromCpl->References[FromCpl->References.size()-1].StreamID=FromCpl->References.size()-1;\r\n }\r\n}\r\n\r\n\/\/***************************************************************************\r\n\/\/ Constructor\/Destructor\r\n\/\/***************************************************************************\r\n\r\n\/\/---------------------------------------------------------------------------\r\nFile_DcpCpl::File_DcpCpl()\r\n:File__Analyze()\r\n{\r\n #if MEDIAINFO_EVENTS\r\n ParserIDs[0]=MediaInfo_Parser_DcpCpl;\r\n StreamIDs_Width[0]=sizeof(size_t)*2;\r\n #endif \/\/MEDIAINFO_EVENTS\r\n #if MEDIAINFO_DEMUX\r\n Demux_EventWasSent_Accept_Specific=true;\r\n #endif \/\/MEDIAINFO_DEMUX\r\n\r\n \/\/Temp\r\n ReferenceFiles=NULL;\r\n}\r\n\r\n\/\/---------------------------------------------------------------------------\r\nFile_DcpCpl::~File_DcpCpl()\r\n{\r\n delete ReferenceFiles; \/\/ReferenceFiles=NULL;\r\n}\r\n\r\n\/\/***************************************************************************\r\n\/\/ Streams management\r\n\/\/***************************************************************************\r\n\r\n\/\/---------------------------------------------------------------------------\r\nvoid File_DcpCpl::Streams_Finish()\r\n{\r\n if (Config->File_IsReferenced_Get() || ReferenceFiles==NULL)\r\n return;\r\n\r\n ReferenceFiles->ParseReferences();\r\n}\r\n\r\n\/\/***************************************************************************\r\n\/\/ Buffer - Global\r\n\/\/***************************************************************************\r\n\r\n\/\/---------------------------------------------------------------------------\r\n#if MEDIAINFO_SEEK\r\nsize_t File_DcpCpl::Read_Buffer_Seek (size_t Method, int64u Value, int64u ID)\r\n{\r\n if (Config->File_IsReferenced_Get() || ReferenceFiles==NULL)\r\n return 0;\r\n\r\n return ReferenceFiles->Read_Buffer_Seek(Method, Value, ID);\r\n}\r\n#endif \/\/MEDIAINFO_SEEK\r\n\r\n\/\/***************************************************************************\r\n\/\/ Buffer - File header\r\n\/\/***************************************************************************\r\n\r\n\/\/---------------------------------------------------------------------------\r\nbool File_DcpCpl::FileHeader_Begin()\r\n{\r\n XMLDocument document;\r\n if (!FileHeader_Begin_XML(document))\r\n return false;\r\n\r\n bool IsDcp=false, IsImf=false;\r\n\r\n XMLElement* Root=document.FirstChildElement(\"CompositionPlaylist\");\r\n if (!Root)\r\n {\r\n Reject(\"DcpCpl\");\r\n return false;\r\n }\r\n\r\n const char* Attribute=Root->Attribute(\"xmlns\");\r\n if (!Attribute)\r\n {\r\n Reject(\"DcpCpl\");\r\n return false;\r\n }\r\n\r\n if (!strcmp(Attribute, \"http:\/\/www.digicine.com\/PROTO-ASDCP-CPL-20040511#\"))\r\n IsDcp=true;\r\n if (!strcmp(Attribute, \"http:\/\/www.smpte-ra.org\/schemas\/2067-3\/XXXX\") \/\/Some muxers use XXXX instead of year\r\n || !strcmp(Attribute, \"http:\/\/www.smpte-ra.org\/schemas\/2067-3\/2013\"))\r\n IsImf=true;\r\n\r\n if (!IsDcp && !IsImf)\r\n {\r\n Reject(\"DcpCpl\");\r\n return false;\r\n }\r\n\r\n Accept(\"DcpCpl\");\r\n Fill(Stream_General, 0, General_Format, IsDcp?\"DCP CPL\":\"IMF CPL\");\r\n Config->File_ID_OnlyRoot_Set(false);\r\n\r\n ReferenceFiles=new File__ReferenceFilesHelper(this, Config);\r\n\r\n \/\/Parsing main elements\r\n for (XMLElement* Root_Item=Root->FirstChildElement(); Root_Item; Root_Item=Root_Item->NextSiblingElement())\r\n {\r\n \/\/ReelList \/ SegmentList\r\n if ((IsDcp && !strcmp(Root_Item->Value(), \"ReelList\"))\r\n || (IsImf && !strcmp(Root_Item->Value(), \"SegmentList\")))\r\n {\r\n for (XMLElement* ReelList_Item=Root_Item->FirstChildElement(); ReelList_Item; ReelList_Item=ReelList_Item->NextSiblingElement())\r\n {\r\n \/\/Reel\r\n if ((IsDcp && !strcmp(ReelList_Item->Value(), \"Reel\"))\r\n || (IsImf && !strcmp(ReelList_Item->Value(), \"Segment\")))\r\n {\r\n for (XMLElement* Reel_Item=ReelList_Item->FirstChildElement(); Reel_Item; Reel_Item=Reel_Item->NextSiblingElement())\r\n {\r\n \/\/AssetList\r\n if ((IsDcp && !strcmp(Reel_Item->Value(), \"AssetList\"))\r\n || (IsImf && !strcmp(Reel_Item->Value(), \"SequenceList\")))\r\n {\r\n for (XMLElement* AssetList_Item=Reel_Item->FirstChildElement(); AssetList_Item; AssetList_Item=AssetList_Item->NextSiblingElement())\r\n {\r\n \/\/File\r\n \/\/if ((IsDcp && (!strcmp(AssetList_Item->Value(), \"MainPicture\") || !strcmp(AssetList_Item->Value(), \"MainSound\")))\r\n \/\/ || (IsImf && (!strcmp(AssetList_Item->Value(), \"cc:MainImageSequence\") || !strcmp(AssetList_Item->Value(), \"cc:MainImage\"))))\r\n {\r\n File__ReferenceFilesHelper::reference ReferenceFile;\r\n Ztring Id;\r\n\r\n if ((IsDcp && !strcmp(AssetList_Item->Value(), \"MainPicture\"))\r\n || (IsImf && !strcmp(AssetList_Item->Value(), \"cc:MainImageSequence\")))\r\n ReferenceFile.StreamKind=Stream_Video;\r\n if ((IsDcp && !strcmp(AssetList_Item->Value(), \"MainSound\"))\r\n || (IsImf && !strcmp(AssetList_Item->Value(), \"cc:MainAudioSequence\")))\r\n ReferenceFile.StreamKind=Stream_Audio;\r\n\r\n for (XMLElement* File_Item=AssetList_Item->FirstChildElement(); File_Item; File_Item=File_Item->NextSiblingElement())\r\n {\r\n \/\/Id\r\n if (!strcmp(File_Item->Value(), \"Id\") && Id.empty())\r\n Id.From_UTF8(File_Item->GetText());\r\n\r\n \/\/ResourceList\r\n if (IsImf && !strcmp(File_Item->Value(), \"ResourceList\"))\r\n {\r\n for (XMLElement* ResourceList_Item=File_Item->FirstChildElement(); ResourceList_Item; ResourceList_Item=ResourceList_Item->NextSiblingElement())\r\n {\r\n \/\/Resource\r\n if (!strcmp(ResourceList_Item->Value(), \"Resource\"))\r\n {\r\n for (XMLElement* Resource_Item=ResourceList_Item->FirstChildElement(); Resource_Item; Resource_Item=Resource_Item->NextSiblingElement())\r\n {\r\n \/\/TrackFileId\r\n if (!strcmp(Resource_Item->Value(), \"TrackFileId\"))\r\n ReferenceFile.FileNames.push_back(Resource_Item->GetText());\r\n }\r\n }\r\n }\r\n }\r\n }\r\n\r\n if (ReferenceFile.FileNames.empty())\r\n ReferenceFile.FileNames.push_back(Id);\r\n ReferenceFile.StreamID=ReferenceFiles->References.size()+1;\r\n ReferenceFiles->References.push_back(ReferenceFile);\r\n }\r\n }\r\n }\r\n }\r\n }\r\n }\r\n }\r\n }\r\n\r\n Element_Offset=File_Size;\r\n\r\n \/\/Getting files names\r\n if (!Config->File_IsReferenced_Get())\r\n {\r\n FileName Directory(File_Name);\r\n ZtringList List;\r\n if (IsDcp)\r\n List=Dir::GetAllFileNames(Directory.Path_Get()+PathSeparator+__T(\"*_pkl.xml\"), Dir::Include_Files);\r\n if (IsImf)\r\n List=Dir::GetAllFileNames(Directory.Path_Get()+PathSeparator+__T(\"PKL_*.xml\"), Dir::Include_Files);\r\n for (size_t Pos=0; PosReferenceFiles);\r\n }\r\n }\r\n }\r\n\r\n \/\/All should be OK...\r\n return true;\r\n}\r\n\r\n} \/\/NameSpace\r\n\r\n#endif \/\/MEDIAINFO_DCP_YES\r\n\r\nPrefer the prefix ++ operator.\/* Copyright (c) MediaArea.net SARL. All Rights Reserved.\r\n *\r\n * Use of this source code is governed by a BSD-style license that can\r\n * be found in the License.html file in the root of the source tree.\r\n *\/\r\n\r\n\/\/---------------------------------------------------------------------------\r\n\/\/ Pre-compilation\r\n#include \"MediaInfo\/PreComp.h\"\r\n#ifdef __BORLANDC__\r\n #pragma hdrstop\r\n#endif\r\n\/\/---------------------------------------------------------------------------\r\n\r\n\/\/---------------------------------------------------------------------------\r\n#include \"MediaInfo\/Setup.h\"\r\n\/\/---------------------------------------------------------------------------\r\n\r\n\/\/---------------------------------------------------------------------------\r\n#if defined(MEDIAINFO_DCP_YES)\r\n\/\/---------------------------------------------------------------------------\r\n\r\n\/\/---------------------------------------------------------------------------\r\n#include \"MediaInfo\/Multiple\/File_DcpCpl.h\"\r\n#include \"MediaInfo\/MediaInfo.h\"\r\n#include \"MediaInfo\/MediaInfo_Internal.h\"\r\n#include \"MediaInfo\/Multiple\/File__ReferenceFilesHelper.h\"\r\n#include \"MediaInfo\/Multiple\/File_DcpPkl.h\"\r\n#include \"MediaInfo\/Multiple\/File_Mxf.h\"\r\n#include \"ZenLib\/Dir.h\"\r\n#include \"ZenLib\/FileName.h\"\r\n#include \"tinyxml2.h\"\r\n#include \r\nusing namespace tinyxml2;\r\nusing namespace std;\r\n\/\/---------------------------------------------------------------------------\r\n\r\nnamespace MediaInfoLib\r\n{\r\n\r\n\/\/***************************************************************************\r\n\/\/ Infos\r\n\/\/***************************************************************************\r\n\r\n\/\/---------------------------------------------------------------------------\r\nextern void DcpCpl_MergeFromPkl(File__ReferenceFilesHelper* FromCpl, File__ReferenceFilesHelper* FromPkl)\r\n{\r\n struct info\r\n {\r\n Ztring FileName;\r\n File__ReferenceFilesHelper::references::iterator Reference;\r\n };\r\n map Map;\r\n list List;\r\n ZtringList ExtraFiles_Name;\r\n for (File__ReferenceFilesHelper::references::iterator Reference=FromPkl->References.begin(); Reference!=FromPkl->References.end(); ++Reference)\r\n {\r\n map::iterator UniqueID=Reference->Infos.find(\"UniqueID\");\r\n for (size_t Pos=0; PosFileNames.size(); Pos++)\r\n if (UniqueID!=Reference->Infos.end())\r\n {\r\n Map[UniqueID->second].FileName=Reference->FileNames[Pos];\r\n Map[UniqueID->second].Reference=Reference;\r\n }\r\n List.push_back(Reference);\r\n }\r\n\r\n for (File__ReferenceFilesHelper::references::iterator Reference=FromCpl->References.begin(); Reference!=FromCpl->References.end(); ++Reference)\r\n for (size_t Pos=0; PosFileNames.size(); Pos++)\r\n {\r\n map::iterator Map_Item=Map.find(Reference->FileNames[Pos]);\r\n if (Map_Item!=Map.end())\r\n {\r\n Reference->FileNames[Pos]=Map_Item->second.FileName;\r\n for (list::iterator Reference2=List.begin(); Reference2!=List.end(); ++Reference2)\r\n if (*Reference2==Map_Item->second.Reference)\r\n {\r\n List.erase(Reference2);\r\n break;\r\n }\r\n }\r\n }\r\n\r\n for (list::iterator Reference=List.begin(); Reference!=List.end(); ++Reference)\r\n {\r\n FromCpl->References.push_back(**Reference);\r\n FromCpl->References[FromCpl->References.size()-1].StreamID=FromCpl->References.size()-1;\r\n }\r\n}\r\n\r\n\/\/***************************************************************************\r\n\/\/ Constructor\/Destructor\r\n\/\/***************************************************************************\r\n\r\n\/\/---------------------------------------------------------------------------\r\nFile_DcpCpl::File_DcpCpl()\r\n:File__Analyze()\r\n{\r\n #if MEDIAINFO_EVENTS\r\n ParserIDs[0]=MediaInfo_Parser_DcpCpl;\r\n StreamIDs_Width[0]=sizeof(size_t)*2;\r\n #endif \/\/MEDIAINFO_EVENTS\r\n #if MEDIAINFO_DEMUX\r\n Demux_EventWasSent_Accept_Specific=true;\r\n #endif \/\/MEDIAINFO_DEMUX\r\n\r\n \/\/Temp\r\n ReferenceFiles=NULL;\r\n}\r\n\r\n\/\/---------------------------------------------------------------------------\r\nFile_DcpCpl::~File_DcpCpl()\r\n{\r\n delete ReferenceFiles; \/\/ReferenceFiles=NULL;\r\n}\r\n\r\n\/\/***************************************************************************\r\n\/\/ Streams management\r\n\/\/***************************************************************************\r\n\r\n\/\/---------------------------------------------------------------------------\r\nvoid File_DcpCpl::Streams_Finish()\r\n{\r\n if (Config->File_IsReferenced_Get() || ReferenceFiles==NULL)\r\n return;\r\n\r\n ReferenceFiles->ParseReferences();\r\n}\r\n\r\n\/\/***************************************************************************\r\n\/\/ Buffer - Global\r\n\/\/***************************************************************************\r\n\r\n\/\/---------------------------------------------------------------------------\r\n#if MEDIAINFO_SEEK\r\nsize_t File_DcpCpl::Read_Buffer_Seek (size_t Method, int64u Value, int64u ID)\r\n{\r\n if (Config->File_IsReferenced_Get() || ReferenceFiles==NULL)\r\n return 0;\r\n\r\n return ReferenceFiles->Read_Buffer_Seek(Method, Value, ID);\r\n}\r\n#endif \/\/MEDIAINFO_SEEK\r\n\r\n\/\/***************************************************************************\r\n\/\/ Buffer - File header\r\n\/\/***************************************************************************\r\n\r\n\/\/---------------------------------------------------------------------------\r\nbool File_DcpCpl::FileHeader_Begin()\r\n{\r\n XMLDocument document;\r\n if (!FileHeader_Begin_XML(document))\r\n return false;\r\n\r\n bool IsDcp=false, IsImf=false;\r\n\r\n XMLElement* Root=document.FirstChildElement(\"CompositionPlaylist\");\r\n if (!Root)\r\n {\r\n Reject(\"DcpCpl\");\r\n return false;\r\n }\r\n\r\n const char* Attribute=Root->Attribute(\"xmlns\");\r\n if (!Attribute)\r\n {\r\n Reject(\"DcpCpl\");\r\n return false;\r\n }\r\n\r\n if (!strcmp(Attribute, \"http:\/\/www.digicine.com\/PROTO-ASDCP-CPL-20040511#\"))\r\n IsDcp=true;\r\n if (!strcmp(Attribute, \"http:\/\/www.smpte-ra.org\/schemas\/2067-3\/XXXX\") \/\/Some muxers use XXXX instead of year\r\n || !strcmp(Attribute, \"http:\/\/www.smpte-ra.org\/schemas\/2067-3\/2013\"))\r\n IsImf=true;\r\n\r\n if (!IsDcp && !IsImf)\r\n {\r\n Reject(\"DcpCpl\");\r\n return false;\r\n }\r\n\r\n Accept(\"DcpCpl\");\r\n Fill(Stream_General, 0, General_Format, IsDcp?\"DCP CPL\":\"IMF CPL\");\r\n Config->File_ID_OnlyRoot_Set(false);\r\n\r\n ReferenceFiles=new File__ReferenceFilesHelper(this, Config);\r\n\r\n \/\/Parsing main elements\r\n for (XMLElement* Root_Item=Root->FirstChildElement(); Root_Item; Root_Item=Root_Item->NextSiblingElement())\r\n {\r\n \/\/ReelList \/ SegmentList\r\n if ((IsDcp && !strcmp(Root_Item->Value(), \"ReelList\"))\r\n || (IsImf && !strcmp(Root_Item->Value(), \"SegmentList\")))\r\n {\r\n for (XMLElement* ReelList_Item=Root_Item->FirstChildElement(); ReelList_Item; ReelList_Item=ReelList_Item->NextSiblingElement())\r\n {\r\n \/\/Reel\r\n if ((IsDcp && !strcmp(ReelList_Item->Value(), \"Reel\"))\r\n || (IsImf && !strcmp(ReelList_Item->Value(), \"Segment\")))\r\n {\r\n for (XMLElement* Reel_Item=ReelList_Item->FirstChildElement(); Reel_Item; Reel_Item=Reel_Item->NextSiblingElement())\r\n {\r\n \/\/AssetList\r\n if ((IsDcp && !strcmp(Reel_Item->Value(), \"AssetList\"))\r\n || (IsImf && !strcmp(Reel_Item->Value(), \"SequenceList\")))\r\n {\r\n for (XMLElement* AssetList_Item=Reel_Item->FirstChildElement(); AssetList_Item; AssetList_Item=AssetList_Item->NextSiblingElement())\r\n {\r\n \/\/File\r\n \/\/if ((IsDcp && (!strcmp(AssetList_Item->Value(), \"MainPicture\") || !strcmp(AssetList_Item->Value(), \"MainSound\")))\r\n \/\/ || (IsImf && (!strcmp(AssetList_Item->Value(), \"cc:MainImageSequence\") || !strcmp(AssetList_Item->Value(), \"cc:MainImage\"))))\r\n {\r\n File__ReferenceFilesHelper::reference ReferenceFile;\r\n Ztring Id;\r\n\r\n if ((IsDcp && !strcmp(AssetList_Item->Value(), \"MainPicture\"))\r\n || (IsImf && !strcmp(AssetList_Item->Value(), \"cc:MainImageSequence\")))\r\n ReferenceFile.StreamKind=Stream_Video;\r\n if ((IsDcp && !strcmp(AssetList_Item->Value(), \"MainSound\"))\r\n || (IsImf && !strcmp(AssetList_Item->Value(), \"cc:MainAudioSequence\")))\r\n ReferenceFile.StreamKind=Stream_Audio;\r\n\r\n for (XMLElement* File_Item=AssetList_Item->FirstChildElement(); File_Item; File_Item=File_Item->NextSiblingElement())\r\n {\r\n \/\/Id\r\n if (!strcmp(File_Item->Value(), \"Id\") && Id.empty())\r\n Id.From_UTF8(File_Item->GetText());\r\n\r\n \/\/ResourceList\r\n if (IsImf && !strcmp(File_Item->Value(), \"ResourceList\"))\r\n {\r\n for (XMLElement* ResourceList_Item=File_Item->FirstChildElement(); ResourceList_Item; ResourceList_Item=ResourceList_Item->NextSiblingElement())\r\n {\r\n \/\/Resource\r\n if (!strcmp(ResourceList_Item->Value(), \"Resource\"))\r\n {\r\n for (XMLElement* Resource_Item=ResourceList_Item->FirstChildElement(); Resource_Item; Resource_Item=Resource_Item->NextSiblingElement())\r\n {\r\n \/\/TrackFileId\r\n if (!strcmp(Resource_Item->Value(), \"TrackFileId\"))\r\n ReferenceFile.FileNames.push_back(Resource_Item->GetText());\r\n }\r\n }\r\n }\r\n }\r\n }\r\n\r\n if (ReferenceFile.FileNames.empty())\r\n ReferenceFile.FileNames.push_back(Id);\r\n ReferenceFile.StreamID=ReferenceFiles->References.size()+1;\r\n ReferenceFiles->References.push_back(ReferenceFile);\r\n }\r\n }\r\n }\r\n }\r\n }\r\n }\r\n }\r\n }\r\n\r\n Element_Offset=File_Size;\r\n\r\n \/\/Getting files names\r\n if (!Config->File_IsReferenced_Get())\r\n {\r\n FileName Directory(File_Name);\r\n ZtringList List;\r\n if (IsDcp)\r\n List=Dir::GetAllFileNames(Directory.Path_Get()+PathSeparator+__T(\"*_pkl.xml\"), Dir::Include_Files);\r\n if (IsImf)\r\n List=Dir::GetAllFileNames(Directory.Path_Get()+PathSeparator+__T(\"PKL_*.xml\"), Dir::Include_Files);\r\n for (size_t Pos=0; PosReferenceFiles);\r\n }\r\n }\r\n }\r\n\r\n \/\/All should be OK...\r\n return true;\r\n}\r\n\r\n} \/\/NameSpace\r\n\r\n#endif \/\/MEDIAINFO_DCP_YES\r\n\r\n<|endoftext|>"} {"text":"#include \"addcomputerscientist.h\"\n#include \"ui_addcomputerscientist.h\"\n\nAddComputerScientist::AddComputerScientist(QWidget *parent) :\n QDialog(parent),\n ui(new Ui::AddComputerScientist)\n{\n ui->setupUi(this);\n\n \/\/ getCurrent year (year is the currentyear)\n time_t timeNow = time(0);\n tm *ltm = localtime(&timeNow);\n int year = ltm->tm_year + 1900;\n\n \/\/ Validation for year of birth & year of death\n QIntValidator *yearValidator = new QIntValidator(0,year);\n ui->lineEdit_Addscientist_yearofbirth->setValidator(yearValidator);\n ui->lineEdit_Addscientist_deathYear->setValidator(yearValidator);\n\n}\n\nAddComputerScientist::~AddComputerScientist()\n{\n delete ui;\n}\n\nvoid AddComputerScientist::on_pushButton_Addscientist_save_clicked()\n{\n \/\/ While loop conditions\n bool exitLoop;\n bool validInput;\n\n \/\/ Gender options\n bool male = false;\n bool female = false;\n bool other = false;\n\n QString name = \"\";\n \/\/ isAlive is connected to the checkbox\n bool isAlive;\n QString gender;\n QString comment;\n QString birthYear;\n QString deathYear;\n\n\n \/\/ Taka inn mynd\n\n\n bool canCreatePerson = true;\n\n\n name = ui->lineEdit_Addscientist_name->text();\n qDebug() << name;\n birthYear = ui->lineEdit_Addscientist_yearofbirth->text();\n qDebug() << birthYear;\n isAlive = ui->checkBox_Addscientist_isPersonAlive->isChecked();\n if(isAlive)\n {\n qDebug() << \"This person is still alive\";\n }\n else if(isAlive == false)\n {\n deathYear = ui->lineEdit_Addscientist_deathYear->selectedText();\n qDebug() << \"This person died in the year\" << deathYear;\n }\n\n \/\/ If name or birthYear are empty strings\n if(name == \"\" || birthYear == \"\")\n {\n canCreatePerson = false;\n }\n\n if(isAlive == false && deathYear == \"\")\n {\n canCreatePerson = false;\n }\n\n \/\/ 1 denotes success 0 denotes failure\n if(canCreatePerson == true)\n {\n CSPerson createdPerson;\n _newPerson = createdPerson;\n \/\/setResult(QDialog::Accepted);\n }\n else\n {\n \/\/setResult(QDialog::Rejected);\n }\n\n\n}\nprogress made on addComputerScientist#include \"addcomputerscientist.h\"\n#include \"ui_addcomputerscientist.h\"\n\nAddComputerScientist::AddComputerScientist(QWidget *parent) :\n QDialog(parent),\n ui(new Ui::AddComputerScientist)\n{\n ui->setupUi(this);\n\n \/\/ getCurrent year (year is the currentyear)\n time_t timeNow = time(0);\n tm *ltm = localtime(&timeNow);\n int year = ltm->tm_year + 1900;\n\n \/\/ Validation for year of birth & year of death\n QIntValidator *yearValidator = new QIntValidator(0,year);\n ui->lineEdit_Addscientist_yearofbirth->setValidator(yearValidator);\n ui->lineEdit_Addscientist_deathYear->setValidator(yearValidator);\n\n}\n\nAddComputerScientist::~AddComputerScientist()\n{\n delete ui;\n}\n\nvoid AddComputerScientist::on_pushButton_Addscientist_save_clicked()\n{\n \/\/ If validation fails these are used\n bool nameFail = false;\n bool genderFail = false;\n bool birthYearFail = false;\n bool deathYearFail = false;\n\n \/\/ If validation fails this is set as false\n bool canCreatePerson = true;\n\n \/\/ Gender options\n bool male = false;\n bool female = false;\n bool other = false;\n\n QString name = \"\";\n QString comment = \"\";\n QString birthYear = \"\";\n QString deathYear = \"\";\n QString gender = \"\";\n\n \/\/ isAlive is connected to the checkbox\n bool isAlive;\n\n\n \/\/ Taka inn mynd\n\n name = ui->lineEdit_Addscientist_name->text();\n birthYear = ui->lineEdit_Addscientist_yearofbirth->text();\n comment = ui->lineEdit_Addscientist_comment->text();\n isAlive = ui->checkBox_Addscientist_isPersonAlive->isChecked();\n\n if(isAlive == true)\n {\n qDebug() << \"This person is still alive\";\n }\n else if(isAlive == false)\n {\n deathYear = ui->lineEdit_Addscientist_deathYear->text();\n }\n\n if(ui->radioButton_Addscientist_male->isChecked())\n {\n gender = \"Male\";\n qDebug() << \"Gender selected Male\";\n }\n if(ui->radioButton_Addscientist_female->isChecked())\n {\n gender = \"Female\";\n qDebug() << \"Gender selected Female\";\n }\n if(ui->radioButton_Addscientist_otherGender->isChecked())\n {\n gender = \"Other\";\n qDebug() << \"Gender selected Other\";\n }\n\n \/\/ Validations\n\n if(name == \"\" || birthYear == \"\")\n {\n canCreatePerson = false;\n nameFail = true;\n }\n\n if(birthYear == \"\")\n {\n canCreatePerson = false;\n birthYearFail = true;\n }\n\n if(isAlive == false && deathYear == \"\")\n {\n canCreatePerson = false;\n deathYearFail = true;\n }\n\n if(gender == \"\")\n {\n canCreatePerson = false;\n genderFail = true;\n }\n\n\n \/\/ 1 denotes success 0 denotes failure\n if(canCreatePerson == true)\n {\n CSPerson createdPerson;\n _newPerson = createdPerson;\n \/\/setResult(QDialog::Accepted);\n }\n else\n {\n \/\/setResult(QDialog::Rejected);\n }\n\n\n}\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * $RCSfile: SlsPageDescriptor.hxx,v $\n *\n * $Revision: 1.4 $\n *\n * last change: $Author: kz $ $Date: 2004-10-04 18:38:08 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef SD_SLIDESORTER_PAGE_DESCRIPTOR_HXX\n#define SD_SLIDESORTER_PAGE_DESCRIPTOR_HXX\n\n#ifndef _SV_GEN_HXX\n#include \n#endif\n#include \n#include \n#include \n\nclass SdPage;\n\n#include \n\nnamespace sdr { namespace contact {\nclass ObjectContact;\n} }\n\nnamespace sd { namespace slidesorter { namespace view {\nclass PageObject;\nclass PageObjectViewObjectContact;\n} } }\n\nnamespace sd { namespace slidesorter { namespace controller {\nclass PageObjectFactory;\n} } }\n\nnamespace sd { namespace slidesorter { namespace model {\n\nclass SlideSorterView;\nclass SlideRenderer;\n\n\/** Each PageDescriptor object represents the preview of one draw page,\n slide, or master page of a Draw or Impress document as they are displayed\n in the slide sorter. This class gives access to some associated\n information like prerendered preview or position on the screen.\n\n

Bounding boxes of page objects come in four varieties:\n Model and screen\/pixel coordinates and the bounding boxes of the actual\n page objects and the larger bounding boxes that include page names and\n fade symbol.<\/p>\n*\/\nclass PageDescriptor\n{\npublic:\n PageDescriptor (\n SdPage& rPage,\n const controller::PageObjectFactory& rPageObjectFactory);\n ~PageDescriptor (void);\n\n \/** Return the page that is represented by the descriptor.\n *\/\n SdPage* GetPage (void) const;\n\n \/** Return the page shape that is used for visualizing the page.\n *\/\n view::PageObject* GetPageObject (void);\n void ReleasePageObject (void);\n\n \/** Return when the page object is fully or parially visible. *\/\n bool IsVisible (void) const;\n\n \/** Set the visible state that is returned by the IsVisible() method.\n This method is typically called by the view who renders the object\n onto the screen.\n *\/\n void SetVisible (bool bVisible);\n\n \/** Make sure that the page is selected and return whether the\n selection state changed.\n *\/\n bool Select (void);\n \/** Make sure that the page is not selected and return whether the\n selection state changed.\n *\/\n bool Deselect (void);\n\n \/** Return whether the page is selected (and thus bypasses the internal\n mbIsSelected flag.\n *\/\n bool IsSelected (void) const;\n\n \/** Set the internal mbIsSelected flag to the selection state of the\n page. Use this method to synchornize a page descriptor with the\n page it describes and determine whether a redraw to update the\n selection indicator is necessary.\n @return\n When the two selection states were different is\n returned. When they were the same this method returns\n .\n *\/\n bool UpdateSelection (void);\n\n bool IsFocused (void) const;\n void SetFocus (void);\n void RemoveFocus (void);\n\n view::PageObjectViewObjectContact* GetViewObjectContact (void) const;\n\n void SetViewObjectContact (\n view::PageObjectViewObjectContact* pViewObjectContact);\n\n \/** Return the currently used page object factory.\n *\/\n const controller::PageObjectFactory& GetPageObjectFactory (void) const;\n\n \/** Replace the current page object factory by the given one.\n *\/\n void SetPageObjectFactory (const controller::PageObjectFactory& rFactory);\n\n void SetModelBorder (const SvBorder& rBorder);\n SvBorder GetModelBorder (void) const;\n\n void SetPageNumberAreaModelSize (const Size& rSize);\n Size GetPageNumberAreaModelSize (void) const;\n\nprivate:\n SdPage& mrPage;\n\n \/\/\/ The factory that is used to create PageObject objects.\n const controller::PageObjectFactory* mpPageObjectFactory;\n\n \/** The page object will be destroyed by the page into which it has\n been inserted.\n *\/\n view::PageObject* mpPageObject;\n\n bool mbIsSelected;\n bool mbVisible;\n bool mbFocused;\n\n view::PageObjectViewObjectContact* mpViewObjectContact;\n\n \/\/\/ The borders in model coordinates arround the page object.\n SvBorder maModelBorder;\n\n \/\/\/ The size of the page number area in model coordinates.\n Size maPageNumberAreaModelSize;\n\n \/\/ Do not use the copy constructor operator. It is not implemented.\n PageDescriptor (const PageDescriptor& rDescriptor);\n\n \/\/ Do not use the assignment operator. It is not implemented\n \/\/ (mrPage can not be assigned).\n PageDescriptor& operator= (const PageDescriptor& rDescriptor);\n};\n\n} } } \/\/ end of namespace ::sd::slidesorter::model\n\n#endif\nINTEGRATION: CWS impress62 (1.4.306); FILE MERGED 2005\/06\/29 08:31:44 af 1.4.306.1: #i47134# Added a comment for SetPageNumberAreaModelSize().\/*************************************************************************\n *\n * $RCSfile: SlsPageDescriptor.hxx,v $\n *\n * $Revision: 1.5 $\n *\n * last change: $Author: obo $ $Date: 2005-07-07 13:37:05 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef SD_SLIDESORTER_PAGE_DESCRIPTOR_HXX\n#define SD_SLIDESORTER_PAGE_DESCRIPTOR_HXX\n\n#ifndef _SV_GEN_HXX\n#include \n#endif\n#include \n#include \n#include \n\nclass SdPage;\n\n#include \n\nnamespace sdr { namespace contact {\nclass ObjectContact;\n} }\n\nnamespace sd { namespace slidesorter { namespace view {\nclass PageObject;\nclass PageObjectViewObjectContact;\n} } }\n\nnamespace sd { namespace slidesorter { namespace controller {\nclass PageObjectFactory;\n} } }\n\nnamespace sd { namespace slidesorter { namespace model {\n\nclass SlideSorterView;\nclass SlideRenderer;\n\n\/** Each PageDescriptor object represents the preview of one draw page,\n slide, or master page of a Draw or Impress document as they are displayed\n in the slide sorter. This class gives access to some associated\n information like prerendered preview or position on the screen.\n\n

Bounding boxes of page objects come in four varieties:\n Model and screen\/pixel coordinates and the bounding boxes of the actual\n page objects and the larger bounding boxes that include page names and\n fade symbol.<\/p>\n*\/\nclass PageDescriptor\n{\npublic:\n PageDescriptor (\n SdPage& rPage,\n const controller::PageObjectFactory& rPageObjectFactory);\n ~PageDescriptor (void);\n\n \/** Return the page that is represented by the descriptor.\n *\/\n SdPage* GetPage (void) const;\n\n \/** Return the page shape that is used for visualizing the page.\n *\/\n view::PageObject* GetPageObject (void);\n void ReleasePageObject (void);\n\n \/** Return when the page object is fully or parially visible. *\/\n bool IsVisible (void) const;\n\n \/** Set the visible state that is returned by the IsVisible() method.\n This method is typically called by the view who renders the object\n onto the screen.\n *\/\n void SetVisible (bool bVisible);\n\n \/** Make sure that the page is selected and return whether the\n selection state changed.\n *\/\n bool Select (void);\n \/** Make sure that the page is not selected and return whether the\n selection state changed.\n *\/\n bool Deselect (void);\n\n \/** Return whether the page is selected (and thus bypasses the internal\n mbIsSelected flag.\n *\/\n bool IsSelected (void) const;\n\n \/** Set the internal mbIsSelected flag to the selection state of the\n page. Use this method to synchornize a page descriptor with the\n page it describes and determine whether a redraw to update the\n selection indicator is necessary.\n @return\n When the two selection states were different is\n returned. When they were the same this method returns\n .\n *\/\n bool UpdateSelection (void);\n\n bool IsFocused (void) const;\n void SetFocus (void);\n void RemoveFocus (void);\n\n view::PageObjectViewObjectContact* GetViewObjectContact (void) const;\n\n void SetViewObjectContact (\n view::PageObjectViewObjectContact* pViewObjectContact);\n\n \/** Return the currently used page object factory.\n *\/\n const controller::PageObjectFactory& GetPageObjectFactory (void) const;\n\n \/** Replace the current page object factory by the given one.\n *\/\n void SetPageObjectFactory (const controller::PageObjectFactory& rFactory);\n\n void SetModelBorder (const SvBorder& rBorder);\n SvBorder GetModelBorder (void) const;\n\n \/** The size of the area in which the page number is displayed is\n calculated by the SlideSorterView and then stored in the page\n descriptors so that the contact objects can access them. The\n contact objects can not calculate them on demand because the total\n number of slides is needed to do that and this number is not known\n to the contact objects.\n *\/\n void SetPageNumberAreaModelSize (const Size& rSize);\n Size GetPageNumberAreaModelSize (void) const;\n\nprivate:\n SdPage& mrPage;\n\n \/\/\/ The factory that is used to create PageObject objects.\n const controller::PageObjectFactory* mpPageObjectFactory;\n\n \/** The page object will be destroyed by the page into which it has\n been inserted.\n *\/\n view::PageObject* mpPageObject;\n\n bool mbIsSelected;\n bool mbVisible;\n bool mbFocused;\n\n view::PageObjectViewObjectContact* mpViewObjectContact;\n\n \/\/\/ The borders in model coordinates arround the page object.\n SvBorder maModelBorder;\n\n \/\/\/ The size of the page number area in model coordinates.\n Size maPageNumberAreaModelSize;\n\n \/\/ Do not use the copy constructor operator. It is not implemented.\n PageDescriptor (const PageDescriptor& rDescriptor);\n\n \/\/ Do not use the assignment operator. It is not implemented\n \/\/ (mrPage can not be assigned).\n PageDescriptor& operator= (const PageDescriptor& rDescriptor);\n};\n\n} } } \/\/ end of namespace ::sd::slidesorter::model\n\n#endif\n<|endoftext|>"} {"text":"\/*=========================================================================\n *\n * Copyright Insight Software Consortium\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0.txt\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *=========================================================================*\/\n\n#include \"itkPhysicalPointImageSource.h\"\n\n#include \"itkImageFileWriter.h\"\n\n#include \"itkVectorImage.h\"\n#include \"itkVectorIndexSelectionCastImageFilter.h\"\n\nnamespace {\ntemplate< typename TImageType >\nint itkPhysicalPointImageSourceTest( const std::string &fname,\n typename TImageType::SizeType &size,\n typename TImageType::SpacingType &spacing,\n typename TImageType::PointType &origin,\n typename TImageType::DirectionType &direction)\n{\n\n typedef TImageType ImageType;\n\n typedef itk::PhysicalPointImageSource< ImageType > PointerSourceType;\n\n typename PointerSourceType::Pointer source = PointerSourceType::New();\n source->SetSize(size);\n source->SetSpacing(spacing);\n source->SetOrigin(origin);\n source->SetDirection( direction );\n\n try\n {\n source->UpdateLargestPossibleRegion();\n }\n catch (itk::ExceptionObject & err)\n {\n std::cout << \"Exception in filter execution!\" << std::endl;\n std::cout << err << std::endl;\n return EXIT_FAILURE;\n }\n\n typedef itk::Image< typename itk::NumericTraits< typename ImageType::PixelType >::ValueType, ImageType::ImageDimension> ValueImageType;\n\n typedef itk::VectorIndexSelectionCastImageFilter< ImageType, ValueImageType > ValueImageCastFilter;\n typename ValueImageCastFilter::Pointer vif = ValueImageCastFilter::New();\n vif->SetInput( source->GetOutput() );\n vif->SetIndex(0);\n\n typedef itk::ImageFileWriter WriterType;\n typename WriterType::Pointer writer = WriterType::New();\n writer->SetFileName( fname );\n writer->SetInput( vif->GetOutput() );\n try\n {\n std::cout << \"Writing image to \" << fname << std::endl;\n writer->Update();\n }\n catch (itk::ExceptionObject & err)\n {\n std::cout << \"Exception in writing!\" << std::endl;\n std::cout << err << std::endl;\n return EXIT_FAILURE;\n }\n return EXIT_SUCCESS;\n}\n\n}\nint itkPhysicalPointImageSourceTest( int argc, char *argv[] )\n{\n double theta = 0;\n const unsigned int ImageDimension = 2;\n\n if ( argc < 3 )\n {\n std::cout << \"Usage: \" << argv[0] << \" outputImage whichTest [ theta ]\" << std::endl;\n return EXIT_FAILURE;\n }\n if ( argc >= 4 )\n {\n theta = atof( argv[3] );\n }\n\n itk::Size size;\n size.Fill(64);\n\n typedef itk::Image ImageType;\n ImageType::SpacingType spacing(1.0);\n ImageType::PointType origin(0.0);\n ImageType::DirectionType direction;\n\n direction.SetIdentity();\n\n int test;\n if ( atoi( argv[2] ) == 0 )\n {\n test = itkPhysicalPointImageSourceTest, ImageDimension > >( std::string( argv[1] ), size, spacing, origin, direction );\n }\n else if ( atoi( argv[2] ) == 1 )\n {\n test = itkPhysicalPointImageSourceTest >( std::string( argv[1] ), size, spacing, origin, direction );\n }\n else if ( atoi( argv[2] ) == 2 )\n {\n spacing.Fill( 1.123 );\n origin.Fill( -0.987 );\n test = itkPhysicalPointImageSourceTest, ImageDimension > >( std::string( argv[1] ), size, spacing, origin, direction );\n }\n else\n {\n itk::SpacePrecisionType M[] = { std::cos( theta ), -std::sin( theta ),\n std::sin( theta ), std::cos( theta ) };\n\n direction = vnl_matrix( M, 2, 2);\n test = itkPhysicalPointImageSourceTest< itk::VectorImage >( std::string( argv[1] ), size, spacing, origin, direction );\n }\n\n return test;\n}\nENH: Improve itkPhysicalPointImageSource class coverage.\/*=========================================================================\n *\n * Copyright Insight Software Consortium\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0.txt\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *=========================================================================*\/\n\n#include \"itkPhysicalPointImageSource.h\"\n\n#include \"itkImageFileWriter.h\"\n\n#include \"itkVectorImage.h\"\n#include \"itkVectorIndexSelectionCastImageFilter.h\"\n#include \"itkTestingMacros.h\"\n\nnamespace {\ntemplate< typename TImageType >\nint itkPhysicalPointImageSourceTest( const std::string &fname,\n typename TImageType::SizeType &size,\n typename TImageType::SpacingType &spacing,\n typename TImageType::PointType &origin,\n typename TImageType::DirectionType &direction )\n{\n\n typedef TImageType ImageType;\n\n typedef itk::PhysicalPointImageSource< ImageType > PointerSourceType;\n\n typename PointerSourceType::Pointer source = PointerSourceType::New();\n source->SetSize(size);\n source->SetSpacing(spacing);\n source->SetOrigin(origin);\n source->SetDirection( direction );\n\n TRY_EXPECT_NO_EXCEPTION( source->UpdateLargestPossibleRegion() );\n\n typedef itk::Image< typename itk::NumericTraits< typename ImageType::PixelType >::ValueType, ImageType::ImageDimension >\n ValueImageType;\n\n typedef itk::VectorIndexSelectionCastImageFilter< ImageType, ValueImageType > ValueImageCastFilter;\n typename ValueImageCastFilter::Pointer vif = ValueImageCastFilter::New();\n vif->SetInput( source->GetOutput() );\n vif->SetIndex(0);\n\n typedef itk::ImageFileWriter< ValueImageType > WriterType;\n typename WriterType::Pointer writer = WriterType::New();\n writer->SetFileName( fname );\n writer->SetInput( vif->GetOutput() );\n\n TRY_EXPECT_NO_EXCEPTION( writer->Update() );\n\n return EXIT_SUCCESS;\n}\n\n}\nint itkPhysicalPointImageSourceTest( int argc, char *argv[] )\n{\n double theta = 0;\n const unsigned int ImageDimension = 2;\n\n if ( argc < 3 )\n {\n std::cout << \"Usage: \" << argv[0] << \" outputImage whichTest [ theta ]\" << std::endl;\n return EXIT_FAILURE;\n }\n if ( argc >= 4 )\n {\n theta = atof( argv[3] );\n }\n\n itk::Size size;\n size.Fill(64);\n\n typedef itk::Image< unsigned char, ImageDimension > ImageType;\n ImageType::SpacingType spacing(1.0);\n ImageType::PointType origin(0.0);\n ImageType::DirectionType direction;\n\n direction.SetIdentity();\n\n \/\/ Exercise basic object methods\n \/\/ Done outside the helper function in the test because GCC is limited\n \/\/ when calling overloaded base class functions.\n typedef itk::PhysicalPointImageSource< itk::Image< itk::Point< double, ImageDimension >, ImageDimension > >\n PointerSourceType;\n PointerSourceType::Pointer source = PointerSourceType::New();\n\n EXERCISE_BASIC_OBJECT_METHODS( source, PhysicalPointImageSource, GenerateImageSource );\n\n int test = EXIT_SUCCESS;\n if ( atoi( argv[2] ) == 0 )\n {\n test =\n itkPhysicalPointImageSourceTest< itk::Image< itk::Point< double, ImageDimension >, ImageDimension > >(\n std::string( argv[1] ), size, spacing, origin, direction );\n }\n else if ( atoi( argv[2] ) == 1 )\n {\n test = itkPhysicalPointImageSourceTest< itk::VectorImage< double, ImageDimension > >(\n std::string( argv[1] ), size, spacing, origin, direction );\n }\n else if ( atoi( argv[2] ) == 2 )\n {\n spacing.Fill( 1.123 );\n origin.Fill( -0.987 );\n test =\n itkPhysicalPointImageSourceTest< itk::Image< itk::Point< float, ImageDimension>, ImageDimension > >(\n std::string( argv[1] ), size, spacing, origin, direction );\n }\n else\n {\n itk::SpacePrecisionType M[] = { std::cos( theta ), -std::sin( theta ),\n std::sin( theta ), std::cos( theta ) };\n\n direction = vnl_matrix< itk::SpacePrecisionType >( M, 2, 2 );\n test = itkPhysicalPointImageSourceTest< itk::VectorImage< float, ImageDimension > >(\n std::string( argv[1] ), size, spacing, origin, direction );\n }\n\n return test;\n}\n<|endoftext|>"} {"text":"#include \"SDL.hh\"\r\n#include \"Logger.hh\"\r\nusing namespace RAGE;\r\nusing namespace RAGE::SDL;\r\n\r\nLogger Log(\"Test Video\");\r\n\r\n\/\/Defining UserInput\r\nclass MyUserInput : public Keyboard\r\n{\r\npublic:\r\n\r\n virtual bool handleKeyEvent (const Sym &s, bool pressed)\r\n {\r\n bool res = false;\r\n switch( s.getKey() )\r\n {\r\n case KEscape:\r\n if (pressed==false)\r\n {\r\n#ifdef DEBUG\r\n Log << nl << \"Quit requested !\" << std::endl;\r\n#endif\r\n\r\n _quitRequested=true;\r\n res=true;\r\n }\r\n break;\r\n case KF5:\r\n if (pressed==true)\r\n App::getInstance().getWindow()->iconify();\r\n res = true;\r\n break;\r\n\t\t\t\tcase KF6:\r\n if (pressed==true)\r\n App::getInstance().getWindow()->setFullscreen(!App::getInstance().getWindow()->isFullscreen());\r\n res = true;\r\n break;\r\n default:\r\n res = false;\r\n }\r\n return res;\r\n }\r\n};\r\n\r\nclass MyEngine : public DefaultEngine\r\n{\r\n\r\npublic:\r\n\r\n\tRGBSurface loadedimage;\r\n\tPoint imagepos;\r\n\r\n\tMyEngine( const std::string & imagefilename) : loadedimage(imagefilename),imagepos()\r\n\t{}\r\n\r\n virtual ~MyEngine(){}\r\n\t\t\t\r\n bool init(int width, int height)\r\n\t{\r\n\t\timagepos.setx( (width - loadedimage.getWidth()) \/2);\r\n\t\timagepos.sety( (height - loadedimage.getHeight()) \/2);\r\n\t\treturn DefaultEngine::init(width,height);\r\n\t}\r\n\r\n\tbool resize(int width, int height)\r\n\t{\r\n\t\timagepos.setx( (width - loadedimage.getWidth()) \/2);\r\n\t\timagepos.sety( (height - loadedimage.getHeight()) \/2);\r\n\t\treturn DefaultEngine::resize(width,height);\r\n\t}\r\n\r\n\tvoid render(VideoSurface & screen) const\r\n {\r\n\t\tscreen.blit(loadedimage, imagepos );\r\n\t\tDefaultEngine::render(screen);\r\n }\r\n};\r\n\r\n\r\n\/\/Main Program\r\nint main(int argc, char** argv)\r\n{\r\n\r\n Logger testlog(\"Test Log\");\r\n\r\n \/\/Setup example\r\n\r\n testlog << nl << \" Enabling SDL Video... \" << std::endl;\r\n App::getInstance().initVideo(false,false,true,false);\r\n \r\n\tApp::getInstance().setName (\"RAGE::SDL test - Video\");\r\n \r\n\r\n testlog << nl << \" Creating the User Interface... \" << std::endl;\r\n \/\/UI Creation\r\n MyUserInput ui;\r\n App::getInstance().getWindow()->getEventManager()->setKeyboard(&ui);\r\n\r\n App::getInstance().getWindow()->setBGColor(Color (64,0,0));\r\n\t\r\n\t\/\/if argument we load the image in the test engine \r\n\tif ( argc > 1)\r\n\t\tApp::getInstance().getWindow()->setEngine(new MyEngine(std::string(argv[1])));\r\n\t\/\/otherwise we use the default engine only.\r\n\r\n if (! (App::getInstance().getWindow()->resetDisplay()))\r\n {\r\n testlog << nl << \"Display Creation FAILED !\"<< std::endl;\r\n exit(0);\r\n }\r\n else\r\n {\r\n App::getInstance().getWindow()->mainLoop(2);\r\n\t\t\/\/think about automatic exit after timeout...\r\n }\r\n return 0;\r\n}\r\n\r\n\r\nchanged a bit the test to tests colorkey transparency also#include \"SDL.hh\"\r\n#include \"Logger.hh\"\r\nusing namespace RAGE;\r\nusing namespace RAGE::SDL;\r\n\r\nLogger Log(\"Test Video\");\r\n\r\n\/\/Defining UserInput\r\nclass MyUserInput : public Keyboard\r\n{\r\npublic:\r\n\r\n virtual bool handleKeyEvent (const Sym &s, bool pressed)\r\n {\r\n bool res = false;\r\n switch( s.getKey() )\r\n {\r\n case KEscape:\r\n if (pressed==false)\r\n {\r\n#ifdef DEBUG\r\n Log << nl << \"Quit requested !\" << std::endl;\r\n#endif\r\n\r\n _quitRequested=true;\r\n res=true;\r\n }\r\n break;\r\n case KF5:\r\n if (pressed==true)\r\n App::getInstance().getWindow()->iconify();\r\n res = true;\r\n break;\r\n\t\t\t\tcase KF6:\r\n if (pressed==true)\r\n App::getInstance().getWindow()->setFullscreen(!App::getInstance().getWindow()->isFullscreen());\r\n res = true;\r\n break;\r\n default:\r\n res = false;\r\n }\r\n return res;\r\n }\r\n};\r\n\r\nclass MyEngine : public DefaultEngine\r\n{\r\n\r\npublic:\r\n\r\n\tRGBSurface loadedimage;\r\n\tPoint imagepos;\r\n\r\n\tMyEngine( const std::string & imagefilename) : loadedimage(imagefilename,Color(0,0,0)),imagepos()\r\n\t{}\r\n\r\n virtual ~MyEngine(){}\r\n\t\t\t\r\n bool init(int width, int height)\r\n\t{\r\n\t\timagepos.setx( (width - loadedimage.getWidth()) \/2);\r\n\t\timagepos.sety( (height - loadedimage.getHeight()) \/2);\r\n\t\treturn DefaultEngine::init(width,height);\r\n\t}\r\n\r\n\tbool resize(int width, int height)\r\n\t{\r\n\t\timagepos.setx( (width - loadedimage.getWidth()) \/2);\r\n\t\timagepos.sety( (height - loadedimage.getHeight()) \/2);\r\n\t\treturn DefaultEngine::resize(width,height);\r\n\t}\r\n\r\n\tvoid render(VideoSurface & screen) const\r\n {\r\n\t\tscreen.blit(loadedimage, imagepos );\r\n\t\tDefaultEngine::render(screen);\r\n }\r\n};\r\n\r\n\r\n\/\/Main Program\r\nint main(int argc, char** argv)\r\n{\r\n\r\n Logger testlog(\"Test Log\");\r\n\r\n \/\/Setup example\r\n\r\n testlog << nl << \" Enabling SDL Video... \" << std::endl;\r\n App::getInstance().initVideo(false,false,true,false);\r\n \r\n\tApp::getInstance().setName (\"RAGE::SDL test - Video\");\r\n \r\n\r\n testlog << nl << \" Creating the User Interface... \" << std::endl;\r\n \/\/UI Creation\r\n MyUserInput ui;\r\n App::getInstance().getWindow()->getEventManager()->setKeyboard(&ui);\r\n\r\n App::getInstance().getWindow()->setBGColor(Color (64,0,0));\r\n\t\r\n\t\/\/if argument we load the image in the test engine \r\n\tif ( argc > 1)\r\n\t\tApp::getInstance().getWindow()->setEngine(new MyEngine(std::string(argv[1])));\r\n\t\/\/otherwise we use the default engine only.\r\n\r\n if (! (App::getInstance().getWindow()->resetDisplay()))\r\n {\r\n testlog << nl << \"Display Creation FAILED !\"<< std::endl;\r\n exit(0);\r\n }\r\n else\r\n {\r\n App::getInstance().getWindow()->mainLoop(2);\r\n\t\/\/think about automatic exit after timeout...\r\n }\r\n return 0;\r\n}\r\n\r\n\r\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace boost {\n namespace asio { class io_service; }\n}\n\n\/\/=============================================================================\nnamespace riak {\n\/\/=============================================================================\n\n\/*!\n * A client is the primary point at which a Riak store is accessed. As it is insufficient to\n * allocate such a client on the stack, such an object must be created using riak::make_client.\n *\/\nclass client\n : public std::enable_shared_from_this\n{\n public:\n \/*! Defaults that allow total control to the database administrators. *\/\n static const object_access_parameters access_override_defaults;\n \n \/*! A sane set of failure defaults; someone who doesn't care to tune their application won't touch these. *\/\n static const request_failure_parameters failure_defaults;\n \n \/*! Yields the object access defaults with which this client was instantiated. *\/\n const object_access_parameters& object_access_override_defaults () const;\n \n void get_object (const key& bucket, const key& k, get_response_handler);\n \/\/ void put_object (const key& bucket, const key& k, put_response_handler);\n void delete_object (const key& bucket, const key& k, delete_response_handler h);\n\n private:\n transport::delivery_provider deliver_request_;\n sibling_resolution resolve_siblings_;\n const object_access_parameters access_overrides_;\n const request_failure_parameters request_failure_defaults_;\n boost::asio::io_service& ios_;\n\n protected:\n friend std::shared_ptr make_client (\n transport::delivery_provider,\n sibling_resolution sr,\n boost::asio::io_service&,\n const request_failure_parameters&,\n const object_access_parameters&);\n \n client (transport::delivery_provider& d,\n sibling_resolution sr,\n boost::asio::io_service& ios,\n const request_failure_parameters& = failure_defaults,\n const object_access_parameters& = access_override_defaults);\n};\n\n\/*!\n * \\param dp will be used to deliver requests.\n * \\param sr will be applied as a default to all cases of sibling resolution.\n * \\param ios will be burdened with query transmission and reception events.\n * \\return a new Riak client which is ready to access shared resources.\n *\/\nstd::shared_ptr make_client (\n transport::delivery_provider dp,\n sibling_resolution sr,\n boost::asio::io_service& ios,\n const request_failure_parameters& = client::failure_defaults,\n const object_access_parameters& = client::access_override_defaults);\n\n\/\/=============================================================================\n} \/\/ namespace riak\n\/\/=============================================================================\nRemoving dead code; put is implemented only after a get.#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace boost {\n namespace asio { class io_service; }\n}\n\n\/\/=============================================================================\nnamespace riak {\n\/\/=============================================================================\n\n\/*!\n * A client is the primary point at which a Riak store is accessed. As it is insufficient to\n * allocate such a client on the stack, such an object must be created using riak::make_client.\n *\/\nclass client\n : public std::enable_shared_from_this\n{\n public:\n \/*! Defaults that allow total control to the database administrators. *\/\n static const object_access_parameters access_override_defaults;\n \n \/*! A sane set of failure defaults; someone who doesn't care to tune their application won't touch these. *\/\n static const request_failure_parameters failure_defaults;\n \n \/*! Yields the object access defaults with which this client was instantiated. *\/\n const object_access_parameters& object_access_override_defaults () const;\n \n void get_object (const key& bucket, const key& k, get_response_handler);\n void delete_object (const key& bucket, const key& k, delete_response_handler h);\n\n private:\n transport::delivery_provider deliver_request_;\n sibling_resolution resolve_siblings_;\n const object_access_parameters access_overrides_;\n const request_failure_parameters request_failure_defaults_;\n boost::asio::io_service& ios_;\n\n protected:\n friend std::shared_ptr make_client (\n transport::delivery_provider,\n sibling_resolution sr,\n boost::asio::io_service&,\n const request_failure_parameters&,\n const object_access_parameters&);\n \n client (transport::delivery_provider& d,\n sibling_resolution sr,\n boost::asio::io_service& ios,\n const request_failure_parameters& = failure_defaults,\n const object_access_parameters& = access_override_defaults);\n};\n\n\/*!\n * \\param dp will be used to deliver requests.\n * \\param sr will be applied as a default to all cases of sibling resolution.\n * \\param ios will be burdened with query transmission and reception events.\n * \\return a new Riak client which is ready to access shared resources.\n *\/\nstd::shared_ptr make_client (\n transport::delivery_provider dp,\n sibling_resolution sr,\n boost::asio::io_service& ios,\n const request_failure_parameters& = client::failure_defaults,\n const object_access_parameters& = client::access_override_defaults);\n\n\/\/=============================================================================\n} \/\/ namespace riak\n\/\/=============================================================================\n<|endoftext|>"} {"text":"\/*\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/ SKIRT -- an advanced radiative transfer code \/\/\/\/\n\/\/\/\/ © Astronomical Observatory, Ghent University \/\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ *\/\n\n#ifndef DUSTGRIDPATH_HPP\n#define DUSTGRIDPATH_HPP\n\n#include \n#include \n#include \"Direction.hpp\"\n#include \"Position.hpp\"\nclass Box;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/** A DustGridPath object contains the details of a path through a dust grid structure. Given a\n dust grid structure, i.e. an object of a DustGridStucture subclass, a starting position\n \\f${\\bf{r}}\\f$ and a propagation direction \\f${\\bf{k}}\\f$, one can calculate the path through\n the dust grid structure. A DustGridPath object keeps record of all the cells that are crossed\n by this path, together with the physical path length \\f$\\Delta s\\f$ covered within each cell,\n and the path length \\f$s\\f$ covered along the entire path up to the end of the cell. Given\n additional information about the dust properties in each cell (at a particular wavelength), one\n can also calculate optical depth information for the path. A DustGridPath object keeps record\n of the optical depth \\f$\\Delta\\tau\\f$ along the path segment within each cell, and the optical\n depth \\f$\\tau\\f$ along the entire path up to the end of the cell. *\/\nclass DustGridPath\n{\npublic:\n\n \/\/ ------- Constructors; handling position and directions -------\n\n \/** This constructor creates an empty path with the specified initial position and propagation\n direction. *\/\n DustGridPath(const Position& bfr, const Direction& bfk);\n\n \/** This constructor creates an empty path with the initial position and propagation direction\n initialized to null values. After using this constructor, invoke the setPosition() and\n setDirection() functions to set these properties to appropriate values. *\/\n DustGridPath();\n\n \/** This function sets the initial position of the path to a new value. *\/\n void setPosition(const Position& bfr) { _bfr = bfr; }\n\n \/** This function sets the propagation direction along the path to a new value. *\/\n void setDirection(const Direction& bfk) { _bfk = bfk; }\n\n \/** This function returns the initial position of the path. *\/\n Position position() const { return _bfr; }\n\n \/** This function returns the propagation direction along the path. *\/\n Direction direction() const { return _bfk; }\n\n \/\/ ------- Handling geometric data on path segments -------\n\n \/** This function removes all path segments, resulting in an empty path with the original\n initial position and propagation direction. *\/\n void clear();\n\n \/** This function adds a segment in cell \\f$m\\f$ with length \\f$\\Delta s\\f$ to the path,\n assuming \\f$\\Delta s>0\\f$. Otherwise the function does nothing. *\/\n void addSegment(int m, double ds);\n\n \/** This function adds the segments to the path that are needed to move the initial position\n along the propagation direction (both specified in the constructor) inside a given box, and\n returns the final position. If the initial position is already inside the box, no segments\n are added. If the half-ray formed by the initial position and the propagation direction\n does not intersect the box, the function returns some arbitrary position outside the box.\n The small value specified by \\em eps is added to the path length beyond the intersection\n point so that the final position is well inside the box, guarding against rounding errors.\n *\/\n Position moveInside(const Box &box, double eps);\n\n \/** This function returns the number of cells crossed along the path. *\/\n int size() const { return _v.size(); }\n\n \/** This function returns the cell number \\f$m\\f$ for segment $i$ in the path. *\/\n int m(int i) const { return _v[i].m; }\n\n \/** This function returns the path length covered within the cell in segment $i$ in the path.\n *\/\n double ds(int i) const { return _v[i].ds; }\n\n \/** This function returns the path length covered from the initial position of the path until\n the end point of the cell in segment $i$ in the path. *\/\n double s(int i) const { return _v[i].s; }\n\n \/\/ ------- Handling data on optical depth -------\n\n \/** This function calculates the optical depth for the specified distance along the path (or,\n if the second argument is missing, for the complete path), using the path segment lengths\n \\f$\\Delta s_i\\f$ already stored within the path object, and the multiplication factors\n \\f$(\\kappa\\rho)_{m_i}\\f$ provided by the caller through a call-back function, where\n \\f$m_i\\f$ is the number of the dust cell being crossed in path segment \\f$i\\f$. The\n call-back function must have the signature \"double kapparho(int m)\". The optical depth\n information in the path is neither used nor stored. *\/\n template double opticalDepth(Functor kapparho, double distance=DBL_MAX) const\n {\n int N = _v.size();\n double tau = 0;\n for (int i=0; i distance) break;\n }\n return tau;\n }\n\n \/** This function calculates and stores the optical depth details for the path \\f[\n (\\Delta\\tau)_i = (\\Delta s)_i \\times (\\kappa\\rho)_{m_i}, \\f] \\f[ \\tau_i = \\sum_{j=0}^i\n (\\Delta\\tau)_j,\\f] using the path segment lengths \\f$\\Delta s_i\\f$ already stored within\n the path object, and the multiplication factors \\f$(\\kappa\\rho)_{m_i}\\f$ provided by the\n caller through a call-back function, where \\f$m_i\\f$ is the number of the dust cell being\n crossed in path segment \\f$i\\f$. The call-back function must have the signature\n \"double kapparho(int m)\". *\/\n template inline void fillOpticalDepth(Functor kapparho)\n {\n int N = _v.size();\n double tau = 0;\n for (int i=0; i _v;\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#endif \/\/ DUSTGRIDPATH_HPP\nVery minor changes in documentation of DustGridPath class\/*\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/ SKIRT -- an advanced radiative transfer code \/\/\/\/\n\/\/\/\/ © Astronomical Observatory, Ghent University \/\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ *\/\n\n#ifndef DUSTGRIDPATH_HPP\n#define DUSTGRIDPATH_HPP\n\n#include \n#include \n#include \"Direction.hpp\"\n#include \"Position.hpp\"\nclass Box;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/** A DustGridPath object contains the details of a path through a dust grid structure. Given a\n dust grid structure, i.e. an object of a DustGridStucture subclass, a starting position\n \\f${\\bf{r}}\\f$ and a propagation direction \\f${\\bf{k}}\\f$, one can calculate the path through\n the dust grid structure. A DustGridPath object keeps record of all the cells that are crossed\n by this path, together with the physical path length \\f$\\Delta s\\f$ covered within each cell,\n and the path length \\f$s\\f$ covered along the entire path up to the end of the cell. Given\n additional information about the dust properties in each cell (at a particular wavelength), one\n can also calculate optical depth information for the path. A DustGridPath object keeps record\n of the optical depth \\f$\\Delta\\tau\\f$ along the path segment within each cell, and the optical\n depth \\f$\\tau\\f$ along the entire path up to the end of the cell. *\/\nclass DustGridPath\n{\npublic:\n\n \/\/ ------- Constructors; handling position and directions -------\n\n \/** This constructor creates an empty path with the specified initial position and propagation\n direction. *\/\n DustGridPath(const Position& bfr, const Direction& bfk);\n\n \/** This constructor creates an empty path with the initial position and propagation direction\n initialized to null values. After using this constructor, invoke the setPosition() and\n setDirection() functions to set these properties to appropriate values. *\/\n DustGridPath();\n\n \/** This function sets the initial position of the path to a new value. *\/\n void setPosition(const Position& bfr) { _bfr = bfr; }\n\n \/** This function sets the propagation direction along the path to a new value. *\/\n void setDirection(const Direction& bfk) { _bfk = bfk; }\n\n \/** This function returns the initial position of the path. *\/\n Position position() const { return _bfr; }\n\n \/** This function returns the propagation direction along the path. *\/\n Direction direction() const { return _bfk; }\n\n \/\/ ------- Handling geometric data on path segments -------\n\n \/** This function removes all path segments, resulting in an empty path with the original\n initial position and propagation direction. *\/\n void clear();\n\n \/** This function adds a segment in cell \\f$m\\f$ with length \\f$\\Delta s\\f$ to the path,\n assuming \\f$\\Delta s>0\\f$. Otherwise the function does nothing. *\/\n void addSegment(int m, double ds);\n\n \/** This function adds the segments to the path that are needed to move the initial position\n along the propagation direction (both specified in the constructor) inside a given box, and\n returns the final position. If the initial position is already inside the box, no segments\n are added. If the half-ray formed by the initial position and the propagation direction\n does not intersect the box, the function returns some arbitrary position outside the box.\n The small value specified by \\em eps is added to the path length beyond the intersection\n point so that the final position is well inside the box, guarding against rounding errors.\n *\/\n Position moveInside(const Box &box, double eps);\n\n \/** This function returns the number of cells crossed along the path. *\/\n int size() const { return _v.size(); }\n\n \/** This function returns the cell number \\f$m\\f$ for segment \\f$i\\f$ in the path. *\/\n int m(int i) const { return _v[i].m; }\n\n \/** This function returns the path length covered within the cell in segment \\f$i\\f$ in the path.\n *\/\n double ds(int i) const { return _v[i].ds; }\n\n \/** This function returns the path length covered from the initial position of the path until\n the end point of the cell in segment \\f$i\\f$ in the path. *\/\n double s(int i) const { return _v[i].s; }\n\n \/\/ ------- Handling data on optical depth -------\n\n \/** This function calculates the optical depth for the specified distance along the path (or,\n if the second argument is missing, for the complete path), using the path segment lengths\n \\f$\\Delta s_i\\f$ already stored within the path object, and the multiplication factors\n \\f$(\\kappa\\rho)_{m_i}\\f$ provided by the caller through a call-back function, where\n \\f$m_i\\f$ is the number of the dust cell being crossed in path segment \\f$i\\f$. The\n call-back function must have the signature \"double kapparho(int m)\". The optical depth\n information in the path is neither used nor stored. *\/\n template double opticalDepth(Functor kapparho, double distance=DBL_MAX) const\n {\n int N = _v.size();\n double tau = 0;\n for (int i=0; i distance) break;\n }\n return tau;\n }\n\n \/** This function calculates and stores the optical depth details for the path \\f[\n (\\Delta\\tau)_i = (\\Delta s)_i \\times (\\kappa\\rho)_{m_i}, \\f] \\f[ \\tau_i = \\sum_{j=0}^i\n (\\Delta\\tau)_j,\\f] using the path segment lengths \\f$\\Delta s_i\\f$ already stored within\n the path object, and the multiplication factors \\f$(\\kappa\\rho)_{m_i}\\f$ provided by the\n caller through a call-back function, where \\f$m_i\\f$ is the number of the dust cell being\n crossed in path segment \\f$i\\f$. The call-back function must have the signature\n \"double kapparho(int m)\". *\/\n template inline void fillOpticalDepth(Functor kapparho)\n {\n int N = _v.size();\n double tau = 0;\n for (int i=0; i _v;\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#endif \/\/ DUSTGRIDPATH_HPP\n<|endoftext|>"} {"text":"#include \"ResourceGUI.h\"\n#include \"IO\/XmlWorld.h\"\n#include \"utils\/stringutils.h\"\n#include \"utils\/ioutils.h\"\n\nResourceGUIBackend::ResourceGUIBackend(RobotWorld* world,ResourceManager* library)\n :WorldGUIBackend(world),resources(library)\n{\n}\n\n\ninline bool LoadResources(const char* fn,ResourceTree& lib)\n{\n size_t origsize = lib.topLevel.size();\n if(!lib.LoadFolder(fn)) {\n lib.TreeFromLibrary();\n fprintf(stderr,\"Warning, couldn't load library %s\\n\",fn);\n return false;\n }\n else {\n printf(\"Loaded %d items from %s\\n\",lib.topLevel.size()-origsize,fn);\n return true;\n }\n return false;\n}\n\ninline bool LoadResources(TiXmlElement* e,ResourceTree& lib)\n{\n size_t origsize = lib.topLevel.size();\n if(!lib.library.Load(e)) {\n fprintf(stderr,\"Warning, couldn't load library from XML\\n\");\n lib.TreeFromLibrary();\n return false;\n }\n else {\n lib.TreeFromLibrary();\n printf(\"Loaded %d items from XML\\n\",lib.topLevel.size()-origsize);\n return true;\n }\n return false;\n}\n\ninline bool LoadItem(const char* fn,ResourceTree& lib)\n{\n ResourceNodePtr r=lib.LoadFile(fn);\n if(r != NULL) {\n printf(\"Loaded %s as type %s\\n\",fn,r->Type());\n return true;\n }\n else {\n fprintf(stderr,\"Couldn't load resource file %s\\n\",fn);\n return false;\n }\n}\n\n\nbool ResourceGUIBackend::LoadCommandLine(int argc,const char** argv)\n{\n for(int i=1;iValue(),\"world\")) {\n\t XmlWorld xmlWorld;\n\t if(!xmlWorld.Load(doc.RootElement(),GetFilePath(argv[i]))) {\n\t printf(\"Error loading world file %s\\n\",argv[i]);\n\t return 0;\n\t }\n\t if(!xmlWorld.GetWorld(*world)) {\n\t printf(\"Error loading world from %s\\n\",argv[i]);\n\t return 0;\n\t }\n\t}\n\telse if(0 == strcmp(doc.RootElement()->Value(),\"resource_library\")) {\n\t LoadResources(doc.RootElement(),*resources);\n\t}\n\telse {\n\t if(!LoadItem(argv[i],*resources))\n\t return 0;\n\t}\n }\n else {\n\t\/\/try loading into the world\n\tconst char* ext = FileExtension(argv[i]);\n\tif(world->CanLoadElementExt(ext) && world->LoadElement(argv[i])>= 0) {\n\t \/\/loaded successfully\n\t}\n\telse {\n\t \/\/failed, now try resource library load\n\t if(!LoadItem(argv[i],*resources))\n\t return 0;\n\t}\n }\n }\n }\n return true;\n}\n\n\n\nResourceNodePtr ResourceGUIBackend::Add(ResourcePtr r)\n{\n if(resources == NULL) return NULL;\n ResourceNode* parent = (resources->selected != NULL ? resources->selected->parent : NULL);\n if(r->name.empty()) {\n stringstream ss;\n if(parent == NULL){\n\tss<Type()<<\"[\"<topLevel.size()<<\"]\";\n }\n else{\n\tss<Type()<<\"[\"<children.size()<<\"]\";\n }\n r->name = ss.str();\n }\n \/\/last_added = resources->AddChildOfSelected(r);\n if(parent == NULL)\n last_added = resources->Add(r);\n else\n last_added = parent->AddChild(r);\n \/\/SendCommand(\"new_resource\", r->Type()+string(\" \")+r->name);\n SendCommand(\"new_resource\", last_added->Identifier());\n return last_added;\n}\n\nResourceNodePtr ResourceGUIBackend::Add(const string& name,const string& type)\n{\n if(resources->library.knownTypes.count(type)==0) return NULL;\n ResourcePtr r=resources->library.knownTypes[type][0]->Make();\n r->name = name;\n return Add(r);\n}\n\nvoid ResourceGUIBackend::SaveCur(const string& file)\n{\n resources->SaveSelected(file);\n}\n\nbool ResourceGUIBackend::LoadNew(const string& file)\n{\n return resources->LoadFile(file) != NULL;\n}\n\nvoid ResourceGUIBackend::SaveAll(const string& path)\n{\n resources->SaveFolder(path);\n}\n\nbool ResourceGUIBackend::LoadAll(const string& path)\n{\n if(!resources->LoadFolder(path)) {\n fprintf(stderr,\"Error loading resources from %s\\n\",path.c_str());\n return false;\n }\n else {\n fprintf(stderr,\"Loaded all resources from %s\\n\",path.c_str());\n return true;\n }\n return false;\n}\n\n\nvoid ResourceGUIBackend::SetLastActive()\n{\n if(last_added == NULL) {\n resources->selected = NULL;\n }\n else {\n resources->selected = last_added;\n }\n}\n\n\nvoid ResourceGUIBackend::SetActive(const string& identifier)\n{\n resources->Select(identifier);\n}\n\nvoid ResourceGUIBackend::SetPathTime(double time){\n viewResource.pathTime = time;\n}\n\nbool ResourceGUIBackend::OnCommand(const string& cmd,const string& args)\n{\n if(cmd == \"set_resource\") {\n resources->Select(args);\n return true; \n }\n else if(cmd == \"get_resource\") {\n stringstream ss;\n ss<selected->Identifier();\n SendCommand(\"current_resource\",ss.str());\n return true;\n }\n else if(cmd == \"set_resource_name\") {\n if(resources->selected) resources->selected->resource->name = args;\n printf(\"Updating name to %s\\n\",args.c_str());\n }\n else if(cmd == \"delete_resource\") {\n resources->DeleteSelected();\n }\n else if(cmd == \"add_resource\") {\n string type,name;\n stringstream ss(args);\n if(!SafeInputString(ss,type)) {\n cout<<\"Error reading resource type from args \\\"\"<Identifier());\n }\n }\n else if(cmd == \"save_resource\") {\n SaveCur(args);\n }\n else if(cmd == \"load_resource_dir\") {\n if(LoadAll(args)) {\n SendCommand(\"refresh_resources\",\"\");\n }\n }\n else if(cmd == \"save_resource_dir\") {\n SaveAll(args);\n }\n else if(cmd == \"convert\") {\n ResourcePtr r=CurrentResource();\n ResourcePtr res = CastResource(r,args.c_str());\n if(!res) {\n fprintf(stderr,\"Conversion failed\\n\");\n return true;\n }\n res->name = r->name;\n Add(res); \n SetLastActive();\n }\n else if(cmd == \"extract\") {\n ResourcePtr r=CurrentResource();\n if(!r) return true;\n vector res = ExtractResources(r,args.c_str());\n for(size_t i=0;i>time;\n SetPathTime(time);\n }\n else {\n return WorldGUIBackend::OnCommand(cmd,args);\n }\n return true;\n}\n\n\nResourcePtr ResourceGUIBackend::CurrentResource()\n{\n if(resources && resources->selected)\n return resources->selected->resource;\n else return 0;\n}\n\nvoid ResourceGUIBackend::RenderCurResource()\n{\n \/*\n ResourcePtr current = CurrentResource();\n if(current)\n viewResource.DrawGL(current);\n *\/\n \/\/separate open?\n viewResource.SetRobot(world->robots[0].robot);\n if(resources && resources->selected)\n viewResource.DrawGL(resources->selected->resource);\n}\nFixed path refresh#include \"ResourceGUI.h\"\n#include \"IO\/XmlWorld.h\"\n#include \"utils\/stringutils.h\"\n#include \"utils\/ioutils.h\"\n\nResourceGUIBackend::ResourceGUIBackend(RobotWorld* world,ResourceManager* library)\n :WorldGUIBackend(world),resources(library)\n{\n}\n\n\ninline bool LoadResources(const char* fn,ResourceTree& lib)\n{\n size_t origsize = lib.topLevel.size();\n if(!lib.LoadFolder(fn)) {\n lib.TreeFromLibrary();\n fprintf(stderr,\"Warning, couldn't load library %s\\n\",fn);\n return false;\n }\n else {\n printf(\"Loaded %d items from %s\\n\",lib.topLevel.size()-origsize,fn);\n return true;\n }\n return false;\n}\n\ninline bool LoadResources(TiXmlElement* e,ResourceTree& lib)\n{\n size_t origsize = lib.topLevel.size();\n if(!lib.library.Load(e)) {\n fprintf(stderr,\"Warning, couldn't load library from XML\\n\");\n lib.TreeFromLibrary();\n return false;\n }\n else {\n lib.TreeFromLibrary();\n printf(\"Loaded %d items from XML\\n\",lib.topLevel.size()-origsize);\n return true;\n }\n return false;\n}\n\ninline bool LoadItem(const char* fn,ResourceTree& lib)\n{\n ResourceNodePtr r=lib.LoadFile(fn);\n if(r != NULL) {\n printf(\"Loaded %s as type %s\\n\",fn,r->Type());\n return true;\n }\n else {\n fprintf(stderr,\"Couldn't load resource file %s\\n\",fn);\n return false;\n }\n}\n\n\nbool ResourceGUIBackend::LoadCommandLine(int argc,const char** argv)\n{\n for(int i=1;iValue(),\"world\")) {\n\t XmlWorld xmlWorld;\n\t if(!xmlWorld.Load(doc.RootElement(),GetFilePath(argv[i]))) {\n\t printf(\"Error loading world file %s\\n\",argv[i]);\n\t return 0;\n\t }\n\t if(!xmlWorld.GetWorld(*world)) {\n\t printf(\"Error loading world from %s\\n\",argv[i]);\n\t return 0;\n\t }\n\t}\n\telse if(0 == strcmp(doc.RootElement()->Value(),\"resource_library\")) {\n\t LoadResources(doc.RootElement(),*resources);\n\t}\n\telse {\n\t if(!LoadItem(argv[i],*resources))\n\t return 0;\n\t}\n }\n else {\n\t\/\/try loading into the world\n\tconst char* ext = FileExtension(argv[i]);\n\tif(world->CanLoadElementExt(ext) && world->LoadElement(argv[i])>= 0) {\n\t \/\/loaded successfully\n\t}\n\telse {\n\t \/\/failed, now try resource library load\n\t if(!LoadItem(argv[i],*resources))\n\t return 0;\n\t}\n }\n }\n }\n return true;\n}\n\n\n\nResourceNodePtr ResourceGUIBackend::Add(ResourcePtr r)\n{\n if(resources == NULL) return NULL;\n ResourceNode* parent = (resources->selected != NULL ? resources->selected->parent : NULL);\n if(r->name.empty()) {\n stringstream ss;\n if(parent == NULL){\n\tss<Type()<<\"[\"<topLevel.size()<<\"]\";\n }\n else{\n\tss<Type()<<\"[\"<children.size()<<\"]\";\n }\n r->name = ss.str();\n }\n \/\/last_added = resources->AddChildOfSelected(r);\n if(parent == NULL)\n last_added = resources->Add(r);\n else\n last_added = parent->AddChild(r);\n \/\/SendCommand(\"new_resource\", r->Type()+string(\" \")+r->name);\n SendCommand(\"new_resource\", last_added->Identifier());\n return last_added;\n}\n\nResourceNodePtr ResourceGUIBackend::Add(const string& name,const string& type)\n{\n if(resources->library.knownTypes.count(type)==0) return NULL;\n ResourcePtr r=resources->library.knownTypes[type][0]->Make();\n r->name = name;\n return Add(r);\n}\n\nvoid ResourceGUIBackend::SaveCur(const string& file)\n{\n resources->SaveSelected(file);\n}\n\nbool ResourceGUIBackend::LoadNew(const string& file)\n{\n return resources->LoadFile(file) != NULL;\n}\n\nvoid ResourceGUIBackend::SaveAll(const string& path)\n{\n resources->SaveFolder(path);\n}\n\nbool ResourceGUIBackend::LoadAll(const string& path)\n{\n if(!resources->LoadFolder(path)) {\n fprintf(stderr,\"Error loading resources from %s\\n\",path.c_str());\n return false;\n }\n else {\n fprintf(stderr,\"Loaded all resources from %s\\n\",path.c_str());\n return true;\n }\n return false;\n}\n\n\nvoid ResourceGUIBackend::SetLastActive()\n{\n if(last_added == NULL) {\n resources->selected = NULL;\n }\n else {\n resources->selected = last_added;\n }\n}\n\n\nvoid ResourceGUIBackend::SetActive(const string& identifier)\n{\n resources->Select(identifier);\n}\n\nvoid ResourceGUIBackend::SetPathTime(double time){\n viewResource.pathTime = time;\n}\n\nbool ResourceGUIBackend::OnCommand(const string& cmd,const string& args)\n{\n if(cmd == \"set_resource\") {\n resources->Select(args);\n return true; \n }\n else if(cmd == \"get_resource\") {\n stringstream ss;\n ss<selected->Identifier();\n SendCommand(\"current_resource\",ss.str());\n return true;\n }\n else if(cmd == \"set_resource_name\") {\n if(resources->selected) resources->selected->resource->name = args;\n printf(\"Updating name to %s\\n\",args.c_str());\n }\n else if(cmd == \"delete_resource\") {\n resources->DeleteSelected();\n }\n else if(cmd == \"add_resource\") {\n string type,name;\n stringstream ss(args);\n if(!SafeInputString(ss,type)) {\n cout<<\"Error reading resource type from args \\\"\"<Identifier());\n }\n }\n else if(cmd == \"save_resource\") {\n SaveCur(args);\n }\n else if(cmd == \"load_resource_dir\") {\n if(LoadAll(args)) {\n SendCommand(\"refresh_resources\",\"\");\n }\n }\n else if(cmd == \"save_resource_dir\") {\n SaveAll(args);\n }\n else if(cmd == \"convert\") {\n ResourcePtr r=CurrentResource();\n ResourcePtr res = CastResource(r,args.c_str());\n if(!res) {\n fprintf(stderr,\"Conversion failed\\n\");\n return true;\n }\n res->name = r->name;\n Add(res); \n SetLastActive();\n }\n else if(cmd == \"extract\") {\n ResourcePtr r=CurrentResource();\n if(!r) return true;\n vector res = ExtractResources(r,args.c_str());\n for(size_t i=0;i>time;\n SetPathTime(time);\n SendRefresh();\n }\n else {\n return WorldGUIBackend::OnCommand(cmd,args);\n }\n return true;\n}\n\n\nResourcePtr ResourceGUIBackend::CurrentResource()\n{\n if(resources && resources->selected)\n return resources->selected->resource;\n else return 0;\n}\n\nvoid ResourceGUIBackend::RenderCurResource()\n{\n \/*\n ResourcePtr current = CurrentResource();\n if(current)\n viewResource.DrawGL(current);\n *\/\n \/\/separate open?\n viewResource.SetRobot(world->robots[0].robot);\n if(resources && resources->selected)\n viewResource.DrawGL(resources->selected->resource);\n}\n<|endoftext|>"} {"text":"#include \"stdafx.h\"\r\n#include \"CtrlrUtilities.h\"\r\n#include \"CtrlrPanel\/CtrlrPanel.h\"\r\n#include \"CtrlrManager\/CtrlrManager.h\"\r\n#include \"CtrlrFontPropertyComponent.h\"\r\n#include \"CtrlrProcessor.h\"\r\n\r\nCtrlrFontPropertyComponent::CtrlrFontPropertyComponent (const Value &_valueToControl, CtrlrPanel *_owner)\r\n : valueToControl(_valueToControl), owner(_owner),\r\n typeface (0),\r\n fontBold (0),\r\n fontItalic (0),\r\n fontUnderline (0),\r\n fontSize (0),\r\n\t kerning(0),\r\n\t horizontalScale(0)\r\n{\r\n addAndMakeVisible (typeface = new ComboBox (String::empty));\r\n typeface->setEditableText (false);\r\n typeface->setJustificationType (Justification::centredLeft);\r\n typeface->setTextWhenNothingSelected (L\"\");\r\n typeface->setTextWhenNoChoicesAvailable (L\"\");\r\n typeface->addListener (this);\r\n\r\n addAndMakeVisible (fontBold = new ImageButton (String::empty));\r\n fontBold->setTooltip (L\"Bold\");\r\n fontBold->setButtonText (L\"new button\");\r\n fontBold->addListener (this);\r\n\r\n fontBold->setImages (false, true, true,\r\n IMAGE (ico_font_bold_png), 0.5000f, Colour (0x0),\r\n IMAGE (ico_font_bold_png), 0.7500f, Colour (0xa0ffffff),\r\n IMAGE (ico_font_bold_png), 1.0000f, Colour (0x0));\r\n addAndMakeVisible (fontItalic = new ImageButton (String::empty));\r\n fontItalic->setTooltip (L\"Italic\");\r\n fontItalic->setButtonText (L\"new button\");\r\n fontItalic->addListener (this);\r\n\r\n fontItalic->setImages (false, true, true,\r\n IMAGE (ico_font_italic_png), 0.5000f, Colour (0x0),\r\n IMAGE (ico_font_italic_png), 0.7500f, Colour (0xa0ffffff),\r\n IMAGE (ico_font_italic_png), 1.0000f, Colour (0x0));\r\n addAndMakeVisible (fontUnderline = new ImageButton (String::empty));\r\n fontUnderline->setTooltip (L\"Underline\");\r\n fontUnderline->setButtonText (L\"new button\");\r\n fontUnderline->addListener (this);\r\n\r\n fontUnderline->setImages (false, true, true,\r\n IMAGE (ico_font_underline_png), 0.5000f, Colour (0x0),\r\n IMAGE (ico_font_underline_png), 0.7500f, Colour (0xa0ffffff),\r\n IMAGE (ico_font_underline_png), 1.0000f, Colour (0x0));\r\n\r\n addAndMakeVisible (fontSize = new Slider (String::empty));\r\n\tfontSize->setLookAndFeel (this);\r\n fontSize->setTooltip (L\"Size\");\r\n fontSize->setRange (1, 999, 1);\r\n fontSize->setSliderStyle (Slider::RotaryVerticalDrag);\r\n fontSize->setTextBoxStyle (Slider::TextBoxRight, false, 34, 16);\r\n fontSize->addListener (this);\r\n\r\n\taddAndMakeVisible (horizontalScale = new Slider (String::empty));\r\n\thorizontalScale->setLookAndFeel (this);\r\n horizontalScale->setTooltip (L\"Horizontal Scale\");\r\n horizontalScale->setRange (0.0, 10.0, 0.01);\r\n horizontalScale->setSliderStyle (Slider::RotaryVerticalDrag);\r\n horizontalScale->setTextBoxStyle (Slider::TextBoxRight, false, 34, 16);\r\n horizontalScale->addListener (this);\r\n\r\n\taddAndMakeVisible (kerning = new Slider (String::empty));\r\n kerning->setLookAndFeel (this);\r\n\tkerning->setTooltip (L\"Extra Kerning\");\r\n kerning->setRange (0.0, 10.0, 0.01);\r\n kerning->setSliderStyle (Slider::RotaryVerticalDrag);\r\n kerning->setTextBoxStyle (Slider::TextBoxRight, false, 34, 16);\r\n kerning->addListener (this);\r\n\r\n\tfontBold->setClickingTogglesState (true);\r\n\tfontBold->setMouseCursor (MouseCursor::PointingHandCursor);\r\n\tfontItalic->setClickingTogglesState (true);\r\n\tfontItalic->setMouseCursor (MouseCursor::PointingHandCursor);\r\n\tfontUnderline->setClickingTogglesState (true);\r\n\tfontUnderline->setMouseCursor (MouseCursor::PointingHandCursor);\r\n\r\n owner->getCtrlrManagerOwner().getFontManager().fillCombo (*typeface, true, true, true, true);\r\n\r\n setSize (300, 32);\r\n}\r\n\r\nCtrlrFontPropertyComponent::~CtrlrFontPropertyComponent()\r\n{\r\n deleteAndZero (typeface);\r\n deleteAndZero (fontBold);\r\n deleteAndZero (fontItalic);\r\n deleteAndZero (fontUnderline);\r\n deleteAndZero (fontSize);\r\n\tdeleteAndZero (kerning);\r\n\tdeleteAndZero (horizontalScale);\r\n}\r\n\r\nvoid CtrlrFontPropertyComponent::resized()\r\n{\r\n typeface->setBounds (0, 0, getWidth() * 0.4f, getHeight());\r\n\r\n\tfontBold->setBounds (getWidth() * 0.4f,\t\t\t\t\t\t\t\t\t0, getWidth() * 0.05f,\tgetHeight());\r\n fontItalic->setBounds ((getWidth() * 0.4f) + (getWidth() * 0.05f),\t\t0, getWidth() * 0.05f,\tgetHeight());\r\n\tfontUnderline->setBounds ((getWidth() * 0.4f) + 2*(getWidth() * 0.05f), 0, getWidth() * 0.05f,\tgetHeight());\r\n\r\n fontSize->setBounds\t\t\t((getWidth() * 0.4f) + 3*(getWidth() * 0.05f),\t\t\t\t\t\t\t0, getWidth() * 0.14f,\tgetHeight());\r\n\thorizontalScale->setBounds\t((getWidth() * 0.4f) + 3*(getWidth() * 0.05f) + (getWidth() * 0.14f),\t0, getWidth() * 0.14f,\tgetHeight());\r\n\tkerning->setBounds\t\t\t((getWidth() * 0.4f) + 3*(getWidth() * 0.05f) + 2*(getWidth() * 0.14f),\t0, getWidth() * 0.14f,\tgetHeight());\r\n}\r\n\r\nvoid CtrlrFontPropertyComponent::comboBoxChanged (ComboBox* comboBoxThatHasChanged)\r\n{\r\n\tvalueToControl = owner->getCtrlrManagerOwner().getFontManager().getStringFromFont(getFont());\r\n}\r\n\r\nvoid CtrlrFontPropertyComponent::buttonClicked (Button* buttonThatWasClicked)\r\n{\r\n if (buttonThatWasClicked == fontBold || buttonThatWasClicked == fontItalic || buttonThatWasClicked == fontUnderline)\r\n {\r\n\t\tvalueToControl = owner->getCtrlrManagerOwner().getFontManager().getStringFromFont(getFont());\r\n }\r\n}\r\n\r\nvoid CtrlrFontPropertyComponent::sliderValueChanged (Slider* sliderThatWasMoved)\r\n{\r\n\tvalueToControl = owner->getCtrlrManagerOwner().getFontManager().getStringFromFont(getFont());\r\n}\r\n\r\nvoid CtrlrFontPropertyComponent::refresh()\r\n{\r\n\tFont font = owner->getCtrlrManagerOwner().getFontManager().getFontFromString(valueToControl.toString());\r\n\ttypeface->setText (font.getTypefaceName(), sendNotification);\r\n\tfontSize->setValue (font.getHeight(), dontSendNotification);\r\n\tfontBold->setToggleState (font.isBold(), sendNotification);\r\n\tfontItalic->setToggleState (font.isItalic(), sendNotification);\r\n\tfontUnderline->setToggleState (font.isUnderlined(), sendNotification);\r\n\tkerning->setValue (font.getExtraKerningFactor(), dontSendNotification);\r\n\thorizontalScale->setValue (font.getHorizontalScale(), dontSendNotification);\r\n}\r\n\r\nFont CtrlrFontPropertyComponent::getFont()\r\n{\r\n\tFont font;\r\n\r\n\tif (typeface)\r\n\t\tfont.setTypefaceName (typeface->getText());\r\n\telse\r\n\t\treturn (font);\r\n\r\n\tfont.setHeight (fontSize->getValue());\r\n\tfont.setBold (fontBold->getToggleState());\r\n\tfont.setItalic (fontItalic->getToggleState());\r\n\tfont.setUnderline (fontUnderline->getToggleState());\r\n\tfont.setExtraKerningFactor (kerning->getValue());\r\n\tfont.setHorizontalScale (horizontalScale->getValue());\r\n\treturn (font);\r\n}\r\n\r\nLabel* CtrlrFontPropertyComponent::createSliderTextBox (Slider& slider)\r\n{\r\n Label* const l = new CtrlrFontPropertyComponent::SliderLabelComp();\r\n\r\n\tl->setFont (Font(10.0f,Font::bold));\r\n l->setJustificationType (Justification::centred);\r\n\r\n l->setColour (Label::textColourId, slider.findColour (Slider::textBoxTextColourId));\r\n\r\n l->setColour (Label::backgroundColourId,\r\n (slider.getSliderStyle() == Slider::LinearBar || slider.getSliderStyle() == Slider::LinearBarVertical)\r\n ? Colours::transparentBlack\r\n : slider.findColour (Slider::textBoxBackgroundColourId));\r\n l->setColour (Label::outlineColourId, slider.findColour (Slider::textBoxOutlineColourId));\r\n\r\n l->setColour (TextEditor::textColourId, slider.findColour (Slider::textBoxTextColourId));\r\n\r\n l->setColour (TextEditor::backgroundColourId,\r\n slider.findColour (Slider::textBoxBackgroundColourId)\r\n .withAlpha ((slider.getSliderStyle() == Slider::LinearBar || slider.getSliderStyle() == Slider::LinearBarVertical)\r\n ? 0.7f : 1.0f));\r\n\r\n l->setColour (TextEditor::outlineColourId, slider.findColour (Slider::textBoxOutlineColourId));\r\n\r\n return l;\r\n}\r\nFixed font attribute setting order to prevent multiple modifications of the ValueTree and underlying change notifications (i.e. several modifications of font property when italic status is set while horizontal scale does not yet reflect the actual font's value)#include \"stdafx.h\"\r\n#include \"CtrlrUtilities.h\"\r\n#include \"CtrlrPanel\/CtrlrPanel.h\"\r\n#include \"CtrlrManager\/CtrlrManager.h\"\r\n#include \"CtrlrFontPropertyComponent.h\"\r\n#include \"CtrlrProcessor.h\"\r\n\r\nCtrlrFontPropertyComponent::CtrlrFontPropertyComponent (const Value &_valueToControl, CtrlrPanel *_owner)\r\n : valueToControl(_valueToControl), owner(_owner),\r\n typeface (0),\r\n fontBold (0),\r\n fontItalic (0),\r\n fontUnderline (0),\r\n fontSize (0),\r\n\t kerning(0),\r\n\t horizontalScale(0)\r\n{\r\n addAndMakeVisible (typeface = new ComboBox (String::empty));\r\n typeface->setEditableText (false);\r\n typeface->setJustificationType (Justification::centredLeft);\r\n typeface->setTextWhenNothingSelected (L\"\");\r\n typeface->setTextWhenNoChoicesAvailable (L\"\");\r\n typeface->addListener (this);\r\n\r\n addAndMakeVisible (fontBold = new ImageButton (String::empty));\r\n fontBold->setTooltip (L\"Bold\");\r\n fontBold->setButtonText (L\"new button\");\r\n fontBold->addListener (this);\r\n\r\n fontBold->setImages (false, true, true,\r\n IMAGE (ico_font_bold_png), 0.5000f, Colour (0x0),\r\n IMAGE (ico_font_bold_png), 0.7500f, Colour (0xa0ffffff),\r\n IMAGE (ico_font_bold_png), 1.0000f, Colour (0x0));\r\n addAndMakeVisible (fontItalic = new ImageButton (String::empty));\r\n fontItalic->setTooltip (L\"Italic\");\r\n fontItalic->setButtonText (L\"new button\");\r\n fontItalic->addListener (this);\r\n\r\n fontItalic->setImages (false, true, true,\r\n IMAGE (ico_font_italic_png), 0.5000f, Colour (0x0),\r\n IMAGE (ico_font_italic_png), 0.7500f, Colour (0xa0ffffff),\r\n IMAGE (ico_font_italic_png), 1.0000f, Colour (0x0));\r\n addAndMakeVisible (fontUnderline = new ImageButton (String::empty));\r\n fontUnderline->setTooltip (L\"Underline\");\r\n fontUnderline->setButtonText (L\"new button\");\r\n fontUnderline->addListener (this);\r\n\r\n fontUnderline->setImages (false, true, true,\r\n IMAGE (ico_font_underline_png), 0.5000f, Colour (0x0),\r\n IMAGE (ico_font_underline_png), 0.7500f, Colour (0xa0ffffff),\r\n IMAGE (ico_font_underline_png), 1.0000f, Colour (0x0));\r\n\r\n addAndMakeVisible (fontSize = new Slider (String::empty));\r\n\tfontSize->setLookAndFeel (this);\r\n fontSize->setTooltip (L\"Size\");\r\n fontSize->setRange (1, 999, 1);\r\n fontSize->setSliderStyle (Slider::RotaryVerticalDrag);\r\n fontSize->setTextBoxStyle (Slider::TextBoxRight, false, 34, 16);\r\n fontSize->addListener (this);\r\n\r\n\taddAndMakeVisible (horizontalScale = new Slider (String::empty));\r\n\thorizontalScale->setLookAndFeel (this);\r\n horizontalScale->setTooltip (L\"Horizontal Scale\");\r\n horizontalScale->setRange (0.0, 10.0, 0.01);\r\n horizontalScale->setSliderStyle (Slider::RotaryVerticalDrag);\r\n horizontalScale->setTextBoxStyle (Slider::TextBoxRight, false, 34, 16);\r\n horizontalScale->addListener (this);\r\n\r\n\taddAndMakeVisible (kerning = new Slider (String::empty));\r\n kerning->setLookAndFeel (this);\r\n\tkerning->setTooltip (L\"Extra Kerning\");\r\n kerning->setRange (0.0, 10.0, 0.01);\r\n kerning->setSliderStyle (Slider::RotaryVerticalDrag);\r\n kerning->setTextBoxStyle (Slider::TextBoxRight, false, 34, 16);\r\n kerning->addListener (this);\r\n\r\n\tfontBold->setClickingTogglesState (true);\r\n\tfontBold->setMouseCursor (MouseCursor::PointingHandCursor);\r\n\tfontItalic->setClickingTogglesState (true);\r\n\tfontItalic->setMouseCursor (MouseCursor::PointingHandCursor);\r\n\tfontUnderline->setClickingTogglesState (true);\r\n\tfontUnderline->setMouseCursor (MouseCursor::PointingHandCursor);\r\n\r\n owner->getCtrlrManagerOwner().getFontManager().fillCombo (*typeface, true, true, true, true);\r\n\r\n setSize (300, 32);\r\n}\r\n\r\nCtrlrFontPropertyComponent::~CtrlrFontPropertyComponent()\r\n{\r\n deleteAndZero (typeface);\r\n deleteAndZero (fontBold);\r\n deleteAndZero (fontItalic);\r\n deleteAndZero (fontUnderline);\r\n deleteAndZero (fontSize);\r\n\tdeleteAndZero (kerning);\r\n\tdeleteAndZero (horizontalScale);\r\n}\r\n\r\nvoid CtrlrFontPropertyComponent::resized()\r\n{\r\n typeface->setBounds (0, 0, getWidth() * 0.4f, getHeight());\r\n\r\n\tfontBold->setBounds (getWidth() * 0.4f,\t\t\t\t\t\t\t\t\t0, getWidth() * 0.05f,\tgetHeight());\r\n fontItalic->setBounds ((getWidth() * 0.4f) + (getWidth() * 0.05f),\t\t0, getWidth() * 0.05f,\tgetHeight());\r\n\tfontUnderline->setBounds ((getWidth() * 0.4f) + 2*(getWidth() * 0.05f), 0, getWidth() * 0.05f,\tgetHeight());\r\n\r\n fontSize->setBounds\t\t\t((getWidth() * 0.4f) + 3*(getWidth() * 0.05f),\t\t\t\t\t\t\t0, getWidth() * 0.14f,\tgetHeight());\r\n\thorizontalScale->setBounds\t((getWidth() * 0.4f) + 3*(getWidth() * 0.05f) + (getWidth() * 0.14f),\t0, getWidth() * 0.14f,\tgetHeight());\r\n\tkerning->setBounds\t\t\t((getWidth() * 0.4f) + 3*(getWidth() * 0.05f) + 2*(getWidth() * 0.14f),\t0, getWidth() * 0.14f,\tgetHeight());\r\n}\r\n\r\nvoid CtrlrFontPropertyComponent::comboBoxChanged (ComboBox* comboBoxThatHasChanged)\r\n{\r\n\tvalueToControl = owner->getCtrlrManagerOwner().getFontManager().getStringFromFont(getFont());\r\n}\r\n\r\nvoid CtrlrFontPropertyComponent::buttonClicked (Button* buttonThatWasClicked)\r\n{\r\n if (buttonThatWasClicked == fontBold || buttonThatWasClicked == fontItalic || buttonThatWasClicked == fontUnderline)\r\n {\r\n\t\tvalueToControl = owner->getCtrlrManagerOwner().getFontManager().getStringFromFont(getFont());\r\n\t}\r\n}\r\n\r\nvoid CtrlrFontPropertyComponent::sliderValueChanged (Slider* sliderThatWasMoved)\r\n{\r\n\tvalueToControl = owner->getCtrlrManagerOwner().getFontManager().getStringFromFont(getFont());\r\n}\r\n\r\nvoid CtrlrFontPropertyComponent::refresh()\r\n{\r\n\tFont font = owner->getCtrlrManagerOwner().getFontManager().getFontFromString(valueToControl.toString());\r\n\ttypeface->setText (font.getTypefaceName(), sendNotification);\r\n\tfontSize->setValue (font.getHeight(), dontSendNotification);\r\n\tkerning->setValue(font.getExtraKerningFactor(), dontSendNotification);\r\n\thorizontalScale->setValue(font.getHorizontalScale(), dontSendNotification);\r\n\tfontBold->setToggleState (font.isBold(), sendNotification);\r\n\tfontItalic->setToggleState (font.isItalic(), sendNotification);\r\n\tfontUnderline->setToggleState (font.isUnderlined(), sendNotification);\r\n}\r\n\r\nFont CtrlrFontPropertyComponent::getFont()\r\n{\r\n\tFont font;\r\n\r\n\tif (typeface)\r\n\t\tfont.setTypefaceName (typeface->getText());\r\n\telse\r\n\t\treturn (font);\r\n\r\n\tfont.setHeight (fontSize->getValue());\r\n\tfont.setBold (fontBold->getToggleState());\r\n\tfont.setItalic (fontItalic->getToggleState());\r\n\tfont.setUnderline (fontUnderline->getToggleState());\r\n\tfont.setExtraKerningFactor (kerning->getValue());\r\n\tfont.setHorizontalScale (horizontalScale->getValue());\r\n\treturn (font);\r\n}\r\n\r\nLabel* CtrlrFontPropertyComponent::createSliderTextBox (Slider& slider)\r\n{\r\n Label* const l = new CtrlrFontPropertyComponent::SliderLabelComp();\r\n\r\n\tl->setFont (Font(10.0f,Font::bold));\r\n l->setJustificationType (Justification::centred);\r\n\r\n l->setColour (Label::textColourId, slider.findColour (Slider::textBoxTextColourId));\r\n\r\n l->setColour (Label::backgroundColourId,\r\n (slider.getSliderStyle() == Slider::LinearBar || slider.getSliderStyle() == Slider::LinearBarVertical)\r\n ? Colours::transparentBlack\r\n : slider.findColour (Slider::textBoxBackgroundColourId));\r\n l->setColour (Label::outlineColourId, slider.findColour (Slider::textBoxOutlineColourId));\r\n\r\n l->setColour (TextEditor::textColourId, slider.findColour (Slider::textBoxTextColourId));\r\n\r\n l->setColour (TextEditor::backgroundColourId,\r\n slider.findColour (Slider::textBoxBackgroundColourId)\r\n .withAlpha ((slider.getSliderStyle() == Slider::LinearBar || slider.getSliderStyle() == Slider::LinearBarVertical)\r\n ? 0.7f : 1.0f));\r\n\r\n l->setColour (TextEditor::outlineColourId, slider.findColour (Slider::textBoxOutlineColourId));\r\n\r\n return l;\r\n}\r\n<|endoftext|>"} {"text":"\/**\n * @copyright Copyright 2016 The J-PET Framework Authors. All rights reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may find a copy of the License in the LICENCE file.\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n * @file JPetWriter.cpp\n *\/\n\n#include \"JPetWriter.h\"\n#include \"..\/JPetUserInfoStructure\/JPetUserInfoStructure.h\"\n\n\nJPetWriter::JPetWriter(const char* p_fileName) :\n fFileName(p_fileName),\t\t\t\/\/ string z nazwą pliku\n fFile(0),\t\/\/ plik\n fIsBranchCreated(false),\n fTree(0)\n{\n fFile = new TFile(fFileName.c_str(), \"RECREATE\");\n if (!isOpen()) {\n ERROR(\"Could not open file to write.\");\n } else {\n fTree = new TTree(\"tree\", \"tree\");\n fTree->SetAutoSave(10000);\n }\n}\n\nJPetWriter::~JPetWriter()\n{\n if (isOpen()) {\n fTree->AutoSave(\"SaveSelf\");\n delete fFile;\n fFile = 0;\n fTree = 0;\n }\n}\n\nvoid JPetWriter::closeFile()\n{\n if (isOpen() ) {\n fTree->AutoSave(\"SaveSelf\");\n delete fFile;\n fFile = 0;\n }\n fFileName.clear();\n fIsBranchCreated = false;\n}\n\nvoid JPetWriter::writeHeader(TObject* header)\n{\n \/\/ @todo as the second argument should be passed some enum to indicate position of header\n fTree->GetUserInfo()->AddAt(header, JPetUserInfoStructure::kHeader);\n}\n\nIn JPetWriter destructor add check if fFile is empty before deleting it\/**\n * @copyright Copyright 2016 The J-PET Framework Authors. All rights reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may find a copy of the License in the LICENCE file.\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n * @file JPetWriter.cpp\n *\/\n\n#include \"JPetWriter.h\"\n#include \"..\/JPetUserInfoStructure\/JPetUserInfoStructure.h\"\n\n\nJPetWriter::JPetWriter(const char* p_fileName) :\n fFileName(p_fileName),\t\t\t\/\/ string z nazwą pliku\n fFile(0),\t\/\/ plik\n fIsBranchCreated(false),\n fTree(0)\n{\n fFile = new TFile(fFileName.c_str(), \"RECREATE\");\n if (!isOpen()) {\n ERROR(\"Could not open file to write.\");\n } else {\n fTree = new TTree(\"tree\", \"tree\");\n fTree->SetAutoSave(10000);\n }\n}\n\nJPetWriter::~JPetWriter()\n{\n if (isOpen()) {\n fTree->AutoSave(\"SaveSelf\");\n if (fFile) {\n delete fFile;\n fFile = 0;\n }\n fTree = 0;\n }\n}\n\nvoid JPetWriter::closeFile()\n{\n if (isOpen() ) {\n fTree->AutoSave(\"SaveSelf\");\n delete fFile;\n fFile = 0;\n }\n fFileName.clear();\n fIsBranchCreated = false;\n}\n\nvoid JPetWriter::writeHeader(TObject* header)\n{\n \/\/ @todo as the second argument should be passed some enum to indicate position of header\n fTree->GetUserInfo()->AddAt(header, JPetUserInfoStructure::kHeader);\n}\n\n<|endoftext|>"} {"text":"#include \"atlas\/utils\/Mesh.hpp\"\n#include \"atlas\/gl\/Buffer.hpp\"\n#include \"atlas\/gl\/VertexArrayObject.hpp\"\n#include \"atlas\/core\/Log.hpp\"\n\n#include \n#include \n\nnamespace atlas\n{\n namespace utils\n {\n struct Mesh::MeshImpl\n {\n MeshImpl() :\n vertexBuffer(GL_ARRAY_BUFFER),\n normalBuffer(GL_ARRAY_BUFFER),\n textureBuffer(GL_ARRAY_BUFFER),\n indexBuffer(GL_ELEMENT_ARRAY_BUFFER),\n isValid(false)\n { }\n\n MeshImpl(MeshImpl&& impl) = default;\n ~MeshImpl() = default;\n\n MeshImpl& operator=(MeshImpl&& rhs) = default;\n\n gl::Buffer vertexBuffer;\n gl::Buffer normalBuffer;\n gl::Buffer textureBuffer;\n gl::Buffer indexBuffer;\n gl::VertexArrayObject vao;\n \n GLuint numIndices;\n bool isValid;\n bool hasNormals;\n bool hasTextures;\n };\n\n Mesh::Mesh() :\n mImpl(std::make_unique())\n { }\n\n Mesh::Mesh(Mesh&& rhs) :\n mImpl(std::make_unique(std::move(*rhs.mImpl)))\n { }\n\n Mesh& Mesh::operator=(Mesh&& rhs)\n {\n *mImpl = std::move(*rhs.mImpl);\n return *this;\n }\n\n Mesh::~Mesh()\n { }\n\n void Mesh::fromTriangleSoup(\n std::vector const& vertices,\n std::vector const& indices,\n Mesh& mesh,\n std::vector const& normals,\n std::vector const& uvs)\n {\n struct MeshVertex\n {\n bool operator==(MeshVertex const& rhs) const\n {\n return\n (vertex == rhs.vertex) &&\n (normal == rhs.normal) &&\n (uv == rhs.uv);\n }\n\n bool operator!=(MeshVertex const& rhs) const\n {\n return !(*this == rhs);\n }\n\n math::Point vertex;\n math::Normal normal;\n math::Point2 uv;\n GLuint index;\n };\n\n struct MeshVertexHasher\n {\n std::size_t operator()(MeshVertex const& mv) const\n {\n return std::hash()(mv.vertex.x + mv.vertex.y + \n mv.vertex.z);\n }\n };\n\n bool hasNormals, hasTextures;\n\n hasNormals = !normals.empty();\n hasTextures = !uvs.empty();\n\n if (hasNormals && vertices.size() != normals.size())\n {\n WARN_LOG(\"Number of normals and vertices doesn't match.\");\n return;\n }\n\n if (hasTextures && vertices.size() != uvs.size())\n {\n WARN_LOG(\"Number of texture coordinates and vertices doesn't\\\n match.\");\n return;\n }\n\n std::unordered_set uniqueVertices;\n std::vector normalCount;\n GLuint current = 0;\n for (auto& idx : indices)\n {\n MeshVertex v;\n v.vertex = vertices[idx];\n\n if (hasNormals)\n {\n v.normal = normals[idx];\n }\n\n if (hasTextures)\n {\n v.uv = uvs[idx];\n }\n\n \/\/ Check if this vertex already exists.\n if (uniqueVertices.find(v) == uniqueVertices.end())\n {\n \/\/ It doesn't, so increase the count and insert.\n mesh.indices().push_back(current);\n mesh.vertices().push_back(v.vertex);\n normalCount.push_back(1);\n\n if (hasNormals)\n {\n mesh.normals().push_back(v.normal);\n }\n\n if (hasTextures)\n {\n mesh.uvs().push_back(v.uv);\n }\n\n v.index = current;\n uniqueVertices.insert(v);\n current++;\n }\n else\n {\n \/\/ We have already seen this vertex, so grab it's index.\n auto uniqueV = *uniqueVertices.find(v);\n mesh.indices().push_back(uniqueV.index);\n\n normalCount[uniqueV.index]++;\n auto k = normalCount[uniqueV.index];\n auto mK = mesh.normals()[uniqueV.index];\n mK = mK + ((v.normal - mK) \/ (float)k);\n mesh.normals()[uniqueV.index] = mK;\n }\n }\n\n \/\/ Tell the mesh to update itself to reflect the new data.\n mesh.updateMesh();\n mesh.updateIndices();\n }\n\n std::vector& Mesh::vertices()\n {\n return mVertices;\n }\n\n std::vector& Mesh::normals()\n {\n return mNormals;\n }\n\n std::vector& Mesh::uvs()\n {\n return mUvs;\n }\n\n std::vector& Mesh::indices()\n {\n return mIndices;\n }\n\n bool Mesh::isValid() const\n {\n return mImpl->isValid;\n }\n\n void Mesh::setVertexAttribArrays(std::vector const& arrays)\n {\n if (arrays.size() < 1)\n {\n WARN_LOG(\"No indices provided for vertex attribute arrays.\");\n mImpl->isValid = false;\n return;\n }\n\n mImpl->vao.bindVertexArray();\n for (auto& idx : arrays)\n {\n mImpl->vao.enableVertexAttribArray(idx);\n }\n\n mImpl->vertexBuffer.bindBuffer();\n mImpl->vertexBuffer.vertexAttribPointer(arrays[0],\n 3, GL_FLOAT, GL_FALSE, gl::stride(0),\n gl::bufferOffset(0));\n\n if (mImpl->hasNormals && arrays.size() < 2)\n {\n WARN_LOG(std::string(\"No index for normal vertex attribute\") +\n \" array provided. Normals will not be bound.\");\n return;\n }\n\n mImpl->normalBuffer.bindBuffer();\n mImpl->normalBuffer.vertexAttribPointer(arrays[1],\n 3, GL_FLOAT, GL_FALSE, gl::stride(0),\n gl::bufferOffset(0));\n\n if (mImpl->hasTextures && arrays.size() < 3)\n {\n WARN_LOG(\"No index for texture coordinates vertex attribute \\\n array provided. Texture coordinates will not be bound.\");\n return;\n }\n\n mImpl->textureBuffer.bindBuffer();\n mImpl->textureBuffer.vertexAttribPointer(arrays[2],\n 2, GL_FLOAT, GL_FALSE, gl::stride(0),\n gl::bufferOffset(0));\n\n mImpl->textureBuffer.unBindBuffer();\n mImpl->vao.unBindVertexArray();\n }\n\n void Mesh::updateMesh()\n {\n if (mVertices.empty())\n {\n WARN_LOG(\"Attempting to create a mesh with no vertices.\");\n mImpl->isValid = false;\n return;\n }\n\n \/\/ Now check if we have normals or texture coordinates.\n mImpl->hasNormals = !mNormals.empty();\n mImpl->hasTextures= !mUvs.empty();\n\n \/\/ Now check if all the arrays have the same size.\n if (mImpl->hasNormals && mVertices.size() != mNormals.size())\n {\n WARN_LOG(\"Number of normals and vertices don't match.\");\n mImpl->isValid = false;\n return;\n }\n\n if (mImpl->hasTextures && mVertices.size() != mUvs.size())\n {\n WARN_LOG(\"Number of texture coordinates and vertices don't \\\n match.\");\n mImpl->isValid = false;\n return;\n }\n\n mImpl->vertexBuffer.bindBuffer();\n mImpl->vertexBuffer.bufferData(\n gl::size(mVertices.size()), mVertices.data(),\n GL_DYNAMIC_DRAW);\n mImpl->vertexBuffer.unBindBuffer();\n\n if (mImpl->hasNormals)\n {\n mImpl->normalBuffer.bindBuffer();\n mImpl->normalBuffer.bufferData(\n gl::size(mNormals.size()),\n mNormals.data(), GL_DYNAMIC_DRAW);\n mImpl->normalBuffer.unBindBuffer();\n }\n\n if (mImpl->hasTextures)\n {\n mImpl->textureBuffer.bindBuffer();\n mImpl->textureBuffer.bufferData(\n gl::size(mUvs.size()), mUvs.data(),\n GL_DYNAMIC_DRAW);\n mImpl->textureBuffer.unMapBuffer();\n }\n\n \/\/ At this point everything is bound and ready to go, so the mesh\n \/\/ is valid.\n mImpl->isValid = true;\n }\n\n void Mesh::updateIndices()\n {\n mImpl->indexBuffer.bindBuffer();\n mImpl->indexBuffer.bufferData(gl::size(mIndices.size()),\n mIndices.data(), GL_DYNAMIC_DRAW);\n mImpl->indexBuffer.unBindBuffer();\n mImpl->numIndices = (GLuint)mIndices.size();\n }\n\n void Mesh::renderMesh()\n {\n if (!mImpl->isValid)\n {\n return;\n }\n\n mImpl->vao.bindVertexArray();\n mImpl->indexBuffer.bindBuffer();\n glDrawElements(GL_TRIANGLES, mImpl->numIndices,\n GL_UNSIGNED_INT, gl::bufferOffset(0));\n mImpl->vao.unBindVertexArray();\n mImpl->indexBuffer.unBindBuffer();\n }\n }\n}[brief] Fixes warning message formatting for Mesh.#include \"atlas\/utils\/Mesh.hpp\"\n#include \"atlas\/gl\/Buffer.hpp\"\n#include \"atlas\/gl\/VertexArrayObject.hpp\"\n#include \"atlas\/core\/Log.hpp\"\n\n#include \n#include \n\nnamespace atlas\n{\n namespace utils\n {\n struct Mesh::MeshImpl\n {\n MeshImpl() :\n vertexBuffer(GL_ARRAY_BUFFER),\n normalBuffer(GL_ARRAY_BUFFER),\n textureBuffer(GL_ARRAY_BUFFER),\n indexBuffer(GL_ELEMENT_ARRAY_BUFFER),\n isValid(false)\n { }\n\n MeshImpl(MeshImpl&& impl) = default;\n ~MeshImpl() = default;\n\n MeshImpl& operator=(MeshImpl&& rhs) = default;\n\n gl::Buffer vertexBuffer;\n gl::Buffer normalBuffer;\n gl::Buffer textureBuffer;\n gl::Buffer indexBuffer;\n gl::VertexArrayObject vao;\n \n GLuint numIndices;\n bool isValid;\n bool hasNormals;\n bool hasTextures;\n };\n\n Mesh::Mesh() :\n mImpl(std::make_unique())\n { }\n\n Mesh::Mesh(Mesh&& rhs) :\n mImpl(std::make_unique(std::move(*rhs.mImpl)))\n { }\n\n Mesh& Mesh::operator=(Mesh&& rhs)\n {\n *mImpl = std::move(*rhs.mImpl);\n return *this;\n }\n\n Mesh::~Mesh()\n { }\n\n void Mesh::fromTriangleSoup(\n std::vector const& vertices,\n std::vector const& indices,\n Mesh& mesh,\n std::vector const& normals,\n std::vector const& uvs)\n {\n struct MeshVertex\n {\n bool operator==(MeshVertex const& rhs) const\n {\n return\n (vertex == rhs.vertex) &&\n (normal == rhs.normal) &&\n (uv == rhs.uv);\n }\n\n bool operator!=(MeshVertex const& rhs) const\n {\n return !(*this == rhs);\n }\n\n math::Point vertex;\n math::Normal normal;\n math::Point2 uv;\n GLuint index;\n };\n\n struct MeshVertexHasher\n {\n std::size_t operator()(MeshVertex const& mv) const\n {\n return std::hash()(mv.vertex.x + mv.vertex.y + \n mv.vertex.z);\n }\n };\n\n bool hasNormals, hasTextures;\n\n hasNormals = !normals.empty();\n hasTextures = !uvs.empty();\n\n if (hasNormals && vertices.size() != normals.size())\n {\n WARN_LOG(\"Number of normals and vertices doesn't match.\");\n return;\n }\n\n if (hasTextures && vertices.size() != uvs.size())\n {\n WARN_LOG(\"Number of texture coordinates and vertices doesn't\\\n match.\");\n return;\n }\n\n std::unordered_set uniqueVertices;\n std::vector normalCount;\n GLuint current = 0;\n for (auto& idx : indices)\n {\n MeshVertex v;\n v.vertex = vertices[idx];\n\n if (hasNormals)\n {\n v.normal = normals[idx];\n }\n\n if (hasTextures)\n {\n v.uv = uvs[idx];\n }\n\n \/\/ Check if this vertex already exists.\n if (uniqueVertices.find(v) == uniqueVertices.end())\n {\n \/\/ It doesn't, so increase the count and insert.\n mesh.indices().push_back(current);\n mesh.vertices().push_back(v.vertex);\n normalCount.push_back(1);\n\n if (hasNormals)\n {\n mesh.normals().push_back(v.normal);\n }\n\n if (hasTextures)\n {\n mesh.uvs().push_back(v.uv);\n }\n\n v.index = current;\n uniqueVertices.insert(v);\n current++;\n }\n else\n {\n \/\/ We have already seen this vertex, so grab it's index.\n auto uniqueV = *uniqueVertices.find(v);\n mesh.indices().push_back(uniqueV.index);\n\n normalCount[uniqueV.index]++;\n auto k = normalCount[uniqueV.index];\n auto mK = mesh.normals()[uniqueV.index];\n mK = mK + ((v.normal - mK) \/ (float)k);\n mesh.normals()[uniqueV.index] = mK;\n }\n }\n\n \/\/ Tell the mesh to update itself to reflect the new data.\n mesh.updateMesh();\n mesh.updateIndices();\n }\n\n std::vector& Mesh::vertices()\n {\n return mVertices;\n }\n\n std::vector& Mesh::normals()\n {\n return mNormals;\n }\n\n std::vector& Mesh::uvs()\n {\n return mUvs;\n }\n\n std::vector& Mesh::indices()\n {\n return mIndices;\n }\n\n bool Mesh::isValid() const\n {\n return mImpl->isValid;\n }\n\n void Mesh::setVertexAttribArrays(std::vector const& arrays)\n {\n if (arrays.size() < 1)\n {\n WARN_LOG(\"No indices provided for vertex attribute arrays.\");\n mImpl->isValid = false;\n return;\n }\n\n mImpl->vao.bindVertexArray();\n for (auto& idx : arrays)\n {\n mImpl->vao.enableVertexAttribArray(idx);\n }\n\n mImpl->vertexBuffer.bindBuffer();\n mImpl->vertexBuffer.vertexAttribPointer(arrays[0],\n 3, GL_FLOAT, GL_FALSE, gl::stride(0),\n gl::bufferOffset(0));\n\n if (mImpl->hasNormals && arrays.size() < 2)\n {\n WARN_LOG(std::string(\"No index for normal vertex attribute\") +\n \" array provided. Normals will not be bound.\");\n return;\n }\n\n mImpl->normalBuffer.bindBuffer();\n mImpl->normalBuffer.vertexAttribPointer(arrays[1],\n 3, GL_FLOAT, GL_FALSE, gl::stride(0),\n gl::bufferOffset(0));\n\n if (mImpl->hasTextures && arrays.size() < 3)\n {\n WARN_LOG(std::string(\"No index for texture coordinates \") + \n \"vertex attribute array provided. Texture coordinates will\" +\n \" not be bound.\");\n return;\n }\n\n mImpl->textureBuffer.bindBuffer();\n mImpl->textureBuffer.vertexAttribPointer(arrays[2],\n 2, GL_FLOAT, GL_FALSE, gl::stride(0),\n gl::bufferOffset(0));\n\n mImpl->textureBuffer.unBindBuffer();\n mImpl->vao.unBindVertexArray();\n }\n\n void Mesh::updateMesh()\n {\n if (mVertices.empty())\n {\n WARN_LOG(\"Attempting to create a mesh with no vertices.\");\n mImpl->isValid = false;\n return;\n }\n\n \/\/ Now check if we have normals or texture coordinates.\n mImpl->hasNormals = !mNormals.empty();\n mImpl->hasTextures= !mUvs.empty();\n\n \/\/ Now check if all the arrays have the same size.\n if (mImpl->hasNormals && mVertices.size() != mNormals.size())\n {\n WARN_LOG(\"Number of normals and vertices don't match.\");\n mImpl->isValid = false;\n return;\n }\n\n if (mImpl->hasTextures && mVertices.size() != mUvs.size())\n {\n WARN_LOG(std::string(\"Number of texture coordinates and \") + \n \"vertices don't match.\");\n mImpl->isValid = false;\n return;\n }\n\n mImpl->vertexBuffer.bindBuffer();\n mImpl->vertexBuffer.bufferData(\n gl::size(mVertices.size()), mVertices.data(),\n GL_DYNAMIC_DRAW);\n mImpl->vertexBuffer.unBindBuffer();\n\n if (mImpl->hasNormals)\n {\n mImpl->normalBuffer.bindBuffer();\n mImpl->normalBuffer.bufferData(\n gl::size(mNormals.size()),\n mNormals.data(), GL_DYNAMIC_DRAW);\n mImpl->normalBuffer.unBindBuffer();\n }\n\n if (mImpl->hasTextures)\n {\n mImpl->textureBuffer.bindBuffer();\n mImpl->textureBuffer.bufferData(\n gl::size(mUvs.size()), mUvs.data(),\n GL_DYNAMIC_DRAW);\n mImpl->textureBuffer.unMapBuffer();\n }\n\n \/\/ At this point everything is bound and ready to go, so the mesh\n \/\/ is valid.\n mImpl->isValid = true;\n }\n\n void Mesh::updateIndices()\n {\n mImpl->indexBuffer.bindBuffer();\n mImpl->indexBuffer.bufferData(gl::size(mIndices.size()),\n mIndices.data(), GL_DYNAMIC_DRAW);\n mImpl->indexBuffer.unBindBuffer();\n mImpl->numIndices = (GLuint)mIndices.size();\n }\n\n void Mesh::renderMesh()\n {\n if (!mImpl->isValid)\n {\n return;\n }\n\n mImpl->vao.bindVertexArray();\n mImpl->indexBuffer.bindBuffer();\n glDrawElements(GL_TRIANGLES, mImpl->numIndices,\n GL_UNSIGNED_INT, gl::bufferOffset(0));\n mImpl->vao.unBindVertexArray();\n mImpl->indexBuffer.unBindBuffer();\n }\n }\n}<|endoftext|>"} {"text":"#include \"cetech\/task_manager\/task_manager.h\"\n\n#include \"celib\/memory\/memory.h\"\n#include \"celib\/container\/array.inl.h\"\n#include \"cetech\/thread\/thread.h\"\n\n#include \"cetech\/application\/application.h\"\n#include \"cetech\/log_system\/log_system.h\"\n\n#define TASK_INITIALIZER { { 0 }, { 0 }, { 0 }, 0, 0, { 0, 0 } }\n\n\/\/TODO: REWRITE !!! #62\nnamespace cetech {\n namespace {\n using namespace task_manager;\n\n \/*!\n * Task worker callback.\n *\/\n struct TaskWorkCallback {\n TaskWorkFce_t fce; \/\/!< Worker fce.\n void* data; \/\/!< Worker data.\n };\n\n struct Task {\n TaskID id; \/\/!< Task id\n TaskID depend; \/\/!< Task depend\n TaskID parent; \/\/!< Task parent\n\n uint32_t priority; \/\/!< Task priority\n uint32_t job_count; \/\/!< Task child active job\n TaskWorkCallback clb; \/\/!< Callback\n };\n\n enum {\n MAX_TASK = 512\n };\n\n struct TaskManagerData {\n Spinlock _lock; \/\/!< Spinlock\n\n uint32_t _last_id; \/\/!< Last id\n uint32_t _task_count; \/\/!< Task count\n uint32_t _open_task_count; \/\/!< Open task count\n\n uint32_t _task_queue[MAX_TASK]; \/\/!< Task queue\n uint32_t _open_task[MAX_TASK]; \/\/!< Open task\n Task _task_pool[MAX_TASK]; \/\/!< Task pool\n\n Array < Thread > _workers;\n\n struct {\n char run : 1;\n } flags;\n\n TaskManagerData(Allocator & allocator) : _last_id(0),\n _task_count(0),\n _open_task_count(0),\n _workers(allocator) {\n\n memset(_task_queue, 0, sizeof(uint32_t) * MAX_TASK);\n memset(_open_task, 0, sizeof(uint32_t) * MAX_TASK);\n memset(_task_pool, 0, sizeof(Task) * MAX_TASK);\n }\n\n ~TaskManagerData() {\n for (uint32_t i = 0; i < array::size(_workers); ++i) {\n log::debug(\"task\", \"Killing worker%u.\", i);\n thread::kill(_workers[i]);\n }\n };\n\n\n };\n\n struct Globals {\n static const int MEMORY = sizeof(TaskManagerData);\n char buffer[MEMORY];\n\n TaskManagerData* data;\n\n Globals() : data(0) {}\n } _globals;\n\n uint32_t _core_count() {\n#if defined(CETECH_SDL2)\n return SDL_GetCPUCount();\n#endif\n }\n\n static int task_worker(void* data) {\n while (_globals.data->flags.run) {\n task_manager::do_work();\n }\n\n return 0;\n }\n\n\n \/*! NOP task.\n *\/\n static void _task_nop(void*) {}\n\n \/*! Get new task idx from pool.\n * \\return Task idx.\n *\/\n CE_INLINE uint32_t _new_task_from_pool() {\n for (uint32_t i = 0; i < MAX_TASK; ++i) {\n if (_globals.data->_task_pool[i].id.i != 0) {\n continue;\n }\n\n return i;\n }\n\n \/* TODO =( *\/\n log::error(\"task\", \"Pool overflow\");\n abort();\n }\n\n \/*! Find task in pool\n * \\param id Task id.\n * \\return Task ptr.\n * \\retval NULL Task not found.\n *\/\n CE_INLINE Task* _find_task_in_pool(TaskID id) {\n for (uint32_t i = 0; i < MAX_TASK; ++i) {\n if (_globals.data->_task_pool[i].id.i != id.i) {\n continue;\n }\n\n return &_globals.data->_task_pool[i];\n }\n\n return NULL;\n }\n\n\n \/*! Mark job as done.\n * \\param id Task id.\n *\/\n void _mark_task_job_done(TaskID id) {\n \/\/thread::spin_lock(_globals.data->_lock);\n\n for (uint32_t i = 0; i < _globals.data->_open_task_count; ++i) {\n Task* t = &_globals.data->_task_pool[_globals.data->_open_task[i]];\n\n if (t->id.i != id.i) {\n continue;\n }\n\n t->id.i = 0;\n\n if (t->parent.i != 0) {\n Task* parent_task = _find_task_in_pool(t->parent);\n --parent_task->job_count;\n }\n\n _globals.data->_open_task[i] = _globals.data->_open_task[_globals.data->_open_task_count - 1];\n --_globals.data->_open_task_count;\n break;\n }\n\n \/\/thread::spin_unlock(_globals.data->_lock);\n }\n\n \/*! Is task done?\n * \\param id Task id.\n * \\retval 0 Not done.\n * \\retval 1 Done.\n *\/\n CE_INLINE uint8_t _is_task_done(TaskID id) {\n uint8_t is_done = 1;\n\n for (uint32_t i = 0; i < _globals.data->_open_task_count; ++i) {\n if (_globals.data->_task_pool[_globals.data->_open_task[i]].id.i != id.i) {\n continue;\n }\n\n is_done = 0;\n break;\n }\n\n return is_done;\n }\n\n int8_t task_is_null(TaskID id) {\n return id.i == 0;\n }\n\n uint32_t task_get_worker_id() {\n uint32_t id = thread::id();\n\n for (uint8_t i = 0; i < array::size(_globals.data->_workers); ++i) {\n if (thread::get_id(_globals.data->_workers[i]) != id) {\n continue;\n }\n\n return i + 1;\n }\n\n return 0;\n }\n\n uint8_t task_is_done(TaskID id) {\n \/\/ thread::spin_lock(_lock);\n uint8_t is_done = _is_task_done(id);\n \/\/ thread::spin_unlock(_lock);\n return is_done;\n }\n\n\n\n Task task_pop_new_work() {\n \/\/thread::spin_lock(_globals.data->_lock);\n\n if (_globals.data->_task_count < 1) {\n \/\/thread::spin_unlock(_globals.data->_lock);\n return (Task)TASK_INITIALIZER;\n }\n\n for (int32_t i = _globals.data->_task_count - 1; i >= 0; --i) {\n Task t = _globals.data->_task_pool[_globals.data->_task_queue[i]];\n\n if (t.job_count != 1) {\n continue;\n }\n\n if (t.depend.i > 0) {\n if (!_is_task_done(t.depend)) {\n continue;\n }\n }\n\n for (; i < _globals.data->_task_count; ++i) {\n _globals.data->_task_queue[i] = _globals.data->_task_queue[i + 1];\n }\n\n --_globals.data->_task_count;\n CE_ASSERT(_globals.data->_task_count != 4294967295);\n\n \/\/thread::spin_unlock(_globals.data->_lock);\n return t;\n }\n\n \/\/thread::spin_unlock(_globals.data->_lock);\n return (Task)TASK_INITIALIZER;\n }\n\n }\n\n namespace task_manager {\n TaskID add_begin(const TaskWorkFce_t fce,\n void* data,\n const uint32_t priority,\n const TaskID depend,\n const TaskID parent) {\n TaskWorkCallback callback = { fce, data };\n\n \/\/thread::spin_lock(_globals.data->_lock);\n\n const uint32_t id = ++_globals.data->_last_id;\n\n uint32_t task = _new_task_from_pool();\n\n \/* First? *\/\n if (_globals.data->_task_count == 0) {\n Task t;\n t.id = { id },\n t.priority = priority,\n t.clb = callback,\n t.job_count = 2,\n t.depend = depend,\n t.parent = parent,\n\n _globals.data->_task_pool[task] = t;\n\n _globals.data->_task_queue[0] = task;\n } else {\n\n \/* push item to queue *\/\n uint32_t i = _globals.data->_task_count;\n\n while (i > 0 && _globals.data->_task_pool[_globals.data->_task_queue[i - 1]].priority > priority) {\n _globals.data->_task_queue[i] = _globals.data->_task_queue[i - 1];\n --i;\n }\n\n Task t;\n t.id = { id },\n t.priority = priority,\n t.clb = callback,\n t.job_count = 2,\n t.depend = depend,\n t.parent = parent,\n\n _globals.data->_task_pool[task] = t;\n\n _globals.data->_task_queue[i] = task;\n }\n\n if (parent.i != 0) {\n Task* t = _find_task_in_pool(parent);\n ++t->job_count;\n }\n\n _globals.data->_open_task[_globals.data->_open_task_count] = task;\n ++_globals.data->_open_task_count;\n ++_globals.data->_task_count;\n\n \/\/thread::spin_unlock(_globals.data->_lock);\n return (TaskID) {\n id\n };\n\n }\n\n TaskID add_empty_begin(const uint32_t priority, const TaskID depend, const TaskID parent) {\n return add_begin(_task_nop, 0, priority, depend, parent);\n }\n\n void add_end(const TaskID* tasks, const uint32_t count) {\n \/\/thread::spin_lock(_globals.data->_lock);\n\n for (uint32_t i = 0; i < MAX_TASK; ++i) {\n for (uint32_t j = 0; j < count; ++j) {\n if (_globals.data->_task_pool[i].id.i != tasks[j].i) {\n continue;\n }\n\n --_globals.data->_task_pool[i].job_count;\n break;\n }\n }\n\n \/\/thread::spin_unlock(_globals.data->_lock);\n }\n\n void do_work() {\n Task t = task_pop_new_work();\n\n if (t.id.i == 0) {\n return;\n }\n\n CE_ASSERT(t.clb.fce != NULL);\n\n t.clb.fce(t.clb.data);\n\n _mark_task_job_done(t.id);\n }\n\n void wait(const TaskID id) {\n while (_globals.data->flags.run && (array::size(_globals.data->_workers) > 0) &&\n !task_is_done(id)) {\n do_work();\n }\n }\n\n void spawn_workers() {\n uint32_t core_count = _core_count() * 2;\n\n static const uint32_t main_threads_count = 1 + 1;\n const uint32_t worker_count = core_count - main_threads_count;\n\n log::info(\"task\", \"Core count: %u\", core_count);\n log::info(\"task\", \"Main thread count: %u\", main_threads_count);\n log::info(\"task\", \"Worker count: %u\", worker_count);\n\n if (worker_count > 0) {\n for (uint32_t i = 0; i < worker_count; ++i) {\n log::debug(\"task\", \"Creating worker %u.\", i);\n array::push_back(_globals.data->_workers, thread::create_thread(task_worker, \"Worker\", 0));\n }\n }\n\n _globals.data->flags.run = 1;\n }\n\n void stop() {\n _globals.data->flags.run = 0;\n }\n\n }\n\n namespace task_manager_globals {\n void init() {\n log::info(\"task_manager_globals\", \"Init\");\n char* p = _globals.buffer;\n _globals.data = new(p) TaskManagerData(memory_globals::default_allocator());\n\n spawn_workers();\n }\n\n void shutdown() {\n log::info(\"task_manager_globals\", \"Shutdown\");\n\n _globals.data->~TaskManagerData();\n _globals = Globals();\n }\n }\n\n}new queue to task manager #62#include \"cetech\/task_manager\/task_manager.h\"\n\n#include \"celib\/memory\/memory.h\"\n#include \"celib\/container\/array.inl.h\"\n#include \"celib\/container\/queue.inl.h\"\n\n#include \"cetech\/thread\/thread.h\"\n#include \"cetech\/application\/application.h\"\n#include \"cetech\/log_system\/log_system.h\"\n\n#define TASK_INITIALIZER { { 0 }, { 0 }, { 0 }, 0, 0, { 0, 0 } }\n\n\/\/TODO: REWRITE !!! #62\nnamespace cetech {\n namespace {\n using namespace task_manager;\n\n \/*!\n * Task worker callback.\n *\/\n struct TaskWorkCallback {\n TaskWorkFce_t fce; \/\/!< Worker fce.\n void* data; \/\/!< Worker data.\n };\n\n struct Task {\n TaskID id; \/\/!< Task id\n TaskID depend; \/\/!< Task depend\n TaskID parent; \/\/!< Task parent\n\n uint32_t priority; \/\/!< Task priority\n uint32_t job_count; \/\/!< Task child active job\n TaskWorkCallback clb; \/\/!< Callback\n };\n\n enum {\n MAX_TASK = 512\n };\n\n struct TaskManagerData {\n Spinlock _lock; \/\/!< Spinlock\n\n uint32_t _last_id; \/\/!< Last id\n uint32_t _task_count; \/\/!< Task count\n uint32_t _open_task_count; \/\/!< Open task count\n\n uint32_t _open_task[MAX_TASK]; \/\/!< Open task\n Task _task_pool[MAX_TASK]; \/\/!< Task pool\n\n Array < Thread > _workers;\n Queue _queue;\n\n struct {\n char run : 1;\n } flags;\n\n TaskManagerData(Allocator & allocator) : _last_id(0),\n _task_count(0),\n _open_task_count(0),\n _workers(allocator), _queue(allocator) {\n\n memset(_open_task, 0, sizeof(uint32_t) * MAX_TASK);\n memset(_task_pool, 0, sizeof(Task) * MAX_TASK);\n }\n\n ~TaskManagerData() {\n for (uint32_t i = 0; i < array::size(_workers); ++i) {\n log::debug(\"task\", \"Killing worker%u.\", i);\n thread::kill(_workers[i]);\n }\n };\n\n\n };\n\n struct Globals {\n static const int MEMORY = sizeof(TaskManagerData);\n char buffer[MEMORY];\n\n TaskManagerData* data;\n\n Globals() : data(0) {}\n } _globals;\n\n uint32_t _core_count() {\n#if defined(CETECH_SDL2)\n return SDL_GetCPUCount();\n#endif\n }\n\n static int task_worker(void* data) {\n while (_globals.data->flags.run) {\n task_manager::do_work();\n }\n\n return 0;\n }\n\n\n \/*! NOP task.\n *\/\n static void _task_nop(void*) {}\n\n \/*! Get new task idx from pool.\n * \\return Task idx.\n *\/\n CE_INLINE uint32_t _new_task_from_pool() {\n for (uint32_t i = 0; i < MAX_TASK; ++i) {\n if (_globals.data->_task_pool[i].id.i != 0) {\n continue;\n }\n\n return i;\n }\n CE_ASSERT_MSG(false, \"Pool overflow\");\n abort();\n }\n\n \/*! Find task in pool\n * \\param id Task id.\n * \\return Task ptr.\n * \\retval NULL Task not found.\n *\/\n CE_INLINE Task* _find_task_in_pool(TaskID id) {\n for (uint32_t i = 0; i < MAX_TASK; ++i) {\n if (_globals.data->_task_pool[i].id.i != id.i) {\n continue;\n }\n\n return &_globals.data->_task_pool[i];\n }\n\n return NULL;\n }\n\n\n \/*! Mark job as done.\n * \\param id Task id.\n *\/\n void _mark_task_job_done(TaskID id) {\n \/\/thread::spin_lock(_globals.data->_lock);\n\n for (uint32_t i = 0; i < _globals.data->_open_task_count; ++i) {\n Task* t = &_globals.data->_task_pool[_globals.data->_open_task[i]];\n\n if (t->id.i != id.i) {\n continue;\n }\n\n t->id.i = 0;\n\n if (t->parent.i != 0) {\n Task* parent_task = _find_task_in_pool(t->parent);\n --parent_task->job_count;\n }\n\n _globals.data->_open_task[i] = _globals.data->_open_task[_globals.data->_open_task_count - 1];\n --_globals.data->_open_task_count;\n break;\n }\n\n \/\/thread::spin_unlock(_globals.data->_lock);\n }\n\n \/*! Is task done?\n * \\param id Task id.\n * \\retval 0 Not done.\n * \\retval 1 Done.\n *\/\n CE_INLINE uint8_t _is_task_done(TaskID id) {\n uint8_t is_done = 1;\n\n for (uint32_t i = 0; i < _globals.data->_open_task_count; ++i) {\n if (_globals.data->_task_pool[_globals.data->_open_task[i]].id.i != id.i) {\n continue;\n }\n\n is_done = 0;\n break;\n }\n\n return is_done;\n }\n\n int8_t task_is_null(TaskID id) {\n return id.i == 0;\n }\n\n uint32_t task_get_worker_id() {\n uint32_t id = thread::id();\n\n for (uint8_t i = 0; i < array::size(_globals.data->_workers); ++i) {\n if (thread::get_id(_globals.data->_workers[i]) != id) {\n continue;\n }\n\n return i + 1;\n }\n\n return 0;\n }\n\n uint8_t task_is_done(TaskID id) {\n \/\/ thread::spin_lock(_lock);\n uint8_t is_done = _is_task_done(id);\n \/\/ thread::spin_unlock(_lock);\n return is_done;\n }\n\n\n\n Task task_pop_new_work() {\n \/\/thread::spin_lock(_globals.data->_lock);\n\n while(1) {\n if(queue::size(_globals.data->_queue) < 1) {\n return (Task)TASK_INITIALIZER;\n }\n\n uint32_t poped_task = _globals.data->_queue[0];\n queue::pop_front(_globals.data->_queue);\n\n Task t = _globals.data->_task_pool[poped_task];\n \n if (t.job_count != 1) {\n queue::push_back(_globals.data->_queue, poped_task);\n continue;\n }\n\n if (t.depend.i > 0) {\n if (!_is_task_done(t.depend)) {\n queue::push_back(_globals.data->_queue, poped_task);\n continue;\n }\n }\n\n --_globals.data->_task_count;\n return t;\n }\n\n return (Task)TASK_INITIALIZER;\n\n \/\/thread::spin_unlock(_globals.data->_lock);\n \/\/return (Task)TASK_INITIALIZER;\n }\n\n }\n\n namespace task_manager {\n TaskID add_begin(const TaskWorkFce_t fce,\n void* data,\n const uint32_t priority,\n const TaskID depend,\n const TaskID parent) {\n TaskWorkCallback callback = { fce, data };\n\n \/\/thread::spin_lock(_globals.data->_lock);\n\n const uint32_t id = ++_globals.data->_last_id;\n\n uint32_t task = _new_task_from_pool();\n\n Task t;\n t.id = { id },\n t.priority = priority,\n t.clb = callback,\n t.job_count = 2,\n t.depend = depend,\n t.parent = parent,\n\n _globals.data->_task_pool[task] = t;\n\n if (parent.i != 0) {\n Task* t = _find_task_in_pool(parent);\n ++t->job_count;\n }\n\n _globals.data->_open_task[_globals.data->_open_task_count] = task;\n ++_globals.data->_open_task_count;\n ++_globals.data->_task_count;\n\n \/\/thread::spin_unlock(_globals.data->_lock);\n return (TaskID) {\n id\n };\n\n }\n\n TaskID add_empty_begin(const uint32_t priority, const TaskID depend, const TaskID parent) {\n return add_begin(_task_nop, 0, priority, depend, parent);\n }\n\n void add_end(const TaskID* tasks, const uint32_t count) {\n \/\/thread::spin_lock(_globals.data->_lock);\n\n for (uint32_t i = 0; i < MAX_TASK; ++i) {\n for (uint32_t j = 0; j < count; ++j) {\n if (_globals.data->_task_pool[i].id.i != tasks[j].i) {\n continue;\n }\n\n --_globals.data->_task_pool[i].job_count;\n queue::push_back(_globals.data->_queue, i);\n break;\n }\n }\n\n \/\/thread::spin_unlock(_globals.data->_lock);\n }\n\n void do_work() {\n Task t = task_pop_new_work();\n\n if (t.id.i == 0) {\n return;\n }\n\n CE_ASSERT(t.clb.fce != NULL);\n\n t.clb.fce(t.clb.data);\n\n _mark_task_job_done(t.id);\n }\n\n void wait(const TaskID id) {\n while (_globals.data->flags.run && (array::size(_globals.data->_workers) > 0) &&\n !task_is_done(id)) {\n do_work();\n }\n }\n\n void spawn_workers() {\n uint32_t core_count = _core_count() * 2;\n\n static const uint32_t main_threads_count = 1 + 1;\n const uint32_t worker_count = core_count - main_threads_count;\n\n log::info(\"task\", \"Core count: %u\", core_count);\n log::info(\"task\", \"Main thread count: %u\", main_threads_count);\n log::info(\"task\", \"Worker count: %u\", worker_count);\n\n if (worker_count > 0) {\n for (uint32_t i = 0; i < worker_count; ++i) {\n log::debug(\"task\", \"Creating worker %u.\", i);\n array::push_back(_globals.data->_workers, thread::create_thread(task_worker, \"Worker\", 0));\n }\n }\n\n _globals.data->flags.run = 1;\n }\n\n void stop() {\n _globals.data->flags.run = 0;\n }\n\n }\n\n namespace task_manager_globals {\n void init() {\n log::info(\"task_manager_globals\", \"Init\");\n char* p = _globals.buffer;\n _globals.data = new(p) TaskManagerData(memory_globals::default_allocator());\n\n spawn_workers();\n }\n\n void shutdown() {\n log::info(\"task_manager_globals\", \"Shutdown\");\n\n _globals.data->~TaskManagerData();\n _globals = Globals();\n }\n }\n\n}<|endoftext|>"} {"text":"\/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- *\/\n\/*\n * This file is part of the LibreOffice project.\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\n * This file incorporates work covered by the following license notice:\n *\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed\n * with this work for additional information regarding copyright\n * ownership. The ASF licenses this file to you under the Apache\n * License, Version 2.0 (the \"License\"); you may not use this file\n * except in compliance with the License. You may obtain a copy of\n * the License at http:\/\/www.apache.org\/licenses\/LICENSE-2.0 .\n *\/\n#ifndef INCLUDED_STARMATH_INC_PARSE_HXX\n#define INCLUDED_STARMATH_INC_PARSE_HXX\n\n#include \n\n#include \n\n#include \"types.hxx\"\n#include \"token.hxx\"\n#include \"error.hxx\"\n#include \"node.hxx\"\n\n#include \n\nclass SmParser : boost::noncopyable\n{\n OUString m_aBufferString;\n SmToken m_aCurToken;\n SmNodeStack m_aNodeStack;\n SmErrDescList m_aErrDescList;\n int m_nCurError;\n LanguageType m_nLang;\n sal_Int32 m_nBufferIndex,\n m_nTokenIndex;\n sal_Int32 m_Row,\n m_nColOff;\n bool bImportSymNames,\n m_bExportSymNames;\n\n \/\/ map of used symbols (used to reduce file size by exporting only actually used symbols)\n std::set< OUString > m_aUsedSymbols;\n\n \/\/! locale where '.' is decimal separator!\n ::com::sun::star::lang::Locale m_aDotLoc;\n\nprotected:\n#if OSL_DEBUG_LEVEL > 1\n bool IsDelimiter( const OUString &rTxt, sal_Int32 nPos );\n#endif\n void NextToken();\n sal_Int32 GetTokenIndex() const { return m_nTokenIndex; }\n void Replace( sal_Int32 nPos, sal_Int32 nLen, const OUString &rText );\n\n inline bool TokenInGroup( sal_uLong nGroup );\n\n \/\/ grammar\n void Table();\n void Line();\n void Expression();\n void Relation();\n void Sum();\n void Product();\n void SubSup(sal_uLong nActiveGroup);\n void OpSubSup();\n void Power();\n void Blank();\n void Term(bool bGroupNumberIdent);\n void Escape();\n void Operator();\n void Oper();\n void UnOper();\n void Align();\n void FontAttribut();\n void Attribut();\n void Font();\n void FontSize();\n void Color();\n void Brace();\n void Bracebody(bool bIsLeftRight);\n void Function();\n void Binom();\n void Stack();\n void Matrix();\n void Special();\n void GlyphSpecial();\n \/\/ end of grammar\n\n LanguageType GetLanguage() const { return m_nLang; }\n void SetLanguage( LanguageType nNewLang ) { m_nLang = nNewLang; }\n\n void Error(SmParseError Error);\n\n void ClearUsedSymbols() { m_aUsedSymbols.clear(); }\n void AddToUsedSymbols( const OUString &rSymbolName ) { m_aUsedSymbols.insert( rSymbolName ); }\n\npublic:\n SmParser();\n\n \/** Parse rBuffer to formula tree *\/\n SmNode *Parse(const OUString &rBuffer);\n \/** Parse rBuffer to formula subtree that constitutes an expression *\/\n SmNode *ParseExpression(const OUString &rBuffer);\n\n const OUString & GetText() const { return m_aBufferString; };\n\n bool IsImportSymbolNames() const { return bImportSymNames; }\n void SetImportSymbolNames(bool bVal) { bImportSymNames = bVal; }\n bool IsExportSymbolNames() const { return m_bExportSymNames; }\n void SetExportSymbolNames(bool bVal) { m_bExportSymNames = bVal; }\n\n size_t AddError(SmParseError Type, SmNode *pNode);\n const SmErrorDesc* NextError();\n const SmErrorDesc* PrevError();\n const SmErrorDesc* GetError(size_t i = size_t(-1) );\n static const SmTokenTableEntry* GetTokenTableEntry( const OUString &rName );\n bool IsUsedSymbol( const OUString &rSymbolName ) const { return m_aUsedSymbols.find( rSymbolName ) != m_aUsedSymbols.end(); }\n std::set< OUString > GetUsedSymbols() const { return m_aUsedSymbols; }\n};\n\n\ninline bool SmParser::TokenInGroup( sal_uLong nGroup)\n{\n return (m_aCurToken.nGroup & nGroup) ? true : false;\n}\n\n\n#endif\n\n\/* vim:set shiftwidth=4 softtabstop=4 expandtab: *\/\nOmit unused default value\/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- *\/\n\/*\n * This file is part of the LibreOffice project.\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\n * This file incorporates work covered by the following license notice:\n *\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed\n * with this work for additional information regarding copyright\n * ownership. The ASF licenses this file to you under the Apache\n * License, Version 2.0 (the \"License\"); you may not use this file\n * except in compliance with the License. You may obtain a copy of\n * the License at http:\/\/www.apache.org\/licenses\/LICENSE-2.0 .\n *\/\n#ifndef INCLUDED_STARMATH_INC_PARSE_HXX\n#define INCLUDED_STARMATH_INC_PARSE_HXX\n\n#include \n\n#include \n\n#include \"types.hxx\"\n#include \"token.hxx\"\n#include \"error.hxx\"\n#include \"node.hxx\"\n\n#include \n\nclass SmParser : boost::noncopyable\n{\n OUString m_aBufferString;\n SmToken m_aCurToken;\n SmNodeStack m_aNodeStack;\n SmErrDescList m_aErrDescList;\n int m_nCurError;\n LanguageType m_nLang;\n sal_Int32 m_nBufferIndex,\n m_nTokenIndex;\n sal_Int32 m_Row,\n m_nColOff;\n bool bImportSymNames,\n m_bExportSymNames;\n\n \/\/ map of used symbols (used to reduce file size by exporting only actually used symbols)\n std::set< OUString > m_aUsedSymbols;\n\n \/\/! locale where '.' is decimal separator!\n ::com::sun::star::lang::Locale m_aDotLoc;\n\nprotected:\n#if OSL_DEBUG_LEVEL > 1\n bool IsDelimiter( const OUString &rTxt, sal_Int32 nPos );\n#endif\n void NextToken();\n sal_Int32 GetTokenIndex() const { return m_nTokenIndex; }\n void Replace( sal_Int32 nPos, sal_Int32 nLen, const OUString &rText );\n\n inline bool TokenInGroup( sal_uLong nGroup );\n\n \/\/ grammar\n void Table();\n void Line();\n void Expression();\n void Relation();\n void Sum();\n void Product();\n void SubSup(sal_uLong nActiveGroup);\n void OpSubSup();\n void Power();\n void Blank();\n void Term(bool bGroupNumberIdent);\n void Escape();\n void Operator();\n void Oper();\n void UnOper();\n void Align();\n void FontAttribut();\n void Attribut();\n void Font();\n void FontSize();\n void Color();\n void Brace();\n void Bracebody(bool bIsLeftRight);\n void Function();\n void Binom();\n void Stack();\n void Matrix();\n void Special();\n void GlyphSpecial();\n \/\/ end of grammar\n\n LanguageType GetLanguage() const { return m_nLang; }\n void SetLanguage( LanguageType nNewLang ) { m_nLang = nNewLang; }\n\n void Error(SmParseError Error);\n\n void ClearUsedSymbols() { m_aUsedSymbols.clear(); }\n void AddToUsedSymbols( const OUString &rSymbolName ) { m_aUsedSymbols.insert( rSymbolName ); }\n\npublic:\n SmParser();\n\n \/** Parse rBuffer to formula tree *\/\n SmNode *Parse(const OUString &rBuffer);\n \/** Parse rBuffer to formula subtree that constitutes an expression *\/\n SmNode *ParseExpression(const OUString &rBuffer);\n\n const OUString & GetText() const { return m_aBufferString; };\n\n bool IsImportSymbolNames() const { return bImportSymNames; }\n void SetImportSymbolNames(bool bVal) { bImportSymNames = bVal; }\n bool IsExportSymbolNames() const { return m_bExportSymNames; }\n void SetExportSymbolNames(bool bVal) { m_bExportSymNames = bVal; }\n\n size_t AddError(SmParseError Type, SmNode *pNode);\n const SmErrorDesc* NextError();\n const SmErrorDesc* PrevError();\n const SmErrorDesc* GetError(size_t i);\n static const SmTokenTableEntry* GetTokenTableEntry( const OUString &rName );\n bool IsUsedSymbol( const OUString &rSymbolName ) const { return m_aUsedSymbols.find( rSymbolName ) != m_aUsedSymbols.end(); }\n std::set< OUString > GetUsedSymbols() const { return m_aUsedSymbols; }\n};\n\n\ninline bool SmParser::TokenInGroup( sal_uLong nGroup)\n{\n return (m_aCurToken.nGroup & nGroup) ? true : false;\n}\n\n\n#endif\n\n\/* vim:set shiftwidth=4 softtabstop=4 expandtab: *\/\n<|endoftext|>"} {"text":"\/\/ -------------------------------------------------------------------\n\/\/ Copyright 2014 nil authors. All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions\n\/\/ are met:\n\/\/\n\/\/ 1. Redistributions of source code must retain the above copyright\n\/\/ notice, this list of conditions and the following disclaimer.\n\/\/\n\/\/ 2. Redistributions in binary form must reproduce the above\n\/\/ copyright notice, this list of conditions and the following\n\/\/ disclaimer in the documentation and\/or other materials provided\n\/\/ with the distribution.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE NAMEPSACE EWALENA AUTHORS ``AS\n\/\/ IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n\/\/ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n\/\/ FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n\/\/ NAMESPACE EWALENA AUTHORS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n\/\/ INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n\/\/ (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n\/\/ SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n\/\/ HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,\n\/\/ STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n\/\/ ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED\n\/\/ OF THE POSSIBILITY OF SUCH DAMAGE.\n\/\/\n\/\/ The views and conclusions contained in the software and\n\/\/ documentation are those of the authors and should not be\n\/\/ interpreted as representing official policies, either expressed or\n\/\/ implied, of the nil authors.\n\/\/ -------------------------------------------------------------------\n\n#include \"..\/include\/nil\/geometry_function.h\"\n\nnamespace nil\n{\n \n namespace GeometryFunction\n {\n \n template \n double\n HyperCube::value (const dealii::Point &p,\n\t\t\t\t const unsigned int \/* component *\/) const\n {\n double is_in_hyper_cube = 0.;\n \n switch (dim)\n\t{\n\n\tcase 1:\n\t {\n\t if ((p[0]<=right_) && (p[0]>=left_))\n\t is_in_hyper_cube = 1.;\n\t break;\n\t }\n\t \n\tcase 2:\n\t {\n\t if ((p[0]<=right_) && (p[0]>=left_) &&\n\t\t(p[1]<=right_) && (p[1]>=left_))\n\t is_in_hyper_cube = 1.;\n\t break;\n\t }\n\t \n\tcase 3:\n\t {\n\t if ((p[0]<=right_) && (p[0]>=left_) &&\n\t\t(p[1]<=right_) && (p[1]>=left_) &&\n\t\t(p[2]<=right_) && (p[2]>=left_))\n\t is_in_hyper_cube = 1.;\n\t break;\n\t }\n\t \n\tdefault:\n\t AssertThrow (false, dealii::ExcNotImplemented ());\n\t}\n \n return is_in_hyper_cube;\n }\n\n\n template \n double\n HyperBall::value (const dealii::Point &p,\n\t\t\t\t const unsigned int \/* component *\/) const\n {\n double is_in_hyper_ball = 0.;\n \n const double distance = p.distance (center_);\n \n if (distance<=radius_)\n\tis_in_hyper_ball = 1.;\n\n return is_in_hyper_ball;\n }\n\n\n template \n double\n HalfHyperBall::value (const dealii::Point &p,\n\t\t\t\t\t const unsigned int \/* component *\/) const\n {\n double is_in_half_hyper_ball = 0.;\n \n \/\/ This is the distance to the center that refers to a\n \/\/ hyper-ball.\n const double distance = p.distance (center_);\n \n switch (dim)\n\t{\n\n\tcase 2:\n\t \/\/ check if we are in the upper half of the half\n\t \/\/ hyper-ball. In 2d this happens if the 2-axis of the point\n\t \/\/ is above or on the z-axis of the center\n\t if ((p[1]>=center_[1]) && \n\t (distance<=radius_))\n\t is_in_half_hyper_ball = 1.;\n\t \n\t break;\n\n\tcase 3:\n\n\t \/\/ check if we are in the upper half of the half\n\t \/\/ hyper-ball. In 3d this happens if the 3-axis of the point\n\t \/\/ is above or on the z-axis of the center\n\t if ((p[2]>=center_[2]) && \n\t (distance<=radius_))\n\t is_in_half_hyper_ball = 1.;\n\t \n\t break;\n\t \n\tdefault:\n\t AssertThrow (false, dealii::ExcNotImplemented ());\n\t}\n\n\n if (distance<=radius_)\n\tis_in_half_hyper_ball = 1.;\n\n return is_in_half_hyper_ball;\n }\n \n\n template \n double\n SquarePyramid::value (const dealii::Point &p,\n\t\t\t\t\t const unsigned int \/* component *\/) const\n {\n double is_in_square_pyramid = 0.;\n\n switch (dim)\n\t{\n\tcase 3:\n\n\t \/\/ Project the coordinate onto the first quadrant by using\n\t \/\/ and work with its absolute value.\n\t AssertThrow (false, dealii::ExcNotImplemented ());\n\t break;\n\n\tdefault:\n\t AssertThrow (false, dealii::ExcNotImplemented ());\n\t}\n \n return is_in_square_pyramid;\n }\n\n\n template \n double\n HexagonalPyramid::value (const dealii::Point &p,\n\t\t\t\t\t const unsigned int \/* component *\/) const\n {\n double is_in_hexagonal_pyramid = 0.;\n \n switch (dim)\n\t{\n\tcase 3:\n\n\t \/\/ Project the coordinate onto the first quadrant by using\n\t \/\/ and work with its absolute value.\n\t AssertThrow (false, dealii::ExcNotImplemented ());\n\t break;\n\t \n\tdefault:\n\t AssertThrow (false, dealii::ExcNotImplemented ());\n\t}\n\n return is_in_hexagonal_pyramid;\n }\n\n \n } \/\/ name GeometryDescription\n \n} \/\/ namespace nil\n\n\n\/\/ -------------- Explicit Instantiations -------------------------------\n\n#include \"geometry_function.inst\"\nBug fix.\/\/ -------------------------------------------------------------------\n\/\/ Copyright 2014 nil authors. All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions\n\/\/ are met:\n\/\/\n\/\/ 1. Redistributions of source code must retain the above copyright\n\/\/ notice, this list of conditions and the following disclaimer.\n\/\/\n\/\/ 2. Redistributions in binary form must reproduce the above\n\/\/ copyright notice, this list of conditions and the following\n\/\/ disclaimer in the documentation and\/or other materials provided\n\/\/ with the distribution.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE NAMEPSACE EWALENA AUTHORS ``AS\n\/\/ IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n\/\/ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n\/\/ FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n\/\/ NAMESPACE EWALENA AUTHORS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n\/\/ INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n\/\/ (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n\/\/ SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n\/\/ HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,\n\/\/ STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n\/\/ ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED\n\/\/ OF THE POSSIBILITY OF SUCH DAMAGE.\n\/\/\n\/\/ The views and conclusions contained in the software and\n\/\/ documentation are those of the authors and should not be\n\/\/ interpreted as representing official policies, either expressed or\n\/\/ implied, of the nil authors.\n\/\/ -------------------------------------------------------------------\n\n#include \"..\/include\/nil\/geometry_function.h\"\n\nnamespace nil\n{\n \n namespace GeometryFunction\n {\n \n template \n double\n HyperCube::value (const dealii::Point &p,\n\t\t\t\t const unsigned int \/* component *\/) const\n {\n double is_in_hyper_cube = 0.;\n \n switch (dim)\n\t{\n\n\tcase 1:\n\t {\n\t if ((p[0]<=right_) && (p[0]>=left_))\n\t is_in_hyper_cube = 1.;\n\t break;\n\t }\n\t \n\tcase 2:\n\t {\n\t if ((p[0]<=right_) && (p[0]>=left_) &&\n\t\t(p[1]<=right_) && (p[1]>=left_))\n\t is_in_hyper_cube = 1.;\n\t break;\n\t }\n\t \n\tcase 3:\n\t {\n\t if ((p[0]<=right_) && (p[0]>=left_) &&\n\t\t(p[1]<=right_) && (p[1]>=left_) &&\n\t\t(p[2]<=right_) && (p[2]>=left_))\n\t is_in_hyper_cube = 1.;\n\t break;\n\t }\n\t \n\tdefault:\n\t AssertThrow (false, dealii::ExcNotImplemented ());\n\t}\n \n return is_in_hyper_cube;\n }\n\n\n template \n double\n HyperBall::value (const dealii::Point &p,\n\t\t\t\t const unsigned int \/* component *\/) const\n {\n double is_in_hyper_ball = 0.;\n \n const double distance = p.distance (center_);\n \n if (distance<=radius_)\n\tis_in_hyper_ball = 1.;\n\n return is_in_hyper_ball;\n }\n\n\n template \n double\n HalfHyperBall::value (const dealii::Point &p,\n\t\t\t\t\t const unsigned int \/* component *\/) const\n {\n double is_in_half_hyper_ball = 0.;\n \n \/\/ This is the distance to the center that refers to a\n \/\/ hyper-ball.\n const double distance = p.distance (center_);\n \n switch (dim)\n\t{\n\n\tcase 2:\n\t \/\/ check if we are in the upper half of the half\n\t \/\/ hyper-ball. In 2d this happens if the 2-axis of the point\n\t \/\/ is above or on the z-axis of the center\n\t if ((p[1]>=center_[1]) && \n\t (distance<=radius_))\n\t is_in_half_hyper_ball = 1.;\n\t \n\t break;\n\n\tcase 3:\n\n\t \/\/ check if we are in the upper half of the half\n\t \/\/ hyper-ball. In 3d this happens if the 3-axis of the point\n\t \/\/ is above or on the z-axis of the center\n\t if ((p[2]>=center_[2]) && \n\t (distance<=radius_))\n\t is_in_half_hyper_ball = 1.;\n\t \n\t break;\n\t \n\tdefault:\n\t AssertThrow (false, dealii::ExcNotImplemented ());\n\t}\n\n return is_in_half_hyper_ball;\n }\n \n\n template \n double\n SquarePyramid::value (const dealii::Point &p,\n\t\t\t\t\t const unsigned int \/* component *\/) const\n {\n double is_in_square_pyramid = 0.;\n\n switch (dim)\n\t{\n\tcase 3:\n\n\t \/\/ Project the coordinate onto the first quadrant by using\n\t \/\/ and work with its absolute value.\n\t AssertThrow (false, dealii::ExcNotImplemented ());\n\t break;\n\n\tdefault:\n\t AssertThrow (false, dealii::ExcNotImplemented ());\n\t}\n \n return is_in_square_pyramid;\n }\n\n\n template \n double\n HexagonalPyramid::value (const dealii::Point &p,\n\t\t\t\t\t const unsigned int \/* component *\/) const\n {\n double is_in_hexagonal_pyramid = 0.;\n \n switch (dim)\n\t{\n\tcase 3:\n\n\t \/\/ Project the coordinate onto the first quadrant by using\n\t \/\/ and work with its absolute value.\n\t AssertThrow (false, dealii::ExcNotImplemented ());\n\t break;\n\t \n\tdefault:\n\t AssertThrow (false, dealii::ExcNotImplemented ());\n\t}\n\n return is_in_hexagonal_pyramid;\n }\n\n \n } \/\/ name GeometryDescription\n \n} \/\/ namespace nil\n\n\n\/\/ -------------- Explicit Instantiations -------------------------------\n\n#include \"geometry_function.inst\"\n<|endoftext|>"} {"text":"#include \"SymbolFile.h\"\n#include \"SymbolType.h\"\n#include \"FileHelper.h\"\n\n#include \n#include \n\nnamespace ee\n{\n\nSINGLETON_DEFINITION(SymbolFile);\n\nstatic const char* TAG_GEN = \"gen\";\n\nSymbolFile::SymbolFile()\n{\n\tRegist(SYM_ANIS,\t\t\"anis\");\n\tRegist(SYM_FONTBLANK,\t\"fontblank\");\n\tRegist(SYM_FREETYPE,\t\"freetype\");\n\tRegist(SYM_SCRIPTS,\t\t\"scripts\");\n\tRegist(SYM_P3DINV,\t\t\"p3dinv\");\n\tRegist(SYM_EJOY2D,\t\t\"ejoy2d\");\n\tRegist(SYM_TERRAIN2D,\t\"terrain2d\");\n\tRegist(SYM_SHADOW,\t\t\"shadow\");\n\tRegist(SYM_UI,\t\t\t\"ui\");\n\tRegist(SYM_PSD,\t\t\t\"psd\");\n\tRegist(SYM_UIWND,\t\t\"uiwnd\");\n\n\tRegist(s2::SYM_SCALE9,\t\t\"scale9\");\n\tRegist(s2::SYM_ICON,\t\t\"icon\");\n\tRegist(s2::SYM_TEXTURE,\t\t\"texture\");\n\tRegist(s2::SYM_TEXTBOX,\t\t\"text\");\n\tRegist(s2::SYM_COMPLEX,\t\t\"complex\");\n\tRegist(s2::SYM_ANIMATION,\t\"anim\");\n\tRegist(s2::SYM_PARTICLE3D,\t\"particle\");\n\tRegist(s2::SYM_PARTICLE2D,\t\"particle2d\");\n\tRegist(s2::SYM_SHAPE,\t\t\"shape\");\n\tRegist(s2::SYM_MESH,\t\t\"mesh\");\n\tRegist(s2::SYM_MASK,\t\t\"mask\");\n\tRegist(s2::SYM_TRAIL,\t\t\"trail\");\n\tRegist(s2::SYM_SKELETON,\t\"skeleton\");\n}\n\nint SymbolFile::Type(const std::string& filepath) const\n{\n\tint type = gum::SymbolFile::Instance()->Type(filepath);\n\tif (type != s2::SYM_UNKNOWN && type != s2::SYM_INVALID) {\n\t\treturn type;\n\t}\n\t\n\tint pos = filepath.rfind('.');\n\tstd::string ext = filepath.substr(pos + 1);\n\tif (ext == \"json\")\n\t{\n\t\tconst std::string filename = filepath.substr(0, filepath.find_last_of('.'));\n\t\tint pos = filename.find_last_of('_');\n\t\tif (pos == -1) {\n\t\t\treturn s2::SYM_UNKNOWN;\n\t\t}\n\n\t\tstd::string tag = filename.substr(pos + 1);\n\t\tpos = tag.find(TAG_GEN);\n\t\tif (pos != std::string::npos) {\n\t\t\ttag = tag.substr(0, pos - 1);\n\t\t}\n\n\t\tstd::map::const_iterator itr = m_tag2type.find(tag);\n\t\tif (itr != m_tag2type.end()) {\n\t\t\treturn itr->second;\n\t\t} else {\n\t\t\treturn s2::SYM_UNKNOWN;\n\t\t}\n\t}\n\telse if (ext == \"lua\")\n\t{\n\t\tconst std::string name = filepath.substr(0, filepath.find_last_of('.'));\n\t\tif (name.find('_') == -1) {\n\t\t\treturn s2::SYM_UNKNOWN;\n\t\t}\n\t\tconst std::string json_ext = name.substr(name.find_last_of('_') + 1);\n\t\tif (json_ext == \"scripts\") {\n\t\t\treturn SYM_SCRIPTS;\n\t\t} else {\n\t\t\treturn s2::SYM_UNKNOWN;\n\t\t}\n\t}\n\telse if (ext == \"ttf\")\n\t{\n\t\treturn SYM_FREETYPE;\n\t}\n\telse\n\t{\n\t\tstd::string filename = FileHelper::GetFilename(filepath);\n\t\tif (filename == SYM_GROUP_TAG) {\n\t\t\treturn s2::SYM_COMPLEX;\n\t\t}\n\t}\n\n\treturn s2::SYM_UNKNOWN;\n}\n\nconst std::string& SymbolFile::Tag(int type) const\n{\n\tconst std::string& tag = gum::SymbolFile::Instance()->Tag(type);\n\tif (tag != gum::SymbolFile::UNKNOWN_TAG) {\n\t\treturn tag;\n\t}\n\n\tstd::map::const_iterator itr = m_type2tag.find(type);\n\tif (itr != m_type2tag.end()) {\n\t\treturn itr->second;\n\t} else {\n\t\treturn gum::SymbolFile::UNKNOWN_TAG;\n\t}\n}\n\nvoid SymbolFile::Regist(int type, const std::string& tag)\n{\n\tm_type2tag.insert(std::make_pair(type, tag));\n\tm_tag2type.insert(std::make_pair(tag, type));\n}\n\n}[ADDED] open spine sym#include \"SymbolFile.h\"\n#include \"SymbolType.h\"\n#include \"FileHelper.h\"\n\n#include \n#include \n\n#include \n\n#include \n\nnamespace ee\n{\n\nSINGLETON_DEFINITION(SymbolFile);\n\nstatic const char* TAG_GEN = \"gen\";\n\nSymbolFile::SymbolFile()\n{\n\tRegist(SYM_ANIS,\t\t\"anis\");\n\tRegist(SYM_FONTBLANK,\t\"fontblank\");\n\tRegist(SYM_FREETYPE,\t\"freetype\");\n\tRegist(SYM_SCRIPTS,\t\t\"scripts\");\n\tRegist(SYM_P3DINV,\t\t\"p3dinv\");\n\tRegist(SYM_EJOY2D,\t\t\"ejoy2d\");\n\tRegist(SYM_TERRAIN2D,\t\"terrain2d\");\n\tRegist(SYM_SHADOW,\t\t\"shadow\");\n\tRegist(SYM_UI,\t\t\t\"ui\");\n\tRegist(SYM_PSD,\t\t\t\"psd\");\n\tRegist(SYM_UIWND,\t\t\"uiwnd\");\n\n\tRegist(s2::SYM_SCALE9,\t\t\"scale9\");\n\tRegist(s2::SYM_ICON,\t\t\"icon\");\n\tRegist(s2::SYM_TEXTURE,\t\t\"texture\");\n\tRegist(s2::SYM_TEXTBOX,\t\t\"text\");\n\tRegist(s2::SYM_COMPLEX,\t\t\"complex\");\n\tRegist(s2::SYM_ANIMATION,\t\"anim\");\n\tRegist(s2::SYM_PARTICLE3D,\t\"particle\");\n\tRegist(s2::SYM_PARTICLE2D,\t\"particle2d\");\n\tRegist(s2::SYM_SHAPE,\t\t\"shape\");\n\tRegist(s2::SYM_MESH,\t\t\"mesh\");\n\tRegist(s2::SYM_MASK,\t\t\"mask\");\n\tRegist(s2::SYM_TRAIL,\t\t\"trail\");\n\tRegist(s2::SYM_SKELETON,\t\"skeleton\");\n}\n\nint SymbolFile::Type(const std::string& filepath) const\n{\n\tint type = gum::SymbolFile::Instance()->Type(filepath);\n\tif (type != s2::SYM_UNKNOWN && type != s2::SYM_INVALID) {\n\t\treturn type;\n\t}\n\t\n\tint pos = filepath.rfind('.');\n\tstd::string ext = filepath.substr(pos + 1);\n\tif (ext == \"json\")\n\t{\n\t\tconst std::string filename = filepath.substr(0, filepath.find_last_of('.'));\n\t\tint pos = filename.find_last_of('_');\n\t\tif (pos == -1) {\n\t\t\treturn s2::SYM_UNKNOWN;\n\t\t}\n\n\t\tstd::string tag = filename.substr(pos + 1);\n\t\tpos = tag.find(TAG_GEN);\n\t\tif (pos != std::string::npos) {\n\t\t\ttag = tag.substr(0, pos - 1);\n\t\t}\n\n\t\tstd::map::const_iterator itr = m_tag2type.find(tag);\n\t\tif (itr != m_tag2type.end()) {\n\t\t\treturn itr->second;\n\t\t} \n\n\t\tJson::Value val;\n\t\tJson::Reader reader;\n\t\tstd::locale::global(std::locale(\"\"));\n\t\tstd::ifstream fin(filepath.c_str());\n\t\tstd::locale::global(std::locale(\"C\"));\n\t\treader.parse(fin, val);\n\t\tfin.close();\n\n\t\tif (val.isMember(\"skeleton\") && !val[\"skeleton\"].isArray() && val[\"skeleton\"].isMember(\"spine\")) {\n\t\t\treturn s2::SYM_ANIM2;\n\t\t}\n\n\t\treturn s2::SYM_UNKNOWN;\n\t}\n\telse if (ext == \"lua\")\n\t{\n\t\tconst std::string name = filepath.substr(0, filepath.find_last_of('.'));\n\t\tif (name.find('_') == -1) {\n\t\t\treturn s2::SYM_UNKNOWN;\n\t\t}\n\t\tconst std::string json_ext = name.substr(name.find_last_of('_') + 1);\n\t\tif (json_ext == \"scripts\") {\n\t\t\treturn SYM_SCRIPTS;\n\t\t} else {\n\t\t\treturn s2::SYM_UNKNOWN;\n\t\t}\n\t}\n\telse if (ext == \"ttf\")\n\t{\n\t\treturn SYM_FREETYPE;\n\t}\n\telse\n\t{\n\t\tstd::string filename = FileHelper::GetFilename(filepath);\n\t\tif (filename == SYM_GROUP_TAG) {\n\t\t\treturn s2::SYM_COMPLEX;\n\t\t}\n\t}\n\n\treturn s2::SYM_UNKNOWN;\n}\n\nconst std::string& SymbolFile::Tag(int type) const\n{\n\tconst std::string& tag = gum::SymbolFile::Instance()->Tag(type);\n\tif (tag != gum::SymbolFile::UNKNOWN_TAG) {\n\t\treturn tag;\n\t}\n\n\tstd::map::const_iterator itr = m_type2tag.find(type);\n\tif (itr != m_type2tag.end()) {\n\t\treturn itr->second;\n\t} else {\n\t\treturn gum::SymbolFile::UNKNOWN_TAG;\n\t}\n}\n\nvoid SymbolFile::Regist(int type, const std::string& tag)\n{\n\tm_type2tag.insert(std::make_pair(type, tag));\n\tm_tag2type.insert(std::make_pair(tag, type));\n}\n\n}<|endoftext|>"} {"text":"#include \"SelectShapesOP.h\"\n#include \"Rect.h\"\n#include \"MultiShapesImpl.h\"\n#include \"ShapeSelection.h\"\n#include \"EditPanelImpl.h\"\n#include \"EditCMPT.h\"\n#include \"DrawSelectedShapeVisitor.h\"\n#include \"shape_msg.h\"\n#include \"panel_msg.h\"\n#include \"FetchAllVisitor.h\"\n\nnamespace ee\n{\n\nSelectShapesOP::SelectShapesOP(wxWindow* wnd, EditPanelImpl* stage, MultiShapesImpl* shapes_impl,\n\t\t\t\t\t\t\t EditCMPT* callback\/* = NULL*\/)\n\t: DrawRectangleOP(wnd, stage)\n\t, m_callback(callback)\n\t, m_shape_impl(shapes_impl)\n\t, m_bDraggable(true)\n{\n\tm_selection = shapes_impl->GetShapeSelection();\n\tm_selection->Retain();\n\n\tm_first_pos.SetInvalid();\n}\n\nSelectShapesOP::~SelectShapesOP()\n{\n\tclearClipboard();\n\n \tm_selection->Clear();\n \tm_selection->Release();\n}\n\nbool SelectShapesOP::OnKeyDown(int keyCode)\n{\n\tif (DrawRectangleOP::OnKeyDown(keyCode)) return true;\n\n\tif (keyCode == WXK_DELETE)\n\t{\n\t\tm_shape_impl->ClearSelectedShape();\n\t\tClear();\n\t}\n\telse if (m_stage->GetKeyState(WXK_CONTROL) && (keyCode == 'x' || keyCode == 'X'))\n\t{\n\t\tPasteToSelection();\n\t\tm_shape_impl->ClearSelectedShape();\n\t}\n\telse if (m_stage->GetKeyState(WXK_CONTROL) && (keyCode == 'c' || keyCode == 'C'))\n\t{\n\t\tclearClipboard();\n\n\t\tstd::vector shapes;\n\t\tm_selection->Traverse(FetchAllVisitor(shapes));\n\t\tfor (size_t i = 0, n = shapes.size(); i < n; ++i)\n\t\t\tm_clipboard.push_back(shapes[i]->Clone());\n\t}\n\telse if (m_stage->GetKeyState(WXK_CONTROL) && (keyCode == 'v' || keyCode == 'V'))\n\t{\n\t\tfor (size_t i = 0, n = m_clipboard.size(); i < n; ++i) {\n\t\t\tInsertShapeSJ::Instance()->Insert(m_clipboard[i]->Clone());\n\t\t}\n\t}\n\n\treturn false;\n}\n\nbool SelectShapesOP::OnMouseLeftDown(int x, int y)\n{\n\tm_bDraggable = true;\n\n\tm_move_last_pos.SetInvalid();\n\n\tVector pos = m_stage->TransPosScrToProj(x, y);\n\tShape* selected = m_shape_impl->QueryShapeByPos(pos);\n\tif (selected)\n\t{\n\t\tif (m_stage->GetKeyState(WXK_CONTROL))\n\t\t{\n\t\t\tif (m_selection->IsExist(selected)) {\n\t\t\t\tm_selection->Remove(selected);\n\t\t\t} else {\n\t\t\t\tm_selection->Add(selected);\n\t\t\t}\n\t\t\tSelectShapeSetSJ::Instance()->Selecte(m_selection, m_shape_impl);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif (!m_selection->IsExist(selected))\n\t\t\t{\n\t\t\t\tm_selection->Clear();\n\t\t\t\tm_selection->Add(selected);\n\t\t\t\tSelectShapeSJ::Instance()->Select(selected, m_shape_impl);\n\t\t\t} else {\n\t\t\t\tm_move_last_pos = pos;\n\t\t\t}\n\t\t}\n\t\tm_first_pos.SetInvalid();\n\n\t\tif (m_callback)\n\t\t\tm_callback->UpdateControlValue();\n\t}\n\telse\n\t{\n\t\tDrawRectangleOP::OnMouseLeftDown(x, y);\n\t\tm_first_pos = pos;\n\t\tif (m_stage->GetKeyState(WXK_CONTROL))\n\t\t\tm_bDraggable = false;\n\t\telse\n\t\t\tm_selection->Clear();\n\t}\n\n\treturn false;\n}\n\nbool SelectShapesOP::OnMouseLeftUp(int x, int y)\n{\n\tif (DrawRectangleOP::OnMouseLeftUp(x, y)) return true;\n\n\tm_bDraggable = true;\n\n\tif (m_first_pos.IsValid())\n\t{\n\t\tRect rect(m_first_pos, m_stage->TransPosScrToProj(x, y));\n\t\tstd::vector shapes;\n\t\tm_shape_impl->QueryShapesByRect(rect, shapes);\n\t\tfor (size_t i = 0, n = shapes.size(); i < n; ++i)\n\t\t\tm_selection->Add(shapes[i]);\n\n\t\tSelectShapeSetSJ::Instance()->Selecte(m_selection, m_shape_impl);\n\n\t\tm_first_pos.SetInvalid();\n\n\t\tif (m_callback) {\n\t\t\tm_callback->UpdateControlValue();\n\t\t}\n\t}\n\n\tSetCanvasDirtySJ::Instance()->SetDirty();\n\n\treturn false;\n}\n\nbool SelectShapesOP::OnMouseDrag(int x, int y)\n{\n\tif (DrawRectangleOP::OnMouseDrag(x, y)) return true;\n\n\tif (!m_selection->IsEmpty() && m_move_last_pos.IsValid()) {\n\t\tVector pos = m_stage->TransPosScrToProj(x, y);\n\t\tm_selection->Traverse(TranslateVisitor(pos - m_move_last_pos));\n\t\tm_move_last_pos = pos;\n\t}\n\n\treturn !m_bDraggable;\n}\n\nbool SelectShapesOP::OnDraw() const\n{\n\tif (DrawRectangleOP::OnDraw()) return true;\n\n\tm_selection->Traverse(DrawSelectedShapeVisitor());\n\n\treturn false;\n}\n\nbool SelectShapesOP::Clear()\n{\n\tif (DrawRectangleOP::Clear()) return true;\n\n\tclearClipboard();\n\tm_selection->Clear();\n\tm_first_pos.SetInvalid();\n\n\treturn false;\n}\n\nvoid SelectShapesOP::clearClipboard()\n{\n \tfor (size_t i = 0, n = m_clipboard.size(); i < n; ++i)\n \t\tm_clipboard[i]->Release();\n \tm_clipboard.clear();\n}\n\nvoid SelectShapesOP::PasteToSelection() const\n{\n\tstd::vector shapes;\n\tm_selection->Traverse(FetchAllVisitor(shapes));\n\tfor (size_t i = 0, n = shapes.size(); i < n; ++i) {\n\t\tm_clipboard.push_back(shapes[i]->Clone());\n\t}\n}\n\nvoid SelectShapesOP::CopyFromSelection()\n{\n\tfor (size_t i = 0, n = m_clipboard.size(); i < n; ++i) {\n\t\tInsertShapeSJ::Instance()->Insert(m_clipboard[i]->Clone());\n\t}\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ class TranslateSpriteState::TranslateVisitor\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid SelectShapesOP::TranslateVisitor::\nVisit(Object* object, bool& next)\n{\n\tShape* shape = static_cast(object);\n\tshape->Translate(m_offset);\n\tnext = true;\n}\n\n}[CHANGED] close move shape#include \"SelectShapesOP.h\"\n#include \"Rect.h\"\n#include \"MultiShapesImpl.h\"\n#include \"ShapeSelection.h\"\n#include \"EditPanelImpl.h\"\n#include \"EditCMPT.h\"\n#include \"DrawSelectedShapeVisitor.h\"\n#include \"shape_msg.h\"\n#include \"panel_msg.h\"\n#include \"FetchAllVisitor.h\"\n\nnamespace ee\n{\n\nSelectShapesOP::SelectShapesOP(wxWindow* wnd, EditPanelImpl* stage, MultiShapesImpl* shapes_impl,\n\t\t\t\t\t\t\t EditCMPT* callback\/* = NULL*\/)\n\t: DrawRectangleOP(wnd, stage)\n\t, m_callback(callback)\n\t, m_shape_impl(shapes_impl)\n\t, m_bDraggable(true)\n{\n\tm_selection = shapes_impl->GetShapeSelection();\n\tm_selection->Retain();\n\n\tm_first_pos.SetInvalid();\n}\n\nSelectShapesOP::~SelectShapesOP()\n{\n\tclearClipboard();\n\n \tm_selection->Clear();\n \tm_selection->Release();\n}\n\nbool SelectShapesOP::OnKeyDown(int keyCode)\n{\n\tif (DrawRectangleOP::OnKeyDown(keyCode)) return true;\n\n\tif (keyCode == WXK_DELETE)\n\t{\n\t\tm_shape_impl->ClearSelectedShape();\n\t\tClear();\n\t}\n\telse if (m_stage->GetKeyState(WXK_CONTROL) && (keyCode == 'x' || keyCode == 'X'))\n\t{\n\t\tPasteToSelection();\n\t\tm_shape_impl->ClearSelectedShape();\n\t}\n\telse if (m_stage->GetKeyState(WXK_CONTROL) && (keyCode == 'c' || keyCode == 'C'))\n\t{\n\t\tclearClipboard();\n\n\t\tstd::vector shapes;\n\t\tm_selection->Traverse(FetchAllVisitor(shapes));\n\t\tfor (size_t i = 0, n = shapes.size(); i < n; ++i)\n\t\t\tm_clipboard.push_back(shapes[i]->Clone());\n\t}\n\telse if (m_stage->GetKeyState(WXK_CONTROL) && (keyCode == 'v' || keyCode == 'V'))\n\t{\n\t\tfor (size_t i = 0, n = m_clipboard.size(); i < n; ++i) {\n\t\t\tInsertShapeSJ::Instance()->Insert(m_clipboard[i]->Clone());\n\t\t}\n\t}\n\n\treturn false;\n}\n\nbool SelectShapesOP::OnMouseLeftDown(int x, int y)\n{\n\tm_bDraggable = true;\n\n\tm_move_last_pos.SetInvalid();\n\n\tVector pos = m_stage->TransPosScrToProj(x, y);\n\tShape* selected = m_shape_impl->QueryShapeByPos(pos);\n\tif (selected)\n\t{\n\t\tif (m_stage->GetKeyState(WXK_CONTROL))\n\t\t{\n\t\t\tif (m_selection->IsExist(selected)) {\n\t\t\t\tm_selection->Remove(selected);\n\t\t\t} else {\n\t\t\t\tm_selection->Add(selected);\n\t\t\t}\n\t\t\tSelectShapeSetSJ::Instance()->Selecte(m_selection, m_shape_impl);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif (!m_selection->IsExist(selected))\n\t\t\t{\n\t\t\t\tm_selection->Clear();\n\t\t\t\tm_selection->Add(selected);\n\t\t\t\tSelectShapeSJ::Instance()->Select(selected, m_shape_impl);\n\t\t\t} else {\n\t\t\t\tm_move_last_pos = pos;\n\t\t\t}\n\t\t}\n\t\tm_first_pos.SetInvalid();\n\n\t\tif (m_callback)\n\t\t\tm_callback->UpdateControlValue();\n\t}\n\telse\n\t{\n\t\tDrawRectangleOP::OnMouseLeftDown(x, y);\n\t\tm_first_pos = pos;\n\t\tif (m_stage->GetKeyState(WXK_CONTROL))\n\t\t\tm_bDraggable = false;\n\t\telse\n\t\t\tm_selection->Clear();\n\t}\n\n\treturn false;\n}\n\nbool SelectShapesOP::OnMouseLeftUp(int x, int y)\n{\n\tif (DrawRectangleOP::OnMouseLeftUp(x, y)) return true;\n\n\tm_bDraggable = true;\n\n\tif (m_first_pos.IsValid())\n\t{\n\t\tRect rect(m_first_pos, m_stage->TransPosScrToProj(x, y));\n\t\tstd::vector shapes;\n\t\tm_shape_impl->QueryShapesByRect(rect, shapes);\n\t\tfor (size_t i = 0, n = shapes.size(); i < n; ++i)\n\t\t\tm_selection->Add(shapes[i]);\n\n\t\tSelectShapeSetSJ::Instance()->Selecte(m_selection, m_shape_impl);\n\n\t\tm_first_pos.SetInvalid();\n\n\t\tif (m_callback) {\n\t\t\tm_callback->UpdateControlValue();\n\t\t}\n\t}\n\n\tSetCanvasDirtySJ::Instance()->SetDirty();\n\n\treturn false;\n}\n\nbool SelectShapesOP::OnMouseDrag(int x, int y)\n{\n\tif (DrawRectangleOP::OnMouseDrag(x, y)) return true;\n\n\/\/\t\/\/ no need to move shape?\n\/\/ \tif (!m_selection->IsEmpty() && m_move_last_pos.IsValid()) {\n\/\/ \t\tVector pos = m_stage->TransPosScrToProj(x, y);\n\/\/ \t\tm_selection->Traverse(TranslateVisitor(pos - m_move_last_pos));\n\/\/ \t\tm_move_last_pos = pos;\n\/\/ \t}\n\n\treturn !m_bDraggable;\n}\n\nbool SelectShapesOP::OnDraw() const\n{\n\tif (DrawRectangleOP::OnDraw()) return true;\n\n\tm_selection->Traverse(DrawSelectedShapeVisitor());\n\n\treturn false;\n}\n\nbool SelectShapesOP::Clear()\n{\n\tif (DrawRectangleOP::Clear()) return true;\n\n\tclearClipboard();\n\tm_selection->Clear();\n\tm_first_pos.SetInvalid();\n\n\treturn false;\n}\n\nvoid SelectShapesOP::clearClipboard()\n{\n \tfor (size_t i = 0, n = m_clipboard.size(); i < n; ++i)\n \t\tm_clipboard[i]->Release();\n \tm_clipboard.clear();\n}\n\nvoid SelectShapesOP::PasteToSelection() const\n{\n\tstd::vector shapes;\n\tm_selection->Traverse(FetchAllVisitor(shapes));\n\tfor (size_t i = 0, n = shapes.size(); i < n; ++i) {\n\t\tm_clipboard.push_back(shapes[i]->Clone());\n\t}\n}\n\nvoid SelectShapesOP::CopyFromSelection()\n{\n\tfor (size_t i = 0, n = m_clipboard.size(); i < n; ++i) {\n\t\tInsertShapeSJ::Instance()->Insert(m_clipboard[i]->Clone());\n\t}\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ class TranslateSpriteState::TranslateVisitor\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid SelectShapesOP::TranslateVisitor::\nVisit(Object* object, bool& next)\n{\n\tShape* shape = static_cast(object);\n\tshape->Translate(m_offset);\n\tnext = true;\n}\n\n}<|endoftext|>"} {"text":"\/*************************************************************************\r\n* UrBackup - Client\/Server backup system\r\n* Copyright (C) 2011-2016 Martin Raiber\r\n*\r\n* This program is free software: you can redistribute it and\/or modify\r\n* it under the terms of the GNU Affero General Public License as published by\r\n* the Free Software Foundation, either version 3 of the License, or\r\n* (at your option) any later version.\r\n*\r\n* This program is distributed in the hope that it will be useful,\r\n* but WITHOUT ANY WARRANTY; without even the implied warranty of\r\n* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\r\n* GNU Affero General Public License for more details.\r\n*\r\n* You should have received a copy of the GNU Affero General Public License\r\n* along with this program. If not, see .\r\n**************************************************************************\/\r\n\r\n#include \"vld.h\"\r\n#ifdef _WIN32\r\n#include \r\n#endif\r\n#include \"ServiceAcceptor.h\"\r\n#include \"stringtools.h\"\r\n#include \"ServiceWorker.h\"\r\n#include \r\n\r\n#include \"Interface\/Mutex.h\"\r\n#include \"Interface\/Condition.h\"\r\n#include \"Interface\/Service.h\"\r\n\r\nnamespace\r\n{\r\n\tbool prepareSocket(SOCKET s)\r\n\t{\r\n#if !defined(_WIN32) && !defined(SOCK_CLOEXEC)\n\t\tfcntl(s, F_SETFD, fcntl(s, F_GETFD, 0) | FD_CLOEXEC);\n#endif\r\n\r\n\t\tint optval = 1;\r\n\t\tint rc = setsockopt(s, SOL_SOCKET, SO_REUSEADDR, (char*)&optval, sizeof(int));\r\n\t\tif (rc == SOCKET_ERROR)\r\n\t\t{\r\n\t\t\tServer->Log(\"Failed setting SO_REUSEADDR\", LL_ERROR);\r\n\t\t\treturn false;\r\n\t\t}\r\n\r\n#ifdef __APPLE__\r\n\t\toptval = 1;\r\n\t\tsetsockopt(s, SOL_SOCKET, SO_NOSIGPIPE, (void*)&optval, sizeof(optval));\r\n#endif\r\n\t\treturn true;\r\n\t}\r\n}\r\n\r\nCServiceAcceptor::CServiceAcceptor(IService * pService, std::string pName, unsigned short port, int pMaxClientsPerThread, IServer::BindTarget bindTarget)\r\n\t: maxClientsPerThread(pMaxClientsPerThread), s_v6(SOCKET_ERROR)\r\n{\r\n\tname=pName;\r\n\tservice=pService;\r\n\texitpipe=Server->createMemoryPipe();\r\n\tdo_exit=false;\r\n\thas_error=false;\r\n#ifndef _WIN32\r\n\tpipe(xpipe);\r\n#endif\r\n\r\n\tint rc;\r\n#ifdef _WIN32\r\n\tWSADATA wsadata;\r\n\trc = WSAStartup(MAKEWORD(2,2), &wsadata);\r\n\tif(rc == SOCKET_ERROR)\treturn;\r\n#endif\r\n\r\n\tint type = SOCK_STREAM;\n#if !defined(_WIN32) && defined(SOCK_CLOEXEC)\r\n\ttype |= SOCK_CLOEXEC;\r\n#endif\r\n\ts=socket(AF_INET,type,0);\r\n\tif(s<1)\r\n\t{\r\n\t\tServer->Log(name+\": Creating SOCKET failed\",LL_ERROR);\r\n\t\thas_error=true;\r\n\t\treturn;\r\n\t}\r\n\r\n\tif (!prepareSocket(s))\r\n\t{\r\n\t\thas_error = true;\r\n\t\treturn;\r\n\t}\r\n\r\n\tsockaddr_in addr;\r\n\r\n\tmemset(&addr, 0, sizeof(sockaddr_in));\r\n\taddr.sin_family=AF_INET;\r\n\taddr.sin_port=htons(port);\r\n\tswitch(bindTarget)\r\n\t{\r\n\tcase IServer::BindTarget_All:\r\n\t\taddr.sin_addr.s_addr= htonl(INADDR_ANY);\r\n\t\tbreak;\r\n\tcase IServer::BindTarget_Localhost:\r\n\t\taddr.sin_addr.s_addr=htonl(INADDR_LOOPBACK);\r\n\t\tbreak;\r\n\t}\r\n\r\n\trc=bind(s,(sockaddr*)&addr,sizeof(addr));\r\n\tif(rc==SOCKET_ERROR)\r\n\t{\r\n\t\tServer->Log(name+\": Failed binding socket to port \"+convert(port)+\". Another instance of this application may already be active and bound to this port.\",LL_ERROR);\r\n\t\thas_error=true;\r\n\t\treturn;\r\n\t}\r\n\r\n\tlisten(s, 10000);\r\n\r\n\tif (Server->getServerParameter(\"disable_ipv6\").empty())\n\t{\r\n\t\ts_v6 = socket(AF_INET6, type, 0);\r\n\t\tif (s_v6 < 1)\r\n\t\t{\r\n\t\t\tServer->Log(name + \": Creating v6 SOCKET failed\", LL_ERROR);\r\n\t\t\thas_error = true;\r\n\t\t\treturn;\r\n\t\t}\r\n\r\n\t\tif (!prepareSocket(s_v6))\r\n\t\t{\r\n\t\t\thas_error = true;\r\n\t\t\treturn;\r\n\t\t}\r\n\r\n\t\tint optval = 1;\n\t\tsetsockopt(s_v6, IPPROTO_IPV6, IPV6_V6ONLY, (char*)&optval, sizeof(optval));\r\n\r\n\t\tsockaddr_in6 addr;\r\n\r\n\t\tmemset(&addr, 0, sizeof(addr));\r\n\t\taddr.sin6_family = AF_INET6;\r\n\t\taddr.sin6_port = htons(port);\r\n\t\tswitch (bindTarget)\r\n\t\t{\r\n\t\tcase IServer::BindTarget_All:\r\n\t\t\taddr.sin6_addr = in6addr_any;\r\n\t\t\tbreak;\r\n\t\tcase IServer::BindTarget_Localhost:\r\n\t\t\taddr.sin6_addr= in6addr_loopback;\r\n\t\t\tbreak;\r\n\t\t}\r\n\r\n\t\trc = bind(s_v6, (sockaddr*)&addr, sizeof(addr));\r\n\t\tif (rc == SOCKET_ERROR)\r\n\t\t{\r\n\t\t\tServer->Log(name + \": Failed binding ipv6 socket to port \" + convert(port) + \". Another instance of this application may already be active and bound to this port.\", LL_ERROR);\r\n\t\t\thas_error = true;\r\n\t\t\treturn;\r\n\t\t}\r\n\r\n\t\tlisten(s_v6, 10000);\r\n\t}\r\n\r\n\tServer->Log(name+\": Server started up successfully!\",LL_INFO);\r\n}\r\n\r\nCServiceAcceptor::~CServiceAcceptor()\r\n{\r\n\tif(has_error)\r\n\t\treturn;\r\n\r\n\tdo_exit=true;\r\n#ifndef _WIN32\r\n\tchar ch=0;\r\n\twrite(xpipe[1], &ch, 1);\r\n#endif\r\n\tclosesocket(s);\r\n\tif (s_v6 != SOCKET_ERROR)\r\n\t\tclosesocket(s_v6);\r\n\tfor(size_t i=0;istop();\r\n\t}\r\n\tsize_t c=0;\r\n\tServer->Log(\"c=0\/\"+convert(workers.size()+1));\r\n\twhile(cRead(&r);\r\n\t\tif(r==\"ok\")\r\n\t\t{\r\n\t\t\t++c;\r\n\t\t\tServer->Log(\"c=\"+convert(c)+\"\/\"+convert(workers.size()+1));\r\n\t\t}\r\n\t}\r\n\tServer->destroy(exitpipe);\r\n\tfor(size_t i=0;i=0)\r\n\t\t{\r\n\t\t\tfor (size_t n = 0; n < 2; ++n)\n\t\t\t{\r\n#ifdef _WIN32\n\t\t\t\tSOCKET accept_socket = n == 0 ? s : s_v6;\n\t\t\t\tif (accept_socket == SOCKET_ERROR)\n\t\t\t\t\tcontinue;\n\t\t\t\tif (!FD_ISSET(accept_socket, &fdset))\n\t\t\t\t\tcontinue;\n#else\n\t\t\t\tif (conn[n].revents == 0)\n\t\t\t\t\tcontinue;\n\t\t\t\tSOCKET accept_socket = conn[n].fd;\n#endif\r\n\t\t\t\tif (do_exit)\r\n\t\t\t\t\tbreak;\r\n\r\n\t\t\t\tunion\r\n\t\t\t\t{\r\n\t\t\t\t\tsockaddr_in naddr_v4;\r\n\t\t\t\t\tsockaddr_in6 naddr_v6;\r\n\t\t\t\t} naddr;\r\n\t\t\t\tsocklen_t addrsize;\r\n\t\t\t\tif (accept_socket == s_v6)\r\n\t\t\t\t\taddrsize = sizeof(naddr.naddr_v6);\r\n\t\t\t\telse\r\n\t\t\t\t\taddrsize = sizeof(naddr.naddr_v4);\r\n\r\n\t\t\t\tsockaddr* paddr = (sockaddr*)&naddr;\r\n\t\t\t\tSOCKET ns= ACCEPT_CLOEXEC(accept_socket, paddr, &addrsize);\r\n\t\t\t\tif(ns!=SOCKET_ERROR)\r\n\t\t\t\t{\r\n#ifdef __APPLE__\r\n\t\t\t\t\tint optval = 1;\r\n\t\t\t\t\tsetsockopt(ns, SOL_SOCKET, SO_NOSIGPIPE, (void*)&optval, sizeof(optval));\r\n#endif\r\n\t\t\t\t\t\/\/Server->Log(name+\": New Connection incomming \"+convert(Server->getTimeMS())+\" s: \"+convert((int)ns), LL_DEBUG);\r\n\r\n\t#ifdef _WIN32\r\n\t\t\t\t\tint window_size=Server->getSendWindowSize();\r\n\t\t\t\t\tif(window_size>0)\r\n\t\t\t\t\t\tsetsockopt(ns, SOL_SOCKET, SO_SNDBUF, (char *) &window_size, sizeof(window_size));\r\n\r\n\t\t\t\t\twindow_size = Server->getRecvWindowSize();\r\n\t\t\t\t\tif(window_size>0)\r\n\t\t\t\t\t\tsetsockopt(ns, SOL_SOCKET, SO_RCVBUF, (char *) &window_size, sizeof(window_size));\r\n\t#endif\r\n\t\t\t\t\tchar buf[100];\r\n\t\t\t\t\tconst char* endpoint = inet_ntop(paddr->sa_family,\r\n\t\t\t\t\t\taccept_socket == s_v6 ? (void*)&naddr.naddr_v6.sin6_addr : (void*)&naddr.naddr_v4.sin_addr,\r\n\t\t\t\t\t\tbuf, sizeof(buf));\r\n\r\n\t\t\t\t\tAddToWorker(ns, endpoint!=NULL ? endpoint : \"\");\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tServer->Log(\"Select error in CServiceAcceptor Thread.\", LL_ERROR);\r\n\t\t\tbreak;\r\n\t\t}\r\n\t}\r\n\tServer->Log(\"ServiceAcceptor finished\", LL_DEBUG);\r\n\texitpipe->Write(\"ok\");\r\n}\r\n\r\nvoid CServiceAcceptor::AddToWorker(SOCKET pSocket, const std::string& endpoint)\r\n{\r\n\tfor(size_t i=0;igetAvailableSlots()>0 )\r\n\t\t{\r\n\t\t\tworkers[i]->AddClient(pSocket, endpoint);\r\n\t\t\treturn;\r\n\t\t}\r\n\t}\r\n\r\n\tServer->Log(name+\": No available slots... starting new Worker\", LL_DEBUG);\r\n\r\n\tCServiceWorker *nw=new CServiceWorker(service, name, exitpipe, maxClientsPerThread);\r\n\tworkers.push_back(nw);\r\n\r\n\tServer->createThread(nw, name+\": worker\");\r\n\r\n\tnw->AddClient( pSocket, endpoint );\r\n}\t\r\nFix polling with ipv6 socket\/*************************************************************************\r\n* UrBackup - Client\/Server backup system\r\n* Copyright (C) 2011-2016 Martin Raiber\r\n*\r\n* This program is free software: you can redistribute it and\/or modify\r\n* it under the terms of the GNU Affero General Public License as published by\r\n* the Free Software Foundation, either version 3 of the License, or\r\n* (at your option) any later version.\r\n*\r\n* This program is distributed in the hope that it will be useful,\r\n* but WITHOUT ANY WARRANTY; without even the implied warranty of\r\n* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\r\n* GNU Affero General Public License for more details.\r\n*\r\n* You should have received a copy of the GNU Affero General Public License\r\n* along with this program. If not, see .\r\n**************************************************************************\/\r\n\r\n#include \"vld.h\"\r\n#ifdef _WIN32\r\n#include \r\n#endif\r\n#include \"ServiceAcceptor.h\"\r\n#include \"stringtools.h\"\r\n#include \"ServiceWorker.h\"\r\n#include \r\n\r\n#include \"Interface\/Mutex.h\"\r\n#include \"Interface\/Condition.h\"\r\n#include \"Interface\/Service.h\"\r\n\r\nnamespace\r\n{\r\n\tbool prepareSocket(SOCKET s)\r\n\t{\r\n#if !defined(_WIN32) && !defined(SOCK_CLOEXEC)\n\t\tfcntl(s, F_SETFD, fcntl(s, F_GETFD, 0) | FD_CLOEXEC);\n#endif\r\n\r\n\t\tint optval = 1;\r\n\t\tint rc = setsockopt(s, SOL_SOCKET, SO_REUSEADDR, (char*)&optval, sizeof(int));\r\n\t\tif (rc == SOCKET_ERROR)\r\n\t\t{\r\n\t\t\tServer->Log(\"Failed setting SO_REUSEADDR\", LL_ERROR);\r\n\t\t\treturn false;\r\n\t\t}\r\n\r\n#ifdef __APPLE__\r\n\t\toptval = 1;\r\n\t\tsetsockopt(s, SOL_SOCKET, SO_NOSIGPIPE, (void*)&optval, sizeof(optval));\r\n#endif\r\n\t\treturn true;\r\n\t}\r\n}\r\n\r\nCServiceAcceptor::CServiceAcceptor(IService * pService, std::string pName, unsigned short port, int pMaxClientsPerThread, IServer::BindTarget bindTarget)\r\n\t: maxClientsPerThread(pMaxClientsPerThread), s_v6(SOCKET_ERROR)\r\n{\r\n\tname=pName;\r\n\tservice=pService;\r\n\texitpipe=Server->createMemoryPipe();\r\n\tdo_exit=false;\r\n\thas_error=false;\r\n#ifndef _WIN32\r\n\tpipe(xpipe);\r\n#endif\r\n\r\n\tint rc;\r\n#ifdef _WIN32\r\n\tWSADATA wsadata;\r\n\trc = WSAStartup(MAKEWORD(2,2), &wsadata);\r\n\tif(rc == SOCKET_ERROR)\treturn;\r\n#endif\r\n\r\n\tint type = SOCK_STREAM;\n#if !defined(_WIN32) && defined(SOCK_CLOEXEC)\r\n\ttype |= SOCK_CLOEXEC;\r\n#endif\r\n\ts=socket(AF_INET,type,0);\r\n\tif(s<1)\r\n\t{\r\n\t\tServer->Log(name+\": Creating SOCKET failed\",LL_ERROR);\r\n\t\thas_error=true;\r\n\t\treturn;\r\n\t}\r\n\r\n\tif (!prepareSocket(s))\r\n\t{\r\n\t\thas_error = true;\r\n\t\treturn;\r\n\t}\r\n\r\n\tsockaddr_in addr;\r\n\r\n\tmemset(&addr, 0, sizeof(sockaddr_in));\r\n\taddr.sin_family=AF_INET;\r\n\taddr.sin_port=htons(port);\r\n\tswitch(bindTarget)\r\n\t{\r\n\tcase IServer::BindTarget_All:\r\n\t\taddr.sin_addr.s_addr= htonl(INADDR_ANY);\r\n\t\tbreak;\r\n\tcase IServer::BindTarget_Localhost:\r\n\t\taddr.sin_addr.s_addr=htonl(INADDR_LOOPBACK);\r\n\t\tbreak;\r\n\t}\r\n\r\n\trc=bind(s,(sockaddr*)&addr,sizeof(addr));\r\n\tif(rc==SOCKET_ERROR)\r\n\t{\r\n\t\tServer->Log(name+\": Failed binding socket to port \"+convert(port)+\". Another instance of this application may already be active and bound to this port.\",LL_ERROR);\r\n\t\thas_error=true;\r\n\t\treturn;\r\n\t}\r\n\r\n\tlisten(s, 10000);\r\n\r\n\tif (Server->getServerParameter(\"disable_ipv6\").empty())\n\t{\r\n\t\ts_v6 = socket(AF_INET6, type, 0);\r\n\t\tif (s_v6 < 1)\r\n\t\t{\r\n\t\t\tServer->Log(name + \": Creating v6 SOCKET failed\", LL_ERROR);\r\n\t\t\thas_error = true;\r\n\t\t\treturn;\r\n\t\t}\r\n\r\n\t\tif (!prepareSocket(s_v6))\r\n\t\t{\r\n\t\t\thas_error = true;\r\n\t\t\treturn;\r\n\t\t}\r\n\r\n\t\tint optval = 1;\n\t\tsetsockopt(s_v6, IPPROTO_IPV6, IPV6_V6ONLY, (char*)&optval, sizeof(optval));\r\n\r\n\t\tsockaddr_in6 addr;\r\n\r\n\t\tmemset(&addr, 0, sizeof(addr));\r\n\t\taddr.sin6_family = AF_INET6;\r\n\t\taddr.sin6_port = htons(port);\r\n\t\tswitch (bindTarget)\r\n\t\t{\r\n\t\tcase IServer::BindTarget_All:\r\n\t\t\taddr.sin6_addr = in6addr_any;\r\n\t\t\tbreak;\r\n\t\tcase IServer::BindTarget_Localhost:\r\n\t\t\taddr.sin6_addr= in6addr_loopback;\r\n\t\t\tbreak;\r\n\t\t}\r\n\r\n\t\trc = bind(s_v6, (sockaddr*)&addr, sizeof(addr));\r\n\t\tif (rc == SOCKET_ERROR)\r\n\t\t{\r\n\t\t\tServer->Log(name + \": Failed binding ipv6 socket to port \" + convert(port) + \". Another instance of this application may already be active and bound to this port.\", LL_ERROR);\r\n\t\t\thas_error = true;\r\n\t\t\treturn;\r\n\t\t}\r\n\r\n\t\tlisten(s_v6, 10000);\r\n\t}\r\n\r\n\tServer->Log(name+\": Server started up successfully!\",LL_INFO);\r\n}\r\n\r\nCServiceAcceptor::~CServiceAcceptor()\r\n{\r\n\tif(has_error)\r\n\t\treturn;\r\n\r\n\tdo_exit=true;\r\n#ifndef _WIN32\r\n\tchar ch=0;\r\n\twrite(xpipe[1], &ch, 1);\r\n#endif\r\n\tclosesocket(s);\r\n\tif (s_v6 != SOCKET_ERROR)\r\n\t\tclosesocket(s_v6);\r\n\tfor(size_t i=0;istop();\r\n\t}\r\n\tsize_t c=0;\r\n\tServer->Log(\"c=0\/\"+convert(workers.size()+1));\r\n\twhile(cRead(&r);\r\n\t\tif(r==\"ok\")\r\n\t\t{\r\n\t\t\t++c;\r\n\t\t\tServer->Log(\"c=\"+convert(c)+\"\/\"+convert(workers.size()+1));\r\n\t\t}\r\n\t}\r\n\tServer->destroy(exitpipe);\r\n\tfor(size_t i=0;i=0)\r\n\t\t{\r\n\t\t\tfor (size_t n = 0; n < 2; ++n)\n\t\t\t{\r\n#ifdef _WIN32\n\t\t\t\tSOCKET accept_socket = n == 0 ? s : s_v6;\n\t\t\t\tif (accept_socket == SOCKET_ERROR)\n\t\t\t\t\tcontinue;\n\t\t\t\tif (!FD_ISSET(accept_socket, &fdset))\n\t\t\t\t\tcontinue;\n#else\n\t\t\t\tif (conn[n].revents == 0)\n\t\t\t\t\tcontinue;\n\t\t\t\tSOCKET accept_socket = conn[n].fd;\n#endif\r\n\t\t\t\tif (do_exit)\r\n\t\t\t\t\tbreak;\r\n\r\n\t\t\t\tunion\r\n\t\t\t\t{\r\n\t\t\t\t\tsockaddr_in naddr_v4;\r\n\t\t\t\t\tsockaddr_in6 naddr_v6;\r\n\t\t\t\t} naddr;\r\n\t\t\t\tsocklen_t addrsize;\r\n\t\t\t\tif (accept_socket == s_v6)\r\n\t\t\t\t\taddrsize = sizeof(naddr.naddr_v6);\r\n\t\t\t\telse\r\n\t\t\t\t\taddrsize = sizeof(naddr.naddr_v4);\r\n\r\n\t\t\t\tsockaddr* paddr = (sockaddr*)&naddr;\r\n\t\t\t\tSOCKET ns= ACCEPT_CLOEXEC(accept_socket, paddr, &addrsize);\r\n\t\t\t\tif(ns!=SOCKET_ERROR)\r\n\t\t\t\t{\r\n#ifdef __APPLE__\r\n\t\t\t\t\tint optval = 1;\r\n\t\t\t\t\tsetsockopt(ns, SOL_SOCKET, SO_NOSIGPIPE, (void*)&optval, sizeof(optval));\r\n#endif\r\n\t\t\t\t\t\/\/Server->Log(name+\": New Connection incomming \"+convert(Server->getTimeMS())+\" s: \"+convert((int)ns), LL_DEBUG);\r\n\r\n\t#ifdef _WIN32\r\n\t\t\t\t\tint window_size=Server->getSendWindowSize();\r\n\t\t\t\t\tif(window_size>0)\r\n\t\t\t\t\t\tsetsockopt(ns, SOL_SOCKET, SO_SNDBUF, (char *) &window_size, sizeof(window_size));\r\n\r\n\t\t\t\t\twindow_size = Server->getRecvWindowSize();\r\n\t\t\t\t\tif(window_size>0)\r\n\t\t\t\t\t\tsetsockopt(ns, SOL_SOCKET, SO_RCVBUF, (char *) &window_size, sizeof(window_size));\r\n\t#endif\r\n\t\t\t\t\tchar buf[100];\r\n\t\t\t\t\tconst char* endpoint = inet_ntop(paddr->sa_family,\r\n\t\t\t\t\t\taccept_socket == s_v6 ? (void*)&naddr.naddr_v6.sin6_addr : (void*)&naddr.naddr_v4.sin_addr,\r\n\t\t\t\t\t\tbuf, sizeof(buf));\r\n\r\n\t\t\t\t\tAddToWorker(ns, endpoint!=NULL ? endpoint : \"\");\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tServer->Log(\"Select error in CServiceAcceptor Thread.\", LL_ERROR);\r\n\t\t\tbreak;\r\n\t\t}\r\n\t}\r\n\tServer->Log(\"ServiceAcceptor finished\", LL_DEBUG);\r\n\texitpipe->Write(\"ok\");\r\n}\r\n\r\nvoid CServiceAcceptor::AddToWorker(SOCKET pSocket, const std::string& endpoint)\r\n{\r\n\tfor(size_t i=0;igetAvailableSlots()>0 )\r\n\t\t{\r\n\t\t\tworkers[i]->AddClient(pSocket, endpoint);\r\n\t\t\treturn;\r\n\t\t}\r\n\t}\r\n\r\n\tServer->Log(name+\": No available slots... starting new Worker\", LL_DEBUG);\r\n\r\n\tCServiceWorker *nw=new CServiceWorker(service, name, exitpipe, maxClientsPerThread);\r\n\tworkers.push_back(nw);\r\n\r\n\tServer->createThread(nw, name+\": worker\");\r\n\r\n\tnw->AddClient( pSocket, endpoint );\r\n}\t\r\n<|endoftext|>"} {"text":"\n# include \n# include \"Test\/Siv3DTest.hpp\"\n\nvoid Main()\n{\n\tRunTest();\n\t\n\tLog << Range(0, 100).sum();\n\t\n\tLog << Range(0_big, 100_big).sum();\n\t\n\tLog << step(Vec2(10,10), 5, Vec2(0.5,0.5));\n\t\n\tLog << step(Vec2(10,10), 5, Vec2(0.5,0.5)).sum();\n\n\tLog << step(String(L\"\"), 5, L'.');\n\n\tLog << step(String(L\"\"), 5, L'.').sum();\n\t\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\/\/\n\t\/\/\tRange\n\t\/\/\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\n\t\/\/ 0~100 の範囲\n\tLog << L\"# Range(0, 100)\";\n\tLog << Range(0, 100);\n\t\n\t\/\/ 0~100 の合計\n\tLog << L\"# Range(0, 100).sum()\";\n\tLog << Range(0, 100).sum();\n\t\n\t\/\/ 1\/1 + 1\/2 + 1\/3 + 1\/4 + ... + 1\/10000 の合計\n\tLog << L\"# Range(1, 10000).map(Divides(1.0, none)).sum())\";\n\tLog << 18_dp << Range(10000, 1, -1).map(Divides(1.0, none)).sum();\n\tLog << Range(10000, 1, -1).map(Divides(1.0, none)).sum();\n\tLog << L\"9.78760603604438226417847790485160533485926294557769171838946095668160202494315950680012512729008088259135976018399338...\";\n\t\n\t\/\/ 0~100 のうち 20 未満の個数\n\tLog << L\"# Range(0, 100).count_if(LessThan(20))\";\n\tLog << Range(0, 100).count_if(LessThan(20));\n\t\n\t\/\/ 0~10 の範囲の奇数\n\tLog << L\"# Range(0, 10).filter(IsOdd)\";\n\tLog << Range(0, 10).filter(IsOdd);\n\t\n\t\/\/ 100 の階乗\n\tLog << L\"# Range(1, 100).reduce1(Multiplies())\";\n\tLog << Range(1, 100).reduce1(Multiplies());\n\t\n\t\/\/ FizzBuzz\n\tLog << L\"#FizzBuzz\";\n\tLog << Range(1, 20).map([](auto n) { return n % 15 == 0 ? L\"FizzBuzz\" : n % 3 == 0 ? L\"Fizz\" : n % 5 == 0 ? L\"Buzz\" : Format(n); });\n\t\n\t\/\/ フィボナッチ数列\n\tBigInt a = 0, b = 1;\n\tLog << L\"# Fibbonaci\";\n\tLog << a << L'\\n' << b;\n\tRange(1, 100).map([&a, &b](auto) { a = std::exchange(b, a + b); return b; }).each(Log);\n\t\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\/\/\n\t\/\/\tInfiniteList\n\t\/\/\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\n\t\/\/ 無限リスト\n\tLog << L\"# InfiniteList\";\n\tLog << InfiniteList().take(5);\n\tLog << InfiniteList(0, 0.01).take_while([](auto v) { return v * v < 0.1; });\n\tInfiniteList(L\"1000000000000000000000000000000000000000000000000000000\"_big, 100).take(5).each(Log);\n\t\n\t\/\/ 111122223333 以上の素数を近い順に 5 つ探す\n\tLog << InfiniteList(111122223333).filter(IsPrime).take(5);\n\t\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\/\/\n\t\/\/\tArray\n\t\/\/\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\n\t\/\/ 0〜9 の数をシャッフル\n\tLog << L\"# Range(0, 9).asArray().shuffle()\";\n\tLog << Range(0, 9).asArray().shuffle();\n\t\n\t\/\/ 4 人にポーカーの札を配る\n\tLog << Iota(13 * 4).map([](int32 n) { return Format(L\"♦♣♥♠\"[n \/ 13], (n % 13 + 1)); }).asArray().shuffle().take(20).chunk(5);\n\n\twhile (System::Update())\n\t{\n\t\tif (KeyQ.down() && System::ShowMessageBox(L\"アプリを終了します。\", MessageBoxButtons::OKCancel)\n\t\t\t== MessageBoxSelection::OK)\n\t\t{\n\t\t\tbreak;\n\t\t}\n\t}\n}\nremove test\n# include \n# include \"Test\/Siv3DTest.hpp\"\n\nvoid Main()\n{\n\tRunTest();\n\t\n\tLog << Range(0, 100).sum();\n\t\n\tLog << Range(0_big, 100_big).sum();\n\t\n\tLog << step(Vec2(10,10), 5, Vec2(0.5,0.5));\n\t\n\tLog << step(Vec2(10,10), 5, Vec2(0.5,0.5)).sum();\n\n\tLog << step(String(L\"\"), 5, L'.');\n\n\tLog << step(String(L\"\"), 5, L'.').sum();\n\t\n\twhile (System::Update())\n\t{\n\t\tif (KeyQ.down() && System::ShowMessageBox(L\"アプリを終了します。\", MessageBoxButtons::OKCancel)\n\t\t\t== MessageBoxSelection::OK)\n\t\t{\n\t\t\tbreak;\n\t\t}\n\t}\n}\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \n\n#include \"dep_selector_to_gecode.h\"\n\n#include \n#include \n#include \n\n#define DEBUG\n\nusing namespace Gecode;\nconst int VersionProblem::UNRESOLVED_VARIABLE = INT_MIN;\nconst int VersionProblem::MIN_TRUST_LEVEL = 0;\nconst int VersionProblem::MAX_TRUST_LEVEL = 10;\n\nVersionProblem::VersionProblem(int packageCount)\n : size(packageCount), finalized(false), cur_package(0), package_versions(*this, packageCount), \n disabled_package_variables(*this, packageCount, 0, 1), total_disabled(*this, 0, packageCount*MAX_TRUST_LEVEL),\n disabled_package_weights(new int[packageCount])\n{\n for (int i = 0; i < packageCount; i++) \n disabled_package_weights[i] = MAX_TRUST_LEVEL; \n}\n\nVersionProblem::VersionProblem(bool share, VersionProblem & s) \n : MinimizeSpace(share, s), size(s.size),\n finalized(s.finalized), cur_package(s.cur_package),\n disabled_package_variables(s.disabled_package_variables), total_disabled(s.total_disabled),\n disabled_package_weights(NULL)\n{\n package_versions.update(*this, share, s.package_versions);\n disabled_package_variables.update(*this, share, s.disabled_package_variables);\n total_disabled.update(*this, share, s.total_disabled);\n}\n\n\/\/ Support for gecode\nSpace* VersionProblem::copy(bool share) \n{\n return new VersionProblem(share,*this);\n}\n\nVersionProblem::~VersionProblem() \n{\n delete[] disabled_package_weights;\n}\n\nint VersionProblem::Size() \n{\n return size;\n}\n\nint VersionProblem::PackageCount() \n{\n return cur_package;\n}\n\nint\nVersionProblem::AddPackage(int minVersion, int maxVersion, int currentVersion) \n{\n if (cur_package == size) {\n return -1;\n }\n\n#ifdef DEBUG\n std::cout << cur_package << '\/' << size << \":\" << minVersion << \", \" << maxVersion << \", \" << currentVersion << std::endl;\n std::cout.flush(); \n#endif \/\/ DEBUG\n int index = cur_package;\n cur_package++;\n \/\/ IntVar version(*this, minVersion, maxVersion);\n package_versions[index] = IntVar(*this, minVersion, maxVersion);\n return index;\n}\n\nbool \nVersionProblem::AddVersionConstraint(int packageId, int version, \n\t\t\t\t int dependentPackageId, int minDependentVersion, int maxDependentVersion) \n{\n BoolVar version_match(*this, 0, 1);\n BoolVar depend_match(*this, 0, 1);\n BoolVar predicated_depend_match(*this, 0, 1);\n\n#ifdef DEBUG\n std::cout << \"Add VC for \" << packageId << \" @ \" << version << \" depPkg \" << dependentPackageId;\n std::cout << \" [ \" << minDependentVersion << \", \" << maxDependentVersion << \" ]\" << std::endl;\n std::cout.flush();\n#endif \/\/ DEBUG\n\n\n \/\/version_flags << version_match;\n \/\/ Constrain pred to reify package @ version\n rel(*this, package_versions[packageId], IRT_EQ, version, version_match);\n \/\/ Add the predicated version constraints imposed on dependent package\n\n \/\/ package_versions[dependendPackageId] in domain [minDependentVersion,maxDependentVersion] <=> depend_match\n dom(*this, package_versions[dependentPackageId], minDependentVersion, maxDependentVersion, depend_match);\n\n \/\/ disabled_package_variables[dependentPackageId] OR depend_match <=> predicated_depend_match\n \/\/ rel(*this, disabled_package_variables[dependentPackageId], BOT_OR, depend_match, version_match);\n\n rel(*this, disabled_package_variables[dependentPackageId], BOT_OR, depend_match, predicated_depend_match);\n rel(*this, version_match, BOT_IMP, predicated_depend_match, 1); \n}\n\nvoid\nVersionProblem::MarkPackageSuspicious(int packageId, int trustLevel) \n{\n disabled_package_weights[packageId] = std::max(MIN_TRUST_LEVEL, std::min(disabled_package_weights[packageId], trustLevel));\n}\n\nvoid VersionProblem::Finalize() \n{\n#ifdef DEBUG\n std::cout << \"Finalization Started\" << std::endl;\n std::cout.flush();\n#endif \/\/ DEBUG\n finalized = true;\n\n \/\/ Setup constraint for cost\n \/\/ linear(*this, disabled_package_weights, disabled_package_variables, IRT_EQ, total_disabled);\n IntArgs package_weights(size, disabled_package_weights);\n \/\/IntArgs package_weights = IntArgs::create(size, 1, 0);\n\n#ifdef DEBUG\n std::cout << \"Package weights \" << package_weights << std::endl;\n#endif DEBUG\n linear(*this, package_weights, disabled_package_variables, IRT_EQ, total_disabled);\n \/\/ linear(*this, disabled_package_variables, IRT_EQ, total_disabled);\n\n \/\/ Assign a dummy variable to elements greater than actually used.\n for (int i = cur_package; i < size; i++) {\n package_versions[i] = IntVar(*this, -1, -1);\n disabled_package_variables[i] = BoolVar(*this, 1, 1);\n }\n#ifdef DEBUG\n std::cout << \"Adding branching\" << std::endl;\n std::cout.flush();\n#endif \/\/ DEBUG\n branch(*this, disabled_package_variables, INT_VAR_SIZE_MIN, INT_VAL_MIN);\n branch(*this, package_versions, INT_VAR_SIZE_MIN, INT_VAL_MAX);\n branch(*this, total_disabled, INT_VAL_MIN);\n#ifdef DEBUG\n std::cout << \"Finalization Done\" << std::endl;\n std::cout.flush();\n#endif \/\/ DEBUG\n}\n\nIntVar VersionProblem::cost(void) const {\n return total_disabled;\n}\n\n\n\nIntVar & VersionProblem::GetPackageVersionVar(int packageId)\n{\n if (packageId < cur_package) {\n return package_versions[packageId];\n } else {\n#ifdef DEBUG\n std::cout << \"Bad package Id \" << packageId << \" >= \" << cur_package << std::endl;\n std::cout.flush();\n#endif \/\/DEBUG\n \/\/ return 0;\n }\n}\n\nint VersionProblem::GetPackageVersion(int packageId) \n{\n IntVar & var = GetPackageVersionVar(packageId);\n if (1 == var.size()) return var.val();\n return UNRESOLVED_VARIABLE;\n}\nbool VersionProblem::GetPackageDisabledState(int packageId) \n{\n return disabled_package_variables[packageId].val() == 1;\n}\n\nint VersionProblem::GetAFC(int packageId)\n{\n return GetPackageVersionVar(packageId).afc();\n} \n\nint VersionProblem::GetMax(int packageId)\n{\n return GetPackageVersionVar(packageId).max();\n}\nint VersionProblem::GetMin(int packageId)\n{\n return GetPackageVersionVar(packageId).min();\n}\n\nint VersionProblem::GetDisabledVariableCount()\n{\n if (total_disabled.min() == total_disabled.max()) {\n return total_disabled.min();\n } else {\n return UNRESOLVED_VARIABLE;\n }\n}\n \n\n\/\/ Utility\nvoid VersionProblem::Print(std::ostream & out) \n{\n out << \"Version problem dump: \" << cur_package << \"\/\" << size << \" packages used\/allocated\" << std::endl;\n out << \"Total Disabled variables: \" << total_disabled.min() << \" - \" << total_disabled.max() << std::endl;\n for (int i = 0; i < cur_package; i++) {\n out << \"\\t\";\n PrintPackageVar(out, i);\n out << std::endl;\n }\n out.flush();\n}\n\n\/\/ TODO: Validate package ids !\n\nvoid VersionProblem::PrintPackageVar(std::ostream & out, int packageId) \n{\n \/\/ Hack Alert: we could have the package variable in one of two places, but we don't clearly distinguish where.\n IntVar & var = GetPackageVersionVar(packageId);\n out << \"PackageId: \" << packageId << \" Sltn: \" << var.min() << \" - \" << var.max() << \" afc: \" << var.afc();\n \n out << \" disabled: \";\n if (disabled_package_variables[packageId].min() == disabled_package_variables[packageId].max()) {\n out << disabled_package_variables[packageId].min();\n } else {\n out << disabled_package_variables[packageId].min() << \" - \" << disabled_package_variables[packageId].max();\n }\n}\n\nbool VersionProblem::CheckPackageId(int id) \n{\n return (id < size);\n}\n\nVersionProblem * VersionProblem::Solve(VersionProblem * problem) \n{\n problem->Finalize();\n problem->status();\n#ifdef DEBUG\n std::cout << \"Before solve\" << std::endl;\n problem->Print(std::cout);\n#endif \/\/DEBUG\n\n Restart solver(problem);\n \n \/\/ std::cout << solver.statistics();\n\n if (VersionProblem * solution = solver.next())\n {\n#ifdef DEBUG\n std::cout << \"Solution:\" << std::endl;\n solution->Print(std::cout);\n#endif \/\/DEBUG\n \n return solution;\n }\n return 0;\n}\n\n\n\/\/\n\/\/ \n\/\/\n\n\n\n\/\/\n\/\/ Version Problem\n\/\/\n\/\/\n\/\/ \n\/\/\nAdd more debug stats. Solve to optimality rather that halting early.#include \n#include \n#include \n#include \n#include \n\n#include \"dep_selector_to_gecode.h\"\n\n#include \n#include \n#include \n\n#define DEBUG\n\nusing namespace Gecode;\nconst int VersionProblem::UNRESOLVED_VARIABLE = INT_MIN;\nconst int VersionProblem::MIN_TRUST_LEVEL = 0;\nconst int VersionProblem::MAX_TRUST_LEVEL = 10;\n\nVersionProblem::VersionProblem(int packageCount)\n : size(packageCount), finalized(false), cur_package(0), package_versions(*this, packageCount), \n disabled_package_variables(*this, packageCount, 0, 1), total_disabled(*this, 0, packageCount*MAX_TRUST_LEVEL),\n disabled_package_weights(new int[packageCount])\n{\n for (int i = 0; i < packageCount; i++) \n disabled_package_weights[i] = MAX_TRUST_LEVEL; \n}\n\nVersionProblem::VersionProblem(bool share, VersionProblem & s) \n : MinimizeSpace(share, s), size(s.size),\n finalized(s.finalized), cur_package(s.cur_package),\n disabled_package_variables(s.disabled_package_variables), total_disabled(s.total_disabled),\n disabled_package_weights(NULL)\n{\n package_versions.update(*this, share, s.package_versions);\n disabled_package_variables.update(*this, share, s.disabled_package_variables);\n total_disabled.update(*this, share, s.total_disabled);\n}\n\n\/\/ Support for gecode\nSpace* VersionProblem::copy(bool share) \n{\n return new VersionProblem(share,*this);\n}\n\nVersionProblem::~VersionProblem() \n{\n delete[] disabled_package_weights;\n}\n\nint VersionProblem::Size() \n{\n return size;\n}\n\nint VersionProblem::PackageCount() \n{\n return cur_package;\n}\n\nint\nVersionProblem::AddPackage(int minVersion, int maxVersion, int currentVersion) \n{\n if (cur_package == size) {\n return -1;\n }\n\n#ifdef DEBUG\n std::cout << cur_package << '\/' << size << \":\" << minVersion << \", \" << maxVersion << \", \" << currentVersion << std::endl;\n std::cout.flush(); \n#endif \/\/ DEBUG\n int index = cur_package;\n cur_package++;\n \/\/ IntVar version(*this, minVersion, maxVersion);\n package_versions[index] = IntVar(*this, minVersion, maxVersion);\n return index;\n}\n\nbool \nVersionProblem::AddVersionConstraint(int packageId, int version, \n\t\t\t\t int dependentPackageId, int minDependentVersion, int maxDependentVersion) \n{\n BoolVar version_match(*this, 0, 1);\n BoolVar depend_match(*this, 0, 1);\n BoolVar predicated_depend_match(*this, 0, 1);\n\n#ifdef DEBUG\n std::cout << \"Add VC for \" << packageId << \" @ \" << version << \" depPkg \" << dependentPackageId;\n std::cout << \" [ \" << minDependentVersion << \", \" << maxDependentVersion << \" ]\" << std::endl;\n std::cout.flush();\n#endif \/\/ DEBUG\n\n\n \/\/version_flags << version_match;\n \/\/ Constrain pred to reify package @ version\n rel(*this, package_versions[packageId], IRT_EQ, version, version_match);\n \/\/ Add the predicated version constraints imposed on dependent package\n\n \/\/ package_versions[dependendPackageId] in domain [minDependentVersion,maxDependentVersion] <=> depend_match\n dom(*this, package_versions[dependentPackageId], minDependentVersion, maxDependentVersion, depend_match);\n\n \/\/ disabled_package_variables[dependentPackageId] OR depend_match <=> predicated_depend_match\n \/\/ rel(*this, disabled_package_variables[dependentPackageId], BOT_OR, depend_match, version_match);\n\n rel(*this, disabled_package_variables[dependentPackageId], BOT_OR, depend_match, predicated_depend_match);\n rel(*this, version_match, BOT_IMP, predicated_depend_match, 1); \n}\n\nvoid\nVersionProblem::MarkPackageSuspicious(int packageId, int trustLevel) \n{\n disabled_package_weights[packageId] = std::max(MIN_TRUST_LEVEL, std::min(disabled_package_weights[packageId], trustLevel));\n}\n\nvoid VersionProblem::Finalize() \n{\n#ifdef DEBUG\n std::cout << \"Finalization Started\" << std::endl;\n std::cout.flush();\n#endif \/\/ DEBUG\n finalized = true;\n\n \/\/ Setup constraint for cost\n \/\/ linear(*this, disabled_package_weights, disabled_package_variables, IRT_EQ, total_disabled);\n IntArgs package_weights(size, disabled_package_weights);\n \/\/IntArgs package_weights = IntArgs::create(size, 1, 0);\n\n#ifdef DEBUG\n std::cout << \"Package weights \" << package_weights << std::endl;\n#endif DEBUG\n linear(*this, package_weights, disabled_package_variables, IRT_EQ, total_disabled);\n \/\/ linear(*this, disabled_package_variables, IRT_EQ, total_disabled);\n\n \/\/ Assign a dummy variable to elements greater than actually used.\n for (int i = cur_package; i < size; i++) {\n package_versions[i] = IntVar(*this, -1, -1);\n disabled_package_variables[i] = BoolVar(*this, 1, 1);\n }\n#ifdef DEBUG\n std::cout << \"Adding branching\" << std::endl;\n std::cout.flush();\n#endif \/\/ DEBUG\n branch(*this, disabled_package_variables, INT_VAR_SIZE_MIN, INT_VAL_MIN);\n branch(*this, package_versions, INT_VAR_SIZE_MIN, INT_VAL_MAX);\n branch(*this, total_disabled, INT_VAL_MIN);\n#ifdef DEBUG\n std::cout << \"Finalization Done\" << std::endl;\n std::cout.flush();\n#endif \/\/ DEBUG\n}\n\nIntVar VersionProblem::cost(void) const {\n return total_disabled;\n}\n\n\n\nIntVar & VersionProblem::GetPackageVersionVar(int packageId)\n{\n if (packageId < cur_package) {\n return package_versions[packageId];\n } else {\n#ifdef DEBUG\n std::cout << \"Bad package Id \" << packageId << \" >= \" << cur_package << std::endl;\n std::cout.flush();\n#endif \/\/DEBUG\n \/\/ return 0;\n }\n}\n\nint VersionProblem::GetPackageVersion(int packageId) \n{\n IntVar & var = GetPackageVersionVar(packageId);\n if (1 == var.size()) return var.val();\n return UNRESOLVED_VARIABLE;\n}\nbool VersionProblem::GetPackageDisabledState(int packageId) \n{\n return disabled_package_variables[packageId].val() == 1;\n}\n\nint VersionProblem::GetAFC(int packageId)\n{\n return GetPackageVersionVar(packageId).afc();\n} \n\nint VersionProblem::GetMax(int packageId)\n{\n return GetPackageVersionVar(packageId).max();\n}\nint VersionProblem::GetMin(int packageId)\n{\n return GetPackageVersionVar(packageId).min();\n}\n\nint VersionProblem::GetDisabledVariableCount()\n{\n if (total_disabled.min() == total_disabled.max()) {\n return total_disabled.min();\n } else {\n return UNRESOLVED_VARIABLE;\n }\n}\n \n\n\/\/ Utility\nvoid VersionProblem::Print(std::ostream & out) \n{\n out << \"Version problem dump: \" << cur_package << \"\/\" << size << \" packages used\/allocated\" << std::endl;\n out << \"Total Disabled variables: \" << total_disabled.min() << \" - \" << total_disabled.max() << std::endl;\n for (int i = 0; i < cur_package; i++) {\n out << \"\\t\";\n PrintPackageVar(out, i);\n out << std::endl;\n }\n out.flush();\n}\n\n\/\/ TODO: Validate package ids !\n\nvoid VersionProblem::PrintPackageVar(std::ostream & out, int packageId) \n{\n \/\/ Hack Alert: we could have the package variable in one of two places, but we don't clearly distinguish where.\n IntVar & var = GetPackageVersionVar(packageId);\n out << \"PackageId: \" << packageId << \" Sltn: \" << var.min() << \" - \" << var.max() << \" afc: \" << var.afc();\n \n out << \" disabled: \";\n if (disabled_package_variables[packageId].min() == disabled_package_variables[packageId].max()) {\n out << disabled_package_variables[packageId].min();\n } else {\n out << disabled_package_variables[packageId].min() << \" - \" << disabled_package_variables[packageId].max();\n }\n}\n\nbool VersionProblem::CheckPackageId(int id) \n{\n return (id < size);\n}\n\nVersionProblem * VersionProblem::Solve(VersionProblem * problem) \n{\n problem->Finalize();\n problem->status();\n#ifdef DEBUG\n std::cout << \"Before solve\" << std::endl;\n problem->Print(std::cout);\n#endif \/\/DEBUG\n\n BAB solver(problem);\n\n VersionProblem *best_solution = NULL;\n while (VersionProblem *solution = solver.next())\n {\n if (best_solution != NULL) \n\t{\n\t delete best_solution;\n\t}\n best_solution = solution;\n#ifdef DEBUG\n const Search::Statistics & stats = solver.statistics();\n std::cout << \"Solver stats: Prop:\" << stats.propagate << \" Fail:\" << stats.fail << \" Node:\" << stats.node;\n std::cout << \" Depth:\" << stats.depth << \" memory:\" << stats.memory << std::endl;\n \/\/ std::cout << stats << std::endl;\n std::cout << \"Solution:\" << std::endl;\n solution->Print(std::cout);\n#endif \/\/DEBUG\n }\n return best_solution;\n}\n\n\n\/\/\n\/\/ \n\/\/\n\n\n\n\/\/\n\/\/ Version Problem\n\/\/\n\/\/\n\/\/ \n\/\/\n<|endoftext|>"} {"text":"#include \n#include \n#include \"..\/pipeline.h\"\n#include \"..\/channel.h\"\n#include \"..\/scheduler.h\"\n#include \"..\/shell.h\"\n#include \n#include \n\nclass ChannelTest : testing::Test { };\n\nusing cmd = cu::pipeline;\n\ncmd::link generator()\n{\n\treturn [](cmd::in&, cmd::out& yield)\n\t{\n\t\tfor (auto& s : {100, 200, 300})\n\t\t{\n\t\t\tstd::cout << \"I am generator and push \" << s << std::endl;\n\t\t\tyield(s);\n\t\t}\n\t};\n}\n\ncmd::link link1()\n{\n\treturn [](cmd::in& source, cmd::out& yield)\n\t{\n\t\tfor (auto& s : source)\n\t\t{\n\t\t\tstd::cout << \"I am link1 and push \" << s << std::endl;\n\t\t\tyield(s);\n\t\t}\n\t};\n}\n\ncmd::link link2()\n{\n\treturn [](cmd::in& source, cmd::out& yield)\n\t{\n\t\tfor (auto& s : source)\n\t\t{\n\t\t\tstd::cout << \"I am link2 and push \" << s << std::endl;\n\t\t\tyield(s);\n\t\t}\n\t};\n}\n\ncmd::link link3()\n{\n\treturn [](cmd::in& source, cmd::out& yield)\n\t{\n\t\tfor (auto& s : source)\n\t\t{\n\t\t\tstd::cout << \"I am link3 and push \" << s << std::endl;\n\t\t\tyield(s);\n\t\t}\n\t};\n}\n\nTEST(ChannelTest, pipeline)\n{\n\tcmd(generator(), link1(), link2(), link3());\n}\n\nTEST(ChannelTest, goroutines_consumer)\n{\n\tcu::scheduler sch;\n\tcu::channel go(sch, 7);\n\t\/\/ go.connect(cu::quote(\"__^-^__\"));\n\t\/\/ go.connect(cu::quote(\"__\\o\/__\"));\n\t\n\t\/\/ https:\/\/play.golang.org\/\n\t\/*\npackage main\n\nimport \"fmt\"\n\nfunc worker(done chan int) {\n for i := 0; i < 50; i++ {\n fmt.Println(\"----> send \", i, \" [PRE]\")\n\tdone <- i\n fmt.Println(\"----> send \", i, \" [POST]\")\n }\n}\n\nfunc main() {\n done := make(chan int, 8)\n go worker(done)\n for i := 0; i < 50; i++ {\n\tj := <- done\n\tfmt.Println(\"recv \", j, \" <---- \")\n }\n}\n\t*\/\n\t\n\tsch.spawn([&](auto& yield) {\n\t\tfor(;;)\n\t\t{\n\t\t\tauto data = go.get(yield);\n \t\t\tif(data)\n \t\t\t{\n \t\t\t\tstd::cout << \"recv \" << *data << \" <----\" << std::endl;\n \t\t\t}\n \t\t\telse\n\t \t\t{\n\t\t\t \tstd::cout << \"channel closed\" << std::endl;\n \t\t\t\tbreak;\n \t\t\t}\n\t\t}\n\t});\n\tsch.spawn([&](auto& yield) {\n\t\tfor(int i=0; i<50; ++i)\n\t\t{\n\t\t\tstd::cout << \"----> send \" << i << \" [PRE]\" << std::endl;\n\t\t\tgo(yield, std::to_string(i));\n\t\t\tstd::cout << \"----> send \" << i << \" [POST]\" << std::endl;\n\t\t}\n\t\tgo.close(yield);\n\t});\n\tsch.run_until_complete();\n}\n\nTEST(ChannelTest, goroutines_consumer_unbuffered)\n{\n\tcu::scheduler sch;\n\tcu::channel go(sch);\n\t\/\/ go.connect(cu::quote(\"__^-^__\"));\n\t\/\/ go.connect(cu::quote(\"__\\o\/__\"));\t\n\tsch.spawn([&](auto& yield) {\n\t\tfor(;;)\n\t\t{\n\t\t\tauto data = go.get(yield);\n \t\t\tif(data)\n \t\t\t{\n \t\t\t\tstd::cout << \"recv \" << *data << \" <----\" << std::endl;\n \t\t\t}\n \t\t\telse\n\t \t\t{\n\t\t\t \tstd::cout << \"channel closed\" << std::endl;\n \t\t\t\tbreak;\n \t\t\t}\n\t\t}\n\t});\n\tsch.spawn([&](auto& yield) {\n\t\tfor(int i=0; i<50; ++i)\n\t\t{\n\t\t\tstd::cout << \"----> send \" << i << \" [PRE]\" << std::endl;\n\t\t\tgo(yield, std::to_string(i));\n\t\t\tstd::cout << \"----> send \" << i << \" [POST]\" << std::endl;\n\t\t}\n\t\tgo.close(yield);\n\t});\n\tsch.run_until_complete();\n}\n\nTEST(ChannelTest, goroutines_consumer_buffered_one)\n{\n\tcu::scheduler sch;\n\tcu::channel go(sch, 1);\n\t\/\/ go.connect(cu::quote(\"__^-^__\"));\n\t\/\/ go.connect(cu::quote(\"__\\o\/__\"));\t\n\tsch.spawn([&](auto& yield) {\n\t\tfor(;;)\n\t\t{\n\t\t\tauto data = go.get(yield);\n \t\t\tif(data)\n \t\t\t{\n \t\t\t\tstd::cout << \"recv \" << *data << \" <----\" << std::endl;\n \t\t\t}\n \t\t\telse\n\t \t\t{\n\t\t\t \tstd::cout << \"channel closed\" << std::endl;\n \t\t\t\tbreak;\n \t\t\t}\n\t\t}\n\t});\n\tsch.spawn([&](auto& yield) {\n\t\tfor(int i=0; i<50; ++i)\n\t\t{\n\t\t\tstd::cout << \"----> send \" << i << \" [PRE]\" << std::endl;\n\t\t\tgo(yield, std::to_string(i));\n\t\t\tstd::cout << \"----> send \" << i << \" [POST]\" << std::endl;\n\t\t}\n\t\tgo.close(yield);\n\t});\n\tsch.run_until_complete();\n}\n\nTEST(ChannelTest, goroutines_consumer_buffered_two)\n{\n\tcu::scheduler sch;\n\tcu::channel go(sch, 2);\n\t\/\/ go.connect(cu::quote(\"__^-^__\"));\n\t\/\/ go.connect(cu::quote(\"__\\o\/__\"));\t\n\tsch.spawn([&](auto& yield) {\n\t\tfor(;;)\n\t\t{\n\t\t\tauto data = go.get(yield);\n \t\t\tif(data)\n \t\t\t{\n \t\t\t\tstd::cout << \"recv \" << *data << \" <----\" << std::endl;\n \t\t\t}\n \t\t\telse\n\t \t\t{\n\t\t\t \tstd::cout << \"channel closed\" << std::endl;\n \t\t\t\tbreak;\n \t\t\t}\n\t\t}\n\t});\n\tsch.spawn([&](auto& yield) {\n\t\tfor(int i=0; i<50; ++i)\n\t\t{\n\t\t\tstd::cout << \"----> send \" << i << \" [PRE]\" << std::endl;\n\t\t\tgo(yield, std::to_string(i));\n\t\t\tstd::cout << \"----> send \" << i << \" [POST]\" << std::endl;\n\t\t}\n\t\tgo.close(yield);\n\t});\n\tsch.run_until_complete();\n}\n\nTEST(CoroTest, TestScheduler)\n{\n\tcu::scheduler sch;\n\tcu::semaphore person1(sch);\n\tcu::semaphore person2(sch);\n\tcu::semaphore other(sch);\n\t\/\/ person2\n\tsch.spawn([&](auto& yield) {\n\t\tstd::cout << \"Hola person1\" << std::endl;\n\t\tperson2.notify(yield);\n\t\t\/\/\n\t\tperson1.wait(yield);\n\t\tstd::cout << \"que tal ?\" << std::endl;\n\t\tperson2.notify(yield);\n\t\t\/\/\n\t\tperson1.wait(yield);\n\t\tstd::cout << \"me alegro\" << std::endl;\n\t\tperson2.notify(yield);\n\t\t\/\/\n\t\tother.notify(yield);\n\t});\n\t\/\/ person1\n\tsch.spawn([&](auto& yield) {\n\t\t\/\/\n\t\tperson2.wait(yield);\n\t\tstd::cout << \"Hola person2\" << std::endl;\n\t\tperson1.notify(yield);\n\t\t\/\/\n\t\tperson2.wait(yield);\n\t\tstd::cout << \"bien!\" << std::endl;\n\t\tperson1.notify(yield);\n\t\t\/\/\n\t\tperson2.wait(yield);\n\t\tstd::cout << \"y yo ^^\" << std::endl;\n\t\t\/\/\n\t\tother.notify(yield);\n\t});\n\t\/\/ other\n\tsch.spawn([&](auto& yield) {\n\t\t\/\/\n\t\tother.wait(yield);\n\t\tother.wait(yield);\n\t\tstd::cout << \"parar!!! tengo algo importante\" << std::endl;\n\t});\n\tsch.run_until_complete();\n}\nUpdate test_channel.cpp#include \n#include \n#include \"..\/pipeline.h\"\n#include \"..\/channel.h\"\n#include \"..\/scheduler.h\"\n#include \"..\/shell.h\"\n#include \n#include \n\nclass ChannelTest : testing::Test { };\n\nusing cmd = cu::pipeline;\n\ncmd::link generator()\n{\n\treturn [](cmd::in&, cmd::out& yield)\n\t{\n\t\tfor (auto& s : {100, 200, 300})\n\t\t{\n\t\t\tstd::cout << \"I am generator and push \" << s << std::endl;\n\t\t\tyield(s);\n\t\t}\n\t};\n}\n\ncmd::link link1()\n{\n\treturn [](cmd::in& source, cmd::out& yield)\n\t{\n\t\tfor (auto& s : source)\n\t\t{\n\t\t\tstd::cout << \"I am link1 and push \" << s << std::endl;\n\t\t\tyield(s);\n\t\t}\n\t};\n}\n\ncmd::link link2()\n{\n\treturn [](cmd::in& source, cmd::out& yield)\n\t{\n\t\tfor (auto& s : source)\n\t\t{\n\t\t\tstd::cout << \"I am link2 and push \" << s << std::endl;\n\t\t\tyield(s);\n\t\t}\n\t};\n}\n\ncmd::link link3()\n{\n\treturn [](cmd::in& source, cmd::out& yield)\n\t{\n\t\tfor (auto& s : source)\n\t\t{\n\t\t\tstd::cout << \"I am link3 and push \" << s << std::endl;\n\t\t\tyield(s);\n\t\t}\n\t};\n}\n\nTEST(ChannelTest, pipeline)\n{\n\tcmd(generator(), link1(), link2(), link3());\n}\n\nTEST(ChannelTest, goroutines_consumer)\n{\n\tcu::scheduler sch;\n\tcu::channel go(sch, 7);\n\t\/\/ go.connect(cu::quote(\"__^-^__\"));\n\t\/\/ go.connect(cu::quote(\"__\\o\/__\"));\n\t\n\t\/\/ https:\/\/play.golang.org\/\n\t\/*\npackage main\n\nimport \"fmt\"\n\nfunc worker(done chan int) {\n for i := 0; i < 50; i++ {\n fmt.Println(\"----> send \", i, \" [PRE]\")\n\tdone <- i\n fmt.Println(\"----> send \", i, \" [POST]\")\n }\n}\n\nfunc main() {\n done := make(chan int, 8)\n go worker(done)\n for i := 0; i < 50; i++ {\n\tj := <- done\n\tfmt.Println(\"recv \", j, \" <---- \")\n }\n}\n\t*\/\n\t\n\tsch.spawn([&](auto& yield) {\n\t\tfor(;;)\n\t\t{\n\t\t\tauto data = go.get(yield);\n \t\t\tif(data)\n \t\t\t{\n \t\t\t\tstd::cout << \"recv \" << *data << \" <----\" << std::endl;\n \t\t\t}\n \t\t\telse\n\t \t\t{\n\t\t\t \tstd::cout << \"channel closed\" << std::endl;\n \t\t\t\tbreak;\n \t\t\t}\n\t\t}\n\t});\n\tsch.spawn([&](auto& yield) {\n\t\tfor(int i=0; i<50; ++i)\n\t\t{\n\t\t\tstd::cout << \"----> send \" << i << \" [PRE]\" << std::endl;\n\t\t\tgo(yield, std::to_string(i));\n\t\t\tstd::cout << \"----> send \" << i << \" [POST]\" << std::endl;\n\t\t}\n\t\tgo.close(yield);\n\t});\n\tsch.run_until_complete();\n}\n\nTEST(ChannelTest, goroutines_consumer_unbuffered)\n{\n\tcu::scheduler sch;\n\tcu::channel go(sch);\n\tgo.connect(cu::quote(\"__^-^__\"));\n\tgo.connect(cu::quote(\"__\\o\/__\"));\n\tsch.spawn([&](auto& yield) {\n\t\tfor(;;)\n\t\t{\n\t\t\tauto data = go.get(yield);\n \t\t\tif(data)\n \t\t\t{\n \t\t\t\tstd::cout << \"recv \" << *data << \" <----\" << std::endl;\n \t\t\t}\n \t\t\telse\n\t \t\t{\n\t\t\t \tstd::cout << \"channel closed\" << std::endl;\n \t\t\t\tbreak;\n \t\t\t}\n\t\t}\n\t});\n\tsch.spawn([&](auto& yield) {\n\t\tfor(int i=0; i<50; ++i)\n\t\t{\n\t\t\tstd::cout << \"----> send \" << i << \" [PRE]\" << std::endl;\n\t\t\tgo(yield, std::to_string(i));\n\t\t\tstd::cout << \"----> send \" << i << \" [POST]\" << std::endl;\n\t\t}\n\t\tgo.close(yield);\n\t});\n\tsch.run_until_complete();\n}\n\nTEST(ChannelTest, goroutines_consumer_buffered_one)\n{\n\tcu::scheduler sch;\n\tcu::channel go(sch, 1);\n\t\/\/ go.connect(cu::quote(\"__^-^__\"));\n\t\/\/ go.connect(cu::quote(\"__\\o\/__\"));\t\n\tsch.spawn([&](auto& yield) {\n\t\tfor(;;)\n\t\t{\n\t\t\tauto data = go.get(yield);\n \t\t\tif(data)\n \t\t\t{\n \t\t\t\tstd::cout << \"recv \" << *data << \" <----\" << std::endl;\n \t\t\t}\n \t\t\telse\n\t \t\t{\n\t\t\t \tstd::cout << \"channel closed\" << std::endl;\n \t\t\t\tbreak;\n \t\t\t}\n\t\t}\n\t});\n\tsch.spawn([&](auto& yield) {\n\t\tfor(int i=0; i<50; ++i)\n\t\t{\n\t\t\tstd::cout << \"----> send \" << i << \" [PRE]\" << std::endl;\n\t\t\tgo(yield, std::to_string(i));\n\t\t\tstd::cout << \"----> send \" << i << \" [POST]\" << std::endl;\n\t\t}\n\t\tgo.close(yield);\n\t});\n\tsch.run_until_complete();\n}\n\nTEST(ChannelTest, goroutines_consumer_buffered_two)\n{\n\tcu::scheduler sch;\n\tcu::channel go(sch, 2);\n\t\/\/ go.connect(cu::quote(\"__^-^__\"));\n\t\/\/ go.connect(cu::quote(\"__\\o\/__\"));\t\n\tsch.spawn([&](auto& yield) {\n\t\tfor(;;)\n\t\t{\n\t\t\tauto data = go.get(yield);\n \t\t\tif(data)\n \t\t\t{\n \t\t\t\tstd::cout << \"recv \" << *data << \" <----\" << std::endl;\n \t\t\t}\n \t\t\telse\n\t \t\t{\n\t\t\t \tstd::cout << \"channel closed\" << std::endl;\n \t\t\t\tbreak;\n \t\t\t}\n\t\t}\n\t});\n\tsch.spawn([&](auto& yield) {\n\t\tfor(int i=0; i<50; ++i)\n\t\t{\n\t\t\tstd::cout << \"----> send \" << i << \" [PRE]\" << std::endl;\n\t\t\tgo(yield, std::to_string(i));\n\t\t\tstd::cout << \"----> send \" << i << \" [POST]\" << std::endl;\n\t\t}\n\t\tgo.close(yield);\n\t});\n\tsch.run_until_complete();\n}\n\nTEST(CoroTest, TestScheduler)\n{\n\tcu::scheduler sch;\n\tcu::semaphore person1(sch);\n\tcu::semaphore person2(sch);\n\tcu::semaphore other(sch);\n\t\/\/ person2\n\tsch.spawn([&](auto& yield) {\n\t\tstd::cout << \"Hola person1\" << std::endl;\n\t\tperson2.notify(yield);\n\t\t\/\/\n\t\tperson1.wait(yield);\n\t\tstd::cout << \"que tal ?\" << std::endl;\n\t\tperson2.notify(yield);\n\t\t\/\/\n\t\tperson1.wait(yield);\n\t\tstd::cout << \"me alegro\" << std::endl;\n\t\tperson2.notify(yield);\n\t\t\/\/\n\t\tother.notify(yield);\n\t});\n\t\/\/ person1\n\tsch.spawn([&](auto& yield) {\n\t\t\/\/\n\t\tperson2.wait(yield);\n\t\tstd::cout << \"Hola person2\" << std::endl;\n\t\tperson1.notify(yield);\n\t\t\/\/\n\t\tperson2.wait(yield);\n\t\tstd::cout << \"bien!\" << std::endl;\n\t\tperson1.notify(yield);\n\t\t\/\/\n\t\tperson2.wait(yield);\n\t\tstd::cout << \"y yo ^^\" << std::endl;\n\t\t\/\/\n\t\tother.notify(yield);\n\t});\n\t\/\/ other\n\tsch.spawn([&](auto& yield) {\n\t\t\/\/\n\t\tother.wait(yield);\n\t\tother.wait(yield);\n\t\tstd::cout << \"parar!!! tengo algo importante\" << std::endl;\n\t});\n\tsch.run_until_complete();\n}\n<|endoftext|>"} {"text":"\/*\n * Copyright 2004-2015 Cray Inc.\n * Other additional copyright holders may be indicated within.\n *\n * The entirety of this work is licensed under the Apache License,\n * Version 2.0 (the \"License\"); you may not use this file except\n * in compliance with the License.\n *\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"ipeEvaluate.h\"\n\nvoid ipeEvaluate()\n{\n\n}\nPreliminary version of expression evaluation\/*\n * Copyright 2004-2015 Cray Inc.\n * Other additional copyright holders may be indicated within.\n *\n * The entirety of this work is licensed under the Apache License,\n * Version 2.0 (the \"License\"); you may not use this file except\n * in compliance with the License.\n *\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"ipeEvaluate.h\"\n\n#include \"AstDumpToNode.h\"\n#include \"stmt.h\"\n\n#include \n#include \n\nstatic int rootEnvSize();\nstatic void rootEnvInit(void* env);\nstatic void rootEnvDescribe(void* env);\n\nstatic int sizeForType(Type* type);\n\nvoid ipeEvaluate()\n{\n int rootSize = rootEnvSize();\n void* rootEnv = malloc(rootSize);\n\n rootEnvInit(rootEnv);\n rootEnvDescribe(rootEnv);\n\n free(rootEnv);\n}\n\nstatic int rootEnvSize()\n{\n int retval = 0;\n\n for_alist(rootStmt, rootModule->block->body)\n {\n if (DefExpr* rootDefExpr = toDefExpr(rootStmt))\n {\n if (ModuleSymbol* module = toModuleSymbol(rootDefExpr->sym))\n {\n if (module != rootModule)\n {\n for_alist(stmt, module->block->body)\n {\n if (DefExpr* defExpr = toDefExpr(stmt))\n {\n if (Type* type = defExpr->sym->type)\n retval = retval + sizeForType(type);\n\n else if (isFnSymbol(defExpr->sym) == true)\n retval = retval + 0;\n\n else\n {\n AstDumpToNode logger(stdout);\n\n printf(\"rootEnvSize\\n\");\n printf(\"Failed to determine size for\\n\");\n\n defExpr->accept(&logger);\n printf(\"\\n\\n\\n\");\n }\n }\n }\n }\n }\n }\n }\n\n return retval;\n}\n\nstatic void rootEnvInit(void* env)\n{\n for_alist(rootStmt, rootModule->block->body)\n {\n if (DefExpr* rootDefExpr = toDefExpr(rootStmt))\n {\n if (ModuleSymbol* module = toModuleSymbol(rootDefExpr->sym))\n {\n if (module != rootModule)\n {\n for_alist(stmt, module->block->body)\n {\n if (DefExpr* defExpr = toDefExpr(stmt))\n {\n VarSymbol* varSym = 0;\n\n if (defExpr->init == 0)\n {\n if (Type* type = defExpr->sym->type)\n varSym = toVarSymbol(type->defaultValue);\n }\n\n else\n {\n if (SymExpr* symExpr = toSymExpr(defExpr->init))\n varSym = toVarSymbol(symExpr->var);\n }\n\n if (varSym != 0)\n {\n bool handled = false;\n\n if (Immediate* imm = varSym->immediate)\n {\n Type* type = varSym->type;\n int size = sizeForType(type);\n\n if (strcmp(type->symbol->name, \"bool\") == 0)\n {\n *((long*) env) = imm->v_bool;\n handled = true;\n }\n\n else if (strcmp(type->symbol->name, \"int\") == 0)\n {\n *((long*) env) = imm->v_int64;\n handled = true;\n }\n\n else if (strcmp(type->symbol->name, \"real\") == 0)\n {\n *((double*) env) = imm->v_float64;\n handled = true;\n }\n\n env = ((char*) env) + size;\n }\n\n if (handled == false)\n INT_ASSERT(false);\n }\n\n else if (isFnSymbol(defExpr->sym) == true)\n {\n\n }\n\n else\n {\n AstDumpToNode logger(stdout);\n\n printf(\"rootEnvInit\\n\\n\");\n printf(\"Failed to handle\\n\");\n\n defExpr->accept(&logger);\n printf(\"\\n\\n\\n\");\n\n INT_ASSERT(false);\n }\n }\n }\n }\n }\n }\n }\n}\n\nstatic void rootEnvDescribe(void* env)\n{\n printf(\"Final environment\\n\");\n\n for_alist(rootStmt, rootModule->block->body)\n {\n if (DefExpr* rootDefExpr = toDefExpr(rootStmt))\n {\n if (ModuleSymbol* module = toModuleSymbol(rootDefExpr->sym))\n {\n if (module != rootModule)\n {\n bool first = true;\n\n for_alist(stmt, module->block->body)\n {\n if (DefExpr* defExpr = toDefExpr(stmt))\n {\n if (Type* type = defExpr->sym->type)\n {\n int size = sizeForType(type);\n\n if (first == true)\n {\n printf(\" Module %s\\n\", module->name);\n first = false;\n }\n\n printf(\" %-20s \", defExpr->sym->name);\n\n if (strcmp(type->symbol->name, \"bool\") == 0)\n {\n if (*((long*) env) == 0)\n printf(\" false\\n\");\n else\n printf(\" true\\n\");\n }\n\n else if (strcmp(type->symbol->name, \"int\") == 0)\n {\n printf(\"%12lu\\n\", *((long*) env));\n }\n\n else if (strcmp(type->symbol->name, \"real\") == 0)\n {\n printf(\" %12.4f\\n\", *((double*) env));\n }\n\n env = ((char*) env) + size;\n }\n }\n }\n }\n }\n }\n }\n}\n\nstatic int sizeForType(Type* type)\n{\n int retval = 0;\n\n if (false)\n retval = 0;\n\n else if (strcmp(type->symbol->name, \"bool\") == 0)\n retval = 8;\n\n else if (strcmp(type->symbol->name, \"int\") == 0)\n retval = 8;\n\n else if (strcmp(type->symbol->name, \"real\") == 0)\n retval = 8;\n\n else\n {\n AstDumpToNode logger(stdout);\n\n printf(\"sizeForType unhandled\\n\");\n type->accept(&logger);\n printf(\"\\n\\n\\n\\n\\n\");\n INT_ASSERT(false);\n }\n\n return retval;\n}\n<|endoftext|>"} {"text":"\/*! Copyright (c) 2010-2012 Delft University of Technology.\n *\n * This software is protected by national and international copyright.\n * Any unauthorized use, reproduction or modification is unlawful and\n * will be prosecuted. Commercial and non-private application of the\n * software in any form is strictly prohibited unless otherwise granted\n * by the authors.\n *\n * The code is provided without any warranty; without even the implied\n * warranty of merchantibility or fitness for a particular purpose.\n *\n * Changelog\n * YYMMDD Author Comment\n * 110527 K. Kumar First creation of the code.\n *\n * References\n *\n *\/\n\n\/\/ Temporary notes (move to class\/function doxygen):\n\/\/ Test runs code and verifies result against expected value.\n\/\/ If the tested code is erroneous, the test function returns a boolean\n\/\/ true; if the code is correct, the function returns a boolean false.\n\/\/ \n\n\/\/ Include statements.\n#include \n#include \n#include \n#include \"Tudat\/Astrodynamics\/MissionSegments\/deepSpaceManeuver.h\"\n#include \"Tudat\/Astrodynamics\/States\/cartesianElements.h\"\n\n\/\/! Test deep space maneuver.\nint main( )\n{\n \/\/ Using declarations.\n using std::cerr;\n using std::endl;\n using namespace tudat;\n\n \/\/ Summary of tests.\n \/\/ Test 1: Test setTime( ) and getTime( ) functions.\n \/\/ Test 2: Test setState( ) and getState( ) functions with Cartesian elements state.\n\n \/\/ Test result initialised to false.\n bool isDeepSpaceManeuverErroneous_ = false;\n\n \/\/ Create DSM object.\n DeepSpaceManeuver deepSpaceManeuver_;\n\n \/\/ Test 1: Test setTime( ) and getTime( ) functions.\n \/\/ Declare and initialize time of DSM.\n double timeOfDeepSpaceManeuver_ = 123.3;\n\n \/\/ Set time of DSM.\n deepSpaceManeuver_.setTime( timeOfDeepSpaceManeuver_ );\n\n \/\/ Test if getTime( ) function results in set time for DSM.\n if ( std::fabs( timeOfDeepSpaceManeuver_ - deepSpaceManeuver_.getTime( ) )\n > std::numeric_limits< double >::epsilon( ) )\n {\n cerr << \"The setTime( )\/getTime( ) functions do not work properly.\" << endl;\n\n isDeepSpaceManeuverErroneous_ = true;\n }\n\n \/\/ Test 2: Test setState( ) and getState( ) functions with Cartesian elements\n \/\/ state.\n \/\/ Declare and initialize Cartesian elements state for DSM.\n CartesianElements deepSpaceManeuverState_;\n deepSpaceManeuverState_.setCartesianElementX( 1000.3 );\n deepSpaceManeuverState_.setCartesianElementY( 0.0 );\n deepSpaceManeuverState_.setCartesianElementZ( 613.41 );\n deepSpaceManeuverState_.setCartesianElementXDot( 2300.5 );\n deepSpaceManeuverState_.setCartesianElementYDot( 100.34 );\n deepSpaceManeuverState_.setCartesianElementZ( 0.0 );\n\n \/\/ Set DSM state.\n deepSpaceManeuver_.setState( &deepSpaceManeuverState_ );\n\n \/\/ Test if getState( ) function results in set state for DSM.\n if ( std::fabs( deepSpaceManeuverState_.state.norm( )\n - deepSpaceManeuver_.getState( )->state.norm( ) )\n > std::numeric_limits< double >::epsilon( ) )\n {\n cerr << \"The setState( )\/getState( ) functions do not work properly.\" << endl;\n isDeepSpaceManeuverErroneous_ = true;\n }\n\n \/\/ Test 1: Test setDeltaV( ) and getDeltaV( ) functions.\n \/\/ Declare and initialize deltaV for DSM.\n double deltaVOfDeepSpaceManeuver_ = 254.78;\n\n \/\/ Set deltaV of DSM.\n deepSpaceManeuver_.setDeltaV( deltaVOfDeepSpaceManeuver_ );\n\n \/\/ Test if getDeltaV( ) function results in set deltaV for DSM.\n if ( std::fabs( deltaVOfDeepSpaceManeuver_ - deepSpaceManeuver_.getDeltaV( ) )\n > std::numeric_limits< double >::epsilon( ) )\n {\n cerr << \"The setDeltaV( )\/getDeltaV( ) functions do not work properly.\" << endl;\n isDeepSpaceManeuverErroneous_ = true;\n }\n\n \/\/ Return test result.\n \/\/ If test is successful return false; if test fails, return true.\n if ( isDeepSpaceManeuverErroneous_ )\n {\n cerr << \"testDeepSpaceManeuver failed!\" << endl;\n }\n\n return isDeepSpaceManeuverErroneous_;\n}\n\n\/\/ End of file.\nPrecision fix in DSM unit test\/*! Copyright (c) 2010-2012 Delft University of Technology.\n *\n * This software is protected by national and international copyright.\n * Any unauthorized use, reproduction or modification is unlawful and\n * will be prosecuted. Commercial and non-private application of the\n * software in any form is strictly prohibited unless otherwise granted\n * by the authors.\n *\n * The code is provided without any warranty; without even the implied\n * warranty of merchantibility or fitness for a particular purpose.\n *\n * Changelog\n * YYMMDD Author Comment\n * 110527 K. Kumar First creation of the code.\n *\n * References\n *\n *\/\n\n\/\/ Temporary notes (move to class\/function doxygen):\n\/\/ Test runs code and verifies result against expected value.\n\/\/ If the tested code is erroneous, the test function returns a boolean\n\/\/ true; if the code is correct, the function returns a boolean false.\n\/\/ \n\n\/\/ Include statements.\n#include \n#include \n#include \n#include \"Tudat\/Astrodynamics\/MissionSegments\/deepSpaceManeuver.h\"\n#include \"Tudat\/Astrodynamics\/States\/cartesianElements.h\"\n\n\/\/! Test deep space maneuver.\nint main( )\n{\n \/\/ Using declarations.\n using std::cerr;\n using std::endl;\n using namespace tudat;\n\n \/\/ Summary of tests.\n \/\/ Test 1: Test setTime( ) and getTime( ) functions.\n \/\/ Test 2: Test setState( ) and getState( ) functions with Cartesian elements state.\n\n \/\/ Test result initialised to false.\n bool isDeepSpaceManeuverErroneous_ = false;\n\n \/\/ Create DSM object.\n DeepSpaceManeuver deepSpaceManeuver_;\n\n \/\/ Test 1: Test setTime( ) and getTime( ) functions.\n \/\/ Declare and initialize time of DSM.\n double timeOfDeepSpaceManeuver_ = 123.3;\n\n \/\/ Set time of DSM.\n deepSpaceManeuver_.setTime( timeOfDeepSpaceManeuver_ );\n\n \/\/ Test if getTime( ) function results in set time for DSM.\n if ( std::fabs( timeOfDeepSpaceManeuver_ - deepSpaceManeuver_.getTime( ) )\n > std::numeric_limits< double >::epsilon( ) )\n {\n cerr << \"The setTime( )\/getTime( ) functions do not work properly.\" << endl;\n\n isDeepSpaceManeuverErroneous_ = true;\n }\n\n \/\/ Test 2: Test setState( ) and getState( ) functions with Cartesian elements\n \/\/ state.\n \/\/ Declare and initialize Cartesian elements state for DSM.\n CartesianElements deepSpaceManeuverState_;\n deepSpaceManeuverState_.setCartesianElementX( 1000.3 );\n deepSpaceManeuverState_.setCartesianElementY( 0.0 );\n deepSpaceManeuverState_.setCartesianElementZ( 613.41 );\n deepSpaceManeuverState_.setCartesianElementXDot( 2300.5 );\n deepSpaceManeuverState_.setCartesianElementYDot( 100.34 );\n deepSpaceManeuverState_.setCartesianElementZ( 0.0 );\n\n \/\/ Set DSM state.\n deepSpaceManeuver_.setState( &deepSpaceManeuverState_ );\n\n \/\/ Test if getState( ) function results in set state for DSM.\n if ( std::fabs( deepSpaceManeuverState_.state.norm( )\n - deepSpaceManeuver_.getState( )->state.norm( ) )\n \/ deepSpaceManeuverState_.state.norm( )\n > std::numeric_limits< double >::epsilon( ) )\n {\n cerr << \"The setState( )\/getState( ) functions do not work properly.\" << endl;\n isDeepSpaceManeuverErroneous_ = true;\n }\n\n \/\/ Test 1: Test setDeltaV( ) and getDeltaV( ) functions.\n \/\/ Declare and initialize deltaV for DSM.\n double deltaVOfDeepSpaceManeuver_ = 254.78;\n\n \/\/ Set deltaV of DSM.\n deepSpaceManeuver_.setDeltaV( deltaVOfDeepSpaceManeuver_ );\n\n \/\/ Test if getDeltaV( ) function results in set deltaV for DSM.\n if ( std::fabs( deltaVOfDeepSpaceManeuver_ - deepSpaceManeuver_.getDeltaV( ) )\n > std::numeric_limits< double >::epsilon( ) )\n {\n cerr << \"The setDeltaV( )\/getDeltaV( ) functions do not work properly.\" << endl;\n isDeepSpaceManeuverErroneous_ = true;\n }\n\n \/\/ Return test result.\n \/\/ If test is successful return false; if test fails, return true.\n if ( isDeepSpaceManeuverErroneous_ )\n {\n cerr << \"testDeepSpaceManeuver failed!\" << endl;\n }\n\n return isDeepSpaceManeuverErroneous_;\n}\n\n\/\/ End of file.\n<|endoftext|>"} {"text":"\/*\n * Copyright (c) 2015, Facebook, Inc.\n * All rights reserved.\n *\n * This source code is licensed under the BSD-style license found in the\n * LICENSE file in the root directory of this source tree. An additional grant\n * of patent rights can be found in the PATENTS file in the same directory.\n *\n *\/\n#include \n\n#include \n\nusing folly::IOBuf;\nusing std::unique_ptr;\n\n\/\/ IOBuf uses 24 bytes of data for bookeeping purposes, so requesting for 480\n\/\/ bytes of data will be rounded up to an allocation of 512 bytes. (If we\n\/\/ requested for 512 bytes exactly IOBuf would round this up to 768, since it\n\/\/ needs 24 extra bytes of its own.)\n#ifndef NO_LIB_GFLAGS\n DEFINE_int64(zlib_buffer_growth, 480,\n \"The buffer growth size to use during IOBuf zlib inflation\");\n DEFINE_int64(zlib_buffer_minsize, 64,\n \"The minimum buffer size to use before growing during IOBuf \"\n \"zlib inflation\");\n#endif\n\nnamespace proxygen {\n\n#ifdef NO_LIB_GFLAGS\n int64_t FLAGS_zlib_buffer_growth = 480;\n int64_t FLAGS_zlib_buffer_minsize = 64;\n#endif\n\nvoid ZlibStreamDecompressor::init(ZlibCompressionType type) {\n DCHECK(type_ == ZlibCompressionType::NONE) << \"Must be uninitialized\";\n type_ = type;\n status_ = Z_OK;\n zlibStream_.zalloc = Z_NULL;\n zlibStream_.zfree = Z_NULL;\n zlibStream_.opaque = Z_NULL;\n zlibStream_.total_in = 0;\n zlibStream_.next_in = Z_NULL;\n zlibStream_.avail_in = 0;\n zlibStream_.avail_out = 0;\n zlibStream_.next_out = Z_NULL;\n\n DCHECK(type != ZlibCompressionType::NONE);\n status_ = inflateInit2(&zlibStream_, static_cast(type_));\n}\n\nZlibStreamDecompressor::ZlibStreamDecompressor(ZlibCompressionType type)\n : type_(ZlibCompressionType::NONE), status_(Z_OK) {\n init(type);\n}\n\nZlibStreamDecompressor::~ZlibStreamDecompressor() {\n if (type_ != ZlibCompressionType::NONE) {\n status_ = inflateEnd(&zlibStream_);\n }\n}\n\nstd::unique_ptr ZlibStreamDecompressor::decompress(const IOBuf* in) {\n auto out = IOBuf::create(FLAGS_zlib_buffer_growth);\n auto appender = folly::io::Appender(out.get(),\n FLAGS_zlib_buffer_growth);\n\n const IOBuf* crtBuf = in;\n size_t offset = 0;\n while (true) {\n \/\/ Advance to the next IOBuf if necessary\n DCHECK_GE(crtBuf->length(), offset);\n if (crtBuf->length() == offset) {\n crtBuf = crtBuf->next();\n offset = 0;\n if (crtBuf == in) {\n \/\/ We hit the end of the IOBuf chain, and are done.\n break;\n }\n }\n\n \/\/ The decompressor says we should have finished\n if (status_ == Z_STREAM_END) {\n \/\/ we convert this into a stream error\n status_ = Z_STREAM_ERROR;\n \/\/ we should probably bump up a counter here\n LOG(ERROR) << \"error uncompressing buffer: reached end of zlib data \"\n \"before the end of the buffer\";\n return nullptr;\n }\n\n \/\/ Ensure there is space in the output IOBuf\n appender.ensure(FLAGS_zlib_buffer_minsize);\n DCHECK_GT(appender.length(), 0);\n\n const size_t origAvailIn = crtBuf->length() - offset;\n zlibStream_.next_in = const_cast(crtBuf->data() + offset);\n zlibStream_.avail_in = origAvailIn;\n zlibStream_.next_out = appender.writableData();\n zlibStream_.avail_out = appender.length();\n status_ = inflate(&zlibStream_, Z_PARTIAL_FLUSH);\n if (status_ != Z_OK && status_ != Z_STREAM_END) {\n LOG(ERROR) << \"error uncompressing buffer: r=\" << status_;\n return nullptr;\n }\n\n \/\/ Adjust the input offset ahead\n auto inConsumed = origAvailIn - zlibStream_.avail_in;\n offset += inConsumed;\n \/\/ Move output buffer ahead\n auto outMove = appender.length() - zlibStream_.avail_out;\n appender.append(outMove);\n }\n\n return out;\n}\n\n}\nFires all the time so we're temporarily bumping it to INFO\/*\n * Copyright (c) 2015, Facebook, Inc.\n * All rights reserved.\n *\n * This source code is licensed under the BSD-style license found in the\n * LICENSE file in the root directory of this source tree. An additional grant\n * of patent rights can be found in the PATENTS file in the same directory.\n *\n *\/\n#include \n\n#include \n\nusing folly::IOBuf;\nusing std::unique_ptr;\n\n\/\/ IOBuf uses 24 bytes of data for bookeeping purposes, so requesting for 480\n\/\/ bytes of data will be rounded up to an allocation of 512 bytes. (If we\n\/\/ requested for 512 bytes exactly IOBuf would round this up to 768, since it\n\/\/ needs 24 extra bytes of its own.)\n#ifndef NO_LIB_GFLAGS\n DEFINE_int64(zlib_buffer_growth, 480,\n \"The buffer growth size to use during IOBuf zlib inflation\");\n DEFINE_int64(zlib_buffer_minsize, 64,\n \"The minimum buffer size to use before growing during IOBuf \"\n \"zlib inflation\");\n#endif\n\nnamespace proxygen {\n\n#ifdef NO_LIB_GFLAGS\n int64_t FLAGS_zlib_buffer_growth = 480;\n int64_t FLAGS_zlib_buffer_minsize = 64;\n#endif\n\nvoid ZlibStreamDecompressor::init(ZlibCompressionType type) {\n DCHECK(type_ == ZlibCompressionType::NONE) << \"Must be uninitialized\";\n type_ = type;\n status_ = Z_OK;\n zlibStream_.zalloc = Z_NULL;\n zlibStream_.zfree = Z_NULL;\n zlibStream_.opaque = Z_NULL;\n zlibStream_.total_in = 0;\n zlibStream_.next_in = Z_NULL;\n zlibStream_.avail_in = 0;\n zlibStream_.avail_out = 0;\n zlibStream_.next_out = Z_NULL;\n\n DCHECK(type != ZlibCompressionType::NONE);\n status_ = inflateInit2(&zlibStream_, static_cast(type_));\n}\n\nZlibStreamDecompressor::ZlibStreamDecompressor(ZlibCompressionType type)\n : type_(ZlibCompressionType::NONE), status_(Z_OK) {\n init(type);\n}\n\nZlibStreamDecompressor::~ZlibStreamDecompressor() {\n if (type_ != ZlibCompressionType::NONE) {\n status_ = inflateEnd(&zlibStream_);\n }\n}\n\nstd::unique_ptr ZlibStreamDecompressor::decompress(const IOBuf* in) {\n auto out = IOBuf::create(FLAGS_zlib_buffer_growth);\n auto appender = folly::io::Appender(out.get(),\n FLAGS_zlib_buffer_growth);\n\n const IOBuf* crtBuf = in;\n size_t offset = 0;\n while (true) {\n \/\/ Advance to the next IOBuf if necessary\n DCHECK_GE(crtBuf->length(), offset);\n if (crtBuf->length() == offset) {\n crtBuf = crtBuf->next();\n offset = 0;\n if (crtBuf == in) {\n \/\/ We hit the end of the IOBuf chain, and are done.\n break;\n }\n }\n\n \/\/ The decompressor says we should have finished\n if (status_ == Z_STREAM_END) {\n \/\/ we convert this into a stream error\n status_ = Z_STREAM_ERROR;\n \/\/ we should probably bump up a counter here\n LOG(ERROR) << \"error uncompressing buffer: reached end of zlib data \"\n \"before the end of the buffer\";\n return nullptr;\n }\n\n \/\/ Ensure there is space in the output IOBuf\n appender.ensure(FLAGS_zlib_buffer_minsize);\n DCHECK_GT(appender.length(), 0);\n\n const size_t origAvailIn = crtBuf->length() - offset;\n zlibStream_.next_in = const_cast(crtBuf->data() + offset);\n zlibStream_.avail_in = origAvailIn;\n zlibStream_.next_out = appender.writableData();\n zlibStream_.avail_out = appender.length();\n status_ = inflate(&zlibStream_, Z_PARTIAL_FLUSH);\n if (status_ != Z_OK && status_ != Z_STREAM_END) {\n LOG(INFO) << \"error uncompressing buffer: r=\" << status_;\n return nullptr;\n }\n\n \/\/ Adjust the input offset ahead\n auto inConsumed = origAvailIn - zlibStream_.avail_in;\n offset += inConsumed;\n \/\/ Move output buffer ahead\n auto outMove = appender.length() - zlibStream_.avail_out;\n appender.append(outMove);\n }\n\n return out;\n}\n\n}\n<|endoftext|>"} {"text":"\/*\n\nCopyright (c) 2015, Project OSRM, Dennis Luxen, others\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without modification,\nare permitted provided that the following conditions are met:\n\nRedistributions of source code must retain the above copyright notice, this list\nof conditions and the following disclaimer.\nRedistributions in binary form must reproduce the above copyright notice, this\nlist of conditions and the following disclaimer in the documentation and\/or\nother materials provided with the distribution.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\nANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\nWARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR\nANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\nLOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON\nANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\nSOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#include \"..\/Library\/OSRM.h\"\n#include \"..\/Util\/git_sha.hpp\"\n#include \"..\/Util\/ProgramOptions.h\"\n#include \"..\/Util\/simple_logger.hpp\"\n\n#include \n#include \n#include \n\n#include \n#include \n\n#include \n#include \n#include \n#include \n\n\/\/ Dude, real recursions on the OS stack? You must be brave...\nvoid print_tree(boost::property_tree::ptree const &property_tree, const unsigned recursion_depth)\n{\n auto end = property_tree.end();\n for (auto tree_iterator = property_tree.begin(); tree_iterator != end; ++tree_iterator)\n {\n for (unsigned current_recursion = 0; current_recursion < recursion_depth;\n ++current_recursion)\n {\n std::cout << \" \" << std::flush;\n }\n std::cout << tree_iterator->first << \": \" << tree_iterator->second.get_value()\n << std::endl;\n print_tree(tree_iterator->second, recursion_depth + 1);\n }\n}\n\nint main(int argc, const char *argv[])\n{\n LogPolicy::GetInstance().Unmute();\n try\n {\n std::string ip_address;\n int ip_port, requested_thread_num;\n bool use_shared_memory = false, trial = false;\n ServerPaths server_paths;\n if (!GenerateServerProgramOptions(argc,\n argv,\n server_paths,\n ip_address,\n ip_port,\n requested_thread_num,\n use_shared_memory,\n trial))\n {\n return 0;\n }\n\n SimpleLogger().Write() << \"starting up engines, \" << g_GIT_DESCRIPTION;\n\n OSRM routing_machine(server_paths, use_shared_memory);\n\n RouteParameters route_parameters;\n route_parameters.zoom_level = 18; \/\/ no generalization\n route_parameters.print_instructions = true; \/\/ turn by turn instructions\n route_parameters.alternate_route = true; \/\/ get an alternate route, too\n route_parameters.geometry = true; \/\/ retrieve geometry of route\n route_parameters.compression = true; \/\/ polyline encoding\n route_parameters.check_sum = UINT_MAX; \/\/ see wiki\n route_parameters.service = \"viaroute\"; \/\/ that's routing\n route_parameters.output_format = \"json\";\n route_parameters.jsonp_parameter = \"\"; \/\/ set for jsonp wrapping\n route_parameters.language = \"\"; \/\/ unused atm\n \/\/ route_parameters.hints.push_back(); \/\/ see wiki, saves I\/O if done properly\n\n \/\/ start_coordinate\n route_parameters.coordinates.emplace_back(52.519930 * COORDINATE_PRECISION,\n 13.438640 * COORDINATE_PRECISION);\n \/\/ target_coordinate\n route_parameters.coordinates.emplace_back(52.513191 * COORDINATE_PRECISION,\n 13.415852 * COORDINATE_PRECISION);\n http::Reply osrm_reply;\n routing_machine.RunQuery(route_parameters, osrm_reply);\n\n \/\/ attention: super-inefficient hack below:\n\n std::stringstream my_stream;\n for (const auto &element : osrm_reply.content)\n {\n std::cout << element;\n my_stream << element;\n }\n std::cout << std::endl;\n\n boost::property_tree::ptree property_tree;\n boost::property_tree::read_json(my_stream, property_tree);\n\n print_tree(property_tree, 0);\n }\n catch (std::exception ¤t_exception)\n {\n SimpleLogger().Write(logWARNING) << \"caught exception: \" << current_exception.what();\n return -1;\n }\n return 0;\n}\nfix initialization of simple client\/*\n\nCopyright (c) 2015, Project OSRM, Dennis Luxen, others\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without modification,\nare permitted provided that the following conditions are met:\n\nRedistributions of source code must retain the above copyright notice, this list\nof conditions and the following disclaimer.\nRedistributions in binary form must reproduce the above copyright notice, this\nlist of conditions and the following disclaimer in the documentation and\/or\nother materials provided with the distribution.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\nANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\nWARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR\nANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\nLOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON\nANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\nSOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#include \"..\/Library\/OSRM.h\"\n#include \"..\/Util\/git_sha.hpp\"\n#include \"..\/Util\/ProgramOptions.h\"\n#include \"..\/Util\/simple_logger.hpp\"\n\n#include \n#include \n#include \n\n#include \n#include \n\n#include \n#include \n#include \n#include \n\n\/\/ Dude, real recursions on the OS stack? You must be brave...\nvoid print_tree(boost::property_tree::ptree const &property_tree, const unsigned recursion_depth)\n{\n auto end = property_tree.end();\n for (auto tree_iterator = property_tree.begin(); tree_iterator != end; ++tree_iterator)\n {\n for (unsigned current_recursion = 0; current_recursion < recursion_depth;\n ++current_recursion)\n {\n std::cout << \" \" << std::flush;\n }\n std::cout << tree_iterator->first << \": \" << tree_iterator->second.get_value()\n << std::endl;\n print_tree(tree_iterator->second, recursion_depth + 1);\n }\n}\n\nint main(int argc, const char *argv[])\n{\n LogPolicy::GetInstance().Unmute();\n try\n {\n std::string ip_address;\n int ip_port, requested_thread_num;\n bool use_shared_memory = false, trial_run = false;\n ServerPaths server_paths;\n\n const unsigned init_result = GenerateServerProgramOptions(argc,\n argv,\n server_paths,\n ip_address,\n ip_port,\n requested_thread_num,\n use_shared_memory,\n trial_run);\n\n if (init_result == INIT_FAILED)\n {\n return 0;\n }\n\n SimpleLogger().Write() << \"starting up engines, \" << g_GIT_DESCRIPTION;\n\n OSRM routing_machine(server_paths, use_shared_memory);\n\n RouteParameters route_parameters;\n route_parameters.zoom_level = 18; \/\/ no generalization\n route_parameters.print_instructions = true; \/\/ turn by turn instructions\n route_parameters.alternate_route = true; \/\/ get an alternate route, too\n route_parameters.geometry = true; \/\/ retrieve geometry of route\n route_parameters.compression = true; \/\/ polyline encoding\n route_parameters.check_sum = UINT_MAX; \/\/ see wiki\n route_parameters.service = \"viaroute\"; \/\/ that's routing\n route_parameters.output_format = \"json\";\n route_parameters.jsonp_parameter = \"\"; \/\/ set for jsonp wrapping\n route_parameters.language = \"\"; \/\/ unused atm\n \/\/ route_parameters.hints.push_back(); \/\/ see wiki, saves I\/O if done properly\n\n \/\/ start_coordinate\n route_parameters.coordinates.emplace_back(52.519930 * COORDINATE_PRECISION,\n 13.438640 * COORDINATE_PRECISION);\n \/\/ target_coordinate\n route_parameters.coordinates.emplace_back(52.513191 * COORDINATE_PRECISION,\n 13.415852 * COORDINATE_PRECISION);\n http::Reply osrm_reply;\n routing_machine.RunQuery(route_parameters, osrm_reply);\n\n \/\/ attention: super-inefficient hack below:\n\n std::stringstream my_stream;\n for (const auto &element : osrm_reply.content)\n {\n std::cout << element;\n my_stream << element;\n }\n std::cout << std::endl;\n\n boost::property_tree::ptree property_tree;\n boost::property_tree::read_json(my_stream, property_tree);\n\n print_tree(property_tree, 0);\n }\n catch (std::exception ¤t_exception)\n {\n SimpleLogger().Write(logWARNING) << \"caught exception: \" << current_exception.what();\n return -1;\n }\n return 0;\n}\n<|endoftext|>"} {"text":"\/*\n * Samplebuffer.cpp\n *\n * Created on: Dec 4, 2013\n * Author: gwue\n *\/\n\n#include \"Soundbuffer.hpp\"\n\nSoundbuffer::Soundbuffer()\n{\n\tSoundgatesConfig* cfg = SoundgatesConfig::getInstance();\n\tthis->SOUNDBUFFERSIZE = (int) (cfg->getConf(CFG_SOUND_BUFFER_SIZE));\n\tthis->ALSACHARS = (int) (cfg->getConf(CFG_ALSA_CHUNKS));\n\tunsigned int samplerate = (unsigned int) (cfg->getConf(CFG_SAMPLE_RATE));\n\n\tthis->buffer = (char*) malloc(this->SOUNDBUFFERSIZE * sizeof(char));\n\n\tint err;\n\n\t\/\/ Always offer chunks of the same size to ALSA\n\tthis->alsaSamples = ALSACHARS \/ this->getFrameSize();\n\tthis->sane = true;\n\tthis->running = true;\n\tthis->playing = false;\n\tthis->writeoffset = 0;\n\tthis->readoffset = 0;\n\tfor (int i = 0; i < SOUNDBUFFERSIZE; i++)\n\t{\n\t\tthis->buffer[i] = 0;\n\t}\n\n\tsnd_pcm_stream_t stream = SND_PCM_STREAM_PLAYBACK;\n\n\tif ((err = snd_pcm_open(&(this->pcm_handle), \"plughw:0,0\", stream, 0)) < 0)\n\t{\n\t\tfprintf(stderr, \"cannot open audio device (%s)\\n\", snd_strerror(err));\n\t\tthis->sane = false;\n\t}\n\n\tif ((err = snd_pcm_hw_params_malloc(&this->hw_params)) < 0)\n\t{\n\t\tfprintf(stderr,\n\t\t\t\t\"cannot allocate record hardware parameter structure (%s)\\n\",\n\t\t\t\tsnd_strerror(err));\n\t\tthis->sane = false;\n\t}\n\n\tif ((err = snd_pcm_hw_params_any(this->pcm_handle, this->hw_params)) < 0)\n\t{\n\t\tfprintf(stderr, \"cannot initialize hardware parameter structure (%s)\\n\",\n\t\t\t\tsnd_strerror(err));\n\t\tthis->sane = false;\n\t}\n\tif ((err = snd_pcm_hw_params_set_access(this->pcm_handle, this->hw_params,\n\t\t\tSND_PCM_ACCESS_RW_INTERLEAVED)) < 0)\n\t{\n\t\tfprintf(stderr, \"cannot set access type (%s)\\n\", snd_strerror(err));\n\t\tthis->sane = false;\n\t}\n\t\/\/TODO only one format supported right now. should be made selectable in the future\n\t\/\/ Currently, it is set to Unsigned Integer 32 Bit, Little Endian.\n\t\/\/ If you change this here, every function that operates on sound data would need to be adjusted accordingly!\n\tif ((err = snd_pcm_hw_params_set_format(this->pcm_handle, this->hw_params,\n\t\t\tSND_PCM_FORMAT_S32_LE)) < 0)\n\t{\n\t\tfprintf(stderr, \"cannot set sample format (%s)\\n\", snd_strerror(err));\n\t\tthis->sane = false;\n\t}\n\tif ((err = snd_pcm_hw_params_set_buffer_size(this->pcm_handle,\n\t\t\tthis->hw_params, 2048)) < 0)\n\t{\n\t\tfprintf(stderr, \"cannot set buffer size (%s)\\n\", snd_strerror(err));\n\t\tthis->sane = false;\n\t}\n\n\t\/\/TODO Handling for unsupported sampling rates\n\tunsigned int exact_rate = samplerate;\n\tif ((err = snd_pcm_hw_params_set_rate_near(this->pcm_handle,\n\t\t\tthis->hw_params, &exact_rate, 0)) < 0)\n\t{\n\t\tfprintf(stderr, \"cannot set sample rate (%s)\\n\", snd_strerror(err));\n\t\tthis->sane = false;\n\t}\n\tif (samplerate != exact_rate)\n\t{\n\t\tprintf(\"Rate %i not supported, set to %i \\n\", samplerate, exact_rate);\n\t}\n\n\t\/\/ TODO For now, only one channel. Increase this to two channels in the future\n\tif ((err = snd_pcm_hw_params_set_channels(this->pcm_handle, this->hw_params,\n\t\t\t1)) < 0)\n\t{\n\t\tfprintf(stderr, \"cannot set channel count (%s)\\n\", snd_strerror(err));\n\t\tthis->sane = false;\n\t}\n\tif ((err = snd_pcm_hw_params(this->pcm_handle, this->hw_params)) < 0)\n\t{\n\t\tfprintf(stderr, \"cannot set parameters (%s)\\n\", snd_strerror(err));\n\t\tthis->sane = false;\n\t}\n\tif ((err = snd_pcm_prepare(this->pcm_handle)) < 0)\n\t{\n\t\tfprintf(stderr, \"cannot prepare audio interface for use (%s)\\n\",\n\t\t\t\tsnd_strerror(err));\n\t\tthis->sane = false;\n\t}\n\n\t\/\/ If no errors occured we can create our playback thread\n\t\/\/TODO uncomment this\n\/\/\tif (this->sane)\n\t{\n\t\tthis->bufferThread = boost::thread(&Soundbuffer::run, this);\n\t}\n}\n\nvoid Soundbuffer::run()\n{\n\tint nframes;\n\tint err = 0;\n\tsnd_pcm_prepare(this->pcm_handle);\n\n\twhile (this->running)\n\t{\n\t\t\/\/ Wait for the playback to start\n\t\tif (!this->playing)\n\t\t{\n\t\t\tusleep(50000);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tnframes = 0;\n\n\t\t\t\/\/ Wait for the audio device to become ready (or timeout after a second)\n\t\t\tif ((err = snd_pcm_wait(this->pcm_handle, 1000)) < 0)\n\t\t\t{\n\t\t\t\tfprintf(stderr, \"poll failed (%s)\\n\", snd_strerror(err));\n\t\t\t\tthis->running = 0;\n\t\t\t}\n\n\t\t\t\/\/ Ask the audio device how many frames it can accept\n\t\t\tif ((nframes = snd_pcm_avail_update(this->pcm_handle)) < 0)\n\t\t\t{\n\t\t\t\tfprintf(stderr, \"unknown ALSA avail update return value (%s)\\n\",\n\t\t\t\t\t\tsnd_strerror(nframes));\n\t\t\t\tthis->running = 0;\n\t\t\t}\n\n\t\t\t\/\/ Only write to the soundcard if alsa requested enough frames\n\t\t\tif (nframes >= this->alsaSamples)\n\t\t\t{\n\t\t\t\tthis->mutex.lock();\n\t\t\t\tchar* frames = this->getNextFrames();\n\n\t\t\t\tif ((err = snd_pcm_writei(this->pcm_handle, frames,\n\t\t\t\t\t\tthis->alsaSamples)) < 0)\n\t\t\t\t{\n\t\t\t\t\tfprintf(stderr, \"write to audio interface failed (%s)\\n\",\n\t\t\t\t\t\t\tsnd_strerror(err));\n\t\t\t\t\tthis->running = 0;\n\t\t\t\t}\n\t\t\t\tthis->mutex.unlock();\n\n\t\t\t}\n\t\t}\n\t}\n}\n\nSoundbuffer::~Soundbuffer()\n{\n}\n\nchar* Soundbuffer::getNextFrames()\n{\n\tbool ptr_return = false;\n\n\t\/\/ Advance readbuffer by ALSACHUNKS\n\tint nextReadOffset = this->readoffset + ALSACHARS;\n\t\/\/ If we reached the end, restart from the beginning\n\tif (nextReadOffset >= SOUNDBUFFERSIZE)\n\t{\n\t\tnextReadOffset = 0;\n\t\tptr_return = true;\n\t}\n\t\/\/ We might read samples faster than we produce them.\n\t\/\/ In that case we don't want to advance the readoffset past the writeoffset\n\t\/\/ Write and read offset are allowed to be same. This would mean the buffer is completely filled.\n\t\/\/ Therefore, don't check for equality here.\n\tif ( \t(!ptr_return && (this->readoffset < this->writeoffset && nextReadOffset > this->writeoffset )) ||\n\t\t \t(ptr_return && (this->readoffset < this->writeoffset)))\n\t{\n\t\tstd::cerr\n\t\t\t\t<< \"Buffer has run dry! This should not happen! Will now play previous samples again! RO:\" << this->readoffset << \" WO:\" << this->writeoffset\n\t\t\t\t<< std::endl;\n\t}\n\telse\n\t{\n\t\tthis->readoffset = nextReadOffset;\n\t}\n\n\tchar* buffer_ptr = this->buffer + this->readoffset;\n\treturn buffer_ptr;\n}\n\nvoid Soundbuffer::startPlayback()\n{\n\tthis->playing = true;\n}\n\nvoid Soundbuffer::stopThread()\n{\n\tthis->running = false;\n\tthis->bufferThread.join();\n}\n\nvoid Soundbuffer::testPlayback()\n{\n\tprintf(\"Starting test playback!\\n\");\n\tint err;\n\tint nframes = 0;\n\tchar sine[SOUNDBUFFERSIZE];\n\tdouble phase = 0;\n\n\tfor (double freq = 27.5; freq < 4187; freq *=\n\t\t\t1.0594630943592952645618252949463)\n\t{\n\t\tprintf(\"Freq: %f\\n\", freq);\n\t\tfor (int i = 0; i < 50; i++)\n\t\t{\n\t\t\tif ((err = snd_pcm_wait(this->pcm_handle, 1000)) < 0)\n\t\t\t{\n\t\t\t\tfprintf(stderr, \"poll failed (%s)\\n\", strerror(err));\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif ((nframes = snd_pcm_avail_update(this->pcm_handle)) < 0)\n\t\t\t{\n\t\t\t\tfprintf(stderr, \"unknown ALSA avail update return value (%d)\\n\",\n\t\t\t\t\t\tnframes);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (nframes > SOUNDBUFFERSIZE \/ 4)\n\t\t\t{\n\t\t\t\tnframes = SOUNDBUFFERSIZE \/ 4;\n\t\t\t}\n\t\t\tfor (int j = 0; j < nframes; j++)\n\t\t\t{\n\t\t\t\t((int*) sine)[j] = (int) (sin(phase) * INT_MAX);\n\n\t\t\t\tphase += (2 * M_PI \/ 44100.0) * freq;\n\n\t\t\t\tif (phase > M_PI * 2)\n\t\t\t\t{\n\t\t\t\t\tphase -= M_PI * 2;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif ((err = snd_pcm_writei(this->pcm_handle, sine, nframes)) < 0)\n\t\t\t{\n\t\t\t\tfprintf(stderr, \"write to audio interface failed (%s)\\n\",\n\t\t\t\t\t\tsnd_strerror(err));\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t}\n\n\tprintf(\"Stopping test playback!\\n\");\n}\n\nvoid Soundbuffer::fillbuffer(char* data, int size)\n{\n\tif ((size & (size - 1)) != 0)\n\t{\n\t\tstd::cerr << \"You need to fill the buffer with array sizes x^2\"\n\t\t\t\t<< std::endl;\n\t\treturn;\n\t}\n\tif (size >= SOUNDBUFFERSIZE)\n\t{\n\t\tstd::cerr << \"Too many samples. Might be at most \"\n\t\t\t\t<< SOUNDBUFFERSIZE \/ 2 << std::endl;\n\t\treturn;\n\t}\n\n\twhile (!this->canAcceptData(size))\n\t{\n\t\tusleep(100);\n\t}\n\n\tthis->mutex.lock();\n\tfor (int i = 0; i < size; i++)\n\t{\n\t\tthis->buffer[this->writeoffset] = data[i];\n\t\tthis->writeoffset++;\n\t\tif (this->writeoffset >= SOUNDBUFFERSIZE)\n\t\t{\n\t\t\tthis->writeoffset = 0;\n\t\t}\n\t}\n\tthis->mutex.unlock();\n\n}\n\nbool Soundbuffer::canAcceptData(int size)\n{\n\tint free;\n\n\tthis->mutex.lock();\n\tif (this->writeoffset > this->readoffset)\n\t{\n\t\tfree = this->readoffset + (SOUNDBUFFERSIZE - this->writeoffset);\n\t}\n\telse if (this->writeoffset < this->readoffset)\n\t{\n\t\tfree = this->readoffset - this->writeoffset;\n\t}\n\telse\n\t{\n\t\t\/\/write and readoffset equal ---> buffer is full\n\t\tfree = 0;\n\t}\n\tthis->mutex.unlock();\n\n\tif (free >= size)\n\t{\n\t\treturn true;\n\t}\n\telse\n\t{\n\t\treturn false;\n\t}\n}\n\nint Soundbuffer::getFrameSize()\n{\n\treturn 4;\n}\nALSA wird nun neu initialisiert wenn der Buffer leer läuft anstatt die Ausgabe komplett zu beenden\/*\n * Samplebuffer.cpp\n *\n * Created on: Dec 4, 2013\n * Author: gwue\n *\/\n\n#include \"Soundbuffer.hpp\"\n\nSoundbuffer::Soundbuffer()\n{\n\tSoundgatesConfig* cfg = SoundgatesConfig::getInstance();\n\tthis->SOUNDBUFFERSIZE = (int) (cfg->getConf(CFG_SOUND_BUFFER_SIZE));\n\tthis->ALSACHARS = (int) (cfg->getConf(CFG_ALSA_CHUNKS));\n\tunsigned int samplerate = (unsigned int) (cfg->getConf(CFG_SAMPLE_RATE));\n\n\tthis->buffer = (char*) malloc(this->SOUNDBUFFERSIZE * sizeof(char));\n\n\tint err;\n\n\t\/\/ Always offer chunks of the same size to ALSA\n\tthis->alsaSamples = ALSACHARS \/ this->getFrameSize();\n\tthis->sane = true;\n\tthis->running = true;\n\tthis->playing = false;\n\tthis->writeoffset = 0;\n\tthis->readoffset = 0;\n\tfor (int i = 0; i < SOUNDBUFFERSIZE; i++)\n\t{\n\t\tthis->buffer[i] = 0;\n\t}\n\n\tsnd_pcm_stream_t stream = SND_PCM_STREAM_PLAYBACK;\n\n\tif ((err = snd_pcm_open(&(this->pcm_handle), \"plughw:0,0\", stream, 0)) < 0)\n\t{\n\t\tfprintf(stderr, \"cannot open audio device (%s)\\n\", snd_strerror(err));\n\t\tthis->sane = false;\n\t}\n\n\tif ((err = snd_pcm_hw_params_malloc(&this->hw_params)) < 0)\n\t{\n\t\tfprintf(stderr,\n\t\t\t\t\"cannot allocate record hardware parameter structure (%s)\\n\",\n\t\t\t\tsnd_strerror(err));\n\t\tthis->sane = false;\n\t}\n\n\tif ((err = snd_pcm_hw_params_any(this->pcm_handle, this->hw_params)) < 0)\n\t{\n\t\tfprintf(stderr, \"cannot initialize hardware parameter structure (%s)\\n\",\n\t\t\t\tsnd_strerror(err));\n\t\tthis->sane = false;\n\t}\n\tif ((err = snd_pcm_hw_params_set_access(this->pcm_handle, this->hw_params,\n\t\t\tSND_PCM_ACCESS_RW_INTERLEAVED)) < 0)\n\t{\n\t\tfprintf(stderr, \"cannot set access type (%s)\\n\", snd_strerror(err));\n\t\tthis->sane = false;\n\t}\n\t\/\/TODO only one format supported right now. should be made selectable in the future\n\t\/\/ Currently, it is set to Unsigned Integer 32 Bit, Little Endian.\n\t\/\/ If you change this here, every function that operates on sound data would need to be adjusted accordingly!\n\tif ((err = snd_pcm_hw_params_set_format(this->pcm_handle, this->hw_params,\n\t\t\tSND_PCM_FORMAT_S32_LE)) < 0)\n\t{\n\t\tfprintf(stderr, \"cannot set sample format (%s)\\n\", snd_strerror(err));\n\t\tthis->sane = false;\n\t}\n\tif ((err = snd_pcm_hw_params_set_buffer_size(this->pcm_handle,\n\t\t\tthis->hw_params, 2048)) < 0)\n\t{\n\t\tfprintf(stderr, \"cannot set buffer size (%s)\\n\", snd_strerror(err));\n\t\tthis->sane = false;\n\t}\n\n\t\/\/TODO Handling for unsupported sampling rates\n\tunsigned int exact_rate = samplerate;\n\tif ((err = snd_pcm_hw_params_set_rate_near(this->pcm_handle,\n\t\t\tthis->hw_params, &exact_rate, 0)) < 0)\n\t{\n\t\tfprintf(stderr, \"cannot set sample rate (%s)\\n\", snd_strerror(err));\n\t\tthis->sane = false;\n\t}\n\tif (samplerate != exact_rate)\n\t{\n\t\tprintf(\"Rate %i not supported, set to %i \\n\", samplerate, exact_rate);\n\t}\n\n\t\/\/ TODO For now, only one channel. Increase this to two channels in the future\n\tif ((err = snd_pcm_hw_params_set_channels(this->pcm_handle, this->hw_params,\n\t\t\t1)) < 0)\n\t{\n\t\tfprintf(stderr, \"cannot set channel count (%s)\\n\", snd_strerror(err));\n\t\tthis->sane = false;\n\t}\n\tif ((err = snd_pcm_hw_params(this->pcm_handle, this->hw_params)) < 0)\n\t{\n\t\tfprintf(stderr, \"cannot set parameters (%s)\\n\", snd_strerror(err));\n\t\tthis->sane = false;\n\t}\n\tif ((err = snd_pcm_prepare(this->pcm_handle)) < 0)\n\t{\n\t\tfprintf(stderr, \"cannot prepare audio interface for use (%s)\\n\",\n\t\t\t\tsnd_strerror(err));\n\t\tthis->sane = false;\n\t}\n\n\t\/\/ If no errors occured we can create our playback thread\n\t\/\/TODO uncomment this\n\/\/\tif (this->sane)\n\t{\n\t\tthis->bufferThread = boost::thread(&Soundbuffer::run, this);\n\t}\n}\n\nvoid Soundbuffer::run()\n{\n\tint nframes;\n\tint err = 0;\n\tbool bufferUnderrun = false;\n\tsnd_pcm_prepare(this->pcm_handle);\n\n\twhile (this->running)\n\t{\n\t\t\/\/ Wait for the playback to start\n\t\tif (!this->playing)\n\t\t{\n\t\t\tusleep(50000);\n\t\t}\n\t\telse\n\t\t{\n\t\t\t\/\/If a buffer underrun occured, we need to reinitialize the ALSA device\n\t\t\tif (bufferUnderrun)\n\t\t\t{\n\t\t\t\tsnd_pcm_prepare(this->pcm_handle);\n\t\t\t\tbufferUnderrun =false;\n\t\t\t}\n\n\t\t\tnframes = 0;\n\n\t\t\t\/\/ Wait for the audio device to become ready (or timeout after a second)\n\t\t\tif ((err = snd_pcm_wait(this->pcm_handle, 1000)) < 0)\n\t\t\t{\n\t\t\t\tfprintf(stderr, \"poll failed (%s): Most likely a buffer underrun occured\\n\", snd_strerror(err));\n\t\t\t\tbufferUnderrun = true;\n\t\t\t\t\/\/\tthis->running = 0;\n\t\t\t}\n\n\t\t\t\/\/ Ask the audio device how many frames it can accept\n\t\t\tif (!bufferUnderrun && (nframes = snd_pcm_avail_update(this->pcm_handle)) < 0)\n\t\t\t{\n\t\t\t\tfprintf(stderr, \"unknown ALSA avail update return value (%s)\\n\",\n\t\t\t\t\t\tsnd_strerror(nframes));\n\t\t\t\tthis->running = 0;\n\t\t\t}\n\n\t\t\t\/\/ Only write to the soundcard if alsa requested enough frames\n\t\t\tif (!bufferUnderrun && (nframes >= this->alsaSamples))\n\t\t\t{\n\t\t\t\tthis->mutex.lock();\n\t\t\t\tchar* frames = this->getNextFrames();\n\n\t\t\t\tif ((err = snd_pcm_writei(this->pcm_handle, frames,\n\t\t\t\t\t\tthis->alsaSamples)) < 0)\n\t\t\t\t{\n\t\t\t\t\tfprintf(stderr, \"write to audio interface failed (%s)\\n\",\n\t\t\t\t\t\t\tsnd_strerror(err));\n\t\t\t\t\tthis->running = 0;\n\t\t\t\t}\n\t\t\t\tthis->mutex.unlock();\n\n\t\t\t}\n\t\t}\n\t}\n}\n\nSoundbuffer::~Soundbuffer()\n{\n}\n\nchar* Soundbuffer::getNextFrames()\n{\n\tbool ptr_return = false;\n\n\t\/\/ Advance readbuffer by ALSACHUNKS\n\tint nextReadOffset = this->readoffset + ALSACHARS;\n\t\/\/ If we reached the end, restart from the beginning\n\tif (nextReadOffset >= SOUNDBUFFERSIZE)\n\t{\n\t\tnextReadOffset = 0;\n\t\tptr_return = true;\n\t}\n\t\/\/ We might read samples faster than we produce them.\n\t\/\/ In that case we don't want to advance the readoffset past the writeoffset\n\t\/\/ Write and read offset are allowed to be same. This would mean the buffer is completely filled.\n\t\/\/ Therefore, don't check for equality here.\n\tif ( \t(!ptr_return && (this->readoffset < this->writeoffset && nextReadOffset > this->writeoffset )) ||\n\t\t \t(ptr_return && (this->readoffset < this->writeoffset)))\n\t{\n\t\tstd::cerr\n\t\t\t\t<< \"Buffer has run dry! This should not happen! Will now play previous samples again! RO:\" << this->readoffset << \" WO:\" << this->writeoffset\n\t\t\t\t<< std::endl;\n\t}\n\telse\n\t{\n\t\tthis->readoffset = nextReadOffset;\n\t}\n\n\tchar* buffer_ptr = this->buffer + this->readoffset;\n\treturn buffer_ptr;\n}\n\nvoid Soundbuffer::startPlayback()\n{\n\tthis->playing = true;\n}\n\nvoid Soundbuffer::stopThread()\n{\n\tthis->running = false;\n\tthis->bufferThread.join();\n}\n\nvoid Soundbuffer::testPlayback()\n{\n\tprintf(\"Starting test playback!\\n\");\n\tint err;\n\tint nframes = 0;\n\tchar sine[SOUNDBUFFERSIZE];\n\tdouble phase = 0;\n\n\tfor (double freq = 27.5; freq < 4187; freq *=\n\t\t\t1.0594630943592952645618252949463)\n\t{\n\t\tprintf(\"Freq: %f\\n\", freq);\n\t\tfor (int i = 0; i < 50; i++)\n\t\t{\n\t\t\tif ((err = snd_pcm_wait(this->pcm_handle, 1000)) < 0)\n\t\t\t{\n\t\t\t\tfprintf(stderr, \"poll failed (%s)\\n\", strerror(err));\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif ((nframes = snd_pcm_avail_update(this->pcm_handle)) < 0)\n\t\t\t{\n\t\t\t\tfprintf(stderr, \"unknown ALSA avail update return value (%d)\\n\",\n\t\t\t\t\t\tnframes);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (nframes > SOUNDBUFFERSIZE \/ 4)\n\t\t\t{\n\t\t\t\tnframes = SOUNDBUFFERSIZE \/ 4;\n\t\t\t}\n\t\t\tfor (int j = 0; j < nframes; j++)\n\t\t\t{\n\t\t\t\t((int*) sine)[j] = (int) (sin(phase) * INT_MAX);\n\n\t\t\t\tphase += (2 * M_PI \/ 44100.0) * freq;\n\n\t\t\t\tif (phase > M_PI * 2)\n\t\t\t\t{\n\t\t\t\t\tphase -= M_PI * 2;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif ((err = snd_pcm_writei(this->pcm_handle, sine, nframes)) < 0)\n\t\t\t{\n\t\t\t\tfprintf(stderr, \"write to audio interface failed (%s)\\n\",\n\t\t\t\t\t\tsnd_strerror(err));\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t}\n\n\tprintf(\"Stopping test playback!\\n\");\n}\n\nvoid Soundbuffer::fillbuffer(char* data, int size)\n{\n\tif ((size & (size - 1)) != 0)\n\t{\n\t\tstd::cerr << \"You need to fill the buffer with array sizes x^2\"\n\t\t\t\t<< std::endl;\n\t\treturn;\n\t}\n\tif (size >= SOUNDBUFFERSIZE)\n\t{\n\t\tstd::cerr << \"Too many samples. Might be at most \"\n\t\t\t\t<< SOUNDBUFFERSIZE \/ 2 << std::endl;\n\t\treturn;\n\t}\n\n\twhile (!this->canAcceptData(size))\n\t{\n\t\tusleep(100);\n\t}\n\n\tthis->mutex.lock();\n\tfor (int i = 0; i < size; i++)\n\t{\n\t\tthis->buffer[this->writeoffset] = data[i];\n\t\tthis->writeoffset++;\n\t\tif (this->writeoffset >= SOUNDBUFFERSIZE)\n\t\t{\n\t\t\tthis->writeoffset = 0;\n\t\t}\n\t}\n\tthis->mutex.unlock();\n\n}\n\nbool Soundbuffer::canAcceptData(int size)\n{\n\tint free;\n\n\tthis->mutex.lock();\n\tif (this->writeoffset > this->readoffset)\n\t{\n\t\tfree = this->readoffset + (SOUNDBUFFERSIZE - this->writeoffset);\n\t}\n\telse if (this->writeoffset < this->readoffset)\n\t{\n\t\tfree = this->readoffset - this->writeoffset;\n\t}\n\telse\n\t{\n\t\t\/\/write and readoffset equal ---> buffer is full\n\t\tfree = 0;\n\t}\n\tthis->mutex.unlock();\n\n\tif (free >= size)\n\t{\n\t\treturn true;\n\t}\n\telse\n\t{\n\t\treturn false;\n\t}\n}\n\nint Soundbuffer::getFrameSize()\n{\n\treturn 4;\n}\n<|endoftext|>"} {"text":"#include \"Router.h\"\n\n\/\/ Add a link id to the router's link vector\nvoid Router::addLink(std::string link_id) {\n links.push_back(link_id);\n}\n\n\/\/ Add a (host, link) pair indicating which link to route to given a host\nvoid Router::addRouting(std::string targ_host, std::string targ_link) {\n routing_table[targ_host] = targ_link;\n}\n\n\/\/ Return the proper link to route to given a host\nstd::string Router::getRouting(std::string targ_host) {\n \/\/ should probably do some error checking\n return routing_table[targ_host];\n}\n\n\/\/ Make new event with same packet going to proper link\nvoid Router::giveEvent(std::shared_ptr e) {\n \/\/ Get PacketEvent\n PacketEvent packet_event = *(std::static_pointer_cast(e));\n \n \/\/ strip necessary info out of packet event \n Packet pkt = packet_event.packet;\n std::string dest = getRouting(pkt.final_dest);\n \/\/ make new event\n auto new_event = std::make_shared(dest, this->getID(), packet_event.eventTime(), pkt);\n \/\/ put on event heap\n eventHeap.push(new_event);\n}\nshare everything#include \"Router.h\"\n\n\/\/ Add a link id to the router's link vector\nvoid Router::addLink(std::string link_id) {\n links.push_back(link_id);\n}\n\n\/\/ Add a (host, link) pair indicating which link to route to given a host\nvoid Router::addRouting(std::string targ_host, std::string targ_link) {\n routing_table[targ_host] = targ_link;\n}\n\n\/\/ Return the proper link to route to given a host\nstd::string Router::getRouting(std::string targ_host) {\n \/\/ should probably do some error checking\n return routing_table[targ_host];\n}\n\n\/\/ Make new event with same packet going to proper link\nvoid Router::giveEvent(std::shared_ptr e) {\n \/\/ Get PacketEvent\n PacketEvent packet_event = *(std::static_pointer_cast(e));\n \n \/\/ strip necessary info out of packet event \n std::shared_ptr pkt = packet_event.packet;\n std::string dest = getRouting(pkt->final_dest);\n \/\/ make new event\n auto new_event = std::make_shared(dest, this->getID(), packet_event.eventTime(), pkt);\n \/\/ put on event heap\n eventHeap.push(new_event);\n}\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: CategoryPositionHelper.cxx,v $\n *\n * $Revision: 1.4 $\n *\n * last change: $Author: vg $ $Date: 2007-05-22 19:15:43 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_chart2.hxx\"\n\n#ifndef _CHART2_CATEGORYPOSITIONHELPER_HXX\n#include \"CategoryPositionHelper.hxx\"\n#endif\n\n\/\/.............................................................................\nnamespace chart\n{\n\/\/.............................................................................\n\/\/using namespace ::com::sun::star;\n\/\/using namespace ::com::sun::star::chart2;\n\nCategoryPositionHelper::CategoryPositionHelper( double fSeriesCount, double fCategoryWidth )\n : m_fSeriesCount(fSeriesCount)\n , m_fCategoryWidth(fCategoryWidth)\n , m_fInnerDistance(0.0)\n , m_fOuterDistance(1.0)\n{\n}\n\nCategoryPositionHelper::CategoryPositionHelper( const CategoryPositionHelper& rSource )\n : m_fSeriesCount( rSource.m_fSeriesCount )\n , m_fCategoryWidth( rSource.m_fCategoryWidth )\n , m_fInnerDistance( rSource.m_fInnerDistance )\n , m_fOuterDistance( rSource.m_fOuterDistance )\n{\n}\n\nCategoryPositionHelper::CategoryPositionHelper()\n : m_fSeriesCount(1.0)\n , m_fCategoryWidth(1.0)\n , m_fInnerDistance(0.0)\n , m_fOuterDistance(0.0)\n{\n}\n\nCategoryPositionHelper::~CategoryPositionHelper()\n{\n}\n\ndouble CategoryPositionHelper::getSlotWidth() const\n{\n double fWidth = m_fCategoryWidth \/\n ( m_fSeriesCount\n + m_fOuterDistance\n + m_fInnerDistance*( m_fSeriesCount - 1.0) );\n return fWidth;\n}\n\ndouble CategoryPositionHelper::getSlotPos( double fCategoryX, double fSeriesNumber ) const\n{\n \/\/the returned position is in the middle of the rect\n \/\/fSeriesNumber 0...n-1\n double fPos = fCategoryX - (m_fCategoryWidth\/2.0)\n + (m_fOuterDistance\/2.0 + fSeriesNumber*(1.0+m_fInnerDistance)) * getSlotWidth()\n + getSlotWidth()\/2.0;\n\n return fPos;\n}\n\nvoid CategoryPositionHelper::setInnerDistance( double fInnerDistance )\n{\n if( fInnerDistance < -1.0 )\n fInnerDistance = -1.0;\n if( fInnerDistance > 1.0 )\n fInnerDistance = 1.0;\n m_fInnerDistance = fInnerDistance;\n}\n\nvoid CategoryPositionHelper::setOuterDistance( double fOuterDistance )\n{\n if( fOuterDistance < 0.0 )\n fOuterDistance = 0.0;\n if( fOuterDistance > 6.0 )\n fOuterDistance = 6.0;\n m_fOuterDistance = fOuterDistance;\n}\n\n\/\/.............................................................................\n} \/\/namespace chart\n\/\/.............................................................................\nINTEGRATION: CWS changefileheader (1.4.126); FILE MERGED 2008\/04\/01 10:50:40 thb 1.4.126.2: #i85898# Stripping all external header guards 2008\/03\/28 16:44:38 rt 1.4.126.1: #i87441# Change license header to LPGL v3.\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2008 by Sun Microsystems, Inc.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: CategoryPositionHelper.cxx,v $\n * $Revision: 1.5 $\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * \n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_chart2.hxx\"\n#include \"CategoryPositionHelper.hxx\"\n\n\/\/.............................................................................\nnamespace chart\n{\n\/\/.............................................................................\n\/\/using namespace ::com::sun::star;\n\/\/using namespace ::com::sun::star::chart2;\n\nCategoryPositionHelper::CategoryPositionHelper( double fSeriesCount, double fCategoryWidth )\n : m_fSeriesCount(fSeriesCount)\n , m_fCategoryWidth(fCategoryWidth)\n , m_fInnerDistance(0.0)\n , m_fOuterDistance(1.0)\n{\n}\n\nCategoryPositionHelper::CategoryPositionHelper( const CategoryPositionHelper& rSource )\n : m_fSeriesCount( rSource.m_fSeriesCount )\n , m_fCategoryWidth( rSource.m_fCategoryWidth )\n , m_fInnerDistance( rSource.m_fInnerDistance )\n , m_fOuterDistance( rSource.m_fOuterDistance )\n{\n}\n\nCategoryPositionHelper::CategoryPositionHelper()\n : m_fSeriesCount(1.0)\n , m_fCategoryWidth(1.0)\n , m_fInnerDistance(0.0)\n , m_fOuterDistance(0.0)\n{\n}\n\nCategoryPositionHelper::~CategoryPositionHelper()\n{\n}\n\ndouble CategoryPositionHelper::getSlotWidth() const\n{\n double fWidth = m_fCategoryWidth \/\n ( m_fSeriesCount\n + m_fOuterDistance\n + m_fInnerDistance*( m_fSeriesCount - 1.0) );\n return fWidth;\n}\n\ndouble CategoryPositionHelper::getSlotPos( double fCategoryX, double fSeriesNumber ) const\n{\n \/\/the returned position is in the middle of the rect\n \/\/fSeriesNumber 0...n-1\n double fPos = fCategoryX - (m_fCategoryWidth\/2.0)\n + (m_fOuterDistance\/2.0 + fSeriesNumber*(1.0+m_fInnerDistance)) * getSlotWidth()\n + getSlotWidth()\/2.0;\n\n return fPos;\n}\n\nvoid CategoryPositionHelper::setInnerDistance( double fInnerDistance )\n{\n if( fInnerDistance < -1.0 )\n fInnerDistance = -1.0;\n if( fInnerDistance > 1.0 )\n fInnerDistance = 1.0;\n m_fInnerDistance = fInnerDistance;\n}\n\nvoid CategoryPositionHelper::setOuterDistance( double fOuterDistance )\n{\n if( fOuterDistance < 0.0 )\n fOuterDistance = 0.0;\n if( fOuterDistance > 6.0 )\n fOuterDistance = 6.0;\n m_fOuterDistance = fOuterDistance;\n}\n\n\/\/.............................................................................\n} \/\/namespace chart\n\/\/.............................................................................\n<|endoftext|>"} {"text":"\/*\n * Main authors:\n * Kevin Leo \n * Andrea Rendl \n * Guido Tack \n *\/\n\n\/* This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/. *\/\n\n#include \n#include \n\nusing namespace Gecode;\n\nnamespace MiniZinc {\n\n\n FznSpace::FznSpace(bool share, FznSpace& f) : Space(share, f) {\n \/\/ integer variables\n iv.resize(f.iv.size());\n for(int i=0; i(&s)->iv[_optVarIdx].val());\n else if (_solveType == MiniZinc::SolveI::SolveType::ST_MAX)\n rel(*this, iv[_optVarIdx], IRT_GR,\n static_cast(&s)->iv[_optVarIdx].val());\n } else {\n#ifdef GECODE_HAS_FLOAT_VARS\n if (_solveType == MiniZinc::SolveI::SolveType::ST_MIN)\n rel(*this, fv[_optVarIdx], FRT_LE,\n static_cast(&s)->fv[_optVarIdx].val());\n else if (_solveType == MiniZinc::SolveI::SolveType::ST_MAX)\n rel(*this, fv[_optVarIdx], FRT_GR,\n static_cast(&s)->fv[_optVarIdx].val());\n#endif\n }\n }\n\n}\nGecode Solver: fzn_space copying: copy _solveType\/*\n * Main authors:\n * Kevin Leo \n * Andrea Rendl \n * Guido Tack \n *\/\n\n\/* This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/. *\/\n\n#include \n#include \n\nusing namespace Gecode;\n\nnamespace MiniZinc {\n\n\n FznSpace::FznSpace(bool share, FznSpace& f) : Space(share, f) {\n \/\/ integer variables\n iv.resize(f.iv.size());\n for(int i=0; i(&s)->iv[_optVarIdx].val());\n else if (_solveType == MiniZinc::SolveI::SolveType::ST_MAX)\n rel(*this, iv[_optVarIdx], IRT_GR,\n static_cast(&s)->iv[_optVarIdx].val());\n } else {\n#ifdef GECODE_HAS_FLOAT_VARS\n if (_solveType == MiniZinc::SolveI::SolveType::ST_MIN)\n rel(*this, fv[_optVarIdx], FRT_LE,\n static_cast(&s)->fv[_optVarIdx].val());\n else if (_solveType == MiniZinc::SolveI::SolveType::ST_MAX)\n rel(*this, fv[_optVarIdx], FRT_GR,\n static_cast(&s)->fv[_optVarIdx].val());\n#endif\n }\n }\n\n}\n<|endoftext|>"} {"text":"#include \n#include \n\nusing namespace std;\n\nint search(vector &a, int x) {\n \/\/ Preventing to call size function every iteration\n int m; \/\/ Index of middle element\n size_t n = a.size(); \/\/ Length of vector\n int l = 0, r = n - 1;\n\n while (l <= r) {\n m = l + (r - l) \/ 2;\n if (a[m] == x) {\n return m;\n }\n if (a[m] < x) {\n l = m + 1;\n } else {\n r = m - 1;\n }\n }\n return -1;\n}\n\nint main(){\n\n \/\/ Getting user input and declaring vars\n int x;\n cin >> x; \/\/ This will be our find value\n size_t n;\n cin >> n; \/\/ Given sorted array size\n vector a(n);\n\n for (size_t i = 0; i < n; i++)\n cin >> a[i];\n\n cout << \"Index is : \" << search(a, x) << endl;\n\n return 0;\n}\nupdated binary search suggested changes#include \n#include \n\nusing namespace std;\n\nint search(vector &a, int x) {\n\n size_t n = a.size();\n int l = 0;\n int r = n - 1;\n\n while (l <= r) {\n\n int m = l + (r - l) \/ 2;\n\n if (a[m] == x) {\n return m;\n }\n if (a[m] < x) {\n l = m + 1;\n } else {\n r = m - 1;\n }\n\n }\n return -1;\n}\n\nint main(){\n\n \/\/ Getting user input and declaring vars\n int x;\n cin >> x;\n size_t n;\n cin >> n;\n vector a(n);\n\n for (size_t i = 0; i < n; i++)\n cin >> a[i];\n\n cout << \"Index is : \" << search(a, x) << endl;\n\n return 0;\n}\n<|endoftext|>"} {"text":"Undo disabled toolstrip test, now that upstream bug is fixed.<|endoftext|>"} {"text":"Revert 40769 - Remove flaky label from RSS tests.<|endoftext|>"} {"text":"\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/browser.h\"\n#include \"chrome\/browser\/browser_list.h\"\n#include \"chrome\/browser\/browser_window.h\"\n#include \"chrome\/browser\/extensions\/browser_action_test_util.h\"\n#include \"chrome\/browser\/extensions\/extension_apitest.h\"\n#include \"chrome\/browser\/extensions\/extensions_service.h\"\n#include \"chrome\/browser\/extensions\/user_script_master.h\"\n#include \"chrome\/browser\/profile.h\"\n#include \"chrome\/browser\/tab_contents\/tab_contents.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/common\/url_constants.h\"\n#include \"chrome\/test\/ui_test_utils.h\"\n#include \"net\/base\/mock_host_resolver.h\"\n\nIN_PROC_BROWSER_TEST_F(ExtensionBrowserTest, IncognitoNoScript) {\n host_resolver()->AddRule(\"*\", \"127.0.0.1\");\n ASSERT_TRUE(test_server()->Start());\n\n \/\/ Loads a simple extension which attempts to change the title of every page\n \/\/ that loads to \"modified\".\n ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII(\"api_test\")\n .AppendASCII(\"incognito\").AppendASCII(\"content_scripts\")));\n\n \/\/ Open incognito window and navigate to test page.\n ui_test_utils::OpenURLOffTheRecord(browser()->profile(),\n GURL(\"http:\/\/www.example.com:1337\/files\/extensions\/test_file.html\"));\n Browser* otr_browser = BrowserList::FindBrowserWithType(\n browser()->profile()->GetOffTheRecordProfile(), Browser::TYPE_NORMAL,\n false);\n TabContents* tab = otr_browser->GetSelectedTabContents();\n\n \/\/ Verify the script didn't run.\n bool result = false;\n ui_test_utils::ExecuteJavaScriptAndExtractBool(\n tab->render_view_host(), L\"\",\n L\"window.domAutomationController.send(document.title == 'Unmodified')\",\n &result);\n EXPECT_TRUE(result);\n}\n\nIN_PROC_BROWSER_TEST_F(ExtensionBrowserTest, IncognitoYesScript) {\n host_resolver()->AddRule(\"*\", \"127.0.0.1\");\n ASSERT_TRUE(test_server()->Start());\n\n \/\/ Load a dummy extension. This just tests that we don't regress a\n \/\/ crash fix when multiple incognito- and non-incognito-enabled extensions\n \/\/ are mixed.\n ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII(\"api_test\")\n .AppendASCII(\"content_scripts\").AppendASCII(\"all_frames\")));\n\n \/\/ Loads a simple extension which attempts to change the title of every page\n \/\/ that loads to \"modified\".\n ASSERT_TRUE(LoadExtensionIncognito(test_data_dir_.AppendASCII(\"api_test\")\n .AppendASCII(\"incognito\").AppendASCII(\"content_scripts\")));\n\n \/\/ Dummy extension #2.\n ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII(\"api_test\")\n .AppendASCII(\"content_scripts\").AppendASCII(\"isolated_world1\")));\n\n \/\/ Open incognito window and navigate to test page.\n ui_test_utils::OpenURLOffTheRecord(browser()->profile(),\n GURL(\"http:\/\/www.example.com:1337\/files\/extensions\/test_file.html\"));\n Browser* otr_browser = BrowserList::FindBrowserWithType(\n browser()->profile()->GetOffTheRecordProfile(), Browser::TYPE_NORMAL,\n false);\n TabContents* tab = otr_browser->GetSelectedTabContents();\n\n \/\/ Verify the script ran.\n bool result = false;\n ui_test_utils::ExecuteJavaScriptAndExtractBool(\n tab->render_view_host(), L\"\",\n L\"window.domAutomationController.send(document.title == 'modified')\",\n &result);\n EXPECT_TRUE(result);\n}\n\n\/\/ Tests that the APIs in an incognito-enabled extension work properly.\nIN_PROC_BROWSER_TEST_F(ExtensionApiTest, Incognito) {\n host_resolver()->AddRule(\"*\", \"127.0.0.1\");\n ASSERT_TRUE(test_server()->Start());\n\n ResultCatcher catcher;\n\n \/\/ Open incognito window and navigate to test page.\n ui_test_utils::OpenURLOffTheRecord(browser()->profile(),\n GURL(\"http:\/\/www.example.com:1337\/files\/extensions\/test_file.html\"));\n\n ASSERT_TRUE(LoadExtensionIncognito(test_data_dir_\n .AppendASCII(\"incognito\").AppendASCII(\"apis\")));\n\n EXPECT_TRUE(catcher.GetNextResult()) << catcher.message();\n}\n\n\/\/ Tests that the APIs in an incognito-enabled split-mode extension work\n\/\/ properly.\n#if defined(OS_CHROMEOS) || defined(OS_LINUX)\n\/\/ Hanging on ChromeOS and linux: http:\/\/crbug.com\/53991\n#define MAYBE_IncognitoSplitMode DISABLED_IncognitoSplitMode\n#else\n#define MAYBE_IncognitoSplitMode IncognitoSplitMode\n#endif\nIN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_IncognitoSplitMode) {\n host_resolver()->AddRule(\"*\", \"127.0.0.1\");\n ASSERT_TRUE(test_server()->Start());\n\n \/\/ We need 2 ResultCatchers because we'll be running the same test in both\n \/\/ regular and incognito mode.\n ResultCatcher catcher;\n catcher.RestrictToProfile(browser()->profile());\n ResultCatcher catcher_incognito;\n catcher_incognito.RestrictToProfile(\n browser()->profile()->GetOffTheRecordProfile());\n\n \/\/ Open incognito window and navigate to test page.\n ui_test_utils::OpenURLOffTheRecord(browser()->profile(),\n GURL(\"http:\/\/www.example.com:1337\/files\/extensions\/test_file.html\"));\n\n ASSERT_TRUE(LoadExtensionIncognito(test_data_dir_\n .AppendASCII(\"incognito\").AppendASCII(\"split\")));\n\n EXPECT_TRUE(catcher.GetNextResult()) << catcher.message();\n EXPECT_TRUE(catcher_incognito.GetNextResult()) << catcher.message();\n}\n\n\/\/ Tests that the APIs in an incognito-disabled extension don't see incognito\n\/\/ events or callbacks.\n\/\/ Hangy, http:\/\/crbug.com\/53869.\nIN_PROC_BROWSER_TEST_F(ExtensionApiTest, DISABLED_IncognitoDisabled) {\n host_resolver()->AddRule(\"*\", \"127.0.0.1\");\n ASSERT_TRUE(test_server()->Start());\n\n ResultCatcher catcher;\n\n \/\/ Open incognito window and navigate to test page.\n ui_test_utils::OpenURLOffTheRecord(browser()->profile(),\n GURL(\"http:\/\/www.example.com:1337\/files\/extensions\/test_file.html\"));\n\n ASSERT_TRUE(LoadExtension(test_data_dir_\n .AppendASCII(\"incognito\").AppendASCII(\"apis_disabled\")));\n\n EXPECT_TRUE(catcher.GetNextResult()) << catcher.message();\n}\n\n\/\/ Test that opening a popup from an incognito browser window works properly.\nIN_PROC_BROWSER_TEST_F(ExtensionApiTest, IncognitoPopup) {\n host_resolver()->AddRule(\"*\", \"127.0.0.1\");\n ASSERT_TRUE(test_server()->Start());\n\n ResultCatcher catcher;\n\n ASSERT_TRUE(LoadExtensionIncognito(test_data_dir_\n .AppendASCII(\"incognito\").AppendASCII(\"popup\")));\n\n \/\/ Open incognito window and navigate to test page.\n ui_test_utils::OpenURLOffTheRecord(browser()->profile(),\n GURL(\"http:\/\/www.example.com:1337\/files\/extensions\/test_file.html\"));\n Browser* incognito_browser = BrowserList::FindBrowserWithType(\n browser()->profile()->GetOffTheRecordProfile(), Browser::TYPE_NORMAL,\n false);\n\n \/\/ Simulate the incognito's browser action being clicked.\n BrowserActionTestUtil(incognito_browser).Press(0);\n\n EXPECT_TRUE(catcher.GetNextResult()) << catcher.message();\n}\nDisable IncognitoSplitMode everywhere, it's failing and hangy. Working on a fix.\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/browser.h\"\n#include \"chrome\/browser\/browser_list.h\"\n#include \"chrome\/browser\/browser_window.h\"\n#include \"chrome\/browser\/extensions\/browser_action_test_util.h\"\n#include \"chrome\/browser\/extensions\/extension_apitest.h\"\n#include \"chrome\/browser\/extensions\/extensions_service.h\"\n#include \"chrome\/browser\/extensions\/user_script_master.h\"\n#include \"chrome\/browser\/profile.h\"\n#include \"chrome\/browser\/tab_contents\/tab_contents.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/common\/url_constants.h\"\n#include \"chrome\/test\/ui_test_utils.h\"\n#include \"net\/base\/mock_host_resolver.h\"\n\nIN_PROC_BROWSER_TEST_F(ExtensionBrowserTest, IncognitoNoScript) {\n host_resolver()->AddRule(\"*\", \"127.0.0.1\");\n ASSERT_TRUE(test_server()->Start());\n\n \/\/ Loads a simple extension which attempts to change the title of every page\n \/\/ that loads to \"modified\".\n ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII(\"api_test\")\n .AppendASCII(\"incognito\").AppendASCII(\"content_scripts\")));\n\n \/\/ Open incognito window and navigate to test page.\n ui_test_utils::OpenURLOffTheRecord(browser()->profile(),\n GURL(\"http:\/\/www.example.com:1337\/files\/extensions\/test_file.html\"));\n Browser* otr_browser = BrowserList::FindBrowserWithType(\n browser()->profile()->GetOffTheRecordProfile(), Browser::TYPE_NORMAL,\n false);\n TabContents* tab = otr_browser->GetSelectedTabContents();\n\n \/\/ Verify the script didn't run.\n bool result = false;\n ui_test_utils::ExecuteJavaScriptAndExtractBool(\n tab->render_view_host(), L\"\",\n L\"window.domAutomationController.send(document.title == 'Unmodified')\",\n &result);\n EXPECT_TRUE(result);\n}\n\nIN_PROC_BROWSER_TEST_F(ExtensionBrowserTest, IncognitoYesScript) {\n host_resolver()->AddRule(\"*\", \"127.0.0.1\");\n ASSERT_TRUE(test_server()->Start());\n\n \/\/ Load a dummy extension. This just tests that we don't regress a\n \/\/ crash fix when multiple incognito- and non-incognito-enabled extensions\n \/\/ are mixed.\n ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII(\"api_test\")\n .AppendASCII(\"content_scripts\").AppendASCII(\"all_frames\")));\n\n \/\/ Loads a simple extension which attempts to change the title of every page\n \/\/ that loads to \"modified\".\n ASSERT_TRUE(LoadExtensionIncognito(test_data_dir_.AppendASCII(\"api_test\")\n .AppendASCII(\"incognito\").AppendASCII(\"content_scripts\")));\n\n \/\/ Dummy extension #2.\n ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII(\"api_test\")\n .AppendASCII(\"content_scripts\").AppendASCII(\"isolated_world1\")));\n\n \/\/ Open incognito window and navigate to test page.\n ui_test_utils::OpenURLOffTheRecord(browser()->profile(),\n GURL(\"http:\/\/www.example.com:1337\/files\/extensions\/test_file.html\"));\n Browser* otr_browser = BrowserList::FindBrowserWithType(\n browser()->profile()->GetOffTheRecordProfile(), Browser::TYPE_NORMAL,\n false);\n TabContents* tab = otr_browser->GetSelectedTabContents();\n\n \/\/ Verify the script ran.\n bool result = false;\n ui_test_utils::ExecuteJavaScriptAndExtractBool(\n tab->render_view_host(), L\"\",\n L\"window.domAutomationController.send(document.title == 'modified')\",\n &result);\n EXPECT_TRUE(result);\n}\n\n\/\/ Tests that the APIs in an incognito-enabled extension work properly.\nIN_PROC_BROWSER_TEST_F(ExtensionApiTest, Incognito) {\n host_resolver()->AddRule(\"*\", \"127.0.0.1\");\n ASSERT_TRUE(test_server()->Start());\n\n ResultCatcher catcher;\n\n \/\/ Open incognito window and navigate to test page.\n ui_test_utils::OpenURLOffTheRecord(browser()->profile(),\n GURL(\"http:\/\/www.example.com:1337\/files\/extensions\/test_file.html\"));\n\n ASSERT_TRUE(LoadExtensionIncognito(test_data_dir_\n .AppendASCII(\"incognito\").AppendASCII(\"apis\")));\n\n EXPECT_TRUE(catcher.GetNextResult()) << catcher.message();\n}\n\n\/\/ Tests that the APIs in an incognito-enabled split-mode extension work\n\/\/ properly.\n\/\/ Hanging\/failing: http:\/\/crbug.com\/53991\nIN_PROC_BROWSER_TEST_F(ExtensionApiTest, DISABLED_IncognitoSplitMode) {\n host_resolver()->AddRule(\"*\", \"127.0.0.1\");\n ASSERT_TRUE(test_server()->Start());\n\n \/\/ We need 2 ResultCatchers because we'll be running the same test in both\n \/\/ regular and incognito mode.\n ResultCatcher catcher;\n catcher.RestrictToProfile(browser()->profile());\n ResultCatcher catcher_incognito;\n catcher_incognito.RestrictToProfile(\n browser()->profile()->GetOffTheRecordProfile());\n\n \/\/ Open incognito window and navigate to test page.\n ui_test_utils::OpenURLOffTheRecord(browser()->profile(),\n GURL(\"http:\/\/www.example.com:1337\/files\/extensions\/test_file.html\"));\n\n ASSERT_TRUE(LoadExtensionIncognito(test_data_dir_\n .AppendASCII(\"incognito\").AppendASCII(\"split\")));\n\n EXPECT_TRUE(catcher.GetNextResult()) << catcher.message();\n EXPECT_TRUE(catcher_incognito.GetNextResult()) << catcher.message();\n}\n\n\/\/ Tests that the APIs in an incognito-disabled extension don't see incognito\n\/\/ events or callbacks.\n\/\/ Hangy, http:\/\/crbug.com\/53869.\nIN_PROC_BROWSER_TEST_F(ExtensionApiTest, DISABLED_IncognitoDisabled) {\n host_resolver()->AddRule(\"*\", \"127.0.0.1\");\n ASSERT_TRUE(test_server()->Start());\n\n ResultCatcher catcher;\n\n \/\/ Open incognito window and navigate to test page.\n ui_test_utils::OpenURLOffTheRecord(browser()->profile(),\n GURL(\"http:\/\/www.example.com:1337\/files\/extensions\/test_file.html\"));\n\n ASSERT_TRUE(LoadExtension(test_data_dir_\n .AppendASCII(\"incognito\").AppendASCII(\"apis_disabled\")));\n\n EXPECT_TRUE(catcher.GetNextResult()) << catcher.message();\n}\n\n\/\/ Test that opening a popup from an incognito browser window works properly.\nIN_PROC_BROWSER_TEST_F(ExtensionApiTest, IncognitoPopup) {\n host_resolver()->AddRule(\"*\", \"127.0.0.1\");\n ASSERT_TRUE(test_server()->Start());\n\n ResultCatcher catcher;\n\n ASSERT_TRUE(LoadExtensionIncognito(test_data_dir_\n .AppendASCII(\"incognito\").AppendASCII(\"popup\")));\n\n \/\/ Open incognito window and navigate to test page.\n ui_test_utils::OpenURLOffTheRecord(browser()->profile(),\n GURL(\"http:\/\/www.example.com:1337\/files\/extensions\/test_file.html\"));\n Browser* incognito_browser = BrowserList::FindBrowserWithType(\n browser()->profile()->GetOffTheRecordProfile(), Browser::TYPE_NORMAL,\n false);\n\n \/\/ Simulate the incognito's browser action being clicked.\n BrowserActionTestUtil(incognito_browser).Press(0);\n\n EXPECT_TRUE(catcher.GetNextResult()) << catcher.message();\n}\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2008-2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"base\/nss_util.h\"\n#include \"base\/nss_util_internal.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"base\/file_util.h\"\n#include \"base\/logging.h\"\n#include \"base\/singleton.h\"\n#include \"base\/string_util.h\"\n\n#if defined(USE_NSS)\n#include \"base\/lock.h\"\n#include \"base\/scoped_ptr.h\"\n#endif \/\/ defined(USE_NSS)\n\n\/\/ On some platforms, we use NSS for SSL only -- we don't use NSS for crypto\n\/\/ or certificate verification, and we don't use the NSS certificate and key\n\/\/ databases.\n#if defined(OS_MACOSX) || defined(OS_WIN)\n#define USE_NSS_FOR_SSL_ONLY 1\n#endif\n\nnamespace {\n\n#if !defined(USE_NSS_FOR_SSL_ONLY)\nstd::string GetDefaultConfigDirectory() {\n FilePath home = file_util::GetHomeDir();\n if (home.empty()) {\n LOG(ERROR) << \"$HOME is not set.\";\n return std::string();\n }\n FilePath dir(home);\n dir = dir.AppendASCII(\".pki\").AppendASCII(\"nssdb\");\n if (!file_util::CreateDirectory(dir)) {\n LOG(ERROR) << \"Failed to create ~\/.pki\/nssdb directory.\";\n return std::string();\n }\n return dir.value();\n}\n\n\/\/ On non-chromeos platforms, return the default config directory.\n\/\/ On chromeos, return a read-only directory with fake root CA certs for testing\n\/\/ (which will not exist on non-testing images). These root CA certs are used\n\/\/ by the local Google Accounts server mock we use when testing our login code.\n\/\/ If this directory is not present, NSS_Init() will fail. It is up to the\n\/\/ caller to failover to NSS_NoDB_Init() at that point.\nstd::string GetInitialConfigDirectory() {\n#if defined(OS_CHROMEOS)\n static const char kReadOnlyCertDB[] = \"\/etc\/fake_root_ca\/nssdb\";\n return std::string(kReadOnlyCertDB);\n#else\n return GetDefaultConfigDirectory();\n#endif \/\/ defined(OS_CHROMEOS)\n}\n\n\/\/ Load nss's built-in root certs.\nSECMODModule *InitDefaultRootCerts() {\n const char* kModulePath = \"libnssckbi.so\";\n char modparams[1024];\n snprintf(modparams, sizeof(modparams),\n \"name=\\\"Root Certs\\\" library=\\\"%s\\\"\", kModulePath);\n SECMODModule *root = SECMOD_LoadUserModule(modparams, NULL, PR_FALSE);\n if (root)\n return root;\n\n \/\/ Aw, snap. Can't find\/load root cert shared library.\n \/\/ This will make it hard to talk to anybody via https.\n NOTREACHED();\n return NULL;\n}\n#endif \/\/ !defined(USE_NSS_FOR_SSL_ONLY)\n\n\/\/ A singleton to initialize\/deinitialize NSPR.\n\/\/ Separate from the NSS singleton because we initialize NSPR on the UI thread.\nclass NSPRInitSingleton {\n public:\n NSPRInitSingleton() {\n PR_Init(PR_USER_THREAD, PR_PRIORITY_NORMAL, 0);\n }\n\n ~NSPRInitSingleton() {\n PL_ArenaFinish();\n PRStatus prstatus = PR_Cleanup();\n if (prstatus != PR_SUCCESS) {\n LOG(ERROR) << \"PR_Cleanup failed; was NSPR initialized on wrong thread?\";\n }\n }\n};\n\nclass NSSInitSingleton {\n public:\n NSSInitSingleton()\n : real_db_slot_(NULL),\n root_(NULL),\n chromeos_user_logged_in_(false) {\n base::EnsureNSPRInit();\n\n \/\/ We *must* have NSS >= 3.12.3. See bug 26448.\n COMPILE_ASSERT(\n (NSS_VMAJOR == 3 && NSS_VMINOR == 12 && NSS_VPATCH >= 3) ||\n (NSS_VMAJOR == 3 && NSS_VMINOR > 12) ||\n (NSS_VMAJOR > 3),\n nss_version_check_failed);\n \/\/ Also check the run-time NSS version.\n \/\/ NSS_VersionCheck is a >= check, not strict equality.\n if (!NSS_VersionCheck(\"3.12.3\")) {\n \/\/ It turns out many people have misconfigured NSS setups, where\n \/\/ their run-time NSPR doesn't match the one their NSS was compiled\n \/\/ against. So rather than aborting, complain loudly.\n LOG(ERROR) << \"NSS_VersionCheck(\\\"3.12.3\\\") failed. \"\n \"We depend on NSS >= 3.12.3, and this error is not fatal \"\n \"only because many people have busted NSS setups (for \"\n \"example, using the wrong version of NSPR). \"\n \"Please upgrade to the latest NSS and NSPR, and if you \"\n \"still get this error, contact your distribution \"\n \"maintainer.\";\n }\n\n SECStatus status = SECFailure;\n#if defined(USE_NSS_FOR_SSL_ONLY)\n \/\/ Use the system certificate store, so initialize NSS without database.\n status = NSS_NoDB_Init(NULL);\n if (status != SECSuccess) {\n LOG(ERROR) << \"Error initializing NSS without a persistent \"\n \"database: NSS error code \" << PR_GetError();\n }\n#else\n std::string database_dir = GetInitialConfigDirectory();\n if (!database_dir.empty()) {\n \/\/ Initialize with a persistent database (likely, ~\/.pki\/nssdb).\n \/\/ Use \"sql:\" which can be shared by multiple processes safely.\n std::string nss_config_dir =\n StringPrintf(\"sql:%s\", database_dir.c_str());\n#if defined(OS_CHROMEOS)\n status = NSS_Init(nss_config_dir.c_str());\n#else\n status = NSS_InitReadWrite(nss_config_dir.c_str());\n#endif\n if (status != SECSuccess) {\n LOG(ERROR) << \"Error initializing NSS with a persistent \"\n \"database (\" << nss_config_dir\n << \"): NSS error code \" << PR_GetError();\n }\n }\n if (status != SECSuccess) {\n LOG(WARNING) << \"Initialize NSS without a persistent database \"\n \"(~\/.pki\/nssdb).\";\n status = NSS_NoDB_Init(NULL);\n if (status != SECSuccess) {\n LOG(ERROR) << \"Error initializing NSS without a persistent \"\n \"database: NSS error code \" << PR_GetError();\n return;\n }\n }\n\n \/\/ If we haven't initialized the password for the NSS databases,\n \/\/ initialize an empty-string password so that we don't need to\n \/\/ log in.\n PK11SlotInfo* slot = PK11_GetInternalKeySlot();\n if (slot) {\n \/\/ PK11_InitPin may write to the keyDB, but no other thread can use NSS\n \/\/ yet, so we don't need to lock.\n if (PK11_NeedUserInit(slot))\n PK11_InitPin(slot, NULL, NULL);\n PK11_FreeSlot(slot);\n }\n\n \/\/ TODO(davidben): When https:\/\/bugzilla.mozilla.org\/show_bug.cgi?id=564011\n \/\/ is fixed, we will no longer need the lock. We should detect this and not\n \/\/ initialize a Lock here.\n write_lock_.reset(new Lock());\n\n root_ = InitDefaultRootCerts();\n#endif \/\/ defined(USE_NSS_FOR_SSL_ONLY)\n }\n\n ~NSSInitSingleton() {\n if (real_db_slot_) {\n SECMOD_CloseUserDB(real_db_slot_);\n PK11_FreeSlot(real_db_slot_);\n real_db_slot_ = NULL;\n }\n if (root_) {\n SECMOD_UnloadUserModule(root_);\n SECMOD_DestroyModule(root_);\n root_ = NULL;\n }\n\n SECStatus status = NSS_Shutdown();\n if (status != SECSuccess) {\n \/\/ We LOG(INFO) because this failure is relatively harmless\n \/\/ (leaking, but we're shutting down anyway).\n LOG(INFO) << \"NSS_Shutdown failed; see \"\n \"http:\/\/code.google.com\/p\/chromium\/issues\/detail?id=4609\";\n }\n }\n\n#if defined(OS_CHROMEOS)\n void OpenPersistentNSSDB() {\n if (!chromeos_user_logged_in_) {\n chromeos_user_logged_in_ = true;\n\n const std::string modspec =\n StringPrintf(\"configDir='%s' tokenDescription='Real NSS database'\",\n GetDefaultConfigDirectory().c_str());\n real_db_slot_ = SECMOD_OpenUserDB(modspec.c_str());\n if (real_db_slot_ == NULL) {\n LOG(ERROR) << \"Error opening persistent database (\" << modspec\n << \"): NSS error code \" << PR_GetError();\n } else {\n if (PK11_NeedUserInit(real_db_slot_))\n PK11_InitPin(real_db_slot_, NULL, NULL);\n }\n }\n }\n#endif \/\/ defined(OS_CHROMEOS)\n\n PK11SlotInfo* GetDefaultKeySlot() {\n if (real_db_slot_)\n return PK11_ReferenceSlot(real_db_slot_);\n return PK11_GetInternalKeySlot();\n }\n\n#if defined(USE_NSS)\n Lock* write_lock() {\n return write_lock_.get();\n }\n#endif \/\/ defined(USE_NSS)\n\n private:\n PK11SlotInfo* real_db_slot_; \/\/ Overrides internal key slot if non-NULL.\n SECMODModule *root_;\n bool chromeos_user_logged_in_;\n#if defined(USE_NSS)\n scoped_ptr write_lock_;\n#endif \/\/ defined(USE_NSS)\n};\n\n} \/\/ namespace\n\nnamespace base {\n\nvoid EnsureNSPRInit() {\n Singleton::get();\n}\n\nvoid EnsureNSSInit() {\n Singleton::get();\n}\n\n#if defined(USE_NSS)\nLock* GetNSSWriteLock() {\n return Singleton::get()->write_lock();\n}\n\nAutoNSSWriteLock::AutoNSSWriteLock() : lock_(GetNSSWriteLock()) {\n \/\/ May be NULL if the lock is not needed in our version of NSS.\n if (lock_)\n lock_->Acquire();\n}\n\nAutoNSSWriteLock::~AutoNSSWriteLock() {\n if (lock_) {\n lock_->AssertAcquired();\n lock_->Release();\n }\n}\n#endif \/\/ defined(USE_NSS)\n\n#if defined(OS_CHROMEOS)\nvoid OpenPersistentNSSDB() {\n Singleton::get()->OpenPersistentNSSDB();\n}\n#endif\n\n\/\/ TODO(port): Implement this more simply. We can convert by subtracting an\n\/\/ offset (the difference between NSPR's and base::Time's epochs).\nTime PRTimeToBaseTime(PRTime prtime) {\n PRExplodedTime prxtime;\n PR_ExplodeTime(prtime, PR_GMTParameters, &prxtime);\n\n base::Time::Exploded exploded;\n exploded.year = prxtime.tm_year;\n exploded.month = prxtime.tm_month + 1;\n exploded.day_of_week = prxtime.tm_wday;\n exploded.day_of_month = prxtime.tm_mday;\n exploded.hour = prxtime.tm_hour;\n exploded.minute = prxtime.tm_min;\n exploded.second = prxtime.tm_sec;\n exploded.millisecond = prxtime.tm_usec \/ 1000;\n\n return Time::FromUTCExploded(exploded);\n}\n\nPK11SlotInfo* GetDefaultNSSKeySlot() {\n return Singleton::get()->GetDefaultKeySlot();\n}\n\n} \/\/ namespace base\nNSS's filesystem speed detection doesn't work with the latest versions of sqlite, such as 3.6.22. Set the NSS_SDB_USE_CACHE environment variable to \"yes\" to override NSS's detection if the database is on NFS.\/\/ Copyright (c) 2008-2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"base\/nss_util.h\"\n#include \"base\/nss_util_internal.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#if defined(OS_LINUX)\n#include \n#include \n#endif\n\n#include \"base\/file_util.h\"\n#include \"base\/logging.h\"\n#include \"base\/singleton.h\"\n#include \"base\/string_util.h\"\n\n\/\/ USE_NSS means we use NSS for everything crypto-related. If USE_NSS is not\n\/\/ defined, such as on Mac and Windows, we use NSS for SSL only -- we don't\n\/\/ use NSS for crypto or certificate verification, and we don't use the NSS\n\/\/ certificate and key databases.\n#if defined(USE_NSS)\n#include \"base\/env_var.h\"\n#include \"base\/lock.h\"\n#include \"base\/scoped_ptr.h\"\n#endif \/\/ defined(USE_NSS)\n\nnamespace {\n\n#if defined(USE_NSS)\nFilePath GetDefaultConfigDirectory() {\n FilePath dir = file_util::GetHomeDir();\n if (dir.empty()) {\n LOG(ERROR) << \"Failed to get home directory.\";\n return dir;\n }\n dir = dir.AppendASCII(\".pki\").AppendASCII(\"nssdb\");\n if (!file_util::CreateDirectory(dir)) {\n LOG(ERROR) << \"Failed to create ~\/.pki\/nssdb directory.\";\n dir.clear();\n }\n return dir;\n}\n\n\/\/ On non-chromeos platforms, return the default config directory.\n\/\/ On chromeos, return a read-only directory with fake root CA certs for testing\n\/\/ (which will not exist on non-testing images). These root CA certs are used\n\/\/ by the local Google Accounts server mock we use when testing our login code.\n\/\/ If this directory is not present, NSS_Init() will fail. It is up to the\n\/\/ caller to failover to NSS_NoDB_Init() at that point.\nFilePath GetInitialConfigDirectory() {\n#if defined(OS_CHROMEOS)\n static const FilePath::CharType kReadOnlyCertDB[] =\n FILE_PATH_LITERAL(\"\/etc\/fake_root_ca\/nssdb\");\n return FilePath(kReadOnlyCertDB);\n#else\n return GetDefaultConfigDirectory();\n#endif \/\/ defined(OS_CHROMEOS)\n}\n\n\/\/ NSS creates a local cache of the sqlite database if it detects that the\n\/\/ filesystem the database is on is much slower than the local disk. The\n\/\/ detection doesn't work with the latest versions of sqlite, such as 3.6.22\n\/\/ (NSS bug https:\/\/bugzilla.mozilla.org\/show_bug.cgi?id=578561). So we set\n\/\/ the NSS environment variable NSS_SDB_USE_CACHE to \"yes\" to override NSS's\n\/\/ detection when database_dir is on NFS. See http:\/\/crbug.com\/48585.\n\/\/\n\/\/ TODO(wtc): port this function to other USE_NSS platforms. It is defined\n\/\/ only for OS_LINUX simply because the statfs structure is OS-specific.\nvoid UseLocalCacheOfNSSDatabaseIfNFS(const FilePath& database_dir) {\n#if defined(OS_LINUX)\n struct statfs buf;\n if (statfs(database_dir.value().c_str(), &buf) == 0) {\n if (buf.f_type == NFS_SUPER_MAGIC) {\n scoped_ptr env(base::EnvVarGetter::Create());\n const char* use_cache_env_var = \"NSS_SDB_USE_CACHE\";\n if (!env->HasEnv(use_cache_env_var))\n env->SetEnv(use_cache_env_var, \"yes\");\n }\n }\n#endif \/\/ defined(OS_LINUX)\n}\n\n\/\/ Load nss's built-in root certs.\nSECMODModule *InitDefaultRootCerts() {\n const char* kModulePath = \"libnssckbi.so\";\n char modparams[1024];\n snprintf(modparams, sizeof(modparams),\n \"name=\\\"Root Certs\\\" library=\\\"%s\\\"\", kModulePath);\n SECMODModule *root = SECMOD_LoadUserModule(modparams, NULL, PR_FALSE);\n if (root)\n return root;\n\n \/\/ Aw, snap. Can't find\/load root cert shared library.\n \/\/ This will make it hard to talk to anybody via https.\n NOTREACHED();\n return NULL;\n}\n#endif \/\/ defined(USE_NSS)\n\n\/\/ A singleton to initialize\/deinitialize NSPR.\n\/\/ Separate from the NSS singleton because we initialize NSPR on the UI thread.\nclass NSPRInitSingleton {\n public:\n NSPRInitSingleton() {\n PR_Init(PR_USER_THREAD, PR_PRIORITY_NORMAL, 0);\n }\n\n ~NSPRInitSingleton() {\n PL_ArenaFinish();\n PRStatus prstatus = PR_Cleanup();\n if (prstatus != PR_SUCCESS) {\n LOG(ERROR) << \"PR_Cleanup failed; was NSPR initialized on wrong thread?\";\n }\n }\n};\n\nclass NSSInitSingleton {\n public:\n NSSInitSingleton()\n : real_db_slot_(NULL),\n root_(NULL),\n chromeos_user_logged_in_(false) {\n base::EnsureNSPRInit();\n\n \/\/ We *must* have NSS >= 3.12.3. See bug 26448.\n COMPILE_ASSERT(\n (NSS_VMAJOR == 3 && NSS_VMINOR == 12 && NSS_VPATCH >= 3) ||\n (NSS_VMAJOR == 3 && NSS_VMINOR > 12) ||\n (NSS_VMAJOR > 3),\n nss_version_check_failed);\n \/\/ Also check the run-time NSS version.\n \/\/ NSS_VersionCheck is a >= check, not strict equality.\n if (!NSS_VersionCheck(\"3.12.3\")) {\n \/\/ It turns out many people have misconfigured NSS setups, where\n \/\/ their run-time NSPR doesn't match the one their NSS was compiled\n \/\/ against. So rather than aborting, complain loudly.\n LOG(ERROR) << \"NSS_VersionCheck(\\\"3.12.3\\\") failed. \"\n \"We depend on NSS >= 3.12.3, and this error is not fatal \"\n \"only because many people have busted NSS setups (for \"\n \"example, using the wrong version of NSPR). \"\n \"Please upgrade to the latest NSS and NSPR, and if you \"\n \"still get this error, contact your distribution \"\n \"maintainer.\";\n }\n\n SECStatus status = SECFailure;\n#if !defined(USE_NSS)\n \/\/ Use the system certificate store, so initialize NSS without database.\n status = NSS_NoDB_Init(NULL);\n if (status != SECSuccess) {\n LOG(ERROR) << \"Error initializing NSS without a persistent \"\n \"database: NSS error code \" << PR_GetError();\n }\n#else\n FilePath database_dir = GetInitialConfigDirectory();\n if (!database_dir.empty()) {\n UseLocalCacheOfNSSDatabaseIfNFS(database_dir);\n\n \/\/ Initialize with a persistent database (likely, ~\/.pki\/nssdb).\n \/\/ Use \"sql:\" which can be shared by multiple processes safely.\n std::string nss_config_dir =\n StringPrintf(\"sql:%s\", database_dir.value().c_str());\n#if defined(OS_CHROMEOS)\n status = NSS_Init(nss_config_dir.c_str());\n#else\n status = NSS_InitReadWrite(nss_config_dir.c_str());\n#endif\n if (status != SECSuccess) {\n LOG(ERROR) << \"Error initializing NSS with a persistent \"\n \"database (\" << nss_config_dir\n << \"): NSS error code \" << PR_GetError();\n }\n }\n if (status != SECSuccess) {\n LOG(WARNING) << \"Initialize NSS without a persistent database \"\n \"(~\/.pki\/nssdb).\";\n status = NSS_NoDB_Init(NULL);\n if (status != SECSuccess) {\n LOG(ERROR) << \"Error initializing NSS without a persistent \"\n \"database: NSS error code \" << PR_GetError();\n return;\n }\n }\n\n \/\/ If we haven't initialized the password for the NSS databases,\n \/\/ initialize an empty-string password so that we don't need to\n \/\/ log in.\n PK11SlotInfo* slot = PK11_GetInternalKeySlot();\n if (slot) {\n \/\/ PK11_InitPin may write to the keyDB, but no other thread can use NSS\n \/\/ yet, so we don't need to lock.\n if (PK11_NeedUserInit(slot))\n PK11_InitPin(slot, NULL, NULL);\n PK11_FreeSlot(slot);\n }\n\n \/\/ TODO(davidben): When https:\/\/bugzilla.mozilla.org\/show_bug.cgi?id=564011\n \/\/ is fixed, we will no longer need the lock. We should detect this and not\n \/\/ initialize a Lock here.\n write_lock_.reset(new Lock());\n\n root_ = InitDefaultRootCerts();\n#endif \/\/ !defined(USE_NSS)\n }\n\n ~NSSInitSingleton() {\n if (real_db_slot_) {\n SECMOD_CloseUserDB(real_db_slot_);\n PK11_FreeSlot(real_db_slot_);\n real_db_slot_ = NULL;\n }\n if (root_) {\n SECMOD_UnloadUserModule(root_);\n SECMOD_DestroyModule(root_);\n root_ = NULL;\n }\n\n SECStatus status = NSS_Shutdown();\n if (status != SECSuccess) {\n \/\/ We LOG(INFO) because this failure is relatively harmless\n \/\/ (leaking, but we're shutting down anyway).\n LOG(INFO) << \"NSS_Shutdown failed; see \"\n \"http:\/\/code.google.com\/p\/chromium\/issues\/detail?id=4609\";\n }\n }\n\n#if defined(OS_CHROMEOS)\n void OpenPersistentNSSDB() {\n if (!chromeos_user_logged_in_) {\n chromeos_user_logged_in_ = true;\n\n const std::string modspec =\n StringPrintf(\"configDir='%s' tokenDescription='Real NSS database'\",\n GetDefaultConfigDirectory().value().c_str());\n real_db_slot_ = SECMOD_OpenUserDB(modspec.c_str());\n if (real_db_slot_ == NULL) {\n LOG(ERROR) << \"Error opening persistent database (\" << modspec\n << \"): NSS error code \" << PR_GetError();\n } else {\n if (PK11_NeedUserInit(real_db_slot_))\n PK11_InitPin(real_db_slot_, NULL, NULL);\n }\n }\n }\n#endif \/\/ defined(OS_CHROMEOS)\n\n PK11SlotInfo* GetDefaultKeySlot() {\n if (real_db_slot_)\n return PK11_ReferenceSlot(real_db_slot_);\n return PK11_GetInternalKeySlot();\n }\n\n#if defined(USE_NSS)\n Lock* write_lock() {\n return write_lock_.get();\n }\n#endif \/\/ defined(USE_NSS)\n\n private:\n PK11SlotInfo* real_db_slot_; \/\/ Overrides internal key slot if non-NULL.\n SECMODModule *root_;\n bool chromeos_user_logged_in_;\n#if defined(USE_NSS)\n scoped_ptr write_lock_;\n#endif \/\/ defined(USE_NSS)\n};\n\n} \/\/ namespace\n\nnamespace base {\n\nvoid EnsureNSPRInit() {\n Singleton::get();\n}\n\nvoid EnsureNSSInit() {\n Singleton::get();\n}\n\n#if defined(USE_NSS)\nLock* GetNSSWriteLock() {\n return Singleton::get()->write_lock();\n}\n\nAutoNSSWriteLock::AutoNSSWriteLock() : lock_(GetNSSWriteLock()) {\n \/\/ May be NULL if the lock is not needed in our version of NSS.\n if (lock_)\n lock_->Acquire();\n}\n\nAutoNSSWriteLock::~AutoNSSWriteLock() {\n if (lock_) {\n lock_->AssertAcquired();\n lock_->Release();\n }\n}\n#endif \/\/ defined(USE_NSS)\n\n#if defined(OS_CHROMEOS)\nvoid OpenPersistentNSSDB() {\n Singleton::get()->OpenPersistentNSSDB();\n}\n#endif\n\n\/\/ TODO(port): Implement this more simply. We can convert by subtracting an\n\/\/ offset (the difference between NSPR's and base::Time's epochs).\nTime PRTimeToBaseTime(PRTime prtime) {\n PRExplodedTime prxtime;\n PR_ExplodeTime(prtime, PR_GMTParameters, &prxtime);\n\n base::Time::Exploded exploded;\n exploded.year = prxtime.tm_year;\n exploded.month = prxtime.tm_month + 1;\n exploded.day_of_week = prxtime.tm_wday;\n exploded.day_of_month = prxtime.tm_mday;\n exploded.hour = prxtime.tm_hour;\n exploded.minute = prxtime.tm_min;\n exploded.second = prxtime.tm_sec;\n exploded.millisecond = prxtime.tm_usec \/ 1000;\n\n return Time::FromUTCExploded(exploded);\n}\n\nPK11SlotInfo* GetDefaultNSSKeySlot() {\n return Singleton::get()->GetDefaultKeySlot();\n}\n\n} \/\/ namespace base\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2015-2016 The Khronos Group Inc.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \"source\/spirv_target_env.h\"\n\n#include \n#include \n#include \n\n#include \"source\/spirv_constant.h\"\n#include \"spirv-tools\/libspirv.h\"\n\nconst char* spvTargetEnvDescription(spv_target_env env) {\n switch (env) {\n case SPV_ENV_UNIVERSAL_1_0:\n return \"SPIR-V 1.0\";\n case SPV_ENV_VULKAN_1_0:\n return \"SPIR-V 1.0 (under Vulkan 1.0 semantics)\";\n case SPV_ENV_UNIVERSAL_1_1:\n return \"SPIR-V 1.1\";\n case SPV_ENV_OPENCL_1_2:\n return \"SPIR-V 1.0 (under OpenCL 1.2 Full Profile semantics)\";\n case SPV_ENV_OPENCL_EMBEDDED_1_2:\n return \"SPIR-V 1.0 (under OpenCL 1.2 Embedded Profile semantics)\";\n case SPV_ENV_OPENCL_2_0:\n return \"SPIR-V 1.0 (under OpenCL 2.0 Full Profile semantics)\";\n case SPV_ENV_OPENCL_EMBEDDED_2_0:\n return \"SPIR-V 1.0 (under OpenCL 2.0 Embedded Profile semantics)\";\n case SPV_ENV_OPENCL_2_1:\n return \"SPIR-V 1.0 (under OpenCL 2.1 Full Profile semantics)\";\n case SPV_ENV_OPENCL_EMBEDDED_2_1:\n return \"SPIR-V 1.0 (under OpenCL 2.1 Embedded Profile semantics)\";\n case SPV_ENV_OPENCL_2_2:\n return \"SPIR-V 1.2 (under OpenCL 2.2 Full Profile semantics)\";\n case SPV_ENV_OPENCL_EMBEDDED_2_2:\n return \"SPIR-V 1.2 (under OpenCL 2.2 Embedded Profile semantics)\";\n case SPV_ENV_OPENGL_4_0:\n return \"SPIR-V 1.0 (under OpenGL 4.0 semantics)\";\n case SPV_ENV_OPENGL_4_1:\n return \"SPIR-V 1.0 (under OpenGL 4.1 semantics)\";\n case SPV_ENV_OPENGL_4_2:\n return \"SPIR-V 1.0 (under OpenGL 4.2 semantics)\";\n case SPV_ENV_OPENGL_4_3:\n return \"SPIR-V 1.0 (under OpenGL 4.3 semantics)\";\n case SPV_ENV_OPENGL_4_5:\n return \"SPIR-V 1.0 (under OpenGL 4.5 semantics)\";\n case SPV_ENV_UNIVERSAL_1_2:\n return \"SPIR-V 1.2\";\n case SPV_ENV_UNIVERSAL_1_3:\n return \"SPIR-V 1.3\";\n case SPV_ENV_VULKAN_1_1:\n return \"SPIR-V 1.3 (under Vulkan 1.1 semantics)\";\n case SPV_ENV_WEBGPU_0:\n return \"SPIR-V 1.3 (under WIP WebGPU semantics)\";\n case SPV_ENV_UNIVERSAL_1_4:\n return \"SPIR-V 1.4\";\n case SPV_ENV_VULKAN_1_1_SPIRV_1_4:\n return \"SPIR-V 1.4 (under Vulkan 1.1 semantics)\";\n }\n return \"\";\n}\n\nuint32_t spvVersionForTargetEnv(spv_target_env env) {\n switch (env) {\n case SPV_ENV_UNIVERSAL_1_0:\n case SPV_ENV_VULKAN_1_0:\n case SPV_ENV_OPENCL_1_2:\n case SPV_ENV_OPENCL_EMBEDDED_1_2:\n case SPV_ENV_OPENCL_2_0:\n case SPV_ENV_OPENCL_EMBEDDED_2_0:\n case SPV_ENV_OPENCL_2_1:\n case SPV_ENV_OPENCL_EMBEDDED_2_1:\n case SPV_ENV_OPENGL_4_0:\n case SPV_ENV_OPENGL_4_1:\n case SPV_ENV_OPENGL_4_2:\n case SPV_ENV_OPENGL_4_3:\n case SPV_ENV_OPENGL_4_5:\n return SPV_SPIRV_VERSION_WORD(1, 0);\n case SPV_ENV_UNIVERSAL_1_1:\n return SPV_SPIRV_VERSION_WORD(1, 1);\n case SPV_ENV_UNIVERSAL_1_2:\n case SPV_ENV_OPENCL_2_2:\n case SPV_ENV_OPENCL_EMBEDDED_2_2:\n return SPV_SPIRV_VERSION_WORD(1, 2);\n case SPV_ENV_UNIVERSAL_1_3:\n case SPV_ENV_VULKAN_1_1:\n case SPV_ENV_WEBGPU_0:\n return SPV_SPIRV_VERSION_WORD(1, 3);\n case SPV_ENV_UNIVERSAL_1_4:\n case SPV_ENV_VULKAN_1_1_SPIRV_1_4:\n return SPV_SPIRV_VERSION_WORD(1, 4);\n }\n return SPV_SPIRV_VERSION_WORD(0, 0);\n}\n\nstatic const std::map spvTargetEnvNameMap = {\n {\"vulkan1.1spv1.4\", SPV_ENV_VULKAN_1_1_SPIRV_1_4},\n {\"vulkan1.0\", SPV_ENV_VULKAN_1_0},\n {\"vulkan1.1\", SPV_ENV_VULKAN_1_1},\n {\"spv1.0\", SPV_ENV_UNIVERSAL_1_0},\n {\"spv1.1\", SPV_ENV_UNIVERSAL_1_1},\n {\"spv1.2\", SPV_ENV_UNIVERSAL_1_2},\n {\"spv1.3\", SPV_ENV_UNIVERSAL_1_3},\n {\"spv1.4\", SPV_ENV_UNIVERSAL_1_4},\n {\"opencl1.2embedded\", SPV_ENV_OPENCL_EMBEDDED_1_2},\n {\"opencl1.2\", SPV_ENV_OPENCL_1_2},\n {\"opencl2.0embedded\", SPV_ENV_OPENCL_EMBEDDED_2_0},\n {\"opencl2.0\", SPV_ENV_OPENCL_2_0},\n {\"opencl2.1embedded\", SPV_ENV_OPENCL_EMBEDDED_2_1},\n {\"opencl2.1\", SPV_ENV_OPENCL_2_1},\n {\"opencl2.2embedded\", SPV_ENV_OPENCL_EMBEDDED_2_2},\n {\"opencl2.2\", SPV_ENV_OPENCL_2_2},\n {\"opengl4.0\", SPV_ENV_OPENGL_4_0},\n {\"opengl4.1\", SPV_ENV_OPENGL_4_1},\n {\"opengl4.2\", SPV_ENV_OPENGL_4_2},\n {\"opengl4.3\", SPV_ENV_OPENGL_4_3},\n {\"opengl4.5\", SPV_ENV_OPENGL_4_5},\n {\"webgpu0\", SPV_ENV_WEBGPU_0},\n};\n\nbool spvParseTargetEnv(const char* s, spv_target_env* env) {\n std::string envstr;\n if (s != nullptr) {\n envstr = s;\n }\n if (spvTargetEnvNameMap.count(envstr) != 0) {\n if (env) {\n *env = spvTargetEnvNameMap.at(envstr);\n }\n return true;\n }\n if (env) *env = SPV_ENV_UNIVERSAL_1_0;\n return false;\n}\n\nbool spvIsVulkanEnv(spv_target_env env) {\n switch (env) {\n case SPV_ENV_UNIVERSAL_1_0:\n case SPV_ENV_OPENCL_1_2:\n case SPV_ENV_OPENCL_EMBEDDED_1_2:\n case SPV_ENV_OPENCL_2_0:\n case SPV_ENV_OPENCL_EMBEDDED_2_0:\n case SPV_ENV_OPENCL_2_1:\n case SPV_ENV_OPENCL_EMBEDDED_2_1:\n case SPV_ENV_OPENGL_4_0:\n case SPV_ENV_OPENGL_4_1:\n case SPV_ENV_OPENGL_4_2:\n case SPV_ENV_OPENGL_4_3:\n case SPV_ENV_OPENGL_4_5:\n case SPV_ENV_UNIVERSAL_1_1:\n case SPV_ENV_UNIVERSAL_1_2:\n case SPV_ENV_OPENCL_2_2:\n case SPV_ENV_OPENCL_EMBEDDED_2_2:\n case SPV_ENV_UNIVERSAL_1_3:\n case SPV_ENV_WEBGPU_0:\n case SPV_ENV_UNIVERSAL_1_4:\n return false;\n case SPV_ENV_VULKAN_1_0:\n case SPV_ENV_VULKAN_1_1:\n case SPV_ENV_VULKAN_1_1_SPIRV_1_4:\n return true;\n }\n return false;\n}\n\nbool spvIsOpenCLEnv(spv_target_env env) {\n switch (env) {\n case SPV_ENV_UNIVERSAL_1_0:\n case SPV_ENV_VULKAN_1_0:\n case SPV_ENV_UNIVERSAL_1_1:\n case SPV_ENV_OPENGL_4_0:\n case SPV_ENV_OPENGL_4_1:\n case SPV_ENV_OPENGL_4_2:\n case SPV_ENV_OPENGL_4_3:\n case SPV_ENV_OPENGL_4_5:\n case SPV_ENV_UNIVERSAL_1_2:\n case SPV_ENV_UNIVERSAL_1_3:\n case SPV_ENV_VULKAN_1_1:\n case SPV_ENV_WEBGPU_0:\n case SPV_ENV_UNIVERSAL_1_4:\n case SPV_ENV_VULKAN_1_1_SPIRV_1_4:\n return false;\n case SPV_ENV_OPENCL_1_2:\n case SPV_ENV_OPENCL_EMBEDDED_1_2:\n case SPV_ENV_OPENCL_2_0:\n case SPV_ENV_OPENCL_EMBEDDED_2_0:\n case SPV_ENV_OPENCL_EMBEDDED_2_1:\n case SPV_ENV_OPENCL_EMBEDDED_2_2:\n case SPV_ENV_OPENCL_2_1:\n case SPV_ENV_OPENCL_2_2:\n return true;\n }\n return false;\n}\n\nbool spvIsWebGPUEnv(spv_target_env env) {\n switch (env) {\n case SPV_ENV_UNIVERSAL_1_0:\n case SPV_ENV_VULKAN_1_0:\n case SPV_ENV_UNIVERSAL_1_1:\n case SPV_ENV_OPENGL_4_0:\n case SPV_ENV_OPENGL_4_1:\n case SPV_ENV_OPENGL_4_2:\n case SPV_ENV_OPENGL_4_3:\n case SPV_ENV_OPENGL_4_5:\n case SPV_ENV_UNIVERSAL_1_2:\n case SPV_ENV_UNIVERSAL_1_3:\n case SPV_ENV_VULKAN_1_1:\n case SPV_ENV_OPENCL_1_2:\n case SPV_ENV_OPENCL_EMBEDDED_1_2:\n case SPV_ENV_OPENCL_2_0:\n case SPV_ENV_OPENCL_EMBEDDED_2_0:\n case SPV_ENV_OPENCL_EMBEDDED_2_1:\n case SPV_ENV_OPENCL_EMBEDDED_2_2:\n case SPV_ENV_OPENCL_2_1:\n case SPV_ENV_OPENCL_2_2:\n case SPV_ENV_UNIVERSAL_1_4:\n case SPV_ENV_VULKAN_1_1_SPIRV_1_4:\n return false;\n case SPV_ENV_WEBGPU_0:\n return true;\n }\n return false;\n}\n\nbool spvIsVulkanOrWebGPUEnv(spv_target_env env) {\n return spvIsVulkanEnv(env) || spvIsWebGPUEnv(env);\n}\n\nstd::string spvLogStringForEnv(spv_target_env env) {\n switch (env) {\n case SPV_ENV_OPENCL_1_2:\n case SPV_ENV_OPENCL_2_0:\n case SPV_ENV_OPENCL_2_1:\n case SPV_ENV_OPENCL_2_2:\n case SPV_ENV_OPENCL_EMBEDDED_1_2:\n case SPV_ENV_OPENCL_EMBEDDED_2_0:\n case SPV_ENV_OPENCL_EMBEDDED_2_1:\n case SPV_ENV_OPENCL_EMBEDDED_2_2: {\n return \"OpenCL\";\n }\n case SPV_ENV_OPENGL_4_0:\n case SPV_ENV_OPENGL_4_1:\n case SPV_ENV_OPENGL_4_2:\n case SPV_ENV_OPENGL_4_3:\n case SPV_ENV_OPENGL_4_5: {\n return \"OpenGL\";\n }\n case SPV_ENV_VULKAN_1_0:\n case SPV_ENV_VULKAN_1_1:\n case SPV_ENV_VULKAN_1_1_SPIRV_1_4: {\n return \"Vulkan\";\n }\n case SPV_ENV_WEBGPU_0: {\n return \"WebGPU\";\n }\n case SPV_ENV_UNIVERSAL_1_0:\n case SPV_ENV_UNIVERSAL_1_1:\n case SPV_ENV_UNIVERSAL_1_2:\n case SPV_ENV_UNIVERSAL_1_3:\n case SPV_ENV_UNIVERSAL_1_4: {\n return \"Universal\";\n }\n }\n return \"Unknown\";\n}\n\nstd::string spvTargetEnvList(const int pad, const int wrap) {\n std::string ret;\n size_t max_line_len = wrap - pad; \/\/ The first line isn't padded\n std::string line;\n std::string sep = \"\";\n\n for (auto& env_name : spvTargetEnvNameMap) {\n std::string word = sep + env_name.first;\n if (line.length() + word.length() > max_line_len) {\n \/\/ Adding one word wouldn't fit, commit the line in progress and\n \/\/ start a new one.\n ret += line + \"\\n\";\n line.assign(pad, ' ');\n \/\/ The first line is done. The max length now comprises the\n \/\/ padding.\n max_line_len = wrap;\n }\n line += word;\n sep = \"|\";\n }\n\n ret += line;\n\n return ret;\n}\nReplace global static map with an array of pairs (#2691)\/\/ Copyright (c) 2015-2016 The Khronos Group Inc.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \"source\/spirv_target_env.h\"\n\n#include \n#include \n\n#include \"source\/spirv_constant.h\"\n#include \"spirv-tools\/libspirv.h\"\n\nconst char* spvTargetEnvDescription(spv_target_env env) {\n switch (env) {\n case SPV_ENV_UNIVERSAL_1_0:\n return \"SPIR-V 1.0\";\n case SPV_ENV_VULKAN_1_0:\n return \"SPIR-V 1.0 (under Vulkan 1.0 semantics)\";\n case SPV_ENV_UNIVERSAL_1_1:\n return \"SPIR-V 1.1\";\n case SPV_ENV_OPENCL_1_2:\n return \"SPIR-V 1.0 (under OpenCL 1.2 Full Profile semantics)\";\n case SPV_ENV_OPENCL_EMBEDDED_1_2:\n return \"SPIR-V 1.0 (under OpenCL 1.2 Embedded Profile semantics)\";\n case SPV_ENV_OPENCL_2_0:\n return \"SPIR-V 1.0 (under OpenCL 2.0 Full Profile semantics)\";\n case SPV_ENV_OPENCL_EMBEDDED_2_0:\n return \"SPIR-V 1.0 (under OpenCL 2.0 Embedded Profile semantics)\";\n case SPV_ENV_OPENCL_2_1:\n return \"SPIR-V 1.0 (under OpenCL 2.1 Full Profile semantics)\";\n case SPV_ENV_OPENCL_EMBEDDED_2_1:\n return \"SPIR-V 1.0 (under OpenCL 2.1 Embedded Profile semantics)\";\n case SPV_ENV_OPENCL_2_2:\n return \"SPIR-V 1.2 (under OpenCL 2.2 Full Profile semantics)\";\n case SPV_ENV_OPENCL_EMBEDDED_2_2:\n return \"SPIR-V 1.2 (under OpenCL 2.2 Embedded Profile semantics)\";\n case SPV_ENV_OPENGL_4_0:\n return \"SPIR-V 1.0 (under OpenGL 4.0 semantics)\";\n case SPV_ENV_OPENGL_4_1:\n return \"SPIR-V 1.0 (under OpenGL 4.1 semantics)\";\n case SPV_ENV_OPENGL_4_2:\n return \"SPIR-V 1.0 (under OpenGL 4.2 semantics)\";\n case SPV_ENV_OPENGL_4_3:\n return \"SPIR-V 1.0 (under OpenGL 4.3 semantics)\";\n case SPV_ENV_OPENGL_4_5:\n return \"SPIR-V 1.0 (under OpenGL 4.5 semantics)\";\n case SPV_ENV_UNIVERSAL_1_2:\n return \"SPIR-V 1.2\";\n case SPV_ENV_UNIVERSAL_1_3:\n return \"SPIR-V 1.3\";\n case SPV_ENV_VULKAN_1_1:\n return \"SPIR-V 1.3 (under Vulkan 1.1 semantics)\";\n case SPV_ENV_WEBGPU_0:\n return \"SPIR-V 1.3 (under WIP WebGPU semantics)\";\n case SPV_ENV_UNIVERSAL_1_4:\n return \"SPIR-V 1.4\";\n case SPV_ENV_VULKAN_1_1_SPIRV_1_4:\n return \"SPIR-V 1.4 (under Vulkan 1.1 semantics)\";\n }\n return \"\";\n}\n\nuint32_t spvVersionForTargetEnv(spv_target_env env) {\n switch (env) {\n case SPV_ENV_UNIVERSAL_1_0:\n case SPV_ENV_VULKAN_1_0:\n case SPV_ENV_OPENCL_1_2:\n case SPV_ENV_OPENCL_EMBEDDED_1_2:\n case SPV_ENV_OPENCL_2_0:\n case SPV_ENV_OPENCL_EMBEDDED_2_0:\n case SPV_ENV_OPENCL_2_1:\n case SPV_ENV_OPENCL_EMBEDDED_2_1:\n case SPV_ENV_OPENGL_4_0:\n case SPV_ENV_OPENGL_4_1:\n case SPV_ENV_OPENGL_4_2:\n case SPV_ENV_OPENGL_4_3:\n case SPV_ENV_OPENGL_4_5:\n return SPV_SPIRV_VERSION_WORD(1, 0);\n case SPV_ENV_UNIVERSAL_1_1:\n return SPV_SPIRV_VERSION_WORD(1, 1);\n case SPV_ENV_UNIVERSAL_1_2:\n case SPV_ENV_OPENCL_2_2:\n case SPV_ENV_OPENCL_EMBEDDED_2_2:\n return SPV_SPIRV_VERSION_WORD(1, 2);\n case SPV_ENV_UNIVERSAL_1_3:\n case SPV_ENV_VULKAN_1_1:\n case SPV_ENV_WEBGPU_0:\n return SPV_SPIRV_VERSION_WORD(1, 3);\n case SPV_ENV_UNIVERSAL_1_4:\n case SPV_ENV_VULKAN_1_1_SPIRV_1_4:\n return SPV_SPIRV_VERSION_WORD(1, 4);\n }\n return SPV_SPIRV_VERSION_WORD(0, 0);\n}\n\nstatic const std::pair spvTargetEnvNameMap[] = {\n {\"vulkan1.1spv1.4\", SPV_ENV_VULKAN_1_1_SPIRV_1_4},\n {\"vulkan1.0\", SPV_ENV_VULKAN_1_0},\n {\"vulkan1.1\", SPV_ENV_VULKAN_1_1},\n {\"spv1.0\", SPV_ENV_UNIVERSAL_1_0},\n {\"spv1.1\", SPV_ENV_UNIVERSAL_1_1},\n {\"spv1.2\", SPV_ENV_UNIVERSAL_1_2},\n {\"spv1.3\", SPV_ENV_UNIVERSAL_1_3},\n {\"spv1.4\", SPV_ENV_UNIVERSAL_1_4},\n {\"opencl1.2embedded\", SPV_ENV_OPENCL_EMBEDDED_1_2},\n {\"opencl1.2\", SPV_ENV_OPENCL_1_2},\n {\"opencl2.0embedded\", SPV_ENV_OPENCL_EMBEDDED_2_0},\n {\"opencl2.0\", SPV_ENV_OPENCL_2_0},\n {\"opencl2.1embedded\", SPV_ENV_OPENCL_EMBEDDED_2_1},\n {\"opencl2.1\", SPV_ENV_OPENCL_2_1},\n {\"opencl2.2embedded\", SPV_ENV_OPENCL_EMBEDDED_2_2},\n {\"opencl2.2\", SPV_ENV_OPENCL_2_2},\n {\"opengl4.0\", SPV_ENV_OPENGL_4_0},\n {\"opengl4.1\", SPV_ENV_OPENGL_4_1},\n {\"opengl4.2\", SPV_ENV_OPENGL_4_2},\n {\"opengl4.3\", SPV_ENV_OPENGL_4_3},\n {\"opengl4.5\", SPV_ENV_OPENGL_4_5},\n {\"webgpu0\", SPV_ENV_WEBGPU_0},\n};\n\nbool spvParseTargetEnv(const char* s, spv_target_env* env) {\n auto match = [s](const char* b) {\n return s && (0 == strncmp(s, b, strlen(b)));\n };\n for (auto& name_env : spvTargetEnvNameMap) {\n if (match(name_env.first)) {\n if (env) {\n *env = name_env.second;\n }\n return true;\n }\n }\n if (env) *env = SPV_ENV_UNIVERSAL_1_0;\n return false;\n}\n\nbool spvIsVulkanEnv(spv_target_env env) {\n switch (env) {\n case SPV_ENV_UNIVERSAL_1_0:\n case SPV_ENV_OPENCL_1_2:\n case SPV_ENV_OPENCL_EMBEDDED_1_2:\n case SPV_ENV_OPENCL_2_0:\n case SPV_ENV_OPENCL_EMBEDDED_2_0:\n case SPV_ENV_OPENCL_2_1:\n case SPV_ENV_OPENCL_EMBEDDED_2_1:\n case SPV_ENV_OPENGL_4_0:\n case SPV_ENV_OPENGL_4_1:\n case SPV_ENV_OPENGL_4_2:\n case SPV_ENV_OPENGL_4_3:\n case SPV_ENV_OPENGL_4_5:\n case SPV_ENV_UNIVERSAL_1_1:\n case SPV_ENV_UNIVERSAL_1_2:\n case SPV_ENV_OPENCL_2_2:\n case SPV_ENV_OPENCL_EMBEDDED_2_2:\n case SPV_ENV_UNIVERSAL_1_3:\n case SPV_ENV_WEBGPU_0:\n case SPV_ENV_UNIVERSAL_1_4:\n return false;\n case SPV_ENV_VULKAN_1_0:\n case SPV_ENV_VULKAN_1_1:\n case SPV_ENV_VULKAN_1_1_SPIRV_1_4:\n return true;\n }\n return false;\n}\n\nbool spvIsOpenCLEnv(spv_target_env env) {\n switch (env) {\n case SPV_ENV_UNIVERSAL_1_0:\n case SPV_ENV_VULKAN_1_0:\n case SPV_ENV_UNIVERSAL_1_1:\n case SPV_ENV_OPENGL_4_0:\n case SPV_ENV_OPENGL_4_1:\n case SPV_ENV_OPENGL_4_2:\n case SPV_ENV_OPENGL_4_3:\n case SPV_ENV_OPENGL_4_5:\n case SPV_ENV_UNIVERSAL_1_2:\n case SPV_ENV_UNIVERSAL_1_3:\n case SPV_ENV_VULKAN_1_1:\n case SPV_ENV_WEBGPU_0:\n case SPV_ENV_UNIVERSAL_1_4:\n case SPV_ENV_VULKAN_1_1_SPIRV_1_4:\n return false;\n case SPV_ENV_OPENCL_1_2:\n case SPV_ENV_OPENCL_EMBEDDED_1_2:\n case SPV_ENV_OPENCL_2_0:\n case SPV_ENV_OPENCL_EMBEDDED_2_0:\n case SPV_ENV_OPENCL_EMBEDDED_2_1:\n case SPV_ENV_OPENCL_EMBEDDED_2_2:\n case SPV_ENV_OPENCL_2_1:\n case SPV_ENV_OPENCL_2_2:\n return true;\n }\n return false;\n}\n\nbool spvIsWebGPUEnv(spv_target_env env) {\n switch (env) {\n case SPV_ENV_UNIVERSAL_1_0:\n case SPV_ENV_VULKAN_1_0:\n case SPV_ENV_UNIVERSAL_1_1:\n case SPV_ENV_OPENGL_4_0:\n case SPV_ENV_OPENGL_4_1:\n case SPV_ENV_OPENGL_4_2:\n case SPV_ENV_OPENGL_4_3:\n case SPV_ENV_OPENGL_4_5:\n case SPV_ENV_UNIVERSAL_1_2:\n case SPV_ENV_UNIVERSAL_1_3:\n case SPV_ENV_VULKAN_1_1:\n case SPV_ENV_OPENCL_1_2:\n case SPV_ENV_OPENCL_EMBEDDED_1_2:\n case SPV_ENV_OPENCL_2_0:\n case SPV_ENV_OPENCL_EMBEDDED_2_0:\n case SPV_ENV_OPENCL_EMBEDDED_2_1:\n case SPV_ENV_OPENCL_EMBEDDED_2_2:\n case SPV_ENV_OPENCL_2_1:\n case SPV_ENV_OPENCL_2_2:\n case SPV_ENV_UNIVERSAL_1_4:\n case SPV_ENV_VULKAN_1_1_SPIRV_1_4:\n return false;\n case SPV_ENV_WEBGPU_0:\n return true;\n }\n return false;\n}\n\nbool spvIsVulkanOrWebGPUEnv(spv_target_env env) {\n return spvIsVulkanEnv(env) || spvIsWebGPUEnv(env);\n}\n\nstd::string spvLogStringForEnv(spv_target_env env) {\n switch (env) {\n case SPV_ENV_OPENCL_1_2:\n case SPV_ENV_OPENCL_2_0:\n case SPV_ENV_OPENCL_2_1:\n case SPV_ENV_OPENCL_2_2:\n case SPV_ENV_OPENCL_EMBEDDED_1_2:\n case SPV_ENV_OPENCL_EMBEDDED_2_0:\n case SPV_ENV_OPENCL_EMBEDDED_2_1:\n case SPV_ENV_OPENCL_EMBEDDED_2_2: {\n return \"OpenCL\";\n }\n case SPV_ENV_OPENGL_4_0:\n case SPV_ENV_OPENGL_4_1:\n case SPV_ENV_OPENGL_4_2:\n case SPV_ENV_OPENGL_4_3:\n case SPV_ENV_OPENGL_4_5: {\n return \"OpenGL\";\n }\n case SPV_ENV_VULKAN_1_0:\n case SPV_ENV_VULKAN_1_1:\n case SPV_ENV_VULKAN_1_1_SPIRV_1_4: {\n return \"Vulkan\";\n }\n case SPV_ENV_WEBGPU_0: {\n return \"WebGPU\";\n }\n case SPV_ENV_UNIVERSAL_1_0:\n case SPV_ENV_UNIVERSAL_1_1:\n case SPV_ENV_UNIVERSAL_1_2:\n case SPV_ENV_UNIVERSAL_1_3:\n case SPV_ENV_UNIVERSAL_1_4: {\n return \"Universal\";\n }\n }\n return \"Unknown\";\n}\n\nstd::string spvTargetEnvList(const int pad, const int wrap) {\n std::string ret;\n size_t max_line_len = wrap - pad; \/\/ The first line isn't padded\n std::string line;\n std::string sep = \"\";\n\n for (auto& name_env : spvTargetEnvNameMap) {\n std::string word = sep + name_env.first;\n if (line.length() + word.length() > max_line_len) {\n \/\/ Adding one word wouldn't fit, commit the line in progress and\n \/\/ start a new one.\n ret += line + \"\\n\";\n line.assign(pad, ' ');\n \/\/ The first line is done. The max length now comprises the\n \/\/ padding.\n max_line_len = wrap;\n }\n line += word;\n sep = \"|\";\n }\n\n ret += line;\n\n return ret;\n}\n<|endoftext|>"} {"text":"#define BOOST_TEST_MAIN\n#if !defined( WIN32 )\n #define BOOST_TEST_DYN_LINK\n#endif\n#define BOOST_TEST_MODULE Future2Tests\n\n#include \n#include \n#include \n\n\/* For symbol_thingey *\/\n#define BOOST_CHRONO_VERSION 2\n#include \n#include \n\n#define FUTURE_TRACE 0\n\n#include \n#include \"Log.h\"\n\nusing namespace cps;\nusing namespace std;\n\nBOOST_AUTO_TEST_CASE(leaf_future_string)\n{\n\t{ \/* shared_ptr interface means this is about as far as we can get with these: *\/\n\t\tfuture f { };\n\t\tBOOST_CHECK(!f.is_ready());\n\t\tBOOST_CHECK(!f.is_done());\n\t\tBOOST_CHECK(!f.is_failed());\n\t\tBOOST_CHECK(!f.is_cancelled());\n\t}\n\tauto f = future::create_shared();\n\tauto f2 = f->done(445)->on_done([](int v) {\n\t\tBOOST_CHECK_EQUAL(v, 445);\n\t\tcout << \"Have value \" << v << endl;\n\t})->then([](int v) {\n\t\tBOOST_CHECK_EQUAL(v, 445);\n\t\tcout << \"Value is still \" << v << endl;\n\t\treturn future::create_shared();\n\t})->on_done([](string v) {\n\t\tBOOST_CHECK_EQUAL(v, \"test\");\n\t\tcout << \"New futue is \" << v << endl;\n\t})->done(\"test\")->on_done([](string v) {\n\t\tBOOST_CHECK_EQUAL(v, \"test\");\n\t\tcout << \"Finally \" << v << endl;\n\t})->on_done([](const string &v) {\n\t\tBOOST_CHECK_EQUAL(v, \"test\");\n\t\tcout << \"Alternatively \" << v << endl;\n\t});\n}\n\ntypedef boost::mpl::list<\n\tint,\n\tuint8_t, int8_t,\n\tuint16_t, int16_t,\n\tuint32_t, int32_t,\n\tuint64_t, int64_t,\n\tshort, int, long, long long,\n\tfloat, double\n> leaf_integral_types;\nBOOST_AUTO_TEST_CASE_TEMPLATE(leaf_future_integral, T, leaf_integral_types)\n{\n\t{\n\t\tauto f = future::create_shared();\n\t\tBOOST_CHECK(!f->is_ready());\n\t\tBOOST_CHECK(!f->is_done());\n\t\tBOOST_CHECK(!f->is_failed());\n\t\tBOOST_CHECK(!f->is_cancelled());\n\t\t\/\/ Pick a smallish number that fits all the numeric types\n\t\tf->done(17)->on_done([](T v) {\n\t\t\tBOOST_CHECK_EQUAL(v, 17);\n\t\t\tcout << \"Have value \" << v << endl;\n\t\t});\n\t\tBOOST_CHECK( f->is_ready());\n\t\tBOOST_CHECK( f->is_done());\n\t\tBOOST_CHECK(!f->is_failed());\n\t\tBOOST_CHECK(!f->is_cancelled());\n\t}\n\t{\n\t\tauto f = future::create_shared();\n\t\tBOOST_CHECK(!f->is_ready());\n\t\tBOOST_CHECK(!f->is_done());\n\t\tBOOST_CHECK(!f->is_failed());\n\t\tBOOST_CHECK(!f->is_cancelled());\n\t\t\/\/ Pick a smallish number that fits all the numeric types\n\t\tf->fail(\"some problem\")->on_fail([](const std::string &err) {\n\t\t\tBOOST_CHECK_EQUAL(err, \"some problem\");\n\t\t});\n\t\tBOOST_CHECK( f->is_ready());\n\t\tBOOST_CHECK(!f->is_done());\n\t\tBOOST_CHECK( f->is_failed());\n\t\tBOOST_CHECK(!f->is_cancelled());\n\t}\n}\n\nBOOST_AUTO_TEST_CASE_TEMPLATE(leaf_future_other, T, boost::mpl::list<\n\tbool\n>)\n{\n\tauto f = future::create_shared();\n\tBOOST_CHECK(!f->is_ready());\n\tBOOST_CHECK(!f->is_done());\n\tBOOST_CHECK(!f->is_failed());\n\tBOOST_CHECK(!f->is_cancelled());\n\tf->done(true);\n\tBOOST_CHECK( f->is_ready());\n\tBOOST_CHECK( f->is_done());\n\tBOOST_CHECK(!f->is_failed());\n\tBOOST_CHECK(!f->is_cancelled());\n}\n\nBOOST_AUTO_TEST_CASE(composition_needs_all)\n{\n\t{\n\t\tauto f1 = future::create_shared();\n\t\tauto f2 = future::create_shared();\n\n\t\tauto composed = needs_all(\n\t\t\tf1,\n\t\t\tf2\n\t\t);\n\t\tcomposed->on_ready([](future &f) {\n\t\t\tcout << \"ready\" << endl;\n\t\t});\n\t\tBOOST_CHECK(!composed->is_ready());\n\t\tf1->done(432);\n\t\tBOOST_CHECK(!composed->is_ready());\n\t\tf2->done(\"test\");\n\t\tBOOST_CHECK( composed->is_ready());\n\t\tBOOST_CHECK( composed->is_done());\n\t}\n\t{\n\t\tauto f1 = future::create_shared();\n\t\tauto f2 = future::create_shared();\n\n\t\tauto composed = needs_all(\n\t\t\tf1,\n\t\t\tf2\n\t\t);\n\t\tcomposed->on_ready([](future &f) {\n\t\t\tBOOST_CHECK(f.is_ready());\n\t\t});\n\t\tBOOST_CHECK(!composed->is_ready());\n\t\tf1->fail(\"aiee\");\n\t\tBOOST_CHECK( composed->is_ready());\n\t\tBOOST_CHECK( composed->is_failed());\n\t}\n\t{\n\t\tstd::vector>> pending {\n\t\t\tfuture::create_shared(),\n\t\t\tfuture::create_shared(),\n\t\t\tfuture::create_shared(),\n\t\t\tfuture::create_shared(),\n\t\t\tfuture::create_shared(),\n\t\t\tfuture::create_shared()\n\t\t};\n\n\t\tauto composed = needs_all(\n\t\t\tpending\n\t\t);\n\t\tcomposed->on_ready([](future &f) {\n\t\t\tBOOST_CHECK(f.is_ready());\n\t\t});\n\t\tBOOST_CHECK(!composed->is_ready());\n\t\tint i = 0;\n\t\tfor(auto &it : pending) {\n\t\t\tit->done(++i);\n\t\t\tif(i == pending.size()) {\n\t\t\t\tBOOST_CHECK( composed->is_done());\n\t\t\t} else {\n\t\t\t\tBOOST_CHECK(!composed->is_ready());\n\t\t\t}\n\t\t}\n\t\tBOOST_CHECK( composed->is_ready());\n\t}\n}\n\nBOOST_AUTO_TEST_CASE(composition_needs_any)\n{\n\t{\n\t\tauto f1 = future::create_shared();\n\t\tauto f2 = future::create_shared();\n\n\t\tauto composed = needs_all(\n\t\t\tf1,\n\t\t\tf2\n\t\t);\n\t\tcomposed->on_ready([](future &f) {\n\t\t\tcout << \"ready\" << endl;\n\t\t});\n\t\tBOOST_CHECK(!composed->is_ready());\n\t\tf1->done(432);\n\t\tBOOST_CHECK(!composed->is_ready());\n\t\tf2->done(\"test\");\n\t\tBOOST_CHECK( composed->is_ready());\n\t\tBOOST_CHECK( composed->is_done());\n\t}\n\t{\n\t\tauto f1 = future::create_shared();\n\t\tauto f2 = future::create_shared();\n\n\t\tauto composed = needs_all(\n\t\t\tf1,\n\t\t\tf2\n\t\t);\n\t\tcomposed->on_ready([](future &f) {\n\t\t\tBOOST_CHECK(f.is_ready());\n\t\t});\n\t\tBOOST_CHECK(!composed->is_ready());\n\t\tf1->fail(\"aiee\");\n\t\tBOOST_CHECK( composed->is_ready());\n\t\tBOOST_CHECK( composed->is_failed());\n\t}\n\t{\n\t\tstd::vector>> pending {\n\t\t\tfuture::create_shared(),\n\t\t\tfuture::create_shared(),\n\t\t\tfuture::create_shared(),\n\t\t\tfuture::create_shared(),\n\t\t\tfuture::create_shared(),\n\t\t\tfuture::create_shared()\n\t\t};\n\n\t\tauto composed = needs_all(\n\t\t\tpending\n\t\t);\n\t\tcomposed->on_ready([](future &f) {\n\t\t\tBOOST_CHECK(f.is_ready());\n\t\t});\n\t\tBOOST_CHECK(!composed->is_ready());\n\t\tint i = 0;\n\t\tfor(auto &it : pending) {\n\t\t\tit->done(++i);\n\t\t\tif(i == pending.size()) {\n\t\t\t\tBOOST_CHECK( composed->is_done());\n\t\t\t} else {\n\t\t\t\tBOOST_CHECK(!composed->is_ready());\n\t\t\t}\n\t\t}\n\t\tBOOST_CHECK( composed->is_ready());\n\t}\n}\n\nUpdated tests#define BOOST_TEST_MAIN\n#if !defined( WIN32 )\n #define BOOST_TEST_DYN_LINK\n#endif\n#define BOOST_TEST_MODULE FutureTests\n\n#include \n#include \n#include \n\n\/* For symbol_thingey *\/\n#define BOOST_CHRONO_VERSION 2\n#include \n#include \n\n#define FUTURE_TRACE 0\n\n#include \n#include \"Log.h\"\n\nusing namespace cps;\nusing namespace std;\n\nBOOST_AUTO_TEST_CASE(future_string)\n{\n\t{ \/* shared_ptr interface means this is about as far as we can get with these: *\/\n\t\tfuture f { };\n\t\tBOOST_CHECK(!f.is_ready());\n\t\tBOOST_CHECK(!f.is_done());\n\t\tBOOST_CHECK(!f.is_failed());\n\t\tBOOST_CHECK(!f.is_cancelled());\n\t}\n\tauto f = future::create_shared();\n\tauto f2 = f->done(445)->on_done([](int v) {\n\t\tBOOST_CHECK_EQUAL(v, 445);\n\t\tcout << \"Have value \" << v << endl;\n\t})->then([](int v) {\n\t\tBOOST_CHECK_EQUAL(v, 445);\n\t\tcout << \"Value is still \" << v << endl;\n\t\treturn future::create_shared();\n\t})->on_done([](string v) {\n\t\tBOOST_CHECK_EQUAL(v, \"test\");\n\t\tcout << \"New futue is \" << v << endl;\n\t})->done(\"test\")->on_done([](string v) {\n\t\tBOOST_CHECK_EQUAL(v, \"test\");\n\t\tcout << \"Finally \" << v << endl;\n\t})->on_done([](const string &v) {\n\t\tBOOST_CHECK_EQUAL(v, \"test\");\n\t\tcout << \"Alternatively \" << v << endl;\n\t});\n}\n\ntypedef boost::mpl::list<\n\tint,\n\tuint8_t, int8_t,\n\tuint16_t, int16_t,\n\tuint32_t, int32_t,\n\tuint64_t, int64_t,\n\tshort, int, long, long long,\n\tfloat, double\n> integral_types;\nBOOST_AUTO_TEST_CASE_TEMPLATE(future_integral, T, integral_types)\n{\n\t{\n\t\tauto f = future::create_shared();\n\t\tBOOST_CHECK(!f->is_ready());\n\t\tBOOST_CHECK(!f->is_done());\n\t\tBOOST_CHECK(!f->is_failed());\n\t\tBOOST_CHECK(!f->is_cancelled());\n\t\t\/\/ Pick a smallish number that fits all the numeric types\n\t\tf->done(17)->on_done([](T v) {\n\t\t\tBOOST_CHECK_EQUAL(v, 17);\n\t\t\tcout << \"Have value \" << v << endl;\n\t\t});\n\t\tBOOST_CHECK( f->is_ready());\n\t\tBOOST_CHECK( f->is_done());\n\t\tBOOST_CHECK(!f->is_failed());\n\t\tBOOST_CHECK(!f->is_cancelled());\n\t}\n\t{\n\t\tauto f = future::create_shared();\n\t\tBOOST_CHECK(!f->is_ready());\n\t\tBOOST_CHECK(!f->is_done());\n\t\tBOOST_CHECK(!f->is_failed());\n\t\tBOOST_CHECK(!f->is_cancelled());\n\t\t\/\/ Pick a smallish number that fits all the numeric types\n\t\tf->fail(\"some problem\")->on_fail([](const std::string &err) {\n\t\t\tBOOST_CHECK_EQUAL(err, \"some problem\");\n\t\t});\n\t\tBOOST_CHECK( f->is_ready());\n\t\tBOOST_CHECK(!f->is_done());\n\t\tBOOST_CHECK( f->is_failed());\n\t\tBOOST_CHECK(!f->is_cancelled());\n\t}\n}\n\nBOOST_AUTO_TEST_CASE_TEMPLATE(future_other, T, boost::mpl::list<\n\tbool\n>)\n{\n\tauto f = future::create_shared();\n\tBOOST_CHECK(!f->is_ready());\n\tBOOST_CHECK(!f->is_done());\n\tBOOST_CHECK(!f->is_failed());\n\tBOOST_CHECK(!f->is_cancelled());\n\tf->done(true);\n\tBOOST_CHECK( f->is_ready());\n\tBOOST_CHECK( f->is_done());\n\tBOOST_CHECK(!f->is_failed());\n\tBOOST_CHECK(!f->is_cancelled());\n}\n\nBOOST_AUTO_TEST_CASE(future_then)\n{\n\tauto f = future::create_shared();\n\tshared_ptr> str1;\n\tshared_ptr> bool1;\n\tauto f2 = f->then([&str1](int v) {\n\t\tBOOST_CHECK_EQUAL(v, 23);\n\t\tstr1 = future::create_shared();\n\t\treturn str1;\n\t})->then([&bool1](string v) {\n\t\tBOOST_CHECK_EQUAL(v, \"testing\");\n\t\tbool1 = future::create_shared();\n\t\treturn bool1;\n\t})->on_ready([&str1](future &in) {\n\t\tBOOST_CHECK_EQUAL(str1->value(), \"testing\");\n\t\tBOOST_CHECK(in.value());\n\t});\n\tBOOST_CHECK(!str1);\n\tBOOST_CHECK(!bool1);\n\tf->done(23);\n\tBOOST_CHECK( str1);\n\tBOOST_CHECK(!bool1);\n\tstr1->done(\"testing\");\n\tBOOST_CHECK_EQUAL( str1->value(), \"testing\");\n\tBOOST_CHECK( bool1);\n\tbool1->done(true);\n\tBOOST_CHECK(bool1->value());\n}\n\nBOOST_AUTO_TEST_CASE(composition_needs_all)\n{\n\t{\n\t\tauto f1 = future::create_shared();\n\t\tauto f2 = future::create_shared();\n\n\t\tauto composed = needs_all(\n\t\t\tf1,\n\t\t\tf2\n\t\t);\n\t\tcomposed->on_ready([](future &f) {\n\t\t\tcout << \"ready\" << endl;\n\t\t});\n\t\tBOOST_CHECK(!composed->is_ready());\n\t\tf1->done(432);\n\t\tBOOST_CHECK(!composed->is_ready());\n\t\tf2->done(\"test\");\n\t\tBOOST_CHECK( composed->is_ready());\n\t\tBOOST_CHECK( composed->is_done());\n\t}\n\t{\n\t\tauto f1 = future::create_shared();\n\t\tauto f2 = future::create_shared();\n\n\t\tauto composed = needs_all(\n\t\t\tf1,\n\t\t\tf2\n\t\t);\n\t\tcomposed->on_ready([](future &f) {\n\t\t\tBOOST_CHECK(f.is_ready());\n\t\t});\n\t\tBOOST_CHECK(!composed->is_ready());\n\t\tf1->fail(\"aiee\");\n\t\tBOOST_CHECK( composed->is_ready());\n\t\tBOOST_CHECK( composed->is_failed());\n\t}\n\t{\n\t\tstd::vector>> pending {\n\t\t\tfuture::create_shared(),\n\t\t\tfuture::create_shared(),\n\t\t\tfuture::create_shared(),\n\t\t\tfuture::create_shared(),\n\t\t\tfuture::create_shared(),\n\t\t\tfuture::create_shared()\n\t\t};\n\n\t\tauto composed = needs_all(\n\t\t\tpending\n\t\t);\n\t\tcomposed->on_ready([](future &f) {\n\t\t\tBOOST_CHECK(f.is_ready());\n\t\t});\n\t\tBOOST_CHECK(!composed->is_ready());\n\t\tint i = 0;\n\t\tfor(auto &it : pending) {\n\t\t\tit->done(++i);\n\t\t\tif(i == pending.size()) {\n\t\t\t\tBOOST_CHECK( composed->is_done());\n\t\t\t} else {\n\t\t\t\tBOOST_CHECK(!composed->is_ready());\n\t\t\t}\n\t\t}\n\t\tBOOST_CHECK( composed->is_ready());\n\t}\n}\n\nBOOST_AUTO_TEST_CASE(composition_needs_any)\n{\n\t{\n\t\tauto f1 = future::create_shared();\n\t\tauto f2 = future::create_shared();\n\n\t\tauto composed = needs_any(\n\t\t\tf1,\n\t\t\tf2\n\t\t);\n\t\tcomposed->on_ready([](future &f) {\n\t\t\tcout << \"ready\" << endl;\n\t\t});\n\t\tBOOST_CHECK(!composed->is_ready());\n\t\tf1->done(432);\n\t\tBOOST_CHECK( composed->is_ready());\n\t\tBOOST_CHECK( composed->is_done());\n\t\tf2->done(\"test\");\n\t\tBOOST_CHECK( composed->is_ready());\n\t\tBOOST_CHECK( composed->is_done());\n\t}\n\t{\n\t\tauto f1 = future::create_shared();\n\t\tauto f2 = future::create_shared();\n\n\t\tauto composed = needs_all(\n\t\t\tf1,\n\t\t\tf2\n\t\t);\n\t\tcomposed->on_ready([](future &f) {\n\t\t\tBOOST_CHECK(f.is_ready());\n\t\t});\n\t\tBOOST_CHECK(!composed->is_ready());\n\t\tf1->fail(\"aiee\");\n\t\tBOOST_CHECK( composed->is_ready());\n\t\tBOOST_CHECK( composed->is_failed());\n\t}\n\t{\n\t\tstd::vector>> pending {\n\t\t\tfuture::create_shared(),\n\t\t\tfuture::create_shared(),\n\t\t\tfuture::create_shared(),\n\t\t\tfuture::create_shared(),\n\t\t\tfuture::create_shared(),\n\t\t\tfuture::create_shared()\n\t\t};\n\n\t\tauto composed = needs_all(\n\t\t\tpending\n\t\t);\n\t\tcomposed->on_ready([](future &f) {\n\t\t\tBOOST_CHECK(f.is_ready());\n\t\t});\n\t\tBOOST_CHECK(!composed->is_ready());\n\t\tint i = 0;\n\t\tfor(auto &it : pending) {\n\t\t\tit->done(++i);\n\t\t\tif(i == pending.size()) {\n\t\t\t\tBOOST_CHECK( composed->is_done());\n\t\t\t} else {\n\t\t\t\tBOOST_CHECK(!composed->is_ready());\n\t\t\t}\n\t\t}\n\t\tBOOST_CHECK( composed->is_ready());\n\t}\n}\n\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2009 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"base\/nss_init.h\"\n\n#include \n#include \n#include \n#include \n#include \n\n\/\/ Work around https:\/\/bugzilla.mozilla.org\/show_bug.cgi?id=455424\n\/\/ until NSS 3.12.2 comes out and we update to it.\n#define Lock FOO_NSS_Lock\n#include \n#include \n#include \n#undef Lock\n\n#include \"base\/file_util.h\"\n#include \"base\/logging.h\"\n#include \"base\/singleton.h\"\n#include \"base\/string_util.h\"\n\nnamespace {\n\nstd::string GetDefaultConfigDirectory() {\n const char* home = getenv(\"HOME\");\n if (home == NULL) {\n LOG(ERROR) << \"$HOME is not set.\";\n return \"\";\n }\n FilePath dir(home);\n dir = dir.AppendASCII(\".pki\").AppendASCII(\"nssdb\");\n if (!file_util::CreateDirectory(dir)) {\n LOG(ERROR) << \"Failed to create ~\/.pki\/nssdb directory.\";\n return \"\";\n }\n return dir.value();\n}\n\n\/\/ Load nss's built-in root certs.\nSECMODModule *InitDefaultRootCerts() {\n const char* kModulePath = \"libnssckbi.so\";\n char modparams[1024];\n snprintf(modparams, sizeof(modparams),\n \"name=\\\"Root Certs\\\" library=\\\"%s\\\"\", kModulePath);\n SECMODModule *root = SECMOD_LoadUserModule(modparams, NULL, PR_FALSE);\n if (root)\n return root;\n\n \/\/ Aw, snap. Can't find\/load root cert shared library.\n \/\/ This will make it hard to talk to anybody via https.\n NOTREACHED();\n return NULL;\n}\n\n\/\/ A singleton to initialize\/deinitialize NSPR.\n\/\/ Separate from the NSS singleton because we initialize NSPR on the UI thread.\nclass NSPRInitSingleton {\n public:\n NSPRInitSingleton() {\n PR_Init(PR_USER_THREAD, PR_PRIORITY_NORMAL, 0);\n }\n\n ~NSPRInitSingleton() {\n PRStatus prstatus = PR_Cleanup();\n if (prstatus != PR_SUCCESS) {\n LOG(ERROR) << \"PR_Cleanup failed; was NSPR initialized on wrong thread?\";\n }\n }\n};\n\nclass NSSInitSingleton {\n public:\n NSSInitSingleton() {\n base::EnsureNSPRInit();\n\n SECStatus status;\n std::string database_dir = GetDefaultConfigDirectory();\n if (!database_dir.empty()) {\n \/\/ Initialize with a persistant database (~\/.pki\/nssdb).\n \/\/ Use \"sql:\" which can be shared by multiple processes safely.\n status = NSS_InitReadWrite(\n StringPrintf(\"sql:%s\", database_dir.c_str()).c_str());\n } else {\n LOG(WARNING) << \"Initialize NSS without using a persistent database \"\n << \"(~\/.pki\/nssdb).\";\n status = NSS_NoDB_Init(\".\");\n }\n if (status != SECSuccess) {\n char buffer[513] = \"Couldn't retrieve error\";\n PRInt32 err_length = PR_GetErrorTextLength();\n if (err_length > 0 && static_cast(err_length) < sizeof(buffer))\n PR_GetErrorText(buffer);\n\n NOTREACHED() << \"Error initializing NSS: \" << buffer;\n }\n\n \/\/ If we haven't initialized the password for the NSS databases,\n \/\/ initialize an empty-string password so that we don't need to\n \/\/ log in.\n PK11SlotInfo* slot = PK11_GetInternalKeySlot();\n if (slot) {\n if (PK11_NeedUserInit(slot))\n PK11_InitPin(slot, NULL, NULL);\n PK11_FreeSlot(slot);\n }\n\n root_ = InitDefaultRootCerts();\n\n NSS_SetDomesticPolicy();\n\n \/\/ Use late binding to avoid scary but benign warning\n \/\/ \"Symbol `SSL_ImplementedCiphers' has different size in shared object,\n \/\/ consider re-linking\"\n const PRUint16* pSSL_ImplementedCiphers = static_cast(\n dlsym(RTLD_DEFAULT, \"SSL_ImplementedCiphers\"));\n if (pSSL_ImplementedCiphers == NULL) {\n NOTREACHED() << \"Can't get list of supported ciphers\";\n return;\n }\n\n \/\/ Explicitly enable exactly those ciphers with keys of at least 80 bits\n for (int i = 0; i < SSL_NumImplementedCiphers; i++) {\n SSLCipherSuiteInfo info;\n if (SSL_GetCipherSuiteInfo(pSSL_ImplementedCiphers[i], &info,\n sizeof(info)) == SECSuccess) {\n SSL_CipherPrefSetDefault(pSSL_ImplementedCiphers[i],\n (info.effectiveKeyBits >= 80));\n }\n }\n\n \/\/ Enable SSL\n SSL_OptionSetDefault(SSL_SECURITY, PR_TRUE);\n\n \/\/ All other SSL options are set per-session by SSLClientSocket.\n }\n\n ~NSSInitSingleton() {\n if (root_) {\n SECMOD_UnloadUserModule(root_);\n SECMOD_DestroyModule(root_);\n root_ = NULL;\n }\n\n \/\/ Have to clear the cache, or NSS_Shutdown fails with SEC_ERROR_BUSY\n SSL_ClearSessionCache();\n\n SECStatus status = NSS_Shutdown();\n if (status != SECSuccess) {\n \/\/ We LOG(INFO) because this failure is relatively harmless\n \/\/ (leaking, but we're shutting down anyway).\n LOG(INFO) << \"NSS_Shutdown failed; see \"\n \"http:\/\/code.google.com\/p\/chromium\/issues\/detail?id=4609\";\n }\n\n PL_ArenaFinish();\n }\n\n private:\n SECMODModule *root_;\n};\n\n} \/\/ namespace\n\nnamespace base {\n\nvoid EnsureNSPRInit() {\n Singleton::get();\n}\n\nvoid EnsureNSSInit() {\n Singleton::get();\n}\n\n} \/\/ namespace base\nIf NSS_InitReadWrite fails, fall back on NSS_NoDB_Init.\/\/ Copyright (c) 2008-2009 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"base\/nss_init.h\"\n\n#include \n#include \n#include \n#include \n#include \n\n\/\/ Work around https:\/\/bugzilla.mozilla.org\/show_bug.cgi?id=455424\n\/\/ until NSS 3.12.2 comes out and we update to it.\n#define Lock FOO_NSS_Lock\n#include \n#include \n#include \n#undef Lock\n\n#include \"base\/file_util.h\"\n#include \"base\/logging.h\"\n#include \"base\/singleton.h\"\n#include \"base\/string_util.h\"\n\nnamespace {\n\nstd::string GetDefaultConfigDirectory() {\n const char* home = getenv(\"HOME\");\n if (home == NULL) {\n LOG(ERROR) << \"$HOME is not set.\";\n return \"\";\n }\n FilePath dir(home);\n dir = dir.AppendASCII(\".pki\").AppendASCII(\"nssdb\");\n if (!file_util::CreateDirectory(dir)) {\n LOG(ERROR) << \"Failed to create ~\/.pki\/nssdb directory.\";\n return \"\";\n }\n return dir.value();\n}\n\n\/\/ Load nss's built-in root certs.\nSECMODModule *InitDefaultRootCerts() {\n const char* kModulePath = \"libnssckbi.so\";\n char modparams[1024];\n snprintf(modparams, sizeof(modparams),\n \"name=\\\"Root Certs\\\" library=\\\"%s\\\"\", kModulePath);\n SECMODModule *root = SECMOD_LoadUserModule(modparams, NULL, PR_FALSE);\n if (root)\n return root;\n\n \/\/ Aw, snap. Can't find\/load root cert shared library.\n \/\/ This will make it hard to talk to anybody via https.\n NOTREACHED();\n return NULL;\n}\n\n\/\/ A singleton to initialize\/deinitialize NSPR.\n\/\/ Separate from the NSS singleton because we initialize NSPR on the UI thread.\nclass NSPRInitSingleton {\n public:\n NSPRInitSingleton() {\n PR_Init(PR_USER_THREAD, PR_PRIORITY_NORMAL, 0);\n }\n\n ~NSPRInitSingleton() {\n PRStatus prstatus = PR_Cleanup();\n if (prstatus != PR_SUCCESS) {\n LOG(ERROR) << \"PR_Cleanup failed; was NSPR initialized on wrong thread?\";\n }\n }\n};\n\nclass NSSInitSingleton {\n public:\n NSSInitSingleton() {\n base::EnsureNSPRInit();\n\n SECStatus status = SECFailure;\n std::string database_dir = GetDefaultConfigDirectory();\n if (!database_dir.empty()) {\n \/\/ Initialize with a persistant database (~\/.pki\/nssdb).\n \/\/ Use \"sql:\" which can be shared by multiple processes safely.\n status = NSS_InitReadWrite(\n StringPrintf(\"sql:%s\", database_dir.c_str()).c_str());\n if (status != SECSuccess) {\n LOG(ERROR) << \"Error initializing NSS with a persistent \"\n \"databases: NSS error code \" << PR_GetError();\n }\n }\n if (status != SECSuccess) {\n LOG(WARNING) << \"Initialize NSS without a persistent database \"\n \"(~\/.pki\/nssdb).\";\n status = NSS_NoDB_Init(NULL);\n if (status != SECSuccess) {\n LOG(ERROR) << \"Error initializing NSS without a persistent \"\n \"database: NSS error code \" << PR_GetError();\n }\n }\n\n \/\/ If we haven't initialized the password for the NSS databases,\n \/\/ initialize an empty-string password so that we don't need to\n \/\/ log in.\n PK11SlotInfo* slot = PK11_GetInternalKeySlot();\n if (slot) {\n if (PK11_NeedUserInit(slot))\n PK11_InitPin(slot, NULL, NULL);\n PK11_FreeSlot(slot);\n }\n\n root_ = InitDefaultRootCerts();\n\n NSS_SetDomesticPolicy();\n\n \/\/ Use late binding to avoid scary but benign warning\n \/\/ \"Symbol `SSL_ImplementedCiphers' has different size in shared object,\n \/\/ consider re-linking\"\n const PRUint16* pSSL_ImplementedCiphers = static_cast(\n dlsym(RTLD_DEFAULT, \"SSL_ImplementedCiphers\"));\n if (pSSL_ImplementedCiphers == NULL) {\n NOTREACHED() << \"Can't get list of supported ciphers\";\n return;\n }\n\n \/\/ Explicitly enable exactly those ciphers with keys of at least 80 bits\n for (int i = 0; i < SSL_NumImplementedCiphers; i++) {\n SSLCipherSuiteInfo info;\n if (SSL_GetCipherSuiteInfo(pSSL_ImplementedCiphers[i], &info,\n sizeof(info)) == SECSuccess) {\n SSL_CipherPrefSetDefault(pSSL_ImplementedCiphers[i],\n (info.effectiveKeyBits >= 80));\n }\n }\n\n \/\/ Enable SSL\n SSL_OptionSetDefault(SSL_SECURITY, PR_TRUE);\n\n \/\/ All other SSL options are set per-session by SSLClientSocket.\n }\n\n ~NSSInitSingleton() {\n if (root_) {\n SECMOD_UnloadUserModule(root_);\n SECMOD_DestroyModule(root_);\n root_ = NULL;\n }\n\n \/\/ Have to clear the cache, or NSS_Shutdown fails with SEC_ERROR_BUSY\n SSL_ClearSessionCache();\n\n SECStatus status = NSS_Shutdown();\n if (status != SECSuccess) {\n \/\/ We LOG(INFO) because this failure is relatively harmless\n \/\/ (leaking, but we're shutting down anyway).\n LOG(INFO) << \"NSS_Shutdown failed; see \"\n \"http:\/\/code.google.com\/p\/chromium\/issues\/detail?id=4609\";\n }\n\n PL_ArenaFinish();\n }\n\n private:\n SECMODModule *root_;\n};\n\n} \/\/ namespace\n\nnamespace base {\n\nvoid EnsureNSPRInit() {\n Singleton::get();\n}\n\nvoid EnsureNSSInit() {\n Singleton::get();\n}\n\n} \/\/ namespace base\n<|endoftext|>"} {"text":"\/*-------------------------------------------------------------------------\n * Vulkan Conformance Tests\n * ------------------------\n *\n * Copyright (c) 2015 Google Inc.\n *\n * Permission is hereby granted, free of charge, to any person obtaining a\n * copy of this software and\/or associated documentation files (the\n * \"Materials\"), to deal in the Materials without restriction, including\n * without limitation the rights to use, copy, modify, merge, publish,\n * distribute, sublicense, and\/or sell copies of the Materials, and to\n * permit persons to whom the Materials are furnished to do so, subject to\n * the following conditions:\n *\n * The above copyright notice(s) and this permission notice shall be\n * included in all copies or substantial portions of the Materials.\n *\n * The Materials are Confidential Information as defined by the\n * Khronos Membership Agreement until designated non-confidential by\n * Khronos, at which point this condition clause shall be removed.\n *\n * THE MATERIALS ARE PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\n * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\n * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n * MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS.\n *\n *\/\/*!\n * \\file\n * \\brief Utility for pre-compiling source programs to SPIR-V\n *\/\/*--------------------------------------------------------------------*\/\n\n#include \"tcuDefs.hpp\"\n#include \"tcuCommandLine.hpp\"\n#include \"tcuPlatform.hpp\"\n#include \"tcuResource.hpp\"\n#include \"tcuTestLog.hpp\"\n#include \"tcuTestHierarchyIterator.hpp\"\n#include \"deUniquePtr.hpp\"\n#include \"vkPrograms.hpp\"\n#include \"vkBinaryRegistry.hpp\"\n#include \"vktTestCase.hpp\"\n#include \"vktTestPackage.hpp\"\n#include \"deUniquePtr.hpp\"\n#include \"deCommandLine.hpp\"\n\n#include \n\nnamespace vkt\n{\n\nusing std::vector;\nusing std::string;\nusing de::UniquePtr;\n\ntcu::TestPackageRoot* createRoot (tcu::TestContext& testCtx)\n{\n\tvector\tchildren;\n\tchildren.push_back(new TestPackage(testCtx));\n\treturn new tcu::TestPackageRoot(testCtx, children);\n}\n\nenum BuildMode\n{\n\tBUILDMODE_BUILD = 0,\n\tBUILDMODE_VERIFY,\n\n\tBUILDMODE_LAST\n};\n\nstruct BuildStats\n{\n\tint\t\tnumSucceeded;\n\tint\t\tnumFailed;\n\n\tBuildStats (void)\n\t\t: numSucceeded\t(0)\n\t\t, numFailed\t\t(0)\n\t{\n\t}\n};\n\nBuildStats buildPrograms (tcu::TestContext& testCtx, const std::string& dstPath, BuildMode mode)\n{\n\tconst UniquePtr\troot\t\t(createRoot(testCtx));\n\ttcu::DefaultHierarchyInflater\t\t\tinflater\t(testCtx);\n\ttcu::TestHierarchyIterator\t\t\t\titerator\t(*root, inflater, testCtx.getCommandLine());\n\tconst tcu::DirArchive\t\t\t\t\tsrcArchive\t(dstPath.c_str());\n\tUniquePtr\t\twriter\t\t(mode == BUILDMODE_BUILD\t? new vk::BinaryRegistryWriter(dstPath)\t\t\t: DE_NULL);\n\tUniquePtr\t\treader\t\t(mode == BUILDMODE_VERIFY\t? new vk::BinaryRegistryReader(srcArchive, \"\")\t: DE_NULL);\n\tBuildStats\t\t\t\t\t\t\t\tstats;\n\n\twhile (iterator.getState() != tcu::TestHierarchyIterator::STATE_FINISHED)\n\t{\n\t\tif (iterator.getState() == tcu::TestHierarchyIterator::STATE_ENTER_NODE &&\n\t\t\ttcu::isTestNodeTypeExecutable(iterator.getNode()->getNodeType()))\n\t\t{\n\t\t\tconst TestCase* const\t\ttestCase\t= dynamic_cast(iterator.getNode());\n\t\t\tconst string\t\t\t\tcasePath\t= iterator.getNodePath();\n\t\t\tvk::SourceCollection\t\tprogs;\n\n\t\t\ttcu::print(\"%s\\n\", casePath.c_str());\n\n\t\t\ttestCase->initPrograms(progs);\n\n\t\t\tfor (vk::SourceCollection::Iterator progIter = progs.begin(); progIter != progs.end(); ++progIter)\n\t\t\t{\n\t\t\t\ttry\n\t\t\t\t{\n\t\t\t\t\tconst vk::ProgramIdentifier\t\t\tprogId\t\t(casePath, progIter.getName());\n\t\t\t\t\tglu::ShaderProgramInfo\t\t\t\tbuildInfo;\n\t\t\t\t\tconst UniquePtr\tbinary\t\t(vk::buildProgram(progIter.getProgram(), vk::PROGRAM_FORMAT_SPIRV, &buildInfo));\n\n\t\t\t\t\tif (mode == BUILDMODE_BUILD)\n\t\t\t\t\t\twriter->storeProgram(progId, *binary);\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tDE_ASSERT(mode == BUILDMODE_VERIFY);\n\n\t\t\t\t\t\tconst UniquePtr\tstoredBinary\t(reader->loadProgram(progId));\n\n\t\t\t\t\t\tif (binary->getSize() != storedBinary->getSize())\n\t\t\t\t\t\t\tthrow tcu::Exception(\"Binary size doesn't match\");\n\n\t\t\t\t\t\tif (deMemCmp(binary->getBinary(), storedBinary->getBinary(), binary->getSize()))\n\t\t\t\t\t\t\tthrow tcu::Exception(\"Binary contents don't match\");\n\t\t\t\t\t}\n\n\t\t\t\t\ttcu::print(\" OK: %s\\n\", progIter.getName().c_str());\n\t\t\t\t\tstats.numSucceeded += 1;\n\t\t\t\t}\n\t\t\t\tcatch (const std::exception& e)\n\t\t\t\t{\n\t\t\t\t\ttcu::print(\" ERROR: %s: %s\\n\", progIter.getName().c_str(), e.what());\n\t\t\t\t\tstats.numFailed += 1;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\titerator.next();\n\t}\n\n\treturn stats;\n}\n\n} \/\/ vkt\n\nnamespace opt\n{\n\nDE_DECLARE_COMMAND_LINE_OPT(DstPath,\tstd::string);\nDE_DECLARE_COMMAND_LINE_OPT(Mode,\t\tvkt::BuildMode);\n\n} \/\/ opt\n\nvoid registerOptions (de::cmdline::Parser& parser)\n{\n\tusing de::cmdline::Option;\n\tusing de::cmdline::NamedValue;\n\n\tstatic const NamedValue s_modes[] =\n\t{\n\t\t{ \"build\",\tvkt::BUILDMODE_BUILD\t},\n\t\t{ \"verify\",\tvkt::BUILDMODE_VERIFY\t}\n\t};\n\n\tparser << Option\t(\"d\", \"dst-path\",\t\"Destination path\",\t\".\")\n\t\t << Option\t\t(\"m\", \"mode\",\t\t\"Build mode\",\t\ts_modes,\t\"build\");\n}\n\nint main (int argc, const char* argv[])\n{\n\tde::cmdline::CommandLine\tcmdLine;\n\n\t{\n\t\tde::cmdline::Parser\t\tparser;\n\t\tregisterOptions(parser);\n\t\tif (!parser.parse(argc, argv, &cmdLine, std::cerr))\n\t\t{\n\t\t\tparser.help(std::cout);\n\t\t\treturn -1;\n\t\t}\n\t}\n\n\ttry\n\t{\n\t\tconst tcu::CommandLine\tdeqpCmdLine\t\t(\"unused\");\n\t\ttcu::DirArchive\t\t\tarchive\t\t\t(\".\");\n\t\ttcu::TestLog\t\t\tlog\t\t\t\t(deqpCmdLine.getLogFileName(), deqpCmdLine.getLogFlags());\n\t\ttcu::Platform\t\t\tplatform;\n\t\ttcu::TestContext\t\ttestCtx\t\t\t(platform, archive, log, deqpCmdLine, DE_NULL);\n\n\t\tconst vkt::BuildStats\tstats\t\t\t= vkt::buildPrograms(testCtx, cmdLine.getOption(), cmdLine.getOption());\n\n\t\ttcu::print(\"DONE: %d passed, %d failed\\n\", stats.numSucceeded, stats.numFailed);\n\n\t\treturn stats.numFailed == 0 ? 0 : -1;\n\t}\n\tcatch (const std::exception& e)\n\t{\n\t\ttcu::die(\"%s\", e.what());\n\t}\n}\nAdd --verbose option to vk-build-programs\/*-------------------------------------------------------------------------\n * Vulkan Conformance Tests\n * ------------------------\n *\n * Copyright (c) 2015 Google Inc.\n *\n * Permission is hereby granted, free of charge, to any person obtaining a\n * copy of this software and\/or associated documentation files (the\n * \"Materials\"), to deal in the Materials without restriction, including\n * without limitation the rights to use, copy, modify, merge, publish,\n * distribute, sublicense, and\/or sell copies of the Materials, and to\n * permit persons to whom the Materials are furnished to do so, subject to\n * the following conditions:\n *\n * The above copyright notice(s) and this permission notice shall be\n * included in all copies or substantial portions of the Materials.\n *\n * The Materials are Confidential Information as defined by the\n * Khronos Membership Agreement until designated non-confidential by\n * Khronos, at which point this condition clause shall be removed.\n *\n * THE MATERIALS ARE PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\n * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\n * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n * MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS.\n *\n *\/\/*!\n * \\file\n * \\brief Utility for pre-compiling source programs to SPIR-V\n *\/\/*--------------------------------------------------------------------*\/\n\n#include \"tcuDefs.hpp\"\n#include \"tcuCommandLine.hpp\"\n#include \"tcuPlatform.hpp\"\n#include \"tcuResource.hpp\"\n#include \"tcuTestLog.hpp\"\n#include \"tcuTestHierarchyIterator.hpp\"\n#include \"deUniquePtr.hpp\"\n#include \"vkPrograms.hpp\"\n#include \"vkBinaryRegistry.hpp\"\n#include \"vktTestCase.hpp\"\n#include \"vktTestPackage.hpp\"\n#include \"deUniquePtr.hpp\"\n#include \"deCommandLine.hpp\"\n\n#include \n\nnamespace vkt\n{\n\nusing std::vector;\nusing std::string;\nusing de::UniquePtr;\n\ntcu::TestPackageRoot* createRoot (tcu::TestContext& testCtx)\n{\n\tvector\tchildren;\n\tchildren.push_back(new TestPackage(testCtx));\n\treturn new tcu::TestPackageRoot(testCtx, children);\n}\n\nenum BuildMode\n{\n\tBUILDMODE_BUILD = 0,\n\tBUILDMODE_VERIFY,\n\n\tBUILDMODE_LAST\n};\n\nstruct BuildStats\n{\n\tint\t\tnumSucceeded;\n\tint\t\tnumFailed;\n\n\tBuildStats (void)\n\t\t: numSucceeded\t(0)\n\t\t, numFailed\t\t(0)\n\t{\n\t}\n};\n\nBuildStats buildPrograms (tcu::TestContext& testCtx, const std::string& dstPath, BuildMode mode, bool verbose)\n{\n\tconst UniquePtr\troot\t\t(createRoot(testCtx));\n\ttcu::DefaultHierarchyInflater\t\t\tinflater\t(testCtx);\n\ttcu::TestHierarchyIterator\t\t\t\titerator\t(*root, inflater, testCtx.getCommandLine());\n\tconst tcu::DirArchive\t\t\t\t\tsrcArchive\t(dstPath.c_str());\n\tUniquePtr\t\twriter\t\t(mode == BUILDMODE_BUILD\t? new vk::BinaryRegistryWriter(dstPath)\t\t\t: DE_NULL);\n\tUniquePtr\t\treader\t\t(mode == BUILDMODE_VERIFY\t? new vk::BinaryRegistryReader(srcArchive, \"\")\t: DE_NULL);\n\tBuildStats\t\t\t\t\t\t\t\tstats;\n\tconst bool\t\t\t\t\t\t\t\tprintLogs\t= verbose;\n\n\twhile (iterator.getState() != tcu::TestHierarchyIterator::STATE_FINISHED)\n\t{\n\t\tif (iterator.getState() == tcu::TestHierarchyIterator::STATE_ENTER_NODE &&\n\t\t\ttcu::isTestNodeTypeExecutable(iterator.getNode()->getNodeType()))\n\t\t{\n\t\t\tconst TestCase* const\t\ttestCase\t= dynamic_cast(iterator.getNode());\n\t\t\tconst string\t\t\t\tcasePath\t= iterator.getNodePath();\n\t\t\tvk::SourceCollection\t\tprogs;\n\n\t\t\ttcu::print(\"%s\\n\", casePath.c_str());\n\n\t\t\ttestCase->initPrograms(progs);\n\n\t\t\tfor (vk::SourceCollection::Iterator progIter = progs.begin(); progIter != progs.end(); ++progIter)\n\t\t\t{\n\t\t\t\tglu::ShaderProgramInfo\tbuildInfo;\n\n\t\t\t\ttry\n\t\t\t\t{\n\t\t\t\t\tconst vk::ProgramIdentifier\t\t\tprogId\t\t(casePath, progIter.getName());\n\t\t\t\t\tconst UniquePtr\tbinary\t\t(vk::buildProgram(progIter.getProgram(), vk::PROGRAM_FORMAT_SPIRV, &buildInfo));\n\n\t\t\t\t\tif (mode == BUILDMODE_BUILD)\n\t\t\t\t\t\twriter->storeProgram(progId, *binary);\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tDE_ASSERT(mode == BUILDMODE_VERIFY);\n\n\t\t\t\t\t\tconst UniquePtr\tstoredBinary\t(reader->loadProgram(progId));\n\n\t\t\t\t\t\tif (binary->getSize() != storedBinary->getSize())\n\t\t\t\t\t\t\tthrow tcu::Exception(\"Binary size doesn't match\");\n\n\t\t\t\t\t\tif (deMemCmp(binary->getBinary(), storedBinary->getBinary(), binary->getSize()))\n\t\t\t\t\t\t\tthrow tcu::Exception(\"Binary contents don't match\");\n\t\t\t\t\t}\n\n\t\t\t\t\ttcu::print(\" OK: %s\\n\", progIter.getName().c_str());\n\t\t\t\t\tstats.numSucceeded += 1;\n\t\t\t\t}\n\t\t\t\tcatch (const std::exception& e)\n\t\t\t\t{\n\t\t\t\t\ttcu::print(\" ERROR: %s: %s\\n\", progIter.getName().c_str(), e.what());\n\n\t\t\t\t\tif (printLogs)\n\t\t\t\t\t{\n\t\t\t\t\t\tfor (size_t shaderNdx = 0; shaderNdx < buildInfo.shaders.size(); shaderNdx++)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tconst glu::ShaderInfo&\tshaderInfo\t= buildInfo.shaders[shaderNdx];\n\t\t\t\t\t\t\tconst char* const\t\tshaderName\t= getShaderTypeName(shaderInfo.type);\n\n\t\t\t\t\t\t\ttcu::print(\"%s source:\\n---\\n%s\\n---\\n\", shaderName, shaderInfo.source.c_str());\n\t\t\t\t\t\t\ttcu::print(\"%s compile log:\\n---\\n%s\\n---\\n\", shaderName, shaderInfo.infoLog.c_str());\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tstats.numFailed += 1;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\titerator.next();\n\t}\n\n\treturn stats;\n}\n\n} \/\/ vkt\n\nnamespace opt\n{\n\nDE_DECLARE_COMMAND_LINE_OPT(DstPath,\tstd::string);\nDE_DECLARE_COMMAND_LINE_OPT(Mode,\t\tvkt::BuildMode);\nDE_DECLARE_COMMAND_LINE_OPT(Verbose,\tbool);\n\n} \/\/ opt\n\nvoid registerOptions (de::cmdline::Parser& parser)\n{\n\tusing de::cmdline::Option;\n\tusing de::cmdline::NamedValue;\n\n\tstatic const NamedValue s_modes[] =\n\t{\n\t\t{ \"build\",\tvkt::BUILDMODE_BUILD\t},\n\t\t{ \"verify\",\tvkt::BUILDMODE_VERIFY\t}\n\t};\n\n\tparser << Option\t(\"d\", \"dst-path\",\t\"Destination path\",\t\"out\")\n\t\t << Option\t\t(\"m\", \"mode\",\t\t\"Build mode\",\t\ts_modes,\t\"build\")\n\t\t << Option\t(\"v\", \"verbose\",\t\"Verbose output\");\n}\n\nint main (int argc, const char* argv[])\n{\n\tde::cmdline::CommandLine\tcmdLine;\n\n\t{\n\t\tde::cmdline::Parser\t\tparser;\n\t\tregisterOptions(parser);\n\t\tif (!parser.parse(argc, argv, &cmdLine, std::cerr))\n\t\t{\n\t\t\tparser.help(std::cout);\n\t\t\treturn -1;\n\t\t}\n\t}\n\n\ttry\n\t{\n\t\tconst tcu::CommandLine\tdeqpCmdLine\t\t(\"unused\");\n\t\ttcu::DirArchive\t\t\tarchive\t\t\t(\".\");\n\t\ttcu::TestLog\t\t\tlog\t\t\t\t(deqpCmdLine.getLogFileName(), deqpCmdLine.getLogFlags());\n\t\ttcu::Platform\t\t\tplatform;\n\t\ttcu::TestContext\t\ttestCtx\t\t\t(platform, archive, log, deqpCmdLine, DE_NULL);\n\n\t\tconst vkt::BuildStats\tstats\t\t\t= vkt::buildPrograms(testCtx,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t cmdLine.getOption(),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t cmdLine.getOption(),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t cmdLine.getOption());\n\n\t\ttcu::print(\"DONE: %d passed, %d failed\\n\", stats.numSucceeded, stats.numFailed);\n\n\t\treturn stats.numFailed == 0 ? 0 : -1;\n\t}\n\tcatch (const std::exception& e)\n\t{\n\t\ttcu::die(\"%s\", e.what());\n\t}\n}\n<|endoftext|>"} {"text":"\/\/$Id: ResultsPostProcessor.h 3456 2013-06-26 02:11:13Z Jamshid $\n\n\/*\n * The Software is made available solely for use according to the License Agreement. Any reproduction\n * or redistribution of the Software not in accordance with the License Agreement is expressly prohibited\n * by law, and may result in severe civil and criminal penalties. Violators will be prosecuted to the\n * maximum extent possible.\n *\n * THE SOFTWARE IS WARRANTED, IF AT ALL, ONLY ACCORDING TO THE TERMS OF THE LICENSE AGREEMENT. EXCEPT\n * AS WARRANTED IN THE LICENSE AGREEMENT, SRCH2 INC. HEREBY DISCLAIMS ALL WARRANTIES AND CONDITIONS WITH\n * REGARD TO THE SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES AND CONDITIONS OF MERCHANTABILITY, FITNESS\n * FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT SHALL SRCH2 INC. BE LIABLE FOR ANY\n * SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA\n * OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER ACTION, ARISING OUT OF OR IN CONNECTION\n * WITH THE USE OR PERFORMANCE OF SOFTWARE.\n\n * Copyright © 2010 SRCH2 Inc. All rights reserved\n *\/\n\n#include \"FacetedSearchFilterInternal.h\"\n#include \n#include \n#include \n#include \n#include \"util\/Assert.h\"\n#include \"instantsearch\/Score.h\"\n\nusing namespace std;\nnamespace srch2 {\nnamespace instantsearch {\n\nvoid FacetedSearchFilterInternal::doAggregationCategorical(const Score & attributeValue,\n std::map * counts) {\n\n \/\/ move on computed facet results to see if this value is seen before (increment) or is new (add and initialize)\n\tstd::string attributeValueLowerCase = attributeValue.toString();\n\tstd::transform(attributeValueLowerCase.begin(), attributeValueLowerCase.end(), attributeValueLowerCase.begin(), ::tolower);\n std::map::iterator p = counts->find(attributeValueLowerCase);\n if( p != counts->end()){\n p->second ++;\n return;\n }\n \/\/ not found in map, initialization with 1\n (*counts)[attributeValueLowerCase] = 1;\n return;\n}\n\n\/\/ Range facet\nvoid FacetedSearchFilterInternal::doAggregationRange(const Score & attributeValue,\n const std::vector & lowerBounds,\n std::vector > * counts , Score & start, Score & end, Score & gap) {\n\n unsigned groupId = attributeValue.findIndexOfContainingInterval(start,end, gap);\n if(groupId == -1){\n return;\n }\n if(groupId >= counts->size()){\n groupId = counts->size() - 1;\n }\n counts->at(groupId).second ++ ;\n return;\n}\n\n\/*\n * Example :\n * If we have two attributes : price,model (facet type : range, categorical)\n * and start,end and gap for price are 1,100 and 10. Then this function\n * produces an empty vector for model (because it's categorical) and a vector with the following\n * values for price:\n * -large_value, 1, 11, 21, 31, 41, ..., 91, 101\n *\/\nvoid FacetedSearchFilterInternal::prepareFacetInputs(IndexSearcher *indexSearcher) {\n\n if(isPrepared){\n return;\n }else{\n isPrepared = true;\n }\n\n IndexSearcherInternal * indexSearcherInternal =\n dynamic_cast(indexSearcher);\n Schema * schema = indexSearcherInternal->getSchema();\n ForwardIndex * forwardIndex = indexSearcherInternal->getForwardIndex();\n\n\n \/\/ 1. parse the values into Score.\n unsigned fieldIndex = 0;\n for (std::vector::iterator field = this->fields.begin();\n field != this->fields.end(); ++field) {\n if (this->facetTypes.at(fieldIndex) == FacetTypeCategorical) { \/\/ Simple facet\n Score placeHolder; \/\/ just insert placeholders\n rangeStartScores.push_back(placeHolder);\n rangeEndScores.push_back(placeHolder);\n rangeGapScores.push_back(placeHolder);\n } else { \/\/ Range facet\n FilterType attributeType = schema->getTypeOfNonSearchableAttribute(\n schema->getNonSearchableAttributeId(*field));\n Score start;\n start.setScore(attributeType, this->rangeStarts.at(fieldIndex));\n\n Score end;\n end.setScore(attributeType, this->rangeEnds.at(fieldIndex));\n\n Score gap;\n if(attributeType == ATTRIBUTE_TYPE_TIME){\n \t\/\/ For time attributes gap should not be of the same type, it should be\n \t\/\/ of type TimeDuration.\n \tif(start > end){ \/\/ start should not be greater than end\n \t\tstart = end;\n \t\tgap.setScore(ATTRIBUTE_TYPE_DURATION, \"00:00:00\");\n \t}else{\n \t\tgap.setScore(ATTRIBUTE_TYPE_DURATION, this->rangeGaps.at(fieldIndex));\n \t}\n }else{\n \tif(start > end){ \/\/ start should not be greater than end\n \t\tstart = end;\n \t\tgap.setScore(attributeType , \"0\");\n \t}else{\n \t\tgap.setScore(attributeType, this->rangeGaps.at(fieldIndex));\n \t}\n }\n\n rangeStartScores.push_back(start);\n rangeEndScores.push_back(end);\n rangeGapScores.push_back(gap);\n\n }\n\n \/\/\n fieldIndex++;\n }\n\n \/\/ 2. create the lowerbound vector for each attribute\n\n unsigned facetTypeIndex = 0;\n for (std::vector::iterator facetTypeIterator = facetTypes.begin();\n facetTypeIterator != facetTypes.end(); ++facetTypeIterator) {\n\n std::vector lowerBounds;\n\t\tScore & start = rangeStartScores.at(facetTypeIndex);\n\t\tScore & end = rangeEndScores.at(facetTypeIndex);\n\t\tScore & gap = rangeGapScores.at(facetTypeIndex);\n\t\tScore lowerBoundToAdd = start;\n switch (*facetTypeIterator) {\n case FacetTypeCategorical: \/\/ lower bounds vector is empty, because lower bounds are not determined before results\n break;\n\n case FacetTypeRange:\n ASSERT(start.getType() != srch2::instantsearch::ATTRIBUTE_TYPE_TEXT);\n\n \/\/ Example : start : 1, gap : 10 , end : 100\n \/\/ first -large_value is added as the first category\n \/\/ then 1, 11, 21, ...and 91 are added in the loop.\n \/\/ and 101 is added after loop.\n lowerBounds.push_back(lowerBoundToAdd.minimumValue()); \/\/ to collect data smaller than start\n while (lowerBoundToAdd < end) {\n lowerBounds.push_back(lowerBoundToAdd); \/\/ data of normal categories\n lowerBoundToAdd = lowerBoundToAdd + gap;\n }\n lowerBounds.push_back(end); \/\/ to collect data greater than end\n break;\n default:\n \tASSERT(false);\n \tbreak;\n }\n lowerBoundsOfIntervals[fields.at(facetTypeIndex)] = lowerBounds;\n \/\/\n facetTypeIndex++;\n }\n\n}\n\n}\n}\nA bug is fixed.\/\/$Id: ResultsPostProcessor.h 3456 2013-06-26 02:11:13Z Jamshid $\n\n\/*\n * The Software is made available solely for use according to the License Agreement. Any reproduction\n * or redistribution of the Software not in accordance with the License Agreement is expressly prohibited\n * by law, and may result in severe civil and criminal penalties. Violators will be prosecuted to the\n * maximum extent possible.\n *\n * THE SOFTWARE IS WARRANTED, IF AT ALL, ONLY ACCORDING TO THE TERMS OF THE LICENSE AGREEMENT. EXCEPT\n * AS WARRANTED IN THE LICENSE AGREEMENT, SRCH2 INC. HEREBY DISCLAIMS ALL WARRANTIES AND CONDITIONS WITH\n * REGARD TO THE SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES AND CONDITIONS OF MERCHANTABILITY, FITNESS\n * FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT SHALL SRCH2 INC. BE LIABLE FOR ANY\n * SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA\n * OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER ACTION, ARISING OUT OF OR IN CONNECTION\n * WITH THE USE OR PERFORMANCE OF SOFTWARE.\n\n * Copyright © 2010 SRCH2 Inc. All rights reserved\n *\/\n\n#include \"FacetedSearchFilterInternal.h\"\n#include \n#include \n#include \n#include \n#include \"util\/Assert.h\"\n#include \"instantsearch\/Score.h\"\n\nusing namespace std;\nnamespace srch2 {\nnamespace instantsearch {\n\nvoid FacetedSearchFilterInternal::doAggregationCategorical(const Score & attributeValue,\n std::map * counts) {\n\n \/\/ move on computed facet results to see if this value is seen before (increment) or is new (add and initialize)\n\tstd::string attributeValueLowerCase = attributeValue.toString();\n\tstd::transform(attributeValueLowerCase.begin(), attributeValueLowerCase.end(), attributeValueLowerCase.begin(), ::tolower);\n std::map::iterator p = counts->find(attributeValueLowerCase);\n if( p != counts->end()){\n p->second ++;\n return;\n }\n \/\/ not found in map, initialization with 1\n (*counts)[attributeValueLowerCase] = 1;\n return;\n}\n\n\/\/ Range facet\nvoid FacetedSearchFilterInternal::doAggregationRange(const Score & attributeValue,\n const std::vector & lowerBounds,\n std::vector > * counts , Score & start, Score & end, Score & gap) {\n\n\t\/\/ the reason for this is that the interval right before end can be smaller than gap. So the formula used in\n\t\/\/ findIndexOfContainingInterval will return a wrong index.\n\t\/\/ example:\n\t\/\/ start = 0 ; gap = 6; end = 10\n\t\/\/ intervals will be (*,0) , [0,6), [6,10), [10,*)\n\t\/\/ interval [6,10) is smaller than gap. now if we use formula (value - start ) \/ gap + 1\n\t\/\/ for 10 or 11, it returns 2 which is wrong.\n\tif(attributeValue >= end){\n\t\tunsigned groupId = counts->size() - 1;\n\t counts->at(groupId).second ++ ;\n\t return;\n\t}\n unsigned groupId = attributeValue.findIndexOfContainingInterval(start,end, gap);\n if(groupId == -1){\n return;\n }\n if(groupId >= counts->size()){\n groupId = counts->size() - 1;\n }\n counts->at(groupId).second ++ ;\n return;\n}\n\n\/*\n * Example :\n * If we have two attributes : price,model (facet type : range, categorical)\n * and start,end and gap for price are 1,100 and 10. Then this function\n * produces an empty vector for model (because it's categorical) and a vector with the following\n * values for price:\n * -large_value, 1, 11, 21, 31, 41, ..., 91, 101\n *\/\nvoid FacetedSearchFilterInternal::prepareFacetInputs(IndexSearcher *indexSearcher) {\n\n if(isPrepared){\n return;\n }else{\n isPrepared = true;\n }\n\n IndexSearcherInternal * indexSearcherInternal =\n dynamic_cast(indexSearcher);\n Schema * schema = indexSearcherInternal->getSchema();\n ForwardIndex * forwardIndex = indexSearcherInternal->getForwardIndex();\n\n\n \/\/ 1. parse the values into Score.\n unsigned fieldIndex = 0;\n for (std::vector::iterator field = this->fields.begin();\n field != this->fields.end(); ++field) {\n if (this->facetTypes.at(fieldIndex) == FacetTypeCategorical) { \/\/ Simple facet\n Score placeHolder; \/\/ just insert placeholders\n rangeStartScores.push_back(placeHolder);\n rangeEndScores.push_back(placeHolder);\n rangeGapScores.push_back(placeHolder);\n } else { \/\/ Range facet\n FilterType attributeType = schema->getTypeOfNonSearchableAttribute(\n schema->getNonSearchableAttributeId(*field));\n Score start;\n start.setScore(attributeType, this->rangeStarts.at(fieldIndex));\n\n Score end;\n end.setScore(attributeType, this->rangeEnds.at(fieldIndex));\n\n Score gap;\n if(attributeType == ATTRIBUTE_TYPE_TIME){\n \t\/\/ For time attributes gap should not be of the same type, it should be\n \t\/\/ of type TimeDuration.\n \tif(start > end){ \/\/ start should not be greater than end\n \t\tstart = end;\n \t\tgap.setScore(ATTRIBUTE_TYPE_DURATION, \"00:00:00\");\n \t}else{\n \t\tgap.setScore(ATTRIBUTE_TYPE_DURATION, this->rangeGaps.at(fieldIndex));\n \t}\n }else{\n \tif(start > end){ \/\/ start should not be greater than end\n \t\tstart = end;\n \t\tgap.setScore(attributeType , \"0\");\n \t}else{\n \t\tgap.setScore(attributeType, this->rangeGaps.at(fieldIndex));\n \t}\n }\n\n rangeStartScores.push_back(start);\n rangeEndScores.push_back(end);\n rangeGapScores.push_back(gap);\n\n }\n\n \/\/\n fieldIndex++;\n }\n\n \/\/ 2. create the lowerbound vector for each attribute\n\n unsigned facetTypeIndex = 0;\n for (std::vector::iterator facetTypeIterator = facetTypes.begin();\n facetTypeIterator != facetTypes.end(); ++facetTypeIterator) {\n\n std::vector lowerBounds;\n\t\tScore & start = rangeStartScores.at(facetTypeIndex);\n\t\tScore & end = rangeEndScores.at(facetTypeIndex);\n\t\tScore & gap = rangeGapScores.at(facetTypeIndex);\n\t\tScore lowerBoundToAdd = start;\n switch (*facetTypeIterator) {\n case FacetTypeCategorical: \/\/ lower bounds vector is empty, because lower bounds are not determined before results\n break;\n\n case FacetTypeRange:\n ASSERT(start.getType() != srch2::instantsearch::ATTRIBUTE_TYPE_TEXT);\n\n \/\/ Example : start : 1, gap : 10 , end : 100\n \/\/ first -large_value is added as the first category\n \/\/ then 1, 11, 21, ...and 91 are added in the loop.\n \/\/ and 101 is added after loop.\n lowerBounds.push_back(lowerBoundToAdd.minimumValue()); \/\/ to collect data smaller than start\n while (lowerBoundToAdd < end) {\n lowerBounds.push_back(lowerBoundToAdd); \/\/ data of normal categories\n lowerBoundToAdd = lowerBoundToAdd + gap;\n }\n lowerBounds.push_back(end); \/\/ to collect data greater than end\n break;\n default:\n \tASSERT(false);\n \tbreak;\n }\n lowerBoundsOfIntervals[fields.at(facetTypeIndex)] = lowerBounds;\n \/\/\n facetTypeIndex++;\n }\n\n}\n\n}\n}\n<|endoftext|>"} {"text":"#include \"ConfigActivationManager.h\"\n#include \"System\/Events\/EventLoop.h\"\n#include \"Application\/Common\/DatabaseConsts.h\"\n#include \"Application\/Common\/ContextTransport.h\"\n#include \"ConfigServer.h\"\n#include \"ConfigQuorumProcessor.h\"\n\nvoid ConfigActivationManager::Init(ConfigServer* configServer_)\n{\n configServer = configServer_;\n \n activationTimeout.SetCallable(MFUNC(ConfigActivationManager, OnActivationTimeout));\n}\n\nvoid ConfigActivationManager::TryDeactivateShardServer(uint64_t nodeID)\n{\n ConfigState* configState;\n ConfigQuorum* itQuorum;\n ConfigShardServer* shardServer;\n\n configState = configServer->GetDatabaseManager()->GetConfigState();\n\n FOREACH(itQuorum, configState->quorums)\n {\n if (itQuorum->isActivatingNode && itQuorum->activatingNodeID == nodeID)\n {\n shardServer = configState->GetShardServer(itQuorum->activatingNodeID);\n assert(shardServer != NULL);\n\n itQuorum->ClearActivation();\n UpdateTimeout();\n\n Log_Message(\"Activation failed for shard server %U and quorum %U...\",\n itQuorum->quorumID, itQuorum->activatingNodeID);\n }\n\n if (itQuorum->IsActiveMember(nodeID))\n {\n \/\/ if this node was part of an activation process, cancel it\n if (itQuorum->isActivatingNode)\n {\n shardServer = configState->GetShardServer(itQuorum->activatingNodeID);\n assert(shardServer != NULL);\n\n itQuorum->ClearActivation();\n UpdateTimeout();\n\n Log_Message(\"Activation failed for shard server %U and quorum %U...\",\n itQuorum->activatingNodeID, itQuorum->quorumID);\n }\n \n configServer->GetQuorumProcessor()->DeactivateNode(itQuorum->quorumID, nodeID);\n }\n }\n}\n\nvoid ConfigActivationManager::TryActivateShardServer(uint64_t nodeID, bool force)\n{\n uint64_t paxosID;\n ConfigState* configState;\n ConfigQuorum* itQuorum;\n ConfigShardServer* shardServer;\n uint64_t now;\n \n now = EventLoop::Now();\n \n Log_Trace();\n\n configState = configServer->GetDatabaseManager()->GetConfigState();\n shardServer = configState->GetShardServer(nodeID);\n\n FOREACH(itQuorum, configState->quorums)\n {\n Log_Trace(\"itQuorum->isActivatingNode: %b\", itQuorum->isActivatingNode);\n if (itQuorum->isActivatingNode)\n continue;\n \n Log_Trace(\"itQuorum->hasPrimary: %b\", itQuorum->hasPrimary);\n if (!itQuorum->hasPrimary)\n continue;\n\n if (itQuorum->IsInactiveMember(nodeID))\n {\n paxosID = QuorumInfo::GetQuorumInfo(shardServer->quorumInfos, itQuorum->quorumID)->paxosID;\n if (paxosID >= (itQuorum->paxosID - RLOG_REACTIVATION_DIFF) ||\n itQuorum->paxosID <= RLOG_REACTIVATION_DIFF)\n {\n if (!force && !shardServer->tryAutoActivation)\n continue;\n\n \/\/ the shard server is \"almost caught up\", start the activation process\n itQuorum->OnActivationStart(nodeID, now + ACTIVATION_TIMEOUT);\n UpdateTimeout();\n \n shardServer->tryAutoActivation = false;\n\n Log_Message(\"Activation started for shard server %U and quorum %U...\",\n itQuorum->activatingNodeID, itQuorum->quorumID);\n configServer->OnConfigStateChanged(false);\n }\n }\n } \n}\n\nvoid ConfigActivationManager::OnExtendLease(ConfigQuorum& quorum, ClusterMessage& message)\n{\n ConfigState* configState;\n ConfigShardServer* shardServer;\n\n Log_Trace();\n\n if (!quorum.hasPrimary || message.nodeID != quorum.primaryID)\n return;\n\n configState = configServer->GetDatabaseManager()->GetConfigState();\n\n if (!quorum.isActivatingNode || quorum.isReplicatingActivation ||\n message.configID != quorum.configID)\n {\n Log_Trace(\"ExtendLease condition: %b %b %U %U\", quorum.isActivatingNode,\n quorum.isReplicatingActivation,\n message.configID,\n quorum.configID); \n return;\n }\n \n if (!quorum.isWatchingPaxosID)\n {\n Log_Message(\"Activating shard server %U in quorum %U: Starting to monitor the primary's paxosID\",\n quorum.quorumID, quorum.activatingNodeID);\n \n quorum.OnActivationMonitoring(message.paxosID);\n configServer->OnConfigStateChanged(false);\n }\n else\n {\n Log_Trace();\n \n \/\/ if the primary was able to increase its paxosID, the new shardserver joined successfully\n if (message.paxosID > quorum.activationPaxosID)\n {\n Log_Message(\"Activating shard server %U in quorum %U: The primary was able to increase its paxosID!\",\n quorum.quorumID, quorum.activatingNodeID);\n \n quorum.OnActivationReplication();\n configServer->OnConfigStateChanged(false);\n configServer->GetQuorumProcessor()->ActivateNode(quorum.quorumID, quorum.activatingNodeID);\n\n shardServer = configState->GetShardServer(quorum.activatingNodeID);\n shardServer->tryAutoActivation = true;\n }\n else\n {\n Log_Message(\"Activating shard server %U in quorum %U: The primary was not able to increase its paxosID so far...\",\n quorum.quorumID, quorum.activatingNodeID);\n }\n } \n}\n\nvoid ConfigActivationManager::OnActivationTimeout()\n{\n uint64_t now;\n ConfigState* configState;\n ConfigQuorum* itQuorum;\n ConfigShardServer* shardServer;\n \n Log_Trace();\n \n now = EventLoop::Now();\n configState = configServer->GetDatabaseManager()->GetConfigState();\n \n FOREACH(itQuorum, configState->quorums)\n {\n if (itQuorum->activationExpireTime > 0 && itQuorum->activationExpireTime < now)\n {\n \/\/ stop activation\n \n assert(itQuorum->isActivatingNode == true);\n assert(itQuorum->isReplicatingActivation == false);\n\n shardServer = configState->GetShardServer(itQuorum->activatingNodeID);\n assert(shardServer != NULL);\n\n Log_Message(\"Activating shard server %U in quorum %U: Activation failed...\",\n itQuorum->activatingNodeID, itQuorum->quorumID);\n\n itQuorum->ClearActivation();\n \n configServer->OnConfigStateChanged(false);\n }\n }\n \n UpdateTimeout();\n}\n\nvoid ConfigActivationManager::UpdateTimeout()\n{\n ConfigQuorum* it;\n uint64_t activationExpireTime;\n \n Log_Trace();\n \n activationExpireTime = 0;\n FOREACH(it, configServer->GetDatabaseManager()->GetConfigState()->quorums)\n {\n if (it->isActivatingNode && !it->isReplicatingActivation)\n {\n if (activationExpireTime == 0 || it->activationExpireTime < activationExpireTime)\n activationExpireTime = it->activationExpireTime;\n }\n }\n \n if (activationExpireTime > 0)\n {\n activationTimeout.SetExpireTime(activationExpireTime);\n EventLoop::Reset(&activationTimeout);\n }\n}\nFixed Log_Debugs.#include \"ConfigActivationManager.h\"\n#include \"System\/Events\/EventLoop.h\"\n#include \"Application\/Common\/DatabaseConsts.h\"\n#include \"Application\/Common\/ContextTransport.h\"\n#include \"ConfigServer.h\"\n#include \"ConfigQuorumProcessor.h\"\n\nvoid ConfigActivationManager::Init(ConfigServer* configServer_)\n{\n configServer = configServer_;\n \n activationTimeout.SetCallable(MFUNC(ConfigActivationManager, OnActivationTimeout));\n}\n\nvoid ConfigActivationManager::TryDeactivateShardServer(uint64_t nodeID)\n{\n ConfigState* configState;\n ConfigQuorum* itQuorum;\n ConfigShardServer* shardServer;\n\n configState = configServer->GetDatabaseManager()->GetConfigState();\n\n FOREACH(itQuorum, configState->quorums)\n {\n if (itQuorum->isActivatingNode && itQuorum->activatingNodeID == nodeID)\n {\n shardServer = configState->GetShardServer(itQuorum->activatingNodeID);\n assert(shardServer != NULL);\n\n itQuorum->ClearActivation();\n UpdateTimeout();\n\n Log_Message(\"Activation failed for shard server %U and quorum %U...\",\n itQuorum->quorumID, itQuorum->activatingNodeID);\n }\n\n if (itQuorum->IsActiveMember(nodeID))\n {\n \/\/ if this node was part of an activation process, cancel it\n if (itQuorum->isActivatingNode)\n {\n shardServer = configState->GetShardServer(itQuorum->activatingNodeID);\n assert(shardServer != NULL);\n\n itQuorum->ClearActivation();\n UpdateTimeout();\n\n Log_Message(\"Activation failed for shard server %U and quorum %U...\",\n itQuorum->activatingNodeID, itQuorum->quorumID);\n }\n \n configServer->GetQuorumProcessor()->DeactivateNode(itQuorum->quorumID, nodeID);\n }\n }\n}\n\nvoid ConfigActivationManager::TryActivateShardServer(uint64_t nodeID, bool force)\n{\n uint64_t paxosID;\n ConfigState* configState;\n ConfigQuorum* itQuorum;\n ConfigShardServer* shardServer;\n uint64_t now;\n \n now = EventLoop::Now();\n \n Log_Trace();\n\n configState = configServer->GetDatabaseManager()->GetConfigState();\n shardServer = configState->GetShardServer(nodeID);\n\n FOREACH(itQuorum, configState->quorums)\n {\n Log_Trace(\"itQuorum->isActivatingNode: %b\", itQuorum->isActivatingNode);\n if (itQuorum->isActivatingNode)\n continue;\n \n Log_Trace(\"itQuorum->hasPrimary: %b\", itQuorum->hasPrimary);\n if (!itQuorum->hasPrimary)\n continue;\n\n if (itQuorum->IsInactiveMember(nodeID))\n {\n paxosID = QuorumInfo::GetQuorumInfo(shardServer->quorumInfos, itQuorum->quorumID)->paxosID;\n if (paxosID >= (itQuorum->paxosID - RLOG_REACTIVATION_DIFF) ||\n itQuorum->paxosID <= RLOG_REACTIVATION_DIFF)\n {\n if (!force && !shardServer->tryAutoActivation)\n continue;\n\n \/\/ the shard server is \"almost caught up\", start the activation process\n itQuorum->OnActivationStart(nodeID, now + ACTIVATION_TIMEOUT);\n UpdateTimeout();\n \n shardServer->tryAutoActivation = false;\n\n Log_Message(\"Activation started for shard server %U and quorum %U...\",\n itQuorum->activatingNodeID, itQuorum->quorumID);\n configServer->OnConfigStateChanged(false);\n }\n }\n } \n}\n\nvoid ConfigActivationManager::OnExtendLease(ConfigQuorum& quorum, ClusterMessage& message)\n{\n ConfigState* configState;\n ConfigShardServer* shardServer;\n\n Log_Trace();\n\n if (!quorum.hasPrimary || message.nodeID != quorum.primaryID)\n return;\n\n configState = configServer->GetDatabaseManager()->GetConfigState();\n\n if (!quorum.isActivatingNode || quorum.isReplicatingActivation ||\n message.configID != quorum.configID)\n {\n Log_Trace(\"ExtendLease condition: %b %b %U %U\", quorum.isActivatingNode,\n quorum.isReplicatingActivation,\n message.configID,\n quorum.configID); \n return;\n }\n \n if (!quorum.isWatchingPaxosID)\n {\n Log_Message(\"Activating shard server %U in quorum %U: Starting to monitor the primary's paxosID\",\n quorum.activatingNodeID, quorum.quorumID);\n \n quorum.OnActivationMonitoring(message.paxosID);\n configServer->OnConfigStateChanged(false);\n }\n else\n {\n Log_Trace();\n \n \/\/ if the primary was able to increase its paxosID, the new shardserver joined successfully\n if (message.paxosID > quorum.activationPaxosID)\n {\n Log_Message(\"Activating shard server %U in quorum %U: The primary was able to increase its paxosID!\",\n quorum.activatingNodeID, quorum.quorumID);\n \n quorum.OnActivationReplication();\n configServer->OnConfigStateChanged(false);\n configServer->GetQuorumProcessor()->ActivateNode(quorum.quorumID, quorum.activatingNodeID);\n\n shardServer = configState->GetShardServer(quorum.activatingNodeID);\n shardServer->tryAutoActivation = true;\n }\n else\n {\n Log_Message(\"Activating shard server %U in quorum %U: The primary was not able to increase its paxosID so far...\",\n quorum.activatingNodeID, quorum.quorumID);\n }\n } \n}\n\nvoid ConfigActivationManager::OnActivationTimeout()\n{\n uint64_t now;\n ConfigState* configState;\n ConfigQuorum* itQuorum;\n ConfigShardServer* shardServer;\n \n Log_Trace();\n \n now = EventLoop::Now();\n configState = configServer->GetDatabaseManager()->GetConfigState();\n \n FOREACH(itQuorum, configState->quorums)\n {\n if (itQuorum->activationExpireTime > 0 && itQuorum->activationExpireTime < now)\n {\n \/\/ stop activation\n \n assert(itQuorum->isActivatingNode == true);\n assert(itQuorum->isReplicatingActivation == false);\n\n shardServer = configState->GetShardServer(itQuorum->activatingNodeID);\n assert(shardServer != NULL);\n\n Log_Message(\"Activating shard server %U in quorum %U: Activation failed...\",\n itQuorum->activatingNodeID, itQuorum->quorumID);\n\n itQuorum->ClearActivation();\n \n configServer->OnConfigStateChanged(false);\n }\n }\n \n UpdateTimeout();\n}\n\nvoid ConfigActivationManager::UpdateTimeout()\n{\n ConfigQuorum* it;\n uint64_t activationExpireTime;\n \n Log_Trace();\n \n activationExpireTime = 0;\n FOREACH(it, configServer->GetDatabaseManager()->GetConfigState()->quorums)\n {\n if (it->isActivatingNode && !it->isReplicatingActivation)\n {\n if (activationExpireTime == 0 || it->activationExpireTime < activationExpireTime)\n activationExpireTime = it->activationExpireTime;\n }\n }\n \n if (activationExpireTime > 0)\n {\n activationTimeout.SetExpireTime(activationExpireTime);\n EventLoop::Reset(&activationTimeout);\n }\n}\n<|endoftext|>"} {"text":"\/\/=====================================================================\/\/\n\/*!\t@file\n\t@brief\tLCD 表示を使ったファイラー・サンプル @n\n\t\t\tST7565(R)、128 x 64 ピクセルの液晶を接続 @n\n\t\t\t\/CS ---> P53 (36) @n\n\t\t\tA0 ---> P50 (33) @n\n\t\t\tSD ---> P13\/SO20 (43) @n\n\t\t\tSCL ---> P15\/SCK20 (41) @n \n\t\t\t\/RES ---> \/RESET ( 6)\n\t@author\t平松邦仁 (hira@rvf-rc45.net)\n*\/\n\/\/=====================================================================\/\/\n#include \n#include \"G13\/system.hpp\"\n#include \"common\/port_utils.hpp\"\n#include \"common\/fifo.hpp\"\n#include \"common\/uart_io.hpp\"\n#include \"common\/itimer.hpp\"\n#include \"common\/format.hpp\"\n#include \"common\/delay.hpp\"\n#include \"common\/monograph.hpp\"\n#include \"common\/font6x12.hpp\"\n#include \"common\/kfont12.hpp\"\n#include \"common\/sdc_io.hpp\"\n\n\/\/ ターゲットLCDのタイプを選択\n#define LCD_ST7565\n\/\/ #define LCD_SSD1306\n#ifdef LCD_ST7565\n#include \"chip\/ST7565.hpp\"\n#endif\n#ifdef LCD_SSD1306\n#include \"chip\/SSD1306.hpp\"\n#endif\n\nnamespace {\n\t\/\/ 送信、受信バッファの定義\n\ttypedef utils::fifo buffer;\n\t\/\/ UART の定義(SAU02、SAU03)\n\tdevice::uart_io uart_;\n\n\tdevice::itimer itm_;\n\n\t\/\/ SDC CSI(SPI) の定義、CSI00 の通信では、「SAU00」を利用、0ユニット、チャネル0\n\ttypedef device::csi_io csi;\n\tcsi csi_;\n\n\t\/\/ FatFS インターフェースの定義\n\ttypedef device::PORT card_select;\t\/\/\/< カード選択信号\n\ttypedef device::PORT card_power;\t\/\/\/< カード電源制御\n\ttypedef device::PORT card_detect;\t\/\/\/< カード検出\n\n\tutils::sdc_io sdc_(csi_);\n\n\t\/\/ LCD CSI(SPI) の定義、CSI20 の通信では、「SAU10」を利用、1ユニット、チャネル0\n\ttypedef device::csi_io csig;\n\tcsig csig_;\n\n\t\/\/ LCD インターフェースの定義\n\ttypedef device::PORT lcd_sel;\t\/\/\/< LCD 選択信号\n\ttypedef device::PORT lcd_reg;\t\/\/\/< LCD レジスタ選択\n\n#ifdef LCD_ST7565\n\tchip::ST7565 lcd_(csig_);\n#endif\n#ifdef LCD_SSD1306\n\tchip::SSD1306 lcd_(csig_);\n#endif\n\n\ttypedef graphics::font6x12 afont;\n\ttypedef graphics::kfont12<16> kfont;\n\tkfont kfont_;\n\tgraphics::monograph<128, 64, afont, kfont> bitmap_(kfont_);\n}\n\nconst void* ivec_[] __attribute__ ((section (\".ivec\"))) = {\n\t\/* 0 *\/ nullptr,\n\t\/* 1 *\/ nullptr,\n\t\/* 2 *\/ nullptr,\n\t\/* 3 *\/ nullptr,\n\t\/* 4 *\/ nullptr,\n\t\/* 5 *\/ nullptr,\n\t\/* 6 *\/ nullptr,\n\t\/* 7 *\/ nullptr,\n\t\/* 8 *\/ nullptr,\n\t\/* 9 *\/ nullptr,\n\t\/* 10 *\/ nullptr,\n\t\/* 11 *\/ nullptr,\n\t\/* 12 *\/ nullptr,\n\t\/* 13 *\/ nullptr,\n\t\/* 14 *\/ nullptr,\n\t\/* 15 *\/ nullptr,\n\t\/* 16 *\/ reinterpret_cast(uart_.send_task),\n\t\/* 17 *\/ reinterpret_cast(uart_.recv_task),\n\t\/* 18 *\/ reinterpret_cast(uart_.error_task),\n\t\/* 19 *\/ nullptr,\n\t\/* 20 *\/ nullptr,\n\t\/* 21 *\/ nullptr,\n\t\/* 22 *\/ nullptr,\n\t\/* 23 *\/ nullptr,\n\t\/* 24 *\/ nullptr,\n\t\/* 25 *\/ nullptr,\n\t\/* 26 *\/ reinterpret_cast(itm_.task),\n};\n\n\nextern \"C\" {\n\tvoid sci_putch(char ch)\n\t{\n\t\tuart_.putch(ch);\n\t}\n\n\tvoid sci_puts(const char* str)\n\t{\n\t\tuart_.puts(str);\n\t}\n\n\tDSTATUS disk_initialize(BYTE drv) {\n\t\treturn sdc_.at_mmc().disk_initialize(drv);\n\t}\n\n\tDSTATUS disk_status(BYTE drv) {\n\t\treturn sdc_.at_mmc().disk_status(drv);\n\t}\n\n\tDRESULT disk_read(BYTE drv, BYTE* buff, DWORD sector, UINT count) {\n\t\treturn sdc_.at_mmc().disk_read(drv, buff, sector, count);\n\t}\n\n\tDRESULT disk_write(BYTE drv, const BYTE* buff, DWORD sector, UINT count) {\n\t\treturn sdc_.at_mmc().disk_write(drv, buff, sector, count);\n\t}\n\n\tDRESULT disk_ioctl(BYTE drv, BYTE ctrl, void* buff) {\n\t\treturn sdc_.at_mmc().disk_ioctl(drv, ctrl, buff);\n\t}\n\n\tDWORD get_fattime(void) {\n#ifdef WITH_RTC\n\t\ttime_t t = 0;\n\t\tif(!rtc_.get_time(t)) {\n\t\t\tutils::format(\"Stall RTC read (%d)\\n\") % static_cast(iica_.get_last_error());\n\t\t}\n\t\treturn utils::str::get_fattime(t);\n#else\n\t\treturn 0;\n#endif\n\t}\n};\n\n\nint main(int argc, char* argv[])\n{\n\tusing namespace device;\n\n\tutils::port::pullup_all(); \/\/\/< 安全の為、全ての入力をプルアップ\n\n\t\/\/ インターバル・タイマー開始\n\t{\n\t\tuint8_t intr_level = 1;\n\t\titm_.start(60, intr_level);\n\t}\n\n\t\/\/ UART 開始\n\t{\n\t\tuint8_t intr_level = 1;\n\t\tuart_.start(115200, intr_level);\n\t}\n\n\t\/\/ SD カードアクセス開始\n\tsdc_.initialize();\n\n\t\/\/ CSI graphics 開始\n\t{\n\t\tuint8_t intr_level = 0;\n\t\tif(!csig_.start(8000000, csig::PHASE::TYPE4, intr_level)) {\n\t\t\tuart_.puts(\"CSI Start fail...\\n\");\n\t\t}\n\t}\n\n\tuart_.puts(\"Start RL78\/G13 SDC Filer sample\\n\");\n\n\tPM4.B3 = 0; \/\/ output\n\n\t{\n\t\tlcd_.start(0x04, true);\n\t\tbitmap_.flash(0);\n\t}\n\n\tuint8_t n = 0;\n\tuint8_t nn = 0;\n\n\twhile(1) {\n\t\titm_.sync();\n\n\t\tsdc_.service();\n\n\t\tif(nn >= 3) {\n\t\t\tlcd_.copy(bitmap_.fb());\n\t\t\tbitmap_.flash(0);\n\t\t\tnn = 0;\n\t\t}\n\t\t++nn;\n\n\t\tbitmap_.draw_text(0, 0, \"漢字\");\n\n\t\t++n;\n\t\tif(n >= 30) n = 0;\n\t\tP4.B3 = n < 10 ? false : true; \t\n\t}\n}\nupdate kanji text\/\/=====================================================================\/\/\n\/*!\t@file\n\t@brief\tLCD 表示を使ったファイラー・サンプル @n\n\t\t\tST7565(R)、128 x 64 ピクセルの液晶を接続 @n\n\t\t\t\/CS ---> P53 (36) @n\n\t\t\tA0 ---> P50 (33) @n\n\t\t\tSD ---> P13\/SO20 (43) @n\n\t\t\tSCL ---> P15\/SCK20 (41) @n \n\t\t\t\/RES ---> \/RESET ( 6)\n\t@author\t平松邦仁 (hira@rvf-rc45.net)\n*\/\n\/\/=====================================================================\/\/\n#include \n#include \"G13\/system.hpp\"\n#include \"common\/port_utils.hpp\"\n#include \"common\/fifo.hpp\"\n#include \"common\/uart_io.hpp\"\n#include \"common\/itimer.hpp\"\n#include \"common\/format.hpp\"\n#include \"common\/delay.hpp\"\n#include \"common\/monograph.hpp\"\n#include \"common\/font6x12.hpp\"\n#include \"common\/kfont12.hpp\"\n#include \"common\/sdc_io.hpp\"\n\n\/\/ ターゲットLCDのタイプを選択\n#define LCD_ST7565\n\/\/ #define LCD_SSD1306\n#ifdef LCD_ST7565\n#include \"chip\/ST7565.hpp\"\n#endif\n#ifdef LCD_SSD1306\n#include \"chip\/SSD1306.hpp\"\n#endif\n\nnamespace {\n\t\/\/ 送信、受信バッファの定義\n\ttypedef utils::fifo buffer;\n\t\/\/ UART の定義(SAU02、SAU03)\n\tdevice::uart_io uart_;\n\n\tdevice::itimer itm_;\n\n\t\/\/ SDC CSI(SPI) の定義、CSI00 の通信では、「SAU00」を利用、0ユニット、チャネル0\n\ttypedef device::csi_io csi;\n\tcsi csi_;\n\n\t\/\/ FatFS インターフェースの定義\n\ttypedef device::PORT card_select;\t\/\/\/< カード選択信号\n\ttypedef device::PORT card_power;\t\/\/\/< カード電源制御\n\ttypedef device::PORT card_detect;\t\/\/\/< カード検出\n\n\tutils::sdc_io sdc_(csi_);\n\n\t\/\/ LCD CSI(SPI) の定義、CSI20 の通信では、「SAU10」を利用、1ユニット、チャネル0\n\ttypedef device::csi_io csig;\n\tcsig csig_;\n\n\t\/\/ LCD インターフェースの定義\n\ttypedef device::PORT lcd_sel;\t\/\/\/< LCD 選択信号\n\ttypedef device::PORT lcd_reg;\t\/\/\/< LCD レジスタ選択\n\n#ifdef LCD_ST7565\n\tchip::ST7565 lcd_(csig_);\n#endif\n#ifdef LCD_SSD1306\n\tchip::SSD1306 lcd_(csig_);\n#endif\n\n\ttypedef graphics::font6x12 afont;\n\ttypedef graphics::kfont12<16> kfont;\n\tkfont kfont_;\n\tgraphics::monograph<128, 64, afont, kfont> bitmap_(kfont_);\n}\n\nconst void* ivec_[] __attribute__ ((section (\".ivec\"))) = {\n\t\/* 0 *\/ nullptr,\n\t\/* 1 *\/ nullptr,\n\t\/* 2 *\/ nullptr,\n\t\/* 3 *\/ nullptr,\n\t\/* 4 *\/ nullptr,\n\t\/* 5 *\/ nullptr,\n\t\/* 6 *\/ nullptr,\n\t\/* 7 *\/ nullptr,\n\t\/* 8 *\/ nullptr,\n\t\/* 9 *\/ nullptr,\n\t\/* 10 *\/ nullptr,\n\t\/* 11 *\/ nullptr,\n\t\/* 12 *\/ nullptr,\n\t\/* 13 *\/ nullptr,\n\t\/* 14 *\/ nullptr,\n\t\/* 15 *\/ nullptr,\n\t\/* 16 *\/ reinterpret_cast(uart_.send_task),\n\t\/* 17 *\/ reinterpret_cast(uart_.recv_task),\n\t\/* 18 *\/ reinterpret_cast(uart_.error_task),\n\t\/* 19 *\/ nullptr,\n\t\/* 20 *\/ nullptr,\n\t\/* 21 *\/ nullptr,\n\t\/* 22 *\/ nullptr,\n\t\/* 23 *\/ nullptr,\n\t\/* 24 *\/ nullptr,\n\t\/* 25 *\/ nullptr,\n\t\/* 26 *\/ reinterpret_cast(itm_.task),\n};\n\n\nextern \"C\" {\n\tvoid sci_putch(char ch)\n\t{\n\t\tuart_.putch(ch);\n\t}\n\n\tvoid sci_puts(const char* str)\n\t{\n\t\tuart_.puts(str);\n\t}\n\n\tDSTATUS disk_initialize(BYTE drv) {\n\t\treturn sdc_.at_mmc().disk_initialize(drv);\n\t}\n\n\tDSTATUS disk_status(BYTE drv) {\n\t\treturn sdc_.at_mmc().disk_status(drv);\n\t}\n\n\tDRESULT disk_read(BYTE drv, BYTE* buff, DWORD sector, UINT count) {\n\t\treturn sdc_.at_mmc().disk_read(drv, buff, sector, count);\n\t}\n\n\tDRESULT disk_write(BYTE drv, const BYTE* buff, DWORD sector, UINT count) {\n\t\treturn sdc_.at_mmc().disk_write(drv, buff, sector, count);\n\t}\n\n\tDRESULT disk_ioctl(BYTE drv, BYTE ctrl, void* buff) {\n\t\treturn sdc_.at_mmc().disk_ioctl(drv, ctrl, buff);\n\t}\n\n\tDWORD get_fattime(void) {\n#ifdef WITH_RTC\n\t\ttime_t t = 0;\n\t\tif(!rtc_.get_time(t)) {\n\t\t\tutils::format(\"Stall RTC read (%d)\\n\") % static_cast(iica_.get_last_error());\n\t\t}\n\t\treturn utils::str::get_fattime(t);\n#else\n\t\treturn 0;\n#endif\n\t}\n};\n\n\nint main(int argc, char* argv[])\n{\n\tusing namespace device;\n\n\tutils::port::pullup_all(); \/\/\/< 安全の為、全ての入力をプルアップ\n\n\t\/\/ インターバル・タイマー開始\n\t{\n\t\tuint8_t intr_level = 1;\n\t\titm_.start(60, intr_level);\n\t}\n\n\t\/\/ UART 開始\n\t{\n\t\tuint8_t intr_level = 1;\n\t\tuart_.start(115200, intr_level);\n\t}\n\n\t\/\/ SD カードアクセス開始\n\tsdc_.initialize();\n\n\t\/\/ CSI graphics 開始\n\t{\n\t\tuint8_t intr_level = 0;\n\t\tif(!csig_.start(8000000, csig::PHASE::TYPE4, intr_level)) {\n\t\t\tuart_.puts(\"CSI Start fail...\\n\");\n\t\t}\n\t}\n\n\tuart_.puts(\"Start RL78\/G13 SDC Filer sample\\n\");\n\n\tPM4.B3 = 0; \/\/ output\n\n\t{\n\t\tlcd_.start(0x04, true);\n\t\tbitmap_.flash(0);\n\t}\n\n\tuint8_t n = 0;\n\tuint8_t nn = 0;\n\n\twhile(1) {\n\t\titm_.sync();\n\n\t\tbool f = sdc_.service();\n\t\tkfont_.set_mount(f);\t\t\n\n\t\tif(nn >= 3) {\n\t\t\tlcd_.copy(bitmap_.fb());\n\t\t\tbitmap_.flash(0);\n\t\t\tnn = 0;\n\t\t}\n\t\t++nn;\n\n\t\tbitmap_.draw_text(0, 0, \"美しい漢字の表示\");\n\n\t\t++n;\n\t\tif(n >= 30) n = 0;\n\t\tP4.B3 = n < 10 ? false : true; \t\n\t}\n}\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * $RCSfile: statusbarcontrollerfactory.hxx,v $\n *\n * $Revision: 1.2 $\n *\n * last change: $Author: obo $ $Date: 2004-11-17 14:57:26 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef __FRAMEWORK_UIFACTORY_STATUSBARCONTROLLERFACTORY_HXX_\n#define __FRAMEWORK_UIFACTORY_STATUSBARCONTROLLERFACTORY_HXX_\n\n\/** Attention: stl headers must(!) be included at first. Otherwhise it can make trouble\n with solaris headers ...\n*\/\n#include \n#include \n#include \n\n\/\/_________________________________________________________________________________________________________________\n\/\/ my own includes\n\/\/_________________________________________________________________________________________________________________\n\n#ifndef __FRAMEWORK_THREADHELP_THREADHELPBASE_HXX_\n#include \n#endif\n\n#ifndef __FRAMEWORK_MACROS_GENERIC_HXX_\n#include \n#endif\n\n#ifndef __FRAMEWORK_MACROS_XINTERFACE_HXX_\n#include \n#endif\n\n#ifndef __FRAMEWORK_MACROS_XTYPEPROVIDER_HXX_\n#include \n#endif\n\n#ifndef __FRAMEWORK_MACROS_XSERVICEINFO_HXX_\n#include \n#endif\n\n#ifndef __FRAMEWORK_STDTYPES_H_\n#include \n#endif\n\n\/\/_________________________________________________________________________________________________________________\n\/\/ interface includes\n\/\/_________________________________________________________________________________________________________________\n\n#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_\n#include \n#endif\n\n#ifndef _COM_SUN_STAR_LANG_XTYPEPROVIDER_HPP_\n#include \n#endif\n\n#ifndef _COM_SUN_STAR_LANG_XMULTICOMPONENTFACTORY_HPP_\n#include \n#endif\n\n#ifndef _DRAFTS_COM_SUN_STAR_FRAME_XUICONTROLLERREGISTRATION_HPP_\n#include \n#endif\n\n\/\/_________________________________________________________________________________________________________________\n\/\/ other includes\n\/\/_________________________________________________________________________________________________________________\n\n#ifndef _CPPUHELPER_WEAK_HXX_\n#include \n#endif\n\n#ifndef _RTL_USTRING_HXX_\n#include \n#endif\n\nnamespace framework\n{\n\nclass ConfigurationAccess_StatusbarControllerFactory;\nclass StatusbarControllerFactory : public com::sun::star::lang::XTypeProvider ,\n public com::sun::star::lang::XServiceInfo ,\n public com::sun::star::lang::XMultiComponentFactory ,\n public drafts::com::sun::star::frame::XUIControllerRegistration ,\n private ThreadHelpBase , \/\/ Struct for right initalization of mutex member! Must be first of baseclasses.\n public ::cppu::OWeakObject\n{\n public:\n StatusbarControllerFactory( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xServiceManager );\n virtual ~StatusbarControllerFactory();\n\n \/\/ XInterface, XTypeProvider, XServiceInfo\n DECLARE_XINTERFACE\n DECLARE_XTYPEPROVIDER\n DECLARE_XSERVICEINFO\n\n \/\/ XMultiComponentFactory\n virtual ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > SAL_CALL createInstanceWithContext( const ::rtl::OUString& aServiceSpecifier, const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext >& Context ) throw (::com::sun::star::uno::Exception, ::com::sun::star::uno::RuntimeException);\n virtual ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > SAL_CALL createInstanceWithArgumentsAndContext( const ::rtl::OUString& ServiceSpecifier, const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& Arguments, const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext >& Context ) throw (::com::sun::star::uno::Exception, ::com::sun::star::uno::RuntimeException);\n virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getAvailableServiceNames() throw (::com::sun::star::uno::RuntimeException);\n\n \/\/ XUIControllerRegistration\n virtual sal_Bool SAL_CALL hasController( const ::rtl::OUString& aCommandURL, const rtl::OUString& aModuleName ) throw (::com::sun::star::uno::RuntimeException);\n virtual void SAL_CALL registerController( const ::rtl::OUString& aCommandURL, const rtl::OUString& aModuleName, const ::rtl::OUString& aControllerImplementationName ) throw (::com::sun::star::uno::RuntimeException);\n virtual void SAL_CALL deregisterController( const ::rtl::OUString& aCommandURL, const rtl::OUString& aModuleName ) throw (::com::sun::star::uno::RuntimeException);\n\n private:\n sal_Bool m_bConfigRead;\n ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > m_xServiceManager;\n ConfigurationAccess_StatusbarControllerFactory* m_pConfigAccess;\n};\n\n} \/\/ namespace framework\n\n#endif \/\/ __FRAMEWORK_SERVICES_STATUSBARCONTROLLERFACTORY_HXX_\nINTEGRATION: CWS removedrafts (1.2.62); FILE MERGED 2005\/02\/17 12:45:57 cd 1.2.62.1: #i42557# move UNOIDL types from drafts to com\/*************************************************************************\n *\n * $RCSfile: statusbarcontrollerfactory.hxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: kz $ $Date: 2005-03-01 19:32:42 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef __FRAMEWORK_UIFACTORY_STATUSBARCONTROLLERFACTORY_HXX_\n#define __FRAMEWORK_UIFACTORY_STATUSBARCONTROLLERFACTORY_HXX_\n\n\/** Attention: stl headers must(!) be included at first. Otherwhise it can make trouble\n with solaris headers ...\n*\/\n#include \n#include \n#include \n\n\/\/_________________________________________________________________________________________________________________\n\/\/ my own includes\n\/\/_________________________________________________________________________________________________________________\n\n#ifndef __FRAMEWORK_THREADHELP_THREADHELPBASE_HXX_\n#include \n#endif\n\n#ifndef __FRAMEWORK_MACROS_GENERIC_HXX_\n#include \n#endif\n\n#ifndef __FRAMEWORK_MACROS_XINTERFACE_HXX_\n#include \n#endif\n\n#ifndef __FRAMEWORK_MACROS_XTYPEPROVIDER_HXX_\n#include \n#endif\n\n#ifndef __FRAMEWORK_MACROS_XSERVICEINFO_HXX_\n#include \n#endif\n\n#ifndef __FRAMEWORK_STDTYPES_H_\n#include \n#endif\n\n\/\/_________________________________________________________________________________________________________________\n\/\/ interface includes\n\/\/_________________________________________________________________________________________________________________\n\n#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_\n#include \n#endif\n\n#ifndef _COM_SUN_STAR_LANG_XTYPEPROVIDER_HPP_\n#include \n#endif\n\n#ifndef _COM_SUN_STAR_LANG_XMULTICOMPONENTFACTORY_HPP_\n#include \n#endif\n\n#ifndef _COM_SUN_STAR_FRAME_XUICONTROLLERREGISTRATION_HPP_\n#include \n#endif\n\n\/\/_________________________________________________________________________________________________________________\n\/\/ other includes\n\/\/_________________________________________________________________________________________________________________\n\n#ifndef _CPPUHELPER_WEAK_HXX_\n#include \n#endif\n\n#ifndef _RTL_USTRING_HXX_\n#include \n#endif\n\nnamespace framework\n{\n\nclass ConfigurationAccess_StatusbarControllerFactory;\nclass StatusbarControllerFactory : public com::sun::star::lang::XTypeProvider ,\n public com::sun::star::lang::XServiceInfo ,\n public com::sun::star::lang::XMultiComponentFactory ,\n public ::com::sun::star::frame::XUIControllerRegistration ,\n private ThreadHelpBase , \/\/ Struct for right initalization of mutex member! Must be first of baseclasses.\n public ::cppu::OWeakObject\n{\n public:\n StatusbarControllerFactory( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xServiceManager );\n virtual ~StatusbarControllerFactory();\n\n \/\/ XInterface, XTypeProvider, XServiceInfo\n DECLARE_XINTERFACE\n DECLARE_XTYPEPROVIDER\n DECLARE_XSERVICEINFO\n\n \/\/ XMultiComponentFactory\n virtual ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > SAL_CALL createInstanceWithContext( const ::rtl::OUString& aServiceSpecifier, const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext >& Context ) throw (::com::sun::star::uno::Exception, ::com::sun::star::uno::RuntimeException);\n virtual ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > SAL_CALL createInstanceWithArgumentsAndContext( const ::rtl::OUString& ServiceSpecifier, const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& Arguments, const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext >& Context ) throw (::com::sun::star::uno::Exception, ::com::sun::star::uno::RuntimeException);\n virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getAvailableServiceNames() throw (::com::sun::star::uno::RuntimeException);\n\n \/\/ XUIControllerRegistration\n virtual sal_Bool SAL_CALL hasController( const ::rtl::OUString& aCommandURL, const rtl::OUString& aModuleName ) throw (::com::sun::star::uno::RuntimeException);\n virtual void SAL_CALL registerController( const ::rtl::OUString& aCommandURL, const rtl::OUString& aModuleName, const ::rtl::OUString& aControllerImplementationName ) throw (::com::sun::star::uno::RuntimeException);\n virtual void SAL_CALL deregisterController( const ::rtl::OUString& aCommandURL, const rtl::OUString& aModuleName ) throw (::com::sun::star::uno::RuntimeException);\n\n private:\n sal_Bool m_bConfigRead;\n ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > m_xServiceManager;\n ConfigurationAccess_StatusbarControllerFactory* m_pConfigAccess;\n};\n\n} \/\/ namespace framework\n\n#endif \/\/ __FRAMEWORK_SERVICES_STATUSBARCONTROLLERFACTORY_HXX_\n<|endoftext|>"} {"text":"\/** @file\n @brief Implementation\n\n @date 2016\n\n @author\n Sensics, Inc.\n \n*\/\n\n\/\/ Copyright 2016 Razer Inc.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n\/\/ Internal Includes\n#include \"ChaperoneData.h\"\n\n\/\/ Library\/third-party includes\n#include \n#include \n\n#include \n\n\/\/ Standard includes\n#include \n#include \n#include \n#include \n#include \n\n#ifdef _WIN32\n#define WIN32_LEAN_AND_MEAN\n#define NO_MINMAX\n#include \n\nstatic inline std::string formatLastErrorAsString() {\n char *lpMsgBuf = nullptr;\n FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,\n nullptr, GetLastError(),\n MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),\n \/\/ Default language\n reinterpret_cast(&lpMsgBuf), 0, nullptr);\n \/\/\/ Free that buffer when we're out of scope.\n auto cleanupBuf = osvr::util::finally([&] { LocalFree(lpMsgBuf); });\n auto errorMessage = std::string(lpMsgBuf);\n return errorMessage;\n}\nstatic inline std::string\ngetFile(std::string const &fn,\n std::function const &errorReport) {\n \/\/\/ Had trouble with \"permission denied\" errors using standard C++ iostreams\n \/\/\/ on the chaperone data, so had to go back down to Win32 API.\n HANDLE f = CreateFileA(fn.c_str(), GENERIC_READ,\n FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr,\n OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);\n if (INVALID_HANDLE_VALUE == f) {\n errorReport(\"Could not open file: \" + formatLastErrorAsString());\n return std::string{};\n }\n auto closer = osvr::util::finally([&f] { CloseHandle(f); });\n\n std::ostringstream os;\n static const auto BUFSIZE = 1024;\n std::array buf;\n \/\/\/ Null terminate for ease of use.\n buf.back() = '\\0';\n bool keepReading = true;\n while (1) {\n DWORD bytesRead;\n auto ret = ReadFile(f, buf.data(), buf.size() - 1, &bytesRead, nullptr);\n if (ret) {\n if (bytesRead == 0) {\n \/\/ end of file\n break;\n } else {\n \/\/ Null terminate this block and slide it in.\n \/\/ std::cout << \"read \" << bytesRead << \" bytes this time \"\n \/\/ << std::endl;\n buf[bytesRead] = '\\0';\n os << buf.data();\n }\n } else {\n\n errorReport(\"Error after reading \" +\n std::to_string(os.str().size()) + \" bytes: \" +\n formatLastErrorAsString());\n return std::string{};\n }\n }\n return os.str();\n}\n#else\n\nstd::string\ngetFile(std::string const &fn,\n std::function const &errorReport) {\n std::ifstream s(fn, std::ios::in | std::ios::binary);\n if (!s) {\n std::ostringstream os;\n os << \"Could not open file \";\n\n \/\/\/ Sadly errno is far more useful in its error messages than\n \/\/\/ failbit-triggered exceptions, etc.\n auto theErrno = errno;\n os << \" (Error code: \" << theErrno << \" - \" << strerror(theErrno)\n << \")\";\n errorReport(os.str());\n return std::string{};\n }\n std::ostringstream os;\n std::string temp;\n while (std::getline(os, temp)) {\n os << temp;\n }\n return os.str();\n}\n#endif\n\nnamespace osvr {\nnamespace vive {\n static const auto PREFIX = \"[ChaperoneData] \";\n static const auto CHAPERONE_DATA_FILENAME = \"chaperone_info.vrchap\";\n#ifdef _WIN32\n static const auto PATH_SEPARATOR = \"\\\\\";\n#else\n static const auto PATH_SEPARATOR = \"\/\";\n#endif\n\n using UniverseDataMap =\n std::map;\n\n using UniverseBaseSerials = std::vector<\n std::pair>;\n struct ChaperoneData::Impl {\n Json::Value chaperoneInfo;\n UniverseDataMap universes;\n UniverseBaseSerials baseSerials;\n };\n\n void loadJsonIntoUniverseData(Json::Value const &obj,\n ChaperoneData::UniverseData &data) {\n data.yaw = obj[\"yaw\"].asDouble();\n auto &xlate = obj[\"translation\"];\n for (Json::Value::ArrayIndex i = 0; i < 3; ++i) {\n data.translation[i] = xlate[i].asDouble();\n }\n }\n ChaperoneData::ChaperoneData(std::string const &steamConfigDir)\n : impl_(new Impl), configDir_(steamConfigDir) {\n {\n Json::Reader reader;\n auto chapInfoFn =\n configDir_ + PATH_SEPARATOR + CHAPERONE_DATA_FILENAME;\n#if 0\n std::ifstream chapInfoFile(configDir_,\n std::ios::in | std::ios::binary);\n if (!chapInfoFile) {\n std::ostringstream os;\n os << \"Could not open chaperone info file, expected at \"\n << chapInfoFn;\n\n \/\/\/ Sadly errno is far more useful in its error messages than\n \/\/\/ failbit-triggered exceptions, etc.\n auto theErrno = errno;\n os << \" (Error code: \" << theErrno << \" - \"\n << strerror(theErrno) << \")\";\n errorOut_(os.str());\n return;\n }\n\n if (!chapInfoFile.good()) {\n errorOut_(\"Could not open chaperone info file, expected at \" +\n chapInfoFn);\n return;\n }\n#endif\n std::string fileData =\n getFile(chapInfoFn, [&](std::string const &message) {\n std::ostringstream os;\n os << \"Could not open chaperone info file, expected at \"\n << chapInfoFn;\n os << \" - details [\" << message << \"]\";\n errorOut_(os.str());\n\n });\n if (!valid()) {\n \/\/\/ this means our fail handler got called.\n return;\n }\n if (!reader.parse(fileData, impl_->chaperoneInfo)) {\n errorOut_(\"Could not parse JSON in chaperone info file at \" +\n chapInfoFn + \": \" +\n reader.getFormattedErrorMessages());\n return;\n }\n\n \/\/\/ Basic sanity checks\n if (impl_->chaperoneInfo[\"jsonid\"] != \"chaperone_info\") {\n errorOut_(\"Chaperone info file at \" + chapInfoFn +\n \" did not match expected format (no element \"\n \"\\\"jsonid\\\": \\\"chaperone_info\\\" in top level \"\n \"object)\");\n return;\n }\n\n if (impl_->chaperoneInfo[\"universes\"].size() == 0) {\n errorOut_(\"Chaperone info file at \" + chapInfoFn +\n \" did not contain any known chaperone universes - \"\n \"user must run Room Setup at least once\");\n return;\n }\n }\n\n for (auto const &univ : impl_->chaperoneInfo[\"universes\"]) {\n auto univIdString = univ[\"universeID\"].asString();\n UniverseData data;\n auto &standing = univ[\"standing\"];\n if (standing.isNull()) {\n warn_(\"No standing calibration data for universe \" +\n univIdString + \", so had to look for seated data.\");\n auto &seated = univ[\"seated\"];\n if (seated.isNull()) {\n warn_(\n \"No seated or standing calibration data for universe \" +\n univIdString + \", so had to skip it.\");\n continue;\n } else {\n data.type = CalibrationType::Seated;\n loadJsonIntoUniverseData(seated, data);\n }\n } else {\n data.type = CalibrationType::Standing;\n loadJsonIntoUniverseData(standing, data);\n }\n \/\/\/ Convert universe ID (64-bit int) from string, in JSON, to an int\n \/\/\/ again.\n UniverseId id;\n std::istringstream is(univIdString);\n is >> id;\n \/\/\/ Add the universe data in.\n impl_->universes.insert(std::make_pair(id, data));\n\n BaseStationSerials serials;\n for (auto const &tracker : univ[\"trackers\"]) {\n auto &serial = tracker[\"serial\"];\n if (serial.isString()) {\n serials.push_back(serial.asString());\n }\n }\n\n \/\/\/ Add the serial data in.\n impl_->baseSerials.emplace_back(id, std::move(serials));\n }\n }\n\n ChaperoneData::~ChaperoneData() {}\n\n bool ChaperoneData::valid() const { return static_cast(impl_); }\n\n bool ChaperoneData::knowUniverseId(UniverseId universe) const {\n if (0 == universe) {\n return false;\n }\n return (impl_->universes.find(universe) != end(impl_->universes));\n }\n\n ChaperoneData::UniverseData\n ChaperoneData::getDataForUniverse(UniverseId universe) const {\n auto it = impl_->universes.find(universe);\n if (it == end(impl_->universes)) {\n return UniverseData();\n }\n return it->second;\n }\n\n std::size_t ChaperoneData::getNumberOfKnownUniverses() const {\n return impl_->universes.size();\n }\n\n ChaperoneData::UniverseId ChaperoneData::guessUniverseIdFromBaseStations(\n BaseStationSerials const &bases) {\n auto providedSize = bases.size();\n UniverseId ret = 0;\n using UniverseRank = std::pair;\n \/\/\/ Compare function for heap.\n auto compare = [](UniverseRank const &a, UniverseRank const &b) {\n return a.first < b.first;\n };\n\n \/\/\/ Will contain heap of potential universes and their value (a fraction\n \/\/\/ of their base stations and provided base stations that were included\n \/\/\/ in the base station list provided to the function)\n std::vector potentialUniverses;\n auto push = [&](float value, UniverseId id) {\n potentialUniverses.emplace_back(value, id);\n std::push_heap(begin(potentialUniverses), end(potentialUniverses),\n compare);\n };\n\n for (auto &univBaseSerial : impl_->baseSerials) {\n auto const &baseSerials = univBaseSerial.second;\n std::size_t hits = 0;\n auto b = begin(baseSerials);\n auto e = end(baseSerials);\n \/\/\/ Count the number of entries that we were given that are also in\n \/\/\/ this universe's list.\n auto found = std::count_if(begin(bases), end(bases),\n [&](std::string const &needle) {\n return std::find(b, e, needle) != e;\n });\n if (found > 0) {\n \/\/\/ This is meant to combine the influence of \"found\" in both\n \/\/\/ providedSize and universe size, and the +1 in the\n \/\/\/ denominator is to avoid division by zero.\n auto weight = 2.f * static_cast(found) \/\n (baseSerials.size() + providedSize + 1);\n#if 0\n std::cout << \"Guessing produced weight of \" << weight << \" for \"\n << univBaseSerial.first << std::endl;\n#endif\n push(weight, univBaseSerial.first);\n }\n }\n if (!potentialUniverses.empty()) {\n \/\/\/ it's a heap, so the best one is always on top.\n return potentialUniverses.front().second;\n }\n return ret;\n }\n\n void ChaperoneData::errorOut_(std::string const &message) {\n \/\/\/ This reset may be redundant in some cases, but better to not miss\n \/\/\/ it, since it's also our error flag.\n impl_.reset();\n\n warn_(\"ERROR: \" + message);\n }\n\n void ChaperoneData::warn_(std::string const &message) {\n\n if (err_.empty()) {\n \/\/\/ First error\n err_ = message;\n return;\n }\n\n static const auto BEGIN_LIST = \"[\";\n static const auto BEGIN_LIST_CH = BEGIN_LIST[0];\n static const auto END_LIST = \"]\";\n static const auto MIDDLE_LIST = \"][\";\n if (BEGIN_LIST_CH == err_.front()) {\n \/\/\/ We've already started a list of errors, just tack one more on.\n err_ += BEGIN_LIST + message + END_LIST;\n return;\n }\n\n \/\/\/ OK, so this is our exactly second error, wrap the first and second.\n err_ = BEGIN_LIST + err_ + MIDDLE_LIST + message + END_LIST;\n }\n\n} \/\/ namespace vive\n} \/\/ namespace osvr\nAdd missing includes and fix mistype in std::getline call\/** @file\n @brief Implementation\n\n @date 2016\n\n @author\n Sensics, Inc.\n \n*\/\n\n\/\/ Copyright 2016 Razer Inc.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n\/\/ Internal Includes\n#include \"ChaperoneData.h\"\n\n\/\/ Library\/third-party includes\n#include \n#include \n\n#include \n\n\/\/ Standard includes\n#include \n#include \n#include \n#include \n#include \n#include \n\n#ifdef _WIN32\n#define WIN32_LEAN_AND_MEAN\n#define NO_MINMAX\n#include \n\nstatic inline std::string formatLastErrorAsString() {\n char *lpMsgBuf = nullptr;\n FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,\n nullptr, GetLastError(),\n MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),\n \/\/ Default language\n reinterpret_cast(&lpMsgBuf), 0, nullptr);\n \/\/\/ Free that buffer when we're out of scope.\n auto cleanupBuf = osvr::util::finally([&] { LocalFree(lpMsgBuf); });\n auto errorMessage = std::string(lpMsgBuf);\n return errorMessage;\n}\nstatic inline std::string\ngetFile(std::string const &fn,\n std::function const &errorReport) {\n \/\/\/ Had trouble with \"permission denied\" errors using standard C++ iostreams\n \/\/\/ on the chaperone data, so had to go back down to Win32 API.\n HANDLE f = CreateFileA(fn.c_str(), GENERIC_READ,\n FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr,\n OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);\n if (INVALID_HANDLE_VALUE == f) {\n errorReport(\"Could not open file: \" + formatLastErrorAsString());\n return std::string{};\n }\n auto closer = osvr::util::finally([&f] { CloseHandle(f); });\n\n std::ostringstream os;\n static const auto BUFSIZE = 1024;\n std::array buf;\n \/\/\/ Null terminate for ease of use.\n buf.back() = '\\0';\n bool keepReading = true;\n while (1) {\n DWORD bytesRead;\n auto ret = ReadFile(f, buf.data(), buf.size() - 1, &bytesRead, nullptr);\n if (ret) {\n if (bytesRead == 0) {\n \/\/ end of file\n break;\n } else {\n \/\/ Null terminate this block and slide it in.\n \/\/ std::cout << \"read \" << bytesRead << \" bytes this time \"\n \/\/ << std::endl;\n buf[bytesRead] = '\\0';\n os << buf.data();\n }\n } else {\n\n errorReport(\"Error after reading \" +\n std::to_string(os.str().size()) + \" bytes: \" +\n formatLastErrorAsString());\n return std::string{};\n }\n }\n return os.str();\n}\n#else\n#include \/\/ strerror\n\nstd::string\ngetFile(std::string const &fn,\n std::function const &errorReport) {\n std::ifstream s(fn, std::ios::in | std::ios::binary);\n if (!s) {\n std::ostringstream os;\n os << \"Could not open file \";\n\n \/\/\/ Sadly errno is far more useful in its error messages than\n \/\/\/ failbit-triggered exceptions, etc.\n auto theErrno = errno;\n os << \" (Error code: \" << theErrno << \" - \" << strerror(theErrno)\n << \")\";\n errorReport(os.str());\n return std::string{};\n }\n std::ostringstream os;\n std::string temp;\n while (std::getline(s, temp)) {\n os << temp;\n }\n return os.str();\n}\n#endif\n\nnamespace osvr {\nnamespace vive {\n static const auto PREFIX = \"[ChaperoneData] \";\n static const auto CHAPERONE_DATA_FILENAME = \"chaperone_info.vrchap\";\n#ifdef _WIN32\n static const auto PATH_SEPARATOR = \"\\\\\";\n#else\n static const auto PATH_SEPARATOR = \"\/\";\n#endif\n\n using UniverseDataMap =\n std::map;\n\n using UniverseBaseSerials = std::vector<\n std::pair>;\n struct ChaperoneData::Impl {\n Json::Value chaperoneInfo;\n UniverseDataMap universes;\n UniverseBaseSerials baseSerials;\n };\n\n void loadJsonIntoUniverseData(Json::Value const &obj,\n ChaperoneData::UniverseData &data) {\n data.yaw = obj[\"yaw\"].asDouble();\n auto &xlate = obj[\"translation\"];\n for (Json::Value::ArrayIndex i = 0; i < 3; ++i) {\n data.translation[i] = xlate[i].asDouble();\n }\n }\n ChaperoneData::ChaperoneData(std::string const &steamConfigDir)\n : impl_(new Impl), configDir_(steamConfigDir) {\n {\n Json::Reader reader;\n auto chapInfoFn =\n configDir_ + PATH_SEPARATOR + CHAPERONE_DATA_FILENAME;\n#if 0\n std::ifstream chapInfoFile(configDir_,\n std::ios::in | std::ios::binary);\n if (!chapInfoFile) {\n std::ostringstream os;\n os << \"Could not open chaperone info file, expected at \"\n << chapInfoFn;\n\n \/\/\/ Sadly errno is far more useful in its error messages than\n \/\/\/ failbit-triggered exceptions, etc.\n auto theErrno = errno;\n os << \" (Error code: \" << theErrno << \" - \"\n << strerror(theErrno) << \")\";\n errorOut_(os.str());\n return;\n }\n\n if (!chapInfoFile.good()) {\n errorOut_(\"Could not open chaperone info file, expected at \" +\n chapInfoFn);\n return;\n }\n#endif\n std::string fileData =\n getFile(chapInfoFn, [&](std::string const &message) {\n std::ostringstream os;\n os << \"Could not open chaperone info file, expected at \"\n << chapInfoFn;\n os << \" - details [\" << message << \"]\";\n errorOut_(os.str());\n\n });\n if (!valid()) {\n \/\/\/ this means our fail handler got called.\n return;\n }\n if (!reader.parse(fileData, impl_->chaperoneInfo)) {\n errorOut_(\"Could not parse JSON in chaperone info file at \" +\n chapInfoFn + \": \" +\n reader.getFormattedErrorMessages());\n return;\n }\n\n \/\/\/ Basic sanity checks\n if (impl_->chaperoneInfo[\"jsonid\"] != \"chaperone_info\") {\n errorOut_(\"Chaperone info file at \" + chapInfoFn +\n \" did not match expected format (no element \"\n \"\\\"jsonid\\\": \\\"chaperone_info\\\" in top level \"\n \"object)\");\n return;\n }\n\n if (impl_->chaperoneInfo[\"universes\"].size() == 0) {\n errorOut_(\"Chaperone info file at \" + chapInfoFn +\n \" did not contain any known chaperone universes - \"\n \"user must run Room Setup at least once\");\n return;\n }\n }\n\n for (auto const &univ : impl_->chaperoneInfo[\"universes\"]) {\n auto univIdString = univ[\"universeID\"].asString();\n UniverseData data;\n auto &standing = univ[\"standing\"];\n if (standing.isNull()) {\n warn_(\"No standing calibration data for universe \" +\n univIdString + \", so had to look for seated data.\");\n auto &seated = univ[\"seated\"];\n if (seated.isNull()) {\n warn_(\n \"No seated or standing calibration data for universe \" +\n univIdString + \", so had to skip it.\");\n continue;\n } else {\n data.type = CalibrationType::Seated;\n loadJsonIntoUniverseData(seated, data);\n }\n } else {\n data.type = CalibrationType::Standing;\n loadJsonIntoUniverseData(standing, data);\n }\n \/\/\/ Convert universe ID (64-bit int) from string, in JSON, to an int\n \/\/\/ again.\n UniverseId id;\n std::istringstream is(univIdString);\n is >> id;\n \/\/\/ Add the universe data in.\n impl_->universes.insert(std::make_pair(id, data));\n\n BaseStationSerials serials;\n for (auto const &tracker : univ[\"trackers\"]) {\n auto &serial = tracker[\"serial\"];\n if (serial.isString()) {\n serials.push_back(serial.asString());\n }\n }\n\n \/\/\/ Add the serial data in.\n impl_->baseSerials.emplace_back(id, std::move(serials));\n }\n }\n\n ChaperoneData::~ChaperoneData() {}\n\n bool ChaperoneData::valid() const { return static_cast(impl_); }\n\n bool ChaperoneData::knowUniverseId(UniverseId universe) const {\n if (0 == universe) {\n return false;\n }\n return (impl_->universes.find(universe) != end(impl_->universes));\n }\n\n ChaperoneData::UniverseData\n ChaperoneData::getDataForUniverse(UniverseId universe) const {\n auto it = impl_->universes.find(universe);\n if (it == end(impl_->universes)) {\n return UniverseData();\n }\n return it->second;\n }\n\n std::size_t ChaperoneData::getNumberOfKnownUniverses() const {\n return impl_->universes.size();\n }\n\n ChaperoneData::UniverseId ChaperoneData::guessUniverseIdFromBaseStations(\n BaseStationSerials const &bases) {\n auto providedSize = bases.size();\n UniverseId ret = 0;\n using UniverseRank = std::pair;\n \/\/\/ Compare function for heap.\n auto compare = [](UniverseRank const &a, UniverseRank const &b) {\n return a.first < b.first;\n };\n\n \/\/\/ Will contain heap of potential universes and their value (a fraction\n \/\/\/ of their base stations and provided base stations that were included\n \/\/\/ in the base station list provided to the function)\n std::vector potentialUniverses;\n auto push = [&](float value, UniverseId id) {\n potentialUniverses.emplace_back(value, id);\n std::push_heap(begin(potentialUniverses), end(potentialUniverses),\n compare);\n };\n\n for (auto &univBaseSerial : impl_->baseSerials) {\n auto const &baseSerials = univBaseSerial.second;\n std::size_t hits = 0;\n auto b = begin(baseSerials);\n auto e = end(baseSerials);\n \/\/\/ Count the number of entries that we were given that are also in\n \/\/\/ this universe's list.\n auto found = std::count_if(begin(bases), end(bases),\n [&](std::string const &needle) {\n return std::find(b, e, needle) != e;\n });\n if (found > 0) {\n \/\/\/ This is meant to combine the influence of \"found\" in both\n \/\/\/ providedSize and universe size, and the +1 in the\n \/\/\/ denominator is to avoid division by zero.\n auto weight = 2.f * static_cast(found) \/\n (baseSerials.size() + providedSize + 1);\n#if 0\n std::cout << \"Guessing produced weight of \" << weight << \" for \"\n << univBaseSerial.first << std::endl;\n#endif\n push(weight, univBaseSerial.first);\n }\n }\n if (!potentialUniverses.empty()) {\n \/\/\/ it's a heap, so the best one is always on top.\n return potentialUniverses.front().second;\n }\n return ret;\n }\n\n void ChaperoneData::errorOut_(std::string const &message) {\n \/\/\/ This reset may be redundant in some cases, but better to not miss\n \/\/\/ it, since it's also our error flag.\n impl_.reset();\n\n warn_(\"ERROR: \" + message);\n }\n\n void ChaperoneData::warn_(std::string const &message) {\n\n if (err_.empty()) {\n \/\/\/ First error\n err_ = message;\n return;\n }\n\n static const auto BEGIN_LIST = \"[\";\n static const auto BEGIN_LIST_CH = BEGIN_LIST[0];\n static const auto END_LIST = \"]\";\n static const auto MIDDLE_LIST = \"][\";\n if (BEGIN_LIST_CH == err_.front()) {\n \/\/\/ We've already started a list of errors, just tack one more on.\n err_ += BEGIN_LIST + message + END_LIST;\n return;\n }\n\n \/\/\/ OK, so this is our exactly second error, wrap the first and second.\n err_ = BEGIN_LIST + err_ + MIDDLE_LIST + message + END_LIST;\n }\n\n} \/\/ namespace vive\n} \/\/ namespace osvr\n<|endoftext|>"} {"text":"#include \"gtest\/gtest.h\"\n#include \"..\/src\/tmxparser.h\"\n\nclass TmxParseTest : public ::testing::Test\n{\nprotected:\n\tstatic void SetUpTestCase()\n\t{\n\t\t_map = new tmxparser::TmxMap();\n\t\ttmxparser::parseFromFile(\"..\/test_xml_level.tmx\", _map, \"assets\/textures\/\");\n\t}\n\n\n\tstatic void TearDownTestCase()\n\t{\n\t\tdelete _map;\n\t\t_map = NULL;\n\t}\n\n\n\tvirtual void SetUp()\n\t{\n\n\t}\n\n\n\tvirtual void TearDown()\n\t{\n\n\t}\n\n\n\tstatic tmxparser::TmxMap* _map;\n};\n\n\ntmxparser::TmxMap* TmxParseTest::_map = NULL;\n\n\nTEST_F(TmxParseTest, MapNotNull)\n{\n\tASSERT_TRUE(_map != NULL);\n}\n\n\nTEST_F(TmxParseTest, MapProperties)\n{\n\tASSERT_TRUE(_map != NULL);\n\tASSERT_EQ(\"1.0\", _map->version);\n\tASSERT_EQ(\"orthogonal\", _map->orientation);\n\tASSERT_EQ(\"right-down\", _map->renderOrder);\n\tASSERT_EQ(16, _map->width);\n\tASSERT_EQ(16, _map->height);\n\tASSERT_EQ(16, _map->tileWidth);\n\tASSERT_EQ(16, _map->tileHeight);\n}\n\n\nTEST_F(TmxParseTest, TilesetProperties)\n{\n\tASSERT_EQ(2, _map->tilesetCollection.size());\n\n\ttmxparser::TmxTileset tileset = _map->tilesetCollection[0];\n\tASSERT_EQ(1, tileset.firstgid);\n\tASSERT_EQ(\"super_mario_one_tileset\", tileset.name);\n\tASSERT_EQ(16, tileset.tileWidth);\n\tASSERT_EQ(16, tileset.tileHeight);\n\n\ttileset = _map->tilesetCollection[1];\n\tASSERT_EQ(925, tileset.firstgid);\n\tASSERT_EQ(\"BowserBreath\", tileset.name);\n\tASSERT_EQ(32, tileset.tileWidth);\n\tASSERT_EQ(32, tileset.tileHeight);\n}\n\n\nTEST_F(TmxParseTest, TilesetImageSourceProperties)\n{\n\tASSERT_EQ(2, _map->tilesetCollection.size());\n\n\ttmxparser::TmxTileset tileset = _map->tilesetCollection[0];\n\ttmxparser::TmxImage image = tileset.image;\n\n\tASSERT_EQ(\"assets\/textures\/super_mario_one_tileset.png\", image.source);\n\tASSERT_EQ(528, image.width);\n\tASSERT_EQ(448, image.height);\n\n\ttileset = _map->tilesetCollection[1];\n\timage = tileset.image;\n\n\tASSERT_EQ(\"assets\/textures\/BowserBreath.png\", image.source);\n\tASSERT_EQ(128, image.width);\n\tASSERT_EQ(32, image.height);\n}\n\n\nint main(int argc, char **argv)\n{\n\t::testing::InitGoogleTest(&argc, argv);\n\treturn RUN_ALL_TESTS();\n}\n- added layer properties test#include \"gtest\/gtest.h\"\n#include \"..\/src\/tmxparser.h\"\n\nclass TmxParseTest : public ::testing::Test\n{\nprotected:\n\tstatic void SetUpTestCase()\n\t{\n\t\t_map = new tmxparser::TmxMap();\n\t\ttmxparser::parseFromFile(\"..\/test_xml_level.tmx\", _map, \"assets\/textures\/\");\n\t}\n\n\n\tstatic void TearDownTestCase()\n\t{\n\t\tdelete _map;\n\t\t_map = NULL;\n\t}\n\n\n\tvirtual void SetUp()\n\t{\n\n\t}\n\n\n\tvirtual void TearDown()\n\t{\n\n\t}\n\n\n\tstatic tmxparser::TmxMap* _map;\n};\n\n\ntmxparser::TmxMap* TmxParseTest::_map = NULL;\n\n\nTEST_F(TmxParseTest, MapNotNull)\n{\n\tASSERT_TRUE(_map != NULL);\n}\n\n\nTEST_F(TmxParseTest, MapProperties)\n{\n\tASSERT_TRUE(_map != NULL);\n\tASSERT_EQ(\"1.0\", _map->version);\n\tASSERT_EQ(\"orthogonal\", _map->orientation);\n\tASSERT_EQ(\"right-down\", _map->renderOrder);\n\tASSERT_EQ(16, _map->width);\n\tASSERT_EQ(16, _map->height);\n\tASSERT_EQ(16, _map->tileWidth);\n\tASSERT_EQ(16, _map->tileHeight);\n}\n\n\nTEST_F(TmxParseTest, TilesetProperties)\n{\n\tASSERT_EQ(2, _map->tilesetCollection.size());\n\n\ttmxparser::TmxTileset tileset = _map->tilesetCollection[0];\n\tASSERT_EQ(1, tileset.firstgid);\n\tASSERT_EQ(\"super_mario_one_tileset\", tileset.name);\n\tASSERT_EQ(16, tileset.tileWidth);\n\tASSERT_EQ(16, tileset.tileHeight);\n\n\ttileset = _map->tilesetCollection[1];\n\tASSERT_EQ(925, tileset.firstgid);\n\tASSERT_EQ(\"BowserBreath\", tileset.name);\n\tASSERT_EQ(32, tileset.tileWidth);\n\tASSERT_EQ(32, tileset.tileHeight);\n}\n\n\nTEST_F(TmxParseTest, TilesetImageSourceProperties)\n{\n\tASSERT_EQ(2, _map->tilesetCollection.size());\n\n\ttmxparser::TmxTileset tileset = _map->tilesetCollection[0];\n\ttmxparser::TmxImage image = tileset.image;\n\n\tASSERT_EQ(\"assets\/textures\/super_mario_one_tileset.png\", image.source);\n\tASSERT_EQ(528, image.width);\n\tASSERT_EQ(448, image.height);\n\n\ttileset = _map->tilesetCollection[1];\n\timage = tileset.image;\n\n\tASSERT_EQ(\"assets\/textures\/BowserBreath.png\", image.source);\n\tASSERT_EQ(128, image.width);\n\tASSERT_EQ(32, image.height);\n}\n\n\nTEST_F(TmxParseTest, LayerProperties)\n{\n\tASSERT_EQ(1, _map->layerCollection.size());\n\ttmxparser::TmxLayer layer = _map->layerCollection[0];\n\n\tASSERT_EQ(\"World\", layer.name);\n\tASSERT_EQ(16, layer.width);\n\tASSERT_EQ(16, layer.height);\n\n\tASSERT_EQ(256, layer.tiles.size());\n}\n\n\nint main(int argc, char **argv)\n{\n\t::testing::InitGoogleTest(&argc, argv);\n\treturn RUN_ALL_TESTS();\n}\n<|endoftext|>"} {"text":"#include \"gtest\/gtest.h\"\n#include \"..\/src\/tmxparser.h\"\n\nclass TmxParseTest : public ::testing::Test\n{\nprotected:\n\tstatic void SetUpTestCase()\n\t{\n\t\t_map = new tmxparser::TmxMap();\n\t\ttmxparser::parseFromFile(\"..\/test_files\/test_xml_level.tmx\", _map, \"assets\/textures\/\");\n\t}\n\n\n\tstatic void TearDownTestCase()\n\t{\n\t\tdelete _map;\n\t\t_map = NULL;\n\t}\n\n\n\tvirtual void SetUp()\n\t{\n\n\t}\n\n\n\tvirtual void TearDown()\n\t{\n\n\t}\n\n\n\tstatic tmxparser::TmxMap* _map;\n};\n\n\ntmxparser::TmxMap* TmxParseTest::_map = NULL;\n\n\nTEST_F(TmxParseTest, MapNotNull)\n{\n\tASSERT_TRUE(_map != NULL);\n}\n\n\nTEST_F(TmxParseTest, MapProperties)\n{\n\tASSERT_TRUE(_map != NULL);\n\tASSERT_EQ(\"1.0\", _map->version);\n\tASSERT_EQ(\"orthogonal\", _map->orientation);\n\tASSERT_EQ(\"right-down\", _map->renderOrder);\n\tASSERT_EQ(10, _map->width);\n\tASSERT_EQ(10, _map->height);\n\tASSERT_EQ(16, _map->tileWidth);\n\tASSERT_EQ(16, _map->tileHeight);\n}\n\n\nTEST_F(TmxParseTest, TilesetProperties)\n{\n\tASSERT_EQ(2, _map->tilesetCollection.size());\n\n\ttmxparser::TmxTileset tileset = _map->tilesetCollection[0];\n\tASSERT_EQ(1, tileset.firstgid);\n\tASSERT_EQ(\"super_mario_one_tileset\", tileset.name);\n\tASSERT_EQ(16, tileset.tileWidth);\n\tASSERT_EQ(16, tileset.tileHeight);\n\n\ttileset = _map->tilesetCollection[1];\n\tASSERT_EQ(925, tileset.firstgid);\n\tASSERT_EQ(\"legend_of_zelda_one_overworld_tiles\", tileset.name);\n\tASSERT_EQ(16, tileset.tileWidth);\n\tASSERT_EQ(16, tileset.tileHeight);\n}\n\n\nTEST_F(TmxParseTest, TilesetImageSourceProperties)\n{\n\tASSERT_EQ(2, _map->tilesetCollection.size());\n\n\ttmxparser::TmxTileset tileset = _map->tilesetCollection[0];\n\ttmxparser::TmxImage image = tileset.image;\n\n\tASSERT_EQ(\"assets\/textures\/super_mario_one_tileset.png\", image.source);\n\tASSERT_EQ(528, image.width);\n\tASSERT_EQ(448, image.height);\n\n\ttileset = _map->tilesetCollection[1];\n\timage = tileset.image;\n\n\tASSERT_EQ(\"assets\/textures\/legend_of_zelda_one_overworld_tiles.png\", image.source);\n\tASSERT_EQ(307, image.width);\n\tASSERT_EQ(163, image.height);\n}\n\n\nTEST_F(TmxParseTest, LayerProperties)\n{\n\tASSERT_EQ(1, _map->layerCollection.size());\n\ttmxparser::TmxLayer layer = _map->layerCollection[0];\n\n\tASSERT_EQ(\"World\", layer.name);\n\tASSERT_EQ(10, layer.width);\n\tASSERT_EQ(10, layer.height);\n\n\tASSERT_EQ(100, layer.tiles.size());\n}\n\n\nint main(int argc, char **argv)\n{\n\t::testing::InitGoogleTest(&argc, argv);\n\treturn RUN_ALL_TESTS();\n}\n- validating tiles in test#include \"gtest\/gtest.h\"\n#include \"..\/src\/tmxparser.h\"\n\nclass TmxParseTest : public ::testing::Test\n{\nprotected:\n\tstatic void SetUpTestCase()\n\t{\n\t\t_map = new tmxparser::TmxMap();\n\t\ttmxparser::parseFromFile(\"..\/test_files\/test_xml_level.tmx\", _map, \"assets\/textures\/\");\n\t}\n\n\n\tstatic void TearDownTestCase()\n\t{\n\t\tdelete _map;\n\t\t_map = NULL;\n\t}\n\n\n\tvirtual void SetUp()\n\t{\n\n\t}\n\n\n\tvirtual void TearDown()\n\t{\n\n\t}\n\n\n\tstatic tmxparser::TmxMap* _map;\n};\n\n\ntmxparser::TmxMap* TmxParseTest::_map = NULL;\n\n\nTEST_F(TmxParseTest, MapNotNull)\n{\n\tASSERT_TRUE(_map != NULL);\n}\n\n\nTEST_F(TmxParseTest, MapProperties)\n{\n\tASSERT_TRUE(_map != NULL);\n\tASSERT_EQ(\"1.0\", _map->version);\n\tASSERT_EQ(\"orthogonal\", _map->orientation);\n\tASSERT_EQ(\"right-down\", _map->renderOrder);\n\tASSERT_EQ(10, _map->width);\n\tASSERT_EQ(10, _map->height);\n\tASSERT_EQ(16, _map->tileWidth);\n\tASSERT_EQ(16, _map->tileHeight);\n}\n\n\nTEST_F(TmxParseTest, TilesetProperties)\n{\n\tASSERT_EQ(2, _map->tilesetCollection.size());\n\n\ttmxparser::TmxTileset tileset = _map->tilesetCollection[0];\n\tASSERT_EQ(1, tileset.firstgid);\n\tASSERT_EQ(\"super_mario_one_tileset\", tileset.name);\n\tASSERT_EQ(16, tileset.tileWidth);\n\tASSERT_EQ(16, tileset.tileHeight);\n\n\ttileset = _map->tilesetCollection[1];\n\tASSERT_EQ(925, tileset.firstgid);\n\tASSERT_EQ(\"legend_of_zelda_one_overworld_tiles\", tileset.name);\n\tASSERT_EQ(16, tileset.tileWidth);\n\tASSERT_EQ(16, tileset.tileHeight);\n}\n\n\nTEST_F(TmxParseTest, TilesetImageSourceProperties)\n{\n\tASSERT_EQ(2, _map->tilesetCollection.size());\n\n\ttmxparser::TmxTileset tileset = _map->tilesetCollection[0];\n\ttmxparser::TmxImage image = tileset.image;\n\n\tASSERT_EQ(\"assets\/textures\/super_mario_one_tileset.png\", image.source);\n\tASSERT_EQ(528, image.width);\n\tASSERT_EQ(448, image.height);\n\n\ttileset = _map->tilesetCollection[1];\n\timage = tileset.image;\n\n\tASSERT_EQ(\"assets\/textures\/legend_of_zelda_one_overworld_tiles.png\", image.source);\n\tASSERT_EQ(307, image.width);\n\tASSERT_EQ(163, image.height);\n}\n\n\nTEST_F(TmxParseTest, LayerProperties)\n{\n\tASSERT_EQ(1, _map->layerCollection.size());\n\ttmxparser::TmxLayer layer = _map->layerCollection[0];\n\n\tASSERT_EQ(\"World\", layer.name);\n\tASSERT_EQ(10, layer.width);\n\tASSERT_EQ(10, layer.height);\n\n\tASSERT_EQ(100, layer.tiles.size());\n}\n\n\nTEST_F(TmxParseTest, TilesValidation)\n{\n\tASSERT_EQ(1, _map->layerCollection.size());\n\ttmxparser::TmxLayer layer = _map->layerCollection[0];\n\n\ttmxparser::TmxLayerTileCollection_t tiles = layer.tiles;\n\tASSERT_EQ(100, tiles.size());\n\n\tint expectedGidValues[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10,\n\t\t\t\t\t\t\t34, 35, 36, 37, 38, 39, 40, 41, 42, 43,\n\t\t\t\t\t\t\t925, 926, 927, 928, 929, 930, 931, 932, 933, 934\n\t\t\t\t\t\t\t};\n\tint testTileCount = sizeof(expectedGidValues) \/ sizeof(int);\n\tfor (unsigned int i = 0; i < testTileCount; i++)\n\t{\n\t\tASSERT_EQ(expectedGidValues[i], tiles[i].gid);\n\t}\n}\n\n\nint main(int argc, char **argv)\n{\n\tint retVal = 0;\n\n\t::testing::InitGoogleTest(&argc, argv);\n\n\tprintf(\"\\033[32m\" \"==========\\nXML TESTS\\n==========\\n\" \"\\033[0m\");\n\tretVal = RUN_ALL_TESTS();\n\n\t\/\/printf(\"\\033[32m\" \"==========\\nCSV TESTS\\n==========\\n\" \"\\033[0m\");\n\t\/\/retVal = RUN_ALL_TESTS();\n\n\t\/\/printf(\"\\033[32m\" \"==========\\nBASE64 TESTS\\n==========\\n\" \"\\033[0m\");\n\t\/\/retVal = RUN_ALL_TESTS();\n\n\treturn retVal;\n}\n<|endoftext|>"} {"text":"\/\/ Rabin-Karp - String Matching + Hashing O(n+m)\nconst int B = 31;\nchar s[N], p[N];\nint n, m; \/\/ n = strlen(s), m = strlen(p)\n\nvoid rabin() {\n if (nFixed overflow bug\/\/ Rabin-Karp - String Matching + Hashing O(n+m)\nconst int B = 31;\nchar s[N], p[N];\nint n, m; \/\/ n = strlen(s), m = strlen(p)\n\nvoid rabin() {\n if (n"} {"text":"\n\n#include \n#include \n#include \n#include \n#include \n#include \n\nusing Rxq = ssnlib::Rxq_interface;\nusing Txq = ssnlib::Txq_interface;\nusing Port = ssnlib::Port_interface;\nusing Cpu = ssnlib::Cpu_interface;\nusing System = ssnlib::System_interface;\n#include \"commands.h\"\n\n\n\nclass Allocator {\npublic:\n const std::string name;\n Allocator(const char* n) : name(n)\n { if (name == \"\") throw slankdev::exception(\"not set thread name\"); }\n virtual ~Allocator() {}\n virtual ssnlib::ssn_thread* alloc() = 0;\n};\n\nclass Allocator_wk : public Allocator {\n\n class Thrd_wk : public ssnlib::ssn_thread {\n bool running;\n size_t id;\n public:\n Thrd_wk() : ssn_thread(\"wk\"), running(false) {}\n bool kill() { running = false; return true; }\n void operator()()\n {\n running = true;\n while (running) {\n sleep(1);\n }\n }\n };\n\npublic:\n Allocator_wk() : Allocator(\"wk\") {}\n ssnlib::ssn_thread* alloc() override { return new Thrd_wk; }\n};\n\nclass Allocator_rx : public Allocator {\n\n class Thrd_rx : public ssnlib::ssn_thread {\n bool running;\n size_t id;\n public:\n Thrd_rx() : ssn_thread(\"rx\"), running(false) {}\n bool kill() { running = false; return true; }\n void operator()()\n {\n running = true;\n while (running) {\n sleep(1);\n }\n }\n };\n\npublic:\n Allocator_rx() : Allocator(\"rx\") {}\n ssnlib::ssn_thread* alloc() override { return new Thrd_rx; }\n};\n\n\nclass dta2 {\n\n class Cmd_dta : public ssnlib::Command {\n struct pcmd_params {\n cmdline_fixed_string_t cmd;\n cmdline_fixed_string_t op;\n };\n dta2* d;\n public:\n Cmd_dta(dta2* d_) : d(d_)\n {\n append_token(TOKEN_STRING(struct pcmd_params, cmd, \"dta\"));\n append_token(TOKEN_STRING(struct pcmd_params, op , NULL));\n token_fin();\n\n init_raw();\n set_raw(\"dta < inc** | dec** | stop >\");\n }\n void handle(void* p)\n {\n pcmd_params* param = reinterpret_cast(p);\n const std::string op = param->op;\n\n if (op == \"stop\") d->stop();\n else if (op == \"incwk\") d->inc(\"wk\");\n else if (op == \"incrx\") d->inc(\"rx\");\n else if (op == \"decwk\") d->dec(\"wk\");\n else if (op == \"decrx\") d->dec(\"rx\");\n else printf(\"Bad arguments\\n\");\n }\n };\n\n\npublic:\n System sys;\n ssnlib::Shell shell;\n std::vector allocators;\n\npublic:\n dta2(int argc, char** argv) : sys(argc, argv), shell(\"susanow> \")\n {\n shell.add_cmd(new Cmd_clear );\n shell.add_cmd(new Cmd_findthread(&sys));\n shell.add_cmd(new Cmd_quit (&sys));\n shell.add_cmd(new Cmd_thread (&sys));\n shell.add_cmd(new Cmd_port (&sys));\n shell.add_cmd(new Cmd_lscpu (&sys));\n shell.add_cmd(new Cmd_version (&sys));\n shell.add_cmd(new Cmd_dta (this));\n shell.fin();\n\n allocators.push_back(new Allocator_wk);\n allocators.push_back(new Allocator_rx);\n\n sys.append_thread(&shell);\n }\n void inc(const std::string& threadname)\n {\n try {\n for (auto* p : allocators) {\n if (p->name == threadname) {\n sys.append_thread(p->alloc());\n start();\n return;\n }\n }\n printf(\"can't append thread\\n\");\n } catch (std::exception& e) {\n printf(\"can't append thread\\n\");\n }\n }\n void dec(const std::string& threadname)\n {\n size_t nb_cpus = sys.cpus.size();\n for (ssize_t i=nb_cpus-1; i>=0; i--) {\n if (i == 0) continue;\n\n Cpu& cpu = sys.cpus.at(i);\n if (cpu.thread && cpu.thread->name == threadname) {\n ssnlib::ssn_thread* tmp = cpu.thread;\n if (cpu.get_state() != RUNNING) {\n } else {\n tmp->kill();\n cpu.wait();\n }\n delete tmp;\n cpu.thread = nullptr;\n return ;\n }\n }\n printf(\"no such thread\\n\");\n }\n void start()\n {\n for (Cpu& cpu : sys.cpus) {\n if (cpu.thread && have_thread(cpu.thread->name)) {\n cpu.launch();\n }\n }\n }\n void stop()\n {\n for (Cpu& cpu : sys.cpus) {\n if (cpu.thread && have_thread(cpu.thread->name)) {\n cpu.thread->kill();\n cpu.wait();\n }\n }\n }\n bool have_thread(const std::string& name)\n {\n for (auto* alctr : allocators) {\n if (alctr->name == name) return true;\n }\n return false;\n }\n};\n\n\n\nint main(int argc, char** argv)\n{\n using namespace ssnlib;\n\n Port::nb_rx_rings = 2;\n Port::nb_tx_rings = 2;\n Port::rx_ring_size = 128;\n Port::tx_ring_size = 512;\n\n dta2 d(argc, argv);\n\n d.sys.launch_all();\n d.sys.wait_all();\n}\n\nADD: dtaa sample interface\n\n#include \n#include \n#include \n#include \n#include \n#include \n\nusing Rxq = ssnlib::Rxq_interface;\nusing Txq = ssnlib::Txq_interface;\nusing Port = ssnlib::Port_interface;\nusing Cpu = ssnlib::Cpu_interface;\nusing System = ssnlib::System_interface;\n#include \"commands.h\"\n\n\n\nclass Allocator {\npublic:\n const std::string name;\n Allocator(const char* n) : name(n)\n { if (name == \"\") throw slankdev::exception(\"not set thread name\"); }\n virtual ~Allocator() {}\n virtual ssnlib::ssn_thread* alloc() = 0;\n};\n\nclass Allocator_wk : public Allocator {\n\n class Thrd_wk : public ssnlib::ssn_thread {\n bool running;\n size_t id;\n public:\n Thrd_wk() : ssn_thread(\"wk\"), running(false) {}\n bool kill() { running = false; return true; }\n void operator()()\n {\n running = true;\n while (running) {\n sleep(1);\n }\n }\n };\n\npublic:\n Allocator_wk() : Allocator(\"wk\") {}\n ssnlib::ssn_thread* alloc() override { return new Thrd_wk; }\n};\n\nclass Allocator_rx : public Allocator {\n\n class Thrd_rx : public ssnlib::ssn_thread {\n bool running;\n size_t id;\n public:\n Thrd_rx() : ssn_thread(\"rx\"), running(false) {}\n bool kill() { running = false; return true; }\n void operator()()\n {\n running = true;\n while (running) {\n sleep(1);\n }\n }\n };\n\npublic:\n Allocator_rx() : Allocator(\"rx\") {}\n ssnlib::ssn_thread* alloc() override { return new Thrd_rx; }\n};\n\n\nclass dta2system : public System {\n std::vector allocators;\n\npublic:\n dta2system(int argc, char** argv) : System(argc, argv) {}\n void append_dtaa_thread(Allocator* newthread)\n { allocators.push_back(newthread); }\n void inc(const std::string& threadname)\n {\n try {\n for (auto* p : allocators) {\n if (p->name == threadname) {\n append_thread(p->alloc());\n start();\n return;\n }\n }\n printf(\"can't append thread\\n\");\n } catch (std::exception& e) {\n printf(\"can't append thread\\n\");\n }\n }\n void dec(const std::string& threadname)\n {\n size_t nb_cpus = cpus.size();\n for (ssize_t i=nb_cpus-1; i>=0; i--) {\n if (i == 0) continue;\n\n Cpu& cpu = cpus.at(i);\n if (cpu.thread && cpu.thread->name == threadname) {\n ssnlib::ssn_thread* tmp = cpu.thread;\n if (cpu.get_state() != RUNNING) {\n } else {\n tmp->kill();\n cpu.wait();\n }\n delete tmp;\n cpu.thread = nullptr;\n return ;\n }\n }\n printf(\"no such thread\\n\");\n }\n void start()\n {\n for (Cpu& cpu : cpus) {\n if (cpu.thread && have_thread(cpu.thread->name)) {\n cpu.launch();\n }\n }\n }\n void stop()\n {\n for (Cpu& cpu : cpus) {\n if (cpu.thread && have_thread(cpu.thread->name)) {\n cpu.thread->kill();\n cpu.wait();\n }\n }\n }\n bool have_thread(const std::string& name)\n {\n for (auto* alctr : allocators) {\n if (alctr->name == name) return true;\n }\n return false;\n }\n};\n\n\nclass Cmd_dta : public ssnlib::Command {\n struct pcmd_params {\n cmdline_fixed_string_t cmd;\n cmdline_fixed_string_t op;\n };\n dta2system* sys;\npublic:\n Cmd_dta(dta2system* s) : sys(s)\n {\n append_token(TOKEN_STRING(struct pcmd_params, cmd, \"dta\"));\n append_token(TOKEN_STRING(struct pcmd_params, op , NULL));\n token_fin();\n\n init_raw();\n set_raw(\"dta < inc** | dec** | stop >\");\n }\n void handle(void* p)\n {\n pcmd_params* param = reinterpret_cast(p);\n const std::string op = param->op;\n\n if (op == \"stop\") sys->stop();\n else if (op == \"incwk\") sys->inc(\"wk\");\n else if (op == \"incrx\") sys->inc(\"rx\");\n else if (op == \"decwk\") sys->dec(\"wk\");\n else if (op == \"decrx\") sys->dec(\"rx\");\n else printf(\"Bad arguments\\n\");\n }\n};\n\n\n\nint main(int argc, char** argv)\n{\n using namespace ssnlib;\n\n Port::nb_rx_rings = 2;\n Port::nb_tx_rings = 2;\n Port::rx_ring_size = 128;\n Port::tx_ring_size = 512;\n\n dta2system sys(argc, argv);\n\n ssnlib::Shell shell(\"susanow> \");\n shell.add_cmd(new Cmd_clear );\n shell.add_cmd(new Cmd_findthread(&sys));\n shell.add_cmd(new Cmd_quit (&sys));\n shell.add_cmd(new Cmd_thread (&sys));\n shell.add_cmd(new Cmd_port (&sys));\n shell.add_cmd(new Cmd_lscpu (&sys));\n shell.add_cmd(new Cmd_version (&sys));\n shell.add_cmd(new Cmd_dta (&sys));\n shell.fin();\n\n sys.append_thread(&shell);\n sys.append_dtaa_thread(new Allocator_wk);\n sys.append_dtaa_thread(new Allocator_rx);\n\n sys.launch_all();\n sys.wait_all();\n}\n\n<|endoftext|>"} {"text":"\/\/\/ \\file\n\/\/\/ \\ingroup tutorial_tdataframe\n\/\/\/ \\notebook\n\/\/\/ This tutorial illustrates how to express the H1 analysis with a TDataFrame.\n\/\/\/\n\/\/\/ \\macro_code\n\/\/\/\n\/\/\/ \\date December 2016\n\/\/\/ \\author Axel Naumann\n\nauto Select = [](ROOT::Experimental::TDataFrame &dataFrame) {\n using Farray_t = ROOT::Experimental::TDF::TArrayBranch;\n using Iarray_t = ROOT::Experimental::TDF::TArrayBranch;\n\n auto ret =\n dataFrame.Filter(\"TMath::Abs(md0_d - 1.8646) < 0.04\")\n .Filter(\"ptds_d > 2.5\")\n .Filter(\"TMath::Abs(etads_d) < 1.5\")\n .Filter([](int ik, int ipi, Iarray_t nhitrp) { return nhitrp[ik - 1] * nhitrp[ipi - 1] > 1; },\n {\"ik\", \"ipi\", \"nhitrp\"})\n .Filter([](int ik, Farray_t rstart, Farray_t rend) { return rend[ik - 1] - rstart[ik - 1] > 22; },\n {\"ik\", \"rstart\", \"rend\"})\n .Filter([](int ipi, Farray_t rstart, Farray_t rend) { return rend[ipi - 1] - rstart[ipi - 1] > 22; },\n {\"ipi\", \"rstart\", \"rend\"})\n .Filter([](int ik, Farray_t nlhk) { return nlhk[ik - 1] > 0.1; }, {\"ik\", \"nlhk\"})\n .Filter([](int ipi, Farray_t nlhpi) { return nlhpi[ipi - 1] > 0.1; }, {\"ipi\", \"nlhpi\"})\n .Filter([](int ipis, Farray_t nlhpi) { return nlhpi[ipis - 1] > 0.1; }, {\"ipis\", \"nlhpi\"})\n .Filter(\"njets >= 1\");\n\n return ret;\n};\n\nconst Double_t dxbin = (0.17 - 0.13) \/ 40; \/\/ Bin-width\n\nDouble_t fdm5(Double_t *xx, Double_t *par)\n{\n Double_t x = xx[0];\n if (x <= 0.13957)\n return 0;\n Double_t xp3 = (x - par[3]) * (x - par[3]);\n Double_t res =\n dxbin * (par[0] * pow(x - 0.13957, par[1]) + par[2] \/ 2.5066 \/ par[4] * exp(-xp3 \/ 2 \/ par[4] \/ par[4]));\n return res;\n}\n\nDouble_t fdm2(Double_t *xx, Double_t *par)\n{\n static const Double_t sigma = 0.0012;\n Double_t x = xx[0];\n if (x <= 0.13957)\n return 0;\n Double_t xp3 = (x - 0.1454) * (x - 0.1454);\n Double_t res = dxbin * (par[0] * pow(x - 0.13957, 0.25) + par[1] \/ 2.5066 \/ sigma * exp(-xp3 \/ 2 \/ sigma \/ sigma));\n return res;\n}\n\nvoid FitAndPlotHdmd(TH1 &hdmd)\n{\n \/\/ create the canvas for the h1analysis fit\n gStyle->SetOptFit();\n auto c1 = new TCanvas(\"c1\", \"h1analysis analysis\", 10, 10, 800, 600);\n hdmd.GetXaxis()->SetTitle(\"m_{K#pi#pi} - m_{K#pi}[GeV\/c^{2}]\");\n hdmd.GetXaxis()->SetTitleOffset(1.4);\n\n \/\/ fit histogram hdmd with function f5 using the loglikelihood option\n auto f5 = new TF1(\"f5\", fdm5, 0.139, 0.17, 5);\n f5->SetParameters(1000000, .25, 2000, .1454, .001);\n hdmd.Fit(\"f5\", \"lr\");\n\n hdmd.DrawClone();\n}\n\nvoid FitAndPlotH2(TH2 &h2)\n{\n \/\/ create the canvas for tau d0\n auto c2 = new TCanvas(\"c2\", \"tauD0\", 100, 100, 800, 600);\n\n c2->SetGrid();\n c2->SetBottomMargin(0.15);\n\n \/\/ Project slices of 2-d histogram h2 along X , then fit each slice\n \/\/ with function f2 and make a histogram for each fit parameter\n \/\/ Note that the generated histograms are added to the list of objects\n \/\/ in the current directory.\n auto f2 = new TF1(\"f2\", fdm2, 0.139, 0.17, 2);\n f2->SetParameters(10000, 10);\n h2.FitSlicesX(f2, 0, -1, 1, \"qln\");\n\n \/\/ See TH2::FitSlicesX documentation\n auto h2_1 = (TH1D *)gDirectory->Get(\"h2_1\");\n h2_1->GetXaxis()->SetTitle(\"#tau [ps]\");\n h2_1->SetMarkerStyle(21);\n h2_1->DrawClone();\n c2->Update();\n\n auto line = new TLine(0, 0, 0, c2->GetUymax());\n line->Draw();\n}\n\nvoid tdf101_h1Analysis()\n{\n TChain chain(\"h42\");\n chain.Add(\"http:\/\/root.cern.ch\/files\/h1\/dstarmb.root\");\n chain.Add(\"http:\/\/root.cern.ch\/files\/h1\/dstarp1a.root\");\n chain.Add(\"http:\/\/root.cern.ch\/files\/h1\/dstarp1b.root\");\n chain.Add(\"http:\/\/root.cern.ch\/files\/h1\/dstarp2.root\");\n\n ROOT::EnableImplicitMT(4);\n\n ROOT::Experimental::TDataFrame dataFrame(chain);\n auto selected = Select(dataFrame);\n auto hdmdARP = selected.Histo1D({\"hdmd\", \"Dm_d\", 40, 0.13, 0.17}, \"dm_d\");\n auto selectedAddedBranch = selected.Define(\"h2_y\", \"rpd0_t \/ 0.029979f * 1.8646f \/ ptd0_d\");\n auto h2ARP = selectedAddedBranch.Histo2D({\"h2\", \"ptD0 vs Dm_d\", 30, 0.135, 0.165, 30, -3, 6}, \"dm_d\", \"h2_y\");\n\n FitAndPlotHdmd(*hdmdARP);\n FitAndPlotH2(*h2ARP);\n}\nFormatting\/\/\/ \\file\n\/\/\/ \\ingroup tutorial_tdataframe\n\/\/\/ \\notebook\n\/\/\/ This tutorial illustrates how to express the H1 analysis with a TDataFrame.\n\/\/\/\n\/\/\/ \\macro_code\n\/\/\/\n\/\/\/ \\date December 2016\n\/\/\/ \\author Axel Naumann\n\nauto Select = [](ROOT::Experimental::TDataFrame &dataFrame) {\n using Farray_t = ROOT::Experimental::TDF::TArrayBranch;\n using Iarray_t = ROOT::Experimental::TDF::TArrayBranch;\n\n auto ret = dataFrame.Filter(\"TMath::Abs(md0_d - 1.8646) < 0.04\")\n .Filter(\"ptds_d > 2.5\")\n .Filter(\"TMath::Abs(etads_d) < 1.5\")\n .Filter([](int ik, int ipi, Iarray_t nhitrp) { return nhitrp[ik - 1] * nhitrp[ipi - 1] > 1; },\n {\"ik\", \"ipi\", \"nhitrp\"})\n .Filter([](int ik, Farray_t rstart, Farray_t rend) { return rend[ik - 1] - rstart[ik - 1] > 22; },\n {\"ik\", \"rstart\", \"rend\"})\n .Filter([](int ipi, Farray_t rstart, Farray_t rend) { return rend[ipi - 1] - rstart[ipi - 1] > 22; },\n {\"ipi\", \"rstart\", \"rend\"})\n .Filter([](int ik, Farray_t nlhk) { return nlhk[ik - 1] > 0.1; }, {\"ik\", \"nlhk\"})\n .Filter([](int ipi, Farray_t nlhpi) { return nlhpi[ipi - 1] > 0.1; }, {\"ipi\", \"nlhpi\"})\n .Filter([](int ipis, Farray_t nlhpi) { return nlhpi[ipis - 1] > 0.1; }, {\"ipis\", \"nlhpi\"})\n .Filter(\"njets >= 1\");\n\n return ret;\n};\n\nconst Double_t dxbin = (0.17 - 0.13) \/ 40; \/\/ Bin-width\n\nDouble_t fdm5(Double_t *xx, Double_t *par)\n{\n Double_t x = xx[0];\n if (x <= 0.13957)\n return 0;\n Double_t xp3 = (x - par[3]) * (x - par[3]);\n Double_t res =\n dxbin * (par[0] * pow(x - 0.13957, par[1]) + par[2] \/ 2.5066 \/ par[4] * exp(-xp3 \/ 2 \/ par[4] \/ par[4]));\n return res;\n}\n\nDouble_t fdm2(Double_t *xx, Double_t *par)\n{\n static const Double_t sigma = 0.0012;\n Double_t x = xx[0];\n if (x <= 0.13957)\n return 0;\n Double_t xp3 = (x - 0.1454) * (x - 0.1454);\n Double_t res = dxbin * (par[0] * pow(x - 0.13957, 0.25) + par[1] \/ 2.5066 \/ sigma * exp(-xp3 \/ 2 \/ sigma \/ sigma));\n return res;\n}\n\nvoid FitAndPlotHdmd(TH1 &hdmd)\n{\n \/\/ create the canvas for the h1analysis fit\n gStyle->SetOptFit();\n auto c1 = new TCanvas(\"c1\", \"h1analysis analysis\", 10, 10, 800, 600);\n hdmd.GetXaxis()->SetTitle(\"m_{K#pi#pi} - m_{K#pi}[GeV\/c^{2}]\");\n hdmd.GetXaxis()->SetTitleOffset(1.4);\n\n \/\/ fit histogram hdmd with function f5 using the loglikelihood option\n auto f5 = new TF1(\"f5\", fdm5, 0.139, 0.17, 5);\n f5->SetParameters(1000000, .25, 2000, .1454, .001);\n hdmd.Fit(\"f5\", \"lr\");\n\n hdmd.DrawClone();\n}\n\nvoid FitAndPlotH2(TH2 &h2)\n{\n \/\/ create the canvas for tau d0\n auto c2 = new TCanvas(\"c2\", \"tauD0\", 100, 100, 800, 600);\n\n c2->SetGrid();\n c2->SetBottomMargin(0.15);\n\n \/\/ Project slices of 2-d histogram h2 along X , then fit each slice\n \/\/ with function f2 and make a histogram for each fit parameter\n \/\/ Note that the generated histograms are added to the list of objects\n \/\/ in the current directory.\n auto f2 = new TF1(\"f2\", fdm2, 0.139, 0.17, 2);\n f2->SetParameters(10000, 10);\n h2.FitSlicesX(f2, 0, -1, 1, \"qln\");\n\n \/\/ See TH2::FitSlicesX documentation\n auto h2_1 = (TH1D *)gDirectory->Get(\"h2_1\");\n h2_1->GetXaxis()->SetTitle(\"#tau [ps]\");\n h2_1->SetMarkerStyle(21);\n h2_1->DrawClone();\n c2->Update();\n\n auto line = new TLine(0, 0, 0, c2->GetUymax());\n line->Draw();\n}\n\nvoid tdf101_h1Analysis()\n{\n TChain chain(\"h42\");\n chain.Add(\"http:\/\/root.cern.ch\/files\/h1\/dstarmb.root\");\n chain.Add(\"http:\/\/root.cern.ch\/files\/h1\/dstarp1a.root\");\n chain.Add(\"http:\/\/root.cern.ch\/files\/h1\/dstarp1b.root\");\n chain.Add(\"http:\/\/root.cern.ch\/files\/h1\/dstarp2.root\");\n\n ROOT::EnableImplicitMT(4);\n\n ROOT::Experimental::TDataFrame dataFrame(chain);\n auto selected = Select(dataFrame);\n auto hdmdARP = selected.Histo1D({\"hdmd\", \"Dm_d\", 40, 0.13, 0.17}, \"dm_d\");\n auto selectedAddedBranch = selected.Define(\"h2_y\", \"rpd0_t \/ 0.029979f * 1.8646f \/ ptd0_d\");\n auto h2ARP = selectedAddedBranch.Histo2D({\"h2\", \"ptD0 vs Dm_d\", 30, 0.135, 0.165, 30, -3, 6}, \"dm_d\", \"h2_y\");\n\n FitAndPlotHdmd(*hdmdARP);\n FitAndPlotH2(*h2ARP);\n}\n<|endoftext|>"} {"text":"\/*\n\tThis file is part of cpp-ethereum.\n\n\tcpp-ethereum is free software: you can redistribute it and\/or modify\n\tit under the terms of the GNU General Public License as published by\n\tthe Free Software Foundation, either version 3 of the License, or\n\t(at your option) any later version.\n\n\tcpp-ethereum is distributed in the hope that it will be useful,\n\tbut WITHOUT ANY WARRANTY; without even the implied warranty of\n\tMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n\tGNU General Public License for more details.\n\n\tYou should have received a copy of the GNU General Public License\n\talong with cpp-ethereum. If not, see .\n *\/\n\/**\n * @author Marek Kotewicz \n * @date 2014\n * Unit tests for the solidity compiler JSON Interface output.\n *\/\n\n#include \n#include \n#include \n#include \n\nnamespace dev\n{\nnamespace solidity\n{\nnamespace test\n{\n\nclass InterfaceChecker\n{\npublic:\n\tInterfaceChecker(): m_compilerStack(false) {}\n\n\tvoid checkInterface(std::string const& _code, std::string const& _expectedInterfaceString)\n\t{\n\t\ttry\n\t\t{\n\t\t\tm_compilerStack.parse(_code);\n\t\t}\n\t\tcatch(boost::exception const& _e)\n\t\t{\n\t\t\tauto msg = std::string(\"Parsing contract failed with: \") + boost::diagnostic_information(_e);\n\t\t\tBOOST_FAIL(msg);\n\t\t}\n\t\tstd::string generatedInterfaceString = m_compilerStack.getMetadata(\"\", DocumentationType::ABI_INTERFACE);\n\t\tJson::Value generatedInterface;\n\t\tm_reader.parse(generatedInterfaceString, generatedInterface);\n\t\tJson::Value expectedInterface;\n\t\tm_reader.parse(_expectedInterfaceString, expectedInterface);\n\t\tBOOST_CHECK_MESSAGE(expectedInterface == generatedInterface,\n\t\t\t\t\t\t\t\"Expected \" << _expectedInterfaceString <<\n\t\t\t\t\t\t\t\"\\n but got:\\n\" << generatedInterfaceString);\n\t}\n\nprivate:\n\tCompilerStack m_compilerStack;\n\tJson::Reader m_reader;\n};\n\nBOOST_FIXTURE_TEST_SUITE(SolidityABIJSON, InterfaceChecker)\n\nBOOST_AUTO_TEST_CASE(basic_test)\n{\n\tchar const* sourceCode = \"contract test {\\n\"\n\t\" function f(uint a) returns(uint d) { return a * 7; }\\n\"\n\t\"}\\n\";\n\n\tchar const* interface = R\"([\n\t{\n\t\t\"name\": \"f\",\n\t\t\"constant\": false,\n\t\t\"type\": \"function\",\n\t\t\"inputs\": [\n\t\t{\n\t\t\t\"name\": \"a\",\n\t\t\t\"type\": \"uint256\"\n\t\t}\n\t\t],\n\t\t\"outputs\": [\n\t\t{\n\t\t\t\"name\": \"d\",\n\t\t\t\"type\": \"uint256\"\n\t\t}\n\t\t]\n\t}\n\t])\";\n\n\tcheckInterface(sourceCode, interface);\n}\n\nBOOST_AUTO_TEST_CASE(empty_contract)\n{\n\tchar const* sourceCode = \"contract test {\\n\"\n\t\"}\\n\";\n\n\tchar const* interface = \"[]\";\n\n\tcheckInterface(sourceCode, interface);\n}\n\nBOOST_AUTO_TEST_CASE(multiple_methods)\n{\n\tchar const* sourceCode = \"contract test {\\n\"\n\t\" function f(uint a) returns(uint d) { return a * 7; }\\n\"\n\t\" function g(uint b) returns(uint e) { return b * 8; }\\n\"\n\t\"}\\n\";\n\n\tchar const* interface = R\"([\n\t{\n\t\t\"name\": \"f\",\n\t\t\"constant\": false,\n\t\t\"type\": \"function\",\n\t\t\"inputs\": [\n\t\t{\n\t\t\t\"name\": \"a\",\n\t\t\t\"type\": \"uint256\"\n\t\t}\n\t\t],\n\t\t\"outputs\": [\n\t\t{\n\t\t\t\"name\": \"d\",\n\t\t\t\"type\": \"uint256\"\n\t\t}\n\t\t]\n\t},\n\t{\n\t\t\"name\": \"g\",\n\t\t\"constant\": false,\n\t\t\"type\": \"function\",\n\t\t\"inputs\": [\n\t\t{\n\t\t\t\"name\": \"b\",\n\t\t\t\"type\": \"uint256\"\n\t\t}\n\t\t],\n\t\t\"outputs\": [\n\t\t{\n\t\t\t\"name\": \"e\",\n\t\t\t\"type\": \"uint256\"\n\t\t}\n\t\t]\n\t}\n\t])\";\n\n\tcheckInterface(sourceCode, interface);\n}\n\nBOOST_AUTO_TEST_CASE(multiple_params)\n{\n\tchar const* sourceCode = \"contract test {\\n\"\n\t\" function f(uint a, uint b) returns(uint d) { return a + b; }\\n\"\n\t\"}\\n\";\n\n\tchar const* interface = R\"([\n\t{\n\t\t\"name\": \"f\",\n\t\t\"constant\": false,\n\t\t\"type\": \"function\",\n\t\t\"inputs\": [\n\t\t{\n\t\t\t\"name\": \"a\",\n\t\t\t\"type\": \"uint256\"\n\t\t},\n\t\t{\n\t\t\t\"name\": \"b\",\n\t\t\t\"type\": \"uint256\"\n\t\t}\n\t\t],\n\t\t\"outputs\": [\n\t\t{\n\t\t\t\"name\": \"d\",\n\t\t\t\"type\": \"uint256\"\n\t\t}\n\t\t]\n\t}\n\t])\";\n\n\tcheckInterface(sourceCode, interface);\n}\n\nBOOST_AUTO_TEST_CASE(multiple_methods_order)\n{\n\t\/\/ methods are expected to be in alpabetical order\n\tchar const* sourceCode = \"contract test {\\n\"\n\t\" function f(uint a) returns(uint d) { return a * 7; }\\n\"\n\t\" function c(uint b) returns(uint e) { return b * 8; }\\n\"\n\t\"}\\n\";\n\n\tchar const* interface = R\"([\n\t{\n\t\t\"name\": \"c\",\n\t\t\"constant\": false,\n\t\t\"type\": \"function\",\n\t\t\"inputs\": [\n\t\t{\n\t\t\t\"name\": \"b\",\n\t\t\t\"type\": \"uint256\"\n\t\t}\n\t\t],\n\t\t\"outputs\": [\n\t\t{\n\t\t\t\"name\": \"e\",\n\t\t\t\"type\": \"uint256\"\n\t\t}\n\t\t]\n\t},\n\t{\n\t\t\"name\": \"f\",\n\t\t\"constant\": false,\n\t\t\"type\": \"function\",\n\t\t\"inputs\": [\n\t\t{\n\t\t\t\"name\": \"a\",\n\t\t\t\"type\": \"uint256\"\n\t\t}\n\t\t],\n\t\t\"outputs\": [\n\t\t{\n\t\t\t\"name\": \"d\",\n\t\t\t\"type\": \"uint256\"\n\t\t}\n\t\t]\n\t}\n\t])\";\n\n\tcheckInterface(sourceCode, interface);\n}\n\nBOOST_AUTO_TEST_CASE(const_function)\n{\n\tchar const* sourceCode = \"contract test {\\n\"\n\t\" function foo(uint a, uint b) returns(uint d) { return a + b; }\\n\"\n\t\" function boo(uint32 a) constant returns(uint b) { return a * 4; }\\n\"\n\t\"}\\n\";\n\n\tchar const* interface = R\"([\n\t{\n\t\t\"name\": \"foo\",\n\t\t\"constant\": false,\n\t\t\"type\": \"function\",\n\t\t\"inputs\": [\n\t\t{\n\t\t\t\"name\": \"a\",\n\t\t\t\"type\": \"uint256\"\n\t\t},\n\t\t{\n\t\t\t\"name\": \"b\",\n\t\t\t\"type\": \"uint256\"\n\t\t}\n\t\t],\n\t\t\"outputs\": [\n\t\t{\n\t\t\t\"name\": \"d\",\n\t\t\t\"type\": \"uint256\"\n\t\t}\n\t\t]\n\t},\n\t{\n\t\t\"name\": \"boo\",\n\t\t\"constant\": true,\n\t\t\"type\": \"function\",\n\t\t\"inputs\": [{\n\t\t\t\"name\": \"a\",\n\t\t\t\"type\": \"uint32\"\n\t\t}],\n\t\t\"outputs\": [\n\t\t{\n\t\t\t\"name\": \"b\",\n\t\t\t\"type\": \"uint256\"\n\t\t}\n\t\t]\n\t}\n\t])\";\n\n\tcheckInterface(sourceCode, interface);\n}\n\nBOOST_AUTO_TEST_CASE(exclude_fallback_function)\n{\n\tchar const* sourceCode = \"contract test { function() {} }\";\n\n\tchar const* interface = \"[]\";\n\n\tcheckInterface(sourceCode, interface);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n\n}\n}\n}\njson and solidity ABI generted for events\/*\n\tThis file is part of cpp-ethereum.\n\n\tcpp-ethereum is free software: you can redistribute it and\/or modify\n\tit under the terms of the GNU General Public License as published by\n\tthe Free Software Foundation, either version 3 of the License, or\n\t(at your option) any later version.\n\n\tcpp-ethereum is distributed in the hope that it will be useful,\n\tbut WITHOUT ANY WARRANTY; without even the implied warranty of\n\tMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n\tGNU General Public License for more details.\n\n\tYou should have received a copy of the GNU General Public License\n\talong with cpp-ethereum. If not, see .\n *\/\n\/**\n * @author Marek Kotewicz \n * @date 2014\n * Unit tests for the solidity compiler JSON Interface output.\n *\/\n\n#include \n#include \n#include \n#include \n\nnamespace dev\n{\nnamespace solidity\n{\nnamespace test\n{\n\nclass InterfaceChecker\n{\npublic:\n\tInterfaceChecker(): m_compilerStack(false) {}\n\n\tvoid checkInterface(std::string const& _code, std::string const& _expectedInterfaceString, std::string const& expectedSolidityInterface)\n\t{\n\t\ttry\n\t\t{\n\t\t\tm_compilerStack.parse(_code);\n\t\t}\n\t\tcatch(boost::exception const& _e)\n\t\t{\n\t\t\tauto msg = std::string(\"Parsing contract failed with: \") + boost::diagnostic_information(_e);\n\t\t\tBOOST_FAIL(msg);\n\t\t}\n\t\tstd::string generatedInterfaceString = m_compilerStack.getMetadata(\"\", DocumentationType::ABI_INTERFACE);\n\t\tstd::string generatedSolidityInterfaceString = m_compilerStack.getMetadata(\"\", DocumentationType::ABI_SOLIDITY_INTERFACE);\n\t\tJson::Value generatedInterface;\n\t\tm_reader.parse(generatedInterfaceString, generatedInterface);\n\t\tJson::Value expectedInterface;\n\t\tm_reader.parse(_expectedInterfaceString, expectedInterface);\n\t\tBOOST_CHECK_MESSAGE(expectedInterface == generatedInterface,\n\t\t\t\t\t\t\t\"Expected:\\n\" << expectedInterface.toStyledString() <<\n\t\t\t\t\t\t\t\"\\n but got:\\n\" << generatedInterface.toStyledString());\n\t\tBOOST_CHECK_MESSAGE(expectedSolidityInterface == generatedSolidityInterfaceString,\n\t\t\t\t\t\t\t\"Expected:\\n\" << expectedSolidityInterface <<\n\t\t\t\t\t\t\t\"\\n but got:\\n\" << generatedSolidityInterfaceString);\n\t}\n\nprivate:\n\tCompilerStack m_compilerStack;\n\tJson::Reader m_reader;\n};\n\nBOOST_FIXTURE_TEST_SUITE(SolidityABIJSON, InterfaceChecker)\n\nBOOST_AUTO_TEST_CASE(basic_test)\n{\n\tchar const* sourceCode = \"contract test {\\n\"\n\t\" function f(uint a) returns(uint d) { return a * 7; }\\n\"\n\t\"}\\n\";\n\n\tchar const* sourceInterface = \"contract test{function f(uint256 a)returns(uint256 d){}}\";\n\n\tchar const* interface = R\"([\n\t{\n\t\t\"name\": \"f\",\n\t\t\"constant\": false,\n\t\t\"type\": \"function\",\n\t\t\"inputs\": [\n\t\t{\n\t\t\t\"name\": \"a\",\n\t\t\t\"type\": \"uint256\"\n\t\t}\n\t\t],\n\t\t\"outputs\": [\n\t\t{\n\t\t\t\"name\": \"d\",\n\t\t\t\"type\": \"uint256\"\n\t\t}\n\t\t]\n\t}\n\t])\";\n\n\tcheckInterface(sourceCode, interface, sourceInterface);\n}\n\nBOOST_AUTO_TEST_CASE(empty_contract)\n{\n\tchar const* sourceCode = \"contract test {\\n\"\n\t\"}\\n\";\n\tchar const* sourceInterface = \"contract test{}\";\n\n\tchar const* interface = \"[]\";\n\n\tcheckInterface(sourceCode, interface, sourceInterface);\n}\n\nBOOST_AUTO_TEST_CASE(multiple_methods)\n{\n\tchar const* sourceCode = \"contract test {\\n\"\n\t\" function f(uint a) returns(uint d) { return a * 7; }\\n\"\n\t\" function g(uint b) returns(uint e) { return b * 8; }\\n\"\n\t\"}\\n\";\n\tchar const* sourceInterface = \"contract test{function f(uint256 a)returns(uint256 d){}function g(uint256 b)returns(uint256 e){}}\";\n\n\tchar const* interface = R\"([\n\t{\n\t\t\"name\": \"f\",\n\t\t\"constant\": false,\n\t\t\"type\": \"function\",\n\t\t\"inputs\": [\n\t\t{\n\t\t\t\"name\": \"a\",\n\t\t\t\"type\": \"uint256\"\n\t\t}\n\t\t],\n\t\t\"outputs\": [\n\t\t{\n\t\t\t\"name\": \"d\",\n\t\t\t\"type\": \"uint256\"\n\t\t}\n\t\t]\n\t},\n\t{\n\t\t\"name\": \"g\",\n\t\t\"constant\": false,\n\t\t\"type\": \"function\",\n\t\t\"inputs\": [\n\t\t{\n\t\t\t\"name\": \"b\",\n\t\t\t\"type\": \"uint256\"\n\t\t}\n\t\t],\n\t\t\"outputs\": [\n\t\t{\n\t\t\t\"name\": \"e\",\n\t\t\t\"type\": \"uint256\"\n\t\t}\n\t\t]\n\t}\n\t])\";\n\n\tcheckInterface(sourceCode, interface, sourceInterface);\n}\n\nBOOST_AUTO_TEST_CASE(multiple_params)\n{\n\tchar const* sourceCode = \"contract test {\\n\"\n\t\" function f(uint a, uint b) returns(uint d) { return a + b; }\\n\"\n\t\"}\\n\";\n\tchar const* sourceInterface = \"contract test{function f(uint256 a,uint256 b)returns(uint256 d){}}\";\n\n\tchar const* interface = R\"([\n\t{\n\t\t\"name\": \"f\",\n\t\t\"constant\": false,\n\t\t\"type\": \"function\",\n\t\t\"inputs\": [\n\t\t{\n\t\t\t\"name\": \"a\",\n\t\t\t\"type\": \"uint256\"\n\t\t},\n\t\t{\n\t\t\t\"name\": \"b\",\n\t\t\t\"type\": \"uint256\"\n\t\t}\n\t\t],\n\t\t\"outputs\": [\n\t\t{\n\t\t\t\"name\": \"d\",\n\t\t\t\"type\": \"uint256\"\n\t\t}\n\t\t]\n\t}\n\t])\";\n\n\tcheckInterface(sourceCode, interface, sourceInterface);\n}\n\nBOOST_AUTO_TEST_CASE(multiple_methods_order)\n{\n\t\/\/ methods are expected to be in alpabetical order\n\tchar const* sourceCode = \"contract test {\\n\"\n\t\" function f(uint a) returns(uint d) { return a * 7; }\\n\"\n\t\" function c(uint b) returns(uint e) { return b * 8; }\\n\"\n\t\"}\\n\";\n\tchar const* sourceInterface = \"contract test{function c(uint256 b)returns(uint256 e){}function f(uint256 a)returns(uint256 d){}}\";\n\n\tchar const* interface = R\"([\n\t{\n\t\t\"name\": \"c\",\n\t\t\"constant\": false,\n\t\t\"type\": \"function\",\n\t\t\"inputs\": [\n\t\t{\n\t\t\t\"name\": \"b\",\n\t\t\t\"type\": \"uint256\"\n\t\t}\n\t\t],\n\t\t\"outputs\": [\n\t\t{\n\t\t\t\"name\": \"e\",\n\t\t\t\"type\": \"uint256\"\n\t\t}\n\t\t]\n\t},\n\t{\n\t\t\"name\": \"f\",\n\t\t\"constant\": false,\n\t\t\"type\": \"function\",\n\t\t\"inputs\": [\n\t\t{\n\t\t\t\"name\": \"a\",\n\t\t\t\"type\": \"uint256\"\n\t\t}\n\t\t],\n\t\t\"outputs\": [\n\t\t{\n\t\t\t\"name\": \"d\",\n\t\t\t\"type\": \"uint256\"\n\t\t}\n\t\t]\n\t}\n\t])\";\n\n\tcheckInterface(sourceCode, interface, sourceInterface);\n}\n\nBOOST_AUTO_TEST_CASE(const_function)\n{\n\tchar const* sourceCode = \"contract test {\\n\"\n\t\" function foo(uint a, uint b) returns(uint d) { return a + b; }\\n\"\n\t\" function boo(uint32 a) constant returns(uint b) { return a * 4; }\\n\"\n\t\"}\\n\";\n\tchar const* sourceInterface = \"contract test{function foo(uint256 a,uint256 b)returns(uint256 d){}function boo(uint32 a)constant returns(uint256 b){}}\";\n\n\tchar const* interface = R\"([\n\t{\n\t\t\"name\": \"foo\",\n\t\t\"constant\": false,\n\t\t\"type\": \"function\",\n\t\t\"inputs\": [\n\t\t{\n\t\t\t\"name\": \"a\",\n\t\t\t\"type\": \"uint256\"\n\t\t},\n\t\t{\n\t\t\t\"name\": \"b\",\n\t\t\t\"type\": \"uint256\"\n\t\t}\n\t\t],\n\t\t\"outputs\": [\n\t\t{\n\t\t\t\"name\": \"d\",\n\t\t\t\"type\": \"uint256\"\n\t\t}\n\t\t]\n\t},\n\t{\n\t\t\"name\": \"boo\",\n\t\t\"constant\": true,\n\t\t\"type\": \"function\",\n\t\t\"inputs\": [{\n\t\t\t\"name\": \"a\",\n\t\t\t\"type\": \"uint32\"\n\t\t}],\n\t\t\"outputs\": [\n\t\t{\n\t\t\t\"name\": \"b\",\n\t\t\t\"type\": \"uint256\"\n\t\t}\n\t\t]\n\t}\n\t])\";\n\n\tcheckInterface(sourceCode, interface, sourceInterface);\n}\n\nBOOST_AUTO_TEST_CASE(exclude_fallback_function)\n{\n\tchar const* sourceCode = \"contract test { function() {} }\";\n\tchar const* sourceInterface = \"contract test{}\";\n\n\tchar const* interface = \"[]\";\n\n\tcheckInterface(sourceCode, interface, sourceInterface);\n}\n\nBOOST_AUTO_TEST_CASE(events)\n{\n\tchar const* sourceCode = \"contract test {\\n\"\n\t\" function f(uint a) returns(uint d) { return a * 7; }\\n\"\n\t\" event e1(uint b, address indexed c); \\n\"\n\t\" event e2(); \\n\"\n\t\"}\\n\";\n\tchar const* sourceInterface = \"contract test{function f(uint256 a)returns(uint256 d){}event e1(uint256 b,address indexed c);event e2;}\";\n\n\tchar const* interface = R\"([\n\t{\n\t\t\"name\": \"f\",\n\t\t\"constant\": false,\n\t\t\"type\": \"function\",\n\t\t\"inputs\": [\n\t\t{\n\t\t\t\"name\": \"a\",\n\t\t\t\"type\": \"uint256\"\n\t\t}\n\t\t],\n\t\t\"outputs\": [\n\t\t{\n\t\t\t\"name\": \"d\",\n\t\t\t\"type\": \"uint256\"\n\t\t}\n\t\t]\n\t},\n\t{\n\t\t\"name\": \"e1\",\n\t\t\"type\": \"event\",\n\t\t\"inputs\": [\n\t\t{\n\t\t\t\"indexed\": false,\n\t\t\t\"name\": \"b\",\n\t\t\t\"type\": \"uint256\"\n\t\t},\n\t\t{\n\t\t\t\"indexed\": true,\n\t\t\t\"name\": \"c\",\n\t\t\t\"type\": \"address\"\n\t\t}\n\t\t]\n\t},\n\t{\n\t\t\"name\": \"e2\",\n\t\t\"type\": \"event\",\n\t\t\"inputs\": []\n\t}\n\n\t])\";\n\n\tcheckInterface(sourceCode, interface, sourceInterface);\n}\n\n\nBOOST_AUTO_TEST_CASE(inherited)\n{\n\tchar const* sourceCode =\n\t\"\tcontract Base { \\n\"\n\t\"\t\tfunction baseFunction(uint p) returns (uint i) { return p; } \\n\"\n\t\"\t\tevent baseEvent(string32 indexed evtArgBase); \\n\"\n\t\"\t} \\n\"\n\t\"\tcontract Derived is Base { \\n\"\n\t\"\t\tfunction derivedFunction(string32 p) returns (string32 i) { return p; } \\n\"\n\t\"\t\tevent derivedEvent(uint indexed evtArgDerived); \\n\"\n\t\"\t}\";\n\tchar const* sourceInterface = \"contract Derived{function baseFunction(uint256 p)returns(uint256 i){}function derivedFunction(string32 p)returns(string32 i){}event derivedEvent(uint256 indexed evtArgDerived);event baseEvent(string32 indexed evtArgBase);}\";\n\n\tchar const* interface = R\"([\n\t{\n\t\t\"name\": \"baseFunction\",\n\t\t\"constant\": false,\n\t\t\"type\": \"function\",\n\t\t\"inputs\":\n\t\t[{\n\t\t\t\"name\": \"p\",\n\t\t\t\"type\": \"uint256\"\n\t\t}],\n\t\t\"outputs\":\n\t\t[{\n\t\t\t\"name\": \"i\",\n\t\t\t\"type\": \"uint256\"\n\t\t}]\n\t},\n\t{\n\t\t\"name\": \"derivedFunction\",\n\t\t\"constant\": false,\n\t\t\"type\": \"function\",\n\t\t\"inputs\":\n\t\t[{\n\t\t\t\"name\": \"p\",\n\t\t\t\"type\": \"string32\"\n\t\t}],\n\t\t\"outputs\":\n\t\t[{\n\t\t\t\"name\": \"i\",\n\t\t\t\"type\": \"string32\"\n\t\t}]\n\t},\n\t{\n\t\t\"name\": \"derivedEvent\",\n\t\t\"type\": \"event\",\n\t\t\"inputs\":\n\t\t[{\n\t\t\t\"indexed\": true,\n\t\t\t\"name\": \"evtArgDerived\",\n\t\t\t\"type\": \"uint256\"\n\t\t}]\n\t},\n\t{\n\t\t\"name\": \"baseEvent\",\n\t\t\"type\": \"event\",\n\t\t\"inputs\":\n\t\t[{\n\t\t\t\"indexed\": true,\n\t\t\t\"name\": \"evtArgBase\",\n\t\t\t\"type\": \"string32\"\n\t\t}]\n\t}])\";\n\n\n\tcheckInterface(sourceCode, interface, sourceInterface);\n}\n\n\nBOOST_AUTO_TEST_SUITE_END()\n\n}\n}\n}\n<|endoftext|>"} {"text":"\/\/ Copyright (C) 2010 - 2013 by Pedro Mendes, Virginia Tech Intellectual\n\/\/ Properties, Inc., University of Heidelberg, and The University\n\/\/ of Manchester.\n\/\/ All rights reserved.\n\n\/\/ Copyright (C) 2008 - 2009 by Pedro Mendes, Virginia Tech Intellectual\n\/\/ Properties, Inc., EML Research, gGmbH, University of Heidelberg,\n\/\/ and The University of Manchester.\n\/\/ All rights reserved.\n\n\/\/ Copyright (C) 2005 - 2007 by Pedro Mendes, Virginia Tech Intellectual\n\/\/ Properties, Inc. and EML Research, gGmbH.\n\/\/ All rights reserved.\n\n#include \n#include \n#include \n\n#include \n\n#include \"SensitivitiesWidget.h\"\n#include \"DataModelGUI.h\"\n#include \"qtUtilities.h\"\n#include \"CQTaskBtnWidget.h\"\n#include \"CQTaskHeaderWidget.h\"\n#include \"CQTaskMethodWidget.h\"\n#include \"CCopasiSelectionDialog.h\"\n#include \"resourcesUI\/CQIconResource.h\"\n\n#include \"CopasiDataModel\/CCopasiDataModel.h\"\n#include \"report\/CCopasiRootContainer.h\"\n#include \"sensitivities\/CSensTask.h\"\n#include \"sensitivities\/CSensProblem.h\"\n#include \"sensitivities\/CSensMethod.h\"\n#include \"model\/CModel.h\"\n#include \"utilities\/CCopasiException.h\"\n#include \"report\/CKeyFactory.h\"\n#include \"CQSensResultWidget.h\"\n\n\/**\n * Constructs a SensitivitiesWidget which is a child of 'parent', with the\n * name 'name' and widget flags set to 'f'.\n *\/\nSensitivitiesWidget::SensitivitiesWidget(QWidget* parent, const char* name, Qt::WFlags fl)\n : TaskWidget(parent, name, fl),\n mpSingleFunction(NULL),\n mpSingleVariable(NULL),\n mpSingleVariable2(NULL)\n{\n setupUi(this);\n\n init();\n retranslateUi(this);\n}\n\n\/*\n * Destroys the object and frees any allocated resources\n *\/\nSensitivitiesWidget::~SensitivitiesWidget()\n{}\n\nvoid SensitivitiesWidget::init()\n{\n mpHeaderWidget->setTaskName(\"Sensitivities\");\n\n verticalLayout->insertWidget(0, mpHeaderWidget); \/\/ header\n \/\/ verticalLayout->insertSpacing(1, 14); \/\/ space between header and body\n\n mpMethodWidget->showMethodParameters(true);\n verticalLayout->addWidget(mpMethodWidget);\n\n verticalLayout->addWidget(mpBtnWidget); \/\/ 'footer'\n\n \/\/ icons\n SingleFunctionChooser->setIcon(CQIconResource::icon(CQIconResource::copasi));\n SingleVariableChooser->setIcon(CQIconResource::icon(CQIconResource::copasi));\n SingleVariable2Chooser->setIcon(CQIconResource::icon(CQIconResource::copasi));\n\n \/\/ initialization\n initCombos();\n}\n\nbool SensitivitiesWidget::saveTask()\n{\n saveCommon();\n saveMethod();\n\n CSensTask* sensTask =\n dynamic_cast(CCopasiRootContainer::getKeyFactory()->get(mKey));\n\n if (sensTask == NULL)\n return false;\n\n CSensProblem* problem =\n dynamic_cast(sensTask->getProblem());\n\n if (problem == NULL)\n return false;\n\n CSensMethod* method =\n dynamic_cast(sensTask->getMethod());\n\n if (method == NULL)\n return false;\n\n \/\/ subtask\n problem->setSubTaskType((CSensProblem::SubTaskType)SubTaskChooser->currentIndex());\n\n CSensItem tmp;\n\n \/\/ target function\n if (FunctionChooser->getCurrentObjectList() == CObjectLists::SINGLE_OBJECT)\n {\n if (mpSingleFunction)\n tmp.setSingleObjectCN(mpSingleFunction->getCN());\n }\n else\n tmp.setListType(FunctionChooser->getCurrentObjectList());\n\n problem->changeTargetFunctions(tmp);\n\n \/\/ variables 1\n if (VariableChooser->getCurrentObjectList() == CObjectLists::SINGLE_OBJECT)\n {\n if (mpSingleVariable)\n tmp.setSingleObjectCN(mpSingleVariable->getCN());\n }\n else\n tmp.setListType(VariableChooser->getCurrentObjectList());\n\n problem->removeVariables();\n\n if (tmp.getListType() != CObjectLists::EMPTY_LIST)\n problem->addVariables(tmp);\n else\n return true;\n\n \/\/variables 2\n CSensItem tmp2;\n\n if (Variable2Chooser->getCurrentObjectList() == CObjectLists::SINGLE_OBJECT)\n {\n if (mpSingleVariable2)\n tmp2.setSingleObjectCN(mpSingleVariable2->getCN());\n }\n else\n tmp2.setListType(Variable2Chooser->getCurrentObjectList());\n\n \/\/ write variables to problem\n problem->removeVariables();\n\n if (tmp.getListType() != CObjectLists::EMPTY_LIST)\n {\n problem->addVariables(tmp);\n\n if (tmp2.getListType() != CObjectLists::EMPTY_LIST)\n problem->addVariables(tmp2);\n }\n\n \/\/ :TODO Bug 322: This should only be called when actual changes have been saved.\n \/\/ However we do not track the changes for the variables we just delete them and add them again.\n if (true)\n {\n if (mpDataModel != NULL)\n {\n mpDataModel->changed();\n }\n\n mChanged = false;\n }\n\n return true;\n}\n\nCCopasiMethod * SensitivitiesWidget::createMethod(const CCopasiMethod::SubType & type)\n{return CSensMethod::createMethod(type);}\n\nbool SensitivitiesWidget::runTask()\n{\n if (FunctionChooser->getCurrentObjectList() != CObjectLists::SINGLE_OBJECT)\n FunctionLineEdit->setText(QApplication::translate(\"SensitivitiesWidget\", \"[Please Choose Object.] --->\", 0, QApplication::UnicodeUTF8));\n\n if (!commonBeforeRunTask()) return false;\n\n bool success = true;\n\n if (!commonRunTask()) success = false;\n\n return success;\n}\n\nbool SensitivitiesWidget::taskFinishedEvent()\n{\n bool success = true;\n \/\/setup the result widget\n CQSensResultWidget *pResult =\n dynamic_cast(mpListView->findWidgetFromId(341));\n\n if (pResult) pResult->newResult();\n\n if (success && isVisible()) mpListView->switchToOtherWidget(341, \"\"); \/\/change to the results window\n\n return success;\n}\n\nbool SensitivitiesWidget::loadTask()\n{\n loadCommon();\n loadMethod();\n\n CSensTask* sensTask =\n dynamic_cast(CCopasiRootContainer::getKeyFactory()->get(mKey));\n assert(sensTask);\n\n CSensProblem* problem =\n dynamic_cast(sensTask->getProblem());\n assert(problem);\n\n \/\/CSensMethod* method =\n \/\/ dynamic_cast(sensTask->getMethod());\n \/\/assert(method);\n\n \/\/mSubTaskType = problem->getSubTaskType();\n SubTaskChooser->setCurrentIndex((int)problem->getSubTaskType());\n updateComboBoxes(problem->getSubTaskType());\n\n CSensItem tmp = problem->getTargetFunctions();\n\n \/\/target function\n assert(CCopasiRootContainer::getDatamodelList()->size() > 0);\n CCopasiDataModel* pDataModel = (*CCopasiRootContainer::getDatamodelList())[0];\n assert(pDataModel != NULL);\n\n if (tmp.isSingleObject())\n {\n FunctionChooser->setCurrentObjectList(CObjectLists::SINGLE_OBJECT);\n mpSingleFunction = pDataModel->getDataObject(tmp.getSingleObjectCN());\n\n if (mpSingleFunction)\n FunctionLineEdit->setText(FROM_UTF8(mpSingleFunction->getObjectDisplayName()));\n }\n else\n {\n mpSingleFunction = NULL;\n FunctionChooser->setCurrentObjectList(tmp.getListType());\n }\n\n \/\/variables 1\n if (problem->getNumberOfVariables() > 0)\n {\n tmp = problem->getVariables(0);\n\n if (tmp.isSingleObject())\n {\n VariableChooser->setCurrentObjectList(CObjectLists::SINGLE_OBJECT);\n mpSingleVariable = pDataModel->getDataObject(tmp.getSingleObjectCN());\n\n if (mpSingleVariable)\n VariableLineEdit->setText(FROM_UTF8(mpSingleVariable->getObjectDisplayName()));\n }\n else\n VariableChooser->setCurrentObjectList(tmp.getListType());\n }\n else\n {\n VariableChooser->setCurrentObjectList(CObjectLists::EMPTY_LIST);\n mpSingleVariable = NULL;\n }\n\n \/\/variables 2\n if (problem->getNumberOfVariables() > 1)\n {\n tmp = problem->getVariables(1);\n\n if (tmp.isSingleObject())\n {\n Variable2Chooser->setCurrentObjectList(CObjectLists::SINGLE_OBJECT);\n mpSingleVariable2 = pDataModel->getDataObject(tmp.getSingleObjectCN());\n\n if (mpSingleVariable2)\n Variable2LineEdit->setText(FROM_UTF8(mpSingleVariable2->getObjectDisplayName()));\n }\n else\n Variable2Chooser->setCurrentObjectList(tmp.getListType());\n }\n else\n {\n Variable2Chooser->setCurrentObjectList(CObjectLists::EMPTY_LIST);\n mpSingleVariable2 = NULL;\n }\n\n \/\/ initCombos(problem);\n\n mChanged = false;\n\n updateAllLineditEnable();\n return true;\n}\n\n\/\/**************************************************************************\n\nvoid SensitivitiesWidget::updateLineeditEnable(const SensWidgetComboBox* box, QWidget* w1, QWidget* w2)\n{\n if (!box) return;\n\n bool enable = false;\n\n if (box->getCurrentObjectList() == CObjectLists::SINGLE_OBJECT)\n enable = true;\n\n if (w1) w1->setVisible(enable);\n\n if (w2) w2->setVisible(enable);\n}\n\nvoid SensitivitiesWidget::updateAllLineditEnable()\n{\n \/*\n updateLineeditEnable(FunctionChooser, FunctionLineEdit, SingleFunctionChooserButton);\n updateLineeditEnable(VariableChooser, VariableLineEdit, SingleVariableChooserButton);\n updateLineeditEnable(Variable2Chooser, Variable2LineEdit, SingleVariable2ChooserButton);\n *\/\n updateLineeditEnable(FunctionChooser, FunctionLineEdit, SingleFunctionChooser);\n updateLineeditEnable(VariableChooser, VariableLineEdit, SingleVariableChooser);\n updateLineeditEnable(Variable2Chooser, Variable2LineEdit, SingleVariable2Chooser);\n}\n\nvoid\nSensitivitiesWidget::initCombos()\n{\n QStringList StringList;\n \/\/std::vector mFunctionIndexTable, mVariableIndexTable;\n\n \/\/ SubTaskChooser combo\n int i = 0;\n\n while (CSensProblem::SubTaskName[i].length() > 0)\n {\n StringList.append(FROM_UTF8(CSensProblem::SubTaskName[i]));\n ++i;\n }\n\n SubTaskChooser->insertItems(SubTaskChooser->count(), StringList);\n SubTaskChooser->setCurrentIndex(0);\n updateComboBoxes((CSensProblem::SubTaskType)0);\n}\n\nvoid SensitivitiesWidget::updateComboBoxes(CSensProblem::SubTaskType type)\n{\n FunctionChooser->fillFromList(CSensProblem::getPossibleTargetFunctions(type));\n VariableChooser->fillFromList(CSensProblem::getPossibleVariables(type));\n Variable2Chooser->fillFromList(CSensProblem::getPossibleVariables(type));\n}\n\n\/\/ ******************* SLOTs *******************************+\n\nvoid\n\/\/SensitivitiesWidget::on_SubTaskChooser_activated(int)\nSensitivitiesWidget::slotChooseSubTask(int)\n{\n CSensProblem::SubTaskType subTaskType = (CSensProblem::SubTaskType)SubTaskChooser->currentIndex();\n updateComboBoxes(subTaskType);\n\n updateAllLineditEnable();\n}\n\nvoid\n\/\/SensitivitiesWidget::on_FunctionChooser_activated(int a)\nSensitivitiesWidget::slotChooseFunction(int)\n{\n updateAllLineditEnable();\n}\n\nvoid\n\/\/SensitivitiesWidget::on_VariableChooser_activated(int)\nSensitivitiesWidget::slotChooseVariable(int)\n{\n updateAllLineditEnable();\n}\n\nvoid\n\/\/SensitivitiesWidget::on_Variable2Chooser_activated(int)\nSensitivitiesWidget::slotChooseVariable2(int)\n{\n updateAllLineditEnable();\n}\n\nvoid\n\/\/SensitivitiesWidget::on_SingleFunctionChooser_clicked()\nSensitivitiesWidget::slotChooseSingleFunction()\n{\n const CCopasiObject * pObject =\n CCopasiSelectionDialog::getObjectSingle(this,\n CQSimpleSelectionTree::Variables |\n CQSimpleSelectionTree::ObservedValues |\n CQSimpleSelectionTree::ObservedConstants);\n\n if (pObject)\n {\n FunctionLineEdit->setText(FROM_UTF8(pObject->getObjectDisplayName()));\n mpSingleFunction = pObject;\n FunctionChooser->setCurrentObjectList(CObjectLists::SINGLE_OBJECT);\n }\n}\n\nvoid\n\/\/SensitivitiesWidget::on_SingleVariableChooser_clicked()\nSensitivitiesWidget::slotChooseSingleVariable()\n{\n const CCopasiObject * pObject =\n CCopasiSelectionDialog::getObjectSingle(this,\n CQSimpleSelectionTree::InitialTime |\n CQSimpleSelectionTree::Parameters);\n\n if (pObject)\n {\n VariableLineEdit->setText(FROM_UTF8(pObject->getObjectDisplayName()));\n mpSingleVariable = pObject;\n VariableChooser->setCurrentObjectList(CObjectLists::SINGLE_OBJECT);\n }\n}\n\nvoid\n\/\/SensitivitiesWidget::on_SingleVariable2Chooser_clicked()\nSensitivitiesWidget::slotChooseSingleVariable2()\n{\n const CCopasiObject * pObject =\n CCopasiSelectionDialog::getObjectSingle(this,\n CQSimpleSelectionTree::InitialTime |\n CQSimpleSelectionTree::Parameters);\n\n if (pObject)\n {\n Variable2LineEdit->setText(FROM_UTF8(pObject->getObjectDisplayName()));\n mpSingleVariable2 = pObject;\n Variable2Chooser->setCurrentObjectList(CObjectLists::SINGLE_OBJECT);\n }\n}\nFixed Bug 2097. The constant are no longer shown in the object browser.\/\/ Copyright (C) 2010 - 2014 by Pedro Mendes, Virginia Tech Intellectual\n\/\/ Properties, Inc., University of Heidelberg, and The University\n\/\/ of Manchester.\n\/\/ All rights reserved.\n\n\/\/ Copyright (C) 2008 - 2009 by Pedro Mendes, Virginia Tech Intellectual\n\/\/ Properties, Inc., EML Research, gGmbH, University of Heidelberg,\n\/\/ and The University of Manchester.\n\/\/ All rights reserved.\n\n\/\/ Copyright (C) 2005 - 2007 by Pedro Mendes, Virginia Tech Intellectual\n\/\/ Properties, Inc. and EML Research, gGmbH.\n\/\/ All rights reserved.\n\n#include \n#include \n#include \n\n#include \n\n#include \"SensitivitiesWidget.h\"\n#include \"DataModelGUI.h\"\n#include \"qtUtilities.h\"\n#include \"CQTaskBtnWidget.h\"\n#include \"CQTaskHeaderWidget.h\"\n#include \"CQTaskMethodWidget.h\"\n#include \"CCopasiSelectionDialog.h\"\n#include \"resourcesUI\/CQIconResource.h\"\n\n#include \"CopasiDataModel\/CCopasiDataModel.h\"\n#include \"report\/CCopasiRootContainer.h\"\n#include \"sensitivities\/CSensTask.h\"\n#include \"sensitivities\/CSensProblem.h\"\n#include \"sensitivities\/CSensMethod.h\"\n#include \"model\/CModel.h\"\n#include \"utilities\/CCopasiException.h\"\n#include \"report\/CKeyFactory.h\"\n#include \"CQSensResultWidget.h\"\n\n\/**\n * Constructs a SensitivitiesWidget which is a child of 'parent', with the\n * name 'name' and widget flags set to 'f'.\n *\/\nSensitivitiesWidget::SensitivitiesWidget(QWidget* parent, const char* name, Qt::WFlags fl)\n : TaskWidget(parent, name, fl),\n mpSingleFunction(NULL),\n mpSingleVariable(NULL),\n mpSingleVariable2(NULL)\n{\n setupUi(this);\n\n init();\n retranslateUi(this);\n}\n\n\/*\n * Destroys the object and frees any allocated resources\n *\/\nSensitivitiesWidget::~SensitivitiesWidget()\n{}\n\nvoid SensitivitiesWidget::init()\n{\n mpHeaderWidget->setTaskName(\"Sensitivities\");\n\n verticalLayout->insertWidget(0, mpHeaderWidget); \/\/ header\n \/\/ verticalLayout->insertSpacing(1, 14); \/\/ space between header and body\n\n mpMethodWidget->showMethodParameters(true);\n verticalLayout->addWidget(mpMethodWidget);\n\n verticalLayout->addWidget(mpBtnWidget); \/\/ 'footer'\n\n \/\/ icons\n SingleFunctionChooser->setIcon(CQIconResource::icon(CQIconResource::copasi));\n SingleVariableChooser->setIcon(CQIconResource::icon(CQIconResource::copasi));\n SingleVariable2Chooser->setIcon(CQIconResource::icon(CQIconResource::copasi));\n\n \/\/ initialization\n initCombos();\n}\n\nbool SensitivitiesWidget::saveTask()\n{\n saveCommon();\n saveMethod();\n\n CSensTask* sensTask =\n dynamic_cast(CCopasiRootContainer::getKeyFactory()->get(mKey));\n\n if (sensTask == NULL)\n return false;\n\n CSensProblem* problem =\n dynamic_cast(sensTask->getProblem());\n\n if (problem == NULL)\n return false;\n\n CSensMethod* method =\n dynamic_cast(sensTask->getMethod());\n\n if (method == NULL)\n return false;\n\n \/\/ subtask\n problem->setSubTaskType((CSensProblem::SubTaskType)SubTaskChooser->currentIndex());\n\n CSensItem tmp;\n\n \/\/ target function\n if (FunctionChooser->getCurrentObjectList() == CObjectLists::SINGLE_OBJECT)\n {\n if (mpSingleFunction)\n tmp.setSingleObjectCN(mpSingleFunction->getCN());\n }\n else\n tmp.setListType(FunctionChooser->getCurrentObjectList());\n\n problem->changeTargetFunctions(tmp);\n\n \/\/ variables 1\n if (VariableChooser->getCurrentObjectList() == CObjectLists::SINGLE_OBJECT)\n {\n if (mpSingleVariable)\n tmp.setSingleObjectCN(mpSingleVariable->getCN());\n }\n else\n tmp.setListType(VariableChooser->getCurrentObjectList());\n\n problem->removeVariables();\n\n if (tmp.getListType() != CObjectLists::EMPTY_LIST)\n problem->addVariables(tmp);\n else\n return true;\n\n \/\/variables 2\n CSensItem tmp2;\n\n if (Variable2Chooser->getCurrentObjectList() == CObjectLists::SINGLE_OBJECT)\n {\n if (mpSingleVariable2)\n tmp2.setSingleObjectCN(mpSingleVariable2->getCN());\n }\n else\n tmp2.setListType(Variable2Chooser->getCurrentObjectList());\n\n \/\/ write variables to problem\n problem->removeVariables();\n\n if (tmp.getListType() != CObjectLists::EMPTY_LIST)\n {\n problem->addVariables(tmp);\n\n if (tmp2.getListType() != CObjectLists::EMPTY_LIST)\n problem->addVariables(tmp2);\n }\n\n \/\/ :TODO Bug 322: This should only be called when actual changes have been saved.\n \/\/ However we do not track the changes for the variables we just delete them and add them again.\n if (true)\n {\n if (mpDataModel != NULL)\n {\n mpDataModel->changed();\n }\n\n mChanged = false;\n }\n\n return true;\n}\n\nCCopasiMethod * SensitivitiesWidget::createMethod(const CCopasiMethod::SubType & type)\n{return CSensMethod::createMethod(type);}\n\nbool SensitivitiesWidget::runTask()\n{\n if (FunctionChooser->getCurrentObjectList() != CObjectLists::SINGLE_OBJECT)\n FunctionLineEdit->setText(QApplication::translate(\"SensitivitiesWidget\", \"[Please Choose Object.] --->\", 0, QApplication::UnicodeUTF8));\n\n if (!commonBeforeRunTask()) return false;\n\n bool success = true;\n\n if (!commonRunTask()) success = false;\n\n return success;\n}\n\nbool SensitivitiesWidget::taskFinishedEvent()\n{\n bool success = true;\n \/\/setup the result widget\n CQSensResultWidget *pResult =\n dynamic_cast(mpListView->findWidgetFromId(341));\n\n if (pResult) pResult->newResult();\n\n if (success && isVisible()) mpListView->switchToOtherWidget(341, \"\"); \/\/change to the results window\n\n return success;\n}\n\nbool SensitivitiesWidget::loadTask()\n{\n loadCommon();\n loadMethod();\n\n CSensTask* sensTask =\n dynamic_cast(CCopasiRootContainer::getKeyFactory()->get(mKey));\n assert(sensTask);\n\n CSensProblem* problem =\n dynamic_cast(sensTask->getProblem());\n assert(problem);\n\n \/\/CSensMethod* method =\n \/\/ dynamic_cast(sensTask->getMethod());\n \/\/assert(method);\n\n \/\/mSubTaskType = problem->getSubTaskType();\n SubTaskChooser->setCurrentIndex((int)problem->getSubTaskType());\n updateComboBoxes(problem->getSubTaskType());\n\n CSensItem tmp = problem->getTargetFunctions();\n\n \/\/target function\n assert(CCopasiRootContainer::getDatamodelList()->size() > 0);\n CCopasiDataModel* pDataModel = (*CCopasiRootContainer::getDatamodelList())[0];\n assert(pDataModel != NULL);\n\n if (tmp.isSingleObject())\n {\n FunctionChooser->setCurrentObjectList(CObjectLists::SINGLE_OBJECT);\n mpSingleFunction = pDataModel->getDataObject(tmp.getSingleObjectCN());\n\n if (mpSingleFunction)\n FunctionLineEdit->setText(FROM_UTF8(mpSingleFunction->getObjectDisplayName()));\n }\n else\n {\n mpSingleFunction = NULL;\n FunctionChooser->setCurrentObjectList(tmp.getListType());\n }\n\n \/\/variables 1\n if (problem->getNumberOfVariables() > 0)\n {\n tmp = problem->getVariables(0);\n\n if (tmp.isSingleObject())\n {\n VariableChooser->setCurrentObjectList(CObjectLists::SINGLE_OBJECT);\n mpSingleVariable = pDataModel->getDataObject(tmp.getSingleObjectCN());\n\n if (mpSingleVariable)\n VariableLineEdit->setText(FROM_UTF8(mpSingleVariable->getObjectDisplayName()));\n }\n else\n VariableChooser->setCurrentObjectList(tmp.getListType());\n }\n else\n {\n VariableChooser->setCurrentObjectList(CObjectLists::EMPTY_LIST);\n mpSingleVariable = NULL;\n }\n\n \/\/variables 2\n if (problem->getNumberOfVariables() > 1)\n {\n tmp = problem->getVariables(1);\n\n if (tmp.isSingleObject())\n {\n Variable2Chooser->setCurrentObjectList(CObjectLists::SINGLE_OBJECT);\n mpSingleVariable2 = pDataModel->getDataObject(tmp.getSingleObjectCN());\n\n if (mpSingleVariable2)\n Variable2LineEdit->setText(FROM_UTF8(mpSingleVariable2->getObjectDisplayName()));\n }\n else\n Variable2Chooser->setCurrentObjectList(tmp.getListType());\n }\n else\n {\n Variable2Chooser->setCurrentObjectList(CObjectLists::EMPTY_LIST);\n mpSingleVariable2 = NULL;\n }\n\n \/\/ initCombos(problem);\n\n mChanged = false;\n\n updateAllLineditEnable();\n return true;\n}\n\n\/\/**************************************************************************\n\nvoid SensitivitiesWidget::updateLineeditEnable(const SensWidgetComboBox* box, QWidget* w1, QWidget* w2)\n{\n if (!box) return;\n\n bool enable = false;\n\n if (box->getCurrentObjectList() == CObjectLists::SINGLE_OBJECT)\n enable = true;\n\n if (w1) w1->setVisible(enable);\n\n if (w2) w2->setVisible(enable);\n}\n\nvoid SensitivitiesWidget::updateAllLineditEnable()\n{\n \/*\n updateLineeditEnable(FunctionChooser, FunctionLineEdit, SingleFunctionChooserButton);\n updateLineeditEnable(VariableChooser, VariableLineEdit, SingleVariableChooserButton);\n updateLineeditEnable(Variable2Chooser, Variable2LineEdit, SingleVariable2ChooserButton);\n *\/\n updateLineeditEnable(FunctionChooser, FunctionLineEdit, SingleFunctionChooser);\n updateLineeditEnable(VariableChooser, VariableLineEdit, SingleVariableChooser);\n updateLineeditEnable(Variable2Chooser, Variable2LineEdit, SingleVariable2Chooser);\n}\n\nvoid\nSensitivitiesWidget::initCombos()\n{\n QStringList StringList;\n \/\/std::vector mFunctionIndexTable, mVariableIndexTable;\n\n \/\/ SubTaskChooser combo\n int i = 0;\n\n while (CSensProblem::SubTaskName[i].length() > 0)\n {\n StringList.append(FROM_UTF8(CSensProblem::SubTaskName[i]));\n ++i;\n }\n\n SubTaskChooser->insertItems(SubTaskChooser->count(), StringList);\n SubTaskChooser->setCurrentIndex(0);\n updateComboBoxes((CSensProblem::SubTaskType)0);\n}\n\nvoid SensitivitiesWidget::updateComboBoxes(CSensProblem::SubTaskType type)\n{\n FunctionChooser->fillFromList(CSensProblem::getPossibleTargetFunctions(type));\n VariableChooser->fillFromList(CSensProblem::getPossibleVariables(type));\n Variable2Chooser->fillFromList(CSensProblem::getPossibleVariables(type));\n}\n\n\/\/ ******************* SLOTs *******************************+\n\nvoid\n\/\/SensitivitiesWidget::on_SubTaskChooser_activated(int)\nSensitivitiesWidget::slotChooseSubTask(int)\n{\n CSensProblem::SubTaskType subTaskType = (CSensProblem::SubTaskType)SubTaskChooser->currentIndex();\n updateComboBoxes(subTaskType);\n\n updateAllLineditEnable();\n}\n\nvoid\n\/\/SensitivitiesWidget::on_FunctionChooser_activated(int a)\nSensitivitiesWidget::slotChooseFunction(int)\n{\n updateAllLineditEnable();\n}\n\nvoid\n\/\/SensitivitiesWidget::on_VariableChooser_activated(int)\nSensitivitiesWidget::slotChooseVariable(int)\n{\n updateAllLineditEnable();\n}\n\nvoid\n\/\/SensitivitiesWidget::on_Variable2Chooser_activated(int)\nSensitivitiesWidget::slotChooseVariable2(int)\n{\n updateAllLineditEnable();\n}\n\nvoid\n\/\/SensitivitiesWidget::on_SingleFunctionChooser_clicked()\nSensitivitiesWidget::slotChooseSingleFunction()\n{\n const CCopasiObject * pObject =\n CCopasiSelectionDialog::getObjectSingle(this,\n CQSimpleSelectionTree::Variables |\n CQSimpleSelectionTree::ObservedValues);\n\n if (pObject)\n {\n FunctionLineEdit->setText(FROM_UTF8(pObject->getObjectDisplayName()));\n mpSingleFunction = pObject;\n FunctionChooser->setCurrentObjectList(CObjectLists::SINGLE_OBJECT);\n }\n}\n\nvoid\n\/\/SensitivitiesWidget::on_SingleVariableChooser_clicked()\nSensitivitiesWidget::slotChooseSingleVariable()\n{\n const CCopasiObject * pObject =\n CCopasiSelectionDialog::getObjectSingle(this,\n CQSimpleSelectionTree::InitialTime |\n CQSimpleSelectionTree::Parameters);\n\n if (pObject)\n {\n VariableLineEdit->setText(FROM_UTF8(pObject->getObjectDisplayName()));\n mpSingleVariable = pObject;\n VariableChooser->setCurrentObjectList(CObjectLists::SINGLE_OBJECT);\n }\n}\n\nvoid\n\/\/SensitivitiesWidget::on_SingleVariable2Chooser_clicked()\nSensitivitiesWidget::slotChooseSingleVariable2()\n{\n const CCopasiObject * pObject =\n CCopasiSelectionDialog::getObjectSingle(this,\n CQSimpleSelectionTree::InitialTime |\n CQSimpleSelectionTree::Parameters);\n\n if (pObject)\n {\n Variable2LineEdit->setText(FROM_UTF8(pObject->getObjectDisplayName()));\n mpSingleVariable2 = pObject;\n Variable2Chooser->setCurrentObjectList(CObjectLists::SINGLE_OBJECT);\n }\n}\n<|endoftext|>"} {"text":"\/*\n * qiunwrap.cpp\n *\n * Created by Tobias Wood on 11\/06\/2015.\n * Copyright (c) 2015 Tobias Wood.\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\n *\/\n\n#include \n#include \n#include \n#include \n#include \"Eigen\/Dense\"\n\n#include \"itkImageSource.h\"\n#include \"itkConstNeighborhoodIterator.h\"\n#include \"itkImageRegionIteratorWithIndex.h\"\n#include \"itkMultiplyImageFilter.h\"\n#include \"itkForwardFFTImageFilter.h\"\n#include \"itkInverseFFTImageFilter.h\"\n#include \"itkFFTPadImageFilter.h\"\n#include \"Types.h\"\n#include \"Util.h\"\n\nusing namespace std;\nusing namespace Eigen;\n\nnamespace itk {\n\nclass DiscreteLaplacePhaseFilter : public ImageToImageFilter {\nprotected:\n\npublic:\n\t\/** Standard class typedefs. *\/\n\ttypedef QI::ImageF TImage;\n\n\ttypedef DiscreteLaplacePhaseFilter Self;\n\ttypedef ImageToImageFilter Superclass;\n\ttypedef SmartPointer Pointer;\n\ttypedef typename TImage::RegionType RegionType;\n\n\titkNewMacro(Self);\n\titkTypeMacro(DiscreteLaplacePhaseFilter, DiscreteLaplacePhaseFilter);\n\n void SetInput(const TImage *img) override { this->SetNthInput(0, const_cast(img)); }\n void SetMask(const TImage *img) { this->SetNthInput(1, const_cast(img)); }\n\ttypename TImage::ConstPointer GetInput() const { return static_cast(this->ProcessObject::GetInput(0)); }\n\ttypename TImage::ConstPointer GetMask() const { return static_cast(this->ProcessObject::GetInput(1)); }\n\n\tvirtual void GenerateOutputInformation() override {\n\t\tSuperclass::GenerateOutputInformation();\n\t\tauto op = this->GetOutput();\n\t\top->SetRegions(this->GetInput()->GetLargestPossibleRegion());\n\t\top->Allocate();\n\t}\n\nprotected:\n\tDiscreteLaplacePhaseFilter() {\n\t\tthis->SetNumberOfRequiredInputs(1);\n\t\tthis->SetNumberOfRequiredOutputs(1);\n\t\tthis->SetNthOutput(0, this->MakeOutput(0));\n\t}\n\t~DiscreteLaplacePhaseFilter() {}\n\n\tDataObject::Pointer MakeOutput(unsigned int idx) {\n\t\t\/\/std::cout << __PRETTY_FUNCTION__ << endl;\n\t\tif (idx == 0) {\n\t\t\tDataObject::Pointer output = (TImage::New()).GetPointer();\n\t\t\treturn output.GetPointer();\n\t\t} else {\n\t\t\tstd::cerr << \"No output \" << idx << std::endl;\n\t\t\treturn NULL;\n\t\t}\n\t}\n\n virtual void ThreadedGenerateData(const RegionType ®ion, ThreadIdType threadId) override {\n\t\t\/\/std::cout << __PRETTY_FUNCTION__ << endl;\n\t\tConstNeighborhoodIterator::RadiusType radius;\n\t\tradius.Fill(1);\n\t\tConstNeighborhoodIterator inputIter(radius, this->GetInput(), region);\n\t\tImageRegionIterator outputIter(this->GetOutput(), region);\n\n\t\tImageRegionConstIterator maskIter;\n\t\tconst auto mask = this->GetMask();\n\t\tif (mask) {\n\t\t\tmaskIter = ImageRegionConstIterator(mask, region);\n\t\t}\n\n\t\tvector::OffsetType> back, fwrd;\n\t\tback.push_back({{-1, 0, 0}});\n\t\tfwrd.push_back({{ 1, 0, 0}});\n\t\tback.push_back({{ 0,-1, 0}});\n\t\tfwrd.push_back({{ 0, 1, 0}});\n\t\tback.push_back({{ 0, 0,-1}});\n\t\tfwrd.push_back({{ 0, 0, 1}});\n\n\t\tTImage::SpacingType spacing = this->GetInput()->GetSpacing();\n\t\tTImage::SpacingType s_sqr = spacing * spacing;\n\t\twhile(!inputIter.IsAtEnd()) {\n\t\t\tdouble sum = 0;\n\t\t\tif (!mask || maskIter.Get()) {\n\t\t\t\tdouble cphase = inputIter.GetCenterPixel();\n\t\t\t\tcomplex c = std::polar(1., cphase);\n\t\t\t\tfor (int i = 0; i < fwrd.size(); ++i) {\n\t\t\t\t\tdouble bphase = inputIter.GetPixel(back[i]);\n\t\t\t\t\tdouble fphase = inputIter.GetPixel(fwrd[i]);\n\t\t\t\t\tcomplex b = std::polar(1., bphase);\n\t\t\t\t\tcomplex f = std::polar(1., fphase);\n\t\t\t\t\tsum += std::arg((f*b)\/(c*c)) \/ s_sqr[i];\n\t\t\t\t}\n\t\t\t}\n\t\t\toutputIter.Set(sum \/ 7.);\n\t\t\t++inputIter;\n\t\t\t++outputIter;\n\t\t\tif (mask)\n\t\t\t\t++maskIter;\n\t\t}\n\t}\n\nprivate:\n\tDiscreteLaplacePhaseFilter(const Self &); \/\/purposely not implemented\n\tvoid operator=(const Self &); \/\/purposely not implemented\n};\n\nclass DiscreteInverseLaplace : public ImageSource {\npublic:\n\ttypedef QI::ImageF TImage;\n\ttypedef DiscreteInverseLaplace Self;\n\ttypedef ImageSource Superclass;\n\ttypedef SmartPointer Pointer;\n\n\titkNewMacro(Self);\n\titkTypeMacro(DiscreteInverseLaplace, ImageSource);\n\n void SetImageProperties(const TImage *img) {\n m_region = img->GetLargestPossibleRegion();\n\t\tm_spacing = img->GetSpacing();\n\t\tm_direction = img->GetDirection();\n\t\tm_origin = img->GetOrigin();\n\t}\n\nprotected:\n typename TImage::RegionType m_region;\n\ttypename TImage::SpacingType m_spacing;\n\ttypename TImage::DirectionType m_direction;\n\ttypename TImage::PointType m_origin;\n\n\tDiscreteInverseLaplace(){}\n\t~DiscreteInverseLaplace(){}\n virtual void GenerateData() override {\n\t\ttypename TImage::Pointer output = this->GetOutput();\n output->SetRegions(m_region);\n\t\toutput->Allocate();\n\t\toutput->SetSpacing(m_spacing);\n\t\toutput->SetDirection(m_direction);\n\t\toutput->SetOrigin(m_origin);\n\t\titk::ImageRegionIteratorWithIndex imageIt(output,output->GetLargestPossibleRegion());\n\t\timageIt.GoToBegin();\n\t\timageIt.Set(0.); \/\/ There is a pole here\n\t\t++imageIt;\n\t\twhile(!imageIt.IsAtEnd()) {\n\t\t\tauto index = imageIt.GetIndex();\n\t\t\tdouble val = 0;\n\t\t\tfor (int i = 0; i < 3; i++) {\n val += 2. - 2. * cos(index[i] * 2. * M_PI \/ m_region.GetSize()[i]);\n\t\t\t}\n\t\t\tval \/= 7.;\n\t\t\timageIt.Set(1.\/val);\n\t\t\t++imageIt;\n\t\t}\n\t}\n\nprivate:\n\tDiscreteInverseLaplace(const Self &);\n\tvoid operator=(const Self &);\n};\n\n} \/\/ End namespace itk\n\n\/\/******************************************************************************\n\/\/ Arguments \/ Usage\n\/\/******************************************************************************\nconst string usage {\n\"Usage is: qiunwrap [options] input \\n\\\n\\n\\\nInput is a single wrapped phase volume\\n\\\n\\n\\\nOptions:\\n\\\n\t--help, -h : Print this message.\\n\\\n\t--verbose, -v : Print more information.\\n\\\n\t--out, -o path : Specify an output filename (default image base).\\n\\\n\t--mask, -m file : Mask input with specified file.\\n\\\n\t--threads, -T N : Use N threads (default=hardware limit).\\n\\\n\t--lop, -l C : Use Continuous Laplacian operators.\\n\\\n\t D Use Discrete Laplacian operators (default).\\n\"\n};\n\nconst struct option long_options[] = {\n\t{\"help\", no_argument, 0, 'h'},\n\t{\"verbose\", no_argument, 0, 'v'},\n\t{\"out\", required_argument, 0, 'o'},\n\t{\"mask\", required_argument, 0, 'm'},\n\t{\"threads\", required_argument, 0, 'T'},\n\t{\"lop\", required_argument, 0, 'l'},\n\t{0, 0, 0, 0}\n};\nconst char *short_options = \"hvo:m:T:l:\";\n\n\/\/******************************************************************************\n\/\/ Main\n\/\/******************************************************************************\nint main(int argc, char **argv) {\n\tEigen::initParallel();\n\n\tbool verbose = false;\n\tstring prefix;\n\titk::ImageFileReader>::Pointer mask = ITK_NULLPTR;\n\tint indexptr = 0, c;\n\twhile ((c = getopt_long(argc, argv, short_options, long_options, &indexptr)) != -1) {\n\t\tswitch (c) {\n\t\t\tcase 'v': verbose = true; break;\n\t\t\tcase 'm':\n\t\t\t\tif (verbose) cout << \"Reading mask file \" << optarg << endl;\n\t\t\t\tmask = itk::ImageFileReader>::New();\n\t\t\t\tmask->SetFileName(optarg);\n\t\t\t\tbreak;\n\t\t\tcase 'o':\n\t\t\t\tprefix = optarg;\n\t\t\t\tcout << \"Output prefix will be: \" << prefix << endl;\n\t\t\t\tbreak;\n\t\t\tcase 'l':\n\t\t\t\tbreak;\n\t\t\tcase 'T': itk::MultiThreader::SetGlobalMaximumNumberOfThreads(atoi(optarg)); break;\n\t\t\tcase 'h':\n\t\t\t\tcout << usage << endl;\n\t\t\t\treturn EXIT_SUCCESS;\n\t\t\tcase '?': \/\/ getopt will print an error message\n\t\t\t\treturn EXIT_FAILURE;\n\t\t\tdefault:\n\t\t\t\tcout << \"Unhandled option \" << string(1, c) << endl;\n\t\t\t\treturn EXIT_FAILURE;\n\t\t}\n\t}\n\tif ((argc - optind) != 1) {\n\t\tcout << \"Incorrect number of arguments.\" << endl << usage << endl;\n\t\treturn EXIT_FAILURE;\n\t}\n\tif (verbose) cout << \"Opening input file: \" << argv[optind] << endl;\n\tstring fname(argv[optind++]);\n\tif (prefix == \"\")\n\t\tprefix = fname.substr(0, fname.find(\".nii\"));\n\tstring outname = prefix + \"_unwrap\" + QI::OutExt();\n\tif (verbose) cout << \"Output filename: \" << outname << endl;\n\n\tauto inFile = QI::ReadImageF::New();\n\tauto calcLaplace = itk::DiscreteLaplacePhaseFilter::New();\n\tinFile->SetFileName(fname);\n\tinFile->Update(); \/\/ Need the size info\n\tcalcLaplace->SetInput(inFile->GetOutput());\n\tif (mask)\n\t\tcalcLaplace->SetMask(mask->GetOutput());\n if (verbose) cout << \"Padding image to valid FFT size.\" << endl;\n typedef itk::FFTPadImageFilter PadFFTType;\n auto padFFT = PadFFTType::New();\n padFFT->SetInput(calcLaplace->GetOutput());\n padFFT->Update();\n\tif (verbose) cout << \"Calculating Forward FFT.\" << endl;\n\ttypedef itk::ForwardFFTImageFilter FFFTType;\n\tauto forwardFFT = FFFTType::New();\n forwardFFT->SetInput(padFFT->GetOutput());\n forwardFFT->Update();\n\tif (verbose) cout << \"Generating Inverse Laplace Kernel.\" << endl;\n\tauto inverseLaplace = itk::DiscreteInverseLaplace::New();\n inverseLaplace->SetImageProperties(padFFT->GetOutput());\n inverseLaplace->Update();\n\tif (verbose) cout << \"Multiplying.\" << endl;\n\tauto mult = itk::MultiplyImageFilter::New();\n\tmult->SetInput1(forwardFFT->GetOutput());\n\tmult->SetInput2(inverseLaplace->GetOutput());\n\n\tif (verbose) cout << \"Inverse FFT.\" << endl;\n auto inverseFFT = itk::InverseFFTImageFilter::New();\n\tinverseFFT->SetInput(mult->GetOutput());\n\n auto outFile = QI::WriteImageF::New();\n outFile->SetInput(inverseFFT->GetOutput());\n\toutFile->SetFileName(outname);\n\tif (verbose) cout << \"Writing output.\" << endl;\n\toutFile->Update();\n\tif (verbose) cout << \"Finished.\" << endl;\n\treturn EXIT_SUCCESS;\n}\nAdded a step to extract the original size image (to remove FFT padding)\/*\n * qiunwrap.cpp\n *\n * Created by Tobias Wood on 11\/06\/2015.\n * Copyright (c) 2015 Tobias Wood.\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\n *\/\n\n#include \n#include \n#include \n#include \n#include \"Eigen\/Dense\"\n\n#include \"itkImageSource.h\"\n#include \"itkConstNeighborhoodIterator.h\"\n#include \"itkImageRegionIteratorWithIndex.h\"\n#include \"itkMultiplyImageFilter.h\"\n#include \"itkForwardFFTImageFilter.h\"\n#include \"itkInverseFFTImageFilter.h\"\n#include \"itkFFTPadImageFilter.h\"\n#include \"Types.h\"\n#include \"Util.h\"\n\nusing namespace std;\nusing namespace Eigen;\n\nnamespace itk {\n\nclass DiscreteLaplacePhaseFilter : public ImageToImageFilter {\nprotected:\n\npublic:\n\t\/** Standard class typedefs. *\/\n\ttypedef QI::ImageF TImage;\n\n\ttypedef DiscreteLaplacePhaseFilter Self;\n\ttypedef ImageToImageFilter Superclass;\n\ttypedef SmartPointer Pointer;\n\ttypedef typename TImage::RegionType RegionType;\n\n\titkNewMacro(Self);\n\titkTypeMacro(DiscreteLaplacePhaseFilter, DiscreteLaplacePhaseFilter);\n\n void SetInput(const TImage *img) override { this->SetNthInput(0, const_cast(img)); }\n void SetMask(const TImage *img) { this->SetNthInput(1, const_cast(img)); }\n\ttypename TImage::ConstPointer GetInput() const { return static_cast(this->ProcessObject::GetInput(0)); }\n\ttypename TImage::ConstPointer GetMask() const { return static_cast(this->ProcessObject::GetInput(1)); }\n\n\tvirtual void GenerateOutputInformation() override {\n\t\tSuperclass::GenerateOutputInformation();\n\t\tauto op = this->GetOutput();\n\t\top->SetRegions(this->GetInput()->GetLargestPossibleRegion());\n\t\top->Allocate();\n\t}\n\nprotected:\n\tDiscreteLaplacePhaseFilter() {\n\t\tthis->SetNumberOfRequiredInputs(1);\n\t\tthis->SetNumberOfRequiredOutputs(1);\n\t\tthis->SetNthOutput(0, this->MakeOutput(0));\n\t}\n\t~DiscreteLaplacePhaseFilter() {}\n\n\tDataObject::Pointer MakeOutput(unsigned int idx) {\n\t\t\/\/std::cout << __PRETTY_FUNCTION__ << endl;\n\t\tif (idx == 0) {\n\t\t\tDataObject::Pointer output = (TImage::New()).GetPointer();\n\t\t\treturn output.GetPointer();\n\t\t} else {\n\t\t\tstd::cerr << \"No output \" << idx << std::endl;\n\t\t\treturn NULL;\n\t\t}\n\t}\n\n virtual void ThreadedGenerateData(const RegionType ®ion, ThreadIdType threadId) override {\n\t\t\/\/std::cout << __PRETTY_FUNCTION__ << endl;\n\t\tConstNeighborhoodIterator::RadiusType radius;\n\t\tradius.Fill(1);\n\t\tConstNeighborhoodIterator inputIter(radius, this->GetInput(), region);\n\t\tImageRegionIterator outputIter(this->GetOutput(), region);\n\n\t\tImageRegionConstIterator maskIter;\n\t\tconst auto mask = this->GetMask();\n\t\tif (mask) {\n\t\t\tmaskIter = ImageRegionConstIterator(mask, region);\n\t\t}\n\n\t\tvector::OffsetType> back, fwrd;\n\t\tback.push_back({{-1, 0, 0}});\n\t\tfwrd.push_back({{ 1, 0, 0}});\n\t\tback.push_back({{ 0,-1, 0}});\n\t\tfwrd.push_back({{ 0, 1, 0}});\n\t\tback.push_back({{ 0, 0,-1}});\n\t\tfwrd.push_back({{ 0, 0, 1}});\n\n\t\tTImage::SpacingType spacing = this->GetInput()->GetSpacing();\n\t\tTImage::SpacingType s_sqr = spacing * spacing;\n\t\twhile(!inputIter.IsAtEnd()) {\n\t\t\tdouble sum = 0;\n\t\t\tif (!mask || maskIter.Get()) {\n\t\t\t\tdouble cphase = inputIter.GetCenterPixel();\n\t\t\t\tcomplex c = std::polar(1., cphase);\n\t\t\t\tfor (int i = 0; i < fwrd.size(); ++i) {\n\t\t\t\t\tdouble bphase = inputIter.GetPixel(back[i]);\n\t\t\t\t\tdouble fphase = inputIter.GetPixel(fwrd[i]);\n\t\t\t\t\tcomplex b = std::polar(1., bphase);\n\t\t\t\t\tcomplex f = std::polar(1., fphase);\n\t\t\t\t\tsum += std::arg((f*b)\/(c*c)) \/ s_sqr[i];\n\t\t\t\t}\n\t\t\t}\n\t\t\toutputIter.Set(sum \/ 7.);\n\t\t\t++inputIter;\n\t\t\t++outputIter;\n\t\t\tif (mask)\n\t\t\t\t++maskIter;\n\t\t}\n\t}\n\nprivate:\n\tDiscreteLaplacePhaseFilter(const Self &); \/\/purposely not implemented\n\tvoid operator=(const Self &); \/\/purposely not implemented\n};\n\nclass DiscreteInverseLaplace : public ImageSource {\npublic:\n\ttypedef QI::ImageF TImage;\n\ttypedef DiscreteInverseLaplace Self;\n\ttypedef ImageSource Superclass;\n\ttypedef SmartPointer Pointer;\n\n\titkNewMacro(Self);\n\titkTypeMacro(DiscreteInverseLaplace, ImageSource);\n\n void SetImageProperties(const TImage *img) {\n m_region = img->GetLargestPossibleRegion();\n\t\tm_spacing = img->GetSpacing();\n\t\tm_direction = img->GetDirection();\n\t\tm_origin = img->GetOrigin();\n\t}\n\nprotected:\n typename TImage::RegionType m_region;\n\ttypename TImage::SpacingType m_spacing;\n\ttypename TImage::DirectionType m_direction;\n\ttypename TImage::PointType m_origin;\n\n\tDiscreteInverseLaplace(){}\n\t~DiscreteInverseLaplace(){}\n virtual void GenerateData() override {\n\t\ttypename TImage::Pointer output = this->GetOutput();\n output->SetRegions(m_region);\n\t\toutput->Allocate();\n\t\toutput->SetSpacing(m_spacing);\n\t\toutput->SetDirection(m_direction);\n\t\toutput->SetOrigin(m_origin);\n\t\titk::ImageRegionIteratorWithIndex imageIt(output,output->GetLargestPossibleRegion());\n\t\timageIt.GoToBegin();\n\t\timageIt.Set(0.); \/\/ There is a pole here\n\t\t++imageIt;\n\t\twhile(!imageIt.IsAtEnd()) {\n\t\t\tauto index = imageIt.GetIndex();\n\t\t\tdouble val = 0;\n\t\t\tfor (int i = 0; i < 3; i++) {\n val += 2. - 2. * cos(index[i] * 2. * M_PI \/ m_region.GetSize()[i]);\n\t\t\t}\n\t\t\tval \/= 7.;\n\t\t\timageIt.Set(1.\/val);\n\t\t\t++imageIt;\n\t\t}\n\t}\n\nprivate:\n\tDiscreteInverseLaplace(const Self &);\n\tvoid operator=(const Self &);\n};\n\n} \/\/ End namespace itk\n\n\/\/******************************************************************************\n\/\/ Arguments \/ Usage\n\/\/******************************************************************************\nconst string usage {\n\"Usage is: qiunwrap [options] input \\n\\\n\\n\\\nInput is a single wrapped phase volume\\n\\\n\\n\\\nOptions:\\n\\\n\t--help, -h : Print this message.\\n\\\n\t--verbose, -v : Print more information.\\n\\\n\t--out, -o path : Specify an output filename (default image base).\\n\\\n\t--mask, -m file : Mask input with specified file.\\n\\\n\t--threads, -T N : Use N threads (default=hardware limit).\\n\\\n\t--lop, -l C : Use Continuous Laplacian operators.\\n\\\n\t D Use Discrete Laplacian operators (default).\\n\"\n};\n\nconst struct option long_options[] = {\n\t{\"help\", no_argument, 0, 'h'},\n\t{\"verbose\", no_argument, 0, 'v'},\n\t{\"out\", required_argument, 0, 'o'},\n\t{\"mask\", required_argument, 0, 'm'},\n\t{\"threads\", required_argument, 0, 'T'},\n\t{\"lop\", required_argument, 0, 'l'},\n\t{0, 0, 0, 0}\n};\nconst char *short_options = \"hvo:m:T:l:\";\n\n\/\/******************************************************************************\n\/\/ Main\n\/\/******************************************************************************\nint main(int argc, char **argv) {\n\tEigen::initParallel();\n\n\tbool verbose = false;\n\tstring prefix;\n\titk::ImageFileReader>::Pointer mask = ITK_NULLPTR;\n\tint indexptr = 0, c;\n\twhile ((c = getopt_long(argc, argv, short_options, long_options, &indexptr)) != -1) {\n\t\tswitch (c) {\n\t\t\tcase 'v': verbose = true; break;\n\t\t\tcase 'm':\n\t\t\t\tif (verbose) cout << \"Reading mask file \" << optarg << endl;\n\t\t\t\tmask = itk::ImageFileReader>::New();\n\t\t\t\tmask->SetFileName(optarg);\n\t\t\t\tbreak;\n\t\t\tcase 'o':\n\t\t\t\tprefix = optarg;\n\t\t\t\tcout << \"Output prefix will be: \" << prefix << endl;\n\t\t\t\tbreak;\n\t\t\tcase 'l':\n\t\t\t\tbreak;\n\t\t\tcase 'T': itk::MultiThreader::SetGlobalMaximumNumberOfThreads(atoi(optarg)); break;\n\t\t\tcase 'h':\n\t\t\t\tcout << usage << endl;\n\t\t\t\treturn EXIT_SUCCESS;\n\t\t\tcase '?': \/\/ getopt will print an error message\n\t\t\t\treturn EXIT_FAILURE;\n\t\t\tdefault:\n\t\t\t\tcout << \"Unhandled option \" << string(1, c) << endl;\n\t\t\t\treturn EXIT_FAILURE;\n\t\t}\n\t}\n\tif ((argc - optind) != 1) {\n\t\tcout << \"Incorrect number of arguments.\" << endl << usage << endl;\n\t\treturn EXIT_FAILURE;\n\t}\n\tif (verbose) cout << \"Opening input file: \" << argv[optind] << endl;\n\tstring fname(argv[optind++]);\n\tif (prefix == \"\")\n\t\tprefix = fname.substr(0, fname.find(\".nii\"));\n\tstring outname = prefix + \"_unwrap\" + QI::OutExt();\n\tif (verbose) cout << \"Output filename: \" << outname << endl;\n\n\tauto inFile = QI::ReadImageF::New();\n\tauto calcLaplace = itk::DiscreteLaplacePhaseFilter::New();\n\tinFile->SetFileName(fname);\n\tinFile->Update(); \/\/ Need the size info\n\tcalcLaplace->SetInput(inFile->GetOutput());\n\tif (mask)\n calcLaplace->SetMask(mask->GetOutput());\n\n if (verbose) cout << \"Padding image to valid FFT size.\" << endl;\n typedef itk::FFTPadImageFilter PadFFTType;\n auto padFFT = PadFFTType::New();\n padFFT->SetInput(calcLaplace->GetOutput());\n padFFT->Update();\n\n\tif (verbose) cout << \"Calculating Forward FFT.\" << endl;\n\ttypedef itk::ForwardFFTImageFilter FFFTType;\n\tauto forwardFFT = FFFTType::New();\n forwardFFT->SetInput(padFFT->GetOutput());\n forwardFFT->Update();\n\n\tif (verbose) cout << \"Generating Inverse Laplace Kernel.\" << endl;\n\tauto inverseLaplace = itk::DiscreteInverseLaplace::New();\n inverseLaplace->SetImageProperties(padFFT->GetOutput());\n inverseLaplace->Update();\n\n if (verbose) cout << \"Multiplying.\" << endl;\n\tauto mult = itk::MultiplyImageFilter::New();\n\tmult->SetInput1(forwardFFT->GetOutput());\n\tmult->SetInput2(inverseLaplace->GetOutput());\n\n\tif (verbose) cout << \"Inverse FFT.\" << endl;\n auto inverseFFT = itk::InverseFFTImageFilter::New();\n\tinverseFFT->SetInput(mult->GetOutput());\n\n if (verbose) cout << \"Extracting original size image\" << endl;\n auto extract = itk::ExtractImageFilter::New();\n extract->SetInput(inverseFFT->GetOutput());\n extract->SetDirectionCollapseToSubmatrix();\n extract->SetExtractionRegion(calcLaplace->GetOutput()->GetLargestPossibleRegion());\n extract->Update();\n\n auto outFile = QI::WriteImageF::New();\n outFile->SetInput(extract->GetOutput());\n\toutFile->SetFileName(outname);\n if (verbose) cout << \"Writing output.\" << endl;\n\toutFile->Update();\n\tif (verbose) cout << \"Finished.\" << endl;\n\treturn EXIT_SUCCESS;\n}\n<|endoftext|>"} {"text":"\/\/\n\/\/ SpcFileGenerate.cpp\n\/\/ C700\n\/\/\n\/\/ Created by osoumen on 2017\/01\/30.\n\/\/\n\/\/\n\n#include \"SpcFileGenerate.h\"\n\nSpcFileGenerate::SpcFileGenerate(int allocSize)\n: PlayingFileGenerateBase(allocSize)\n{\n \/\/SetSpcPlayCode( spcplayercode, sizeof(spcplayercode) );\n strncpy(mSongTitle, \"Song title\", 32);\n strncpy(mGameTitle, \"Game title\", 32);\n strncpy(mNameOfDumper, \"dumper\", 16);\n strncpy(mArtistOfSong, \"Artist of song\", 32);\n strncpy(mSongComments, \"Comments\", 32);\n mPlaySec = 120;\n mFadeMs = 5000;\n\n}\n\nSpcFileGenerate::~SpcFileGenerate()\n{\n \n}\n\nvoid SpcFileGenerate::SetSpcPlayCode( const void *code, int size, const void *smccode, int smcsize )\n{\n m_pSpcPlayCode = (unsigned char*)code;\n mSpcPlayCodeSize = size;\n\tmSpcPlayCodeSize2 = findDspregAccCode( smccode, smcsize, &m_pSpcPlayCode2 );\n}\n\nbool SpcFileGenerate::WriteToFile( const char *path, const RegisterLogger ®log, double tickPerSec )\n{\n DataBuffer spcFile(0x10200);\n \n \/\/ レジスタログの生成\n unsigned char *reglogData = new unsigned char [4 * 1024 * 1024];\n int loopPoint;\n int reglogSize = convertLogData( reglog, tickPerSec, reglogData, 4 * 1024 * 1024, &loopPoint, true );\n \n\tconst int echoSize = reglog.getDspRegionData()[0x7d] << 11;\n\tint logAddr = 0x600 + echoSize;\n\tint brrAddr = reglog.getBrrRegionLocateAddr();\n\tbool outputScript700 = false;\n\tif (reglogSize > (brrAddr - logAddr))\n\t{\n\t\t\/\/ 64kに収まらない場合、700ファイルの形式で書き出す\n\t\tchar script700path[PATH_LEN_MAX];\n\t\tget700FileName(path, script700path, PATH_LEN_MAX);\n\t\texportScript700(script700path, reglog);\n\t\toutputScript700 = true;\n\t}\n\t\n \/\/ SPCヘッダの書き出し\n spcFile.writeData(\"SNES-SPC700 Sound File Data v0.30\", 33);\n spcFile.writeByte(26, 3);\n spcFile.writeByte(30); \/\/ Version minor\n\tif (outputScript700) {\n\t\tspcFile.writeU16(0x31); \/\/ PC\n\t}\n\telse {\n\t\tspcFile.writeU16(0x100); \/\/ PC\n\t}\n spcFile.writeByte(0); \/\/ A\n spcFile.writeByte(0); \/\/ X\n spcFile.writeByte(0); \/\/ Y\n spcFile.writeByte(0x02); \/\/ PSW\n spcFile.writeByte(0xff); \/\/ SP\n spcFile.writeByte(0, 2); \/\/ reserved\n \n spcFile.writeData(mSongTitle, 32); \/\/ Song title\n spcFile.writeData(mGameTitle, 32); \/\/ Game title\n spcFile.writeData(mNameOfDumper, 16); \/\/ Name of dumper\n spcFile.writeData(mSongComments, 32); \/\/ Comments\n {\n time_t timer;\n struct tm *local;\n timer = time(NULL);\n local = localtime(&timer);\n char dateStr[16];\n sprintf(dateStr, \"%02d\/%02d\/%04d\", local->tm_mon + 1, local->tm_mday, local->tm_year + 1900);\n spcFile.writeData(dateStr, 11); \/\/ Date SPC was dumped (MM\/DD\/YYYY)\n }\n {\n char str[4] = {0,0,0,0};\n sprintf(str, \"%d\", mPlaySec);\n spcFile.writeData(str, 3); \/\/ Number of seconds to play song before fading out\n }\n {\n char str[6] = {0,0,0,0,0,0};\n sprintf(str, \"%d\", mFadeMs);\n spcFile.writeData(str, 5); \/\/ Length of fade in milliseconds\n }\n spcFile.writeData(mArtistOfSong, 32); \/\/ Artist of song\n spcFile.writeByte(0); \/\/ Default channel disables (0 = enable, 1 = disable)\n spcFile.writeByte(0); \/\/ Emulator used to dump SPC: 0 = unknown, 1 = ZSNES, 2 = Snes9x\n spcFile.writeByte(0, 45); \/\/ reserved (set to all 0's)\n \n \/\/ WaitTableの書き出し\n\tif (!outputScript700) {\n\t\tspcFile.setPos(0x130);\n\t\twriteWaitTable(spcFile, reglog);\n\t}\n \n \/\/ 実行コードの書き出し\n\tif (outputScript700) {\n\t\tspcFile.setPos(0x110);\n\t\tspcFile.writeData(m_pSpcPlayCode2, mSpcPlayCodeSize2);\n\t}\n\telse {\n\t\tspcFile.setPos(0x170);\n\t\tspcFile.writeData(m_pSpcPlayCode, mSpcPlayCodeSize);\n\t}\n \n \/\/ DIR領域の書き出し\n spcFile.setPos(0x300);\n spcFile.writeData(reglog.getDirRegionData(), reglog.getDirRegionSize());\n \n \/\/ レジスタログの書き出し\n\tif (!outputScript700) {\n\t\t\/\/ エコー領域の後に演奏データを入れる\n\t\tspcFile.setPos(0x700 + echoSize); \/\/ DSP_EDL\n\t\tspcFile.writeData(reglogData, reglogSize);\n\t}\n \n \/\/ BRR領域の書き出し\n spcFile.setPos(0x100 + brrAddr);\n spcFile.writeData(reglog.getBrrRegionData(), reglog.getBrrRegionSize());\n \n \/\/ 初期変数の設定\n\tif (!outputScript700) {\n\t\tspcFile.setPos(0x102); \/\/ 変数領域へ移動\n\t\tspcFile.writeU16(logAddr & 0xffff); \/\/ 演奏データ開始アドレス\n\t\tspcFile.writeU16(loopPoint & 0xffff); \/\/ ループポイント\n\t\tspcFile.writeByte(0xff); \/\/ _INITIAL_WAIT_FRAMES\n\t}\n \n \/\/ DSP領域の書き出し\n spcFile.setPos(0x10100);\n writeDspRegion(spcFile, reglog);\n\t\n\t\/\/ KON,KOFフラグをクリアする\n\tspcFile.setPos(0x1014c);\n\tspcFile.writeByte(0x00);\n\tspcFile.setPos(0x1015c);\n\tspcFile.writeByte(0x00);\n\n spcFile.WriteToFile(path);\n \n delete [] reglogData;\n \n return true;\n}\n\nvoid SpcFileGenerate::SetGameTitle(const char *title)\n{\n setHeaderString(mGameTitle, title, 32);\n}\n\nvoid SpcFileGenerate::SetSongTitle(const char *title)\n{\n setHeaderString(mSongTitle, title, 32);\n}\n\nvoid SpcFileGenerate::SetNameOfDumper(const char *dumper)\n{\n setHeaderString(mNameOfDumper, dumper, 16);\n}\n\nvoid SpcFileGenerate::SetArtistOfSong(const char *artist)\n{\n setHeaderString(mArtistOfSong, artist, 32);\n}\n\nvoid SpcFileGenerate::SetSongComments(const char *comments)\n{\n setHeaderString(mSongComments, comments, 32);\n}\n\nvoid SpcFileGenerate::setHeaderString(char *dst, const char *src, int len)\n{\n if (src[0] == 0) {\n return;\n }\n memset(dst, 0x20, len);\n for (int i=0; (i 999) {\n mPlaySec = 999;\n }\n if (mPlaySec < 0) {\n mPlaySec = 0;\n }\n}\n\nvoid SpcFileGenerate::SetFadeMs(int ms)\n{\n mFadeMs = ms;\n if (mFadeMs > 99999) {\n mFadeMs = 99999;\n }\n if (mFadeMs < 0) {\n mFadeMs = 0;\n }\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid SpcFileGenerate::get700FileName( const char *path, char *out, int maxLen )\n{\n#if MAC\n\tCFURLRef\turl = CFURLCreateFromFileSystemRepresentation(NULL, (UInt8*)path, strlen(path), false);\n\tCFURLRef\textlesspath=CFURLCreateCopyDeletingPathExtension(NULL, url);\n\tCFStringRef\tfilename = CFURLCopyFileSystemPath(extlesspath,kCFURLPOSIXPathStyle);\n\tCFStringGetCString(filename, out, maxLen-1, kCFStringEncodingUTF8);\n\tstrcat(out, \".700\");\n\tCFRelease(filename);\n\tCFRelease(extlesspath);\n\tCFRelease(url);\n#else\n\tint\tlen = static_cast(strlen(path));\n\tint extPos = len;\n\tfor ( int i=len-1; i>=0; i-- ) {\n\t\tif ( path[i] == '.' ) {\n\t\t\textPos = i;\n\t\t\tbreak;\n\t\t}\n\t}\n\tstrncpy(out, path, extPos);\n\tout[extPos] = 0;\n\tstrcat(out, \".700\");\n#endif\n}\n\n\/\/-----------------------------------------------------------------------------\nint SpcFileGenerate::findDspregAccCode( const void *code, int size, const unsigned char **outCode )\n{\n\tconst unsigned char *p_code = (unsigned char*)code;\n\tfor (int i=0; i<(size-3); ++i) {\n\t\tif (p_code[i] == 0x8f && p_code[i+1] == 0x00 && p_code[i+2] == 0xf1) {\n\t\t\t*outCode = &p_code[i];\n\t\t\treturn size - i;\n\t\t}\n\t}\n\treturn 0;\n}\nSpcPlayCodeSizeに応じてspcファイルのDIR,ESAの位置を移動させる処理\/\/\n\/\/ SpcFileGenerate.cpp\n\/\/ C700\n\/\/\n\/\/ Created by osoumen on 2017\/01\/30.\n\/\/\n\/\/\n\n#include \"SpcFileGenerate.h\"\n\nSpcFileGenerate::SpcFileGenerate(int allocSize)\n: PlayingFileGenerateBase(allocSize)\n{\n \/\/SetSpcPlayCode( spcplayercode, sizeof(spcplayercode) );\n strncpy(mSongTitle, \"Song title\", 32);\n strncpy(mGameTitle, \"Game title\", 32);\n strncpy(mNameOfDumper, \"dumper\", 16);\n strncpy(mArtistOfSong, \"Artist of song\", 32);\n strncpy(mSongComments, \"Comments\", 32);\n mPlaySec = 120;\n mFadeMs = 5000;\n\n}\n\nSpcFileGenerate::~SpcFileGenerate()\n{\n \n}\n\nvoid SpcFileGenerate::SetSpcPlayCode( const void *code, int size, const void *smccode, int smcsize )\n{\n m_pSpcPlayCode = (unsigned char*)code;\n mSpcPlayCodeSize = size;\n\tmSpcPlayCodeSize2 = findDspregAccCode( smccode, smcsize, &m_pSpcPlayCode2 );\n}\n\nbool SpcFileGenerate::WriteToFile( const char *path, const RegisterLogger ®log, double tickPerSec )\n{\n DataBuffer spcFile(0x10200);\n \n \/\/ レジスタログの生成\n unsigned char *reglogData = new unsigned char [4 * 1024 * 1024];\n int loopPoint;\n int reglogSize = convertLogData( reglog, tickPerSec, reglogData, 4 * 1024 * 1024, &loopPoint, true );\n \n\tconst int echoSize = reglog.getDspRegionData()[0x7d] << 11;\n\tint brrAddr = reglog.getBrrRegionLocateAddr();\n\tbool outputScript700 = false;\n\tint dirPos = (0x200 + mSpcPlayCodeSize + 0xff) & 0xff00;\n\tint esaPos = dirPos + 0x400;\n\tint logAddr = esaPos + echoSize;\n\n\tif (reglogSize > (brrAddr - logAddr))\n\t{\n\t\t\/\/ 64kに収まらない場合、700ファイルの形式で書き出す\n\t\tchar script700path[PATH_LEN_MAX];\n\t\tget700FileName(path, script700path, PATH_LEN_MAX);\n\t\texportScript700(script700path, reglog);\n\t\toutputScript700 = true;\n\t\tdirPos = 0x200;\n\t\tesaPos = dirPos + 0x400;\n\t}\n\t\n \/\/ SPCヘッダの書き出し\n spcFile.writeData(\"SNES-SPC700 Sound File Data v0.30\", 33);\n spcFile.writeByte(26, 3);\n spcFile.writeByte(30); \/\/ Version minor\n\tif (outputScript700) {\n\t\tspcFile.writeU16(0x31); \/\/ PC\n\t}\n\telse {\n\t\tspcFile.writeU16(0x100); \/\/ PC\n\t}\n spcFile.writeByte(0); \/\/ A\n spcFile.writeByte(0); \/\/ X\n spcFile.writeByte(0); \/\/ Y\n spcFile.writeByte(0x02); \/\/ PSW\n spcFile.writeByte(0xff); \/\/ SP\n spcFile.writeByte(0, 2); \/\/ reserved\n \n spcFile.writeData(mSongTitle, 32); \/\/ Song title\n spcFile.writeData(mGameTitle, 32); \/\/ Game title\n spcFile.writeData(mNameOfDumper, 16); \/\/ Name of dumper\n spcFile.writeData(mSongComments, 32); \/\/ Comments\n {\n time_t timer;\n struct tm *local;\n timer = time(NULL);\n local = localtime(&timer);\n char dateStr[16];\n sprintf(dateStr, \"%02d\/%02d\/%04d\", local->tm_mon + 1, local->tm_mday, local->tm_year + 1900);\n spcFile.writeData(dateStr, 11); \/\/ Date SPC was dumped (MM\/DD\/YYYY)\n }\n {\n char str[4] = {0,0,0,0};\n sprintf(str, \"%d\", mPlaySec);\n spcFile.writeData(str, 3); \/\/ Number of seconds to play song before fading out\n }\n {\n char str[6] = {0,0,0,0,0,0};\n sprintf(str, \"%d\", mFadeMs);\n spcFile.writeData(str, 5); \/\/ Length of fade in milliseconds\n }\n spcFile.writeData(mArtistOfSong, 32); \/\/ Artist of song\n spcFile.writeByte(0); \/\/ Default channel disables (0 = enable, 1 = disable)\n spcFile.writeByte(0); \/\/ Emulator used to dump SPC: 0 = unknown, 1 = ZSNES, 2 = Snes9x\n spcFile.writeByte(0, 45); \/\/ reserved (set to all 0's)\n \n \/\/ WaitTableの書き出し\n\tif (!outputScript700) {\n\t\tspcFile.setPos(0x130);\n\t\twriteWaitTable(spcFile, reglog);\n\t}\n \n \/\/ 実行コードの書き出し\n\tif (outputScript700) {\n\t\tspcFile.setPos(0x110);\n\t\tspcFile.writeData(m_pSpcPlayCode2, mSpcPlayCodeSize2);\n\t}\n\telse {\n\t\tspcFile.setPos(0x170);\n\t\tspcFile.writeData(m_pSpcPlayCode, mSpcPlayCodeSize);\n\t}\n \n \/\/ DIR領域の書き出し\n spcFile.setPos(0x100 + dirPos);\n spcFile.writeData(reglog.getDirRegionData(), reglog.getDirRegionSize());\n \n \/\/ レジスタログの書き出し\n\tif (!outputScript700) {\n\t\t\/\/ エコー領域の後に演奏データを入れる\n\t\tspcFile.setPos(0x100 + esaPos + echoSize); \/\/ DSP_EDL\n\t\tspcFile.writeData(reglogData, reglogSize);\n\t}\n \n \/\/ BRR領域の書き出し\n spcFile.setPos(0x100 + brrAddr);\n spcFile.writeData(reglog.getBrrRegionData(), reglog.getBrrRegionSize());\n \n \/\/ 初期変数の設定\n\tif (!outputScript700) {\n\t\tspcFile.setPos(0x102); \/\/ 変数領域へ移動\n\t\tspcFile.writeU16(logAddr & 0xffff); \/\/ 演奏データ開始アドレス\n\t\tspcFile.writeU16(loopPoint & 0xffff); \/\/ ループポイント\n\t\tspcFile.writeByte(0xff); \/\/ _INITIAL_WAIT_FRAMES\n\t}\n \n \/\/ DSP領域の書き出し\n spcFile.setPos(0x10100);\n writeDspRegion(spcFile, reglog);\n\t\n\t\/\/ DIR,ESAの書き換え\n\tspcFile.setPos(0x1015d);\t\/\/ DIR\n\tspcFile.writeByte(dirPos >> 8);\n\tspcFile.setPos(0x1016d);\t\/\/ ESA\n\tspcFile.writeByte(esaPos >> 8);\n\t\n\t\/\/ KON,KOFフラグをクリアする\n\tspcFile.setPos(0x1014c);\n\tspcFile.writeByte(0x00);\n\tspcFile.setPos(0x1015c);\n\tspcFile.writeByte(0x00);\n\n spcFile.WriteToFile(path);\n \n delete [] reglogData;\n \n return true;\n}\n\nvoid SpcFileGenerate::SetGameTitle(const char *title)\n{\n setHeaderString(mGameTitle, title, 32);\n}\n\nvoid SpcFileGenerate::SetSongTitle(const char *title)\n{\n setHeaderString(mSongTitle, title, 32);\n}\n\nvoid SpcFileGenerate::SetNameOfDumper(const char *dumper)\n{\n setHeaderString(mNameOfDumper, dumper, 16);\n}\n\nvoid SpcFileGenerate::SetArtistOfSong(const char *artist)\n{\n setHeaderString(mArtistOfSong, artist, 32);\n}\n\nvoid SpcFileGenerate::SetSongComments(const char *comments)\n{\n setHeaderString(mSongComments, comments, 32);\n}\n\nvoid SpcFileGenerate::setHeaderString(char *dst, const char *src, int len)\n{\n if (src[0] == 0) {\n return;\n }\n memset(dst, 0x20, len);\n for (int i=0; (i 999) {\n mPlaySec = 999;\n }\n if (mPlaySec < 0) {\n mPlaySec = 0;\n }\n}\n\nvoid SpcFileGenerate::SetFadeMs(int ms)\n{\n mFadeMs = ms;\n if (mFadeMs > 99999) {\n mFadeMs = 99999;\n }\n if (mFadeMs < 0) {\n mFadeMs = 0;\n }\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid SpcFileGenerate::get700FileName( const char *path, char *out, int maxLen )\n{\n#if MAC\n\tCFURLRef\turl = CFURLCreateFromFileSystemRepresentation(NULL, (UInt8*)path, strlen(path), false);\n\tCFURLRef\textlesspath=CFURLCreateCopyDeletingPathExtension(NULL, url);\n\tCFStringRef\tfilename = CFURLCopyFileSystemPath(extlesspath,kCFURLPOSIXPathStyle);\n\tCFStringGetCString(filename, out, maxLen-1, kCFStringEncodingUTF8);\n\tstrcat(out, \".700\");\n\tCFRelease(filename);\n\tCFRelease(extlesspath);\n\tCFRelease(url);\n#else\n\tint\tlen = static_cast(strlen(path));\n\tint extPos = len;\n\tfor ( int i=len-1; i>=0; i-- ) {\n\t\tif ( path[i] == '.' ) {\n\t\t\textPos = i;\n\t\t\tbreak;\n\t\t}\n\t}\n\tstrncpy(out, path, extPos);\n\tout[extPos] = 0;\n\tstrcat(out, \".700\");\n#endif\n}\n\n\/\/-----------------------------------------------------------------------------\nint SpcFileGenerate::findDspregAccCode( const void *code, int size, const unsigned char **outCode )\n{\n\tconst unsigned char *p_code = (unsigned char*)code;\n\tfor (int i=0; i<(size-3); ++i) {\n\t\tif (p_code[i] == 0x8f && p_code[i+1] == 0x00 && p_code[i+2] == 0xf1) {\n\t\t\t*outCode = &p_code[i];\n\t\t\treturn size - i;\n\t\t}\n\t}\n\treturn 0;\n}\n<|endoftext|>"} {"text":"\/*\nT0 DA for online calibration\nContact: AllaMaevskaya@cern.ch\nRun Type: PHYSICS\nDA Type: MON\nNumber of events needed: 10000 \nInput Files: inPhys.dat, external parameters, T0\/Calib\/Slewing_Walk\nOutput Files: daPhys.root, to be exported to the DAQ FXS\nTrigger types used: PHYSICS_EVENT\n\n*\/\n\n#define FILE_OUT \"daPhys.root\"\n#define FILE_IN \"inPhys.dat\"\n#include \n#include \n#include \n \n#include \n#include \n#include \n\n\/\/AliRoot\n#include \n#include \n#include \n#include \n#include \n#include \n\/\/ROOT\n#include \"TROOT.h\"\n#include \"TPluginManager.h\"\n#include \"TFile.h\"\n#include \"TKey.h\"\n#include \"TObject.h\"\n#include \"TBenchmark.h\"\n#include \"TString.h\"\n#include \"TH1.h\"\n#include \"TMath.h\"\n\n\n\/* Main routine\n Arguments: \n 1- monitoring data source\n*\/\nint main(int argc, char **argv) {\n\/\/int main(){\n int status;\n\n \/* magic line *\/\n gROOT->GetPluginManager()->AddHandler(\"TVirtualStreamerInfo\",\n \"*\",\n \"TStreamerInfo\",\n \"RIO\",\n \"TStreamerInfo()\");\n \n if(daqDA_DB_getFile(FILE_IN, FILE_IN)){\n printf(\"Couldn't get input file >>inPhys.dat<< from DAQ_DB !!!\\n\");\n return -1;\n }\n \n \n FILE *inp;\n char c;\n inp = fopen(FILE_IN, \"r\");\n if(!inp){\n printf(\"Input file >>inPhys.dat<< not found !!!\\n\");\n return -1;\n }\n int kcbx, kt0bx, knpmtA, knpmtC,kcfdbx;\n float kclx,kcmx, kt0lx, kt0hx, kcfdlx, kcfdhx;\n \n while((c=getc(inp))!=EOF) {\n switch(c) {\n case 'a': {fscanf(inp, \"%d\", &kcbx ); break;} \/\/N of X bins hCFD1minCFD\n case 'b': {fscanf(inp, \"%f\", &kclx ); break;} \/\/Low x hCFD1minCFD\n case 'c': {fscanf(inp, \"%f\", &kcmx ); break;} \/\/High x hCFD1minCFD\n case 'd': {fscanf(inp, \"%d\", &knpmtC ); break;} \/\/number of reference PMTC\n case 'e': {fscanf(inp, \"%d\", &knpmtA ); break;} \/\/number of reference PMTA\n case 'f': {fscanf(inp, \"%d\", &kcfdbx ); break;} \/\/N of X bins hCFD&OR\n case 'g': {fscanf(inp, \"%f\", &kcfdlx ); break;} \/\/Low x hCFD&OR\n case 'k': {fscanf(inp, \"%f\", &kcfdhx ); break;} \/\/High x hCFD&OR\n case 'm': {fscanf(inp, \"%d\", &kt0bx ); break;} \/\/N of X bins TVDC\n case 'n': {fscanf(inp, \"%f\", &kt0lx ); break;} \/\/Low x TVDC\n case 'q': {fscanf(inp, \"%f\", &kt0hx ); break;} \/\/High x TVDC\n }\n }\n fclose(inp);\n\n if (argc!=2) {\n printf(\"Wrong number of arguments\\n\");\n return -1;\n }\n \n\n \/* define data source : this is argument 1 *\/ \n status=monitorSetDataSource( argv[1] );\n if (status!=0) {\n printf(\"monitorSetDataSource() failed : %s\\n\",monitorDecodeError(status));\n return -1;\n }\n \n \n \/* declare monitoring program *\/\n status=monitorDeclareMp( __FILE__ );\n if (status!=0) {\n printf(\"monitorDeclareMp() failed : %s\\n\",monitorDecodeError(status));\n return -1;\n }\n \n \n \/* define wait event timeout - 1s max *\/\n monitorSetNowait();\n monitorSetNoWaitNetworkTimeout(1000);\n \n \n \/* log start of process *\/\n printf(\"T0 monitoring program started\\n\"); \n \n \/\/ Get run number\n if (getenv(\"DATE_RUN_NUMBER\")==0) {\n printf(\"DATE_RUN_NUMBER not properly set.\\n\");\n return -1;\n }\n int runNr = atoi(getenv(\"DATE_RUN_NUMBER\"));\n\n \/\/ Get the necessary OCDB files from the DAQ detector DB\n if (gSystem->AccessPathName(\"localOCDB\/T0\/Calib\/Slewing_Walk\/\",kFileExists)) {\n if (gSystem->mkdir(\"localOCDB\/T0\/Calib\/Slewing_Walk\/\",kTRUE) != 0) {\n printf(\"Failed to create directory: localOCDB\/T0\/Calib\/Slewing_Walk\/\");\n return -1;\n }\n }\n status = daqDA_DB_getFile(\"T0\/Calib\/Slewing_Walk\/Run0_999999999_v0_s0.root\",\"localOCDB\/T0\/Calib\/Slewing_Walk\/Run0_999999999_v0_s0.root\");\n if (status) {\n printf(\"Failed to get file T0\/Calib\/Slewing_Walk() from DAQdetDB, status=%d\\n\", status);\n return -1;\n }\n \n TGraph *gr[24]; TGraph *gramp[24];\n AliCDBManager *man = AliCDBManager::Instance();\n man->SetDefaultStorage(\"local:\/\/localOCDB\");\n man->SetRun(runNr);\n cout<<\" run number \"<Get(\"T0\/Calib\/Slewing_Walk\");\n if(entry) {\n AliT0CalibWalk *fParam = (AliT0CalibWalk*)entry->GetObject();\n for (Int_t i=0; i<24; i++) {\n gr[i] = fParam->GetWalk(i); \n gramp[i] = fParam->GetQTC(i); \n }\n }\n Int_t chargeQT0[24], chargeQT1[24];\n Float_t adc ,walk, amp;\n \n \/\/ Allocation of histograms - start\n\n TH1F *hCFD1minCFD[24]; \n TH1F *hCFD[24], *hQT1[24], *hPed[24]; \n \n for(Int_t ic=0; ic<24; ic++) {\n hCFD1minCFD[ic] = new TH1F(Form(\"CFD1minCFD%d\",ic+1),\"CFD-CFD\",kcbx,kclx,kcmx);\n hCFD[ic] = new TH1F(Form(\"CFD%d\",ic+1),\"CFD\",kcfdbx,kcfdlx,kcfdhx);\n hQT1[ic] = new TH1F(Form(\"QT1%d\",ic+1),\"QT1\",kt0bx,kt0lx,kt0hx);\n hPed[ic] = new TH1F(Form(\"hPed%d\",ic+1),\"pedestal\",500,500,2000);\n }\n TH1F *hVertex = new TH1F(\"hVertex\",\"TVDC\",kt0bx,kt0lx,kt0hx);\n TH1F *hOrA = new TH1F(\"hOrA\",\"OrA\",kcfdbx,kcfdlx,kcfdhx);\n TH1F *hOrC = new TH1F(\"hOrC\",\"OrC\",kcfdbx,kcfdlx,kcfdhx);\n \n \/\/ Allocation of histograms - end\n\n\n Int_t iev=0;\n \/* main loop (infinite) *\/\n for(;;) {\n struct eventHeaderStruct *event;\n eventTypeType eventT;\n \n \/* check shutdown condition *\/\n if (daqDA_checkShutdown()) {break;}\n \n \/* get next event (blocking call until timeout) *\/\n status=monitorGetEventDynamic((void **)&event);\n if (status==(int)MON_ERR_EOF) {\n printf (\"End of File detected\\n\");\n break; \/* end of monitoring file has been reached *\/\n }\n \n if (status!=0) {\n printf(\"monitorGetEventDynamic() failed : %s\\n\",monitorDecodeError(status));\n break;\n }\n \n \/* retry if got no event *\/\n if (event==NULL) {\n continue;\n }\n \n \/* use event - here, just write event id to result file *\/\n eventT=event->eventType;\n \n switch (event->eventType){\n \n case START_OF_RUN:\n break;\n\t\n case END_OF_RUN:\n break;\n \n case PHYSICS_EVENT:\n \/\/\t \t case CALIBRATION_EVENT: for test\n iev++;\n \n if(iev==1){\n\tprintf(\"First event - %i\\n\",iev);\n }\n \n \/\/ Initalize raw-data reading and decoding\n AliRawReader *reader = new AliRawReaderDate((void*)event);\n \n \/\/ Enable the following two lines in case of real-data\n reader->RequireHeader(kTRUE);\n AliT0RawReader *start = new AliT0RawReader(reader, kTRUE);\n \/\/ start->SetPrintout(kFALSE);\n \/\/ Read raw data\n Int_t allData[220][5];\n for(Int_t i0=0;i0<220;i0++)\n \tfor(Int_t j0=0;j0<5;j0++)\n\t allData[i0][j0] = 0;\n \n if(start->Next()){\n\tfor (Int_t i=0; i<211; i++) {\n\t for(Int_t iHit=0;iHit<5;iHit++){\n\t allData[i][iHit]= start->GetData(i,iHit);\n\t }\n\t}\n }\n if (allData[50][0] == 0) continue;\n hVertex->Fill(allData[50][0]);\n hOrA->Fill(allData[51][0]);\n hOrC->Fill(allData[52][0]);\n \/\/ Fill the histograms\n walk = adc = amp = -999;\n for (Int_t in=0; in<12; in++)\n\t{\n\t chargeQT0[in]=allData[2*in+25][0];\n\t chargeQT1[in]=allData[2*in+26][0];\n\t}\t\n for (Int_t in=12; in<24; in++)\n\t{\n\t chargeQT0[in]=allData[2*in+57][0];\n\t chargeQT1[in]=allData[2*in+58][0];\n\t}\n Float_t time[24]; \n Float_t meanShift[24];\n for (Int_t ik = 0; ik<24; ik++)\n\t{ \t \n\t if( ( chargeQT0[ik] - chargeQT1[ik])>0) {\n\t adc = chargeQT0[ik] - chargeQT1[ik];\n\t \/\/\tcout<0) \n\t walk = Int_t(gr[ik]->Eval(Double_t(adc) ) );\n\t \/\/\t cout<0 ){\n\t if( walk >-100) hCFD[ik]->Fill(allData[ik+1][0] - walk);\n\t hQT1[ik]->Fill(chargeQT1[ik]);\n\t if ( allData[knpmtC][0]>0 )\n\t hCFD1minCFD[ik]->Fill(allData[ik+1][0]-allData[knpmtC][0]);\n\t }\n\t \n\t if(ik>11 && allData[ik+45][0]>0 )\n\t {\n\t if( walk >-100) hCFD[ik]->Fill(allData[ik+45][0] - walk);\n\t hQT1[ik]->Fill(chargeQT1[ik]);\n\t if (allData[56+knpmtA][0]>0)\n\t\t hCFD1minCFD[ik]->Fill(allData[ik+45][0]-allData[56+knpmtA][0]);\n\t }\n\t if(ik<12 && allData[ik+1][0]==0 && adc>0 ) hPed[ik]->Fill(adc);\n\t if(ik>11 && allData[ik+45][0]==0 && adc>0 ) hPed[ik]->Fill(adc);\n\n\t}\n\t \n delete start;\n start = 0x0;\n delete reader;\n reader= 0x0;\n \/\/ End of fill histograms\n \n }\n \n \/* free resources *\/\n free(event);\n \n \/* exit when last event received, no need to wait for TERM signal *\/\n if (eventT==END_OF_RUN) {\n printf(\"EOR event detected\\n\");\n printf(\"Number of events processed - %i\\n \",iev); \t\n break;\n }\n }\n printf(\"After loop, before writing histos\\n\");\n \/\/ write a file with the histograms\n\n TFile hist(FILE_OUT,\"RECREATE\");\n\n for(Int_t j=0;j<24;j++){\n hCFD1minCFD[j]->SetDirectory(&hist);\n hCFD1minCFD[j]->Write();\n hCFD[j]->Write();\n hQT1[j]->Write();\n hPed[j]->Write();\n }\n hVertex->Write();\n hOrA->Write();\n hOrC->Write();\n hist.Close();\n \/\/delete hist;\n\n status=0;\n\n \/* export file to FXS *\/\n if (daqDA_FES_storeFile(FILE_OUT, \"PHYSICS\")) {\n status=-2;\n }\n\n return status;\n}\n\n\nT00Physda read full 226 channels\/*\nT0 DA for online calibration\nContact: AllaMaevskaya@cern.ch\nRun Type: PHYSICS\nDA Type: MON\nNumber of events needed: 10000 \nInput Files: inPhys.dat, external parameters, T0\/Calib\/Slewing_Walk\nOutput Files: daPhys.root, to be exported to the DAQ FXS\nTrigger types used: PHYSICS_EVENT\n\n*\/\n\n#define FILE_OUT \"daPhys.root\"\n#define FILE_IN \"inPhys.dat\"\n#include \n#include \n#include \n \n#include \n#include \n#include \n\n\/\/AliRoot\n#include \n#include \n#include \n#include \n#include \n#include \n\/\/ROOT\n#include \"TROOT.h\"\n#include \"TPluginManager.h\"\n#include \"TFile.h\"\n#include \"TKey.h\"\n#include \"TObject.h\"\n#include \"TBenchmark.h\"\n#include \"TString.h\"\n#include \"TH1.h\"\n#include \"TMath.h\"\n\n\n\/* Main routine\n Arguments: \n 1- monitoring data source\n*\/\nint main(int argc, char **argv) {\n\/\/int main(){\n int status;\n\n \/* magic line *\/\n gROOT->GetPluginManager()->AddHandler(\"TVirtualStreamerInfo\",\n \"*\",\n \"TStreamerInfo\",\n \"RIO\",\n \"TStreamerInfo()\");\n \n if(daqDA_DB_getFile(FILE_IN, FILE_IN)){\n printf(\"Couldn't get input file >>inPhys.dat<< from DAQ_DB !!!\\n\");\n return -1;\n }\n \n \n FILE *inp;\n char c;\n inp = fopen(FILE_IN, \"r\");\n if(!inp){\n printf(\"Input file >>inPhys.dat<< not found !!!\\n\");\n return -1;\n }\n int kcbx, kt0bx, knpmtA, knpmtC,kcfdbx;\n float kclx,kcmx, kt0lx, kt0hx, kcfdlx, kcfdhx;\n \n while((c=getc(inp))!=EOF) {\n switch(c) {\n case 'a': {fscanf(inp, \"%d\", &kcbx ); break;} \/\/N of X bins hCFD1minCFD\n case 'b': {fscanf(inp, \"%f\", &kclx ); break;} \/\/Low x hCFD1minCFD\n case 'c': {fscanf(inp, \"%f\", &kcmx ); break;} \/\/High x hCFD1minCFD\n case 'd': {fscanf(inp, \"%d\", &knpmtC ); break;} \/\/number of reference PMTC\n case 'e': {fscanf(inp, \"%d\", &knpmtA ); break;} \/\/number of reference PMTA\n case 'f': {fscanf(inp, \"%d\", &kcfdbx ); break;} \/\/N of X bins hCFD&OR\n case 'g': {fscanf(inp, \"%f\", &kcfdlx ); break;} \/\/Low x hCFD&OR\n case 'k': {fscanf(inp, \"%f\", &kcfdhx ); break;} \/\/High x hCFD&OR\n case 'm': {fscanf(inp, \"%d\", &kt0bx ); break;} \/\/N of X bins TVDC\n case 'n': {fscanf(inp, \"%f\", &kt0lx ); break;} \/\/Low x TVDC\n case 'q': {fscanf(inp, \"%f\", &kt0hx ); break;} \/\/High x TVDC\n }\n }\n fclose(inp);\n\n if (argc!=2) {\n printf(\"Wrong number of arguments\\n\");\n return -1;\n }\n \n\n \/* define data source : this is argument 1 *\/ \n status=monitorSetDataSource( argv[1] );\n if (status!=0) {\n printf(\"monitorSetDataSource() failed : %s\\n\",monitorDecodeError(status));\n return -1;\n }\n \n \n \/* declare monitoring program *\/\n status=monitorDeclareMp( __FILE__ );\n if (status!=0) {\n printf(\"monitorDeclareMp() failed : %s\\n\",monitorDecodeError(status));\n return -1;\n }\n \n \n \/* define wait event timeout - 1s max *\/\n monitorSetNowait();\n monitorSetNoWaitNetworkTimeout(1000);\n \n \n \/* log start of process *\/\n printf(\"T0 monitoring program started\\n\"); \n \n \/\/ Get run number\n if (getenv(\"DATE_RUN_NUMBER\")==0) {\n printf(\"DATE_RUN_NUMBER not properly set.\\n\");\n return -1;\n }\n int runNr = atoi(getenv(\"DATE_RUN_NUMBER\"));\n\n \/\/ Get the necessary OCDB files from the DAQ detector DB\n if (gSystem->AccessPathName(\"localOCDB\/T0\/Calib\/Slewing_Walk\/\",kFileExists)) {\n if (gSystem->mkdir(\"localOCDB\/T0\/Calib\/Slewing_Walk\/\",kTRUE) != 0) {\n printf(\"Failed to create directory: localOCDB\/T0\/Calib\/Slewing_Walk\/\");\n return -1;\n }\n }\n status = daqDA_DB_getFile(\"T0\/Calib\/Slewing_Walk\/Run0_999999999_v0_s0.root\",\"localOCDB\/T0\/Calib\/Slewing_Walk\/Run0_999999999_v0_s0.root\");\n if (status) {\n printf(\"Failed to get file T0\/Calib\/Slewing_Walk() from DAQdetDB, status=%d\\n\", status);\n return -1;\n }\n \n TGraph *gr[24]; TGraph *gramp[24];\n AliCDBManager *man = AliCDBManager::Instance();\n man->SetDefaultStorage(\"local:\/\/localOCDB\");\n man->SetRun(runNr);\n cout<<\" run number \"<Get(\"T0\/Calib\/Slewing_Walk\");\n if(entry) {\n AliT0CalibWalk *fParam = (AliT0CalibWalk*)entry->GetObject();\n for (Int_t i=0; i<24; i++) {\n gr[i] = fParam->GetWalk(i); \n gramp[i] = fParam->GetQTC(i); \n }\n }\n Int_t chargeQT0[24], chargeQT1[24];\n Float_t adc ,walk, amp;\n \n \/\/ Allocation of histograms - start\n\n TH1F *hCFD1minCFD[24]; \n TH1F *hCFD[24], *hQT1[24], *hPed[24]; \n \n for(Int_t ic=0; ic<24; ic++) {\n hCFD1minCFD[ic] = new TH1F(Form(\"CFD1minCFD%d\",ic+1),\"CFD-CFD\",kcbx,kclx,kcmx);\n hCFD[ic] = new TH1F(Form(\"CFD%d\",ic+1),\"CFD\",kcfdbx,kcfdlx,kcfdhx);\n hQT1[ic] = new TH1F(Form(\"QT1%d\",ic+1),\"QT1\",kt0bx,kt0lx,kt0hx);\n hPed[ic] = new TH1F(Form(\"hPed%d\",ic+1),\"pedestal\",500,500,2000);\n }\n TH1F *hVertex = new TH1F(\"hVertex\",\"TVDC\",kt0bx,kt0lx,kt0hx);\n TH1F *hOrA = new TH1F(\"hOrA\",\"OrA\",kcfdbx,kcfdlx,kcfdhx);\n TH1F *hOrC = new TH1F(\"hOrC\",\"OrC\",kcfdbx,kcfdlx,kcfdhx);\n \n \/\/ Allocation of histograms - end\n\n\n Int_t iev=0;\n \/* main loop (infinite) *\/\n for(;;) {\n struct eventHeaderStruct *event;\n eventTypeType eventT;\n \n \/* check shutdown condition *\/\n if (daqDA_checkShutdown()) {break;}\n \n \/* get next event (blocking call until timeout) *\/\n status=monitorGetEventDynamic((void **)&event);\n if (status==(int)MON_ERR_EOF) {\n printf (\"End of File detected\\n\");\n break; \/* end of monitoring file has been reached *\/\n }\n \n if (status!=0) {\n printf(\"monitorGetEventDynamic() failed : %s\\n\",monitorDecodeError(status));\n break;\n }\n \n \/* retry if got no event *\/\n if (event==NULL) {\n continue;\n }\n \n \/* use event - here, just write event id to result file *\/\n eventT=event->eventType;\n \n switch (event->eventType){\n \n case START_OF_RUN:\n break;\n\t\n case END_OF_RUN:\n break;\n \n case PHYSICS_EVENT:\n \/\/\t \t case CALIBRATION_EVENT: for test\n iev++;\n \n if(iev==1){\n\tprintf(\"First event - %i\\n\",iev);\n }\n \n \/\/ Initalize raw-data reading and decoding\n AliRawReader *reader = new AliRawReaderDate((void*)event);\n \n \/\/ Enable the following two lines in case of real-data\n reader->RequireHeader(kTRUE);\n AliT0RawReader *start = new AliT0RawReader(reader, kTRUE);\n \/\/ start->SetPrintout(kFALSE);\n \/\/ Read raw data\n Int_t allData[250][5];\n for(Int_t i0=0;i0<250;i0++)\n \tfor(Int_t j0=0;j0<5;j0++)\n\t allData[i0][j0] = 0;\n \n if(start->Next()){\n\tfor (Int_t i=0; i<226; i++) {\n\t for(Int_t iHit=0;iHit<5;iHit++){\n\t allData[i][iHit]= start->GetData(i,iHit);\n\t }\n\t}\n }\n if (allData[50][0] == 0) continue;\n hVertex->Fill(allData[50][0]);\n hOrA->Fill(allData[51][0]);\n hOrC->Fill(allData[52][0]);\n \/\/ Fill the histograms\n walk = adc = amp = -999;\n for (Int_t in=0; in<12; in++)\n\t{\n\t chargeQT0[in]=allData[2*in+25][0];\n\t chargeQT1[in]=allData[2*in+26][0];\n\t}\t\n for (Int_t in=12; in<24; in++)\n\t{\n\t chargeQT0[in]=allData[2*in+57][0];\n\t chargeQT1[in]=allData[2*in+58][0];\n\t}\n Float_t time[24]; \n Float_t meanShift[24];\n for (Int_t ik = 0; ik<24; ik++)\n\t{ \t \n\t if( ( chargeQT0[ik] - chargeQT1[ik])>0) {\n\t adc = chargeQT0[ik] - chargeQT1[ik];\n\t \/\/\tcout<0) \n\t walk = Int_t(gr[ik]->Eval(Double_t(adc) ) );\n\t \/\/\t cout<0 ){\n\t if( walk >-100) hCFD[ik]->Fill(allData[ik+1][0] - walk);\n\t hQT1[ik]->Fill(chargeQT1[ik]);\n\t if ( allData[knpmtC][0]>0 )\n\t hCFD1minCFD[ik]->Fill(allData[ik+1][0]-allData[knpmtC][0]);\n\t }\n\t \n\t if(ik>11 && allData[ik+45][0]>0 )\n\t {\n\t if( walk >-100) hCFD[ik]->Fill(allData[ik+45][0] - walk);\n\t hQT1[ik]->Fill(chargeQT1[ik]);\n\t if (allData[56+knpmtA][0]>0)\n\t\t hCFD1minCFD[ik]->Fill(allData[ik+45][0]-allData[56+knpmtA][0]);\n\t }\n\t if(ik<12 && allData[ik+1][0]==0 && adc>0 ) hPed[ik]->Fill(adc);\n\t if(ik>11 && allData[ik+45][0]==0 && adc>0 ) hPed[ik]->Fill(adc);\n\n\t}\n\t \n delete start;\n start = 0x0;\n delete reader;\n reader= 0x0;\n \/\/ End of fill histograms\n \n }\n \n \/* free resources *\/\n free(event);\n \n \/* exit when last event received, no need to wait for TERM signal *\/\n if (eventT==END_OF_RUN) {\n printf(\"EOR event detected\\n\");\n printf(\"Number of events processed - %i\\n \",iev); \t\n break;\n }\n }\n printf(\"After loop, before writing histos\\n\");\n \/\/ write a file with the histograms\n\n TFile hist(FILE_OUT,\"RECREATE\");\n\n for(Int_t j=0;j<24;j++){\n hCFD1minCFD[j]->SetDirectory(&hist);\n hCFD1minCFD[j]->Write();\n hCFD[j]->Write();\n hQT1[j]->Write();\n hPed[j]->Write();\n }\n hVertex->Write();\n hOrA->Write();\n hOrC->Write();\n hist.Close();\n \/\/delete hist;\n\n status=0;\n\n \/* export file to FXS *\/\n if (daqDA_FES_storeFile(FILE_OUT, \"PHYSICS\")) {\n status=-2;\n }\n\n return status;\n}\n\n\n<|endoftext|>"} {"text":"\/\/\n\/\/ MSXDSK.cpp\n\/\/ Clock Signal\n\/\/\n\/\/ Created by Thomas Harte on 07\/01\/2018.\n\/\/ Copyright © 2018 Thomas Harte. All rights reserved.\n\/\/\n\n#include \"MSXDSK.hpp\"\n\n#include \"Utility\/ImplicitSectors.hpp\"\n\nnamespace {\n\tstatic const int sectors_per_track = 9;\n\tstatic const int sector_size = 2;\n}\n\nusing namespace Storage::Disk;\n\nMSXDSK::MSXDSK(const char *file_name) :\n\tMFMSectorDump(file_name) {\n\t\/\/ The only sanity check here is whether a sensible\n\t\/\/ geometry can be guessed.\n\toff_t file_size = file_.stats().st_size;\n\tconst off_t track_size = 512*9;\n\n\t\/\/ Throw if there would seemingly be an incomplete track.\n\tif(file_size % track_size) throw ErrorNotMSXDSK;\n\n\ttrack_count_ = static_cast(file_size \/ track_size);\n\thead_count_ = 1;\n\n\t\/\/ Throw if too large or too small or too large for single sided and\n\t\/\/ clearly not double sided.\n\tif(track_count_ < 40) throw ErrorNotMSXDSK;\n\tif(track_count_ > 82*2) throw ErrorNotMSXDSK;\n\tif(track_count_ > 82 && track_count_&1) throw ErrorNotMSXDSK;\n\n\t\/\/ The below effectively prefers the idea of a single-sided 80-track disk\n\t\/\/ to a double-sided 40-track disk. Emulators have to guess.\n\tif(track_count_ > 82) {\n\t\ttrack_count_ \/= 2;\n\t\thead_count_ = 2;\n\t}\n\n\tset_geometry(sectors_per_track, sector_size, 1, true);\n}\n\nint MSXDSK::get_head_position_count() {\n\treturn track_count_;\n}\n\nint MSXDSK::get_head_count() {\n\treturn head_count_;\n}\n\nlong MSXDSK::get_file_offset_for_position(Track::Address address) {\n\treturn (address.position*2 + address.head) * 512 * 9;\n}\nCorrects assumption of double sidedness.\/\/\n\/\/ MSXDSK.cpp\n\/\/ Clock Signal\n\/\/\n\/\/ Created by Thomas Harte on 07\/01\/2018.\n\/\/ Copyright © 2018 Thomas Harte. All rights reserved.\n\/\/\n\n#include \"MSXDSK.hpp\"\n\n#include \"Utility\/ImplicitSectors.hpp\"\n\nnamespace {\n\tstatic const int sectors_per_track = 9;\n\tstatic const int sector_size = 2;\n}\n\nusing namespace Storage::Disk;\n\nMSXDSK::MSXDSK(const char *file_name) :\n\tMFMSectorDump(file_name) {\n\t\/\/ The only sanity check here is whether a sensible\n\t\/\/ geometry can be guessed.\n\toff_t file_size = file_.stats().st_size;\n\tconst off_t track_size = 512*9;\n\n\t\/\/ Throw if there would seemingly be an incomplete track.\n\tif(file_size % track_size) throw ErrorNotMSXDSK;\n\n\ttrack_count_ = static_cast(file_size \/ track_size);\n\thead_count_ = 1;\n\n\t\/\/ Throw if too large or too small or too large for single sided and\n\t\/\/ clearly not double sided.\n\tif(track_count_ < 40) throw ErrorNotMSXDSK;\n\tif(track_count_ > 82*2) throw ErrorNotMSXDSK;\n\tif(track_count_ > 82 && track_count_&1) throw ErrorNotMSXDSK;\n\n\t\/\/ The below effectively prefers the idea of a single-sided 80-track disk\n\t\/\/ to a double-sided 40-track disk. Emulators have to guess.\n\tif(track_count_ > 82) {\n\t\ttrack_count_ \/= 2;\n\t\thead_count_ = 2;\n\t}\n\n\tset_geometry(sectors_per_track, sector_size, 1, true);\n}\n\nint MSXDSK::get_head_position_count() {\n\treturn track_count_;\n}\n\nint MSXDSK::get_head_count() {\n\treturn head_count_;\n}\n\nlong MSXDSK::get_file_offset_for_position(Track::Address address) {\n\treturn (address.position*head_count_ + address.head) * 512 * 9;\n}\n<|endoftext|>"} {"text":"\/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- *\/\n\/*************************************************************************\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2000, 2010 Oracle and\/or its affiliates.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * \n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_extensions.hxx\"\n\n#include \n\n#include \"oooimprovecore_module.hxx\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace ::com::sun::star::oooimprovement;\nusing ::com::sun::star::frame::XTerminateListener;\nusing ::com::sun::star::lang::EventObject;\nusing ::com::sun::star::lang::XMultiServiceFactory;\nusing ::com::sun::star::lang::XServiceInfo;\nusing ::com::sun::star::uno::Reference;\nusing ::com::sun::star::uno::RuntimeException;\nusing ::com::sun::star::uno::Sequence;\nusing ::com::sun::star::uno::UNO_QUERY;\nusing ::com::sun::star::uno::XComponentContext;\nusing ::com::sun::star::uno::XInterface;\nusing ::comphelper::UiEventsLogger;\nusing ::rtl::OUString;\n\n\/\/ declaration\nnamespace oooimprovecore\n{\n class Core : public ::cppu::WeakImplHelper3\n {\n public:\n \/\/ XServiceInfo - static version\n static OUString SAL_CALL getImplementationName_static();\n static Sequence SAL_CALL getSupportedServiceNames_static();\n static Reference Create(const Reference& context );\n\n protected:\n Core(const Reference&);\n virtual ~Core();\n\n \/\/ XCore\n virtual sal_Int32 SAL_CALL getSessionLogEventCount() throw(RuntimeException);\n virtual sal_Bool SAL_CALL getUiEventsLoggerEnabled() throw(RuntimeException);\n virtual void SAL_CALL inviteUser() throw(RuntimeException);\n\n \/\/ XServiceInfo\n virtual OUString SAL_CALL getImplementationName() throw(RuntimeException);\n virtual sal_Bool SAL_CALL supportsService(const OUString& service_name) throw(RuntimeException);\n virtual Sequence SAL_CALL getSupportedServiceNames() throw(RuntimeException);\n\n \/\/ XTerminateListener\n virtual void SAL_CALL queryTermination(const EventObject&) throw(RuntimeException);\n virtual void SAL_CALL notifyTermination(const EventObject&) throw(RuntimeException);\n\n \/\/ XEventListener\n virtual void SAL_CALL disposing(const EventObject&) throw(RuntimeException);\n };\n}\n\n\n\/\/ implementation\nnamespace oooimprovecore\n{\n\n Core::Core(const Reference&)\n { }\n\n Core::~Core()\n { }\n\n sal_Int32 SAL_CALL Core::getSessionLogEventCount() throw(RuntimeException)\n { return UiEventsLogger::getSessionLogEventCount(); }\n\n sal_Bool SAL_CALL Core::getUiEventsLoggerEnabled() throw(RuntimeException)\n { return UiEventsLogger::isEnabled(); }\n\n void SAL_CALL Core::inviteUser() throw(RuntimeException)\n {\n Reference xServiceFactory = ::comphelper::getProcessServiceFactory();\n\n OUString help_url;\n Reference core_c(\n xServiceFactory->createInstance(OUString::createFromAscii(\"com.sun.star.oooimprovement.CoreController\")),\n UNO_QUERY);\n if(core_c.is())\n ::comphelper::ConfigurationHelper::readDirectKey(\n xServiceFactory,\n OUString::createFromAscii(\"\/org.openoffice.Office.OOoImprovement.Settings\"),\n OUString::createFromAscii(\"Participation\"),\n OUString::createFromAscii(\"HelpUrl\"),\n ::comphelper::ConfigurationHelper::E_READONLY) >>= help_url;\n else\n help_url = OUString::createFromAscii(\"http:\/\/www.openoffice.org\");\n {\n SolarMutexGuard aGuard;\n SfxAllItemSet aSet( SFX_APP()->GetPool() );\n aSet.Put( SfxStringItem( SID_CURRENT_URL, help_url ) );\n SvxAbstractDialogFactory* pFact = SvxAbstractDialogFactory::Create();\n if ( pFact )\n {\n SfxAbstractDialog *pDlg = pFact->CreateSfxDialog( NULL, aSet, 0, RID_SVXPAGE_IMPROVEMENT );\n pDlg->Execute();\n delete pDlg;\n }\n }\n }\n\n sal_Bool SAL_CALL Core::supportsService(const OUString& service_name) throw(RuntimeException)\n {\n const Sequence service_names(getSupportedServiceNames());\n for (sal_Int32 idx = service_names.getLength()-1; idx>=0; --idx)\n if(service_name == service_names[idx]) return sal_True;\n return sal_False;\n }\n\n OUString SAL_CALL Core::getImplementationName() throw(RuntimeException)\n { return getImplementationName_static(); }\n\n Sequence SAL_CALL Core::getSupportedServiceNames() throw(RuntimeException)\n { return getSupportedServiceNames_static(); }\n\n OUString SAL_CALL Core::getImplementationName_static()\n { return OUString::createFromAscii(\"com.sun.star.comp.extensions.oooimprovecore.Core\"); }\n\n Sequence SAL_CALL Core::getSupportedServiceNames_static()\n {\n Sequence aServiceNames(1);\n aServiceNames[0] = OUString::createFromAscii(\"com.sun.star.oooimprovement.Core\");\n return aServiceNames;\n }\n\n void Core::queryTermination(const EventObject&) throw(RuntimeException)\n { }\n\n void Core::notifyTermination(const EventObject&) throw(RuntimeException)\n {\n UiEventsLogger::disposing();\n }\n\n void Core::disposing(const EventObject&) throw(RuntimeException)\n { }\n\n Reference Core::Create(const Reference& context)\n { return *(new Core(context)); }\n\n void createRegistryInfo_Core()\n {\n static OAutoRegistration auto_reg;\n }\n}\n\n\/* vim:set shiftwidth=4 softtabstop=4 expandtab: *\/\nChanging a few more strings to read \"LibreOffice\" (cherry picked from commit da9762a0da84a061fd2adadfdb51295357d5e270)\/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- *\/\n\/*************************************************************************\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2000, 2010 Oracle and\/or its affiliates.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * \n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_extensions.hxx\"\n\n#include \n\n#include \"oooimprovecore_module.hxx\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace ::com::sun::star::oooimprovement;\nusing ::com::sun::star::frame::XTerminateListener;\nusing ::com::sun::star::lang::EventObject;\nusing ::com::sun::star::lang::XMultiServiceFactory;\nusing ::com::sun::star::lang::XServiceInfo;\nusing ::com::sun::star::uno::Reference;\nusing ::com::sun::star::uno::RuntimeException;\nusing ::com::sun::star::uno::Sequence;\nusing ::com::sun::star::uno::UNO_QUERY;\nusing ::com::sun::star::uno::XComponentContext;\nusing ::com::sun::star::uno::XInterface;\nusing ::comphelper::UiEventsLogger;\nusing ::rtl::OUString;\n\n\/\/ declaration\nnamespace oooimprovecore\n{\n class Core : public ::cppu::WeakImplHelper3\n {\n public:\n \/\/ XServiceInfo - static version\n static OUString SAL_CALL getImplementationName_static();\n static Sequence SAL_CALL getSupportedServiceNames_static();\n static Reference Create(const Reference& context );\n\n protected:\n Core(const Reference&);\n virtual ~Core();\n\n \/\/ XCore\n virtual sal_Int32 SAL_CALL getSessionLogEventCount() throw(RuntimeException);\n virtual sal_Bool SAL_CALL getUiEventsLoggerEnabled() throw(RuntimeException);\n virtual void SAL_CALL inviteUser() throw(RuntimeException);\n\n \/\/ XServiceInfo\n virtual OUString SAL_CALL getImplementationName() throw(RuntimeException);\n virtual sal_Bool SAL_CALL supportsService(const OUString& service_name) throw(RuntimeException);\n virtual Sequence SAL_CALL getSupportedServiceNames() throw(RuntimeException);\n\n \/\/ XTerminateListener\n virtual void SAL_CALL queryTermination(const EventObject&) throw(RuntimeException);\n virtual void SAL_CALL notifyTermination(const EventObject&) throw(RuntimeException);\n\n \/\/ XEventListener\n virtual void SAL_CALL disposing(const EventObject&) throw(RuntimeException);\n };\n}\n\n\n\/\/ implementation\nnamespace oooimprovecore\n{\n\n Core::Core(const Reference&)\n { }\n\n Core::~Core()\n { }\n\n sal_Int32 SAL_CALL Core::getSessionLogEventCount() throw(RuntimeException)\n { return UiEventsLogger::getSessionLogEventCount(); }\n\n sal_Bool SAL_CALL Core::getUiEventsLoggerEnabled() throw(RuntimeException)\n { return UiEventsLogger::isEnabled(); }\n\n void SAL_CALL Core::inviteUser() throw(RuntimeException)\n {\n Reference xServiceFactory = ::comphelper::getProcessServiceFactory();\n\n OUString help_url;\n Reference core_c(\n xServiceFactory->createInstance(OUString::createFromAscii(\"com.sun.star.oooimprovement.CoreController\")),\n UNO_QUERY);\n if(core_c.is())\n ::comphelper::ConfigurationHelper::readDirectKey(\n xServiceFactory,\n OUString::createFromAscii(\"\/org.openoffice.Office.OOoImprovement.Settings\"),\n OUString::createFromAscii(\"Participation\"),\n OUString::createFromAscii(\"HelpUrl\"),\n ::comphelper::ConfigurationHelper::E_READONLY) >>= help_url;\n else\n help_url = OUString::createFromAscii(\"http:\/\/www.libreoffice.org\");\n {\n SolarMutexGuard aGuard;\n SfxAllItemSet aSet( SFX_APP()->GetPool() );\n aSet.Put( SfxStringItem( SID_CURRENT_URL, help_url ) );\n SvxAbstractDialogFactory* pFact = SvxAbstractDialogFactory::Create();\n if ( pFact )\n {\n SfxAbstractDialog *pDlg = pFact->CreateSfxDialog( NULL, aSet, 0, RID_SVXPAGE_IMPROVEMENT );\n pDlg->Execute();\n delete pDlg;\n }\n }\n }\n\n sal_Bool SAL_CALL Core::supportsService(const OUString& service_name) throw(RuntimeException)\n {\n const Sequence service_names(getSupportedServiceNames());\n for (sal_Int32 idx = service_names.getLength()-1; idx>=0; --idx)\n if(service_name == service_names[idx]) return sal_True;\n return sal_False;\n }\n\n OUString SAL_CALL Core::getImplementationName() throw(RuntimeException)\n { return getImplementationName_static(); }\n\n Sequence SAL_CALL Core::getSupportedServiceNames() throw(RuntimeException)\n { return getSupportedServiceNames_static(); }\n\n OUString SAL_CALL Core::getImplementationName_static()\n { return OUString::createFromAscii(\"com.sun.star.comp.extensions.oooimprovecore.Core\"); }\n\n Sequence SAL_CALL Core::getSupportedServiceNames_static()\n {\n Sequence aServiceNames(1);\n aServiceNames[0] = OUString::createFromAscii(\"com.sun.star.oooimprovement.Core\");\n return aServiceNames;\n }\n\n void Core::queryTermination(const EventObject&) throw(RuntimeException)\n { }\n\n void Core::notifyTermination(const EventObject&) throw(RuntimeException)\n {\n UiEventsLogger::disposing();\n }\n\n void Core::disposing(const EventObject&) throw(RuntimeException)\n { }\n\n Reference Core::Create(const Reference& context)\n { return *(new Core(context)); }\n\n void createRegistryInfo_Core()\n {\n static OAutoRegistration auto_reg;\n }\n}\n\n\/* vim:set shiftwidth=4 softtabstop=4 expandtab: *\/\n<|endoftext|>"} {"text":"\/\/ TestDAQ.cpp : Defines the entry point for the console application.\n\/\/\n\n#include \"stdafx.h\"\n\n#include \"util-nidaqmx.h\"\n\n#define CHK(expr) Guarded_DAQmx( (expr), #expr, error )\n\n#define N 4000\n\nvoid test2(void)\n{\n\tTaskHandle cur_task=0, ao_task=0, clk_task=0;\n\tfloat64 data[N];\t\n\tfloat64 freq = 10000; \/\/ Hz\t- sample rate\n\tint32 written;\n\n { int i=N;\n\t while(i--)\n\t\t data[i] = 5.0*(double)i\/((double)N); \/\/ linear ramp from 0.0 to 5.0 V\n }\n\n Reporting_Setup_Log_To_Stdout();\n Reporting_Setup_Log_To_VSDebugger_Console();\n\n \/\/ set up ao task\n cur_task = 0;\n\tCHK( DAQmxCreateTask (\"galvo\",&cur_task));\n\tCHK( DAQmxCreateAOVoltageChan (cur_task,\"\/Dev1\/ao0\",\"\",-10.0,10.0,DAQmx_Val_Volts ,NULL));\n\tCHK( DAQmxCfgSampClkTiming (cur_task,\n\t \"Ctr0InternalOutput\",\n\t freq,\n\t DAQmx_Val_Rising,\n\t DAQmx_Val_ContSamps, \/\/ use continuous output so that counter stays in control\n\t N));\n\tCHK( DAQmxCfgAnlgEdgeStartTrig (cur_task,\"APFI0\",DAQmx_Val_Rising, 0.0));\n\tCHK( DAQmxWriteAnalogF64 (cur_task,\n\t N,\n\t 0, \/\/ autostart?\n\t 10.0, \/\/ timeout (s)\n\t DAQmx_Val_GroupByChannel,\n\t data,\n\t &written,\n\t NULL));\n\tao_task = cur_task;\n\n\t\/\/ set up counter for sample clock\n\tcur_task = 0;\n\tCHK( DAQmxCreateTask ( \"clock\",&cur_task)); \n\tCHK( DAQmxCreateCOPulseChanFreq ( cur_task, \"Dev1\/ctr0\", \"\", DAQmx_Val_Hz, DAQmx_Val_Low, 0.0, freq, 0.5 ));\n\tCHK( DAQmxCfgImplicitTiming ( cur_task, DAQmx_Val_FiniteSamps, N ));\n\tCHK( DAQmxCfgDigEdgeStartTrig ( cur_task, \"AnalogComparisonEvent\", DAQmx_Val_Rising ));\n\tCHK( DAQmxSetArmStartTrigType ( cur_task, DAQmx_Val_DigEdge ));\n\tCHK( DAQmxSetDigEdgeArmStartTrigSrc ( cur_task, \"PFI0\" ));\n\tCHK( DAQmxSetDigEdgeArmStartTrigEdge ( cur_task, DAQmx_Val_Rising ));\n\tclk_task = cur_task;\n\t\n\t{ int i;\n\t TicTocTimer clock = tic();\n\t CHK( DAQmxStartTask (ao_task));\n\t for(i=0;i<10; i++ )\n\t { \n\t CHK( DAQmxStartTask (clk_task));\n\t \/\/debug(\"iter: %d time: %g\\r\\n\",i, toc(&clock) );\n\t debug(\",%g\\r\\n\",toc(&clock) );\n\t CHK( DAQmxWaitUntilTaskDone (clk_task,100.0));\n\t toc(&clock);\n\t CHK( DAQmxStopTask (clk_task));\t \n\t }\n\t DAQmxStopTask(ao_task);\n\t}\n\nError:\n\n\tif( clk_task!=0 ) {\n\t\tDAQmxStopTask(clk_task);\n\t\tDAQmxClearTask(clk_task);\n\t}\n if( ao_task!=0 ) {\n\t\tDAQmxStopTask(ao_task);\n\t\tDAQmxClearTask(ao_task);\n\t}\n\tprintf(\"End of program, press Enter key to quit\\n\");\n\tgetchar();\n\treturn;\n}\n\n\n\/* Timings 2010-01-11 Time for Start\/Stop of AO task\na = array([8.17151e-005\n,0.000236025\n,0.000238579\n,0.000252806\n,0.000249523\n,0.000233107\n,0.000254995\n,0.000231648\n,0.000252806\n,0.000253901])\n*\/\n\n\/* Timings 2010-01-12 (test2) Time for Start\/Stop of doubley triggered ctr task\n * delay: 472 +- 6 us max: 483 us min: 459 us\na = array([0.000458918\n,0.000482995\n,0.000475334\n,0.000474969\n,0.000468768\n,0.00047424\n,0.000468768\n,0.000476064\n,0.000472416])\n*\/\nint _tmain(int argc, _TCHAR* argv[])\n{ test2();\n}Integrating w digitizer.\/\/ TestDAQ.cpp : Defines the entry point for the console application.\n\/\/\n\n#include \"stdafx.h\"\n\n#include \"util-nidaqmx.h\"\n\n#define CHK(expr) Guarded_DAQmx( (expr), #expr, error )\n\n#define N 4000\n\nvoid test2(void)\n{\n\tTaskHandle cur_task=0, ao_task=0, clk_task=0;\/\/, trg_task=0;\n\tfloat64 data[N];\t\n\tfloat64 freq = 10000; \/\/ Hz\t- sample rate\n\tint32 written;\n\n { int i=N;\n\t while(i--)\n\t\t data[i] = 5.0*(double)i\/((double)N); \/\/ linear ramp from 0.0 to 5.0 V\n }\n\n Reporting_Setup_Log_To_Stdout();\n Reporting_Setup_Log_To_VSDebugger_Console();\n\n \/\/ set up ao task\n cur_task = 0;\n\tCHK( DAQmxCreateTask (\"galvo\",&cur_task));\n\tCHK( DAQmxCreateAOVoltageChan (cur_task,\"\/Dev1\/ao0\",\"\",-10.0,10.0,DAQmx_Val_Volts ,NULL));\n\tCHK( DAQmxCfgSampClkTiming (cur_task,\n\t \"Ctr1InternalOutput\",\n\t freq,\n\t DAQmx_Val_Rising,\n\t DAQmx_Val_ContSamps, \/\/ use continuous output so that counter stays in control\n\t N));\n\tCHK( DAQmxCfgAnlgEdgeStartTrig (cur_task,\"APFI0\",DAQmx_Val_Rising, 0.0));\n\tCHK( DAQmxWriteAnalogF64 (cur_task,\n\t N,\n\t 0, \/\/ autostart?\n\t 10.0, \/\/ timeout (s)\n\t DAQmx_Val_GroupByChannel,\n\t data,\n\t &written,\n\t NULL));\n\tao_task = cur_task;\n\n\t\/\/ set up counter for sample clock\n\tcur_task = 0;\n\tCHK( DAQmxCreateTask ( \"clock\",&cur_task));\n\tCHK( DAQmxCreateCOPulseChanFreq ( cur_task, \"Dev1\/ctr1\", \"\", DAQmx_Val_Hz, DAQmx_Val_Low, 0.0, freq, 0.5 ));\n\tCHK( DAQmxCfgImplicitTiming ( cur_task, DAQmx_Val_FiniteSamps, N ));\n\tCHK( DAQmxCfgDigEdgeStartTrig ( cur_task, \"AnalogComparisonEvent\", DAQmx_Val_Rising ));\n\tCHK( DAQmxSetArmStartTrigType ( cur_task, DAQmx_Val_DigEdge ));\n\tCHK( DAQmxSetDigEdgeArmStartTrigSrc ( cur_task, \"PFI0\" ));\n\tCHK( DAQmxSetDigEdgeArmStartTrigEdge ( cur_task, DAQmx_Val_Rising ));\n\tclk_task = cur_task;\n\t\n\t\/\/\/\/ set up retiggerable frame sync pulse\n\t\/\/cur_task = 0;\n\t\/\/CHK( DAQmxCreateTask ( \"FrameSync\",&cur_task)); \/\/ delay and low time can be used to controllably offset the AO start from digitizier start\n\t\/\/CHK( DAQmxCreateCOPulseChanTime ( cur_task, \"Dev1\/ctr1\", \"\", DAQmx_Val_Seconds, DAQmx_Val_Low, 50e-9, 50e-9, 1e-3 ));\n\t\/\/CHK( DAQmxCfgDigEdgeStartTrig ( cur_task, \"AnalogComparisonEvent\", DAQmx_Val_Rising ));\n\t\/\/trg_task = cur_task;\n\t\n\t{ int i;\n\t TicTocTimer clock = tic();\n\t CHK( DAQmxStartTask ( ao_task));\n\t \/\/CHK( DAQmxStartTask (trg_task));\n\t \/\/for(i=0;i<10; i++ )\n\t while(1)\n\t { \n\t CHK( DAQmxStartTask (clk_task));\n\t \/\/debug(\"iter: %d time: %g\\r\\n\",i, toc(&clock) );\n\t debug(\",%g\\r\\n\",toc(&clock) );\n\t CHK( DAQmxWaitUntilTaskDone (clk_task,DAQmx_Val_WaitInfinitely));\n\t toc(&clock);\n\t CHK( DAQmxStopTask (clk_task));\t \n\t }\n\t DAQmxStopTask(ao_task);\n\t \/\/DAQmxStopTask(trg_task);\n\t}\n\nError:\n\n\tif( clk_task!=0 ) {\n\t\tDAQmxStopTask(clk_task);\n\t\tDAQmxClearTask(clk_task);\n\t}\n if( ao_task!=0 ) {\n\t\tDAQmxStopTask(ao_task);\n\t\tDAQmxClearTask(ao_task);\n\t}\n\t\/\/if( trg_task!=0 ) {\n\t\/\/\tDAQmxStopTask(trg_task);\n\t\/\/\tDAQmxClearTask(trg_task);\n\t\/\/}\n\tprintf(\"End of program, press Enter key to quit\\n\");\n\tgetchar();\n\treturn;\n}\n\n\n\/* Timings 2010-01-11 Time for Start\/Stop of AO task\na = array([8.17151e-005\n,0.000236025\n,0.000238579\n,0.000252806\n,0.000249523\n,0.000233107\n,0.000254995\n,0.000231648\n,0.000252806\n,0.000253901])\n*\/\n\n\/* Timings 2010-01-12 (test2) Time for Start\/Stop of doubley triggered ctr task\n * delay: 472 +- 6 us max: 483 us min: 459 us\n * in git repository (fetch) see commit 43c1803db7fea66082f772afa6f659ebe586da25\n **\na = array([0.000458918\n,0.000482995\n,0.000475334\n,0.000474969\n,0.000468768\n,0.00047424\n,0.000468768\n,0.000476064\n,0.000472416])\n*\/\nint _tmain(int argc, _TCHAR* argv[])\n{ test2();\n}<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n\n\nSlOverlayMenu* MnuMenu;\n\nMenuVars MenuOsd[20];\nMenuVars MnuCache[10];\n\nWCHAR* GroupOpt[] = {L\"\", L\"\"};\nWCHAR* ItemOpt[] = {L\"Off\", L\"On\"};\n\nBOOLEAN MnuInitialized;\nHANDLE MenuProcessHeap;\n\n\/\/Add menu items to menu\n\nVOID\nAddItems()\n{\n MnuMenu->AddGroup(L\"OSD\", GroupOpt, &MenuOsd[0].Var);\n\n if (MenuOsd[0].Var)\n {\n MnuMenu->AddItem(L\"GPU Core utilization\", ItemOpt, &MenuOsd[1].Var);\n MnuMenu->AddItem(L\"GPU Core temperature\", ItemOpt, &MenuOsd[2].Var);\n MnuMenu->AddItem(L\"GPU Engine Clock\", ItemOpt, &MenuOsd[3].Var);\n MnuMenu->AddItem(L\"GPU Memory Clock\", ItemOpt, &MenuOsd[4].Var);\n MnuMenu->AddItem(L\"GPU VRAM usage\", ItemOpt, &MenuOsd[5].Var);\n MnuMenu->AddItem(L\"CPU utilization\", ItemOpt, &MenuOsd[6].Var);\n MnuMenu->AddItem(L\"CPU temperature\", ItemOpt, &MenuOsd[7].Var);\n MnuMenu->AddItem(L\"RAM usage\", ItemOpt, &MenuOsd[8].Var);\n MnuMenu->AddItem(L\"Max core usage\", ItemOpt, &MenuOsd[9].Var);\n MnuMenu->AddItem(L\"Max thread usage\", ItemOpt, &MenuOsd[10].Var);\n MnuMenu->AddItem(L\"Disk read-write rate\", ItemOpt, &MenuOsd[11].Var);\n MnuMenu->AddItem(L\"Disk response time\", ItemOpt, &MenuOsd[12].Var);\n MnuMenu->AddItem(L\"Frame Buffer count\", ItemOpt, &MenuOsd[13].Var);\n MnuMenu->AddItem(L\"Show Time\", ItemOpt, &MenuOsd[14].Var);\n }\n\n MnuMenu->AddGroup(L\"CACHE\", GroupOpt, &MnuCache[0].Var);\n\n if (MnuCache[0].Var)\n {\n MnuMenu->AddItem(L\"NULL\", ItemOpt, &MnuCache[1].Var);\n MnuMenu->AddItem(L\"NULL\", ItemOpt, &MnuCache[2].Var);\n MnuMenu->AddItem(L\"NULL\", ItemOpt, &MnuCache[3].Var);\n MnuMenu->AddItem(L\"NULL\", ItemOpt, &MnuCache[4].Var);\n }\n}\n\n\nVOID\nProcessOptions()\n{\n if (MenuOsd[1].Var > 0)\n PushSharedMemory->OSDFlags |= OSD_GPU_LOAD;\n \/*else\n PushSharedMemory->OSDFlags &= ~OSD_GPU_LOAD;*\/\n \/\/this needs to be fixed, if it was enable by main gui\n \/\/checkbox then it'll get disabled. too lazy...\n\n if (MenuOsd[2].Var > 0)\n PushSharedMemory->OSDFlags |= OSD_GPU_TEMP;\n\n if (MenuOsd[3].Var > 0)\n PushSharedMemory->OSDFlags |= OSD_GPU_E_CLK;\n\n if (MenuOsd[4].Var > 0)\n PushSharedMemory->OSDFlags |= OSD_GPU_M_CLK;\n\n if (MenuOsd[7].Var > 0)\n PushSharedMemory->OSDFlags |= OSD_CPU_TEMP;\n \n if (MenuOsd[9].Var > 0)\n PushSharedMemory->OSDFlags |= OSD_MCU;\n\n if (MenuOsd[10].Var > 0)\n PushSharedMemory->OSDFlags |= OSD_MTU;\n\n if (MenuOsd[11].Var > 0)\n PushSharedMemory->OSDFlags |= OSD_DISK_RWRATE;\n\n if (MenuOsd[12].Var > 0)\n PushSharedMemory->OSDFlags |= OSD_DISK_RESPONSE;\n\n if (MenuOsd[14].Var > 0)\n PushSharedMemory->OSDFlags |= OSD_TIME;\n}\n\n\nVOID\nMnuRender( OvOverlay* Overlay )\n{\n if (!MnuInitialized)\n {\n MnuMenu = new SlOverlayMenu(300);\n MnuInitialized = TRUE;\n }\n\n if( MnuMenu->mSet.MaxItems == 0 )\n AddItems();\n\n \/\/Call drawing and navigation functions\n MnuMenu->Render(100, 200, Overlay);\n}\n\n\n#define GROUP 1\n#define ITEM 2\n#define HEIGHT 16\n\n\nDWORD LightBlue = 0xFF4DD0EB;\nDWORD Green = 0xFF33FF00;\nDWORD White = 0xFFE6E6E6;\nDWORD Blue = 0xFF00A4C5;\n\nWNDPROC OldWNDPROC;\nSlOverlayMenu* OvmMenu;\n\n\nVOID\nMenuKeyboardHook( WPARAM Key )\n{\n switch( Key )\n {\n case VK_INSERT:\n OvmMenu->mSet.Show = !OvmMenu->mSet.Show;\n break;\n \n case VK_UP:\n {\n if (!OvmMenu->mSet.Show)\n break;\n\n OvmMenu->mSet.SeletedIndex--;\n \n if (OvmMenu->mSet.SeletedIndex < 0)\n OvmMenu->mSet.SeletedIndex = OvmMenu->mSet.MaxItems - 1;\n\n } break;\n\n case VK_DOWN:\n {\n if (!OvmMenu->mSet.Show)\n break;\n\n OvmMenu->mSet.SeletedIndex++;\n \n if (OvmMenu->mSet.SeletedIndex == OvmMenu->mSet.MaxItems)\n OvmMenu->mSet.SeletedIndex = 0;\n\n } break;\n\n case VK_LEFT:\n {\n if (!OvmMenu->mSet.Show)\n break;\n\n if (OvmMenu->Items[OvmMenu->mSet.SeletedIndex].Var && *OvmMenu->Items[OvmMenu->mSet.SeletedIndex].Var > 0)\n {\n *OvmMenu->Items[OvmMenu->mSet.SeletedIndex].Var += -1;\n \n if (OvmMenu->Items[OvmMenu->mSet.SeletedIndex].Type == GROUP)\n OvmMenu->mSet.MaxItems = 0;\n }\n\n } break;\n\n case VK_RIGHT:\n {\n if (!OvmMenu->mSet.Show)\n break;\n\n if (OvmMenu->Items[OvmMenu->mSet.SeletedIndex].Var \n && *OvmMenu->Items[OvmMenu->mSet.SeletedIndex].Var < (OvmMenu->Items[OvmMenu->mSet.SeletedIndex].MaxValue - 1))\n {\n *OvmMenu->Items[OvmMenu->mSet.SeletedIndex].Var += 1;\n\n if (OvmMenu->Items[OvmMenu->mSet.SeletedIndex].Type == GROUP)\n OvmMenu->mSet.MaxItems = 0;\n }\n\n\n } break;\n }\n\n \/\/ Update osd items.\n ProcessOptions();\n}\n\n\nSlOverlayMenu::SlOverlayMenu( int OptionsX )\n{\n OpX = OptionsX;\n \n mSet.Show = FALSE;\n mSet.MaxItems = 0;\n mSet.SeletedIndex = 0;\n \n OvmMenu = this;\n MenuProcessHeap = GetProcessHeap();\n}\n\n\nvoid SlOverlayMenu::AddItemToMenu(WCHAR* Title, WCHAR** Options, int* Var, int MaxValue, int Type)\n{\n Items[mSet.MaxItems].Title = Title;\n Items[mSet.MaxItems].Options= Options;\n Items[mSet.MaxItems].Var = Var;\n Items[mSet.MaxItems].MaxValue = MaxValue;\n Items[mSet.MaxItems].Type = Type;\n mSet.MaxItems++;\n}\n\n\nVOID \nSlOverlayMenu::Render( int X, int Y, OvOverlay* Overlay )\n{\n DWORD ColorOne, ColorTwo;\n int ValueOne, ValueTwo;\n\n if (!mSet.Show)\n return;\n\n for (int i = 0; i < mSet.MaxItems; i++)\n {\n ValueOne = (Items[i].Var) ? (*Items[i].Var) : 0;\n ValueTwo = (Items[i].Var) ? (*Items[i].Var) : 0;\n\n if (i == mSet.SeletedIndex)\n {\n ColorOne = LightBlue;\n ColorTwo = (ValueTwo) ? Green : White;\n }\n else if (Items[i].Type == GROUP)\n {\n ColorOne = Blue;\n ColorTwo = Blue;\n }\n else\n {\n ColorOne = (ValueOne) ? White : White;\n ColorTwo = (ValueTwo) ? Green : White;\n }\n\n if (Items[i].Type == GROUP)\n Overlay->DrawText(Items[i].Title, X, Y, ColorOne);\n\n if (Items[i].Type == ITEM)\n Overlay->DrawText(Items[i].Title, X + 20, Y, ColorOne);\n\n if (Items[i].Options)\n Overlay->DrawText(Items[i].Options[ValueTwo], OpX, Y, ColorTwo);\n\n Y += HEIGHT;\n }\n}\nfixed ram usage menu item#include \n#include \n#include \n#include \n\n\nSlOverlayMenu* MnuMenu;\n\nMenuVars MenuOsd[20];\nMenuVars MnuCache[10];\n\nWCHAR* GroupOpt[] = {L\"\", L\"\"};\nWCHAR* ItemOpt[] = {L\"Off\", L\"On\"};\n\nBOOLEAN MnuInitialized;\nHANDLE MenuProcessHeap;\n\n\/\/Add menu items to menu\n\nVOID\nAddItems()\n{\n MnuMenu->AddGroup(L\"OSD\", GroupOpt, &MenuOsd[0].Var);\n\n if (MenuOsd[0].Var)\n {\n MnuMenu->AddItem(L\"GPU Core utilization\", ItemOpt, &MenuOsd[1].Var);\n MnuMenu->AddItem(L\"GPU Core temperature\", ItemOpt, &MenuOsd[2].Var);\n MnuMenu->AddItem(L\"GPU Engine Clock\", ItemOpt, &MenuOsd[3].Var);\n MnuMenu->AddItem(L\"GPU Memory Clock\", ItemOpt, &MenuOsd[4].Var);\n MnuMenu->AddItem(L\"GPU VRAM usage\", ItemOpt, &MenuOsd[5].Var);\n MnuMenu->AddItem(L\"CPU utilization\", ItemOpt, &MenuOsd[6].Var);\n MnuMenu->AddItem(L\"CPU temperature\", ItemOpt, &MenuOsd[7].Var);\n MnuMenu->AddItem(L\"RAM usage\", ItemOpt, &MenuOsd[8].Var);\n MnuMenu->AddItem(L\"Max core usage\", ItemOpt, &MenuOsd[9].Var);\n MnuMenu->AddItem(L\"Max thread usage\", ItemOpt, &MenuOsd[10].Var);\n MnuMenu->AddItem(L\"Disk read-write rate\", ItemOpt, &MenuOsd[11].Var);\n MnuMenu->AddItem(L\"Disk response time\", ItemOpt, &MenuOsd[12].Var);\n MnuMenu->AddItem(L\"Frame Buffer count\", ItemOpt, &MenuOsd[13].Var);\n MnuMenu->AddItem(L\"Show Time\", ItemOpt, &MenuOsd[14].Var);\n }\n\n MnuMenu->AddGroup(L\"CACHE\", GroupOpt, &MnuCache[0].Var);\n\n if (MnuCache[0].Var)\n {\n MnuMenu->AddItem(L\"NULL\", ItemOpt, &MnuCache[1].Var);\n MnuMenu->AddItem(L\"NULL\", ItemOpt, &MnuCache[2].Var);\n MnuMenu->AddItem(L\"NULL\", ItemOpt, &MnuCache[3].Var);\n MnuMenu->AddItem(L\"NULL\", ItemOpt, &MnuCache[4].Var);\n }\n}\n\n\nVOID\nProcessOptions()\n{\n if (MenuOsd[1].Var > 0)\n PushSharedMemory->OSDFlags |= OSD_GPU_LOAD;\n \/*else\n PushSharedMemory->OSDFlags &= ~OSD_GPU_LOAD;*\/\n \/\/this needs to be fixed, if it was enable by main gui\n \/\/checkbox then it'll get disabled. too lazy...\n\n if (MenuOsd[2].Var > 0)\n PushSharedMemory->OSDFlags |= OSD_GPU_TEMP;\n\n if (MenuOsd[3].Var > 0)\n PushSharedMemory->OSDFlags |= OSD_GPU_E_CLK;\n\n if (MenuOsd[4].Var > 0)\n PushSharedMemory->OSDFlags |= OSD_GPU_M_CLK;\n\n if (MenuOsd[7].Var > 0)\n PushSharedMemory->OSDFlags |= OSD_CPU_TEMP;\n\n if (MenuOsd[8].Var > 0)\n PushSharedMemory->OSDFlags |= OSD_RAM;\n \n if (MenuOsd[9].Var > 0)\n PushSharedMemory->OSDFlags |= OSD_MCU;\n\n if (MenuOsd[10].Var > 0)\n PushSharedMemory->OSDFlags |= OSD_MTU;\n\n if (MenuOsd[11].Var > 0)\n PushSharedMemory->OSDFlags |= OSD_DISK_RWRATE;\n\n if (MenuOsd[12].Var > 0)\n PushSharedMemory->OSDFlags |= OSD_DISK_RESPONSE;\n\n if (MenuOsd[14].Var > 0)\n PushSharedMemory->OSDFlags |= OSD_TIME;\n}\n\n\nVOID\nMnuRender( OvOverlay* Overlay )\n{\n if (!MnuInitialized)\n {\n MnuMenu = new SlOverlayMenu(300);\n MnuInitialized = TRUE;\n }\n\n if( MnuMenu->mSet.MaxItems == 0 )\n AddItems();\n\n \/\/Call drawing and navigation functions\n MnuMenu->Render(100, 200, Overlay);\n}\n\n\n#define GROUP 1\n#define ITEM 2\n#define HEIGHT 16\n\n\nDWORD LightBlue = 0xFF4DD0EB;\nDWORD Green = 0xFF33FF00;\nDWORD White = 0xFFE6E6E6;\nDWORD Blue = 0xFF00A4C5;\n\nWNDPROC OldWNDPROC;\nSlOverlayMenu* OvmMenu;\n\n\nVOID\nMenuKeyboardHook( WPARAM Key )\n{\n switch( Key )\n {\n case VK_INSERT:\n OvmMenu->mSet.Show = !OvmMenu->mSet.Show;\n break;\n \n case VK_UP:\n {\n if (!OvmMenu->mSet.Show)\n break;\n\n OvmMenu->mSet.SeletedIndex--;\n \n if (OvmMenu->mSet.SeletedIndex < 0)\n OvmMenu->mSet.SeletedIndex = OvmMenu->mSet.MaxItems - 1;\n\n } break;\n\n case VK_DOWN:\n {\n if (!OvmMenu->mSet.Show)\n break;\n\n OvmMenu->mSet.SeletedIndex++;\n \n if (OvmMenu->mSet.SeletedIndex == OvmMenu->mSet.MaxItems)\n OvmMenu->mSet.SeletedIndex = 0;\n\n } break;\n\n case VK_LEFT:\n {\n if (!OvmMenu->mSet.Show)\n break;\n\n if (OvmMenu->Items[OvmMenu->mSet.SeletedIndex].Var && *OvmMenu->Items[OvmMenu->mSet.SeletedIndex].Var > 0)\n {\n *OvmMenu->Items[OvmMenu->mSet.SeletedIndex].Var += -1;\n \n if (OvmMenu->Items[OvmMenu->mSet.SeletedIndex].Type == GROUP)\n OvmMenu->mSet.MaxItems = 0;\n }\n\n } break;\n\n case VK_RIGHT:\n {\n if (!OvmMenu->mSet.Show)\n break;\n\n if (OvmMenu->Items[OvmMenu->mSet.SeletedIndex].Var \n && *OvmMenu->Items[OvmMenu->mSet.SeletedIndex].Var < (OvmMenu->Items[OvmMenu->mSet.SeletedIndex].MaxValue - 1))\n {\n *OvmMenu->Items[OvmMenu->mSet.SeletedIndex].Var += 1;\n\n if (OvmMenu->Items[OvmMenu->mSet.SeletedIndex].Type == GROUP)\n OvmMenu->mSet.MaxItems = 0;\n }\n\n\n } break;\n }\n\n \/\/ Update osd items.\n ProcessOptions();\n}\n\n\nSlOverlayMenu::SlOverlayMenu( int OptionsX )\n{\n OpX = OptionsX;\n \n mSet.Show = FALSE;\n mSet.MaxItems = 0;\n mSet.SeletedIndex = 0;\n \n OvmMenu = this;\n MenuProcessHeap = GetProcessHeap();\n}\n\n\nvoid SlOverlayMenu::AddItemToMenu(WCHAR* Title, WCHAR** Options, int* Var, int MaxValue, int Type)\n{\n Items[mSet.MaxItems].Title = Title;\n Items[mSet.MaxItems].Options= Options;\n Items[mSet.MaxItems].Var = Var;\n Items[mSet.MaxItems].MaxValue = MaxValue;\n Items[mSet.MaxItems].Type = Type;\n mSet.MaxItems++;\n}\n\n\nVOID \nSlOverlayMenu::Render( int X, int Y, OvOverlay* Overlay )\n{\n DWORD ColorOne, ColorTwo;\n int ValueOne, ValueTwo;\n\n if (!mSet.Show)\n return;\n\n for (int i = 0; i < mSet.MaxItems; i++)\n {\n ValueOne = (Items[i].Var) ? (*Items[i].Var) : 0;\n ValueTwo = (Items[i].Var) ? (*Items[i].Var) : 0;\n\n if (i == mSet.SeletedIndex)\n {\n ColorOne = LightBlue;\n ColorTwo = (ValueTwo) ? Green : White;\n }\n else if (Items[i].Type == GROUP)\n {\n ColorOne = Blue;\n ColorTwo = Blue;\n }\n else\n {\n ColorOne = (ValueOne) ? White : White;\n ColorTwo = (ValueTwo) ? Green : White;\n }\n\n if (Items[i].Type == GROUP)\n Overlay->DrawText(Items[i].Title, X, Y, ColorOne);\n\n if (Items[i].Type == ITEM)\n Overlay->DrawText(Items[i].Title, X + 20, Y, ColorOne);\n\n if (Items[i].Options)\n Overlay->DrawText(Items[i].Options[ValueTwo], OpX, Y, ColorTwo);\n\n Y += HEIGHT;\n }\n}\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: sysplug.cxx,v $\n *\n * $Revision: 1.4 $\n *\n * last change: $Author: vg $ $Date: 2007-12-07 11:52:36 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n#include \n\n#include \n#include \n#include \n#include \n\n#include \n\nint MacPluginComm::nConnCounter = 0;\n\nMacPluginComm::MacPluginComm(\n const String& mimetype,\n const String& library,\n NSView* aParent,\n int nDescriptor1,\n int nDescriptor2\n ) :\nPluginComm( ::rtl::OUStringToOString( library, osl_getThreadTextEncoding() ) )\/*,\nPluginConnector( nDescriptor2 )*\/\n{\n \/\/char pDesc[32];\n\/\/ char pWindow[32];\n\/\/ sprintf( pWindow, \"%d\", aParent );\n\/\/ sprintf( pDesc, \"%d\", nDescriptor1 );\n\/\/ ByteString aLib( library, osl_getThreadTextEncoding() );\n\/\/\n\/\/ char* pArgs[5];\n\/\/ pArgs[0] = \"pluginapp.bin\";\n\/\/ pArgs[1] = pDesc;\n\/\/ pArgs[2] = const_cast(aLib.GetBuffer());\n\/\/ pArgs[3] = pWindow;\n\/\/ pArgs[4] = NULL;\n\/\/\n\/\/#if OSL_DEBUG_LEVEL > 1\n\/\/ m_nCommPID = 10;\n\/\/ fprintf( stderr, \"Try to launch: %s %s %s %s, descriptors are %d, %d\\n\", pArgs[0], pArgs[1], pArgs[2], pArgs[3], nDescriptor1, nDescriptor2 );\n\/\/#endif\n\/\/\n\/\/ if( ! ( m_nCommPID = fork() ) )\n\/\/ {\n\/\/ execvp( pArgs[0], pArgs );\n\/\/ fprintf( stderr, \"Error: could not exec %s\\n\", pArgs[0] );\n\/\/ _exit(255);\n\/\/ }\n\/\/\n\/\/ if( m_nCommPID != -1 )\n\/\/ {\n\/\/ \/\/ wait for pluginapp.bin to start up\n\/\/ if( ! WaitForMessage( 5000 ) )\n\/\/ {\n\/\/ fprintf( stderr, \"Timeout on command: %s %s %s %s\\n\", pArgs[0], pArgs[1], pArgs[2], pArgs[3] );\n\/\/ invalidate();\n\/\/ }\n\/\/ else\n\/\/ {\n\/\/ MediatorMessage* pMessage = GetNextMessage( TRUE );\n\/\/ Respond( pMessage->m_nID,\n\/\/ \"init ack\",8,\n\/\/ NULL );\n\/\/ delete pMessage;\n\/\/ NPP_Initialize();\n\/\/ }\n\/\/ }\n}\n\nMacPluginComm::~MacPluginComm()\n{\n NPP_Shutdown();\n if( m_nCommPID != -1 && m_nCommPID != 0 )\n {\n int status = 16777216;\n pid_t nExit = waitpid( m_nCommPID, &status, WUNTRACED );\n#if OSL_DEBUG_LEVEL > 1\n fprintf( stderr, \"child %d (plugin app child %d) exited with status %d\\n\", nExit, m_nCommPID, WEXITSTATUS(status) );\n#endif\n }\n}\n\nNPError MacPluginComm::NPP_Destroy( NPP instance,\n NPSavedData** save )\n{\n return 0;\n}\n\nNPError MacPluginComm::NPP_DestroyStream( NPP instance,\n NPStream* stream,\n NPError reason )\n{\n return 0;\n}\n\nvoid* MacPluginComm::NPP_GetJavaClass()\n{\n return 0;\n}\n\nNPError MacPluginComm::NPP_Initialize()\n{\n return 0;\n}\n\nNPError MacPluginComm::NPP_New( NPMIMEType pluginType,\n NPP instance,\n uint16 mode,\n int16 argc,\n char* argn[],\n char* argv[],\n NPSavedData *saved )\n{\n return 0;\n}\n\nNPError MacPluginComm::NPP_NewStream( NPP instance,\n NPMIMEType type,\n NPStream* stream,\n NPBool seekable,\n uint16* stype )\n{\n return 0;\n}\n\nvoid MacPluginComm::NPP_Print( NPP instance,\n NPPrint* platformPrint )\n{\n\n}\n\nNPError MacPluginComm::NPP_SetWindow( NPP instance,\n NPWindow* window )\n{\n return 0;\n}\n\nvoid MacPluginComm::NPP_Shutdown()\n{\n\n}\n\nvoid MacPluginComm::NPP_StreamAsFile( NPP instance,\n NPStream* stream,\n const char* fname )\n{\n\n}\n\nvoid MacPluginComm::NPP_URLNotify( NPP instance,\n const char* url,\n NPReason reason,\n void* notifyData )\n{\n\n}\n\nint32 MacPluginComm::NPP_Write( NPP instance,\n NPStream* stream,\n int32 offset,\n int32 len,\n void* buffer )\n{\n return 0;\n}\n\nint32 MacPluginComm::NPP_WriteReady( NPP instance,\n NPStream* stream )\n{\n return 0;\n}\n\nchar* MacPluginComm::NPP_GetMIMEDescription()\n{\n return \"\";\n}\n\nNPError MacPluginComm::NPP_GetValue( NPP instance, NPPVariable variable, void* value )\n{\n return 0;\n}\n\nNPError MacPluginComm::NPP_SetValue( NPP instance,\n NPNVariable variable,\n void *value)\n{\n return 0;\n}\n\nINTEGRATION: CWS wae4extensions (1.2.44); FILE MERGED 2008\/01\/09 21:11:08 ericb 1.2.44.4: RESYNC: (1.3-1.4); FILE MERGED 2007\/10\/04 21:36:52 ericb 1.2.44.3: #i81612# add a better fix for warning in sysplug.cxx 2007\/10\/04 15:19:14 ericb 1.2.44.2: #i81612# fix warning on Mac OS X Aqua 2007\/10\/03 12:45:23 ericb 1.2.44.1: #i81612# fix warning because of bad type in aqua mozilla plugin\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: sysplug.cxx,v $\n *\n * $Revision: 1.5 $\n *\n * last change: $Author: ihi $ $Date: 2008-01-14 14:49:48 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n#include \n\n#include \n#include \n#include \n#include \n\n#include \n\nint MacPluginComm::nConnCounter = 0;\n\nMacPluginComm::MacPluginComm(\n const String& mimetype,\n const String& library,\n NSView* aParent,\n int nDescriptor1,\n int nDescriptor2\n ) :\nPluginComm( ::rtl::OUStringToOString( library, osl_getThreadTextEncoding() ) )\/*,\nPluginConnector( nDescriptor2 )*\/\n{\n \/\/char pDesc[32];\n\/\/ char pWindow[32];\n\/\/ sprintf( pWindow, \"%d\", aParent );\n\/\/ sprintf( pDesc, \"%d\", nDescriptor1 );\n\/\/ ByteString aLib( library, osl_getThreadTextEncoding() );\n\/\/\n\/\/ char* pArgs[5];\n\/\/ pArgs[0] = \"pluginapp.bin\";\n\/\/ pArgs[1] = pDesc;\n\/\/ pArgs[2] = const_cast(aLib.GetBuffer());\n\/\/ pArgs[3] = pWindow;\n\/\/ pArgs[4] = NULL;\n\/\/\n\/\/#if OSL_DEBUG_LEVEL > 1\n\/\/ m_nCommPID = 10;\n\/\/ fprintf( stderr, \"Try to launch: %s %s %s %s, descriptors are %d, %d\\n\", pArgs[0], pArgs[1], pArgs[2], pArgs[3], nDescriptor1, nDescriptor2 );\n\/\/#endif\n\/\/\n\/\/ if( ! ( m_nCommPID = fork() ) )\n\/\/ {\n\/\/ execvp( pArgs[0], pArgs );\n\/\/ fprintf( stderr, \"Error: could not exec %s\\n\", pArgs[0] );\n\/\/ _exit(255);\n\/\/ }\n\/\/\n\/\/ if( m_nCommPID != -1 )\n\/\/ {\n\/\/ \/\/ wait for pluginapp.bin to start up\n\/\/ if( ! WaitForMessage( 5000 ) )\n\/\/ {\n\/\/ fprintf( stderr, \"Timeout on command: %s %s %s %s\\n\", pArgs[0], pArgs[1], pArgs[2], pArgs[3] );\n\/\/ invalidate();\n\/\/ }\n\/\/ else\n\/\/ {\n\/\/ MediatorMessage* pMessage = GetNextMessage( TRUE );\n\/\/ Respond( pMessage->m_nID,\n\/\/ \"init ack\",8,\n\/\/ NULL );\n\/\/ delete pMessage;\n\/\/ NPP_Initialize();\n\/\/ }\n\/\/ }\n}\n\nMacPluginComm::~MacPluginComm()\n{\n NPP_Shutdown();\n if( m_nCommPID != -1 && m_nCommPID != 0 )\n {\n int status = 16777216;\n#if OSL_DEBUG_LEVEL > 1\n pid_t nExit = waitpid( m_nCommPID, &status, WUNTRACED );\n fprintf( stderr, \"child %d (plugin app child %d) exited with status %d\\n\", nExit, m_nCommPID, WEXITSTATUS(status) );\n#else\n waitpid( m_nCommPID, &status, WUNTRACED );\n#endif\n }\n}\n\nNPError MacPluginComm::NPP_Destroy( NPP instance,\n NPSavedData** save )\n{\n return 0;\n}\n\nNPError MacPluginComm::NPP_DestroyStream( NPP instance,\n NPStream* stream,\n NPError reason )\n{\n return 0;\n}\n\nvoid* MacPluginComm::NPP_GetJavaClass()\n{\n return 0;\n}\n\nNPError MacPluginComm::NPP_Initialize()\n{\n return 0;\n}\n\nNPError MacPluginComm::NPP_New( NPMIMEType pluginType,\n NPP instance,\n uint16 mode,\n int16 argc,\n char* argn[],\n char* argv[],\n NPSavedData *saved )\n{\n return 0;\n}\n\nNPError MacPluginComm::NPP_NewStream( NPP instance,\n NPMIMEType type,\n NPStream* stream,\n NPBool seekable,\n uint16* stype )\n{\n return 0;\n}\n\nvoid MacPluginComm::NPP_Print( NPP instance,\n NPPrint* platformPrint )\n{\n\n}\n\nNPError MacPluginComm::NPP_SetWindow( NPP instance,\n NPWindow* window )\n{\n return 0;\n}\n\nvoid MacPluginComm::NPP_Shutdown()\n{\n\n}\n\nvoid MacPluginComm::NPP_StreamAsFile( NPP instance,\n NPStream* stream,\n const char* fname )\n{\n\n}\n\nvoid MacPluginComm::NPP_URLNotify( NPP instance,\n const char* url,\n NPReason reason,\n void* notifyData )\n{\n\n}\n\nint32 MacPluginComm::NPP_Write( NPP instance,\n NPStream* stream,\n int32 offset,\n int32 len,\n void* buffer )\n{\n return 0;\n}\n\nint32 MacPluginComm::NPP_WriteReady( NPP instance,\n NPStream* stream )\n{\n return 0;\n}\n\nchar* MacPluginComm::NPP_GetMIMEDescription()\n{\n return \"\";\n}\n\nNPError MacPluginComm::NPP_GetValue( NPP instance, NPPVariable variable, void* value )\n{\n return 0;\n}\n\nNPError MacPluginComm::NPP_SetValue( NPP instance,\n NPNVariable variable,\n void *value)\n{\n return 0;\n}\n\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2017 ASMlover. All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions\n\/\/ are met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright\n\/\/ notice, this list ofconditions and the following disclaimer.\n\/\/\n\/\/ * Redistributions in binary form must reproduce the above copyright\n\/\/ notice, this list of conditions and the following disclaimer in\n\/\/ the documentation and\/or other materialsprovided with the\n\/\/ distribution.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\/\/ \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n\/\/ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n\/\/ FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n\/\/ COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n\/\/ INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n\/\/ BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n\/\/ LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n\/\/ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n\/\/ LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n\/\/ ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n\/\/ POSSIBILITY OF SUCH DAMAGE.\n#include \n#include \n\nCHAOS_TEST(ColorIO, Chaos::FakeTester) {\n namespace cc = ::Chaos::ColorIO;\n\n cc::fprintf(stdout,\n cc::ColorType::COLORTYPE_GREEN,\n \"Chaos::ColorIO unittest - green information with `fprintf`\\n\");\n cc::printf(cc::ColorType::COLORTYPE_GREEN,\n \"Chaos::ColorIO unittest - green information with `printf`\\n\");\n cc::fprintf(stdout,\n cc::ColorType::COLORTYPE_RED,\n \"Chaos::ColorIO unittest - red information with `fprintf`\\n\");\n cc::printf(cc::ColorType::COLORTYPE_RED,\n \"Chaos::ColorIO unittest - red information with `printf`\\n\");\n}\n:construction: test(colorio): updated the unittest for colorio\/\/ Copyright (c) 2017 ASMlover. All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions\n\/\/ are met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright\n\/\/ notice, this list ofconditions and the following disclaimer.\n\/\/\n\/\/ * Redistributions in binary form must reproduce the above copyright\n\/\/ notice, this list of conditions and the following disclaimer in\n\/\/ the documentation and\/or other materialsprovided with the\n\/\/ distribution.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\/\/ \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n\/\/ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n\/\/ FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n\/\/ COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n\/\/ INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n\/\/ BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n\/\/ LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n\/\/ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n\/\/ LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n\/\/ ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n\/\/ POSSIBILITY OF SUCH DAMAGE.\n#include \n#include \n\nCHAOS_TEST(ColorIO, Chaos::FakeTester) {\n namespace cc = ::Chaos::ColorIO;\n\n cc::printf(cc::ColorType::COLORTYPE_RED,\n \"Chaos::ColorIO unittest - red information with `printf`\\n\");\n cc::printf(cc::ColorType::COLORTYPE_LIGHTRED,\n \"Chaos::ColorIO unittest - light red information with `printf`\\n\");\n cc::printf(cc::ColorType::COLORTYPE_GREEN,\n \"Chaos::ColorIO unittest - green information with `printf`\\n\");\n cc::printf(cc::ColorType::COLORTYPE_LIGHTGREEN,\n \"Chaos::ColorIO unittest - light green information with `printf`\\n\");\n cc::printf(cc::ColorType::COLORTYPE_YELLOW,\n \"Chaos::ColorIO unittest - yellow information with `printf`\\n\");\n cc::printf(cc::ColorType::COLORTYPE_LIGHTYELLOW,\n \"Chaos::ColorIO unittest - light yellow information with `printf`\\n\");\n cc::printf(cc::ColorType::COLORTYPE_BLUE,\n \"Chaos::ColorIO unittest - blue information with `printf`\\n\");\n cc::printf(cc::ColorType::COLORTYPE_LIGHTBLUE,\n \"Chaos::ColorIO unittest - light blue information with `printf`\\n\");\n cc::printf(cc::ColorType::COLORTYPE_MAGENTA,\n \"Chaos::ColorIO unittest - magenta information with `printf`\\n\");\n cc::printf(cc::ColorType::COLORTYPE_LIGHTMAGENTA,\n \"Chaos::ColorIO unittest - light magenta information with `printf`\\n\");\n cc::printf(cc::ColorType::COLORTYPE_CYAN,\n \"Chaos::ColorIO unittest - cyan information with `printf`\\n\");\n cc::printf(cc::ColorType::COLORTYPE_LIGHTCYAN,\n \"Chaos::ColorIO unittest - light cyan information with `printf`\\n\");\n cc::printf(cc::ColorType::COLORTYPE_WHITE,\n \"Chaos::ColorIO unittest - white information with `printf`\\n\");\n cc::printf(cc::ColorType::COLORTYPE_LIGHTWHITE,\n \"Chaos::ColorIO unittest - light white information with `printf`\\n\");\n\n cc::fprintf(stdout, cc::ColorType::COLORTYPE_RED,\n \"Chaos::ColorIO unittest - red information with `fprintf`\\n\");\n cc::fprintf(stdout, cc::ColorType::COLORTYPE_LIGHTRED,\n \"Chaos::ColorIO unittest - light red information with `fprintf`\\n\");\n cc::fprintf(stdout, cc::ColorType::COLORTYPE_GREEN,\n \"Chaos::ColorIO unittest - green information with `fprintf`\\n\");\n cc::fprintf(stdout, cc::ColorType::COLORTYPE_LIGHTGREEN,\n \"Chaos::ColorIO unittest - light green information with `fprintf`\\n\");\n cc::fprintf(stdout, cc::ColorType::COLORTYPE_YELLOW,\n \"Chaos::ColorIO unittest - yellow information with `fprintf`\\n\");\n cc::fprintf(stdout, cc::ColorType::COLORTYPE_LIGHTYELLOW,\n \"Chaos::ColorIO unittest - light yellow information with `fprintf`\\n\");\n cc::fprintf(stdout, cc::ColorType::COLORTYPE_BLUE,\n \"Chaos::ColorIO unittest - blue information with `fprintf`\\n\");\n cc::fprintf(stdout, cc::ColorType::COLORTYPE_LIGHTBLUE,\n \"Chaos::ColorIO unittest - light blue information with `fprintf`\\n\");\n cc::fprintf(stdout, cc::ColorType::COLORTYPE_MAGENTA,\n \"Chaos::ColorIO unittest - magenta information with `fprintf`\\n\");\n cc::fprintf(stdout, cc::ColorType::COLORTYPE_LIGHTMAGENTA,\n \"Chaos::ColorIO unittest - light magenta information with `fprintf`\\n\");\n cc::fprintf(stdout, cc::ColorType::COLORTYPE_CYAN,\n \"Chaos::ColorIO unittest - cyan information with `fprintf`\\n\");\n cc::fprintf(stdout, cc::ColorType::COLORTYPE_LIGHTCYAN,\n \"Chaos::ColorIO unittest - light cyan information with `fprintf`\\n\");\n cc::fprintf(stdout, cc::ColorType::COLORTYPE_WHITE,\n \"Chaos::ColorIO unittest - white information with `fprintf`\\n\");\n cc::fprintf(stdout, cc::ColorType::COLORTYPE_LIGHTWHITE,\n \"Chaos::ColorIO unittest - light white information with `fprintf`\\n\");\n}\n<|endoftext|>"} {"text":"\/\/ This file is a part of the OpenSurgSim project.\n\/\/ Copyright 2015, SimQuest Solutions Inc.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \"SurgSim\/Devices\/Oculus\/OculusScaffold.h\"\n\n#include \n#include \n#include \n#include \n\n#include \n#if 6 == OVR_MAJOR_VERSION\n#include \n#elif 5 == OVR_MAJOR_VERSION\n#include \n#endif\n\n#include \"SurgSim\/DataStructures\/DataGroup.h\"\n#include \"SurgSim\/DataStructures\/DataGroupBuilder.h\"\n#include \"SurgSim\/Devices\/Oculus\/OculusDevice.h\"\n#include \"SurgSim\/Framework\/Log.h\"\n#include \"SurgSim\/Framework\/SharedInstance.h\"\n#include \"SurgSim\/Math\/Quaternion.h\"\n#include \"SurgSim\/Math\/RigidTransform.h\"\n\nusing SurgSim::DataStructures::DataGroup;\nusing SurgSim::DataStructures::DataGroupBuilder;\nusing SurgSim::Framework::Logger;\nusing SurgSim::Math::makeRigidTransform;\nusing SurgSim::Math::Quaterniond;\nusing SurgSim::Math::RigidTransform3d;\nusing SurgSim::Math::Vector3d;\n\nnamespace SurgSim\n{\nnamespace Devices\n{\n\nstruct OculusScaffold::DeviceData\n{\n\t\/\/\/ Constructor\n\t\/\/\/ \\param device Device to be wrapped\n\texplicit DeviceData(OculusDevice* device) :\n\t\tdeviceObject(device),\n\t\thandle(nullptr)\n\t{\n#if 6 == OVR_MAJOR_VERSION\n\t\tovrHmd_Create(0, &handle);\n#elif 5 == OVR_MAJOR_VERSION\n\t\thandle = ovrHmd_Create(0);\n#endif\n\t}\n\n\t~DeviceData()\n\t{\n\t\tif (handle != nullptr)\n\t\t{\n\t\t\tovrHmd_Destroy(handle);\n\t\t}\n\t}\n\n\t\/\/\/ The device object wrapped in this class.\n\tOculusDevice* const deviceObject;\n\n\t\/\/\/ Device handle\n\tovrHmd handle;\n};\n\nstruct OculusScaffold::StateData\n{\n\t\/\/\/ List of registered devices.\n\tstd::list> registeredDevices;\n\n\t\/\/\/ The mutex that protects the list of registered devices.\n\tboost::mutex mutex;\n};\n\nOculusScaffold::OculusScaffold() :\n\tFramework::BasicThread(\"OculusScaffold\"),\n\tm_logger(Logger::getLogger(\"Devices\/Oculus\")),\n\tm_state(new StateData)\n{\n\tSURGSIM_LOG_DEBUG(m_logger) << \"Oculus: Shared scaffold created.\";\n\n\t\/\/ Oculus DK2 tracks Gyroscope, Accelerometer, Magnetometer at 1000Hz and\n\t\/\/ positional tracking is done at 60Hz.\n\tsetRate(1000.0);\n\n}\n\nOculusScaffold::~OculusScaffold()\n{\n\tovr_Shutdown();\n}\n\nbool OculusScaffold::registerDevice(OculusDevice* device)\n{\n\tbool success = true;\n\tif (!isRunning())\n\t{\n\t\tstd::shared_ptr barrier = std::make_shared(2);\n\t\tstart(barrier);\n\t\tbarrier->wait(true); \/\/ Wait for initialize\n\t\tbarrier->wait(true); \/\/ Wait for startup\n\t\tsuccess = isInitialized();\n\t}\n\n\tif (success)\n\t{\n\t\tboost::lock_guard lock(m_state->mutex);\n\t\tconst std::string deviceName = device->getName();\n\t\tauto sameName = [&deviceName](const std::unique_ptr& info)\n\t\t{\n\t\t\treturn info->deviceObject->getName() == deviceName;\n\t\t};\n\t\tauto found = std::find_if(m_state->registeredDevices.cbegin(), m_state->registeredDevices.cend(), sameName);\n\n\t\tif (found == m_state->registeredDevices.end())\n\t\t{\n\t\t\tstd::unique_ptr info(new DeviceData(device));\n\t\t\tsuccess = doRegisterDevice(info.get());\n\t\t\tif (success)\n\t\t\t{\n\t\t\t\tSURGSIM_LOG_INFO(m_logger) << \"Device \" << device->getName() << \": Registered\";\n\t\t\t\tm_state->registeredDevices.emplace_back(std::move(info));\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tSURGSIM_LOG_SEVERE(m_logger) << \"Tried to register a device when the same name, '\" <<\n\t\t\t\tdevice->getName() << \"', is already present!\";\n\t\t\tsuccess = false;\n\t\t}\n\t}\n\n\treturn success;\n}\n\nbool OculusScaffold::doRegisterDevice(DeviceData* info)\n{\n\tif (ovrHmd_Detect() < 1)\n\t{\n\t\tSURGSIM_LOG_SEVERE(m_logger) << \"No available Oculus device detected.\";\n\t\treturn false;\n\t}\n\n\tif (m_state->registeredDevices.size() > 0)\n\t{\n\t\tSURGSIM_LOG_SEVERE(m_logger)\n\t\t\t<< \"There is one registered Oculus device already. OculusScaffold only supports one device right now\";\n\t\treturn false;\n\t}\n\n\tif (info->handle == nullptr)\n\t{\n\t\tSURGSIM_LOG_SEVERE(m_logger) << \"Failed to obtain a handle to Oculus Device. Is an Oculus device plugged in?\";\n\t\treturn false;\n\t}\n\n#if 6 == OVR_MAJOR_VERSION\n\tif (ovrSuccess != ovrHmd_ConfigureTracking(info->handle, ovrTrackingCap_Orientation |\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t ovrTrackingCap_MagYawCorrection |\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t ovrTrackingCap_Position, 0))\n#elif 5 == OVR_MAJOR_VERSION\n\tif (ovrTrue != ovrHmd_ConfigureTracking(info->handle, ovrTrackingCap_Orientation |\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t ovrTrackingCap_MagYawCorrection |\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t ovrTrackingCap_Position, 0))\n#endif\n\t{\n\t\tSURGSIM_LOG_SEVERE(m_logger) << \"Failed to configure an Oculus Device. Registration failed\";\n\t\treturn false;\n\t}\n\n\t\/\/ Query the HMD for the left and right projection matrices.\n\tovrFovPort defaultLeftFov = info->handle->DefaultEyeFov[ovrEyeType::ovrEye_Left];\n\tovrFovPort defaultRightFov = info->handle->DefaultEyeFov[ovrEyeType::ovrEye_Right];\n\n\tfloat nearPlane = info->deviceObject->getNearPlane();\n\tfloat farPlane = info->deviceObject->getFarPlane();\n\n\tovrMatrix4f leftProjection = ovrMatrix4f_Projection(defaultLeftFov, nearPlane, farPlane,\n\t\t\tovrProjectionModifier::ovrProjection_RightHanded);\n\tovrMatrix4f rightProjection = ovrMatrix4f_Projection(defaultRightFov, nearPlane, farPlane,\n\t\t\tovrProjectionModifier::ovrProjection_RightHanded);\n\n\tDataGroup& inputData = info->deviceObject->getInputData();\n\tinputData.matrices().set(DataStructures::Names::LEFT_PROJECTION_MATRIX,\n\t\t\tEigen::Map>\n\t\t\t(&leftProjection.M[0][0]).cast());\n\tinputData.matrices().set(DataStructures::Names::RIGHT_PROJECTION_MATRIX,\n\t\t\tEigen::Map>\n\t\t\t(&rightProjection.M[0][0]).cast());\n\tinfo->deviceObject->pushInput();\n\n\treturn true;\n}\n\nbool OculusScaffold::unregisterDevice(const OculusDevice* const device)\n{\n\tbool result = false;\n\t{\n\t\tboost::lock_guard lock(m_state->mutex);\n\t\tauto match = std::find_if(m_state->registeredDevices.begin(), m_state->registeredDevices.end(),\n\t\t\t\t\t\t\t\t [&device](const std::unique_ptr& info)\n\t\t{\n\t\t\treturn info->deviceObject == device;\n\t\t});\n\n\t\tif (match != m_state->registeredDevices.end())\n\t\t{\n\t\t\tm_state->registeredDevices.erase(match);\n\t\t\t\/\/ the iterator is now invalid but that's OK\n\t\t\tSURGSIM_LOG_INFO(m_logger) << \"Device \" << getName() << \": unregistered.\";\n\t\t\tresult = true;\n\t\t}\n\t}\n\n\t\/\/ #threadsafety After unregistering, another thread could be in the process of registering.\n\tif (isRunning() && m_state->registeredDevices.size() == 0)\n\t{\n\t\tstop();\n\t}\n\n\tSURGSIM_LOG_IF(!result, m_logger, SEVERE) << \"Attempted to release a non-registered device.\";\n\n\treturn result;\n}\n\nbool OculusScaffold::doInitialize()\n{\n#if 6 == OVR_MAJOR_VERSION\n\tif (ovrSuccess != ovr_Initialize(nullptr))\n#elif 5 == OVR_MAJOR_VERSION\n\tif (ovrTrue != ovr_Initialize(nullptr))\n#endif\n\t{\n\t\tSURGSIM_LOG_SEVERE(m_logger) << \"Oculus SDK initialization failed.\";\n\t}\n\n\treturn true;\n}\n\nbool OculusScaffold::doStartUp()\n{\n\treturn true;\n}\n\nbool OculusScaffold::doUpdate(double dt)\n{\n\tboost::lock_guard lock(m_state->mutex);\n\n\tfor (auto& device : m_state->registeredDevices)\n\t{\n\t\tDataGroup& inputData = device->deviceObject->getInputData();\n\n\t\t\/\/ Query the HMD for the current tracking state.\n\t\t\/\/ If time in 2nd parameter is now or earlier, no pose prediction is made.\n\t\t\/\/ Pose is reported in a right handed coordinate system, X->RIGHT, Y->UP, Z->OUT.\n\t\t\/\/ Positive rotation is counterclockwise.\n\t\t\/\/ The XZ plane is ALWAYS aligned with the ground regardless of camera orientation.\n\t\t\/\/ Default tracking origin is one meter away from the camera.\n\t\tovrTrackingState ts = ovrHmd_GetTrackingState(device->handle, ovr_GetTimeInSeconds());\n\t\tif (ts.StatusFlags & (ovrStatus_OrientationTracked | ovrStatus_PositionTracked))\n\t\t{\n\t\t\tovrPosef ovrPose = ts.HeadPose.ThePose;\n\n\t\t\tVector3d position(ovrPose.Position.x, ovrPose.Position.y, ovrPose.Position.z);\n\t\t\tQuaterniond orientation(ovrPose.Orientation.w, ovrPose.Orientation.x,\n\t\t\t\t\t\t\t\t\tovrPose.Orientation.y, ovrPose.Orientation.z);\n\t\t\tRigidTransform3d pose = makeRigidTransform(orientation, position);\n\n\t\t\tinputData.poses().set(DataStructures::Names::POSE, pose);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tinputData.poses().reset(DataStructures::Names::POSE);\n\t\t}\n\n\t\tdevice->deviceObject->pushInput();\n\t}\n\n\treturn true;\n}\n\nSurgSim::DataStructures::DataGroup OculusScaffold::buildDeviceInputData()\n{\n\tDataGroupBuilder builder;\n\tbuilder.addPose(DataStructures::Names::POSE);\n\tbuilder.addMatrix(DataStructures::Names::LEFT_PROJECTION_MATRIX);\n\tbuilder.addMatrix(DataStructures::Names::RIGHT_PROJECTION_MATRIX);\n\treturn builder.createData();\n}\n\nstd::shared_ptr OculusScaffold::getOrCreateSharedInstance()\n{\n\tstatic auto creator = []()\n\t{\n\t\treturn std::shared_ptr(new OculusScaffold);\n\t};\n\tstatic Framework::SharedInstance sharedInstance(creator);\n\treturn sharedInstance.get();\n}\n\n}; \/\/ namespace Devices\n}; \/\/ namespace SurgSim\nFix bug where the occulus desctructs after register\/\/ This file is a part of the OpenSurgSim project.\n\/\/ Copyright 2015-2016, SimQuest Solutions Inc.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \"SurgSim\/Devices\/Oculus\/OculusScaffold.h\"\n\n#include \n#include \n#include \n#include \n\n#include \n#if 6 == OVR_MAJOR_VERSION\n#include \n#elif 5 == OVR_MAJOR_VERSION\n#include \n#endif\n\n#include \"SurgSim\/DataStructures\/DataGroup.h\"\n#include \"SurgSim\/DataStructures\/DataGroupBuilder.h\"\n#include \"SurgSim\/Devices\/Oculus\/OculusDevice.h\"\n#include \"SurgSim\/Framework\/Log.h\"\n#include \"SurgSim\/Framework\/SharedInstance.h\"\n#include \"SurgSim\/Math\/Quaternion.h\"\n#include \"SurgSim\/Math\/RigidTransform.h\"\n\nusing SurgSim::DataStructures::DataGroup;\nusing SurgSim::DataStructures::DataGroupBuilder;\nusing SurgSim::Framework::Logger;\nusing SurgSim::Math::makeRigidTransform;\nusing SurgSim::Math::Quaterniond;\nusing SurgSim::Math::RigidTransform3d;\nusing SurgSim::Math::Vector3d;\n\nnamespace SurgSim\n{\nnamespace Devices\n{\n\nstruct OculusScaffold::DeviceData\n{\n\t\/\/\/ Constructor\n\t\/\/\/ \\param device Device to be wrapped\n\texplicit DeviceData(OculusDevice* device) :\n\t\tdeviceObject(device),\n\t\thandle(nullptr)\n\t{\n#if 6 == OVR_MAJOR_VERSION\n\t\tovrHmd_Create(0, &handle);\n#elif 5 == OVR_MAJOR_VERSION\n\t\thandle = ovrHmd_Create(0);\n#endif\n\t}\n\n\t~DeviceData()\n\t{\n\t\tif (handle != nullptr)\n\t\t{\n\t\t\tovrHmd_Destroy(handle);\n\t\t}\n\t}\n\n\t\/\/\/ The device object wrapped in this class.\n\tOculusDevice* const deviceObject;\n\n\t\/\/\/ Device handle\n\tovrHmd handle;\n};\n\nstruct OculusScaffold::StateData\n{\n\t\/\/\/ List of registered devices.\n\tstd::list> registeredDevices;\n\n\t\/\/\/ The mutex that protects the list of registered devices.\n\tboost::mutex mutex;\n};\n\nOculusScaffold::OculusScaffold() :\n\tFramework::BasicThread(\"OculusScaffold\"),\n\tm_logger(Logger::getLogger(\"Devices\/Oculus\")),\n\tm_state(new StateData)\n{\n\tSURGSIM_LOG_DEBUG(m_logger) << \"Oculus: Shared scaffold created.\";\n\n\t\/\/ Oculus DK2 tracks Gyroscope, Accelerometer, Magnetometer at 1000Hz and\n\t\/\/ positional tracking is done at 60Hz.\n\tsetRate(1000.0);\n\n}\n\nOculusScaffold::~OculusScaffold()\n{\n\tovr_Shutdown();\n}\n\nbool OculusScaffold::registerDevice(OculusDevice* device)\n{\n\tbool success = true;\n\tif (!isRunning())\n\t{\n\t\tstd::shared_ptr barrier = std::make_shared(2);\n\t\tstart(barrier);\n\t\tbarrier->wait(true); \/\/ Wait for initialize\n\t\tbarrier->wait(true); \/\/ Wait for startup\n\t\tsuccess = isInitialized();\n\t}\n\n\tif (success)\n\t{\n\t\tboost::lock_guard lock(m_state->mutex);\n\t\tconst std::string deviceName = device->getName();\n\t\tauto sameName = [&deviceName](const std::unique_ptr& info)\n\t\t{\n\t\t\treturn info->deviceObject->getName() == deviceName;\n\t\t};\n\t\tauto found = std::find_if(m_state->registeredDevices.cbegin(), m_state->registeredDevices.cend(), sameName);\n\n\t\tif (found == m_state->registeredDevices.end())\n\t\t{\n\t\t\tstd::unique_ptr info(new DeviceData(device));\n\t\t\tsuccess = doRegisterDevice(info.get());\n\t\t\tif (success)\n\t\t\t{\n\t\t\t\tSURGSIM_LOG_INFO(m_logger) << \"Device \" << device->getName() << \": Registered\";\n\t\t\t\tm_state->registeredDevices.emplace_back(std::move(info));\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tSURGSIM_LOG_SEVERE(m_logger) << \"Tried to register a device when the same name, '\" <<\n\t\t\t\tdevice->getName() << \"', is already present!\";\n\t\t\tsuccess = false;\n\t\t}\n\t}\n\n\tif (isRunning() && m_state->registeredDevices.size() == 0)\n\t{\n\t\tstop();\n\t}\n\n\treturn success;\n}\n\nbool OculusScaffold::doRegisterDevice(DeviceData* info)\n{\n\tif (ovrHmd_Detect() < 1)\n\t{\n\t\tSURGSIM_LOG_SEVERE(m_logger) << \"No available Oculus device detected.\";\n\t\treturn false;\n\t}\n\n\tif (m_state->registeredDevices.size() > 0)\n\t{\n\t\tSURGSIM_LOG_SEVERE(m_logger)\n\t\t\t<< \"There is one registered Oculus device already. OculusScaffold only supports one device right now\";\n\t\treturn false;\n\t}\n\n\tif (info->handle == nullptr)\n\t{\n\t\tSURGSIM_LOG_SEVERE(m_logger) << \"Failed to obtain a handle to Oculus Device. Is an Oculus device plugged in?\";\n\t\treturn false;\n\t}\n\n#if 6 == OVR_MAJOR_VERSION\n\tif (ovrSuccess != ovrHmd_ConfigureTracking(info->handle, ovrTrackingCap_Orientation |\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t ovrTrackingCap_MagYawCorrection |\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t ovrTrackingCap_Position, 0))\n#elif 5 == OVR_MAJOR_VERSION\n\tif (ovrTrue != ovrHmd_ConfigureTracking(info->handle, ovrTrackingCap_Orientation |\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t ovrTrackingCap_MagYawCorrection |\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t ovrTrackingCap_Position, 0))\n#endif\n\t{\n\t\tSURGSIM_LOG_SEVERE(m_logger) << \"Failed to configure an Oculus Device. Registration failed\";\n\t\treturn false;\n\t}\n\n\t\/\/ Query the HMD for the left and right projection matrices.\n\tovrFovPort defaultLeftFov = info->handle->DefaultEyeFov[ovrEyeType::ovrEye_Left];\n\tovrFovPort defaultRightFov = info->handle->DefaultEyeFov[ovrEyeType::ovrEye_Right];\n\n\tfloat nearPlane = info->deviceObject->getNearPlane();\n\tfloat farPlane = info->deviceObject->getFarPlane();\n\n\tovrMatrix4f leftProjection = ovrMatrix4f_Projection(defaultLeftFov, nearPlane, farPlane,\n\t\t\tovrProjectionModifier::ovrProjection_RightHanded);\n\tovrMatrix4f rightProjection = ovrMatrix4f_Projection(defaultRightFov, nearPlane, farPlane,\n\t\t\tovrProjectionModifier::ovrProjection_RightHanded);\n\n\tDataGroup& inputData = info->deviceObject->getInputData();\n\tinputData.matrices().set(DataStructures::Names::LEFT_PROJECTION_MATRIX,\n\t\t\tEigen::Map>\n\t\t\t(&leftProjection.M[0][0]).cast());\n\tinputData.matrices().set(DataStructures::Names::RIGHT_PROJECTION_MATRIX,\n\t\t\tEigen::Map>\n\t\t\t(&rightProjection.M[0][0]).cast());\n\tinfo->deviceObject->pushInput();\n\n\treturn true;\n}\n\nbool OculusScaffold::unregisterDevice(const OculusDevice* const device)\n{\n\tbool result = false;\n\t{\n\t\tboost::lock_guard lock(m_state->mutex);\n\t\tauto match = std::find_if(m_state->registeredDevices.begin(), m_state->registeredDevices.end(),\n\t\t\t\t\t\t\t\t [&device](const std::unique_ptr& info)\n\t\t{\n\t\t\treturn info->deviceObject == device;\n\t\t});\n\n\t\tif (match != m_state->registeredDevices.end())\n\t\t{\n\t\t\tm_state->registeredDevices.erase(match);\n\t\t\t\/\/ the iterator is now invalid but that's OK\n\t\t\tSURGSIM_LOG_INFO(m_logger) << \"Device \" << getName() << \": unregistered.\";\n\t\t\tresult = true;\n\t\t}\n\t}\n\n\t\/\/ #threadsafety After unregistering, another thread could be in the process of registering.\n\tif (isRunning() && m_state->registeredDevices.size() == 0)\n\t{\n\t\tstop();\n\t}\n\n\tSURGSIM_LOG_IF(!result, m_logger, SEVERE) << \"Attempted to release a non-registered device.\";\n\n\treturn result;\n}\n\nbool OculusScaffold::doInitialize()\n{\n#if 6 == OVR_MAJOR_VERSION\n\tif (ovrSuccess != ovr_Initialize(nullptr))\n#elif 5 == OVR_MAJOR_VERSION\n\tif (ovrTrue != ovr_Initialize(nullptr))\n#endif\n\t{\n\t\tSURGSIM_LOG_SEVERE(m_logger) << \"Oculus SDK initialization failed.\";\n\t}\n\n\treturn true;\n}\n\nbool OculusScaffold::doStartUp()\n{\n\treturn true;\n}\n\nbool OculusScaffold::doUpdate(double dt)\n{\n\tboost::lock_guard lock(m_state->mutex);\n\n\tfor (auto& device : m_state->registeredDevices)\n\t{\n\t\tDataGroup& inputData = device->deviceObject->getInputData();\n\n\t\t\/\/ Query the HMD for the current tracking state.\n\t\t\/\/ If time in 2nd parameter is now or earlier, no pose prediction is made.\n\t\t\/\/ Pose is reported in a right handed coordinate system, X->RIGHT, Y->UP, Z->OUT.\n\t\t\/\/ Positive rotation is counterclockwise.\n\t\t\/\/ The XZ plane is ALWAYS aligned with the ground regardless of camera orientation.\n\t\t\/\/ Default tracking origin is one meter away from the camera.\n\t\tovrTrackingState ts = ovrHmd_GetTrackingState(device->handle, ovr_GetTimeInSeconds());\n\t\tif (ts.StatusFlags & (ovrStatus_OrientationTracked | ovrStatus_PositionTracked))\n\t\t{\n\t\t\tovrPosef ovrPose = ts.HeadPose.ThePose;\n\n\t\t\tVector3d position(ovrPose.Position.x, ovrPose.Position.y, ovrPose.Position.z);\n\t\t\tQuaterniond orientation(ovrPose.Orientation.w, ovrPose.Orientation.x,\n\t\t\t\t\t\t\t\t\tovrPose.Orientation.y, ovrPose.Orientation.z);\n\t\t\tRigidTransform3d pose = makeRigidTransform(orientation, position);\n\n\t\t\tinputData.poses().set(DataStructures::Names::POSE, pose);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tinputData.poses().reset(DataStructures::Names::POSE);\n\t\t}\n\n\t\tdevice->deviceObject->pushInput();\n\t}\n\n\treturn true;\n}\n\nSurgSim::DataStructures::DataGroup OculusScaffold::buildDeviceInputData()\n{\n\tDataGroupBuilder builder;\n\tbuilder.addPose(DataStructures::Names::POSE);\n\tbuilder.addMatrix(DataStructures::Names::LEFT_PROJECTION_MATRIX);\n\tbuilder.addMatrix(DataStructures::Names::RIGHT_PROJECTION_MATRIX);\n\treturn builder.createData();\n}\n\nstd::shared_ptr OculusScaffold::getOrCreateSharedInstance()\n{\n\tstatic auto creator = []()\n\t{\n\t\treturn std::shared_ptr(new OculusScaffold);\n\t};\n\tstatic Framework::SharedInstance sharedInstance(creator);\n\treturn sharedInstance.get();\n}\n\n}; \/\/ namespace Devices\n}; \/\/ namespace SurgSim\n<|endoftext|>"} {"text":"\/**\n* Copyright (C) 2016 3D Repo Ltd\n*\n* This program is free software: you can redistribute it and\/or modify\n* it under the terms of the GNU Affero General Public License as\n* published by the Free Software Foundation, either version 3 of the\n* License, or (at your option) any later version.\n*\n* This program is distributed in the hope that it will be useful,\n* but WITHOUT ANY WARRANTY; without even the implied warranty of\n* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n* GNU Affero General Public License for more details.\n*\n* You should have received a copy of the GNU Affero General Public License\n* along with this program. If not, see .\n*\/\n#include \"repo_maker_selection_tree.h\"\n#include \"..\/..\/core\/model\/bson\/repo_node_reference.h\"\n#include \"..\/modeloptimizer\/repo_optimizer_ifc.h\"\n\nusing namespace repo::manipulator::modelutility;\n\nconst static std::string REPO_LABEL_VISIBILITY_STATE = \"toggleState\";\nconst static std::string REPO_VISIBILITY_STATE_SHOW = \"visible\";\nconst static std::string REPO_VISIBILITY_STATE_HIDDEN = \"invisible\";\nconst static std::string REPO_VISIBILITY_STATE_HALF_HIDDEN = \"parentOfInvisible\";\n\nSelectionTreeMaker::SelectionTreeMaker(\n\tconst repo::core::model::RepoScene *scene)\n\t: scene(scene)\n{\n}\n\nrepo::lib::PropertyTree SelectionTreeMaker::generatePTree(\n\tconst repo::core::model::RepoNode *currentNode,\n\tstd::unordered_map < std::string,\n\tstd::pair < std::string, std::string >> &idMaps,\n\tconst std::string ¤tPath,\n\tbool &hiddenOnDefault,\n\tstd::vector &hiddenNode) const\n{\n\trepo::lib::PropertyTree tree;\n\tif (currentNode)\n\t{\n\t\tstd::string idString = currentNode->getUniqueID().toString();\n\t\trepo::lib::RepoUUID sharedID = currentNode->getSharedID();\n\t\tstd::string childPath = currentPath.empty() ? idString : currentPath + \"__\" + idString;\n\n\t\tauto children = scene->getChildrenAsNodes(repo::core::model::RepoScene::GraphType::DEFAULT, sharedID);\n\t\tstd::vector childrenTrees;\n\n\t\tstd::vector childrenTypes[2];\n\t\tfor (const auto &child : children)\n\t\t{\n\t\t\t\/\/Ensure IFC Space (if any) are put into the tree first.\n\t\t\tif (child->getName().find(IFC_TYPE_SPACE_LABEL) != std::string::npos)\n\t\t\t\tchildrenTypes[0].push_back(child);\n\t\t\telse\n\t\t\t\tchildrenTypes[1].push_back(child);\n\t\t}\n\n\t\tbool hasHiddenChildren = false;\n\t\tfor (const auto childrenSet : childrenTypes)\n\t\t{\n\t\t\tfor (const auto &child : childrenSet)\n\t\t\t{\n\t\t\t\tif (child)\n\t\t\t\t{\n\t\t\t\t\tswitch (child->getTypeAsEnum())\n\t\t\t\t\t{\n\t\t\t\t\tcase repo::core::model::NodeType::MESH:\n\t\t\t\t\tcase repo::core::model::NodeType::TRANSFORMATION:\n\t\t\t\t\tcase repo::core::model::NodeType::CAMERA:\n\t\t\t\t\tcase repo::core::model::NodeType::REFERENCE:\n\t\t\t\t\t{\n\t\t\t\t\t\tbool hiddenChild = false;\n\t\t\t\t\t\tchildrenTrees.push_back(generatePTree(child, idMaps, childPath, hiddenChild, hiddenNode));\n\t\t\t\t\t\thasHiddenChildren = hasHiddenChildren || hiddenChild;\n\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\trepoDebug << \"Null pointer for child node at generatePTree, current path : \" << currentPath;\n\t\t\t\t\trepoError << \"Unexpected error at selection tree generation, the tree may not be complete.\";\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tstd::string name = currentNode->getName();\n\t\tif (repo::core::model::NodeType::REFERENCE == currentNode->getTypeAsEnum())\n\t\t{\n\t\t\tif (auto refNode = dynamic_cast(currentNode))\n\t\t\t{\n\t\t\t\tauto refDb = refNode->getDatabaseName();\n\t\t\t\tname = (scene->getDatabaseName() == refDb ? \"\" : (refDb + \"\/\")) + refNode->getProjectName();\n\t\t\t}\n\t\t}\n\n\t\ttree.addToTree(\"account\", scene->getDatabaseName());\n\t\ttree.addToTree(\"project\", scene->getProjectName());\n\t\tif (!name.empty())\n\t\t\ttree.addToTree(\"name\", name);\n\t\ttree.addToTree(\"path\", childPath);\n\t\ttree.addToTree(\"_id\", idString);\n\t\ttree.addToTree(\"shared_id\", sharedID.toString());\n\t\ttree.addToTree(\"children\", childrenTrees);\n\n\t\tif (name.find(IFC_TYPE_SPACE_LABEL) != std::string::npos\n\t\t\t&& currentNode->getTypeAsEnum() == repo::core::model::NodeType::MESH)\n\t\t{\n\t\t\ttree.addToTree(REPO_LABEL_VISIBILITY_STATE, REPO_VISIBILITY_STATE_HIDDEN);\n\t\t\thiddenOnDefault = true;\n\t\t\thiddenNode.push_back(idString);\n\t\t}\n\t\telse if (hiddenOnDefault = hiddenOnDefault || hasHiddenChildren)\n\t\t{\n\t\t\ttree.addToTree(REPO_LABEL_VISIBILITY_STATE, REPO_VISIBILITY_STATE_HALF_HIDDEN);\n\t\t}\n\t\telse\n\t\t{\n\t\t\ttree.addToTree(REPO_LABEL_VISIBILITY_STATE, REPO_VISIBILITY_STATE_SHOW);\n\t\t}\n\n\t\tidMaps[idString] = { name, childPath };\n\t}\n\telse\n\t{\n\t\trepoDebug << \"Null pointer at generatePTree, current path : \" << currentPath;\n\t\trepoError << \"Unexpected error at selection tree generation, the tree may not be complete.\";\n\t}\n\n\treturn tree;\n}\n\nstd::map> SelectionTreeMaker::getSelectionTreeAsBuffer() const\n{\n\tauto trees = getSelectionTreeAsPropertyTree();\n\tstd::map> buffer;\n\tfor (const auto &tree : trees)\n\t{\n\t\tstd::stringstream ss;\n\t\ttree.second.write_json(ss);\n\t\tstd::string jsonString = ss.str();\n\t\tif (!jsonString.empty())\n\t\t{\n\t\t\tsize_t byteLength = jsonString.size() * sizeof(*jsonString.data());\n\t\t\tbuffer[tree.first] = std::vector();\n\t\t\tbuffer[tree.first].resize(byteLength);\n\t\t\tmemcpy(buffer[tree.first].data(), jsonString.data(), byteLength);\n\t\t}\n\t\telse\n\t\t{\n\t\t\trepoError << \"Failed to write selection tree into the buffer: JSON string is empty.\";\n\t\t}\n\t}\n\n\treturn buffer;\n}\n\nstd::map SelectionTreeMaker::getSelectionTreeAsPropertyTree() const\n{\n\tstd::map trees;\n\n\trepo::core::model::RepoNode *root;\n\tif (scene && (root = scene->getRoot(repo::core::model::RepoScene::GraphType::DEFAULT)))\n\t{\n\t\tstd::unordered_map< std::string, std::pair> map;\n\t\tstd::vector hiddenNodes;\n\t\tbool dummy;\n\t\trepo::lib::PropertyTree tree, settingsTree;\n\t\ttree.mergeSubTree(\"nodes\", generatePTree(root, map, \"\", dummy, hiddenNodes));\n\t\tfor (const auto pair : map)\n\t\t{\n\t\t\t\/\/if there's an entry in maps it must have an entry in paths\n\t\t\ttree.addToTree(\"idToName.\" + pair.first, pair.second.first);\n\t\t\ttree.addToTree(\"idToPath.\" + pair.first, pair.second.second);\n\t\t}\n\n\t\ttrees[\"fulltree.json\"] = tree;\n\n\t\tif (hiddenNodes.size())\n\t\t{\n\t\t\tsettingsTree.addToTree(\"hiddenNodes\", hiddenNodes);\n\t\t\ttrees[\"modelProperties.json\"] = settingsTree;\n\t\t}\n\t}\n\telse\n\t{\n\t\trepoError << \"Failed to generate selection tree: scene is empty or default scene is not loaded\";\n\t}\n\n\treturn trees;\n}\n\nSelectionTreeMaker::~SelectionTreeMaker()\n{\n}restore changes that were loss due to merge\/**\n* Copyright (C) 2016 3D Repo Ltd\n*\n* This program is free software: you can redistribute it and\/or modify\n* it under the terms of the GNU Affero General Public License as\n* published by the Free Software Foundation, either version 3 of the\n* License, or (at your option) any later version.\n*\n* This program is distributed in the hope that it will be useful,\n* but WITHOUT ANY WARRANTY; without even the implied warranty of\n* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n* GNU Affero General Public License for more details.\n*\n* You should have received a copy of the GNU Affero General Public License\n* along with this program. If not, see .\n*\/\n#include \"repo_maker_selection_tree.h\"\n#include \"..\/..\/core\/model\/bson\/repo_node_reference.h\"\n#include \"..\/modeloptimizer\/repo_optimizer_ifc.h\"\n\nusing namespace repo::manipulator::modelutility;\n\nconst static std::string REPO_LABEL_VISIBILITY_STATE = \"toggleState\";\nconst static std::string REPO_VISIBILITY_STATE_SHOW = \"visible\";\nconst static std::string REPO_VISIBILITY_STATE_HIDDEN = \"invisible\";\nconst static std::string REPO_VISIBILITY_STATE_HALF_HIDDEN = \"parentOfInvisible\";\n\nSelectionTreeMaker::SelectionTreeMaker(\n\tconst repo::core::model::RepoScene *scene)\n\t: scene(scene)\n{\n}\n\nrepo::lib::PropertyTree SelectionTreeMaker::generatePTree(\n\tconst repo::core::model::RepoNode *currentNode,\n\tstd::unordered_map < std::string,\n\tstd::pair < std::string, std::string >> &idMaps,\n\tconst std::string ¤tPath,\n\tbool &hiddenOnDefault,\n\tstd::vector &hiddenNode) const\n{\n\trepo::lib::PropertyTree tree;\n\tif (currentNode)\n\t{\n\t\tstd::string idString = currentNode->getUniqueID().toString();\n\t\trepo::lib::RepoUUID sharedID = currentNode->getSharedID();\n\t\tstd::string childPath = currentPath.empty() ? idString : currentPath + \"__\" + idString;\n\n\t\tauto children = scene->getChildrenAsNodes(repo::core::model::RepoScene::GraphType::DEFAULT, sharedID);\n\t\tstd::vector childrenTrees;\n\n\t\tstd::vector childrenTypes[2];\n\t\tstd::vector metaIDs;\n\t\tfor (const auto &child : children)\n\t\t{\n\t\t\t\/\/Ensure IFC Space (if any) are put into the tree first.\n\t\t\tif (child->getName().find(IFC_TYPE_SPACE_LABEL) != std::string::npos)\n\t\t\t\tchildrenTypes[0].push_back(child);\n\t\t\telse if (child->getTypeAsEnum() == repo::core::model::NodeType::METADATA)\n\t\t\t{\n\t\t\t\tmetaIDs.push_back(child->getUniqueID());\n\t\t\t}\n\t\t\telse\n\t\t\t\tchildrenTypes[1].push_back(child);\n\t\t}\n\n\t\tbool hasHiddenChildren = false;\n\t\tfor (const auto childrenSet : childrenTypes)\n\t\t{\n\t\t\tfor (const auto &child : childrenSet)\n\t\t\t{\n\t\t\t\tif (child)\n\t\t\t\t{\n\t\t\t\t\tswitch (child->getTypeAsEnum())\n\t\t\t\t\t{\n\t\t\t\t\tcase repo::core::model::NodeType::MESH:\n\t\t\t\t\tcase repo::core::model::NodeType::TRANSFORMATION:\n\t\t\t\t\tcase repo::core::model::NodeType::CAMERA:\n\t\t\t\t\tcase repo::core::model::NodeType::REFERENCE:\n\t\t\t\t\t{\n\t\t\t\t\t\tbool hiddenChild = false;\n\t\t\t\t\t\tchildrenTrees.push_back(generatePTree(child, idMaps, childPath, hiddenChild, hiddenNode));\n\t\t\t\t\t\thasHiddenChildren = hasHiddenChildren || hiddenChild;\n\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\trepoDebug << \"Null pointer for child node at generatePTree, current path : \" << currentPath;\n\t\t\t\t\trepoError << \"Unexpected error at selection tree generation, the tree may not be complete.\";\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tstd::string name = currentNode->getName();\n\t\tif (repo::core::model::NodeType::REFERENCE == currentNode->getTypeAsEnum())\n\t\t{\n\t\t\tif (auto refNode = dynamic_cast(currentNode))\n\t\t\t{\n\t\t\t\tauto refDb = refNode->getDatabaseName();\n\t\t\t\tname = (scene->getDatabaseName() == refDb ? \"\" : (refDb + \"\/\")) + refNode->getProjectName();\n\t\t\t}\n\t\t}\n\n\t\ttree.addToTree(\"account\", scene->getDatabaseName());\n\t\ttree.addToTree(\"project\", scene->getProjectName());\n\t\tif (!name.empty())\n\t\t\ttree.addToTree(\"name\", name);\n\t\ttree.addToTree(\"path\", childPath);\n\t\ttree.addToTree(\"_id\", idString);\n\t\ttree.addToTree(\"shared_id\", sharedID.toString());\n\t\ttree.addToTree(\"children\", childrenTrees);\n\t\ttree.addToTree(\"meta\", metaIDs);\n\n\t\tif (name.find(IFC_TYPE_SPACE_LABEL) != std::string::npos\n\t\t\t&& currentNode->getTypeAsEnum() == repo::core::model::NodeType::MESH)\n\t\t{\n\t\t\ttree.addToTree(REPO_LABEL_VISIBILITY_STATE, REPO_VISIBILITY_STATE_HIDDEN);\n\t\t\thiddenOnDefault = true;\n\t\t\thiddenNode.push_back(idString);\n\t\t}\n\t\telse if (hiddenOnDefault = hiddenOnDefault || hasHiddenChildren)\n\t\t{\n\t\t\ttree.addToTree(REPO_LABEL_VISIBILITY_STATE, REPO_VISIBILITY_STATE_HALF_HIDDEN);\n\t\t}\n\t\telse\n\t\t{\n\t\t\ttree.addToTree(REPO_LABEL_VISIBILITY_STATE, REPO_VISIBILITY_STATE_SHOW);\n\t\t}\n\n\t\tidMaps[idString] = { name, childPath };\n\t}\n\telse\n\t{\n\t\trepoDebug << \"Null pointer at generatePTree, current path : \" << currentPath;\n\t\trepoError << \"Unexpected error at selection tree generation, the tree may not be complete.\";\n\t}\n\n\treturn tree;\n}\n\nstd::map> SelectionTreeMaker::getSelectionTreeAsBuffer() const\n{\n\tauto trees = getSelectionTreeAsPropertyTree();\n\tstd::map> buffer;\n\tfor (const auto &tree : trees)\n\t{\n\t\tstd::stringstream ss;\n\t\ttree.second.write_json(ss);\n\t\tstd::string jsonString = ss.str();\n\t\tif (!jsonString.empty())\n\t\t{\n\t\t\tsize_t byteLength = jsonString.size() * sizeof(*jsonString.data());\n\t\t\tbuffer[tree.first] = std::vector();\n\t\t\tbuffer[tree.first].resize(byteLength);\n\t\t\tmemcpy(buffer[tree.first].data(), jsonString.data(), byteLength);\n\t\t}\n\t\telse\n\t\t{\n\t\t\trepoError << \"Failed to write selection tree into the buffer: JSON string is empty.\";\n\t\t}\n\t}\n\n\treturn buffer;\n}\n\nstd::map SelectionTreeMaker::getSelectionTreeAsPropertyTree() const\n{\n\tstd::map trees;\n\n\trepo::core::model::RepoNode *root;\n\tif (scene && (root = scene->getRoot(repo::core::model::RepoScene::GraphType::DEFAULT)))\n\t{\n\t\tstd::unordered_map< std::string, std::pair> map;\n\t\tstd::vector hiddenNodes;\n\t\tbool dummy;\n\t\trepo::lib::PropertyTree tree, settingsTree;\n\t\ttree.mergeSubTree(\"nodes\", generatePTree(root, map, \"\", dummy, hiddenNodes));\n\t\tfor (const auto pair : map)\n\t\t{\n\t\t\t\/\/if there's an entry in maps it must have an entry in paths\n\t\t\ttree.addToTree(\"idToName.\" + pair.first, pair.second.first);\n\t\t\ttree.addToTree(\"idToPath.\" + pair.first, pair.second.second);\n\t\t}\n\n\t\ttrees[\"fulltree.json\"] = tree;\n\n\t\tif (hiddenNodes.size())\n\t\t{\n\t\t\tsettingsTree.addToTree(\"hiddenNodes\", hiddenNodes);\n\t\t\ttrees[\"modelProperties.json\"] = settingsTree;\n\t\t}\n\t}\n\telse\n\t{\n\t\trepoError << \"Failed to generate selection tree: scene is empty or default scene is not loaded\";\n\t}\n\n\treturn trees;\n}\n\nSelectionTreeMaker::~SelectionTreeMaker()\n{\n}<|endoftext|>"} {"text":"\/* IBM_PROLOG_BEGIN_TAG *\/\n\/* This is an automatically generated prolog. *\/\n\/* *\/\n\/* $Source: src\/import\/chips\/p9\/procedures\/hwp\/memory\/p9_mss_volt.C $ *\/\n\/* *\/\n\/* OpenPOWER HostBoot Project *\/\n\/* *\/\n\/* Contributors Listed Below - COPYRIGHT 2015,2019 *\/\n\/* [+] International Business Machines Corp. *\/\n\/* *\/\n\/* *\/\n\/* Licensed under the Apache License, Version 2.0 (the \"License\"); *\/\n\/* you may not use this file except in compliance with the License. *\/\n\/* You may obtain a copy of the License at *\/\n\/* *\/\n\/* http:\/\/www.apache.org\/licenses\/LICENSE-2.0 *\/\n\/* *\/\n\/* Unless required by applicable law or agreed to in writing, software *\/\n\/* distributed under the License is distributed on an \"AS IS\" BASIS, *\/\n\/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or *\/\n\/* implied. See the License for the specific language governing *\/\n\/* permissions and limitations under the License. *\/\n\/* *\/\n\/* IBM_PROLOG_END_TAG *\/\n\n\/\/\/\n\/\/\/ @file p9_mss_volt.C\n\/\/\/ @brief Calculate and save off rail voltages\n\/\/\/\n\/\/ *HWP HWP Owner: Jacob Harvey \n\/\/ *HWP HWP Backup: Andre A. Marin \n\/\/ *HWP Team: Memory\n\/\/ *HWP Level: 3\n\/\/ *HWP Consumed by: FSP:HB\n\n#include \n\n\/\/ std lib\n#include \n\n\/\/ fapi2\n#include \n\n\/\/ mss lib\n#include \n#include \n#include \n#include \n#include \n#include \n\nusing fapi2::TARGET_TYPE_MCBIST;\nusing fapi2::TARGET_TYPE_MCS;\nusing fapi2::TARGET_TYPE_MCA;\nusing fapi2::TARGET_TYPE_DIMM;\nusing fapi2::FAPI2_RC_SUCCESS;\n\nextern \"C\"\n{\n\n \/\/\/\n \/\/\/ @brief Calculate and save off rail voltages\n \/\/\/ @param[in] i_targets vector of controllers (e.g., MCS)\n \/\/\/ @return FAPI2_RC_SUCCESS iff ok\n \/\/\/\n fapi2::ReturnCode p9_mss_volt( const std::vector< fapi2::Target >& i_targets )\n {\n \/\/ Loop through MCS\n for (const auto& l_mcs : i_targets)\n {\n FAPI_INF(\"Populating decoder cache for %s\", mss::c_str(l_mcs));\n\n \/\/Factory cache is per MCS\n std::vector< mss::spd::facade > l_spd_facades;\n FAPI_TRY( get_spd_decoder_list(l_mcs, l_spd_facades) );\n\n \/\/ Get dimms for each MCS\n for ( const auto& l_cache : l_spd_facades )\n {\n const auto l_dimm = l_cache.get_dimm_target();\n uint8_t l_dimm_nominal = 0;\n uint8_t l_dimm_endurant = 0;\n\n \/\/ Read nominal and endurant bits from SPD, 0 = 1.2V is not operable and endurant, 1 = 1.2 is valid\n FAPI_TRY( l_cache.operable_nominal_voltage(l_dimm_nominal) );\n FAPI_TRY( l_cache.endurant_nominal_voltage(l_dimm_endurant) );\n\n \/\/Check to make sure 1.2 V is both operable and endurant, fail if it is not\n FAPI_ASSERT ( (l_dimm_nominal == mss::spd::OPERABLE) && (l_dimm_endurant == mss::spd::ENDURANT),\n fapi2::MSS_VOLT_DDR_TYPE_REQUIRED_VOLTAGE().\n set_ACTUAL_OPERABLE(l_dimm_nominal).\n set_ACTUAL_ENDURANT(l_dimm_endurant).\n set_EXPECTED_OPERABLE(mss::spd::OPERABLE).\n set_EXPECTED_ENDURANT(mss::spd::ENDURANT).\n set_DIMM_TARGET(l_dimm),\n \"%s: DIMM is not operable (%d) expected (%d)\"\n \" and\/or endurant (%d) expected (%d) at 1.2V\",\n mss::c_str(l_dimm),\n l_dimm_nominal,\n mss::spd::OPERABLE,\n l_dimm_endurant,\n mss::spd::ENDURANT);\n } \/\/ l_dimm\n\n \/\/ Set the attributes for this MCS, values are in mss_const.H\n FAPI_TRY (mss::set_voltage_attributes (l_mcs,\n mss::DDR4_NOMINAL_VOLTAGE,\n mss::DDR4_VPP_VOLTAGE),\n \"Failed to set volt attributes\");\n } \/\/ mcs\n\n FAPI_INF(\"End mss volt\");\n return FAPI2_RC_SUCCESS;\n\n fapi_try_exit:\n return fapi2::current_err;\n } \/\/ p9_mss_volt\n} \/\/extern \"C\"\nMove MSS volt attr setters to generic folder\/* IBM_PROLOG_BEGIN_TAG *\/\n\/* This is an automatically generated prolog. *\/\n\/* *\/\n\/* $Source: src\/import\/chips\/p9\/procedures\/hwp\/memory\/p9_mss_volt.C $ *\/\n\/* *\/\n\/* OpenPOWER HostBoot Project *\/\n\/* *\/\n\/* Contributors Listed Below - COPYRIGHT 2015,2019 *\/\n\/* [+] International Business Machines Corp. *\/\n\/* *\/\n\/* *\/\n\/* Licensed under the Apache License, Version 2.0 (the \"License\"); *\/\n\/* you may not use this file except in compliance with the License. *\/\n\/* You may obtain a copy of the License at *\/\n\/* *\/\n\/* http:\/\/www.apache.org\/licenses\/LICENSE-2.0 *\/\n\/* *\/\n\/* Unless required by applicable law or agreed to in writing, software *\/\n\/* distributed under the License is distributed on an \"AS IS\" BASIS, *\/\n\/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or *\/\n\/* implied. See the License for the specific language governing *\/\n\/* permissions and limitations under the License. *\/\n\/* *\/\n\/* IBM_PROLOG_END_TAG *\/\n\n\/\/\/\n\/\/\/ @file p9_mss_volt.C\n\/\/\/ @brief Calculate and save off rail voltages\n\/\/\/\n\/\/ *HWP HWP Owner: Jacob Harvey \n\/\/ *HWP HWP Backup: Andre A. Marin \n\/\/ *HWP Team: Memory\n\/\/ *HWP Level: 3\n\/\/ *HWP Consumed by: FSP:HB\n\n#include \n\n\/\/ std lib\n#include \n\n\/\/ fapi2\n#include \n\n\/\/ mss lib\n#include \n#include \n\nusing fapi2::TARGET_TYPE_MCS;\n\nextern \"C\"\n{\n\n \/\/\/\n \/\/\/ @brief Calculate and save off rail voltages\n \/\/\/ @param[in] i_targets vector of controllers (e.g., MCS)\n \/\/\/ @return FAPI2_RC_SUCCESS iff ok\n \/\/\/\n fapi2::ReturnCode p9_mss_volt( const std::vector< fapi2::Target >& i_targets )\n {\n for (const auto& l_mcs : i_targets)\n {\n FAPI_TRY( (mss::setup_voltage_rail_values(l_mcs)),\n \"Failed setup_voltage_rail_values for %s\", mss::c_str(l_mcs) );\n } \/\/ mcs\n\n FAPI_INF(\"End mss volt\");\n\n fapi_try_exit:\n return fapi2::current_err;\n } \/\/ p9_mss_volt\n} \/\/extern \"C\"\n<|endoftext|>"} {"text":"\/\/ This file is part of CAF, the C++ Actor Framework. See the file LICENSE in\n\/\/ the main distribution directory for license terms and copyright or visit\n\/\/ https:\/\/github.com\/actor-framework\/actor-framework\/blob\/master\/LICENSE.\n\n#define CAF_SUITE sum_type\n\n#include \"caf\/sum_type.hpp\"\n\n#include \"core-test.hpp\"\n\n#include \n#include \n#include \n\n#include \"caf\/default_sum_type_access.hpp\"\n#include \"caf\/detail\/overload.hpp\"\n#include \"caf\/raise_error.hpp\"\n#include \"caf\/sum_type_access.hpp\"\n\nnamespace {\n\nclass union_type {\npublic:\n friend struct caf::default_sum_type_access;\n\n using T0 = int;\n using T1 = std::string;\n using T2 = std::map;\n\n using types = caf::detail::type_list;\n\n union_type() : index_(0), v0(0) {\n \/\/ nop\n }\n\n ~union_type() {\n destroy();\n }\n\n union_type& operator=(T0 value) {\n destroy();\n index_ = 0;\n v0 = value;\n return *this;\n }\n\n union_type& operator=(T1 value) {\n destroy();\n index_ = 1;\n new (&v1) T1(std::move(value));\n return *this;\n }\n\n union_type& operator=(T2 value) {\n destroy();\n index_ = 2;\n new (&v2) T2(std::move(value));\n return *this;\n }\n\nprivate:\n inline union_type& get_data() {\n return *this;\n }\n\n inline const union_type& get_data() const {\n return *this;\n }\n\n inline T0& get(std::integral_constant) {\n CAF_REQUIRE_EQUAL(index_, 0);\n return v0;\n }\n\n inline const T0& get(std::integral_constant) const {\n CAF_REQUIRE_EQUAL(index_, 0);\n return v0;\n }\n\n inline T1& get(std::integral_constant) {\n CAF_REQUIRE_EQUAL(index_, 1);\n return v1;\n }\n\n inline const T1& get(std::integral_constant) const {\n CAF_REQUIRE_EQUAL(index_, 1);\n return v1;\n }\n\n inline T2& get(std::integral_constant) {\n CAF_REQUIRE_EQUAL(index_, 2);\n return v2;\n }\n\n inline const T2& get(std::integral_constant) const {\n CAF_REQUIRE_EQUAL(index_, 2);\n return v2;\n }\n\n template \n inline bool is(std::integral_constant) const {\n return index_ == Index;\n }\n\n template \n inline Result apply(Visitor&& f, Ts&&... xs) const {\n switch (index_) {\n case 0:\n return f(std::forward(xs)..., v0);\n case 1:\n return f(std::forward(xs)..., v1);\n case 2:\n return f(std::forward(xs)..., v2);\n }\n CAF_RAISE_ERROR(\"invalid index in union_type\");\n }\n\n void destroy() {\n if (index_ == 1)\n v1.~T1();\n else if (index_ == 2)\n v2.~T2();\n }\n\n int index_;\n union {\n T0 v0;\n T1 v1;\n T2 v2;\n };\n};\n\n} \/\/ namespace\n\nnamespace caf {\n\ntemplate <>\nstruct sum_type_access : default_sum_type_access {};\n\n} \/\/ namespace caf\n\nusing namespace caf;\n\nusing std::string;\nusing map_type = std::map;\n\nnamespace {\n\nstruct stringify_t {\n string operator()(int x) const {\n return std::to_string(x);\n }\n\n string operator()(std::string x) const {\n return x;\n }\n\n string operator()(const map_type& x) const {\n return deep_to_string(x);\n }\n\n template \n string operator()(const T0& x0, const T1& x1) const {\n return (*this) (x0) + \", \" + (*this) (x1);\n }\n\n template \n string operator()(const T0& x0, const T1& x1, const T2& x2) const {\n return (*this) (x0, x1) + \", \" + (*this) (x2);\n }\n};\n\nconstexpr stringify_t stringify = stringify_t{};\n\n} \/\/ namespace\n\nCAF_TEST(holds_alternative) {\n union_type x;\n CAF_CHECK_EQUAL(holds_alternative(x), true);\n CAF_CHECK_EQUAL(holds_alternative(x), false);\n CAF_CHECK_EQUAL(holds_alternative(x), false);\n x = string{\"hello world\"};\n CAF_CHECK_EQUAL(holds_alternative(x), false);\n CAF_CHECK_EQUAL(holds_alternative(x), true);\n CAF_CHECK_EQUAL(holds_alternative(x), false);\n x = map_type{{1, 1}, {2, 2}};\n CAF_CHECK_EQUAL(holds_alternative(x), false);\n CAF_CHECK_EQUAL(holds_alternative(x), false);\n CAF_CHECK_EQUAL(holds_alternative(x), true);\n}\n\nCAF_TEST(get) {\n union_type x;\n CAF_CHECK_EQUAL(get(x), 0);\n x = 42;\n CAF_CHECK_EQUAL(get(x), 42);\n x = string{\"hello world\"};\n CAF_CHECK_EQUAL(get(x), \"hello world\");\n x = map_type{{1, 1}, {2, 2}};\n CAF_CHECK_EQUAL(get(x), map_type({{1, 1}, {2, 2}}));\n}\n\nCAF_TEST(get_if) {\n union_type x;\n CAF_CHECK_EQUAL(get_if(&x), &get(x));\n CAF_CHECK_EQUAL(get_if(&x), nullptr);\n CAF_CHECK_EQUAL(get_if(&x), nullptr);\n x = string{\"hello world\"};\n CAF_CHECK_EQUAL(get_if(&x), nullptr);\n CAF_CHECK_EQUAL(get_if(&x), &get(x));\n CAF_CHECK_EQUAL(get_if(&x), nullptr);\n x = map_type{{1, 1}, {2, 2}};\n CAF_CHECK_EQUAL(get_if(&x), nullptr);\n CAF_CHECK_EQUAL(get_if(&x), nullptr);\n CAF_CHECK_EQUAL(get_if(&x), &get(x));\n}\n\nCAF_TEST(unary visit) {\n union_type x;\n CAF_CHECK_EQUAL(visit(stringify, x), \"0\");\n x = string{\"hello world\"};\n CAF_CHECK_EQUAL(visit(stringify, x), \"hello world\");\n x = map_type{{1, 1}, {2, 2}};\n CAF_CHECK_EQUAL(visit(stringify, x), \"{1 = 1, 2 = 2}\");\n}\n\nCAF_TEST(binary visit) {\n union_type x;\n union_type y;\n CAF_CHECK_EQUAL(visit(stringify, x, y), \"0, 0\");\n x = 42;\n y = string{\"hello world\"};\n CAF_CHECK_EQUAL(visit(stringify, x, y), \"42, hello world\");\n}\n\nCAF_TEST(ternary visit) {\n union_type x;\n union_type y;\n union_type z;\n \/\/ CAF_CHECK_EQUAL(visit(stringify, x, y, z), \"0, 0, 0\");\n x = 42;\n y = string{\"foo\"};\n z = map_type{{1, 1}, {2, 2}};\n CAF_CHECK_EQUAL(visit(stringify, x, y, z), \"42, foo, {1 = 1, 2 = 2}\");\n}\nFix formatting\/\/ This file is part of CAF, the C++ Actor Framework. See the file LICENSE in\n\/\/ the main distribution directory for license terms and copyright or visit\n\/\/ https:\/\/github.com\/actor-framework\/actor-framework\/blob\/master\/LICENSE.\n\n#define CAF_SUITE sum_type\n\n#include \"caf\/sum_type.hpp\"\n\n#include \"core-test.hpp\"\n\n#include \n#include \n#include \n\n#include \"caf\/default_sum_type_access.hpp\"\n#include \"caf\/detail\/overload.hpp\"\n#include \"caf\/raise_error.hpp\"\n#include \"caf\/sum_type_access.hpp\"\n\nnamespace {\n\nclass union_type {\npublic:\n friend struct caf::default_sum_type_access;\n\n using T0 = int;\n using T1 = std::string;\n using T2 = std::map;\n\n using types = caf::detail::type_list;\n\n union_type() : index_(0), v0(0) {\n \/\/ nop\n }\n\n ~union_type() {\n destroy();\n }\n\n union_type& operator=(T0 value) {\n destroy();\n index_ = 0;\n v0 = value;\n return *this;\n }\n\n union_type& operator=(T1 value) {\n destroy();\n index_ = 1;\n new (&v1) T1(std::move(value));\n return *this;\n }\n\n union_type& operator=(T2 value) {\n destroy();\n index_ = 2;\n new (&v2) T2(std::move(value));\n return *this;\n }\n\nprivate:\n inline union_type& get_data() {\n return *this;\n }\n\n inline const union_type& get_data() const {\n return *this;\n }\n\n inline T0& get(std::integral_constant) {\n CAF_REQUIRE_EQUAL(index_, 0);\n return v0;\n }\n\n inline const T0& get(std::integral_constant) const {\n CAF_REQUIRE_EQUAL(index_, 0);\n return v0;\n }\n\n inline T1& get(std::integral_constant) {\n CAF_REQUIRE_EQUAL(index_, 1);\n return v1;\n }\n\n inline const T1& get(std::integral_constant) const {\n CAF_REQUIRE_EQUAL(index_, 1);\n return v1;\n }\n\n inline T2& get(std::integral_constant) {\n CAF_REQUIRE_EQUAL(index_, 2);\n return v2;\n }\n\n inline const T2& get(std::integral_constant) const {\n CAF_REQUIRE_EQUAL(index_, 2);\n return v2;\n }\n\n template \n inline bool is(std::integral_constant) const {\n return index_ == Index;\n }\n\n template \n inline Result apply(Visitor&& f, Ts&&... xs) const {\n switch (index_) {\n case 0:\n return f(std::forward(xs)..., v0);\n case 1:\n return f(std::forward(xs)..., v1);\n case 2:\n return f(std::forward(xs)..., v2);\n }\n CAF_RAISE_ERROR(\"invalid index in union_type\");\n }\n\n void destroy() {\n if (index_ == 1)\n v1.~T1();\n else if (index_ == 2)\n v2.~T2();\n }\n\n int index_;\n union {\n T0 v0;\n T1 v1;\n T2 v2;\n };\n};\n\n} \/\/ namespace\n\nnamespace caf {\n\ntemplate <>\nstruct sum_type_access : default_sum_type_access {};\n\n} \/\/ namespace caf\n\nusing namespace caf;\n\nusing std::string;\nusing map_type = std::map;\n\nnamespace {\n\nstruct stringify_t {\n string operator()(int x) const {\n return std::to_string(x);\n }\n\n string operator()(std::string x) const {\n return x;\n }\n\n string operator()(const map_type& x) const {\n return deep_to_string(x);\n }\n\n template \n string operator()(const T0& x0, const T1& x1) const {\n return (*this)(x0) + \", \" + (*this)(x1);\n }\n\n template \n string operator()(const T0& x0, const T1& x1, const T2& x2) const {\n return (*this)(x0, x1) + \", \" + (*this)(x2);\n }\n};\n\nconstexpr stringify_t stringify = stringify_t{};\n\n} \/\/ namespace\n\nCAF_TEST(holds_alternative) {\n union_type x;\n CAF_CHECK_EQUAL(holds_alternative(x), true);\n CAF_CHECK_EQUAL(holds_alternative(x), false);\n CAF_CHECK_EQUAL(holds_alternative(x), false);\n x = string{\"hello world\"};\n CAF_CHECK_EQUAL(holds_alternative(x), false);\n CAF_CHECK_EQUAL(holds_alternative(x), true);\n CAF_CHECK_EQUAL(holds_alternative(x), false);\n x = map_type{{1, 1}, {2, 2}};\n CAF_CHECK_EQUAL(holds_alternative(x), false);\n CAF_CHECK_EQUAL(holds_alternative(x), false);\n CAF_CHECK_EQUAL(holds_alternative(x), true);\n}\n\nCAF_TEST(get) {\n union_type x;\n CAF_CHECK_EQUAL(get(x), 0);\n x = 42;\n CAF_CHECK_EQUAL(get(x), 42);\n x = string{\"hello world\"};\n CAF_CHECK_EQUAL(get(x), \"hello world\");\n x = map_type{{1, 1}, {2, 2}};\n CAF_CHECK_EQUAL(get(x), map_type({{1, 1}, {2, 2}}));\n}\n\nCAF_TEST(get_if) {\n union_type x;\n CAF_CHECK_EQUAL(get_if(&x), &get(x));\n CAF_CHECK_EQUAL(get_if(&x), nullptr);\n CAF_CHECK_EQUAL(get_if(&x), nullptr);\n x = string{\"hello world\"};\n CAF_CHECK_EQUAL(get_if(&x), nullptr);\n CAF_CHECK_EQUAL(get_if(&x), &get(x));\n CAF_CHECK_EQUAL(get_if(&x), nullptr);\n x = map_type{{1, 1}, {2, 2}};\n CAF_CHECK_EQUAL(get_if(&x), nullptr);\n CAF_CHECK_EQUAL(get_if(&x), nullptr);\n CAF_CHECK_EQUAL(get_if(&x), &get(x));\n}\n\nCAF_TEST(unary visit) {\n union_type x;\n CAF_CHECK_EQUAL(visit(stringify, x), \"0\");\n x = string{\"hello world\"};\n CAF_CHECK_EQUAL(visit(stringify, x), \"hello world\");\n x = map_type{{1, 1}, {2, 2}};\n CAF_CHECK_EQUAL(visit(stringify, x), \"{1 = 1, 2 = 2}\");\n}\n\nCAF_TEST(binary visit) {\n union_type x;\n union_type y;\n CAF_CHECK_EQUAL(visit(stringify, x, y), \"0, 0\");\n x = 42;\n y = string{\"hello world\"};\n CAF_CHECK_EQUAL(visit(stringify, x, y), \"42, hello world\");\n}\n\nCAF_TEST(ternary visit) {\n union_type x;\n union_type y;\n union_type z;\n \/\/ CAF_CHECK_EQUAL(visit(stringify, x, y, z), \"0, 0, 0\");\n x = 42;\n y = string{\"foo\"};\n z = map_type{{1, 1}, {2, 2}};\n CAF_CHECK_EQUAL(visit(stringify, x, y, z), \"42, foo, {1 = 1, 2 = 2}\");\n}\n<|endoftext|>"} {"text":"#include \"polylineStyle.h\"\n\n#include \"tangram.h\"\n#include \"platform.h\"\n#include \"material.h\"\n#include \"gl\/shaderProgram.h\"\n#include \"gl\/typedMesh.h\"\n#include \"scene\/stops.h\"\n#include \"scene\/drawRule.h\"\n#include \"tile\/tile.h\"\n#include \"util\/mapProjection.h\"\n#include \"glm\/vec3.hpp\"\n\nnamespace Tangram {\n\nstruct PolylineVertex {\n glm::vec3 pos;\n glm::vec2 texcoord;\n glm::vec4 extrude;\n GLuint abgr;\n GLfloat layer;\n};\n\nusing Mesh = TypedMesh;\n\nPolylineStyle::PolylineStyle(std::string _name, Blending _blendMode, GLenum _drawMode)\n : Style(_name, _blendMode, _drawMode) {\n}\n\nvoid PolylineStyle::constructVertexLayout() {\n\n \/\/ TODO: Ideally this would be in the same location as the struct that it basically describes\n m_vertexLayout = std::shared_ptr(new VertexLayout({\n {\"a_position\", 3, GL_FLOAT, false, 0},\n {\"a_texcoord\", 2, GL_FLOAT, false, 0},\n {\"a_extrude\", 4, GL_FLOAT, false, 0},\n {\"a_color\", 4, GL_UNSIGNED_BYTE, true, 0},\n {\"a_layer\", 1, GL_FLOAT, false, 0}\n }));\n\n}\n\nvoid PolylineStyle::constructShaderProgram() {\n\n std::string vertShaderSrcStr = stringFromFile(\"shaders\/polyline.vs\", PathType::internal);\n std::string fragShaderSrcStr = stringFromFile(\"shaders\/polyline.fs\", PathType::internal);\n\n m_shaderProgram->setSourceStrings(fragShaderSrcStr, vertShaderSrcStr);\n}\n\nVboMesh* PolylineStyle::newMesh() const {\n return new Mesh(m_vertexLayout, m_drawMode);\n}\n\nPolylineStyle::Parameters PolylineStyle::parseRule(const DrawRule& _rule) const {\n Parameters p;\n\n uint32_t cap = 0, join = 0;\n\n _rule.get(StyleParamKey::extrude, p.extrude);\n _rule.get(StyleParamKey::color, p.color);\n _rule.get(StyleParamKey::cap, cap);\n _rule.get(StyleParamKey::join, join);\n _rule.get(StyleParamKey::order, p.order);\n\n p.cap = static_cast(cap);\n p.join = static_cast(join);\n\n p.outlineOrder = p.order; \/\/ will offset from fill later\n\n if (_rule.get(StyleParamKey::outline_color, p.outlineColor) |\n _rule.get(StyleParamKey::outline_order, p.outlineOrder) |\n _rule.contains(StyleParamKey::outline_width) |\n _rule.get(StyleParamKey::outline_cap, cap) |\n _rule.get(StyleParamKey::outline_join, join)) {\n p.outlineOn = true;\n p.outlineCap = static_cast(cap);\n p.outlineJoin = static_cast(join);\n }\n\n return p;\n}\n\nvoid PolylineStyle::buildPolygon(const Polygon& _poly, const DrawRule& _rule, const Properties& _props,\n VboMesh& _mesh, Tile& _tile) const {\n\n for (const auto& line : _poly) {\n buildLine(line, _rule, _props, _mesh, _tile);\n }\n}\n\ndouble widthMeterToPixel(int _zoom, double _tileSize, double _width) {\n \/\/ pixel per meter at z == 0\n double meterRes = _tileSize \/ (2.0 * MapProjection::HALF_CIRCUMFERENCE);\n \/\/ pixel per meter at zoom\n meterRes *= exp2(_zoom);\n\n return _width * meterRes;\n}\n\nbool evalStyleParamWidth(StyleParamKey _key, const DrawRule& _rule, const Tile& _tile,\n float& width, float& dWdZ){\n\n int zoom = _tile.getID().z;\n double tileSize = _tile.getProjection()->TileSize();\n\n \/\/ NB: 0.5 because 'width' will be extruded in both directions\n double tileRes = 0.5 \/ tileSize;\n\n\n auto& styleParam = _rule.findParameter(_key);\n if (styleParam.stops) {\n\n width = styleParam.stops->evalWidth(zoom);\n width *= tileRes;\n\n dWdZ = styleParam.stops->evalWidth(zoom + 1);\n dWdZ *= tileRes;\n \/\/ NB: Multiply by 2 for the outline to get the expected stroke pixel width.\n if (_key == StyleParamKey::outline_width) {\n width *= 2;\n dWdZ *= 2;\n }\n\n dWdZ -= width;\n\n return true;\n }\n\n if (styleParam.value.is()) {\n auto& widthParam = styleParam.value.get();\n\n width = widthParam.value;\n\n if (widthParam.isMeter()) {\n width = widthMeterToPixel(zoom, tileSize, width);\n width *= tileRes;\n dWdZ = width * 2;\n } else {\n width *= tileRes;\n dWdZ = width;\n }\n\n if (_key == StyleParamKey::outline_width) {\n width *= 2;\n dWdZ *= 2;\n }\n\n dWdZ -= width;\n\n return true;\n }\n\n LOGD(\"Invalid type for Width '%d'\\n\", styleParam.value.which());\n return false;\n}\n\nvoid PolylineStyle::buildLine(const Line& _line, const DrawRule& _rule, const Properties& _props,\n VboMesh& _mesh, Tile& _tile) const {\n\n std::vector vertices;\n\n Parameters params = parseRule(_rule);\n GLuint abgr = params.color;\n\n float dWdZ = 0.f;\n float width = 0.f;\n\n if (!evalStyleParamWidth(StyleParamKey::width, _rule, _tile, width, dWdZ)) {\n return;\n }\n\n if ( (width > -FLT_EPSILON && width < FLT_EPSILON) &&\n (dWdZ > -FLT_EPSILON && dWdZ < FLT_EPSILON) ) { return; }\n\n if (Tangram::getDebugFlag(Tangram::DebugFlags::proxy_colors)) {\n abgr = abgr << (_tile.getID().z % 6);\n }\n\n float height = 0.0f;\n auto& extrude = params.extrude;\n\n if (extrude[0] != 0.0f || extrude[1] != 0.0f) {\n const static std::string key_height(\"height\");\n\n height = _props.getNumeric(key_height) * _tile.getInverseScale();\n if (std::isnan(extrude[1])) {\n if (!std::isnan(extrude[0])) {\n height = extrude[0];\n }\n } else { height = extrude[1]; }\n }\n\n PolyLineBuilder builder {\n [&](const glm::vec3& coord, const glm::vec2& normal, const glm::vec2& uv) {\n glm::vec4 extrude = { normal.x, normal.y, width, dWdZ };\n vertices.push_back({ {coord.x, coord.y, height}, uv, extrude, abgr, (float)params.order });\n },\n [&](size_t sizeHint){ vertices.reserve(sizeHint); },\n params.cap,\n params.join\n };\n\n Builders::buildPolyLine(_line, builder);\n\n if (params.outlineOn) {\n\n GLuint abgrOutline = params.outlineColor;\n float outlineOrder = std::min(params.outlineOrder, params.order) - .5f;\n\n float widthOutline = 0.f;\n float dWdZOutline = 0.f;\n\n if (evalStyleParamWidth(StyleParamKey::outline_width, _rule, _tile, widthOutline, dWdZOutline) &&\n ((widthOutline < -FLT_EPSILON || widthOutline > FLT_EPSILON) ||\n (dWdZOutline < -FLT_EPSILON || dWdZOutline > FLT_EPSILON)) ) {\n\n widthOutline += width;\n dWdZOutline += dWdZ;\n\n if (params.outlineCap != params.cap || params.outlineJoin != params.join) {\n \/\/ need to re-triangulate with different cap and\/or join\n builder.cap = params.outlineCap;\n builder.join = params.outlineJoin;\n Builders::buildPolyLine(_line, builder);\n } else {\n \/\/ re-use indices from original line\n size_t oldSize = builder.indices.size();\n size_t offset = vertices.size();\n builder.indices.reserve(2 * oldSize);\n\n for(size_t i = 0; i < oldSize; i++) {\n builder.indices.push_back(offset + builder.indices[i]);\n }\n for (size_t i = 0; i < offset; i++) {\n const auto& v = vertices[i];\n glm::vec4 extrudeOutline = { v.extrude.x, v.extrude.y, widthOutline, dWdZOutline };\n vertices.push_back({ v.pos, v.texcoord, extrudeOutline, abgrOutline, outlineOrder });\n }\n }\n }\n }\n\n auto& mesh = static_cast(_mesh);\n mesh.addVertices(std::move(vertices), std::move(builder.indices));\n}\n\n}\nomit drawing line with negative width#include \"polylineStyle.h\"\n\n#include \"tangram.h\"\n#include \"platform.h\"\n#include \"material.h\"\n#include \"gl\/shaderProgram.h\"\n#include \"gl\/typedMesh.h\"\n#include \"scene\/stops.h\"\n#include \"scene\/drawRule.h\"\n#include \"tile\/tile.h\"\n#include \"util\/mapProjection.h\"\n#include \"glm\/vec3.hpp\"\n\nnamespace Tangram {\n\nstruct PolylineVertex {\n glm::vec3 pos;\n glm::vec2 texcoord;\n glm::vec4 extrude;\n GLuint abgr;\n GLfloat layer;\n};\n\nusing Mesh = TypedMesh;\n\nPolylineStyle::PolylineStyle(std::string _name, Blending _blendMode, GLenum _drawMode)\n : Style(_name, _blendMode, _drawMode) {\n}\n\nvoid PolylineStyle::constructVertexLayout() {\n\n \/\/ TODO: Ideally this would be in the same location as the struct that it basically describes\n m_vertexLayout = std::shared_ptr(new VertexLayout({\n {\"a_position\", 3, GL_FLOAT, false, 0},\n {\"a_texcoord\", 2, GL_FLOAT, false, 0},\n {\"a_extrude\", 4, GL_FLOAT, false, 0},\n {\"a_color\", 4, GL_UNSIGNED_BYTE, true, 0},\n {\"a_layer\", 1, GL_FLOAT, false, 0}\n }));\n\n}\n\nvoid PolylineStyle::constructShaderProgram() {\n\n std::string vertShaderSrcStr = stringFromFile(\"shaders\/polyline.vs\", PathType::internal);\n std::string fragShaderSrcStr = stringFromFile(\"shaders\/polyline.fs\", PathType::internal);\n\n m_shaderProgram->setSourceStrings(fragShaderSrcStr, vertShaderSrcStr);\n}\n\nVboMesh* PolylineStyle::newMesh() const {\n return new Mesh(m_vertexLayout, m_drawMode);\n}\n\nPolylineStyle::Parameters PolylineStyle::parseRule(const DrawRule& _rule) const {\n Parameters p;\n\n uint32_t cap = 0, join = 0;\n\n _rule.get(StyleParamKey::extrude, p.extrude);\n _rule.get(StyleParamKey::color, p.color);\n _rule.get(StyleParamKey::cap, cap);\n _rule.get(StyleParamKey::join, join);\n _rule.get(StyleParamKey::order, p.order);\n\n p.cap = static_cast(cap);\n p.join = static_cast(join);\n\n p.outlineOrder = p.order; \/\/ will offset from fill later\n\n if (_rule.get(StyleParamKey::outline_color, p.outlineColor) |\n _rule.get(StyleParamKey::outline_order, p.outlineOrder) |\n _rule.contains(StyleParamKey::outline_width) |\n _rule.get(StyleParamKey::outline_cap, cap) |\n _rule.get(StyleParamKey::outline_join, join)) {\n p.outlineOn = true;\n p.outlineCap = static_cast(cap);\n p.outlineJoin = static_cast(join);\n }\n\n return p;\n}\n\nvoid PolylineStyle::buildPolygon(const Polygon& _poly, const DrawRule& _rule, const Properties& _props,\n VboMesh& _mesh, Tile& _tile) const {\n\n for (const auto& line : _poly) {\n buildLine(line, _rule, _props, _mesh, _tile);\n }\n}\n\ndouble widthMeterToPixel(int _zoom, double _tileSize, double _width) {\n \/\/ pixel per meter at z == 0\n double meterRes = _tileSize \/ (2.0 * MapProjection::HALF_CIRCUMFERENCE);\n \/\/ pixel per meter at zoom\n meterRes *= exp2(_zoom);\n\n return _width * meterRes;\n}\n\nbool evalStyleParamWidth(StyleParamKey _key, const DrawRule& _rule, const Tile& _tile,\n float& width, float& dWdZ){\n\n int zoom = _tile.getID().z;\n double tileSize = _tile.getProjection()->TileSize();\n\n \/\/ NB: 0.5 because 'width' will be extruded in both directions\n double tileRes = 0.5 \/ tileSize;\n\n\n auto& styleParam = _rule.findParameter(_key);\n if (styleParam.stops) {\n\n width = styleParam.stops->evalWidth(zoom);\n width *= tileRes;\n\n dWdZ = styleParam.stops->evalWidth(zoom + 1);\n dWdZ *= tileRes;\n \/\/ NB: Multiply by 2 for the outline to get the expected stroke pixel width.\n if (_key == StyleParamKey::outline_width) {\n width *= 2;\n dWdZ *= 2;\n }\n\n dWdZ -= width;\n\n return true;\n }\n\n if (styleParam.value.is()) {\n auto& widthParam = styleParam.value.get();\n\n width = widthParam.value;\n\n if (widthParam.isMeter()) {\n width = widthMeterToPixel(zoom, tileSize, width);\n width *= tileRes;\n dWdZ = width * 2;\n } else {\n width *= tileRes;\n dWdZ = width;\n }\n\n if (_key == StyleParamKey::outline_width) {\n width *= 2;\n dWdZ *= 2;\n }\n\n dWdZ -= width;\n\n return true;\n }\n\n LOGD(\"Invalid type for Width '%d'\\n\", styleParam.value.which());\n return false;\n}\n\nvoid PolylineStyle::buildLine(const Line& _line, const DrawRule& _rule, const Properties& _props,\n VboMesh& _mesh, Tile& _tile) const {\n\n std::vector vertices;\n\n Parameters params = parseRule(_rule);\n GLuint abgr = params.color;\n\n float dWdZ = 0.f;\n float width = 0.f;\n\n if (!evalStyleParamWidth(StyleParamKey::width, _rule, _tile, width, dWdZ)) {\n return;\n }\n\n if (width < FLT_EPSILON && dWdZ < FLT_EPSILON) { return; }\n\n if (Tangram::getDebugFlag(Tangram::DebugFlags::proxy_colors)) {\n abgr = abgr << (_tile.getID().z % 6);\n }\n\n float height = 0.0f;\n auto& extrude = params.extrude;\n\n if (extrude[0] != 0.0f || extrude[1] != 0.0f) {\n const static std::string key_height(\"height\");\n\n height = _props.getNumeric(key_height) * _tile.getInverseScale();\n if (std::isnan(extrude[1])) {\n if (!std::isnan(extrude[0])) {\n height = extrude[0];\n }\n } else { height = extrude[1]; }\n }\n\n PolyLineBuilder builder {\n [&](const glm::vec3& coord, const glm::vec2& normal, const glm::vec2& uv) {\n glm::vec4 extrude = { normal.x, normal.y, width, dWdZ };\n vertices.push_back({ {coord.x, coord.y, height}, uv, extrude, abgr, (float)params.order });\n },\n [&](size_t sizeHint){ vertices.reserve(sizeHint); },\n params.cap,\n params.join\n };\n\n Builders::buildPolyLine(_line, builder);\n\n if (params.outlineOn) {\n\n GLuint abgrOutline = params.outlineColor;\n float outlineOrder = std::min(params.outlineOrder, params.order) - .5f;\n\n float widthOutline = 0.f;\n float dWdZOutline = 0.f;\n\n if (evalStyleParamWidth(StyleParamKey::outline_width, _rule, _tile, widthOutline, dWdZOutline) &&\n ((widthOutline > FLT_EPSILON && dWdZOutline >= 0) ||\n (dWdZOutline > FLT_EPSILON && widthOutline >= 0))) {\n\n widthOutline += width;\n dWdZOutline += dWdZ;\n\n if (params.outlineCap != params.cap || params.outlineJoin != params.join) {\n \/\/ need to re-triangulate with different cap and\/or join\n builder.cap = params.outlineCap;\n builder.join = params.outlineJoin;\n Builders::buildPolyLine(_line, builder);\n } else {\n \/\/ re-use indices from original line\n size_t oldSize = builder.indices.size();\n size_t offset = vertices.size();\n builder.indices.reserve(2 * oldSize);\n\n for(size_t i = 0; i < oldSize; i++) {\n builder.indices.push_back(offset + builder.indices[i]);\n }\n for (size_t i = 0; i < offset; i++) {\n const auto& v = vertices[i];\n glm::vec4 extrudeOutline = { v.extrude.x, v.extrude.y, widthOutline, dWdZOutline };\n vertices.push_back({ v.pos, v.texcoord, extrudeOutline, abgrOutline, outlineOrder });\n }\n }\n }\n }\n\n auto& mesh = static_cast(_mesh);\n mesh.addVertices(std::move(vertices), std::move(builder.indices));\n}\n\n}\n<|endoftext|>"} {"text":"\/*\n * yosys -- Yosys Open SYnthesis Suite\n *\n * Copyright (C) 2012 Claire Wolf \n * Copyright (C) 2019 Dan Ravensloft \n *\n * Permission to use, copy, modify, and\/or distribute this software for any\n * purpose with or without fee is hereby granted, provided that the above\n * copyright notice and this permission notice appear in all copies.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n *\n *\/\n\n#include \"kernel\/celltypes.h\"\n#include \"kernel\/log.h\"\n#include \"kernel\/register.h\"\n#include \"kernel\/rtlil.h\"\n\nUSING_YOSYS_NAMESPACE\nPRIVATE_NAMESPACE_BEGIN\n\nstruct SynthIntelALMPass : public ScriptPass {\n\tSynthIntelALMPass() : ScriptPass(\"synth_intel_alm\", \"synthesis for ALM-based Intel (Altera) FPGAs.\") {}\n\n\tvoid help() override\n\t{\n\t\t\/\/ |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|\n\t\tlog(\"\\n\");\n\t\tlog(\" synth_intel_alm [options]\\n\");\n\t\tlog(\"\\n\");\n\t\tlog(\"This command runs synthesis for ALM-based Intel FPGAs.\\n\");\n\t\tlog(\"\\n\");\n\t\tlog(\" -top \\n\");\n\t\tlog(\" use the specified module as top module\\n\");\n\t\tlog(\"\\n\");\n\t\tlog(\" -family \\n\");\n\t\tlog(\" target one of:\\n\");\n\t\tlog(\" \\\"cyclonev\\\" - Cyclone V (default)\\n\");\n\t\tlog(\" \\\"cyclone10gx\\\" - Cyclone 10GX\\n\");\n\t\tlog(\"\\n\");\n\t\tlog(\" -vqm \\n\");\n\t\tlog(\" write the design to the specified Verilog Quartus Mapping File. Writing of an\\n\");\n\t\tlog(\" output file is omitted if this parameter is not specified. Implies -quartus.\\n\");\n\t\tlog(\"\\n\");\n\t\tlog(\" -noflatten\\n\");\n\t\tlog(\" do not flatten design before synthesis; useful for per-module area statistics\\n\");\n\t\tlog(\"\\n\");\n\t\tlog(\" -quartus\\n\");\n\t\tlog(\" output a netlist using Quartus cells instead of MISTRAL_* cells\\n\");\n\t\tlog(\"\\n\");\n\t\tlog(\" -dff\\n\");\n\t\tlog(\" pass DFFs to ABC to perform sequential logic optimisations (EXPERIMENTAL)\\n\");\n\t\tlog(\"\\n\");\n\t\tlog(\" -run :\\n\");\n\t\tlog(\" only run the commands between the labels (see below). an empty\\n\");\n\t\tlog(\" from label is synonymous to 'begin', and empty to label is\\n\");\n\t\tlog(\" synonymous to the end of the command list.\\n\");\n\t\tlog(\"\\n\");\n\t\tlog(\" -nolutram\\n\");\n\t\tlog(\" do not use LUT RAM cells in output netlist\\n\");\n\t\tlog(\"\\n\");\n\t\tlog(\" -nobram\\n\");\n\t\tlog(\" do not use block RAM cells in output netlist\\n\");\n\t\tlog(\"\\n\");\n\t\tlog(\" -nodsp\\n\");\n\t\tlog(\" do not map multipliers to MISTRAL_MUL cells\\n\");\n\t\tlog(\"\\n\");\n\t\tlog(\"The following commands are executed by this synthesis command:\\n\");\n\t\thelp_script();\n\t\tlog(\"\\n\");\n\t}\n\n\tstring top_opt, family_opt, bram_type, vout_file;\n\tbool flatten, quartus, nolutram, nobram, dff, nodsp;\n\n\tvoid clear_flags() override\n\t{\n\t\ttop_opt = \"-auto-top\";\n\t\tfamily_opt = \"cyclonev\";\n\t\tbram_type = \"m10k\";\n\t\tvout_file = \"\";\n\t\tflatten = true;\n\t\tquartus = false;\n\t\tnolutram = false;\n\t\tnobram = false;\n\t\tdff = false;\n\t\tnodsp = false;\n\t}\n\n\tvoid execute(std::vector args, RTLIL::Design *design) override\n\t{\n\t\tstring run_from, run_to;\n\t\tclear_flags();\n\n\t\tsize_t argidx;\n\t\tfor (argidx = 1; argidx < args.size(); argidx++) {\n\t\t\tif (args[argidx] == \"-family\" && argidx + 1 < args.size()) {\n\t\t\t\tfamily_opt = args[++argidx];\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (args[argidx] == \"-top\" && argidx + 1 < args.size()) {\n\t\t\t\ttop_opt = \"-top \" + args[++argidx];\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (args[argidx] == \"-vqm\" && argidx + 1 < args.size()) {\n\t\t\t\tquartus = true;\n\t\t\t\tvout_file = args[++argidx];\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (args[argidx] == \"-run\" && argidx + 1 < args.size()) {\n\t\t\t\tsize_t pos = args[argidx + 1].find(':');\n\t\t\t\tif (pos == std::string::npos)\n\t\t\t\t\tbreak;\n\t\t\t\trun_from = args[++argidx].substr(0, pos);\n\t\t\t\trun_to = args[argidx].substr(pos + 1);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (args[argidx] == \"-quartus\") {\n\t\t\t\tquartus = true;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (args[argidx] == \"-nolutram\") {\n\t\t\t\tnolutram = true;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (args[argidx] == \"-nobram\") {\n\t\t\t\tnobram = true;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (args[argidx] == \"-nodsp\") {\n\t\t\t\tnodsp = true;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (args[argidx] == \"-noflatten\") {\n\t\t\t\tflatten = false;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (args[argidx] == \"-dff\") {\n\t\t\t\tdff = true;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\textra_args(args, argidx, design);\n\n\t\tif (!design->full_selection())\n\t\t\tlog_cmd_error(\"This command only operates on fully selected designs!\\n\");\n\n\t\tif (family_opt == \"cyclonev\") {\n\t\t\tbram_type = \"m10k\";\n\t\t} else if (family_opt == \"cyclone10gx\") {\n\t\t\tbram_type = \"m20k\";\n\t\t} else {\n\t\t\tlog_cmd_error(\"Invalid family specified: '%s'\\n\", family_opt.c_str());\n\t\t}\n\n\t\tlog_header(design, \"Executing SYNTH_INTEL_ALM pass.\\n\");\n\t\tlog_push();\n\n\t\trun_script(design, run_from, run_to);\n\n\t\tlog_pop();\n\t}\n\n\tvoid script() override\n\t{\n\t\tif (help_mode) {\n\t\t\tfamily_opt = \"\";\n\t\t\tbram_type = \"\";\n\t\t}\n\n\t\tif (check_label(\"begin\")) {\n\t\t\tif (family_opt == \"cyclonev\")\n\t\t\t\trun(stringf(\"read_verilog -sv -lib +\/intel_alm\/%s\/cells_sim.v\", family_opt.c_str()));\n\t\t\trun(stringf(\"read_verilog -specify -lib -D %s +\/intel_alm\/common\/alm_sim.v\", family_opt.c_str()));\n\t\t\trun(stringf(\"read_verilog -specify -lib -D %s +\/intel_alm\/common\/dff_sim.v\", family_opt.c_str()));\n\t\t\trun(stringf(\"read_verilog -specify -lib -D %s +\/intel_alm\/common\/dsp_sim.v\", family_opt.c_str()));\n\t\t\trun(stringf(\"read_verilog -specify -lib -D %s +\/intel_alm\/common\/mem_sim.v\", family_opt.c_str()));\n\t\t\trun(stringf(\"read_verilog -specify -lib -D %s -icells +\/intel_alm\/common\/abc9_model.v\", family_opt.c_str()));\n\n\t\t\t\/\/ Misc and common cells\n\t\t\trun(\"read_verilog -lib +\/intel\/common\/altpll_bb.v\");\n\t\t\trun(\"read_verilog -lib +\/intel_alm\/common\/megafunction_bb.v\");\n\t\t\trun(stringf(\"hierarchy -check %s\", help_mode ? \"-top \" : top_opt.c_str()));\n\t\t}\n\n\t\tif (check_label(\"coarse\")) {\n\t\t\trun(\"proc\");\n\t\t\tif (flatten || help_mode)\n\t\t\t\trun(\"flatten\", \"(skip if -noflatten)\");\n\t\t\trun(\"tribuf -logic\");\n\t\t\trun(\"deminout\");\n\t\t\trun(\"opt_expr\");\n\t\t\trun(\"opt_clean\");\n\t\t\trun(\"check\");\n\t\t\trun(\"opt -nodffe -nosdff\");\n\t\t\trun(\"fsm\");\n\t\t\trun(\"opt\");\n\t\t\trun(\"wreduce\");\n\t\t\trun(\"peepopt\");\n\t\t\trun(\"opt_clean\");\n\t\t\trun(\"share\");\n\t\t\trun(\"techmap -map +\/cmp2lut.v -D LUT_WIDTH=6\");\n\t\t\trun(\"opt_expr\");\n\t\t\trun(\"opt_clean\");\n\t\t\tif (help_mode) {\n\t\t\t\trun(\"techmap -map +\/mul2dsp.v [...]\", \"(unless -nodsp)\");\n\t\t\t} else if (!nodsp) {\n\t\t\t\t\/\/ Cyclone V supports 9x9 multiplication, Cyclone 10 GX does not.\n\t\t\t\trun(\"techmap -map +\/mul2dsp.v -D DSP_A_MAXWIDTH=27 -D DSP_B_MAXWIDTH=27 -D DSP_A_MINWIDTH=19 -D DSP_B_MINWIDTH=19 -D DSP_NAME=__MUL27X27\");\n\t\t\t\trun(\"chtype -set $mul t:$__soft_mul\");\n\t\t\t\tif (family_opt == \"cyclonev\") {\n\t\t\t\t\trun(\"techmap -map +\/mul2dsp.v -D DSP_A_MAXWIDTH=18 -D DSP_B_MAXWIDTH=18 -D DSP_A_MINWIDTH=10 -D DSP_B_MINWIDTH=10 -D DSP_NAME=__MUL18X18\");\n\t\t\t\t\trun(\"chtype -set $mul t:$__soft_mul\");\n\t\t\t\t\trun(\"techmap -map +\/mul2dsp.v -D DSP_A_MAXWIDTH=9 -D DSP_B_MAXWIDTH=9 -D DSP_A_MINWIDTH=4 -D DSP_B_MINWIDTH=4 -D DSP_NAME=__MUL9X9\");\n\t\t\t\t\trun(\"chtype -set $mul t:$__soft_mul\");\n\t\t\t\t} else if (family_opt == \"cyclone10gx\") {\n\t\t\t\t\trun(\"techmap -map +\/mul2dsp.v -D DSP_A_MAXWIDTH=18 -D DSP_B_MAXWIDTH=18 -D DSP_A_MINWIDTH=4 -D DSP_B_MINWIDTH=4 -D DSP_NAME=__MUL18X18\");\n\t\t\t\t\trun(\"chtype -set $mul t:$__soft_mul\");\n\t\t\t\t}\n\t\t\t}\n\t\t\trun(\"alumacc\");\n\t\t\trun(\"techmap -map +\/intel_alm\/common\/arith_alm_map.v -map +\/intel_alm\/common\/dsp_map.v\");\n\t\t\trun(\"opt\");\n\t\t\trun(\"memory -nomap\");\n\t\t\trun(\"opt_clean\");\n\t\t}\n\n\t\tif (!nobram && check_label(\"map_bram\", \"(skip if -nobram)\")) {\n\t\t\trun(stringf(\"memory_bram -rules +\/intel_alm\/common\/bram_%s.txt\", bram_type.c_str()));\n\t\t\tif (help_mode || bram_type != \"m10k\")\n\t\t\t\trun(stringf(\"techmap -map +\/intel_alm\/common\/bram_%s_map.v\", bram_type.c_str()));\n\t\t}\n\n\t\tif (!nolutram && check_label(\"map_lutram\", \"(skip if -nolutram)\")) {\n\t\t\trun(\"memory_bram -rules +\/intel_alm\/common\/lutram_mlab.txt\", \"(for Cyclone V \/ Cyclone 10GX)\");\n\t\t}\n\n\t\tif (check_label(\"map_ffram\")) {\n\t\t\trun(\"memory_map\");\n\t\t\trun(\"opt -full\");\n\t\t}\n\n\t\tif (check_label(\"map_ffs\")) {\n\t\t\trun(\"techmap\");\n\t\t\trun(\"dfflegalize -cell $_DFFE_PN0P_ 0 -cell $_SDFFCE_PP0P_ 0\");\n\t\t\trun(\"techmap -map +\/intel_alm\/common\/dff_map.v\");\n\t\t\trun(\"opt -full -undriven -mux_undef\");\n\t\t\trun(\"clean -purge\");\n\t\t}\n\n\t\tif (check_label(\"map_luts\")) {\n\t\t\trun(\"techmap -map +\/intel_alm\/common\/abc9_map.v\");\n\t\t\trun(stringf(\"abc9 %s -maxlut 6 -W 600\", help_mode ? \"[-dff]\" : dff ? \"-dff\" : \"\"));\n\t\t\trun(\"techmap -map +\/intel_alm\/common\/abc9_unmap.v\");\n\t\t\trun(\"techmap -map +\/intel_alm\/common\/alm_map.v\");\n\t\t\trun(\"opt -fast\");\n\t\t\trun(\"autoname\");\n\t\t\trun(\"clean\");\n\t\t}\n\n\t\tif (check_label(\"check\")) {\n\t\t\trun(\"hierarchy -check\");\n\t\t\trun(\"stat\");\n\t\t\trun(\"check\");\n\t\t}\n\n\t\tif (check_label(\"quartus\")) {\n\t\t\tif (quartus || help_mode) {\n\t\t\t\t\/\/ Quartus ICEs if you have a wire which has `[]` in its name,\n\t\t\t\t\/\/ which Yosys produces when building memories out of flops.\n\t\t\t\trun(\"rename -hide w:*[* w:*]*\");\n\t\t\t\t\/\/ VQM mode does not support 'x, so replace those with zero.\n\t\t\t\trun(\"setundef -zero\");\n\t\t\t\t\/\/ VQM mode does not support multi-bit constant assignments\n\t\t\t\t\/\/ (e.g. 2'b00 is an error), so as a workaround use references\n\t\t\t\t\/\/ to constant driver cells, which Quartus accepts.\n\t\t\t\trun(\"hilomap -singleton -hicell __MISTRAL_VCC Q -locell __MISTRAL_GND Q\");\n\t\t\t\t\/\/ Rename from Yosys-internal MISTRAL_* cells to Quartus cells.\n\t\t\t\trun(stringf(\"techmap -D %s -map +\/intel_alm\/common\/quartus_rename.v\", family_opt.c_str()));\n\t\t\t}\n\t\t}\n\n\t\tif (check_label(\"vqm\")) {\n\t\t\tif (!vout_file.empty() || help_mode) {\n\t\t\t\trun(stringf(\"write_verilog -attr2comment -defparam -nohex -decimal %s\", help_mode ? \"\" : vout_file.c_str()));\n\t\t\t}\n\t\t}\n\t}\n} SynthIntelALMPass;\n\nPRIVATE_NAMESPACE_END\nintel_alm: better map wide but shallow multiplies\/*\n * yosys -- Yosys Open SYnthesis Suite\n *\n * Copyright (C) 2012 Claire Wolf \n * Copyright (C) 2019 Dan Ravensloft \n *\n * Permission to use, copy, modify, and\/or distribute this software for any\n * purpose with or without fee is hereby granted, provided that the above\n * copyright notice and this permission notice appear in all copies.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n *\n *\/\n\n#include \"kernel\/celltypes.h\"\n#include \"kernel\/log.h\"\n#include \"kernel\/register.h\"\n#include \"kernel\/rtlil.h\"\n\nUSING_YOSYS_NAMESPACE\nPRIVATE_NAMESPACE_BEGIN\n\nstruct SynthIntelALMPass : public ScriptPass {\n\tSynthIntelALMPass() : ScriptPass(\"synth_intel_alm\", \"synthesis for ALM-based Intel (Altera) FPGAs.\") {}\n\n\tvoid help() override\n\t{\n\t\t\/\/ |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|\n\t\tlog(\"\\n\");\n\t\tlog(\" synth_intel_alm [options]\\n\");\n\t\tlog(\"\\n\");\n\t\tlog(\"This command runs synthesis for ALM-based Intel FPGAs.\\n\");\n\t\tlog(\"\\n\");\n\t\tlog(\" -top \\n\");\n\t\tlog(\" use the specified module as top module\\n\");\n\t\tlog(\"\\n\");\n\t\tlog(\" -family \\n\");\n\t\tlog(\" target one of:\\n\");\n\t\tlog(\" \\\"cyclonev\\\" - Cyclone V (default)\\n\");\n\t\tlog(\" \\\"cyclone10gx\\\" - Cyclone 10GX\\n\");\n\t\tlog(\"\\n\");\n\t\tlog(\" -vqm \\n\");\n\t\tlog(\" write the design to the specified Verilog Quartus Mapping File. Writing of an\\n\");\n\t\tlog(\" output file is omitted if this parameter is not specified. Implies -quartus.\\n\");\n\t\tlog(\"\\n\");\n\t\tlog(\" -noflatten\\n\");\n\t\tlog(\" do not flatten design before synthesis; useful for per-module area statistics\\n\");\n\t\tlog(\"\\n\");\n\t\tlog(\" -quartus\\n\");\n\t\tlog(\" output a netlist using Quartus cells instead of MISTRAL_* cells\\n\");\n\t\tlog(\"\\n\");\n\t\tlog(\" -dff\\n\");\n\t\tlog(\" pass DFFs to ABC to perform sequential logic optimisations (EXPERIMENTAL)\\n\");\n\t\tlog(\"\\n\");\n\t\tlog(\" -run :\\n\");\n\t\tlog(\" only run the commands between the labels (see below). an empty\\n\");\n\t\tlog(\" from label is synonymous to 'begin', and empty to label is\\n\");\n\t\tlog(\" synonymous to the end of the command list.\\n\");\n\t\tlog(\"\\n\");\n\t\tlog(\" -nolutram\\n\");\n\t\tlog(\" do not use LUT RAM cells in output netlist\\n\");\n\t\tlog(\"\\n\");\n\t\tlog(\" -nobram\\n\");\n\t\tlog(\" do not use block RAM cells in output netlist\\n\");\n\t\tlog(\"\\n\");\n\t\tlog(\" -nodsp\\n\");\n\t\tlog(\" do not map multipliers to MISTRAL_MUL cells\\n\");\n\t\tlog(\"\\n\");\n\t\tlog(\"The following commands are executed by this synthesis command:\\n\");\n\t\thelp_script();\n\t\tlog(\"\\n\");\n\t}\n\n\tstring top_opt, family_opt, bram_type, vout_file;\n\tbool flatten, quartus, nolutram, nobram, dff, nodsp;\n\n\tvoid clear_flags() override\n\t{\n\t\ttop_opt = \"-auto-top\";\n\t\tfamily_opt = \"cyclonev\";\n\t\tbram_type = \"m10k\";\n\t\tvout_file = \"\";\n\t\tflatten = true;\n\t\tquartus = false;\n\t\tnolutram = false;\n\t\tnobram = false;\n\t\tdff = false;\n\t\tnodsp = false;\n\t}\n\n\tvoid execute(std::vector args, RTLIL::Design *design) override\n\t{\n\t\tstring run_from, run_to;\n\t\tclear_flags();\n\n\t\tsize_t argidx;\n\t\tfor (argidx = 1; argidx < args.size(); argidx++) {\n\t\t\tif (args[argidx] == \"-family\" && argidx + 1 < args.size()) {\n\t\t\t\tfamily_opt = args[++argidx];\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (args[argidx] == \"-top\" && argidx + 1 < args.size()) {\n\t\t\t\ttop_opt = \"-top \" + args[++argidx];\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (args[argidx] == \"-vqm\" && argidx + 1 < args.size()) {\n\t\t\t\tquartus = true;\n\t\t\t\tvout_file = args[++argidx];\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (args[argidx] == \"-run\" && argidx + 1 < args.size()) {\n\t\t\t\tsize_t pos = args[argidx + 1].find(':');\n\t\t\t\tif (pos == std::string::npos)\n\t\t\t\t\tbreak;\n\t\t\t\trun_from = args[++argidx].substr(0, pos);\n\t\t\t\trun_to = args[argidx].substr(pos + 1);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (args[argidx] == \"-quartus\") {\n\t\t\t\tquartus = true;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (args[argidx] == \"-nolutram\") {\n\t\t\t\tnolutram = true;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (args[argidx] == \"-nobram\") {\n\t\t\t\tnobram = true;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (args[argidx] == \"-nodsp\") {\n\t\t\t\tnodsp = true;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (args[argidx] == \"-noflatten\") {\n\t\t\t\tflatten = false;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (args[argidx] == \"-dff\") {\n\t\t\t\tdff = true;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\textra_args(args, argidx, design);\n\n\t\tif (!design->full_selection())\n\t\t\tlog_cmd_error(\"This command only operates on fully selected designs!\\n\");\n\n\t\tif (family_opt == \"cyclonev\") {\n\t\t\tbram_type = \"m10k\";\n\t\t} else if (family_opt == \"cyclone10gx\") {\n\t\t\tbram_type = \"m20k\";\n\t\t} else {\n\t\t\tlog_cmd_error(\"Invalid family specified: '%s'\\n\", family_opt.c_str());\n\t\t}\n\n\t\tlog_header(design, \"Executing SYNTH_INTEL_ALM pass.\\n\");\n\t\tlog_push();\n\n\t\trun_script(design, run_from, run_to);\n\n\t\tlog_pop();\n\t}\n\n\tvoid script() override\n\t{\n\t\tif (help_mode) {\n\t\t\tfamily_opt = \"\";\n\t\t\tbram_type = \"\";\n\t\t}\n\n\t\tif (check_label(\"begin\")) {\n\t\t\tif (family_opt == \"cyclonev\")\n\t\t\t\trun(stringf(\"read_verilog -sv -lib +\/intel_alm\/%s\/cells_sim.v\", family_opt.c_str()));\n\t\t\trun(stringf(\"read_verilog -specify -lib -D %s +\/intel_alm\/common\/alm_sim.v\", family_opt.c_str()));\n\t\t\trun(stringf(\"read_verilog -specify -lib -D %s +\/intel_alm\/common\/dff_sim.v\", family_opt.c_str()));\n\t\t\trun(stringf(\"read_verilog -specify -lib -D %s +\/intel_alm\/common\/dsp_sim.v\", family_opt.c_str()));\n\t\t\trun(stringf(\"read_verilog -specify -lib -D %s +\/intel_alm\/common\/mem_sim.v\", family_opt.c_str()));\n\t\t\trun(stringf(\"read_verilog -specify -lib -D %s -icells +\/intel_alm\/common\/abc9_model.v\", family_opt.c_str()));\n\n\t\t\t\/\/ Misc and common cells\n\t\t\trun(\"read_verilog -lib +\/intel\/common\/altpll_bb.v\");\n\t\t\trun(\"read_verilog -lib +\/intel_alm\/common\/megafunction_bb.v\");\n\t\t\trun(stringf(\"hierarchy -check %s\", help_mode ? \"-top \" : top_opt.c_str()));\n\t\t}\n\n\t\tif (check_label(\"coarse\")) {\n\t\t\trun(\"proc\");\n\t\t\tif (flatten || help_mode)\n\t\t\t\trun(\"flatten\", \"(skip if -noflatten)\");\n\t\t\trun(\"tribuf -logic\");\n\t\t\trun(\"deminout\");\n\t\t\trun(\"opt_expr\");\n\t\t\trun(\"opt_clean\");\n\t\t\trun(\"check\");\n\t\t\trun(\"opt -nodffe -nosdff\");\n\t\t\trun(\"fsm\");\n\t\t\trun(\"opt\");\n\t\t\trun(\"wreduce\");\n\t\t\trun(\"peepopt\");\n\t\t\trun(\"opt_clean\");\n\t\t\trun(\"share\");\n\t\t\trun(\"techmap -map +\/cmp2lut.v -D LUT_WIDTH=6\");\n\t\t\trun(\"opt_expr\");\n\t\t\trun(\"opt_clean\");\n\t\t\tif (help_mode) {\n\t\t\t\trun(\"techmap -map +\/mul2dsp.v [...]\", \"(unless -nodsp)\");\n\t\t\t} else if (!nodsp) {\n\t\t\t\t\/\/ Cyclone V supports 9x9 multiplication, Cyclone 10 GX does not.\n\t\t\t\trun(\"techmap -map +\/mul2dsp.v -D DSP_A_MAXWIDTH=27 -D DSP_B_MAXWIDTH=27 -D DSP_A_MINWIDTH=19 -D DSP_B_MINWIDTH=4 -D DSP_NAME=__MUL27X27\");\n\t\t\t\trun(\"chtype -set $mul t:$__soft_mul\");\n\t\t\t\trun(\"techmap -map +\/mul2dsp.v -D DSP_A_MAXWIDTH=27 -D DSP_B_MAXWIDTH=27 -D DSP_A_MINWIDTH=4 -D DSP_B_MINWIDTH=19 -D DSP_NAME=__MUL27X27\");\n\t\t\t\trun(\"chtype -set $mul t:$__soft_mul\");\n\t\t\t\tif (family_opt == \"cyclonev\") {\n\t\t\t\t\trun(\"techmap -map +\/mul2dsp.v -D DSP_A_MAXWIDTH=18 -D DSP_B_MAXWIDTH=18 -D DSP_A_MINWIDTH=10 -D DSP_B_MINWIDTH=4 -D DSP_NAME=__MUL18X18\");\n\t\t\t\t\trun(\"chtype -set $mul t:$__soft_mul\");\n\t\t\t\t\trun(\"techmap -map +\/mul2dsp.v -D DSP_A_MAXWIDTH=18 -D DSP_B_MAXWIDTH=18 -D DSP_A_MINWIDTH=4 -D DSP_B_MINWIDTH=10 -D DSP_NAME=__MUL18X18\");\n\t\t\t\t\trun(\"chtype -set $mul t:$__soft_mul\");\n\t\t\t\t\trun(\"techmap -map +\/mul2dsp.v -D DSP_A_MAXWIDTH=9 -D DSP_B_MAXWIDTH=9 -D DSP_A_MINWIDTH=4 -D DSP_B_MINWIDTH=4 -D DSP_NAME=__MUL9X9\");\n\t\t\t\t\trun(\"chtype -set $mul t:$__soft_mul\");\n\t\t\t\t} else if (family_opt == \"cyclone10gx\") {\n\t\t\t\t\trun(\"techmap -map +\/mul2dsp.v -D DSP_A_MAXWIDTH=18 -D DSP_B_MAXWIDTH=18 -D DSP_A_MINWIDTH=4 -D DSP_B_MINWIDTH=4 -D DSP_NAME=__MUL18X18\");\n\t\t\t\t\trun(\"chtype -set $mul t:$__soft_mul\");\n\t\t\t\t}\n\t\t\t}\n\t\t\trun(\"alumacc\");\n\t\t\trun(\"techmap -map +\/intel_alm\/common\/arith_alm_map.v -map +\/intel_alm\/common\/dsp_map.v\");\n\t\t\trun(\"opt\");\n\t\t\trun(\"memory -nomap\");\n\t\t\trun(\"opt_clean\");\n\t\t}\n\n\t\tif (!nobram && check_label(\"map_bram\", \"(skip if -nobram)\")) {\n\t\t\trun(stringf(\"memory_bram -rules +\/intel_alm\/common\/bram_%s.txt\", bram_type.c_str()));\n\t\t\tif (help_mode || bram_type != \"m10k\")\n\t\t\t\trun(stringf(\"techmap -map +\/intel_alm\/common\/bram_%s_map.v\", bram_type.c_str()));\n\t\t}\n\n\t\tif (!nolutram && check_label(\"map_lutram\", \"(skip if -nolutram)\")) {\n\t\t\trun(\"memory_bram -rules +\/intel_alm\/common\/lutram_mlab.txt\", \"(for Cyclone V \/ Cyclone 10GX)\");\n\t\t}\n\n\t\tif (check_label(\"map_ffram\")) {\n\t\t\trun(\"memory_map\");\n\t\t\trun(\"opt -full\");\n\t\t}\n\n\t\tif (check_label(\"map_ffs\")) {\n\t\t\trun(\"techmap\");\n\t\t\trun(\"dfflegalize -cell $_DFFE_PN0P_ 0 -cell $_SDFFCE_PP0P_ 0\");\n\t\t\trun(\"techmap -map +\/intel_alm\/common\/dff_map.v\");\n\t\t\trun(\"opt -full -undriven -mux_undef\");\n\t\t\trun(\"clean -purge\");\n\t\t}\n\n\t\tif (check_label(\"map_luts\")) {\n\t\t\trun(\"techmap -map +\/intel_alm\/common\/abc9_map.v\");\n\t\t\trun(stringf(\"abc9 %s -maxlut 6 -W 600\", help_mode ? \"[-dff]\" : dff ? \"-dff\" : \"\"));\n\t\t\trun(\"techmap -map +\/intel_alm\/common\/abc9_unmap.v\");\n\t\t\trun(\"techmap -map +\/intel_alm\/common\/alm_map.v\");\n\t\t\trun(\"opt -fast\");\n\t\t\trun(\"autoname\");\n\t\t\trun(\"clean\");\n\t\t}\n\n\t\tif (check_label(\"check\")) {\n\t\t\trun(\"hierarchy -check\");\n\t\t\trun(\"stat\");\n\t\t\trun(\"check\");\n\t\t}\n\n\t\tif (check_label(\"quartus\")) {\n\t\t\tif (quartus || help_mode) {\n\t\t\t\t\/\/ Quartus ICEs if you have a wire which has `[]` in its name,\n\t\t\t\t\/\/ which Yosys produces when building memories out of flops.\n\t\t\t\trun(\"rename -hide w:*[* w:*]*\");\n\t\t\t\t\/\/ VQM mode does not support 'x, so replace those with zero.\n\t\t\t\trun(\"setundef -zero\");\n\t\t\t\t\/\/ VQM mode does not support multi-bit constant assignments\n\t\t\t\t\/\/ (e.g. 2'b00 is an error), so as a workaround use references\n\t\t\t\t\/\/ to constant driver cells, which Quartus accepts.\n\t\t\t\trun(\"hilomap -singleton -hicell __MISTRAL_VCC Q -locell __MISTRAL_GND Q\");\n\t\t\t\t\/\/ Rename from Yosys-internal MISTRAL_* cells to Quartus cells.\n\t\t\t\trun(stringf(\"techmap -D %s -map +\/intel_alm\/common\/quartus_rename.v\", family_opt.c_str()));\n\t\t\t}\n\t\t}\n\n\t\tif (check_label(\"vqm\")) {\n\t\t\tif (!vout_file.empty() || help_mode) {\n\t\t\t\trun(stringf(\"write_verilog -attr2comment -defparam -nohex -decimal %s\", help_mode ? \"\" : vout_file.c_str()));\n\t\t\t}\n\t\t}\n\t}\n} SynthIntelALMPass;\n\nPRIVATE_NAMESPACE_END\n<|endoftext|>"} {"text":"#include \"SkeletonIO.h\"\n\n#include \n#include \n#include \n\nnamespace gum\n{\n\n\/************************************************************************\/\n\/* class JointPose *\/\n\/************************************************************************\/\n\nvoid SkeletonIO::Load(const Json::Value& val, s2::JointPose& pose)\n{\n\tpose.trans.x = val[\"trans_x\"].asDouble();\n\tpose.trans.y = val[\"trans_y\"].asDouble();\n\tpose.rot = val[\"rot\"].asDouble();\n\tpose.scale = val[\"scale\"].asDouble();\n}\n\nvoid SkeletonIO::Store(Json::Value& val, const s2::JointPose& pose)\n{\n\tval[\"trans_x\"] = pose.trans.x;\n\tval[\"trans_y\"] = pose.trans.y;\n\tval[\"rot\"] = pose.rot;\n\tval[\"scale\"] = pose.scale;\n}\n\n\/************************************************************************\/\n\/* class SkeletonPose *\/\n\/************************************************************************\/\n\nvoid SkeletonIO::Load(const Json::Value& val, s2::SkeletonPose& pose)\n{\n\tstd::vector joints;\n\tjoints.reserve(val[\"joint\"].size());\n\tfor (int i = 0, n = val[\"joint\"].size(); i < n; ++i) {\n\t\ts2::JointPose joint;\n\t\tLoad(val[\"joint\"][i], joint);\n\t\tjoints.push_back(joint);\n\t}\n\tpose.SetJointPose(joints);\n}\n\nvoid SkeletonIO::Store(Json::Value& val, const s2::SkeletonPose& pose)\n{\n\tconst std::vector& joints = pose.GetJointPose();\n\tfor (int i = 0, n = joints.size(); i < n; ++i) {\n\t\tStore(val[\"joint\"][i], joints[i]);\n\t}\n}\n\n}[CHANGED] no uniform scale#include \"SkeletonIO.h\"\n\n#include \n#include \n#include \n\nnamespace gum\n{\n\n\/************************************************************************\/\n\/* class JointPose *\/\n\/************************************************************************\/\n\nvoid SkeletonIO::Load(const Json::Value& val, s2::JointPose& pose)\n{\n\tpose.trans.x\t= val[\"trans_x\"].asDouble();\n\tpose.trans.y\t= val[\"trans_y\"].asDouble();\n\tpose.rot\t\t= val[\"rot\"].asDouble();\n\tpose.scale.x\t= val[\"scale_x\"].asDouble();\n\tpose.scale.y\t= val[\"scale_y\"].asDouble();\n}\n\nvoid SkeletonIO::Store(Json::Value& val, const s2::JointPose& pose)\n{\n\tval[\"trans_x\"]\t= pose.trans.x;\n\tval[\"trans_y\"]\t= pose.trans.y;\n\tval[\"rot\"]\t\t= pose.rot;\n\tval[\"scale_x\"]\t= pose.scale.x;\n\tval[\"scale_y\"]\t= pose.scale.y;\n}\n\n\/************************************************************************\/\n\/* class SkeletonPose *\/\n\/************************************************************************\/\n\nvoid SkeletonIO::Load(const Json::Value& val, s2::SkeletonPose& pose)\n{\n\tstd::vector joints;\n\tjoints.reserve(val[\"joint\"].size());\n\tfor (int i = 0, n = val[\"joint\"].size(); i < n; ++i) {\n\t\ts2::JointPose joint;\n\t\tLoad(val[\"joint\"][i], joint);\n\t\tjoints.push_back(joint);\n\t}\n\tpose.SetJointPose(joints);\n}\n\nvoid SkeletonIO::Store(Json::Value& val, const s2::SkeletonPose& pose)\n{\n\tconst std::vector& joints = pose.GetJointPose();\n\tfor (int i = 0, n = joints.size(); i < n; ++i) {\n\t\tStore(val[\"joint\"][i], joints[i]);\n\t}\n}\n\n}<|endoftext|>"} {"text":"#include \"iteration\/initializer\/set_fixed_terms.h\"\n\n#include \n\n#include \"data\/system.h\"\n#include \"data\/system\/tests\/bilinear_term_mock.h\"\n#include \"iteration\/updater\/tests\/fixed_updater_mock.h\"\n#include \"test_helpers\/gmock_wrapper.h\"\n#include \"test_helpers\/test_helper_functions.h\"\n\nnamespace {\n\nusing namespace bart;\n\nusing ::testing::NiceMock, ::testing::Ref, ::testing::Return;\n\nclass IterationInitializerSetFixedTermsTest : public ::testing::Test {\n protected:\n using InitializerType = iteration::initializer::SetFixedTerms;\n using MockFixedUpdaterType = iteration::updater::FixedUpdaterMock;\n using MockBilinearTermType = data::system::BilinearTermMock;\n\n IterationInitializerSetFixedTermsTest()\n : total_groups_(btest::RandomDouble(1, 5)),\n total_angles_(btest::RandomDouble(1, 5)) {}\n\n \/\/ Initializer to be tested\n std::unique_ptr test_initializer_;\n\n \/\/ Supporting objects\n data::System test_system_;\n std::shared_ptr mpi_matrix_ptr_;\n\n \/\/ Pointers for observing mocks owned by other objects\n MockBilinearTermType* bilinear_term_obs_ptr_ = nullptr;\n MockFixedUpdaterType* updater_obs_ptr_ = nullptr;\n\n \/\/ Random values for testing\n const int total_groups_;\n const int total_angles_;\n\n void SetUp() override;\n};\n\nvoid IterationInitializerSetFixedTermsTest::SetUp() {\n \/\/ Set up testing object\n auto mock_fixed_updater_ptr =\n std::make_unique>();\n test_initializer_ =\n std::make_unique(std::move(mock_fixed_updater_ptr),\n total_groups_,\n total_angles_);\n\n \/\/ Set up supporting objects\n auto mock_bilinear_term = std::make_unique();\n test_system_.left_hand_side_ptr_ = std::move(mock_bilinear_term);\n mpi_matrix_ptr_ = std::make_shared();\n\n \/\/ Set up observing pointers\n updater_obs_ptr_ =\n dynamic_cast(test_initializer_->fixed_updater_ptr());\n bilinear_term_obs_ptr_ =\n dynamic_cast(test_system_.left_hand_side_ptr_.get());\n}\n\nTEST_F(IterationInitializerSetFixedTermsTest, Constructor) {\n EXPECT_TRUE(updater_obs_ptr_ != nullptr);\n EXPECT_EQ(test_initializer_->total_angles(), total_angles_);\n EXPECT_EQ(test_initializer_->total_groups(), total_groups_);\n}\n\nTEST_F(IterationInitializerSetFixedTermsTest, ConstructorThrows) {\n \/\/ Constructor should throw if fixed updater ptr is null\n std::unique_ptr null_fixed_updater = nullptr;\n EXPECT_ANY_THROW(\n InitializerType initializer(std::move(null_fixed_updater),\n total_groups_,\n total_angles_);\n );\n\n \/\/ Constructor should throw for bad groups and angle values\n std::array bad_values = {0, -1};\n\n for (int value : bad_values) {\n auto fixed_updater = std::make_unique();\n EXPECT_ANY_THROW(\n InitializerType initializer(std::move(fixed_updater),\n value,\n total_angles_);\n );\n fixed_updater = std::make_unique();\n EXPECT_ANY_THROW(\n InitializerType initializer(std::move(fixed_updater),\n total_groups_,\n value);\n );\n }\n}\n\nTEST_F(IterationInitializerSetFixedTermsTest, Initialize) {\n \/\/ Initializer should access all left hand side terms (all groups\/angles)\n for (int group = 0; group < total_groups_; ++group) {\n for (int angle = 0; angle < total_angles_; ++angle) {\n EXPECT_CALL(*updater_obs_ptr_, UpdateFixedTerms(Ref(test_system_),\n group, angle));\n }\n }\n\n test_initializer_->Initialize(test_system_);\n}\n\n} \/\/ namespaceremoved extraneous objects and fixed spacing for tests for SetFixedTerms#include \"iteration\/initializer\/set_fixed_terms.h\"\n\n#include \n\n#include \"data\/system.h\"\n#include \"data\/system\/tests\/bilinear_term_mock.h\"\n#include \"iteration\/updater\/tests\/fixed_updater_mock.h\"\n#include \"test_helpers\/gmock_wrapper.h\"\n#include \"test_helpers\/test_helper_functions.h\"\n\nnamespace {\n\nusing namespace bart;\n\nusing ::testing::NiceMock, ::testing::Ref, ::testing::Return;\n\nclass IterationInitializerSetFixedTermsTest : public ::testing::Test {\n protected:\n using InitializerType = iteration::initializer::SetFixedTerms;\n using MockFixedUpdaterType = iteration::updater::FixedUpdaterMock;\n using MockBilinearTermType = data::system::BilinearTermMock;\n\n IterationInitializerSetFixedTermsTest()\n : total_groups_(btest::RandomDouble(1, 5)),\n total_angles_(btest::RandomDouble(1, 5)) {}\n\n \/\/ Initializer to be tested\n std::unique_ptr test_initializer_;\n\n \/\/ Supporting objects\n data::System test_system_;\n\n \/\/ Pointers for observing mocks owned by other objects\n MockFixedUpdaterType* updater_obs_ptr_ = nullptr;\n\n \/\/ Random values for testing\n const int total_groups_;\n const int total_angles_;\n\n void SetUp() override;\n};\n\nvoid IterationInitializerSetFixedTermsTest::SetUp() {\n \/\/ Set up testing object\n auto mock_fixed_updater_ptr =\n std::make_unique>();\n test_initializer_ =\n std::make_unique(std::move(mock_fixed_updater_ptr),\n total_groups_,\n total_angles_);\n\n \/\/ Set up supporting objects\n auto mock_bilinear_term = std::make_unique();\n test_system_.left_hand_side_ptr_ = std::move(mock_bilinear_term);\n\n \/\/ Set up observing pointers\n updater_obs_ptr_ =\n dynamic_cast(test_initializer_->fixed_updater_ptr());\n}\n\nTEST_F(IterationInitializerSetFixedTermsTest, Constructor) {\n EXPECT_TRUE(updater_obs_ptr_ != nullptr);\n EXPECT_EQ(test_initializer_->total_angles(), total_angles_);\n EXPECT_EQ(test_initializer_->total_groups(), total_groups_);\n}\n\nTEST_F(IterationInitializerSetFixedTermsTest, ConstructorThrows) {\n \/\/ Constructor should throw if fixed updater ptr is null\n std::unique_ptr null_fixed_updater = nullptr;\n EXPECT_ANY_THROW(InitializerType initializer(std::move(null_fixed_updater),\n total_groups_, total_angles_););\n\n \/\/ Constructor should throw for bad groups and angle values\n std::array bad_values = {0, -1};\n\n for (int value : bad_values) {\n auto fixed_updater = std::make_unique();\n EXPECT_ANY_THROW(InitializerType initializer(std::move(fixed_updater),\n value, total_angles_););\n fixed_updater = std::make_unique();\n EXPECT_ANY_THROW(InitializerType initializer(std::move(fixed_updater),\n total_groups_, value););\n }\n}\n\nTEST_F(IterationInitializerSetFixedTermsTest, Initialize) {\n \/\/ Initializer should access all left hand side terms (all groups\/angles)\n for (int group = 0; group < total_groups_; ++group) {\n for (int angle = 0; angle < total_angles_; ++angle) {\n EXPECT_CALL(*updater_obs_ptr_, UpdateFixedTerms(Ref(test_system_),\n group, angle));\n }\n }\n\n test_initializer_->Initialize(test_system_);\n}\n\n} \/\/ namespace<|endoftext|>"} {"text":"\/*!\n \\file file_lock.cpp\n \\brief File-lock synchronization primitive implementation\n \\author Ivan Shynkarenka\n \\date 01.09.2016\n \\copyright MIT License\n*\/\n\n#include \"threads\/file_lock.h\"\n\n#include \"errors\/fatal.h\"\n#include \"filesystem\/exceptions.h\"\n\n#if defined(_WIN32) || defined(_WIN64)\n#include \n#elif defined(unix) || defined(__unix) || defined(__unix__)\n#include \n#include \n#include \n#endif\n\nnamespace CppCommon {\n\nclass FileLock::Impl\n{\npublic:\n Impl(const Path& path) : _path(path)\n {\n#if defined(_WIN32) || defined(_WIN64)\n std::wstring wpath = _path.to_wstring();\n\n \/\/ Retries in CreateFile, see http:\/\/support.microsoft.com\/kb\/316609\n const int attempts = 5;\n const int sleep = 250;\n for (int attempt = 0; attempt < attempts; ++attempt)\n {\n _file = CreateFileW(wpath.c_str(), GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, nullptr, CREATE_NEW, FILE_ATTRIBUTE_HIDDEN, nullptr);\n if (_file == INVALID_HANDLE_VALUE)\n {\n if (GetLastError() == ERROR_SHARING_VIOLATION)\n {\n Sleep(sleep);\n continue;\n }\n else\n {\n _file = CreateFileW(wpath.c_str(), GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_HIDDEN, nullptr);\n if (_file == INVALID_HANDLE_VALUE)\n {\n if (GetLastError() == ERROR_SHARING_VIOLATION)\n {\n Sleep(sleep);\n continue;\n }\n else\n break;\n }\n else\n {\n _owner = false;\n return;\n }\n }\n }\n else\n {\n _owner = true;\n return;\n }\n }\n throwex FileSystemException(\"Cannot create or open file-lock file!\").Attach(_path);\n#elif defined(unix) || defined(__unix) || defined(__unix__)\n _file = open(_path.native().c_str(), O_CREAT | O_EXCL | O_RDWR, 0644);\n if (_file < 0)\n {\n if (errno == EEXIST)\n {\n _file = open(_path.native().c_str(), O_CREAT | O_RDWR, 0644);\n if (_file >= 0)\n {\n _owner = false;\n return;\n }\n }\n }\n else\n {\n _owner = true;\n return;\n }\n throwex FileSystemException(\"Cannot create or open file-lock! file\").Attach(_path);\n#endif\n }\n\n ~Impl()\n {\n#if defined(_WIN32) || defined(_WIN64)\n if (!CloseHandle(_file))\n fatality(FileSystemException(\"Cannot close the file-lock handle!\").Attach(_path));\n\n \/\/ Remove the file-lock file (owner only)\n if (_owner)\n {\n if (!DeleteFileW(_path.to_wstring().c_str()))\n fatality(FileSystemException(\"Cannot delete the file-lock file!\").Attach(_path));\n }\n#elif defined(unix) || defined(__unix) || defined(__unix__)\n int result = close(_file);\n if (result != 0)\n fatality(FileSystemException(\"Cannot close the file-lock descriptor!\").Attach(_path));\n\n \/\/ Remove the file-lock file (owner only)\n if (_owner)\n {\n result = unlink(_path.native().c_str());\n if (result != 0)\n fatality(FileSystemException(\"Cannot unlink the file-lock file!\").Attach(_path));\n }\n#endif\n }\n\n const Path& path() const noexcept { return _path; }\n\n bool TryLockRead()\n {\n#if defined(_WIN32) || defined(_WIN64)\n OVERLAPPED overlapped;\n ZeroMemory(&overlapped, sizeof(OVERLAPPED));\n return LockFileEx(_file, LOCKFILE_FAIL_IMMEDIATELY, 0, MAXDWORD, MAXDWORD, &overlapped) ? true : false;\n#elif defined(linux) || defined(__linux) || defined(__linux__)\n struct flock lock;\n lock.l_type = F_RDLCK;\n lock.l_whence = SEEK_SET;\n lock.l_start = 0;\n lock.l_len = 0;\n int result = fcntl(_file, F_OFD_SETLK, &lock);\n if (result == -1)\n {\n if (errno == EAGAIN)\n return false;\n else\n throwex FileSystemException(\"Failed to try lock for read!\").Attach(_path);\n }\n else\n return true;\n#elif defined(unix) || defined(__unix) || defined(__unix__)\n int result = flock(_file, LOCK_SH | LOCK_NB);\n if (result != 0)\n {\n if (errno == EWOULDBLOCK)\n return false;\n else\n throwex FileSystemException(\"Failed to try lock for read!\").Attach(_path);\n }\n else\n return true;\n#endif\n }\n\n bool TryLockWrite()\n {\n#if defined(_WIN32) || defined(_WIN64)\n OVERLAPPED overlapped;\n ZeroMemory(&overlapped, sizeof(OVERLAPPED));\n return LockFileEx(_file, LOCKFILE_EXCLUSIVE_LOCK | LOCKFILE_FAIL_IMMEDIATELY, 0, MAXDWORD, MAXDWORD, &overlapped) ? true : false;\n#elif defined(linux) || defined(__linux) || defined(__linux__)\n struct flock lock;\n lock.l_type = F_WRLCK;\n lock.l_whence = SEEK_SET;\n lock.l_start = 0;\n lock.l_len = 0;\n int result = fcntl(_file, F_OFD_SETLK, &lock);\n if (result == -1)\n {\n if (errno == EAGAIN)\n return false;\n else\n throwex FileSystemException(\"Failed to try lock for write!\").Attach(_path);\n }\n else\n return true;\n#elif defined(unix) || defined(__unix) || defined(__unix__)\n int result = flock(_file, LOCK_EX | LOCK_NB);\n if (result != 0)\n {\n if (errno == EWOULDBLOCK)\n return false;\n else\n throwex FileSystemException(\"Failed to try lock for write!\").Attach(_path);\n }\n else\n return true;\n#endif\n }\n\n void LockRead()\n {\n#if defined(_WIN32) || defined(_WIN64)\n OVERLAPPED overlapped;\n ZeroMemory(&overlapped, sizeof(OVERLAPPED));\n if (!LockFileEx(_file, 0, 0, MAXDWORD, MAXDWORD, &overlapped))\n throwex FileSystemException(\"Failed to lock for read!\").Attach(_path);\n#elif defined(linux) || defined(__linux) || defined(__linux__)\n struct flock lock;\n lock.l_type = F_RDLCK;\n lock.l_whence = SEEK_SET;\n lock.l_start = 0;\n lock.l_len = 0;\n int result = fcntl(_file, F_OFD_SETLKW, &lock);\n if (result == -1)\n throwex FileSystemException(\"Failed to lock for read!\").Attach(_path);\n#elif defined(unix) || defined(__unix) || defined(__unix__)\n int result = flock(_file, LOCK_SH);\n if (result != 0)\n throwex FileSystemException(\"Failed to lock for read!\").Attach(_path);\n#endif\n }\n\n void LockWrite()\n {\n#if defined(_WIN32) || defined(_WIN64)\n OVERLAPPED overlapped;\n ZeroMemory(&overlapped, sizeof(OVERLAPPED));\n if (!LockFileEx(_file, LOCKFILE_EXCLUSIVE_LOCK, 0, MAXDWORD, MAXDWORD, &overlapped))\n throwex FileSystemException(\"Failed to lock for write!\").Attach(_path);\n#elif defined(linux) || defined(__linux) || defined(__linux__)\n struct flock lock;\n lock.l_type = F_WRLCK;\n lock.l_whence = SEEK_SET;\n lock.l_start = 0;\n lock.l_len = 0;\n int result = fcntl(_file, F_OFD_SETLKW, &lock);\n if (result == -1)\n throwex FileSystemException(\"Failed to lock for write!\").Attach(_path);\n#elif defined(unix) || defined(__unix) || defined(__unix__)\n int result = flock(_file, LOCK_EX);\n if (result != 0)\n throwex FileSystemException(\"Failed to lock for write!\").Attach(_path);\n#endif\n }\n\n void UnlockRead()\n {\n#if defined(_WIN32) || defined(_WIN64)\n OVERLAPPED overlapped;\n ZeroMemory(&overlapped, sizeof(OVERLAPPED));\n if (!UnlockFileEx(_file, 0, MAXDWORD, MAXDWORD, &overlapped))\n throwex FileSystemException(\"Failed to unlock the read lock!\").Attach(_path);\n#elif defined(linux) || defined(__linux) || defined(__linux__)\n struct flock lock;\n lock.l_type = F_UNLCK;\n lock.l_whence = SEEK_SET;\n lock.l_start = 0;\n lock.l_len = 0;\n int result = fcntl(_file, F_OFD_SETLK, &lock);\n if (result != 0)\n throwex FileSystemException(\"Failed to unlock the read lock!\").Attach(_path);\n#elif defined(unix) || defined(__unix) || defined(__unix__)\n int result = flock(_file, LOCK_UN);\n if (result != 0)\n throwex FileSystemException(\"Failed to unlock the read lock!\").Attach(_path);\n#endif\n }\n\n void UnlockWrite()\n {\n#if defined(_WIN32) || defined(_WIN64)\n OVERLAPPED overlapped;\n ZeroMemory(&overlapped, sizeof(OVERLAPPED));\n if (!UnlockFileEx(_file, 0, MAXDWORD, MAXDWORD, &overlapped))\n throwex FileSystemException(\"Failed to unlock the write lock!\").Attach(_path);\n#elif defined(linux) || defined(__linux) || defined(__linux__)\n struct flock lock;\n lock.l_type = F_UNLCK;\n lock.l_whence = SEEK_SET;\n lock.l_start = 0;\n lock.l_len = 0;\n int result = fcntl(_file, F_OFD_SETLK, &lock);\n if (result != 0)\n throwex FileSystemException(\"Failed to unlock the write lock!\").Attach(_path);\n#elif defined(unix) || defined(__unix) || defined(__unix__)\n int result = flock(_file, LOCK_UN);\n if (result != 0)\n throwex FileSystemException(\"Failed to unlock the write lock!\").Attach(_path);\n#endif\n }\n\nprivate:\n Path _path;\n#if defined(_WIN32) || defined(_WIN64)\n HANDLE _file;\n#elif defined(unix) || defined(__unix) || defined(__unix__)\n int _file;\n#endif\n bool _owner;\n};\n\nFileLock::FileLock(const Path& path) : _pimpl(new Impl(path))\n{\n}\n\nFileLock::~FileLock()\n{\n}\n\nconst Path& FileLock::path() const noexcept\n{\n return _pimpl->path();\n}\n\nbool FileLock::TryLockRead()\n{\n return _pimpl->TryLockRead();\n}\n\nbool FileLock::TryLockWrite()\n{\n return _pimpl->TryLockWrite();\n}\n\nvoid FileLock::LockRead()\n{\n _pimpl->LockRead();\n}\n\nvoid FileLock::LockWrite()\n{\n _pimpl->LockWrite();\n}\n\nvoid FileLock::UnlockRead()\n{\n _pimpl->UnlockRead();\n}\n\nvoid FileLock::UnlockWrite()\n{\n _pimpl->UnlockWrite();\n}\n\n} \/\/ namespace CppCommon\nBugfixing\/*!\n \\file file_lock.cpp\n \\brief File-lock synchronization primitive implementation\n \\author Ivan Shynkarenka\n \\date 01.09.2016\n \\copyright MIT License\n*\/\n\n#include \"threads\/file_lock.h\"\n\n#include \"errors\/fatal.h\"\n#include \"filesystem\/exceptions.h\"\n\n#if defined(_WIN32) || defined(_WIN64)\n#include \n#elif defined(unix) || defined(__unix) || defined(__unix__)\n#include \n#include \n#include \n#endif\n\nnamespace CppCommon {\n\nclass FileLock::Impl\n{\npublic:\n Impl(const Path& path) : _path(path)\n {\n#if defined(_WIN32) || defined(_WIN64)\n std::wstring wpath = _path.to_wstring();\n\n \/\/ Retries in CreateFile, see http:\/\/support.microsoft.com\/kb\/316609\n const int attempts = 5;\n const int sleep = 250;\n for (int attempt = 0; attempt < attempts; ++attempt)\n {\n _file = CreateFileW(wpath.c_str(), GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, nullptr, CREATE_NEW, FILE_ATTRIBUTE_HIDDEN, nullptr);\n if (_file == INVALID_HANDLE_VALUE)\n {\n if (GetLastError() == ERROR_SHARING_VIOLATION)\n {\n Sleep(sleep);\n continue;\n }\n else\n {\n _file = CreateFileW(wpath.c_str(), GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_HIDDEN, nullptr);\n if (_file == INVALID_HANDLE_VALUE)\n {\n if (GetLastError() == ERROR_SHARING_VIOLATION)\n {\n Sleep(sleep);\n continue;\n }\n else\n break;\n }\n else\n {\n _owner = false;\n return;\n }\n }\n }\n else\n {\n _owner = true;\n return;\n }\n }\n throwex FileSystemException(\"Cannot create or open file-lock file!\").Attach(_path);\n#elif defined(unix) || defined(__unix) || defined(__unix__)\n _file = open(_path.native().c_str(), O_CREAT | O_EXCL | O_RDWR, 0644);\n if (_file < 0)\n {\n if (errno == EEXIST)\n {\n _file = open(_path.native().c_str(), O_CREAT | O_RDWR, 0644);\n if (_file >= 0)\n {\n _owner = false;\n return;\n }\n }\n }\n else\n {\n _owner = true;\n return;\n }\n throwex FileSystemException(\"Cannot create or open file-lock! file\").Attach(_path);\n#endif\n }\n\n ~Impl()\n {\n#if defined(_WIN32) || defined(_WIN64)\n if (!CloseHandle(_file))\n fatality(FileSystemException(\"Cannot close the file-lock handle!\").Attach(_path));\n\n \/\/ Remove the file-lock file (owner only)\n if (_owner)\n {\n if (!DeleteFileW(_path.to_wstring().c_str()))\n fatality(FileSystemException(\"Cannot delete the file-lock file!\").Attach(_path));\n }\n#elif defined(unix) || defined(__unix) || defined(__unix__)\n int result = close(_file);\n if (result != 0)\n fatality(FileSystemException(\"Cannot close the file-lock descriptor!\").Attach(_path));\n\n \/\/ Remove the file-lock file (owner only)\n if (_owner)\n {\n result = unlink(_path.native().c_str());\n if (result != 0)\n fatality(FileSystemException(\"Cannot unlink the file-lock file!\").Attach(_path));\n }\n#endif\n }\n\n const Path& path() const noexcept { return _path; }\n\n bool TryLockRead()\n {\n#if defined(_WIN32) || defined(_WIN64)\n OVERLAPPED overlapped;\n ZeroMemory(&overlapped, sizeof(OVERLAPPED));\n return LockFileEx(_file, LOCKFILE_FAIL_IMMEDIATELY, 0, MAXDWORD, MAXDWORD, &overlapped) ? true : false;\n#elif defined(linux) || defined(__linux) || defined(__linux__)\n struct flock lock;\n lock.l_type = F_RDLCK;\n lock.l_whence = SEEK_SET;\n lock.l_start = 0;\n lock.l_len = 0;\n lock.l_pid = 0;\n int result = fcntl(_file, F_OFD_SETLK, &lock);\n if (result == -1)\n {\n if (errno == EAGAIN)\n return false;\n else\n throwex FileSystemException(\"Failed to try lock for read!\").Attach(_path);\n }\n else\n return true;\n#elif defined(unix) || defined(__unix) || defined(__unix__)\n int result = flock(_file, LOCK_SH | LOCK_NB);\n if (result != 0)\n {\n if (errno == EWOULDBLOCK)\n return false;\n else\n throwex FileSystemException(\"Failed to try lock for read!\").Attach(_path);\n }\n else\n return true;\n#endif\n }\n\n bool TryLockWrite()\n {\n#if defined(_WIN32) || defined(_WIN64)\n OVERLAPPED overlapped;\n ZeroMemory(&overlapped, sizeof(OVERLAPPED));\n return LockFileEx(_file, LOCKFILE_EXCLUSIVE_LOCK | LOCKFILE_FAIL_IMMEDIATELY, 0, MAXDWORD, MAXDWORD, &overlapped) ? true : false;\n#elif defined(linux) || defined(__linux) || defined(__linux__)\n struct flock lock;\n lock.l_type = F_WRLCK;\n lock.l_whence = SEEK_SET;\n lock.l_start = 0;\n lock.l_len = 0;\n lock.l_pid = 0;\n int result = fcntl(_file, F_OFD_SETLK, &lock);\n if (result == -1)\n {\n if (errno == EAGAIN)\n return false;\n else\n throwex FileSystemException(\"Failed to try lock for write!\").Attach(_path);\n }\n else\n return true;\n#elif defined(unix) || defined(__unix) || defined(__unix__)\n int result = flock(_file, LOCK_EX | LOCK_NB);\n if (result != 0)\n {\n if (errno == EWOULDBLOCK)\n return false;\n else\n throwex FileSystemException(\"Failed to try lock for write!\").Attach(_path);\n }\n else\n return true;\n#endif\n }\n\n void LockRead()\n {\n#if defined(_WIN32) || defined(_WIN64)\n OVERLAPPED overlapped;\n ZeroMemory(&overlapped, sizeof(OVERLAPPED));\n if (!LockFileEx(_file, 0, 0, MAXDWORD, MAXDWORD, &overlapped))\n throwex FileSystemException(\"Failed to lock for read!\").Attach(_path);\n#elif defined(linux) || defined(__linux) || defined(__linux__)\n struct flock lock;\n lock.l_type = F_RDLCK;\n lock.l_whence = SEEK_SET;\n lock.l_start = 0;\n lock.l_len = 0;\n lock.l_pid = 0;\n int result = fcntl(_file, F_OFD_SETLKW, &lock);\n if (result == -1)\n throwex FileSystemException(\"Failed to lock for read!\").Attach(_path);\n#elif defined(unix) || defined(__unix) || defined(__unix__)\n int result = flock(_file, LOCK_SH);\n if (result != 0)\n throwex FileSystemException(\"Failed to lock for read!\").Attach(_path);\n#endif\n }\n\n void LockWrite()\n {\n#if defined(_WIN32) || defined(_WIN64)\n OVERLAPPED overlapped;\n ZeroMemory(&overlapped, sizeof(OVERLAPPED));\n if (!LockFileEx(_file, LOCKFILE_EXCLUSIVE_LOCK, 0, MAXDWORD, MAXDWORD, &overlapped))\n throwex FileSystemException(\"Failed to lock for write!\").Attach(_path);\n#elif defined(linux) || defined(__linux) || defined(__linux__)\n struct flock lock;\n lock.l_type = F_WRLCK;\n lock.l_whence = SEEK_SET;\n lock.l_start = 0;\n lock.l_len = 0;\n lock.l_pid = 0;\n int result = fcntl(_file, F_OFD_SETLKW, &lock);\n if (result == -1)\n throwex FileSystemException(\"Failed to lock for write!\").Attach(_path);\n#elif defined(unix) || defined(__unix) || defined(__unix__)\n int result = flock(_file, LOCK_EX);\n if (result != 0)\n throwex FileSystemException(\"Failed to lock for write!\").Attach(_path);\n#endif\n }\n\n void UnlockRead()\n {\n#if defined(_WIN32) || defined(_WIN64)\n OVERLAPPED overlapped;\n ZeroMemory(&overlapped, sizeof(OVERLAPPED));\n if (!UnlockFileEx(_file, 0, MAXDWORD, MAXDWORD, &overlapped))\n throwex FileSystemException(\"Failed to unlock the read lock!\").Attach(_path);\n#elif defined(linux) || defined(__linux) || defined(__linux__)\n struct flock lock;\n lock.l_type = F_UNLCK;\n lock.l_whence = SEEK_SET;\n lock.l_start = 0;\n lock.l_len = 0;\n lock.l_pid = 0;\n int result = fcntl(_file, F_OFD_SETLK, &lock);\n if (result != 0)\n throwex FileSystemException(\"Failed to unlock the read lock!\").Attach(_path);\n#elif defined(unix) || defined(__unix) || defined(__unix__)\n int result = flock(_file, LOCK_UN);\n if (result != 0)\n throwex FileSystemException(\"Failed to unlock the read lock!\").Attach(_path);\n#endif\n }\n\n void UnlockWrite()\n {\n#if defined(_WIN32) || defined(_WIN64)\n OVERLAPPED overlapped;\n ZeroMemory(&overlapped, sizeof(OVERLAPPED));\n if (!UnlockFileEx(_file, 0, MAXDWORD, MAXDWORD, &overlapped))\n throwex FileSystemException(\"Failed to unlock the write lock!\").Attach(_path);\n#elif defined(linux) || defined(__linux) || defined(__linux__)\n struct flock lock;\n lock.l_type = F_UNLCK;\n lock.l_whence = SEEK_SET;\n lock.l_start = 0;\n lock.l_len = 0;\n lock.l_pid = 0;\n int result = fcntl(_file, F_OFD_SETLK, &lock);\n if (result != 0)\n throwex FileSystemException(\"Failed to unlock the write lock!\").Attach(_path);\n#elif defined(unix) || defined(__unix) || defined(__unix__)\n int result = flock(_file, LOCK_UN);\n if (result != 0)\n throwex FileSystemException(\"Failed to unlock the write lock!\").Attach(_path);\n#endif\n }\n\nprivate:\n Path _path;\n#if defined(_WIN32) || defined(_WIN64)\n HANDLE _file;\n#elif defined(unix) || defined(__unix) || defined(__unix__)\n int _file;\n#endif\n bool _owner;\n};\n\nFileLock::FileLock(const Path& path) : _pimpl(new Impl(path))\n{\n}\n\nFileLock::~FileLock()\n{\n}\n\nconst Path& FileLock::path() const noexcept\n{\n return _pimpl->path();\n}\n\nbool FileLock::TryLockRead()\n{\n return _pimpl->TryLockRead();\n}\n\nbool FileLock::TryLockWrite()\n{\n return _pimpl->TryLockWrite();\n}\n\nvoid FileLock::LockRead()\n{\n _pimpl->LockRead();\n}\n\nvoid FileLock::LockWrite()\n{\n _pimpl->LockWrite();\n}\n\nvoid FileLock::UnlockRead()\n{\n _pimpl->UnlockRead();\n}\n\nvoid FileLock::UnlockWrite()\n{\n _pimpl->UnlockWrite();\n}\n\n} \/\/ namespace CppCommon\n<|endoftext|>"} {"text":"\/*=========================================================================\n\n Program: Insight Segmentation & Registration Toolkit\n Module: itkFixedArrayTest.cxx\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n Copyright (c) Insight Software Consortium. All rights reserved.\n See ITKCopyright.txt or http:\/\/www.itk.org\/HTML\/Copyright.htm for details.\n\n This software is distributed WITHOUT ANY WARRANTY; without even \n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR \n PURPOSE. See the above copyright notices for more information.\n\n=========================================================================*\/\n#if defined(_MSC_VER)\n#pragma warning ( disable : 4786 )\n#endif\n\n#include \n\n#include \"itkFixedArray.h\"\n\n#ifndef ITK_EXPLICIT_INSTANTIATION\n\/\/ Explicit instantiation to make sure all methods are compiled.\ntemplate class itk::FixedArray;\n#endif\n\nvoid Set_c_Array(int x[3])\n{\n x[0] = 1;\n x[1] = 2;\n x[2] = 3;\n}\n\nvoid Print_Array(itk::FixedArray x, std::ostream& os)\n{\n os << '{' << x[0] << ',' << x[1] << ',' << x[2] << '}' << std::endl;\n}\n\nvoid Print_c_ArrayConst(const int x[3], std::ostream& os)\n{\n os << '{' << x[0] << ',' << x[1] << ',' << x[2] << '}' << std::endl;\n}\n\nvoid Print_Array5(itk::FixedArray x, std::ostream& os)\n{\n os << '{' << x[0] << ',' << x[1] << ',' << x[2] << ','\n << x[3] << ',' << x[4] << '}' << std::endl;\n}\n\nint itkFixedArrayTest(int, char* [] )\n{\n \/\/ Test out many combinations of using c-style arrays and FixedArray\n \n int c_Array1[3] = {0,0,0};\n \n Set_c_Array(c_Array1);\n Print_Array(c_Array1, std::cout);\n Print_c_ArrayConst(c_Array1, std::cout);\n\n int c_Array2[3] = {0,0,0};\n Print_Array(c_Array2, std::cout);\n \n int array3Init[3] = {4,4,4};\n itk::FixedArray array3 = array3Init;\n Print_Array(array3, std::cout);\n Print_c_ArrayConst(array3.GetDataPointer(), std::cout);\n\n Set_c_Array(array3.GetDataPointer());\n Print_Array(array3, std::cout);\n\n itk::FixedArray array4;\n array4.Fill(0);\n Print_Array(array4, std::cout);\n \n \/\/ Test operator!= and operator==\n if ( array4 != array4 ) return EXIT_FAILURE; \/\/should be equal\n if ( !(array4 == array4) ) return EXIT_FAILURE; \/\/should be equal\n\n \/\/ Test Get\/Set element\n const unsigned int n = 20;\n itk::FixedArray< unsigned int, n > array20;\n for(unsigned int i=0; i::Iterator it = array20.Begin();\" << std::endl;\n itk::FixedArray::Iterator it = array20.Begin();\n while (it != array20.End())\n {\n std::cout << *it << std::endl;\n ++it;\n }\n\n std::cout << \"FixedArray::Iterator it = array20.End();\" << std::endl;\n itk::FixedArray::Iterator bit = array20.End();\n while (--bit >= array20.Begin())\n {\n std::cout << *bit << std::endl;\n }\n\n std::cout << \"FixedArray::ConstIterator it = array20.Begin();\" << std::endl;\n itk::FixedArray::ConstIterator cit = array20.Begin();\n while (cit != array20.End())\n {\n std::cout << *cit << std::endl;\n ++cit;\n }\n\n \/\/ Try all index types\n#define TRY_INDEX_CONST(T) {T in = 10; if (array20[in] != 10) {std::cerr << \"index failed\" << std::endl; return EXIT_FAILURE;}}\n TRY_INDEX_CONST(short);\n TRY_INDEX_CONST(unsigned short);\n TRY_INDEX_CONST(int);\n TRY_INDEX_CONST(unsigned int);\n TRY_INDEX_CONST(long);\n TRY_INDEX_CONST(unsigned long);\n#define TRY_INDEX(T) {T in = 10; array20[in] = 10;}\n TRY_INDEX(short);\n TRY_INDEX(unsigned short);\n TRY_INDEX(int);\n TRY_INDEX(unsigned int);\n TRY_INDEX(long);\n TRY_INDEX(unsigned long);\n return EXIT_SUCCESS;\n}\nENH: cover the reverse iteartors.\/*=========================================================================\n\n Program: Insight Segmentation & Registration Toolkit\n Module: itkFixedArrayTest.cxx\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n Copyright (c) Insight Software Consortium. All rights reserved.\n See ITKCopyright.txt or http:\/\/www.itk.org\/HTML\/Copyright.htm for details.\n\n This software is distributed WITHOUT ANY WARRANTY; without even \n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR \n PURPOSE. See the above copyright notices for more information.\n\n=========================================================================*\/\n#if defined(_MSC_VER)\n#pragma warning ( disable : 4786 )\n#endif\n\n#include \n\n#include \"itkFixedArray.h\"\n\n#ifndef ITK_EXPLICIT_INSTANTIATION\n\/\/ Explicit instantiation to make sure all methods are compiled.\ntemplate class itk::FixedArray;\n#endif\n\nvoid Set_c_Array(int x[3])\n{\n x[0] = 1;\n x[1] = 2;\n x[2] = 3;\n}\n\nvoid Print_Array(itk::FixedArray x, std::ostream& os)\n{\n os << '{' << x[0] << ',' << x[1] << ',' << x[2] << '}' << std::endl;\n}\n\nvoid Print_c_ArrayConst(const int x[3], std::ostream& os)\n{\n os << '{' << x[0] << ',' << x[1] << ',' << x[2] << '}' << std::endl;\n}\n\nvoid Print_Array5(itk::FixedArray x, std::ostream& os)\n{\n os << '{' << x[0] << ',' << x[1] << ',' << x[2] << ','\n << x[3] << ',' << x[4] << '}' << std::endl;\n}\n\nint itkFixedArrayTest(int, char* [] )\n{\n \/\/ Test out many combinations of using c-style arrays and FixedArray\n \n int c_Array1[3] = {0,0,0};\n \n Set_c_Array(c_Array1);\n Print_Array(c_Array1, std::cout);\n Print_c_ArrayConst(c_Array1, std::cout);\n\n int c_Array2[3] = {0,0,0};\n Print_Array(c_Array2, std::cout);\n \n int array3Init[3] = {4,4,4};\n itk::FixedArray array3 = array3Init;\n Print_Array(array3, std::cout);\n Print_c_ArrayConst(array3.GetDataPointer(), std::cout);\n\n Set_c_Array(array3.GetDataPointer());\n Print_Array(array3, std::cout);\n\n itk::FixedArray array4;\n array4.Fill(0);\n Print_Array(array4, std::cout);\n \n \/\/ Test operator!= and operator==\n if ( array4 != array4 ) return EXIT_FAILURE; \/\/should be equal\n if ( !(array4 == array4) ) return EXIT_FAILURE; \/\/should be equal\n\n \/\/ Test Get\/Set element\n const unsigned int n = 20;\n itk::FixedArray< unsigned int, n > array20;\n for(unsigned int i=0; i::Iterator it = array20.Begin();\" << std::endl;\n itk::FixedArray::Iterator it = array20.Begin();\n while (it != array20.End())\n {\n std::cout << *it << std::endl;\n ++it;\n }\n\n std::cout << \"FixedArray::Iterator it = array20.End();\" << std::endl;\n itk::FixedArray::Iterator bit = array20.End();\n while (--bit >= array20.Begin())\n {\n std::cout << *bit << std::endl;\n }\n\n std::cout << \"FixedArray::ConstIterator it = array20.Begin();\" << std::endl;\n itk::FixedArray::ConstIterator cit = array20.Begin();\n while (cit != array20.End())\n {\n std::cout << *cit << std::endl;\n ++cit;\n }\n\n std::cout << \"FixedArray::ReverseIterator rit = array20.rBegin();\" << std::endl;\n itk::FixedArray::ReverseIterator rit = array20.rBegin();\n while (rit != array20.rEnd())\n {\n std::cout << *rit << std::endl;\n ++rit;\n }\n\n std::cout << \"FixedArray::ConstReverseIterator crit = array20.rBegin();\" << std::endl;\n itk::FixedArray::ConstReverseIterator crit = array20.rBegin();\n while (crit != array20.rEnd())\n {\n std::cout << *crit << std::endl;\n ++crit;\n }\n\n \/\/ Try all index types\n#define TRY_INDEX_CONST(T) {T in = 10; if (array20[in] != 10) {std::cerr << \"index failed\" << std::endl; return EXIT_FAILURE;}}\n TRY_INDEX_CONST(short);\n TRY_INDEX_CONST(unsigned short);\n TRY_INDEX_CONST(int);\n TRY_INDEX_CONST(unsigned int);\n TRY_INDEX_CONST(long);\n TRY_INDEX_CONST(unsigned long);\n#define TRY_INDEX(T) {T in = 10; array20[in] = 10;}\n TRY_INDEX(short);\n TRY_INDEX(unsigned short);\n TRY_INDEX(int);\n TRY_INDEX(unsigned int);\n TRY_INDEX(long);\n TRY_INDEX(unsigned long);\n return EXIT_SUCCESS;\n}\n<|endoftext|>"} {"text":"\/*=========================================================================\n\n Program: ORFEO Toolbox\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n\n Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.\n See OTBCopyright.txt for details.\n\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notices for more information.\n\n=========================================================================*\/\n\n#include \"otbCartographicRegion.h\"\n\n\nint otbCartoRegionNew(int argc, char * argv[])\n{\n \n typedef double Type;\n typedef otb::CartographicRegion TypedRegion;\n \n TypedRegion Cartoregion();\n \n return EXIT_SUCCESS;\n}\n\nCOMP: Suppress warning in CartoRegionNew testing\/*=========================================================================\n\n Program: ORFEO Toolbox\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n\n Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.\n See OTBCopyright.txt for details.\n\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notices for more information.\n\n=========================================================================*\/\n\n#include \"otbCartographicRegion.h\"\n\n\nint otbCartoRegionNew(int argc, char * argv[])\n{\n \n typedef double Type;\n typedef otb::CartographicRegion TypedRegion;\n \n TypedRegion Cartoregion;\n \n return EXIT_SUCCESS;\n}\n\n<|endoftext|>"} {"text":"\/*! \\file tracking.hpp\n \\brief The Object and Feature Tracking\n *\/\n\n\/*M\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.\n\/\/\n\/\/ By downloading, copying, installing or using the software you agree to this license.\n\/\/ If you do not agree to this license, do not download, install,\n\/\/ copy or use the software.\n\/\/\n\/\/\n\/\/ License Agreement\n\/\/ For Open Source Computer Vision Library\n\/\/\n\/\/ Copyright (C) 2000-2008, Intel Corporation, all rights reserved.\n\/\/ Copyright (C) 2009, Willow Garage Inc., all rights reserved.\n\/\/ Third party copyrights are property of their respective owners.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without modification,\n\/\/ are permitted provided that the following conditions are met:\n\/\/\n\/\/ * Redistribution's of source code must retain the above copyright notice,\n\/\/ this list of conditions and the following disclaimer.\n\/\/\n\/\/ * Redistribution's in binary form must reproduce the above copyright notice,\n\/\/ this list of conditions and the following disclaimer in the documentation\n\/\/ and\/or other materials provided with the distribution.\n\/\/\n\/\/ * The name of the copyright holders may not be used to endorse or promote products\n\/\/ derived from this software without specific prior written permission.\n\/\/\n\/\/ This software is provided by the copyright holders and contributors \"as is\" and\n\/\/ any express or implied warranties, including, but not limited to, the implied\n\/\/ warranties of merchantability and fitness for a particular purpose are disclaimed.\n\/\/ In no event shall the Intel Corporation or contributors be liable for any direct,\n\/\/ indirect, incidental, special, exemplary, or consequential damages\n\/\/ (including, but not limited to, procurement of substitute goods or services;\n\/\/ loss of use, data, or profits; or business interruption) however caused\n\/\/ and on any theory of liability, whether in contract, strict liability,\n\/\/ or tort (including negligence or otherwise) arising in any way out of\n\/\/ the use of this software, even if advised of the possibility of such damage.\n\/\/\n\/\/M*\/\n\n#ifndef __OPENCV_TRACKING_HPP__\n#define __OPENCV_TRACKING_HPP__\n\n#include \"opencv2\/core\/core.hpp\"\n#include \"opencv2\/imgproc\/imgproc_c.h\"\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n\/****************************************************************************************\\\n* Motion Analysis *\n\\****************************************************************************************\/\n\n\/************************************ optical flow ***************************************\/\n\n#define CV_LKFLOW_PYR_A_READY 1\n#define CV_LKFLOW_PYR_B_READY 2\n#define CV_LKFLOW_INITIAL_GUESSES 4\n#define CV_LKFLOW_GET_MIN_EIGENVALS 8\n\n\/* It is Lucas & Kanade method, modified to use pyramids.\n Also it does several iterations to get optical flow for\n every point at every pyramid level.\n Calculates optical flow between two images for certain set of points (i.e.\n it is a \"sparse\" optical flow, which is opposite to the previous 3 methods) *\/\nCVAPI(void) cvCalcOpticalFlowPyrLK( const CvArr* prev, const CvArr* curr,\n CvArr* prev_pyr, CvArr* curr_pyr,\n const CvPoint2D32f* prev_features,\n CvPoint2D32f* curr_features,\n int count,\n CvSize win_size,\n int level,\n char* status,\n float* track_error,\n CvTermCriteria criteria,\n int flags );\n\n\n\/* Modification of a previous sparse optical flow algorithm to calculate\n affine flow *\/\nCVAPI(void) cvCalcAffineFlowPyrLK( const CvArr* prev, const CvArr* curr,\n CvArr* prev_pyr, CvArr* curr_pyr,\n const CvPoint2D32f* prev_features,\n CvPoint2D32f* curr_features,\n float* matrices, int count,\n CvSize win_size, int level,\n char* status, float* track_error,\n CvTermCriteria criteria, int flags );\n\n\/* Estimate rigid transformation between 2 images or 2 point sets *\/\nCVAPI(int) cvEstimateRigidTransform( const CvArr* A, const CvArr* B,\n CvMat* M, int full_affine );\n\n\/* Estimate optical flow for each pixel using the two-frame G. Farneback algorithm *\/\nCVAPI(void) cvCalcOpticalFlowFarneback( const CvArr* prev, const CvArr* next,\n CvArr* flow, double pyr_scale, int levels,\n int winsize, int iterations, int poly_n,\n double poly_sigma, int flags );\n\n\/********************************* motion templates *************************************\/\n\n\/****************************************************************************************\\\n* All the motion template functions work only with single channel images. *\n* Silhouette image must have depth IPL_DEPTH_8U or IPL_DEPTH_8S *\n* Motion history image must have depth IPL_DEPTH_32F, *\n* Gradient mask - IPL_DEPTH_8U or IPL_DEPTH_8S, *\n* Motion orientation image - IPL_DEPTH_32F *\n* Segmentation mask - IPL_DEPTH_32F *\n* All the angles are in degrees, all the times are in milliseconds *\n\\****************************************************************************************\/\n\n\/* Updates motion history image given motion silhouette *\/\nCVAPI(void) cvUpdateMotionHistory( const CvArr* silhouette, CvArr* mhi,\n double timestamp, double duration );\n\n\/* Calculates gradient of the motion history image and fills\n a mask indicating where the gradient is valid *\/\nCVAPI(void) cvCalcMotionGradient( const CvArr* mhi, CvArr* mask, CvArr* orientation,\n double delta1, double delta2,\n int aperture_size CV_DEFAULT(3));\n\n\/* Calculates average motion direction within a selected motion region\n (region can be selected by setting ROIs and\/or by composing a valid gradient mask\n with the region mask) *\/\nCVAPI(double) cvCalcGlobalOrientation( const CvArr* orientation, const CvArr* mask,\n const CvArr* mhi, double timestamp,\n double duration );\n\n\/* Splits a motion history image into a few parts corresponding to separate independent motions\n (e.g. left hand, right hand) *\/\nCVAPI(CvSeq*) cvSegmentMotion( const CvArr* mhi, CvArr* seg_mask,\n CvMemStorage* storage,\n double timestamp, double seg_thresh );\n\n\/****************************************************************************************\\\n* Tracking *\n\\****************************************************************************************\/\n\n\/* Implements CAMSHIFT algorithm - determines object position, size and orientation\n from the object histogram back project (extension of meanshift) *\/\nCVAPI(int) cvCamShift( const CvArr* prob_image, CvRect window,\n CvTermCriteria criteria, CvConnectedComp* comp,\n CvBox2D* box CV_DEFAULT(NULL) );\n\n\/* Implements MeanShift algorithm - determines object position\n from the object histogram back project *\/\nCVAPI(int) cvMeanShift( const CvArr* prob_image, CvRect window,\n CvTermCriteria criteria, CvConnectedComp* comp );\n\n\/*\nstandard Kalman filter (in G. Welch' and G. Bishop's notation):\n\n x(k)=A*x(k-1)+B*u(k)+w(k) p(w)~N(0,Q)\n z(k)=H*x(k)+v(k), p(v)~N(0,R)\n*\/\ntypedef struct CvKalman\n{\n int MP; \/* number of measurement vector dimensions *\/\n int DP; \/* number of state vector dimensions *\/\n int CP; \/* number of control vector dimensions *\/\n\n \/* backward compatibility fields *\/\n#if 1\n float* PosterState; \/* =state_pre->data.fl *\/\n float* PriorState; \/* =state_post->data.fl *\/\n float* DynamMatr; \/* =transition_matrix->data.fl *\/\n float* MeasurementMatr; \/* =measurement_matrix->data.fl *\/\n float* MNCovariance; \/* =measurement_noise_cov->data.fl *\/\n float* PNCovariance; \/* =process_noise_cov->data.fl *\/\n float* KalmGainMatr; \/* =gain->data.fl *\/\n float* PriorErrorCovariance;\/* =error_cov_pre->data.fl *\/\n float* PosterErrorCovariance;\/* =error_cov_post->data.fl *\/\n float* Temp1; \/* temp1->data.fl *\/\n float* Temp2; \/* temp2->data.fl *\/\n#endif\n\n CvMat* state_pre; \/* predicted state (x'(k)):\n x(k)=A*x(k-1)+B*u(k) *\/\n CvMat* state_post; \/* corrected state (x(k)):\n x(k)=x'(k)+K(k)*(z(k)-H*x'(k)) *\/\n CvMat* transition_matrix; \/* state transition matrix (A) *\/\n CvMat* control_matrix; \/* control matrix (B)\n (it is not used if there is no control)*\/\n CvMat* measurement_matrix; \/* measurement matrix (H) *\/\n CvMat* process_noise_cov; \/* process noise covariance matrix (Q) *\/\n CvMat* measurement_noise_cov; \/* measurement noise covariance matrix (R) *\/\n CvMat* error_cov_pre; \/* priori error estimate covariance matrix (P'(k)):\n P'(k)=A*P(k-1)*At + Q)*\/\n CvMat* gain; \/* Kalman gain matrix (K(k)):\n K(k)=P'(k)*Ht*inv(H*P'(k)*Ht+R)*\/\n CvMat* error_cov_post; \/* posteriori error estimate covariance matrix (P(k)):\n P(k)=(I-K(k)*H)*P'(k) *\/\n CvMat* temp1; \/* temporary matrices *\/\n CvMat* temp2;\n CvMat* temp3;\n CvMat* temp4;\n CvMat* temp5;\n} CvKalman;\n\n\/* Creates Kalman filter and sets A, B, Q, R and state to some initial values *\/\nCVAPI(CvKalman*) cvCreateKalman( int dynam_params, int measure_params,\n int control_params CV_DEFAULT(0));\n\n\/* Releases Kalman filter state *\/\nCVAPI(void) cvReleaseKalman( CvKalman** kalman);\n\n\/* Updates Kalman filter by time (predicts future state of the system) *\/\nCVAPI(const CvMat*) cvKalmanPredict( CvKalman* kalman,\n const CvMat* control CV_DEFAULT(NULL));\n\n\/* Updates Kalman filter by measurement\n (corrects state of the system and internal matrices) *\/\nCVAPI(const CvMat*) cvKalmanCorrect( CvKalman* kalman, const CvMat* measurement );\n\n#define cvKalmanUpdateByTime cvKalmanPredict\n#define cvKalmanUpdateByMeasurement cvKalmanCorrect\n \n#ifdef __cplusplus\n}\n\nnamespace cv\n{\n \n\/\/! updates motion history image using the current silhouette\nCV_EXPORTS_W void updateMotionHistory( InputArray silhouette, InputOutputArray mhi,\n double timestamp, double duration );\n\n\/\/! computes the motion gradient orientation image from the motion history image\nCV_EXPORTS_W void calcMotionGradient( InputArray mhi, OutputArray mask,\n OutputArray orientation,\n double delta1, double delta2,\n int apertureSize=3 );\n\n\/\/! computes the global orientation of the selected motion history image part\nCV_EXPORTS_W double calcGlobalOrientation( InputArray orientation, InputArray mask,\n InputArray mhi, double timestamp,\n double duration );\n\nCV_EXPORTS_W void segmentMotion(InputArray mhi, OutputArray segmask,\n CV_OUT vector& boundingRects,\n double timestamp, double segThresh);\n\n\/\/! updates the object tracking window using CAMSHIFT algorithm\nCV_EXPORTS_W RotatedRect CamShift( InputArray probImage, CV_OUT CV_IN_OUT Rect& window,\n TermCriteria criteria );\n\n\/\/! updates the object tracking window using meanshift algorithm\nCV_EXPORTS_W int meanShift( InputArray probImage, CV_OUT CV_IN_OUT Rect& window,\n TermCriteria criteria );\n\n\/*!\n Kalman filter.\n \n The class implements standard Kalman filter \\url{http:\/\/en.wikipedia.org\/wiki\/Kalman_filter}.\n However, you can modify KalmanFilter::transitionMatrix, KalmanFilter::controlMatrix and\n KalmanFilter::measurementMatrix to get the extended Kalman filter functionality.\n*\/\nclass CV_EXPORTS_W KalmanFilter\n{\npublic:\n \/\/! the default constructor\n CV_WRAP KalmanFilter();\n \/\/! the full constructor taking the dimensionality of the state, of the measurement and of the control vector\n CV_WRAP KalmanFilter(int dynamParams, int measureParams, int controlParams=0, int type=CV_32F);\n \/\/! re-initializes Kalman filter. The previous content is destroyed.\n void init(int dynamParams, int measureParams, int controlParams=0, int type=CV_32F);\n\n \/\/! computes predicted state\n CV_WRAP const Mat& predict(const Mat& control=Mat());\n \/\/! updates the predicted state from the measurement\n CV_WRAP const Mat& correct(const Mat& measurement);\n\n Mat statePre; \/\/!< predicted state (x'(k)): x(k)=A*x(k-1)+B*u(k)\n Mat statePost; \/\/!< corrected state (x(k)): x(k)=x'(k)+K(k)*(z(k)-H*x'(k))\n Mat transitionMatrix; \/\/!< state transition matrix (A)\n Mat controlMatrix; \/\/!< control matrix (B) (not used if there is no control)\n Mat measurementMatrix; \/\/!< measurement matrix (H)\n Mat processNoiseCov; \/\/!< process noise covariance matrix (Q)\n Mat measurementNoiseCov;\/\/!< measurement noise covariance matrix (R)\n Mat errorCovPre; \/\/!< priori error estimate covariance matrix (P'(k)): P'(k)=A*P(k-1)*At + Q)*\/\n Mat gain; \/\/!< Kalman gain matrix (K(k)): K(k)=P'(k)*Ht*inv(H*P'(k)*Ht+R)\n Mat errorCovPost; \/\/!< posteriori error estimate covariance matrix (P(k)): P(k)=(I-K(k)*H)*P'(k)\n \n \/\/ temporary matrices\n Mat temp1;\n Mat temp2;\n Mat temp3;\n Mat temp4;\n Mat temp5;\n};\n\n\nenum { OPTFLOW_USE_INITIAL_FLOW=4, OPTFLOW_FARNEBACK_GAUSSIAN=256 };\n\n\/\/! computes sparse optical flow using multi-scale Lucas-Kanade algorithm\nCV_EXPORTS_W void calcOpticalFlowPyrLK( InputArray prevImg, InputArray nextImg,\n InputArray prevPts, CV_OUT InputOutputArray nextPts,\n OutputArray status, OutputArray err,\n Size winSize=Size(21,21), int maxLevel=3,\n TermCriteria criteria=TermCriteria(\n TermCriteria::COUNT+TermCriteria::EPS,\n 30, 0.01),\n int flags=0,\n double minEigThreshold=1e-4);\n\n\/\/! computes dense optical flow using Farneback algorithm\nCV_EXPORTS_W void calcOpticalFlowFarneback( InputArray prev, InputArray next,\n CV_OUT InputOutputArray flow, double pyr_scale, int levels, int winsize,\n int iterations, int poly_n, double poly_sigma, int flags );\n\n\/\/! estimates the best-fit Euqcidean, similarity, affine or perspective transformation\n\/\/ that maps one 2D point set to another or one image to another.\nCV_EXPORTS_W Mat estimateRigidTransform( InputArray src, InputArray dst,\n bool fullAffine);\n \n}\n\n#endif\n\n#endif\nAdded OPTFLOW_LK_GET_MIN_EIGENVALS flag as alias for CV_LKFLOW_GET_MIN_EIGENVALS.\/*! \\file tracking.hpp\n \\brief The Object and Feature Tracking\n *\/\n\n\/*M\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.\n\/\/\n\/\/ By downloading, copying, installing or using the software you agree to this license.\n\/\/ If you do not agree to this license, do not download, install,\n\/\/ copy or use the software.\n\/\/\n\/\/\n\/\/ License Agreement\n\/\/ For Open Source Computer Vision Library\n\/\/\n\/\/ Copyright (C) 2000-2008, Intel Corporation, all rights reserved.\n\/\/ Copyright (C) 2009, Willow Garage Inc., all rights reserved.\n\/\/ Third party copyrights are property of their respective owners.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without modification,\n\/\/ are permitted provided that the following conditions are met:\n\/\/\n\/\/ * Redistribution's of source code must retain the above copyright notice,\n\/\/ this list of conditions and the following disclaimer.\n\/\/\n\/\/ * Redistribution's in binary form must reproduce the above copyright notice,\n\/\/ this list of conditions and the following disclaimer in the documentation\n\/\/ and\/or other materials provided with the distribution.\n\/\/\n\/\/ * The name of the copyright holders may not be used to endorse or promote products\n\/\/ derived from this software without specific prior written permission.\n\/\/\n\/\/ This software is provided by the copyright holders and contributors \"as is\" and\n\/\/ any express or implied warranties, including, but not limited to, the implied\n\/\/ warranties of merchantability and fitness for a particular purpose are disclaimed.\n\/\/ In no event shall the Intel Corporation or contributors be liable for any direct,\n\/\/ indirect, incidental, special, exemplary, or consequential damages\n\/\/ (including, but not limited to, procurement of substitute goods or services;\n\/\/ loss of use, data, or profits; or business interruption) however caused\n\/\/ and on any theory of liability, whether in contract, strict liability,\n\/\/ or tort (including negligence or otherwise) arising in any way out of\n\/\/ the use of this software, even if advised of the possibility of such damage.\n\/\/\n\/\/M*\/\n\n#ifndef __OPENCV_TRACKING_HPP__\n#define __OPENCV_TRACKING_HPP__\n\n#include \"opencv2\/core\/core.hpp\"\n#include \"opencv2\/imgproc\/imgproc_c.h\"\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n\/****************************************************************************************\\\n* Motion Analysis *\n\\****************************************************************************************\/\n\n\/************************************ optical flow ***************************************\/\n\n#define CV_LKFLOW_PYR_A_READY 1\n#define CV_LKFLOW_PYR_B_READY 2\n#define CV_LKFLOW_INITIAL_GUESSES 4\n#define CV_LKFLOW_GET_MIN_EIGENVALS 8\n\n\/* It is Lucas & Kanade method, modified to use pyramids.\n Also it does several iterations to get optical flow for\n every point at every pyramid level.\n Calculates optical flow between two images for certain set of points (i.e.\n it is a \"sparse\" optical flow, which is opposite to the previous 3 methods) *\/\nCVAPI(void) cvCalcOpticalFlowPyrLK( const CvArr* prev, const CvArr* curr,\n CvArr* prev_pyr, CvArr* curr_pyr,\n const CvPoint2D32f* prev_features,\n CvPoint2D32f* curr_features,\n int count,\n CvSize win_size,\n int level,\n char* status,\n float* track_error,\n CvTermCriteria criteria,\n int flags );\n\n\n\/* Modification of a previous sparse optical flow algorithm to calculate\n affine flow *\/\nCVAPI(void) cvCalcAffineFlowPyrLK( const CvArr* prev, const CvArr* curr,\n CvArr* prev_pyr, CvArr* curr_pyr,\n const CvPoint2D32f* prev_features,\n CvPoint2D32f* curr_features,\n float* matrices, int count,\n CvSize win_size, int level,\n char* status, float* track_error,\n CvTermCriteria criteria, int flags );\n\n\/* Estimate rigid transformation between 2 images or 2 point sets *\/\nCVAPI(int) cvEstimateRigidTransform( const CvArr* A, const CvArr* B,\n CvMat* M, int full_affine );\n\n\/* Estimate optical flow for each pixel using the two-frame G. Farneback algorithm *\/\nCVAPI(void) cvCalcOpticalFlowFarneback( const CvArr* prev, const CvArr* next,\n CvArr* flow, double pyr_scale, int levels,\n int winsize, int iterations, int poly_n,\n double poly_sigma, int flags );\n\n\/********************************* motion templates *************************************\/\n\n\/****************************************************************************************\\\n* All the motion template functions work only with single channel images. *\n* Silhouette image must have depth IPL_DEPTH_8U or IPL_DEPTH_8S *\n* Motion history image must have depth IPL_DEPTH_32F, *\n* Gradient mask - IPL_DEPTH_8U or IPL_DEPTH_8S, *\n* Motion orientation image - IPL_DEPTH_32F *\n* Segmentation mask - IPL_DEPTH_32F *\n* All the angles are in degrees, all the times are in milliseconds *\n\\****************************************************************************************\/\n\n\/* Updates motion history image given motion silhouette *\/\nCVAPI(void) cvUpdateMotionHistory( const CvArr* silhouette, CvArr* mhi,\n double timestamp, double duration );\n\n\/* Calculates gradient of the motion history image and fills\n a mask indicating where the gradient is valid *\/\nCVAPI(void) cvCalcMotionGradient( const CvArr* mhi, CvArr* mask, CvArr* orientation,\n double delta1, double delta2,\n int aperture_size CV_DEFAULT(3));\n\n\/* Calculates average motion direction within a selected motion region\n (region can be selected by setting ROIs and\/or by composing a valid gradient mask\n with the region mask) *\/\nCVAPI(double) cvCalcGlobalOrientation( const CvArr* orientation, const CvArr* mask,\n const CvArr* mhi, double timestamp,\n double duration );\n\n\/* Splits a motion history image into a few parts corresponding to separate independent motions\n (e.g. left hand, right hand) *\/\nCVAPI(CvSeq*) cvSegmentMotion( const CvArr* mhi, CvArr* seg_mask,\n CvMemStorage* storage,\n double timestamp, double seg_thresh );\n\n\/****************************************************************************************\\\n* Tracking *\n\\****************************************************************************************\/\n\n\/* Implements CAMSHIFT algorithm - determines object position, size and orientation\n from the object histogram back project (extension of meanshift) *\/\nCVAPI(int) cvCamShift( const CvArr* prob_image, CvRect window,\n CvTermCriteria criteria, CvConnectedComp* comp,\n CvBox2D* box CV_DEFAULT(NULL) );\n\n\/* Implements MeanShift algorithm - determines object position\n from the object histogram back project *\/\nCVAPI(int) cvMeanShift( const CvArr* prob_image, CvRect window,\n CvTermCriteria criteria, CvConnectedComp* comp );\n\n\/*\nstandard Kalman filter (in G. Welch' and G. Bishop's notation):\n\n x(k)=A*x(k-1)+B*u(k)+w(k) p(w)~N(0,Q)\n z(k)=H*x(k)+v(k), p(v)~N(0,R)\n*\/\ntypedef struct CvKalman\n{\n int MP; \/* number of measurement vector dimensions *\/\n int DP; \/* number of state vector dimensions *\/\n int CP; \/* number of control vector dimensions *\/\n\n \/* backward compatibility fields *\/\n#if 1\n float* PosterState; \/* =state_pre->data.fl *\/\n float* PriorState; \/* =state_post->data.fl *\/\n float* DynamMatr; \/* =transition_matrix->data.fl *\/\n float* MeasurementMatr; \/* =measurement_matrix->data.fl *\/\n float* MNCovariance; \/* =measurement_noise_cov->data.fl *\/\n float* PNCovariance; \/* =process_noise_cov->data.fl *\/\n float* KalmGainMatr; \/* =gain->data.fl *\/\n float* PriorErrorCovariance;\/* =error_cov_pre->data.fl *\/\n float* PosterErrorCovariance;\/* =error_cov_post->data.fl *\/\n float* Temp1; \/* temp1->data.fl *\/\n float* Temp2; \/* temp2->data.fl *\/\n#endif\n\n CvMat* state_pre; \/* predicted state (x'(k)):\n x(k)=A*x(k-1)+B*u(k) *\/\n CvMat* state_post; \/* corrected state (x(k)):\n x(k)=x'(k)+K(k)*(z(k)-H*x'(k)) *\/\n CvMat* transition_matrix; \/* state transition matrix (A) *\/\n CvMat* control_matrix; \/* control matrix (B)\n (it is not used if there is no control)*\/\n CvMat* measurement_matrix; \/* measurement matrix (H) *\/\n CvMat* process_noise_cov; \/* process noise covariance matrix (Q) *\/\n CvMat* measurement_noise_cov; \/* measurement noise covariance matrix (R) *\/\n CvMat* error_cov_pre; \/* priori error estimate covariance matrix (P'(k)):\n P'(k)=A*P(k-1)*At + Q)*\/\n CvMat* gain; \/* Kalman gain matrix (K(k)):\n K(k)=P'(k)*Ht*inv(H*P'(k)*Ht+R)*\/\n CvMat* error_cov_post; \/* posteriori error estimate covariance matrix (P(k)):\n P(k)=(I-K(k)*H)*P'(k) *\/\n CvMat* temp1; \/* temporary matrices *\/\n CvMat* temp2;\n CvMat* temp3;\n CvMat* temp4;\n CvMat* temp5;\n} CvKalman;\n\n\/* Creates Kalman filter and sets A, B, Q, R and state to some initial values *\/\nCVAPI(CvKalman*) cvCreateKalman( int dynam_params, int measure_params,\n int control_params CV_DEFAULT(0));\n\n\/* Releases Kalman filter state *\/\nCVAPI(void) cvReleaseKalman( CvKalman** kalman);\n\n\/* Updates Kalman filter by time (predicts future state of the system) *\/\nCVAPI(const CvMat*) cvKalmanPredict( CvKalman* kalman,\n const CvMat* control CV_DEFAULT(NULL));\n\n\/* Updates Kalman filter by measurement\n (corrects state of the system and internal matrices) *\/\nCVAPI(const CvMat*) cvKalmanCorrect( CvKalman* kalman, const CvMat* measurement );\n\n#define cvKalmanUpdateByTime cvKalmanPredict\n#define cvKalmanUpdateByMeasurement cvKalmanCorrect\n \n#ifdef __cplusplus\n}\n\nnamespace cv\n{\n \n\/\/! updates motion history image using the current silhouette\nCV_EXPORTS_W void updateMotionHistory( InputArray silhouette, InputOutputArray mhi,\n double timestamp, double duration );\n\n\/\/! computes the motion gradient orientation image from the motion history image\nCV_EXPORTS_W void calcMotionGradient( InputArray mhi, OutputArray mask,\n OutputArray orientation,\n double delta1, double delta2,\n int apertureSize=3 );\n\n\/\/! computes the global orientation of the selected motion history image part\nCV_EXPORTS_W double calcGlobalOrientation( InputArray orientation, InputArray mask,\n InputArray mhi, double timestamp,\n double duration );\n\nCV_EXPORTS_W void segmentMotion(InputArray mhi, OutputArray segmask,\n CV_OUT vector& boundingRects,\n double timestamp, double segThresh);\n\n\/\/! updates the object tracking window using CAMSHIFT algorithm\nCV_EXPORTS_W RotatedRect CamShift( InputArray probImage, CV_OUT CV_IN_OUT Rect& window,\n TermCriteria criteria );\n\n\/\/! updates the object tracking window using meanshift algorithm\nCV_EXPORTS_W int meanShift( InputArray probImage, CV_OUT CV_IN_OUT Rect& window,\n TermCriteria criteria );\n\n\/*!\n Kalman filter.\n \n The class implements standard Kalman filter \\url{http:\/\/en.wikipedia.org\/wiki\/Kalman_filter}.\n However, you can modify KalmanFilter::transitionMatrix, KalmanFilter::controlMatrix and\n KalmanFilter::measurementMatrix to get the extended Kalman filter functionality.\n*\/\nclass CV_EXPORTS_W KalmanFilter\n{\npublic:\n \/\/! the default constructor\n CV_WRAP KalmanFilter();\n \/\/! the full constructor taking the dimensionality of the state, of the measurement and of the control vector\n CV_WRAP KalmanFilter(int dynamParams, int measureParams, int controlParams=0, int type=CV_32F);\n \/\/! re-initializes Kalman filter. The previous content is destroyed.\n void init(int dynamParams, int measureParams, int controlParams=0, int type=CV_32F);\n\n \/\/! computes predicted state\n CV_WRAP const Mat& predict(const Mat& control=Mat());\n \/\/! updates the predicted state from the measurement\n CV_WRAP const Mat& correct(const Mat& measurement);\n\n Mat statePre; \/\/!< predicted state (x'(k)): x(k)=A*x(k-1)+B*u(k)\n Mat statePost; \/\/!< corrected state (x(k)): x(k)=x'(k)+K(k)*(z(k)-H*x'(k))\n Mat transitionMatrix; \/\/!< state transition matrix (A)\n Mat controlMatrix; \/\/!< control matrix (B) (not used if there is no control)\n Mat measurementMatrix; \/\/!< measurement matrix (H)\n Mat processNoiseCov; \/\/!< process noise covariance matrix (Q)\n Mat measurementNoiseCov;\/\/!< measurement noise covariance matrix (R)\n Mat errorCovPre; \/\/!< priori error estimate covariance matrix (P'(k)): P'(k)=A*P(k-1)*At + Q)*\/\n Mat gain; \/\/!< Kalman gain matrix (K(k)): K(k)=P'(k)*Ht*inv(H*P'(k)*Ht+R)\n Mat errorCovPost; \/\/!< posteriori error estimate covariance matrix (P(k)): P(k)=(I-K(k)*H)*P'(k)\n \n \/\/ temporary matrices\n Mat temp1;\n Mat temp2;\n Mat temp3;\n Mat temp4;\n Mat temp5;\n};\n\nenum\n{\n OPTFLOW_USE_INITIAL_FLOW = CV_LKFLOW_INITIAL_GUESSES,\n OPTFLOW_LK_GET_MIN_EIGENVALS = CV_LKFLOW_GET_MIN_EIGENVALS,\n OPTFLOW_FARNEBACK_GAUSSIAN = 256\n};\n\n\/\/! computes sparse optical flow using multi-scale Lucas-Kanade algorithm\nCV_EXPORTS_W void calcOpticalFlowPyrLK( InputArray prevImg, InputArray nextImg,\n InputArray prevPts, CV_OUT InputOutputArray nextPts,\n OutputArray status, OutputArray err,\n Size winSize=Size(21,21), int maxLevel=3,\n TermCriteria criteria=TermCriteria(\n TermCriteria::COUNT+TermCriteria::EPS,\n 30, 0.01),\n int flags=0,\n double minEigThreshold=1e-4);\n\n\/\/! computes dense optical flow using Farneback algorithm\nCV_EXPORTS_W void calcOpticalFlowFarneback( InputArray prev, InputArray next,\n CV_OUT InputOutputArray flow, double pyr_scale, int levels, int winsize,\n int iterations, int poly_n, double poly_sigma, int flags );\n\n\/\/! estimates the best-fit Euqcidean, similarity, affine or perspective transformation\n\/\/ that maps one 2D point set to another or one image to another.\nCV_EXPORTS_W Mat estimateRigidTransform( InputArray src, InputArray dst,\n bool fullAffine);\n \n}\n\n#endif\n\n#endif\n<|endoftext|>"} {"text":"\/*-------------------------------------------------------------------------\n *\n * FILE\n *\tconnectionitf.cxx\n *\n * DESCRIPTION\n * implementation of the pqxx::ConnectionItf abstract base class.\n * pqxx::ConnectionItf encapsulates a frontend to backend connection\n *\n * Copyright (c) 2001-2003, Jeroen T. Vermeulen \n *\n *-------------------------------------------------------------------------\n *\/\n#include \n#include \n#include \n\n#include \"pqxx\/connectionitf.h\"\n#include \"pqxx\/result.h\"\n#include \"pqxx\/transaction.h\"\n#include \"pqxx\/trigger.h\"\n\n\nusing namespace PGSTD;\n\nnamespace\n{\n\n\/\/ Keep track of a pointer to be free()d automatically.\n\/\/ Ownership policy is simple: object dies when PQAlloc object's value does.\ntemplate class PQAlloc\n{\n T *m_Obj;\npublic:\n PQAlloc() : m_Obj(0) {}\n explicit PQAlloc(T *obj) : m_Obj(obj) {}\n ~PQAlloc() { close(); }\n\n PQAlloc &operator=(T *obj) throw ()\n { \n if (obj != m_Obj)\n {\n close();\n m_Obj = obj;\n }\n return *this;\n }\n\n operator bool() const throw () { return m_Obj != 0; }\n bool operator!() const throw () { return !m_Obj; }\n\n T *operator->() const\n {\n if (!m_Obj) throw logic_error(\"Null pointer dereferenced\");\n return m_Obj;\n }\n\n T &operator*() const { return *operator->(); }\n\n T *c_ptr() const throw () { return m_Obj; }\n\n void close() throw () { if (m_Obj) freemem(); m_Obj = 0; }\n\n void freemem() throw ()\n {\n#ifdef HAVE_PQFREEMEM\n PQfreemem(m_Obj);\n#else\n free(m_Obj);\n#endif\n }\n\nprivate:\n PQAlloc(const PQAlloc &);\t\t\/\/ Not allowed\n PQAlloc &operator=(const PQAlloc &);\t\/\/ Not allowed\n};\n}\n\n\nextern \"C\"\n{\n\/\/ Pass C-linkage notice processor call on to C++-linkage Noticer object. The\n\/\/ void * argument points to the Noticer.\nvoid pqxxNoticeCaller(void *arg, const char *Msg)\n{\n if (arg && Msg) (*static_cast(arg))(Msg);\n}\n}\n\n\npqxx::ConnectionItf::ConnectionItf(const string &ConnInfo) :\n m_ConnInfo(ConnInfo),\n m_Conn(0),\n m_Trans(),\n m_Noticer(),\n m_Trace(0)\n{\n}\n\n\npqxx::ConnectionItf::ConnectionItf(const char ConnInfo[]) :\n m_ConnInfo(ConnInfo ? ConnInfo : \"\"),\n m_Conn(0),\n m_Trans(),\n m_Noticer(),\n m_Trace(0)\n{\n}\n\n\nvoid pqxx::ConnectionItf::Connect() const\n{\n if (m_Conn) throw logic_error(\"libqxx internal error: spurious Connect()\");\n\n m_Conn = PQconnectdb(m_ConnInfo.c_str());\n\n if (!m_Conn)\n throw broken_connection();\n\n if (!is_open())\n {\n const string Msg( ErrMsg() );\n Disconnect();\n throw broken_connection(Msg);\n }\n\n if (Status() != CONNECTION_OK)\n {\n const string Msg( ErrMsg() );\n Disconnect();\n throw runtime_error(Msg);\n }\n\n SetupState();\n}\n\n\n\nvoid pqxx::ConnectionItf::Deactivate() const\n{\n if (m_Conn)\n {\n if (m_Trans.get())\n throw logic_error(\"Attempt to deactivate connection while transaction \"\n\t \"'\" + m_Trans.get()->Name() + \"' \"\n\t\t\t\"still open\");\n\n Disconnect();\n }\n}\n\n\nvoid pqxx::ConnectionItf::SetClientEncoding(const char Encoding[])\n{\n if (PQsetClientEncoding(m_Conn, Encoding) != 0)\n throw runtime_error(\"Could not set client encoding to \" +\n\t string(Encoding));\n}\n\n\n\/** Set up various parts of logical connection state that may need to be\n * recovered because the physical connection to the database was lost and is\n * being reset, or that may not have been initialized yet.\n *\/\nvoid pqxx::ConnectionItf::SetupState() const\n{\n if (!m_Conn) \n throw logic_error(\"libpqxx internal error: SetupState() on no connection\");\n\n if (m_Noticer.get())\n PQsetNoticeProcessor(m_Conn, pqxxNoticeCaller, m_Noticer.get());\n\n InternalSetTrace();\n\n \/\/ Reinstate all active triggers\n if (!m_Triggers.empty())\n {\n const TriggerList::const_iterator End = m_Triggers.end();\n string Last;\n for (TriggerList::const_iterator i = m_Triggers.begin(); i != End; ++i)\n {\n \/\/ m_Triggers can handle multiple Triggers waiting on the same event; \n \/\/ issue just one LISTEN for each event.\n if (i->first != Last)\n {\n Result R( PQexec(m_Conn, (\"LISTEN \" + i->first).c_str()) );\n R.CheckStatus();\n Last = i->first;\n }\n }\n }\n}\n\n\nvoid pqxx::ConnectionItf::Disconnect() const throw ()\n{\n if (m_Conn)\n {\n PQfinish(m_Conn);\n m_Conn = 0;\n }\n}\n\n\nbool pqxx::ConnectionItf::is_open() const\n{\n return m_Conn && (Status() != CONNECTION_BAD);\n}\n\n\nauto_ptr \npqxx::ConnectionItf::SetNoticer(auto_ptr N)\n{\n if (N.get()) PQsetNoticeProcessor(m_Conn, pqxxNoticeCaller, N.get());\n else PQsetNoticeProcessor(m_Conn, 0, 0);\n \n auto_ptr Old = m_Noticer;\n \/\/ TODO: Can this line fail? If yes, we'd be killing Old prematurely...\n m_Noticer = N;\n\n return Old;\n}\n\n\nvoid pqxx::ConnectionItf::ProcessNotice(const char msg[]) throw ()\n{\n if (msg)\n {\n \/\/ TODO: Find cleaner solution for default case!\n if (m_Noticer.get()) (*m_Noticer.get())(msg);\n else fputs(msg, stderr);\n }\n}\n\n\nvoid pqxx::ConnectionItf::Trace(FILE *Out)\n{\n m_Trace = Out;\n if (m_Conn) InternalSetTrace();\n}\n\n\nvoid pqxx::ConnectionItf::AddTrigger(pqxx::Trigger *T)\n{\n if (!T) throw invalid_argument(\"Null trigger registered\");\n\n \/\/ Add to triggers list and attempt to start listening.\n const TriggerList::iterator p = m_Triggers.find(T->Name());\n const TriggerList::value_type NewVal(T->Name(), T);\n\n if (m_Conn && (p == m_Triggers.end()))\n {\n \/\/ Not listening on this event yet, start doing so.\n \/\/\n Result R( PQexec(m_Conn, (\"LISTEN \" + string(T->Name())).c_str()) );\n\n try\n {\n R.CheckStatus();\n }\n catch (const broken_connection &)\n {\n }\n catch (const exception &)\n {\n if (is_open()) throw;\n }\n m_Triggers.insert(NewVal);\n }\n else\n {\n m_Triggers.insert(p, NewVal);\n }\n\n}\n\n\nvoid pqxx::ConnectionItf::RemoveTrigger(pqxx::Trigger *T) throw ()\n{\n if (!T) return;\n\n try\n {\n \/\/ Keep Sun compiler happy... Hope it doesn't annoy other compilers\n pair tmp_pair(T->Name(), T);\n TriggerList::value_type E = tmp_pair;\n\n typedef pair Range;\n Range R = m_Triggers.equal_range(E.first);\n\n const TriggerList::iterator i = find(R.first, R.second, E);\n\n if (i == R.second) \n {\n ProcessNotice(\"Attempt to remove unknown trigger '\" + \n\t\t E.first + \n\t\t \"'\");\n }\n else\n {\n if (m_Conn && (R.second == ++R.first))\n\tPQexec(m_Conn, (\"UNLISTEN \" + string(T->Name())).c_str());\n\n m_Triggers.erase(i);\n }\n }\n catch (const exception &e)\n {\n ProcessNotice(e.what());\n }\n}\n\n\nvoid pqxx::ConnectionItf::GetNotifs()\n{\n if (!m_Conn) return;\n\n PQconsumeInput(m_Conn);\n\n \/\/ Even if somehow we receive notifications during our transaction, don't\n \/\/ deliver them.\n if (m_Trans.get()) return;\n\n for (PQAlloc N( PQnotifies(m_Conn) ); N; N = PQnotifies(m_Conn))\n {\n typedef TriggerList::iterator TI;\n\n pair Hit = m_Triggers.equal_range(string(N->relname));\n for (TI i = Hit.first; i != Hit.second; ++i)\n try\n {\n (*i->second)(N->be_pid);\n }\n catch (const exception &e)\n {\n\tProcessNotice(\"Exception in trigger handler '\" +\n\t\t i->first + \n\t\t \"': \" + \n\t\t e.what() +\n\t\t \"\\n\");\n }\n\n N.close();\n }\n}\n\n\nconst char *pqxx::ConnectionItf::ErrMsg() const\n{\n return m_Conn ? PQerrorMessage(m_Conn) : \"No connection to database\";\n}\n\n\npqxx::Result pqxx::ConnectionItf::Exec(const char Query[], \n int Retries, \n\t\t\t\t const char OnReconnect[])\n{\n Activate();\n\n Result R( PQexec(m_Conn, Query) );\n\n while ((Retries > 0) && !R && !is_open())\n {\n Retries--;\n\n Reset(OnReconnect);\n if (is_open()) R = PQexec(m_Conn, Query);\n }\n\n if (!R) throw broken_connection();\n R.CheckStatus();\n\n GetNotifs();\n\n return R;\n}\n\n\nvoid pqxx::ConnectionItf::Reset(const char OnReconnect[])\n{\n \/\/ Attempt to set up or restore connection\n if (!m_Conn) Connect();\n else \n {\n PQreset(m_Conn);\n SetupState();\n\n \/\/ Perform any extra patchup work involved in restoring the connection,\n \/\/ typically set up a transaction.\n if (OnReconnect)\n {\n Result Temp( PQexec(m_Conn, OnReconnect) );\n Temp.CheckStatus();\n }\n }\n}\n\n\nvoid pqxx::ConnectionItf::close() throw ()\n{\n try\n {\n if (m_Trans.get()) \n ProcessNotice(\"Closing connection while transaction '\" +\n\t\t m_Trans.get()->Name() +\n\t\t \"' still open\\n\");\n\n if (!m_Triggers.empty())\n {\n string T;\n for (TriggerList::const_iterator i = m_Triggers.begin(); \n\t i != m_Triggers.end();\n\t ++i)\n\tT += \" \" + i->first;\n\n ProcessNotice(\"Closing connection with outstanding triggers:\" + \n\t T + \n\t\t \"\\n\");\n m_Triggers.clear();\n }\n\n Disconnect();\n }\n catch (...)\n {\n }\n}\n\n\n\n\nvoid pqxx::ConnectionItf::InternalSetTrace() const\n{\n if (m_Trace) PQtrace(m_Conn, m_Trace);\n else PQuntrace(m_Conn);\n}\n\n\n\nvoid pqxx::ConnectionItf::RegisterTransaction(const TransactionItf *T)\n{\n m_Trans.Register(T);\n}\n\n\nvoid pqxx::ConnectionItf::UnregisterTransaction(const TransactionItf *T) throw ()\n{\n try\n {\n m_Trans.Unregister(T);\n }\n catch (const exception &e)\n {\n ProcessNotice(string(e.what()) + \"\\n\");\n }\n}\n\n\nvoid pqxx::ConnectionItf::MakeEmpty(pqxx::Result &R, ExecStatusType Stat)\n{\n if (!m_Conn) \n throw logic_error(\"Internal libpqxx error: MakeEmpty() on null connection\");\n\n R = Result(PQmakeEmptyPGresult(m_Conn, Stat));\n}\n\n\nvoid pqxx::ConnectionItf::BeginCopyRead(const string &Table)\n{\n Result R( Exec((\"COPY \" + Table + \" TO STDOUT\").c_str()) );\n R.CheckStatus();\n}\n\n\nbool pqxx::ConnectionItf::ReadCopyLine(string &Line)\n{\n if (!m_Conn)\n throw logic_error(\"Internal libpqxx error: \"\n\t \"ReadCopyLine() on null connection\");\n\n char Buf[256];\n bool LineComplete = false;\n\n Line.erase();\n\n while (!LineComplete)\n {\n switch (PQgetline(m_Conn, Buf, sizeof(Buf)))\n {\n case EOF:\n throw runtime_error(\"Unexpected EOF from backend\");\n\n case 0:\n LineComplete = true;\n break;\n\n case 1:\n break;\n\n default:\n throw runtime_error(\"Unexpected COPY response from backend\");\n }\n\n Line += Buf;\n }\n\n bool Result = (Line != \"\\\\.\");\n\n if (!Result) Line.erase();\n\n return Result;\n}\n\n\nvoid pqxx::ConnectionItf::BeginCopyWrite(const string &Table)\n{\n Result R( Exec((\"COPY \" + Table + \" FROM STDIN\").c_str()) );\n R.CheckStatus();\n}\n\n\n\nvoid pqxx::ConnectionItf::WriteCopyLine(const string &Line)\n{\n if (!m_Conn)\n throw logic_error(\"Internal libpqxx error: \"\n\t \"WriteCopyLine() on null connection\");\n\n PQputline(m_Conn, (Line + \"\\n\").c_str());\n}\n\n\n\/\/ End COPY operation. Careful: this assumes that no more lines remain to be\n\/\/ read or written, and the COPY operation has been properly terminated with a\n\/\/ line containing only the two characters \"\\.\"\nvoid pqxx::ConnectionItf::EndCopy()\n{\n if (PQendcopy(m_Conn) != 0) throw runtime_error(ErrMsg());\n}\n\n\n\nMade less confusing to doxygen\/*-------------------------------------------------------------------------\n *\n * FILE\n *\tconnectionitf.cxx\n *\n * DESCRIPTION\n * implementation of the pqxx::ConnectionItf abstract base class.\n * pqxx::ConnectionItf encapsulates a frontend to backend connection\n *\n * Copyright (c) 2001-2003, Jeroen T. Vermeulen \n *\n *-------------------------------------------------------------------------\n *\/\n#include \n#include \n#include \n\n#include \"pqxx\/connectionitf.h\"\n#include \"pqxx\/result.h\"\n#include \"pqxx\/transaction.h\"\n#include \"pqxx\/trigger.h\"\n\n\nusing namespace PGSTD;\n\nnamespace\n{\n\n\/\/ Keep track of a pointer to be free()d automatically.\n\/\/ Ownership policy is simple: object dies when PQAlloc object's value does.\ntemplate class PQAlloc\n{\n T *m_Obj;\npublic:\n PQAlloc() : m_Obj(0) {}\n explicit PQAlloc(T *obj) : m_Obj(obj) {}\n ~PQAlloc() { close(); }\n\n PQAlloc &operator=(T *obj) throw ()\n { \n if (obj != m_Obj)\n {\n close();\n m_Obj = obj;\n }\n return *this;\n }\n\n operator bool() const throw () { return m_Obj != 0; }\n bool operator!() const throw () { return !m_Obj; }\n\n T *operator->() const\n {\n if (!m_Obj) throw logic_error(\"Null pointer dereferenced\");\n return m_Obj;\n }\n\n T &operator*() const { return *operator->(); }\n\n T *c_ptr() const throw () { return m_Obj; }\n\n void close() throw () { if (m_Obj) freemem(); m_Obj = 0; }\n\n void freemem() throw ()\n {\n#ifdef HAVE_PQFREEMEM\n PQfreemem(m_Obj);\n#else\n free(m_Obj);\n#endif\n }\n\nprivate:\n PQAlloc(const PQAlloc &);\t\t\/\/ Not allowed\n PQAlloc &operator=(const PQAlloc &);\t\/\/ Not allowed\n};\n}\n\n\nextern \"C\"\n{\n\/\/ Pass C-linkage notice processor call on to C++-linkage Noticer object. The\n\/\/ void * argument points to the Noticer.\nvoid pqxxNoticeCaller(void *arg, const char *Msg)\n{\n if (arg && Msg) (*static_cast(arg))(Msg);\n}\n}\n\n\npqxx::ConnectionItf::ConnectionItf(const string &ConnInfo) :\n m_ConnInfo(ConnInfo),\n m_Conn(0),\n m_Trans(),\n m_Noticer(),\n m_Trace(0)\n{\n}\n\n\npqxx::ConnectionItf::ConnectionItf(const char ConnInfo[]) :\n m_ConnInfo(ConnInfo ? ConnInfo : \"\"),\n m_Conn(0),\n m_Trans(),\n m_Noticer(),\n m_Trace(0)\n{\n}\n\n\nvoid pqxx::ConnectionItf::Connect() const\n{\n if (m_Conn) throw logic_error(\"libqxx internal error: spurious Connect()\");\n\n m_Conn = PQconnectdb(m_ConnInfo.c_str());\n\n if (!m_Conn)\n throw broken_connection();\n\n if (!is_open())\n {\n const string Msg( ErrMsg() );\n Disconnect();\n throw broken_connection(Msg);\n }\n\n if (Status() != CONNECTION_OK)\n {\n const string Msg( ErrMsg() );\n Disconnect();\n throw runtime_error(Msg);\n }\n\n SetupState();\n}\n\n\n\nvoid pqxx::ConnectionItf::Deactivate() const\n{\n if (m_Conn)\n {\n if (m_Trans.get())\n throw logic_error(\"Attempt to deactivate connection while transaction \"\n\t \"'\" + m_Trans.get()->Name() + \"' \"\n\t\t\t\"still open\");\n\n Disconnect();\n }\n}\n\n\nvoid pqxx::ConnectionItf::SetClientEncoding(const char Encoding[])\n{\n if (PQsetClientEncoding(m_Conn, Encoding) != 0)\n throw runtime_error(\"Could not set client encoding to \" +\n\t string(Encoding));\n}\n\n\n\/** Set up various parts of logical connection state that may need to be\n * recovered because the physical connection to the database was lost and is\n * being reset, or that may not have been initialized yet.\n *\/\nvoid pqxx::ConnectionItf::SetupState() const\n{\n if (!m_Conn) \n throw logic_error(\"libpqxx internal error: SetupState() on no connection\");\n\n if (m_Noticer.get())\n PQsetNoticeProcessor(m_Conn, pqxxNoticeCaller, m_Noticer.get());\n\n InternalSetTrace();\n\n \/\/ Reinstate all active triggers\n if (!m_Triggers.empty())\n {\n const TriggerList::const_iterator End = m_Triggers.end();\n string Last;\n for (TriggerList::const_iterator i = m_Triggers.begin(); i != End; ++i)\n {\n \/\/ m_Triggers can handle multiple Triggers waiting on the same event; \n \/\/ issue just one LISTEN for each event.\n if (i->first != Last)\n {\n Result R( PQexec(m_Conn, (\"LISTEN \" + i->first).c_str()) );\n R.CheckStatus();\n Last = i->first;\n }\n }\n }\n}\n\n\nvoid pqxx::ConnectionItf::Disconnect() const throw ()\n{\n if (m_Conn)\n {\n PQfinish(m_Conn);\n m_Conn = 0;\n }\n}\n\n\nbool pqxx::ConnectionItf::is_open() const\n{\n return m_Conn && (Status() != CONNECTION_BAD);\n}\n\n\nauto_ptr \npqxx::ConnectionItf::SetNoticer(auto_ptr N)\n{\n if (N.get()) PQsetNoticeProcessor(m_Conn, pqxxNoticeCaller, N.get());\n else PQsetNoticeProcessor(m_Conn, 0, 0);\n \n auto_ptr Old = m_Noticer;\n \/\/ TODO: Can this line fail? If yes, we'd be killing Old prematurely...\n m_Noticer = N;\n\n return Old;\n}\n\n\nvoid pqxx::ConnectionItf::ProcessNotice(const char msg[]) throw ()\n{\n if (msg)\n {\n \/\/ TODO: Find cleaner solution for default case!\n if (m_Noticer.get()) (*m_Noticer.get())(msg);\n else fputs(msg, stderr);\n }\n}\n\n\nvoid pqxx::ConnectionItf::Trace(FILE *Out)\n{\n m_Trace = Out;\n if (m_Conn) InternalSetTrace();\n}\n\n\nvoid pqxx::ConnectionItf::AddTrigger(pqxx::Trigger *T)\n{\n if (!T) throw invalid_argument(\"Null trigger registered\");\n\n \/\/ Add to triggers list and attempt to start listening.\n const TriggerList::iterator p = m_Triggers.find(T->Name());\n const TriggerList::value_type NewVal(T->Name(), T);\n\n if (m_Conn && (p == m_Triggers.end()))\n {\n \/\/ Not listening on this event yet, start doing so.\n \/\/\n Result R( PQexec(m_Conn, (\"LISTEN \" + string(T->Name())).c_str()) );\n\n try\n {\n R.CheckStatus();\n }\n catch (const broken_connection &)\n {\n }\n catch (const exception &)\n {\n if (is_open()) throw;\n }\n m_Triggers.insert(NewVal);\n }\n else\n {\n m_Triggers.insert(p, NewVal);\n }\n\n}\n\n\nvoid pqxx::ConnectionItf::RemoveTrigger(pqxx::Trigger *T) throw ()\n{\n if (!T) return;\n\n try\n {\n \/\/ Keep Sun compiler happy... Hope it doesn't annoy other compilers\n pair tmp_pair(T->Name(), T);\n TriggerList::value_type E = tmp_pair;\n\n typedef pair Range;\n Range R = m_Triggers.equal_range(E.first);\n\n const TriggerList::iterator i = find(R.first, R.second, E);\n\n if (i == R.second) \n {\n ProcessNotice(\"Attempt to remove unknown trigger '\" + \n\t\t E.first + \n\t\t \"'\");\n }\n else\n {\n if (m_Conn && (R.second == ++R.first))\n\tPQexec(m_Conn, (\"UNLISTEN \" + string(T->Name())).c_str());\n\n m_Triggers.erase(i);\n }\n }\n catch (const exception &e)\n {\n ProcessNotice(e.what());\n }\n}\n\n\nvoid pqxx::ConnectionItf::GetNotifs()\n{\n if (!m_Conn) return;\n\n PQconsumeInput(m_Conn);\n\n \/\/ Even if somehow we receive notifications during our transaction, don't\n \/\/ deliver them.\n if (m_Trans.get()) return;\n\n for (PQAlloc N( PQnotifies(m_Conn) ); N; N = PQnotifies(m_Conn))\n {\n typedef TriggerList::iterator TI;\n\n pair Hit = m_Triggers.equal_range(string(N->relname));\n for (TI i = Hit.first; i != Hit.second; ++i)\n try\n {\n (*i->second)(N->be_pid);\n }\n catch (const exception &e)\n {\n\tProcessNotice(\"Exception in trigger handler '\" +\n\t\t i->first + \n\t\t \"': \" + \n\t\t e.what() +\n\t\t \"\\n\");\n }\n\n N.close();\n }\n}\n\n\nconst char *pqxx::ConnectionItf::ErrMsg() const\n{\n return m_Conn ? PQerrorMessage(m_Conn) : \"No connection to database\";\n}\n\n\npqxx::Result pqxx::ConnectionItf::Exec(const char Query[], \n int Retries, \n\t\t\t\t const char OnReconnect[])\n{\n Activate();\n\n Result R( PQexec(m_Conn, Query) );\n\n while ((Retries > 0) && !R && !is_open())\n {\n Retries--;\n\n Reset(OnReconnect);\n if (is_open()) R = PQexec(m_Conn, Query);\n }\n\n if (!R) throw broken_connection();\n R.CheckStatus();\n\n GetNotifs();\n\n return R;\n}\n\n\nvoid pqxx::ConnectionItf::Reset(const char OnReconnect[])\n{\n \/\/ Attempt to set up or restore connection\n if (!m_Conn) Connect();\n else \n {\n PQreset(m_Conn);\n SetupState();\n\n \/\/ Perform any extra patchup work involved in restoring the connection,\n \/\/ typically set up a transaction.\n if (OnReconnect)\n {\n Result Temp( PQexec(m_Conn, OnReconnect) );\n Temp.CheckStatus();\n }\n }\n}\n\n\nvoid pqxx::ConnectionItf::close() throw ()\n{\n try\n {\n if (m_Trans.get()) \n ProcessNotice(\"Closing connection while transaction '\" +\n\t\t m_Trans.get()->Name() +\n\t\t \"' still open\\n\");\n\n if (!m_Triggers.empty())\n {\n string T;\n for (TriggerList::const_iterator i = m_Triggers.begin(); \n\t i != m_Triggers.end();\n\t ++i)\n\tT += \" \" + i->first;\n\n ProcessNotice(\"Closing connection with outstanding triggers:\" + \n\t T + \n\t\t \"\\n\");\n m_Triggers.clear();\n }\n\n Disconnect();\n }\n catch (...)\n {\n }\n}\n\n\n\n\nvoid pqxx::ConnectionItf::InternalSetTrace() const\n{\n if (m_Trace) PQtrace(m_Conn, m_Trace);\n else PQuntrace(m_Conn);\n}\n\n\n\nvoid pqxx::ConnectionItf::RegisterTransaction(const TransactionItf *T)\n{\n m_Trans.Register(T);\n}\n\n\nvoid pqxx::ConnectionItf::UnregisterTransaction(const TransactionItf *T) throw ()\n{\n try\n {\n m_Trans.Unregister(T);\n }\n catch (const exception &e)\n {\n ProcessNotice(string(e.what()) + \"\\n\");\n }\n}\n\n\nvoid pqxx::ConnectionItf::MakeEmpty(pqxx::Result &R, ExecStatusType Stat)\n{\n if (!m_Conn) \n throw logic_error(\"Internal libpqxx error: MakeEmpty() on null connection\");\n\n R = Result(PQmakeEmptyPGresult(m_Conn, Stat));\n}\n\n\nvoid pqxx::ConnectionItf::BeginCopyRead(const string &Table)\n{\n Result R( Exec((\"COPY \" + Table + \" TO STDOUT\").c_str()) );\n R.CheckStatus();\n}\n\n\nbool pqxx::ConnectionItf::ReadCopyLine(string &Line)\n{\n if (!m_Conn)\n throw logic_error(\"Internal libpqxx error: \"\n\t \"ReadCopyLine() on null connection\");\n\n char Buf[256];\n bool LineComplete = false;\n\n Line.erase();\n\n while (!LineComplete)\n {\n switch (PQgetline(m_Conn, Buf, sizeof(Buf)))\n {\n case EOF:\n throw runtime_error(\"Unexpected EOF from backend\");\n\n case 0:\n LineComplete = true;\n break;\n\n case 1:\n break;\n\n default:\n throw runtime_error(\"Unexpected COPY response from backend\");\n }\n\n Line += Buf;\n }\n\n bool Result = (Line != \"\\\\.\");\n\n if (!Result) Line.erase();\n\n return Result;\n}\n\n\nvoid pqxx::ConnectionItf::BeginCopyWrite(const string &Table)\n{\n Result R( Exec((\"COPY \" + Table + \" FROM STDIN\").c_str()) );\n R.CheckStatus();\n}\n\n\n\nvoid pqxx::ConnectionItf::WriteCopyLine(const string &Line)\n{\n if (!m_Conn)\n throw logic_error(\"Internal libpqxx error: \"\n\t \"WriteCopyLine() on null connection\");\n\n PQputline(m_Conn, (Line + \"\\n\").c_str());\n}\n\n\n\/\/ End COPY operation. Careful: this assumes that no more lines remain to be\n\/\/ read or written, and the COPY operation has been properly terminated with a\n\/\/ line containing only the two characters \"\\.\"\nvoid pqxx::ConnectionItf::EndCopy()\n{\n if (PQendcopy(m_Conn) != 0) throw runtime_error(ErrMsg());\n}\n\n\n\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: DAVProperties.hxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: rt $ $Date: 2005-09-09 16:06:28 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n#ifndef _DAVPROPERTIES_HXX_\n#define _DAVPROPERTIES_HXX_\n\n#ifndef _RTL_USTRING_HXX_\n#include \n#endif\n#ifndef _NEONTYPES_HXX_\n#include \"NeonTypes.hxx\"\n#endif\n\nnamespace webdav_ucp\n{\n\nstruct DAVProperties\n{\n static const ::rtl::OUString CREATIONDATE;\n static const ::rtl::OUString DISPLAYNAME;\n static const ::rtl::OUString GETCONTENTLANGUAGE;\n static const ::rtl::OUString GETCONTENTLENGTH;\n static const ::rtl::OUString GETCONTENTTYPE;\n static const ::rtl::OUString GETETAG;\n static const ::rtl::OUString GETLASTMODIFIED;\n static const ::rtl::OUString LOCKDISCOVERY;\n static const ::rtl::OUString RESOURCETYPE;\n static const ::rtl::OUString SOURCE;\n static const ::rtl::OUString SUPPORTEDLOCK;\n static const ::rtl::OUString EXECUTABLE;\n\n static void createNeonPropName( const rtl::OUString & rFullName,\n NeonPropName & rName );\n static void createUCBPropName ( const char * nspace,\n const char * name,\n rtl::OUString & rFullName );\n\n static bool isUCBDeadProperty( const NeonPropName & rName );\n};\n\n}; \/\/ namespace webdav_ucp\n\n#endif \/\/ _DAVPROPERTIES_HXX_\nINTEGRATION: CWS warnings01 (1.3.10); FILE MERGED 2005\/11\/10 18:10:16 pl 1.3.10.1: #i55991# removed warnings\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: DAVProperties.hxx,v $\n *\n * $Revision: 1.4 $\n *\n * last change: $Author: hr $ $Date: 2006-06-20 05:33:29 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n#ifndef _DAVPROPERTIES_HXX_\n#define _DAVPROPERTIES_HXX_\n\n#ifndef _RTL_USTRING_HXX_\n#include \n#endif\n#ifndef _NEONTYPES_HXX_\n#include \"NeonTypes.hxx\"\n#endif\n\nnamespace webdav_ucp\n{\n\nstruct DAVProperties\n{\n static const ::rtl::OUString CREATIONDATE;\n static const ::rtl::OUString DISPLAYNAME;\n static const ::rtl::OUString GETCONTENTLANGUAGE;\n static const ::rtl::OUString GETCONTENTLENGTH;\n static const ::rtl::OUString GETCONTENTTYPE;\n static const ::rtl::OUString GETETAG;\n static const ::rtl::OUString GETLASTMODIFIED;\n static const ::rtl::OUString LOCKDISCOVERY;\n static const ::rtl::OUString RESOURCETYPE;\n static const ::rtl::OUString SOURCE;\n static const ::rtl::OUString SUPPORTEDLOCK;\n static const ::rtl::OUString EXECUTABLE;\n\n static void createNeonPropName( const rtl::OUString & rFullName,\n NeonPropName & rName );\n static void createUCBPropName ( const char * nspace,\n const char * name,\n rtl::OUString & rFullName );\n\n static bool isUCBDeadProperty( const NeonPropName & rName );\n};\n\n} \/\/ namespace webdav_ucp\n\n#endif \/\/ _DAVPROPERTIES_HXX_\n<|endoftext|>"} {"text":"MODULE DevSearch;\n(**\n\tproject\t= \"BlackBox\"\n\torganization\t= \"www.oberon.ch\"\n\tcontributors\t= \"Oberon microsystems\"\n\tversion\t= \"System\/Rsrc\/About\"\n\tcopyright\t= \"System\/Rsrc\/About\"\n\tlicense\t= \"Docu\/BB-License\"\n\tchanges\t= \"\n\t- 20070307, bh, caseSens handling in Find corrected\n\t\"\n\tissues\t= \"\"\n\n**)\n\n\tIMPORT\n\t\tKernel, Files, Fonts, Ports, Models, Views, Containers, Dialog, Windows,\n\t\tTextModels, TextRulers, TextViews, TextControllers, TextMappers, TextCmds, StdLinks;\n\n\tCONST\n\t\tN = 32; T = 10;\n\t\tmaxPat = 64;\n\t\tnoMatchFoundKey = \"#Std:NoMatchFound\";\n\t\tlocationKey = \"#Std:Location\";\n\t\tcountKey = \"#Std:Count\";\n\t\tsearchingKey = \"#Std:Searching\";\n\t\topenFindCmdKey = \"#Dev:OpenFindCmd\";\n\t\topenFindCmdNotFoundKey = \"#Dev:OpenFindCmdNotFound\";\n\n\tTYPE\n\t\tPattern = ARRAY maxPat OF CHAR;\n\t\tText = POINTER TO RECORD\n\t\t\tnext: Text;\n\t\t\tnum: INTEGER;\n\t\t\ttitle: Files.Name\n\t\tEND;\n\n\tVAR\n\t\tw: TextMappers.Formatter;\n\n\tPROCEDURE Find (t: TextModels.Model; pat: Pattern; title: Files.Name; VAR list: Text; caseSens: BOOLEAN);\n\t\tVAR r: TextModels.Reader; num: INTEGER; i, j, b, e, n: INTEGER; ch: CHAR; ref: Pattern; l: Text;\n\tBEGIN\n\t\tn := 0; num := 0;\n\t\tWHILE pat[n] # 0X DO\n\t\t\tIF ~caseSens THEN pat[n] := CAP(pat[n]) END ;\n\t\t\tINC(n)\n\t\tEND;\n\t\tr := t.NewReader(NIL);\n\t\tr.SetPos(0); r.ReadChar(ch);\n\t\tWHILE ~r.eot DO\n\t\t\tref[0] := ch; i := 0; j := 0; b := 0; e := 1;\n\t\t\tWHILE ~r.eot & (i < n) DO\n\t\t\t\tIF caseSens & (pat[i]=ch) OR ~caseSens & (pat[i] = CAP(ch)) THEN INC(i); j := (j + 1) MOD maxPat\n\t\t\t\tELSE i := 0; b := (b + 1) MOD maxPat; j := b\n\t\t\t\tEND;\n\t\t\t\tIF j # e THEN ch := ref[j]\n\t\t\t\tELSE r.ReadChar(ch); ref[j] := ch; e := (e + 1) MOD maxPat\n\t\t\t\tEND\n\t\t\tEND;\n\t\t\tIF i = n THEN INC(num) END\n\t\tEND;\n\t\tIF num > 0 THEN\n\t\t\tNEW(l); l.num := num; l.title := title; l.next := list; list := l\n\t\tEND\n\tEND Find;\n\t\n\tPROCEDURE List (list: Text; pat: Pattern; source, caseSens: BOOLEAN);\n\t\tVAR a0: TextModels.Attributes; cmd: ARRAY 256 OF CHAR; this, t: Text; max: INTEGER;\n\tBEGIN\n\t\tIF list = NIL THEN\n\t\t\tDialog.MapString(noMatchFoundKey, cmd);\n\t\t\tw.WriteString(cmd)\n\t\tELSE\n\t\t\ta0 := w.rider.attr;\n\t\t\tw.rider.SetAttr(TextModels.NewStyle(w.rider.attr, {Fonts.italic}));\n\t\t\tDialog.MapString(locationKey, cmd);\n\t\t\tw.WriteString(cmd); w.WriteTab;\n\t\t\tDialog.MapString(countKey, cmd);\n\t\t\tw.WriteString(cmd); w.WriteLn;\n\t\t\tw.rider.SetAttr(a0);\n\t\t\tREPEAT\n\t\t\t\tt := list; max := 1; this := NIL;\n\t\t\t\tWHILE t # NIL DO\n\t\t\t\t\tIF t.num >= max THEN max := t.num; this := t END;\n\t\t\t\t\tt := t.next\n\t\t\t\tEND;\n\t\t\t\tIF this # NIL THEN\n\t\t\t\t\tw.rider.SetAttr(TextModels.NewStyle(w.rider.attr, {Fonts.underline}));\n\t\t\t\t\tw.rider.SetAttr(TextModels.NewColor(w.rider.attr, Ports.blue));\n\t\t\t\t\tIF source THEN \n\t\t\t\t\t\tcmd := \"StdCmds.OpenDoc('\" + this.title + \"'); DevSearch.SelectCaseSens('\" + pat + \"')\"\n\t\t\t\t\tELSE\n\t\t\t\t\t\tIF caseSens THEN\n\t\t\t\t\t\t\tcmd := \"StdCmds.OpenBrowser('\" + this.title + \"', '\" + this.title + \"'); \" +\n\t\t\t\t\t\t\t\t\"DevSearch.SelectCaseSens('\" + pat + \"')\"\n\t\t\t\t\t\tELSE\n\t\t\t\t\t\t\tcmd := \"StdCmds.OpenBrowser('\" + this.title + \"', '\" + this.title + \"'); \" +\n\t\t\t\t\t\t\t\t\"DevSearch.SelectCaseInSens('\" + pat + \"')\"\n\t\t\t\t\t\tEND\n\t\t\t\t\tEND;\n\t\t\t\t\tw.WriteView(StdLinks.dir.NewLink(cmd));\n\t\t\t\t\tw.WriteString(this.title);\n\t\t\t\t\tw.WriteView(StdLinks.dir.NewLink(\"\"));\n\t\t\t\t\tw.rider.SetAttr(a0);\n\t\t\t\t\tw.WriteTab; w.WriteInt(this.num); w.WriteLn;\n\t\t\t\t\tthis.num := 0\n\t\t\t\tEND\n\t\t\tUNTIL this = NIL\n\t\tEND\n\tEND List;\n\n\tPROCEDURE NewRuler (): TextRulers.Ruler;\n\t\tCONST mm = Ports.mm;\n\t\tVAR p: TextRulers.Prop;\n\tBEGIN\n\t\tNEW(p);\n\t\tp.valid := {TextRulers.right, TextRulers.tabs, TextRulers.opts};\n\t\tp.opts.val := {TextRulers.rightFixed}; p.opts.mask := p.opts.val;\n\t\tp.right := 100 * mm;\n\t\tp.tabs.len := 1;\n\t\tp.tabs.tab[0].stop := 70 * mm;\n\t\tRETURN TextRulers.dir.NewFromProp(p)\n\tEND NewRuler;\n\n\tPROCEDURE ThisText (loc: Files.Locator; VAR name: Files.Name): TextModels.Model;\n\t\tVAR v: Views.View; m: Models.Model;\n\tBEGIN\n\t\tv := Views.OldView(loc, name);\n\t\tIF v # NIL THEN\n\t\t\tm := v.ThisModel();\n\t\t\tIF m # NIL THEN\n\t\t\t\tWITH m: TextModels.Model DO RETURN m ELSE END\n\t\t\tEND\n\t\tEND;\n\t\tRETURN NIL\n\tEND ThisText;\n\n\tPROCEDURE Search (source, caseSens: BOOLEAN);\n\t\tVAR pat: Pattern; t, log: TextModels.Model; v: Views.View; title: Views.Title; c: Containers.Controller;\n\t\t\tfiles: Files.FileInfo; dirs: Files.LocInfo;\n\t\t\tloc: Files.Locator; path, p: Files.Name; list: Text;\n\tBEGIN\n\t\t(*TextCmds.InitFindDialog; *)\n\t\tpat := TextCmds.find.find$;\n\t\tIF pat # \"\" THEN\n\t\t\tDialog.ShowStatus(searchingKey);\n\t\t\tTextCmds.find.find := pat$;\n\t\t\tlog := TextModels.dir.New();\n\t\t\tw.ConnectTo(log); w.SetPos(0);\n\t\t\tIF source THEN loc := Files.dir.This(\"Mod\"); path := \"Mod\"\n\t\t\tELSE loc := Files.dir.This(\"Docu\"); path := \"Docu\"\n\t\t\tEND;\n\t\t\tfiles := Files.dir.FileList(loc); list := NIL;\n\t\t\tWHILE files # NIL DO\n\t\t\t\tIF files.type = Kernel.docType THEN\n\t\t\t\t\tp := path + \"\/\" + files.name;\n\t\t\t\t\tFind(ThisText(loc, files.name), pat, p, list, caseSens)\n\t\t\t\tEND;\n\t\t\t\tfiles := files.next\n\t\t\tEND;\n\t\t\tloc := Files.dir.This(\"\");\n\t\t\tdirs := Files.dir.LocList(loc);\n\t\t\tWHILE dirs # NIL DO\n\t\t\t\tloc := Files.dir.This(dirs.name); path := dirs.name + \"\/\";\n\t\t\t\tIF source THEN loc := loc.This(\"Mod\"); path := path + \"Mod\"\n\t\t\t\tELSE loc := loc.This(\"Docu\"); path := path +\"Docu\"\n\t\t\t\tEND;\n\t\t\t\tfiles := Files.dir.FileList(loc);\n\t\t\t\tWHILE files # NIL DO\n\t\t\t\t\tIF files.type = Kernel.docType THEN\n\t\t\t\t\t\tp := path + \"\/\" + files.name;\n\t\t\t\t\t\tt := ThisText(loc, files.name);\n\t\t\t\t\t\tIF t # NIL THEN\n\t\t\t\t\t\t\tFind(t, pat, p, list, caseSens)\n\t\t\t\t\t\tEND\n\t\t\t\t\tEND;\n\t\t\t\t\tfiles := files.next\n\t\t\t\tEND;\n\t\t\t\tdirs := dirs.next\n\t\t\tEND;\n\t\t\tList(list, pat, source, caseSens);\n\t\t\tv := TextViews.dir.New(log);\n\t\t\ttitle := 'Search for \"' + pat + '\"';\n\t\t\tv(TextViews.View).SetDefaults(NewRuler(), TextViews.dir.defAttr);\n\t\t\tViews.OpenAux(v, title);\n\t\t\tc := v(Containers.View).ThisController();\n\t\t\tc.SetOpts(c.opts + {Containers.noCaret});\n\t\t\tw.ConnectTo(NIL);\n\t\t\tDialog.ShowStatus(\"\")\n\t\tEND\n\tEND Search;\n\n\tPROCEDURE SearchInSources*;\n\tBEGIN\n\t\tSearch(TRUE, TRUE)\n\tEND SearchInSources;\n\n\tPROCEDURE SearchInDocu* (opts: ARRAY OF CHAR);\n\t\tVAR caseSens: BOOLEAN;\n\tBEGIN\n\t\tcaseSens := ~TextCmds.find.ignoreCase;\n\t\tIF LEN(opts$) > 0 THEN\n\t\t\tIF CAP(opts[0]) = 'S' THEN\n\t\t\t\tcaseSens := TRUE\n\t\t\tELSIF CAP(opts[0]) = 'I' THEN\n\t\t\t\tcaseSens := FALSE\n\t\t\tEND\n\t\tEND;\n\t\tSearch(FALSE, caseSens)\n\tEND SearchInDocu;\n\t\n\tPROCEDURE SelectCaseSens* (pat: ARRAY OF CHAR);\n\tBEGIN\n\t\tTextCmds.find.find := pat$;\n\t\tTextCmds.find.ignoreCase := FALSE;\n\t\tDialog.Update(TextCmds.find);\n\t\tTextCmds.FindFirst(\"\")\n\tEND SelectCaseSens;\n\n\tPROCEDURE SelectCaseInSens* (pat: ARRAY OF CHAR);\n\t\tVAR res: INTEGER; cmd: Dialog.String;\n\tBEGIN\n\t\tTextCmds.find.find := pat$;\n\t\tTextCmds.find.ignoreCase := TRUE;\n\t\tDialog.Update(TextCmds.find);\n\t\tDialog.MapString(openFindCmdKey, cmd);\n\t\tDialog.Call(cmd, openFindCmdNotFoundKey, res);\n\t\tTextCmds.FindFirst(\"\")\n\tEND SelectCaseInSens;\n\n\n\tPROCEDURE NextChar (r: TextModels.Reader): CHAR;\n\t\tVAR ch: CHAR;\n\tBEGIN\n\t\tREPEAT r.ReadChar(ch) UNTIL (ch > \" \") OR r.eot;\n\t\tRETURN ch\n\tEND NextChar;\n\n\tPROCEDURE CompTexts (ta, tb: TextModels.Model; VAR sa, sb, ea, eb: INTEGER);\n\t\tVAR da, db, d, i, j, p: INTEGER; t: LONGINT; ra, rb: TextModels.Reader;\n\t\t\tcha, chb: CHAR; s: ARRAY N OF CHAR;\n\tBEGIN\n\t\tra := ta.NewReader(NIL); ra.SetPos(ea);\n\t\trb := tb.NewReader(NIL); rb.SetPos(eb);\n\t\tREPEAT\n\t\t\tcha := NextChar(ra); chb := NextChar(rb)\n\t\tUNTIL (cha # chb) OR ra.eot OR rb.eot;\n\t\tIF ra.eot THEN sa := ra.Pos() ELSE sa := ra.Pos() - 1 END;\n\t\tIF rb.eot THEN sb := rb.Pos() ELSE sb := rb.Pos() - 1 END;\n\t\tt := Kernel.Time() + T * Kernel.timeResolution;\n\t\tda := sa + 1; db := sb + 1; d := 1; j := 0;\n\t\tREPEAT\n\t\t\tea := da;\n\t\t\tIF ea < ta.Length() THEN\n\t\t\t\tra.SetPos(ea); s[0] := NextChar(ra);\n\t\t\t\tda := ra.Pos(); i := 1;\n\t\t\t\tWHILE i < N DO s[i] := NextChar(ra); INC(i) END;\n\t\t\t\ti := 0; rb.SetPos(sb);\n\t\t\t\tREPEAT\n\t\t\t\t\teb := rb.Pos(); chb := NextChar(rb);\n\t\t\t\t\tIF chb = s[0] THEN\n\t\t\t\t\t\tp := rb.Pos(); j := 0;\n\t\t\t\t\t\tWHILE (j < N) & (chb = s[j]) DO chb := NextChar(rb); INC(j) END;\n\t\t\t\t\t\trb.SetPos(p)\n\t\t\t\t\tEND;\n\t\t\t\t\tINC(i)\n\t\t\t\tUNTIL (j = N) OR (i = d) OR rb.eot\n\t\t\tEND;\n\t\t\tINC(d);\n\t\t\tIF j < N THEN\n\t\t\t\teb := db;\n\t\t\t\tIF eb < tb.Length() THEN\n\t\t\t\t\trb.SetPos(eb); s[0] := NextChar(rb);\n\t\t\t\t\tdb := rb.Pos(); i := 1;\n\t\t\t\t\tWHILE i < N DO s[i] := NextChar(rb); INC(i) END;\n\t\t\t\t\ti := 0; ra.SetPos(sa);\n\t\t\t\t\tREPEAT\n\t\t\t\t\t\tea := ra.Pos(); cha := NextChar(ra);\n\t\t\t\t\t\tIF cha = s[0] THEN\n\t\t\t\t\t\t\tp := ra.Pos(); j := 0;\n\t\t\t\t\t\t\tWHILE (j < N) & (cha = s[j]) DO cha := NextChar(ra); INC(j) END;\n\t\t\t\t\t\t\tra.SetPos(p)\n\t\t\t\t\t\tEND;\n\t\t\t\t\t\tINC(i)\n\t\t\t\t\tUNTIL (j = N) OR (i = d) OR ra.eot\n\t\t\t\tEND\n\t\t\tEND\n\t\tUNTIL (j = N) OR (ea >= ta.Length()) & (eb >= tb.Length()) OR (Kernel.Time() > t);\n\t\tIF j < N THEN ea := ta.Length(); eb := tb.Length() END\n\tEND CompTexts;\n\n\tPROCEDURE Compare*;\n\t\tVAR wa, wb: Windows.Window; va, vb: Views.View; ca, cb: Containers.Controller; sa, sb, ea, eb: INTEGER;\n\tBEGIN\n\t\twa := Windows.dir.First();\n\t\tIF wa # NIL THEN\n\t\t\twb := Windows.dir.Next(wa);\n\t\t\tIF wb # NIL THEN\n\t\t\t\tva := wa.doc.ThisView();\n\t\t\t\tWITH va: TextViews.View DO\n\t\t\t\t\tvb := wb.doc.ThisView();\n\t\t\t\t\tWITH vb: TextViews.View DO\n\t\t\t\t\t\tca := va.ThisController();\n\t\t\t\t\t\tWITH ca: TextControllers.Controller DO\n\t\t\t\t\t\t\tcb := vb.ThisController();\n\t\t\t\t\t\t\tWITH cb: TextControllers.Controller DO\n\t\t\t\t\t\t\t\tca.GetSelection(sa, ea);\n\t\t\t\t\t\t\t\tIF (* ea = -1 *) sa = ea THEN ea := MAX(0, ca.CaretPos()) END;\n\t\t\t\t\t\t\t\tcb.GetSelection(sb, eb);\n\t\t\t\t\t\t\t\tIF (* eb = -1 *) sb = eb THEN eb := MAX(0, cb.CaretPos()) END;\n\t\t\t\t\t\t\t\tCompTexts(va.ThisModel(), vb.ThisModel(), sa, sb, ea, eb);\n\t\t\t\t\t\t\t\tIF ea > sa THEN ca.SetSelection(sa, ea) ELSE ca.SetCaret(sa) END;\n\t\t\t\t\t\t\t\tIF eb > sb THEN cb.SetSelection(sb, eb) ELSE cb.SetCaret(sb) END;\n\t\t\t\t\t\t\t\tva.ShowRangeIn(Views.ThisFrame(wa.frame, va), sa, ea);\n\t\t\t\t\t\t\t\tvb.ShowRangeIn(Views.ThisFrame(wb.frame, vb), sb, eb)\n\t\t\t\t\t\t\tEND\n\t\t\t\t\t\tEND\n\t\t\t\t\tELSE\n\t\t\t\t\tEND\n\t\t\t\tELSE\n\t\t\t\tEND\n\t\t\tEND\n\t\tEND\n\tEND Compare;\n\nEND DevSearch.\n20150403, center #37, fixing traps with long search patterns in DevSearchMODULE DevSearch;\n(**\n\tproject\t= \"BlackBox\"\n\torganization\t= \"www.oberon.ch\"\n\tcontributors\t= \"Oberon microsystems\"\n\tversion\t= \"System\/Rsrc\/About\"\n\tcopyright\t= \"System\/Rsrc\/About\"\n\tlicense\t= \"Docu\/BB-License\"\n\tchanges\t= \"\n\t- 20070307, bh, caseSens handling in Find corrected\n\t\"\n\tissues\t= \"\"\n\n**)\n\n\tIMPORT\n\t\tKernel, Files, Fonts, Ports, Models, Views, Containers, Dialog, Windows,\n\t\tTextModels, TextRulers, TextViews, TextControllers, TextMappers, TextCmds, StdLinks;\n\n\tCONST\n\t\tN = 32; T = 10;\n\t\tmaxPat = LEN(TextCmds.find.find);\n\t\tnoMatchFoundKey = \"#Std:NoMatchFound\";\n\t\tlocationKey = \"#Std:Location\";\n\t\tcountKey = \"#Std:Count\";\n\t\tsearchingKey = \"#Std:Searching\";\n\t\topenFindCmdKey = \"#Dev:OpenFindCmd\";\n\t\topenFindCmdNotFoundKey = \"#Dev:OpenFindCmdNotFound\";\n\n\tTYPE\n\t\tPattern = ARRAY maxPat OF CHAR;\n\t\tText = POINTER TO RECORD\n\t\t\tnext: Text;\n\t\t\tnum: INTEGER;\n\t\t\ttitle: Files.Name\n\t\tEND;\n\n\tVAR\n\t\tw: TextMappers.Formatter;\n\n\tPROCEDURE Find (t: TextModels.Model; pat: Pattern; title: Files.Name; VAR list: Text; caseSens: BOOLEAN);\n\t\tVAR r: TextModels.Reader; num: INTEGER; i, j, b, e, n: INTEGER; ch: CHAR; ref: Pattern; l: Text;\n\tBEGIN\n\t\tn := 0; num := 0;\n\t\tWHILE pat[n] # 0X DO\n\t\t\tIF ~caseSens THEN pat[n] := CAP(pat[n]) END ;\n\t\t\tINC(n)\n\t\tEND;\n\t\tr := t.NewReader(NIL);\n\t\tr.SetPos(0); r.ReadChar(ch);\n\t\tWHILE ~r.eot DO\n\t\t\tref[0] := ch; i := 0; j := 0; b := 0; e := 1;\n\t\t\tWHILE ~r.eot & (i < n) DO\n\t\t\t\tIF caseSens & (pat[i]=ch) OR ~caseSens & (pat[i] = CAP(ch)) THEN INC(i); j := (j + 1) MOD maxPat\n\t\t\t\tELSE i := 0; b := (b + 1) MOD maxPat; j := b\n\t\t\t\tEND;\n\t\t\t\tIF j # e THEN ch := ref[j]\n\t\t\t\tELSE r.ReadChar(ch); ref[j] := ch; e := (e + 1) MOD maxPat\n\t\t\t\tEND\n\t\t\tEND;\n\t\t\tIF i = n THEN INC(num) END\n\t\tEND;\n\t\tIF num > 0 THEN\n\t\t\tNEW(l); l.num := num; l.title := title; l.next := list; list := l\n\t\tEND\n\tEND Find;\n\t\n\tPROCEDURE List (list: Text; pat: Pattern; source, caseSens: BOOLEAN);\n\t\tVAR a0: TextModels.Attributes; this, t: Text; max: INTEGER;\n\t\t\tcmd: ARRAY maxPat + LEN(t.title) + 50 OF CHAR;\n\tBEGIN\n\t\tIF list = NIL THEN\n\t\t\tDialog.MapString(noMatchFoundKey, cmd);\n\t\t\tw.WriteString(cmd)\n\t\tELSE\n\t\t\ta0 := w.rider.attr;\n\t\t\tw.rider.SetAttr(TextModels.NewStyle(w.rider.attr, {Fonts.italic}));\n\t\t\tDialog.MapString(locationKey, cmd);\n\t\t\tw.WriteString(cmd); w.WriteTab;\n\t\t\tDialog.MapString(countKey, cmd);\n\t\t\tw.WriteString(cmd); w.WriteLn;\n\t\t\tw.rider.SetAttr(a0);\n\t\t\tREPEAT\n\t\t\t\tt := list; max := 1; this := NIL;\n\t\t\t\tWHILE t # NIL DO\n\t\t\t\t\tIF t.num >= max THEN max := t.num; this := t END;\n\t\t\t\t\tt := t.next\n\t\t\t\tEND;\n\t\t\t\tIF this # NIL THEN\n\t\t\t\t\tw.rider.SetAttr(TextModels.NewStyle(w.rider.attr, {Fonts.underline}));\n\t\t\t\t\tw.rider.SetAttr(TextModels.NewColor(w.rider.attr, Ports.blue));\n\t\t\t\t\tIF source THEN \n\t\t\t\t\t\tcmd := \"StdCmds.OpenDoc('\" + this.title + \"'); DevSearch.SelectCaseSens('\" + pat + \"')\"\n\t\t\t\t\tELSE\n\t\t\t\t\t\tIF caseSens THEN\n\t\t\t\t\t\t\tcmd := \"StdCmds.OpenBrowser('\" + this.title + \"', '\" + this.title + \"'); \" +\n\t\t\t\t\t\t\t\t\"DevSearch.SelectCaseSens('\" + pat + \"')\"\n\t\t\t\t\t\tELSE\n\t\t\t\t\t\t\tcmd := \"StdCmds.OpenBrowser('\" + this.title + \"', '\" + this.title + \"'); \" +\n\t\t\t\t\t\t\t\t\"DevSearch.SelectCaseInSens('\" + pat + \"')\"\n\t\t\t\t\t\tEND\n\t\t\t\t\tEND;\n\t\t\t\t\tw.WriteView(StdLinks.dir.NewLink(cmd));\n\t\t\t\t\tw.WriteString(this.title);\n\t\t\t\t\tw.WriteView(StdLinks.dir.NewLink(\"\"));\n\t\t\t\t\tw.rider.SetAttr(a0);\n\t\t\t\t\tw.WriteTab; w.WriteInt(this.num); w.WriteLn;\n\t\t\t\t\tthis.num := 0\n\t\t\t\tEND\n\t\t\tUNTIL this = NIL\n\t\tEND\n\tEND List;\n\n\tPROCEDURE NewRuler (): TextRulers.Ruler;\n\t\tCONST mm = Ports.mm;\n\t\tVAR p: TextRulers.Prop;\n\tBEGIN\n\t\tNEW(p);\n\t\tp.valid := {TextRulers.right, TextRulers.tabs, TextRulers.opts};\n\t\tp.opts.val := {TextRulers.rightFixed}; p.opts.mask := p.opts.val;\n\t\tp.right := 100 * mm;\n\t\tp.tabs.len := 1;\n\t\tp.tabs.tab[0].stop := 70 * mm;\n\t\tRETURN TextRulers.dir.NewFromProp(p)\n\tEND NewRuler;\n\n\tPROCEDURE ThisText (loc: Files.Locator; VAR name: Files.Name): TextModels.Model;\n\t\tVAR v: Views.View; m: Models.Model;\n\tBEGIN\n\t\tv := Views.OldView(loc, name);\n\t\tIF v # NIL THEN\n\t\t\tm := v.ThisModel();\n\t\t\tIF m # NIL THEN\n\t\t\t\tWITH m: TextModels.Model DO RETURN m ELSE END\n\t\t\tEND\n\t\tEND;\n\t\tRETURN NIL\n\tEND ThisText;\n\n\tPROCEDURE GetTitle(IN pat: ARRAY OF CHAR; OUT title: Views.Title);\n\t\tVAR pos: INTEGER; i, j: INTEGER; ch: CHAR;\n\tBEGIN\n\t\ttitle := 'Search for \"'; i := LEN(title$); j := 0; ch := pat[0];\n\t\tWHILE (ch # 0X) & (i < LEN(title) - 2) DO\n\t\t\tIF ch < \" \" THEN title[i] := \" \" ELSE title[i] := ch END ; (* replace tabs and line feeds by spaces *)\n\t\t\tINC(i); INC(j); ch := pat[j]\n\t\tEND ;\n\t\tIF ch # 0X THEN title[i - 3] := \".\"; title[i - 2] := \".\"; title[i - 1] := \".\" END ;\n\t\ttitle[i] := '\"'; title[i + 1] := 0X\n\tEND GetTitle;\n\n\tPROCEDURE Search (source, caseSens: BOOLEAN);\n\t\tVAR pat: Pattern; t, log: TextModels.Model; v: Views.View; title: Views.Title; c: Containers.Controller;\n\t\t\tfiles: Files.FileInfo; dirs: Files.LocInfo;\n\t\t\tloc: Files.Locator; path, p: Files.Name; list: Text;\n\tBEGIN\n\t\t(*TextCmds.InitFindDialog; *)\n\t\tpat := TextCmds.find.find$;\n\t\tIF pat # \"\" THEN\n\t\t\tDialog.ShowStatus(searchingKey);\n\t\t\tTextCmds.find.find := pat$;\n\t\t\tlog := TextModels.dir.New();\n\t\t\tw.ConnectTo(log); w.SetPos(0);\n\t\t\tIF source THEN loc := Files.dir.This(\"Mod\"); path := \"Mod\"\n\t\t\tELSE loc := Files.dir.This(\"Docu\"); path := \"Docu\"\n\t\t\tEND;\n\t\t\tfiles := Files.dir.FileList(loc); list := NIL;\n\t\t\tWHILE files # NIL DO\n\t\t\t\tIF files.type = Kernel.docType THEN\n\t\t\t\t\tp := path + \"\/\" + files.name;\n\t\t\t\t\tFind(ThisText(loc, files.name), pat, p, list, caseSens)\n\t\t\t\tEND;\n\t\t\t\tfiles := files.next\n\t\t\tEND;\n\t\t\tloc := Files.dir.This(\"\");\n\t\t\tdirs := Files.dir.LocList(loc);\n\t\t\tWHILE dirs # NIL DO\n\t\t\t\tloc := Files.dir.This(dirs.name); path := dirs.name + \"\/\";\n\t\t\t\tIF source THEN loc := loc.This(\"Mod\"); path := path + \"Mod\"\n\t\t\t\tELSE loc := loc.This(\"Docu\"); path := path +\"Docu\"\n\t\t\t\tEND;\n\t\t\t\tfiles := Files.dir.FileList(loc);\n\t\t\t\tWHILE files # NIL DO\n\t\t\t\t\tIF files.type = Kernel.docType THEN\n\t\t\t\t\t\tp := path + \"\/\" + files.name;\n\t\t\t\t\t\tt := ThisText(loc, files.name);\n\t\t\t\t\t\tIF t # NIL THEN\n\t\t\t\t\t\t\tFind(t, pat, p, list, caseSens)\n\t\t\t\t\t\tEND\n\t\t\t\t\tEND;\n\t\t\t\t\tfiles := files.next\n\t\t\t\tEND;\n\t\t\t\tdirs := dirs.next\n\t\t\tEND;\n\t\t\tList(list, pat, source, caseSens);\n\t\t\tv := TextViews.dir.New(log);\n\t\t\tGetTitle(pat, title);\n\t\t\tv(TextViews.View).SetDefaults(NewRuler(), TextViews.dir.defAttr);\n\t\t\tViews.OpenAux(v, title);\n\t\t\tc := v(Containers.View).ThisController();\n\t\t\tc.SetOpts(c.opts + {Containers.noCaret});\n\t\t\tw.ConnectTo(NIL);\n\t\t\tDialog.ShowStatus(\"\")\n\t\tEND\n\tEND Search;\n\t\n\tPROCEDURE SearchInSources*;\n\tBEGIN\n\t\tSearch(TRUE, TRUE)\n\tEND SearchInSources;\n\n\tPROCEDURE SearchInDocu* (opts: ARRAY OF CHAR);\n\t\tVAR caseSens: BOOLEAN;\n\tBEGIN\n\t\tcaseSens := ~TextCmds.find.ignoreCase;\n\t\tIF LEN(opts$) > 0 THEN\n\t\t\tIF CAP(opts[0]) = 'S' THEN\n\t\t\t\tcaseSens := TRUE\n\t\t\tELSIF CAP(opts[0]) = 'I' THEN\n\t\t\t\tcaseSens := FALSE\n\t\t\tEND\n\t\tEND;\n\t\tSearch(FALSE, caseSens)\n\tEND SearchInDocu;\n\t\n\tPROCEDURE SelectCaseSens* (pat: ARRAY OF CHAR);\n\tBEGIN\n\t\tTextCmds.find.find := pat$;\n\t\tTextCmds.find.ignoreCase := FALSE;\n\t\tDialog.Update(TextCmds.find);\n\t\tTextCmds.FindFirst(\"\")\n\tEND SelectCaseSens;\n\n\tPROCEDURE SelectCaseInSens* (pat: ARRAY OF CHAR);\n\t\tVAR res: INTEGER; cmd: Dialog.String;\n\tBEGIN\n\t\tTextCmds.find.find := pat$;\n\t\tTextCmds.find.ignoreCase := TRUE;\n\t\tDialog.Update(TextCmds.find);\n\t\tDialog.MapString(openFindCmdKey, cmd);\n\t\tDialog.Call(cmd, openFindCmdNotFoundKey, res);\n\t\tTextCmds.FindFirst(\"\")\n\tEND SelectCaseInSens;\n\n\n\tPROCEDURE NextChar (r: TextModels.Reader): CHAR;\n\t\tVAR ch: CHAR;\n\tBEGIN\n\t\tREPEAT r.ReadChar(ch) UNTIL (ch > \" \") OR r.eot;\n\t\tRETURN ch\n\tEND NextChar;\n\n\tPROCEDURE CompTexts (ta, tb: TextModels.Model; VAR sa, sb, ea, eb: INTEGER);\n\t\tVAR da, db, d, i, j, p: INTEGER; t: LONGINT; ra, rb: TextModels.Reader;\n\t\t\tcha, chb: CHAR; s: ARRAY N OF CHAR;\n\tBEGIN\n\t\tra := ta.NewReader(NIL); ra.SetPos(ea);\n\t\trb := tb.NewReader(NIL); rb.SetPos(eb);\n\t\tREPEAT\n\t\t\tcha := NextChar(ra); chb := NextChar(rb)\n\t\tUNTIL (cha # chb) OR ra.eot OR rb.eot;\n\t\tIF ra.eot THEN sa := ra.Pos() ELSE sa := ra.Pos() - 1 END;\n\t\tIF rb.eot THEN sb := rb.Pos() ELSE sb := rb.Pos() - 1 END;\n\t\tt := Kernel.Time() + T * Kernel.timeResolution;\n\t\tda := sa + 1; db := sb + 1; d := 1; j := 0;\n\t\tREPEAT\n\t\t\tea := da;\n\t\t\tIF ea < ta.Length() THEN\n\t\t\t\tra.SetPos(ea); s[0] := NextChar(ra);\n\t\t\t\tda := ra.Pos(); i := 1;\n\t\t\t\tWHILE i < N DO s[i] := NextChar(ra); INC(i) END;\n\t\t\t\ti := 0; rb.SetPos(sb);\n\t\t\t\tREPEAT\n\t\t\t\t\teb := rb.Pos(); chb := NextChar(rb);\n\t\t\t\t\tIF chb = s[0] THEN\n\t\t\t\t\t\tp := rb.Pos(); j := 0;\n\t\t\t\t\t\tWHILE (j < N) & (chb = s[j]) DO chb := NextChar(rb); INC(j) END;\n\t\t\t\t\t\trb.SetPos(p)\n\t\t\t\t\tEND;\n\t\t\t\t\tINC(i)\n\t\t\t\tUNTIL (j = N) OR (i = d) OR rb.eot\n\t\t\tEND;\n\t\t\tINC(d);\n\t\t\tIF j < N THEN\n\t\t\t\teb := db;\n\t\t\t\tIF eb < tb.Length() THEN\n\t\t\t\t\trb.SetPos(eb); s[0] := NextChar(rb);\n\t\t\t\t\tdb := rb.Pos(); i := 1;\n\t\t\t\t\tWHILE i < N DO s[i] := NextChar(rb); INC(i) END;\n\t\t\t\t\ti := 0; ra.SetPos(sa);\n\t\t\t\t\tREPEAT\n\t\t\t\t\t\tea := ra.Pos(); cha := NextChar(ra);\n\t\t\t\t\t\tIF cha = s[0] THEN\n\t\t\t\t\t\t\tp := ra.Pos(); j := 0;\n\t\t\t\t\t\t\tWHILE (j < N) & (cha = s[j]) DO cha := NextChar(ra); INC(j) END;\n\t\t\t\t\t\t\tra.SetPos(p)\n\t\t\t\t\t\tEND;\n\t\t\t\t\t\tINC(i)\n\t\t\t\t\tUNTIL (j = N) OR (i = d) OR ra.eot\n\t\t\t\tEND\n\t\t\tEND\n\t\tUNTIL (j = N) OR (ea >= ta.Length()) & (eb >= tb.Length()) OR (Kernel.Time() > t);\n\t\tIF j < N THEN ea := ta.Length(); eb := tb.Length() END\n\tEND CompTexts;\n\n\tPROCEDURE Compare*;\n\t\tVAR wa, wb: Windows.Window; va, vb: Views.View; ca, cb: Containers.Controller; sa, sb, ea, eb: INTEGER;\n\tBEGIN\n\t\twa := Windows.dir.First();\n\t\tIF wa # NIL THEN\n\t\t\twb := Windows.dir.Next(wa);\n\t\t\tIF wb # NIL THEN\n\t\t\t\tva := wa.doc.ThisView();\n\t\t\t\tWITH va: TextViews.View DO\n\t\t\t\t\tvb := wb.doc.ThisView();\n\t\t\t\t\tWITH vb: TextViews.View DO\n\t\t\t\t\t\tca := va.ThisController();\n\t\t\t\t\t\tWITH ca: TextControllers.Controller DO\n\t\t\t\t\t\t\tcb := vb.ThisController();\n\t\t\t\t\t\t\tWITH cb: TextControllers.Controller DO\n\t\t\t\t\t\t\t\tca.GetSelection(sa, ea);\n\t\t\t\t\t\t\t\tIF (* ea = -1 *) sa = ea THEN ea := MAX(0, ca.CaretPos()) END;\n\t\t\t\t\t\t\t\tcb.GetSelection(sb, eb);\n\t\t\t\t\t\t\t\tIF (* eb = -1 *) sb = eb THEN eb := MAX(0, cb.CaretPos()) END;\n\t\t\t\t\t\t\t\tCompTexts(va.ThisModel(), vb.ThisModel(), sa, sb, ea, eb);\n\t\t\t\t\t\t\t\tIF ea > sa THEN ca.SetSelection(sa, ea) ELSE ca.SetCaret(sa) END;\n\t\t\t\t\t\t\t\tIF eb > sb THEN cb.SetSelection(sb, eb) ELSE cb.SetCaret(sb) END;\n\t\t\t\t\t\t\t\tva.ShowRangeIn(Views.ThisFrame(wa.frame, va), sa, ea);\n\t\t\t\t\t\t\t\tvb.ShowRangeIn(Views.ThisFrame(wb.frame, vb), sb, eb)\n\t\t\t\t\t\t\tEND\n\t\t\t\t\t\tEND\n\t\t\t\t\tELSE\n\t\t\t\t\tEND\n\t\t\t\tELSE\n\t\t\t\tEND\n\t\t\tEND\n\t\tEND\n\tEND Compare;\n\nEND DevSearch.\n<|endoftext|>"} {"text":"\/*\n* Copyright (C) 2017 by Godlike\n* This code is licensed under the MIT license (MIT)\n* (http:\/\/opensource.org\/licenses\/MIT)\n*\/\n\n#include \n#include \n\n#include \n\nnamespace unicorn\n{\nnamespace video\n{\nvoid Primitives::Cube(Mesh& mesh)\n{\n std::vector vertices{{\n \/\/front\n {{0.5f, -0.5f, 0.5f},{1.0f, 0.0f}},\n {{0.5f, -0.5f, 0.5f},{0.0f, 0.0f}},\n {{0.5f, -0.5f, 0.5f},{0.0f, 0.0f}},\n {{-0.5f, 0.5f, 0.5f},{1.0f, 1.0f}},\n\n \/\/right\n {{0.5f, 0.5f, 0.5f},{1.0f, 1.0f}},\n {{0.5f, 0.5f, -0.5f},{0.0f, 1.0f}},\n {{0.5f, -0.5f, -0.5f},{0.0f, 0.0f}},\n {{0.5f, -0.5f, 0.5f},{1.0f, 0.0f}},\n \/\/back\n {{-0.5f, -0.5f, -0.5f},{1.0f, 0.0f}},\n {{0.5f, -0.5f, -0.5f},{0.0f, 0.0f}},\n {{0.5f, 0.5f, -0.5f},{0.0f, 1.0f}},\n {{-0.5f, 0.5f, -0.5f},{1.0f, 1.0f}},\n\n \/\/left\n {{-0.5f, -0.5f, -0.5f},{1.0f, 0.0f}},\n {{-0.5f, -0.5f, 0.5f},{0.0f, 0.0f}},\n {{-0.5f, 0.5f, 0.5f},{0.0f, 1.0f}},\n {{-0.5f, 0.5f, -0.5f},{1.0f, 1.0f}},\n\n \/\/upper\n {{0.5f, 0.5f, 0.5f},{1.0f, 0.0f}},\n {{-0.5f, 0.5f, 0.5f},{0.0f, 0.0f}},\n {{-0.5f, 0.5f, -0.5f},{0.0f, 1.0f}},\n {{0.5f, 0.5f, -0.5f},{1.0f, 1.0f}},\n\n \/\/bottom\n {{-0.5f, -0.5f, -0.5f},{1.0f, 0.0f}},\n {{0.5f, -0.5f, -0.5f},{0.0f, 0.0f}},\n {{0.5f, -0.5f, 0.5f},{0.0f, 1.0f}},\n {{-0.5f, -0.5f, 0.5f},{1.0f, 1.0f}},\n }};\n\n mesh.SetMeshData(vertices, {\n 0, 1, 2, 0, 2, 3,\n 4, 5, 6, 4, 6, 7,\n 8, 9, 10, 8, 10, 11,\n 12, 13, 14, 12, 14, 15,\n 16, 17, 18, 16, 18, 19,\n 20, 21, 22, 20, 22, 23});\n}\n\nvoid Primitives::Quad(Mesh& mesh)\n{\n std::vector vertices{{\n {{-0.5f , -0.5f , 0.0f},{1.0f , 0.0f}} ,\n {{0.5f , -0.5f , 0.0f},{0.0f , 0.0f}} ,\n {{0.5f , 0.5f , 0.0f},{0.0f , 1.0f}},\n {{-0.5f , 0.5f , 0.0f},{1.0f , 1.0f}},\n }};\n\n mesh.SetMeshData(vertices, {0, 1, 2, 2, 3, 0});\n}\n\nvoid Primitives::Sphere(Mesh& mesh, float radius, uint32_t rings, uint32_t sectors)\n{\n if(radius < 0)\n {\n LOG_WARNING(\"Sphere radius less then 0! UV will be inverted!\");\n }\n if(rings < 4 || sectors < 4)\n {\n LOG_WARNING(\"Rings or sectors are less then 4, sphere will not be generated!\");\n return;\n }\n\n std::vector indices;\n std::vector temp_vertices;\n\n uint32_t vectorSize = rings * sectors;\n\n if(vectorSize > temp_vertices.max_size())\n {\n LOG_WARNING(\"Number of vertices is too big, sphere will not be generated!\");\n return;\n }\n\n temp_vertices.resize(rings * sectors);\n {\n float const R = 1. \/ static_cast(rings - 1);\n float const S = 1. \/ static_cast(sectors - 1);\n\n auto vert_iter = temp_vertices.begin();\n for(uint32_t r = 0; r < rings; r++)\n {\n for(uint32_t s = 0; s < sectors; s++)\n {\n float const y = sin(-glm::half_pi() + glm::pi() * r * R);\n float const x = cos(2 * glm::pi() * s * S) * sin(glm::pi() * r * R);\n float const z = sin(2 * glm::pi() * s * S) * sin(glm::pi() * r * R);\n *vert_iter++ = {{x * radius , y * radius , z * radius},{s * S, r * R}};\n }\n }\n }\n\n indices.resize(sectors * rings * 6);\n auto indices_iter = indices.begin();\n for(uint32_t x = 0; x < sectors; x++)\n {\n for(uint32_t y = 0; y < rings; y++)\n {\n int left = x;\n float right = (x + 1) % sectors;\n float top = y;\n float bottom = (y + 1) % rings;\n *indices_iter++ = {static_cast(left + top * sectors)};\n *indices_iter++ = {static_cast(left + bottom * sectors)};\n *indices_iter++ = {static_cast(right + top * sectors)};\n *indices_iter++ = {static_cast(right + top * sectors)};\n *indices_iter++ = {static_cast(left + bottom * sectors)};\n *indices_iter++ = {static_cast(right + bottom * sectors)};\n }\n }\n\n mesh.SetMeshData(temp_vertices, indices);\n}\n}\n}\n[#84] Fixed cube rendering\/*\n* Copyright (C) 2017 by Godlike\n* This code is licensed under the MIT license (MIT)\n* (http:\/\/opensource.org\/licenses\/MIT)\n*\/\n\n#include \n#include \n\n#include \n\nnamespace unicorn\n{\nnamespace video\n{\nvoid Primitives::Cube(Mesh& mesh)\n{\n std::vector vertices{{\n \/\/front\n {{-0.5f, -0.5f, 0.5f},{1.0f, 0.0f}},\n {{0.5f, -0.5f, 0.5f},{0.0f, 0.0f}},\n {{0.5f, 0.5f, 0.5f},{0.0f, 1.0f}},\n {{-0.5f, 0.5f, 0.5f},{1.0f, 1.0f}},\n\n \/\/right\n {{0.5f, 0.5f, 0.5f},{1.0f, 1.0f}},\n {{0.5f, 0.5f, -0.5f},{0.0f, 1.0f}},\n {{0.5f, -0.5f, -0.5f},{0.0f, 0.0f}},\n {{0.5f, -0.5f, 0.5f},{1.0f, 0.0f}},\n\n \/\/back\n {{-0.5f, -0.5f, -0.5f},{1.0f, 0.0f}},\n {{0.5f, -0.5f, -0.5f},{0.0f, 0.0f}},\n {{0.5f, 0.5f, -0.5f},{0.0f, 1.0f}},\n {{-0.5f, 0.5f, -0.5f},{1.0f, 1.0f}},\n\n \/\/left\n {{-0.5f, -0.5f, -0.5f},{1.0f, 0.0f}},\n {{-0.5f, -0.5f, 0.5f},{0.0f, 0.0f}},\n {{-0.5f, 0.5f, 0.5f},{0.0f, 1.0f}},\n {{-0.5f, 0.5f, -0.5f},{1.0f, 1.0f}},\n\n \/\/upper\n {{0.5f, 0.5f, 0.5f},{1.0f, 0.0f}},\n {{-0.5f, 0.5f, 0.5f},{0.0f, 0.0f}},\n {{-0.5f, 0.5f, -0.5f},{0.0f, 1.0f}},\n {{0.5f, 0.5f, -0.5f},{1.0f, 1.0f}},\n\n \/\/bottom\n {{-0.5f, -0.5f, -0.5f},{1.0f, 0.0f}},\n {{0.5f, -0.5f, -0.5f},{0.0f, 0.0f}},\n {{0.5f, -0.5f, 0.5f},{0.0f, 1.0f}},\n {{-0.5f, -0.5f, 0.5f},{1.0f, 1.0f}},\n }};\n\n mesh.SetMeshData(vertices, {\n 0, 1, 2, 0, 2, 3,\n 4, 5, 6, 4, 6, 7,\n 8, 9, 10, 8, 10, 11,\n 12, 13, 14, 12, 14, 15,\n 16, 17, 18, 16, 18, 19,\n 20, 21, 22, 20, 22, 23});\n}\n\nvoid Primitives::Quad(Mesh& mesh)\n{\n std::vector vertices{{\n {{-0.5f , -0.5f , 0.0f},{1.0f , 0.0f}} ,\n {{0.5f , -0.5f , 0.0f},{0.0f , 0.0f}} ,\n {{0.5f , 0.5f , 0.0f},{0.0f , 1.0f}},\n {{-0.5f , 0.5f , 0.0f},{1.0f , 1.0f}},\n }};\n\n mesh.SetMeshData(vertices, {0, 1, 2, 2, 3, 0});\n}\n\nvoid Primitives::Sphere(Mesh& mesh, float radius, uint32_t rings, uint32_t sectors)\n{\n if(radius < 0)\n {\n LOG_WARNING(\"Sphere radius less then 0! UV will be inverted!\");\n }\n if(rings < 4 || sectors < 4)\n {\n LOG_WARNING(\"Rings or sectors are less then 4, sphere will not be generated!\");\n return;\n }\n\n std::vector indices;\n std::vector temp_vertices;\n\n uint32_t vectorSize = rings * sectors;\n\n if(vectorSize > temp_vertices.max_size())\n {\n LOG_WARNING(\"Number of vertices is too big, sphere will not be generated!\");\n return;\n }\n\n temp_vertices.resize(rings * sectors);\n {\n float const R = 1.f \/ static_cast(rings - 1);\n float const S = 1.f \/ static_cast(sectors - 1);\n\n auto vert_iter = temp_vertices.begin();\n for(uint32_t r = 0; r < rings; r++)\n {\n for(uint32_t s = 0; s < sectors; s++)\n {\n float const y = sin(-glm::half_pi() + glm::pi() * r * R);\n float const x = cos(2 * glm::pi() * s * S) * sin(glm::pi() * r * R);\n float const z = sin(2 * glm::pi() * s * S) * sin(glm::pi() * r * R);\n *vert_iter++ = {{x * radius , y * radius , z * radius},{s * S, r * R}};\n }\n }\n }\n\n indices.resize(sectors * rings * 6);\n auto indices_iter = indices.begin();\n for(uint32_t x = 0; x < sectors; x++)\n {\n for(uint32_t y = 0; y < rings; y++)\n {\n uint32_t left = x;\n float right = static_cast((x + 1) % sectors);\n float top = static_cast(y);\n float bottom = static_cast((y + 1) % rings);\n *indices_iter++ = {static_cast(left + top * sectors)};\n *indices_iter++ = {static_cast(left + bottom * sectors)};\n *indices_iter++ = {static_cast(right + top * sectors)};\n *indices_iter++ = {static_cast(right + top * sectors)};\n *indices_iter++ = {static_cast(left + bottom * sectors)};\n *indices_iter++ = {static_cast(right + bottom * sectors)};\n }\n }\n\n mesh.SetMeshData(temp_vertices, indices);\n}\n}\n}\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2014-2015, RadiantBlue Technologies, Inc.\n\/\/ This file may only be used under the MIT-style\n\/\/ license found in the accompanying LICENSE.txt file.\n\n#include \"TilingScheme.hpp\"\n\n\nTilingScheme::TilingScheme(Rectangle& rectangle,\n boost::uint32_t numberOfLevelZeroTilesX, \/\/ 2\n boost::uint32_t numberOfLevelZeroTilesY) \/\/ 1\n{\n _rectangle = rectangle;\n _numberOfLevelZeroTilesX = numberOfLevelZeroTilesX;\n _numberOfLevelZeroTilesY = numberOfLevelZeroTilesY;\n};\n\n\nconst Rectangle& TilingScheme::getRectangle() const\n{\n return _rectangle;\n}\n\n\nboost::uint32_t TilingScheme::getNumberOfXTilesAtLevel(boost::uint32_t level) const\n{\n return _numberOfLevelZeroTilesX << level;\n};\n\n\nboost::uint32_t TilingScheme::getNumberOfYTilesAtLevel(boost::uint32_t level) const\n{\n return _numberOfLevelZeroTilesY << level;\n}\n\n\nRectangle TilingScheme::rectangleToNativeRectangle(const Rectangle& rectangle) const\n{\n boost::uint32_t west = toDegrees(rectangle.west);\n boost::uint32_t south = toDegrees(rectangle.south);\n boost::uint32_t east = toDegrees(rectangle.east);\n boost::uint32_t north = toDegrees(rectangle.north);\n\n Rectangle result(north, south, east, west);\n return result;\n}\n\n\nRectangle TilingScheme::tileXYToNativeRectangle(boost::uint32_t x, boost::uint32_t y, boost::uint32_t level) const\n{\n Rectangle rectangleRadians = tileXYToRectangle(x, y, level);\n rectangleRadians.west = toDegrees(rectangleRadians.west);\n rectangleRadians.south = toDegrees(rectangleRadians.south);\n rectangleRadians.east = toDegrees(rectangleRadians.east);\n rectangleRadians.north = toDegrees(rectangleRadians.north);\n return rectangleRadians;\n}\n\n\nRectangle TilingScheme::tileXYToRectangle(boost::uint32_t x, boost::uint32_t y, boost::uint32_t level) const\n{\n boost::uint32_t xTiles = getNumberOfXTilesAtLevel(level);\n boost::uint32_t yTiles = getNumberOfYTilesAtLevel(level);\n\n boost::uint32_t xTileWidth = _rectangle.width() \/ xTiles;\n boost::uint32_t west = x * xTileWidth + _rectangle.west;\n boost::uint32_t east = (x + 1) * xTileWidth + _rectangle.west;\n\n boost::uint32_t yTileHeight = _rectangle.height() \/ yTiles;\n boost::uint32_t north = _rectangle.north - y * yTileHeight;\n boost::uint32_t south = _rectangle.north - (y + 1) * yTileHeight;\n\n Rectangle result(west, south, east, north);\n return result;\n}\n\n \/\/ position in cartographic degrees\n bool TilingScheme::positionToTileXY(double xPosition, double yPosition,\n boost::uint32_t& level,\n boost::uint32_t& xResult, boost::uint32_t& yResult) const\n{\n static const double PI = boost::math::constants::pi();\n\n if (!_rectangle.contains(xPosition, yPosition)) {\n \/\/ outside the bounds of the tiling scheme\n return false;\n }\n\n boost::uint32_t xTiles = getNumberOfXTilesAtLevel(level);\n boost::uint32_t yTiles = getNumberOfYTilesAtLevel(level);\n\n boost::uint32_t xTileWidth = _rectangle.width() \/ xTiles;\n boost::uint32_t yTileHeight = _rectangle.height() \/ yTiles;\n\n if (_rectangle.east < _rectangle.west) {\n xPosition += PI * 2.0;\n }\n\n boost::uint32_t xTileCoordinate = (xPosition - _rectangle.west) \/ xTileWidth; \/\/ TODO: trunc\n if (xTileCoordinate >= xTiles) {\n xTileCoordinate = xTiles - 1;\n }\n\n boost::uint32_t yTileCoordinate = (_rectangle.north - yPosition) \/ yTileHeight; \/\/ TODO: trunc\n if (yTileCoordinate >= yTiles) {\n yTileCoordinate = yTiles - 1;\n }\n\n xResult = xTileCoordinate;\n yResult = yTileCoordinate;\n\n return true;\n}\n\nstatic const double PI = boost::math::constants::pi();\n\ndouble TilingScheme::toDegrees(double radians)\n{\n return radians * (180.0\/PI);\n};\n\n\ndouble TilingScheme::toRadians(double degrees)\n{\n return degrees * (PI\/180.0);\n};\nadding in-mem tile hierarchy\/\/ Copyright (c) 2014-2015, RadiantBlue Technologies, Inc.\n\/\/ This file may only be used under the MIT-style\n\/\/ license found in the accompanying LICENSE.txt file.\n\n#include \"TilingScheme.hpp\"\n\n\nclass Buffer {\npublic:\n Buffer(int l, int x, int y) :\n level(l), tileX(x), tileY(y) {\n return;\n }\n\n virtual void add(int l, int x, int y, char* data) = 0;\n\nprotected:\n int level;\n int tileX;\n int tileY;\n};\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\n\/\/ all the points in one tile\nclass TileBuffer : public Buffer\n{\npublic:\n TileBuffer(int l, int x, int y) : Buffer(l, x, y)\n {\n assert(l != -1);\n assert(x != -1);\n assert(y != -1);\n return;\n }\n\n void add(int l, int x, int y, char* data)\n {\n assert(l == level);\n assert(x == tileX);\n assert(y == tileY);\n\n vec.push_back(data);\n }\n\nprivate:\n \/\/ all the points of (a col of a row of a level)\n std::vector vec; \/\/ points\n};\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\n\/\/ all the cols of (a row of a level)\nclass RowsBuffer : public Buffer\n{\npublic:\n RowsBuffer(int l, int x, int y) : Buffer(l, x, y)\n {\n assert(l != -1);\n assert(x != -1);\n assert(y == -1);\n return;\n }\n\n void add(int l, int x, int y, char* data)\n {\n assert(l == level);\n assert(x == tileX);\n assert(-1 == tileY);\n\n TileBuffer* tile = map[y];\n if (!tile) {\n map.insert( std::pair(x, new TileBuffer(l, x, y)) );\n tile = map[y];\n }\n tile->add(l, x, y, data);\n }\n\nprivate:\n \/\/ all the cols of (a row of a level)\n std::map map; \/\/ col -> (tile buffer)\n};\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\n\/\/ all the rows of a level\nclass LevelBuffer : public Buffer {\npublic:\n LevelBuffer(int l, int x, int y) : Buffer(l, x, y)\n {\n assert(l != -1);\n assert(x == -1);\n assert(y == -1);\n }\n\n void add(int l, int x, int y, char* data)\n {\n assert(l == level);\n assert(-1 == tileX);\n assert(-1 == tileY);\n\n RowsBuffer* rows = map[x];\n if (!rows) {\n map.insert( std::pair(x, new RowsBuffer(l, x, -1)) );\n rows = map[x];\n }\n rows->add(l, x, y, data);\n }\n\nprivate:\n \/\/ all the rows of (a level)\n std::map map; \/\/ row -> (row buffer)\n};\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\n\/\/ all the levels\nclass Storage : public Buffer\n{\npublic:\n Storage(int l, int x, int y) : Buffer(l, x, y)\n {\n assert(l == -1);\n assert(x == -1);\n assert(y == -1);\n }\n\n void add(int l, int x, int y, char* data)\n {\n assert(-1 == level);\n assert(-1 == tileX);\n assert(-1 == tileY);\n\n LevelBuffer* level = map[l];\n if (!level) {\n map.insert( std::pair(x, new LevelBuffer(l, -1, -1)) );\n level = map[l];\n }\n level->add(l, x, y, data);\n }\n\nprivate:\n \/\/ all the levels\n std::map map; \/\/ level -> (level buffer)\n\n};\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\nTilingScheme::TilingScheme(Rectangle& rectangle,\n boost::uint32_t numberOfLevelZeroTilesX, \/\/ 2\n boost::uint32_t numberOfLevelZeroTilesY) \/\/ 1\n{\n _rectangle = rectangle;\n _numberOfLevelZeroTilesX = numberOfLevelZeroTilesX;\n _numberOfLevelZeroTilesY = numberOfLevelZeroTilesY;\n};\n\n\nconst Rectangle& TilingScheme::getRectangle() const\n{\n return _rectangle;\n}\n\n\nboost::uint32_t TilingScheme::getNumberOfXTilesAtLevel(boost::uint32_t level) const\n{\n return _numberOfLevelZeroTilesX << level;\n};\n\n\nboost::uint32_t TilingScheme::getNumberOfYTilesAtLevel(boost::uint32_t level) const\n{\n return _numberOfLevelZeroTilesY << level;\n}\n\n\nRectangle TilingScheme::rectangleToNativeRectangle(const Rectangle& rectangle) const\n{\n boost::uint32_t west = toDegrees(rectangle.west);\n boost::uint32_t south = toDegrees(rectangle.south);\n boost::uint32_t east = toDegrees(rectangle.east);\n boost::uint32_t north = toDegrees(rectangle.north);\n\n Rectangle result(north, south, east, west);\n return result;\n}\n\n\nRectangle TilingScheme::tileXYToNativeRectangle(boost::uint32_t x, boost::uint32_t y, boost::uint32_t level) const\n{\n Rectangle rectangleRadians = tileXYToRectangle(x, y, level);\n rectangleRadians.west = toDegrees(rectangleRadians.west);\n rectangleRadians.south = toDegrees(rectangleRadians.south);\n rectangleRadians.east = toDegrees(rectangleRadians.east);\n rectangleRadians.north = toDegrees(rectangleRadians.north);\n return rectangleRadians;\n}\n\n\nRectangle TilingScheme::tileXYToRectangle(boost::uint32_t x, boost::uint32_t y, boost::uint32_t level) const\n{\n boost::uint32_t xTiles = getNumberOfXTilesAtLevel(level);\n boost::uint32_t yTiles = getNumberOfYTilesAtLevel(level);\n\n boost::uint32_t xTileWidth = _rectangle.width() \/ xTiles;\n boost::uint32_t west = x * xTileWidth + _rectangle.west;\n boost::uint32_t east = (x + 1) * xTileWidth + _rectangle.west;\n\n boost::uint32_t yTileHeight = _rectangle.height() \/ yTiles;\n boost::uint32_t north = _rectangle.north - y * yTileHeight;\n boost::uint32_t south = _rectangle.north - (y + 1) * yTileHeight;\n\n Rectangle result(west, south, east, north);\n return result;\n}\n\n \/\/ position in cartographic degrees\n bool TilingScheme::positionToTileXY(double xPosition, double yPosition,\n boost::uint32_t& level,\n boost::uint32_t& xResult, boost::uint32_t& yResult) const\n{\n static const double PI = boost::math::constants::pi();\n\n if (!_rectangle.contains(xPosition, yPosition)) {\n \/\/ outside the bounds of the tiling scheme\n return false;\n }\n\n boost::uint32_t xTiles = getNumberOfXTilesAtLevel(level);\n boost::uint32_t yTiles = getNumberOfYTilesAtLevel(level);\n\n boost::uint32_t xTileWidth = _rectangle.width() \/ xTiles;\n boost::uint32_t yTileHeight = _rectangle.height() \/ yTiles;\n\n if (_rectangle.east < _rectangle.west) {\n xPosition += PI * 2.0;\n }\n\n boost::uint32_t xTileCoordinate = (xPosition - _rectangle.west) \/ xTileWidth; \/\/ TODO: trunc\n if (xTileCoordinate >= xTiles) {\n xTileCoordinate = xTiles - 1;\n }\n\n boost::uint32_t yTileCoordinate = (_rectangle.north - yPosition) \/ yTileHeight; \/\/ TODO: trunc\n if (yTileCoordinate >= yTiles) {\n yTileCoordinate = yTiles - 1;\n }\n\n xResult = xTileCoordinate;\n yResult = yTileCoordinate;\n\n return true;\n}\n\nstatic const double PI = boost::math::constants::pi();\n\ndouble TilingScheme::toDegrees(double radians)\n{\n return radians * (180.0\/PI);\n};\n\n\ndouble TilingScheme::toRadians(double degrees)\n{\n return degrees * (PI\/180.0);\n};\n<|endoftext|>"} {"text":"\/\/===-- ClangMoveTest.cpp - clang-move unit tests -------------------------===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"ClangMove.h\"\n#include \"unittests\/Tooling\/RewriterTestContext.h\"\n#include \"clang\/Format\/Format.h\"\n#include \"clang\/Frontend\/FrontendActions.h\"\n#include \"clang\/Frontend\/TextDiagnosticPrinter.h\"\n#include \"clang\/Rewrite\/Core\/Rewriter.h\"\n#include \"clang\/Tooling\/Refactoring.h\"\n#include \"clang\/Tooling\/Tooling.h\"\n#include \"llvm\/ADT\/StringRef.h\"\n#include \"gtest\/gtest.h\"\n#include \n#include \n\nnamespace clang {\nnamespace move {\nnamespace {\n\nconst char TestHeaderName[] = \"foo.h\";\n\nconst char TestCCName[] = \"foo.cc\";\n\nconst char TestHeader[] = \"namespace a {\\n\"\n \"class C1; \/\/ test\\n\"\n \"namespace b {\\n\"\n \"\/\/ This is a Foo class\\n\"\n \"\/\/ which is used in\\n\"\n \"\/\/ test.\\n\"\n \"class Foo {\\n\"\n \"public:\\n\"\n \" void f();\\n\"\n \"\\n\"\n \"private:\\n\"\n \" C1 *c1;\\n\"\n \" static int b;\\n\"\n \"}; \/\/ abc\\n\"\n \"\\n\"\n \"class Foo2 {\\n\"\n \"public:\\n\"\n \" int f();\\n\"\n \"};\\n\"\n \"} \/\/ namespace b\\n\"\n \"} \/\/ namespace a\\n\";\n\nconst char TestCC[] = \"#include \\\"foo.h\\\"\\n\"\n \"namespace a {\\n\"\n \"namespace b {\\n\"\n \"namespace {\\n\"\n \"\/\/ comment1.\\n\"\n \"void f1() {}\\n\"\n \"\/\/\/ comment2.\\n\"\n \"int kConstInt1 = 0;\\n\"\n \"} \/\/ namespace\\n\"\n \"\\n\"\n \"\/* comment 3*\/\\n\"\n \"static int kConstInt2 = 1;\\n\"\n \"\\n\"\n \"\/** comment4\\n\"\n \"*\/\\n\"\n \"static int help() {\\n\"\n \" int a = 0;\\n\"\n \" return a;\\n\"\n \"}\\n\"\n \"\\n\"\n \"\/\/ comment5\\n\"\n \"\/\/ comment5\\n\"\n \"void Foo::f() { f1(); }\\n\"\n \"\\n\"\n \"\/\/\/\/\/\/\/\/\/\/\/\/\/\\n\"\n \"\/\/ comment \/\/\\n\"\n \"\/\/\/\/\/\/\/\/\/\/\/\/\/\\n\"\n \"int Foo::b = 2;\\n\"\n \"int Foo2::f() {\\n\"\n \" f1();\\n\"\n \" return 1;\\n\"\n \"}\\n\"\n \"} \/\/ namespace b\\n\"\n \"} \/\/ namespace a\\n\";\n\nconst char ExpectedTestHeader[] = \"namespace a {\\n\"\n \"class C1; \/\/ test\\n\"\n \"namespace b {\\n\"\n \"\\n\"\n \"class Foo2 {\\n\"\n \"public:\\n\"\n \" int f();\\n\"\n \"};\\n\"\n \"} \/\/ namespace b\\n\"\n \"} \/\/ namespace a\\n\";\n\nconst char ExpectedTestCC[] = \"#include \\\"foo.h\\\"\\n\"\n \"namespace a {\\n\"\n \"namespace b {\\n\"\n \"namespace {\\n\"\n \"\/\/ comment1.\\n\"\n \"void f1() {}\\n\"\n \"\/\/\/ comment2.\\n\"\n \"int kConstInt1 = 0;\\n\"\n \"} \/\/ namespace\\n\"\n \"\\n\"\n \"\/* comment 3*\/\\n\"\n \"static int kConstInt2 = 1;\\n\"\n \"\\n\"\n \"\/** comment4\\n\"\n \"*\/\\n\"\n \"static int help() {\\n\"\n \" int a = 0;\\n\"\n \" return a;\\n\"\n \"}\\n\"\n \"\\n\"\n \"int Foo2::f() {\\n\"\n \" f1();\\n\"\n \" return 1;\\n\"\n \"}\\n\"\n \"} \/\/ namespace b\\n\"\n \"} \/\/ namespace a\\n\";\n\nconst char ExpectedNewHeader[] = \"#ifndef NEW_FOO_H\\n\"\n \"#define NEW_FOO_H\\n\"\n \"namespace a {\\n\"\n \"class C1; \/\/ test\\n\"\n \"namespace b {\\n\"\n \"\/\/ This is a Foo class\\n\"\n \"\/\/ which is used in\\n\"\n \"\/\/ test.\\n\"\n \"class Foo {\\n\"\n \"public:\\n\"\n \" void f();\\n\"\n \"\\n\"\n \"private:\\n\"\n \" C1 *c1;\\n\"\n \" static int b;\\n\"\n \"}; \/\/ abc\\n\"\n \"} \/\/ namespace b\\n\"\n \"} \/\/ namespace a\\n\"\n \"#endif \/\/ NEW_FOO_H\\n\";\n\nconst char ExpectedNewCC[] = \"namespace a {\\n\"\n \"namespace b {\\n\"\n \"namespace {\\n\"\n \"\/\/ comment1.\\n\"\n \"void f1() {}\\n\"\n \"\/\/\/ comment2.\\n\"\n \"int kConstInt1 = 0;\\n\"\n \"} \/\/ namespace\\n\"\n \"\/* comment 3*\/\\n\"\n \"static int kConstInt2 = 1;\\n\"\n \"\/** comment4\\n\"\n \"*\/\\n\"\n \"static int help() {\\n\"\n \" int a = 0;\\n\"\n \" return a;\\n\"\n \"}\\n\"\n \"\/\/ comment5\\n\"\n \"\/\/ comment5\\n\"\n \"void Foo::f() { f1(); }\\n\"\n \"\/\/\/\/\/\/\/\/\/\/\/\/\/\\n\"\n \"\/\/ comment \/\/\\n\"\n \"\/\/\/\/\/\/\/\/\/\/\/\/\/\\n\"\n \"int Foo::b = 2;\\n\"\n \"} \/\/ namespace b\\n\"\n \"} \/\/ namespace a\\n\";\n\nstd::map\nrunClangMoveOnCode(const move::ClangMoveTool::MoveDefinitionSpec &Spec) {\n clang::RewriterTestContext Context;\n\n std::map FileToFileID;\n std::vector> FileToSourceText = {\n {TestHeaderName, TestHeader}, {TestCCName, TestCC}};\n\n auto CreateFiles = [&FileToSourceText, &Context, &FileToFileID](\n llvm::StringRef Name, llvm::StringRef Code) {\n if (!Name.empty()) {\n FileToSourceText.emplace_back(Name, Code);\n FileToFileID[Name] = Context.createInMemoryFile(Name, Code);\n }\n };\n CreateFiles(Spec.NewCC, \"\");\n CreateFiles(Spec.NewHeader, \"\");\n CreateFiles(Spec.OldHeader, TestHeader);\n CreateFiles(Spec.OldCC, TestCC);\n\n std::map FileToReplacements;\n llvm::SmallString<128> InitialDirectory;\n std::error_code EC = llvm::sys::fs::current_path(InitialDirectory);\n assert(!EC);\n (void)EC;\n auto Factory = llvm::make_unique(\n Spec, FileToReplacements, InitialDirectory.str(), \"LLVM\");\n\n tooling::runToolOnCodeWithArgs(\n Factory->create(), TestCC, {\"-std=c++11\", \"-fparse-all-comments\"},\n TestCCName, \"clang-move\", std::make_shared(),\n FileToSourceText);\n formatAndApplyAllReplacements(FileToReplacements, Context.Rewrite, \"llvm\");\n \/\/ The Key is file name, value is the new code after moving the class.\n std::map Results;\n for (const auto &It : FileToReplacements) {\n StringRef FilePath = It.first;\n Results[FilePath] = Context.getRewrittenText(FileToFileID[FilePath]);\n }\n return Results;\n}\n\nTEST(ClangMove, MoveHeaderAndCC) {\n move::ClangMoveTool::MoveDefinitionSpec Spec;\n Spec.Names = { \"a::b::Foo\" };\n Spec.OldHeader = \"foo.h\";\n Spec.OldCC = \"foo.cc\";\n Spec.NewHeader = \"new_foo.h\";\n Spec.NewCC = \"new_foo.cc\";\n std::string ExpectedHeader = \"#include \\\"\" + Spec.NewHeader + \"\\\"\\n\\n\";\n auto Results = runClangMoveOnCode(Spec);\n EXPECT_EQ(ExpectedTestHeader, Results[Spec.OldHeader]);\n EXPECT_EQ(ExpectedTestCC, Results[Spec.OldCC]);\n EXPECT_EQ(ExpectedNewHeader, Results[Spec.NewHeader]);\n EXPECT_EQ(ExpectedHeader + ExpectedNewCC, Results[Spec.NewCC]);\n}\n\nTEST(ClangMove, MoveHeaderOnly) {\n move::ClangMoveTool::MoveDefinitionSpec Spec;\n Spec.Names = { \"a::b::Foo\" };\n Spec.OldHeader = \"foo.h\";\n Spec.NewHeader = \"new_foo.h\";\n auto Results = runClangMoveOnCode(Spec);\n EXPECT_EQ(2u, Results.size());\n EXPECT_EQ(ExpectedTestHeader, Results[Spec.OldHeader]);\n EXPECT_EQ(ExpectedNewHeader, Results[Spec.NewHeader]);\n}\n\nTEST(ClangMove, MoveCCOnly) {\n move::ClangMoveTool::MoveDefinitionSpec Spec;\n Spec.Names = { \"a::b::Foo\" };\n Spec.OldCC = \"foo.cc\";\n Spec.NewCC = \"new_foo.cc\";\n std::string ExpectedHeader = \"#include \\\"foo.h\\\"\\n\\n\";\n auto Results = runClangMoveOnCode(Spec);\n EXPECT_EQ(2u, Results.size());\n EXPECT_EQ(ExpectedTestCC, Results[Spec.OldCC]);\n EXPECT_EQ(ExpectedHeader + ExpectedNewCC, Results[Spec.NewCC]);\n}\n\nTEST(ClangMove, MoveNonExistClass) {\n move::ClangMoveTool::MoveDefinitionSpec Spec;\n Spec.Names = { \"NonExistFoo\" };\n Spec.OldHeader = \"foo.h\";\n Spec.OldCC = \"foo.cc\";\n Spec.NewHeader = \"new_foo.h\";\n Spec.NewCC = \"new_foo.cc\";\n auto Results = runClangMoveOnCode(Spec);\n EXPECT_EQ(0u, Results.size());\n}\n\n} \/\/ namespace\n} \/\/ namespce move\n} \/\/ namespace clang\nReformat.\/\/===-- ClangMoveTest.cpp - clang-move unit tests -------------------------===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"ClangMove.h\"\n#include \"unittests\/Tooling\/RewriterTestContext.h\"\n#include \"clang\/Format\/Format.h\"\n#include \"clang\/Frontend\/FrontendActions.h\"\n#include \"clang\/Frontend\/TextDiagnosticPrinter.h\"\n#include \"clang\/Rewrite\/Core\/Rewriter.h\"\n#include \"clang\/Tooling\/Refactoring.h\"\n#include \"clang\/Tooling\/Tooling.h\"\n#include \"llvm\/ADT\/StringRef.h\"\n#include \"gtest\/gtest.h\"\n#include \n#include \n\nnamespace clang {\nnamespace move {\nnamespace {\n\nconst char TestHeaderName[] = \"foo.h\";\n\nconst char TestCCName[] = \"foo.cc\";\n\nconst char TestHeader[] = \"namespace a {\\n\"\n \"class C1; \/\/ test\\n\"\n \"namespace b {\\n\"\n \"\/\/ This is a Foo class\\n\"\n \"\/\/ which is used in\\n\"\n \"\/\/ test.\\n\"\n \"class Foo {\\n\"\n \"public:\\n\"\n \" void f();\\n\"\n \"\\n\"\n \"private:\\n\"\n \" C1 *c1;\\n\"\n \" static int b;\\n\"\n \"}; \/\/ abc\\n\"\n \"\\n\"\n \"class Foo2 {\\n\"\n \"public:\\n\"\n \" int f();\\n\"\n \"};\\n\"\n \"} \/\/ namespace b\\n\"\n \"} \/\/ namespace a\\n\";\n\nconst char TestCC[] = \"#include \\\"foo.h\\\"\\n\"\n \"namespace a {\\n\"\n \"namespace b {\\n\"\n \"namespace {\\n\"\n \"\/\/ comment1.\\n\"\n \"void f1() {}\\n\"\n \"\/\/\/ comment2.\\n\"\n \"int kConstInt1 = 0;\\n\"\n \"} \/\/ namespace\\n\"\n \"\\n\"\n \"\/* comment 3*\/\\n\"\n \"static int kConstInt2 = 1;\\n\"\n \"\\n\"\n \"\/** comment4\\n\"\n \"*\/\\n\"\n \"static int help() {\\n\"\n \" int a = 0;\\n\"\n \" return a;\\n\"\n \"}\\n\"\n \"\\n\"\n \"\/\/ comment5\\n\"\n \"\/\/ comment5\\n\"\n \"void Foo::f() { f1(); }\\n\"\n \"\\n\"\n \"\/\/\/\/\/\/\/\/\/\/\/\/\/\\n\"\n \"\/\/ comment \/\/\\n\"\n \"\/\/\/\/\/\/\/\/\/\/\/\/\/\\n\"\n \"int Foo::b = 2;\\n\"\n \"int Foo2::f() {\\n\"\n \" f1();\\n\"\n \" return 1;\\n\"\n \"}\\n\"\n \"} \/\/ namespace b\\n\"\n \"} \/\/ namespace a\\n\";\n\nconst char ExpectedTestHeader[] = \"namespace a {\\n\"\n \"class C1; \/\/ test\\n\"\n \"namespace b {\\n\"\n \"\\n\"\n \"class Foo2 {\\n\"\n \"public:\\n\"\n \" int f();\\n\"\n \"};\\n\"\n \"} \/\/ namespace b\\n\"\n \"} \/\/ namespace a\\n\";\n\nconst char ExpectedTestCC[] = \"#include \\\"foo.h\\\"\\n\"\n \"namespace a {\\n\"\n \"namespace b {\\n\"\n \"namespace {\\n\"\n \"\/\/ comment1.\\n\"\n \"void f1() {}\\n\"\n \"\/\/\/ comment2.\\n\"\n \"int kConstInt1 = 0;\\n\"\n \"} \/\/ namespace\\n\"\n \"\\n\"\n \"\/* comment 3*\/\\n\"\n \"static int kConstInt2 = 1;\\n\"\n \"\\n\"\n \"\/** comment4\\n\"\n \"*\/\\n\"\n \"static int help() {\\n\"\n \" int a = 0;\\n\"\n \" return a;\\n\"\n \"}\\n\"\n \"\\n\"\n \"int Foo2::f() {\\n\"\n \" f1();\\n\"\n \" return 1;\\n\"\n \"}\\n\"\n \"} \/\/ namespace b\\n\"\n \"} \/\/ namespace a\\n\";\n\nconst char ExpectedNewHeader[] = \"#ifndef NEW_FOO_H\\n\"\n \"#define NEW_FOO_H\\n\"\n \"namespace a {\\n\"\n \"class C1; \/\/ test\\n\"\n \"namespace b {\\n\"\n \"\/\/ This is a Foo class\\n\"\n \"\/\/ which is used in\\n\"\n \"\/\/ test.\\n\"\n \"class Foo {\\n\"\n \"public:\\n\"\n \" void f();\\n\"\n \"\\n\"\n \"private:\\n\"\n \" C1 *c1;\\n\"\n \" static int b;\\n\"\n \"}; \/\/ abc\\n\"\n \"} \/\/ namespace b\\n\"\n \"} \/\/ namespace a\\n\"\n \"#endif \/\/ NEW_FOO_H\\n\";\n\nconst char ExpectedNewCC[] = \"namespace a {\\n\"\n \"namespace b {\\n\"\n \"namespace {\\n\"\n \"\/\/ comment1.\\n\"\n \"void f1() {}\\n\"\n \"\/\/\/ comment2.\\n\"\n \"int kConstInt1 = 0;\\n\"\n \"} \/\/ namespace\\n\"\n \"\/* comment 3*\/\\n\"\n \"static int kConstInt2 = 1;\\n\"\n \"\/** comment4\\n\"\n \"*\/\\n\"\n \"static int help() {\\n\"\n \" int a = 0;\\n\"\n \" return a;\\n\"\n \"}\\n\"\n \"\/\/ comment5\\n\"\n \"\/\/ comment5\\n\"\n \"void Foo::f() { f1(); }\\n\"\n \"\/\/\/\/\/\/\/\/\/\/\/\/\/\\n\"\n \"\/\/ comment \/\/\\n\"\n \"\/\/\/\/\/\/\/\/\/\/\/\/\/\\n\"\n \"int Foo::b = 2;\\n\"\n \"} \/\/ namespace b\\n\"\n \"} \/\/ namespace a\\n\";\n\nstd::map\nrunClangMoveOnCode(const move::ClangMoveTool::MoveDefinitionSpec &Spec) {\n clang::RewriterTestContext Context;\n\n std::map FileToFileID;\n std::vector> FileToSourceText = {\n {TestHeaderName, TestHeader}, {TestCCName, TestCC}};\n\n auto CreateFiles = [&FileToSourceText, &Context, &FileToFileID](\n llvm::StringRef Name, llvm::StringRef Code) {\n if (!Name.empty()) {\n FileToSourceText.emplace_back(Name, Code);\n FileToFileID[Name] = Context.createInMemoryFile(Name, Code);\n }\n };\n CreateFiles(Spec.NewCC, \"\");\n CreateFiles(Spec.NewHeader, \"\");\n CreateFiles(Spec.OldHeader, TestHeader);\n CreateFiles(Spec.OldCC, TestCC);\n\n std::map FileToReplacements;\n llvm::SmallString<128> InitialDirectory;\n std::error_code EC = llvm::sys::fs::current_path(InitialDirectory);\n assert(!EC);\n (void)EC;\n auto Factory = llvm::make_unique(\n Spec, FileToReplacements, InitialDirectory.str(), \"LLVM\");\n\n tooling::runToolOnCodeWithArgs(\n Factory->create(), TestCC, {\"-std=c++11\", \"-fparse-all-comments\"},\n TestCCName, \"clang-move\", std::make_shared(),\n FileToSourceText);\n formatAndApplyAllReplacements(FileToReplacements, Context.Rewrite, \"llvm\");\n \/\/ The Key is file name, value is the new code after moving the class.\n std::map Results;\n for (const auto &It : FileToReplacements) {\n StringRef FilePath = It.first;\n Results[FilePath] = Context.getRewrittenText(FileToFileID[FilePath]);\n }\n return Results;\n}\n\nTEST(ClangMove, MoveHeaderAndCC) {\n move::ClangMoveTool::MoveDefinitionSpec Spec;\n Spec.Names = {\"a::b::Foo\"};\n Spec.OldHeader = \"foo.h\";\n Spec.OldCC = \"foo.cc\";\n Spec.NewHeader = \"new_foo.h\";\n Spec.NewCC = \"new_foo.cc\";\n std::string ExpectedHeader = \"#include \\\"\" + Spec.NewHeader + \"\\\"\\n\\n\";\n auto Results = runClangMoveOnCode(Spec);\n EXPECT_EQ(ExpectedTestHeader, Results[Spec.OldHeader]);\n EXPECT_EQ(ExpectedTestCC, Results[Spec.OldCC]);\n EXPECT_EQ(ExpectedNewHeader, Results[Spec.NewHeader]);\n EXPECT_EQ(ExpectedHeader + ExpectedNewCC, Results[Spec.NewCC]);\n}\n\nTEST(ClangMove, MoveHeaderOnly) {\n move::ClangMoveTool::MoveDefinitionSpec Spec;\n Spec.Names = {\"a::b::Foo\"};\n Spec.OldHeader = \"foo.h\";\n Spec.NewHeader = \"new_foo.h\";\n auto Results = runClangMoveOnCode(Spec);\n EXPECT_EQ(2u, Results.size());\n EXPECT_EQ(ExpectedTestHeader, Results[Spec.OldHeader]);\n EXPECT_EQ(ExpectedNewHeader, Results[Spec.NewHeader]);\n}\n\nTEST(ClangMove, MoveCCOnly) {\n move::ClangMoveTool::MoveDefinitionSpec Spec;\n Spec.Names = {\"a::b::Foo\"};\n Spec.OldCC = \"foo.cc\";\n Spec.NewCC = \"new_foo.cc\";\n std::string ExpectedHeader = \"#include \\\"foo.h\\\"\\n\\n\";\n auto Results = runClangMoveOnCode(Spec);\n EXPECT_EQ(2u, Results.size());\n EXPECT_EQ(ExpectedTestCC, Results[Spec.OldCC]);\n EXPECT_EQ(ExpectedHeader + ExpectedNewCC, Results[Spec.NewCC]);\n}\n\nTEST(ClangMove, MoveNonExistClass) {\n move::ClangMoveTool::MoveDefinitionSpec Spec;\n Spec.Names = {\"NonExistFoo\"};\n Spec.OldHeader = \"foo.h\";\n Spec.OldCC = \"foo.cc\";\n Spec.NewHeader = \"new_foo.h\";\n Spec.NewCC = \"new_foo.cc\";\n auto Results = runClangMoveOnCode(Spec);\n EXPECT_EQ(0u, Results.size());\n}\n\n} \/\/ namespace\n} \/\/ namespce move\n} \/\/ namespace clang\n<|endoftext|>"} {"text":"\/\/ This file is part of Eigen, a lightweight C++ template library\n\/\/ for linear algebra.\n\/\/\n\/\/ Copyright (C) 2009 Jitse Niesen \n\/\/\n\/\/ Eigen is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU Lesser General Public\n\/\/ License as published by the Free Software Foundation; either\n\/\/ version 3 of the License, or (at your option) any later version.\n\/\/\n\/\/ Alternatively, you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU General Public License as\n\/\/ published by the Free Software Foundation; either version 2 of\n\/\/ the License, or (at your option) any later version.\n\/\/\n\/\/ Eigen is distributed in the hope that it will be useful, but WITHOUT ANY\n\/\/ WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n\/\/ FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the\n\/\/ GNU General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License and a copy of the GNU General Public License along with\n\/\/ Eigen. If not, see .\n\n#include \"main.h\"\n#include \n\ndouble binom(int n, int k)\n{\n double res = 1;\n for (int i=0; i\ndouble relerr(const MatrixBase& A, const MatrixBase& B)\n{\n return std::sqrt((A - B).cwiseAbs2().sum() \/ std::min(A.cwiseAbs2().sum(), B.cwiseAbs2().sum()));\n}\n\ntemplate \nT expfn(T x, int)\n{\n return std::exp(x);\n}\n\ntemplate \nvoid test2dRotation(double tol)\n{\n Matrix A, B, C;\n T angle;\n\n A << 0, 1, -1, 0;\n for (int i=0; i<=20; i++)\n {\n angle = static_cast(pow(10, i \/ 5. - 2));\n B << cos(angle), sin(angle), -sin(angle), cos(angle);\n\n C = (angle*A).matrixFunction(expfn);\n std::cout << \"test2dRotation: i = \" << i << \" error funm = \" << relerr(C, B);\n VERIFY(C.isApprox(B, static_cast(tol)));\n\n C = (angle*A).exp();\n std::cout << \" error expm = \" << relerr(C, B) << \"\\n\";\n VERIFY(C.isApprox(B, static_cast(tol)));\n }\n}\n\ntemplate \nvoid test2dHyperbolicRotation(double tol)\n{\n Matrix,2,2> A, B, C;\n std::complex imagUnit(0,1);\n T angle, ch, sh;\n\n for (int i=0; i<=20; i++)\n {\n angle = static_cast((i-10) \/ 2.0);\n ch = std::cosh(angle);\n sh = std::sinh(angle);\n A << 0, angle*imagUnit, -angle*imagUnit, 0;\n B << ch, sh*imagUnit, -sh*imagUnit, ch;\n\n C = A.matrixFunction(expfn);\n std::cout << \"test2dHyperbolicRotation: i = \" << i << \" error funm = \" << relerr(C, B);\n VERIFY(C.isApprox(B, static_cast(tol)));\n\n C = A.exp();\n std::cout << \" error expm = \" << relerr(C, B) << \"\\n\";\n VERIFY(C.isApprox(B, static_cast(tol)));\n }\n}\n\ntemplate \nvoid testPascal(double tol)\n{\n for (int size=1; size<20; size++)\n {\n Matrix A(size,size), B(size,size), C(size,size);\n A.setZero();\n for (int i=0; i(i+1);\n B.setZero();\n for (int i=0; i(binom(i,j));\n\n C = A.matrixFunction(expfn);\n std::cout << \"testPascal: size = \" << size << \" error funm = \" << relerr(C, B);\n VERIFY(C.isApprox(B, static_cast(tol)));\n\n C = A.exp();\n std::cout << \" error expm = \" << relerr(C, B) << \"\\n\";\n VERIFY(C.isApprox(B, static_cast(tol)));\n }\n}\n\ntemplate\nvoid randomTest(const MatrixType& m, double tol)\n{\n \/* this test covers the following files:\n Inverse.h\n *\/\n typename MatrixType::Index rows = m.rows();\n typename MatrixType::Index cols = m.cols();\n MatrixType m1(rows, cols), m2(rows, cols), m3(rows, cols),\n identity = MatrixType::Identity(rows, rows);\n\n typedef typename NumTraits::Scalar>::Real RealScalar;\n\n for(int i = 0; i < g_repeat; i++) {\n m1 = MatrixType::Random(rows, cols);\n\n m2 = m1.matrixFunction(expfn) * (-m1).matrixFunction(expfn);\n std::cout << \"randomTest: error funm = \" << relerr(identity, m2);\n VERIFY(identity.isApprox(m2, static_cast(tol)));\n\n m2 = m1.exp() * (-m1).exp();\n std::cout << \" error expm = \" << relerr(identity, m2) << \"\\n\";\n VERIFY(identity.isApprox(m2, static_cast(tol)));\n }\n}\n\nvoid test_matrix_exponential()\n{\n CALL_SUBTEST_2(test2dRotation(1e-13));\n CALL_SUBTEST_1(test2dRotation(1e-5));\n CALL_SUBTEST_2(test2dHyperbolicRotation(1e-14));\n CALL_SUBTEST_1(test2dHyperbolicRotation(1e-5));\n CALL_SUBTEST_6(testPascal(1e-6));\n CALL_SUBTEST_5(testPascal(1e-15));\n CALL_SUBTEST_2(randomTest(Matrix2d(), 1e-13));\n CALL_SUBTEST_7(randomTest(Matrix(), 1e-13));\n CALL_SUBTEST_3(randomTest(Matrix4cd(), 1e-13));\n CALL_SUBTEST_4(randomTest(MatrixXd(8,8), 1e-13));\n CALL_SUBTEST_1(randomTest(Matrix2f(), 1e-4));\n CALL_SUBTEST_5(randomTest(Matrix3cf(), 1e-4));\n CALL_SUBTEST_1(randomTest(Matrix4f(), 1e-4));\n CALL_SUBTEST_6(randomTest(MatrixXf(8,8), 1e-4));\n}\nrelax condition in matrix_exponential test for clang\/\/ This file is part of Eigen, a lightweight C++ template library\n\/\/ for linear algebra.\n\/\/\n\/\/ Copyright (C) 2009 Jitse Niesen \n\/\/\n\/\/ Eigen is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU Lesser General Public\n\/\/ License as published by the Free Software Foundation; either\n\/\/ version 3 of the License, or (at your option) any later version.\n\/\/\n\/\/ Alternatively, you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU General Public License as\n\/\/ published by the Free Software Foundation; either version 2 of\n\/\/ the License, or (at your option) any later version.\n\/\/\n\/\/ Eigen is distributed in the hope that it will be useful, but WITHOUT ANY\n\/\/ WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n\/\/ FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the\n\/\/ GNU General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License and a copy of the GNU General Public License along with\n\/\/ Eigen. If not, see .\n\n#include \"main.h\"\n#include \n\ndouble binom(int n, int k)\n{\n double res = 1;\n for (int i=0; i\ndouble relerr(const MatrixBase& A, const MatrixBase& B)\n{\n return std::sqrt((A - B).cwiseAbs2().sum() \/ std::min(A.cwiseAbs2().sum(), B.cwiseAbs2().sum()));\n}\n\ntemplate \nT expfn(T x, int)\n{\n return std::exp(x);\n}\n\ntemplate \nvoid test2dRotation(double tol)\n{\n Matrix A, B, C;\n T angle;\n\n A << 0, 1, -1, 0;\n for (int i=0; i<=20; i++)\n {\n angle = static_cast(pow(10, i \/ 5. - 2));\n B << cos(angle), sin(angle), -sin(angle), cos(angle);\n\n C = (angle*A).matrixFunction(expfn);\n std::cout << \"test2dRotation: i = \" << i << \" error funm = \" << relerr(C, B);\n VERIFY(C.isApprox(B, static_cast(tol)));\n\n C = (angle*A).exp();\n std::cout << \" error expm = \" << relerr(C, B) << \"\\n\";\n VERIFY(C.isApprox(B, static_cast(tol)));\n }\n}\n\ntemplate \nvoid test2dHyperbolicRotation(double tol)\n{\n Matrix,2,2> A, B, C;\n std::complex imagUnit(0,1);\n T angle, ch, sh;\n\n for (int i=0; i<=20; i++)\n {\n angle = static_cast((i-10) \/ 2.0);\n ch = std::cosh(angle);\n sh = std::sinh(angle);\n A << 0, angle*imagUnit, -angle*imagUnit, 0;\n B << ch, sh*imagUnit, -sh*imagUnit, ch;\n\n C = A.matrixFunction(expfn);\n std::cout << \"test2dHyperbolicRotation: i = \" << i << \" error funm = \" << relerr(C, B);\n VERIFY(C.isApprox(B, static_cast(tol)));\n\n C = A.exp();\n std::cout << \" error expm = \" << relerr(C, B) << \"\\n\";\n VERIFY(C.isApprox(B, static_cast(tol)));\n }\n}\n\ntemplate \nvoid testPascal(double tol)\n{\n for (int size=1; size<20; size++)\n {\n Matrix A(size,size), B(size,size), C(size,size);\n A.setZero();\n for (int i=0; i(i+1);\n B.setZero();\n for (int i=0; i(binom(i,j));\n\n C = A.matrixFunction(expfn);\n std::cout << \"testPascal: size = \" << size << \" error funm = \" << relerr(C, B);\n VERIFY(C.isApprox(B, static_cast(tol)));\n\n C = A.exp();\n std::cout << \" error expm = \" << relerr(C, B) << \"\\n\";\n VERIFY(C.isApprox(B, static_cast(tol)));\n }\n}\n\ntemplate\nvoid randomTest(const MatrixType& m, double tol)\n{\n \/* this test covers the following files:\n Inverse.h\n *\/\n typename MatrixType::Index rows = m.rows();\n typename MatrixType::Index cols = m.cols();\n MatrixType m1(rows, cols), m2(rows, cols), m3(rows, cols),\n identity = MatrixType::Identity(rows, rows);\n\n typedef typename NumTraits::Scalar>::Real RealScalar;\n\n for(int i = 0; i < g_repeat; i++) {\n m1 = MatrixType::Random(rows, cols);\n\n m2 = m1.matrixFunction(expfn) * (-m1).matrixFunction(expfn);\n std::cout << \"randomTest: error funm = \" << relerr(identity, m2);\n VERIFY(identity.isApprox(m2, static_cast(tol)));\n\n m2 = m1.exp() * (-m1).exp();\n std::cout << \" error expm = \" << relerr(identity, m2) << \"\\n\";\n VERIFY(identity.isApprox(m2, static_cast(tol)));\n }\n}\n\nvoid test_matrix_exponential()\n{\n CALL_SUBTEST_2(test2dRotation(1e-13));\n CALL_SUBTEST_1(test2dRotation(2e-5)); \/\/ was 1e-5, relaxed for clang 2.8 \/ linux \/ x86-64\n CALL_SUBTEST_2(test2dHyperbolicRotation(1e-14));\n CALL_SUBTEST_1(test2dHyperbolicRotation(1e-5));\n CALL_SUBTEST_6(testPascal(1e-6));\n CALL_SUBTEST_5(testPascal(1e-15));\n CALL_SUBTEST_2(randomTest(Matrix2d(), 1e-13));\n CALL_SUBTEST_7(randomTest(Matrix(), 1e-13));\n CALL_SUBTEST_3(randomTest(Matrix4cd(), 1e-13));\n CALL_SUBTEST_4(randomTest(MatrixXd(8,8), 1e-13));\n CALL_SUBTEST_1(randomTest(Matrix2f(), 1e-4));\n CALL_SUBTEST_5(randomTest(Matrix3cf(), 1e-4));\n CALL_SUBTEST_1(randomTest(Matrix4f(), 1e-4));\n CALL_SUBTEST_6(randomTest(MatrixXf(8,8), 1e-4));\n}\n<|endoftext|>"} {"text":"#include \"UDPServerSocket.h\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"MessageDecoder.h\"\n\nextern \"C\" {\n\tchar * inet_ntoa(struct in_addr);\n}\n\nUDPServerSocket::UDPServerSocket(char * _myAddr, int _myPort):UDPSocket(){\n\tin_mutex = PTHREAD_MUTEX_INITIALIZER;\n\tout_mutex = PTHREAD_MUTEX_INITIALIZER;\n\n\tif(!initializeServer(_myAddr, _myPort))\n\t\tcout<<\"failed to initialize Socket\\n\";\n\tpthread_t p;\n\tpthread_create( &p, NULL, &UDPServerSocket::messenger, this);\n}\n\nbool UDPServerSocket::initializeServer (char * _myAddr, int _myPort){\n\tlock();\n\tmyAddress = new char[strlen(_myAddr)+1];\n\tstrcpy(myAddress,_myAddr);\n\tmyPort = _myPort;\n\tmyAddr.sin_family = AF_INET;\n\tmyAddr.sin_port = htons(myPort);\n\tmyAddr.sin_addr.s_addr = htonl(INADDR_ANY);\n\tif(bind(sock, (const sockaddr*)(&myAddr), sizeof(struct sockaddr_in))!= 0){\n\t\tperror(\"Bind failed\\n\");\n\t\tclose(sock);\n\t\tunlock();\n\t\treturn false;\n\t}\n\tpeerAddr.sin_family = AF_INET;\n\tsize_t nn = 1024*1024*10;\n\tif (setsockopt(sock, SOL_SOCKET, SO_SNDBUF, &nn, sizeof(nn)) == -1) {\n\t\t\tcout<<\"failed to resize buffer\\n\";\n\t\t}\n\tunlock();\n\treturn true;\n}\n\nvoid* UDPServerSocket::messenger(void* arg){\n\tUDPServerSocket* me = (UDPServerSocket*)arg;\n\tint WORK;\n\twhile(true){\n\t\tWORK = 0;\n\t\tif(me->readyToRead()){\n\t\t\tcout<<\"inbox is not empty\\n\";\n\t\t\tWORK++;\n\t\t\tchar* incoming = new char[MAX_DATAGRAM_SIZE];\n\t\t\tint trials = 2;\n\t\t\twhile(trials--){\n\t\t\t\tint res = me->readFromSocketWithBlock(incoming, MAX_DATAGRAM_SIZE);\n\t\t\t\tif(res<0)\n\t\t\t\t\tcout<<\"Error reading packet..\\n\";\n\t\t\t\telse\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t\tMessage* temp = new Message(incoming);\n\t\t\tdelete [] incoming;\n\t\t\tif(me->ip_id.find({temp->getRPCId(), MessageDecoder::encodeIpPort(me->peerAddr)})==me->ip_id.end()){\n\t\t\t\tint new_rpc = Message::getNewRPC();\n\t\t\t\tcout<<\"the new local rpcid is: \"<ip_id[{temp->getRPCId(), MessageDecoder::encodeIpPort(me->peerAddr)}] = new_rpc;\n\t\t\t\tme->id_ip[new_rpc] = {temp->getRPCId(), MessageDecoder::encodeIpPort(me->peerAddr)};\n\t\t\t\ttemp->setRPCId(new_rpc);\n\t\t\t}else{\n\t\t\t\tint new_rpc = me->ip_id[{temp->getRPCId(), MessageDecoder::encodeIpPort(me->peerAddr)}];\n\t\t\t\ttemp->setRPCId(new_rpc);\n\t\t\t}\n\t\t\tif(temp->getMessageType()== Ack){\n\t\t\t\tpthread_mutex_lock(&me->ack_mutex);\n\t\t\t\tme->acks.push(temp);\n\t\t\t\tpthread_mutex_unlock(&me->ack_mutex);\n\t\t\t}else if(temp->isComplete()){\n\t\t\t\tpthread_mutex_lock(&me->in_mutex);\n\t\t\t\tme->inbox.push(temp);\n\t\t\t\tpthread_mutex_unlock(&me->in_mutex);\n\t\t\t}else{\n\t\t\t\tme->parts[temp->getRPCId()].push_back(temp);\n\t\t\t\tif(me->parts[temp->getRPCId()].size()==temp->getPartsNum()){\n\t\t\t\t\ttemp = new Message(me->parts[temp->getRPCId()]);\n\t\t\t\t\tpthread_mutex_lock(&me->in_mutex);\n\t\t\t\t\tme->inbox.push(temp);\n\t\t\t\t\tpthread_mutex_unlock(&me->in_mutex);\n\t\t\t\t}\n\t\t\t}\n\n\t\t}\n\n\t\tpthread_mutex_lock(&me->out_mutex);\n\t\tif(!me->outbox.empty())\n\t\t{\n\t\t\tcout<<\"outbox is not empty\";\n\t\t\tWORK++;\n\t\t\tMessage* temp = me->outbox.front();\n\t\t\tme->outbox.pop();\n\t\t\tpthread_mutex_unlock(&me->out_mutex);\n\t\t\tint trials = 3;\n\t\t\tcout<<\"this is the message to send\\n\";\n\/\/\t\t\ttemp->print();\n\t\t\tint localRPCId = temp->getRPCId();\n\t\t\ttemp->setRPCId(me->id_ip[localRPCId].first);\n\n\t\t\twhile(trials--){\n\t\t\t\tint t = 0;\n\t\t\t\tchar* x = temp->marshal(t);\n\t\t\t\tme->setPeer(MessageDecoder::decodeIpPort(me->id_ip[localRPCId].second));\n\t\t\t\tint res = me->writeToSocket(x,t);\n\t\t\t\tif(res<0)\n\t\t\t\t\tcout<<\"error sending packet\\n\";\n\t\t\t\telse{\n\t\t\t\t\tcout<<\"packet sent\\n\";\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\telse\n\t\t\tpthread_mutex_unlock(&me->out_mutex);\n\t\tif(!WORK){\n\/\/\t\t\tsleep(1);\n\t\t\t;\n\t\t}\n\t}\n\n}\nvoid UDPServerSocket::sendReply(Message* m){\n\tvector temp_parts;\n\tif(m->getMessageSize()+32 > MAX_DATAGRAM_SIZE)\n\t\tcout<<(sendReplyWaitAck(m,10)?\"sent successfully\\n\":\"failed to send\\n\")< temp_parts,copy;\n\tvector recvAck;\n\ttemp_parts = m->split(MAX_DATAGRAM_SIZE);\n\tcopy.resize(temp_parts.size());\n\trecvAck.assign(temp_parts.size(),false);\n\tcout<<\"this message is split into \"<getPartNum()] = true;\n\n\/\/\t\t\tdelete temp;\n\t\t}\n\t\tpthread_mutex_unlock(&ack_mutex);\n\t}\n\tif(done)\n\t\treturn true;\n\telse\n\t\treturn false;\n}\n\nbool UDPServerSocket::readyRequest(){\n\tbool flag = true;\n\tpthread_mutex_lock(&in_mutex);\n\tif(inbox.empty())\n\t\tflag = false;\n\tpthread_mutex_unlock(&in_mutex);\n\treturn flag;\n}\n\nMessage* UDPServerSocket::getRequest(){\n\tif(!readyRequest())\n\t\treturn NULL;\n\tpthread_mutex_lock(&in_mutex);\n\tMessage * temp = inbox.front();\n\tinbox.pop();\n\tpthread_mutex_unlock(&in_mutex);\n\treturn temp;\n}\nsockaddr_in UDPServerSocket::getMyAddr(){\n\treturn this->myAddr;\n}\n\npair UDPServerSocket::getMyAddrPair(){\n\treturn {string(myAddress), myPort};\n}\nUDPServerSocket::~UDPServerSocket (){\n\tpthread_mutex_destroy(&in_mutex);\n\tpthread_mutex_destroy(&out_mutex);\n\n};\n\n\n\ntrials#include \"UDPServerSocket.h\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"MessageDecoder.h\"\n\nextern \"C\" {\n\tchar * inet_ntoa(struct in_addr);\n}\n\nUDPServerSocket::UDPServerSocket(char * _myAddr, int _myPort):UDPSocket(){\n\tin_mutex = PTHREAD_MUTEX_INITIALIZER;\n\tout_mutex = PTHREAD_MUTEX_INITIALIZER;\n\n\tif(!initializeServer(_myAddr, _myPort))\n\t\tcout<<\"failed to initialize Socket\\n\";\n\tpthread_t p;\n\tpthread_create( &p, NULL, &UDPServerSocket::messenger, this);\n}\n\nbool UDPServerSocket::initializeServer (char * _myAddr, int _myPort){\n\tlock();\n\tmyAddress = new char[strlen(_myAddr)+1];\n\tstrcpy(myAddress,_myAddr);\n\tmyPort = _myPort;\n\tmyAddr.sin_family = AF_INET;\n\tmyAddr.sin_port = htons(myPort);\n\tmyAddr.sin_addr.s_addr = htonl(INADDR_ANY);\n\tif(bind(sock, (const sockaddr*)(&myAddr), sizeof(struct sockaddr_in))!= 0){\n\t\tperror(\"Bind failed\\n\");\n\t\tclose(sock);\n\t\tunlock();\n\t\treturn false;\n\t}\n\tpeerAddr.sin_family = AF_INET;\n\tsize_t nn = 1024*1024*10;\n\tif (setsockopt(sock, SOL_SOCKET, SO_SNDBUF, &nn, sizeof(nn)) == -1) {\n\t\t\tcout<<\"failed to resize buffer\\n\";\n\t\t}\n\tunlock();\n\treturn true;\n}\n\nvoid* UDPServerSocket::messenger(void* arg){\n\tUDPServerSocket* me = (UDPServerSocket*)arg;\n\tint WORK;\n\twhile(true){\n\t\tWORK = 0;\n\t\tif(me->readyToRead()){\n\t\t\tcout<<\"inbox is not empty\\n\";\n\t\t\tWORK++;\n\t\t\tchar* incoming = new char[MAX_DATAGRAM_SIZE];\n\t\t\tint trials = 2;\n\t\t\twhile(trials--){\n\t\t\t\tint res = me->readFromSocketWithBlock(incoming, MAX_DATAGRAM_SIZE);\n\t\t\t\tif(res<0)\n\t\t\t\t\tcout<<\"Error reading packet..\\n\";\n\t\t\t\telse\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t\tMessage* temp = new Message(incoming);\n\t\t\tdelete [] incoming;\n\t\t\tif(me->ip_id.find({temp->getRPCId(), MessageDecoder::encodeIpPort(me->peerAddr)})==me->ip_id.end()){\n\t\t\t\tint new_rpc = Message::getNewRPC();\n\t\t\t\tcout<<\"the new local rpcid is: \"<ip_id[{temp->getRPCId(), MessageDecoder::encodeIpPort(me->peerAddr)}] = new_rpc;\n\t\t\t\tme->id_ip[new_rpc] = {temp->getRPCId(), MessageDecoder::encodeIpPort(me->peerAddr)};\n\t\t\t\ttemp->setRPCId(new_rpc);\n\t\t\t}else{\n\t\t\t\tint new_rpc = me->ip_id[{temp->getRPCId(), MessageDecoder::encodeIpPort(me->peerAddr)}];\n\t\t\t\ttemp->setRPCId(new_rpc);\n\t\t\t}\n\t\t\tif(temp->getMessageType()== Ack){\n\t\t\t\tpthread_mutex_lock(&me->ack_mutex);\n\t\t\t\tme->acks.push(temp);\n\t\t\t\tpthread_mutex_unlock(&me->ack_mutex);\n\t\t\t}else if(temp->isComplete()){\n\t\t\t\tpthread_mutex_lock(&me->in_mutex);\n\t\t\t\tme->inbox.push(temp);\n\t\t\t\tpthread_mutex_unlock(&me->in_mutex);\n\t\t\t}else{\n\t\t\t\tme->parts[temp->getRPCId()].push_back(temp);\n\t\t\t\tif(me->parts[temp->getRPCId()].size()==temp->getPartsNum()){\n\t\t\t\t\ttemp = new Message(me->parts[temp->getRPCId()]);\n\t\t\t\t\tpthread_mutex_lock(&me->in_mutex);\n\t\t\t\t\tme->inbox.push(temp);\n\t\t\t\t\tpthread_mutex_unlock(&me->in_mutex);\n\t\t\t\t}\n\t\t\t}\n\n\t\t}\n\n\t\tpthread_mutex_lock(&me->out_mutex);\n\t\tif(!me->outbox.empty())\n\t\t{\n\t\t\tcout<<\"outbox is not empty\";\n\t\t\tWORK++;\n\t\t\tMessage* temp = me->outbox.front();\n\t\t\tme->outbox.pop();\n\t\t\tpthread_mutex_unlock(&me->out_mutex);\n\t\t\tint trials = 3;\n\t\t\tcout<<\"this is the message to send\\n\";\n\/\/\t\t\ttemp->print();\n\t\t\tint localRPCId = temp->getRPCId();\n\t\t\ttemp->setRPCId(me->id_ip[localRPCId].first);\n\n\t\t\twhile(trials--){\n\t\t\t\tint t = 0;\n\t\t\t\tchar* x = temp->marshal(t);\n\t\t\t\tme->setPeer(MessageDecoder::decodeIpPort(me->id_ip[localRPCId].second));\n\t\t\t\tint res = me->writeToSocket(x,t);\n\t\t\t\tif(res<0)\n\t\t\t\t\tcout<<\"error sending packet\\n\";\n\t\t\t\telse{\n\t\t\t\t\tcout<<\"packet sent\\n\";\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\telse\n\t\t\tpthread_mutex_unlock(&me->out_mutex);\n\t\tif(!WORK){\n\/\/\t\t\tsleep(1);\n\t\t\t;\n\t\t}\n\t}\n\n}\nvoid UDPServerSocket::sendReply(Message* m){\n\tvector temp_parts;\n\tif(m->getMessageSize()+32 > MAX_DATAGRAM_SIZE)\n cout<<(sendReplyWaitAck(m,100)?\"sent successfully\\n\":\"failed to send\\n\")< temp_parts,copy;\n\tvector recvAck;\n\ttemp_parts = m->split(MAX_DATAGRAM_SIZE);\n\tcopy.resize(temp_parts.size());\n\trecvAck.assign(temp_parts.size(),false);\n\tcout<<\"this message is split into \"<getPartNum()] = true;\n\n\/\/\t\t\tdelete temp;\n\t\t}\n\t\tpthread_mutex_unlock(&ack_mutex);\n\t}\n\tif(done)\n\t\treturn true;\n\telse\n\t\treturn false;\n}\n\nbool UDPServerSocket::readyRequest(){\n\tbool flag = true;\n\tpthread_mutex_lock(&in_mutex);\n\tif(inbox.empty())\n\t\tflag = false;\n\tpthread_mutex_unlock(&in_mutex);\n\treturn flag;\n}\n\nMessage* UDPServerSocket::getRequest(){\n\tif(!readyRequest())\n\t\treturn NULL;\n\tpthread_mutex_lock(&in_mutex);\n\tMessage * temp = inbox.front();\n\tinbox.pop();\n\tpthread_mutex_unlock(&in_mutex);\n\treturn temp;\n}\nsockaddr_in UDPServerSocket::getMyAddr(){\n\treturn this->myAddr;\n}\n\npair UDPServerSocket::getMyAddrPair(){\n\treturn {string(myAddress), myPort};\n}\nUDPServerSocket::~UDPServerSocket (){\n\tpthread_mutex_destroy(&in_mutex);\n\tpthread_mutex_destroy(&out_mutex);\n\n};\n\n\n\n<|endoftext|>"} {"text":"\/*****************************************************************************\n * Licensed to Qualys, Inc. (QUALYS) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * QUALYS licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n ****************************************************************************\/\n\n\/**\n * @file\n * @brief IronBee --- Trusted Proxy Module\n *\/\n\n\/\/ Include all of IronBee++\n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n\n#include \n\nusing namespace std;\n\nnamespace {\n\n\/**\n * Configuration for the Trusted Proxy Module\n *\/\nclass TrustedProxyConfig\n{\npublic:\n \/\/! Constructor.\n TrustedProxyConfig();\n\n \/\/! Is X-Forwarded-For handling enabled?\n bool is_xff_enabled() const;\n\n \/\/! Enable or disable X-Forwarded-For handling.\n void set_xff_enabled(bool enabled);\n\n \/\/! Clear the trusted and untrusted network lists.\n void clear_networks();\n\n \/\/! Add a network to the trusted list.\n void add_trusted_network(const char* network);\n\n \/\/! Add a network to the untrusted list.\n void add_untrusted_network(const char* network);\n\n \/**\n * Check if the ip address is trusted.\n *\n * The default is to trust all addresses.\n *\n * @param[in] ipstr IP address to check.\n *\n * @returns True if the address is trusted.\n *\/\n bool is_trusted(const char* ipstr) const;\n\n \/\/! Finalize the configuration when the context is closed.\n void context_close(IronBee::Engine& ib);\n\nprivate:\n \/\/! X-Forwarding-For handling enabled?\n bool m_xff_enabled;\n\n \/\/! List of trusted networks\n vector m_trusted_net_list;\n\n \/\/! List of untrusted networks\n vector m_untrusted_net_list;\n\n \/\/! IP set of the trusted and untrusted networks.\n ib_ipset4_t m_trusted_networks;\n};\n\n\/**\n * Module to handle X-Forwarded-For headers from trusted Proxies.\n *\/\nclass TrustedProxyModule : public IronBee::ModuleDelegate\n{\npublic:\n \/\/! Constructor.\n explicit TrustedProxyModule(IronBee::Module module);\n\nprivate:\n \/\/! Source for recording the remote address\n IronBee::VarSource m_remote_addr_source;\n\n \/**\n * Handle the TrustedProxyUseXFFHeader directive.\n *\n * @param[in] cp Configuration parser.\n * @param[in] enabled Should XFF handling be enabled?\n *\/\n void enable_xff_directive(\n IronBee::ConfigurationParser cp,\n bool enabled);\n\n \/**\n * @param[in] cp Configuration parser.\n * @param[in] ip_list List of IPs or CIDR blocks.\n *\/\n void trusted_ips_directive(\n IronBee::ConfigurationParser cp,\n IronBee::ConstList ip_list);\n\n void on_context_close(IronBee::Engine ib, IronBee::Context ctx);\n\n \/**\n * Update the transaction effective IP based.\n *\n * @param[in] ib Ironbee engine.\n * @param[in,out] tx Transaction to update.\n *\/\n void set_effective_ip(\n IronBee::Engine ib,\n IronBee::Transaction tx);\n};\n\n} \/\/ Anonymous namespace\n\nIBPP_BOOTSTRAP_MODULE_DELEGATE(\"TrustedProxyModule\", TrustedProxyModule)\n\nnamespace {\n\nvoid make_ipset_entry(const char* cidr_or_ip, ib_ipset4_entry_t& entry)\n{\n if (strchr(cidr_or_ip, '\/') != NULL) {\n \/\/ Has \/ assume CIDR\n IronBee::throw_if_error(\n ib_ip4_str_to_net(cidr_or_ip, &(entry.network)),\n \"Invalid CIDR block\");\n }\n else {\n \/\/ IP make \/32\n IronBee::throw_if_error(\n ib_ip4_str_to_ip(cidr_or_ip, &(entry.network.ip)),\n \"Invalid IP address\");\n entry.network.size=32;\n }\n}\n\nTrustedProxyConfig::TrustedProxyConfig()\n : m_xff_enabled(true)\n{\n ib_ipset4_init(&m_trusted_networks, NULL, 0, NULL, 0);\n}\n\nbool TrustedProxyConfig::is_xff_enabled() const\n{\n return m_xff_enabled;\n}\n\nvoid TrustedProxyConfig::set_xff_enabled(bool enabled)\n{\n m_xff_enabled = enabled;\n}\n\nvoid TrustedProxyConfig::clear_networks()\n{\n m_trusted_net_list.clear();\n m_untrusted_net_list.clear();\n}\n\nvoid TrustedProxyConfig::add_trusted_network(const char* cidr_or_ip)\n{\n ib_ipset4_entry_t net_entry;\n make_ipset_entry(cidr_or_ip, net_entry);\n m_trusted_net_list.push_back(net_entry);\n}\n\nvoid TrustedProxyConfig::add_untrusted_network(const char* cidr_or_ip)\n{\n ib_ipset4_entry_t net_entry;\n make_ipset_entry(cidr_or_ip, net_entry);\n m_untrusted_net_list.push_back(net_entry);\n}\n\nvoid TrustedProxyConfig::context_close(IronBee::Engine& ib)\n{\n IronBee::throw_if_error(\n ib_ipset4_init(\n &m_trusted_networks,\n m_untrusted_net_list.data(),\n m_untrusted_net_list.size(),\n m_trusted_net_list.data(),\n m_trusted_net_list.size()),\n \"Failed to initialize IPv4 set.\");\n}\n\nbool TrustedProxyConfig::is_trusted(const char* ipstr) const\n{\n ib_ip4_t ip;\n\n IronBee::throw_if_error(\n ib_ip4_str_to_ip(ipstr, &ip),\n \"Invalid remote IP address\");\n ib_status_t rc =\n ib_ipset4_query(&m_trusted_networks, ip, NULL, NULL, NULL);\n return rc == IB_OK;\n}\n\nTrustedProxyModule::TrustedProxyModule(IronBee::Module module) :\n IronBee::ModuleDelegate(module)\n{\n module.set_configuration_data();\n\n m_remote_addr_source = IronBee::VarSource::register_(\n module.engine().var_config(),\n IB_S2SL(\"remote_addr\"),\n IB_PHASE_REQUEST_HEADER,\n IB_PHASE_REQUEST_HEADER);\n\n module.engine().register_configuration_directives()\n .on_off(\n \"TrustedProxyUseXFFHeader\",\n boost::bind(&TrustedProxyModule::enable_xff_directive,\n this, _1, _3))\n .list(\n \"TrustedProxyIPs\",\n boost::bind(&TrustedProxyModule::trusted_ips_directive,\n this, _1, _3));\n\n module.engine().register_hooks()\n .context_close(\n boost::bind(&TrustedProxyModule::on_context_close,\n this, _1, _2))\n .handle_context_transaction(\n boost::bind(&TrustedProxyModule::set_effective_ip,\n this, _1, _2));\n}\n\nvoid TrustedProxyModule::enable_xff_directive(\n IronBee::ConfigurationParser cp,\n bool enabled\n)\n{\n TrustedProxyConfig& config =\n module().configuration_data(cp.current_context());\n config.set_xff_enabled(enabled);\n}\n\nvoid TrustedProxyModule::trusted_ips_directive(\n IronBee::ConfigurationParser cp,\n IronBee::ConstList ip_list\n)\n{\n TrustedProxyConfig& config =\n module().configuration_data(cp.current_context());\n\n const char* first_arg = ip_list.front();\n if (*first_arg != '+' and *first_arg != '-') {\n config.clear_networks();\n }\n\n BOOST_FOREACH(const char* arg, ip_list) {\n if (*arg == '+') {\n config.add_trusted_network(arg+1);\n }\n else if (*arg == '-') {\n config.add_untrusted_network(arg+1);\n }\n else {\n config.add_trusted_network(arg);\n }\n }\n}\n\nvoid TrustedProxyModule::on_context_close(\n IronBee::Engine ib,\n IronBee::Context ctx\n)\n{\n TrustedProxyConfig& config =\n module().configuration_data(ctx);\n\n config.context_close(ib);\n}\n\nvoid TrustedProxyModule::set_effective_ip(\n IronBee::Engine ib,\n IronBee::Transaction tx\n)\n{\n using namespace boost::algorithm;\n\n ib_status_t rc;\n IronBee::Context ctx = tx.context();\n TrustedProxyConfig& config =\n module().configuration_data(ctx);\n\n ib_log_debug_tx(tx.ib(), \"checking: %s\",\n tx.connection().remote_ip_string());\n \/\/ check actual remote ip against trusted ips\n if (! config.is_trusted(tx.connection().remote_ip_string())) {\n ib_log_debug_tx(tx.ib(), \"Remote address '%s' not a trusted proxy.\",\n tx.connection().remote_ip_string());\n return;\n }\n\n \/\/ Last remote address is trusted, get the last X-Forwarded-For value.\n string forwarded;\n for (\n IronBee::ParsedHeader header = tx.request_header();\n header;\n header = header.next()\n )\n {\n if (iequals(\"X-Forwarded-For\", header.name().to_s())) {\n forwarded = header.value().to_s();\n }\n }\n\n if (forwarded.length() == 0) {\n return;\n }\n\n list forwarded_list;\n\n split(forwarded_list, forwarded, is_any_of(\",\"));\n\n string remote_ip = trim_copy(forwarded_list.back());\n\n \/* Verify that it looks like a valid IP address, ignore it if not *\/\n rc = ib_ip_validate(remote_ip.c_str());\n if (rc != IB_OK) {\n ib_log_error_tx(tx.ib(),\n \"X-Forwarded-For \\\"%s\\\" is not a valid IP address\",\n remote_ip.c_str());\n return;\n }\n char* buf = static_cast(tx.memory_manager().alloc(remote_ip.length()+1));\n strcpy(buf, remote_ip.c_str());\n\n \/* This will lose the pointer to the original address\n * buffer, but it should be cleaned up with the rest\n * of the memory pool. *\/\n tx.ib()->remote_ipstr = buf;\n\n ib_log_debug_tx(tx.ib(), \"Remote address changed to \\\"%s\\\"\", buf);\n\n IronBee::ByteString remote_addr_bs = IronBee::ByteString::create_alias(\n tx.memory_manager(),\n remote_ip);\n\n try {\n IronBee::Field f = m_remote_addr_source.get(tx.var_store());\n f.set_no_copy_byte_string(remote_addr_bs);\n }\n catch (const IronBee::enoent &e) {\n IronBee::Field remote_addr_field = IronBee::Field::create_byte_string(\n tx.memory_manager(),\n IB_S2SL(\"REMOTE_ADDR\"),\n remote_addr_bs);\n m_remote_addr_source.set(tx.var_store(), remote_addr_field);\n }\n\n}\n\n} \/\/ Anonymous namespace\ntrusted_proxy: Bug fix - use the memory manager copy of the IP string to populate tx->var_store.\/*****************************************************************************\n * Licensed to Qualys, Inc. (QUALYS) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * QUALYS licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n ****************************************************************************\/\n\n\/**\n * @file\n * @brief IronBee --- Trusted Proxy Module\n *\/\n\n\/\/ Include all of IronBee++\n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n\n#include \n\nusing namespace std;\n\nnamespace {\n\n\/**\n * Configuration for the Trusted Proxy Module\n *\/\nclass TrustedProxyConfig\n{\npublic:\n \/\/! Constructor.\n TrustedProxyConfig();\n\n \/\/! Is X-Forwarded-For handling enabled?\n bool is_xff_enabled() const;\n\n \/\/! Enable or disable X-Forwarded-For handling.\n void set_xff_enabled(bool enabled);\n\n \/\/! Clear the trusted and untrusted network lists.\n void clear_networks();\n\n \/\/! Add a network to the trusted list.\n void add_trusted_network(const char* network);\n\n \/\/! Add a network to the untrusted list.\n void add_untrusted_network(const char* network);\n\n \/**\n * Check if the ip address is trusted.\n *\n * The default is to trust all addresses.\n *\n * @param[in] ipstr IP address to check.\n *\n * @returns True if the address is trusted.\n *\/\n bool is_trusted(const char* ipstr) const;\n\n \/\/! Finalize the configuration when the context is closed.\n void context_close(IronBee::Engine& ib);\n\nprivate:\n \/\/! X-Forwarding-For handling enabled?\n bool m_xff_enabled;\n\n \/\/! List of trusted networks\n vector m_trusted_net_list;\n\n \/\/! List of untrusted networks\n vector m_untrusted_net_list;\n\n \/\/! IP set of the trusted and untrusted networks.\n ib_ipset4_t m_trusted_networks;\n};\n\n\/**\n * Module to handle X-Forwarded-For headers from trusted Proxies.\n *\/\nclass TrustedProxyModule : public IronBee::ModuleDelegate\n{\npublic:\n \/\/! Constructor.\n explicit TrustedProxyModule(IronBee::Module module);\n\nprivate:\n \/\/! Source for recording the remote address\n IronBee::VarSource m_remote_addr_source;\n\n \/**\n * Handle the TrustedProxyUseXFFHeader directive.\n *\n * @param[in] cp Configuration parser.\n * @param[in] enabled Should XFF handling be enabled?\n *\/\n void enable_xff_directive(\n IronBee::ConfigurationParser cp,\n bool enabled);\n\n \/**\n * @param[in] cp Configuration parser.\n * @param[in] ip_list List of IPs or CIDR blocks.\n *\/\n void trusted_ips_directive(\n IronBee::ConfigurationParser cp,\n IronBee::ConstList ip_list);\n\n void on_context_close(IronBee::Engine ib, IronBee::Context ctx);\n\n \/**\n * Update the transaction effective IP based.\n *\n * @param[in] ib Ironbee engine.\n * @param[in,out] tx Transaction to update.\n *\/\n void set_effective_ip(\n IronBee::Engine ib,\n IronBee::Transaction tx);\n};\n\n} \/\/ Anonymous namespace\n\nIBPP_BOOTSTRAP_MODULE_DELEGATE(\"TrustedProxyModule\", TrustedProxyModule)\n\nnamespace {\n\nvoid make_ipset_entry(const char* cidr_or_ip, ib_ipset4_entry_t& entry)\n{\n if (strchr(cidr_or_ip, '\/') != NULL) {\n \/\/ Has \/ assume CIDR\n IronBee::throw_if_error(\n ib_ip4_str_to_net(cidr_or_ip, &(entry.network)),\n \"Invalid CIDR block\");\n }\n else {\n \/\/ IP make \/32\n IronBee::throw_if_error(\n ib_ip4_str_to_ip(cidr_or_ip, &(entry.network.ip)),\n \"Invalid IP address\");\n entry.network.size=32;\n }\n}\n\nTrustedProxyConfig::TrustedProxyConfig()\n : m_xff_enabled(true)\n{\n ib_ipset4_init(&m_trusted_networks, NULL, 0, NULL, 0);\n}\n\nbool TrustedProxyConfig::is_xff_enabled() const\n{\n return m_xff_enabled;\n}\n\nvoid TrustedProxyConfig::set_xff_enabled(bool enabled)\n{\n m_xff_enabled = enabled;\n}\n\nvoid TrustedProxyConfig::clear_networks()\n{\n m_trusted_net_list.clear();\n m_untrusted_net_list.clear();\n}\n\nvoid TrustedProxyConfig::add_trusted_network(const char* cidr_or_ip)\n{\n ib_ipset4_entry_t net_entry;\n make_ipset_entry(cidr_or_ip, net_entry);\n m_trusted_net_list.push_back(net_entry);\n}\n\nvoid TrustedProxyConfig::add_untrusted_network(const char* cidr_or_ip)\n{\n ib_ipset4_entry_t net_entry;\n make_ipset_entry(cidr_or_ip, net_entry);\n m_untrusted_net_list.push_back(net_entry);\n}\n\nvoid TrustedProxyConfig::context_close(IronBee::Engine& ib)\n{\n IronBee::throw_if_error(\n ib_ipset4_init(\n &m_trusted_networks,\n m_untrusted_net_list.data(),\n m_untrusted_net_list.size(),\n m_trusted_net_list.data(),\n m_trusted_net_list.size()),\n \"Failed to initialize IPv4 set.\");\n}\n\nbool TrustedProxyConfig::is_trusted(const char* ipstr) const\n{\n ib_ip4_t ip;\n\n IronBee::throw_if_error(\n ib_ip4_str_to_ip(ipstr, &ip),\n \"Invalid remote IP address\");\n ib_status_t rc =\n ib_ipset4_query(&m_trusted_networks, ip, NULL, NULL, NULL);\n return rc == IB_OK;\n}\n\nTrustedProxyModule::TrustedProxyModule(IronBee::Module module) :\n IronBee::ModuleDelegate(module)\n{\n module.set_configuration_data();\n\n m_remote_addr_source = IronBee::VarSource::register_(\n module.engine().var_config(),\n IB_S2SL(\"remote_addr\"),\n IB_PHASE_REQUEST_HEADER,\n IB_PHASE_REQUEST_HEADER);\n\n module.engine().register_configuration_directives()\n .on_off(\n \"TrustedProxyUseXFFHeader\",\n boost::bind(&TrustedProxyModule::enable_xff_directive,\n this, _1, _3))\n .list(\n \"TrustedProxyIPs\",\n boost::bind(&TrustedProxyModule::trusted_ips_directive,\n this, _1, _3));\n\n module.engine().register_hooks()\n .context_close(\n boost::bind(&TrustedProxyModule::on_context_close,\n this, _1, _2))\n .handle_context_transaction(\n boost::bind(&TrustedProxyModule::set_effective_ip,\n this, _1, _2));\n}\n\nvoid TrustedProxyModule::enable_xff_directive(\n IronBee::ConfigurationParser cp,\n bool enabled\n)\n{\n TrustedProxyConfig& config =\n module().configuration_data(cp.current_context());\n config.set_xff_enabled(enabled);\n}\n\nvoid TrustedProxyModule::trusted_ips_directive(\n IronBee::ConfigurationParser cp,\n IronBee::ConstList ip_list\n)\n{\n TrustedProxyConfig& config =\n module().configuration_data(cp.current_context());\n\n const char* first_arg = ip_list.front();\n if (*first_arg != '+' and *first_arg != '-') {\n config.clear_networks();\n }\n\n BOOST_FOREACH(const char* arg, ip_list) {\n if (*arg == '+') {\n config.add_trusted_network(arg+1);\n }\n else if (*arg == '-') {\n config.add_untrusted_network(arg+1);\n }\n else {\n config.add_trusted_network(arg);\n }\n }\n}\n\nvoid TrustedProxyModule::on_context_close(\n IronBee::Engine ib,\n IronBee::Context ctx\n)\n{\n TrustedProxyConfig& config =\n module().configuration_data(ctx);\n\n config.context_close(ib);\n}\n\nvoid TrustedProxyModule::set_effective_ip(\n IronBee::Engine ib,\n IronBee::Transaction tx\n)\n{\n using namespace boost::algorithm;\n\n ib_status_t rc;\n IronBee::Context ctx = tx.context();\n TrustedProxyConfig& config =\n module().configuration_data(ctx);\n\n ib_log_debug_tx(tx.ib(), \"checking: %s\",\n tx.connection().remote_ip_string());\n \/\/ check actual remote ip against trusted ips\n if (! config.is_trusted(tx.connection().remote_ip_string())) {\n ib_log_debug_tx(tx.ib(), \"Remote address '%s' not a trusted proxy.\",\n tx.connection().remote_ip_string());\n return;\n }\n\n \/\/ Last remote address is trusted, get the last X-Forwarded-For value.\n string forwarded;\n for (\n IronBee::ParsedHeader header = tx.request_header();\n header;\n header = header.next()\n )\n {\n if (iequals(\"X-Forwarded-For\", header.name().to_s())) {\n forwarded = header.value().to_s();\n }\n }\n\n if (forwarded.length() == 0) {\n return;\n }\n\n list forwarded_list;\n\n split(forwarded_list, forwarded, is_any_of(\",\"));\n\n string remote_ip = trim_copy(forwarded_list.back());\n\n \/* Verify that it looks like a valid IP address, ignore it if not *\/\n rc = ib_ip_validate(remote_ip.c_str());\n if (rc != IB_OK) {\n ib_log_error_tx(tx.ib(),\n \"X-Forwarded-For \\\"%s\\\" is not a valid IP address\",\n remote_ip.c_str());\n return;\n }\n char* buf = static_cast(tx.memory_manager().alloc(remote_ip.length()+1));\n strcpy(buf, remote_ip.c_str());\n\n \/* This will lose the pointer to the original address\n * buffer, but it should be cleaned up with the rest\n * of the memory pool. *\/\n tx.ib()->remote_ipstr = buf;\n\n ib_log_debug_tx(tx.ib(), \"Remote address changed to \\\"%s\\\"\", buf);\n\n IronBee::ByteString remote_addr_bs = IronBee::ByteString::create_alias(\n tx.memory_manager(),\n buf);\n\n try {\n IronBee::Field f = m_remote_addr_source.get(tx.var_store());\n f.set_no_copy_byte_string(remote_addr_bs);\n }\n catch (const IronBee::enoent &e) {\n IronBee::Field remote_addr_field = IronBee::Field::create_byte_string(\n tx.memory_manager(),\n IB_S2SL(\"REMOTE_ADDR\"),\n remote_addr_bs);\n m_remote_addr_source.set(tx.var_store(), remote_addr_field);\n }\n}\n\n} \/\/ Anonymous namespace\n<|endoftext|>"} {"text":"#include \"log.h\"\r\n\r\n#include \"SongDb.h\"\r\n\r\n#include \"sqlite3\/sqlite3.h\"\r\n#include \"utils.h\"\r\n\r\n#include \r\n#include \r\n#include \r\n\r\nusing namespace std;\r\nusing namespace utils;\r\n\r\n\r\nSongDatabase::SongDatabase(const string &name) {\r\n\tdb = nullptr;\r\n\tint rc = sqlite3_open(name.c_str(), &db);\/\/, SQLITE_READONLY, NULL);\r\n\tif(rc != SQLITE_OK) {\t\r\n\t\tthrow database_exception(format(\"%s: %s\", name, sqlite3_errstr(rc)).c_str());\r\n\t};\r\n}\r\n\r\nSongDatabase::~SongDatabase() {\r\n\tif(db)\r\n\t\tsqlite3_close(db);\r\n}\r\n\r\n\r\nstring SongDatabase::getFullString(int id) {\r\n\r\n\tid++;\r\n\tLOGD(\"ID %d\", id);\r\n\r\n\tsqlite3_stmt *s;\r\n\tconst char *tail;\r\n\tint rc = sqlite3_prepare_v2(db, \"SELECT title, composer, path, metadata FROM songs WHERE _id == ?\", -1, &s, &tail);\r\n\tLOGD(\"Result '%d'\\n\", rc);\r\n\tif(rc != SQLITE_OK)\r\n\t\tthrow database_exception(\"Select failed\");\r\n\tsqlite3_bind_int(s, 1, id);\r\n\tint ok = sqlite3_step(s);\r\n\t\r\n\tif(ok == SQLITE_ROW) {\r\n\t\tconst char *title = (const char *)sqlite3_column_text(s, 0);\r\n\t\tconst char *composer = (const char *)sqlite3_column_text(s, 1);\r\n\t\tconst char *path = (const char *)sqlite3_column_text(s, 2);\r\n\t\tconst char *metadata = (const char *)sqlite3_column_text(s, 3);\r\n\r\n\t\tLOGD(\"Result %s %s %s\\n\", title, composer, path);\r\n\t\tstring r = format(\"%s\\t%s\\t%s\\t%s\", title, composer, path, metadata);\r\n\t\tsqlite3_finalize(s);\r\n\t\treturn r;\r\n\t} else {\r\n\t\tsqlite3_finalize(s);\r\n\t\tthrow not_found_exception();\r\n\t}\r\n\t\/\/return \"\";\r\n}\r\nenum {\r\n\tUNKNOWN,\r\n\tC64_SID,\r\n\tTRACKER_ANY = 0x10,\r\n\tTRACKER_MOD,\r\n\tTRACKER_XM,\r\n\tTRACKER_S3M,\r\n\tTRACKER_FT,\r\n\r\n\tGM_ANY = 0x30,\r\n\tGM_NES,\r\n\tGM_SNES,\r\n\tGM_GAMEBOY,\r\n\r\n\tAUDIO_ANY = 0x50,\r\n\r\n\tAMI_ANY = 0x80,\r\n\tAMI_TFMX,\r\n\tAMI_CUSTOM,\r\n\tAMI_FC,\r\n};\r\n\r\n\r\n\r\nunordered_map formatMap {\r\n\t{ \"sid\", C64_SID },\r\n\t{ \"mod\", TRACKER_MOD },\r\n\t{ \"xm\", TRACKER_XM },\r\n\t{ \"s3m\", TRACKER_S3M },\r\n\t{ \"nsf\", GM_NES },\r\n\t{ \"smc\", GM_SNES },\r\n\t{ \"gbs\", GM_GAMEBOY }\r\n};\t\r\n\r\n\r\nvoid SongDatabase::generateIndex() {\r\n\r\n\tsqlite3_stmt *s;\r\n\tconst char *tail;\r\n\tchar oldComposer[256] = \"\";\r\n\r\n\tint rc = sqlite3_prepare_v2(db, \"SELECT title, composer, path FROM songs;\", -1, &s, &tail);\r\n\tLOGD(\"Result '%d'\\n\", rc);\r\n\tif(rc != SQLITE_OK)\r\n\t\tthrow database_exception(\"Select failed\");\r\n\r\n\tint count = 0;\r\n\t\/\/int maxTotal = 3;\r\n\tint cindex = 0;\r\n\twhile(count < 1000000) {\r\n\t\tcount++;\r\n\t\tint ok = sqlite3_step(s);\r\n\t\tif(ok == SQLITE_ROW) {\r\n\t\t\tconst char *title = (const char *)sqlite3_column_text(s, 0);\r\n\t\t\tconst char *composer = (const char *)sqlite3_column_text(s, 1);\r\n\t\t\tconst char *path = (const char *)sqlite3_column_text(s, 2);\r\n\r\n\t\t\tstring ext = path_extention(path);\r\n\t\t\tint fmt = formatMap[ext];\r\n\t\t\tformats.push_back(fmt);\r\n\r\n\r\n\t\t\tint tindex = titleIndex.add(title);\r\n\r\n\t\t\tif(strcmp(composer, oldComposer) != 0) {\r\n\t\t\t\tstrcpy(oldComposer, composer);\r\n\t\t\t\tcindex = composerIndex.add(composer);\r\n\t\t\t\tcomposerToTitle.push_back(tindex);\r\n\t\t\t}\r\n\r\n\t\t\ttitleToComposer.push_back(cindex);\r\n\r\n\t\t} else if(ok == SQLITE_DONE) {\r\n\t\t\tbreak;\r\n\t\t}\r\n\t}\r\n\r\n\tsqlite3_finalize(s);\r\n\r\n\t\/\/LOGD(\"%d titles by %d composer generated %d + %d 3 letter indexes\\n\", titles.size(), composers.size(), titleMap.size(), composerMap.size());\r\n}\r\nint SongDatabase::search(const string &query, vector &result, unsigned int searchLimit) {\r\n\r\n\tresult.resize(0);\r\n\t\/\/if(query.size() < 3)\r\n\t\/\/\treturn 0;\r\n\t\/\/bool q3 = (q.size() <= 3);\r\n\r\n\ttitleIndex.search(query, result, searchLimit);\r\n\r\n\tvector cresult;\r\n\tcomposerIndex.search(query, cresult, searchLimit);\r\n\tfor(int index : cresult) {\r\n\t\tint title_index = composerToTitle[index];\r\n\r\n\t\twhile(titleToComposer[title_index] == index) {\r\n\t\t\tresult.push_back(title_index++);\r\n\t\t}\r\n\t}\r\n\r\n\treturn result.size();\r\n}\r\n\r\n#ifdef UNIT_TEST\r\n\r\n#include \"catch.hpp\"\r\n#include \r\n\r\nTEST_CASE(\"db::index\", \"Generate index\") {\r\n\r\n\tSongDatabase db {\"hvsc.db\"};\r\n\tdb.generateIndex();\r\n\r\n\tstring search_string = \"tune tel fre\";\r\n\tvector results { 155, 1, 2944, 2694, 2694, 1954, 524, 11, 11, 1, 1, 1 };\r\n\tIncrementalQuery q = db.find();\r\n\tint i = 0;\r\n\tfor(char c : search_string) {\t\t\r\n\t\tq.addLetter(c);\r\n\t\t\/\/LOGD(\"%s %d\", q.getString(), q.numHits());\r\n\t\tREQUIRE(q.numHits() == results[i]);\r\n\t\ti++;\r\n\t}\r\n\tstring res = q.getResult(0, 10)[0];\r\n\tREQUIRE(res.find(\"Freaky Tune\") != string::npos);\r\n}\r\n\r\n\/*\r\nTEST_CASE(\"db::tlcode\", \"Codes\") {\r\n\r\n\tSongDatabase db {\"hvsc.db\"};\r\n\tunordered_map> stringMap;\r\n\tlogging::setLevel(logging::VERBOSE);\r\n\tdb.addSubStrings(\"Testing (4-Mat)\", stringMap, 0);\r\n\tlogging::setLevel(logging::DEBUG);\r\n}*\/\r\n\r\n\r\nTEST_CASE(\"db::find\", \"Search Benchmark\") {\r\n\r\n\ttimeval tv;\r\n\tgettimeofday(&tv, NULL);\r\n\tlong d0 = tv.tv_sec * 1000000 + tv.tv_usec;\r\n\r\n\tlogging::setLevel(logging::INFO);\r\n\r\n\tSongDatabase db {\"hvsc.db\"};\r\n\tdb.generateIndex();\r\n\r\n\r\n\tvector iqs;\r\n\r\n\tfor(int i=0; i<100; i++) {\r\n\t\tiqs.push_back(db.find());\r\n\t}\r\n\r\n\tstring search_string = \"tune tel\";\r\n\tint i = 0;\r\n\r\n\tgettimeofday(&tv, NULL);\r\n\tlong d1 = tv.tv_sec * 1000000 + tv.tv_usec;\r\n\r\n\tfor(char c : search_string) {\t\t\r\n\t\tfor(auto &q : iqs) {\r\n\t\t\tq.addLetter(c);\t\t\t\r\n\t\t\t\/\/REQUIRE(q.numHits() == results[i]);\r\n\t\t}\r\n\t\ti++;\r\n\t}\r\n\r\n\tgettimeofday(&tv, NULL);\r\n\tlong d2 = tv.tv_sec * 1000000 + tv.tv_usec;\r\n\r\n\tLOGI(\"Search took %dms\", (d2-d1)\/1000);\r\n}\r\n\r\n#endif\r\nA few new formats#include \"log.h\"\r\n\r\n#include \"SongDb.h\"\r\n\r\n#include \"sqlite3\/sqlite3.h\"\r\n#include \"utils.h\"\r\n\r\n#include \r\n#include \r\n#include \r\n\r\nusing namespace std;\r\nusing namespace utils;\r\n\r\n\r\nSongDatabase::SongDatabase(const string &name) {\r\n\tdb = nullptr;\r\n\tint rc = sqlite3_open(name.c_str(), &db);\/\/, SQLITE_READONLY, NULL);\r\n\tif(rc != SQLITE_OK) {\t\r\n\t\tthrow database_exception(format(\"%s: %s\", name, sqlite3_errstr(rc)).c_str());\r\n\t};\r\n}\r\n\r\nSongDatabase::~SongDatabase() {\r\n\tif(db)\r\n\t\tsqlite3_close(db);\r\n}\r\n\r\n\r\nstring SongDatabase::getFullString(int id) {\r\n\r\n\tid++;\r\n\tLOGD(\"ID %d\", id);\r\n\r\n\tsqlite3_stmt *s;\r\n\tconst char *tail;\r\n\tint rc = sqlite3_prepare_v2(db, \"SELECT title, composer, path, metadata FROM songs WHERE _id == ?\", -1, &s, &tail);\r\n\tLOGD(\"Result '%d'\\n\", rc);\r\n\tif(rc != SQLITE_OK)\r\n\t\tthrow database_exception(\"Select failed\");\r\n\tsqlite3_bind_int(s, 1, id);\r\n\tint ok = sqlite3_step(s);\r\n\t\r\n\tif(ok == SQLITE_ROW) {\r\n\t\tconst char *title = (const char *)sqlite3_column_text(s, 0);\r\n\t\tconst char *composer = (const char *)sqlite3_column_text(s, 1);\r\n\t\tconst char *path = (const char *)sqlite3_column_text(s, 2);\r\n\t\tconst char *metadata = (const char *)sqlite3_column_text(s, 3);\r\n\r\n\t\tLOGD(\"Result %s %s %s\\n\", title, composer, path);\r\n\t\tstring r = format(\"%s\\t%s\\t%s\\t%s\", title, composer, path, metadata);\r\n\t\tsqlite3_finalize(s);\r\n\t\treturn r;\r\n\t} else {\r\n\t\tsqlite3_finalize(s);\r\n\t\tthrow not_found_exception();\r\n\t}\r\n\t\/\/return \"\";\r\n}\r\nenum {\r\n\tUNKNOWN,\r\n\tC64_SID,\r\n\tTRACKER_ANY = 0x10,\r\n\tTRACKER_MOD,\r\n\tTRACKER_XM,\r\n\tTRACKER_S3M,\r\n\tTRACKER_FT,\r\n\tTRACKER_IT,\r\n\r\n\tTRACKER_END = 0x2f,\r\n\tGM_ANY = 0x30,\r\n\tGM_NES,\r\n\tGM_SNES,\r\n\tGM_GAMEBOY,\r\n\tGM_VGM,\r\n\tGM_END = 0x3f,\r\n\r\n\tAUDIO_ANY = 0x50,\r\n\r\n\tAMI_ANY = 0x80,\r\n\tAMI_TFMX,\r\n\tAMI_CUSTOM,\r\n\tAMI_FC,\r\n\tAMI_AHX,\r\n\tAMI_END = 0xff\r\n};\r\n\r\n\r\n\r\nunordered_map formatMap {\r\n\t{ \"sid\", C64_SID },\r\n\t{ \"mod\", TRACKER_MOD },\r\n\t{ \"xm\", TRACKER_XM },\r\n\t{ \"it\", TRACKER_IT },\r\n\t{ \"s3m\", TRACKER_S3M },\r\n\t{ \"nsf\", GM_NES },\r\n\t{ \"smc\", GM_SNES },\r\n\t{ \"gbs\", GM_GAMEBOY },\r\n\t{ \"vgz\", GM_VGM },\r\n\t{ \"ahx\", AMI_AHX },\r\n};\t\r\n\r\n\r\nvoid SongDatabase::generateIndex() {\r\n\r\n\tsqlite3_stmt *s;\r\n\tconst char *tail;\r\n\tchar oldComposer[256] = \"\";\r\n\r\n\tint rc = sqlite3_prepare_v2(db, \"SELECT title, composer, path FROM songs;\", -1, &s, &tail);\r\n\tLOGD(\"Result '%d'\\n\", rc);\r\n\tif(rc != SQLITE_OK)\r\n\t\tthrow database_exception(\"Select failed\");\r\n\r\n\tint count = 0;\r\n\t\/\/int maxTotal = 3;\r\n\tint cindex = 0;\r\n\twhile(count < 1000000) {\r\n\t\tcount++;\r\n\t\tint ok = sqlite3_step(s);\r\n\t\tif(ok == SQLITE_ROW) {\r\n\t\t\tconst char *title = (const char *)sqlite3_column_text(s, 0);\r\n\t\t\tconst char *composer = (const char *)sqlite3_column_text(s, 1);\r\n\t\t\tconst char *path = (const char *)sqlite3_column_text(s, 2);\r\n\r\n\t\t\tstring ext = path_extention(path);\r\n\r\n\t\t\tint fmt = formatMap[ext];\r\n\r\n\t\t\tformats.push_back(fmt);\r\n\r\n\r\n\t\t\tint tindex = titleIndex.add(title);\r\n\r\n\t\t\tif(strcmp(composer, oldComposer) != 0) {\r\n\t\t\t\tstrcpy(oldComposer, composer);\r\n\t\t\t\tcindex = composerIndex.add(composer);\r\n\t\t\t\tcomposerToTitle.push_back(tindex);\r\n\t\t\t}\r\n\r\n\t\t\ttitleToComposer.push_back(cindex);\r\n\r\n\t\t} else if(ok == SQLITE_DONE) {\r\n\t\t\tbreak;\r\n\t\t}\r\n\t}\r\n\r\n\tsqlite3_finalize(s);\r\n\r\n\t\/\/LOGD(\"%d titles by %d composer generated %d + %d 3 letter indexes\\n\", titles.size(), composers.size(), titleMap.size(), composerMap.size());\r\n}\r\nint SongDatabase::search(const string &query, vector &result, unsigned int searchLimit) {\r\n\r\n\tresult.resize(0);\r\n\t\/\/if(query.size() < 3)\r\n\t\/\/\treturn 0;\r\n\t\/\/bool q3 = (q.size() <= 3);\r\n\r\n\ttitleIndex.search(query, result, searchLimit);\r\n\r\n\tvector cresult;\r\n\tcomposerIndex.search(query, cresult, searchLimit);\r\n\tfor(int index : cresult) {\r\n\t\tint title_index = composerToTitle[index];\r\n\r\n\t\twhile(titleToComposer[title_index] == index) {\r\n\t\t\tresult.push_back(title_index++);\r\n\t\t}\r\n\t}\r\n\r\n\treturn result.size();\r\n}\r\n\r\n#ifdef UNIT_TEST\r\n\r\n#include \"catch.hpp\"\r\n#include \r\n\r\nTEST_CASE(\"db::index\", \"Generate index\") {\r\n\r\n\tSongDatabase db {\"hvsc.db\"};\r\n\tdb.generateIndex();\r\n\r\n\tstring search_string = \"tune tel fre\";\r\n\tvector results { 155, 1, 2944, 2694, 2694, 1954, 524, 11, 11, 1, 1, 1 };\r\n\tIncrementalQuery q = db.find();\r\n\tint i = 0;\r\n\tfor(char c : search_string) {\t\t\r\n\t\tq.addLetter(c);\r\n\t\t\/\/LOGD(\"%s %d\", q.getString(), q.numHits());\r\n\t\tREQUIRE(q.numHits() == results[i]);\r\n\t\ti++;\r\n\t}\r\n\tstring res = q.getResult(0, 10)[0];\r\n\tREQUIRE(res.find(\"Freaky Tune\") != string::npos);\r\n}\r\n\r\n\/*\r\nTEST_CASE(\"db::tlcode\", \"Codes\") {\r\n\r\n\tSongDatabase db {\"hvsc.db\"};\r\n\tunordered_map> stringMap;\r\n\tlogging::setLevel(logging::VERBOSE);\r\n\tdb.addSubStrings(\"Testing (4-Mat)\", stringMap, 0);\r\n\tlogging::setLevel(logging::DEBUG);\r\n}*\/\r\n\r\n\r\nTEST_CASE(\"db::find\", \"Search Benchmark\") {\r\n\r\n\ttimeval tv;\r\n\tgettimeofday(&tv, NULL);\r\n\tlong d0 = tv.tv_sec * 1000000 + tv.tv_usec;\r\n\r\n\tlogging::setLevel(logging::INFO);\r\n\r\n\tSongDatabase db {\"hvsc.db\"};\r\n\tdb.generateIndex();\r\n\r\n\r\n\tvector iqs;\r\n\r\n\tfor(int i=0; i<100; i++) {\r\n\t\tiqs.push_back(db.find());\r\n\t}\r\n\r\n\tstring search_string = \"tune tel\";\r\n\tint i = 0;\r\n\r\n\tgettimeofday(&tv, NULL);\r\n\tlong d1 = tv.tv_sec * 1000000 + tv.tv_usec;\r\n\r\n\tfor(char c : search_string) {\t\t\r\n\t\tfor(auto &q : iqs) {\r\n\t\t\tq.addLetter(c);\t\t\t\r\n\t\t\t\/\/REQUIRE(q.numHits() == results[i]);\r\n\t\t}\r\n\t\ti++;\r\n\t}\r\n\r\n\tgettimeofday(&tv, NULL);\r\n\tlong d2 = tv.tv_sec * 1000000 + tv.tv_usec;\r\n\r\n\tLOGI(\"Search took %dms\", (d2-d1)\/1000);\r\n}\r\n\r\n#endif\r\n<|endoftext|>"} {"text":"\n#include \"Cache.hpp\"\n\n\n\n#include \n\nBOOST_AUTO_TEST_SUITE( Cache_tests );\n\nint64_t foo = 1234;\nint64_t bar[4] = { 2345, 3456, 4567, 6789 };\n\nvoid user_main( thread * me, void * args ) \n{\n {\n Incoherent< int64_t >::RO buf( GlobalAddress< int64_t >( &foo ), 1 );\n BOOST_CHECK_EQUAL( *buf, foo );\n }\n\n {\n {\n Incoherent::RW buf( GlobalAddress< int64_t >( &foo ), 1 );\n BOOST_CHECK_EQUAL( *buf, foo );\n foo = 1235;\n BOOST_CHECK( *buf != foo );\n BOOST_CHECK_EQUAL( foo, 1235 );\n *buf = 1235;\n BOOST_CHECK_EQUAL( *buf, foo );\n *buf = 1236;\n }\n BOOST_CHECK_EQUAL( foo, 1236 );\n }\n\n {\n int64_t x;\n Incoherent::RO buf( GlobalAddress< int64_t >( &foo ), 1, &x );\n BOOST_CHECK_EQUAL( *buf, foo );\n }\n\n {\n int64_t y[4];\n Incoherent::RO buf2( GlobalAddress< int64_t >( bar ), 4, &y[0] );\n BOOST_CHECK_EQUAL( buf2[2], bar[2] );\n }\n\n {\n Incoherent::RW buf3( GlobalAddress< int64_t >( bar ), 4);\n BOOST_CHECK_EQUAL( buf3[2], bar[2] );\n }\n\n {\n \/\/ test for early wakeup handled properly\n BOOST_MESSAGE( \"Wakeup test\" );\n Incoherent::RW buf4( GlobalAddress< int64_t >( bar, 1 ), 1);\n buf4.start_acquire( );\n for (int i=0; i<2000; i++) {\n SoftXMT_yield();\n }\n buf4.block_until_acquired( );\n\n buf4.start_release( );\n for (int i=0; i<2000; i++) {\n SoftXMT_yield();\n }\n buf4.block_until_released( );\n }\n\n SoftXMT_signal_done();\n}\n\nBOOST_AUTO_TEST_CASE( test1 ) {\n\n SoftXMT_init( &(boost::unit_test::framework::master_test_suite().argc),\n &(boost::unit_test::framework::master_test_suite().argv) );\n\n SoftXMT_activate();\n\n BOOST_CHECK_EQUAL( SoftXMT_nodes(), 2 );\n SoftXMT_run_user_main( &user_main, NULL );\n BOOST_CHECK( SoftXMT_done() == true );\n\n SoftXMT_finish( 0 );\n}\n\nBOOST_AUTO_TEST_SUITE_END();\n\ncomments in Cache_test\n#include \"Cache.hpp\"\n\n\n\n#include \n\nBOOST_AUTO_TEST_SUITE( Cache_tests );\n\nint64_t foo = 1234;\nint64_t bar[4] = { 2345, 3456, 4567, 6789 };\n\nvoid user_main( thread * me, void * args ) \n{\n {\n Incoherent< int64_t >::RO buf( GlobalAddress< int64_t >( &foo ), 1 );\n BOOST_CHECK_EQUAL( *buf, foo );\n }\n\n {\n {\n Incoherent::RW buf( GlobalAddress< int64_t >( &foo ), 1 );\n BOOST_CHECK_EQUAL( *buf, foo );\n foo = 1235;\n BOOST_CHECK( *buf != foo );\n BOOST_CHECK_EQUAL( foo, 1235 );\n *buf = 1235;\n BOOST_CHECK_EQUAL( *buf, foo );\n *buf = 1236;\n }\n BOOST_CHECK_EQUAL( foo, 1236 );\n }\n\n {\n int64_t x;\n Incoherent::RO buf( GlobalAddress< int64_t >( &foo ), 1, &x );\n BOOST_CHECK_EQUAL( *buf, foo );\n }\n\n {\n int64_t y[4];\n Incoherent::RO buf2( GlobalAddress< int64_t >( bar ), 4, &y[0] );\n BOOST_CHECK_EQUAL( buf2[2], bar[2] );\n }\n\n {\n Incoherent::RW buf3( GlobalAddress< int64_t >( bar ), 4);\n BOOST_CHECK_EQUAL( buf3[2], bar[2] );\n }\n\n {\n \/\/ test for early wakeup handled properly\n BOOST_MESSAGE( \"Wakeup test\" );\n Incoherent::RW buf4( GlobalAddress< int64_t >( bar, 1 ), 1);\n buf4.start_acquire( );\n for (int i=0; i<2000; i++) {\n SoftXMT_yield(); \/\/ spin to let reply come back\n }\n buf4.block_until_acquired( );\n\n buf4.start_release( );\n for (int i=0; i<2000; i++) {\n SoftXMT_yield(); \/\/ spin to let reply come back\n }\n buf4.block_until_released( );\n }\n\n SoftXMT_signal_done();\n}\n\nBOOST_AUTO_TEST_CASE( test1 ) {\n\n SoftXMT_init( &(boost::unit_test::framework::master_test_suite().argc),\n &(boost::unit_test::framework::master_test_suite().argv) );\n\n SoftXMT_activate();\n\n BOOST_CHECK_EQUAL( SoftXMT_nodes(), 2 );\n SoftXMT_run_user_main( &user_main, NULL );\n BOOST_CHECK( SoftXMT_done() == true );\n\n SoftXMT_finish( 0 );\n}\n\nBOOST_AUTO_TEST_SUITE_END();\n\n<|endoftext|>"} {"text":"#include \"LIBSPU.H\"\n#include \"LIBETC.H\"\n#include \n#include \"EMULATOR.H\"\n\n#include \n\nenum VV_Phase\n{\n\tPHASE_NORMAL = 0,\n\tPHASE_INVERTED = 1\n};\n\nenum VV_SweepMode\n{\n\tSWEEP_INCREASE = 0,\n\tSWEEP_DECREASE = 1\n};\n\nenum VV_SweepSlope\n{\n\tSLOPE_LINEAR = 0,\n\tSLOPE_EXPONENTIAL = 1\n};\n\nenum VD_Pitch\n{\n\tPITCH_MINUS3 = 0x0200,\n\tPITCH_MINUS2 = 0x0400,\n\tPITCH_MINUS1 = 0x0800,\n\tPITCH_ORIG = 0x1000,\n\tPITCH_PLUS1 = 0x2000,\n\tPITCH_PLUS2 = 0x3fff\n};\n\nunion VoiceVolume\n{\n\tstruct\n\t{\n\t\tunsigned short Volume : 14;\n\t\tunsigned short Phase : 1;\n\t} VolumeMode;\n\n\tstruct\n\t{\n\t\tunsigned short Volume : 7;\n\t\tunsigned short _pad : 5;\n\t\tunsigned short Phase : 1;\n\t\tunsigned short Mode : 1;\n\t\tunsigned short Slope : 1;\n\t} SweepMode;\n\n\tunsigned short Raw;\n};\n\nstruct VoiceData\n{\n\tunion VoiceVolume VolumeLeft;\n\tunion VoiceVolume VolumeRight;\n\n\tunsigned short Pitch;\n\n\tunsigned short StartAddress;\n\n\tunsigned short SustainLevel : 4;\n\tunsigned short DecayRate : 4;\n\tunsigned short AttackRate : 7;\n\tunsigned short AttackMode : 1; \/\/ lin or exp\n\n\tunsigned short ReleaseRate : 5;\n\tunsigned short DecreaseMode : 1; \/\/ lin or exp\n\tunsigned short SustainRate : 7;\n\tunsigned short _pad : 1;\n\tunsigned short SustainRateMode : 1; \/\/ inc or dec\n\tunsigned short SustainRateSlope : 1; \/\/ lin or exp\n\n\tunsigned short CurrentADSRVolume;\n\n\tunsigned short RepeatAddress;\n};\n\nstruct VoiceData Voices[24]; \/\/ 0x1F801C00\n\nstruct ReverbDepthInfo\n{\n\tunsigned short Volume : 15;\n\tunsigned short Phase : 1;\n};\n\nstruct\n{\n\tunion VoiceVolume VolumeLeft;\n\tunion VoiceVolume VolumeRight;\n} MasterVolume; \/\/ 1f801d80\n\nstruct\n{\n\tstruct\n\t{\n\t\tunsigned short Volume : 15;\n\t\tunsigned short Phase : 1;\n\t} Left, Right;\n} ReverbDepth; \/\/ 1f801d84 \n\nunsigned int SPU_DELAY = 0x200931E1; \/\/ 1F801014h\n\nint AllocBlockNum = 0;\nint AllocLastNum = 0;\nchar* memList = NULL;\nint EVdma = 0;\nint keystat = 0;\nint trans_mode = 0;\nint rev_flag = 0;\nint rev_reserve_wa = 0;\nint rev_offsetaddr = 0;\nint rev_attr = 0;\nint dword_9EE7C = 0;\nshort word_9EE80 = 0;\nshort word_9EE82 = 0;\nint dword_9EE84 = 0;\nint dword_9EE88 = 0;\nint RQvoice = 0;\nint RQmask = 0;\nint voice_centerNote[12] =\n{\n\t-1073692672, -1073692672, -1073692672, -1073692672, -1073692672, -1073692672,\n\t-1073692672, -1073692672, -1073692672, -1073692672, -1073692672, -1073692672\n};\nint zerobuf[256] = { 0 };\nint env = 0;\nint isCalled = 0;\nint startAddr[20] =\n{\n\t65534, 64296, 64536, 63224, 61956, \n\t59972, 52640, 53240, 53240, 63616, \n\t2, 1240, 984, 2312, 3580, \n\t5564, 7896, 12296, 12296, 1920\n};\nunsigned int DMAControlRegister = 0;\nunsigned int DMA1 = 0;\nunsigned int DMA2 = 0;\nunsigned int DMA3 = 0;\nvoid* RXX[6] = \n{\n\t&Voices, &DMA1, &DMA2, &DMA3, &DMAControlRegister, &SPU_DELAY\n};\nshort tsa[2] = { 0, 0 };\nint transMode = 0;\nint addrMode = 0;\nint mem_mode = 2;\nint mem_mode_plus = 3;\nint mem_mode_unit = 8;\nint mem_mode_unitM = 7;\nint inTransfer = 1;\nint transferCallback = 0;\nint IRQCallback = 0;\nchar* spu_buf;\nlong spu_b_size = 0;\n\n\nunsigned long SpuWrite(unsigned char * addr, unsigned long size)\n{\n\t\/\/eprintf(\"SPU WRITE size=%d\\n\", size);\n\t\/\/memcpy(spu_buf, addr, size);\n\t\/\/spu_b_size = size;\n\tUNIMPLEMENTED();\n\treturn 0;\n}\n\nlong SpuSetTransferMode(long mode)\n{\n\tlong mode_fix = mode == 0 ? 0 : 1;\n\n\ttrans_mode = mode;\n\ttransMode = mode_fix;\n\n\treturn mode_fix;\n}\n\nunsigned long SpuSetTransferStartAddr(unsigned long addr)\n{\n\tUNIMPLEMENTED();\n\treturn 0;\n}\n\nlong SpuIsTransferCompleted(long flag)\n{\n\tUNIMPLEMENTED();\n\treturn 0;\n}\n\nvoid SpuInit(void)\n{\n\teprintf(\"SpuInit\\n\");\n\tResetCallback();\n\tUNIMPLEMENTED();\n\tspu_buf = NULL;\/* (char*)malloc(1024 * 1024)*\/;\n}\n\nlong SpuSetReverb(long on_off)\n{\n\tUNIMPLEMENTED();\n\treturn 0;\n}\n\nunsigned long SpuSetReverbVoice(long on_off, unsigned long voice_bit)\n{\n\tUNIMPLEMENTED();\n\treturn 0;\n}\n\nvoid SpuSetCommonAttr(SpuCommonAttr * attr)\n{\n\tUNIMPLEMENTED();\n}\n\nlong SpuInitMalloc(long num, char * top)\n{\n\tif (num > 0)\n\t{\n\t\tmemList = top;\n\t\tAllocLastNum = 0;\n\t\tAllocBlockNum = num;\n\t\t*((int*)memList) = mem_mode_plus = 0x4000 | 0x1010;\n\t\t*((int*)memList + 1) = 0x4000;\n\t}\n\n\treturn num;\n}\n\nlong SpuMalloc(long size)\n{\n\treturn 0\/*(long)(uintptr_t)malloc(size)*\/;\n}\n\nlong SpuMallocWithStartAddr(unsigned long addr, long size)\n{\n\tUNIMPLEMENTED();\n\treturn 0;\n}\n\nvoid SpuFree(unsigned long addr)\n{\n\t\/*free((void*)(uintptr_t)addr)*\/;\n}\n\nvoid SpuSetCommonMasterVolume(short mvol_left, short mvol_right)\/\/ (F)\n{\n\tMasterVolume.VolumeLeft.Raw = mvol_left;\n\tMasterVolume.VolumeRight.Raw = mvol_right;\n}\n\nlong SpuSetReverbModeType(long mode)\n{\n\tUNIMPLEMENTED();\n\treturn 0;\n}\n\nvoid SpuSetReverbModeDepth(short depth_left, short depth_right)\n{\n\tUNIMPLEMENTED();\n}\n[Emu]: Implement SpuInit.#include \"LIBSPU.H\"\n#include \"LIBETC.H\"\n#include \n#include \"EMULATOR.H\"\n\n#include \n\nenum VV_Phase\n{\n\tPHASE_NORMAL = 0,\n\tPHASE_INVERTED = 1\n};\n\nenum VV_SweepMode\n{\n\tSWEEP_INCREASE = 0,\n\tSWEEP_DECREASE = 1\n};\n\nenum VV_SweepSlope\n{\n\tSLOPE_LINEAR = 0,\n\tSLOPE_EXPONENTIAL = 1\n};\n\nenum VD_Pitch\n{\n\tPITCH_MINUS3 = 0x0200,\n\tPITCH_MINUS2 = 0x0400,\n\tPITCH_MINUS1 = 0x0800,\n\tPITCH_ORIG = 0x1000,\n\tPITCH_PLUS1 = 0x2000,\n\tPITCH_PLUS2 = 0x3fff\n};\n\nunion VoiceVolume\n{\n\tstruct\n\t{\n\t\tunsigned short Volume : 14;\n\t\tunsigned short Phase : 1;\n\t} VolumeMode;\n\n\tstruct\n\t{\n\t\tunsigned short Volume : 7;\n\t\tunsigned short _pad : 5;\n\t\tunsigned short Phase : 1;\n\t\tunsigned short Mode : 1;\n\t\tunsigned short Slope : 1;\n\t} SweepMode;\n\n\tunsigned short Raw;\n};\n\nstruct VoiceData\n{\n\tunion VoiceVolume VolumeLeft;\n\tunion VoiceVolume VolumeRight;\n\n\tunsigned short Pitch;\n\n\tunsigned short StartAddress;\n\n\tunsigned short SustainLevel : 4;\n\tunsigned short DecayRate : 4;\n\tunsigned short AttackRate : 7;\n\tunsigned short AttackMode : 1; \/\/ lin or exp\n\n\tunsigned short ReleaseRate : 5;\n\tunsigned short DecreaseMode : 1; \/\/ lin or exp\n\tunsigned short SustainRate : 7;\n\tunsigned short _pad : 1;\n\tunsigned short SustainRateMode : 1; \/\/ inc or dec\n\tunsigned short SustainRateSlope : 1; \/\/ lin or exp\n\n\tunsigned short CurrentADSRVolume;\n\n\tunsigned short RepeatAddress;\n};\n\nstruct VoiceData Voices[24]; \/\/ 0x1F801C00\n\nstruct ReverbDepthInfo\n{\n\tunsigned short Volume : 15;\n\tunsigned short Phase : 1;\n};\n\nstruct\n{\n\tunion VoiceVolume VolumeLeft;\n\tunion VoiceVolume VolumeRight;\n} MasterVolume; \/\/ 1f801d80\n\nstruct\n{\n\tstruct\n\t{\n\t\tunsigned short Volume : 15;\n\t\tunsigned short Phase : 1;\n\t} Left, Right;\n} ReverbDepth; \/\/ 1f801d84 \n\nunsigned int SPU_DELAY = 0x200931E1; \/\/ 1F801014h\n\nint AllocBlockNum = 0;\nint AllocLastNum = 0;\nchar* memList = NULL;\nint EVdma = 0;\nint keystat = 0;\nint trans_mode = 0;\nint rev_flag = 0;\nint rev_reserve_wa = 0;\nint rev_offsetaddr = 0;\nint rev_attr = 0;\nint dword_9EE7C = 0;\nshort word_9EE80 = 0;\nshort word_9EE82 = 0;\nint dword_9EE84 = 0;\nint dword_9EE88 = 0;\nint RQvoice = 0;\nint RQmask = 0;\nint voice_centerNote[12] =\n{\n\t-1073692672, -1073692672, -1073692672, -1073692672, -1073692672, -1073692672,\n\t-1073692672, -1073692672, -1073692672, -1073692672, -1073692672, -1073692672\n};\nint zerobuf[256] = { 0 };\nint env = 0;\nint isCalled = 0;\nint startAddr[20] =\n{\n\t65534, 64296, 64536, 63224, 61956, \n\t59972, 52640, 53240, 53240, 63616, \n\t2, 1240, 984, 2312, 3580, \n\t5564, 7896, 12296, 12296, 1920\n};\nunsigned int DMAControlRegister = 0;\nunsigned int DMA1 = 0;\nunsigned int DMA2 = 0;\nunsigned int DMA3 = 0;\nvoid* RXX[6] = \n{\n\t&Voices, &DMA1, &DMA2, &DMA3, &DMAControlRegister, &SPU_DELAY\n};\nshort tsa[2] = { 0, 0 };\nint transMode = 0;\nint addrMode = 0;\nint mem_mode = 2;\nint mem_mode_plus = 3;\nint mem_mode_unit = 8;\nint mem_mode_unitM = 7;\nint inTransfer = 1;\nint transferCallback = 0;\nint IRQCallback = 0;\nchar* spu_buf;\nlong spu_b_size = 0;\n\n\nunsigned long SpuWrite(unsigned char * addr, unsigned long size)\n{\n\t\/\/eprintf(\"SPU WRITE size=%d\\n\", size);\n\t\/\/memcpy(spu_buf, addr, size);\n\t\/\/spu_b_size = size;\n\tUNIMPLEMENTED();\n\treturn 0;\n}\n\nlong SpuSetTransferMode(long mode)\n{\n\tlong mode_fix = mode == 0 ? 0 : 1;\n\n\ttrans_mode = mode;\n\ttransMode = mode_fix;\n\n\treturn mode_fix;\n}\n\nunsigned long SpuSetTransferStartAddr(unsigned long addr)\n{\n\tUNIMPLEMENTED();\n\treturn 0;\n}\n\nlong SpuIsTransferCompleted(long flag)\n{\n\tUNIMPLEMENTED();\n\treturn 0;\n}\n\nvoid _SpuInit(int a0)\n{\n\n}\n\nvoid SpuInit(void)\n{\n\t_SpuInit(0);\n}\n\nlong SpuSetReverb(long on_off)\n{\n\tUNIMPLEMENTED();\n\treturn 0;\n}\n\nunsigned long SpuSetReverbVoice(long on_off, unsigned long voice_bit)\n{\n\tUNIMPLEMENTED();\n\treturn 0;\n}\n\nvoid SpuSetCommonAttr(SpuCommonAttr * attr)\n{\n\tUNIMPLEMENTED();\n}\n\nlong SpuInitMalloc(long num, char * top)\n{\n\tif (num > 0)\n\t{\n\t\tmemList = top;\n\t\tAllocLastNum = 0;\n\t\tAllocBlockNum = num;\n\t\t*((int*)memList) = mem_mode_plus = 0x4000 | 0x1010;\n\t\t*((int*)memList + 1) = 0x4000;\n\t}\n\n\treturn num;\n}\n\nlong SpuMalloc(long size)\n{\n\treturn 0\/*(long)(uintptr_t)malloc(size)*\/;\n}\n\nlong SpuMallocWithStartAddr(unsigned long addr, long size)\n{\n\tUNIMPLEMENTED();\n\treturn 0;\n}\n\nvoid SpuFree(unsigned long addr)\n{\n\t\/*free((void*)(uintptr_t)addr)*\/;\n}\n\nvoid SpuSetCommonMasterVolume(short mvol_left, short mvol_right)\/\/ (F)\n{\n\tMasterVolume.VolumeLeft.Raw = mvol_left;\n\tMasterVolume.VolumeRight.Raw = mvol_right;\n}\n\nlong SpuSetReverbModeType(long mode)\n{\n\tUNIMPLEMENTED();\n\treturn 0;\n}\n\nvoid SpuSetReverbModeDepth(short depth_left, short depth_right)\n{\n\tUNIMPLEMENTED();\n}\n<|endoftext|>"} {"text":"#include \"terminalscreen.hpp\"\n#include \"logging.h\"\n\nusing namespace bb::cascades;\n\nTerminalScreen::TerminalScreen( term_t handle, int argc, char *argv[], AbstractPane *pane) : terminal(handle)\n{\n int ret = 0;\n QObject *pObj;\n\n term_get_grid_size( handle, &width, &height );\n slog2f(buffer_handle, 0, SLOG2_INFO, \"TerminalScreen start %dx%d\", width, height);\n mStringListModel = new QStringListDataModel;\n term_set_user_data( terminal, this );\n term_register_update( terminal, term_update );\n pObj = pane->findChild(\"terminalLines\");\n mStringList = (ListView *) pObj;\n mStringList->setDataModel( mStringListModel );\n\n notifier = new QSocketNotifier( term_get_file_descriptor(terminal), QSocketNotifier::Read );\n QObject::connect(notifier, SIGNAL(activated(int)), this, SLOT(terminal_data()));\n}\n\nTerminalScreen::~TerminalScreen()\n{\n delete notifier;\n}\n\nvoid TerminalScreen::term_update( term_t term, int x, int y, int width, int height )\n{\n TerminalScreen *ts = (TerminalScreen *)term_get_user_data( term );\n slog2c(buffer_handle, 0, SLOG2_INFO, \"terminal update\");\n for( int i = 0; i < height; i ++ ) {\n *ts->mStringListModel << QString(term_get_line(ts->terminal, i));\n }\n}\n\nvoid TerminalScreen::terminal_data()\n{\n if( !term_process_child( terminal ) ) {\n exit(0);\n }\n}\nUpdate list entries on term_update instead of appending more#include \"terminalscreen.hpp\"\n#include \"logging.h\"\n\nusing namespace bb::cascades;\n\nTerminalScreen::TerminalScreen( term_t handle, int argc, char *argv[], AbstractPane *pane) : terminal(handle)\n{\n int ret = 0;\n QObject *pObj;\n\n term_get_grid_size( handle, &width, &height );\n slog2f(buffer_handle, 0, SLOG2_INFO, \"TerminalScreen start %dx%d\", width, height);\n mStringListModel = new QStringListDataModel;\n term_set_user_data( terminal, this );\n term_register_update( terminal, term_update );\n pObj = pane->findChild(\"terminalLines\");\n mStringList = (ListView *) pObj;\n mStringList->setDataModel( mStringListModel );\n\n for( int i = 0; i < height; i ++ ) {\n *mStringListModel << QString(term_get_line(terminal, i));\n }\n\n notifier = new QSocketNotifier( term_get_file_descriptor(terminal), QSocketNotifier::Read );\n QObject::connect(notifier, SIGNAL(activated(int)), this, SLOT(terminal_data()));\n}\n\nTerminalScreen::~TerminalScreen()\n{\n delete notifier;\n}\n\nvoid TerminalScreen::term_update( term_t term, int x, int y, int width, int height )\n{\n TerminalScreen *ts = (TerminalScreen *)term_get_user_data( term );\n slog2c(buffer_handle, 0, SLOG2_INFO, \"terminal update\");\n for( int i = 0; i < height; i ++ ) {\n ts->mStringListModel->replace(i, QString(term_get_line(ts->terminal, i)));\n }\n}\n\nvoid TerminalScreen::terminal_data()\n{\n if( !term_process_child( terminal ) ) {\n exit(0);\n }\n}\n<|endoftext|>"} {"text":"#include \n\n#include \"helpers.hpp\"\n\n#include \n#include \n#include \n\n#include \"catch.hpp\"\n\nusing iter::product;\nusing Vec = const std::vector;\n\nTEST_CASE(\"product: basic test, two vectors\", \"[product]\") {\n using ResType = std::vector>;\n using TP = std::tuple;\n\n Vec n1 = {0, 1};\n Vec n2 = {0, 1, 2};\n\n auto p = product(n1, n2);\n ResType v(std::begin(p), std::end(p));\n ResType vc = {TP{0,0}, TP{0,1}, TP{0,2}, TP{1,0}, TP{1,1}, TP{1,2}};\n\n REQUIRE( v == vc );\n}\n\ntests product with empty sequences#include \n\n#include \"helpers.hpp\"\n\n#include \n#include \n#include \n\n#include \"catch.hpp\"\n\nusing iter::product;\nusing Vec = const std::vector;\n\nTEST_CASE(\"product: basic test, two vectors\", \"[product]\") {\n using ResType = std::vector>;\n using TP = std::tuple;\n\n Vec n1 = {0, 1};\n Vec n2 = {0, 1, 2};\n\n auto p = product(n1, n2);\n ResType v(std::begin(p), std::end(p));\n ResType vc = {TP{0,0}, TP{0,1}, TP{0,2}, TP{1,0}, TP{1,1}, TP{1,2}};\n\n REQUIRE( v == vc );\n}\n\nTEST_CASE(\"product: empty when any iterable is empty\", \"[product]\") {\n Vec n1 = {0, 1};\n Vec n2 = {0, 1, 2};\n Vec emp = {};\n\n SECTION(\"first iterable is empty\") {\n auto p = product(emp, n1, n2);\n REQUIRE( std::begin(p) == std::end(p) );\n }\n\n SECTION(\"middle iterable is empty\") {\n auto p = product(n1, emp, n2);\n REQUIRE( std::begin(p) == std::end(p) );\n }\n\n SECTION(\"last iterable is empty\") {\n auto p = product(n1, n2, emp);\n REQUIRE( std::begin(p) == std::end(p) );\n }\n}\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: targethelper.cxx,v $\n *\n * $Revision: 1.5 $\n *\n * last change: $Author: obo $ $Date: 2006-09-16 14:05:40 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_framework.hxx\"\n\n\/\/_______________________________________________\n\/\/ own includes\n\n#ifndef __FRAMEWORK_LOADENV_TARGETHELPER_HXX_\n#include \n#endif\n\n\/\/_______________________________________________\n\/\/ namespace\n\nnamespace framework{\n\n\/\/_______________________________________________\n\/\/ declarations\n\n\/*-----------------------------------------------\n 05.08.2003 09:12\n-----------------------------------------------*\/\nTargetHelper::ESpecialTarget TargetHelper::classifyTarget(const ::rtl::OUString& sTarget)\n{\n if (\n (!sTarget.getLength() ) ||\n (sTarget.equals(SPECIALTARGET_SELF))\n )\n return E_SELF;\n\n if (sTarget.equals(SPECIALTARGET_PARENT))\n return E_PARENT;\n\n if (sTarget.equals(SPECIALTARGET_TOP))\n return E_TOP;\n\n if (sTarget.equals(SPECIALTARGET_BLANK))\n return E_BLANK;\n\n if (sTarget.equals(SPECIALTARGET_DEFAULT))\n return E_DEFAULT;\n\n if (sTarget.equals(SPECIALTARGET_BEAMER))\n return E_BEAMER;\n\n if (sTarget.equals(SPECIALTARGET_MENUBAR))\n return E_MENUBAR;\n\n if (sTarget.equals(SPECIALTARGET_HELPAGENT))\n return E_HELPAGENT;\n\n if (sTarget.equals(SPECIALTARGET_HELPTASK))\n return E_HELPTASK;\n\n return E_NOT_SPECIAL;\n}\n\n\/*-----------------------------------------------\n 05.08.2003 09:08\n-----------------------------------------------*\/\nsal_Bool TargetHelper::matchSpecialTarget(const ::rtl::OUString& sCheckTarget ,\n ESpecialTarget eSpecialTarget)\n{\n switch(eSpecialTarget)\n {\n case E_SELF :\n return (\n (!sCheckTarget.getLength() ) ||\n (sCheckTarget.equals(SPECIALTARGET_SELF))\n );\n\n case E_PARENT :\n return (sCheckTarget.equals(SPECIALTARGET_PARENT));\n\n case E_TOP :\n return (sCheckTarget.equals(SPECIALTARGET_TOP));\n\n case E_BLANK :\n return (sCheckTarget.equals(SPECIALTARGET_BLANK));\n\n case E_DEFAULT :\n return (sCheckTarget.equals(SPECIALTARGET_DEFAULT));\n\n case E_BEAMER :\n return (sCheckTarget.equals(SPECIALTARGET_BEAMER));\n\n case E_MENUBAR :\n return (sCheckTarget.equals(SPECIALTARGET_MENUBAR));\n\n case E_HELPAGENT :\n return (sCheckTarget.equals(SPECIALTARGET_HELPAGENT));\n\n case E_HELPTASK :\n return (sCheckTarget.equals(SPECIALTARGET_HELPTASK));\n default:\n return sal_False;\n }\n\n return sal_False;\n}\n\n\/*-----------------------------------------------\n 05.08.2003 09:17\n-----------------------------------------------*\/\nsal_Bool TargetHelper::isValidNameForFrame(const ::rtl::OUString& sName)\n{\n \/\/ some special targets are realy special ones :-)\n \/\/ E.g. the are realy used to locate one frame inside the frame tree.\n if (\n (!sName.getLength() ) ||\n (TargetHelper::matchSpecialTarget(sName, E_HELPTASK)) ||\n (TargetHelper::matchSpecialTarget(sName, E_BEAMER) )\n )\n return sal_True;\n\n \/\/ all other names must be checked more general\n \/\/ special targets starts with a \"_\".\n return (sName.indexOf('_') != 0);\n}\n\n} \/\/ namespace framework\nINTEGRATION: CWS changefileheader (1.5.262); FILE MERGED 2008\/03\/28 15:35:23 rt 1.5.262.1: #i87441# Change license header to LPGL v3.\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2008 by Sun Microsystems, Inc.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: targethelper.cxx,v $\n * $Revision: 1.6 $\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * \n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_framework.hxx\"\n\n\/\/_______________________________________________\n\/\/ own includes\n\n#ifndef __FRAMEWORK_LOADENV_TARGETHELPER_HXX_\n#include \n#endif\n\n\/\/_______________________________________________\n\/\/ namespace\n\nnamespace framework{\n\n\/\/_______________________________________________\n\/\/ declarations\n\n\/*-----------------------------------------------\n 05.08.2003 09:12\n-----------------------------------------------*\/\nTargetHelper::ESpecialTarget TargetHelper::classifyTarget(const ::rtl::OUString& sTarget)\n{\n if (\n (!sTarget.getLength() ) ||\n (sTarget.equals(SPECIALTARGET_SELF))\n )\n return E_SELF;\n\n if (sTarget.equals(SPECIALTARGET_PARENT))\n return E_PARENT;\n\n if (sTarget.equals(SPECIALTARGET_TOP))\n return E_TOP;\n\n if (sTarget.equals(SPECIALTARGET_BLANK))\n return E_BLANK;\n\n if (sTarget.equals(SPECIALTARGET_DEFAULT))\n return E_DEFAULT;\n\n if (sTarget.equals(SPECIALTARGET_BEAMER))\n return E_BEAMER;\n\n if (sTarget.equals(SPECIALTARGET_MENUBAR))\n return E_MENUBAR;\n\n if (sTarget.equals(SPECIALTARGET_HELPAGENT))\n return E_HELPAGENT;\n\n if (sTarget.equals(SPECIALTARGET_HELPTASK))\n return E_HELPTASK;\n\n return E_NOT_SPECIAL;\n}\n\n\/*-----------------------------------------------\n 05.08.2003 09:08\n-----------------------------------------------*\/\nsal_Bool TargetHelper::matchSpecialTarget(const ::rtl::OUString& sCheckTarget ,\n ESpecialTarget eSpecialTarget)\n{\n switch(eSpecialTarget)\n {\n case E_SELF :\n return (\n (!sCheckTarget.getLength() ) ||\n (sCheckTarget.equals(SPECIALTARGET_SELF))\n );\n\n case E_PARENT :\n return (sCheckTarget.equals(SPECIALTARGET_PARENT));\n\n case E_TOP :\n return (sCheckTarget.equals(SPECIALTARGET_TOP));\n\n case E_BLANK :\n return (sCheckTarget.equals(SPECIALTARGET_BLANK));\n\n case E_DEFAULT :\n return (sCheckTarget.equals(SPECIALTARGET_DEFAULT));\n\n case E_BEAMER :\n return (sCheckTarget.equals(SPECIALTARGET_BEAMER));\n\n case E_MENUBAR :\n return (sCheckTarget.equals(SPECIALTARGET_MENUBAR));\n\n case E_HELPAGENT :\n return (sCheckTarget.equals(SPECIALTARGET_HELPAGENT));\n\n case E_HELPTASK :\n return (sCheckTarget.equals(SPECIALTARGET_HELPTASK));\n default:\n return sal_False;\n }\n\n return sal_False;\n}\n\n\/*-----------------------------------------------\n 05.08.2003 09:17\n-----------------------------------------------*\/\nsal_Bool TargetHelper::isValidNameForFrame(const ::rtl::OUString& sName)\n{\n \/\/ some special targets are realy special ones :-)\n \/\/ E.g. the are realy used to locate one frame inside the frame tree.\n if (\n (!sName.getLength() ) ||\n (TargetHelper::matchSpecialTarget(sName, E_HELPTASK)) ||\n (TargetHelper::matchSpecialTarget(sName, E_BEAMER) )\n )\n return sal_True;\n\n \/\/ all other names must be checked more general\n \/\/ special targets starts with a \"_\".\n return (sName.indexOf('_') != 0);\n}\n\n} \/\/ namespace framework\n<|endoftext|>"} {"text":"#include \n#include \n#include \n\n#include \"acmacs-base\/stream.hh\"\n#include \"acmacs-base\/enumerate.hh\"\n#include \"acmacs-base\/string.hh\"\n#include \"acmacs-map-draw\/mod-connection-lines.hh\"\n#include \"acmacs-map-draw\/select.hh\"\n\nstatic std::pair select_antigens_sera_for_connection_lines(ChartDraw& aChartDraw, const rjson::value& select_antigens, const rjson::value& select_sera);\n\n\/\/ ----------------------------------------------------------------------\n\nvoid ModConnectionLines::apply(ChartDraw& aChartDraw, const rjson::value& \/*aModData*\/)\n{\n const auto [antigen_indexes, serum_indexes] = select_antigens_sera_for_connection_lines(aChartDraw, args()[\"antigens\"], args()[\"sera\"]);\n\n const Color line_color{rjson::get_or(args(), \"color\", \"black\")};\n const double line_width{rjson::get_or(args(), \"line_width\", 1.0)};\n\n auto layout = aChartDraw.transformed_layout();\n auto titers = aChartDraw.chart().titers();\n for (const auto ag_no : antigen_indexes) {\n for (const auto sr_no : serum_indexes) {\n if (const auto titer = titers->titer(ag_no, sr_no); !titer.is_dont_care()) {\n \/\/ std::cerr << \"DEBUG: \" << ag_no << ' ' << sr_no << ' ' << titer << '\\n';\n if (const auto from = layout->get(ag_no), to = layout->get(sr_no + aChartDraw.number_of_antigens()); from.exists() && to.exists())\n aChartDraw.line(from, to).color(line_color).line_width(line_width);\n }\n }\n }\n\n} \/\/ ModConnectionLines::apply\n\n\/\/ ----------------------------------------------------------------------\n\nvoid ModColorByNumberOfConnectionLines::apply(ChartDraw& aChartDraw, const rjson::value& \/*aModData*\/)\n{\n \/\/ ['#ffffcc','#ffeda0','#fed976','#feb24c','#fd8d3c','#fc4e2a','#e31a1c','#bd0026','#800026']\n\n \/\/ const std::array colors{0x313695,0x4575b4,0x74add1,0xabd9e9,0xe0f3f8,0xffffbf,0xfee090,0xfdae61,0xf46d43,0xd73027,0xa50026};\n \/\/ const std::array colors{0xfff5f0,0xfee0d2,0xfcbba1,0xfc9272,0xfb6a4a,0xef3b2c,0xcb181d,0xa50f15,0x67000d};\n const std::array colors{0x313695,0x74add1,0xfcbba1,0xfc9272,0xfb6a4a,0xef3b2c,0xcb181d,0xa50f15,0x67000d};\n const auto [antigen_indexes, serum_indexes] = select_antigens_sera_for_connection_lines(aChartDraw, args()[\"antigens\"], args()[\"sera\"]);\n\n std::map antigens_titers, sera_titers;\n auto titers = aChartDraw.chart().titers();\n for (const auto ag_no : antigen_indexes) {\n for (const auto sr_no : serum_indexes) {\n if (const auto titer = titers->titer(ag_no, sr_no); !titer.is_dont_care()) {\n ++antigens_titers[ag_no];\n ++sera_titers[sr_no];\n }\n }\n }\n \/\/ std::cerr << \"DEBUG: antigens: \" << antigens_titers << '\\n';\n \/\/ std::cerr << \"DEBUG: sera: \" << sera_titers << '\\n';\n\n const auto max_antigen_titers = std::max_element(std::begin(antigens_titers), std::end(antigens_titers), [](const auto& e1, const auto& e2) { return e1.second < e2.second; })->second;\n const auto bin_size = static_cast(std::ceil(double(max_antigen_titers + 1) \/ colors.size()));\n \/\/ std::cerr << \"DEBUG: max_antigen_titers: \" << max_antigen_titers << '\\n';\n\n std::vector antigens_per_bin(colors.size());\n for (const auto& [ag_no, num_titers] : antigens_titers)\n antigens_per_bin.at(num_titers \/ bin_size).insert(ag_no);\n for (auto [color_no, antigens] : acmacs::enumerate(antigens_per_bin)) {\n acmacs::PointStyle style;\n \/\/ style.outline = BLACK;\n style.fill = style.outline = colors.at(color_no);\n aChartDraw.modify(antigens, style, PointDrawingOrder::Raise);\n add_legend(aChartDraw, antigens, style, string::concat(color_no * bin_size, \"-\", (color_no + 1) * bin_size - 1, \" titrations\"), rjson::object{});\n }\n\n} \/\/ ModColorByNumberOfConnectionLines::apply\n\n\/\/ ----------------------------------------------------------------------\n\nvoid ModErrorLines::apply(ChartDraw& aChartDraw, const rjson::value& \/*aModData*\/)\n{\n const auto [antigen_indexes, serum_indexes] = select_antigens_sera_for_connection_lines(aChartDraw, args()[\"antigens\"], args()[\"sera\"]);\n\n const Color line_color_td_more{rjson::get_or(args(), \"color\", \"red\")};\n const Color line_color_td_less{rjson::get_or(args(), \"color\", \"blue\")};\n const double line_width{rjson::get_or(args(), \"line_width\", 1.0)};\n const bool report{rjson::get_or(args(), \"report\", false)};\n const auto error_lines = aChartDraw.projection().error_lines();\n\n auto layout = aChartDraw.transformed_layout();\n auto titers = aChartDraw.chart().titers();\n auto antigens = aChartDraw.chart().antigens();\n auto sera = aChartDraw.chart().sera();\n const auto number_of_antigens = antigens->size();\n for (const auto ag_no : antigen_indexes) {\n for (const auto sr_no : serum_indexes) {\n const auto p2_no = sr_no + number_of_antigens;\n if (const auto found =\n std::find_if(std::begin(error_lines), std::end(error_lines), [p1_no=ag_no,p2_no](const auto& erl) { return erl.point_1 == p1_no && erl.point_2 == p2_no; });\n found != std::end(error_lines)) {\n if (const auto p1 = layout->get(ag_no), p2 = layout->get(p2_no); p1.exists() && p2.exists()) {\n if (report)\n fmt::print(\"INFO: error line {} {} -- {} {} : {}\\n\", ag_no, antigens->at(ag_no)->full_name(), sr_no, sera->at(sr_no)->full_name(), found->error_line);\n \/\/aChartDraw.line(p1, p2).color(GREY).line_width(line_width * 3);\n const auto v3 = (p2 - p1) \/ distance(p1, p2) * (- found->error_line) \/ 2.0;\n const auto& color = found->error_line > 0 ? line_color_td_more : line_color_td_less;\n aChartDraw.line(p1, p1 + v3).color(color).line_width(line_width);\n aChartDraw.line(p2, p2 - v3).color(color).line_width(line_width);\n \/\/ std::cerr << \"DEBUG: \" << found->point_1 << ' ' << sr_no << ' ' << found->error_line << ' ' << v3 << '\\n';\n }\n }\n }\n }\n\n} \/\/ ModErrorLines::apply\n\n\/\/ ----------------------------------------------------------------------\n\nstd::pair select_antigens_sera_for_connection_lines(ChartDraw& aChartDraw, const rjson::value& select_antigens, const rjson::value& select_sera)\n{\n acmacs::chart::Indexes antigen_indexes, serum_indexes;\n if (!select_antigens.is_null())\n antigen_indexes = SelectAntigens(SelectAntigens::verbose::no, 100).select(aChartDraw, select_antigens);\n else\n antigen_indexes = aChartDraw.chart().antigens()->all_indexes();\n if (!select_sera.is_null())\n serum_indexes = SelectSera(SelectSera::verbose::no, 100).select(aChartDraw, select_sera);\n else\n serum_indexes = aChartDraw.chart().sera()->all_indexes();\n \/\/ std::cerr << \"DEBUG: antigens: \" << antigen_indexes << '\\n';\n \/\/ std::cerr << \"DEBUG: sera: \" << serum_indexes << '\\n';\n return {antigen_indexes, serum_indexes};\n\n} \/\/ select_antigens_sera_for_connection_lines\n\n\/\/ ----------------------------------------------------------------------\n\n\n\/\/ ----------------------------------------------------------------------\n\/\/\/ Local Variables:\n\/\/\/ eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))\n\/\/\/ End:\ndebugging#include \n#include \n#include \n\n#include \"acmacs-base\/stream.hh\"\n#include \"acmacs-base\/enumerate.hh\"\n#include \"acmacs-base\/string.hh\"\n#include \"acmacs-map-draw\/mod-connection-lines.hh\"\n#include \"acmacs-map-draw\/select.hh\"\n\nstatic std::pair select_antigens_sera_for_connection_lines(ChartDraw& aChartDraw, const rjson::value& select_antigens, const rjson::value& select_sera);\n\n\/\/ ----------------------------------------------------------------------\n\nvoid ModConnectionLines::apply(ChartDraw& aChartDraw, const rjson::value& \/*aModData*\/)\n{\n const auto [antigen_indexes, serum_indexes] = select_antigens_sera_for_connection_lines(aChartDraw, args()[\"antigens\"], args()[\"sera\"]);\n\n const Color line_color{rjson::get_or(args(), \"color\", \"black\")};\n const double line_width{rjson::get_or(args(), \"line_width\", 1.0)};\n\n auto layout = aChartDraw.transformed_layout();\n auto titers = aChartDraw.chart().titers();\n for (const auto ag_no : antigen_indexes) {\n for (const auto sr_no : serum_indexes) {\n if (const auto titer = titers->titer(ag_no, sr_no); !titer.is_dont_care()) {\n \/\/ std::cerr << \"DEBUG: \" << ag_no << ' ' << sr_no << ' ' << titer << '\\n';\n if (const auto from = layout->get(ag_no), to = layout->get(sr_no + aChartDraw.number_of_antigens()); from.exists() && to.exists())\n aChartDraw.line(from, to).color(line_color).line_width(line_width);\n }\n }\n }\n\n} \/\/ ModConnectionLines::apply\n\n\/\/ ----------------------------------------------------------------------\n\nvoid ModColorByNumberOfConnectionLines::apply(ChartDraw& aChartDraw, const rjson::value& \/*aModData*\/)\n{\n \/\/ ['#ffffcc','#ffeda0','#fed976','#feb24c','#fd8d3c','#fc4e2a','#e31a1c','#bd0026','#800026']\n\n \/\/ const std::array colors{0x313695,0x4575b4,0x74add1,0xabd9e9,0xe0f3f8,0xffffbf,0xfee090,0xfdae61,0xf46d43,0xd73027,0xa50026};\n \/\/ const std::array colors{0xfff5f0,0xfee0d2,0xfcbba1,0xfc9272,0xfb6a4a,0xef3b2c,0xcb181d,0xa50f15,0x67000d};\n const std::array colors{0x313695,0x74add1,0xfcbba1,0xfc9272,0xfb6a4a,0xef3b2c,0xcb181d,0xa50f15,0x67000d};\n const auto [antigen_indexes, serum_indexes] = select_antigens_sera_for_connection_lines(aChartDraw, args()[\"antigens\"], args()[\"sera\"]);\n\n std::map antigens_titers, sera_titers;\n auto titers = aChartDraw.chart().titers();\n for (const auto ag_no : antigen_indexes) {\n for (const auto sr_no : serum_indexes) {\n if (const auto titer = titers->titer(ag_no, sr_no); !titer.is_dont_care()) {\n ++antigens_titers[ag_no];\n ++sera_titers[sr_no];\n }\n }\n }\n \/\/ std::cerr << \"DEBUG: antigens: \" << antigens_titers << '\\n';\n \/\/ std::cerr << \"DEBUG: sera: \" << sera_titers << '\\n';\n\n const auto max_antigen_titers = std::max_element(std::begin(antigens_titers), std::end(antigens_titers), [](const auto& e1, const auto& e2) { return e1.second < e2.second; })->second;\n const auto bin_size = static_cast(std::ceil(double(max_antigen_titers + 1) \/ colors.size()));\n \/\/ std::cerr << \"DEBUG: max_antigen_titers: \" << max_antigen_titers << '\\n';\n\n std::vector antigens_per_bin(colors.size());\n for (const auto& [ag_no, num_titers] : antigens_titers)\n antigens_per_bin.at(num_titers \/ bin_size).insert(ag_no);\n for (auto [color_no, antigens] : acmacs::enumerate(antigens_per_bin)) {\n acmacs::PointStyle style;\n \/\/ style.outline = BLACK;\n style.fill = style.outline = colors.at(color_no);\n aChartDraw.modify(antigens, style, PointDrawingOrder::Raise);\n add_legend(aChartDraw, antigens, style, string::concat(color_no * bin_size, \"-\", (color_no + 1) * bin_size - 1, \" titrations\"), rjson::object{});\n }\n\n} \/\/ ModColorByNumberOfConnectionLines::apply\n\n\/\/ ----------------------------------------------------------------------\n\nvoid ModErrorLines::apply(ChartDraw& aChartDraw, const rjson::value& \/*aModData*\/)\n{\n const auto [antigen_indexes, serum_indexes] = select_antigens_sera_for_connection_lines(aChartDraw, args()[\"antigens\"], args()[\"sera\"]);\n\n const Color line_color_td_more{rjson::get_or(args(), \"color\", \"red\")};\n const Color line_color_td_less{rjson::get_or(args(), \"color\", \"blue\")};\n const double line_width{rjson::get_or(args(), \"line_width\", 1.0)};\n const bool report{rjson::get_or(args(), \"report\", false)};\n const auto error_lines = aChartDraw.projection().error_lines();\n\n \/\/ if (report) {\n \/\/ fmt::print(\"INFO: antigens for error lines: {}\\nINFO: sera for error lines: {}\\n\", antigen_indexes, serum_indexes);\n \/\/ for (const auto& errl : error_lines)\n \/\/ fmt::print(\"INFO: error line {} {} : {}\\n\", errl.point_1, errl.point_2, errl.error_line);\n \/\/ }\n\n auto layout = aChartDraw.transformed_layout();\n auto titers = aChartDraw.chart().titers();\n auto antigens = aChartDraw.chart().antigens();\n auto sera = aChartDraw.chart().sera();\n const auto number_of_antigens = antigens->size();\n for (const auto ag_no : antigen_indexes) {\n for (const auto sr_no : serum_indexes) {\n const auto p2_no = sr_no + number_of_antigens;\n if (const auto found =\n std::find_if(std::begin(error_lines), std::end(error_lines), [p1_no=ag_no,p2_no](const auto& erl) { return erl.point_1 == p1_no && erl.point_2 == p2_no; });\n found != std::end(error_lines)) {\n if (const auto p1 = layout->get(ag_no), p2 = layout->get(p2_no); p1.exists() && p2.exists()) {\n if (report)\n fmt::print(\"INFO: error line {} {} -- {} {} : {}\\n\", ag_no, antigens->at(ag_no)->full_name(), sr_no, sera->at(sr_no)->full_name(), found->error_line);\n \/\/aChartDraw.line(p1, p2).color(GREY).line_width(line_width * 3);\n const auto v3 = (p2 - p1) \/ distance(p1, p2) * (- found->error_line) \/ 2.0;\n const auto& color = found->error_line > 0 ? line_color_td_more : line_color_td_less;\n aChartDraw.line(p1, p1 + v3).color(color).line_width(line_width);\n aChartDraw.line(p2, p2 - v3).color(color).line_width(line_width);\n \/\/ std::cerr << \"DEBUG: \" << found->point_1 << ' ' << sr_no << ' ' << found->error_line << ' ' << v3 << '\\n';\n }\n }\n }\n }\n\n} \/\/ ModErrorLines::apply\n\n\/\/ ----------------------------------------------------------------------\n\nstd::pair select_antigens_sera_for_connection_lines(ChartDraw& aChartDraw, const rjson::value& select_antigens, const rjson::value& select_sera)\n{\n acmacs::chart::Indexes antigen_indexes, serum_indexes;\n if (!select_antigens.is_null())\n antigen_indexes = SelectAntigens(SelectAntigens::verbose::no, 100).select(aChartDraw, select_antigens);\n else\n antigen_indexes = aChartDraw.chart().antigens()->all_indexes();\n if (!select_sera.is_null())\n serum_indexes = SelectSera(SelectSera::verbose::no, 100).select(aChartDraw, select_sera);\n else\n serum_indexes = aChartDraw.chart().sera()->all_indexes();\n \/\/ std::cerr << \"DEBUG: antigens: \" << antigen_indexes << '\\n';\n \/\/ std::cerr << \"DEBUG: sera: \" << serum_indexes << '\\n';\n return {antigen_indexes, serum_indexes};\n\n} \/\/ select_antigens_sera_for_connection_lines\n\n\/\/ ----------------------------------------------------------------------\n\n\n\/\/ ----------------------------------------------------------------------\n\/\/\/ Local Variables:\n\/\/\/ eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))\n\/\/\/ End:\n<|endoftext|>"} {"text":"\/***********************************************************************\n filename: CEGUIIrrlichtTextureTarget.cpp\n created: Tue Mar 3 2009\n author: Paul D Turner (parts based on original code by Thomas Suter)\n*************************************************************************\/\n\/***************************************************************************\n * Copyright (C) 2004 - 2009 Paul D Turner & The CEGUI Development Team\n *\n * Permission is hereby granted, free of charge, to any person obtaining\n * a copy of this software and associated documentation files (the\n * \"Software\"), to deal in the Software without restriction, including\n * without limitation the rights to use, copy, modify, merge, publish,\n * distribute, sublicense, and\/or sell copies of the Software, and to\n * permit persons to whom the Software is furnished to do so, subject to\n * the following conditions:\n *\n * The above copyright notice and this permission notice shall be\n * included in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\n * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR\n * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,\n * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\n * OTHER DEALINGS IN THE SOFTWARE.\n ***************************************************************************\/\n#ifdef HAVE_CONFIG_H\n# include \"config.h\"\n#endif\n\n#include \"CEGUIIrrlichtTextureTarget.h\"\n#include \"CEGUIIrrlichtTexture.h\"\n\n\/\/ Start of CEGUI namespace section\nnamespace CEGUI\n{\n\/\/----------------------------------------------------------------------------\/\/\nconst float IrrlichtTextureTarget::DEFAULT_SIZE = 128.0f;\n\n\/\/----------------------------------------------------------------------------\/\/\nIrrlichtTextureTarget::IrrlichtTextureTarget(IrrlichtRenderer& owner,\n irr::video::IVideoDriver& driver) :\n IrrlichtRenderTarget(owner, driver),\n d_texture(0),\n d_CEGUITexture(static_cast(&d_owner.createTexture()))\n{\n \/\/ setup area and cause the initial texture to be generated.\n declareRenderSize(Size(DEFAULT_SIZE, DEFAULT_SIZE));\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nIrrlichtTextureTarget::~IrrlichtTextureTarget()\n{\n cleanupTargetTexture();\n d_owner.destroyTexture(*d_CEGUITexture);\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nvoid IrrlichtTextureTarget::activate()\n{\n d_driver.setRenderTarget(d_texture, false, false);\n IrrlichtRenderTarget::activate();\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nvoid IrrlichtTextureTarget::deactivate()\n{\n IrrlichtRenderTarget::deactivate();\n d_driver.setRenderTarget(0);\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nbool IrrlichtTextureTarget::isImageryCache() const\n{\n return true;\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nvoid IrrlichtTextureTarget::clear()\n{\n d_driver.setRenderTarget(d_texture, true, false,\n irr::video::SColor(0, 0, 0, 0));\n d_driver.setRenderTarget(0);\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nTexture& IrrlichtTextureTarget::getTexture() const\n{\n return *d_CEGUITexture;\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nvoid IrrlichtTextureTarget::declareRenderSize(const Size& sz)\n{\n const bool realloc =\n !d_texture ||\n static_cast(d_texture->getSize().Width) < sz.d_width ||\n static_cast(d_texture->getSize().Height) < sz.d_height;\n\n \/\/ update area to render into.\n setArea(Rect(d_area.getPosition(), sz));\n\n \/\/ exit if current texture size is large enough\n if (!realloc)\n return;\n\n \/\/ get adjusted size - to account for device capabilities\n const Size final_sz(d_owner.getAdjustedTextureSize(sz));\n\n cleanupTargetTexture();\n\n #if CEGUI_IRR_SDK_VERSION >= 16\n const irr::core::dimension2d irr_sz(\n static_cast(final_sz.d_width),\n static_cast(final_sz.d_height));\n #else\n const irr::core::dimension2d irr_sz(\n static_cast(final_sz.d_width),\n static_cast(final_sz.d_height));\n #endif\n\n d_texture = d_driver.addRenderTargetTexture(\n irr_sz, IrrlichtTexture::getUniqueName().c_str());\n\n d_CEGUITexture->setIrrlichtTexture(d_texture);\n d_CEGUITexture->setOriginalDataSize(d_area.getSize());\n\n clear();\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nbool IrrlichtTextureTarget::isRenderingInverted() const\n{\n return false;\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nvoid IrrlichtTextureTarget::cleanupTargetTexture()\n{\n if (d_texture)\n {\n d_CEGUITexture->setIrrlichtTexture(0);\n d_driver.removeTexture(d_texture);\n d_texture = 0;\n }\n}\n\n\/\/----------------------------------------------------------------------------\/\/\n\n} \/\/ End of CEGUI namespace section\nFIX: IrrlichtRenderer would incorrectly clear the main render target (screen) during render to texture operations. Thanks to Timo. See: http:\/\/www.cegui.org.uk\/mantis\/view.php?id=348\/***********************************************************************\n filename: CEGUIIrrlichtTextureTarget.cpp\n created: Tue Mar 3 2009\n author: Paul D Turner (parts based on original code by Thomas Suter)\n*************************************************************************\/\n\/***************************************************************************\n * Copyright (C) 2004 - 2009 Paul D Turner & The CEGUI Development Team\n *\n * Permission is hereby granted, free of charge, to any person obtaining\n * a copy of this software and associated documentation files (the\n * \"Software\"), to deal in the Software without restriction, including\n * without limitation the rights to use, copy, modify, merge, publish,\n * distribute, sublicense, and\/or sell copies of the Software, and to\n * permit persons to whom the Software is furnished to do so, subject to\n * the following conditions:\n *\n * The above copyright notice and this permission notice shall be\n * included in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\n * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR\n * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,\n * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\n * OTHER DEALINGS IN THE SOFTWARE.\n ***************************************************************************\/\n#ifdef HAVE_CONFIG_H\n# include \"config.h\"\n#endif\n\n#include \"CEGUIIrrlichtTextureTarget.h\"\n#include \"CEGUIIrrlichtTexture.h\"\n\n\/\/ Start of CEGUI namespace section\nnamespace CEGUI\n{\n\/\/----------------------------------------------------------------------------\/\/\nconst float IrrlichtTextureTarget::DEFAULT_SIZE = 128.0f;\n\n\/\/----------------------------------------------------------------------------\/\/\nIrrlichtTextureTarget::IrrlichtTextureTarget(IrrlichtRenderer& owner,\n irr::video::IVideoDriver& driver) :\n IrrlichtRenderTarget(owner, driver),\n d_texture(0),\n d_CEGUITexture(static_cast(&d_owner.createTexture()))\n{\n \/\/ setup area and cause the initial texture to be generated.\n declareRenderSize(Size(DEFAULT_SIZE, DEFAULT_SIZE));\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nIrrlichtTextureTarget::~IrrlichtTextureTarget()\n{\n cleanupTargetTexture();\n d_owner.destroyTexture(*d_CEGUITexture);\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nvoid IrrlichtTextureTarget::activate()\n{\n d_driver.setRenderTarget(d_texture, false, false);\n IrrlichtRenderTarget::activate();\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nvoid IrrlichtTextureTarget::deactivate()\n{\n IrrlichtRenderTarget::deactivate();\n d_driver.setRenderTarget(0, false, false);\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nbool IrrlichtTextureTarget::isImageryCache() const\n{\n return true;\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nvoid IrrlichtTextureTarget::clear()\n{\n d_driver.setRenderTarget(d_texture, true, false,\n irr::video::SColor(0, 0, 0, 0));\n d_driver.setRenderTarget(0, false, false);\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nTexture& IrrlichtTextureTarget::getTexture() const\n{\n return *d_CEGUITexture;\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nvoid IrrlichtTextureTarget::declareRenderSize(const Size& sz)\n{\n const bool realloc =\n !d_texture ||\n static_cast(d_texture->getSize().Width) < sz.d_width ||\n static_cast(d_texture->getSize().Height) < sz.d_height;\n\n \/\/ update area to render into.\n setArea(Rect(d_area.getPosition(), sz));\n\n \/\/ exit if current texture size is large enough\n if (!realloc)\n return;\n\n \/\/ get adjusted size - to account for device capabilities\n const Size final_sz(d_owner.getAdjustedTextureSize(sz));\n\n cleanupTargetTexture();\n\n #if CEGUI_IRR_SDK_VERSION >= 16\n const irr::core::dimension2d irr_sz(\n static_cast(final_sz.d_width),\n static_cast(final_sz.d_height));\n #else\n const irr::core::dimension2d irr_sz(\n static_cast(final_sz.d_width),\n static_cast(final_sz.d_height));\n #endif\n\n d_texture = d_driver.addRenderTargetTexture(\n irr_sz, IrrlichtTexture::getUniqueName().c_str());\n\n d_CEGUITexture->setIrrlichtTexture(d_texture);\n d_CEGUITexture->setOriginalDataSize(d_area.getSize());\n\n clear();\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nbool IrrlichtTextureTarget::isRenderingInverted() const\n{\n return false;\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nvoid IrrlichtTextureTarget::cleanupTargetTexture()\n{\n if (d_texture)\n {\n d_CEGUITexture->setIrrlichtTexture(0);\n d_driver.removeTexture(d_texture);\n d_texture = 0;\n }\n}\n\n\/\/----------------------------------------------------------------------------\/\/\n\n} \/\/ End of CEGUI namespace section\n<|endoftext|>"} {"text":"\/*\n * HypothesisColl.cpp\n *\n * Created on: 26 Feb 2016\n * Author: hieu\n *\/\n#include \n#include \n#include \n#include \n#include \"HypothesisColl.h\"\n#include \"ManagerBase.h\"\n#include \"System.h\"\n#include \"MemPoolAllocator.h\"\n\nusing namespace std;\n\nnamespace Moses2\n{\n\nHypothesisColl::HypothesisColl(const ManagerBase &mgr)\n :m_coll(MemPoolAllocator(mgr.GetPool()))\n ,m_sortedHypos(NULL)\n{\n m_bestScore = -std::numeric_limits::infinity();\n m_worstScore = std::numeric_limits::infinity();\n}\n\nconst HypothesisBase *HypothesisColl::GetBestHypo() const\n{\n if (GetSize() == 0) {\n return NULL;\n }\n if (m_sortedHypos) {\n return (*m_sortedHypos)[0];\n }\n\n SCORE bestScore = -std::numeric_limits::infinity();\n const HypothesisBase *bestHypo;\n BOOST_FOREACH(const HypothesisBase *hypo, m_coll) {\n if (hypo->GetFutureScore() > bestScore) {\n bestScore = hypo->GetFutureScore();\n bestHypo = hypo;\n }\n }\n return bestHypo;\n}\n\nvoid HypothesisColl::Add(\n const ManagerBase &mgr,\n HypothesisBase *hypo,\n Recycler &hypoRecycle,\n ArcLists &arcLists)\n{\n size_t maxStackSize = mgr.system.options.search.stack_size;\n\n if (GetSize() > maxStackSize * 2) {\n \/\/cerr << \"maxStackSize=\" << maxStackSize << \" \" << GetSize() << endl;\n PruneHypos(mgr, mgr.arcLists);\n }\n\n SCORE futureScore = hypo->GetFutureScore();\n\n \/*\n cerr << \"scores:\"\n << futureScore << \" \"\n << m_bestScore << \" \"\n << GetSize() << \" \"\n << endl;\n *\/\n if (GetSize() >= maxStackSize && futureScore < m_worstScore) {\n \/\/ beam threshold or really bad hypo that won't make the pruning cut\n \/\/ as more hypos are added, the m_worstScore stat gets out of date and isn't the optimum cut-off point\n \/\/cerr << \"Discard, really bad score:\" << hypo->Debug(mgr.system) << endl;\n hypoRecycle.Recycle(hypo);\n return;\n }\n\n StackAdd added = Add(hypo);\n\n size_t nbestSize = mgr.system.options.nbest.nbest_size;\n if (nbestSize) {\n arcLists.AddArc(added.added, hypo, added.other);\n } else {\n if (added.added) {\n if (added.other) {\n hypoRecycle.Recycle(added.other);\n }\n } else {\n hypoRecycle.Recycle(hypo);\n }\n }\n\n \/\/ update beam variables\n if (added.added) {\n if (futureScore > m_bestScore) {\n m_bestScore = futureScore;\n float beamWidth = mgr.system.options.search.beam_width;\n if ( m_bestScore + beamWidth > m_worstScore ) {\n m_worstScore = m_bestScore + beamWidth;\n }\n } else if (GetSize() <= maxStackSize && futureScore < m_worstScore) {\n m_worstScore = futureScore;\n }\n }\n}\n\nStackAdd HypothesisColl::Add(const HypothesisBase *hypo)\n{\n std::pair<_HCType::iterator, bool> addRet = m_coll.insert(hypo);\n \/\/cerr << endl << \"new=\" << hypo->Debug(hypo->GetManager().system) << endl;\n\n \/\/ CHECK RECOMBINATION\n if (addRet.second) {\n \/\/ equiv hypo doesn't exists\n \/\/cerr << \"Added \" << hypo << endl;\n return StackAdd(true, NULL);\n } else {\n HypothesisBase *hypoExisting = const_cast(*addRet.first);\n \/\/cerr << \"hypoExisting=\" << hypoExisting->Debug(hypo->GetManager().system) << endl;\n\n if (hypo->GetFutureScore() > hypoExisting->GetFutureScore()) {\n \/\/ incoming hypo is better than the one we have\n const HypothesisBase * const &hypoExisting1 = *addRet.first;\n const HypothesisBase *&hypoExisting2 =\n const_cast(hypoExisting1);\n hypoExisting2 = hypo;\n\n \/\/cerr << \"Added \" << hypo << \" dicard existing \" << hypoExisting2 << endl;\n return StackAdd(true, hypoExisting);\n } else {\n \/\/ already storing the best hypo. discard incoming hypo\n \/\/cerr << \"Keep existing \" << hypoExisting << \" dicard new \" << hypo << endl;\n return StackAdd(false, hypoExisting);\n }\n }\n\n \/\/assert(false);\n}\n\nconst Hypotheses &HypothesisColl::GetSortedAndPrunedHypos(\n const ManagerBase &mgr,\n ArcLists &arcLists) const\n{\n if (m_sortedHypos == NULL) {\n \/\/ create sortedHypos first\n MemPool &pool = mgr.GetPool();\n m_sortedHypos = new (pool.Allocate()) Hypotheses(pool,\n m_coll.size());\n\n SortHypos(mgr, m_sortedHypos->GetArray());\n\n \/\/ prune\n Recycler &recycler = mgr.GetHypoRecycle();\n\n size_t maxStackSize = mgr.system.options.search.stack_size;\n if (maxStackSize && m_sortedHypos->size() > maxStackSize) {\n for (size_t i = maxStackSize; i < m_sortedHypos->size(); ++i) {\n HypothesisBase *hypo = const_cast((*m_sortedHypos)[i]);\n recycler.Recycle(hypo);\n\n \/\/ delete from arclist\n if (mgr.system.options.nbest.nbest_size) {\n arcLists.Delete(hypo);\n }\n }\n m_sortedHypos->resize(maxStackSize);\n }\n\n }\n\n return *m_sortedHypos;\n}\n\nvoid HypothesisColl::PruneHypos(const ManagerBase &mgr, ArcLists &arcLists)\n{\n size_t maxStackSize = mgr.system.options.search.stack_size;\n\n Recycler &recycler = mgr.GetHypoRecycle();\n\n const HypothesisBase **sortedHypos = (const HypothesisBase **) alloca(GetSize() * sizeof(const HypothesisBase *));\n SortHypos(mgr, sortedHypos);\n\n \/\/ update worse score\n m_worstScore = sortedHypos[maxStackSize - 1]->GetFutureScore();\n\n \/\/ prune\n for (size_t i = maxStackSize; i < GetSize(); ++i) {\n HypothesisBase *hypo = const_cast(sortedHypos[i]);\n\n \/\/ delete from arclist\n if (mgr.system.options.nbest.nbest_size) {\n arcLists.Delete(hypo);\n }\n\n \/\/ delete from collection\n Delete(hypo);\n\n recycler.Recycle(hypo);\n }\n\n}\n\nvoid HypothesisColl::SortHypos(const ManagerBase &mgr, const HypothesisBase **sortedHypos) const\n{\n size_t maxStackSize = mgr.system.options.search.stack_size;\n \/\/assert(maxStackSize); \/\/ can't do stack=0 - unlimited stack size. No-one ever uses that\n \/\/assert(GetSize() > maxStackSize);\n \/\/assert(sortedHypos.size() == GetSize());\n\n \/*\n cerr << \"UNSORTED hypos: \";\n BOOST_FOREACH(const HypothesisBase *hypo, m_coll) {\n cerr << hypo << \"(\" << hypo->GetFutureScore() << \")\" << \" \";\n }\n cerr << endl;\n *\/\n size_t ind = 0;\n BOOST_FOREACH(const HypothesisBase *hypo, m_coll) {\n sortedHypos[ind] = hypo;\n ++ind;\n }\n\n size_t indMiddle;\n if (maxStackSize == 0) {\n indMiddle = GetSize();\n } else if (GetSize() > maxStackSize) {\n indMiddle = maxStackSize;\n } else {\n \/\/ GetSize() <= maxStackSize\n indMiddle = GetSize();\n }\n\n const HypothesisBase **iterMiddle = sortedHypos + indMiddle;\n\n std::partial_sort(\n sortedHypos,\n iterMiddle,\n sortedHypos + GetSize(),\n HypothesisFutureScoreOrderer());\n\n \/*\n cerr << \"sorted hypos: \";\n for (size_t i = 0; i < sortedHypos.size(); ++i) {\n const HypothesisBase *hypo = sortedHypos[i];\n cerr << hypo << \" \";\n }\n cerr << endl;\n *\/\n}\n\nvoid HypothesisColl::Delete(const HypothesisBase *hypo)\n{\n \/\/cerr << \"hypo=\" << hypo << \" \" << m_coll.size() << endl;\n\n size_t erased = m_coll.erase(hypo);\n UTIL_THROW_IF2(erased != 1, \"couldn't erase hypo \" << hypo);\n}\n\nvoid HypothesisColl::Clear()\n{\n m_sortedHypos = NULL;\n m_coll.clear();\n\n m_bestScore = -std::numeric_limits::infinity();\n m_worstScore = std::numeric_limits::infinity();\n}\n\nstd::string HypothesisColl::Debug(const System &system) const\n{\n stringstream out;\n BOOST_FOREACH (const HypothesisBase *hypo, m_coll) {\n out << hypo->Debug(system);\n out << std::endl << std::endl;\n }\n\n return out.str();\n}\n\n} \/* namespace Moses2 *\/\ndebug\/*\n * HypothesisColl.cpp\n *\n * Created on: 26 Feb 2016\n * Author: hieu\n *\/\n#include \n#include \n#include \n#include \n#include \"HypothesisColl.h\"\n#include \"ManagerBase.h\"\n#include \"System.h\"\n#include \"MemPoolAllocator.h\"\n\nusing namespace std;\n\nnamespace Moses2\n{\n\nHypothesisColl::HypothesisColl(const ManagerBase &mgr)\n :m_coll(MemPoolAllocator(mgr.GetPool()))\n ,m_sortedHypos(NULL)\n{\n m_bestScore = -std::numeric_limits::infinity();\n m_worstScore = std::numeric_limits::infinity();\n}\n\nconst HypothesisBase *HypothesisColl::GetBestHypo() const\n{\n if (GetSize() == 0) {\n return NULL;\n }\n if (m_sortedHypos) {\n return (*m_sortedHypos)[0];\n }\n\n SCORE bestScore = -std::numeric_limits::infinity();\n const HypothesisBase *bestHypo;\n BOOST_FOREACH(const HypothesisBase *hypo, m_coll) {\n if (hypo->GetFutureScore() > bestScore) {\n bestScore = hypo->GetFutureScore();\n bestHypo = hypo;\n }\n }\n return bestHypo;\n}\n\nvoid HypothesisColl::Add(\n const ManagerBase &mgr,\n HypothesisBase *hypo,\n Recycler &hypoRecycle,\n ArcLists &arcLists)\n{\n size_t maxStackSize = mgr.system.options.search.stack_size;\n\n if (GetSize() > maxStackSize * 2) {\n \/\/cerr << \"maxStackSize=\" << maxStackSize << \" \" << GetSize() << endl;\n PruneHypos(mgr, mgr.arcLists);\n }\n\n SCORE futureScore = hypo->GetFutureScore();\n\n \/*\n cerr << \"scores:\"\n << futureScore << \" \"\n << m_bestScore << \" \"\n << GetSize() << \" \"\n << endl;\n *\/\n if (GetSize() >= maxStackSize && futureScore < m_worstScore) {\n \/\/ beam threshold or really bad hypo that won't make the pruning cut\n \/\/ as more hypos are added, the m_worstScore stat gets out of date and isn't the optimum cut-off point\n \/\/cerr << \"Discard, really bad score:\" << hypo->Debug(mgr.system) << endl;\n hypoRecycle.Recycle(hypo);\n return;\n }\n\n StackAdd added = Add(hypo);\n\n size_t nbestSize = mgr.system.options.nbest.nbest_size;\n if (nbestSize) {\n arcLists.AddArc(added.added, hypo, added.other);\n } else {\n if (added.added) {\n if (added.other) {\n hypoRecycle.Recycle(added.other);\n }\n } else {\n hypoRecycle.Recycle(hypo);\n }\n }\n\n \/\/ update beam variables\n if (added.added) {\n if (futureScore > m_bestScore) {\n m_bestScore = futureScore;\n float beamWidth = mgr.system.options.search.beam_width;\n if ( m_bestScore + beamWidth > m_worstScore ) {\n m_worstScore = m_bestScore + beamWidth;\n }\n } else if (GetSize() <= maxStackSize && futureScore < m_worstScore) {\n m_worstScore = futureScore;\n }\n }\n}\n\nStackAdd HypothesisColl::Add(const HypothesisBase *hypo)\n{\n std::pair<_HCType::iterator, bool> addRet = m_coll.insert(hypo);\n \/\/cerr << endl << \"new=\" << hypo->Debug(hypo->GetManager().system) << endl;\n\n \/\/ CHECK RECOMBINATION\n if (addRet.second) {\n \/\/ equiv hypo doesn't exists\n \/\/cerr << \"Added \" << hypo << endl;\n return StackAdd(true, NULL);\n } else {\n HypothesisBase *hypoExisting = const_cast(*addRet.first);\n \/\/cerr << \"hypoExisting=\" << hypoExisting->Debug(hypo->GetManager().system) << endl;\n\n if (hypo->GetFutureScore() > hypoExisting->GetFutureScore()) {\n \/\/ incoming hypo is better than the one we have\n const HypothesisBase * const &hypoExisting1 = *addRet.first;\n const HypothesisBase *&hypoExisting2 =\n const_cast(hypoExisting1);\n hypoExisting2 = hypo;\n\n cerr << \"Added \" << hypo << \"(\" << hypo->hash() << \")\"\n \t\t << \" discard existing \" << hypoExisting << \"(\" << hypoExisting->hash() << \")\"\n\t\t\t << endl;\n\n return StackAdd(true, hypoExisting);\n } else {\n \/\/ already storing the best hypo. discard incoming hypo\n cerr << \"Keep existing \" << hypoExisting << \"(\" << hypoExisting->hash() << \")\"\n \t\t << \" discard new \" << hypo << \"(\" << hypo->hash() << \")\"\n\t\t\t << endl;\n return StackAdd(false, hypoExisting);\n }\n }\n\n \/\/assert(false);\n}\n\nconst Hypotheses &HypothesisColl::GetSortedAndPrunedHypos(\n const ManagerBase &mgr,\n ArcLists &arcLists) const\n{\n if (m_sortedHypos == NULL) {\n \/\/ create sortedHypos first\n MemPool &pool = mgr.GetPool();\n m_sortedHypos = new (pool.Allocate()) Hypotheses(pool,\n m_coll.size());\n\n SortHypos(mgr, m_sortedHypos->GetArray());\n\n \/\/ prune\n Recycler &recycler = mgr.GetHypoRecycle();\n\n size_t maxStackSize = mgr.system.options.search.stack_size;\n if (maxStackSize && m_sortedHypos->size() > maxStackSize) {\n for (size_t i = maxStackSize; i < m_sortedHypos->size(); ++i) {\n HypothesisBase *hypo = const_cast((*m_sortedHypos)[i]);\n recycler.Recycle(hypo);\n\n \/\/ delete from arclist\n if (mgr.system.options.nbest.nbest_size) {\n arcLists.Delete(hypo);\n }\n }\n m_sortedHypos->resize(maxStackSize);\n }\n\n }\n\n return *m_sortedHypos;\n}\n\nvoid HypothesisColl::PruneHypos(const ManagerBase &mgr, ArcLists &arcLists)\n{\n size_t maxStackSize = mgr.system.options.search.stack_size;\n\n Recycler &recycler = mgr.GetHypoRecycle();\n\n const HypothesisBase **sortedHypos = (const HypothesisBase **) alloca(GetSize() * sizeof(const HypothesisBase *));\n SortHypos(mgr, sortedHypos);\n\n \/\/ update worse score\n m_worstScore = sortedHypos[maxStackSize - 1]->GetFutureScore();\n\n \/\/ prune\n for (size_t i = maxStackSize; i < GetSize(); ++i) {\n HypothesisBase *hypo = const_cast(sortedHypos[i]);\n\n \/\/ delete from arclist\n if (mgr.system.options.nbest.nbest_size) {\n arcLists.Delete(hypo);\n }\n\n \/\/ delete from collection\n Delete(hypo);\n\n recycler.Recycle(hypo);\n }\n\n}\n\nvoid HypothesisColl::SortHypos(const ManagerBase &mgr, const HypothesisBase **sortedHypos) const\n{\n size_t maxStackSize = mgr.system.options.search.stack_size;\n \/\/assert(maxStackSize); \/\/ can't do stack=0 - unlimited stack size. No-one ever uses that\n \/\/assert(GetSize() > maxStackSize);\n \/\/assert(sortedHypos.size() == GetSize());\n\n \/*\n cerr << \"UNSORTED hypos: \";\n BOOST_FOREACH(const HypothesisBase *hypo, m_coll) {\n cerr << hypo << \"(\" << hypo->GetFutureScore() << \")\" << \" \";\n }\n cerr << endl;\n *\/\n size_t ind = 0;\n BOOST_FOREACH(const HypothesisBase *hypo, m_coll) {\n sortedHypos[ind] = hypo;\n ++ind;\n }\n\n size_t indMiddle;\n if (maxStackSize == 0) {\n indMiddle = GetSize();\n } else if (GetSize() > maxStackSize) {\n indMiddle = maxStackSize;\n } else {\n \/\/ GetSize() <= maxStackSize\n indMiddle = GetSize();\n }\n\n const HypothesisBase **iterMiddle = sortedHypos + indMiddle;\n\n std::partial_sort(\n sortedHypos,\n iterMiddle,\n sortedHypos + GetSize(),\n HypothesisFutureScoreOrderer());\n\n \/*\n cerr << \"sorted hypos: \";\n for (size_t i = 0; i < sortedHypos.size(); ++i) {\n const HypothesisBase *hypo = sortedHypos[i];\n cerr << hypo << \" \";\n }\n cerr << endl;\n *\/\n}\n\nvoid HypothesisColl::Delete(const HypothesisBase *hypo)\n{\n cerr << \" Delete hypo=\" << hypo << \"(\" << hypo->hash() << \")\"\n\t\t<< \" m_coll=\" << m_coll.size() << endl;\n\n size_t erased = m_coll.erase(hypo);\n UTIL_THROW_IF2(erased != 1, \"couldn't erase hypo \" << hypo);\n}\n\nvoid HypothesisColl::Clear()\n{\n m_sortedHypos = NULL;\n m_coll.clear();\n\n m_bestScore = -std::numeric_limits::infinity();\n m_worstScore = std::numeric_limits::infinity();\n}\n\nstd::string HypothesisColl::Debug(const System &system) const\n{\n stringstream out;\n BOOST_FOREACH (const HypothesisBase *hypo, m_coll) {\n out << hypo->Debug(system);\n out << std::endl << std::endl;\n }\n\n return out.str();\n}\n\n} \/* namespace Moses2 *\/\n<|endoftext|>"} {"text":"#include \n#include \"elevator.h\"\n#include \"log.h\"\n\n\nElevator::Elevator(int idnum) {\n id = idnum;\n\n current_floor = 1;\n requested_floor = 1;\n next_floor = 1;\n direction_arrived = UP;\n elevator_state = INITIALIZING;\n\n pthread_cond_init(&elevator_wait, NULL);\n pthread_mutex_init(&elevator_mutex, NULL);\n\n pthread_create(&elevator_thread, NULL, elevator_run, this);\n}\n\nvoid *Elevator::elevator_run(void *arg) {\n Elevator *me = static_cast(arg);\n\n if (me == NULL)\n return NULL;\n\n while (1) {\n pthread_mutex_lock(&me->elevator_mutex);\n me->elevator_state = READY;\n while (me->schedule_next_request() == false) {\n eprintf(\"%s:%s Waiting...\\n\", __func__, __FILE__);\n pthread_cond_wait(&me->elevator_wait, &me->elevator_mutex);\n eprintf(\"%s:%s Scheduer kicking in...\\n\", __func__, __FILE__);\n }\n me->elevator_state = RUNNING;\n\n eprintf(\"%s:%s Elevator RUNNING dest %d\\n\", __func__, __FILE__, me->requested_floor);\n me->process_request();\n\n pthread_mutex_unlock(&me->elevator_mutex);\n }\n\n return NULL;\n}\n\nvoid Elevator::process_request() {\n next_floor = requested_floor;\n if (requested_floor > current_floor)\n direction_arrived = UP;\n else\n direction_arrived = DOWN;\n\n current_floor = next_floor;\n}\n\nbool Elevator::queue_next_request(int floor) {\n\n while (elevator_state != READY);\n requested_floor = floor;\n\n return true;\n}\n\nbool Elevator::queue_pending_request(int floor, displacement d) {\n pthread_mutex_lock(&elevator_mutex);\n\n requests.push_back(make_pair(floor, d));\n eprintf(\"%s:%s queue request floor:%d direction:%d sz %lu\\n\",\n __func__, __FILE__, floor, d, requests.size());\n pthread_cond_signal(&elevator_wait);\n\n pthread_mutex_unlock(&elevator_mutex);\n\n return true;\n}\n\nbool Elevator::schedule_next_request() {\n\n eprintf(\"%s:%s Called... %lu\\n\", __func__, __FILE__, requests.size());\n if (requests.size() == 0) {\n eprintf(\"%s:%s Queue is empty\\n\", __func__, __FILE__);\n return false;\n }\n\n if (requests.size() == 1) {\n queue_next_request(requests[0].first);\n eprintf(\"%s:%s q size 1, next floor %d\\n\",\n __func__, __FILE__, requests[0].first);\n requests.erase(requests.begin());\n return true;\n }\n\n int size = requests.size();\n\n if (direction_arrived == UP) {\n int same_d_floor = MAX_FLOORS + 1, same_d_min_index;\n int opp_d_floor = MAX_FLOORS + 1, opp_d_min_index;\n\n int same_d_low_floor = -1, same_d_low_max_index;\n int opp_d_low_floor = -1, opp_d_low_max_index;\n\n pair p;\n\n for (int i = 0; i < size; i++) {\n p = requests[i];\n if (p.first > current_floor) {\n if (p.second == direction_arrived) {\n same_d_floor = min(same_d_floor, p.first);\n same_d_min_index = i;\n } else {\n opp_d_floor = min(opp_d_floor, p.first);\n opp_d_min_index = i;\n }\n } else {\n if (p.second != direction_arrived) {\n opp_d_low_floor = max(opp_d_low_floor, p.first);\n opp_d_low_max_index = i;\n } else {\n same_d_low_floor = max(same_d_low_floor, p.first);\n same_d_low_max_index = i;\n }\n }\n }\n\n if (same_d_floor != MAX_FLOORS + 1) {\n queue_next_request(requests[same_d_min_index].first);\n eprintf(\"%s:%s q size %d, next floor %d\\n\",\n __func__, __FILE__, size, requests[0].first);\n requests.erase(requests.begin() + same_d_min_index);\n return true;\n }\n\n if (opp_d_floor != MAX_FLOORS + 1) {\n queue_next_request(requests[opp_d_min_index].first);\n eprintf(\"%s:%s q size %d, next floor %d\\n\",\n __func__, __FILE__, size, requests[0].first);\n requests.erase(requests.begin() + opp_d_min_index);\n return true;\n }\n\n if (opp_d_low_floor != - 1) {\n queue_next_request(requests[opp_d_low_max_index].first);\n eprintf(\"%s:%s q size %d, next floor %d\\n\",\n __func__, __FILE__, size, requests[0].first);\n requests.erase(requests.begin() + opp_d_low_max_index);\n return true;\n }\n\n if (same_d_low_floor != - 1) {\n queue_next_request(requests[same_d_low_max_index].first);\n eprintf(\"%s:%s q size %d, next floor %d\\n\",\n __func__, __FILE__, size, requests[0].first);\n requests.erase(requests.begin() + same_d_low_max_index);\n return true;\n }\n\n } else {\n int same_d_floor = -1, same_d_max_index;\n int opp_d_floor = -1, opp_d_max_index;\n\n int same_d_high_floor = MAX_FLOORS + 1, same_d_high_min_index;\n int opp_d_high_floor = MAX_FLOORS + 1, opp_d_high_min_index;\n\n pair p;\n\n for (int i = 0; i < size; i++) {\n p = requests[i];\n if (p.first < current_floor) {\n if (p.second == direction_arrived) {\n same_d_floor = max(same_d_floor, p.first);\n same_d_max_index = i;\n } else {\n opp_d_floor = max(opp_d_floor, p.first);\n opp_d_max_index = i;\n }\n } else {\n if (p.second != direction_arrived) {\n opp_d_high_floor = min(opp_d_high_floor, p.first);\n opp_d_high_min_index = i;\n } else {\n same_d_high_floor = min(same_d_high_floor, p.first);\n same_d_high_min_index = i;\n }\n }\n }\n\n if (same_d_floor != -1) {\n queue_next_request(requests[same_d_max_index].first);\n eprintf(\"%s:%s q size %d, next floor %d\\n\",\n __func__, __FILE__, size, requests[0].first);\n requests.erase(requests.begin() + same_d_max_index);\n return true;\n }\n\n if (opp_d_floor != -1) {\n queue_next_request(requests[opp_d_max_index].first);\n eprintf(\"%s:%s q size %d, next floor %d\\n\",\n __func__, __FILE__, size, requests[0].first);\n requests.erase(requests.begin() + opp_d_max_index);\n return true;\n }\n\n if (opp_d_high_floor != MAX_FLOORS + 1) {\n queue_next_request(requests[opp_d_high_min_index].first);\n eprintf(\"%s:%s q size %d, next floor %d\\n\",\n __func__, __FILE__, size, requests[0].first);\n requests.erase(requests.begin() + opp_d_high_min_index);\n return true;\n }\n\n if (same_d_high_floor != MAX_FLOORS + 1) {\n queue_next_request(requests[same_d_high_min_index].first);\n eprintf(\"%s:%s q size %d, next floor %d\\n\",\n __func__, __FILE__, size, requests[0].first);\n requests.erase(requests.begin() + same_d_high_min_index);\n return true;\n }\n }\n\n eprintf(\"%s:%s Error! cannot process queue (%lu)\\n\",\n __func__, __FILE__, requests.size());\n return false;\n}\n\nint Elevator::get_current_floor() {\n pthread_mutex_lock(&elevator_mutex);\n\n while (elevator_state != READY);\n return current_floor;\n\n pthread_mutex_unlock(&elevator_mutex);\n}\n\ndisplacement Elevator::get_displacement() {\n pthread_mutex_lock(&elevator_mutex);\n\n while (elevator_state != READY);\n return direction_arrived;\n\n pthread_mutex_unlock(&elevator_mutex);\n}\nelevator: modify elevator algorithm#include \n#include \"elevator.h\"\n#include \"log.h\"\n\n\nElevator::Elevator(int idnum) {\n id = idnum;\n\n current_floor = 1;\n requested_floor = 1;\n next_floor = 1;\n direction_arrived = UP;\n elevator_state = INITIALIZING;\n\n pthread_cond_init(&elevator_wait, NULL);\n pthread_mutex_init(&elevator_mutex, NULL);\n\n pthread_create(&elevator_thread, NULL, elevator_run, this);\n}\n\nvoid *Elevator::elevator_run(void *arg) {\n Elevator *me = static_cast(arg);\n\n if (me == NULL)\n return NULL;\n\n while (1) {\n pthread_mutex_lock(&me->elevator_mutex);\n me->elevator_state = READY;\n while (me->schedule_next_request() == false) {\n eprintf(\"%s:%s Waiting...\\n\", __func__, __FILE__);\n pthread_cond_wait(&me->elevator_wait, &me->elevator_mutex);\n eprintf(\"%s:%s Scheduer kicking in...\\n\", __func__, __FILE__);\n }\n me->elevator_state = RUNNING;\n\n eprintf(\"%s:%s Elevator RUNNING dest %d\\n\", __func__, __FILE__, me->requested_floor);\n me->process_request();\n\n pthread_mutex_unlock(&me->elevator_mutex);\n }\n\n return NULL;\n}\n\nvoid Elevator::process_request() {\n next_floor = requested_floor;\n if (requested_floor > current_floor)\n direction_arrived = UP;\n else\n direction_arrived = DOWN;\n\n current_floor = next_floor;\n}\n\nbool Elevator::queue_next_request(int floor) {\n\n while (elevator_state != READY);\n requested_floor = floor;\n\n return true;\n}\n\nbool Elevator::queue_pending_request(int floor, displacement d) {\n pthread_mutex_lock(&elevator_mutex);\n\n requests.push_back(make_pair(floor, d));\n eprintf(\"%s:%s queue request floor:%d direction:%d sz %lu\\n\",\n __func__, __FILE__, floor, d, requests.size());\n pthread_cond_signal(&elevator_wait);\n\n pthread_mutex_unlock(&elevator_mutex);\n\n return true;\n}\n\nbool Elevator::schedule_next_request() {\n\n eprintf(\"%s:%s Called... %lu\\n\", __func__, __FILE__, requests.size());\n if (requests.size() == 0) {\n eprintf(\"%s:%s Queue is empty\\n\", __func__, __FILE__);\n return false;\n }\n\n if (requests.size() == 1) {\n queue_next_request(requests[0].first);\n eprintf(\"%s:%s q size 1, next floor %d\\n\",\n __func__, __FILE__, requests[0].first);\n requests.erase(requests.begin());\n return true;\n }\n\n int size = requests.size();\n\n if (direction_arrived == UP) {\n int same_d_floor = MAX_FLOORS + 1, same_d_min_index;\n int opp_d_floor = -1, opp_d_max_index;\n\n int same_d_low_floor = MAX_FLOORS + 1, same_d_low_min_index;\n int opp_d_low_floor = -1, opp_d_low_max_index;\n\n pair p;\n\n for (int i = 0; i < size; i++) {\n p = requests[i];\n if (p.first > current_floor) {\n if (p.second == direction_arrived) {\n same_d_floor = min(same_d_floor, p.first);\n same_d_min_index = i;\n } else {\n opp_d_floor = max(opp_d_floor, p.first);\n opp_d_max_index = i;\n }\n } else {\n if (p.second != direction_arrived) {\n opp_d_low_floor = max(opp_d_low_floor, p.first);\n opp_d_low_max_index = i;\n } else {\n same_d_low_floor = min(same_d_low_floor, p.first);\n same_d_low_min_index = i;\n }\n }\n }\n\n if (same_d_floor != MAX_FLOORS + 1) {\n queue_next_request(requests[same_d_min_index].first);\n eprintf(\"%s:%s q size %d, next floor %d\\n\",\n __func__, __FILE__, size, requests[0].first);\n requests.erase(requests.begin() + same_d_min_index);\n return true;\n }\n\n if (opp_d_floor != MAX_FLOORS + 1) {\n queue_next_request(requests[opp_d_max_index].first);\n eprintf(\"%s:%s q size %d, next floor %d\\n\",\n __func__, __FILE__, size, requests[0].first);\n requests.erase(requests.begin() + opp_d_max_index);\n return true;\n }\n\n if (opp_d_low_floor != - 1) {\n queue_next_request(requests[opp_d_low_max_index].first);\n eprintf(\"%s:%s q size %d, next floor %d\\n\",\n __func__, __FILE__, size, requests[0].first);\n requests.erase(requests.begin() + opp_d_low_max_index);\n return true;\n }\n\n if (same_d_low_floor != - 1) {\n queue_next_request(requests[same_d_low_min_index].first);\n eprintf(\"%s:%s q size %d, next floor %d\\n\",\n __func__, __FILE__, size, requests[0].first);\n requests.erase(requests.begin() + same_d_low_min_index);\n return true;\n }\n\n } else {\n int same_d_floor = -1, same_d_max_index;\n int opp_d_floor = MAX_FLOORS + 1, opp_d_min_index;\n\n int same_d_high_floor = MAX_FLOORS + 1, same_d_high_min_index;\n int opp_d_high_floor = -1, opp_d_high_max_index;\n\n pair p;\n\n for (int i = 0; i < size; i++) {\n p = requests[i];\n if (p.first < current_floor) {\n if (p.second == direction_arrived) {\n same_d_floor = max(same_d_floor, p.first);\n same_d_max_index = i;\n } else {\n opp_d_floor = min(opp_d_floor, p.first);\n opp_d_min_index = i;\n }\n } else {\n if (p.second != direction_arrived) {\n opp_d_high_floor = min(opp_d_high_floor, p.first);\n opp_d_high_max_index = i;\n } else {\n same_d_high_floor = max(same_d_high_floor, p.first);\n same_d_high_min_index = i;\n }\n }\n }\n\n if (same_d_floor != -1) {\n queue_next_request(requests[same_d_max_index].first);\n eprintf(\"%s:%s q size %d, next floor %d\\n\",\n __func__, __FILE__, size, requests[0].first);\n requests.erase(requests.begin() + same_d_max_index);\n return true;\n }\n\n if (opp_d_floor != -1) {\n queue_next_request(requests[opp_d_min_index].first);\n eprintf(\"%s:%s q size %d, next floor %d\\n\",\n __func__, __FILE__, size, requests[0].first);\n requests.erase(requests.begin() + opp_d_min_index);\n return true;\n }\n\n if (opp_d_high_floor != MAX_FLOORS + 1) {\n queue_next_request(requests[opp_d_high_max_index].first);\n eprintf(\"%s:%s q size %d, next floor %d\\n\",\n __func__, __FILE__, size, requests[0].first);\n requests.erase(requests.begin() + opp_d_high_max_index);\n return true;\n }\n\n if (same_d_high_floor != MAX_FLOORS + 1) {\n queue_next_request(requests[same_d_high_min_index].first);\n eprintf(\"%s:%s q size %d, next floor %d\\n\",\n __func__, __FILE__, size, requests[0].first);\n requests.erase(requests.begin() + same_d_high_min_index);\n return true;\n }\n }\n\n eprintf(\"%s:%s Error! cannot process queue (%lu)\\n\",\n __func__, __FILE__, requests.size());\n return false;\n}\n\nint Elevator::get_current_floor() {\n pthread_mutex_lock(&elevator_mutex);\n\n while (elevator_state != READY);\n return current_floor;\n\n pthread_mutex_unlock(&elevator_mutex);\n}\n\ndisplacement Elevator::get_displacement() {\n pthread_mutex_lock(&elevator_mutex);\n\n while (elevator_state != READY);\n return direction_arrived;\n\n pthread_mutex_unlock(&elevator_mutex);\n}\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: WrappedScaleProperty.hxx,v $\n *\n * $Revision: 1.2 $\n *\n * last change: $Author: vg $ $Date: 2007-05-22 17:22:52 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n#ifndef CHART_WRAPPED_SCALE_PROPERTY_HXX\n#define CHART_WRAPPED_SCALE_PROPERTY_HXX\n\n#include \"WrappedProperty.hxx\"\n#include \"Chart2ModelContact.hxx\"\n\n#include \n#include \n\n\/\/.............................................................................\nnamespace chart\n{\nnamespace wrapper\n{\n\nclass WrappedScaleProperty : public WrappedProperty\n{\npublic:\n enum tScaleProperty\n {\n SCALE_PROP_MAX\n , SCALE_PROP_MIN\n , SCALE_PROP_ORIGIN\n , SCALE_PROP_STEPMAIN\n , SCALE_PROP_STEPHELP\n , SCALE_PROP_AUTO_MAX\n , SCALE_PROP_AUTO_MIN\n , SCALE_PROP_AUTO_ORIGIN\n , SCALE_PROP_AUTO_STEPMAIN\n , SCALE_PROP_AUTO_STEPHELP\n , SCALE_PROP_LOGARITHMIC\n };\n\npublic:\n WrappedScaleProperty( tScaleProperty eScaleProperty, ::boost::shared_ptr< Chart2ModelContact > spChart2ModelContact );\n virtual ~WrappedScaleProperty();\n\n static void addWrappedProperties( std::vector< WrappedProperty* >& rList, ::boost::shared_ptr< Chart2ModelContact > spChart2ModelContact );\n\n virtual void setPropertyValue( const ::com::sun::star::uno::Any& rOuterValue, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >& xInnerPropertySet ) const\n throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::beans::PropertyVetoException, ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);\n\n virtual ::com::sun::star::uno::Any getPropertyValue( const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >& xInnerPropertySet ) const\n throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);\n\nprotected: \/\/methods\n void setPropertyValue( tScaleProperty eScaleProperty, const ::com::sun::star::uno::Any& rOuterValue, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >& xInnerPropertySet ) const\n throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::beans::PropertyVetoException, ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);\n ::com::sun::star::uno::Any getPropertyValue( tScaleProperty eScaleProperty, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >& xInnerPropertySet ) const\n throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);\n\nprivate: \/\/member\n ::boost::shared_ptr< Chart2ModelContact > m_spChart2ModelContact;\n tScaleProperty m_eScaleProperty;\n\n mutable ::com::sun::star::uno::Any m_aOuterValue;\n};\n\n} \/\/ namespace wrapper\n} \/\/ namespace chart\n\/\/.............................................................................\n\n\/\/ CHART_WRAPPED_SCALE_PROPERTY_HXX\n#endif\nINTEGRATION: CWS chart14 (1.2.48); FILE MERGED 2007\/09\/20 11:22:12 iha 1.2.48.1: #i24614# enable reverse scales\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: WrappedScaleProperty.hxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: vg $ $Date: 2007-10-22 16:42:56 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n#ifndef CHART_WRAPPED_SCALE_PROPERTY_HXX\n#define CHART_WRAPPED_SCALE_PROPERTY_HXX\n\n#include \"WrappedProperty.hxx\"\n#include \"Chart2ModelContact.hxx\"\n\n#include \n#include \n\n\/\/.............................................................................\nnamespace chart\n{\nnamespace wrapper\n{\n\nclass WrappedScaleProperty : public WrappedProperty\n{\npublic:\n enum tScaleProperty\n {\n SCALE_PROP_MAX\n , SCALE_PROP_MIN\n , SCALE_PROP_ORIGIN\n , SCALE_PROP_STEPMAIN\n , SCALE_PROP_STEPHELP\n , SCALE_PROP_AUTO_MAX\n , SCALE_PROP_AUTO_MIN\n , SCALE_PROP_AUTO_ORIGIN\n , SCALE_PROP_AUTO_STEPMAIN\n , SCALE_PROP_AUTO_STEPHELP\n , SCALE_PROP_LOGARITHMIC\n , SCALE_PROP_REVERSEDIRECTION\n };\n\npublic:\n WrappedScaleProperty( tScaleProperty eScaleProperty, ::boost::shared_ptr< Chart2ModelContact > spChart2ModelContact );\n virtual ~WrappedScaleProperty();\n\n static void addWrappedProperties( std::vector< WrappedProperty* >& rList, ::boost::shared_ptr< Chart2ModelContact > spChart2ModelContact );\n\n virtual void setPropertyValue( const ::com::sun::star::uno::Any& rOuterValue, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >& xInnerPropertySet ) const\n throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::beans::PropertyVetoException, ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);\n\n virtual ::com::sun::star::uno::Any getPropertyValue( const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >& xInnerPropertySet ) const\n throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);\n\nprotected: \/\/methods\n void setPropertyValue( tScaleProperty eScaleProperty, const ::com::sun::star::uno::Any& rOuterValue, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >& xInnerPropertySet ) const\n throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::beans::PropertyVetoException, ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);\n ::com::sun::star::uno::Any getPropertyValue( tScaleProperty eScaleProperty, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >& xInnerPropertySet ) const\n throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);\n\nprivate: \/\/member\n ::boost::shared_ptr< Chart2ModelContact > m_spChart2ModelContact;\n tScaleProperty m_eScaleProperty;\n\n mutable ::com::sun::star::uno::Any m_aOuterValue;\n};\n\n} \/\/ namespace wrapper\n} \/\/ namespace chart\n\/\/.............................................................................\n\n\/\/ CHART_WRAPPED_SCALE_PROPERTY_HXX\n#endif\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \n\n#include \"base\/basictypes.h\"\n#include \"base\/command_line.h\"\n#include \"base\/memory\/scoped_ptr.h\"\n#include \"base\/message_loop\/message_loop.h\"\n#include \"base\/prefs\/pref_service.h\"\n#include \"base\/prefs\/scoped_user_pref_update.h\"\n#include \"base\/run_loop.h\"\n#include \"base\/strings\/utf_string_conversions.h\"\n#include \"chrome\/browser\/background\/background_contents_service.h\"\n#include \"chrome\/browser\/background\/background_contents_service_factory.h\"\n#include \"chrome\/browser\/chrome_notification_types.h\"\n#include \"chrome\/browser\/tab_contents\/background_contents.h\"\n#include \"chrome\/browser\/ui\/browser_list.h\"\n#include \"chrome\/common\/extensions\/extension_test_util.h\"\n#include \"chrome\/common\/pref_names.h\"\n#include \"chrome\/test\/base\/browser_with_test_window_test.h\"\n#include \"chrome\/test\/base\/testing_browser_process.h\"\n#include \"chrome\/test\/base\/testing_profile.h\"\n#include \"chrome\/test\/base\/testing_profile_manager.h\"\n#include \"content\/public\/browser\/notification_service.h\"\n#include \"content\/public\/test\/test_browser_thread.h\"\n#include \"extensions\/common\/extension.h\"\n#include \"testing\/gtest\/include\/gtest\/gtest.h\"\n#include \"testing\/platform_test.h\"\n#include \"url\/gurl.h\"\n\n#if defined(ENABLE_NOTIFICATIONS)\n#include \"chrome\/browser\/notifications\/message_center_notification_manager.h\"\n#include \"chrome\/browser\/notifications\/notification.h\"\n#include \"ui\/message_center\/fake_message_center_tray_delegate.h\"\n#include \"ui\/message_center\/message_center.h\"\n#include \"ui\/message_center\/message_center_observer.h\"\n#endif\n\nclass BackgroundContentsServiceTest : public testing::Test {\n public:\n BackgroundContentsServiceTest() {}\n virtual ~BackgroundContentsServiceTest() {}\n virtual void SetUp() {\n command_line_.reset(new CommandLine(CommandLine::NO_PROGRAM));\n }\n\n const base::DictionaryValue* GetPrefs(Profile* profile) {\n return profile->GetPrefs()->GetDictionary(\n prefs::kRegisteredBackgroundContents);\n }\n\n \/\/ Returns the stored pref URL for the passed app id.\n std::string GetPrefURLForApp(Profile* profile, const base::string16& appid) {\n const base::DictionaryValue* pref = GetPrefs(profile);\n EXPECT_TRUE(pref->HasKey(base::UTF16ToUTF8(appid)));\n const base::DictionaryValue* value;\n pref->GetDictionaryWithoutPathExpansion(base::UTF16ToUTF8(appid), &value);\n std::string url;\n value->GetString(\"url\", &url);\n return url;\n }\n\n scoped_ptr command_line_;\n};\n\nclass MockBackgroundContents : public BackgroundContents {\n public:\n explicit MockBackgroundContents(Profile* profile)\n : appid_(base::ASCIIToUTF16(\"app_id\")),\n profile_(profile) {\n }\n MockBackgroundContents(Profile* profile, const std::string& id)\n : appid_(base::ASCIIToUTF16(id)),\n profile_(profile) {\n }\n\n void SendOpenedNotification(BackgroundContentsService* service) {\n base::string16 frame_name = base::ASCIIToUTF16(\"background\");\n BackgroundContentsOpenedDetails details = {\n this, frame_name, appid_ };\n service->BackgroundContentsOpened(&details);\n }\n\n virtual void Navigate(GURL url) {\n url_ = url;\n content::NotificationService::current()->Notify(\n chrome::NOTIFICATION_BACKGROUND_CONTENTS_NAVIGATED,\n content::Source(profile_),\n content::Details(this));\n }\n virtual const GURL& GetURL() const OVERRIDE { return url_; }\n\n void MockClose(Profile* profile) {\n content::NotificationService::current()->Notify(\n chrome::NOTIFICATION_BACKGROUND_CONTENTS_CLOSED,\n content::Source(profile),\n content::Details(this));\n delete this;\n }\n\n virtual ~MockBackgroundContents() {\n content::NotificationService::current()->Notify(\n chrome::NOTIFICATION_BACKGROUND_CONTENTS_DELETED,\n content::Source(profile_),\n content::Details(this));\n }\n\n const base::string16& appid() { return appid_; }\n\n private:\n GURL url_;\n\n \/\/ The ID of our parent application\n base::string16 appid_;\n\n \/\/ Parent profile\n Profile* profile_;\n};\n\n#if defined(ENABLE_NOTIFICATIONS)\n\/\/ Wait for the notification created.\nclass NotificationWaiter : public message_center::MessageCenterObserver {\n public:\n explicit NotificationWaiter(const std::string& target_id)\n : target_id_(target_id) {}\n virtual ~NotificationWaiter() {}\n\n void WaitForNotificationAdded() {\n DCHECK(!run_loop_.running());\n message_center::MessageCenter* message_center =\n message_center::MessageCenter::Get();\n if (message_center->HasNotification(target_id_))\n return;\n\n message_center->AddObserver(this);\n run_loop_.Run();\n message_center->RemoveObserver(this);\n }\n\n private:\n \/\/ message_center::MessageCenterObserver overrides:\n virtual void OnNotificationAdded(\n const std::string& notification_id) OVERRIDE {\n if (notification_id == target_id_)\n run_loop_.Quit();\n }\n\n std::string target_id_;\n base::RunLoop run_loop_;\n\n DISALLOW_COPY_AND_ASSIGN(NotificationWaiter);\n};\n\nclass BackgroundContentsServiceNotificationTest\n : public BrowserWithTestWindowTest {\n public:\n BackgroundContentsServiceNotificationTest() {}\n virtual ~BackgroundContentsServiceNotificationTest() {}\n\n \/\/ Overridden from testing::Test\n virtual void SetUp() {\n BrowserWithTestWindowTest::SetUp();\n if (!NotificationUIManager::DelegatesToMessageCenter())\n return;\n\n \/\/ In ChromeOS environment, BrowserWithTestWindowTest initializes\n \/\/ MessageCenter.\n#if !defined(OS_CHROMEOS)\n message_center::MessageCenter::Initialize();\n#endif\n profile_manager_.reset(new TestingProfileManager(\n TestingBrowserProcess::GetGlobal()));\n ASSERT_TRUE(profile_manager_->SetUp());\n MessageCenterNotificationManager* manager =\n static_cast(\n g_browser_process->notification_ui_manager());\n manager->SetMessageCenterTrayDelegateForTest(\n new message_center::FakeMessageCenterTrayDelegate(\n message_center::MessageCenter::Get(), base::Closure()));\n }\n\n virtual void TearDown() {\n g_browser_process->notification_ui_manager()->CancelAll();\n profile_manager_.reset();\n#if !defined(OS_CHROMEOS)\n message_center::MessageCenter::Shutdown();\n#endif\n BrowserWithTestWindowTest::TearDown();\n }\n\n protected:\n \/\/ Creates crash notification for the specified extension and returns\n \/\/ the created one.\n const Notification* CreateCrashNotification(\n scoped_refptr extension) {\n std::string notification_id =\n BackgroundContentsService::GetNotificationIdForExtensionForTesting(\n extension->id());\n NotificationWaiter waiter(notification_id);\n BackgroundContentsService::ShowBalloonForTesting(\n extension.get(), profile());\n waiter.WaitForNotificationAdded();\n\n return g_browser_process->notification_ui_manager()->FindById(\n notification_id);\n }\n\n private:\n scoped_ptr profile_manager_;\n\n DISALLOW_COPY_AND_ASSIGN(BackgroundContentsServiceNotificationTest);\n};\n#endif \/\/ ENABLE_NOTIFICATIONS\n\nTEST_F(BackgroundContentsServiceTest, Create) {\n \/\/ Check for creation and leaks.\n TestingProfile profile;\n BackgroundContentsService service(&profile, command_line_.get());\n}\n\nTEST_F(BackgroundContentsServiceTest, BackgroundContentsCreateDestroy) {\n TestingProfile profile;\n BackgroundContentsService service(&profile, command_line_.get());\n MockBackgroundContents* contents = new MockBackgroundContents(&profile);\n EXPECT_FALSE(service.IsTracked(contents));\n contents->SendOpenedNotification(&service);\n EXPECT_TRUE(service.IsTracked(contents));\n delete contents;\n EXPECT_FALSE(service.IsTracked(contents));\n}\n\nTEST_F(BackgroundContentsServiceTest, BackgroundContentsUrlAdded) {\n TestingProfile profile;\n BackgroundContentsService service(&profile, command_line_.get());\n BackgroundContentsServiceFactory::GetInstance()->\n RegisterUserPrefsOnBrowserContextForTest(&profile);\n GURL orig_url;\n GURL url(\"http:\/\/a\/\");\n GURL url2(\"http:\/\/a\/\");\n {\n scoped_ptr contents(\n new MockBackgroundContents(&profile));\n EXPECT_EQ(0U, GetPrefs(&profile)->size());\n contents->SendOpenedNotification(&service);\n\n contents->Navigate(url);\n EXPECT_EQ(1U, GetPrefs(&profile)->size());\n EXPECT_EQ(url.spec(), GetPrefURLForApp(&profile, contents->appid()));\n\n \/\/ Navigate the contents to a new url, should not change url.\n contents->Navigate(url2);\n EXPECT_EQ(1U, GetPrefs(&profile)->size());\n EXPECT_EQ(url.spec(), GetPrefURLForApp(&profile, contents->appid()));\n }\n \/\/ Contents are deleted, url should persist.\n EXPECT_EQ(1U, GetPrefs(&profile)->size());\n}\n\nTEST_F(BackgroundContentsServiceTest, BackgroundContentsUrlAddedAndClosed) {\n TestingProfile profile;\n BackgroundContentsService service(&profile, command_line_.get());\n BackgroundContentsServiceFactory::GetInstance()->\n RegisterUserPrefsOnBrowserContextForTest(&profile);\n\n GURL url(\"http:\/\/a\/\");\n MockBackgroundContents* contents = new MockBackgroundContents(&profile);\n EXPECT_EQ(0U, GetPrefs(&profile)->size());\n contents->SendOpenedNotification(&service);\n contents->Navigate(url);\n EXPECT_EQ(1U, GetPrefs(&profile)->size());\n EXPECT_EQ(url.spec(), GetPrefURLForApp(&profile, contents->appid()));\n\n \/\/ Fake a window closed by script.\n contents->MockClose(&profile);\n EXPECT_EQ(0U, GetPrefs(&profile)->size());\n}\n\n\/\/ Test what happens if a BackgroundContents shuts down (say, due to a renderer\n\/\/ crash) then is restarted. Should not persist URL twice.\nTEST_F(BackgroundContentsServiceTest, RestartBackgroundContents) {\n TestingProfile profile;\n BackgroundContentsService service(&profile, command_line_.get());\n BackgroundContentsServiceFactory::GetInstance()->\n RegisterUserPrefsOnBrowserContextForTest(&profile);\n\n GURL url(\"http:\/\/a\/\");\n {\n scoped_ptr contents(new MockBackgroundContents(\n &profile, \"appid\"));\n contents->SendOpenedNotification(&service);\n contents->Navigate(url);\n EXPECT_EQ(1U, GetPrefs(&profile)->size());\n EXPECT_EQ(url.spec(), GetPrefURLForApp(&profile, contents->appid()));\n }\n \/\/ Contents deleted, url should be persisted.\n EXPECT_EQ(1U, GetPrefs(&profile)->size());\n\n {\n \/\/ Reopen the BackgroundContents to the same URL, we should not register the\n \/\/ URL again.\n scoped_ptr contents(new MockBackgroundContents(\n &profile, \"appid\"));\n contents->SendOpenedNotification(&service);\n contents->Navigate(url);\n EXPECT_EQ(1U, GetPrefs(&profile)->size());\n }\n}\n\n\/\/ Ensures that BackgroundContentsService properly tracks the association\n\/\/ between a BackgroundContents and its parent extension, including\n\/\/ unregistering the BC when the extension is uninstalled.\nTEST_F(BackgroundContentsServiceTest, TestApplicationIDLinkage) {\n TestingProfile profile;\n BackgroundContentsService service(&profile, command_line_.get());\n BackgroundContentsServiceFactory::GetInstance()->\n RegisterUserPrefsOnBrowserContextForTest(&profile);\n\n EXPECT_EQ(NULL,\n service.GetAppBackgroundContents(base::ASCIIToUTF16(\"appid\")));\n MockBackgroundContents* contents = new MockBackgroundContents(&profile,\n \"appid\");\n scoped_ptr contents2(\n new MockBackgroundContents(&profile, \"appid2\"));\n contents->SendOpenedNotification(&service);\n EXPECT_EQ(contents, service.GetAppBackgroundContents(contents->appid()));\n contents2->SendOpenedNotification(&service);\n EXPECT_EQ(contents2.get(), service.GetAppBackgroundContents(\n contents2->appid()));\n EXPECT_EQ(0U, GetPrefs(&profile)->size());\n\n \/\/ Navigate the contents, then make sure the one associated with the extension\n \/\/ is unregistered.\n GURL url(\"http:\/\/a\/\");\n GURL url2(\"http:\/\/b\/\");\n contents->Navigate(url);\n EXPECT_EQ(1U, GetPrefs(&profile)->size());\n contents2->Navigate(url2);\n EXPECT_EQ(2U, GetPrefs(&profile)->size());\n service.ShutdownAssociatedBackgroundContents(base::ASCIIToUTF16(\"appid\"));\n EXPECT_FALSE(service.IsTracked(contents));\n EXPECT_EQ(NULL,\n service.GetAppBackgroundContents(base::ASCIIToUTF16(\"appid\")));\n EXPECT_EQ(1U, GetPrefs(&profile)->size());\n EXPECT_EQ(url2.spec(), GetPrefURLForApp(&profile, contents2->appid()));\n}\n\n#if defined(ENABLE_NOTIFICATIONS)\nTEST_F(BackgroundContentsServiceNotificationTest, TestShowBalloon) {\n if (!NotificationUIManager::DelegatesToMessageCenter())\n return;\n\n scoped_refptr extension =\n extension_test_util::LoadManifest(\"image_loading_tracker\", \"app.json\");\n ASSERT_TRUE(extension.get());\n ASSERT_TRUE(extension->GetManifestData(\"icons\"));\n\n const Notification* notification = CreateCrashNotification(extension);\n EXPECT_FALSE(notification->icon().IsEmpty());\n}\n\n\/\/ Verify if a test notification can show the default extension icon for\n\/\/ a crash notification for an extension without icon.\nTEST_F(BackgroundContentsServiceNotificationTest, TestShowBalloonNoIcon) {\n if (!NotificationUIManager::DelegatesToMessageCenter())\n return;\n\n \/\/ Extension manifest file with no 'icon' field.\n scoped_refptr extension =\n extension_test_util::LoadManifest(\"app\", \"manifest.json\");\n ASSERT_TRUE(extension.get());\n ASSERT_FALSE(extension->GetManifestData(\"icons\"));\n\n const Notification* notification = CreateCrashNotification(extension);\n EXPECT_FALSE(notification->icon().IsEmpty());\n}\n#endif\nDisable BackgroundContentsServiceNotificationTest for Linux-Gtk.\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \n\n#include \"base\/basictypes.h\"\n#include \"base\/command_line.h\"\n#include \"base\/memory\/scoped_ptr.h\"\n#include \"base\/message_loop\/message_loop.h\"\n#include \"base\/prefs\/pref_service.h\"\n#include \"base\/prefs\/scoped_user_pref_update.h\"\n#include \"base\/run_loop.h\"\n#include \"base\/strings\/utf_string_conversions.h\"\n#include \"chrome\/browser\/background\/background_contents_service.h\"\n#include \"chrome\/browser\/background\/background_contents_service_factory.h\"\n#include \"chrome\/browser\/chrome_notification_types.h\"\n#include \"chrome\/browser\/tab_contents\/background_contents.h\"\n#include \"chrome\/browser\/ui\/browser_list.h\"\n#include \"chrome\/common\/extensions\/extension_test_util.h\"\n#include \"chrome\/common\/pref_names.h\"\n#include \"chrome\/test\/base\/browser_with_test_window_test.h\"\n#include \"chrome\/test\/base\/testing_browser_process.h\"\n#include \"chrome\/test\/base\/testing_profile.h\"\n#include \"chrome\/test\/base\/testing_profile_manager.h\"\n#include \"content\/public\/browser\/notification_service.h\"\n#include \"content\/public\/test\/test_browser_thread.h\"\n#include \"extensions\/common\/extension.h\"\n#include \"testing\/gtest\/include\/gtest\/gtest.h\"\n#include \"testing\/platform_test.h\"\n#include \"url\/gurl.h\"\n\n#if defined(ENABLE_NOTIFICATIONS)\n#include \"chrome\/browser\/notifications\/message_center_notification_manager.h\"\n#include \"chrome\/browser\/notifications\/notification.h\"\n#include \"ui\/message_center\/fake_message_center_tray_delegate.h\"\n#include \"ui\/message_center\/message_center.h\"\n#include \"ui\/message_center\/message_center_observer.h\"\n#endif\n\nclass BackgroundContentsServiceTest : public testing::Test {\n public:\n BackgroundContentsServiceTest() {}\n virtual ~BackgroundContentsServiceTest() {}\n virtual void SetUp() {\n command_line_.reset(new CommandLine(CommandLine::NO_PROGRAM));\n }\n\n const base::DictionaryValue* GetPrefs(Profile* profile) {\n return profile->GetPrefs()->GetDictionary(\n prefs::kRegisteredBackgroundContents);\n }\n\n \/\/ Returns the stored pref URL for the passed app id.\n std::string GetPrefURLForApp(Profile* profile, const base::string16& appid) {\n const base::DictionaryValue* pref = GetPrefs(profile);\n EXPECT_TRUE(pref->HasKey(base::UTF16ToUTF8(appid)));\n const base::DictionaryValue* value;\n pref->GetDictionaryWithoutPathExpansion(base::UTF16ToUTF8(appid), &value);\n std::string url;\n value->GetString(\"url\", &url);\n return url;\n }\n\n scoped_ptr command_line_;\n};\n\nclass MockBackgroundContents : public BackgroundContents {\n public:\n explicit MockBackgroundContents(Profile* profile)\n : appid_(base::ASCIIToUTF16(\"app_id\")),\n profile_(profile) {\n }\n MockBackgroundContents(Profile* profile, const std::string& id)\n : appid_(base::ASCIIToUTF16(id)),\n profile_(profile) {\n }\n\n void SendOpenedNotification(BackgroundContentsService* service) {\n base::string16 frame_name = base::ASCIIToUTF16(\"background\");\n BackgroundContentsOpenedDetails details = {\n this, frame_name, appid_ };\n service->BackgroundContentsOpened(&details);\n }\n\n virtual void Navigate(GURL url) {\n url_ = url;\n content::NotificationService::current()->Notify(\n chrome::NOTIFICATION_BACKGROUND_CONTENTS_NAVIGATED,\n content::Source(profile_),\n content::Details(this));\n }\n virtual const GURL& GetURL() const OVERRIDE { return url_; }\n\n void MockClose(Profile* profile) {\n content::NotificationService::current()->Notify(\n chrome::NOTIFICATION_BACKGROUND_CONTENTS_CLOSED,\n content::Source(profile),\n content::Details(this));\n delete this;\n }\n\n virtual ~MockBackgroundContents() {\n content::NotificationService::current()->Notify(\n chrome::NOTIFICATION_BACKGROUND_CONTENTS_DELETED,\n content::Source(profile_),\n content::Details(this));\n }\n\n const base::string16& appid() { return appid_; }\n\n private:\n GURL url_;\n\n \/\/ The ID of our parent application\n base::string16 appid_;\n\n \/\/ Parent profile\n Profile* profile_;\n};\n\n#if defined(ENABLE_NOTIFICATIONS) && !defined(TOOLKIT_GTK)\n\/\/ Wait for the notification created.\nclass NotificationWaiter : public message_center::MessageCenterObserver {\n public:\n explicit NotificationWaiter(const std::string& target_id)\n : target_id_(target_id) {}\n virtual ~NotificationWaiter() {}\n\n void WaitForNotificationAdded() {\n DCHECK(!run_loop_.running());\n message_center::MessageCenter* message_center =\n message_center::MessageCenter::Get();\n if (message_center->HasNotification(target_id_))\n return;\n\n message_center->AddObserver(this);\n run_loop_.Run();\n message_center->RemoveObserver(this);\n }\n\n private:\n \/\/ message_center::MessageCenterObserver overrides:\n virtual void OnNotificationAdded(\n const std::string& notification_id) OVERRIDE {\n if (notification_id == target_id_)\n run_loop_.Quit();\n }\n\n std::string target_id_;\n base::RunLoop run_loop_;\n\n DISALLOW_COPY_AND_ASSIGN(NotificationWaiter);\n};\n\nclass BackgroundContentsServiceNotificationTest\n : public BrowserWithTestWindowTest {\n public:\n BackgroundContentsServiceNotificationTest() {}\n virtual ~BackgroundContentsServiceNotificationTest() {}\n\n \/\/ Overridden from testing::Test\n virtual void SetUp() {\n BrowserWithTestWindowTest::SetUp();\n if (!NotificationUIManager::DelegatesToMessageCenter())\n return;\n\n \/\/ In ChromeOS environment, BrowserWithTestWindowTest initializes\n \/\/ MessageCenter.\n#if !defined(OS_CHROMEOS)\n message_center::MessageCenter::Initialize();\n#endif\n profile_manager_.reset(new TestingProfileManager(\n TestingBrowserProcess::GetGlobal()));\n ASSERT_TRUE(profile_manager_->SetUp());\n MessageCenterNotificationManager* manager =\n static_cast(\n g_browser_process->notification_ui_manager());\n manager->SetMessageCenterTrayDelegateForTest(\n new message_center::FakeMessageCenterTrayDelegate(\n message_center::MessageCenter::Get(), base::Closure()));\n }\n\n virtual void TearDown() {\n g_browser_process->notification_ui_manager()->CancelAll();\n profile_manager_.reset();\n#if !defined(OS_CHROMEOS)\n message_center::MessageCenter::Shutdown();\n#endif\n BrowserWithTestWindowTest::TearDown();\n }\n\n protected:\n \/\/ Creates crash notification for the specified extension and returns\n \/\/ the created one.\n const Notification* CreateCrashNotification(\n scoped_refptr extension) {\n std::string notification_id =\n BackgroundContentsService::GetNotificationIdForExtensionForTesting(\n extension->id());\n NotificationWaiter waiter(notification_id);\n BackgroundContentsService::ShowBalloonForTesting(\n extension.get(), profile());\n waiter.WaitForNotificationAdded();\n\n return g_browser_process->notification_ui_manager()->FindById(\n notification_id);\n }\n\n private:\n scoped_ptr profile_manager_;\n\n DISALLOW_COPY_AND_ASSIGN(BackgroundContentsServiceNotificationTest);\n};\n#endif \/\/ ENABLE_NOTIFICATIONS\n\nTEST_F(BackgroundContentsServiceTest, Create) {\n \/\/ Check for creation and leaks.\n TestingProfile profile;\n BackgroundContentsService service(&profile, command_line_.get());\n}\n\nTEST_F(BackgroundContentsServiceTest, BackgroundContentsCreateDestroy) {\n TestingProfile profile;\n BackgroundContentsService service(&profile, command_line_.get());\n MockBackgroundContents* contents = new MockBackgroundContents(&profile);\n EXPECT_FALSE(service.IsTracked(contents));\n contents->SendOpenedNotification(&service);\n EXPECT_TRUE(service.IsTracked(contents));\n delete contents;\n EXPECT_FALSE(service.IsTracked(contents));\n}\n\nTEST_F(BackgroundContentsServiceTest, BackgroundContentsUrlAdded) {\n TestingProfile profile;\n BackgroundContentsService service(&profile, command_line_.get());\n BackgroundContentsServiceFactory::GetInstance()->\n RegisterUserPrefsOnBrowserContextForTest(&profile);\n GURL orig_url;\n GURL url(\"http:\/\/a\/\");\n GURL url2(\"http:\/\/a\/\");\n {\n scoped_ptr contents(\n new MockBackgroundContents(&profile));\n EXPECT_EQ(0U, GetPrefs(&profile)->size());\n contents->SendOpenedNotification(&service);\n\n contents->Navigate(url);\n EXPECT_EQ(1U, GetPrefs(&profile)->size());\n EXPECT_EQ(url.spec(), GetPrefURLForApp(&profile, contents->appid()));\n\n \/\/ Navigate the contents to a new url, should not change url.\n contents->Navigate(url2);\n EXPECT_EQ(1U, GetPrefs(&profile)->size());\n EXPECT_EQ(url.spec(), GetPrefURLForApp(&profile, contents->appid()));\n }\n \/\/ Contents are deleted, url should persist.\n EXPECT_EQ(1U, GetPrefs(&profile)->size());\n}\n\nTEST_F(BackgroundContentsServiceTest, BackgroundContentsUrlAddedAndClosed) {\n TestingProfile profile;\n BackgroundContentsService service(&profile, command_line_.get());\n BackgroundContentsServiceFactory::GetInstance()->\n RegisterUserPrefsOnBrowserContextForTest(&profile);\n\n GURL url(\"http:\/\/a\/\");\n MockBackgroundContents* contents = new MockBackgroundContents(&profile);\n EXPECT_EQ(0U, GetPrefs(&profile)->size());\n contents->SendOpenedNotification(&service);\n contents->Navigate(url);\n EXPECT_EQ(1U, GetPrefs(&profile)->size());\n EXPECT_EQ(url.spec(), GetPrefURLForApp(&profile, contents->appid()));\n\n \/\/ Fake a window closed by script.\n contents->MockClose(&profile);\n EXPECT_EQ(0U, GetPrefs(&profile)->size());\n}\n\n\/\/ Test what happens if a BackgroundContents shuts down (say, due to a renderer\n\/\/ crash) then is restarted. Should not persist URL twice.\nTEST_F(BackgroundContentsServiceTest, RestartBackgroundContents) {\n TestingProfile profile;\n BackgroundContentsService service(&profile, command_line_.get());\n BackgroundContentsServiceFactory::GetInstance()->\n RegisterUserPrefsOnBrowserContextForTest(&profile);\n\n GURL url(\"http:\/\/a\/\");\n {\n scoped_ptr contents(new MockBackgroundContents(\n &profile, \"appid\"));\n contents->SendOpenedNotification(&service);\n contents->Navigate(url);\n EXPECT_EQ(1U, GetPrefs(&profile)->size());\n EXPECT_EQ(url.spec(), GetPrefURLForApp(&profile, contents->appid()));\n }\n \/\/ Contents deleted, url should be persisted.\n EXPECT_EQ(1U, GetPrefs(&profile)->size());\n\n {\n \/\/ Reopen the BackgroundContents to the same URL, we should not register the\n \/\/ URL again.\n scoped_ptr contents(new MockBackgroundContents(\n &profile, \"appid\"));\n contents->SendOpenedNotification(&service);\n contents->Navigate(url);\n EXPECT_EQ(1U, GetPrefs(&profile)->size());\n }\n}\n\n\/\/ Ensures that BackgroundContentsService properly tracks the association\n\/\/ between a BackgroundContents and its parent extension, including\n\/\/ unregistering the BC when the extension is uninstalled.\nTEST_F(BackgroundContentsServiceTest, TestApplicationIDLinkage) {\n TestingProfile profile;\n BackgroundContentsService service(&profile, command_line_.get());\n BackgroundContentsServiceFactory::GetInstance()->\n RegisterUserPrefsOnBrowserContextForTest(&profile);\n\n EXPECT_EQ(NULL,\n service.GetAppBackgroundContents(base::ASCIIToUTF16(\"appid\")));\n MockBackgroundContents* contents = new MockBackgroundContents(&profile,\n \"appid\");\n scoped_ptr contents2(\n new MockBackgroundContents(&profile, \"appid2\"));\n contents->SendOpenedNotification(&service);\n EXPECT_EQ(contents, service.GetAppBackgroundContents(contents->appid()));\n contents2->SendOpenedNotification(&service);\n EXPECT_EQ(contents2.get(), service.GetAppBackgroundContents(\n contents2->appid()));\n EXPECT_EQ(0U, GetPrefs(&profile)->size());\n\n \/\/ Navigate the contents, then make sure the one associated with the extension\n \/\/ is unregistered.\n GURL url(\"http:\/\/a\/\");\n GURL url2(\"http:\/\/b\/\");\n contents->Navigate(url);\n EXPECT_EQ(1U, GetPrefs(&profile)->size());\n contents2->Navigate(url2);\n EXPECT_EQ(2U, GetPrefs(&profile)->size());\n service.ShutdownAssociatedBackgroundContents(base::ASCIIToUTF16(\"appid\"));\n EXPECT_FALSE(service.IsTracked(contents));\n EXPECT_EQ(NULL,\n service.GetAppBackgroundContents(base::ASCIIToUTF16(\"appid\")));\n EXPECT_EQ(1U, GetPrefs(&profile)->size());\n EXPECT_EQ(url2.spec(), GetPrefURLForApp(&profile, contents2->appid()));\n}\n\n#if defined(ENABLE_NOTIFICATIONS) && !defined(TOOLKIT_GTK)\nTEST_F(BackgroundContentsServiceNotificationTest, TestShowBalloon) {\n if (!NotificationUIManager::DelegatesToMessageCenter())\n return;\n\n scoped_refptr extension =\n extension_test_util::LoadManifest(\"image_loading_tracker\", \"app.json\");\n ASSERT_TRUE(extension.get());\n ASSERT_TRUE(extension->GetManifestData(\"icons\"));\n\n const Notification* notification = CreateCrashNotification(extension);\n EXPECT_FALSE(notification->icon().IsEmpty());\n}\n\n\/\/ Verify if a test notification can show the default extension icon for\n\/\/ a crash notification for an extension without icon.\nTEST_F(BackgroundContentsServiceNotificationTest, TestShowBalloonNoIcon) {\n if (!NotificationUIManager::DelegatesToMessageCenter())\n return;\n\n \/\/ Extension manifest file with no 'icon' field.\n scoped_refptr extension =\n extension_test_util::LoadManifest(\"app\", \"manifest.json\");\n ASSERT_TRUE(extension.get());\n ASSERT_FALSE(extension->GetManifestData(\"icons\"));\n\n const Notification* notification = CreateCrashNotification(extension);\n EXPECT_FALSE(notification->icon().IsEmpty());\n}\n#endif\n<|endoftext|>"} {"text":"inline\ncov_mat_kth::cov_mat_kth( const std::string in_path,\n\t\t\t const std::string in_actionNames, \n\t\t\t const int in_scale_factor, \n\t\t\t const int in_shift,\n\t\t\t const int in_scene, \/\/only for kth\n\t\t\t const int in_segment_length\n)\n:path(in_path), actionNames(in_actionNames), scale_factor(in_scale_factor), shift(in_shift), scene(in_scene), segment_length(in_segment_length)\n{\n actions.load( actionNames ); \n}\n\n\ninline\nvoid\ncov_mat_kth::calculate( field all_people, int in_dim )\n{\n dim = in_dim;\n int n_actions = actions.n_rows;\n int n_peo = all_people.n_rows;\n \/\/all_people.print(\"people\");\n \n for (int sc = 1; sc<=1; ++sc) \/\/scene\n {\n for (int pe = 0; pe< n_peo; ++pe)\n {\n for (int act=0; act stat_seg(true);\n int k =0;\n\n\n for (int j=l; j more_stats(true);\n\nfor(uword i=0; i<20; ++i)\n {\n sample = randu(3);\n \n sample(1) -= sample(0);\n sample(2) += sample(1);\n \n more_stats(sample);\n }*\/First tryinline\ncov_mat_kth::cov_mat_kth( const std::string in_path,\n\t\t\t const std::string in_actionNames, \n\t\t\t const int in_scale_factor, \n\t\t\t const int in_shift,\n\t\t\t const int in_scene, \/\/only for kth\n\t\t\t const int in_segment_length\n)\n:path(in_path), actionNames(in_actionNames), scale_factor(in_scale_factor), shift(in_shift), scene(in_scene), segment_length(in_segment_length)\n{\n actions.load( actionNames ); \n}\n\n\ninline\nvoid\ncov_mat_kth::calculate( field all_people, int in_dim )\n{\n dim = in_dim;\n int n_actions = actions.n_rows;\n int n_peo = all_people.n_rows;\n \/\/all_people.print(\"people\");\n \n for (int sc = 1; sc<=1; ++sc) \/\/scene\n {\n for (int pe = 0; pe< n_peo; ++pe)\n {\n for (int act=0; act stat_seg(true);\n int k =0;\n\n\n for (int j=l; j more_stats(true);\n\nfor(uword i=0; i<20; ++i)\n {\n sample = randu(3);\n \n sample(1) -= sample(0);\n sample(2) += sample(1);\n \n more_stats(sample);\n }*\/<|endoftext|>"} {"text":"inline\ncov_mat_kth::cov_mat_kth( const std::string in_path,\n\t\t\t const std::string in_actionNames, \n\t\t\t const int in_scale_factor, \n\t\t\t const int in_shift,\n\t\t\t const int in_scene, \/\/only for kth\n\t\t\t const int in_segment_length\n)\n:path(in_path), actionNames(in_actionNames), scale_factor(in_scale_factor), shift(in_shift), scene(in_scene), segment_length(in_segment_length)\n{\n actions.load( actionNames ); \n}\n\n\ninline\nvoid\ncov_mat_kth::calculate( field in_all_people, int in_dim )\n{\n all_people = in_all_people;\n dim = in_dim;\n int n_actions = actions.n_rows;\n int n_peo = all_people.n_rows;\n \/\/all_people.print(\"people\");\n \n for (int sc = 1; sc<=1; ++sc) \/\/scene\n {\n for (int pe = 0; pe< n_peo; ++pe)\n {\n for (int act=0; act stat_seg(true);\n \/\/int k =0;\n \n \/\/cout << \" \" << l;\n \n \n for (int j=l; j<=segment_length+1; ++j)\n {\n \/\/k++;\n cout << \" \" << j;\n uvec indices = find(lab_video_i == j);\n mat tmp_feat = mat_features_video_i.cols(indices);\n \/\/cout << \"row&col \" << tmp_feat.n_rows << \" & \" << tmp_feat.n_cols << endl;\n for (int v=0; v < tmp_feat.n_cols; ++v)\n {\n\tvec sample = tmp_feat.col(v);\n\tstat_seg (sample);\n\t\n }\n \n \n }\n \n \n cout << \" \" << stat_seg.count();\n std::stringstream save_cov_seg;\n save_cov_seg << save_folder.str() << \"\/cov_seg\" << s << \"_\"<< all_people (pe) << \"_\" << actions(act) << \"_dim\" << dim << \".h5\";\n \n double THRESH = 0.000001;\n mat cov_seg_i = stat_seg.cov();\n \n \/\/Following Mehrtash suggestions as per email dated June26th 2014\n cov_seg_i = 0.5*(cov_seg_i + cov_seg_i.t());\n vec D;\n mat V;\n eig_sym(D, V, cov_seg_i);\n uvec q1 = find(D < THRESH);\n \n if (q1.n_elem>0)\n {\n for (uword pos = 0; pos < q1.n_elem; ++pos)\n {\n\tD( q1(pos) ) = THRESH;\n\t\n }\n \n cov_seg_i = V*diagmat(D)*V.t(); \n \n } \n \n \/\/end suggestion\n \n \n cov_seg_i.save( save_cov_seg.str(), hdf5_binary ); \n \n \n s++;\n \n \n }\n \n \n std::stringstream save_seg;\n vec total_seg; \n total_seg.zeros(1);\n total_seg( 0 ) = s;\n save_seg << save_folder.str() << \"\/num_seg_\"<< all_people (pe) << \"_\" << actions(act) << \"_dim\" << dim << \".dat\";\n total_seg.save( save_seg.str(), raw_ascii );\n cout << \"press a key \" ;\n getchar();\n \n}\n\n\nAnother bug buuuuuu :( inline\ncov_mat_kth::cov_mat_kth( const std::string in_path,\n\t\t\t const std::string in_actionNames, \n\t\t\t const int in_scale_factor, \n\t\t\t const int in_shift,\n\t\t\t const int in_scene, \/\/only for kth\n\t\t\t const int in_segment_length\n)\n:path(in_path), actionNames(in_actionNames), scale_factor(in_scale_factor), shift(in_shift), scene(in_scene), segment_length(in_segment_length)\n{\n actions.load( actionNames ); \n}\n\n\ninline\nvoid\ncov_mat_kth::calculate( field in_all_people, int in_dim )\n{\n all_people = in_all_people;\n dim = in_dim;\n int n_actions = actions.n_rows;\n int n_peo = all_people.n_rows;\n \/\/all_people.print(\"people\");\n \n for (int sc = 1; sc<=1; ++sc) \/\/scene\n {\n for (int pe = 0; pe< n_peo; ++pe)\n {\n for (int act=0; act stat_seg(true);\n \/\/int k =0;\n \n \/\/cout << \" \" << l;\n \n \n for (int j=l; j<=segment_length+1; ++j)\n {\n \/\/k++;\n cout << \" \" << j;\n uvec indices = find(lab_video_i == j);\n mat tmp_feat = mat_features_video_i.cols(indices);\n \/\/cout << \"row&col \" << tmp_feat.n_rows << \" & \" << tmp_feat.n_cols << endl;\n for (int v=0; v < tmp_feat.n_cols; ++v)\n {\n\tvec sample = tmp_feat.col(v);\n\tstat_seg (sample);\n\t\n }\n \n \n }\n \n cout << endl;\n cout << \" \" << stat_seg.count();\n std::stringstream save_cov_seg;\n save_cov_seg << save_folder.str() << \"\/cov_seg\" << s << \"_\"<< all_people (pe) << \"_\" << actions(act) << \"_dim\" << dim << \".h5\";\n \n double THRESH = 0.000001;\n mat cov_seg_i = stat_seg.cov();\n \n \/\/Following Mehrtash suggestions as per email dated June26th 2014\n cov_seg_i = 0.5*(cov_seg_i + cov_seg_i.t());\n vec D;\n mat V;\n eig_sym(D, V, cov_seg_i);\n uvec q1 = find(D < THRESH);\n \n if (q1.n_elem>0)\n {\n for (uword pos = 0; pos < q1.n_elem; ++pos)\n {\n\tD( q1(pos) ) = THRESH;\n\t\n }\n \n cov_seg_i = V*diagmat(D)*V.t(); \n \n } \n \n \/\/end suggestion\n \n \n cov_seg_i.save( save_cov_seg.str(), hdf5_binary ); \n \n \n s++;\n \n \n }\n \n \n std::stringstream save_seg;\n vec total_seg; \n total_seg.zeros(1);\n total_seg( 0 ) = s;\n save_seg << save_folder.str() << \"\/num_seg_\"<< all_people (pe) << \"_\" << actions(act) << \"_dim\" << dim << \".dat\";\n total_seg.save( save_seg.str(), raw_ascii );\n cout << \"press a key \" ;\n getchar();\n \n}\n\n\n<|endoftext|>"} {"text":"\/\/ Copyright Toru Niina 2017.\n\/\/ Distributed under the MIT License.\n#ifndef TOML11_REGION_HPP\n#define TOML11_REGION_HPP\n#include \"exception.hpp\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace toml\n{\nnamespace detail\n{\n\n\/\/ helper function to avoid std::string(0, 'c') or std::string(iter, iter)\ntemplate\nstd::string make_string(Iterator first, Iterator last)\n{\n if(first == last) {return \"\";}\n return std::string(first, last);\n}\ninline std::string make_string(std::size_t len, char c)\n{\n if(len == 0) {return \"\";}\n return std::string(len, c);\n}\n\n\/\/ region_base is a base class of location and region that are defined below.\n\/\/ it will be used to generate better error messages.\nstruct region_base\n{\n region_base() = default;\n virtual ~region_base() = default;\n region_base(const region_base&) = default;\n region_base(region_base&& ) = default;\n region_base& operator=(const region_base&) = default;\n region_base& operator=(region_base&& ) = default;\n\n virtual bool is_ok() const noexcept {return false;}\n\n virtual std::string str() const {return std::string(\"unknown region\");}\n virtual std::string name() const {return std::string(\"unknown file\");}\n virtual std::string line() const {return std::string(\"unknown line\");}\n virtual std::string line_num() const {return std::string(\"?\");}\n\n \/\/ length of the region\n virtual std::size_t size() const noexcept {return 0;}\n \/\/ number of characters in the line before the region\n virtual std::size_t before() const noexcept {return 0;}\n \/\/ number of characters in the line after the region\n virtual std::size_t after() const noexcept {return 0;}\n\n virtual std::string comment_before() const {return \"\";} \/\/ just before\n virtual std::string comment_inline() const {return \"\";} \/\/ in the same line\n virtual std::string comment() const {return \"\";} \/\/ concatenate\n \/\/ ```toml\n \/\/ # comment_before\n \/\/ key = \"value\" # comment_inline\n \/\/ ```\n};\n\n\/\/ location represents a position in a container, which contains a file content.\n\/\/ it can be considered as a region that contains only one character.\n\/\/\n\/\/ it contains pointer to the file content and iterator that points the current\n\/\/ location.\ntemplate\nstruct location final : public region_base\n{\n using const_iterator = typename Container::const_iterator;\n using source_ptr = std::shared_ptr;\n\n static_assert(std::is_same::value,\"\");\n static_assert(std::is_same::iterator_category>::value,\n \"container should be randomly accessible\");\n\n location(std::string name, Container cont)\n : source_(std::make_shared(std::move(cont))), line_number_(1),\n source_name_(std::move(name)), iter_(source_->cbegin())\n {}\n location(const location&) = default;\n location(location&&) = default;\n location& operator=(const location&) = default;\n location& operator=(location&&) = default;\n ~location() = default;\n\n bool is_ok() const noexcept override {return static_cast(source_);}\n\n \/\/ this const prohibits codes like `++(loc.iter())`.\n const const_iterator iter() const noexcept {return iter_;}\n\n const_iterator begin() const noexcept {return source_->cbegin();}\n const_iterator end() const noexcept {return source_->cend();}\n\n \/\/ XXX `location::line_num()` used to be implemented using `std::count` to\n \/\/ count a number of '\\n'. But with a long toml file (typically, 10k lines),\n \/\/ it becomes intolerably slow because each time it generates error messages,\n \/\/ it counts '\\n' from thousands of characters. To workaround it, I decided\n \/\/ to introduce `location::line_number_` member variable and synchronize it\n \/\/ to the location changes the point to look. So an overload of `iter()`\n \/\/ which returns mutable reference is removed and `advance()`, `retrace()`\n \/\/ and `reset()` is added.\n void advance(std::size_t n = 1) noexcept\n {\n this->line_number_ += std::count(this->iter_, this->iter_ + n, '\\n');\n this->iter_ += n;\n return;\n }\n void retrace(std::size_t n = 1) noexcept\n {\n this->line_number_ -= std::count(this->iter_ - n, this->iter_, '\\n');\n this->iter_ -= n;\n return;\n }\n void reset(const_iterator rollback) noexcept\n {\n \/\/ since c++11, std::distance works in both ways for random-access\n \/\/ iterators and returns a negative value if `first > last`.\n if(0 <= std::distance(rollback, this->iter_)) \/\/ rollback < iter\n {\n this->line_number_ -= std::count(rollback, this->iter_, '\\n');\n }\n else \/\/ iter < rollback [[unlikely]]\n {\n this->line_number_ += std::count(this->iter_, rollback, '\\n');\n }\n this->iter_ = rollback;\n return;\n }\n\n std::string str() const override {return make_string(1, *this->iter());}\n std::string name() const override {return source_name_;}\n\n std::string line_num() const override\n {\n return std::to_string(this->line_number_);\n }\n\n std::string line() const override\n {\n return make_string(this->line_begin(), this->line_end());\n }\n\n const_iterator line_begin() const noexcept\n {\n using reverse_iterator = std::reverse_iterator;\n return std::find(reverse_iterator(this->iter()),\n reverse_iterator(this->begin()), '\\n').base();\n }\n const_iterator line_end() const noexcept\n {\n return std::find(this->iter(), this->end(), '\\n');\n }\n\n \/\/ location is always points a character. so the size is 1.\n std::size_t size() const noexcept override\n {\n return 1u;\n }\n std::size_t before() const noexcept override\n {\n return std::distance(this->line_begin(), this->iter());\n }\n std::size_t after() const noexcept override\n {\n return std::distance(this->iter(), this->line_end());\n }\n\n source_ptr const& source() const& noexcept {return source_;}\n source_ptr&& source() && noexcept {return std::move(source_);}\n\n private:\n\n source_ptr source_;\n std::size_t line_number_;\n std::string source_name_;\n const_iterator iter_;\n};\n\n\/\/ region represents a range in a container, which contains a file content.\n\/\/\n\/\/ it contains pointer to the file content and iterator that points the first\n\/\/ and last location.\ntemplate\nstruct region final : public region_base\n{\n using const_iterator = typename Container::const_iterator;\n using source_ptr = std::shared_ptr;\n\n static_assert(std::is_same::value,\"\");\n static_assert(std::is_same::iterator_category>::value,\n \"container should be randomly accessible\");\n\n \/\/ delete default constructor. source_ never be null.\n region() = delete;\n\n region(const location& loc)\n : source_(loc.source()), source_name_(loc.name()),\n first_(loc.iter()), last_(loc.iter())\n {}\n region(location&& loc)\n : source_(loc.source()), source_name_(loc.name()),\n first_(loc.iter()), last_(loc.iter())\n {}\n\n region(const location& loc, const_iterator f, const_iterator l)\n : source_(loc.source()), source_name_(loc.name()), first_(f), last_(l)\n {}\n region(location&& loc, const_iterator f, const_iterator l)\n : source_(loc.source()), source_name_(loc.name()), first_(f), last_(l)\n {}\n\n region(const region&) = default;\n region(region&&) = default;\n region& operator=(const region&) = default;\n region& operator=(region&&) = default;\n ~region() = default;\n\n region& operator+=(const region& other)\n {\n if(this->begin() != other.begin() || this->end() != other.end() ||\n this->last_ != other.first_)\n {\n throw internal_error(\"invalid region concatenation\");\n }\n this->last_ = other.last_;\n return *this;\n }\n\n bool is_ok() const noexcept override {return static_cast(source_);}\n\n std::string str() const override {return make_string(first_, last_);}\n std::string line() const override\n {\n if(this->contain_newline())\n {\n return make_string(this->line_begin(),\n std::find(this->line_begin(), this->last(), '\\n'));\n }\n return make_string(this->line_begin(), this->line_end());\n }\n std::string line_num() const override\n {\n return std::to_string(1 + std::count(this->begin(), this->first(), '\\n'));\n }\n\n std::size_t size() const noexcept override\n {\n return std::distance(first_, last_);\n }\n std::size_t before() const noexcept override\n {\n return std::distance(this->line_begin(), this->first());\n }\n std::size_t after() const noexcept override\n {\n return std::distance(this->last(), this->line_end());\n }\n\n bool contain_newline() const noexcept\n {\n return std::find(this->first(), this->last(), '\\n') != this->last();\n }\n\n const_iterator line_begin() const noexcept\n {\n using reverse_iterator = std::reverse_iterator;\n return std::find(reverse_iterator(this->first()),\n reverse_iterator(this->begin()), '\\n').base();\n }\n const_iterator line_end() const noexcept\n {\n return std::find(this->last(), this->end(), '\\n');\n }\n\n const_iterator begin() const noexcept {return source_->cbegin();}\n const_iterator end() const noexcept {return source_->cend();}\n const_iterator first() const noexcept {return first_;}\n const_iterator last() const noexcept {return last_;}\n\n source_ptr const& source() const& noexcept {return source_;}\n source_ptr&& source() && noexcept {return std::move(source_);}\n\n std::string name() const override {return source_name_;}\n\n std::string comment_before() const override\n {\n auto iter = this->line_begin(); \/\/ points the first element\n std::vector> comments;\n while(iter != this->begin())\n {\n iter = std::prev(iter);\n using rev_iter = std::reverse_iterator;\n auto line_before = std::find(rev_iter(iter), rev_iter(this->begin()),\n '\\n').base();\n \/\/ range [line_before, iter) represents the previous line\n\n auto comment_found = std::find(line_before, iter, '#');\n if(iter != comment_found && std::all_of(line_before, comment_found,\n [](const char c) noexcept -> bool {\n return c == ' ' || c == '\\t';\n }))\n {\n \/\/ the line before this range contains only a comment.\n comments.push_back(std::make_pair(comment_found, iter));\n }\n else\n {\n break;\n }\n iter = line_before;\n }\n\n std::string com;\n for(auto i = comments.crbegin(), e = comments.crend(); i!=e; ++i)\n {\n if(i != comments.crbegin()) {com += '\\n';}\n com += std::string(i->first, i->second);\n }\n return com;\n }\n\n std::string comment_inline() const override\n {\n if(this->contain_newline())\n {\n std::string com;\n \/\/ check both the first and the last line.\n const auto first_line_end =\n std::find(this->line_begin(), this->last(), '\\n');\n const auto first_comment_found =\n std::find(this->line_begin(), first_line_end, '#');\n\n if(first_comment_found != first_line_end)\n {\n com += std::string(first_comment_found, first_line_end);\n }\n\n const auto last_comment_found =\n std::find(this->last(), this->line_end(), '#');\n if(last_comment_found != this->line_end())\n {\n if(!com.empty()){com += '\\n';}\n com += std::string(last_comment_found, this->line_end());\n }\n return com;\n }\n const auto comment_found =\n std::find(this->line_begin(), this->line_end(), '#');\n return std::string(comment_found, this->line_end());\n }\n\n std::string comment() const override\n {\n std::string com_bef = this->comment_before();\n std::string com_inl = this->comment_inline();\n if(!com_bef.empty() && !com_inl.empty())\n {\n com_bef += '\\n';\n return com_bef + com_inl;\n }\n else if(com_bef.empty())\n {\n return com_inl;\n }\n else\n {\n return com_bef;\n }\n }\n\n private:\n\n source_ptr source_;\n std::string source_name_;\n const_iterator first_, last_;\n};\n\n\/\/ to show a better error message.\ninline std::string format_underline(const std::string& message,\n const std::vector>& reg_com,\n const std::vector& helps = {})\n{\n assert(!reg_com.empty());\n\n const auto line_num_width = std::max_element(reg_com.begin(), reg_com.end(),\n [](std::pair const& lhs,\n std::pair const& rhs)\n {\n return lhs.first->line_num().size() < rhs.first->line_num().size();\n }\n )->first->line_num().size();\n\n std::ostringstream retval;\n retval << message << '\\n';\n\n for(auto iter = reg_com.begin(); iter != reg_com.end(); ++iter)\n {\n \/\/ if the filenames are the same, print \"...\"\n if(iter != reg_com.begin() &&\n std::prev(iter)->first->name() == iter->first->name())\n {\n retval << \"\\n ...\\n\";\n }\n else \/\/ if filename differs, print \" --> filename.toml\"\n {\n if(iter != reg_com.begin()) {retval << '\\n';}\n retval << \" --> \" << iter->first->name() << '\\n';\n }\n const region_base* const reg = iter->first;\n const std::string& comment = iter->second;\n\n retval << ' ' << std::setw(line_num_width) << reg->line_num();\n retval << \" | \" << reg->line() << '\\n';\n retval << make_string(line_num_width + 1, ' ');\n retval << \" | \" << make_string(reg->before(), ' ');\n\n if(reg->size() == 1)\n {\n \/\/ invalid\n \/\/ ^------\n retval << '^';\n retval << make_string(reg->after(), '-');\n }\n else\n {\n \/\/ invalid\n \/\/ ~~~~~~~\n const auto underline_len = std::min(reg->size(), reg->line().size());\n retval << make_string(underline_len, '~');\n }\n retval << ' ';\n retval << comment;\n }\n\n if(!helps.empty())\n {\n retval << '\\n';\n retval << make_string(line_num_width + 1, ' ');\n retval << \" | \";\n for(const auto help : helps)\n {\n retval << \"\\nHint: \";\n retval << help;\n }\n }\n return retval.str();\n}\n\n} \/\/ detail\n} \/\/ toml\n#endif\/\/ TOML11_REGION_H\nfeat: :boom: change comment interface in region\/\/ Copyright Toru Niina 2017.\n\/\/ Distributed under the MIT License.\n#ifndef TOML11_REGION_HPP\n#define TOML11_REGION_HPP\n#include \"exception.hpp\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace toml\n{\nnamespace detail\n{\n\n\/\/ helper function to avoid std::string(0, 'c') or std::string(iter, iter)\ntemplate\nstd::string make_string(Iterator first, Iterator last)\n{\n if(first == last) {return \"\";}\n return std::string(first, last);\n}\ninline std::string make_string(std::size_t len, char c)\n{\n if(len == 0) {return \"\";}\n return std::string(len, c);\n}\n\n\/\/ region_base is a base class of location and region that are defined below.\n\/\/ it will be used to generate better error messages.\nstruct region_base\n{\n region_base() = default;\n virtual ~region_base() = default;\n region_base(const region_base&) = default;\n region_base(region_base&& ) = default;\n region_base& operator=(const region_base&) = default;\n region_base& operator=(region_base&& ) = default;\n\n virtual bool is_ok() const noexcept {return false;}\n\n virtual std::string str() const {return std::string(\"unknown region\");}\n virtual std::string name() const {return std::string(\"unknown file\");}\n virtual std::string line() const {return std::string(\"unknown line\");}\n virtual std::string line_num() const {return std::string(\"?\");}\n\n \/\/ length of the region\n virtual std::size_t size() const noexcept {return 0;}\n \/\/ number of characters in the line before the region\n virtual std::size_t before() const noexcept {return 0;}\n \/\/ number of characters in the line after the region\n virtual std::size_t after() const noexcept {return 0;}\n\n virtual std::vector comments()const {return {};}\n \/\/ ```toml\n \/\/ # comment_before\n \/\/ key = \"value\" # comment_inline\n \/\/ ```\n};\n\n\/\/ location represents a position in a container, which contains a file content.\n\/\/ it can be considered as a region that contains only one character.\n\/\/\n\/\/ it contains pointer to the file content and iterator that points the current\n\/\/ location.\ntemplate\nstruct location final : public region_base\n{\n using const_iterator = typename Container::const_iterator;\n using source_ptr = std::shared_ptr;\n\n static_assert(std::is_same::value,\"\");\n static_assert(std::is_same::iterator_category>::value,\n \"container should be randomly accessible\");\n\n location(std::string name, Container cont)\n : source_(std::make_shared(std::move(cont))), line_number_(1),\n source_name_(std::move(name)), iter_(source_->cbegin())\n {}\n location(const location&) = default;\n location(location&&) = default;\n location& operator=(const location&) = default;\n location& operator=(location&&) = default;\n ~location() = default;\n\n bool is_ok() const noexcept override {return static_cast(source_);}\n\n \/\/ this const prohibits codes like `++(loc.iter())`.\n const const_iterator iter() const noexcept {return iter_;}\n\n const_iterator begin() const noexcept {return source_->cbegin();}\n const_iterator end() const noexcept {return source_->cend();}\n\n \/\/ XXX `location::line_num()` used to be implemented using `std::count` to\n \/\/ count a number of '\\n'. But with a long toml file (typically, 10k lines),\n \/\/ it becomes intolerably slow because each time it generates error messages,\n \/\/ it counts '\\n' from thousands of characters. To workaround it, I decided\n \/\/ to introduce `location::line_number_` member variable and synchronize it\n \/\/ to the location changes the point to look. So an overload of `iter()`\n \/\/ which returns mutable reference is removed and `advance()`, `retrace()`\n \/\/ and `reset()` is added.\n void advance(std::size_t n = 1) noexcept\n {\n this->line_number_ += std::count(this->iter_, this->iter_ + n, '\\n');\n this->iter_ += n;\n return;\n }\n void retrace(std::size_t n = 1) noexcept\n {\n this->line_number_ -= std::count(this->iter_ - n, this->iter_, '\\n');\n this->iter_ -= n;\n return;\n }\n void reset(const_iterator rollback) noexcept\n {\n \/\/ since c++11, std::distance works in both ways for random-access\n \/\/ iterators and returns a negative value if `first > last`.\n if(0 <= std::distance(rollback, this->iter_)) \/\/ rollback < iter\n {\n this->line_number_ -= std::count(rollback, this->iter_, '\\n');\n }\n else \/\/ iter < rollback [[unlikely]]\n {\n this->line_number_ += std::count(this->iter_, rollback, '\\n');\n }\n this->iter_ = rollback;\n return;\n }\n\n std::string str() const override {return make_string(1, *this->iter());}\n std::string name() const override {return source_name_;}\n\n std::string line_num() const override\n {\n return std::to_string(this->line_number_);\n }\n\n std::string line() const override\n {\n return make_string(this->line_begin(), this->line_end());\n }\n\n const_iterator line_begin() const noexcept\n {\n using reverse_iterator = std::reverse_iterator;\n return std::find(reverse_iterator(this->iter()),\n reverse_iterator(this->begin()), '\\n').base();\n }\n const_iterator line_end() const noexcept\n {\n return std::find(this->iter(), this->end(), '\\n');\n }\n\n \/\/ location is always points a character. so the size is 1.\n std::size_t size() const noexcept override\n {\n return 1u;\n }\n std::size_t before() const noexcept override\n {\n return std::distance(this->line_begin(), this->iter());\n }\n std::size_t after() const noexcept override\n {\n return std::distance(this->iter(), this->line_end());\n }\n\n source_ptr const& source() const& noexcept {return source_;}\n source_ptr&& source() && noexcept {return std::move(source_);}\n\n private:\n\n source_ptr source_;\n std::size_t line_number_;\n std::string source_name_;\n const_iterator iter_;\n};\n\n\/\/ region represents a range in a container, which contains a file content.\n\/\/\n\/\/ it contains pointer to the file content and iterator that points the first\n\/\/ and last location.\ntemplate\nstruct region final : public region_base\n{\n using const_iterator = typename Container::const_iterator;\n using source_ptr = std::shared_ptr;\n\n static_assert(std::is_same::value,\"\");\n static_assert(std::is_same::iterator_category>::value,\n \"container should be randomly accessible\");\n\n \/\/ delete default constructor. source_ never be null.\n region() = delete;\n\n region(const location& loc)\n : source_(loc.source()), source_name_(loc.name()),\n first_(loc.iter()), last_(loc.iter())\n {}\n region(location&& loc)\n : source_(loc.source()), source_name_(loc.name()),\n first_(loc.iter()), last_(loc.iter())\n {}\n\n region(const location& loc, const_iterator f, const_iterator l)\n : source_(loc.source()), source_name_(loc.name()), first_(f), last_(l)\n {}\n region(location&& loc, const_iterator f, const_iterator l)\n : source_(loc.source()), source_name_(loc.name()), first_(f), last_(l)\n {}\n\n region(const region&) = default;\n region(region&&) = default;\n region& operator=(const region&) = default;\n region& operator=(region&&) = default;\n ~region() = default;\n\n region& operator+=(const region& other)\n {\n if(this->begin() != other.begin() || this->end() != other.end() ||\n this->last_ != other.first_)\n {\n throw internal_error(\"invalid region concatenation\");\n }\n this->last_ = other.last_;\n return *this;\n }\n\n bool is_ok() const noexcept override {return static_cast(source_);}\n\n std::string str() const override {return make_string(first_, last_);}\n std::string line() const override\n {\n if(this->contain_newline())\n {\n return make_string(this->line_begin(),\n std::find(this->line_begin(), this->last(), '\\n'));\n }\n return make_string(this->line_begin(), this->line_end());\n }\n std::string line_num() const override\n {\n return std::to_string(1 + std::count(this->begin(), this->first(), '\\n'));\n }\n\n std::size_t size() const noexcept override\n {\n return std::distance(first_, last_);\n }\n std::size_t before() const noexcept override\n {\n return std::distance(this->line_begin(), this->first());\n }\n std::size_t after() const noexcept override\n {\n return std::distance(this->last(), this->line_end());\n }\n\n bool contain_newline() const noexcept\n {\n return std::find(this->first(), this->last(), '\\n') != this->last();\n }\n\n const_iterator line_begin() const noexcept\n {\n using reverse_iterator = std::reverse_iterator;\n return std::find(reverse_iterator(this->first()),\n reverse_iterator(this->begin()), '\\n').base();\n }\n const_iterator line_end() const noexcept\n {\n return std::find(this->last(), this->end(), '\\n');\n }\n\n const_iterator begin() const noexcept {return source_->cbegin();}\n const_iterator end() const noexcept {return source_->cend();}\n const_iterator first() const noexcept {return first_;}\n const_iterator last() const noexcept {return last_;}\n\n source_ptr const& source() const& noexcept {return source_;}\n source_ptr&& source() && noexcept {return std::move(source_);}\n\n std::string name() const override {return source_name_;}\n\n std::vector comments() const override\n {\n \/\/ assuming the current region (`*this`) points a value.\n \/\/ ```toml\n \/\/ a = \"value\"\n \/\/ ^^^^^^^- this region\n \/\/ ```\n using rev_iter = std::reverse_iterator;\n\n std::vector com{};\n {\n \/\/ find comments just before the current region.\n \/\/ ```toml\n \/\/ # this should be collected.\n \/\/ # this also.\n \/\/ a = value # not this.\n \/\/ ```\n auto iter = this->line_begin(); \/\/ points the first character\n while(iter != this->begin())\n {\n iter = std::prev(iter);\n\n \/\/ range [line_start, iter) represents the previous line\n const auto line_start = std::find(\n rev_iter(iter), rev_iter(this->begin()), '\\n').base();\n const auto comment_found = std::find(line_start, iter, '#');\n if(comment_found == iter)\n {\n break; \/\/ comment not found.\n }\n\n \/\/ exclude the following case.\n \/\/ > a = \"foo\" # comment \/\/ <-- this is not a comment for b but a.\n \/\/ > b = \"current value\"\n if(std::all_of(line_start, comment_found,\n [](const char c) noexcept -> bool {\n return c == ' ' || c == '\\t';\n }))\n {\n \/\/ unwrap the first '#' by std::next.\n com.push_back(make_string(std::next(comment_found), iter));\n }\n else\n {\n break;\n }\n iter = line_start;\n }\n }\n {\n \/\/ find comments just after the current region.\n \/\/ ```toml\n \/\/ # not this.\n \/\/ a = value # this one.\n \/\/ a = [ # not this (technically difficult)\n \/\/\n \/\/ ] # and this.\n \/\/ ```\n \/\/ The reason why it's difficult is that it requires parsing in the\n \/\/ following case.\n \/\/ ```toml\n \/\/ a = [ 10 # this comment is for `10`. not for `a` but `a[0]`.\n \/\/ # ...\n \/\/ ] # this is apparently a comment for a.\n \/\/\n \/\/ b = [\n \/\/ 3.14 ] # there is no way to add a comment to `3.14` currently.\n \/\/\n \/\/ c = [\n \/\/ 3.14 # do this if you need a comment here.\n \/\/ ]\n \/\/ ```\n const auto last_comment_found =\n std::find(this->last(), this->line_end(), '#');\n if(last_comment_found != this->line_end()) \/\/ '#' found\n {\n com.push_back(make_string(last_comment_found, this->line_end()));\n }\n }\n return com;\n }\n\n private:\n\n source_ptr source_;\n std::string source_name_;\n const_iterator first_, last_;\n};\n\n\/\/ to show a better error message.\ninline std::string format_underline(const std::string& message,\n const std::vector>& reg_com,\n const std::vector& helps = {})\n{\n assert(!reg_com.empty());\n\n const auto line_num_width = std::max_element(reg_com.begin(), reg_com.end(),\n [](std::pair const& lhs,\n std::pair const& rhs)\n {\n return lhs.first->line_num().size() < rhs.first->line_num().size();\n }\n )->first->line_num().size();\n\n std::ostringstream retval;\n retval << message << '\\n';\n\n for(auto iter = reg_com.begin(); iter != reg_com.end(); ++iter)\n {\n \/\/ if the filenames are the same, print \"...\"\n if(iter != reg_com.begin() &&\n std::prev(iter)->first->name() == iter->first->name())\n {\n retval << \"\\n ...\\n\";\n }\n else \/\/ if filename differs, print \" --> filename.toml\"\n {\n if(iter != reg_com.begin()) {retval << '\\n';}\n retval << \" --> \" << iter->first->name() << '\\n';\n }\n const region_base* const reg = iter->first;\n const std::string& comment = iter->second;\n\n retval << ' ' << std::setw(line_num_width) << reg->line_num();\n retval << \" | \" << reg->line() << '\\n';\n retval << make_string(line_num_width + 1, ' ');\n retval << \" | \" << make_string(reg->before(), ' ');\n\n if(reg->size() == 1)\n {\n \/\/ invalid\n \/\/ ^------\n retval << '^';\n retval << make_string(reg->after(), '-');\n }\n else\n {\n \/\/ invalid\n \/\/ ~~~~~~~\n const auto underline_len = std::min(reg->size(), reg->line().size());\n retval << make_string(underline_len, '~');\n }\n retval << ' ';\n retval << comment;\n }\n\n if(!helps.empty())\n {\n retval << '\\n';\n retval << make_string(line_num_width + 1, ' ');\n retval << \" | \";\n for(const auto help : helps)\n {\n retval << \"\\nHint: \";\n retval << help;\n }\n }\n return retval.str();\n}\n\n} \/\/ detail\n} \/\/ toml\n#endif\/\/ TOML11_REGION_H\n<|endoftext|>"} {"text":"\/**\n * @file\n * @brief Implementation of default digitization module\n * @copyright MIT License\n *\/\n\n#include \"DefaultDigitizerModule.hpp\"\n\n#include \"core\/utils\/unit.h\"\n#include \"tools\/ROOT.h\"\n\n#include \n#include \n#include \n\n#include \"objects\/PixelHit.hpp\"\n\nusing namespace allpix;\n\nDefaultDigitizerModule::DefaultDigitizerModule(Configuration config,\n Messenger* messenger,\n std::shared_ptr detector)\n : Module(config, std::move(detector)), config_(std::move(config)), messenger_(messenger), pixel_message_(nullptr) {\n \/\/ Enable parallelization of this module if multithreading is enabled\n enable_parallelization();\n\n \/\/ Require PixelCharge message for single detector\n messenger_->bindSingle(this, &DefaultDigitizerModule::pixel_message_, MsgFlags::REQUIRED);\n\n \/\/ Seed the random generator with the global seed\n random_generator_.seed(getRandomSeed());\n\n \/\/ Set defaults for config variables\n config_.setDefault(\"electronics_noise\", Units::get(110, \"e\"));\n config_.setDefault(\"threshold\", Units::get(600, \"e\"));\n config_.setDefault(\"threshold_smearing\", Units::get(30, \"e\"));\n\n config_.setDefault(\"adc_resolution\", 0);\n config_.setDefault(\"adc_smearing\", Units::get(300, \"e\"));\n config_.setDefault(\"adc_offset\", Units::get(0, \"e\"));\n config_.setDefault(\"adc_slope\", Units::get(10, \"e\"));\n\n config_.setDefault(\"output_plots\", false);\n}\n\nvoid DefaultDigitizerModule::init() {\n if(config_.get(\"output_plots\")) {\n LOG(TRACE) << \"Creating output plots\";\n\n \/\/ Create histograms if needed\n h_pxq = new TH1D(\"pixelcharge\", \"raw pixel charge;pixel charge [ke];pixels\", 100, 0, 10);\n h_pxq_noise = new TH1D(\"pixelcharge_noise_\", \"pixel charge w\/ el. noise;pixel charge [ke];pixels\", 100, 0, 10);\n h_thr = new TH1D(\"threshold\", \"applied threshold; threshold [ke];events\", 100, 0, 10);\n h_pxq_thr = new TH1D(\"pixelcharge_threshold_\", \"pixel charge above threshold;pixel charge [ke];pixels\", 100, 0, 10);\n h_pxq_adc = new TH1D(\"pixelcharge_adc\", \"pixel charge after ADC;pixel charge [ke];pixels\", 100, 0, 10);\n }\n\n \/\/ Conversion to ADC units requested:\n if(config_.get(\"adc_resolution\") > 0) {\n LOG(INFO) << \"Converting charge to ADC units, ADC resolution: \" << config_.get(\"adc_resolution\")\n << \"bit, max. value \" << ((1 << config_.get(\"adc_resolution\")) - 1);\n }\n}\n\nvoid DefaultDigitizerModule::run(unsigned int) {\n \/\/ Loop through all pixels with charges\n std::vector hits;\n for(auto& pixel_charge : pixel_message_->getData()) {\n auto pixel = pixel_charge.getPixel();\n auto pixel_index = pixel.getIndex();\n auto charge = static_cast(pixel_charge.getCharge());\n\n LOG(DEBUG) << \"Received pixel \" << pixel_index << \", charge \" << Units::display(charge, \"e\");\n if(config_.get(\"output_plots\")) {\n h_pxq->Fill(charge \/ 1e3);\n }\n\n \/\/ Add electronics noise from Gaussian:\n std::normal_distribution el_noise(0, config_.get(\"electronics_noise\"));\n charge += el_noise(random_generator_);\n\n LOG(DEBUG) << \"Charge with noise: \" << Units::display(charge, \"e\");\n if(config_.get(\"output_plots\")) {\n h_pxq_noise->Fill(charge \/ 1e3);\n }\n\n \/\/ FIXME Simulate gain \/ gain smearing\n\n \/\/ Smear the threshold, Gaussian distribution around \"threshold\" with width \"threshold_smearing\"\n std::normal_distribution thr_smearing(config_.get(\"threshold\"),\n config_.get(\"threshold_smearing\"));\n double threshold = thr_smearing(random_generator_);\n if(config_.get(\"output_plots\")) {\n h_thr->Fill(threshold \/ 1e3);\n }\n\n \/\/ Discard charges below threshold:\n if(charge < threshold) {\n LOG(DEBUG) << \"Below smeared threshold: \" << Units::display(charge, \"e\") << \" < \"\n << Units::display(threshold, \"e\");\n continue;\n }\n\n LOG(DEBUG) << \"Passed threshold: \" << Units::display(charge, \"e\") << \" > \" << Units::display(threshold, \"e\");\n if(config_.get(\"output_plots\")) {\n h_pxq_thr->Fill(charge \/ 1e3);\n }\n\n \/\/ Simulate ADC if resolution set to more than 0bit\n if(config_.get(\"adc_resolution\") > 0) {\n \/\/ Add ADC smearing:\n std::normal_distribution adc_smearing(0, config_.get(\"adc_smearing\"));\n charge += adc_smearing(random_generator_);\n if(config_.get(\"output_plots\")) {\n h_pxq_adc->Fill(charge \/ 1e3);\n }\n LOG(DEBUG) << \"Smeared for simulating limited ADC sensitivity: \" << Units::display(charge, \"e\");\n\n \/\/ Convert to ADC units and precision:\n charge = std::max(\n std::min(static_cast(config_.get(\"adc_offset\") + charge \/ config_.get(\"adc_slope\")),\n (1 << config_.get(\"adc_resolution\")) - 1),\n 0);\n LOG(DEBUG) << \"Charge converted to ADC units: \" << charge;\n }\n\n \/\/ Add the hit to the hitmap\n hits.emplace_back(pixel, 0, charge, &pixel_charge);\n }\n\n \/\/ Output summary and update statistics\n LOG(INFO) << \"Digitized \" << hits.size() << \" pixel hits\";\n total_hits_ += hits.size();\n\n if(!hits.empty()) {\n \/\/ Create and dispatch hit message\n auto hits_message = std::make_shared(std::move(hits), getDetector());\n messenger_->dispatchMessage(this, hits_message);\n }\n}\n\nvoid DefaultDigitizerModule::finalize() {\n if(config_.get(\"output_plots\")) {\n \/\/ Write histograms\n LOG(TRACE) << \"Writing output plots to file\";\n h_pxq->Write();\n h_pxq_noise->Write();\n h_thr->Write();\n h_pxq_thr->Write();\n h_pxq_adc->Write();\n }\n\n LOG(INFO) << \"Digitized \" << total_hits_ << \" pixel hits in total\";\n}\nThrow InvaldValueError for too high ADC precision\/**\n * @file\n * @brief Implementation of default digitization module\n * @copyright MIT License\n *\/\n\n#include \"DefaultDigitizerModule.hpp\"\n\n#include \"core\/utils\/unit.h\"\n#include \"tools\/ROOT.h\"\n\n#include \n#include \n#include \n\n#include \"objects\/PixelHit.hpp\"\n\nusing namespace allpix;\n\nDefaultDigitizerModule::DefaultDigitizerModule(Configuration config,\n Messenger* messenger,\n std::shared_ptr detector)\n : Module(config, std::move(detector)), config_(std::move(config)), messenger_(messenger), pixel_message_(nullptr) {\n \/\/ Enable parallelization of this module if multithreading is enabled\n enable_parallelization();\n\n \/\/ Require PixelCharge message for single detector\n messenger_->bindSingle(this, &DefaultDigitizerModule::pixel_message_, MsgFlags::REQUIRED);\n\n \/\/ Seed the random generator with the global seed\n random_generator_.seed(getRandomSeed());\n\n \/\/ Set defaults for config variables\n config_.setDefault(\"electronics_noise\", Units::get(110, \"e\"));\n config_.setDefault(\"threshold\", Units::get(600, \"e\"));\n config_.setDefault(\"threshold_smearing\", Units::get(30, \"e\"));\n\n config_.setDefault(\"adc_resolution\", 0);\n config_.setDefault(\"adc_smearing\", Units::get(300, \"e\"));\n config_.setDefault(\"adc_offset\", Units::get(0, \"e\"));\n config_.setDefault(\"adc_slope\", Units::get(10, \"e\"));\n\n config_.setDefault(\"output_plots\", false);\n}\n\nvoid DefaultDigitizerModule::init() {\n if(config_.get(\"output_plots\")) {\n LOG(TRACE) << \"Creating output plots\";\n\n \/\/ Create histograms if needed\n h_pxq = new TH1D(\"pixelcharge\", \"raw pixel charge;pixel charge [ke];pixels\", 100, 0, 10);\n h_pxq_noise = new TH1D(\"pixelcharge_noise_\", \"pixel charge w\/ el. noise;pixel charge [ke];pixels\", 100, 0, 10);\n h_thr = new TH1D(\"threshold\", \"applied threshold; threshold [ke];events\", 100, 0, 10);\n h_pxq_thr = new TH1D(\"pixelcharge_threshold_\", \"pixel charge above threshold;pixel charge [ke];pixels\", 100, 0, 10);\n h_pxq_adc = new TH1D(\"pixelcharge_adc\", \"pixel charge after ADC;pixel charge [ke];pixels\", 100, 0, 10);\n }\n\n \/\/ Conversion to ADC units requested:\n if(config_.get(\"adc_resolution\") > 63) {\n throw InvalidValueError(config_, \"adc_resolution\", \"precision higher than 64bit is not possible\");\n }\n if(config_.get(\"adc_resolution\") > 0) {\n LOG(INFO) << \"Converting charge to ADC units, ADC resolution: \" << config_.get(\"adc_resolution\")\n << \"bit, max. value \" << ((1 << config_.get(\"adc_resolution\")) - 1);\n }\n}\n\nvoid DefaultDigitizerModule::run(unsigned int) {\n \/\/ Loop through all pixels with charges\n std::vector hits;\n for(auto& pixel_charge : pixel_message_->getData()) {\n auto pixel = pixel_charge.getPixel();\n auto pixel_index = pixel.getIndex();\n auto charge = static_cast(pixel_charge.getCharge());\n\n LOG(DEBUG) << \"Received pixel \" << pixel_index << \", charge \" << Units::display(charge, \"e\");\n if(config_.get(\"output_plots\")) {\n h_pxq->Fill(charge \/ 1e3);\n }\n\n \/\/ Add electronics noise from Gaussian:\n std::normal_distribution el_noise(0, config_.get(\"electronics_noise\"));\n charge += el_noise(random_generator_);\n\n LOG(DEBUG) << \"Charge with noise: \" << Units::display(charge, \"e\");\n if(config_.get(\"output_plots\")) {\n h_pxq_noise->Fill(charge \/ 1e3);\n }\n\n \/\/ FIXME Simulate gain \/ gain smearing\n\n \/\/ Smear the threshold, Gaussian distribution around \"threshold\" with width \"threshold_smearing\"\n std::normal_distribution thr_smearing(config_.get(\"threshold\"),\n config_.get(\"threshold_smearing\"));\n double threshold = thr_smearing(random_generator_);\n if(config_.get(\"output_plots\")) {\n h_thr->Fill(threshold \/ 1e3);\n }\n\n \/\/ Discard charges below threshold:\n if(charge < threshold) {\n LOG(DEBUG) << \"Below smeared threshold: \" << Units::display(charge, \"e\") << \" < \"\n << Units::display(threshold, \"e\");\n continue;\n }\n\n LOG(DEBUG) << \"Passed threshold: \" << Units::display(charge, \"e\") << \" > \" << Units::display(threshold, \"e\");\n if(config_.get(\"output_plots\")) {\n h_pxq_thr->Fill(charge \/ 1e3);\n }\n\n \/\/ Simulate ADC if resolution set to more than 0bit\n if(config_.get(\"adc_resolution\") > 0) {\n \/\/ Add ADC smearing:\n std::normal_distribution adc_smearing(0, config_.get(\"adc_smearing\"));\n charge += adc_smearing(random_generator_);\n if(config_.get(\"output_plots\")) {\n h_pxq_adc->Fill(charge \/ 1e3);\n }\n LOG(DEBUG) << \"Smeared for simulating limited ADC sensitivity: \" << Units::display(charge, \"e\");\n\n \/\/ Convert to ADC units and precision:\n charge = std::max(\n std::min(static_cast(config_.get(\"adc_offset\") + charge \/ config_.get(\"adc_slope\")),\n (1 << config_.get(\"adc_resolution\")) - 1),\n 0);\n LOG(DEBUG) << \"Charge converted to ADC units: \" << charge;\n }\n\n \/\/ Add the hit to the hitmap\n hits.emplace_back(pixel, 0, charge, &pixel_charge);\n }\n\n \/\/ Output summary and update statistics\n LOG(INFO) << \"Digitized \" << hits.size() << \" pixel hits\";\n total_hits_ += hits.size();\n\n if(!hits.empty()) {\n \/\/ Create and dispatch hit message\n auto hits_message = std::make_shared(std::move(hits), getDetector());\n messenger_->dispatchMessage(this, hits_message);\n }\n}\n\nvoid DefaultDigitizerModule::finalize() {\n if(config_.get(\"output_plots\")) {\n \/\/ Write histograms\n LOG(TRACE) << \"Writing output plots to file\";\n h_pxq->Write();\n h_pxq_noise->Write();\n h_thr->Write();\n h_pxq_thr->Write();\n h_pxq_adc->Write();\n }\n\n LOG(INFO) << \"Digitized \" << total_hits_ << \" pixel hits in total\";\n}\n<|endoftext|>"} {"text":"#include \"..\/..\/..\/SDP_Solver.hxx\"\n\n\/\/ result = \\sum_p a[p] A_p,\n\/\/\n\/\/ where a[p] is a vector of length primalObjective.size() and the\n\/\/ constraint matrices A_p are given by\n\/\/\n\/\/ A_(j,r,s,k) = \\sum_{b \\in blocks[j]}\n\/\/ Block_b(v_{b,k} v_{b,k}^T \\otimes E^{rs}),\n\/\/\n\/\/ where v_{b,k} is the k-th column of bilinearBases[b], as described\n\/\/ in SDP.h.\n\/\/\n\/\/ Inputs: sdp, a\n\/\/ Output: result (overwritten)\n\/\/\n\nvoid diagonal_congruence(const Real *d, const Matrix &V, const int blockRow,\n const int blockCol, Matrix &result);\n\nvoid constraint_matrix_weighted_sum(const SDP &sdp, const Vector &a,\n Block_Diagonal_Matrix &result)\n{\n for(unsigned int j = 0; j < sdp.dimensions.size(); j++)\n {\n const int ej = sdp.degrees[j] + 1;\n\n \/\/ For each j, t points to the first Index_Tuple corresponding to j\n for(auto t(sdp.constraint_indices[j].begin());\n t != sdp.constraint_indices[j].end(); t += ej)\n {\n const int p = t->p;\n const int r = t->r;\n const int s = t->s;\n assert(t->k == 0);\n\n for(auto &b : sdp.blocks[j])\n {\n \/\/ result.blocks[b]^(r,s) = V diag(a') V^T, where\n \/\/ V=sdp.bilinearBases[b], a' denotes the subvector of a\n \/\/ corresponding to j, and M^(r,s) denotes the (r,s)-th block\n \/\/ of M.\n diagonal_congruence(&a[p], sdp.bilinear_bases[b], r, s,\n result.blocks[b]);\n\n \/\/ result should be symmetric, so if r != s, we must\n \/\/ divide the (r,s)-th block of result.blocks[b] by 2\n \/\/ and copy it to its transpose, the (s,r)-th block.\n if(r != s)\n {\n const int u = sdp.bilinear_bases[b].rows;\n for(int m = r * u; m < (r + 1) * u; m++)\n {\n for(int n = s * u; n < (s + 1) * u; n++)\n {\n result.blocks[b].elt(m, n) \/= 2;\n result.blocks[b].elt(n, m)\n = result.blocks[b].elt(m, n);\n }\n }\n }\n }\n }\n }\n}\n\nvoid constraint_matrix_weighted_sum(const SDP &sdp, const Block_Matrix &a,\n Block_Diagonal_Matrix &result)\n{\n for(size_t jj = 0; jj < sdp.dimensions.size(); ++jj)\n {\n const size_t block_size(sdp.degrees[jj] + 1);\n for(size_t block_index(2 * jj); block_index < 2 * jj + 2; ++block_index)\n {\n El::Zero(result.blocks_elemental[block_index]);\n for(size_t column_block = 0; column_block < sdp.dimensions[jj];\n ++column_block)\n for(size_t row_block = 0; row_block <= column_block; ++row_block)\n {\n size_t row_offset(\n ((column_block * (column_block + 1)) \/ 2 + row_block)\n * block_size);\n El::DistMatrix sub_vector(\n El::LockedView(a.blocks[jj], row_offset, 0, block_size, 1));\n El::DistMatrix scaled_bases(\n sdp.bilinear_bases_elemental_dist[block_index]);\n \n El::DiagonalScale(El::LeftOrRight::RIGHT,\n El::Orientation::NORMAL, sub_vector,\n scaled_bases);\n\n El::Gemm(El::Orientation::NORMAL, El::Orientation::TRANSPOSE,\n El::BigFloat(1),\n sdp.bilinear_bases_elemental_dist[block_index],\n scaled_bases, El::BigFloat(0),\n result.blocks_elemental[block_index]);\n }\n }\n }\n}\nUse a proper result sub_block in constraint_matrix_weighted_sum#include \"..\/..\/..\/SDP_Solver.hxx\"\n\n\/\/ result = \\sum_p a[p] A_p,\n\/\/\n\/\/ where a[p] is a vector of length primalObjective.size() and the\n\/\/ constraint matrices A_p are given by\n\/\/\n\/\/ A_(j,r,s,k) = \\sum_{b \\in blocks[j]}\n\/\/ Block_b(v_{b,k} v_{b,k}^T \\otimes E^{rs}),\n\/\/\n\/\/ where v_{b,k} is the k-th column of bilinearBases[b], as described\n\/\/ in SDP.h.\n\/\/\n\/\/ Inputs: sdp, a\n\/\/ Output: result (overwritten)\n\/\/\n\nvoid diagonal_congruence(const Real *d, const Matrix &V, const int blockRow,\n const int blockCol, Matrix &result);\n\nvoid constraint_matrix_weighted_sum(const SDP &sdp, const Vector &a,\n Block_Diagonal_Matrix &result)\n{\n for(unsigned int j = 0; j < sdp.dimensions.size(); j++)\n {\n const int ej = sdp.degrees[j] + 1;\n\n \/\/ For each j, t points to the first Index_Tuple corresponding to j\n for(auto t(sdp.constraint_indices[j].begin());\n t != sdp.constraint_indices[j].end(); t += ej)\n {\n const int p = t->p;\n const int r = t->r;\n const int s = t->s;\n assert(t->k == 0);\n\n for(auto &b : sdp.blocks[j])\n {\n \/\/ result.blocks[b]^(r,s) = V diag(a') V^T, where\n \/\/ V=sdp.bilinearBases[b], a' denotes the subvector of a\n \/\/ corresponding to j, and M^(r,s) denotes the (r,s)-th block\n \/\/ of M.\n diagonal_congruence(&a[p], sdp.bilinear_bases[b], r, s,\n result.blocks[b]);\n\n \/\/ result should be symmetric, so if r != s, we must\n \/\/ divide the (r,s)-th block of result.blocks[b] by 2\n \/\/ and copy it to its transpose, the (s,r)-th block.\n if(r != s)\n {\n const int u = sdp.bilinear_bases[b].rows;\n for(int m = r * u; m < (r + 1) * u; m++)\n {\n for(int n = s * u; n < (s + 1) * u; n++)\n {\n result.blocks[b].elt(m, n) \/= 2;\n result.blocks[b].elt(n, m)\n = result.blocks[b].elt(m, n);\n }\n }\n }\n }\n }\n }\n}\n\nvoid constraint_matrix_weighted_sum(const SDP &sdp, const Block_Matrix &a,\n Block_Diagonal_Matrix &result)\n{\n for(size_t jj = 0; jj < sdp.dimensions.size(); ++jj)\n {\n const size_t block_size(sdp.degrees[jj] + 1);\n for(size_t block_index(2 * jj); block_index < 2 * jj + 2; ++block_index)\n {\n El::Zero(result.blocks_elemental[block_index]);\n for(size_t column_block = 0; column_block < sdp.dimensions[jj];\n ++column_block)\n for(size_t row_block = 0; row_block <= column_block; ++row_block)\n {\n const size_t result_block_size(\n sdp.bilinear_bases_elemental_dist[block_index].Height());\n const size_t column_offset(column_block * result_block_size),\n row_offset(row_block * result_block_size);\n size_t vector_offset(\n ((column_block * (column_block + 1)) \/ 2 + row_block)\n * block_size);\n El::DistMatrix sub_vector(El::LockedView(\n a.blocks[jj], vector_offset, 0, block_size, 1));\n El::DistMatrix scaled_bases(\n sdp.bilinear_bases_elemental_dist[block_index]);\n\n El::DiagonalScale(El::LeftOrRight::RIGHT,\n El::Orientation::NORMAL, sub_vector,\n scaled_bases);\n\n El::DistMatrix result_sub_block(El::View(\n result.blocks_elemental[block_index], row_offset,\n column_offset, result_block_size, result_block_size));\n El::Gemm(El::Orientation::NORMAL, El::Orientation::TRANSPOSE,\n El::BigFloat(1),\n sdp.bilinear_bases_elemental_dist[block_index],\n scaled_bases, El::BigFloat(0), result_sub_block);\n }\n }\n }\n}\n<|endoftext|>"} {"text":"\/\/ Copyright Toru Niina 2017.\n\/\/ Distributed under the MIT License.\n#ifndef TOML11_TRAITS_HPP\n#define TOML11_TRAITS_HPP\n#include \n#include \n#include \n#include \n#include \n#if __cplusplus >= 201703L\n#if __has_include()\n#include \n#endif \/\/ has_include()\n#endif \/\/ cplusplus >= C++17\n\nnamespace toml\n{\ntemplate class T, template class A>\nclass basic_value;\n\nnamespace detail\n{\n\/\/ ---------------------------------------------------------------------------\n\/\/ check whether type T is a kind of container\/map class\n\nstruct has_iterator_impl\n{\n template static std::true_type check(typename T::iterator*);\n template static std::false_type check(...);\n};\nstruct has_value_type_impl\n{\n template static std::true_type check(typename T::value_type*);\n template static std::false_type check(...);\n};\nstruct has_key_type_impl\n{\n template static std::true_type check(typename T::key_type*);\n template static std::false_type check(...);\n};\nstruct has_mapped_type_impl\n{\n template static std::true_type check(typename T::mapped_type*);\n template static std::false_type check(...);\n};\nstruct has_resize_method_impl\n{\n constexpr static std::size_t dummy=0;\n template static std::true_type check(decltype(std::declval().resize(dummy))*);\n template static std::false_type check(...);\n};\n\nstruct is_comparable_impl\n{\n template static std::true_type check(decltype(std::declval() < std::declval())*);\n template static std::false_type check(...);\n};\n\nstruct has_from_toml_method_impl\n{\n template class Tb, template class A>\n static std::true_type check(\n decltype(std::declval().from_toml(\n std::declval<::toml::basic_value>()))*);\n\n template class Tb, template class A>\n static std::false_type check(...);\n};\nstruct has_into_toml_method_impl\n{\n template\n static std::true_type check(decltype(std::declval().into_toml())*);\n template\n static std::false_type check(...);\n};\n\n\/\/\/ Intel C++ compiler can not use decltype in parent class declaration, here\n\/\/\/ is a hack to work around it. https:\/\/stackoverflow.com\/a\/23953090\/4692076\n#ifdef __INTEL_COMPILER\n#define decltype(...) std::enable_if::type\n#endif\n\ntemplate\nstruct has_iterator : decltype(has_iterator_impl::check(nullptr)){};\ntemplate\nstruct has_value_type : decltype(has_value_type_impl::check(nullptr)){};\ntemplate\nstruct has_key_type : decltype(has_key_type_impl::check(nullptr)){};\ntemplate\nstruct has_mapped_type : decltype(has_mapped_type_impl::check(nullptr)){};\ntemplate\nstruct has_resize_method : decltype(has_resize_method_impl::check(nullptr)){};\ntemplate\nstruct is_comparable : decltype(is_comparable_impl::check(nullptr)){};\n\ntemplate class Tb, template class A>\nstruct has_from_toml_method\n: decltype(has_from_toml_method_impl::check(nullptr)){};\n\ntemplate\nstruct has_into_toml_method\n: decltype(has_into_toml_method_impl::check(nullptr)){};\n\n#ifdef __INTEL_COMPILER\n#undef decltype(...)\n#endif\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ C++17 and\/or\/not\n\ntemplate struct conjunction : std::true_type{};\ntemplate struct conjunction : T{};\ntemplate\nstruct conjunction :\n std::conditional(T::value), conjunction, T>::type\n{};\n\ntemplate struct disjunction : std::false_type{};\ntemplate struct disjunction : T {};\ntemplate\nstruct disjunction :\n std::conditional(T::value), T, disjunction>::type\n{};\n\ntemplate\nstruct negation : std::integral_constant(T::value)>{};\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ type checkers\n\ntemplate struct is_std_pair : std::false_type{};\ntemplate\nstruct is_std_pair> : std::true_type{};\n\ntemplate struct is_std_tuple : std::false_type{};\ntemplate\nstruct is_std_tuple> : std::true_type{};\n\ntemplate struct is_chrono_duration: std::false_type{};\ntemplate\nstruct is_chrono_duration>: std::true_type{};\n\ntemplate\nstruct is_map : conjunction< \/\/ map satisfies all the following conditions\n has_iterator, \/\/ has T::iterator\n has_value_type, \/\/ has T::value_type\n has_key_type, \/\/ has T::key_type\n has_mapped_type \/\/ has T::mapped_type\n >{};\ntemplate struct is_map : is_map{};\ntemplate struct is_map : is_map{};\ntemplate struct is_map : is_map{};\ntemplate struct is_map : is_map{};\n\ntemplate\nstruct is_container : conjunction<\n negation>, \/\/ not a map\n negation>, \/\/ not a std::string\n#if __cplusplus >= 201703L\n negation>, \/\/ not a std::string_view\n#endif\n has_iterator, \/\/ has T::iterator\n has_value_type \/\/ has T::value_type\n >{};\ntemplate struct is_container : is_container{};\ntemplate struct is_container : is_container{};\ntemplate struct is_container : is_container{};\ntemplate struct is_container : is_container{};\n\ntemplate\nstruct is_basic_value: std::false_type{};\ntemplate struct is_basic_value : is_basic_value{};\ntemplate struct is_basic_value : is_basic_value{};\ntemplate struct is_basic_value : is_basic_value{};\ntemplate struct is_basic_value : is_basic_value{};\ntemplate class M, template class V>\nstruct is_basic_value<::toml::basic_value>: std::true_type{};\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ C++14 index_sequence\n\ntemplate struct index_sequence{};\n\ntemplate struct push_back_index_sequence{};\ntemplate\nstruct push_back_index_sequence, N>\n{\n typedef index_sequence type;\n};\n\ntemplate\nstruct index_sequence_maker\n{\n typedef typename push_back_index_sequence<\n typename index_sequence_maker::type, N>::type type;\n};\ntemplate<>\nstruct index_sequence_maker<0>\n{\n typedef index_sequence<0> type;\n};\ntemplate\nusing make_index_sequence = typename index_sequence_maker::type;\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ C++14 enable_if_t\ntemplate\nusing enable_if_t = typename std::enable_if::type;\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ return_type_of_t\n\n#if __cplusplus >= 201703L\n\ntemplate\nusing return_type_of_t = std::invoke_result_t;\n\n#else\n\/\/ result_of is deprecated after C++17\ntemplate\nusing return_type_of_t = typename std::result_of::type;\n\n#endif\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ is_string_literal\n\/\/\n\/\/ to use this, pass `typename remove_reference::type` to T.\n\ntemplate\nstruct is_string_literal:\ndisjunction<\n std::is_same,\n conjunction<\n std::is_array,\n std::is_same::type>\n >\n >{};\n\n}\/\/ detail\n}\/\/toml\n#endif \/\/ TOML_TRAITS\nrefactor: add utility meta-func for internal use\/\/ Copyright Toru Niina 2017.\n\/\/ Distributed under the MIT License.\n#ifndef TOML11_TRAITS_HPP\n#define TOML11_TRAITS_HPP\n#include \n#include \n#include \n#include \n#include \n#if __cplusplus >= 201703L\n#if __has_include()\n#include \n#endif \/\/ has_include()\n#endif \/\/ cplusplus >= C++17\n\nnamespace toml\n{\ntemplate class T, template class A>\nclass basic_value;\n\nnamespace detail\n{\n\/\/ ---------------------------------------------------------------------------\n\/\/ check whether type T is a kind of container\/map class\n\nstruct has_iterator_impl\n{\n template static std::true_type check(typename T::iterator*);\n template static std::false_type check(...);\n};\nstruct has_value_type_impl\n{\n template static std::true_type check(typename T::value_type*);\n template static std::false_type check(...);\n};\nstruct has_key_type_impl\n{\n template static std::true_type check(typename T::key_type*);\n template static std::false_type check(...);\n};\nstruct has_mapped_type_impl\n{\n template static std::true_type check(typename T::mapped_type*);\n template static std::false_type check(...);\n};\nstruct has_resize_method_impl\n{\n constexpr static std::size_t dummy=0;\n template static std::true_type check(decltype(std::declval().resize(dummy))*);\n template static std::false_type check(...);\n};\n\nstruct is_comparable_impl\n{\n template static std::true_type check(decltype(std::declval() < std::declval())*);\n template static std::false_type check(...);\n};\n\nstruct has_from_toml_method_impl\n{\n template class Tb, template class A>\n static std::true_type check(\n decltype(std::declval().from_toml(\n std::declval<::toml::basic_value>()))*);\n\n template class Tb, template class A>\n static std::false_type check(...);\n};\nstruct has_into_toml_method_impl\n{\n template\n static std::true_type check(decltype(std::declval().into_toml())*);\n template\n static std::false_type check(...);\n};\n\n\/\/\/ Intel C++ compiler can not use decltype in parent class declaration, here\n\/\/\/ is a hack to work around it. https:\/\/stackoverflow.com\/a\/23953090\/4692076\n#ifdef __INTEL_COMPILER\n#define decltype(...) std::enable_if::type\n#endif\n\ntemplate\nstruct has_iterator : decltype(has_iterator_impl::check(nullptr)){};\ntemplate\nstruct has_value_type : decltype(has_value_type_impl::check(nullptr)){};\ntemplate\nstruct has_key_type : decltype(has_key_type_impl::check(nullptr)){};\ntemplate\nstruct has_mapped_type : decltype(has_mapped_type_impl::check(nullptr)){};\ntemplate\nstruct has_resize_method : decltype(has_resize_method_impl::check(nullptr)){};\ntemplate\nstruct is_comparable : decltype(is_comparable_impl::check(nullptr)){};\n\ntemplate class Tb, template class A>\nstruct has_from_toml_method\n: decltype(has_from_toml_method_impl::check(nullptr)){};\n\ntemplate\nstruct has_into_toml_method\n: decltype(has_into_toml_method_impl::check(nullptr)){};\n\n#ifdef __INTEL_COMPILER\n#undef decltype(...)\n#endif\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ C++17 and\/or\/not\n\ntemplate struct conjunction : std::true_type{};\ntemplate struct conjunction : T{};\ntemplate\nstruct conjunction :\n std::conditional(T::value), conjunction, T>::type\n{};\n\ntemplate struct disjunction : std::false_type{};\ntemplate struct disjunction : T {};\ntemplate\nstruct disjunction :\n std::conditional(T::value), T, disjunction>::type\n{};\n\ntemplate\nstruct negation : std::integral_constant(T::value)>{};\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ type checkers\n\ntemplate struct is_std_pair : std::false_type{};\ntemplate\nstruct is_std_pair> : std::true_type{};\n\ntemplate struct is_std_tuple : std::false_type{};\ntemplate\nstruct is_std_tuple> : std::true_type{};\n\ntemplate struct is_chrono_duration: std::false_type{};\ntemplate\nstruct is_chrono_duration>: std::true_type{};\n\ntemplate\nstruct is_map : conjunction< \/\/ map satisfies all the following conditions\n has_iterator, \/\/ has T::iterator\n has_value_type, \/\/ has T::value_type\n has_key_type, \/\/ has T::key_type\n has_mapped_type \/\/ has T::mapped_type\n >{};\ntemplate struct is_map : is_map{};\ntemplate struct is_map : is_map{};\ntemplate struct is_map : is_map{};\ntemplate struct is_map : is_map{};\n\ntemplate\nstruct is_container : conjunction<\n negation>, \/\/ not a map\n negation>, \/\/ not a std::string\n#if __cplusplus >= 201703L\n negation>, \/\/ not a std::string_view\n#endif\n has_iterator, \/\/ has T::iterator\n has_value_type \/\/ has T::value_type\n >{};\ntemplate struct is_container : is_container{};\ntemplate struct is_container : is_container{};\ntemplate struct is_container : is_container{};\ntemplate struct is_container : is_container{};\n\ntemplate\nstruct is_basic_value: std::false_type{};\ntemplate struct is_basic_value : is_basic_value{};\ntemplate struct is_basic_value : is_basic_value{};\ntemplate struct is_basic_value : is_basic_value{};\ntemplate struct is_basic_value : is_basic_value{};\ntemplate class M, template class V>\nstruct is_basic_value<::toml::basic_value>: std::true_type{};\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ C++14 index_sequence\n\ntemplate struct index_sequence{};\n\ntemplate struct push_back_index_sequence{};\ntemplate\nstruct push_back_index_sequence, N>\n{\n typedef index_sequence type;\n};\n\ntemplate\nstruct index_sequence_maker\n{\n typedef typename push_back_index_sequence<\n typename index_sequence_maker::type, N>::type type;\n};\ntemplate<>\nstruct index_sequence_maker<0>\n{\n typedef index_sequence<0> type;\n};\ntemplate\nusing make_index_sequence = typename index_sequence_maker::type;\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ C++14 enable_if_t\ntemplate\nusing enable_if_t = typename std::enable_if::type;\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ return_type_of_t\n\n#if __cplusplus >= 201703L\n\ntemplate\nusing return_type_of_t = std::invoke_result_t;\n\n#else\n\/\/ result_of is deprecated after C++17\ntemplate\nusing return_type_of_t = typename std::result_of::type;\n\n#endif\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ is_string_literal\n\/\/\n\/\/ to use this, pass `typename remove_reference::type` to T.\n\ntemplate\nstruct is_string_literal:\ndisjunction<\n std::is_same,\n conjunction<\n std::is_array,\n std::is_same::type>\n >\n >{};\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ C++20 remove_cvref_t\n\ntemplate\nstruct remove_cvref\n{\n using type = typename std::remove_cv<\n typename std::remove_reference::type>::type;\n};\n\ntemplate\nusing remove_cvref_t = typename remove_cvref::type;\n\n}\/\/ detail\n}\/\/toml\n#endif \/\/ TOML_TRAITS\n<|endoftext|>"} {"text":"#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \"opencv2\/gpu\/gpu.hpp\"\r\n#include \"opencv2\/highgui\/highgui.hpp\"\r\n\r\nusing namespace cv;\r\nusing namespace std;\r\n\r\n\r\nstruct Params\r\n{\r\n Params();\r\n static Params read(int argc, char** argv);\r\n\r\n string left;\r\n string right;\r\n\r\n string method_str() const\r\n {\r\n switch (method)\r\n {\r\n case BM: return \"BM\";\r\n case BP: return \"BP\";\r\n case CSBP: return \"CSBP\";\r\n }\r\n return \"\";\r\n }\r\n enum {BM, BP, CSBP} method;\r\n int ndisp; \/\/ Max disparity + 1\r\n};\r\n\r\n\r\nstruct App\r\n{\r\n App(const Params& p);\r\n void run();\r\n void handleKey(char key);\r\n void printParams() const;\r\n\r\n void workBegin() { work_begin = getTickCount(); }\r\n void workEnd() \r\n {\r\n int64 d = getTickCount() - work_begin;\r\n double f = getTickFrequency();\r\n work_fps = f \/ d;\r\n }\r\n\r\n string text() const\r\n {\r\n stringstream ss;\r\n ss << \"(\" << p.method_str() << \") FPS: \" << setiosflags(ios::left) << setprecision(4) << work_fps;\r\n return ss.str();\r\n }\r\nprivate:\r\n Params p;\r\n bool running;\r\n\r\n Mat left_src, right_src;\r\n Mat left, right; \r\n gpu::GpuMat d_left, d_right;\r\n\r\n gpu::StereoBM_GPU bm;\r\n gpu::StereoBeliefPropagation bp;\r\n gpu::StereoConstantSpaceBP csbp;\r\n\r\n int64 work_begin;\r\n double work_fps;\r\n};\r\n\r\n\r\nint main(int argc, char** argv)\r\n{\r\n try\r\n {\r\n if (argc < 2)\r\n {\r\n cout << \"Usage: stereo_match_gpu\\n\"\r\n << \"\\t-l -r # must be rectified\\n\"\r\n << \"\\t-m # bm | bp | csbp\\n\";\r\n return 1;\r\n }\r\n App app(Params::read(argc, argv));\r\n app.run();\r\n }\r\n catch (const exception& e)\r\n {\r\n cout << \"error: \" << e.what() << endl;\r\n }\r\n return 0;\r\n}\r\n\r\n\r\nParams::Params()\r\n{\r\n method = BM;\r\n ndisp = 64;\r\n}\r\n\r\n\r\nParams Params::read(int argc, char** argv)\r\n{\r\n Params p;\r\n\r\n for (int i = 1; i < argc - 1; i += 2)\r\n {\r\n string key = argv[i];\r\n string val = argv[i + 1];\r\n if (key == \"-l\") p.left = val;\r\n else if (key == \"-r\") p.right = val;\r\n else if (key == \"-m\") \r\n {\r\n if (val == \"BM\") p.method = BM;\r\n else if (val == \"BP\") p.method = BP;\r\n else if (val == \"CSBP\") p.method = CSBP;\r\n else throw runtime_error(\"unknown stereo match method: \" + val);\r\n }\r\n else if (key == \"-ndisp\") p.ndisp = atoi(val.c_str());\r\n else throw runtime_error(\"unknown key: \" + key);\r\n }\r\n\r\n return p;\r\n}\r\n\r\n\r\nApp::App(const Params& p)\r\n : p(p), running(false) \r\n{\r\n cout << \"stereo_match_gpu sample\\n\";\r\n cout << \"\\nControls:\\n\"\r\n << \"\\tesc - exit\\n\"\r\n << \"\\tp - print current parameters\\n\"\r\n << \"\\tg - convert source images into gray\\n\"\r\n << \"\\tm - change stereo match method\\n\"\r\n << \"\\ts - change Sobel prefiltering flag (for BM only)\\n\"\r\n << \"\\t1\/q - increase\/decrease maximum disparity\\n\"\r\n << \"\\t2\/w - increase\/decrease window size (for BM only)\\n\"\r\n << \"\\t3\/e - increase\/decrease iteration count (for BP and CSBP only)\\n\"\r\n << \"\\t4\/r - increase\/decrease level count (for BP and CSBP only)\\n\";\r\n}\r\n\r\n\r\nvoid App::run()\r\n{\r\n \/\/ Load images\r\n left_src = imread(p.left);\r\n right_src = imread(p.right);\r\n if (left_src.empty()) throw runtime_error(\"can't open file \\\"\" + p.left + \"\\\"\");\r\n if (right_src.empty()) throw runtime_error(\"can't open file \\\"\" + p.right + \"\\\"\");\r\n cvtColor(left_src, left, CV_BGR2GRAY);\r\n cvtColor(right_src, right, CV_BGR2GRAY);\r\n d_left = left;\r\n d_right = right;\r\n\r\n imshow(\"left\", left);\r\n imshow(\"right\", right);\r\n\r\n\t\/\/ Set common parameters\r\n bm.ndisp = p.ndisp;\r\n bp.ndisp = p.ndisp;\r\n csbp.ndisp = p.ndisp;\r\n\r\n \/\/ Prepare disparity map of specified type\r\n Mat disp(left.size(), CV_8U);\r\n gpu::GpuMat d_disp(left.size(), CV_8U);\r\n\r\n cout << endl;\r\n printParams();\r\n\r\n running = true;\r\n while (running)\r\n {\r\n workBegin();\r\n switch (p.method)\r\n {\r\n case Params::BM: \r\n if (d_left.channels() > 1 || d_right.channels() > 1)\r\n {\r\n cout << \"BM doesn't support color images\\n\";\r\n cvtColor(left_src, left, CV_BGR2GRAY);\r\n cvtColor(right_src, right, CV_BGR2GRAY);\r\n cout << \"image_channels: \" << left.channels() << endl;\r\n d_left = left;\r\n d_right = right;\r\n imshow(\"left\", left);\r\n imshow(\"right\", right);\r\n }\r\n bm(d_left, d_right, d_disp); \r\n break;\r\n case Params::BP: bp(d_left, d_right, d_disp); break;\r\n case Params::CSBP: csbp(d_left, d_right, d_disp); break;\r\n }\r\n workEnd();\r\n\r\n \/\/ Show results\r\n disp = d_disp;\r\n putText(disp, text(), Point(5, 25), FONT_HERSHEY_SIMPLEX, 1.0, Scalar::all(255));\r\n imshow(\"disparity\", disp);\r\n\r\n handleKey((char)waitKey(3));\r\n }\r\n}\r\n\r\n\r\nvoid App::printParams() const\r\n{\r\n cout << \"--- Parameters ---\\n\";\r\n cout << \"image_size: (\" << left.cols << \", \" << left.rows << \")\\n\";\r\n cout << \"image_channels: \" << left.channels() << endl;\r\n cout << \"method: \" << p.method_str() << endl\r\n << \"ndisp: \" << p.ndisp << endl;\r\n switch (p.method)\r\n {\r\n case Params::BM:\r\n cout << \"win_size: \" << bm.winSize << endl;\r\n cout << \"prefilter_sobel: \" << bm.preset << endl;\r\n break;\r\n case Params::BP:\r\n cout << \"iter_count: \" << bp.iters << endl;\r\n cout << \"level_count: \" << bp.levels << endl;\r\n break;\r\n case Params::CSBP:\r\n cout << \"iter_count: \" << csbp.iters << endl;\r\n cout << \"level_count: \" << csbp.levels << endl;\r\n break;\r\n }\r\n cout << endl;\r\n}\r\n\r\n\r\nvoid App::handleKey(char key)\r\n{\r\n switch (key)\r\n {\r\n case 27:\r\n running = false;\r\n break;\r\n case 'p': case 'P':\r\n printParams();\r\n break;\r\n case 'g': case 'G':\r\n if (left.channels() == 1 && p.method != Params::BM)\r\n {\r\n left = left_src;\r\n right = right_src;\r\n }\r\n else \r\n {\r\n cvtColor(left_src, left, CV_BGR2GRAY);\r\n cvtColor(right_src, right, CV_BGR2GRAY);\r\n }\r\n d_left = left;\r\n d_right = right;\r\n cout << \"image_channels: \" << left.channels() << endl;\r\n imshow(\"left\", left);\r\n imshow(\"right\", right);\r\n break;\r\n case 'm': case 'M':\r\n switch (p.method)\r\n {\r\n case Params::BM:\r\n p.method = Params::BP;\r\n break;\r\n case Params::BP:\r\n p.method = Params::CSBP;\r\n break;\r\n case Params::CSBP:\r\n p.method = Params::BM;\r\n break;\r\n }\r\n cout << \"method: \" << p.method_str() << endl;\r\n break;\r\n case 's': case 'S':\r\n if (p.method == Params::BM)\r\n {\r\n switch (bm.preset)\r\n {\r\n case gpu::StereoBM_GPU::BASIC_PRESET:\r\n bm.preset = gpu::StereoBM_GPU::PREFILTER_XSOBEL;\r\n break;\r\n case gpu::StereoBM_GPU::PREFILTER_XSOBEL:\r\n bm.preset = gpu::StereoBM_GPU::BASIC_PRESET;\r\n break;\r\n }\r\n cout << \"prefilter_sobel: \" << bm.preset << endl;\r\n }\r\n break;\r\n case '1':\r\n p.ndisp = p.ndisp == 1 ? 8 : p.ndisp + 8;\r\n cout << \"ndisp: \" << p.ndisp << endl;\r\n bm.ndisp = p.ndisp;\r\n bp.ndisp = p.ndisp;\r\n csbp.ndisp = p.ndisp;\r\n break;\r\n case 'q': case 'Q':\r\n p.ndisp = max(p.ndisp - 8, 1);\r\n cout << \"ndisp: \" << p.ndisp << endl;\r\n bm.ndisp = p.ndisp;\r\n bp.ndisp = p.ndisp;\r\n csbp.ndisp = p.ndisp;\r\n break;\r\n case '2':\r\n if (p.method == Params::BM)\r\n {\r\n bm.winSize = min(bm.winSize + 1, 51);\r\n cout << \"win_size: \" << bm.winSize << endl;\r\n }\r\n break;\r\n case 'w': case 'W':\r\n if (p.method == Params::BM)\r\n {\r\n bm.winSize = max(bm.winSize - 1, 2);\r\n cout << \"win_size: \" << bm.winSize << endl;\r\n }\r\n break;\r\n case '3':\r\n if (p.method == Params::BP)\r\n {\r\n bp.iters += 1;\r\n cout << \"iter_count: \" << bp.iters << endl;\r\n }\r\n else if (p.method == Params::CSBP)\r\n {\r\n csbp.iters += 1;\r\n cout << \"iter_count: \" << csbp.iters << endl;\r\n }\r\n break;\r\n case 'e': case 'E':\r\n if (p.method == Params::BP)\r\n {\r\n bp.iters = max(bp.iters - 1, 1);\r\n cout << \"iter_count: \" << bp.iters << endl;\r\n }\r\n else if (p.method == Params::CSBP)\r\n {\r\n csbp.iters = max(csbp.iters - 1, 1);\r\n cout << \"iter_count: \" << csbp.iters << endl;\r\n }\r\n break;\r\n case '4':\r\n if (p.method == Params::BP)\r\n {\r\n bp.levels += 1;\r\n cout << \"level_count: \" << bp.levels << endl;\r\n }\r\n else if (p.method == Params::CSBP)\r\n {\r\n csbp.levels += 1;\r\n cout << \"level_count: \" << csbp.levels << endl;\r\n }\r\n break;\r\n case 'r': case 'R':\r\n if (p.method == Params::BP)\r\n {\r\n bp.levels = max(bp.levels - 1, 1);\r\n cout << \"level_count: \" << bp.levels << endl;\r\n }\r\n else if (p.method == Params::CSBP)\r\n {\r\n csbp.levels = max(csbp.levels - 1, 1);\r\n cout << \"level_count: \" << csbp.levels << endl;\r\n }\r\n break;\r\n }\r\n}\r\n\r\n\r\nminor changes in the gpu stereo sample#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \"opencv2\/gpu\/gpu.hpp\"\r\n#include \"opencv2\/highgui\/highgui.hpp\"\r\n\r\nusing namespace cv;\r\nusing namespace std;\r\n\r\n\r\nstruct Params\r\n{\r\n Params();\r\n static Params read(int argc, char** argv);\r\n\r\n string left;\r\n string right;\r\n\r\n string method_str() const\r\n {\r\n switch (method)\r\n {\r\n case BM: return \"BM\";\r\n case BP: return \"BP\";\r\n case CSBP: return \"CSBP\";\r\n }\r\n return \"\";\r\n }\r\n enum {BM, BP, CSBP} method;\r\n int ndisp; \/\/ Max disparity + 1\r\n};\r\n\r\n\r\nstruct App\r\n{\r\n App(const Params& p);\r\n void run();\r\n void handleKey(char key);\r\n void printParams() const;\r\n\r\n void workBegin() { work_begin = getTickCount(); }\r\n void workEnd() \r\n {\r\n int64 d = getTickCount() - work_begin;\r\n double f = getTickFrequency();\r\n work_fps = f \/ d;\r\n }\r\n\r\n string text() const\r\n {\r\n stringstream ss;\r\n ss << \"(\" << p.method_str() << \") FPS: \" << setiosflags(ios::left)\r\n << setprecision(4) << work_fps;\r\n return ss.str();\r\n }\r\nprivate:\r\n Params p;\r\n bool running;\r\n\r\n Mat left_src, right_src;\r\n Mat left, right; \r\n gpu::GpuMat d_left, d_right;\r\n\r\n gpu::StereoBM_GPU bm;\r\n gpu::StereoBeliefPropagation bp;\r\n gpu::StereoConstantSpaceBP csbp;\r\n\r\n int64 work_begin;\r\n double work_fps;\r\n};\r\n\r\n\r\nint main(int argc, char** argv)\r\n{\r\n try\r\n {\r\n if (argc < 2)\r\n {\r\n cout << \"Usage: stereo_match_gpu\\n\"\r\n << \"\\t-l -r # must be rectified\\n\"\r\n << \"\\t-m # BM | BP | CSBP\\n\";\r\n return 1;\r\n }\r\n App app(Params::read(argc, argv));\r\n app.run();\r\n }\r\n catch (const exception& e)\r\n {\r\n cout << \"error: \" << e.what() << endl;\r\n }\r\n return 0;\r\n}\r\n\r\n\r\nParams::Params()\r\n{\r\n method = BM;\r\n ndisp = 64;\r\n}\r\n\r\n\r\nParams Params::read(int argc, char** argv)\r\n{\r\n Params p;\r\n\r\n for (int i = 1; i < argc - 1; i += 2)\r\n {\r\n string key = argv[i];\r\n string val = argv[i + 1];\r\n if (key == \"-l\") p.left = val;\r\n else if (key == \"-r\") p.right = val;\r\n else if (key == \"-m\") \r\n {\r\n if (val == \"BM\") p.method = BM;\r\n else if (val == \"BP\") p.method = BP;\r\n else if (val == \"CSBP\") p.method = CSBP;\r\n else throw runtime_error(\"unknown stereo match method: \" + val);\r\n }\r\n else if (key == \"-ndisp\") p.ndisp = atoi(val.c_str());\r\n else throw runtime_error(\"unknown key: \" + key);\r\n }\r\n\r\n return p;\r\n}\r\n\r\n\r\nApp::App(const Params& p)\r\n : p(p), running(false) \r\n{\r\n cout << \"stereo_match_gpu sample\\n\";\r\n cout << \"\\nControls:\\n\"\r\n << \"\\tesc - exit\\n\"\r\n << \"\\tp - print current parameters\\n\"\r\n << \"\\tg - convert source images into gray\\n\"\r\n << \"\\tm - change stereo match method\\n\"\r\n << \"\\ts - change Sobel prefiltering flag (for BM only)\\n\"\r\n << \"\\t1\/q - increase\/decrease maximum disparity\\n\"\r\n << \"\\t2\/w - increase\/decrease window size (for BM only)\\n\"\r\n << \"\\t3\/e - increase\/decrease iteration count (for BP and CSBP only)\\n\"\r\n << \"\\t4\/r - increase\/decrease level count (for BP and CSBP only)\\n\";\r\n}\r\n\r\n\r\nvoid App::run()\r\n{\r\n \/\/ Load images\r\n left_src = imread(p.left);\r\n right_src = imread(p.right);\r\n if (left_src.empty()) throw runtime_error(\"can't open file \\\"\" + p.left + \"\\\"\");\r\n if (right_src.empty()) throw runtime_error(\"can't open file \\\"\" + p.right + \"\\\"\");\r\n cvtColor(left_src, left, CV_BGR2GRAY);\r\n cvtColor(right_src, right, CV_BGR2GRAY);\r\n d_left = left;\r\n d_right = right;\r\n\r\n imshow(\"left\", left);\r\n imshow(\"right\", right);\r\n\r\n\t\/\/ Set common parameters\r\n bm.ndisp = p.ndisp;\r\n bp.ndisp = p.ndisp;\r\n csbp.ndisp = p.ndisp;\r\n\r\n \/\/ Prepare disparity map of specified type\r\n Mat disp(left.size(), CV_8U);\r\n gpu::GpuMat d_disp(left.size(), CV_8U);\r\n\r\n cout << endl;\r\n printParams();\r\n\r\n running = true;\r\n while (running)\r\n {\r\n workBegin();\r\n switch (p.method)\r\n {\r\n case Params::BM: \r\n if (d_left.channels() > 1 || d_right.channels() > 1)\r\n {\r\n cout << \"BM doesn't support color images\\n\";\r\n cvtColor(left_src, left, CV_BGR2GRAY);\r\n cvtColor(right_src, right, CV_BGR2GRAY);\r\n cout << \"image_channels: \" << left.channels() << endl;\r\n d_left = left;\r\n d_right = right;\r\n imshow(\"left\", left);\r\n imshow(\"right\", right);\r\n }\r\n bm(d_left, d_right, d_disp); \r\n break;\r\n case Params::BP: bp(d_left, d_right, d_disp); break;\r\n case Params::CSBP: csbp(d_left, d_right, d_disp); break;\r\n }\r\n workEnd();\r\n\r\n \/\/ Show results\r\n disp = d_disp;\r\n putText(disp, text(), Point(5, 25), FONT_HERSHEY_SIMPLEX, 1.0, Scalar::all(255));\r\n imshow(\"disparity\", disp);\r\n\r\n handleKey((char)waitKey(3));\r\n }\r\n}\r\n\r\n\r\nvoid App::printParams() const\r\n{\r\n cout << \"--- Parameters ---\\n\";\r\n cout << \"image_size: (\" << left.cols << \", \" << left.rows << \")\\n\";\r\n cout << \"image_channels: \" << left.channels() << endl;\r\n cout << \"method: \" << p.method_str() << endl\r\n << \"ndisp: \" << p.ndisp << endl;\r\n switch (p.method)\r\n {\r\n case Params::BM:\r\n cout << \"win_size: \" << bm.winSize << endl;\r\n cout << \"prefilter_sobel: \" << bm.preset << endl;\r\n break;\r\n case Params::BP:\r\n cout << \"iter_count: \" << bp.iters << endl;\r\n cout << \"level_count: \" << bp.levels << endl;\r\n break;\r\n case Params::CSBP:\r\n cout << \"iter_count: \" << csbp.iters << endl;\r\n cout << \"level_count: \" << csbp.levels << endl;\r\n break;\r\n }\r\n cout << endl;\r\n}\r\n\r\n\r\nvoid App::handleKey(char key)\r\n{\r\n switch (key)\r\n {\r\n case 27:\r\n running = false;\r\n break;\r\n case 'p': case 'P':\r\n printParams();\r\n break; \r\n case 'g': case 'G':\r\n if (left.channels() == 1 && p.method != Params::BM)\r\n {\r\n left = left_src;\r\n right = right_src;\r\n }\r\n else \r\n {\r\n cvtColor(left_src, left, CV_BGR2GRAY);\r\n cvtColor(right_src, right, CV_BGR2GRAY);\r\n }\r\n d_left = left;\r\n d_right = right;\r\n cout << \"image_channels: \" << left.channels() << endl;\r\n imshow(\"left\", left);\r\n imshow(\"right\", right);\r\n break;\r\n case 'm': case 'M':\r\n switch (p.method)\r\n {\r\n case Params::BM:\r\n p.method = Params::BP;\r\n break;\r\n case Params::BP:\r\n p.method = Params::CSBP;\r\n break;\r\n case Params::CSBP:\r\n p.method = Params::BM;\r\n break;\r\n }\r\n cout << \"method: \" << p.method_str() << endl;\r\n break;\r\n case 's': case 'S':\r\n if (p.method == Params::BM)\r\n {\r\n switch (bm.preset)\r\n {\r\n case gpu::StereoBM_GPU::BASIC_PRESET:\r\n bm.preset = gpu::StereoBM_GPU::PREFILTER_XSOBEL;\r\n break;\r\n case gpu::StereoBM_GPU::PREFILTER_XSOBEL:\r\n bm.preset = gpu::StereoBM_GPU::BASIC_PRESET;\r\n break;\r\n }\r\n cout << \"prefilter_sobel: \" << bm.preset << endl;\r\n }\r\n break;\r\n case '1':\r\n p.ndisp = p.ndisp == 1 ? 8 : p.ndisp + 8;\r\n cout << \"ndisp: \" << p.ndisp << endl;\r\n bm.ndisp = p.ndisp;\r\n bp.ndisp = p.ndisp;\r\n csbp.ndisp = p.ndisp;\r\n break;\r\n case 'q': case 'Q':\r\n p.ndisp = max(p.ndisp - 8, 1);\r\n cout << \"ndisp: \" << p.ndisp << endl;\r\n bm.ndisp = p.ndisp;\r\n bp.ndisp = p.ndisp;\r\n csbp.ndisp = p.ndisp;\r\n break;\r\n case '2':\r\n if (p.method == Params::BM)\r\n {\r\n bm.winSize = min(bm.winSize + 1, 51);\r\n cout << \"win_size: \" << bm.winSize << endl;\r\n }\r\n break;\r\n case 'w': case 'W':\r\n if (p.method == Params::BM)\r\n {\r\n bm.winSize = max(bm.winSize - 1, 2);\r\n cout << \"win_size: \" << bm.winSize << endl;\r\n }\r\n break;\r\n case '3':\r\n if (p.method == Params::BP)\r\n {\r\n bp.iters += 1;\r\n cout << \"iter_count: \" << bp.iters << endl;\r\n }\r\n else if (p.method == Params::CSBP)\r\n {\r\n csbp.iters += 1;\r\n cout << \"iter_count: \" << csbp.iters << endl;\r\n }\r\n break;\r\n case 'e': case 'E':\r\n if (p.method == Params::BP)\r\n {\r\n bp.iters = max(bp.iters - 1, 1);\r\n cout << \"iter_count: \" << bp.iters << endl;\r\n }\r\n else if (p.method == Params::CSBP)\r\n {\r\n csbp.iters = max(csbp.iters - 1, 1);\r\n cout << \"iter_count: \" << csbp.iters << endl;\r\n }\r\n break;\r\n case '4':\r\n if (p.method == Params::BP)\r\n {\r\n bp.levels += 1;\r\n cout << \"level_count: \" << bp.levels << endl;\r\n }\r\n else if (p.method == Params::CSBP)\r\n {\r\n csbp.levels += 1;\r\n cout << \"level_count: \" << csbp.levels << endl;\r\n }\r\n break;\r\n case 'r': case 'R':\r\n if (p.method == Params::BP)\r\n {\r\n bp.levels = max(bp.levels - 1, 1);\r\n cout << \"level_count: \" << bp.levels << endl;\r\n }\r\n else if (p.method == Params::CSBP)\r\n {\r\n csbp.levels = max(csbp.levels - 1, 1);\r\n cout << \"level_count: \" << csbp.levels << endl;\r\n }\r\n break;\r\n }\r\n}\r\n\r\n\r\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: prevloc.hxx,v $\n *\n * $Revision: 1.11 $\n *\n * last change: $Author: rt $ $Date: 2005-09-08 21:45:04 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef SC_PREVLOC_HXX\n#define SC_PREVLOC_HXX\n\n#ifndef SC_ADDRESS_HXX\n#include \"address.hxx\"\n#endif\n\n#ifndef _LIST_HXX\n#include \n#endif\n\n#ifndef _SV_MAPMOD_HXX\n#include \n#endif\n\n#ifndef _SAL_TYPES_H_\n#include \n#endif\n\n\n#define SC_PREVIEW_MAXRANGES 4\n#define SC_PREVIEW_RANGE_EDGE 0\n#define SC_PREVIEW_RANGE_REPCOL 1\n#define SC_PREVIEW_RANGE_REPROW 2\n#define SC_PREVIEW_RANGE_TAB 3\n\nclass OutputDevice;\nclass String;\nclass Point;\nclass Rectangle;\nclass ScAddress;\nclass ScRange;\nclass ScDocument;\n\nstruct ScPreviewColRowInfo\n{\n BOOL bIsHeader;\n SCCOLROW nDocIndex;\n long nPixelStart;\n long nPixelEnd;\n\n void Set( BOOL bHeader, SCCOLROW nIndex, long nStart, long nEnd )\n {\n bIsHeader = bHeader;\n nDocIndex = nIndex;\n nPixelStart = nStart;\n nPixelEnd = nEnd;\n }\n};\n\nclass ScPreviewTableInfo\n{\n SCTAB nTab;\n SCCOL nCols;\n SCROW nRows;\n ScPreviewColRowInfo* pColInfo;\n ScPreviewColRowInfo* pRowInfo;\n\npublic:\n ScPreviewTableInfo();\n ~ScPreviewTableInfo();\n\n SCTAB GetTab() const { return nTab; }\n SCCOL GetCols() const { return nCols; }\n SCROW GetRows() const { return nRows; }\n const ScPreviewColRowInfo* GetColInfo() const { return pColInfo; }\n const ScPreviewColRowInfo* GetRowInfo() const { return pRowInfo; }\n\n void SetTab( SCTAB nNewTab );\n void SetColInfo( SCCOL nCount, ScPreviewColRowInfo* pNewInfo );\n void SetRowInfo( SCROW nCount, ScPreviewColRowInfo* pNewInfo );\n void LimitToArea( const Rectangle& rPixelArea );\n};\n\n\nclass ScPreviewLocationData\n{\n OutputDevice* pWindow;\n ScDocument* pDoc;\n MapMode aCellMapMode;\n MapMode aDrawMapMode[SC_PREVIEW_MAXRANGES];\n Rectangle aDrawRectangle[SC_PREVIEW_MAXRANGES];\n sal_uInt8 aDrawRangeId[SC_PREVIEW_MAXRANGES];\n USHORT nDrawRanges;\n SCTAB nPrintTab;\n List aEntries;\n\n ScAddress GetCellFromRange( const Size& rOffsetPixel, const ScRange& rRange ) const;\n Rectangle GetOffsetPixel( const ScAddress& rCellPos, const ScRange& rRange ) const;\n\npublic:\n ScPreviewLocationData( ScDocument* pDocument, OutputDevice* pWin );\n ~ScPreviewLocationData();\n\n void SetCellMapMode( const MapMode& rMapMode );\n void SetPrintTab( SCTAB nNew );\n void Clear();\n void AddCellRange( const Rectangle& rRect, const ScRange& rRange, BOOL bRepCol, BOOL bRepRow,\n const MapMode& rDrawMap );\n void AddColHeaders( const Rectangle& rRect, SCCOL nStartCol, SCCOL nEndCol, BOOL bRepCol );\n void AddRowHeaders( const Rectangle& rRect, SCROW nStartRow, SCROW nEndRow, BOOL bRepRow );\n void AddHeaderFooter( const Rectangle& rRect, BOOL bHeader, BOOL bLeft );\n void AddNoteMark( const Rectangle& rRect, const ScAddress& rPos );\n void AddNoteText( const Rectangle& rRect, const ScAddress& rPos );\n\n SCTAB GetPrintTab() const { return nPrintTab; }\n\n \/\/ Get info on visible columns\/rows in the visible area\n void GetTableInfo( const Rectangle& rVisiblePixel, ScPreviewTableInfo& rInfo ) const;\n\n USHORT GetDrawRanges() const { return nDrawRanges; }\n void GetDrawRange( USHORT nPos, Rectangle& rPixelRect, MapMode& rMapMode, sal_uInt8& rRangeId ) const;\n\n BOOL GetHeaderPosition( Rectangle& rHeaderRect ) const;\n BOOL GetFooterPosition( Rectangle& rFooterRect ) const;\n BOOL IsHeaderLeft() const;\n BOOL IsFooterLeft() const;\n\n long GetNoteCountInRange( const Rectangle& rVisiblePixel, BOOL bNoteMarks ) const;\n BOOL GetNoteInRange( const Rectangle& rVisiblePixel, long nIndex, BOOL bNoteMarks,\n ScAddress& rCellPos, Rectangle& rNoteRect ) const;\n Rectangle GetNoteInRangeOutputRect(const Rectangle& rVisiblePixel, BOOL bNoteMarks,\n const ScAddress& aCellPos) const;\n\n \/\/ Check if any cells (including column\/row headers) are in the visible area\n BOOL HasCellsInRange( const Rectangle& rVisiblePixel ) const;\n\n BOOL GetCell( const Point& rPos, ScAddress& rCellPos, Rectangle& rCellRect ) const;\n BOOL GetCellPosition( const ScAddress& rCellPos, Rectangle& rCellRect ) const;\n\n \/\/ returns the rectangle where the EditEngine draws the text of a Header Cell\n \/\/ if bColHeader is true it returns the rectangle of the header of the column in rCellPos\n \/\/ otherwise of the header of the row in rCellPos\n Rectangle GetHeaderCellOutputRect(const Rectangle& rVisRect, const ScAddress& rCellPos, sal_Bool bColHeader) const;\n Rectangle GetCellOutputRect(const ScAddress& rCellPos) const;\n\n \/\/ Query the range and rectangle of the main (non-repeat) cell range.\n \/\/ Returns FALSE if not contained.\n BOOL GetMainCellRange( ScRange& rRange, Rectangle& rPixRect ) const;\n};\n\n#endif\nINTEGRATION: CWS changefileheader (1.11.700); FILE MERGED 2008\/04\/01 15:30:59 thb 1.11.700.3: #i85898# Stripping all external header guards 2008\/04\/01 12:36:48 thb 1.11.700.2: #i85898# Stripping all external header guards 2008\/03\/31 17:15:46 rt 1.11.700.1: #i87441# Change license header to LPGL v3.\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2008 by Sun Microsystems, Inc.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: prevloc.hxx,v $\n * $Revision: 1.12 $\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * \n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n#ifndef SC_PREVLOC_HXX\n#define SC_PREVLOC_HXX\n\n#include \"address.hxx\"\n#include \n#include \n#include \n\n\n#define SC_PREVIEW_MAXRANGES 4\n#define SC_PREVIEW_RANGE_EDGE 0\n#define SC_PREVIEW_RANGE_REPCOL 1\n#define SC_PREVIEW_RANGE_REPROW 2\n#define SC_PREVIEW_RANGE_TAB 3\n\nclass OutputDevice;\nclass String;\nclass Point;\nclass Rectangle;\nclass ScAddress;\nclass ScRange;\nclass ScDocument;\n\nstruct ScPreviewColRowInfo\n{\n BOOL bIsHeader;\n SCCOLROW nDocIndex;\n long nPixelStart;\n long nPixelEnd;\n\n void Set( BOOL bHeader, SCCOLROW nIndex, long nStart, long nEnd )\n {\n bIsHeader = bHeader;\n nDocIndex = nIndex;\n nPixelStart = nStart;\n nPixelEnd = nEnd;\n }\n};\n\nclass ScPreviewTableInfo\n{\n SCTAB nTab;\n SCCOL nCols;\n SCROW nRows;\n ScPreviewColRowInfo* pColInfo;\n ScPreviewColRowInfo* pRowInfo;\n\npublic:\n ScPreviewTableInfo();\n ~ScPreviewTableInfo();\n\n SCTAB GetTab() const { return nTab; }\n SCCOL GetCols() const { return nCols; }\n SCROW GetRows() const { return nRows; }\n const ScPreviewColRowInfo* GetColInfo() const { return pColInfo; }\n const ScPreviewColRowInfo* GetRowInfo() const { return pRowInfo; }\n\n void SetTab( SCTAB nNewTab );\n void SetColInfo( SCCOL nCount, ScPreviewColRowInfo* pNewInfo );\n void SetRowInfo( SCROW nCount, ScPreviewColRowInfo* pNewInfo );\n void LimitToArea( const Rectangle& rPixelArea );\n};\n\n\nclass ScPreviewLocationData\n{\n OutputDevice* pWindow;\n ScDocument* pDoc;\n MapMode aCellMapMode;\n MapMode aDrawMapMode[SC_PREVIEW_MAXRANGES];\n Rectangle aDrawRectangle[SC_PREVIEW_MAXRANGES];\n sal_uInt8 aDrawRangeId[SC_PREVIEW_MAXRANGES];\n USHORT nDrawRanges;\n SCTAB nPrintTab;\n List aEntries;\n\n ScAddress GetCellFromRange( const Size& rOffsetPixel, const ScRange& rRange ) const;\n Rectangle GetOffsetPixel( const ScAddress& rCellPos, const ScRange& rRange ) const;\n\npublic:\n ScPreviewLocationData( ScDocument* pDocument, OutputDevice* pWin );\n ~ScPreviewLocationData();\n\n void SetCellMapMode( const MapMode& rMapMode );\n void SetPrintTab( SCTAB nNew );\n void Clear();\n void AddCellRange( const Rectangle& rRect, const ScRange& rRange, BOOL bRepCol, BOOL bRepRow,\n const MapMode& rDrawMap );\n void AddColHeaders( const Rectangle& rRect, SCCOL nStartCol, SCCOL nEndCol, BOOL bRepCol );\n void AddRowHeaders( const Rectangle& rRect, SCROW nStartRow, SCROW nEndRow, BOOL bRepRow );\n void AddHeaderFooter( const Rectangle& rRect, BOOL bHeader, BOOL bLeft );\n void AddNoteMark( const Rectangle& rRect, const ScAddress& rPos );\n void AddNoteText( const Rectangle& rRect, const ScAddress& rPos );\n\n SCTAB GetPrintTab() const { return nPrintTab; }\n\n \/\/ Get info on visible columns\/rows in the visible area\n void GetTableInfo( const Rectangle& rVisiblePixel, ScPreviewTableInfo& rInfo ) const;\n\n USHORT GetDrawRanges() const { return nDrawRanges; }\n void GetDrawRange( USHORT nPos, Rectangle& rPixelRect, MapMode& rMapMode, sal_uInt8& rRangeId ) const;\n\n BOOL GetHeaderPosition( Rectangle& rHeaderRect ) const;\n BOOL GetFooterPosition( Rectangle& rFooterRect ) const;\n BOOL IsHeaderLeft() const;\n BOOL IsFooterLeft() const;\n\n long GetNoteCountInRange( const Rectangle& rVisiblePixel, BOOL bNoteMarks ) const;\n BOOL GetNoteInRange( const Rectangle& rVisiblePixel, long nIndex, BOOL bNoteMarks,\n ScAddress& rCellPos, Rectangle& rNoteRect ) const;\n Rectangle GetNoteInRangeOutputRect(const Rectangle& rVisiblePixel, BOOL bNoteMarks,\n const ScAddress& aCellPos) const;\n\n \/\/ Check if any cells (including column\/row headers) are in the visible area\n BOOL HasCellsInRange( const Rectangle& rVisiblePixel ) const;\n\n BOOL GetCell( const Point& rPos, ScAddress& rCellPos, Rectangle& rCellRect ) const;\n BOOL GetCellPosition( const ScAddress& rCellPos, Rectangle& rCellRect ) const;\n\n \/\/ returns the rectangle where the EditEngine draws the text of a Header Cell\n \/\/ if bColHeader is true it returns the rectangle of the header of the column in rCellPos\n \/\/ otherwise of the header of the row in rCellPos\n Rectangle GetHeaderCellOutputRect(const Rectangle& rVisRect, const ScAddress& rCellPos, sal_Bool bColHeader) const;\n Rectangle GetCellOutputRect(const ScAddress& rCellPos) const;\n\n \/\/ Query the range and rectangle of the main (non-repeat) cell range.\n \/\/ Returns FALSE if not contained.\n BOOL GetMainCellRange( ScRange& rRange, Rectangle& rPixRect ) const;\n};\n\n#endif\n<|endoftext|>"} {"text":"#include \"Wren++.h\"\n#include \/\/ for malloc\n#include \/\/ for strcmp, memcpy\n#include \n#include \n\nnamespace\n{\n\nstruct BoundState\n{\n std::unordered_map< std::size_t, WrenForeignMethodFn > methods{};\n std::unordered_map< std::size_t, WrenForeignClassMethods > classes{};\n};\n\nWrenForeignMethodFn foreignMethodProvider(WrenVM* vm,\n const char* module,\n const char* className,\n bool isStatic,\n const char* signature)\n{\n auto* boundState = (BoundState*)wrenGetUserData(vm);\n auto it = boundState->methods.find(wrenpp::detail::hashMethodSignature(module, className, isStatic, signature));\n if (it == boundState->methods.end())\n {\n return NULL;\n }\n\n return it->second;\n}\n\nWrenForeignClassMethods foreignClassProvider(WrenVM* vm, const char* m, const char* c)\n{\n auto* boundState = (BoundState*)wrenGetUserData(vm);\n auto it = boundState->classes.find(wrenpp::detail::hashClassSignature(m, c));\n if (it == boundState->classes.end())\n {\n return WrenForeignClassMethods{ nullptr, nullptr };\n }\n\n return it->second;\n}\n\ninline const char* errorTypeToString(WrenErrorType type)\n{\n switch (type)\n {\n case WREN_ERROR_COMPILE: return \"WREN_ERROR_COMPILE\";\n case WREN_ERROR_RUNTIME: return \"WREN_ERROR_RUNTIME\";\n case WREN_ERROR_STACK_TRACE: return \"WREN_ERROR_STACK_TRACE\";\n default: assert(false); return \"\";\n }\n}\n\nchar* loadModuleFnWrapper(WrenVM* vm, const char* mod)\n{\n return wrenpp::VM::loadModuleFn(mod);\n}\n\nvoid writeFnWrapper(WrenVM* vm, const char* text)\n{\n wrenpp::VM::writeFn(text);\n}\n\nvoid errorFnWrapper(WrenVM*, WrenErrorType type, const char* module, int line, const char* message)\n{\n wrenpp::VM::errorFn(type, module, line, message);\n}\n\nvoid* reallocateFnWrapper(void* memory, std::size_t newSize)\n{\n return wrenpp::VM::reallocateFn(memory, newSize);\n}\n\n}\n\nnamespace wrenpp\n{\n\nnamespace detail\n{\nvoid registerFunction(WrenVM* vm, const std::string& mod, const std::string& cName, bool isStatic, std::string sig, WrenForeignMethodFn function)\n{\n BoundState* boundState = (BoundState*)wrenGetUserData(vm);\n std::size_t hash = detail::hashMethodSignature(mod.c_str(), cName.c_str(), isStatic, sig.c_str());\n boundState->methods.insert(std::make_pair(hash, function));\n}\n\nvoid registerClass(WrenVM* vm, const std::string& mod, std::string cName, WrenForeignClassMethods methods)\n{\n BoundState* boundState = (BoundState*)wrenGetUserData(vm);\n std::size_t hash = detail::hashClassSignature(mod.c_str(), cName.c_str());\n boundState->classes.insert(std::make_pair(hash, methods));\n}\n\n}\n\nValue null = Value();\n\nValue::Value(bool val)\n : type_{ WREN_TYPE_BOOL }, string_{ nullptr }\n{\n set(val);\n}\n\nValue::Value(float val)\n : type_{ WREN_TYPE_NUM }, string_{ nullptr }\n{\n set(val);\n}\n\nValue::Value(double val)\n : type_{ WREN_TYPE_NUM }, string_{ nullptr }\n{\n set(val);\n}\n\nValue::Value(int val)\n : type_{ WREN_TYPE_NUM }, string_{ nullptr }\n{\n set(val);\n}\n\nValue::Value(unsigned int val)\n : type_{ WREN_TYPE_NUM }, string_{ nullptr }\n{\n set(val);\n}\n\nValue::Value(const char* str)\n : type_{ WREN_TYPE_STRING }, string_{ nullptr }\n{\n string_ = (char*)VM::reallocateFn(nullptr, std::strlen(str) + 1);\n std::strcpy(string_, str);\n}\n\nValue::~Value()\n{\n if (string_)\n {\n VM::reallocateFn(string_, 0u);\n }\n}\n\nMethod::Method(VM* vm, WrenHandle* variable, WrenHandle* method)\n : vm_(vm),\n method_(method),\n variable_(variable)\n{}\n\nMethod::Method(Method&& other)\n : vm_(other.vm_),\n method_(other.method_),\n variable_(other.variable_)\n{\n other.vm_ = nullptr;\n other.method_ = nullptr;\n other.variable_ = nullptr;\n}\n\nMethod::~Method()\n{\n if (vm_)\n {\n assert(method_ && variable_);\n wrenReleaseHandle(vm_->ptr(), method_);\n wrenReleaseHandle(vm_->ptr(), variable_);\n }\n}\n\nMethod& Method::operator=(Method&& rhs)\n{\n vm_ = rhs.vm_;\n method_ = rhs.method_;\n variable_ = rhs.variable_;\n rhs.vm_ = nullptr;\n rhs.method_ = nullptr;\n rhs.variable_ = nullptr;\n\n return *this;\n}\n\nClassContext ModuleContext::beginClass(std::string c)\n{\n return ClassContext(c, *this);\n}\n\nvoid ModuleContext::endModule() {}\n\nModuleContext& ClassContext::endClass()\n{\n return module_;\n}\n\nClassContext::ClassContext(std::string c, ModuleContext& mod)\n : module_(mod),\n class_(c)\n{}\n\nClassContext& ClassContext::bindCFunction(bool isStatic, std::string signature, WrenForeignMethodFn function)\n{\n detail::registerFunction(module_.vm_, module_.name_, class_, isStatic, signature, function);\n return *this;\n}\n\n\/*\n * Returns the source as a heap-allocated string.\n * Uses malloc, because our reallocateFn is set to default:\n * it uses malloc, realloc and free.\n * *\/\nLoadModuleFn VM::loadModuleFn = [](const char* mod) -> char*\n{\n std::string path(mod);\n path += \".wren\";\n std::string source;\n try\n {\n source = wrenpp::detail::fileToString(path);\n }\n catch (const std::exception&)\n {\n return NULL;\n }\n char* buffer = (char*)malloc(source.size());\n assert(buffer != nullptr);\n memcpy(buffer, source.c_str(), source.size());\n return buffer;\n};\n\nWriteFn VM::writeFn = [](const char* text) -> void\n{\n std::cout << text;\n};\n\nErrorFn VM::errorFn = [](WrenErrorType type, const char* module_name, int line, const char* message) -> void\n{\n const char* typeStr = errorTypeToString(type);\n if (module_name)\n {\n std::cout << typeStr << \" in \" << module_name << \":\" << line << \"> \" << message << std::endl;\n }\n else\n {\n std::cout << typeStr << \"> \" << message << std::endl;\n }\n};\n\nReallocateFn VM::reallocateFn = std::realloc;\n\nstd::size_t VM::initialHeapSize = 0xA00000u;\n\nstd::size_t VM::minHeapSize = 0x100000u;\n\nint VM::heapGrowthPercent = 50;\n\nstd::size_t VM::chunkSize = 0x500000u;\n\nVM::VM()\n : vm_{ nullptr }\n{\n WrenConfiguration configuration{};\n wrenInitConfiguration(&configuration);\n configuration.reallocateFn = reallocateFnWrapper;\n configuration.initialHeapSize = initialHeapSize;\n configuration.minHeapSize = minHeapSize;\n configuration.heapGrowthPercent = heapGrowthPercent;\n configuration.bindForeignMethodFn = foreignMethodProvider;\n configuration.loadModuleFn = loadModuleFnWrapper;\n configuration.bindForeignClassFn = foreignClassProvider;\n configuration.writeFn = writeFnWrapper;\n configuration.errorFn = errorFnWrapper;\n configuration.userData = new BoundState();\n\n vm_ = wrenNewVM(&configuration);\n}\n\nVM::VM(VM&& other)\n : vm_{ other.vm_ }\n{\n other.vm_ = nullptr;\n}\n\nVM& VM::operator=(VM&& rhs)\n{\n vm_ = rhs.vm_;\n rhs.vm_ = nullptr;\n return *this;\n}\n\nVM::~VM()\n{\n if (vm_ != nullptr)\n {\n delete (BoundState*)wrenGetUserData(vm_);\n wrenFreeVM(vm_);\n }\n}\n\nResult VM::executeModule(const std::string& mod)\n{\n const std::string source(loadModuleFn(mod.c_str()));\n auto res = wrenInterpret(vm_, source.c_str());\n\n if (res == WrenInterpretResult::WREN_RESULT_COMPILE_ERROR)\n {\n return Result::CompileError;\n }\n\n if (res == WrenInterpretResult::WREN_RESULT_RUNTIME_ERROR)\n {\n return Result::RuntimeError;\n }\n\n return Result::Success;\n}\n\nResult VM::executeString(const std::string& code)\n{\n auto res = wrenInterpret(vm_, code.c_str());\n\n if (res == WrenInterpretResult::WREN_RESULT_COMPILE_ERROR)\n {\n return Result::CompileError;\n }\n\n if (res == WrenInterpretResult::WREN_RESULT_RUNTIME_ERROR)\n {\n return Result::RuntimeError;\n }\n\n return Result::Success;\n}\n\nvoid VM::collectGarbage()\n{\n wrenCollectGarbage(vm_);\n}\n\nMethod VM::method(\n const std::string& mod,\n const std::string& var,\n const std::string& sig\n)\n{\n wrenEnsureSlots(vm_, 1);\n wrenGetVariable(vm_, mod.c_str(), var.c_str(), 0);\n WrenHandle* variable = wrenGetSlotHandle(vm_, 0);\n WrenHandle* handle = wrenMakeCallHandle(vm_, sig.c_str());\n return Method(this, variable, handle);\n}\n\nModuleContext VM::beginModule(std::string name)\n{\n return ModuleContext(vm_, name);\n}\n\n}\nResolve #12 (#13)#include \"Wren++.h\"\n#include \/\/ for malloc\n#include \/\/ for strcmp, memcpy\n#include \n#include \n\nnamespace\n{\n\nstruct BoundState\n{\n std::unordered_map< std::size_t, WrenForeignMethodFn > methods{};\n std::unordered_map< std::size_t, WrenForeignClassMethods > classes{};\n};\n\nWrenForeignMethodFn foreignMethodProvider(WrenVM* vm,\n const char* module,\n const char* className,\n bool isStatic,\n const char* signature)\n{\n auto* boundState = (BoundState*)wrenGetUserData(vm);\n auto it = boundState->methods.find(wrenpp::detail::hashMethodSignature(module, className, isStatic, signature));\n if (it == boundState->methods.end())\n {\n return NULL;\n }\n\n return it->second;\n}\n\nWrenForeignClassMethods foreignClassProvider(WrenVM* vm, const char* m, const char* c)\n{\n auto* boundState = (BoundState*)wrenGetUserData(vm);\n auto it = boundState->classes.find(wrenpp::detail::hashClassSignature(m, c));\n if (it == boundState->classes.end())\n {\n return WrenForeignClassMethods{ nullptr, nullptr };\n }\n\n return it->second;\n}\n\ninline const char* errorTypeToString(WrenErrorType type)\n{\n switch (type)\n {\n case WREN_ERROR_COMPILE: return \"WREN_ERROR_COMPILE\";\n case WREN_ERROR_RUNTIME: return \"WREN_ERROR_RUNTIME\";\n case WREN_ERROR_STACK_TRACE: return \"WREN_ERROR_STACK_TRACE\";\n default: assert(false); return \"\";\n }\n}\n\nchar* loadModuleFnWrapper(WrenVM* vm, const char* mod)\n{\n return wrenpp::VM::loadModuleFn(mod);\n}\n\nvoid writeFnWrapper(WrenVM* vm, const char* text)\n{\n wrenpp::VM::writeFn(text);\n}\n\nvoid errorFnWrapper(WrenVM*, WrenErrorType type, const char* module, int line, const char* message)\n{\n wrenpp::VM::errorFn(type, module, line, message);\n}\n\nvoid* reallocateFnWrapper(void* memory, std::size_t newSize)\n{\n return wrenpp::VM::reallocateFn(memory, newSize);\n}\n\n}\n\nnamespace wrenpp\n{\n\nnamespace detail\n{\nvoid registerFunction(WrenVM* vm, const std::string& mod, const std::string& cName, bool isStatic, std::string sig, WrenForeignMethodFn function)\n{\n BoundState* boundState = (BoundState*)wrenGetUserData(vm);\n std::size_t hash = detail::hashMethodSignature(mod.c_str(), cName.c_str(), isStatic, sig.c_str());\n boundState->methods.insert(std::make_pair(hash, function));\n}\n\nvoid registerClass(WrenVM* vm, const std::string& mod, std::string cName, WrenForeignClassMethods methods)\n{\n BoundState* boundState = (BoundState*)wrenGetUserData(vm);\n std::size_t hash = detail::hashClassSignature(mod.c_str(), cName.c_str());\n boundState->classes.insert(std::make_pair(hash, methods));\n}\n\n}\n\nValue null = Value();\n\nValue::Value(bool val)\n : type_{ WREN_TYPE_BOOL }, string_{ nullptr }\n{\n set(val);\n}\n\nValue::Value(float val)\n : type_{ WREN_TYPE_NUM }, string_{ nullptr }\n{\n set(val);\n}\n\nValue::Value(double val)\n : type_{ WREN_TYPE_NUM }, string_{ nullptr }\n{\n set(val);\n}\n\nValue::Value(int val)\n : type_{ WREN_TYPE_NUM }, string_{ nullptr }\n{\n set(val);\n}\n\nValue::Value(unsigned int val)\n : type_{ WREN_TYPE_NUM }, string_{ nullptr }\n{\n set(val);\n}\n\nValue::Value(const char* str)\n : type_{ WREN_TYPE_STRING }, string_{ nullptr }\n{\n string_ = (char*)VM::reallocateFn(nullptr, std::strlen(str) + 1);\n std::strcpy(string_, str);\n}\n\nValue::~Value()\n{\n if (string_)\n {\n VM::reallocateFn(string_, 0u);\n }\n}\n\nMethod::Method(VM* vm, WrenHandle* variable, WrenHandle* method)\n : vm_(vm),\n method_(method),\n variable_(variable)\n{}\n\nMethod::Method(Method&& other)\n : vm_(other.vm_),\n method_(other.method_),\n variable_(other.variable_)\n{\n other.vm_ = nullptr;\n other.method_ = nullptr;\n other.variable_ = nullptr;\n}\n\nMethod::~Method()\n{\n if (vm_)\n {\n assert(method_ && variable_);\n wrenReleaseHandle(vm_->ptr(), method_);\n wrenReleaseHandle(vm_->ptr(), variable_);\n }\n}\n\nMethod& Method::operator=(Method&& rhs)\n{\n if (&rhs != this)\n {\n vm_ = rhs.vm_;\n method_ = rhs.method_;\n variable_ = rhs.variable_;\n rhs.vm_ = nullptr;\n rhs.method_ = nullptr;\n rhs.variable_ = nullptr;\n }\n \n return *this;\n}\n\nClassContext ModuleContext::beginClass(std::string c)\n{\n return ClassContext(c, *this);\n}\n\nvoid ModuleContext::endModule() {}\n\nModuleContext& ClassContext::endClass()\n{\n return module_;\n}\n\nClassContext::ClassContext(std::string c, ModuleContext& mod)\n : module_(mod),\n class_(c)\n{}\n\nClassContext& ClassContext::bindCFunction(bool isStatic, std::string signature, WrenForeignMethodFn function)\n{\n detail::registerFunction(module_.vm_, module_.name_, class_, isStatic, signature, function);\n return *this;\n}\n\n\/*\n * Returns the source as a heap-allocated string.\n * Uses malloc, because our reallocateFn is set to default:\n * it uses malloc, realloc and free.\n * *\/\nLoadModuleFn VM::loadModuleFn = [](const char* mod) -> char*\n{\n std::string path(mod);\n path += \".wren\";\n std::string source;\n try\n {\n source = wrenpp::detail::fileToString(path);\n }\n catch (const std::exception&)\n {\n return NULL;\n }\n char* buffer = (char*)malloc(source.size());\n assert(buffer != nullptr);\n memcpy(buffer, source.c_str(), source.size());\n return buffer;\n};\n\nWriteFn VM::writeFn = [](const char* text) -> void\n{\n std::cout << text;\n};\n\nErrorFn VM::errorFn = [](WrenErrorType type, const char* module_name, int line, const char* message) -> void\n{\n const char* typeStr = errorTypeToString(type);\n if (module_name)\n {\n std::cout << typeStr << \" in \" << module_name << \":\" << line << \"> \" << message << std::endl;\n }\n else\n {\n std::cout << typeStr << \"> \" << message << std::endl;\n }\n};\n\nReallocateFn VM::reallocateFn = std::realloc;\n\nstd::size_t VM::initialHeapSize = 0xA00000u;\n\nstd::size_t VM::minHeapSize = 0x100000u;\n\nint VM::heapGrowthPercent = 50;\n\nstd::size_t VM::chunkSize = 0x500000u;\n\nVM::VM()\n : vm_{ nullptr }\n{\n WrenConfiguration configuration{};\n wrenInitConfiguration(&configuration);\n configuration.reallocateFn = reallocateFnWrapper;\n configuration.initialHeapSize = initialHeapSize;\n configuration.minHeapSize = minHeapSize;\n configuration.heapGrowthPercent = heapGrowthPercent;\n configuration.bindForeignMethodFn = foreignMethodProvider;\n configuration.loadModuleFn = loadModuleFnWrapper;\n configuration.bindForeignClassFn = foreignClassProvider;\n configuration.writeFn = writeFnWrapper;\n configuration.errorFn = errorFnWrapper;\n configuration.userData = new BoundState();\n\n vm_ = wrenNewVM(&configuration);\n}\n\nVM::VM(VM&& other)\n : vm_{ other.vm_ }\n{\n other.vm_ = nullptr;\n}\n\nVM& VM::operator=(VM&& rhs)\n{\n if (&rhs != this)\n {\n vm_ = rhs.vm_;\n rhs.vm_ = nullptr;\n }\n return *this;\n}\n\nVM::~VM()\n{\n if (vm_ != nullptr)\n {\n delete (BoundState*)wrenGetUserData(vm_);\n wrenFreeVM(vm_);\n }\n}\n\nResult VM::executeModule(const std::string& mod)\n{\n const std::string source(loadModuleFn(mod.c_str()));\n auto res = wrenInterpret(vm_, source.c_str());\n\n if (res == WrenInterpretResult::WREN_RESULT_COMPILE_ERROR)\n {\n return Result::CompileError;\n }\n\n if (res == WrenInterpretResult::WREN_RESULT_RUNTIME_ERROR)\n {\n return Result::RuntimeError;\n }\n\n return Result::Success;\n}\n\nResult VM::executeString(const std::string& code)\n{\n auto res = wrenInterpret(vm_, code.c_str());\n\n if (res == WrenInterpretResult::WREN_RESULT_COMPILE_ERROR)\n {\n return Result::CompileError;\n }\n\n if (res == WrenInterpretResult::WREN_RESULT_RUNTIME_ERROR)\n {\n return Result::RuntimeError;\n }\n\n return Result::Success;\n}\n\nvoid VM::collectGarbage()\n{\n wrenCollectGarbage(vm_);\n}\n\nMethod VM::method(\n const std::string& mod,\n const std::string& var,\n const std::string& sig\n)\n{\n wrenEnsureSlots(vm_, 1);\n wrenGetVariable(vm_, mod.c_str(), var.c_str(), 0);\n WrenHandle* variable = wrenGetSlotHandle(vm_, 0);\n WrenHandle* handle = wrenMakeCallHandle(vm_, sig.c_str());\n return Method(this, variable, handle);\n}\n\nModuleContext VM::beginModule(std::string name)\n{\n return ModuleContext(vm_, name);\n}\n\n}\n<|endoftext|>"} {"text":"\/*\n * Copyright (c) 2008-2010 Digital Bazaar, Inc. All rights reserved.\n *\/\n#define __STDC_FORMAT_MACROS\n\n#include \"bitmunk\/purchase\/PieceDownloader.h\"\n\n#include \"bitmunk\/purchase\/PurchaseModule.h\"\n#include \"monarch\/event\/ObserverDelegate.h\"\n#include \"monarch\/io\/FileOutputStream.h\"\n#include \"monarch\/rt\/RunnableDelegate.h\"\n#include \"monarch\/util\/Timer.h\"\n\nusing namespace std;\nusing namespace bitmunk::common;\nusing namespace bitmunk::protocol;\nusing namespace bitmunk::purchase;\nusing namespace bitmunk::node;\nusing namespace monarch::event;\nusing namespace monarch::fiber;\nusing namespace monarch::http;\nusing namespace monarch::io;\nusing namespace monarch::modest;\nusing namespace monarch::net;\nusing namespace monarch::rt;\nusing namespace monarch::util;\n\n#define EVENT_DOWNLOAD_STATE \"bitmunk.purchase.DownloadState\"\n\nPieceDownloader::PieceDownloader(Node* node, FiberId parentId) :\n NodeFiber(node, parentId),\n DownloadStateFiber(node, \"PieceDownloader\", &mFiberExitData),\n mUniqueId(0),\n mPieceSize(0),\n mSection(NULL),\n mFileId(NULL),\n mFilePiece(NULL),\n mConnection(NULL),\n mRequest(NULL),\n mResponse(NULL),\n mPieceDownloadRate(NULL),\n mDownloadRate(NULL),\n mInterrupted(false)\n{\n}\n\nPieceDownloader::~PieceDownloader()\n{\n if(mFileId != NULL)\n {\n free(mFileId);\n }\n}\n\nvoid PieceDownloader::initialize(\n uint32_t id,\n uint32_t pieceSize,\n ContractSection& cs, FileId fileId, FilePiece& fp,\n RateAverager* pa, RateAverager* ra)\n{\n mUniqueId = id;\n mPieceSize = pieceSize;\n mSection = cs.clone();\n mFileId = strdup(fileId);\n mFilePiece = fp.clone();\n mPieceDownloadRate = pa;\n mDownloadRate = ra;\n}\n\nvoid PieceDownloader::download()\n{\n \/* Algorithm:\n\n 1. If download failed, send event, notify parent, exit.\n 2. If download would block, register with IOWatcher.\n 3. If download finished, send event, notify parent, exit.\n\n *\/\n\n bool error = false;\n\n \/\/ connect if not already connected\n if(mConnection == NULL)\n {\n if(connect())\n {\n \/\/ FIXME: set connection to asynchronous IO when writing optimization\n \/\/ to use IOMonitor (and maybe even move this out of an operation)\n\n \/\/ add bandwidth throttler to connection\n mConnection->setBandwidthThrottler(mDownloadThrottler, true);\n }\n else\n {\n error = true;\n }\n }\n\n if(!error)\n {\n logDownloadStateMessage(\"downloading piece from seller...\");\n\n \/\/ send an event that the download has started\n sendEvent(false, EVENT_DOWNLOAD_STATE \".pieceStarted\");\n\n \/\/ FIXME: when switching to IOMonitor, possibly just do this in\n \/\/ the fiber, and do one tiny read at a time\n\n \/\/ keep receiving and writing data while success\n bool success = true;\n char b[2048];\n int numBytes;\n uint64_t start = System::getCurrentMilliseconds();\n while(success && (numBytes = mInputStream->read(b, 2048)) > 0)\n {\n mTotalDownloadRate->addItems(numBytes, start);\n mDownloadRate->addItems(numBytes, start);\n mPieceDownloadRate->addItems(numBytes, start);\n success = success && mOutputStream->write(b, numBytes);\n start = System::getCurrentMilliseconds();\n }\n\n if(success && numBytes == 0)\n {\n \/\/ check content security\n mInMessage.checkContentSecurity(\n mResponse->getHeader(), &(*mTrailer), &(*mSignature));\n if(mInMessage.getSecurityStatus() == BtpMessage::Breach)\n {\n \/\/ set exception\n ExceptionRef e = new Exception(\n \"Message security breach.\",\n \"bitmunk.protocol.Security\");\n e->getDetails()[\"resource\"] = mUrl.toString().c_str();\n Exception::set(e);\n success = false;\n }\n }\n\n if(numBytes < 0 || !success)\n {\n ExceptionRef e = Exception::get();\n if(true)\/\/!e->getDetails()->hasMember(\"wouldBlock\"))\n {\n \/\/ download failed:\n error = true;\n\n \/\/ disconnect\n mConnection->close();\n\n \/\/ clean up\n delete mConnection;\n delete mRequest;\n delete mResponse;\n mOutputStream->close();\n mOutputStream.setNull();\n }\n else\n {\n \/\/ download would block, register with IOWatcher (which\n \/\/ will wakeup piece downloader to run step 2 again)\n \/\/ FIXME: use &PieceDownloader::fdUpdated;\n }\n }\n else\n {\n \/\/ disconnect\n mConnection->close();\n\n \/\/ clean up\n delete mConnection;\n delete mRequest;\n delete mResponse;\n mOutputStream->close();\n mOutputStream.setNull();\n\n \/\/ download finished\n logDownloadStateMessage(\"piece download finished\");\n\n MO_CAT_INFO(BM_PURCHASE_CAT,\n \"UserId %\" PRIu64 \", DownloadState %\" PRIu64 \": \"\n \"piece download finished, rate: %g bytes\/s\",\n BM_USER_ID(mDownloadState[\"userId\"]),\n mDownloadState[\"id\"]->getUInt64(),\n mPieceDownloadRate->getTotalItemsPerSecond());\n\n \/\/ get file piece trailers:\n string value;\n\n \/\/ actual size of file piece\n mTrailer->getField(\"Bitmunk-Piece-Size\", value);\n mFilePiece[\"size\"] = value.c_str();\n \/\/ convert\n mFilePiece[\"size\"]->setType(UInt32);\n \/\/ FIXME: check errno\n\n \/\/ bfp signature on piece\n mTrailer->getField(\"Bitmunk-Bfp-Signature\", value);\n mFilePiece[\"bfpSignature\"] = value.c_str();\n\n \/\/ seller signature on piece + seller profile ID\n mTrailer->getField(\"Bitmunk-Seller-Signature\", value);\n mFilePiece[\"sellerSignature\"] = value.c_str();\n mTrailer->getField(\"Bitmunk-Seller-Profile-Id\", value);\n BM_ID_SET(mFilePiece[\"sellerProfileId\"], value.c_str());\n\n \/\/ open key information (to be sent to SVA to unlock piece key)\n mTrailer->getField(\"Bitmunk-Open-Key-Algorithm\", value);\n mFilePiece[\"openKey\"][\"algorithm\"] = value.c_str();\n mTrailer->getField(\"Bitmunk-Open-Key-Data\", value);\n mFilePiece[\"openKey\"][\"data\"] = value.c_str();\n mTrailer->getField(\"Bitmunk-Open-Key-Length\", value);\n mFilePiece[\"openKey\"][\"length\"] = value.c_str();\n \/\/ convert\n mFilePiece[\"openKey\"][\"length\"]->setType(UInt32);\n \/\/ FIXME: check errno\n\n \/\/ encrypted piece key information\n \/\/ (to be unlocked with open key by SVA)\n mTrailer->getField(\"Bitmunk-Piece-Key-Algorithm\", value);\n mFilePiece[\"pieceKey\"][\"algorithm\"] = value.c_str();\n mTrailer->getField(\"Bitmunk-Piece-Key-Data\", value);\n mFilePiece[\"pieceKey\"][\"data\"] = value.c_str();\n mTrailer->getField(\"Bitmunk-Piece-Key-Length\", value);\n mFilePiece[\"pieceKey\"][\"length\"] = value.c_str();\n \/\/ convert\n mFilePiece[\"pieceKey\"][\"length\"]->setType(UInt32);\n \/\/ FIXME: check errno\n\n \/\/ set piece to encrypted and ciphered\n mFilePiece[\"encrypted\"] = true;\n mFilePiece[\"ciphered\"] = true;\n }\n }\n\n \/\/ create message regarding operation completion\n DynamicObject msg;\n msg[\"pieceReceived\"] = !error;\n if(error)\n {\n msg[\"exception\"] = Exception::getAsDynamicObject();\n }\n\n \/\/ send message to self\n messageSelf(msg);\n}\n\nvoid PieceDownloader::fdUpdated(int fd, int events)\n{\n \/\/ FIXME: this code must be changed to send a message to self like the\n \/\/ download operation does -- this ensures that interrupting this fiber\n \/\/ happens cleanly\n\n \/*\n \/\/ FIXME: determine if error based on events\n bool error = false;\n\n if(error)\n {\n \/\/ create exception for given IO error event\n \/\/ FIXME: get specific event error\n ExceptionRef e = new Exception(\n \"FIXME: I am an exception that occurred while waiting for IO \"\n \"in the purchase module's PieceDownloader class\");\n sendEvent(true, NULL);\n }\n *\/\n}\n\nvoid PieceDownloader::processMessages()\n{\n logDownloadStateMessage(\"starting...\");\n\n \/\/ send message to parent that piece has been started\n DynamicObject msg;\n msg[\"pieceDownloaderId\"] = mUniqueId;\n msg[\"downloadStateId\"] = mDownloadState[\"id\"]->getUInt64();\n BM_ID_SET(msg[\"userId\"], BM_USER_ID(mDownloadState[\"userId\"]));\n msg[\"pieceStarted\"] = true;\n msg[\"piece\"] = mFilePiece.clone();\n msg[\"section\"] = mSection.clone();\n BM_ID_SET(msg[\"fileId\"], mFileId);\n messageParent(msg);\n\n \/\/ run a new download operation\n RunnableRef r = new RunnableDelegate(\n this, &PieceDownloader::download);\n Operation op = r;\n getNode()->runOperation(op);\n\n \/\/ wait for messages\n const char* keys[] =\n {\"interrupt\", \"pieceReceived\", \"pieceFailed\", NULL};\n bool pieceReceived = false;\n bool done = false;\n while(!done)\n {\n DynamicObject list = waitForMessages(keys);\n DynamicObjectIterator i = list.getIterator();\n while(i->hasNext())\n {\n DynamicObject& msg = i->next();\n\n \/\/ if interrupted, interrupt operation\n if(msg->hasMember(\"interrupt\"))\n {\n \/\/ ensure unique piece downloader ID matches\n if(mUniqueId == msg[\"pieceDownloaderId\"]->getUInt32())\n {\n \/\/ piece downloader interrupted\n mInterrupted = true;\n\n \/\/ send interruption event if pause is false\n if(!msg[\"pause\"]->getBoolean())\n {\n ExceptionRef e = new Exception(\n \"PieceDownloader interrupted.\",\n \"bitmunk.purchase.PieceDownloader.interrupted\");\n Exception::set(e);\n sendEvent(true, NULL);\n }\n\n \/\/ interrupt download operation\n op->interrupt();\n }\n }\n \/\/ message regards receiving piece\n else if(msg[\"pieceReceived\"]->getBoolean())\n {\n sendEvent(false, EVENT_DOWNLOAD_STATE \".pieceFinished\");\n pieceReceived = done = true;\n }\n \/\/ piece failed message\n else\n {\n \/\/ only send an error event if there was no interruption\n if(!mInterrupted)\n {\n \/\/ convert the exception from a dynamic object, send error event\n ExceptionRef e = Exception::convertToException(msg[\"exception\"]);\n Exception::set(e);\n sendEvent(true, NULL);\n }\n\n done = true;\n }\n }\n }\n\n if(pieceReceived)\n {\n logDownloadStateMessage(\"finished with success\");\n\n \/\/ send message to parent that piece has been received\n DynamicObject msg;\n msg[\"pieceDownloaderId\"] = mUniqueId;\n msg[\"downloadStateId\"] = mDownloadState[\"id\"]->getUInt64();\n BM_ID_SET(msg[\"userId\"], BM_USER_ID(mDownloadState[\"userId\"]));\n msg[\"pieceReceived\"] = true;\n msg[\"piece\"] = mFilePiece;\n msg[\"section\"] = mSection;\n BM_ID_SET(msg[\"fileId\"], mFileId);\n msg[\"pieceRate\"] = mPieceDownloadRate->getTotalItemsPerSecond();\n messageParent(msg);\n }\n else\n {\n logDownloadStateMessage(\"finished with error\");\n\n \/\/ send message to parent that piece has failed\n DynamicObject msg;\n msg[\"pieceDownloaderId\"] = mUniqueId;\n msg[\"downloadStateId\"] = mDownloadState[\"id\"]->getUInt64();\n BM_ID_SET(msg[\"userId\"], BM_USER_ID(mDownloadState[\"userId\"]));\n msg[\"pieceFailed\"] = true;\n msg[\"piece\"] = mFilePiece;\n msg[\"section\"] = mSection;\n BM_ID_SET(msg[\"fileId\"], mFileId);\n msg[\"pieceRate\"] = mPieceDownloadRate->getTotalItemsPerSecond();\n messageParent(msg);\n }\n}\n\nbool PieceDownloader::connect()\n{\n bool rval = false;\n\n \/\/ get buyer's profile\n ProfileRef profile;\n UserId userId = BM_USER_ID(mDownloadState[\"userId\"]);\n if((rval = getNode()->getLoginData(userId, NULL, &profile)))\n {\n \/\/ find media ID for file ID\n MediaId mediaId = 0;\n FileInfoIterator fii = mSection[\"ware\"][\"fileInfos\"].getIterator();\n while(mediaId == 0 && fii->hasNext())\n {\n FileInfo& fi = fii->next();\n if(BM_FILE_ID_EQUALS(BM_FILE_ID(fi[\"id\"]), mFileId))\n {\n mediaId = BM_MEDIA_ID(fi[\"mediaId\"]);\n }\n }\n\n \/\/ create piece request\n DynamicObject pieceRequest;\n pieceRequest[\"csHash\"] = mSection[\"hash\"]->getString();\n BM_ID_SET(pieceRequest[\"fileId\"], mFileId);\n BM_ID_SET(pieceRequest[\"mediaId\"], mediaId);\n pieceRequest[\"index\"] = mFilePiece[\"index\"]->getUInt32();\n \/\/ use full standard piece size, seller may truncate if last piece\n pieceRequest[\"size\"] = mPieceSize;\n pieceRequest[\"peerbuyKey\"] = mSection[\"peerbuyKey\"]->getString();\n BM_ID_SET(\n pieceRequest[\"sellerProfileId\"],\n BM_PROFILE_ID(mSection[\"seller\"][\"profileId\"]));\n BM_ID_SET(pieceRequest[\"bfpId\"], BM_BFP_ID(mFilePiece[\"bfpId\"]));\n\n \/\/ setup btp messages\n mOutMessage.setDynamicObject(pieceRequest);\n mOutMessage.setType(BtpMessage::Post);\n mOutMessage.setUserId(userId);\n mOutMessage.setAgentProfile(profile);\n mInMessage.setPublicKeySource(getNode()->getPublicKeyCache());\n\n \/\/ create url to get file piece\n mUrl.format(\"%s\/api\/3.0\/sales\/contract\/filepiece?nodeuser=%\" PRIu64,\n mSection[\"seller\"][\"url\"]->getString(),\n BM_USER_ID(mSection[\"seller\"][\"userId\"]));\n\n MO_CAT_INFO(BM_PURCHASE_CAT,\n \"UserId %\" PRIu64 \", DownloadState %\" PRIu64 \": \"\n \"connecting to seller (%\" PRIu64 \":%u) @ %s\",\n BM_USER_ID(mDownloadState[\"userId\"]),\n mDownloadState[\"id\"]->getUInt64(),\n BM_USER_ID(mSection[\"seller\"][\"userId\"]),\n BM_SERVER_ID(mSection[\"seller\"][\"serverId\"]),\n mUrl.toString().c_str());\n\n \/\/ connect to seller\n \/\/ bfp->startReading() may take more than 30 seconds to execute\n \/\/ on seller side, so clients should set their read timeouts to\n \/\/ something high like 2-5 minutes\n \/\/ FIXME: this may need to be done in the IOMonitor\/IOWatcher, not\n \/\/ on the connection\n BtpClient* btpc = getNode()->getMessenger()->getBtpClient();\n mConnection = btpc->createConnection(\n BM_USER_ID(mSection[\"seller\"][\"userId\"]), &mUrl, 120);\n if((rval = (mConnection != NULL)))\n {\n logDownloadStateMessage(\"connected to seller...\");\n\n \/\/ create request and response\n mRequest = mConnection->createRequest();\n mResponse = mRequest->createResponse();\n\n \/\/ send message\n if((rval = btpc->sendMessage(\n &mUrl, &mOutMessage, mRequest, &mInMessage, mResponse)))\n {\n logDownloadStateMessage(\"preparing to download piece...\");\n\n \/\/ get receive content stream\n mInMessage.getContentReceiveStream(\n mResponse, mInputStream, mTrailer, mSignature);\n\n \/\/ set up output stream\n File file(mFilePiece[\"path\"]->getString());\n if(!(rval = file->mkdirs()))\n {\n ExceptionRef e = new Exception(\n \"Failed to create output directory for downloading file \"\n \"pieces.\",\n \"bitmunk.purchase.PieceDownloader.OutputFileWriteError\");\n e->getDetails()[\"path\"] = file->getPath();\n Exception::push(e);\n }\n else\n {\n mOutputStream = new FileOutputStream(file);\n }\n }\n }\n\n if(!rval)\n {\n \/\/ clean up\n if(mConnection != NULL)\n {\n mConnection->close();\n delete mConnection;\n delete mRequest;\n delete mResponse;\n }\n }\n }\n\n return rval;\n}\n\/\/ FIXME: clean these parameters up, its ugly\nvoid PieceDownloader::sendEvent(bool error, const char* type)\n{\n Event e;\n\n if(error)\n {\n \/\/ set failure event\n e[\"type\"] = EVENT_DOWNLOAD_STATE \".exception\";\n e[\"details\"][\"exception\"] = Exception::getAsDynamicObject();\n }\n else\n {\n \/\/ send success event\n e[\"type\"] = type;\n }\n\n \/\/ send event\n BM_ID_SET(e[\"details\"][\"fileId\"], mFileId);\n e[\"details\"][\"piece\"] = mFilePiece;\n e[\"details\"][\"downloaded\"] = mPieceDownloadRate->getTotalItemCount();\n sendDownloadStateEvent(e);\n}\nUpdated FIXME.\/*\n * Copyright (c) 2008-2010 Digital Bazaar, Inc. All rights reserved.\n *\/\n#define __STDC_FORMAT_MACROS\n\n#include \"bitmunk\/purchase\/PieceDownloader.h\"\n\n#include \"bitmunk\/purchase\/PurchaseModule.h\"\n#include \"monarch\/event\/ObserverDelegate.h\"\n#include \"monarch\/io\/FileOutputStream.h\"\n#include \"monarch\/rt\/RunnableDelegate.h\"\n#include \"monarch\/util\/Timer.h\"\n\nusing namespace std;\nusing namespace bitmunk::common;\nusing namespace bitmunk::protocol;\nusing namespace bitmunk::purchase;\nusing namespace bitmunk::node;\nusing namespace monarch::event;\nusing namespace monarch::fiber;\nusing namespace monarch::http;\nusing namespace monarch::io;\nusing namespace monarch::modest;\nusing namespace monarch::net;\nusing namespace monarch::rt;\nusing namespace monarch::util;\n\n#define EVENT_DOWNLOAD_STATE \"bitmunk.purchase.DownloadState\"\n\nPieceDownloader::PieceDownloader(Node* node, FiberId parentId) :\n NodeFiber(node, parentId),\n DownloadStateFiber(node, \"PieceDownloader\", &mFiberExitData),\n mUniqueId(0),\n mPieceSize(0),\n mSection(NULL),\n mFileId(NULL),\n mFilePiece(NULL),\n mConnection(NULL),\n mRequest(NULL),\n mResponse(NULL),\n mPieceDownloadRate(NULL),\n mDownloadRate(NULL),\n mInterrupted(false)\n{\n}\n\nPieceDownloader::~PieceDownloader()\n{\n if(mFileId != NULL)\n {\n free(mFileId);\n }\n}\n\nvoid PieceDownloader::initialize(\n uint32_t id,\n uint32_t pieceSize,\n ContractSection& cs, FileId fileId, FilePiece& fp,\n RateAverager* pa, RateAverager* ra)\n{\n mUniqueId = id;\n mPieceSize = pieceSize;\n mSection = cs.clone();\n mFileId = strdup(fileId);\n mFilePiece = fp.clone();\n mPieceDownloadRate = pa;\n mDownloadRate = ra;\n}\n\nvoid PieceDownloader::download()\n{\n \/* Algorithm:\n\n 1. If download failed, send event, notify parent, exit.\n 2. If download would block, register with IOWatcher.\n 3. If download finished, send event, notify parent, exit.\n\n *\/\n\n bool error = false;\n\n \/\/ connect if not already connected\n if(mConnection == NULL)\n {\n if(connect())\n {\n \/\/ FIXME: set connection to asynchronous IO when writing optimization\n \/\/ to use IOMonitor (and maybe even move this out of an operation)\n\n \/\/ add bandwidth throttler to connection\n mConnection->setBandwidthThrottler(mDownloadThrottler, true);\n }\n else\n {\n error = true;\n }\n }\n\n if(!error)\n {\n logDownloadStateMessage(\"downloading piece from seller...\");\n\n \/\/ send an event that the download has started\n sendEvent(false, EVENT_DOWNLOAD_STATE \".pieceStarted\");\n\n \/\/ FIXME: when switching to IOMonitor this will be done in the fiber\n \/\/ with IO scheduling handled at the appropriate layer\n\n \/\/ keep receiving and writing data while success\n bool success = true;\n char b[2048];\n int numBytes;\n uint64_t start = System::getCurrentMilliseconds();\n while(success && (numBytes = mInputStream->read(b, 2048)) > 0)\n {\n mTotalDownloadRate->addItems(numBytes, start);\n mDownloadRate->addItems(numBytes, start);\n mPieceDownloadRate->addItems(numBytes, start);\n success = success && mOutputStream->write(b, numBytes);\n start = System::getCurrentMilliseconds();\n }\n\n if(success && numBytes == 0)\n {\n \/\/ check content security\n mInMessage.checkContentSecurity(\n mResponse->getHeader(), &(*mTrailer), &(*mSignature));\n if(mInMessage.getSecurityStatus() == BtpMessage::Breach)\n {\n \/\/ set exception\n ExceptionRef e = new Exception(\n \"Message security breach.\",\n \"bitmunk.protocol.Security\");\n e->getDetails()[\"resource\"] = mUrl.toString().c_str();\n Exception::set(e);\n success = false;\n }\n }\n\n if(numBytes < 0 || !success)\n {\n ExceptionRef e = Exception::get();\n if(true)\/\/!e->getDetails()->hasMember(\"wouldBlock\"))\n {\n \/\/ download failed:\n error = true;\n\n \/\/ disconnect\n mConnection->close();\n\n \/\/ clean up\n delete mConnection;\n delete mRequest;\n delete mResponse;\n mOutputStream->close();\n mOutputStream.setNull();\n }\n else\n {\n \/\/ download would block, register with IOWatcher (which\n \/\/ will wakeup piece downloader to run step 2 again)\n \/\/ FIXME: use &PieceDownloader::fdUpdated;\n }\n }\n else\n {\n \/\/ disconnect\n mConnection->close();\n\n \/\/ clean up\n delete mConnection;\n delete mRequest;\n delete mResponse;\n mOutputStream->close();\n mOutputStream.setNull();\n\n \/\/ download finished\n logDownloadStateMessage(\"piece download finished\");\n\n MO_CAT_INFO(BM_PURCHASE_CAT,\n \"UserId %\" PRIu64 \", DownloadState %\" PRIu64 \": \"\n \"piece download finished, rate: %g bytes\/s\",\n BM_USER_ID(mDownloadState[\"userId\"]),\n mDownloadState[\"id\"]->getUInt64(),\n mPieceDownloadRate->getTotalItemsPerSecond());\n\n \/\/ get file piece trailers:\n string value;\n\n \/\/ actual size of file piece\n mTrailer->getField(\"Bitmunk-Piece-Size\", value);\n mFilePiece[\"size\"] = value.c_str();\n \/\/ convert\n mFilePiece[\"size\"]->setType(UInt32);\n \/\/ FIXME: check errno\n\n \/\/ bfp signature on piece\n mTrailer->getField(\"Bitmunk-Bfp-Signature\", value);\n mFilePiece[\"bfpSignature\"] = value.c_str();\n\n \/\/ seller signature on piece + seller profile ID\n mTrailer->getField(\"Bitmunk-Seller-Signature\", value);\n mFilePiece[\"sellerSignature\"] = value.c_str();\n mTrailer->getField(\"Bitmunk-Seller-Profile-Id\", value);\n BM_ID_SET(mFilePiece[\"sellerProfileId\"], value.c_str());\n\n \/\/ open key information (to be sent to SVA to unlock piece key)\n mTrailer->getField(\"Bitmunk-Open-Key-Algorithm\", value);\n mFilePiece[\"openKey\"][\"algorithm\"] = value.c_str();\n mTrailer->getField(\"Bitmunk-Open-Key-Data\", value);\n mFilePiece[\"openKey\"][\"data\"] = value.c_str();\n mTrailer->getField(\"Bitmunk-Open-Key-Length\", value);\n mFilePiece[\"openKey\"][\"length\"] = value.c_str();\n \/\/ convert\n mFilePiece[\"openKey\"][\"length\"]->setType(UInt32);\n \/\/ FIXME: check errno\n\n \/\/ encrypted piece key information\n \/\/ (to be unlocked with open key by SVA)\n mTrailer->getField(\"Bitmunk-Piece-Key-Algorithm\", value);\n mFilePiece[\"pieceKey\"][\"algorithm\"] = value.c_str();\n mTrailer->getField(\"Bitmunk-Piece-Key-Data\", value);\n mFilePiece[\"pieceKey\"][\"data\"] = value.c_str();\n mTrailer->getField(\"Bitmunk-Piece-Key-Length\", value);\n mFilePiece[\"pieceKey\"][\"length\"] = value.c_str();\n \/\/ convert\n mFilePiece[\"pieceKey\"][\"length\"]->setType(UInt32);\n \/\/ FIXME: check errno\n\n \/\/ set piece to encrypted and ciphered\n mFilePiece[\"encrypted\"] = true;\n mFilePiece[\"ciphered\"] = true;\n }\n }\n\n \/\/ create message regarding operation completion\n DynamicObject msg;\n msg[\"pieceReceived\"] = !error;\n if(error)\n {\n msg[\"exception\"] = Exception::getAsDynamicObject();\n }\n\n \/\/ send message to self\n messageSelf(msg);\n}\n\nvoid PieceDownloader::fdUpdated(int fd, int events)\n{\n \/\/ FIXME: this code must be changed to send a message to self like the\n \/\/ download operation does -- this ensures that interrupting this fiber\n \/\/ happens cleanly\n\n \/*\n \/\/ FIXME: determine if error based on events\n bool error = false;\n\n if(error)\n {\n \/\/ create exception for given IO error event\n \/\/ FIXME: get specific event error\n ExceptionRef e = new Exception(\n \"FIXME: I am an exception that occurred while waiting for IO \"\n \"in the purchase module's PieceDownloader class\");\n sendEvent(true, NULL);\n }\n *\/\n}\n\nvoid PieceDownloader::processMessages()\n{\n logDownloadStateMessage(\"starting...\");\n\n \/\/ send message to parent that piece has been started\n DynamicObject msg;\n msg[\"pieceDownloaderId\"] = mUniqueId;\n msg[\"downloadStateId\"] = mDownloadState[\"id\"]->getUInt64();\n BM_ID_SET(msg[\"userId\"], BM_USER_ID(mDownloadState[\"userId\"]));\n msg[\"pieceStarted\"] = true;\n msg[\"piece\"] = mFilePiece.clone();\n msg[\"section\"] = mSection.clone();\n BM_ID_SET(msg[\"fileId\"], mFileId);\n messageParent(msg);\n\n \/\/ run a new download operation\n RunnableRef r = new RunnableDelegate(\n this, &PieceDownloader::download);\n Operation op = r;\n getNode()->runOperation(op);\n\n \/\/ wait for messages\n const char* keys[] =\n {\"interrupt\", \"pieceReceived\", \"pieceFailed\", NULL};\n bool pieceReceived = false;\n bool done = false;\n while(!done)\n {\n DynamicObject list = waitForMessages(keys);\n DynamicObjectIterator i = list.getIterator();\n while(i->hasNext())\n {\n DynamicObject& msg = i->next();\n\n \/\/ if interrupted, interrupt operation\n if(msg->hasMember(\"interrupt\"))\n {\n \/\/ ensure unique piece downloader ID matches\n if(mUniqueId == msg[\"pieceDownloaderId\"]->getUInt32())\n {\n \/\/ piece downloader interrupted\n mInterrupted = true;\n\n \/\/ send interruption event if pause is false\n if(!msg[\"pause\"]->getBoolean())\n {\n ExceptionRef e = new Exception(\n \"PieceDownloader interrupted.\",\n \"bitmunk.purchase.PieceDownloader.interrupted\");\n Exception::set(e);\n sendEvent(true, NULL);\n }\n\n \/\/ interrupt download operation\n op->interrupt();\n }\n }\n \/\/ message regards receiving piece\n else if(msg[\"pieceReceived\"]->getBoolean())\n {\n sendEvent(false, EVENT_DOWNLOAD_STATE \".pieceFinished\");\n pieceReceived = done = true;\n }\n \/\/ piece failed message\n else\n {\n \/\/ only send an error event if there was no interruption\n if(!mInterrupted)\n {\n \/\/ convert the exception from a dynamic object, send error event\n ExceptionRef e = Exception::convertToException(msg[\"exception\"]);\n Exception::set(e);\n sendEvent(true, NULL);\n }\n\n done = true;\n }\n }\n }\n\n if(pieceReceived)\n {\n logDownloadStateMessage(\"finished with success\");\n\n \/\/ send message to parent that piece has been received\n DynamicObject msg;\n msg[\"pieceDownloaderId\"] = mUniqueId;\n msg[\"downloadStateId\"] = mDownloadState[\"id\"]->getUInt64();\n BM_ID_SET(msg[\"userId\"], BM_USER_ID(mDownloadState[\"userId\"]));\n msg[\"pieceReceived\"] = true;\n msg[\"piece\"] = mFilePiece;\n msg[\"section\"] = mSection;\n BM_ID_SET(msg[\"fileId\"], mFileId);\n msg[\"pieceRate\"] = mPieceDownloadRate->getTotalItemsPerSecond();\n messageParent(msg);\n }\n else\n {\n logDownloadStateMessage(\"finished with error\");\n\n \/\/ send message to parent that piece has failed\n DynamicObject msg;\n msg[\"pieceDownloaderId\"] = mUniqueId;\n msg[\"downloadStateId\"] = mDownloadState[\"id\"]->getUInt64();\n BM_ID_SET(msg[\"userId\"], BM_USER_ID(mDownloadState[\"userId\"]));\n msg[\"pieceFailed\"] = true;\n msg[\"piece\"] = mFilePiece;\n msg[\"section\"] = mSection;\n BM_ID_SET(msg[\"fileId\"], mFileId);\n msg[\"pieceRate\"] = mPieceDownloadRate->getTotalItemsPerSecond();\n messageParent(msg);\n }\n}\n\nbool PieceDownloader::connect()\n{\n bool rval = false;\n\n \/\/ get buyer's profile\n ProfileRef profile;\n UserId userId = BM_USER_ID(mDownloadState[\"userId\"]);\n if((rval = getNode()->getLoginData(userId, NULL, &profile)))\n {\n \/\/ find media ID for file ID\n MediaId mediaId = 0;\n FileInfoIterator fii = mSection[\"ware\"][\"fileInfos\"].getIterator();\n while(mediaId == 0 && fii->hasNext())\n {\n FileInfo& fi = fii->next();\n if(BM_FILE_ID_EQUALS(BM_FILE_ID(fi[\"id\"]), mFileId))\n {\n mediaId = BM_MEDIA_ID(fi[\"mediaId\"]);\n }\n }\n\n \/\/ create piece request\n DynamicObject pieceRequest;\n pieceRequest[\"csHash\"] = mSection[\"hash\"]->getString();\n BM_ID_SET(pieceRequest[\"fileId\"], mFileId);\n BM_ID_SET(pieceRequest[\"mediaId\"], mediaId);\n pieceRequest[\"index\"] = mFilePiece[\"index\"]->getUInt32();\n \/\/ use full standard piece size, seller may truncate if last piece\n pieceRequest[\"size\"] = mPieceSize;\n pieceRequest[\"peerbuyKey\"] = mSection[\"peerbuyKey\"]->getString();\n BM_ID_SET(\n pieceRequest[\"sellerProfileId\"],\n BM_PROFILE_ID(mSection[\"seller\"][\"profileId\"]));\n BM_ID_SET(pieceRequest[\"bfpId\"], BM_BFP_ID(mFilePiece[\"bfpId\"]));\n\n \/\/ setup btp messages\n mOutMessage.setDynamicObject(pieceRequest);\n mOutMessage.setType(BtpMessage::Post);\n mOutMessage.setUserId(userId);\n mOutMessage.setAgentProfile(profile);\n mInMessage.setPublicKeySource(getNode()->getPublicKeyCache());\n\n \/\/ create url to get file piece\n mUrl.format(\"%s\/api\/3.0\/sales\/contract\/filepiece?nodeuser=%\" PRIu64,\n mSection[\"seller\"][\"url\"]->getString(),\n BM_USER_ID(mSection[\"seller\"][\"userId\"]));\n\n MO_CAT_INFO(BM_PURCHASE_CAT,\n \"UserId %\" PRIu64 \", DownloadState %\" PRIu64 \": \"\n \"connecting to seller (%\" PRIu64 \":%u) @ %s\",\n BM_USER_ID(mDownloadState[\"userId\"]),\n mDownloadState[\"id\"]->getUInt64(),\n BM_USER_ID(mSection[\"seller\"][\"userId\"]),\n BM_SERVER_ID(mSection[\"seller\"][\"serverId\"]),\n mUrl.toString().c_str());\n\n \/\/ connect to seller\n \/\/ bfp->startReading() may take more than 30 seconds to execute\n \/\/ on seller side, so clients should set their read timeouts to\n \/\/ something high like 2-5 minutes\n \/\/ FIXME: this may need to be done in the IOMonitor\/IOWatcher, not\n \/\/ on the connection\n BtpClient* btpc = getNode()->getMessenger()->getBtpClient();\n mConnection = btpc->createConnection(\n BM_USER_ID(mSection[\"seller\"][\"userId\"]), &mUrl, 120);\n if((rval = (mConnection != NULL)))\n {\n logDownloadStateMessage(\"connected to seller...\");\n\n \/\/ create request and response\n mRequest = mConnection->createRequest();\n mResponse = mRequest->createResponse();\n\n \/\/ send message\n if((rval = btpc->sendMessage(\n &mUrl, &mOutMessage, mRequest, &mInMessage, mResponse)))\n {\n logDownloadStateMessage(\"preparing to download piece...\");\n\n \/\/ get receive content stream\n mInMessage.getContentReceiveStream(\n mResponse, mInputStream, mTrailer, mSignature);\n\n \/\/ set up output stream\n File file(mFilePiece[\"path\"]->getString());\n if(!(rval = file->mkdirs()))\n {\n ExceptionRef e = new Exception(\n \"Failed to create output directory for downloading file \"\n \"pieces.\",\n \"bitmunk.purchase.PieceDownloader.OutputFileWriteError\");\n e->getDetails()[\"path\"] = file->getPath();\n Exception::push(e);\n }\n else\n {\n mOutputStream = new FileOutputStream(file);\n }\n }\n }\n\n if(!rval)\n {\n \/\/ clean up\n if(mConnection != NULL)\n {\n mConnection->close();\n delete mConnection;\n delete mRequest;\n delete mResponse;\n }\n }\n }\n\n return rval;\n}\n\/\/ FIXME: clean these parameters up, its ugly\nvoid PieceDownloader::sendEvent(bool error, const char* type)\n{\n Event e;\n\n if(error)\n {\n \/\/ set failure event\n e[\"type\"] = EVENT_DOWNLOAD_STATE \".exception\";\n e[\"details\"][\"exception\"] = Exception::getAsDynamicObject();\n }\n else\n {\n \/\/ send success event\n e[\"type\"] = type;\n }\n\n \/\/ send event\n BM_ID_SET(e[\"details\"][\"fileId\"], mFileId);\n e[\"details\"][\"piece\"] = mFilePiece;\n e[\"details\"][\"downloaded\"] = mPieceDownloadRate->getTotalItemCount();\n sendDownloadStateEvent(e);\n}\n<|endoftext|>"} {"text":"\/****************************************************************************\n** mode2.c *****************************************************************\n****************************************************************************\n*\n* mode2 - shows the pulse\/space length of a remote button\n*\n* Copyright (C) 1998 Trent Piepho \n* Copyright (C) 1998 Christoph Bartelmus \n*\n*\/\n\n#ifdef HAVE_CONFIG_H\n# include \n#endif\n\n#ifdef _CYGWIN_\n#define __USE_LINUX_IOCTL_DEFS\n#endif\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"lirc_private.h\"\n\nstatic char* opt_device = NULL;\nstatic int opt_dmode = 0;\nstatic int t_div = 500;\nstatic unsigned int opt_gap = 10000;\nstatic int opt_raw_access = 0;\n\nstatic const char* const help =\n\t\"Usage: mode2 [options]\\n\"\n\t\"\\t -d --device=device\\tread from given device\\n\"\n\t\"\\t -H --driver=driver\\tuse given driver\\n\"\n\t\"\\t -U --plugindir=path\\tLoad plugins from path.\\n\"\n\t\"\\t -k --keep-root\\t\\tkeep root privileges\\n\"\n\t\"\\t -m --mode\\t\\tenable column display mode\\n\"\n\t\"\\t -r --raw\\t\\taccess device directly\\n\"\n\t\"\\t -g --gap=time\\t\\ttreat spaces longer than time as the gap\\n\"\n\t\"\\t -s --scope=time\\t'scope like display with time us per char.\\n\"\n\t\"\\t -h --help\\t\\tdisplay usage summary\\n\"\n\t\"\\t -v --version\\t\\tdisplay version\\n\"\n\t\"\\t -A --driver-options=key:value[|key:value...]\\n\"\n\t\"\\t\\t\\t\\tSet driver options\\n\";\n\n\nstatic const struct option options[] = {\n\t{\"help\", no_argument, NULL, 'h'},\n\t{\"version\", no_argument, NULL, 'v'},\n\t{\"device\", required_argument, NULL, 'd'},\n\t{\"driver\", required_argument, NULL, 'H'},\n\t{\"keep-root\", no_argument, NULL, 'k'},\n\t{\"mode\", no_argument, NULL, 'm'},\n\t{\"raw\", no_argument, NULL, 'r'},\n\t{\"gap\", required_argument, NULL, 'g'},\n\t{\"scope\", required_argument, NULL, 's'},\n\t{\"plugindir\", required_argument, NULL, 'U'},\n\t{\"driver-options\", required_argument, NULL, 'A'},\n\t{0,\t 0,\t\t 0, 0 }\n};\n\nconst char* const MSG_NO_GETMODE =\n\t\"Problems: this device is not a LIRC kernel device (it does not\\n\"\n\t\"support LIRC_GET_REC_MODE ioctl). This is not necessarily a\\n\"\n\t\"problem, but mode2 will not work. If you are using the --raw\\n\"\n\t\"option you might try using without it and select a driver\\n\"\n\t\"instead. Otherwise, try using lircd + irw to view the decoded\\n\"\n\t\"data - this might very well work even if mode2 doesn't.\";\n\n\nstatic void add_defaults(void)\n{\n\tchar level[4];\n\n\tsnprintf(level, sizeof(level), \"%d\", lirc_log_defaultlevel());\n\n\tconst char* const defaults[] = {\n\t\t\"mode2:driver\",\t \"default\",\n\t\t\"mode2:lircdfile\", LIRCD,\n\t\t\"lircd:logfile\", \"syslog\",\n\t\t\"lircd:debug\",\t level,\n\t\t\"lircd:plugindir\", PLUGINDIR,\n\t\t\"lircd:configfile\", LIRCDCFGFILE,\n\t\t(const char*)NULL, (const char*)NULL\n\t};\n\toptions_add_defaults(defaults);\n}\n\n\nstatic void parse_options(int argc, char** argv)\n{\n\tint c;\n\tstatic const char* const optstring = \"hvd:H:mkrg:s:U:A:\";\n\tchar driver[64];\n\n\tstrcpy(driver, \"default\");\n\tadd_defaults();\n\twhile ((c = getopt_long(argc, argv, optstring, options, NULL)) != -1) {\n\t\tswitch (c) {\n\t\tcase 'h':\n\t\t\tputs(help);\n\t\t\texit(EXIT_SUCCESS);\n\t\tcase 'H':\n\t\t\tstrncpy(driver, optarg, sizeof(driver) - 1);\n\t\t\tbreak;\n\t\tcase 'v':\n\t\t\tprintf(\"%s %s\\n\", \"mode2 \", VERSION);\n\t\t\texit(EXIT_SUCCESS);\n\t\tcase 'U':\n\t\t\toptions_set_opt(\"lircd:plugindir\", optarg);\n\t\t\tbreak;\n\t\tcase 'k':\n\t\t\tunsetenv(\"SUDO_USER\");\n\t\t\tbreak;\n\t\tcase 'd':\n\t\t\topt_device = optarg;\n\t\t\tbreak;\n\t\tcase 's':\n\t\t\topt_dmode = 2;\n\t\t\tt_div = atoi(optarg);\n\t\t\tbreak;\n\t\tcase 'm':\n\t\t\topt_dmode = 1;\n\t\t\tbreak;\n\t\tcase 'r':\n\t\t\topt_raw_access = 1;\n\t\t\tbreak;\n\t\tcase 'g':\n\t\t\topt_gap = atoi(optarg);\n\t\t\tbreak;\n\t\tcase 'A':\n\t\t\toptions_set_opt(\"lircd:driver-options\", optarg);\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tprintf(\"Usage: mode2 [options]\\n\");\n\t\t\texit(EXIT_FAILURE);\n\t\t}\n\t}\n\tif (optind < argc) {\n\t\tfputs(\"Too many arguments\\n\", stderr);\n\t\texit(EXIT_FAILURE);\n\t}\n\tif (opt_raw_access && opt_device == NULL) {\n\t\tfprintf(stderr, \"The --raw option requires a --device\\n\");\n\t\texit(EXIT_FAILURE);\n\t}\n\tif (hw_choose_driver(driver) != 0) {\n\t\tfprintf(stderr, \"Driver `%s' not found.\", driver);\n\t\tfputs(\" (Missing -U\/--plugins option?)\\n\", stderr);\n\t\tfputs(\"Available drivers:\\n\", stderr);\n\t\thw_print_drivers(stderr);\n\t\texit(EXIT_FAILURE);\n\t}\n}\n\n\n\/** Open device using curr_driver->open_func() and curr_driver->init_func().*\/\nint open_device(int opt_raw_access, const char* device)\n{\n\tstruct stat s;\n\n\t__u32 mode;\n\tint fd;\n\tconst char* opt;\n\n\tif (opt_raw_access) {\n\t\tfd = open(device, O_RDONLY);\n\t\tif (fd == -1) {\n\t\t\tdevice = device ? device : \"(Null)\";\n\t\t\tperrorf(\"Error while opening device: %s\", device);\n\t\t\texit(EXIT_FAILURE);\n\t\t}\n\t\t;\n\t\tif ((fstat(fd, &s) != -1) && (S_ISFIFO(s.st_mode))) {\n\t\t\t\/* can't do ioctls on a pipe *\/\n\t\t} else if ((fstat(fd, &s) != -1) && (!S_ISCHR(s.st_mode))) {\n\t\t\tfprintf(stderr, \"%s is not a character device\\n\",\n\t\t\t\tdevice);\n\t\t\tfputs(\"Use the -d option to specify device\\n\",\n\t\t\t stderr);\n\t\t\tclose(fd);\n\t\t\texit(EXIT_FAILURE);\n\t\t} else if (ioctl(fd, LIRC_GET_REC_MODE, &mode) == -1) {\n\t\t\tputs(MSG_NO_GETMODE);\n\t\t\tclose(fd);\n\t\t\texit(EXIT_FAILURE);\n\t\t}\n\t} else {\n\t\tcurr_driver->open_func(device);\n\t\topt = options_getstring(\"lircd:driver-options\");\n\t\tif (opt != NULL)\n\t\t\tif (drv_handle_options(opt) != 0) {\n\t\t\t\tfprintf(stderr,\n\t\t\t\t\"Cannot set driver (%s) options (%s)\\n\",\n\t\t\t\tcurr_driver->name, opt);\n\t\t\t\texit(EXIT_FAILURE);\n\t\t\t}\n\t\tif (!curr_driver->init_func || !curr_driver->init_func()) {\n\t\t\tfprintf(stderr, \"Cannot initiate device %s\\n\",\n\t\t\t\tcurr_driver->device);\n\t\t\texit(EXIT_FAILURE);\n\t\t}\n\t\tprintf(\"Using device: %s\\n\", curr_driver->device);\n\t\tfd = curr_driver->fd; \/* please compiler *\/\n\t\tmode = curr_driver->rec_mode;\n\t\tif (mode != LIRC_MODE_MODE2) {\n\t\t\tif (strcmp(curr_driver->name, \"default\") == 0) {\n\t\t\t\tputs(\"Please use the --raw option to access \"\n\t\t\t\t \"the device directly instead through\\n\"\n\t\t\t\t \"the abstraction layer\");\n\t\t\t\texit(EXIT_FAILURE);\n\t\t\t} else if (mode != LIRC_MODE_LIRCCODE) {\n\t\t\t\tputs(\"Internal error: bad receive mode\");\n\t\t\t\texit(EXIT_FAILURE);\n\t\t\t}\n\t\t}\n\t}\n\tif (opt_device && strcmp(opt_device, LIRCD) == 0) {\n\t\tfputs(\"Refusing to connect to lircd socket\\n\", stderr);\n\t\texit(EXIT_FAILURE);\n\t}\n\tprintf(\"Using device: %s\\n\", curr_driver->device);\n\treturn fd;\n}\n\n\n\/** Define loglevel and open the log file. *\/\nstatic void setup_log(void)\n{\n\tchar path[128];\n\tconst char* loglevel;\n\n\tloglevel = getenv(\"LIRC_LOGLEVEL\");\n\tif (loglevel == NULL) {\n\t\tloglevel = \"LIRC_NOTICE\";\n\t} else if (string2loglevel(loglevel) == LIRC_BADLEVEL) {\n\t\tfprintf(stderr, \"Bad LIRC_LOGLEVEL: %s\\n\", loglevel);\n\t\tloglevel = \"LIRC_NOTICE\";\n\t}\n\tlirc_log_get_clientlog(\"mode2\", path, sizeof(path));\n\tlirc_log_set_file(path);\n\tlirc_log_open(\"mode2\", 1, string2loglevel(loglevel));\n}\n\n\n\/** Get the codelength (bits per decoded value) for lirccode data. *\/\nunsigned int get_codelength(int fd, int use_raw_access)\n{\n\tunsigned int code_length;\n\tint r = 1;\n\n\tif (use_raw_access) {\n\t\tif (ioctl(fd, LIRC_GET_LENGTH, &code_length) == -1) {\n\t\t\tperror(\"Could not get code length\");\n\t\t\tclose(fd);\n\t\t\texit(EXIT_FAILURE);\n\t\t}\n\t\treturn code_length;\n\t}\n\tif (curr_driver->drvctl_func) {\n\t\tr = curr_driver->drvctl_func(DRVCTL_GET_RAW_CODELENGTH,\n\t\t\t\t\t &code_length);\n\t}\n\tif (r != 0)\n\t\tcode_length = curr_driver->code_length;\n\treturn code_length;\n}\n\n\n\/** Print mode2 data as pulse\/space durations, one per line. *\/\nvoid print_mode2_data(unsigned int data)\n{\n\tstatic int bitno = 1;\n\n\tswitch (opt_dmode) {\n\tcase 0:\n\t\tprintf(\"%s %u\\n\", (\n\t\t\t data & PULSE_BIT) ? \"pulse\" : \"space\",\n\t\t (__u32)(data & PULSE_MASK));\n\t\tbreak;\n\tcase 1: {\n\t\t\/* print output like irrecord raw config file data *\/\n\t\tprintf(\" %8u\", (__u32)data & PULSE_MASK);\n\t\t++bitno;\n\t\tif (data & PULSE_BIT) {\n\t\t\tif ((bitno & 1) == 0)\n\t\t\t\t\/* not in expected order *\/\n\t\t\t\tfputs(\"-pulse\", stdout);\n\t\t} else {\n\t\t\tif (bitno & 1)\n\t\t\t\t\/* not in expected order *\/\n\t\t\t\tfputs(\"-space\", stdout);\n\t\t\tif (((data & PULSE_MASK) > opt_gap) || (bitno >= 6)) {\n\t\t\t\t\/* real long space or more\n\t\t\t\t * than 6 codes, start new line *\/\n\t\t\t\tputs(\"\");\n\t\t\t\tif ((data & PULSE_MASK) > opt_gap)\n\t\t\t\t\tputs(\"\");\n\t\t\t\tbitno = 0;\n\t\t\t}\n\t\t}\n\t\tbreak;\n\t}\n\tcase 2:\n\t\tif ((data & PULSE_MASK) > opt_gap) {\n\t\t\tfputs(\"_\\n\\n_\", stdout);\n\t\t} else {\n\t\t\tprintf(\"%.*s\",\n\t\t\t ((data & PULSE_MASK) + t_div \/ 2) \/ t_div,\n\t\t\t (data & PULSE_BIT) ?\n\t\t\t \"------------\" : \"____________\");\n\t\t}\n\t\tbreak;\n\t}\n\tfflush(stdout);\n}\n\n\n\/** Print lirccode data as a decoded value (an integer) per line. *\/\nvoid print_lirccode_data(char* buffer, size_t count)\n{\n\tsize_t i;\n\n\tfputs(\"code: 0x\", stdout);\n\tfor (i = 0; i < count; i++)\n\t\tprintf(\"%02x\", (unsigned char)buffer[i]);\n\tputs(\"\");\n\tfflush(stdout);\n}\n\n\n\/**\n * Process next button press and print a dump, return boolean OK\/FAIL.\n *\/\nint next_press(int fd, int mode, int bytes)\n{\n\tchar buffspace[bytes];\n\tint r;\n union {\n\t\tchar* buffer;\n\t\tlirc_t data;\n\t} input;\n\n\tinput.buffer = buffspace;\n\tif (opt_raw_access || mode != LIRC_MODE_MODE2) {\n\t\tr = read(fd, input.buffer, bytes);\n\t\tif (r == -1)\n\t\t\tperrorf(\"read() error on %s\", opt_device);\n\t\telse if (r != (int)bytes)\n\t\t\tfprintf(stderr, \"Partial read %d bytes on %s\",\n\t\t\t\tr, opt_device);\n\t\tif (r != (int)bytes)\n\t\t\treturn 0;\n\t\tif (mode == LIRC_MODE_MODE2)\n\t\t\tprint_mode2_data(input.data);\n\t\telse\n\t\t\tprint_lirccode_data(input.buffer, bytes);\n\t} else {\n\t\tinput.data = curr_driver->readdata(0);\n\t\tif (input.data == 0) {\n\t\t\tfputs(\"readdata() failed\\n\", stderr);\n\t\t\treturn 0;\n\t\t}\n\t\tprint_mode2_data(input.data);\n\t}\n\treturn 1;\n}\n\n\nint main(int argc, char** argv)\n{\n\tint fd;\n\t__u32 mode;\n\tsize_t bytes = sizeof(lirc_t);\n\t\/**\n\t * Was hard coded to 50000 but this is too long, the shortest gap in the\n\t * supplied .conf files is 10826, the longest space defined for any one,\n\t * zero or header is 7590\n\t *\/\n\t__u32 code_length;\n\n\thw_choose_driver(NULL);\n\toptions_load(argc, argv, NULL, parse_options);\n\tsetup_log();\n\tfd = open_device(opt_raw_access, opt_device);\n\tif (geteuid() == 0)\n\t\tdrop_root_cli(setuid);\n\tmode = curr_driver->rec_mode;\n\tif (mode == LIRC_MODE_LIRCCODE) {\n\t\tcode_length = get_codelength(fd, opt_raw_access);\n\t\tbytes = (code_length + CHAR_BIT - 1) \/ CHAR_BIT;\n\t}\n\twhile (next_press(fd, mode, bytes))\n\t\t;\n\treturn EXIT_SUCCESS;\n}\nmode2: Clean up stdout\/stderr output(#142).\/****************************************************************************\n** mode2.c *****************************************************************\n****************************************************************************\n*\n* mode2 - shows the pulse\/space length or decoded values of remote buttons.\n*\n*\n* Copyright (C) 1998 Trent Piepho \n* Copyright (C) 1998 Christoph Bartelmus \n*\n*\/\n\n\/*\n * TODO: Close stuff (call curr_driver->close_func(), closing logs)\n * when a terminating signal arrives.\n *\/\n\n#ifdef HAVE_CONFIG_H\n# include \n#endif\n\n#ifdef _CYGWIN_\n#define __USE_LINUX_IOCTL_DEFS\n#endif\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"lirc_private.h\"\n\nstatic char* opt_device = NULL;\nstatic int opt_dmode = 0;\nstatic int t_div = 500;\nstatic unsigned int opt_gap = 10000;\nstatic int opt_raw_access = 0;\n\nstatic const char* const help =\n\t\"Usage: mode2 [options]\\n\"\n\t\"\\t -d --device=device\\tread from given device\\n\"\n\t\"\\t -H --driver=driver\\tuse given driver\\n\"\n\t\"\\t -U --plugindir=path\\tLoad plugins from path.\\n\"\n\t\"\\t -k --keep-root\\t\\tkeep root privileges\\n\"\n\t\"\\t -m --mode\\t\\tenable column display mode\\n\"\n\t\"\\t -r --raw\\t\\taccess device directly\\n\"\n\t\"\\t -g --gap=time\\t\\ttreat spaces longer than time as the gap\\n\"\n\t\"\\t -s --scope=time\\t'scope like display with time us per char.\\n\"\n\t\"\\t -h --help\\t\\tdisplay usage summary\\n\"\n\t\"\\t -v --version\\t\\tdisplay version\\n\"\n\t\"\\t -A --driver-options=key:value[|key:value...]\\n\"\n\t\"\\t\\t\\t\\tSet driver options\\n\";\n\n\nstatic const struct option options[] = {\n\t{\"help\", no_argument, NULL, 'h'},\n\t{\"version\", no_argument, NULL, 'v'},\n\t{\"device\", required_argument, NULL, 'd'},\n\t{\"driver\", required_argument, NULL, 'H'},\n\t{\"keep-root\", no_argument, NULL, 'k'},\n\t{\"mode\", no_argument, NULL, 'm'},\n\t{\"raw\", no_argument, NULL, 'r'},\n\t{\"gap\", required_argument, NULL, 'g'},\n\t{\"scope\", required_argument, NULL, 's'},\n\t{\"plugindir\", required_argument, NULL, 'U'},\n\t{\"driver-options\", required_argument, NULL, 'A'},\n\t{0,\t 0,\t\t 0, 0 }\n};\n\nconst char* const MSG_NO_GETMODE =\n\"Problems: this device is not a LIRC kernel device (it does not\\n\"\n\"support LIRC_GET_REC_MODE ioctl). This is not necessarily a\\n\"\n\"problem, but mode2 will not work. If you are using the --raw\\n\"\n\"option you might try using without it and select a driver\\n\"\n\"instead. Otherwise, try using lircd + irw to view the decoded\\n\"\n\"data - this might very well work even if mode2 doesn't.\\n\";\n\nconst char* const USE_RAW_MSG =\n\"Please use the --raw option to access the device directly instead\"\n\" through the abstraction layer\\n\";\n\nstatic void add_defaults(void)\n{\n\tchar level[4];\n\n\tsnprintf(level, sizeof(level), \"%d\", lirc_log_defaultlevel());\n\n\tconst char* const defaults[] = {\n\t\t\"mode2:driver\",\t \"default\",\n\t\t\"mode2:lircdfile\", LIRCD,\n\t\t\"lircd:logfile\", \"syslog\",\n\t\t\"lircd:debug\",\t level,\n\t\t\"lircd:plugindir\", PLUGINDIR,\n\t\t\"lircd:configfile\", LIRCDCFGFILE,\n\t\t(const char*)NULL, (const char*)NULL\n\t};\n\toptions_add_defaults(defaults);\n}\n\n\nstatic void parse_options(int argc, char** argv)\n{\n\tint c;\n\tstatic const char* const optstring = \"hvd:H:mkrg:s:U:A:\";\n\tchar driver[64];\n\n\tstrcpy(driver, \"default\");\n\tadd_defaults();\n\twhile ((c = getopt_long(argc, argv, optstring, options, NULL)) != -1) {\n\t\tswitch (c) {\n\t\tcase 'h':\n\t\t\tputs(help);\n\t\t\texit(EXIT_SUCCESS);\n\t\tcase 'H':\n\t\t\tstrncpy(driver, optarg, sizeof(driver) - 1);\n\t\t\tbreak;\n\t\tcase 'v':\n\t\t\tprintf(\"%s %s\\n\", \"mode2 \", VERSION);\n\t\t\texit(EXIT_SUCCESS);\n\t\tcase 'U':\n\t\t\toptions_set_opt(\"lircd:plugindir\", optarg);\n\t\t\tbreak;\n\t\tcase 'k':\n\t\t\tunsetenv(\"SUDO_USER\");\n\t\t\tbreak;\n\t\tcase 'd':\n\t\t\topt_device = optarg;\n\t\t\tbreak;\n\t\tcase 's':\n\t\t\topt_dmode = 2;\n\t\t\tt_div = atoi(optarg);\n\t\t\tbreak;\n\t\tcase 'm':\n\t\t\topt_dmode = 1;\n\t\t\tbreak;\n\t\tcase 'r':\n\t\t\topt_raw_access = 1;\n\t\t\tbreak;\n\t\tcase 'g':\n\t\t\topt_gap = atoi(optarg);\n\t\t\tbreak;\n\t\tcase 'A':\n\t\t\toptions_set_opt(\"lircd:driver-options\", optarg);\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tfprintf(stderr, \"Usage: mode2 [options]\\n\");\n\t\t\texit(EXIT_FAILURE);\n\t\t}\n\t}\n\tif (optind < argc) {\n\t\tfputs(\"Too many arguments\\n\", stderr);\n\t\texit(EXIT_FAILURE);\n\t}\n\tif (opt_raw_access && opt_device == NULL) {\n\t\tfprintf(stderr, \"The --raw option requires a --device\\n\");\n\t\texit(EXIT_FAILURE);\n\t}\n\tif (hw_choose_driver(driver) != 0) {\n\t\tfprintf(stderr, \"Driver `%s' not found.\", driver);\n\t\tfputs(\" (Missing -U\/--plugins option?)\\n\", stderr);\n\t\tfputs(\"Available drivers:\\n\", stderr);\n\t\thw_print_drivers(stderr);\n\t\texit(EXIT_FAILURE);\n\t}\n}\n\n\n\/** Open device using curr_driver->open_func() and curr_driver->init_func().*\/\nint open_device(int opt_raw_access, const char* device)\n{\n\tstruct stat s;\n\n\t__u32 mode;\n\tint fd;\n\tconst char* opt;\n\n\tif (opt_raw_access) {\n\t\tfd = open(device, O_RDONLY);\n\t\tif (fd == -1) {\n\t\t\tdevice = device ? device : \"(Null)\";\n\t\t\tperrorf(\"Error while opening device: %s\", device);\n\t\t\texit(EXIT_FAILURE);\n\t\t}\n\t\t;\n\t\tif ((fstat(fd, &s) != -1) && (S_ISFIFO(s.st_mode))) {\n\t\t\t\/* can't do ioctls on a pipe *\/\n\t\t} else if ((fstat(fd, &s) != -1) && (!S_ISCHR(s.st_mode))) {\n\t\t\tfprintf(stderr, \"%s is not a character device\\n\",\n\t\t\t\tdevice);\n\t\t\tfputs(\"Use the -d option to specify device\\n\",\n\t\t\t stderr);\n\t\t\tclose(fd);\n\t\t\texit(EXIT_FAILURE);\n\t\t} else if (ioctl(fd, LIRC_GET_REC_MODE, &mode) == -1) {\n\t\t\tfputs(MSG_NO_GETMODE, stderr);\n\t\t\tclose(fd);\n\t\t\texit(EXIT_FAILURE);\n\t\t}\n\t} else {\n\t\tcurr_driver->open_func(device);\n\t\topt = options_getstring(\"lircd:driver-options\");\n\t\tif (opt != NULL)\n\t\t\tif (drv_handle_options(opt) != 0) {\n\t\t\t\tfprintf(stderr,\n\t\t\t\t\"Cannot set driver (%s) options (%s)\\n\",\n\t\t\t\tcurr_driver->name, opt);\n\t\t\t\texit(EXIT_FAILURE);\n\t\t\t}\n\t\tif (!curr_driver->init_func || !curr_driver->init_func()) {\n\t\t\tfprintf(stderr, \"Cannot initiate device %s\\n\",\n\t\t\t\tcurr_driver->device);\n\t\t\texit(EXIT_FAILURE);\n\t\t}\n\t\tfprintf(stderr, \"Trying device: %s\\n\", curr_driver->device);\n\t\tfd = curr_driver->fd; \/* please compiler *\/\n\t\tmode = curr_driver->rec_mode;\n\t\tif (mode != LIRC_MODE_MODE2) {\n\t\t\tif (strcmp(curr_driver->name, \"default\") == 0) {\n\t\t\t\tfputs(USE_RAW_MSG, stderr);\n\t\t\t\texit(EXIT_FAILURE);\n\t\t\t} else if (mode != LIRC_MODE_LIRCCODE) {\n\t\t\t\tfputs(\"Internal error: bad receive mode\\n\",\n\t\t\t\t stderr);\n\t\t\t\texit(EXIT_FAILURE);\n\t\t\t}\n\t\t}\n\t}\n\tif (opt_device && strcmp(opt_device, LIRCD) == 0) {\n\t\tfputs(\"Refusing to connect to lircd socket\\n\", stderr);\n\t\texit(EXIT_FAILURE);\n\t}\n\tfprintf(stderr, \"Using device: %s\\n\", curr_driver->device);\n\treturn fd;\n}\n\n\n\/** Define loglevel and open the log file. *\/\nstatic void setup_log(void)\n{\n\tchar path[128];\n\tconst char* loglevel;\n\n\tloglevel = getenv(\"LIRC_LOGLEVEL\");\n\tif (loglevel == NULL) {\n\t\tloglevel = \"DEBUG\";\n\t} else if (string2loglevel(loglevel) == LIRC_BADLEVEL) {\n\t\tfprintf(stderr, \"Bad LIRC_LOGLEVEL: %s\\n\", loglevel);\n\t\tloglevel = \"DEBUG\";\n\t}\n\tlirc_log_get_clientlog(\"mode2\", path, sizeof(path));\n\tlirc_log_set_file(path);\n\tlirc_log_open(\"mode2\", 1, string2loglevel(loglevel));\n}\n\n\n\/** Get the codelength (bits per decoded value) for lirccode data. *\/\nunsigned int get_codelength(int fd, int use_raw_access)\n{\n\tunsigned int code_length;\n\tint r = 1;\n\n\tif (use_raw_access) {\n\t\tif (ioctl(fd, LIRC_GET_LENGTH, &code_length) == -1) {\n\t\t\tperror(\"Could not get code length\");\n\t\t\tclose(fd);\n\t\t\texit(EXIT_FAILURE);\n\t\t}\n\t\treturn code_length;\n\t}\n\tif (curr_driver->drvctl_func) {\n\t\tr = curr_driver->drvctl_func(DRVCTL_GET_RAW_CODELENGTH,\n\t\t\t\t\t &code_length);\n\t}\n\tif (r != 0)\n\t\tcode_length = curr_driver->code_length;\n\treturn code_length;\n}\n\n\n\/** Print mode2 data as pulse\/space durations, one per line. *\/\nvoid print_mode2_data(unsigned int data)\n{\n\tstatic int bitno = 1;\n\n\tswitch (opt_dmode) {\n\tcase 0:\n\t\tprintf(\"%s %u\\n\", (\n\t\t\t data & PULSE_BIT) ? \"pulse\" : \"space\",\n\t\t (__u32)(data & PULSE_MASK));\n\t\tbreak;\n\tcase 1: {\n\t\t\/* print output like irrecord raw config file data *\/\n\t\tprintf(\" %8u\", (__u32)data & PULSE_MASK);\n\t\t++bitno;\n\t\tif (data & PULSE_BIT) {\n\t\t\tif ((bitno & 1) == 0)\n\t\t\t\t\/* not in expected order *\/\n\t\t\t\tfputs(\"-pulse\", stdout);\n\t\t} else {\n\t\t\tif (bitno & 1)\n\t\t\t\t\/* not in expected order *\/\n\t\t\t\tfputs(\"-space\", stdout);\n\t\t\tif (((data & PULSE_MASK) > opt_gap) || (bitno >= 6)) {\n\t\t\t\t\/* real long space or more\n\t\t\t\t * than 6 codes, start new line *\/\n\t\t\t\tputs(\"\");\n\t\t\t\tif ((data & PULSE_MASK) > opt_gap)\n\t\t\t\t\tputs(\"\");\n\t\t\t\tbitno = 0;\n\t\t\t}\n\t\t}\n\t\tbreak;\n\t}\n\tcase 2:\n\t\tif ((data & PULSE_MASK) > opt_gap) {\n\t\t\tfputs(\"_\\n\\n_\", stdout);\n\t\t} else {\n\t\t\tprintf(\"%.*s\",\n\t\t\t ((data & PULSE_MASK) + t_div \/ 2) \/ t_div,\n\t\t\t (data & PULSE_BIT) ?\n\t\t\t \"------------\" : \"____________\");\n\t\t}\n\t\tbreak;\n\t}\n\tfflush(stdout);\n}\n\n\n\/** Print lirccode data as a decoded value (an integer) per line. *\/\nvoid print_lirccode_data(char* buffer, size_t count)\n{\n\tsize_t i;\n\n\tfputs(\"code: 0x\", stdout);\n\tfor (i = 0; i < count; i++)\n\t\tprintf(\"%02x\", (unsigned char)buffer[i]);\n\tputs(\"\");\n\tfflush(stdout);\n}\n\n\n\/**\n * Process next button press and print a dump, return boolean OK\/FAIL.\n *\/\nint next_press(int fd, int mode, int bytes)\n{\n\tchar buffspace[bytes];\n\tint r;\n union {\n\t\tchar* buffer;\n\t\tlirc_t data;\n\t} input;\n\n\tinput.buffer = buffspace;\n\tif (opt_raw_access || mode != LIRC_MODE_MODE2) {\n\t\tr = read(fd, input.buffer, bytes);\n\t\tif (r == -1)\n\t\t\tperrorf(\"read() error on %s\", opt_device);\n\t\telse if (r != (int)bytes)\n\t\t\tfprintf(stderr, \"Partial read %d bytes on %s\",\n\t\t\t\tr, opt_device);\n\t\tif (r != (int)bytes)\n\t\t\treturn 0;\n\t\tif (mode == LIRC_MODE_MODE2)\n\t\t\tprint_mode2_data(input.data);\n\t\telse\n\t\t\tprint_lirccode_data(input.buffer, bytes);\n\t} else {\n\t\tinput.data = curr_driver->readdata(0);\n\t\tif (input.data == 0) {\n\t\t\tfputs(\"readdata() failed\\n\", stderr);\n\t\t\treturn 0;\n\t\t}\n\t\tprint_mode2_data(input.data);\n\t}\n\treturn 1;\n}\n\n\nint main(int argc, char** argv)\n{\n\tint fd;\n\t__u32 mode;\n\tsize_t bytes = sizeof(lirc_t);\n\t\/**\n\t * Was hard coded to 50000 but this is too long, the shortest gap in the\n\t * supplied .conf files is 10826, the longest space defined for any one,\n\t * zero or header is 7590\n\t *\/\n\t__u32 code_length;\n\n\thw_choose_driver(NULL);\n\toptions_load(argc, argv, NULL, parse_options);\n\tsetup_log();\n\tfd = open_device(opt_raw_access, opt_device);\n\tif (geteuid() == 0)\n\t\tdrop_root_cli(setuid);\n\tmode = curr_driver->rec_mode;\n\tif (mode == LIRC_MODE_LIRCCODE) {\n\t\tcode_length = get_codelength(fd, opt_raw_access);\n\t\tbytes = (code_length + CHAR_BIT - 1) \/ CHAR_BIT;\n\t}\n\twhile (next_press(fd, mode, bytes))\n\t\t;\n\treturn EXIT_SUCCESS;\n}\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2008, Google Inc.\n\/\/ All rights reserved.\n\/\/ \n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are\n\/\/ met:\n\/\/ \n\/\/ * Redistributions of source code must retain the above copyright\n\/\/ notice, this list of conditions and the following disclaimer.\n\/\/ * Redistributions in binary form must reproduce the above\n\/\/ copyright notice, this list of conditions and the following disclaimer\n\/\/ in the documentation and\/or other materials provided with the\n\/\/ distribution.\n\/\/ * Neither the name of Google Inc. nor the names of its\n\/\/ contributors may be used to endorse or promote products derived from\n\/\/ this software without specific prior written permission.\n\/\/ \n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\/\/ \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n\/\/ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n\/\/ A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n\/\/ OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n\/\/ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n\/\/ LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n\/\/ DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n\/\/ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n\/\/ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n\/\/ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n#include \"config.h\"\n\n#include \"v8_helpers.h\"\n#include \"v8_npobject.h\"\n#include \"v8_np_utils.h\"\n#include \"np_v8object.h\"\n#include \"npruntime_priv.h\"\n#include \"v8_proxy.h\"\n#include \"dom_wrapper_map.h\"\n#include \"HTMLPlugInElement.h\"\n#include \"V8HTMLAppletElement.h\"\n#include \"V8HTMLEmbedElement.h\"\n#include \"V8HTMLObjectElement.h\"\n\nusing namespace WebCore;\n\nenum InvokeFunctionType {\n INVOKE_METHOD = 1,\n INVOKE_DEFAULT = 2\n};\n\n\/\/ TODO(mbelshe): need comments.\n\/\/ Params: holder could be HTMLEmbedElement or NPObject\nstatic v8::Handle NPObjectInvokeImpl(\n const v8::Arguments& args, InvokeFunctionType func_id) {\n NPObject* npobject;\n\n \/\/ These three types are subtypes of HTMLPlugInElement.\n if (V8HTMLAppletElement::HasInstance(args.Holder()) ||\n V8HTMLEmbedElement::HasInstance(args.Holder()) ||\n V8HTMLObjectElement::HasInstance(args.Holder())) {\n \/\/ The holder object is a subtype of HTMLPlugInElement.\n HTMLPlugInElement* imp =\n V8Proxy::DOMWrapperToNode(args.Holder());\n v8::Handle instance = imp->getInstance();\n npobject = V8Proxy::ToNativeObject(\n V8ClassIndex::NPOBJECT, instance);\n\n } else {\n \/\/ The holder object is not a subtype of HTMLPlugInElement, it\n \/\/ must be an NPObject which has three internal fields.\n ASSERT(args.Holder()->InternalFieldCount() == 3);\n npobject = V8Proxy::ToNativeObject(\n V8ClassIndex::NPOBJECT, args.Holder());\n }\n\n \/\/ Verify that our wrapper wasn't using a NPObject which\n \/\/ has already been deleted.\n if (!npobject || !_NPN_IsAlive(npobject)) {\n V8Proxy::ThrowError(V8Proxy::REFERENCE_ERROR, \"NPObject deleted\");\n return v8::Undefined();\n }\n\n \/\/ wrap up parameters\n int argc = args.Length();\n NPVariant* np_args = new NPVariant[argc];\n\n for (int i = 0; i < argc; i++) {\n ConvertV8ObjectToNPVariant(args[i], npobject, &np_args[i]);\n }\n\n NPVariant result;\n VOID_TO_NPVARIANT(result);\n\n switch (func_id) {\n case INVOKE_METHOD:\n if (npobject->_class->invoke) {\n v8::Handle function_name(v8::String::Cast(*args.Data()));\n NPIdentifier ident = GetStringIdentifier(function_name);\n npobject->_class->invoke(npobject, ident, np_args, argc, &result);\n }\n break;\n case INVOKE_DEFAULT:\n if (npobject->_class->invokeDefault) {\n npobject->_class->invokeDefault(npobject, np_args, argc, &result);\n }\n break;\n default:\n break;\n }\n\n for (int i=0; i < argc; i++) {\n NPN_ReleaseVariantValue(&np_args[i]);\n }\n delete[] np_args;\n\n \/\/ unwrap return values\n v8::Handle rv = ConvertNPVariantToV8Object(&result, npobject);\n NPN_ReleaseVariantValue(&result);\n\n return rv;\n}\n\n\nv8::Handle NPObjectMethodHandler(const v8::Arguments& args) {\n return NPObjectInvokeImpl(args, INVOKE_METHOD);\n}\n\n\nv8::Handle NPObjectInvokeDefaultHandler(const v8::Arguments& args) {\n return NPObjectInvokeImpl(args, INVOKE_DEFAULT);\n}\n\n\nstatic void WeakTemplateCallback(v8::Persistent obj, void* param);\n\n\/\/ NPIdentifier is PrivateIdentifier*.\nstatic WeakReferenceMap \\\n static_template_map(&WeakTemplateCallback);\n\nstatic void WeakTemplateCallback(v8::Persistent obj,\n void* param) {\n PrivateIdentifier* iden = static_cast(param);\n ASSERT(iden != NULL);\n ASSERT(static_template_map.contains(iden));\n\n static_template_map.forget(iden);\n}\n\n\nstatic v8::Handle NPObjectGetProperty(v8::Local self,\n NPIdentifier ident,\n v8::Local key) {\n NPObject* npobject = V8Proxy::ToNativeObject(V8ClassIndex::NPOBJECT,\n self);\n\n \/\/ Verify that our wrapper wasn't using a NPObject which\n \/\/ has already been deleted.\n if (!npobject || !_NPN_IsAlive(npobject)) {\n V8Proxy::ThrowError(V8Proxy::REFERENCE_ERROR, \"NPObject deleted\");\n return v8::Handle();\n }\n\n if (npobject->_class->hasProperty &&\n npobject->_class->hasProperty(npobject, ident) &&\n npobject->_class->getProperty) {\n NPVariant result;\n VOID_TO_NPVARIANT(result);\n if (!npobject->_class->getProperty(npobject, ident, &result)) {\n return v8::Handle();\n }\n\n v8::Handle rv = ConvertNPVariantToV8Object(&result, npobject);\n NPN_ReleaseVariantValue(&result);\n return rv;\n\n } else if (key->IsString() &&\n npobject->_class->hasMethod &&\n npobject->_class->hasMethod(npobject, ident)) {\n PrivateIdentifier* id = static_cast(ident);\n v8::Persistent desc = static_template_map.get(id);\n \/\/ Cache templates using identifier as the key.\n if (desc.IsEmpty()) {\n \/\/ Create a new template\n v8::Local temp = v8::FunctionTemplate::New();\n temp->SetCallHandler(NPObjectMethodHandler, key);\n desc = v8::Persistent::New(temp);\n static_template_map.set(id, desc);\n }\n\n \/\/ FunctionTemplate caches function for each context.\n v8::Local func = desc->GetFunction();\n func->SetName(v8::Handle::Cast(key));\n return func;\n }\n\n return v8::Handle();\n}\n\nv8::Handle NPObjectNamedPropertyGetter(v8::Local name,\n const v8::AccessorInfo& info) {\n NPIdentifier ident = GetStringIdentifier(name);\n return NPObjectGetProperty(info.Holder(), ident, name);\n}\n\nv8::Handle NPObjectIndexedPropertyGetter(uint32_t index,\n const v8::AccessorInfo& info) {\n NPIdentifier ident = NPN_GetIntIdentifier(index);\n return NPObjectGetProperty(info.Holder(), ident, v8::Number::New(index));\n}\n\nv8::Handle NPObjectGetNamedProperty(v8::Local self,\n v8::Local name) {\n NPIdentifier ident = GetStringIdentifier(name);\n return NPObjectGetProperty(self, ident, name);\n}\n\nv8::Handle NPObjectGetIndexedProperty(v8::Local self,\n uint32_t index) {\n NPIdentifier ident = NPN_GetIntIdentifier(index);\n return NPObjectGetProperty(self, ident, v8::Number::New(index));\n}\n\nstatic v8::Handle NPObjectSetProperty(v8::Local self,\n NPIdentifier ident,\n v8::Local value) {\n NPObject* npobject =\n V8Proxy::ToNativeObject(V8ClassIndex::NPOBJECT, self);\n\n \/\/ Verify that our wrapper wasn't using a NPObject which\n \/\/ has already been deleted.\n if (!npobject || !_NPN_IsAlive(npobject)) {\n V8Proxy::ThrowError(V8Proxy::REFERENCE_ERROR, \"NPObject deleted\");\n return value; \/\/ intercepted, but an exception was thrown\n }\n\n if (npobject->_class->hasProperty &&\n npobject->_class->hasProperty(npobject, ident) &&\n npobject->_class->setProperty) {\n NPVariant npvalue;\n VOID_TO_NPVARIANT(npvalue);\n ConvertV8ObjectToNPVariant(value, npobject, &npvalue);\n bool succ = npobject->_class->setProperty(npobject, ident, &npvalue);\n NPN_ReleaseVariantValue(&npvalue);\n if (succ) return value; \/\/ intercept the call\n }\n return v8::Local(); \/\/ do not intercept the call\n}\n\n\nv8::Handle NPObjectNamedPropertySetter(v8::Local name,\n v8::Local value,\n const v8::AccessorInfo& info) {\n NPIdentifier ident = GetStringIdentifier(name);\n return NPObjectSetProperty(info.Holder(), ident, value);\n}\n\n\nv8::Handle NPObjectIndexedPropertySetter(uint32_t index,\n v8::Local value,\n const v8::AccessorInfo& info) {\n NPIdentifier ident = NPN_GetIntIdentifier(index);\n return NPObjectSetProperty(info.Holder(), ident, value);\n}\n\nv8::Handle NPObjectSetNamedProperty(v8::Local self,\n v8::Local name,\n v8::Local value) {\n NPIdentifier ident = GetStringIdentifier(name);\n return NPObjectSetProperty(self, ident, value);\n}\n\nv8::Handle NPObjectSetIndexedProperty(v8::Local self,\n uint32_t index,\n v8::Local value) {\n NPIdentifier ident = NPN_GetIntIdentifier(index);\n return NPObjectSetProperty(self, ident, value);\n}\n\n\nstatic void WeakNPObjectCallback(v8::Persistent obj, void* param);\n\nstatic DOMWrapperMap static_npobject_map(&WeakNPObjectCallback);\n\nstatic void WeakNPObjectCallback(v8::Persistent obj,\n void* param) {\n NPObject* npobject = static_cast(param);\n ASSERT(static_npobject_map.contains(npobject));\n ASSERT(npobject != NULL);\n\n \/\/ Must remove from our map before calling NPN_ReleaseObject().\n \/\/ NPN_ReleaseObject can call ForgetV8ObjectForNPObject, which\n \/\/ uses the table as well.\n static_npobject_map.forget(npobject);\n\n if (_NPN_IsAlive(npobject))\n NPN_ReleaseObject(npobject);\n}\n\n\nv8::Local CreateV8ObjectForNPObject(NPObject* object,\n NPObject* root) {\n static v8::Persistent np_object_desc;\n\n ASSERT(v8::Context::InContext());\n\n \/\/ If this is a v8 object, just return it.\n if (object->_class == NPScriptObjectClass) {\n V8NPObject* v8npobject = reinterpret_cast(object);\n return v8::Local::New(v8npobject->v8_object);\n }\n\n \/\/ If we've already wrapped this object, just return it.\n if (static_npobject_map.contains(object))\n return v8::Local::New(static_npobject_map.get(object));\n\n \/\/ TODO: we should create a Wrapper type as a subclass of JSObject.\n \/\/ It has two internal fields, field 0 is the wrapped pointer,\n \/\/ and field 1 is the type. There should be an api function that\n \/\/ returns unused type id.\n \/\/ The same Wrapper type can be used by DOM bindings.\n if (np_object_desc.IsEmpty()) {\n np_object_desc =\n v8::Persistent::New(v8::FunctionTemplate::New());\n np_object_desc->InstanceTemplate()->SetInternalFieldCount(3);\n np_object_desc->InstanceTemplate()->SetNamedPropertyHandler(\n NPObjectNamedPropertyGetter, NPObjectNamedPropertySetter);\n np_object_desc->InstanceTemplate()->SetIndexedPropertyHandler(\n NPObjectIndexedPropertyGetter, NPObjectIndexedPropertySetter);\n np_object_desc->InstanceTemplate()->SetCallAsFunctionHandler(\n NPObjectInvokeDefaultHandler); \n }\n\n v8::Handle func = np_object_desc->GetFunction();\n v8::Local value = SafeAllocation::NewInstance(func);\n \n \/\/ If we were unable to allocate the instance we avoid wrapping \n \/\/ and registering the NP object. \n if (value.IsEmpty()) \n return value;\n\n WrapNPObject(value, object);\n\n \/\/ KJS retains the object as part of its wrapper (see Bindings::CInstance)\n NPN_RetainObject(object);\n\n _NPN_RegisterObject(object, root);\n\n \/\/ Maintain a weak pointer for v8 so we can cleanup the object.\n v8::Persistent weak_ref = v8::Persistent::New(value);\n static_npobject_map.set(object, weak_ref);\n\n return value;\n}\n\nvoid ForgetV8ObjectForNPObject(NPObject* object) {\n if (static_npobject_map.contains(object)) {\n v8::HandleScope scope;\n v8::Persistent handle(static_npobject_map.get(object));\n WebCore::V8Proxy::SetDOMWrapper(handle,\n WebCore::V8ClassIndex::NPOBJECT, NULL);\n static_npobject_map.forget(object);\n NPN_ReleaseObject(object);\n }\n}\nFix a renderer crashing bug with NPObject method references. http:\/\/www.corp.google.com\/~michaeln\/flash_crash\/crash.html\/\/ Copyright (c) 2008, Google Inc.\n\/\/ All rights reserved.\n\/\/ \n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are\n\/\/ met:\n\/\/ \n\/\/ * Redistributions of source code must retain the above copyright\n\/\/ notice, this list of conditions and the following disclaimer.\n\/\/ * Redistributions in binary form must reproduce the above\n\/\/ copyright notice, this list of conditions and the following disclaimer\n\/\/ in the documentation and\/or other materials provided with the\n\/\/ distribution.\n\/\/ * Neither the name of Google Inc. nor the names of its\n\/\/ contributors may be used to endorse or promote products derived from\n\/\/ this software without specific prior written permission.\n\/\/ \n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\/\/ \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n\/\/ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n\/\/ A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n\/\/ OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n\/\/ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n\/\/ LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n\/\/ DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n\/\/ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n\/\/ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n\/\/ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n#include \"config.h\"\n\n#include \"v8_helpers.h\"\n#include \"v8_npobject.h\"\n#include \"v8_np_utils.h\"\n#include \"np_v8object.h\"\n#include \"npruntime_priv.h\"\n#include \"v8_proxy.h\"\n#include \"dom_wrapper_map.h\"\n#include \"HTMLPlugInElement.h\"\n#include \"V8HTMLAppletElement.h\"\n#include \"V8HTMLEmbedElement.h\"\n#include \"V8HTMLObjectElement.h\"\n\nusing namespace WebCore;\n\nenum InvokeFunctionType {\n INVOKE_METHOD = 1,\n INVOKE_DEFAULT = 2\n};\n\n\/\/ TODO(mbelshe): need comments.\n\/\/ Params: holder could be HTMLEmbedElement or NPObject\nstatic v8::Handle NPObjectInvokeImpl(\n const v8::Arguments& args, InvokeFunctionType func_id) {\n NPObject* npobject;\n\n \/\/ These three types are subtypes of HTMLPlugInElement.\n if (V8HTMLAppletElement::HasInstance(args.Holder()) ||\n V8HTMLEmbedElement::HasInstance(args.Holder()) ||\n V8HTMLObjectElement::HasInstance(args.Holder())) {\n \/\/ The holder object is a subtype of HTMLPlugInElement.\n HTMLPlugInElement* imp =\n V8Proxy::DOMWrapperToNode(args.Holder());\n v8::Handle instance = imp->getInstance();\n npobject = V8Proxy::ToNativeObject(\n V8ClassIndex::NPOBJECT, instance);\n\n } else {\n \/\/ The holder object is not a subtype of HTMLPlugInElement, it\n \/\/ must be an NPObject which has three internal fields.\n if (args.Holder()->InternalFieldCount() != 3) {\n V8Proxy::ThrowError(V8Proxy::REFERENCE_ERROR,\n \"NPMethod called on non-NPObject\");\n return v8::Undefined();\n }\n npobject = V8Proxy::ToNativeObject(\n V8ClassIndex::NPOBJECT, args.Holder());\n }\n\n \/\/ Verify that our wrapper wasn't using a NPObject which\n \/\/ has already been deleted.\n if (!npobject || !_NPN_IsAlive(npobject)) {\n V8Proxy::ThrowError(V8Proxy::REFERENCE_ERROR, \"NPObject deleted\");\n return v8::Undefined();\n }\n\n \/\/ wrap up parameters\n int argc = args.Length();\n NPVariant* np_args = new NPVariant[argc];\n\n for (int i = 0; i < argc; i++) {\n ConvertV8ObjectToNPVariant(args[i], npobject, &np_args[i]);\n }\n\n NPVariant result;\n VOID_TO_NPVARIANT(result);\n\n switch (func_id) {\n case INVOKE_METHOD:\n if (npobject->_class->invoke) {\n v8::Handle function_name(v8::String::Cast(*args.Data()));\n NPIdentifier ident = GetStringIdentifier(function_name);\n npobject->_class->invoke(npobject, ident, np_args, argc, &result);\n }\n break;\n case INVOKE_DEFAULT:\n if (npobject->_class->invokeDefault) {\n npobject->_class->invokeDefault(npobject, np_args, argc, &result);\n }\n break;\n default:\n break;\n }\n\n for (int i=0; i < argc; i++) {\n NPN_ReleaseVariantValue(&np_args[i]);\n }\n delete[] np_args;\n\n \/\/ unwrap return values\n v8::Handle rv = ConvertNPVariantToV8Object(&result, npobject);\n NPN_ReleaseVariantValue(&result);\n\n return rv;\n}\n\n\nv8::Handle NPObjectMethodHandler(const v8::Arguments& args) {\n return NPObjectInvokeImpl(args, INVOKE_METHOD);\n}\n\n\nv8::Handle NPObjectInvokeDefaultHandler(const v8::Arguments& args) {\n return NPObjectInvokeImpl(args, INVOKE_DEFAULT);\n}\n\n\nstatic void WeakTemplateCallback(v8::Persistent obj, void* param);\n\n\/\/ NPIdentifier is PrivateIdentifier*.\nstatic WeakReferenceMap \\\n static_template_map(&WeakTemplateCallback);\n\nstatic void WeakTemplateCallback(v8::Persistent obj,\n void* param) {\n PrivateIdentifier* iden = static_cast(param);\n ASSERT(iden != NULL);\n ASSERT(static_template_map.contains(iden));\n\n static_template_map.forget(iden);\n}\n\n\nstatic v8::Handle NPObjectGetProperty(v8::Local self,\n NPIdentifier ident,\n v8::Local key) {\n NPObject* npobject = V8Proxy::ToNativeObject(V8ClassIndex::NPOBJECT,\n self);\n\n \/\/ Verify that our wrapper wasn't using a NPObject which\n \/\/ has already been deleted.\n if (!npobject || !_NPN_IsAlive(npobject)) {\n V8Proxy::ThrowError(V8Proxy::REFERENCE_ERROR, \"NPObject deleted\");\n return v8::Handle();\n }\n\n if (npobject->_class->hasProperty &&\n npobject->_class->hasProperty(npobject, ident) &&\n npobject->_class->getProperty) {\n NPVariant result;\n VOID_TO_NPVARIANT(result);\n if (!npobject->_class->getProperty(npobject, ident, &result)) {\n return v8::Handle();\n }\n\n v8::Handle rv = ConvertNPVariantToV8Object(&result, npobject);\n NPN_ReleaseVariantValue(&result);\n return rv;\n\n } else if (key->IsString() &&\n npobject->_class->hasMethod &&\n npobject->_class->hasMethod(npobject, ident)) {\n PrivateIdentifier* id = static_cast(ident);\n v8::Persistent desc = static_template_map.get(id);\n \/\/ Cache templates using identifier as the key.\n if (desc.IsEmpty()) {\n \/\/ Create a new template\n v8::Local temp = v8::FunctionTemplate::New();\n temp->SetCallHandler(NPObjectMethodHandler, key);\n desc = v8::Persistent::New(temp);\n static_template_map.set(id, desc);\n }\n\n \/\/ FunctionTemplate caches function for each context.\n v8::Local func = desc->GetFunction();\n func->SetName(v8::Handle::Cast(key));\n return func;\n }\n\n return v8::Handle();\n}\n\nv8::Handle NPObjectNamedPropertyGetter(v8::Local name,\n const v8::AccessorInfo& info) {\n NPIdentifier ident = GetStringIdentifier(name);\n return NPObjectGetProperty(info.Holder(), ident, name);\n}\n\nv8::Handle NPObjectIndexedPropertyGetter(uint32_t index,\n const v8::AccessorInfo& info) {\n NPIdentifier ident = NPN_GetIntIdentifier(index);\n return NPObjectGetProperty(info.Holder(), ident, v8::Number::New(index));\n}\n\nv8::Handle NPObjectGetNamedProperty(v8::Local self,\n v8::Local name) {\n NPIdentifier ident = GetStringIdentifier(name);\n return NPObjectGetProperty(self, ident, name);\n}\n\nv8::Handle NPObjectGetIndexedProperty(v8::Local self,\n uint32_t index) {\n NPIdentifier ident = NPN_GetIntIdentifier(index);\n return NPObjectGetProperty(self, ident, v8::Number::New(index));\n}\n\nstatic v8::Handle NPObjectSetProperty(v8::Local self,\n NPIdentifier ident,\n v8::Local value) {\n NPObject* npobject =\n V8Proxy::ToNativeObject(V8ClassIndex::NPOBJECT, self);\n\n \/\/ Verify that our wrapper wasn't using a NPObject which\n \/\/ has already been deleted.\n if (!npobject || !_NPN_IsAlive(npobject)) {\n V8Proxy::ThrowError(V8Proxy::REFERENCE_ERROR, \"NPObject deleted\");\n return value; \/\/ intercepted, but an exception was thrown\n }\n\n if (npobject->_class->hasProperty &&\n npobject->_class->hasProperty(npobject, ident) &&\n npobject->_class->setProperty) {\n NPVariant npvalue;\n VOID_TO_NPVARIANT(npvalue);\n ConvertV8ObjectToNPVariant(value, npobject, &npvalue);\n bool succ = npobject->_class->setProperty(npobject, ident, &npvalue);\n NPN_ReleaseVariantValue(&npvalue);\n if (succ) return value; \/\/ intercept the call\n }\n return v8::Local(); \/\/ do not intercept the call\n}\n\n\nv8::Handle NPObjectNamedPropertySetter(v8::Local name,\n v8::Local value,\n const v8::AccessorInfo& info) {\n NPIdentifier ident = GetStringIdentifier(name);\n return NPObjectSetProperty(info.Holder(), ident, value);\n}\n\n\nv8::Handle NPObjectIndexedPropertySetter(uint32_t index,\n v8::Local value,\n const v8::AccessorInfo& info) {\n NPIdentifier ident = NPN_GetIntIdentifier(index);\n return NPObjectSetProperty(info.Holder(), ident, value);\n}\n\nv8::Handle NPObjectSetNamedProperty(v8::Local self,\n v8::Local name,\n v8::Local value) {\n NPIdentifier ident = GetStringIdentifier(name);\n return NPObjectSetProperty(self, ident, value);\n}\n\nv8::Handle NPObjectSetIndexedProperty(v8::Local self,\n uint32_t index,\n v8::Local value) {\n NPIdentifier ident = NPN_GetIntIdentifier(index);\n return NPObjectSetProperty(self, ident, value);\n}\n\n\nstatic void WeakNPObjectCallback(v8::Persistent obj, void* param);\n\nstatic DOMWrapperMap static_npobject_map(&WeakNPObjectCallback);\n\nstatic void WeakNPObjectCallback(v8::Persistent obj,\n void* param) {\n NPObject* npobject = static_cast(param);\n ASSERT(static_npobject_map.contains(npobject));\n ASSERT(npobject != NULL);\n\n \/\/ Must remove from our map before calling NPN_ReleaseObject().\n \/\/ NPN_ReleaseObject can call ForgetV8ObjectForNPObject, which\n \/\/ uses the table as well.\n static_npobject_map.forget(npobject);\n\n if (_NPN_IsAlive(npobject))\n NPN_ReleaseObject(npobject);\n}\n\n\nv8::Local CreateV8ObjectForNPObject(NPObject* object,\n NPObject* root) {\n static v8::Persistent np_object_desc;\n\n ASSERT(v8::Context::InContext());\n\n \/\/ If this is a v8 object, just return it.\n if (object->_class == NPScriptObjectClass) {\n V8NPObject* v8npobject = reinterpret_cast(object);\n return v8::Local::New(v8npobject->v8_object);\n }\n\n \/\/ If we've already wrapped this object, just return it.\n if (static_npobject_map.contains(object))\n return v8::Local::New(static_npobject_map.get(object));\n\n \/\/ TODO: we should create a Wrapper type as a subclass of JSObject.\n \/\/ It has two internal fields, field 0 is the wrapped pointer,\n \/\/ and field 1 is the type. There should be an api function that\n \/\/ returns unused type id.\n \/\/ The same Wrapper type can be used by DOM bindings.\n if (np_object_desc.IsEmpty()) {\n np_object_desc =\n v8::Persistent::New(v8::FunctionTemplate::New());\n np_object_desc->InstanceTemplate()->SetInternalFieldCount(3);\n np_object_desc->InstanceTemplate()->SetNamedPropertyHandler(\n NPObjectNamedPropertyGetter, NPObjectNamedPropertySetter);\n np_object_desc->InstanceTemplate()->SetIndexedPropertyHandler(\n NPObjectIndexedPropertyGetter, NPObjectIndexedPropertySetter);\n np_object_desc->InstanceTemplate()->SetCallAsFunctionHandler(\n NPObjectInvokeDefaultHandler); \n }\n\n v8::Handle func = np_object_desc->GetFunction();\n v8::Local value = SafeAllocation::NewInstance(func);\n \n \/\/ If we were unable to allocate the instance we avoid wrapping \n \/\/ and registering the NP object. \n if (value.IsEmpty()) \n return value;\n\n WrapNPObject(value, object);\n\n \/\/ KJS retains the object as part of its wrapper (see Bindings::CInstance)\n NPN_RetainObject(object);\n\n _NPN_RegisterObject(object, root);\n\n \/\/ Maintain a weak pointer for v8 so we can cleanup the object.\n v8::Persistent weak_ref = v8::Persistent::New(value);\n static_npobject_map.set(object, weak_ref);\n\n return value;\n}\n\nvoid ForgetV8ObjectForNPObject(NPObject* object) {\n if (static_npobject_map.contains(object)) {\n v8::HandleScope scope;\n v8::Persistent handle(static_npobject_map.get(object));\n WebCore::V8Proxy::SetDOMWrapper(handle,\n WebCore::V8ClassIndex::NPOBJECT, NULL);\n static_npobject_map.forget(object);\n NPN_ReleaseObject(object);\n }\n}\n<|endoftext|>"} {"text":"#include \"pch.h\"\r\n#include \"WASAPIEngine.h\"\r\n\r\nusing namespace concurrency;\r\n\r\nWASAPIEngine::WASAPIEngine()\r\n{\r\n\tm_deviceList = std::vector();\r\n\tm_collector = nullptr;\r\n\tm_consumer = nullptr;\r\n\tHRESULT hr = MFStartup(MF_VERSION, MFSTARTUP_LITE);\r\n}\r\n\r\nWASAPIEngine::~WASAPIEngine()\r\n{\r\n}\r\n\r\nIAsyncAction^ WASAPIEngine::InitializeCaptureAsync(UIDelegate1^ func, AudioDevices^ devParams, AudioParameters^ params)\r\n{\r\n\treturn InitializeCaptureAsync(func, nullptr, devParams, params);\r\n}\r\n\r\n[Windows::Foundation::Metadata::DefaultOverloadAttribute]\r\nIAsyncAction^ WASAPIEngine::InitializeCaptureAsync(UIDelegate2^ func, AudioDevices^ devParams, AudioParameters^ params)\r\n{\r\n\treturn InitializeCaptureAsync(nullptr, func, devParams, params);\r\n}\r\n\r\nIAsyncAction^ WASAPIEngine::InitializeCaptureAsync(UIDelegate1^ func1, UIDelegate2^ func2, AudioDevices^ devParams, AudioParameters^ params)\r\n{\r\n\treturn create_async([this ,func1, func2, devParams, params]\r\n\t{\r\n\t\t\/\/ Get the string identifier of the audio renderer\r\n\t\tauto AudioSelector = MediaDevice::GetAudioCaptureSelector();\r\n\r\n\t\t\/\/ Add custom properties to the query\r\n\t\tauto PropertyList = ref new Platform::Collections::Vector();\r\n\t\tPropertyList->Append(PKEY_AudioEndpoint_Supports_EventDriven_Mode);\r\n\r\n\t\t\/\/ Setup the asynchronous callback\r\n\t\tConcurrency::task enumOperation(DeviceInformation::FindAllAsync(AudioSelector, PropertyList));\r\n\t\tenumOperation.then([this](DeviceInformationCollection^ DeviceInfoCollection)\r\n\t\t{\r\n\t\t\tif ((DeviceInfoCollection == nullptr) || (DeviceInfoCollection->Size == 0))\r\n\t\t\t{\r\n\t\t\t\tOutputDebugString(L\"No Devices Found.\\n\");\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\ttry\r\n\t\t\t\t{\r\n\t\t\t\t\t\/\/ Enumerate through the devices and the custom properties\r\n\t\t\t\t\tfor (unsigned int i = 0; i < DeviceInfoCollection->Size; i++)\r\n\t\t\t\t\t{ \r\n\t\t\t\t\t\tauto deviceInfo = DeviceInfoCollection->GetAt(i);\r\n\t\t\t\t\t\tauto DeviceInfoString = deviceInfo->Name;\r\n\t\t\t\t\t\tauto DeviceIdString = deviceInfo->Id;\r\n\r\n\t\t\t\t\t\tif (deviceInfo->Properties->Size > 0)\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\tauto device = ref new WASAPIDevice();\r\n\t\t\t\t\t\t\tdevice->Name = DeviceInfoString;\r\n\t\t\t\t\t\t\tdevice->ID = DeviceIdString;\r\n\t\t\t\t\t\t\tm_deviceList.push_back(device);\r\n\t\t\t\t\t\t\tOutputDebugString(device->Name->Data());\r\n\t\t\t\t\t\t\tOutputDebugString(device->ID->Data());\r\n\t\t\t\t\t\t\tOutputDebugString(L\"\\n\");\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\tcatch (Platform::Exception^) {}\r\n\t\t\t}\r\n\t\t})\r\n\t\t.then([this, func1, func2, devParams, params]()\r\n\t\t{\r\n\t\t\tif (m_deviceList.size() >= devParams->Devices()) \r\n\t\t\t{\r\n\t\t\t\tm_collector = ref new DataCollector(devParams->Devices());\r\n\t\t\t\tfor (size_t i = 0; i < m_deviceList.size(); i++)\r\n\t\t\t\t{\r\n\t\t\t\t\tauto index = devParams->GetIndex(m_deviceList[i]->ID, i);\r\n\t\t\t\t\tif (index != -1)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tm_deviceList[i]->InitCaptureDevice(index, m_collector);\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\tm_consumer = ref new DataConsumer(devParams->Devices(), m_collector, func1, func2, devParams, params);\r\n\t\t\t\tm_consumer->Start();\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\tif (func1 == nullptr)\r\n\t\t\t\t{\r\n\t\t\t\t\tfunc2(LibAudio::HeartBeatType::NODEVICE, 0, 0, 0, 0, nullptr, nullptr, nullptr, nullptr);\r\n\t\t\t\t}\r\n\t\t\t\telse\r\n\t\t\t\t{\r\n\t\t\t\t\tfunc1(LibAudio::HeartBeatType::NODEVICE, nullptr, nullptr, nullptr);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t});\r\n\t});\r\n}\r\n\r\nIAsyncAction^ WASAPIEngine::InitializeRendererAsync(AudioDevices^ devParams, AudioParameters^ params)\r\n{\r\n\treturn create_async([this, devParams, params]\r\n\t{\r\n\t\t\/\/ Get the string identifier of the audio renderer\r\n\t\tauto AudioSelector = MediaDevice::GetAudioRenderSelector();\r\n\r\n\t\t\/\/ Add custom properties to the query\r\n\t\tauto PropertyList = ref new Platform::Collections::Vector();\r\n\t\tPropertyList->Append(PKEY_AudioEndpoint_Supports_EventDriven_Mode);\r\n\r\n\t\t\/\/ Setup the asynchronous callback\r\n\t\tConcurrency::task enumOperation(DeviceInformation::FindAllAsync(AudioSelector, PropertyList));\r\n\t\tenumOperation.then([this](DeviceInformationCollection^ DeviceInfoCollection)\r\n\t\t{\r\n\t\t\tif ((DeviceInfoCollection == nullptr) || (DeviceInfoCollection->Size == 0))\r\n\t\t\t{\r\n\t\t\t\tOutputDebugString(L\"No Devices Found.\\n\");\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\ttry\r\n\t\t\t\t{\r\n\t\t\t\t\t\/\/ Enumerate through the devices and the custom properties\r\n\t\t\t\t\tfor (unsigned int i = 0; i < DeviceInfoCollection->Size; i++)\r\n\t\t\t\t\t{ \r\n\t\t\t\t\t\tauto deviceInfo = DeviceInfoCollection->GetAt(i);\r\n\t\t\t\t\t\tauto DeviceInfoString = deviceInfo->Name;\r\n\t\t\t\t\t\tauto DeviceIdString = deviceInfo->Id;\r\n\r\n\t\t\t\t\t\tif (deviceInfo->Properties->Size > 0)\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\tauto device = ref new WASAPIDevice();\r\n\t\t\t\t\t\t\tdevice->Name = DeviceInfoString;\r\n\t\t\t\t\t\t\tdevice->ID = DeviceIdString;\r\n\t\t\t\t\t\t\tm_deviceList.push_back(device);\r\n\t\t\t\t\t\t\tOutputDebugString(device->Name->Data());\r\n\t\t\t\t\t\t\tOutputDebugString(device->ID->Data());\r\n\t\t\t\t\t\t\tOutputDebugString(L\"\\n\");\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\tcatch (Platform::Exception^) {}\r\n\t\t\t}\r\n\t\t})\r\n\t\t.then([this, devParams, params]()\r\n\t\t{\r\n\t\t\tif (m_deviceList.size() >= devParams->Devices()) \r\n\t\t\t{\r\n\t\t\t\tm_collector = ref new DataCollector(devParams->Devices());\r\n\t\t\t\tfor (size_t i = 0; i < m_deviceList.size(); i++)\r\n\t\t\t\t{\r\n\t\t\t\t\tauto index = devParams->GetIndex(m_deviceList[i]->ID, i);\r\n\t\t\t\t\tif (index != -1)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tm_deviceList[i]->InitRendererDevice(index, nullptr);\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t});\r\n\t});\r\n}\r\n\r\nIAsyncAction^ WASAPIEngine::GetCaptureDevicesAsync(UIDelegate3^ func)\r\n{\r\n\treturn create_async([this, func]\r\n\t{\r\n\t\t\/\/ Get the string identifier of the audio renderer\r\n\t\tauto AudioSelector = MediaDevice::GetAudioCaptureSelector();\r\n\r\n\t\t\/\/ Add custom properties to the query\r\n\t\tauto PropertyList = ref new Platform::Collections::Vector();\r\n\t\tPropertyList->Append(PKEY_AudioEndpoint_Supports_EventDriven_Mode);\r\n\r\n\t\t\/\/ Setup the asynchronous callback\r\n\t\tConcurrency::task enumOperation(DeviceInformation::FindAllAsync(AudioSelector, PropertyList));\r\n\t\tenumOperation.then([this, func](DeviceInformationCollection^ DeviceInfoCollection)\r\n\t\t{\r\n\t\t\tif ((DeviceInfoCollection == nullptr) || (DeviceInfoCollection->Size == 0))\r\n\t\t\t{\r\n\t\t\t\tfunc(L\"No Devices Found.\\n\");\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\ttry\r\n\t\t\t\t{\r\n\t\t\t\t\t\/\/ Enumerate through the devices and the custom properties\r\n\t\t\t\t\tfor (unsigned int i = 0; i < DeviceInfoCollection->Size; i++)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tauto deviceInfo = DeviceInfoCollection->GetAt(i);\r\n\t\t\t\t\t\tfunc(deviceInfo->Id);\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\tcatch (Platform::Exception^) {}\r\n\t\t\t}\r\n\t\t});\r\n\t});\r\n}\r\n\r\nIAsyncAction^ WASAPIEngine::GetRendererDevicesAsync(UIDelegate3^ func)\r\n{\r\n\treturn create_async([this, func]\r\n\t{\r\n\t\t\/\/ Get the string identifier of the audio renderer\r\n\t\tauto AudioSelector = MediaDevice::GetAudioRenderSelector();\r\n\r\n\t\t\/\/ Add custom properties to the query\r\n\t\tauto PropertyList = ref new Platform::Collections::Vector();\r\n\t\tPropertyList->Append(PKEY_AudioEndpoint_Supports_EventDriven_Mode);\r\n\r\n\t\t\/\/ Setup the asynchronous callback\r\n\t\tConcurrency::task enumOperation(DeviceInformation::FindAllAsync(AudioSelector, PropertyList));\r\n\t\tenumOperation.then([this, func](DeviceInformationCollection^ DeviceInfoCollection)\r\n\t\t{\r\n\t\t\tif ((DeviceInfoCollection == nullptr) || (DeviceInfoCollection->Size == 0))\r\n\t\t\t{\r\n\t\t\t\tfunc(L\"No Devices Found.\\n\");\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\ttry\r\n\t\t\t\t{\r\n\t\t\t\t\t\/\/ Enumerate through the devices and the custom properties\r\n\t\t\t\t\tfor (unsigned int i = 0; i < DeviceInfoCollection->Size; i++)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tauto deviceInfo = DeviceInfoCollection->GetAt(i);\r\n\t\t\t\t\t\tfunc(deviceInfo->Id);\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\tcatch (Platform::Exception^) {}\r\n\t\t\t}\r\n\t\t});\r\n\t});\r\n}\r\n\r\nvoid WASAPIEngine::Finish()\r\n{\r\n\tif (m_consumer != nullptr)\r\n\t{\r\n\t\tm_consumer->Finish();\r\n\t\tm_consumer = nullptr;\r\n\t}\r\n\r\n\tfor (size_t i = 0; i < m_deviceList.size(); i++)\r\n\t{\r\n\t\tif (m_deviceList[i]->Initialized())\r\n\t\t{\r\n\t\t\tm_deviceList[i]->StopAsync();\r\n\t\t}\t\t\r\n\t\tm_deviceList[i] = nullptr;\r\n\t}\r\n\r\n\tif (m_collector != nullptr)\r\n\t{\r\n\t\tm_collector->Finish();\r\n\t\tm_collector = nullptr;\r\n\t}\t\t\r\n}\r\n\r\nvoid WASAPIEngine::Continue()\r\n{\r\n\tif (m_consumer != nullptr)\r\n\t{\r\n\t\tm_consumer->Continue();\r\n\t}\r\n}\r\n12052016 - 14:49#include \"pch.h\"\r\n#include \"WASAPIEngine.h\"\r\n\r\nusing namespace concurrency;\r\n\r\nWASAPIEngine::WASAPIEngine()\r\n{\r\n\tm_deviceList = std::vector();\r\n\tm_collector = nullptr;\r\n\tm_consumer = nullptr;\r\n\tHRESULT hr = MFStartup(MF_VERSION, MFSTARTUP_LITE);\r\n}\r\n\r\nWASAPIEngine::~WASAPIEngine()\r\n{\r\n}\r\n\r\nIAsyncAction^ WASAPIEngine::InitializeCaptureAsync(UIDelegate1^ func, AudioDevices^ devParams, AudioParameters^ params)\r\n{\r\n\treturn InitializeCaptureAsync(func, nullptr, devParams, params);\r\n}\r\n\r\n[Windows::Foundation::Metadata::DefaultOverloadAttribute]\r\nIAsyncAction^ WASAPIEngine::InitializeCaptureAsync(UIDelegate2^ func, AudioDevices^ devParams, AudioParameters^ params)\r\n{\r\n\treturn InitializeCaptureAsync(nullptr, func, devParams, params);\r\n}\r\n\r\nIAsyncAction^ WASAPIEngine::InitializeCaptureAsync(UIDelegate1^ func1, UIDelegate2^ func2, AudioDevices^ devParams, AudioParameters^ params)\r\n{\r\n\treturn create_async([this ,func1, func2, devParams, params]\r\n\t{\r\n\t\t\/\/ Get the string identifier of the audio renderer\r\n\t\tauto AudioSelector = MediaDevice::GetAudioCaptureSelector();\r\n\r\n\t\t\/\/ Add custom properties to the query\r\n\t\tauto PropertyList = ref new Platform::Collections::Vector();\r\n\t\tPropertyList->Append(PKEY_AudioEndpoint_Supports_EventDriven_Mode);\r\n\r\n\t\t\/\/ Setup the asynchronous callback\r\n\t\tConcurrency::task enumOperation(DeviceInformation::FindAllAsync(AudioSelector, PropertyList));\r\n\t\tenumOperation.then([this](DeviceInformationCollection^ DeviceInfoCollection)\r\n\t\t{\r\n\t\t\tif ((DeviceInfoCollection == nullptr) || (DeviceInfoCollection->Size == 0))\r\n\t\t\t{\r\n\t\t\t\tOutputDebugString(L\"No Devices Found.\\n\");\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\ttry\r\n\t\t\t\t{\r\n\t\t\t\t\t\/\/ Enumerate through the devices and the custom properties\r\n\t\t\t\t\tfor (unsigned int i = 0; i < DeviceInfoCollection->Size; i++)\r\n\t\t\t\t\t{ \r\n\t\t\t\t\t\tauto deviceInfo = DeviceInfoCollection->GetAt(i);\r\n\t\t\t\t\t\tauto DeviceInfoString = deviceInfo->Name;\r\n\t\t\t\t\t\tauto DeviceIdString = deviceInfo->Id;\r\n\r\n\t\t\t\t\t\tif (deviceInfo->Properties->Size > 0)\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\tauto device = ref new WASAPIDevice();\r\n\t\t\t\t\t\t\tdevice->Name = DeviceInfoString;\r\n\t\t\t\t\t\t\tdevice->ID = DeviceIdString;\r\n\t\t\t\t\t\t\tm_deviceList.push_back(device);\r\n\t\t\t\t\t\t\tOutputDebugString(device->Name->Data());\r\n\t\t\t\t\t\t\tOutputDebugString(device->ID->Data());\r\n\t\t\t\t\t\t\tOutputDebugString(L\"\\n\");\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\tcatch (Platform::Exception^) {}\r\n\t\t\t}\r\n\t\t})\r\n\t\t.then([this, func1, func2, devParams, params]()\r\n\t\t{\r\n\t\t\tif (m_deviceList.size() >= devParams->Devices()) \r\n\t\t\t{\r\n\t\t\t\tm_collector = ref new DataCollector(devParams->Devices());\r\n\t\t\t\tfor (size_t i = 0; i < m_deviceList.size(); i++)\r\n\t\t\t\t{\r\n\t\t\t\t\tauto index = devParams->GetIndex(m_deviceList[i]->ID, i);\r\n\t\t\t\t\tif (index != -1)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tm_deviceList[i]->InitCaptureDevice(index, m_collector);\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\tm_consumer = ref new DataConsumer(devParams->Devices(), m_collector, func1, func2, devParams, params);\r\n\t\t\t\tm_consumer->Start();\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\tif (func1 == nullptr)\r\n\t\t\t\t{\r\n\t\t\t\t\tfunc2(LibAudio::HeartBeatType::NODEVICE, 0, 0, 0, 0, nullptr, nullptr, nullptr, nullptr);\r\n\t\t\t\t}\r\n\t\t\t\telse\r\n\t\t\t\t{\r\n\t\t\t\t\tfunc1(LibAudio::HeartBeatType::NODEVICE, nullptr, nullptr, nullptr);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t});\r\n\t});\r\n}\r\n\r\nIAsyncAction^ WASAPIEngine::InitializeRendererAsync(AudioDevices^ devParams, AudioParameters^ params)\r\n{\r\n\treturn create_async([this, devParams, params]\r\n\t{\r\n\t\t\/\/ Get the string identifier of the audio renderer\r\n\t\tauto AudioSelector = MediaDevice::GetAudioRenderSelector();\r\n\r\n\t\t\/\/ Add custom properties to the query\r\n\t\tauto PropertyList = ref new Platform::Collections::Vector();\r\n\t\tPropertyList->Append(PKEY_AudioEndpoint_Supports_EventDriven_Mode);\r\n\r\n\t\t\/\/ Setup the asynchronous callback\r\n\t\tConcurrency::task enumOperation(DeviceInformation::FindAllAsync(AudioSelector, PropertyList));\r\n\t\tenumOperation.then([this](DeviceInformationCollection^ DeviceInfoCollection)\r\n\t\t{\r\n\t\t\tif ((DeviceInfoCollection == nullptr) || (DeviceInfoCollection->Size == 0))\r\n\t\t\t{\r\n\t\t\t\tOutputDebugString(L\"No Devices Found.\\n\");\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\ttry\r\n\t\t\t\t{\r\n\t\t\t\t\t\/\/ Enumerate through the devices and the custom properties\r\n\t\t\t\t\tfor (unsigned int i = 0; i < DeviceInfoCollection->Size; i++)\r\n\t\t\t\t\t{ \r\n\t\t\t\t\t\tauto deviceInfo = DeviceInfoCollection->GetAt(i);\r\n\t\t\t\t\t\tauto DeviceInfoString = deviceInfo->Name;\r\n\t\t\t\t\t\tauto DeviceIdString = deviceInfo->Id;\r\n\r\n\t\t\t\t\t\tif (deviceInfo->Properties->Size > 0)\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\tauto device = ref new WASAPIDevice();\r\n\t\t\t\t\t\t\tdevice->Name = DeviceInfoString;\r\n\t\t\t\t\t\t\tdevice->ID = DeviceIdString;\r\n\t\t\t\t\t\t\tm_deviceList.push_back(device);\r\n\t\t\t\t\t\t\tOutputDebugString(device->Name->Data());\r\n\t\t\t\t\t\t\tOutputDebugString(device->ID->Data());\r\n\t\t\t\t\t\t\tOutputDebugString(L\"\\n\");\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\tcatch (Platform::Exception^) {}\r\n\t\t\t}\r\n\t\t})\r\n\t\t.then([this, devParams, params]()\r\n\t\t{\r\n\t\t\tif (m_deviceList.size() >= devParams->Devices()) \r\n\t\t\t{\r\n\t\t\t\tm_collector = ref new DataCollector(devParams->Devices());\r\n\t\t\t\tfor (size_t i = 0; i < m_deviceList.size(); i++)\r\n\t\t\t\t{\r\n\t\t\t\t\tauto index = devParams->GetIndex(m_deviceList[i]->ID, i);\r\n\t\t\t\t\tif (index != -1)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tm_deviceList[i]->InitRendererDevice(index, nullptr);\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t});\r\n\t});\r\n}\r\n\r\nIAsyncAction^ WASAPIEngine::GetCaptureDevicesAsync(UIDelegate3^ func)\r\n{\r\n\treturn create_async([this, func]\r\n\t{\r\n\t\t\/\/ Get the string identifier of the audio renderer\r\n\t\tauto AudioSelector = MediaDevice::GetAudioCaptureSelector();\r\n\r\n\t\t\/\/ Add custom properties to the query\r\n\t\tauto PropertyList = ref new Platform::Collections::Vector();\r\n\t\tPropertyList->Append(PKEY_AudioEndpoint_Supports_EventDriven_Mode);\r\n\r\n\t\t\/\/ Setup the asynchronous callback\r\n\t\tConcurrency::task enumOperation(DeviceInformation::FindAllAsync(AudioSelector, PropertyList));\r\n\t\tenumOperation.then([this, func](DeviceInformationCollection^ DeviceInfoCollection)\r\n\t\t{\r\n\t\t\tif ((DeviceInfoCollection == nullptr) || (DeviceInfoCollection->Size == 0))\r\n\t\t\t{\r\n\t\t\t\tfunc(L\"No Devices Found.\\n\");\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\ttry\r\n\t\t\t\t{\r\n\t\t\t\t\t\/\/ Enumerate through the devices and the custom properties\r\n\t\t\t\t\tfor (unsigned int i = 0; i < DeviceInfoCollection->Size; i++)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tauto deviceInfo = DeviceInfoCollection->GetAt(i);\r\n\t\t\t\t\t\tfunc(\"C - \" + deviceInfo->Id + deviceInfo->IsDefault ? \"*\" : \"\");\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\tcatch (Platform::Exception^) {}\r\n\t\t\t}\r\n\t\t});\r\n\t});\r\n}\r\n\r\nIAsyncAction^ WASAPIEngine::GetRendererDevicesAsync(UIDelegate3^ func)\r\n{\r\n\treturn create_async([this, func]\r\n\t{\r\n\t\t\/\/ Get the string identifier of the audio renderer\r\n\t\tauto AudioSelector = MediaDevice::GetAudioRenderSelector();\r\n\r\n\t\t\/\/ Add custom properties to the query\r\n\t\tauto PropertyList = ref new Platform::Collections::Vector();\r\n\t\tPropertyList->Append(PKEY_AudioEndpoint_Supports_EventDriven_Mode);\r\n\r\n\t\t\/\/ Setup the asynchronous callback\r\n\t\tConcurrency::task enumOperation(DeviceInformation::FindAllAsync(AudioSelector, PropertyList));\r\n\t\tenumOperation.then([this, func](DeviceInformationCollection^ DeviceInfoCollection)\r\n\t\t{\r\n\t\t\tif ((DeviceInfoCollection == nullptr) || (DeviceInfoCollection->Size == 0))\r\n\t\t\t{\r\n\t\t\t\tfunc(L\"No Devices Found.\\n\");\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\ttry\r\n\t\t\t\t{\r\n\t\t\t\t\t\/\/ Enumerate through the devices and the custom properties\r\n\t\t\t\t\tfor (unsigned int i = 0; i < DeviceInfoCollection->Size; i++)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tauto deviceInfo = DeviceInfoCollection->GetAt(i);\r\n\t\t\t\t\t\tfunc(\"R - \" + deviceInfo->Id + deviceInfo->IsDefault ? \"*\" : \"\");\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\tcatch (Platform::Exception^) {}\r\n\t\t\t}\r\n\t\t});\r\n\t});\r\n}\r\n\r\nvoid WASAPIEngine::Finish()\r\n{\r\n\tif (m_consumer != nullptr)\r\n\t{\r\n\t\tm_consumer->Finish();\r\n\t\tm_consumer = nullptr;\r\n\t}\r\n\r\n\tfor (size_t i = 0; i < m_deviceList.size(); i++)\r\n\t{\r\n\t\tif (m_deviceList[i]->Initialized())\r\n\t\t{\r\n\t\t\tm_deviceList[i]->StopAsync();\r\n\t\t}\t\t\r\n\t\tm_deviceList[i] = nullptr;\r\n\t}\r\n\r\n\tif (m_collector != nullptr)\r\n\t{\r\n\t\tm_collector->Finish();\r\n\t\tm_collector = nullptr;\r\n\t}\t\t\r\n}\r\n\r\nvoid WASAPIEngine::Continue()\r\n{\r\n\tif (m_consumer != nullptr)\r\n\t{\r\n\t\tm_consumer->Continue();\r\n\t}\r\n}\r\n<|endoftext|>"} {"text":"#define DEBUG 1\n\/**\n * File : E2.cpp\n * Author : Kazune Takahashi\n * Created : 7\/6\/2020, 8:25:26 PM\n * Powered by Visual Studio Code\n *\/\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\/\/ ----- boost -----\n#include \n#include \n#include \n\/\/ ----- using directives and manipulations -----\nusing namespace std;\nusing boost::rational;\nusing boost::integer::gcd; \/\/ for C++14 or for cpp_int\nusing boost::integer::lcm; \/\/ for C++14 or for cpp_int\nusing boost::multiprecision::cpp_int;\nusing ll = long long;\nusing ld = long double;\ntemplate \nusing max_heap = priority_queue;\ntemplate \nusing min_heap = priority_queue, greater>;\n\/\/ ----- constexpr for Mint and Combination -----\nconstexpr ll MOD{1'000'000'007LL};\n\/\/ constexpr ll MOD{998'244'353LL}; \/\/ be careful\nconstexpr ll MAX_SIZE{3'000'010LL};\n\/\/ constexpr ll MAX_SIZE{30'000'010LL}; \/\/ if 10^7 is needed\n\/\/ ----- ch_max and ch_min -----\ntemplate \nbool ch_max(T &left, T right)\n{\n if (left < right)\n {\n left = right;\n return true;\n }\n return false;\n}\ntemplate \nbool ch_min(T &left, T right)\n{\n if (left > right)\n {\n left = right;\n return true;\n }\n return false;\n}\n\/\/ ----- Mint -----\ntemplate \nclass Mint\n{\npublic:\n ll x;\n Mint() : x{0LL} {}\n Mint(ll x) : x{(x % MOD + MOD) % MOD} {}\n Mint operator-() const { return x ? MOD - x : 0; }\n Mint &operator+=(Mint const &a)\n {\n if ((x += a.x) >= MOD)\n {\n x -= MOD;\n }\n return *this;\n }\n Mint &operator-=(Mint const &a) { return *this += -a; }\n Mint &operator++() { return *this += 1; }\n Mint operator++(int)\n {\n Mint tmp{*this};\n ++*this;\n return tmp;\n }\n Mint &operator--() { return *this -= 1; }\n Mint operator--(int)\n {\n Mint tmp{*this};\n --*this;\n return tmp;\n }\n Mint &operator*=(Mint const &a)\n {\n (x *= a.x) %= MOD;\n return *this;\n }\n Mint &operator\/=(Mint const &a)\n {\n Mint b{a};\n return *this *= b.power(MOD - 2);\n }\n Mint operator+(Mint const &a) const { return Mint(*this) += a; }\n Mint operator-(Mint const &a) const { return Mint(*this) -= a; }\n Mint operator*(Mint const &a) const { return Mint(*this) *= a; }\n Mint operator\/(Mint const &a) const { return Mint(*this) \/= a; }\n bool operator<(Mint const &a) const { return x < a.x; }\n bool operator<=(Mint const &a) const { return x <= a.x; }\n bool operator>(Mint const &a) const { return x > a.x; }\n bool operator>=(Mint const &a) const { return x >= a.x; }\n bool operator==(Mint const &a) const { return x == a.x; }\n bool operator!=(Mint const &a) const { return !(*this == a); }\n Mint power(ll N) const\n {\n if (N == 0)\n {\n return 1;\n }\n else if (N % 2 == 1)\n {\n return *this * power(N - 1);\n }\n else\n {\n Mint half = power(N \/ 2);\n return half * half;\n }\n }\n};\ntemplate \nMint operator+(ll lhs, Mint const &rhs) { return rhs + lhs; }\ntemplate \nMint operator-(ll lhs, Mint const &rhs) { return -rhs + lhs; }\ntemplate \nMint operator*(ll lhs, Mint const &rhs) { return rhs * lhs; }\ntemplate \nMint operator\/(ll lhs, Mint const &rhs) { return Mint{lhs} \/ rhs; }\ntemplate \nistream &operator>>(istream &stream, Mint &a) { return stream >> a.x; }\ntemplate \nostream &operator<<(ostream &stream, Mint const &a) { return stream << a.x; }\n\/\/ ----- Combination -----\ntemplate \nclass Combination\n{\npublic:\n vector> inv, fact, factinv;\n Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE)\n {\n inv[1] = 1;\n for (auto i{2LL}; i < MAX_SIZE; i++)\n {\n inv[i] = (-inv[MOD % i]) * (MOD \/ i);\n }\n fact[0] = factinv[0] = 1;\n for (auto i{1LL}; i < MAX_SIZE; i++)\n {\n fact[i] = Mint(i) * fact[i - 1];\n factinv[i] = inv[i] * factinv[i - 1];\n }\n }\n Mint operator()(int n, int k)\n {\n if (n >= 0 && k >= 0 && n - k >= 0)\n {\n return fact[n] * factinv[k] * factinv[n - k];\n }\n return 0;\n }\n Mint catalan(int x, int y)\n {\n return (*this)(x + y, y) - (*this)(x + y, y - 1);\n }\n};\n\/\/ ----- for C++14 -----\nusing mint = Mint;\nusing combination = Combination;\n\/\/ ----- for C++17 -----\ntemplate ::value>::type * = nullptr>\nsize_t popcount(T x) { return bitset<64>(x).count(); }\nsize_t popcount(string const &S) { return bitset<200010>{S}.count(); }\n\/\/ ----- Infty -----\ntemplate \nconstexpr T Infty() { return numeric_limits::max(); }\ntemplate \nconstexpr T mInfty() { return numeric_limits::min(); }\n\/\/ ----- frequently used constexpr -----\n\/\/ constexpr double epsilon{1e-10};\n\/\/ constexpr ll infty{1'000'000'000'000'010LL}; \/\/ or\n\/\/ constexpr int infty{1'000'000'010};\n\/\/ constexpr int dx[4] = {1, 0, -1, 0};\n\/\/ constexpr int dy[4] = {0, 1, 0, -1};\n\/\/ ----- Yes() and No() -----\nvoid Yes()\n{\n cout << \"Yes\" << endl;\n exit(0);\n}\nvoid No()\n{\n cout << \"No\" << endl;\n exit(0);\n}\n\n\/\/ ----- Solve -----\n\nclass Solve\n{\n\npublic:\n Solve()\n {\n }\n\n void flush()\n {\n }\n\nprivate:\n};\n\n\/\/ ----- main() -----\n\n\/*\nint main()\n{\n Solve solve;\n solve.flush();\n}\n*\/\n\nint main()\n{\n int n, k;\n cin >> n >> k;\n vector a(n);\n for (auto i{0}; i < n; ++i)\n {\n cin >> a[i];\n }\n sort(a.rbegin(), a.rend());\n if (a[0] < 0)\n {\n cout << accumulate(a.begin(), a.begin() + k, mint{1}, multiplies()) << endl;\n return 0;\n }\n auto l{0}, r{n - 1};\n mint ans{1};\n if (k & 1)\n {\n ans *= a[l++];\n }\n for (auto t{0}; t < k \/ 2; ++t)\n {\n if (auto left{a[l] * a[l + 1]}, right{a[r] * a[r - 1]}; left >= right)\n {\n ans *= left;\n l += 2;\n }\n else\n {\n ans *= right;\n r -= 2;\n }\n }\n if (ans == 0)\n {\n sleep(1000);\n }\n cout << ans << endl;\n}\nsubmit E2.cpp to 'E - Multiplication 4' (abc173) [C++ (GCC 9.2.1)]#define DEBUG 1\n\/**\n * File : E2.cpp\n * Author : Kazune Takahashi\n * Created : 7\/6\/2020, 8:25:26 PM\n * Powered by Visual Studio Code\n *\/\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\/\/ ----- boost -----\n#include \n#include \n#include \n\/\/ ----- using directives and manipulations -----\nusing namespace std;\nusing boost::rational;\nusing boost::integer::gcd; \/\/ for C++14 or for cpp_int\nusing boost::integer::lcm; \/\/ for C++14 or for cpp_int\nusing boost::multiprecision::cpp_int;\nusing ll = long long;\nusing ld = long double;\ntemplate \nusing max_heap = priority_queue;\ntemplate \nusing min_heap = priority_queue, greater>;\n\/\/ ----- constexpr for Mint and Combination -----\nconstexpr ll MOD{1'000'000'007LL};\n\/\/ constexpr ll MOD{998'244'353LL}; \/\/ be careful\nconstexpr ll MAX_SIZE{3'000'010LL};\n\/\/ constexpr ll MAX_SIZE{30'000'010LL}; \/\/ if 10^7 is needed\n\/\/ ----- ch_max and ch_min -----\ntemplate \nbool ch_max(T &left, T right)\n{\n if (left < right)\n {\n left = right;\n return true;\n }\n return false;\n}\ntemplate \nbool ch_min(T &left, T right)\n{\n if (left > right)\n {\n left = right;\n return true;\n }\n return false;\n}\n\/\/ ----- Mint -----\ntemplate \nclass Mint\n{\npublic:\n ll x;\n Mint() : x{0LL} {}\n Mint(ll x) : x{(x % MOD + MOD) % MOD} {}\n Mint operator-() const { return x ? MOD - x : 0; }\n Mint &operator+=(Mint const &a)\n {\n if ((x += a.x) >= MOD)\n {\n x -= MOD;\n }\n return *this;\n }\n Mint &operator-=(Mint const &a) { return *this += -a; }\n Mint &operator++() { return *this += 1; }\n Mint operator++(int)\n {\n Mint tmp{*this};\n ++*this;\n return tmp;\n }\n Mint &operator--() { return *this -= 1; }\n Mint operator--(int)\n {\n Mint tmp{*this};\n --*this;\n return tmp;\n }\n Mint &operator*=(Mint const &a)\n {\n (x *= a.x) %= MOD;\n return *this;\n }\n Mint &operator\/=(Mint const &a)\n {\n Mint b{a};\n return *this *= b.power(MOD - 2);\n }\n Mint operator+(Mint const &a) const { return Mint(*this) += a; }\n Mint operator-(Mint const &a) const { return Mint(*this) -= a; }\n Mint operator*(Mint const &a) const { return Mint(*this) *= a; }\n Mint operator\/(Mint const &a) const { return Mint(*this) \/= a; }\n bool operator<(Mint const &a) const { return x < a.x; }\n bool operator<=(Mint const &a) const { return x <= a.x; }\n bool operator>(Mint const &a) const { return x > a.x; }\n bool operator>=(Mint const &a) const { return x >= a.x; }\n bool operator==(Mint const &a) const { return x == a.x; }\n bool operator!=(Mint const &a) const { return !(*this == a); }\n Mint power(ll N) const\n {\n if (N == 0)\n {\n return 1;\n }\n else if (N % 2 == 1)\n {\n return *this * power(N - 1);\n }\n else\n {\n Mint half = power(N \/ 2);\n return half * half;\n }\n }\n};\ntemplate \nMint operator+(ll lhs, Mint const &rhs) { return rhs + lhs; }\ntemplate \nMint operator-(ll lhs, Mint const &rhs) { return -rhs + lhs; }\ntemplate \nMint operator*(ll lhs, Mint const &rhs) { return rhs * lhs; }\ntemplate \nMint operator\/(ll lhs, Mint const &rhs) { return Mint{lhs} \/ rhs; }\ntemplate \nistream &operator>>(istream &stream, Mint &a) { return stream >> a.x; }\ntemplate \nostream &operator<<(ostream &stream, Mint const &a) { return stream << a.x; }\n\/\/ ----- Combination -----\ntemplate \nclass Combination\n{\npublic:\n vector> inv, fact, factinv;\n Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE)\n {\n inv[1] = 1;\n for (auto i{2LL}; i < MAX_SIZE; i++)\n {\n inv[i] = (-inv[MOD % i]) * (MOD \/ i);\n }\n fact[0] = factinv[0] = 1;\n for (auto i{1LL}; i < MAX_SIZE; i++)\n {\n fact[i] = Mint(i) * fact[i - 1];\n factinv[i] = inv[i] * factinv[i - 1];\n }\n }\n Mint operator()(int n, int k)\n {\n if (n >= 0 && k >= 0 && n - k >= 0)\n {\n return fact[n] * factinv[k] * factinv[n - k];\n }\n return 0;\n }\n Mint catalan(int x, int y)\n {\n return (*this)(x + y, y) - (*this)(x + y, y - 1);\n }\n};\n\/\/ ----- for C++14 -----\nusing mint = Mint;\nusing combination = Combination;\n\/\/ ----- for C++17 -----\ntemplate ::value>::type * = nullptr>\nsize_t popcount(T x) { return bitset<64>(x).count(); }\nsize_t popcount(string const &S) { return bitset<200010>{S}.count(); }\n\/\/ ----- Infty -----\ntemplate \nconstexpr T Infty() { return numeric_limits::max(); }\ntemplate \nconstexpr T mInfty() { return numeric_limits::min(); }\n\/\/ ----- frequently used constexpr -----\n\/\/ constexpr double epsilon{1e-10};\n\/\/ constexpr ll infty{1'000'000'000'000'010LL}; \/\/ or\n\/\/ constexpr int infty{1'000'000'010};\n\/\/ constexpr int dx[4] = {1, 0, -1, 0};\n\/\/ constexpr int dy[4] = {0, 1, 0, -1};\n\/\/ ----- Yes() and No() -----\nvoid Yes()\n{\n cout << \"Yes\" << endl;\n exit(0);\n}\nvoid No()\n{\n cout << \"No\" << endl;\n exit(0);\n}\n\n\/\/ ----- Solve -----\n\nclass Solve\n{\n\npublic:\n Solve()\n {\n }\n\n void flush()\n {\n }\n\nprivate:\n};\n\n\/\/ ----- main() -----\n\n\/*\nint main()\n{\n Solve solve;\n solve.flush();\n}\n*\/\n\nint main()\n{\n int n, k;\n cin >> n >> k;\n vector a(n);\n for (auto i{0}; i < n; ++i)\n {\n cin >> a[i];\n }\n sort(a.rbegin(), a.rend());\n if (a[0] < 0)\n {\n cout << accumulate(a.begin(), a.begin() + k, mint{1}, multiplies()) << endl;\n return 0;\n }\n auto l{0}, r{n - 1};\n mint ans{1};\n if (k & 1)\n {\n ans *= a[l++];\n }\n for (auto t{0}; t < k \/ 2; ++t)\n {\n if (auto left{a[l] * a[l + 1]}, right{a[r] * a[r - 1]}; left >= right)\n {\n ans *= left;\n l += 2;\n }\n else\n {\n ans *= right;\n r -= 2;\n }\n }\n if (ans == 0)\n {\n assert(false);\n }\n cout << ans << endl;\n}\n<|endoftext|>"} {"text":"#include \"catch.hpp\"\n\n#include \n#include \n\n\n#include \n#include \n#include \n#include \n\ntemplate \nstruct NumericTest {\n\tstatic\n\tvoid test(lua_State* state) {\n\t\tconst I max_value = std::numeric_limits::max();\n\t\tconst I min_value = std::numeric_limits::lowest();\n\t\tconst I avg_value = (max_value + min_value) \/ 2;\n\n\t\t\/\/ Largest value\n\t\tREQUIRE(luwra::Value::push(state, max_value) == 1);\n\t\tREQUIRE(luwra::Value::read(state, -1) == max_value);\n\n\t\t\/\/ Lowest value\n\t\tREQUIRE(luwra::Value::push(state, min_value) == 1);\n\t\tREQUIRE(luwra::Value::read(state, -1) == min_value);\n\n\t\t\/\/ Average value\n\t\tREQUIRE(luwra::Value::push(state, avg_value) == 1);\n\t\tREQUIRE(luwra::Value::read(state, -1) == avg_value);\n\t}\n};\n\nstruct TautologyTest {\n\tstatic\n\tvoid test(lua_State*) {}\n};\n\ntemplate \nusing SelectNumericTest =\n\ttypename std::conditional<\n\t\tluwra::internal::NumericContainedValueBase::qualifies,\n\t\tNumericTest,\n\t\tTautologyTest\n\t>::type;\n\nTEST_CASE(\"Test Value specialization for numeric C types\", \"types_numeric\") {\n\tlua_State* state = luaL_newstate();\n\n\t\/\/ Integer-based types\n\tSelectNumericTest::test(state);\n\tSelectNumericTest::test(state);\n\tSelectNumericTest::test(state);\n\tSelectNumericTest::test(state);\n\tSelectNumericTest::test(state);\n\tSelectNumericTest::test(state);\n\tSelectNumericTest::test(state);\n\tSelectNumericTest::test(state);\n\n\t\/\/ Number-based types\n\tSelectNumericTest::test(state);\n\tSelectNumericTest::test(state);\n\tSelectNumericTest::test(state);\n\n\tlua_close(state);\n}\n\nTEST_CASE(\"Test Value specialization for string types\", \"types_string\") {\n\tlua_State* state = luaL_newstate();\n\n\tconst char* test_cstr = \"Luwra Test String\";\n\tstd::string test_str(test_cstr);\n\n\t\/\/ Safety first\n\tREQUIRE(test_str == test_cstr);\n\n\t\/\/ Push both strings\n\tREQUIRE(luwra::Value::push(state, test_cstr) == 1);\n\tREQUIRE(luwra::Value::push(state, test_str) == 1);\n\n\t\/\/ They must be equal to Lua\n\tREQUIRE(lua_compare(state, -1, -2, LUA_OPEQ));\n\n\t\/\/ Extraction as C string must not change the string's value\n\tconst char* l_cstr1 = luwra::Value::read(state, -1);\n\tconst char* l_cstr2 = luwra::Value::read(state, -2);\n\n\tREQUIRE(std::strcmp(test_cstr, l_cstr1) == 0);\n\tREQUIRE(std::strcmp(test_cstr, l_cstr2) == 0);\n\tREQUIRE(std::strcmp(test_str.c_str(), l_cstr1) == 0);\n\tREQUIRE(std::strcmp(test_str.c_str(), l_cstr2) == 0);\n\tREQUIRE(std::strcmp(l_cstr1, l_cstr2) == 0);\n\n\t\/\/ Extraction as C++ string must not change the string's value\n\tstd::string l_str1 = luwra::Value::read(state, -1);\n\tstd::string l_str2 = luwra::Value::read(state, -2);\n\n\tREQUIRE(l_str1 == test_cstr);\n\tREQUIRE(l_str2 == test_cstr);\n\tREQUIRE(test_str == l_str1);\n\tREQUIRE(test_str == l_str2);\n\tREQUIRE(l_str1 == l_str2);\n\n\tlua_close(state);\n}\n\nTEST_CASE(\"Test Value specialization for tuples\", \"types_tuple\") {\n\tlua_State* state = luaL_newstate();\n\n\tint a = 13;\n\tstd::string b(\"Hello\");\n\tfloat c = 0.37;\n\n\t\/\/ Push normal tuple\n\tauto tuple = std::make_tuple(a, b, c);\n\tREQUIRE(luwra::Value::push(state, tuple) == 3);\n\n\t\/\/ Push nested tuple\n\tauto tuple_nested = std::make_tuple(a, b, c, tuple);\n\tREQUIRE(luwra::Value::push(state, tuple_nested) == 6);\n\n\tlua_close(state);\n}\nAdd test case for booleans#include \"catch.hpp\"\n\n#include \n#include \n\n\n#include \n#include \n#include \n#include \n\ntemplate \nstruct NumericTest {\n\tstatic\n\tvoid test(lua_State* state) {\n\t\tconst I max_value = std::numeric_limits::max();\n\t\tconst I min_value = std::numeric_limits::lowest();\n\t\tconst I avg_value = (max_value + min_value) \/ 2;\n\n\t\t\/\/ Largest value\n\t\tREQUIRE(luwra::Value::push(state, max_value) == 1);\n\t\tREQUIRE(luwra::Value::read(state, -1) == max_value);\n\n\t\t\/\/ Lowest value\n\t\tREQUIRE(luwra::Value::push(state, min_value) == 1);\n\t\tREQUIRE(luwra::Value::read(state, -1) == min_value);\n\n\t\t\/\/ Average value\n\t\tREQUIRE(luwra::Value::push(state, avg_value) == 1);\n\t\tREQUIRE(luwra::Value::read(state, -1) == avg_value);\n\t}\n};\n\nstruct TautologyTest {\n\tstatic\n\tvoid test(lua_State*) {}\n};\n\ntemplate \nusing SelectNumericTest =\n\ttypename std::conditional<\n\t\tluwra::internal::NumericContainedValueBase::qualifies,\n\t\tNumericTest,\n\t\tTautologyTest\n\t>::type;\n\nTEST_CASE(\"Test Value specialization for numeric C types\", \"types_numeric\") {\n\tlua_State* state = luaL_newstate();\n\n\t\/\/ Integer-based types\n\tSelectNumericTest::test(state);\n\tSelectNumericTest::test(state);\n\tSelectNumericTest::test(state);\n\tSelectNumericTest::test(state);\n\tSelectNumericTest::test(state);\n\tSelectNumericTest::test(state);\n\tSelectNumericTest::test(state);\n\tSelectNumericTest::test(state);\n\n\t\/\/ Number-based types\n\tSelectNumericTest::test(state);\n\tSelectNumericTest::test(state);\n\tSelectNumericTest::test(state);\n\n\tlua_close(state);\n}\n\nTEST_CASE(\"Test Value specialization for string types\", \"types_string\") {\n\tlua_State* state = luaL_newstate();\n\n\tconst char* test_cstr = \"Luwra Test String\";\n\tstd::string test_str(test_cstr);\n\n\t\/\/ Safety first\n\tREQUIRE(test_str == test_cstr);\n\n\t\/\/ Push both strings\n\tREQUIRE(luwra::Value::push(state, test_cstr) == 1);\n\tREQUIRE(luwra::Value::push(state, test_str) == 1);\n\n\t\/\/ They must be equal to Lua\n\tREQUIRE(lua_compare(state, -1, -2, LUA_OPEQ));\n\n\t\/\/ Extraction as C string must not change the string's value\n\tconst char* l_cstr1 = luwra::Value::read(state, -1);\n\tconst char* l_cstr2 = luwra::Value::read(state, -2);\n\n\tREQUIRE(std::strcmp(test_cstr, l_cstr1) == 0);\n\tREQUIRE(std::strcmp(test_cstr, l_cstr2) == 0);\n\tREQUIRE(std::strcmp(test_str.c_str(), l_cstr1) == 0);\n\tREQUIRE(std::strcmp(test_str.c_str(), l_cstr2) == 0);\n\tREQUIRE(std::strcmp(l_cstr1, l_cstr2) == 0);\n\n\t\/\/ Extraction as C++ string must not change the string's value\n\tstd::string l_str1 = luwra::Value::read(state, -1);\n\tstd::string l_str2 = luwra::Value::read(state, -2);\n\n\tREQUIRE(l_str1 == test_cstr);\n\tREQUIRE(l_str2 == test_cstr);\n\tREQUIRE(test_str == l_str1);\n\tREQUIRE(test_str == l_str2);\n\tREQUIRE(l_str1 == l_str2);\n\n\tlua_close(state);\n}\n\nTEST_CASE(\"Test Value specialization for tuples\", \"types_tuple\") {\n\tlua_State* state = luaL_newstate();\n\n\tint a = 13;\n\tstd::string b(\"Hello\");\n\tfloat c = 0.37;\n\n\t\/\/ Push normal tuple\n\tauto tuple = std::make_tuple(a, b, c);\n\tREQUIRE(luwra::Value::push(state, tuple) == 3);\n\n\t\/\/ Push nested tuple\n\tauto tuple_nested = std::make_tuple(a, b, c, tuple);\n\tREQUIRE(luwra::Value::push(state, tuple_nested) == 6);\n\n\tlua_close(state);\n}\n\nTEST_CASE(\"Test Value specialization for bool\") {\n\tlua_State* state = luaL_newstate();\n\n\tbool value = true;\n\n\tREQUIRE(luwra::Value::push(state, value) == 1);\n\tREQUIRE(luwra::Value::read(state, -1) == value);\n\n\tlua_close(state);\n}\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n\n#include \n\n#include \n#include \n\n#ifndef SEARCH_GRID_6D_H_\n#define SEARCH_GRID_6D_H_\n\nnamespace search\n{\n\tvoid grid_setup(Search_setup setup, std::vector& results){\n\t\tfor(int x=0; x < setup.x.steps_max; ++x)\n\t\t{\n\t\t\tfor(int y=0; y < setup.y.steps_max; ++y)\n\t\t\t{\n\t\t\t\tfor(int z=0; z < setup.z.steps_max; ++z)\n\t\t\t\t{\n\t\t\t\t\tfor(int roll=0; roll < setup.roll.steps_max; ++roll)\n\t\t\t\t\t{\n\t\t\t\t\t\tfor(int pitch=0; pitch < setup.pitch.steps_max; ++pitch)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tfor(int yaw=0; yaw < setup.yaw.steps_max; ++yaw)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tresults.push_back(Search_value(setup.x.at(x), setup.y.at(y), setup.z.at(z), setup.roll.at(roll), setup.pitch.at(pitch), setup.yaw.at(yaw)));\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\ttemplate \n\tvoid get_best_tf(\ttf::Transform in,\n\t\t\t\t\t\ttf::Transform &out,\n\t\t\t\t\t\tconst image_geometry::PinholeCameraModel &camera_model,\n\t\t\t\t\t\tconst std::deque > &pointclouds,\n\t\t\t\t\t\tconst std::deque &images,\n\t\t\t\t\t\tfloat range = 0.5,\n\t\t\t\t\t\tint steps = 3)\n\t{\n\t\tSearch_setup search_range;\n\t\tstd::vector results;\n\n\t\tdouble r,p,y;\n\t\tin.getBasis().getRPY(r, p, y, 1);\n\t\tsearch_range.x.init_range(in.getOrigin()[0], range, steps);\n\t\tsearch_range.y.init_range(in.getOrigin()[1], range, steps);\n\t\tsearch_range.z.init_range(in.getOrigin()[2], range, steps);\n\t\tsearch_range.roll.init_range(r, range, steps);\n\t\tsearch_range.pitch.init_range(p, range, steps);\n\t\tsearch_range.yaw.init_range(y, range, steps);\n\n\t\tgrid_setup(search_range, results);\n\n\t\tcalculate( camera_model, pointclouds, images, results );\n\n\t\tint best_result_idx = 0;\n\t\tlong unsigned int best_result = 0;\n\t\tfor(int i=0; i< results.size(); ++i){\n\t\t\tif(results.at(i).result > best_result){\n\t\t\t\tbest_result_idx = i;\n\t\t\t\tbest_result = results.at(i).result;\n\t\t\t}\n\t\t}\n\t\t\/\/printf(\"%d: \\t%s\\n\", best_result_idx, results.at(best_result_idx).to_string().c_str());\n\n\t\tout.setOrigin( tf::Vector3(results.at(best_result_idx).x, results.at(best_result_idx).y, results.at(best_result_idx).z ) );\n\n\t\ttf::Quaternion q;\n\t\tq.setRPY(results.at(best_result_idx).roll, results.at(best_result_idx).pitch, results.at(best_result_idx).yaw );\n\t\tout.setRotation( q);\n\t}\n\n\n\ttemplate \n\tinline void calculate(const image_geometry::PinholeCameraModel &camera_model, const std::vector > &pointclouds, const std::vector &edge_images, std::vector& results){\n\t\tfor(int i=0; i < results.size(); ++i){\n\t\t\tscore::multi_score(camera_model, pointclouds, edge_images, results.at(i));\n\t\t}\n\t}\n}\n\n#endif\ninlined functions, use new tf helper function#include \n#include \n#include \n#include \n\n#include \n\n#include \n#include \n\n#ifndef SEARCH_GRID_6D_H_\n#define SEARCH_GRID_6D_H_\n\nnamespace search\n{\n\tinline void grid_setup(Search_setup setup, std::vector& results){\n\t\tfor(int x=0; x < setup.x.steps_max; ++x)\n\t\t{\n\t\t\tfor(int y=0; y < setup.y.steps_max; ++y)\n\t\t\t{\n\t\t\t\tfor(int z=0; z < setup.z.steps_max; ++z)\n\t\t\t\t{\n\t\t\t\t\tfor(int roll=0; roll < setup.roll.steps_max; ++roll)\n\t\t\t\t\t{\n\t\t\t\t\t\tfor(int pitch=0; pitch < setup.pitch.steps_max; ++pitch)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tfor(int yaw=0; yaw < setup.yaw.steps_max; ++yaw)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tresults.push_back(Search_value(setup.x.at(x), setup.y.at(y), setup.z.at(z), setup.roll.at(roll), setup.pitch.at(pitch), setup.yaw.at(yaw)));\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\ttemplate \n\tinline void get_best_tf(\ttf::Transform in,\n\t\t\t\t\t\ttf::Transform &out,\n\t\t\t\t\t\tconst image_geometry::PinholeCameraModel &camera_model,\n\t\t\t\t\t\tconst std::deque > &pointclouds,\n\t\t\t\t\t\tconst std::deque &images,\n\t\t\t\t\t\tfloat range = 0.5,\n\t\t\t\t\t\tint steps = 3)\n\t{\n\t\tSearch_setup search_range;\n\t\tstd::vector results;\n\n\t\tdouble r,p,y;\n\t\tin.getBasis().getRPY(r, p, y, 1);\n\t\tsearch_range.x.init_range(in.getOrigin()[0], range, steps);\n\t\tsearch_range.y.init_range(in.getOrigin()[1], range, steps);\n\t\tsearch_range.z.init_range(in.getOrigin()[2], range, steps);\n\t\tsearch_range.roll.init_range(r, range, steps);\n\t\tsearch_range.pitch.init_range(p, range, steps);\n\t\tsearch_range.yaw.init_range(y, range, steps);\n\n\t\tgrid_setup(search_range, results);\n\n\t\tcalculate( camera_model, pointclouds, images, results );\n\n\t\tint best_result_idx = 0;\n\t\tlong unsigned int best_result = 0;\n\t\tfor(int i=0; i< results.size(); ++i){\n\t\t\tif(results.at(i).result > best_result){\n\t\t\t\tbest_result_idx = i;\n\t\t\t\tbest_result = results.at(i).result;\n\t\t\t}\n\t\t}\n\t\t\/\/printf(\"%d: \\t%s\\n\", best_result_idx, results.at(best_result_idx).to_string().c_str());\n\n\t\tresults.at(best_result_idx).get_transform(out);\n\t}\n\n\ttemplate \n\tinline void calculate(const image_geometry::PinholeCameraModel &camera_model, const std::vector > &pointclouds, const std::vector &edge_images, std::vector& results){\n\t\tfor(int i=0; i < results.size(); ++i){\n\t\t\tscore::multi_score(camera_model, pointclouds, edge_images, results.at(i));\n\t\t}\n\t}\n}\n\n#endif\n<|endoftext|>"} {"text":"#pragma once\n\n\/**\n * \\file sal\/buf_ptr.hpp\n *\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n\n__sal_begin\n\n\n\/**\n * buf_ptr represents contiguous region of raw memory with specified size.\n * Internally it is kept as pointer pair to beginning and one byte past\n * end of region. Object of this class does not own pointed region. It is\n * application responsibility to handle lifecycle of buf_ptr and pointed\n * region.\n *\/\nclass buf_ptr\n{\npublic:\n\n buf_ptr () = default;\n\n\n \/**\n * Construct buf_ptr pointing to \\a region with \\a size.\n *\/\n buf_ptr (void *region, size_t size) noexcept\n : begin_(static_cast(region))\n , end_(begin_ + size)\n {}\n\n\n \/**\n * Return byte pointer to beginning of region.\n *\/\n uint8_t *begin () const noexcept\n {\n return begin_;\n }\n\n\n \/**\n * Return byte pointer to end of region.\n *\/\n uint8_t *end () const noexcept\n {\n return end_;\n }\n\n\n \/**\n * Return raw pointer to beginning of region.\n *\/\n void *data () const noexcept\n {\n return begin_;\n }\n\n\n \/**\n * Return raw pointer to beginning of region.\n *\/\n void *get () const noexcept\n {\n return begin_;\n }\n\n\n \/**\n * Return size of region\n *\/\n size_t size () const noexcept\n {\n return end_ - begin_;\n }\n\n\n \/**\n * Move beginning of pointed region by \\a s bytes toward end of region.\n *\/\n buf_ptr &operator+= (size_t s) noexcept\n {\n begin_ += s;\n if (begin_ + s > end_)\n {\n begin_ = end_;\n }\n return *this;\n }\n\n\nprivate:\n\n uint8_t *begin_{}, * const end_{};\n};\n\n\n\/**\n * Create and return new ptr from \\a p with beginning of region moved\n * toward end by \\a n bytes.\n *\/\ninline buf_ptr operator+ (const buf_ptr &p, size_t n) noexcept\n{\n auto r = p;\n r += n;\n return r;\n}\n\n\n\/**\n * Create and return new ptr from \\a p with beginning of region moved\n * toward end by \\a n bytes.\n *\/\ninline buf_ptr operator+ (size_t n, const buf_ptr &p) noexcept\n{\n auto r = p;\n r += n;\n return r;\n}\n\n\n\/**\n * Construct buf_ptr pointing to \\a region with \\a size.\n *\/\ninline buf_ptr make_buf (void *region, size_t size) noexcept\n{\n return buf_ptr(region, size);\n}\n\n\n\/**\n * Construct new buf_ptr as copy of \\a ptr.\n *\/\ninline buf_ptr make_buf (const buf_ptr &ptr) noexcept\n{\n return buf_ptr(ptr.get(), ptr.size());\n}\n\n\n\/**\n * Construct new buf_ptr as copy of \\a ptr with up \\a max_bytes.\n *\/\ninline buf_ptr make_buf (const buf_ptr &ptr, size_t max_bytes) noexcept\n{\n return buf_ptr(ptr.get(), (std::min)(max_bytes, ptr.size()));\n}\n\n\n\/**\n * Construct buf_ptr using region owned by \\a data\n *\/\ntemplate \ninline buf_ptr make_buf (char_array_t &data) noexcept\n{\n \/\/ not nice, but ok: returned pointer is initialized known size area\n return buf_ptr(const_cast(data.data()), data.size());\n}\n\n\n\/**\n * Construct buf_ptr using region owned by \\a data.\n *\/\ntemplate \ninline buf_ptr make_buf (T (&data)[N]) noexcept\n{\n return buf_ptr(data, N * sizeof(T));\n}\n\n\n\/**\n * Construct buf_ptr using region owned by \\a data.\n *\/\ntemplate \ninline buf_ptr make_buf (std::array &data) noexcept\n{\n return buf_ptr(data.data(), data.size() * sizeof(T));\n}\n\n\n\/**\n * Construct buf_ptr using region owned by \\a data. Returned object is\n * invalidated by any vector operation that invalidates all references,\n * pointers and iterators referring to the elements in the sequence.\n *\/\ntemplate \ninline buf_ptr make_buf (std::vector &data) noexcept\n{\n return buf_ptr(data.data(), data.size() * sizeof(T));\n}\n\n\n\/**\n * Construct buf_ptr using region owned by \\a data. Returned object is\n * invalidated by any string operation that invalidates all references,\n * pointers and iterators referring to the elements in the sequence.\n *\/\ntemplate \ninline buf_ptr make_buf (std::basic_string &data)\n noexcept\n{\n return buf_ptr(&data[0], data.size() * sizeof(T));\n}\n\n\n\/**\n * Construct buf_ptr using region owned by \\a data but not more than\n * \\a max_bytes\n *\/\ntemplate \ninline buf_ptr make_buf (char_array_t &data, size_t max_bytes) noexcept\n{\n \/\/ not nice, but ok: returned pointer is initialized known size area\n return buf_ptr(const_cast(data.data()),\n (std::min)(max_bytes, data.size())\n );\n}\n\n\n\/**\n * Construct buf_ptr using region owned by \\a data but not more than\n * \\a max_bytes.\n *\/\ntemplate \ninline buf_ptr make_buf (T (&data)[N], size_t max_bytes) noexcept\n{\n return buf_ptr(data, (std::min)(max_bytes, N * sizeof(T)));\n}\n\n\n\/**\n * Construct buf_ptr using region owned by \\a data but not more than\n * \\a max_bytes.\n *\/\ntemplate \ninline buf_ptr make_buf (std::array &data, size_t max_bytes) noexcept\n{\n return buf_ptr(data.data(), (std::min)(max_bytes, data.size() * sizeof(T)));\n}\n\n\n\/**\n * Construct buf_ptr using region owned by \\a data but not more than\n * \\a max_bytes.\n *\/\ntemplate \ninline buf_ptr make_buf (std::vector &data, size_t max_bytes)\n noexcept\n{\n return buf_ptr(data.data(), (std::min)(max_bytes, data.size() * sizeof(T)));\n}\n\n\n\/**\n * Construct buf_ptr using region owned by \\a data but not more than\n * \\a max_bytes.\n *\/\ntemplate \ninline buf_ptr make_buf (std::basic_string &data,\n size_t max_bytes) noexcept\n{\n return buf_ptr(&data[0], (std::min)(max_bytes, data.size() * sizeof(T)));\n}\n\n\n\/**\n * const_buf_ptr represents contiguous region of raw memory with specified\n * size. Internally it is kept as pointer pair to beginning and one byte past\n * end of region. Object of this class does not own pointed region. It is\n * application responsibility to handle lifecycle of buf_ptr and pointed\n * region.\n *\/\nclass const_buf_ptr\n{\npublic:\n\n const_buf_ptr () = default;\n\n\n \/**\n * Construct const_buf_ptr pointing to \\a region with \\a size.\n *\/\n const_buf_ptr (const void *region, size_t size) noexcept\n : begin_(static_cast(region))\n , end_(begin_ + size)\n {}\n\n\n \/**\n * Return byte pointer to beginning of region.\n *\/\n const uint8_t *begin () const noexcept\n {\n return begin_;\n }\n\n\n \/**\n * Return byte pointer to end of region.\n *\/\n const uint8_t *end () const noexcept\n {\n return end_;\n }\n\n\n \/**\n * Return pointer to beginning of region.\n *\/\n const void *data () const noexcept\n {\n return begin_;\n }\n\n\n \/**\n * Return pointer to beginning of region.\n *\/\n const void *get () const noexcept\n {\n return begin_;\n }\n\n\n \/**\n * Return size of region\n *\/\n size_t size () const noexcept\n {\n return end_ - begin_;\n }\n\n\n \/**\n * Move beginning of pointed region by \\a s bytes toward end of region.\n *\/\n const_buf_ptr &operator+= (size_t s) noexcept\n {\n begin_ += s;\n if (begin_ > end_)\n {\n begin_ = end_;\n }\n return *this;\n }\n\n\nprivate:\n\n const uint8_t *begin_{}, * const end_{};\n};\n\n\n\/**\n * Create and return new ptr from \\a p with beginning of region moved\n * toward end by \\a n bytes.\n *\/\ninline const_buf_ptr operator+ (const const_buf_ptr &p, size_t n) noexcept\n{\n auto r = p;\n r += n;\n return r;\n}\n\n\n\/**\n * Create and return new ptr from \\a p with beginning of region moved\n * toward end by \\a n bytes.\n *\/\ninline const_buf_ptr operator+ (size_t n, const const_buf_ptr &p) noexcept\n{\n auto r = p;\n r += n;\n return r;\n}\n\n\n\/**\n * Construct const_buf_ptr pointing to \\a region with \\a size.\n *\/\ninline const_buf_ptr make_buf (const void *region, size_t size) noexcept\n{\n return const_buf_ptr(region, size);\n}\n\n\n\/**\n * Construct new const_buf_ptr as copy of \\a ptr.\n *\/\ninline const_buf_ptr make_buf (const const_buf_ptr &ptr) noexcept\n{\n return const_buf_ptr(ptr.get(), ptr.size());\n}\n\n\n\/**\n * Construct new const_buf_ptr as copy of \\a ptr with up \\a max_bytes.\n *\/\ninline const_buf_ptr make_buf (const const_buf_ptr &ptr, size_t max_bytes)\n noexcept\n{\n return const_buf_ptr(ptr.get(), (std::min)(max_bytes, ptr.size()));\n}\n\n\n\/**\n * Construct const_buf_ptr using region owned by \\a data\n *\/\ntemplate \ninline const_buf_ptr make_buf (const char_array_t &data) noexcept\n{\n return const_buf_ptr(data.data(), data.size());\n}\n\n\n\/**\n * Construct const_buf_ptr using region owned by \\a data.\n *\/\ntemplate \ninline const_buf_ptr make_buf (const T (&data)[N]) noexcept\n{\n return const_buf_ptr(data, N * sizeof(T));\n}\n\n\n\/**\n * Construct const_buf_ptr using region owned by \\a data.\n *\/\ntemplate \ninline const_buf_ptr make_buf (const std::array &data) noexcept\n{\n return const_buf_ptr(data.data(), data.size() * sizeof(T));\n}\n\n\n\/**\n * Construct const_buf_ptr using region owned by \\a data. Returned object is\n * invalidated by any vector operation that invalidates all references,\n * pointers and iterators referring to the elements in the sequence.\n *\/\ntemplate \ninline const_buf_ptr make_buf (const std::vector &data) noexcept\n{\n return const_buf_ptr(data.data(), data.size() * sizeof(T));\n}\n\n\n\/**\n * Construct const_buf_ptr using region owned by \\a data. Returned object is\n * invalidated by any string operation that invalidates all references,\n * pointers and iterators referring to the elements in the sequence.\n *\/\ntemplate \ninline const_buf_ptr make_buf (\n const std::basic_string &data) noexcept\n{\n return const_buf_ptr(&data[0], data.size() * sizeof(T));\n}\n\n\n\/**\n * Construct const_buf_ptr using region owned by \\a data but not more than\n * \\a max_bytes.\n *\/\ntemplate \ninline const_buf_ptr make_buf (const char_array_t &data, size_t max_bytes)\n noexcept\n{\n return const_buf_ptr(data.data(), (std::min)(max_bytes, data.size()));\n}\n\n\n\/**\n * Construct const_buf_ptr using region owned by \\a data but not more than\n * \\a max_bytes.\n *\/\ntemplate \ninline const_buf_ptr make_buf (const T (&data)[N], size_t max_bytes) noexcept\n{\n return const_buf_ptr(data, (std::min)(max_bytes, N * sizeof(T)));\n}\n\n\n\/**\n * Construct const_buf_ptr using region owned by \\a data but not more than\n * \\a max_bytes.\n *\/\ntemplate \ninline const_buf_ptr make_buf (const std::array &data, size_t max_bytes)\n noexcept\n{\n return const_buf_ptr(data.data(),\n (std::min)(max_bytes, data.size() * sizeof(T))\n );\n}\n\n\n\/**\n * Construct const_buf_ptr using region owned by \\a data but not more than\n * \\a max_bytes.\n *\/\ntemplate \ninline const_buf_ptr make_buf (const std::vector &data,\n size_t max_bytes) noexcept\n{\n return const_buf_ptr(data.data(),\n (std::min)(max_bytes, data.size() * sizeof(T))\n );\n}\n\n\n\/**\n * Construct const_buf_ptr using region owned by \\a data but not more than\n * \\a max_bytes.\n *\/\ntemplate \ninline const_buf_ptr make_buf (\n const std::basic_string &data,\n size_t max_bytes) noexcept\n{\n return const_buf_ptr(&data[0],\n (std::min)(max_bytes, data.size() * sizeof(T))\n );\n}\n\n\n__sal_end\nbuf_ptr: add null_buf & const_null_buf#pragma once\n\n\/**\n * \\file sal\/buf_ptr.hpp\n *\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n\n__sal_begin\n\n\n\/**\n * buf_ptr represents contiguous region of raw memory with specified size.\n * Internally it is kept as pointer pair to beginning and one byte past\n * end of region. Object of this class does not own pointed region. It is\n * application responsibility to handle lifecycle of buf_ptr and pointed\n * region.\n *\/\nclass buf_ptr\n{\npublic:\n\n buf_ptr () = default;\n\n\n \/**\n * Construct buf_ptr pointing to \\a region with \\a size.\n *\/\n buf_ptr (void *region, size_t size) noexcept\n : begin_(static_cast(region))\n , end_(begin_ + size)\n {}\n\n\n \/**\n * Return byte pointer to beginning of region.\n *\/\n uint8_t *begin () const noexcept\n {\n return begin_;\n }\n\n\n \/**\n * Return byte pointer to end of region.\n *\/\n uint8_t *end () const noexcept\n {\n return end_;\n }\n\n\n \/**\n * Return raw pointer to beginning of region.\n *\/\n void *data () const noexcept\n {\n return begin_;\n }\n\n\n \/**\n * Return raw pointer to beginning of region.\n *\/\n void *get () const noexcept\n {\n return begin_;\n }\n\n\n \/**\n * Return size of region\n *\/\n size_t size () const noexcept\n {\n return end_ - begin_;\n }\n\n\n \/**\n * Move beginning of pointed region by \\a s bytes toward end of region.\n *\/\n buf_ptr &operator+= (size_t s) noexcept\n {\n begin_ += s;\n if (begin_ + s > end_)\n {\n begin_ = end_;\n }\n return *this;\n }\n\n\nprivate:\n\n uint8_t *begin_{}, * const end_{};\n};\n\n\n\/**\n * Nullptr buf_ptr with no size.\n *\/\ninline const buf_ptr null_buf;\n\n\n\/**\n * Create and return new ptr from \\a p with beginning of region moved\n * toward end by \\a n bytes.\n *\/\ninline buf_ptr operator+ (const buf_ptr &p, size_t n) noexcept\n{\n auto r = p;\n r += n;\n return r;\n}\n\n\n\/**\n * Create and return new ptr from \\a p with beginning of region moved\n * toward end by \\a n bytes.\n *\/\ninline buf_ptr operator+ (size_t n, const buf_ptr &p) noexcept\n{\n auto r = p;\n r += n;\n return r;\n}\n\n\n\/**\n * Construct buf_ptr pointing to \\a region with \\a size.\n *\/\ninline buf_ptr make_buf (void *region, size_t size) noexcept\n{\n return buf_ptr(region, size);\n}\n\n\n\/**\n * Construct new buf_ptr as copy of \\a ptr.\n *\/\ninline buf_ptr make_buf (const buf_ptr &ptr) noexcept\n{\n return buf_ptr(ptr.get(), ptr.size());\n}\n\n\n\/**\n * Construct new buf_ptr as copy of \\a ptr with up \\a max_bytes.\n *\/\ninline buf_ptr make_buf (const buf_ptr &ptr, size_t max_bytes) noexcept\n{\n return buf_ptr(ptr.get(), (std::min)(max_bytes, ptr.size()));\n}\n\n\n\/**\n * Construct buf_ptr using region owned by \\a data\n *\/\ntemplate \ninline buf_ptr make_buf (char_array_t &data) noexcept\n{\n \/\/ not nice, but ok: returned pointer is initialized known size area\n return buf_ptr(const_cast(data.data()), data.size());\n}\n\n\n\/**\n * Construct buf_ptr using region owned by \\a data.\n *\/\ntemplate \ninline buf_ptr make_buf (T (&data)[N]) noexcept\n{\n return buf_ptr(data, N * sizeof(T));\n}\n\n\n\/**\n * Construct buf_ptr using region owned by \\a data.\n *\/\ntemplate \ninline buf_ptr make_buf (std::array &data) noexcept\n{\n return buf_ptr(data.data(), data.size() * sizeof(T));\n}\n\n\n\/**\n * Construct buf_ptr using region owned by \\a data. Returned object is\n * invalidated by any vector operation that invalidates all references,\n * pointers and iterators referring to the elements in the sequence.\n *\/\ntemplate \ninline buf_ptr make_buf (std::vector &data) noexcept\n{\n return buf_ptr(data.data(), data.size() * sizeof(T));\n}\n\n\n\/**\n * Construct buf_ptr using region owned by \\a data. Returned object is\n * invalidated by any string operation that invalidates all references,\n * pointers and iterators referring to the elements in the sequence.\n *\/\ntemplate \ninline buf_ptr make_buf (std::basic_string &data)\n noexcept\n{\n return buf_ptr(&data[0], data.size() * sizeof(T));\n}\n\n\n\/**\n * Construct buf_ptr using region owned by \\a data but not more than\n * \\a max_bytes\n *\/\ntemplate \ninline buf_ptr make_buf (char_array_t &data, size_t max_bytes) noexcept\n{\n \/\/ not nice, but ok: returned pointer is initialized known size area\n return buf_ptr(const_cast(data.data()),\n (std::min)(max_bytes, data.size())\n );\n}\n\n\n\/**\n * Construct buf_ptr using region owned by \\a data but not more than\n * \\a max_bytes.\n *\/\ntemplate \ninline buf_ptr make_buf (T (&data)[N], size_t max_bytes) noexcept\n{\n return buf_ptr(data, (std::min)(max_bytes, N * sizeof(T)));\n}\n\n\n\/**\n * Construct buf_ptr using region owned by \\a data but not more than\n * \\a max_bytes.\n *\/\ntemplate \ninline buf_ptr make_buf (std::array &data, size_t max_bytes) noexcept\n{\n return buf_ptr(data.data(), (std::min)(max_bytes, data.size() * sizeof(T)));\n}\n\n\n\/**\n * Construct buf_ptr using region owned by \\a data but not more than\n * \\a max_bytes.\n *\/\ntemplate \ninline buf_ptr make_buf (std::vector &data, size_t max_bytes)\n noexcept\n{\n return buf_ptr(data.data(), (std::min)(max_bytes, data.size() * sizeof(T)));\n}\n\n\n\/**\n * Construct buf_ptr using region owned by \\a data but not more than\n * \\a max_bytes.\n *\/\ntemplate \ninline buf_ptr make_buf (std::basic_string &data,\n size_t max_bytes) noexcept\n{\n return buf_ptr(&data[0], (std::min)(max_bytes, data.size() * sizeof(T)));\n}\n\n\n\/**\n * const_buf_ptr represents contiguous region of raw memory with specified\n * size. Internally it is kept as pointer pair to beginning and one byte past\n * end of region. Object of this class does not own pointed region. It is\n * application responsibility to handle lifecycle of buf_ptr and pointed\n * region.\n *\/\nclass const_buf_ptr\n{\npublic:\n\n const_buf_ptr () = default;\n\n\n \/**\n * Construct const_buf_ptr pointing to \\a region with \\a size.\n *\/\n const_buf_ptr (const void *region, size_t size) noexcept\n : begin_(static_cast(region))\n , end_(begin_ + size)\n {}\n\n\n \/**\n * Return byte pointer to beginning of region.\n *\/\n const uint8_t *begin () const noexcept\n {\n return begin_;\n }\n\n\n \/**\n * Return byte pointer to end of region.\n *\/\n const uint8_t *end () const noexcept\n {\n return end_;\n }\n\n\n \/**\n * Return pointer to beginning of region.\n *\/\n const void *data () const noexcept\n {\n return begin_;\n }\n\n\n \/**\n * Return pointer to beginning of region.\n *\/\n const void *get () const noexcept\n {\n return begin_;\n }\n\n\n \/**\n * Return size of region\n *\/\n size_t size () const noexcept\n {\n return end_ - begin_;\n }\n\n\n \/**\n * Move beginning of pointed region by \\a s bytes toward end of region.\n *\/\n const_buf_ptr &operator+= (size_t s) noexcept\n {\n begin_ += s;\n if (begin_ > end_)\n {\n begin_ = end_;\n }\n return *this;\n }\n\n\nprivate:\n\n const uint8_t *begin_{}, * const end_{};\n};\n\n\n\/**\n * Nullptr const_buf_ptr with no size.\n *\/\ninline const const_buf_ptr const_null_buf;\n\n\n\/**\n * Create and return new ptr from \\a p with beginning of region moved\n * toward end by \\a n bytes.\n *\/\ninline const_buf_ptr operator+ (const const_buf_ptr &p, size_t n) noexcept\n{\n auto r = p;\n r += n;\n return r;\n}\n\n\n\/**\n * Create and return new ptr from \\a p with beginning of region moved\n * toward end by \\a n bytes.\n *\/\ninline const_buf_ptr operator+ (size_t n, const const_buf_ptr &p) noexcept\n{\n auto r = p;\n r += n;\n return r;\n}\n\n\n\/**\n * Construct const_buf_ptr pointing to \\a region with \\a size.\n *\/\ninline const_buf_ptr make_buf (const void *region, size_t size) noexcept\n{\n return const_buf_ptr(region, size);\n}\n\n\n\/**\n * Construct new const_buf_ptr as copy of \\a ptr.\n *\/\ninline const_buf_ptr make_buf (const const_buf_ptr &ptr) noexcept\n{\n return const_buf_ptr(ptr.get(), ptr.size());\n}\n\n\n\/**\n * Construct new const_buf_ptr as copy of \\a ptr with up \\a max_bytes.\n *\/\ninline const_buf_ptr make_buf (const const_buf_ptr &ptr, size_t max_bytes)\n noexcept\n{\n return const_buf_ptr(ptr.get(), (std::min)(max_bytes, ptr.size()));\n}\n\n\n\/**\n * Construct const_buf_ptr using region owned by \\a data\n *\/\ntemplate \ninline const_buf_ptr make_buf (const char_array_t &data) noexcept\n{\n return const_buf_ptr(data.data(), data.size());\n}\n\n\n\/**\n * Construct const_buf_ptr using region owned by \\a data.\n *\/\ntemplate \ninline const_buf_ptr make_buf (const T (&data)[N]) noexcept\n{\n return const_buf_ptr(data, N * sizeof(T));\n}\n\n\n\/**\n * Construct const_buf_ptr using region owned by \\a data.\n *\/\ntemplate \ninline const_buf_ptr make_buf (const std::array &data) noexcept\n{\n return const_buf_ptr(data.data(), data.size() * sizeof(T));\n}\n\n\n\/**\n * Construct const_buf_ptr using region owned by \\a data. Returned object is\n * invalidated by any vector operation that invalidates all references,\n * pointers and iterators referring to the elements in the sequence.\n *\/\ntemplate \ninline const_buf_ptr make_buf (const std::vector &data) noexcept\n{\n return const_buf_ptr(data.data(), data.size() * sizeof(T));\n}\n\n\n\/**\n * Construct const_buf_ptr using region owned by \\a data. Returned object is\n * invalidated by any string operation that invalidates all references,\n * pointers and iterators referring to the elements in the sequence.\n *\/\ntemplate \ninline const_buf_ptr make_buf (\n const std::basic_string &data) noexcept\n{\n return const_buf_ptr(&data[0], data.size() * sizeof(T));\n}\n\n\n\/**\n * Construct const_buf_ptr using region owned by \\a data but not more than\n * \\a max_bytes.\n *\/\ntemplate \ninline const_buf_ptr make_buf (const char_array_t &data, size_t max_bytes)\n noexcept\n{\n return const_buf_ptr(data.data(), (std::min)(max_bytes, data.size()));\n}\n\n\n\/**\n * Construct const_buf_ptr using region owned by \\a data but not more than\n * \\a max_bytes.\n *\/\ntemplate \ninline const_buf_ptr make_buf (const T (&data)[N], size_t max_bytes) noexcept\n{\n return const_buf_ptr(data, (std::min)(max_bytes, N * sizeof(T)));\n}\n\n\n\/**\n * Construct const_buf_ptr using region owned by \\a data but not more than\n * \\a max_bytes.\n *\/\ntemplate \ninline const_buf_ptr make_buf (const std::array &data, size_t max_bytes)\n noexcept\n{\n return const_buf_ptr(data.data(),\n (std::min)(max_bytes, data.size() * sizeof(T))\n );\n}\n\n\n\/**\n * Construct const_buf_ptr using region owned by \\a data but not more than\n * \\a max_bytes.\n *\/\ntemplate \ninline const_buf_ptr make_buf (const std::vector &data,\n size_t max_bytes) noexcept\n{\n return const_buf_ptr(data.data(),\n (std::min)(max_bytes, data.size() * sizeof(T))\n );\n}\n\n\n\/**\n * Construct const_buf_ptr using region owned by \\a data but not more than\n * \\a max_bytes.\n *\/\ntemplate \ninline const_buf_ptr make_buf (\n const std::basic_string &data,\n size_t max_bytes) noexcept\n{\n return const_buf_ptr(&data[0],\n (std::min)(max_bytes, data.size() * sizeof(T))\n );\n}\n\n\n__sal_end\n<|endoftext|>"} {"text":"\/\/Copyright 2015 Adam Smith\n\/\/\n\/\/Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/you may not use this file except in compliance with the License.\n\/\/You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/Unless required by applicable law or agreed to in writing, software\n\/\/distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/See the License for the specific language governing permissions and\n\/\/limitations under the License.\n\n\/\/ Contact :\n\/\/ Email : solairelibrary@mail.com\n\/\/ GitHub repository : https:\/\/github.com\/SolaireLibrary\/SolaireCPP\n\n#include \"Solaire\/XML\/Format.hpp\"\n\nnamespace Solaire {\n\n static bool skipWhitespace(IStream& aStream) {\n if(aStream.end()) return true;\n char c;\n aStream >> c;\n while(std::isspace(c)) {\n if(aStream.end()) return true;\n aStream >> c;\n }\n aStream.setOffset(aStream.getOffset() - 1);\n return true;\n }\n\n static bool writeObject(const StringConstant& aName, const GenericObject& aValue, OStream& aStream) throw();\n\n static bool writeArray(const StringConstant& aName, const GenericArray& aValue, OStream& aStream) throw() {\n aStream << '<';\n aStream << aName;\n if(aValue.size() > 0) {\n aStream << '>';\n const auto end = aValue.end();\n for(auto i = aValue.begin(); i != end; ++i) {\n switch(i->getType()) {\n case GenericValue::NULL_T:\n aStream << \"\";\n break;\n case GenericValue::CHAR_T:\n aStream << \"getChar();\n aStream << \"\\\"\/>\";\n break;\n case GenericValue::BOOL_T:\n aStream << \"getBool()) {\n aStream << \"true\";\n }else {\n aStream << \"false\";\n }\n aStream << \"\\\"\/>\";\n break;\n case GenericValue::UNSIGNED_T:\n aStream << \"getUnsigned();\n aStream << \"\\\"\/>\";\n break;\n case GenericValue::SIGNED_T:\n aStream << \"getSigned();\n aStream << \"\\\"\/>\";\n break;\n case GenericValue::DOUBLE_T:\n aStream << \"getDouble();\n aStream << \"\\\"\/>\";\n break;\n case GenericValue::STRING_T:\n aStream << \"getString();\n aStream << \"\\\"\/>\";\n break;\n case GenericValue::ARRAY_T:\n writeArray(CString(\"solaire_array_element\"), i->getArray(), aStream);\n break;\n case GenericValue::OBJECT_T:\n writeObject(CString(\"solaire_array_element\"), i->getObject(), aStream);\n break;\n default:\n break;\n }\n }\n\n aStream << '<';\n aStream << '\/';\n aStream << aName;\n aStream << '>';\n }else {\n aStream << '\/';\n aStream << '>';\n }\n return true;\n }\n\n static bool writeObject(const StringConstant& aName, const GenericObject& aValue, OStream& aStream) throw() {\n if(aValue.size() == 0) {\n aStream << '<';\n aStream << aName;\n aStream << '\/';\n aStream << '>';\n return true;\n }\n\n const auto entries = aValue.getEntries();\n const auto end = entries->end();\n\n aStream << '<';\n aStream << aName;\n\n \/\/ Write attributes\n aStream << ' ';\n for(auto i = entries->begin(); i != end; ++i) {\n switch(i->second.getType()) {\n case GenericValue::NULL_T:\n aStream << i->first;\n aStream << \"=\\\"null\\\" \";\n break;\n case GenericValue::CHAR_T:\n aStream << i->first;\n aStream << \"=\\\"\";\n aStream << i->second.getChar();\n aStream << \"\\\" \";\n break;\n case GenericValue::BOOL_T:\n aStream << i->first;\n if(i->second.getBool()) {\n aStream << \"=\\\"true\\\" \";\n }else {\n aStream << \"=\\\"false\\\" \";\n }\n break;\n case GenericValue::UNSIGNED_T:\n aStream << i->first;\n aStream << \"=\\\"\";\n aStream << i->second.getUnsigned();\n aStream << \"\\\" \";\n break;\n case GenericValue::SIGNED_T:\n aStream << i->first;\n aStream << \"=\\\"\";\n aStream << i->second.getSigned();\n aStream << \"\\\" \";\n break;\n case GenericValue::DOUBLE_T:\n aStream << i->first;\n aStream << \"=\\\"\";\n aStream << i->second.getDouble();\n aStream << \"\\\" \";\n break;\n case GenericValue::STRING_T:\n aStream << i->first;\n aStream << \"=\\\"\";\n aStream << i->second.getString();\n aStream << \"\\\" \";\n break;\n default:\n break;\n }\n }\n\n aStream << '>';\n\n \/\/ Write elements\n for(auto i = entries->begin(); i != end; ++i) {\n switch(i->second.getType()) {\n case GenericValue::ARRAY_T:\n writeArray(i->first, i->second.getArray(), aStream);\n break;\n case GenericValue::OBJECT_T:\n writeObject(i->first, i->second.getObject(), aStream);\n break;\n default:\n break;\n }\n }\n\n aStream << '<';\n aStream << '\/';\n aStream << aName;\n aStream << '>';\n return true;\n }\n\n\n \/\/ JsonFormat\n\n SOLAIRE_EXPORT_CALL XmlFormat::~XmlFormat() {\n\n }\n\n GenericValue SOLAIRE_EXPORT_CALL XmlFormat::readValue(IStream& aStream) const throw() {\n try{\n \/\/! \\todo Implement XML read\n throw std::runtime_error(\"Not implemented\");\n }catch(std::exception& e) {\n std::cerr << e.what() << std::endl;\n return GenericValue();\n }\n }\n\n bool SOLAIRE_EXPORT_CALL XmlFormat::writeValue(const GenericValue& aValue, OStream& aStream) const throw() {\n\n try{\n switch(aValue.getType()) {\n case GenericValue::ARRAY_T:\n return writeArray(CString(\"array\"), aValue.getArray(), aStream);\n case GenericValue::OBJECT_T:\n return writeObject(CString(\"object\"), aValue.getObject(), aStream);\n default:\n return false;\n }\n }catch(std::exception& e) {\n std::cerr << e.what() << std::endl;\n return false;\n }\n }\n\n Attribute XmlFormat::readAttribute(IStream& aStream) const throw() {\n if(! skipWhitespace(aStream)) return Attribute();\n CString name;\n char c;\n if(aStream.end()) return Attribute();\n aStream >> c;\n while(c != '=') {\n if(aStream.end()) return Attribute();\n name += c;\n aStream >> c;\n }\n if(aStream.end()) return Attribute();\n aStream >> c;\n if(c != '\"') return Attribute();\n CString value;\n if(aStream.end()) return Attribute();\n aStream >> c;\n while(c != '\"') {\n if(aStream.end()) return Attribute();\n name += c;\n aStream >> c;\n }\n return Attribute(name, value);\n }\n\n bool XmlFormat::writeAttribute(const Attribute& aAttribute, OStream& aStream) const throw() {\n aStream << aAttribute.getName() << \"=\\\"\" << aAttribute.getValue() << '\"';\n return true;\n }\n\n Element XmlFormat::readElement(IStream& aStream) const throw() {\n if(! skipWhitespace(aStream)) return Element();\n char c;\n Element element;\n String& name = element.getName();\n String& body = element.getBody();\n List& attributes = element.getAttributes();\n List& elements = element.getElements();\n\n \/\/ Start tag\n {\n \/\/ Open tag\n if(aStream.end()) return Element();\n aStream >> c;\n if(c != '<') return Element();\n\n \/\/ Read name\n if(aStream.end()) return Element();\n aStream >> c;\n\n while(! (std::isspace(c) || c == '\/' || c == '>')) {\n name += c;\n if(aStream.end()) return Element();\n aStream >> c;\n }\n\n \/\/ Close tag\n bool endTag = true;\n while(endTag) {\n while(std::isspace(c)) {\n if(aStream.end()) return Element();\n aStream >> c;\n }\n if(c == '\/') {\n if(aStream.end()) return Element();\n aStream >> c;\n if(c != '>') return Element();\n return element;\n }else if(c == '>') {\n endTag = false;\n }else{\n aStream.setOffset(aStream.getOffset() - 1);\n \/\/ Read attributes\n attributes.pushBack(readAttribute(aStream));\n c = aStream.peek();\n }\n }\n }\n\n \/\/ Body\n {\n bool endBody = true;\n while(endBody){\n while(std::isspace(c)) {\n if(aStream.end()) return Element();\n aStream >> c;\n }\n\n if(c == '<'){\n if(aStream.end()) return Element();\n aStream >> c;\n if(c == '\/'){\n endBody = false;\n aStream.setOffset(aStream.getOffset() - 2);\n }else {\n \/\/ Read Element\n aStream.setOffset(aStream.getOffset() - 2);\n elements.pushBack(readElement(aStream));\n c = aStream.peek();\n }\n }else{\n \/\/ Read body\n body += c;\n if(aStream.end()) return Element();\n aStream >> c;\n }\n }\n\n\n }\n\n \/\/ End tag\n {\n\n \/\/ Open tag\n while(std::isspace(c)) {\n if(aStream.end()) return Element();\n aStream >> c;\n }\n if(aStream.end()) return Element();\n aStream >> c;\n if(c != '<') return Element();\n\n if(aStream.end()) return Element();\n aStream >> c;\n if(c != '\/') return Element();\n\n \/\/ Read name\n while(std::isspace(c)) {\n if(aStream.end()) return Element();\n aStream >> c;\n }\n\n CString endName;\n while(! (std::isspace(c) || c == '>')) {\n endName += c;\n if(aStream.end()) return Element();\n aStream >> c;\n }\n\n if(name != endName) return Element();\n\n \/\/ Close Tag\n while(c != '>') {\n if(aStream.end()) return Element();\n aStream >> c;\n }\n }\n\n return element;\n }\n\n bool XmlFormat::writeElement(const Element& aElement, OStream& aStream) const throw() {\n aStream << '<' << aElement.getName();\n\n const StaticContainer& attributes = aElement.getAttributes();\n if(attributes.size() > 0) {\n aStream << ' ';\n for(const Attribute& i : attributes) {\n writeAttribute(i, aStream);\n aStream << ' ';\n }\n }\n\n const int32_t bodySize = aElement.getBody().size();\n const int32_t elementCount = aElement.getElements().size();\n if(bodySize + elementCount == 0) {\n aStream << \"\/>\";\n }else {\n aStream << '>';\n\n if(bodySize != 0) {\n if(elementCount != 0) return false;\n const StaticContainer& elements = aElement.getElements();\n for(const Element& i : elements) {\n writeElement(i, aStream);\n }\n }else {\n aStream << aElement.getBody();\n }\n\n aStream << \"<\/\";\n aStream << aElement.getName();\n aStream << '>';\n }\n return true;\n }\n\n}\nAdded partial logic for convertion form Xml element to GenericValue\/\/Copyright 2015 Adam Smith\n\/\/\n\/\/Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/you may not use this file except in compliance with the License.\n\/\/You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/Unless required by applicable law or agreed to in writing, software\n\/\/distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/See the License for the specific language governing permissions and\n\/\/limitations under the License.\n\n\/\/ Contact :\n\/\/ Email : solairelibrary@mail.com\n\/\/ GitHub repository : https:\/\/github.com\/SolaireLibrary\/SolaireCPP\n\n#include \"Solaire\/XML\/Format.hpp\"\n\nnamespace Solaire {\n\n static bool skipWhitespace(IStream& aStream) {\n if(aStream.end()) return true;\n char c;\n aStream >> c;\n while(std::isspace(c)) {\n if(aStream.end()) return true;\n aStream >> c;\n }\n aStream.setOffset(aStream.getOffset() - 1);\n return true;\n }\n\n static bool writeObject(const StringConstant& aName, const GenericObject& aValue, OStream& aStream) throw();\n\n static bool writeArray(const StringConstant& aName, const GenericArray& aValue, OStream& aStream) throw() {\n aStream << '<';\n aStream << aName;\n if(aValue.size() > 0) {\n aStream << '>';\n const auto end = aValue.end();\n for(auto i = aValue.begin(); i != end; ++i) {\n switch(i->getType()) {\n case GenericValue::NULL_T:\n aStream << \"\";\n break;\n case GenericValue::CHAR_T:\n aStream << \"getChar();\n aStream << \"\\\"\/>\";\n break;\n case GenericValue::BOOL_T:\n aStream << \"getBool()) {\n aStream << \"true\";\n }else {\n aStream << \"false\";\n }\n aStream << \"\\\"\/>\";\n break;\n case GenericValue::UNSIGNED_T:\n aStream << \"getUnsigned();\n aStream << \"\\\"\/>\";\n break;\n case GenericValue::SIGNED_T:\n aStream << \"getSigned();\n aStream << \"\\\"\/>\";\n break;\n case GenericValue::DOUBLE_T:\n aStream << \"getDouble();\n aStream << \"\\\"\/>\";\n break;\n case GenericValue::STRING_T:\n aStream << \"getString();\n aStream << \"\\\"\/>\";\n break;\n case GenericValue::ARRAY_T:\n writeArray(CString(\"solaire_array_element\"), i->getArray(), aStream);\n break;\n case GenericValue::OBJECT_T:\n writeObject(CString(\"solaire_array_element\"), i->getObject(), aStream);\n break;\n default:\n break;\n }\n }\n\n aStream << '<';\n aStream << '\/';\n aStream << aName;\n aStream << '>';\n }else {\n aStream << '\/';\n aStream << '>';\n }\n return true;\n }\n\n static bool writeObject(const StringConstant& aName, const GenericObject& aValue, OStream& aStream) throw() {\n if(aValue.size() == 0) {\n aStream << '<';\n aStream << aName;\n aStream << '\/';\n aStream << '>';\n return true;\n }\n\n const auto entries = aValue.getEntries();\n const auto end = entries->end();\n\n aStream << '<';\n aStream << aName;\n\n \/\/ Write attributes\n aStream << ' ';\n for(auto i = entries->begin(); i != end; ++i) {\n switch(i->second.getType()) {\n case GenericValue::NULL_T:\n aStream << i->first;\n aStream << \"=\\\"null\\\" \";\n break;\n case GenericValue::CHAR_T:\n aStream << i->first;\n aStream << \"=\\\"\";\n aStream << i->second.getChar();\n aStream << \"\\\" \";\n break;\n case GenericValue::BOOL_T:\n aStream << i->first;\n if(i->second.getBool()) {\n aStream << \"=\\\"true\\\" \";\n }else {\n aStream << \"=\\\"false\\\" \";\n }\n break;\n case GenericValue::UNSIGNED_T:\n aStream << i->first;\n aStream << \"=\\\"\";\n aStream << i->second.getUnsigned();\n aStream << \"\\\" \";\n break;\n case GenericValue::SIGNED_T:\n aStream << i->first;\n aStream << \"=\\\"\";\n aStream << i->second.getSigned();\n aStream << \"\\\" \";\n break;\n case GenericValue::DOUBLE_T:\n aStream << i->first;\n aStream << \"=\\\"\";\n aStream << i->second.getDouble();\n aStream << \"\\\" \";\n break;\n case GenericValue::STRING_T:\n aStream << i->first;\n aStream << \"=\\\"\";\n aStream << i->second.getString();\n aStream << \"\\\" \";\n break;\n default:\n break;\n }\n }\n\n aStream << '>';\n\n \/\/ Write elements\n for(auto i = entries->begin(); i != end; ++i) {\n switch(i->second.getType()) {\n case GenericValue::ARRAY_T:\n writeArray(i->first, i->second.getArray(), aStream);\n break;\n case GenericValue::OBJECT_T:\n writeObject(i->first, i->second.getObject(), aStream);\n break;\n default:\n break;\n }\n }\n\n aStream << '<';\n aStream << '\/';\n aStream << aName;\n aStream << '>';\n return true;\n }\n\n static GenericValue elementToGenericValue(const Element& aElement) throw() {\n const String& body = aElement.getBody();\n const List& attributes = aElement.getAttributes();\n const List& elements = aElement.getElements();\n const int32_t bodySize = body.size();\n const int32_t attributeCount = attributes.size();\n const int32_t elementCount = elements.size();\n\n if(bodySize + attributeCount + elementCount == 0) return GenericValue();\n if(attributeCount + elementCount > 0) {\n \/\/ Parse object\n }else if(attributeCount + elementCount > 0) {\n if(bodySize > 0) return GenericValue();\n \/\/ Check if array\n \/\/ Parse array\n \/\/ Check if object\n \/\/ Parse object\n return GenericValue();\n }else{\n \/\/ Parse body value\n GenericValue();\n }\n\n \/\/! \\todo convert Element to GenericValue\n return GenericValue();\n }\n\n \/\/ JsonFormat\n\n SOLAIRE_EXPORT_CALL XmlFormat::~XmlFormat() {\n\n }\n\n GenericValue SOLAIRE_EXPORT_CALL XmlFormat::readValue(IStream& aStream) const throw() {\n return elementToGenericValue(readElement(aStream));\n }\n\n bool SOLAIRE_EXPORT_CALL XmlFormat::writeValue(const GenericValue& aValue, OStream& aStream) const throw() {\n\n try{\n switch(aValue.getType()) {\n case GenericValue::ARRAY_T:\n return writeArray(CString(\"array\"), aValue.getArray(), aStream);\n case GenericValue::OBJECT_T:\n return writeObject(CString(\"object\"), aValue.getObject(), aStream);\n default:\n return false;\n }\n }catch(std::exception& e) {\n std::cerr << e.what() << std::endl;\n return false;\n }\n }\n\n Attribute XmlFormat::readAttribute(IStream& aStream) const throw() {\n if(! skipWhitespace(aStream)) return Attribute();\n CString name;\n char c;\n if(aStream.end()) return Attribute();\n aStream >> c;\n while(c != '=') {\n if(aStream.end()) return Attribute();\n name += c;\n aStream >> c;\n }\n if(aStream.end()) return Attribute();\n aStream >> c;\n if(c != '\"') return Attribute();\n CString value;\n if(aStream.end()) return Attribute();\n aStream >> c;\n while(c != '\"') {\n if(aStream.end()) return Attribute();\n name += c;\n aStream >> c;\n }\n return Attribute(name, value);\n }\n\n bool XmlFormat::writeAttribute(const Attribute& aAttribute, OStream& aStream) const throw() {\n aStream << aAttribute.getName() << \"=\\\"\" << aAttribute.getValue() << '\"';\n return true;\n }\n\n Element XmlFormat::readElement(IStream& aStream) const throw() {\n if(! skipWhitespace(aStream)) return Element();\n char c;\n Element element;\n String& name = element.getName();\n String& body = element.getBody();\n List& attributes = element.getAttributes();\n List& elements = element.getElements();\n\n \/\/ Start tag\n {\n \/\/ Open tag\n if(aStream.end()) return Element();\n aStream >> c;\n if(c != '<') return Element();\n\n \/\/ Read name\n if(aStream.end()) return Element();\n aStream >> c;\n\n while(! (std::isspace(c) || c == '\/' || c == '>')) {\n name += c;\n if(aStream.end()) return Element();\n aStream >> c;\n }\n\n \/\/ Close tag\n bool endTag = true;\n while(endTag) {\n while(std::isspace(c)) {\n if(aStream.end()) return Element();\n aStream >> c;\n }\n if(c == '\/') {\n if(aStream.end()) return Element();\n aStream >> c;\n if(c != '>') return Element();\n return element;\n }else if(c == '>') {\n endTag = false;\n }else{\n aStream.setOffset(aStream.getOffset() - 1);\n \/\/ Read attributes\n attributes.pushBack(readAttribute(aStream));\n c = aStream.peek();\n }\n }\n }\n\n \/\/ Body\n {\n bool endBody = true;\n while(endBody){\n while(std::isspace(c)) {\n if(aStream.end()) return Element();\n aStream >> c;\n }\n\n if(c == '<'){\n if(aStream.end()) return Element();\n aStream >> c;\n if(c == '\/'){\n endBody = false;\n aStream.setOffset(aStream.getOffset() - 2);\n }else {\n \/\/ Read Element\n aStream.setOffset(aStream.getOffset() - 2);\n elements.pushBack(readElement(aStream));\n c = aStream.peek();\n }\n }else{\n \/\/ Read body\n body += c;\n if(aStream.end()) return Element();\n aStream >> c;\n }\n }\n\n\n }\n\n \/\/ End tag\n {\n\n \/\/ Open tag\n while(std::isspace(c)) {\n if(aStream.end()) return Element();\n aStream >> c;\n }\n if(aStream.end()) return Element();\n aStream >> c;\n if(c != '<') return Element();\n\n if(aStream.end()) return Element();\n aStream >> c;\n if(c != '\/') return Element();\n\n \/\/ Read name\n while(std::isspace(c)) {\n if(aStream.end()) return Element();\n aStream >> c;\n }\n\n CString endName;\n while(! (std::isspace(c) || c == '>')) {\n endName += c;\n if(aStream.end()) return Element();\n aStream >> c;\n }\n\n if(name != endName) return Element();\n\n \/\/ Close Tag\n while(c != '>') {\n if(aStream.end()) return Element();\n aStream >> c;\n }\n }\n\n return element;\n }\n\n bool XmlFormat::writeElement(const Element& aElement, OStream& aStream) const throw() {\n aStream << '<' << aElement.getName();\n\n const StaticContainer& attributes = aElement.getAttributes();\n if(attributes.size() > 0) {\n aStream << ' ';\n for(const Attribute& i : attributes) {\n writeAttribute(i, aStream);\n aStream << ' ';\n }\n }\n\n const int32_t bodySize = aElement.getBody().size();\n const int32_t elementCount = aElement.getElements().size();\n if(bodySize + elementCount == 0) {\n aStream << \"\/>\";\n }else {\n aStream << '>';\n\n if(bodySize != 0) {\n if(elementCount != 0) return false;\n const StaticContainer& elements = aElement.getElements();\n for(const Element& i : elements) {\n writeElement(i, aStream);\n }\n }else {\n aStream << aElement.getBody();\n }\n\n aStream << \"<\/\";\n aStream << aElement.getName();\n aStream << '>';\n }\n return true;\n }\n\n}\n<|endoftext|>"} {"text":"#include \"common.h\"\n#include \"Freefall.h\"\n#include \n#include \"Polar.h\"\n#include \"JobManager.h\"\n#include \"EventManager.h\"\n#include \"AssetManager.h\"\n#include \"InputManager.h\"\n#include \"Integrator.h\"\n#include \"Tweener.h\"\n#include \"AudioManager.h\"\n#include \"GL32Renderer.h\"\n#include \"World.h\"\n#include \"MenuSystem.h\"\n#include \"TitlePlayerController.h\"\n#include \"HumanPlayerController.h\"\n#include \"BoundingComponent.h\"\n#include \"Text.h\"\n\nvoid Freefall::Run(const std::vector &args) {\n\tconst double secsPerBeat = 1.2631578947368421;\n\tPolar engine;\n\tIDType playerID;\n\n\tsrand((unsigned int)time(0));\n\tstd::mt19937_64 rng(time(0));\n\n\tengine.AddState(\"root\", [] (Polar *engine, EngineState &st) {\n\t\tst.transitions.emplace(\"forward\", Transition{Push(\"world\")});\n\n\t\t\/\/st.AddSystem();\n\t\tst.AddSystem();\n\t\tst.AddSystem();\n\t\tst.AddSystem();\n\t\tst.AddSystem();\n\t\tst.AddSystem>();\n\t\tst.AddSystem();\n\t\tst.AddSystemAs &>({ \"perlin\" });\n\n\t\tauto assetM = engine->GetSystem().lock();\n\t\tassetM->Get(\"nexus\");\n\t\tassetM->Get(\"laser\");\n\t\tassetM->Get(\"beep1\");\n\t\tassetM->Get(\"menu1\");\n\t\tassetM->Get(\"30\");\n\t\tassetM->Get(\"60\");\n\t\tassetM->Get(\"1\");\n\t\tassetM->Get(\"2\");\n\t\tassetM->Get(\"3\");\n\t\tassetM->Get(\"4\");\n\t\tassetM->Get(\"5\");\n\t\tassetM->Get(\"6\");\n\t\tassetM->Get(\"7\");\n\t\tassetM->Get(\"8\");\n\t\tassetM->Get(\"9\");\n\t\tassetM->Get(\"seconds\");\n\t\tassetM->Get(\"hundred\");\n\t\tassetM->Get(\"fifty\");\n\t\tassetM->Get(\"freefall\");\n\n\t\tengine->transition = \"forward\";\n\t});\n\n\tengine.AddState(\"world\", [&rng, &playerID] (Polar *engine, EngineState &st) {\n\t\tst.transitions.emplace(\"forward\", Transition{Push(\"title\")});\n\n\t\tst.AddSystem();\n\n\t\tst.dtors.emplace_back(engine->AddObject(&playerID));\n\n\t\tPoint3 seed = glm::ballRand(Decimal(1000.0));\n\t\tengine->AddComponent(playerID, seed);\n\t\tengine->AddComponent(playerID);\n\n\t\tauto renderer = engine->GetSystem().lock();\n\t\trenderer->SetUniform(\"u_baseThreshold\", Decimal( 0.7));\n\t\trenderer->SetUniform(\"u_beatTicks\", Decimal(1000.0));\n\t\trenderer->SetUniform(\"u_beatPower\", Decimal( 4.0));\n\t\trenderer->SetUniform(\"u_beatStrength\", Decimal( 0.005));\n\t\trenderer->SetUniform(\"u_waveTicks\", Decimal(2345.0));\n\t\trenderer->SetUniform(\"u_wavePower\", Decimal( 8.0));\n\t\trenderer->SetUniform(\"u_waveStrength\", Decimal( 0.02));\n\t\trenderer->SetUniform(\"u_worldScale\", Point3(20.0));\n\n\t\tengine->transition = \"forward\";\n\t});\n\n\tengine.AddState(\"title\", [&playerID] (Polar *engine, EngineState &st) {\n\t\tst.transitions.emplace(\"forward\", Transition{ Pop(), Push(\"playing\") });\n\t\tst.transitions.emplace(\"back\", Transition{ QuitAction() });\n\n\t\tst.AddSystem(playerID);\n\n\t\tauto assetM = engine->GetSystem().lock();\n\t\tauto inputM = engine->GetSystem().lock();\n\t\tauto tweener = engine->GetSystem>().lock();\n\t\tauto renderer = engine->GetSystem().lock();\n\t\tauto audioM = engine->GetSystem().lock();\n\n\t\tMenu menu = {\n\t\t\tMenuItem(\"Solo Play\", [engine] (Decimal) {\n\t\t\t\tengine->transition = \"forward\";\n\t\t\t\treturn false;\n\t\t\t}),\n\t\t\tMenuItem(\"Options\", {\n\t\t\t\tMenuItem(\"Graphics\", {\n\t\t\t\t\tMenuItem(\"Base Detail\", MenuControl::Slider(6, 30, renderer->GetUniformDecimal(\"u_baseDetail\", 10)), [engine] (Decimal x) {\n\t\t\t\t\t\tauto renderer = engine->GetSystem().lock();\n\t\t\t\t\t\trenderer->SetUniform(\"u_baseDetail\", x);\n\t\t\t\t\t\treturn true;\n\t\t\t\t\t}),\n\t\t\t\t\t\/\/MenuItem(\"Far Detail\", MenuControl::Slider(), [] (Decimal) { return true; }),\n\t\t\t\t\t\/\/MenuItem(\"Far Limiter\", MenuControl::Slider(), [] (Decimal) { return true; }),\n\t\t\t\t\t\/\/MenuItem(\"Precision\", MenuControl::Selection({\"Float\", \"Double\"}), [] (Decimal) { return true; }),\n\t\t\t\t\tMenuItem(\"Pixel Factor\", MenuControl::Slider(0, 20, renderer->GetUniformDecimal(\"u_pixelFactor\", 0)), [engine] (Decimal x) {\n\t\t\t\t\t\tauto renderer = engine->GetSystem().lock();\n\t\t\t\t\t\trenderer->SetUniform(\"u_pixelFactor\", x);\n\t\t\t\t\t\treturn true;\n\t\t\t\t\t}),\n\t\t\t\t\tMenuItem(\"Voxel Factor\", MenuControl::Slider(0, 20, renderer->GetUniformDecimal(\"u_voxelFactor\", 0)), [engine] (Decimal x) {\n\t\t\t\t\t\tauto renderer = engine->GetSystem().lock();\n\t\t\t\t\t\trenderer->SetUniform(\"u_voxelFactor\", x);\n\t\t\t\t\t\treturn true;\n\t\t\t\t\t}),\n\t\t\t\t\tMenuItem(\"Show FPS\", MenuControl::Checkbox(renderer->showFPS), [engine] (Decimal state) {\n\t\t\t\t\t\tauto renderer = engine->GetSystem().lock();\n\t\t\t\t\t\trenderer->showFPS = state;\n\t\t\t\t\t\treturn true;\n\t\t\t\t\t}),\n\t\t\t\t}),\n\t\t\t\tMenuItem(\"Audio\", {\n\t\t\t\t\tMenuItem(\"Mute\", MenuControl::Checkbox(audioM->muted), [engine] (Decimal state) {\n\t\t\t\t\t\tauto audioM = engine->GetSystem().lock();\n\t\t\t\t\t\taudioM->muted = state;\n\t\t\t\t\t\treturn true;\n\t\t\t\t\t}),\n\t\t\t\t}),\n\t\t\t\t\/\/MenuItem(\"Controls\", [] (Decimal) { return true; }),\n\t\t\t\tMenuItem(\"World\", {\n\t\t\t\t\tMenuItem(\"u_baseThreshold\", MenuControl::Slider(0, 1, renderer->GetUniformDecimal(\"u_baseThreshold\"), 0.05), [engine] (Decimal x) {\n\t\t\t\t\t\tauto renderer = engine->GetSystem().lock();\n\t\t\t\t\t\trenderer->SetUniform(\"u_baseThreshold\", x);\n\t\t\t\t\t\treturn true;\n\t\t\t\t\t}),\n\t\t\t\t\tMenuItem(\"u_beatTicks\", MenuControl::Slider(50, 10000, renderer->GetUniformDecimal(\"u_beatTicks\"), 50), [engine] (Decimal x) {\n\t\t\t\t\t\tauto renderer = engine->GetSystem().lock();\n\t\t\t\t\t\trenderer->SetUniform(\"u_beatTicks\", x);\n\t\t\t\t\t\treturn true;\n\t\t\t\t\t}),\n\t\t\t\t\tMenuItem(\"u_beatPower\", MenuControl::Slider(1, 16, renderer->GetUniformDecimal(\"u_beatPower\")), [engine] (Decimal x) {\n\t\t\t\t\t\tauto renderer = engine->GetSystem().lock();\n\t\t\t\t\t\trenderer->SetUniform(\"u_beatPower\", x);\n\t\t\t\t\t\treturn true;\n\t\t\t\t\t}),\n\t\t\t\t\tMenuItem(\"u_beatStrength\", MenuControl::Slider(-1, 1, renderer->GetUniformDecimal(\"u_beatStrength\"), 0.002), [engine] (Decimal x) {\n\t\t\t\t\t\tauto renderer = engine->GetSystem().lock();\n\t\t\t\t\t\trenderer->SetUniform(\"u_beatStrength\", x);\n\t\t\t\t\t\treturn true;\n\t\t\t\t\t}),\n\t\t\t\t\tMenuItem(\"u_waveTicks\", MenuControl::Slider(50, 10000, renderer->GetUniformDecimal(\"u_waveTicks\"), 50), [engine] (Decimal x) {\n\t\t\t\t\t\tauto renderer = engine->GetSystem().lock();\n\t\t\t\t\t\trenderer->SetUniform(\"u_waveTicks\", x);\n\t\t\t\t\t\treturn true;\n\t\t\t\t\t}),\n\t\t\t\t\tMenuItem(\"u_wavePower\", MenuControl::Slider(1, 16, renderer->GetUniformDecimal(\"u_wavePower\")), [engine] (Decimal x) {\n\t\t\t\t\t\tauto renderer = engine->GetSystem().lock();\n\t\t\t\t\t\trenderer->SetUniform(\"u_wavePower\", x);\n\t\t\t\t\t\treturn true;\n\t\t\t\t\t}),\n\t\t\t\t\tMenuItem(\"u_waveStrength\", MenuControl::Slider(-1, 1, renderer->GetUniformDecimal(\"u_waveStrength\"), 0.002), [engine] (Decimal x) {\n\t\t\t\t\t\tauto renderer = engine->GetSystem().lock();\n\t\t\t\t\t\trenderer->SetUniform(\"u_waveStrength\", x);\n\t\t\t\t\t\treturn true;\n\t\t\t\t\t}),\n\t\t\t\t\tMenuItem(\"u_worldScale.x\", MenuControl::Slider(1, 100, renderer->GetUniformPoint3(\"u_worldScale\").x, 0.5), [engine] (Decimal x) {\n\t\t\t\t\t\tauto renderer = engine->GetSystem().lock();\n\t\t\t\t\t\tauto p = renderer->GetUniformPoint3(\"u_worldScale\");\n\t\t\t\t\t\tp.x = x;\n\t\t\t\t\t\trenderer->SetUniform(\"u_worldScale\", p);\n\t\t\t\t\t\treturn true;\n\t\t\t\t\t}),\n\t\t\t\t\tMenuItem(\"u_worldScale.y\", MenuControl::Slider(1, 100, renderer->GetUniformPoint3(\"u_worldScale\").y, 0.5), [engine] (Decimal y) {\n\t\t\t\t\t\tauto renderer = engine->GetSystem().lock();\n\t\t\t\t\t\tauto p = renderer->GetUniformPoint3(\"u_worldScale\");\n\t\t\t\t\t\tp.y = y;\n\t\t\t\t\t\trenderer->SetUniform(\"u_worldScale\", p);\n\t\t\t\t\t\treturn true;\n\t\t\t\t\t}),\n\t\t\t\t\tMenuItem(\"u_worldScale.z\", MenuControl::Slider(1, 100, renderer->GetUniformPoint3(\"u_worldScale\").z, 0.5), [engine] (Decimal z) {\n\t\t\t\t\t\tauto renderer = engine->GetSystem().lock();\n\t\t\t\t\t\tauto p = renderer->GetUniformPoint3(\"u_worldScale\");\n\t\t\t\t\t\tp.z = z;\n\t\t\t\t\t\trenderer->SetUniform(\"u_worldScale\", p);\n\t\t\t\t\t\treturn true;\n\t\t\t\t\t}),\n\t\t\t\t}),\n\t\t\t}),\n\t\t\tMenuItem(\"Quit Game\", [engine] (Decimal) {\n\t\t\t\tengine->Quit();\n\t\t\t\treturn false;\n\t\t\t}),\n\t\t};\n\t\tst.AddSystem(menu);\n\n\t\tIDType laserID;\n\t\tst.dtors.emplace_back(engine->AddObject(&laserID));\n\t\tengine->AddComponent(laserID, assetM->Get(\"laser\"), true);\n\n\t\tst.dtors.emplace_back(tweener->Tween(0.5f, 1.0f, 1.0, true, [] (Polar *engine, const float &x) {\n\t\t\tauto renderer = engine->GetSystem().lock();\n\t\t\tauto color = renderer->GetUniformPoint3(\"u_color\");\n\t\t\tcolor.r = x;\n\t\t\trenderer->SetUniform(\"u_color\", color);\n\t\t}, 5.0 * 4 - 1.0, renderer->GetUniformPoint3(\"u_color\").r));\n\t\tst.dtors.emplace_back(tweener->Tween(0.5f, 1.0f, 0.5, true, [] (Polar *engine, const float &x) {\n\t\t\tauto renderer = engine->GetSystem().lock();\n\t\t\tauto color = renderer->GetUniformPoint3(\"u_color\");\n\t\t\tcolor.g = x;\n\t\t\trenderer->SetUniform(\"u_color\", color);\n\t\t}, 5.0 * 2 - 1.0, renderer->GetUniformPoint3(\"u_color\").g));\n\t\tst.dtors.emplace_back(tweener->Tween(0.5f, 1.0f, 0.5, true, [] (Polar *engine, const float &x) {\n\t\t\tauto renderer = engine->GetSystem().lock();\n\t\t\tauto color = renderer->GetUniformPoint3(\"u_color\");\n\t\t\tcolor.b = x;\n\t\t\trenderer->SetUniform(\"u_color\", color);\n\t\t}, 5.0 - 1.0, renderer->GetUniformPoint3(\"u_color\").b));\n\t});\n\n\tengine.AddState(\"playing\", [secsPerBeat, &playerID] (Polar *engine, EngineState &st) {\n\t\tst.transitions.emplace(\"back\", Transition{Pop(), Pop(), Push(\"world\")});\n\n\t\tst.AddSystem(playerID);\n\n\t\tauto assetM = engine->GetSystem().lock();\n\t\tauto inputM = engine->GetSystem().lock();\n\t\tauto tweener = engine->GetSystem>().lock();\n\t\tauto renderer = engine->GetSystem().lock();\n\n\t\tst.dtors.emplace_back(inputM->On(Key::Escape, [engine] (Key) { engine->transition = \"back\"; }));\n\t\tst.dtors.emplace_back(inputM->On(Key::ControllerBack, [engine] (Key) { engine->transition = \"back\"; }));\n\n\t\tIDType beepID;\n\t\tst.dtors.emplace_back(engine->AddObject(&beepID));\n\t\tengine->AddComponent(beepID, assetM->Get(\"begin\"));\n\n\t\tIDType musicID;\n\t\tst.dtors.emplace_back(engine->AddObject(&musicID));\n\t\tengine->AddComponent(musicID, assetM->Get(\"nexus\"), LoopIn{3565397});\n\n\t\tst.dtors.emplace_back(tweener->Tween(0.5f, 1.0f, 0.5, true, [] (Polar *engine, const float &x) {\n\t\t\tauto renderer = engine->GetSystem().lock();\n\t\t\tauto color = renderer->GetUniformPoint3(\"u_color\");\n\t\t\tcolor.r = x;\n\t\t\trenderer->SetUniform(\"u_color\", color);\n\t\t}, secsPerBeat * 4 - 0.5, renderer->GetUniformPoint3(\"u_color\").r));\n\t\tst.dtors.emplace_back(tweener->Tween(0.5f, 1.0f, 0.5, true, [] (Polar *engine, const float &x) {\n\t\t\tauto renderer = engine->GetSystem().lock();\n\t\t\tauto color = renderer->GetUniformPoint3(\"u_color\");\n\t\t\tcolor.g = x;\n\t\t\trenderer->SetUniform(\"u_color\", color);\n\t\t}, secsPerBeat * 2 - 0.5, renderer->GetUniformPoint3(\"u_color\").g));\n\t\tst.dtors.emplace_back(tweener->Tween(0.5f, 1.0f, 0.5, true, [] (Polar *engine, const float &x) {\n\t\t\tauto renderer = engine->GetSystem().lock();\n\t\t\tauto color = renderer->GetUniformPoint3(\"u_color\");\n\t\t\tcolor.b = x;\n\t\t\trenderer->SetUniform(\"u_color\", color);\n\t\t}, secsPerBeat - 0.5, renderer->GetUniformPoint3(\"u_color\").b));\n\t});\n\n\tengine.Run(\"root\");\n}\nIncrease max base detail to 40#include \"common.h\"\n#include \"Freefall.h\"\n#include \n#include \"Polar.h\"\n#include \"JobManager.h\"\n#include \"EventManager.h\"\n#include \"AssetManager.h\"\n#include \"InputManager.h\"\n#include \"Integrator.h\"\n#include \"Tweener.h\"\n#include \"AudioManager.h\"\n#include \"GL32Renderer.h\"\n#include \"World.h\"\n#include \"MenuSystem.h\"\n#include \"TitlePlayerController.h\"\n#include \"HumanPlayerController.h\"\n#include \"BoundingComponent.h\"\n#include \"Text.h\"\n\nvoid Freefall::Run(const std::vector &args) {\n\tconst double secsPerBeat = 1.2631578947368421;\n\tPolar engine;\n\tIDType playerID;\n\n\tsrand((unsigned int)time(0));\n\tstd::mt19937_64 rng(time(0));\n\n\tengine.AddState(\"root\", [] (Polar *engine, EngineState &st) {\n\t\tst.transitions.emplace(\"forward\", Transition{Push(\"world\")});\n\n\t\t\/\/st.AddSystem();\n\t\tst.AddSystem();\n\t\tst.AddSystem();\n\t\tst.AddSystem();\n\t\tst.AddSystem();\n\t\tst.AddSystem>();\n\t\tst.AddSystem();\n\t\tst.AddSystemAs &>({ \"perlin\" });\n\n\t\tauto assetM = engine->GetSystem().lock();\n\t\tassetM->Get(\"nexus\");\n\t\tassetM->Get(\"laser\");\n\t\tassetM->Get(\"beep1\");\n\t\tassetM->Get(\"menu1\");\n\t\tassetM->Get(\"30\");\n\t\tassetM->Get(\"60\");\n\t\tassetM->Get(\"1\");\n\t\tassetM->Get(\"2\");\n\t\tassetM->Get(\"3\");\n\t\tassetM->Get(\"4\");\n\t\tassetM->Get(\"5\");\n\t\tassetM->Get(\"6\");\n\t\tassetM->Get(\"7\");\n\t\tassetM->Get(\"8\");\n\t\tassetM->Get(\"9\");\n\t\tassetM->Get(\"seconds\");\n\t\tassetM->Get(\"hundred\");\n\t\tassetM->Get(\"fifty\");\n\t\tassetM->Get(\"freefall\");\n\n\t\tengine->transition = \"forward\";\n\t});\n\n\tengine.AddState(\"world\", [&rng, &playerID] (Polar *engine, EngineState &st) {\n\t\tst.transitions.emplace(\"forward\", Transition{Push(\"title\")});\n\n\t\tst.AddSystem();\n\n\t\tst.dtors.emplace_back(engine->AddObject(&playerID));\n\n\t\tPoint3 seed = glm::ballRand(Decimal(1000.0));\n\t\tengine->AddComponent(playerID, seed);\n\t\tengine->AddComponent(playerID);\n\n\t\tauto renderer = engine->GetSystem().lock();\n\t\trenderer->SetUniform(\"u_baseThreshold\", Decimal( 0.7));\n\t\trenderer->SetUniform(\"u_beatTicks\", Decimal(1000.0));\n\t\trenderer->SetUniform(\"u_beatPower\", Decimal( 4.0));\n\t\trenderer->SetUniform(\"u_beatStrength\", Decimal( 0.005));\n\t\trenderer->SetUniform(\"u_waveTicks\", Decimal(2345.0));\n\t\trenderer->SetUniform(\"u_wavePower\", Decimal( 8.0));\n\t\trenderer->SetUniform(\"u_waveStrength\", Decimal( 0.02));\n\t\trenderer->SetUniform(\"u_worldScale\", Point3(20.0));\n\n\t\tengine->transition = \"forward\";\n\t});\n\n\tengine.AddState(\"title\", [&playerID] (Polar *engine, EngineState &st) {\n\t\tst.transitions.emplace(\"forward\", Transition{ Pop(), Push(\"playing\") });\n\t\tst.transitions.emplace(\"back\", Transition{ QuitAction() });\n\n\t\tst.AddSystem(playerID);\n\n\t\tauto assetM = engine->GetSystem().lock();\n\t\tauto inputM = engine->GetSystem().lock();\n\t\tauto tweener = engine->GetSystem>().lock();\n\t\tauto renderer = engine->GetSystem().lock();\n\t\tauto audioM = engine->GetSystem().lock();\n\n\t\tMenu menu = {\n\t\t\tMenuItem(\"Solo Play\", [engine] (Decimal) {\n\t\t\t\tengine->transition = \"forward\";\n\t\t\t\treturn false;\n\t\t\t}),\n\t\t\tMenuItem(\"Options\", {\n\t\t\t\tMenuItem(\"Graphics\", {\n\t\t\t\t\tMenuItem(\"Base Detail\", MenuControl::Slider(6, 40, renderer->GetUniformDecimal(\"u_baseDetail\", 10)), [engine] (Decimal x) {\n\t\t\t\t\t\tauto renderer = engine->GetSystem().lock();\n\t\t\t\t\t\trenderer->SetUniform(\"u_baseDetail\", x);\n\t\t\t\t\t\treturn true;\n\t\t\t\t\t}),\n\t\t\t\t\t\/\/MenuItem(\"Far Detail\", MenuControl::Slider(), [] (Decimal) { return true; }),\n\t\t\t\t\t\/\/MenuItem(\"Far Limiter\", MenuControl::Slider(), [] (Decimal) { return true; }),\n\t\t\t\t\t\/\/MenuItem(\"Precision\", MenuControl::Selection({\"Float\", \"Double\"}), [] (Decimal) { return true; }),\n\t\t\t\t\tMenuItem(\"Pixel Factor\", MenuControl::Slider(0, 20, renderer->GetUniformDecimal(\"u_pixelFactor\", 0)), [engine] (Decimal x) {\n\t\t\t\t\t\tauto renderer = engine->GetSystem().lock();\n\t\t\t\t\t\trenderer->SetUniform(\"u_pixelFactor\", x);\n\t\t\t\t\t\treturn true;\n\t\t\t\t\t}),\n\t\t\t\t\tMenuItem(\"Voxel Factor\", MenuControl::Slider(0, 20, renderer->GetUniformDecimal(\"u_voxelFactor\", 0)), [engine] (Decimal x) {\n\t\t\t\t\t\tauto renderer = engine->GetSystem().lock();\n\t\t\t\t\t\trenderer->SetUniform(\"u_voxelFactor\", x);\n\t\t\t\t\t\treturn true;\n\t\t\t\t\t}),\n\t\t\t\t\tMenuItem(\"Show FPS\", MenuControl::Checkbox(renderer->showFPS), [engine] (Decimal state) {\n\t\t\t\t\t\tauto renderer = engine->GetSystem().lock();\n\t\t\t\t\t\trenderer->showFPS = state;\n\t\t\t\t\t\treturn true;\n\t\t\t\t\t}),\n\t\t\t\t}),\n\t\t\t\tMenuItem(\"Audio\", {\n\t\t\t\t\tMenuItem(\"Mute\", MenuControl::Checkbox(audioM->muted), [engine] (Decimal state) {\n\t\t\t\t\t\tauto audioM = engine->GetSystem().lock();\n\t\t\t\t\t\taudioM->muted = state;\n\t\t\t\t\t\treturn true;\n\t\t\t\t\t}),\n\t\t\t\t}),\n\t\t\t\t\/\/MenuItem(\"Controls\", [] (Decimal) { return true; }),\n\t\t\t\tMenuItem(\"World\", {\n\t\t\t\t\tMenuItem(\"u_baseThreshold\", MenuControl::Slider(0, 1, renderer->GetUniformDecimal(\"u_baseThreshold\"), 0.05), [engine] (Decimal x) {\n\t\t\t\t\t\tauto renderer = engine->GetSystem().lock();\n\t\t\t\t\t\trenderer->SetUniform(\"u_baseThreshold\", x);\n\t\t\t\t\t\treturn true;\n\t\t\t\t\t}),\n\t\t\t\t\tMenuItem(\"u_beatTicks\", MenuControl::Slider(50, 10000, renderer->GetUniformDecimal(\"u_beatTicks\"), 50), [engine] (Decimal x) {\n\t\t\t\t\t\tauto renderer = engine->GetSystem().lock();\n\t\t\t\t\t\trenderer->SetUniform(\"u_beatTicks\", x);\n\t\t\t\t\t\treturn true;\n\t\t\t\t\t}),\n\t\t\t\t\tMenuItem(\"u_beatPower\", MenuControl::Slider(1, 16, renderer->GetUniformDecimal(\"u_beatPower\")), [engine] (Decimal x) {\n\t\t\t\t\t\tauto renderer = engine->GetSystem().lock();\n\t\t\t\t\t\trenderer->SetUniform(\"u_beatPower\", x);\n\t\t\t\t\t\treturn true;\n\t\t\t\t\t}),\n\t\t\t\t\tMenuItem(\"u_beatStrength\", MenuControl::Slider(-1, 1, renderer->GetUniformDecimal(\"u_beatStrength\"), 0.002), [engine] (Decimal x) {\n\t\t\t\t\t\tauto renderer = engine->GetSystem().lock();\n\t\t\t\t\t\trenderer->SetUniform(\"u_beatStrength\", x);\n\t\t\t\t\t\treturn true;\n\t\t\t\t\t}),\n\t\t\t\t\tMenuItem(\"u_waveTicks\", MenuControl::Slider(50, 10000, renderer->GetUniformDecimal(\"u_waveTicks\"), 50), [engine] (Decimal x) {\n\t\t\t\t\t\tauto renderer = engine->GetSystem().lock();\n\t\t\t\t\t\trenderer->SetUniform(\"u_waveTicks\", x);\n\t\t\t\t\t\treturn true;\n\t\t\t\t\t}),\n\t\t\t\t\tMenuItem(\"u_wavePower\", MenuControl::Slider(1, 16, renderer->GetUniformDecimal(\"u_wavePower\")), [engine] (Decimal x) {\n\t\t\t\t\t\tauto renderer = engine->GetSystem().lock();\n\t\t\t\t\t\trenderer->SetUniform(\"u_wavePower\", x);\n\t\t\t\t\t\treturn true;\n\t\t\t\t\t}),\n\t\t\t\t\tMenuItem(\"u_waveStrength\", MenuControl::Slider(-1, 1, renderer->GetUniformDecimal(\"u_waveStrength\"), 0.002), [engine] (Decimal x) {\n\t\t\t\t\t\tauto renderer = engine->GetSystem().lock();\n\t\t\t\t\t\trenderer->SetUniform(\"u_waveStrength\", x);\n\t\t\t\t\t\treturn true;\n\t\t\t\t\t}),\n\t\t\t\t\tMenuItem(\"u_worldScale.x\", MenuControl::Slider(1, 100, renderer->GetUniformPoint3(\"u_worldScale\").x, 0.5), [engine] (Decimal x) {\n\t\t\t\t\t\tauto renderer = engine->GetSystem().lock();\n\t\t\t\t\t\tauto p = renderer->GetUniformPoint3(\"u_worldScale\");\n\t\t\t\t\t\tp.x = x;\n\t\t\t\t\t\trenderer->SetUniform(\"u_worldScale\", p);\n\t\t\t\t\t\treturn true;\n\t\t\t\t\t}),\n\t\t\t\t\tMenuItem(\"u_worldScale.y\", MenuControl::Slider(1, 100, renderer->GetUniformPoint3(\"u_worldScale\").y, 0.5), [engine] (Decimal y) {\n\t\t\t\t\t\tauto renderer = engine->GetSystem().lock();\n\t\t\t\t\t\tauto p = renderer->GetUniformPoint3(\"u_worldScale\");\n\t\t\t\t\t\tp.y = y;\n\t\t\t\t\t\trenderer->SetUniform(\"u_worldScale\", p);\n\t\t\t\t\t\treturn true;\n\t\t\t\t\t}),\n\t\t\t\t\tMenuItem(\"u_worldScale.z\", MenuControl::Slider(1, 100, renderer->GetUniformPoint3(\"u_worldScale\").z, 0.5), [engine] (Decimal z) {\n\t\t\t\t\t\tauto renderer = engine->GetSystem().lock();\n\t\t\t\t\t\tauto p = renderer->GetUniformPoint3(\"u_worldScale\");\n\t\t\t\t\t\tp.z = z;\n\t\t\t\t\t\trenderer->SetUniform(\"u_worldScale\", p);\n\t\t\t\t\t\treturn true;\n\t\t\t\t\t}),\n\t\t\t\t}),\n\t\t\t}),\n\t\t\tMenuItem(\"Quit Game\", [engine] (Decimal) {\n\t\t\t\tengine->Quit();\n\t\t\t\treturn false;\n\t\t\t}),\n\t\t};\n\t\tst.AddSystem(menu);\n\n\t\tIDType laserID;\n\t\tst.dtors.emplace_back(engine->AddObject(&laserID));\n\t\tengine->AddComponent(laserID, assetM->Get(\"laser\"), true);\n\n\t\tst.dtors.emplace_back(tweener->Tween(0.5f, 1.0f, 1.0, true, [] (Polar *engine, const float &x) {\n\t\t\tauto renderer = engine->GetSystem().lock();\n\t\t\tauto color = renderer->GetUniformPoint3(\"u_color\");\n\t\t\tcolor.r = x;\n\t\t\trenderer->SetUniform(\"u_color\", color);\n\t\t}, 5.0 * 4 - 1.0, renderer->GetUniformPoint3(\"u_color\").r));\n\t\tst.dtors.emplace_back(tweener->Tween(0.5f, 1.0f, 0.5, true, [] (Polar *engine, const float &x) {\n\t\t\tauto renderer = engine->GetSystem().lock();\n\t\t\tauto color = renderer->GetUniformPoint3(\"u_color\");\n\t\t\tcolor.g = x;\n\t\t\trenderer->SetUniform(\"u_color\", color);\n\t\t}, 5.0 * 2 - 1.0, renderer->GetUniformPoint3(\"u_color\").g));\n\t\tst.dtors.emplace_back(tweener->Tween(0.5f, 1.0f, 0.5, true, [] (Polar *engine, const float &x) {\n\t\t\tauto renderer = engine->GetSystem().lock();\n\t\t\tauto color = renderer->GetUniformPoint3(\"u_color\");\n\t\t\tcolor.b = x;\n\t\t\trenderer->SetUniform(\"u_color\", color);\n\t\t}, 5.0 - 1.0, renderer->GetUniformPoint3(\"u_color\").b));\n\t});\n\n\tengine.AddState(\"playing\", [secsPerBeat, &playerID] (Polar *engine, EngineState &st) {\n\t\tst.transitions.emplace(\"back\", Transition{Pop(), Pop(), Push(\"world\")});\n\n\t\tst.AddSystem(playerID);\n\n\t\tauto assetM = engine->GetSystem().lock();\n\t\tauto inputM = engine->GetSystem().lock();\n\t\tauto tweener = engine->GetSystem>().lock();\n\t\tauto renderer = engine->GetSystem().lock();\n\n\t\tst.dtors.emplace_back(inputM->On(Key::Escape, [engine] (Key) { engine->transition = \"back\"; }));\n\t\tst.dtors.emplace_back(inputM->On(Key::ControllerBack, [engine] (Key) { engine->transition = \"back\"; }));\n\n\t\tIDType beepID;\n\t\tst.dtors.emplace_back(engine->AddObject(&beepID));\n\t\tengine->AddComponent(beepID, assetM->Get(\"begin\"));\n\n\t\tIDType musicID;\n\t\tst.dtors.emplace_back(engine->AddObject(&musicID));\n\t\tengine->AddComponent(musicID, assetM->Get(\"nexus\"), LoopIn{3565397});\n\n\t\tst.dtors.emplace_back(tweener->Tween(0.5f, 1.0f, 0.5, true, [] (Polar *engine, const float &x) {\n\t\t\tauto renderer = engine->GetSystem().lock();\n\t\t\tauto color = renderer->GetUniformPoint3(\"u_color\");\n\t\t\tcolor.r = x;\n\t\t\trenderer->SetUniform(\"u_color\", color);\n\t\t}, secsPerBeat * 4 - 0.5, renderer->GetUniformPoint3(\"u_color\").r));\n\t\tst.dtors.emplace_back(tweener->Tween(0.5f, 1.0f, 0.5, true, [] (Polar *engine, const float &x) {\n\t\t\tauto renderer = engine->GetSystem().lock();\n\t\t\tauto color = renderer->GetUniformPoint3(\"u_color\");\n\t\t\tcolor.g = x;\n\t\t\trenderer->SetUniform(\"u_color\", color);\n\t\t}, secsPerBeat * 2 - 0.5, renderer->GetUniformPoint3(\"u_color\").g));\n\t\tst.dtors.emplace_back(tweener->Tween(0.5f, 1.0f, 0.5, true, [] (Polar *engine, const float &x) {\n\t\t\tauto renderer = engine->GetSystem().lock();\n\t\t\tauto color = renderer->GetUniformPoint3(\"u_color\");\n\t\t\tcolor.b = x;\n\t\t\trenderer->SetUniform(\"u_color\", color);\n\t\t}, secsPerBeat - 0.5, renderer->GetUniformPoint3(\"u_color\").b));\n\t});\n\n\tengine.Run(\"root\");\n}\n<|endoftext|>"} {"text":"\/* +------------------------------------------------------------------------+\n | Mobile Robot Programming Toolkit (MRPT) |\n | http:\/\/www.mrpt.org\/ |\n | |\n | Copyright (c) 2005-2018, Individual contributors, see AUTHORS file |\n | See: http:\/\/www.mrpt.org\/Authors - All rights reserved. |\n | Released under BSD License. See details in http:\/\/www.mrpt.org\/License |\n +------------------------------------------------------------------------+ *\/\n\n#include \"gui-precomp.h\" \/\/ Precompiled headers\n\n#if MRPT_HAS_WXWIDGETS\n\n#include \"CAboutBox_wx.h\"\n\n\/\/(*InternalHeaders(CAboutBox)\n#include \n#include \n#include \n#include \n#include \n#include \n\/\/*)\n\n#include \n#include \/\/ _U()\n\n\/\/ For CV_VERSION\n#include \n\n#include \n\nusing namespace mrpt;\nusing namespace mrpt::system;\nusing namespace std;\n\n\/\/(*IdInit(CAboutBox)\nconst long CAboutBox::ID_STATICTEXT1 = wxNewId();\nconst long CAboutBox::ID_STATICTEXT2 = wxNewId();\nconst long CAboutBox::ID_STATICBITMAP1 = wxNewId();\nconst long CAboutBox::ID_STATICLINE1 = wxNewId();\nconst long CAboutBox::ID_TEXTCTRL1 = wxNewId();\nconst long CAboutBox::ID_TEXTCTRL2 = wxNewId();\nconst long CAboutBox::ID_TEXTCTRL3 = wxNewId();\nconst long CAboutBox::ID_NOTEBOOK1 = wxNewId();\nconst long CAboutBox::ID_BUTTON1 = wxNewId();\n\/\/*)\n\nBEGIN_EVENT_TABLE(CAboutBox, wxDialog)\n\/\/(*EventTable(CAboutBox)\n\/\/*)\nEND_EVENT_TABLE()\n\nCAboutBox::CAboutBox(\n\twxWindow* parent, const std::string& appName,\n\tconst std::string& additionalInfo, const bool showStandardInfo)\n\t: CAboutBoxBase(appName, additionalInfo, showStandardInfo)\n{\n\tconst wxWindowID id = -1;\n\t\/\/(*Initialize(CAboutBox)\n\twxFlexGridSizer* FlexGridSizer2;\n\n\tCreate(\n\t\tparent, id, _(\"About box...\"), wxDefaultPosition, wxDefaultSize,\n\t\twxDEFAULT_DIALOG_STYLE | wxCLOSE_BOX, _T(\"id\"));\n\tSetClientSize(wxSize(636, 375));\n\tFlexGridSizer1 = new wxFlexGridSizer(0, 1, 0, 0);\n\tFlexGridSizer1->AddGrowableCol(0);\n\tFlexGridSizer4 = new wxFlexGridSizer(0, 2, 0, 0);\n\tFlexGridSizer4->AddGrowableCol(1);\n\tFlexGridSizer4->AddGrowableRow(0);\n\tFlexGridSizer2 = new wxFlexGridSizer(2, 1, 0, 0);\n\tFlexGridSizer2->AddGrowableCol(0);\n\tFlexGridSizer2->AddGrowableRow(0);\n\tFlexGridSizer2->AddGrowableRow(1);\n\tlbProgName = new wxStaticText(\n\t\tthis, ID_STATICTEXT1, _(\"Title\"), wxDefaultPosition, wxDefaultSize, 0,\n\t\t_T(\"ID_STATICTEXT1\"));\n\twxFont lbProgNameFont(\n\t\t22, wxSWISS, wxFONTSTYLE_NORMAL, wxFONTWEIGHT_BOLD, false,\n\t\t_T(\"Times New Roman\"), wxFONTENCODING_DEFAULT);\n\tlbProgName->SetFont(lbProgNameFont);\n\tFlexGridSizer2->Add(\n\t\tlbProgName, 1, wxALL | wxALIGN_BOTTOM | wxALIGN_CENTER_HORIZONTAL, 5);\n\tlbBuild = new wxStaticText(\n\t\tthis, ID_STATICTEXT2, _(\"Label\"), wxDefaultPosition, wxDefaultSize, 0,\n\t\t_T(\"ID_STATICTEXT2\"));\n\tFlexGridSizer2->Add(\n\t\tlbBuild, 1, wxALL | wxALIGN_TOP | wxALIGN_CENTER_HORIZONTAL, 5);\n\tFlexGridSizer4->Add(\n\t\tFlexGridSizer2, 1, wxALL | wxEXPAND | wxALIGN_LEFT | wxALIGN_TOP, 0);\n\tStaticBitmap1 = new wxStaticBitmap(\n\t\tthis, ID_STATICBITMAP1,\n\t\twxArtProvider::GetBitmap(\n\t\t\twxART_MAKE_ART_ID_FROM_STR(_T(\"IMG_MRPT_LOGO\")), wxART_OTHER),\n\t\twxDefaultPosition, wxDefaultSize, 0, _T(\"ID_STATICBITMAP1\"));\n\tFlexGridSizer4->Add(\n\t\tStaticBitmap1, 1,\n\t\twxALL | wxALIGN_CENTER_HORIZONTAL | wxALIGN_CENTER_VERTICAL, 5);\n\tFlexGridSizer1->Add(\n\t\tFlexGridSizer4, 1, wxALL | wxEXPAND | wxALIGN_LEFT | wxALIGN_TOP, 1);\n\tStaticLine1 = new wxStaticLine(\n\t\tthis, ID_STATICLINE1, wxPoint(3, 86), wxSize(627, 2), wxLI_HORIZONTAL,\n\t\t_T(\"ID_STATICLINE1\"));\n\tFlexGridSizer1->Add(\n\t\tStaticLine1, 1, wxALL | wxEXPAND | wxALIGN_LEFT | wxALIGN_TOP, 5);\n\tNotebook1 = new wxNotebook(\n\t\tthis, ID_NOTEBOOK1, wxPoint(6, 91), wxSize(625, 250), 0,\n\t\t_T(\"ID_NOTEBOOK1\"));\n\tlbInfo = new wxTextCtrl(\n\t\tNotebook1, ID_TEXTCTRL1, wxEmptyString, wxPoint(4, 24),\n\t\twxSize(545, 250), wxTE_MULTILINE | wxTE_READONLY | wxTE_AUTO_URL,\n\t\twxDefaultValidator, _T(\"ID_TEXTCTRL1\"));\n\twxFont lbInfoFont(\n\t\t10, wxSWISS, wxFONTSTYLE_NORMAL, wxNORMAL, false, _T(\"Courier New\"),\n\t\twxFONTENCODING_DEFAULT);\n\tlbInfo->SetFont(lbInfoFont);\n\tlbLicense = new wxTextCtrl(\n\t\tNotebook1, ID_TEXTCTRL2, _(\"\"), wxDefaultPosition, wxDefaultSize,\n\t\twxTE_MULTILINE | wxTE_READONLY | wxTE_AUTO_URL, wxDefaultValidator,\n\t\t_T(\"ID_TEXTCTRL2\"));\n\twxFont lbLicenseFont(\n\t\t10, wxSWISS, wxFONTSTYLE_NORMAL, wxNORMAL, false, _T(\"Courier New\"),\n\t\twxFONTENCODING_DEFAULT);\n\tlbLicense->SetFont(lbLicenseFont);\n\tTextCtrl1 = new wxTextCtrl(\n\t\tNotebook1, ID_TEXTCTRL3, _U(tutorial().c_str()), wxPoint(4, 24),\n\t\twxSize(545, 222), wxTE_MULTILINE | wxTE_READONLY | wxTE_AUTO_URL,\n\t\twxDefaultValidator, _T(\"ID_TEXTCTRL3\"));\n\twxFont TextCtrl1Font(\n\t\t10, wxSWISS, wxFONTSTYLE_NORMAL, wxNORMAL, false, _T(\"Courier New\"),\n\t\twxFONTENCODING_DEFAULT);\n\tTextCtrl1->SetFont(TextCtrl1Font);\n\tNotebook1->AddPage(lbInfo, _(\"Information\"), false);\n\tNotebook1->AddPage(lbLicense, _(\"License\"), false);\n\tNotebook1->AddPage(TextCtrl1, _(\"Tutorial\"), false);\n\tFlexGridSizer1->Add(\n\t\tNotebook1, 1, wxALL | wxEXPAND | wxALIGN_LEFT | wxALIGN_TOP, 5);\n\tButton11 = new wxButton(\n\t\tthis, ID_BUTTON1, _(\"OK\"), wxPoint(250, 345), wxSize(76, 26), 0,\n\t\twxDefaultValidator, _T(\"ID_BUTTON1\"));\n\tFlexGridSizer1->Add(\n\t\tButton11, 1,\n\t\twxALL | wxALIGN_CENTER_HORIZONTAL | wxALIGN_CENTER_VERTICAL, 5);\n\tSetSizer(FlexGridSizer1);\n\tFlexGridSizer1->SetSizeHints(this);\n\tCenter();\n\n\tConnect(\n\t\tID_BUTTON1, wxEVT_COMMAND_BUTTON_CLICKED,\n\t\t(wxObjectEventFunction)&CAboutBox::OnButton1Click);\n\tConnect(\n\t\twxID_ANY, wxEVT_INIT_DIALOG, (wxObjectEventFunction)&CAboutBox::OnInit);\n\t\/\/*)\n\n\tlbLicense->SetValue(_U(license().c_str()));\n}\n\nCAboutBox::~CAboutBox()\n{\n\t\/\/(*Destroy(CAboutBox)\n\t\/\/*)\n}\n\nvoid CAboutBox::OnInit(wxInitDialogEvent& event)\n{\n\t\/\/ Build strings:\n\twxString MRPTver(MRPT_getVersion().c_str(), wxConvLibc);\n\n\t\/\/ Set the label with MRPT version:\n\twxString s(_(\"Build: \"));\n\ts << _U(mrpt::system::MRPT_getCompilationDate().c_str());\n\ts << _(\" - \") << MRPTver;\n\n\tlbBuild->SetLabel(s);\n\n\t\/\/ Info:\n\tlbInfo->Clear();\n\n\t{\n\t\tCMyRedirector myRedirector(lbInfo);\n\t\twxString wxVer(wxVERSION_STRING);\n\t\tcout << information(\"wxWidgets\", std::string(wxVer.mb_str()));\n\t}\n\n\tlbProgName->SetLabel(_U(m_appName.c_str()));\n\tlbProgName->SetForegroundColour(wxColour(0, 0, 128));\n\n\tFlexGridSizer1->RecalcSizes();\n\tthis->Fit();\n}\n\nvoid CAboutBox::OnButton1Click(wxCommandEvent& event) { Close(); }\n#endif \/\/ MRPT_HAS_WXWIDGETS\ndeprecated wx3 constants\/* +------------------------------------------------------------------------+\n | Mobile Robot Programming Toolkit (MRPT) |\n | http:\/\/www.mrpt.org\/ |\n | |\n | Copyright (c) 2005-2018, Individual contributors, see AUTHORS file |\n | See: http:\/\/www.mrpt.org\/Authors - All rights reserved. |\n | Released under BSD License. See details in http:\/\/www.mrpt.org\/License |\n +------------------------------------------------------------------------+ *\/\n\n#include \"gui-precomp.h\" \/\/ Precompiled headers\n\n#if MRPT_HAS_WXWIDGETS\n\n#include \"CAboutBox_wx.h\"\n\n\/\/(*InternalHeaders(CAboutBox)\n#include \n#include \n#include \n#include \n#include \n#include \n\/\/*)\n\n#include \n#include \/\/ _U()\n\n\/\/ For CV_VERSION\n#include \n\n#include \n\nusing namespace mrpt;\nusing namespace mrpt::system;\nusing namespace std;\n\n\/\/(*IdInit(CAboutBox)\nconst long CAboutBox::ID_STATICTEXT1 = wxNewId();\nconst long CAboutBox::ID_STATICTEXT2 = wxNewId();\nconst long CAboutBox::ID_STATICBITMAP1 = wxNewId();\nconst long CAboutBox::ID_STATICLINE1 = wxNewId();\nconst long CAboutBox::ID_TEXTCTRL1 = wxNewId();\nconst long CAboutBox::ID_TEXTCTRL2 = wxNewId();\nconst long CAboutBox::ID_TEXTCTRL3 = wxNewId();\nconst long CAboutBox::ID_NOTEBOOK1 = wxNewId();\nconst long CAboutBox::ID_BUTTON1 = wxNewId();\n\/\/*)\n\nBEGIN_EVENT_TABLE(CAboutBox, wxDialog)\n\/\/(*EventTable(CAboutBox)\n\/\/*)\nEND_EVENT_TABLE()\n\nCAboutBox::CAboutBox(\n\twxWindow* parent, const std::string& appName,\n\tconst std::string& additionalInfo, const bool showStandardInfo)\n\t: CAboutBoxBase(appName, additionalInfo, showStandardInfo)\n{\n\tconst wxWindowID id = -1;\n\t\/\/(*Initialize(CAboutBox)\n\twxFlexGridSizer* FlexGridSizer2;\n\n\tCreate(\n\t\tparent, id, _(\"About box...\"), wxDefaultPosition, wxDefaultSize,\n\t\twxDEFAULT_DIALOG_STYLE | wxCLOSE_BOX, _T(\"id\"));\n\tSetClientSize(wxSize(636, 375));\n\tFlexGridSizer1 = new wxFlexGridSizer(0, 1, 0, 0);\n\tFlexGridSizer1->AddGrowableCol(0);\n\tFlexGridSizer4 = new wxFlexGridSizer(0, 2, 0, 0);\n\tFlexGridSizer4->AddGrowableCol(1);\n\tFlexGridSizer4->AddGrowableRow(0);\n\tFlexGridSizer2 = new wxFlexGridSizer(2, 1, 0, 0);\n\tFlexGridSizer2->AddGrowableCol(0);\n\tFlexGridSizer2->AddGrowableRow(0);\n\tFlexGridSizer2->AddGrowableRow(1);\n\tlbProgName = new wxStaticText(\n\t\tthis, ID_STATICTEXT1, _(\"Title\"), wxDefaultPosition, wxDefaultSize, 0,\n\t\t_T(\"ID_STATICTEXT1\"));\n\twxFont lbProgNameFont(\n\t\t22, wxFONTFAMILY_SWISS, wxFONTSTYLE_NORMAL, wxFONTWEIGHT_BOLD, false,\n\t\t_T(\"Times New Roman\"), wxFONTENCODING_DEFAULT);\n\tlbProgName->SetFont(lbProgNameFont);\n\tFlexGridSizer2->Add(\n\t\tlbProgName, 1, wxALL | wxALIGN_BOTTOM | wxALIGN_CENTER_HORIZONTAL, 5);\n\tlbBuild = new wxStaticText(\n\t\tthis, ID_STATICTEXT2, _(\"Label\"), wxDefaultPosition, wxDefaultSize, 0,\n\t\t_T(\"ID_STATICTEXT2\"));\n\tFlexGridSizer2->Add(\n\t\tlbBuild, 1, wxALL | wxALIGN_TOP | wxALIGN_CENTER_HORIZONTAL, 5);\n\tFlexGridSizer4->Add(\n\t\tFlexGridSizer2, 1, wxALL | wxEXPAND | wxALIGN_LEFT | wxALIGN_TOP, 0);\n\tStaticBitmap1 = new wxStaticBitmap(\n\t\tthis, ID_STATICBITMAP1,\n\t\twxArtProvider::GetBitmap(\n\t\t\twxART_MAKE_ART_ID_FROM_STR(_T(\"IMG_MRPT_LOGO\")), wxART_OTHER),\n\t\twxDefaultPosition, wxDefaultSize, 0, _T(\"ID_STATICBITMAP1\"));\n\tFlexGridSizer4->Add(\n\t\tStaticBitmap1, 1,\n\t\twxALL | wxALIGN_CENTER_HORIZONTAL | wxALIGN_CENTER_VERTICAL, 5);\n\tFlexGridSizer1->Add(\n\t\tFlexGridSizer4, 1, wxALL | wxEXPAND | wxALIGN_LEFT | wxALIGN_TOP, 1);\n\tStaticLine1 = new wxStaticLine(\n\t\tthis, ID_STATICLINE1, wxPoint(3, 86), wxSize(627, 2), wxLI_HORIZONTAL,\n\t\t_T(\"ID_STATICLINE1\"));\n\tFlexGridSizer1->Add(\n\t\tStaticLine1, 1, wxALL | wxEXPAND | wxALIGN_LEFT | wxALIGN_TOP, 5);\n\tNotebook1 = new wxNotebook(\n\t\tthis, ID_NOTEBOOK1, wxPoint(6, 91), wxSize(625, 250), 0,\n\t\t_T(\"ID_NOTEBOOK1\"));\n\tlbInfo = new wxTextCtrl(\n\t\tNotebook1, ID_TEXTCTRL1, wxEmptyString, wxPoint(4, 24),\n\t\twxSize(545, 250), wxTE_MULTILINE | wxTE_READONLY | wxTE_AUTO_URL,\n\t\twxDefaultValidator, _T(\"ID_TEXTCTRL1\"));\n\twxFont lbInfoFont(\n\t\t10, wxFONTFAMILY_SWISS, wxFONTSTYLE_NORMAL, wxFONTWEIGHT_NORMAL, false,\n\t\t_T(\"Courier New\"), wxFONTENCODING_DEFAULT);\n\tlbInfo->SetFont(lbInfoFont);\n\tlbLicense = new wxTextCtrl(\n\t\tNotebook1, ID_TEXTCTRL2, _(\"\"), wxDefaultPosition, wxDefaultSize,\n\t\twxTE_MULTILINE | wxTE_READONLY | wxTE_AUTO_URL, wxDefaultValidator,\n\t\t_T(\"ID_TEXTCTRL2\"));\n\twxFont lbLicenseFont(\n\t\t10, wxFONTFAMILY_SWISS, wxFONTSTYLE_NORMAL, wxFONTWEIGHT_NORMAL, false,\n\t\t_T(\"Courier New\"), wxFONTENCODING_DEFAULT);\n\tlbLicense->SetFont(lbLicenseFont);\n\tTextCtrl1 = new wxTextCtrl(\n\t\tNotebook1, ID_TEXTCTRL3, _U(tutorial().c_str()), wxPoint(4, 24),\n\t\twxSize(545, 222), wxTE_MULTILINE | wxTE_READONLY | wxTE_AUTO_URL,\n\t\twxDefaultValidator, _T(\"ID_TEXTCTRL3\"));\n\twxFont TextCtrl1Font(\n\t\t10, wxFONTFAMILY_SWISS, wxFONTSTYLE_NORMAL, wxFONTWEIGHT_NORMAL, false,\n\t\t_T(\"Courier New\"), wxFONTENCODING_DEFAULT);\n\tTextCtrl1->SetFont(TextCtrl1Font);\n\tNotebook1->AddPage(lbInfo, _(\"Information\"), false);\n\tNotebook1->AddPage(lbLicense, _(\"License\"), false);\n\tNotebook1->AddPage(TextCtrl1, _(\"Tutorial\"), false);\n\tFlexGridSizer1->Add(\n\t\tNotebook1, 1, wxALL | wxEXPAND | wxALIGN_LEFT | wxALIGN_TOP, 5);\n\tButton11 = new wxButton(\n\t\tthis, ID_BUTTON1, _(\"OK\"), wxPoint(250, 345), wxSize(76, 26), 0,\n\t\twxDefaultValidator, _T(\"ID_BUTTON1\"));\n\tFlexGridSizer1->Add(\n\t\tButton11, 1,\n\t\twxALL | wxALIGN_CENTER_HORIZONTAL | wxALIGN_CENTER_VERTICAL, 5);\n\tSetSizer(FlexGridSizer1);\n\tFlexGridSizer1->SetSizeHints(this);\n\tCenter();\n\n\tConnect(\n\t\tID_BUTTON1, wxEVT_COMMAND_BUTTON_CLICKED,\n\t\t(wxObjectEventFunction)&CAboutBox::OnButton1Click);\n\tConnect(\n\t\twxID_ANY, wxEVT_INIT_DIALOG, (wxObjectEventFunction)&CAboutBox::OnInit);\n\t\/\/*)\n\n\tlbLicense->SetValue(_U(license().c_str()));\n}\n\nCAboutBox::~CAboutBox()\n{\n\t\/\/(*Destroy(CAboutBox)\n\t\/\/*)\n}\n\nvoid CAboutBox::OnInit(wxInitDialogEvent& event)\n{\n\t\/\/ Build strings:\n\twxString MRPTver(MRPT_getVersion().c_str(), wxConvLibc);\n\n\t\/\/ Set the label with MRPT version:\n\twxString s(_(\"Build: \"));\n\ts << _U(mrpt::system::MRPT_getCompilationDate().c_str());\n\ts << _(\" - \") << MRPTver;\n\n\tlbBuild->SetLabel(s);\n\n\t\/\/ Info:\n\tlbInfo->Clear();\n\n\t{\n\t\tCMyRedirector myRedirector(lbInfo);\n\t\twxString wxVer(wxVERSION_STRING);\n\t\tcout << information(\"wxWidgets\", std::string(wxVer.mb_str()));\n\t}\n\n\tlbProgName->SetLabel(_U(m_appName.c_str()));\n\tlbProgName->SetForegroundColour(wxColour(0, 0, 128));\n\n\tFlexGridSizer1->RecalcSizes();\n\tthis->Fit();\n}\n\nvoid CAboutBox::OnButton1Click(wxCommandEvent& event) { Close(); }\n#endif \/\/ MRPT_HAS_WXWIDGETS\n<|endoftext|>"} {"text":"#ifndef SAMPLE_UTIL_HPP\n#define SAMPLE_UTIL_HPP\n\n#include \"ranger\/bhvr_tree\/agent_proxy.hpp\"\n#include \"ranger\/bhvr_tree\/abstract_node.hpp\"\n#include \n#include \n#include \n#include \n\nnamespace std {\n\ninline std::string to_string(const std::thread::id& tid) {\n\tstd::stringstream ss;\n\tss << tid;\n\treturn ss.str();\n}\n\n}\n\nusing true_atom = caf::atom_constant;\nusing false_atom = caf::atom_constant;\nusing result_actor = caf::typed_actor<\tcaf::replies_to::with,\n\t\t\t\t\t\t\t\t\t\tcaf::replies_to::with\t>;\n\nresult_actor::behavior_type result_actor_impl(result_actor::pointer self) {\n\treturn {\n\t\t[=] (true_atom) {\n\t\t\treturn true;\n\t\t},\n\t\t[=] (false_atom) {\n\t\t\treturn false;\n\t\t},\n\t\tcaf::after(std::chrono::seconds(3)) >> [=] {\n\t\t\tself->quit();\n\t\t}\n\t};\n}\n\ntemplate \nclass behavior_node : public ranger::bhvr_tree::abstract_node {\npublic:\n\tbehavior_node() : m_target(caf::spawn(result_actor_impl)) {\n\t\t\/\/ nop\n\t}\n\n\tvoid exec(ranger::bhvr_tree::agent_proxy& ap, std::function hdl) final {\n\t\tstd::cout << \"behavior_node::exec\" << std::endl;\n\t\tcaf::spawn([this, hdl] (caf::event_based_actor* self) {\n\t\t\tself->sync_send(m_target, Atom::value).then(\n\t\t\t\t[=] (bool result) {\n\t\t\t\t\tcaf::aout(self) << std::this_thread::get_id() << std::endl;\n\t\t\t\t\thdl(result);\n\t\t\t\t}\n\t\t\t);\n\t\t});\n\t}\n\nprivate:\n\tresult_actor m_target;\n};\n\nusing true_node = behavior_node;\nusing false_node = behavior_node;\n\n#endif\t\/\/ SAMPLE_UTIL_HPP\n移除Sample中线程id的打印逻辑#ifndef SAMPLE_UTIL_HPP\n#define SAMPLE_UTIL_HPP\n\n#include \"ranger\/bhvr_tree\/agent_proxy.hpp\"\n#include \"ranger\/bhvr_tree\/abstract_node.hpp\"\n#include \n#include \n\nusing true_atom = caf::atom_constant;\nusing false_atom = caf::atom_constant;\nusing result_actor = caf::typed_actor<\tcaf::replies_to::with,\n\t\t\t\t\t\t\t\t\t\tcaf::replies_to::with\t>;\n\nresult_actor::behavior_type result_actor_impl(result_actor::pointer self) {\n\treturn {\n\t\t[=] (true_atom) {\n\t\t\treturn true;\n\t\t},\n\t\t[=] (false_atom) {\n\t\t\treturn false;\n\t\t},\n\t\tcaf::after(std::chrono::seconds(3)) >> [=] {\n\t\t\tself->quit();\n\t\t}\n\t};\n}\n\ntemplate \nclass behavior_node : public ranger::bhvr_tree::abstract_node {\npublic:\n\tbehavior_node() : m_target(caf::spawn(result_actor_impl)) {\n\t\t\/\/ nop\n\t}\n\n\tvoid exec(ranger::bhvr_tree::agent_proxy& ap, std::function hdl) final {\n\t\tstd::cout << \"behavior_node::exec\" << std::endl;\n\t\tcaf::spawn([this, hdl] (caf::event_based_actor* self) {\n\t\t\tself->sync_send(m_target, Atom::value).then(\n\t\t\t\t[=] (bool result) {\n\t\t\t\t\thdl(result);\n\t\t\t\t}\n\t\t\t);\n\t\t});\n\t}\n\nprivate:\n\tresult_actor m_target;\n};\n\nusing true_node = behavior_node;\nusing false_node = behavior_node;\n\n#endif\t\/\/ SAMPLE_UTIL_HPP\n<|endoftext|>"} {"text":"\/* Copyright 2015 The TensorFlow Authors. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*\/\n\n#include \"tensorflow\/core\/framework\/common_shape_fns.h\"\n#include \"tensorflow\/core\/framework\/op.h\"\n#include \"tensorflow\/core\/framework\/shape_inference.h\"\n\nnamespace tensorflow {\n\nusing shape_inference::InferenceContext;\n\nREGISTER_OP(\"SymbolicGradient\")\n .Input(\"input: Tin\")\n .Output(\"output: Tout\")\n .Attr(\"Tin: list(type)\")\n .Attr(\"Tout: list(type)\")\n .Attr(\"f: func\")\n .SetShapeFn([](InferenceContext* c) {\n if (c->num_inputs() < c->num_outputs()) {\n return errors::InvalidArgument(\"len(inputs) < len(outputs)\");\n }\n std::vector types;\n TF_RETURN_IF_ERROR(c->GetAttr(\"Tin\", &types));\n \/\/ Say, (u, v) = f(x, y, z), _symbolic_gradient(f) is a function of\n \/\/ (x, y, z, du, dv) -> (dx, dy, dz). Therefore, shapes of its\n \/\/ outputs (dx, dy, dz) are the same as (x, y, z).\n for (int i = 0; i < c->num_outputs(); ++i) {\n if (types[i] == DT_RESOURCE) {\n const std::vector* handle_type =\n c->input_handle_shapes_and_types(i);\n c->set_output(i, handle_type->at(0).shape);\n } else {\n c->set_output(i, c->input(i));\n }\n }\n return Status::OK();\n });\n\nREGISTER_OP(\"RemoteCall\")\n .Input(\"target: string\")\n .Input(\"args: Tin\")\n .Output(\"output: Tout\")\n .Attr(\"Tin: list(type)\")\n .Attr(\"Tout: list(type)\")\n .Attr(\"f: func\")\n .SetIsStateful()\n .SetShapeFn(shape_inference::UnknownShape);\n\n\/\/ TODO(drpng): remove this.\nREGISTER_OP(\"_If\")\n .Input(\"cond: Tcond\")\n .Input(\"input: Tin\")\n .Output(\"output: Tout\")\n .Attr(\"Tcond: type\")\n .Attr(\"Tin: list(type)\")\n .Attr(\"Tout: list(type)\")\n .Attr(\"then_branch: func\")\n .Attr(\"else_branch: func\")\n .SetShapeFn(shape_inference::UnknownShape)\n .Doc(R\"doc(\noutput = cond ? then_branch(input) : else_branch(input)\n\ncond: A Tensor. If the tensor is a scalar of non-boolean type, the\n scalar is converted to a boolean according to the\n following rule: if the scalar is a numerical value, non-zero means\n True and zero means False; if the scalar is a string, non-empty\n means True and empty means False. If the tensor is not a scalar,\n being empty means False and being non-empty means True.\ninput: A list of input tensors.\nthen_branch: A function that takes 'inputs' and returns a list of\n tensors, whose types are the same as what else_branch returns.\nelse_branch: A function that takes 'inputs' and returns a list of\n tensors. whose types are the same as what then_branch returns.\n)doc\");\n\nREGISTER_OP(\"If\")\n .Input(\"cond: Tcond\")\n .Input(\"input: Tin\")\n .Output(\"output: Tout\")\n .Attr(\"Tcond: type\")\n .Attr(\"Tin: list(type) >= 0\")\n .Attr(\"Tout: list(type)\")\n .Attr(\"then_branch: func\")\n .Attr(\"else_branch: func\")\n .SetShapeFn(shape_inference::UnknownShape);\n\n\/\/ TODO(drpng): remove this.\nREGISTER_OP(\"_While\")\n .Input(\"input: T\")\n .Output(\"output: T\")\n .Attr(\"T: list(type) >= 0\")\n .Attr(\"cond: func\")\n .Attr(\"body: func\")\n .SetIsStateful()\n .SetShapeFn([](shape_inference::InferenceContext* c) {\n for (int i = 0; i < c->num_outputs(); ++i) {\n c->set_output(i, c->input(i));\n }\n return Status::OK();\n })\n .Doc(R\"doc(\noutput = input; While (Cond(output)) { output = Body(output) }\n\ninput: A list of input tensors whose types are T.\noutput: A list of output tensors whose types are T.\ncond: A function takes 'input' and returns a tensor. If the tensor is\n a scalar of non-boolean, the scalar is converted to a boolean\n according to the following rule: if the scalar is a numerical\n value, non-zero means True and zero means False; if the scalar is\n a string, non-empty means True and empty means False. If the\n tensor is not a scalar, non-emptiness means True and False\n otherwise.\nbody: A function that takes a list of tensors and returns another\n list of tensors. Both lists have the same types as specified\n by T.\n)doc\");\n\n\/\/ TODO(b\/37549631) setting the While Op to always be stateful is too\n\/\/ conservative.\nREGISTER_OP(\"While\")\n .Input(\"input: T\")\n .Output(\"output: T\")\n .Attr(\"T: list(type) >= 0\")\n .Attr(\"cond: func\")\n .Attr(\"body: func\")\n .SetIsStateful()\n .SetShapeFn([](shape_inference::InferenceContext* c) {\n for (int i = 0; i < c->num_outputs(); ++i) {\n c->set_output(i, c->input(i));\n }\n return Status::OK();\n });\n\nREGISTER_OP(\"For\")\n .Input(\"start: int32\")\n .Input(\"limit: int32\")\n .Input(\"delta: int32\")\n .Input(\"input: T\")\n .Output(\"output: T\")\n .Attr(\"T: list(type) >= 0\")\n .Attr(\"body: func\")\n .SetShapeFn(shape_inference::UnknownShape);\n\n\/\/ TODO(b\/73826847, b\/37549631) Mark as stateful.\nREGISTER_OP(\"PartitionedCall\")\n .Input(\"args: Tin\")\n .Output(\"output: Tout\")\n .Attr(\"Tin: list(type) >= 0\")\n .Attr(\"Tout: list(type) >= 0\")\n .Attr(\"f: func\")\n .SetShapeFn(shape_inference::UnknownShape);\n\n\/\/ This op is used as a placeholder in If branch functions. It doesn't provide a\n\/\/ valid output when run, so must either be removed (e.g. replaced with a\n\/\/ function input) or guaranteed not to be used (e.g. if mirroring an\n\/\/ intermediate output needed for the gradient computation of the other branch).\nREGISTER_OP(\"FakeParam\")\n .Output(\"output: dtype\")\n .Attr(\"dtype: type\")\n .Attr(\"shape: shape\")\n .SetShapeFn([](InferenceContext* c) {\n PartialTensorShape shape;\n TF_RETURN_IF_ERROR(c->GetAttr(\"shape\", &shape));\n shape_inference::ShapeHandle out;\n TF_RETURN_IF_ERROR(c->MakeShapeFromPartialTensorShape(shape, &out));\n c->set_output(0, out);\n return Status::OK();\n });\n\n} \/\/ end namespace tensorflow\nRelaxed the functional If op to allow no outputs.\/* Copyright 2015 The TensorFlow Authors. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*\/\n\n#include \"tensorflow\/core\/framework\/common_shape_fns.h\"\n#include \"tensorflow\/core\/framework\/op.h\"\n#include \"tensorflow\/core\/framework\/shape_inference.h\"\n\nnamespace tensorflow {\n\nusing shape_inference::InferenceContext;\n\nREGISTER_OP(\"SymbolicGradient\")\n .Input(\"input: Tin\")\n .Output(\"output: Tout\")\n .Attr(\"Tin: list(type)\")\n .Attr(\"Tout: list(type)\")\n .Attr(\"f: func\")\n .SetShapeFn([](InferenceContext* c) {\n if (c->num_inputs() < c->num_outputs()) {\n return errors::InvalidArgument(\"len(inputs) < len(outputs)\");\n }\n std::vector types;\n TF_RETURN_IF_ERROR(c->GetAttr(\"Tin\", &types));\n \/\/ Say, (u, v) = f(x, y, z), _symbolic_gradient(f) is a function of\n \/\/ (x, y, z, du, dv) -> (dx, dy, dz). Therefore, shapes of its\n \/\/ outputs (dx, dy, dz) are the same as (x, y, z).\n for (int i = 0; i < c->num_outputs(); ++i) {\n if (types[i] == DT_RESOURCE) {\n const std::vector* handle_type =\n c->input_handle_shapes_and_types(i);\n c->set_output(i, handle_type->at(0).shape);\n } else {\n c->set_output(i, c->input(i));\n }\n }\n return Status::OK();\n });\n\nREGISTER_OP(\"RemoteCall\")\n .Input(\"target: string\")\n .Input(\"args: Tin\")\n .Output(\"output: Tout\")\n .Attr(\"Tin: list(type)\")\n .Attr(\"Tout: list(type)\")\n .Attr(\"f: func\")\n .SetIsStateful()\n .SetShapeFn(shape_inference::UnknownShape);\n\n\/\/ TODO(drpng): remove this.\nREGISTER_OP(\"_If\")\n .Input(\"cond: Tcond\")\n .Input(\"input: Tin\")\n .Output(\"output: Tout\")\n .Attr(\"Tcond: type\")\n .Attr(\"Tin: list(type)\")\n .Attr(\"Tout: list(type)\")\n .Attr(\"then_branch: func\")\n .Attr(\"else_branch: func\")\n .SetShapeFn(shape_inference::UnknownShape)\n .Doc(R\"doc(\noutput = cond ? then_branch(input) : else_branch(input)\n\ncond: A Tensor. If the tensor is a scalar of non-boolean type, the\n scalar is converted to a boolean according to the\n following rule: if the scalar is a numerical value, non-zero means\n True and zero means False; if the scalar is a string, non-empty\n means True and empty means False. If the tensor is not a scalar,\n being empty means False and being non-empty means True.\ninput: A list of input tensors.\nthen_branch: A function that takes 'inputs' and returns a list of\n tensors, whose types are the same as what else_branch returns.\nelse_branch: A function that takes 'inputs' and returns a list of\n tensors. whose types are the same as what then_branch returns.\n)doc\");\n\nREGISTER_OP(\"If\")\n .Input(\"cond: Tcond\")\n .Input(\"input: Tin\")\n .Output(\"output: Tout\")\n .Attr(\"Tcond: type\")\n .Attr(\"Tin: list(type) >= 0\")\n .Attr(\"Tout: list(type) >= 0\")\n .Attr(\"then_branch: func\")\n .Attr(\"else_branch: func\")\n .SetShapeFn(shape_inference::UnknownShape);\n\n\/\/ TODO(drpng): remove this.\nREGISTER_OP(\"_While\")\n .Input(\"input: T\")\n .Output(\"output: T\")\n .Attr(\"T: list(type) >= 0\")\n .Attr(\"cond: func\")\n .Attr(\"body: func\")\n .SetIsStateful()\n .SetShapeFn([](shape_inference::InferenceContext* c) {\n for (int i = 0; i < c->num_outputs(); ++i) {\n c->set_output(i, c->input(i));\n }\n return Status::OK();\n })\n .Doc(R\"doc(\noutput = input; While (Cond(output)) { output = Body(output) }\n\ninput: A list of input tensors whose types are T.\noutput: A list of output tensors whose types are T.\ncond: A function takes 'input' and returns a tensor. If the tensor is\n a scalar of non-boolean, the scalar is converted to a boolean\n according to the following rule: if the scalar is a numerical\n value, non-zero means True and zero means False; if the scalar is\n a string, non-empty means True and empty means False. If the\n tensor is not a scalar, non-emptiness means True and False\n otherwise.\nbody: A function that takes a list of tensors and returns another\n list of tensors. Both lists have the same types as specified\n by T.\n)doc\");\n\n\/\/ TODO(b\/37549631) setting the While Op to always be stateful is too\n\/\/ conservative.\nREGISTER_OP(\"While\")\n .Input(\"input: T\")\n .Output(\"output: T\")\n .Attr(\"T: list(type) >= 0\")\n .Attr(\"cond: func\")\n .Attr(\"body: func\")\n .SetIsStateful()\n .SetShapeFn([](shape_inference::InferenceContext* c) {\n for (int i = 0; i < c->num_outputs(); ++i) {\n c->set_output(i, c->input(i));\n }\n return Status::OK();\n });\n\nREGISTER_OP(\"For\")\n .Input(\"start: int32\")\n .Input(\"limit: int32\")\n .Input(\"delta: int32\")\n .Input(\"input: T\")\n .Output(\"output: T\")\n .Attr(\"T: list(type) >= 0\")\n .Attr(\"body: func\")\n .SetShapeFn(shape_inference::UnknownShape);\n\n\/\/ TODO(b\/73826847, b\/37549631) Mark as stateful.\nREGISTER_OP(\"PartitionedCall\")\n .Input(\"args: Tin\")\n .Output(\"output: Tout\")\n .Attr(\"Tin: list(type) >= 0\")\n .Attr(\"Tout: list(type) >= 0\")\n .Attr(\"f: func\")\n .SetShapeFn(shape_inference::UnknownShape);\n\n\/\/ This op is used as a placeholder in If branch functions. It doesn't provide a\n\/\/ valid output when run, so must either be removed (e.g. replaced with a\n\/\/ function input) or guaranteed not to be used (e.g. if mirroring an\n\/\/ intermediate output needed for the gradient computation of the other branch).\nREGISTER_OP(\"FakeParam\")\n .Output(\"output: dtype\")\n .Attr(\"dtype: type\")\n .Attr(\"shape: shape\")\n .SetShapeFn([](InferenceContext* c) {\n PartialTensorShape shape;\n TF_RETURN_IF_ERROR(c->GetAttr(\"shape\", &shape));\n shape_inference::ShapeHandle out;\n TF_RETURN_IF_ERROR(c->MakeShapeFromPartialTensorShape(shape, &out));\n c->set_output(0, out);\n return Status::OK();\n });\n\n} \/\/ end namespace tensorflow\n<|endoftext|>"} {"text":"\/\/ RUN: grep -Ev \"\/\/ *[A-Z0-9]+:\" %s > %t.cpp\n\/\/ RUN: clang-format -style=\"{BasedOnStyle: Google, IndentWidth: 8}\" %t.cpp | FileCheck -strict-whitespace -check-prefix=CHECK1 %s\n\/\/ RUN: clang-format -style=\"{BasedOnStyle: LLVM, IndentWidth: 7}\" %t.cpp | FileCheck -strict-whitespace -check-prefix=CHECK2 %s\n\/\/ RUN: clang-format -style=\"{BasedOnStyle: invalid, IndentWidth: 7}\" %t.cpp 2>&1 | FileCheck -strict-whitespace -check-prefix=CHECK3 %s\n\/\/ RUN: clang-format -style=\"{lsjd}\" %t.cpp 2>&1 | FileCheck -strict-whitespace -check-prefix=CHECK4 %s\n\/\/ RUN: [ ! -e %T\/.clang-format ] || rm %T\/.clang-format\n\/\/ RUN: printf \"BasedOnStyle: google\\nIndentWidth: 5\\n\" > %T\/.clang-format\n\/\/ RUN: clang-format -style=file %t.cpp 2>&1 | FileCheck -strict-whitespace -check-prefix=CHECK5 %s\nvoid f() {\n\/\/ CHECK1: {{^ int\\* i;$}}\n\/\/ CHECK2: {{^ int \\*i;$}}\n\/\/ CHECK3: Unknown value for BasedOnStyle: invalid\n\/\/ CHECK3: Error parsing -style: Invalid argument, using LLVM style\n\/\/ CHECK3: {{^ int \\*i;$}}\n\/\/ CHECK4: Error parsing -style: Invalid argument, using LLVM style\n\/\/ CHECK4: {{^ int \\*i;$}}\n\/\/ CHECK5: {{^ int\\* i;$}}\nint*i;\nint j;\n}\nTest for empty .clang-format file.\/\/ RUN: grep -Ev \"\/\/ *[A-Z0-9]+:\" %s > %t.cpp\n\/\/ RUN: clang-format -style=\"{BasedOnStyle: Google, IndentWidth: 8}\" %t.cpp | FileCheck -strict-whitespace -check-prefix=CHECK1 %s\n\/\/ RUN: clang-format -style=\"{BasedOnStyle: LLVM, IndentWidth: 7}\" %t.cpp | FileCheck -strict-whitespace -check-prefix=CHECK2 %s\n\/\/ RUN: clang-format -style=\"{BasedOnStyle: invalid, IndentWidth: 7}\" %t.cpp 2>&1 | FileCheck -strict-whitespace -check-prefix=CHECK3 %s\n\/\/ RUN: clang-format -style=\"{lsjd}\" %t.cpp 2>&1 | FileCheck -strict-whitespace -check-prefix=CHECK4 %s\n\/\/ RUN: [ ! -e %T\/.clang-format ] || rm %T\/.clang-format\n\/\/ RUN: printf \"BasedOnStyle: google\\nIndentWidth: 5\\n\" > %T\/.clang-format\n\/\/ RUN: clang-format -style=file %t.cpp 2>&1 | FileCheck -strict-whitespace -check-prefix=CHECK5 %s\n\/\/ RUN: printf \"\\n\" > %T\/.clang-format\n\/\/ RUN: clang-format -style=file %t.cpp 2>&1 | FileCheck -strict-whitespace -check-prefix=CHECK6 %s\nvoid f() {\n\/\/ CHECK1: {{^ int\\* i;$}}\n\/\/ CHECK2: {{^ int \\*i;$}}\n\/\/ CHECK3: Unknown value for BasedOnStyle: invalid\n\/\/ CHECK3: Error parsing -style: Invalid argument, using LLVM style\n\/\/ CHECK3: {{^ int \\*i;$}}\n\/\/ CHECK4: Error parsing -style: Invalid argument, using LLVM style\n\/\/ CHECK4: {{^ int \\*i;$}}\n\/\/ CHECK5: {{^ int\\* i;$}}\n\/\/ CHECK6: Can't find usable .clang-format, using LLVM style\n\/\/ CHECK6: {{^ int \\*i;$}}\nint*i;\nint j;\n}\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"benchmark\/benchmark.h\"\n\n\/\/ Test that Setup() and Teardown() are called exactly once\n\/\/ for each benchmark run (single-threaded).\nnamespace single {\nstatic int setup_call = 0;\nstatic int teardown_call = 0;\n} \/\/ namespace single\nstatic void DoSetup1(const benchmark::State& state) {\n ++single::setup_call;\n\n \/\/ Setup\/Teardown should never be called with any thread_idx != 0.\n assert(state.thread_index() == 0);\n}\n\nstatic void DoTeardown1(const benchmark::State& state) {\n ++single::teardown_call;\n assert(state.thread_index() == 0);\n}\n\nstatic void BM_with_setup(benchmark::State& state) {\n for (auto s : state) {\n }\n}\nBENCHMARK(BM_with_setup)\n ->Arg(1)\n ->Arg(3)\n ->Arg(5)\n ->Arg(7)\n ->Iterations(100)\n ->Setup(DoSetup1)\n ->Teardown(DoTeardown1);\n\n\/\/ Test that Setup() and Teardown() are called once for each group of threads.\nnamespace concurrent {\nstatic std::atomic setup_call(0);\nstatic std::atomic teardown_call(0);\nstatic std::atomic func_call(0);\n} \/\/ namespace concurrent\n\nstatic void DoSetup2(const benchmark::State& state) {\n concurrent::setup_call.fetch_add(1, std::memory_order_acquire);\n assert(state.thread_index() == 0);\n}\n\nstatic void DoTeardown2(const benchmark::State& state) {\n concurrent::teardown_call.fetch_add(1, std::memory_order_acquire);\n assert(state.thread_index() == 0);\n}\n\nstatic void BM_concurrent(benchmark::State& state) {\n for (auto s : state) {\n }\n concurrent::func_call.fetch_add(1, std::memory_order_acquire);\n}\n\nBENCHMARK(BM_concurrent)\n ->Setup(DoSetup2)\n ->Teardown(DoTeardown2)\n ->Iterations(100)\n ->Threads(5)\n ->Threads(10)\n ->Threads(15);\n\n\/\/ Testing interaction with Fixture::Setup\/Teardown\nnamespace fixture_interaction {\nint setup = 0;\nint fixture_setup = 0;\n} \/\/ namespace fixture_interaction\n\n#define FIXTURE_BECHMARK_NAME MyFixture\n\nclass FIXTURE_BECHMARK_NAME : public ::benchmark::Fixture {\n public:\n void SetUp(const ::benchmark::State& state) BENCHMARK_OVERRIDE {\n fixture_interaction::fixture_setup++;\n }\n\n ~FIXTURE_BECHMARK_NAME() {}\n};\n\nBENCHMARK_F(FIXTURE_BECHMARK_NAME, BM_WithFixture)(benchmark::State& st) {\n for (auto _ : st) {\n }\n}\n\nstatic void DoSetupWithFixture(const benchmark::State& state) {\n fixture_interaction::setup++;\n}\n\nBENCHMARK_REGISTER_F(FIXTURE_BECHMARK_NAME, BM_WithFixture)\n ->Arg(1)\n ->Arg(3)\n ->Arg(5)\n ->Arg(7)\n ->Setup(DoSetupWithFixture)\n ->Repetitions(1)\n ->Iterations(100);\n\n\/\/ Testing repetitions.\nnamespace repetitions {\nint setup = 0;\n}\n\nstatic void DoSetupWithRepetitions(const benchmark::State& state) {\n repetitions::setup++;\n}\nstatic void BM_WithRep(benchmark::State& state) {\n for (auto _ : state) {\n }\n}\n\nBENCHMARK(BM_WithRep)\n ->Arg(1)\n ->Arg(3)\n ->Arg(5)\n ->Arg(7)\n ->Setup(DoSetupWithRepetitions)\n ->Iterations(100)\n ->Repetitions(4);\n\nint main(int argc, char** argv) {\n benchmark::Initialize(&argc, argv);\n\n size_t ret = benchmark::RunSpecifiedBenchmarks(\".\");\n assert(ret > 0);\n\n \/\/ Setup\/Teardown is called once for each arg group (1,3,5,7).\n assert(single::setup_call == 4);\n assert(single::teardown_call == 4);\n\n \/\/ 3 group of threads calling this function (3,5,10).\n assert(concurrent::setup_call.load(std::memory_order_relaxed) == 3);\n assert(concurrent::teardown_call.load(std::memory_order_relaxed) == 3);\n assert((5 + 10 + 15) ==\n concurrent::func_call.load(std::memory_order_relaxed));\n\n \/\/ Setup is called 4 times, once for each arg group (1,3,5,7)\n assert(fixture_interaction::setup == 4);\n \/\/ Fixture::Setup is called everytime the bm routine is run.\n \/\/ The exact number is indeterministic, so we just assert that\n \/\/ it's more than setup.\n assert(fixture_interaction::fixture_setup > fixture_interaction::setup);\n\n \/\/ Setup is call once for each repetition * num_arg = 4 * 4 = 16.\n assert(repetitions::setup == 16);\n\n return 0;\n}\nlose some build warnings#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"benchmark\/benchmark.h\"\n\n\/\/ Test that Setup() and Teardown() are called exactly once\n\/\/ for each benchmark run (single-threaded).\nnamespace single {\nstatic int setup_call = 0;\nstatic int teardown_call = 0;\n} \/\/ namespace single\nstatic void DoSetup1(const benchmark::State& state) {\n ++single::setup_call;\n\n \/\/ Setup\/Teardown should never be called with any thread_idx != 0.\n assert(state.thread_index() == 0);\n}\n\nstatic void DoTeardown1(const benchmark::State& state) {\n ++single::teardown_call;\n assert(state.thread_index() == 0);\n}\n\nstatic void BM_with_setup(benchmark::State& state) {\n for (auto s : state) {\n }\n}\nBENCHMARK(BM_with_setup)\n ->Arg(1)\n ->Arg(3)\n ->Arg(5)\n ->Arg(7)\n ->Iterations(100)\n ->Setup(DoSetup1)\n ->Teardown(DoTeardown1);\n\n\/\/ Test that Setup() and Teardown() are called once for each group of threads.\nnamespace concurrent {\nstatic std::atomic setup_call(0);\nstatic std::atomic teardown_call(0);\nstatic std::atomic func_call(0);\n} \/\/ namespace concurrent\n\nstatic void DoSetup2(const benchmark::State& state) {\n concurrent::setup_call.fetch_add(1, std::memory_order_acquire);\n assert(state.thread_index() == 0);\n}\n\nstatic void DoTeardown2(const benchmark::State& state) {\n concurrent::teardown_call.fetch_add(1, std::memory_order_acquire);\n assert(state.thread_index() == 0);\n}\n\nstatic void BM_concurrent(benchmark::State& state) {\n for (auto s : state) {\n }\n concurrent::func_call.fetch_add(1, std::memory_order_acquire);\n}\n\nBENCHMARK(BM_concurrent)\n ->Setup(DoSetup2)\n ->Teardown(DoTeardown2)\n ->Iterations(100)\n ->Threads(5)\n ->Threads(10)\n ->Threads(15);\n\n\/\/ Testing interaction with Fixture::Setup\/Teardown\nnamespace fixture_interaction {\nint setup = 0;\nint fixture_setup = 0;\n} \/\/ namespace fixture_interaction\n\n#define FIXTURE_BECHMARK_NAME MyFixture\n\nclass FIXTURE_BECHMARK_NAME : public ::benchmark::Fixture {\n public:\n void SetUp(const ::benchmark::State&) BENCHMARK_OVERRIDE {\n fixture_interaction::fixture_setup++;\n }\n\n ~FIXTURE_BECHMARK_NAME() {}\n};\n\nBENCHMARK_F(FIXTURE_BECHMARK_NAME, BM_WithFixture)(benchmark::State& st) {\n for (auto _ : st) {\n }\n}\n\nstatic void DoSetupWithFixture(const benchmark::State&) {\n fixture_interaction::setup++;\n}\n\nBENCHMARK_REGISTER_F(FIXTURE_BECHMARK_NAME, BM_WithFixture)\n ->Arg(1)\n ->Arg(3)\n ->Arg(5)\n ->Arg(7)\n ->Setup(DoSetupWithFixture)\n ->Repetitions(1)\n ->Iterations(100);\n\n\/\/ Testing repetitions.\nnamespace repetitions {\nint setup = 0;\n}\n\nstatic void DoSetupWithRepetitions(const benchmark::State&) {\n repetitions::setup++;\n}\nstatic void BM_WithRep(benchmark::State& state) {\n for (auto _ : state) {\n }\n}\n\nBENCHMARK(BM_WithRep)\n ->Arg(1)\n ->Arg(3)\n ->Arg(5)\n ->Arg(7)\n ->Setup(DoSetupWithRepetitions)\n ->Iterations(100)\n ->Repetitions(4);\n\nint main(int argc, char** argv) {\n benchmark::Initialize(&argc, argv);\n\n size_t ret = benchmark::RunSpecifiedBenchmarks(\".\");\n assert(ret > 0);\n\n \/\/ Setup\/Teardown is called once for each arg group (1,3,5,7).\n assert(single::setup_call == 4);\n assert(single::teardown_call == 4);\n\n \/\/ 3 group of threads calling this function (3,5,10).\n assert(concurrent::setup_call.load(std::memory_order_relaxed) == 3);\n assert(concurrent::teardown_call.load(std::memory_order_relaxed) == 3);\n assert((5 + 10 + 15) ==\n concurrent::func_call.load(std::memory_order_relaxed));\n\n \/\/ Setup is called 4 times, once for each arg group (1,3,5,7)\n assert(fixture_interaction::setup == 4);\n \/\/ Fixture::Setup is called everytime the bm routine is run.\n \/\/ The exact number is indeterministic, so we just assert that\n \/\/ it's more than setup.\n assert(fixture_interaction::fixture_setup > fixture_interaction::setup);\n\n \/\/ Setup is call once for each repetition * num_arg = 4 * 4 = 16.\n assert(repetitions::setup == 16);\n\n return 0;\n}\n<|endoftext|>"} {"text":"\/*\n Copyright (C) 2013 Digia Plc and\/or its subsidiary(-ies).\n Copyright (C) 2013 basysKom GmbH \n Copyright (C) 2013 Collabora Ltd. \n\n This library is free software; you can redistribute it and\/or modify\n it under the terms of the GNU Lesser General Public License version 2.1\n as published by the Free Software Foundation.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU Lesser General Public License for more details.\n\n You should have received a copy of the GNU Lesser General Public License\n along with this program. If not, see .\n*\/\n\n\/**\n * @file\n * @brief Extracted from QtGstreamer to avoid overly complex dependency\n * @author Gus Grubba \n *\/\n\n#include \"videonode.h\"\n#include \"videomaterial.h\"\n\n#include \n\nVideoNode::VideoNode()\n : QSGGeometryNode()\n{\n setFlags(OwnsGeometry | OwnsMaterial, true);\n setMaterialTypeSolidBlack();\n}\n\nvoid VideoNode::changeFormat(const BufferFormat & format)\n{\n setMaterial(VideoMaterial::create(format));\n setGeometry(0);\n m_materialType = MaterialTypeVideo;\n}\n\nvoid VideoNode::setMaterialTypeSolidBlack()\n{\n QSGFlatColorMaterial *m = new QSGFlatColorMaterial;\n m->setColor(Qt::black);\n setMaterial(m);\n setGeometry(0);\n m_materialType = MaterialTypeSolidBlack;\n}\n\nvoid VideoNode::setCurrentFrame(GstBuffer* buffer)\n{\n Q_ASSERT (m_materialType == MaterialTypeVideo);\n static_cast(material())->setCurrentFrame(buffer);\n markDirty(DirtyMaterial);\n}\n\nvoid VideoNode::updateColors(int brightness, int contrast, int hue, int saturation)\n{\n Q_ASSERT (m_materialType == MaterialTypeVideo);\n static_cast(material())->updateColors(brightness, contrast, hue, saturation);\n markDirty(DirtyMaterial);\n}\n\n\/* Helpers *\/\ntemplate \nstatic inline void setGeom(V *v, const QPointF &p)\n{\n v->x = p.x();\n v->y = p.y();\n}\n\nstatic inline void setTex(QSGGeometry::TexturedPoint2D *v, const QPointF &p)\n{\n v->tx = p.x();\n v->ty = p.y();\n}\n\nvoid VideoNode::updateGeometry(const PaintAreas & areas)\n{\n QSGGeometry *g = geometry();\n\n if (m_materialType == MaterialTypeVideo) {\n if (!g)\n g = new QSGGeometry(QSGGeometry::defaultAttributes_TexturedPoint2D(), 4);\n\n QSGGeometry::TexturedPoint2D *v = g->vertexDataAsTexturedPoint2D();\n\n \/\/ Set geometry first\n setGeom(v + 0, areas.videoArea.topLeft());\n setGeom(v + 1, areas.videoArea.bottomLeft());\n setGeom(v + 2, areas.videoArea.topRight());\n setGeom(v + 3, areas.videoArea.bottomRight());\n\n \/\/ and then texture coordinates\n setTex(v + 0, areas.sourceRect.topLeft());\n setTex(v + 1, areas.sourceRect.bottomLeft());\n setTex(v + 2, areas.sourceRect.topRight());\n setTex(v + 3, areas.sourceRect.bottomRight());\n } else {\n if (!g)\n g = new QSGGeometry(QSGGeometry::defaultAttributes_Point2D(), 4);\n\n QSGGeometry::Point2D *v = g->vertexDataAsPoint2D();\n\n setGeom(v + 0, areas.videoArea.topLeft());\n setGeom(v + 1, areas.videoArea.bottomLeft());\n setGeom(v + 2, areas.videoArea.topRight());\n setGeom(v + 3, areas.videoArea.bottomRight());\n }\n\n if (!geometry())\n setGeometry(g);\n\n markDirty(DirtyGeometry);\n}\nvideonode: Do not finish if material is different\/*\n Copyright (C) 2013 Digia Plc and\/or its subsidiary(-ies).\n Copyright (C) 2013 basysKom GmbH \n Copyright (C) 2013 Collabora Ltd. \n\n This library is free software; you can redistribute it and\/or modify\n it under the terms of the GNU Lesser General Public License version 2.1\n as published by the Free Software Foundation.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU Lesser General Public License for more details.\n\n You should have received a copy of the GNU Lesser General Public License\n along with this program. If not, see .\n*\/\n\n\/**\n * @file\n * @brief Extracted from QtGstreamer to avoid overly complex dependency\n * @author Gus Grubba \n *\/\n\n#include \"videonode.h\"\n#include \"videomaterial.h\"\n\n#include \n\nVideoNode::VideoNode()\n : QSGGeometryNode()\n{\n setFlags(OwnsGeometry | OwnsMaterial, true);\n setMaterialTypeSolidBlack();\n}\n\nvoid VideoNode::changeFormat(const BufferFormat & format)\n{\n setMaterial(VideoMaterial::create(format));\n setGeometry(0);\n m_materialType = MaterialTypeVideo;\n}\n\nvoid VideoNode::setMaterialTypeSolidBlack()\n{\n QSGFlatColorMaterial *m = new QSGFlatColorMaterial;\n m->setColor(Qt::black);\n setMaterial(m);\n setGeometry(0);\n m_materialType = MaterialTypeSolidBlack;\n}\n\nvoid VideoNode::setCurrentFrame(GstBuffer* buffer)\n{\n if (m_materialType != MaterialTypeVideo) {\n return;\n }\n static_cast(material())->setCurrentFrame(buffer);\n markDirty(DirtyMaterial);\n}\n\nvoid VideoNode::updateColors(int brightness, int contrast, int hue, int saturation)\n{\n if (m_materialType != MaterialTypeVideo) {\n return;\n }\n static_cast(material())->updateColors(brightness, contrast, hue, saturation);\n markDirty(DirtyMaterial);\n}\n\n\/* Helpers *\/\ntemplate \nstatic inline void setGeom(V *v, const QPointF &p)\n{\n v->x = p.x();\n v->y = p.y();\n}\n\nstatic inline void setTex(QSGGeometry::TexturedPoint2D *v, const QPointF &p)\n{\n v->tx = p.x();\n v->ty = p.y();\n}\n\nvoid VideoNode::updateGeometry(const PaintAreas & areas)\n{\n QSGGeometry *g = geometry();\n\n if (m_materialType == MaterialTypeVideo) {\n if (!g)\n g = new QSGGeometry(QSGGeometry::defaultAttributes_TexturedPoint2D(), 4);\n\n QSGGeometry::TexturedPoint2D *v = g->vertexDataAsTexturedPoint2D();\n\n \/\/ Set geometry first\n setGeom(v + 0, areas.videoArea.topLeft());\n setGeom(v + 1, areas.videoArea.bottomLeft());\n setGeom(v + 2, areas.videoArea.topRight());\n setGeom(v + 3, areas.videoArea.bottomRight());\n\n \/\/ and then texture coordinates\n setTex(v + 0, areas.sourceRect.topLeft());\n setTex(v + 1, areas.sourceRect.bottomLeft());\n setTex(v + 2, areas.sourceRect.topRight());\n setTex(v + 3, areas.sourceRect.bottomRight());\n } else {\n if (!g)\n g = new QSGGeometry(QSGGeometry::defaultAttributes_Point2D(), 4);\n\n QSGGeometry::Point2D *v = g->vertexDataAsPoint2D();\n\n setGeom(v + 0, areas.videoArea.topLeft());\n setGeom(v + 1, areas.videoArea.bottomLeft());\n setGeom(v + 2, areas.videoArea.topRight());\n setGeom(v + 3, areas.videoArea.bottomRight());\n }\n\n if (!geometry())\n setGeometry(g);\n\n markDirty(DirtyGeometry);\n}\n<|endoftext|>"} {"text":"#include \n\n\/\/ ROS\n#include \n\n\/\/ PCL\n#include \n#include \n#include \n\nusing namespace std;\nusing namespace pcl;\nusing namespace rail::pick_and_place;\n\nPointCloudRecognizer::PointCloudRecognizer()\n{\n}\n\nbool PointCloudRecognizer::recognizeObject(rail_manipulation_msgs::SegmentedObject &object,\n const vector &candidates) const\n{\n \/\/ make sure we have some candidates\n if (candidates.empty())\n {\n ROS_WARN(\"Candidate object list is empty. Nothing to compare segmented object to.\");\n return false;\n }\n if (object.point_cloud.data.empty())\n {\n ROS_WARN(\"Segmented object point cloud is empty. Nothing to compare candidate objects to.\");\n return false;\n }\n\n \/\/ convert to a PCL point cloud\n pcl::PCLPointCloud2 object_converter;\n pcl_conversions::toPCL(object.point_cloud, object_converter);\n pcl::PointCloud::Ptr object_point_cloud(new pcl::PointCloud);\n pcl::fromPCLPointCloud2(object_converter, *object_point_cloud);\n\n \/\/ pre-process input cloud\n this->filterPointCloudOutliers(object_point_cloud);\n this->translateToOrigin(object_point_cloud, object.centroid);\n\n \/\/ perform recognition\n double min_score = numeric_limits::infinity();\n size_t min_index;\n Eigen::Matrix4f min_icp_tf;\n bool min_swapped;\n for (size_t i = 0; i < candidates.size(); i++)\n {\n \/\/ convert the candidate point cloud to a PCL point cloud\n pcl::PCLPointCloud2 cur_converter;\n pcl_conversions::toPCL(candidates[i].getPointCloud(), cur_converter);\n pcl::PointCloud::Ptr candidate_point_cloud(new pcl::PointCloud);\n pcl::fromPCLPointCloud2(cur_converter, *candidate_point_cloud);\n\n Eigen::Matrix4f cur_icp_tf;\n bool cur_swapped;\n double score = this->scoreRegistration(candidate_point_cloud, object_point_cloud, cur_icp_tf, cur_swapped);\n if (score < min_score)\n {\n min_score = score;\n min_index = i;\n min_icp_tf = cur_icp_tf;\n min_swapped = cur_swapped;\n }\n }\n\n \/\/ check if there is enough confidence\n if (min_score > SCORE_CONFIDENCE_THRESHOLD)\n {\n return false;\n }\n\n \/\/ fill in recognition information\n object.name = candidates[min_index].getObjectName();\n object.model_id = candidates[min_index].getID();\n object.recognized = true;\n object.grasps.clear();\n\n \/\/ extract possible grasps for this model\n vector possible_grasps;\n this->transformGrasps(min_icp_tf, min_swapped, object.centroid,\n candidates[min_index].toROSGraspModelMessage().grasps, possible_grasps);\n\n \/\/ sort and remove any grasps with 0 success rates\n vector success_rates;\n for (size_t i = 0; i < possible_grasps.size(); i++)\n {\n double rate = (possible_grasps[i].attempts > 0) ?\n ((double) possible_grasps[i].successes) \/ ((double) possible_grasps[i].attempts) : 0.0;\n\n \/\/ check the success rate\n if (rate > 0)\n {\n \/\/ place it in order\n bool inserted = false;\n for (size_t j = 0; j < success_rates.size(); j++)\n {\n if (rate <= success_rates[j])\n {\n object.grasps.insert(object.grasps.begin() + j, possible_grasps[i].grasp_pose);\n success_rates.insert(success_rates.begin() + j, rate);\n inserted = true;\n break;\n }\n }\n\n if (!inserted)\n {\n object.grasps.push_back(possible_grasps[i].grasp_pose);\n success_rates.push_back(rate);\n }\n }\n }\n\n return true;\n}\n\nvoid PointCloudRecognizer::filterPointCloudOutliers(PointCloud::Ptr pc) const\n{\n \/\/ use a KD tree to search\n pcl::KdTreeFLANN search_tree;\n search_tree.setInputCloud(pc);\n\n \/\/ check each point\n pcl::IndicesPtr to_keep(new vector);\n for (size_t i = 0; i < pc->size(); i++)\n {\n vector indices;\n vector distances;\n \/\/ check how many neighbors pass the test\n int neighbors = search_tree.radiusSearch(pc->at(i), FILTER_SEARCH_RADIUS, indices, distances);\n if (neighbors >= FILTER_MIN_NUM_NEIGHBORS)\n {\n to_keep->push_back(i);\n }\n }\n\n \/\/ extract the point we wish to keep\n pcl::ExtractIndices extract;\n extract.setInputCloud(pc);\n extract.setIndices(to_keep);\n extract.filter(*pc);\n}\n\nvoid PointCloudRecognizer::translateToOrigin(pcl::PointCloud::Ptr pc,\n const geometry_msgs::Point ¢roid) const\n{\n \/\/ transformation matrix\n Eigen::Matrix4f tf;\n tf << 1, 0, 0, -centroid.x,\n 0, 1, 0, -centroid.y,\n 0, 0, 1, -centroid.z,\n 0, 0, 0, 1;\n\n \/\/ transform the point cloud\n pcl::transformPointCloud(*pc, *pc, tf);\n}\n\ndouble PointCloudRecognizer::scoreRegistration(PointCloud::ConstPtr candidate,\n PointCloud::ConstPtr object, Eigen::Matrix4f &icp_tf, bool &icp_swapped) const\n{\n \/\/ use the larger as the base cloud\n icp_swapped = object->size() > candidate->size();\n \/\/ use ICP to for matching\n pcl::IterativeClosestPoint icp;\n if (icp_swapped)\n {\n icp.setInputSource(candidate);\n icp.setInputTarget(object);\n } else\n {\n icp.setInputSource(object);\n icp.setInputTarget(candidate);\n }\n\n \/\/ run ICP on the two point clouds\n pcl::PointCloud::Ptr aligned(new pcl::PointCloud);\n icp.align(*aligned);\n \/\/ extract the final transform\n icp_tf = icp.getFinalTransformation();\n\n \/\/ calculate the distance and color error\n double distance_error = this->calculateRegistrationMetricDistanceError(candidate, aligned);\n double color_error = this->calculateRegistrationMetricOverlap(candidate, aligned);\n\n \/\/ calculate the final weighted result\n double result = ALPHA * (3.0 * distance_error) + (1.0 - ALPHA) * (color_error \/ 100.0);\n return result;\n}\n\ndouble PointCloudRecognizer::calculateRegistrationMetricDistanceError(pcl::PointCloud::ConstPtr base,\n pcl::PointCloud::ConstPtr target) const\n{\n \/\/ search using a KD tree\n pcl::KdTreeFLANN search_tree;\n search_tree.setInputCloud(base);\n\n \/\/ search for the nearest point to each point\n double score = 0;\n for (size_t i = 0; i < target->size(); i++)\n {\n vector indices;\n vector distances;\n search_tree.nearestKSearch(target->at(i), 1, indices, distances);\n score += (double) distances[0];\n }\n\n return score;\n}\n\ndouble PointCloudRecognizer::calculateRegistrationMetricOverlap(pcl::PointCloud::ConstPtr base,\n pcl::PointCloud::ConstPtr target) const\n{\n \/\/ search with a KD tree\n pcl::KdTreeFLANN search_tree;\n search_tree.setInputCloud(base);\n\n \/\/ search each point\n int score = 0;\n float error = 0;\n for (size_t i = 0; i < target->size(); i++)\n {\n \/\/ get the current point\n vector indices;\n vector distances;\n const pcl::PointXYZRGB &search_point = target->at(i);\n \/\/ perform a radius search to see how many neighbors are found\n int neighbors = search_tree.radiusSearch(search_point, OVERLAP_SEARCH_RADIUS, indices, distances);\n \/\/ check if there are enough neighbors\n if (neighbors > 0)\n {\n score++;\n \/\/ check the average RGB color distance\n double rgb_distance = 0;\n for (size_t j = 0; j < indices.size(); j++)\n {\n const pcl::PointXYZRGB &point = base->at(indices[j]);\n rgb_distance += sqrt(pow(search_point.r - point.r, 2) + pow(search_point.g - point.g, 2) +\n pow(search_point.b - point.b, 2));\n }\n \/\/ normalize the distance\n rgb_distance \/= neighbors;\n error += rgb_distance;\n }\n }\n\n \/\/ normalize the error\n error \/= ((double) score);\n return error;\n}\n\nvoid PointCloudRecognizer::transformGrasps(const Eigen::Matrix4f &icp_transform, const bool icp_swapped,\n const geometry_msgs::Point ¢roid,\n const vector &candidate_grasps,\n vector &grasps) const\n{\n \/\/ convert to a TF2 matrix\n tf2::Matrix3x3 rotation(icp_transform(0, 0), icp_transform(0, 1), icp_transform(0, 2),\n icp_transform(1, 0), icp_transform(1, 1), icp_transform(1, 2),\n icp_transform(2, 0), icp_transform(2, 1), icp_transform(2, 2));\n tf2::Vector3 translation(icp_transform(0, 3), icp_transform(1, 3), icp_transform(2, 3));\n tf2::Transform tf_icp(rotation, translation);\n\n \/\/ transform each pose\n for (size_t i = 0; i < candidate_grasps.size(); i++)\n {\n \/\/ convert to tf2 matrix\n const geometry_msgs::Pose &pose = candidate_grasps[i].grasp_pose.pose;\n tf2::Quaternion q_pose(pose.orientation.x, pose.orientation.y, pose.orientation.z, pose.orientation.w);\n tf2::Vector3 v_pose(pose.position.x, pose.position.y, pose.position.z);\n tf2::Transform tf_pose(q_pose, v_pose);\n\n \/\/ push back the basic information\n grasps.push_back(candidate_grasps[i]);\n\n tf2::Transform result;\n if (icp_swapped)\n {\n tf2::Transform result;\n result.mult(tf_icp, tf_pose);\n } else\n {\n \/\/ use the invese for the result\n tf2::Transform inverse = tf_icp.inverse();\n result.mult(inverse, tf_pose);\n }\n\n \/\/ copy over the values\n grasps[i].grasp_pose.pose.position.x = result.getOrigin().x();\n grasps[i].grasp_pose.pose.position.y = result.getOrigin().y();\n grasps[i].grasp_pose.pose.position.z = result.getOrigin().z();\n grasps[i].grasp_pose.pose.orientation.x = result.getRotation().x();\n grasps[i].grasp_pose.pose.orientation.y = result.getRotation().y();\n grasps[i].grasp_pose.pose.orientation.z = result.getRotation().z();\n grasps[i].grasp_pose.pose.orientation.w = result.getRotation().w();\n\n \/\/ correct for the origin transform\n grasps[i].grasp_pose.pose.position.x += centroid.x;\n grasps[i].grasp_pose.pose.position.y += centroid.y;\n grasps[i].grasp_pose.pose.position.z += centroid.z;\n }\n}\norientation added#include \n\n\/\/ ROS\n#include \n\n\/\/ PCL\n#include \n#include \n#include \n\nusing namespace std;\nusing namespace pcl;\nusing namespace rail::pick_and_place;\n\nPointCloudRecognizer::PointCloudRecognizer()\n{\n}\n\nbool PointCloudRecognizer::recognizeObject(rail_manipulation_msgs::SegmentedObject &object,\n const vector &candidates) const\n{\n \/\/ make sure we have some candidates\n if (candidates.empty())\n {\n ROS_WARN(\"Candidate object list is empty. Nothing to compare segmented object to.\");\n return false;\n }\n if (object.point_cloud.data.empty())\n {\n ROS_WARN(\"Segmented object point cloud is empty. Nothing to compare candidate objects to.\");\n return false;\n }\n\n \/\/ convert to a PCL point cloud\n pcl::PCLPointCloud2 object_converter;\n pcl_conversions::toPCL(object.point_cloud, object_converter);\n pcl::PointCloud::Ptr object_point_cloud(new pcl::PointCloud);\n pcl::fromPCLPointCloud2(object_converter, *object_point_cloud);\n\n \/\/ pre-process input cloud\n this->filterPointCloudOutliers(object_point_cloud);\n this->translateToOrigin(object_point_cloud, object.centroid);\n\n \/\/ perform recognition\n double min_score = numeric_limits::infinity();\n size_t min_index;\n Eigen::Matrix4f min_icp_tf;\n bool min_swapped;\n for (size_t i = 0; i < candidates.size(); i++)\n {\n \/\/ convert the candidate point cloud to a PCL point cloud\n pcl::PCLPointCloud2 cur_converter;\n pcl_conversions::toPCL(candidates[i].getPointCloud(), cur_converter);\n pcl::PointCloud::Ptr candidate_point_cloud(new pcl::PointCloud);\n pcl::fromPCLPointCloud2(cur_converter, *candidate_point_cloud);\n\n Eigen::Matrix4f cur_icp_tf;\n bool cur_swapped;\n double score = this->scoreRegistration(candidate_point_cloud, object_point_cloud, cur_icp_tf, cur_swapped);\n if (score < min_score)\n {\n min_score = score;\n min_index = i;\n min_icp_tf = cur_icp_tf;\n min_swapped = cur_swapped;\n }\n }\n\n \/\/ check if there is enough confidence\n if (min_score > SCORE_CONFIDENCE_THRESHOLD)\n {\n return false;\n }\n\n \/\/ fill in recognition information\n object.name = candidates[min_index].getObjectName();\n object.model_id = candidates[min_index].getID();\n object.confidence = min_score;\n object.recognized = true;\n \/\/ TODO infer object orientation\n object.orientation.w = 1.0;\n object.grasps.clear();\n\n \/\/ extract possible grasps for this model\n vector possible_grasps;\n this->transformGrasps(min_icp_tf, min_swapped, object.centroid,\n candidates[min_index].toROSGraspModelMessage().grasps, possible_grasps);\n\n \/\/ sort and remove any grasps with 0 success rates\n vector success_rates;\n for (size_t i = 0; i < possible_grasps.size(); i++)\n {\n double rate = (possible_grasps[i].attempts > 0) ?\n ((double) possible_grasps[i].successes) \/ ((double) possible_grasps[i].attempts) : 0.0;\n\n \/\/ check the success rate\n if (rate > 0)\n {\n \/\/ place it in order\n bool inserted = false;\n for (size_t j = 0; j < success_rates.size(); j++)\n {\n if (rate <= success_rates[j])\n {\n object.grasps.insert(object.grasps.begin() + j, possible_grasps[i].grasp_pose);\n success_rates.insert(success_rates.begin() + j, rate);\n inserted = true;\n break;\n }\n }\n\n if (!inserted)\n {\n object.grasps.push_back(possible_grasps[i].grasp_pose);\n success_rates.push_back(rate);\n }\n }\n }\n\n return true;\n}\n\nvoid PointCloudRecognizer::filterPointCloudOutliers(PointCloud::Ptr pc) const\n{\n \/\/ use a KD tree to search\n pcl::KdTreeFLANN search_tree;\n search_tree.setInputCloud(pc);\n\n \/\/ check each point\n pcl::IndicesPtr to_keep(new vector);\n for (size_t i = 0; i < pc->size(); i++)\n {\n vector indices;\n vector distances;\n \/\/ check how many neighbors pass the test\n int neighbors = search_tree.radiusSearch(pc->at(i), FILTER_SEARCH_RADIUS, indices, distances);\n if (neighbors >= FILTER_MIN_NUM_NEIGHBORS)\n {\n to_keep->push_back(i);\n }\n }\n\n \/\/ extract the point we wish to keep\n pcl::ExtractIndices extract;\n extract.setInputCloud(pc);\n extract.setIndices(to_keep);\n extract.filter(*pc);\n}\n\nvoid PointCloudRecognizer::translateToOrigin(pcl::PointCloud::Ptr pc,\n const geometry_msgs::Point ¢roid) const\n{\n \/\/ transformation matrix\n Eigen::Matrix4f tf;\n tf << 1, 0, 0, -centroid.x,\n 0, 1, 0, -centroid.y,\n 0, 0, 1, -centroid.z,\n 0, 0, 0, 1;\n\n \/\/ transform the point cloud\n pcl::transformPointCloud(*pc, *pc, tf);\n}\n\ndouble PointCloudRecognizer::scoreRegistration(PointCloud::ConstPtr candidate,\n PointCloud::ConstPtr object, Eigen::Matrix4f &icp_tf, bool &icp_swapped) const\n{\n \/\/ use the larger as the base cloud\n icp_swapped = object->size() > candidate->size();\n \/\/ use ICP to for matching\n pcl::IterativeClosestPoint icp;\n if (icp_swapped)\n {\n icp.setInputSource(candidate);\n icp.setInputTarget(object);\n } else\n {\n icp.setInputSource(object);\n icp.setInputTarget(candidate);\n }\n\n \/\/ run ICP on the two point clouds\n pcl::PointCloud::Ptr aligned(new pcl::PointCloud);\n icp.align(*aligned);\n \/\/ extract the final transform\n icp_tf = icp.getFinalTransformation();\n\n \/\/ calculate the distance and color error\n double distance_error = this->calculateRegistrationMetricDistanceError(candidate, aligned);\n double color_error = this->calculateRegistrationMetricOverlap(candidate, aligned);\n\n \/\/ calculate the final weighted result\n double result = ALPHA * (3.0 * distance_error) + (1.0 - ALPHA) * (color_error \/ 100.0);\n return result;\n}\n\ndouble PointCloudRecognizer::calculateRegistrationMetricDistanceError(pcl::PointCloud::ConstPtr base,\n pcl::PointCloud::ConstPtr target) const\n{\n \/\/ search using a KD tree\n pcl::KdTreeFLANN search_tree;\n search_tree.setInputCloud(base);\n\n \/\/ search for the nearest point to each point\n double score = 0;\n for (size_t i = 0; i < target->size(); i++)\n {\n vector indices;\n vector distances;\n search_tree.nearestKSearch(target->at(i), 1, indices, distances);\n score += (double) distances[0];\n }\n\n return score;\n}\n\ndouble PointCloudRecognizer::calculateRegistrationMetricOverlap(pcl::PointCloud::ConstPtr base,\n pcl::PointCloud::ConstPtr target) const\n{\n \/\/ search with a KD tree\n pcl::KdTreeFLANN search_tree;\n search_tree.setInputCloud(base);\n\n \/\/ search each point\n int score = 0;\n float error = 0;\n for (size_t i = 0; i < target->size(); i++)\n {\n \/\/ get the current point\n vector indices;\n vector distances;\n const pcl::PointXYZRGB &search_point = target->at(i);\n \/\/ perform a radius search to see how many neighbors are found\n int neighbors = search_tree.radiusSearch(search_point, OVERLAP_SEARCH_RADIUS, indices, distances);\n \/\/ check if there are enough neighbors\n if (neighbors > 0)\n {\n score++;\n \/\/ check the average RGB color distance\n double rgb_distance = 0;\n for (size_t j = 0; j < indices.size(); j++)\n {\n const pcl::PointXYZRGB &point = base->at(indices[j]);\n rgb_distance += sqrt(pow(search_point.r - point.r, 2) + pow(search_point.g - point.g, 2) +\n pow(search_point.b - point.b, 2));\n }\n \/\/ normalize the distance\n rgb_distance \/= neighbors;\n error += rgb_distance;\n }\n }\n\n \/\/ normalize the error\n error \/= ((double) score);\n return error;\n}\n\nvoid PointCloudRecognizer::transformGrasps(const Eigen::Matrix4f &icp_transform, const bool icp_swapped,\n const geometry_msgs::Point ¢roid,\n const vector &candidate_grasps,\n vector &grasps) const\n{\n \/\/ convert to a TF2 matrix\n tf2::Matrix3x3 rotation(icp_transform(0, 0), icp_transform(0, 1), icp_transform(0, 2),\n icp_transform(1, 0), icp_transform(1, 1), icp_transform(1, 2),\n icp_transform(2, 0), icp_transform(2, 1), icp_transform(2, 2));\n tf2::Vector3 translation(icp_transform(0, 3), icp_transform(1, 3), icp_transform(2, 3));\n tf2::Transform tf_icp(rotation, translation);\n\n \/\/ transform each pose\n for (size_t i = 0; i < candidate_grasps.size(); i++)\n {\n \/\/ convert to tf2 matrix\n const geometry_msgs::Pose &pose = candidate_grasps[i].grasp_pose.pose;\n tf2::Quaternion q_pose(pose.orientation.x, pose.orientation.y, pose.orientation.z, pose.orientation.w);\n tf2::Vector3 v_pose(pose.position.x, pose.position.y, pose.position.z);\n tf2::Transform tf_pose(q_pose, v_pose);\n\n \/\/ push back the basic information\n grasps.push_back(candidate_grasps[i]);\n\n tf2::Transform result;\n if (icp_swapped)\n {\n tf2::Transform result;\n result.mult(tf_icp, tf_pose);\n } else\n {\n \/\/ use the invese for the result\n tf2::Transform inverse = tf_icp.inverse();\n result.mult(inverse, tf_pose);\n }\n\n \/\/ copy over the values\n grasps[i].grasp_pose.pose.position.x = result.getOrigin().x();\n grasps[i].grasp_pose.pose.position.y = result.getOrigin().y();\n grasps[i].grasp_pose.pose.position.z = result.getOrigin().z();\n grasps[i].grasp_pose.pose.orientation.x = result.getRotation().x();\n grasps[i].grasp_pose.pose.orientation.y = result.getRotation().y();\n grasps[i].grasp_pose.pose.orientation.z = result.getRotation().z();\n grasps[i].grasp_pose.pose.orientation.w = result.getRotation().w();\n\n \/\/ correct for the origin transform\n grasps[i].grasp_pose.pose.position.x += centroid.x;\n grasps[i].grasp_pose.pose.position.y += centroid.y;\n grasps[i].grasp_pose.pose.position.z += centroid.z;\n }\n}\n<|endoftext|>"} {"text":"\/*\n Copyright 2005-2007 Adobe Systems Incorporated\n Distributed under the MIT License (see accompanying file LICENSE_1_0_0.txt\n or a copy at http:\/\/stlab.adobe.com\/licenses.html)\n*\/\n\n#include \"platform_listbox.hpp\"\n\n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n\n\nnamespace {\n\n GG::Y RowHeight()\n {\n static GG::Y retval = GG::Y0;\n if (!retval) {\n const GG::Y DEFAULT_MARGIN(8); \/\/ DEFAULT_ROW_HEIGHT from ListBox.cpp, minus the default font's lineskip of 14\n retval = adobe::implementation::DefaultFont()->Lineskip() + DEFAULT_MARGIN;\n }\n return retval;\n }\n\n GG::Y Height(unsigned int lines)\n { return RowHeight() * static_cast(lines) + static_cast(2 * GG::ListBox::BORDER_THICK); }\n\n enum metrics {\n gap = 4 \/\/ Measured as space from listbox to label.\n };\n\n void clear_items(adobe::listbox_t& control)\n {\n assert(control.control_m);\n control.items_m.clear();\n control.control_m->Clear();\n }\n\n void listbox_selection_changed(adobe::listbox_t& listbox, const GG::ListBox::SelectionSet& selections)\n {\n assert(listbox.control_m);\n\n if (listbox.value_proc_m) {\n for (GG::ListBox::SelectionSet::const_iterator it = selections.begin(), end_it = selections.end();\n it != end_it;\n ++it) {\n std::ptrdiff_t index = std::distance(listbox.control_m->begin(), *it);\n if (listbox.value_proc_m)\n listbox.value_proc_m(listbox.items_m.at(index).second);\n }\n }\n\n if (listbox.selection_changed_proc_m)\n listbox.selection_changed_proc_m(listbox, selections);\n }\n\n void listbox_dropped(adobe::listbox_t& listbox, GG::ListBox::iterator row)\n {\n if (listbox.dropped_proc_m)\n listbox.dropped_proc_m(listbox, row);\n }\n\n void listbox_drop_acceptable(adobe::listbox_t& listbox, GG::ListBox::const_iterator row)\n {\n if (listbox.drop_acceptable_proc_m)\n listbox.drop_acceptable_proc_m(listbox, row);\n }\n\n void listbox_left_clicked(adobe::listbox_t& listbox, GG::ListBox::iterator row, const GG::Pt& pt)\n {\n if (listbox.left_clicked_proc_m)\n listbox.left_clicked_proc_m(listbox, row, pt);\n }\n\n void listbox_right_clicked(adobe::listbox_t& listbox, GG::ListBox::iterator row, const GG::Pt& pt)\n {\n if (listbox.right_clicked_proc_m)\n listbox.right_clicked_proc_m(listbox, row, pt);\n }\n\n void listbox_double_clicked(adobe::listbox_t& listbox, GG::ListBox::iterator row)\n {\n if (listbox.double_clicked_proc_m)\n listbox.double_clicked_proc_m(listbox, row);\n }\n\n void listbox_erased(adobe::listbox_t& listbox, GG::ListBox::iterator row)\n {\n if (listbox.erased_proc_m)\n listbox.erased_proc_m(listbox, row);\n }\n\n void listbox_browsed(adobe::listbox_t& listbox, GG::ListBox::iterator row)\n {\n if (listbox.browsed_proc_m)\n listbox.browsed_proc_m(listbox, row);\n }\n\n void message_item_set(adobe::listbox_t& listbox)\n {\n assert(listbox.control_m);\n\n for (adobe::listbox_t::item_set_t::const_iterator\n first = listbox.items_m.begin(), last = listbox.items_m.end();\n first != last;\n ++first) {\n GG::ListBox::Row* row = new GG::ListBox::Row(GG::X1, RowHeight(), \"\");\n row->push_back(\n adobe::implementation::Factory().NewTextControl(GG::X0, GG::Y0, first->first,\n adobe::implementation::DefaultFont(),\n listbox.item_text_color_m, GG::FORMAT_LEFT)\n );\n listbox.control_m->Insert(row);\n }\n }\n\n}\n\nnamespace adobe {\n\n listbox_t::listbox_t(const std::string& name,\n const std::string& alt_text,\n int characters,\n int rows,\n GG::Flags style,\n const item_set_t& items,\n GG::Clr color,\n GG::Clr interior_color,\n GG::Clr label_color,\n GG::Clr item_text_color,\n const std::vector& drop_types,\n name_t signal_id) :\n control_m(0),\n name_m(name, alt_text, 0, GG::FORMAT_LEFT | GG::FORMAT_TOP, label_color),\n alt_text_m(alt_text),\n using_label_m(!name.empty()),\n items_m(items),\n characters_m(characters),\n rows_m(rows),\n style_m(style),\n color_m(color),\n interior_color_m(interior_color),\n item_text_color_m(item_text_color),\n drop_types_m(drop_types),\n signal_id_m(signal_id)\n {}\n\n void listbox_t::measure(extents_t& result)\n {\n assert(control_m);\n\n \/\/\n \/\/ The listbox_t has multiple text items. We need to find the one with\n \/\/ the widest extents (when drawn). Then we can make sure that we get\n \/\/ enough space to draw our largest text item.\n \/\/\n const boost::shared_ptr& font = implementation::DefaultFont();\n\n GG::X width = implementation::CharWidth() * characters_m;\n\n GG::Pt non_client_size = implementation::NonClientSize(*control_m);\n\n result.width() = Value(width + non_client_size.x);\n result.height() = original_height_m;\n GG::Y baseline =\n (static_cast(result.height()) - implementation::CharHeight()) \/ 2 +\n implementation::DefaultFont()->Ascent();\n result.vertical().guide_set_m.push_back(Value(baseline));\n\n \/\/\n \/\/ If we have a label (always on our left side?) then we\n \/\/ need to add the size of the label to our result. We try\n \/\/ to align the label with the listbox by baseline. Which is\n \/\/ kind of what Eve does, so it's bad that we do this\n \/\/ ourselves, really...\n \/\/\n if (!using_label_m)\n return;\n \/\/\n \/\/ We store the height of the label, from this we can\n \/\/ figure out how much to offset it when positioning\n \/\/ the widgets in set_bounds.\n \/\/\n extents_t label_bounds(measure_text(name_m.name_m, font));\n label_bounds.vertical().guide_set_m.push_back(Value(font->Ascent()));\n \/\/\n \/\/ Now we can align the label within the vertical\n \/\/ slice of the result. This doesn't do anything if\n \/\/ the label is shorter than the listbox.\n \/\/\n align_slices(result.vertical(), label_bounds.vertical());\n \/\/\n \/\/ Add the width of the label (plus a gap) to the\n \/\/ resulting width.\n \/\/\n result.width() += gap + label_bounds.width();\n\n \/\/\n \/\/ Add a point-of-interest where the label ends.\n \/\/ We put the label to the left of the listbox.\n \/\/\n result.horizontal().guide_set_m.push_back(label_bounds.width());\n }\n\n void listbox_t::place(const place_data_t& place_data)\n {\n using adobe::place;\n\n assert(control_m);\n\n place_data_t local_place_data(place_data);\n\n if (using_label_m) {\n \/\/\n \/\/ The vertical offset of the label is the geometry's\n \/\/ baseline - the label's baseline.\n \/\/\n assert(place_data.vertical().guide_set_m.empty() == false);\n\n place_data_t label_place_data;\n label_place_data.horizontal().position_m = left(place_data);\n label_place_data.vertical().position_m = top(place_data);\n\n \/\/\n \/\/ The width of the label is the first horizontal\n \/\/ point of interest.\n \/\/\n assert(place_data.horizontal().guide_set_m.empty() == false);\n width(label_place_data) = place_data.horizontal().guide_set_m[0];\n height(label_place_data) = height(place_data);\n\n \/\/\n \/\/ Set the label dimensions.\n \/\/\n place(name_m, label_place_data);\n\n \/\/\n \/\/ Now we need to adjust the position of the listbox\n \/\/ widget.\n \/\/\n long width = gap + adobe::width(label_place_data);\n local_place_data.horizontal().position_m += width;\n adobe::width(local_place_data) -= width;\n }\n\n implementation::set_control_bounds(control_m, local_place_data);\n }\n\n void listbox_t::enable(bool make_enabled)\n {\n assert(control_m);\n control_m->Disable(!make_enabled);\n }\n\n void listbox_t::reset_item_set(const item_t* first, const item_t* last)\n {\n assert(control_m);\n clear_items(*this);\n for (; first != last; ++first) {\n items_m.push_back(*first);\n }\n ::message_item_set(*this);\n }\n\n void listbox_t::display(const model_type& value)\n {\n assert(control_m);\n\n GG::ListBox::iterator it = control_m->begin();\n for (item_set_t::iterator first = items_m.begin(), last = items_m.end();\n first != last;\n ++first, ++it) {\n if ((*first).second == value) {\n control_m->SelectRow(it);\n return;\n }\n }\n }\n\n void listbox_t::monitor(const setter_type& proc)\n {\n assert(control_m);\n value_proc_m = proc;\n }\n\n template <>\n platform_display_type insert(display_t& display,\n platform_display_type& parent,\n listbox_t& element)\n {\n if (element.using_label_m)\n insert(display, parent, element.name_m);\n\n assert(!element.control_m);\n\n int lines = std::min(element.items_m.size(), std::size_t(20u));\n if (1 < element.rows_m)\n lines = element.rows_m;\n element.control_m =\n implementation::Factory().NewListBox(GG::X0, GG::Y0, GG::X1, Height(lines),\n element.color_m, element.interior_color_m);\n element.control_m->SetStyle(element.style_m);\n\n element.original_height_m = Value(element.control_m->Height());\n\n for (std::size_t i = 0; i < element.drop_types_m.size(); ++i) {\n element.control_m->AllowDropType(element.drop_types_m[i]);\n }\n\n GG::Connect(element.control_m->SelChangedSignal,\n boost::bind(&listbox_selection_changed, boost::ref(element), _1));\n\n GG::Connect(element.control_m->DroppedSignal,\n boost::bind(&listbox_dropped, boost::ref(element), _1));\n\n GG::Connect(element.control_m->DropAcceptableSignal,\n boost::bind(&listbox_drop_acceptable, boost::ref(element), _1));\n\n GG::Connect(element.control_m->LeftClickedSignal,\n boost::bind(&listbox_left_clicked, boost::ref(element), _1, _2));\n\n GG::Connect(element.control_m->RightClickedSignal,\n boost::bind(&listbox_right_clicked, boost::ref(element), _1, _2));\n\n GG::Connect(element.control_m->DoubleClickedSignal,\n boost::bind(&listbox_double_clicked, boost::ref(element), _1));\n\n GG::Connect(element.control_m->ErasedSignal,\n boost::bind(&listbox_erased, boost::ref(element), _1));\n\n GG::Connect(element.control_m->BrowsedSignal,\n boost::bind(&listbox_browsed, boost::ref(element), _1));\n\n if (!element.alt_text_m.empty())\n adobe::implementation::set_control_alt_text(element.control_m, element.alt_text_m);\n\n ::message_item_set(element);\n\n return display.insert(parent, element.control_m);\n }\n\n}\nAdded handling of multiple listbox selections when interactingg with the property sheet.\/*\n Copyright 2005-2007 Adobe Systems Incorporated\n Distributed under the MIT License (see accompanying file LICENSE_1_0_0.txt\n or a copy at http:\/\/stlab.adobe.com\/licenses.html)\n*\/\n\n#include \"platform_listbox.hpp\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n\n\nnamespace {\n\n GG::Y RowHeight()\n {\n static GG::Y retval = GG::Y0;\n if (!retval) {\n const GG::Y DEFAULT_MARGIN(8); \/\/ DEFAULT_ROW_HEIGHT from ListBox.cpp, minus the default font's lineskip of 14\n retval = adobe::implementation::DefaultFont()->Lineskip() + DEFAULT_MARGIN;\n }\n return retval;\n }\n\n GG::Y Height(unsigned int lines)\n { return RowHeight() * static_cast(lines) + static_cast(2 * GG::ListBox::BORDER_THICK); }\n\n enum metrics {\n gap = 4 \/\/ Measured as space from listbox to label.\n };\n\n void clear_items(adobe::listbox_t& control)\n {\n assert(control.control_m);\n control.items_m.clear();\n control.control_m->Clear();\n }\n\n void listbox_selection_changed(adobe::listbox_t& listbox, const GG::ListBox::SelectionSet& selections)\n {\n assert(listbox.control_m);\n\n if (listbox.value_proc_m) {\n adobe::any_regular_t value;\n if (selections.size() == 1u) {\n std::ptrdiff_t index = std::distance(listbox.control_m->begin(), *selections.begin());\n value = listbox.items_m.at(index).second;\n } else {\n value.assign(adobe::array_t());\n adobe::array_t& array = value.cast();\n for (GG::ListBox::SelectionSet::const_iterator it = selections.begin(), end_it = selections.end();\n it != end_it;\n ++it) {\n std::ptrdiff_t index = std::distance(listbox.control_m->begin(), *it);\n array.push_back(listbox.items_m.at(index).second);\n }\n }\n listbox.value_proc_m(value);\n }\n\n if (listbox.selection_changed_proc_m)\n listbox.selection_changed_proc_m(listbox, selections);\n }\n\n void listbox_dropped(adobe::listbox_t& listbox, GG::ListBox::iterator row)\n {\n if (listbox.dropped_proc_m)\n listbox.dropped_proc_m(listbox, row);\n }\n\n void listbox_drop_acceptable(adobe::listbox_t& listbox, GG::ListBox::const_iterator row)\n {\n if (listbox.drop_acceptable_proc_m)\n listbox.drop_acceptable_proc_m(listbox, row);\n }\n\n void listbox_left_clicked(adobe::listbox_t& listbox, GG::ListBox::iterator row, const GG::Pt& pt)\n {\n if (listbox.left_clicked_proc_m)\n listbox.left_clicked_proc_m(listbox, row, pt);\n }\n\n void listbox_right_clicked(adobe::listbox_t& listbox, GG::ListBox::iterator row, const GG::Pt& pt)\n {\n if (listbox.right_clicked_proc_m)\n listbox.right_clicked_proc_m(listbox, row, pt);\n }\n\n void listbox_double_clicked(adobe::listbox_t& listbox, GG::ListBox::iterator row)\n {\n if (listbox.double_clicked_proc_m)\n listbox.double_clicked_proc_m(listbox, row);\n }\n\n void listbox_erased(adobe::listbox_t& listbox, GG::ListBox::iterator row)\n {\n if (listbox.erased_proc_m)\n listbox.erased_proc_m(listbox, row);\n }\n\n void listbox_browsed(adobe::listbox_t& listbox, GG::ListBox::iterator row)\n {\n if (listbox.browsed_proc_m)\n listbox.browsed_proc_m(listbox, row);\n }\n\n void message_item_set(adobe::listbox_t& listbox)\n {\n assert(listbox.control_m);\n\n for (adobe::listbox_t::item_set_t::const_iterator\n first = listbox.items_m.begin(), last = listbox.items_m.end();\n first != last;\n ++first) {\n GG::ListBox::Row* row = new GG::ListBox::Row(GG::X1, RowHeight(), \"\");\n row->push_back(\n adobe::implementation::Factory().NewTextControl(GG::X0, GG::Y0, first->first,\n adobe::implementation::DefaultFont(),\n listbox.item_text_color_m, GG::FORMAT_LEFT)\n );\n listbox.control_m->Insert(row);\n }\n }\n\n}\n\nnamespace adobe {\n\n listbox_t::listbox_t(const std::string& name,\n const std::string& alt_text,\n int characters,\n int rows,\n GG::Flags style,\n const item_set_t& items,\n GG::Clr color,\n GG::Clr interior_color,\n GG::Clr label_color,\n GG::Clr item_text_color,\n const std::vector& drop_types,\n name_t signal_id) :\n control_m(0),\n name_m(name, alt_text, 0, GG::FORMAT_LEFT | GG::FORMAT_TOP, label_color),\n alt_text_m(alt_text),\n using_label_m(!name.empty()),\n items_m(items),\n characters_m(characters),\n rows_m(rows),\n style_m(style),\n color_m(color),\n interior_color_m(interior_color),\n item_text_color_m(item_text_color),\n drop_types_m(drop_types),\n signal_id_m(signal_id)\n {}\n\n void listbox_t::measure(extents_t& result)\n {\n assert(control_m);\n\n \/\/\n \/\/ The listbox_t has multiple text items. We need to find the one with\n \/\/ the widest extents (when drawn). Then we can make sure that we get\n \/\/ enough space to draw our largest text item.\n \/\/\n const boost::shared_ptr& font = implementation::DefaultFont();\n\n GG::X width = implementation::CharWidth() * characters_m;\n\n GG::Pt non_client_size = implementation::NonClientSize(*control_m);\n\n result.width() = Value(width + non_client_size.x);\n result.height() = original_height_m;\n GG::Y baseline =\n (static_cast(result.height()) - implementation::CharHeight()) \/ 2 +\n implementation::DefaultFont()->Ascent();\n result.vertical().guide_set_m.push_back(Value(baseline));\n\n \/\/\n \/\/ If we have a label (always on our left side?) then we\n \/\/ need to add the size of the label to our result. We try\n \/\/ to align the label with the listbox by baseline. Which is\n \/\/ kind of what Eve does, so it's bad that we do this\n \/\/ ourselves, really...\n \/\/\n if (!using_label_m)\n return;\n \/\/\n \/\/ We store the height of the label, from this we can\n \/\/ figure out how much to offset it when positioning\n \/\/ the widgets in set_bounds.\n \/\/\n extents_t label_bounds(measure_text(name_m.name_m, font));\n label_bounds.vertical().guide_set_m.push_back(Value(font->Ascent()));\n \/\/\n \/\/ Now we can align the label within the vertical\n \/\/ slice of the result. This doesn't do anything if\n \/\/ the label is shorter than the listbox.\n \/\/\n align_slices(result.vertical(), label_bounds.vertical());\n \/\/\n \/\/ Add the width of the label (plus a gap) to the\n \/\/ resulting width.\n \/\/\n result.width() += gap + label_bounds.width();\n\n \/\/\n \/\/ Add a point-of-interest where the label ends.\n \/\/ We put the label to the left of the listbox.\n \/\/\n result.horizontal().guide_set_m.push_back(label_bounds.width());\n }\n\n void listbox_t::place(const place_data_t& place_data)\n {\n using adobe::place;\n\n assert(control_m);\n\n place_data_t local_place_data(place_data);\n\n if (using_label_m) {\n \/\/\n \/\/ The vertical offset of the label is the geometry's\n \/\/ baseline - the label's baseline.\n \/\/\n assert(place_data.vertical().guide_set_m.empty() == false);\n\n place_data_t label_place_data;\n label_place_data.horizontal().position_m = left(place_data);\n label_place_data.vertical().position_m = top(place_data);\n\n \/\/\n \/\/ The width of the label is the first horizontal\n \/\/ point of interest.\n \/\/\n assert(place_data.horizontal().guide_set_m.empty() == false);\n width(label_place_data) = place_data.horizontal().guide_set_m[0];\n height(label_place_data) = height(place_data);\n\n \/\/\n \/\/ Set the label dimensions.\n \/\/\n place(name_m, label_place_data);\n\n \/\/\n \/\/ Now we need to adjust the position of the listbox\n \/\/ widget.\n \/\/\n long width = gap + adobe::width(label_place_data);\n local_place_data.horizontal().position_m += width;\n adobe::width(local_place_data) -= width;\n }\n\n implementation::set_control_bounds(control_m, local_place_data);\n }\n\n void listbox_t::enable(bool make_enabled)\n {\n assert(control_m);\n control_m->Disable(!make_enabled);\n }\n\n void listbox_t::reset_item_set(const item_t* first, const item_t* last)\n {\n assert(control_m);\n clear_items(*this);\n for (; first != last; ++first) {\n items_m.push_back(*first);\n }\n ::message_item_set(*this);\n }\n\n void listbox_t::display(const model_type& value)\n {\n assert(control_m);\n\n const bool value_is_array = value.type_info() == adobe::type_info();\n\n adobe::array_t single_value;\n if (!value_is_array)\n single_value.push_back(value);\n const adobe::array_t& values = value_is_array ? value.cast() : single_value;\n\n control_m->DeselectAll();\n\n for (adobe::array_t::const_iterator it = values.begin(), end_it = values.end(); it != end_it; ++it) {\n GG::ListBox::iterator row_it = control_m->begin();\n for (item_set_t::iterator first = items_m.begin(), last = items_m.end();\n first != last;\n ++first, ++row_it) {\n if ((*first).second == value) {\n control_m->SelectRow(row_it);\n break;\n }\n }\n }\n }\n\n void listbox_t::monitor(const setter_type& proc)\n {\n assert(control_m);\n value_proc_m = proc;\n }\n\n template <>\n platform_display_type insert(display_t& display,\n platform_display_type& parent,\n listbox_t& element)\n {\n if (element.using_label_m)\n insert(display, parent, element.name_m);\n\n assert(!element.control_m);\n\n int lines = std::min(element.items_m.size(), std::size_t(20u));\n if (1 < element.rows_m)\n lines = element.rows_m;\n element.control_m =\n implementation::Factory().NewListBox(GG::X0, GG::Y0, GG::X1, Height(lines),\n element.color_m, element.interior_color_m);\n element.control_m->SetStyle(element.style_m);\n\n element.original_height_m = Value(element.control_m->Height());\n\n for (std::size_t i = 0; i < element.drop_types_m.size(); ++i) {\n element.control_m->AllowDropType(element.drop_types_m[i]);\n }\n\n GG::Connect(element.control_m->SelChangedSignal,\n boost::bind(&listbox_selection_changed, boost::ref(element), _1));\n\n GG::Connect(element.control_m->DroppedSignal,\n boost::bind(&listbox_dropped, boost::ref(element), _1));\n\n GG::Connect(element.control_m->DropAcceptableSignal,\n boost::bind(&listbox_drop_acceptable, boost::ref(element), _1));\n\n GG::Connect(element.control_m->LeftClickedSignal,\n boost::bind(&listbox_left_clicked, boost::ref(element), _1, _2));\n\n GG::Connect(element.control_m->RightClickedSignal,\n boost::bind(&listbox_right_clicked, boost::ref(element), _1, _2));\n\n GG::Connect(element.control_m->DoubleClickedSignal,\n boost::bind(&listbox_double_clicked, boost::ref(element), _1));\n\n GG::Connect(element.control_m->ErasedSignal,\n boost::bind(&listbox_erased, boost::ref(element), _1));\n\n GG::Connect(element.control_m->BrowsedSignal,\n boost::bind(&listbox_browsed, boost::ref(element), _1));\n\n if (!element.alt_text_m.empty())\n adobe::implementation::set_control_alt_text(element.control_m, element.alt_text_m);\n\n ::message_item_set(element);\n\n return display.insert(parent, element.control_m);\n }\n\n}\n<|endoftext|>"} {"text":"#include \"stdafx.h\"\n#include \"CppUnitTest.h\"\n#include \"..\/DNAnalyzerServer\/Dictionnaire.h\"\n#include \"..\/DNAnalyzerServer\/Mots.h\"\n#include \n#include \n#include \n#include \n\nusing namespace Microsoft::VisualStudio::CppUnitTestFramework;\n\nnamespace DNAnalyzerServerTest\n{\n\tTEST_CLASS(DictionnaireTest)\n\t{\n\tpublic:\n\t\tTEST_METHOD_CLEANUP(CleanUp)\n\t\t{\n\t\t\tMots::RafraichirInstance();\n\t\t\tDictionnaire::RafraichirInstance();\n\t\t}\n\n\t\t\/\/ObtenirInstance\n\t\tTEST_METHOD(ObtenirInstance_NotNull)\n\t\t{\n\t\t\t\/\/ L'instance retourne ne doit pas tre null\n\t\t\tAssert::IsTrue(&(Dictionnaire::ObtenirInstance())!=(Dictionnaire*) nullptr);\n\t\t}\n\n\t\tTEST_METHOD(ObtenirInstance_SameReference)\n\t\t{\n\t\t\t\/\/ L'instance retourne doit toujours tre la mme\n\t\t\tAssert::IsTrue(&(Dictionnaire::ObtenirInstance()) == &(Dictionnaire::ObtenirInstance()));\n\t\t}\n\t\tTEST_METHOD(ObtenirMaladie_KnownMaladie) {\n\n\t\t}\n\t\tTEST_METHOD(ObtenirMaladie_UnKnownMaladie) {\n\n\t\t}\n\t\tTEST_METHOD(ObtenirMaladies_NoMaladies) {\n\t\t\tchar motInexistant[] = \"ATCGINEXISTANT\";\n\t\t\tunsigned int indexMotInexistant = Mots::ObtenirInstance().InsererMot(motInexistant);\n\t\t\tconst unordered_set resultat = Dictionnaire::ObtenirInstance().ObtenirMaladies(indexMotInexistant);\n\t\t\tAssert::AreEqual((int)resultat.size(), 0);\n\t\t}\n\t\tTEST_METHOD(ObtenirMaladies_OneMaladies) {\n\n\t\t}\n\t\tTEST_METHOD(ObtenirMaladies_TwoMaladies) {\n\n\t\t}\n\t\tTEST_METHOD(ObtenirNomMaladies_EmptyDictionnaire) {\n\n\t\t}\n\t\tTEST_METHOD(ObtenirNomMaladies_NotEmptyDictionnaire) {\n\n\t\t}\n\t};\n}ajout de TEST_CLASS_INITIALIZE#include \"stdafx.h\"\n#include \"CppUnitTest.h\"\n#include \"..\/DNAnalyzerServer\/Dictionnaire.h\"\n#include \"..\/DNAnalyzerServer\/Mots.h\"\n#include \n#include \n#include \n#include \n\nusing namespace Microsoft::VisualStudio::CppUnitTestFramework;\n\nnamespace DNAnalyzerServerTest\n{\n\tTEST_CLASS(DictionnaireTest)\n\t{\n\tpublic:\n\t\tTEST_CLASS_INITIALIZE(initialize) {\n\t\t\tMots::RafraichirInstance();\n\t\t\tDictionnaire::RafraichirInstance();\n\t\t}\n\n\t\tTEST_METHOD_CLEANUP(CleanUp)\n\t\t{\n\t\t\tMots::RafraichirInstance();\n\t\t\tDictionnaire::RafraichirInstance();\n\t\t}\n\n\t\t\/\/ObtenirInstance\n\t\tTEST_METHOD(ObtenirInstance_NotNull)\n\t\t{\n\t\t\t\/\/ L'instance retourne ne doit pas tre null\n\t\t\tAssert::IsTrue(&(Dictionnaire::ObtenirInstance())!=(Dictionnaire*) nullptr);\n\t\t}\n\n\t\tTEST_METHOD(ObtenirInstance_SameReference)\n\t\t{\n\t\t\t\/\/ L'instance retourne doit toujours tre la mme\n\t\t\tAssert::IsTrue(&(Dictionnaire::ObtenirInstance()) == &(Dictionnaire::ObtenirInstance()));\n\t\t}\n\t\tTEST_METHOD(ObtenirMaladie_KnownMaladie) {\n\t\t\tAssert::Fail();\/\/ TODO\n\t\t}\n\t\tTEST_METHOD(ObtenirMaladie_UnKnownMaladie) {\n\t\t\tAssert::Fail();\/\/ TODO\n\t\t}\n\t\tTEST_METHOD(ObtenirMaladies_NoMaladies) {\n\t\t\tchar motInexistant[] = \"ATCGINEXISTANT\";\n\t\t\tunsigned int indexMotInexistant = Mots::ObtenirInstance().InsererMot(motInexistant);\n\t\t\tconst unordered_set resultat = Dictionnaire::ObtenirInstance().ObtenirMaladies(indexMotInexistant);\n\t\t\tAssert::AreEqual((int)resultat.size(), 0);\n\t\t}\n\t\tTEST_METHOD(ObtenirMaladies_OneMaladies) {\n\t\t\tAssert::Fail();\/\/ TODO\n\t\t}\n\t\tTEST_METHOD(ObtenirMaladies_TwoMaladies) {\n\t\t\tAssert::Fail();\/\/ TODO\n\t\t}\n\t\tTEST_METHOD(ObtenirNomMaladies_EmptyDictionnaire) {\n\t\t\tAssert::Fail();\/\/ TODO\n\t\t}\n\t\tTEST_METHOD(ObtenirNomMaladies_NotEmptyDictionnaire) {\n\t\t\tAssert::Fail();\/\/ TODO\n\t\t}\n\t};\n}<|endoftext|>"} {"text":"\/*\n * Software License Agreement (BSD License)\n *\n * Copyright (c) 2011, Willow Garage, Inc.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following\n * disclaimer in the documentation and\/or other materials provided\n * with the distribution.\n * * Neither the name of Willow Garage, Inc. nor the names of its\n * contributors may be used to endorse or promote products derived\n * from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n *\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n\ntypedef pcl::PointXYZ PointType;\ntypedef pcl::PointCloud Cloud;\ntypedef Cloud::ConstPtr CloudConstPtr;\ntypedef Cloud::Ptr CloudPtr;\n\n\nvoid\nselfTest ()\n{\n CloudPtr model (new Cloud);\n model->points.push_back (PointType (1,1,0)); \n model->points.push_back (PointType (4,4,0)); \n model->points.push_back (PointType (5,6,0));\n model->points.push_back (PointType (3,3,0));\n model->points.push_back (PointType (6,7,0));\n model->points.push_back (PointType (7,11,0));\n model->points.push_back (PointType (12,15,0));\n model->points.push_back (PointType (7,12,0));\n\n CloudPtr data (new Cloud);\n data->points.push_back (PointType (3,1,0));\n data->points.push_back (PointType (7,4,0));\n data->points.push_back (PointType (9,6,0));\n\n pcl::console::setVerbosityLevel (pcl::console::L_DEBUG); \n \n pcl::NormalDistributionsTransform ndt;\n\n ndt.setMaximumIterations (40);\n ndt.setGridCentre (Eigen::Vector2f (0,0));\n ndt.setGridExtent (Eigen::Vector2f (20,20));\n ndt.setGridStep (Eigen::Vector2f (20,20));\n ndt.setOptimisationStepSize (Eigen::Vector3d (0.4,0.4,0.1));\n ndt.setTransformationEpsilon (1e-9);\n\n ndt.setInputTarget (model);\n ndt.setInputCloud (data);\n\n CloudPtr tmp (new Cloud);\n ndt.align (*tmp);\n std::cout << ndt.getFinalTransformation () << std::endl;\n}\n\n\nint\nmain (int argc, char **argv)\n{\n int iter = 10;\n double grid_step = 3.0;\n double grid_extent = 25.0;\n double optim_step = 1.0;\n\n pcl::console::parse_argument (argc, argv, \"-i\", iter);\n pcl::console::parse_argument (argc, argv, \"-g\", grid_step);\n pcl::console::parse_argument (argc, argv, \"-e\", grid_extent);\n pcl::console::parse_argument (argc, argv, \"-s\", optim_step);\n\n std::vector pcd_indices;\n pcd_indices = pcl::console::parse_file_extension_argument (argc, argv, \".pcd\");\n\n CloudPtr model (new Cloud);\n if (pcl::io::loadPCDFile (argv[pcd_indices[0]], *model) == -1)\n {\n std::cout << \"Could not read file\" << std::endl;\n return -1;\n }\n std::cout << argv[pcd_indices[0]] << \" width: \" << model->width << \" height: \" << model->height << std::endl;\n\n std::string result_filename (argv[pcd_indices[0]]);\n result_filename = result_filename.substr (result_filename.rfind (\"\/\") + 1);\n try\n {\n pcl::io::savePCDFile (result_filename.c_str (), *model);\n std::cout << \"saving first model to \" << result_filename << std::endl;\n }\n catch(pcl::IOException& e)\n {\n std::cerr << e.what() << std::endl;\n }\n\n Eigen::Matrix4f t (Eigen::Matrix4f::Identity ());\n\n for (size_t i = 1; i < pcd_indices.size (); i++)\n {\n CloudPtr data (new Cloud);\n if (pcl::io::loadPCDFile (argv[pcd_indices[i]], *data) == -1)\n {\n std::cout << \"Could not read file\" << std::endl;\n return -1;\n }\n std::cout << argv[pcd_indices[i]] << \" width: \" << data->width << \" height: \" << data->height << std::endl;\n\n \/\/pcl::console::setVerbosityLevel(pcl::console::L_DEBUG);\n\n pcl::NormalDistributionsTransform ndt;\n\n ndt.setMaximumIterations (iter);\n ndt.setGridCentre (Eigen::Vector2f (15,0));\n ndt.setGridExtent (Eigen::Vector2f (grid_extent,grid_extent));\n ndt.setGridStep (Eigen::Vector2f (grid_step,grid_step));\n ndt.setOptimisationStepSize (optim_step);\n ndt.setTransformationEpsilon (1e-5);\n\n ndt.setInputTarget (model);\n ndt.setInputCloud (data);\n\n CloudPtr tmp (new Cloud);\n ndt.align (*tmp);\n\n t = ndt.getFinalTransformation () * t;\n\n pcl::transformPointCloud (*data, *tmp, t);\n\n std::cout << ndt.getFinalTransformation () << std::endl;\n\n *model = *data;\n\n try\n {\n std::string result_filename (argv[pcd_indices[i]]);\n result_filename = result_filename.substr (result_filename.rfind (\"\/\") + 1);\n pcl::io::savePCDFileBinary (result_filename.c_str (), *tmp);\n std::cout << \"saving result to \" << result_filename << std::endl;\n }\n catch(pcl::IOException& e)\n {\n std::cerr << e.what() << std::endl;\n }\n }\n\n return 0;\n}\noptimisation -> optimization\/*\n * Software License Agreement (BSD License)\n *\n * Copyright (c) 2011, Willow Garage, Inc.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following\n * disclaimer in the documentation and\/or other materials provided\n * with the distribution.\n * * Neither the name of Willow Garage, Inc. nor the names of its\n * contributors may be used to endorse or promote products derived\n * from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n *\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n\ntypedef pcl::PointXYZ PointType;\ntypedef pcl::PointCloud Cloud;\ntypedef Cloud::ConstPtr CloudConstPtr;\ntypedef Cloud::Ptr CloudPtr;\n\n\nvoid\nselfTest ()\n{\n CloudPtr model (new Cloud);\n model->points.push_back (PointType (1,1,0)); \n model->points.push_back (PointType (4,4,0)); \n model->points.push_back (PointType (5,6,0));\n model->points.push_back (PointType (3,3,0));\n model->points.push_back (PointType (6,7,0));\n model->points.push_back (PointType (7,11,0));\n model->points.push_back (PointType (12,15,0));\n model->points.push_back (PointType (7,12,0));\n\n CloudPtr data (new Cloud);\n data->points.push_back (PointType (3,1,0));\n data->points.push_back (PointType (7,4,0));\n data->points.push_back (PointType (9,6,0));\n\n pcl::console::setVerbosityLevel (pcl::console::L_DEBUG); \n \n pcl::NormalDistributionsTransform ndt;\n\n ndt.setMaximumIterations (40);\n ndt.setGridCentre (Eigen::Vector2f (0,0));\n ndt.setGridExtent (Eigen::Vector2f (20,20));\n ndt.setGridStep (Eigen::Vector2f (20,20));\n ndt.setOptimizationStepSize (Eigen::Vector3d (0.4,0.4,0.1));\n ndt.setTransformationEpsilon (1e-9);\n\n ndt.setInputTarget (model);\n ndt.setInputCloud (data);\n\n CloudPtr tmp (new Cloud);\n ndt.align (*tmp);\n std::cout << ndt.getFinalTransformation () << std::endl;\n}\n\n\nint\nmain (int argc, char **argv)\n{\n int iter = 10;\n double grid_step = 3.0;\n double grid_extent = 25.0;\n double optim_step = 1.0;\n\n pcl::console::parse_argument (argc, argv, \"-i\", iter);\n pcl::console::parse_argument (argc, argv, \"-g\", grid_step);\n pcl::console::parse_argument (argc, argv, \"-e\", grid_extent);\n pcl::console::parse_argument (argc, argv, \"-s\", optim_step);\n\n std::vector pcd_indices;\n pcd_indices = pcl::console::parse_file_extension_argument (argc, argv, \".pcd\");\n\n CloudPtr model (new Cloud);\n if (pcl::io::loadPCDFile (argv[pcd_indices[0]], *model) == -1)\n {\n std::cout << \"Could not read file\" << std::endl;\n return -1;\n }\n std::cout << argv[pcd_indices[0]] << \" width: \" << model->width << \" height: \" << model->height << std::endl;\n\n std::string result_filename (argv[pcd_indices[0]]);\n result_filename = result_filename.substr (result_filename.rfind (\"\/\") + 1);\n try\n {\n pcl::io::savePCDFile (result_filename.c_str (), *model);\n std::cout << \"saving first model to \" << result_filename << std::endl;\n }\n catch(pcl::IOException& e)\n {\n std::cerr << e.what() << std::endl;\n }\n\n Eigen::Matrix4f t (Eigen::Matrix4f::Identity ());\n\n for (size_t i = 1; i < pcd_indices.size (); i++)\n {\n CloudPtr data (new Cloud);\n if (pcl::io::loadPCDFile (argv[pcd_indices[i]], *data) == -1)\n {\n std::cout << \"Could not read file\" << std::endl;\n return -1;\n }\n std::cout << argv[pcd_indices[i]] << \" width: \" << data->width << \" height: \" << data->height << std::endl;\n\n \/\/pcl::console::setVerbosityLevel(pcl::console::L_DEBUG);\n\n pcl::NormalDistributionsTransform ndt;\n\n ndt.setMaximumIterations (iter);\n ndt.setGridCentre (Eigen::Vector2f (15,0));\n ndt.setGridExtent (Eigen::Vector2f (grid_extent,grid_extent));\n ndt.setGridStep (Eigen::Vector2f (grid_step,grid_step));\n ndt.setOptimizationStepSize (optim_step);\n ndt.setTransformationEpsilon (1e-5);\n\n ndt.setInputTarget (model);\n ndt.setInputCloud (data);\n\n CloudPtr tmp (new Cloud);\n ndt.align (*tmp);\n\n t = ndt.getFinalTransformation () * t;\n\n pcl::transformPointCloud (*data, *tmp, t);\n\n std::cout << ndt.getFinalTransformation () << std::endl;\n\n *model = *data;\n\n try\n {\n std::string result_filename (argv[pcd_indices[i]]);\n result_filename = result_filename.substr (result_filename.rfind (\"\/\") + 1);\n pcl::io::savePCDFileBinary (result_filename.c_str (), *tmp);\n std::cout << \"saving result to \" << result_filename << std::endl;\n }\n catch(pcl::IOException& e)\n {\n std::cerr << e.what() << std::endl;\n }\n }\n\n return 0;\n}\n<|endoftext|>"} {"text":"\n#pragma once\n\n#include \"geometry\/symmetric_bilinear_form.hpp\"\n\n#include \n\nnamespace principia {\nnamespace geometry {\nnamespace internal_symmetric_bilinear_form {\n\ntemplate\nSymmetricBilinearForm& SymmetricBilinearForm::\noperator+=(SymmetricBilinearForm const& right) {\n return *this = *this + right;\n}\n\ntemplate\nSymmetricBilinearForm& SymmetricBilinearForm::\noperator-=(SymmetricBilinearForm const& right) {\n return *this = *this - right;\n}\n\ntemplate\nSymmetricBilinearForm& SymmetricBilinearForm::\noperator*=(double const right) {\n return *this = *this * right;\n}\n\ntemplate\nSymmetricBilinearForm& SymmetricBilinearForm::\noperator\/=(double const right) {\n return *this = *this \/ right;\n}\n\ntemplate\ntemplate\nProduct>\nSymmetricBilinearForm::operator()(\n Vector const& left,\n Vector const& right) const {\n return InnerProduct(left, *this * right);\n}\n\ntemplate\nvoid SymmetricBilinearForm::WriteToMessage(\n not_null message) const {\n Frame::WriteToMessage(message->mutable_frame());\n matrix_.WriteToMessage(message->mutable_matrix());\n}\n\ntemplate\nSymmetricBilinearForm\nSymmetricBilinearForm::ReadFromMessage(\n serialization::SymmetricBilinearForm const& message) {\n Frame::ReadFromMessage(message.frame());\n return SymmetricBilinearForm(\n R3x3Matrix::ReadFromMessage(message.matrix()));\n}\n\ntemplate\nSymmetricBilinearForm::SymmetricBilinearForm(\n R3x3Matrix const& matrix) : matrix_(matrix) {\n DCHECK_EQ(matrix_(0, 1), matrix_(1, 0));\n DCHECK_EQ(matrix_(0, 2), matrix_(2, 0));\n DCHECK_EQ(matrix_(1, 2), matrix_(2, 1));\n}\n\ntemplate\nSymmetricBilinearForm::SymmetricBilinearForm(\n R3x3Matrix&& matrix) : matrix_(std::move(matrix)) {\n DCHECK_EQ(matrix_(0, 1), matrix_(1, 0));\n DCHECK_EQ(matrix_(0, 2), matrix_(2, 0));\n DCHECK_EQ(matrix_(1, 2), matrix_(2, 1));\n}\n\ntemplate\nSymmetricBilinearForm const& InnerProductForm() {\n static auto const identity =\n SymmetricBilinearForm(R3x3Matrix::Identity());\n return identity;\n}\n\ntemplate\nSymmetricBilinearForm operator+(\n SymmetricBilinearForm const& right) {\n return SymmetricBilinearForm(right.matrix_);\n}\n\ntemplate\nSymmetricBilinearForm operator-(\n SymmetricBilinearForm const& right) {\n return SymmetricBilinearForm(-right.matrix_);\n}\n\ntemplate\nSymmetricBilinearForm operator+(\n SymmetricBilinearForm const& left,\n SymmetricBilinearForm const& right) {\n return SymmetricBilinearForm(left.matrix_ + right.matrix_);\n}\n\ntemplate\nSymmetricBilinearForm operator-(\n SymmetricBilinearForm const& left,\n SymmetricBilinearForm const& right) {\n return SymmetricBilinearForm(left.matrix_ - right.matrix_);\n}\n\ntemplate\nSymmetricBilinearForm operator*(\n double const left,\n SymmetricBilinearForm const& right) {\n return SymmetricBilinearForm(left * right.matrix_);\n}\n\ntemplate\nSymmetricBilinearForm operator*(\n SymmetricBilinearForm const& left,\n double const right) {\n return SymmetricBilinearForm(left.matrix_ * right);\n}\n\ntemplate\nSymmetricBilinearForm operator\/(\n SymmetricBilinearForm const& left,\n double const right) {\n return SymmetricBilinearForm(left.matrix_ \/ right);\n}\n\ntemplate\nVector, Frame> operator*(\n SymmetricBilinearForm const& left,\n Vector const& right) {\n return Vector, Frame>(left.matrix_ *\n right.coordinates());\n}\n\ntemplate\nVector, Frame> operator*(\n Vector const& left,\n SymmetricBilinearForm const& right) {\n return Vector, Frame>(left.coordinates() *\n right.matrix_);\n}\n\ntemplate\nSymmetricBilinearForm, Frame> SymmetricProduct(\n Vector const& left,\n Vector const& right) {\n return SymmetricBilinearForm, Frame>(\n 0.5 * (KroneckerProduct(left.coordinates(), right.coordinates()) +\n KroneckerProduct(right.coordinates(), left.coordinates())));\n}\n\ntemplate\nBivector, Frame> Anticommutator(\n SymmetricBilinearForm const& form,\n Bivector const& bivector) {\n R3x3Matrix const multiplier = R3x3Matrix::Identity() *\n form.matrix_.Trace() - form.matrix_;\n return Bivector, Frame>(multiplier *\n bivector.coordinates());\n}\n\ntemplate\nbool operator==(SymmetricBilinearForm const& left,\n SymmetricBilinearForm const& right) {\n return left.matrix_ == right.matrix_;\n}\n\ntemplate\nbool operator!=(SymmetricBilinearForm const& left,\n SymmetricBilinearForm const& right) {\n return left.matrix_ != right.matrix_;\n}\n\ntemplate\nstd::string DebugString(SymmetricBilinearForm const& form) {\n return DebugString(form.matrix_);\n}\n\ntemplate\nstd::ostream& operator<<(std::ostream& out,\n SymmetricBilinearForm const& form) {\n out << form.matrix_;\n return out;\n}\n\n} \/\/ namespace internal_symmetric_bilinear_form\n} \/\/ namespace geometry\n} \/\/ namespace principia\nAfter egg's review.\n#pragma once\n\n#include \"geometry\/symmetric_bilinear_form.hpp\"\n\n#include \n\nnamespace principia {\nnamespace geometry {\nnamespace internal_symmetric_bilinear_form {\n\ntemplate\nSymmetricBilinearForm& SymmetricBilinearForm::\noperator+=(SymmetricBilinearForm const& right) {\n return *this = *this + right;\n}\n\ntemplate\nSymmetricBilinearForm& SymmetricBilinearForm::\noperator-=(SymmetricBilinearForm const& right) {\n return *this = *this - right;\n}\n\ntemplate\nSymmetricBilinearForm& SymmetricBilinearForm::\noperator*=(double const right) {\n return *this = *this * right;\n}\n\ntemplate\nSymmetricBilinearForm& SymmetricBilinearForm::\noperator\/=(double const right) {\n return *this = *this \/ right;\n}\n\ntemplate\ntemplate\nProduct>\nSymmetricBilinearForm::operator()(\n Vector const& left,\n Vector const& right) const {\n return InnerProduct(left, *this * right);\n}\n\ntemplate\nvoid SymmetricBilinearForm::WriteToMessage(\n not_null message) const {\n Frame::WriteToMessage(message->mutable_frame());\n matrix_.WriteToMessage(message->mutable_matrix());\n}\n\ntemplate\nSymmetricBilinearForm\nSymmetricBilinearForm::ReadFromMessage(\n serialization::SymmetricBilinearForm const& message) {\n Frame::ReadFromMessage(message.frame());\n return SymmetricBilinearForm(\n R3x3Matrix::ReadFromMessage(message.matrix()));\n}\n\ntemplate\nSymmetricBilinearForm::SymmetricBilinearForm(\n R3x3Matrix const& matrix) : matrix_(matrix) {\n DCHECK_EQ(matrix_(0, 1), matrix_(1, 0));\n DCHECK_EQ(matrix_(0, 2), matrix_(2, 0));\n DCHECK_EQ(matrix_(1, 2), matrix_(2, 1));\n}\n\ntemplate\nSymmetricBilinearForm::SymmetricBilinearForm(\n R3x3Matrix&& matrix) : matrix_(std::move(matrix)) {\n DCHECK_EQ(matrix_(0, 1), matrix_(1, 0));\n DCHECK_EQ(matrix_(0, 2), matrix_(2, 0));\n DCHECK_EQ(matrix_(1, 2), matrix_(2, 1));\n}\n\ntemplate\nSymmetricBilinearForm const& InnerProductForm() {\n static auto const identity =\n SymmetricBilinearForm(R3x3Matrix::Identity());\n return identity;\n}\n\ntemplate\nSymmetricBilinearForm operator+(\n SymmetricBilinearForm const& right) {\n return SymmetricBilinearForm(right.matrix_);\n}\n\ntemplate\nSymmetricBilinearForm operator-(\n SymmetricBilinearForm const& right) {\n return SymmetricBilinearForm(-right.matrix_);\n}\n\ntemplate\nSymmetricBilinearForm operator+(\n SymmetricBilinearForm const& left,\n SymmetricBilinearForm const& right) {\n return SymmetricBilinearForm(left.matrix_ + right.matrix_);\n}\n\ntemplate\nSymmetricBilinearForm operator-(\n SymmetricBilinearForm const& left,\n SymmetricBilinearForm const& right) {\n return SymmetricBilinearForm(left.matrix_ - right.matrix_);\n}\n\ntemplate\nSymmetricBilinearForm operator*(\n double const left,\n SymmetricBilinearForm const& right) {\n return SymmetricBilinearForm(left * right.matrix_);\n}\n\ntemplate\nSymmetricBilinearForm operator*(\n SymmetricBilinearForm const& left,\n double const right) {\n return SymmetricBilinearForm(left.matrix_ * right);\n}\n\ntemplate\nSymmetricBilinearForm operator\/(\n SymmetricBilinearForm const& left,\n double const right) {\n return SymmetricBilinearForm(left.matrix_ \/ right);\n}\n\ntemplate\nVector, Frame> operator*(\n SymmetricBilinearForm const& left,\n Vector const& right) {\n return Vector, Frame>(left.matrix_ *\n right.coordinates());\n}\n\ntemplate\nVector, Frame> operator*(\n Vector const& left,\n SymmetricBilinearForm const& right) {\n return Vector, Frame>(left.coordinates() *\n right.matrix_);\n}\n\ntemplate\nSymmetricBilinearForm, Frame> SymmetricProduct(\n Vector const& left,\n Vector const& right) {\n return SymmetricBilinearForm, Frame>(\n 0.5 * (KroneckerProduct(left.coordinates(), right.coordinates()) +\n KroneckerProduct(right.coordinates(), left.coordinates())));\n}\n\ntemplate\nBivector, Frame> Anticommutator(\n SymmetricBilinearForm const& form,\n Bivector const& bivector) {\n return Bivector, Frame>(\n form.matrix_.Trace() * bivector.coordinates() -\n form.matrix_ * bivector.coordinates());\n}\n\ntemplate\nbool operator==(SymmetricBilinearForm const& left,\n SymmetricBilinearForm const& right) {\n return left.matrix_ == right.matrix_;\n}\n\ntemplate\nbool operator!=(SymmetricBilinearForm const& left,\n SymmetricBilinearForm const& right) {\n return left.matrix_ != right.matrix_;\n}\n\ntemplate\nstd::string DebugString(SymmetricBilinearForm const& form) {\n return DebugString(form.matrix_);\n}\n\ntemplate\nstd::ostream& operator<<(std::ostream& out,\n SymmetricBilinearForm const& form) {\n out << form.matrix_;\n return out;\n}\n\n} \/\/ namespace internal_symmetric_bilinear_form\n} \/\/ namespace geometry\n} \/\/ namespace principia\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: SlideSorterView.hxx,v $\n *\n * $Revision: 1.9 $\n *\n * last change: $Author: vg $ $Date: 2006-04-06 16:25:20 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef SD_SLIDESORTER_SLIDE_SORTER_VIEW_HXX\n#define SD_SLIDESORTER_SLIDE_SORTER_VIEW_HXX\n\n#include \"View.hxx\"\n\n#include \"model\/SlsSharedPageDescriptor.hxx\"\n\n#include \n\n#ifndef _PRESENTATION_HXX\n#include \"pres.hxx\"\n#endif\n\n#ifndef _SV_GEN_HXX\n#include \n#endif\n#include \n#include \n\nclass Point;\n\nnamespace sdr { namespace contact {\nclass ObjectContact;\n} }\n\nnamespace sd { namespace slidesorter {\nclass SlideSorterViewShell;\n} }\n\nnamespace sd { namespace slidesorter { namespace controller {\nclass SlideSorterController;\n} } }\n\nnamespace sd { namespace slidesorter { namespace cache {\nclass PageCache;\n} } }\n\nnamespace sd { namespace slidesorter { namespace model {\nclass SlideSorterModel;\n} } }\n\nnamespace sd { namespace slidesorter { namespace view {\n\nclass Layouter;\nclass ViewOverlay;\n\n\nclass SlideSorterView\n : public View\n{\npublic:\n \/** Create a new view for the slide sorter.\n @param rViewShell\n This reference is simply passed to the base class and not used\n by this class.\n\n *\/\n SlideSorterView (\n SlideSorterViewShell& rViewShell,\n model::SlideSorterModel& rModel);\n\n virtual ~SlideSorterView (void);\n\n void RequestRepaint (void);\n void RequestRepaint (const model::SharedPageDescriptor& rDescriptor);\n\n Rectangle GetModelArea (void);\n\n enum CoordinateSystem { CS_SCREEN, CS_MODEL };\n enum BoundingBoxType { BBT_SHAPE, BBT_INFO };\n\n \/** Return the rectangle that bounds the page object represented by the\n given page descriptor.\n @param rDescriptor\n The descriptor of the page for which to return the bounding box.\n @param eCoordinateSystem\n Specifies whether to return the screen or model coordinates.\n @param eBoundingBoxType\n Specifies whether to return the bounding box of only the page\n object or the one that additionally includes other displayed\n information like page name and fader symbol.\n *\/\n Rectangle GetPageBoundingBox (\n const model::SharedPageDescriptor& rpDescriptor,\n CoordinateSystem eCoordinateSystem,\n BoundingBoxType eBoundingBoxType) const;\n\n \/** Return the rectangle that bounds the page object represented by the\n given page index .\n @param nIndex\n The index of the page for which to return the bounding box.\n @param eCoordinateSystem\n Specifies whether to return the screen or model coordinates.\n @param eBoundingBoxType\n Specifies whether to return the bounding box of only the page\n object or the one that additionally includes other displayed\n information like page name and fader symbol.\n *\/\n Rectangle GetPageBoundingBox (\n sal_Int32 nIndex,\n CoordinateSystem eCoordinateSystem,\n BoundingBoxType eBoundingBoxType) const;\n\n \/** Return the index of the page that is rendered at the given position.\n @param rPosition\n The position is expected to be in pixel coordinates.\n @return\n The returned index is -1 when there is no page object at the\n given position.\n *\/\n sal_Int32 GetPageIndexAtPoint (const Point& rPosition) const;\n sal_Int32 GetFadePageIndexAtPoint (const Point& rPosition) const;\n\n view::Layouter& GetLayouter (void);\n\n virtual void ModelHasChanged (void);\n\n \/** This method is typically called before a model change takes place.\n All references to model data are released. PostModelChange() has to\n be called to complete the handling of the model change. When the\n calls to Pre- and PostModelChange() are very close to each other you\n may call HandleModelChange() instead.\n *\/\n void PreModelChange (void);\n\n \/** This method is typically called after a model change took place.\n References to model data are re-allocated. Call this method only\n after PreModelChange() has been called.\n *\/\n void PostModelChange (void);\n\n \/** This method is a convenience function that simply calls\n PreModelChange() and then PostModelChange().\n *\/\n void HandleModelChange (void);\n\n virtual void Resize (void);\n virtual void CompleteRedraw (\n OutputDevice* pDevice,\n const Region& rPaintArea,\n ::sdr::contact::ViewObjectContactRedirector* pRedirector = 0L);\n virtual void InvalidateOneWin (\n ::Window& rWindow);\n virtual void InvalidateOneWin (\n ::Window& rWindow,\n const Rectangle& rPaintArea );\n\n void Layout (void);\n \/** This tells the view that it has to re-determine the visibility of\n the page objects before painting them the next time.\n *\/\n void InvalidatePageObjectVisibilities (void);\n\n \/** Return the window to which this view renders its output.\n *\/\n ::sd::Window* GetWindow (void) const;\n\n\n ::boost::shared_ptr GetPreviewCache (void);\n\n view::ViewOverlay& GetOverlay (void);\n\n \/** Set the bounding box of the insertion marker in model coordinates.\n\n It will be painted as a dark rectangle that fills the given box.\n *\/\n void SetInsertionMarker (const Rectangle& rBBox);\n\n \/** Specify whether the insertion marker will be painted or not.\n *\/\n void SetInsertionMarkerVisibility (bool bVisible);\n\n \/** Set the size and position of the selection rectangle.\n\n It will be painted as a dashed rectangle.\n *\/\n void SetSelectionRectangle (const Rectangle& rBox);\n\n \/** Specify whether the selection rectangle will be painted or not.\n *\/\n void SetSelectionRectangleVisibility (bool bVisible);\n\n ::sdr::contact::ObjectContact& GetObjectContact (void) const;\n\n typedef ::std::pair PageRange;\n \/** Return the range of currently visible page objects including the\n first and last one in that range.\n @return\n The returned pair of page object indices is empty when the\n second index is lower than the first.\n *\/\n PageRange GetVisiblePageRange (void);\n\n \/** Return the size of the area where the page numbers are displayed.\n @return\n The returned size is given in model coordinates.\n *\/\n Size GetPageNumberAreaModelSize (void) const;\n\n \/** Return the size of the border around the original SdrPageObj.\n *\/\n SvBorder GetModelBorder (void) const;\n\nprotected:\n virtual void Notify (SfxBroadcaster& rBroadcaster, const SfxHint& rHint);\n\nprivate:\n model::SlideSorterModel& mrModel;\n \/\/\/ This model is used for the maPage object.\n SdrModel maPageModel;\n \/** This page acts as container for the page objects that represent the\n pages of the document that is represented by the SlideSorterModel.\n *\/\n SdrPage* mpPage;\n ::std::auto_ptr mpLayouter;\n bool mbPageObjectVisibilitiesValid;\n ::boost::shared_ptr mpPreviewCache;\n ::std::auto_ptr mpViewOverlay;\n\n int mnFirstVisiblePageIndex;\n int mnLastVisiblePageIndex;\n\n SvBorder maPagePixelBorder;\n\n bool mbModelChangedWhileModifyEnabled;\n\n Size maPreviewSize;\n\n bool mbPreciousFlagUpdatePending;\n\n Size maPageNumberAreaModelSize;\n SvBorder maModelBorder;\n\n \/** Adapt the coordinates of the given bounding box according to the\n other parameters.\n @param rModelPageObjectBoundingBox\n Bounding box given in model coordinates that bounds only the\n page object.\n @param eCoordinateSystem\n When CS_SCREEN is given then the bounding box is converted into\n screen coordinates.\n @param eBoundingBoxType\n When BBT_INFO is given then the bounding box is made larger so\n that it encloses all relevant displayed information.\n *\/\n void AdaptBoundingBox (\n Rectangle& rModelPageObjectBoundingBox,\n CoordinateSystem eCoordinateSystem,\n BoundingBoxType eBoundingBoxType) const;\n\n \/** Determine the visibility of all page objects.\n *\/\n void DeterminePageObjectVisibilities (void);\n\n controller::SlideSorterController& GetController (void);\n\n \/** Update the page borders used by the layouter by using those returned\n by the first page. Call this function when the model changes,\n especially when the number of pages changes, or when the window is\n resized as the borders may be device dependent.\n *\/\n void UpdatePageBorders (void);\n\n void UpdatePreciousFlags (void);\n};\n\n\n} } } \/\/ end of namespace ::sd::slidesorter::view\n\n#endif\nINTEGRATION: CWS impress92 (1.9.8); FILE MERGED 2006\/04\/26 13:14:09 af 1.9.8.1: #i63668# Added HandleDrawModeChange() method.\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: SlideSorterView.hxx,v $\n *\n * $Revision: 1.10 $\n *\n * last change: $Author: rt $ $Date: 2006-05-05 10:06:32 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef SD_SLIDESORTER_SLIDE_SORTER_VIEW_HXX\n#define SD_SLIDESORTER_SLIDE_SORTER_VIEW_HXX\n\n#include \"View.hxx\"\n\n#include \"model\/SlsSharedPageDescriptor.hxx\"\n\n#include \n\n#ifndef _PRESENTATION_HXX\n#include \"pres.hxx\"\n#endif\n\n#ifndef _SV_GEN_HXX\n#include \n#endif\n#include \n#include \n\nclass Point;\n\nnamespace sdr { namespace contact {\nclass ObjectContact;\n} }\n\nnamespace sd { namespace slidesorter {\nclass SlideSorterViewShell;\n} }\n\nnamespace sd { namespace slidesorter { namespace controller {\nclass SlideSorterController;\n} } }\n\nnamespace sd { namespace slidesorter { namespace cache {\nclass PageCache;\n} } }\n\nnamespace sd { namespace slidesorter { namespace model {\nclass SlideSorterModel;\n} } }\n\nnamespace sd { namespace slidesorter { namespace view {\n\nclass Layouter;\nclass ViewOverlay;\n\n\nclass SlideSorterView\n : public View\n{\npublic:\n \/** Create a new view for the slide sorter.\n @param rViewShell\n This reference is simply passed to the base class and not used\n by this class.\n\n *\/\n SlideSorterView (\n SlideSorterViewShell& rViewShell,\n model::SlideSorterModel& rModel);\n\n virtual ~SlideSorterView (void);\n\n void RequestRepaint (void);\n void RequestRepaint (const model::SharedPageDescriptor& rDescriptor);\n\n Rectangle GetModelArea (void);\n\n enum CoordinateSystem { CS_SCREEN, CS_MODEL };\n enum BoundingBoxType { BBT_SHAPE, BBT_INFO };\n\n \/** Return the rectangle that bounds the page object represented by the\n given page descriptor.\n @param rDescriptor\n The descriptor of the page for which to return the bounding box.\n @param eCoordinateSystem\n Specifies whether to return the screen or model coordinates.\n @param eBoundingBoxType\n Specifies whether to return the bounding box of only the page\n object or the one that additionally includes other displayed\n information like page name and fader symbol.\n *\/\n Rectangle GetPageBoundingBox (\n const model::SharedPageDescriptor& rpDescriptor,\n CoordinateSystem eCoordinateSystem,\n BoundingBoxType eBoundingBoxType) const;\n\n \/** Return the rectangle that bounds the page object represented by the\n given page index .\n @param nIndex\n The index of the page for which to return the bounding box.\n @param eCoordinateSystem\n Specifies whether to return the screen or model coordinates.\n @param eBoundingBoxType\n Specifies whether to return the bounding box of only the page\n object or the one that additionally includes other displayed\n information like page name and fader symbol.\n *\/\n Rectangle GetPageBoundingBox (\n sal_Int32 nIndex,\n CoordinateSystem eCoordinateSystem,\n BoundingBoxType eBoundingBoxType) const;\n\n \/** Return the index of the page that is rendered at the given position.\n @param rPosition\n The position is expected to be in pixel coordinates.\n @return\n The returned index is -1 when there is no page object at the\n given position.\n *\/\n sal_Int32 GetPageIndexAtPoint (const Point& rPosition) const;\n sal_Int32 GetFadePageIndexAtPoint (const Point& rPosition) const;\n\n view::Layouter& GetLayouter (void);\n\n virtual void ModelHasChanged (void);\n\n \/** This method is typically called before a model change takes place.\n All references to model data are released. PostModelChange() has to\n be called to complete the handling of the model change. When the\n calls to Pre- and PostModelChange() are very close to each other you\n may call HandleModelChange() instead.\n *\/\n void PreModelChange (void);\n\n \/** This method is typically called after a model change took place.\n References to model data are re-allocated. Call this method only\n after PreModelChange() has been called.\n *\/\n void PostModelChange (void);\n\n \/** This method is a convenience function that simply calls\n PreModelChange() and then PostModelChange().\n *\/\n void HandleModelChange (void);\n\n void HandleDrawModeChange (void);\n\n virtual void Resize (void);\n virtual void CompleteRedraw (\n OutputDevice* pDevice,\n const Region& rPaintArea,\n ::sdr::contact::ViewObjectContactRedirector* pRedirector = 0L);\n virtual void InvalidateOneWin (\n ::Window& rWindow);\n virtual void InvalidateOneWin (\n ::Window& rWindow,\n const Rectangle& rPaintArea );\n\n void Layout (void);\n \/** This tells the view that it has to re-determine the visibility of\n the page objects before painting them the next time.\n *\/\n void InvalidatePageObjectVisibilities (void);\n\n \/** Return the window to which this view renders its output.\n *\/\n ::sd::Window* GetWindow (void) const;\n\n\n ::boost::shared_ptr GetPreviewCache (void);\n\n view::ViewOverlay& GetOverlay (void);\n\n \/** Set the bounding box of the insertion marker in model coordinates.\n\n It will be painted as a dark rectangle that fills the given box.\n *\/\n void SetInsertionMarker (const Rectangle& rBBox);\n\n \/** Specify whether the insertion marker will be painted or not.\n *\/\n void SetInsertionMarkerVisibility (bool bVisible);\n\n \/** Set the size and position of the selection rectangle.\n\n It will be painted as a dashed rectangle.\n *\/\n void SetSelectionRectangle (const Rectangle& rBox);\n\n \/** Specify whether the selection rectangle will be painted or not.\n *\/\n void SetSelectionRectangleVisibility (bool bVisible);\n\n ::sdr::contact::ObjectContact& GetObjectContact (void) const;\n\n typedef ::std::pair PageRange;\n \/** Return the range of currently visible page objects including the\n first and last one in that range.\n @return\n The returned pair of page object indices is empty when the\n second index is lower than the first.\n *\/\n PageRange GetVisiblePageRange (void);\n\n \/** Return the size of the area where the page numbers are displayed.\n @return\n The returned size is given in model coordinates.\n *\/\n Size GetPageNumberAreaModelSize (void) const;\n\n \/** Return the size of the border around the original SdrPageObj.\n *\/\n SvBorder GetModelBorder (void) const;\n\nprotected:\n virtual void Notify (SfxBroadcaster& rBroadcaster, const SfxHint& rHint);\n\nprivate:\n model::SlideSorterModel& mrModel;\n \/\/\/ This model is used for the maPage object.\n SdrModel maPageModel;\n \/** This page acts as container for the page objects that represent the\n pages of the document that is represented by the SlideSorterModel.\n *\/\n SdrPage* mpPage;\n ::std::auto_ptr mpLayouter;\n bool mbPageObjectVisibilitiesValid;\n ::boost::shared_ptr mpPreviewCache;\n ::std::auto_ptr mpViewOverlay;\n\n int mnFirstVisiblePageIndex;\n int mnLastVisiblePageIndex;\n\n SvBorder maPagePixelBorder;\n\n bool mbModelChangedWhileModifyEnabled;\n\n Size maPreviewSize;\n\n bool mbPreciousFlagUpdatePending;\n\n Size maPageNumberAreaModelSize;\n SvBorder maModelBorder;\n\n \/** Adapt the coordinates of the given bounding box according to the\n other parameters.\n @param rModelPageObjectBoundingBox\n Bounding box given in model coordinates that bounds only the\n page object.\n @param eCoordinateSystem\n When CS_SCREEN is given then the bounding box is converted into\n screen coordinates.\n @param eBoundingBoxType\n When BBT_INFO is given then the bounding box is made larger so\n that it encloses all relevant displayed information.\n *\/\n void AdaptBoundingBox (\n Rectangle& rModelPageObjectBoundingBox,\n CoordinateSystem eCoordinateSystem,\n BoundingBoxType eBoundingBoxType) const;\n\n \/** Determine the visibility of all page objects.\n *\/\n void DeterminePageObjectVisibilities (void);\n\n controller::SlideSorterController& GetController (void);\n\n \/** Update the page borders used by the layouter by using those returned\n by the first page. Call this function when the model changes,\n especially when the number of pages changes, or when the window is\n resized as the borders may be device dependent.\n *\/\n void UpdatePageBorders (void);\n\n void UpdatePreciousFlags (void);\n};\n\n\n} } } \/\/ end of namespace ::sd::slidesorter::view\n\n#endif\n<|endoftext|>"} {"text":"\/\/ Project specific\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n\/\/\/ Engine\n\/\/ Core\n#include \n\/\/ Physics\n#include \n#include \n#include \n\nnamespace Doremi\n{\n namespace Core\n {\n EntityFactory* EntityFactory::mSingleton = nullptr;\n\n EntityFactory* EntityFactory::GetInstance() { return mSingleton; }\n\n void EntityFactory::StartupEntityFactory(const DoremiEngine::Core::SharedContext& p_sharedContext)\n {\n if(mSingleton == nullptr)\n {\n mSingleton = new EntityFactory(p_sharedContext);\n }\n }\n\n\n \/\/ TODORT Make sure this is called.\n void EntityFactory::ReleaseInstance()\n {\n delete mSingleton;\n mSingleton = nullptr;\n }\n\n EntityFactory::EntityFactory(const DoremiEngine::Core::SharedContext& p_sharedContext) : m_sharedContext(p_sharedContext) {}\n\n EntityFactory::~EntityFactory() {}\n\n void EntityFactory::CreateComponents(EntityID p_entityID, Blueprints p_blueprintID)\n {\n EntityBlueprint tComponentMap = mEntityBlueprints[p_blueprintID];\n EntityManager* tEntityManager = tEntityManager->GetInstance();\n ComponentTable* tComponentTable = tComponentTable->GetInstance();\n\n for(EntityBlueprint::iterator iter = tComponentMap.begin(); iter != tComponentMap.end(); ++iter)\n {\n\n\n \/\/ Check which component we copy\n if(iter->first == ComponentType::Example)\n {\n memcpy(GetComponent(p_entityID), iter->second, sizeof(ExampleComponent));\n }\n else if(iter->first == ComponentType::Example2)\n {\n memcpy(GetComponent(p_entityID), iter->second, sizeof(Example2Component));\n }\n else if(iter->first == ComponentType::Audio)\n {\n memcpy(GetComponent(p_entityID), iter->second, sizeof(AudioComponent));\n }\n else if(iter->first == ComponentType::AudioActive)\n {\n memcpy(GetComponent(p_entityID), iter->second, sizeof(AudioActiveComponent));\n }\n else if(iter->first == ComponentType::Render)\n {\n memcpy(GetComponent(p_entityID), iter->second, sizeof(RenderComponent));\n }\n else if(iter->first == ComponentType::Transform)\n {\n \/\/ We we already got one from the position CreateEntity overload, we don't need to copy the blueprint's\n if(!tComponentTable->HasComponent(p_entityID, (int)ComponentType::Transform))\n {\n memcpy(GetComponent(p_entityID), iter->second, sizeof(TransformComponent));\n }\n }\n else if(iter->first == ComponentType::RigidBody)\n {\n \/\/ Get the transform component so we can acces our position and orientation (Bold but works)\n TransformComponent* transComp = GetComponent(p_entityID);\n \/\/ Get us our rigid body manager\n DoremiEngine::Physics::RigidBodyManager& rigidBodyManager = m_sharedContext.GetPhysicsModule().GetRigidBodyManager();\n \/\/ Copy the data\n memcpy(GetComponent(p_entityID), iter->second, sizeof(RigidBodyComponent));\n \/\/ Get our body comp\n RigidBodyComponent* bodyComp = reinterpret_cast(iter->second);\n\n \/\/\/ Create the body\n \/\/ Get the material. This is haxxy. It probably works most of the time\n PhysicsMaterialComponent* matComp =\n reinterpret_cast(mEntityBlueprints[p_blueprintID][ComponentType::PhysicalMaterial]);\n \/\/ Create the bodies\n switch(bodyComp->geometry)\n {\n case RigidBodyGeometry::dynamicBox:\n rigidBodyManager.AddBoxBodyDynamic(p_entityID, transComp->position, transComp->rotation, bodyComp->boxDims, matComp->p_materialID);\n break;\n case RigidBodyGeometry::dynamicSphere:\n rigidBodyManager.AddSphereBodyDynamic(p_entityID, transComp->position, bodyComp->sphereRadius);\n break;\n case RigidBodyGeometry::staticBox:\n rigidBodyManager.AddBoxBodyStatic(p_entityID, transComp->position, transComp->rotation, bodyComp->boxDims, matComp->p_materialID);\n break;\n default:\n break;\n }\n \/\/ Apply flags\n if(((int)bodyComp->flags & (int)RigidBodyFlags::kinematic) == (int)RigidBodyFlags::kinematic)\n {\n rigidBodyManager.SetKinematicActor(p_entityID, true);\n }\n if(((int)bodyComp->flags & (int)RigidBodyFlags::trigger) == (int)RigidBodyFlags::trigger)\n {\n rigidBodyManager.SetTrigger(p_entityID, true);\n }\n if(((int)bodyComp->flags & (int)RigidBodyFlags::drain) == (int)RigidBodyFlags::drain)\n {\n rigidBodyManager.SetDrain(p_entityID, true);\n }\n if(((int)bodyComp->flags & (int)RigidBodyFlags::ignoredDEBUG) == (int)RigidBodyFlags::ignoredDEBUG)\n {\n rigidBodyManager.SetIgnoredDEBUG(p_entityID);\n }\n }\n else if(iter->first == ComponentType::PhysicalMaterial)\n {\n memcpy(GetComponent(p_entityID), iter->second, sizeof(PhysicsMaterialComponent));\n }\n else if(iter->first == ComponentType::Movement)\n {\n memcpy(GetComponent(p_entityID), iter->second, sizeof(MovementComponent));\n }\n else if(iter->first == ComponentType::Health)\n {\n memcpy(GetComponent(p_entityID), iter->second, sizeof(HealthComponent));\n }\n else if(iter->first == ComponentType::Range)\n {\n memcpy(GetComponent(p_entityID), iter->second, sizeof(RangeComponent));\n }\n else if(iter->first == ComponentType::PotentialField)\n {\n memcpy(GetComponent(p_entityID), iter->second, sizeof(PotentialFieldComponent));\n }\n else if(iter->first == ComponentType::AIGroup)\n {\n memcpy(GetComponent(p_entityID), iter->second, sizeof(AIGroupComponent));\n }\n else if(iter->first == ComponentType::Jump)\n {\n memcpy(GetComponent(p_entityID), iter->second, sizeof(JumpComponent));\n }\n else if(iter->first == ComponentType::Gravity)\n {\n memcpy(GetComponent(p_entityID), iter->second, sizeof(GravityComponent));\n }\n else if(iter->first == ComponentType::EntityType)\n {\n memcpy(GetComponent(p_entityID), iter->second, sizeof(EntityTypeComponent));\n }\n else if(iter->first == ComponentType::PressureParticleSystem)\n {\n memcpy(GetComponent(p_entityID), iter->second, sizeof(ParticlePressureComponent));\n }\n else if(iter->first == ComponentType::Light)\n {\n memcpy(GetComponent(p_entityID), iter->second, sizeof(LightComponent));\n }\n else if(iter->first == ComponentType::PlatFormPatrolComponent)\n {\n memcpy(GetComponent(p_entityID), iter->second, sizeof(PlatformPatrolComponent));\n }\n else if(iter->first == ComponentType::Trigger)\n {\n memcpy(GetComponent(p_entityID), iter->second, sizeof(TriggerComponent));\n }\n else if(iter->first == ComponentType::DamageInflictors)\n {\n memcpy(GetComponent(p_entityID), iter->second, sizeof(DamageInflictorsComponent));\n }\n else if(iter->first == ComponentType::NetworkObject)\n {\n memcpy(GetComponent(p_entityID), iter->second, sizeof(NetworkObjectComponent));\n }\n else if(iter->first == ComponentType::EntitySpawner)\n {\n memcpy(GetComponent(p_entityID), iter->second, sizeof(EntitySpawnComponent));\n }\n\n \/\/ Add bitmask. This is now done last due to transform being a dick\n tComponentTable->AddComponent(p_entityID, (int)iter->first);\n }\n }\n\n void EntityFactory::Initialize() {}\n\n void EntityFactory::RegisterEntityTemplate(Blueprints p_blueprintID, EntityBlueprint pComponents)\n {\n mEntityBlueprints[p_blueprintID] = pComponents;\n }\n\n EntityID EntityFactory::CreateEntity(Blueprints p_blueprintID)\n {\n EntityManager* tEntityManager = tEntityManager->GetInstance();\n\n \/\/ create a new ID\n EntityID tNewEntityID = tEntityManager->AddEntity();\n CreateComponents(tNewEntityID, p_blueprintID);\n return tNewEntityID;\n }\n\n EntityID EntityFactory::CreateEntity(Blueprints p_blueprintID, DirectX::XMFLOAT3 p_position)\n {\n EntityManager* tEntityManager = tEntityManager->GetInstance();\n EntityID tNewEntityID = tEntityManager->AddEntity();\n\n ComponentTable::GetInstance()->AddComponent(tNewEntityID, (int)ComponentType::Transform);\n TransformComponent* transComp = GetComponent(tNewEntityID);\n transComp->position = p_position;\n transComp->rotation = XMFLOAT4(0, 0, 0, 1);\n\n memcpy(GetComponent(tNewEntityID), transComp, sizeof(TransformComponent));\n memcpy(GetComponent(tNewEntityID), transComp, sizeof(TransformComponent));\n *GetComponent(tNewEntityID) = TransformComponentSnapshotNext(*GetComponent(tNewEntityID));\n *GetComponent(tNewEntityID) =\n TransformComponentSnapshotPrevious(*GetComponent(tNewEntityID));\n\n CreateComponents(tNewEntityID, p_blueprintID);\n\n return tNewEntityID;\n }\n\n EntityID EntityFactory::CreateEntity(Blueprints p_blueprintID, DirectX::XMFLOAT3 p_position, DirectX::XMFLOAT4 p_orientation)\n {\n EntityManager* tEntityManager = tEntityManager->GetInstance();\n EntityID tNewEntityID = tEntityManager->AddEntity();\n\n TransformComponent* transComp = GetComponent(tNewEntityID);\n transComp->position = p_position;\n transComp->rotation = p_orientation;\n\n memcpy(GetComponent(tNewEntityID), transComp, sizeof(TransformComponent));\n memcpy(GetComponent(tNewEntityID), transComp, sizeof(TransformComponent));\n *GetComponent(tNewEntityID) = TransformComponentSnapshotNext(*GetComponent(tNewEntityID));\n *GetComponent(tNewEntityID) =\n TransformComponentSnapshotPrevious(*GetComponent(tNewEntityID));\n\n CreateComponents(tNewEntityID, p_blueprintID);\n\n return tNewEntityID;\n }\n }\n}Character controllers now created in factory\/\/ Project specific\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n\/\/\/ Engine\n\/\/ Core\n#include \n\/\/ Physics\n#include \n#include \n#include \n#include \n\nnamespace Doremi\n{\n namespace Core\n {\n EntityFactory* EntityFactory::mSingleton = nullptr;\n\n EntityFactory* EntityFactory::GetInstance() { return mSingleton; }\n\n void EntityFactory::StartupEntityFactory(const DoremiEngine::Core::SharedContext& p_sharedContext)\n {\n if(mSingleton == nullptr)\n {\n mSingleton = new EntityFactory(p_sharedContext);\n }\n }\n\n\n \/\/ TODORT Make sure this is called.\n void EntityFactory::ReleaseInstance()\n {\n delete mSingleton;\n mSingleton = nullptr;\n }\n\n EntityFactory::EntityFactory(const DoremiEngine::Core::SharedContext& p_sharedContext) : m_sharedContext(p_sharedContext) {}\n\n EntityFactory::~EntityFactory() {}\n\n void EntityFactory::CreateComponents(EntityID p_entityID, Blueprints p_blueprintID)\n {\n EntityBlueprint tComponentMap = mEntityBlueprints[p_blueprintID];\n EntityManager* tEntityManager = tEntityManager->GetInstance();\n ComponentTable* tComponentTable = tComponentTable->GetInstance();\n\n for(EntityBlueprint::iterator iter = tComponentMap.begin(); iter != tComponentMap.end(); ++iter)\n {\n\n\n \/\/ Check which component we copy\n if(iter->first == ComponentType::Example)\n {\n memcpy(GetComponent(p_entityID), iter->second, sizeof(ExampleComponent));\n }\n else if(iter->first == ComponentType::Example2)\n {\n memcpy(GetComponent(p_entityID), iter->second, sizeof(Example2Component));\n }\n else if(iter->first == ComponentType::Audio)\n {\n memcpy(GetComponent(p_entityID), iter->second, sizeof(AudioComponent));\n }\n else if(iter->first == ComponentType::AudioActive)\n {\n memcpy(GetComponent(p_entityID), iter->second, sizeof(AudioActiveComponent));\n }\n else if(iter->first == ComponentType::Render)\n {\n memcpy(GetComponent(p_entityID), iter->second, sizeof(RenderComponent));\n }\n else if(iter->first == ComponentType::Transform)\n {\n \/\/ We we already got one from the position CreateEntity overload, we don't need to copy the blueprint's\n if(!tComponentTable->HasComponent(p_entityID, (int)ComponentType::Transform))\n {\n memcpy(GetComponent(p_entityID), iter->second, sizeof(TransformComponent));\n }\n }\n else if(iter->first == ComponentType::RigidBody)\n {\n \/\/ Get the transform component so we can acces our position and orientation (Bold but works)\n TransformComponent* transComp = GetComponent(p_entityID);\n \/\/ Get us our rigid body manager\n DoremiEngine::Physics::RigidBodyManager& rigidBodyManager = m_sharedContext.GetPhysicsModule().GetRigidBodyManager();\n \/\/ Copy the data\n memcpy(GetComponent(p_entityID), iter->second, sizeof(RigidBodyComponent));\n \/\/ Get our body comp\n RigidBodyComponent* bodyComp = reinterpret_cast(iter->second);\n\n \/\/\/ Create the body\n \/\/ Get the material. This is haxxy. It probably works most of the time\n PhysicsMaterialComponent* matComp =\n reinterpret_cast(mEntityBlueprints[p_blueprintID][ComponentType::PhysicalMaterial]);\n \/\/ Create the bodies\n switch(bodyComp->geometry)\n {\n case RigidBodyGeometry::dynamicBox:\n rigidBodyManager.AddBoxBodyDynamic(p_entityID, transComp->position, transComp->rotation, bodyComp->boxDims, matComp->p_materialID);\n break;\n case RigidBodyGeometry::dynamicSphere:\n rigidBodyManager.AddSphereBodyDynamic(p_entityID, transComp->position, bodyComp->sphereRadius);\n break;\n case RigidBodyGeometry::staticBox:\n rigidBodyManager.AddBoxBodyStatic(p_entityID, transComp->position, transComp->rotation, bodyComp->boxDims, matComp->p_materialID);\n break;\n default:\n break;\n }\n \/\/ Apply flags\n if(((int)bodyComp->flags & (int)RigidBodyFlags::kinematic) == (int)RigidBodyFlags::kinematic)\n {\n rigidBodyManager.SetKinematicActor(p_entityID, true);\n }\n if(((int)bodyComp->flags & (int)RigidBodyFlags::trigger) == (int)RigidBodyFlags::trigger)\n {\n rigidBodyManager.SetTrigger(p_entityID, true);\n }\n if(((int)bodyComp->flags & (int)RigidBodyFlags::drain) == (int)RigidBodyFlags::drain)\n {\n rigidBodyManager.SetDrain(p_entityID, true);\n }\n if(((int)bodyComp->flags & (int)RigidBodyFlags::ignoredDEBUG) == (int)RigidBodyFlags::ignoredDEBUG)\n {\n rigidBodyManager.SetIgnoredDEBUG(p_entityID);\n }\n }\n\n else if(iter->first == ComponentType::CharacterController)\n {\n \/\/ Get the transform component\n TransformComponent* transComp = GetComponent(p_entityID);\n \/\/ Get the character control manager\n DoremiEngine::Physics::CharacterControlManager& characterControlManager = m_sharedContext.GetPhysicsModule().GetCharacterControlManager();\n \/\/ Copy the data\n memcpy(GetComponent(p_entityID), iter->second, sizeof(CharacterControlComponent));\n \/\/ Get our body comp\n CharacterControlComponent* controlComp = reinterpret_cast(iter->second);\n\n \/\/\/ Create the body\n \/\/ Get the material. This is haxxy. It probably works most of the time\n PhysicsMaterialComponent* matComp =\n reinterpret_cast(mEntityBlueprints[p_blueprintID][ComponentType::PhysicalMaterial]);\n \/\/ Create the controller\n characterControlManager.AddController(p_entityID, matComp->p_materialID, transComp->position, controlComp->dims);\n\n \/\/ Apply flags\n if(((int)controlComp->flags & (int)CharacterControlFlags::drain) == (int)CharacterControlFlags::drain)\n {\n characterControlManager.SetDrain(p_entityID, true);\n }\n }\n else if(iter->first == ComponentType::PhysicalMaterial)\n {\n memcpy(GetComponent(p_entityID), iter->second, sizeof(PhysicsMaterialComponent));\n }\n else if(iter->first == ComponentType::Movement)\n {\n memcpy(GetComponent(p_entityID), iter->second, sizeof(MovementComponent));\n }\n else if(iter->first == ComponentType::Health)\n {\n memcpy(GetComponent(p_entityID), iter->second, sizeof(HealthComponent));\n }\n else if(iter->first == ComponentType::Range)\n {\n memcpy(GetComponent(p_entityID), iter->second, sizeof(RangeComponent));\n }\n else if(iter->first == ComponentType::PotentialField)\n {\n memcpy(GetComponent(p_entityID), iter->second, sizeof(PotentialFieldComponent));\n }\n else if(iter->first == ComponentType::AIGroup)\n {\n memcpy(GetComponent(p_entityID), iter->second, sizeof(AIGroupComponent));\n }\n else if(iter->first == ComponentType::Jump)\n {\n memcpy(GetComponent(p_entityID), iter->second, sizeof(JumpComponent));\n }\n else if(iter->first == ComponentType::Gravity)\n {\n memcpy(GetComponent(p_entityID), iter->second, sizeof(GravityComponent));\n }\n else if(iter->first == ComponentType::EntityType)\n {\n memcpy(GetComponent(p_entityID), iter->second, sizeof(EntityTypeComponent));\n }\n else if(iter->first == ComponentType::PressureParticleSystem)\n {\n memcpy(GetComponent(p_entityID), iter->second, sizeof(ParticlePressureComponent));\n }\n else if(iter->first == ComponentType::Light)\n {\n memcpy(GetComponent(p_entityID), iter->second, sizeof(LightComponent));\n }\n else if(iter->first == ComponentType::PlatFormPatrolComponent)\n {\n memcpy(GetComponent(p_entityID), iter->second, sizeof(PlatformPatrolComponent));\n }\n else if(iter->first == ComponentType::Trigger)\n {\n memcpy(GetComponent(p_entityID), iter->second, sizeof(TriggerComponent));\n }\n else if(iter->first == ComponentType::DamageInflictors)\n {\n memcpy(GetComponent(p_entityID), iter->second, sizeof(DamageInflictorsComponent));\n }\n else if(iter->first == ComponentType::NetworkObject)\n {\n memcpy(GetComponent(p_entityID), iter->second, sizeof(NetworkObjectComponent));\n }\n else if(iter->first == ComponentType::EntitySpawner)\n {\n memcpy(GetComponent(p_entityID), iter->second, sizeof(EntitySpawnComponent));\n }\n\n \/\/ Add bitmask. This is now done last due to transform being a dick\n tComponentTable->AddComponent(p_entityID, (int)iter->first);\n }\n }\n\n void EntityFactory::Initialize() {}\n\n void EntityFactory::RegisterEntityTemplate(Blueprints p_blueprintID, EntityBlueprint pComponents)\n {\n mEntityBlueprints[p_blueprintID] = pComponents;\n }\n\n EntityID EntityFactory::CreateEntity(Blueprints p_blueprintID)\n {\n EntityManager* tEntityManager = tEntityManager->GetInstance();\n\n \/\/ create a new ID\n EntityID tNewEntityID = tEntityManager->AddEntity();\n CreateComponents(tNewEntityID, p_blueprintID);\n return tNewEntityID;\n }\n\n EntityID EntityFactory::CreateEntity(Blueprints p_blueprintID, DirectX::XMFLOAT3 p_position)\n {\n EntityManager* tEntityManager = tEntityManager->GetInstance();\n EntityID tNewEntityID = tEntityManager->AddEntity();\n\n ComponentTable::GetInstance()->AddComponent(tNewEntityID, (int)ComponentType::Transform);\n TransformComponent* transComp = GetComponent(tNewEntityID);\n transComp->position = p_position;\n transComp->rotation = XMFLOAT4(0, 0, 0, 1);\n\n memcpy(GetComponent(tNewEntityID), transComp, sizeof(TransformComponent));\n memcpy(GetComponent(tNewEntityID), transComp, sizeof(TransformComponent));\n *GetComponent(tNewEntityID) = TransformComponentSnapshotNext(*GetComponent(tNewEntityID));\n *GetComponent(tNewEntityID) =\n TransformComponentSnapshotPrevious(*GetComponent(tNewEntityID));\n\n CreateComponents(tNewEntityID, p_blueprintID);\n\n return tNewEntityID;\n }\n\n EntityID EntityFactory::CreateEntity(Blueprints p_blueprintID, DirectX::XMFLOAT3 p_position, DirectX::XMFLOAT4 p_orientation)\n {\n EntityManager* tEntityManager = tEntityManager->GetInstance();\n EntityID tNewEntityID = tEntityManager->AddEntity();\n\n TransformComponent* transComp = GetComponent(tNewEntityID);\n transComp->position = p_position;\n transComp->rotation = p_orientation;\n\n memcpy(GetComponent(tNewEntityID), transComp, sizeof(TransformComponent));\n memcpy(GetComponent(tNewEntityID), transComp, sizeof(TransformComponent));\n *GetComponent(tNewEntityID) = TransformComponentSnapshotNext(*GetComponent(tNewEntityID));\n *GetComponent(tNewEntityID) =\n TransformComponentSnapshotPrevious(*GetComponent(tNewEntityID));\n\n CreateComponents(tNewEntityID, p_blueprintID);\n\n return tNewEntityID;\n }\n }\n}<|endoftext|>"} {"text":"\/\/\n\/\/ Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.\n\/\/\n\n#ifndef VERSIONS_HPP_\n#define VERSIONS_HPP_\n\n#include \"utils\/macros.hpp\"\n\n#ifndef AMD_PLATFORM_NAME\n# define AMD_PLATFORM_NAME \"AMD Accelerated Parallel Processing\"\n#endif \/\/ AMD_PLATFORM_NAME\n\n#ifndef AMD_PLATFORM_BUILD_NUMBER\n# define AMD_PLATFORM_BUILD_NUMBER 2052\n#endif \/\/ AMD_PLATFORM_BUILD_NUMBER\n\n#ifndef AMD_PLATFORM_REVISION_NUMBER\n# define AMD_PLATFORM_REVISION_NUMBER 0\n#endif \/\/ AMD_PLATFORM_REVISION_NUMBER\n\n#ifndef AMD_PLATFORM_RELEASE_INFO\n# define AMD_PLATFORM_RELEASE_INFO\n#endif \/\/ AMD_PLATFORM_RELEASE_INFO\n\n#define AMD_BUILD_STRING XSTR(AMD_PLATFORM_BUILD_NUMBER) \\\n \".\" XSTR(AMD_PLATFORM_REVISION_NUMBER)\n\n#ifndef AMD_PLATFORM_INFO\n# define AMD_PLATFORM_INFO \"AMD-APP\" AMD_PLATFORM_RELEASE_INFO \\\n DEBUG_ONLY(\".\" IF(IS_OPTIMIZED,\"opt\",\"dbg\")) \" (\" AMD_BUILD_STRING \")\"\n#endif \/\/ ATI_PLATFORM_INFO\n\n#endif \/\/ VERSIONS_HPP_\nP4 to Git Change 1243815 by johtaylo@johtaylo-JTBUILDER03-increment on 2016\/03\/04 03:00:13\/\/\n\/\/ Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.\n\/\/\n\n#ifndef VERSIONS_HPP_\n#define VERSIONS_HPP_\n\n#include \"utils\/macros.hpp\"\n\n#ifndef AMD_PLATFORM_NAME\n# define AMD_PLATFORM_NAME \"AMD Accelerated Parallel Processing\"\n#endif \/\/ AMD_PLATFORM_NAME\n\n#ifndef AMD_PLATFORM_BUILD_NUMBER\n# define AMD_PLATFORM_BUILD_NUMBER 2053\n#endif \/\/ AMD_PLATFORM_BUILD_NUMBER\n\n#ifndef AMD_PLATFORM_REVISION_NUMBER\n# define AMD_PLATFORM_REVISION_NUMBER 0\n#endif \/\/ AMD_PLATFORM_REVISION_NUMBER\n\n#ifndef AMD_PLATFORM_RELEASE_INFO\n# define AMD_PLATFORM_RELEASE_INFO\n#endif \/\/ AMD_PLATFORM_RELEASE_INFO\n\n#define AMD_BUILD_STRING XSTR(AMD_PLATFORM_BUILD_NUMBER) \\\n \".\" XSTR(AMD_PLATFORM_REVISION_NUMBER)\n\n#ifndef AMD_PLATFORM_INFO\n# define AMD_PLATFORM_INFO \"AMD-APP\" AMD_PLATFORM_RELEASE_INFO \\\n DEBUG_ONLY(\".\" IF(IS_OPTIMIZED,\"opt\",\"dbg\")) \" (\" AMD_BUILD_STRING \")\"\n#endif \/\/ ATI_PLATFORM_INFO\n\n#endif \/\/ VERSIONS_HPP_\n<|endoftext|>"} {"text":"\/\/\n\/\/ Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.\n\/\/\n\n#ifndef VERSIONS_HPP_\n#define VERSIONS_HPP_\n\n#include \"utils\/macros.hpp\"\n\n#ifndef AMD_PLATFORM_NAME\n#define AMD_PLATFORM_NAME \"AMD Accelerated Parallel Processing\"\n#endif \/\/ AMD_PLATFORM_NAME\n\n#ifndef AMD_PLATFORM_BUILD_NUMBER\n#define AMD_PLATFORM_BUILD_NUMBER 2417\n#endif \/\/ AMD_PLATFORM_BUILD_NUMBER\n\n#ifndef AMD_PLATFORM_REVISION_NUMBER\n#define AMD_PLATFORM_REVISION_NUMBER 0\n#endif \/\/ AMD_PLATFORM_REVISION_NUMBER\n\n#ifndef AMD_PLATFORM_RELEASE_INFO\n#define AMD_PLATFORM_RELEASE_INFO\n#endif \/\/ AMD_PLATFORM_RELEASE_INFO\n\n#define AMD_BUILD_STRING \\\n XSTR(AMD_PLATFORM_BUILD_NUMBER) \\\n \".\" XSTR(AMD_PLATFORM_REVISION_NUMBER)\n\n#ifndef AMD_PLATFORM_INFO\n#define AMD_PLATFORM_INFO \\\n \"AMD-APP\" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \\\n \".\" IF(IS_OPTIMIZED, \"opt\", \"dbg\")) \" (\" AMD_BUILD_STRING \")\"\n#endif \/\/ ATI_PLATFORM_INFO\n\n#endif \/\/ VERSIONS_HPP_\nP4 to Git Change 1407897 by johtaylo@johtaylo-jtincrementor-increment on 2017\/05\/10 03:00:04\/\/\n\/\/ Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.\n\/\/\n\n#ifndef VERSIONS_HPP_\n#define VERSIONS_HPP_\n\n#include \"utils\/macros.hpp\"\n\n#ifndef AMD_PLATFORM_NAME\n#define AMD_PLATFORM_NAME \"AMD Accelerated Parallel Processing\"\n#endif \/\/ AMD_PLATFORM_NAME\n\n#ifndef AMD_PLATFORM_BUILD_NUMBER\n#define AMD_PLATFORM_BUILD_NUMBER 2418\n#endif \/\/ AMD_PLATFORM_BUILD_NUMBER\n\n#ifndef AMD_PLATFORM_REVISION_NUMBER\n#define AMD_PLATFORM_REVISION_NUMBER 0\n#endif \/\/ AMD_PLATFORM_REVISION_NUMBER\n\n#ifndef AMD_PLATFORM_RELEASE_INFO\n#define AMD_PLATFORM_RELEASE_INFO\n#endif \/\/ AMD_PLATFORM_RELEASE_INFO\n\n#define AMD_BUILD_STRING \\\n XSTR(AMD_PLATFORM_BUILD_NUMBER) \\\n \".\" XSTR(AMD_PLATFORM_REVISION_NUMBER)\n\n#ifndef AMD_PLATFORM_INFO\n#define AMD_PLATFORM_INFO \\\n \"AMD-APP\" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \\\n \".\" IF(IS_OPTIMIZED, \"opt\", \"dbg\")) \" (\" AMD_BUILD_STRING \")\"\n#endif \/\/ ATI_PLATFORM_INFO\n\n#endif \/\/ VERSIONS_HPP_\n<|endoftext|>"} {"text":"\/\/\n\/\/ Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.\n\/\/\n\n#ifndef VERSIONS_HPP_\n#define VERSIONS_HPP_\n\n#include \"utils\/macros.hpp\"\n\n#ifndef AMD_PLATFORM_NAME\n#define AMD_PLATFORM_NAME \"AMD Accelerated Parallel Processing\"\n#endif \/\/ AMD_PLATFORM_NAME\n\n#ifndef AMD_PLATFORM_BUILD_NUMBER\n#define AMD_PLATFORM_BUILD_NUMBER 2590\n#endif \/\/ AMD_PLATFORM_BUILD_NUMBER\n\n#ifndef AMD_PLATFORM_REVISION_NUMBER\n#define AMD_PLATFORM_REVISION_NUMBER 0\n#endif \/\/ AMD_PLATFORM_REVISION_NUMBER\n\n#ifndef AMD_PLATFORM_RELEASE_INFO\n#define AMD_PLATFORM_RELEASE_INFO\n#endif \/\/ AMD_PLATFORM_RELEASE_INFO\n\n#define AMD_BUILD_STRING \\\n XSTR(AMD_PLATFORM_BUILD_NUMBER) \\\n \".\" XSTR(AMD_PLATFORM_REVISION_NUMBER)\n\n#ifndef AMD_PLATFORM_INFO\n#define AMD_PLATFORM_INFO \\\n \"AMD-APP\" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \\\n \".\" IF(IS_OPTIMIZED, \"opt\", \"dbg\")) \" (\" AMD_BUILD_STRING \")\"\n#endif \/\/ ATI_PLATFORM_INFO\n\n#endif \/\/ VERSIONS_HPP_\nP4 to Git Change 1515945 by johtaylo@johtaylo-jtincrementor2-increment on 2018\/02\/14 03:00:25\/\/\n\/\/ Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.\n\/\/\n\n#ifndef VERSIONS_HPP_\n#define VERSIONS_HPP_\n\n#include \"utils\/macros.hpp\"\n\n#ifndef AMD_PLATFORM_NAME\n#define AMD_PLATFORM_NAME \"AMD Accelerated Parallel Processing\"\n#endif \/\/ AMD_PLATFORM_NAME\n\n#ifndef AMD_PLATFORM_BUILD_NUMBER\n#define AMD_PLATFORM_BUILD_NUMBER 2591\n#endif \/\/ AMD_PLATFORM_BUILD_NUMBER\n\n#ifndef AMD_PLATFORM_REVISION_NUMBER\n#define AMD_PLATFORM_REVISION_NUMBER 0\n#endif \/\/ AMD_PLATFORM_REVISION_NUMBER\n\n#ifndef AMD_PLATFORM_RELEASE_INFO\n#define AMD_PLATFORM_RELEASE_INFO\n#endif \/\/ AMD_PLATFORM_RELEASE_INFO\n\n#define AMD_BUILD_STRING \\\n XSTR(AMD_PLATFORM_BUILD_NUMBER) \\\n \".\" XSTR(AMD_PLATFORM_REVISION_NUMBER)\n\n#ifndef AMD_PLATFORM_INFO\n#define AMD_PLATFORM_INFO \\\n \"AMD-APP\" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \\\n \".\" IF(IS_OPTIMIZED, \"opt\", \"dbg\")) \" (\" AMD_BUILD_STRING \")\"\n#endif \/\/ ATI_PLATFORM_INFO\n\n#endif \/\/ VERSIONS_HPP_\n<|endoftext|>"} {"text":"\/\/\n\/\/ Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.\n\/\/\n\n#ifndef VERSIONS_HPP_\n#define VERSIONS_HPP_\n\n#include \"utils\/macros.hpp\"\n\n#ifndef AMD_PLATFORM_NAME\n# define AMD_PLATFORM_NAME \"AMD Accelerated Parallel Processing\"\n#endif \/\/ AMD_PLATFORM_NAME\n\n#ifndef AMD_PLATFORM_BUILD_NUMBER\n# define AMD_PLATFORM_BUILD_NUMBER 2356\n#endif \/\/ AMD_PLATFORM_BUILD_NUMBER\n\n#ifndef AMD_PLATFORM_REVISION_NUMBER\n# define AMD_PLATFORM_REVISION_NUMBER 0\n#endif \/\/ AMD_PLATFORM_REVISION_NUMBER\n\n#ifndef AMD_PLATFORM_RELEASE_INFO\n# define AMD_PLATFORM_RELEASE_INFO\n#endif \/\/ AMD_PLATFORM_RELEASE_INFO\n\n#define AMD_BUILD_STRING XSTR(AMD_PLATFORM_BUILD_NUMBER) \\\n \".\" XSTR(AMD_PLATFORM_REVISION_NUMBER)\n\n#ifndef AMD_PLATFORM_INFO\n# define AMD_PLATFORM_INFO \"AMD-APP\" AMD_PLATFORM_RELEASE_INFO \\\n DEBUG_ONLY(\".\" IF(IS_OPTIMIZED,\"opt\",\"dbg\")) \" (\" AMD_BUILD_STRING \")\"\n#endif \/\/ ATI_PLATFORM_INFO\n\n#endif \/\/ VERSIONS_HPP_\nP4 to Git Change 1369347 by johtaylo@johtaylo-jtincrementor-increment on 2017\/02\/05 03:00:10\/\/\n\/\/ Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.\n\/\/\n\n#ifndef VERSIONS_HPP_\n#define VERSIONS_HPP_\n\n#include \"utils\/macros.hpp\"\n\n#ifndef AMD_PLATFORM_NAME\n# define AMD_PLATFORM_NAME \"AMD Accelerated Parallel Processing\"\n#endif \/\/ AMD_PLATFORM_NAME\n\n#ifndef AMD_PLATFORM_BUILD_NUMBER\n# define AMD_PLATFORM_BUILD_NUMBER 2357\n#endif \/\/ AMD_PLATFORM_BUILD_NUMBER\n\n#ifndef AMD_PLATFORM_REVISION_NUMBER\n# define AMD_PLATFORM_REVISION_NUMBER 0\n#endif \/\/ AMD_PLATFORM_REVISION_NUMBER\n\n#ifndef AMD_PLATFORM_RELEASE_INFO\n# define AMD_PLATFORM_RELEASE_INFO\n#endif \/\/ AMD_PLATFORM_RELEASE_INFO\n\n#define AMD_BUILD_STRING XSTR(AMD_PLATFORM_BUILD_NUMBER) \\\n \".\" XSTR(AMD_PLATFORM_REVISION_NUMBER)\n\n#ifndef AMD_PLATFORM_INFO\n# define AMD_PLATFORM_INFO \"AMD-APP\" AMD_PLATFORM_RELEASE_INFO \\\n DEBUG_ONLY(\".\" IF(IS_OPTIMIZED,\"opt\",\"dbg\")) \" (\" AMD_BUILD_STRING \")\"\n#endif \/\/ ATI_PLATFORM_INFO\n\n#endif \/\/ VERSIONS_HPP_\n<|endoftext|>"} {"text":"\/\/\n\/\/ Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.\n\/\/\n\n#ifndef VERSIONS_HPP_\n#define VERSIONS_HPP_\n\n#include \"utils\/macros.hpp\"\n\n#ifndef AMD_PLATFORM_NAME\n# define AMD_PLATFORM_NAME \"AMD Accelerated Parallel Processing\"\n#endif \/\/ AMD_PLATFORM_NAME\n\n#ifndef AMD_PLATFORM_BUILD_NUMBER\n# define AMD_PLATFORM_BUILD_NUMBER 2160\n#endif \/\/ AMD_PLATFORM_BUILD_NUMBER\n\n#ifndef AMD_PLATFORM_REVISION_NUMBER\n# define AMD_PLATFORM_REVISION_NUMBER 0\n#endif \/\/ AMD_PLATFORM_REVISION_NUMBER\n\n#ifndef AMD_PLATFORM_RELEASE_INFO\n# define AMD_PLATFORM_RELEASE_INFO\n#endif \/\/ AMD_PLATFORM_RELEASE_INFO\n\n#define AMD_BUILD_STRING XSTR(AMD_PLATFORM_BUILD_NUMBER) \\\n \".\" XSTR(AMD_PLATFORM_REVISION_NUMBER)\n\n#ifndef AMD_PLATFORM_INFO\n# define AMD_PLATFORM_INFO \"AMD-APP\" AMD_PLATFORM_RELEASE_INFO \\\n DEBUG_ONLY(\".\" IF(IS_OPTIMIZED,\"opt\",\"dbg\")) \" (\" AMD_BUILD_STRING \")\"\n#endif \/\/ ATI_PLATFORM_INFO\n\n#endif \/\/ VERSIONS_HPP_\nP4 to Git Change 1289489 by johtaylo@johtaylo-JTBUILDER03-increment on 2016\/07\/10 03:00:08\/\/\n\/\/ Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.\n\/\/\n\n#ifndef VERSIONS_HPP_\n#define VERSIONS_HPP_\n\n#include \"utils\/macros.hpp\"\n\n#ifndef AMD_PLATFORM_NAME\n# define AMD_PLATFORM_NAME \"AMD Accelerated Parallel Processing\"\n#endif \/\/ AMD_PLATFORM_NAME\n\n#ifndef AMD_PLATFORM_BUILD_NUMBER\n# define AMD_PLATFORM_BUILD_NUMBER 2161\n#endif \/\/ AMD_PLATFORM_BUILD_NUMBER\n\n#ifndef AMD_PLATFORM_REVISION_NUMBER\n# define AMD_PLATFORM_REVISION_NUMBER 0\n#endif \/\/ AMD_PLATFORM_REVISION_NUMBER\n\n#ifndef AMD_PLATFORM_RELEASE_INFO\n# define AMD_PLATFORM_RELEASE_INFO\n#endif \/\/ AMD_PLATFORM_RELEASE_INFO\n\n#define AMD_BUILD_STRING XSTR(AMD_PLATFORM_BUILD_NUMBER) \\\n \".\" XSTR(AMD_PLATFORM_REVISION_NUMBER)\n\n#ifndef AMD_PLATFORM_INFO\n# define AMD_PLATFORM_INFO \"AMD-APP\" AMD_PLATFORM_RELEASE_INFO \\\n DEBUG_ONLY(\".\" IF(IS_OPTIMIZED,\"opt\",\"dbg\")) \" (\" AMD_BUILD_STRING \")\"\n#endif \/\/ ATI_PLATFORM_INFO\n\n#endif \/\/ VERSIONS_HPP_\n<|endoftext|>"} {"text":"\/\/\n\/\/ Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.\n\/\/\n\n#ifndef VERSIONS_HPP_\n#define VERSIONS_HPP_\n\n#include \"utils\/macros.hpp\"\n\n#ifndef AMD_PLATFORM_NAME\n# define AMD_PLATFORM_NAME \"AMD Accelerated Parallel Processing\"\n#endif \/\/ AMD_PLATFORM_NAME\n\n#ifndef AMD_PLATFORM_BUILD_NUMBER\n# define AMD_PLATFORM_BUILD_NUMBER 2058\n#endif \/\/ AMD_PLATFORM_BUILD_NUMBER\n\n#ifndef AMD_PLATFORM_REVISION_NUMBER\n# define AMD_PLATFORM_REVISION_NUMBER 0\n#endif \/\/ AMD_PLATFORM_REVISION_NUMBER\n\n#ifndef AMD_PLATFORM_RELEASE_INFO\n# define AMD_PLATFORM_RELEASE_INFO\n#endif \/\/ AMD_PLATFORM_RELEASE_INFO\n\n#define AMD_BUILD_STRING XSTR(AMD_PLATFORM_BUILD_NUMBER) \\\n \".\" XSTR(AMD_PLATFORM_REVISION_NUMBER)\n\n#ifndef AMD_PLATFORM_INFO\n# define AMD_PLATFORM_INFO \"AMD-APP\" AMD_PLATFORM_RELEASE_INFO \\\n DEBUG_ONLY(\".\" IF(IS_OPTIMIZED,\"opt\",\"dbg\")) \" (\" AMD_BUILD_STRING \")\"\n#endif \/\/ ATI_PLATFORM_INFO\n\n#endif \/\/ VERSIONS_HPP_\nP4 to Git Change 1245787 by johtaylo@johtaylo-JTBUILDER03-increment on 2016\/03\/10 03:00:13\/\/\n\/\/ Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.\n\/\/\n\n#ifndef VERSIONS_HPP_\n#define VERSIONS_HPP_\n\n#include \"utils\/macros.hpp\"\n\n#ifndef AMD_PLATFORM_NAME\n# define AMD_PLATFORM_NAME \"AMD Accelerated Parallel Processing\"\n#endif \/\/ AMD_PLATFORM_NAME\n\n#ifndef AMD_PLATFORM_BUILD_NUMBER\n# define AMD_PLATFORM_BUILD_NUMBER 2059\n#endif \/\/ AMD_PLATFORM_BUILD_NUMBER\n\n#ifndef AMD_PLATFORM_REVISION_NUMBER\n# define AMD_PLATFORM_REVISION_NUMBER 0\n#endif \/\/ AMD_PLATFORM_REVISION_NUMBER\n\n#ifndef AMD_PLATFORM_RELEASE_INFO\n# define AMD_PLATFORM_RELEASE_INFO\n#endif \/\/ AMD_PLATFORM_RELEASE_INFO\n\n#define AMD_BUILD_STRING XSTR(AMD_PLATFORM_BUILD_NUMBER) \\\n \".\" XSTR(AMD_PLATFORM_REVISION_NUMBER)\n\n#ifndef AMD_PLATFORM_INFO\n# define AMD_PLATFORM_INFO \"AMD-APP\" AMD_PLATFORM_RELEASE_INFO \\\n DEBUG_ONLY(\".\" IF(IS_OPTIMIZED,\"opt\",\"dbg\")) \" (\" AMD_BUILD_STRING \")\"\n#endif \/\/ ATI_PLATFORM_INFO\n\n#endif \/\/ VERSIONS_HPP_\n<|endoftext|>"} {"text":"\/\/\n\/\/ Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.\n\/\/\n\n#ifndef VERSIONS_HPP_\n#define VERSIONS_HPP_\n\n#include \"utils\/macros.hpp\"\n\n#ifndef AMD_PLATFORM_NAME\n# define AMD_PLATFORM_NAME \"AMD Accelerated Parallel Processing\"\n#endif \/\/ AMD_PLATFORM_NAME\n\n#ifndef AMD_PLATFORM_BUILD_NUMBER\n# define AMD_PLATFORM_BUILD_NUMBER 1616\n#endif \/\/ AMD_PLATFORM_BUILD_NUMBER\n\n#ifndef AMD_PLATFORM_REVISION_NUMBER\n# define AMD_PLATFORM_REVISION_NUMBER 0\n#endif \/\/ AMD_PLATFORM_REVISION_NUMBER\n\n#ifndef AMD_PLATFORM_RELEASE_INFO\n# define AMD_PLATFORM_RELEASE_INFO\n#endif \/\/ AMD_PLATFORM_RELEASE_INFO\n\n#define AMD_BUILD_STRING XSTR(AMD_PLATFORM_BUILD_NUMBER) \\\n \".\" XSTR(AMD_PLATFORM_REVISION_NUMBER)\n\n#ifndef AMD_PLATFORM_INFO\n# define AMD_PLATFORM_INFO \"AMD-APP\" AMD_PLATFORM_RELEASE_INFO \\\n DEBUG_ONLY(\".\" IF(IS_OPTIMIZED,\"opt\",\"dbg\")) \" (\" AMD_BUILD_STRING \")\"\n#endif \/\/ ATI_PLATFORM_INFO\n\n#endif \/\/ VERSIONS_HPP_\nP4 to Git Change 1068739 by johtaylo@johtaylo-JTBUILDER03-increment on 2014\/08\/21 03:00:13\/\/\n\/\/ Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.\n\/\/\n\n#ifndef VERSIONS_HPP_\n#define VERSIONS_HPP_\n\n#include \"utils\/macros.hpp\"\n\n#ifndef AMD_PLATFORM_NAME\n# define AMD_PLATFORM_NAME \"AMD Accelerated Parallel Processing\"\n#endif \/\/ AMD_PLATFORM_NAME\n\n#ifndef AMD_PLATFORM_BUILD_NUMBER\n# define AMD_PLATFORM_BUILD_NUMBER 1617\n#endif \/\/ AMD_PLATFORM_BUILD_NUMBER\n\n#ifndef AMD_PLATFORM_REVISION_NUMBER\n# define AMD_PLATFORM_REVISION_NUMBER 0\n#endif \/\/ AMD_PLATFORM_REVISION_NUMBER\n\n#ifndef AMD_PLATFORM_RELEASE_INFO\n# define AMD_PLATFORM_RELEASE_INFO\n#endif \/\/ AMD_PLATFORM_RELEASE_INFO\n\n#define AMD_BUILD_STRING XSTR(AMD_PLATFORM_BUILD_NUMBER) \\\n \".\" XSTR(AMD_PLATFORM_REVISION_NUMBER)\n\n#ifndef AMD_PLATFORM_INFO\n# define AMD_PLATFORM_INFO \"AMD-APP\" AMD_PLATFORM_RELEASE_INFO \\\n DEBUG_ONLY(\".\" IF(IS_OPTIMIZED,\"opt\",\"dbg\")) \" (\" AMD_BUILD_STRING \")\"\n#endif \/\/ ATI_PLATFORM_INFO\n\n#endif \/\/ VERSIONS_HPP_\n<|endoftext|>"} {"text":"\/\/\n\/\/ Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.\n\/\/\n\n#ifndef VERSIONS_HPP_\n#define VERSIONS_HPP_\n\n#include \"utils\/macros.hpp\"\n\n#ifndef AMD_PLATFORM_NAME\n# define AMD_PLATFORM_NAME \"AMD Accelerated Parallel Processing\"\n#endif \/\/ AMD_PLATFORM_NAME\n\n#ifndef AMD_PLATFORM_BUILD_NUMBER\n# define AMD_PLATFORM_BUILD_NUMBER 2169\n#endif \/\/ AMD_PLATFORM_BUILD_NUMBER\n\n#ifndef AMD_PLATFORM_REVISION_NUMBER\n# define AMD_PLATFORM_REVISION_NUMBER 0\n#endif \/\/ AMD_PLATFORM_REVISION_NUMBER\n\n#ifndef AMD_PLATFORM_RELEASE_INFO\n# define AMD_PLATFORM_RELEASE_INFO\n#endif \/\/ AMD_PLATFORM_RELEASE_INFO\n\n#define AMD_BUILD_STRING XSTR(AMD_PLATFORM_BUILD_NUMBER) \\\n \".\" XSTR(AMD_PLATFORM_REVISION_NUMBER)\n\n#ifndef AMD_PLATFORM_INFO\n# define AMD_PLATFORM_INFO \"AMD-APP\" AMD_PLATFORM_RELEASE_INFO \\\n DEBUG_ONLY(\".\" IF(IS_OPTIMIZED,\"opt\",\"dbg\")) \" (\" AMD_BUILD_STRING \")\"\n#endif \/\/ ATI_PLATFORM_INFO\n\n#endif \/\/ VERSIONS_HPP_\nP4 to Git Change 1292862 by johtaylo@johtaylo-JTBUILDER03-increment on 2016\/07\/19 03:00:09\/\/\n\/\/ Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.\n\/\/\n\n#ifndef VERSIONS_HPP_\n#define VERSIONS_HPP_\n\n#include \"utils\/macros.hpp\"\n\n#ifndef AMD_PLATFORM_NAME\n# define AMD_PLATFORM_NAME \"AMD Accelerated Parallel Processing\"\n#endif \/\/ AMD_PLATFORM_NAME\n\n#ifndef AMD_PLATFORM_BUILD_NUMBER\n# define AMD_PLATFORM_BUILD_NUMBER 2170\n#endif \/\/ AMD_PLATFORM_BUILD_NUMBER\n\n#ifndef AMD_PLATFORM_REVISION_NUMBER\n# define AMD_PLATFORM_REVISION_NUMBER 0\n#endif \/\/ AMD_PLATFORM_REVISION_NUMBER\n\n#ifndef AMD_PLATFORM_RELEASE_INFO\n# define AMD_PLATFORM_RELEASE_INFO\n#endif \/\/ AMD_PLATFORM_RELEASE_INFO\n\n#define AMD_BUILD_STRING XSTR(AMD_PLATFORM_BUILD_NUMBER) \\\n \".\" XSTR(AMD_PLATFORM_REVISION_NUMBER)\n\n#ifndef AMD_PLATFORM_INFO\n# define AMD_PLATFORM_INFO \"AMD-APP\" AMD_PLATFORM_RELEASE_INFO \\\n DEBUG_ONLY(\".\" IF(IS_OPTIMIZED,\"opt\",\"dbg\")) \" (\" AMD_BUILD_STRING \")\"\n#endif \/\/ ATI_PLATFORM_INFO\n\n#endif \/\/ VERSIONS_HPP_\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"landmarkbrowser.h\"\n#include \"landmarkadddialog.cpp\"\n\nQTM_USE_NAMESPACE\n\nLandmarkBrowser::LandmarkBrowser(QWidget *parent, Qt::WindowFlags flags)\n{\n setupUi(this);\n table->insertColumn(3);\n table->hideColumn(3);\n\n manager = new QLandmarkManager(this);\n\n landmarkFetch = new QLandmarkFetchRequest(manager, this);\n QObject::connect(landmarkFetch, SIGNAL(stateChanged(QLandmarkAbstractRequest::State)),\n this,SLOT(fetchHandler(QLandmarkAbstractRequest::State)));\n\n landmarkImport = new QLandmarkImportRequest(manager, this);\n QObject::connect(landmarkImport, SIGNAL(stateChanged(QLandmarkAbstractRequest::State)),\n this,SLOT(fetchHandler(QLandmarkAbstractRequest::State)));\n\n landmarkRemove = new QLandmarkRemoveRequest(manager, this);\n QObject::connect(landmarkRemove, SIGNAL(stateChanged(QLandmarkAbstractRequest::State)),\n this,SLOT(fetchHandler(QLandmarkAbstractRequest::State)));\n\n landmarkSave = new QLandmarkSaveRequest(manager, this);\n QObject::connect(landmarkSave, SIGNAL(stateChanged(QLandmarkAbstractRequest::State)),\n this,SLOT(fetchHandler(QLandmarkAbstractRequest::State)));\n\n table->setSelectionBehavior(QAbstractItemView::SelectRows);\n\n table->setHorizontalHeaderItem(0, new QTableWidgetItem(\"Lat\"));\n table->setHorizontalHeaderItem(1, new QTableWidgetItem(\"Long\"));\n table->setHorizontalHeaderItem(2, new QTableWidgetItem(\"Name\"));\n\n progress = new QProgressDialog (tr(\"Please wait...\"),tr(\"Cancel\"),0,0, this);\n progress->setCancelButton(0);\n progress->setWindowTitle(tr(\"Loading Landmarks\"));\n landmarkFetch->start();\n progress->show();\n}\n\nLandmarkBrowser::~LandmarkBrowser()\n{\n delete landmarkFetch;\n delete landmarkImport;\n delete landmarkRemove;\n delete landmarkSave;\n delete progress;\n delete manager;\n}\n\nvoid LandmarkBrowser::on_importLandmarks_clicked()\n{\n QString fileName = QFileDialog::getOpenFileName(this,tr(\"Import File\"),\".\",tr(\"Landmark files (*.gpx)\"));\n if (!fileName.isEmpty()) {\n landmarkImport->setFileName(fileName);\n landmarkImport->setFormat(\"GpxV1.1\");\n landmarkImport->start();\n progress->setWindowTitle(tr(\"Importing Landmarks\"));\n progress->show();\n }\n}\n\nvoid LandmarkBrowser::on_deleteLandmarks_clicked()\n{\n QItemSelectionModel *selection = table->selectionModel();\n QModelIndexList selectedIndexes = selection->selectedRows();\n\n QList deleteIds;\n\n QLandmarkId id;\n QModelIndex index;\n while(selectedIndexes.count() > 0) {\n index = selectedIndexes.takeLast();\n id.setManagerUri(manager->managerUri());\n id.setLocalId(table->item(index.row(),3)->text());\n deleteIds.append(id);\n table->removeRow(index.row());\n selectedIndexes = table->selectionModel()->selectedRows();\n }\n\n if (deleteIds.count() == 0)\n return;\n\n manager->removeLandmarks(deleteIds);\n}\n\nvoid LandmarkBrowser::on_addLandmark_clicked()\n{\n LandmarkAddDialog addDialog(this);\n if (!addDialog.exec()) {\n return;\n }\n\n QLandmark lm = addDialog.landmark();\n manager->saveLandmark(&lm);\n table->insertRow(table->rowCount());\n table->setItem(table->rowCount()-1,0,new QTableWidgetItem(QString::number(lm.coordinate().latitude(),'f',2)));\n table->setItem(table->rowCount()-1,1,new QTableWidgetItem(QString::number(lm.coordinate().longitude(),'f',2)));\n table->setItem(table->rowCount()-1,2,new QTableWidgetItem(lm.name()));\n table->setItem(table->rowCount()-1,3,new QTableWidgetItem(lm.landmarkId().localId()));\n}\n\n\nvoid LandmarkBrowser::fetchHandler(QLandmarkAbstractRequest::State state)\n{\n if (state == QLandmarkAbstractRequest::FinishedState)\n {\n QLandmarkAbstractRequest *request = qobject_cast (sender());\n if (!request)\n return;\n switch (request->type()) {\n case QLandmarkAbstractRequest::ImportRequest : {\n if (request->error() == QLandmarkManager::NoError) {\n landmarkFetch->start();\n } else {\n QMessageBox::warning(this,\"Warning\", \"Import Failed\", QMessageBox::Ok, QMessageBox::NoButton);\n progress->hide();\n }\n break;\n }\n case QLandmarkAbstractRequest::LandmarkFetchRequest: {\n if (landmarkFetch->error() == QLandmarkManager::NoError) {\n table->setUpdatesEnabled(false);\n for(int i = table->rowCount() -1; i >= 0; --i) {\n if (i %20 == 0)\n qApp->processEvents();\n table->removeRow(i);\n }\n\n QList lms;\n if (request->type() == QLandmarkAbstractRequest::LandmarkFetchRequest)\n lms = landmarkFetch->landmarks();\n else\n lms = manager->landmarks(QLandmarkFilter());\n\n QLandmark lm;\n for ( int i =0; i < lms.count(); ++i) {\n lm = lms.at(i);\n table->insertRow(table->rowCount());\n table->setItem(table->rowCount()-1,0,new QTableWidgetItem(QString::number(lm.coordinate().latitude(),'f',2)));\n table->setItem(table->rowCount()-1,1,new QTableWidgetItem(QString::number(lm.coordinate().longitude(),'f',2)));\n table->setItem(table->rowCount()-1,2,new QTableWidgetItem(lm.name()));\n table->setItem(table->rowCount()-1,3,new QTableWidgetItem(lm.landmarkId().localId()));\n\n if (i %20)\n qApp->processEvents();\n }\n table->setUpdatesEnabled(true);\n } else {\n QMessageBox::warning(this,\"Warning\", \"Fetch Failed\", QMessageBox::Ok, QMessageBox::NoButton);\n }\n progress->hide();\n break;\n }\n }\n }\n}\nAllow landmark browser to import lmx files#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"landmarkbrowser.h\"\n#include \"landmarkadddialog.cpp\"\n\nQTM_USE_NAMESPACE\n\nLandmarkBrowser::LandmarkBrowser(QWidget *parent, Qt::WindowFlags flags)\n{\n setupUi(this);\n table->insertColumn(3);\n table->hideColumn(3);\n\n manager = new QLandmarkManager(this);\n\n landmarkFetch = new QLandmarkFetchRequest(manager, this);\n QObject::connect(landmarkFetch, SIGNAL(stateChanged(QLandmarkAbstractRequest::State)),\n this,SLOT(fetchHandler(QLandmarkAbstractRequest::State)));\n\n landmarkImport = new QLandmarkImportRequest(manager, this);\n QObject::connect(landmarkImport, SIGNAL(stateChanged(QLandmarkAbstractRequest::State)),\n this,SLOT(fetchHandler(QLandmarkAbstractRequest::State)));\n\n landmarkRemove = new QLandmarkRemoveRequest(manager, this);\n QObject::connect(landmarkRemove, SIGNAL(stateChanged(QLandmarkAbstractRequest::State)),\n this,SLOT(fetchHandler(QLandmarkAbstractRequest::State)));\n\n landmarkSave = new QLandmarkSaveRequest(manager, this);\n QObject::connect(landmarkSave, SIGNAL(stateChanged(QLandmarkAbstractRequest::State)),\n this,SLOT(fetchHandler(QLandmarkAbstractRequest::State)));\n\n table->setSelectionBehavior(QAbstractItemView::SelectRows);\n\n table->setHorizontalHeaderItem(0, new QTableWidgetItem(\"Lat\"));\n table->setHorizontalHeaderItem(1, new QTableWidgetItem(\"Long\"));\n table->setHorizontalHeaderItem(2, new QTableWidgetItem(\"Name\"));\n\n progress = new QProgressDialog (tr(\"Please wait...\"),tr(\"Cancel\"),0,0, this);\n progress->setCancelButton(0);\n progress->setWindowTitle(tr(\"Loading Landmarks\"));\n landmarkFetch->start();\n progress->show();\n}\n\nLandmarkBrowser::~LandmarkBrowser()\n{\n delete landmarkFetch;\n delete landmarkImport;\n delete landmarkRemove;\n delete landmarkSave;\n delete progress;\n delete manager;\n}\n\nvoid LandmarkBrowser::on_importLandmarks_clicked()\n{\n QString fileName = QFileDialog::getOpenFileName(this,tr(\"Import File\"),\".\",tr(\"Landmark files (*.gpx *.lmx)\"));\n if (!fileName.isEmpty()) {\n landmarkImport->setFileName(fileName);\n landmarkImport->start();\n progress->setWindowTitle(tr(\"Importing Landmarks\"));\n progress->show();\n }\n}\n\nvoid LandmarkBrowser::on_deleteLandmarks_clicked()\n{\n QItemSelectionModel *selection = table->selectionModel();\n QModelIndexList selectedIndexes = selection->selectedRows();\n\n QList deleteIds;\n\n QLandmarkId id;\n QModelIndex index;\n while(selectedIndexes.count() > 0) {\n index = selectedIndexes.takeLast();\n id.setManagerUri(manager->managerUri());\n id.setLocalId(table->item(index.row(),3)->text());\n deleteIds.append(id);\n table->removeRow(index.row());\n selectedIndexes = table->selectionModel()->selectedRows();\n }\n\n if (deleteIds.count() == 0)\n return;\n\n manager->removeLandmarks(deleteIds);\n}\n\nvoid LandmarkBrowser::on_addLandmark_clicked()\n{\n LandmarkAddDialog addDialog(this);\n if (!addDialog.exec()) {\n return;\n }\n\n QLandmark lm = addDialog.landmark();\n manager->saveLandmark(&lm);\n table->insertRow(table->rowCount());\n table->setItem(table->rowCount()-1,0,new QTableWidgetItem(QString::number(lm.coordinate().latitude(),'f',2)));\n table->setItem(table->rowCount()-1,1,new QTableWidgetItem(QString::number(lm.coordinate().longitude(),'f',2)));\n table->setItem(table->rowCount()-1,2,new QTableWidgetItem(lm.name()));\n table->setItem(table->rowCount()-1,3,new QTableWidgetItem(lm.landmarkId().localId()));\n}\n\n\nvoid LandmarkBrowser::fetchHandler(QLandmarkAbstractRequest::State state)\n{\n if (state == QLandmarkAbstractRequest::FinishedState)\n {\n QLandmarkAbstractRequest *request = qobject_cast (sender());\n if (!request)\n return;\n switch (request->type()) {\n case QLandmarkAbstractRequest::ImportRequest : {\n if (request->error() == QLandmarkManager::NoError) {\n landmarkFetch->start();\n } else {\n QMessageBox::warning(this,\"Warning\", \"Import Failed\", QMessageBox::Ok, QMessageBox::NoButton);\n progress->hide();\n }\n break;\n }\n case QLandmarkAbstractRequest::LandmarkFetchRequest: {\n if (landmarkFetch->error() == QLandmarkManager::NoError) {\n table->setUpdatesEnabled(false);\n for(int i = table->rowCount() -1; i >= 0; --i) {\n if (i %20 == 0)\n qApp->processEvents();\n table->removeRow(i);\n }\n\n QList lms;\n if (request->type() == QLandmarkAbstractRequest::LandmarkFetchRequest)\n lms = landmarkFetch->landmarks();\n else\n lms = manager->landmarks(QLandmarkFilter());\n\n QLandmark lm;\n for ( int i =0; i < lms.count(); ++i) {\n lm = lms.at(i);\n table->insertRow(table->rowCount());\n table->setItem(table->rowCount()-1,0,new QTableWidgetItem(QString::number(lm.coordinate().latitude(),'f',2)));\n table->setItem(table->rowCount()-1,1,new QTableWidgetItem(QString::number(lm.coordinate().longitude(),'f',2)));\n table->setItem(table->rowCount()-1,2,new QTableWidgetItem(lm.name()));\n table->setItem(table->rowCount()-1,3,new QTableWidgetItem(lm.landmarkId().localId()));\n\n if (i %20)\n qApp->processEvents();\n }\n table->setUpdatesEnabled(true);\n } else {\n QMessageBox::warning(this,\"Warning\", \"Fetch Failed\", QMessageBox::Ok, QMessageBox::NoButton);\n }\n progress->hide();\n break;\n }\n }\n }\n}\n<|endoftext|>"} {"text":"\/\/ RUN: %check_clang_tidy %s cert-err09-cpp,cert-err61-cpp %t\n\nvoid alwaysThrows() {\n int ex = 42;\n \/\/ CHECK-MESSAGES: warning: throw expression should throw anonymous temporary values instead [cert-err09-cpp]\n \/\/ CHECK-MESSAGES: warning: throw expression should throw anonymous temporary values instead [cert-err61-cpp]\n throw ex;\n}\n\nvoid doTheJob() {\n try {\n alwaysThrows();\n } catch (int&) {\n }\n}\n[clang-tidy] Manually enable exceptions in tesst that uses them\/\/ RUN: %check_clang_tidy %s cert-err09-cpp,cert-err61-cpp %t -- -- -fexceptions\n\nvoid alwaysThrows() {\n int ex = 42;\n \/\/ CHECK-MESSAGES: warning: throw expression should throw anonymous temporary values instead [cert-err09-cpp]\n \/\/ CHECK-MESSAGES: warning: throw expression should throw anonymous temporary values instead [cert-err61-cpp]\n throw ex;\n}\n\nvoid doTheJob() {\n try {\n alwaysThrows();\n } catch (int&) {\n }\n}\n<|endoftext|>"} {"text":"\/*\n * Software License Agreement (BSD License)\n *\n * Point Cloud Library (PCL) - www.pointclouds.org\n * Copyright (c) 2010-2011, Willow Garage, Inc.\n *\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following\n * disclaimer in the documentation and\/or other materials provided\n * with the distribution.\n * * Neither the name of Willow Garage, Inc. nor the names of its\n * contributors may be used to endorse or promote products derived\n * from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n * Author: Raphael Favier, Technical University Eindhoven, (r.mysurname tue.nl)\n *\/\n\n #include \n #include \n\n\n\nPCL_INSTANTIATE(WorldModel, (pcl::PointXYZ)(pcl::PointXYZI));\nneed to include instantiate.hpp to use PCL_INSTANTIATE\/*\n * Software License Agreement (BSD License)\n *\n * Point Cloud Library (PCL) - www.pointclouds.org\n * Copyright (c) 2010-2011, Willow Garage, Inc.\n *\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following\n * disclaimer in the documentation and\/or other materials provided\n * with the distribution.\n * * Neither the name of Willow Garage, Inc. nor the names of its\n * contributors may be used to endorse or promote products derived\n * from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n * Author: Raphael Favier, Technical University Eindhoven, (r.mysurname tue.nl)\n *\/\n\n #include \n #include \n #include \n\n\n\nPCL_INSTANTIATE(WorldModel, (pcl::PointXYZ)(pcl::PointXYZI));\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * $RCSfile: formlayerexport.cxx,v $\n *\n * $Revision: 1.14 $\n *\n * last change: $Author: vg $ $Date: 2005-03-23 11:25:13 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#include \n\n#ifndef _XMLOFF_FORMLAYEREXPORT_HXX_\n#include \"formlayerexport.hxx\"\n#endif\n#ifndef _XMLOFF_FORMS_STRINGS_HXX_\n#include \"strings.hxx\"\n#endif\n#ifndef _XMLOFF_ELEMENTEXPORT_HXX_\n#include \"elementexport.hxx\"\n#endif\n#ifndef _XMLOFF_XMLNMSPE_HXX\n#include \"xmlnmspe.hxx\"\n#endif\n#ifndef _XMLOFF_XMLEXP_HXX\n#include \"xmlexp.hxx\"\n#endif\n#ifndef _XMLOFF_FORMS_LAYEREXPORT_HXX_\n#include \"layerexport.hxx\"\n#endif\n#ifndef _XMLOFF_FORMS_PROPERTYEXPORT_HXX_\n#include \"propertyexport.hxx\"\n#endif\n#ifndef _OSL_DIAGNOSE_H_\n#include \n#endif\n#ifndef _COMPHELPER_EXTRACT_HXX_\n#include \n#endif\n#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_\n#include \n#endif\n#ifndef _COMPHELPER_STLTYPES_HXX_\n#include \n#endif\n#ifndef _XMLOFF_FORMS_OFFICEFORMS_HXX_\n#include \"officeforms.hxx\"\n#endif\n\n\n\/\/.........................................................................\nnamespace xmloff\n{\n\/\/.........................................................................\n\n using namespace ::com::sun::star::uno;\n using namespace ::com::sun::star::lang;\n using namespace ::com::sun::star::awt;\n using namespace ::com::sun::star::beans;\n using namespace ::com::sun::star::container;\n using namespace ::com::sun::star::drawing;\n using namespace ::com::sun::star::frame;\n\n \/\/=====================================================================\n \/\/= OFormLayerXMLExport\n \/\/=====================================================================\n\n \/\/---------------------------------------------------------------------\n OFormLayerXMLExport::OFormLayerXMLExport(SvXMLExport& _rContext)\n :m_rContext(_rContext)\n ,m_pImpl(new OFormLayerXMLExport_Impl(_rContext))\n {\n }\n\n \/\/---------------------------------------------------------------------\n OFormLayerXMLExport::~OFormLayerXMLExport()\n {\n delete m_pImpl;\n m_pImpl = NULL;\n }\n\n \/\/---------------------------------------------------------------------\n sal_Bool OFormLayerXMLExport::seekPage(const Reference< XDrawPage >& _rxDrawPage)\n {\n return m_pImpl->seekPage(_rxDrawPage);\n }\n\n \/\/---------------------------------------------------------------------\n ::rtl::OUString OFormLayerXMLExport::getControlId(const Reference< XPropertySet >& _rxControl)\n {\n return m_pImpl->getControlId(_rxControl);\n }\n\n \/\/---------------------------------------------------------------------\n ::rtl::OUString OFormLayerXMLExport::getControlNumberStyle( const Reference< XPropertySet >& _rxControl )\n {\n return m_pImpl->getControlNumberStyle(_rxControl);\n }\n\n \/\/---------------------------------------------------------------------\n ::vos::ORef< SvXMLExportPropertyMapper > OFormLayerXMLExport::getStylePropertyMapper()\n {\n return m_pImpl->getStylePropertyMapper();\n }\n\n \/\/---------------------------------------------------------------------\n void OFormLayerXMLExport::initialize()\n {\n m_pImpl->clear();\n }\n\n \/\/---------------------------------------------------------------------\n void OFormLayerXMLExport::examineForms(const Reference< XDrawPage >& _rxDrawPage)\n {\n try\n {\n m_pImpl->examineForms(_rxDrawPage);\n }\n catch(Exception&)\n {\n OSL_ENSURE(sal_False, \"OFormLayerXMLExport::examine: could not examine the draw page!\");\n }\n }\n\n \/\/---------------------------------------------------------------------\n void OFormLayerXMLExport::exportForms(const Reference< XDrawPage >& _rxDrawPage)\n {\n m_pImpl->exportForms(_rxDrawPage);\n }\n\n \/\/---------------------------------------------------------------------\n void OFormLayerXMLExport::exportXForms() const\n {\n m_pImpl->exportXForms();\n }\n\n \/\/---------------------------------------------------------------------\n bool OFormLayerXMLExport::pageContainsForms( const Reference< XDrawPage >& _rxDrawPage ) const\n {\n return m_pImpl->pageContainsForms( _rxDrawPage );\n }\n\n \/\/---------------------------------------------------------------------\n bool OFormLayerXMLExport::documentContainsXForms() const\n {\n return m_pImpl->documentContainsXForms();\n }\n\n \/\/---------------------------------------------------------------------\n void OFormLayerXMLExport::exportControlNumberStyles()\n {\n m_pImpl->exportControlNumberStyles();\n }\n\n \/\/---------------------------------------------------------------------\n void OFormLayerXMLExport::exportAutoControlNumberStyles()\n {\n m_pImpl->exportAutoControlNumberStyles();\n }\n\n \/\/---------------------------------------------------------------------\n void OFormLayerXMLExport::exportAutoStyles()\n {\n m_pImpl->exportAutoStyles();\n }\n\n \/\/---------------------------------------------------------------------\n void OFormLayerXMLExport::excludeFromExport( const Reference< XControlModel > _rxControl )\n {\n m_pImpl->excludeFromExport( _rxControl );\n }\n\n \/\/=========================================================================\n \/\/= OOfficeFormsExport\n \/\/=========================================================================\n \/\/-------------------------------------------------------------------------\n OOfficeFormsExport::OOfficeFormsExport( SvXMLExport& _rExp )\n :m_pImpl(NULL)\n {\n m_pImpl = new OFormsRootExport(_rExp);\n }\n\n \/\/-------------------------------------------------------------------------\n OOfficeFormsExport::~OOfficeFormsExport()\n {\n delete m_pImpl;\n }\n\n\/\/.........................................................................\n} \/\/ namespace xmloff\n\/\/.........................................................................\n\n\/*************************************************************************\n * history:\n * $Log: not supported by cvs2svn $\n * Revision 1.13.430.1 2004\/12\/13 17:27:32 fs\n * #i36597# +exportXForms\/pageContainsForms\/documentContainsXForms\n *\n * Revision 1.13 2002\/10\/25 07:58:00 fs\n * #104402# re-introduced exportAutoStyles\n *\n * Revision 1.12 2002\/09\/25 12:02:38 fs\n * #103597# +excludeFromExport\n *\n * Revision 1.11 2001\/05\/28 14:59:18 fs\n * #86712# added control number style related functionality\n *\n * Revision 1.10 2001\/03\/20 13:35:38 fs\n * #83970# +OOfficeFormsExport\n *\n * Revision 1.9 2001\/03\/20 08:04:08 fs\n * removed exportAutoStyles (was obsolete)\n *\n * Revision 1.8 2001\/03\/16 14:36:39 sab\n * did the required change (move of extract.hxx form cppuhelper to comphelper)\n *\n * Revision 1.7 2001\/02\/01 09:46:47 fs\n * no own style handling anymore - the shape exporter is responsible for our styles now\n *\n * Revision 1.6 2000\/12\/18 16:22:35 fs\n * forgot an & on the getControlId parameter\n *\n * Revision 1.5 2000\/12\/18 15:14:35 fs\n * some changes ... now exporting\/importing styles\n *\n * Revision 1.4 2000\/12\/06 17:28:05 fs\n * changes for the formlayer import - still under construction\n *\n * Revision 1.3 2000\/12\/03 10:57:06 fs\n * some changes to support more than one page to be examined\/exported\n *\n * Revision 1.2 2000\/11\/29 10:32:13 mh\n * add: header for Solaris8\n *\n * Revision 1.1 2000\/11\/17 19:02:16 fs\n * initial checkin - export and\/or import the applications form layer\n *\n *\n * Revision 1.0 13.11.00 14:58:17 fs\n ************************************************************************\/\n\nINTEGRATION: CWS ooo19126 (1.14.94); FILE MERGED 2005\/09\/05 14:38:59 rt 1.14.94.1: #i54170# Change license header: remove SISSL\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: formlayerexport.cxx,v $\n *\n * $Revision: 1.15 $\n *\n * last change: $Author: rt $ $Date: 2005-09-09 14:10:24 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#include \n\n#ifndef _XMLOFF_FORMLAYEREXPORT_HXX_\n#include \"formlayerexport.hxx\"\n#endif\n#ifndef _XMLOFF_FORMS_STRINGS_HXX_\n#include \"strings.hxx\"\n#endif\n#ifndef _XMLOFF_ELEMENTEXPORT_HXX_\n#include \"elementexport.hxx\"\n#endif\n#ifndef _XMLOFF_XMLNMSPE_HXX\n#include \"xmlnmspe.hxx\"\n#endif\n#ifndef _XMLOFF_XMLEXP_HXX\n#include \"xmlexp.hxx\"\n#endif\n#ifndef _XMLOFF_FORMS_LAYEREXPORT_HXX_\n#include \"layerexport.hxx\"\n#endif\n#ifndef _XMLOFF_FORMS_PROPERTYEXPORT_HXX_\n#include \"propertyexport.hxx\"\n#endif\n#ifndef _OSL_DIAGNOSE_H_\n#include \n#endif\n#ifndef _COMPHELPER_EXTRACT_HXX_\n#include \n#endif\n#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_\n#include \n#endif\n#ifndef _COMPHELPER_STLTYPES_HXX_\n#include \n#endif\n#ifndef _XMLOFF_FORMS_OFFICEFORMS_HXX_\n#include \"officeforms.hxx\"\n#endif\n\n\n\/\/.........................................................................\nnamespace xmloff\n{\n\/\/.........................................................................\n\n using namespace ::com::sun::star::uno;\n using namespace ::com::sun::star::lang;\n using namespace ::com::sun::star::awt;\n using namespace ::com::sun::star::beans;\n using namespace ::com::sun::star::container;\n using namespace ::com::sun::star::drawing;\n using namespace ::com::sun::star::frame;\n\n \/\/=====================================================================\n \/\/= OFormLayerXMLExport\n \/\/=====================================================================\n\n \/\/---------------------------------------------------------------------\n OFormLayerXMLExport::OFormLayerXMLExport(SvXMLExport& _rContext)\n :m_rContext(_rContext)\n ,m_pImpl(new OFormLayerXMLExport_Impl(_rContext))\n {\n }\n\n \/\/---------------------------------------------------------------------\n OFormLayerXMLExport::~OFormLayerXMLExport()\n {\n delete m_pImpl;\n m_pImpl = NULL;\n }\n\n \/\/---------------------------------------------------------------------\n sal_Bool OFormLayerXMLExport::seekPage(const Reference< XDrawPage >& _rxDrawPage)\n {\n return m_pImpl->seekPage(_rxDrawPage);\n }\n\n \/\/---------------------------------------------------------------------\n ::rtl::OUString OFormLayerXMLExport::getControlId(const Reference< XPropertySet >& _rxControl)\n {\n return m_pImpl->getControlId(_rxControl);\n }\n\n \/\/---------------------------------------------------------------------\n ::rtl::OUString OFormLayerXMLExport::getControlNumberStyle( const Reference< XPropertySet >& _rxControl )\n {\n return m_pImpl->getControlNumberStyle(_rxControl);\n }\n\n \/\/---------------------------------------------------------------------\n ::vos::ORef< SvXMLExportPropertyMapper > OFormLayerXMLExport::getStylePropertyMapper()\n {\n return m_pImpl->getStylePropertyMapper();\n }\n\n \/\/---------------------------------------------------------------------\n void OFormLayerXMLExport::initialize()\n {\n m_pImpl->clear();\n }\n\n \/\/---------------------------------------------------------------------\n void OFormLayerXMLExport::examineForms(const Reference< XDrawPage >& _rxDrawPage)\n {\n try\n {\n m_pImpl->examineForms(_rxDrawPage);\n }\n catch(Exception&)\n {\n OSL_ENSURE(sal_False, \"OFormLayerXMLExport::examine: could not examine the draw page!\");\n }\n }\n\n \/\/---------------------------------------------------------------------\n void OFormLayerXMLExport::exportForms(const Reference< XDrawPage >& _rxDrawPage)\n {\n m_pImpl->exportForms(_rxDrawPage);\n }\n\n \/\/---------------------------------------------------------------------\n void OFormLayerXMLExport::exportXForms() const\n {\n m_pImpl->exportXForms();\n }\n\n \/\/---------------------------------------------------------------------\n bool OFormLayerXMLExport::pageContainsForms( const Reference< XDrawPage >& _rxDrawPage ) const\n {\n return m_pImpl->pageContainsForms( _rxDrawPage );\n }\n\n \/\/---------------------------------------------------------------------\n bool OFormLayerXMLExport::documentContainsXForms() const\n {\n return m_pImpl->documentContainsXForms();\n }\n\n \/\/---------------------------------------------------------------------\n void OFormLayerXMLExport::exportControlNumberStyles()\n {\n m_pImpl->exportControlNumberStyles();\n }\n\n \/\/---------------------------------------------------------------------\n void OFormLayerXMLExport::exportAutoControlNumberStyles()\n {\n m_pImpl->exportAutoControlNumberStyles();\n }\n\n \/\/---------------------------------------------------------------------\n void OFormLayerXMLExport::exportAutoStyles()\n {\n m_pImpl->exportAutoStyles();\n }\n\n \/\/---------------------------------------------------------------------\n void OFormLayerXMLExport::excludeFromExport( const Reference< XControlModel > _rxControl )\n {\n m_pImpl->excludeFromExport( _rxControl );\n }\n\n \/\/=========================================================================\n \/\/= OOfficeFormsExport\n \/\/=========================================================================\n \/\/-------------------------------------------------------------------------\n OOfficeFormsExport::OOfficeFormsExport( SvXMLExport& _rExp )\n :m_pImpl(NULL)\n {\n m_pImpl = new OFormsRootExport(_rExp);\n }\n\n \/\/-------------------------------------------------------------------------\n OOfficeFormsExport::~OOfficeFormsExport()\n {\n delete m_pImpl;\n }\n\n\/\/.........................................................................\n} \/\/ namespace xmloff\n\/\/.........................................................................\n\n\/*************************************************************************\n * history:\n * $Log: not supported by cvs2svn $\n * Revision 1.14.94.1 2005\/09\/05 14:38:59 rt\n * #i54170# Change license header: remove SISSL\n *\n * Revision 1.14 2005\/03\/23 11:25:13 vg\n * INTEGRATION: CWS eforms4 (1.13.430); FILE MERGED\n * 2004\/12\/13 17:27:32 fs 1.13.430.1: #i36597# +exportXForms\/pageContainsForms\/documentContainsXForms\n *\n * Revision 1.13.430.1 2004\/12\/13 17:27:32 fs\n * #i36597# +exportXForms\/pageContainsForms\/documentContainsXForms\n *\n * Revision 1.13 2002\/10\/25 07:58:00 fs\n * #104402# re-introduced exportAutoStyles\n *\n * Revision 1.12 2002\/09\/25 12:02:38 fs\n * #103597# +excludeFromExport\n *\n * Revision 1.11 2001\/05\/28 14:59:18 fs\n * #86712# added control number style related functionality\n *\n * Revision 1.10 2001\/03\/20 13:35:38 fs\n * #83970# +OOfficeFormsExport\n *\n * Revision 1.9 2001\/03\/20 08:04:08 fs\n * removed exportAutoStyles (was obsolete)\n *\n * Revision 1.8 2001\/03\/16 14:36:39 sab\n * did the required change (move of extract.hxx form cppuhelper to comphelper)\n *\n * Revision 1.7 2001\/02\/01 09:46:47 fs\n * no own style handling anymore - the shape exporter is responsible for our styles now\n *\n * Revision 1.6 2000\/12\/18 16:22:35 fs\n * forgot an & on the getControlId parameter\n *\n * Revision 1.5 2000\/12\/18 15:14:35 fs\n * some changes ... now exporting\/importing styles\n *\n * Revision 1.4 2000\/12\/06 17:28:05 fs\n * changes for the formlayer import - still under construction\n *\n * Revision 1.3 2000\/12\/03 10:57:06 fs\n * some changes to support more than one page to be examined\/exported\n *\n * Revision 1.2 2000\/11\/29 10:32:13 mh\n * add: header for Solaris8\n *\n * Revision 1.1 2000\/11\/17 19:02:16 fs\n * initial checkin - export and\/or import the applications form layer\n *\n *\n * Revision 1.0 13.11.00 14:58:17 fs\n ************************************************************************\/\n\n<|endoftext|>"} {"text":"\/******************************************************************************\n * Copyright (c) 2014 Jamis Hoo \n * Distributed under the MIT license \n * (See accompanying file LICENSE or copy at http:\/\/opensource.org\/licenses\/MIT)\n * \n * Project: \n * Filename: test.cc \n * Version: 1.0\n * Author: Jamis Hoo\n * E-mail: hjm211324@gmail.com\n * Date: Dec. 29, 2014\n * Time: 11:10:09\n * Description: \n *****************************************************************************\/\n#include \n\nint main() {\n std::cout << \"Hello world!\" << std::endl;\n\n}\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n--allow-empty_message\/******************************************************************************\n * Copyright (c) 2014 Jamis Hoo \n * Distributed under the MIT license \n * (See accompanying file LICENSE or copy at http:\/\/opensource.org\/licenses\/MIT)\n * \n * Project: \n * Filename: test.cc \n * Version: 1.0\n * Author: Jamis Hoo\n * E-mail: hjm211324@gmail.com\n * Date: Dec. 29, 2014\n * Time: 11:10:09\n * Description: \n *****************************************************************************\/\n#include \n\nint main() {\n std::cout << \"Hello world!\" << std::endl;\n\n}\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n<|endoftext|>"} {"text":"#include \"cppbencode.h\"\n#include \n#include \n\nvoid verify(const ben::Value &value, const char *encoded)\n{\n\t\/* verify that the encoder produces the expected output *\/\n\tstd::ostringstream ss;\n\tvalue.write(ss);\n\tassert(ss.str() == encoded);\n\n\t\/* try to load the bencoded string, and check that it is equal *\/\n\tstd::istringstream parser(ss.str());\n\tben::Value value2;\n\tvalue2.load_all(parser);\n\tassert(value == value2);\n}\n\nvoid verify_error(const char *s, const char *error)\n{\n\tben::Value val;\n\tstd::istringstream ss(s);\n\ttry {\n\t\tval.load(ss);\n\t\t\/* should always raise an exception *\/\n\t\tassert(0);\n\t} catch (const ben::decode_error &e) {\n\t\tassert(e.what() == std::string(error));\n\t}\n}\n\nint main()\n{\n\tverify(0, \"i0e\");\n\tverify(1234, \"i1234e\");\n\tverify(-1234, \"i-1234e\");\n\tverify(std::string(\"foobar\"), \"6:foobar\");\n\tverify(std::string(\"\"), \"0:\");\n\tverify(true, \"b1\");\n\tverify(false, \"b0\");\n\n\tstd::vector arr;\n\tarr.push_back(std::string(\"foo\"));\n\tarr.push_back(1234);\n\tarr.push_back(true);\n\tverify(arr, \"l3:fooi1234eb1e\");\n\n\tben::dict_map_t dict;\n\tdict.insert(std::make_pair(\"bar\", arr));\n\tdict.insert(std::make_pair(\"foo\", std::string(\"test\")));\n\tverify(dict, \"d3:barl3:fooi1234eb1e3:foo4:teste\");\n\n\tverify_error(\"i1234\", \"Expected 'e'\");\n\tverify_error(\"dx\", \"Expected a digit\");\n\tverify_error(\"d-5\", \"Expected a digit\");\n\tverify_error(\"d123\", \"Expected ':'\");\n\tverify_error(\"i\", \"Unexpected end of input\");\n\tverify_error(\"i 1e\", \"Expected a digit or '-'\");\n\tverify_error(\"i1111111111111111111111e\", \"Invalid integer\");\n\tverify_error(\"i- 1e\", \"Invalid integer\");\n\tverify_error(\"i-0e\", \"Zero with a minus sign\");\n\tverify_error(\"i05e\", \"Integer has leading zeroes\");\n\tverify_error(\"06:foobar\", \"String length has leading zeroes\");\n\tverify_error(\"123\", \"Expected ':'\");\n\tverify_error(\"5:foo\", \"Unexpected end of input\");\n\tverify_error(\"l\", \"Unexpected end of input\");\n\n\ttry {\n\t\tben::Value val;\n\t\tstd::istringstream ss(\"d3:bari123ee\");\n\t\tval.load_all(ss);\n\t\tint i = val.get(\"foo\").as_integer();\n\t\t(void) i;\n\t} catch (const ben::type_error &e) {\n\t\tassert(e.what() == std::string(\"Expected type integer, but got null\"));\n\t}\n\n\ttry {\n\t\tben::Value val;\n\t\tstd::istringstream ss(\"d3:bari123e3:foob1e\");\n\t\tval.load_all(ss);\n\t\tint i = val.get(\"foo\").as_integer();\n\t\t(void) i;\n\t} catch (const ben::type_error &e) {\n\t\tassert(e.what() == std::string(\"Expected type integer, but got boolean\"));\n\t}\n\n\tprintf(\"ok\\n\");\n\treturn 0;\n}\ntest: Use simplier method to insert to std::map [CLEANUP]#include \"cppbencode.h\"\n#include \n#include \n\nvoid verify(const ben::Value &value, const char *encoded)\n{\n\t\/* verify that the encoder produces the expected output *\/\n\tstd::ostringstream ss;\n\tvalue.write(ss);\n\tassert(ss.str() == encoded);\n\n\t\/* try to load the bencoded string, and check that it is equal *\/\n\tstd::istringstream parser(ss.str());\n\tben::Value value2;\n\tvalue2.load_all(parser);\n\tassert(value == value2);\n}\n\nvoid verify_error(const char *s, const char *error)\n{\n\tben::Value val;\n\tstd::istringstream ss(s);\n\ttry {\n\t\tval.load(ss);\n\t\t\/* should always raise an exception *\/\n\t\tassert(0);\n\t} catch (const ben::decode_error &e) {\n\t\tassert(e.what() == std::string(error));\n\t}\n}\n\nint main()\n{\n\tverify(0, \"i0e\");\n\tverify(1234, \"i1234e\");\n\tverify(-1234, \"i-1234e\");\n\tverify(std::string(\"foobar\"), \"6:foobar\");\n\tverify(std::string(\"\"), \"0:\");\n\tverify(true, \"b1\");\n\tverify(false, \"b0\");\n\n\tstd::vector arr;\n\tarr.push_back(std::string(\"foo\"));\n\tarr.push_back(1234);\n\tarr.push_back(true);\n\tverify(arr, \"l3:fooi1234eb1e\");\n\n\tben::dict_map_t dict;\n\tdict[\"bar\"] = arr;\n\tdict[\"foo\"] = std::string(\"test\");\n\tverify(dict, \"d3:barl3:fooi1234eb1e3:foo4:teste\");\n\n\tverify_error(\"i1234\", \"Expected 'e'\");\n\tverify_error(\"dx\", \"Expected a digit\");\n\tverify_error(\"d-5\", \"Expected a digit\");\n\tverify_error(\"d123\", \"Expected ':'\");\n\tverify_error(\"i\", \"Unexpected end of input\");\n\tverify_error(\"i 1e\", \"Expected a digit or '-'\");\n\tverify_error(\"i1111111111111111111111e\", \"Invalid integer\");\n\tverify_error(\"i- 1e\", \"Invalid integer\");\n\tverify_error(\"i-0e\", \"Zero with a minus sign\");\n\tverify_error(\"i05e\", \"Integer has leading zeroes\");\n\tverify_error(\"06:foobar\", \"String length has leading zeroes\");\n\tverify_error(\"123\", \"Expected ':'\");\n\tverify_error(\"5:foo\", \"Unexpected end of input\");\n\tverify_error(\"l\", \"Unexpected end of input\");\n\n\ttry {\n\t\tben::Value val;\n\t\tstd::istringstream ss(\"d3:bari123ee\");\n\t\tval.load_all(ss);\n\t\tint i = val.get(\"foo\").as_integer();\n\t\t(void) i;\n\t} catch (const ben::type_error &e) {\n\t\tassert(e.what() == std::string(\"Expected type integer, but got null\"));\n\t}\n\n\ttry {\n\t\tben::Value val;\n\t\tstd::istringstream ss(\"d3:bari123e3:foob1e\");\n\t\tval.load_all(ss);\n\t\tint i = val.get(\"foo\").as_integer();\n\t\t(void) i;\n\t} catch (const ben::type_error &e) {\n\t\tassert(e.what() == std::string(\"Expected type integer, but got boolean\"));\n\t}\n\n\tprintf(\"ok\\n\");\n\treturn 0;\n}\n<|endoftext|>"} {"text":"\/\/=======================================================================\n\/\/ Copyright (c) 2013-2020 Baptiste Wicht\n\/\/ Distributed under the terms of the MIT License.\n\/\/ (See accompanying file LICENSE or copy at\n\/\/ http:\/\/opensource.org\/licenses\/MIT)\n\/\/=======================================================================\n\n#include \"test.hpp\"\n#include \"date.hpp\"\n\nusing namespace std::string_literals;\n\nTEST_CASE(\"date\/to_string\") {\n budget::date a(1988, 4, 9);\n\n FAST_CHECK_EQ(budget::date_to_string(a), \"1988-04-09\"s);\n FAST_CHECK_EQ(budget::to_string(a), \"1988-04-09\"s);\n\n budget::date b(2111, 10, 10);\n\n FAST_CHECK_EQ(budget::date_to_string(b), \"2111-10-10\"s);\n FAST_CHECK_EQ(budget::to_string(b), \"2111-10-10\"s);\n}\n\nTEST_CASE(\"date\/from_string\") {\n auto as = budget::from_string(\"1988-04-09\");\n auto bs = budget::from_string(\"2111-10-10\");\n\n budget::date a(1988, 4, 9);\n budget::date b(2111, 10, 10);\n\n FAST_CHECK_EQ(a, as);\n FAST_CHECK_EQ(b, bs);\n}\n\nTEST_CASE(\"date\/minus\/days\") {\n budget::date a(2010, 5, 6);\n a -= budget::days(1);\n\n FAST_CHECK_EQ(a.year(), 2010);\n FAST_CHECK_EQ(a.month(), 5);\n FAST_CHECK_EQ(a.day(), 5);\n\n a -= budget::days(10);\n\n FAST_CHECK_EQ(a.year(), 2010);\n FAST_CHECK_EQ(a.month(), 4);\n FAST_CHECK_EQ(a.day(), 25);\n}\n\nTEST_CASE(\"date\/minus\/month\") {\n budget::date a(2010, 5, 6);\n a -= budget::months(1);\n\n FAST_CHECK_EQ(a.year(), 2010);\n FAST_CHECK_EQ(a.month(), 4);\n FAST_CHECK_EQ(a.day(), 6);\n\n a -= budget::months(10);\n\n FAST_CHECK_EQ(a.year(), 2009);\n FAST_CHECK_EQ(a.month(), 6);\n FAST_CHECK_EQ(a.day(), 6);\n}\n\nTEST_CASE(\"date\/minus\/years\") {\n budget::date a(2010, 5, 6);\n a -= budget::years(1);\n\n FAST_CHECK_EQ(a.year(), 2009);\n FAST_CHECK_EQ(a.month(), 5);\n FAST_CHECK_EQ(a.day(), 6);\n\n a -= budget::years(10);\n\n FAST_CHECK_EQ(a.year(), 1999);\n FAST_CHECK_EQ(a.month(), 5);\n FAST_CHECK_EQ(a.day(), 6);\n}\n\nTEST_CASE(\"date\/plus\/days\") {\n budget::date a(2010, 5, 6);\n a += budget::days(1);\n\n FAST_CHECK_EQ(a.year(), 2010);\n FAST_CHECK_EQ(a.month(), 5);\n FAST_CHECK_EQ(a.day(), 7);\n\n a += budget::days(30);\n\n FAST_CHECK_EQ(a.year(), 2010);\n FAST_CHECK_EQ(a.month(), 6);\n FAST_CHECK_EQ(a.day(), 6);\n}\n\nTEST_CASE(\"date\/plus\/month\") {\n budget::date a(2010, 5, 6);\n a += budget::months(1);\n\n FAST_CHECK_EQ(a.year(), 2010);\n FAST_CHECK_EQ(a.month(), 6);\n FAST_CHECK_EQ(a.day(), 6);\n\n a += budget::months(10);\n\n FAST_CHECK_EQ(a.year(), 2011);\n FAST_CHECK_EQ(a.month(), 4);\n FAST_CHECK_EQ(a.day(), 6);\n}\n\nTEST_CASE(\"date\/plus\/years\") {\n budget::date a(2010, 5, 6);\n a += budget::years(1);\n\n FAST_CHECK_EQ(a.year(), 2011);\n FAST_CHECK_EQ(a.month(), 5);\n FAST_CHECK_EQ(a.day(), 6);\n\n a += budget::years(10);\n\n FAST_CHECK_EQ(a.year(), 2021);\n FAST_CHECK_EQ(a.month(), 5);\n FAST_CHECK_EQ(a.day(), 6);\n}\n\nTEST_CASE(\"date\/is_leap\") {\n FAST_CHECK_UNARY(budget::date(1804, 1, 1).is_leap());\n FAST_CHECK_UNARY(budget::date(1944, 1, 1).is_leap());\n FAST_CHECK_UNARY(budget::date(2000, 1, 1).is_leap());\n FAST_CHECK_UNARY(budget::date(2212, 1, 1).is_leap());\n FAST_CHECK_UNARY(budget::date(2400, 1, 1).is_leap());\n\n FAST_CHECK_UNARY(!budget::date(1805, 1, 1).is_leap());\n FAST_CHECK_UNARY(!budget::date(1943, 1, 1).is_leap());\n FAST_CHECK_UNARY(!budget::date(2001, 1, 1).is_leap());\n FAST_CHECK_UNARY(!budget::date(2399, 1, 1).is_leap());\n}\n\nTEST_CASE(\"date\/day_of_the_week\") {\n \/\/ A leap year\n FAST_CHECK_EQ(budget::date(2000, 3, 3).day_of_the_week(), 5);\n FAST_CHECK_EQ(budget::date(2000, 3, 4).day_of_the_week(), 6);\n FAST_CHECK_EQ(budget::date(2000, 3, 5).day_of_the_week(), 7);\n FAST_CHECK_EQ(budget::date(2000, 3, 6).day_of_the_week(), 1);\n\n \/\/ A non-leap year\n FAST_CHECK_EQ(budget::date(2019, 3, 3).day_of_the_week(), 7);\n FAST_CHECK_EQ(budget::date(2019, 3, 4).day_of_the_week(), 1);\n FAST_CHECK_EQ(budget::date(2019, 3, 5).day_of_the_week(), 2);\n FAST_CHECK_EQ(budget::date(2019, 3, 6).day_of_the_week(), 3);\n FAST_CHECK_EQ(budget::date(2019, 3, 7).day_of_the_week(), 4);\n}\n\n\/\/ TODO Test for leap years\n\/\/ TODO Test for start_of_week\n\/\/ TODO Test for start_of_month\n\/\/ TODO Test for end_of_month\n\/\/ TODO Test for week()\n\/\/ TODO Test for year_days()\n\/\/ TODO Test for comparisons\n\/\/ TODO Test for date differences\nComplete the unit test\/\/=======================================================================\n\/\/ Copyright (c) 2013-2020 Baptiste Wicht\n\/\/ Distributed under the terms of the MIT License.\n\/\/ (See accompanying file LICENSE or copy at\n\/\/ http:\/\/opensource.org\/licenses\/MIT)\n\/\/=======================================================================\n\n#include \"test.hpp\"\n#include \"date.hpp\"\n\nusing namespace std::string_literals;\n\nTEST_CASE(\"date\/to_string\") {\n budget::date a(1988, 4, 9);\n\n FAST_CHECK_EQ(budget::date_to_string(a), \"1988-04-09\"s);\n FAST_CHECK_EQ(budget::to_string(a), \"1988-04-09\"s);\n\n budget::date b(2111, 10, 10);\n\n FAST_CHECK_EQ(budget::date_to_string(b), \"2111-10-10\"s);\n FAST_CHECK_EQ(budget::to_string(b), \"2111-10-10\"s);\n}\n\nTEST_CASE(\"date\/from_string\/1\") {\n auto as = budget::from_string(\"1988-04-09\");\n auto bs = budget::from_string(\"2111-10-10\");\n\n budget::date a(1988, 4, 9);\n budget::date b(2111, 10, 10);\n\n FAST_CHECK_EQ(a, as);\n FAST_CHECK_EQ(b, bs);\n}\n\nTEST_CASE(\"date\/from_string\/1\") {\n \/\/ Size must be 10 exactly\n REQUIRE_THROWS_AS(budget::from_string(\"1988-4-9\"), budget::date_exception);\n REQUIRE_THROWS_AS(budget::from_string(\"1988-04-9\"), budget::date_exception);\n REQUIRE_THROWS_AS(budget::from_string(\"88-04-09\"), budget::date_exception);\n REQUIRE_THROWS_AS(budget::from_string(\"1988 -04-9\"), budget::date_exception);\n}\n\nTEST_CASE(\"date\/from_string\/2\") {\n \/\/ Each of the parts must be exactly a number\n REQUIRE_THROWS_AS(budget::from_string(\"abcd-4-9\"), budget::date_exception);\n REQUIRE_THROWS_AS(budget::from_string(\"1988-AB-9\"), budget::date_exception);\n REQUIRE_THROWS_AS(budget::from_string(\"88-04-9a\"), budget::date_exception);\n REQUIRE_THROWS_AS(budget::from_string(\"1988--4-9\"), budget::date_exception);\n REQUIRE_THROWS_AS(budget::from_string(\"19o8--4-9\"), budget::date_exception);\n REQUIRE_THROWS_AS(budget::from_string(\"198 -04-09\"), budget::date_exception);\n}\n\nTEST_CASE(\"date\/minus\/days\") {\n budget::date a(2010, 5, 6);\n a -= budget::days(1);\n\n FAST_CHECK_EQ(a.year(), 2010);\n FAST_CHECK_EQ(a.month(), 5);\n FAST_CHECK_EQ(a.day(), 5);\n\n a -= budget::days(10);\n\n FAST_CHECK_EQ(a.year(), 2010);\n FAST_CHECK_EQ(a.month(), 4);\n FAST_CHECK_EQ(a.day(), 25);\n}\n\nTEST_CASE(\"date\/minus\/month\") {\n budget::date a(2010, 5, 6);\n a -= budget::months(1);\n\n FAST_CHECK_EQ(a.year(), 2010);\n FAST_CHECK_EQ(a.month(), 4);\n FAST_CHECK_EQ(a.day(), 6);\n\n a -= budget::months(10);\n\n FAST_CHECK_EQ(a.year(), 2009);\n FAST_CHECK_EQ(a.month(), 6);\n FAST_CHECK_EQ(a.day(), 6);\n}\n\nTEST_CASE(\"date\/minus\/years\") {\n budget::date a(2010, 5, 6);\n a -= budget::years(1);\n\n FAST_CHECK_EQ(a.year(), 2009);\n FAST_CHECK_EQ(a.month(), 5);\n FAST_CHECK_EQ(a.day(), 6);\n\n a -= budget::years(10);\n\n FAST_CHECK_EQ(a.year(), 1999);\n FAST_CHECK_EQ(a.month(), 5);\n FAST_CHECK_EQ(a.day(), 6);\n}\n\nTEST_CASE(\"date\/plus\/days\") {\n budget::date a(2010, 5, 6);\n a += budget::days(1);\n\n FAST_CHECK_EQ(a.year(), 2010);\n FAST_CHECK_EQ(a.month(), 5);\n FAST_CHECK_EQ(a.day(), 7);\n\n a += budget::days(30);\n\n FAST_CHECK_EQ(a.year(), 2010);\n FAST_CHECK_EQ(a.month(), 6);\n FAST_CHECK_EQ(a.day(), 6);\n}\n\nTEST_CASE(\"date\/plus\/month\") {\n budget::date a(2010, 5, 6);\n a += budget::months(1);\n\n FAST_CHECK_EQ(a.year(), 2010);\n FAST_CHECK_EQ(a.month(), 6);\n FAST_CHECK_EQ(a.day(), 6);\n\n a += budget::months(10);\n\n FAST_CHECK_EQ(a.year(), 2011);\n FAST_CHECK_EQ(a.month(), 4);\n FAST_CHECK_EQ(a.day(), 6);\n}\n\nTEST_CASE(\"date\/plus\/years\") {\n budget::date a(2010, 5, 6);\n a += budget::years(1);\n\n FAST_CHECK_EQ(a.year(), 2011);\n FAST_CHECK_EQ(a.month(), 5);\n FAST_CHECK_EQ(a.day(), 6);\n\n a += budget::years(10);\n\n FAST_CHECK_EQ(a.year(), 2021);\n FAST_CHECK_EQ(a.month(), 5);\n FAST_CHECK_EQ(a.day(), 6);\n}\n\nTEST_CASE(\"date\/is_leap\") {\n FAST_CHECK_UNARY(budget::date(1804, 1, 1).is_leap());\n FAST_CHECK_UNARY(budget::date(1944, 1, 1).is_leap());\n FAST_CHECK_UNARY(budget::date(2000, 1, 1).is_leap());\n FAST_CHECK_UNARY(budget::date(2212, 1, 1).is_leap());\n FAST_CHECK_UNARY(budget::date(2400, 1, 1).is_leap());\n\n FAST_CHECK_UNARY(!budget::date(1805, 1, 1).is_leap());\n FAST_CHECK_UNARY(!budget::date(1943, 1, 1).is_leap());\n FAST_CHECK_UNARY(!budget::date(2001, 1, 1).is_leap());\n FAST_CHECK_UNARY(!budget::date(2399, 1, 1).is_leap());\n}\n\nTEST_CASE(\"date\/day_of_the_week\") {\n \/\/ A leap year\n FAST_CHECK_EQ(budget::date(2000, 3, 3).day_of_the_week(), 5);\n FAST_CHECK_EQ(budget::date(2000, 3, 4).day_of_the_week(), 6);\n FAST_CHECK_EQ(budget::date(2000, 3, 5).day_of_the_week(), 7);\n FAST_CHECK_EQ(budget::date(2000, 3, 6).day_of_the_week(), 1);\n\n \/\/ A non-leap year\n FAST_CHECK_EQ(budget::date(2019, 3, 3).day_of_the_week(), 7);\n FAST_CHECK_EQ(budget::date(2019, 3, 4).day_of_the_week(), 1);\n FAST_CHECK_EQ(budget::date(2019, 3, 5).day_of_the_week(), 2);\n FAST_CHECK_EQ(budget::date(2019, 3, 6).day_of_the_week(), 3);\n FAST_CHECK_EQ(budget::date(2019, 3, 7).day_of_the_week(), 4);\n}\n\n\/\/ TODO Test for leap years\n\/\/ TODO Test for start_of_week\n\/\/ TODO Test for start_of_month\n\/\/ TODO Test for end_of_month\n\/\/ TODO Test for week()\n\/\/ TODO Test for year_days()\n\/\/ TODO Test for comparisons\n\/\/ TODO Test for date differences\n<|endoftext|>"} {"text":"\/\/=======================================================================\n\/\/ Copyright (c) 2013-2020 Baptiste Wicht\n\/\/ Distributed under the terms of the MIT License.\n\/\/ (See accompanying file LICENSE or copy at\n\/\/ http:\/\/opensource.org\/licenses\/MIT)\n\/\/=======================================================================\n\n#include \"test.hpp\"\n#include \"date.hpp\"\n\nusing namespace std::string_literals;\n\nTEST_CASE(\"date\/to_string\") {\n budget::date a(1988, 4, 9);\n\n FAST_CHECK_EQ(budget::date_to_string(a), \"1988-04-09\"s);\n FAST_CHECK_EQ(budget::to_string(a), \"1988-04-09\"s);\n\n budget::date b(2111, 10, 10);\n\n FAST_CHECK_EQ(budget::date_to_string(b), \"2111-10-10\"s);\n FAST_CHECK_EQ(budget::to_string(b), \"2111-10-10\"s);\n}\n\nTEST_CASE(\"date\/from_string\") {\n auto as = budget::from_string(\"1988-04-09\");\n auto bs = budget::from_string(\"2111-10-10\");\n\n budget::date a(1988, 4, 9);\n budget::date b(2111, 10, 10);\n\n FAST_CHECK_EQ(a, as);\n FAST_CHECK_EQ(b, bs);\n}\n\nTEST_CASE(\"date\/minus\/days\") {\n budget::date a(2010, 5, 6);\n a -= budget::days(1);\n\n FAST_CHECK_EQ(a.year(), 2010);\n FAST_CHECK_EQ(a.month(), 5);\n FAST_CHECK_EQ(a.day(), 5);\n\n a -= budget::days(10);\n\n FAST_CHECK_EQ(a.year(), 2010);\n FAST_CHECK_EQ(a.month(), 4);\n FAST_CHECK_EQ(a.day(), 25);\n}\n\nTEST_CASE(\"date\/minus\/month\") {\n budget::date a(2010, 5, 6);\n a -= budget::months(1);\n\n FAST_CHECK_EQ(a.year(), 2010);\n FAST_CHECK_EQ(a.month(), 4);\n FAST_CHECK_EQ(a.day(), 6);\n\n a -= budget::months(10);\n\n FAST_CHECK_EQ(a.year(), 2009);\n FAST_CHECK_EQ(a.month(), 6);\n FAST_CHECK_EQ(a.day(), 6);\n}\n\nTEST_CASE(\"date\/minus\/years\") {\n budget::date a(2010, 5, 6);\n a -= budget::years(1);\n\n FAST_CHECK_EQ(a.year(), 2009);\n FAST_CHECK_EQ(a.month(), 5);\n FAST_CHECK_EQ(a.day(), 6);\n\n a -= budget::years(10);\n\n FAST_CHECK_EQ(a.year(), 1999);\n FAST_CHECK_EQ(a.month(), 5);\n FAST_CHECK_EQ(a.day(), 6);\n}\n\nTEST_CASE(\"date\/plus\/days\") {\n budget::date a(2010, 5, 6);\n a += budget::days(1);\n\n FAST_CHECK_EQ(a.year(), 2010);\n FAST_CHECK_EQ(a.month(), 5);\n FAST_CHECK_EQ(a.day(), 7);\n\n a += budget::days(30);\n\n FAST_CHECK_EQ(a.year(), 2010);\n FAST_CHECK_EQ(a.month(), 6);\n FAST_CHECK_EQ(a.day(), 6);\n}\n\nTEST_CASE(\"date\/plus\/month\") {\n budget::date a(2010, 5, 6);\n a += budget::months(1);\n\n FAST_CHECK_EQ(a.year(), 2010);\n FAST_CHECK_EQ(a.month(), 6);\n FAST_CHECK_EQ(a.day(), 6);\n\n a += budget::months(10);\n\n FAST_CHECK_EQ(a.year(), 2011);\n FAST_CHECK_EQ(a.month(), 4);\n FAST_CHECK_EQ(a.day(), 6);\n}\n\nTEST_CASE(\"date\/plus\/years\") {\n budget::date a(2010, 5, 6);\n a += budget::years(1);\n\n FAST_CHECK_EQ(a.year(), 2011);\n FAST_CHECK_EQ(a.month(), 5);\n FAST_CHECK_EQ(a.day(), 6);\n\n a += budget::years(10);\n\n FAST_CHECK_EQ(a.year(), 2021);\n FAST_CHECK_EQ(a.month(), 5);\n FAST_CHECK_EQ(a.day(), 6);\n}\n\n\/\/ TODO Test for leap years\n\/\/ TODO Test for start_of_week\n\/\/ TODO Test for start_of_month\n\/\/ TODO Test for week()\n\/\/ TODO Test for year_days()\n\/\/ TODO Test for day_of_the_week\n\/\/ TODO Test for comparisons\n\/\/ TODO Test for date differences\nUnit tests for is_leap\/\/=======================================================================\n\/\/ Copyright (c) 2013-2020 Baptiste Wicht\n\/\/ Distributed under the terms of the MIT License.\n\/\/ (See accompanying file LICENSE or copy at\n\/\/ http:\/\/opensource.org\/licenses\/MIT)\n\/\/=======================================================================\n\n#include \"test.hpp\"\n#include \"date.hpp\"\n\nusing namespace std::string_literals;\n\nTEST_CASE(\"date\/to_string\") {\n budget::date a(1988, 4, 9);\n\n FAST_CHECK_EQ(budget::date_to_string(a), \"1988-04-09\"s);\n FAST_CHECK_EQ(budget::to_string(a), \"1988-04-09\"s);\n\n budget::date b(2111, 10, 10);\n\n FAST_CHECK_EQ(budget::date_to_string(b), \"2111-10-10\"s);\n FAST_CHECK_EQ(budget::to_string(b), \"2111-10-10\"s);\n}\n\nTEST_CASE(\"date\/from_string\") {\n auto as = budget::from_string(\"1988-04-09\");\n auto bs = budget::from_string(\"2111-10-10\");\n\n budget::date a(1988, 4, 9);\n budget::date b(2111, 10, 10);\n\n FAST_CHECK_EQ(a, as);\n FAST_CHECK_EQ(b, bs);\n}\n\nTEST_CASE(\"date\/minus\/days\") {\n budget::date a(2010, 5, 6);\n a -= budget::days(1);\n\n FAST_CHECK_EQ(a.year(), 2010);\n FAST_CHECK_EQ(a.month(), 5);\n FAST_CHECK_EQ(a.day(), 5);\n\n a -= budget::days(10);\n\n FAST_CHECK_EQ(a.year(), 2010);\n FAST_CHECK_EQ(a.month(), 4);\n FAST_CHECK_EQ(a.day(), 25);\n}\n\nTEST_CASE(\"date\/minus\/month\") {\n budget::date a(2010, 5, 6);\n a -= budget::months(1);\n\n FAST_CHECK_EQ(a.year(), 2010);\n FAST_CHECK_EQ(a.month(), 4);\n FAST_CHECK_EQ(a.day(), 6);\n\n a -= budget::months(10);\n\n FAST_CHECK_EQ(a.year(), 2009);\n FAST_CHECK_EQ(a.month(), 6);\n FAST_CHECK_EQ(a.day(), 6);\n}\n\nTEST_CASE(\"date\/minus\/years\") {\n budget::date a(2010, 5, 6);\n a -= budget::years(1);\n\n FAST_CHECK_EQ(a.year(), 2009);\n FAST_CHECK_EQ(a.month(), 5);\n FAST_CHECK_EQ(a.day(), 6);\n\n a -= budget::years(10);\n\n FAST_CHECK_EQ(a.year(), 1999);\n FAST_CHECK_EQ(a.month(), 5);\n FAST_CHECK_EQ(a.day(), 6);\n}\n\nTEST_CASE(\"date\/plus\/days\") {\n budget::date a(2010, 5, 6);\n a += budget::days(1);\n\n FAST_CHECK_EQ(a.year(), 2010);\n FAST_CHECK_EQ(a.month(), 5);\n FAST_CHECK_EQ(a.day(), 7);\n\n a += budget::days(30);\n\n FAST_CHECK_EQ(a.year(), 2010);\n FAST_CHECK_EQ(a.month(), 6);\n FAST_CHECK_EQ(a.day(), 6);\n}\n\nTEST_CASE(\"date\/plus\/month\") {\n budget::date a(2010, 5, 6);\n a += budget::months(1);\n\n FAST_CHECK_EQ(a.year(), 2010);\n FAST_CHECK_EQ(a.month(), 6);\n FAST_CHECK_EQ(a.day(), 6);\n\n a += budget::months(10);\n\n FAST_CHECK_EQ(a.year(), 2011);\n FAST_CHECK_EQ(a.month(), 4);\n FAST_CHECK_EQ(a.day(), 6);\n}\n\nTEST_CASE(\"date\/plus\/years\") {\n budget::date a(2010, 5, 6);\n a += budget::years(1);\n\n FAST_CHECK_EQ(a.year(), 2011);\n FAST_CHECK_EQ(a.month(), 5);\n FAST_CHECK_EQ(a.day(), 6);\n\n a += budget::years(10);\n\n FAST_CHECK_EQ(a.year(), 2021);\n FAST_CHECK_EQ(a.month(), 5);\n FAST_CHECK_EQ(a.day(), 6);\n}\n\nTEST_CASE(\"date\/is_leap\") {\n FAST_CHECK_UNARY(budget::date(1804, 1, 1).is_leap());\n FAST_CHECK_UNARY(budget::date(1944, 1, 1).is_leap());\n FAST_CHECK_UNARY(budget::date(2000, 1, 1).is_leap());\n FAST_CHECK_UNARY(budget::date(2212, 1, 1).is_leap());\n FAST_CHECK_UNARY(budget::date(2400, 1, 1).is_leap());\n\n FAST_CHECK_UNARY(!budget::date(1805, 1, 1).is_leap());\n FAST_CHECK_UNARY(!budget::date(1943, 1, 1).is_leap());\n FAST_CHECK_UNARY(!budget::date(2001, 1, 1).is_leap());\n FAST_CHECK_UNARY(!budget::date(2399, 1, 1).is_leap());\n}\n\n\/\/ TODO Test for leap years\n\/\/ TODO Test for start_of_week\n\/\/ TODO Test for start_of_month\n\/\/ TODO Test for week()\n\/\/ TODO Test for year_days()\n\/\/ TODO Test for day_of_the_week\n\/\/ TODO Test for comparisons\n\/\/ TODO Test for date differences\n<|endoftext|>"} {"text":"\/\/ csastil_uppernames.cpp -*-C++-*-\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace csabase { class PPObserver; }\nnamespace csabase { class Visitor; }\n\nusing namespace clang;\nusing namespace clang::ast_matchers;\nusing namespace csabase;\n\n\/\/ ----------------------------------------------------------------------------\n\nstatic std::string const check_name(\"upper-case-names\");\n\n\/\/ ----------------------------------------------------------------------------\n\nnamespace\n{\n\nstruct data\n{\n data();\n\n std::set d_decls;\n};\n\ndata::data()\n{\n}\n\nstruct report\n \/\/ Complain about upper-case only variables and constants.\n{\n report(Analyser& analyser);\n \/\/ Create an object of this type using the specified analyser.\n\n void match_has_name(const BoundNodes& nodes);\n \/\/ Find named declarations.\n\n void operator()();\n \/\/ Callback invoked at end of translation unit.\n\n Analyser& d_analyser;\n data& d_data;\n};\n\nreport::report(Analyser& analyser)\n: d_analyser(analyser)\n, d_data(analyser.attachment())\n{\n}\n\ninternal::DynTypedMatcher has_name_matcher()\n \/\/ Return an AST matcher which looks for named declarations.\n{\n return decl(forEachDescendant(namedDecl().bind(\"decl\")));\n}\n\nvoid report::match_has_name(const BoundNodes& nodes)\n{\n NamedDecl const* decl = nodes.getNodeAs(\"decl\");\n if (!d_data.d_decls.insert(decl).second) {\n return; \/\/ RETURN\n }\n if (decl->getLocation().isMacroID()) {\n return; \/\/ RETURN\n }\n if (!d_analyser.is_component(decl)) {\n return; \/\/ RETURN\n }\n if (llvm::dyn_cast(decl) ||\n llvm::dyn_cast(decl) ||\n llvm::dyn_cast(decl)) {\n return; \/\/ RETURN\n }\n if (FunctionDecl const* func = llvm::dyn_cast(decl)) {\n if (func->isDefaulted()) {\n return; \/\/ RETURN\n }\n }\n if (RecordDecl const* record = llvm::dyn_cast(decl)) {\n if (record->isInjectedClassName()) {\n return; \/\/ RETURN\n }\n }\n\n IdentifierInfo const* ii = decl->getIdentifier();\n if (ii) {\n llvm::StringRef name = ii->getName();\n if (name.find_first_of(\"abcdefghijklmnopqrstuvwxyz\") == name.npos &&\n name.find_first_of(\"ABCDEFGHIJKLMNOPQRSTUVWXYZ\") != name.npos &&\n name.find(llvm::StringRef(d_analyser.component()).upper()) ==\n name.npos) {\n d_analyser.report(decl, check_name, \"UC01\",\n \"Name should not be all upper-case\");\n }\n }\n\n if (TemplateDecl const* tplt = llvm::dyn_cast(decl)) {\n d_data.d_decls.insert(tplt->getTemplatedDecl());\n }\n}\n\nvoid report::operator()()\n{\n if (!d_analyser.is_test_driver()) {\n MatchFinder mf;\n OnMatch m1(this);\n mf.addDynamicMatcher(has_name_matcher(), &m1);\n mf.match(*d_analyser.context()->getTranslationUnitDecl(),\n *d_analyser.context());\n }\n}\n\nvoid subscribe(Analyser& analyser, Visitor&, PPObserver&)\n{\n analyser.onTranslationUnitDone += report(analyser);\n}\n\n}\n\n\/\/ ----------------------------------------------------------------------------\n\nstatic RegisterCheck c1(check_name, &subscribe);\n\n\/\/ ----------------------------------------------------------------------------\n\/\/ Copyright (C) 2014 Bloomberg Finance L.P.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/ ----------------------------- END-OF-FILE ----------------------------------\nDon't warn inside #ifndef BDE_OMIT_INTERNAL_DEPRECATED.\/\/ csastil_uppernames.cpp -*-C++-*-\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace csabase { class PPObserver; }\nnamespace csabase { class Visitor; }\n\nusing namespace clang;\nusing namespace clang::ast_matchers;\nusing namespace csabase;\n\n\/\/ ----------------------------------------------------------------------------\n\nstatic std::string const check_name(\"upper-case-names\");\n\n\/\/ ----------------------------------------------------------------------------\n\nnamespace\n{\n\nstruct data\n{\n std::set d_decls;\n std::vector d_omit_internal_deprecated;\n};\n\nstruct report : Report\n \/\/ Complain about upper-case only variables and constants.\n{\n INHERIT_REPORT_CTOR(report, Report, data);\n\n void match_has_name(const BoundNodes& nodes);\n \/\/ Find named declarations.\n\n void operator()();\n \/\/ Callback invoked at end of translation unit.\n\n void operator()(SourceLocation,\n SourceRange,\n PPCallbacks::ConditionValueKind,\n SourceLocation);\n \/\/ Callback for #elif.\n\n void operator()(SourceLocation, const Token &, const MacroDefinition &);\n \/\/ Callback for #ifndef.\n\n void operator()(SourceLocation, SourceLocation);\n \/\/ Callback for #else\/#endif.\n};\n\ninternal::DynTypedMatcher has_name_matcher()\n \/\/ Return an AST matcher which looks for named declarations.\n{\n return decl(forEachDescendant(namedDecl().bind(\"decl\")));\n}\n\nvoid report::match_has_name(const BoundNodes& nodes)\n{\n NamedDecl const* decl = nodes.getNodeAs(\"decl\");\n if (!d_data.d_decls.insert(decl).second) {\n return; \/\/ RETURN\n }\n if (decl->getLocation().isMacroID()) {\n return; \/\/ RETURN\n }\n if (!d_analyser.is_component(decl)) {\n return; \/\/ RETURN\n }\n if (llvm::dyn_cast(decl) ||\n llvm::dyn_cast(decl) ||\n llvm::dyn_cast(decl)) {\n return; \/\/ RETURN\n }\n if (FunctionDecl const* func = llvm::dyn_cast(decl)) {\n if (func->isDefaulted()) {\n return; \/\/ RETURN\n }\n }\n if (RecordDecl const* record = llvm::dyn_cast(decl)) {\n if (record->isInjectedClassName()) {\n return; \/\/ RETURN\n }\n }\n\n IdentifierInfo const* ii = decl->getIdentifier();\n if (ii) {\n llvm::StringRef name = ii->getName();\n if (name.find_first_of(\"abcdefghijklmnopqrstuvwxyz\") == name.npos &&\n name.find_first_of(\"ABCDEFGHIJKLMNOPQRSTUVWXYZ\") != name.npos &&\n name.find(llvm::StringRef(d_analyser.component()).upper()) ==\n name.npos) {\n bool omit = false;\n for (auto i : d.d_omit_internal_deprecated) {\n if (m.isBeforeInTranslationUnit(i.getBegin(),\n decl->getLocation()) &&\n m.isBeforeInTranslationUnit(decl->getLocation(),\n i.getEnd())) {\n omit = true;\n break;\n }\n }\n if (!omit) {\n d_analyser.report(decl, check_name, \"UC01\",\n \"Name should not be all upper-case\");\n }\n }\n }\n\n if (TemplateDecl const* tplt = llvm::dyn_cast(decl)) {\n d_data.d_decls.insert(tplt->getTemplatedDecl());\n }\n}\n\nvoid report::operator()()\n{\n if (!d_analyser.is_test_driver()) {\n MatchFinder mf;\n OnMatch m1(this);\n mf.addDynamicMatcher(has_name_matcher(), &m1);\n mf.match(*d_analyser.context()->getTranslationUnitDecl(),\n *d_analyser.context());\n }\n}\n\n\/\/ Ifndef\nvoid report::operator()(SourceLocation loc,\n const Token& macro,\n const MacroDefinition& md)\n{\n if (macro.getIdentifierInfo()->getName() ==\n \"BDE_OMIT_INTERNAL_DEPRECATED\") {\n d.d_omit_internal_deprecated.emplace_back(loc);\n }\n}\n\n\/\/ Else\n\/\/ Endif\nvoid report::operator()(SourceLocation loc, SourceLocation ifloc)\n \/\/ Callback for #else\/#endif.\n{\n for (auto &i : d.d_omit_internal_deprecated) {\n if (i.getBegin() == ifloc && i.getEnd() == ifloc) {\n i.setEnd(loc);\n }\n }\n}\n\n\/\/ Elif\nvoid report::operator()(SourceLocation loc,\n SourceRange condition,\n PPCallbacks::ConditionValueKind kind,\n SourceLocation ifloc)\n{\n (*this)(loc, ifloc);\n}\n\nvoid subscribe(Analyser& analyser, Visitor&, PPObserver& observer)\n{\n analyser.onTranslationUnitDone += report(analyser);\n\n observer.onPPIfndef += report(analyser, observer.e_Ifndef);\n observer.onPPElif += report(analyser, observer.e_Elif);\n observer.onPPElse += report(analyser, observer.e_Else);\n observer.onPPEndif += report(analyser, observer.e_Endif);\n}\n\n}\n\n\/\/ ----------------------------------------------------------------------------\n\nstatic RegisterCheck c1(check_name, &subscribe);\n\n\/\/ ----------------------------------------------------------------------------\n\/\/ Copyright (C) 2014 Bloomberg Finance L.P.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/ ----------------------------- END-OF-FILE ----------------------------------\n<|endoftext|>"} {"text":"\/\/---------------------------------------------------------------------------\n\/\/ $Id$\n\/\/ Version: $Name$\n\/\/\n\/\/ Copyright (C) 2001, 2002, 2003, 2004, 2005, 2006 by the deal.II authors\n\/\/\n\/\/ This file is subject to QPL and may not be distributed\n\/\/ without copyright and license information. Please refer\n\/\/ to the file deal.II\/doc\/license.html for the text and\n\/\/ further information on this license.\n\/\/\n\/\/---------------------------------------------------------------------------\n\n\n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n\nDEAL_II_NAMESPACE_OPEN\n\n\n\ntemplate \nvoid\nCompressedSimpleSparsityPattern::Line::add_entries (ForwardIterator begin,\n\t\t\t\t\t\t ForwardIterator end,\n\t\t\t\t\t\t const bool indices_are_sorted)\n{\n const int n_elements = end - begin;\n if (n_elements <= 0)\n return;\n\n const unsigned int stop_size = entries.size() + n_elements;\n\n if (indices_are_sorted == true && n_elements > 3)\n {\n\t\t\t\t \/\/ in debug mode, check whether the\n\t\t\t\t \/\/ indices really are sorted.\n#ifdef DEBUG\n {\n\tForwardIterator test = begin, test1 = begin;\n\t++test1;\n\tfor ( ; test1 != end; ++test, ++test1)\n\t {\n\t if (*test1 <= *test)\n\t std::cout << end-begin << \" \" << test1-begin << \" \" << *test1 << \" \" << *test << \" \" << std::flush;\n\t Assert (*test1 > *test, ExcInternalError());\n\t }\n }\n#endif\n\n if (entries.size() == 0 || entries.back() < *begin)\n\t{\n\t entries.insert(entries.end(), begin, end);\n\t return;\n\t}\n\n\t\t\t\t \/\/ find a possible insertion point for\n\t\t\t\t \/\/ the first entry. check whether the\n\t\t\t\t \/\/ first entry is a duplicate before\n\t\t\t\t \/\/ actually doing something.\n ForwardIterator my_it = begin;\n unsigned int col = *my_it;\n std::vector::iterator it = \n\tstd::lower_bound(entries.begin(), entries.end(), col);\n while (*it == col) \n\t{\n\t ++my_it;\n\t if (my_it == end)\n\t break;\n\t col = *my_it;\n\t\t\t\t \/\/ check the very next entry in the\n\t\t\t\t \/\/ current array\n\t ++it;\n\t if (it == entries.end())\n\t break;\n\t if (*it > col)\n\t break;\n\t if (*it == col)\n\t continue;\n\t\t\t\t \/\/ ok, it wasn't the very next one, do a\n\t\t\t\t \/\/ binary search to find the insert point\n\t it = std::lower_bound(it, entries.end(), col);\n\t if (it == entries.end())\n\t break;\n\t}\n\t\t\t\t \/\/ all input entries were duplicates.\n if (my_it == end)\n\treturn;\n\n\t\t\t\t \/\/ resize vector by just inserting the\n\t\t\t\t \/\/ list\n const unsigned int pos1 = it - entries.begin();\n Assert (pos1 <= entries.size(), ExcInternalError());\n entries.insert (it, my_it, end);\n it = entries.begin() + pos1;\n Assert (entries.size() >= (unsigned int)(it-entries.begin()), ExcInternalError());\n\n\t\t\t\t \/\/ now merge the two lists.\n std::vector::iterator it2 = it + (end-my_it);\n\n\t\t\t\t \/\/ as long as there are indices both in\n\t\t\t\t \/\/ the end of the entries list and in the\n\t\t\t\t \/\/ input list\n while (my_it != end && it2 != entries.end())\n\t{\n\t if (*my_it < *it2)\n\t *it++ = *my_it++;\n\t else if (*my_it == *it2)\n\t {\n\t *it++ = *it2++;\n\t ++my_it;\n\t }\n\t else\n\t *it++ = *it2++;\n\t}\n\t\t\t\t \/\/ in case there are indices left in the\n\t\t\t\t \/\/ input list\n while (my_it != end)\n\t*it++ = *my_it++;\n\n\t\t\t\t \/\/ in case there are indices left in the\n\t\t\t\t \/\/ end of entries\n while (it2 != entries.end())\n\t*it++ = *it2++;\n\n\t\t\t\t \/\/ resize and return\n const unsigned int new_size = it - entries.begin();\n Assert (new_size <= stop_size, ExcInternalError());\n entries.resize (new_size);\n return;\n }\n\n\t\t\t\t \/\/ unsorted case or case with too few\n\t\t\t\t \/\/ elements\n ForwardIterator my_it = begin;\n\n\t\t\t\t \/\/ If necessary, increase the size of the\n\t\t\t\t \/\/ array.\n if (stop_size > entries.capacity())\n entries.reserve (stop_size);\n\n unsigned int col = *my_it;\n std::vector::iterator it, it2;\n\t\t\t\t \/\/ insert the first element as for one\n\t\t\t\t \/\/ entry only first check the last\n\t\t\t\t \/\/ element (or if line is still empty)\n if ( (entries.size()==0) || ( entries.back() < col) ) {\n entries.push_back(col);\n it = entries.end()-1;\n }\n else { \n\t\t\t\t \/\/ do a binary search to find the place\n\t\t\t\t \/\/ where to insert:\n it2 = std::lower_bound(entries.begin(), entries.end(), col); \n\n\t\t\t\t \/\/ If this entry is a duplicate, continue\n\t\t\t\t \/\/ immediately Insert at the right place\n\t\t\t\t \/\/ in the vector. Vector grows\n\t\t\t\t \/\/ automatically to fit elements. Always\n\t\t\t\t \/\/ doubles its size.\n if (*it2 != col)\n it = entries.insert(it2, col);\n else\n it = it2;\n }\n\n ++my_it;\n\t\t\t\t \/\/ Now try to be smart and insert with\n\t\t\t\t \/\/ bias in the direction we are\n\t\t\t\t \/\/ walking. This has the advantage that\n\t\t\t\t \/\/ for sorted lists, we always search in\n\t\t\t\t \/\/ the right direction, what should\n\t\t\t\t \/\/ decrease the work needed in here.\n for ( ; my_it != end; ++my_it)\n {\n col = *my_it;\n\t\t\t\t \/\/ need a special insertion command when\n\t\t\t\t \/\/ we're at the end of the list\n if (col > entries.back()) {\n\tentries.push_back(col);\n\tit = entries.end()-1;\n }\n\t\t\t\t \/\/ search to the right (preferred search\n\t\t\t\t \/\/ direction)\n else if (col > *it) {\n \tit2 = std::lower_bound(it++, entries.end(), col);\n\tif (*it2 != col)\n\t it = entries.insert(it2, col);\n }\n\t\t\t\t \/\/ search to the left\n else if (col < *it) {\n\tit2 = std::lower_bound(entries.begin(), it, col);\n\tif (*it2 != col)\n\t it = entries.insert(it2, col);\n }\n\t\t\t\t \/\/ if we're neither larger nor smaller,\n\t\t\t\t \/\/ then this was a duplicate and we can\n\t\t\t\t \/\/ just continue.\n }\n}\n\n\n\nCompressedSimpleSparsityPattern::CompressedSimpleSparsityPattern ()\n :\n\t\trows(0),\n\t\tcols(0)\n{}\n\n\n\nCompressedSimpleSparsityPattern::\nCompressedSimpleSparsityPattern (const CompressedSimpleSparsityPattern &s)\n :\n\t\tSubscriptor(),\n\t\trows(0),\n\t\tcols(0)\n{\n Assert (s.rows == 0, ExcInvalidConstructorCall());\n Assert (s.cols == 0, ExcInvalidConstructorCall());\n}\n\n\n\nCompressedSimpleSparsityPattern::CompressedSimpleSparsityPattern (const unsigned int m,\n\t\t\t\t\t\t const unsigned int n) \n\t\t:\n rows(0),\n cols(0)\n{\n reinit (m,n);\n}\n\n\n\nCompressedSimpleSparsityPattern::CompressedSimpleSparsityPattern (const unsigned int n)\n\t\t:\n rows(0),\n cols(0)\n{\n reinit (n,n);\n}\n\n\n\nCompressedSimpleSparsityPattern &\nCompressedSimpleSparsityPattern::operator = (const CompressedSimpleSparsityPattern &s)\n{\n Assert (s.rows == 0, ExcInvalidConstructorCall());\n Assert (s.cols == 0, ExcInvalidConstructorCall());\n\n Assert (rows == 0, ExcInvalidConstructorCall());\n Assert (cols == 0, ExcInvalidConstructorCall());\n\n return *this;\n}\n\n\n\nvoid\nCompressedSimpleSparsityPattern::reinit (const unsigned int m,\n\t\t\t\t const unsigned int n)\n{\n rows = m;\n cols = n;\n\n std::vector new_lines (rows);\n lines.swap (new_lines);\n}\n\n\n\nvoid\nCompressedSimpleSparsityPattern::compress ()\n{}\n\n\n\nbool\nCompressedSimpleSparsityPattern::empty () const\n{\n return ((rows==0) && (cols==0));\n}\n\n\n\nunsigned int\nCompressedSimpleSparsityPattern::max_entries_per_row () const\n{\n unsigned int m = 0;\n for (unsigned int i=0; i(lines[i].entries.size()));\n }\n \n return m;\n}\n\n\n\nbool \nCompressedSimpleSparsityPattern::exists (const unsigned int i,\n\t\t\t\t const unsigned int j) const\n{\n Assert (i::const_iterator\n j=lines[row].entries.begin();\n j != lines[row].entries.end();\n ++j)\n\t\t\t\t \/\/ add the transpose entry if\n\t\t\t\t \/\/ this is not the diagonal\n if (row != *j)\n add (*j, row);\n }\n}\n\n\n\nvoid\nCompressedSimpleSparsityPattern::print (std::ostream &out) const\n{\n for (unsigned int row=0; row::const_iterator\n j=lines[row].entries.begin();\n j != lines[row].entries.end(); ++j)\n out << ',' << *j;\n\n out << ']' << std::endl;\n }\n\n AssertThrow (out, ExcIO());\n}\n\n\n\nvoid\nCompressedSimpleSparsityPattern::print_gnuplot (std::ostream &out) const\n{ \n for (unsigned int row=0; row::const_iterator\n j=lines[row].entries.begin();\n j != lines[row].entries.end(); ++j)\n \/\/ while matrix entries are usually\n \/\/ written (i,j), with i vertical and\n \/\/ j horizontal, gnuplot output is\n \/\/ x-y, that is we have to exchange\n \/\/ the order of output\n out << *j << \" \" << -static_cast(row) << std::endl;\n }\n \n\n AssertThrow (out, ExcIO());\n}\n\n\n\nunsigned int\nCompressedSimpleSparsityPattern::bandwidth () const\n{\n unsigned int b=0;\n for (unsigned int row=0; row::const_iterator\n j=lines[row].entries.begin();\n j != lines[row].entries.end(); ++j)\n if (static_cast(std::abs(static_cast(row-*j))) > b)\n b = std::abs(static_cast(row-*j));\n }\n \n return b;\n}\n\n\n\nunsigned int\nCompressedSimpleSparsityPattern::n_nonzero_elements () const\n{\n unsigned int n=0;\n for (unsigned int i=0; i::iterator,\n\t std::vector::iterator,\n\t const bool);\n\n\nDEAL_II_NAMESPACE_CLOSE\nI committed some nonsense.\/\/---------------------------------------------------------------------------\n\/\/ $Id$\n\/\/ Version: $Name$\n\/\/\n\/\/ Copyright (C) 2001, 2002, 2003, 2004, 2005, 2006 by the deal.II authors\n\/\/\n\/\/ This file is subject to QPL and may not be distributed\n\/\/ without copyright and license information. Please refer\n\/\/ to the file deal.II\/doc\/license.html for the text and\n\/\/ further information on this license.\n\/\/\n\/\/---------------------------------------------------------------------------\n\n\n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n\nDEAL_II_NAMESPACE_OPEN\n\n\n\ntemplate \nvoid\nCompressedSimpleSparsityPattern::Line::add_entries (ForwardIterator begin,\n\t\t\t\t\t\t ForwardIterator end,\n\t\t\t\t\t\t const bool indices_are_sorted)\n{\n const int n_elements = end - begin;\n if (n_elements <= 0)\n return;\n\n const unsigned int stop_size = entries.size() + n_elements;\n\n if (indices_are_sorted == true && n_elements > 3)\n {\n\t\t\t\t \/\/ in debug mode, check whether the\n\t\t\t\t \/\/ indices really are sorted.\n#ifdef DEBUG\n {\n\tForwardIterator test = begin, test1 = begin;\n\t++test1;\n\tfor ( ; test1 != end; ++test, ++test1)\n\t Assert (*test1 > *test, ExcInternalError());\n }\n#endif\n\n if (entries.size() == 0 || entries.back() < *begin)\n\t{\n\t entries.insert(entries.end(), begin, end);\n\t return;\n\t}\n\n\t\t\t\t \/\/ find a possible insertion point for\n\t\t\t\t \/\/ the first entry. check whether the\n\t\t\t\t \/\/ first entry is a duplicate before\n\t\t\t\t \/\/ actually doing something.\n ForwardIterator my_it = begin;\n unsigned int col = *my_it;\n std::vector::iterator it = \n\tstd::lower_bound(entries.begin(), entries.end(), col);\n while (*it == col) \n\t{\n\t ++my_it;\n\t if (my_it == end)\n\t break;\n\t col = *my_it;\n\t\t\t\t \/\/ check the very next entry in the\n\t\t\t\t \/\/ current array\n\t ++it;\n\t if (it == entries.end())\n\t break;\n\t if (*it > col)\n\t break;\n\t if (*it == col)\n\t continue;\n\t\t\t\t \/\/ ok, it wasn't the very next one, do a\n\t\t\t\t \/\/ binary search to find the insert point\n\t it = std::lower_bound(it, entries.end(), col);\n\t if (it == entries.end())\n\t break;\n\t}\n\t\t\t\t \/\/ all input entries were duplicates.\n if (my_it == end)\n\treturn;\n\n\t\t\t\t \/\/ resize vector by just inserting the\n\t\t\t\t \/\/ list\n const unsigned int pos1 = it - entries.begin();\n Assert (pos1 <= entries.size(), ExcInternalError());\n entries.insert (it, my_it, end);\n it = entries.begin() + pos1;\n Assert (entries.size() >= (unsigned int)(it-entries.begin()), ExcInternalError());\n\n\t\t\t\t \/\/ now merge the two lists.\n std::vector::iterator it2 = it + (end-my_it);\n\n\t\t\t\t \/\/ as long as there are indices both in\n\t\t\t\t \/\/ the end of the entries list and in the\n\t\t\t\t \/\/ input list\n while (my_it != end && it2 != entries.end())\n\t{\n\t if (*my_it < *it2)\n\t *it++ = *my_it++;\n\t else if (*my_it == *it2)\n\t {\n\t *it++ = *it2++;\n\t ++my_it;\n\t }\n\t else\n\t *it++ = *it2++;\n\t}\n\t\t\t\t \/\/ in case there are indices left in the\n\t\t\t\t \/\/ input list\n while (my_it != end)\n\t*it++ = *my_it++;\n\n\t\t\t\t \/\/ in case there are indices left in the\n\t\t\t\t \/\/ end of entries\n while (it2 != entries.end())\n\t*it++ = *it2++;\n\n\t\t\t\t \/\/ resize and return\n const unsigned int new_size = it - entries.begin();\n Assert (new_size <= stop_size, ExcInternalError());\n entries.resize (new_size);\n return;\n }\n\n\t\t\t\t \/\/ unsorted case or case with too few\n\t\t\t\t \/\/ elements\n ForwardIterator my_it = begin;\n\n\t\t\t\t \/\/ If necessary, increase the size of the\n\t\t\t\t \/\/ array.\n if (stop_size > entries.capacity())\n entries.reserve (stop_size);\n\n unsigned int col = *my_it;\n std::vector::iterator it, it2;\n\t\t\t\t \/\/ insert the first element as for one\n\t\t\t\t \/\/ entry only first check the last\n\t\t\t\t \/\/ element (or if line is still empty)\n if ( (entries.size()==0) || ( entries.back() < col) ) {\n entries.push_back(col);\n it = entries.end()-1;\n }\n else { \n\t\t\t\t \/\/ do a binary search to find the place\n\t\t\t\t \/\/ where to insert:\n it2 = std::lower_bound(entries.begin(), entries.end(), col); \n\n\t\t\t\t \/\/ If this entry is a duplicate, continue\n\t\t\t\t \/\/ immediately Insert at the right place\n\t\t\t\t \/\/ in the vector. Vector grows\n\t\t\t\t \/\/ automatically to fit elements. Always\n\t\t\t\t \/\/ doubles its size.\n if (*it2 != col)\n it = entries.insert(it2, col);\n else\n it = it2;\n }\n\n ++my_it;\n\t\t\t\t \/\/ Now try to be smart and insert with\n\t\t\t\t \/\/ bias in the direction we are\n\t\t\t\t \/\/ walking. This has the advantage that\n\t\t\t\t \/\/ for sorted lists, we always search in\n\t\t\t\t \/\/ the right direction, what should\n\t\t\t\t \/\/ decrease the work needed in here.\n for ( ; my_it != end; ++my_it)\n {\n col = *my_it;\n\t\t\t\t \/\/ need a special insertion command when\n\t\t\t\t \/\/ we're at the end of the list\n if (col > entries.back()) {\n\tentries.push_back(col);\n\tit = entries.end()-1;\n }\n\t\t\t\t \/\/ search to the right (preferred search\n\t\t\t\t \/\/ direction)\n else if (col > *it) {\n \tit2 = std::lower_bound(it++, entries.end(), col);\n\tif (*it2 != col)\n\t it = entries.insert(it2, col);\n }\n\t\t\t\t \/\/ search to the left\n else if (col < *it) {\n\tit2 = std::lower_bound(entries.begin(), it, col);\n\tif (*it2 != col)\n\t it = entries.insert(it2, col);\n }\n\t\t\t\t \/\/ if we're neither larger nor smaller,\n\t\t\t\t \/\/ then this was a duplicate and we can\n\t\t\t\t \/\/ just continue.\n }\n}\n\n\n\nCompressedSimpleSparsityPattern::CompressedSimpleSparsityPattern ()\n :\n\t\trows(0),\n\t\tcols(0)\n{}\n\n\n\nCompressedSimpleSparsityPattern::\nCompressedSimpleSparsityPattern (const CompressedSimpleSparsityPattern &s)\n :\n\t\tSubscriptor(),\n\t\trows(0),\n\t\tcols(0)\n{\n Assert (s.rows == 0, ExcInvalidConstructorCall());\n Assert (s.cols == 0, ExcInvalidConstructorCall());\n}\n\n\n\nCompressedSimpleSparsityPattern::CompressedSimpleSparsityPattern (const unsigned int m,\n\t\t\t\t\t\t const unsigned int n) \n\t\t:\n rows(0),\n cols(0)\n{\n reinit (m,n);\n}\n\n\n\nCompressedSimpleSparsityPattern::CompressedSimpleSparsityPattern (const unsigned int n)\n\t\t:\n rows(0),\n cols(0)\n{\n reinit (n,n);\n}\n\n\n\nCompressedSimpleSparsityPattern &\nCompressedSimpleSparsityPattern::operator = (const CompressedSimpleSparsityPattern &s)\n{\n Assert (s.rows == 0, ExcInvalidConstructorCall());\n Assert (s.cols == 0, ExcInvalidConstructorCall());\n\n Assert (rows == 0, ExcInvalidConstructorCall());\n Assert (cols == 0, ExcInvalidConstructorCall());\n\n return *this;\n}\n\n\n\nvoid\nCompressedSimpleSparsityPattern::reinit (const unsigned int m,\n\t\t\t\t const unsigned int n)\n{\n rows = m;\n cols = n;\n\n std::vector new_lines (rows);\n lines.swap (new_lines);\n}\n\n\n\nvoid\nCompressedSimpleSparsityPattern::compress ()\n{}\n\n\n\nbool\nCompressedSimpleSparsityPattern::empty () const\n{\n return ((rows==0) && (cols==0));\n}\n\n\n\nunsigned int\nCompressedSimpleSparsityPattern::max_entries_per_row () const\n{\n unsigned int m = 0;\n for (unsigned int i=0; i(lines[i].entries.size()));\n }\n \n return m;\n}\n\n\n\nbool \nCompressedSimpleSparsityPattern::exists (const unsigned int i,\n\t\t\t\t const unsigned int j) const\n{\n Assert (i::const_iterator\n j=lines[row].entries.begin();\n j != lines[row].entries.end();\n ++j)\n\t\t\t\t \/\/ add the transpose entry if\n\t\t\t\t \/\/ this is not the diagonal\n if (row != *j)\n add (*j, row);\n }\n}\n\n\n\nvoid\nCompressedSimpleSparsityPattern::print (std::ostream &out) const\n{\n for (unsigned int row=0; row::const_iterator\n j=lines[row].entries.begin();\n j != lines[row].entries.end(); ++j)\n out << ',' << *j;\n\n out << ']' << std::endl;\n }\n\n AssertThrow (out, ExcIO());\n}\n\n\n\nvoid\nCompressedSimpleSparsityPattern::print_gnuplot (std::ostream &out) const\n{ \n for (unsigned int row=0; row::const_iterator\n j=lines[row].entries.begin();\n j != lines[row].entries.end(); ++j)\n \/\/ while matrix entries are usually\n \/\/ written (i,j), with i vertical and\n \/\/ j horizontal, gnuplot output is\n \/\/ x-y, that is we have to exchange\n \/\/ the order of output\n out << *j << \" \" << -static_cast(row) << std::endl;\n }\n \n\n AssertThrow (out, ExcIO());\n}\n\n\n\nunsigned int\nCompressedSimpleSparsityPattern::bandwidth () const\n{\n unsigned int b=0;\n for (unsigned int row=0; row::const_iterator\n j=lines[row].entries.begin();\n j != lines[row].entries.end(); ++j)\n if (static_cast(std::abs(static_cast(row-*j))) > b)\n b = std::abs(static_cast(row-*j));\n }\n \n return b;\n}\n\n\n\nunsigned int\nCompressedSimpleSparsityPattern::n_nonzero_elements () const\n{\n unsigned int n=0;\n for (unsigned int i=0; i::iterator,\n\t std::vector::iterator,\n\t const bool);\n\n\nDEAL_II_NAMESPACE_CLOSE\n<|endoftext|>"} {"text":"\/**\n * computeDifferenceImage\n *\n * This program computes the difference between images.\n *\n *\n * authors: Marius Staring\n *\n *\/\n\n#include \n#include \"itkImageFileReader.h\"\n\n\/** In order to determine if argv[1] is a directory or a file,\n * so that we can distinguish between dicom and other files.\n *\/\n#include \n\n\/\/ extern int ComputeScalarDifferenceImage( const std::string &inputPixelComponentType1,\n\/\/ const std::string &inputPixelComponentType2, const std::string &outputPixelComponentType,\n\/\/ const std::string &image1FileName, const std::string &image2FileName,\n\/\/ const std::string &outputFileName, int inputDimension);\n\nextern int ComputeVectorDifferenceImage( const std::string &inputPixelComponentType1,\n const std::string &inputPixelComponentType2, const std::string &outputPixelComponentType,\n const std::string &image1FileName, const std::string &image2FileName,\n const std::string &outputFileName, int inputDimension, int vectorDimension);\n\n\/\/-------------------------------------------------------------------------------------\n\nint main( int argc, char *argv[] )\n{\n \/** TASK 1:\n * Check arguments.\n * *******************************************************************\n *\/\n if ( argc < 3 || argv[ 1 ] == \"--help\" )\n {\n std::cout << \"Usage:\" << std::endl;\n std::cout << \"\\tpxcomputedifferenceimage inputimage1filename inputimage2filename [outputimagefilename] [outputPixelComponentType]\" << std::endl;\n std::cout << \"\\twhere outputPixelComponentType is one of:\" << std::endl;\n std::cout << \"\\t\\t- unsigned_char\" << std::endl;\n std::cout << \"\\t\\t- char\" << std::endl;\n std::cout << \"\\t\\t- unsigned_short\" << std::endl;\n std::cout << \"\\t\\t- short\" << std::endl;\n std::cout << \"\\t\\t- unsigned_int\" << std::endl;\n std::cout << \"\\t\\t- int\" << std::endl;\n std::cout << \"\\t\\t- unsigned_long\" << std::endl;\n std::cout << \"\\t\\t- long\" << std::endl;\n std::cout << \"\\t\\t- float\" << std::endl;\n std::cout << \"\\t\\t- double\" << std::endl;\n std::cout << \"\\tprovided that the outputPixelComponentType is supported by the output file format.\" << std::endl;\n std::cout << \"\\tBy default the outputPixelComponentType is set to the inputPixelComponentType of image1.\" << std::endl;\n return 1;\n }\n\n \/** Print arguments. *\/\n std::cout << \"pxcomputedifferenceimage \";\n for ( unsigned int i = 1; i < argc; i++ )\n {\n std::cout << argv[ i ] << \" \";\n }\n std::cout << std::endl;\n\n \/** Get the image names. *\/\n std::string image1FileName = argv[ 1 ];\n std::string image2FileName = argv[ 2 ];\n std::string outputFileName = \"\";\n std::string outputPixelComponentType = \"\";\n if ( argc == 3 )\n {\n std::string::size_type slash = image2FileName.find_last_of( \"\/\" ) + 1;\n outputFileName = image1FileName.substr( 0, image1FileName.rfind( \".\" ) );\n outputFileName += \"MINUS\";\n outputFileName += image2FileName.substr( slash, image2FileName.rfind( \".\" ) - slash );\n outputFileName += \".mhd\";\n }\n else if ( argc == 4 )\n {\n outputFileName = argv[ 3 ];\n }\n else if ( argc == 5 )\n {\n outputFileName = argv[ 3 ];\n outputPixelComponentType = argv[ 4 ];\n }\n\n \/** Check if image1FileName and image2FileName exist. *\/\n bool exists1 = itksys::SystemTools::FileExists( image1FileName.c_str() );\n bool exists2 = itksys::SystemTools::FileExists( image2FileName.c_str() );\n\n if ( !exists1 || !exists2 )\n {\n \/** Something is wrong. *\/\n std::cerr << \"ERROR: first input argument does not exist!\" << std::endl;\n return 1;\n }\n\n \/** Check outputPixelType. *\/\n if ( outputPixelComponentType != \"\"\n && outputPixelComponentType != \"unsigned_char\"\n && outputPixelComponentType != \"char\"\n && outputPixelComponentType != \"unsigned_short\"\n && outputPixelComponentType != \"short\"\n && outputPixelComponentType != \"unsigned_int\"\n && outputPixelComponentType != \"int\"\n && outputPixelComponentType != \"unsigned_long\"\n && outputPixelComponentType != \"long\"\n && outputPixelComponentType != \"float\"\n && outputPixelComponentType != \"double\" )\n {\n \/** In this case an illegal outputPixelComponentType is given. *\/\n std::cerr << \"The given outputPixelComponentType is \\\"\" << outputPixelComponentType\n << \"\\\", which is not supported.\" << std::endl;\n return 1;\n }\n\n \/** TASK 2:\n * Typedefs and test reading to determine correct image types.\n * *******************************************************************\n *\/\n\n \/** Initial image type. *\/\n const unsigned int Dimension = 3;\n typedef short PixelType;\n\n \/** Some typedef's. *\/\n typedef itk::Image< PixelType, Dimension > ImageType;\n typedef itk::ImageFileReader< ImageType > ReaderType;\n typedef itk::ImageIOBase ImageIOBaseType;\n\n \/** Create testReaders. *\/\n ReaderType::Pointer testReader1 = ReaderType::New();\n ReaderType::Pointer testReader2 = ReaderType::New();\n\n \/** Setup the testReaders. *\/\n testReader1->SetFileName( image1FileName.c_str() );\n testReader2->SetFileName( image2FileName.c_str() );\n\n \/** Generate all information. *\/\n testReader1->GenerateOutputInformation();\n testReader2->GenerateOutputInformation();\n\n \/** Extract the ImageIO from the testReaders. *\/\n ImageIOBaseType::Pointer testImageIOBase1 = testReader1->GetImageIO();\n ImageIOBaseType::Pointer testImageIOBase2 = testReader2->GetImageIO();\n\n \/** Get the component type, number of components, dimension and pixel type of image1. *\/\n unsigned int inputDimension1 = testImageIOBase1->GetNumberOfDimensions();\n unsigned int numberOfComponents1 = testImageIOBase1->GetNumberOfComponents();\n std::string inputPixelComponentType1 = testImageIOBase1->GetComponentTypeAsString(\n testImageIOBase1->GetComponentType() );\n std::string pixelType1 = testImageIOBase1->GetPixelTypeAsString(\n testImageIOBase1->GetPixelType() );\n\n \/** Get the component type, number of components, dimension and pixel type of image2. *\/\n unsigned int inputDimension2 = testImageIOBase2->GetNumberOfDimensions();\n unsigned int numberOfComponents2 = testImageIOBase2->GetNumberOfComponents();\n std::string inputPixelComponentType2 = testImageIOBase2->GetComponentTypeAsString(\n testImageIOBase2->GetComponentType() );\n std::string pixelType2 = testImageIOBase2->GetPixelTypeAsString(\n testImageIOBase2->GetPixelType() );\n\n \/** TASK 3:\n * Do some preparations and checks.\n * *******************************************************************\n *\/\n\n \/** Check dimension equality. *\/\n if ( inputDimension1 != inputDimension2 )\n {\n std::cerr << \"The dimensions of the input images are \"\n << inputDimension1 << \" and \"\n << inputDimension2 << \".\" << std::endl;\n std::cerr << \"They should match!\" << std::endl;\n return 1;\n }\n\n \/** Check equality of the pixel type. *\/\n if ( pixelType1 != pixelType2 )\n {\n std::cerr << \"The pixel type of the input images are \"\n << pixelType1 << \" and \"\n << pixelType2 << \".\" << std::endl;\n std::cerr << \"They should match!\" << std::endl;\n return 1;\n }\n\n \/** Check equality of the number of components. *\/\n if ( numberOfComponents1 != numberOfComponents2 )\n {\n std::cerr << \"The number of components of the input images are \"\n << numberOfComponents1 << \" and \"\n << numberOfComponents2 << \".\" << std::endl;\n std::cerr << \"They should match!\" << std::endl;\n return 1;\n }\n\n \/** Check inputPixelComponentType1. *\/\n if ( inputPixelComponentType1 != \"unsigned_char\"\n && inputPixelComponentType1 != \"char\"\n && inputPixelComponentType1 != \"unsigned_short\"\n && inputPixelComponentType1 != \"short\"\n && inputPixelComponentType1 != \"unsigned_int\"\n && inputPixelComponentType1 != \"int\"\n && inputPixelComponentType1 != \"unsigned_long\"\n && inputPixelComponentType1 != \"long\"\n && inputPixelComponentType1 != \"float\"\n && inputPixelComponentType1 != \"double\" )\n {\n \/** In this case an illegal inputPixelComponentType is found. *\/\n std::cerr << \"The found inputPixelComponentType of image1 is \\\"\" << inputPixelComponentType1\n << \"\\\", which is not supported.\" << std::endl;\n return 1;\n }\n\n \/** Check inputPixelType2. *\/\n if ( inputPixelComponentType2 != \"unsigned_char\"\n && inputPixelComponentType2 != \"char\"\n && inputPixelComponentType2 != \"unsigned_short\"\n && inputPixelComponentType2 != \"short\"\n && inputPixelComponentType2 != \"unsigned_int\"\n && inputPixelComponentType2 != \"int\"\n && inputPixelComponentType2 != \"unsigned_long\"\n && inputPixelComponentType2 != \"long\"\n && inputPixelComponentType2 != \"float\"\n && inputPixelComponentType2 != \"double\" )\n {\n \/** In this case an illegal inputPixelComponentType is found. *\/\n std::cerr << \"The found inputPixelComponentType of image2 is \\\"\" << inputPixelComponentType2\n << \"\\\", which is not supported.\" << std::endl;\n return 1;\n }\n\n \/** Check outputPixelType. *\/\n if ( outputPixelComponentType == \"\" )\n {\n \/** In this case this option is not given, and by default\n * we set it to the inputPixelComponentType.\n *\/\n outputPixelComponentType = inputPixelComponentType1;\n }\n\n \/** Get rid of the \"_\" in inputPixelComponentTypes and outputPixelComponentType. *\/\n std::basic_string::size_type pos = inputPixelComponentType1.find( \"_\" );\n static const std::basic_string::size_type npos = std::basic_string::npos;\n if ( pos != npos )\n {\n inputPixelComponentType1.replace( pos, 1, \" \" );\n }\n pos = inputPixelComponentType2.find( \"_\" );\n if ( pos != npos )\n {\n inputPixelComponentType2.replace( pos, 1, \" \" );\n }\n pos = outputPixelComponentType.find( \"_\" );\n if ( pos != npos )\n {\n outputPixelComponentType.replace( pos, 1, \" \" );\n }\n\n \/** TASK 4:\n * Now we are ready to check on image type and subsequently call the\n * correct ComputeDifference-function.\n * *******************************************************************\n *\/\n\n try\n {\n \/**\n * ****************** Support for SCALAR pixel types. **********************************\n *\n if ( strcmp( pixelType1.c_str(), \"scalar\" ) == 0 && numberOfComponents1 == 1 )\n {\n const int ret_value = ComputeScalarDifferenceImage(\n inputPixelComponentType1, inputPixelComponentType2,\n outputPixelComponentType, image1FileName, image2FileName,\n outputFileName, inputDimension1 );\n if ( ret_value != 0 )\n {\n return ret_value;\n }\n } \/\/ end scalar support *\/\n \/**\n * ****************** Support for VECTOR pixel types. **********************************\n *\/\n \/\/else if ( strcmp( pixelType1.c_str(), \"vector\" ) == 0 )\n if ( numberOfComponents1 > 1 )\n {\n const int ret_value = ComputeVectorDifferenceImage(\n inputPixelComponentType1, inputPixelComponentType2,\n outputPixelComponentType, image1FileName, image2FileName,\n outputFileName, inputDimension1, numberOfComponents1 );\n if ( ret_value != 0 )\n {\n return ret_value;\n }\n } \/\/ end vector support\n else\n {\n std::cerr << \"Pixel types are \" << pixelType1\n << \", component types are \" << inputPixelComponentType1\n << \" and number of components equals \" << numberOfComponents1 << \".\" << std::endl;\n std::cerr << \"ERROR: This image type is not supported.\" << std::endl;\n return 1;\n }\n } \/\/ end try\n\n \/** If any errors have occurred, catch and print the exception and return false. *\/\n catch( itk::ExceptionObject & err )\n {\n std::cerr << \"ExceptionObject caught !\" << std::endl;\n std::cerr << err << std::endl;\n return 1;\n }\n\n \/** End program. Return success. *\/\n return 0;\n\n} \/\/ end main\nFix comparison with string literal results in unspecified behavior warning\/**\n * computeDifferenceImage\n *\n * This program computes the difference between images.\n *\n *\n * authors: Marius Staring\n *\n *\/\n\n#include \n#include \"itkImageFileReader.h\"\n\n\/** In order to determine if argv[1] is a directory or a file,\n * so that we can distinguish between dicom and other files.\n *\/\n#include \n\n\/\/ extern int ComputeScalarDifferenceImage( const std::string &inputPixelComponentType1,\n\/\/ const std::string &inputPixelComponentType2, const std::string &outputPixelComponentType,\n\/\/ const std::string &image1FileName, const std::string &image2FileName,\n\/\/ const std::string &outputFileName, int inputDimension);\n\nextern int ComputeVectorDifferenceImage( const std::string &inputPixelComponentType1,\n const std::string &inputPixelComponentType2, const std::string &outputPixelComponentType,\n const std::string &image1FileName, const std::string &image2FileName,\n const std::string &outputFileName, int inputDimension, int vectorDimension);\n\n\/\/-------------------------------------------------------------------------------------\n\nint main( int argc, char *argv[] )\n{\n \/** TASK 1:\n * Check arguments.\n * *******************************************************************\n *\/\n if ( argc < 3 || strcmp(argv[ 1 ], \"--help\") == 0 )\n {\n std::cout << \"Usage:\" << std::endl;\n std::cout << \"\\tpxcomputedifferenceimage inputimage1filename inputimage2filename [outputimagefilename] [outputPixelComponentType]\" << std::endl;\n std::cout << \"\\twhere outputPixelComponentType is one of:\" << std::endl;\n std::cout << \"\\t\\t- unsigned_char\" << std::endl;\n std::cout << \"\\t\\t- char\" << std::endl;\n std::cout << \"\\t\\t- unsigned_short\" << std::endl;\n std::cout << \"\\t\\t- short\" << std::endl;\n std::cout << \"\\t\\t- unsigned_int\" << std::endl;\n std::cout << \"\\t\\t- int\" << std::endl;\n std::cout << \"\\t\\t- unsigned_long\" << std::endl;\n std::cout << \"\\t\\t- long\" << std::endl;\n std::cout << \"\\t\\t- float\" << std::endl;\n std::cout << \"\\t\\t- double\" << std::endl;\n std::cout << \"\\tprovided that the outputPixelComponentType is supported by the output file format.\" << std::endl;\n std::cout << \"\\tBy default the outputPixelComponentType is set to the inputPixelComponentType of image1.\" << std::endl;\n return 1;\n }\n\n \/** Print arguments. *\/\n std::cout << \"pxcomputedifferenceimage \";\n for ( unsigned int i = 1; i < argc; i++ )\n {\n std::cout << argv[ i ] << \" \";\n }\n std::cout << std::endl;\n\n \/** Get the image names. *\/\n std::string image1FileName = argv[ 1 ];\n std::string image2FileName = argv[ 2 ];\n std::string outputFileName = \"\";\n std::string outputPixelComponentType = \"\";\n if ( argc == 3 )\n {\n std::string::size_type slash = image2FileName.find_last_of( \"\/\" ) + 1;\n outputFileName = image1FileName.substr( 0, image1FileName.rfind( \".\" ) );\n outputFileName += \"MINUS\";\n outputFileName += image2FileName.substr( slash, image2FileName.rfind( \".\" ) - slash );\n outputFileName += \".mhd\";\n }\n else if ( argc == 4 )\n {\n outputFileName = argv[ 3 ];\n }\n else if ( argc == 5 )\n {\n outputFileName = argv[ 3 ];\n outputPixelComponentType = argv[ 4 ];\n }\n\n \/** Check if image1FileName and image2FileName exist. *\/\n bool exists1 = itksys::SystemTools::FileExists( image1FileName.c_str() );\n bool exists2 = itksys::SystemTools::FileExists( image2FileName.c_str() );\n\n if ( !exists1 || !exists2 )\n {\n \/** Something is wrong. *\/\n std::cerr << \"ERROR: first input argument does not exist!\" << std::endl;\n return 1;\n }\n\n \/** Check outputPixelType. *\/\n if ( outputPixelComponentType != \"\"\n && outputPixelComponentType != \"unsigned_char\"\n && outputPixelComponentType != \"char\"\n && outputPixelComponentType != \"unsigned_short\"\n && outputPixelComponentType != \"short\"\n && outputPixelComponentType != \"unsigned_int\"\n && outputPixelComponentType != \"int\"\n && outputPixelComponentType != \"unsigned_long\"\n && outputPixelComponentType != \"long\"\n && outputPixelComponentType != \"float\"\n && outputPixelComponentType != \"double\" )\n {\n \/** In this case an illegal outputPixelComponentType is given. *\/\n std::cerr << \"The given outputPixelComponentType is \\\"\" << outputPixelComponentType\n << \"\\\", which is not supported.\" << std::endl;\n return 1;\n }\n\n \/** TASK 2:\n * Typedefs and test reading to determine correct image types.\n * *******************************************************************\n *\/\n\n \/** Initial image type. *\/\n const unsigned int Dimension = 3;\n typedef short PixelType;\n\n \/** Some typedef's. *\/\n typedef itk::Image< PixelType, Dimension > ImageType;\n typedef itk::ImageFileReader< ImageType > ReaderType;\n typedef itk::ImageIOBase ImageIOBaseType;\n\n \/** Create testReaders. *\/\n ReaderType::Pointer testReader1 = ReaderType::New();\n ReaderType::Pointer testReader2 = ReaderType::New();\n\n \/** Setup the testReaders. *\/\n testReader1->SetFileName( image1FileName.c_str() );\n testReader2->SetFileName( image2FileName.c_str() );\n\n \/** Generate all information. *\/\n testReader1->GenerateOutputInformation();\n testReader2->GenerateOutputInformation();\n\n \/** Extract the ImageIO from the testReaders. *\/\n ImageIOBaseType::Pointer testImageIOBase1 = testReader1->GetImageIO();\n ImageIOBaseType::Pointer testImageIOBase2 = testReader2->GetImageIO();\n\n \/** Get the component type, number of components, dimension and pixel type of image1. *\/\n unsigned int inputDimension1 = testImageIOBase1->GetNumberOfDimensions();\n unsigned int numberOfComponents1 = testImageIOBase1->GetNumberOfComponents();\n std::string inputPixelComponentType1 = testImageIOBase1->GetComponentTypeAsString(\n testImageIOBase1->GetComponentType() );\n std::string pixelType1 = testImageIOBase1->GetPixelTypeAsString(\n testImageIOBase1->GetPixelType() );\n\n \/** Get the component type, number of components, dimension and pixel type of image2. *\/\n unsigned int inputDimension2 = testImageIOBase2->GetNumberOfDimensions();\n unsigned int numberOfComponents2 = testImageIOBase2->GetNumberOfComponents();\n std::string inputPixelComponentType2 = testImageIOBase2->GetComponentTypeAsString(\n testImageIOBase2->GetComponentType() );\n std::string pixelType2 = testImageIOBase2->GetPixelTypeAsString(\n testImageIOBase2->GetPixelType() );\n\n \/** TASK 3:\n * Do some preparations and checks.\n * *******************************************************************\n *\/\n\n \/** Check dimension equality. *\/\n if ( inputDimension1 != inputDimension2 )\n {\n std::cerr << \"The dimensions of the input images are \"\n << inputDimension1 << \" and \"\n << inputDimension2 << \".\" << std::endl;\n std::cerr << \"They should match!\" << std::endl;\n return 1;\n }\n\n \/** Check equality of the pixel type. *\/\n if ( pixelType1 != pixelType2 )\n {\n std::cerr << \"The pixel type of the input images are \"\n << pixelType1 << \" and \"\n << pixelType2 << \".\" << std::endl;\n std::cerr << \"They should match!\" << std::endl;\n return 1;\n }\n\n \/** Check equality of the number of components. *\/\n if ( numberOfComponents1 != numberOfComponents2 )\n {\n std::cerr << \"The number of components of the input images are \"\n << numberOfComponents1 << \" and \"\n << numberOfComponents2 << \".\" << std::endl;\n std::cerr << \"They should match!\" << std::endl;\n return 1;\n }\n\n \/** Check inputPixelComponentType1. *\/\n if ( inputPixelComponentType1 != \"unsigned_char\"\n && inputPixelComponentType1 != \"char\"\n && inputPixelComponentType1 != \"unsigned_short\"\n && inputPixelComponentType1 != \"short\"\n && inputPixelComponentType1 != \"unsigned_int\"\n && inputPixelComponentType1 != \"int\"\n && inputPixelComponentType1 != \"unsigned_long\"\n && inputPixelComponentType1 != \"long\"\n && inputPixelComponentType1 != \"float\"\n && inputPixelComponentType1 != \"double\" )\n {\n \/** In this case an illegal inputPixelComponentType is found. *\/\n std::cerr << \"The found inputPixelComponentType of image1 is \\\"\" << inputPixelComponentType1\n << \"\\\", which is not supported.\" << std::endl;\n return 1;\n }\n\n \/** Check inputPixelType2. *\/\n if ( inputPixelComponentType2 != \"unsigned_char\"\n && inputPixelComponentType2 != \"char\"\n && inputPixelComponentType2 != \"unsigned_short\"\n && inputPixelComponentType2 != \"short\"\n && inputPixelComponentType2 != \"unsigned_int\"\n && inputPixelComponentType2 != \"int\"\n && inputPixelComponentType2 != \"unsigned_long\"\n && inputPixelComponentType2 != \"long\"\n && inputPixelComponentType2 != \"float\"\n && inputPixelComponentType2 != \"double\" )\n {\n \/** In this case an illegal inputPixelComponentType is found. *\/\n std::cerr << \"The found inputPixelComponentType of image2 is \\\"\" << inputPixelComponentType2\n << \"\\\", which is not supported.\" << std::endl;\n return 1;\n }\n\n \/** Check outputPixelType. *\/\n if ( outputPixelComponentType == \"\" )\n {\n \/** In this case this option is not given, and by default\n * we set it to the inputPixelComponentType.\n *\/\n outputPixelComponentType = inputPixelComponentType1;\n }\n\n \/** Get rid of the \"_\" in inputPixelComponentTypes and outputPixelComponentType. *\/\n std::basic_string::size_type pos = inputPixelComponentType1.find( \"_\" );\n static const std::basic_string::size_type npos = std::basic_string::npos;\n if ( pos != npos )\n {\n inputPixelComponentType1.replace( pos, 1, \" \" );\n }\n pos = inputPixelComponentType2.find( \"_\" );\n if ( pos != npos )\n {\n inputPixelComponentType2.replace( pos, 1, \" \" );\n }\n pos = outputPixelComponentType.find( \"_\" );\n if ( pos != npos )\n {\n outputPixelComponentType.replace( pos, 1, \" \" );\n }\n\n \/** TASK 4:\n * Now we are ready to check on image type and subsequently call the\n * correct ComputeDifference-function.\n * *******************************************************************\n *\/\n\n try\n {\n \/**\n * ****************** Support for SCALAR pixel types. **********************************\n *\n if ( strcmp( pixelType1.c_str(), \"scalar\" ) == 0 && numberOfComponents1 == 1 )\n {\n const int ret_value = ComputeScalarDifferenceImage(\n inputPixelComponentType1, inputPixelComponentType2,\n outputPixelComponentType, image1FileName, image2FileName,\n outputFileName, inputDimension1 );\n if ( ret_value != 0 )\n {\n return ret_value;\n }\n } \/\/ end scalar support *\/\n \/**\n * ****************** Support for VECTOR pixel types. **********************************\n *\/\n \/\/else if ( strcmp( pixelType1.c_str(), \"vector\" ) == 0 )\n if ( numberOfComponents1 > 1 )\n {\n const int ret_value = ComputeVectorDifferenceImage(\n inputPixelComponentType1, inputPixelComponentType2,\n outputPixelComponentType, image1FileName, image2FileName,\n outputFileName, inputDimension1, numberOfComponents1 );\n if ( ret_value != 0 )\n {\n return ret_value;\n }\n } \/\/ end vector support\n else\n {\n std::cerr << \"Pixel types are \" << pixelType1\n << \", component types are \" << inputPixelComponentType1\n << \" and number of components equals \" << numberOfComponents1 << \".\" << std::endl;\n std::cerr << \"ERROR: This image type is not supported.\" << std::endl;\n return 1;\n }\n } \/\/ end try\n\n \/** If any errors have occurred, catch and print the exception and return false. *\/\n catch( itk::ExceptionObject & err )\n {\n std::cerr << \"ExceptionObject caught !\" << std::endl;\n std::cerr << err << std::endl;\n return 1;\n }\n\n \/** End program. Return success. *\/\n return 0;\n\n} \/\/ end main\n<|endoftext|>"} {"text":"#include \"Sandbox.h\"\n\n#include \"TestObject.h\"\n#include \"Entity.h\"\n\n#include \n#include \n#include \n#include \n#include \"imgui_impl_opengl3.h\"\n#include \"imgui_impl_glfw.h\"\n\n\nint main(int argc, char* argv[])\n{\n auto console = spdlog::stdout_color_mt(\"console\");\n spdlog::set_level(spdlog::level::info);\n\n try\n {\n auto box = std::make_shared();\n auto entity = std::make_shared();\n\n while (true)\n {\n if (box->isStopping())\n {\n break;\n }\n\n box->poolEvents();\n\n \/\/ Start the Dear ImGui frame\n ImGui_ImplOpenGL3_NewFrame();\n ImGui_ImplGlfw_NewFrame();\n ImGui::NewFrame();\n\n\n entity->render();\n\n ImGui::Render();\n ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData());\n\n box->swapBuffers();\n }\n }\n catch (std::exception& e)\n {\n console->critical(u8\"(┛◉Д◉)┛彡┻━┻: {0}\\n\", e.what());\n\n return 1;\n }\n\n return 0;\n}\nUsing fmt instead of spdlog for logging exception.#include \"Sandbox.h\"\n\n#include \"TestObject.h\"\n#include \"Entity.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \"imgui_impl_opengl3.h\"\n#include \"imgui_impl_glfw.h\"\n\n\nint main(int argc, char* argv[])\n{\n spdlog::set_level(spdlog::level::info);\n\n try\n {\n auto box = std::make_shared();\n auto entity = std::make_shared();\n\n while (true)\n {\n if (box->isStopping())\n {\n break;\n }\n\n box->poolEvents();\n\n \/\/ Start the Dear ImGui frame\n ImGui_ImplOpenGL3_NewFrame();\n ImGui_ImplGlfw_NewFrame();\n ImGui::NewFrame();\n\n\n entity->render();\n\n ImGui::Render();\n ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData());\n\n box->swapBuffers();\n }\n }\n catch (std::exception& e)\n {\n fmt::format(u8\"(┛◉Д◉)┛彡┻━┻: {0}\\n\", e.what());\n\n return 1;\n }\n\n return 0;\n}\n<|endoftext|>"} {"text":"\/*\n * Copyright (c) 2016 Zubax, zubax.com\n * Distributed under the MIT License, available in the file LICENSE.\n * Author: Pavel Kirienko \n *\/\n\n#pragma once\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \"util.hpp\"\n\n\nnamespace os\n{\nnamespace bootloader\n{\n\/**\n * Bootloader states. Some of the states are designed as commands to the outer logic, e.g. @ref ReadyToBoot\n * means that the application should be started.\n *\/\nenum class State\n{\n NoAppToBoot,\n BootDelay,\n BootCancelled,\n AppUpgradeInProgress,\n ReadyToBoot,\n};\n\nstatic inline const char* stateToString(State state)\n{\n switch (state)\n {\n case State::NoAppToBoot: return \"NoAppToBoot\";\n case State::BootDelay: return \"BootDelay\";\n case State::BootCancelled: return \"BootCancelled\";\n case State::AppUpgradeInProgress: return \"AppUpgradeInProgress\";\n case State::ReadyToBoot: return \"ReadyToBoot\";\n default: return \"INVALID_STATE\";\n }\n}\n\n\/**\n * These fields are defined by the Brickproof Bootloader specification.\n *\/\nstruct __attribute__((packed)) AppInfo\n{\n std::uint64_t image_crc = 0;\n std::uint32_t image_size = 0;\n std::uint32_t vcs_commit = 0;\n std::uint8_t major_version = 0;\n std::uint8_t minor_version = 0;\n};\n\n\/**\n * This interface abstracts the target-specific ROM routines.\n * Upgrade scenario:\n * 1. beginUpgrade()\n * 2. write() repeated until finished.\n * 3. endUpgrade(success or not)\n *\n * Please note that the performance of the ROM reading routine is critical.\n * Slow access may lead to watchdog timeouts (assuming that the watchdog is used),\n * disruption of communications, and premature expiration of the boot timeout.\n *\/\nclass IAppStorageBackend\n{\npublic:\n virtual ~IAppStorageBackend() { }\n\n \/**\n * @return 0 on success, negative on error\n *\/\n virtual int beginUpgrade() = 0;\n\n \/**\n * @return number of bytes written; negative on error\n *\/\n virtual int write(std::size_t offset, const void* data, std::size_t size) = 0;\n\n \/**\n * @return 0 on success, negative on error\n *\/\n virtual int endUpgrade(bool success) = 0;\n\n \/**\n * @return number of bytes read; negative on error\n *\/\n virtual int read(std::size_t offset, void* data, std::size_t size) = 0;\n};\n\n\/**\n * This interface proxies data received by the downloader into the bootloader.\n *\/\nclass IDownloadStreamSink\n{\npublic:\n virtual ~IDownloadStreamSink() { }\n\n \/**\n * @return Negative on error, non-negative on success.\n *\/\n virtual int handleNextDataChunk(const void* data, std::size_t size) = 0;\n};\n\n\/**\n * Inherit this class to implement firmware loading protocol, from remote to the local storage.\n *\/\nclass IDownloader\n{\npublic:\n virtual ~IDownloader() { }\n\n \/**\n * Performs the download operation synchronously.\n * Every received data chunk is fed into the sink using the corresponding method (refer to the interface\n * definition). If the sink returns error, downloading will be aborted.\n * @return Negative on error, 0 on success.\n *\/\n virtual int download(IDownloadStreamSink& sink) = 0;\n};\n\n\/**\n * Main bootloader controller.\n *\/\nclass Bootloader\n{\n static constexpr unsigned DefaultBootDelayMSec = 5000;\n\n State state_;\n IAppStorageBackend& backend_;\n\n const std::uint32_t max_application_image_size_;\n const unsigned boot_delay_msec_;\n ::systime_t boot_delay_started_at_st_;\n\n chibios_rt::Mutex mutex_;\n\n \/\/\/ Caching is needed because app check can sometimes take a very long time (several seconds)\n os::helpers::LazyConstructor cached_app_info_;\n\n \/**\n * Refer to the Brickproof Bootloader specs.\n * Note that the structure must be aligned at 8 bytes boundary, and the image must be padded to 8 bytes!\n *\/\n struct __attribute__((packed)) AppDescriptor\n {\n static constexpr unsigned ImagePaddingBytes = 8;\n\n std::array signature;\n AppInfo app_info;\n std::array reserved;\n\n static constexpr std::array getSignatureValue()\n {\n return {'A','P','D','e','s','c','0','0'};\n }\n\n bool isValid(const std::uint32_t max_application_image_size) const\n {\n const auto sgn = getSignatureValue();\n return std::equal(std::begin(signature), std::end(signature), std::begin(sgn)) &&\n (app_info.image_size > 0) &&\n (app_info.image_size <= max_application_image_size) &&\n ((app_info.image_size % ImagePaddingBytes) == 0);\n }\n };\n static_assert(sizeof(AppDescriptor) == 32, \"Invalid packing\");\n\n std::pair locateAppDescriptor();\n\n void verifyAppAndUpdateState(const State state_on_success);\n\npublic:\n \/**\n * Time since boot will be measured starting from the moment when the object was constructed.\n *\n * The max application image size parameter is very important for performance reasons;\n * without it, the bootloader may encounter an unrelated data structure in the ROM that looks like a\n * valid app descriptor (by virtue of having the same signature, which is only 64 bit long),\n * and it may spend a considerable amount of time trying to check the CRC that is certainly invalid.\n * Having an upper size limit for the application image allows the bootloader to weed out too large\n * values early, greatly improving robustness.\n *\/\n Bootloader(IAppStorageBackend& backend,\n std::uint32_t max_application_image_size = 0xFFFFFFFFU,\n unsigned boot_delay_msec = DefaultBootDelayMSec);\n\n \/**\n * @ref State.\n *\/\n State getState();\n\n \/**\n * Returns info about the application, if any.\n * @return First component is the application, second component is the status:\n * true means that the info is valid, false means that there is no application to work with.\n *\/\n std::pair getAppInfo();\n\n \/**\n * Switches the state to @ref BootCancelled, if allowed.\n *\/\n void cancelBoot();\n\n \/**\n * Switches the state to @ref ReadyToBoot, if allowed.\n *\/\n void requestBoot();\n\n \/**\n * Template method that implements all of the high-level steps of the application update procedure.\n *\/\n int upgradeApp(IDownloader& downloader);\n};\n\n}\n}\nIAppStorageBackend made const\/*\n * Copyright (c) 2016 Zubax, zubax.com\n * Distributed under the MIT License, available in the file LICENSE.\n * Author: Pavel Kirienko \n *\/\n\n#pragma once\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \"util.hpp\"\n\n\nnamespace os\n{\nnamespace bootloader\n{\n\/**\n * Bootloader states. Some of the states are designed as commands to the outer logic, e.g. @ref ReadyToBoot\n * means that the application should be started.\n *\/\nenum class State\n{\n NoAppToBoot,\n BootDelay,\n BootCancelled,\n AppUpgradeInProgress,\n ReadyToBoot,\n};\n\nstatic inline const char* stateToString(State state)\n{\n switch (state)\n {\n case State::NoAppToBoot: return \"NoAppToBoot\";\n case State::BootDelay: return \"BootDelay\";\n case State::BootCancelled: return \"BootCancelled\";\n case State::AppUpgradeInProgress: return \"AppUpgradeInProgress\";\n case State::ReadyToBoot: return \"ReadyToBoot\";\n default: return \"INVALID_STATE\";\n }\n}\n\n\/**\n * These fields are defined by the Brickproof Bootloader specification.\n *\/\nstruct __attribute__((packed)) AppInfo\n{\n std::uint64_t image_crc = 0;\n std::uint32_t image_size = 0;\n std::uint32_t vcs_commit = 0;\n std::uint8_t major_version = 0;\n std::uint8_t minor_version = 0;\n};\n\n\/**\n * This interface abstracts the target-specific ROM routines.\n * Upgrade scenario:\n * 1. beginUpgrade()\n * 2. write() repeated until finished.\n * 3. endUpgrade(success or not)\n *\n * Please note that the performance of the ROM reading routine is critical.\n * Slow access may lead to watchdog timeouts (assuming that the watchdog is used),\n * disruption of communications, and premature expiration of the boot timeout.\n *\/\nclass IAppStorageBackend\n{\npublic:\n virtual ~IAppStorageBackend() { }\n\n \/**\n * @return 0 on success, negative on error\n *\/\n virtual int beginUpgrade() = 0;\n\n \/**\n * @return number of bytes written; negative on error\n *\/\n virtual int write(std::size_t offset, const void* data, std::size_t size) = 0;\n\n \/**\n * @return 0 on success, negative on error\n *\/\n virtual int endUpgrade(bool success) = 0;\n\n \/**\n * @return number of bytes read; negative on error\n *\/\n virtual int read(std::size_t offset, void* data, std::size_t size) const = 0;\n};\n\n\/**\n * This interface proxies data received by the downloader into the bootloader.\n *\/\nclass IDownloadStreamSink\n{\npublic:\n virtual ~IDownloadStreamSink() { }\n\n \/**\n * @return Negative on error, non-negative on success.\n *\/\n virtual int handleNextDataChunk(const void* data, std::size_t size) = 0;\n};\n\n\/**\n * Inherit this class to implement firmware loading protocol, from remote to the local storage.\n *\/\nclass IDownloader\n{\npublic:\n virtual ~IDownloader() { }\n\n \/**\n * Performs the download operation synchronously.\n * Every received data chunk is fed into the sink using the corresponding method (refer to the interface\n * definition). If the sink returns error, downloading will be aborted.\n * @return Negative on error, 0 on success.\n *\/\n virtual int download(IDownloadStreamSink& sink) = 0;\n};\n\n\/**\n * Main bootloader controller.\n *\/\nclass Bootloader\n{\n static constexpr unsigned DefaultBootDelayMSec = 5000;\n\n State state_;\n IAppStorageBackend& backend_;\n\n const std::uint32_t max_application_image_size_;\n const unsigned boot_delay_msec_;\n ::systime_t boot_delay_started_at_st_;\n\n chibios_rt::Mutex mutex_;\n\n \/\/\/ Caching is needed because app check can sometimes take a very long time (several seconds)\n os::helpers::LazyConstructor cached_app_info_;\n\n \/**\n * Refer to the Brickproof Bootloader specs.\n * Note that the structure must be aligned at 8 bytes boundary, and the image must be padded to 8 bytes!\n *\/\n struct __attribute__((packed)) AppDescriptor\n {\n static constexpr unsigned ImagePaddingBytes = 8;\n\n std::array signature;\n AppInfo app_info;\n std::array reserved;\n\n static constexpr std::array getSignatureValue()\n {\n return {'A','P','D','e','s','c','0','0'};\n }\n\n bool isValid(const std::uint32_t max_application_image_size) const\n {\n const auto sgn = getSignatureValue();\n return std::equal(std::begin(signature), std::end(signature), std::begin(sgn)) &&\n (app_info.image_size > 0) &&\n (app_info.image_size <= max_application_image_size) &&\n ((app_info.image_size % ImagePaddingBytes) == 0);\n }\n };\n static_assert(sizeof(AppDescriptor) == 32, \"Invalid packing\");\n\n std::pair locateAppDescriptor();\n\n void verifyAppAndUpdateState(const State state_on_success);\n\npublic:\n \/**\n * Time since boot will be measured starting from the moment when the object was constructed.\n *\n * The max application image size parameter is very important for performance reasons;\n * without it, the bootloader may encounter an unrelated data structure in the ROM that looks like a\n * valid app descriptor (by virtue of having the same signature, which is only 64 bit long),\n * and it may spend a considerable amount of time trying to check the CRC that is certainly invalid.\n * Having an upper size limit for the application image allows the bootloader to weed out too large\n * values early, greatly improving robustness.\n *\/\n Bootloader(IAppStorageBackend& backend,\n std::uint32_t max_application_image_size = 0xFFFFFFFFU,\n unsigned boot_delay_msec = DefaultBootDelayMSec);\n\n \/**\n * @ref State.\n *\/\n State getState();\n\n \/**\n * Returns info about the application, if any.\n * @return First component is the application, second component is the status:\n * true means that the info is valid, false means that there is no application to work with.\n *\/\n std::pair getAppInfo();\n\n \/**\n * Switches the state to @ref BootCancelled, if allowed.\n *\/\n void cancelBoot();\n\n \/**\n * Switches the state to @ref ReadyToBoot, if allowed.\n *\/\n void requestBoot();\n\n \/**\n * Template method that implements all of the high-level steps of the application update procedure.\n *\/\n int upgradeApp(IDownloader& downloader);\n};\n\n}\n}\n<|endoftext|>"} {"text":"\/* Copyright (C) 2018, Project Pluto. See LICENSE.\n\n This program will generate simulated geocentric observations\nfor a given object from a TLE. In theory, one can then fit these\npseudo-observations to a higher-quality physical model to get a\nconsiderably more accurate ephemeris for the object. *\/\n\n#include \n#include \n#include \n#include \"norad.h\"\n#include \"observe.h\"\n\n#define PI 3.1415926535897932384626433832795028841971693993751058209749445923\n\nint main( const int argc, const char **argv)\n{\n FILE *ifile = fopen( argv[1], \"rb\");\n char line1[100], line2[100];\n const char *intl_id = NULL;\n double step_size = .1;\n int i, n_steps = 100;\n bool show_vectors = false;\n\n if( !ifile)\n {\n printf( \"Couldn't open input file\\n\");\n exit( -1);\n }\n for( i = 1; i < argc; i++)\n if( argv[i][0] == '-')\n switch( argv[i][1])\n {\n case 'i':\n intl_id = argv[i] + 2;\n break;\n case 'n':\n n_steps = atoi( argv[i] + 2);\n break;\n case 's':\n step_size = atof( argv[i] + 2);\n break;\n case 'v':\n show_vectors = true;\n break;\n default:\n printf( \"Unrecognized option '%s'\\n\", argv[i]);\n break;\n }\n *line1 = '\\0';\n sxpx_set_implementation_param( SXPX_DUNDEE_COMPLIANCE, 1);\n while( fgets( line2, sizeof( line2), ifile))\n {\n tle_t tle; \/* Pointer to two-line elements set for satellite *\/\n int err_val;\n\n if( (!intl_id || !memcmp( intl_id, line1 + 9, 6))\n && (err_val = parse_elements( line1, line2, &tle)) >= 0)\n { \/* hey! we got a TLE! *\/\n int is_deep = select_ephemeris( &tle);\n double sat_params[N_SAT_PARAMS], observer_loc[3];\n double prev_pos[3];\n\n if( err_val)\n printf( \"WARNING: TLE parsing error %d\\n\", err_val);\n for( i = 0; i < 3; i++)\n observer_loc[i] = '\\0';\n if( is_deep)\n SDP4_init( sat_params, &tle);\n else\n SGP4_init( sat_params, &tle);\n for( i = 0; i < n_steps; i++)\n {\n double pos[3]; \/* Satellite position vector *\/\n double t_since = (double)( i - n_steps \/ 2) * step_size;\n double jd = tle.epoch + t_since;\n\n t_since *= 1440.;\n if( is_deep)\n err_val = SDP4( t_since, &tle, sat_params, pos, NULL);\n else\n err_val = SGP4( t_since, &tle, sat_params, pos, NULL);\n if( err_val)\n printf( \"Ephemeris error %d\\n\", err_val);\n if( show_vectors)\n {\n if( i)\n printf( \"%14.6f %14.6f %14.6f - \", pos[0] - prev_pos[0],\n pos[1] - prev_pos[1],\n pos[2] - prev_pos[2]);\n printf( \"%14.6f %14.6f %14.6f\\n\", pos[0], pos[1], pos[2]);\n memcpy( prev_pos, pos, 3 * sizeof( double));\n }\n else\n {\n double ra, dec, dist_to_satellite;\n\n get_satellite_ra_dec_delta( observer_loc, pos,\n &ra, &dec, &dist_to_satellite);\n epoch_of_date_to_j2000( jd, &ra, &dec);\n printf( \"%-14sC%13.5f %08.4f %+08.4f\",\n intl_id, jd, ra * 180. \/ PI, dec * 180. \/ PI);\n printf( \" TLEs 500\\n\");\n }\n }\n }\n strcpy( line1, line2);\n }\n fclose( ifile);\n return( 0);\n} \/* End of main() *\/\n\nWhy did I set a double-precision floating-point value to '\\0' instead of to '0.'? And how does this not get a warning message from gcc?\/* Copyright (C) 2018, Project Pluto. See LICENSE.\n\n This program will generate simulated geocentric observations\nfor a given object from a TLE. In theory, one can then fit these\npseudo-observations to a higher-quality physical model to get a\nconsiderably more accurate ephemeris for the object. *\/\n\n#include \n#include \n#include \n#include \"norad.h\"\n#include \"observe.h\"\n\n#define PI 3.1415926535897932384626433832795028841971693993751058209749445923\n\nint main( const int argc, const char **argv)\n{\n FILE *ifile = fopen( argv[1], \"rb\");\n char line1[100], line2[100];\n const char *intl_id = NULL;\n double step_size = .1;\n int i, n_steps = 100;\n bool show_vectors = false;\n\n if( !ifile)\n {\n printf( \"Couldn't open input file\\n\");\n exit( -1);\n }\n for( i = 1; i < argc; i++)\n if( argv[i][0] == '-')\n switch( argv[i][1])\n {\n case 'i':\n intl_id = argv[i] + 2;\n break;\n case 'n':\n n_steps = atoi( argv[i] + 2);\n break;\n case 's':\n step_size = atof( argv[i] + 2);\n break;\n case 'v':\n show_vectors = true;\n break;\n default:\n printf( \"Unrecognized option '%s'\\n\", argv[i]);\n break;\n }\n *line1 = '\\0';\n sxpx_set_implementation_param( SXPX_DUNDEE_COMPLIANCE, 1);\n while( fgets( line2, sizeof( line2), ifile))\n {\n tle_t tle; \/* Pointer to two-line elements set for satellite *\/\n int err_val;\n\n if( (!intl_id || !memcmp( intl_id, line1 + 9, 6))\n && (err_val = parse_elements( line1, line2, &tle)) >= 0)\n { \/* hey! we got a TLE! *\/\n int is_deep = select_ephemeris( &tle);\n double sat_params[N_SAT_PARAMS], observer_loc[3];\n double prev_pos[3];\n\n if( err_val)\n printf( \"WARNING: TLE parsing error %d\\n\", err_val);\n for( i = 0; i < 3; i++)\n observer_loc[i] = 0.;\n if( is_deep)\n SDP4_init( sat_params, &tle);\n else\n SGP4_init( sat_params, &tle);\n for( i = 0; i < n_steps; i++)\n {\n double pos[3]; \/* Satellite position vector *\/\n double t_since = (double)( i - n_steps \/ 2) * step_size;\n double jd = tle.epoch + t_since;\n\n t_since *= 1440.;\n if( is_deep)\n err_val = SDP4( t_since, &tle, sat_params, pos, NULL);\n else\n err_val = SGP4( t_since, &tle, sat_params, pos, NULL);\n if( err_val)\n printf( \"Ephemeris error %d\\n\", err_val);\n if( show_vectors)\n {\n if( i)\n printf( \"%14.6f %14.6f %14.6f - \", pos[0] - prev_pos[0],\n pos[1] - prev_pos[1],\n pos[2] - prev_pos[2]);\n printf( \"%14.6f %14.6f %14.6f\\n\", pos[0], pos[1], pos[2]);\n memcpy( prev_pos, pos, 3 * sizeof( double));\n }\n else\n {\n double ra, dec, dist_to_satellite;\n\n get_satellite_ra_dec_delta( observer_loc, pos,\n &ra, &dec, &dist_to_satellite);\n epoch_of_date_to_j2000( jd, &ra, &dec);\n printf( \"%-14sC%13.5f %08.4f %+08.4f\",\n intl_id, jd, ra * 180. \/ PI, dec * 180. \/ PI);\n printf( \" TLEs 500\\n\");\n }\n }\n }\n strcpy( line1, line2);\n }\n fclose( ifile);\n return( 0);\n} \/* End of main() *\/\n\n<|endoftext|>"} {"text":"\/****************************************************************************\n**\n** Copyright (C) 2010 Nokia Corporation and\/or its subsidiary(-ies).\n** All rights reserved.\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n** This file is part of the QtDeclarative module of the Qt Toolkit.\n**\n** $QT_BEGIN_LICENSE:LGPL$\n** No Commercial Usage\n** This file contains pre-release code and may not be distributed.\n** You may use this file in accordance with the terms and conditions\n** contained in the Technology Preview License Agreement accompanying\n** this package.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Nokia gives you certain additional\n** rights. These rights are described in the Nokia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at qt-info@nokia.com.\n**\n**\n**\n**\n**\n**\n**\n**\n** $QT_END_LICENSE$\n**\n****************************************************************************\/\n\n\n#include \"qsgsimpletexturenode.h\"\n\nQT_BEGIN_NAMESPACE\n\nstatic void qsgsimpletexturenode_update(QSGGeometry *g,\n QSGTexture *texture,\n const QRectF &rect)\n{\n if (!texture)\n return;\n\n QSize ts = texture->textureSize();\n QRectF sourceRect(0, ts.height(), ts.width(), -ts.height());\n QSGGeometry::updateTexturedRectGeometry(g, rect, texture->convertToNormalizedSourceRect(sourceRect));\n}\n\n\/*!\n \\class QSGSimpleTextureNode\n \\brief The QSGSimpleTextureNode provided for convenience to easily draw\n textured content using the QML scene graph.\n\n \\warning The simple texture node class must have texture before being\n added to the scene graph to be rendered.\n*\/\n\n\/*!\n Constructs a new simple texture node\n *\/\nQSGSimpleTextureNode::QSGSimpleTextureNode()\n : m_geometry(QSGGeometry::defaultAttributes_TexturedPoint2D(), 4)\n{\n setGeometry(&m_geometry);\n setMaterial(&m_material);\n setOpaqueMaterial(&m_opaque_material);\n}\n\n\/*!\n Sets the filtering to be used for this texture node to \\a filtering.\n\n For smooth scaling, use QSGTexture::Linear; for normal scaling, use\n QSGTexture::Nearest.\n *\/\nvoid QSGSimpleTextureNode::setFiltering(QSGTexture::Filtering filtering)\n{\n if (m_material.filtering() == filtering)\n return;\n\n m_material.setFiltering(filtering);\n m_opaque_material.setFiltering(filtering);\n markDirty(DirtyMaterial);\n}\n\n\n\/*!\n Returns the filtering currently set on this texture node\n *\/\nQSGTexture::Filtering QSGSimpleTextureNode::filtering() const\n{\n return m_material.filtering();\n}\n\n\n\/*!\n Sets the target rect of this texture node to \\a r\n *\/\nvoid QSGSimpleTextureNode::setRect(const QRectF &r)\n{\n if (m_rect == r)\n return;\n m_rect = r;\n qsgsimpletexturenode_update(&m_geometry, texture(), m_rect);\n markDirty(DirtyGeometry);\n}\n\n\n\/*!\n Returns the target rect of this texture node.\n *\/\nQRectF QSGSimpleTextureNode::rect() const\n{\n return m_rect;\n}\n\n\/*!\n Sets the texture of this texture node to \\a texture.\n\n \\warning A texture node must have a texture before being added\n to the scenegraph to be rendered.\n *\/\nvoid QSGSimpleTextureNode::setTexture(QSGTexture *texture)\n{\n if (m_material.texture() == texture)\n return;\n m_material.setTexture(texture);\n m_opaque_material.setTexture(texture);\n qsgsimpletexturenode_update(&m_geometry, texture, m_rect);\n markDirty(DirtyMaterial);\n}\n\n\n\n\/*!\n Returns the texture for this texture node\n *\/\nQSGTexture *QSGSimpleTextureNode::texture() const\n{\n return m_material.texture();\n}\n\nQT_END_NAMESPACE\nFixes wrong flipping of textures.\/****************************************************************************\n**\n** Copyright (C) 2010 Nokia Corporation and\/or its subsidiary(-ies).\n** All rights reserved.\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n** This file is part of the QtDeclarative module of the Qt Toolkit.\n**\n** $QT_BEGIN_LICENSE:LGPL$\n** No Commercial Usage\n** This file contains pre-release code and may not be distributed.\n** You may use this file in accordance with the terms and conditions\n** contained in the Technology Preview License Agreement accompanying\n** this package.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Nokia gives you certain additional\n** rights. These rights are described in the Nokia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at qt-info@nokia.com.\n**\n**\n**\n**\n**\n**\n**\n**\n** $QT_END_LICENSE$\n**\n****************************************************************************\/\n\n\n#include \"qsgsimpletexturenode.h\"\n\nQT_BEGIN_NAMESPACE\n\nstatic void qsgsimpletexturenode_update(QSGGeometry *g,\n QSGTexture *texture,\n const QRectF &rect)\n{\n if (!texture)\n return;\n\n QSize ts = texture->textureSize();\n QRectF sourceRect(0, 0, ts.width(), ts.height());\n QSGGeometry::updateTexturedRectGeometry(g, rect, texture->convertToNormalizedSourceRect(sourceRect));\n}\n\n\/*!\n \\class QSGSimpleTextureNode\n \\brief The QSGSimpleTextureNode provided for convenience to easily draw\n textured content using the QML scene graph.\n\n \\warning The simple texture node class must have texture before being\n added to the scene graph to be rendered.\n*\/\n\n\/*!\n Constructs a new simple texture node\n *\/\nQSGSimpleTextureNode::QSGSimpleTextureNode()\n : m_geometry(QSGGeometry::defaultAttributes_TexturedPoint2D(), 4)\n{\n setGeometry(&m_geometry);\n setMaterial(&m_material);\n setOpaqueMaterial(&m_opaque_material);\n}\n\n\/*!\n Sets the filtering to be used for this texture node to \\a filtering.\n\n For smooth scaling, use QSGTexture::Linear; for normal scaling, use\n QSGTexture::Nearest.\n *\/\nvoid QSGSimpleTextureNode::setFiltering(QSGTexture::Filtering filtering)\n{\n if (m_material.filtering() == filtering)\n return;\n\n m_material.setFiltering(filtering);\n m_opaque_material.setFiltering(filtering);\n markDirty(DirtyMaterial);\n}\n\n\n\/*!\n Returns the filtering currently set on this texture node\n *\/\nQSGTexture::Filtering QSGSimpleTextureNode::filtering() const\n{\n return m_material.filtering();\n}\n\n\n\/*!\n Sets the target rect of this texture node to \\a r\n *\/\nvoid QSGSimpleTextureNode::setRect(const QRectF &r)\n{\n if (m_rect == r)\n return;\n m_rect = r;\n qsgsimpletexturenode_update(&m_geometry, texture(), m_rect);\n markDirty(DirtyGeometry);\n}\n\n\n\/*!\n Returns the target rect of this texture node.\n *\/\nQRectF QSGSimpleTextureNode::rect() const\n{\n return m_rect;\n}\n\n\/*!\n Sets the texture of this texture node to \\a texture.\n\n \\warning A texture node must have a texture before being added\n to the scenegraph to be rendered.\n *\/\nvoid QSGSimpleTextureNode::setTexture(QSGTexture *texture)\n{\n if (m_material.texture() == texture)\n return;\n m_material.setTexture(texture);\n m_opaque_material.setTexture(texture);\n qsgsimpletexturenode_update(&m_geometry, texture, m_rect);\n markDirty(DirtyMaterial);\n}\n\n\n\n\/*!\n Returns the texture for this texture node\n *\/\nQSGTexture *QSGSimpleTextureNode::texture() const\n{\n return m_material.texture();\n}\n\nQT_END_NAMESPACE\n<|endoftext|>"} {"text":"\/***********************************************************************************************************************\n**\n** Copyright (c) 2011, 2013 ETH Zurich\n** All rights reserved.\n**\n** Redistribution and use in source and binary forms, with or without modification, are permitted provided that the\n** following conditions are met:\n**\n** * Redistributions of source code must retain the above copyright notice, this list of conditions and the following\n** disclaimer.\n** * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the\n** following disclaimer in the documentation and\/or other materials provided with the distribution.\n** * Neither the name of the ETH Zurich nor the names of its contributors may be used to endorse or promote products\n** derived from this software without specific prior written permission.\n**\n**\n** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES,\n** INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n** SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n**\n***********************************************************************************************************************\/\n\n#include \"AutoTypeExpression.h\"\n\n#include \"..\/..\/declarations\/VariableDeclaration.h\"\n#include \"..\/..\/types\/ErrorType.h\"\n\n#include \"ModelBase\/src\/nodes\/TypedListDefinition.h\"\nDEFINE_TYPED_LIST(OOModel::AutoTypeExpression)\n\nnamespace OOModel {\n\nCOMPOSITENODE_DEFINE_EMPTY_CONSTRUCTORS(AutoTypeExpression)\nCOMPOSITENODE_DEFINE_TYPE_REGISTRATION_METHODS(AutoTypeExpression)\n\nType* AutoTypeExpression::type()\n{\n\tauto t = dynamic_cast(parent());\n\tQ_ASSERT(t);\n\tif(t->initialValue()) return t->initialValue()->type();\n\treturn new ErrorType(\"No initial value in auto type\");\n}\n\n}\nFix AutoTypeExpression type() resolution Add support for auto& and auto*\/***********************************************************************************************************************\n**\n** Copyright (c) 2011, 2013 ETH Zurich\n** All rights reserved.\n**\n** Redistribution and use in source and binary forms, with or without modification, are permitted provided that the\n** following conditions are met:\n**\n** * Redistributions of source code must retain the above copyright notice, this list of conditions and the following\n** disclaimer.\n** * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the\n** following disclaimer in the documentation and\/or other materials provided with the distribution.\n** * Neither the name of the ETH Zurich nor the names of its contributors may be used to endorse or promote products\n** derived from this software without specific prior written permission.\n**\n**\n** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES,\n** INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n** SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n**\n***********************************************************************************************************************\/\n\n#include \"AutoTypeExpression.h\"\n\n#include \"..\/..\/declarations\/VariableDeclaration.h\"\n#include \"..\/..\/types\/ErrorType.h\"\n\n#include \"ModelBase\/src\/nodes\/TypedListDefinition.h\"\nDEFINE_TYPED_LIST(OOModel::AutoTypeExpression)\n\nnamespace OOModel {\n\nCOMPOSITENODE_DEFINE_EMPTY_CONSTRUCTORS(AutoTypeExpression)\nCOMPOSITENODE_DEFINE_TYPE_REGISTRATION_METHODS(AutoTypeExpression)\n\nType* AutoTypeExpression::type()\n{\n\tauto p = parent();\n\tVariableDeclaration* varDecl = nullptr;\n\tif(!(varDecl = dynamic_cast(p)))\n\t\tvarDecl = dynamic_cast(p->parent());\n\tQ_ASSERT(varDecl);\n\tif(!varDecl->initialValue())\n\t\treturn new ErrorType(\"No initial value in auto type\");\n\tauto initType = varDecl->initialValue()->type();\n\tif(varDecl == p)\n\t\treturn initType;\n\tif(dynamic_cast(p))\n\t\treturn new ReferenceType(initType, initType->isValueType());\n\tif(dynamic_cast(p))\n\t\treturn new PointerType(initType, initType->isValueType());\n\t\/\/ this can\/should not happen\n\tQ_ASSERT(0);\n\treturn nullptr;\n}\n\n}\n<|endoftext|>"} {"text":"#include \n#include \n\n#include \"src\/args\/args.h\"\n#include \"src\/ext\/cpputil\/include\/command_line\/command_line.h\"\n#include \"src\/ext\/cpputil\/include\/system\/terminal.h\"\n#include \"src\/ext\/x64asm\/include\/x64asm.h\"\n\nusing namespace cpputil;\nusing namespace std;\nusing namespace x64asm;\n\nauto& h1 = Heading::create(\"I\/O options:\");\n\nauto& binary = ValueArg::create(\"object\")\n\t.usage(\"\")\n\t.description(\"Object file to scrape code from\")\n\t.default_val(\".\/a.out\");\n\nauto& out_dir = ValueArg::create(\"out\")\n .alternate(\"o\")\n\t.usage(\"\")\n .description(\"Directory to write results to\")\n .default_val(\"bins\");\n\nbool exists(const string& file) {\n\tifstream temp(file);\n\treturn temp.is_open();\n}\n\nbool symdump(const string& file) {\n\tTerminal term1;\n\tterm1 << \"nm -a \" << file \n\t\t<< \" | grep \\\" [WTti] \\\" | sed \\\"s\/.* [WTti] \/\/\\\" > \/tmp\/stoke.$USER.symdump\" << endl;\n\n\tTerminal term2;\n\tterm2 << \"nm -D \" << file \n\t\t<< \" | grep \\\" [WTti] \\\" | sed \\\"s\/.* [WTti] \/\/\\\" >> \/tmp\/stoke.$USER.symdump\" << endl;\n\n return term1.result() == 0 || term2.result() == 0;\n}\n\nbool objdump(const string& file) {\n\tTerminal term;\n\tterm << \"objdump -d -Msuffix \" << file << \" > \/tmp\/stoke.$USER.objdump\" << endl;\n\treturn term.result() == 0;\n}\n\nbool mkdir() {\n\tTerminal term;\n term << \"mkdir -p \" << out_dir.value() << endl;\n return term.result() == 0;\n}\n\nint main(int argc, char** argv) {\n\tCommandLineConfig::strict_with_convenience(argc, argv);\n\n\tif ( !exists(binary) ) {\n\t\tcout << \"Unable to read binary file \" << binary.value() << \"!\" << endl;\n\t\treturn 1;\n\t} else if ( !symdump(binary) ) {\n\t\tcout << \"Unable to extract symbols from binary file \" << binary.value() << \"!\" << endl;\n\t\treturn 1;\n\t} else if ( !objdump(binary) ) {\n\t\tcout << \"Unable to extract object code from binary file \" << binary.value() << \"!\" << endl;\n return 1;\n\t} else if ( !mkdir() ) {\n cout << \"Unable to create output directory \" << out_dir.value() << \"!\" << endl;\n return 1;\n }\n\n\treturn 0;\n}\n\nUsing term instead of fstream for checking file.#include \n#include \n\n#include \"src\/args\/args.h\"\n#include \"src\/ext\/cpputil\/include\/command_line\/command_line.h\"\n#include \"src\/ext\/cpputil\/include\/system\/terminal.h\"\n#include \"src\/ext\/x64asm\/include\/x64asm.h\"\n\nusing namespace cpputil;\nusing namespace std;\nusing namespace x64asm;\n\nauto& h1 = Heading::create(\"I\/O options:\");\n\nauto& binary = ValueArg::create(\"object\")\n\t.usage(\"\")\n\t.description(\"Object file to scrape code from\")\n\t.default_val(\".\/a.out\");\n\nauto& out_dir = ValueArg::create(\"out\")\n .alternate(\"o\")\n\t.usage(\"\")\n .description(\"Directory to write results to\")\n .default_val(\"bins\");\n\nbool exists(const string& file) {\n\tTerminal term;\n\tterm << \"ls \" << file << endl;\n\treturn term.result() == 0;\n}\n\nbool symdump(const string& file) {\n\tTerminal term1;\n\tterm1 << \"nm -a \" << file \n\t\t<< \" | grep \\\" [WTti] \\\" | sed \\\"s\/.* [WTti] \/\/\\\" > \/tmp\/stoke.$USER.symdump\" << endl;\n\n\tTerminal term2;\n\tterm2 << \"nm -D \" << file \n\t\t<< \" | grep \\\" [WTti] \\\" | sed \\\"s\/.* [WTti] \/\/\\\" >> \/tmp\/stoke.$USER.symdump\" << endl;\n\n return term1.result() == 0 || term2.result() == 0;\n}\n\nbool objdump(const string& file) {\n\tTerminal term;\n\tterm << \"objdump -d -Msuffix \" << file << \" > \/tmp\/stoke.$USER.objdump\" << endl;\n\treturn term.result() == 0;\n}\n\nbool mkdir() {\n\tTerminal term;\n term << \"mkdir -p \" << out_dir.value() << endl;\n return term.result() == 0;\n}\n\nint main(int argc, char** argv) {\n\tCommandLineConfig::strict_with_convenience(argc, argv);\n\n\tif ( !exists(binary) ) {\n\t\tcout << \"Unable to read binary file \" << binary.value() << \"!\" << endl;\n\t\treturn 1;\n\t} else if ( !symdump(binary) ) {\n\t\tcout << \"Unable to extract symbols from binary file \" << binary.value() << \"!\" << endl;\n\t\treturn 1;\n\t} else if ( !objdump(binary) ) {\n\t\tcout << \"Unable to extract object code from binary file \" << binary.value() << \"!\" << endl;\n return 1;\n\t} else if ( !mkdir() ) {\n cout << \"Unable to create output directory \" << out_dir.value() << \"!\" << endl;\n return 1;\n }\n\n\treturn 0;\n}\n\n<|endoftext|>"} {"text":"#include \"amd64.h\"\n#include \"distribution.hh\"\n#include \"spinbarrier.hh\"\n#include \"libutil.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n\nusing std::string;\n\nenum { warmup_secs = 1 };\nenum { duration = 5 };\n\nconst char *message =\n \"Received: from incoming.csail.mit.edu (incoming.csail.mit.edu [128.30.2.16])\\n\"\n \" by metroplex (Cyrus v2.2.13-Debian-2.2.13-14+lenny5) with LMTPA;\\n\"\n \" Tue, 19 Mar 2013 22:45:50 -0400\\n\"\n \"X-Sieve: CMU Sieve 2.2\\n\"\n \"Received: from mailhub-auth-3.mit.edu ([18.9.21.43])\\n\"\n \" by incoming.csail.mit.edu with esmtps\\n\"\n \" (TLS1.0:DHE_RSA_AES_256_CBC_SHA1:32)\\n\"\n \" (Exim 4.72)\\n\"\n \" (envelope-from )\\n\"\n \" id 1UI92E-0007D2-7N\\n\"\n \" for xxxxxxxxx@csail.mit.edu; Tue, 19 Mar 2013 22:45:50 -0400\\n\"\n \"Received: from outgoing.mit.edu (OUTGOING-AUTH-1.MIT.EDU [18.9.28.11])\\n\"\n \" by mailhub-auth-3.mit.edu (8.13.8\/8.9.2) with ESMTP id r2K2jnO5025684\\n\"\n \" for ; Tue, 19 Mar 2013 22:45:49 -0400\\n\"\n \"Received: from xxxxxxxxx.csail.mit.edu (xxxxxxxxx.csail.mit.edu [18.26.4.91])\\n\"\n \" (authenticated bits=0)\\n\"\n \" (User authenticated as xxxxxxxx@ATHENA.MIT.EDU)\\n\"\n \" by outgoing.mit.edu (8.13.8\/8.12.4) with ESMTP id r2K2jmc7032022\\n\"\n \" (version=TLSv1\/SSLv3 cipher=DHE-RSA-AES128-SHA bits=128 verify=NOT)\\n\"\n \" for ; Tue, 19 Mar 2013 22:45:49 -0400\\n\"\n \"Received: from xxxxxxx by xxxxxxxxx.csail.mit.edu with local (Exim 4.80)\\n\"\n \" (envelope-from )\\n\"\n \" id 1UI92C-0000il-4L\\n\"\n \" for xxxxxxxx@mit.edu; Tue, 19 Mar 2013 22:45:48 -0400\\n\"\n \"From: Austin Clements \\n\"\n \"To: xxxxxxxx@mit.edu\\n\"\n \"Subject: Test message\\n\"\n \"User-Agent: Notmuch\/0.15+6~g7d4cb73 (http:\/\/notmuchmail.org) Emacs\/23.4.1\\n\"\n \" (i486-pc-linux-gnu)\\n\"\n \"Date: Tue, 19 Mar 2013 22:45:48 -0400\\n\"\n \"Message-ID: <874ng6vler.fsf@xxxxxxxxx.csail.mit.edu>\\n\"\n \"MIME-Version: 1.0\\n\"\n \"Content-Type: text\/plain; charset=us-ascii\\n\"\n \"\\n\"\n \"Hello.\\n\";\n\nextern char **environ;\n\nstatic spin_barrier bar;\n\nstatic concurrent_distribution start_tsc, stop_tsc;\nstatic concurrent_distribution start_usec, stop_usec;\nstatic concurrent_distribution count;\n\nstatic volatile bool stop __mpalign__;\nstatic volatile bool warmup;\nstatic __padout__ __attribute__((unused));\n\nstatic void\ntimer_thread(void)\n{\n warmup = true;\n bar.join();\n bar.join();\n sleep(warmup_secs);\n warmup = false;\n sleep(duration);\n stop = true;\n}\n\nstatic void\ndo_mua(int cpu, string spooldir, string msgpath)\n{\n const char *argv[] = {\".\/mail-enqueue\", spooldir.c_str(), \"user\", nullptr};\n#if defined(XV6_USER)\n int errno;\n#endif\n setaffinity(cpu);\n\n \/\/ Open message file (alternatively, we could use an open spawn\n \/\/ action)\n int msgfd = open(msgpath.c_str(), O_RDONLY|O_CLOEXEC);\n if (msgfd < 0)\n edie(\"open %s failed\", msgpath.c_str());\n\n bool mywarmup = true;\n uint64_t mycount = 0;\n while (!stop) {\n if (__builtin_expect(warmup != mywarmup, 0)) {\n mywarmup = warmup;\n mycount = 0;\n start_usec.add(now_usec());\n start_tsc.add(rdtsc());\n }\n\n pid_t pid;\n posix_spawn_file_actions_t actions;\n if ((errno = posix_spawn_file_actions_init(&actions)))\n edie(\"posix_spawn_file_actions_init failed\");\n if ((errno = posix_spawn_file_actions_adddup2(&actions, msgfd, 0)))\n edie(\"posix_spawn_file_actions_adddup2 failed\");\n if ((errno = posix_spawn(&pid, argv[0], &actions, nullptr,\n const_cast(argv), environ)))\n edie(\"posix_spawn failed\");\n if ((errno = posix_spawn_file_actions_destroy(&actions)))\n edie(\"posix_spawn_file_actions_destroy failed\");\n\n int status;\n if (waitpid(pid, &status, 0) < 0)\n edie(\"waitpid failed\");\n if (!WIFEXITED(status) || WEXITSTATUS(status))\n die(\"deliver failed: status %d\", status);\n\n ++mycount;\n }\n\n stop_usec.add(now_usec());\n stop_tsc.add(rdtsc());\n count.add(mycount);\n}\n\nstatic void\nxmkdir(const string &d)\n{\n if (mkdir(d.c_str(), 0777) < 0)\n edie(\"failed to mkdir %s\", d.c_str());\n}\n\nstatic void\ncreate_spool(const string &base)\n{\n xmkdir(base);\n xmkdir(base + \"\/pid\");\n xmkdir(base + \"\/todo\");\n xmkdir(base + \"\/mess\");\n}\n\nstatic void\ncreate_maildir(const string &base)\n{\n xmkdir(base);\n xmkdir(base + \"\/tmp\");\n xmkdir(base + \"\/new\");\n xmkdir(base + \"\/cur\");\n}\n\nvoid\nusage(const char *argv0)\n{\n fprintf(stderr, \"Usage: %s basedir nthreads\\n\", argv0);\n exit(2);\n}\n\nint\nmain(int argc, char **argv)\n{\n if (argc != 3)\n usage(argv[0]);\n\n string basedir(argv[1]);\n const char *nthreads_str = argv[2];\n int nthreads = atoi(nthreads_str);\n if (nthreads <= 0)\n usage(argv[0]);\n\n \/\/ Create spool and inboxes\n \/\/ XXX This terminology is wrong. The spool is where mail\n \/\/ ultimately gets delivered to.\n string spooldir = basedir + \"\/spool\";\n create_spool(spooldir);\n string mailroot = basedir + \"\/mail\";\n xmkdir(mailroot);\n create_maildir(mailroot + \"\/user\");\n\n \/\/ Start queue manager\n const char *qman[] = {\".\/mail-qman\", spooldir.c_str(), mailroot.c_str(),\n nthreads_str, nullptr};\n pid_t qman_pid;\n if (posix_spawn(&qman_pid, qman[0], nullptr, nullptr,\n const_cast(qman), environ) != 0)\n die(\"posix_spawn %s failed\", qman[0]);\n sleep(1);\n\n \/\/ Write message to a file\n int fd = open((basedir + \"\/msg\").c_str(), O_CREAT|O_WRONLY, 0666);\n if (fd < 0)\n edie(\"open\");\n xwrite(fd, message, strlen(message));\n close(fd);\n\n printf(\"# --cores=%d --duration=%ds\\n\", nthreads, duration);\n\n \/\/ Run benchmark\n bar.init(nthreads + 1);\n\n std::thread timer(timer_thread);\n\n std::thread *threads = new std::thread[nthreads];\n for (int i = 0; i < nthreads; ++i)\n threads[i] = std::thread(do_mua, i, basedir + \"\/spool\", basedir + \"\/msg\");\n\n \/\/ Wait\n timer.join();\n for (int i = 0; i < nthreads; ++i)\n threads[i].join();\n\n \/\/ XXX Kill qman and wait for it to exit\n\n \/\/ Summarize\n printf(\"%lu start usec skew\\n\", start_usec.span());\n printf(\"%lu stop usec skew\\n\", stop_usec.span());\n uint64_t usec = stop_usec.mean() - start_usec.mean();\n printf(\"%f secs\\n\", (double)usec \/ 1e6);\n printf(\"%lu cycles\\n\", stop_tsc.mean() - start_tsc.mean());\n\n uint64_t iters = count.sum();\n printf(\"%lu iters\\n\", iters);\n if (iters) {\n printf(\"%lu cycles\/iter\\n\", (stop_tsc.sum() - start_tsc.sum()) \/ iters);\n printf(\"%lu iters\/sec\\n\", iters * 1000000 \/ usec);\n }\n}\nmailbench: Exit the queue manager#include \"amd64.h\"\n#include \"distribution.hh\"\n#include \"spinbarrier.hh\"\n#include \"libutil.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n\n\/\/ Set to 1 to manage the queue manager's life time from this program.\n\/\/ Set to 0 if the queue manager is started and stopped outside of\n\/\/ mailbench.\n#define START_QMAN 1\n\nusing std::string;\n\nenum { warmup_secs = 1 };\nenum { duration = 5 };\n\nconst char *message =\n \"Received: from incoming.csail.mit.edu (incoming.csail.mit.edu [128.30.2.16])\\n\"\n \" by metroplex (Cyrus v2.2.13-Debian-2.2.13-14+lenny5) with LMTPA;\\n\"\n \" Tue, 19 Mar 2013 22:45:50 -0400\\n\"\n \"X-Sieve: CMU Sieve 2.2\\n\"\n \"Received: from mailhub-auth-3.mit.edu ([18.9.21.43])\\n\"\n \" by incoming.csail.mit.edu with esmtps\\n\"\n \" (TLS1.0:DHE_RSA_AES_256_CBC_SHA1:32)\\n\"\n \" (Exim 4.72)\\n\"\n \" (envelope-from )\\n\"\n \" id 1UI92E-0007D2-7N\\n\"\n \" for xxxxxxxxx@csail.mit.edu; Tue, 19 Mar 2013 22:45:50 -0400\\n\"\n \"Received: from outgoing.mit.edu (OUTGOING-AUTH-1.MIT.EDU [18.9.28.11])\\n\"\n \" by mailhub-auth-3.mit.edu (8.13.8\/8.9.2) with ESMTP id r2K2jnO5025684\\n\"\n \" for ; Tue, 19 Mar 2013 22:45:49 -0400\\n\"\n \"Received: from xxxxxxxxx.csail.mit.edu (xxxxxxxxx.csail.mit.edu [18.26.4.91])\\n\"\n \" (authenticated bits=0)\\n\"\n \" (User authenticated as xxxxxxxx@ATHENA.MIT.EDU)\\n\"\n \" by outgoing.mit.edu (8.13.8\/8.12.4) with ESMTP id r2K2jmc7032022\\n\"\n \" (version=TLSv1\/SSLv3 cipher=DHE-RSA-AES128-SHA bits=128 verify=NOT)\\n\"\n \" for ; Tue, 19 Mar 2013 22:45:49 -0400\\n\"\n \"Received: from xxxxxxx by xxxxxxxxx.csail.mit.edu with local (Exim 4.80)\\n\"\n \" (envelope-from )\\n\"\n \" id 1UI92C-0000il-4L\\n\"\n \" for xxxxxxxx@mit.edu; Tue, 19 Mar 2013 22:45:48 -0400\\n\"\n \"From: Austin Clements \\n\"\n \"To: xxxxxxxx@mit.edu\\n\"\n \"Subject: Test message\\n\"\n \"User-Agent: Notmuch\/0.15+6~g7d4cb73 (http:\/\/notmuchmail.org) Emacs\/23.4.1\\n\"\n \" (i486-pc-linux-gnu)\\n\"\n \"Date: Tue, 19 Mar 2013 22:45:48 -0400\\n\"\n \"Message-ID: <874ng6vler.fsf@xxxxxxxxx.csail.mit.edu>\\n\"\n \"MIME-Version: 1.0\\n\"\n \"Content-Type: text\/plain; charset=us-ascii\\n\"\n \"\\n\"\n \"Hello.\\n\";\n\nextern char **environ;\n\nstatic spin_barrier bar;\n\nstatic concurrent_distribution start_tsc, stop_tsc;\nstatic concurrent_distribution start_usec, stop_usec;\nstatic concurrent_distribution count;\n\nstatic volatile bool stop __mpalign__;\nstatic volatile bool warmup;\nstatic __padout__ __attribute__((unused));\n\nstatic void\ntimer_thread(void)\n{\n warmup = true;\n bar.join();\n bar.join();\n sleep(warmup_secs);\n warmup = false;\n sleep(duration);\n stop = true;\n}\n\nstatic void\nxwaitpid(int pid, const char *cmd)\n{\n int status;\n if (waitpid(pid, &status, 0) < 0)\n edie(\"waitpid %s failed\", cmd);\n if (!WIFEXITED(status) || WEXITSTATUS(status))\n die(\"status %d from %s\", status, cmd);\n}\n\nstatic void\ndo_mua(int cpu, string spooldir, string msgpath)\n{\n const char *argv[] = {\".\/mail-enqueue\", spooldir.c_str(), \"user\", nullptr};\n#if defined(XV6_USER)\n int errno;\n#endif\n setaffinity(cpu);\n\n \/\/ Open message file (alternatively, we could use an open spawn\n \/\/ action)\n int msgfd = open(msgpath.c_str(), O_RDONLY|O_CLOEXEC);\n if (msgfd < 0)\n edie(\"open %s failed\", msgpath.c_str());\n\n bool mywarmup = true;\n uint64_t mycount = 0;\n while (!stop) {\n if (__builtin_expect(warmup != mywarmup, 0)) {\n mywarmup = warmup;\n mycount = 0;\n start_usec.add(now_usec());\n start_tsc.add(rdtsc());\n }\n\n pid_t pid;\n posix_spawn_file_actions_t actions;\n if ((errno = posix_spawn_file_actions_init(&actions)))\n edie(\"posix_spawn_file_actions_init failed\");\n if ((errno = posix_spawn_file_actions_adddup2(&actions, msgfd, 0)))\n edie(\"posix_spawn_file_actions_adddup2 failed\");\n if ((errno = posix_spawn(&pid, argv[0], &actions, nullptr,\n const_cast(argv), environ)))\n edie(\"posix_spawn failed\");\n if ((errno = posix_spawn_file_actions_destroy(&actions)))\n edie(\"posix_spawn_file_actions_destroy failed\");\n xwaitpid(pid, argv[0]);\n\n ++mycount;\n }\n\n stop_usec.add(now_usec());\n stop_tsc.add(rdtsc());\n count.add(mycount);\n}\n\nstatic void\nxmkdir(const string &d)\n{\n if (mkdir(d.c_str(), 0777) < 0)\n edie(\"failed to mkdir %s\", d.c_str());\n}\n\nstatic void\ncreate_spool(const string &base)\n{\n xmkdir(base);\n xmkdir(base + \"\/pid\");\n xmkdir(base + \"\/todo\");\n xmkdir(base + \"\/mess\");\n}\n\nstatic void\ncreate_maildir(const string &base)\n{\n xmkdir(base);\n xmkdir(base + \"\/tmp\");\n xmkdir(base + \"\/new\");\n xmkdir(base + \"\/cur\");\n}\n\nvoid\nusage(const char *argv0)\n{\n fprintf(stderr, \"Usage: %s basedir nthreads\\n\", argv0);\n exit(2);\n}\n\nint\nmain(int argc, char **argv)\n{\n if (argc != 3)\n usage(argv[0]);\n\n string basedir(argv[1]);\n const char *nthreads_str = argv[2];\n int nthreads = atoi(nthreads_str);\n if (nthreads <= 0)\n usage(argv[0]);\n\n \/\/ Create spool and inboxes\n \/\/ XXX This terminology is wrong. The spool is where mail\n \/\/ ultimately gets delivered to.\n string spooldir = basedir + \"\/spool\";\n if (START_QMAN)\n create_spool(spooldir);\n string mailroot = basedir + \"\/mail\";\n xmkdir(mailroot);\n create_maildir(mailroot + \"\/user\");\n\n pid_t qman_pid;\n if (START_QMAN) {\n \/\/ Start queue manager\n const char *qman[] = {\".\/mail-qman\", spooldir.c_str(), mailroot.c_str(),\n nthreads_str, nullptr};\n if (posix_spawn(&qman_pid, qman[0], nullptr, nullptr,\n const_cast(qman), environ) != 0)\n die(\"posix_spawn %s failed\", qman[0]);\n sleep(1);\n }\n\n \/\/ Write message to a file\n int fd = open((basedir + \"\/msg\").c_str(), O_CREAT|O_WRONLY, 0666);\n if (fd < 0)\n edie(\"open\");\n xwrite(fd, message, strlen(message));\n close(fd);\n\n printf(\"# --cores=%d --duration=%ds\\n\", nthreads, duration);\n\n \/\/ Run benchmark\n bar.init(nthreads + 1);\n\n std::thread timer(timer_thread);\n\n std::thread *threads = new std::thread[nthreads];\n for (int i = 0; i < nthreads; ++i)\n threads[i] = std::thread(do_mua, i, basedir + \"\/spool\", basedir + \"\/msg\");\n\n \/\/ Wait\n timer.join();\n for (int i = 0; i < nthreads; ++i)\n threads[i].join();\n\n if (START_QMAN) {\n \/\/ Kill qman and wait for it to exit\n const char *enq[] = {\".\/mail-enqueue\", \"--exit\", spooldir.c_str(), nullptr};\n pid_t enq_pid;\n if (posix_spawn(&enq_pid, enq[0], nullptr, nullptr,\n const_cast(enq), environ) != 0)\n die(\"posix_spawn %s failed\", enq[0]);\n xwaitpid(enq_pid, \"mail-enqueue --exit\");\n xwaitpid(qman_pid, \"mail-qman\");\n }\n\n \/\/ Summarize\n printf(\"%lu start usec skew\\n\", start_usec.span());\n printf(\"%lu stop usec skew\\n\", stop_usec.span());\n uint64_t usec = stop_usec.mean() - start_usec.mean();\n printf(\"%f secs\\n\", (double)usec \/ 1e6);\n printf(\"%lu cycles\\n\", stop_tsc.mean() - start_tsc.mean());\n\n uint64_t iters = count.sum();\n printf(\"%lu iters\\n\", iters);\n if (iters) {\n printf(\"%lu cycles\/iter\\n\", (stop_tsc.sum() - start_tsc.sum()) \/ iters);\n printf(\"%lu iters\/sec\\n\", iters * 1000000 \/ usec);\n }\n\n printf(\"\\n\");\n}\n<|endoftext|>"} {"text":"\/**\n * Copyright 2007-2013 IMP Inventors. All rights reserved.\n *\/\n\n#include \n#include \n#include \n#include \n\n#include \"RMF\/FileConstHandle.h\"\n#include \"RMF\/ID.h\"\n#include \"RMF\/info.h\"\n#include \"common.h\"\n\nnamespace {\nstd::string description(\"Print out information about categories and keys.\");\n\nunsigned int frame = 0;\n}\n\nint main(int argc, char** argv) {\n try {\n options.add_options()(\"frame,f\",\n boost::program_options::value(&frame),\n \"Frame to use\");\n RMF_ADD_INPUT_FILE(\"rmf\");\n process_options(argc, argv);\n\n RMF::FileConstHandle rh = RMF::open_rmf_file_read_only(input);\n if (!rh.get_description().empty()) {\n std::cout << \"description: \" << rh.get_description();\n }\n rh.set_current_frame(RMF::FrameID(frame));\n std::cout << \"frames: \" << rh.get_number_of_frames() << std::endl;\n RMF::show_info(rh, std::cout);\n return 0;\n }\n catch (const std::exception& e) {\n std::cerr << \"Error: \" << e.what() << std::endl;\n }\n}\nprint producer when set\/**\n * Copyright 2007-2013 IMP Inventors. All rights reserved.\n *\/\n\n#include \n#include \n#include \n#include \n\n#include \"RMF\/FileConstHandle.h\"\n#include \"RMF\/ID.h\"\n#include \"RMF\/info.h\"\n#include \"common.h\"\n\nnamespace {\nstd::string description(\"Print out information about categories and keys.\");\n\nunsigned int frame = 0;\n}\n\nint main(int argc, char** argv) {\n try {\n options.add_options()(\"frame,f\",\n boost::program_options::value(&frame),\n \"Frame to use\");\n RMF_ADD_INPUT_FILE(\"rmf\");\n process_options(argc, argv);\n\n RMF::FileConstHandle rh = RMF::open_rmf_file_read_only(input);\n if (!rh.get_description().empty()) {\n std::cout << \"description: \" << rh.get_description() << std::endl;\n }\n if (!rh.get_producer().empty()) {\n std::cout << \"producer: \" << rh.get_producer() << std::endl;\n }\n rh.set_current_frame(RMF::FrameID(frame));\n std::cout << \"frames: \" << rh.get_number_of_frames() << std::endl;\n RMF::show_info(rh, std::cout);\n return 0;\n }\n catch (const std::exception& e) {\n std::cerr << \"Error: \" << e.what() << std::endl;\n }\n}\n<|endoftext|>"} {"text":"\/\/ $Id: Pair6_12InteractionEnergyProcessor_test.C,v 1.4 2000\/10\/17 17:22:12 anker Exp $\n#include \n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/ insert includes here\n#include \n#include \n#include \n#include \n#include \n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nSTART_TEST(class_name, \"$Id: Pair6_12InteractionEnergyProcessor_test.C,v 1.4 2000\/10\/17 17:22:12 anker Exp $\")\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nusing namespace BALL;\nusing namespace std;\n\n\/\/\/ insert tests for each member function here \n\/\/\/\n\t\n\/\/ GROSSBAUSTELLE\n\nPair6_12InteractionEnergyProcessor* pointer;\n\nCHECK(Pair6_12InteractionEnergyProcessor::Pair6_12InteractionEnergyProcessor())\n\tpointer = new Pair6_12InteractionEnergyProcessor;\n\tTEST_NOT_EQUAL(pointer, 0)\nRESULT\n\nCHECK(Pair6_12InteractionEnergyProcessor::~Pair6_12InteractionEnergyProcessor())\n\tdelete pointer;\nRESULT\n\nCHECK(Pair6_12InteractionEnergyProcessor::Pair6_12InteractionEnergyProcessor(const Pair6_12InteractionEnergyProcessor& proc))\n\tPair6_12InteractionEnergyProcessor proc1;\n\tPair6_12InteractionEnergyProcessor proc2(proc1);\n\t\/\/ BAUSTELLE\nRESULT\n\nCHECK(Pair6_12InteractionEnergyProcessor::clear())\n\t\/\/ BAUSTELLE\nRESULT\n\nCHECK(Pair6_12InteractionEnergyProcessor::operator = (const Pair6_12InteractionEnergyProcessor& proc))\n\t\/\/ BAUSTELLE\nRESULT\n\nCHECK(Pair6_12InteractionEnergyProcessor::finish())\n\tPRECISION(0.0001)\n\tSystem S;\n\tHINFile f(\"data\/6_12-test.hin\");\n\tf >> S;\n\tf.close();\n\tINIFile ini(\"data\/6_12-test.rul\");\n\tini.read();\n\tRadiusRuleProcessor radius_rules;\n\tradius_rules.initialize(ini, \"RadiusRules\");\n\tS.apply(radius_rules);\n\n\tPair6_12InteractionEnergyProcessor proc;\n\tproc.options.readOptionFile(\"data\/6_12-test.options\");\n\n\tS.apply(proc);\n\tdouble val = proc.getEnergy();\n\tTEST_REAL_EQUAL(val, -6.027207050)\n\n\tproc.options.setBool(Pair6_12InteractionEnergyProcessor::Option::USE_RDF,\n\t\t\ttrue);\n\tS.apply(proc);\n\tval = proc.getEnergy();\n\tTEST_REAL_EQUAL(val, -6.027207050)\n\n\tproc.options.set(Pair6_12InteractionEnergyProcessor::Option::RDF_FILENAME,\n\t\"data\/6_12-test.rdf.ini\");\n\tS.apply(proc);\n\tval = proc.getEnergy();\n\tTEST_REAL_EQUAL(val, -6.027207050)\nRESULT\n\nCHECK(Pair6_12InteractionEnergyProcessor::isValid())\n\tPair6_12InteractionEnergyProcessor proc;\n\tTEST_EQUAL(proc.isValid(), false)\n\n\t\/\/ BAUSTELLE\nRESULT\n\nCHECK(Pair6_12InteractionEnergyProcessor::operator == ())\n \/\/ BAUSTELLE\nRESULT\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nEND_TEST\nfixed: RDF call with proper filename\/\/ $Id: Pair6_12InteractionEnergyProcessor_test.C,v 1.5 2000\/11\/14 19:13:06 anker Exp $\n#include \n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/ insert includes here\n#include \n#include \n#include \n#include \n#include \n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nSTART_TEST(class_name, \"$Id: Pair6_12InteractionEnergyProcessor_test.C,v 1.5 2000\/11\/14 19:13:06 anker Exp $\")\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nusing namespace BALL;\nusing namespace std;\n\n\/\/\/ insert tests for each member function here \n\/\/\/\n\t\n\/\/ GROSSBAUSTELLE\n\nPair6_12InteractionEnergyProcessor* pointer;\n\nCHECK(Pair6_12InteractionEnergyProcessor::Pair6_12InteractionEnergyProcessor())\n\tpointer = new Pair6_12InteractionEnergyProcessor;\n\tTEST_NOT_EQUAL(pointer, 0)\nRESULT\n\nCHECK(Pair6_12InteractionEnergyProcessor::~Pair6_12InteractionEnergyProcessor())\n\tdelete pointer;\nRESULT\n\nCHECK(Pair6_12InteractionEnergyProcessor::Pair6_12InteractionEnergyProcessor(const Pair6_12InteractionEnergyProcessor& proc))\n\tPair6_12InteractionEnergyProcessor proc1;\n\tPair6_12InteractionEnergyProcessor proc2(proc1);\n\t\/\/ BAUSTELLE\nRESULT\n\nCHECK(Pair6_12InteractionEnergyProcessor::clear())\n\t\/\/ BAUSTELLE\nRESULT\n\nCHECK(Pair6_12InteractionEnergyProcessor::operator = (const Pair6_12InteractionEnergyProcessor& proc))\n\t\/\/ BAUSTELLE\nRESULT\n\nCHECK(Pair6_12InteractionEnergyProcessor::finish())\n\tPRECISION(0.0001)\n\tSystem S;\n\tHINFile f(\"data\/6_12-test.hin\");\n\tf >> S;\n\tf.close();\n\tINIFile ini(\"data\/6_12-test.rul\");\n\tini.read();\n\tRadiusRuleProcessor radius_rules;\n\tradius_rules.initialize(ini, \"RadiusRules\");\n\tS.apply(radius_rules);\n\n\tPair6_12InteractionEnergyProcessor proc;\n\tproc.options.readOptionFile(\"data\/6_12-test.options\");\n\n\tS.apply(proc);\n\tdouble val = proc.getEnergy();\n\tTEST_REAL_EQUAL(val, -6.027207050)\n\n\tproc.options.set(Pair6_12InteractionEnergyProcessor::Option::RDF_FILENAME,\n\t\"data\/6_12-test.rdf-fake.ini\");\n\tproc.options.setBool(Pair6_12InteractionEnergyProcessor::Option::USE_RDF,\n\t\t\ttrue);\n\tS.apply(proc);\n\tval = proc.getEnergy();\n\tTEST_REAL_EQUAL(val, -6.027207050)\n\n\tproc.options.set(Pair6_12InteractionEnergyProcessor::Option::RDF_FILENAME,\n\t\"data\/6_12-test.rdf.ini\");\n\tS.apply(proc);\n\tval = proc.getEnergy();\n\tTEST_REAL_EQUAL(val, -6.027207050)\n\n\t\/\/ BAUSTELLE: USE_RDF=true geht trotz nicht gesetzten Dateinamens!!!\nRESULT\n\nCHECK(Pair6_12InteractionEnergyProcessor::isValid())\n\tPair6_12InteractionEnergyProcessor proc;\n\tTEST_EQUAL(proc.isValid(), false)\n\n\t\/\/ BAUSTELLE\nRESULT\n\nCHECK(Pair6_12InteractionEnergyProcessor::operator == ())\n \/\/ BAUSTELLE\nRESULT\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nEND_TEST\n<|endoftext|>"} {"text":"\/*\n * Distributed under the OSI-approved Apache License, Version 2.0. See\n * accompanying file Copyright.txt for details.\n *\n * BP3Zfp.tcc :\n *\n * Created on: Jul 18, 2018\n * Author: William F Godoy godoywf@ornl.gov\n *\/\n\n#ifndef ADIOS2_TOOLKIT_FORMAT_BP3_OPERATION_BP3ZFP_TCC_\n#define ADIOS2_TOOLKIT_FORMAT_BP3_OPERATION_BP3ZFP_TCC_\n\n#include \"BP3Zfp.h\"\n\n#include \"adios2\/helper\/adiosFunctions.h\"\n\nnamespace adios2\n{\nnamespace format\n{\n\ntemplate \nvoid BP3Zfp::SetDataCommon(\n const core::Variable &variable,\n const typename core::Variable::Info &blockInfo,\n const typename core::Variable::Operation &operation,\n BufferSTL &bufferSTL) const noexcept\n{\n const core::Operator &op = *operation.Op;\n const Params ¶meters = operation.Parameters;\n\n const size_t outputSize = op.Compress(\n blockInfo.Data, blockInfo.Count, variable.m_ElementSize,\n variable.m_Type, bufferSTL.m_Buffer.data() + bufferSTL.m_Position,\n parameters);\n\n \/\/ being naughty here\n Params &info = const_cast(operation.Info);\n info[\"OutputSize\"] = std::to_string(outputSize);\n\n bufferSTL.m_Position += outputSize;\n bufferSTL.m_AbsolutePosition += outputSize;\n}\n\ntemplate \nvoid BP3Zfp::SetMetadataCommon(\n const core::Variable &variable,\n const typename core::Variable::Info &blockInfo,\n const typename core::Variable::Operation &operation,\n std::vector &buffer) const noexcept\n{\n const uint64_t inputSize =\n helper::GetTotalSize(blockInfo.Count) * sizeof(T);\n \/\/ being naughty here\n Params &info = const_cast(operation.Info);\n info[\"InputSize\"] = std::to_string(inputSize);\n\n const uint64_t outputSize = 0; \/\/ not known yet\n\n auto itMode = operation.Parameters.find(\"accuracy\");\n int32_t mode = -1;\n\n if (itMode != operation.Parameters.end())\n {\n mode = static_cast(zfp_mode_accuracy);\n }\n else\n {\n itMode = operation.Parameters.find(\"precision\");\n if (itMode != operation.Parameters.end())\n {\n mode = static_cast(zfp_mode_precision);\n }\n itMode = operation.Parameters.find(\"rate\");\n if (itMode != operation.Parameters.end())\n {\n mode = static_cast(zfp_mode_rate);\n }\n }\n const std::string modeStr = itMode->second;\n\n \/\/ fixed size\n constexpr uint16_t metadataSize = 532;\n helper::InsertToBuffer(buffer, &metadataSize);\n helper::InsertToBuffer(buffer, &inputSize);\n \/\/ to be filled out after operation is applied on data\n info[\"OutputSizeMetadataPosition\"] = std::to_string(buffer.size());\n helper::InsertToBuffer(buffer, &outputSize);\n helper::InsertToBuffer(buffer, &mode);\n\n const size_t fixedRecordsPosition = buffer.size();\n buffer.resize(fixedRecordsPosition + 512, '\\0');\n size_t backPosition = fixedRecordsPosition;\n helper::CopyToBuffer(buffer, backPosition, modeStr.data(), modeStr.size());\n backPosition = fixedRecordsPosition + 256;\n helper::CopyToBuffer(buffer, backPosition, variable.m_Name.data(),\n variable.m_Name.size());\n}\n\ntemplate \nvoid BP3Zfp::UpdateMetadataCommon(\n const core::Variable &variable,\n const typename core::Variable::Info &blockInfo,\n const typename core::Variable::Operation &operation,\n std::vector &buffer) const noexcept\n{\n const uint64_t outputSize =\n static_cast(std::stoll(operation.Info.at(\"OutputSize\")));\n\n size_t backPosition = static_cast(\n std::stoll(operation.Info.at(\"OutputSizeMetadataPosition\")));\n\n helper::CopyToBuffer(buffer, backPosition, &outputSize);\n\n \/\/ being naughty here\n Params &info = const_cast(operation.Info);\n info.erase(\"OutputSizeMetadataPosition\");\n}\n\n} \/\/ end namespace format\n} \/\/ end namespace adios2\n\n#endif \/* ADIOS2_TOOLKIT_FORMAT_BP3_OPERATION_BP3ZFP_H_ *\/\nFixed crash when using ZFP compression under fixed-precision mode\/*\n * Distributed under the OSI-approved Apache License, Version 2.0. See\n * accompanying file Copyright.txt for details.\n *\n * BP3Zfp.tcc :\n *\n * Created on: Jul 18, 2018\n * Author: William F Godoy godoywf@ornl.gov\n *\/\n\n#ifndef ADIOS2_TOOLKIT_FORMAT_BP3_OPERATION_BP3ZFP_TCC_\n#define ADIOS2_TOOLKIT_FORMAT_BP3_OPERATION_BP3ZFP_TCC_\n\n#include \"BP3Zfp.h\"\n\n#include \"adios2\/helper\/adiosFunctions.h\"\n\nnamespace adios2\n{\nnamespace format\n{\n\ntemplate \nvoid BP3Zfp::SetDataCommon(\n const core::Variable &variable,\n const typename core::Variable::Info &blockInfo,\n const typename core::Variable::Operation &operation,\n BufferSTL &bufferSTL) const noexcept\n{\n const core::Operator &op = *operation.Op;\n const Params ¶meters = operation.Parameters;\n\n const size_t outputSize = op.Compress(\n blockInfo.Data, blockInfo.Count, variable.m_ElementSize,\n variable.m_Type, bufferSTL.m_Buffer.data() + bufferSTL.m_Position,\n parameters);\n\n \/\/ being naughty here\n Params &info = const_cast(operation.Info);\n info[\"OutputSize\"] = std::to_string(outputSize);\n\n bufferSTL.m_Position += outputSize;\n bufferSTL.m_AbsolutePosition += outputSize;\n}\n\ntemplate \nvoid BP3Zfp::SetMetadataCommon(\n const core::Variable &variable,\n const typename core::Variable::Info &blockInfo,\n const typename core::Variable::Operation &operation,\n std::vector &buffer) const noexcept\n{\n const uint64_t inputSize =\n helper::GetTotalSize(blockInfo.Count) * sizeof(T);\n \/\/ being naughty here\n Params &info = const_cast(operation.Info);\n info[\"InputSize\"] = std::to_string(inputSize);\n\n const uint64_t outputSize = 0; \/\/ not known yet\n\n auto itMode = operation.Parameters.find(\"accuracy\");\n int32_t mode = -1;\n\n if (itMode != operation.Parameters.end())\n {\n mode = static_cast(zfp_mode_accuracy);\n }\n else\n {\n itMode = operation.Parameters.find(\"precision\");\n if (itMode != operation.Parameters.end())\n {\n mode = static_cast(zfp_mode_precision);\n }\n else\n {\n itMode = operation.Parameters.find(\"rate\");\n if (itMode != operation.Parameters.end())\n {\n mode = static_cast(zfp_mode_rate);\n }\n }\n }\n const std::string modeStr = itMode->second;\n\n \/\/ fixed size\n constexpr uint16_t metadataSize = 532;\n helper::InsertToBuffer(buffer, &metadataSize);\n helper::InsertToBuffer(buffer, &inputSize);\n \/\/ to be filled out after operation is applied on data\n info[\"OutputSizeMetadataPosition\"] = std::to_string(buffer.size());\n helper::InsertToBuffer(buffer, &outputSize);\n helper::InsertToBuffer(buffer, &mode);\n\n const size_t fixedRecordsPosition = buffer.size();\n buffer.resize(fixedRecordsPosition + 512, '\\0');\n size_t backPosition = fixedRecordsPosition;\n helper::CopyToBuffer(buffer, backPosition, modeStr.data(), modeStr.size());\n backPosition = fixedRecordsPosition + 256;\n helper::CopyToBuffer(buffer, backPosition, variable.m_Name.data(),\n variable.m_Name.size());\n}\n\ntemplate \nvoid BP3Zfp::UpdateMetadataCommon(\n const core::Variable &variable,\n const typename core::Variable::Info &blockInfo,\n const typename core::Variable::Operation &operation,\n std::vector &buffer) const noexcept\n{\n const uint64_t outputSize =\n static_cast(std::stoll(operation.Info.at(\"OutputSize\")));\n\n size_t backPosition = static_cast(\n std::stoll(operation.Info.at(\"OutputSizeMetadataPosition\")));\n\n helper::CopyToBuffer(buffer, backPosition, &outputSize);\n\n \/\/ being naughty here\n Params &info = const_cast(operation.Info);\n info.erase(\"OutputSizeMetadataPosition\");\n}\n\n} \/\/ end namespace format\n} \/\/ end namespace adios2\n\n#endif \/* ADIOS2_TOOLKIT_FORMAT_BP3_OPERATION_BP3ZFP_H_ *\/\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"truncater.hpp\"\n\ntypedef std::vector> matrix_type;\nstruct evaluate_set_type\n{\n matrix_type matrix;\n point_type position;\/\/場所\n point_type content;\n int score;\n std::string direct;\n};\n\n\/\/ class definition {{{1\nclass truncater::impl : boost::noncopyable\n{\npublic:\n typedef truncater::return_type return_type;\n\n impl() = default;\n virtual ~impl() = default;\n\n auto get() -> boost::optional;\n void reset(question_data const& data);\n\nprivate:\n void process(boost::coroutines::coroutine::push_type& yield);\n void operator() (boost::coroutines::coroutine::push_type& yield);\n\n boost::optional data_;\n boost::coroutines::coroutine::pull_type co_;\n\n void ymove();\n int form_evaluate(matrix_type const& mat);\n point_type get_start_point(matrix_type const& mat);\n int eval_two_piece(evaluate_set_type const& eval_set, point_type const& new_position);\n evaluate_set_type try_u(evaluate_set_type return_set);\n evaluate_set_type try_r(evaluate_set_type return_set);\n evaluate_set_type try_d(evaluate_set_type return_set);\n evaluate_set_type try_l(evaluate_set_type return_set);\n\n matrix_type matrix;\n answer_type answer;\n int width;\n int height;\n int selectable;\n};\n\n\/\/ interfaces for Boost.Coroutine {{{1\ntruncater::truncater()\n : pimpl_(new impl())\n{\n}\n\ntruncater::~truncater()\n{\n delete pimpl_;\n}\n\nauto truncater::get() -> boost::optional\n{\n return pimpl_->get();\n}\n\nvoid truncater::reset(question_data const& data)\n{\n pimpl_->reset(data);\n}\n\nauto truncater::impl::get() -> boost::optional\n{\n if(co_ && data_)\n {\n auto&& result = co_.get();\n co_();\n return result;\n }\n return boost::none;\n}\n\nvoid truncater::impl::reset(question_data const& data)\n{\n data_ = data.clone();\n co_ = boost::coroutines::coroutine::pull_type(\n boost::bind(&impl::process, this, _1)\n );\n}\n\nvoid truncater::impl::process(boost::coroutines::coroutine::push_type& yield)\n{\n \/\/ 訳ありで転送するだけの関数\n (*this)(yield);\n}\n\n\/\/ yoshikawa {{{1\nint truncater::impl::form_evaluate(matrix_type const& mat)\n{\n int s = 0;\n for (int i = 0; i < mat.size(); ++i)\n {\n for (int j = 0; j < mat.at(0).size(); ++j)\n {\n s += mat[i][j].manhattan_pow({ j, i });\n }\n }\n return s;\n}\n\npoint_type truncater::impl::get_start_point(matrix_type const& mat)\n{\n int max_val = 0;\n point_type max_point;\/\/実態\n point_type position;\n\n for (int i = 0; i < mat.size(); ++i)\n {\n for (int j = 0; j < mat.at(0).size(); ++j)\n {\n int temp = mat[i][j].manhattan_pow({ j, i });\n if (temp > max_val)\n {\n max_val = temp;\n max_point = point_type{ j, i };\n position = point_type{ mat[i][j].x, mat[i][j].y };\n }\n }\n }\n return position;\n}\n\nint truncater::impl::eval_two_piece(evaluate_set_type const& eval_set, point_type const& new_position)\n{\n int s = 0;\n point_type const& content_a = eval_set.matrix[eval_set.position.y][eval_set.position.x];\n \/\/aの新しい場所からの距離\n s += content_a.manhattan_pow(new_position);\n \/\/aの古い場所からの距離\n s -= content_a.manhattan_pow(eval_set.position);\n point_type const& content_b = eval_set.matrix[new_position.y][new_position.x];\n \/\/bの新しい場所からの距離\n s += content_b.manhattan_pow(eval_set.position);\n \/\/bの古い場所からの距離\n s -= content_b.manhattan_pow(new_position);\n\n \/\/assert(s == -2 || s == 0 || s == 2);\n return s;\n}\n\n\nevaluate_set_type truncater::impl::try_u(evaluate_set_type return_set)\n{\n point_type const& new_position = { return_set.position.x, return_set.position.y - 1 };\n return_set.score += eval_two_piece(return_set, new_position);\n std::swap(return_set.matrix[return_set.position.y][return_set.position.x], return_set.matrix[new_position.y][new_position.x]);\n return_set.direct += \"U\";\n return_set.position = new_position;\n return std::move(return_set);\n}\n\nevaluate_set_type truncater::impl::try_r(evaluate_set_type return_set)\n{\n point_type const& new_position = { return_set.position.x + 1, return_set.position.y };\n return_set.score += eval_two_piece(return_set, new_position);\n std::swap(return_set.matrix[return_set.position.y][return_set.position.x], return_set.matrix[new_position.y][new_position.x]);\n return_set.direct += \"R\";\n return_set.position = new_position;\n return std::move(return_set);\n}\n\nevaluate_set_type truncater::impl::try_d(evaluate_set_type return_set)\n{\n point_type const& new_position = { return_set.position.x, return_set.position.y + 1 };\n return_set.score += eval_two_piece(return_set, new_position);\n std::swap(return_set.matrix[return_set.position.y][return_set.position.x], return_set.matrix[new_position.y][new_position.x]);\n return_set.direct += \"D\";\n return_set.position = new_position;\n return std::move(return_set);\n}\n\nevaluate_set_type truncater::impl::try_l(evaluate_set_type return_set)\n{\n point_type const& new_position = { return_set.position.x - 1, return_set.position.y };\n return_set.score += eval_two_piece(return_set, new_position);\n std::swap(return_set.matrix[return_set.position.y][return_set.position.x], return_set.matrix[new_position.y][new_position.x]);\n return_set.direct += \"L\";\n return_set.position = new_position;\n return std::move(return_set);\n}\n\nvoid truncater::impl::ymove()\n{\n std::cout << \"ymove start\" << std::endl;\n\n int const width = matrix.at(0).size();\n int const height = matrix.size();\n\n std::queue que;\n std::vector children;\n children.reserve(900);\n\n point_type const start_position = get_start_point(matrix);\n evaluate_set_type start = evaluate_set_type{ matrix, start_position, matrix[start_position.y][start_position.x], form_evaluate(start.matrix), \" \" };\n evaluate_set_type best = start;\n \n que.push(start);\n\n \/\/std::cout << \"select piece position = \" << start.position << std::endl;\n \/\/std::cout << \"select piece content = \" << start.content << std::endl;\n \n auto P = [](int e, int ne, double T) {\n if( ne < e ) {\n return 1.0;\n } else {\n return std::exp((e - ne)\/T);\n }\n };\n double T = 1000.0;\n \n std::random_device sec_rng;\n std::mt19937 mt(sec_rng());\n std::uniform_real_distribution prob_dist(0.0, 1.0);\n auto prob = [&]{return prob_dist(mt);};\n \n auto is_transition = [&](int s, int ns) {\n return prob() < P(s, ns, T);\n };\n\n while (que.size() > 0 && T > 1.0)\n {\n \/\/std::cout << \"T = \" << T << \", score = \" << best.score << \" que size = \" << que.size() << std::endl;\n while (que.size() > 0)\n {\n auto const node = que.front();\n que.pop();\n\n if (best.score > node.score) best = node;\n\n if (node.position.y != 0 && node.direct.back() != 'D')\n {\n auto child = try_u(node);\n \/\/if (child.score <= node.score)\n if (is_transition(node.score, child.score))\n {\n children.push_back(std::move(child));\n }\n }\n if (node.position.x != width - 1 && node.direct.back() != 'L')\n {\n auto child = try_r(node);\n \/\/if (child.score <= node.score)\n if (is_transition(node.score, child.score))\n {\n children.push_back(std::move(child));\n }\n }\n if (node.position.y != height - 1 && node.direct.back() != 'U')\n {\n auto child = try_d(node);\n \/\/if (child.score <= node.score)\n if (is_transition(node.score, child.score))\n {\n children.push_back(std::move(child));\n }\n }\n if (node.position.x != 0 && node.direct.back() != 'R')\n {\n auto child = try_l(node);\n \/\/if (child.score <= node.score)\n if (is_transition(node.score, child.score))\n {\n children.push_back(std::move(child));\n }\n }\n }\n \n std::sort(children.begin(), children.end(), [](evaluate_set_type a, evaluate_set_type b){return a.score < b.score; });\n\n for (int i = 0; i < children.size() && i < 100; ++i)\n {\n que.push(children.at(i));\n }\n \n children.clear();\n \n T *= 0.95;\n }\n\n matrix = best.matrix;\n answer.list.push_back({ start_position, best.direct.substr(1) });\n\n std::cout << \"ymove done.\" << std::endl;\n}\n\n\/\/ operator() {{{1\nvoid truncater::impl::operator() (boost::coroutines::coroutine::push_type& yield)\n{\n algorithm algo;\n matrix = data_->block;\n width = data_->size.first;\n height = data_->size.second;\n selectable = data_->selectable;\n\n if ((width > 3 || height > 3) && selectable >= 3) ymove();\n\n auto qdata = question_data(\n data_->problem_id,\n data_->player_id,\n data_->size,\n data_->selectable,\n data_->cost_change,\n data_->cost_change,\n std::move(matrix)\n );\n algo.reset(std::move(qdata));\n answer_type subsequent_answer = *algo.get();\n std::copy(subsequent_answer.list.begin(), subsequent_answer.list.end(), std::back_inserter(answer.list));\n yield(std::move(answer));\n}\nUpdate truncater.cpp#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"truncater.hpp\"\n\ntypedef std::vector> matrix_type;\nstruct evaluate_set_type\n{\n matrix_type matrix;\n point_type position;\/\/場所\n point_type content;\n int score;\n std::string direct;\n};\n\n\/\/ class definition {{{1\nclass truncater::impl : boost::noncopyable\n{\npublic:\n typedef truncater::return_type return_type;\n\n impl() = default;\n virtual ~impl() = default;\n\n auto get() -> boost::optional;\n void reset(question_data const& data);\n\nprivate:\n void process(boost::coroutines::coroutine::push_type& yield);\n void operator() (boost::coroutines::coroutine::push_type& yield);\n\n boost::optional data_;\n boost::coroutines::coroutine::pull_type co_;\n\n void ymove();\n int form_evaluate(matrix_type const& mat);\n point_type get_start_point(matrix_type const& mat);\n int eval_two_piece(evaluate_set_type const& eval_set, point_type const& new_position);\n evaluate_set_type try_u(evaluate_set_type return_set);\n evaluate_set_type try_r(evaluate_set_type return_set);\n evaluate_set_type try_d(evaluate_set_type return_set);\n evaluate_set_type try_l(evaluate_set_type return_set);\n\n matrix_type matrix;\n answer_type answer;\n int width;\n int height;\n int selectable;\n};\n\n\/\/ interfaces for Boost.Coroutine {{{1\ntruncater::truncater()\n : pimpl_(new impl())\n{\n}\n\ntruncater::~truncater()\n{\n delete pimpl_;\n}\n\nauto truncater::get() -> boost::optional\n{\n return pimpl_->get();\n}\n\nvoid truncater::reset(question_data const& data)\n{\n pimpl_->reset(data);\n}\n\nauto truncater::impl::get() -> boost::optional\n{\n if(co_ && data_)\n {\n auto&& result = co_.get();\n co_();\n return result;\n }\n return boost::none;\n}\n\nvoid truncater::impl::reset(question_data const& data)\n{\n data_ = data.clone();\n co_ = boost::coroutines::coroutine::pull_type(\n boost::bind(&impl::process, this, _1)\n );\n}\n\nvoid truncater::impl::process(boost::coroutines::coroutine::push_type& yield)\n{\n \/\/ 訳ありで転送するだけの関数\n (*this)(yield);\n}\n\n\/\/ yoshikawa {{{1\nint truncater::impl::form_evaluate(matrix_type const& mat)\n{\n int s = 0;\n for (int i = 0; i < mat.size(); ++i)\n {\n for (int j = 0; j < mat.at(0).size(); ++j)\n {\n s += mat[i][j].manhattan_pow({ j, i });\n }\n }\n return s;\n}\n\npoint_type truncater::impl::get_start_point(matrix_type const& mat)\n{\n int max_val = 0;\n point_type max_point;\/\/実態\n point_type position;\n\n for (int i = 0; i < mat.size(); ++i)\n {\n for (int j = 0; j < mat.at(0).size(); ++j)\n {\n int temp = mat[i][j].manhattan_pow({ j, i });\n if (temp > max_val)\n {\n max_val = temp;\n max_point = point_type{ j, i };\n position = point_type{ mat[i][j].x, mat[i][j].y };\n }\n }\n }\n return position;\n}\n\nint truncater::impl::eval_two_piece(evaluate_set_type const& eval_set, point_type const& new_position)\n{\n int s = 0;\n point_type const& content_a = eval_set.matrix[eval_set.position.y][eval_set.position.x];\n \/\/aの新しい場所からの距離\n s += content_a.manhattan_pow(new_position);\n \/\/aの古い場所からの距離\n s -= content_a.manhattan_pow(eval_set.position);\n point_type const& content_b = eval_set.matrix[new_position.y][new_position.x];\n \/\/bの新しい場所からの距離\n s += content_b.manhattan_pow(eval_set.position);\n \/\/bの古い場所からの距離\n s -= content_b.manhattan_pow(new_position);\n\n \/\/assert(s == -2 || s == 0 || s == 2);\n return s;\n}\n\n\nevaluate_set_type truncater::impl::try_u(evaluate_set_type return_set)\n{\n point_type const& new_position = { return_set.position.x, return_set.position.y - 1 };\n return_set.score += eval_two_piece(return_set, new_position);\n std::swap(return_set.matrix[return_set.position.y][return_set.position.x], return_set.matrix[new_position.y][new_position.x]);\n return_set.direct += \"U\";\n return_set.position = new_position;\n return std::move(return_set);\n}\n\nevaluate_set_type truncater::impl::try_r(evaluate_set_type return_set)\n{\n point_type const& new_position = { return_set.position.x + 1, return_set.position.y };\n return_set.score += eval_two_piece(return_set, new_position);\n std::swap(return_set.matrix[return_set.position.y][return_set.position.x], return_set.matrix[new_position.y][new_position.x]);\n return_set.direct += \"R\";\n return_set.position = new_position;\n return std::move(return_set);\n}\n\nevaluate_set_type truncater::impl::try_d(evaluate_set_type return_set)\n{\n point_type const& new_position = { return_set.position.x, return_set.position.y + 1 };\n return_set.score += eval_two_piece(return_set, new_position);\n std::swap(return_set.matrix[return_set.position.y][return_set.position.x], return_set.matrix[new_position.y][new_position.x]);\n return_set.direct += \"D\";\n return_set.position = new_position;\n return std::move(return_set);\n}\n\nevaluate_set_type truncater::impl::try_l(evaluate_set_type return_set)\n{\n point_type const& new_position = { return_set.position.x - 1, return_set.position.y };\n return_set.score += eval_two_piece(return_set, new_position);\n std::swap(return_set.matrix[return_set.position.y][return_set.position.x], return_set.matrix[new_position.y][new_position.x]);\n return_set.direct += \"L\";\n return_set.position = new_position;\n return std::move(return_set);\n}\n\nvoid truncater::impl::ymove()\n{\n std::cout << \"ymove start\" << std::endl;\n\n int const width = matrix.at(0).size();\n int const height = matrix.size();\n\n std::queue que;\n std::vector children;\n children.reserve(900);\n\n point_type const start_position = get_start_point(matrix);\n evaluate_set_type start = evaluate_set_type{ matrix, start_position, matrix[start_position.y][start_position.x], form_evaluate(start.matrix), \" \" };\n evaluate_set_type best = start;\n \n que.push(start);\n\n \/\/std::cout << \"select piece position = \" << start.position << std::endl;\n \/\/std::cout << \"select piece content = \" << start.content << std::endl;\n \n auto P = [](int e, int ne, double T) {\n if( ne < e ) {\n return 1.0;\n } else {\n return std::exp((e - ne)\/T);\n }\n };\n double T = 1000.0;\n \n std::random_device sec_rng;\n std::mt19937 mt(sec_rng());\n std::uniform_real_distribution prob_dist(0.0, 1.0);\n auto prob = [&]{return prob_dist(mt);};\n \n auto is_transition = [&](int s, int ns) {\n return prob() < P(s, ns, T);\n };\n\n while (que.size() > 0 && T > 1.0)\n {\n \/\/std::cout << \"T = \" << T << \", score = \" << best.score << \" que size = \" << que.size() << std::endl;\n while (que.size() > 0)\n {\n auto const node = que.front();\n que.pop();\n\n if (best.score > node.score) best = node;\n\n if (node.position.y != 0 && node.direct.back() != 'D')\n {\n auto child = try_u(node);\n \/\/if (child.score <= node.score)\n if (is_transition(node.score, child.score))\n {\n children.push_back(std::move(child));\n }\n }\n if (node.position.x != width - 1 && node.direct.back() != 'L')\n {\n auto child = try_r(node);\n \/\/if (child.score <= node.score)\n if (is_transition(node.score, child.score))\n {\n children.push_back(std::move(child));\n }\n }\n if (node.position.y != height - 1 && node.direct.back() != 'U')\n {\n auto child = try_d(node);\n \/\/if (child.score <= node.score)\n if (is_transition(node.score, child.score))\n {\n children.push_back(std::move(child));\n }\n }\n if (node.position.x != 0 && node.direct.back() != 'R')\n {\n auto child = try_l(node);\n \/\/if (child.score <= node.score)\n if (is_transition(node.score, child.score))\n {\n children.push_back(std::move(child));\n }\n }\n }\n \n std::sort(children.begin(), children.end(), [](evaluate_set_type a, evaluate_set_type b){return a.score < b.score; });\n\n for (int i = 0; i < children.size() && i < 100; ++i)\n {\n que.push(children.at(i));\n }\n \n children.clear();\n \n T *= 0.95;\n }\n\n matrix = best.matrix;\n answer.list.push_back({ start_position, best.direct.substr(1) });\n\n std::cout << \"ymove done.\" << std::endl;\n}\n\n\/\/ operator() {{{1\nvoid truncater::impl::operator() (boost::coroutines::coroutine::push_type& yield)\n{\n algorithm algo;\n matrix = data_->block;\n width = data_->size.first;\n height = data_->size.second;\n selectable = data_->selectable;\n\n if ((width > 3 || height > 3) && selectable >= 3) ymove();\n\n auto qdata = question_data(\n data_->problem_id,\n data_->player_id,\n data_->size,\n data_->selectable,\n data_->cost_select,\n data_->cost_change,\n std::move(matrix)\n );\n algo.reset(std::move(qdata));\n answer_type subsequent_answer = *algo.get();\n std::copy(subsequent_answer.list.begin(), subsequent_answer.list.end(), std::back_inserter(answer.list));\n yield(std::move(answer));\n}\n<|endoftext|>"} {"text":"\/*\n * Copyright (c) 2013 The WebRTC project authors. All Rights Reserved.\n *\n * Use of this source code is governed by a BSD-style license\n * that can be found in the LICENSE file in the root of the source\n * tree. An additional intellectual property rights grant can be found\n * in the file PATENTS. All contributing project authors may\n * be found in the AUTHORS file in the root of the source tree.\n *\/\n\n#include \n\n#include \"absl\/debugging\/failure_signal_handler.h\"\n#include \"absl\/debugging\/symbolize.h\"\n#include \"test\/test_main_lib.h\"\n\nint main(int argc, char* argv[]) {\n \/\/ Initialize the symbolizer to get a human-readable stack trace\n \/\/ TODO(crbug.com\/1050976): Breaks iossim tests, re-enable when fixed.\n \/\/ absl::InitializeSymbolizer(argv[0]);\n\n \/\/ absl::FailureSignalHandlerOptions options;\n \/\/ absl::InstallFailureSignalHandler(options);\n\n std::unique_ptr main = webrtc::TestMain::Create();\n int err_code = main->Init(&argc, argv);\n if (err_code != 0) {\n return err_code;\n }\n return main->Run(argc, argv);\n}\nRe-enable absl FailureSignalHandler in tests.\/*\n * Copyright (c) 2013 The WebRTC project authors. All Rights Reserved.\n *\n * Use of this source code is governed by a BSD-style license\n * that can be found in the LICENSE file in the root of the source\n * tree. An additional intellectual property rights grant can be found\n * in the file PATENTS. All contributing project authors may\n * be found in the AUTHORS file in the root of the source tree.\n *\/\n\n#include \n\n#include \"absl\/debugging\/failure_signal_handler.h\"\n#include \"absl\/debugging\/symbolize.h\"\n#include \"test\/test_main_lib.h\"\n\nint main(int argc, char* argv[]) {\n \/\/ Initialize the symbolizer to get a human-readable stack trace\n absl::InitializeSymbolizer(argv[0]);\n\n absl::FailureSignalHandlerOptions options;\n absl::InstallFailureSignalHandler(options);\n\n std::unique_ptr main = webrtc::TestMain::Create();\n int err_code = main->Init(&argc, argv);\n if (err_code != 0) {\n return err_code;\n }\n return main->Run(argc, argv);\n}\n<|endoftext|>"} {"text":"#pragma once\n\n#include \n\n\/* XXX: Comment out this line for a non-test network *\/\n\/\/#define BTS_TEST_NETWORK\n\n#define BTS_TEST_NETWORK_VERSION 83 \/\/ autogenerated\n\n#define BTS_BLOCKCHAIN_DATABASE_VERSION uint64_t( 199 )\n\n#define BTS_ADDRESS_PREFIX \"BTS\"\n#define BTS_BLOCKCHAIN_SYMBOL \"BTS\"\n#define BTS_BLOCKCHAIN_NAME \"BitShares\"\n#define BTS_BLOCKCHAIN_DESCRIPTION \"Decentralized Exchange\"\n#define BTS_BLOCKCHAIN_PRECISION 100000\n\n#define BTS_BLOCKCHAIN_MAX_UIA_MARKET_FEE 10000\n#define BTS_BLOCKCHAIN_BLOCK_INTERVAL_SEC int64_t(10)\n#define BTS_BLOCKCHAIN_BLOCKS_PER_HOUR ((60*60)\/BTS_BLOCKCHAIN_BLOCK_INTERVAL_SEC)\n#define BTS_BLOCKCHAIN_BLOCKS_PER_DAY (BTS_BLOCKCHAIN_BLOCKS_PER_HOUR*int64_t(24))\n#define BTS_BLOCKCHAIN_BLOCKS_PER_YEAR (BTS_BLOCKCHAIN_BLOCKS_PER_DAY*int64_t(365))\n\n#define BTS_BLOCKCHAIN_NUM_DELEGATES uint32_t(101)\n#define BTS_MAX_DELEGATE_PAY_PER_BLOCK int64_t( 50 * BTS_BLOCKCHAIN_PRECISION ) \/\/ 50 XTS\n#define BTS_BLOCKCHAIN_MAX_UNDO_HISTORY BTS_BLOCKCHAIN_BLOCKS_PER_HOUR\n\n#define BTS_BLOCKCHAIN_MAX_SLATE_SIZE (BTS_BLOCKCHAIN_NUM_DELEGATES + (BTS_BLOCKCHAIN_NUM_DELEGATES\/10))\n#define BTS_BLOCKCHAIN_MAX_TRANSACTION_EXPIRATION_SEC (60*60*24*2)\n#define BTS_BLOCKCHAIN_MAX_MEMO_SIZE 19 \/\/ bytes\n#define BTS_BLOCKCHAIN_EXTENDED_MEMO_SIZE 32 \/\/ bytes\n#define BTS_BLOCKCHAIN_MAX_EXTENDED_MEMO_SIZE (BTS_BLOCKCHAIN_MAX_MEMO_SIZE + BTS_BLOCKCHAIN_EXTENDED_MEMO_SIZE)\n\n\/**\n * The maximum amount that can be issued for user assets.\n *\n * 10^18 \/ 2^63 < 1 however, to support representing all share values as a double in\n * languages like java script, we must stay within the epsilon so\n *\n * 10^15 \/ 2^53 < 1 allows all values to be represented as a double or an int64\n *\/\n#define BTS_BLOCKCHAIN_MAX_SHARES (1000*1000*int64_t(1000)*1000*int64_t(1000))\n\n#define BTS_BLOCKCHAIN_MIN_NAME_SIZE 1\n#define BTS_BLOCKCHAIN_MAX_NAME_SIZE 63\n#define BTS_BLOCKCHAIN_MAX_NAME_DATA_SIZE (1024*64)\n\n#define BTS_BLOCKCHAIN_MAX_SUB_SYMBOL_SIZE 8 \/\/ characters\n#define BTS_BLOCKCHAIN_MIN_SYMBOL_SIZE 3 \/\/ characters\n#define BTS_BLOCKCHAIN_MAX_SYMBOL_SIZE 12 \/\/ characters\n\n#define BTS_BLOCKCHAIN_MIN_BURN_FEE BTS_BLOCKCHAIN_PRECISION * 1 \/\/ 1 XTS\n\n#ifdef BTS_TEST_NETWORK\n#define BTS_BLOCKCHAIN_VOTE_UPDATE_PERIOD_SEC 10\n#else\n#define BTS_BLOCKCHAIN_VOTE_UPDATE_PERIOD_SEC (60*60) \/\/ 1 hour\n#endif\n\n#define BTS_BLOCKCHAIN_MIN_FEEDS ((BTS_BLOCKCHAIN_NUM_DELEGATES\/2) + 1)\n#define BTS_BLOCKCHAIN_MINIMUM_SHORT_ORDER_SIZE (BTS_BLOCKCHAIN_PRECISION*100)\n#define BTS_BLOCKCHAIN_MIN_YIELD_PERIOD_SEC (60*60*24) \/\/ 24 hours\n#define BTS_BLOCKCHAIN_MAX_YIELD_PERIOD_SEC (BTS_BLOCKCHAIN_BLOCKS_PER_YEAR * BTS_BLOCKCHAIN_BLOCK_INTERVAL_SEC) \/\/ 1 year\n\n#ifdef BTS_TEST_NETWORK\n#define BTS_BLOCKCHAIN_MAX_SHORT_PERIOD_SEC (2*60*60) \/\/ 2 hours\n#else\n#define BTS_BLOCKCHAIN_MAX_SHORT_PERIOD_SEC (30*24*60*60) \/\/ 1 month\n#endif\n#define BTS_BLOCKCHAIN_MAX_SHORT_APR_PCT (uint64_t(1000))\n\n#define BTS_BLOCKCHAIN_MCALL_D2C_NUMERATOR 1\n#define BTS_BLOCKCHAIN_MCALL_D2C_DENOMINATOR 2\n\n\/\/ TODO: This stuff only matters for propagation throttling; should go somewhere else\n#define BTS_BLOCKCHAIN_DEFAULT_RELAY_FEE 10000 \/\/ XTS\n#define BTS_BLOCKCHAIN_MAX_TRX_PER_SECOND 1 \/\/ (10)\n#define BTS_BLOCKCHAIN_MAX_PENDING_QUEUE_SIZE 10 \/\/ (BTS_BLOCKCHAIN_MAX_TRX_PER_SECOND * BTS_BLOCKCHAIN_BLOCK_INTERVAL_SEC)\nchanging max APR to 50%#pragma once\n\n#include \n\n\/* XXX: Comment out this line for a non-test network *\/\n\/\/#define BTS_TEST_NETWORK\n\n#define BTS_TEST_NETWORK_VERSION 83 \/\/ autogenerated\n\n#define BTS_BLOCKCHAIN_DATABASE_VERSION uint64_t( 199 )\n\n#define BTS_ADDRESS_PREFIX \"BTS\"\n#define BTS_BLOCKCHAIN_SYMBOL \"BTS\"\n#define BTS_BLOCKCHAIN_NAME \"BitShares\"\n#define BTS_BLOCKCHAIN_DESCRIPTION \"Decentralized Exchange\"\n#define BTS_BLOCKCHAIN_PRECISION 100000\n\n#define BTS_BLOCKCHAIN_MAX_UIA_MARKET_FEE 10000\n#define BTS_BLOCKCHAIN_BLOCK_INTERVAL_SEC int64_t(10)\n#define BTS_BLOCKCHAIN_BLOCKS_PER_HOUR ((60*60)\/BTS_BLOCKCHAIN_BLOCK_INTERVAL_SEC)\n#define BTS_BLOCKCHAIN_BLOCKS_PER_DAY (BTS_BLOCKCHAIN_BLOCKS_PER_HOUR*int64_t(24))\n#define BTS_BLOCKCHAIN_BLOCKS_PER_YEAR (BTS_BLOCKCHAIN_BLOCKS_PER_DAY*int64_t(365))\n\n#define BTS_BLOCKCHAIN_NUM_DELEGATES uint32_t(101)\n#define BTS_MAX_DELEGATE_PAY_PER_BLOCK int64_t( 50 * BTS_BLOCKCHAIN_PRECISION ) \/\/ 50 XTS\n#define BTS_BLOCKCHAIN_MAX_UNDO_HISTORY BTS_BLOCKCHAIN_BLOCKS_PER_HOUR\n\n#define BTS_BLOCKCHAIN_MAX_SLATE_SIZE (BTS_BLOCKCHAIN_NUM_DELEGATES + (BTS_BLOCKCHAIN_NUM_DELEGATES\/10))\n#define BTS_BLOCKCHAIN_MAX_TRANSACTION_EXPIRATION_SEC (60*60*24*2)\n#define BTS_BLOCKCHAIN_MAX_MEMO_SIZE 19 \/\/ bytes\n#define BTS_BLOCKCHAIN_EXTENDED_MEMO_SIZE 32 \/\/ bytes\n#define BTS_BLOCKCHAIN_MAX_EXTENDED_MEMO_SIZE (BTS_BLOCKCHAIN_MAX_MEMO_SIZE + BTS_BLOCKCHAIN_EXTENDED_MEMO_SIZE)\n\n\/**\n * The maximum amount that can be issued for user assets.\n *\n * 10^18 \/ 2^63 < 1 however, to support representing all share values as a double in\n * languages like java script, we must stay within the epsilon so\n *\n * 10^15 \/ 2^53 < 1 allows all values to be represented as a double or an int64\n *\/\n#define BTS_BLOCKCHAIN_MAX_SHARES (1000*1000*int64_t(1000)*1000*int64_t(1000))\n\n#define BTS_BLOCKCHAIN_MIN_NAME_SIZE 1\n#define BTS_BLOCKCHAIN_MAX_NAME_SIZE 63\n#define BTS_BLOCKCHAIN_MAX_NAME_DATA_SIZE (1024*64)\n\n#define BTS_BLOCKCHAIN_MAX_SUB_SYMBOL_SIZE 8 \/\/ characters\n#define BTS_BLOCKCHAIN_MIN_SYMBOL_SIZE 3 \/\/ characters\n#define BTS_BLOCKCHAIN_MAX_SYMBOL_SIZE 12 \/\/ characters\n\n#define BTS_BLOCKCHAIN_MIN_BURN_FEE BTS_BLOCKCHAIN_PRECISION * 1 \/\/ 1 XTS\n\n#ifdef BTS_TEST_NETWORK\n#define BTS_BLOCKCHAIN_VOTE_UPDATE_PERIOD_SEC 10\n#else\n#define BTS_BLOCKCHAIN_VOTE_UPDATE_PERIOD_SEC (60*60) \/\/ 1 hour\n#endif\n\n#define BTS_BLOCKCHAIN_MIN_FEEDS ((BTS_BLOCKCHAIN_NUM_DELEGATES\/2) + 1)\n#define BTS_BLOCKCHAIN_MINIMUM_SHORT_ORDER_SIZE (BTS_BLOCKCHAIN_PRECISION*100)\n#define BTS_BLOCKCHAIN_MIN_YIELD_PERIOD_SEC (60*60*24) \/\/ 24 hours\n#define BTS_BLOCKCHAIN_MAX_YIELD_PERIOD_SEC (BTS_BLOCKCHAIN_BLOCKS_PER_YEAR * BTS_BLOCKCHAIN_BLOCK_INTERVAL_SEC) \/\/ 1 year\n\n#ifdef BTS_TEST_NETWORK\n#define BTS_BLOCKCHAIN_MAX_SHORT_PERIOD_SEC (2*60*60) \/\/ 2 hours\n#else\n#define BTS_BLOCKCHAIN_MAX_SHORT_PERIOD_SEC (30*24*60*60) \/\/ 1 month\n#endif\n#define BTS_BLOCKCHAIN_MAX_SHORT_APR_PCT (uint64_t(50))\n\n#define BTS_BLOCKCHAIN_MCALL_D2C_NUMERATOR 1\n#define BTS_BLOCKCHAIN_MCALL_D2C_DENOMINATOR 2\n\n\/\/ TODO: This stuff only matters for propagation throttling; should go somewhere else\n#define BTS_BLOCKCHAIN_DEFAULT_RELAY_FEE 10000 \/\/ XTS\n#define BTS_BLOCKCHAIN_MAX_TRX_PER_SECOND 1 \/\/ (10)\n#define BTS_BLOCKCHAIN_MAX_PENDING_QUEUE_SIZE 10 \/\/ (BTS_BLOCKCHAIN_MAX_TRX_PER_SECOND * BTS_BLOCKCHAIN_BLOCK_INTERVAL_SEC)\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \n\n#include \"shunting-yard.h\"\n\ndouble toDouble(TokenBase* base) {\n if(base->type == NUM) {\n return static_cast*>(base)->val;\n } else {\n throw std::domain_error(\n \"Cannot convert non numeric types to double!\");\n }\n}\n\nvoid assert(double actual, double expected, const char* expr = 0) {\n double diff = actual - expected;\n if (diff < 0) diff *= -1;\n if (diff < 1e-15) {\n if(expr) {\n std::cout << \" '\" << expr << \"' indeed evaluated to \" <<\n expected << \".\" << std::endl;\n } else {\n std::cout << \" actual value '\" << actual <<\n \"' indeed matches the expected value '\" << expected << \"'\" << std::endl;\n }\n } else {\n if(expr) {\n std::cout << \" FAILURE '\" << expr << \"' evaluated to \" <<\n actual << \" and NOT \" << expected << \"!\" << std::endl;\n } else {\n std::cout << \" FAILURE, actual value '\" << actual <<\n \"' does not match the expected value '\" << expected <<\n \"'\" << std::endl;\n }\n }\n}\nvoid assert(const char* expr, double expected,\n TokenMap_t* vars = 0) {\n double actual = toDouble(calculator::calculate(expr, vars));\n assert(actual, expected, expr);\n}\n\n#define assert_throws(a) {try {\\\n a; \\\n std::cout << \" FAILURE, it did not THROW as expected\" << std::endl; \\\n} catch(...) { \\\n std::cout << \" THROWS as expected\" << std::endl; \\\n}}\n\n#define assert_not_throw(a) {try {\\\n a; \\\n std::cout << \" Do not THROW as expected\" << std::endl; \\\n} catch(...) { \\\n std::cout << \" FAILURE, it did THROW which was unexpected\" << std::endl; \\\n}}\n\nint main(int argc, char** argv) {\n TokenMap_t vars;\n vars[\"pi\"] = 3.14;\n vars[\"b1\"] = 0;\n\n std::cout << \"\\nTests with static calculate::calculate()\\n\" << std::endl;\n\n assert(\"-pi + 1\", -2.14, &vars);\n assert(\"-pi + 1 * b1\", -3.14, &vars);\n\n assert(\"(20+10)*3\/2-3\", 42.0);\n assert(\"1 << 4\", 16.0);\n assert(\"1+(-2*3)\", -5);\n\n std::cout << \"\\nTests with calculate::compile() & calculate::eval()\\n\" << std::endl;\n\n calculator c1;\n c1.compile(\"-pi+1\", &vars);\n assert(toDouble(c1.eval()), -2.14);\n\n calculator c2(\"pi+4\", &vars);\n assert(toDouble(c2.eval()), 7.14);\n assert(toDouble(c2.eval()), 7.14);\n\n calculator c3(\"pi+b1+b2\", &vars);\n\n vars[\"b2\"] = 1;\n assert(toDouble(c3.eval(&vars)), 4.14);\n\n vars[\"b2\"] = .86;\n assert(toDouble(c3.eval(&vars)), 4);\n\n std::cout << \"\\nTesting boolean expressions\\n\" << std::endl;\n\n assert(\"3 < 3\", false);\n assert(\"3 <= 3\", true);\n assert(\"3 > 3\", false);\n assert(\"3 >= 3\", true);\n assert(\"3 == 3\", true);\n assert(\"3 != 3\", false);\n\n assert(\"(3 && true) == true\", true);\n assert(\"(3 && 0) == true\", false);\n assert(\"(3 || 0) == true\", true);\n assert(\"(false || 0) == true\", false);\n\n std::cout << \"\\nTesting string expressions\\n\" << std::endl;\n\n vars[\"str1\"] = new Token(\"foo\", STR);\n vars[\"str2\"] = new Token(\"bar\", STR);\n vars[\"str3\"] = new Token(\"foobar\", STR);\n vars[\"str4\"] = new Token(\"foo10\", STR);\n vars[\"str5\"] = new Token(\"10bar\", STR);\n\n assert(\"str1 + str2 == str3\", true, &vars);\n assert(\"str1 + str2 != str3\", false, &vars);\n assert(\"str1 + 10 == str4\", true, &vars);\n assert(\"10 + str2 == str5\", true, &vars);\n\n assert(\"'foo' + \\\"bar\\\" == str3\", true, &vars);\n assert(\"'foo' + \\\"bar\\\" != 'foobar\\\"'\", true, &vars);\n assert(\"'foo' + \\\"bar\\\\\\\"\\\" == 'foobar\\\"'\", true, &vars);\n\n std::cout << \"\\nTesting exception management\\n\" << std::endl;\n\n assert_throws(c3.eval());\n\n assert_throws({\n vars.erase(\"b2\");\n c3.eval(&vars);\n });\n\n assert_not_throw({\n vars[\"b2\"] = 0;\n vars.erase(\"b1\");\n c3.eval(&vars);\n });\n\n std::cout << \"\\nEnd testing\" << std::endl;\n\n return 0;\n}\nUpdate assert function to work with any type of Token#include \n#include \n#include \n#include \n#include \n\n#include \"shunting-yard.h\"\n\nvoid assert(packToken actual, packToken expected, const char* expr = 0) {\n bool match = false;\n if(actual->type == expected->type && actual->type == NUM) {\n double diff = actual.asDouble() - expected.asDouble();\n if (diff < 0) diff *= -1;\n if (diff < 1e-15) match = true;\n } else if(actual == expected) {\n match = true;\n }\n\n if(match) {\n if(expr) {\n std::cout << \" '\" << expr << \"' indeed evaluated to \" <<\n expected << \".\" << std::endl;\n } else {\n std::cout << \" actual value '\" << actual <<\n \"' indeed matches the expected value '\" << expected << \"'\" << std::endl;\n }\n } else {\n if(expr) {\n std::cout << \" FAILURE '\" << expr << \"' evaluated to \" <<\n actual << \" and NOT \" << expected << \"!\" << std::endl;\n } else {\n std::cout << \" FAILURE, actual value '\" << actual <<\n \"' does not match the expected value '\" << expected <<\n \"'\" << std::endl;\n }\n }\n}\nvoid assert(const char* expr, packToken expected,\n TokenMap_t* vars = 0) {\n packToken actual = calculator::calculate(expr, vars);\n assert(actual, expected, expr);\n}\n\n#define assert_throws(a) {try {\\\n a; \\\n std::cout << \" FAILURE, it did not THROW as expected\" << std::endl; \\\n} catch(...) { \\\n std::cout << \" THROWS as expected\" << std::endl; \\\n}}\n\n#define assert_not_throw(a) {try {\\\n a; \\\n std::cout << \" Do not THROW as expected\" << std::endl; \\\n} catch(...) { \\\n std::cout << \" FAILURE, it did THROW which was unexpected\" << std::endl; \\\n}}\n\nint main(int argc, char** argv) {\n TokenMap_t vars;\n vars[\"pi\"] = 3.14;\n vars[\"b1\"] = 0;\n\n std::cout << \"\\nTests with static calculate::calculate()\\n\" << std::endl;\n\n assert(\"-pi + 1\", -2.14, &vars);\n assert(\"-pi + 1 * b1\", -3.14, &vars);\n\n assert(\"(20+10)*3\/2-3\", 42.0);\n assert(\"1 << 4\", 16.0);\n assert(\"1+(-2*3)\", -5);\n\n std::cout << \"\\nTests with calculate::compile() & calculate::eval()\\n\" << std::endl;\n\n calculator c1;\n c1.compile(\"-pi+1\", &vars);\n assert(c1.eval(), -2.14);\n\n calculator c2(\"pi+4\", &vars);\n assert(c2.eval(), 7.14);\n assert(c2.eval(), 7.14);\n\n calculator c3(\"pi+b1+b2\", &vars);\n\n vars[\"b2\"] = 1;\n assert(c3.eval(&vars), 4.14);\n\n vars[\"b2\"] = .86;\n assert(c3.eval(&vars), 4);\n\n std::cout << \"\\nTesting boolean expressions\\n\" << std::endl;\n\n assert(\"3 < 3\", false);\n assert(\"3 <= 3\", true);\n assert(\"3 > 3\", false);\n assert(\"3 >= 3\", true);\n assert(\"3 == 3\", true);\n assert(\"3 != 3\", false);\n\n assert(\"(3 && true) == true\", true);\n assert(\"(3 && 0) == true\", false);\n assert(\"(3 || 0) == true\", true);\n assert(\"(false || 0) == true\", false);\n\n std::cout << \"\\nTesting string expressions\\n\" << std::endl;\n\n vars[\"str1\"] = new Token(\"foo\", STR);\n vars[\"str2\"] = new Token(\"bar\", STR);\n vars[\"str3\"] = new Token(\"foobar\", STR);\n vars[\"str4\"] = new Token(\"foo10\", STR);\n vars[\"str5\"] = new Token(\"10bar\", STR);\n\n assert(\"str1 + str2 == str3\", true, &vars);\n assert(\"str1 + str2 != str3\", false, &vars);\n assert(\"str1 + 10 == str4\", true, &vars);\n assert(\"10 + str2 == str5\", true, &vars);\n\n assert(\"'foo' + \\\"bar\\\" == str3\", true, &vars);\n assert(\"'foo' + \\\"bar\\\" != 'foobar\\\"'\", true, &vars);\n assert(\"'foo' + \\\"bar\\\\\\\"\\\" == 'foobar\\\"'\", true, &vars);\n\n std::cout << \"\\nTesting exception management\\n\" << std::endl;\n\n assert_throws(c3.eval());\n\n assert_throws({\n vars.erase(\"b2\");\n c3.eval(&vars);\n });\n\n assert_not_throw({\n vars[\"b2\"] = 0;\n vars.erase(\"b1\");\n c3.eval(&vars);\n });\n\n std::cout << \"\\nEnd testing\" << std::endl;\n\n return 0;\n}\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * $RCSfile: calendarImpl.cxx,v $\n *\n * $Revision: 1.4 $\n *\n * last change: $Author: khong $ $Date: 2002-07-12 17:25:26 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#include \"calendarImpl.hxx\"\n#include \"localedata.hxx\"\n#include \n\nusing namespace ::com::sun::star::uno;\nusing namespace ::com::sun::star::lang;\nusing namespace ::com::sun::star::i18n;\nusing namespace ::rtl;\n\n#define ERROR RuntimeException()\n\nCalendarImpl::CalendarImpl(const Reference< XMultiServiceFactory > &rxMSF) : xMSF(rxMSF)\n{\n}\n\nCalendarImpl::~CalendarImpl()\n{\n \/\/ Clear lookuptable\n for (lookupTableItem *listItem = (lookupTableItem*)lookupTable.First();\n listItem; listItem = (lookupTableItem*)lookupTable.Next())\n delete listItem;\n lookupTable.Clear();\n}\n\n\nvoid SAL_CALL\nCalendarImpl::loadDefaultCalendar( const Locale& rLocale ) throw(RuntimeException)\n{\n loadCalendar(OUString(), rLocale);\n}\n\nvoid SAL_CALL\nCalendarImpl::loadCachedCalendar(OUString& uniqueID) throw (RuntimeException)\n{\n for (lookupTableItem *listItem = (lookupTableItem*)lookupTable.First();\n listItem; listItem = (lookupTableItem*)lookupTable.Next()) {\n if (uniqueID == listItem->uniqueID) {\n xCalendar = listItem->xCalendar;\n return;\n }\n }\n\n Reference < XInterface > xI = xMSF->createInstance(\n OUString::createFromAscii(\"com.sun.star.i18n.Calendar_\") + uniqueID);\n if ( xI.is() )\n xI->queryInterface(::getCppuType((const Reference< XExtendedCalendar>*)0)) >>= xCalendar;\n else\n throw ERROR;\n\n lookupTable.Insert( new lookupTableItem(uniqueID, xCalendar) );\n}\n\nvoid SAL_CALL\nCalendarImpl::loadCalendar( const OUString& uniqueID, const Locale& rLocale ) throw(RuntimeException)\n{\n aLocale = rLocale;\n Sequence< Calendar> xC = LocaleData().getAllCalendars(rLocale);\n for (sal_Int32 i = 0; i < xC.getLength(); i++) {\n if ( (uniqueID.getLength() != 0) ? (uniqueID == xC[i].Name) : (xC[i].Default == sal_True) ) {\n aCalendar = xC[i];\n loadCachedCalendar(aCalendar.Name);\n if (xCalendar.is())\n xCalendar->loadCalendar(uniqueID, aLocale);\n \/\/ setup first day of week\n for (aStartOfWeek = aCalendar.Days.getLength()-1; aStartOfWeek>=0; aStartOfWeek-- )\n if (aCalendar.StartOfWeek == aCalendar.Days[aStartOfWeek].ID)\n return;\n }\n }\n throw ERROR;\n}\n\n\nCalendar SAL_CALL\nCalendarImpl::getLoadedCalendar() throw(RuntimeException)\n{\n return aCalendar;\n}\n\nSequence< OUString > SAL_CALL\nCalendarImpl::getAllCalendars( const Locale& rLocale ) throw(RuntimeException)\n{\n Sequence< Calendar> xC = LocaleData().getAllCalendars(rLocale);\n sal_Int32 nLen = xC.getLength();\n Sequence< OUString > xSeq( nLen );\n for (sal_Int32 i = 0; i < nLen; i++)\n xSeq[i] = xC[i].Name;\n return xSeq;\n}\n\nvoid SAL_CALL\nCalendarImpl::setDateTime( double timeInDays ) throw(RuntimeException)\n{\n if (xCalendar.is())\n xCalendar->setDateTime( timeInDays );\n else\n throw ERROR ;\n}\n\ndouble SAL_CALL\nCalendarImpl::getDateTime() throw(RuntimeException)\n{\n if (xCalendar.is())\n return xCalendar->getDateTime();\n else\n throw ERROR ;\n}\n\nOUString SAL_CALL\nCalendarImpl::getUniqueID() throw(RuntimeException)\n{\n return aCalendar.Name;\n}\n\nvoid SAL_CALL\nCalendarImpl::setValue( sal_Int16 fieldIndex, sal_Int16 value ) throw(RuntimeException)\n{\n if (xCalendar.is())\n xCalendar->setValue( fieldIndex, value );\n else\n throw ERROR ;\n}\n\nsal_Int16 SAL_CALL\nCalendarImpl::getValue( sal_Int16 fieldIndex ) throw(RuntimeException)\n{\n if (xCalendar.is())\n return xCalendar->getValue( fieldIndex );\n else\n throw ERROR ;\n}\n\nvoid SAL_CALL\nCalendarImpl::addValue( sal_Int16 fieldIndex, sal_Int32 amount ) throw(RuntimeException)\n{\n if (xCalendar.is())\n xCalendar->addValue( fieldIndex, amount);\n else\n throw ERROR ;\n}\n\nsal_Int16 SAL_CALL\nCalendarImpl::getFirstDayOfWeek() throw(RuntimeException)\n{\n return aStartOfWeek;\n}\n\nvoid SAL_CALL\nCalendarImpl::setFirstDayOfWeek( sal_Int16 day )\nthrow(RuntimeException)\n{\n aStartOfWeek = day;\n}\n\nvoid SAL_CALL\nCalendarImpl::setMinimumNumberOfDaysForFirstWeek( sal_Int16 days ) throw(RuntimeException)\n{\n aCalendar.MinimumNumberOfDaysForFirstWeek = days;\n}\n\nsal_Int16 SAL_CALL\nCalendarImpl::getMinimumNumberOfDaysForFirstWeek() throw(RuntimeException)\n{\n return aCalendar.MinimumNumberOfDaysForFirstWeek;\n}\n\n\nOUString SAL_CALL\nCalendarImpl::getDisplayName( sal_Int16 displayIndex, sal_Int16 idx, sal_Int16 nameType ) throw(RuntimeException)\n{\n OUString aStr;\n\n switch( displayIndex ) {\n case CalendarDisplayIndex::AM_PM:\/* ==0 *\/\n if (idx == 0) aStr = LocaleData().getLocaleItem(aLocale).timeAM;\n else if (idx == 1) aStr = LocaleData().getLocaleItem(aLocale).timePM;\n else throw ERROR;\n break;\n case CalendarDisplayIndex::DAY:\n if( idx >= aCalendar.Days.getLength() ) throw ERROR;\n if (nameType == 0) aStr = aCalendar.Days[idx].AbbrevName;\n else if (nameType == 1) aStr = aCalendar.Days[idx].FullName;\n else throw ERROR;\n break;\n case CalendarDisplayIndex::MONTH:\n if( idx >= aCalendar.Months.getLength() ) throw ERROR;\n if (nameType == 0) aStr = aCalendar.Months[idx].AbbrevName;\n else if (nameType == 1) aStr = aCalendar.Months[idx].FullName;\n else throw ERROR;\n break;\n case CalendarDisplayIndex::ERA:\n if( idx >= aCalendar.Eras.getLength() ) throw ERROR;\n if (nameType == 0) aStr = aCalendar.Eras[idx].AbbrevName;\n else if (nameType == 1) aStr = aCalendar.Eras[idx].FullName;\n else throw ERROR;\n break;\n case CalendarDisplayIndex::YEAR:\n break;\n default:\n throw ERROR;\n }\n return aStr;\n}\n\nsal_Int16 SAL_CALL\nCalendarImpl::getNumberOfMonthsInYear() throw(RuntimeException)\n{\n return (sal_Int16) aCalendar.Months.getLength();\n}\n\n\nsal_Int16 SAL_CALL\nCalendarImpl::getNumberOfDaysInWeek() throw(RuntimeException)\n{\n return (sal_Int16) aCalendar.Days.getLength();\n}\n\n\nSequence< CalendarItem > SAL_CALL\nCalendarImpl::getMonths() throw(RuntimeException)\n{\n return aCalendar.Months;\n}\n\n\nSequence< CalendarItem > SAL_CALL\nCalendarImpl::getDays() throw(RuntimeException)\n{\n return aCalendar.Days;\n}\n\nsal_Bool SAL_CALL\nCalendarImpl::isValid() throw(RuntimeException)\n{\n if (xCalendar.is())\n return xCalendar->isValid();\n else\n throw ERROR ;\n}\n\nOUString SAL_CALL\nCalendarImpl::getDisplayString( sal_Int32 nCalendarDisplayCode, sal_Int16 nNativeNumberMode )\n throw (RuntimeException)\n{\n if (xCalendar.is())\n return xCalendar->getDisplayString(nCalendarDisplayCode, nNativeNumberMode);\n else\n throw ERROR ;\n}\n\nOUString SAL_CALL\nCalendarImpl::getImplementationName(void) throw( RuntimeException )\n{\n return OUString::createFromAscii(\"com.sun.star.i18n.CalendarImpl\");\n}\n\nconst sal_Char cCalendar[] = \"com.sun.star.i18n.LocaleCalendar\";\n\nsal_Bool SAL_CALL\nCalendarImpl::supportsService(const OUString& rServiceName) throw( RuntimeException )\n{\n return !rServiceName.compareToAscii(cCalendar);\n}\n\nSequence< OUString > SAL_CALL\nCalendarImpl::getSupportedServiceNames(void) throw( RuntimeException )\n{\n Sequence< OUString > aRet(1);\n aRet[0] = OUString::createFromAscii(cCalendar);\n return aRet;\n}\n\n#98695# add drafts namespace (why was only MSC bothered? How did other compilers know?)\/*************************************************************************\n *\n * $RCSfile: calendarImpl.cxx,v $\n *\n * $Revision: 1.5 $\n *\n * last change: $Author: er $ $Date: 2002-07-16 09:52:54 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#include \"calendarImpl.hxx\"\n#include \"localedata.hxx\"\n#include \n\nusing namespace ::com::sun::star::uno;\nusing namespace ::com::sun::star::lang;\nusing namespace ::com::sun::star::i18n;\nusing namespace ::drafts::com::sun::star::i18n;\nusing namespace ::rtl;\n\n#define ERROR RuntimeException()\n\nCalendarImpl::CalendarImpl(const Reference< XMultiServiceFactory > &rxMSF) : xMSF(rxMSF)\n{\n}\n\nCalendarImpl::~CalendarImpl()\n{\n \/\/ Clear lookuptable\n for (lookupTableItem *listItem = (lookupTableItem*)lookupTable.First();\n listItem; listItem = (lookupTableItem*)lookupTable.Next())\n delete listItem;\n lookupTable.Clear();\n}\n\n\nvoid SAL_CALL\nCalendarImpl::loadDefaultCalendar( const Locale& rLocale ) throw(RuntimeException)\n{\n loadCalendar(OUString(), rLocale);\n}\n\nvoid SAL_CALL\nCalendarImpl::loadCachedCalendar(OUString& uniqueID) throw (RuntimeException)\n{\n for (lookupTableItem *listItem = (lookupTableItem*)lookupTable.First();\n listItem; listItem = (lookupTableItem*)lookupTable.Next()) {\n if (uniqueID == listItem->uniqueID) {\n xCalendar = listItem->xCalendar;\n return;\n }\n }\n\n Reference < XInterface > xI = xMSF->createInstance(\n OUString::createFromAscii(\"com.sun.star.i18n.Calendar_\") + uniqueID);\n if ( xI.is() )\n xI->queryInterface(::getCppuType((const Reference< XExtendedCalendar>*)0)) >>= xCalendar;\n else\n throw ERROR;\n\n lookupTable.Insert( new lookupTableItem(uniqueID, xCalendar) );\n}\n\nvoid SAL_CALL\nCalendarImpl::loadCalendar( const OUString& uniqueID, const Locale& rLocale ) throw(RuntimeException)\n{\n aLocale = rLocale;\n Sequence< Calendar> xC = LocaleData().getAllCalendars(rLocale);\n for (sal_Int32 i = 0; i < xC.getLength(); i++) {\n if ( (uniqueID.getLength() != 0) ? (uniqueID == xC[i].Name) : (xC[i].Default == sal_True) ) {\n aCalendar = xC[i];\n loadCachedCalendar(aCalendar.Name);\n if (xCalendar.is())\n xCalendar->loadCalendar(uniqueID, aLocale);\n \/\/ setup first day of week\n for (aStartOfWeek = aCalendar.Days.getLength()-1; aStartOfWeek>=0; aStartOfWeek-- )\n if (aCalendar.StartOfWeek == aCalendar.Days[aStartOfWeek].ID)\n return;\n }\n }\n throw ERROR;\n}\n\n\nCalendar SAL_CALL\nCalendarImpl::getLoadedCalendar() throw(RuntimeException)\n{\n return aCalendar;\n}\n\nSequence< OUString > SAL_CALL\nCalendarImpl::getAllCalendars( const Locale& rLocale ) throw(RuntimeException)\n{\n Sequence< Calendar> xC = LocaleData().getAllCalendars(rLocale);\n sal_Int32 nLen = xC.getLength();\n Sequence< OUString > xSeq( nLen );\n for (sal_Int32 i = 0; i < nLen; i++)\n xSeq[i] = xC[i].Name;\n return xSeq;\n}\n\nvoid SAL_CALL\nCalendarImpl::setDateTime( double timeInDays ) throw(RuntimeException)\n{\n if (xCalendar.is())\n xCalendar->setDateTime( timeInDays );\n else\n throw ERROR ;\n}\n\ndouble SAL_CALL\nCalendarImpl::getDateTime() throw(RuntimeException)\n{\n if (xCalendar.is())\n return xCalendar->getDateTime();\n else\n throw ERROR ;\n}\n\nOUString SAL_CALL\nCalendarImpl::getUniqueID() throw(RuntimeException)\n{\n return aCalendar.Name;\n}\n\nvoid SAL_CALL\nCalendarImpl::setValue( sal_Int16 fieldIndex, sal_Int16 value ) throw(RuntimeException)\n{\n if (xCalendar.is())\n xCalendar->setValue( fieldIndex, value );\n else\n throw ERROR ;\n}\n\nsal_Int16 SAL_CALL\nCalendarImpl::getValue( sal_Int16 fieldIndex ) throw(RuntimeException)\n{\n if (xCalendar.is())\n return xCalendar->getValue( fieldIndex );\n else\n throw ERROR ;\n}\n\nvoid SAL_CALL\nCalendarImpl::addValue( sal_Int16 fieldIndex, sal_Int32 amount ) throw(RuntimeException)\n{\n if (xCalendar.is())\n xCalendar->addValue( fieldIndex, amount);\n else\n throw ERROR ;\n}\n\nsal_Int16 SAL_CALL\nCalendarImpl::getFirstDayOfWeek() throw(RuntimeException)\n{\n return aStartOfWeek;\n}\n\nvoid SAL_CALL\nCalendarImpl::setFirstDayOfWeek( sal_Int16 day )\nthrow(RuntimeException)\n{\n aStartOfWeek = day;\n}\n\nvoid SAL_CALL\nCalendarImpl::setMinimumNumberOfDaysForFirstWeek( sal_Int16 days ) throw(RuntimeException)\n{\n aCalendar.MinimumNumberOfDaysForFirstWeek = days;\n}\n\nsal_Int16 SAL_CALL\nCalendarImpl::getMinimumNumberOfDaysForFirstWeek() throw(RuntimeException)\n{\n return aCalendar.MinimumNumberOfDaysForFirstWeek;\n}\n\n\nOUString SAL_CALL\nCalendarImpl::getDisplayName( sal_Int16 displayIndex, sal_Int16 idx, sal_Int16 nameType ) throw(RuntimeException)\n{\n OUString aStr;\n\n switch( displayIndex ) {\n case CalendarDisplayIndex::AM_PM:\/* ==0 *\/\n if (idx == 0) aStr = LocaleData().getLocaleItem(aLocale).timeAM;\n else if (idx == 1) aStr = LocaleData().getLocaleItem(aLocale).timePM;\n else throw ERROR;\n break;\n case CalendarDisplayIndex::DAY:\n if( idx >= aCalendar.Days.getLength() ) throw ERROR;\n if (nameType == 0) aStr = aCalendar.Days[idx].AbbrevName;\n else if (nameType == 1) aStr = aCalendar.Days[idx].FullName;\n else throw ERROR;\n break;\n case CalendarDisplayIndex::MONTH:\n if( idx >= aCalendar.Months.getLength() ) throw ERROR;\n if (nameType == 0) aStr = aCalendar.Months[idx].AbbrevName;\n else if (nameType == 1) aStr = aCalendar.Months[idx].FullName;\n else throw ERROR;\n break;\n case CalendarDisplayIndex::ERA:\n if( idx >= aCalendar.Eras.getLength() ) throw ERROR;\n if (nameType == 0) aStr = aCalendar.Eras[idx].AbbrevName;\n else if (nameType == 1) aStr = aCalendar.Eras[idx].FullName;\n else throw ERROR;\n break;\n case CalendarDisplayIndex::YEAR:\n break;\n default:\n throw ERROR;\n }\n return aStr;\n}\n\nsal_Int16 SAL_CALL\nCalendarImpl::getNumberOfMonthsInYear() throw(RuntimeException)\n{\n return (sal_Int16) aCalendar.Months.getLength();\n}\n\n\nsal_Int16 SAL_CALL\nCalendarImpl::getNumberOfDaysInWeek() throw(RuntimeException)\n{\n return (sal_Int16) aCalendar.Days.getLength();\n}\n\n\nSequence< CalendarItem > SAL_CALL\nCalendarImpl::getMonths() throw(RuntimeException)\n{\n return aCalendar.Months;\n}\n\n\nSequence< CalendarItem > SAL_CALL\nCalendarImpl::getDays() throw(RuntimeException)\n{\n return aCalendar.Days;\n}\n\nsal_Bool SAL_CALL\nCalendarImpl::isValid() throw(RuntimeException)\n{\n if (xCalendar.is())\n return xCalendar->isValid();\n else\n throw ERROR ;\n}\n\nOUString SAL_CALL\nCalendarImpl::getDisplayString( sal_Int32 nCalendarDisplayCode, sal_Int16 nNativeNumberMode )\n throw (RuntimeException)\n{\n if (xCalendar.is())\n return xCalendar->getDisplayString(nCalendarDisplayCode, nNativeNumberMode);\n else\n throw ERROR ;\n}\n\nOUString SAL_CALL\nCalendarImpl::getImplementationName(void) throw( RuntimeException )\n{\n return OUString::createFromAscii(\"com.sun.star.i18n.CalendarImpl\");\n}\n\nconst sal_Char cCalendar[] = \"com.sun.star.i18n.LocaleCalendar\";\n\nsal_Bool SAL_CALL\nCalendarImpl::supportsService(const OUString& rServiceName) throw( RuntimeException )\n{\n return !rServiceName.compareToAscii(cCalendar);\n}\n\nSequence< OUString > SAL_CALL\nCalendarImpl::getSupportedServiceNames(void) throw( RuntimeException )\n{\n Sequence< OUString > aRet(1);\n aRet[0] = OUString::createFromAscii(cCalendar);\n return aRet;\n}\n\n<|endoftext|>"} {"text":"\/\/ This is improperly intended code\n\/\/ Beautify.uc will fix this\n\nconst int MyEquate = 0x100;\nconst int Other = 0x200;\n\nlong ProgStatus;\n\n#if defined Other\n\/\/ Something\n#elif !defined abcd\n\/\/ Something else\n#else\n\/\/ Etc\n#endif\n\nstruct point {\n long x;\n long y;\n}\n\nlong MyFunction(long a, float& b)\n{\n long x;\n long y;\n long *Test = new long [a+25+1];\n long yVar;\n \n \/\/ Dim q As Long\n \/\/ I don't want the commented line above to be translated\n \n MySub(a);\n x = MySub(b)+1;\n \n if (b > 5) {\n for (x=1; x<=10; x += 1) {\n for (yVar=10; yVar>=1; yVar += -1) {\n if (x > y) {\n return a+y;\n }\n if (y < MyEquate) {\n return Test[x-y]*10;\n }\n }\n }\n }\n \n delete[] Test;\n}\n\nvoid MySub(long x)\n{\n long y;\n long *Test;\n float *Number = new float [10+1];\n long *Other = new long [x+1];\n long z;\n \n ProgStatus = 10;\n y = x + 1;\n z = y+x;\n Other[x] = x+1;\n \n while (x < 10) {\n y = MyFunction(x, 10.5);\n Test = &x;\n Number[z] = *Test + Other[5+x];\n x = x+1;\n } \n \n delete[] Other;\n delete[] Other;\n}\nUpdate AfterBeautify.cpp\/\/ This is improperly intended code\n\/\/ Beautify.uc will fix this\n\nconst int MyEquate = 0x100;\nconst int Other = 0x200;\n\nlong ProgStatus;\n\n#if defined Other\n\/\/ Something\n#elif !defined abcd\n\/\/ Something else\n#else\n\/\/ Etc\n#endif\n\nstruct point {\n long x;\n long y;\n}\n\nlong MyFunction(long a, float& b)\n{\n long x;\n long y;\n long *Test = new long [a+25+1];\n long yVar;\n \n \/\/ Dim q As Long\n \/\/ I don't want the commented line above to be translated\n \n MySub(a);\n x = MySub(b)+1;\n printf(\"Hello world\");\n \n if (b > 5) {\n for (x=1; x<=10; x += 1) {\n for (yVar=10; yVar>=1; yVar += -1) {\n if (x > y) {\n return a+y;\n }\n if (y < MyEquate) {\n return Test[x-y]*10;\n }\n }\n }\n }\n \n delete[] Test;\n}\n\nvoid MySub(long x)\n{\n long y;\n long *Test;\n float *Number = new float [10+1];\n long *Other = new long [x+1];\n long z;\n \n ProgStatus = 10;\n y = x + 1;\n z = y+x;\n Other[x] = x+1;\n \n while (x < 10) {\n y = MyFunction(x, 10.5);\n Test = &x;\n Number[z] = *Test + Other[5+x];\n x = x+1;\n }\n \n if (x > 5) {\n y = 10;\n z = 5+x;\n } else {\n y=y+1;\n z=x-1;\n }\n \n delete[] Other;\n delete[] Other;\n}\n<|endoftext|>"} {"text":"\/\/ For conditions of distribution and use, see copyright notice in LICENSE\n\n#include \"StableHeaders.h\"\n#include \"OgreMaterialDefines.h\"\n#include \"CoreStringUtils.h\"\n#include \"LoggingFunctions.h\"\n\n#include \n\nnamespace Tundra\n{\n\nnamespace Ogre\n{\n\n\/\/ MaterialBlock\n\nMaterialBlock::MaterialBlock(MaterialBlock *parent_, MaterialPart part_, int t, int p, int tu) : \n parent(parent_),\n part(part_),\n technique(t),\n pass(p),\n textureUnit(tu)\n{\n}\n\nMaterialBlock::~MaterialBlock()\n{\n for(uint i=0; ipart == part)\n num++;\n }\n return num;\n}\n\nuint MaterialBlock::NumTechniques() const\n{\n return NumChildren(MP_Technique);\n}\n\nuint MaterialBlock::NumPasses() const\n{\n return NumChildren(MP_Pass);\n}\n\nuint MaterialBlock::NumTextureUnits() const\n{\n return NumChildren(MP_TextureUnit);\n}\n\nMaterialBlock *MaterialBlock::Technique(uint index) const\n{\n foreach(MaterialBlock *block, blocks)\n {\n if (block->part == MP_Technique && block->technique == static_cast(index))\n return block;\n }\n return nullptr;\n}\n\nMaterialBlock *MaterialBlock::Pass(uint index) const\n{\n foreach(MaterialBlock *block, blocks)\n {\n if (block->part == MP_Pass && block->pass == static_cast(index))\n return block;\n }\n return nullptr;\n}\n\nMaterialBlock *MaterialBlock::TextureUnit(uint index) const\n{\n foreach(MaterialBlock *block, blocks)\n {\n if (block->part == MP_TextureUnit && block->textureUnit == static_cast(index))\n return block;\n }\n return nullptr;\n}\n\nMaterialBlock *MaterialBlock::VertexProgram() const\n{\n foreach(MaterialBlock *block, blocks)\n {\n if (block->part == MP_VertexProgram)\n return block;\n }\n return nullptr;\n}\n\nMaterialBlock *MaterialBlock::FragmentProgram() const\n{\n foreach(MaterialBlock *block, blocks)\n {\n if (block->part == MP_FragmentProgram)\n return block;\n }\n return nullptr;\n}\n\nuint MaterialBlock::Num(const StringHash &name) const\n{\n MaterialProperties::ConstIterator iter = properties.Find(name);\n if (iter != properties.End())\n return iter->second_.Size();\n return 0;\n}\n\nbool MaterialBlock::Has(const StringHash &name) const\n{\n return (Num(name) > 0);\n}\n\nString MaterialBlock::StringValue(const StringHash &name, const String &defaultValue, uint index) const\n{\n MaterialProperties::ConstIterator iter = properties.Find(name);\n if (iter != properties.End() && index < iter->second_.Size())\n return iter->second_[index];\n return defaultValue;\n}\n\nStringVector MaterialBlock::StringVectorValue(const StringHash &name, uint index) const\n{\n String value = StringValue(name, \"\", index).Trimmed();\n StringVector parts = (!value.Empty() ? value.Split(' ') : StringVector());\n \/\/ Remove empty parts to correctly parse \"1.0 1.0 1.0 1.0\" type of values\n for(auto iter = parts.Begin(); iter != parts.End();)\n {\n *iter = iter->Trimmed();\n if (iter->Empty())\n iter = parts.Erase(iter);\n else\n iter++;\n }\n return parts;\n}\n\nUrho3D::Vector2 MaterialBlock::Vector2Value(const StringHash &name, const Urho3D::Vector2 &defaultValue, uint index) const\n{\n StringVector parts = StringVectorValue(name, index);\n if (parts.Size() >= 2)\n return Urho3D::Vector2(Urho3D::ToFloat(parts[0]), Urho3D::ToFloat(parts[1]));\n return defaultValue;\n}\n\nUrho3D::Vector3 MaterialBlock::Vector3Value(const StringHash &name, const Urho3D::Vector3 &defaultValue, uint index) const\n{\n StringVector parts = StringVectorValue(name, index);\n if (parts.Size() >= 3)\n return Urho3D::Vector3(Urho3D::ToFloat(parts[0]), Urho3D::ToFloat(parts[1]), Urho3D::ToFloat(parts[2]));\n return defaultValue;\n}\n\nUrho3D::Vector4 MaterialBlock::Vector4Value(const StringHash &name, const Urho3D::Vector4 &defaultValue, uint index) const\n{\n StringVector parts = StringVectorValue(name, index);\n if (parts.Size() >= 4)\n return Urho3D::Vector4(Urho3D::ToFloat(parts[0]), Urho3D::ToFloat(parts[1]), Urho3D::ToFloat(parts[2]), Urho3D::ToFloat(parts[3]));\n return defaultValue;\n}\n\nUrho3D::Color MaterialBlock::ColorValue(const StringHash &name, const Urho3D::Color &defaultValue, uint index) const\n{\n StringVector parts = StringVectorValue(name, index);\n if (parts.Size() >= 3)\n {\n Urho3D::Color color(Urho3D::ToFloat(parts[0]), Urho3D::ToFloat(parts[1]), Urho3D::ToFloat(parts[2]));\n if (parts.Size() >= 4)\n color.a_ = Urho3D::ToFloat(parts[3]);\n return color;\n }\n return defaultValue;\n}\n\nbool MaterialBlock::BooleanValue(const StringHash &name, bool defaultValue, uint index) const\n{\n String value = StringValue(name, \"\", index).Trimmed();\n if (value.Compare(\"on\", false) == 0 || value.Compare(\"enabled\", false) == 0 || value.Compare(\"true\", false) == 0 || value.Compare(\"1\", false) == 0)\n return true;\n else if (value.Compare(\"off\", false) == 0 || value.Compare(\"disabled\", false) == 0 || value.Compare(\"false\", false) == 0 || value.Compare(\"0\", false) == 0)\n return false;\n return defaultValue;\n}\n\nvoid MaterialBlock::Dump(bool recursive, uint indentation)\n{\n String ind = \"\";\n while(ind.Length() < indentation) ind += \" \";\n\n LogInfoF(\"%s%s '%s'\", ind.CString(), MaterialPartToString(part).CString(), id.CString());\n\n indentation += 2;\n while(ind.Length() < indentation) ind += \" \";\n\n for (auto iter = properties.Begin(); iter != properties.End(); ++iter)\n {\n const StringVector &values = iter->second_;\n if (!values.Empty())\n {\n for (uint vi=0; vifirst_], 20).CString(), values[vi].CString());\n else\n LogInfoF(\"%s%s '%s'\", ind.CString(), propertyNames[iter->first_].CString(), values[vi].CString());\n }\n }\n }\n\n if (recursive)\n {\n for (auto iter = blocks.Begin(); iter != blocks.End(); ++iter)\n (*iter)->Dump(recursive, indentation);\n }\n\n indentation -= 2;\n if (indentation == 0)\n LogInfo(\"\");\n}\n\n\/\/ MaterialParser\n\nMaterialParser::MaterialParser() :\n root(0)\n{\n}\n\nMaterialParser::~MaterialParser()\n{\n SAFE_DELETE(root);\n}\n\nString MaterialParser::Error() const\n{\n return state.error;\n}\n\nbool MaterialParser::Parse(const char *data_, uint lenght_)\n{\n data = String(data_, lenght_);\n pos = 0;\n lineNum = 0;\n\n SAFE_DELETE(root);\n\n for(;;)\n {\n if (!ProcessLine())\n break;\n }\n\n \/\/ Make root safe even on failure\n if (!root)\n root = new MaterialBlock();\n\n return (state.error.Length() == 0);\n}\n\nvoid MaterialParser::Advance()\n{\n uint endPos = data.Find('\\n', pos);\n if (endPos == String::NPOS || endPos < pos)\n {\n pos = String::NPOS;\n return;\n }\n \/\/ Empty line with only \\n at the start\n else if (endPos == pos)\n {\n pos += 1;\n line = \"\";\n return;\n }\n line = data.Substring(pos, endPos - pos - (data[endPos-1] == '\\r' ? 1 : 0)).Trimmed();\n pos = endPos + 1;\n lineNum++;\n}\n\nvoid MaterialParser::SkipBlock()\n{\n uint endPos = data.Find('}', pos);\n if (endPos == String::NPOS || endPos < pos)\n {\n state.error = Urho3D::ToString(\"Failed to find Block scope end '}', started looking from index %d\", pos);\n pos = String::NPOS;\n return;\n }\n \/\/ There is a newline after found '}' advance over it.\n pos = endPos + 1;\n Advance();\n}\n\nbool IsBlockIndentifier(const StringHash &hash)\n{\n return (hash == Material::Block::Material\n || hash == Material::Block::Technique\n || hash == Material::Block::Pass\n || hash == Material::Block::TextureUnit\n || hash == Material::Block::VertexProgram\n || hash == Material::Block::FragmentProgram\n || hash == Material::Block::DefaultParameters);\n}\n\nbool MaterialParser::ProcessLine()\n{\n \/\/ Read next line\n Advance();\n\n \/\/ No more lines?\n if (pos == String::NPOS)\n return false;\n else if (line.Empty())\n return true;\n\n \/*if (lineNum < 10)\n PrintRaw(\" \" + String(lineNum) + \" '\" + line + \"'\\n\");\n else\n PrintRaw(String(lineNum) + \" '\" + line + \"'\\n\");*\/\n\n \/\/ Filter comments. Spec only allows single line comments.\n if (line.Length() > 1 && line[0] == '\/' && line[1] == '\/')\n return true;\n\n \/\/ Block scope end\n if (line[0] == '}')\n {\n \/\/ Material not yet started\n if (!state.block)\n return true;\n\n \/\/ Store parsed block to parent\n if (state.block->parent)\n state.block->parent->blocks.Push(state.block);\n\n \/\/ If traversed back to root we are done.\n \/\/\/ @todo If we want to parse multiple materials from a single file change this logic.\n state.block = state.block->parent;\n return (state.block != 0);\n }\n \/\/ Block scope start\n else if (line[0] == '{')\n {\n \/\/ Material not yet started\n if (!state.block)\n return true;\n\n \/\/ Skip invalid blocks\n if (!state.block || !state.block->IsSupported())\n SkipBlock();\n return true;\n }\n\n \/\/ Split to \" \" from the first space.\n \/\/ Note that value can contain spaces, it is stored as is.\n uint splitPos = line.Find(' ');\n String keyStr = (splitPos == String::NPOS ? line : line.Substring(0, splitPos).ToLower());\n StringHash key(keyStr);\n String value = (splitPos == String::NPOS ? \"\" : line.Substring(splitPos+1));\n \n \/\/ Do not begin default_params block if material not started yet\n if (key == Material::Block::DefaultParameters && !state.block)\n return true;\n\n \/\/ Is this a new block scope identifier?\n if (IsBlockIndentifier(key))\n {\n MaterialPart part = MP_Unsupported;\n\n \/\/ Detect block type\n if (key == Material::Block::Material)\n {\n \/\/\/ @todo http:\/\/www.ogre3d.org\/docs\/manual\/manual_25.html#Script-Inheritance\n part = MP_Material;\n state.technique = -1;\n state.pass = -1;\n state.textureUnit = -1;\n }\n else if (key == Material::Block::Technique)\n {\n part = MP_Technique;\n state.technique++;\n state.pass = -1;\n state.textureUnit = -1;\n }\n else if (key == Material::Block::Pass)\n {\n part = MP_Pass;\n state.pass++;\n state.textureUnit = -1;\n }\n else if (key == Material::Block::TextureUnit)\n {\n part = MP_TextureUnit;\n state.textureUnit++;\n }\n else if (key == Material::Block::VertexProgram)\n part = MP_VertexProgram;\n else if (key == Material::Block::FragmentProgram)\n part = MP_FragmentProgram;\n else if (key == Material::Block::DefaultParameters)\n part = MP_DefaultParameters;\n\n state.block = new MaterialBlock(state.block, part, state.technique, state.pass, state.textureUnit);\n state.block->id = value;\n\n if (!root && part == MP_Material)\n root = state.block;\n\n \/\/LogInfoF(\" tech %d pass %d tu %d\", state.block->technique, state.block->pass, state.block->textureUnit);\n return true;\n }\n else if (value.Empty())\n {\n LogWarningF(\"Ogre::MaterialParser: Invalid script token '%s' without a value on line %d before column %d\", keyStr.CString(), lineNum, pos);\n return true;\n }\n \/\/ Material not yet started\n if (!state.block)\n return true;\n\n \/\/ Add property to current block\n state.block->propertyNames[key] = keyStr;\n state.block->properties[key].Push(value);\n return true;\n}\n\n}\n\n}\nMaterialParser: Clarify in warning message that we are only skipping this one invalid token.\/\/ For conditions of distribution and use, see copyright notice in LICENSE\n\n#include \"StableHeaders.h\"\n#include \"OgreMaterialDefines.h\"\n#include \"CoreStringUtils.h\"\n#include \"LoggingFunctions.h\"\n\n#include \n\nnamespace Tundra\n{\n\nnamespace Ogre\n{\n\n\/\/ MaterialBlock\n\nMaterialBlock::MaterialBlock(MaterialBlock *parent_, MaterialPart part_, int t, int p, int tu) : \n parent(parent_),\n part(part_),\n technique(t),\n pass(p),\n textureUnit(tu)\n{\n}\n\nMaterialBlock::~MaterialBlock()\n{\n for(uint i=0; ipart == part)\n num++;\n }\n return num;\n}\n\nuint MaterialBlock::NumTechniques() const\n{\n return NumChildren(MP_Technique);\n}\n\nuint MaterialBlock::NumPasses() const\n{\n return NumChildren(MP_Pass);\n}\n\nuint MaterialBlock::NumTextureUnits() const\n{\n return NumChildren(MP_TextureUnit);\n}\n\nMaterialBlock *MaterialBlock::Technique(uint index) const\n{\n foreach(MaterialBlock *block, blocks)\n {\n if (block->part == MP_Technique && block->technique == static_cast(index))\n return block;\n }\n return nullptr;\n}\n\nMaterialBlock *MaterialBlock::Pass(uint index) const\n{\n foreach(MaterialBlock *block, blocks)\n {\n if (block->part == MP_Pass && block->pass == static_cast(index))\n return block;\n }\n return nullptr;\n}\n\nMaterialBlock *MaterialBlock::TextureUnit(uint index) const\n{\n foreach(MaterialBlock *block, blocks)\n {\n if (block->part == MP_TextureUnit && block->textureUnit == static_cast(index))\n return block;\n }\n return nullptr;\n}\n\nMaterialBlock *MaterialBlock::VertexProgram() const\n{\n foreach(MaterialBlock *block, blocks)\n {\n if (block->part == MP_VertexProgram)\n return block;\n }\n return nullptr;\n}\n\nMaterialBlock *MaterialBlock::FragmentProgram() const\n{\n foreach(MaterialBlock *block, blocks)\n {\n if (block->part == MP_FragmentProgram)\n return block;\n }\n return nullptr;\n}\n\nuint MaterialBlock::Num(const StringHash &name) const\n{\n MaterialProperties::ConstIterator iter = properties.Find(name);\n if (iter != properties.End())\n return iter->second_.Size();\n return 0;\n}\n\nbool MaterialBlock::Has(const StringHash &name) const\n{\n return (Num(name) > 0);\n}\n\nString MaterialBlock::StringValue(const StringHash &name, const String &defaultValue, uint index) const\n{\n MaterialProperties::ConstIterator iter = properties.Find(name);\n if (iter != properties.End() && index < iter->second_.Size())\n return iter->second_[index];\n return defaultValue;\n}\n\nStringVector MaterialBlock::StringVectorValue(const StringHash &name, uint index) const\n{\n String value = StringValue(name, \"\", index).Trimmed();\n StringVector parts = (!value.Empty() ? value.Split(' ') : StringVector());\n \/\/ Remove empty parts to correctly parse \"1.0 1.0 1.0 1.0\" type of values\n for(auto iter = parts.Begin(); iter != parts.End();)\n {\n *iter = iter->Trimmed();\n if (iter->Empty())\n iter = parts.Erase(iter);\n else\n iter++;\n }\n return parts;\n}\n\nUrho3D::Vector2 MaterialBlock::Vector2Value(const StringHash &name, const Urho3D::Vector2 &defaultValue, uint index) const\n{\n StringVector parts = StringVectorValue(name, index);\n if (parts.Size() >= 2)\n return Urho3D::Vector2(Urho3D::ToFloat(parts[0]), Urho3D::ToFloat(parts[1]));\n return defaultValue;\n}\n\nUrho3D::Vector3 MaterialBlock::Vector3Value(const StringHash &name, const Urho3D::Vector3 &defaultValue, uint index) const\n{\n StringVector parts = StringVectorValue(name, index);\n if (parts.Size() >= 3)\n return Urho3D::Vector3(Urho3D::ToFloat(parts[0]), Urho3D::ToFloat(parts[1]), Urho3D::ToFloat(parts[2]));\n return defaultValue;\n}\n\nUrho3D::Vector4 MaterialBlock::Vector4Value(const StringHash &name, const Urho3D::Vector4 &defaultValue, uint index) const\n{\n StringVector parts = StringVectorValue(name, index);\n if (parts.Size() >= 4)\n return Urho3D::Vector4(Urho3D::ToFloat(parts[0]), Urho3D::ToFloat(parts[1]), Urho3D::ToFloat(parts[2]), Urho3D::ToFloat(parts[3]));\n return defaultValue;\n}\n\nUrho3D::Color MaterialBlock::ColorValue(const StringHash &name, const Urho3D::Color &defaultValue, uint index) const\n{\n StringVector parts = StringVectorValue(name, index);\n if (parts.Size() >= 3)\n {\n Urho3D::Color color(Urho3D::ToFloat(parts[0]), Urho3D::ToFloat(parts[1]), Urho3D::ToFloat(parts[2]));\n if (parts.Size() >= 4)\n color.a_ = Urho3D::ToFloat(parts[3]);\n return color;\n }\n return defaultValue;\n}\n\nbool MaterialBlock::BooleanValue(const StringHash &name, bool defaultValue, uint index) const\n{\n String value = StringValue(name, \"\", index).Trimmed();\n if (value.Compare(\"on\", false) == 0 || value.Compare(\"enabled\", false) == 0 || value.Compare(\"true\", false) == 0 || value.Compare(\"1\", false) == 0)\n return true;\n else if (value.Compare(\"off\", false) == 0 || value.Compare(\"disabled\", false) == 0 || value.Compare(\"false\", false) == 0 || value.Compare(\"0\", false) == 0)\n return false;\n return defaultValue;\n}\n\nvoid MaterialBlock::Dump(bool recursive, uint indentation)\n{\n String ind = \"\";\n while(ind.Length() < indentation) ind += \" \";\n\n LogInfoF(\"%s%s '%s'\", ind.CString(), MaterialPartToString(part).CString(), id.CString());\n\n indentation += 2;\n while(ind.Length() < indentation) ind += \" \";\n\n for (auto iter = properties.Begin(); iter != properties.End(); ++iter)\n {\n const StringVector &values = iter->second_;\n if (!values.Empty())\n {\n for (uint vi=0; vifirst_], 20).CString(), values[vi].CString());\n else\n LogInfoF(\"%s%s '%s'\", ind.CString(), propertyNames[iter->first_].CString(), values[vi].CString());\n }\n }\n }\n\n if (recursive)\n {\n for (auto iter = blocks.Begin(); iter != blocks.End(); ++iter)\n (*iter)->Dump(recursive, indentation);\n }\n\n indentation -= 2;\n if (indentation == 0)\n LogInfo(\"\");\n}\n\n\/\/ MaterialParser\n\nMaterialParser::MaterialParser() :\n root(0)\n{\n}\n\nMaterialParser::~MaterialParser()\n{\n SAFE_DELETE(root);\n}\n\nString MaterialParser::Error() const\n{\n return state.error;\n}\n\nbool MaterialParser::Parse(const char *data_, uint lenght_)\n{\n data = String(data_, lenght_);\n pos = 0;\n lineNum = 0;\n\n SAFE_DELETE(root);\n\n for(;;)\n {\n if (!ProcessLine())\n break;\n }\n\n \/\/ Make root safe even on failure\n if (!root)\n root = new MaterialBlock();\n\n return (state.error.Length() == 0);\n}\n\nvoid MaterialParser::Advance()\n{\n uint endPos = data.Find('\\n', pos);\n if (endPos == String::NPOS || endPos < pos)\n {\n pos = String::NPOS;\n return;\n }\n \/\/ Empty line with only \\n at the start\n else if (endPos == pos)\n {\n pos += 1;\n line = \"\";\n return;\n }\n line = data.Substring(pos, endPos - pos - (data[endPos-1] == '\\r' ? 1 : 0)).Trimmed();\n pos = endPos + 1;\n lineNum++;\n}\n\nvoid MaterialParser::SkipBlock()\n{\n uint endPos = data.Find('}', pos);\n if (endPos == String::NPOS || endPos < pos)\n {\n state.error = Urho3D::ToString(\"Failed to find Block scope end '}', started looking from index %d\", pos);\n pos = String::NPOS;\n return;\n }\n \/\/ There is a newline after found '}' advance over it.\n pos = endPos + 1;\n Advance();\n}\n\nbool IsBlockIndentifier(const StringHash &hash)\n{\n return (hash == Material::Block::Material\n || hash == Material::Block::Technique\n || hash == Material::Block::Pass\n || hash == Material::Block::TextureUnit\n || hash == Material::Block::VertexProgram\n || hash == Material::Block::FragmentProgram\n || hash == Material::Block::DefaultParameters);\n}\n\nbool MaterialParser::ProcessLine()\n{\n \/\/ Read next line\n Advance();\n\n \/\/ No more lines?\n if (pos == String::NPOS)\n return false;\n else if (line.Empty())\n return true;\n\n \/*if (lineNum < 10)\n PrintRaw(\" \" + String(lineNum) + \" '\" + line + \"'\\n\");\n else\n PrintRaw(String(lineNum) + \" '\" + line + \"'\\n\");*\/\n\n \/\/ Filter comments. Spec only allows single line comments.\n if (line.Length() > 1 && line[0] == '\/' && line[1] == '\/')\n return true;\n\n \/\/ Block scope end\n if (line[0] == '}')\n {\n \/\/ Material not yet started\n if (!state.block)\n return true;\n\n \/\/ Store parsed block to parent\n if (state.block->parent)\n state.block->parent->blocks.Push(state.block);\n\n \/\/ If traversed back to root we are done.\n \/\/\/ @todo If we want to parse multiple materials from a single file change this logic.\n state.block = state.block->parent;\n return (state.block != 0);\n }\n \/\/ Block scope start\n else if (line[0] == '{')\n {\n \/\/ Material not yet started\n if (!state.block)\n return true;\n\n \/\/ Skip invalid blocks\n if (!state.block || !state.block->IsSupported())\n SkipBlock();\n return true;\n }\n\n \/\/ Split to \" \" from the first space.\n \/\/ Note that value can contain spaces, it is stored as is.\n uint splitPos = line.Find(' ');\n String keyStr = (splitPos == String::NPOS ? line : line.Substring(0, splitPos).ToLower());\n StringHash key(keyStr);\n String value = (splitPos == String::NPOS ? \"\" : line.Substring(splitPos+1));\n \n \/\/ Do not begin default_params block if material not started yet\n if (key == Material::Block::DefaultParameters && !state.block)\n return true;\n\n \/\/ Is this a new block scope identifier?\n if (IsBlockIndentifier(key))\n {\n MaterialPart part = MP_Unsupported;\n\n \/\/ Detect block type\n if (key == Material::Block::Material)\n {\n \/\/\/ @todo http:\/\/www.ogre3d.org\/docs\/manual\/manual_25.html#Script-Inheritance\n part = MP_Material;\n state.technique = -1;\n state.pass = -1;\n state.textureUnit = -1;\n }\n else if (key == Material::Block::Technique)\n {\n part = MP_Technique;\n state.technique++;\n state.pass = -1;\n state.textureUnit = -1;\n }\n else if (key == Material::Block::Pass)\n {\n part = MP_Pass;\n state.pass++;\n state.textureUnit = -1;\n }\n else if (key == Material::Block::TextureUnit)\n {\n part = MP_TextureUnit;\n state.textureUnit++;\n }\n else if (key == Material::Block::VertexProgram)\n part = MP_VertexProgram;\n else if (key == Material::Block::FragmentProgram)\n part = MP_FragmentProgram;\n else if (key == Material::Block::DefaultParameters)\n part = MP_DefaultParameters;\n\n state.block = new MaterialBlock(state.block, part, state.technique, state.pass, state.textureUnit);\n state.block->id = value;\n\n if (!root && part == MP_Material)\n root = state.block;\n\n \/\/LogInfoF(\" tech %d pass %d tu %d\", state.block->technique, state.block->pass, state.block->textureUnit);\n return true;\n }\n else if (value.Empty())\n {\n LogWarningF(\"Ogre::MaterialParser: Skipping invalid script token '%s' without a value on line %d before column %d\", keyStr.CString(), lineNum, pos);\n return true;\n }\n \/\/ Material not yet started\n if (!state.block)\n return true;\n\n \/\/ Add property to current block\n state.block->propertyNames[key] = keyStr;\n state.block->properties[key].Push(value);\n return true;\n}\n\n}\n\n}\n<|endoftext|>"} {"text":"#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\n#include \n\n#define BOOST_TEST_DYN_LINK\n\n#include \n\n#include \"TestingUtils.h\"\n\n\nconst char* g_input_file = 0;\nconst char* g_output_dir = 0;\nbool g_dont_exit = false;\n\nstruct StopDialog\n{\n StopDialog(GG::Wnd* dialog, const std::string& output) :\n m_dialog(dialog),\n m_output(output)\n {}\n void operator()(unsigned int, GG::Timer*)\n {\n GG::GUI::GetGUI()->SaveWndAsPNG(m_dialog, m_output);\n m_dialog->EndRun();\n }\n GG::Wnd* m_dialog;\n std::string m_output;\n};\n\nclass MinimalGGApp : public GG::SDLGUI\n{\npublic:\n MinimalGGApp();\n\n virtual void Enter2DMode();\n virtual void Exit2DMode();\n\nprivate:\n virtual void GLInit();\n virtual void Initialize();\n virtual void FinalCleanup();\n};\n\nMinimalGGApp::MinimalGGApp() : \n SDLGUI(1024, 768, false, \"Minimal GG App\")\n{}\n\nvoid MinimalGGApp::Enter2DMode()\n{\n glPushAttrib(GL_ENABLE_BIT | GL_PIXEL_MODE_BIT | GL_TEXTURE_BIT);\n glDisable(GL_DEPTH_TEST);\n glDisable(GL_LIGHTING);\n glDisable(GL_CULL_FACE);\n glEnable(GL_TEXTURE_2D);\n\n glEnable(GL_BLEND);\n glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);\n\n glViewport(0, 0, Value(AppWidth()), Value(AppHeight()));\n\n glMatrixMode(GL_PROJECTION);\n glPushMatrix();\n glLoadIdentity();\n\n glOrtho(0.0, Value(AppWidth()), Value(AppHeight()), 0.0, 0.0, Value(AppWidth()));\n\n glMatrixMode(GL_MODELVIEW);\n glPushMatrix();\n glLoadIdentity();\n}\n\nvoid MinimalGGApp::Exit2DMode()\n{\n glMatrixMode(GL_MODELVIEW);\n glPopMatrix();\n glMatrixMode(GL_PROJECTION);\n glPopMatrix();\n glPopAttrib();\n}\n\nvoid MinimalGGApp::GLInit()\n{\n double ratio = Value(AppWidth() * 1.0) \/ Value(AppHeight());\n\n glEnable(GL_BLEND);\n glEnable(GL_CULL_FACE);\n glEnable(GL_DEPTH_TEST);\n glClearColor(0, 0, 0, 0);\n glViewport(0, 0, Value(AppWidth()), Value(AppHeight()));\n glMatrixMode(GL_PROJECTION);\n glLoadIdentity();\n gluPerspective(50.0, ratio, 1.0, 10.0);\n gluLookAt(0.0, 0.0, 5.0,\n 0.0, 0.0, 0.0,\n 0.0, 1.0, 0.0);\n glMatrixMode(GL_MODELVIEW);\n}\n\nvoid MinimalGGApp::Initialize()\n{\n adobe::sheet_t sheet;\n GG::EveLayout layout(sheet);\n adobe::eve_callback_suite_t callbacks = layout.BindCallbacks();\n std::string file_contents = read_file(g_input_file);\n GG::Wnd* w = 0;\n if (GG::Parse(file_contents, g_input_file, w, callbacks)) {\n GG::Wnd& eve_dialog = layout.Finish();\n boost::filesystem::path input(g_input_file);\n boost::filesystem::path output(g_output_dir);\n#if defined(BOOST_FILESYSTEM_VERSION) && BOOST_FILESYSTEM_VERSION == 3\n output \/= input.stem().native() + \".png\";\n#else\n output \/= input.stem() + \".png\";\n#endif\n GG::Timer timer(100);\n if (!g_dont_exit)\n GG::Connect(timer.FiredSignal, StopDialog(&eve_dialog, output.string()));\n eve_dialog.Run();\n }\n Exit(0);\n}\n\nvoid MinimalGGApp::FinalCleanup()\n{}\n\nBOOST_AUTO_TEST_CASE( eve_layout )\n{\n MinimalGGApp app;\n app();\n}\n\n\/\/ Most of this is boilerplate cut-and-pasted from Boost.Test. We need to\n\/\/ select which test(s) to do, so we can't use it here unmodified.\n\n#ifdef BOOST_TEST_ALTERNATIVE_INIT_API\nbool init_unit_test() {\n#else\n::boost::unit_test::test_suite*\ninit_unit_test_suite( int, char* [] ) {\n#endif\n\n#ifdef BOOST_TEST_MODULE\n using namespace ::boost::unit_test;\n assign_op( framework::master_test_suite().p_name.value, BOOST_TEST_STRINGIZE( BOOST_TEST_MODULE ).trim( \"\\\"\" ), 0 );\n \n#endif\n\n#ifdef BOOST_TEST_ALTERNATIVE_INIT_API\n return true;\n}\n#else\n return 0;\n}\n#endif\n\nint BOOST_TEST_CALL_DECL\nmain( int argc, char* argv[] )\n{\n g_input_file = argv[1];\n g_output_dir = argv[2];\n if (argc == 4)\n g_dont_exit = true;\n return ::boost::unit_test::unit_test_main( &init_unit_test, argc, argv );\n}\nChanged Eve layout test to use GG::MakeDialog() instead of EveLayout.#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\n#include \n\n#define BOOST_TEST_DYN_LINK\n\n#include \n\n#include \"TestingUtils.h\"\n\n\nconst char* g_input_file = 0;\nconst char* g_output_dir = 0;\nbool g_dont_exit = false;\n\nstruct StopDialog\n{\n StopDialog(GG::Wnd* dialog, const std::string& output) :\n m_dialog(dialog),\n m_output(output)\n {}\n void operator()(unsigned int, GG::Timer*)\n {\n GG::GUI::GetGUI()->SaveWndAsPNG(m_dialog, m_output);\n m_dialog->EndRun();\n }\n GG::Wnd* m_dialog;\n std::string m_output;\n};\n\nclass MinimalGGApp : public GG::SDLGUI\n{\npublic:\n MinimalGGApp();\n\n virtual void Enter2DMode();\n virtual void Exit2DMode();\n\nprivate:\n virtual void GLInit();\n virtual void Initialize();\n virtual void FinalCleanup();\n};\n\nMinimalGGApp::MinimalGGApp() : \n SDLGUI(1024, 768, false, \"Minimal GG App\")\n{}\n\nvoid MinimalGGApp::Enter2DMode()\n{\n glPushAttrib(GL_ENABLE_BIT | GL_PIXEL_MODE_BIT | GL_TEXTURE_BIT);\n glDisable(GL_DEPTH_TEST);\n glDisable(GL_LIGHTING);\n glDisable(GL_CULL_FACE);\n glEnable(GL_TEXTURE_2D);\n\n glEnable(GL_BLEND);\n glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);\n\n glViewport(0, 0, Value(AppWidth()), Value(AppHeight()));\n\n glMatrixMode(GL_PROJECTION);\n glPushMatrix();\n glLoadIdentity();\n\n glOrtho(0.0, Value(AppWidth()), Value(AppHeight()), 0.0, 0.0, Value(AppWidth()));\n\n glMatrixMode(GL_MODELVIEW);\n glPushMatrix();\n glLoadIdentity();\n}\n\nvoid MinimalGGApp::Exit2DMode()\n{\n glMatrixMode(GL_MODELVIEW);\n glPopMatrix();\n glMatrixMode(GL_PROJECTION);\n glPopMatrix();\n glPopAttrib();\n}\n\nvoid MinimalGGApp::GLInit()\n{\n double ratio = Value(AppWidth() * 1.0) \/ Value(AppHeight());\n\n glEnable(GL_BLEND);\n glEnable(GL_CULL_FACE);\n glEnable(GL_DEPTH_TEST);\n glClearColor(0, 0, 0, 0);\n glViewport(0, 0, Value(AppWidth()), Value(AppHeight()));\n glMatrixMode(GL_PROJECTION);\n glLoadIdentity();\n gluPerspective(50.0, ratio, 1.0, 10.0);\n gluLookAt(0.0, 0.0, 5.0,\n 0.0, 0.0, 0.0,\n 0.0, 1.0, 0.0);\n glMatrixMode(GL_MODELVIEW);\n}\n\nbool OkHandler(adobe::name_t name, const adobe::any_regular_t&)\n{ return name == adobe::static_name_t(\"ok\"); }\n\nvoid MinimalGGApp::Initialize()\n{\n std::ifstream eve(g_input_file);\n std::istringstream adam(\"sheet foo\\n\"\n \"{\\n\"\n \"output:\\n\"\n \" result <== { foo: 42 };\\n\"\n \"}\");\n GG::Wnd* eve_dialog = GG::MakeDialog(eve, adam, &OkHandler);\n\n boost::filesystem::path input(g_input_file);\n boost::filesystem::path output(g_output_dir);\n#if defined(BOOST_FILESYSTEM_VERSION) && BOOST_FILESYSTEM_VERSION == 3\n output \/= input.stem().native() + \".png\";\n#else\n output \/= input.stem() + \".png\";\n#endif\n GG::Timer timer(100);\n if (!g_dont_exit)\n GG::Connect(timer.FiredSignal, StopDialog(eve_dialog, output.string()));\n eve_dialog->Run();\n\n Exit(0);\n}\n\nvoid MinimalGGApp::FinalCleanup()\n{}\n\nBOOST_AUTO_TEST_CASE( eve_layout )\n{\n MinimalGGApp app;\n app();\n}\n\n\/\/ Most of this is boilerplate cut-and-pasted from Boost.Test. We need to\n\/\/ select which test(s) to do, so we can't use it here unmodified.\n\n#ifdef BOOST_TEST_ALTERNATIVE_INIT_API\nbool init_unit_test() {\n#else\n::boost::unit_test::test_suite*\ninit_unit_test_suite( int, char* [] ) {\n#endif\n\n#ifdef BOOST_TEST_MODULE\n using namespace ::boost::unit_test;\n assign_op( framework::master_test_suite().p_name.value, BOOST_TEST_STRINGIZE( BOOST_TEST_MODULE ).trim( \"\\\"\" ), 0 );\n \n#endif\n\n#ifdef BOOST_TEST_ALTERNATIVE_INIT_API\n return true;\n}\n#else\n return 0;\n}\n#endif\n\nint BOOST_TEST_CALL_DECL\nmain( int argc, char* argv[] )\n{\n g_input_file = argv[1];\n g_output_dir = argv[2];\n if (argc == 4)\n g_dont_exit = true;\n return ::boost::unit_test::unit_test_main( &init_unit_test, argc, argv );\n}\n<|endoftext|>"} {"text":"#ifndef ITER_ACCUMULATE_H_\n#define ITER_ACCUMULATE_H_\n\n#include \"internal\/iterator_wrapper.hpp\"\n#include \"internal\/iterbase.hpp\"\n\n#include \n#include \n#include \n#include \n#include \n\nnamespace iter {\n namespace impl {\n template \n class Accumulator;\n\n using AccumulateFn = IterToolFnOptionalBindSecond>;\n }\n constexpr impl::AccumulateFn accumulate{};\n}\n\ntemplate \nclass iter::impl::Accumulator {\n private:\n Container container_;\n mutable AccumulateFunc accumulate_func_;\n\n friend AccumulateFn;\n\n using AccumVal = std::remove_reference_t, iterator_deref)>>;\n\n Accumulator(Container&& container, AccumulateFunc accumulate_func)\n : container_(std::forward(container)),\n accumulate_func_(accumulate_func) {}\n\n public:\n Accumulator(Accumulator&&) = default;\n\n template \n class Iterator {\n private:\n template \n friend class Iterator;\n IteratorWrapper sub_iter_;\n IteratorWrapper sub_end_;\n AccumulateFunc* accumulate_func_;\n std::optional acc_val_;\n\n public:\n using iterator_category = std::input_iterator_tag;\n using value_type = AccumVal;\n using difference_type = std::ptrdiff_t;\n using pointer = value_type*;\n using reference = value_type&;\n\n Iterator(IteratorWrapper&& sub_iter,\n IteratorWrapper&& sub_end, AccumulateFunc& accumulate_fun)\n : sub_iter_{std::move(sub_iter)},\n sub_end_{std::move(sub_end)},\n accumulate_func_(&accumulate_fun),\n \/\/ only get first value if not an end iterator\n acc_val_{!(sub_iter_ != sub_end_)\n ? std::nullopt\n : std::make_optional(*sub_iter_)} {}\n\n const AccumVal& operator*() const {\n return *acc_val_;\n }\n\n const AccumVal* operator->() const {\n return &*acc_val_;\n }\n\n Iterator& operator++() {\n ++sub_iter_;\n if (sub_iter_ != sub_end_) {\n *acc_val_ = (*accumulate_func_)(*acc_val_, *sub_iter_);\n }\n return *this;\n }\n\n Iterator operator++(int) {\n auto ret = *this;\n ++*this;\n return ret;\n }\n\n template \n bool operator!=(const Iterator& other) const {\n return sub_iter_ != other.sub_iter_;\n }\n\n template \n bool operator==(const Iterator& other) const {\n return !(*this != other);\n }\n };\n\n Iterator begin() {\n return {get_begin(container_), get_end(container_), accumulate_func_};\n }\n\n Iterator end() {\n return {get_end(container_), get_end(container_), accumulate_func_};\n }\n Iterator> begin() const {\n return {get_begin(std::as_const(container_)),\n get_end(std::as_const(container_)), accumulate_func_};\n }\n\n Iterator> end() const {\n return {get_end(std::as_const(container_)),\n get_end(std::as_const(container_)), accumulate_func_};\n }\n};\n\n#endif\nUses std::invoke in accumulate#ifndef ITER_ACCUMULATE_H_\n#define ITER_ACCUMULATE_H_\n\n#include \"internal\/iterator_wrapper.hpp\"\n#include \"internal\/iterbase.hpp\"\n\n#include \n#include \n#include \n#include \n#include \n\nnamespace iter {\n namespace impl {\n template \n class Accumulator;\n\n using AccumulateFn = IterToolFnOptionalBindSecond>;\n }\n constexpr impl::AccumulateFn accumulate{};\n}\n\ntemplate \nclass iter::impl::Accumulator {\n private:\n Container container_;\n mutable AccumulateFunc accumulate_func_;\n\n friend AccumulateFn;\n\n using AccumVal = std::remove_reference_t, iterator_deref)>>;\n\n Accumulator(Container&& container, AccumulateFunc accumulate_func)\n : container_(std::forward(container)),\n accumulate_func_(accumulate_func) {}\n\n public:\n Accumulator(Accumulator&&) = default;\n\n template \n class Iterator {\n private:\n template \n friend class Iterator;\n IteratorWrapper sub_iter_;\n IteratorWrapper sub_end_;\n AccumulateFunc* accumulate_func_;\n std::optional acc_val_;\n\n public:\n using iterator_category = std::input_iterator_tag;\n using value_type = AccumVal;\n using difference_type = std::ptrdiff_t;\n using pointer = value_type*;\n using reference = value_type&;\n\n Iterator(IteratorWrapper&& sub_iter,\n IteratorWrapper&& sub_end, AccumulateFunc& accumulate_fun)\n : sub_iter_{std::move(sub_iter)},\n sub_end_{std::move(sub_end)},\n accumulate_func_(&accumulate_fun),\n \/\/ only get first value if not an end iterator\n acc_val_{!(sub_iter_ != sub_end_)\n ? std::nullopt\n : std::make_optional(*sub_iter_)} {}\n\n const AccumVal& operator*() const {\n return *acc_val_;\n }\n\n const AccumVal* operator->() const {\n return &*acc_val_;\n }\n\n Iterator& operator++() {\n ++sub_iter_;\n if (sub_iter_ != sub_end_) {\n *acc_val_ = std::invoke(*accumulate_func_, *acc_val_, *sub_iter_);\n }\n return *this;\n }\n\n Iterator operator++(int) {\n auto ret = *this;\n ++*this;\n return ret;\n }\n\n template \n bool operator!=(const Iterator& other) const {\n return sub_iter_ != other.sub_iter_;\n }\n\n template \n bool operator==(const Iterator& other) const {\n return !(*this != other);\n }\n };\n\n Iterator begin() {\n return {get_begin(container_), get_end(container_), accumulate_func_};\n }\n\n Iterator end() {\n return {get_end(container_), get_end(container_), accumulate_func_};\n }\n Iterator> begin() const {\n return {get_begin(std::as_const(container_)),\n get_end(std::as_const(container_)), accumulate_func_};\n }\n\n Iterator> end() const {\n return {get_end(std::as_const(container_)),\n get_end(std::as_const(container_)), accumulate_func_};\n }\n};\n\n#endif\n<|endoftext|>"} {"text":"\/**\n * These codes are licensed under the Unlicense.\n * http:\/\/unlicense.org\n *\/\n\n#ifndef FURFURYLIC_GUARD_E8F031F6_10D8_4585_9012_CFADC2F95BA7\n#define FURFURYLIC_GUARD_E8F031F6_10D8_4585_9012_CFADC2F95BA7\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"formatted_output.hpp\"\n\nnamespace furfurylic {\nnamespace commata {\nnamespace detail {\n\ntemplate \nstruct npos_impl\n{\n constexpr static T npos = static_cast(-1);\n};\n\n\/\/ To define this in a header, npos_impl is a template\ntemplate \nconstexpr T npos_impl::npos;\n\n} \/\/ end namespace detail\n\nclass text_error;\n\nclass text_error_info\n{\n const text_error* ex_;\n\npublic:\n explicit text_error_info(const text_error& ex) noexcept :\n ex_(&ex)\n {}\n\n text_error_info(const text_error_info& ex) noexcept = default;\n text_error_info& operator=(const text_error_info& ex) noexcept = default;\n\n const text_error& error() const noexcept\n {\n return *ex_;\n }\n};\n\nclass text_error :\n public std::exception, public detail::npos_impl\n{\n std::shared_ptr what_;\n std::pair physical_position_;\n\npublic:\n template ::value>>\n explicit text_error(T&& what_arg) :\n what_(std::make_shared(std::forward(what_arg))),\n physical_position_(npos, npos)\n {}\n\n \/\/ Copy\/move ctors and copy\/move assignment ops are explicitly defined\n \/\/ so that they are noexcept\n\n text_error(const text_error& other) noexcept :\n std::exception(other),\n what_(other.what_),\n physical_position_(other.physical_position_)\n \/\/ According to C++14 20.3.2 (1), pair's copy ctor is noexcept\n {}\n\n text_error(text_error&& other) noexcept :\n std::exception(std::move(other)),\n what_(std::move(other.what_)),\n physical_position_(other.physical_position_)\n \/\/ ditto\n {}\n\n text_error& operator=(const text_error& other) noexcept\n {\n std::exception::operator=(other);\n what_ = other.what_;\n physical_position_ = other.physical_position_;\n \/\/ According to C++14 20.3.2 (1), pair's assignments are noexcept\n return *this;\n }\n\n text_error& operator=(text_error&& other) noexcept\n {\n std::exception::operator=(std::move(other));\n what_ = std::move(other.what_);\n physical_position_ = other.physical_position_;\n \/\/ ditto\n return *this;\n }\n\n const char* what() const noexcept override\n {\n return what_->c_str(); \/\/ std::string::c_str is noexcept\n }\n\n void set_physical_position(std::size_t line = npos, std::size_t col = npos)\n {\n physical_position_ = std::make_pair(line, col);\n }\n\n const std::pair* get_physical_position() const\n noexcept\n {\n \/\/ std::make_pair shall not throw exceptions\n return (physical_position_ != std::make_pair(npos, npos)) ?\n &physical_position_ : nullptr;\n }\n\n text_error_info info() const noexcept\n {\n return text_error_info(*this);\n }\n};\n\nnamespace detail {\n\n\/\/ Prints a non-negative integer value in the decimal system\n\/\/ into a sufficient-length buffer\ntemplate \nstd::streamsize print_pos(char (&s)[N], std::size_t pos)\n{\n const auto len = (pos != text_error::npos) ?\n std::snprintf(s, N, \"%zu\", pos + 1) :\n std::snprintf(s, N, \"n\/a\");\n assert((len > 0 ) && (static_cast(len) < N));\n return static_cast(len);\n}\n\ntemplate \nstd::streamsize print_pos(wchar_t (&s)[N], std::size_t pos)\n{\n const auto len = (pos != text_error::npos) ?\n std::swprintf(s, N, L\"%zu\", pos + 1) :\n std::swprintf(s, N, L\"n\/a\");\n assert((len > 0 ) && (static_cast(len) < N));\n return static_cast(len);\n}\n\n} \/\/ end namespace detail\n\ntemplate \nstd::basic_ostream& operator<<(\n std::basic_ostream& os, const text_error_info& i)\n{\n if (const auto p = i.error().get_physical_position()) {\n \/\/ line\n char l[std::numeric_limits::digits10 + 2];\n const auto l_len = detail::print_pos(l, p->first);\n\n \/\/ column\n char c[sizeof(l)];\n const auto c_len = detail::print_pos(c, p->second);\n\n \/\/ what\n const auto w = i.error().what();\n const auto w_len = static_cast(std::strlen(w));\n\n const auto n = w_len + l_len + c_len + ((w_len > 0) ? 15 : 27);\n\n return detail::formatted_output(os, n,\n [w, w_len, l = &l[0], l_len, c = &c[0], c_len]\n (auto* sb) {\n if (w_len > 0) {\n if ((sb->sputn(w, w_len) != w_len)\n || (sb->sputn(\"; line \", 7) != 7)) {\n return false;\n }\n } else if (sb->sputn(\"Text error at line \", 19) != 19) {\n return false;\n }\n return (sb->sputn(l, l_len) == l_len)\n && (sb->sputn(\" column \", 8) == 8)\n && (sb->sputn(c, c_len) == c_len);\n });\n\n } else {\n return os << i.error().what();\n }\n}\n\ntemplate \nstd::basic_ostream& operator<<(\n std::basic_ostream& os, const text_error_info& i)\n{\n \/\/ Count the wide characters in what, which may be an NTMBS\n auto w_raw = i.error().what();\n#ifdef _MSC_VER\n#pragma warning(push)\n#pragma warning(disable:4996)\n#endif\n auto w_len = static_cast(std::mbstowcs(0, w_raw, 0));\n#ifdef _MSC_VER\n#pragma warning(pop)\n#endif\n if (w_len == -1) {\n \/\/ Conversion failed\n w_raw = \"\";\n w_len = 0;\n }\n\n if (const auto p = i.error().get_physical_position()) {\n \/\/ line\n wchar_t l[std::numeric_limits::digits10 + 2];\n const auto l_len = detail::print_pos(l, p->first);\n\n \/\/ column\n wchar_t c[sizeof(l)];\n const auto c_len = detail::print_pos(c, p->second);\n\n const auto n = w_len + l_len + c_len + ((w_len > 0) ? 15 : 27);\n\n return detail::formatted_output(os, n,\n [w_raw, w_len, l = &l[0], l_len, c = &c[0], c_len]\n (auto* sb) {\n if (w_len > 0) {\n std::unique_ptr w(\n new wchar_t[w_len + 1]); \/\/ throw\n#ifdef _MSC_VER\n#pragma warning(push)\n#pragma warning(disable:4996)\n#endif\n std::mbstowcs(w.get(), w_raw, w_len);\n#ifdef _MSC_VER\n#pragma warning(pop)\n#endif\n w[w_len] = L'\\0'; \/\/ maybe not required\n if ((sb->sputn(w.get(), w_len) != w_len)\n || (sb->sputn(L\"; line \", 7) != 7)) {\n return false;\n }\n } else if (sb->sputn(L\"Text error at line \", 19) != 19) {\n return false;\n }\n return (sb->sputn(l, l_len) == l_len)\n && (sb->sputn(L\" column \", 8) == 8)\n && (sb->sputn(c, c_len) == c_len);\n });\n\n } else if (w_len > 0) {\n return detail::formatted_output(os, w_len,\n [w_raw, &w_len]\n (auto* sb) {\n std::unique_ptr w(\n new wchar_t[w_len + 1]); \/\/ throw\n#ifdef _MSC_VER\n#pragma warning(push)\n#pragma warning(disable:4996)\n#endif\n std::mbstowcs(w.get(), w_raw, w_len);\n#ifdef _MSC_VER\n#pragma warning(pop)\n#endif\n w[w_len] = L'\\0'; \/\/ maybe not required\n return sb->sputn(w.get(), w_len) == w_len;\n });\n\n } else {\n return os;\n }\n}\n\ninline std::string to_string(const text_error_info& i)\n{\n std::ostringstream s;\n s << i;\n return s.str();\n}\n\ninline std::wstring to_wstring(const text_error_info& i)\n{\n std::wostringstream s;\n s << i;\n return s.str();\n}\n\n}}\n\n#endif\nMake text_error have a \"fluent interface\"\/**\n * These codes are licensed under the Unlicense.\n * http:\/\/unlicense.org\n *\/\n\n#ifndef FURFURYLIC_GUARD_E8F031F6_10D8_4585_9012_CFADC2F95BA7\n#define FURFURYLIC_GUARD_E8F031F6_10D8_4585_9012_CFADC2F95BA7\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"formatted_output.hpp\"\n\nnamespace furfurylic {\nnamespace commata {\nnamespace detail {\n\ntemplate \nstruct npos_impl\n{\n constexpr static T npos = static_cast(-1);\n};\n\n\/\/ To define this in a header, npos_impl is a template\ntemplate \nconstexpr T npos_impl::npos;\n\n} \/\/ end namespace detail\n\nclass text_error;\n\nclass text_error_info\n{\n const text_error* ex_;\n\npublic:\n explicit text_error_info(const text_error& ex) noexcept :\n ex_(&ex)\n {}\n\n text_error_info(const text_error_info& ex) noexcept = default;\n text_error_info& operator=(const text_error_info& ex) noexcept = default;\n\n const text_error& error() const noexcept\n {\n return *ex_;\n }\n};\n\nclass text_error :\n public std::exception, public detail::npos_impl\n{\n std::shared_ptr what_;\n std::pair physical_position_;\n\npublic:\n template ::value>>\n explicit text_error(T&& what_arg) :\n what_(std::make_shared(std::forward(what_arg))),\n physical_position_(npos, npos)\n {}\n\n \/\/ Copy\/move ctors and copy\/move assignment ops are explicitly defined\n \/\/ so that they are noexcept\n\n text_error(const text_error& other) noexcept :\n std::exception(other),\n what_(other.what_),\n physical_position_(other.physical_position_)\n \/\/ According to C++14 20.3.2 (1), pair's copy ctor is noexcept\n {}\n\n text_error(text_error&& other) noexcept :\n std::exception(std::move(other)),\n what_(std::move(other.what_)),\n physical_position_(other.physical_position_)\n \/\/ ditto\n {}\n\n text_error& operator=(const text_error& other) noexcept\n {\n std::exception::operator=(other);\n what_ = other.what_;\n physical_position_ = other.physical_position_;\n \/\/ According to C++14 20.3.2 (1), pair's assignments are noexcept\n return *this;\n }\n\n text_error& operator=(text_error&& other) noexcept\n {\n std::exception::operator=(std::move(other));\n what_ = std::move(other.what_);\n physical_position_ = other.physical_position_;\n \/\/ ditto\n return *this;\n }\n\n const char* what() const noexcept override\n {\n return what_->c_str(); \/\/ std::string::c_str is noexcept\n }\n\n text_error& set_physical_position(\n std::size_t line = npos, std::size_t col = npos)\n {\n physical_position_ = std::make_pair(line, col);\n return *this;\n }\n\n const std::pair* get_physical_position() const\n noexcept\n {\n \/\/ std::make_pair shall not throw exceptions\n return (physical_position_ != std::make_pair(npos, npos)) ?\n &physical_position_ : nullptr;\n }\n\n text_error_info info() const noexcept\n {\n return text_error_info(*this);\n }\n};\n\nnamespace detail {\n\n\/\/ Prints a non-negative integer value in the decimal system\n\/\/ into a sufficient-length buffer\ntemplate \nstd::streamsize print_pos(char (&s)[N], std::size_t pos)\n{\n const auto len = (pos != text_error::npos) ?\n std::snprintf(s, N, \"%zu\", pos + 1) :\n std::snprintf(s, N, \"n\/a\");\n assert((len > 0 ) && (static_cast(len) < N));\n return static_cast(len);\n}\n\ntemplate \nstd::streamsize print_pos(wchar_t (&s)[N], std::size_t pos)\n{\n const auto len = (pos != text_error::npos) ?\n std::swprintf(s, N, L\"%zu\", pos + 1) :\n std::swprintf(s, N, L\"n\/a\");\n assert((len > 0 ) && (static_cast(len) < N));\n return static_cast(len);\n}\n\n} \/\/ end namespace detail\n\ntemplate \nstd::basic_ostream& operator<<(\n std::basic_ostream& os, const text_error_info& i)\n{\n if (const auto p = i.error().get_physical_position()) {\n \/\/ line\n char l[std::numeric_limits::digits10 + 2];\n const auto l_len = detail::print_pos(l, p->first);\n\n \/\/ column\n char c[sizeof(l)];\n const auto c_len = detail::print_pos(c, p->second);\n\n \/\/ what\n const auto w = i.error().what();\n const auto w_len = static_cast(std::strlen(w));\n\n const auto n = w_len + l_len + c_len + ((w_len > 0) ? 15 : 27);\n\n return detail::formatted_output(os, n,\n [w, w_len, l = &l[0], l_len, c = &c[0], c_len]\n (auto* sb) {\n if (w_len > 0) {\n if ((sb->sputn(w, w_len) != w_len)\n || (sb->sputn(\"; line \", 7) != 7)) {\n return false;\n }\n } else if (sb->sputn(\"Text error at line \", 19) != 19) {\n return false;\n }\n return (sb->sputn(l, l_len) == l_len)\n && (sb->sputn(\" column \", 8) == 8)\n && (sb->sputn(c, c_len) == c_len);\n });\n\n } else {\n return os << i.error().what();\n }\n}\n\ntemplate \nstd::basic_ostream& operator<<(\n std::basic_ostream& os, const text_error_info& i)\n{\n \/\/ Count the wide characters in what, which may be an NTMBS\n auto w_raw = i.error().what();\n#ifdef _MSC_VER\n#pragma warning(push)\n#pragma warning(disable:4996)\n#endif\n auto w_len = static_cast(std::mbstowcs(0, w_raw, 0));\n#ifdef _MSC_VER\n#pragma warning(pop)\n#endif\n if (w_len == -1) {\n \/\/ Conversion failed\n w_raw = \"\";\n w_len = 0;\n }\n\n if (const auto p = i.error().get_physical_position()) {\n \/\/ line\n wchar_t l[std::numeric_limits::digits10 + 2];\n const auto l_len = detail::print_pos(l, p->first);\n\n \/\/ column\n wchar_t c[sizeof(l)];\n const auto c_len = detail::print_pos(c, p->second);\n\n const auto n = w_len + l_len + c_len + ((w_len > 0) ? 15 : 27);\n\n return detail::formatted_output(os, n,\n [w_raw, w_len, l = &l[0], l_len, c = &c[0], c_len]\n (auto* sb) {\n if (w_len > 0) {\n std::unique_ptr w(\n new wchar_t[w_len + 1]); \/\/ throw\n#ifdef _MSC_VER\n#pragma warning(push)\n#pragma warning(disable:4996)\n#endif\n std::mbstowcs(w.get(), w_raw, w_len);\n#ifdef _MSC_VER\n#pragma warning(pop)\n#endif\n w[w_len] = L'\\0'; \/\/ maybe not required\n if ((sb->sputn(w.get(), w_len) != w_len)\n || (sb->sputn(L\"; line \", 7) != 7)) {\n return false;\n }\n } else if (sb->sputn(L\"Text error at line \", 19) != 19) {\n return false;\n }\n return (sb->sputn(l, l_len) == l_len)\n && (sb->sputn(L\" column \", 8) == 8)\n && (sb->sputn(c, c_len) == c_len);\n });\n\n } else if (w_len > 0) {\n return detail::formatted_output(os, w_len,\n [w_raw, &w_len]\n (auto* sb) {\n std::unique_ptr w(\n new wchar_t[w_len + 1]); \/\/ throw\n#ifdef _MSC_VER\n#pragma warning(push)\n#pragma warning(disable:4996)\n#endif\n std::mbstowcs(w.get(), w_raw, w_len);\n#ifdef _MSC_VER\n#pragma warning(pop)\n#endif\n w[w_len] = L'\\0'; \/\/ maybe not required\n return sb->sputn(w.get(), w_len) == w_len;\n });\n\n } else {\n return os;\n }\n}\n\ninline std::string to_string(const text_error_info& i)\n{\n std::ostringstream s;\n s << i;\n return s.str();\n}\n\ninline std::wstring to_wstring(const text_error_info& i)\n{\n std::wostringstream s;\n s << i;\n return s.str();\n}\n\n}}\n\n#endif\n<|endoftext|>"} {"text":"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n\nnamespace bts { namespace tscript {\n\nclass client_context\n{\npublic:\n client_context();\n virtual ~client_context();\n \n void configure_client_from_args();\n void start();\n \n std::vector args;\n bts::client::client_ptr client;\n fc::future client_done;\n std::map template_context;\n};\n\ntypedef std::shared_ptr client_context_ptr;\n\nclass context\n{\npublic:\n context();\n virtual ~context();\n\n void set_genesis(const fc::path& genesis_json_filename);\n\n void create_client(const std::string& name);\n fc::path get_data_dir_for_client(const std::string& name) const;\n \n void get_clients_by_variant(const fc::variant& spec, std::vector& result, int depth=0);\n \n fc::path basedir;\n std::vector v_clients;\n std::map m_name_client;\n std::map> m_name_client_group;\n std::map template_context;\n fc::path genesis_json_filename;\n bts::blockchain::genesis_block_config genesis_config;\n bts::net::simulated_network_ptr sim_network;\n};\n\ntypedef std::shared_ptr context_ptr;\n\nclass interpreter\n{\npublic:\n interpreter();\n virtual ~interpreter();\n \n void run_single_command(const fc::variants& cmd);\n void run_command_list(const fc::variants& cmd_list);\n void run_file(const fc::path& path);\n \n void cmd_clients(const fc::variants& args);\n void cmd_x(const fc::variants& cmd);\n \n context_ptr ctx;\n};\n\nclient_context::client_context()\n{\n return;\n}\n\nclient_context::~client_context()\n{\n return;\n}\n\ninline void copy_str_to_buffer_with_0(std::vector &buf, const std::string& s)\n{\n std::copy(s.c_str(), s.c_str()+s.length(), std::back_inserter(buf));\n buf.push_back('\\0');\n return;\n}\n\nvoid client_context::configure_client_from_args()\n{\n std::vector buf;\n std::vector arg_offset;\n \n std::string arg_0 = \"bitshares_client\";\n arg_offset.push_back(0);\n copy_str_to_buffer_with_0(buf, arg_0);\n \n int argc = (int) this->args.size() + 1;\n \n for(int i=1;iargs[i-1]);\n }\n\n std::vector v_argv;\n v_argv.push_back(buf.data());\n for(int i=1;iclient->configure_from_command_line(argc, v_argv.data());\n\n return;\n}\n\nvoid client_context::start()\n{\n this->client_done = this->client->start();\n return;\n}\n\ncontext::context()\n{\n this->sim_network = std::make_shared(\"tscript\");\n this->m_name_client_group[\"all\"] = std::vector();\n this->basedir = \"tmp\";\n return;\n}\n\ncontext::~context()\n{\n return;\n}\n\nvoid context::set_genesis(const fc::path& genesis_json_filename)\n{\n this->genesis_json_filename = genesis_json_filename;\n this->genesis_config = fc::json::from_file(genesis_json_filename).as();\n this->template_context[\"genesis.timestamp\"] = this->genesis_config.timestamp.to_iso_string();\n return;\n}\n\nvoid context::create_client(const std::string& name)\n{\n client_context_ptr cc = std::make_shared();\n cc->args.push_back(\"--disable-default-peers\");\n cc->args.push_back(\"--log-commands\");\n cc->args.push_back(\"--ulog=0\");\n cc->args.push_back(\"--min-delegate-connection-count=0\");\n cc->args.push_back(\"--upnp=false\");\n cc->args.push_back(\"--genesis-config=\" + this->genesis_json_filename.string());\n cc->args.push_back(\"--data-dir=\" + this->get_data_dir_for_client(name).string());\n \n cc->client = std::make_shared(\"tscript\", this->sim_network);\n cc->configure_client_from_args();\n cc->client->set_client_debug_name(name);\n cc->template_context[\"client.name\"] = name;\n\n this->m_name_client[name] = cc;\n this->m_name_client_group[\"all\"].push_back(name);\n\n return;\n}\n\nfc::path context::get_data_dir_for_client(const std::string& name) const\n{\n return this->basedir \/ \"client\" \/ name;\n}\n\nvoid context::get_clients_by_variant(const fc::variant& spec, std::vector& result, int depth)\n{\n FC_ASSERT(depth < 20);\n \n if( spec.is_array() )\n {\n const fc::variants& v = spec.get_array();\n for( const fc::variant& e : v )\n this->get_clients_by_variant(e, result, depth+1);\n return;\n }\n\n if( spec.is_string() )\n {\n std::string target_name = spec.get_string();\n std::cout << \"in spec.is_string() : target=\" << target_name << \"\\n\";\n auto p = this->m_name_client_group.find(target_name);\n if( p != this->m_name_client_group.end() )\n {\n std::cout << \" found group\\n\";\n for( const fc::string& e : p->second )\n {\n auto q = this->m_name_client.find(e);\n if( q != this->m_name_client.end() )\n {\n result.push_back(q->second);\n std::cout << \" group member \" << e << \" found\\n\";\n }\n else\n FC_ASSERT(false, \"couldn't find named client when expanding group definition\");\n }\n return;\n }\n auto q = this->m_name_client.find(target_name);\n if( q != this->m_name_client.end() )\n {\n std::cout << \" found singleton\\n\";\n result.push_back(q->second);\n return;\n }\n FC_ASSERT(false, \"couldn't find named client\");\n }\n \n FC_ASSERT(false, \"expected: client-spec\");\n}\n\ninterpreter::interpreter()\n{\n this->ctx = std::make_shared();\n return;\n}\n\ninterpreter::~interpreter()\n{\n return;\n}\n\nvoid interpreter::run_single_command(const fc::variants& cmd)\n{\n \/\/ parse the command\n std::string action = cmd[0].get_string();\n \n if( action == \"x\")\n {\n this->cmd_x(cmd);\n }\n else if( action == \"!clients\" )\n {\n this->cmd_clients( cmd );\n }\n else if( action == \"!defgroup\" )\n {\n FC_ASSERT(false, \"unimplemented command\");\n }\n else if( action == \"!include\" )\n {\n FC_ASSERT(false, \"unimplemented command\");\n }\n else if( action == \"!pragma\" )\n {\n FC_ASSERT(false, \"unimplemented command\");\n }\n else\n {\n FC_ASSERT(false, \"unknown command\");\n }\n return;\n}\n\nvoid interpreter::run_command_list(const fc::variants& cmd_list)\n{\n for(auto cmd : cmd_list)\n this->run_single_command(cmd.as());\n return;\n}\n\nvoid interpreter::run_file(const fc::path& path)\n{\n fc::variants v = fc::json::from_file(path);\n this->run_command_list(v);\n return;\n}\n\nvoid interpreter::cmd_clients(const fc::variants& cmd)\n{\n FC_ASSERT(cmd.size() >= 2);\n \n fc::variants args = cmd[1].get_array();\n \n \/\/ create clients\n for( const fc::variant& e : args )\n {\n std::string cname = e.as();\n std::cout << \"creating client \" << cname << \"\\n\";\n this->ctx->create_client(cname);\n }\n return;\n}\n\nvoid interpreter::cmd_x(const fc::variants& cmd)\n{\n FC_ASSERT( cmd.size() >= 3 );\n\n std::cout << \"in cmd_x\\n\";\n \n std::vector targets;\n \n this->ctx->get_clients_by_variant( cmd[1], targets );\n\n std::cout << \"targets found: \" << targets.size() << \"\\n\";\n\n for( bts::tscript::client_context_ptr& t : targets )\n {\n std::cout << \" \" << t->client->debug_get_client_name() << \":\\n\";\n\n const std::string& method_name = cmd[2].get_string();\n\n std::cout << \" \" << method_name << \"\\n\";\n \n \/\/ create context for command by combining template context dictionaries\n fc::mutable_variant_object effective_ctx;\n for( auto& e : this->ctx->template_context )\n effective_ctx[e.first] = e.second;\n for( auto& e : t->template_context )\n effective_ctx[e.first] = e.second;\n fc::variant_object v_effective_ctx = effective_ctx;\n \n \/\/ substitute into parameters\n fc::variants args;\n if( cmd.size() >= 4 )\n args = cmd[3].get_array();\n \n for( size_t i=0,n=args.size(); i result;\n fc::optional exc;\n \n try\n {\n result = t->client->get_rpc_server()->direct_invoke_method(method_name, args);\n std::cout << \" result:\" << fc::json::to_string(result) << \"\\n\";\n }\n catch( const fc::exception& e )\n {\n exc = e;\n std::cout << \" \" << e.to_detail_string() << \"\\n\";\n }\n \n std::string cmp_op = \"nop\";\n fc::variant cmp_op_arg;\n if( cmd.size() >= 5 )\n {\n cmp_op = cmd[4].get_string();\n if( cmd.size() >= 6 )\n {\n cmp_op_arg = cmd[5];\n }\n }\n \n bool expected_exception = false;\n \n if( cmp_op == \"nop\" )\n ;\n else if( cmp_op == \"eq\" )\n {\n FC_ASSERT(result.valid());\n std::cout << \"*result : \" << fc::json::to_string(*result) << \"\\n\";\n std::cout << \"cmp_op_arg : \" << fc::json::to_string(cmp_op_arg) << \"\\n\";\n FC_ASSERT(((*result) == cmp_op_arg).as_bool());\n }\n else if( cmp_op == \"ex\" )\n {\n expected_exception = true;\n }\n else if( cmp_op == \"ss\" )\n {\n FC_ASSERT(result.valid());\n FC_ASSERT(cmp_op_arg.is_object());\n FC_ASSERT(result->is_object());\n \n fc::variant_object vo_result = result->get_object();\n for( auto& kv : cmp_op_arg.get_object() )\n {\n auto it = vo_result.find(kv.key());\n FC_ASSERT( it != vo_result.end() );\n FC_ASSERT( (it->value() == kv.value()).as_bool() );\n }\n }\n \n if( (!expected_exception) && (!result.valid()) )\n FC_ASSERT(false, \"terminating due to unexpected exception\");\n }\n std::cout << \"\\n\";\n\n return;\n}\n\nvoid run_single_tscript(\n const fc::path& genesis_json_filename,\n const fc::path& tscript_filename\n )\n{\n FC_ASSERT( fc::is_regular_file(tscript_filename) );\n\n \/\/ delete client directories\n fc::remove_all( \"tmp\/client\" );\n\n bts::tscript::interpreter interp;\n interp.ctx->set_genesis(genesis_json_filename);\n interp.run_file(tscript_filename);\n return;\n}\n\ninline bool startswith(\n const std::string& a,\n const std::string& prefix\n )\n{\n size_t m = prefix.length(), n = a.length();\n return (m <= n) && (0 == a.compare( 0, m, prefix ));\n}\n\ninline bool endswith(\n const std::string& a,\n const std::string& suffix\n )\n{\n size_t m = suffix.length(), n = a.length();\n return (m <= n) && (0 == a.compare( n-m, m, suffix ));\n}\n\nvoid run_tscripts(\n const fc::path& genesis_json_filename,\n const fc::path& target_filename\n )\n{\n if( !fc::is_directory(target_filename) )\n {\n run_single_tscript( genesis_json_filename, target_filename );\n return;\n }\n\n for( fc::recursive_directory_iterator it(target_filename), it_end;\n it != it_end; ++it )\n {\n fc::path filename = (*it);\n if( !fc::is_regular_file(filename) )\n continue;\n if( !endswith(filename.string(), \".tscript\") )\n continue;\n run_single_tscript(genesis_json_filename, filename);\n }\n return;\n}\n\n} }\n\nint main(int argc, char **argv, char **envp)\n{\n for( int i=1; iDisplay argument using fc::json::to_string() instead of as_string()\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n\nnamespace bts { namespace tscript {\n\nclass client_context\n{\npublic:\n client_context();\n virtual ~client_context();\n \n void configure_client_from_args();\n void start();\n \n std::vector args;\n bts::client::client_ptr client;\n fc::future client_done;\n std::map template_context;\n};\n\ntypedef std::shared_ptr client_context_ptr;\n\nclass context\n{\npublic:\n context();\n virtual ~context();\n\n void set_genesis(const fc::path& genesis_json_filename);\n\n void create_client(const std::string& name);\n fc::path get_data_dir_for_client(const std::string& name) const;\n \n void get_clients_by_variant(const fc::variant& spec, std::vector& result, int depth=0);\n \n fc::path basedir;\n std::vector v_clients;\n std::map m_name_client;\n std::map> m_name_client_group;\n std::map template_context;\n fc::path genesis_json_filename;\n bts::blockchain::genesis_block_config genesis_config;\n bts::net::simulated_network_ptr sim_network;\n};\n\ntypedef std::shared_ptr context_ptr;\n\nclass interpreter\n{\npublic:\n interpreter();\n virtual ~interpreter();\n \n void run_single_command(const fc::variants& cmd);\n void run_command_list(const fc::variants& cmd_list);\n void run_file(const fc::path& path);\n \n void cmd_clients(const fc::variants& args);\n void cmd_x(const fc::variants& cmd);\n \n context_ptr ctx;\n};\n\nclient_context::client_context()\n{\n return;\n}\n\nclient_context::~client_context()\n{\n return;\n}\n\ninline void copy_str_to_buffer_with_0(std::vector &buf, const std::string& s)\n{\n std::copy(s.c_str(), s.c_str()+s.length(), std::back_inserter(buf));\n buf.push_back('\\0');\n return;\n}\n\nvoid client_context::configure_client_from_args()\n{\n std::vector buf;\n std::vector arg_offset;\n \n std::string arg_0 = \"bitshares_client\";\n arg_offset.push_back(0);\n copy_str_to_buffer_with_0(buf, arg_0);\n \n int argc = (int) this->args.size() + 1;\n \n for(int i=1;iargs[i-1]);\n }\n\n std::vector v_argv;\n v_argv.push_back(buf.data());\n for(int i=1;iclient->configure_from_command_line(argc, v_argv.data());\n\n return;\n}\n\nvoid client_context::start()\n{\n this->client_done = this->client->start();\n return;\n}\n\ncontext::context()\n{\n this->sim_network = std::make_shared(\"tscript\");\n this->m_name_client_group[\"all\"] = std::vector();\n this->basedir = \"tmp\";\n return;\n}\n\ncontext::~context()\n{\n return;\n}\n\nvoid context::set_genesis(const fc::path& genesis_json_filename)\n{\n this->genesis_json_filename = genesis_json_filename;\n this->genesis_config = fc::json::from_file(genesis_json_filename).as();\n this->template_context[\"genesis.timestamp\"] = this->genesis_config.timestamp.to_iso_string();\n return;\n}\n\nvoid context::create_client(const std::string& name)\n{\n client_context_ptr cc = std::make_shared();\n cc->args.push_back(\"--disable-default-peers\");\n cc->args.push_back(\"--log-commands\");\n cc->args.push_back(\"--ulog=0\");\n cc->args.push_back(\"--min-delegate-connection-count=0\");\n cc->args.push_back(\"--upnp=false\");\n cc->args.push_back(\"--genesis-config=\" + this->genesis_json_filename.string());\n cc->args.push_back(\"--data-dir=\" + this->get_data_dir_for_client(name).string());\n \n cc->client = std::make_shared(\"tscript\", this->sim_network);\n cc->configure_client_from_args();\n cc->client->set_client_debug_name(name);\n cc->template_context[\"client.name\"] = name;\n\n this->m_name_client[name] = cc;\n this->m_name_client_group[\"all\"].push_back(name);\n\n return;\n}\n\nfc::path context::get_data_dir_for_client(const std::string& name) const\n{\n return this->basedir \/ \"client\" \/ name;\n}\n\nvoid context::get_clients_by_variant(const fc::variant& spec, std::vector& result, int depth)\n{\n FC_ASSERT(depth < 20);\n \n if( spec.is_array() )\n {\n const fc::variants& v = spec.get_array();\n for( const fc::variant& e : v )\n this->get_clients_by_variant(e, result, depth+1);\n return;\n }\n\n if( spec.is_string() )\n {\n std::string target_name = spec.get_string();\n std::cout << \"in spec.is_string() : target=\" << target_name << \"\\n\";\n auto p = this->m_name_client_group.find(target_name);\n if( p != this->m_name_client_group.end() )\n {\n std::cout << \" found group\\n\";\n for( const fc::string& e : p->second )\n {\n auto q = this->m_name_client.find(e);\n if( q != this->m_name_client.end() )\n {\n result.push_back(q->second);\n std::cout << \" group member \" << e << \" found\\n\";\n }\n else\n FC_ASSERT(false, \"couldn't find named client when expanding group definition\");\n }\n return;\n }\n auto q = this->m_name_client.find(target_name);\n if( q != this->m_name_client.end() )\n {\n std::cout << \" found singleton\\n\";\n result.push_back(q->second);\n return;\n }\n FC_ASSERT(false, \"couldn't find named client\");\n }\n \n FC_ASSERT(false, \"expected: client-spec\");\n}\n\ninterpreter::interpreter()\n{\n this->ctx = std::make_shared();\n return;\n}\n\ninterpreter::~interpreter()\n{\n return;\n}\n\nvoid interpreter::run_single_command(const fc::variants& cmd)\n{\n \/\/ parse the command\n std::string action = cmd[0].get_string();\n \n if( action == \"x\")\n {\n this->cmd_x(cmd);\n }\n else if( action == \"!clients\" )\n {\n this->cmd_clients( cmd );\n }\n else if( action == \"!defgroup\" )\n {\n FC_ASSERT(false, \"unimplemented command\");\n }\n else if( action == \"!include\" )\n {\n FC_ASSERT(false, \"unimplemented command\");\n }\n else if( action == \"!pragma\" )\n {\n FC_ASSERT(false, \"unimplemented command\");\n }\n else\n {\n FC_ASSERT(false, \"unknown command\");\n }\n return;\n}\n\nvoid interpreter::run_command_list(const fc::variants& cmd_list)\n{\n for(auto cmd : cmd_list)\n this->run_single_command(cmd.as());\n return;\n}\n\nvoid interpreter::run_file(const fc::path& path)\n{\n fc::variants v = fc::json::from_file(path);\n this->run_command_list(v);\n return;\n}\n\nvoid interpreter::cmd_clients(const fc::variants& cmd)\n{\n FC_ASSERT(cmd.size() >= 2);\n \n fc::variants args = cmd[1].get_array();\n \n \/\/ create clients\n for( const fc::variant& e : args )\n {\n std::string cname = e.as();\n std::cout << \"creating client \" << cname << \"\\n\";\n this->ctx->create_client(cname);\n }\n return;\n}\n\nvoid interpreter::cmd_x(const fc::variants& cmd)\n{\n FC_ASSERT( cmd.size() >= 3 );\n\n std::cout << \"in cmd_x\\n\";\n \n std::vector targets;\n \n this->ctx->get_clients_by_variant( cmd[1], targets );\n\n std::cout << \"targets found: \" << targets.size() << \"\\n\";\n\n for( bts::tscript::client_context_ptr& t : targets )\n {\n std::cout << \" \" << t->client->debug_get_client_name() << \":\\n\";\n\n const std::string& method_name = cmd[2].get_string();\n\n std::cout << \" \" << method_name << \"\\n\";\n \n \/\/ create context for command by combining template context dictionaries\n fc::mutable_variant_object effective_ctx;\n for( auto& e : this->ctx->template_context )\n effective_ctx[e.first] = e.second;\n for( auto& e : t->template_context )\n effective_ctx[e.first] = e.second;\n fc::variant_object v_effective_ctx = effective_ctx;\n \n \/\/ substitute into parameters\n fc::variants args;\n if( cmd.size() >= 4 )\n args = cmd[3].get_array();\n \n for( size_t i=0,n=args.size(); i result;\n fc::optional exc;\n \n try\n {\n result = t->client->get_rpc_server()->direct_invoke_method(method_name, args);\n std::cout << \" result:\" << fc::json::to_string(result) << \"\\n\";\n }\n catch( const fc::exception& e )\n {\n exc = e;\n std::cout << \" \" << e.to_detail_string() << \"\\n\";\n }\n \n std::string cmp_op = \"nop\";\n fc::variant cmp_op_arg;\n if( cmd.size() >= 5 )\n {\n cmp_op = cmd[4].get_string();\n if( cmd.size() >= 6 )\n {\n cmp_op_arg = cmd[5];\n }\n }\n \n bool expected_exception = false;\n \n if( cmp_op == \"nop\" )\n ;\n else if( cmp_op == \"eq\" )\n {\n FC_ASSERT(result.valid());\n std::cout << \"*result : \" << fc::json::to_string(*result) << \"\\n\";\n std::cout << \"cmp_op_arg : \" << fc::json::to_string(cmp_op_arg) << \"\\n\";\n FC_ASSERT(((*result) == cmp_op_arg).as_bool());\n }\n else if( cmp_op == \"ex\" )\n {\n expected_exception = true;\n }\n else if( cmp_op == \"ss\" )\n {\n FC_ASSERT(result.valid());\n FC_ASSERT(cmp_op_arg.is_object());\n FC_ASSERT(result->is_object());\n \n fc::variant_object vo_result = result->get_object();\n for( auto& kv : cmp_op_arg.get_object() )\n {\n auto it = vo_result.find(kv.key());\n FC_ASSERT( it != vo_result.end() );\n FC_ASSERT( (it->value() == kv.value()).as_bool() );\n }\n }\n \n if( (!expected_exception) && (!result.valid()) )\n FC_ASSERT(false, \"terminating due to unexpected exception\");\n }\n std::cout << \"\\n\";\n\n return;\n}\n\nvoid run_single_tscript(\n const fc::path& genesis_json_filename,\n const fc::path& tscript_filename\n )\n{\n FC_ASSERT( fc::is_regular_file(tscript_filename) );\n\n \/\/ delete client directories\n fc::remove_all( \"tmp\/client\" );\n\n bts::tscript::interpreter interp;\n interp.ctx->set_genesis(genesis_json_filename);\n interp.run_file(tscript_filename);\n return;\n}\n\ninline bool startswith(\n const std::string& a,\n const std::string& prefix\n )\n{\n size_t m = prefix.length(), n = a.length();\n return (m <= n) && (0 == a.compare( 0, m, prefix ));\n}\n\ninline bool endswith(\n const std::string& a,\n const std::string& suffix\n )\n{\n size_t m = suffix.length(), n = a.length();\n return (m <= n) && (0 == a.compare( n-m, m, suffix ));\n}\n\nvoid run_tscripts(\n const fc::path& genesis_json_filename,\n const fc::path& target_filename\n )\n{\n if( !fc::is_directory(target_filename) )\n {\n run_single_tscript( genesis_json_filename, target_filename );\n return;\n }\n\n for( fc::recursive_directory_iterator it(target_filename), it_end;\n it != it_end; ++it )\n {\n fc::path filename = (*it);\n if( !fc::is_regular_file(filename) )\n continue;\n if( !endswith(filename.string(), \".tscript\") )\n continue;\n run_single_tscript(genesis_json_filename, filename);\n }\n return;\n}\n\n} }\n\nint main(int argc, char **argv, char **envp)\n{\n for( int i=1; i"} {"text":"\/* This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\n * Copyright 2018 (c) Fraunhofer IOSB (Author: Julius Pfrommer)\n *\/\n\n#include \n#include \n\n\/* Decode a message, then encode, decode, encode.\n * The two encodings must be bit-equal. *\/\nextern \"C\" int\nLLVMFuzzerTestOneInput(uint8_t *data, size_t size) {\n UA_ByteString buf;\n buf.data = (UA_Byte*)data;\n buf.length = size;\n\n UA_Variant value;\n UA_Variant_init(&value);\n\n UA_StatusCode retval = UA_decodeJson(&buf, &value, &UA_TYPES[UA_TYPES_VARIANT], NULL);\n if(retval != UA_STATUSCODE_GOOD)\n return 0;\n\n size_t jsonSize = UA_calcSizeJson(&value, &UA_TYPES[UA_TYPES_VARIANT], NULL);\n\n UA_ByteString buf2 = UA_BYTESTRING_NULL;\n retval = UA_ByteString_allocBuffer(&buf2, jsonSize);\n if(retval != UA_STATUSCODE_GOOD) {\n UA_Variant_clear(&value);\n return 0;\n }\n\n retval = UA_encodeJson(&value, &UA_TYPES[UA_TYPES_VARIANT], &buf2, NULL);\n UA_assert(retval == UA_STATUSCODE_GOOD);\n\n UA_Variant value2;\n UA_Variant_init(&value2);\n retval = UA_decodeJson(&buf2, &value2, &UA_TYPES[UA_TYPES_VARIANT], NULL);\n if(retval != UA_STATUSCODE_GOOD) {\n UA_Variant_clear(&value);\n UA_ByteString_clear(&buf2);\n return 0;\n }\n\n UA_assert(UA_order(&value, &value2, &UA_TYPES[UA_TYPES_VARIANT]) == UA_ORDER_EQ);\n UA_Variant_clear(&value);\n\n UA_ByteString buf3 = UA_BYTESTRING_NULL;\n retval = UA_ByteString_allocBuffer(&buf3, jsonSize);\n if(retval != UA_STATUSCODE_GOOD) {\n UA_Variant_clear(&value2);\n UA_ByteString_clear(&buf2);\n return 0;\n }\n\n retval = UA_encodeJson(&value2, &UA_TYPES[UA_TYPES_VARIANT], &buf3, NULL);\n UA_assert(retval == UA_STATUSCODE_GOOD);\n\n UA_assert(buf2.length == buf3.length);\n UA_assert(memcmp(buf2.data, buf3.data, buf2.length) == 0);\n\n UA_Variant_clear(&value2);\n UA_ByteString_clear(&buf2);\n UA_ByteString_clear(&buf3);\n return 0;\n}\nfeat(tests): Decoding of JSON (we encoded) must succeed in fuzzing\/* This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\n * Copyright 2018 (c) Fraunhofer IOSB (Author: Julius Pfrommer)\n *\/\n\n#include \n#include \n\n\/* Decode a message, then encode, decode, encode.\n * The two encodings must be bit-equal. *\/\nextern \"C\" int\nLLVMFuzzerTestOneInput(uint8_t *data, size_t size) {\n UA_ByteString buf;\n buf.data = (UA_Byte*)data;\n buf.length = size;\n\n UA_Variant value;\n UA_Variant_init(&value);\n\n UA_StatusCode retval = UA_decodeJson(&buf, &value, &UA_TYPES[UA_TYPES_VARIANT], NULL);\n if(retval != UA_STATUSCODE_GOOD)\n return 0;\n\n size_t jsonSize = UA_calcSizeJson(&value, &UA_TYPES[UA_TYPES_VARIANT], NULL);\n\n UA_ByteString buf2 = UA_BYTESTRING_NULL;\n retval = UA_ByteString_allocBuffer(&buf2, jsonSize);\n if(retval != UA_STATUSCODE_GOOD) {\n UA_Variant_clear(&value);\n return 0;\n }\n\n retval = UA_encodeJson(&value, &UA_TYPES[UA_TYPES_VARIANT], &buf2, NULL);\n UA_assert(retval == UA_STATUSCODE_GOOD);\n\n UA_Variant value2;\n UA_Variant_init(&value2);\n retval = UA_decodeJson(&buf2, &value2, &UA_TYPES[UA_TYPES_VARIANT], NULL);\n UA_assert(retval == UA_STATUSCODE_GOOD);\n UA_assert(UA_order(&value, &value2, &UA_TYPES[UA_TYPES_VARIANT]) == UA_ORDER_EQ);\n UA_Variant_clear(&value);\n\n UA_ByteString buf3 = UA_BYTESTRING_NULL;\n retval = UA_ByteString_allocBuffer(&buf3, jsonSize);\n if(retval != UA_STATUSCODE_GOOD) {\n UA_Variant_clear(&value2);\n UA_ByteString_clear(&buf2);\n return 0;\n }\n\n retval = UA_encodeJson(&value2, &UA_TYPES[UA_TYPES_VARIANT], &buf3, NULL);\n UA_assert(retval == UA_STATUSCODE_GOOD);\n\n UA_assert(buf2.length == buf3.length);\n UA_assert(memcmp(buf2.data, buf3.data, buf2.length) == 0);\n\n UA_Variant_clear(&value2);\n UA_ByteString_clear(&buf2);\n UA_ByteString_clear(&buf3);\n return 0;\n}\n<|endoftext|>"} {"text":"\/*\n * Copyright (C) 2016 ScyllaDB\n *\/\n\n\/*\n * This file is part of Scylla.\n *\n * Scylla is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * Scylla is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with Scylla. If not, see .\n *\/\n\n#pragma once\n\n#include \n#include \n#include \n\n#include \n\n#include \"utils\/exceptions.hh\"\n\nnamespace bi = boost::intrusive;\n\nnamespace utils {\n\/\/ Simple variant of the \"LoadingCache\" used for permissions in origin.\n\ntypedef lowres_clock loading_cache_clock_type;\n\ntemplate\nclass timestamped_val : public bi::unordered_set_base_hook> {\npublic:\n typedef _Key key_type;\n typedef _Tp value_type;\n\nprivate:\n std::experimental::optional<_Tp> _opt_value;\n loading_cache_clock_type::time_point _loaded;\n loading_cache_clock_type::time_point _last_read;\n _Key _key;\n\npublic:\n struct key_eq {\n bool operator()(const _Key& k, const timestamped_val& c) const {\n return _EqualPred()(k, c.key());\n }\n\n bool operator()(const timestamped_val& c, const _Key& k) const {\n return _EqualPred()(c.key(), k);\n }\n };\n\n timestamped_val(const _Key& key)\n : _loaded(loading_cache_clock_type::now())\n , _last_read(_loaded)\n , _key(key) {}\n\n timestamped_val(_Key&& key)\n : _loaded(loading_cache_clock_type::now())\n , _last_read(_loaded)\n , _key(std::move(key)) {}\n\n timestamped_val(const timestamped_val&) = default;\n timestamped_val(timestamped_val&&) = default;\n\n \/\/ Make sure copy\/move-assignments don't go through the template below\n timestamped_val& operator=(const timestamped_val&) = default;\n timestamped_val& operator=(timestamped_val&) = default;\n timestamped_val& operator=(timestamped_val&&) = default;\n\n template \n timestamped_val& operator=(U&& new_val) {\n _opt_value = std::forward(new_val);\n _loaded = loading_cache_clock_type::now();\n return *this;\n }\n\n const _Tp& value() {\n _last_read = loading_cache_clock_type::now();\n return _opt_value.value();\n }\n\n explicit operator bool() const noexcept {\n return bool(_opt_value);\n }\n\n loading_cache_clock_type::time_point last_read() const noexcept {\n return _last_read;\n }\n\n loading_cache_clock_type::time_point loaded() const noexcept {\n return _loaded;\n }\n\n const _Key& key() const {\n return _key;\n }\n\n friend bool operator==(const timestamped_val& a, const timestamped_val& b){\n return _EqualPred()(a.key(), b.key());\n }\n\n friend std::size_t hash_value(const timestamped_val& v) {\n return _Hash()(v.key());\n }\n};\n\nclass shared_mutex {\nprivate:\n lw_shared_ptr _mutex_ptr;\n\npublic:\n shared_mutex() : _mutex_ptr(make_lw_shared(1)) {}\n semaphore& get() const noexcept {\n return *_mutex_ptr;\n }\n};\n\ntemplate,\n typename _Pred = std::equal_to<_Key>,\n typename _Alloc = std::allocator>,\n typename SharedMutexMapAlloc = std::allocator>>\nclass loading_cache {\nprivate:\n typedef timestamped_val<_Tp, _Key, _Hash, _Pred> ts_value_type;\n typedef bi::unordered_set, bi::compare_hash> set_type;\n typedef std::unordered_map<_Key, shared_mutex, _Hash, _Pred, SharedMutexMapAlloc> write_mutex_map_type;\n typedef loading_cache<_Key, _Tp, _Hash, _Pred, _Alloc> _MyType;\n typedef typename set_type::bucket_traits bi_set_bucket_traits;\n\n static constexpr int initial_num_buckets = 256;\n static constexpr int max_num_buckets = 1024 * 1024;\n\npublic:\n typedef _Tp value_type;\n typedef _Key key_type;\n typedef typename set_type::iterator iterator;\n\n template\n loading_cache(size_t max_size, std::chrono::milliseconds expiry, std::chrono::milliseconds refresh, logging::logger& logger, Func&& load)\n : _buckets(initial_num_buckets)\n , _set(bi_set_bucket_traits(_buckets.data(), _buckets.size()))\n , _max_size(max_size)\n , _expiry(expiry)\n , _refresh(refresh)\n , _logger(logger)\n , _load(std::forward(load)) {\n\n \/\/ If expiration period is zero - caching is disabled\n if (!caching_enabled()) {\n return;\n }\n\n \/\/ Sanity check: if expiration period is given then non-zero refresh period and maximal size are required\n if (_refresh == std::chrono::milliseconds(0) || _max_size == 0) {\n throw exceptions::configuration_exception(\"loading_cache: caching is enabled but refresh period and\/or max_size are zero\");\n }\n\n _timer.set_callback([this] { on_timer(); });\n _timer.arm(_refresh);\n }\n\n ~loading_cache() {\n _set.clear_and_dispose([] (ts_value_type* ptr) { loading_cache::destroy_ts_value(ptr); });\n }\n\n future<_Tp> get(const _Key& k) {\n \/\/ If caching is disabled - always load in the foreground\n if (!caching_enabled()) {\n return _load(k);\n }\n\n \/\/ If the key is not in the cache yet, then find_or_create() is going to\n \/\/ create a new uninitialized value in the map. If the value is already\n \/\/ in the cache (the fast path) simply return the value. Otherwise, take\n \/\/ the mutex and try to load the value (the slow path).\n iterator ts_value_it = find_or_create(k);\n if (*ts_value_it) {\n return make_ready_future<_Tp>(ts_value_it->value());\n } else {\n return slow_load(k);\n }\n }\n\nprivate:\n bool caching_enabled() const {\n return _expiry != std::chrono::milliseconds(0);\n }\n\n \/\/\/ Look for the entry with the given key. It it doesn't exist - create a new one and add it to the _set.\n \/\/\/\n \/\/\/ \\param k The key to look for\n \/\/\/\n \/\/\/ \\return An iterator to the value with the given key (always dirrerent from _set.end())\n template \n iterator find_or_create(KeyType&& k) {\n iterator i = _set.find(k, _Hash(), typename ts_value_type::key_eq());\n if (i == _set.end()) {\n ts_value_type* new_ts_val = _Alloc().allocate(1);\n new(new_ts_val) ts_value_type(std::forward(k));\n auto p = _set.insert(*new_ts_val);\n i = p.first;\n }\n\n return i;\n }\n\n static void destroy_ts_value(ts_value_type* val) {\n val->~ts_value_type();\n _Alloc().deallocate(val, 1);\n }\n\n future<_Tp> slow_load(const _Key& k) {\n \/\/ If the key is not in the cache yet, then _write_mutex_map[k] is going\n \/\/ to create a new value with the initialized mutex. The mutex is going\n \/\/ to serialize the producers and only the first one is going to\n \/\/ actually issue a load operation and initialize the value with the\n \/\/ received result. The rest are going to see (and read) the initialized\n \/\/ value when they enter the critical section.\n shared_mutex sm = _write_mutex_map[k];\n return with_semaphore(sm.get(), 1, [this, k] {\n iterator ts_value_it = find_or_create(k);\n if (*ts_value_it) {\n return make_ready_future<_Tp>(ts_value_it->value());\n }\n _logger.trace(\"{}: storing the value for the first time\", k);\n return _load(k).then([this, k] (_Tp t) {\n \/\/ we have to \"re-read\" the _set here because the value may have been evicted by now\n iterator ts_value_it = find_or_create(std::move(k));\n *ts_value_it = std::move(t);\n return make_ready_future<_Tp>(ts_value_it->value());\n });\n }).finally([sm] {});\n }\n\n future<> reload(ts_value_type& ts_val) {\n return _load(ts_val.key()).then_wrapped([this, &ts_val] (auto&& f) {\n \/\/ The exceptions are related to the load operation itself.\n \/\/ We should ignore them for the background reads - if\n \/\/ they persist the value will age and will be reloaded in\n \/\/ the forground. If the foreground READ fails the error\n \/\/ will be propagated up to the user and will fail the\n \/\/ corresponding query.\n try {\n ts_val = f.get0();\n } catch (std::exception& e) {\n _logger.debug(\"{}: reload failed: {}\", ts_val.key(), e.what());\n } catch (...) {\n _logger.debug(\"{}: reload failed: unknown error\", ts_val.key());\n }\n });\n }\n\n void erase(iterator it) {\n _set.erase_and_dispose(it, [] (ts_value_type* ptr) { loading_cache::destroy_ts_value(ptr); });\n }\n\n \/\/ We really miss the std::erase_if()... :(\n void drop_expired() {\n auto now = loading_cache_clock_type::now();\n auto i = _set.begin();\n auto e = _set.end();\n\n while (i != e) {\n \/\/ An entry should be discarded if it hasn't been reloaded for too long or nobody cares about it anymore\n auto since_last_read = now - i->last_read();\n auto since_loaded = now - i->loaded();\n if (_expiry < since_last_read || _expiry < since_loaded) {\n using namespace std::chrono;\n _logger.trace(\"drop_expired(): {}: dropping the entry: _expiry {}, ms passed since: loaded {} last_read {}\", i->key(), _expiry.count(), duration_cast(since_loaded).count(), duration_cast(since_last_read).count());\n erase(i++);\n continue;\n }\n ++i;\n }\n }\n\n \/\/ Shrink the cache to the _max_size discarding the least recently used items\n void shrink() {\n if (_max_size != 0 && _set.size() > _max_size) {\n std::vector tmp;\n tmp.reserve(_set.size());\n\n iterator i = _set.begin();\n while (i != _set.end()) {\n tmp.emplace_back(i++);\n }\n\n std::sort(tmp.begin(), tmp.end(), [] (iterator i1, iterator i2) {\n return i1->last_read() < i2->last_read();\n });\n\n tmp.resize(_set.size() - _max_size);\n std::for_each(tmp.begin(), tmp.end(), [this] (auto& k) {\n using namespace std::chrono;\n _logger.trace(\"shrink(): {}: dropping the entry: ms since last_read {}\", k->key(), duration_cast(loading_cache_clock_type::now() - k->last_read()).count());\n this->erase(k);\n });\n }\n }\n\n void rehash() {\n size_t new_buckets_count = 0;\n\n \/\/ Don't grow or shrink too fast even if there is a steep drop\/growth in the number of elements in the set.\n \/\/ Exponential growth\/backoff should be good enough.\n \/\/\n \/\/ Try to keep the load factor between 0.25 and 1.0.\n if (_set.size() < _current_buckets_count \/ 4) {\n new_buckets_count = _current_buckets_count \/ 4;\n } else if (_set.size() > _current_buckets_count) {\n new_buckets_count = _current_buckets_count * 2;\n }\n\n if (new_buckets_count < initial_num_buckets || new_buckets_count > max_num_buckets) {\n return;\n }\n\n std::vector new_buckets(new_buckets_count);\n _set.rehash(bi_set_bucket_traits(new_buckets.data(), new_buckets.size()));\n _logger.trace(\"rehash(): buckets count changed: {} -> {}\", _current_buckets_count, new_buckets_count);\n\n _buckets.swap(new_buckets);\n _current_buckets_count = new_buckets_count;\n }\n\n void on_timer() {\n _logger.trace(\"on_timer(): start\");\n\n auto timer_start_tp = loading_cache_clock_type::now();\n\n \/\/ Clear all cached mutexes\n _write_mutex_map.clear();\n\n \/\/ Clean up items that were not touched for the whole _expiry period.\n drop_expired();\n\n \/\/ Remove the least recently used items if map is too big.\n shrink();\n\n \/\/ check if rehashing is needed and do it if it is.\n rehash();\n\n \/\/ Reload all those which vlaue needs to be reloaded.\n parallel_for_each(_set.begin(), _set.end(), [this, curr_time = timer_start_tp] (auto& ts_val) {\n _logger.trace(\"on_timer(): {}: checking the value age\", ts_val.key());\n if (ts_val && ts_val.loaded() + _refresh < curr_time) {\n _logger.trace(\"on_timer(): {}: reloading the value\", ts_val.key());\n return this->reload(ts_val);\n }\n return now();\n }).finally([this, timer_start_tp] {\n _logger.trace(\"on_timer(): rearming\");\n _timer.arm(timer_start_tp + _refresh);\n });\n }\n\n std::vector _buckets;\n size_t _current_buckets_count = initial_num_buckets;\n set_type _set;\n write_mutex_map_type _write_mutex_map;\n size_t _max_size;\n std::chrono::milliseconds _expiry;\n std::chrono::milliseconds _refresh;\n logging::logger& _logger;\n std::function(const _Key&)> _load;\n timer _timer;\n};\n\n}\n\nutils\/loading_cache.hh: use intrusive list to store the lru entry\/*\n * Copyright (C) 2016 ScyllaDB\n *\/\n\n\/*\n * This file is part of Scylla.\n *\n * Scylla is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * Scylla is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with Scylla. If not, see .\n *\/\n\n#pragma once\n\n#include \n#include \n#include \n#include \n\n#include \n\n#include \"utils\/exceptions.hh\"\n\nnamespace bi = boost::intrusive;\n\nnamespace utils {\n\/\/ Simple variant of the \"LoadingCache\" used for permissions in origin.\n\ntypedef lowres_clock loading_cache_clock_type;\ntypedef bi::list_base_hook> auto_unlink_list_hook;\n\ntemplate\nclass timestamped_val : public auto_unlink_list_hook, public bi::unordered_set_base_hook> {\npublic:\n typedef bi::list> lru_list_type;\n typedef _Key key_type;\n typedef _Tp value_type;\n\nprivate:\n std::experimental::optional<_Tp> _opt_value;\n loading_cache_clock_type::time_point _loaded;\n loading_cache_clock_type::time_point _last_read;\n lru_list_type& _lru_list; \/\/\/ MRU item is at the front, LRU - at the back\n _Key _key;\n\npublic:\n struct key_eq {\n bool operator()(const _Key& k, const timestamped_val& c) const {\n return _EqualPred()(k, c.key());\n }\n\n bool operator()(const timestamped_val& c, const _Key& k) const {\n return _EqualPred()(c.key(), k);\n }\n };\n\n timestamped_val(lru_list_type& lru_list, const _Key& key)\n : _loaded(loading_cache_clock_type::now())\n , _last_read(_loaded)\n , _lru_list(lru_list)\n , _key(key) {}\n\n timestamped_val(lru_list_type& lru_list, _Key&& key)\n : _loaded(loading_cache_clock_type::now())\n , _last_read(_loaded)\n , _lru_list(lru_list)\n , _key(std::move(key)) {}\n\n timestamped_val(const timestamped_val&) = default;\n timestamped_val(timestamped_val&&) = default;\n\n \/\/ Make sure copy\/move-assignments don't go through the template below\n timestamped_val& operator=(const timestamped_val&) = default;\n timestamped_val& operator=(timestamped_val&) = default;\n timestamped_val& operator=(timestamped_val&&) = default;\n\n template \n timestamped_val& operator=(U&& new_val) {\n _opt_value = std::forward(new_val);\n _loaded = loading_cache_clock_type::now();\n return *this;\n }\n\n const _Tp& value() {\n _last_read = loading_cache_clock_type::now();\n touch();\n return _opt_value.value();\n }\n\n explicit operator bool() const noexcept {\n return bool(_opt_value);\n }\n\n loading_cache_clock_type::time_point last_read() const noexcept {\n return _last_read;\n }\n\n loading_cache_clock_type::time_point loaded() const noexcept {\n return _loaded;\n }\n\n const _Key& key() const {\n return _key;\n }\n\n friend bool operator==(const timestamped_val& a, const timestamped_val& b){\n return _EqualPred()(a.key(), b.key());\n }\n\n friend std::size_t hash_value(const timestamped_val& v) {\n return _Hash()(v.key());\n }\n\nprivate:\n \/\/\/ Set the given item as the most recently used item.\n \/\/\/ The MRU item is going to be at the front of the _lru_list, the LRU item - at the back.\n \/\/\/\n \/\/\/ \\param item item to set as MRU item\n void touch() noexcept {\n auto_unlink_list_hook::unlink();\n _lru_list.push_front(*this);\n }\n};\n\nclass shared_mutex {\nprivate:\n lw_shared_ptr _mutex_ptr;\n\npublic:\n shared_mutex() : _mutex_ptr(make_lw_shared(1)) {}\n semaphore& get() const noexcept {\n return *_mutex_ptr;\n }\n};\n\ntemplate,\n typename _Pred = std::equal_to<_Key>,\n typename _Alloc = std::allocator>,\n typename SharedMutexMapAlloc = std::allocator>>\nclass loading_cache {\nprivate:\n typedef timestamped_val<_Tp, _Key, _Hash, _Pred> ts_value_type;\n typedef bi::unordered_set, bi::compare_hash> set_type;\n typedef std::unordered_map<_Key, shared_mutex, _Hash, _Pred, SharedMutexMapAlloc> write_mutex_map_type;\n typedef loading_cache<_Key, _Tp, _Hash, _Pred, _Alloc> _MyType;\n typedef typename ts_value_type::lru_list_type lru_list_type;\n typedef typename set_type::bucket_traits bi_set_bucket_traits;\n\n static constexpr int initial_num_buckets = 256;\n static constexpr int max_num_buckets = 1024 * 1024;\n\npublic:\n typedef _Tp value_type;\n typedef _Key key_type;\n typedef typename set_type::iterator iterator;\n\n template\n loading_cache(size_t max_size, std::chrono::milliseconds expiry, std::chrono::milliseconds refresh, logging::logger& logger, Func&& load)\n : _buckets(initial_num_buckets)\n , _set(bi_set_bucket_traits(_buckets.data(), _buckets.size()))\n , _max_size(max_size)\n , _expiry(expiry)\n , _refresh(refresh)\n , _logger(logger)\n , _load(std::forward(load)) {\n\n \/\/ If expiration period is zero - caching is disabled\n if (!caching_enabled()) {\n return;\n }\n\n \/\/ Sanity check: if expiration period is given then non-zero refresh period and maximal size are required\n if (_refresh == std::chrono::milliseconds(0) || _max_size == 0) {\n throw exceptions::configuration_exception(\"loading_cache: caching is enabled but refresh period and\/or max_size are zero\");\n }\n\n _timer.set_callback([this] { on_timer(); });\n _timer.arm(_refresh);\n }\n\n ~loading_cache() {\n _set.clear_and_dispose([] (ts_value_type* ptr) { loading_cache::destroy_ts_value(ptr); });\n }\n\n future<_Tp> get(const _Key& k) {\n \/\/ If caching is disabled - always load in the foreground\n if (!caching_enabled()) {\n return _load(k);\n }\n\n \/\/ If the key is not in the cache yet, then find_or_create() is going to\n \/\/ create a new uninitialized value in the map. If the value is already\n \/\/ in the cache (the fast path) simply return the value. Otherwise, take\n \/\/ the mutex and try to load the value (the slow path).\n iterator ts_value_it = find_or_create(k);\n if (*ts_value_it) {\n return make_ready_future<_Tp>(ts_value_it->value());\n } else {\n return slow_load(k);\n }\n }\n\nprivate:\n bool caching_enabled() const {\n return _expiry != std::chrono::milliseconds(0);\n }\n\n \/\/\/ Look for the entry with the given key. It it doesn't exist - create a new one and add it to the _set.\n \/\/\/\n \/\/\/ \\param k The key to look for\n \/\/\/\n \/\/\/ \\return An iterator to the value with the given key (always dirrerent from _set.end())\n template \n iterator find_or_create(KeyType&& k) {\n iterator i = _set.find(k, _Hash(), typename ts_value_type::key_eq());\n if (i == _set.end()) {\n ts_value_type* new_ts_val = _Alloc().allocate(1);\n new(new_ts_val) ts_value_type(_lru_list, std::forward(k));\n auto p = _set.insert(*new_ts_val);\n i = p.first;\n }\n\n return i;\n }\n\n static void destroy_ts_value(ts_value_type* val) {\n val->~ts_value_type();\n _Alloc().deallocate(val, 1);\n }\n\n future<_Tp> slow_load(const _Key& k) {\n \/\/ If the key is not in the cache yet, then _write_mutex_map[k] is going\n \/\/ to create a new value with the initialized mutex. The mutex is going\n \/\/ to serialize the producers and only the first one is going to\n \/\/ actually issue a load operation and initialize the value with the\n \/\/ received result. The rest are going to see (and read) the initialized\n \/\/ value when they enter the critical section.\n shared_mutex sm = _write_mutex_map[k];\n return with_semaphore(sm.get(), 1, [this, k] {\n iterator ts_value_it = find_or_create(k);\n if (*ts_value_it) {\n return make_ready_future<_Tp>(ts_value_it->value());\n }\n _logger.trace(\"{}: storing the value for the first time\", k);\n return _load(k).then([this, k] (_Tp t) {\n \/\/ we have to \"re-read\" the _set here because the value may have been evicted by now\n iterator ts_value_it = find_or_create(std::move(k));\n *ts_value_it = std::move(t);\n return make_ready_future<_Tp>(ts_value_it->value());\n });\n }).finally([sm] {});\n }\n\n future<> reload(ts_value_type& ts_val) {\n return _load(ts_val.key()).then_wrapped([this, &ts_val] (auto&& f) {\n \/\/ The exceptions are related to the load operation itself.\n \/\/ We should ignore them for the background reads - if\n \/\/ they persist the value will age and will be reloaded in\n \/\/ the forground. If the foreground READ fails the error\n \/\/ will be propagated up to the user and will fail the\n \/\/ corresponding query.\n try {\n ts_val = f.get0();\n } catch (std::exception& e) {\n _logger.debug(\"{}: reload failed: {}\", ts_val.key(), e.what());\n } catch (...) {\n _logger.debug(\"{}: reload failed: unknown error\", ts_val.key());\n }\n });\n }\n\n void erase(iterator it) {\n _set.erase_and_dispose(it, [] (ts_value_type* ptr) { loading_cache::destroy_ts_value(ptr); });\n \/\/ no need to delete the item from _lru_list - it's auto-deleted\n }\n\n void drop_expired() {\n auto now = loading_cache_clock_type::now();\n _lru_list.remove_and_dispose_if([now, this] (const ts_value_type& v) {\n using namespace std::chrono;\n \/\/ An entry should be discarded if it hasn't been reloaded for too long or nobody cares about it anymore\n auto since_last_read = now - v.last_read();\n auto since_loaded = now - v.loaded();\n if (_expiry < since_last_read || _expiry < since_loaded) {\n _logger.trace(\"drop_expired(): {}: dropping the entry: _expiry {}, ms passed since: loaded {} last_read {}\", v.key(), _expiry.count(), duration_cast(since_loaded).count(), duration_cast(since_last_read).count());\n return true;\n }\n return false;\n }, [this] (ts_value_type* p) {\n erase(_set.iterator_to(*p));\n });\n }\n\n \/\/ Shrink the cache to the _max_size discarding the least recently used items\n void shrink() {\n if (_set.size() > _max_size) {\n auto num_items_to_erase = _set.size() - _max_size;\n for (size_t i = 0; i < num_items_to_erase; ++i) {\n using namespace std::chrono;\n ts_value_type& ts_val = *_lru_list.rbegin();\n _logger.trace(\"shrink(): {}: dropping the entry: ms since last_read {}\", ts_val.key(), duration_cast(loading_cache_clock_type::now() - ts_val.last_read()).count());\n erase(_set.iterator_to(ts_val));\n }\n }\n }\n\n void rehash() {\n size_t new_buckets_count = 0;\n\n \/\/ Don't grow or shrink too fast even if there is a steep drop\/growth in the number of elements in the set.\n \/\/ Exponential growth\/backoff should be good enough.\n \/\/\n \/\/ Try to keep the load factor between 0.25 and 1.0.\n if (_set.size() < _current_buckets_count \/ 4) {\n new_buckets_count = _current_buckets_count \/ 4;\n } else if (_set.size() > _current_buckets_count) {\n new_buckets_count = _current_buckets_count * 2;\n }\n\n if (new_buckets_count < initial_num_buckets || new_buckets_count > max_num_buckets) {\n return;\n }\n\n std::vector new_buckets(new_buckets_count);\n _set.rehash(bi_set_bucket_traits(new_buckets.data(), new_buckets.size()));\n _logger.trace(\"rehash(): buckets count changed: {} -> {}\", _current_buckets_count, new_buckets_count);\n\n _buckets.swap(new_buckets);\n _current_buckets_count = new_buckets_count;\n }\n\n void on_timer() {\n _logger.trace(\"on_timer(): start\");\n\n auto timer_start_tp = loading_cache_clock_type::now();\n\n \/\/ Clear all cached mutexes\n _write_mutex_map.clear();\n\n \/\/ Clean up items that were not touched for the whole _expiry period.\n drop_expired();\n\n \/\/ Remove the least recently used items if map is too big.\n shrink();\n\n \/\/ check if rehashing is needed and do it if it is.\n rehash();\n\n \/\/ Reload all those which vlaue needs to be reloaded.\n parallel_for_each(_set.begin(), _set.end(), [this, curr_time = timer_start_tp] (auto& ts_val) {\n _logger.trace(\"on_timer(): {}: checking the value age\", ts_val.key());\n if (ts_val && ts_val.loaded() + _refresh < curr_time) {\n _logger.trace(\"on_timer(): {}: reloading the value\", ts_val.key());\n return this->reload(ts_val);\n }\n return now();\n }).finally([this, timer_start_tp] {\n _logger.trace(\"on_timer(): rearming\");\n _timer.arm(timer_start_tp + _refresh);\n });\n }\n\n std::vector _buckets;\n size_t _current_buckets_count = initial_num_buckets;\n set_type _set;\n write_mutex_map_type _write_mutex_map;\n lru_list_type _lru_list;\n size_t _max_size;\n std::chrono::milliseconds _expiry;\n std::chrono::milliseconds _refresh;\n logging::logger& _logger;\n std::function(const _Key&)> _load;\n timer _timer;\n};\n\n}\n\n<|endoftext|>"} {"text":"\n\/*\n * Copyright 2015 Cloudius Systems\n *\/\n\n\/*\n * This file is part of Scylla.\n *\n * Scylla is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * Scylla is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with Scylla. If not, see .\n *\/\n\n#pragma once\n\n#include \n#include \n#include \"bytes.hh\"\n#include \"utils\/allocation_strategy.hh\"\n\nstruct blob_storage {\n using size_type = uint32_t;\n using char_type = bytes_view::value_type;\n\n blob_storage** backref;\n size_type size;\n size_type frag_size;\n blob_storage* next;\n char_type data[];\n\n blob_storage(blob_storage** backref, size_type size, size_type frag_size) noexcept\n : backref(backref)\n , size(size)\n , frag_size(frag_size)\n , next(nullptr)\n {\n *backref = this;\n }\n\n blob_storage(blob_storage&& o) noexcept\n : backref(o.backref)\n , size(o.size)\n , frag_size(o.frag_size)\n , next(o.next)\n {\n *backref = this;\n o.next = nullptr;\n if (next) {\n next->backref = &next;\n }\n memcpy(data, o.data, size);\n }\n} __attribute__((packed));\n\n\/\/ A managed version of \"bytes\" (can be used with LSA).\nclass managed_bytes {\n static constexpr size_t max_inline_size = 15;\n struct small_blob {\n bytes_view::value_type data[max_inline_size];\n int8_t size; \/\/ -1 -> use blob_storage\n };\n union {\n blob_storage* ptr;\n small_blob small;\n } _u;\n static_assert(sizeof(small_blob) > sizeof(blob_storage*), \"inline size too small\");\nprivate:\n bool external() const {\n return _u.small.size < 0;\n }\n size_t max_seg(allocation_strategy& alctr) {\n return alctr.preferred_max_contiguous_allocation() - sizeof(blob_storage);\n }\n void free_chain(blob_storage* p) {\n auto& alctr = current_allocator();\n while (p) {\n auto n = p->next;\n alctr.destroy(p);\n p = n;\n }\n }\npublic:\n using size_type = blob_storage::size_type;\n struct initialized_later {};\n\n managed_bytes() {\n _u.small.size = 0;\n }\n\n managed_bytes(const blob_storage::char_type* ptr, size_type size)\n : managed_bytes(bytes_view(ptr, size)) {}\n\n managed_bytes(const bytes& b) : managed_bytes(static_cast(b)) {}\n\n managed_bytes(initialized_later, size_type size) {\n if (size <= max_inline_size) {\n _u.small.size = size;\n } else {\n _u.small.size = -1;\n auto& alctr = current_allocator();\n auto maxseg = max_seg(alctr);\n auto now = std::min(size_t(size), maxseg);\n void* p = alctr.alloc(&standard_migrator::object,\n sizeof(blob_storage) + now, alignof(blob_storage));\n auto first = new (p) blob_storage(&_u.ptr, size, now);\n auto last = first;\n size -= now;\n try {\n while (size) {\n auto now = std::min(size_t(size), maxseg);\n void* p = alctr.alloc(&standard_migrator::object,\n sizeof(blob_storage) + now, alignof(blob_storage));\n last = new (p) blob_storage(&last->next, 0, now);\n size -= now;\n }\n } catch (...) {\n free_chain(first);\n throw;\n }\n }\n }\n\n managed_bytes(bytes_view v) : managed_bytes(initialized_later(), v.size()) {\n auto p = v.data();\n auto s = v.size();\n if (!external()) {\n memcpy(_u.small.data, p, s);\n return;\n }\n auto b = _u.ptr;\n while (s) {\n memcpy(b->data, p, b->frag_size);\n p += b->frag_size;\n s -= b->frag_size;\n b = b->next;\n }\n assert(!b);\n }\n\n managed_bytes(std::initializer_list b) : managed_bytes(b.begin(), b.size()) {}\n\n ~managed_bytes() {\n if (external()) {\n free_chain(_u.ptr);\n }\n }\n\n managed_bytes(const managed_bytes& o) : managed_bytes(initialized_later(), o.size()) {\n if (!external()) {\n memcpy(data(), o.data(), size());\n return;\n }\n auto s = size();\n blob_storage* const* next_src = &o._u.ptr;\n blob_storage* blob_src = nullptr;\n size_type size_src = 0;\n size_type offs_src = 0;\n blob_storage** next_dst = &_u.ptr;\n blob_storage* blob_dst = nullptr;\n size_type size_dst = 0;\n size_type offs_dst = 0;\n while (s) {\n if (!size_src) {\n blob_src = *next_src;\n next_src = &blob_src->next;\n size_src = blob_src->frag_size;\n offs_src = 0;\n }\n if (!size_dst) {\n blob_dst = *next_dst;\n next_dst = &blob_dst->next;\n size_dst = blob_dst->frag_size;\n offs_dst = 0;\n }\n auto now = std::min(size_src, size_dst);\n memcpy(blob_dst->data + offs_dst, blob_src->data + offs_src, now);\n s -= now;\n offs_src += now; size_src -= now;\n offs_dst += now; size_dst -= now;\n }\n assert(size_src == 0 && size_dst == 0);\n }\n\n managed_bytes(managed_bytes&& o) noexcept\n : _u(o._u)\n {\n if (external()) {\n if (_u.ptr) {\n _u.ptr->backref = &_u.ptr;\n }\n }\n o._u.small.size = 0;\n }\n\n managed_bytes& operator=(managed_bytes&& o) {\n if (this != &o) {\n this->~managed_bytes();\n new (this) managed_bytes(std::move(o));\n }\n return *this;\n }\n\n managed_bytes& operator=(const managed_bytes& o) {\n if (this != &o) {\n \/\/ FIXME: not exception safe\n this->~managed_bytes();\n new (this) managed_bytes(o);\n }\n return *this;\n }\n\n bool operator==(const managed_bytes& o) const {\n return static_cast(*this) == static_cast(o);\n }\n\n bool operator!=(const managed_bytes& o) const {\n return !(*this == o);\n }\n\n operator bytes_view() const {\n return { data(), size() };\n }\n\n bytes_view::value_type& operator[](size_type index) {\n return data()[index];\n }\n\n const bytes_view::value_type& operator[](size_type index) const {\n return data()[index];\n }\n\n size_type size() const {\n if (external()) {\n return _u.ptr->size;\n } else {\n return _u.small.size;\n }\n }\n\n const blob_storage::char_type* begin() const {\n return data();\n }\n\n const blob_storage::char_type* end() const {\n return data() + size();\n }\n\n blob_storage::char_type* begin() {\n return data();\n }\n\n blob_storage::char_type* end() {\n return data() + size();\n }\n\n bool empty() const {\n return _u.small.size == 0;\n }\n\n blob_storage::char_type* data() {\n if (external()) {\n assert(!_u.ptr->next); \/\/ must be linearized\n return _u.ptr->data;\n } else {\n return _u.small.data;\n }\n }\n\n const blob_storage::char_type* data() const {\n return const_cast(this)->data();\n }\n\n void linearize() {\n if (!external() || !_u.ptr->next) {\n return;\n }\n auto& alctr = current_allocator();\n auto size = _u.ptr->size;\n void* p = alctr.alloc(&standard_migrator::object,\n sizeof(blob_storage) + size, alignof(blob_storage));\n auto old = _u.ptr;\n auto blob = new (p) blob_storage(&_u.ptr, size, size);\n auto pos = size_type(0);\n while (old) {\n memcpy(blob->data + pos, old->data, old->frag_size);\n pos += old->frag_size;\n auto next = old->next;\n alctr.destroy(old);\n old = next;\n }\n assert(pos == size);\n }\n\n void scatter() {\n if (!external()) {\n return;\n }\n if (_u.ptr->size <= max_seg(current_allocator())) {\n return;\n }\n *this = managed_bytes(*this);\n }\n};\n\nnamespace std {\n\ntemplate <>\nstruct hash {\n size_t operator()(managed_bytes v) const {\n return hash()(v);\n }\n};\n\n}\nmanaged_bytes: fix copy size in move constructor\n\/*\n * Copyright 2015 Cloudius Systems\n *\/\n\n\/*\n * This file is part of Scylla.\n *\n * Scylla is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * Scylla is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with Scylla. If not, see .\n *\/\n\n#pragma once\n\n#include \n#include \n#include \"bytes.hh\"\n#include \"utils\/allocation_strategy.hh\"\n\nstruct blob_storage {\n using size_type = uint32_t;\n using char_type = bytes_view::value_type;\n\n blob_storage** backref;\n size_type size;\n size_type frag_size;\n blob_storage* next;\n char_type data[];\n\n blob_storage(blob_storage** backref, size_type size, size_type frag_size) noexcept\n : backref(backref)\n , size(size)\n , frag_size(frag_size)\n , next(nullptr)\n {\n *backref = this;\n }\n\n blob_storage(blob_storage&& o) noexcept\n : backref(o.backref)\n , size(o.size)\n , frag_size(o.frag_size)\n , next(o.next)\n {\n *backref = this;\n o.next = nullptr;\n if (next) {\n next->backref = &next;\n }\n memcpy(data, o.data, frag_size);\n }\n} __attribute__((packed));\n\n\/\/ A managed version of \"bytes\" (can be used with LSA).\nclass managed_bytes {\n static constexpr size_t max_inline_size = 15;\n struct small_blob {\n bytes_view::value_type data[max_inline_size];\n int8_t size; \/\/ -1 -> use blob_storage\n };\n union {\n blob_storage* ptr;\n small_blob small;\n } _u;\n static_assert(sizeof(small_blob) > sizeof(blob_storage*), \"inline size too small\");\nprivate:\n bool external() const {\n return _u.small.size < 0;\n }\n size_t max_seg(allocation_strategy& alctr) {\n return alctr.preferred_max_contiguous_allocation() - sizeof(blob_storage);\n }\n void free_chain(blob_storage* p) {\n auto& alctr = current_allocator();\n while (p) {\n auto n = p->next;\n alctr.destroy(p);\n p = n;\n }\n }\npublic:\n using size_type = blob_storage::size_type;\n struct initialized_later {};\n\n managed_bytes() {\n _u.small.size = 0;\n }\n\n managed_bytes(const blob_storage::char_type* ptr, size_type size)\n : managed_bytes(bytes_view(ptr, size)) {}\n\n managed_bytes(const bytes& b) : managed_bytes(static_cast(b)) {}\n\n managed_bytes(initialized_later, size_type size) {\n if (size <= max_inline_size) {\n _u.small.size = size;\n } else {\n _u.small.size = -1;\n auto& alctr = current_allocator();\n auto maxseg = max_seg(alctr);\n auto now = std::min(size_t(size), maxseg);\n void* p = alctr.alloc(&standard_migrator::object,\n sizeof(blob_storage) + now, alignof(blob_storage));\n auto first = new (p) blob_storage(&_u.ptr, size, now);\n auto last = first;\n size -= now;\n try {\n while (size) {\n auto now = std::min(size_t(size), maxseg);\n void* p = alctr.alloc(&standard_migrator::object,\n sizeof(blob_storage) + now, alignof(blob_storage));\n last = new (p) blob_storage(&last->next, 0, now);\n size -= now;\n }\n } catch (...) {\n free_chain(first);\n throw;\n }\n }\n }\n\n managed_bytes(bytes_view v) : managed_bytes(initialized_later(), v.size()) {\n auto p = v.data();\n auto s = v.size();\n if (!external()) {\n memcpy(_u.small.data, p, s);\n return;\n }\n auto b = _u.ptr;\n while (s) {\n memcpy(b->data, p, b->frag_size);\n p += b->frag_size;\n s -= b->frag_size;\n b = b->next;\n }\n assert(!b);\n }\n\n managed_bytes(std::initializer_list b) : managed_bytes(b.begin(), b.size()) {}\n\n ~managed_bytes() {\n if (external()) {\n free_chain(_u.ptr);\n }\n }\n\n managed_bytes(const managed_bytes& o) : managed_bytes(initialized_later(), o.size()) {\n if (!external()) {\n memcpy(data(), o.data(), size());\n return;\n }\n auto s = size();\n blob_storage* const* next_src = &o._u.ptr;\n blob_storage* blob_src = nullptr;\n size_type size_src = 0;\n size_type offs_src = 0;\n blob_storage** next_dst = &_u.ptr;\n blob_storage* blob_dst = nullptr;\n size_type size_dst = 0;\n size_type offs_dst = 0;\n while (s) {\n if (!size_src) {\n blob_src = *next_src;\n next_src = &blob_src->next;\n size_src = blob_src->frag_size;\n offs_src = 0;\n }\n if (!size_dst) {\n blob_dst = *next_dst;\n next_dst = &blob_dst->next;\n size_dst = blob_dst->frag_size;\n offs_dst = 0;\n }\n auto now = std::min(size_src, size_dst);\n memcpy(blob_dst->data + offs_dst, blob_src->data + offs_src, now);\n s -= now;\n offs_src += now; size_src -= now;\n offs_dst += now; size_dst -= now;\n }\n assert(size_src == 0 && size_dst == 0);\n }\n\n managed_bytes(managed_bytes&& o) noexcept\n : _u(o._u)\n {\n if (external()) {\n if (_u.ptr) {\n _u.ptr->backref = &_u.ptr;\n }\n }\n o._u.small.size = 0;\n }\n\n managed_bytes& operator=(managed_bytes&& o) {\n if (this != &o) {\n this->~managed_bytes();\n new (this) managed_bytes(std::move(o));\n }\n return *this;\n }\n\n managed_bytes& operator=(const managed_bytes& o) {\n if (this != &o) {\n \/\/ FIXME: not exception safe\n this->~managed_bytes();\n new (this) managed_bytes(o);\n }\n return *this;\n }\n\n bool operator==(const managed_bytes& o) const {\n return static_cast(*this) == static_cast(o);\n }\n\n bool operator!=(const managed_bytes& o) const {\n return !(*this == o);\n }\n\n operator bytes_view() const {\n return { data(), size() };\n }\n\n bytes_view::value_type& operator[](size_type index) {\n return data()[index];\n }\n\n const bytes_view::value_type& operator[](size_type index) const {\n return data()[index];\n }\n\n size_type size() const {\n if (external()) {\n return _u.ptr->size;\n } else {\n return _u.small.size;\n }\n }\n\n const blob_storage::char_type* begin() const {\n return data();\n }\n\n const blob_storage::char_type* end() const {\n return data() + size();\n }\n\n blob_storage::char_type* begin() {\n return data();\n }\n\n blob_storage::char_type* end() {\n return data() + size();\n }\n\n bool empty() const {\n return _u.small.size == 0;\n }\n\n blob_storage::char_type* data() {\n if (external()) {\n assert(!_u.ptr->next); \/\/ must be linearized\n return _u.ptr->data;\n } else {\n return _u.small.data;\n }\n }\n\n const blob_storage::char_type* data() const {\n return const_cast(this)->data();\n }\n\n void linearize() {\n if (!external() || !_u.ptr->next) {\n return;\n }\n auto& alctr = current_allocator();\n auto size = _u.ptr->size;\n void* p = alctr.alloc(&standard_migrator::object,\n sizeof(blob_storage) + size, alignof(blob_storage));\n auto old = _u.ptr;\n auto blob = new (p) blob_storage(&_u.ptr, size, size);\n auto pos = size_type(0);\n while (old) {\n memcpy(blob->data + pos, old->data, old->frag_size);\n pos += old->frag_size;\n auto next = old->next;\n alctr.destroy(old);\n old = next;\n }\n assert(pos == size);\n }\n\n void scatter() {\n if (!external()) {\n return;\n }\n if (_u.ptr->size <= max_seg(current_allocator())) {\n return;\n }\n *this = managed_bytes(*this);\n }\n};\n\nnamespace std {\n\ntemplate <>\nstruct hash {\n size_t operator()(managed_bytes v) const {\n return hash()(v);\n }\n};\n\n}\n<|endoftext|>"} {"text":"\n\/*\n * Copyright 2015 Cloudius Systems\n *\/\n\n\/*\n * This file is part of Scylla.\n *\n * Scylla is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * Scylla is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with Scylla. If not, see .\n *\/\n\n#pragma once\n\n#include \n#include \n#include \"bytes.hh\"\n#include \"utils\/allocation_strategy.hh\"\n#include \n#include \n#include \n\nstruct blob_storage {\n using size_type = uint32_t;\n using char_type = bytes_view::value_type;\n\n blob_storage** backref;\n size_type size;\n size_type frag_size;\n blob_storage* next;\n char_type data[];\n\n blob_storage(blob_storage** backref, size_type size, size_type frag_size) noexcept\n : backref(backref)\n , size(size)\n , frag_size(frag_size)\n , next(nullptr)\n {\n *unaligned_cast(backref) = this;\n }\n\n blob_storage(blob_storage&& o) noexcept\n : backref(o.backref)\n , size(o.size)\n , frag_size(o.frag_size)\n , next(o.next)\n {\n *unaligned_cast(backref) = this;\n o.next = nullptr;\n if (next) {\n next->backref = &next;\n }\n memcpy(data, o.data, frag_size);\n }\n} __attribute__((packed));\n\n\/\/ A managed version of \"bytes\" (can be used with LSA).\nclass managed_bytes {\n struct linearization_context {\n unsigned _nesting = 0;\n \/\/ Map from first blob_storage address to linearized version\n \/\/ We use the blob_storage address to be insentive to moving\n \/\/ a managed_bytes object.\n std::unordered_map> _state;\n void enter() {\n ++_nesting;\n }\n void leave() {\n if (!--_nesting) {\n _state.clear();\n }\n }\n void forget(const blob_storage* p) noexcept;\n };\n static thread_local linearization_context _linearization_context;\npublic:\n struct linearization_context_guard {\n linearization_context_guard() {\n _linearization_context.enter();\n }\n ~linearization_context_guard() {\n _linearization_context.leave();\n }\n };\nprivate:\n static constexpr size_t max_inline_size = 15;\n struct small_blob {\n bytes_view::value_type data[max_inline_size];\n int8_t size; \/\/ -1 -> use blob_storage\n };\n union {\n blob_storage* ptr;\n small_blob small;\n } _u;\n static_assert(sizeof(small_blob) > sizeof(blob_storage*), \"inline size too small\");\nprivate:\n bool external() const {\n return _u.small.size < 0;\n }\n size_t max_seg(allocation_strategy& alctr) {\n return alctr.preferred_max_contiguous_allocation() - sizeof(blob_storage);\n }\n void free_chain(blob_storage* p) {\n if (p->next && _linearization_context._nesting) {\n _linearization_context.forget(p);\n }\n auto& alctr = current_allocator();\n while (p) {\n auto n = p->next;\n alctr.destroy(p);\n p = n;\n }\n }\n const bytes_view::value_type* read_linearize() const {\n if (!external()) {\n return _u.small.data;\n } else if (!_u.ptr->next) {\n return _u.ptr->data;\n } else {\n return do_linearize();\n }\n }\n const bytes_view::value_type* do_linearize() const;\npublic:\n using size_type = blob_storage::size_type;\n struct initialized_later {};\n\n managed_bytes() {\n _u.small.size = 0;\n }\n\n managed_bytes(const blob_storage::char_type* ptr, size_type size)\n : managed_bytes(bytes_view(ptr, size)) {}\n\n managed_bytes(const bytes& b) : managed_bytes(static_cast(b)) {}\n\n managed_bytes(initialized_later, size_type size) {\n if (size <= max_inline_size) {\n _u.small.size = size;\n } else {\n _u.small.size = -1;\n auto& alctr = current_allocator();\n auto maxseg = max_seg(alctr);\n auto now = std::min(size_t(size), maxseg);\n void* p = alctr.alloc(&standard_migrator::object,\n sizeof(blob_storage) + now, alignof(blob_storage));\n auto first = new (p) blob_storage(&_u.ptr, size, now);\n auto last = first;\n size -= now;\n try {\n while (size) {\n auto now = std::min(size_t(size), maxseg);\n void* p = alctr.alloc(&standard_migrator::object,\n sizeof(blob_storage) + now, alignof(blob_storage));\n last = new (p) blob_storage(&last->next, 0, now);\n size -= now;\n }\n } catch (...) {\n free_chain(first);\n throw;\n }\n }\n }\n\n managed_bytes(bytes_view v) : managed_bytes(initialized_later(), v.size()) {\n if (!external()) {\n std::copy(v.begin(), v.end(), _u.small.data);\n return;\n }\n auto p = v.data();\n auto s = v.size();\n auto b = _u.ptr;\n while (s) {\n memcpy(b->data, p, b->frag_size);\n p += b->frag_size;\n s -= b->frag_size;\n b = b->next;\n }\n assert(!b);\n }\n\n managed_bytes(std::initializer_list b) : managed_bytes(b.begin(), b.size()) {}\n\n ~managed_bytes() {\n if (external()) {\n free_chain(_u.ptr);\n }\n }\n\n managed_bytes(const managed_bytes& o) : managed_bytes(initialized_later(), o.size()) {\n if (!external()) {\n memcpy(data(), o.data(), size());\n return;\n }\n auto s = size();\n blob_storage* const* next_src = &o._u.ptr;\n blob_storage* blob_src = nullptr;\n size_type size_src = 0;\n size_type offs_src = 0;\n blob_storage** next_dst = &_u.ptr;\n blob_storage* blob_dst = nullptr;\n size_type size_dst = 0;\n size_type offs_dst = 0;\n while (s) {\n if (!size_src) {\n blob_src = *unaligned_cast(next_src);\n next_src = &blob_src->next;\n size_src = blob_src->frag_size;\n offs_src = 0;\n }\n if (!size_dst) {\n blob_dst = *unaligned_cast(next_dst);\n next_dst = &blob_dst->next;\n size_dst = blob_dst->frag_size;\n offs_dst = 0;\n }\n auto now = std::min(size_src, size_dst);\n memcpy(blob_dst->data + offs_dst, blob_src->data + offs_src, now);\n s -= now;\n offs_src += now; size_src -= now;\n offs_dst += now; size_dst -= now;\n }\n assert(size_src == 0 && size_dst == 0);\n }\n\n managed_bytes(managed_bytes&& o) noexcept\n : _u(o._u)\n {\n if (external()) {\n if (_u.ptr) {\n _u.ptr->backref = &_u.ptr;\n }\n }\n o._u.small.size = 0;\n }\n\n managed_bytes& operator=(managed_bytes&& o) {\n if (this != &o) {\n this->~managed_bytes();\n new (this) managed_bytes(std::move(o));\n }\n return *this;\n }\n\n managed_bytes& operator=(const managed_bytes& o) {\n if (this != &o) {\n \/\/ FIXME: not exception safe\n this->~managed_bytes();\n new (this) managed_bytes(o);\n }\n return *this;\n }\n\n bool operator==(const managed_bytes& o) const {\n if (size() != o.size()) {\n return false;\n }\n if (!external()) {\n return bytes_view(*this) == bytes_view(o);\n } else {\n auto a = _u.ptr;\n auto a_data = a->data;\n auto a_remain = a->frag_size;\n a = a->next;\n auto b = o._u.ptr;\n auto b_data = b->data;\n auto b_remain = b->frag_size;\n b = b->next;\n while (a_remain || b_remain) {\n auto now = std::min(a_remain, b_remain);\n if (bytes_view(a_data, now) != bytes_view(b_data, now)) {\n return false;\n }\n a_data += now;\n a_remain -= now;\n if (!a_remain && a) {\n a_data = a->data;\n a_remain = a->frag_size;\n a = a->next;\n }\n b_data += now;\n b_remain -= now;\n if (!b_remain && b) {\n b_data = b->data;\n b_remain = b->frag_size;\n b = b->next;\n }\n }\n return true;\n }\n }\n\n bool operator!=(const managed_bytes& o) const {\n return !(*this == o);\n }\n\n operator bytes_view() const {\n return { data(), size() };\n }\n\n bytes_view::value_type& operator[](size_type index) {\n return data()[index];\n }\n\n const bytes_view::value_type& operator[](size_type index) const {\n return data()[index];\n }\n\n size_type size() const {\n if (external()) {\n return _u.ptr->size;\n } else {\n return _u.small.size;\n }\n }\n\n const blob_storage::char_type* begin() const {\n return data();\n }\n\n const blob_storage::char_type* end() const {\n return data() + size();\n }\n\n blob_storage::char_type* begin() {\n return data();\n }\n\n blob_storage::char_type* end() {\n return data() + size();\n }\n\n bool empty() const {\n return _u.small.size == 0;\n }\n\n blob_storage::char_type* data() {\n if (external()) {\n assert(!_u.ptr->next); \/\/ must be linearized\n return _u.ptr->data;\n } else {\n return _u.small.data;\n }\n }\n\n const blob_storage::char_type* data() const {\n return read_linearize();\n }\n\n template \n friend std::result_of_t with_linearized_managed_bytes(Func&& func);\n};\n\n\/\/ Run func() while ensuring that reads of managed_bytes objects are\n\/\/ temporarlily linearized\ntemplate \ninline\nstd::result_of_t\nwith_linearized_managed_bytes(Func&& func) {\n managed_bytes::linearization_context_guard g;\n return func();\n}\n\nnamespace std {\n\ntemplate <>\nstruct hash {\n size_t operator()(const managed_bytes& v) const {\n return hash()(v);\n }\n};\n\n}\nmanaged_bytes: Make copy assignment exception-safe\n\/*\n * Copyright 2015 Cloudius Systems\n *\/\n\n\/*\n * This file is part of Scylla.\n *\n * Scylla is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * Scylla is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with Scylla. If not, see .\n *\/\n\n#pragma once\n\n#include \n#include \n#include \"bytes.hh\"\n#include \"utils\/allocation_strategy.hh\"\n#include \n#include \n#include \n\nstruct blob_storage {\n using size_type = uint32_t;\n using char_type = bytes_view::value_type;\n\n blob_storage** backref;\n size_type size;\n size_type frag_size;\n blob_storage* next;\n char_type data[];\n\n blob_storage(blob_storage** backref, size_type size, size_type frag_size) noexcept\n : backref(backref)\n , size(size)\n , frag_size(frag_size)\n , next(nullptr)\n {\n *unaligned_cast(backref) = this;\n }\n\n blob_storage(blob_storage&& o) noexcept\n : backref(o.backref)\n , size(o.size)\n , frag_size(o.frag_size)\n , next(o.next)\n {\n *unaligned_cast(backref) = this;\n o.next = nullptr;\n if (next) {\n next->backref = &next;\n }\n memcpy(data, o.data, frag_size);\n }\n} __attribute__((packed));\n\n\/\/ A managed version of \"bytes\" (can be used with LSA).\nclass managed_bytes {\n struct linearization_context {\n unsigned _nesting = 0;\n \/\/ Map from first blob_storage address to linearized version\n \/\/ We use the blob_storage address to be insentive to moving\n \/\/ a managed_bytes object.\n std::unordered_map> _state;\n void enter() {\n ++_nesting;\n }\n void leave() {\n if (!--_nesting) {\n _state.clear();\n }\n }\n void forget(const blob_storage* p) noexcept;\n };\n static thread_local linearization_context _linearization_context;\npublic:\n struct linearization_context_guard {\n linearization_context_guard() {\n _linearization_context.enter();\n }\n ~linearization_context_guard() {\n _linearization_context.leave();\n }\n };\nprivate:\n static constexpr size_t max_inline_size = 15;\n struct small_blob {\n bytes_view::value_type data[max_inline_size];\n int8_t size; \/\/ -1 -> use blob_storage\n };\n union {\n blob_storage* ptr;\n small_blob small;\n } _u;\n static_assert(sizeof(small_blob) > sizeof(blob_storage*), \"inline size too small\");\nprivate:\n bool external() const {\n return _u.small.size < 0;\n }\n size_t max_seg(allocation_strategy& alctr) {\n return alctr.preferred_max_contiguous_allocation() - sizeof(blob_storage);\n }\n void free_chain(blob_storage* p) noexcept {\n if (p->next && _linearization_context._nesting) {\n _linearization_context.forget(p);\n }\n auto& alctr = current_allocator();\n while (p) {\n auto n = p->next;\n alctr.destroy(p);\n p = n;\n }\n }\n const bytes_view::value_type* read_linearize() const {\n if (!external()) {\n return _u.small.data;\n } else if (!_u.ptr->next) {\n return _u.ptr->data;\n } else {\n return do_linearize();\n }\n }\n const bytes_view::value_type* do_linearize() const;\npublic:\n using size_type = blob_storage::size_type;\n struct initialized_later {};\n\n managed_bytes() {\n _u.small.size = 0;\n }\n\n managed_bytes(const blob_storage::char_type* ptr, size_type size)\n : managed_bytes(bytes_view(ptr, size)) {}\n\n managed_bytes(const bytes& b) : managed_bytes(static_cast(b)) {}\n\n managed_bytes(initialized_later, size_type size) {\n if (size <= max_inline_size) {\n _u.small.size = size;\n } else {\n _u.small.size = -1;\n auto& alctr = current_allocator();\n auto maxseg = max_seg(alctr);\n auto now = std::min(size_t(size), maxseg);\n void* p = alctr.alloc(&standard_migrator::object,\n sizeof(blob_storage) + now, alignof(blob_storage));\n auto first = new (p) blob_storage(&_u.ptr, size, now);\n auto last = first;\n size -= now;\n try {\n while (size) {\n auto now = std::min(size_t(size), maxseg);\n void* p = alctr.alloc(&standard_migrator::object,\n sizeof(blob_storage) + now, alignof(blob_storage));\n last = new (p) blob_storage(&last->next, 0, now);\n size -= now;\n }\n } catch (...) {\n free_chain(first);\n throw;\n }\n }\n }\n\n managed_bytes(bytes_view v) : managed_bytes(initialized_later(), v.size()) {\n if (!external()) {\n std::copy(v.begin(), v.end(), _u.small.data);\n return;\n }\n auto p = v.data();\n auto s = v.size();\n auto b = _u.ptr;\n while (s) {\n memcpy(b->data, p, b->frag_size);\n p += b->frag_size;\n s -= b->frag_size;\n b = b->next;\n }\n assert(!b);\n }\n\n managed_bytes(std::initializer_list b) : managed_bytes(b.begin(), b.size()) {}\n\n ~managed_bytes() noexcept {\n if (external()) {\n free_chain(_u.ptr);\n }\n }\n\n managed_bytes(const managed_bytes& o) : managed_bytes(initialized_later(), o.size()) {\n if (!external()) {\n memcpy(data(), o.data(), size());\n return;\n }\n auto s = size();\n blob_storage* const* next_src = &o._u.ptr;\n blob_storage* blob_src = nullptr;\n size_type size_src = 0;\n size_type offs_src = 0;\n blob_storage** next_dst = &_u.ptr;\n blob_storage* blob_dst = nullptr;\n size_type size_dst = 0;\n size_type offs_dst = 0;\n while (s) {\n if (!size_src) {\n blob_src = *unaligned_cast(next_src);\n next_src = &blob_src->next;\n size_src = blob_src->frag_size;\n offs_src = 0;\n }\n if (!size_dst) {\n blob_dst = *unaligned_cast(next_dst);\n next_dst = &blob_dst->next;\n size_dst = blob_dst->frag_size;\n offs_dst = 0;\n }\n auto now = std::min(size_src, size_dst);\n memcpy(blob_dst->data + offs_dst, blob_src->data + offs_src, now);\n s -= now;\n offs_src += now; size_src -= now;\n offs_dst += now; size_dst -= now;\n }\n assert(size_src == 0 && size_dst == 0);\n }\n\n managed_bytes(managed_bytes&& o) noexcept\n : _u(o._u)\n {\n if (external()) {\n if (_u.ptr) {\n _u.ptr->backref = &_u.ptr;\n }\n }\n o._u.small.size = 0;\n }\n\n managed_bytes& operator=(managed_bytes&& o) {\n if (this != &o) {\n this->~managed_bytes();\n new (this) managed_bytes(std::move(o));\n }\n return *this;\n }\n\n managed_bytes& operator=(const managed_bytes& o) {\n if (this != &o) {\n managed_bytes tmp(o);\n this->~managed_bytes();\n new (this) managed_bytes(std::move(tmp));\n }\n return *this;\n }\n\n bool operator==(const managed_bytes& o) const {\n if (size() != o.size()) {\n return false;\n }\n if (!external()) {\n return bytes_view(*this) == bytes_view(o);\n } else {\n auto a = _u.ptr;\n auto a_data = a->data;\n auto a_remain = a->frag_size;\n a = a->next;\n auto b = o._u.ptr;\n auto b_data = b->data;\n auto b_remain = b->frag_size;\n b = b->next;\n while (a_remain || b_remain) {\n auto now = std::min(a_remain, b_remain);\n if (bytes_view(a_data, now) != bytes_view(b_data, now)) {\n return false;\n }\n a_data += now;\n a_remain -= now;\n if (!a_remain && a) {\n a_data = a->data;\n a_remain = a->frag_size;\n a = a->next;\n }\n b_data += now;\n b_remain -= now;\n if (!b_remain && b) {\n b_data = b->data;\n b_remain = b->frag_size;\n b = b->next;\n }\n }\n return true;\n }\n }\n\n bool operator!=(const managed_bytes& o) const {\n return !(*this == o);\n }\n\n operator bytes_view() const {\n return { data(), size() };\n }\n\n bytes_view::value_type& operator[](size_type index) {\n return data()[index];\n }\n\n const bytes_view::value_type& operator[](size_type index) const {\n return data()[index];\n }\n\n size_type size() const {\n if (external()) {\n return _u.ptr->size;\n } else {\n return _u.small.size;\n }\n }\n\n const blob_storage::char_type* begin() const {\n return data();\n }\n\n const blob_storage::char_type* end() const {\n return data() + size();\n }\n\n blob_storage::char_type* begin() {\n return data();\n }\n\n blob_storage::char_type* end() {\n return data() + size();\n }\n\n bool empty() const {\n return _u.small.size == 0;\n }\n\n blob_storage::char_type* data() {\n if (external()) {\n assert(!_u.ptr->next); \/\/ must be linearized\n return _u.ptr->data;\n } else {\n return _u.small.data;\n }\n }\n\n const blob_storage::char_type* data() const {\n return read_linearize();\n }\n\n template \n friend std::result_of_t with_linearized_managed_bytes(Func&& func);\n};\n\n\/\/ Run func() while ensuring that reads of managed_bytes objects are\n\/\/ temporarlily linearized\ntemplate \ninline\nstd::result_of_t\nwith_linearized_managed_bytes(Func&& func) {\n managed_bytes::linearization_context_guard g;\n return func();\n}\n\nnamespace std {\n\ntemplate <>\nstruct hash {\n size_t operator()(const managed_bytes& v) const {\n return hash()(v);\n }\n};\n\n}\n<|endoftext|>"} {"text":"\/*\n * Copyright (C) 2014 ScyllaDB\n *\/\n\n\/*\n * This file is part of Scylla.\n *\n * Scylla is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * Scylla is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with Scylla. If not, see .\n *\/\n\nnamespace utils {\n\/**\n * This class implements an add-only vector that ensures that the elements are\n * unique.\n *\n * This class provides a similar functionality to the Java's LinkedHashSet\n * class.\n *\/\ntemplate\nstruct sequenced_set {\n typedef typename std::vector::iterator iterator;\n\n void push_back(const T& val) {\n if (_set.find(val) != _set.end()) {\n return;\n }\n\n _set.insert(val);\n _vec.push_back(val);\n }\n\n size_t size() {\n return _vec.size();\n }\n\n iterator begin() {\n return _vec.begin();\n }\n\n iterator end() {\n return _vec.end();\n }\n\n const std::vector& get_vector() const {\n return _vec;\n }\n\n std::vector& get_vector() {\n return _vec;\n }\n\n void reserve(size_t sz) {\n _set.reserve(sz);\n _vec.reserve(sz);\n }\n\nprivate:\n std::unordered_set _set;\n std::vector _vec;\n};\n} \/\/ namespace utils\n\nsequenced_set: Add \"insert\" method, following std::set semantics\/*\n * Copyright (C) 2014 ScyllaDB\n *\/\n\n\/*\n * This file is part of Scylla.\n *\n * Scylla is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * Scylla is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with Scylla. If not, see .\n *\/\n\nnamespace utils {\n\/**\n * This class implements an add-only vector that ensures that the elements are\n * unique.\n *\n * This class provides a similar functionality to the Java's LinkedHashSet\n * class.\n *\/\ntemplate\nstruct sequenced_set {\n typedef typename std::vector::iterator iterator;\n\n void push_back(const T& val) {\n insert(val);\n }\n\n std::pair insert(const T& t) {\n auto r = _set.insert(t);\n if (r.second) {\n try {\n _vec.push_back(t);\n return std::make_pair(std::prev(_vec.end()), true);\n } catch (...) {\n _set.erase(r.first);\n throw;\n }\n }\n return std::make_pair(_vec.end(), false);\n }\n\n size_t size() {\n return _vec.size();\n }\n\n iterator begin() {\n return _vec.begin();\n }\n\n iterator end() {\n return _vec.end();\n }\n\n const std::vector& get_vector() const {\n return _vec;\n }\n\n std::vector& get_vector() {\n return _vec;\n }\n\n void reserve(size_t sz) {\n _set.reserve(sz);\n _vec.reserve(sz);\n }\n\nprivate:\n std::unordered_set _set;\n std::vector _vec;\n};\n} \/\/ namespace utils\n\n<|endoftext|>"} {"text":"Fix of the initial locale set.<|endoftext|>"} {"text":"Fix language switch ignored changing RTL-ness.<|endoftext|>"} {"text":"\/\/ Copyright (c) 2017-2020 Dr. Colin Hirsch and Daniel Frey\n\/\/ Please see LICENSE for license or visit https:\/\/github.com\/taocpp\/PEGTL\/\n\n#ifndef TAO_PEGTL_INTERNAL_FILESYSTEM_HPP\n#define TAO_PEGTL_INTERNAL_FILESYSTEM_HPP\n\n#include \"..\/config.hpp\"\n\n#if defined( TAO_PEGTL_STD_EXPERIMENTAL_FILESYSTEM )\n\n#include \n\nnamespace TAO_PEGTL_NAMESPACE::internal::filesystem = ::std::experimental::filesystem;\n\n#elseif defined( TAO_PEGTL_BOOST_FILESYSTEM )\n\n#define BOOST_FILESYSTEM_NO_DEPRECATED\n\n#include \n\nnamespace TAO_PEGTL_NAMESPACE::internal::filesystem = ::boost::filesystem;\n\n#else\n\n#include \n\nnamespace TAO_PEGTL_NAMESPACE::internal\n{\n namespace filesystem = ::std::filesystem;\n}\n\n#endif\n\n#endif\nFixup internal header\/\/ Copyright (c) 2017-2020 Dr. Colin Hirsch and Daniel Frey\n\/\/ Please see LICENSE for license or visit https:\/\/github.com\/taocpp\/PEGTL\/\n\n#ifndef TAO_PEGTL_INTERNAL_FILESYSTEM_HPP\n#define TAO_PEGTL_INTERNAL_FILESYSTEM_HPP\n\n#include \"..\/config.hpp\"\n\n#if defined( TAO_PEGTL_STD_EXPERIMENTAL_FILESYSTEM )\n\n#include \n\nnamespace TAO_PEGTL_NAMESPACE::internal\n{\n namespace filesystem = ::std::experimental::filesystem;\n}\n\n#elif defined( TAO_PEGTL_BOOST_FILESYSTEM )\n\n#define BOOST_FILESYSTEM_NO_DEPRECATED\n\n#include \n\nnamespace TAO_PEGTL_NAMESPACE::internal\n{\n namespace filesystem = ::boost::filesystem;\n}\n\n#else\n\n#include \n\nnamespace TAO_PEGTL_NAMESPACE::internal\n{\n namespace filesystem = ::std::filesystem;\n}\n\n#endif\n\n#endif\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2009-2012, Andre Caron (andre.l.caron@gmail.com)\n\/\/ All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are\n\/\/ met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright\n\/\/ notice, this list of conditions and the following disclaimer.\n\/\/\n\/\/ * Redistributions in binary form must reproduce the above copyright\n\/\/ notice, this list of conditions and the following disclaimer in the\n\/\/ documentation and\/or other materials provided with the distribution.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\/\/ \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n\/\/ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n\/\/ A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n\/\/ HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n\/\/ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n\/\/ LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n\/\/ DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n\/\/ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n\/\/ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n\/\/ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\/\/ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY\n\/\/ or FITNESS FOR A PARTICULAR PURPOSE. See the accompanying \"license.txt\" file\n\/\/ for more details.\n\/\/\n\n#include \"PreparedStatement.hpp\"\n#include \"Connection.hpp\"\n#include \"Diagnostic.hpp\"\n\n\/\/ Since ::SQLBindParameter() does not have a const-correct interface. It's 3rd\n\/\/ parameter indicates if it should read or write to the given location. If this\n\/\/ value is SQL_PARAM_INPUT, the data is not modified, even though it requires\n\/\/ write-access to the value. Do not be surprised to see const casts to discard\n\/\/ qualifiers.\n\nnamespace sql {\n\n PreparedStatement::PreparedStatement (\n Connection& connection, const string& query\n )\n : Statement(connection), myNext(1)\n {\n \/\/ Indicate the statement will be using bound parameters.\n ::SQLRETURN result = ::SQLPrepare(\n handle().value(), const_cast(query.data()), SQL_NTS\n );\n if ( result != SQL_SUCCESS ) {\n throw (Diagnostic(handle()));\n }\n }\n\n PreparedStatement& PreparedStatement::execute ()\n {\n \/\/ Execute query with currently bound parameters.\n Statement::execute();\n \n \/\/ Prepare for re-execution of the same query.\n return (reset());\n }\n\n PreparedStatement& PreparedStatement::reset ()\n {\n myNext = 1; return (*this);\n }\n\n PreparedStatement& PreparedStatement::bind ( const Null& )\n {\n ::SQLLEN length = SQL_NULL_DATA;\n ::SQLRETURN result = ::SQLBindParameter(\n handle().value(), myNext, SQL_PARAM_INPUT,\n 0, 0, 0, 0, 0, 0, &length\n );\n if ( result != SQL_SUCCESS ) {\n throw (Diagnostic(handle()));\n }\n ++myNext; return (*this);\n }\n\n PreparedStatement& PreparedStatement::bind ( const int8& value )\n {\n ::SQLLEN length = 0;\n ::SQLRETURN result = ::SQLBindParameter(\n handle().value(), myNext, SQL_PARAM_INPUT, SQL_C_STINYINT,\n SQL_TINYINT, 0, 0, const_cast(&value), 0, &length\n );\n if ( result != SQL_SUCCESS ) {\n throw (Diagnostic(handle()));\n }\n ++myNext; return (*this);\n }\n\n PreparedStatement& PreparedStatement::bind ( const uint8& value )\n {\n ::SQLLEN length = 0;\n ::SQLRETURN result = ::SQLBindParameter(\n handle().value(), myNext, SQL_PARAM_INPUT, SQL_C_UTINYINT,\n SQL_TINYINT, 0, 0, const_cast(&value), 0, &length\n );\n if ( result != SQL_SUCCESS ) {\n throw (Diagnostic(handle()));\n }\n ++myNext; return (*this);\n }\n\n PreparedStatement& PreparedStatement::bind ( const int16& value )\n {\n ::SQLLEN length = 0;\n ::SQLRETURN result = ::SQLBindParameter(\n handle().value(), myNext, SQL_PARAM_INPUT, SQL_C_SSHORT,\n SQL_SMALLINT, 0, 0, const_cast(&value), 0, &length\n );\n if ( result != SQL_SUCCESS ) {\n throw (Diagnostic(handle()));\n }\n ++myNext; return (*this);\n }\n\n PreparedStatement& PreparedStatement::bind ( const uint16& value )\n {\n ::SQLLEN length = 0;\n ::SQLRETURN result = ::SQLBindParameter(\n handle().value(), myNext, SQL_PARAM_INPUT, SQL_C_USHORT,\n SQL_SMALLINT, 0, 0, const_cast(&value), 0, &length\n );\n if ( result != SQL_SUCCESS ) {\n throw (Diagnostic(handle()));\n }\n ++myNext; return (*this);\n }\n\n PreparedStatement& PreparedStatement::bind ( const int32& value )\n {\n ::SQLLEN length = 0;\n ::SQLRETURN result = ::SQLBindParameter(\n handle().value(), myNext, SQL_PARAM_INPUT, SQL_C_SLONG, SQL_INTEGER,\n 0, 0, const_cast(&value), 0, &length\n );\n if ( result != SQL_SUCCESS ) {\n throw (Diagnostic(handle()));\n }\n ++myNext; return (*this);\n }\n\n PreparedStatement& PreparedStatement::bind ( const uint32& value )\n {\n ::SQLLEN length = 0;\n ::SQLRETURN result = ::SQLBindParameter(\n handle().value(), myNext, SQL_PARAM_INPUT, SQL_C_ULONG, SQL_INTEGER,\n 0, 0, const_cast(&value), 0, &length\n );\n if ( result != SQL_SUCCESS ) {\n throw (Diagnostic(handle()));\n }\n ++myNext; return (*this);\n }\n\n PreparedStatement& PreparedStatement::bind ( const int64& value )\n {\n ::SQLLEN length = 0;\n ::SQLRETURN result = ::SQLBindParameter(\n handle().value(), myNext, SQL_PARAM_INPUT, SQL_C_SBIGINT,\n SQL_BIGINT, 0, 0, const_cast(&value), 0, &length\n );\n if ( result != SQL_SUCCESS ) {\n throw (Diagnostic(handle()));\n }\n ++myNext; return (*this);\n }\n\n PreparedStatement& PreparedStatement::bind ( const uint64& value )\n {\n ::SQLLEN length = 0;\n ::SQLRETURN result = ::SQLBindParameter(\n handle().value(), myNext, SQL_PARAM_INPUT, SQL_C_UBIGINT,\n SQL_BIGINT, 0, 0, const_cast(&value), 0, &length\n );\n if ( result != SQL_SUCCESS ) {\n throw (Diagnostic(handle()));\n }\n ++myNext; return (*this);\n }\n\n PreparedStatement& PreparedStatement::bind ( const float& value )\n {\n ::SQLLEN length = 0;\n ::SQLRETURN result = ::SQLBindParameter(\n handle().value(), myNext, SQL_PARAM_INPUT, SQL_C_FLOAT, SQL_REAL,\n 0, 0, const_cast(&value), 0, &length\n );\n if ( result != SQL_SUCCESS ) {\n throw (Diagnostic(handle()));\n }\n ++myNext; return (*this);\n }\n\n PreparedStatement& PreparedStatement::bind ( const double& value )\n {\n ::SQLLEN length = 0;\n ::SQLRETURN result = ::SQLBindParameter(\n handle().value(), myNext, SQL_PARAM_INPUT, SQL_C_DOUBLE, SQL_DOUBLE,\n 0, 0, const_cast(&value), 0, &length\n );\n if ( result != SQL_SUCCESS ) {\n throw (Diagnostic(handle()));\n }\n ++myNext; return (*this);\n }\n\n PreparedStatement& PreparedStatement::bind ( const string& value )\n {\n ::SQLLEN length = SQL_NTS;\n ::SQLRETURN result = ::SQLBindParameter(\n handle().value(), myNext, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_CHAR,\n value.length(), 0, const_cast(value.data()), 0, &length\n );\n if ( result != SQL_SUCCESS ) {\n throw (Diagnostic(handle()));\n }\n ++myNext; return (*this);\n }\n\n PreparedStatement& PreparedStatement::bind ( const wstring& value )\n {\n ::SQLLEN length = SQL_NTS;\n ::SQLRETURN result = ::SQLBindParameter(\n handle().value(), myNext, SQL_PARAM_INPUT, SQL_C_WCHAR, SQL_WCHAR,\n value.length(), 0, const_cast(value.data()), 0, &length\n );\n if ( result != SQL_SUCCESS ) {\n throw (Diagnostic(handle()));\n }\n ++myNext; return (*this);\n }\n\n PreparedStatement& PreparedStatement::bind ( const Date& date )\n {\n ::SQLLEN length = 0;\n ::SQLRETURN result = ::SQLBindParameter(\n handle().value(), myNext, SQL_PARAM_INPUT, SQL_C_TYPE_DATE,\n SQL_TYPE_TIME, sizeof(::SQL_DATE_STRUCT), 0,\n const_cast<::SQL_DATE_STRUCT*>(&date.value()), 0, &length\n );\n if ( result != SQL_SUCCESS ) {\n throw (Diagnostic(handle()));\n }\n ++myNext; return (*this);\n }\n\n PreparedStatement& PreparedStatement::bind ( const Guid& guid )\n {\n ::SQLLEN length = 0;\n ::SQLRETURN result = ::SQLBindParameter(\n handle().value(), myNext, SQL_PARAM_INPUT, SQL_C_GUID,\n SQL_GUID, sizeof(::SQLGUID), 0,\n const_cast<::SQLGUID*>(&guid.value()), 0, &length\n );\n if ( result != SQL_SUCCESS ) {\n throw (Diagnostic(handle()));\n }\n ++myNext; return (*this);\n }\n\n PreparedStatement& PreparedStatement::bind ( const Numeric& numeric )\n {\n ::SQLLEN length = 0;\n ::SQLRETURN result = ::SQLBindParameter(\n handle().value(), myNext, SQL_PARAM_INPUT, SQL_C_NUMERIC,\n SQL_NUMERIC, sizeof(::SQL_NUMERIC_STRUCT), 0,\n const_cast<::SQL_NUMERIC_STRUCT*>(&numeric.value()), 0, &length\n );\n if ( result != SQL_SUCCESS ) {\n throw (Diagnostic(handle()));\n }\n ++myNext; return (*this);\n }\n\n PreparedStatement& PreparedStatement::bind ( const Time& time )\n {\n ::SQLLEN length = 0;\n ::SQLRETURN result = ::SQLBindParameter(\n handle().value(), myNext, SQL_PARAM_INPUT, SQL_C_TYPE_TIME,\n SQL_TYPE_TIME, sizeof(::SQL_TIME_STRUCT), 0,\n const_cast<::SQL_TIME_STRUCT*>(&time.value()), 0, &length\n );\n if ( result != SQL_SUCCESS ) {\n throw (Diagnostic(handle()));\n }\n ++myNext; return (*this);\n }\n\n PreparedStatement& PreparedStatement::bind ( const Timestamp& timestamp )\n {\n ::SQLLEN length = 0;\n ::SQLRETURN result = ::SQLBindParameter(\n handle().value(), myNext, SQL_PARAM_INPUT, SQL_C_TYPE_TIMESTAMP,\n SQL_TYPE_TIMESTAMP, sizeof(::SQL_TIMESTAMP_STRUCT), 0,\n const_cast<::SQL_TIMESTAMP_STRUCT*>(×tamp.value()), 0, &length\n );\n if ( result != SQL_SUCCESS ) {\n throw (Diagnostic(handle()));\n }\n ++myNext; return (*this);\n }\n\n PreparedStatement& reset ( PreparedStatement& statement )\n {\n return (statement.reset());\n }\n\n PreparedStatement& execute ( PreparedStatement& statement )\n {\n return (statement.execute());\n }\n\n}\nPrevents 'SQL_NEED_DATA' on 'SQLExecute()'.\/\/ Copyright (c) 2009-2012, Andre Caron (andre.l.caron@gmail.com)\n\/\/ All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are\n\/\/ met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright\n\/\/ notice, this list of conditions and the following disclaimer.\n\/\/\n\/\/ * Redistributions in binary form must reproduce the above copyright\n\/\/ notice, this list of conditions and the following disclaimer in the\n\/\/ documentation and\/or other materials provided with the distribution.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\/\/ \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n\/\/ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n\/\/ A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n\/\/ HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n\/\/ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n\/\/ LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n\/\/ DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n\/\/ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n\/\/ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n\/\/ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\/\/ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY\n\/\/ or FITNESS FOR A PARTICULAR PURPOSE. See the accompanying \"license.txt\" file\n\/\/ for more details.\n\/\/\n\n#include \"PreparedStatement.hpp\"\n#include \"Connection.hpp\"\n#include \"Diagnostic.hpp\"\n\n\/\/ Since ::SQLBindParameter() does not have a const-correct interface. It's 3rd\n\/\/ parameter indicates if it should read or write to the given location. If this\n\/\/ value is SQL_PARAM_INPUT, the data is not modified, even though it requires\n\/\/ write-access to the value. Do not be surprised to see const casts to discard\n\/\/ qualifiers.\n\nnamespace {\n\n \/\/ Shared between all null values. Must be available between calls\n \/\/ to PreparedStatement::bind() and PreparedStatement::execute().\n ::SQLLEN null_value = SQL_NULL_DATA;\n\n \/\/ Shared between all string parameters. Must be available between calls\n \/\/ to PreparedStatement::bind() and PreparedStatement::execute().\n ::SQLLEN null_terminated = SQL_NTS;\n\n}\n\nnamespace sql {\n\n PreparedStatement::PreparedStatement (\n Connection& connection, const string& query\n )\n : Statement(connection), myNext(1)\n {\n \/\/ Indicate the statement will be using bound parameters.\n ::SQLRETURN result = ::SQLPrepare(\n handle().value(), const_cast(query.data()), SQL_NTS\n );\n if ( result != SQL_SUCCESS ) {\n throw (Diagnostic(handle()));\n }\n }\n\n PreparedStatement& PreparedStatement::execute ()\n {\n \/\/ Execute query with currently bound parameters.\n Statement::execute();\n \n \/\/ Prepare for re-execution of the same query.\n return (reset());\n }\n\n PreparedStatement& PreparedStatement::reset ()\n {\n myNext = 1; return (*this);\n }\n\n PreparedStatement& PreparedStatement::bind ( const Null& )\n {\n ::SQLRETURN result = ::SQLBindParameter(\n handle().value(), myNext, SQL_PARAM_INPUT,\n 0, 0, 0, 0, 0, 0, &::null_value\n );\n if ( result != SQL_SUCCESS ) {\n throw (Diagnostic(handle()));\n }\n ++myNext; return (*this);\n }\n\n PreparedStatement& PreparedStatement::bind ( const int8& value )\n {\n ::SQLRETURN result = ::SQLBindParameter(\n handle().value(), myNext, SQL_PARAM_INPUT, SQL_C_STINYINT,\n SQL_TINYINT, 0, 0, const_cast(&value), 0, 0\n );\n if ( result != SQL_SUCCESS ) {\n throw (Diagnostic(handle()));\n }\n ++myNext; return (*this);\n }\n\n PreparedStatement& PreparedStatement::bind ( const uint8& value )\n {\n ::SQLRETURN result = ::SQLBindParameter(\n handle().value(), myNext, SQL_PARAM_INPUT, SQL_C_UTINYINT,\n SQL_TINYINT, 0, 0, const_cast(&value), 0, 0\n );\n if ( result != SQL_SUCCESS ) {\n throw (Diagnostic(handle()));\n }\n ++myNext; return (*this);\n }\n\n PreparedStatement& PreparedStatement::bind ( const int16& value )\n {\n ::SQLRETURN result = ::SQLBindParameter(\n handle().value(), myNext, SQL_PARAM_INPUT, SQL_C_SSHORT,\n SQL_SMALLINT, 0, 0, const_cast(&value), 0, 0\n );\n if ( result != SQL_SUCCESS ) {\n throw (Diagnostic(handle()));\n }\n ++myNext; return (*this);\n }\n\n PreparedStatement& PreparedStatement::bind ( const uint16& value )\n {\n ::SQLRETURN result = ::SQLBindParameter(\n handle().value(), myNext, SQL_PARAM_INPUT, SQL_C_USHORT,\n SQL_SMALLINT, 0, 0, const_cast(&value), 0, 0\n );\n if ( result != SQL_SUCCESS ) {\n throw (Diagnostic(handle()));\n }\n ++myNext; return (*this);\n }\n\n PreparedStatement& PreparedStatement::bind ( const int32& value )\n {\n ::SQLRETURN result = ::SQLBindParameter(\n handle().value(), myNext, SQL_PARAM_INPUT, SQL_C_SLONG,\n SQL_INTEGER, 0, 0, const_cast(&value), 0, 0\n );\n if ( result != SQL_SUCCESS ) {\n throw (Diagnostic(handle()));\n }\n ++myNext; return (*this);\n }\n\n PreparedStatement& PreparedStatement::bind ( const uint32& value )\n {\n ::SQLRETURN result = ::SQLBindParameter(\n handle().value(), myNext, SQL_PARAM_INPUT, SQL_C_ULONG, SQL_INTEGER,\n 0, 0, const_cast(&value), 0, 0\n );\n if ( result != SQL_SUCCESS ) {\n throw (Diagnostic(handle()));\n }\n ++myNext; return (*this);\n }\n\n PreparedStatement& PreparedStatement::bind ( const int64& value )\n {\n ::SQLRETURN result = ::SQLBindParameter(\n handle().value(), myNext, SQL_PARAM_INPUT, SQL_C_SBIGINT,\n SQL_BIGINT, 0, 0, const_cast(&value), 0, 0\n );\n if ( result != SQL_SUCCESS ) {\n throw (Diagnostic(handle()));\n }\n ++myNext; return (*this);\n }\n\n PreparedStatement& PreparedStatement::bind ( const uint64& value )\n {\n ::SQLRETURN result = ::SQLBindParameter(\n handle().value(), myNext, SQL_PARAM_INPUT, SQL_C_UBIGINT,\n SQL_BIGINT, 0, 0, const_cast(&value), 0, 0\n );\n if ( result != SQL_SUCCESS ) {\n throw (Diagnostic(handle()));\n }\n ++myNext; return (*this);\n }\n\n PreparedStatement& PreparedStatement::bind ( const float& value )\n {\n ::SQLRETURN result = ::SQLBindParameter(\n handle().value(), myNext, SQL_PARAM_INPUT, SQL_C_FLOAT, SQL_REAL,\n 0, 0, const_cast(&value), 0, 0\n );\n if ( result != SQL_SUCCESS ) {\n throw (Diagnostic(handle()));\n }\n ++myNext; return (*this);\n }\n\n PreparedStatement& PreparedStatement::bind ( const double& value )\n {\n ::SQLRETURN result = ::SQLBindParameter(\n handle().value(), myNext, SQL_PARAM_INPUT, SQL_C_DOUBLE, SQL_DOUBLE,\n 0, 0, const_cast(&value), 0, 0\n );\n if ( result != SQL_SUCCESS ) {\n throw (Diagnostic(handle()));\n }\n ++myNext; return (*this);\n }\n\n PreparedStatement& PreparedStatement::bind ( const string& value )\n {\n ::SQLRETURN result = ::SQLBindParameter(\n handle().value(), myNext, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_CHAR,\n value.length(), 0, const_cast(value.data()), 0,\n &::null_terminated\n );\n if ( result != SQL_SUCCESS ) {\n throw (Diagnostic(handle()));\n }\n ++myNext; return (*this);\n }\n\n PreparedStatement& PreparedStatement::bind ( const wstring& value )\n {\n ::SQLRETURN result = ::SQLBindParameter(\n handle().value(), myNext, SQL_PARAM_INPUT, SQL_C_WCHAR, SQL_WCHAR,\n value.length(), 0, const_cast(value.data()), 0,\n &::null_terminated\n );\n if ( result != SQL_SUCCESS ) {\n throw (Diagnostic(handle()));\n }\n ++myNext; return (*this);\n }\n\n PreparedStatement& PreparedStatement::bind ( const Date& date )\n {\n ::SQLRETURN result = ::SQLBindParameter(\n handle().value(), myNext, SQL_PARAM_INPUT, SQL_C_TYPE_DATE,\n SQL_TYPE_DATE, SQL_DATE_LEN, 0,\n const_cast<::SQL_DATE_STRUCT*>(&date.value()), 0, 0\n );\n if ( result != SQL_SUCCESS ) {\n throw (Diagnostic(handle()));\n }\n ++myNext; return (*this);\n }\n\n PreparedStatement& PreparedStatement::bind ( const Guid& guid )\n {\n ::SQLRETURN result = ::SQLBindParameter(\n handle().value(), myNext, SQL_PARAM_INPUT, SQL_C_GUID,\n SQL_GUID, sizeof(::SQLGUID), 0,\n const_cast<::SQLGUID*>(&guid.value()), 0, 0\n );\n if ( result != SQL_SUCCESS ) {\n throw (Diagnostic(handle()));\n }\n ++myNext; return (*this);\n }\n\n PreparedStatement& PreparedStatement::bind ( const Numeric& numeric )\n {\n ::SQLRETURN result = ::SQLBindParameter(\n handle().value(), myNext, SQL_PARAM_INPUT, SQL_C_NUMERIC,\n SQL_NUMERIC, sizeof(::SQL_NUMERIC_STRUCT), 0,\n const_cast<::SQL_NUMERIC_STRUCT*>(&numeric.value()), 0, 0\n );\n if ( result != SQL_SUCCESS ) {\n throw (Diagnostic(handle()));\n }\n ++myNext; return (*this);\n }\n\n PreparedStatement& PreparedStatement::bind ( const Time& time )\n {\n ::SQLRETURN result = ::SQLBindParameter(\n handle().value(), myNext, SQL_PARAM_INPUT, SQL_C_TYPE_TIME,\n SQL_TYPE_TIME, SQL_TIME_LEN, 0,\n const_cast<::SQL_TIME_STRUCT*>(&time.value()), 0, 0\n );\n if ( result != SQL_SUCCESS ) {\n throw (Diagnostic(handle()));\n }\n ++myNext; return (*this);\n }\n\n PreparedStatement& PreparedStatement::bind ( const Timestamp& timestamp )\n {\n ::SQLRETURN result = ::SQLBindParameter(\n handle().value(), myNext, SQL_PARAM_INPUT, SQL_C_TYPE_TIMESTAMP,\n SQL_TYPE_TIMESTAMP, sizeof(::SQL_TIMESTAMP_STRUCT), 0,\n const_cast<::SQL_TIMESTAMP_STRUCT*>(×tamp.value()), 0, 0\n );\n if ( result != SQL_SUCCESS ) {\n throw (Diagnostic(handle()));\n }\n ++myNext; return (*this);\n }\n\n PreparedStatement& reset ( PreparedStatement& statement )\n {\n return (statement.reset());\n }\n\n PreparedStatement& execute ( PreparedStatement& statement )\n {\n return (statement.execute());\n }\n\n}\n<|endoftext|>"} {"text":"\/*\n * Copyright (c) 2015 The WebRTC project authors. All Rights Reserved.\n *\n * Use of this source code is governed by a BSD-style license\n * that can be found in the LICENSE file in the root of the source\n * tree. An additional intellectual property rights grant can be found\n * in the file PATENTS. All contributing project authors may\n * be found in the AUTHORS file in the root of the source tree.\n *\/\n\n#include \"testing\/gtest\/include\/gtest\/gtest.h\"\n#include \"webrtc\/base\/arraysize.h\"\n#include \"webrtc\/base\/safe_conversions.h\"\n#include \"webrtc\/modules\/audio_coding\/codecs\/mock\/mock_audio_encoder.h\"\n#include \"webrtc\/modules\/audio_coding\/main\/acm2\/codec_owner.h\"\n\nnamespace webrtc {\nnamespace acm2 {\n\nusing ::testing::Return;\nusing ::testing::InSequence;\n\nnamespace {\nconst int kDataLengthSamples = 80;\nconst int kPacketSizeSamples = 2 * kDataLengthSamples;\nconst int16_t kZeroData[kDataLengthSamples] = {0};\nconst CodecInst kDefaultCodecInst =\n {0, \"pcmu\", 8000, kPacketSizeSamples, 1, 64000};\nconst int kCngPt = 13;\n} \/\/ namespace\n\nclass CodecOwnerTest : public ::testing::Test {\n protected:\n CodecOwnerTest() : timestamp_(0) {}\n\n void CreateCodec() {\n codec_owner_.SetEncoders(kDefaultCodecInst, kCngPt, VADNormal, -1);\n }\n\n void EncodeAndVerify(size_t expected_out_length,\n uint32_t expected_timestamp,\n int expected_payload_type,\n int expected_send_even_if_empty) {\n uint8_t out[kPacketSizeSamples];\n AudioEncoder::EncodedInfo encoded_info;\n encoded_info = codec_owner_.Encoder()->Encode(\n timestamp_, kZeroData, kDataLengthSamples, kPacketSizeSamples, out);\n timestamp_ += kDataLengthSamples;\n EXPECT_TRUE(encoded_info.redundant.empty());\n EXPECT_EQ(expected_out_length, encoded_info.encoded_bytes);\n EXPECT_EQ(expected_timestamp, encoded_info.encoded_timestamp);\n if (expected_payload_type >= 0)\n EXPECT_EQ(expected_payload_type, encoded_info.payload_type);\n if (expected_send_even_if_empty >= 0)\n EXPECT_EQ(static_cast(expected_send_even_if_empty),\n encoded_info.send_even_if_empty);\n }\n\n CodecOwner codec_owner_;\n uint32_t timestamp_;\n};\n\n\/\/ This test verifies that CNG frames are delivered as expected. Since the frame\n\/\/ size is set to 20 ms, we expect the first encode call to produce no output\n\/\/ (which is signaled as 0 bytes output of type kNoEncoding). The next encode\n\/\/ call should produce one SID frame of 9 bytes. The third call should not\n\/\/ result in any output (just like the first one). The fourth and final encode\n\/\/ call should produce an \"empty frame\", which is like no output, but with\n\/\/ AudioEncoder::EncodedInfo::send_even_if_empty set to true. (The reason to\n\/\/ produce an empty frame is to drive sending of DTMF packets in the RTP\/RTCP\n\/\/ module.)\nTEST_F(CodecOwnerTest, VerifyCngFrames) {\n CreateCodec();\n uint32_t expected_timestamp = timestamp_;\n \/\/ Verify no frame.\n {\n SCOPED_TRACE(\"First encoding\");\n EncodeAndVerify(0, expected_timestamp, -1, -1);\n }\n\n \/\/ Verify SID frame delivered.\n {\n SCOPED_TRACE(\"Second encoding\");\n EncodeAndVerify(9, expected_timestamp, kCngPt, 1);\n }\n\n \/\/ Verify no frame.\n {\n SCOPED_TRACE(\"Third encoding\");\n EncodeAndVerify(0, expected_timestamp, -1, -1);\n }\n\n \/\/ Verify NoEncoding.\n expected_timestamp += 2 * kDataLengthSamples;\n {\n SCOPED_TRACE(\"Fourth encoding\");\n EncodeAndVerify(0, expected_timestamp, kCngPt, 1);\n }\n}\n\nTEST_F(CodecOwnerTest, ExternalEncoder) {\n MockAudioEncoder external_encoder;\n codec_owner_.SetEncoders(&external_encoder, -1, VADNormal, -1);\n const int kSampleRateHz = 8000;\n const int kPacketSizeSamples = kSampleRateHz \/ 100;\n int16_t audio[kPacketSizeSamples] = {0};\n uint8_t encoded[kPacketSizeSamples];\n AudioEncoder::EncodedInfo info;\n EXPECT_CALL(external_encoder, SampleRateHz())\n .WillRepeatedly(Return(kSampleRateHz));\n\n {\n InSequence s;\n info.encoded_timestamp = 0;\n EXPECT_CALL(external_encoder,\n EncodeInternal(0, audio, arraysize(encoded), encoded))\n .WillOnce(Return(info));\n EXPECT_CALL(external_encoder, Mark(\"A\"));\n EXPECT_CALL(external_encoder, Mark(\"B\"));\n info.encoded_timestamp = 2;\n EXPECT_CALL(external_encoder,\n EncodeInternal(2, audio, arraysize(encoded), encoded))\n .WillOnce(Return(info));\n EXPECT_CALL(external_encoder, Die());\n }\n\n info = codec_owner_.Encoder()->Encode(0, audio, arraysize(audio),\n arraysize(encoded), encoded);\n EXPECT_EQ(0u, info.encoded_timestamp);\n external_encoder.Mark(\"A\");\n\n \/\/ Change to internal encoder.\n CodecInst codec_inst = kDefaultCodecInst;\n codec_inst.pacsize = kPacketSizeSamples;\n codec_owner_.SetEncoders(codec_inst, -1, VADNormal, -1);\n \/\/ Don't expect any more calls to the external encoder.\n info = codec_owner_.Encoder()->Encode(1, audio, arraysize(audio),\n arraysize(encoded), encoded);\n external_encoder.Mark(\"B\");\n\n \/\/ Change back to external encoder again.\n codec_owner_.SetEncoders(&external_encoder, -1, VADNormal, -1);\n info = codec_owner_.Encoder()->Encode(2, audio, arraysize(audio),\n arraysize(encoded), encoded);\n EXPECT_EQ(2u, info.encoded_timestamp);\n}\n\n} \/\/ namespace acm2\n} \/\/ namespace webrtc\nACM CodecOwner: Test that we reset speech encoder when enabling CNG or RED\/*\n * Copyright (c) 2015 The WebRTC project authors. All Rights Reserved.\n *\n * Use of this source code is governed by a BSD-style license\n * that can be found in the LICENSE file in the root of the source\n * tree. An additional intellectual property rights grant can be found\n * in the file PATENTS. All contributing project authors may\n * be found in the AUTHORS file in the root of the source tree.\n *\/\n\n#include \"testing\/gtest\/include\/gtest\/gtest.h\"\n#include \"webrtc\/base\/arraysize.h\"\n#include \"webrtc\/base\/safe_conversions.h\"\n#include \"webrtc\/modules\/audio_coding\/codecs\/mock\/mock_audio_encoder.h\"\n#include \"webrtc\/modules\/audio_coding\/main\/acm2\/codec_owner.h\"\n\nnamespace webrtc {\nnamespace acm2 {\n\nusing ::testing::Return;\nusing ::testing::InSequence;\n\nnamespace {\nconst int kDataLengthSamples = 80;\nconst int kPacketSizeSamples = 2 * kDataLengthSamples;\nconst int16_t kZeroData[kDataLengthSamples] = {0};\nconst CodecInst kDefaultCodecInst =\n {0, \"pcmu\", 8000, kPacketSizeSamples, 1, 64000};\nconst int kCngPt = 13;\n} \/\/ namespace\n\nclass CodecOwnerTest : public ::testing::Test {\n protected:\n CodecOwnerTest() : timestamp_(0) {}\n\n void CreateCodec() {\n codec_owner_.SetEncoders(kDefaultCodecInst, kCngPt, VADNormal, -1);\n }\n\n void EncodeAndVerify(size_t expected_out_length,\n uint32_t expected_timestamp,\n int expected_payload_type,\n int expected_send_even_if_empty) {\n uint8_t out[kPacketSizeSamples];\n AudioEncoder::EncodedInfo encoded_info;\n encoded_info = codec_owner_.Encoder()->Encode(\n timestamp_, kZeroData, kDataLengthSamples, kPacketSizeSamples, out);\n timestamp_ += kDataLengthSamples;\n EXPECT_TRUE(encoded_info.redundant.empty());\n EXPECT_EQ(expected_out_length, encoded_info.encoded_bytes);\n EXPECT_EQ(expected_timestamp, encoded_info.encoded_timestamp);\n if (expected_payload_type >= 0)\n EXPECT_EQ(expected_payload_type, encoded_info.payload_type);\n if (expected_send_even_if_empty >= 0)\n EXPECT_EQ(static_cast(expected_send_even_if_empty),\n encoded_info.send_even_if_empty);\n }\n\n \/\/ Verify that the speech encoder's Reset method is called when CNG or RED\n \/\/ (or both) are switched on, but not when they're switched off.\n void TestCngAndRedResetSpeechEncoder(bool use_cng, bool use_red) {\n MockAudioEncoder speech_encoder;\n EXPECT_CALL(speech_encoder, NumChannels())\n .WillRepeatedly(Return(1));\n EXPECT_CALL(speech_encoder, Max10MsFramesInAPacket())\n .WillRepeatedly(Return(2));\n EXPECT_CALL(speech_encoder, SampleRateHz())\n .WillRepeatedly(Return(8000));\n {\n InSequence s;\n EXPECT_CALL(speech_encoder, Mark(\"start off\"));\n EXPECT_CALL(speech_encoder, Mark(\"switch on\"));\n if (use_cng || use_red)\n EXPECT_CALL(speech_encoder, Reset());\n EXPECT_CALL(speech_encoder, Mark(\"start on\"));\n if (use_cng || use_red)\n EXPECT_CALL(speech_encoder, Reset());\n EXPECT_CALL(speech_encoder, Mark(\"switch off\"));\n EXPECT_CALL(speech_encoder, Die());\n }\n\n int cng_pt = use_cng ? 17 : -1;\n int red_pt = use_red ? 19 : -1;\n speech_encoder.Mark(\"start off\");\n codec_owner_.SetEncoders(&speech_encoder, -1, VADNormal, -1);\n speech_encoder.Mark(\"switch on\");\n codec_owner_.ChangeCngAndRed(cng_pt, VADNormal, red_pt);\n speech_encoder.Mark(\"start on\");\n codec_owner_.SetEncoders(&speech_encoder, cng_pt, VADNormal, red_pt);\n speech_encoder.Mark(\"switch off\");\n codec_owner_.ChangeCngAndRed(-1, VADNormal, -1);\n }\n\n CodecOwner codec_owner_;\n uint32_t timestamp_;\n};\n\n\/\/ This test verifies that CNG frames are delivered as expected. Since the frame\n\/\/ size is set to 20 ms, we expect the first encode call to produce no output\n\/\/ (which is signaled as 0 bytes output of type kNoEncoding). The next encode\n\/\/ call should produce one SID frame of 9 bytes. The third call should not\n\/\/ result in any output (just like the first one). The fourth and final encode\n\/\/ call should produce an \"empty frame\", which is like no output, but with\n\/\/ AudioEncoder::EncodedInfo::send_even_if_empty set to true. (The reason to\n\/\/ produce an empty frame is to drive sending of DTMF packets in the RTP\/RTCP\n\/\/ module.)\nTEST_F(CodecOwnerTest, VerifyCngFrames) {\n CreateCodec();\n uint32_t expected_timestamp = timestamp_;\n \/\/ Verify no frame.\n {\n SCOPED_TRACE(\"First encoding\");\n EncodeAndVerify(0, expected_timestamp, -1, -1);\n }\n\n \/\/ Verify SID frame delivered.\n {\n SCOPED_TRACE(\"Second encoding\");\n EncodeAndVerify(9, expected_timestamp, kCngPt, 1);\n }\n\n \/\/ Verify no frame.\n {\n SCOPED_TRACE(\"Third encoding\");\n EncodeAndVerify(0, expected_timestamp, -1, -1);\n }\n\n \/\/ Verify NoEncoding.\n expected_timestamp += 2 * kDataLengthSamples;\n {\n SCOPED_TRACE(\"Fourth encoding\");\n EncodeAndVerify(0, expected_timestamp, kCngPt, 1);\n }\n}\n\nTEST_F(CodecOwnerTest, ExternalEncoder) {\n MockAudioEncoder external_encoder;\n codec_owner_.SetEncoders(&external_encoder, -1, VADNormal, -1);\n const int kSampleRateHz = 8000;\n const int kPacketSizeSamples = kSampleRateHz \/ 100;\n int16_t audio[kPacketSizeSamples] = {0};\n uint8_t encoded[kPacketSizeSamples];\n AudioEncoder::EncodedInfo info;\n EXPECT_CALL(external_encoder, SampleRateHz())\n .WillRepeatedly(Return(kSampleRateHz));\n\n {\n InSequence s;\n info.encoded_timestamp = 0;\n EXPECT_CALL(external_encoder,\n EncodeInternal(0, audio, arraysize(encoded), encoded))\n .WillOnce(Return(info));\n EXPECT_CALL(external_encoder, Mark(\"A\"));\n EXPECT_CALL(external_encoder, Mark(\"B\"));\n info.encoded_timestamp = 2;\n EXPECT_CALL(external_encoder,\n EncodeInternal(2, audio, arraysize(encoded), encoded))\n .WillOnce(Return(info));\n EXPECT_CALL(external_encoder, Die());\n }\n\n info = codec_owner_.Encoder()->Encode(0, audio, arraysize(audio),\n arraysize(encoded), encoded);\n EXPECT_EQ(0u, info.encoded_timestamp);\n external_encoder.Mark(\"A\");\n\n \/\/ Change to internal encoder.\n CodecInst codec_inst = kDefaultCodecInst;\n codec_inst.pacsize = kPacketSizeSamples;\n codec_owner_.SetEncoders(codec_inst, -1, VADNormal, -1);\n \/\/ Don't expect any more calls to the external encoder.\n info = codec_owner_.Encoder()->Encode(1, audio, arraysize(audio),\n arraysize(encoded), encoded);\n external_encoder.Mark(\"B\");\n\n \/\/ Change back to external encoder again.\n codec_owner_.SetEncoders(&external_encoder, -1, VADNormal, -1);\n info = codec_owner_.Encoder()->Encode(2, audio, arraysize(audio),\n arraysize(encoded), encoded);\n EXPECT_EQ(2u, info.encoded_timestamp);\n}\n\nTEST_F(CodecOwnerTest, CngResetsSpeechEncoder) {\n TestCngAndRedResetSpeechEncoder(true, false);\n}\n\nTEST_F(CodecOwnerTest, RedResetsSpeechEncoder) {\n TestCngAndRedResetSpeechEncoder(false, true);\n}\n\nTEST_F(CodecOwnerTest, CngAndRedResetsSpeechEncoder) {\n TestCngAndRedResetSpeechEncoder(true, true);\n}\n\nTEST_F(CodecOwnerTest, NoCngAndRedNoSpeechEncoderReset) {\n TestCngAndRedResetSpeechEncoder(false, false);\n}\n\n} \/\/ namespace acm2\n} \/\/ namespace webrtc\n<|endoftext|>"} {"text":"#include \n\/\/#include \"FunctorNew.h\"\n\n\/\/#include \"Math\/IGenFunction.h\"\n#include \"Math\/WrappedFunction.h\"\n\/\/#include \"Fit\/WrappedTF1.h\"\n#include \"TStopwatch.h\"\n#include \n#include \"TRandom2.h\"\n#include \"TF1.h\"\n#include \"TF2.h\"\n#include \"Math\/WrappedTF1.h\"\n#include \"Math\/WrappedMultiTF1.h\"\n\n#ifdef HAVE_ROOFIT\n#include \"RooRealVar.h\"\n#include \"RooArgList.h\"\n#include \"RooExponential.h\"\n#endif\n\n#include \"Math\/IFunctionfwd.h\"\n#include \"Math\/IFunction.h\"\n#include \"Math\/Functor.h\"\n\n#include \n\n#define NLOOP 100\n#define NTIMES 1000000\n#define FUNC x[0]+x[1]\n\/\/#define FUNC x[0]*std::exp(x[1])\n\/\/#define FUNC 100 * (x[1]-x[0]*x[0])*(x[1]-x[0]*x[0]) + (1.-x[0])*(1-x[0])\n\n#define FUNC1D x+x; \n\/\/#define FUNC1D std::exp(x); \n\ndouble freeFunction(const double * x ) { \n return FUNC; \n \/\/return ; \n}\n\ndouble freeRootFunc2D(double *x, double *){ \n return FUNC;\n}\ndouble freeRootFunc1D(double *xx, double *){ \n double x = *xx;\n return FUNC1D;\n}\n\ndouble freeFunction1D(double x ) { \n return FUNC1D; \n}\n\n\nclass MyFunction { \n\n\npublic: \n double operator()(const double *x) const { \n return FUNC; \n \/\/return x[0]*std::exp(x[1]); \n } \n \n double Derivative(const double * x, int \/* icoord *\/) const { return FUNC; }\n double Eval(const double * x) const { return FUNC; }\n};\n\n\nclass MyFunction1D { \n\n\npublic: \n\n double operator()(double x) const { \n return FUNC1D; \n } \n\n double operator()(const double * x) const { \n return (*this)(*x); \n } \n \n double Derivative(double x) const { return FUNC1D; }\n};\n\n\n\nclass DerivFunction : public ROOT::Math::IMultiGenFunction { \n\npublic: \n\n\n unsigned int NDim() const { return 2; }\n\n DerivFunction * Clone() const { \n return new DerivFunction(); \n } \n\nprivate: \n\n\n double DoEval(const double *x) const { \n return FUNC; \n } \n\n};\n\n\nclass DerivFunction1D : public ROOT::Math::IGenFunction { \n\npublic: \n\n DerivFunction1D * Clone() const { \n return new DerivFunction1D(); \n } \n\nprivate: \n\n\n double DoEval(double x) const { \n return FUNC1D; \n } \n\n};\n\nstruct F1D { \n double Eval(double x) {\n return FUNC1D; \n }\n}; \n\n\nconst int Ntimes = NTIMES; \n\ntemplate \nvoid TestTime(const Func & f) { \n double x[Ntimes]; \n TStopwatch w; \n TRandom2 r; \n r.RndmArray(Ntimes,x);\n w. Start(); \n double s=0;\n for (int ipass = 0; ipass (&arg); \n\/\/ assert(x != 0);\n for (int ipass = 0; ipass setVal(x[i+1]);\n double y = x[i]*f.getVal(); \n s+= y; \n }\n }\n w.Stop(); \n std::cout << \"Time for \" << \"RooPdf\\t\\t\" << \"\\t: \" << w.RealTime() << \" \" << w.CpuTime() << std::endl; \n std::cout << s << std::endl;\n}\n#endif\n\n\nint main() { \n\n\n \n MyFunction myf;\n TestTime(myf);\n\n MyFunction1D myf1;\n TestTime(myf1);\n\n ROOT::Math::Functor f1(myf,2); \n TestTime(f1);\n\n ROOT::Math::Functor f2(&freeFunction,2); \n TestTime(f2);\n\n\n DerivFunction f3; \n TestTime(f3);\n\n ROOT::Math::Functor f4(&myf,&MyFunction::Eval,2); \n TestTime(f4);\n\n \/\/1D\n\n ROOT::Math::Functor1D f11(myf1); \n TestTime(f11);\n\n ROOT::Math::Functor1D f12(&freeFunction1D); \n TestTime(f12);\n\n DerivFunction1D f13; \n TestTime(f13);\n\n ROOT::Math::Functor1D f14(&myf1,&MyFunction1D::Derivative); \n TestTime(f14);\n \n\n \n \/\/TestTimeGF(f3); \n typedef double( * FreeFunc ) (double ); \n ROOT::Math::WrappedFunction<> f5(freeFunction1D);\n TestTime(f5);\n\n F1D fobj;\n \/\/std::cout << typeid(&F1D::Eval).name() << std::endl;\n ROOT::Math::Functor1D f6(std::bind1st(std::mem_fun(&F1D::Eval), &fobj) );\n TestTime(f6);\n\n ROOT::Math::WrappedFunction > > f6a((std::bind1st(std::mem_fun(&F1D::Eval), &fobj)));\n TestTime(f6a);\n\n \/\/ROOT::Math::WrappedMemFunction f6b(&fobj, &F1D::Eval, );\n \n\/\/ typedef double (F1D::*MemFun)(double); \n\/\/ double (F1D::*p1 )(double) = &F1D::Eval; \n\/\/ std::cout << typeid(p1).name() << std::endl; \n ROOT::Math::WrappedMemFunction f6b(fobj, &F1D::Eval );\n TestTime(f6b);\n\n ROOT::Math::Functor1D f6c(&fobj, &F1D::Eval );\n TestTime(f6c);\n\n\n\n#ifdef LATER\n FunctorNV f5(myf);\n TestTime(f5);\n\n \/\/ test of virtuality two times \n Functor f6(f3);\n TestTime(f6);\n#endif\n \n TF1 tf1(\"tf1\",freeRootFunc2D,0,1,0);\n \/\/TF2 tf1(\"tf1\",\"x+y\",0,1,0,1);\n TestTimeTF1(tf1);\n\n\/\/ ROOT::Fit::WrappedTF1 f7(&tf1);\n\/\/ TestTime(f7);\n\n ROOT::Math::WrappedMultiTF1 f7b(tf1);\n TestTime(f7b);\n\n TF1 tf2(\"tf2\",freeRootFunc1D,0,1,0);\n TestTimeTF1(tf2);\n\n ROOT::Math::WrappedTF1 f7c(tf2);\n TestTime(f7c);\n \n\/\/ double xx[1] = {2};\n\/\/ f7(xx);\n\n ROOT::Math::Functor f8(f7b,f7b.NDim());\n TestTime(f8);\n\n\/\/ this does not compile oin Windows, since it does not understand the default arguments\n#ifndef _WIN32\n ROOT::Math::Functor1D f9(&tf1,&TF1::Eval);\n TestTime(f9);\n\n ROOT::Math::Functor f10(&tf1,&TF1::EvalPar,tf1.GetNdim());\n TestTime(f10);\n#endif\n \n\n\n \/\/ test with rootit\n#ifdef HAVE_ROOFIT\n RooRealVar x(\"x\",\"x\",0);\n RooRealVar c(\"c\",\"c\",1.,1.,1.);\n RooExponential rooExp(\"exp\",\"exponential\",x,c);\n TestTimeRooPdf(rooExp,&x);\n#endif\n\n return 0;\n}\nfix a problem on Windows due to too large allocated stack memory#include \n\/\/#include \"FunctorNew.h\"\n\n\/\/#include \"Math\/IGenFunction.h\"\n#include \"Math\/WrappedFunction.h\"\n\/\/#include \"Fit\/WrappedTF1.h\"\n#include \"TStopwatch.h\"\n#include \n#include \"TRandom2.h\"\n#include \"TF1.h\"\n#include \"TF2.h\"\n#include \"Math\/WrappedTF1.h\"\n#include \"Math\/WrappedMultiTF1.h\"\n\n#ifdef HAVE_ROOFIT\n#include \"RooRealVar.h\"\n#include \"RooArgList.h\"\n#include \"RooExponential.h\"\n#endif\n\n#include \"Math\/IFunctionfwd.h\"\n#include \"Math\/IFunction.h\"\n#include \"Math\/Functor.h\"\n\n#include \n#include \n\n#define NLOOP 100\n#define NTIMES 500000\n#define FUNC x[0]+x[1]\n\/\/#define FUNC x[0]*std::exp(x[1])\n\/\/#define FUNC 100 * (x[1]-x[0]*x[0])*(x[1]-x[0]*x[0]) + (1.-x[0])*(1-x[0])\n\n#define FUNC1D x+x; \n\/\/#define FUNC1D std::exp(x); \n\ndouble freeFunction(const double * x ) { \n return FUNC; \n \/\/return ; \n}\n\ndouble freeRootFunc2D(double *x, double *){ \n return FUNC;\n}\ndouble freeRootFunc1D(double *xx, double *){ \n double x = *xx;\n return FUNC1D;\n}\n\ndouble freeFunction1D(double x ) { \n return FUNC1D; \n}\n\n\nclass MyFunction { \n\n\npublic: \n double operator()(const double *x) const { \n return FUNC; \n \/\/return x[0]*std::exp(x[1]); \n } \n \n double Derivative(const double * x, int \/* icoord *\/) const { return FUNC; }\n double Eval(const double * x) const { return FUNC; }\n};\n\n\nclass MyFunction1D { \n\n\npublic: \n\n double operator()(double x) const { \n return FUNC1D; \n } \n\n double operator()(const double * x) const { \n return (*this)(*x); \n } \n \n double Derivative(double x) const { return FUNC1D; }\n};\n\n\n\nclass DerivFunction : public ROOT::Math::IMultiGenFunction { \n\npublic: \n\n\n unsigned int NDim() const { return 2; }\n\n DerivFunction * Clone() const { \n return new DerivFunction(); \n } \n\nprivate: \n\n\n double DoEval(const double *x) const { \n return FUNC; \n } \n\n};\n\n\nclass DerivFunction1D : public ROOT::Math::IGenFunction { \n\npublic: \n\n DerivFunction1D * Clone() const { \n return new DerivFunction1D(); \n } \n\nprivate: \n\n\n double DoEval(double x) const { \n return FUNC1D; \n } \n\n};\n\nstruct F1D { \n double Eval(double x) {\n return FUNC1D; \n }\n}; \n\n\nconst int Ntimes = NTIMES; \n\ntemplate \nvoid TestTime(const Func & f) { \n \/\/double x[Ntimes]; \n \/\/ use std::vector's to avoid crashes on Windows \n std::vector x(Ntimes); \n TStopwatch w; \n TRandom2 r; \n r.RndmArray(Ntimes,&x[0]);\n w. Start(); \n double s=0;\n for (int ipass = 0; ipass x(Ntimes); \n TStopwatch w; \n TRandom2 r; \n r.RndmArray(Ntimes,&x[0]);\n w. Start(); \n double s=0;\n for (int ipass = 0; ipass x(Ntimes); \n TStopwatch w; \n TRandom2 r; \n r.RndmArray(Ntimes,&x[0]);\n w. Start(); \n double s=0;\n\/\/ RooArgSet * varSet = f.getVariables(); \n\/\/ RooArgList varList(*varSet); \n\/\/ delete varSet; \n\/\/ RooAbsArg & arg = varList[0];\n\/\/ RooRealVar * vars = dynamic_cast (&arg); \n\/\/ assert(x != 0);\n for (int ipass = 0; ipass setVal(x[i+1]);\n double y = x[i]*f.getVal(); \n s+= y; \n }\n }\n w.Stop(); \n std::cout << \"Time for \" << \"RooPdf\\t\\t\" << \"\\t: \" << w.RealTime() << \" \" << w.CpuTime() << std::endl; \n std::cout << s << std::endl;\n}\n#endif\n\n\nint main() { \n\n\n \n MyFunction myf;\n TestTime(myf);\n\n MyFunction1D myf1;\n TestTime(myf1);\n\n ROOT::Math::Functor f1(myf,2); \n TestTime(f1);\n\n ROOT::Math::Functor f2(&freeFunction,2); \n TestTime(f2);\n\n\n DerivFunction f3; \n TestTime(f3);\n\n ROOT::Math::Functor f4(&myf,&MyFunction::Eval,2); \n TestTime(f4);\n\n \/\/1D\n\n ROOT::Math::Functor1D f11(myf1); \n TestTime(f11);\n\n ROOT::Math::Functor1D f12(&freeFunction1D); \n TestTime(f12);\n\n DerivFunction1D f13; \n TestTime(f13);\n\n ROOT::Math::Functor1D f14(&myf1,&MyFunction1D::Derivative); \n TestTime(f14);\n \n\n \n \/\/TestTimeGF(f3); \n typedef double( * FreeFunc ) (double ); \n ROOT::Math::WrappedFunction<> f5(freeFunction1D);\n TestTime(f5);\n\n F1D fobj;\n \/\/std::cout << typeid(&F1D::Eval).name() << std::endl;\n ROOT::Math::Functor1D f6(std::bind1st(std::mem_fun(&F1D::Eval), &fobj) );\n TestTime(f6);\n\n ROOT::Math::WrappedFunction > > f6a((std::bind1st(std::mem_fun(&F1D::Eval), &fobj)));\n TestTime(f6a);\n\n \/\/ROOT::Math::WrappedMemFunction f6b(&fobj, &F1D::Eval, );\n \n\/\/ typedef double (F1D::*MemFun)(double); \n\/\/ double (F1D::*p1 )(double) = &F1D::Eval; \n\/\/ std::cout << typeid(p1).name() << std::endl; \n ROOT::Math::WrappedMemFunction f6b(fobj, &F1D::Eval );\n TestTime(f6b);\n\n ROOT::Math::Functor1D f6c(&fobj, &F1D::Eval );\n TestTime(f6c);\n\n\n\n#ifdef LATER\n FunctorNV f5(myf);\n TestTime(f5);\n\n \/\/ test of virtuality two times \n Functor f6(f3);\n TestTime(f6);\n#endif\n \n TF1 tf1(\"tf1\",freeRootFunc2D,0,1,0);\n \/\/TF2 tf1(\"tf1\",\"x+y\",0,1,0,1);\n TestTimeTF1(tf1);\n\n\/\/ ROOT::Fit::WrappedTF1 f7(&tf1);\n\/\/ TestTime(f7);\n\n ROOT::Math::WrappedMultiTF1 f7b(tf1);\n TestTime(f7b);\n\n TF1 tf2(\"tf2\",freeRootFunc1D,0,1,0);\n TestTimeTF1(tf2);\n\n ROOT::Math::WrappedTF1 f7c(tf2);\n TestTime(f7c);\n \n\/\/ double xx[1] = {2};\n\/\/ f7(xx);\n\n ROOT::Math::Functor f8(f7b,f7b.NDim());\n TestTime(f8);\n\n\/\/ this does not compile oin Windows, since it does not understand the default arguments\n#ifndef _WIN32\n ROOT::Math::Functor1D f9(&tf1,&TF1::Eval);\n TestTime(f9);\n\n ROOT::Math::Functor f10(&tf1,&TF1::EvalPar,tf1.GetNdim());\n TestTime(f10);\n#endif\n \n\n\n \/\/ test with rootit\n#ifdef HAVE_ROOFIT\n RooRealVar x(\"x\",\"x\",0);\n RooRealVar c(\"c\",\"c\",1.,1.,1.);\n RooExponential rooExp(\"exp\",\"exponential\",x,c);\n TestTimeRooPdf(rooExp,&x);\n#endif\n\n return 0;\n}\n<|endoftext|>"} {"text":"\/* \n * jcom.parameter\n * External for Jamoma: parameter definition\n * By Tim Place and Théo de la Hogue, Copyright © 2011\n * \n * License: This code is licensed under the terms of the \"New BSD License\"\n * http:\/\/creativecommons.org\/licenses\/BSD\/\n *\/\n\n#include \"TTModularClassWrapperMax.h\"\n\n#define data_out 0\n#define\tdump_out 1\n\n\/\/ Definitions\nvoid\t\tWrapTTDataClass(WrappedClassPtr c);\nvoid\t\tWrappedDataClass_new(TTPtr self, AtomCount argc, AtomPtr argv);\n\nvoid\t\tdata_assist(TTPtr self, TTPtr b, long msg, AtomCount arg, char *dst);\n\nvoid\t\tdata_new_address(TTPtr self, SymbolPtr msg, AtomCount argc, AtomPtr argv);\nvoid\t\tdata_subscribe(TTPtr self, SymbolPtr address, AtomCount argc, AtomPtr argv);\nvoid\t\tdata_address(TTPtr self, SymbolPtr name);\n\n#ifndef JMOD_RETURN\nvoid\t\tdata_return_value(TTPtr self, SymbolPtr msg, AtomCount argc, AtomPtr argv);\n#endif\n\n#ifndef JMOD_MESSAGE\nvoid\t\tWrappedDataClass_anything(TTPtr self, SymbolPtr msg, AtomCount argc, AtomPtr argv);\nvoid\t\tdata_bang(TTPtr self);\nvoid\t\tdata_int(TTPtr self, long value);\nvoid\t\tdata_float(TTPtr self, double value);\nvoid\t\tdata_list(TTPtr self, SymbolPtr msg, AtomCount argc, AtomPtr argv);\n\nvoid\t\tdata_inc(TTPtr self, SymbolPtr msg, AtomCount argc, AtomPtr argv);\nvoid\t\tdata_dec(TTPtr self, SymbolPtr msg, AtomCount argc, AtomPtr argv);\n#endif\n\nint TTCLASSWRAPPERMAX_EXPORT main(void)\n{\n\tModularSpec *spec = new ModularSpec;\n\tspec->_wrap = &WrapTTDataClass;\n\tspec->_new = &WrappedDataClass_new;\n\tspec->_free = NULL;\n#ifndef JMOD_MESSAGE\n\tspec->_any = &WrappedDataClass_anything;\n#else\n\tspec->_any = NULL;\n#endif\n\t\n#ifdef JMOD_MESSAGE\n\treturn wrapTTModularClassAsMaxClass(kTTSym_Data, \"jcom.message\", NULL, spec);\n#endif\n\t\n#ifdef JMOD_RETURN\n\treturn wrapTTModularClassAsMaxClass(kTTSym_Data, \"jcom.return\", NULL, spec);\n#endif\n\t\n#ifndef JMOD_MESSAGE\n#ifndef JMOD_RETURN\n\treturn wrapTTModularClassAsMaxClass(kTTSym_Data, \"jcom.parameter\", NULL, spec);\n#endif\n#endif\n}\n\nvoid WrapTTDataClass(WrappedClassPtr c)\n{\n\tclass_addmethod(c->maxClass, (method)data_assist,\t\t\t\t\t\t\"assist\",\t\t\t\tA_CANT, 0L);\n\t\n#ifndef JMOD_RETURN\n\tclass_addmethod(c->maxClass, (method)data_return_value,\t\t\t\t\t\"return_value\",\t\t\tA_CANT, 0);\n#endif\n\t\n#ifndef JMOD_MESSAGE\t\n\tclass_addmethod(c->maxClass, (method)data_bang,\t\t\t\t\t\t\t\"bang\",\t\t\t\t\t0L);\n\tclass_addmethod(c->maxClass, (method)data_int,\t\t\t\t\t\t\t\"int\",\t\t\t\t\tA_LONG, 0);\n\tclass_addmethod(c->maxClass, (method)data_float,\t\t\t\t\t\t\"float\",\t\t\t\tA_FLOAT, 0);\n\tclass_addmethod(c->maxClass, (method)data_list,\t\t\t\t\t\t\t\"list\",\t\t\t\t\tA_GIMME, 0);\n\t\n\tclass_addmethod(c->maxClass, (method)data_inc,\t\t\t\t\t\t\t\"+\",\t\t\t\t\tA_GIMME, 0);\n\tclass_addmethod(c->maxClass, (method)data_dec,\t\t\t\t\t\t\t\"-\",\t\t\t\t\tA_GIMME, 0);\n#endif\n\t\n\tclass_addmethod(c->maxClass, (method)data_address,\t\t\t\t\t\t\"address\",\t\t\t\tA_SYM,0);\n}\n\nvoid WrappedDataClass_new(TTPtr self, AtomCount argc, AtomPtr argv)\n{\n\tWrappedModularInstancePtr\tx = (WrappedModularInstancePtr)self;\n\tSymbolPtr\t\t\t\t\trelativeAddress;\n\tlong\t\t\t\t\t\tattrstart = attr_args_offset(argc, argv);\t\t\t\/\/ support normal arguments\n\t\n\t\/\/ check address argument\n\trelativeAddress = _sym_nothing;\n\tif (attrstart && argv)\n\t\tif (atom_gettype(argv) == A_SYM)\n\t\t\trelativeAddress = atom_getsym(argv);\n\t\n\tif (relativeAddress == _sym_nothing) {\n\t\tobject_error((ObjectPtr)x, \"needs a name as first argument\");\n\t\treturn;\n\t}\n\t\n\t\/\/ Make outlets (before attr_args_process)\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n#ifndef JMOD_RETURN\n\t\n\t\/\/ Don't create outlets during dynamic changes\n\t\tx->outlets = (TTHandle)sysmem_newptr(sizeof(TTPtr) * 2);\n\t\tx->outlets[data_out] = outlet_new(x, NULL);\t\t\t\t\t\t\/\/ anything outlet to output data\n\n#endif\n\n\tdata_new_address(self, relativeAddress, argc--, argv++);\n}\n\t\nvoid data_new_address(TTPtr self, SymbolPtr relativeAddress, AtomCount argc, AtomPtr argv)\n{\n\tWrappedModularInstancePtr\tx = (WrappedModularInstancePtr)self;\n\t\n\tx->useInternals = false;\n\t\n\t\/\/ create the data\n#ifdef JMOD_MESSAGE\n\tjamoma_data_create((ObjectPtr)x, &x->wrappedObject, kTTSym_message);\n#endif\n\t\n#if JMOD_RETURN\n\tjamoma_data_create((ObjectPtr)x, &x->wrappedObject, kTTSym_return);\n#endif\n\t\n#ifndef JMOD_MESSAGE\n#ifndef JMOD_RETURN\n\tjamoma_data_create((ObjectPtr)x, &x->wrappedObject, kTTSym_parameter);\n#endif\n#endif\n \n if (argc && argv)\n attr_args_process(x, argc, argv);\n\t\n\t\/\/ The following must be deferred because we have to interrogate our box,\n\t\/\/ and our box is not yet valid until we have finished instantiating the object.\n\t\/\/ Trying to use a loadbang method instead is also not fully successful (as of Max 5.0.6)\n\tdefer_low((ObjectPtr)x, (method)data_subscribe, relativeAddress, argc, argv);\n}\n\nvoid data_subscribe(TTPtr self, SymbolPtr relativeAddress, AtomCount argc, AtomPtr argv)\n{\n\tWrappedModularInstancePtr\tx = (WrappedModularInstancePtr)self;\n\n\t\/\/ for relative address\n\tif (TTAddress(relativeAddress->s_name).getType() == kAddressRelative) {\n\t\tjamoma_subscriber_create((ObjectPtr)x, x->wrappedObject, TTAddress(jamoma_parse_dieze((ObjectPtr)x, relativeAddress)->s_name), &x->subscriberObject);\n\t\t\n\t\t\n\t}\n\telse\n\t\tobject_error((ObjectPtr)x, \"can't register because %s is not a relative address\", relativeAddress->s_name);\n}\n\nvoid data_address(TTPtr self, SymbolPtr address)\n{\n\tWrappedModularInstancePtr\tx = (WrappedModularInstancePtr)self;\n\t\n\t\/\/ unregister wrapped object (or internals)\n\twrappedModularClass_unregister(x);\n\t\n\t\/\/ rebuild wrapped object (or internals)\n\tdefer_low(self,(method)data_new_address, address, 0, NULL); \/\/ TODO : give all @attribute too\n}\n\n\/\/ Method for Assistance Messages\nvoid data_assist(TTPtr self, TTPtr b, long msg, AtomCount arg, char *dst)\n{\n\tif (msg==1) \t\t\t\t\t\t\/\/ Inlet\n\t\tstrcpy(dst, \"input\");\n\telse {\t\t\t\t\t\t\t\/\/ Outlets\n\t\tswitch(arg) {\n\t\t\tcase data_out:\n\t\t\t\tstrcpy(dst, \"direct: values\");\n\t\t\t\tbreak;\n\t\t\tcase dump_out:\n\t\t\t\tstrcpy(dst, \"dumpout\");\n\t\t\t\tbreak;\n\t\t}\n \t}\n}\n\n#ifndef JMOD_MESSAGE\nvoid data_bang(TTPtr self)\n{\n\tdata_list(self, _sym_bang, 0, NULL);\n}\n\nvoid data_int(TTPtr self, long value)\n{\n\tt_atom a;\n\t\n\tatom_setlong(&a, value);\n\tdata_list(self, _sym_int, 1, &a);\n}\n\nvoid data_float(TTPtr self, double value)\n{\n\tt_atom a;\n\t\n\tatom_setfloat(&a, value);\n\tdata_list(self, _sym_float, 1, &a);\n}\n\nvoid data_list(TTPtr self, t_symbol *msg, long argc, t_atom *argv)\n{\n\tWrappedModularInstancePtr\tx = (WrappedModularInstancePtr)self;\n\n\tjamoma_data_command((TTDataPtr)selectedObject, msg, argc, argv);\n}\n\nvoid WrappedDataClass_anything(TTPtr self, SymbolPtr msg, AtomCount argc, AtomPtr argv)\n{\n\tWrappedModularInstancePtr\tx = (WrappedModularInstancePtr)self;\n\t\n\tjamoma_data_command((TTDataPtr)selectedObject, msg, argc, argv);\n}\n#endif\n\n#ifndef JMOD_RETURN\nvoid data_return_value(TTPtr self, SymbolPtr msg, AtomCount argc, AtomPtr argv)\n{\n\tWrappedModularInstancePtr\tx = (WrappedModularInstancePtr)self;\n\t\n\t\/\/ avoid blank before data\n\tif (msg == _sym_nothing)\n\t\toutlet_atoms(x->outlets[data_out], argc, argv);\n\telse\n\t\toutlet_anything(x->outlets[data_out], msg, argc, argv);\n}\n#endif\n\n#ifndef JMOD_MESSAGE\nvoid data_inc(TTPtr self, SymbolPtr msg, AtomCount argc, AtomPtr argv)\n{\n\tWrappedModularInstancePtr\tx = (WrappedModularInstancePtr)self;\n\tTTValue v;\n\n\tjamoma_ttvalue_from_Atom(v, _sym_nothing, argc, argv);\n\tselectedObject->sendMessage(TTSymbol(\"Inc\"), v, kTTValNONE);\n}\n\nvoid data_dec(TTPtr self, SymbolPtr msg, AtomCount argc, AtomPtr argv)\n{\n\tWrappedModularInstancePtr\tx = (WrappedModularInstancePtr)self;\n\tTTValue v;\n\t\n\tjamoma_ttvalue_from_Atom(v, _sym_nothing, argc, argv);\n\tselectedObject->sendMessage(TTSymbol(\"Dec\"), v, kTTValNONE);\n}\n#endifStoring arguments to recall them when address change\/* \n * jcom.parameter\n * External for Jamoma: parameter definition\n * By Tim Place and Théo de la Hogue, Copyright © 2011\n * \n * License: This code is licensed under the terms of the \"New BSD License\"\n * http:\/\/creativecommons.org\/licenses\/BSD\/\n *\/\n\n#include \"TTModularClassWrapperMax.h\"\n\n#define data_out 0\n#define\tdump_out 1\n\n\/\/ This is used to store extra data\ntypedef struct extra {\n\t\n\tTTValue arrayArgs;\t\t\/\/ store arguments\n\n} t_extra;\n#define EXTRA ((t_extra*)x->extra)\n\n\n\/\/ Definitions\nvoid\t\tWrapTTDataClass(WrappedClassPtr c);\nvoid\t\tWrappedDataClass_new(TTPtr self, AtomCount argc, AtomPtr argv);\nvoid WrappedDataClass_free(TTPtr self);\n\nvoid\t\tdata_assist(TTPtr self, TTPtr b, long msg, AtomCount arg, char *dst);\n\nvoid\t\tdata_new_address(TTPtr self, SymbolPtr msg, AtomCount argc, AtomPtr argv);\nvoid\t\tdata_subscribe(TTPtr self, SymbolPtr address, AtomCount argc, AtomPtr argv);\nvoid\t\tdata_address(TTPtr self, SymbolPtr name);\n\n#ifndef JMOD_RETURN\nvoid\t\tdata_return_value(TTPtr self, SymbolPtr msg, AtomCount argc, AtomPtr argv);\n#endif\n\n#ifndef JMOD_MESSAGE\nvoid\t\tWrappedDataClass_anything(TTPtr self, SymbolPtr msg, AtomCount argc, AtomPtr argv);\nvoid\t\tdata_bang(TTPtr self);\nvoid\t\tdata_int(TTPtr self, long value);\nvoid\t\tdata_float(TTPtr self, double value);\nvoid\t\tdata_list(TTPtr self, SymbolPtr msg, AtomCount argc, AtomPtr argv);\n\nvoid\t\tdata_inc(TTPtr self, SymbolPtr msg, AtomCount argc, AtomPtr argv);\nvoid\t\tdata_dec(TTPtr self, SymbolPtr msg, AtomCount argc, AtomPtr argv);\n#endif\n\nint TTCLASSWRAPPERMAX_EXPORT main(void)\n{\n\tModularSpec *spec = new ModularSpec;\n\tspec->_wrap = &WrapTTDataClass;\n\tspec->_new = &WrappedDataClass_new;\n\tspec->_free = &WrappedDataClass_free;\n#ifndef JMOD_MESSAGE\n\tspec->_any = &WrappedDataClass_anything;\n#else\n\tspec->_any = NULL;\n#endif\n\t\n#ifdef JMOD_MESSAGE\n\treturn wrapTTModularClassAsMaxClass(kTTSym_Data, \"jcom.message\", NULL, spec);\n#endif\n\t\n#ifdef JMOD_RETURN\n\treturn wrapTTModularClassAsMaxClass(kTTSym_Data, \"jcom.return\", NULL, spec);\n#endif\n\t\n#ifndef JMOD_MESSAGE\n#ifndef JMOD_RETURN\n\treturn wrapTTModularClassAsMaxClass(kTTSym_Data, \"jcom.parameter\", NULL, spec);\n#endif\n#endif\n}\n\nvoid WrapTTDataClass(WrappedClassPtr c)\n{\n\tclass_addmethod(c->maxClass, (method)data_assist,\t\t\t\t\t\t\"assist\",\t\t\t\tA_CANT, 0L);\n\t\n#ifndef JMOD_RETURN\n\tclass_addmethod(c->maxClass, (method)data_return_value,\t\t\t\t\t\"return_value\",\t\t\tA_CANT, 0);\n#endif\n\t\n#ifndef JMOD_MESSAGE\t\n\tclass_addmethod(c->maxClass, (method)data_bang,\t\t\t\t\t\t\t\"bang\",\t\t\t\t\t0L);\n\tclass_addmethod(c->maxClass, (method)data_int,\t\t\t\t\t\t\t\"int\",\t\t\t\t\tA_LONG, 0);\n\tclass_addmethod(c->maxClass, (method)data_float,\t\t\t\t\t\t\"float\",\t\t\t\tA_FLOAT, 0);\n\tclass_addmethod(c->maxClass, (method)data_list,\t\t\t\t\t\t\t\"list\",\t\t\t\t\tA_GIMME, 0);\n\t\n\tclass_addmethod(c->maxClass, (method)data_inc,\t\t\t\t\t\t\t\"+\",\t\t\t\t\tA_GIMME, 0);\n\tclass_addmethod(c->maxClass, (method)data_dec,\t\t\t\t\t\t\t\"-\",\t\t\t\t\tA_GIMME, 0);\n#endif\n\t\n\tclass_addmethod(c->maxClass, (method)data_address,\t\t\t\t\t\t\"address\",\t\t\t\tA_SYM,0);\n}\n\nvoid WrappedDataClass_new(TTPtr self, AtomCount argc, AtomPtr argv)\n{\n\tWrappedModularInstancePtr\tx = (WrappedModularInstancePtr)self;\n\tSymbolPtr\t\t\t\t\trelativeAddress;\n\tlong\t\t\t\t\t\tattrstart = attr_args_offset(argc, argv);\t\t\t\/\/ support normal arguments\n\t\n\t\/\/ check address argument\n\trelativeAddress = _sym_nothing;\n\tif (attrstart && argv)\n\t\tif (atom_gettype(argv) == A_SYM)\n\t\t\trelativeAddress = atom_getsym(argv);\n\t\n\tif (relativeAddress == _sym_nothing) {\n\t\tobject_error((ObjectPtr)x, \"needs a name as first argument\");\n\t\treturn;\n\t}\n\t\n\t\/\/ Make outlets (before attr_args_process)\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n#ifndef JMOD_RETURN\n\t\n\t\/\/ Don't create outlets during dynamic changes\n\t\tx->outlets = (TTHandle)sysmem_newptr(sizeof(TTPtr) * 2);\n\t\tx->outlets[data_out] = outlet_new(x, NULL);\t\t\t\t\t\t\/\/ anything outlet to output data\n\n#endif\n \n \/\/ Prepare extra data\n\tx->extra = (t_extra*)malloc(sizeof(t_extra));\n \n EXTRA->arrayArgs = kTTValNONE;\n\n \/\/ Store arguments\n\tif (argc > 1 && argv)\n jamoma_ttvalue_from_Atom(EXTRA->arrayArgs, _sym_list, argc--, argv++);\n\n\tdata_new_address(self, relativeAddress, argc--, argv++);\n}\n\nvoid WrappedDataClass_free(TTPtr self)\n{\n\tWrappedModularInstancePtr\tx = (WrappedModularInstancePtr)self;\n\tfree(EXTRA);\n}\n\t\nvoid data_new_address(TTPtr self, SymbolPtr relativeAddress, AtomCount argc, AtomPtr argv)\n{\n\tWrappedModularInstancePtr\tx = (WrappedModularInstancePtr)self;\n\t\n\tx->useInternals = false;\n\t\n\t\/\/ create the data\n#ifdef JMOD_MESSAGE\n\tjamoma_data_create((ObjectPtr)x, &x->wrappedObject, kTTSym_message);\n#endif\n\t\n#if JMOD_RETURN\n\tjamoma_data_create((ObjectPtr)x, &x->wrappedObject, kTTSym_return);\n#endif\n\t\n#ifndef JMOD_MESSAGE\n#ifndef JMOD_RETURN\n\tjamoma_data_create((ObjectPtr)x, &x->wrappedObject, kTTSym_parameter);\n#endif\n#endif\n \n if (argc && argv)\n attr_args_process(x, argc, argv);\n\t\n\t\/\/ The following must be deferred because we have to interrogate our box,\n\t\/\/ and our box is not yet valid until we have finished instantiating the object.\n\t\/\/ Trying to use a loadbang method instead is also not fully successful (as of Max 5.0.6)\n\tdefer_low((ObjectPtr)x, (method)data_subscribe, relativeAddress, argc, argv);\n}\n\nvoid data_subscribe(TTPtr self, SymbolPtr relativeAddress, AtomCount argc, AtomPtr argv)\n{\n\tWrappedModularInstancePtr\tx = (WrappedModularInstancePtr)self;\n\n\t\/\/ for relative address\n\tif (TTAddress(relativeAddress->s_name).getType() == kAddressRelative) {\n \n\t\tjamoma_subscriber_create((ObjectPtr)x, x->wrappedObject, TTAddress(jamoma_parse_dieze((ObjectPtr)x, relativeAddress)->s_name), &x->subscriberObject);\n\t\t\n\t}\n\telse\n\t\tobject_error((ObjectPtr)x, \"can't register because %s is not a relative address\", relativeAddress->s_name);\n}\n\nvoid data_address(TTPtr self, SymbolPtr address)\n{\n\tWrappedModularInstancePtr\tx = (WrappedModularInstancePtr)self;\n AtomCount\t\t\t\t\targc = 0;\n\tAtomPtr\t\t\t\t\t\targv = NULL;\n\t\n\t\/\/ unregister wrapped object (or internals)\n\twrappedModularClass_unregister(x);\n \n \/\/ use stored arguments\n jamoma_ttvalue_to_Atom(EXTRA->arrayArgs, &argc, &argv);\n\t\n\t\/\/ rebuild wrapped object (or internals)\n\tdefer_low(self,(method)data_new_address, address, argc, argv);\n}\n\n\/\/ Method for Assistance Messages\nvoid data_assist(TTPtr self, TTPtr b, long msg, AtomCount arg, char *dst)\n{\n\tif (msg==1) \t\t\t\t\t\t\/\/ Inlet\n\t\tstrcpy(dst, \"input\");\n\telse {\t\t\t\t\t\t\t\/\/ Outlets\n\t\tswitch(arg) {\n\t\t\tcase data_out:\n\t\t\t\tstrcpy(dst, \"direct: values\");\n\t\t\t\tbreak;\n\t\t\tcase dump_out:\n\t\t\t\tstrcpy(dst, \"dumpout\");\n\t\t\t\tbreak;\n\t\t}\n \t}\n}\n\n#ifndef JMOD_MESSAGE\nvoid data_bang(TTPtr self)\n{\n\tdata_list(self, _sym_bang, 0, NULL);\n}\n\nvoid data_int(TTPtr self, long value)\n{\n\tt_atom a;\n\t\n\tatom_setlong(&a, value);\n\tdata_list(self, _sym_int, 1, &a);\n}\n\nvoid data_float(TTPtr self, double value)\n{\n\tt_atom a;\n\t\n\tatom_setfloat(&a, value);\n\tdata_list(self, _sym_float, 1, &a);\n}\n\nvoid data_list(TTPtr self, t_symbol *msg, long argc, t_atom *argv)\n{\n\tWrappedModularInstancePtr\tx = (WrappedModularInstancePtr)self;\n\n\tjamoma_data_command((TTDataPtr)selectedObject, msg, argc, argv);\n}\n\nvoid WrappedDataClass_anything(TTPtr self, SymbolPtr msg, AtomCount argc, AtomPtr argv)\n{\n\tWrappedModularInstancePtr\tx = (WrappedModularInstancePtr)self;\n\t\n\tjamoma_data_command((TTDataPtr)selectedObject, msg, argc, argv);\n}\n#endif\n\n#ifndef JMOD_RETURN\nvoid data_return_value(TTPtr self, SymbolPtr msg, AtomCount argc, AtomPtr argv)\n{\n\tWrappedModularInstancePtr\tx = (WrappedModularInstancePtr)self;\n\t\n\t\/\/ avoid blank before data\n\tif (msg == _sym_nothing)\n\t\toutlet_atoms(x->outlets[data_out], argc, argv);\n\telse\n\t\toutlet_anything(x->outlets[data_out], msg, argc, argv);\n}\n#endif\n\n#ifndef JMOD_MESSAGE\nvoid data_inc(TTPtr self, SymbolPtr msg, AtomCount argc, AtomPtr argv)\n{\n\tWrappedModularInstancePtr\tx = (WrappedModularInstancePtr)self;\n\tTTValue v;\n\n\tjamoma_ttvalue_from_Atom(v, _sym_nothing, argc, argv);\n\tselectedObject->sendMessage(TTSymbol(\"Inc\"), v, kTTValNONE);\n}\n\nvoid data_dec(TTPtr self, SymbolPtr msg, AtomCount argc, AtomPtr argv)\n{\n\tWrappedModularInstancePtr\tx = (WrappedModularInstancePtr)self;\n\tTTValue v;\n\t\n\tjamoma_ttvalue_from_Atom(v, _sym_nothing, argc, argv);\n\tselectedObject->sendMessage(TTSymbol(\"Dec\"), v, kTTValNONE);\n}\n#endif<|endoftext|>"} {"text":"\/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- *\/\n\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2000, 2010 Oracle and\/or its affiliates.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * \n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n#ifndef _SV_GLYPHCACHE_HXX\n#define _SV_GLYPHCACHE_HXX\n\n#include \n\nclass GlyphCache;\nclass GlyphMetric;\nclass GlyphData;\nclass ServerFont;\nclass GlyphCachePeer;\nclass ServerFontLayoutEngine;\nclass ServerFontLayout;\nclass ExtraKernInfo;\nstruct ImplKernPairData;\nclass ImplFontOptions;\n\n#include \n#include \n#include \n#include \n\nnamespace basegfx { class B2DPolyPolygon; }\n\nclass RawBitmap;\n\n#include \n#include \n\nclass ServerFontLayout;\n#include \n\nnamespace vcl\n{\n struct FontCapabilities;\n}\n\n\/\/ =======================================================================\n\nclass VCL_PLUGIN_PUBLIC GlyphCache\n{\npublic:\n explicit GlyphCache( GlyphCachePeer& );\n \/*virtual*\/ ~GlyphCache();\n\n static GlyphCache& GetInstance();\n\n void AddFontFile( const rtl::OString& rNormalizedName,\n int nFaceNum, sal_IntPtr nFontId, const ImplDevFontAttributes&,\n const ExtraKernInfo* = NULL );\n void AnnounceFonts( ImplDevFontList* ) const;\n\n ServerFont* CacheFont( const ImplFontSelectData& );\n void UncacheFont( ServerFont& );\n void InvalidateAllGlyphs();\n\nprotected:\n GlyphCachePeer& mrPeer;\n\nprivate:\n friend class ServerFont;\n \/\/ used by ServerFont class only\n void AddedGlyph( ServerFont&, GlyphData& );\n void RemovingGlyph( ServerFont&, GlyphData&, int nGlyphIndex );\n void UsingGlyph( ServerFont&, GlyphData& );\n void GrowNotify();\n\nprivate:\n void GarbageCollect();\n\n \/\/ the GlyphCache's FontList matches a font request to a serverfont instance\n \/\/ the FontList key's mpFontData member is reinterpreted as integer font id\n struct IFSD_Equal{ bool operator()( const ImplFontSelectData&, const ImplFontSelectData& ) const; };\n struct IFSD_Hash{ size_t operator()( const ImplFontSelectData& ) const; };\n typedef ::boost::unordered_map FontList;\n FontList maFontList;\n sal_uLong mnMaxSize; \/\/ max overall cache size in bytes\n mutable sal_uLong mnBytesUsed;\n mutable long mnLruIndex;\n mutable int mnGlyphCount;\n ServerFont* mpCurrentGCFont;\n\n class FreetypeManager* mpFtManager;\n};\n\n\/\/ =======================================================================\n\nclass GlyphMetric\n{\npublic:\n Point GetOffset() const { return maOffset; }\n Point GetDelta() const { return maDelta; }\n Size GetSize() const { return maSize; }\n long GetCharWidth() const { return mnAdvanceWidth; }\n\nprotected:\n friend class GlyphData;\n void SetOffset( int nX, int nY ) { maOffset = Point( nX, nY); }\n void SetDelta( int nX, int nY ) { maDelta = Point( nX, nY); }\n void SetSize( const Size& s ) { maSize = s; }\n void SetCharWidth( long nW ) { mnAdvanceWidth = nW; }\n\nprivate:\n long mnAdvanceWidth;\n Point maDelta;\n Point maOffset;\n Size maSize;\n};\n\n\/\/ -----------------------------------------------------------------------\n\n\/\/ the glyph specific data needed by a GlyphCachePeer is usually trivial,\n\/\/ not attaching it to the corresponding GlyphData would be overkill\nstruct ExtGlyphData\n{\n int meInfo;\n void* mpData;\n\n ExtGlyphData() : meInfo(0), mpData(NULL) {}\n};\n\n\/\/ -----------------------------------------------------------------------\n\nclass GlyphData\n{\npublic:\n const GlyphMetric& GetMetric() const { return maMetric; }\n Size GetSize() const { return maMetric.GetSize(); }\n\n void SetSize( const Size& s) { maMetric.SetSize( s ); }\n void SetOffset( int nX, int nY ) { maMetric.SetOffset( nX, nY ); }\n void SetDelta( int nX, int nY ) { maMetric.SetDelta( nX, nY ); }\n void SetCharWidth( long nW ) { maMetric.SetCharWidth( nW ); }\n\n void SetLruValue( int n ) const { mnLruValue = n; }\n long GetLruValue() const { return mnLruValue;}\n\n ExtGlyphData& ExtDataRef() { return maExtData; }\n const ExtGlyphData& ExtDataRef() const { return maExtData; }\n\nprivate:\n GlyphMetric maMetric;\n ExtGlyphData maExtData;\n\n \/\/ used by GlyphCache for cache LRU algorithm\n mutable long mnLruValue;\n};\n\n\/\/ =======================================================================\n\nclass VCL_PLUGIN_PUBLIC ServerFont\n{\npublic:\n virtual const ::rtl::OString* GetFontFileName() const { return NULL; }\n virtual int GetFontFaceNumber() const { return 0; }\n virtual bool TestFont() const { return true; }\n virtual void* GetFtFace() const { return 0; }\n virtual int GetLoadFlags() const { return 0; }\n virtual void SetFontOptions( boost::shared_ptr ) {}\n virtual boost::shared_ptr GetFontOptions() const\n { return boost::shared_ptr(); }\n virtual bool NeedsArtificialBold() const { return false; }\n virtual bool NeedsArtificialItalic() const { return false; }\n\n const ImplFontSelectData& GetFontSelData() const { return maFontSelData; }\n\n virtual void FetchFontMetric( ImplFontMetricData&, long& rFactor ) const = 0;\n virtual sal_uLong GetKernPairs( ImplKernPairData** ) const { return 0; }\n virtual int GetGlyphKernValue( int, int ) const { return 0; }\n virtual const ImplFontCharMap* GetImplFontCharMap() const = 0;\n virtual bool GetFontCapabilities(vcl::FontCapabilities &) const { return false; }\n Point TransformPoint( const Point& ) const;\n\n GlyphData& GetGlyphData( int nGlyphIndex );\n const GlyphMetric& GetGlyphMetric( int nGlyphIndex )\n { return GetGlyphData( nGlyphIndex ).GetMetric(); }\n\n virtual int GetGlyphIndex( sal_UCS4 ) const = 0;\n virtual bool GetGlyphOutline( int nGlyphIndex, ::basegfx::B2DPolyPolygon& ) const = 0;\n virtual bool GetAntialiasAdvice( void ) const = 0;\n bool IsGlyphInvisible( int nGlyphIndex );\n virtual bool GetGlyphBitmap1( int nGlyphIndex, RawBitmap& ) const = 0;\n virtual bool GetGlyphBitmap8( int nGlyphIndex, RawBitmap& ) const = 0;\n\n void SetExtended( int nInfo, void* ppVoid );\n int GetExtInfo() { return mnExtInfo; }\n void* GetExtPointer() { return mpExtData; }\n\nprotected:\n friend class GlyphCache;\n friend class ServerFontLayout;\n explicit ServerFont( const ImplFontSelectData& );\n virtual ~ServerFont();\n\n void AddRef() const { ++mnRefCount; }\n long GetRefCount() const { return mnRefCount; }\n long Release() const;\n sal_uLong GetByteCount() const { return mnBytesUsed; }\n\n virtual void InitGlyphData( int nGlyphIndex, GlyphData& ) const = 0;\n virtual void GarbageCollect( long );\n void ReleaseFromGarbageCollect();\n\n virtual ServerFontLayoutEngine* GetLayoutEngine() { return NULL; }\n\nprivate:\n typedef ::boost::unordered_map GlyphList;\n mutable GlyphList maGlyphList;\n\n const ImplFontSelectData maFontSelData;\n\n \/\/ info for GlyphcachePeer\n int mnExtInfo;\n void* mpExtData;\n\n \/\/ used by GlyphCache for cache LRU algorithm\n mutable long mnRefCount;\n mutable sal_uLong mnBytesUsed;\n\n ServerFont* mpPrevGCFont;\n ServerFont* mpNextGCFont;\n\nprotected:\n \/\/ 16.16 fixed point values used for a rotated font\n long mnCos;\n long mnSin;\nprivate:\n int mnZWJ;\n int mnZWNJ;\n bool mbCollectedZW;\n};\n\n\/\/ =======================================================================\n\n\/\/ a class for cache entries for physical font instances that are based on serverfonts\nclass VCL_PLUGIN_PUBLIC ImplServerFontEntry : public ImplFontEntry\n{\nprivate:\n ServerFont* mpServerFont;\n boost::shared_ptr mpFontOptions;\n bool mbGotFontOptions;\n\npublic:\n ImplServerFontEntry( ImplFontSelectData& );\n virtual ~ImplServerFontEntry();\n void SetServerFont( ServerFont* p) { mpServerFont = p; }\n void HandleFontOptions();\n};\n\n\/\/ =======================================================================\n\nclass VCL_PLUGIN_PUBLIC ServerFontLayout : public GenericSalLayout\n{\nprivate:\n ServerFont& mrServerFont;\n\n \/\/ enforce proper copy semantic\n SAL_DLLPRIVATE ServerFontLayout( const ServerFontLayout& );\n SAL_DLLPRIVATE ServerFontLayout& operator=( const ServerFontLayout& );\n\npublic:\n ServerFontLayout( ServerFont& );\n virtual bool LayoutText( ImplLayoutArgs& );\n virtual void AdjustLayout( ImplLayoutArgs& );\n virtual void DrawText( SalGraphics& ) const;\n ServerFont& GetServerFont() const { return mrServerFont; }\n};\n\n\/\/ =======================================================================\n\nclass ServerFontLayoutEngine\n{\npublic:\n virtual ~ServerFontLayoutEngine() {}\n virtual bool operator()( ServerFontLayout&, ImplLayoutArgs& );\n};\n\n\/\/ =======================================================================\n\nclass GlyphCachePeer\n{\nprotected:\n GlyphCachePeer() : mnBytesUsed(0) {}\n virtual ~GlyphCachePeer() {}\n\npublic:\n sal_Int32 GetByteCount() const { return mnBytesUsed; }\n virtual void RemovingFont( ServerFont& ) {}\n virtual void RemovingGlyph( ServerFont&, GlyphData&, int ) {}\n\nprotected:\n sal_Int32 mnBytesUsed;\n};\n\n\/\/ =======================================================================\n\nclass VCL_PLUGIN_PUBLIC RawBitmap\n{\npublic:\n RawBitmap();\n ~RawBitmap();\n bool Rotate( int nAngle );\n\npublic:\n unsigned char* mpBits;\n sal_uLong mnAllocated;\n\n sal_uLong mnWidth;\n sal_uLong mnHeight;\n\n sal_uLong mnScanlineSize;\n sal_uLong mnBitCount;\n\n int mnXOffset;\n int mnYOffset;\n};\n\n\/\/ =======================================================================\n\ninline void ServerFont::SetExtended( int nInfo, void* pVoid )\n{\n mnExtInfo = nInfo;\n mpExtData = pVoid;\n}\n\n\/\/ =======================================================================\n\n\/\/ ExtraKernInfo allows an on-demand query of extra kerning info #i29881#\n\/\/ The kerning values have to be scaled to match the font size before use\nclass VCL_PLUGIN_PUBLIC ExtraKernInfo\n{\npublic:\n ExtraKernInfo( sal_IntPtr nFontId );\n virtual ~ExtraKernInfo() {}\n\n bool HasKernPairs() const;\n int GetUnscaledKernPairs( ImplKernPairData** ) const;\n int GetUnscaledKernValue( sal_Unicode cLeft, sal_Unicode cRight ) const;\n\nprotected:\n mutable bool mbInitialized;\n virtual void Initialize() const = 0;\n\nprotected:\n sal_IntPtr mnFontId;\n\n \/\/ container to map a unicode pair to an unscaled kerning value\n struct PairEqual{ int operator()(const ImplKernPairData& rA, const ImplKernPairData& rB) const\n { return (rA.mnChar1 == rB.mnChar1) && (rA.mnChar2 == rB.mnChar2); } };\n struct PairHash{ int operator()(const ImplKernPairData& rA) const\n { return (rA.mnChar1) * 256 ^ rA.mnChar2; } };\n typedef boost::unordered_set< ImplKernPairData, PairHash, PairEqual > UnicodeKernPairs;\n mutable UnicodeKernPairs maUnicodeKernPairs;\n};\n\n\/\/ =======================================================================\n\n#endif \/\/ _SV_GLYPHCACHE_HXX\n\n\/* vim:set shiftwidth=4 softtabstop=4 expandtab: *\/\nmake these pure virtual to prove all implemented in sole sub-class\/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- *\/\n\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2000, 2010 Oracle and\/or its affiliates.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * \n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n#ifndef _SV_GLYPHCACHE_HXX\n#define _SV_GLYPHCACHE_HXX\n\n#include \n\nclass GlyphCache;\nclass GlyphMetric;\nclass GlyphData;\nclass ServerFont;\nclass GlyphCachePeer;\nclass ServerFontLayoutEngine;\nclass ServerFontLayout;\nclass ExtraKernInfo;\nstruct ImplKernPairData;\nclass ImplFontOptions;\n\n#include \n#include \n#include \n#include \n\nnamespace basegfx { class B2DPolyPolygon; }\n\nclass RawBitmap;\n\n#include \n#include \n\nclass ServerFontLayout;\n#include \n\nnamespace vcl\n{\n struct FontCapabilities;\n}\n\n\/\/ =======================================================================\n\nclass VCL_PLUGIN_PUBLIC GlyphCache\n{\npublic:\n explicit GlyphCache( GlyphCachePeer& );\n \/*virtual*\/ ~GlyphCache();\n\n static GlyphCache& GetInstance();\n\n void AddFontFile( const rtl::OString& rNormalizedName,\n int nFaceNum, sal_IntPtr nFontId, const ImplDevFontAttributes&,\n const ExtraKernInfo* = NULL );\n void AnnounceFonts( ImplDevFontList* ) const;\n\n ServerFont* CacheFont( const ImplFontSelectData& );\n void UncacheFont( ServerFont& );\n void InvalidateAllGlyphs();\n\nprotected:\n GlyphCachePeer& mrPeer;\n\nprivate:\n friend class ServerFont;\n \/\/ used by ServerFont class only\n void AddedGlyph( ServerFont&, GlyphData& );\n void RemovingGlyph( ServerFont&, GlyphData&, int nGlyphIndex );\n void UsingGlyph( ServerFont&, GlyphData& );\n void GrowNotify();\n\nprivate:\n void GarbageCollect();\n\n \/\/ the GlyphCache's FontList matches a font request to a serverfont instance\n \/\/ the FontList key's mpFontData member is reinterpreted as integer font id\n struct IFSD_Equal{ bool operator()( const ImplFontSelectData&, const ImplFontSelectData& ) const; };\n struct IFSD_Hash{ size_t operator()( const ImplFontSelectData& ) const; };\n typedef ::boost::unordered_map FontList;\n FontList maFontList;\n sal_uLong mnMaxSize; \/\/ max overall cache size in bytes\n mutable sal_uLong mnBytesUsed;\n mutable long mnLruIndex;\n mutable int mnGlyphCount;\n ServerFont* mpCurrentGCFont;\n\n class FreetypeManager* mpFtManager;\n};\n\n\/\/ =======================================================================\n\nclass GlyphMetric\n{\npublic:\n Point GetOffset() const { return maOffset; }\n Point GetDelta() const { return maDelta; }\n Size GetSize() const { return maSize; }\n long GetCharWidth() const { return mnAdvanceWidth; }\n\nprotected:\n friend class GlyphData;\n void SetOffset( int nX, int nY ) { maOffset = Point( nX, nY); }\n void SetDelta( int nX, int nY ) { maDelta = Point( nX, nY); }\n void SetSize( const Size& s ) { maSize = s; }\n void SetCharWidth( long nW ) { mnAdvanceWidth = nW; }\n\nprivate:\n long mnAdvanceWidth;\n Point maDelta;\n Point maOffset;\n Size maSize;\n};\n\n\/\/ -----------------------------------------------------------------------\n\n\/\/ the glyph specific data needed by a GlyphCachePeer is usually trivial,\n\/\/ not attaching it to the corresponding GlyphData would be overkill\nstruct ExtGlyphData\n{\n int meInfo;\n void* mpData;\n\n ExtGlyphData() : meInfo(0), mpData(NULL) {}\n};\n\n\/\/ -----------------------------------------------------------------------\n\nclass GlyphData\n{\npublic:\n const GlyphMetric& GetMetric() const { return maMetric; }\n Size GetSize() const { return maMetric.GetSize(); }\n\n void SetSize( const Size& s) { maMetric.SetSize( s ); }\n void SetOffset( int nX, int nY ) { maMetric.SetOffset( nX, nY ); }\n void SetDelta( int nX, int nY ) { maMetric.SetDelta( nX, nY ); }\n void SetCharWidth( long nW ) { maMetric.SetCharWidth( nW ); }\n\n void SetLruValue( int n ) const { mnLruValue = n; }\n long GetLruValue() const { return mnLruValue;}\n\n ExtGlyphData& ExtDataRef() { return maExtData; }\n const ExtGlyphData& ExtDataRef() const { return maExtData; }\n\nprivate:\n GlyphMetric maMetric;\n ExtGlyphData maExtData;\n\n \/\/ used by GlyphCache for cache LRU algorithm\n mutable long mnLruValue;\n};\n\n\/\/ =======================================================================\n\nclass VCL_PLUGIN_PUBLIC ServerFont\n{\npublic:\n virtual const ::rtl::OString* GetFontFileName() const = 0;\n virtual int GetFontFaceNumber() const = 0;\n virtual bool TestFont() const = 0;\n virtual void* GetFtFace() const = 0;\n virtual int GetLoadFlags() const = 0;\n virtual void SetFontOptions( boost::shared_ptr ) = 0;\n virtual boost::shared_ptr GetFontOptions() const = 0;\n virtual bool NeedsArtificialBold() const = 0;\n virtual bool NeedsArtificialItalic() const = 0;\n\n const ImplFontSelectData& GetFontSelData() const { return maFontSelData; }\n\n virtual void FetchFontMetric( ImplFontMetricData&, long& rFactor ) const = 0;\n virtual sal_uLong GetKernPairs( ImplKernPairData** ) const = 0;\n virtual int GetGlyphKernValue( int, int ) const = 0;\n virtual const ImplFontCharMap* GetImplFontCharMap() const = 0;\n virtual bool GetFontCapabilities(vcl::FontCapabilities &) const = 0;\n Point TransformPoint( const Point& ) const;\n\n GlyphData& GetGlyphData( int nGlyphIndex );\n const GlyphMetric& GetGlyphMetric( int nGlyphIndex )\n { return GetGlyphData( nGlyphIndex ).GetMetric(); }\n\n virtual int GetGlyphIndex( sal_UCS4 ) const = 0;\n virtual bool GetGlyphOutline( int nGlyphIndex, ::basegfx::B2DPolyPolygon& ) const = 0;\n virtual bool GetAntialiasAdvice( void ) const = 0;\n bool IsGlyphInvisible( int nGlyphIndex );\n virtual bool GetGlyphBitmap1( int nGlyphIndex, RawBitmap& ) const = 0;\n virtual bool GetGlyphBitmap8( int nGlyphIndex, RawBitmap& ) const = 0;\n\n void SetExtended( int nInfo, void* ppVoid );\n int GetExtInfo() { return mnExtInfo; }\n void* GetExtPointer() { return mpExtData; }\n\nprotected:\n friend class GlyphCache;\n friend class ServerFontLayout;\n explicit ServerFont( const ImplFontSelectData& );\n virtual ~ServerFont();\n\n void AddRef() const { ++mnRefCount; }\n long GetRefCount() const { return mnRefCount; }\n long Release() const;\n sal_uLong GetByteCount() const { return mnBytesUsed; }\n\n virtual void InitGlyphData( int nGlyphIndex, GlyphData& ) const = 0;\n virtual void GarbageCollect( long );\n void ReleaseFromGarbageCollect();\n\n virtual ServerFontLayoutEngine* GetLayoutEngine() = 0;\n\nprivate:\n typedef ::boost::unordered_map GlyphList;\n mutable GlyphList maGlyphList;\n\n const ImplFontSelectData maFontSelData;\n\n \/\/ info for GlyphcachePeer\n int mnExtInfo;\n void* mpExtData;\n\n \/\/ used by GlyphCache for cache LRU algorithm\n mutable long mnRefCount;\n mutable sal_uLong mnBytesUsed;\n\n ServerFont* mpPrevGCFont;\n ServerFont* mpNextGCFont;\n\nprotected:\n \/\/ 16.16 fixed point values used for a rotated font\n long mnCos;\n long mnSin;\nprivate:\n int mnZWJ;\n int mnZWNJ;\n bool mbCollectedZW;\n};\n\n\/\/ =======================================================================\n\n\/\/ a class for cache entries for physical font instances that are based on serverfonts\nclass VCL_PLUGIN_PUBLIC ImplServerFontEntry : public ImplFontEntry\n{\nprivate:\n ServerFont* mpServerFont;\n boost::shared_ptr mpFontOptions;\n bool mbGotFontOptions;\n\npublic:\n ImplServerFontEntry( ImplFontSelectData& );\n virtual ~ImplServerFontEntry();\n void SetServerFont( ServerFont* p) { mpServerFont = p; }\n void HandleFontOptions();\n};\n\n\/\/ =======================================================================\n\nclass VCL_PLUGIN_PUBLIC ServerFontLayout : public GenericSalLayout\n{\nprivate:\n ServerFont& mrServerFont;\n\n \/\/ enforce proper copy semantic\n SAL_DLLPRIVATE ServerFontLayout( const ServerFontLayout& );\n SAL_DLLPRIVATE ServerFontLayout& operator=( const ServerFontLayout& );\n\npublic:\n ServerFontLayout( ServerFont& );\n virtual bool LayoutText( ImplLayoutArgs& );\n virtual void AdjustLayout( ImplLayoutArgs& );\n virtual void DrawText( SalGraphics& ) const;\n ServerFont& GetServerFont() const { return mrServerFont; }\n};\n\n\/\/ =======================================================================\n\nclass ServerFontLayoutEngine\n{\npublic:\n virtual ~ServerFontLayoutEngine() {}\n virtual bool operator()( ServerFontLayout&, ImplLayoutArgs& );\n};\n\n\/\/ =======================================================================\n\nclass GlyphCachePeer\n{\nprotected:\n GlyphCachePeer() : mnBytesUsed(0) {}\n virtual ~GlyphCachePeer() {}\n\npublic:\n sal_Int32 GetByteCount() const { return mnBytesUsed; }\n virtual void RemovingFont( ServerFont& ) {}\n virtual void RemovingGlyph( ServerFont&, GlyphData&, int ) {}\n\nprotected:\n sal_Int32 mnBytesUsed;\n};\n\n\/\/ =======================================================================\n\nclass VCL_PLUGIN_PUBLIC RawBitmap\n{\npublic:\n RawBitmap();\n ~RawBitmap();\n bool Rotate( int nAngle );\n\npublic:\n unsigned char* mpBits;\n sal_uLong mnAllocated;\n\n sal_uLong mnWidth;\n sal_uLong mnHeight;\n\n sal_uLong mnScanlineSize;\n sal_uLong mnBitCount;\n\n int mnXOffset;\n int mnYOffset;\n};\n\n\/\/ =======================================================================\n\ninline void ServerFont::SetExtended( int nInfo, void* pVoid )\n{\n mnExtInfo = nInfo;\n mpExtData = pVoid;\n}\n\n\/\/ =======================================================================\n\n\/\/ ExtraKernInfo allows an on-demand query of extra kerning info #i29881#\n\/\/ The kerning values have to be scaled to match the font size before use\nclass VCL_PLUGIN_PUBLIC ExtraKernInfo\n{\npublic:\n ExtraKernInfo( sal_IntPtr nFontId );\n virtual ~ExtraKernInfo() {}\n\n bool HasKernPairs() const;\n int GetUnscaledKernPairs( ImplKernPairData** ) const;\n int GetUnscaledKernValue( sal_Unicode cLeft, sal_Unicode cRight ) const;\n\nprotected:\n mutable bool mbInitialized;\n virtual void Initialize() const = 0;\n\nprotected:\n sal_IntPtr mnFontId;\n\n \/\/ container to map a unicode pair to an unscaled kerning value\n struct PairEqual{ int operator()(const ImplKernPairData& rA, const ImplKernPairData& rB) const\n { return (rA.mnChar1 == rB.mnChar1) && (rA.mnChar2 == rB.mnChar2); } };\n struct PairHash{ int operator()(const ImplKernPairData& rA) const\n { return (rA.mnChar1) * 256 ^ rA.mnChar2; } };\n typedef boost::unordered_set< ImplKernPairData, PairHash, PairEqual > UnicodeKernPairs;\n mutable UnicodeKernPairs maUnicodeKernPairs;\n};\n\n\/\/ =======================================================================\n\n#endif \/\/ _SV_GLYPHCACHE_HXX\n\n\/* vim:set shiftwidth=4 softtabstop=4 expandtab: *\/\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * $RCSfile: multi.hxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: kz $ $Date: 2005-01-18 13:28:47 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef INCLUDED_testtools_source_bridgetest_multi_hxx\n#define INCLUDED_testtools_source_bridgetest_multi_hxx\n\n#include \"sal\/config.h\"\n\n#include \"com\/sun\/star\/uno\/Reference.hxx\"\n#include \"com\/sun\/star\/uno\/RuntimeException.hpp\"\n#include \"cppuhelper\/implbase1.hxx\"\n#include \"rtl\/ustring.hxx\"\n#include \"sal\/types.h\"\n#include \"test\/testtools\/bridgetest\/XMulti.hpp\"\n\nnamespace testtools { namespace bridgetest {\n\nclass Multi: public cppu::WeakImplHelper1< test::testtools::bridgetest::XMulti >\n{\npublic:\n Multi(): m_attribute1(0.0), m_attribute3(0.0) {}\n\n virtual double SAL_CALL getatt1()\n throw (com::sun::star::uno::RuntimeException)\n { return m_attribute1; }\n\n virtual void SAL_CALL setatt1(double value)\n throw (com::sun::star::uno::RuntimeException)\n { m_attribute1 = value; }\n\n virtual sal_Int32 SAL_CALL fn11(sal_Int32 arg)\n throw (com::sun::star::uno::RuntimeException)\n { return 11 * arg; }\n\n virtual rtl::OUString SAL_CALL fn12(rtl::OUString const & arg)\n throw (com::sun::star::uno::RuntimeException)\n { return rtl::OUString::createFromAscii(\"12\") + arg; }\n\n virtual sal_Int32 SAL_CALL fn21(sal_Int32 arg)\n throw (com::sun::star::uno::RuntimeException)\n { return 21 * arg; }\n\n virtual rtl::OUString SAL_CALL fn22(rtl::OUString const & arg)\n throw (com::sun::star::uno::RuntimeException)\n { return rtl::OUString::createFromAscii(\"22\") + arg; }\n\n virtual double SAL_CALL getatt3()\n throw (com::sun::star::uno::RuntimeException)\n { return m_attribute3; }\n\n virtual void SAL_CALL setatt3(double value)\n throw (com::sun::star::uno::RuntimeException)\n { m_attribute3 = value; }\n\n virtual sal_Int32 SAL_CALL fn31(sal_Int32 arg)\n throw (com::sun::star::uno::RuntimeException)\n { return 31 * arg; }\n\n virtual rtl::OUString SAL_CALL fn32(rtl::OUString const & arg)\n throw (com::sun::star::uno::RuntimeException)\n { return rtl::OUString::createFromAscii(\"32\") + arg; }\n\n virtual sal_Int32 SAL_CALL fn33()\n throw (com::sun::star::uno::RuntimeException)\n { return 33; }\n\n virtual sal_Int32 SAL_CALL fn41(sal_Int32 arg)\n throw (com::sun::star::uno::RuntimeException)\n { return 41 * arg; }\n\n virtual sal_Int32 SAL_CALL fn61(sal_Int32 arg)\n throw (com::sun::star::uno::RuntimeException)\n { return 61 * arg; }\n\n virtual rtl::OUString SAL_CALL fn62(rtl::OUString const & arg)\n throw (com::sun::star::uno::RuntimeException)\n { return rtl::OUString::createFromAscii(\"62\") + arg; }\n\n virtual sal_Int32 SAL_CALL fn71(sal_Int32 arg)\n throw (com::sun::star::uno::RuntimeException)\n { return 71 * arg; }\n\n virtual rtl::OUString SAL_CALL fn72(rtl::OUString const & arg)\n throw (com::sun::star::uno::RuntimeException)\n { return rtl::OUString::createFromAscii(\"72\") + arg; }\n\n virtual sal_Int32 SAL_CALL fn73()\n throw (com::sun::star::uno::RuntimeException)\n { return 73; }\n\nprivate:\n double m_attribute1;\n double m_attribute3;\n};\n\nrtl::OUString testMulti(\n com::sun::star::uno::Reference< test::testtools::bridgetest::XMulti >\n const & multi);\n\n} }\n\n#endif\nINTEGRATION: CWS ooo19126 (1.3.18); FILE MERGED 2005\/09\/05 17:00:53 rt 1.3.18.1: #i54170# Change license header: remove SISSL\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: multi.hxx,v $\n *\n * $Revision: 1.4 $\n *\n * last change: $Author: rt $ $Date: 2005-09-09 12:22:54 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef INCLUDED_testtools_source_bridgetest_multi_hxx\n#define INCLUDED_testtools_source_bridgetest_multi_hxx\n\n#include \"sal\/config.h\"\n\n#include \"com\/sun\/star\/uno\/Reference.hxx\"\n#include \"com\/sun\/star\/uno\/RuntimeException.hpp\"\n#include \"cppuhelper\/implbase1.hxx\"\n#include \"rtl\/ustring.hxx\"\n#include \"sal\/types.h\"\n#include \"test\/testtools\/bridgetest\/XMulti.hpp\"\n\nnamespace testtools { namespace bridgetest {\n\nclass Multi: public cppu::WeakImplHelper1< test::testtools::bridgetest::XMulti >\n{\npublic:\n Multi(): m_attribute1(0.0), m_attribute3(0.0) {}\n\n virtual double SAL_CALL getatt1()\n throw (com::sun::star::uno::RuntimeException)\n { return m_attribute1; }\n\n virtual void SAL_CALL setatt1(double value)\n throw (com::sun::star::uno::RuntimeException)\n { m_attribute1 = value; }\n\n virtual sal_Int32 SAL_CALL fn11(sal_Int32 arg)\n throw (com::sun::star::uno::RuntimeException)\n { return 11 * arg; }\n\n virtual rtl::OUString SAL_CALL fn12(rtl::OUString const & arg)\n throw (com::sun::star::uno::RuntimeException)\n { return rtl::OUString::createFromAscii(\"12\") + arg; }\n\n virtual sal_Int32 SAL_CALL fn21(sal_Int32 arg)\n throw (com::sun::star::uno::RuntimeException)\n { return 21 * arg; }\n\n virtual rtl::OUString SAL_CALL fn22(rtl::OUString const & arg)\n throw (com::sun::star::uno::RuntimeException)\n { return rtl::OUString::createFromAscii(\"22\") + arg; }\n\n virtual double SAL_CALL getatt3()\n throw (com::sun::star::uno::RuntimeException)\n { return m_attribute3; }\n\n virtual void SAL_CALL setatt3(double value)\n throw (com::sun::star::uno::RuntimeException)\n { m_attribute3 = value; }\n\n virtual sal_Int32 SAL_CALL fn31(sal_Int32 arg)\n throw (com::sun::star::uno::RuntimeException)\n { return 31 * arg; }\n\n virtual rtl::OUString SAL_CALL fn32(rtl::OUString const & arg)\n throw (com::sun::star::uno::RuntimeException)\n { return rtl::OUString::createFromAscii(\"32\") + arg; }\n\n virtual sal_Int32 SAL_CALL fn33()\n throw (com::sun::star::uno::RuntimeException)\n { return 33; }\n\n virtual sal_Int32 SAL_CALL fn41(sal_Int32 arg)\n throw (com::sun::star::uno::RuntimeException)\n { return 41 * arg; }\n\n virtual sal_Int32 SAL_CALL fn61(sal_Int32 arg)\n throw (com::sun::star::uno::RuntimeException)\n { return 61 * arg; }\n\n virtual rtl::OUString SAL_CALL fn62(rtl::OUString const & arg)\n throw (com::sun::star::uno::RuntimeException)\n { return rtl::OUString::createFromAscii(\"62\") + arg; }\n\n virtual sal_Int32 SAL_CALL fn71(sal_Int32 arg)\n throw (com::sun::star::uno::RuntimeException)\n { return 71 * arg; }\n\n virtual rtl::OUString SAL_CALL fn72(rtl::OUString const & arg)\n throw (com::sun::star::uno::RuntimeException)\n { return rtl::OUString::createFromAscii(\"72\") + arg; }\n\n virtual sal_Int32 SAL_CALL fn73()\n throw (com::sun::star::uno::RuntimeException)\n { return 73; }\n\nprivate:\n double m_attribute1;\n double m_attribute3;\n};\n\nrtl::OUString testMulti(\n com::sun::star::uno::Reference< test::testtools::bridgetest::XMulti >\n const & multi);\n\n} }\n\n#endif\n<|endoftext|>"} {"text":"#include \n#include \n\n#include \"bulk_test_common.hpp\"\n#include \"set_backend.hpp\"\n#include \n\nextern environment env;\n\nvoid test_communication() {\n env.spawn(env.available_processors(), [](auto& world) {\n int s = world.processor_id();\n int p = world.active_processors();\n\n BULK_SKIP_SECTION_IF(\"Communication\", p < 1);\n\n BULK_SECTION(\"Put\") {\n \/\/ test `put` to single variable\n bulk::var a(world, 3);\n\n BULK_CHECK(a.value() == 3,\n \"correct initial value for variable\");\n\n bulk::put(world.next_processor(), s, a);\n world.sync();\n\n BULK_CHECK(a.value() == ((s + p - 1) % p),\n \"receive correct value after putting\");\n }\n\n BULK_SECTION(\"Broadcast\") {\n \/\/ test `put` to single variable\n bulk::var a(world, 3);\n\n if (world.processor_id() == 1) {\n a.broadcast(2);\n }\n world.sync();\n\n BULK_CHECK(a.value() == 2,\n \"receive correct value after broadcasting\");\n }\n\n BULK_SECTION(\"Put is delayed\") {\n using namespace std::chrono_literals;\n\n \/\/ test `put` to single variable\n bulk::var a(world, s);\n\n bulk::put(world.next_processor(), s, a);\n\n \/\/ sleep\n std::this_thread::sleep_for(20ms);\n\n BULK_CHECK(a.value() == s, \"local copy untouched before sync\");\n\n world.sync();\n\n BULK_CHECK(a.value() == world.prev_processor(), \"receive data after sync\");\n }\n\n BULK_SECTION(\"Sugarized put\") {\n \/\/ test `put` to single variable\n bulk::var a(world);\n\n a(world.next_processor()) = s;\n world.sync();\n\n BULK_CHECK(a.value() == ((s + p - 1) % p),\n \"receive correct value after sugarized putting\");\n }\n\n BULK_SECTION(\"Put to self\") {\n bulk::var a(world);\n\n bulk::put(s, s, a);\n world.sync();\n\n BULK_CHECK(a.value() == s,\n \"receive correct value after putting to self\");\n }\n\n BULK_SECTION(\"Get from self\") {\n bulk::var a(world);\n a = s;\n auto b = bulk::get(s, a);\n world.sync();\n\n BULK_CHECK(b.value() == s,\n \"receive correct value after getting from self\");\n }\n\n BULK_SECTION(\"Put non-int\") {\n \/\/ test `put` float to single variable\n bulk::var a(world, 5.0f);\n\n bulk::put(world.next_processor(), 1.0f, a);\n world.sync();\n\n BULK_CHECK(a.value() == 1.0f,\n \"receive correct value after putting float\");\n }\n\n BULK_SECTION(\"Put custom struct\") {\n struct custom_struct {\n int x;\n float y;\n };\n bulk::var a(world, {4, 8.0f});\n\n bulk::put(world.next_processor(), {3, 2.0f}, a);\n world.sync();\n\n BULK_CHECK(a.value().x == 3 && a.value().y == 2.0f,\n \"receive correct value after putting custom struct\");\n }\n\n\n BULK_SECTION(\"Put multiple\") {\n int size = 5;\n\n \/\/ test `put` to multiple variables\n std::vector> xs;\n for (int i = 0; i < size; ++i)\n xs.emplace_back(world);\n\n for (int i = 0; i < size; ++i) {\n bulk::put(world.next_processor(), s + i, xs[i]);\n }\n\n world.sync();\n\n for (int i = 0; i < size; ++i) {\n BULK_CHECK(xs[i].value() == ((s + p - 1) % p) + i,\n \"receive correct value after multiple puts to \"\n \"array of variables\");\n }\n }\n\n BULK_SECTION(\"Put unequal\") {\n int size = 5;\n\n \/\/ test `put` to multiple variables\n std::vector> xs;\n for (int i = 0; i < size; ++i)\n xs.emplace_back(world);\n\n if (s == 0)\n for (int i = 1; i < p; ++i) {\n for (int j = 0; j < size; ++j) {\n bulk::put(i, i, xs[j]);\n }\n }\n\n world.sync();\n\n bulk::future a(world);\n if (s == 0)\n a = bulk::get(p - 1, xs[size - 1]);\n\n world.sync();\n\n BULK_CHECK(\n a.value() == p - 1,\n \"receive correct value after heterogeneous puts and getting\");\n }\n\n BULK_SECTION(\"Get\") {\n bulk::var b(world);\n b.value() = s;\n world.sync();\n\n auto c = bulk::get(world.next_processor(), b);\n world.sync();\n\n BULK_CHECK(c.value() == world.next_processor(),\n \"receive correct value after getting\");\n }\n\n BULK_SECTION(\"Sugarized get\") {\n bulk::var b(world);\n b.value() = s;\n world.sync();\n\n auto c = b(world.next_processor()).get();\n world.sync();\n\n BULK_CHECK(c.value() == world.next_processor(),\n \"receive correct value after sugarized getting\");\n }\n\n BULK_SECTION(\"Get multiple\") {\n int size = 5;\n bulk::var x(world);\n x.value() = s;\n\n world.sync();\n\n std::vector> ys;\n for (int i = 0; i < size; ++i) {\n ys.push_back(bulk::get(world.next_processor(), x));\n }\n\n world.sync();\n\n for (auto& y : ys) {\n BULK_CHECK(y.value() == world.next_processor(),\n \"receive correct value after getting multiple\");\n }\n }\n\n BULK_SECTION(\"Put array\") {\n std::vector test(10);\n std::iota(test.begin(), test.end(), 1);\n\n bulk::coarray xs(world, 10, 5);\n xs.put(world.next_processor(), test.begin(), test.end());\n world.sync();\n\n BULK_CHECK(xs[5] == 6, \"put iterator range\");\n }\n\n BULK_SECTION(\"Coarray\") {\n bulk::coarray zs(world, 10);\n\n BULK_CHECK(zs.size() == 10,\n \"can obtain the size of a coarray\");\n BULK_CHECK(zs.empty() == false, \"can check for emptyness\");\n\n zs(world.next_processor())[1] = s;\n\n world.sync();\n\n BULK_CHECK(\n zs[1] == world.prev_processor(),\n \"putting to remote coarray image gives correct result\");\n\n zs[3] = 2;\n\n BULK_CHECK(zs[3] == 2,\n \"writing to local coarray gives correct result\");\n\n auto a = zs(2)[1].get();\n world.sync();\n\n BULK_CHECK(a.value() == 1,\n \"getting from coarray gives correct result\");\n }\n\n BULK_SECTION(\"Coarray iteration\") {\n auto xs = bulk::gather_all(world, s);\n int t = 0;\n for (auto x : xs) {\n BULK_CHECK(x == t++, \"gather operation succeeded\");\n }\n }\n\n BULK_SECTION(\"Coarray slicing\") {\n bulk::coarray zs(world, 10, 0);\n zs(world.next_processor())[{2, 5}] = s;\n zs(world.next_processor())[{0, 2}] = {s - 1, s - 2};\n\n world.sync();\n\n for (int i = 2; i < 5; ++i) {\n BULK_CHECK(zs[i] == world.prev_processor(),\n \"setting slice to constant\");\n }\n BULK_CHECK(zs[5] == 0,\n \"outside the slice values are untouched\");\n BULK_CHECK(zs[0] == world.prev_processor() - 1,\n \"individual slice setting\");\n BULK_CHECK(zs[1] == world.prev_processor() - 2,\n \"individual slice setting\");\n }\n\n BULK_SECTION(\"Single message passing\") {\n bulk::queue q(world);\n q(world.next_processor()).send(123, 1337);\n world.sync();\n for (auto& msg : q) {\n BULK_CHECK(std::get<0>(msg) == 123 &&\n std::get<1>(msg) == 1337,\n \"message passed succesfully\");\n }\n }\n\n BULK_SECTION(\"Message to self\") {\n bulk::queue q(world);\n\n q(world.processor_id()).send(123, 1337);\n world.sync();\n int tag = 0;\n int content = 0;\n for (auto msg : q) {\n tag = std::get<0>(msg);\n content = std::get<1>(msg);\n }\n BULK_CHECK(tag == 123 && content == 1337,\n \"message passed succesfully\");\n }\n\n BULK_SECTION(\"Multiple messages to self\") {\n auto q = bulk::queue(world);\n\n q(world.processor_id()).send(123, 1337);\n world.sync();\n int tag = 0;\n int content = 0;\n for (auto msg : q) {\n tag = std::get<0>(msg);\n content = std::get<1>(msg);\n }\n BULK_CHECK(tag == 123 && content == 1337,\n \"message passed succesfully\");\n }\n\n BULK_SECTION(\"Multiple message passing\") {\n std::vector contents = {1337, 12345, 1230519, 5, 8};\n\n bulk::queue q(world);\n for (size_t i = 0; i < contents.size(); ++i) {\n q(world.next_processor()).send(s, contents[i]);\n }\n\n world.sync();\n\n int k = 0;\n BULK_CHECK(!q.empty(), \"multiple messages arrived\");\n for (auto msg : q) {\n BULK_CHECK(std::get<0>(msg) == world.prev_processor() &&\n std::get<1>(msg) == contents[k++],\n \"multiple messages passed succesfully\");\n }\n }\n\n BULK_SECTION(\"Multiple queue and types message passing\") {\n std::vector contents = {1337, 12345, 1230519, 5, 8};\n std::vector contents2 = {1.0f, 2.0f, 3.0f, 4.0f};\n\n bulk::queue q(world);\n bulk::queue q2(world);\n\n for (size_t i = 0; i < contents.size(); ++i) {\n q(world.next_processor()).send(contents[i]);\n }\n for (size_t i = 0; i < contents2.size(); ++i) {\n q2(world.next_processor()).send(s, contents2[i]);\n }\n\n world.sync();\n\n int k = 0;\n BULK_CHECK(!q.empty() && !q2.empty(), \"queues are non-empty\");\n for (auto& msg : q) {\n BULK_CHECK(msg == contents[k++],\n \"received correct result on q\");\n }\n\n int l = 0;\n BULK_CHECK(q.size() == contents.size(),\n \"first queue correct number of messages\");\n\n BULK_CHECK(q2.size() == contents2.size(),\n \"second queue correct number of messages\");\n\n for (auto& msg : q2) {\n BULK_CHECK(std::get<0>(msg) == world.prev_processor() &&\n std::get<1>(msg) == contents2[l++],\n \"received correct result on q2\");\n }\n\n world.sync();\n\n BULK_CHECK(q.empty(), \"first queue gets emptied\");\n BULK_CHECK(q2.empty(), \"second queue gets emptied\");\n }\n });\n}\nAdd delayed get unittest#include \n#include \n\n#include \"bulk_test_common.hpp\"\n#include \"set_backend.hpp\"\n#include \n\nextern environment env;\n\nvoid test_communication() {\n env.spawn(env.available_processors(), [](auto& world) {\n int s = world.processor_id();\n int p = world.active_processors();\n\n BULK_SKIP_SECTION_IF(\"Communication\", p < 1);\n\n BULK_SECTION(\"Put\") {\n \/\/ test `put` to single variable\n bulk::var a(world, 3);\n\n BULK_CHECK(a.value() == 3,\n \"correct initial value for variable\");\n\n bulk::put(world.next_processor(), s, a);\n world.sync();\n\n BULK_CHECK(a.value() == ((s + p - 1) % p),\n \"receive correct value after putting\");\n }\n\n BULK_SECTION(\"Broadcast\") {\n \/\/ test `put` to single variable\n bulk::var a(world, 3);\n\n if (world.processor_id() == 1) {\n a.broadcast(2);\n }\n world.sync();\n\n BULK_CHECK(a.value() == 2,\n \"receive correct value after broadcasting\");\n }\n\n BULK_SECTION(\"Put and get delayed\") {\n using namespace std::chrono_literals;\n\n \/\/ test `put` to single variable\n bulk::var a(world, s);\n\n bulk::put(world.next_processor(), s, a);\n\n \/\/ sleep\n std::this_thread::sleep_for(20ms);\n\n BULK_CHECK(a.value() == s, \"local copy untouched before sync\");\n\n world.sync();\n\n BULK_CHECK(a.value() == world.prev_processor(), \"receive data after sync\");\n\n a.value() = 42;\n\n world.sync();\n\n auto b = bulk::get(world.next_processor(), a);\n\n std::this_thread::sleep_for(20ms);\n\n a.value() = 45;\n\n world.sync();\n\n BULK_CHECK(b.value() == 45, \"receive correct value after get\");\n }\n\n BULK_SECTION(\"Sugarized put\") {\n \/\/ test `put` to single variable\n bulk::var a(world);\n\n a(world.next_processor()) = s;\n world.sync();\n\n BULK_CHECK(a.value() == ((s + p - 1) % p),\n \"receive correct value after sugarized putting\");\n }\n\n BULK_SECTION(\"Put to self\") {\n bulk::var a(world);\n\n bulk::put(s, s, a);\n world.sync();\n\n BULK_CHECK(a.value() == s,\n \"receive correct value after putting to self\");\n }\n\n BULK_SECTION(\"Get from self\") {\n bulk::var a(world);\n a = s;\n auto b = bulk::get(s, a);\n world.sync();\n\n BULK_CHECK(b.value() == s,\n \"receive correct value after getting from self\");\n }\n\n BULK_SECTION(\"Put non-int\") {\n \/\/ test `put` float to single variable\n bulk::var a(world, 5.0f);\n\n bulk::put(world.next_processor(), 1.0f, a);\n world.sync();\n\n BULK_CHECK(a.value() == 1.0f,\n \"receive correct value after putting float\");\n }\n\n BULK_SECTION(\"Put custom struct\") {\n struct custom_struct {\n int x;\n float y;\n };\n bulk::var a(world, {4, 8.0f});\n\n bulk::put(world.next_processor(), {3, 2.0f}, a);\n world.sync();\n\n BULK_CHECK(a.value().x == 3 && a.value().y == 2.0f,\n \"receive correct value after putting custom struct\");\n }\n\n\n BULK_SECTION(\"Put multiple\") {\n int size = 5;\n\n \/\/ test `put` to multiple variables\n std::vector> xs;\n for (int i = 0; i < size; ++i)\n xs.emplace_back(world);\n\n for (int i = 0; i < size; ++i) {\n bulk::put(world.next_processor(), s + i, xs[i]);\n }\n\n world.sync();\n\n for (int i = 0; i < size; ++i) {\n BULK_CHECK(xs[i].value() == ((s + p - 1) % p) + i,\n \"receive correct value after multiple puts to \"\n \"array of variables\");\n }\n }\n\n BULK_SECTION(\"Put unequal\") {\n int size = 5;\n\n \/\/ test `put` to multiple variables\n std::vector> xs;\n for (int i = 0; i < size; ++i)\n xs.emplace_back(world);\n\n if (s == 0)\n for (int i = 1; i < p; ++i) {\n for (int j = 0; j < size; ++j) {\n bulk::put(i, i, xs[j]);\n }\n }\n\n world.sync();\n\n BULK_CHECK(xs[2].value() == s,\n \"receive correct value after heterogeneous puts\");\n\n bulk::future a(world);\n if (s == 0)\n a = bulk::get(p - 1, xs[size - 1]);\n\n world.sync();\n\n BULK_CHECK_ONCE(a.value() == p - 1,\n \"receive correct value after getting\");\n }\n\n BULK_SECTION(\"Get\") {\n bulk::var b(world);\n b.value() = s;\n world.sync();\n\n auto c = bulk::get(world.next_processor(), b);\n world.sync();\n\n BULK_CHECK(c.value() == world.next_processor(),\n \"receive correct value after getting\");\n }\n\n BULK_SECTION(\"Sugarized get\") {\n bulk::var b(world);\n b.value() = s;\n world.sync();\n\n auto c = b(world.next_processor()).get();\n world.sync();\n\n BULK_CHECK(c.value() == world.next_processor(),\n \"receive correct value after sugarized getting\");\n }\n\n BULK_SECTION(\"Get multiple\") {\n int size = 5;\n bulk::var x(world);\n x.value() = s;\n\n world.sync();\n\n std::vector> ys;\n for (int i = 0; i < size; ++i) {\n ys.push_back(bulk::get(world.next_processor(), x));\n }\n\n world.sync();\n\n for (auto& y : ys) {\n BULK_CHECK(y.value() == world.next_processor(),\n \"receive correct value after getting multiple\");\n }\n }\n\n BULK_SECTION(\"Put array\") {\n std::vector test(10);\n std::iota(test.begin(), test.end(), 1);\n\n bulk::coarray xs(world, 10, 5);\n xs.put(world.next_processor(), test.begin(), test.end());\n world.sync();\n\n BULK_CHECK(xs[5] == 6, \"put iterator range\");\n }\n\n BULK_SECTION(\"Coarray\") {\n bulk::coarray zs(world, 10);\n\n BULK_CHECK(zs.size() == 10,\n \"can obtain the size of a coarray\");\n BULK_CHECK(zs.empty() == false, \"can check for emptyness\");\n\n zs(world.next_processor())[1] = s;\n\n world.sync();\n\n BULK_CHECK(\n zs[1] == world.prev_processor(),\n \"putting to remote coarray image gives correct result\");\n\n zs[3] = 2;\n\n BULK_CHECK(zs[3] == 2,\n \"writing to local coarray gives correct result\");\n\n auto a = zs(2)[1].get();\n world.sync();\n\n BULK_CHECK(a.value() == 1,\n \"getting from coarray gives correct result\");\n }\n\n BULK_SECTION(\"Coarray iteration\") {\n auto xs = bulk::gather_all(world, s);\n int t = 0;\n for (auto x : xs) {\n BULK_CHECK(x == t++, \"gather operation succeeded\");\n }\n }\n\n BULK_SECTION(\"Coarray slicing\") {\n bulk::coarray zs(world, 10, 0);\n zs(world.next_processor())[{2, 5}] = s;\n zs(world.next_processor())[{0, 2}] = {s - 1, s - 2};\n\n world.sync();\n\n for (int i = 2; i < 5; ++i) {\n BULK_CHECK(zs[i] == world.prev_processor(),\n \"setting slice to constant\");\n }\n BULK_CHECK(zs[5] == 0,\n \"outside the slice values are untouched\");\n BULK_CHECK(zs[0] == world.prev_processor() - 1,\n \"individual slice setting\");\n BULK_CHECK(zs[1] == world.prev_processor() - 2,\n \"individual slice setting\");\n }\n\n BULK_SECTION(\"Single message passing\") {\n bulk::queue q(world);\n q(world.next_processor()).send(123, 1337);\n world.sync();\n for (auto& msg : q) {\n BULK_CHECK(std::get<0>(msg) == 123 &&\n std::get<1>(msg) == 1337,\n \"message passed succesfully\");\n }\n }\n\n BULK_SECTION(\"Message to self\") {\n bulk::queue q(world);\n\n q(world.processor_id()).send(123, 1337);\n world.sync();\n int tag = 0;\n int content = 0;\n for (auto msg : q) {\n tag = std::get<0>(msg);\n content = std::get<1>(msg);\n }\n BULK_CHECK(tag == 123 && content == 1337,\n \"message passed succesfully\");\n }\n\n BULK_SECTION(\"Multiple messages to self\") {\n auto q = bulk::queue(world);\n\n q(world.processor_id()).send(123, 1337);\n world.sync();\n int tag = 0;\n int content = 0;\n for (auto msg : q) {\n tag = std::get<0>(msg);\n content = std::get<1>(msg);\n }\n BULK_CHECK(tag == 123 && content == 1337,\n \"message passed succesfully\");\n }\n\n BULK_SECTION(\"Multiple message passing\") {\n std::vector contents = {1337, 12345, 1230519, 5, 8};\n\n bulk::queue q(world);\n for (size_t i = 0; i < contents.size(); ++i) {\n q(world.next_processor()).send(s, contents[i]);\n }\n\n world.sync();\n\n int k = 0;\n BULK_CHECK(!q.empty(), \"multiple messages arrived\");\n for (auto msg : q) {\n BULK_CHECK(std::get<0>(msg) == world.prev_processor() &&\n std::get<1>(msg) == contents[k++],\n \"multiple messages passed succesfully\");\n }\n }\n\n BULK_SECTION(\"Multiple queue and types message passing\") {\n std::vector contents = {1337, 12345, 1230519, 5, 8};\n std::vector contents2 = {1.0f, 2.0f, 3.0f, 4.0f};\n\n bulk::queue q(world);\n bulk::queue q2(world);\n\n for (size_t i = 0; i < contents.size(); ++i) {\n q(world.next_processor()).send(contents[i]);\n }\n for (size_t i = 0; i < contents2.size(); ++i) {\n q2(world.next_processor()).send(s, contents2[i]);\n }\n\n world.sync();\n\n int k = 0;\n BULK_CHECK(!q.empty() && !q2.empty(), \"queues are non-empty\");\n for (auto& msg : q) {\n BULK_CHECK(msg == contents[k++],\n \"received correct result on q\");\n }\n\n int l = 0;\n BULK_CHECK(q.size() == contents.size(),\n \"first queue correct number of messages\");\n\n BULK_CHECK(q2.size() == contents2.size(),\n \"second queue correct number of messages\");\n\n for (auto& msg : q2) {\n BULK_CHECK(std::get<0>(msg) == world.prev_processor() &&\n std::get<1>(msg) == contents2[l++],\n \"received correct result on q2\");\n }\n\n world.sync();\n\n BULK_CHECK(q.empty(), \"first queue gets emptied\");\n BULK_CHECK(q2.empty(), \"second queue gets emptied\");\n }\n });\n}\n<|endoftext|>"} {"text":"\/*\n * Quantum++\n *\n * Copyright (c) 2013 - 2015 Vlad Gheorghiu (vgheorgh@gmail.com)\n *\n * This file is part of Quantum++.\n *\n * Quantum++ is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * Quantum++ is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with Quantum++. If not, see .\n *\/\n\n#include \n\n#include \n\/\/ #include \/\/ support for MATLAB\n\/\/ #include \/\/ support for testing features\n\nusing namespace qpp;\n\n\/\/ TODO: write your unit tests here\n\n\/\/ ********** qpp::sum() **********\nTEST(qpp_sum_test, PositiveNumbers)\n{\n std::vector v{0, 1, 2, 3};\n EXPECT_EQ (6, qpp::sum(v.begin(), v.end()));\n}\n\nTEST(qpp_sum_test, NegativeNumbers)\n{\n std::vector v{0, -1, -2, -3};\n EXPECT_EQ (-6, qpp::sum(v.begin(), v.end()));\n}\n\nTEST(qpp_sum_test, MixedNumbers)\n{\n std::vector v{ -3, -2, -1, 0, 1, 2};\n EXPECT_EQ (-3, qpp::sum(v.begin(), v.end()));\n}\n\/\/ ********** END qpp::sum() **********\n\n\/\/ ********** qpp::prod() **********\nTEST(qpp_prod_test, PositiveNumbers)\n{\n std::vector v{1, 2, 3, 4};\n EXPECT_EQ (24, qpp::prod(v.begin(), v.end()));\n}\n\/\/ ********** END qpp::prod() **********\n\n\/\/ ********** qpp::modpow() **********\nTEST(qpp_modpow_test, PositiveNumbers)\n{\n EXPECT_EQ (0, qpp::modpow(2, 3, 4));\n EXPECT_EQ (34, qpp::modpow(17, 176, 37));\n EXPECT_EQ (4042, qpp::modpow(178373, 9281623, 6217));\n}\n\/\/ ********** END qpp::modpow() **********\n\n\nint main(int argc, char** argv)\n{\n ::testing::InitGoogleTest(&argc, argv);\n return RUN_ALL_TESTS();\n}\ncommit\/*\n * Quantum++\n *\n * Copyright (c) 2013 - 2015 Vlad Gheorghiu (vgheorgh@gmail.com)\n *\n * This file is part of Quantum++.\n *\n * Quantum++ is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * Quantum++ is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with Quantum++. If not, see .\n *\/\n\n#include \n\n#include \n\/\/ #include \/\/ support for MATLAB\n\/\/ #include \/\/ support for testing features\n\nusing namespace qpp;\n\n\/\/ TODO: write your unit tests here\n\n\/\/ ********** qpp::sum() **********\nTEST(qpp_sum_test, PositiveNumbers)\n{\n std::vector v{0, 1, 2, 3};\n EXPECT_EQ (6, qpp::sum(v.begin(), v.end()));\n}\n\nTEST(qpp_sum_test, NegativeNumbers)\n{\n std::vector v{0, -1, -2, -3};\n EXPECT_EQ (-6, qpp::sum(v.begin(), v.end()));\n}\n\nTEST(qpp_sum_test, MixedNumbers)\n{\n std::vector v{ -3, -2, -1, 0, 1, 2};\n EXPECT_EQ (-3, qpp::sum(v.begin(), v.end()));\n}\n\/\/ ********** END qpp::sum() **********\n\n\/\/ ********** qpp::prod() **********\nTEST(qpp_prod_test, PositiveNumbers)\n{\n std::vector v{1, 2, 3, 4};\n EXPECT_EQ (24, qpp::prod(v.begin(), v.end()));\n}\n\/\/ ********** END qpp::prod() **********\n\n\/\/ ********** qpp::modpow() **********\nTEST(qpp_modpow_test, PositiveNumbers)\n{\n EXPECT_EQ (0, qpp::modpow(2, 3, 4));\n EXPECT_EQ (34, qpp::modpow(17, 176, 37));\n EXPECT_EQ (4042, qpp::modpow(178373, 9281623, 6217));\n}\n\/\/ ********** END qpp::modpow() **********\n\nint main(int argc, char** argv)\n{\n ::testing::InitGoogleTest(&argc, argv);\n return RUN_ALL_TESTS();\n}\n<|endoftext|>"} {"text":"#ifndef ITER_CYCLE_H_\n#define ITER_CYCLE_H_\n\n#include \"internal\/iterator_wrapper.hpp\"\n#include \"internal\/iterbase.hpp\"\n\n#include \n#include \n#include \n\nnamespace iter {\n namespace impl {\n template \n class Cycler;\n\n using CycleFn = IterToolFn;\n }\n constexpr impl::CycleFn cycle{};\n}\n\ntemplate \nclass iter::impl::Cycler {\n private:\n friend CycleFn;\n\n Container container_;\n\n Cycler(Container&& container)\n : container_(std::forward(container)) {}\n\n public:\n Cycler(Cycler&&) = default;\n class Iterator : public std::iterator> {\n private:\n IteratorWrapper sub_iter_;\n IteratorWrapper sub_begin_;\n IteratorWrapper sub_end_;\n\n public:\n Iterator(IteratorWrapper&& sub_iter,\n IteratorWrapper&& sub_end)\n : sub_iter_{sub_iter},\n sub_begin_{sub_iter},\n sub_end_{std::move(sub_end)} {}\n\n iterator_deref operator*() {\n return *sub_iter_;\n }\n\n iterator_arrow operator->() {\n return apply_arrow(sub_iter_);\n }\n\n Iterator& operator++() {\n ++sub_iter_;\n \/\/ reset to beginning upon reaching the sub_end_\n if (!(sub_iter_ != sub_end_)) {\n sub_iter_ = sub_begin_;\n }\n return *this;\n }\n\n Iterator operator++(int) {\n auto ret = *this;\n ++*this;\n return ret;\n }\n\n bool operator!=(const Iterator& other) const {\n return sub_iter_ != other.sub_iter_;\n }\n\n bool operator==(const Iterator& other) const {\n return !(*this != other);\n }\n };\n\n Iterator begin() {\n return {get_begin(container_), get_end(container_)};\n }\n\n Iterator end() {\n return {get_end(container_), get_end(container_)};\n }\n};\n\n#endif\nAdds support for const iteration to cycle#ifndef ITER_CYCLE_H_\n#define ITER_CYCLE_H_\n\n#include \"internal\/iterator_wrapper.hpp\"\n#include \"internal\/iterbase.hpp\"\n\n#include \n#include \n#include \n\nnamespace iter {\n namespace impl {\n template \n class Cycler;\n\n using CycleFn = IterToolFn;\n }\n constexpr impl::CycleFn cycle{};\n}\n\ntemplate \nclass iter::impl::Cycler {\n private:\n friend CycleFn;\n\n Container container_;\n\n Cycler(Container&& container)\n : container_(std::forward(container)) {}\n\n public:\n Cycler(Cycler&&) = default;\n template \n class Iterator : public std::iterator> {\n private:\n template \n friend class Iterator;\n IteratorWrapper sub_iter_;\n IteratorWrapper sub_begin_;\n IteratorWrapper sub_end_;\n\n public:\n Iterator(IteratorWrapper&& sub_iter,\n IteratorWrapper&& sub_end)\n : sub_iter_{sub_iter},\n sub_begin_{sub_iter},\n sub_end_{std::move(sub_end)} {}\n\n iterator_deref operator*() {\n return *sub_iter_;\n }\n\n iterator_arrow operator->() {\n return apply_arrow(sub_iter_);\n }\n\n Iterator& operator++() {\n ++sub_iter_;\n \/\/ reset to beginning upon reaching the sub_end_\n if (!(sub_iter_ != sub_end_)) {\n sub_iter_ = sub_begin_;\n }\n return *this;\n }\n\n Iterator operator++(int) {\n auto ret = *this;\n ++*this;\n return ret;\n }\n\n template \n bool operator!=(const Iterator& other) const {\n return sub_iter_ != other.sub_iter_;\n }\n\n template \n bool operator==(const Iterator& other) const {\n return !(*this != other);\n }\n };\n\n Iterator begin() {\n return {get_begin(container_), get_end(container_)};\n }\n\n Iterator end() {\n return {get_end(container_), get_end(container_)};\n }\n\n Iterator> begin() const {\n return {get_begin(as_const(container_)), get_end(as_const(container_))};\n }\n\n Iterator> end() const {\n return {get_end(as_const(container_)), get_end(as_const(container_))};\n }\n};\n\n#endif\n<|endoftext|>"} {"text":"#ifndef ITER_CYCLE_H_\n#define ITER_CYCLE_H_\n\n#include \"iterbase.hpp\"\n\n#include \n#include \n#include \n\nnamespace iter {\n\n \/\/Forward declarations of Cycle and cycle\n template \n class Cycle;\n\n template \n Cycle cycle(Container&&);\n\n template \n Cycle> cycle(std::initializer_list);\n\n template \n class Cycle {\n private:\n \/\/ The cycle function is the only thing allowed to create a Cycle\n friend Cycle cycle(Container&&);\n template \n friend Cycle> cycle(\n std::initializer_list);\n\n Container container;\n \n \/\/ Value constructor for use only in the cycle function\n Cycle(Container container)\n : container(std::forward(container))\n { }\n\n public:\n class Iterator \n : public std::iterator>\n {\n private:\n using iter_type = iterator_type;\n iterator_type sub_iter;\n iterator_type begin;\n iterator_type end;\n public:\n Iterator (iterator_type iter,\n iterator_type end)\n : sub_iter{iter},\n begin{iter},\n end{end}\n { } \n\n iterator_deref operator*() const {\n return *this->sub_iter;\n }\n\n Iterator& operator++() { \n ++this->sub_iter;\n \/\/ reset to beginning upon reaching the end\n if (!(this->sub_iter != this->end)) {\n \/\/ explicit destruction with placement new in order\n \/\/ to support iterators with no operator=\n this->sub_iter.~iter_type();\n new(&this->sub_iter) iterator_type(\n this->begin);\n }\n return *this;\n }\n\n Iterator operator++(int) {\n auto ret = *this;\n ++*this;\n return ret;\n }\n\n bool operator!=(const Iterator& other) const {\n return this->sub_iter != other.sub_iter;\n }\n\n bool operator==(const Iterator& other) const {\n return !(*this != other);\n }\n };\n\n Iterator begin() {\n return {std::begin(this->container),\n std::end(this->container)};\n }\n\n Iterator end() {\n return {std::end(this->container),\n std::end(this->container)};\n }\n\n };\n\n \/\/ Helper function to instantiate a Cycle\n template \n Cycle cycle(Container&& container) {\n return {std::forward(container)};\n }\n\n template \n Cycle> cycle(std::initializer_list il)\n {\n return {std::move(il)};\n }\n}\n\n#endif\nRemoves placement new in favor of assignment#ifndef ITER_CYCLE_H_\n#define ITER_CYCLE_H_\n\n#include \"iterbase.hpp\"\n\n#include \n#include \n#include \n\nnamespace iter {\n\n \/\/Forward declarations of Cycle and cycle\n template \n class Cycle;\n\n template \n Cycle cycle(Container&&);\n\n template \n Cycle> cycle(std::initializer_list);\n\n template \n class Cycle {\n private:\n \/\/ The cycle function is the only thing allowed to create a Cycle\n friend Cycle cycle(Container&&);\n template \n friend Cycle> cycle(\n std::initializer_list);\n\n Container container;\n \n \/\/ Value constructor for use only in the cycle function\n Cycle(Container container)\n : container(std::forward(container))\n { }\n\n public:\n class Iterator \n : public std::iterator>\n {\n private:\n using iter_type = iterator_type;\n iterator_type sub_iter;\n iterator_type begin;\n iterator_type end;\n public:\n Iterator (iterator_type iter,\n iterator_type end)\n : sub_iter{iter},\n begin{iter},\n end{end}\n { } \n\n iterator_deref operator*() const {\n return *this->sub_iter;\n }\n\n Iterator& operator++() { \n ++this->sub_iter;\n \/\/ reset to beginning upon reaching the end\n if (!(this->sub_iter != this->end)) {\n this->sub_iter = this->begin;\n }\n return *this;\n }\n\n Iterator operator++(int) {\n auto ret = *this;\n ++*this;\n return ret;\n }\n\n bool operator!=(const Iterator& other) const {\n return this->sub_iter != other.sub_iter;\n }\n\n bool operator==(const Iterator& other) const {\n return !(*this != other);\n }\n };\n\n Iterator begin() {\n return {std::begin(this->container),\n std::end(this->container)};\n }\n\n Iterator end() {\n return {std::end(this->container),\n std::end(this->container)};\n }\n\n };\n\n \/\/ Helper function to instantiate a Cycle\n template \n Cycle cycle(Container&& container) {\n return {std::forward(container)};\n }\n\n template \n Cycle> cycle(std::initializer_list il)\n {\n return {std::move(il)};\n }\n}\n\n#endif\n<|endoftext|>"} {"text":"#ifndef CYCLE__H__\n#define CYCLE__H__\n\n#include \n\n#include \n#include \n\nnamespace iter {\n\n \/\/Forward declarations of Cycle and cycle\n template \n class Cycle;\n\n template \n Cycle cycle(Container &);\n\n\n template \n class Cycle : public IterBase{\n private:\n \/\/ The cycle function is the only thing allowed to create a Cycle\n friend Cycle cycle(Container &);\n\n using typename IterBase::contained_iter_type;\n\n using typename IterBase::contained_iter_ret;\n\n Container & container;\n \n \/\/ Value constructor for use only in the cycle function\n Cycle(Container & container) : container(container) { }\n Cycle () = delete;\n Cycle & operator=(const Cycle &) = delete;\n\n public:\n Cycle(const Cycle &) = default;\n class Iterator {\n private:\n contained_iter_type sub_iter;\n const contained_iter_type begin;\n const contained_iter_type end;\n public:\n Iterator (contained_iter_type iter,\n contained_iter_type end) :\n sub_iter(iter),\n begin(iter),\n end(end)\n { } \n\n contained_iter_ret operator*() const {\n return *this->sub_iter;\n }\n\n Iterator & operator++() { \n ++this->sub_iter;\n \/\/ reset to beginning upon reaching the end\n if (this->sub_iter == this->end) {\n this->sub_iter = this->begin;\n }\n return *this;\n }\n\n constexpr bool operator!=(const Iterator &) const {\n return true;\n }\n };\n\n Iterator begin() const {\n return Iterator(std::begin(this->container),\n std::end(this->container));\n }\n\n Iterator end() const {\n return Iterator(std::end(this->container),\n std::end(this->container));\n }\n\n };\n\n \/\/ Helper function to instantiate an Filter\n template \n Cycle cycle(Container & container) {\n return Cycle(container);\n }\n\n}\n\n#endif \/\/ifndef CYCLE__H__\nAdds support for initializer_list#ifndef CYCLE__H__\n#define CYCLE__H__\n\n#include \n\n#include \n#include \n\nnamespace iter {\n\n \/\/Forward declarations of Cycle and cycle\n template \n class Cycle;\n\n template \n Cycle cycle(Container &&);\n\n template \n Cycle> cycle(\n std::initializer_list &&);\n\n template \n class Cycle : public IterBase{\n public:\n \/\/ The cycle function is the only thing allowed to create a Cycle\n friend Cycle cycle(Container &&);\n template \n friend Cycle> cycle(\n std::initializer_list &&);\n\n using typename IterBase::contained_iter_type;\n\n using typename IterBase::contained_iter_ret;\n\n Container & container;\n \n \/\/ Value constructor for use only in the cycle function\n Cycle(Container && container) : container(container) { }\n Cycle () = delete;\n Cycle & operator=(const Cycle &) = delete;\n\n public:\n Cycle(const Cycle &) = default;\n class Iterator {\n private:\n contained_iter_type sub_iter;\n const contained_iter_type begin;\n const contained_iter_type end;\n public:\n Iterator (contained_iter_type iter,\n contained_iter_type end) :\n sub_iter(iter),\n begin(iter),\n end(end)\n { } \n\n contained_iter_ret operator*() const {\n return *this->sub_iter;\n }\n\n Iterator & operator++() { \n ++this->sub_iter;\n \/\/ reset to beginning upon reaching the end\n if (this->sub_iter == this->end) {\n this->sub_iter = this->begin;\n }\n return *this;\n }\n\n constexpr bool operator!=(const Iterator &) const {\n return true;\n }\n };\n\n Iterator begin() const {\n return Iterator(std::begin(this->container),\n std::end(this->container));\n }\n\n Iterator end() const {\n return Iterator(std::end(this->container),\n std::end(this->container));\n }\n\n };\n\n \/\/ Helper function to instantiate an Filter\n template \n Cycle cycle(Container && container) {\n return Cycle(std::forward(container));\n }\n\n template \n Cycle> cycle(std::initializer_list && il)\n {\n return Cycle>(\n std::forward>(il));\n }\n}\n\n#endif \/\/ifndef CYCLE__H__\n<|endoftext|>"} {"text":"\/*\n * SessionBlogdown.cpp\n *\n * Copyright (C) 2020 by RStudio, PBC\n *\n * Unless you have received this program directly from RStudio pursuant\n * to the terms of a commercial license agreement with RStudio, then\n * this program is licensed to you under the terms of version 3 of the\n * GNU Affero General Public License. This program is distributed WITHOUT\n * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,\n * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the\n * AGPL (http:\/\/www.gnu.org\/licenses\/agpl-3.0.txt) for more details.\n *\n *\/\n\n#include \"SessionBlogdown.hpp\"\n\n#include \n#include \n#include \n\n#include \n#include \n\n#include \n#include \n\n#include \"SessionRMarkdown.hpp\"\n\nusing namespace rstudio::core;\nusing namespace rstudio::core::shell_utils;\nusing namespace rstudio::session::module_context;\nusing namespace rstudio::session::modules::rmarkdown;\n\nnamespace rstudio {\nnamespace session {\nnamespace modules {\nnamespace rmarkdown {\nnamespace blogdown {\nnamespace {\n\n\nFilePath hugoRootPath()\n{\n return projects::projectContext().config().buildType != r_util::kBuildTypeNone\n ? projects::projectContext().buildTargetPath()\n : projects::projectContext().directory();\n}\n\ntemplate \nstd::string runHugo(const Args& args, bool logErrors = true)\n{\n ShellCommand hugo(\"hugo\");\n\n core::system::ProcessOptions options;\n\n \/\/ use build target path if this project has a build type\n options.workingDir = hugoRootPath();\n\n \/\/ detach the session so there is no terminal\n#ifndef _WIN32\n options.detachSession = true;\n#endif\n\n core::system::ProcessResult result;\n Error error = core::system::runCommand(hugo << args, options, &result);\n if (error)\n {\n if (logErrors)\n LOG_ERROR(error);\n return \"\";\n }\n else if (result.exitStatus != EXIT_SUCCESS)\n {\n if (logErrors)\n LOG_ERROR_MESSAGE(\"Error running hugo: \" + result.stdErr);\n return \"\";\n }\n else\n {\n return result.stdOut;\n }\n}\n\n\n} \/\/ anonymous namespace\n\ncore::json::Object blogdownConfig()\n{\n\n const char* const kIsBlogdownProject = \"is_blogdown_project\";\n const char* const kIsHugoProject = \"is_hugo_project\";\n const char* const kSiteDir = \"site_dir\";\n const char* const kStaticDirs = \"static_dirs\";\n const char* const kMarkdownEngine = \"markdown_engine\";\n const char* const kMarkdownEngineGoldmark = \"goldmark\";\n const char* const kMarkdownEngineBlackfriday = \"blackfriday\";\n const char* const kMarkdownExtensions = \"markdown_extensions\";\n\n json::Object config;\n\n \/\/ detect project type(s)\n bool isBlogdownProject = rmarkdown::isSiteProject(\"blogdown_site\");\n bool isHugoProject = isBlogdownProject;\n\n \/\/ if it's not a blogdown project, see if it's a hugo project. note that\n \/\/ we don't want to run hugo if we don't need to (startup time impacting\n \/\/ IDE startup time), so we gate the check by looking for a few sentinel\n \/\/ files + the presence of hugo on the system\n if (!isHugoProject)\n {\n if (projects::projectContext().hasProject())\n {\n FilePath hugoRoot = hugoRootPath();\n if (hugoRoot.completeChildPath(\"config.toml\").exists() ||\n hugoRoot.completeChildPath(\"config.yaml\").exists() ||\n hugoRoot.completeChildPath(\"config.json\").exists() ||\n hugoRoot.completeChildPath(\"config\").exists())\n {\n if (!module_context::findProgram(\"hugo\").isEmpty())\n {\n if (runHugo(\"config\", false).size() > 0)\n isHugoProject = true;\n }\n }\n }\n }\n\n \/\/ set into config\n config[kIsBlogdownProject] = isBlogdownProject;\n config[kIsHugoProject] = isHugoProject;\n\n if (isBlogdownProject || isHugoProject)\n {\n \/\/ get the site dir\n config[kSiteDir] = module_context::createFileSystemItem(hugoRootPath());\n\n \/\/ set the default static dirs\n json::Array staticDirs;\n staticDirs.push_back(\"static\");\n config[kStaticDirs] = staticDirs;\n\n \/\/ get the hugo version and use it to determine the default markdown engine\n std::string defaultMarkdownEngine = kMarkdownEngineGoldmark;\n std::string version = runHugo(\"version\");\n if (version.size() > 0)\n {\n boost::regex verRegex(\"(\\\\d+)\\\\.(\\\\d+)(?:.(\\\\d+))?\");\n boost::smatch match;\n if (regex_utils::search(version, match, verRegex))\n {\n int major = safe_convert::stringTo(match[1], 0);\n int minor = safe_convert::stringTo(match[2], 0);\n if (major <= 0 && minor < 60)\n defaultMarkdownEngine = kMarkdownEngineBlackfriday;\n }\n }\n\n \/\/ set defaults to start with\n std::string markdownEngine = defaultMarkdownEngine;\n std::string markdownExtensions = \"\";\n\n \/\/ get the hugo config\n std::string hugoConfig = runHugo(\"config\");\n\n \/\/ create map of variables\n if (hugoConfig.size() > 0)\n {\n std::map variables;\n boost::regex var(\"^([A-Za-z0-9_]+\\\\s*=\\\\s*[^\\n]+)$\");\n boost::sregex_token_iterator it(hugoConfig.begin(), hugoConfig.end(), var, 0);\n boost::sregex_token_iterator end;\n while (it != end)\n {\n core::system::Option var;\n if (core::system::parseEnvVar(*it, &var))\n {\n boost::algorithm::trim(var.first);\n boost::algorithm::trim(var.second);\n variables.insert(var);\n }\n it++;\n }\n\n \/\/ see if there is a markup variable\n const std::string markup = variables[\"markup\"];\n if (markup.size() > 0)\n {\n boost::regex handlerRegex(\"defaultmarkdownhandler\\\\:(\\\\w+)\");\n boost::smatch handlerMatch;\n if (regex_utils::search(markup, handlerMatch, handlerRegex))\n {\n \/\/ get the engine and set it if it's recognized (otherwise just behave as if\n \/\/ the default engine is configured)\n std::string matchedEngine = handlerMatch[1];\n if (matchedEngine == kMarkdownEngineBlackfriday || matchedEngine == kMarkdownEngineGoldmark)\n markdownEngine = matchedEngine;\n }\n\n \/\/ if we are goldmark check to see if unsafe is enabled. in that case\n \/\/ add the raw_html extension\n if (markdownEngine == kMarkdownEngineGoldmark)\n {\n boost::regex unsafeRegex(\"unsafe\\\\:true\");\n boost::smatch unsafeMatch;\n if (regex_utils::search(markup, unsafeMatch, unsafeRegex))\n markdownExtensions += \"+raw_html\";\n }\n }\n\n \/\/ see if there is a staticdir variable\n std::string staticdir = variables[\"staticdir\"];\n if (staticdir.size() > 0)\n {\n staticDirs.clear();\n\n staticdir = string_utils::strippedOfQuotes(staticdir);\n if (boost::algorithm::starts_with(staticdir, \"[\"))\n {\n boost::algorithm::replace_first(staticdir, \"[\", \"\");\n boost::algorithm::replace_last(staticdir, \"]\", \"\");\n std::vector dirs;\n boost::algorithm::split(dirs, staticdir, boost::algorithm::is_any_of(\" \"));\n staticDirs = core::json::toJsonArray(dirs);\n }\n else\n {\n staticDirs.push_back(staticdir);\n }\n config[kStaticDirs] = staticDirs;\n }\n }\n\n \/\/ populate config\n config[kMarkdownEngine] = markdownEngine;\n config[kMarkdownExtensions] = markdownExtensions;\n }\n else\n {\n config[kIsBlogdownProject] = false;\n }\n\n return config;\n}\n\n\n\n\n} \/\/ namespace blogdown\n} \/\/ namespace rmarkdown\n} \/\/ namespace modules\n} \/\/ namespace session\n} \/\/ namespace rstudio\ndetect hugo emojis\/*\n * SessionBlogdown.cpp\n *\n * Copyright (C) 2020 by RStudio, PBC\n *\n * Unless you have received this program directly from RStudio pursuant\n * to the terms of a commercial license agreement with RStudio, then\n * this program is licensed to you under the terms of version 3 of the\n * GNU Affero General Public License. This program is distributed WITHOUT\n * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,\n * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the\n * AGPL (http:\/\/www.gnu.org\/licenses\/agpl-3.0.txt) for more details.\n *\n *\/\n\n#include \"SessionBlogdown.hpp\"\n\n#include \n#include \n#include \n\n#include \n#include \n\n#include \n#include \n\n#include \"SessionRMarkdown.hpp\"\n\nusing namespace rstudio::core;\nusing namespace rstudio::core::shell_utils;\nusing namespace rstudio::session::module_context;\nusing namespace rstudio::session::modules::rmarkdown;\n\nnamespace rstudio {\nnamespace session {\nnamespace modules {\nnamespace rmarkdown {\nnamespace blogdown {\nnamespace {\n\n\nFilePath hugoRootPath()\n{\n return projects::projectContext().config().buildType != r_util::kBuildTypeNone\n ? projects::projectContext().buildTargetPath()\n : projects::projectContext().directory();\n}\n\ntemplate \nstd::string runHugo(const Args& args, bool logErrors = true)\n{\n ShellCommand hugo(\"hugo\");\n\n core::system::ProcessOptions options;\n\n \/\/ use build target path if this project has a build type\n options.workingDir = hugoRootPath();\n\n \/\/ detach the session so there is no terminal\n#ifndef _WIN32\n options.detachSession = true;\n#endif\n\n core::system::ProcessResult result;\n Error error = core::system::runCommand(hugo << args, options, &result);\n if (error)\n {\n if (logErrors)\n LOG_ERROR(error);\n return \"\";\n }\n else if (result.exitStatus != EXIT_SUCCESS)\n {\n if (logErrors)\n LOG_ERROR_MESSAGE(\"Error running hugo: \" + result.stdErr);\n return \"\";\n }\n else\n {\n return result.stdOut;\n }\n}\n\n\n} \/\/ anonymous namespace\n\ncore::json::Object blogdownConfig()\n{\n\n const char* const kIsBlogdownProject = \"is_blogdown_project\";\n const char* const kIsHugoProject = \"is_hugo_project\";\n const char* const kSiteDir = \"site_dir\";\n const char* const kStaticDirs = \"static_dirs\";\n const char* const kMarkdownEngine = \"markdown_engine\";\n const char* const kMarkdownEngineGoldmark = \"goldmark\";\n const char* const kMarkdownEngineBlackfriday = \"blackfriday\";\n const char* const kMarkdownExtensions = \"markdown_extensions\";\n\n json::Object config;\n\n \/\/ detect project type(s)\n bool isBlogdownProject = rmarkdown::isSiteProject(\"blogdown_site\");\n bool isHugoProject = isBlogdownProject;\n\n \/\/ if it's not a blogdown project, see if it's a hugo project. note that\n \/\/ we don't want to run hugo if we don't need to (startup time impacting\n \/\/ IDE startup time), so we gate the check by looking for a few sentinel\n \/\/ files + the presence of hugo on the system\n if (!isHugoProject)\n {\n if (projects::projectContext().hasProject())\n {\n FilePath hugoRoot = hugoRootPath();\n if (hugoRoot.completeChildPath(\"config.toml\").exists() ||\n hugoRoot.completeChildPath(\"config.yaml\").exists() ||\n hugoRoot.completeChildPath(\"config.json\").exists() ||\n hugoRoot.completeChildPath(\"config\").exists())\n {\n if (!module_context::findProgram(\"hugo\").isEmpty())\n {\n if (runHugo(\"config\", false).size() > 0)\n isHugoProject = true;\n }\n }\n }\n }\n\n \/\/ set into config\n config[kIsBlogdownProject] = isBlogdownProject;\n config[kIsHugoProject] = isHugoProject;\n\n if (isBlogdownProject || isHugoProject)\n {\n \/\/ get the site dir\n config[kSiteDir] = module_context::createFileSystemItem(hugoRootPath());\n\n \/\/ set the default static dirs\n json::Array staticDirs;\n staticDirs.push_back(\"static\");\n config[kStaticDirs] = staticDirs;\n\n \/\/ get the hugo version and use it to determine the default markdown engine\n std::string defaultMarkdownEngine = kMarkdownEngineGoldmark;\n std::string version = runHugo(\"version\");\n if (version.size() > 0)\n {\n boost::regex verRegex(\"(\\\\d+)\\\\.(\\\\d+)(?:.(\\\\d+))?\");\n boost::smatch match;\n if (regex_utils::search(version, match, verRegex))\n {\n int major = safe_convert::stringTo(match[1], 0);\n int minor = safe_convert::stringTo(match[2], 0);\n if (major <= 0 && minor < 60)\n defaultMarkdownEngine = kMarkdownEngineBlackfriday;\n }\n }\n\n \/\/ set defaults to start with\n std::string markdownEngine = defaultMarkdownEngine;\n std::string markdownExtensions = \"\";\n\n \/\/ get the hugo config\n std::string hugoConfig = runHugo(\"config\");\n\n \/\/ create map of variables\n if (hugoConfig.size() > 0)\n {\n std::map variables;\n boost::regex var(\"^([A-Za-z0-9_]+\\\\s*=\\\\s*[^\\n]+)$\");\n boost::sregex_token_iterator it(hugoConfig.begin(), hugoConfig.end(), var, 0);\n boost::sregex_token_iterator end;\n while (it != end)\n {\n core::system::Option var;\n if (core::system::parseEnvVar(*it, &var))\n {\n boost::algorithm::trim(var.first);\n boost::algorithm::trim(var.second);\n variables.insert(var);\n }\n it++;\n }\n\n \/\/ see if there is an enableEmoji variable\n const std::string enableEmoji = variables[\"enableemoji\"];\n if (enableEmoji == \"true\") {\n markdownExtensions += \"+emoji\";\n }\n\n \/\/ see if there is a markup variable\n const std::string markup = variables[\"markup\"];\n if (markup.size() > 0)\n {\n boost::regex handlerRegex(\"defaultmarkdownhandler\\\\:(\\\\w+)\");\n boost::smatch handlerMatch;\n if (regex_utils::search(markup, handlerMatch, handlerRegex))\n {\n \/\/ get the engine and set it if it's recognized (otherwise just behave as if\n \/\/ the default engine is configured)\n std::string matchedEngine = handlerMatch[1];\n if (matchedEngine == kMarkdownEngineBlackfriday || matchedEngine == kMarkdownEngineGoldmark)\n markdownEngine = matchedEngine;\n }\n\n \/\/ if we are goldmark check to see if unsafe is enabled. in that case\n \/\/ add the raw_html extension\n if (markdownEngine == kMarkdownEngineGoldmark)\n {\n boost::regex unsafeRegex(\"unsafe\\\\:true\");\n boost::smatch unsafeMatch;\n if (regex_utils::search(markup, unsafeMatch, unsafeRegex))\n markdownExtensions += \"+raw_html\";\n }\n }\n\n \/\/ see if there is a staticdir variable\n std::string staticdir = variables[\"staticdir\"];\n if (staticdir.size() > 0)\n {\n staticDirs.clear();\n\n staticdir = string_utils::strippedOfQuotes(staticdir);\n if (boost::algorithm::starts_with(staticdir, \"[\"))\n {\n boost::algorithm::replace_first(staticdir, \"[\", \"\");\n boost::algorithm::replace_last(staticdir, \"]\", \"\");\n std::vector dirs;\n boost::algorithm::split(dirs, staticdir, boost::algorithm::is_any_of(\" \"));\n staticDirs = core::json::toJsonArray(dirs);\n }\n else\n {\n staticDirs.push_back(staticdir);\n }\n config[kStaticDirs] = staticDirs;\n }\n }\n\n \/\/ populate config\n config[kMarkdownEngine] = markdownEngine;\n config[kMarkdownExtensions] = markdownExtensions;\n }\n else\n {\n config[kIsBlogdownProject] = false;\n }\n\n return config;\n}\n\n\n\n\n} \/\/ namespace blogdown\n} \/\/ namespace rmarkdown\n} \/\/ namespace modules\n} \/\/ namespace session\n} \/\/ namespace rstudio\n<|endoftext|>"} {"text":"\/*\n * Copyright 2008-2009 NVIDIA Corporation\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n\n\/*! \\file for_each.inl\n * \\brief Inline file for for_each.h.\n *\/\n\n#include \n#include \n#include \n\nnamespace thrust\n{\nnamespace detail\n{\nnamespace device\n{\nnamespace omp\n{\n\ntemplate\nvoid for_each(InputIterator first,\n InputIterator last,\n UnaryFunction f)\n{\n typedef typename thrust::iterator_difference::type difference;\n difference n = thrust::distance(first,last);\n\n#pragma omp parallel for\n for(difference i = 0;\n i < n;\n ++i)\n {\n InputIterator temp = first + i;\n f(dereference(temp));\n }\n} \n\n\n} \/\/ end namespace omp\n} \/\/ end namespace device\n} \/\/ end namespace detail\n} \/\/ end namespace thrust\n\nGuard omp's for_each implementation from non-existence of _OPENMP.\/*\n * Copyright 2008-2009 NVIDIA Corporation\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n\n\/*! \\file for_each.inl\n * \\brief Inline file for for_each.h.\n *\/\n\n\/\/ do not attempt to compile this code unless the compiler is generating multicore code\n\/\/ TODO: do this check inside omp::for_each with static_assert\n#ifdef _OPENMP\n\n#include \n#include \n#include \n\nnamespace thrust\n{\nnamespace detail\n{\nnamespace device\n{\nnamespace omp\n{\n\ntemplate\nvoid for_each(InputIterator first,\n InputIterator last,\n UnaryFunction f)\n{\n typedef typename thrust::iterator_difference::type difference;\n difference n = thrust::distance(first,last);\n\n#pragma omp parallel for\n for(difference i = 0;\n i < n;\n ++i)\n {\n InputIterator temp = first + i;\n f(dereference(temp));\n }\n} \n\n\n} \/\/ end namespace omp\n} \/\/ end namespace device\n} \/\/ end namespace detail\n} \/\/ end namespace thrust\n\n#endif \/\/ _OPENMP\n\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n\n#include \"util.h\"\n#include \"com_tightdb_Group.h\"\n\nusing namespace tightdb;\n\nJNIEXPORT jlong JNICALL Java_com_tightdb_Group_createNative__(\n\tJNIEnv* env, jobject jGroup)\n{\t\n\treturn reinterpret_cast(new Group());\n}\n\n\/* !!! TODO:\n Update interface :\n\nenum GroupMode {\n GROUP_DEFAULT = 0,\n GROUP_READONLY = 1,\n GROUP_SHARED = 2,\n GROUP_APPEND = 4,\n GROUP_ASYNC = 8,\n GROUP_SWAPONLY = 16\n};\n*\/\n\nJNIEXPORT jlong JNICALL Java_com_tightdb_Group_createNative__Ljava_lang_String_2Z(\n\tJNIEnv* env, jobject jGroup, jstring jFileName, jboolean readOnly)\n{\t\n\tconst char* fileNameCharPtr = env->GetStringUTFChars(jFileName, NULL);\n\tif (fileNameCharPtr == NULL)\n\t\treturn NULL;\n\n\tGroup* pGroup = new Group(fileNameCharPtr, readOnly != 0 ? GROUP_READONLY : GROUP_DEFAULT);\n\tif (!pGroup->is_valid()) {\n\t\tdelete pGroup;\n\t\tThrowException(env, IllegalArgument, \"Group(): File is not a valid tightdb database\");\n\t\treturn NULL;\n\t}\n\treturn reinterpret_cast(pGroup);\n}\n\nJNIEXPORT jlong JNICALL Java_com_tightdb_Group_createNative___3B(\n\tJNIEnv* env, jobject jGroup, jbyteArray jData)\n{\t\n\tjbyte* jbytePtr = env->GetByteArrayElements(jData, NULL);\n\tif (jbytePtr == NULL) {\n\t\tThrowException(env, IllegalArgument, \"Unable to fetch the buffer\");\n\t\treturn NULL;\n\t}\n\tjlong byteArrayLength = env->GetArrayLength(jData); \/\/ CHECK, FIXME: Does this return a long?\n\tGroup* pGroup = new Group((const char*)jbytePtr, S(byteArrayLength));\n\tif (!pGroup->is_valid()) {\n\t delete pGroup;\n ThrowException(env, IllegalArgument, \"Data is not a valid tightdb database\");\n\t return NULL;\n\t}\n\treturn reinterpret_cast(pGroup);\n}\n\nJNIEXPORT jlong JNICALL Java_com_tightdb_Group_createNative__Ljava_nio_ByteBuffer_2(\n\tJNIEnv* env, jobject jTableBase, jobject jByteBuffer)\n{\t\n \/\/ !!! TODO: Check Buffer for NULL!!!\n\tGroup* pGroup = new Group(static_cast(env->GetDirectBufferAddress(jByteBuffer)), \n S(env->GetDirectBufferCapacity(jByteBuffer)));\n\tif (!(pGroup->is_valid())) {\n\t\tdelete pGroup;\n ThrowException(env, IllegalArgument, \"Data is not a valid tightdb database\");\n\t\treturn NULL;\n\t}\n\treturn reinterpret_cast(pGroup);\n}\n\nJNIEXPORT void JNICALL Java_com_tightdb_Group_nativeClose(\n\tJNIEnv* env, jobject jGroup, jlong nativeGroupPtr)\n{\t\n\tdelete G(nativeGroupPtr);\n}\n\nJNIEXPORT jboolean JNICALL Java_com_tightdb_Group_nativeIsValid(\n\tJNIEnv* env, jobject jGroup, jlong nativeGroupPtr)\n{\t\n\treturn G(nativeGroupPtr)->is_valid();\n}\n\nJNIEXPORT jlong JNICALL Java_com_tightdb_Group_nativeGetTableCount(\n\tJNIEnv *env, jobject jGroup, jlong nativeGroupPtr)\n{\t\n return static_cast( G(nativeGroupPtr)->get_table_count() ); \n}\n\nJNIEXPORT jboolean JNICALL Java_com_tightdb_Group_nativeHasTable(\n\tJNIEnv* env, jobject jGroup, jlong nativeGroupPtr, jstring jTableName)\n{\t\n\tconst char* tableNameCharPtr = env->GetStringUTFChars(jTableName, NULL);\n if (tableNameCharPtr) {\n\t bool result = G(nativeGroupPtr)->has_table(tableNameCharPtr);\n\t env->ReleaseStringUTFChars(jTableName, tableNameCharPtr);\n\t return result;\n }\n \/\/ (exception is thrown by GetStringUTFChars if it fails.)\n return NULL;\n}\n\nJNIEXPORT jstring JNICALL Java_com_tightdb_Group_nativeGetTableName(\n\tJNIEnv* env, jobject jGroup, jlong nativeGroupPtr, jint index)\n{\t\n\tconst char* nameCharPtr = G(nativeGroupPtr)->get_table_name(index);\n\treturn env->NewStringUTF(nameCharPtr);\n}\n\nJNIEXPORT jlong JNICALL Java_com_tightdb_Group_nativeGetTableNativePtr(\n\tJNIEnv *env, jobject jGroup, jlong nativeGroupPtr, jstring name)\n{\t\n\tconst char* tableNameCharPtr = env->GetStringUTFChars(name, NULL);\n if (tableNameCharPtr) {\n\t Table* pTable = LangBindHelper::get_table_ptr(G(nativeGroupPtr), tableNameCharPtr); \n\t env->ReleaseStringUTFChars(name, tableNameCharPtr);\n\t return (jlong)pTable;\n }\n \/\/ (exception is thrown by GetStringUTFChars if it fails.)\n return 0;\n}\n\nJNIEXPORT void JNICALL Java_com_tightdb_Group_nativeWriteToFile(\n\tJNIEnv* env, jobject jGroup, jlong nativeGroupPtr, jstring jFileName)\n{\t\n\tconst char* fileNameCharPtr = env->GetStringUTFChars(jFileName, NULL);\n\tif (fileNameCharPtr) {\t\n\t bool success = G(nativeGroupPtr)->write(fileNameCharPtr);\n if (!success)\n ThrowException(env, IOFailed, fileNameCharPtr);\n\t env->ReleaseStringUTFChars(jFileName, fileNameCharPtr);\n }\n \/\/ (exception is thrown by GetStringUTFChars if it fails.)\n}\n\nJNIEXPORT jbyteArray JNICALL Java_com_tightdb_Group_nativeWriteToMem(\n\tJNIEnv* env, jobject jGroup, jlong nativeGroupPtr)\n{\t\n\tsize_t len;\n\tchar* memValue = G(nativeGroupPtr)->write_to_mem(len);\n jbyteArray jByteArray;\n if (len <= MAX_JSIZE) {\n jsize jlen = static_cast(len);\n jByteArray = env->NewByteArray(jlen);\n\t env->SetByteArrayRegion(jByteArray, 0, jlen, (const jbyte*)memValue);\n } else {\n jByteArray = NULL;\n ThrowException(env, IndexOutOfBounds, \"Group too big to write.\");\n }\n free(memValue); \/\/ Data was copied to array - so we can free data.\n\treturn jByteArray;\n}\n\nJNIEXPORT jobject JNICALL Java_com_tightdb_Group_nativeWriteToByteBuffer(\n\tJNIEnv* env, jobject jGroup, jlong nativeGroupPtr)\n{\t\n\tsize_t len;\n\tchar* memValue = G(nativeGroupPtr)->write_to_mem(len);\n\tif (len <= MAX_JLONG) {\n return env->NewDirectByteBuffer(static_cast(memValue), static_cast(len));\n \/\/ Data is NOT copied in DirectByteBuffer - so we can't free it.\n } else {\n ThrowException(env, IndexOutOfBounds, \"Group too big to write.\");\n return NULL;\n }\n}\n\nJNIEXPORT jboolean JNICALL Java_com_tightdb_Group_nativeCommit(\n\tJNIEnv* env, jobject jGroup, jlong nativeGroupPtr)\n{\n\treturn G(nativeGroupPtr)->commit();\n}Better error check in Group()#include \n#include \n#include \n#include \n\n#include \"util.h\"\n#include \"com_tightdb_Group.h\"\n\nusing namespace tightdb;\n\nJNIEXPORT jlong JNICALL Java_com_tightdb_Group_createNative__(\n\tJNIEnv* env, jobject jGroup)\n{\t\n\treturn reinterpret_cast(new Group());\n}\n\n\/* !!! TODO:\n Update interface :\n\nenum GroupMode {\n GROUP_DEFAULT = 0,\n GROUP_READONLY = 1,\n GROUP_SHARED = 2,\n GROUP_APPEND = 4,\n GROUP_ASYNC = 8,\n GROUP_SWAPONLY = 16\n};\n*\/\n\nJNIEXPORT jlong JNICALL Java_com_tightdb_Group_createNative__Ljava_lang_String_2Z(\n\tJNIEnv* env, jobject jGroup, jstring jFileName, jboolean readOnly)\n{\t\n\tconst char* fileNameCharPtr = env->GetStringUTFChars(jFileName, NULL);\n\tif (fileNameCharPtr == NULL)\n\t\treturn NULL; \/\/ Exception is thrown by GetStringUTFChars()\n\n\tGroup* pGroup = new Group(fileNameCharPtr, readOnly != 0 ? GROUP_READONLY : GROUP_DEFAULT);\n\tif (!pGroup->is_valid()) {\n\t\tdelete pGroup;\n\t\tThrowException(env, IllegalArgument, \"Group(): File is not a valid tightdb database\");\n\t\treturn NULL;\n\t}\n\treturn reinterpret_cast(pGroup);\n}\n\nJNIEXPORT jlong JNICALL Java_com_tightdb_Group_createNative___3B(\n\tJNIEnv* env, jobject jGroup, jbyteArray jData)\n{\t\n\tjbyte* jbytePtr = env->GetByteArrayElements(jData, NULL);\n\tif (jbytePtr == NULL) {\n\t\tThrowException(env, IllegalArgument, \"Unable to fetch the buffer\");\n\t\treturn NULL;\n\t}\n\tjlong byteArrayLength = env->GetArrayLength(jData); \/\/ CHECK, FIXME: Does this return a long?\n\tGroup* pGroup = new Group((const char*)jbytePtr, S(byteArrayLength));\n\tif (!pGroup->is_valid()) {\n\t delete pGroup;\n ThrowException(env, IllegalArgument, \"Data is not a valid tightdb database\");\n\t return NULL;\n\t}\n\treturn reinterpret_cast(pGroup);\n}\n\nJNIEXPORT jlong JNICALL Java_com_tightdb_Group_createNative__Ljava_nio_ByteBuffer_2(\n\tJNIEnv* env, jobject jTableBase, jobject jByteBuffer)\n{\t\n BinaryData data;\n if (!GetBinaryData(env, jByteBuffer, data))\n return 0;\n \n\tGroup* pGroup = new Group(data.pointer, data.len);\n\tif (!(pGroup->is_valid())) {\n\t\tdelete pGroup;\n ThrowException(env, IllegalArgument, \"Data is not a valid tightdb database\");\n\t\treturn 0;\n\t}\n\treturn reinterpret_cast(pGroup);\n}\n\nJNIEXPORT void JNICALL Java_com_tightdb_Group_nativeClose(\n\tJNIEnv* env, jobject jGroup, jlong nativeGroupPtr)\n{\t\n\tdelete G(nativeGroupPtr);\n}\n\nJNIEXPORT jboolean JNICALL Java_com_tightdb_Group_nativeIsValid(\n\tJNIEnv* env, jobject jGroup, jlong nativeGroupPtr)\n{\t\n\treturn G(nativeGroupPtr)->is_valid();\n}\n\nJNIEXPORT jlong JNICALL Java_com_tightdb_Group_nativeGetTableCount(\n\tJNIEnv *env, jobject jGroup, jlong nativeGroupPtr)\n{\t\n return static_cast( G(nativeGroupPtr)->get_table_count() ); \n}\n\nJNIEXPORT jboolean JNICALL Java_com_tightdb_Group_nativeHasTable(\n\tJNIEnv* env, jobject jGroup, jlong nativeGroupPtr, jstring jTableName)\n{\t\n\tconst char* tableNameCharPtr = env->GetStringUTFChars(jTableName, NULL);\n if (tableNameCharPtr) {\n\t bool result = G(nativeGroupPtr)->has_table(tableNameCharPtr);\n\t env->ReleaseStringUTFChars(jTableName, tableNameCharPtr);\n\t return result;\n }\n \/\/ (exception is thrown by GetStringUTFChars if it fails.)\n return NULL;\n}\n\nJNIEXPORT jstring JNICALL Java_com_tightdb_Group_nativeGetTableName(\n\tJNIEnv* env, jobject jGroup, jlong nativeGroupPtr, jint index)\n{\t\n\tconst char* nameCharPtr = G(nativeGroupPtr)->get_table_name(index);\n\treturn env->NewStringUTF(nameCharPtr);\n}\n\nJNIEXPORT jlong JNICALL Java_com_tightdb_Group_nativeGetTableNativePtr(\n\tJNIEnv *env, jobject jGroup, jlong nativeGroupPtr, jstring name)\n{\t\n\tconst char* tableNameCharPtr = env->GetStringUTFChars(name, NULL);\n if (tableNameCharPtr) {\n\t Table* pTable = LangBindHelper::get_table_ptr(G(nativeGroupPtr), tableNameCharPtr); \n\t env->ReleaseStringUTFChars(name, tableNameCharPtr);\n\t return (jlong)pTable;\n }\n \/\/ (exception is thrown by GetStringUTFChars if it fails.)\n return 0;\n}\n\nJNIEXPORT void JNICALL Java_com_tightdb_Group_nativeWriteToFile(\n\tJNIEnv* env, jobject jGroup, jlong nativeGroupPtr, jstring jFileName)\n{\t\n\tconst char* fileNameCharPtr = env->GetStringUTFChars(jFileName, NULL);\n\tif (fileNameCharPtr) {\t\n\t bool success = G(nativeGroupPtr)->write(fileNameCharPtr);\n if (!success)\n ThrowException(env, IOFailed, fileNameCharPtr);\n\t env->ReleaseStringUTFChars(jFileName, fileNameCharPtr);\n }\n \/\/ (exception is thrown by GetStringUTFChars if it fails.)\n}\n\nJNIEXPORT jbyteArray JNICALL Java_com_tightdb_Group_nativeWriteToMem(\n\tJNIEnv* env, jobject jGroup, jlong nativeGroupPtr)\n{\t\n\tsize_t len;\n\tchar* memValue = G(nativeGroupPtr)->write_to_mem(len);\n jbyteArray jByteArray;\n if (len <= MAX_JSIZE) {\n jsize jlen = static_cast(len);\n jByteArray = env->NewByteArray(jlen);\n\t env->SetByteArrayRegion(jByteArray, 0, jlen, (const jbyte*)memValue);\n } else {\n jByteArray = NULL;\n ThrowException(env, IndexOutOfBounds, \"Group too big to write.\");\n }\n free(memValue); \/\/ Data was copied to array - so we can free data.\n\treturn jByteArray;\n}\n\nJNIEXPORT jobject JNICALL Java_com_tightdb_Group_nativeWriteToByteBuffer(\n\tJNIEnv* env, jobject jGroup, jlong nativeGroupPtr)\n{\t\n\tsize_t len;\n\tchar* memValue = G(nativeGroupPtr)->write_to_mem(len);\n\tif (len <= MAX_JLONG) {\n return env->NewDirectByteBuffer(static_cast(memValue), static_cast(len));\n \/\/ Data is NOT copied in DirectByteBuffer - so we can't free it.\n } else {\n ThrowException(env, IndexOutOfBounds, \"Group too big to write.\");\n return NULL;\n }\n}\n\nJNIEXPORT jboolean JNICALL Java_com_tightdb_Group_nativeCommit(\n\tJNIEnv* env, jobject jGroup, jlong nativeGroupPtr)\n{\n\treturn G(nativeGroupPtr)->commit();\n}<|endoftext|>"} {"text":"\/******************************************************************************\n\n This source file is part of the tomviz project.\n\n Copyright Kitware, Inc.\n\n This source code is released under the New BSD License, (the \"License\").\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n\n******************************************************************************\/\n#include \"AddPythonTransformReaction.h\"\n\n#include \"ActiveObjects.h\"\n#include \"DataSource.h\"\n#include \"OperatorPython.h\"\n#include \"pqCoreUtilities.h\"\n#include \"EditPythonOperatorDialog.h\"\n\n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace tomviz\n{\n\/\/-----------------------------------------------------------------------------\nAddPythonTransformReaction::AddPythonTransformReaction(QAction* parentObject,\n const QString &l,\n const QString &s)\n : Superclass(parentObject), scriptLabel(l), scriptSource(s),\n interactive(false)\n{\n connect(&ActiveObjects::instance(), SIGNAL(dataSourceChanged(DataSource*)),\n SLOT(updateEnableState()));\n updateEnableState();\n}\n\n\/\/-----------------------------------------------------------------------------\nAddPythonTransformReaction::~AddPythonTransformReaction()\n{\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid AddPythonTransformReaction::updateEnableState()\n{\n parentAction()->setEnabled(\n ActiveObjects::instance().activeDataSource() != NULL);\n}\n\n\/\/-----------------------------------------------------------------------------\nOperatorPython* AddPythonTransformReaction::addExpression(DataSource* source)\n{\n source = source ? source : ActiveObjects::instance().activeDataSource();\n if (!source)\n {\n return NULL;\n }\n\n OperatorPython *opPython = new OperatorPython();\n QSharedPointer op(opPython);\n opPython->setLabel(scriptLabel);\n opPython->setScript(scriptSource);\n\n \/\/ Shift uniformly, crop, both have custom gui\n if (scriptLabel == \"Shift Uniformly\")\n {\n vtkTrivialProducer *t = vtkTrivialProducer::SafeDownCast(\n source->producer()->GetClientSideObject());\n vtkImageData *data = vtkImageData::SafeDownCast(t->GetOutputDataObject(0));\n int *extent = data->GetExtent();\n\n QDialog dialog(pqCoreUtilities::mainWidget());\n QHBoxLayout *layout = new QHBoxLayout;\n QLabel *label = new QLabel(\"Shift to apply:\");\n layout->addWidget(label);\n QSpinBox *spinx = new QSpinBox;\n spinx->setRange(-(extent[1]-extent[0]), extent[1]-extent[0]);\n spinx->setValue(0);\n QSpinBox *spiny = new QSpinBox;\n spiny->setRange(-(extent[3]-extent[2]), extent[3]-extent[2]);\n spiny->setValue(0);\n QSpinBox *spinz = new QSpinBox;\n spinz->setRange(-(extent[5]-extent[4]), extent[5]-extent[4]);\n spinz->setValue(0);\n layout->addWidget(spinx);\n layout->addWidget(spiny);\n layout->addWidget(spinz);\n QVBoxLayout *v = new QVBoxLayout;\n QDialogButtonBox *buttons = new QDialogButtonBox(QDialogButtonBox::Ok\n | QDialogButtonBox::Cancel);\n connect(buttons, SIGNAL(accepted()), &dialog, SLOT(accept()));\n connect(buttons, SIGNAL(rejected()), &dialog, SLOT(reject()));\n v->addLayout(layout);\n v->addWidget(buttons);\n dialog.setLayout(v);\n\n if (dialog.exec() == QDialog::Accepted)\n {\n QString shiftScript = scriptSource;\n shiftScript.replace(\"###SHIFT###\",\n QString(\"SHIFT = [%1, %2, %3]\").arg(spinx->value())\n .arg(spiny->value()).arg(spinz->value()));\n opPython->setScript(shiftScript);\n source->addOperator(op);\n }\n }\n else if (scriptLabel == \"Crop\")\n {\n vtkTrivialProducer *t = vtkTrivialProducer::SafeDownCast(\n source->producer()->GetClientSideObject());\n vtkImageData *data = vtkImageData::SafeDownCast(t->GetOutputDataObject(0));\n int *extent = data->GetExtent();\n\n QDialog dialog(pqCoreUtilities::mainWidget());\n QHBoxLayout *layout1 = new QHBoxLayout;\n QLabel *label = new QLabel(\"Crop data start:\");\n layout1->addWidget(label);\n QSpinBox *spinx = new QSpinBox;\n spinx->setRange(extent[0], extent[1]);\n spinx->setValue(extent[0]);\n QSpinBox *spiny = new QSpinBox;\n spiny->setRange(extent[2], extent[3]);\n spiny->setValue(extent[2]);\n QSpinBox *spinz = new QSpinBox;\n spinz->setRange(extent[4], extent[5]);\n spinz->setValue(extent[4]);\n layout1->addWidget(label);\n layout1->addWidget(spinx);\n layout1->addWidget(spiny);\n layout1->addWidget(spinz);\n QHBoxLayout *layout2 = new QHBoxLayout;\n label = new QLabel(\"Crop data end:\");\n layout2->addWidget(label);\n QSpinBox *spinxx = new QSpinBox;\n spinxx->setRange(extent[0], extent[1]);\n spinxx->setValue(extent[1]);\n QSpinBox *spinyy = new QSpinBox;\n spinyy->setRange(extent[2], extent[3]);\n spinyy->setValue(extent[3]);\n QSpinBox *spinzz = new QSpinBox;\n spinzz->setRange(extent[4], extent[5]);\n spinzz->setValue(extent[5]);\n layout2->addWidget(label);\n layout2->addWidget(spinxx);\n layout2->addWidget(spinyy);\n layout2->addWidget(spinzz);\n QVBoxLayout *v = new QVBoxLayout;\n QDialogButtonBox *buttons = new QDialogButtonBox(QDialogButtonBox::Ok\n | QDialogButtonBox::Cancel);\n connect(buttons, SIGNAL(accepted()), &dialog, SLOT(accept()));\n connect(buttons, SIGNAL(rejected()), &dialog, SLOT(reject()));\n v->addLayout(layout1);\n v->addLayout(layout2);\n v->addWidget(buttons);\n dialog.setLayout(v);\n\n if (dialog.exec() == QDialog::Accepted)\n {\n QString cropScript = scriptSource;\n cropScript.replace(\"###START_CROP###\",\n QString(\"START_CROP = [%1, %2, %3]\").arg(spinx->value())\n .arg(spiny->value()).arg(spinz->value()));\n cropScript.replace(\"###END_CROP###\",\n QString(\"END_CROP = [%1, %2, %3]\").arg(spinxx->value())\n .arg(spinyy->value()).arg(spinzz->value()));\n opPython->setScript(cropScript);\n source->addOperator(op);\n }\n }\n else if (scriptLabel == \"Rotate\")\n {\n QDialog dialog(pqCoreUtilities::mainWidget());\n QHBoxLayout *layout1 = new QHBoxLayout;\n QLabel *label = new QLabel(\"Rotate Angle:\");\n layout1->addWidget(label);\n QDoubleSpinBox *angle = new QDoubleSpinBox;\n angle->setRange(0, 360);\n angle->setValue(90);\n layout1->addWidget(label);\n layout1->addWidget(angle);\n QHBoxLayout *layout2 = new QHBoxLayout;\n label = new QLabel(\"Rotate Axis:\");\n layout2->addWidget(label);\n QSpinBox *axis = new QSpinBox;\n axis->setRange(0, 2);\n axis->setValue(2);\n layout2->addWidget(label);\n layout2->addWidget(axis);\n QVBoxLayout *v = new QVBoxLayout;\n QDialogButtonBox *buttons = new QDialogButtonBox(QDialogButtonBox::Ok\n | QDialogButtonBox::Cancel);\n connect(buttons, SIGNAL(accepted()), &dialog, SLOT(accept()));\n connect(buttons, SIGNAL(rejected()), &dialog, SLOT(reject()));\n v->addLayout(layout1);\n v->addLayout(layout2);\n v->addWidget(buttons);\n dialog.setLayout(v);\n \n if (dialog.exec() == QDialog::Accepted)\n {\n QString cropScript = scriptSource;\n cropScript.replace(\"###ROT_AXIS###\",\n QString(\"ROT_AXIS = %1\").arg(axis->value()) );\n cropScript.replace(\"###ROT_ANGLE###\",\n QString(\"ROT_ANGLE = %1\").arg(angle->value()) );\n opPython->setScript(cropScript);\n source->addOperator(op);\n }\n }\n else if (scriptLabel == \"Sobel Filter\") \/\/UI for Sobel Filter\n {\n QDialog dialog(pqCoreUtilities::mainWidget());\n QHBoxLayout *layout = new QHBoxLayout;\n QLabel *label = new QLabel(\"Axis:\");\n layout->addWidget(label);\n QSpinBox *axis = new QSpinBox;\n axis->setRange(0, 2);\n axis->setValue(0);\n layout->addWidget(label);\n layout->addWidget(axis);\n QVBoxLayout *v = new QVBoxLayout;\n QDialogButtonBox *buttons = new QDialogButtonBox(QDialogButtonBox::Ok\n | QDialogButtonBox::Cancel);\n connect(buttons, SIGNAL(accepted()), &dialog, SLOT(accept()));\n connect(buttons, SIGNAL(rejected()), &dialog, SLOT(reject()));\n v->addLayout(layout);\n v->addWidget(buttons);\n dialog.setLayout(v);\n \n if (dialog.exec() == QDialog::Accepted)\n {\n QString cropScript = scriptSource;\n cropScript.replace(\"###Filter_AXIS###\",\n QString(\"Filter_AXIS = %1\").arg(axis->value()) );\n opPython->setScript(cropScript);\n source->addOperator(op);\n }\n }\n else if (interactive)\n {\n \/\/ Create a non-modal dialog, delete it once it has been closed.\n EditPythonOperatorDialog *dialog =\n new EditPythonOperatorDialog(op, pqCoreUtilities::mainWidget());\n dialog->setAttribute(Qt::WA_DeleteOnClose, true);\n connect(dialog, SIGNAL(accepted()), SLOT(addOperator()));\n dialog->show();\n }\n else\n {\n source->addOperator(op);\n }\n return NULL;\n}\n\nvoid AddPythonTransformReaction::addOperator()\n{\n EditPythonOperatorDialog *dialog =\n qobject_cast(sender());\n if (!dialog)\n return;\n DataSource *source = ActiveObjects::instance().activeDataSource();\n if (!source)\n {\n return;\n }\n source->addOperator(dialog->op());\n}\n\n}\nChanged axis selection to a QComboBox\/******************************************************************************\n\n This source file is part of the tomviz project.\n\n Copyright Kitware, Inc.\n\n This source code is released under the New BSD License, (the \"License\").\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n\n******************************************************************************\/\n#include \"AddPythonTransformReaction.h\"\n\n#include \"ActiveObjects.h\"\n#include \"DataSource.h\"\n#include \"OperatorPython.h\"\n#include \"pqCoreUtilities.h\"\n#include \"EditPythonOperatorDialog.h\"\n\n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace tomviz\n{\n\/\/-----------------------------------------------------------------------------\nAddPythonTransformReaction::AddPythonTransformReaction(QAction* parentObject,\n const QString &l,\n const QString &s)\n : Superclass(parentObject), scriptLabel(l), scriptSource(s),\n interactive(false)\n{\n connect(&ActiveObjects::instance(), SIGNAL(dataSourceChanged(DataSource*)),\n SLOT(updateEnableState()));\n updateEnableState();\n}\n\n\/\/-----------------------------------------------------------------------------\nAddPythonTransformReaction::~AddPythonTransformReaction()\n{\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid AddPythonTransformReaction::updateEnableState()\n{\n parentAction()->setEnabled(\n ActiveObjects::instance().activeDataSource() != NULL);\n}\n\n\/\/-----------------------------------------------------------------------------\nOperatorPython* AddPythonTransformReaction::addExpression(DataSource* source)\n{\n source = source ? source : ActiveObjects::instance().activeDataSource();\n if (!source)\n {\n return NULL;\n }\n\n OperatorPython *opPython = new OperatorPython();\n QSharedPointer op(opPython);\n opPython->setLabel(scriptLabel);\n opPython->setScript(scriptSource);\n\n \/\/ Shift uniformly, crop, both have custom gui\n if (scriptLabel == \"Shift Uniformly\")\n {\n vtkTrivialProducer *t = vtkTrivialProducer::SafeDownCast(\n source->producer()->GetClientSideObject());\n vtkImageData *data = vtkImageData::SafeDownCast(t->GetOutputDataObject(0));\n int *extent = data->GetExtent();\n\n QDialog dialog(pqCoreUtilities::mainWidget());\n QHBoxLayout *layout = new QHBoxLayout;\n QLabel *label = new QLabel(\"Shift to apply:\");\n layout->addWidget(label);\n QSpinBox *spinx = new QSpinBox;\n spinx->setRange(-(extent[1]-extent[0]), extent[1]-extent[0]);\n spinx->setValue(0);\n QSpinBox *spiny = new QSpinBox;\n spiny->setRange(-(extent[3]-extent[2]), extent[3]-extent[2]);\n spiny->setValue(0);\n QSpinBox *spinz = new QSpinBox;\n spinz->setRange(-(extent[5]-extent[4]), extent[5]-extent[4]);\n spinz->setValue(0);\n layout->addWidget(spinx);\n layout->addWidget(spiny);\n layout->addWidget(spinz);\n QVBoxLayout *v = new QVBoxLayout;\n QDialogButtonBox *buttons = new QDialogButtonBox(QDialogButtonBox::Ok\n | QDialogButtonBox::Cancel);\n connect(buttons, SIGNAL(accepted()), &dialog, SLOT(accept()));\n connect(buttons, SIGNAL(rejected()), &dialog, SLOT(reject()));\n v->addLayout(layout);\n v->addWidget(buttons);\n dialog.setLayout(v);\n\n if (dialog.exec() == QDialog::Accepted)\n {\n QString shiftScript = scriptSource;\n shiftScript.replace(\"###SHIFT###\",\n QString(\"SHIFT = [%1, %2, %3]\").arg(spinx->value())\n .arg(spiny->value()).arg(spinz->value()));\n opPython->setScript(shiftScript);\n source->addOperator(op);\n }\n }\n else if (scriptLabel == \"Crop\")\n {\n vtkTrivialProducer *t = vtkTrivialProducer::SafeDownCast(\n source->producer()->GetClientSideObject());\n vtkImageData *data = vtkImageData::SafeDownCast(t->GetOutputDataObject(0));\n int *extent = data->GetExtent();\n\n QDialog dialog(pqCoreUtilities::mainWidget());\n QHBoxLayout *layout1 = new QHBoxLayout;\n QLabel *label = new QLabel(\"Crop data start:\");\n layout1->addWidget(label);\n QSpinBox *spinx = new QSpinBox;\n spinx->setRange(extent[0], extent[1]);\n spinx->setValue(extent[0]);\n QSpinBox *spiny = new QSpinBox;\n spiny->setRange(extent[2], extent[3]);\n spiny->setValue(extent[2]);\n QSpinBox *spinz = new QSpinBox;\n spinz->setRange(extent[4], extent[5]);\n spinz->setValue(extent[4]);\n layout1->addWidget(label);\n layout1->addWidget(spinx);\n layout1->addWidget(spiny);\n layout1->addWidget(spinz);\n QHBoxLayout *layout2 = new QHBoxLayout;\n label = new QLabel(\"Crop data end:\");\n layout2->addWidget(label);\n QSpinBox *spinxx = new QSpinBox;\n spinxx->setRange(extent[0], extent[1]);\n spinxx->setValue(extent[1]);\n QSpinBox *spinyy = new QSpinBox;\n spinyy->setRange(extent[2], extent[3]);\n spinyy->setValue(extent[3]);\n QSpinBox *spinzz = new QSpinBox;\n spinzz->setRange(extent[4], extent[5]);\n spinzz->setValue(extent[5]);\n layout2->addWidget(label);\n layout2->addWidget(spinxx);\n layout2->addWidget(spinyy);\n layout2->addWidget(spinzz);\n QVBoxLayout *v = new QVBoxLayout;\n QDialogButtonBox *buttons = new QDialogButtonBox(QDialogButtonBox::Ok\n | QDialogButtonBox::Cancel);\n connect(buttons, SIGNAL(accepted()), &dialog, SLOT(accept()));\n connect(buttons, SIGNAL(rejected()), &dialog, SLOT(reject()));\n v->addLayout(layout1);\n v->addLayout(layout2);\n v->addWidget(buttons);\n dialog.setLayout(v);\n\n if (dialog.exec() == QDialog::Accepted)\n {\n QString cropScript = scriptSource;\n cropScript.replace(\"###START_CROP###\",\n QString(\"START_CROP = [%1, %2, %3]\").arg(spinx->value())\n .arg(spiny->value()).arg(spinz->value()));\n cropScript.replace(\"###END_CROP###\",\n QString(\"END_CROP = [%1, %2, %3]\").arg(spinxx->value())\n .arg(spinyy->value()).arg(spinzz->value()));\n opPython->setScript(cropScript);\n source->addOperator(op);\n }\n }\n else if (scriptLabel == \"Rotate\")\n {\n QDialog dialog(pqCoreUtilities::mainWidget());\n QHBoxLayout *layout1 = new QHBoxLayout;\n QLabel *label = new QLabel(\"Rotate Angle:\");\n layout1->addWidget(label);\n QDoubleSpinBox *angle = new QDoubleSpinBox;\n angle->setRange(0, 360);\n angle->setValue(90);\n layout1->addWidget(label);\n layout1->addWidget(angle);\n QHBoxLayout *layout2 = new QHBoxLayout;\n label = new QLabel(\"Rotate Axis:\");\n layout2->addWidget(label);\n QComboBox *axis = new QComboBox(&dialog);\n axis->addItem(\"X\");\n axis->addItem(\"Y\");\n axis->addItem(\"Z\");\n axis->setCurrentIndex(2);\n layout2->addWidget(label);\n layout2->addWidget(axis);\n QVBoxLayout *v = new QVBoxLayout;\n QDialogButtonBox *buttons = new QDialogButtonBox(QDialogButtonBox::Ok\n | QDialogButtonBox::Cancel);\n connect(buttons, SIGNAL(accepted()), &dialog, SLOT(accept()));\n connect(buttons, SIGNAL(rejected()), &dialog, SLOT(reject()));\n v->addLayout(layout1);\n v->addLayout(layout2);\n v->addWidget(buttons);\n dialog.setLayout(v);\n \n if (dialog.exec() == QDialog::Accepted)\n {\n QString cropScript = scriptSource;\n cropScript.replace(\"###ROT_AXIS###\",\n QString(\"ROT_AXIS = %1\").arg(axis->currentIndex()) );\n cropScript.replace(\"###ROT_ANGLE###\",\n QString(\"ROT_ANGLE = %1\").arg(angle->value()) );\n opPython->setScript(cropScript);\n source->addOperator(op);\n }\n }\n else if (scriptLabel == \"Sobel Filter\") \/\/UI for Sobel Filter\n {\n QDialog dialog(pqCoreUtilities::mainWidget());\n QHBoxLayout *layout = new QHBoxLayout;\n QLabel *label = new QLabel(\"Axis:\");\n layout->addWidget(label);\n QComboBox *axis = new QComboBox(&dialog);\n axis->addItem(\"X\");\n axis->addItem(\"Y\");\n axis->addItem(\"Z\");\n axis->setCurrentIndex(2);\n layout->addWidget(label);\n layout->addWidget(axis);\n QVBoxLayout *v = new QVBoxLayout;\n QDialogButtonBox *buttons = new QDialogButtonBox(QDialogButtonBox::Ok\n | QDialogButtonBox::Cancel);\n connect(buttons, SIGNAL(accepted()), &dialog, SLOT(accept()));\n connect(buttons, SIGNAL(rejected()), &dialog, SLOT(reject()));\n v->addLayout(layout);\n v->addWidget(buttons);\n dialog.setLayout(v);\n \n if (dialog.exec() == QDialog::Accepted)\n {\n QString cropScript = scriptSource;\n cropScript.replace(\"###Filter_AXIS###\",\n QString(\"Filter_AXIS = %1\").arg(axis->currentIndex()) );\n opPython->setScript(cropScript);\n source->addOperator(op);\n }\n }\n else if (interactive)\n {\n \/\/ Create a non-modal dialog, delete it once it has been closed.\n EditPythonOperatorDialog *dialog =\n new EditPythonOperatorDialog(op, pqCoreUtilities::mainWidget());\n dialog->setAttribute(Qt::WA_DeleteOnClose, true);\n connect(dialog, SIGNAL(accepted()), SLOT(addOperator()));\n dialog->show();\n }\n else\n {\n source->addOperator(op);\n }\n return NULL;\n}\n\nvoid AddPythonTransformReaction::addOperator()\n{\n EditPythonOperatorDialog *dialog =\n qobject_cast(sender());\n if (!dialog)\n return;\n DataSource *source = ActiveObjects::instance().activeDataSource();\n if (!source)\n {\n return;\n }\n source->addOperator(dialog->op());\n}\n\n}\n<|endoftext|>"} {"text":"\/*\n * yosys -- Yosys Open SYnthesis Suite\n *\n * Copyright (C) 2012 Clifford Wolf \n * 2019 Nina Engelhardt \n *\n * Permission to use, copy, modify, and\/or distribute this software for any\n * purpose with or without fee is hereby granted, provided that the above\n * copyright notice and this permission notice appear in all copies.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n *\n *\/\n\n#include \"kernel\/register.h\"\n#include \"kernel\/rtlil.h\"\n#include \"kernel\/log.h\"\n\nUSING_YOSYS_NAMESPACE\nPRIVATE_NAMESPACE_BEGIN\n\nstruct ScratchpadPass : public Pass {\n\tScratchpadPass() : Pass(\"scratchpad\", \"get\/set values in the scratchpad\") { }\n\tvoid help() YS_OVERRIDE\n\t{\n\t\t\/\/ |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|\n\t\tlog(\"\\n\");\n\t\tlog(\" scratchpad [options]\\n\");\n\t\tlog(\"\\n\");\n\t\tlog(\"This pass allows to read and modify values from the scratchpad of the current\\n\");\n\t\tlog(\"design. Options:\\n\");\n\t\tlog(\"\\n\");\n\t\tlog(\" -get \\n\");\n\t\tlog(\" print the value saved in the scratchpad under the given identifier.\\n\");\n\t\tlog(\"\\n\");\n\t\tlog(\" -set \\n\");\n\t\tlog(\" save the given value in the scratchpad under the given identifier.\\n\");\n\t\tlog(\"\\n\");\n\t\tlog(\" -unset \\n\");\n\t\tlog(\" remove the entry for the given identifier from the scratchpad.\\n\");\n\t\tlog(\"\\n\");\n\t\tlog(\" -copy \\n\");\n\t\tlog(\" copy the value of the first identifier to the second identifier.\\n\");\n\t\tlog(\"\\n\");\n\t\tlog(\" -assert \\n\");\n\t\tlog(\" assert that the entry for the given identifier is set to the given value.\\n\");\n\t\tlog(\"\\n\");\n\t\tlog(\" -assert-set \\n\");\n\t\tlog(\" assert that the entry for the given identifier exists.\\n\");\n\t\tlog(\"\\n\");\n\t\tlog(\" -assert-unset \\n\");\n\t\tlog(\" assert that the entry for the given identifier does not exist.\\n\");\n\t\tlog(\"\\n\");\n\t\tlog(\"The identifier may not contain whitespace. By convention, it is usually prefixed\\n\");\n\t\tlog(\"by the name of the pass that uses it, e.g. 'opt.did_something'. If the value\\n\");\n\t\tlog(\"contains whitespace, it must be enclosed in double quotes.\\n\");\n\t\tlog(\"\\n\");\n\t}\n\n\tvoid execute(std::vector args, RTLIL::Design *design) YS_OVERRIDE\n\t{\n\t\tsize_t argidx;\n\t\tfor (argidx = 1; argidx < args.size(); argidx++)\n\t\t{\n\t\t\tif (args[argidx] == \"-get\" && argidx+1 < args.size()) {\n\t\t\t\tstring identifier = args[++argidx];\n\t\t\t\tif (design->scratchpad.count(identifier)){\n\t\t\t\t\tlog(\"%s\\n\", design->scratchpad_get_string(identifier).c_str());\n\t\t\t\t} else {\n\t\t\t\t\tlog(\"\\\"%s\\\" not set\\n\", identifier.c_str());\n\t\t\t\t}\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (args[argidx] == \"-set\" && argidx+2 < args.size()) {\n\t\t\t\tstring identifier = args[++argidx];\n\t\t\t\tstring value = args[++argidx];\n\t\t\t\tif (value.front() == '\\\"' && value.back() == '\\\"') value = value.substr(1, value.size() - 2);\n\t\t\t\tdesign->scratchpad_set_string(identifier, value);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (args[argidx] == \"-unset\" && argidx+1 < args.size()) {\n\t\t\t\tstring identifier = args[++argidx];\n\t\t\t\tdesign->scratchpad_unset(identifier);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (args[argidx] == \"-copy\" && argidx+2 < args.size()) {\n\t\t\t\tstring identifier_from = args[++argidx];\n\t\t\t\tstring identifier_to = args[++argidx];\n\t\t\t\tif (design->scratchpad.count(identifier_from) == 0) log_error(\"\\\"%s\\\" not set\\n\", identifier_from.c_str());\n\t\t\t\tstring value = design->scratchpad_get_string(identifier_from);\n\t\t\t\tdesign->scratchpad_set_string(identifier_to, value);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (args[argidx] == \"-assert\" && argidx+2 < args.size()) {\n\t\t\t\tstring identifier = args[++argidx];\n\t\t\t\tstring expected = args[++argidx];\n\t\t\t\tif (expected.front() == '\\\"' && expected.back() == '\\\"') expected = expected.substr(1, expected.size() - 2);\n\t\t\t\tif (design->scratchpad.count(identifier) == 0)\n\t\t\t\t\tlog_error(\"Assertion failed: scratchpad entry '%s' is not defined\\n\", identifier.c_str());\n\t\t\t\tstring value = design->scratchpad_get_string(identifier);\n\t\t\t\tif (value != expected) {\n\t\t\t\t\tlog_error(\"Assertion failed: scratchpad entry '%s' is set to '%s' instead of the asserted '%s'\\n\",\n\t\t\t\t\t identifier.c_str(), value.c_str(), expected.c_str());\n\t\t\t\t}\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (args[argidx] == \"-assert-set\" && argidx+1 < args.size()) {\n\t\t\t\tstring identifier = args[++argidx];\n\t\t\t\tif (design->scratchpad.count(identifier) == 0)\n\t\t\t\t\tlog_error(\"Assertion failed: scratchpad entry '%s' is not defined\\n\", identifier.c_str());\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (args[argidx] == \"-assert-unset\" && argidx+1 < args.size()) {\n\t\t\t\tstring identifier = args[++argidx];\n\t\t\t\tif (design->scratchpad.count(identifier) > 0)\n\t\t\t\t\tlog_error(\"Assertion failed: scratchpad entry '%s' is defined\\n\", identifier.c_str());\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tlog(\"Unrecognized argument: %s\\n\", args[argidx].c_str());\n\t\t\tbreak;\n\t\t}\n\t}\n} ScratchpadPass;\nPRIVATE_NAMESPACE_END\nuse extra_args\/*\n * yosys -- Yosys Open SYnthesis Suite\n *\n * Copyright (C) 2012 Clifford Wolf \n * 2019 Nina Engelhardt \n *\n * Permission to use, copy, modify, and\/or distribute this software for any\n * purpose with or without fee is hereby granted, provided that the above\n * copyright notice and this permission notice appear in all copies.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n *\n *\/\n\n#include \"kernel\/register.h\"\n#include \"kernel\/rtlil.h\"\n#include \"kernel\/log.h\"\n\nUSING_YOSYS_NAMESPACE\nPRIVATE_NAMESPACE_BEGIN\n\nstruct ScratchpadPass : public Pass {\n\tScratchpadPass() : Pass(\"scratchpad\", \"get\/set values in the scratchpad\") { }\n\tvoid help() YS_OVERRIDE\n\t{\n\t\t\/\/ |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|\n\t\tlog(\"\\n\");\n\t\tlog(\" scratchpad [options]\\n\");\n\t\tlog(\"\\n\");\n\t\tlog(\"This pass allows to read and modify values from the scratchpad of the current\\n\");\n\t\tlog(\"design. Options:\\n\");\n\t\tlog(\"\\n\");\n\t\tlog(\" -get \\n\");\n\t\tlog(\" print the value saved in the scratchpad under the given identifier.\\n\");\n\t\tlog(\"\\n\");\n\t\tlog(\" -set \\n\");\n\t\tlog(\" save the given value in the scratchpad under the given identifier.\\n\");\n\t\tlog(\"\\n\");\n\t\tlog(\" -unset \\n\");\n\t\tlog(\" remove the entry for the given identifier from the scratchpad.\\n\");\n\t\tlog(\"\\n\");\n\t\tlog(\" -copy \\n\");\n\t\tlog(\" copy the value of the first identifier to the second identifier.\\n\");\n\t\tlog(\"\\n\");\n\t\tlog(\" -assert \\n\");\n\t\tlog(\" assert that the entry for the given identifier is set to the given value.\\n\");\n\t\tlog(\"\\n\");\n\t\tlog(\" -assert-set \\n\");\n\t\tlog(\" assert that the entry for the given identifier exists.\\n\");\n\t\tlog(\"\\n\");\n\t\tlog(\" -assert-unset \\n\");\n\t\tlog(\" assert that the entry for the given identifier does not exist.\\n\");\n\t\tlog(\"\\n\");\n\t\tlog(\"The identifier may not contain whitespace. By convention, it is usually prefixed\\n\");\n\t\tlog(\"by the name of the pass that uses it, e.g. 'opt.did_something'. If the value\\n\");\n\t\tlog(\"contains whitespace, it must be enclosed in double quotes.\\n\");\n\t\tlog(\"\\n\");\n\t}\n\n\tvoid execute(std::vector args, RTLIL::Design *design) YS_OVERRIDE\n\t{\n\t\tsize_t argidx;\n\t\tfor (argidx = 1; argidx < args.size(); argidx++)\n\t\t{\n\t\t\tif (args[argidx] == \"-get\" && argidx+1 < args.size()) {\n\t\t\t\tstring identifier = args[++argidx];\n\t\t\t\tif (design->scratchpad.count(identifier)){\n\t\t\t\t\tlog(\"%s\\n\", design->scratchpad_get_string(identifier).c_str());\n\t\t\t\t} else {\n\t\t\t\t\tlog(\"\\\"%s\\\" not set\\n\", identifier.c_str());\n\t\t\t\t}\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (args[argidx] == \"-set\" && argidx+2 < args.size()) {\n\t\t\t\tstring identifier = args[++argidx];\n\t\t\t\tstring value = args[++argidx];\n\t\t\t\tif (value.front() == '\\\"' && value.back() == '\\\"') value = value.substr(1, value.size() - 2);\n\t\t\t\tdesign->scratchpad_set_string(identifier, value);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (args[argidx] == \"-unset\" && argidx+1 < args.size()) {\n\t\t\t\tstring identifier = args[++argidx];\n\t\t\t\tdesign->scratchpad_unset(identifier);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (args[argidx] == \"-copy\" && argidx+2 < args.size()) {\n\t\t\t\tstring identifier_from = args[++argidx];\n\t\t\t\tstring identifier_to = args[++argidx];\n\t\t\t\tif (design->scratchpad.count(identifier_from) == 0) log_error(\"\\\"%s\\\" not set\\n\", identifier_from.c_str());\n\t\t\t\tstring value = design->scratchpad_get_string(identifier_from);\n\t\t\t\tdesign->scratchpad_set_string(identifier_to, value);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (args[argidx] == \"-assert\" && argidx+2 < args.size()) {\n\t\t\t\tstring identifier = args[++argidx];\n\t\t\t\tstring expected = args[++argidx];\n\t\t\t\tif (expected.front() == '\\\"' && expected.back() == '\\\"') expected = expected.substr(1, expected.size() - 2);\n\t\t\t\tif (design->scratchpad.count(identifier) == 0)\n\t\t\t\t\tlog_error(\"Assertion failed: scratchpad entry '%s' is not defined\\n\", identifier.c_str());\n\t\t\t\tstring value = design->scratchpad_get_string(identifier);\n\t\t\t\tif (value != expected) {\n\t\t\t\t\tlog_error(\"Assertion failed: scratchpad entry '%s' is set to '%s' instead of the asserted '%s'\\n\",\n\t\t\t\t\t identifier.c_str(), value.c_str(), expected.c_str());\n\t\t\t\t}\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (args[argidx] == \"-assert-set\" && argidx+1 < args.size()) {\n\t\t\t\tstring identifier = args[++argidx];\n\t\t\t\tif (design->scratchpad.count(identifier) == 0)\n\t\t\t\t\tlog_error(\"Assertion failed: scratchpad entry '%s' is not defined\\n\", identifier.c_str());\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (args[argidx] == \"-assert-unset\" && argidx+1 < args.size()) {\n\t\t\t\tstring identifier = args[++argidx];\n\t\t\t\tif (design->scratchpad.count(identifier) > 0)\n\t\t\t\t\tlog_error(\"Assertion failed: scratchpad entry '%s' is defined\\n\", identifier.c_str());\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\textra_args(args, argidx, design, false);\n\t}\n} ScratchpadPass;\nPRIVATE_NAMESPACE_END\n<|endoftext|>"} {"text":"\/*\n * yosys -- Yosys Open SYnthesis Suite\n *\n * Copyright (C) 2012 Clifford Wolf \n *\n * Permission to use, copy, modify, and\/or distribute this software for any\n * purpose with or without fee is hereby granted, provided that the above\n * copyright notice and this permission notice appear in all copies.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n *\n *\/\n\n#include \"kernel\/yosys.h\"\n#include \"kernel\/sigtools.h\"\n\nUSING_YOSYS_NAMESPACE\nPRIVATE_NAMESPACE_BEGIN\n\nstruct Clk2fflogicPass : public Pass {\n\tClk2fflogicPass() : Pass(\"clk2fflogic\", \"convert clocked FFs to generic $ff cells\") { }\n\tvirtual void help()\n\t{\n\t\t\/\/ |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|\n\t\tlog(\"\\n\");\n\t\tlog(\" clk2fflogic [options] [selection]\\n\");\n\t\tlog(\"\\n\");\n\t\tlog(\"This command replaces clocked flip-flops with generic $ff cells that use the\\n\");\n\t\tlog(\"implicit global clock. This is useful for formal verification of designs with\\n\");\n\t\tlog(\"multiple clocks.\\n\");\n\t\tlog(\"\\n\");\n\t}\n\tvirtual void execute(std::vector args, RTLIL::Design *design)\n\t{\n\t\t\/\/ bool flag_noinit = false;\n\n\t\tlog_header(design, \"Executing CLK2FFLOGIC pass (convert clocked FFs to generic $ff cells).\\n\");\n\n\t\tsize_t argidx;\n\t\tfor (argidx = 1; argidx < args.size(); argidx++)\n\t\t{\n\t\t\t\/\/ if (args[argidx] == \"-noinit\") {\n\t\t\t\/\/ \tflag_noinit = true;\n\t\t\t\/\/ \tcontinue;\n\t\t\t\/\/ }\n\t\t\tbreak;\n\t\t}\n\t\textra_args(args, argidx, design);\n\n\t\tfor (auto module : design->selected_modules())\n\t\t{\n\t\t\tSigMap sigmap(module);\n\t\t\tdict initbits;\n\t\t\tpool del_initbits;\n\n\t\t\tfor (auto wire : module->wires())\n\t\t\t\tif (wire->attributes.count(\"\\\\init\") > 0)\n\t\t\t\t{\n\t\t\t\t\tConst initval = wire->attributes.at(\"\\\\init\");\n\t\t\t\t\tSigSpec initsig = sigmap(wire);\n\n\t\t\t\t\tfor (int i = 0; i < GetSize(initval) && i < GetSize(initsig); i++)\n\t\t\t\t\t\tif (initval[i] == State::S0 || initval[i] == State::S1)\n\t\t\t\t\t\t\tinitbits[initsig[i]] = initval[i];\n\t\t\t\t}\n\n\t\t\tfor (auto cell : vector(module->selected_cells()))\n\t\t\t{\n\t\t\t\tif (cell->type.in(\"$dff\", \"$adff\"))\n\t\t\t\t{\n\t\t\t\t\tbool clkpol = cell->parameters[\"\\\\CLK_POLARITY\"].as_bool();\n\n\t\t\t\t\tSigSpec clk = cell->getPort(\"\\\\CLK\");\n\t\t\t\t\tWire *past_clk = module->addWire(NEW_ID);\n\t\t\t\t\tpast_clk->attributes[\"\\\\init\"] = clkpol ? State::S1 : State::S0;\n\t\t\t\t\tmodule->addFf(NEW_ID, clk, past_clk);\n\n\t\t\t\t\tSigSpec sig_d = cell->getPort(\"\\\\D\");\n\t\t\t\t\tSigSpec sig_q = cell->getPort(\"\\\\Q\");\n\n\t\t\t\t\tlog(\"Replacing %s.%s (%s): CLK=%s, D=%s, Q=%s\\n\",\n\t\t\t\t\t\t\tlog_id(module), log_id(cell), log_id(cell->type),\n\t\t\t\t\t\t\tlog_signal(clk), log_signal(sig_d), log_signal(sig_q));\n\n\t\t\t\t\tSigSpec clock_edge_pattern;\n\n\t\t\t\t\tif (clkpol) {\n\t\t\t\t\t\tclock_edge_pattern.append_bit(State::S0);\n\t\t\t\t\t\tclock_edge_pattern.append_bit(State::S1);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tclock_edge_pattern.append_bit(State::S1);\n\t\t\t\t\t\tclock_edge_pattern.append_bit(State::S0);\n\t\t\t\t\t}\n\n\t\t\t\t\tSigSpec clock_edge = module->Eqx(NEW_ID, {clk, SigSpec(past_clk)}, clock_edge_pattern);\n\n\t\t\t\t\tWire *past_d = module->addWire(NEW_ID, GetSize(sig_d));\n\t\t\t\t\tWire *past_q = module->addWire(NEW_ID, GetSize(sig_q));\n\t\t\t\t\tmodule->addFf(NEW_ID, sig_d, past_d);\n\t\t\t\t\tmodule->addFf(NEW_ID, sig_q, past_q);\n\n\t\t\t\t\tif (cell->type == \"$adff\")\n\t\t\t\t\t{\n\t\t\t\t\t\tSigSpec arst = cell->getPort(\"\\\\ARST\");\n\t\t\t\t\t\tSigSpec qval = module->Mux(NEW_ID, past_q, past_d, clock_edge);\n\t\t\t\t\t\tConst rstval = cell->parameters[\"\\\\ARST_VALUE\"];\n\n\t\t\t\t\t\tif (cell->parameters[\"\\\\ARST_POLARITY\"].as_bool())\n\t\t\t\t\t\t\tmodule->addMux(NEW_ID, qval, rstval, arst, sig_q);\n\t\t\t\t\t\telse\n\t\t\t\t\t\t\tmodule->addMux(NEW_ID, rstval, qval, arst, sig_q);\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tmodule->addMux(NEW_ID, past_q, past_d, clock_edge, sig_q);\n\t\t\t\t\t}\n\n\t\t\t\t\tConst initval;\n\t\t\t\t\tbool assign_initval = false;\n\t\t\t\t\tfor (int i = 0; i < GetSize(sig_d); i++) {\n\t\t\t\t\t\tSigBit qbit = sigmap(sig_q[i]);\n\t\t\t\t\t\tif (initbits.count(qbit)) {\n\t\t\t\t\t\t\tinitval.bits.push_back(initbits.at(qbit));\n\t\t\t\t\t\t\tdel_initbits.insert(qbit);\n\t\t\t\t\t\t} else\n\t\t\t\t\t\t\tinitval.bits.push_back(State::Sx);\n\t\t\t\t\t\tif (initval.bits.back() != State::Sx)\n\t\t\t\t\t\t\tassign_initval = true;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (assign_initval) {\n\t\t\t\t\t\tpast_d->attributes[\"\\\\init\"] = initval;\n\t\t\t\t\t\tpast_q->attributes[\"\\\\init\"] = initval;\n\t\t\t\t\t}\n\n\t\t\t\t\tmodule->remove(cell);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tfor (auto wire : module->wires())\n\t\t\t\tif (wire->attributes.count(\"\\\\init\") > 0)\n\t\t\t\t{\n\t\t\t\t\tbool delete_initattr = true;\n\t\t\t\t\tConst initval = wire->attributes.at(\"\\\\init\");\n\t\t\t\t\tSigSpec initsig = sigmap(wire);\n\n\t\t\t\t\tfor (int i = 0; i < GetSize(initval) && i < GetSize(initsig); i++)\n\t\t\t\t\t\tif (del_initbits.count(initsig[i]) > 0)\n\t\t\t\t\t\t\tinitval[i] = State::Sx;\n\t\t\t\t\t\telse if (initval[i] != State::Sx)\n\t\t\t\t\t\t\tdelete_initattr = false;\n\n\t\t\t\t\tif (delete_initattr)\n\t\t\t\t\t\twire->attributes.erase(\"\\\\init\");\n\t\t\t\t\telse\n\t\t\t\t\t\twire->attributes.at(\"\\\\init\") = initval;\n\t\t\t\t}\n\t\t}\n\n\t}\n} Clk2fflogicPass;\n\nPRIVATE_NAMESPACE_END\nAdded clk2fflogic support for $dffsr and $dlatch\/*\n * yosys -- Yosys Open SYnthesis Suite\n *\n * Copyright (C) 2012 Clifford Wolf \n *\n * Permission to use, copy, modify, and\/or distribute this software for any\n * purpose with or without fee is hereby granted, provided that the above\n * copyright notice and this permission notice appear in all copies.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n *\n *\/\n\n#include \"kernel\/yosys.h\"\n#include \"kernel\/sigtools.h\"\n\nUSING_YOSYS_NAMESPACE\nPRIVATE_NAMESPACE_BEGIN\n\nstruct Clk2fflogicPass : public Pass {\n\tClk2fflogicPass() : Pass(\"clk2fflogic\", \"convert clocked FFs to generic $ff cells\") { }\n\tvirtual void help()\n\t{\n\t\t\/\/ |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|\n\t\tlog(\"\\n\");\n\t\tlog(\" clk2fflogic [options] [selection]\\n\");\n\t\tlog(\"\\n\");\n\t\tlog(\"This command replaces clocked flip-flops with generic $ff cells that use the\\n\");\n\t\tlog(\"implicit global clock. This is useful for formal verification of designs with\\n\");\n\t\tlog(\"multiple clocks.\\n\");\n\t\tlog(\"\\n\");\n\t}\n\tvirtual void execute(std::vector args, RTLIL::Design *design)\n\t{\n\t\t\/\/ bool flag_noinit = false;\n\n\t\tlog_header(design, \"Executing CLK2FFLOGIC pass (convert clocked FFs to generic $ff cells).\\n\");\n\n\t\tsize_t argidx;\n\t\tfor (argidx = 1; argidx < args.size(); argidx++)\n\t\t{\n\t\t\t\/\/ if (args[argidx] == \"-noinit\") {\n\t\t\t\/\/ \tflag_noinit = true;\n\t\t\t\/\/ \tcontinue;\n\t\t\t\/\/ }\n\t\t\tbreak;\n\t\t}\n\t\textra_args(args, argidx, design);\n\n\t\tfor (auto module : design->selected_modules())\n\t\t{\n\t\t\tSigMap sigmap(module);\n\t\t\tdict initbits;\n\t\t\tpool del_initbits;\n\n\t\t\tfor (auto wire : module->wires())\n\t\t\t\tif (wire->attributes.count(\"\\\\init\") > 0)\n\t\t\t\t{\n\t\t\t\t\tConst initval = wire->attributes.at(\"\\\\init\");\n\t\t\t\t\tSigSpec initsig = sigmap(wire);\n\n\t\t\t\t\tfor (int i = 0; i < GetSize(initval) && i < GetSize(initsig); i++)\n\t\t\t\t\t\tif (initval[i] == State::S0 || initval[i] == State::S1)\n\t\t\t\t\t\t\tinitbits[initsig[i]] = initval[i];\n\t\t\t\t}\n\n\t\t\tfor (auto cell : vector(module->selected_cells()))\n\t\t\t{\n\t\t\t\tif (cell->type.in(\"$dlatch\"))\n\t\t\t\t{\n\t\t\t\t\tbool enpol = cell->parameters[\"\\\\EN_POLARITY\"].as_bool();\n\n\t\t\t\t\tSigSpec sig_en = cell->getPort(\"\\\\EN\");\n\t\t\t\t\tSigSpec sig_d = cell->getPort(\"\\\\D\");\n\t\t\t\t\tSigSpec sig_q = cell->getPort(\"\\\\Q\");\n\n\t\t\t\t\tlog(\"Replacing %s.%s (%s): EN=%s, D=%s, Q=%s\\n\",\n\t\t\t\t\t\t\tlog_id(module), log_id(cell), log_id(cell->type),\n\t\t\t\t\t\t\tlog_signal(sig_en), log_signal(sig_d), log_signal(sig_q));\n\n\t\t\t\t\tWire *past_q = module->addWire(NEW_ID, GetSize(sig_q));\n\t\t\t\t\tmodule->addFf(NEW_ID, sig_q, past_q);\n\n\t\t\t\t\tif (enpol)\n\t\t\t\t\t\tmodule->addMux(NEW_ID, past_q, sig_d, sig_en, sig_q);\n\t\t\t\t\telse\n\t\t\t\t\t\tmodule->addMux(NEW_ID, sig_d, past_q, sig_en, sig_q);\n\n\t\t\t\t\tConst initval;\n\t\t\t\t\tbool assign_initval = false;\n\t\t\t\t\tfor (int i = 0; i < GetSize(sig_d); i++) {\n\t\t\t\t\t\tSigBit qbit = sigmap(sig_q[i]);\n\t\t\t\t\t\tif (initbits.count(qbit)) {\n\t\t\t\t\t\t\tinitval.bits.push_back(initbits.at(qbit));\n\t\t\t\t\t\t\tdel_initbits.insert(qbit);\n\t\t\t\t\t\t} else\n\t\t\t\t\t\t\tinitval.bits.push_back(State::Sx);\n\t\t\t\t\t\tif (initval.bits.back() != State::Sx)\n\t\t\t\t\t\t\tassign_initval = true;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (assign_initval)\n\t\t\t\t\t\tpast_q->attributes[\"\\\\init\"] = initval;\n\n\t\t\t\t\tmodule->remove(cell);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tif (cell->type.in(\"$dff\", \"$adff\", \"$dffsr\"))\n\t\t\t\t{\n\t\t\t\t\tbool clkpol = cell->parameters[\"\\\\CLK_POLARITY\"].as_bool();\n\n\t\t\t\t\tSigSpec clk = cell->getPort(\"\\\\CLK\");\n\t\t\t\t\tWire *past_clk = module->addWire(NEW_ID);\n\t\t\t\t\tpast_clk->attributes[\"\\\\init\"] = clkpol ? State::S1 : State::S0;\n\t\t\t\t\tmodule->addFf(NEW_ID, clk, past_clk);\n\n\t\t\t\t\tSigSpec sig_d = cell->getPort(\"\\\\D\");\n\t\t\t\t\tSigSpec sig_q = cell->getPort(\"\\\\Q\");\n\n\t\t\t\t\tlog(\"Replacing %s.%s (%s): CLK=%s, D=%s, Q=%s\\n\",\n\t\t\t\t\t\t\tlog_id(module), log_id(cell), log_id(cell->type),\n\t\t\t\t\t\t\tlog_signal(clk), log_signal(sig_d), log_signal(sig_q));\n\n\t\t\t\t\tSigSpec clock_edge_pattern;\n\n\t\t\t\t\tif (clkpol) {\n\t\t\t\t\t\tclock_edge_pattern.append_bit(State::S0);\n\t\t\t\t\t\tclock_edge_pattern.append_bit(State::S1);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tclock_edge_pattern.append_bit(State::S1);\n\t\t\t\t\t\tclock_edge_pattern.append_bit(State::S0);\n\t\t\t\t\t}\n\n\t\t\t\t\tSigSpec clock_edge = module->Eqx(NEW_ID, {clk, SigSpec(past_clk)}, clock_edge_pattern);\n\n\t\t\t\t\tWire *past_d = module->addWire(NEW_ID, GetSize(sig_d));\n\t\t\t\t\tWire *past_q = module->addWire(NEW_ID, GetSize(sig_q));\n\t\t\t\t\tmodule->addFf(NEW_ID, sig_d, past_d);\n\t\t\t\t\tmodule->addFf(NEW_ID, sig_q, past_q);\n\n\t\t\t\t\tif (cell->type == \"$adff\")\n\t\t\t\t\t{\n\t\t\t\t\t\tSigSpec arst = cell->getPort(\"\\\\ARST\");\n\t\t\t\t\t\tSigSpec qval = module->Mux(NEW_ID, past_q, past_d, clock_edge);\n\t\t\t\t\t\tConst rstval = cell->parameters[\"\\\\ARST_VALUE\"];\n\n\t\t\t\t\t\tif (cell->parameters[\"\\\\ARST_POLARITY\"].as_bool())\n\t\t\t\t\t\t\tmodule->addMux(NEW_ID, qval, rstval, arst, sig_q);\n\t\t\t\t\t\telse\n\t\t\t\t\t\t\tmodule->addMux(NEW_ID, rstval, qval, arst, sig_q);\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\tif (cell->type == \"$dffsr\")\n\t\t\t\t\t{\n\t\t\t\t\t\tSigSpec qval = module->Mux(NEW_ID, past_q, past_d, clock_edge);\n\t\t\t\t\t\tSigSpec setval = cell->getPort(\"\\\\SET\");\n\t\t\t\t\t\tSigSpec clrval = cell->getPort(\"\\\\CLR\");\n\n\t\t\t\t\t\tif (!cell->parameters[\"\\\\SET_POLARITY\"].as_bool())\n\t\t\t\t\t\t\tsetval = module->Not(NEW_ID, setval);\n\n\t\t\t\t\t\tif (cell->parameters[\"\\\\CLR_POLARITY\"].as_bool())\n\t\t\t\t\t\t\tclrval = module->Not(NEW_ID, clrval);\n\n\t\t\t\t\t\tqval = module->Or(NEW_ID, qval, setval);\n\t\t\t\t\t\tmodule->addAnd(NEW_ID, qval, clrval, sig_q);\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tmodule->addMux(NEW_ID, past_q, past_d, clock_edge, sig_q);\n\t\t\t\t\t}\n\n\t\t\t\t\tConst initval;\n\t\t\t\t\tbool assign_initval = false;\n\t\t\t\t\tfor (int i = 0; i < GetSize(sig_d); i++) {\n\t\t\t\t\t\tSigBit qbit = sigmap(sig_q[i]);\n\t\t\t\t\t\tif (initbits.count(qbit)) {\n\t\t\t\t\t\t\tinitval.bits.push_back(initbits.at(qbit));\n\t\t\t\t\t\t\tdel_initbits.insert(qbit);\n\t\t\t\t\t\t} else\n\t\t\t\t\t\t\tinitval.bits.push_back(State::Sx);\n\t\t\t\t\t\tif (initval.bits.back() != State::Sx)\n\t\t\t\t\t\t\tassign_initval = true;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (assign_initval) {\n\t\t\t\t\t\tpast_d->attributes[\"\\\\init\"] = initval;\n\t\t\t\t\t\tpast_q->attributes[\"\\\\init\"] = initval;\n\t\t\t\t\t}\n\n\t\t\t\t\tmodule->remove(cell);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tfor (auto wire : module->wires())\n\t\t\t\tif (wire->attributes.count(\"\\\\init\") > 0)\n\t\t\t\t{\n\t\t\t\t\tbool delete_initattr = true;\n\t\t\t\t\tConst initval = wire->attributes.at(\"\\\\init\");\n\t\t\t\t\tSigSpec initsig = sigmap(wire);\n\n\t\t\t\t\tfor (int i = 0; i < GetSize(initval) && i < GetSize(initsig); i++)\n\t\t\t\t\t\tif (del_initbits.count(initsig[i]) > 0)\n\t\t\t\t\t\t\tinitval[i] = State::Sx;\n\t\t\t\t\t\telse if (initval[i] != State::Sx)\n\t\t\t\t\t\t\tdelete_initattr = false;\n\n\t\t\t\t\tif (delete_initattr)\n\t\t\t\t\t\twire->attributes.erase(\"\\\\init\");\n\t\t\t\t\telse\n\t\t\t\t\t\twire->attributes.at(\"\\\\init\") = initval;\n\t\t\t\t}\n\t\t}\n\n\t}\n} Clk2fflogicPass;\n\nPRIVATE_NAMESPACE_END\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * $RCSfile: macros.hxx,v $\n *\n * $Revision: 1.6 $\n *\n * last change: $Author: hr $ $Date: 2003-03-27 17:03:01 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef _TOOLKIT_HELPER_MACROS_HXX_\n#define _TOOLKIT_HELPER_MACROS_HXX_\n\n\/\/ -------------------------------------------------------------------------------------\n\n#define IMPL_XUNOTUNNEL( ClassName ) \\\nsal_Int64 ClassName::getSomething( const ::com::sun::star::uno::Sequence< sal_Int8 >& rIdentifier ) throw(::com::sun::star::uno::RuntimeException) \\\n{ \\\n if( ( rIdentifier.getLength() == 16 ) && ( 0 == rtl_compareMemory( ClassName::GetUnoTunnelId().getConstArray(), rIdentifier.getConstArray(), 16 ) ) ) \\\n { \\\n return (sal_Int64)this; \\\n } \\\n return 0; \\\n} \\\nconst ::com::sun::star::uno::Sequence< sal_Int8 >& ClassName::GetUnoTunnelId() throw() \\\n{ \\\n static ::com::sun::star::uno::Sequence< sal_Int8 > * pSeq = NULL; \\\n if( !pSeq ) \\\n { \\\n ::osl::Guard< ::osl::Mutex > aGuard( ::osl::Mutex::getGlobalMutex() ); \\\n if( !pSeq ) \\\n { \\\n static ::com::sun::star::uno::Sequence< sal_Int8 > aSeq( 16 ); \\\n rtl_createUuid( (sal_uInt8*)aSeq.getArray(), 0, sal_True ); \\\n pSeq = &aSeq; \\\n } \\\n } \\\n return *pSeq; \\\n} \\\nClassName* ClassName::GetImplementation( const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& rxIFace ) throw() \\\n{ \\\n ::com::sun::star::uno::Reference< ::com::sun::star::lang::XUnoTunnel > xUT( rxIFace, ::com::sun::star::uno::UNO_QUERY ); \\\n return xUT.is() ? (ClassName*)xUT->getSomething( ClassName::GetUnoTunnelId() ) : NULL; \\\n}\n\n#define IMPL_XUNOTUNNEL2( ClassName, BaseClass ) \\\nsal_Int64 ClassName::getSomething( const ::com::sun::star::uno::Sequence< sal_Int8 >& rIdentifier ) throw(::com::sun::star::uno::RuntimeException) \\\n{ \\\n if( ( rIdentifier.getLength() == 16 ) && ( 0 == rtl_compareMemory( ClassName::GetUnoTunnelId().getConstArray(), rIdentifier.getConstArray(), 16 ) ) ) \\\n { \\\n return (sal_Int64)this; \\\n } \\\n return BaseClass::getSomething( rIdentifier ); \\\n} \\\nconst ::com::sun::star::uno::Sequence< sal_Int8 >& ClassName::GetUnoTunnelId() throw() \\\n{ \\\n static ::com::sun::star::uno::Sequence< sal_Int8 > * pSeq = NULL; \\\n if( !pSeq ) \\\n { \\\n ::osl::Guard< ::osl::Mutex > aGuard( ::osl::Mutex::getGlobalMutex() ); \\\n if( !pSeq ) \\\n { \\\n static ::com::sun::star::uno::Sequence< sal_Int8 > aSeq( 16 ); \\\n rtl_createUuid( (sal_uInt8*)aSeq.getArray(), 0, sal_True ); \\\n pSeq = &aSeq; \\\n } \\\n } \\\n return *pSeq; \\\n} \\\nClassName* ClassName::GetImplementation( const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& rxIFace ) throw() \\\n{ \\\n ::com::sun::star::uno::Reference< ::com::sun::star::lang::XUnoTunnel > xUT( rxIFace, ::com::sun::star::uno::UNO_QUERY ); \\\n return xUT.is() ? (ClassName*)xUT->getSomething( ClassName::GetUnoTunnelId() ) : NULL; \\\n}\n\n\/\/ -------------------------------------------------------------------------------------\n\n#define IMPL_IMPLEMENTATION_ID( ClassName ) \\\n::com::sun::star::uno::Sequence< sal_Int8 > ClassName::getImplementationId() throw(::com::sun::star::uno::RuntimeException) \\\n{ \\\n static ::cppu::OImplementationId* pId = NULL; \\\n if( !pId ) \\\n { \\\n ::osl::Guard< ::osl::Mutex > aGuard( ::osl::Mutex::getGlobalMutex() ); \\\n if( ! pId ) \\\n { \\\n static ::cppu::OImplementationId id( sal_False ); \\\n pId = &id; \\\n } \\\n } \\\n return (*pId).getImplementationId(); \\\n}\n\n#define IMPL_XTYPEPROVIDER_START( ClassName ) \\\nIMPL_IMPLEMENTATION_ID( ClassName ) \\\n::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type > ClassName::getTypes() throw(::com::sun::star::uno::RuntimeException) \\\n{ \\\n static ::cppu::OTypeCollection* pCollection = NULL; \\\n if( !pCollection ) \\\n { \\\n ::osl::Guard< ::osl::Mutex > aGuard( ::osl::Mutex::getGlobalMutex() ); \\\n if( !pCollection ) \\\n { \\\n static ::cppu::OTypeCollection collection( \\\n getCppuType( ( ::com::sun::star::uno::Reference< ::com::sun::star::lang::XTypeProvider>* ) NULL ),\n\n\/\/ -------------------------------------------------------------------------------------\n\n#define IMPL_XTYPEPROVIDER_END \\\n ); \\\n pCollection = &collection; \\\n } \\\n } \\\n return (*pCollection).getTypes(); \\\n}\n\n\/\/ -------------------------------------------------------------------------------------\n\n#define DECL_LISTENERMULTIPLEXER_START( ClassName, InterfaceName ) \\\nclass ClassName : public ListenerMultiplexerBase, public InterfaceName \\\n{ \\\npublic: \\\n ClassName( ::cppu::OWeakObject& rSource ); \\\n ::com::sun::star::uno::Any SAL_CALL queryInterface( const ::com::sun::star::uno::Type & rType ) throw(::com::sun::star::uno::RuntimeException); \\\n void SAL_CALL acquire() throw() { ListenerMultiplexerBase::acquire(); } \\\n void SAL_CALL release() throw() { ListenerMultiplexerBase::release(); } \\\n void SAL_CALL disposing( const ::com::sun::star::lang::EventObject& Source ) throw(::com::sun::star::uno::RuntimeException);\n\n\/\/ -------------------------------------------------------------------------------------\n\n#define DECL_LISTENERMULTIPLEXER_END \\\n};\n\n\/\/ -------------------------------------------------------------------------------------\n\n#define IMPL_LISTENERMULTIPLEXER_BASEMETHODS( ClassName, InterfaceName ) \\\nClassName::ClassName( ::cppu::OWeakObject& rSource ) \\\n : ListenerMultiplexerBase( rSource ) \\\n{ \\\n} \\\n::com::sun::star::uno::Any ClassName::queryInterface( const ::com::sun::star::uno::Type & rType ) throw(::com::sun::star::uno::RuntimeException) \\\n{ \\\n ::com::sun::star::uno::Any aRet = ::cppu::queryInterface( rType, \\\n SAL_STATIC_CAST( ::com::sun::star::lang::XEventListener*, this ), \\\n SAL_STATIC_CAST( InterfaceName*, this ) ); \\\n return (aRet.hasValue() ? aRet : ListenerMultiplexerBase::queryInterface( rType )); \\\n} \\\nvoid ClassName::disposing( const ::com::sun::star::lang::EventObject& ) throw(::com::sun::star::uno::RuntimeException) \\\n{ \\\n}\n\n\/\/ -------------------------------------------------------------------------------------\n\n#define IMPL_LISTENERMULTIPLEXER_LISTENERMETHOD( ClassName, InterfaceName, MethodName, EventType ) \\\nvoid ClassName::MethodName( const EventType& e ) throw(::com::sun::star::uno::RuntimeException) \\\n{ \\\n EventType aMulti( e ); \\\n aMulti.Source = &GetContext(); \\\n ::cppu::OInterfaceIteratorHelper aIt( *this ); \\\n while( aIt.hasMoreElements() ) \\\n ((InterfaceName*)aIt.next())->MethodName( aMulti ); \\\n}\n\n\/\/ -------------------------------------------------------------------------------------\n\n#define DECLIMPL_SUPPORTS_SERVICE( ) \\\n sal_Bool SAL_CALL supportsService( const ::rtl::OUString& rServiceName ) throw(::com::sun::star::uno::RuntimeException) \\\n { \\\n ::com::sun::star::uno::Sequence< ::rtl::OUString > aServiceNames( getSupportedServiceNames() ); \\\n const ::rtl::OUString* pSupported = aServiceNames.getConstArray(); \\\n const ::rtl::OUString* pSupportedEnd = pSupported + aServiceNames.getLength(); \\\n for ( ; pSupported != pSupportedEnd; ++pSupported ) \\\n if ( *pSupported == rServiceName ) \\\n return sal_True; \\\n return sal_False; \\\n }\n\n\/\/ -------------------------------------------------------------------------------------\n\n#define DECLIMPL_SERVICEINFO_DERIVED( ImplName, BaseClass, ServiceName ) \\\n ::rtl::OUString SAL_CALL getImplementationName( ) throw(::com::sun::star::uno::RuntimeException) { return ::rtl::OUString::createFromAscii( \"stardiv.Toolkit.\" #ImplName ); } \\\n ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames() throw(::com::sun::star::uno::RuntimeException) \\\n { \\\n ::com::sun::star::uno::Sequence< ::rtl::OUString > aNames = BaseClass::getSupportedServiceNames( ); \\\n aNames.realloc( aNames.getLength() + 1 ); \\\n aNames[ aNames.getLength() - 1 ] = ::rtl::OUString::createFromAscii( ServiceName ); \\\n return aNames; \\\n } \\\n\n\/\/ -------------------------------------------------------------------------------------\n\n#define DECLIMPL_SERVICEINFO( ImplName, ServiceName ) \\\n ::rtl::OUString SAL_CALL getImplementationName( ) throw(::com::sun::star::uno::RuntimeException) { return ::rtl::OUString::createFromAscii( \"stardiv.Toolkit.\" #ImplName ); } \\\n ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames() throw(::com::sun::star::uno::RuntimeException) \\\n { \\\n ::com::sun::star::uno::Sequence< ::rtl::OUString > aNames( 1 ); \\\n aNames[ 0 ] = ::rtl::OUString::createFromAscii( ServiceName ); \\\n return aNames; \\\n } \\\n DECLIMPL_SUPPORTS_SERVICE( )\n\n\n\n\n\n\n#endif \/\/ _TOOLKIT_HELPER_MACROS_HXX_\n\nINTEGRATION: CWS dba17 (1.6.232); FILE MERGED 2004\/09\/08 13:34:20 fs 1.6.232.1: #i33728# care for DisposedExceptions while notifying listeners\/*************************************************************************\n *\n * $RCSfile: macros.hxx,v $\n *\n * $Revision: 1.7 $\n *\n * last change: $Author: pjunck $ $Date: 2004-10-22 11:35:50 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef _TOOLKIT_HELPER_MACROS_HXX_\n#define _TOOLKIT_HELPER_MACROS_HXX_\n\n\/\/ -------------------------------------------------------------------------------------\n\n#define IMPL_XUNOTUNNEL( ClassName ) \\\nsal_Int64 ClassName::getSomething( const ::com::sun::star::uno::Sequence< sal_Int8 >& rIdentifier ) throw(::com::sun::star::uno::RuntimeException) \\\n{ \\\n if( ( rIdentifier.getLength() == 16 ) && ( 0 == rtl_compareMemory( ClassName::GetUnoTunnelId().getConstArray(), rIdentifier.getConstArray(), 16 ) ) ) \\\n { \\\n return (sal_Int64)this; \\\n } \\\n return 0; \\\n} \\\nconst ::com::sun::star::uno::Sequence< sal_Int8 >& ClassName::GetUnoTunnelId() throw() \\\n{ \\\n static ::com::sun::star::uno::Sequence< sal_Int8 > * pSeq = NULL; \\\n if( !pSeq ) \\\n { \\\n ::osl::Guard< ::osl::Mutex > aGuard( ::osl::Mutex::getGlobalMutex() ); \\\n if( !pSeq ) \\\n { \\\n static ::com::sun::star::uno::Sequence< sal_Int8 > aSeq( 16 ); \\\n rtl_createUuid( (sal_uInt8*)aSeq.getArray(), 0, sal_True ); \\\n pSeq = &aSeq; \\\n } \\\n } \\\n return *pSeq; \\\n} \\\nClassName* ClassName::GetImplementation( const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& rxIFace ) throw() \\\n{ \\\n ::com::sun::star::uno::Reference< ::com::sun::star::lang::XUnoTunnel > xUT( rxIFace, ::com::sun::star::uno::UNO_QUERY ); \\\n return xUT.is() ? (ClassName*)xUT->getSomething( ClassName::GetUnoTunnelId() ) : NULL; \\\n}\n\n#define IMPL_XUNOTUNNEL2( ClassName, BaseClass ) \\\nsal_Int64 ClassName::getSomething( const ::com::sun::star::uno::Sequence< sal_Int8 >& rIdentifier ) throw(::com::sun::star::uno::RuntimeException) \\\n{ \\\n if( ( rIdentifier.getLength() == 16 ) && ( 0 == rtl_compareMemory( ClassName::GetUnoTunnelId().getConstArray(), rIdentifier.getConstArray(), 16 ) ) ) \\\n { \\\n return (sal_Int64)this; \\\n } \\\n return BaseClass::getSomething( rIdentifier ); \\\n} \\\nconst ::com::sun::star::uno::Sequence< sal_Int8 >& ClassName::GetUnoTunnelId() throw() \\\n{ \\\n static ::com::sun::star::uno::Sequence< sal_Int8 > * pSeq = NULL; \\\n if( !pSeq ) \\\n { \\\n ::osl::Guard< ::osl::Mutex > aGuard( ::osl::Mutex::getGlobalMutex() ); \\\n if( !pSeq ) \\\n { \\\n static ::com::sun::star::uno::Sequence< sal_Int8 > aSeq( 16 ); \\\n rtl_createUuid( (sal_uInt8*)aSeq.getArray(), 0, sal_True ); \\\n pSeq = &aSeq; \\\n } \\\n } \\\n return *pSeq; \\\n} \\\nClassName* ClassName::GetImplementation( const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& rxIFace ) throw() \\\n{ \\\n ::com::sun::star::uno::Reference< ::com::sun::star::lang::XUnoTunnel > xUT( rxIFace, ::com::sun::star::uno::UNO_QUERY ); \\\n return xUT.is() ? (ClassName*)xUT->getSomething( ClassName::GetUnoTunnelId() ) : NULL; \\\n}\n\n\/\/ -------------------------------------------------------------------------------------\n\n#define IMPL_IMPLEMENTATION_ID( ClassName ) \\\n::com::sun::star::uno::Sequence< sal_Int8 > ClassName::getImplementationId() throw(::com::sun::star::uno::RuntimeException) \\\n{ \\\n static ::cppu::OImplementationId* pId = NULL; \\\n if( !pId ) \\\n { \\\n ::osl::Guard< ::osl::Mutex > aGuard( ::osl::Mutex::getGlobalMutex() ); \\\n if( ! pId ) \\\n { \\\n static ::cppu::OImplementationId id( sal_False ); \\\n pId = &id; \\\n } \\\n } \\\n return (*pId).getImplementationId(); \\\n}\n\n#define IMPL_XTYPEPROVIDER_START( ClassName ) \\\nIMPL_IMPLEMENTATION_ID( ClassName ) \\\n::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type > ClassName::getTypes() throw(::com::sun::star::uno::RuntimeException) \\\n{ \\\n static ::cppu::OTypeCollection* pCollection = NULL; \\\n if( !pCollection ) \\\n { \\\n ::osl::Guard< ::osl::Mutex > aGuard( ::osl::Mutex::getGlobalMutex() ); \\\n if( !pCollection ) \\\n { \\\n static ::cppu::OTypeCollection collection( \\\n getCppuType( ( ::com::sun::star::uno::Reference< ::com::sun::star::lang::XTypeProvider>* ) NULL ),\n\n\/\/ -------------------------------------------------------------------------------------\n\n#define IMPL_XTYPEPROVIDER_END \\\n ); \\\n pCollection = &collection; \\\n } \\\n } \\\n return (*pCollection).getTypes(); \\\n}\n\n\/\/ -------------------------------------------------------------------------------------\n\n#define DECL_LISTENERMULTIPLEXER_START( ClassName, InterfaceName ) \\\nclass ClassName : public ListenerMultiplexerBase, public InterfaceName \\\n{ \\\npublic: \\\n ClassName( ::cppu::OWeakObject& rSource ); \\\n ::com::sun::star::uno::Any SAL_CALL queryInterface( const ::com::sun::star::uno::Type & rType ) throw(::com::sun::star::uno::RuntimeException); \\\n void SAL_CALL acquire() throw() { ListenerMultiplexerBase::acquire(); } \\\n void SAL_CALL release() throw() { ListenerMultiplexerBase::release(); } \\\n void SAL_CALL disposing( const ::com::sun::star::lang::EventObject& Source ) throw(::com::sun::star::uno::RuntimeException);\n\n\/\/ -------------------------------------------------------------------------------------\n\n#define DECL_LISTENERMULTIPLEXER_END \\\n};\n\n\/\/ -------------------------------------------------------------------------------------\n\n#define IMPL_LISTENERMULTIPLEXER_BASEMETHODS( ClassName, InterfaceName ) \\\nClassName::ClassName( ::cppu::OWeakObject& rSource ) \\\n : ListenerMultiplexerBase( rSource ) \\\n{ \\\n} \\\n::com::sun::star::uno::Any ClassName::queryInterface( const ::com::sun::star::uno::Type & rType ) throw(::com::sun::star::uno::RuntimeException) \\\n{ \\\n ::com::sun::star::uno::Any aRet = ::cppu::queryInterface( rType, \\\n SAL_STATIC_CAST( ::com::sun::star::lang::XEventListener*, this ), \\\n SAL_STATIC_CAST( InterfaceName*, this ) ); \\\n return (aRet.hasValue() ? aRet : ListenerMultiplexerBase::queryInterface( rType )); \\\n} \\\nvoid ClassName::disposing( const ::com::sun::star::lang::EventObject& ) throw(::com::sun::star::uno::RuntimeException) \\\n{ \\\n}\n\n\/\/ -------------------------------------------------------------------------------------\n\n#define IMPL_LISTENERMULTIPLEXER_LISTENERMETHOD( ClassName, InterfaceName, MethodName, EventType ) \\\nvoid ClassName::MethodName( const EventType& e ) throw(::com::sun::star::uno::RuntimeException) \\\n{ \\\n EventType aMulti( e ); \\\n aMulti.Source = &GetContext(); \\\n ::cppu::OInterfaceIteratorHelper aIt( *this ); \\\n while( aIt.hasMoreElements() ) \\\n { \\\n ::com::sun::star::uno::Reference< InterfaceName > xListener( \\\n static_cast< InterfaceName* >( aIt.next() ) ); \\\n try \\\n { \\\n xListener->MethodName( aMulti ); \\\n } \\\n catch( ::com::sun::star::lang::DisposedException e ) \\\n { \\\n OSL_ENSURE( e.Context.is(), \"caught DisposedException with empty Context field\" ); \\\n if ( e.Context == xListener || !e.Context.is() ) \\\n aIt.remove(); \\\n } \\\n } \\\n}\n\n\/\/ -------------------------------------------------------------------------------------\n\n#define DECLIMPL_SUPPORTS_SERVICE( ) \\\n sal_Bool SAL_CALL supportsService( const ::rtl::OUString& rServiceName ) throw(::com::sun::star::uno::RuntimeException) \\\n { \\\n ::com::sun::star::uno::Sequence< ::rtl::OUString > aServiceNames( getSupportedServiceNames() ); \\\n const ::rtl::OUString* pSupported = aServiceNames.getConstArray(); \\\n const ::rtl::OUString* pSupportedEnd = pSupported + aServiceNames.getLength(); \\\n for ( ; pSupported != pSupportedEnd; ++pSupported ) \\\n if ( *pSupported == rServiceName ) \\\n return sal_True; \\\n return sal_False; \\\n }\n\n\/\/ -------------------------------------------------------------------------------------\n\n#define DECLIMPL_SERVICEINFO_DERIVED( ImplName, BaseClass, ServiceName ) \\\n ::rtl::OUString SAL_CALL getImplementationName( ) throw(::com::sun::star::uno::RuntimeException) { return ::rtl::OUString::createFromAscii( \"stardiv.Toolkit.\" #ImplName ); } \\\n ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames() throw(::com::sun::star::uno::RuntimeException) \\\n { \\\n ::com::sun::star::uno::Sequence< ::rtl::OUString > aNames = BaseClass::getSupportedServiceNames( ); \\\n aNames.realloc( aNames.getLength() + 1 ); \\\n aNames[ aNames.getLength() - 1 ] = ::rtl::OUString::createFromAscii( ServiceName ); \\\n return aNames; \\\n } \\\n\n\/\/ -------------------------------------------------------------------------------------\n\n#define DECLIMPL_SERVICEINFO( ImplName, ServiceName ) \\\n ::rtl::OUString SAL_CALL getImplementationName( ) throw(::com::sun::star::uno::RuntimeException) { return ::rtl::OUString::createFromAscii( \"stardiv.Toolkit.\" #ImplName ); } \\\n ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames() throw(::com::sun::star::uno::RuntimeException) \\\n { \\\n ::com::sun::star::uno::Sequence< ::rtl::OUString > aNames( 1 ); \\\n aNames[ 0 ] = ::rtl::OUString::createFromAscii( ServiceName ); \\\n return aNames; \\\n } \\\n DECLIMPL_SUPPORTS_SERVICE( )\n\n\n\n\n\n\n#endif \/\/ _TOOLKIT_HELPER_MACROS_HXX_\n\n<|endoftext|>"} {"text":"\/*************************************************\/\n\/* class_drc_item.cpp - DRC_ITEM class functions *\/\n\/*************************************************\/\n#include \"fctsys.h\"\n#include \"common.h\"\n\n#include \"pcbnew.h\"\n\nwxString DRC_ITEM::GetErrorText() const\n{\n switch( m_ErrorCode )\n {\n\/\/ case DRCE_: not assigned yet\n \n case DRCE_UNCONNECTED_PADS:\n return wxString( _(\"Unconnected pads\") );\n case DRCE_TRACK_NEAR_THROUGH_HOLE:\n return wxString( _(\"Track near thru-hole\") ); \n case DRCE_TRACK_NEAR_PAD:\n return wxString( _(\"Track near pad\") );\n case DRCE_TRACK_NEAR_VIA:\n return wxString( _(\"Track near via\") );\n case DRCE_VIA_NEAR_VIA:\n return wxString( _(\"Via near via\") );\n case DRCE_VIA_NEAR_TRACK:\n return wxString( _(\"Via near track\") );\n case DRCE_TRACK_ENDS1:\n case DRCE_TRACK_ENDS2:\n case DRCE_TRACK_ENDS3:\n case DRCE_TRACK_ENDS4:\n case DRCE_ENDS_PROBLEM1: \n case DRCE_ENDS_PROBLEM2:\n case DRCE_ENDS_PROBLEM3:\n case DRCE_ENDS_PROBLEM4:\n case DRCE_ENDS_PROBLEM5:\n return wxString( _(\"Two track ends\") );\n case DRCE_TRACK_UNKNOWN1:\n return wxString( _(\"This looks bad\") ); \/\/\/< @todo check source code and change this comment\n case DRCE_TRACKS_CROSSING:\n return wxString( _(\"Tracks crossing\") );\n case DRCE_PAD_NEAR_PAD1:\n return wxString( _(\"Pad near pad\") );\n case DRCE_VIA_HOLE_BIGGER:\n return wxString( _(\"Via hole > diameter\"));\n \n default:\n return wxString( wxT(\"PROGRAM BUG, PLEASE LEAVE THE ROOM.\") );\n }\n}\n\n\nwxString DRC_ITEM::ShowCoord( const wxPoint& aPos )\n{\n wxString temp;\n wxString ret;\n\n ret << wxT(\"@(\") << valeur_param( aPos.x, temp ); \n ret << wxT(\",\") << valeur_param( aPos.y, temp );\n ret << wxT(\")\");\n\n return ret;\n}\n\ncopyright notice\/*\n * This program source code file is part of KICAD, a free EDA CAD application.\n *\n * Copyright (C) 2007 Dick Hollenbeck, dick@softplc.com\n * Copyright (C) 2007 Kicad Developers, see change_log.txt for contributors.\n *\n * This program is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU General Public License\n * as published by the Free Software Foundation; either version 2\n * of the License, or (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program; if not, you may find one here:\n * http:\/\/www.gnu.org\/licenses\/old-licenses\/gpl-2.0.html\n * or you may search the http:\/\/www.gnu.org website for the version 2 license,\n * or you may write to the Free Software Foundation, Inc.,\n * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA\n *\/\n\n \n\/*************************************************\/\n\/* class_drc_item.cpp - DRC_ITEM class functions *\/\n\/*************************************************\/\n#include \"fctsys.h\"\n#include \"common.h\"\n\n#include \"pcbnew.h\"\n\nwxString DRC_ITEM::GetErrorText() const\n{\n switch( m_ErrorCode )\n {\n case DRCE_UNCONNECTED_PADS:\n return wxString( _(\"Unconnected pads\") );\n case DRCE_TRACK_NEAR_THROUGH_HOLE:\n return wxString( _(\"Track near thru-hole\") ); \n case DRCE_TRACK_NEAR_PAD:\n return wxString( _(\"Track near pad\") );\n case DRCE_TRACK_NEAR_VIA:\n return wxString( _(\"Track near via\") );\n case DRCE_VIA_NEAR_VIA:\n return wxString( _(\"Via near via\") );\n case DRCE_VIA_NEAR_TRACK:\n return wxString( _(\"Via near track\") );\n case DRCE_TRACK_ENDS1:\n case DRCE_TRACK_ENDS2:\n case DRCE_TRACK_ENDS3:\n case DRCE_TRACK_ENDS4:\n case DRCE_ENDS_PROBLEM1: \n case DRCE_ENDS_PROBLEM2:\n case DRCE_ENDS_PROBLEM3:\n case DRCE_ENDS_PROBLEM4:\n case DRCE_ENDS_PROBLEM5:\n return wxString( _(\"Two track ends\") );\n case DRCE_TRACK_UNKNOWN1:\n return wxString( _(\"This looks bad\") ); \/\/\/< @todo check source code and change this comment\n case DRCE_TRACKS_CROSSING:\n return wxString( _(\"Tracks crossing\") );\n case DRCE_PAD_NEAR_PAD1:\n return wxString( _(\"Pad near pad\") );\n case DRCE_VIA_HOLE_BIGGER:\n return wxString( _(\"Via hole > diameter\"));\n \n default:\n return wxString( wxT(\"PROGRAM BUG, PLEASE LEAVE THE ROOM.\") );\n }\n}\n\n\nwxString DRC_ITEM::ShowCoord( const wxPoint& aPos )\n{\n wxString temp;\n wxString ret;\n\n ret << wxT(\"@(\") << valeur_param( aPos.x, temp ); \n ret << wxT(\",\") << valeur_param( aPos.y, temp );\n ret << wxT(\")\");\n\n return ret;\n}\n\n<|endoftext|>"} {"text":"#include \"MifareClassic.h\"\n#include \"Ndef.h\"\n#include \n\n#define BLOCK_SIZE 16\n\nNdefMessage readMifareClassic(Adafruit_NFCShield_I2C& nfc, uint8_t * uid, int uidLength)\n{\n uint8_t key[6] = { 0xD3, 0xF7, 0xD3, 0xF7, 0xD3, 0xF7 };\n int currentBlock = 4;\n int messageLength = 0;\n byte data[16];\n\n \/\/ read first block to get message length\n int success = nfc.mifareclassic_AuthenticateBlock(uid, uidLength, currentBlock, 0, key);\n if (success)\n {\n success = nfc.mifareclassic_ReadDataBlock(currentBlock, data);\n if (success)\n {\n messageLength = getNdefLength(data); \n }\n else\n {\n Serial.print(\"Error. Failed read block \");Serial.println(currentBlock); \n }\n }\n else\n {\n Serial.print(\"Error. Block Authentication failed for \");Serial.println(currentBlock);\n }\n\n \/\/ this should be nested in the message length loop\n int index = 0;\n int bufferSize = getBufferSize(messageLength);\n uint8_t buffer[bufferSize];\n\n Serial.print(\"Message Length \");Serial.println(messageLength);\n Serial.print(\"Buffer Size \");Serial.println(bufferSize);\n\n while (index < bufferSize)\n {\n \/\/ authenticate on every sector\n if (nfc.mifareclassic_IsFirstBlock(currentBlock))\n {\n success = nfc.mifareclassic_AuthenticateBlock(uid, uidLength, currentBlock, 0, key); \n if (!success)\n {\n Serial.print(\"Error. Block Authentication failed for \");Serial.println(currentBlock);\n }\n }\n\n \/\/ read the data\n success = nfc.mifareclassic_ReadDataBlock(currentBlock, &buffer[index]);\n if (success) \n {\n Serial.print(\"Read block \");Serial.println(currentBlock);\n \/\/ Serial.print(\"Block \");Serial.print(currentBlock);Serial.print(\" \");\n \/\/ nfc.PrintHexChar(&buffer[index], BLOCK_SIZE);\n } \n else \n {\n Serial.print(\"Read failed \");Serial.println(currentBlock);\n }\n\n index += BLOCK_SIZE; \n currentBlock++;\n\n \/\/ skip the trailer block\n if (nfc.mifareclassic_IsTrailerBlock(currentBlock))\n {\n Serial.print(\"Skipping block \");Serial.println(currentBlock);\n currentBlock++; \n }\n\n }\n\n \/\/ print out for debugging (this would be easier block by block)\n Serial.println(\"\\nRaw NDEF data\");\n uint8_t* buffer_ptr = &buffer[0]; \n int j = 0;\n for (j = 0; j < (bufferSize \/ BLOCK_SIZE); j++) \n {\n nfc.PrintHexChar(buffer_ptr, BLOCK_SIZE);\n buffer_ptr += BLOCK_SIZE;\n }\n Serial.println();\n\n nfc.PrintHex(&buffer[4], messageLength);\n\n NdefMessage ndefMessage = NdefMessage(&buffer[4], messageLength);\n return ndefMessage;\n}\n\nint getBufferSize(int messageLength)\n{ \n\n \/\/ TLV header is 4 bytes. TLV terminator is 1 byte.\n int bufferSize = messageLength + 5;\n\n \/\/ bufferSize needs to be a multiple of BLOCK_SIZE\n if (bufferSize % BLOCK_SIZE != 0)\n {\n bufferSize = ((messageLength \/ BLOCK_SIZE) + 1) * BLOCK_SIZE; \n }\n\n return bufferSize;\n}\n\n\/\/ get the ndef data length from the mifare TLV\n\/\/ assuming the type and the length are in the first 4 bytes\n\/\/ { 0x0, 0x0, 0x3, LENGTH }\n\/\/ { 0x3, 0xFF, LENGTH, LENGTH }\nint getNdefLength(byte *data)\n{\n int ndefLength;\n if (data[0] == 0x03 && data[1] == 0xFF) {\n \/\/ would rather find spec, but using \n \/\/ http:\/\/www.developer.nokia.com\/Community\/Discussion\/showthread.php?131601-Problem-decoding-NDEF-message-on-Mifare-Card&p=407235&viewfull=1#post407235\n ndefLength = ((0xFF & data[2]) << 8) | (0xFF & data[3]);\n } else if (data[2] == 0x03) { \/\/ 1 byte\n ndefLength = data[3];\n } else {\n Serial.println(\"ERROR: Do not know how to decode length.\");\n ndefLength = -1;\n }\n \n return ndefLength;\n}\n\n\/\/ TODO return success \/ failure\nvoid writeMifareClassic(Adafruit_NFCShield_I2C& nfc, NdefMessage& m, uint8_t * uid, int uidLength)\n{\n\n uint8_t encoded[m.getEncodedSize()];\n m.encode(encoded);\n \n uint8_t buffer[getBufferSize(sizeof(encoded))];\n memset(buffer, 0, sizeof(buffer));\n buffer[0] = 0x0; \n buffer[1] = 0x0; \n buffer[2] = 0x3; \n buffer[3] = sizeof(encoded);\n memcpy(&buffer[4], encoded, sizeof(encoded));\n buffer[4+sizeof(encoded)] = 0xFE; \/\/ terminator\n\n \/\/ Write to tag\n int index = 0;\n int currentBlock = 4;\n uint8_t key[6] = { 0xD3, 0xF7, 0xD3, 0xF7, 0xD3, 0xF7 }; \/\/ this is Sector 1 - 15 key\n\n while (index < sizeof(buffer))\n { \n\n if (nfc.mifareclassic_IsFirstBlock(currentBlock))\n {\n int success = nfc.mifareclassic_AuthenticateBlock(uid, uidLength, currentBlock, 0, key); \n if (!success)\n {\n Serial.print(\"Error. Block Authentication failed for \");Serial.println(currentBlock);\n while (1); \/\/ halt\n }\n }\n\n int write_success = nfc.mifareclassic_WriteDataBlock (currentBlock, &buffer[index]);\n if (write_success) \n {\n Serial.print(F(\"Wrote block \"));Serial.print(currentBlock);Serial.print(\" - \");\n nfc.PrintHexChar(&buffer[index], BLOCK_SIZE);\n } \n else \n {\n Serial.print(F(\"Write failed \"));Serial.println(currentBlock);\n while (1); \/\/ halt\n }\n index += BLOCK_SIZE; \n currentBlock++;\n\n if (nfc.mifareclassic_IsTrailerBlock(currentBlock))\n {\n \/\/ can't write to trailer block\n Serial.print(F(\"Skipping block \"));Serial.println(currentBlock);\n currentBlock++; \n }\n\n }\n }Fix buffer size calculation#include \"MifareClassic.h\"\n#include \"Ndef.h\"\n#include \n\n#define BLOCK_SIZE 16\n\nNdefMessage readMifareClassic(Adafruit_NFCShield_I2C& nfc, uint8_t * uid, int uidLength)\n{\n uint8_t key[6] = { 0xD3, 0xF7, 0xD3, 0xF7, 0xD3, 0xF7 };\n int currentBlock = 4;\n int messageLength = 0;\n byte data[16];\n\n \/\/ read first block to get message length\n int success = nfc.mifareclassic_AuthenticateBlock(uid, uidLength, currentBlock, 0, key);\n if (success)\n {\n success = nfc.mifareclassic_ReadDataBlock(currentBlock, data);\n if (success)\n {\n messageLength = getNdefLength(data); \n }\n else\n {\n Serial.print(\"Error. Failed read block \");Serial.println(currentBlock); \n }\n }\n else\n {\n Serial.print(\"Error. Block Authentication failed for \");Serial.println(currentBlock);\n }\n\n \/\/ this should be nested in the message length loop\n int index = 0;\n int bufferSize = getBufferSize(messageLength);\n uint8_t buffer[bufferSize];\n\n Serial.print(\"Message Length \");Serial.println(messageLength);\n Serial.print(\"Buffer Size \");Serial.println(bufferSize);\n\n while (index < bufferSize)\n {\n \/\/ authenticate on every sector\n if (nfc.mifareclassic_IsFirstBlock(currentBlock))\n {\n success = nfc.mifareclassic_AuthenticateBlock(uid, uidLength, currentBlock, 0, key); \n if (!success)\n {\n Serial.print(\"Error. Block Authentication failed for \");Serial.println(currentBlock);\n }\n }\n\n \/\/ read the data\n success = nfc.mifareclassic_ReadDataBlock(currentBlock, &buffer[index]);\n if (success) \n {\n Serial.print(\"Read block \");Serial.println(currentBlock);\n \/\/ Serial.print(\"Block \");Serial.print(currentBlock);Serial.print(\" \");\n \/\/ nfc.PrintHexChar(&buffer[index], BLOCK_SIZE);\n } \n else \n {\n Serial.print(\"Read failed \");Serial.println(currentBlock);\n }\n\n index += BLOCK_SIZE; \n currentBlock++;\n\n \/\/ skip the trailer block\n if (nfc.mifareclassic_IsTrailerBlock(currentBlock))\n {\n Serial.print(\"Skipping block \");Serial.println(currentBlock);\n currentBlock++; \n }\n\n }\n\n \/\/ print out for debugging (this would be easier block by block)\n Serial.println(\"\\nRaw NDEF data\");\n uint8_t* buffer_ptr = &buffer[0]; \n int j = 0;\n for (j = 0; j < (bufferSize \/ BLOCK_SIZE); j++) \n {\n nfc.PrintHexChar(buffer_ptr, BLOCK_SIZE);\n buffer_ptr += BLOCK_SIZE;\n }\n Serial.println();\n\n nfc.PrintHex(&buffer[4], messageLength);\n\n NdefMessage ndefMessage = NdefMessage(&buffer[4], messageLength);\n return ndefMessage;\n}\n\nint getBufferSize(int messageLength)\n{ \n\n \/\/ TLV header is 4 bytes. TLV terminator is 1 byte.\n int bufferSize = messageLength + 5;\n\n \/\/ bufferSize needs to be a multiple of BLOCK_SIZE\n if (bufferSize % BLOCK_SIZE != 0)\n {\n bufferSize = ((bufferSize \/ BLOCK_SIZE) + 1) * BLOCK_SIZE; \n }\n\n return bufferSize;\n}\n\n\/\/ get the ndef data length from the mifare TLV\n\/\/ assuming the type and the length are in the first 4 bytes\n\/\/ { 0x0, 0x0, 0x3, LENGTH }\n\/\/ { 0x3, 0xFF, LENGTH, LENGTH }\nint getNdefLength(byte *data)\n{\n int ndefLength;\n if (data[0] == 0x03 && data[1] == 0xFF) {\n \/\/ would rather find spec, but using \n \/\/ http:\/\/www.developer.nokia.com\/Community\/Discussion\/showthread.php?131601-Problem-decoding-NDEF-message-on-Mifare-Card&p=407235&viewfull=1#post407235\n ndefLength = ((0xFF & data[2]) << 8) | (0xFF & data[3]);\n } else if (data[2] == 0x03) { \/\/ 1 byte\n ndefLength = data[3];\n } else {\n Serial.println(\"ERROR: Do not know how to decode length.\");\n ndefLength = -1;\n }\n \n return ndefLength;\n}\n\n\/\/ TODO return success \/ failure\nvoid writeMifareClassic(Adafruit_NFCShield_I2C& nfc, NdefMessage& m, uint8_t * uid, int uidLength)\n{\n\n uint8_t encoded[m.getEncodedSize()];\n m.encode(encoded);\n \n uint8_t buffer[getBufferSize(sizeof(encoded))];\n memset(buffer, 0, sizeof(buffer));\n\n Serial.print(\"sizeof(encoded) \");Serial.println(sizeof(encoded));\n Serial.print(\"sizeof(buffer) \");Serial.println(sizeof(buffer));\n\n buffer[0] = 0x0; \n buffer[1] = 0x0; \n buffer[2] = 0x3; \n buffer[3] = sizeof(encoded);\n memcpy(&buffer[4], encoded, sizeof(encoded));\n buffer[4+sizeof(encoded)] = 0xFE; \/\/ terminator\n \n \/\/ Write to tag\n int index = 0;\n int currentBlock = 4;\n uint8_t key[6] = { 0xD3, 0xF7, 0xD3, 0xF7, 0xD3, 0xF7 }; \/\/ this is Sector 1 - 15 key\n\n while (index < sizeof(buffer))\n { \n\n if (nfc.mifareclassic_IsFirstBlock(currentBlock))\n {\n int success = nfc.mifareclassic_AuthenticateBlock(uid, uidLength, currentBlock, 0, key); \n if (!success)\n {\n Serial.print(\"Error. Block Authentication failed for \");Serial.println(currentBlock);\n while (1); \/\/ halt\n }\n }\n\n int write_success = nfc.mifareclassic_WriteDataBlock (currentBlock, &buffer[index]);\n if (write_success) \n {\n Serial.print(F(\"Wrote block \"));Serial.print(currentBlock);Serial.print(\" - \");\n nfc.PrintHexChar(&buffer[index], BLOCK_SIZE);\n } \n else \n {\n Serial.print(F(\"Write failed \"));Serial.println(currentBlock);\n while (1); \/\/ halt\n }\n index += BLOCK_SIZE; \n currentBlock++;\n\n if (nfc.mifareclassic_IsTrailerBlock(currentBlock))\n {\n \/\/ can't write to trailer block\n Serial.print(F(\"Skipping block \"));Serial.println(currentBlock);\n currentBlock++; \n }\n\n }\n }<|endoftext|>"} {"text":"#include \n#include \n#include \"Input.h\"\n#include \"ValType.h\"\n#include \n#include \n\/\/MR CHANGE\n#include \n\/\/MR CHANGE END\n\n\/\/ return a given key value (if it's in the map)\nValType phSolver::Input::GetValue(const string &str) const\n{\n if (input_map->find(str) != input_map->end()) {\n if ( (*input_map)[str] == \"NODEFAULT\" ) {\n stringstream ost;\n ost << \"required input variable not set: \" << str << ends;\n throw invalid_argument( ost.str() );\n }\n } else {\n stringstream ost;\n ost << \"required input variable not set: \" << str << ends;\n throw invalid_argument( ost.str() );\n }\n\n return ValType( (*input_map)[str] );\n}\n\nconst char* phSolver::Input::GetUserFileName() {\n return userConfFileName.c_str();\n}\n\nconst char* phSolver::Input::GetDefaultFileName() {\n return defaultConfFileName.c_str();\n}\n\nphSolver::Input::Input(const string &fname, const string &default_fname) \n : userConfFileName(fname), defaultConfFileName(default_fname)\n{\n \/\/ open the input file\n ifstream infile( fname.c_str(), ios::in);\n\n if(!infile || infile.eof()){\n cerr<<\" Input file does not exist or is empty or perhaps you forgot mpirun? \"<;\n input_map = new map;\n\n \/\/ get the lines of text from the input file\n get_input_lines(input_text, infile);\n build_map(input_map, input_text);\n\n \/\/ build and merge with default map ( if desired )\n if (!default_fname.empty()) {\n ifstream infile2( default_fname.c_str(), ios::in);\n\n map *default_map = new map;\n vector *default_text = new vector;\n\n get_input_lines(default_text, infile2);\n build_map(default_map, default_text);\n\n \/\/ merge the two maps\n map::const_iterator iter = default_map->begin();\n for ( ; iter != default_map->end(); ++iter ) {\n string defkey = iter->first;\n string defval = iter->second;\n if ( input_map->find(defkey) == input_map->end() ) {\n\t(*input_map)[defkey] = defval;\n }\n }\n infile2.close();\n\n delete default_map;\n delete default_text;\n \n } else {\n cerr << \"Input warning: no input.config file found.\" << endl;\n cerr << \"Get one from source directory.\" << endl;\n exit(-2);\n }\n\n infile.close();\n \n}\n \nphSolver::Input::~Input()\n{\n delete input_text;\n delete input_map;\n}\n\n\n\/\/ return the input map\nmap phSolver::Input::InputMap() const\n{\n return *input_map;\n}\n\n\/\/ echo the entire map\nvoid phSolver::Input::EchoInputMap(const ostream &ofile)\n{\n map::const_iterator iter = input_map->begin();\n for ( ; iter != input_map->end(); ++iter ) {\n cout << \"Keyphrase: \" << iter->first << endl \n\t << \"Keyvalue: \" << iter->second << endl << endl;\n }\n}\n\n\/\/ read the input text from the given stream\nvoid phSolver::Input::get_input_lines(vector *text, ifstream &infile)\n{\n string textline;\n while ( getline( infile, textline, '\\n' ) ) {\n \/\/ ignore everything on a comment line\n if ( textline[0] != '#' ) {\n text->push_back( textline );\n }\n }\n}\n\n\n\/\/ \nvoid phSolver::Input::build_map(map *inmap,\n\t\t vector *intext)\n{\n \/\/ iterate through input_text of text and separate at :'s\n for (int i = 0 ; i < intext->size(); i++) {\n string textlineALL = (*intext)[i];\n string textline;\n int pos = 0;\n \n \/\/ modification introduced so that comments starting midway in a file \n \/\/ can be handled.\n\n if ( (pos = textlineALL.find_first_of( '#',pos)) != string::npos) {\n textline = textlineALL.substr(0,pos);\n }else {\n textline = textlineALL;\n }\n pos = 0;\n if ( (pos = textline.find_first_of( ':',pos)) != string::npos) {\n \n \/\/ get the keyphrase\n string keywd = textline.substr(0,pos);\n trim_string(&keywd);\n \n \/\/ get the key-value\n string keyval = textline.substr( pos+1, textline.length() - pos);\n trim_string(&keyval);\n \n \/\/ put the pair into the map\n (*inmap)[keywd] = keyval;\n \n }\n }\n}\n\n\/\/ remove leading and trailing spaces (or tabs)\nvoid phSolver::Input::trim_string(string *str)\n{\n \/\/ check for empty string\n int length = str->length();\n if ( length == 0 )\n return;\n \n \/\/ erase leading spaces (or tabs)\n int pos0 = 0;\n while ( (*str)[pos0] == ' ' || (*str)[pos0] == '\\t') {\n pos0++;\n }\n if ( pos0 > 0 ) {\n str->erase(0,pos0);\n }\n\n length = str->length();\n pos0 = length-1;\n \/\/ erase trailing spaces (or tabs)\n while ( (*str)[pos0] == ' ' || (*str)[pos0] == '\\t') {\n pos0--;\n }\n if ( pos0 < length-1 ) {\n str->erase(pos0+1, length-pos0);\n }\n\n}\ninitialize variables, and compare like types#include \n#include \n#include \"Input.h\"\n#include \"ValType.h\"\n#include \n#include \n\/\/MR CHANGE\n#include \n\/\/MR CHANGE END\n\n\/\/ return a given key value (if it's in the map)\nValType phSolver::Input::GetValue(const string &str) const\n{\n if (input_map->find(str) != input_map->end()) {\n if ( (*input_map)[str] == \"NODEFAULT\" ) {\n stringstream ost;\n ost << \"required input variable not set: \" << str << ends;\n throw invalid_argument( ost.str() );\n }\n } else {\n stringstream ost;\n ost << \"required input variable not set: \" << str << ends;\n throw invalid_argument( ost.str() );\n }\n\n return ValType( (*input_map)[str] );\n}\n\nconst char* phSolver::Input::GetUserFileName() {\n return userConfFileName.c_str();\n}\n\nconst char* phSolver::Input::GetDefaultFileName() {\n return defaultConfFileName.c_str();\n}\n\nphSolver::Input::Input(const string &fname, const string &default_fname) \n : userConfFileName(fname), defaultConfFileName(default_fname)\n{\n \/\/ open the input file\n ifstream infile( fname.c_str(), ios::in);\n\n if(!infile || infile.eof()){\n cerr<<\" Input file does not exist or is empty or perhaps you forgot mpirun? \"<;\n input_map = new map;\n\n \/\/ get the lines of text from the input file\n get_input_lines(input_text, infile);\n build_map(input_map, input_text);\n\n \/\/ build and merge with default map ( if desired )\n if (!default_fname.empty()) {\n ifstream infile2( default_fname.c_str(), ios::in);\n\n map *default_map = new map;\n vector *default_text = new vector;\n\n get_input_lines(default_text, infile2);\n build_map(default_map, default_text);\n\n \/\/ merge the two maps\n map::const_iterator iter = default_map->begin();\n for ( ; iter != default_map->end(); ++iter ) {\n string defkey = iter->first;\n string defval = iter->second;\n if ( input_map->find(defkey) == input_map->end() ) {\n\t(*input_map)[defkey] = defval;\n }\n }\n infile2.close();\n\n delete default_map;\n delete default_text;\n \n } else {\n cerr << \"Input warning: no input.config file found.\" << endl;\n cerr << \"Get one from source directory.\" << endl;\n exit(-2);\n }\n\n infile.close();\n \n}\n \nphSolver::Input::~Input()\n{\n delete input_text;\n delete input_map;\n}\n\n\n\/\/ return the input map\nmap phSolver::Input::InputMap() const\n{\n return *input_map;\n}\n\n\/\/ echo the entire map\nvoid phSolver::Input::EchoInputMap(const ostream &ofile)\n{\n map::const_iterator iter = input_map->begin();\n for ( ; iter != input_map->end(); ++iter ) {\n cout << \"Keyphrase: \" << iter->first << endl \n\t << \"Keyvalue: \" << iter->second << endl << endl;\n }\n}\n\n\/\/ read the input text from the given stream\nvoid phSolver::Input::get_input_lines(vector *text, ifstream &infile)\n{\n string textline;\n while ( getline( infile, textline, '\\n' ) ) {\n \/\/ ignore everything on a comment line\n if ( textline[0] != '#' ) {\n text->push_back( textline );\n }\n }\n}\n\n\n\/\/ \nvoid phSolver::Input::build_map(map *inmap,\n\t\t vector *intext)\n{\n \/\/ iterate through input_text of text and separate at :'s\n for (unsigned i = 0 ; i < intext->size(); i++) {\n string textlineALL = (*intext)[i];\n string textline;\n \n \/\/ modification introduced so that comments starting midway in a file \n \/\/ can be handled.\n size_t pos = textlineALL.find_first_of( '#',0);\n if ( pos != string::npos) {\n textline = textlineALL.substr(0,pos);\n }else {\n textline = textlineALL;\n }\n pos = textline.find_first_of( ':', 0);\n if ( pos != string::npos) {\n \n \/\/ get the keyphrase\n string keywd = textline.substr(0,pos);\n trim_string(&keywd);\n \n \/\/ get the key-value\n string keyval = textline.substr( pos+1, textline.length() - pos);\n trim_string(&keyval);\n \n \/\/ put the pair into the map\n (*inmap)[keywd] = keyval;\n \n }\n }\n}\n\n\/\/ remove leading and trailing spaces (or tabs)\nvoid phSolver::Input::trim_string(string *str)\n{\n \/\/ check for empty string\n int length = str->length();\n if ( length == 0 )\n return;\n \n \/\/ erase leading spaces (or tabs)\n int pos0 = 0;\n while ( (*str)[pos0] == ' ' || (*str)[pos0] == '\\t') {\n pos0++;\n }\n if ( pos0 > 0 ) {\n str->erase(0,pos0);\n }\n\n length = str->length();\n pos0 = length-1;\n \/\/ erase trailing spaces (or tabs)\n while ( (*str)[pos0] == ' ' || (*str)[pos0] == '\\t') {\n pos0--;\n }\n if ( pos0 < length-1 ) {\n str->erase(pos0+1, length-pos0);\n }\n\n}\n<|endoftext|>"} {"text":"\n#ifndef AT_COMMAND_LINE_HPP\n#define AT_COMMAND_LINE_HPP\n\n\n#include \"atNotifier.h++\"\n#include \"atString.h++\"\n#include \"atList.h++\"\n#include \"atMap.h++\"\n\n\nclass atCommandLine : public atNotifier\n{\n protected:\n\n atMap valid_options;\n\n atMap options_map;\n atList args_list;\n\n void parseValidOptions(atString optionsSpec);\n bool takesValue(atString option);\n bool parseOption(char * arg, char * nextArg);\n\n public:\n\n atCommandLine();\n atCommandLine(atString optionsSpec);\n atCommandLine(int argc, char ** argv, atString optionsSpec);\n virtual ~atCommandLine();\n\n void setValidOptions(atString optionsSpec);\n void addValidOption(char option, bool takesValue);\n\n void parseCommandLine(int argc, char ** argv);\n\n bool hasOption(atString opt);\n atString getOptionValue(atString opt);\n\n atList * getOptionList();\n atList * getArgumentList();\n};\n\n\n#endif\n\nForgot ATLAS_SYM\n#ifndef AT_COMMAND_LINE_HPP\n#define AT_COMMAND_LINE_HPP\n\n\n#include \"atNotifier.h++\"\n#include \"atString.h++\"\n#include \"atList.h++\"\n#include \"atMap.h++\"\n\n\nclass ATLAS_SYM atCommandLine : public atNotifier\n{\n protected:\n\n atMap valid_options;\n\n atMap options_map;\n atList args_list;\n\n void parseValidOptions(atString optionsSpec);\n bool takesValue(atString option);\n bool parseOption(char * arg, char * nextArg);\n\n public:\n\n atCommandLine();\n atCommandLine(atString optionsSpec);\n atCommandLine(int argc, char ** argv, atString optionsSpec);\n virtual ~atCommandLine();\n\n void setValidOptions(atString optionsSpec);\n void addValidOption(char option, bool takesValue);\n\n void parseCommandLine(int argc, char ** argv);\n\n bool hasOption(atString opt);\n atString getOptionValue(atString opt);\n\n atList * getOptionList();\n atList * getArgumentList();\n};\n\n\n#endif\n\n<|endoftext|>"} {"text":"\/\/\n\/\/ Copyright 2012 Francisco Jerez\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a\n\/\/ copy of this software and associated documentation files (the \"Software\"),\n\/\/ to deal in the Software without restriction, including without limitation\n\/\/ the rights to use, copy, modify, merge, publish, distribute, sublicense,\n\/\/ and\/or sell copies of the Software, and to permit persons to whom the\n\/\/ Software is furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n\/\/ THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR\n\/\/ OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,\n\/\/ ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\n\/\/ OTHER DEALINGS IN THE SOFTWARE.\n\/\/\n\n#include \"core\/compiler.hpp\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#if HAVE_LLVM < 0x0303\n#include \n#include \n#include \n#else\n#include \n#include \n#include \n#include \n#include \n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n\n#if HAVE_LLVM < 0x0302\n#include \n#elif HAVE_LLVM < 0x0303\n#include \n#else\n#include \n#endif\n\n#include \"pipe\/p_state.h\"\n#include \"util\/u_memory.h\"\n\n#include \n#include \n#include \n#include \n#include \n\nusing namespace clover;\n\nnamespace {\n#if 0\n void\n build_binary(const std::string &source, const std::string &target,\n const std::string &name) {\n clang::CompilerInstance c;\n clang::EmitObjAction act(&llvm::getGlobalContext());\n std::string log;\n llvm::raw_string_ostream s_log(log);\n\n LLVMInitializeTGSITarget();\n LLVMInitializeTGSITargetInfo();\n LLVMInitializeTGSITargetMC();\n LLVMInitializeTGSIAsmPrinter();\n\n c.getFrontendOpts().Inputs.push_back(\n std::make_pair(clang::IK_OpenCL, name));\n c.getHeaderSearchOpts().UseBuiltinIncludes = false;\n c.getHeaderSearchOpts().UseStandardIncludes = false;\n c.getLangOpts().NoBuiltin = true;\n c.getTargetOpts().Triple = target;\n c.getInvocation().setLangDefaults(clang::IK_OpenCL);\n c.createDiagnostics(0, NULL, new clang::TextDiagnosticPrinter(\n s_log, c.getDiagnosticOpts()));\n\n c.getPreprocessorOpts().addRemappedFile(\n name, llvm::MemoryBuffer::getMemBuffer(source));\n\n if (!c.ExecuteAction(act))\n throw build_error(log);\n }\n\n module\n load_binary(const char *name) {\n std::ifstream fs((name));\n std::vector str((std::istreambuf_iterator(fs)),\n (std::istreambuf_iterator()));\n compat::istream cs(str);\n return module::deserialize(cs);\n }\n#endif\n\n llvm::Module *\n compile(const std::string &source, const std::string &name,\n const std::string &triple, const std::string &processor,\n const std::string &opts) {\n\n clang::CompilerInstance c;\n clang::CompilerInvocation invocation;\n clang::EmitLLVMOnlyAction act(&llvm::getGlobalContext());\n std::string log;\n llvm::raw_string_ostream s_log(log);\n\n \/\/ Parse the compiler options:\n std::vector opts_array;\n std::istringstream ss(opts);\n\n while (!ss.eof()) {\n std::string opt;\n getline(ss, opt, ' ');\n opts_array.push_back(opt);\n }\n\n opts_array.push_back(name);\n\n std::vector opts_carray;\n for (unsigned i = 0; i < opts_array.size(); i++) {\n opts_carray.push_back(opts_array.at(i).c_str());\n }\n\n llvm::IntrusiveRefCntPtr DiagID;\n llvm::IntrusiveRefCntPtr DiagOpts;\n clang::TextDiagnosticBuffer *DiagsBuffer;\n\n DiagID = new clang::DiagnosticIDs();\n DiagOpts = new clang::DiagnosticOptions();\n DiagsBuffer = new clang::TextDiagnosticBuffer();\n\n clang::DiagnosticsEngine Diags(DiagID, &*DiagOpts, DiagsBuffer);\n bool Success;\n\n Success = clang::CompilerInvocation::CreateFromArgs(c.getInvocation(),\n opts_carray.data(),\n opts_carray.data() + opts_carray.size(),\n Diags);\n if (!Success) {\n throw invalid_option_error();\n }\n c.getFrontendOpts().ProgramAction = clang::frontend::EmitLLVMOnly;\n c.getHeaderSearchOpts().UseBuiltinIncludes = true;\n c.getHeaderSearchOpts().UseStandardSystemIncludes = true;\n c.getHeaderSearchOpts().ResourceDir = CLANG_RESOURCE_DIR;\n\n \/\/ Add libclc generic search path\n c.getHeaderSearchOpts().AddPath(LIBCLC_INCLUDEDIR,\n clang::frontend::Angled,\n false, false\n#if HAVE_LLVM < 0x0303\n , false\n#endif\n );\n\n \/\/ Add libclc include\n c.getPreprocessorOpts().Includes.push_back(\"clc\/clc.h\");\n\n \/\/ clc.h requires that this macro be defined:\n c.getPreprocessorOpts().addMacroDef(\"cl_clang_storage_class_specifiers\");\n\n c.getLangOpts().NoBuiltin = true;\n c.getTargetOpts().Triple = triple;\n c.getTargetOpts().CPU = processor;\n#if HAVE_LLVM <= 0x0301\n c.getInvocation().setLangDefaults(clang::IK_OpenCL);\n#else\n c.getInvocation().setLangDefaults(c.getLangOpts(), clang::IK_OpenCL,\n clang::LangStandard::lang_opencl11);\n#endif\n c.createDiagnostics(\n#if HAVE_LLVM < 0x0303\n 0, NULL,\n#endif\n new clang::TextDiagnosticPrinter(\n s_log,\n#if HAVE_LLVM <= 0x0301\n c.getDiagnosticOpts()));\n#else\n &c.getDiagnosticOpts()));\n#endif\n\n c.getPreprocessorOpts().addRemappedFile(name,\n llvm::MemoryBuffer::getMemBuffer(source));\n\n \/\/ Compile the code\n if (!c.ExecuteAction(act))\n throw build_error(log);\n\n return act.takeModule();\n }\n\n void\n find_kernels(llvm::Module *mod, std::vector &kernels) {\n const llvm::NamedMDNode *kernel_node =\n mod->getNamedMetadata(\"opencl.kernels\");\n for (unsigned i = 0; i < kernel_node->getNumOperands(); ++i) {\n kernels.push_back(llvm::dyn_cast(\n kernel_node->getOperand(i)->getOperand(0)));\n }\n }\n\n void\n link(llvm::Module *mod, const std::string &triple,\n const std::string &processor,\n const std::vector &kernels) {\n\n llvm::PassManager PM;\n llvm::PassManagerBuilder Builder;\n llvm::sys::Path libclc_path =\n llvm::sys::Path(LIBCLC_LIBEXECDIR + processor +\n\t\t\t \"-\" + triple + \".bc\");\n\n \/\/ Link the kernel with libclc\n#if HAVE_LLVM < 0x0303\n bool isNative;\n llvm::Linker linker(\"clover\", mod);\n linker.LinkInFile(libclc_path, isNative);\n mod = linker.releaseModule();\n#else\n std::string err_str;\n llvm::SMDiagnostic err;\n llvm::Module *libclc_mod = llvm::ParseIRFile(libclc_path.str(), err,\n mod->getContext());\n if (llvm::Linker::LinkModules(mod, libclc_mod,\n llvm::Linker::DestroySource,\n &err_str)) {\n throw build_error(err_str);\n }\n#endif\n\n \/\/ Add a function internalizer pass.\n \/\/\n \/\/ By default, the function internalizer pass will look for a function\n \/\/ called \"main\" and then mark all other functions as internal. Marking\n \/\/ functions as internal enables the optimizer to perform optimizations\n \/\/ like function inlining and global dead-code elimination.\n \/\/\n \/\/ When there is no \"main\" function in a module, the internalize pass will\n \/\/ treat the module like a library, and it won't internalize any functions.\n \/\/ Since there is no \"main\" function in our kernels, we need to tell\n \/\/ the internalizer pass that this module is not a library by passing a\n \/\/ list of kernel functions to the internalizer. The internalizer will\n \/\/ treat the functions in the list as \"main\" functions and internalize\n \/\/ all of the other functions.\n std::vector export_list;\n for (std::vector::const_iterator I = kernels.begin(),\n E = kernels.end();\n I != E; ++I) {\n llvm::Function *kernel = *I;\n export_list.push_back(kernel->getName().data());\n }\n PM.add(llvm::createInternalizePass(export_list));\n\n \/\/ Run link time optimizations\n Builder.OptLevel = 2;\n Builder.populateLTOPassManager(PM, false, true);\n PM.run(*mod);\n }\n\n module\n build_module_llvm(llvm::Module *mod,\n const std::vector &kernels) {\n\n module m;\n struct pipe_llvm_program_header header;\n\n llvm::SmallVector llvm_bitcode;\n llvm::raw_svector_ostream bitcode_ostream(llvm_bitcode);\n llvm::BitstreamWriter writer(llvm_bitcode);\n llvm::WriteBitcodeToFile(mod, bitcode_ostream);\n bitcode_ostream.flush();\n\n for (unsigned i = 0; i < kernels.size(); ++i) {\n llvm::Function *kernel_func;\n std::string kernel_name;\n compat::vector args;\n\n kernel_func = kernels[i];\n kernel_name = kernel_func->getName();\n\n for (llvm::Function::arg_iterator I = kernel_func->arg_begin(),\n E = kernel_func->arg_end(); I != E; ++I) {\n llvm::Argument &arg = *I;\n llvm::Type *arg_type = arg.getType();\n#if HAVE_LLVM < 0x0302\n llvm::TargetData TD(kernel_func->getParent());\n#else\n llvm::DataLayout TD(kernel_func->getParent()->getDataLayout());\n#endif\n unsigned arg_size = TD.getTypeStoreSize(arg_type);\n\n if (llvm::isa(arg_type) && arg.hasByValAttr()) {\n arg_type =\n llvm::dyn_cast(arg_type)->getElementType();\n }\n\n if (arg_type->isPointerTy()) {\n \/\/ XXX: Figure out LLVM->OpenCL address space mappings for each\n \/\/ target. I think we need to ask clang what these are. For now,\n \/\/ pretend everything is in the global address space.\n unsigned address_space = llvm::cast(arg_type)->getAddressSpace();\n switch (address_space) {\n default:\n args.push_back(module::argument(module::argument::global, arg_size));\n break;\n }\n } else {\n args.push_back(module::argument(module::argument::scalar, arg_size));\n }\n }\n\n m.syms.push_back(module::symbol(kernel_name, 0, i, args ));\n }\n\n header.num_bytes = llvm_bitcode.size();\n std::string data;\n data.insert(0, (char*)(&header), sizeof(header));\n data.insert(data.end(), llvm_bitcode.begin(),\n llvm_bitcode.end());\n m.secs.push_back(module::section(0, module::section::text,\n header.num_bytes, data));\n\n return m;\n }\n} \/\/ End anonymous namespace\n\nmodule\nclover::compile_program_llvm(const compat::string &source,\n enum pipe_shader_ir ir,\n const compat::string &target,\n const compat::string &opts) {\n\n std::vector kernels;\n size_t processor_str_len = std::string(target.begin()).find_first_of(\"-\");\n std::string processor(target.begin(), 0, processor_str_len);\n std::string triple(target.begin(), processor_str_len + 1,\n target.size() - processor_str_len - 1);\n\n \/\/ The input file name must have the .cl extension in order for the\n \/\/ CompilerInvocation class to recognize it as an OpenCL source file.\n llvm::Module *mod = compile(source, \"input.cl\", triple, processor, opts);\n\n find_kernels(mod, kernels);\n\n link(mod, triple, processor, kernels);\n\n \/\/ Build the clover::module\n switch (ir) {\n case PIPE_SHADER_IR_TGSI:\n \/\/XXX: Handle TGSI\n assert(0);\n return module();\n default:\n return build_module_llvm(mod, kernels);\n }\n}\nclover: Fix build with LLVM 3.4\/\/\n\/\/ Copyright 2012 Francisco Jerez\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a\n\/\/ copy of this software and associated documentation files (the \"Software\"),\n\/\/ to deal in the Software without restriction, including without limitation\n\/\/ the rights to use, copy, modify, merge, publish, distribute, sublicense,\n\/\/ and\/or sell copies of the Software, and to permit persons to whom the\n\/\/ Software is furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n\/\/ THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR\n\/\/ OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,\n\/\/ ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\n\/\/ OTHER DEALINGS IN THE SOFTWARE.\n\/\/\n\n#include \"core\/compiler.hpp\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#if HAVE_LLVM < 0x0303\n#include \n#include \n#include \n#else\n#include \n#include \n#include \n#include \n#include \n#endif\n#include \n#include \n#include \n#if HAVE_LLVM < 0x0303\n#include \n#endif\n#include \n#include \n\n#if HAVE_LLVM < 0x0302\n#include \n#elif HAVE_LLVM < 0x0303\n#include \n#else\n#include \n#endif\n\n#include \"pipe\/p_state.h\"\n#include \"util\/u_memory.h\"\n\n#include \n#include \n#include \n#include \n#include \n\nusing namespace clover;\n\nnamespace {\n#if 0\n void\n build_binary(const std::string &source, const std::string &target,\n const std::string &name) {\n clang::CompilerInstance c;\n clang::EmitObjAction act(&llvm::getGlobalContext());\n std::string log;\n llvm::raw_string_ostream s_log(log);\n\n LLVMInitializeTGSITarget();\n LLVMInitializeTGSITargetInfo();\n LLVMInitializeTGSITargetMC();\n LLVMInitializeTGSIAsmPrinter();\n\n c.getFrontendOpts().Inputs.push_back(\n std::make_pair(clang::IK_OpenCL, name));\n c.getHeaderSearchOpts().UseBuiltinIncludes = false;\n c.getHeaderSearchOpts().UseStandardIncludes = false;\n c.getLangOpts().NoBuiltin = true;\n c.getTargetOpts().Triple = target;\n c.getInvocation().setLangDefaults(clang::IK_OpenCL);\n c.createDiagnostics(0, NULL, new clang::TextDiagnosticPrinter(\n s_log, c.getDiagnosticOpts()));\n\n c.getPreprocessorOpts().addRemappedFile(\n name, llvm::MemoryBuffer::getMemBuffer(source));\n\n if (!c.ExecuteAction(act))\n throw build_error(log);\n }\n\n module\n load_binary(const char *name) {\n std::ifstream fs((name));\n std::vector str((std::istreambuf_iterator(fs)),\n (std::istreambuf_iterator()));\n compat::istream cs(str);\n return module::deserialize(cs);\n }\n#endif\n\n llvm::Module *\n compile(const std::string &source, const std::string &name,\n const std::string &triple, const std::string &processor,\n const std::string &opts) {\n\n clang::CompilerInstance c;\n clang::CompilerInvocation invocation;\n clang::EmitLLVMOnlyAction act(&llvm::getGlobalContext());\n std::string log;\n llvm::raw_string_ostream s_log(log);\n\n \/\/ Parse the compiler options:\n std::vector opts_array;\n std::istringstream ss(opts);\n\n while (!ss.eof()) {\n std::string opt;\n getline(ss, opt, ' ');\n opts_array.push_back(opt);\n }\n\n opts_array.push_back(name);\n\n std::vector opts_carray;\n for (unsigned i = 0; i < opts_array.size(); i++) {\n opts_carray.push_back(opts_array.at(i).c_str());\n }\n\n llvm::IntrusiveRefCntPtr DiagID;\n llvm::IntrusiveRefCntPtr DiagOpts;\n clang::TextDiagnosticBuffer *DiagsBuffer;\n\n DiagID = new clang::DiagnosticIDs();\n DiagOpts = new clang::DiagnosticOptions();\n DiagsBuffer = new clang::TextDiagnosticBuffer();\n\n clang::DiagnosticsEngine Diags(DiagID, &*DiagOpts, DiagsBuffer);\n bool Success;\n\n Success = clang::CompilerInvocation::CreateFromArgs(c.getInvocation(),\n opts_carray.data(),\n opts_carray.data() + opts_carray.size(),\n Diags);\n if (!Success) {\n throw invalid_option_error();\n }\n c.getFrontendOpts().ProgramAction = clang::frontend::EmitLLVMOnly;\n c.getHeaderSearchOpts().UseBuiltinIncludes = true;\n c.getHeaderSearchOpts().UseStandardSystemIncludes = true;\n c.getHeaderSearchOpts().ResourceDir = CLANG_RESOURCE_DIR;\n\n \/\/ Add libclc generic search path\n c.getHeaderSearchOpts().AddPath(LIBCLC_INCLUDEDIR,\n clang::frontend::Angled,\n false, false\n#if HAVE_LLVM < 0x0303\n , false\n#endif\n );\n\n \/\/ Add libclc include\n c.getPreprocessorOpts().Includes.push_back(\"clc\/clc.h\");\n\n \/\/ clc.h requires that this macro be defined:\n c.getPreprocessorOpts().addMacroDef(\"cl_clang_storage_class_specifiers\");\n\n c.getLangOpts().NoBuiltin = true;\n c.getTargetOpts().Triple = triple;\n c.getTargetOpts().CPU = processor;\n#if HAVE_LLVM <= 0x0301\n c.getInvocation().setLangDefaults(clang::IK_OpenCL);\n#else\n c.getInvocation().setLangDefaults(c.getLangOpts(), clang::IK_OpenCL,\n clang::LangStandard::lang_opencl11);\n#endif\n c.createDiagnostics(\n#if HAVE_LLVM < 0x0303\n 0, NULL,\n#endif\n new clang::TextDiagnosticPrinter(\n s_log,\n#if HAVE_LLVM <= 0x0301\n c.getDiagnosticOpts()));\n#else\n &c.getDiagnosticOpts()));\n#endif\n\n c.getPreprocessorOpts().addRemappedFile(name,\n llvm::MemoryBuffer::getMemBuffer(source));\n\n \/\/ Compile the code\n if (!c.ExecuteAction(act))\n throw build_error(log);\n\n return act.takeModule();\n }\n\n void\n find_kernels(llvm::Module *mod, std::vector &kernels) {\n const llvm::NamedMDNode *kernel_node =\n mod->getNamedMetadata(\"opencl.kernels\");\n for (unsigned i = 0; i < kernel_node->getNumOperands(); ++i) {\n kernels.push_back(llvm::dyn_cast(\n kernel_node->getOperand(i)->getOperand(0)));\n }\n }\n\n void\n link(llvm::Module *mod, const std::string &triple,\n const std::string &processor,\n const std::vector &kernels) {\n\n llvm::PassManager PM;\n llvm::PassManagerBuilder Builder;\n std::string libclc_path = LIBCLC_LIBEXECDIR + processor + \"-\"\n + triple + \".bc\";\n \/\/ Link the kernel with libclc\n#if HAVE_LLVM < 0x0303\n bool isNative;\n llvm::Linker linker(\"clover\", mod);\n linker.LinkInFile(llvm::sys::Path(libclc_path), isNative);\n mod = linker.releaseModule();\n#else\n std::string err_str;\n llvm::SMDiagnostic err;\n llvm::Module *libclc_mod = llvm::ParseIRFile(libclc_path, err,\n mod->getContext());\n if (llvm::Linker::LinkModules(mod, libclc_mod,\n llvm::Linker::DestroySource,\n &err_str)) {\n throw build_error(err_str);\n }\n#endif\n\n \/\/ Add a function internalizer pass.\n \/\/\n \/\/ By default, the function internalizer pass will look for a function\n \/\/ called \"main\" and then mark all other functions as internal. Marking\n \/\/ functions as internal enables the optimizer to perform optimizations\n \/\/ like function inlining and global dead-code elimination.\n \/\/\n \/\/ When there is no \"main\" function in a module, the internalize pass will\n \/\/ treat the module like a library, and it won't internalize any functions.\n \/\/ Since there is no \"main\" function in our kernels, we need to tell\n \/\/ the internalizer pass that this module is not a library by passing a\n \/\/ list of kernel functions to the internalizer. The internalizer will\n \/\/ treat the functions in the list as \"main\" functions and internalize\n \/\/ all of the other functions.\n std::vector export_list;\n for (std::vector::const_iterator I = kernels.begin(),\n E = kernels.end();\n I != E; ++I) {\n llvm::Function *kernel = *I;\n export_list.push_back(kernel->getName().data());\n }\n PM.add(llvm::createInternalizePass(export_list));\n\n \/\/ Run link time optimizations\n Builder.OptLevel = 2;\n Builder.populateLTOPassManager(PM, false, true);\n PM.run(*mod);\n }\n\n module\n build_module_llvm(llvm::Module *mod,\n const std::vector &kernels) {\n\n module m;\n struct pipe_llvm_program_header header;\n\n llvm::SmallVector llvm_bitcode;\n llvm::raw_svector_ostream bitcode_ostream(llvm_bitcode);\n llvm::BitstreamWriter writer(llvm_bitcode);\n llvm::WriteBitcodeToFile(mod, bitcode_ostream);\n bitcode_ostream.flush();\n\n for (unsigned i = 0; i < kernels.size(); ++i) {\n llvm::Function *kernel_func;\n std::string kernel_name;\n compat::vector args;\n\n kernel_func = kernels[i];\n kernel_name = kernel_func->getName();\n\n for (llvm::Function::arg_iterator I = kernel_func->arg_begin(),\n E = kernel_func->arg_end(); I != E; ++I) {\n llvm::Argument &arg = *I;\n llvm::Type *arg_type = arg.getType();\n#if HAVE_LLVM < 0x0302\n llvm::TargetData TD(kernel_func->getParent());\n#else\n llvm::DataLayout TD(kernel_func->getParent()->getDataLayout());\n#endif\n unsigned arg_size = TD.getTypeStoreSize(arg_type);\n\n if (llvm::isa(arg_type) && arg.hasByValAttr()) {\n arg_type =\n llvm::dyn_cast(arg_type)->getElementType();\n }\n\n if (arg_type->isPointerTy()) {\n \/\/ XXX: Figure out LLVM->OpenCL address space mappings for each\n \/\/ target. I think we need to ask clang what these are. For now,\n \/\/ pretend everything is in the global address space.\n unsigned address_space = llvm::cast(arg_type)->getAddressSpace();\n switch (address_space) {\n default:\n args.push_back(module::argument(module::argument::global, arg_size));\n break;\n }\n } else {\n args.push_back(module::argument(module::argument::scalar, arg_size));\n }\n }\n\n m.syms.push_back(module::symbol(kernel_name, 0, i, args ));\n }\n\n header.num_bytes = llvm_bitcode.size();\n std::string data;\n data.insert(0, (char*)(&header), sizeof(header));\n data.insert(data.end(), llvm_bitcode.begin(),\n llvm_bitcode.end());\n m.secs.push_back(module::section(0, module::section::text,\n header.num_bytes, data));\n\n return m;\n }\n} \/\/ End anonymous namespace\n\nmodule\nclover::compile_program_llvm(const compat::string &source,\n enum pipe_shader_ir ir,\n const compat::string &target,\n const compat::string &opts) {\n\n std::vector kernels;\n size_t processor_str_len = std::string(target.begin()).find_first_of(\"-\");\n std::string processor(target.begin(), 0, processor_str_len);\n std::string triple(target.begin(), processor_str_len + 1,\n target.size() - processor_str_len - 1);\n\n \/\/ The input file name must have the .cl extension in order for the\n \/\/ CompilerInvocation class to recognize it as an OpenCL source file.\n llvm::Module *mod = compile(source, \"input.cl\", triple, processor, opts);\n\n find_kernels(mod, kernels);\n\n link(mod, triple, processor, kernels);\n\n \/\/ Build the clover::module\n switch (ir) {\n case PIPE_SHADER_IR_TGSI:\n \/\/XXX: Handle TGSI\n assert(0);\n return module();\n default:\n return build_module_llvm(mod, kernels);\n }\n}\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2013, Facebook, Inc. All rights reserved.\n\/\/ This source code is licensed under the BSD-style license found in the\n\/\/ LICENSE file in the root directory of this source tree. An additional grant\n\/\/ of patent rights can be found in the PATENTS file in the same directory.\n\n#ifndef __STDC_FORMAT_MACROS\n#define __STDC_FORMAT_MACROS\n#endif\n\n#include \n#include \n#include \n#include \n#include \n\n#include \"db\/filename.h\"\n#include \"rocksdb\/options.h\"\n#include \"rocksdb\/env.h\"\n#include \"util\/db_info_dumper.h\"\n\nnamespace rocksdb {\n\nvoid DumpDBFileSummary(const DBOptions& options, const std::string& dbname) {\n if (options.info_log == nullptr) {\n return;\n }\n\n auto* env = options.env;\n uint64_t number = 0;\n FileType type = kInfoLogFile;\n\n std::vector files;\n uint64_t file_num = 0;\n uint64_t file_size;\n std::string file_info, wal_info;\n\n Warn(options.info_log, \"DB SUMMARY\\n\");\n \/\/ Get files in dbname dir\n if (!env->GetChildren(dbname, &files).ok()) {\n Error(options.info_log,\n \"Error when reading %s dir\\n\", dbname.c_str());\n }\n std::sort(files.begin(), files.end());\n for (std::string file : files) {\n if (!ParseFileName(file, &number, &type)) {\n continue;\n }\n switch (type) {\n case kCurrentFile:\n Warn(options.info_log,\n \"CURRENT file: %s\\n\", file.c_str());\n break;\n case kIdentityFile:\n Warn(options.info_log,\n \"IDENTITY file: %s\\n\", file.c_str());\n break;\n case kDescriptorFile:\n env->GetFileSize(dbname + \"\/\" + file, &file_size);\n Warn(options.info_log,\n \"MANIFEST file: %s size: %\" PRIu64 \" Bytes\\n\",\n file.c_str(), file_size);\n break;\n case kLogFile:\n env->GetFileSize(dbname + \"\/\" + file, &file_size);\n char str[8];\n snprintf(str, sizeof(str), \"%\" PRIu64, file_size);\n wal_info.append(file).append(\" size: \").\n append(str, sizeof(str)).append(\" ;\");\n break;\n case kTableFile:\n if (++file_num < 10) {\n file_info.append(file).append(\" \");\n }\n break;\n default:\n break;\n }\n }\n\n \/\/ Get sst files in db_path dir\n for (auto& db_path : options.db_paths) {\n if (dbname.compare(db_path.path) != 0) {\n if (!env->GetChildren(db_path.path, &files).ok()) {\n Error(options.info_log,\n \"Error when reading %s dir\\n\",\n db_path.path.c_str());\n continue;\n }\n std::sort(files.begin(), files.end());\n for (std::string file : files) {\n if (ParseFileName(file, &number, &type)) {\n if (type == kTableFile && ++file_num < 10) {\n file_info.append(file).append(\" \");\n }\n }\n }\n }\n Warn(options.info_log,\n \"SST files in %s dir, Total Num: %\" PRIu64 \", files: %s\\n\",\n db_path.path.c_str(), file_num, file_info.c_str());\n file_num = 0;\n file_info.clear();\n }\n\n \/\/ Get wal file in wal_dir\n if (dbname.compare(options.wal_dir) != 0) {\n if (!env->GetChildren(options.wal_dir, &files).ok()) {\n Error(options.info_log,\n \"Error when reading %s dir\\n\",\n options.wal_dir.c_str());\n return;\n }\n wal_info.clear();\n for (std::string file : files) {\n if (ParseFileName(file, &number, &type)) {\n if (type == kLogFile) {\n env->GetFileSize(options.wal_dir + \"\/\" + file, &file_size);\n char str[8];\n snprintf(str, sizeof(str), \"%\" PRIu64, file_size);\n wal_info.append(file).append(\" size: \").\n append(str, sizeof(str)).append(\" ;\");\n }\n }\n }\n }\n Warn(options.info_log,\n \"Write Ahead Log file in %s: %s\\n\",\n options.wal_dir.c_str(), wal_info.c_str());\n}\n} \/\/ namespace rocksdb\nfix append bug in DumpDBFileSummary()\/\/ Copyright (c) 2013, Facebook, Inc. All rights reserved.\n\/\/ This source code is licensed under the BSD-style license found in the\n\/\/ LICENSE file in the root directory of this source tree. An additional grant\n\/\/ of patent rights can be found in the PATENTS file in the same directory.\n\n#ifndef __STDC_FORMAT_MACROS\n#define __STDC_FORMAT_MACROS\n#endif\n\n#include \n#include \n#include \n#include \n#include \n\n#include \"db\/filename.h\"\n#include \"rocksdb\/options.h\"\n#include \"rocksdb\/env.h\"\n#include \"util\/db_info_dumper.h\"\n\nnamespace rocksdb {\n\nvoid DumpDBFileSummary(const DBOptions& options, const std::string& dbname) {\n if (options.info_log == nullptr) {\n return;\n }\n\n auto* env = options.env;\n uint64_t number = 0;\n FileType type = kInfoLogFile;\n\n std::vector files;\n uint64_t file_num = 0;\n uint64_t file_size;\n std::string file_info, wal_info;\n\n Warn(options.info_log, \"DB SUMMARY\\n\");\n \/\/ Get files in dbname dir\n if (!env->GetChildren(dbname, &files).ok()) {\n Error(options.info_log,\n \"Error when reading %s dir\\n\", dbname.c_str());\n }\n std::sort(files.begin(), files.end());\n for (std::string file : files) {\n if (!ParseFileName(file, &number, &type)) {\n continue;\n }\n switch (type) {\n case kCurrentFile:\n Warn(options.info_log,\n \"CURRENT file: %s\\n\", file.c_str());\n break;\n case kIdentityFile:\n Warn(options.info_log,\n \"IDENTITY file: %s\\n\", file.c_str());\n break;\n case kDescriptorFile:\n env->GetFileSize(dbname + \"\/\" + file, &file_size);\n Warn(options.info_log,\n \"MANIFEST file: %s size: %\" PRIu64 \" Bytes\\n\",\n file.c_str(), file_size);\n break;\n case kLogFile:\n env->GetFileSize(dbname + \"\/\" + file, &file_size);\n char str[8];\n snprintf(str, sizeof(str), \"%\" PRIu64, file_size);\n wal_info.append(file).append(\" size: \").\n append(str).append(\" ; \");\n break;\n case kTableFile:\n if (++file_num < 10) {\n file_info.append(file).append(\" \");\n }\n break;\n default:\n break;\n }\n }\n\n \/\/ Get sst files in db_path dir\n for (auto& db_path : options.db_paths) {\n if (dbname.compare(db_path.path) != 0) {\n if (!env->GetChildren(db_path.path, &files).ok()) {\n Error(options.info_log,\n \"Error when reading %s dir\\n\",\n db_path.path.c_str());\n continue;\n }\n std::sort(files.begin(), files.end());\n for (std::string file : files) {\n if (ParseFileName(file, &number, &type)) {\n if (type == kTableFile && ++file_num < 10) {\n file_info.append(file).append(\" \");\n }\n }\n }\n }\n Warn(options.info_log,\n \"SST files in %s dir, Total Num: %\" PRIu64 \", files: %s\\n\",\n db_path.path.c_str(), file_num, file_info.c_str());\n file_num = 0;\n file_info.clear();\n }\n\n \/\/ Get wal file in wal_dir\n if (dbname.compare(options.wal_dir) != 0) {\n if (!env->GetChildren(options.wal_dir, &files).ok()) {\n Error(options.info_log,\n \"Error when reading %s dir\\n\",\n options.wal_dir.c_str());\n return;\n }\n wal_info.clear();\n for (std::string file : files) {\n if (ParseFileName(file, &number, &type)) {\n if (type == kLogFile) {\n env->GetFileSize(options.wal_dir + \"\/\" + file, &file_size);\n char str[8];\n snprintf(str, sizeof(str), \"%\" PRIu64, file_size);\n wal_info.append(file).append(\" size: \").\n append(str).append(\" ; \");\n }\n }\n }\n }\n Warn(options.info_log,\n \"Write Ahead Log file in %s: %s\\n\",\n options.wal_dir.c_str(), wal_info.c_str());\n}\n} \/\/ namespace rocksdb\n<|endoftext|>"} {"text":"\/* IBM_PROLOG_BEGIN_TAG *\/\n\/* This is an automatically generated prolog. *\/\n\/* *\/\n\/* $Source: src\/import\/chips\/p9\/procedures\/hwp\/pm\/p9_pm_firinit.C $ *\/\n\/* *\/\n\/* OpenPOWER HostBoot Project *\/\n\/* *\/\n\/* Contributors Listed Below - COPYRIGHT 2015,2019 *\/\n\/* [+] International Business Machines Corp. *\/\n\/* *\/\n\/* *\/\n\/* Licensed under the Apache License, Version 2.0 (the \"License\"); *\/\n\/* you may not use this file except in compliance with the License. *\/\n\/* You may obtain a copy of the License at *\/\n\/* *\/\n\/* http:\/\/www.apache.org\/licenses\/LICENSE-2.0 *\/\n\/* *\/\n\/* Unless required by applicable law or agreed to in writing, software *\/\n\/* distributed under the License is distributed on an \"AS IS\" BASIS, *\/\n\/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or *\/\n\/* implied. See the License for the specific language governing *\/\n\/* permissions and limitations under the License. *\/\n\/* *\/\n\/* IBM_PROLOG_END_TAG *\/\n\/\/\/\n\/\/\/ @file p9_pm_firinit.C\n\/\/\/ @brief Calls firinit procedures to configure the FIRs to predefined types\n\/\/\/\n\/\/ *HWP HWP Owner: Amit Kumar \n\/\/ *HWP Backup HWP Owner: Greg Still \n\/\/ *HWP FW Owner: Sangeetha T S \n\/\/ *HWP Team: PM\n\/\/ *HWP Level: 1\n\/\/ *HWP Consumed by: FSP:HS\n\n\/\/\/\n\/\/\/ High-level procedure flow:\n\/\/\/\n\/\/\/ \\verbatim\n\/\/\/ - call p8_pm_pmc_firinit.C *chiptarget\n\/\/\/ - evaluate RC\n\/\/\/\n\/\/\/ - call p8_pm_pba_firinit.C *chiptarget\n\/\/\/ - evaluate RC\n\/\/\/\n\/\/\/ \\endverbatim\n\/\/\/\n\/\/\/ Procedure Prereq:\n\/\/\/ - System clocks are running\n\/\/\/\n\n\/\/ ----------------------------------------------------------------------\n\/\/ Includes\n\/\/ ----------------------------------------------------------------------\n#include \n\/\/ Need to include the headers for all the procedures to be invoked\n\/\/ Need to include the header containing the necessary scom addresses\n\n\/\/ ----------------------------------------------------------------------\n\/\/ Function definitions\n\/\/ ----------------------------------------------------------------------\nfapi2::ReturnCode p9_pm_firinit(\n const fapi2::Target& i_target,\n const p9pm::PM_FLOW_MODE i_mode)\n{\n FAPI_IMP(\"p9_pm_firinit start\");\n\n FAPI_INF(\"p9_pm_firinit end\");\n return fapi2::current_err;\n} \/\/ END p9_pm_firinit\np9_pm_firinit L2: PM FIR setup\/* IBM_PROLOG_BEGIN_TAG *\/\n\/* This is an automatically generated prolog. *\/\n\/* *\/\n\/* $Source: src\/import\/chips\/p9\/procedures\/hwp\/pm\/p9_pm_firinit.C $ *\/\n\/* *\/\n\/* OpenPOWER HostBoot Project *\/\n\/* *\/\n\/* Contributors Listed Below - COPYRIGHT 2015,2019 *\/\n\/* [+] International Business Machines Corp. *\/\n\/* *\/\n\/* *\/\n\/* Licensed under the Apache License, Version 2.0 (the \"License\"); *\/\n\/* you may not use this file except in compliance with the License. *\/\n\/* You may obtain a copy of the License at *\/\n\/* *\/\n\/* http:\/\/www.apache.org\/licenses\/LICENSE-2.0 *\/\n\/* *\/\n\/* Unless required by applicable law or agreed to in writing, software *\/\n\/* distributed under the License is distributed on an \"AS IS\" BASIS, *\/\n\/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or *\/\n\/* implied. See the License for the specific language governing *\/\n\/* permissions and limitations under the License. *\/\n\/* *\/\n\/* IBM_PROLOG_END_TAG *\/\n\/\/\/\n\/\/\/ @file p9_pm_firinit.C\n\/\/\/ @brief Calls firinit procedures to configure the FIRs to predefined types\n\/\/\/\n\/\/ *HWP HWP Owner: Amit Kumar \n\/\/ *HWP Backup HWP Owner: Greg Still \n\/\/ *HWP FW Owner: Sangeetha T S \n\/\/ *HWP Team: PM\n\/\/ *HWP Level: 2\n\/\/ *HWP Consumed by: FSP:HS\n\n\/\/\/\n\/\/\/ High-level procedure flow:\n\/\/\/\n\/\/\/ \\verbatim\n\/\/\/ - call p9_pm_occ_firinit.C\n\/\/\/ - evaluate RC\n\/\/\/\n\/\/\/ - call p9_pm_pba_firinit.C\n\/\/\/ - evaluate RC\n\/\/\/\n\/\/\/ - call p9_pm_ppm_firinit.C\n\/\/\/ - evaluate RC\n\/\/\/\n\/\/\/ - call p9_pm_cme_firinit.C\n\/\/\/ - evaluate RC\n\/\/\/\n\/\/\/ \\endverbatim\n\/\/\/\n\/\/\/ Procedure Prereq:\n\/\/\/ - System clocks are running\n\/\/\/\n\n\/\/ ----------------------------------------------------------------------\n\/\/ Includes\n\/\/ ----------------------------------------------------------------------\n#include \n#include \n#include \n#include \n#include \n\n\/\/ ----------------------------------------------------------------------\n\/\/ Function definitions\n\/\/ ----------------------------------------------------------------------\nfapi2::ReturnCode p9_pm_firinit(\n const fapi2::Target& i_target,\n const p9pm::PM_FLOW_MODE i_mode)\n{\n FAPI_IMP(\"p9_pm_firinit start\");\n\n fapi2::ReturnCode l_rc;\n uint8_t l_pm_firinit_flag;\n fapi2::buffer l_data64;\n\n \/\/ CHECKING FOR FIRS BEFORE RESET and INIT\n\n FAPI_DBG(\"Checking OCC FIRs\");\n FAPI_TRY(fapi2::getScom(i_target, PERV_TP_OCC_SCOM_OCCLFIR, l_data64),\n \"ERROR: Failed to fetch OCC FIR\");\n\n if(l_data64)\n {\n FAPI_INF(\"WARNING: OCC has active errors\");\n }\n\n FAPI_DBG(\"Checking PBA FIRs\");\n FAPI_TRY(fapi2::getScom(i_target, PU_PBAFIR , l_data64),\n \"ERROR: Failed to fetch PBA FIR\");\n\n if(l_data64)\n {\n FAPI_INF(\"WARNING: PBA has active error(s)\");\n }\n\n \/\/ Handle OCC FIRs, Masks and actions\n FAPI_DBG(\"Calling OCC firinit ...\");\n FAPI_EXEC_HWP(l_rc, p9_pm_occ_firinit, i_target, i_mode);\n FAPI_TRY(l_rc);\n\n \/\/ Handle PBA FIRs, Masks and actions\n FAPI_DBG(\"Calling PBA firinit ...\");\n FAPI_EXEC_HWP(l_rc, p9_pm_pba_firinit, i_target, i_mode);\n FAPI_TRY(l_rc);\n\n \/\/ Handle Core and Quad errors\n FAPI_DBG(\"Calling PPM firinit ...\");\n FAPI_EXEC_HWP(l_rc, p9_pm_ppm_firinit, i_target, i_mode);\n FAPI_TRY(l_rc);\n\n \/\/ Handle CME FIRs, Masks and actions\n FAPI_DBG(\"Calling CME firinit ...\");\n FAPI_EXEC_HWP(l_rc, p9_pm_cme_firinit, i_target, i_mode);\n FAPI_TRY(l_rc);\n\n FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_PM_FIRINIT_DONE_ONCE_FLAG, i_target,\n l_pm_firinit_flag),\n \"ERROR: Failed to fetch the firinit call status flag\");\n\n \/\/ Set the ATTR_PM_FIRINIT_DONE_ONCE_FLAG attribute\n if (i_mode == p9pm::PM_INIT)\n {\n if (l_pm_firinit_flag != 1)\n {\n l_pm_firinit_flag = 1;\n FAPI_TRY(FAPI_ATTR_SET(fapi2::ATTR_PM_FIRINIT_DONE_ONCE_FLAG,\n i_target, l_pm_firinit_flag),\n \"ERROR: Failed to set firinit call status after init\");\n }\n }\n else if (i_mode == p9pm::PM_RESET)\n {\n if (l_pm_firinit_flag != 1)\n {\n l_pm_firinit_flag = 2;\n FAPI_TRY(FAPI_ATTR_SET(fapi2::ATTR_PM_FIRINIT_DONE_ONCE_FLAG,\n i_target, l_pm_firinit_flag),\n \"ERROR: Failed to set firinit call status after reset\");\n }\n }\n\nfapi_try_exit:\n FAPI_INF(\"p9_pm_firinit end\");\n return fapi2::current_err;\n} \/\/ END p9_pm_firinit\n<|endoftext|>"} {"text":"\/*\n* Darwin SecRandomCopyBytes EntropySource\n* (C) 2015 Daniel Seither (Kullo GmbH)\n*\n* Botan is released under the Simplified BSD License (see license.txt)\n*\/\n\n#include \n#include \n#include \n\nnamespace Botan {\n\n\/**\n* Gather entropy from SecRandomCopyBytes\n*\/\nsize_t Darwin_SecRandom::poll(RandomNumberGenerator& rng)\n {\n secure_vector buf(BOTAN_SYSTEM_RNG_POLL_REQUEST);\n\n if(0 == SecRandomCopyBytes(kSecRandomDefault, buf.size(), buf.data()))\n {\n rng.add_entropy(buf.data(), buf.size());\n return buf.size() * 8;\n }\n }\n\n}\nReturn 0 bits in Darwin_SecRandom::poll on SecRandomCopyBytes failure\/*\n* Darwin SecRandomCopyBytes EntropySource\n* (C) 2015 Daniel Seither (Kullo GmbH)\n*\n* Botan is released under the Simplified BSD License (see license.txt)\n*\/\n\n#include \n#include \n#include \n\nnamespace Botan {\n\n\/**\n* Gather entropy from SecRandomCopyBytes\n*\/\nsize_t Darwin_SecRandom::poll(RandomNumberGenerator& rng)\n {\n secure_vector buf(BOTAN_SYSTEM_RNG_POLL_REQUEST);\n\n if(0 == SecRandomCopyBytes(kSecRandomDefault, buf.size(), buf.data()))\n {\n rng.add_entropy(buf.data(), buf.size());\n return buf.size() * 8;\n }\n\n return 0;\n }\n\n}\n<|endoftext|>"} {"text":"\/\/\n\/\/ calcPWP.cpp\n\/\/ \n\/\/\n\/\/ Created by Evan McCartney-Melstad on 1\/10\/15.\n\/\/\n\/\/\n\n#include \"calcPWP.h\"\n#include \n#include \n#include \n#include \n#include \n\n\nint calcPWPfromBinaryFile (std::string binaryFile, unsigned long long int numLoci, const int numIndividuals, std::string outFile, int numThreads) {\n \n \/\/****MODIFY THIS TO ONLY READ IN N LOCI AT A TIME, INSTEAD OF USING THE ENTIRE FILE****\n \n std::cout << \"Number of threads: \" << numThreads << std::endl;\n std::streampos size;\n std::ifstream file (binaryFile, std::ios::in|std::ios::binary|std::ios::ate);\n \/\/ifstream file (\"test500k.binary8bitunsigned\", ios::in|ios::binary|ios::ate);\n if (file.is_open()) {\n size = file.tellg(); \/\/ Just a variable that shows position of stream--at end since ios::ate, so it's the file size. PROBABLY WON'T WORK FOR FILES LARGER THAN ~ 2GB!\n file.seekg (0, std::ios::beg); \/\/ Go back to the beginning of the file\n \/\/file.read((char*)readCounts, size); \/\/ cast to a char* to give to file.read\n \n \/\/unsigned char* readCounts;\n \/\/readCounts = new unsigned char[size];\n std::vector readCounts(size);\n file.read((char*) &readCounts[0], size);\n file.close();\n \n std::cout << \"the entire file content is in memory\" << std::endl;\n std::cout << \"the total size of the file is \" << size << std::endl;\n std::cout << \"the number of elements in the readCounts vector is: \" << readCounts.size() << std::endl; \/\/ Will give the total size bytes divided by the size of one element--so it gives the number of elements\n \n \/* We are going to split the loci between numThreads threads. Each thread will modify two multidimensional\n vectors of the forms std::vector< std::vector > pwp(numIndividuals, std::vector(numIndividuals,0)) and std::vector< std::vector > weightings(numIndividuals, std::vector(numIndividuals,0))\n \n First, we'll generate all of these vectors, which apparently in C++ needs to be constructed of a\n vector of two-dimensional vectors...\n *\/\n std::vector>> pwpThreads(numThreads, std::vector> (numIndividuals, std::vector (numIndividuals,0) ) ); \/\/pwpThreads[0] is the first 2D array for the first thread, etc...\n std::vector>> weightingsThreads(numThreads, std::vector > (numIndividuals, std::vector (numIndividuals,0) ) );\n \n std::cout << \"Initialized the 3d vectors\" << std::endl;\n \n \/\/ Now we need to determine how many loci for each thread. If we want to use the entire binary file, instead of numLoci loci, then change this to lociPerThread = (size\/(numIndividuals*2))\/numThreads\n \/\/unsigned long long int lociPerThread = numLoci \/ numThreads;\n \n \/\/unsigned long long int lociPerThread = (readCounts.size()-1)\/numThreads; \/\/ loci starts with 0, so need to subtract 1 from numLoci\n unsigned long long int lociPerThread;\n if (numLoci == 0) {\n lociPerThread = (unsigned long long)(size\/(numIndividuals*2))\/(unsigned long long)numThreads;\n } else {\n lociPerThread = (unsigned long long)numLoci\/(unsigned long long)numThreads;\n }\n \n \n \n\n std::cout << \"Initialized lociPerThread with \" << numLoci << std::endl;\n \n std::vector threadsVec;\n for (int threadRunning = 0; threadRunning < numThreads; threadRunning++) {\n std::cout << \"Got to the function call. Running thread # \" << threadRunning << std::endl;\n unsigned long long int firstLocus = (unsigned long long int) threadRunning * lociPerThread;\n unsigned long long int finishingLocus = ((unsigned long long int) threadRunning * lociPerThread) + lociPerThread - (unsigned long long)1.0;\n std::cout << \"Set firstLocus to \" << firstLocus << \" and finishingLocus to \" << finishingLocus << std::endl;\n \n threadsVec.push_back(std::thread(calcPWPforRange, firstLocus, finishingLocus, numIndividuals, std::ref(readCounts), std::ref(pwpThreads[threadRunning]), std::ref(weightingsThreads[threadRunning])));\n }\n \n \/\/ Wait on threads to finish\n for (int i = 0; i < numThreads; ++i) {\n threadsVec[i].join();\n std::cout << \"Joined thread \" << i << std::endl;\n }\n std::cout << \"All threads completed running\" << std::endl;\n \n \n \n \/\/ Now aggregate the results of the threads and print final results\n std::vector> weightingsSum(numIndividuals, std::vector(numIndividuals,0));\n std::vector> pwpSum(numIndividuals, std::vector(numIndividuals,0));\n \n for (int tortoise = 0; tortoise < numIndividuals; tortoise++) {\n for (int comparisonTortoise = 0; comparisonTortoise <= tortoise; comparisonTortoise++) {\n for (int threadVector = 0; threadVector < numThreads; threadVector++) {\n weightingsSum[tortoise][comparisonTortoise] += weightingsThreads[threadVector][tortoise][comparisonTortoise];\n pwpSum[tortoise][comparisonTortoise] += pwpThreads[threadVector][tortoise][comparisonTortoise];\n }\n }\n }\n \n \n \n std::cout << \"Finished summing the threads vectors\" << std::endl;\n \n \n \/\/ Now print out the final output to the pairwise pi file:\n std::ofstream pwpOUT (outFile);\n int rowCounter = 0;\n if (!pwpOUT) {\n std::cerr << \"Crap, \" << outFile << \"didn't open!\" << std::endl;\n } else {\n for (int tortoise=0; tortoise < numIndividuals; tortoise++) {\n for (int comparisonTortoise = 0; comparisonTortoise <= tortoise; comparisonTortoise++) {\n rowCounter++;\n \n \/\/std::cout << \"Made it past the beginning of the last end for loop\" << std::endl;\n \/\/std::cout << \"Tortoise numbers: \" << tortoise << \" and \" << comparisonTortoise << std::endl;\n if (weightingsSum[tortoise][comparisonTortoise] > 0) {\n \/\/std::cout << weightings[tortoise][comparisonTortoise] << std::endl;\n \/\/std::cout << pwp[tortoise][comparisonTortoise] \/ weightings[tortoise][comparisonTortoise] << std::endl;\n std::cout << std::fixed;\n std::cout << \"Weightings for tortoise \" << tortoise << \" and comparisonTortoise \" << comparisonTortoise << \" : \" << weightingsSum[tortoise][comparisonTortoise] << std::endl;\n std::cout << \"PWP for tortoise \" << tortoise << \" and comparisonTortoise \" << comparisonTortoise << \" : \" << pwpSum[tortoise][comparisonTortoise] << std::endl;\n std::cout << std::scientific;\n pwpOUT << pwpSum[tortoise][comparisonTortoise] \/ weightingsSum[tortoise][comparisonTortoise] << std::endl;\n } else {\n pwpOUT << \"NA\" << std::endl;\n }\n }\n }\n }\n } else std::cout << \"Unable to open file\";\n \n return 0;\n}\n\n\n\/\/int calcPWPforRange (unsigned long long startingLocus, unsigned long long endingLocus, int numIndividuals, const std::vector& mainReadCountVector, std::vector< std::vector > & threadPWP, std::vector< std::vector > & threadWeightings) {\nint calcPWPforRange (unsigned long long startingLocus, unsigned long long endingLocus, int numIndividuals, std::vector& mainReadCountVector, std::vector>& threadPWP, std::vector>& threadWeightings) {\n \n std::cout << \"Calculating PWP for the following locus range: \" << startingLocus << \" to \" << endingLocus << std::endl;\n for( unsigned long long locus = startingLocus; locus < endingLocus; locus++) {\n \/\/std::cout << \"Processing locus # \" << locus << std::endl;\n if (locus % 100000 == 0) {\n std::cout << locus << \" loci processed through calcPWPfromBinaryFile\" << std::endl;\n }\n \n unsigned long long coverages[numIndividuals];\n long double *majorAlleleFreqs = new long double[numIndividuals]; \/\/ This will hold the major allele frequencies for that locus for each tortoise\n \n for( int tortoise = 0; tortoise < numIndividuals; tortoise++ ) {\n unsigned long long majorIndex = locus * (numIndividuals*2) + 2 * tortoise;\n unsigned long long minorIndex = locus * (numIndividuals*2) + 2 * tortoise + 1;\n \n coverages[tortoise] = int(mainReadCountVector[majorIndex]) + int(mainReadCountVector[minorIndex]); \/\/ Hold the coverages for each locus\n if ( coverages[tortoise] > 0 ) {\n \/\/std::cout << \"Made it to line 222 for locus \" << locus << std::endl;\n majorAlleleFreqs[tortoise] = (long double)mainReadCountVector[majorIndex] \/ (long double)coverages[tortoise]; \/\/ Not necessarily an int, but could be 0 or 1\n\n if (coverages[tortoise] > 1) {\n unsigned long long locusWeighting = (unsigned long long) (coverages[tortoise]*(coverages[tortoise]-1));\n threadWeightings[tortoise][tortoise] += (unsigned long long)locusWeighting; \/\/ This is an int--discrete number of reads\n \n threadPWP[tortoise][tortoise] += (long double)(locusWeighting) * ((long double)2.0 * majorAlleleFreqs[tortoise] * ((long double)(coverages[tortoise]) - (long double)(mainReadCountVector[majorIndex])) \/ (long double)((coverages[tortoise])-(long double)1.0));\n \n \/\/Cancel out the \"coverages[tortoise]-1\"\n \/\/threadPWP[tortoise][tortoise] += (long double)(coverages[tortoise]) * ((long double)2.0 * majorAlleleFreqs[tortoise] * ((long double)(coverages[tortoise]) - (long double)(mainReadCountVector[majorIndex])));\n \/\/threadPWP[tortoise][tortoise] += (long double)(locusWeighting) * ((long double)2.0 * majorAlleleFreqs[tortoise] * ((long double)(coverages[tortoise]) - (long double)(mainReadCountVector[majorIndex])) \/ (long double)((coverages[tortoise]-1)));\n \n \/\/threadPWP[tortoise][tortoise] += locusWeighting*(2*majorAlleleFreqs[tortoise] * (coverages[tortoise]-majorReadCounts)) \/ (coverages[tortoise]-1)\n }\n \n for( int comparisonTortoise = 0; comparisonTortoise < tortoise; comparisonTortoise++) {\n if (coverages[comparisonTortoise] > 0) {\n long double locusWeighting = (long double)coverages[tortoise] * (long double)(coverages[comparisonTortoise]);\n \n threadWeightings[tortoise][comparisonTortoise] += locusWeighting;\n \n threadPWP[tortoise][comparisonTortoise] += (long double)locusWeighting * (majorAlleleFreqs[tortoise] * ((long double)1.0-majorAlleleFreqs[comparisonTortoise]) + majorAlleleFreqs[comparisonTortoise] * ((long double)1.0-majorAlleleFreqs[tortoise]));\n }\n }\n }\n }\n delete[] majorAlleleFreqs; \/\/ Needed to avoid memory leaks\n }\n std::cout << \"Finished thread ending on locus \" << endingLocus << std::endl;\n return 0;\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nMinor changes\/\/\n\/\/ calcPWP.cpp\n\/\/ \n\/\/\n\/\/ Created by Evan McCartney-Melstad on 1\/10\/15.\n\/\/\n\/\/\n\n#include \"calcPWP.h\"\n#include \n#include \n#include \n#include \n#include \n\n\nint calcPWPfromBinaryFile (std::string binaryFile, unsigned long long int numLoci, const int numIndividuals, std::string outFile, int numThreads) {\n \n \/\/****MODIFY THIS TO ONLY READ IN N LOCI AT A TIME, INSTEAD OF USING THE ENTIRE FILE****\n \n std::cout << \"Number of threads: \" << numThreads << std::endl;\n std::streampos size;\n std::ifstream file (binaryFile, std::ios::in|std::ios::binary|std::ios::ate);\n \/\/ifstream file (\"test500k.binary8bitunsigned\", ios::in|ios::binary|ios::ate);\n if (file.is_open()) {\n size = file.tellg(); \/\/ Just a variable that shows position of stream--at end since ios::ate, so it's the file size. PROBABLY WON'T WORK FOR FILES LARGER THAN ~ 2GB!\n file.seekg (0, std::ios::beg); \/\/ Go back to the beginning of the file\n \/\/file.read((char*)readCounts, size); \/\/ cast to a char* to give to file.read\n \n \/\/unsigned char* readCounts;\n \/\/readCounts = new unsigned char[size];\n std::vector readCounts(size);\n file.read((char*) &readCounts[0], size);\n file.close();\n \n std::cout << \"the entire file content is in memory\" << std::endl;\n std::cout << \"the total size of the file is \" << size << std::endl;\n std::cout << \"the number of elements in the readCounts vector is: \" << readCounts.size() << std::endl; \/\/ Will give the total size bytes divided by the size of one element--so it gives the number of elements\n \n \/* We are going to split the loci between numThreads threads. Each thread will modify two multidimensional\n vectors of the forms std::vector< std::vector > pwp(numIndividuals, std::vector(numIndividuals,0)) and std::vector< std::vector > weightings(numIndividuals, std::vector(numIndividuals,0))\n \n First, we'll generate all of these vectors, which apparently in C++ needs to be constructed of a\n vector of two-dimensional vectors...\n *\/\n std::vector>> pwpThreads(numThreads, std::vector> (numIndividuals, std::vector (numIndividuals,0) ) ); \/\/pwpThreads[0] is the first 2D array for the first thread, etc...\n std::vector>> weightingsThreads(numThreads, std::vector > (numIndividuals, std::vector (numIndividuals,0) ) );\n \n std::cout << \"Initialized the 3d vectors\" << std::endl;\n \n \/\/ Now we need to determine how many loci for each thread. If we want to use the entire binary file, instead of numLoci loci, then change this to lociPerThread = (size\/(numIndividuals*2))\/numThreads\n \/\/unsigned long long int lociPerThread = numLoci \/ numThreads;\n \n \/\/unsigned long long int lociPerThread = (readCounts.size()-1)\/numThreads; \/\/ loci starts with 0, so need to subtract 1 from numLoci\n unsigned long long int lociPerThread;\n if (numLoci == 0) {\n lociPerThread = (unsigned long long)(size\/(numIndividuals*2))\/(unsigned long long)numThreads;\n } else {\n lociPerThread = (unsigned long long)numLoci\/(unsigned long long)numThreads;\n }\n \n \n \n\n std::cout << \"Initialized lociPerThread with \" << numLoci << std::endl;\n \n std::vector threadsVec;\n for (int threadRunning = 0; threadRunning < numThreads; threadRunning++) {\n std::cout << \"Got to the function call. Running thread # \" << threadRunning << std::endl;\n unsigned long long int firstLocus = (unsigned long long int) threadRunning * lociPerThread;\n unsigned long long int finishingLocus = ((unsigned long long int) threadRunning * lociPerThread) + lociPerThread - (unsigned long long)1.0;\n std::cout << \"Set firstLocus to \" << firstLocus << \" and finishingLocus to \" << finishingLocus << std::endl;\n \n threadsVec.push_back(std::thread(calcPWPforRange, firstLocus, finishingLocus, numIndividuals, std::ref(readCounts), std::ref(pwpThreads[threadRunning]), std::ref(weightingsThreads[threadRunning])));\n }\n \n \/\/ Wait on threads to finish\n for (int i = 0; i < numThreads; ++i) {\n threadsVec[i].join();\n std::cout << \"Joined thread \" << i << std::endl;\n }\n std::cout << \"All threads completed running\" << std::endl;\n \n \n \n \/\/ Now aggregate the results of the threads and print final results\n std::vector> weightingsSum(numIndividuals, std::vector(numIndividuals,0));\n std::vector> pwpSum(numIndividuals, std::vector(numIndividuals,0));\n \n for (int tortoise = 0; tortoise < numIndividuals; tortoise++) {\n for (int comparisonTortoise = 0; comparisonTortoise <= tortoise; comparisonTortoise++) {\n for (int threadVector = 0; threadVector < numThreads; threadVector++) {\n weightingsSum[tortoise][comparisonTortoise] += weightingsThreads[threadVector][tortoise][comparisonTortoise];\n pwpSum[tortoise][comparisonTortoise] += pwpThreads[threadVector][tortoise][comparisonTortoise];\n }\n }\n }\n \n \n \n std::cout << \"Finished summing the threads vectors\" << std::endl;\n \n \n \/\/ Now print out the final output to the pairwise pi file:\n std::ofstream pwpOUT (outFile);\n int rowCounter = 0;\n if (!pwpOUT) {\n std::cerr << \"Crap, \" << outFile << \"didn't open!\" << std::endl;\n } else {\n for (int tortoise=0; tortoise < numIndividuals; tortoise++) {\n for (int comparisonTortoise = 0; comparisonTortoise <= tortoise; comparisonTortoise++) {\n rowCounter++;\n \n \/\/std::cout << \"Made it past the beginning of the last end for loop\" << std::endl;\n \/\/std::cout << \"Tortoise numbers: \" << tortoise << \" and \" << comparisonTortoise << std::endl;\n if (weightingsSum[tortoise][comparisonTortoise] > 0) {\n \/\/std::cout << weightings[tortoise][comparisonTortoise] << std::endl;\n \/\/std::cout << pwp[tortoise][comparisonTortoise] \/ weightings[tortoise][comparisonTortoise] << std::endl;\n std::cout << std::fixed;\n std::cout << \"Weightings for tortoise \" << tortoise << \" and comparisonTortoise \" << comparisonTortoise << \" : \" << weightingsSum[tortoise][comparisonTortoise] << std::endl;\n std::cout << \"PWP for tortoise \" << tortoise << \" and comparisonTortoise \" << comparisonTortoise << \" : \" << pwpSum[tortoise][comparisonTortoise] << std::endl;\n std::cout << std::scientific;\n pwpOUT << pwpSum[tortoise][comparisonTortoise] \/ weightingsSum[tortoise][comparisonTortoise] << std::endl;\n } else {\n pwpOUT << \"NA\" << std::endl;\n }\n }\n }\n }\n } else std::cout << \"Unable to open file\";\n \n return 0;\n}\n\n\n\/\/int calcPWPforRange (unsigned long long startingLocus, unsigned long long endingLocus, int numIndividuals, const std::vector& mainReadCountVector, std::vector< std::vector > & threadPWP, std::vector< std::vector > & threadWeightings) {\nint calcPWPforRange (unsigned long long startingLocus, unsigned long long endingLocus, int numIndividuals, std::vector& mainReadCountVector, std::vector>& threadPWP, std::vector>& threadWeightings) {\n \n std::cout << \"Calculating PWP for the following locus range: \" << startingLocus << \" to \" << endingLocus << std::endl;\n for( unsigned long long locus = startingLocus; locus < endingLocus; locus++) {\n \/\/std::cout << \"Processing locus # \" << locus << std::endl;\n if (locus % 100000 == 0) {\n std::cout << locus << \" loci processed through calcPWPfromBinaryFile\" << std::endl;\n }\n \n unsigned long long coverages[numIndividuals];\n long double *majorAlleleFreqs = new long double[numIndividuals]; \/\/ This will hold the major allele frequencies for that locus for each tortoise\n \n for( int tortoise = 0; tortoise < numIndividuals; tortoise++ ) {\n unsigned long long majorIndex = locus * (numIndividuals*2) + 2 * tortoise;\n unsigned long long minorIndex = locus * (numIndividuals*2) + 2 * tortoise + 1;\n \n coverages[tortoise] = int(mainReadCountVector[majorIndex]) + int(mainReadCountVector[minorIndex]); \/\/ Hold the coverages for each locus\n if ( coverages[tortoise] > 0 ) {\n \/\/std::cout << \"Made it to line 222 for locus \" << locus << std::endl;\n majorAlleleFreqs[tortoise] = (long double)mainReadCountVector[majorIndex] \/ (long double)coverages[tortoise]; \/\/ Not necessarily an int, but could be 0 or 1\n\n if (coverages[tortoise] > 1) {\n \/\/unsigned long long locusWeighting = (unsigned long long) (coverages[tortoise]*(coverages[tortoise]-1));\n unsigned long long locusWeighting = (unsigned long long) (coverages[tortoise]*(coverages[tortoise]));\n threadWeightings[tortoise][tortoise] += (unsigned long long)locusWeighting; \/\/ This is an int--discrete number of reads\n \n threadPWP[tortoise][tortoise] += (unsigned long long) (coverages[tortoise]*(coverages[tortoise]-1)) * ((long double)2.0 * majorAlleleFreqs[tortoise] * ((long double)(coverages[tortoise]) - (long double)(mainReadCountVector[majorIndex])) \/ (long double)((coverages[tortoise])-(long double)1.0));\n \n \/\/Cancel out the \"coverages[tortoise]-1\"\n \/\/threadPWP[tortoise][tortoise] += (long double)(coverages[tortoise]) * ((long double)2.0 * majorAlleleFreqs[tortoise] * ((long double)(coverages[tortoise]) - (long double)(mainReadCountVector[majorIndex])));\n \/\/threadPWP[tortoise][tortoise] += (long double)(locusWeighting) * ((long double)2.0 * majorAlleleFreqs[tortoise] * ((long double)(coverages[tortoise]) - (long double)(mainReadCountVector[majorIndex])) \/ (long double)((coverages[tortoise]-1)));\n \n \/\/threadPWP[tortoise][tortoise] += locusWeighting*(2*majorAlleleFreqs[tortoise] * (coverages[tortoise]-majorReadCounts)) \/ (coverages[tortoise]-1)\n }\n \n for( int comparisonTortoise = 0; comparisonTortoise < tortoise; comparisonTortoise++) {\n if (coverages[comparisonTortoise] > 0) {\n long double locusWeighting = (long double)coverages[tortoise] * (long double)(coverages[comparisonTortoise]);\n \n threadWeightings[tortoise][comparisonTortoise] += locusWeighting;\n \n threadPWP[tortoise][comparisonTortoise] += (long double)locusWeighting * (majorAlleleFreqs[tortoise] * ((long double)1.0-majorAlleleFreqs[comparisonTortoise]) + majorAlleleFreqs[comparisonTortoise] * ((long double)1.0-majorAlleleFreqs[tortoise]));\n }\n }\n }\n }\n delete[] majorAlleleFreqs; \/\/ Needed to avoid memory leaks\n }\n std::cout << \"Finished thread ending on locus \" << endingLocus << std::endl;\n return 0;\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * $RCSfile: sdmod.hxx,v $\n *\n * $Revision: 1.22 $\n *\n * last change: $Author: rt $ $Date: 2004-08-23 08:12:23 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef _SDMOD_HXX\n#define _SDMOD_HXX\n\n\n#ifndef _SDDLL_HXX\n#define _SD_DLL \/\/ fuer SD_MOD()\n#include \"sddll.hxx\" \/\/ fuer SdModuleDummy\n#endif\n#ifndef _SD_GLOB_HXX\n#include \"glob.hxx\"\n#endif\n#ifndef _PRESENTATION_HXX\n#include \"pres.hxx\"\n#endif\n#ifndef INCLUDED_SDDLLAPI_H\n#include \"sddllapi.h\"\n#endif\n\n#ifndef _SVSTOR_HXX\n#include \n#endif\n#ifndef _SFXLSTNER_HXX\n#include \n#endif\n#ifndef _COM_SUN_STAR_TEXT_WRITINGMODE_HPP_\n#include \n#endif\n\n#ifndef _SFXMODULE_HXX\n#include \n#endif\n\n#ifndef INCLUDED_MEMORY\n#include \n#define INCLUDED_MEMORY\n#endif\n\nclass SdOptions;\nclass BasicIDE;\nclass SvxSearchItem;\nclass SdAppLinkHdl; ;\nclass SvxErrorHandler;\nclass EditFieldInfo;\nclass SvFactory;\nclass SdTransferable;\nclass SvNumberFormatter;\nclass SfxErrorHandler;\nclass OutputDevice;\nclass SdPage;\nclass SdDrawDocument;\n\nnamespace sd {\nclass DrawDocShell;\nclass SdGlobalResourceContainer;\n}\n\n\/\/ ----------------------\n\/\/ - SdOptionStreamMode -\n\/\/ ----------------------\n\nenum SdOptionStreamMode\n{\n SD_OPTION_LOAD = 0,\n SD_OPTION_STORE = 1\n};\n\n\/*************************************************************************\n|*\n|* This subclass of (which is a subclass of ) is\n|* linked to the DLL. One instance of this class exists while the DLL is\n|* loaded.\n|*\n|* SdModule is like to be compared with the -subclass.\n|*\n|* Remember: Don`t export this class! It uses DLL-internal symbols.\n|*\n\\************************************************************************\/\n\nclass SdModule : public SfxModule, public SfxListener\n{\npublic:\n\n TYPEINFO();\n SFX_DECL_INTERFACE(SD_IF_SDAPP);\n DECL_LINK( CalcFieldValueHdl, EditFieldInfo* );\n\n SdModule(SfxObjectFactory* pDrawObjFact, SfxObjectFactory* pGraphicObjFact);\n virtual ~SdModule();\n\n SdTransferable* pTransferClip;\n SdTransferable* pTransferDrag;\n SdTransferable* pTransferSelection;\n\n void Execute(SfxRequest& rReq);\n void GetState(SfxItemSet&);\n\n virtual void FillStatusBar(StatusBar& rBar);\n\n SdOptions* GetSdOptions(DocumentType eDocType);\n SD_DLLPUBLIC SvStorageStreamRef GetOptionStream( const String& rOptionName, SdOptionStreamMode eMode );\n\n BOOL GetWaterCan() const { return bWaterCan; }\n void SetWaterCan( BOOL bWC ) { bWaterCan = bWC; }\n\n SvxSearchItem* GetSearchItem() { return (pSearchItem); }\n void SetSearchItem(SvxSearchItem* pItem) { pSearchItem = pItem; }\n\n \/** Return the virtual device that can be used for printer independent\n layout.\n @return\n The returned pointer is NULL when the device could not be\n created when this modules was instantiated.\n *\/\n OutputDevice* GetVirtualRefDevice (void);\n\n \/** Deprecated alias to GetVirtualRefDevice<\/member>.\n @param rDocShell\n Unused dummy parameter.\n *\/\n OutputDevice* GetRefDevice (::sd::DrawDocShell& rDocShell);\n\n SD_DLLPUBLIC SvNumberFormatter* GetNumberFormatter();\n\n ::com::sun::star::text::WritingMode GetDefaultWritingMode() const;\n\n \/\/virtuelle Methoden fuer den Optionendialog\n virtual SfxItemSet* CreateItemSet( USHORT nId );\n virtual void ApplyItemSet( USHORT nId, const SfxItemSet& rSet );\n virtual SfxTabPage* CreateTabPage( USHORT nId, Window* pParent, const SfxItemSet& rSet );\n\nprotected:\n\n SdOptions* pImpressOptions;\n SdOptions* pDrawOptions;\n SvxSearchItem* pSearchItem;\n SvNumberFormatter* pNumberFormatter;\n SvStorageRef xOptionStorage;\n BOOL bAutoSave;\n BOOL bWaterCan;\n SfxErrorHandler* mpErrorHdl;\n \/** This device is used for printer independent layout. It is virtual\n in the sense that it does not represent a printer. The pointer may\n be NULL when the virtual device could not be created.\n *\/\n OutputDevice* mpVirtualRefDevice;\n\n virtual void Notify( SfxBroadcaster& rBC, const SfxHint& rHint );\n\nprivate:\n \/** The resource container controls the lifetime of some singletons.\n *\/\n ::std::auto_ptr< ::sd::SdGlobalResourceContainer> mpResourceContainer;\n\n \/** Create a new summary page. When the document has been created in\n the kiosk mode with automatical transitions then this method adds\n this kind of transition to the new summary page.\n @param pViewFrame\n The view frame that is used to execute the slot for creating the\n summary page.\n @param pDocument\n The document which will contain the summary page and from which\n the information about the default transition is retrieved.\n *\/\n void AddSummaryPage (SfxViewFrame* pViewFrame, SdDrawDocument* pDocument);\n\n \/** Take an outline from a text document and create a new impress\n document according to the structure of the outline.\n @param rRequest\n This typically is the unmodified request from a execute()\n function from where this function is called.\n *\/\n void OutlineToImpress (SfxRequest& rRequest);\n};\n\n\n\n\n#ifndef SD_MOD\n#define SD_MOD() ( *(SdModule**) GetAppData(SHL_DRAW) )\n#endif\n\n#endif \/\/ _SDMOD_HXX\n\nINTEGRATION: CWS mav09 (1.20.82); FILE MERGED 2004\/09\/16 17:58:18 mav 1.20.82.2: RESYNC: (1.20-1.22); FILE MERGED 2004\/04\/14 14:11:52 mba 1.20.82.1: #i27773#: remove so3; new storage API\/*************************************************************************\n *\n * $RCSfile: sdmod.hxx,v $\n *\n * $Revision: 1.23 $\n *\n * last change: $Author: kz $ $Date: 2004-10-04 18:15:08 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef _SDMOD_HXX\n#define _SDMOD_HXX\n\n\n#ifndef _SDDLL_HXX\n#define _SD_DLL \/\/ fuer SD_MOD()\n#include \"sddll.hxx\" \/\/ fuer SdModuleDummy\n#endif\n#ifndef _SD_GLOB_HXX\n#include \"glob.hxx\"\n#endif\n#ifndef _PRESENTATION_HXX\n#include \"pres.hxx\"\n#endif\n\n#include \n#include \n\n#ifndef INCLUDED_SDDLLAPI_H\n#include \"sddllapi.h\"\n#endif\n\n#ifndef _SFXLSTNER_HXX\n#include \n#endif\n#ifndef _COM_SUN_STAR_TEXT_WRITINGMODE_HPP_\n#include \n#endif\n\n#ifndef _SFXMODULE_HXX\n#include \n#endif\n\n#ifndef INCLUDED_MEMORY\n#include \n#define INCLUDED_MEMORY\n#endif\n\nclass SdOptions;\nclass BasicIDE;\nclass SvxSearchItem;\nclass SdAppLinkHdl; ;\nclass SvxErrorHandler;\nclass EditFieldInfo;\nclass SvFactory;\nclass SdTransferable;\nclass SvNumberFormatter;\nclass SfxErrorHandler;\nclass OutputDevice;\nclass SdPage;\nclass SdDrawDocument;\n\nnamespace sd {\nclass DrawDocShell;\nclass SdGlobalResourceContainer;\n}\n\n\/\/ ----------------------\n\/\/ - SdOptionStreamMode -\n\/\/ ----------------------\n\nenum SdOptionStreamMode\n{\n SD_OPTION_LOAD = 0,\n SD_OPTION_STORE = 1\n};\n\n\/*************************************************************************\n|*\n|* This subclass of (which is a subclass of ) is\n|* linked to the DLL. One instance of this class exists while the DLL is\n|* loaded.\n|*\n|* SdModule is like to be compared with the -subclass.\n|*\n|* Remember: Don`t export this class! It uses DLL-internal symbols.\n|*\n\\************************************************************************\/\n\nclass SdModule : public SfxModule, public SfxListener\n{\npublic:\n\n TYPEINFO();\n SFX_DECL_INTERFACE(SD_IF_SDAPP);\n DECL_LINK( CalcFieldValueHdl, EditFieldInfo* );\n\n SdModule(SfxObjectFactory* pDrawObjFact, SfxObjectFactory* pGraphicObjFact);\n virtual ~SdModule();\n\n SdTransferable* pTransferClip;\n SdTransferable* pTransferDrag;\n SdTransferable* pTransferSelection;\n\n void Execute(SfxRequest& rReq);\n void GetState(SfxItemSet&);\n\n virtual void FillStatusBar(StatusBar& rBar);\n\n SdOptions* GetSdOptions(DocumentType eDocType);\n SD_DLLPUBLIC SvStorageStreamRef GetOptionStream( const String& rOptionName, SdOptionStreamMode eMode );\n\n BOOL GetWaterCan() const { return bWaterCan; }\n void SetWaterCan( BOOL bWC ) { bWaterCan = bWC; }\n\n SvxSearchItem* GetSearchItem() { return (pSearchItem); }\n void SetSearchItem(SvxSearchItem* pItem) { pSearchItem = pItem; }\n\n \/** Return the virtual device that can be used for printer independent\n layout.\n @return\n The returned pointer is NULL when the device could not be\n created when this modules was instantiated.\n *\/\n OutputDevice* GetVirtualRefDevice (void);\n\n \/** Deprecated alias to GetVirtualRefDevice<\/member>.\n @param rDocShell\n Unused dummy parameter.\n *\/\n OutputDevice* GetRefDevice (::sd::DrawDocShell& rDocShell);\n\n SD_DLLPUBLIC SvNumberFormatter* GetNumberFormatter();\n\n ::com::sun::star::text::WritingMode GetDefaultWritingMode() const;\n\n \/\/virtuelle Methoden fuer den Optionendialog\n virtual SfxItemSet* CreateItemSet( USHORT nId );\n virtual void ApplyItemSet( USHORT nId, const SfxItemSet& rSet );\n virtual SfxTabPage* CreateTabPage( USHORT nId, Window* pParent, const SfxItemSet& rSet );\n\nprotected:\n\n SdOptions* pImpressOptions;\n SdOptions* pDrawOptions;\n SvxSearchItem* pSearchItem;\n SvNumberFormatter* pNumberFormatter;\n SvStorageRef xOptionStorage;\n BOOL bAutoSave;\n BOOL bWaterCan;\n SfxErrorHandler* mpErrorHdl;\n \/** This device is used for printer independent layout. It is virtual\n in the sense that it does not represent a printer. The pointer may\n be NULL when the virtual device could not be created.\n *\/\n OutputDevice* mpVirtualRefDevice;\n\n virtual void Notify( SfxBroadcaster& rBC, const SfxHint& rHint );\n\nprivate:\n \/** The resource container controls the lifetime of some singletons.\n *\/\n ::std::auto_ptr< ::sd::SdGlobalResourceContainer> mpResourceContainer;\n\n \/** Create a new summary page. When the document has been created in\n the kiosk mode with automatical transitions then this method adds\n this kind of transition to the new summary page.\n @param pViewFrame\n The view frame that is used to execute the slot for creating the\n summary page.\n @param pDocument\n The document which will contain the summary page and from which\n the information about the default transition is retrieved.\n *\/\n void AddSummaryPage (SfxViewFrame* pViewFrame, SdDrawDocument* pDocument);\n\n \/** Take an outline from a text document and create a new impress\n document according to the structure of the outline.\n @param rRequest\n This typically is the unmodified request from a execute()\n function from where this function is called.\n *\/\n void OutlineToImpress (SfxRequest& rRequest);\n};\n\n\n\n\n#ifndef SD_MOD\n#define SD_MOD() ( *(SdModule**) GetAppData(SHL_DRAW) )\n#endif\n\n#endif \/\/ _SDMOD_HXX\n\n<|endoftext|>"} {"text":"\/\/\n\/\/ ex10_27.cpp\n\/\/ Exercise 10.27\n\/\/\n\/\/ Created by pezy on 12\/13\/14.\n\/\/ Copyright (c) 2014 pezy. All rights reserved.\n\/\/\n\/\/ In addition to unique, the library defines function named unique_copy that\n\/\/ takes a third iterator denoting a destination into which to copy the unique\n\/\/ elements.\n\/\/ Write a program that uses unique_copy to copy the unique elements from\n\/\/ a vector into an initially empty list.\n\n#include \n#include \n#include \n#include \n\nint main()\n{\n std::vector vec{1, 1, 3, 3, 5, 5, 7, 7, 9};\n std::list lst;\n\n std::unique_copy(vec.begin(), vec.end(), back_inserter(lst));\n for (auto i : lst) std::cout << i << \" \";\n std::cout << std::endl;\n}\nUpdate ex10_27.cpp\/\/\n\/\/ ex10_27.cpp\n\/\/ Exercise 10.27\n\/\/\n\/\/ Created by pezy on 12\/13\/14.\n\/\/ Copyright (c) 2014 pezy. All rights reserved.\n\/\/\n\/\/ In addition to unique, the library defines function named unique_copy that\n\/\/ takes a third iterator denoting a destination into which to copy the unique\n\/\/ elements.\n\/\/ Write a program that uses unique_copy to copy the unique elements from\n\/\/ a vector into an initially empty list.\n\n#include \n#include \n#include \n#include \nusing namespace std;\n\nint main()\n{\n vector ivec{1, 1, 3, 3, 5, 5, 7, 7, 9};\n list ilst;\n \n unique_copy(ivec.begin(), ivec.end(), back_inserter(ilst));\n for(const auto &i : ilst)\n cout<"} {"text":"#include \"ex14_05.h\"\n\nstd::istream& operator>>(std::istream &in, Book &book)\n{\n in >> book.no_ >> book.name_ >> book.author_ >> book.pubdate_;\n return in;\n}\n\nstd::ostream& operator<<(std::ostream &out, const Book &book)\n{\n out << book.no_ << \" \" << book.name_ << \" \" << book.author_ << \" \" << book.pubdate_;\n return out;\n}\n\nbool operator==(const Book &lhs, const Book &rhs)\n{\n return lhs.no_ == rhs.no_;\n}\n\nbool operator!=(const Book &lhs, const Book &rhs)\n{\n return !(lhs == rhs);\n}\nUpdate ex14_05.cpp#include \"ex14_05.h\"\n\nstd::istream& operator>>(std::istream &in, Book &book)\n{\n in >> book.no_ >> book.name_ >> book.author_ >> book.pubdate_;\n if(!in)\n item=Book();\n return in;\n}\n\nstd::ostream& operator<<(std::ostream &out, const Book &book)\n{\n out << book.no_ << \" \" << book.name_ << \" \" << book.author_ << \" \" << book.pubdate_;\n return out;\n}\n\nbool operator==(const Book &lhs, const Book &rhs)\n{\n return lhs.no_ == rhs.no_;\n}\n\nbool operator!=(const Book &lhs, const Book &rhs)\n{\n return !(lhs == rhs);\n}\n<|endoftext|>"} {"text":"\n#include \n#include \n#include \n#include \n#include \n\n#include \nusing Botan::byte;\nusing Botan::u64bit;\n\n#include \"common.h\"\n#include \"timer.h\"\n#include \"bench.h\"\n\n\/* Discard output to reduce overhead *\/\nstruct BitBucket : public Botan::Filter\n {\n void write(const byte[], u32bit) {}\n };\n\nBotan::Filter* lookup(const std::string&,\n const std::vector&,\n const std::string& = \"All\");\n\nnamespace {\n\ndouble bench_filter(std::string name, Botan::Filter* filter,\n Botan::RandomNumberGenerator& rng,\n bool html, double seconds)\n {\n Botan::Pipe pipe(filter, new BitBucket);\n\n pipe.start_msg();\n\n byte buf[32 * 1024];\n Timer timer(name, sizeof(buf));\n\n rng.randomize(buf, sizeof(buf));\n\n while(timer.seconds() < seconds)\n {\n timer.start();\n pipe.write(buf, sizeof(buf));\n timer.stop();\n }\n\n pipe.end_msg();\n\n double bytes_per_sec = timer.events() \/ timer.seconds();\n double mbytes_per_sec = bytes_per_sec \/ (1024.0 * 1024.0);\n\n std::cout.setf(std::ios::fixed, std::ios::floatfield);\n std::cout.precision(2);\n if(html)\n {\n if(name.find(\"<\") != std::string::npos)\n name.replace(name.find(\"<\"), 1, \"<\");\n if(name.find(\">\") != std::string::npos)\n name.replace(name.find(\">\"), 1, \">\");\n std::cout << \" \" << name\n << std::string(25 - name.length(), ' ') << \" \";\n std::cout.width(6);\n std::cout << mbytes_per_sec << std::endl;\n }\n else\n {\n std::cout << name << \": \" << std::string(25 - name.length(), ' ');\n std::cout.width(6);\n std::cout << mbytes_per_sec << \" MiB\/sec\" << std::endl;\n }\n return (mbytes_per_sec);\n }\n\ndouble bench(const std::string& name, const std::string& filtername, bool html,\n double seconds, u32bit keylen, u32bit ivlen,\n Botan::RandomNumberGenerator& rng)\n {\n std::vector params;\n\n Botan::SecureVector key(keylen);\n rng.randomize(key, key.size());\n params.push_back(hex_encode(key, key.size()));\n\n \/\/params.push_back(std::string(int(2*keylen), 'A'));\n params.push_back(std::string(int(2* ivlen), 'A'));\n\n Botan::Filter* filter = lookup(filtername, params);\n\n if(filter)\n return bench_filter(name, filter, rng, html, seconds);\n return 0;\n }\n\n}\n\nvoid benchmark(const std::string& what,\n Botan::RandomNumberGenerator& rng,\n bool html, double seconds)\n {\n try {\n if(html)\n {\n std::cout << \"\\n\"\n << \"\\n\\n\"\n << \"Botan Benchmarks<\/TITLE>\\n\\n\"\n << \"<BODY>\\n\\n\"\n << \"<P><TABLE BORDER CELLSPACING=1>\\n\"\n << \"<THEAD>\\n\"\n << \"<TR><TH>Algorithm \"\n << \"<TH>Mib \/ second\\n\"\n << \"<TBODY>\\n\";\n }\n\n double sum = 0;\n u32bit how_many = 0;\n\n std::vector<algorithm> algos = get_algos();\n\n for(u32bit j = 0; j != algos.size(); j++)\n if(what == \"All\" || what == algos[j].type)\n {\n double speed = bench(algos[j].name, algos[j].filtername,\n html, seconds, algos[j].keylen,\n algos[j].ivlen, rng);\n if(speed > .00001) \/* log(0) == -inf -> messed up average *\/\n sum += std::log(speed);\n how_many++;\n }\n\n if(html)\n std::cout << \"<\/TABLE>\\n\\n\";\n\n double average = std::exp(sum \/ static_cast<double>(how_many));\n\n if(what == \"All\" && html)\n std::cout << \"\\n<P>Overall speed average: \" << average\n << \"\\n\\n\";\n else if(what == \"All\")\n std::cout << \"\\nOverall speed average: \" << average\n << std::endl;\n\n if(html) std::cout << \"<\/BODY><\/HTML>\\n\";\n }\n catch(Botan::Exception& e)\n {\n std::cout << \"Botan exception caught: \" << e.what() << std::endl;\n return;\n }\n catch(std::exception& e)\n {\n std::cout << \"Standard library exception caught: \" << e.what()\n << std::endl;\n return;\n }\n catch(...)\n {\n std::cout << \"Unknown exception caught.\" << std::endl;\n return;\n }\n }\n\nu32bit bench_algo(const std::string& name,\n Botan::RandomNumberGenerator& rng,\n double seconds)\n {\n try {\n std::vector<algorithm> algos = get_algos();\n\n for(u32bit j = 0; j != algos.size(); j++)\n {\n if(algos[j].name == name)\n {\n bench(algos[j].name, algos[j].filtername, false, seconds,\n algos[j].keylen, algos[j].ivlen, rng);\n return 1;\n }\n }\n return 0;\n }\n catch(Botan::Exception& e)\n {\n std::cout << \"Botan exception caught: \" << e.what() << std::endl;\n return 0;\n }\n catch(std::exception& e)\n {\n std::cout << \"Standard library exception caught: \" << e.what()\n << std::endl;\n return 0;\n }\n catch(...)\n {\n std::cout << \"Unknown exception caught.\" << std::endl;\n return 0;\n }\n }\n<commit_msg>Use heap rather than stack for data input. Increase size to 128k<commit_after>\n#include <iostream>\n#include <iomanip>\n#include <cmath>\n#include <string>\n#include <exception>\n\n#include <botan\/filters.h>\nusing Botan::byte;\nusing Botan::u64bit;\n\n#include \"common.h\"\n#include \"timer.h\"\n#include \"bench.h\"\n\n\/* Discard output to reduce overhead *\/\nstruct BitBucket : public Botan::Filter\n {\n void write(const byte[], u32bit) {}\n };\n\nBotan::Filter* lookup(const std::string&,\n const std::vector<std::string>&,\n const std::string& = \"All\");\n\nnamespace {\n\ndouble bench_filter(std::string name, Botan::Filter* filter,\n Botan::RandomNumberGenerator& rng,\n bool html, double seconds)\n {\n Botan::Pipe pipe(filter, new BitBucket);\n\n Botan::SecureVector<byte> buf(128 * 1024);\n rng.randomize(buf, buf.size());\n\n pipe.start_msg();\n\n Timer timer(name, buf.size());\n\n while(timer.seconds() < seconds)\n {\n timer.start();\n pipe.write(buf, buf.size());\n timer.stop();\n }\n\n pipe.end_msg();\n\n double bytes_per_sec = timer.events() \/ timer.seconds();\n double mbytes_per_sec = bytes_per_sec \/ (1024.0 * 1024.0);\n\n std::cout.setf(std::ios::fixed, std::ios::floatfield);\n std::cout.precision(2);\n if(html)\n {\n if(name.find(\"<\") != std::string::npos)\n name.replace(name.find(\"<\"), 1, \"<\");\n if(name.find(\">\") != std::string::npos)\n name.replace(name.find(\">\"), 1, \">\");\n std::cout << \" <TR><TH>\" << name\n << std::string(25 - name.length(), ' ') << \" <TH>\";\n std::cout.width(6);\n std::cout << mbytes_per_sec << std::endl;\n }\n else\n {\n std::cout << name << \": \" << std::string(25 - name.length(), ' ');\n std::cout.width(6);\n std::cout << mbytes_per_sec << \" MiB\/sec\" << std::endl;\n }\n return (mbytes_per_sec);\n }\n\ndouble bench(const std::string& name, const std::string& filtername, bool html,\n double seconds, u32bit keylen, u32bit ivlen,\n Botan::RandomNumberGenerator& rng)\n {\n std::vector<std::string> params;\n\n Botan::SecureVector<byte> key(keylen);\n rng.randomize(key, key.size());\n params.push_back(hex_encode(key, key.size()));\n\n \/\/params.push_back(std::string(int(2*keylen), 'A'));\n params.push_back(std::string(int(2* ivlen), 'A'));\n\n Botan::Filter* filter = lookup(filtername, params);\n\n if(filter)\n return bench_filter(name, filter, rng, html, seconds);\n return 0;\n }\n\n}\n\nvoid benchmark(const std::string& what,\n Botan::RandomNumberGenerator& rng,\n bool html, double seconds)\n {\n try {\n if(html)\n {\n std::cout << \"<!DOCTYPE HTML PUBLIC \\\"-\/\/W3C\/\/DTD \"\n << \"HTML 4.0 Transitional\/\/EN\\\">\\n\"\n << \"<HTML>\\n\\n\"\n << \"<TITLE>Botan Benchmarks<\/TITLE>\\n\\n\"\n << \"<BODY>\\n\\n\"\n << \"<P><TABLE BORDER CELLSPACING=1>\\n\"\n << \"<THEAD>\\n\"\n << \"<TR><TH>Algorithm \"\n << \"<TH>Mib \/ second\\n\"\n << \"<TBODY>\\n\";\n }\n\n double sum = 0;\n u32bit how_many = 0;\n\n std::vector<algorithm> algos = get_algos();\n\n for(u32bit j = 0; j != algos.size(); j++)\n if(what == \"All\" || what == algos[j].type)\n {\n double speed = bench(algos[j].name, algos[j].filtername,\n html, seconds, algos[j].keylen,\n algos[j].ivlen, rng);\n if(speed > .00001) \/* log(0) == -inf -> messed up average *\/\n sum += std::log(speed);\n how_many++;\n }\n\n if(html)\n std::cout << \"<\/TABLE>\\n\\n\";\n\n double average = std::exp(sum \/ static_cast<double>(how_many));\n\n if(what == \"All\" && html)\n std::cout << \"\\n<P>Overall speed average: \" << average\n << \"\\n\\n\";\n else if(what == \"All\")\n std::cout << \"\\nOverall speed average: \" << average\n << std::endl;\n\n if(html) std::cout << \"<\/BODY><\/HTML>\\n\";\n }\n catch(Botan::Exception& e)\n {\n std::cout << \"Botan exception caught: \" << e.what() << std::endl;\n return;\n }\n catch(std::exception& e)\n {\n std::cout << \"Standard library exception caught: \" << e.what()\n << std::endl;\n return;\n }\n catch(...)\n {\n std::cout << \"Unknown exception caught.\" << std::endl;\n return;\n }\n }\n\nu32bit bench_algo(const std::string& name,\n Botan::RandomNumberGenerator& rng,\n double seconds)\n {\n try {\n std::vector<algorithm> algos = get_algos();\n\n for(u32bit j = 0; j != algos.size(); j++)\n {\n if(algos[j].name == name)\n {\n bench(algos[j].name, algos[j].filtername, false, seconds,\n algos[j].keylen, algos[j].ivlen, rng);\n return 1;\n }\n }\n return 0;\n }\n catch(Botan::Exception& e)\n {\n std::cout << \"Botan exception caught: \" << e.what() << std::endl;\n return 0;\n }\n catch(std::exception& e)\n {\n std::cout << \"Standard library exception caught: \" << e.what()\n << std::endl;\n return 0;\n }\n catch(...)\n {\n std::cout << \"Unknown exception caught.\" << std::endl;\n return 0;\n }\n }\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright © 2010 Intel Corporation\n *\n * Permission is hereby granted, free of charge, to any person obtaining a\n * copy of this software and associated documentation files (the \"Software\"),\n * to deal in the Software without restriction, including without limitation\n * the rights to use, copy, modify, merge, publish, distribute, sublicense,\n * and\/or sell copies of the Software, and to permit persons to whom the\n * Software is furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice (including the next\n * paragraph) shall be included in all copies or substantial portions of the\n * Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n * DEALINGS IN THE SOFTWARE.\n *\/\n\n\/**\n * \\file brw_wm_vector_splitting.cpp\n *\n * If a vector is only ever referenced by its components, then\n * split those components out to individual variables so they can be\n * handled normally by other optimization passes.\n *\n * This skips vectors in uniforms and varyings, which need to be\n * accessible as vectors for their access by the GL. Also, vector\n * results of non-variable-derefs in assignments aren't handled\n * because to do so we would have to store the vector result to a\n * temporary in order to unload each channel, and to do so would just\n * loop us back to where we started. For the 965, this is exactly the\n * behavior we want for the results of texture lookups, but probably not for\n *\/\n\nextern \"C\" {\n#include \"main\/core.h\"\n#include \"brw_context.h\"\n}\n#include \"glsl\/ir.h\"\n#include \"glsl\/ir_visitor.h\"\n#include \"glsl\/ir_rvalue_visitor.h\"\n#include \"glsl\/glsl_types.h\"\n\nstatic bool debug = false;\n\nclass variable_entry : public exec_node\n{\npublic:\n variable_entry(ir_variable *var)\n {\n this->var = var;\n this->whole_vector_access = 0;\n this->declaration = false;\n this->mem_ctx = NULL;\n }\n\n ir_variable *var; \/* The key: the variable's pointer. *\/\n\n \/** Number of times the variable is referenced, including assignments. *\/\n unsigned whole_vector_access;\n\n bool declaration; \/* If the variable had a decl in the instruction stream *\/\n\n ir_variable *components[4];\n\n \/** ralloc_parent(this->var) -- the shader's ralloc context. *\/\n void *mem_ctx;\n};\n\nclass ir_vector_reference_visitor : public ir_hierarchical_visitor {\npublic:\n ir_vector_reference_visitor(void)\n {\n this->mem_ctx = ralloc_context(NULL);\n this->variable_list.make_empty();\n }\n\n ~ir_vector_reference_visitor(void)\n {\n ralloc_free(mem_ctx);\n }\n\n virtual ir_visitor_status visit(ir_variable *);\n virtual ir_visitor_status visit(ir_dereference_variable *);\n virtual ir_visitor_status visit_enter(ir_swizzle *);\n virtual ir_visitor_status visit_enter(ir_assignment *);\n virtual ir_visitor_status visit_enter(ir_function_signature *);\n\n variable_entry *get_variable_entry(ir_variable *var);\n\n \/* List of variable_entry *\/\n exec_list variable_list;\n\n void *mem_ctx;\n};\n\nvariable_entry *\nir_vector_reference_visitor::get_variable_entry(ir_variable *var)\n{\n assert(var);\n\n if (!var->type->is_vector())\n return NULL;\n\n switch (var->mode) {\n case ir_var_uniform:\n case ir_var_shader_in:\n case ir_var_shader_out:\n case ir_var_function_in:\n case ir_var_function_out:\n case ir_var_function_inout:\n \/* Can't split varyings or uniforms. Function in\/outs won't get split\n * either.\n *\/\n return NULL;\n case ir_var_auto:\n case ir_var_temporary:\n break;\n }\n\n foreach_list(node, &this->variable_list) {\n variable_entry *entry = (variable_entry *)node;\n if (entry->var == var)\n\t return entry;\n }\n\n variable_entry *entry = new(mem_ctx) variable_entry(var);\n this->variable_list.push_tail(entry);\n return entry;\n}\n\n\nir_visitor_status\nir_vector_reference_visitor::visit(ir_variable *ir)\n{\n variable_entry *entry = this->get_variable_entry(ir);\n\n if (entry)\n entry->declaration = true;\n\n return visit_continue;\n}\n\nir_visitor_status\nir_vector_reference_visitor::visit(ir_dereference_variable *ir)\n{\n ir_variable *const var = ir->var;\n variable_entry *entry = this->get_variable_entry(var);\n\n if (entry)\n entry->whole_vector_access++;\n\n return visit_continue;\n}\n\nir_visitor_status\nir_vector_reference_visitor::visit_enter(ir_swizzle *ir)\n{\n \/* Don't descend into a vector ir_dereference_variable below. *\/\n if (ir->val->as_dereference_variable() && ir->type->is_scalar())\n return visit_continue_with_parent;\n\n return visit_continue;\n}\n\nir_visitor_status\nir_vector_reference_visitor::visit_enter(ir_assignment *ir)\n{\n if (ir->lhs->as_dereference_variable() &&\n ir->rhs->as_dereference_variable() &&\n !ir->condition) {\n \/* We'll split copies of a vector to copies of channels, so don't\n * descend to the ir_dereference_variables.\n *\/\n return visit_continue_with_parent;\n }\n if (ir->lhs->as_dereference_variable() &&\n is_power_of_two(ir->write_mask) &&\n !ir->condition) {\n \/* If we're writing just a channel, then channel-splitting the LHS is OK.\n *\/\n ir->rhs->accept(this);\n return visit_continue_with_parent;\n }\n return visit_continue;\n}\n\nir_visitor_status\nir_vector_reference_visitor::visit_enter(ir_function_signature *ir)\n{\n \/* We don't want to descend into the function parameters and\n * split them, so just accept the body here.\n *\/\n visit_list_elements(this, &ir->body);\n return visit_continue_with_parent;\n}\n\nclass ir_vector_splitting_visitor : public ir_rvalue_visitor {\npublic:\n ir_vector_splitting_visitor(exec_list *vars)\n {\n this->variable_list = vars;\n }\n\n virtual ir_visitor_status visit_leave(ir_assignment *);\n\n void handle_rvalue(ir_rvalue **rvalue);\n variable_entry *get_splitting_entry(ir_variable *var);\n\n exec_list *variable_list;\n};\n\nvariable_entry *\nir_vector_splitting_visitor::get_splitting_entry(ir_variable *var)\n{\n assert(var);\n\n if (!var->type->is_vector())\n return NULL;\n\n foreach_list(node, &*this->variable_list) {\n variable_entry *entry = (variable_entry *)node;\n if (entry->var == var) {\n\t return entry;\n }\n }\n\n return NULL;\n}\n\nvoid\nir_vector_splitting_visitor::handle_rvalue(ir_rvalue **rvalue)\n{\n if (!*rvalue)\n return;\n\n ir_swizzle *swiz = (*rvalue)->as_swizzle();\n if (!swiz || !swiz->type->is_scalar())\n return;\n\n ir_dereference_variable *deref_var = swiz->val->as_dereference_variable();\n if (!deref_var)\n return;\n\n variable_entry *entry = get_splitting_entry(deref_var->var);\n if (!entry)\n return;\n\n ir_variable *var = entry->components[swiz->mask.x];\n *rvalue = new(entry->mem_ctx) ir_dereference_variable(var);\n}\n\nir_visitor_status\nir_vector_splitting_visitor::visit_leave(ir_assignment *ir)\n{\n ir_dereference_variable *lhs_deref = ir->lhs->as_dereference_variable();\n ir_dereference_variable *rhs_deref = ir->rhs->as_dereference_variable();\n variable_entry *lhs = lhs_deref ? get_splitting_entry(lhs_deref->var) : NULL;\n variable_entry *rhs = rhs_deref ? get_splitting_entry(rhs_deref->var) : NULL;\n\n if (lhs_deref && rhs_deref && (lhs || rhs) && !ir->condition) {\n unsigned int rhs_chan = 0;\n\n \/* Straight assignment of vector variables. *\/\n for (unsigned int i = 0; i < ir->lhs->type->vector_elements; i++) {\n\t ir_dereference *new_lhs;\n\t ir_rvalue *new_rhs;\n\t void *mem_ctx = lhs ? lhs->mem_ctx : rhs->mem_ctx;\n\t unsigned int writemask;\n\n\t if (!(ir->write_mask & (1 << i)))\n\t continue;\n\n\t if (lhs) {\n\t new_lhs = new(mem_ctx) ir_dereference_variable(lhs->components[i]);\n\t writemask = 1;\n\t } else {\n\t new_lhs = ir->lhs->clone(mem_ctx, NULL);\n\t writemask = 1 << i;\n\t }\n\n\t if (rhs) {\n\t new_rhs =\n\t new(mem_ctx) ir_dereference_variable(rhs->components[rhs_chan]);\n\t } else {\n\t new_rhs = new(mem_ctx) ir_swizzle(ir->rhs->clone(mem_ctx, NULL),\n\t\t\t\t\t rhs_chan, 0, 0, 0, 1);\n\t }\n\n\t ir->insert_before(new(mem_ctx) ir_assignment(new_lhs,\n\t\t\t\t\t\t new_rhs,\n\t\t\t\t\t\t NULL, writemask));\n\n\t rhs_chan++;\n }\n ir->remove();\n } else if (lhs) {\n void *mem_ctx = lhs->mem_ctx;\n int elem = -1;\n\n switch (ir->write_mask) {\n case (1 << 0):\n\t elem = 0;\n\t break;\n case (1 << 1):\n\t elem = 1;\n\t break;\n case (1 << 2):\n\t elem = 2;\n\t break;\n case (1 << 3):\n\t elem = 3;\n\t break;\n default:\n\t ir->print();\n\t assert(!\"not reached: non-channelwise dereference of LHS.\");\n }\n\n ir->lhs = new(mem_ctx) ir_dereference_variable(lhs->components[elem]);\n ir->write_mask = (1 << 0);\n\n handle_rvalue(&ir->rhs);\n } else {\n handle_rvalue(&ir->rhs);\n }\n\n handle_rvalue(&ir->condition);\n\n return visit_continue;\n}\n\nbool\nbrw_do_vector_splitting(exec_list *instructions)\n{\n ir_vector_reference_visitor refs;\n\n visit_list_elements(&refs, instructions);\n\n \/* Trim out variables we can't split. *\/\n foreach_list_safe(node, &refs.variable_list) {\n variable_entry *entry = (variable_entry *)node;\n\n if (debug) {\n\t printf(\"vector %s@%p: decl %d, whole_access %d\\n\",\n\t\tentry->var->name, (void *) entry->var, entry->declaration,\n\t\tentry->whole_vector_access);\n }\n\n if (!entry->declaration || entry->whole_vector_access) {\n\t entry->remove();\n }\n }\n\n if (refs.variable_list.is_empty())\n return false;\n\n void *mem_ctx = ralloc_context(NULL);\n\n \/* Replace the decls of the vectors to be split with their split\n * components.\n *\/\n foreach_list(node, &refs.variable_list) {\n variable_entry *entry = (variable_entry *)node;\n const struct glsl_type *type;\n type = glsl_type::get_instance(entry->var->type->base_type, 1, 1);\n\n entry->mem_ctx = ralloc_parent(entry->var);\n\n for (unsigned int i = 0; i < entry->var->type->vector_elements; i++) {\n\t const char *name = ralloc_asprintf(mem_ctx, \"%s_%c\",\n\t\t\t\t\t entry->var->name,\n\t\t\t\t\t \"xyzw\"[i]);\n\n\t entry->components[i] = new(entry->mem_ctx) ir_variable(type, name,\n\t\t\t\t\t\t\t\tir_var_temporary);\n\t entry->var->insert_before(entry->components[i]);\n }\n\n entry->var->remove();\n }\n\n ir_vector_splitting_visitor split(&refs.variable_list);\n visit_list_elements(&split, instructions);\n\n ralloc_free(mem_ctx);\n\n return true;\n}\n<commit_msg>i965: Don't do vector splitting for ir_var_system_value<commit_after>\/*\n * Copyright © 2010 Intel Corporation\n *\n * Permission is hereby granted, free of charge, to any person obtaining a\n * copy of this software and associated documentation files (the \"Software\"),\n * to deal in the Software without restriction, including without limitation\n * the rights to use, copy, modify, merge, publish, distribute, sublicense,\n * and\/or sell copies of the Software, and to permit persons to whom the\n * Software is furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice (including the next\n * paragraph) shall be included in all copies or substantial portions of the\n * Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n * DEALINGS IN THE SOFTWARE.\n *\/\n\n\/**\n * \\file brw_wm_vector_splitting.cpp\n *\n * If a vector is only ever referenced by its components, then\n * split those components out to individual variables so they can be\n * handled normally by other optimization passes.\n *\n * This skips vectors in uniforms and varyings, which need to be\n * accessible as vectors for their access by the GL. Also, vector\n * results of non-variable-derefs in assignments aren't handled\n * because to do so we would have to store the vector result to a\n * temporary in order to unload each channel, and to do so would just\n * loop us back to where we started. For the 965, this is exactly the\n * behavior we want for the results of texture lookups, but probably not for\n *\/\n\nextern \"C\" {\n#include \"main\/core.h\"\n#include \"brw_context.h\"\n}\n#include \"glsl\/ir.h\"\n#include \"glsl\/ir_visitor.h\"\n#include \"glsl\/ir_rvalue_visitor.h\"\n#include \"glsl\/glsl_types.h\"\n\nstatic bool debug = false;\n\nclass variable_entry : public exec_node\n{\npublic:\n variable_entry(ir_variable *var)\n {\n this->var = var;\n this->whole_vector_access = 0;\n this->declaration = false;\n this->mem_ctx = NULL;\n }\n\n ir_variable *var; \/* The key: the variable's pointer. *\/\n\n \/** Number of times the variable is referenced, including assignments. *\/\n unsigned whole_vector_access;\n\n bool declaration; \/* If the variable had a decl in the instruction stream *\/\n\n ir_variable *components[4];\n\n \/** ralloc_parent(this->var) -- the shader's ralloc context. *\/\n void *mem_ctx;\n};\n\nclass ir_vector_reference_visitor : public ir_hierarchical_visitor {\npublic:\n ir_vector_reference_visitor(void)\n {\n this->mem_ctx = ralloc_context(NULL);\n this->variable_list.make_empty();\n }\n\n ~ir_vector_reference_visitor(void)\n {\n ralloc_free(mem_ctx);\n }\n\n virtual ir_visitor_status visit(ir_variable *);\n virtual ir_visitor_status visit(ir_dereference_variable *);\n virtual ir_visitor_status visit_enter(ir_swizzle *);\n virtual ir_visitor_status visit_enter(ir_assignment *);\n virtual ir_visitor_status visit_enter(ir_function_signature *);\n\n variable_entry *get_variable_entry(ir_variable *var);\n\n \/* List of variable_entry *\/\n exec_list variable_list;\n\n void *mem_ctx;\n};\n\nvariable_entry *\nir_vector_reference_visitor::get_variable_entry(ir_variable *var)\n{\n assert(var);\n\n if (!var->type->is_vector())\n return NULL;\n\n switch (var->mode) {\n case ir_var_uniform:\n case ir_var_shader_in:\n case ir_var_shader_out:\n case ir_var_system_value:\n case ir_var_function_in:\n case ir_var_function_out:\n case ir_var_function_inout:\n \/* Can't split varyings or uniforms. Function in\/outs won't get split\n * either.\n *\/\n return NULL;\n case ir_var_auto:\n case ir_var_temporary:\n break;\n }\n\n foreach_list(node, &this->variable_list) {\n variable_entry *entry = (variable_entry *)node;\n if (entry->var == var)\n\t return entry;\n }\n\n variable_entry *entry = new(mem_ctx) variable_entry(var);\n this->variable_list.push_tail(entry);\n return entry;\n}\n\n\nir_visitor_status\nir_vector_reference_visitor::visit(ir_variable *ir)\n{\n variable_entry *entry = this->get_variable_entry(ir);\n\n if (entry)\n entry->declaration = true;\n\n return visit_continue;\n}\n\nir_visitor_status\nir_vector_reference_visitor::visit(ir_dereference_variable *ir)\n{\n ir_variable *const var = ir->var;\n variable_entry *entry = this->get_variable_entry(var);\n\n if (entry)\n entry->whole_vector_access++;\n\n return visit_continue;\n}\n\nir_visitor_status\nir_vector_reference_visitor::visit_enter(ir_swizzle *ir)\n{\n \/* Don't descend into a vector ir_dereference_variable below. *\/\n if (ir->val->as_dereference_variable() && ir->type->is_scalar())\n return visit_continue_with_parent;\n\n return visit_continue;\n}\n\nir_visitor_status\nir_vector_reference_visitor::visit_enter(ir_assignment *ir)\n{\n if (ir->lhs->as_dereference_variable() &&\n ir->rhs->as_dereference_variable() &&\n !ir->condition) {\n \/* We'll split copies of a vector to copies of channels, so don't\n * descend to the ir_dereference_variables.\n *\/\n return visit_continue_with_parent;\n }\n if (ir->lhs->as_dereference_variable() &&\n is_power_of_two(ir->write_mask) &&\n !ir->condition) {\n \/* If we're writing just a channel, then channel-splitting the LHS is OK.\n *\/\n ir->rhs->accept(this);\n return visit_continue_with_parent;\n }\n return visit_continue;\n}\n\nir_visitor_status\nir_vector_reference_visitor::visit_enter(ir_function_signature *ir)\n{\n \/* We don't want to descend into the function parameters and\n * split them, so just accept the body here.\n *\/\n visit_list_elements(this, &ir->body);\n return visit_continue_with_parent;\n}\n\nclass ir_vector_splitting_visitor : public ir_rvalue_visitor {\npublic:\n ir_vector_splitting_visitor(exec_list *vars)\n {\n this->variable_list = vars;\n }\n\n virtual ir_visitor_status visit_leave(ir_assignment *);\n\n void handle_rvalue(ir_rvalue **rvalue);\n variable_entry *get_splitting_entry(ir_variable *var);\n\n exec_list *variable_list;\n};\n\nvariable_entry *\nir_vector_splitting_visitor::get_splitting_entry(ir_variable *var)\n{\n assert(var);\n\n if (!var->type->is_vector())\n return NULL;\n\n foreach_list(node, &*this->variable_list) {\n variable_entry *entry = (variable_entry *)node;\n if (entry->var == var) {\n\t return entry;\n }\n }\n\n return NULL;\n}\n\nvoid\nir_vector_splitting_visitor::handle_rvalue(ir_rvalue **rvalue)\n{\n if (!*rvalue)\n return;\n\n ir_swizzle *swiz = (*rvalue)->as_swizzle();\n if (!swiz || !swiz->type->is_scalar())\n return;\n\n ir_dereference_variable *deref_var = swiz->val->as_dereference_variable();\n if (!deref_var)\n return;\n\n variable_entry *entry = get_splitting_entry(deref_var->var);\n if (!entry)\n return;\n\n ir_variable *var = entry->components[swiz->mask.x];\n *rvalue = new(entry->mem_ctx) ir_dereference_variable(var);\n}\n\nir_visitor_status\nir_vector_splitting_visitor::visit_leave(ir_assignment *ir)\n{\n ir_dereference_variable *lhs_deref = ir->lhs->as_dereference_variable();\n ir_dereference_variable *rhs_deref = ir->rhs->as_dereference_variable();\n variable_entry *lhs = lhs_deref ? get_splitting_entry(lhs_deref->var) : NULL;\n variable_entry *rhs = rhs_deref ? get_splitting_entry(rhs_deref->var) : NULL;\n\n if (lhs_deref && rhs_deref && (lhs || rhs) && !ir->condition) {\n unsigned int rhs_chan = 0;\n\n \/* Straight assignment of vector variables. *\/\n for (unsigned int i = 0; i < ir->lhs->type->vector_elements; i++) {\n\t ir_dereference *new_lhs;\n\t ir_rvalue *new_rhs;\n\t void *mem_ctx = lhs ? lhs->mem_ctx : rhs->mem_ctx;\n\t unsigned int writemask;\n\n\t if (!(ir->write_mask & (1 << i)))\n\t continue;\n\n\t if (lhs) {\n\t new_lhs = new(mem_ctx) ir_dereference_variable(lhs->components[i]);\n\t writemask = 1;\n\t } else {\n\t new_lhs = ir->lhs->clone(mem_ctx, NULL);\n\t writemask = 1 << i;\n\t }\n\n\t if (rhs) {\n\t new_rhs =\n\t new(mem_ctx) ir_dereference_variable(rhs->components[rhs_chan]);\n\t } else {\n\t new_rhs = new(mem_ctx) ir_swizzle(ir->rhs->clone(mem_ctx, NULL),\n\t\t\t\t\t rhs_chan, 0, 0, 0, 1);\n\t }\n\n\t ir->insert_before(new(mem_ctx) ir_assignment(new_lhs,\n\t\t\t\t\t\t new_rhs,\n\t\t\t\t\t\t NULL, writemask));\n\n\t rhs_chan++;\n }\n ir->remove();\n } else if (lhs) {\n void *mem_ctx = lhs->mem_ctx;\n int elem = -1;\n\n switch (ir->write_mask) {\n case (1 << 0):\n\t elem = 0;\n\t break;\n case (1 << 1):\n\t elem = 1;\n\t break;\n case (1 << 2):\n\t elem = 2;\n\t break;\n case (1 << 3):\n\t elem = 3;\n\t break;\n default:\n\t ir->print();\n\t assert(!\"not reached: non-channelwise dereference of LHS.\");\n }\n\n ir->lhs = new(mem_ctx) ir_dereference_variable(lhs->components[elem]);\n ir->write_mask = (1 << 0);\n\n handle_rvalue(&ir->rhs);\n } else {\n handle_rvalue(&ir->rhs);\n }\n\n handle_rvalue(&ir->condition);\n\n return visit_continue;\n}\n\nbool\nbrw_do_vector_splitting(exec_list *instructions)\n{\n ir_vector_reference_visitor refs;\n\n visit_list_elements(&refs, instructions);\n\n \/* Trim out variables we can't split. *\/\n foreach_list_safe(node, &refs.variable_list) {\n variable_entry *entry = (variable_entry *)node;\n\n if (debug) {\n\t printf(\"vector %s@%p: decl %d, whole_access %d\\n\",\n\t\tentry->var->name, (void *) entry->var, entry->declaration,\n\t\tentry->whole_vector_access);\n }\n\n if (!entry->declaration || entry->whole_vector_access) {\n\t entry->remove();\n }\n }\n\n if (refs.variable_list.is_empty())\n return false;\n\n void *mem_ctx = ralloc_context(NULL);\n\n \/* Replace the decls of the vectors to be split with their split\n * components.\n *\/\n foreach_list(node, &refs.variable_list) {\n variable_entry *entry = (variable_entry *)node;\n const struct glsl_type *type;\n type = glsl_type::get_instance(entry->var->type->base_type, 1, 1);\n\n entry->mem_ctx = ralloc_parent(entry->var);\n\n for (unsigned int i = 0; i < entry->var->type->vector_elements; i++) {\n\t const char *name = ralloc_asprintf(mem_ctx, \"%s_%c\",\n\t\t\t\t\t entry->var->name,\n\t\t\t\t\t \"xyzw\"[i]);\n\n\t entry->components[i] = new(entry->mem_ctx) ir_variable(type, name,\n\t\t\t\t\t\t\t\tir_var_temporary);\n\t entry->var->insert_before(entry->components[i]);\n }\n\n entry->var->remove();\n }\n\n ir_vector_splitting_visitor split(&refs.variable_list);\n visit_list_elements(&split, instructions);\n\n ralloc_free(mem_ctx);\n\n return true;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2015 Klaralvdalens Datakonsult AB (KDAB).\n\/\/ All rights reserved. Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\n#include \"debug.h\"\n\n#include <QString>\n#include <QDebug>\n\n#include <iostream>\n\nstd::ostream& operator<<(std::ostream& stream, const wchar_t *input)\n{\n return stream << qPrintable(QString::fromWCharArray(input));\n}\n\nQDebug operator<<(QDebug stream, const CefString& string)\n{\n return stream << QString::fromStdString(string.ToString());\n}\n\nQ_LOGGING_CATEGORY(handler, \"phantomjs.handler\", QtWarningMsg)\nQ_LOGGING_CATEGORY(print, \"phantomjs.print\", QtWarningMsg)\nQ_LOGGING_CATEGORY(app, \"phantomjs.app\", QtWarningMsg)\n\n<commit_msg>Make code compile with Qt 5.2<commit_after>\/\/ Copyright (c) 2015 Klaralvdalens Datakonsult AB (KDAB).\n\/\/ All rights reserved. Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\n#include \"debug.h\"\n\n#include <QString>\n#include <QDebug>\n\n#include <iostream>\n\nstd::ostream& operator<<(std::ostream& stream, const wchar_t *input)\n{\n return stream << qPrintable(QString::fromWCharArray(input));\n}\n\nQDebug operator<<(QDebug stream, const CefString& string)\n{\n return stream << QString::fromStdString(string.ToString());\n}\n\n#if QT_VERSION >= 0x050400\n#define WARNING_BY_DEFAULT , QtWarningMsg\n#else\n#define WARNING_BY_DEFAULT\n#endif\n\nQ_LOGGING_CATEGORY(handler, \"phantomjs.handler\" WARNING_BY_DEFAULT)\nQ_LOGGING_CATEGORY(print, \"phantomjs.print\" WARNING_BY_DEFAULT)\nQ_LOGGING_CATEGORY(app, \"phantomjs.app\" WARNING_BY_DEFAULT)\n<|endoftext|>"} {"text":"<commit_before>\/\/=======================================================================\n\/\/ Copyright (c) 2013-2016 Baptiste Wicht.\n\/\/ Distributed under the terms of the MIT License.\n\/\/ (See accompanying file LICENSE or copy at\n\/\/ http:\/\/opensource.org\/licenses\/MIT)\n\/\/=======================================================================\n\n\/*!\n * \\file\n * \\brief Contains Template Metaprogramming (TMP) utilities\n *\/\n\n#ifndef CPP_UTILS_TMP_HPP\n#define CPP_UTILS_TMP_HPP\n\n#include <tuple>\n#include <utility>\n\n#include \"tmp\/tmp.hpp\"\n#include \"tmp\/sfinae.hpp\"\n#include \"tmp\/variadic.hpp\"\n\nnamespace cpp {\n\nnamespace tmp_detail {\n\n \/*!\n * \\brief Helper Traits to test if all the types from I to N in\n * T are homogeneous\n *\/\ntemplate <std::size_t I, std::size_t S, typename F, typename... T>\nstruct is_homogeneous_helper {\n \/*!\n * \\brief Sub helper for recursive instantiations\n *\/\n template <std::size_t I1, std::size_t S1, typename Enable = void>\n struct helper_int : and_helper<std::is_same<F, nth_type_t<I1, T...>>::value, is_homogeneous_helper<I1 + 1, S1, F, T...>::value> {};\n\n \/*!\n * \\copydoc helper_int\n *\/\n template <std::size_t I1, std::size_t S1>\n struct helper_int<I1, S1, std::enable_if_t<I1 == S1>> : std::is_same<F, nth_type_t<I1, T...>> {};\n\n static constexpr const auto value = helper_int<I, S>::value; \/\/\/< Indicates if the sequence of types is homogeneous\n};\n\n} \/\/end of namespace tmp_detail\n\n\/*!\n * \\brief Implementation of helper for for_each_tuple_t\n *\/\ntemplate <int I, typename Tuple, typename Functor>\nstruct for_each_tuple_t_impl {\n \/*!\n * \\brief Apply the functof for each elements in the tuple, from I\n *\/\n static void for_each(Functor&& func) {\n std::forward<Functor>(func).template operator()<typename std::tuple_element<I, Tuple>::type>();\n for_each_tuple_t_impl<I - 1, Tuple, Functor>::for_each(std::forward<Functor>(func));\n }\n};\n\n\/*!\n * \\copydoc for_each_tuple_t_impl\n *\/\ntemplate <typename Tuple, typename Functor>\nstruct for_each_tuple_t_impl<0, Tuple, Functor> {\n \/*!\n * \\brief Apply the functof for each elements in the tuple, from I\n *\/\n static void for_each(Functor&& func) {\n std::forward<Functor>(func).template operator()<typename std::tuple_element<0, Tuple>::type>();\n }\n};\n\n\/*!\n * \\copydoc for_each_tuple_t_impl\n *\/\ntemplate <typename Tuple, typename Functor>\nstruct for_each_tuple_t_impl<-1, Tuple, Functor> {\n \/*!\n * \\brief End of the the recursion\n *\/\n static void for_each(Functor&& \/*func*\/) {\n \/\/Nothing to be done\n }\n};\n\n\/*!\n * \\brief Call the given functor for each type in the tuple\n * \\tparam Tuple The tuple type\n * \\param func The functor to call\n *\/\ntemplate <typename Tuple, typename Functor>\nvoid for_each_tuple_t(Functor&& func) {\n for_each_tuple_t_impl<static_cast<int>(std::tuple_size<Tuple>::value) - 1, Tuple, Functor>::for_each(std::forward<Functor>(func));\n}\n\n\/*!\n * \\brief Traits to test if a type is a specialization of a template\n * \\tparam TT The template type\n * \\tparam T The type to test\n *\/\ntemplate <template <typename...> class TT, typename T>\nstruct is_specialization_of : std::false_type {};\n\n\/*!\n * \\copydoc is_specialization_of\n *\/\ntemplate <template <typename...> class TT, typename... Args>\nstruct is_specialization_of<TT, TT<Args...>> : std::true_type {};\n\n\/*!\n * \\brief Traits to test if all the given types are convertible to V\n * \\tparam V The target type\n * \\tparam F The first type to test\n * \\tparam S The types to test\n *\/\ntemplate <typename V, typename F, typename... S>\nstruct all_convertible_to : bool_constant_c<and_c<all_convertible_to<V, F>, all_convertible_to<V, S...>>> {};\n\n\/*!\n * \\copydoc all_convertible_to\n *\/\ntemplate <typename V, typename F>\nstruct all_convertible_to<V, F> : bool_constant_c<std::is_convertible<F, V>> {};\n\n\/*!\n * \\brief Test is a list of types homogeneous\n * \\tparam F The first type\n * \\tparam T The types\n *\/\ntemplate <typename F, typename... T>\nstruct is_homogeneous : bool_constant_c<tmp_detail::is_homogeneous_helper<0, sizeof...(T)-1, F, T...>> {};\n\n\/*!\n * \\copydoc all_convertible_to\n *\/\ntemplate <typename F>\nstruct is_homogeneous<F> : std::true_type {};\n\n\/*\n * \\brief Test if a list of types is sub-homogeneous\n *\n * A sub-homogeneous list of types is a list where the N-1 first types are the\n * same and the last one is different\n *\/\ntemplate <typename... T>\nstruct is_sub_homogeneous;\n\n\/*!\n * \\copydoc is_sub_homogeneous\n *\/\ntemplate <>\nstruct is_sub_homogeneous<> : std::false_type {};\n\n\/*!\n * \\copydoc is_sub_homogeneous\n *\/\ntemplate <typename T>\nstruct is_sub_homogeneous<T> : std::false_type {};\n\n\/*!\n * \\copydoc is_sub_homogeneous\n *\/\ntemplate <typename T1, typename T2>\nstruct is_sub_homogeneous<T1, T2> : bool_constant_c<not_c<std::is_same<T1, T2>>> {};\n\n\/*!\n * \\copydoc is_sub_homogeneous\n *\/\ntemplate <typename T1, typename T2, typename T3, typename... T>\nstruct is_sub_homogeneous<T1, T2, T3, T...> : bool_constant_c<\n and_c<\n std::is_same<T1, T2>,\n is_sub_homogeneous<T2, T3, T...>>> {};\n\n\/*!\n * \\brief Apply the given function to each element of the variadic\n * packs whose position is present in the sequence\n * \\param f The functor\n * \\param i The index sequence\n * \\param args The arguments\n *\/\ntemplate <typename F, std::size_t I1, std::size_t... I, typename... T, enable_if_u<(sizeof...(I) == 0)> = detail::dummy>\nvoid for_each_in_subset(F&& f, const std::index_sequence<I1, I...>& i, T&&... args) {\n f(std::forward<nth_type_t<I1, T...>>(nth_value<I1>(args...)));\n cpp_unused(i);\n}\n\n\/*!\n * \\brief Apply the given function to each element of the variadic\n * packs whose position is present in the sequence\n * \\param f The functor\n * \\param i The index sequence\n * \\param args The arguments\n *\/\ntemplate <typename F, std::size_t I1, std::size_t... I, typename... T, enable_if_u<(sizeof...(I) > 0)> = detail::dummy>\nvoid for_each_in_subset(F&& f, const std::index_sequence<I1, I...>& i, T&&... args) {\n f(std::forward<nth_type_t<I1, T...>>(nth_value<I1>(args...)));\n for_each_in_subset(f, std::index_sequence<I...>(), std::forward<T>(args)...);\n cpp_unused(i);\n}\n\n\/*!\n * \\brief Apply the given function to each element of the variadic pack\n * \\param f The functor\n * \\param args The arguments\n *\/\ntemplate <typename F, typename... T>\nvoid for_each_in(F&& f, T&&... args) {\n for_each_in_subset(f, std::make_index_sequence<sizeof...(T)>(), std::forward<T>(args)...);\n}\n\n\/*!\n * \\brief Test if the variadic list of types containg the given type\n * \\tparam T1 The type to search\n * \\tparam T The list of types\n *\/\ntemplate <typename T1, typename... T>\nstruct variadic_contains;\n\n\/*!\n * \\copydoc variadic_contains\n *\/\ntemplate <typename T1, typename T2, typename... T>\nstruct variadic_contains<T1, T2, T...> : bool_constant_c<or_c<std::is_same<T1, T2>, variadic_contains<T1, T...>>> {};\n\n\/*!\n * \\copydoc variadic_contains\n *\/\ntemplate <typename T1>\nstruct variadic_contains<T1> : std::false_type {};\n\n\/*!\n * \\brief A compile-time type list.\n *\/\ntemplate <typename... T>\nstruct type_list {\n \/*!\n * \\brief Indicates if the list contains the given type\n * \\tparam V The type to search in the list\n * \\return true if the type is in the list, false otherwise.\n *\/\n template <typename V>\n static constexpr bool contains() {\n return variadic_contains<V, T...>::value;\n }\n};\n\n} \/\/end of namespace cpp\n\n#endif \/\/CPP_UTILS_TMP_HPP\n<commit_msg>Add missing include<commit_after>\/\/=======================================================================\n\/\/ Copyright (c) 2013-2016 Baptiste Wicht.\n\/\/ Distributed under the terms of the MIT License.\n\/\/ (See accompanying file LICENSE or copy at\n\/\/ http:\/\/opensource.org\/licenses\/MIT)\n\/\/=======================================================================\n\n\/*!\n * \\file\n * \\brief Contains Template Metaprogramming (TMP) utilities\n *\/\n\n#ifndef CPP_UTILS_TMP_HPP\n#define CPP_UTILS_TMP_HPP\n\n#include <tuple>\n#include <utility>\n\n#include \"assert.hpp\"\n\n#include \"tmp\/tmp.hpp\"\n#include \"tmp\/sfinae.hpp\"\n#include \"tmp\/variadic.hpp\"\n\nnamespace cpp {\n\nnamespace tmp_detail {\n\n \/*!\n * \\brief Helper Traits to test if all the types from I to N in\n * T are homogeneous\n *\/\ntemplate <std::size_t I, std::size_t S, typename F, typename... T>\nstruct is_homogeneous_helper {\n \/*!\n * \\brief Sub helper for recursive instantiations\n *\/\n template <std::size_t I1, std::size_t S1, typename Enable = void>\n struct helper_int : and_helper<std::is_same<F, nth_type_t<I1, T...>>::value, is_homogeneous_helper<I1 + 1, S1, F, T...>::value> {};\n\n \/*!\n * \\copydoc helper_int\n *\/\n template <std::size_t I1, std::size_t S1>\n struct helper_int<I1, S1, std::enable_if_t<I1 == S1>> : std::is_same<F, nth_type_t<I1, T...>> {};\n\n static constexpr const auto value = helper_int<I, S>::value; \/\/\/< Indicates if the sequence of types is homogeneous\n};\n\n} \/\/end of namespace tmp_detail\n\n\/*!\n * \\brief Implementation of helper for for_each_tuple_t\n *\/\ntemplate <int I, typename Tuple, typename Functor>\nstruct for_each_tuple_t_impl {\n \/*!\n * \\brief Apply the functof for each elements in the tuple, from I\n *\/\n static void for_each(Functor&& func) {\n std::forward<Functor>(func).template operator()<typename std::tuple_element<I, Tuple>::type>();\n for_each_tuple_t_impl<I - 1, Tuple, Functor>::for_each(std::forward<Functor>(func));\n }\n};\n\n\/*!\n * \\copydoc for_each_tuple_t_impl\n *\/\ntemplate <typename Tuple, typename Functor>\nstruct for_each_tuple_t_impl<0, Tuple, Functor> {\n \/*!\n * \\brief Apply the functof for each elements in the tuple, from I\n *\/\n static void for_each(Functor&& func) {\n std::forward<Functor>(func).template operator()<typename std::tuple_element<0, Tuple>::type>();\n }\n};\n\n\/*!\n * \\copydoc for_each_tuple_t_impl\n *\/\ntemplate <typename Tuple, typename Functor>\nstruct for_each_tuple_t_impl<-1, Tuple, Functor> {\n \/*!\n * \\brief End of the the recursion\n *\/\n static void for_each(Functor&& \/*func*\/) {\n \/\/Nothing to be done\n }\n};\n\n\/*!\n * \\brief Call the given functor for each type in the tuple\n * \\tparam Tuple The tuple type\n * \\param func The functor to call\n *\/\ntemplate <typename Tuple, typename Functor>\nvoid for_each_tuple_t(Functor&& func) {\n for_each_tuple_t_impl<static_cast<int>(std::tuple_size<Tuple>::value) - 1, Tuple, Functor>::for_each(std::forward<Functor>(func));\n}\n\n\/*!\n * \\brief Traits to test if a type is a specialization of a template\n * \\tparam TT The template type\n * \\tparam T The type to test\n *\/\ntemplate <template <typename...> class TT, typename T>\nstruct is_specialization_of : std::false_type {};\n\n\/*!\n * \\copydoc is_specialization_of\n *\/\ntemplate <template <typename...> class TT, typename... Args>\nstruct is_specialization_of<TT, TT<Args...>> : std::true_type {};\n\n\/*!\n * \\brief Traits to test if all the given types are convertible to V\n * \\tparam V The target type\n * \\tparam F The first type to test\n * \\tparam S The types to test\n *\/\ntemplate <typename V, typename F, typename... S>\nstruct all_convertible_to : bool_constant_c<and_c<all_convertible_to<V, F>, all_convertible_to<V, S...>>> {};\n\n\/*!\n * \\copydoc all_convertible_to\n *\/\ntemplate <typename V, typename F>\nstruct all_convertible_to<V, F> : bool_constant_c<std::is_convertible<F, V>> {};\n\n\/*!\n * \\brief Test is a list of types homogeneous\n * \\tparam F The first type\n * \\tparam T The types\n *\/\ntemplate <typename F, typename... T>\nstruct is_homogeneous : bool_constant_c<tmp_detail::is_homogeneous_helper<0, sizeof...(T)-1, F, T...>> {};\n\n\/*!\n * \\copydoc all_convertible_to\n *\/\ntemplate <typename F>\nstruct is_homogeneous<F> : std::true_type {};\n\n\/*\n * \\brief Test if a list of types is sub-homogeneous\n *\n * A sub-homogeneous list of types is a list where the N-1 first types are the\n * same and the last one is different\n *\/\ntemplate <typename... T>\nstruct is_sub_homogeneous;\n\n\/*!\n * \\copydoc is_sub_homogeneous\n *\/\ntemplate <>\nstruct is_sub_homogeneous<> : std::false_type {};\n\n\/*!\n * \\copydoc is_sub_homogeneous\n *\/\ntemplate <typename T>\nstruct is_sub_homogeneous<T> : std::false_type {};\n\n\/*!\n * \\copydoc is_sub_homogeneous\n *\/\ntemplate <typename T1, typename T2>\nstruct is_sub_homogeneous<T1, T2> : bool_constant_c<not_c<std::is_same<T1, T2>>> {};\n\n\/*!\n * \\copydoc is_sub_homogeneous\n *\/\ntemplate <typename T1, typename T2, typename T3, typename... T>\nstruct is_sub_homogeneous<T1, T2, T3, T...> : bool_constant_c<\n and_c<\n std::is_same<T1, T2>,\n is_sub_homogeneous<T2, T3, T...>>> {};\n\n\/*!\n * \\brief Apply the given function to each element of the variadic\n * packs whose position is present in the sequence\n * \\param f The functor\n * \\param i The index sequence\n * \\param args The arguments\n *\/\ntemplate <typename F, std::size_t I1, std::size_t... I, typename... T, enable_if_u<(sizeof...(I) == 0)> = detail::dummy>\nvoid for_each_in_subset(F&& f, const std::index_sequence<I1, I...>& i, T&&... args) {\n f(std::forward<nth_type_t<I1, T...>>(nth_value<I1>(args...)));\n cpp_unused(i);\n}\n\n\/*!\n * \\brief Apply the given function to each element of the variadic\n * packs whose position is present in the sequence\n * \\param f The functor\n * \\param i The index sequence\n * \\param args The arguments\n *\/\ntemplate <typename F, std::size_t I1, std::size_t... I, typename... T, enable_if_u<(sizeof...(I) > 0)> = detail::dummy>\nvoid for_each_in_subset(F&& f, const std::index_sequence<I1, I...>& i, T&&... args) {\n f(std::forward<nth_type_t<I1, T...>>(nth_value<I1>(args...)));\n for_each_in_subset(f, std::index_sequence<I...>(), std::forward<T>(args)...);\n cpp_unused(i);\n}\n\n\/*!\n * \\brief Apply the given function to each element of the variadic pack\n * \\param f The functor\n * \\param args The arguments\n *\/\ntemplate <typename F, typename... T>\nvoid for_each_in(F&& f, T&&... args) {\n for_each_in_subset(f, std::make_index_sequence<sizeof...(T)>(), std::forward<T>(args)...);\n}\n\n\/*!\n * \\brief Test if the variadic list of types containg the given type\n * \\tparam T1 The type to search\n * \\tparam T The list of types\n *\/\ntemplate <typename T1, typename... T>\nstruct variadic_contains;\n\n\/*!\n * \\copydoc variadic_contains\n *\/\ntemplate <typename T1, typename T2, typename... T>\nstruct variadic_contains<T1, T2, T...> : bool_constant_c<or_c<std::is_same<T1, T2>, variadic_contains<T1, T...>>> {};\n\n\/*!\n * \\copydoc variadic_contains\n *\/\ntemplate <typename T1>\nstruct variadic_contains<T1> : std::false_type {};\n\n\/*!\n * \\brief A compile-time type list.\n *\/\ntemplate <typename... T>\nstruct type_list {\n \/*!\n * \\brief Indicates if the list contains the given type\n * \\tparam V The type to search in the list\n * \\return true if the type is in the list, false otherwise.\n *\/\n template <typename V>\n static constexpr bool contains() {\n return variadic_contains<V, T...>::value;\n }\n};\n\n} \/\/end of namespace cpp\n\n#endif \/\/CPP_UTILS_TMP_HPP\n<|endoftext|>"} {"text":"<commit_before>\/****************************************************************************\n**\n** Copyright (C) 2014 Digia Plc and\/or its subsidiary(-ies).\n** Contact: http:\/\/www.qt-project.org\/legal\n**\n** This file is part of Qt Creator.\n**\n** Commercial License Usage\n** Licensees holding valid commercial Qt licenses may use this file in\n** accordance with the commercial license agreement provided with the\n** Software or, alternatively, in accordance with the terms contained in\n** a written agreement between you and Digia. For licensing terms and\n** conditions see http:\/\/www.qt.io\/licensing. For further information\n** use the contact form at http:\/\/www.qt.io\/contact-us.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 or version 3 as published by the Free\n** Software Foundation and appearing in the file LICENSE.LGPLv21 and\n** LICENSE.LGPLv3 included in the packaging of this file. Please review the\n** following information to ensure the GNU Lesser General Public License\n** requirements will be met: https:\/\/www.gnu.org\/licenses\/lgpl.html and\n** http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Digia gives you certain additional\n** rights. These rights are described in the Digia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n****************************************************************************\/\n\n#include \"jsonwizard.h\"\n\n#include \"jsonwizardgeneratorfactory.h\"\n\n#include <utils\/algorithm.h>\n#include <utils\/qtcassert.h>\n\n#include <QFileInfo>\n#include <QMessageBox>\n#include <QVariant>\n\nnamespace ProjectExplorer {\n\nJsonWizard::JsonWizard(QWidget *parent) :\n Utils::Wizard(parent)\n{\n m_expander.registerExtraResolver([this](const QString &name, QString *ret) -> bool {\n QVariant v = value(name);\n if (v.isValid()) {\n if (v.type() == QVariant::Bool)\n *ret = v.toBool() ? QLatin1String(\"true\") : QString();\n else\n *ret = v.toString();\n }\n return v.isValid();\n });\n m_expander.registerPrefix(\"Exists\", tr(\"Check whether a variable exists. Returns \\\"true\\\" if it does and an empty string if not.\"),\n [this](const QString &value) -> QString\n {\n const QString key = QString::fromLatin1(\"%{\") + value + QLatin1Char('}');\n return m_expander.expand(key) == key ? QString() : QLatin1String(\"true\");\n });\n\n}\n\nJsonWizard::~JsonWizard()\n{\n qDeleteAll(m_generators);\n}\n\nvoid JsonWizard::addGenerator(JsonWizardGenerator *gen)\n{\n QTC_ASSERT(gen, return);\n QTC_ASSERT(!m_generators.contains(gen), return);\n\n m_generators.append(gen);\n}\n\nUtils::MacroExpander *JsonWizard::expander()\n{\n return &m_expander;\n}\n\nvoid JsonWizard::resetFileList()\n{\n m_files.clear();\n}\n\nJsonWizard::GeneratorFiles JsonWizard::fileList()\n{\n QString errorMessage;\n GeneratorFiles list;\n\n QString targetPath = value(QLatin1String(\"TargetPath\")).toString();\n if (targetPath.isEmpty()) {\n errorMessage = tr(\"Could not determine target path. \\\"TargetPath\\\" was not set on any page.\");\n return list;\n }\n\n if (m_files.isEmpty()) {\n emit preGenerateFiles();\n foreach (JsonWizardGenerator *gen, m_generators) {\n Core::GeneratedFiles tmp = gen->fileList(&m_expander, value(QStringLiteral(\"WizardDir\")).toString(),\n targetPath, &errorMessage);\n if (!errorMessage.isEmpty())\n break;\n list.append(Utils::transform(tmp, [&gen](const Core::GeneratedFile &f)\n { return JsonWizard::GeneratorFile(f, gen); }));\n }\n\n if (errorMessage.isEmpty())\n m_files = list;\n emit postGenerateFiles(m_files);\n }\n\n if (!errorMessage.isEmpty()) {\n QMessageBox::critical(this, tr(\"File Generation Failed\"),\n tr(\"The wizard failed to generate files.<br>\"\n \"The error message was: \\\"%1\\\".\").arg(errorMessage));\n reject();\n return GeneratorFiles();\n }\n\n return m_files;\n}\n\nQVariant JsonWizard::value(const QString &n) const\n{\n QVariant v = property(n.toUtf8());\n if (v.isValid()) {\n if (v.type() == QVariant::String)\n return m_expander.expand(v.toString());\n else\n return v;\n }\n if (hasField(n))\n return field(n); \/\/ Can not contain macros!\n return QVariant();\n}\n\nvoid JsonWizard::setValue(const QString &key, const QVariant &value)\n{\n setProperty(key.toUtf8(), value);\n}\n\nbool JsonWizard::boolFromVariant(const QVariant &v, Utils::MacroExpander *expander)\n{\n if (v.type() == QVariant::String)\n return !expander->expand(v.toString()).isEmpty();\n return v.toBool();\n}\n\nvoid JsonWizard::removeAttributeFromAllFiles(Core::GeneratedFile::Attribute a)\n{\n for (int i = 0; i < m_files.count(); ++i)\n m_files[i].file.setAttributes(m_files.at(i).file.attributes() ^ a);\n}\n\nvoid JsonWizard::accept()\n{\n Utils::Wizard::accept();\n\n QString errorMessage;\n GeneratorFiles list = fileList();\n\n if (list.isEmpty())\n return;\n\n emit prePromptForOverwrite(m_files);\n JsonWizardGenerator::OverwriteResult overwrite =\n JsonWizardGenerator::promptForOverwrite(&list, &errorMessage);\n if (overwrite == JsonWizardGenerator::OverwriteError) {\n if (!errorMessage.isEmpty())\n QMessageBox::warning(this, tr(\"Failed to Overwrite Files\"), errorMessage);\n return;\n }\n\n emit preFormatFiles(m_files);\n if (!JsonWizardGenerator::formatFiles(this, &list, &errorMessage)) {\n if (!errorMessage.isEmpty())\n QMessageBox::warning(this, tr(\"Failed to Format Files\"), errorMessage);\n return;\n }\n\n emit preWriteFiles(m_files);\n if (!JsonWizardGenerator::writeFiles(this, &list, &errorMessage)) {\n if (!errorMessage.isEmpty())\n QMessageBox::warning(this, tr(\"Failed to Write Files\"), errorMessage);\n return;\n }\n\n emit postProcessFiles(m_files);\n if (!JsonWizardGenerator::postWrite(this, &list, &errorMessage)) {\n if (!errorMessage.isEmpty())\n QMessageBox::warning(this, tr(\"Failed to Post-Process Files\"), errorMessage);\n return;\n }\n emit filesReady(m_files);\n if (!JsonWizardGenerator::allDone(this, &list, &errorMessage)) {\n if (!errorMessage.isEmpty())\n QMessageBox::warning(this, tr(\"Failed to Open Files\"), errorMessage);\n return;\n }\n\n emit allDone(m_files);\n}\n\n} \/\/ namespace ProjectExplorer\n<commit_msg>JsonWizard: Force minimum size to something sensible<commit_after>\/****************************************************************************\n**\n** Copyright (C) 2014 Digia Plc and\/or its subsidiary(-ies).\n** Contact: http:\/\/www.qt-project.org\/legal\n**\n** This file is part of Qt Creator.\n**\n** Commercial License Usage\n** Licensees holding valid commercial Qt licenses may use this file in\n** accordance with the commercial license agreement provided with the\n** Software or, alternatively, in accordance with the terms contained in\n** a written agreement between you and Digia. For licensing terms and\n** conditions see http:\/\/www.qt.io\/licensing. For further information\n** use the contact form at http:\/\/www.qt.io\/contact-us.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 or version 3 as published by the Free\n** Software Foundation and appearing in the file LICENSE.LGPLv21 and\n** LICENSE.LGPLv3 included in the packaging of this file. Please review the\n** following information to ensure the GNU Lesser General Public License\n** requirements will be met: https:\/\/www.gnu.org\/licenses\/lgpl.html and\n** http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Digia gives you certain additional\n** rights. These rights are described in the Digia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n****************************************************************************\/\n\n#include \"jsonwizard.h\"\n\n#include \"jsonwizardgeneratorfactory.h\"\n\n#include <utils\/algorithm.h>\n#include <utils\/qtcassert.h>\n\n#include <QFileInfo>\n#include <QMessageBox>\n#include <QVariant>\n\nnamespace ProjectExplorer {\n\nJsonWizard::JsonWizard(QWidget *parent) :\n Utils::Wizard(parent)\n{\n setMinimumSize(800, 500);\n m_expander.registerExtraResolver([this](const QString &name, QString *ret) -> bool {\n QVariant v = value(name);\n if (v.isValid()) {\n if (v.type() == QVariant::Bool)\n *ret = v.toBool() ? QLatin1String(\"true\") : QString();\n else\n *ret = v.toString();\n }\n return v.isValid();\n });\n m_expander.registerPrefix(\"Exists\", tr(\"Check whether a variable exists. Returns \\\"true\\\" if it does and an empty string if not.\"),\n [this](const QString &value) -> QString\n {\n const QString key = QString::fromLatin1(\"%{\") + value + QLatin1Char('}');\n return m_expander.expand(key) == key ? QString() : QLatin1String(\"true\");\n });\n\n}\n\nJsonWizard::~JsonWizard()\n{\n qDeleteAll(m_generators);\n}\n\nvoid JsonWizard::addGenerator(JsonWizardGenerator *gen)\n{\n QTC_ASSERT(gen, return);\n QTC_ASSERT(!m_generators.contains(gen), return);\n\n m_generators.append(gen);\n}\n\nUtils::MacroExpander *JsonWizard::expander()\n{\n return &m_expander;\n}\n\nvoid JsonWizard::resetFileList()\n{\n m_files.clear();\n}\n\nJsonWizard::GeneratorFiles JsonWizard::fileList()\n{\n QString errorMessage;\n GeneratorFiles list;\n\n QString targetPath = value(QLatin1String(\"TargetPath\")).toString();\n if (targetPath.isEmpty()) {\n errorMessage = tr(\"Could not determine target path. \\\"TargetPath\\\" was not set on any page.\");\n return list;\n }\n\n if (m_files.isEmpty()) {\n emit preGenerateFiles();\n foreach (JsonWizardGenerator *gen, m_generators) {\n Core::GeneratedFiles tmp = gen->fileList(&m_expander, value(QStringLiteral(\"WizardDir\")).toString(),\n targetPath, &errorMessage);\n if (!errorMessage.isEmpty())\n break;\n list.append(Utils::transform(tmp, [&gen](const Core::GeneratedFile &f)\n { return JsonWizard::GeneratorFile(f, gen); }));\n }\n\n if (errorMessage.isEmpty())\n m_files = list;\n emit postGenerateFiles(m_files);\n }\n\n if (!errorMessage.isEmpty()) {\n QMessageBox::critical(this, tr(\"File Generation Failed\"),\n tr(\"The wizard failed to generate files.<br>\"\n \"The error message was: \\\"%1\\\".\").arg(errorMessage));\n reject();\n return GeneratorFiles();\n }\n\n return m_files;\n}\n\nQVariant JsonWizard::value(const QString &n) const\n{\n QVariant v = property(n.toUtf8());\n if (v.isValid()) {\n if (v.type() == QVariant::String)\n return m_expander.expand(v.toString());\n else\n return v;\n }\n if (hasField(n))\n return field(n); \/\/ Can not contain macros!\n return QVariant();\n}\n\nvoid JsonWizard::setValue(const QString &key, const QVariant &value)\n{\n setProperty(key.toUtf8(), value);\n}\n\nbool JsonWizard::boolFromVariant(const QVariant &v, Utils::MacroExpander *expander)\n{\n if (v.type() == QVariant::String)\n return !expander->expand(v.toString()).isEmpty();\n return v.toBool();\n}\n\nvoid JsonWizard::removeAttributeFromAllFiles(Core::GeneratedFile::Attribute a)\n{\n for (int i = 0; i < m_files.count(); ++i)\n m_files[i].file.setAttributes(m_files.at(i).file.attributes() ^ a);\n}\n\nvoid JsonWizard::accept()\n{\n Utils::Wizard::accept();\n\n QString errorMessage;\n GeneratorFiles list = fileList();\n\n if (list.isEmpty())\n return;\n\n emit prePromptForOverwrite(m_files);\n JsonWizardGenerator::OverwriteResult overwrite =\n JsonWizardGenerator::promptForOverwrite(&list, &errorMessage);\n if (overwrite == JsonWizardGenerator::OverwriteError) {\n if (!errorMessage.isEmpty())\n QMessageBox::warning(this, tr(\"Failed to Overwrite Files\"), errorMessage);\n return;\n }\n\n emit preFormatFiles(m_files);\n if (!JsonWizardGenerator::formatFiles(this, &list, &errorMessage)) {\n if (!errorMessage.isEmpty())\n QMessageBox::warning(this, tr(\"Failed to Format Files\"), errorMessage);\n return;\n }\n\n emit preWriteFiles(m_files);\n if (!JsonWizardGenerator::writeFiles(this, &list, &errorMessage)) {\n if (!errorMessage.isEmpty())\n QMessageBox::warning(this, tr(\"Failed to Write Files\"), errorMessage);\n return;\n }\n\n emit postProcessFiles(m_files);\n if (!JsonWizardGenerator::postWrite(this, &list, &errorMessage)) {\n if (!errorMessage.isEmpty())\n QMessageBox::warning(this, tr(\"Failed to Post-Process Files\"), errorMessage);\n return;\n }\n emit filesReady(m_files);\n if (!JsonWizardGenerator::allDone(this, &list, &errorMessage)) {\n if (!errorMessage.isEmpty())\n QMessageBox::warning(this, tr(\"Failed to Open Files\"), errorMessage);\n return;\n }\n\n emit allDone(m_files);\n}\n\n} \/\/ namespace ProjectExplorer\n<|endoftext|>"} {"text":"<commit_before>\/**************************************************************************\n**\n** Copyright (C) 2012 - 2014 BlackBerry Limited. All rights reserved.\n**\n** Contact: BlackBerry (qt@blackberry.com)\n** Contact: KDAB (info@kdab.com)\n**\n** This file is part of Qt Creator.\n**\n** Commercial License Usage\n** Licensees holding valid commercial Qt licenses may use this file in\n** accordance with the commercial license agreement provided with the\n** Software or, alternatively, in accordance with the terms contained in\n** a written agreement between you and Digia. For licensing terms and\n** conditions see http:\/\/qt.digia.com\/licensing. For further information\n** use the contact form at http:\/\/qt.digia.com\/contact-us.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Digia gives you certain additional\n** rights. These rights are described in the Digia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n****************************************************************************\/\n\n#include \"blackberryrunconfigurationfactory.h\"\n#include \"qnxconstants.h\"\n#include \"blackberryrunconfiguration.h\"\n#include \"blackberrydeviceconfigurationfactory.h\"\n\n#include <projectexplorer\/kitinformation.h>\n#include <projectexplorer\/target.h>\n#include <qmakeprojectmanager\/qmakeproject.h>\n#include <qmakeprojectmanager\/qmakenodes.h>\n\nusing namespace Qnx;\nusing namespace Qnx::Internal;\n\nstatic QString pathFromId(Core::Id id)\n{\n return id.suffixAfter(Constants::QNX_BB_RUNCONFIGURATION_PREFIX);\n}\n\nBlackBerryRunConfigurationFactory::BlackBerryRunConfigurationFactory(QObject *parent) :\n ProjectExplorer::IRunConfigurationFactory(parent)\n{\n}\n\nQList<Core::Id> BlackBerryRunConfigurationFactory::availableCreationIds(ProjectExplorer::Target *parent, CreationMode mode) const\n{\n using QmakeProjectManager::QmakeProject;\n if (!canHandle(parent))\n return QList<Core::Id>();\n\n QmakeProject *qt4Project = qobject_cast<QmakeProject *>(parent->project());\n if (!qt4Project)\n return QList<Core::Id>();\n\n QList<QmakeProjectManager::QmakeProFileNode *> nodes = qt4Project->applicationProFiles();\n if (mode == AutoCreate)\n nodes = QmakeProject::nodesWithQtcRunnable(nodes);\n return QmakeProject::idsForNodes(Core::Id(Constants::QNX_QNX_RUNCONFIGURATION_PREFIX),\n nodes);\n}\n\nQString BlackBerryRunConfigurationFactory::displayNameForId(Core::Id id) const\n{\n const QString path = pathFromId(id);\n if (path.isEmpty())\n return QString();\n\n if (id.name().startsWith(Constants::QNX_BB_RUNCONFIGURATION_PREFIX))\n return QFileInfo(path).completeBaseName();\n\n return QString();\n}\n\nbool BlackBerryRunConfigurationFactory::canCreate(ProjectExplorer::Target *parent, Core::Id id) const\n{\n if (!canHandle(parent))\n return false;\n\n QmakeProjectManager::QmakeProject *qt4Project = qobject_cast<QmakeProjectManager::QmakeProject *>(parent->project());\n if (!qt4Project)\n return false;\n\n if (!id.name().startsWith(Constants::QNX_BB_RUNCONFIGURATION_PREFIX))\n return false;\n\n return qt4Project->hasApplicationProFile(pathFromId(id));\n}\n\nProjectExplorer::RunConfiguration *BlackBerryRunConfigurationFactory::doCreate(ProjectExplorer::Target *parent,\n const Core::Id id)\n{\n return new BlackBerryRunConfiguration(parent, id, pathFromId(id));\n}\n\nbool BlackBerryRunConfigurationFactory::canRestore(ProjectExplorer::Target *parent,\n const QVariantMap &map) const\n{\n if (!canHandle(parent))\n return false;\n\n return ProjectExplorer::idFromMap(map).name().startsWith(Constants::QNX_BB_RUNCONFIGURATION_PREFIX);\n}\n\nProjectExplorer::RunConfiguration *BlackBerryRunConfigurationFactory::doRestore(\n ProjectExplorer::Target *parent,\n const QVariantMap &map)\n{\n Q_UNUSED(map);\n return new BlackBerryRunConfiguration(parent, Core::Id(Constants::QNX_BB_RUNCONFIGURATION_PREFIX), QString());\n}\n\nbool BlackBerryRunConfigurationFactory::canClone(ProjectExplorer::Target *parent,\n ProjectExplorer::RunConfiguration *source) const\n{\n return canCreate(parent, source->id());\n}\n\nProjectExplorer::RunConfiguration *BlackBerryRunConfigurationFactory::clone(\n ProjectExplorer::Target *parent,\n ProjectExplorer::RunConfiguration *source)\n{\n if (!canClone(parent, source))\n return 0;\n\n BlackBerryRunConfiguration *old = static_cast<BlackBerryRunConfiguration *>(source);\n return new BlackBerryRunConfiguration(parent, old);\n\n}\n\nbool BlackBerryRunConfigurationFactory::canHandle(ProjectExplorer::Target *t) const\n{\n if (!t->project()->supportsKit(t->kit()))\n return false;\n if (!qobject_cast<QmakeProjectManager::QmakeProject *>(t->project()))\n return false;\n\n Core::Id deviceType = ProjectExplorer::DeviceTypeKitInformation::deviceTypeId(t->kit());\n if (deviceType != BlackBerryDeviceConfigurationFactory::deviceType())\n return false;\n\n return true;\n}\n<commit_msg>Qnx: Fix the Id for the BlackBerry run configuration<commit_after>\/**************************************************************************\n**\n** Copyright (C) 2012 - 2014 BlackBerry Limited. All rights reserved.\n**\n** Contact: BlackBerry (qt@blackberry.com)\n** Contact: KDAB (info@kdab.com)\n**\n** This file is part of Qt Creator.\n**\n** Commercial License Usage\n** Licensees holding valid commercial Qt licenses may use this file in\n** accordance with the commercial license agreement provided with the\n** Software or, alternatively, in accordance with the terms contained in\n** a written agreement between you and Digia. For licensing terms and\n** conditions see http:\/\/qt.digia.com\/licensing. For further information\n** use the contact form at http:\/\/qt.digia.com\/contact-us.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Digia gives you certain additional\n** rights. These rights are described in the Digia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n****************************************************************************\/\n\n#include \"blackberryrunconfigurationfactory.h\"\n#include \"qnxconstants.h\"\n#include \"blackberryrunconfiguration.h\"\n#include \"blackberrydeviceconfigurationfactory.h\"\n\n#include <projectexplorer\/kitinformation.h>\n#include <projectexplorer\/target.h>\n#include <qmakeprojectmanager\/qmakeproject.h>\n#include <qmakeprojectmanager\/qmakenodes.h>\n\nusing namespace Qnx;\nusing namespace Qnx::Internal;\n\nstatic QString pathFromId(Core::Id id)\n{\n return id.suffixAfter(Constants::QNX_BB_RUNCONFIGURATION_PREFIX);\n}\n\nBlackBerryRunConfigurationFactory::BlackBerryRunConfigurationFactory(QObject *parent) :\n ProjectExplorer::IRunConfigurationFactory(parent)\n{\n}\n\nQList<Core::Id> BlackBerryRunConfigurationFactory::availableCreationIds(ProjectExplorer::Target *parent, CreationMode mode) const\n{\n using QmakeProjectManager::QmakeProject;\n if (!canHandle(parent))\n return QList<Core::Id>();\n\n QmakeProject *qt4Project = qobject_cast<QmakeProject *>(parent->project());\n if (!qt4Project)\n return QList<Core::Id>();\n\n QList<QmakeProjectManager::QmakeProFileNode *> nodes = qt4Project->applicationProFiles();\n if (mode == AutoCreate)\n nodes = QmakeProject::nodesWithQtcRunnable(nodes);\n return QmakeProject::idsForNodes(Core::Id(Constants::QNX_BB_RUNCONFIGURATION_PREFIX),\n nodes);\n}\n\nQString BlackBerryRunConfigurationFactory::displayNameForId(Core::Id id) const\n{\n const QString path = pathFromId(id);\n if (path.isEmpty())\n return QString();\n\n if (id.name().startsWith(Constants::QNX_BB_RUNCONFIGURATION_PREFIX))\n return QFileInfo(path).completeBaseName();\n\n return QString();\n}\n\nbool BlackBerryRunConfigurationFactory::canCreate(ProjectExplorer::Target *parent, Core::Id id) const\n{\n if (!canHandle(parent))\n return false;\n\n QmakeProjectManager::QmakeProject *qt4Project = qobject_cast<QmakeProjectManager::QmakeProject *>(parent->project());\n if (!qt4Project)\n return false;\n\n if (!id.name().startsWith(Constants::QNX_BB_RUNCONFIGURATION_PREFIX))\n return false;\n\n return qt4Project->hasApplicationProFile(pathFromId(id));\n}\n\nProjectExplorer::RunConfiguration *BlackBerryRunConfigurationFactory::doCreate(ProjectExplorer::Target *parent,\n const Core::Id id)\n{\n return new BlackBerryRunConfiguration(parent, id, pathFromId(id));\n}\n\nbool BlackBerryRunConfigurationFactory::canRestore(ProjectExplorer::Target *parent,\n const QVariantMap &map) const\n{\n if (!canHandle(parent))\n return false;\n\n return ProjectExplorer::idFromMap(map).name().startsWith(Constants::QNX_BB_RUNCONFIGURATION_PREFIX);\n}\n\nProjectExplorer::RunConfiguration *BlackBerryRunConfigurationFactory::doRestore(\n ProjectExplorer::Target *parent,\n const QVariantMap &map)\n{\n Q_UNUSED(map);\n return new BlackBerryRunConfiguration(parent, Core::Id(Constants::QNX_BB_RUNCONFIGURATION_PREFIX), QString());\n}\n\nbool BlackBerryRunConfigurationFactory::canClone(ProjectExplorer::Target *parent,\n ProjectExplorer::RunConfiguration *source) const\n{\n return canCreate(parent, source->id());\n}\n\nProjectExplorer::RunConfiguration *BlackBerryRunConfigurationFactory::clone(\n ProjectExplorer::Target *parent,\n ProjectExplorer::RunConfiguration *source)\n{\n if (!canClone(parent, source))\n return 0;\n\n BlackBerryRunConfiguration *old = static_cast<BlackBerryRunConfiguration *>(source);\n return new BlackBerryRunConfiguration(parent, old);\n\n}\n\nbool BlackBerryRunConfigurationFactory::canHandle(ProjectExplorer::Target *t) const\n{\n if (!t->project()->supportsKit(t->kit()))\n return false;\n if (!qobject_cast<QmakeProjectManager::QmakeProject *>(t->project()))\n return false;\n\n Core::Id deviceType = ProjectExplorer::DeviceTypeKitInformation::deviceTypeId(t->kit());\n if (deviceType != BlackBerryDeviceConfigurationFactory::deviceType())\n return false;\n\n return true;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * This program is free software; you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or\n * (at your option) any later version.\n *\n * Written (W) 2012 Fernando José Iglesias García\n * Copyright (C) 2012 Fernando José Iglesias García\n *\/\n\n#include <shogun\/converter\/StochasticProximityEmbedding.h>\n#include <shogun\/lib\/config.h>\n#ifdef HAVE_LAPACK\n#include <shogun\/converter\/EmbeddingConverter.h>\n#include <shogun\/io\/SGIO.h>\n#include <shogun\/lib\/CoverTree.h>\n#include <shogun\/mathematics\/Math.h>\n#include <shogun\/distance\/Distance.h>\n\nusing namespace shogun;\n\nclass SPE_COVERTREE_POINT\n{\npublic:\n\n\tSPE_COVERTREE_POINT(int32_t index, const SGMatrix<float64_t>& dmatrix)\n\t{\n\t\tpoint_index = index;\n\t\tdistance_matrix = dmatrix;\n\t}\n\n\tinline double distance(const SPE_COVERTREE_POINT& p) const\n\t{\n\t\treturn distance_matrix[point_index*distance_matrix.num_rows+p.point_index];\n\t}\n\n\tinline bool operator==(const SPE_COVERTREE_POINT& p) const\n\t{\n\t\treturn (p.point_index==point_index);\n\t}\n\n\tint32_t point_index;\n\tSGMatrix<float64_t> distance_matrix;\n};\n\nCStochasticProximityEmbedding::CStochasticProximityEmbedding() : \n\tCEmbeddingConverter()\n{\n\t\/\/ Initialize to default values\n\tm_k = 12;\n\tm_nupdates = 100;\n\tm_strategy = SPE_GLOBAL;\n\tm_tolerance = 1e-5;\n\n\tinit();\n}\n\nvoid CStochasticProximityEmbedding::init()\n{\n\tSG_ADD(&m_k, \"m_k\", \"Number of neighbors\", MS_NOT_AVAILABLE);\n\tSG_ADD((machine_int_t*) &m_strategy, \"m_strategy\", \"SPE strategy\", \n\t\t\tMS_NOT_AVAILABLE);\n\tSG_ADD(&m_tolerance, \"m_tolerance\", \"Regularization parameter\", \n\t\t\tMS_NOT_AVAILABLE);\n}\n\nCStochasticProximityEmbedding::~CStochasticProximityEmbedding()\n{\n}\n\nvoid CStochasticProximityEmbedding::set_k(int32_t k)\n{\n\tif ( k <= 0 )\n\t\tSG_ERROR(\"Number of neighbors k must be greater than 0\");\n\n\tm_k = k;\n}\n\nint32_t CStochasticProximityEmbedding::get_k() const\n{\n\treturn m_k;\n}\n\nvoid CStochasticProximityEmbedding::set_strategy(ESPEStrategy strategy)\n{\n\tm_strategy = strategy;\n}\n\nESPEStrategy CStochasticProximityEmbedding::get_strategy() const\n{\n\treturn m_strategy;\n}\n\nvoid CStochasticProximityEmbedding::set_tolerance(float32_t tolerance)\n{\n\tif ( tolerance <= 0 )\n\t\tSG_ERROR(\"Tolerance regularization parameter must be greater \"\n\t\t\t \"than 0\");\n\n\tm_tolerance = tolerance;\n}\n\nint32_t CStochasticProximityEmbedding::get_tolerance() const\n{\n\treturn m_tolerance;\n}\n\nvoid CStochasticProximityEmbedding::set_nupdates(int32_t nupdates)\n{\n\tif ( nupdates <= 0 )\n\t\tSG_ERROR(\"The number of updates must be greater than 0\");\n\n\tm_nupdates = nupdates;\n}\n\nint32_t CStochasticProximityEmbedding::get_nupdates() const\n{\n\treturn m_nupdates;\n}\n\nconst char * CStochasticProximityEmbedding::get_name() const\n{\n\treturn \"StochasticProximityEmbedding\";\n}\n\nCFeatures* CStochasticProximityEmbedding::apply(CFeatures* features)\n{\n\tif ( !features )\n\t\tSG_ERROR(\"Features are required to apply SPE\\n\");\n\n\tif ( !(features->get_feature_class() == C_SIMPLE &&\n\t features->get_feature_type() == F_DREAL) )\n\t\tSG_ERROR(\"Features must be dense real features\\n\");\n\n\t\/\/ Shorthand for the SimpleFeatures\n\tCSimpleFeatures< float64_t >* simple_features = \n\t\t(CSimpleFeatures< float64_t >*) features;\n\tSG_REF(features);\n\n\t\/\/ Get and check the number of vectors\n\tint32_t N = simple_features->get_num_vectors();\n\tif ( m_strategy == SPE_LOCAL && m_k >= N )\n\t\tSG_ERROR(\"The number of neighbors (%d) must be less than \"\n\t\t \"the number of vectors (%d)\\n\", m_k, N);\n\n\tif ( 2*m_nupdates > N )\n\t\tSG_ERROR(\"The number of vectors (%d) must be at least two times \"\n\t\t\t \"the number of updates (%d)\\n\", N, m_nupdates);\n\n\t\/\/ Compute distance matrix\n\tSG_DEBUG(\"Computing distance matrix\\n\");\n\n\tif ( m_distance->get_distance_type() != D_EUCLIDIAN )\n\t\tSG_ERROR(\"SPE only supports Euclidian distance, %s given\\n\", \n\t\t\t\tm_distance->get_name());\n\n\tm_distance->init(simple_features, simple_features);\n\tSGMatrix< float64_t > distance_matrix = m_distance->get_distance_matrix();\n\tm_distance->remove_lhs_and_rhs();\n\n\t\/\/ Normalize the distance matrix if global strategy used\n\tif ( m_strategy == SPE_GLOBAL )\n\t{\n\t\tfloat64_t alpha = 1.0 \/ CMath::max(distance_matrix.matrix, N*N) \n\t\t\t\t\t* CMath::sqrt(2.0);\n\t\tCMath::scale_vector(alpha, distance_matrix.matrix, N*N);\n\t}\n\n\t\/\/ Compute neighborhood matrix if local strategy used\n\tSGMatrix< int32_t > neighbors_mat;\n\tif ( m_strategy == SPE_LOCAL )\n\t{\n\t\tSG_DEBUG(\"Computing neighborhood matrix\\n\");\n\t\tneighbors_mat = get_neighborhood_matrix(distance_matrix, m_k);\n\t}\n\n\t\/\/ Initialize vectors in the embedded space randomly, Y is the short for\n\t\/\/ new_feature_matrix\n\tSGMatrix< float64_t > Y(m_target_dim, N);\n\tCMath::random_vector(Y.matrix, m_target_dim*N, 0.0, 1.0);\n\n\t\/\/ SPE's loop\n\t\n\t\/\/ Initialize the maximum number of iterations\n\tint32_t max_iter = 2000 + CMath::round(0.04 * N*N);\n\tif ( m_strategy == SPE_LOCAL )\n\t\tmax_iter *= 3;\n\n\t\/\/ Initialize the learning parameter\n\tfloat32_t lambda = 1.0;\n\n\t\/\/ Initialize variables to use in the main loop\n\tint32_t i, j, k;\n\tfloat64_t sum = 0.0;\n\tindex_t idx1 = 0, idx2 = 0, idx = 0;\n\n\tSGVector< float64_t > scale(m_nupdates);\n\tSGVector< float64_t > D(m_nupdates);\n\tSGMatrix< float64_t > Yd(m_nupdates, m_target_dim);\n\tSGVector< float64_t > Rt(m_nupdates);\n\tint32_t* ind2 = NULL;\n\n\t\/\/ Variables required just if local strategy used\n\tSGMatrix< int32_t > ind1Neighbors;\n\tSGVector< int32_t > J2;\n\tif ( m_strategy == SPE_LOCAL )\n\t{\n\t\tind2 = SG_MALLOC(int32_t, m_nupdates);\n\n\t\tCMath::resize(ind1Neighbors.matrix, 0, m_k*m_nupdates);\n\t\tind1Neighbors.num_rows = m_k;\n\t\tind1Neighbors.num_cols = m_nupdates;\n\n\t\tCMath::resize(J2.vector, 0, m_nupdates);\n\t\tJ2.vlen = m_nupdates;\n\t}\n\n\tfor ( i = 0 ; i < max_iter ; ++i )\n\t{\n\t\tif ( !(i % 1000) )\n\t\t\tSG_DEBUG(\"SPE's loop, iteration %d of %d\\n\", i, max_iter);\n\n\t\t\/\/ Select the vectors to be updated in this iteration\n\t\tint32_t* J = CMath::randperm(N);\n\n\t\t\/\/ Pointer to the first set of vector indices to update\n\t\tint32_t* ind1 = J;\n\n\t\t\/\/ Pointer ind2 to the second set of vector indices to update\n\t\tif ( m_strategy == SPE_GLOBAL )\n\t\t\tind2 = J + m_nupdates;\n\t\telse\n\t\t{\n\t\t\t\/\/ Select the second set of indices to update among neighbors\n\t\t\t\/\/ of the first set\n\t\t\t\t\n\t\t\t\/\/ Get the neighbors of interest\n\t\t\tfor ( j = 0 ; j < m_nupdates ; ++j )\n\t\t\t{\n\t\t\t\tfor ( k = 0 ; k < m_k ; ++k )\n\t\t\t\t\tind1Neighbors[k + j*m_k] =\n\t\t\t\t\t\tneighbors_mat.matrix[k + ind1[j]*m_k];\n\t\t\t}\n\n\t\t\t\/\/ Generate pseudo-random indices\n\t\t\tfor ( j = 0 ; j < m_nupdates ; ++j )\n\t\t\t{\n\t\t\t\tJ2[j] = CMath::round( CMath::random(0.0, 1.0)*(m_k-1) )\n\t\t\t\t\t\t+ m_k*j;\n\t\t\t}\n\n\t\t\t\/\/ Select final indices\n\t\t\tfor ( j = 0 ; j < m_nupdates ; ++j )\n\t\t\t\tind2[j] = ind1Neighbors.matrix[ J2[j] ];\n\t\t}\n\n\t\t\/\/ Compute distances betweeen the selected points in embedded space\n\n\t\tfor ( j = 0 ; j < m_nupdates ; ++j )\n\t\t{\n\t\t\tsum = 0.0;\n\n\t\t\tfor ( k = 0 ; k < m_target_dim ; ++k )\n\t\t\t{\n\t\t\t\tidx1 = k + ind1[j]*m_target_dim;\n\t\t\t\tidx2 = k + ind2[j]*m_target_dim;\n\t\t\t\tsum += CMath::sq(Y.matrix[idx1] - Y.matrix[idx2]);\n\t\t\t}\n\n\t\t\tD[j] = CMath::sqrt(sum);\n\t\t}\n\n\t\t\/\/ Get the corresponding distances in the original space\n\t\tfor ( j = 0 ; j < m_nupdates ; ++j )\n\t\t\tRt[j] = distance_matrix.matrix[ ind1[j]*N + ind2[j] ];\n\n\t\t\/\/ Compute some terms for update\n\n\t\t\/\/ Scale factor: (Rt - D) .\/ (D + m_tolerance)\n\t\tfor ( j = 0 ; j < m_nupdates ; ++j )\n\t\t\tscale[j] = ( Rt[j] - D[j] ) \/ ( D[j] + m_tolerance );\n\n\t\t\/\/ Difference matrix: Y(ind1) - Y(ind2)\n\t\tfor ( j = 0 ; j < m_nupdates ; ++j )\n\t\t\tfor ( k = 0 ; k < m_target_dim ; ++k )\n\t\t\t{\n\t\t\t\tidx1 = k + ind1[j]*m_target_dim;\n\t\t\t\tidx2 = k + ind2[j]*m_target_dim;\n\t\t\t\tidx = k + j *m_target_dim;\n\n\t\t\t\tYd[idx] = Y[idx1] - Y[idx2];\n\t\t\t}\n\n\t\t\/\/ Update the location of the vectors in the embedded space\n\t\tfor ( j = 0 ; j < m_nupdates ; ++j )\n\t\t\tfor ( k = 0 ; k < m_target_dim ; ++k )\n\t\t\t{\n\t\t\t\tidx1 = k + ind1[j]*m_target_dim;\n\t\t\t\tidx2 = k + ind2[j]*m_target_dim;\n\t\t\t\tidx = k + j *m_target_dim;\n\n\t\t\t\tY[idx1] += lambda \/ 2 * scale[j] * Yd[idx];\n\t\t\t\tY[idx2] -= lambda \/ 2 * scale[j] * Yd[idx];\n\t\t\t}\n\n\t\t\/\/ Update the learning parameter\n\t\tlambda = lambda - ( lambda \/ max_iter );\n\n\t\t\/\/ Free memory\n\t\tdelete[] J;\n\t}\n\n\t\/\/ Free memory\n\tdistance_matrix.destroy_matrix();\n\tscale.destroy_vector();\n\tD.destroy_vector();\n\tYd.destroy_matrix();\n\tRt.destroy_vector();\n\tif ( m_strategy == SPE_LOCAL )\n\t{\n\t\tind1Neighbors.destroy_matrix();\n\t\tneighbors_mat.destroy_matrix();\n\t\tJ2.destroy_vector();\n\t\tdelete[] ind2;\n\t}\n\tSG_UNREF(features);\n\n\treturn (CFeatures*)( new CSimpleFeatures< float64_t >(Y) );\n}\n\nSGMatrix<int32_t> CStochasticProximityEmbedding::get_neighborhood_matrix(SGMatrix<float64_t> distance_matrix, int32_t k)\n{\n\tint32_t i;\n\tint32_t N = distance_matrix.num_rows;\n\n\tint32_t* neighborhood_matrix = SG_MALLOC(int32_t, N*k);\n\n\tfloat64_t max_dist = CMath::max(distance_matrix.matrix,N*N);\n\n\tCoverTree<SPE_COVERTREE_POINT>* coverTree = new CoverTree<SPE_COVERTREE_POINT>(max_dist);\n\n\tfor (i=0; i<N; i++)\n\t\tcoverTree->insert(SPE_COVERTREE_POINT(i,distance_matrix));\n\n\tfor (i=0; i<N; i++)\n\t{\n\t\tstd::vector<SPE_COVERTREE_POINT> neighbors =\n\t\t coverTree->kNearestNeighbors(SPE_COVERTREE_POINT(i,distance_matrix),k+1);\n\t\tfor (std::size_t m=1; m<unsigned(k+1); m++)\n\t\t\tneighborhood_matrix[i*k+m-1] = neighbors[m].point_index;\n\t}\n\n\tdelete coverTree;\n\n\treturn SGMatrix<int32_t>(neighborhood_matrix,k,N);\n}\n\n#endif \/* HAVE_LAPACK *\/\n<commit_msg>- check for simple and real features in SPE -> distance makes the check<commit_after>\/*\n * This program is free software; you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or\n * (at your option) any later version.\n *\n * Written (W) 2012 Fernando José Iglesias García\n * Copyright (C) 2012 Fernando José Iglesias García\n *\/\n\n#include <shogun\/converter\/StochasticProximityEmbedding.h>\n#include <shogun\/lib\/config.h>\n#ifdef HAVE_LAPACK\n#include <shogun\/converter\/EmbeddingConverter.h>\n#include <shogun\/io\/SGIO.h>\n#include <shogun\/lib\/CoverTree.h>\n#include <shogun\/mathematics\/Math.h>\n#include <shogun\/distance\/Distance.h>\n\nusing namespace shogun;\n\nclass SPE_COVERTREE_POINT\n{\npublic:\n\n\tSPE_COVERTREE_POINT(int32_t index, const SGMatrix<float64_t>& dmatrix)\n\t{\n\t\tpoint_index = index;\n\t\tdistance_matrix = dmatrix;\n\t}\n\n\tinline double distance(const SPE_COVERTREE_POINT& p) const\n\t{\n\t\treturn distance_matrix[point_index*distance_matrix.num_rows+p.point_index];\n\t}\n\n\tinline bool operator==(const SPE_COVERTREE_POINT& p) const\n\t{\n\t\treturn (p.point_index==point_index);\n\t}\n\n\tint32_t point_index;\n\tSGMatrix<float64_t> distance_matrix;\n};\n\nCStochasticProximityEmbedding::CStochasticProximityEmbedding() : \n\tCEmbeddingConverter()\n{\n\t\/\/ Initialize to default values\n\tm_k = 12;\n\tm_nupdates = 100;\n\tm_strategy = SPE_GLOBAL;\n\tm_tolerance = 1e-5;\n\n\tinit();\n}\n\nvoid CStochasticProximityEmbedding::init()\n{\n\tSG_ADD(&m_k, \"m_k\", \"Number of neighbors\", MS_NOT_AVAILABLE);\n\tSG_ADD((machine_int_t*) &m_strategy, \"m_strategy\", \"SPE strategy\", \n\t\t\tMS_NOT_AVAILABLE);\n\tSG_ADD(&m_tolerance, \"m_tolerance\", \"Regularization parameter\", \n\t\t\tMS_NOT_AVAILABLE);\n}\n\nCStochasticProximityEmbedding::~CStochasticProximityEmbedding()\n{\n}\n\nvoid CStochasticProximityEmbedding::set_k(int32_t k)\n{\n\tif ( k <= 0 )\n\t\tSG_ERROR(\"Number of neighbors k must be greater than 0\");\n\n\tm_k = k;\n}\n\nint32_t CStochasticProximityEmbedding::get_k() const\n{\n\treturn m_k;\n}\n\nvoid CStochasticProximityEmbedding::set_strategy(ESPEStrategy strategy)\n{\n\tm_strategy = strategy;\n}\n\nESPEStrategy CStochasticProximityEmbedding::get_strategy() const\n{\n\treturn m_strategy;\n}\n\nvoid CStochasticProximityEmbedding::set_tolerance(float32_t tolerance)\n{\n\tif ( tolerance <= 0 )\n\t\tSG_ERROR(\"Tolerance regularization parameter must be greater \"\n\t\t\t \"than 0\");\n\n\tm_tolerance = tolerance;\n}\n\nint32_t CStochasticProximityEmbedding::get_tolerance() const\n{\n\treturn m_tolerance;\n}\n\nvoid CStochasticProximityEmbedding::set_nupdates(int32_t nupdates)\n{\n\tif ( nupdates <= 0 )\n\t\tSG_ERROR(\"The number of updates must be greater than 0\");\n\n\tm_nupdates = nupdates;\n}\n\nint32_t CStochasticProximityEmbedding::get_nupdates() const\n{\n\treturn m_nupdates;\n}\n\nconst char * CStochasticProximityEmbedding::get_name() const\n{\n\treturn \"StochasticProximityEmbedding\";\n}\n\nCFeatures* CStochasticProximityEmbedding::apply(CFeatures* features)\n{\n\tif ( !features )\n\t\tSG_ERROR(\"Features are required to apply SPE\\n\");\n\n\t\/\/ Shorthand for the SimpleFeatures\n\tCSimpleFeatures< float64_t >* simple_features = \n\t\t(CSimpleFeatures< float64_t >*) features;\n\tSG_REF(features);\n\n\t\/\/ Get and check the number of vectors\n\tint32_t N = simple_features->get_num_vectors();\n\tif ( m_strategy == SPE_LOCAL && m_k >= N )\n\t\tSG_ERROR(\"The number of neighbors (%d) must be less than \"\n\t\t \"the number of vectors (%d)\\n\", m_k, N);\n\n\tif ( 2*m_nupdates > N )\n\t\tSG_ERROR(\"The number of vectors (%d) must be at least two times \"\n\t\t\t \"the number of updates (%d)\\n\", N, m_nupdates);\n\n\t\/\/ Compute distance matrix\n\tSG_DEBUG(\"Computing distance matrix\\n\");\n\n\tif ( m_distance->get_distance_type() != D_EUCLIDIAN )\n\t\tSG_ERROR(\"SPE only supports Euclidian distance, %s given\\n\", \n\t\t\t\tm_distance->get_name());\n\n\tm_distance->init(simple_features, simple_features);\n\tSGMatrix< float64_t > distance_matrix = m_distance->get_distance_matrix();\n\tm_distance->remove_lhs_and_rhs();\n\n\t\/\/ Normalize the distance matrix if global strategy used\n\tif ( m_strategy == SPE_GLOBAL )\n\t{\n\t\tfloat64_t alpha = 1.0 \/ CMath::max(distance_matrix.matrix, N*N) \n\t\t\t\t\t* CMath::sqrt(2.0);\n\t\tCMath::scale_vector(alpha, distance_matrix.matrix, N*N);\n\t}\n\n\t\/\/ Compute neighborhood matrix if local strategy used\n\tSGMatrix< int32_t > neighbors_mat;\n\tif ( m_strategy == SPE_LOCAL )\n\t{\n\t\tSG_DEBUG(\"Computing neighborhood matrix\\n\");\n\t\tneighbors_mat = get_neighborhood_matrix(distance_matrix, m_k);\n\t}\n\n\t\/\/ Initialize vectors in the embedded space randomly, Y is the short for\n\t\/\/ new_feature_matrix\n\tSGMatrix< float64_t > Y(m_target_dim, N);\n\tCMath::random_vector(Y.matrix, m_target_dim*N, 0.0, 1.0);\n\n\t\/\/ SPE's loop\n\t\n\t\/\/ Initialize the maximum number of iterations\n\tint32_t max_iter = 2000 + CMath::round(0.04 * N*N);\n\tif ( m_strategy == SPE_LOCAL )\n\t\tmax_iter *= 3;\n\n\t\/\/ Initialize the learning parameter\n\tfloat32_t lambda = 1.0;\n\n\t\/\/ Initialize variables to use in the main loop\n\tint32_t i, j, k;\n\tfloat64_t sum = 0.0;\n\tindex_t idx1 = 0, idx2 = 0, idx = 0;\n\n\tSGVector< float64_t > scale(m_nupdates);\n\tSGVector< float64_t > D(m_nupdates);\n\tSGMatrix< float64_t > Yd(m_nupdates, m_target_dim);\n\tSGVector< float64_t > Rt(m_nupdates);\n\tint32_t* ind2 = NULL;\n\n\t\/\/ Variables required just if local strategy used\n\tSGMatrix< int32_t > ind1Neighbors;\n\tSGVector< int32_t > J2;\n\tif ( m_strategy == SPE_LOCAL )\n\t{\n\t\tind2 = SG_MALLOC(int32_t, m_nupdates);\n\n\t\tCMath::resize(ind1Neighbors.matrix, 0, m_k*m_nupdates);\n\t\tind1Neighbors.num_rows = m_k;\n\t\tind1Neighbors.num_cols = m_nupdates;\n\n\t\tCMath::resize(J2.vector, 0, m_nupdates);\n\t\tJ2.vlen = m_nupdates;\n\t}\n\n\tfor ( i = 0 ; i < max_iter ; ++i )\n\t{\n\t\tif ( !(i % 1000) )\n\t\t\tSG_DEBUG(\"SPE's loop, iteration %d of %d\\n\", i, max_iter);\n\n\t\t\/\/ Select the vectors to be updated in this iteration\n\t\tint32_t* J = CMath::randperm(N);\n\n\t\t\/\/ Pointer to the first set of vector indices to update\n\t\tint32_t* ind1 = J;\n\n\t\t\/\/ Pointer ind2 to the second set of vector indices to update\n\t\tif ( m_strategy == SPE_GLOBAL )\n\t\t\tind2 = J + m_nupdates;\n\t\telse\n\t\t{\n\t\t\t\/\/ Select the second set of indices to update among neighbors\n\t\t\t\/\/ of the first set\n\t\t\t\t\n\t\t\t\/\/ Get the neighbors of interest\n\t\t\tfor ( j = 0 ; j < m_nupdates ; ++j )\n\t\t\t{\n\t\t\t\tfor ( k = 0 ; k < m_k ; ++k )\n\t\t\t\t\tind1Neighbors[k + j*m_k] =\n\t\t\t\t\t\tneighbors_mat.matrix[k + ind1[j]*m_k];\n\t\t\t}\n\n\t\t\t\/\/ Generate pseudo-random indices\n\t\t\tfor ( j = 0 ; j < m_nupdates ; ++j )\n\t\t\t{\n\t\t\t\tJ2[j] = CMath::round( CMath::random(0.0, 1.0)*(m_k-1) )\n\t\t\t\t\t\t+ m_k*j;\n\t\t\t}\n\n\t\t\t\/\/ Select final indices\n\t\t\tfor ( j = 0 ; j < m_nupdates ; ++j )\n\t\t\t\tind2[j] = ind1Neighbors.matrix[ J2[j] ];\n\t\t}\n\n\t\t\/\/ Compute distances betweeen the selected points in embedded space\n\n\t\tfor ( j = 0 ; j < m_nupdates ; ++j )\n\t\t{\n\t\t\tsum = 0.0;\n\n\t\t\tfor ( k = 0 ; k < m_target_dim ; ++k )\n\t\t\t{\n\t\t\t\tidx1 = k + ind1[j]*m_target_dim;\n\t\t\t\tidx2 = k + ind2[j]*m_target_dim;\n\t\t\t\tsum += CMath::sq(Y.matrix[idx1] - Y.matrix[idx2]);\n\t\t\t}\n\n\t\t\tD[j] = CMath::sqrt(sum);\n\t\t}\n\n\t\t\/\/ Get the corresponding distances in the original space\n\t\tfor ( j = 0 ; j < m_nupdates ; ++j )\n\t\t\tRt[j] = distance_matrix.matrix[ ind1[j]*N + ind2[j] ];\n\n\t\t\/\/ Compute some terms for update\n\n\t\t\/\/ Scale factor: (Rt - D) .\/ (D + m_tolerance)\n\t\tfor ( j = 0 ; j < m_nupdates ; ++j )\n\t\t\tscale[j] = ( Rt[j] - D[j] ) \/ ( D[j] + m_tolerance );\n\n\t\t\/\/ Difference matrix: Y(ind1) - Y(ind2)\n\t\tfor ( j = 0 ; j < m_nupdates ; ++j )\n\t\t\tfor ( k = 0 ; k < m_target_dim ; ++k )\n\t\t\t{\n\t\t\t\tidx1 = k + ind1[j]*m_target_dim;\n\t\t\t\tidx2 = k + ind2[j]*m_target_dim;\n\t\t\t\tidx = k + j *m_target_dim;\n\n\t\t\t\tYd[idx] = Y[idx1] - Y[idx2];\n\t\t\t}\n\n\t\t\/\/ Update the location of the vectors in the embedded space\n\t\tfor ( j = 0 ; j < m_nupdates ; ++j )\n\t\t\tfor ( k = 0 ; k < m_target_dim ; ++k )\n\t\t\t{\n\t\t\t\tidx1 = k + ind1[j]*m_target_dim;\n\t\t\t\tidx2 = k + ind2[j]*m_target_dim;\n\t\t\t\tidx = k + j *m_target_dim;\n\n\t\t\t\tY[idx1] += lambda \/ 2 * scale[j] * Yd[idx];\n\t\t\t\tY[idx2] -= lambda \/ 2 * scale[j] * Yd[idx];\n\t\t\t}\n\n\t\t\/\/ Update the learning parameter\n\t\tlambda = lambda - ( lambda \/ max_iter );\n\n\t\t\/\/ Free memory\n\t\tdelete[] J;\n\t}\n\n\t\/\/ Free memory\n\tdistance_matrix.destroy_matrix();\n\tscale.destroy_vector();\n\tD.destroy_vector();\n\tYd.destroy_matrix();\n\tRt.destroy_vector();\n\tif ( m_strategy == SPE_LOCAL )\n\t{\n\t\tind1Neighbors.destroy_matrix();\n\t\tneighbors_mat.destroy_matrix();\n\t\tJ2.destroy_vector();\n\t\tdelete[] ind2;\n\t}\n\tSG_UNREF(features);\n\n\treturn (CFeatures*)( new CSimpleFeatures< float64_t >(Y) );\n}\n\nSGMatrix<int32_t> CStochasticProximityEmbedding::get_neighborhood_matrix(SGMatrix<float64_t> distance_matrix, int32_t k)\n{\n\tint32_t i;\n\tint32_t N = distance_matrix.num_rows;\n\n\tint32_t* neighborhood_matrix = SG_MALLOC(int32_t, N*k);\n\n\tfloat64_t max_dist = CMath::max(distance_matrix.matrix,N*N);\n\n\tCoverTree<SPE_COVERTREE_POINT>* coverTree = new CoverTree<SPE_COVERTREE_POINT>(max_dist);\n\n\tfor (i=0; i<N; i++)\n\t\tcoverTree->insert(SPE_COVERTREE_POINT(i,distance_matrix));\n\n\tfor (i=0; i<N; i++)\n\t{\n\t\tstd::vector<SPE_COVERTREE_POINT> neighbors =\n\t\t coverTree->kNearestNeighbors(SPE_COVERTREE_POINT(i,distance_matrix),k+1);\n\t\tfor (std::size_t m=1; m<unsigned(k+1); m++)\n\t\t\tneighborhood_matrix[i*k+m-1] = neighbors[m].point_index;\n\t}\n\n\tdelete coverTree;\n\n\treturn SGMatrix<int32_t>(neighborhood_matrix,k,N);\n}\n\n#endif \/* HAVE_LAPACK *\/\n<|endoftext|>"} {"text":"<commit_before>#include <opencv2\/opencv.hpp>\n\nusing namespace cv;\n\nint main(int, char**)\n{\n \/\/ open the default camera\n VideoCapture cap(0);\n \n \/\/ check if we succeeded\n if(!cap.isOpened()) {\n std::cout << \"Fix your camera!\" << std::endl;\n return -1;\n }\n\n Mat frame;\n namedWindow(\"video\", WINDOW_AUTOSIZE);\n \n while(1)\n {\n \/\/ Get a new frame from camera\n cap >> frame;\n\n \/\/ Show the frame\n imshow(\"video\", frame);\n \n \/\/ Exit\n if(waitKey(30) >= 0) break;\n }\n\n return 0;\n}<commit_msg>small refactor<commit_after>#include <opencv2\/opencv.hpp>\n\nint main(int, char**)\n{\n \/\/ Open default camera\n cv::VideoCapture cap(0);\n\n \/\/ Camera working?\n if(!cap.isOpened()) {\n std::cout << \"Fix your camera!\" << std::endl;\n return -1;\n }\n\n cv::Mat frame;\n cv::namedWindow(\"video\", cv::WINDOW_AUTOSIZE);\n\n while(1)\n {\n \/\/ Get a new frame from camera\n cap >> frame;\n\n \/\/ Show the frame\n imshow(\"video\", frame);\n\n \/\/ Exit\n if(cv::waitKey(30) >= 0) break;\n }\n\n return 0;\n}<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ Copyright (c) 2017 The Khronos Group Inc.\n\/\/ \n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/\n#include \"harness\/compat.h\"\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <sys\/types.h>\n#include <sys\/stat.h>\n\n#include \"procs.h\"\n\nconst char *kernel_code =\n\"__kernel void test_kernel(\\n\"\n\"char%s c, uchar%s uc, short%s s, ushort%s us, int%s i, uint%s ui, float%s f,\\n\"\n\"__global float%s *result)\\n\"\n\"{\\n\"\n\" result[0] = %s(c);\\n\"\n\" result[1] = %s(uc);\\n\"\n\" result[2] = %s(s);\\n\"\n\" result[3] = %s(us);\\n\"\n\" result[4] = %s(i);\\n\"\n\" result[5] = %s(ui);\\n\"\n\" result[6] = f;\\n\"\n\"}\\n\";\n\nconst char *kernel_code_long =\n\"__kernel void test_kernel_long(\\n\"\n\"long%s l, ulong%s ul,\\n\"\n\"__global float%s *result)\\n\"\n\"{\\n\"\n\" result[0] = %s(l);\\n\"\n\" result[1] = %s(ul);\\n\"\n\"}\\n\";\n\nint test_parameter_types_long(cl_device_id device, cl_context context, cl_command_queue queue, int num_elements)\n{\n clMemWrapper results;\n int error;\n size_t global[3] = {1, 1, 1};\n float results_back[2*16];\n int count, index;\n const char* types[] = { \"long\", \"ulong\" };\n char kernel_string[8192];\n int sizes[] = {1, 2, 4, 8, 16};\n const char* size_strings[] = {\"\", \"2\", \"4\", \"8\", \"16\"};\n float expected;\n int total_errors = 0;\n int size_to_test;\n char *ptr;\n char convert_string[1024];\n size_t max_parameter_size;\n\n \/\/ We don't really care about the contents since we're just testing that the types work.\n cl_long l[16]={-21,-1,2,-3,4,-5,6,-7,8,-9,10,-11,12,-13,14,-15};\n cl_ulong ul[16]={22,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15};\n\n \/\/ Calculate how large our paramter size is to the kernel\n size_t parameter_size = sizeof(cl_long) + sizeof(cl_ulong);\n\n \/\/ Init our strings.\n kernel_string[0] = '\\0';\n convert_string[0] = '\\0';\n\n \/\/ Get the maximum parameter size allowed\n error = clGetDeviceInfo( device, CL_DEVICE_MAX_PARAMETER_SIZE, sizeof( max_parameter_size ), &max_parameter_size, NULL );\n test_error( error, \"Unable to get max parameter size from device\" );\n\n \/\/ Create the results buffer\n results = clCreateBuffer(context, CL_MEM_READ_WRITE, sizeof(cl_float)*2*16, NULL, &error);\n test_error(error, \"clCreateBuffer failed\");\n\n \/\/ Go over all the vector sizes\n for (size_to_test = 0; size_to_test < 5; size_to_test++) {\n clProgramWrapper program;\n clKernelWrapper kernel;\n\n size_t total_parameter_size = parameter_size*sizes[size_to_test] + sizeof(cl_mem);\n if (total_parameter_size > max_parameter_size) {\n log_info(\"Can not test with vector size %d because it would exceed the maximum allowed parameter size to the kernel. (%d > %d)\\n\",\n (int)sizes[size_to_test], (int)total_parameter_size, (int)max_parameter_size);\n continue;\n }\n\n log_info(\"Testing vector size %d\\n\", sizes[size_to_test]);\n\n \/\/ If size is > 1, then we need a explicit convert call.\n if (sizes[size_to_test] > 1) {\n sprintf(convert_string, \"convert_float%s\", size_strings[size_to_test]);\n } else {\n sprintf(convert_string, \" \");\n }\n\n \/\/ Build the kernel\n sprintf(kernel_string, kernel_code_long,\n size_strings[size_to_test], size_strings[size_to_test], size_strings[size_to_test],\n convert_string, convert_string\n );\n\n ptr = kernel_string;\n error = create_single_kernel_helper(context, &program, &kernel, 1, (const char **)&ptr, \"test_kernel_long\");\n test_error(error, \"create single kernel failed\");\n\n \/\/ Set the arguments\n for (count = 0; count < 2; count++) {\n switch (count) {\n case 0: error = clSetKernelArg(kernel, count, sizeof(cl_long)*sizes[size_to_test], &l); break;\n case 1: error = clSetKernelArg(kernel, count, sizeof(cl_ulong)*sizes[size_to_test], &ul); break;\n default: log_error(\"Test error\"); break;\n }\n if (error)\n log_error(\"Setting kernel arg %d %s%s: \", count, types[count], size_strings[size_to_test]);\n test_error(error, \"clSetKernelArgs failed\");\n }\n error = clSetKernelArg(kernel, 2, sizeof(cl_mem), &results);\n test_error(error, \"clSetKernelArgs failed\");\n\n \/\/ Execute\n error = clEnqueueNDRangeKernel(queue, kernel, 1, NULL, global, NULL, 0, NULL, NULL);\n test_error(error, \"clEnqueueNDRangeKernel failed\");\n\n \/\/ Read back the results\n error = clEnqueueReadBuffer(queue, results, CL_TRUE, 0, sizeof(cl_float)*2*16, results_back, 0, NULL, NULL);\n test_error(error, \"clEnqueueReadBuffer failed\");\n\n \/\/ Verify the results\n for (count = 0; count < 2; count++) {\n for (index=0; index < sizes[size_to_test]; index++) {\n switch (count) {\n case 0: expected = (float)l[index]; break;\n case 1: expected = (float)ul[index]; break;\n default: log_error(\"Test error\"); break;\n }\n\n if (results_back[count*sizes[size_to_test]+index] != expected) {\n total_errors++;\n log_error(\"Conversion from %s%s failed: index %d got %g, expected %g.\\n\", types[count], size_strings[size_to_test],\n index, results_back[count*sizes[size_to_test]+index], expected);\n }\n }\n }\n }\n\n return total_errors;\n}\n\nint test_parameter_types(cl_device_id device, cl_context context, cl_command_queue queue, int num_elements)\n{\n clMemWrapper results;\n int error;\n size_t global[3] = {1, 1, 1};\n float results_back[7*16];\n int count, index;\n const char* types[] = {\"char\", \"uchar\", \"short\", \"ushort\", \"int\", \"uint\", \"float\"};\n char kernel_string[8192];\n int sizes[] = {1, 2, 4, 8, 16};\n const char* size_strings[] = {\"\", \"2\", \"4\", \"8\", \"16\"};\n float expected;\n int total_errors = 0;\n int size_to_test;\n char *ptr;\n char convert_string[1024];\n size_t max_parameter_size;\n\n \/\/ We don't really care about the contents since we're just testing that the types work.\n cl_char c[16]={0,-1,2,-3,4,-5,6,-7,8,-9,10,-11,12,-13,14,-15};\n cl_uchar uc[16]={16,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15};\n cl_short s[16]={-17,-1,2,-3,4,-5,6,-7,8,-9,10,-11,12,-13,14,-15};\n cl_ushort us[16]={18,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15};\n cl_int i[16]={-19,-1,2,-3,4,-5,6,-7,8,-9,10,-11,12,-13,14,-15};\n cl_uint ui[16]={20,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15};\n cl_float f[16]={-23,-1,2,-3,4,-5,6,-7,8,-9,10,-11,12,-13,14,-15};\n\n \/\/ Calculate how large our paramter size is to the kernel\n size_t parameter_size = sizeof(cl_char) + sizeof(cl_uchar) +\n sizeof(cl_short) +sizeof(cl_ushort) +\n sizeof(cl_int) +sizeof(cl_uint) +\n sizeof(cl_float);\n\n \/\/ Init our strings.\n kernel_string[0] = '\\0';\n convert_string[0] = '\\0';\n\n \/\/ Get the maximum parameter size allowed\n error = clGetDeviceInfo( device, CL_DEVICE_MAX_PARAMETER_SIZE, sizeof( max_parameter_size ), &max_parameter_size, NULL );\n test_error( error, \"Unable to get max parameter size from device\" );\n\n \/\/ Create the results buffer\n results = clCreateBuffer(context, CL_MEM_READ_WRITE, sizeof(cl_float)*7*16, NULL, &error);\n test_error(error, \"clCreateBuffer failed\");\n\n \/\/ Go over all the vector sizes\n for (size_to_test = 0; size_to_test < 5; size_to_test++) {\n clProgramWrapper program;\n clKernelWrapper kernel;\n\n size_t total_parameter_size = parameter_size*sizes[size_to_test] + sizeof(cl_mem);\n if (total_parameter_size > max_parameter_size) {\n log_info(\"Can not test with vector size %d because it would exceed the maximum allowed parameter size to the kernel. (%d > %d)\\n\",\n (int)sizes[size_to_test], (int)total_parameter_size, (int)max_parameter_size);\n continue;\n }\n\n log_info(\"Testing vector size %d\\n\", sizes[size_to_test]);\n\n \/\/ If size is > 1, then we need a explicit convert call.\n if (sizes[size_to_test] > 1) {\n sprintf(convert_string, \"convert_float%s\", size_strings[size_to_test]);\n } else {\n sprintf(convert_string, \" \");\n }\n\n \/\/ Build the kernel\n sprintf(kernel_string, kernel_code,\n size_strings[size_to_test], size_strings[size_to_test], size_strings[size_to_test],\n size_strings[size_to_test], size_strings[size_to_test], size_strings[size_to_test],\n size_strings[size_to_test], size_strings[size_to_test],\n convert_string, convert_string, convert_string,\n convert_string, convert_string, convert_string\n );\n\n ptr = kernel_string;\n error = create_single_kernel_helper(context, &program, &kernel, 1, (const char **)&ptr, \"test_kernel\");\n test_error(error, \"create single kernel failed\");\n\n \/\/ Set the arguments\n for (count = 0; count < 7; count++) {\n switch (count) {\n case 0: error = clSetKernelArg(kernel, count, sizeof(cl_char)*sizes[size_to_test], &c); break;\n case 1: error = clSetKernelArg(kernel, count, sizeof(cl_uchar)*sizes[size_to_test], &uc); break;\n case 2: error = clSetKernelArg(kernel, count, sizeof(cl_short)*sizes[size_to_test], &s); break;\n case 3: error = clSetKernelArg(kernel, count, sizeof(cl_ushort)*sizes[size_to_test], &us); break;\n case 4: error = clSetKernelArg(kernel, count, sizeof(cl_int)*sizes[size_to_test], &i); break;\n case 5: error = clSetKernelArg(kernel, count, sizeof(cl_uint)*sizes[size_to_test], &ui); break;\n case 6: error = clSetKernelArg(kernel, count, sizeof(cl_float)*sizes[size_to_test], &f); break;\n default: log_error(\"Test error\"); break;\n }\n if (error)\n log_error(\"Setting kernel arg %d %s%s: \", count, types[count], size_strings[size_to_test]);\n test_error(error, \"clSetKernelArgs failed\");\n }\n error = clSetKernelArg(kernel, 7, sizeof(cl_mem), &results);\n test_error(error, \"clSetKernelArgs failed\");\n\n \/\/ Execute\n error = clEnqueueNDRangeKernel(queue, kernel, 1, NULL, global, NULL, 0, NULL, NULL);\n test_error(error, \"clEnqueueNDRangeKernel failed\");\n\n \/\/ Read back the results\n error = clEnqueueReadBuffer(queue, results, CL_TRUE, 0, sizeof(cl_float)*7*16, results_back, 0, NULL, NULL);\n test_error(error, \"clEnqueueReadBuffer failed\");\n\n \/\/ Verify the results\n for (count = 0; count < 7; count++) {\n for (index=0; index < sizes[size_to_test]; index++) {\n switch (count) {\n case 0: expected = (float)c[index]; break;\n case 1: expected = (float)uc[index]; break;\n case 2: expected = (float)s[index]; break;\n case 3: expected = (float)us[index]; break;\n case 4: expected = (float)i[index]; break;\n case 5: expected = (float)ui[index]; break;\n case 6: expected = (float)f[index]; break;\n default: log_error(\"Test error\"); break;\n }\n\n if (results_back[count*sizes[size_to_test]+index] != expected) {\n total_errors++;\n log_error(\"Conversion from %s%s failed: index %d got %g, expected %g.\\n\", types[count], size_strings[size_to_test],\n index, results_back[count*sizes[size_to_test]+index], expected);\n }\n }\n }\n }\n\n if (gHasLong) {\n log_info(\"Testing long types...\\n\");\n total_errors += test_parameter_types_long( device, context, queue, num_elements );\n }\n else {\n log_info(\"Longs unsupported, skipping.\");\n }\n\n return total_errors;\n}\n\n\n\n<commit_msg>NFC: clang-format test_basic_parameter_types.cpp (#1151)<commit_after>\/\/\n\/\/ Copyright (c) 2017 The Khronos Group Inc.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/\n#include \"harness\/compat.h\"\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <sys\/types.h>\n#include <sys\/stat.h>\n\n#include \"procs.h\"\n\nconst char *kernel_code = R\"(\n__kernel void test_kernel(\nchar%s c, uchar%s uc, short%s s, ushort%s us, int%s i, uint%s ui, float%s f,\n__global float%s *result)\n{\n result[0] = %s(c);\n result[1] = %s(uc);\n result[2] = %s(s);\n result[3] = %s(us);\n result[4] = %s(i);\n result[5] = %s(ui);\n result[6] = f;\n})\";\n\nconst char *kernel_code_long = R\"(\n__kernel void test_kernel_long(\nlong%s l, ulong%s ul,\n__global float%s *result)\n{\n result[0] = %s(l);\n result[1] = %s(ul);\n})\";\n\nint test_parameter_types_long(cl_device_id device, cl_context context,\n cl_command_queue queue, int num_elements)\n{\n clMemWrapper results;\n int error;\n size_t global[3] = { 1, 1, 1 };\n float results_back[2 * 16];\n int count, index;\n const char *types[] = { \"long\", \"ulong\" };\n char kernel_string[8192];\n int sizes[] = { 1, 2, 4, 8, 16 };\n const char *size_strings[] = { \"\", \"2\", \"4\", \"8\", \"16\" };\n float expected;\n int total_errors = 0;\n int size_to_test;\n char *ptr;\n char convert_string[1024];\n size_t max_parameter_size;\n\n \/\/ We don't really care about the contents since we're just testing that the\n \/\/ types work.\n cl_long l[16] = { -21, -1, 2, -3, 4, -5, 6, -7,\n 8, -9, 10, -11, 12, -13, 14, -15 };\n cl_ulong ul[16] = { 22, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 };\n\n \/\/ Calculate how large our paramter size is to the kernel\n size_t parameter_size = sizeof(cl_long) + sizeof(cl_ulong);\n\n \/\/ Init our strings.\n kernel_string[0] = '\\0';\n convert_string[0] = '\\0';\n\n \/\/ Get the maximum parameter size allowed\n error =\n clGetDeviceInfo(device, CL_DEVICE_MAX_PARAMETER_SIZE,\n sizeof(max_parameter_size), &max_parameter_size, NULL);\n test_error(error, \"Unable to get max parameter size from device\");\n\n \/\/ Create the results buffer\n results = clCreateBuffer(context, CL_MEM_READ_WRITE,\n sizeof(cl_float) * 2 * 16, NULL, &error);\n test_error(error, \"clCreateBuffer failed\");\n\n \/\/ Go over all the vector sizes\n for (size_to_test = 0; size_to_test < 5; size_to_test++)\n {\n clProgramWrapper program;\n clKernelWrapper kernel;\n\n size_t total_parameter_size =\n parameter_size * sizes[size_to_test] + sizeof(cl_mem);\n if (total_parameter_size > max_parameter_size)\n {\n log_info(\n \"Can not test with vector size %d because it would exceed the \"\n \"maximum allowed parameter size to the kernel. (%d > %d)\\n\",\n (int)sizes[size_to_test], (int)total_parameter_size,\n (int)max_parameter_size);\n continue;\n }\n\n log_info(\"Testing vector size %d\\n\", sizes[size_to_test]);\n\n \/\/ If size is > 1, then we need a explicit convert call.\n if (sizes[size_to_test] > 1)\n {\n sprintf(convert_string, \"convert_float%s\",\n size_strings[size_to_test]);\n }\n else\n {\n sprintf(convert_string, \" \");\n }\n\n \/\/ Build the kernel\n sprintf(kernel_string, kernel_code_long, size_strings[size_to_test],\n size_strings[size_to_test], size_strings[size_to_test],\n convert_string, convert_string);\n\n ptr = kernel_string;\n error = create_single_kernel_helper(context, &program, &kernel, 1,\n (const char **)&ptr,\n \"test_kernel_long\");\n test_error(error, \"create single kernel failed\");\n\n \/\/ Set the arguments\n for (count = 0; count < 2; count++)\n {\n switch (count)\n {\n case 0:\n error = clSetKernelArg(\n kernel, count, sizeof(cl_long) * sizes[size_to_test],\n &l);\n break;\n case 1:\n error = clSetKernelArg(\n kernel, count, sizeof(cl_ulong) * sizes[size_to_test],\n &ul);\n break;\n default: log_error(\"Test error\"); break;\n }\n if (error)\n log_error(\"Setting kernel arg %d %s%s: \", count, types[count],\n size_strings[size_to_test]);\n test_error(error, \"clSetKernelArgs failed\");\n }\n error = clSetKernelArg(kernel, 2, sizeof(cl_mem), &results);\n test_error(error, \"clSetKernelArgs failed\");\n\n \/\/ Execute\n error = clEnqueueNDRangeKernel(queue, kernel, 1, NULL, global, NULL, 0,\n NULL, NULL);\n test_error(error, \"clEnqueueNDRangeKernel failed\");\n\n \/\/ Read back the results\n error = clEnqueueReadBuffer(queue, results, CL_TRUE, 0,\n sizeof(cl_float) * 2 * 16, results_back, 0,\n NULL, NULL);\n test_error(error, \"clEnqueueReadBuffer failed\");\n\n \/\/ Verify the results\n for (count = 0; count < 2; count++)\n {\n for (index = 0; index < sizes[size_to_test]; index++)\n {\n switch (count)\n {\n case 0: expected = (float)l[index]; break;\n case 1: expected = (float)ul[index]; break;\n default: log_error(\"Test error\"); break;\n }\n\n if (results_back[count * sizes[size_to_test] + index]\n != expected)\n {\n total_errors++;\n log_error(\"Conversion from %s%s failed: index %d got %g, \"\n \"expected %g.\\n\",\n types[count], size_strings[size_to_test], index,\n results_back[count * sizes[size_to_test] + index],\n expected);\n }\n }\n }\n }\n\n return total_errors;\n}\n\nint test_parameter_types(cl_device_id device, cl_context context,\n cl_command_queue queue, int num_elements)\n{\n clMemWrapper results;\n int error;\n size_t global[3] = { 1, 1, 1 };\n float results_back[7 * 16];\n int count, index;\n const char *types[] = { \"char\", \"uchar\", \"short\", \"ushort\",\n \"int\", \"uint\", \"float\" };\n char kernel_string[8192];\n int sizes[] = { 1, 2, 4, 8, 16 };\n const char *size_strings[] = { \"\", \"2\", \"4\", \"8\", \"16\" };\n float expected;\n int total_errors = 0;\n int size_to_test;\n char *ptr;\n char convert_string[1024];\n size_t max_parameter_size;\n\n \/\/ We don't really care about the contents since we're just testing that the\n \/\/ types work.\n cl_char c[16] = { 0, -1, 2, -3, 4, -5, 6, -7,\n 8, -9, 10, -11, 12, -13, 14, -15 };\n cl_uchar uc[16] = { 16, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 };\n cl_short s[16] = { -17, -1, 2, -3, 4, -5, 6, -7,\n 8, -9, 10, -11, 12, -13, 14, -15 };\n cl_ushort us[16] = {\n 18, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15\n };\n cl_int i[16] = { -19, -1, 2, -3, 4, -5, 6, -7,\n 8, -9, 10, -11, 12, -13, 14, -15 };\n cl_uint ui[16] = { 20, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 };\n cl_float f[16] = { -23, -1, 2, -3, 4, -5, 6, -7,\n 8, -9, 10, -11, 12, -13, 14, -15 };\n\n \/\/ Calculate how large our paramter size is to the kernel\n size_t parameter_size = sizeof(cl_char) + sizeof(cl_uchar)\n + sizeof(cl_short) + sizeof(cl_ushort) + sizeof(cl_int)\n + sizeof(cl_uint) + sizeof(cl_float);\n\n \/\/ Init our strings.\n kernel_string[0] = '\\0';\n convert_string[0] = '\\0';\n\n \/\/ Get the maximum parameter size allowed\n error =\n clGetDeviceInfo(device, CL_DEVICE_MAX_PARAMETER_SIZE,\n sizeof(max_parameter_size), &max_parameter_size, NULL);\n test_error(error, \"Unable to get max parameter size from device\");\n\n \/\/ Create the results buffer\n results = clCreateBuffer(context, CL_MEM_READ_WRITE,\n sizeof(cl_float) * 7 * 16, NULL, &error);\n test_error(error, \"clCreateBuffer failed\");\n\n \/\/ Go over all the vector sizes\n for (size_to_test = 0; size_to_test < 5; size_to_test++)\n {\n clProgramWrapper program;\n clKernelWrapper kernel;\n\n size_t total_parameter_size =\n parameter_size * sizes[size_to_test] + sizeof(cl_mem);\n if (total_parameter_size > max_parameter_size)\n {\n log_info(\n \"Can not test with vector size %d because it would exceed the \"\n \"maximum allowed parameter size to the kernel. (%d > %d)\\n\",\n (int)sizes[size_to_test], (int)total_parameter_size,\n (int)max_parameter_size);\n continue;\n }\n\n log_info(\"Testing vector size %d\\n\", sizes[size_to_test]);\n\n \/\/ If size is > 1, then we need a explicit convert call.\n if (sizes[size_to_test] > 1)\n {\n sprintf(convert_string, \"convert_float%s\",\n size_strings[size_to_test]);\n }\n else\n {\n sprintf(convert_string, \" \");\n }\n\n \/\/ Build the kernel\n sprintf(kernel_string, kernel_code, size_strings[size_to_test],\n size_strings[size_to_test], size_strings[size_to_test],\n size_strings[size_to_test], size_strings[size_to_test],\n size_strings[size_to_test], size_strings[size_to_test],\n size_strings[size_to_test], convert_string, convert_string,\n convert_string, convert_string, convert_string, convert_string);\n\n ptr = kernel_string;\n error = create_single_kernel_helper(context, &program, &kernel, 1,\n (const char **)&ptr, \"test_kernel\");\n test_error(error, \"create single kernel failed\");\n\n \/\/ Set the arguments\n for (count = 0; count < 7; count++)\n {\n switch (count)\n {\n case 0:\n error = clSetKernelArg(\n kernel, count, sizeof(cl_char) * sizes[size_to_test],\n &c);\n break;\n case 1:\n error = clSetKernelArg(\n kernel, count, sizeof(cl_uchar) * sizes[size_to_test],\n &uc);\n break;\n case 2:\n error = clSetKernelArg(\n kernel, count, sizeof(cl_short) * sizes[size_to_test],\n &s);\n break;\n case 3:\n error = clSetKernelArg(\n kernel, count, sizeof(cl_ushort) * sizes[size_to_test],\n &us);\n break;\n case 4:\n error = clSetKernelArg(kernel, count,\n sizeof(cl_int) * sizes[size_to_test],\n &i);\n break;\n case 5:\n error = clSetKernelArg(\n kernel, count, sizeof(cl_uint) * sizes[size_to_test],\n &ui);\n break;\n case 6:\n error = clSetKernelArg(\n kernel, count, sizeof(cl_float) * sizes[size_to_test],\n &f);\n break;\n default: log_error(\"Test error\"); break;\n }\n if (error)\n log_error(\"Setting kernel arg %d %s%s: \", count, types[count],\n size_strings[size_to_test]);\n test_error(error, \"clSetKernelArgs failed\");\n }\n error = clSetKernelArg(kernel, 7, sizeof(cl_mem), &results);\n test_error(error, \"clSetKernelArgs failed\");\n\n \/\/ Execute\n error = clEnqueueNDRangeKernel(queue, kernel, 1, NULL, global, NULL, 0,\n NULL, NULL);\n test_error(error, \"clEnqueueNDRangeKernel failed\");\n\n \/\/ Read back the results\n error = clEnqueueReadBuffer(queue, results, CL_TRUE, 0,\n sizeof(cl_float) * 7 * 16, results_back, 0,\n NULL, NULL);\n test_error(error, \"clEnqueueReadBuffer failed\");\n\n \/\/ Verify the results\n for (count = 0; count < 7; count++)\n {\n for (index = 0; index < sizes[size_to_test]; index++)\n {\n switch (count)\n {\n case 0: expected = (float)c[index]; break;\n case 1: expected = (float)uc[index]; break;\n case 2: expected = (float)s[index]; break;\n case 3: expected = (float)us[index]; break;\n case 4: expected = (float)i[index]; break;\n case 5: expected = (float)ui[index]; break;\n case 6: expected = (float)f[index]; break;\n default: log_error(\"Test error\"); break;\n }\n\n if (results_back[count * sizes[size_to_test] + index]\n != expected)\n {\n total_errors++;\n log_error(\"Conversion from %s%s failed: index %d got %g, \"\n \"expected %g.\\n\",\n types[count], size_strings[size_to_test], index,\n results_back[count * sizes[size_to_test] + index],\n expected);\n }\n }\n }\n }\n\n if (gHasLong)\n {\n log_info(\"Testing long types...\\n\");\n total_errors +=\n test_parameter_types_long(device, context, queue, num_elements);\n }\n else\n {\n log_info(\"Longs unsupported, skipping.\");\n }\n\n return total_errors;\n}\n<|endoftext|>"} {"text":"<commit_before>#include <algorithm>\n#include <cstdint>\n#include <fstream>\n#include <iomanip>\n#include <ios> \/\/std::ios_base::failure\n#include <iostream> \/\/std::cout\n#include <stdexcept> \/\/std::invalid_argument std::exception\n#include <vector>\n\n#include <adios2.h>\n\nconst std::string streamname = \"skeleton_stream\";\n\nstatic void printDataStep(const float *data, const size_t start,\n const size_t count, const int rank, const int step)\n{\n std::ofstream myfile;\n std::string filename = \"data.\" + std::to_string(rank);\n if (step == 0)\n {\n myfile.open(filename);\n }\n else\n {\n myfile.open(filename, std::ios::app);\n }\n\n myfile << \"rank=\" << rank << \" size=\" << count << \" offsets=\" << start\n << \" step=\" << step << std::endl;\n\n myfile << \" step row columns \" << start << \"...\" << start + count - 1\n << std::endl;\n myfile << \" \";\n for (int j = 0; j < count; j++)\n {\n myfile << std::setw(9) << start + j;\n }\n myfile << std::endl;\n myfile << \"------------------------------------------------------------\"\n \"--\\n\";\n for (int i = 0; i < count; i++)\n {\n myfile << std::setw(5) << step << std::setw(5) << start + i;\n for (int j = 0; j < count; j++)\n {\n myfile << std::setw(9) << std::setprecision(4)\n << data[i * count + j];\n }\n myfile << std::endl;\n }\n myfile.close();\n}\n\nint main(int argc, char *argv[])\n{\n int rank = 0, nproc = 1;\n int retval = 0;\n\n std::ofstream out(\"TestSkeletonReaderOutput.txt\");\n auto coutbuf = std::cout.rdbuf(out.rdbuf()); \/\/ save and redirect\n\n#ifdef ADIOS2_HAVE_MPI\n int wrank = 0, wnproc = 1;\n MPI_Comm mpiReaderComm;\n MPI_Init(&argc, &argv);\n MPI_Comm_rank(MPI_COMM_WORLD, &wrank);\n MPI_Comm_size(MPI_COMM_WORLD, &wnproc);\n\n const unsigned int color = 2;\n MPI_Comm_split(MPI_COMM_WORLD, color, wrank, &mpiReaderComm);\n\n MPI_Comm_rank(mpiReaderComm, &rank);\n MPI_Comm_size(mpiReaderComm, &nproc);\n#endif\n\n try\n {\n\n\/** ADIOS class factory of IO class objects, Debug is ON by default *\/\n#ifdef ADIOS2_HAVE_MPI\n adios2::ADIOS adios(mpiReaderComm);\n#else\n adios2::ADIOS adios;\n#endif\n adios2::IO io = adios.DeclareIO(\"reader\");\n io.SetEngine(\"Skeleton\");\n io.SetParameter(\"VerBose\", \"5\");\n adios2::Engine reader = io.Open(streamname, adios2::Mode::Read);\n\n while (true)\n {\n adios2::StepStatus status =\n reader.BeginStep(adios2::StepMode::NextAvailable, 60.0f);\n if (status != adios2::StepStatus::OK)\n {\n break;\n }\n\n \/\/ discover in the metadata that the variable exists\n adios2::Variable<float> vMyArray;\n vMyArray = io.InquireVariable<float>(\"myArray\");\n if (!vMyArray)\n {\n std::cout\n << \"Missing 'myArray' variable. The Skeleton reader \"\n \"engine must retrieve variables from the writer and \"\n \"create Variable objects before they can be \"\n \"inquired\\n\";\n }\n else\n {\n \/\/ now read the variable\n \/\/ Get the read decomposition\n size_t gndx = vMyArray.Shape()[0];\n size_t ndx = gndx \/ (size_t)nproc;\n size_t offsx = ndx * (size_t)rank;\n if (rank == nproc - 1)\n {\n \/\/ right-most processes need to read all the rest\n ndx = gndx - ndx * (size_t)(nproc - 1);\n }\n int step = reader.CurrentStep();\n adios2::Dims count, start;\n count.push_back(ndx);\n start.push_back(offsx);\n\n vMyArray.SetSelection({start, count});\n\n std::vector<float> myArray(ndx);\n reader.Get(vMyArray, myArray.data());\n reader.PerformGets();\n printDataStep(myArray.data(), offsx, ndx, rank, step);\n }\n\n reader.EndStep();\n }\n reader.Close();\n }\n catch (std::invalid_argument &e)\n {\n std::cout << \"Invalid argument exception, STOPPING PROGRAM from rank \"\n << rank << \"\\n\";\n std::cout << e.what() << \"\\n\";\n retval = 1;\n }\n catch (std::ios_base::failure &e)\n {\n std::cout << \"IO System base failure exception, STOPPING PROGRAM \"\n \"from rank \"\n << rank << \"\\n\";\n std::cout << e.what() << \"\\n\";\n retval = 2;\n }\n catch (std::exception &e)\n {\n std::cout << \"Exception, STOPPING PROGRAM from rank \" << rank << \"\\n\";\n std::cout << e.what() << \"\\n\";\n retval = 3;\n }\n\n#ifdef ADIOS2_HAVE_MPI\n MPI_Finalize();\n#endif\n\n std::cout.rdbuf(coutbuf); \/\/ reset to standard output again\n\n return retval;\n}\n<commit_msg>fix appveyor complaint<commit_after>#include <algorithm>\n#include <cstdint>\n#include <fstream>\n#include <iomanip>\n#include <ios> \/\/std::ios_base::failure\n#include <iostream> \/\/std::cout\n#include <stdexcept> \/\/std::invalid_argument std::exception\n#include <vector>\n\n#include <adios2.h>\n\nconst std::string streamname = \"skeleton_stream\";\n\nstatic void printDataStep(const float *data, const size_t start,\n const size_t count, const int rank, const size_t step)\n{\n std::ofstream myfile;\n std::string filename = \"data.\" + std::to_string(rank);\n if (step == 0)\n {\n myfile.open(filename);\n }\n else\n {\n myfile.open(filename, std::ios::app);\n }\n\n myfile << \"rank=\" << rank << \" size=\" << count << \" offsets=\" << start\n << \" step=\" << step << std::endl;\n\n myfile << \" step row columns \" << start << \"...\" << start + count - 1\n << std::endl;\n myfile << \" \";\n for (int j = 0; j < count; j++)\n {\n myfile << std::setw(9) << start + j;\n }\n myfile << std::endl;\n myfile << \"------------------------------------------------------------\"\n \"--\\n\";\n for (int i = 0; i < count; i++)\n {\n myfile << std::setw(5) << step << std::setw(5) << start + i;\n for (int j = 0; j < count; j++)\n {\n myfile << std::setw(9) << std::setprecision(4)\n << data[i * count + j];\n }\n myfile << std::endl;\n }\n myfile.close();\n}\n\nint main(int argc, char *argv[])\n{\n int rank = 0, nproc = 1;\n int retval = 0;\n\n std::ofstream out(\"TestSkeletonReaderOutput.txt\");\n auto coutbuf = std::cout.rdbuf(out.rdbuf()); \/\/ save and redirect\n\n#ifdef ADIOS2_HAVE_MPI\n int wrank = 0, wnproc = 1;\n MPI_Comm mpiReaderComm;\n MPI_Init(&argc, &argv);\n MPI_Comm_rank(MPI_COMM_WORLD, &wrank);\n MPI_Comm_size(MPI_COMM_WORLD, &wnproc);\n\n const unsigned int color = 2;\n MPI_Comm_split(MPI_COMM_WORLD, color, wrank, &mpiReaderComm);\n\n MPI_Comm_rank(mpiReaderComm, &rank);\n MPI_Comm_size(mpiReaderComm, &nproc);\n#endif\n\n try\n {\n\n\/** ADIOS class factory of IO class objects, Debug is ON by default *\/\n#ifdef ADIOS2_HAVE_MPI\n adios2::ADIOS adios(mpiReaderComm);\n#else\n adios2::ADIOS adios;\n#endif\n adios2::IO io = adios.DeclareIO(\"reader\");\n io.SetEngine(\"Skeleton\");\n io.SetParameter(\"VerBose\", \"5\");\n adios2::Engine reader = io.Open(streamname, adios2::Mode::Read);\n\n while (true)\n {\n adios2::StepStatus status =\n reader.BeginStep(adios2::StepMode::NextAvailable, 60.0f);\n if (status != adios2::StepStatus::OK)\n {\n break;\n }\n\n \/\/ discover in the metadata that the variable exists\n adios2::Variable<float> vMyArray;\n vMyArray = io.InquireVariable<float>(\"myArray\");\n if (!vMyArray)\n {\n std::cout\n << \"Missing 'myArray' variable. The Skeleton reader \"\n \"engine must retrieve variables from the writer and \"\n \"create Variable objects before they can be \"\n \"inquired\\n\";\n }\n else\n {\n \/\/ now read the variable\n \/\/ Get the read decomposition\n size_t gndx = vMyArray.Shape()[0];\n size_t ndx = gndx \/ (size_t)nproc;\n size_t offsx = ndx * (size_t)rank;\n if (rank == nproc - 1)\n {\n \/\/ right-most processes need to read all the rest\n ndx = gndx - ndx * (size_t)(nproc - 1);\n }\n size_t step = reader.CurrentStep();\n adios2::Dims count, start;\n count.push_back(ndx);\n start.push_back(offsx);\n\n vMyArray.SetSelection({start, count});\n\n std::vector<float> myArray(ndx);\n reader.Get(vMyArray, myArray.data());\n reader.PerformGets();\n printDataStep(myArray.data(), offsx, ndx, rank, step);\n }\n\n reader.EndStep();\n }\n reader.Close();\n }\n catch (std::invalid_argument &e)\n {\n std::cout << \"Invalid argument exception, STOPPING PROGRAM from rank \"\n << rank << \"\\n\";\n std::cout << e.what() << \"\\n\";\n retval = 1;\n }\n catch (std::ios_base::failure &e)\n {\n std::cout << \"IO System base failure exception, STOPPING PROGRAM \"\n \"from rank \"\n << rank << \"\\n\";\n std::cout << e.what() << \"\\n\";\n retval = 2;\n }\n catch (std::exception &e)\n {\n std::cout << \"Exception, STOPPING PROGRAM from rank \" << rank << \"\\n\";\n std::cout << e.what() << \"\\n\";\n retval = 3;\n }\n\n#ifdef ADIOS2_HAVE_MPI\n MPI_Finalize();\n#endif\n\n std::cout.rdbuf(coutbuf); \/\/ reset to standard output again\n\n return retval;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * main.cpp -- This file is part of primesieve\n *\n * Copyright (C) 2011 Kim Walisch, <kim.walisch@gmail.com>\n *\n * This program is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>\n *\/\n\n\/** \n * @file main.cpp\n * @brief Command-line version of primesieve, multi-threaded (OpenMP),\n * compiles on many platforms.\n *\n * primesieve is a highly optimized implementation of the sieve of\n * Eratosthenes that finds prime numbers and prime k-tuplets (twin\n * primes, prime triplets, ...) up to 2^64 maximum.\n *\/\n\n#include \"..\/expr\/ExpressionParser.h\"\n#include \"..\/soe\/ParallelPrimeSieve.h\"\n#include \"..\/soe\/pmath.h\"\n#include \"..\/soe\/cpuid.h\"\n\n\/\/\/ declared in test.cpp\nvoid test();\n\n#include <stdint.h>\n#include <exception>\n#include <iostream>\n#include <iomanip> \/* std::setw(int) *\/\n#include <cstdlib> \/* std::exit(int) *\/\n#include <string>\n#include <cstring> \/* std::strlen(const char*) *\/\n#include <cctype> \/* std::tolower(int) *\/\n#include <sstream>\n\nnamespace {\n \/\/ Unfortunately there is no easy way to get the CPU L1 and L2 cache\n \/\/ size, these values are close for most x86-64 CPUs in 2011\n const uint32_t L1_CACHE_SIZE = 64;\n const uint32_t L2_CACHE_SIZE = 512;\n const uint64_t L2_THRESHOLD = ipow(10, 11) * 5;\n\n bool quietMode = false;\n bool showExpressionResults = false;\n\n uint64_t start = 0; \/* lower bound for sieving *\/\n uint64_t stop = 0; \/* upper bound for sieving *\/\n uint32_t sieveSize = 0; \/* sieve size in KiloBytes *\/\n uint32_t flags = 0; \/* settings *\/\n\n int maxThreads = ParallelPrimeSieve::getMaxThreads();\n int threads = -1;\n\n std::string primes[7] = { \"Prime numbers\", \"Twin primes\", \"Prime triplets\",\n \"Prime quadruplets\", \"Prime quintuplets\", \"Prime sextuplets\",\n \"Prime septuplets\" };\n}\n\nvoid version() {\n std::cout << \"primesieve 2.0, <http:\/\/primesieve.googlecode.com>\" << std::endl\n << \"Copyright (C) 2011 Kim Walisch\" << std::endl\n << \"License GPLv3+: GNU GPL version 3 or later <http:\/\/gnu.org\/licenses\/gpl.html>.\" << std::endl\n << \"This is free software: you are free to change and redistribute it.\" << std::endl\n << \"There is NO WARRANTY, to the extent permitted by law.\" << std::endl;\n std::exit(EXIT_SUCCESS);\n}\n\nvoid help() {\n std::cout << \"Usage: primesieve START STOP [OPTION]...\" << std::endl\n << \"Use the sieve of Eratosthenes to find the prime numbers and prime\" << std::endl\n << \"k-tuplets between START and STOP < 2^64\" << std::endl\n << std::endl\n << \"Examples:\" << std::endl\n << \" primesieve 1 10000000 -p1\" << std::endl\n << \" primesieve 1 1e11 -s 32\" << std::endl\n << \" primesieve 1e18 1e18+2**32 -c1234567\" << std::endl\n << std::endl\n << \"Options:\" << std::endl\n << \" -c[N] Count prime numbers and\/or prime k-tuplets,\" << std::endl\n << \" e.g -c1 count prime numbers, -c3 count prime triplets, ...\" << std::endl\n << \" N >= 1 and N <= 7\" << std::endl\n << \" -p[N] Print prime numbers or prime k-tuplets,\" << std::endl\n << \" e.g -p1 print prime numbers, -p2 print twin primes, ...\" << std::endl\n << \" N >= 1 and N <= 7\" << std::endl\n << \" -q Quiet mode, print less output\" << std::endl\n << \" -s <SIZE> Set the sieve size in KiloBytes, e.g. -s 256,\" << std::endl\n << \" set SIZE to your CPU's L1\/L2 cache size for best performance\" << std::endl\n << \" SIZE >= 1 and SIZE <= 8192\" << std::endl\n << \" -t <THREADS> Set the number of threads for sieving, e.g. -t 4,\" << std::endl\n << \" THREADS >= 1 and THREADS <= \" << maxThreads << \" (CPU max threads)\" << std::endl\n << \" -test Run various sieving tests and exit\" << std::endl\n << \" -v Print version and license information and exit\" << std::endl;\n std::exit(EXIT_SUCCESS);\n}\n\nvoid exprError(const std::string &str) {\n std::cerr << \"Error: \\\"\" << str\n << \"\\\" is not a valid arithmetic expression\" << std::endl\n << \"Try `primesieve -help' for more information.\" << std::endl;\n std::exit(EXIT_FAILURE);\n}\n\nbool isDigits(const std::string &str) {\n if (str.length() == 0)\n return false;\n return str.find_first_not_of(\"0123456789\") == std::string::npos;\n}\n\n\/**\n * Process the command-line options.\n * @see help(void)\n *\/\nvoid processOptions(int argc, char* argv[]) {\n if (argc < 2 || argc > 20)\n help();\n ExpressionParser<uint64_t> parser;\n int i = 1;\n\n \/\/ process the START and STOP numbers\n if (argc > 2) {\n if (!isDigits(argv[i]))\n showExpressionResults = true;\n if (!parser.eval(argv[i]))\n exprError(argv[i]);\n start = parser.getResult();\n i++;\n if (!isDigits(argv[i]))\n showExpressionResults = true;\n if (!parser.eval(argv[i]))\n exprError(argv[i]);\n stop = parser.getResult();\n i++;\n }\n\n \/\/ process the options ([OPTION]...)\n for (; i < argc; i++) {\n char* c = argv[i];\n if (*c != '-' && *c != '\/')\n help();\n switch (std::tolower(*(++c)++)) {\n case 'c': do {\n if (*c < '1' || *c > '7')\n help();\n flags |= COUNT_PRIMES << (*c - '1');\n } while (*(++c) != 0);\n break;\n case 'p': if (*c < '1' || *c > '7')\n help();\n flags |= PRINT_PRIMES << (*c - '1');\n quietMode = true;\n break;\n case 'q': quietMode = true;\n break;\n case 's': if (++i >= argc || !parser.eval(argv[i]))\n help();\n sieveSize = static_cast<uint32_t> (parser.getResult());\n sieveSize = nextHighestPowerOf2(sieveSize);\n break;\n case 't': if (std::string(\"test\").compare(++argv[i]) == 0) {\n test();\n std::exit(EXIT_SUCCESS);\n }\n if (++i >= argc || !parser.eval(argv[i]))\n help();\n threads = static_cast<int> (parser.getResult());\n break;\n case 'v': version();\n default : help();\n }\n }\n}\n\n\/**\n * Process the command-line options and start sieving.\n *\/\nint main(int argc, char* argv[]) {\n processOptions(argc, argv);\n int width = static_cast<int> (std::strlen(\"Sieve size\"));\n std::cout.setf(std::ios::left);\n\n \/\/ display expression results\n if (!quietMode && showExpressionResults)\n std::cout << std::setw(width) << \"START\" << \" = \" << start << std::endl\n << std::setw(width) << \"STOP\" << \" = \" << stop << std::endl;\n\n \/\/ set default settings\n if ((flags & COUNT_FLAGS) == 0 && (flags & PRINT_FLAGS) == 0)\n flags |= COUNT_PRIMES;\n if (!quietMode && (flags & PRINT_FLAGS) == 0)\n flags |= PRINT_STATUS;\n if (sieveSize == 0)\n sieveSize = (stop < L2_THRESHOLD) ?L1_CACHE_SIZE :L2_CACHE_SIZE;\n\n if (!quietMode)\n std::cout << std::setw(width) << \"Sieve size\" << \" = \" << sieveSize\n << \" KiloBytes\" << std::endl;\n try {\n ParallelPrimeSieve primeSieve;\n primeSieve.setStartNumber(start);\n primeSieve.setStopNumber(stop);\n primeSieve.setSieveSize(sieveSize);\n primeSieve.setFlags(flags);\n\n if (threads == -1)\n threads = primeSieve.getIdealThreadCount();\n if (!quietMode)\n std::cout << std::setw(width) << \"Threads\" << \" = \" << threads << std::endl;\n\n \/\/ start sieving primes\n primeSieve.sieve(threads);\n if ((flags & PRINT_STATUS) || (flags & PRINT_FLAGS))\n std::cout << std::endl;\n\n \/\/ get max output string length\n width = static_cast<int> (std::strlen(\"Time elapsed\"));\n for (int i = 0; i < primeSieve.COUNTS_SIZE; i++) {\n if (flags & (COUNT_PRIMES << i)) {\n int length = static_cast<int> (primes[i].length());\n if (width < length)\n width = length;\n }\n }\n \/\/ print prime count results\n for (int i = 0; i < primeSieve.COUNTS_SIZE; i++) {\n if (flags & (COUNT_PRIMES << i))\n std::cout << std::setw(width) << primes[i] << \" : \" <<\n primeSieve.getCounts(i) << std::endl;\n }\n std::cout << std::setw(width) << \"Time elapsed\" << \" : \" <<\n primeSieve.getTimeElapsed() << \" sec\" << std::endl;\n }\n catch (std::exception& ex) {\n std::cerr << \"Error: \" << ex.what() << std::endl\n << \"Try `primesieve -help' for more information.\" << std::endl;\n std::exit(EXIT_FAILURE);\n }\n return 0;\n}\n<commit_msg>cosmetics<commit_after>\/*\n * main.cpp -- This file is part of primesieve\n *\n * Copyright (C) 2011 Kim Walisch, <kim.walisch@gmail.com>\n *\n * This program is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>\n *\/\n\n\/** \n * @file main.cpp\n * @brief Command-line version of primesieve, multi-threaded (OpenMP),\n * compiles on many platforms.\n *\n * primesieve is a highly optimized implementation of the sieve of\n * Eratosthenes that finds prime numbers and prime k-tuplets (twin\n * primes, prime triplets, ...) up to 2^64 maximum.\n *\/\n\n#include \"..\/expr\/ExpressionParser.h\"\n#include \"..\/soe\/ParallelPrimeSieve.h\"\n#include \"..\/soe\/pmath.h\"\n#include \"..\/soe\/cpuid.h\"\n\n\/\/\/ declared in test.cpp\nvoid test();\n\n#include <stdint.h>\n#include <exception>\n#include <iostream>\n#include <iomanip> \/* std::setw(int) *\/\n#include <cstdlib> \/* std::exit(int) *\/\n#include <string>\n#include <cstring> \/* std::strlen(const char*) *\/\n#include <cctype> \/* std::tolower(int) *\/\n#include <sstream>\n\nnamespace {\n \/\/ Unfortunately there is no easy way to get the CPU L1 and L2 cache\n \/\/ size, these values are close for most x86-64 CPUs in 2011\n const uint32_t L1_CACHE_SIZE = 64;\n const uint32_t L2_CACHE_SIZE = 512;\n const uint64_t L2_THRESHOLD = ipow(10, 11) * 5;\n\n bool quietMode = false;\n bool showExpressionResults = false;\n\n uint64_t numbers[2] = {0, 0}; \/* start and stop number for sieving *\/\n uint32_t sieveSize = 0; \/* sieve size in KiloBytes *\/\n uint32_t flags = 0; \/* settings *\/\n\n int maxThreads = ParallelPrimeSieve::getMaxThreads();\n int threads = -1;\n\n std::string primes[7] = { \"Prime numbers\", \"Twin primes\", \"Prime triplets\",\n \"Prime quadruplets\", \"Prime quintuplets\", \"Prime sextuplets\",\n \"Prime septuplets\" };\n}\n\nvoid version() {\n std::cout << \"primesieve 2.0, <http:\/\/primesieve.googlecode.com>\" << std::endl\n << \"Copyright (C) 2011 Kim Walisch\" << std::endl\n << \"License GPLv3+: GNU GPL version 3 or later <http:\/\/gnu.org\/licenses\/gpl.html>.\" << std::endl\n << \"This is free software: you are free to change and redistribute it.\" << std::endl\n << \"There is NO WARRANTY, to the extent permitted by law.\" << std::endl;\n std::exit(EXIT_SUCCESS);\n}\n\nvoid help() {\n std::cout << \"Usage: primesieve START STOP [OPTION]...\" << std::endl\n << \"Use the sieve of Eratosthenes to find the prime numbers and prime\" << std::endl\n << \"k-tuplets between START and STOP < 2^64\" << std::endl\n << std::endl\n << \"Examples:\" << std::endl\n << \" primesieve 1 10000000 -p1\" << std::endl\n << \" primesieve 1 1e11 -s 32\" << std::endl\n << \" primesieve 1e18 1e18+2**32 -c1234567\" << std::endl\n << std::endl\n << \"Options:\" << std::endl\n << \" -c[N] Count prime numbers and\/or prime k-tuplets,\" << std::endl\n << \" e.g -c1 count prime numbers, -c3 count prime triplets, ...\" << std::endl\n << \" N >= 1 and N <= 7\" << std::endl\n << \" -p[N] Print prime numbers or prime k-tuplets,\" << std::endl\n << \" e.g -p1 print prime numbers, -p2 print twin primes, ...\" << std::endl\n << \" N >= 1 and N <= 7\" << std::endl\n << \" -q Quiet mode, print less output\" << std::endl\n << \" -s <SIZE> Set the sieve size in KiloBytes, e.g. -s 256,\" << std::endl\n << \" set SIZE to your CPU's L1\/L2 cache size for best performance\" << std::endl\n << \" SIZE >= 1 and SIZE <= 8192\" << std::endl\n << \" -t <THREADS> Set the number of threads for sieving, e.g. -t 4,\" << std::endl\n << \" THREADS >= 1 and THREADS <= \" << maxThreads << \" (CPU max threads)\" << std::endl\n << \" -test Run various sieving tests and exit\" << std::endl\n << \" -v Print version and license information and exit\" << std::endl;\n std::exit(EXIT_SUCCESS);\n}\n\nbool isDigits(const std::string &str) {\n if (str.length() == 0)\n return false;\n return str.find_first_not_of(\"0123456789\") == std::string::npos;\n}\n\n\/**\n * Process the command-line options.\n * @see help(void)\n *\/\nvoid processOptions(int argc, char* argv[]) {\n if (argc < 2 || argc > 20)\n help();\n ExpressionParser<uint64_t> parser;\n int i = 1;\n\n \/\/ process the START and STOP numbers\n if (argc > 2)\n for (; i <= 2; i++) {\n if (!parser.eval(argv[i])) {\n std::cerr << \"Error: \\\"\" << argv[i] << \"\\\" is not a valid arithmetic expression\" << std::endl\n << \"Try `primesieve -help' for more information.\" << std::endl;\n std::exit(EXIT_FAILURE);\n }\n numbers[i-1] = parser.getResult();\n if (!isDigits(argv[i]))\n showExpressionResults = true;\n }\n\n \/\/ process the options ([OPTION]...)\n for (; i < argc; i++) {\n char* c = argv[i];\n if (*c != '-' && *c != '\/')\n help();\n switch (std::tolower(*(++c)++)) {\n case 'c': do {\n if (*c < '1' || *c > '7')\n help();\n flags |= COUNT_PRIMES << (*c - '1');\n } while (*(++c) != 0);\n break;\n case 'p': if (*c < '1' || *c > '7')\n help();\n flags |= PRINT_PRIMES << (*c - '1');\n quietMode = true;\n break;\n case 'q': quietMode = true;\n break;\n case 's': if (++i >= argc || !parser.eval(argv[i]))\n help();\n sieveSize = static_cast<uint32_t> (parser.getResult());\n sieveSize = nextHighestPowerOf2(sieveSize);\n break;\n case 't': if (std::string(\"test\").compare(++argv[i]) == 0) {\n test();\n std::exit(EXIT_SUCCESS);\n }\n if (++i >= argc || !parser.eval(argv[i]))\n help();\n threads = static_cast<int> (parser.getResult());\n break;\n case 'v': version();\n default : help();\n }\n }\n}\n\n\/**\n * Process the command-line options and start sieving.\n *\/\nint main(int argc, char* argv[]) {\n processOptions(argc, argv);\n int width = static_cast<int> (std::strlen(\"Sieve size\"));\n std::cout.setf(std::ios::left);\n\n \/\/ display expression results\n if (!quietMode && showExpressionResults)\n std::cout << std::setw(width) << \"START\" << \" = \" << numbers[0] << std::endl\n << std::setw(width) << \"STOP\" << \" = \" << numbers[1] << std::endl;\n\n \/\/ set default settings\n if ((flags & COUNT_FLAGS) == 0 && (flags & PRINT_FLAGS) == 0)\n flags |= COUNT_PRIMES;\n if (!quietMode && (flags & PRINT_FLAGS) == 0)\n flags |= PRINT_STATUS;\n if (sieveSize == 0)\n sieveSize = (numbers[1] < L2_THRESHOLD) ?L1_CACHE_SIZE :L2_CACHE_SIZE;\n\n if (!quietMode)\n std::cout << std::setw(width) << \"Sieve size\" << \" = \" << sieveSize\n << \" KiloBytes\" << std::endl;\n try {\n ParallelPrimeSieve primeSieve;\n primeSieve.setStartNumber(numbers[0]);\n primeSieve.setStopNumber(numbers[1]);\n primeSieve.setSieveSize(sieveSize);\n primeSieve.setFlags(flags);\n\n if (threads == -1)\n threads = primeSieve.getIdealThreadCount();\n if (!quietMode)\n std::cout << std::setw(width) << \"Threads\" << \" = \" << threads << std::endl;\n\n \/\/ start sieving primes\n primeSieve.sieve(threads);\n if ((flags & PRINT_STATUS) || (flags & PRINT_FLAGS))\n std::cout << std::endl;\n\n \/\/ get max output string length\n width = static_cast<int> (std::strlen(\"Time elapsed\"));\n for (int i = 0; i < primeSieve.COUNTS_SIZE; i++) {\n if (flags & (COUNT_PRIMES << i)) {\n int length = static_cast<int> (primes[i].length());\n if (width < length)\n width = length;\n }\n }\n \/\/ print prime count results\n for (int i = 0; i < primeSieve.COUNTS_SIZE; i++) {\n if (flags & (COUNT_PRIMES << i))\n std::cout << std::setw(width) << primes[i] << \" : \" <<\n primeSieve.getCounts(i) << std::endl;\n }\n std::cout << std::setw(width) << \"Time elapsed\" << \" : \" <<\n primeSieve.getTimeElapsed() << \" sec\" << std::endl;\n }\n catch (std::exception& ex) {\n std::cerr << \"Error: \" << ex.what() << std::endl\n << \"Try `primesieve -help' for more information.\" << std::endl;\n std::exit(EXIT_FAILURE);\n }\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n Copyright (c) 2009-2011 250bpm s.r.o.\n Copyright (c) 2011 Botond Ballo\n Copyright (c) 2007-2009 iMatix Corporation\n\n Permission is hereby granted, free of charge, to any person obtaining a copy\n of this software and associated documentation files (the \"Software\"), to\n deal in the Software without restriction, including without limitation the\n rights to use, copy, modify, merge, publish, distribute, sublicense, and\/or\n sell copies of the Software, and to permit persons to whom the Software is\n furnished to do so, subject to the following conditions:\n\n The above copyright notice and this permission notice shall be included in\n all copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n IN THE SOFTWARE.\n*\/\n\n#ifndef __ZMQ_HPP_INCLUDED__\n#define __ZMQ_HPP_INCLUDED__\n\n#include <zmq.h>\n\n#include <cassert>\n#include <cstring>\n#include <algorithm>\n#include <exception>\n\n\/\/ Detect whether the compiler supports C++11 rvalue references.\n#if (defined(__GNUC__) && (__GNUC__ > 4 || \\\n (__GNUC__ == 4 && __GNUC_MINOR__ > 2)) && \\\n defined(__GXX_EXPERIMENTAL_CXX0X__))\n #define ZMQ_HAS_RVALUE_REFS\n#endif\n#if (defined(__clang__))\n #if __has_feature(cxx_rvalue_references)\n #define ZMQ_HAS_RVALUE_REFS\n #endif\n#endif\n#if (defined(_MSC_VER) && (_MSC_VER >= 1600))\n #define ZMQ_HAS_RVALUE_REFS\n#endif\n\n\/\/ In order to prevent unused variable warnings when building in non-debug\n\/\/ mode use this macro to make assertions.\n#ifndef NDEBUG\n# define ZMQ_ASSERT(expression) assert(expression)\n#else\n# define ZMQ_ASSERT(expression) (expression)\n#endif\n\nnamespace zmq\n{\n\n typedef zmq_free_fn free_fn;\n typedef zmq_pollitem_t pollitem_t;\n\n class error_t : public std::exception\n {\n public:\n\n error_t () : errnum (zmq_errno ()) {}\n\n virtual const char *what () const throw ()\n {\n return zmq_strerror (errnum);\n }\n\n int num () const\n {\n return errnum;\n }\n\n private:\n\n int errnum;\n };\n\n inline int poll (zmq_pollitem_t *items_, int nitems_, long timeout_ = -1)\n {\n int rc = zmq_poll (items_, nitems_, timeout_);\n if (rc < 0)\n throw error_t ();\n return rc;\n }\n\n inline void version (int *major_, int *minor_, int *patch_)\n {\n zmq_version (major_, minor_, patch_);\n }\n\n class message_t\n {\n friend class socket_t;\n\n public:\n\n inline message_t ()\n {\n int rc = zmq_msg_init (&msg);\n if (rc != 0)\n throw error_t ();\n }\n\n inline message_t (size_t size_)\n {\n int rc = zmq_msg_init_size (&msg, size_);\n if (rc != 0)\n throw error_t ();\n }\n\n inline message_t (void *data_, size_t size_, free_fn *ffn_,\n void *hint_ = NULL)\n {\n int rc = zmq_msg_init_data (&msg, data_, size_, ffn_, hint_);\n if (rc != 0)\n throw error_t ();\n }\n\n#ifdef ZMQ_HAS_RVALUE_REFS\n inline message_t (message_t &&rhs) : msg (rhs.msg)\n {\n int rc = zmq_msg_init (&rhs.msg);\n if (rc != 0)\n throw error_t ();\n }\n\n inline message_t &operator = (message_t &&rhs)\n {\n std::swap (msg, rhs.msg);\n return *this;\n }\n#endif\n\n inline ~message_t ()\n {\n int rc = zmq_msg_close (&msg);\n ZMQ_ASSERT (rc == 0);\n }\n\n inline void rebuild ()\n {\n int rc = zmq_msg_close (&msg);\n if (rc != 0)\n throw error_t ();\n rc = zmq_msg_init (&msg);\n if (rc != 0)\n throw error_t ();\n }\n\n inline void rebuild (size_t size_)\n {\n int rc = zmq_msg_close (&msg);\n if (rc != 0)\n throw error_t ();\n rc = zmq_msg_init_size (&msg, size_);\n if (rc != 0)\n throw error_t ();\n }\n\n inline void rebuild (void *data_, size_t size_, free_fn *ffn_,\n void *hint_ = NULL)\n {\n int rc = zmq_msg_close (&msg);\n if (rc != 0)\n throw error_t ();\n rc = zmq_msg_init_data (&msg, data_, size_, ffn_, hint_);\n if (rc != 0)\n throw error_t ();\n }\n\n inline void move (message_t *msg_)\n {\n int rc = zmq_msg_move (&msg, &(msg_->msg));\n if (rc != 0)\n throw error_t ();\n }\n\n inline void copy (message_t *msg_)\n {\n int rc = zmq_msg_copy (&msg, &(msg_->msg));\n if (rc != 0)\n throw error_t ();\n }\n\n inline void *data ()\n {\n return zmq_msg_data (&msg);\n }\n\n inline const void* data () const\n {\n return zmq_msg_data (const_cast<zmq_msg_t*>(&msg));\n }\n\n inline size_t size () const\n {\n return zmq_msg_size (const_cast<zmq_msg_t*>(&msg));\n }\n\n private:\n\n \/\/ The underlying message\n zmq_msg_t msg;\n\n \/\/ Disable implicit message copying, so that users won't use shared\n \/\/ messages (less efficient) without being aware of the fact.\n message_t (const message_t&);\n void operator = (const message_t&);\n };\n\n class context_t\n {\n friend class socket_t;\n\n public:\n\n inline context_t (int io_threads_)\n {\n ptr = zmq_init (io_threads_);\n if (ptr == NULL)\n throw error_t ();\n }\n\n#ifdef ZMQ_HAS_RVALUE_REFS\n inline context_t (context_t &&rhs) : ptr (rhs.ptr)\n {\n rhs.ptr = NULL;\n }\n inline context_t &operator = (context_t &&rhs)\n {\n std::swap (ptr, rhs.ptr);\n return *this;\n }\n#endif\n\n inline ~context_t ()\n {\n close();\n }\n\n inline void close()\n {\n if (ptr == NULL)\n return;\n int rc = zmq_term (ptr);\n ZMQ_ASSERT (rc == 0);\n ptr = NULL;\n }\n\n \/\/ Be careful with this, it's probably only useful for\n \/\/ using the C api together with an existing C++ api.\n \/\/ Normally you should never need to use this.\n inline operator void* ()\n {\n return ptr;\n }\n\n private:\n\n void *ptr;\n\n context_t (const context_t&);\n void operator = (const context_t&);\n };\n\n class socket_t\n {\n public:\n\n inline socket_t (context_t &context_, int type_)\n {\n ptr = zmq_socket (context_.ptr, type_);\n if (ptr == NULL)\n throw error_t ();\n }\n\n#ifdef ZMQ_HAS_RVALUE_REFS\n inline socket_t(socket_t&& rhs) : ptr(rhs.ptr)\n {\n rhs.ptr = NULL;\n }\n inline socket_t& operator=(socket_t&& rhs)\n {\n std::swap(ptr, rhs.ptr);\n return *this;\n }\n#endif\n\n inline ~socket_t ()\n {\n close();\n }\n\n inline operator void* ()\n {\n return ptr;\n }\n\n inline void close()\n {\n if(ptr == NULL)\n \/\/ already closed\n return ;\n int rc = zmq_close (ptr);\n ZMQ_ASSERT (rc == 0);\n ptr = 0 ;\n }\n\n inline void setsockopt (int option_, const void *optval_,\n size_t optvallen_)\n {\n int rc = zmq_setsockopt (ptr, option_, optval_, optvallen_);\n if (rc != 0)\n throw error_t ();\n }\n\n inline void getsockopt (int option_, void *optval_,\n size_t *optvallen_)\n {\n int rc = zmq_getsockopt (ptr, option_, optval_, optvallen_);\n if (rc != 0)\n throw error_t ();\n }\n\n inline void bind (const char *addr_)\n {\n int rc = zmq_bind (ptr, addr_);\n if (rc != 0)\n throw error_t ();\n }\n\n inline void connect (const char *addr_)\n {\n int rc = zmq_connect (ptr, addr_);\n if (rc != 0)\n throw error_t ();\n }\n\n inline bool connected()\n {\n return(ptr != NULL);\n }\n\n inline size_t send (const void *buf_, size_t len_, int flags_ = 0)\n {\n int nbytes = zmq_send (ptr, buf_, len_, flags_);\n if (nbytes >= 0)\n return (size_t) nbytes;\n if (zmq_errno () == EAGAIN)\n return 0;\n throw error_t ();\n }\n\n inline bool send (message_t &msg_, int flags_ = 0)\n {\n int nbytes = zmq_sendmsg (ptr, &(msg_.msg), flags_);\n if (nbytes >= 0)\n return true;\n if (zmq_errno () == EAGAIN)\n return false;\n throw error_t ();\n }\n\n inline size_t recv (void *buf_, size_t len_, int flags_ = 0)\n {\n int nbytes = zmq_recv (ptr, buf_, len_, flags_);\n if (nbytes >= 0)\n return (size_t) nbytes;\n if (zmq_errno () == EAGAIN)\n return 0;\n throw error_t ();\n }\n\n inline bool recv (message_t *msg_, int flags_ = 0)\n {\n int nbytes = zmq_recvmsg (ptr, &(msg_->msg), flags_);\n if (nbytes >= 0)\n return true;\n if (zmq_errno () == EAGAIN)\n return false;\n throw error_t ();\n }\n\n private:\n\n void *ptr;\n\n socket_t (const socket_t&);\n void operator = (const socket_t&);\n };\n\n}\n\n#endif\n\n<commit_msg>Don't use deprecated functions<commit_after>\/*\n Copyright (c) 2009-2011 250bpm s.r.o.\n Copyright (c) 2011 Botond Ballo\n Copyright (c) 2007-2009 iMatix Corporation\n\n Permission is hereby granted, free of charge, to any person obtaining a copy\n of this software and associated documentation files (the \"Software\"), to\n deal in the Software without restriction, including without limitation the\n rights to use, copy, modify, merge, publish, distribute, sublicense, and\/or\n sell copies of the Software, and to permit persons to whom the Software is\n furnished to do so, subject to the following conditions:\n\n The above copyright notice and this permission notice shall be included in\n all copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n IN THE SOFTWARE.\n*\/\n\n#ifndef __ZMQ_HPP_INCLUDED__\n#define __ZMQ_HPP_INCLUDED__\n\n#include <zmq.h>\n\n#include <algorithm>\n#include <cassert>\n#include <cstring>\n#include <exception>\n\n\/\/ Detect whether the compiler supports C++11 rvalue references.\n#if (defined(__GNUC__) && (__GNUC__ > 4 || \\\n (__GNUC__ == 4 && __GNUC_MINOR__ > 2)) && \\\n defined(__GXX_EXPERIMENTAL_CXX0X__))\n #define ZMQ_HAS_RVALUE_REFS\n#endif\n#if (defined(__clang__))\n #if __has_feature(cxx_rvalue_references)\n #define ZMQ_HAS_RVALUE_REFS\n #endif\n#endif\n#if (defined(_MSC_VER) && (_MSC_VER >= 1600))\n #define ZMQ_HAS_RVALUE_REFS\n#endif\n\n\/\/ In order to prevent unused variable warnings when building in non-debug\n\/\/ mode use this macro to make assertions.\n#ifndef NDEBUG\n# define ZMQ_ASSERT(expression) assert(expression)\n#else\n# define ZMQ_ASSERT(expression) (expression)\n#endif\n\nnamespace zmq\n{\n\n typedef zmq_free_fn free_fn;\n typedef zmq_pollitem_t pollitem_t;\n\n class error_t : public std::exception\n {\n public:\n\n error_t () : errnum (zmq_errno ()) {}\n\n virtual const char *what () const throw ()\n {\n return zmq_strerror (errnum);\n }\n\n int num () const\n {\n return errnum;\n }\n\n private:\n\n int errnum;\n };\n\n inline int poll (zmq_pollitem_t *items_, int nitems_, long timeout_ = -1)\n {\n int rc = zmq_poll (items_, nitems_, timeout_);\n if (rc < 0)\n throw error_t ();\n return rc;\n }\n\n inline void version (int *major_, int *minor_, int *patch_)\n {\n zmq_version (major_, minor_, patch_);\n }\n\n class message_t\n {\n friend class socket_t;\n\n public:\n\n inline message_t ()\n {\n int rc = zmq_msg_init (&msg);\n if (rc != 0)\n throw error_t ();\n }\n\n inline message_t (size_t size_)\n {\n int rc = zmq_msg_init_size (&msg, size_);\n if (rc != 0)\n throw error_t ();\n }\n\n inline message_t (void *data_, size_t size_, free_fn *ffn_,\n void *hint_ = NULL)\n {\n int rc = zmq_msg_init_data (&msg, data_, size_, ffn_, hint_);\n if (rc != 0)\n throw error_t ();\n }\n\n#ifdef ZMQ_HAS_RVALUE_REFS\n inline message_t (message_t &&rhs) : msg (rhs.msg)\n {\n int rc = zmq_msg_init (&rhs.msg);\n if (rc != 0)\n throw error_t ();\n }\n\n inline message_t &operator = (message_t &&rhs)\n {\n std::swap (msg, rhs.msg);\n return *this;\n }\n#endif\n\n inline ~message_t ()\n {\n int rc = zmq_msg_close (&msg);\n ZMQ_ASSERT (rc == 0);\n }\n\n inline void rebuild ()\n {\n int rc = zmq_msg_close (&msg);\n if (rc != 0)\n throw error_t ();\n rc = zmq_msg_init (&msg);\n if (rc != 0)\n throw error_t ();\n }\n\n inline void rebuild (size_t size_)\n {\n int rc = zmq_msg_close (&msg);\n if (rc != 0)\n throw error_t ();\n rc = zmq_msg_init_size (&msg, size_);\n if (rc != 0)\n throw error_t ();\n }\n\n inline void rebuild (void *data_, size_t size_, free_fn *ffn_,\n void *hint_ = NULL)\n {\n int rc = zmq_msg_close (&msg);\n if (rc != 0)\n throw error_t ();\n rc = zmq_msg_init_data (&msg, data_, size_, ffn_, hint_);\n if (rc != 0)\n throw error_t ();\n }\n\n inline void move (message_t *msg_)\n {\n int rc = zmq_msg_move (&msg, &(msg_->msg));\n if (rc != 0)\n throw error_t ();\n }\n\n inline void copy (message_t *msg_)\n {\n int rc = zmq_msg_copy (&msg, &(msg_->msg));\n if (rc != 0)\n throw error_t ();\n }\n\n inline void *data ()\n {\n return zmq_msg_data (&msg);\n }\n\n inline const void* data () const\n {\n return zmq_msg_data (const_cast<zmq_msg_t*>(&msg));\n }\n\n inline size_t size () const\n {\n return zmq_msg_size (const_cast<zmq_msg_t*>(&msg));\n }\n\n private:\n\n \/\/ The underlying message\n zmq_msg_t msg;\n\n \/\/ Disable implicit message copying, so that users won't use shared\n \/\/ messages (less efficient) without being aware of the fact.\n message_t (const message_t&);\n void operator = (const message_t&);\n };\n\n class context_t\n {\n friend class socket_t;\n\n public:\n\n inline context_t (int io_threads_)\n {\n ptr = zmq_init (io_threads_);\n if (ptr == NULL)\n throw error_t ();\n }\n\n#ifdef ZMQ_HAS_RVALUE_REFS\n inline context_t (context_t &&rhs) : ptr (rhs.ptr)\n {\n rhs.ptr = NULL;\n }\n inline context_t &operator = (context_t &&rhs)\n {\n std::swap (ptr, rhs.ptr);\n return *this;\n }\n#endif\n\n inline ~context_t ()\n {\n close();\n }\n\n inline void close()\n {\n if (ptr == NULL)\n return;\n int rc = zmq_term (ptr);\n ZMQ_ASSERT (rc == 0);\n ptr = NULL;\n }\n\n \/\/ Be careful with this, it's probably only useful for\n \/\/ using the C api together with an existing C++ api.\n \/\/ Normally you should never need to use this.\n inline operator void* ()\n {\n return ptr;\n }\n\n private:\n\n void *ptr;\n\n context_t (const context_t&);\n void operator = (const context_t&);\n };\n\n class socket_t\n {\n public:\n\n inline socket_t (context_t &context_, int type_)\n {\n ptr = zmq_socket (context_.ptr, type_);\n if (ptr == NULL)\n throw error_t ();\n }\n\n#ifdef ZMQ_HAS_RVALUE_REFS\n inline socket_t(socket_t&& rhs) : ptr(rhs.ptr)\n {\n rhs.ptr = NULL;\n }\n inline socket_t& operator=(socket_t&& rhs)\n {\n std::swap(ptr, rhs.ptr);\n return *this;\n }\n#endif\n\n inline ~socket_t ()\n {\n close();\n }\n\n inline operator void* ()\n {\n return ptr;\n }\n\n inline void close()\n {\n if(ptr == NULL)\n \/\/ already closed\n return ;\n int rc = zmq_close (ptr);\n ZMQ_ASSERT (rc == 0);\n ptr = 0 ;\n }\n\n inline void setsockopt (int option_, const void *optval_,\n size_t optvallen_)\n {\n int rc = zmq_setsockopt (ptr, option_, optval_, optvallen_);\n if (rc != 0)\n throw error_t ();\n }\n\n inline void getsockopt (int option_, void *optval_,\n size_t *optvallen_)\n {\n int rc = zmq_getsockopt (ptr, option_, optval_, optvallen_);\n if (rc != 0)\n throw error_t ();\n }\n\n inline void bind (const char *addr_)\n {\n int rc = zmq_bind (ptr, addr_);\n if (rc != 0)\n throw error_t ();\n }\n\n inline void connect (const char *addr_)\n {\n int rc = zmq_connect (ptr, addr_);\n if (rc != 0)\n throw error_t ();\n }\n\n inline bool connected()\n {\n return(ptr != NULL);\n }\n\n inline size_t send (const void *buf_, size_t len_, int flags_ = 0)\n {\n int nbytes = zmq_send (ptr, buf_, len_, flags_);\n if (nbytes >= 0)\n return (size_t) nbytes;\n if (zmq_errno () == EAGAIN)\n return 0;\n throw error_t ();\n }\n\n inline bool send (message_t &msg_, int flags_ = 0)\n {\n int nbytes = zmq_msg_send (&(msg_.msg), ptr, flags_);\n if (nbytes >= 0)\n return true;\n if (zmq_errno () == EAGAIN)\n return false;\n throw error_t ();\n }\n\n inline size_t recv (void *buf_, size_t len_, int flags_ = 0)\n {\n int nbytes = zmq_recv (ptr, buf_, len_, flags_);\n if (nbytes >= 0)\n return (size_t) nbytes;\n if (zmq_errno () == EAGAIN)\n return 0;\n throw error_t ();\n }\n\n inline bool recv (message_t *msg_, int flags_ = 0)\n {\n int nbytes = zmq_msg_recv (&(msg_->msg), ptr, flags_);\n if (nbytes >= 0)\n return true;\n if (zmq_errno () == EAGAIN)\n return false;\n throw error_t ();\n }\n\n private:\n\n void *ptr;\n\n socket_t (const socket_t&);\n void operator = (const socket_t&);\n };\n\n}\n\n#endif\n\n<|endoftext|>"} {"text":"<commit_before>#include <cassert>\n#include <fstream>\n#include <iostream>\n#include <strstream>\n\n#if !defined(NDEBUG) && defined(_MSC_VER)\n#include <crtdbg.h>\n#endif\n\n\/\/These came from the debug test.\n#include <cstdio>\n#include <ctime>\n#include <string>\n#include <vector>\n\n#include <util\/PlatformUtils.hpp>\n\n#include <PlatformSupport\/DOMStringHelper.hpp>\n#include <PlatformSupport\/XalanFileOutputStream.hpp>\n#include <PlatformSupport\/XalanOutputStreamPrintWriter.hpp>\n#include <XercesParserLiaison\/XercesDOMSupport.hpp>\n\n#include <XPath\/XObjectFactoryDefault.hpp>\n#include <XPath\/XPathSupportDefault.hpp>\n#include <XPath\/XPathFactoryDefault.hpp>\n\n#include <XSLT\/StylesheetConstructionContextDefault.hpp>\n#include <XSLT\/StylesheetExecutionContextDefault.hpp>\n#include <XSLT\/StylesheetRoot.hpp>\n#include <XSLT\/XSLTEngineImpl.hpp>\n#include <XSLT\/XSLTInit.hpp>\n#include <XSLT\/XSLTInputSource.hpp>\n#include <XSLT\/XSLTProcessorEnvSupportDefault.hpp>\n#include <XSLT\/XSLTResultTarget.hpp>\n\n#include <XercesParserLiaison\/XercesParserLiaison.hpp>\n\n\n\/\/This is here for the threads.\n#define WIN32_LEAN_AND_MEAN\n#include <windows.h>\n#include <winbase.h>\n#define THREADFUNCTIONRETURN DWORD WINAPI\n\n#if !defined(XALAN_NO_NAMESPACES)\n\tusing std::cerr;\n\tusing std::cout;\n\tusing std::cin;\n\tusing std::endl;\n\tusing std::ifstream;\n\tusing std::ios_base;\n\tusing std::ostrstream;\n\tusing std::string;\n#endif\n\n\n\/\/ This is here for memory leak testing.\n#if defined(_DEBUG)\n#include <crtdbg.h>\n#endif\n\n\nconst char* const\txslStylesheets[] =\n{\n\t\"v:\\\\xsl-test\\\\prod\\\\misc\\\\misc-chess\",\n\t\"v:\\\\xsl-test\\\\perf\\\\basic\\\\basic-all_well\",\n\t\"v:\\\\xsl-test\\\\perf\\\\basic\\\\basic-datetranscode\",\n\t\"v:\\\\xsl-test\\\\perf\\\\basic\\\\basic-dict2\",\n\t\"v:\\\\xsl-test\\\\perf\\\\basic\\\\basic-Fischer-Euwe\",\n\t\"v:\\\\xsl-test\\\\perf\\\\basic\\\\basic-queens\", \n\t\"v:\\\\xsl-test\\\\perf\\\\large\\\\large-all_well\",\n\t\/\/\"v:\\\\xsl-test\\\\perf\\\\large\\\\large-evans_large\", \n\t\"v:\\\\xsl-test\\\\perf\\\\nodes\\\\nodes-fancy_xml_tree_viewer_34\",\n\t\"v:\\\\xsl-test\\\\perf\\\\nodes\\\\nodes-showtree-19991008\",\n\t\"v:\\\\xsl-test\\\\perf\\\\sort\\\\sort-big\",\n\t\"v:\\\\xsl-test\\\\perf\\\\xpath\\\\xpath-evans_small\",\n\t\"v:\\\\xsl-test\\\\perf\\\\xpath\\\\xpath-evans_tiny\",\n\t0\n};\n\n\n\n\/\/ Used to hold compiled stylesheet, and source document.\nStylesheetRoot*\t\tglbStylesheetRoot[sizeof(xslStylesheets) \/ sizeof(const char*)];\n\nXalanNode*\t\t\tglbSourceDoc[sizeof(xslStylesheets) \/ sizeof(const char*)];\n\n\n\nvoid\noutputMessage(int iter)\n{\n\t\tcout << \"\\n\" << \"Starting Iteration: \" << iter << '\\0';\n}\n\n\n\nint\nmain(\n\t\t\tint\t\t\t\targc,\n\t\t\tconst char*\t\targv [])\n{\n\tassert(sizeof(glbStylesheetRoot) == sizeof(glbSourceDoc));\n\n#if !defined(NDEBUG) && defined(_MSC_VER)\n\t_CrtSetDbgFlag(_CrtSetDbgFlag(_CRTDBG_REPORT_FLAG) | _CRTDBG_LEAK_CHECK_DF);\n\n\t_CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);\n\t_CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR);\n#endif\n\n\tif (argc > 2)\n\t{\n\t\tcerr << \"Usage: perf\"\n\t\t\t << endl\n\t\t\t << endl;\n\t}\n\telse\n\t{\n\t\tint\titerCount = 1;\n\n\t\tif (argc == 2)\n\t\t{\n\t\t\titerCount = atoi(argv[1]);\n\t\t}\n\n\n\t\ttry\n\t\t{\n\t\t\t\/\/ Call the static initializers...\n\t\t\tXMLPlatformUtils::Initialize();\n\n\t\t\t{\n\t\t\t\tXSLTInit\ttheInit;\n\n\t\t\t\t\/\/ Create the necessary stuff to compile the stylesheet.\n\t\t\t\tXercesDOMSupport\t\t\t csDOMSupport;\n\t\t\t\tXercesParserLiaison\t\t\t\tcsParserLiaison(csDOMSupport);\n\t\t\t\tXPathSupportDefault\t\t\t\tcsXPathSupport(csDOMSupport);\n\t\t\t\tXSLTProcessorEnvSupportDefault\tcsXSLTProcessorEnvSupport;\n\t\t\t\tXObjectFactoryDefault\t\t\tcsXObjectFactory;\n\t\t\t\tXPathFactoryDefault\t\t\t\tcsXPathFactory;\n\n\t\t\t\t\/\/ Create a processor to compile the stylesheet...\n\t\t\t\tXSLTEngineImpl\tcsProcessor(\n\t\t\t\t\t\tcsParserLiaison,\n\t\t\t\t\t\tcsXPathSupport,\n\t\t\t\t\t\tcsXSLTProcessorEnvSupport,\n\t\t\t\t\t\tcsDOMSupport,\n\t\t\t\t\t\tcsXObjectFactory,\n\t\t\t\t\t\tcsXPathFactory);\n\n\t\t\t\t\/\/ Connect the processor to the support object...\n\t\t\t\tcsXSLTProcessorEnvSupport.setProcessor(&csProcessor);\n\n\t\t\t\t\/\/ Create separate factory support objects so the stylesheet's\n\t\t\t\t\/\/ factory-created XObject and XPath instances are independent \n\t\t\t\t\/\/ from processor's.\n\t\t\t\tXObjectFactoryDefault\tcsStylesheetXObjectFactory;\n\t\t\t\tXPathFactoryDefault\t\tcsStylesheetXPathFactory;\n\n\t\t\t\t\/\/ Create a stylesheet construction context, using the\n\t\t\t\t\/\/ stylesheet's factory support objects.\n\t\t\t\tStylesheetConstructionContextDefault\tcsConstructionContext(\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tcsProcessor,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tcsXSLTProcessorEnvSupport,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tcsStylesheetXPathFactory);\n\n\t\t\t\tconst XalanDOMString theXSLSuffix(\".xsl\");\n\t\t\t\tconst XalanDOMString theXMLSuffix(\".xml\");\n\t\t\t\tconst XalanDOMString theoutputSuffix(\".out\");\n\n\t\t\t\tfor(int i = 0; xslStylesheets[i] != 0; i++)\n\t\t\t\t{\n\t\t\t\t\tconst XalanDOMString theXSLFilename(XalanDOMString(xslStylesheets[i]) + theXSLSuffix);\n\t\t\t\t\tconst XalanDOMString theXMLFilename(XalanDOMString(xslStylesheets[i]) + theXMLSuffix);\n\n\t\t\t\t\tcout << \"Now compiling Stylesheet: \" << xslStylesheets[i] << endl;\n\n\t\t\t\t\t\/\/Generate the XML and XSL input objects.\n\t\t\t\t\tXSLTInputSource\t\tcsStylesheetSourceXSL(c_wstr(theXSLFilename));\n\t\t\t\t\tXSLTInputSource\t\tcsDocumentSource(c_wstr(theXMLFilename));\n\n\t\t\t\t\t\/\/ Ask the processor to create a StylesheetRoot for the specified\n\t\t\t\t\t\/\/ input XSL. This is the compiled stylesheet. We don't have to\n\t\t\t\t\t\/\/ delete it, since it is owned by the StylesheetConstructionContext\n\t\t\t\t\t\/\/ instance.\n\t\t\t\t\tglbStylesheetRoot[i] = csProcessor.processStylesheet(csStylesheetSourceXSL,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t csConstructionContext);\n\t\t\t\t\tassert(glbStylesheetRoot[i] != 0);\n\n\t\t\t\t\t\/\/ Have the processor create a compiled SourceDocument for the specified\n\t\t\t\t\t\/\/ input XML. \n\t\t\t\t\tglbSourceDoc[i] = csProcessor.getSourceTreeFromInput(csDocumentSource);\n\t\t\t\t\tassert(glbSourceDoc[i] != 0);\n\t\t\t\t}\n\n\n\t\t\t\t\tfor(int ii = 0; xslStylesheets[ii] != 0; ii++)\n\t\t\t\t\t{\n\t\t\t\t\t\tcout << endl << \"Now running test: \" << xslStylesheets[ii] << endl;\n\n\t\t\t\t\t\t\/\/ Create the necessary stuff to run the processor.\n\t\t\t\t\t\tXercesDOMSupport\t\t\t\tpsDOMSupport;\n\t\t\t\t\t\tXercesParserLiaison\t\t\t\tpsParserLiaison(psDOMSupport);\n\t\t\t\t\t\tXPathSupportDefault\t\t\t\tpsXPathSupport(psDOMSupport);\n\t\t\t\t\t\tXSLTProcessorEnvSupportDefault\tpsXSLTProcessorEnvSupport;\n\t\t\t\t\t\tXObjectFactoryDefault\t\t\tpsXObjectFactory;\n\t\t\t\t\t\tXPathFactoryDefault\t\t\t\tpsXPathFactory;\n\n\t\t\t\t\t\t\/\/ Create a processor to perform the transform.\n\t\t\t\t\t\tXSLTEngineImpl\tpsProcessor(\n\t\t\t\t\t\t\tpsParserLiaison,\n\t\t\t\t\t\t\tpsXPathSupport,\n\t\t\t\t\t\t\tpsXSLTProcessorEnvSupport,\n\t\t\t\t\t\t\tpsDOMSupport,\n\t\t\t\t\t\t\tpsXObjectFactory,\n\t\t\t\t\t\t\tpsXPathFactory);\n\n\t\t\t\t\t\t\/\/ Connect the processor to the support object...\n\t\t\t\t\t\tpsXSLTProcessorEnvSupport.setProcessor(&psProcessor);\n\n\t\t\t\t\t\t\/\/ The execution context uses the same factory support objects as\n\t\t\t\t\t\t\/\/ the processor, since those objects have the same lifetime as\n\t\t\t\t\t\t\/\/ other objects created as a result of the execution.\n\t\t\t\t\t\tStylesheetExecutionContextDefault\t\tpsExecutionContext(\n\t\t\t\t\t\t\t\tpsProcessor,\n\t\t\t\t\t\t\t\tpsXSLTProcessorEnvSupport,\n\t\t\t\t\t\t\t\tpsXPathSupport,\n\t\t\t\t\t\t\t\tpsXObjectFactory);\n\n\t\t\t\t\t\tconst XalanDOMString outputFileName(XalanDOMString(xslStylesheets[ii]) + theoutputSuffix);\n\n\t\t\t\t\t\t\/\/Generate the XML input and output objects.\n\t\t\t\t\t\tXSLTInputSource\t\tcsDocumentSource(glbSourceDoc[ii]);\n\t\t\t\t\t\tXSLTResultTarget\ttheResultTarget(outputFileName);\n\n\t\t\t\t\t\t\/\/ Set the stylesheet to be the compiled stylesheet. Then do the transform.\n\t\t\t\t\t\tconst double startTime = clock();\n\t\t\t\t\t\tcout << \"Clock before transforms: \" << startTime << endl;\n\t\t\t\t\t\tfor(int j = 0; j < iterCount; ++j)\n\t\t\t\t\t\t{\t\n\t\t\t\t\t\t\tpsProcessor.setStylesheetRoot(glbStylesheetRoot[ii]);\n\t\t\t\t\t\t\tpsProcessor.process(csDocumentSource, theResultTarget,psExecutionContext);\n\t\t\t\t\t\t\tpsExecutionContext.reset();\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconst double endTime = clock();\n\t\t\t\t\t\tcout << \"Clock after transforms: \" << endTime << endl;\n\t\t\t\t\t\tcout << \"Total clock ticks: \" << endTime - startTime << endl;\n\t\t\t\t\t\tconst double\tmillis = ((endTime - startTime) \/ CLOCKS_PER_SEC) * 1000.0;\n\t\t\t\t\t\tcout << \"Milliseconds: \" << millis << endl;\n\t\t\t\t\t\tcout << \"Averaged: \" << millis \/ iterCount << \" per iteration\" << endl;\n\t\t\t\t\t}\n\t\t\t\t\n\t\t\t}\n\n\t\t\tXMLPlatformUtils::Terminate();\n\t\t}\n\t\tcatch(...)\n\t\t{\n\t\t\tcerr << \"Exception caught!!!\"\n\t\t\t\t << endl\n\t\t\t\t << endl;\n\t\t}\n\t}\n\n\treturn 0;\n}\n<commit_msg>Removed second instance of processor, and did alot of cleanup.<commit_after>\/*\n * The Apache Software License, Version 1.1\n *\n *\n * Copyright (c) 1999 The Apache Software Foundation. All rights \n * reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer. \n *\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in\n * the documentation and\/or other materials provided with the\n * distribution.\n *\n * 3. The end-user documentation included with the redistribution,\n * if any, must include the following acknowledgment: \n * \"This product includes software developed by the\n * Apache Software Foundation (http:\/\/www.apache.org\/).\"\n * Alternately, this acknowledgment may appear in the software itself,\n * if and wherever such third-party acknowledgments normally appear.\n *\n * 4. The names \"Xalan\" and \"Apache Software Foundation\" must\n * not be used to endorse or promote products derived from this\n * software without prior written permission. For written \n * permission, please contact apache@apache.org.\n *\n * 5. Products derived from this software may not be called \"Apache\",\n * nor may \"Apache\" appear in their name, without prior written\n * permission of the Apache Software Foundation.\n *\n * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED\n * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR\n * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF\n * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT\n * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n * ====================================================================\n *\n * This software consists of voluntary contributions made by many\n * individuals on behalf of the Apache Software Foundation and was\n * originally based on software copyright (c) 1999, International\n * Business Machines, Inc., http:\/\/www.ibm.com. For more\n * information on the Apache Software Foundation, please see\n * <http:\/\/www.apache.org\/>.\n *\/\n#include <cassert>\n#include <fstream>\n#include <iostream>\n#include <strstream>\n\n#if !defined(NDEBUG) && defined(_MSC_VER)\n#include <crtdbg.h>\n#endif\n\n\/\/These came from the debug test.\n#include <cstdio>\n#include <ctime>\n#include <string>\n#include <vector>\n\n#include <util\/PlatformUtils.hpp>\n\n#include <PlatformSupport\/DOMStringHelper.hpp>\n#include <PlatformSupport\/XalanFileOutputStream.hpp>\n#include <PlatformSupport\/XalanOutputStreamPrintWriter.hpp>\n#include <XercesParserLiaison\/XercesDOMSupport.hpp>\n\n#include <XPath\/XObjectFactoryDefault.hpp>\n#include <XPath\/XPathSupportDefault.hpp>\n#include <XPath\/XPathFactoryDefault.hpp>\n\n#include <XSLT\/StylesheetConstructionContextDefault.hpp>\n#include <XSLT\/StylesheetExecutionContextDefault.hpp>\n#include <XSLT\/StylesheetRoot.hpp>\n#include <XSLT\/XSLTEngineImpl.hpp>\n#include <XSLT\/XSLTInit.hpp>\n#include <XSLT\/XSLTInputSource.hpp>\n#include <XSLT\/XSLTProcessorEnvSupportDefault.hpp>\n#include <XSLT\/XSLTResultTarget.hpp>\n\n#include <XercesParserLiaison\/XercesParserLiaison.hpp>\n\n\n\/\/This is here for the threads.\n#define WIN32_LEAN_AND_MEAN\n#include <windows.h>\n#include <winbase.h>\n#define THREADFUNCTIONRETURN DWORD WINAPI\n\n#if !defined(XALAN_NO_NAMESPACES)\n\tusing std::cerr;\n\tusing std::cout;\n\tusing std::cin;\n\tusing std::endl;\n\tusing std::ifstream;\n\tusing std::ios_base;\n\tusing std::ostrstream;\n\tusing std::string;\n#endif\n\n\n\/\/ This is here for memory leak testing.\n#if defined(_DEBUG)\n#include <crtdbg.h>\n#endif\n\n\nconst char* const\txslStylesheets[] =\n{\n\t\"v:\\\\xsl-test\\\\perf\\\\basic\\\\basic-all_well\",\n\t\"v:\\\\xsl-test\\\\perf\\\\basic\\\\basic-datetranscode\",\n\t\"v:\\\\xsl-test\\\\perf\\\\basic\\\\basic-dict2\",\n\t\"v:\\\\xsl-test\\\\perf\\\\basic\\\\basic-Fischer-Euwe\",\n\t\"v:\\\\xsl-test\\\\perf\\\\basic\\\\basic-queens\", \n\t\"v:\\\\xsl-test\\\\perf\\\\large\\\\large-all_well\",\n\t\/\/\"v:\\\\xsl-test\\\\perf\\\\large\\\\large-evans_large\", \n\t\"v:\\\\xsl-test\\\\perf\\\\nodes\\\\nodes-fancy_xml_tree_viewer_34\",\n\t\"v:\\\\xsl-test\\\\perf\\\\nodes\\\\nodes-showtree-19991008\",\n\t\"v:\\\\xsl-test\\\\perf\\\\sort\\\\sort-big\",\n\t\"v:\\\\xsl-test\\\\perf\\\\xpath\\\\xpath-evans_small\",\n\t\"v:\\\\xsl-test\\\\perf\\\\xpath\\\\xpath-evans_tiny\",\n\t0\n};\n\n\n\n\/\/ Used to hold compiled stylesheet, and source document.\nXalanNode*\t\tglbSourceXML[sizeof(xslStylesheets) \/ sizeof(const char*)];\nStylesheetRoot*\tglbStylesheetRoot[sizeof(xslStylesheets) \/ sizeof(const char*)];\n\nvoid outputMessage(int iter)\n{\n\tcout << \"\\n\" << \"Starting Iteration: \" << iter << '\\0';\n}\n\nint main( int argc,\tconst char* argv [])\n{\n\tassert(sizeof(glbStylesheetRoot) == sizeof(glbSourceXML));\n\n#if !defined(NDEBUG) && defined(_MSC_VER)\n\t_CrtSetDbgFlag(_CrtSetDbgFlag(_CRTDBG_REPORT_FLAG) | _CRTDBG_LEAK_CHECK_DF);\n\n\t_CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);\n\t_CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR);\n#endif\n\n\tif (argc > 2)\n\t{\n\t\tcerr << \"Usage: perf\" << endl << endl;\n\t}\n\telse\n\t{\n\t\tint\titerCount = 1;\n\t\tif (argc == 2)\n\t\t{\n\t\t\titerCount = atoi(argv[1]);\n\t\t}\n\n\t\ttry\n\t\t{\n\t\t\t\/\/ Call the static initializers...\n\t\t\tXMLPlatformUtils::Initialize();\n\n\t\t\t{\n\t\t\t\tXSLTInit\ttheInit;\n\n\t\t\t\tconst XalanDOMString XSLSuffix(\".xsl\");\n\t\t\t\tconst XalanDOMString XMLSuffix(\".xml\");\n\t\t\t\tconst XalanDOMString outputSuffix(\".out\");\n\n\t\t\t\t\/\/ Create the necessary support objects to instantiate a processor.\n\t\t\t\tXercesDOMSupport\t\t\t csDOMSupport;\n\t\t\t\tXercesParserLiaison\t\t\t\tcsParserLiaison(csDOMSupport);\n\t\t\t\tXPathSupportDefault\t\t\t\tcsXPathSupport(csDOMSupport);\n\t\t\t\tXSLTProcessorEnvSupportDefault\tcsXSLTProcessorEnvSupport;\n\t\t\t\tXObjectFactoryDefault\t\t\tcsXObjectFactory;\n\t\t\t\tXPathFactoryDefault\t\t\t\tcsXPathFactory;\n\n\t\t\t\t\/\/ Create a processor for stylesheet compilation and connect to \n\t\t\t\t\/\/ ProcessorEnvSupport object\n\t\t\t\tXSLTEngineImpl\tcsProcessor(\n\t\t\t\t\t\tcsParserLiaison,\n\t\t\t\t\t\tcsXPathSupport,\n\t\t\t\t\t\tcsXSLTProcessorEnvSupport,\n\t\t\t\t\t\tcsDOMSupport,\n\t\t\t\t\t\tcsXObjectFactory, \n\t\t\t\t\t\tcsXPathFactory);\n\t\t\t\tcsXSLTProcessorEnvSupport.setProcessor(&csProcessor);\n\n\t\t\t\t\/\/ Create separate factory support object, so the stylesheet's\n\t\t\t\t\/\/ factory-created XPath instance are independent from processor's.\n\t\t\t\tXPathFactoryDefault\t\t\tssXPathFactory;\n\n\t\t\t\t\/\/ Create a stylesheet construction context, using the\n\t\t\t\t\/\/ stylesheet's factory support objects.\n\t\t\t\tStylesheetConstructionContextDefault\tcsConstructionContext(\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tcsProcessor,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tcsXSLTProcessorEnvSupport,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tssXPathFactory);\n\n\t\t\t\tfor(int i = 0; xslStylesheets[i] != 0; i++)\n\t\t\t\t{\n\t\t\t\t\tconst XalanDOMString theXSLfile(XalanDOMString(xslStylesheets[i]) + XSLSuffix);\n\t\t\t\t\tconst XalanDOMString theXMLfile(XalanDOMString(xslStylesheets[i]) + XMLSuffix);\n\n\t\t\t\t\tcout << \"Now compiling Stylesheet: \" << xslStylesheets[i] << endl;\n\n\t\t\t\t\t\/\/Generate the XML and XSL input objects.\n\t\t\t\t\tXSLTInputSource\t\tcsStylesheetSourceXSL(c_wstr(theXSLfile));\n\t\t\t\t\tXSLTInputSource\t\tcsSourceXML(c_wstr(theXMLfile));\n\n\t\t\t\t\t\/\/ Ask the processor to create a compiled stylesheet (StylesheetRoot) for the \n\t\t\t\t\t\/\/ specified input XSL. We don't have to delete it, since it is owned by the \n\t\t\t\t\t\/\/ StylesheetConstructionContext instance.\n\t\t\t\t\tglbStylesheetRoot[i] = csProcessor.processStylesheet(csStylesheetSourceXSL,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t csConstructionContext);\n\t\t\t\t\tassert(glbStylesheetRoot[i] != 0);\n\n\t\t\t\t\t\/\/ Have the processor create a compiled SourceDocument for the specified\n\t\t\t\t\t\/\/ input XML. \n\t\t\t\t\tglbSourceXML[i] = csProcessor.getSourceTreeFromInput(csSourceXML);\n\t\t\t\t\tassert(glbSourceXML[i] != 0);\n\t\t\t\t}\n\n\t\t\t\tfor(int ii = 0; xslStylesheets[ii] != 0; ii++)\n\t\t\t\t{\n\t\t\t\t\tcout << endl << \"Now running test: \" << xslStylesheets[ii] << endl;\n\n\t\t\t\t\t\/\/ The execution context uses the same factory support objects as\n\t\t\t\t\t\/\/ the processor, since those objects have the same lifetime as\n\t\t\t\t\t\/\/ other objects created as a result of the execution.\n\t\t\t\t\tStylesheetExecutionContextDefault\tpsExecutionContext(\n\t\t\t\t\t\t\tcsProcessor,\n\t\t\t\t\t\t\tcsXSLTProcessorEnvSupport,\n\t\t\t\t\t\t\tcsXPathSupport,\n\t\t\t\t\t\t\tcsXObjectFactory);\n\n\t\t\t\t\tconst XalanDOMString outputfile(XalanDOMString(xslStylesheets[ii]) + outputSuffix);\n\n\t\t\t\t\t\/\/Generate the XML input and output objects.\n\t\t\t\t\tXSLTInputSource\t\tcsSourceXML(glbSourceXML[ii]);\n\t\t\t\t\tXSLTResultTarget\ttheResultTarget(outputfile);\n\n\t\t\t\t\t\/\/ Set the stylesheet to be the compiled stylesheet. Then do the transform.\n\t\t\t\t\tconst double startTime = clock();\n\t\t\t\t\tcout << \"Clock before transforms: \" << startTime << endl;\n\t\t\t\t\tfor(int j = 0; j < iterCount; ++j)\n\t\t\t\t\t{\t\n\t\t\t\t\t\tcsProcessor.setStylesheetRoot(glbStylesheetRoot[ii]);\n\t\t\t\t\t\tcsProcessor.process(csSourceXML, theResultTarget,psExecutionContext);\n\t\t\t\t\t\tpsExecutionContext.reset();\n\t\t\t\t\t}\n\t\t\t\t\tconst double endTime = clock();\n\t\t\t\t\tcout << \"Clock after transforms: \" << endTime << endl;\n\t\t\t\t\tcout << \"Total clock ticks: \" << endTime - startTime << endl;\n\t\t\t\t\tconst double\tmillis = ((endTime - startTime) \/ CLOCKS_PER_SEC) * 1000.0;\n\t\t\t\t\tcout << \"Milliseconds: \" << millis << endl;\n\t\t\t\t\tcout << \"Averaged: \" << millis \/ iterCount << \" per iteration\" << endl;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t}\n\n\t\t\tXMLPlatformUtils::Terminate();\n\t\t}\n\t\tcatch(...)\n\t\t{\n\t\t\tcerr << \"Exception caught!!!\"\n\t\t\t\t << endl\n\t\t\t\t << endl;\n\t\t}\n\t}\n\n\treturn 0;\n}\n<|endoftext|>"} {"text":"<commit_before>#ifndef VIENNAGRID_ALGORITHM_SPANNED_VOLUME_HPP\n#define VIENNAGRID_ALGORITHM_SPANNED_VOLUME_HPP\n\n\/* =======================================================================\n Copyright (c) 2011-2012, Institute for Microelectronics,\n Institute for Analysis and Scientific Computing,\n TU Wien.\n\n -----------------\n ViennaGrid - The Vienna Grid Library\n -----------------\n\n Authors: Karl Rupp rupp@iue.tuwien.ac.at\n Josef Weinbub weinbub@iue.tuwien.ac.at\n \n (A list of additional contributors can be found in the PDF manual)\n\n License: MIT (X11), see file LICENSE in the base directory\n======================================================================= *\/\n\n\n\n\/\/#include <math.h>\n#include \"viennagrid\/forwards.h\"\n#include \"viennagrid\/algorithm\/cross_prod.hpp\"\n#include \"viennagrid\/algorithm\/norm.hpp\"\n#include \"viennagrid\/algorithm\/inner_prod.hpp\"\n#include \"viennagrid\/traits\/point.hpp\"\n\n\n\/** @file spanned_volume.hpp\n @brief Computes the volume of n-simplices spanned by points\n*\/\n\nnamespace viennagrid\n{\n\n namespace detail\n {\n template <typename PointType, long dim = traits::dimension<PointType>::value>\n struct signed_spanned_volume_impl;\n \n \n \/** @brief Implementation of the volume spanned by two points in one dimension *\/\n template <typename PointType>\n struct signed_spanned_volume_impl<PointType, 1>\n {\n typedef typename traits::value_type<PointType>::type value_type;\n\n static value_type apply(PointType const & p1,\n PointType const & p2)\n {\n return p2[0] - p1[0];\n }\n };\n\n \/\/in 2d:\n \/** @brief Implementation of the volume of simplices spanned by points in two geometrical dimension *\/\n template <typename PointType>\n struct signed_spanned_volume_impl<PointType, 2>\n {\n typedef typename traits::value_type<PointType>::type value_type;\n \n static value_type apply(PointType const & p1,\n PointType const & p2)\n {\n \/\/a line\n return sqrt( (p2[0] - p1[0]) * (p2[0] - p1[0])\n + (p2[1] - p1[1]) * (p2[1] - p1[1]) );\n }\n \n static value_type apply(PointType const & A,\n PointType const & B,\n PointType const & C)\n {\n \/\/a triangle:\n return ( A[0] * (B[1] - C[1])\n + B[0] * (C[1] - A[1])\n + C[0] * (A[1] - B[1]) ) \/ 2.0;\n }\n \n };\n \n\n \/** @brief Implementation of the volume of simplices spanned by points in three geometrical dimension *\/\n template <typename PointType>\n struct signed_spanned_volume_impl<PointType, 3>\n {\n typedef typename traits::value_type<PointType>::type value_type;\n \n static value_type apply(PointType const & p1,\n PointType const & p2)\n {\n \/\/a line\n return sqrt( (p2[0] - p1[0]) * (p2[0] - p1[0])\n + (p2[1] - p1[1]) * (p2[1] - p1[1])\n + (p2[2] - p1[2]) * (p2[2] - p1[2]) );\n }\n \n static value_type apply(PointType const & p1,\n PointType const & p2,\n PointType const & p3)\n {\n PointType v1 = p2 - p1;\n PointType v2 = p3 - p1;\n\n PointType v3 = cross_prod(v1, v2);\n \n return norm(v3) \/ 2.0;\n }\n\n static value_type apply(PointType const & p1,\n PointType const & p2,\n PointType const & p3,\n PointType const & p4)\n {\n PointType v1 = p2 - p1;\n PointType v2 = p3 - p1;\n PointType v3 = p4 - p1;\n \n return (inner_prod(v1, cross_prod(v2, v3)) ) \/ 6.0; \n }\n\n };\n } \/\/namespace detail \n \n \n \n \n \n \n \/\/\n \/\/ Mixed coordinate systems:\n \/\/\n \/** @brief Dispatch facility for two points with possibly different coordinate systems *\/\n template<typename PointType1, typename PointType2, typename CSystem1, typename CSystem2>\n typename traits::value_type<PointType1>::type\n signed_spanned_volume_impl(PointType1 const & p1,\n PointType2 const & p2,\n CSystem1 const &,\n CSystem2 const &)\n {\n typedef typename traits::value_type<PointType1>::type value_type;\n typedef typename result_of::cartesian_point<PointType1>::type CartesianPoint1;\n \n return detail::signed_spanned_volume_impl<CartesianPoint1>::apply(to_cartesian(p1), to_cartesian(p2));\n }\n\n \/** @brief Dispatch facility for three points with possibly different coordinate systems *\/\n template<typename PointType1, typename PointType2, typename PointType3,\n typename CSystem1, typename CSystem2, typename CSystem3>\n typename traits::value_type<PointType1>::type\n signed_spanned_volume_impl(PointType1 const & p1,\n PointType2 const & p2,\n PointType3 const & p3,\n CSystem1 const &,\n CSystem2 const &,\n CSystem3 const &)\n {\n typedef typename traits::value_type<PointType1>::type value_type;\n typedef typename result_of::cartesian_point<PointType1>::type CartesianPoint1;\n \n return detail::signed_spanned_volume_impl<CartesianPoint1>::apply(to_cartesian(p1), to_cartesian(p2), to_cartesian(p3));\n }\n\n \/** @brief Dispatch facility for four points with possibly different coordinate systems *\/\n template<typename PointType1, typename PointType2, typename PointType3, typename PointType4,\n typename CSystem1, typename CSystem2, typename CSystem3, typename CSystem4>\n typename traits::value_type<PointType1>::type\n signed_spanned_volume_impl(PointType1 const & p1,\n PointType2 const & p2,\n PointType3 const & p3,\n PointType4 const & p4,\n CSystem1 const &,\n CSystem2 const &,\n CSystem3 const &,\n CSystem4 const &)\n {\n typedef typename traits::value_type<PointType1>::type value_type;\n typedef typename result_of::cartesian_point<PointType1>::type CartesianPoint1;\n \n return detail::signed_spanned_volume_impl<CartesianPoint1>::apply(to_cartesian(p1), to_cartesian(p2), to_cartesian(p3), to_cartesian(p4));\n }\n\n \/\/\n \/\/ All Cartesian:\n \/\/\n \/** @brief Dispatch facility for two points in Cartesian coordinates *\/\n template<typename PointType1, typename PointType2, long d>\n typename traits::value_type<PointType1>::type\n signed_spanned_volume_impl(PointType1 const & p1,\n PointType2 const & p2,\n cartesian_cs<d>,\n cartesian_cs<d>)\n {\n return detail::signed_spanned_volume_impl<PointType1>::apply(p1, p2);\n }\n\n \/** @brief Dispatch facility for three points in Cartesian coordinates *\/\n template <typename PointType1, typename PointType2, typename PointType3, long d>\n typename traits::value_type<PointType1>::type\n signed_spanned_volume_impl(PointType1 const & p1,\n PointType2 const & p2,\n PointType3 const & p3,\n cartesian_cs<d>,\n cartesian_cs<d>,\n cartesian_cs<d>)\n {\n return detail::signed_spanned_volume_impl<PointType1>::apply(p1, p2, p3);\n }\n\n \/** @brief Dispatch facility for four points in Cartesian coordinates *\/\n template <typename PointType1, typename PointType2, typename PointType3, typename PointType4, long d>\n typename traits::value_type<PointType1>::type\n signed_spanned_volume_impl(PointType1 const & p1,\n PointType2 const & p2,\n PointType3 const & p3,\n PointType4 const & p4,\n cartesian_cs<d>,\n cartesian_cs<d>,\n cartesian_cs<d>,\n cartesian_cs<d>)\n {\n return detail::signed_spanned_volume_impl<PointType1>::apply(p1, p2, p3, p4);\n }\n\n \n\n \/\/\n \/\/ public interface\n \/\/\n \/** @brief Returns the volume of the 1-simplex (line) spanned by the two points *\/\n template <typename PointType1, typename PointType2>\n typename traits::value_type<PointType1>::type \n signed_spanned_volume(PointType1 const & p1, PointType2 const & p2)\n {\n return signed_spanned_volume_impl(p1,\n p2,\n typename traits::coordinate_system<PointType1>::type(),\n typename traits::coordinate_system<PointType2>::type()); \n }\n \n \n \/** @brief Returns the two-dimensional volume of the 2-simplex (triangle) spanned by the three points *\/\n template <typename PointType1, typename PointType2, typename PointType3>\n typename traits::value_type<PointType1>::type \n signed_spanned_volume(PointType1 const & p1, PointType2 const & p2, PointType3 const & p3)\n {\n return signed_spanned_volume_impl(p1,\n p2,\n p3,\n typename traits::coordinate_system<PointType1>::type(),\n typename traits::coordinate_system<PointType2>::type(),\n typename traits::coordinate_system<PointType3>::type()\n );\n \n }\n \n \n \/** @brief Returns the three-dimensional volume of the 3-simplex (tetrahedron) spanned by the four points *\/\n template <typename PointType1, typename PointType2, typename PointType3, typename PointType4>\n typename traits::value_type<PointType1>::type \n signed_spanned_volume(PointType1 const & p1,\n PointType2 const & p2,\n PointType3 const & p3,\n PointType4 const & p4)\n {\n return signed_signed_spanned_volume_impl(p1,\n p2,\n p3,\n p4,\n typename traits::coordinate_system<PointType1>::type(),\n typename traits::coordinate_system<PointType2>::type(),\n typename traits::coordinate_system<PointType3>::type(),\n typename traits::coordinate_system<PointType4>::type()\n );\n }\n \n \n \/** @brief Returns the volume of the 1-simplex (line) spanned by the two points *\/\n template <typename PointType1, typename PointType2>\n typename traits::value_type<PointType1>::type \n spanned_volume(PointType1 const & p1, PointType2 const & p2)\n {\n return std::abs(signed_spanned_volume(p1, p2));\n }\n \n \n \/** @brief Returns the two-dimensional volume of the 2-simplex (triangle) spanned by the three points *\/\n template <typename PointType1, typename PointType2, typename PointType3>\n typename traits::value_type<PointType1>::type \n spanned_volume(PointType1 const & p1, PointType2 const & p2, PointType3 const & p3)\n {\n return std::abs(signed_spanned_volume(p1, p2, p3));\n }\n \n \n \/** @brief Returns the three-dimensional volume of the 3-simplex (tetrahedron) spanned by the four points *\/\n template <typename PointType1, typename PointType2, typename PointType3, typename PointType4>\n typename traits::value_type<PointType1>::type \n spanned_volume(PointType1 const & p1,\n PointType2 const & p2,\n PointType3 const & p3,\n PointType4 const & p4)\n {\n return std::abs(signed_spanned_volume(p1, p2, p3, p4));\n }\n\n}\n#endif\n<commit_msg>fixed typo<commit_after>#ifndef VIENNAGRID_ALGORITHM_SPANNED_VOLUME_HPP\n#define VIENNAGRID_ALGORITHM_SPANNED_VOLUME_HPP\n\n\/* =======================================================================\n Copyright (c) 2011-2012, Institute for Microelectronics,\n Institute for Analysis and Scientific Computing,\n TU Wien.\n\n -----------------\n ViennaGrid - The Vienna Grid Library\n -----------------\n\n Authors: Karl Rupp rupp@iue.tuwien.ac.at\n Josef Weinbub weinbub@iue.tuwien.ac.at\n \n (A list of additional contributors can be found in the PDF manual)\n\n License: MIT (X11), see file LICENSE in the base directory\n======================================================================= *\/\n\n\n\n\/\/#include <math.h>\n#include \"viennagrid\/forwards.h\"\n#include \"viennagrid\/algorithm\/cross_prod.hpp\"\n#include \"viennagrid\/algorithm\/norm.hpp\"\n#include \"viennagrid\/algorithm\/inner_prod.hpp\"\n#include \"viennagrid\/traits\/point.hpp\"\n\n\n\/** @file spanned_volume.hpp\n @brief Computes the volume of n-simplices spanned by points\n*\/\n\nnamespace viennagrid\n{\n\n namespace detail\n {\n template <typename PointType, long dim = traits::dimension<PointType>::value>\n struct signed_spanned_volume_impl;\n \n \n \/** @brief Implementation of the volume spanned by two points in one dimension *\/\n template <typename PointType>\n struct signed_spanned_volume_impl<PointType, 1>\n {\n typedef typename traits::value_type<PointType>::type value_type;\n\n static value_type apply(PointType const & p1,\n PointType const & p2)\n {\n return p2[0] - p1[0];\n }\n };\n\n \/\/in 2d:\n \/** @brief Implementation of the volume of simplices spanned by points in two geometrical dimension *\/\n template <typename PointType>\n struct signed_spanned_volume_impl<PointType, 2>\n {\n typedef typename traits::value_type<PointType>::type value_type;\n \n static value_type apply(PointType const & p1,\n PointType const & p2)\n {\n \/\/a line\n return sqrt( (p2[0] - p1[0]) * (p2[0] - p1[0])\n + (p2[1] - p1[1]) * (p2[1] - p1[1]) );\n }\n \n static value_type apply(PointType const & A,\n PointType const & B,\n PointType const & C)\n {\n \/\/a triangle:\n return ( A[0] * (B[1] - C[1])\n + B[0] * (C[1] - A[1])\n + C[0] * (A[1] - B[1]) ) \/ 2.0;\n }\n \n };\n \n\n \/** @brief Implementation of the volume of simplices spanned by points in three geometrical dimension *\/\n template <typename PointType>\n struct signed_spanned_volume_impl<PointType, 3>\n {\n typedef typename traits::value_type<PointType>::type value_type;\n \n static value_type apply(PointType const & p1,\n PointType const & p2)\n {\n \/\/a line\n return sqrt( (p2[0] - p1[0]) * (p2[0] - p1[0])\n + (p2[1] - p1[1]) * (p2[1] - p1[1])\n + (p2[2] - p1[2]) * (p2[2] - p1[2]) );\n }\n \n static value_type apply(PointType const & p1,\n PointType const & p2,\n PointType const & p3)\n {\n PointType v1 = p2 - p1;\n PointType v2 = p3 - p1;\n\n PointType v3 = cross_prod(v1, v2);\n \n return norm(v3) \/ 2.0;\n }\n\n static value_type apply(PointType const & p1,\n PointType const & p2,\n PointType const & p3,\n PointType const & p4)\n {\n PointType v1 = p2 - p1;\n PointType v2 = p3 - p1;\n PointType v3 = p4 - p1;\n \n return (inner_prod(v1, cross_prod(v2, v3)) ) \/ 6.0; \n }\n\n };\n } \/\/namespace detail \n \n \n \n \n \n \n \/\/\n \/\/ Mixed coordinate systems:\n \/\/\n \/** @brief Dispatch facility for two points with possibly different coordinate systems *\/\n template<typename PointType1, typename PointType2, typename CSystem1, typename CSystem2>\n typename traits::value_type<PointType1>::type\n signed_spanned_volume_impl(PointType1 const & p1,\n PointType2 const & p2,\n CSystem1 const &,\n CSystem2 const &)\n {\n typedef typename traits::value_type<PointType1>::type value_type;\n typedef typename result_of::cartesian_point<PointType1>::type CartesianPoint1;\n \n return detail::signed_spanned_volume_impl<CartesianPoint1>::apply(to_cartesian(p1), to_cartesian(p2));\n }\n\n \/** @brief Dispatch facility for three points with possibly different coordinate systems *\/\n template<typename PointType1, typename PointType2, typename PointType3,\n typename CSystem1, typename CSystem2, typename CSystem3>\n typename traits::value_type<PointType1>::type\n signed_spanned_volume_impl(PointType1 const & p1,\n PointType2 const & p2,\n PointType3 const & p3,\n CSystem1 const &,\n CSystem2 const &,\n CSystem3 const &)\n {\n typedef typename traits::value_type<PointType1>::type value_type;\n typedef typename result_of::cartesian_point<PointType1>::type CartesianPoint1;\n \n return detail::signed_spanned_volume_impl<CartesianPoint1>::apply(to_cartesian(p1), to_cartesian(p2), to_cartesian(p3));\n }\n\n \/** @brief Dispatch facility for four points with possibly different coordinate systems *\/\n template<typename PointType1, typename PointType2, typename PointType3, typename PointType4,\n typename CSystem1, typename CSystem2, typename CSystem3, typename CSystem4>\n typename traits::value_type<PointType1>::type\n signed_spanned_volume_impl(PointType1 const & p1,\n PointType2 const & p2,\n PointType3 const & p3,\n PointType4 const & p4,\n CSystem1 const &,\n CSystem2 const &,\n CSystem3 const &,\n CSystem4 const &)\n {\n typedef typename traits::value_type<PointType1>::type value_type;\n typedef typename result_of::cartesian_point<PointType1>::type CartesianPoint1;\n \n return detail::signed_spanned_volume_impl<CartesianPoint1>::apply(to_cartesian(p1), to_cartesian(p2), to_cartesian(p3), to_cartesian(p4));\n }\n\n \/\/\n \/\/ All Cartesian:\n \/\/\n \/** @brief Dispatch facility for two points in Cartesian coordinates *\/\n template<typename PointType1, typename PointType2, long d>\n typename traits::value_type<PointType1>::type\n signed_spanned_volume_impl(PointType1 const & p1,\n PointType2 const & p2,\n cartesian_cs<d>,\n cartesian_cs<d>)\n {\n return detail::signed_spanned_volume_impl<PointType1>::apply(p1, p2);\n }\n\n \/** @brief Dispatch facility for three points in Cartesian coordinates *\/\n template <typename PointType1, typename PointType2, typename PointType3, long d>\n typename traits::value_type<PointType1>::type\n signed_spanned_volume_impl(PointType1 const & p1,\n PointType2 const & p2,\n PointType3 const & p3,\n cartesian_cs<d>,\n cartesian_cs<d>,\n cartesian_cs<d>)\n {\n return detail::signed_spanned_volume_impl<PointType1>::apply(p1, p2, p3);\n }\n\n \/** @brief Dispatch facility for four points in Cartesian coordinates *\/\n template <typename PointType1, typename PointType2, typename PointType3, typename PointType4, long d>\n typename traits::value_type<PointType1>::type\n signed_spanned_volume_impl(PointType1 const & p1,\n PointType2 const & p2,\n PointType3 const & p3,\n PointType4 const & p4,\n cartesian_cs<d>,\n cartesian_cs<d>,\n cartesian_cs<d>,\n cartesian_cs<d>)\n {\n return detail::signed_spanned_volume_impl<PointType1>::apply(p1, p2, p3, p4);\n }\n\n \n\n \/\/\n \/\/ public interface\n \/\/\n \/** @brief Returns the volume of the 1-simplex (line) spanned by the two points *\/\n template <typename PointType1, typename PointType2>\n typename traits::value_type<PointType1>::type \n signed_spanned_volume(PointType1 const & p1, PointType2 const & p2)\n {\n return signed_spanned_volume_impl(p1,\n p2,\n typename traits::coordinate_system<PointType1>::type(),\n typename traits::coordinate_system<PointType2>::type()); \n }\n \n \n \/** @brief Returns the two-dimensional volume of the 2-simplex (triangle) spanned by the three points *\/\n template <typename PointType1, typename PointType2, typename PointType3>\n typename traits::value_type<PointType1>::type \n signed_spanned_volume(PointType1 const & p1, PointType2 const & p2, PointType3 const & p3)\n {\n return signed_spanned_volume_impl(p1,\n p2,\n p3,\n typename traits::coordinate_system<PointType1>::type(),\n typename traits::coordinate_system<PointType2>::type(),\n typename traits::coordinate_system<PointType3>::type()\n );\n \n }\n \n \n \/** @brief Returns the three-dimensional volume of the 3-simplex (tetrahedron) spanned by the four points *\/\n template <typename PointType1, typename PointType2, typename PointType3, typename PointType4>\n typename traits::value_type<PointType1>::type \n signed_spanned_volume(PointType1 const & p1,\n PointType2 const & p2,\n PointType3 const & p3,\n PointType4 const & p4)\n {\n return signed_spanned_volume_impl(p1,\n p2,\n p3,\n p4,\n typename traits::coordinate_system<PointType1>::type(),\n typename traits::coordinate_system<PointType2>::type(),\n typename traits::coordinate_system<PointType3>::type(),\n typename traits::coordinate_system<PointType4>::type()\n );\n }\n \n \n \/** @brief Returns the volume of the 1-simplex (line) spanned by the two points *\/\n template <typename PointType1, typename PointType2>\n typename traits::value_type<PointType1>::type \n spanned_volume(PointType1 const & p1, PointType2 const & p2)\n {\n return std::abs(signed_spanned_volume(p1, p2));\n }\n \n \n \/** @brief Returns the two-dimensional volume of the 2-simplex (triangle) spanned by the three points *\/\n template <typename PointType1, typename PointType2, typename PointType3>\n typename traits::value_type<PointType1>::type \n spanned_volume(PointType1 const & p1, PointType2 const & p2, PointType3 const & p3)\n {\n return std::abs(signed_spanned_volume(p1, p2, p3));\n }\n \n \n \/** @brief Returns the three-dimensional volume of the 3-simplex (tetrahedron) spanned by the four points *\/\n template <typename PointType1, typename PointType2, typename PointType3, typename PointType4>\n typename traits::value_type<PointType1>::type \n spanned_volume(PointType1 const & p1,\n PointType2 const & p2,\n PointType3 const & p3,\n PointType4 const & p4)\n {\n return std::abs(signed_spanned_volume(p1, p2, p3, p4));\n }\n\n}\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/******************************************************************************\n * Copyright 2017 The Apollo Authors. All Rights Reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *****************************************************************************\/\n\n#include <fstream>\n#include <iomanip>\n#include \"modules\/localization\/msf\/common\/io\/velodyne_utility.h\"\n#include \"modules\/localization\/msf\/local_tool\/map_creation\/poses_interpolation\/poses_interpolation.h\"\n\nnamespace apollo {\nnamespace localization {\nnamespace msf {\nPosesInterpolation::PosesInterpolation() {}\n\nbool PosesInterpolation::Init(const std::string &input_poses_path,\n const std::string &ref_timestamps_path,\n const std::string &out_poses_path,\n const std::string &extrinsic_path) {\n this->input_poses_path_ = input_poses_path;\n this->ref_timestamps_path_ = ref_timestamps_path;\n this->out_poses_path_ = out_poses_path;\n this->extrinsic_path_ = extrinsic_path;\n\n bool success = velodyne::LoadExtrinsic(extrinsic_path_, &velodyne_extrinsic_);\n if (!success) {\n std::cerr << \"Load lidar extrinsic failed.\" << std::endl;\n return false;\n }\n\n return true;\n}\n\nvoid PosesInterpolation::DoInterpolation() {\n \/\/ Load input poses\n std::vector<Eigen::Vector3d> input_stds;\n velodyne::LoadPosesAndStds(input_poses_path_, &input_poses_, &input_stds,\n &input_poses_timestamps_);\n\n \/\/ Load pcd timestamp\n LoadPCDTimestamp();\n\n \/\/ Interpolation\n PoseInterpolationByTime(input_poses_, input_poses_timestamps_,\n ref_timestamps_, ref_ids_, &out_indexes_,\n &out_timestamps_, &out_poses_);\n\n \/\/ Write pcd poses\n WritePCDPoses();\n}\n\nvoid PosesInterpolation::LoadPCDTimestamp() {\n FILE *file = fopen(ref_timestamps_path_.c_str(), \"r\");\n if (file) {\n unsigned int index;\n double timestamp;\n constexpr int kSize = 2;\n while (fscanf(file, \"%u %lf\\n\", &index, ×tamp) == kSize) {\n ref_timestamps_.push_back(timestamp);\n ref_ids_.push_back(index);\n }\n fclose(file);\n } else {\n std::cerr << \"Can't open file to read: \" << ref_timestamps_path_;\n }\n}\n\nvoid PosesInterpolation::WritePCDPoses() {\n std::ofstream fout;\n fout.open(out_poses_path_.c_str(), std::ofstream::out);\n fout.setf(std::ios::fixed, std::ios::floatfield);\n fout.precision(6);\n\n if (fout.is_open()) {\n for (size_t i = 0; i < out_poses_.size(); i++) {\n double timestamp = out_timestamps_[i];\n\n Eigen::Affine3d pose_tem = out_poses_[i] * velodyne_extrinsic_;\n Eigen::Quaterniond quatd(pose_tem.linear());\n Eigen::Translation3d transd(pose_tem.translation());\n double qx = quatd.x();\n double qy = quatd.y();\n double qz = quatd.z();\n double qr = quatd.w();\n\n fout << out_indexes_[i] << \" \" << timestamp << \" \" << transd.x() << \" \"\n << transd.y() << \" \" << transd.z() << \" \" << qx << \" \" << qy << \" \"\n << qz << \" \" << qr << \"\\n\";\n }\n fout.close();\n } else {\n std::cerr << \"Can't open file to write: \" << out_poses_path_ << std::endl;\n }\n} \/\/ namespace msf\n\nvoid PosesInterpolation::PoseInterpolationByTime(\n const std::vector<Eigen::Affine3d> &in_poses,\n const std::vector<double> &in_timestamps,\n const std::vector<double> &ref_timestamps,\n const std::vector<unsigned int> &ref_indexes,\n std::vector<unsigned int> *out_indexes, std::vector<double> *out_timestamps,\n std::vector<Eigen::Affine3d> *out_poses) {\n out_indexes->clear();\n out_timestamps->clear();\n out_poses->clear();\n\n unsigned int index = 0;\n for (size_t i = 0; i < ref_timestamps.size(); i++) {\n double ref_timestamp = ref_timestamps[i];\n unsigned int ref_index = ref_indexes[i];\n\n while (index < in_timestamps.size() &&\n in_timestamps.at(index) < ref_timestamp) {\n ++index;\n }\n\n if (index < in_timestamps.size()) {\n if (index >= 1) {\n double cur_timestamp = in_timestamps[index];\n double pre_timestamp = in_timestamps[index - 1];\n assert(cur_timestamp != pre_timestamp);\n\n double t =\n (cur_timestamp - ref_timestamp) \/ (cur_timestamp - pre_timestamp);\n assert(t >= 0.0);\n assert(t <= 1.0);\n\n Eigen::Affine3d pre_pose = in_poses[index - 1];\n Eigen::Affine3d cur_pose = in_poses[index];\n Eigen::Quaterniond pre_quatd(pre_pose.linear());\n Eigen::Translation3d pre_transd(pre_pose.translation());\n Eigen::Quaterniond cur_quatd(cur_pose.linear());\n Eigen::Translation3d cur_transd(cur_pose.translation());\n\n Eigen::Quaterniond res_quatd = pre_quatd.slerp(1 - t, cur_quatd);\n\n Eigen::Translation3d re_transd;\n re_transd.x() = pre_transd.x() * t + cur_transd.x() * (1 - t);\n re_transd.y() = pre_transd.y() * t + cur_transd.y() * (1 - t);\n re_transd.z() = pre_transd.z() * t + cur_transd.z() * (1 - t);\n\n out_poses->push_back(re_transd * res_quatd);\n out_indexes->push_back(ref_index);\n out_timestamps->push_back(ref_timestamp);\n }\n } else {\n std::cerr << \"[ERROR] No more poses. Exit now.\" << std::endl;\n break;\n }\n std::cout << \"Frame_id: \" << i << std::endl;\n }\n}\n\n} \/\/ namespace msf\n} \/\/ namespace localization\n} \/\/ namespace apollo\n<commit_msg>Localization: fix order of fstream operation in PoseInterpolation<commit_after>\/******************************************************************************\n * Copyright 2017 The Apollo Authors. All Rights Reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *****************************************************************************\/\n\n#include <fstream>\n#include <iomanip>\n#include \"modules\/localization\/msf\/common\/io\/velodyne_utility.h\"\n#include \"modules\/localization\/msf\/local_tool\/map_creation\/poses_interpolation\/poses_interpolation.h\"\n\nnamespace apollo {\nnamespace localization {\nnamespace msf {\nPosesInterpolation::PosesInterpolation() {}\n\nbool PosesInterpolation::Init(const std::string &input_poses_path,\n const std::string &ref_timestamps_path,\n const std::string &out_poses_path,\n const std::string &extrinsic_path) {\n this->input_poses_path_ = input_poses_path;\n this->ref_timestamps_path_ = ref_timestamps_path;\n this->out_poses_path_ = out_poses_path;\n this->extrinsic_path_ = extrinsic_path;\n\n bool success = velodyne::LoadExtrinsic(extrinsic_path_, &velodyne_extrinsic_);\n if (!success) {\n std::cerr << \"Load lidar extrinsic failed.\" << std::endl;\n return false;\n }\n\n return true;\n}\n\nvoid PosesInterpolation::DoInterpolation() {\n \/\/ Load input poses\n std::vector<Eigen::Vector3d> input_stds;\n velodyne::LoadPosesAndStds(input_poses_path_, &input_poses_, &input_stds,\n &input_poses_timestamps_);\n\n \/\/ Load pcd timestamp\n LoadPCDTimestamp();\n\n \/\/ Interpolation\n PoseInterpolationByTime(input_poses_, input_poses_timestamps_,\n ref_timestamps_, ref_ids_, &out_indexes_,\n &out_timestamps_, &out_poses_);\n\n \/\/ Write pcd poses\n WritePCDPoses();\n}\n\nvoid PosesInterpolation::LoadPCDTimestamp() {\n FILE *file = fopen(ref_timestamps_path_.c_str(), \"r\");\n if (file) {\n unsigned int index;\n double timestamp;\n constexpr int kSize = 2;\n while (fscanf(file, \"%u %lf\\n\", &index, ×tamp) == kSize) {\n ref_timestamps_.push_back(timestamp);\n ref_ids_.push_back(index);\n }\n fclose(file);\n } else {\n std::cerr << \"Can't open file to read: \" << ref_timestamps_path_;\n }\n}\n\nvoid PosesInterpolation::WritePCDPoses() {\n std::ofstream fout;\n fout.open(out_poses_path_.c_str(), std::ofstream::out);\n fout.setf(std::ios::fixed, std::ios::floatfield);\n\n if (fout.is_open()) {\n for (size_t i = 0; i < out_poses_.size(); i++) {\n double timestamp = out_timestamps_[i];\n\n Eigen::Affine3d pose_tem = out_poses_[i] * velodyne_extrinsic_;\n Eigen::Quaterniond quatd(pose_tem.linear());\n Eigen::Translation3d transd(pose_tem.translation());\n double qx = quatd.x();\n double qy = quatd.y();\n double qz = quatd.z();\n double qr = quatd.w();\n\n fout.precision(6);\n fout << out_indexes_[i] << \" \" << timestamp << \" \" << transd.x() << \" \"\n << transd.y() << \" \" << transd.z() << \" \" << qx << \" \" << qy << \" \"\n << qz << \" \" << qr << \"\\n\";\n }\n fout.close();\n } else {\n std::cerr << \"Can't open file to write: \" << out_poses_path_ << std::endl;\n }\n} \/\/ namespace msf\n\nvoid PosesInterpolation::PoseInterpolationByTime(\n const std::vector<Eigen::Affine3d> &in_poses,\n const std::vector<double> &in_timestamps,\n const std::vector<double> &ref_timestamps,\n const std::vector<unsigned int> &ref_indexes,\n std::vector<unsigned int> *out_indexes, std::vector<double> *out_timestamps,\n std::vector<Eigen::Affine3d> *out_poses) {\n out_indexes->clear();\n out_timestamps->clear();\n out_poses->clear();\n\n unsigned int index = 0;\n for (size_t i = 0; i < ref_timestamps.size(); i++) {\n double ref_timestamp = ref_timestamps[i];\n unsigned int ref_index = ref_indexes[i];\n\n while (index < in_timestamps.size() &&\n in_timestamps.at(index) < ref_timestamp) {\n ++index;\n }\n\n if (index < in_timestamps.size()) {\n if (index >= 1) {\n double cur_timestamp = in_timestamps[index];\n double pre_timestamp = in_timestamps[index - 1];\n assert(cur_timestamp != pre_timestamp);\n\n double t =\n (cur_timestamp - ref_timestamp) \/ (cur_timestamp - pre_timestamp);\n assert(t >= 0.0);\n assert(t <= 1.0);\n\n Eigen::Affine3d pre_pose = in_poses[index - 1];\n Eigen::Affine3d cur_pose = in_poses[index];\n Eigen::Quaterniond pre_quatd(pre_pose.linear());\n Eigen::Translation3d pre_transd(pre_pose.translation());\n Eigen::Quaterniond cur_quatd(cur_pose.linear());\n Eigen::Translation3d cur_transd(cur_pose.translation());\n\n Eigen::Quaterniond res_quatd = pre_quatd.slerp(1 - t, cur_quatd);\n\n Eigen::Translation3d re_transd;\n re_transd.x() = pre_transd.x() * t + cur_transd.x() * (1 - t);\n re_transd.y() = pre_transd.y() * t + cur_transd.y() * (1 - t);\n re_transd.z() = pre_transd.z() * t + cur_transd.z() * (1 - t);\n\n out_poses->push_back(re_transd * res_quatd);\n out_indexes->push_back(ref_index);\n out_timestamps->push_back(ref_timestamp);\n }\n } else {\n std::cerr << \"[ERROR] No more poses. Exit now.\" << std::endl;\n break;\n }\n std::cout << \"Frame_id: \" << i << std::endl;\n }\n}\n\n} \/\/ namespace msf\n} \/\/ namespace localization\n} \/\/ namespace apollo\n<|endoftext|>"} {"text":"<commit_before><commit_msg>coverity#982157 Unchecked return value<commit_after><|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: component.cxx,v $\n *\n * $Revision: 1.12 $\n *\n * last change: $Author: rt $ $Date: 2005-09-08 09:25:07 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef _RTL_STRING_HXX_\n#include <rtl\/string.hxx>\n#endif\n#ifndef _OSL_DIAGNOSE_H_\n#include <osl\/diagnose.h>\n#endif\n#ifndef _CPPUHELPER_COMPONENT_HXX_\n#include <cppuhelper\/component.hxx>\n#endif\n#ifndef _CPPUHELPER_QUERYINTERFACE_HXX_\n#include <cppuhelper\/queryinterface.hxx>\n#endif\n#ifndef _CPPUHELPER_TYPEPROVIDER_HXX_\n#include <cppuhelper\/typeprovider.hxx>\n#endif\n#include \"com\/sun\/star\/uno\/RuntimeException.hpp\"\n\nusing namespace osl;\nusing namespace rtl;\nusing namespace com::sun::star;\nusing namespace com::sun::star::uno;\nusing namespace com::sun::star::lang;\n\nnamespace cppu\n{\n\n\/\/ ----------------------------------------------------\n\/\/ class OComponentHelper\n\/\/ ----------------------------------------------------\n\nOComponentHelper::OComponentHelper( Mutex & rMutex ) SAL_THROW( () )\n : rBHelper( rMutex )\n{\n}\nOComponentHelper::~OComponentHelper() SAL_THROW( (RuntimeException) )\n{\n}\n\nAny OComponentHelper::queryInterface( Type const & rType ) throw (RuntimeException)\n{\n return OWeakAggObject::queryInterface( rType );\n}\nAny OComponentHelper::queryAggregation( Type const & rType ) throw (RuntimeException)\n{\n if (rType == ::getCppuType( (Reference< lang::XComponent > const *)0 ))\n {\n void * p = static_cast< lang::XComponent * >( this );\n return Any( &p, rType );\n }\n else if (rType == ::getCppuType( (Reference< lang::XTypeProvider > const *)0 ))\n {\n void * p = static_cast< lang::XTypeProvider * >( this );\n return Any( &p, rType );\n }\n return OWeakAggObject::queryAggregation( rType );\n}\nvoid OComponentHelper::acquire() throw ()\n{\n OWeakAggObject::acquire();\n}\n\nvoid OComponentHelper::release() throw()\n{\n Reference<XInterface > x( xDelegator );\n if (! x.is())\n {\n if (osl_decrementInterlockedCount( &m_refCount ) == 0)\n {\n if (! rBHelper.bDisposed)\n {\n Reference<XInterface > xHoldAlive( *this );\n \/\/ First dispose\n try\n {\n dispose();\n }\n catch (::com::sun::star::uno::RuntimeException & exc)\n {\n \/\/ release should not throw exceptions\n#if OSL_DEBUG_LEVEL > 0\n OString msg( OUStringToOString( exc.Message, RTL_TEXTENCODING_ASCII_US ) );\n OSL_ENSURE( 0, msg.getStr() );\n#endif\n }\n\n \/\/ only the alive ref holds the object\n OSL_ASSERT( m_refCount == 1 );\n \/\/ destroy the object if xHoldAlive decrement the refcount to 0\n return;\n }\n }\n \/\/ restore the reference count\n osl_incrementInterlockedCount( &m_refCount );\n }\n OWeakAggObject::release();\n}\n\nSequence< Type > OComponentHelper::getTypes() throw (RuntimeException)\n{\n static OTypeCollection * s_pTypes = 0;\n if (! s_pTypes)\n {\n MutexGuard aGuard( Mutex::getGlobalMutex() );\n if (! s_pTypes)\n {\n static OTypeCollection s_aTypes(\n ::getCppuType( (const Reference< lang::XComponent > *)0 ),\n ::getCppuType( (const Reference< lang::XTypeProvider > *)0 ),\n ::getCppuType( (const Reference< XAggregation > *)0 ),\n ::getCppuType( (const Reference< XWeak > *)0 ) );\n s_pTypes = &s_aTypes;\n }\n }\n return s_pTypes->getTypes();\n}\n\n\/\/ XComponent\nvoid OComponentHelper::disposing()\n{\n}\n\n\/\/ XComponent\nvoid OComponentHelper::dispose()\n throw(::com::sun::star::uno::RuntimeException)\n{\n \/\/ An frequently programming error is to release the last\n \/\/ reference to this object in the disposing message.\n \/\/ Make it rubust, hold a self Reference.\n Reference<XComponent > xSelf( this );\n\n \/\/ Guard dispose against multible threading\n \/\/ Remark: It is an error to call dispose more than once\n sal_Bool bDoDispose = sal_False;\n {\n MutexGuard aGuard( rBHelper.rMutex );\n if( !rBHelper.bDisposed && !rBHelper.bInDispose )\n {\n \/\/ only one call go into this section\n rBHelper.bInDispose = sal_True;\n bDoDispose = sal_True;\n }\n }\n\n \/\/ Do not hold the mutex because we are broadcasting\n if( bDoDispose )\n {\n \/\/ Create an event with this as sender\n try\n {\n try\n {\n Reference<XInterface > xSource(\n Reference<XInterface >::query( (XComponent *)this ) );\n EventObject aEvt;\n aEvt.Source = xSource;\n \/\/ inform all listeners to release this object\n \/\/ The listener container are automaticly cleared\n rBHelper.aLC.disposeAndClear( aEvt );\n \/\/ notify subclasses to do their dispose\n disposing();\n }\n catch (...)\n {\n MutexGuard aGuard( rBHelper.rMutex );\n \/\/ bDispose and bInDisposing must be set in this order:\n rBHelper.bDisposed = sal_True;\n rBHelper.bInDispose = sal_False;\n throw;\n }\n MutexGuard aGuard( rBHelper.rMutex );\n \/\/ bDispose and bInDisposing must be set in this order:\n rBHelper.bDisposed = sal_True;\n rBHelper.bInDispose = sal_False;\n }\n catch (RuntimeException &)\n {\n throw;\n }\n catch (Exception & exc)\n {\n throw RuntimeException(\n OUString( RTL_CONSTASCII_USTRINGPARAM(\n \"unexpected UNO exception caught: \") ) +\n exc.Message, Reference< XInterface >() );\n }\n }\n else\n {\n \/\/ in a multithreaded environment, it can't be avoided,\n \/\/ that dispose is called twice.\n \/\/ However this condition is traced, because it MAY indicate an error.\n OSL_TRACE( \"OComponentHelper::dispose() - dispose called twice\" );\n }\n}\n\n\/\/ XComponent\nvoid OComponentHelper::addEventListener(\n const Reference<XEventListener > & rxListener )\n throw(::com::sun::star::uno::RuntimeException)\n{\n ClearableMutexGuard aGuard( rBHelper.rMutex );\n if (rBHelper.bDisposed || rBHelper.bInDispose)\n {\n aGuard.clear();\n Reference< XInterface > x( (XComponent *)this, UNO_QUERY );\n rxListener->disposing( EventObject( x ) );\n }\n else\n {\n rBHelper.addListener( ::getCppuType( &rxListener ) , rxListener );\n }\n}\n\n\/\/ XComponent\nvoid OComponentHelper::removeEventListener(\n const Reference<XEventListener > & rxListener )\n throw(::com::sun::star::uno::RuntimeException)\n{\n rBHelper.removeListener( ::getCppuType( &rxListener ) , rxListener );\n}\n\n}\n\n<commit_msg>INTEGRATION: CWS warnings01 (1.12.4); FILE MERGED 2005\/11\/28 16:39:56 sb 1.12.4.1: #i53898# Made code warning-free.<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: component.cxx,v $\n *\n * $Revision: 1.13 $\n *\n * last change: $Author: hr $ $Date: 2006-06-19 10:32:45 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef _RTL_STRING_HXX_\n#include <rtl\/string.hxx>\n#endif\n#ifndef _OSL_DIAGNOSE_H_\n#include <osl\/diagnose.h>\n#endif\n#ifndef _CPPUHELPER_COMPONENT_HXX_\n#include <cppuhelper\/component.hxx>\n#endif\n#ifndef _CPPUHELPER_QUERYINTERFACE_HXX_\n#include <cppuhelper\/queryinterface.hxx>\n#endif\n#ifndef _CPPUHELPER_TYPEPROVIDER_HXX_\n#include <cppuhelper\/typeprovider.hxx>\n#endif\n#include \"com\/sun\/star\/uno\/RuntimeException.hpp\"\n\nusing namespace osl;\nusing namespace rtl;\nusing namespace com::sun::star;\nusing namespace com::sun::star::uno;\nusing namespace com::sun::star::lang;\n\nnamespace cppu\n{\n\n\/\/ ----------------------------------------------------\n\/\/ class OComponentHelper\n\/\/ ----------------------------------------------------\n\nOComponentHelper::OComponentHelper( Mutex & rMutex ) SAL_THROW( () )\n : rBHelper( rMutex )\n{\n}\nOComponentHelper::~OComponentHelper() SAL_THROW( (RuntimeException) )\n{\n}\n\nAny OComponentHelper::queryInterface( Type const & rType ) throw (RuntimeException)\n{\n return OWeakAggObject::queryInterface( rType );\n}\nAny OComponentHelper::queryAggregation( Type const & rType ) throw (RuntimeException)\n{\n if (rType == ::getCppuType( (Reference< lang::XComponent > const *)0 ))\n {\n void * p = static_cast< lang::XComponent * >( this );\n return Any( &p, rType );\n }\n else if (rType == ::getCppuType( (Reference< lang::XTypeProvider > const *)0 ))\n {\n void * p = static_cast< lang::XTypeProvider * >( this );\n return Any( &p, rType );\n }\n return OWeakAggObject::queryAggregation( rType );\n}\nvoid OComponentHelper::acquire() throw ()\n{\n OWeakAggObject::acquire();\n}\n\nvoid OComponentHelper::release() throw()\n{\n Reference<XInterface > x( xDelegator );\n if (! x.is())\n {\n if (osl_decrementInterlockedCount( &m_refCount ) == 0)\n {\n if (! rBHelper.bDisposed)\n {\n Reference<XInterface > xHoldAlive( *this );\n \/\/ First dispose\n try\n {\n dispose();\n }\n catch (::com::sun::star::uno::RuntimeException & exc)\n {\n \/\/ release should not throw exceptions\n#if OSL_DEBUG_LEVEL > 0\n OString msg( OUStringToOString( exc.Message, RTL_TEXTENCODING_ASCII_US ) );\n OSL_ENSURE( 0, msg.getStr() );\n#else\n (void) exc; \/\/ avoid warning about unused variable\n#endif\n }\n\n \/\/ only the alive ref holds the object\n OSL_ASSERT( m_refCount == 1 );\n \/\/ destroy the object if xHoldAlive decrement the refcount to 0\n return;\n }\n }\n \/\/ restore the reference count\n osl_incrementInterlockedCount( &m_refCount );\n }\n OWeakAggObject::release();\n}\n\nSequence< Type > OComponentHelper::getTypes() throw (RuntimeException)\n{\n static OTypeCollection * s_pTypes = 0;\n if (! s_pTypes)\n {\n MutexGuard aGuard( Mutex::getGlobalMutex() );\n if (! s_pTypes)\n {\n static OTypeCollection s_aTypes(\n ::getCppuType( (const Reference< lang::XComponent > *)0 ),\n ::getCppuType( (const Reference< lang::XTypeProvider > *)0 ),\n ::getCppuType( (const Reference< XAggregation > *)0 ),\n ::getCppuType( (const Reference< XWeak > *)0 ) );\n s_pTypes = &s_aTypes;\n }\n }\n return s_pTypes->getTypes();\n}\n\n\/\/ XComponent\nvoid OComponentHelper::disposing()\n{\n}\n\n\/\/ XComponent\nvoid OComponentHelper::dispose()\n throw(::com::sun::star::uno::RuntimeException)\n{\n \/\/ An frequently programming error is to release the last\n \/\/ reference to this object in the disposing message.\n \/\/ Make it rubust, hold a self Reference.\n Reference<XComponent > xSelf( this );\n\n \/\/ Guard dispose against multible threading\n \/\/ Remark: It is an error to call dispose more than once\n sal_Bool bDoDispose = sal_False;\n {\n MutexGuard aGuard( rBHelper.rMutex );\n if( !rBHelper.bDisposed && !rBHelper.bInDispose )\n {\n \/\/ only one call go into this section\n rBHelper.bInDispose = sal_True;\n bDoDispose = sal_True;\n }\n }\n\n \/\/ Do not hold the mutex because we are broadcasting\n if( bDoDispose )\n {\n \/\/ Create an event with this as sender\n try\n {\n try\n {\n Reference<XInterface > xSource(\n Reference<XInterface >::query( (XComponent *)this ) );\n EventObject aEvt;\n aEvt.Source = xSource;\n \/\/ inform all listeners to release this object\n \/\/ The listener container are automaticly cleared\n rBHelper.aLC.disposeAndClear( aEvt );\n \/\/ notify subclasses to do their dispose\n disposing();\n }\n catch (...)\n {\n MutexGuard aGuard( rBHelper.rMutex );\n \/\/ bDispose and bInDisposing must be set in this order:\n rBHelper.bDisposed = sal_True;\n rBHelper.bInDispose = sal_False;\n throw;\n }\n MutexGuard aGuard( rBHelper.rMutex );\n \/\/ bDispose and bInDisposing must be set in this order:\n rBHelper.bDisposed = sal_True;\n rBHelper.bInDispose = sal_False;\n }\n catch (RuntimeException &)\n {\n throw;\n }\n catch (Exception & exc)\n {\n throw RuntimeException(\n OUString( RTL_CONSTASCII_USTRINGPARAM(\n \"unexpected UNO exception caught: \") ) +\n exc.Message, Reference< XInterface >() );\n }\n }\n else\n {\n \/\/ in a multithreaded environment, it can't be avoided,\n \/\/ that dispose is called twice.\n \/\/ However this condition is traced, because it MAY indicate an error.\n OSL_TRACE( \"OComponentHelper::dispose() - dispose called twice\" );\n }\n}\n\n\/\/ XComponent\nvoid OComponentHelper::addEventListener(\n const Reference<XEventListener > & rxListener )\n throw(::com::sun::star::uno::RuntimeException)\n{\n ClearableMutexGuard aGuard( rBHelper.rMutex );\n if (rBHelper.bDisposed || rBHelper.bInDispose)\n {\n aGuard.clear();\n Reference< XInterface > x( (XComponent *)this, UNO_QUERY );\n rxListener->disposing( EventObject( x ) );\n }\n else\n {\n rBHelper.addListener( ::getCppuType( &rxListener ) , rxListener );\n }\n}\n\n\/\/ XComponent\nvoid OComponentHelper::removeEventListener(\n const Reference<XEventListener > & rxListener )\n throw(::com::sun::star::uno::RuntimeException)\n{\n rBHelper.removeListener( ::getCppuType( &rxListener ) , rxListener );\n}\n\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 2017 Cryptonomex, Inc., and contributors.\n *\n * The MIT License\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n *\/\n#pragma once\n\n#include <graphene\/app\/plugin.hpp>\n#include <graphene\/chain\/database.hpp>\n\nnamespace graphene { namespace es_objects {\n using namespace chain;\n \/\/using namespace graphene::db;\n \/\/using boost::multi_index_container;\n \/\/using namespace boost::multi_index;\n\n\/\/\n\/\/ Plugins should #define their SPACE_ID's so plugins with\n\/\/ conflicting SPACE_ID assignments can be compiled into the\n\/\/ same binary (by simply re-assigning some of the conflicting #defined\n\/\/ SPACE_ID's in a build script).\n\/\/\n\/\/ Assignment of SPACE_ID's cannot be done at run-time because\n\/\/ various template automagic depends on them being known at compile\n\/\/ time.\n\/\/\n#ifndef PROPOSAL_SPACE_ID\n#define PROPOSAL_SPACE_ID 6\n#endif\n\nstatic size_t WriteCallback(void *contents, size_t size, size_t nmemb, void *userp)\n{\n ((std::string*)userp)->append((char*)contents, size * nmemb);\n return size * nmemb;\n}\n\nnamespace detail\n{\n class es_objects_plugin_impl;\n}\n\nclass es_objects_plugin : public graphene::app::plugin\n{\n public:\n es_objects_plugin();\n virtual ~es_objects_plugin();\n\n std::string plugin_name()const override;\n std::string plugin_description()const override;\n virtual void plugin_set_program_options(\n boost::program_options::options_description& cli,\n boost::program_options::options_description& cfg) override;\n virtual void plugin_initialize(const boost::program_options::variables_map& options) override;\n virtual void plugin_startup() override;\n\n friend class detail::es_objects_plugin_impl;\n std::unique_ptr<detail::es_objects_plugin_impl> my;\n};\n\nstruct proposal_struct {\n proposal_id_type id;\n time_point_sec expiration_time;\n optional<time_point_sec> review_period_time;\n std::string proposed_transaction;\n};\n\nstruct account_struct {\n account_id_type id;\n time_point_sec membership_expiration_date;\n account_id_type registrar;\n account_id_type referrer;\n account_id_type lifetime_referrer;\n uint16_t network_fee_percentage;\n uint16_t lifetime_referrer_fee_percentage;\n uint16_t referrer_rewards_percentage;\n string name;\n string owner;\n string active;\n account_id_type voting_account;\n};\nstruct asset_struct {\n asset_id_type id;\n std::string symbol;\n account_id_type issuer;\n};\nstruct balance_struct {\n balance_id_type id;\n address owner;\n asset_id_type asset_id;\n share_type amount;\n};\n\n\n} } \/\/graphene::es_objects\n\nFC_REFLECT( graphene::es_objects::proposal_struct, (id)(expiration_time)(review_period_time)(proposed_transaction) )\nFC_REFLECT( graphene::es_objects::account_struct, (id)(membership_expiration_date)(registrar)(referrer)(lifetime_referrer)(network_fee_percentage)(lifetime_referrer_fee_percentage)(referrer_rewards_percentage)(name)(owner)(active)(voting_account) )\nFC_REFLECT( graphene::es_objects::asset_struct, (id)(symbol)(issuer) )\nFC_REFLECT( graphene::es_objects::balance_struct, (id)(owner)(asset_id)(amount) )\n\n\n<commit_msg>remove non needed space_id from plugin<commit_after>\/*\n * Copyright (c) 2017 Cryptonomex, Inc., and contributors.\n *\n * The MIT License\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n *\/\n#pragma once\n\n#include <graphene\/app\/plugin.hpp>\n#include <graphene\/chain\/database.hpp>\n\nnamespace graphene { namespace es_objects {\n\nusing namespace chain;\n\n\nstatic size_t WriteCallback(void *contents, size_t size, size_t nmemb, void *userp)\n{\n ((std::string*)userp)->append((char*)contents, size * nmemb);\n return size * nmemb;\n}\n\nnamespace detail\n{\n class es_objects_plugin_impl;\n}\n\nclass es_objects_plugin : public graphene::app::plugin\n{\n public:\n es_objects_plugin();\n virtual ~es_objects_plugin();\n\n std::string plugin_name()const override;\n std::string plugin_description()const override;\n virtual void plugin_set_program_options(\n boost::program_options::options_description& cli,\n boost::program_options::options_description& cfg) override;\n virtual void plugin_initialize(const boost::program_options::variables_map& options) override;\n virtual void plugin_startup() override;\n\n friend class detail::es_objects_plugin_impl;\n std::unique_ptr<detail::es_objects_plugin_impl> my;\n};\n\nstruct proposal_struct {\n proposal_id_type id;\n time_point_sec expiration_time;\n optional<time_point_sec> review_period_time;\n std::string proposed_transaction;\n};\n\nstruct account_struct {\n account_id_type id;\n time_point_sec membership_expiration_date;\n account_id_type registrar;\n account_id_type referrer;\n account_id_type lifetime_referrer;\n uint16_t network_fee_percentage;\n uint16_t lifetime_referrer_fee_percentage;\n uint16_t referrer_rewards_percentage;\n string name;\n string owner;\n string active;\n account_id_type voting_account;\n};\nstruct asset_struct {\n asset_id_type id;\n std::string symbol;\n account_id_type issuer;\n};\nstruct balance_struct {\n balance_id_type id;\n address owner;\n asset_id_type asset_id;\n share_type amount;\n};\n\n\n} } \/\/graphene::es_objects\n\nFC_REFLECT( graphene::es_objects::proposal_struct, (id)(expiration_time)(review_period_time)(proposed_transaction) )\nFC_REFLECT( graphene::es_objects::account_struct, (id)(membership_expiration_date)(registrar)(referrer)(lifetime_referrer)(network_fee_percentage)(lifetime_referrer_fee_percentage)(referrer_rewards_percentage)(name)(owner)(active)(voting_account) )\nFC_REFLECT( graphene::es_objects::asset_struct, (id)(symbol)(issuer) )\nFC_REFLECT( graphene::es_objects::balance_struct, (id)(owner)(asset_id)(amount) )\n\n\n<|endoftext|>"} {"text":"<commit_before>#ifndef ALEPH_TOPOLOGY_MESH_HH__\n#define ALEPH_TOPOLOGY_MESH_HH__\n\n#include <cassert>\n\n#include <algorithm>\n#include <iterator>\n#include <memory>\n#include <vector>\n\nnamespace aleph\n{\n\nnamespace topology\n{\n\n\/**\n @class Mesh\n @brief Half-edge mesh data structure\n\n This data structure is capable of representing two-dimensional piecewise\n linear manifolds. In order to speed up standard queries, this class uses\n a standard half-edge data structure.\n*\/\n\ntemplate <class Position = float, class Data = float> class Mesh\n{\npublic:\n struct Face;\n struct HalfEdge;\n struct Vertex;\n\n using Index = std::size_t;\n\n using FacePointer = std::shared_ptr<Face>;\n using HalfEdgePointer = std::shared_ptr<HalfEdge>;\n using VertexPointer = std::shared_ptr<Vertex>;\n\n struct HalfEdge\n {\n FacePointer face;\n VertexPointer vertex;\n\n HalfEdgePointer next; \/\/ Next half-edge (counter-clockwise)\n HalfEdgePointer prev; \/\/ Previous half-edge\n HalfEdgePointer pair; \/\/ Opposite half-edge\n\n VertexPointer source() const noexcept\n {\n return pair->vertex;\n }\n\n VertexPointer target() const noexcept\n {\n return vertex;\n }\n };\n\n struct Face\n {\n HalfEdgePointer edge;\n };\n\n struct Vertex\n {\n Position x = Position();\n Position y = Position();\n Position z = Position();\n Data d = Data();\n\n HalfEdgePointer edge;\n };\n\n \/\/ Mesh attributes ---------------------------------------------------\n\n std::size_t vertices() const noexcept\n {\n return _vertices.size();\n }\n\n std::size_t faces() const noexcept\n {\n \/\/ TODO: Not yet implemented\n return 0;\n }\n\n \/\/ Mesh modification -------------------------------------------------\n\n \/** Adds a new vertex to the mesh *\/\n void addVertex( Position x, Position y, Position z, Data d = Data() )\n {\n Vertex v;\n\n v.x = x;\n v.y = y;\n v.z = z;\n v.d = d;\n\n _vertices.push_back( std::make_shared<Vertex>( v ) );\n }\n\n \/**\n Adds a new face to the mesh. This function expects a range of vertex IDs\n that make up the face. The vertices of the face need to sorted correctly\n in order for the orientation to be consistent.\n *\/\n\n template <class InputIterator> void addFace( InputIterator begin, InputIterator end )\n {\n FacePointer face = std::make_shared<Face>();\n\n \/\/ Stores all half-edges created (or found) by this function in the\n \/\/ order in which they belong to the face.\n std::vector<HalfEdgePointer> edges;\n edges.reserve( std::distance( begin, end ) );\n\n for( InputIterator it = begin; it != end; ++it )\n {\n auto curr = it;\n auto next = std::next( it );\n\n if( next == end )\n next = begin;\n\n auto source = _vertices.at( *curr ); \/\/ Edge source vertex\n auto target = _vertices.at( *next ); \/\/ Edge target vertex\n auto edge = getEdge( *curr, *next ); \/\/ Edge\n\n if( !edge )\n {\n edge = std::make_shared<HalfEdge>();\n auto pair = std::make_shared<HalfEdge>();\n\n edge->face = face;\n edge->pair = pair;\n edge->vertex = target;\n pair->vertex = source;\n pair->pair = edge;\n\n if( !source->edge )\n source->edge = edge;\n\n if( !target->edge )\n target->edge = pair;\n }\n else\n {\n assert( !edge->face );\n edge->face = face;\n }\n\n edges.push_back( edge );\n }\n\n \/\/ Set 'next' and 'prev' pointers correctly ------------------------\n \/\/\n \/\/ We first traverse all edges that bound the current face. Here, it\n \/\/ should be possible to traverse the face directly, so we require a\n \/\/ proper pointer in both directions.\n\n for( auto itEdge = edges.begin(); itEdge != edges.end(); ++itEdge )\n {\n auto curr = itEdge;\n auto prev = std::prev( curr );\n auto next = std::next( curr );\n\n if( curr == edges.begin() )\n prev = std::prev( edges.end() );\n\n if( next == edges.end() )\n next = edges.begin();\n\n auto&& edge = *itEdge;\n\n assert( !edge->next );\n assert( !edge->prev );\n\n edge->next = *next;\n edge->prev = *prev;\n }\n }\n\n \/\/ Mesh queries ------------------------------------------------------\n\n std::vector<VertexPointer> getLowerNeighbours( const Vertex& v )\n {\n auto neighbours = this->getNeighbours( v );\n auto d = v.d;\n\n neighbours.erase( std::remove_if( neighbours.begin(), neighbours.end(),\n [&d] ( const VertexPointer& neighbour )\n {\n return neighbour->d >= d;\n } ),\n neighbours.end() );\n\n return neighbours;\n }\n\n std::vector<VertexPointer> getHigherNeighbours( const Vertex& v )\n {\n auto neighbours = this->getNeighbours( v );\n auto d = v.d;\n\n neighbours.erase( std::remove_if( neighbours.begin(), neighbours.end(),\n [&d] ( const VertexPointer& neighbour )\n {\n return neighbour->d <= d;\n } ),\n neighbours.end() );\n\n return neighbours;\n }\n\nprivate:\n\n \/** Gets all vertices that are adjacent to a given vertex *\/\n std::vector<VertexPointer> getNeighbours( const Vertex& v )\n {\n std::vector<VertexPointer> neighbours;\n\n auto edge = v.edge;\n do\n {\n if( edge )\n neighbours.push_back( edge->target );\n else\n break;\n\n edge = edge->pair->next;\n }\n while( edge != v.edge );\n\n return neighbours;\n }\n\n \/** Gets all edges that are incident on a given vertex. *\/\n std::vector<HalfEdgePointer> getEdges( const Vertex& v )\n {\n std::vector<HalfEdgePointer> edges;\n\n auto edge = v.edge;\n do\n {\n if( edge )\n edges.push_back( edge );\n else\n break;\n\n edge = edge->pair->next;\n }\n while( edge != v.edge );\n\n return edges;\n }\n\n \/**\n Check whether a given (directed) edge already exists. If so,\n a pointer to the edge is being returned.\n *\/\n\n HalfEdgePointer getEdge( Index u, Index v )\n {\n auto source = _vertices.at(u); \/\/ Edge source vertex\n auto target = _vertices.at(v); \/\/ Edge target vertex\n auto edges = this->getEdges( *source ); \/\/ Incident edges\n\n auto itEdge = std::find_if( edges.begin(), edges.end(),\n [&source, &target] ( const HalfEdgePointer& edge )\n {\n return edge->source() == source && edge->target() == target;\n } );\n\n if( itEdge != edges.end() )\n return *itEdge;\n else\n return nullptr;\n }\n\n \/**\n Stores all vertex pointers. This is sufficient to store the\n complete mesh.\n *\/\n\n std::vector<VertexPointer> _vertices;\n};\n\n} \/\/ namespace topology\n\n} \/\/ namespace aleph\n\n#endif\n<commit_msg>Ensuring const-correctness of mesh operations<commit_after>#ifndef ALEPH_TOPOLOGY_MESH_HH__\n#define ALEPH_TOPOLOGY_MESH_HH__\n\n#include <cassert>\n\n#include <algorithm>\n#include <iterator>\n#include <memory>\n#include <vector>\n\nnamespace aleph\n{\n\nnamespace topology\n{\n\n\/**\n @class Mesh\n @brief Half-edge mesh data structure\n\n This data structure is capable of representing two-dimensional piecewise\n linear manifolds. In order to speed up standard queries, this class uses\n a standard half-edge data structure.\n*\/\n\ntemplate <class Position = float, class Data = float> class Mesh\n{\npublic:\n struct Face;\n struct HalfEdge;\n struct Vertex;\n\n using Index = std::size_t;\n\n using FacePointer = std::shared_ptr<Face>;\n using HalfEdgePointer = std::shared_ptr<HalfEdge>;\n using VertexPointer = std::shared_ptr<Vertex>;\n\n struct HalfEdge\n {\n FacePointer face;\n VertexPointer vertex;\n\n HalfEdgePointer next; \/\/ Next half-edge (counter-clockwise)\n HalfEdgePointer prev; \/\/ Previous half-edge\n HalfEdgePointer pair; \/\/ Opposite half-edge\n\n VertexPointer source() const noexcept\n {\n return pair->vertex;\n }\n\n VertexPointer target() const noexcept\n {\n return vertex;\n }\n };\n\n struct Face\n {\n HalfEdgePointer edge;\n };\n\n struct Vertex\n {\n Position x = Position();\n Position y = Position();\n Position z = Position();\n Data d = Data();\n\n HalfEdgePointer edge;\n };\n\n \/\/ Mesh attributes ---------------------------------------------------\n\n std::size_t vertices() const noexcept\n {\n return _vertices.size();\n }\n\n std::size_t faces() const noexcept\n {\n \/\/ TODO: Not yet implemented\n return 0;\n }\n\n \/\/ Mesh modification -------------------------------------------------\n\n \/** Adds a new vertex to the mesh *\/\n void addVertex( Position x, Position y, Position z, Data d = Data() )\n {\n Vertex v;\n\n v.x = x;\n v.y = y;\n v.z = z;\n v.d = d;\n\n _vertices.push_back( std::make_shared<Vertex>( v ) );\n }\n\n \/**\n Adds a new face to the mesh. This function expects a range of vertex IDs\n that make up the face. The vertices of the face need to sorted correctly\n in order for the orientation to be consistent.\n *\/\n\n template <class InputIterator> void addFace( InputIterator begin, InputIterator end )\n {\n FacePointer face = std::make_shared<Face>();\n\n \/\/ Stores all half-edges created (or found) by this function in the\n \/\/ order in which they belong to the face.\n std::vector<HalfEdgePointer> edges;\n edges.reserve( std::distance( begin, end ) );\n\n for( InputIterator it = begin; it != end; ++it )\n {\n auto curr = it;\n auto next = std::next( it );\n\n if( next == end )\n next = begin;\n\n auto source = _vertices.at( *curr ); \/\/ Edge source vertex\n auto target = _vertices.at( *next ); \/\/ Edge target vertex\n auto edge = getEdge( *curr, *next ); \/\/ Edge\n\n if( !edge )\n {\n edge = std::make_shared<HalfEdge>();\n auto pair = std::make_shared<HalfEdge>();\n\n edge->face = face;\n edge->pair = pair;\n edge->vertex = target;\n pair->vertex = source;\n pair->pair = edge;\n\n if( !source->edge )\n source->edge = edge;\n\n if( !target->edge )\n target->edge = pair;\n }\n else\n {\n assert( !edge->face );\n edge->face = face;\n }\n\n edges.push_back( edge );\n }\n\n \/\/ Set 'next' and 'prev' pointers correctly ------------------------\n \/\/\n \/\/ We first traverse all edges that bound the current face. Here, it\n \/\/ should be possible to traverse the face directly, so we require a\n \/\/ proper pointer in both directions.\n\n for( auto itEdge = edges.begin(); itEdge != edges.end(); ++itEdge )\n {\n auto curr = itEdge;\n auto prev = std::prev( curr );\n auto next = std::next( curr );\n\n if( curr == edges.begin() )\n prev = std::prev( edges.end() );\n\n if( next == edges.end() )\n next = edges.begin();\n\n auto&& edge = *itEdge;\n\n assert( !edge->next );\n assert( !edge->prev );\n\n edge->next = *next;\n edge->prev = *prev;\n }\n }\n\n \/\/ Mesh queries ------------------------------------------------------\n\n std::vector<VertexPointer> getLowerNeighbours( const Vertex& v ) const noexcept\n {\n auto neighbours = this->getNeighbours( v );\n auto d = v.d;\n\n neighbours.erase( std::remove_if( neighbours.begin(), neighbours.end(),\n [&d] ( const VertexPointer& neighbour )\n {\n return neighbour->d >= d;\n } ),\n neighbours.end() );\n\n return neighbours;\n }\n\n std::vector<VertexPointer> getHigherNeighbours( const Vertex& v ) const noexcept\n {\n auto neighbours = this->getNeighbours( v );\n auto d = v.d;\n\n neighbours.erase( std::remove_if( neighbours.begin(), neighbours.end(),\n [&d] ( const VertexPointer& neighbour )\n {\n return neighbour->d <= d;\n } ),\n neighbours.end() );\n\n return neighbours;\n }\n\n VertexPointer vertex( std::size_t id ) const\n {\n return _vertices.at( id );\n }\n\nprivate:\n\n \/** Gets all vertices that are adjacent to a given vertex *\/\n std::vector<VertexPointer> getNeighbours( const Vertex& v ) const noexcept\n {\n std::vector<VertexPointer> neighbours;\n\n auto edge = v.edge;\n do\n {\n if( edge )\n neighbours.push_back( edge->target() );\n else\n break;\n\n edge = edge->pair->next;\n }\n while( edge != v.edge );\n\n return neighbours;\n }\n\n \/** Gets all edges that are incident on a given vertex. *\/\n std::vector<HalfEdgePointer> getEdges( const Vertex& v ) const noexcept\n {\n std::vector<HalfEdgePointer> edges;\n\n auto edge = v.edge;\n do\n {\n if( edge )\n edges.push_back( edge );\n else\n break;\n\n edge = edge->pair->next;\n }\n while( edge != v.edge );\n\n return edges;\n }\n\n \/**\n Check whether a given (directed) edge already exists. If so,\n a pointer to the edge is being returned.\n *\/\n\n HalfEdgePointer getEdge( Index u, Index v ) const noexcept\n {\n auto source = _vertices.at(u); \/\/ Edge source vertex\n auto target = _vertices.at(v); \/\/ Edge target vertex\n auto edges = this->getEdges( *source ); \/\/ Incident edges\n\n auto itEdge = std::find_if( edges.begin(), edges.end(),\n [&source, &target] ( const HalfEdgePointer& edge )\n {\n return edge->source() == source && edge->target() == target;\n } );\n\n if( itEdge != edges.end() )\n return *itEdge;\n else\n return nullptr;\n }\n\n \/**\n Stores all vertex pointers. This is sufficient to store the\n complete mesh.\n *\/\n\n std::vector<VertexPointer> _vertices;\n};\n\n} \/\/ namespace topology\n\n} \/\/ namespace aleph\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/*=========================================================================\n*\n* Copyright NumFOCUS\n*\n* Licensed under the Apache License, Version 2.0 (the \"License\");\n* you may not use this file except in compliance with the License.\n* You may obtain a copy of the License at\n*\n* http:\/\/www.apache.org\/licenses\/LICENSE-2.0.txt\n*\n* Unless required by applicable law or agreed to in writing, software\n* distributed under the License is distributed on an \"AS IS\" BASIS,\n* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n* See the License for the specific language governing permissions and\n* limitations under the License.\n*\n*=========================================================================*\/\n#ifndef sitkImageConvert_hxx\n#define sitkImageConvert_hxx\n\n#include \"sitkImageConvert.h\"\n#include \"itkHolderCommand.h\"\n\nnamespace itk\n{\n\nnamespace simple\n{\n\n\n\/** \\brief A utility method to help convert between itk image types efficiently.\n *\n *\/\ntemplate< typename TPixelType, unsigned int ImageDimension >\nSITKCommon_HIDDEN\ntypename itk::Image< itk::Vector< TPixelType, ImageDimension >, ImageDimension>::Pointer\nGetImageFromVectorImage( itk::VectorImage< TPixelType, ImageDimension > *img, bool transferOwnership )\n{\n typedef itk::Image< itk::Vector< TPixelType, ImageDimension >, ImageDimension> ImageType;\n typedef itk::VectorImage< TPixelType, ImageDimension > VectorImageType;\n\n \/\/ check number of element compatibility\n if ( img->GetNumberOfComponentsPerPixel() != VectorImageType::ImageDimension )\n {\n sitkExceptionMacro(\"Expected number of elements in vector image to be the same as the dimension!\");\n }\n\n size_t numberOfElements = img->GetBufferedRegion().GetNumberOfPixels();\n typename ImageType::PixelType* buffer = reinterpret_cast<typename ImageType::PixelType*>( img->GetPixelContainer()->GetBufferPointer() );\n\n\n typename ImageType::Pointer out = ImageType::New();\n\n if (img->GetPixelContainer()->GetContainerManageMemory() && transferOwnership )\n {\n out->GetPixelContainer()->SetImportPointer(buffer, numberOfElements, true );\n img->GetPixelContainer()->ContainerManageMemoryOff();\n }\n else\n {\n auto holder = itk::HolderCommand<typename VectorImageType::PixelContainer::Pointer>::New();\n holder->Set( img->GetPixelContainer() );\n\n \/\/ Set the image's pixel container to import the pointer provided.\n out->GetPixelContainer()->SetImportPointer(buffer, numberOfElements, false );\n out->AddObserver( itk::DeleteEvent(), holder);\n }\n\n out->CopyInformation( img );\n out->SetRegions( img->GetBufferedRegion() );\n\n return out;\n\n}\n\n\ntemplate< class TPixelType, unsigned int NImageDimension, unsigned int NLength >\nSITKCommon_HIDDEN\ntypename itk::VectorImage< TPixelType, NImageDimension >::Pointer\nGetVectorImageFromImage( itk::Image< itk::Vector< TPixelType, NLength >, NImageDimension> *img, bool transferOwnership )\n{\n typedef itk::VectorImage< TPixelType, NImageDimension > VectorImageType;\n typedef itk::Image< itk::Vector< TPixelType, NLength >, NImageDimension> ImageType;\n\n size_t numberOfElements = img->GetBufferedRegion().GetNumberOfPixels();\n typename VectorImageType::InternalPixelType* buffer = reinterpret_cast<typename VectorImageType::InternalPixelType*>( img->GetPixelContainer()->GetBufferPointer() );\n\n \/\/ Unlike an image of Vectors a VectorImage's container is a\n \/\/ container of TPixelType, whos size is the image's number of\n \/\/ pixels * number of pixels per component\n numberOfElements *= NImageDimension;\n\n\n typename VectorImageType::Pointer out = VectorImageType::New();\n\n if (img->GetPixelContainer()->GetContainerManageMemory() && transferOwnership)\n {\n out->GetPixelContainer()->SetImportPointer(buffer, numberOfElements, true );\n img->GetPixelContainer()->ContainerManageMemoryOff();\n }\n else\n {\n auto holder = itk::HolderCommand<typename ImageType::PixelContainer::Pointer>::New();\n holder->Set( typename ImageType::PixelContainer::Pointer(img->GetPixelContainer()) );\n\n \/\/ Set the image's pixel container to import the pointer provided.\n out->GetPixelContainer()->SetImportPointer(buffer, numberOfElements, false );\n out->AddObserver( itk::DeleteEvent(), holder);\n\n }\n\n\n out->CopyInformation( img );\n out->SetRegions( img->GetBufferedRegion() );\n\n return out;\n}\n\n\ntemplate< class TPixelType, unsigned int NImageDimension, unsigned int NLength >\nSITKCommon_HIDDEN\ntypename itk::VectorImage< TPixelType, NImageDimension >::Pointer\nGetVectorImageFromImage( itk::Image< itk::CovariantVector< TPixelType, NLength>, NImageDimension> *img, bool transferOwnership )\n{\n typedef itk::VectorImage< TPixelType, NImageDimension > VectorImageType;\n typedef itk::Image< itk::CovariantVector< TPixelType, NLength >, NImageDimension> ImageType;\n\n size_t numberOfElements = img->GetBufferedRegion().GetNumberOfPixels();\n typename VectorImageType::InternalPixelType* buffer = reinterpret_cast<typename VectorImageType::InternalPixelType*>( img->GetPixelContainer()->GetBufferPointer() );\n\n \/\/ Unlike an image of Vectors a VectorImage's container is a\n \/\/ container of TPixelType, whos size is the image's number of\n \/\/ pixels * number of pixels per component\n numberOfElements *= NLength;\n\n\n typename VectorImageType::Pointer out = VectorImageType::New();\n\n if (img->GetPixelContainer()->GetContainerManageMemory() && transferOwnership)\n {\n out->GetPixelContainer()->SetImportPointer(buffer, numberOfElements, true );\n img->GetPixelContainer()->ContainerManageMemoryOff();\n }\n else\n {\n auto holder = itk::HolderCommand<typename ImageType::PixelContainer::Pointer>::New();\n holder->Set( typename ImageType::PixelContainer::Pointer(img->GetPixelContainer()) );\n\n \/\/ Set the image's pixel container to import the pointer provided.\n out->GetPixelContainer()->SetImportPointer(buffer, numberOfElements, false );\n out->AddObserver( itk::DeleteEvent(), holder);\n\n }\n\n\n out->CopyInformation( img );\n out->SetRegions( img->GetBufferedRegion() );\n\n return out;\n}\n\n\n}\n}\n\n#endif \/\/ sitkImageConvert_hxx\n<commit_msg>Fix size buffer size in GetVectorImageFromImage<commit_after>\/*=========================================================================\n*\n* Copyright NumFOCUS\n*\n* Licensed under the Apache License, Version 2.0 (the \"License\");\n* you may not use this file except in compliance with the License.\n* You may obtain a copy of the License at\n*\n* http:\/\/www.apache.org\/licenses\/LICENSE-2.0.txt\n*\n* Unless required by applicable law or agreed to in writing, software\n* distributed under the License is distributed on an \"AS IS\" BASIS,\n* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n* See the License for the specific language governing permissions and\n* limitations under the License.\n*\n*=========================================================================*\/\n#ifndef sitkImageConvert_hxx\n#define sitkImageConvert_hxx\n\n#include \"sitkImageConvert.h\"\n#include \"itkHolderCommand.h\"\n\nnamespace itk\n{\n\nnamespace simple\n{\n\n\n\/** \\brief A utility method to help convert between itk image types efficiently.\n *\n *\/\ntemplate< typename TPixelType, unsigned int ImageDimension >\nSITKCommon_HIDDEN\ntypename itk::Image< itk::Vector< TPixelType, ImageDimension >, ImageDimension>::Pointer\nGetImageFromVectorImage( itk::VectorImage< TPixelType, ImageDimension > *img, bool transferOwnership )\n{\n typedef itk::Image< itk::Vector< TPixelType, ImageDimension >, ImageDimension> ImageType;\n typedef itk::VectorImage< TPixelType, ImageDimension > VectorImageType;\n\n \/\/ check number of element compatibility\n if ( img->GetNumberOfComponentsPerPixel() != VectorImageType::ImageDimension )\n {\n sitkExceptionMacro(\"Expected number of elements in vector image to be the same as the dimension!\");\n }\n\n size_t numberOfElements = img->GetBufferedRegion().GetNumberOfPixels();\n typename ImageType::PixelType* buffer = reinterpret_cast<typename ImageType::PixelType*>( img->GetPixelContainer()->GetBufferPointer() );\n\n\n typename ImageType::Pointer out = ImageType::New();\n\n if (img->GetPixelContainer()->GetContainerManageMemory() && transferOwnership )\n {\n out->GetPixelContainer()->SetImportPointer(buffer, numberOfElements, true );\n img->GetPixelContainer()->ContainerManageMemoryOff();\n }\n else\n {\n auto holder = itk::HolderCommand<typename VectorImageType::PixelContainer::Pointer>::New();\n holder->Set( img->GetPixelContainer() );\n\n \/\/ Set the image's pixel container to import the pointer provided.\n out->GetPixelContainer()->SetImportPointer(buffer, numberOfElements, false );\n out->AddObserver( itk::DeleteEvent(), holder);\n }\n\n out->CopyInformation( img );\n out->SetRegions( img->GetBufferedRegion() );\n\n return out;\n\n}\n\n\ntemplate< class TPixelType, unsigned int NImageDimension, unsigned int NLength >\nSITKCommon_HIDDEN\ntypename itk::VectorImage< TPixelType, NImageDimension >::Pointer\nGetVectorImageFromImage( itk::Image< itk::Vector< TPixelType, NLength >, NImageDimension> *img, bool transferOwnership )\n{\n typedef itk::VectorImage< TPixelType, NImageDimension > VectorImageType;\n typedef itk::Image< itk::Vector< TPixelType, NLength >, NImageDimension> ImageType;\n\n size_t numberOfElements = img->GetBufferedRegion().GetNumberOfPixels();\n typename VectorImageType::InternalPixelType* buffer = reinterpret_cast<typename VectorImageType::InternalPixelType*>( img->GetPixelContainer()->GetBufferPointer() );\n\n \/\/ Unlike an image of Vectors a VectorImage's container is a\n \/\/ container of TPixelType, whos size is the image's number of\n \/\/ pixels * number of pixels per component\n numberOfElements *= NLength;\n\n\n typename VectorImageType::Pointer out = VectorImageType::New();\n\n if (img->GetPixelContainer()->GetContainerManageMemory() && transferOwnership)\n {\n out->GetPixelContainer()->SetImportPointer(buffer, numberOfElements, true );\n img->GetPixelContainer()->ContainerManageMemoryOff();\n }\n else\n {\n auto holder = itk::HolderCommand<typename ImageType::PixelContainer::Pointer>::New();\n holder->Set( typename ImageType::PixelContainer::Pointer(img->GetPixelContainer()) );\n\n \/\/ Set the image's pixel container to import the pointer provided.\n out->GetPixelContainer()->SetImportPointer(buffer, numberOfElements, false );\n out->AddObserver( itk::DeleteEvent(), holder);\n\n }\n\n\n out->CopyInformation( img );\n out->SetRegions( img->GetBufferedRegion() );\n\n assert(out->GetNumberOfComponentsPerPixel() == NLength);\n\n return out;\n}\n\n\ntemplate< class TPixelType, unsigned int NImageDimension, unsigned int NLength >\nSITKCommon_HIDDEN\ntypename itk::VectorImage< TPixelType, NImageDimension >::Pointer\nGetVectorImageFromImage( itk::Image< itk::CovariantVector< TPixelType, NLength>, NImageDimension> *img, bool transferOwnership )\n{\n typedef itk::VectorImage< TPixelType, NImageDimension > VectorImageType;\n typedef itk::Image< itk::CovariantVector< TPixelType, NLength >, NImageDimension> ImageType;\n\n size_t numberOfElements = img->GetBufferedRegion().GetNumberOfPixels();\n typename VectorImageType::InternalPixelType* buffer = reinterpret_cast<typename VectorImageType::InternalPixelType*>( img->GetPixelContainer()->GetBufferPointer() );\n\n \/\/ Unlike an image of Vectors a VectorImage's container is a\n \/\/ container of TPixelType, whos size is the image's number of\n \/\/ pixels * number of pixels per component\n numberOfElements *= NLength;\n\n\n typename VectorImageType::Pointer out = VectorImageType::New();\n\n if (img->GetPixelContainer()->GetContainerManageMemory() && transferOwnership)\n {\n out->GetPixelContainer()->SetImportPointer(buffer, numberOfElements, true );\n img->GetPixelContainer()->ContainerManageMemoryOff();\n }\n else\n {\n auto holder = itk::HolderCommand<typename ImageType::PixelContainer::Pointer>::New();\n holder->Set( typename ImageType::PixelContainer::Pointer(img->GetPixelContainer()) );\n\n \/\/ Set the image's pixel container to import the pointer provided.\n out->GetPixelContainer()->SetImportPointer(buffer, numberOfElements, false );\n out->AddObserver( itk::DeleteEvent(), holder);\n\n }\n\n\n out->CopyInformation( img );\n out->SetRegions( img->GetBufferedRegion() );\n\n assert(out->GetNumberOfComponentsPerPixel() == NLength);\n\n return out;\n}\n\n\n}\n}\n\n#endif \/\/ sitkImageConvert_hxx\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (C) 2018-present ScyllaDB\n *\/\n\n\/*\n * SPDX-License-Identifier: AGPL-3.0-or-later\n *\/\n\n#include <seastar\/util\/defer.hh>\n#include <boost\/range\/adaptor\/map.hpp>\n#include \"view_update_generator.hh\"\n#include \"service\/priority_manager.hh\"\n#include \"utils\/error_injection.hh\"\n#include \"db\/view\/view_updating_consumer.hh\"\n#include \"sstables\/sstables.hh\"\n#include \"readers\/evictable.hh\"\n\nstatic logging::logger vug_logger(\"view_update_generator\");\n\nstatic inline void inject_failure(std::string_view operation) {\n utils::get_local_injector().inject(operation,\n [operation] { throw std::runtime_error(std::string(operation)); });\n}\n\nnamespace db::view {\n\nfuture<> view_update_generator::start() {\n thread_attributes attr;\n attr.sched_group = _db.get_streaming_scheduling_group();\n _started = seastar::async(std::move(attr), [this]() mutable {\n auto drop_sstable_references = defer([&] () noexcept {\n \/\/ Clear sstable references so sstables_manager::stop() doesn't hang.\n vug_logger.info(\"leaving {} unstaged sstables unprocessed\",\n _sstables_to_move.size(), _sstables_with_tables.size());\n _sstables_to_move.clear();\n _sstables_with_tables.clear();\n });\n while (!_as.abort_requested()) {\n if (_sstables_with_tables.empty()) {\n _pending_sstables.wait().get();\n }\n\n \/\/ To ensure we don't race with updates, move the entire content\n \/\/ into a local variable.\n auto sstables_with_tables = std::exchange(_sstables_with_tables, {});\n\n \/\/ If we got here, we will process all tables we know about so far eventually so there\n \/\/ is no starvation\n for (auto table_it = sstables_with_tables.begin(); table_it != sstables_with_tables.end(); table_it = sstables_with_tables.erase(table_it)) {\n auto& [t, sstables] = *table_it;\n schema_ptr s = t->schema();\n\n vug_logger.trace(\"Processing {}.{}: {} sstables\", s->ks_name(), s->cf_name(), sstables.size());\n\n const auto num_sstables = sstables.size();\n\n try {\n \/\/ Exploit the fact that sstables in the staging directory\n \/\/ are usually non-overlapping and use a partitioned set for\n \/\/ the read.\n auto ssts = make_lw_shared<sstables::sstable_set>(sstables::make_partitioned_sstable_set(s, false));\n for (auto& sst : sstables) {\n ssts->insert(sst);\n }\n\n auto permit = _db.obtain_reader_permit(*t, \"view_update_generator\", db::no_timeout).get0();\n auto ms = mutation_source([this, ssts] (\n schema_ptr s,\n reader_permit permit,\n const dht::partition_range& pr,\n const query::partition_slice& ps,\n const io_priority_class& pc,\n tracing::trace_state_ptr ts,\n streamed_mutation::forwarding fwd_ms,\n mutation_reader::forwarding fwd_mr) {\n return ssts->make_range_sstable_reader(s, std::move(permit), pr, ps, pc, std::move(ts), fwd_ms, fwd_mr);\n });\n auto [staging_sstable_reader, staging_sstable_reader_handle] = make_manually_paused_evictable_reader_v2(\n std::move(ms),\n s,\n permit,\n query::full_partition_range,\n s->full_slice(),\n service::get_local_streaming_priority(),\n nullptr,\n ::mutation_reader::forwarding::no);\n\n inject_failure(\"view_update_generator_consume_staging_sstable\");\n auto result = staging_sstable_reader.consume_in_thread(view_updating_consumer(s, std::move(permit), *t, sstables, _as, staging_sstable_reader_handle));\n staging_sstable_reader.close().get();\n if (result == stop_iteration::yes) {\n break;\n }\n } catch (...) {\n vug_logger.warn(\"Processing {} failed for table {}:{}. Will retry...\", s->ks_name(), s->cf_name(), std::current_exception());\n \/\/ Need to add sstables back to the set so we can retry later. By now it may\n \/\/ have had other updates.\n std::move(sstables.begin(), sstables.end(), std::back_inserter(_sstables_with_tables[t]));\n break;\n }\n try {\n inject_failure(\"view_update_generator_collect_consumed_sstables\");\n \/\/ collect all staging sstables to move in a map, grouped by table.\n std::move(sstables.begin(), sstables.end(), std::back_inserter(_sstables_to_move[t]));\n } catch (...) {\n \/\/ Move from staging will be retried upon restart.\n vug_logger.warn(\"Moving {} from staging failed: {}:{}. Ignoring...\", s->ks_name(), s->cf_name(), std::current_exception());\n }\n _registration_sem.signal(num_sstables);\n }\n \/\/ For each table, move the processed staging sstables into the table's base dir.\n for (auto it = _sstables_to_move.begin(); it != _sstables_to_move.end(); ) {\n auto& [t, sstables] = *it;\n try {\n inject_failure(\"view_update_generator_move_staging_sstable\");\n t->move_sstables_from_staging(sstables).get();\n } catch (...) {\n \/\/ Move from staging will be retried upon restart.\n vug_logger.warn(\"Moving some sstable from staging failed: {}. Ignoring...\", std::current_exception());\n }\n it = _sstables_to_move.erase(it);\n }\n }\n });\n return make_ready_future<>();\n}\n\nfuture<> view_update_generator::stop() {\n _as.request_abort();\n _pending_sstables.signal();\n return std::move(_started).then([this] {\n _registration_sem.broken();\n });\n}\n\nbool view_update_generator::should_throttle() const {\n return !_started.available();\n}\n\nfuture<> view_update_generator::register_staging_sstable(sstables::shared_sstable sst, lw_shared_ptr<replica::table> table) {\n if (_as.abort_requested()) {\n return make_ready_future<>();\n }\n inject_failure(\"view_update_generator_registering_staging_sstable\");\n _sstables_with_tables[table].push_back(std::move(sst));\n\n _pending_sstables.signal();\n if (should_throttle()) {\n return _registration_sem.wait(1);\n } else {\n _registration_sem.consume(1);\n return make_ready_future<>();\n }\n}\n\nvoid view_update_generator::setup_metrics() {\n namespace sm = seastar::metrics;\n\n _metrics.add_group(\"view_update_generator\", {\n sm::make_gauge(\"pending_registrations\", sm::description(\"Number of tasks waiting to register staging sstables\"),\n [this] { return _registration_sem.waiters(); }),\n\n sm::make_gauge(\"queued_batches_count\", \n sm::description(\"Number of sets of sstables queued for view update generation\"),\n [this] { return _sstables_with_tables.size(); }),\n\n sm::make_gauge(\"sstables_to_move_count\",\n sm::description(\"Number of sets of sstables which are already processed and wait to be moved from their staging directory\"),\n [this] { return _sstables_to_move.size(); })\n });\n}\n\nvoid view_update_generator::discover_staging_sstables() {\n for (auto& x : _db.get_column_families()) {\n replica::table& t = *(x.second);\n for (auto sstables = t.get_sstables(); sstables::shared_sstable sst : *sstables) {\n if (sst->requires_view_building()) {\n _sstables_with_tables[t.shared_from_this()].push_back(std::move(sst));\n \/\/ we're at early stage here, no need to kick _pending_sstables (the\n \/\/ bulding fiber is not running), neither we can wait on the semaphore\n _registration_sem.consume(1);\n }\n }\n }\n}\n\n}\n<commit_msg>view_update_generator: discover_staging_sstables: get shared table ptr earlier<commit_after>\/*\n * Copyright (C) 2018-present ScyllaDB\n *\/\n\n\/*\n * SPDX-License-Identifier: AGPL-3.0-or-later\n *\/\n\n#include <seastar\/util\/defer.hh>\n#include <boost\/range\/adaptor\/map.hpp>\n#include \"view_update_generator.hh\"\n#include \"service\/priority_manager.hh\"\n#include \"utils\/error_injection.hh\"\n#include \"db\/view\/view_updating_consumer.hh\"\n#include \"sstables\/sstables.hh\"\n#include \"readers\/evictable.hh\"\n\nstatic logging::logger vug_logger(\"view_update_generator\");\n\nstatic inline void inject_failure(std::string_view operation) {\n utils::get_local_injector().inject(operation,\n [operation] { throw std::runtime_error(std::string(operation)); });\n}\n\nnamespace db::view {\n\nfuture<> view_update_generator::start() {\n thread_attributes attr;\n attr.sched_group = _db.get_streaming_scheduling_group();\n _started = seastar::async(std::move(attr), [this]() mutable {\n auto drop_sstable_references = defer([&] () noexcept {\n \/\/ Clear sstable references so sstables_manager::stop() doesn't hang.\n vug_logger.info(\"leaving {} unstaged sstables unprocessed\",\n _sstables_to_move.size(), _sstables_with_tables.size());\n _sstables_to_move.clear();\n _sstables_with_tables.clear();\n });\n while (!_as.abort_requested()) {\n if (_sstables_with_tables.empty()) {\n _pending_sstables.wait().get();\n }\n\n \/\/ To ensure we don't race with updates, move the entire content\n \/\/ into a local variable.\n auto sstables_with_tables = std::exchange(_sstables_with_tables, {});\n\n \/\/ If we got here, we will process all tables we know about so far eventually so there\n \/\/ is no starvation\n for (auto table_it = sstables_with_tables.begin(); table_it != sstables_with_tables.end(); table_it = sstables_with_tables.erase(table_it)) {\n auto& [t, sstables] = *table_it;\n schema_ptr s = t->schema();\n\n vug_logger.trace(\"Processing {}.{}: {} sstables\", s->ks_name(), s->cf_name(), sstables.size());\n\n const auto num_sstables = sstables.size();\n\n try {\n \/\/ Exploit the fact that sstables in the staging directory\n \/\/ are usually non-overlapping and use a partitioned set for\n \/\/ the read.\n auto ssts = make_lw_shared<sstables::sstable_set>(sstables::make_partitioned_sstable_set(s, false));\n for (auto& sst : sstables) {\n ssts->insert(sst);\n }\n\n auto permit = _db.obtain_reader_permit(*t, \"view_update_generator\", db::no_timeout).get0();\n auto ms = mutation_source([this, ssts] (\n schema_ptr s,\n reader_permit permit,\n const dht::partition_range& pr,\n const query::partition_slice& ps,\n const io_priority_class& pc,\n tracing::trace_state_ptr ts,\n streamed_mutation::forwarding fwd_ms,\n mutation_reader::forwarding fwd_mr) {\n return ssts->make_range_sstable_reader(s, std::move(permit), pr, ps, pc, std::move(ts), fwd_ms, fwd_mr);\n });\n auto [staging_sstable_reader, staging_sstable_reader_handle] = make_manually_paused_evictable_reader_v2(\n std::move(ms),\n s,\n permit,\n query::full_partition_range,\n s->full_slice(),\n service::get_local_streaming_priority(),\n nullptr,\n ::mutation_reader::forwarding::no);\n\n inject_failure(\"view_update_generator_consume_staging_sstable\");\n auto result = staging_sstable_reader.consume_in_thread(view_updating_consumer(s, std::move(permit), *t, sstables, _as, staging_sstable_reader_handle));\n staging_sstable_reader.close().get();\n if (result == stop_iteration::yes) {\n break;\n }\n } catch (...) {\n vug_logger.warn(\"Processing {} failed for table {}:{}. Will retry...\", s->ks_name(), s->cf_name(), std::current_exception());\n \/\/ Need to add sstables back to the set so we can retry later. By now it may\n \/\/ have had other updates.\n std::move(sstables.begin(), sstables.end(), std::back_inserter(_sstables_with_tables[t]));\n break;\n }\n try {\n inject_failure(\"view_update_generator_collect_consumed_sstables\");\n \/\/ collect all staging sstables to move in a map, grouped by table.\n std::move(sstables.begin(), sstables.end(), std::back_inserter(_sstables_to_move[t]));\n } catch (...) {\n \/\/ Move from staging will be retried upon restart.\n vug_logger.warn(\"Moving {} from staging failed: {}:{}. Ignoring...\", s->ks_name(), s->cf_name(), std::current_exception());\n }\n _registration_sem.signal(num_sstables);\n }\n \/\/ For each table, move the processed staging sstables into the table's base dir.\n for (auto it = _sstables_to_move.begin(); it != _sstables_to_move.end(); ) {\n auto& [t, sstables] = *it;\n try {\n inject_failure(\"view_update_generator_move_staging_sstable\");\n t->move_sstables_from_staging(sstables).get();\n } catch (...) {\n \/\/ Move from staging will be retried upon restart.\n vug_logger.warn(\"Moving some sstable from staging failed: {}. Ignoring...\", std::current_exception());\n }\n it = _sstables_to_move.erase(it);\n }\n }\n });\n return make_ready_future<>();\n}\n\nfuture<> view_update_generator::stop() {\n _as.request_abort();\n _pending_sstables.signal();\n return std::move(_started).then([this] {\n _registration_sem.broken();\n });\n}\n\nbool view_update_generator::should_throttle() const {\n return !_started.available();\n}\n\nfuture<> view_update_generator::register_staging_sstable(sstables::shared_sstable sst, lw_shared_ptr<replica::table> table) {\n if (_as.abort_requested()) {\n return make_ready_future<>();\n }\n inject_failure(\"view_update_generator_registering_staging_sstable\");\n _sstables_with_tables[table].push_back(std::move(sst));\n\n _pending_sstables.signal();\n if (should_throttle()) {\n return _registration_sem.wait(1);\n } else {\n _registration_sem.consume(1);\n return make_ready_future<>();\n }\n}\n\nvoid view_update_generator::setup_metrics() {\n namespace sm = seastar::metrics;\n\n _metrics.add_group(\"view_update_generator\", {\n sm::make_gauge(\"pending_registrations\", sm::description(\"Number of tasks waiting to register staging sstables\"),\n [this] { return _registration_sem.waiters(); }),\n\n sm::make_gauge(\"queued_batches_count\", \n sm::description(\"Number of sets of sstables queued for view update generation\"),\n [this] { return _sstables_with_tables.size(); }),\n\n sm::make_gauge(\"sstables_to_move_count\",\n sm::description(\"Number of sets of sstables which are already processed and wait to be moved from their staging directory\"),\n [this] { return _sstables_to_move.size(); })\n });\n}\n\nvoid view_update_generator::discover_staging_sstables() {\n for (auto& x : _db.get_column_families()) {\n auto t = x.second->shared_from_this();\n for (auto sstables = t->get_sstables(); sstables::shared_sstable sst : *sstables) {\n if (sst->requires_view_building()) {\n _sstables_with_tables[t].push_back(std::move(sst));\n \/\/ we're at early stage here, no need to kick _pending_sstables (the\n \/\/ bulding fiber is not running), neither we can wait on the semaphore\n _registration_sem.consume(1);\n }\n }\n }\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/---------------------------------------------------------------------------\n\/\/ $Id$\n\/\/ Version: $Name$\n\/\/\n\/\/ Copyright (C) 2005, 2006, 2008, 2009 by the deal.II authors\n\/\/\n\/\/ This file is subject to QPL and may not be distributed\n\/\/ without copyright and license information. Please refer\n\/\/ to the file deal.II\/doc\/license.html for the text and\n\/\/ further information on this license.\n\/\/\n\/\/---------------------------------------------------------------------------\n\n\n#include <base\/index_set.h>\n\n#ifdef DEAL_II_USE_TRILINOS\n# ifdef DEAL_II_COMPILER_SUPPORTS_MPI\n# include <Epetra_MpiComm.h>\n# endif\n# include <Epetra_SerialComm.h>\n# include <Epetra_Map.h>\n#endif\n\nDEAL_II_NAMESPACE_OPEN\n\nvoid\nIndexSet::do_compress () const\n{\n\t\t\t\t \/\/ see if any of the\n\t\t\t\t \/\/ contiguous ranges can be\n\t\t\t\t \/\/ merged. since they are sorted by\n\t\t\t\t \/\/ their first index, determining\n\t\t\t\t \/\/ overlap isn't all that hard\n for (std::vector<Range>::iterator\n\t i = ranges.begin();\n i != ranges.end(); )\n {\n std::vector<Range>::iterator\n\tnext = i;\n ++next;\n\n unsigned int first_index = i->begin;\n unsigned int last_index = i->end;\n\n\t\t\t\t \/\/ see if we can merge any of\n\t\t\t\t \/\/ the following ranges\n bool can_merge = false;\n while (next != ranges.end() &&\n\t (next->begin <= last_index))\n\t{\n\t last_index = std::max (last_index, next->end);\n\t ++next;\n\t can_merge = true;\n\t}\n\n if (can_merge == true)\n\t{\n\t\t\t\t\t \/\/ delete the old ranges\n\t\t\t\t\t \/\/ and insert the new range\n\t\t\t\t\t \/\/ in place of the previous\n\t\t\t\t\t \/\/ one\n\t *i = Range(first_index, last_index);\n\t i = ranges.erase (i+1, next);\n\t}\n else\n\t++i;\n }\n\n\n\t\t\t\t \/\/ now compute indices within set\n unsigned int next_index = 0;\n for (std::vector<Range>::iterator\n\t i = ranges.begin();\n i != ranges.end();\n ++i)\n {\n i->nth_index_in_set = next_index;\n next_index += (i->end - i->begin);\n }\n is_compressed = true;\n\n\t\t\t\t \/\/ check that next_index is\n\t\t\t\t \/\/ correct. needs to be after the\n\t\t\t\t \/\/ previous statement because we\n\t\t\t\t \/\/ otherwise will get into an\n\t\t\t\t \/\/ endless loop\n Assert (next_index == n_elements(), ExcInternalError());\n}\n\n\n\nIndexSet\nIndexSet::operator & (const IndexSet &is) const\n{\n Assert (size() == is.size(),\n\t ExcDimensionMismatch (size(), is.size()));\n\n compress ();\n is.compress ();\n\n std::vector<Range>::const_iterator r1 = ranges.begin(),\n\t\t\t\t r2 = is.ranges.begin();\n IndexSet result (size());\n\n while ((r1 != ranges.end())\n\t &&\n\t (r2 != is.ranges.end()))\n {\n\t\t\t\t \/\/ if r1 and r2 do not overlap\n\t\t\t\t \/\/ at all, then move the\n\t\t\t\t \/\/ pointer that sits to the\n\t\t\t\t \/\/ left of the other up by one\n if (r1->end <= r2->begin)\n\t++r1;\n else if (r2->end <= r1->begin)\n\t++r2;\n else\n\t{\n\t\t\t\t\t \/\/ the ranges must overlap\n\t\t\t\t\t \/\/ somehow\n\t Assert (((r1->begin <= r2->begin) &&\n\t\t (r1->end > r2->begin))\n\t\t ||\n\t\t ((r2->begin <= r1->begin) &&\n\t\t (r2->end > r1->begin)),\n\t\t ExcInternalError());\n\n\t\t\t\t\t \/\/ add the overlapping\n\t\t\t\t\t \/\/ range to the result\n\t result.add_range (std::max (r1->begin,\n\t\t\t\t r2->begin),\n\t\t\t std::min (r1->end,\n\t\t\t\t r2->end));\n\n\t\t\t\t\t \/\/ now move that iterator\n\t\t\t\t\t \/\/ that ends earlier one\n\t\t\t\t\t \/\/ up. note that it has to\n\t\t\t\t\t \/\/ be this one because a\n\t\t\t\t\t \/\/ subsequent range may\n\t\t\t\t\t \/\/ still have a chance of\n\t\t\t\t\t \/\/ overlapping with the\n\t\t\t\t\t \/\/ range that ends later\n\t if (r1->end <= r2->end)\n\t ++r1;\n\t else\n\t ++r2;\n\t}\n }\n\n result.compress ();\n return result;\n}\n\n\n\nIndexSet\nIndexSet::get_view (const unsigned int begin,\n\t\t const unsigned int end) const\n{\n Assert (begin <= end,\n\t ExcMessage (\"End index needs to be larger or equal to begin index!\"));\n Assert (end <= size(),\n\t ExcMessage (\"Given range exceeds index set dimension\"));\n\n IndexSet result (end-begin);\n std::vector<Range>::const_iterator r1 = ranges.begin();\n\n while (r1 != ranges.end())\n {\n if ((r1->end > begin)\n\t &&\n\t (r1->begin < end))\n\t{\n\t result.add_range (std::max(r1->begin, begin)-begin,\n\t\t\t std::min(r1->end, end)-begin);\n\n\t}\n else\n\tif (r1->begin >= end)\n\t break\n\n ++r1;\n }\n\n result.compress();\n return result;\n}\n\n\n\n#ifdef DEAL_II_USE_TRILINOS\n\nEpetra_Map\nIndexSet::make_trilinos_map (const MPI_Comm &communicator,\n\t\t\t const bool overlapping) const\n{\n compress ();\n\n if ((is_contiguous() == true) && (!overlapping))\n return Epetra_Map (size(),\n\t\t n_elements(),\n\t\t 0,\n#ifdef DEAL_II_COMPILER_SUPPORTS_MPI\n\t\t Epetra_MpiComm(communicator));\n#else\n\t\t Epetra_SerialComm());\n#endif\n else\n {\n std::vector<int> indices;\n indices.reserve(n_elements());\n for (std::vector<Range>::iterator\n\t i = ranges.begin();\n\t i != ranges.end();\n\t ++i)\n\tfor (unsigned int j=i->begin; j<i->end; ++j)\n\t indices.push_back (j);\n Assert (indices.size() == n_elements(), ExcInternalError());\n\n return Epetra_Map (-1,\n\t\t\t n_elements(),\n\t\t\t &indices[0],\n\t\t\t 0,\n#ifdef DEAL_II_COMPILER_SUPPORTS_MPI\n\t\t\t Epetra_MpiComm(communicator));\n#else\n\t\t\t Epetra_SerialComm());\n#endif\n }\n}\n\n\n#endif\n\n\nDEAL_II_NAMESPACE_CLOSE\n<commit_msg>Make sure it also compiles :-(<commit_after>\/\/---------------------------------------------------------------------------\n\/\/ $Id$\n\/\/ Version: $Name$\n\/\/\n\/\/ Copyright (C) 2005, 2006, 2008, 2009 by the deal.II authors\n\/\/\n\/\/ This file is subject to QPL and may not be distributed\n\/\/ without copyright and license information. Please refer\n\/\/ to the file deal.II\/doc\/license.html for the text and\n\/\/ further information on this license.\n\/\/\n\/\/---------------------------------------------------------------------------\n\n\n#include <base\/index_set.h>\n\n#ifdef DEAL_II_USE_TRILINOS\n# ifdef DEAL_II_COMPILER_SUPPORTS_MPI\n# include <Epetra_MpiComm.h>\n# endif\n# include <Epetra_SerialComm.h>\n# include <Epetra_Map.h>\n#endif\n\nDEAL_II_NAMESPACE_OPEN\n\nvoid\nIndexSet::do_compress () const\n{\n\t\t\t\t \/\/ see if any of the\n\t\t\t\t \/\/ contiguous ranges can be\n\t\t\t\t \/\/ merged. since they are sorted by\n\t\t\t\t \/\/ their first index, determining\n\t\t\t\t \/\/ overlap isn't all that hard\n for (std::vector<Range>::iterator\n\t i = ranges.begin();\n i != ranges.end(); )\n {\n std::vector<Range>::iterator\n\tnext = i;\n ++next;\n\n unsigned int first_index = i->begin;\n unsigned int last_index = i->end;\n\n\t\t\t\t \/\/ see if we can merge any of\n\t\t\t\t \/\/ the following ranges\n bool can_merge = false;\n while (next != ranges.end() &&\n\t (next->begin <= last_index))\n\t{\n\t last_index = std::max (last_index, next->end);\n\t ++next;\n\t can_merge = true;\n\t}\n\n if (can_merge == true)\n\t{\n\t\t\t\t\t \/\/ delete the old ranges\n\t\t\t\t\t \/\/ and insert the new range\n\t\t\t\t\t \/\/ in place of the previous\n\t\t\t\t\t \/\/ one\n\t *i = Range(first_index, last_index);\n\t i = ranges.erase (i+1, next);\n\t}\n else\n\t++i;\n }\n\n\n\t\t\t\t \/\/ now compute indices within set\n unsigned int next_index = 0;\n for (std::vector<Range>::iterator\n\t i = ranges.begin();\n i != ranges.end();\n ++i)\n {\n i->nth_index_in_set = next_index;\n next_index += (i->end - i->begin);\n }\n is_compressed = true;\n\n\t\t\t\t \/\/ check that next_index is\n\t\t\t\t \/\/ correct. needs to be after the\n\t\t\t\t \/\/ previous statement because we\n\t\t\t\t \/\/ otherwise will get into an\n\t\t\t\t \/\/ endless loop\n Assert (next_index == n_elements(), ExcInternalError());\n}\n\n\n\nIndexSet\nIndexSet::operator & (const IndexSet &is) const\n{\n Assert (size() == is.size(),\n\t ExcDimensionMismatch (size(), is.size()));\n\n compress ();\n is.compress ();\n\n std::vector<Range>::const_iterator r1 = ranges.begin(),\n\t\t\t\t r2 = is.ranges.begin();\n IndexSet result (size());\n\n while ((r1 != ranges.end())\n\t &&\n\t (r2 != is.ranges.end()))\n {\n\t\t\t\t \/\/ if r1 and r2 do not overlap\n\t\t\t\t \/\/ at all, then move the\n\t\t\t\t \/\/ pointer that sits to the\n\t\t\t\t \/\/ left of the other up by one\n if (r1->end <= r2->begin)\n\t++r1;\n else if (r2->end <= r1->begin)\n\t++r2;\n else\n\t{\n\t\t\t\t\t \/\/ the ranges must overlap\n\t\t\t\t\t \/\/ somehow\n\t Assert (((r1->begin <= r2->begin) &&\n\t\t (r1->end > r2->begin))\n\t\t ||\n\t\t ((r2->begin <= r1->begin) &&\n\t\t (r2->end > r1->begin)),\n\t\t ExcInternalError());\n\n\t\t\t\t\t \/\/ add the overlapping\n\t\t\t\t\t \/\/ range to the result\n\t result.add_range (std::max (r1->begin,\n\t\t\t\t r2->begin),\n\t\t\t std::min (r1->end,\n\t\t\t\t r2->end));\n\n\t\t\t\t\t \/\/ now move that iterator\n\t\t\t\t\t \/\/ that ends earlier one\n\t\t\t\t\t \/\/ up. note that it has to\n\t\t\t\t\t \/\/ be this one because a\n\t\t\t\t\t \/\/ subsequent range may\n\t\t\t\t\t \/\/ still have a chance of\n\t\t\t\t\t \/\/ overlapping with the\n\t\t\t\t\t \/\/ range that ends later\n\t if (r1->end <= r2->end)\n\t ++r1;\n\t else\n\t ++r2;\n\t}\n }\n\n result.compress ();\n return result;\n}\n\n\n\nIndexSet\nIndexSet::get_view (const unsigned int begin,\n\t\t const unsigned int end) const\n{\n Assert (begin <= end,\n\t ExcMessage (\"End index needs to be larger or equal to begin index!\"));\n Assert (end <= size(),\n\t ExcMessage (\"Given range exceeds index set dimension\"));\n\n IndexSet result (end-begin);\n std::vector<Range>::const_iterator r1 = ranges.begin();\n\n while (r1 != ranges.end())\n {\n if ((r1->end > begin)\n\t &&\n\t (r1->begin < end))\n\t{\n\t result.add_range (std::max(r1->begin, begin)-begin,\n\t\t\t std::min(r1->end, end)-begin);\n\n\t}\n else\n\tif (r1->begin >= end)\n\t break;\n\n ++r1;\n }\n\n result.compress();\n return result;\n}\n\n\n\n#ifdef DEAL_II_USE_TRILINOS\n\nEpetra_Map\nIndexSet::make_trilinos_map (const MPI_Comm &communicator,\n\t\t\t const bool overlapping) const\n{\n compress ();\n\n if ((is_contiguous() == true) && (!overlapping))\n return Epetra_Map (size(),\n\t\t n_elements(),\n\t\t 0,\n#ifdef DEAL_II_COMPILER_SUPPORTS_MPI\n\t\t Epetra_MpiComm(communicator));\n#else\n\t\t Epetra_SerialComm());\n#endif\n else\n {\n std::vector<int> indices;\n indices.reserve(n_elements());\n for (std::vector<Range>::iterator\n\t i = ranges.begin();\n\t i != ranges.end();\n\t ++i)\n\tfor (unsigned int j=i->begin; j<i->end; ++j)\n\t indices.push_back (j);\n Assert (indices.size() == n_elements(), ExcInternalError());\n\n return Epetra_Map (-1,\n\t\t\t n_elements(),\n\t\t\t &indices[0],\n\t\t\t 0,\n#ifdef DEAL_II_COMPILER_SUPPORTS_MPI\n\t\t\t Epetra_MpiComm(communicator));\n#else\n\t\t\t Epetra_SerialComm());\n#endif\n }\n}\n\n\n#endif\n\n\nDEAL_II_NAMESPACE_CLOSE\n<|endoftext|>"} {"text":"<commit_before>\/*=========================================================================\n\n Program: Visualization Toolkit\n Module: vtkStructuredGridConnectivity.cxx\n\n Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen\n All rights reserved.\n See Copyright.txt or http:\/\/www.kitware.com\/Copyright.htm for details.\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notice for more information.\n\n =========================================================================*\/\n#include \"vtkStructuredGridConnectivity.h\"\n#include \"vtkObjectFactory.h\"\n#include \"vtkMeshProperty.h\"\n#include \"vtkMeshPropertyEncoder.h\"\n#include \"vtkStructuredData.h\"\n#include \"vtkStructuredExtent.h\"\n#include \"vtkIdList.h\"\n#include \"vtkStructuredNeighbor.h\"\n\n#include <set>\n#include <vector>\n#include <algorithm>\n\n#define NO_OVERLAP 0\n#define NODE_OVERLAP 1\n#define EDGE_OVERLAP 2\n\nvtkStandardNewMacro( vtkStructuredGridConnectivity );\n\n\/\/------------------------------------------------------------------------------\nvtkStructuredGridConnectivity::vtkStructuredGridConnectivity()\n{\n this->DataDescription = -1;\n this->NumberOfGrids = 0;\n this->WholeExtent[0] = this->WholeExtent[1] = this->WholeExtent[2] =\n this->WholeExtent[3] = this->WholeExtent[4] = this->WholeExtent[5] = -1;\n this->GridExtents.clear();\n}\n\n\/\/------------------------------------------------------------------------------\nvtkStructuredGridConnectivity::~vtkStructuredGridConnectivity()\n{\n this->GridExtents.clear();\n}\n\n\/\/------------------------------------------------------------------------------\nvoid vtkStructuredGridConnectivity::PrintSelf(std::ostream& os,vtkIndent indent)\n{\n this->Superclass::PrintSelf( os, indent );\n}\n\n\/\/------------------------------------------------------------------------------\nvoid vtkStructuredGridConnectivity::RegisterGrid(const int gridID,int ext[6])\n{\n assert( \"pre: gridID out-of-bounds!\" &&\n (gridID >= 0 && gridID < this->NumberOfGrids) );\n for( int i=0; i < 6; ++i )\n this->GridExtents[ gridID*6+i ] = ext[i];\n}\n\n\/\/------------------------------------------------------------------------------\nvoid vtkStructuredGridConnectivity::GetGridExtent(const int gridID, int ext[6])\n{\n assert( \"pre: gridID out-of-bounds!\" &&\n (gridID >= 0 && gridID < this->NumberOfGrids) );\n for( int i=0; i < 6; ++i )\n ext[i] = this->GridExtents[ gridID*6+i ];\n}\n\n\/\/------------------------------------------------------------------------------\nvoid vtkStructuredGridConnectivity::AcquireDataDescription()\n{\n if( this->DataDescription != -1 )\n return;\n\n int dims[3];\n vtkStructuredExtent::GetDimensions( this->WholeExtent, dims );\n this->DataDescription = vtkStructuredData::GetDataDescription( dims );\n assert( \"pre: Error acquiring data description\" &&\n (this->DataDescription >= 0) );\n}\n\n\/\/------------------------------------------------------------------------------\nvtkIdList* vtkStructuredGridConnectivity::GetNeighbors(\n const int gridID,int *extents )\n{\n assert( \"pre: input extents array is NULL\" && (extents != NULL) );\n\n int N = this->GetNumberOfNeighbors( gridID );\n if( N < 1 ) return NULL;\n\n vtkIdList *neiList = vtkIdList::New();\n neiList->SetNumberOfIds( N );\n\n unsigned int nei=0;\n for( ; nei < this->Neighbors[ gridID ].size(); ++nei )\n {\n vtkIdType neiId = this->Neighbors[ gridID ][ nei ].NeighborID;\n neiList->SetId( nei, neiId );\n for( int i=0; i < 6; ++i )\n extents[ nei*6+i ] = this->Neighbors[ gridID ][ nei ].OverlapExtent[ i ];\n } \/\/ END for all neighbors\n\n assert( \"post: N==neiList.size()\" &&\n (N == neiList->GetNumberOfIds()) );\n return( neiList );\n}\n\n\/\/------------------------------------------------------------------------------\nvoid vtkStructuredGridConnectivity::ComputeNeighbors()\n{\n this->AcquireDataDescription( );\n if( this->DataDescription == VTK_EMPTY ||\n this->DataDescription == VTK_SINGLE_POINT )\n return;\n\n for( int i=0; i < this->NumberOfGrids; ++i )\n {\n for( int j=i+1; j < this->NumberOfGrids; ++j )\n {\n this->EstablishNeighbors(i,j);\n } \/\/ END for all j\n } \/\/ END for all i\n}\n\n\/\/------------------------------------------------------------------------------\nvoid vtkStructuredGridConnectivity::SearchNeighbors(\n const int gridID, const int i, const int j, const int k,\n vtkIdList *neiList )\n{\n assert( \"pre: neiList should not be NULL\" && (neiList != NULL) );\n assert( \"pre: gridID is out-of-bounds\" &&\n ( (gridID >= 0) && (gridID < this->NumberOfGrids) ) );\n\n for( unsigned int nei=0; nei < this->Neighbors[ gridID ].size(); ++nei )\n {\n vtkStructuredNeighbor *myNei = &this->Neighbors[ gridID ][ nei ];\n assert( \"pre: myNei != NULL\" && (myNei != NULL) );\n\n if( this->IsNodeWithinExtent( i, j, k, myNei->OverlapExtent) )\n neiList->InsertNextId( myNei->NeighborID );\n } \/\/ END for all neis\n}\n\n\/\/------------------------------------------------------------------------------\nvoid vtkStructuredGridConnectivity::MarkNodeProperty(\n const int gridID, const int i, const int j, const int k,\n int ext[6], unsigned char &p )\n{\n vtkMeshPropertyEncoder::Reset( p );\n\n if( this->IsNodeInterior( i, j, k, ext ) )\n {\n vtkMeshPropertyEncoder::SetProperty( p,VTKNodeProperties::INTERNAL );\n }\n else\n {\n if( this->IsNodeOnBoundary(i,j,k) )\n {\n vtkMeshPropertyEncoder::SetProperty( p,VTKNodeProperties::BOUNDARY );\n }\n\n \/\/ Figure out if the point is shared and who owns the point\n vtkIdList *neiList = vtkIdList::New();\n this->SearchNeighbors( gridID, i, j, k, neiList );\n\n if( neiList->GetNumberOfIds() > 0 )\n {\n std::cout << \"Mark node as shared!\" << std::endl;\n std::cout.flush();\n\n vtkMeshPropertyEncoder::SetProperty( p, VTKNodeProperties::SHARED );\n\n for( vtkIdType nei=0; nei < neiList->GetNumberOfIds(); ++nei )\n {\n \/\/ If my gridID is not the smallest gridID that shares the point, then\n \/\/ I don't own the point.\n \/\/ The convention is that the grid with the smallest gridID will own the\n \/\/ point and all other grids should IGNORE it when computing statistics etc.\n if( gridID > neiList->GetId( nei ) )\n {\n std::cout << \"Mark node as IGNORE!\\n\";\n std::cout.flush();\n\n vtkMeshPropertyEncoder::SetProperty( p,VTKNodeProperties::IGNORE );\n break;\n }\n } \/\/END for all neis\n } \/\/ END if shared\n neiList->Delete();\n }\n}\n\n\/\/------------------------------------------------------------------------------\nvoid vtkStructuredGridConnectivity::FillMeshPropertyArrays(\n const int gridID, unsigned char *nodesArray, unsigned char *cellsArray )\n{\n assert( \"pre: Nodes array is not NULL\" && (nodesArray != NULL) );\n assert( \"pre: Cell array is not NULL\" && (cellsArray != NULL) );\n\n int GridExtent[6];\n this->GetGridExtent( gridID, GridExtent );\n\n int ijkmin[3];\n ijkmin[0] = GridExtent[0];\n ijkmin[1] = GridExtent[2];\n ijkmin[2] = GridExtent[4];\n\n int dims[3];\n vtkStructuredExtent::GetDimensions( GridExtent, dims );\n\n for( int i=GridExtent[0]; i <= GridExtent[1]; ++i )\n {\n for( int j=GridExtent[2]; j <= GridExtent[3]; ++j )\n {\n for( int k=GridExtent[4]; k <= GridExtent[5]; ++k )\n {\n \/\/ Convert global indices to local indices\n int li = i - ijkmin[0];\n int lj = j - ijkmin[1];\n int lk = k - ijkmin[2];\n\n int idx = vtkStructuredData::ComputePointId( dims, li, lj, lk );\n this->MarkNodeProperty( gridID,i,j,k,GridExtent,nodesArray[idx] );\n } \/\/ END for all k\n } \/\/ END for all j\n } \/\/ END for all i\n}\n\n\/\/------------------------------------------------------------------------------\nbool vtkStructuredGridConnectivity::IsNodeOnBoundary(\n const int i, const int j, const int k )\n{\n \/\/ TODO: Add support for 2-D and 1-D cases\n if( i==this->WholeExtent[0] || i==this->WholeExtent[1] ||\n j==this->WholeExtent[2] || j==this->WholeExtent[3] ||\n k==this->WholeExtent[4] || k==this->WholeExtent[5] )\n return true;\n return false;\n}\n\n\/\/------------------------------------------------------------------------------\nbool vtkStructuredGridConnectivity::IsNodeInterior(\n const int i, const int j, const int k,\n int GridExtent[6] )\n{\n \/\/ TODO: Add support for 2-D and 1-D cases\n if( (GridExtent[0] < i) && (i < GridExtent[1]) &&\n (GridExtent[2] < j) && (j < GridExtent[3]) &&\n (GridExtent[4] < k) && (k < GridExtent[5]) )\n return true;\n return false;\n}\n\n\/\/------------------------------------------------------------------------------\nbool vtkStructuredGridConnectivity::IsNodeWithinExtent(\n const int i, const int j, const int k,\n int GridExtent[6] )\n{\n \/\/ TODO: Add support for 2-D and 1-D cases\n if( (GridExtent[0] <= i) && (i <= GridExtent[1] ) &&\n (GridExtent[2] <= j) && (j <= GridExtent[3] ) &&\n (GridExtent[4] <= k) && (k <= GridExtent[5] ) )\n return true;\n return false;\n}\n\n\/\/------------------------------------------------------------------------------\nvoid vtkStructuredGridConnectivity::EstablishNeighbors(const int i,const int j)\n{\n assert( \"pre: i < j\" && (i < j) );\n\n int iGridExtent[6];\n int jGridExtent[6];\n this->GetGridExtent( i, iGridExtent );\n this->GetGridExtent( j, jGridExtent );\n\n \/\/ A 3-tuple that defines the grid orientation of the form {i,j,k} where\n \/\/ i=0;, j=1, k=2. For example, let's say that we want to define the\n \/\/ orientation to be in the XZ plane, then, orientation array would be\n \/\/ constructed as follows: {0,2 -1}, where -1 indicates a NIL value.\n int orientation[3];\n\n \/\/ A place holder for setting up ndim, which store the dimensionality of\n \/\/ the data.\n int ndim = 3;\n\n switch( this->DataDescription )\n {\n case VTK_X_LINE:\n ndim = 1;\n orientation[0] = 0;\n orientation[1] = -1;\n orientation[2] = -1;\n break;\n case VTK_Y_LINE:\n ndim = 1;\n orientation[0] = 1;\n orientation[1] = -1;\n orientation[2] = -1;\n break;\n case VTK_Z_LINE:\n ndim = 1;\n orientation[0] = 2;\n orientation[1] = -1;\n orientation[2] = -1;\n break;\n case VTK_XY_PLANE:\n ndim = 2;\n orientation[0] = 0;\n orientation[1] = 1;\n orientation[2] = -1;\n break;\n case VTK_YZ_PLANE:\n ndim = 2;\n orientation[0] = 1;\n orientation[1] = 2;\n orientation[2] = -1;\n break;\n case VTK_XZ_PLANE:\n ndim = 2;\n orientation[0] = 0;\n orientation[1] = 2;\n orientation[2] = -1;\n break;\n case VTK_XYZ_GRID:\n ndim = 3;\n orientation[0] = 0;\n orientation[1] = 1;\n orientation[2] = 2;\n break;\n default:\n assert( \"pre: Undefined data-description!\" && false );\n } \/\/ END switch\n\n this->DetectNeighbors( i, j, iGridExtent, jGridExtent, orientation, ndim );\n}\n\n\/\/------------------------------------------------------------------------------\nvoid vtkStructuredGridConnectivity::DetectNeighbors(\n const int i, const int j,\n int ex1[6], int ex2[6], int orientation[3], int ndim )\n{\n std::vector< int > status;\n status.resize( ndim );\n\n int A[2];\n int B[2];\n int overlap[2];\n\n int overlapExtent[6];\n for( int ii=0; ii < 6; ++ii )\n overlapExtent[ ii ] = 0;\n\n\n int dim = 0;\n int idx = 0;\n for( dim=0; dim < ndim; ++dim )\n {\n idx = orientation[dim];\n A[0] = ex1[ idx*2 ];\n A[1] = ex1[ idx*2+1 ];\n B[0] = ex2[ idx*2 ];\n B[1] = ex2[ idx*2+1 ];\n status[ idx ] = this->IntervalOverlap( A, B, overlap );\n if( status[idx] == NO_OVERLAP )\n return; \/* No neighbors *\/\n overlapExtent[ idx*2 ] = overlap[0];\n overlapExtent[ idx*2+1 ] = overlap[1];\n } \/\/ END for all dimensions\n\n this->SetNeighbors( i, j, overlapExtent );\n}\n\n\/\/------------------------------------------------------------------------------\nvoid vtkStructuredGridConnectivity::SetNeighbors(\n const int i, const int j, int overlapExtent[6] )\n{\n vtkStructuredNeighbor Ni2j( j, overlapExtent );\n vtkStructuredNeighbor Nj2i( i, overlapExtent );\n\n this->Neighbors[ i ].push_back( Ni2j );\n this->Neighbors[ j ].push_back( Nj2i );\n\n\/\/ BEGIN DEBUG\n int iGridExtent[6];\n int jGridExtent[6];\n this->GetGridExtent( i, iGridExtent );\n this->GetGridExtent( j, jGridExtent );\n\n std::cout << \"===\\n\";\n this->PrintExtent( iGridExtent );\n this->PrintExtent( jGridExtent );\n std::cout << \"\\n\\n\";\n this->PrintExtent( overlapExtent );\n\/\/ END DEBUG\n\n}\n\n\/\/------------------------------------------------------------------------------\nvoid vtkStructuredGridConnectivity::PrintExtent( int ex[6] )\n{\n for( int i=0; i < 3; ++i )\n std::cout << \" [\" << ex[i*2] << \", \" << ex[i*2+1] << \"] \";\n std::cout << std::endl;\n std::cout.flush();\n}\n\n\/\/------------------------------------------------------------------------------\nint vtkStructuredGridConnectivity::IntervalOverlap(\n int A[2], int B[2], int overlap[2] )\n{\n int rc = NO_OVERLAP;\n\n \/\/ STEP 0: Initialize overlap\n for( int i=0; i < 2; i++ )\n overlap[i] = -1;\n\n \/\/ STEP 1: Allocate internal intersection vector. Note, since the cardinality\n \/\/ of A,B is 2, the intersection vector can be at most of size 2.\n std::vector< int > intersection;\n intersection.resize( 2 );\n\n \/\/ STEP 2: Compute intersection\n std::vector< int >::iterator it;\n it = std::set_intersection( A, A+2, B, B+2, intersection.begin() );\n\n \/\/ STEP 3: Find number of intersections and overlap extent\n int N = static_cast< int >( it-intersection.begin() );\n\n switch( N )\n {\n case 0:\n rc = NO_OVERLAP;\n overlap[ 0 ] = overlap[ 1 ] = -1;\n break;\n case 1:\n rc = NODE_OVERLAP;\n overlap[0] = overlap[1] = intersection[0];\n break;\n case 2:\n rc = EDGE_OVERLAP;\n overlap[0] = intersection[0];\n overlap[1] = intersection[1];\n break;\n default:\n rc = NO_OVERLAP;\n overlap[ 0 ] = overlap[ 1 ] = -1;\n vtkErrorMacro( \"Code should not reach here!\" )\n }\n\n return( rc );\n}\n\n<commit_msg>DEBUG: Remove debug statements<commit_after>\/*=========================================================================\n\n Program: Visualization Toolkit\n Module: vtkStructuredGridConnectivity.cxx\n\n Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen\n All rights reserved.\n See Copyright.txt or http:\/\/www.kitware.com\/Copyright.htm for details.\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notice for more information.\n\n =========================================================================*\/\n#include \"vtkStructuredGridConnectivity.h\"\n#include \"vtkObjectFactory.h\"\n#include \"vtkMeshProperty.h\"\n#include \"vtkMeshPropertyEncoder.h\"\n#include \"vtkStructuredData.h\"\n#include \"vtkStructuredExtent.h\"\n#include \"vtkIdList.h\"\n#include \"vtkStructuredNeighbor.h\"\n\n#include <set>\n#include <vector>\n#include <algorithm>\n\n#define NO_OVERLAP 0\n#define NODE_OVERLAP 1\n#define EDGE_OVERLAP 2\n\nvtkStandardNewMacro( vtkStructuredGridConnectivity );\n\n\/\/------------------------------------------------------------------------------\nvtkStructuredGridConnectivity::vtkStructuredGridConnectivity()\n{\n this->DataDescription = -1;\n this->NumberOfGrids = 0;\n this->WholeExtent[0] = this->WholeExtent[1] = this->WholeExtent[2] =\n this->WholeExtent[3] = this->WholeExtent[4] = this->WholeExtent[5] = -1;\n this->GridExtents.clear();\n}\n\n\/\/------------------------------------------------------------------------------\nvtkStructuredGridConnectivity::~vtkStructuredGridConnectivity()\n{\n this->GridExtents.clear();\n}\n\n\/\/------------------------------------------------------------------------------\nvoid vtkStructuredGridConnectivity::PrintSelf(std::ostream& os,vtkIndent indent)\n{\n this->Superclass::PrintSelf( os, indent );\n}\n\n\/\/------------------------------------------------------------------------------\nvoid vtkStructuredGridConnectivity::RegisterGrid(const int gridID,int ext[6])\n{\n assert( \"pre: gridID out-of-bounds!\" &&\n (gridID >= 0 && gridID < this->NumberOfGrids) );\n for( int i=0; i < 6; ++i )\n this->GridExtents[ gridID*6+i ] = ext[i];\n}\n\n\/\/------------------------------------------------------------------------------\nvoid vtkStructuredGridConnectivity::GetGridExtent(const int gridID, int ext[6])\n{\n assert( \"pre: gridID out-of-bounds!\" &&\n (gridID >= 0 && gridID < this->NumberOfGrids) );\n for( int i=0; i < 6; ++i )\n ext[i] = this->GridExtents[ gridID*6+i ];\n}\n\n\/\/------------------------------------------------------------------------------\nvoid vtkStructuredGridConnectivity::AcquireDataDescription()\n{\n if( this->DataDescription != -1 )\n return;\n\n int dims[3];\n vtkStructuredExtent::GetDimensions( this->WholeExtent, dims );\n this->DataDescription = vtkStructuredData::GetDataDescription( dims );\n assert( \"pre: Error acquiring data description\" &&\n (this->DataDescription >= 0) );\n}\n\n\/\/------------------------------------------------------------------------------\nvtkIdList* vtkStructuredGridConnectivity::GetNeighbors(\n const int gridID,int *extents )\n{\n assert( \"pre: input extents array is NULL\" && (extents != NULL) );\n\n int N = this->GetNumberOfNeighbors( gridID );\n if( N < 1 ) return NULL;\n\n vtkIdList *neiList = vtkIdList::New();\n neiList->SetNumberOfIds( N );\n\n unsigned int nei=0;\n for( ; nei < this->Neighbors[ gridID ].size(); ++nei )\n {\n vtkIdType neiId = this->Neighbors[ gridID ][ nei ].NeighborID;\n neiList->SetId( nei, neiId );\n for( int i=0; i < 6; ++i )\n extents[ nei*6+i ] = this->Neighbors[ gridID ][ nei ].OverlapExtent[ i ];\n } \/\/ END for all neighbors\n\n assert( \"post: N==neiList.size()\" &&\n (N == neiList->GetNumberOfIds()) );\n return( neiList );\n}\n\n\/\/------------------------------------------------------------------------------\nvoid vtkStructuredGridConnectivity::ComputeNeighbors()\n{\n this->AcquireDataDescription( );\n if( this->DataDescription == VTK_EMPTY ||\n this->DataDescription == VTK_SINGLE_POINT )\n return;\n\n for( int i=0; i < this->NumberOfGrids; ++i )\n {\n for( int j=i+1; j < this->NumberOfGrids; ++j )\n {\n this->EstablishNeighbors(i,j);\n } \/\/ END for all j\n } \/\/ END for all i\n}\n\n\/\/------------------------------------------------------------------------------\nvoid vtkStructuredGridConnectivity::SearchNeighbors(\n const int gridID, const int i, const int j, const int k,\n vtkIdList *neiList )\n{\n assert( \"pre: neiList should not be NULL\" && (neiList != NULL) );\n assert( \"pre: gridID is out-of-bounds\" &&\n ( (gridID >= 0) && (gridID < this->NumberOfGrids) ) );\n\n for( unsigned int nei=0; nei < this->Neighbors[ gridID ].size(); ++nei )\n {\n vtkStructuredNeighbor *myNei = &this->Neighbors[ gridID ][ nei ];\n assert( \"pre: myNei != NULL\" && (myNei != NULL) );\n\n if( this->IsNodeWithinExtent( i, j, k, myNei->OverlapExtent) )\n neiList->InsertNextId( myNei->NeighborID );\n } \/\/ END for all neis\n}\n\n\/\/------------------------------------------------------------------------------\nvoid vtkStructuredGridConnectivity::MarkNodeProperty(\n const int gridID, const int i, const int j, const int k,\n int ext[6], unsigned char &p )\n{\n vtkMeshPropertyEncoder::Reset( p );\n\n if( this->IsNodeInterior( i, j, k, ext ) )\n {\n vtkMeshPropertyEncoder::SetProperty( p,VTKNodeProperties::INTERNAL );\n }\n else\n {\n if( this->IsNodeOnBoundary(i,j,k) )\n {\n vtkMeshPropertyEncoder::SetProperty( p,VTKNodeProperties::BOUNDARY );\n }\n\n \/\/ Figure out if the point is shared and who owns the point\n vtkIdList *neiList = vtkIdList::New();\n this->SearchNeighbors( gridID, i, j, k, neiList );\n\n if( neiList->GetNumberOfIds() > 0 )\n {\n vtkMeshPropertyEncoder::SetProperty( p, VTKNodeProperties::SHARED );\n\n for( vtkIdType nei=0; nei < neiList->GetNumberOfIds(); ++nei )\n {\n \/\/ If my gridID is not the smallest gridID that shares the point, then\n \/\/ I don't own the point.\n \/\/ The convention is that the grid with the smallest gridID will own the\n \/\/ point and all other grids should IGNORE it when computing statistics etc.\n if( gridID > neiList->GetId( nei ) )\n {\n vtkMeshPropertyEncoder::SetProperty( p,VTKNodeProperties::IGNORE );\n break;\n }\n } \/\/END for all neis\n } \/\/ END if shared\n neiList->Delete();\n }\n}\n\n\/\/------------------------------------------------------------------------------\nvoid vtkStructuredGridConnectivity::FillMeshPropertyArrays(\n const int gridID, unsigned char *nodesArray, unsigned char *cellsArray )\n{\n assert( \"pre: Nodes array is not NULL\" && (nodesArray != NULL) );\n assert( \"pre: Cell array is not NULL\" && (cellsArray != NULL) );\n\n int GridExtent[6];\n this->GetGridExtent( gridID, GridExtent );\n\n int ijkmin[3];\n ijkmin[0] = GridExtent[0];\n ijkmin[1] = GridExtent[2];\n ijkmin[2] = GridExtent[4];\n\n int dims[3];\n vtkStructuredExtent::GetDimensions( GridExtent, dims );\n\n for( int i=GridExtent[0]; i <= GridExtent[1]; ++i )\n {\n for( int j=GridExtent[2]; j <= GridExtent[3]; ++j )\n {\n for( int k=GridExtent[4]; k <= GridExtent[5]; ++k )\n {\n \/\/ Convert global indices to local indices\n int li = i - ijkmin[0];\n int lj = j - ijkmin[1];\n int lk = k - ijkmin[2];\n\n int idx = vtkStructuredData::ComputePointId( dims, li, lj, lk );\n this->MarkNodeProperty( gridID,i,j,k,GridExtent,nodesArray[idx] );\n } \/\/ END for all k\n } \/\/ END for all j\n } \/\/ END for all i\n}\n\n\/\/------------------------------------------------------------------------------\nbool vtkStructuredGridConnectivity::IsNodeOnBoundary(\n const int i, const int j, const int k )\n{\n \/\/ TODO: Add support for 2-D and 1-D cases\n if( i==this->WholeExtent[0] || i==this->WholeExtent[1] ||\n j==this->WholeExtent[2] || j==this->WholeExtent[3] ||\n k==this->WholeExtent[4] || k==this->WholeExtent[5] )\n return true;\n return false;\n}\n\n\/\/------------------------------------------------------------------------------\nbool vtkStructuredGridConnectivity::IsNodeInterior(\n const int i, const int j, const int k,\n int GridExtent[6] )\n{\n \/\/ TODO: Add support for 2-D and 1-D cases\n if( (GridExtent[0] < i) && (i < GridExtent[1]) &&\n (GridExtent[2] < j) && (j < GridExtent[3]) &&\n (GridExtent[4] < k) && (k < GridExtent[5]) )\n return true;\n return false;\n}\n\n\/\/------------------------------------------------------------------------------\nbool vtkStructuredGridConnectivity::IsNodeWithinExtent(\n const int i, const int j, const int k,\n int GridExtent[6] )\n{\n \/\/ TODO: Add support for 2-D and 1-D cases\n if( (GridExtent[0] <= i) && (i <= GridExtent[1] ) &&\n (GridExtent[2] <= j) && (j <= GridExtent[3] ) &&\n (GridExtent[4] <= k) && (k <= GridExtent[5] ) )\n return true;\n return false;\n}\n\n\/\/------------------------------------------------------------------------------\nvoid vtkStructuredGridConnectivity::EstablishNeighbors(const int i,const int j)\n{\n assert( \"pre: i < j\" && (i < j) );\n\n int iGridExtent[6];\n int jGridExtent[6];\n this->GetGridExtent( i, iGridExtent );\n this->GetGridExtent( j, jGridExtent );\n\n \/\/ A 3-tuple that defines the grid orientation of the form {i,j,k} where\n \/\/ i=0;, j=1, k=2. For example, let's say that we want to define the\n \/\/ orientation to be in the XZ plane, then, orientation array would be\n \/\/ constructed as follows: {0,2 -1}, where -1 indicates a NIL value.\n int orientation[3];\n\n \/\/ A place holder for setting up ndim, which store the dimensionality of\n \/\/ the data.\n int ndim = 3;\n\n switch( this->DataDescription )\n {\n case VTK_X_LINE:\n ndim = 1;\n orientation[0] = 0;\n orientation[1] = -1;\n orientation[2] = -1;\n break;\n case VTK_Y_LINE:\n ndim = 1;\n orientation[0] = 1;\n orientation[1] = -1;\n orientation[2] = -1;\n break;\n case VTK_Z_LINE:\n ndim = 1;\n orientation[0] = 2;\n orientation[1] = -1;\n orientation[2] = -1;\n break;\n case VTK_XY_PLANE:\n ndim = 2;\n orientation[0] = 0;\n orientation[1] = 1;\n orientation[2] = -1;\n break;\n case VTK_YZ_PLANE:\n ndim = 2;\n orientation[0] = 1;\n orientation[1] = 2;\n orientation[2] = -1;\n break;\n case VTK_XZ_PLANE:\n ndim = 2;\n orientation[0] = 0;\n orientation[1] = 2;\n orientation[2] = -1;\n break;\n case VTK_XYZ_GRID:\n ndim = 3;\n orientation[0] = 0;\n orientation[1] = 1;\n orientation[2] = 2;\n break;\n default:\n assert( \"pre: Undefined data-description!\" && false );\n } \/\/ END switch\n\n this->DetectNeighbors( i, j, iGridExtent, jGridExtent, orientation, ndim );\n}\n\n\/\/------------------------------------------------------------------------------\nvoid vtkStructuredGridConnectivity::DetectNeighbors(\n const int i, const int j,\n int ex1[6], int ex2[6], int orientation[3], int ndim )\n{\n std::vector< int > status;\n status.resize( ndim );\n\n int A[2];\n int B[2];\n int overlap[2];\n\n int overlapExtent[6];\n for( int ii=0; ii < 6; ++ii )\n overlapExtent[ ii ] = 0;\n\n\n int dim = 0;\n int idx = 0;\n for( dim=0; dim < ndim; ++dim )\n {\n idx = orientation[dim];\n A[0] = ex1[ idx*2 ];\n A[1] = ex1[ idx*2+1 ];\n B[0] = ex2[ idx*2 ];\n B[1] = ex2[ idx*2+1 ];\n status[ idx ] = this->IntervalOverlap( A, B, overlap );\n if( status[idx] == NO_OVERLAP )\n return; \/* No neighbors *\/\n overlapExtent[ idx*2 ] = overlap[0];\n overlapExtent[ idx*2+1 ] = overlap[1];\n } \/\/ END for all dimensions\n\n this->SetNeighbors( i, j, overlapExtent );\n}\n\n\/\/------------------------------------------------------------------------------\nvoid vtkStructuredGridConnectivity::SetNeighbors(\n const int i, const int j, int overlapExtent[6] )\n{\n vtkStructuredNeighbor Ni2j( j, overlapExtent );\n vtkStructuredNeighbor Nj2i( i, overlapExtent );\n\n this->Neighbors[ i ].push_back( Ni2j );\n this->Neighbors[ j ].push_back( Nj2i );\n\n\/\/ BEGIN DEBUG\n int iGridExtent[6];\n int jGridExtent[6];\n this->GetGridExtent( i, iGridExtent );\n this->GetGridExtent( j, jGridExtent );\n\n std::cout << \"===\\n\";\n this->PrintExtent( iGridExtent );\n this->PrintExtent( jGridExtent );\n std::cout << \"\\n\\n\";\n this->PrintExtent( overlapExtent );\n\/\/ END DEBUG\n\n}\n\n\/\/------------------------------------------------------------------------------\nvoid vtkStructuredGridConnectivity::PrintExtent( int ex[6] )\n{\n for( int i=0; i < 3; ++i )\n std::cout << \" [\" << ex[i*2] << \", \" << ex[i*2+1] << \"] \";\n std::cout << std::endl;\n std::cout.flush();\n}\n\n\/\/------------------------------------------------------------------------------\nint vtkStructuredGridConnectivity::IntervalOverlap(\n int A[2], int B[2], int overlap[2] )\n{\n int rc = NO_OVERLAP;\n\n \/\/ STEP 0: Initialize overlap\n for( int i=0; i < 2; i++ )\n overlap[i] = -1;\n\n \/\/ STEP 1: Allocate internal intersection vector. Note, since the cardinality\n \/\/ of A,B is 2, the intersection vector can be at most of size 2.\n std::vector< int > intersection;\n intersection.resize( 2 );\n\n \/\/ STEP 2: Compute intersection\n std::vector< int >::iterator it;\n it = std::set_intersection( A, A+2, B, B+2, intersection.begin() );\n\n \/\/ STEP 3: Find number of intersections and overlap extent\n int N = static_cast< int >( it-intersection.begin() );\n\n switch( N )\n {\n case 0:\n rc = NO_OVERLAP;\n overlap[ 0 ] = overlap[ 1 ] = -1;\n break;\n case 1:\n rc = NODE_OVERLAP;\n overlap[0] = overlap[1] = intersection[0];\n break;\n case 2:\n rc = EDGE_OVERLAP;\n overlap[0] = intersection[0];\n overlap[1] = intersection[1];\n break;\n default:\n rc = NO_OVERLAP;\n overlap[ 0 ] = overlap[ 1 ] = -1;\n vtkErrorMacro( \"Code should not reach here!\" )\n }\n\n return( rc );\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/\/---------------------------------------------------------------------------\n\/\/ $Id$\n\/\/ Version: $Name$\n\/\/\n\/\/ Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2008, 2009, 2010, 2011 by the deal.II authors\n\/\/\n\/\/ This file is subject to QPL and may not be distributed\n\/\/ without copyright and license information. Please refer\n\/\/ to the file deal.II\/doc\/license.html for the text and\n\/\/ further information on this license.\n\/\/\n\/\/---------------------------------------------------------------------------\n\n\n#include <deal.II\/base\/logstream.h>\n#include <deal.II\/base\/job_identifier.h>\n#include <deal.II\/base\/memory_consumption.h>\n#include <deal.II\/base\/thread_management.h>\n\n\/\/ include sys\/resource.h for rusage(). Mac OS X needs sys\/time.h then\n\/\/ as well (strange), so include that, too.\n#include <sys\/resource.h>\n#include <sys\/types.h>\n#include <unistd.h>\n#include <iostream>\n#include <iomanip>\n#include <fstream>\n#include <sstream>\n\n\n\/\/ on SunOS 4.x, getrusage is stated in the man pages and exists, but\n\/\/ is not declared in resource.h. declare it ourselves\n#ifdef NO_HAVE_GETRUSAGE\nextern \"C\" {\n int getrusage(int who, struct rusage* ru);\n}\n#endif\n\n\/\/ When modifying the prefix list, we need to lock it just in case\n\/\/ another thread tries to do the same.\nDEAL_II_NAMESPACE_OPEN\n\nnamespace\n{\n Threads::ThreadMutex log_lock;\n Threads::ThreadMutex write_lock;\n}\n\n\nLogStream deallog;\n\n\nLogStream::LogStream()\n\t\t:\n\t\tstd_out(&std::cerr), file(0),\n\t\tstd_depth(10000), file_depth(10000),\n\t\tprint_utime(false), diff_utime(false),\n\t\tlast_time (0.), double_threshold(0.), old_cerr(0)\n{\n prefixes.push(\"DEAL:\");\n std_out->setf(std::ios::showpoint | std::ios::left);\n#ifdef HAVE_TIMES\n reference_time_val = 1.\/sysconf(_SC_CLK_TCK) * times(&reference_tms);\n#endif\n}\n\n\nLogStream::~LogStream()\n{\n\t\t\t\t \/\/ if there was anything left in\n\t\t\t\t \/\/ the stream that is current to\n\t\t\t\t \/\/ this thread, make sure we flush\n\t\t\t\t \/\/ it before it gets lost\n {\n const unsigned int id = Threads::this_thread_id();\n if ((outstreams.find(id) != outstreams.end())\n\t&&\n\t(*outstreams[id] != 0)\n\t&&\n\t(outstreams[id]->str().length() > 0))\n *this << std::endl;\n }\n\n if (old_cerr)\n std::cerr.rdbuf(old_cerr);\n\n\t\t\t\t \/\/ on some systems, destroying the\n\t\t\t\t \/\/ outstreams objects of deallog\n\t\t\t\t \/\/ triggers some sort of memory\n\t\t\t\t \/\/ corruption, in particular when\n\t\t\t\t \/\/ we also link with Trilinos;\n\t\t\t\t \/\/ since this happens at the very\n\t\t\t\t \/\/ end of the program, we take the\n\t\t\t\t \/\/ liberty to simply not do it by\n\t\t\t\t \/\/ putting that object into a\n\t\t\t\t \/\/ deliberate memory leak and\n\t\t\t\t \/\/ instead destroying an empty\n\t\t\t\t \/\/ object\n#ifdef DEAL_II_USE_TRILINOS\n if (this == &deallog)\n {\n stream_map_type * dummy = new stream_map_type();\n dummy->swap (outstreams);\n delete dummy;\n }\n#endif\n}\n\n\nLogStream &\nLogStream::operator<< (std::ostream& (*p) (std::ostream&))\n{\n\t\t\t\t \/\/ do the work that is common to\n\t\t\t\t \/\/ the operator<< functions\n print (p);\n\n\t\t\t\t \/\/ next check whether this is the\n\t\t\t\t \/\/ <tt>endl<\/tt> manipulator, and if so\n\t\t\t\t \/\/ set a flag\n std::ostream & (* const p_endl) (std::ostream&) = &std::endl;\n if (p == p_endl)\n {\n Threads::ThreadMutex::ScopedLock lock(write_lock);\n print_line_head();\n std::ostringstream& stream = get_stream();\n if (prefixes.size() <= std_depth)\n\t*std_out << stream.str();\n\n if (file && (prefixes.size() <= file_depth))\n\t*file << stream.str() << std::flush;\n\n\t\t\t\t \/\/ Start a new string\n stream.str(\"\");\n }\n return *this;\n}\n\n\nstd::ostringstream&\nLogStream::get_stream()\n{\n\/\/TODO: use a ThreadLocalStorage object here\n Threads::ThreadMutex::ScopedLock lock(log_lock);\n const unsigned int id = Threads::this_thread_id();\n\n std_cxx1x::shared_ptr<std::ostringstream>& sptr = outstreams[id];\n if (sptr == std_cxx1x::shared_ptr<std::ostringstream>())\n {\n sptr = std_cxx1x::shared_ptr<std::ostringstream> (new std::ostringstream());\n sptr->setf(std::ios::showpoint | std::ios::left);\n }\n return *sptr;\n}\n\n\n\nvoid\nLogStream::attach(std::ostream& o)\n{\n Threads::ThreadMutex::ScopedLock lock(log_lock);\n file = &o;\n o.setf(std::ios::showpoint | std::ios::left);\n o << dealjobid();\n}\n\n\nvoid LogStream::detach ()\n{\n Threads::ThreadMutex::ScopedLock lock(log_lock);\n file = 0;\n}\n\n\nvoid LogStream::log_cerr ()\n{\n Threads::ThreadMutex::ScopedLock lock(log_lock);\n if (old_cerr == 0)\n {\n old_cerr = std::cerr.rdbuf(file->rdbuf());\n } else {\n std::cerr.rdbuf(old_cerr);\n old_cerr = 0;\n }\n}\n\n\nstd::ostream&\nLogStream::get_console()\n{\n return *std_out;\n}\n\n\nstd::ostream&\nLogStream::get_file_stream()\n{\n Assert(file, ExcNoFileStreamGiven());\n return *file;\n}\n\n\nbool\nLogStream::has_file() const\n{\n return (file != 0);\n}\n\n\nconst std::string&\nLogStream::get_prefix() const\n{\n return prefixes.top();\n}\n\n\nvoid\nLogStream::push (const std::string& text)\n{\n Threads::ThreadMutex::ScopedLock lock(log_lock);\n std::string pre=prefixes.top();\n pre += text;\n pre += std::string(\":\");\n prefixes.push(pre);\n}\n\n\nvoid LogStream::pop ()\n{\n Threads::ThreadMutex::ScopedLock lock(log_lock);\n if (prefixes.size() > 1)\n prefixes.pop();\n}\n\n\nunsigned int\nLogStream::depth_console (const unsigned n)\n{\n Threads::ThreadMutex::ScopedLock lock(log_lock);\n const unsigned int h = std_depth;\n std_depth = n;\n return h;\n}\n\n\nunsigned int\nLogStream::depth_file (const unsigned n)\n{\n Threads::ThreadMutex::ScopedLock lock(log_lock);\n const unsigned int h = file_depth;\n file_depth = n;\n return h;\n}\n\n\nvoid\nLogStream::threshold_double (const double t)\n{\n Threads::ThreadMutex::ScopedLock lock(log_lock);\n double_threshold = t;\n}\n\n\nbool\nLogStream::log_execution_time (const bool flag)\n{\n Threads::ThreadMutex::ScopedLock lock(log_lock);\n const bool h = print_utime;\n print_utime = flag;\n return h;\n}\n\n\nbool\nLogStream::log_time_differences (const bool flag)\n{\n Threads::ThreadMutex::ScopedLock lock(log_lock);\n const bool h = diff_utime;\n diff_utime = flag;\n return h;\n}\n\n\nbool\nLogStream::log_thread_id (const bool flag)\n{\n Threads::ThreadMutex::ScopedLock lock(log_lock);\n const bool h = print_thread_id;\n print_thread_id = flag;\n return h;\n}\n\n\nvoid\nLogStream::print_line_head()\n{\n rusage usage;\n double utime = 0.;\n if (print_utime)\n {\n getrusage(RUSAGE_SELF, &usage);\n utime = usage.ru_utime.tv_sec + 1.e-6 * usage.ru_utime.tv_usec;\n if (diff_utime)\n\t{\n\t double diff = utime - last_time;\n\t last_time = utime;\n\t utime = diff;\n\t}\n }\n\n\/*\n * The following lines were used for debugging a memory leak.\n * They work on Linux, not on Solaris, since the \/proc filesystem\n * on Solaris is quite cryptic. For other systems, we don't know.\n *\n * Unfortunately, the information in \/proc\/pid\/stat is updated slowly,\n * therefore, the information is quite unreliable.\n *\n * Furthermore, the constructor of ifstream caused another memory leak.\n *\n * Still, this code might be useful sometimes, so I kept it here.\n * When we have more information about the kernel, this should be\n * incorporated properly. Suggestions are welcome!\n *\/\n\n#ifdef DEALII_MEMORY_DEBUG\n static const pid_t id = getpid();\n\n std::ostringstream statname;\n statname << \"\/proc\/\" << id << \"\/stat\";\n\n static long size;\n static string dummy;\n ifstream stat(statname.str());\n\t\t\t\t \/\/ ignore 22 values\n stat >> dummy >> dummy >> dummy >> dummy >> dummy >> dummy >>\n dummy >> dummy >> dummy >> dummy >> dummy >>\n dummy >> dummy >> dummy >> dummy >> dummy >> dummy >>\n dummy >> dummy >> dummy >> dummy >> dummy >> size;\n#endif\n\n const std::string& head = get_prefix();\n const unsigned int thread = Threads::this_thread_id();\n\n if (prefixes.size() <= std_depth)\n {\n if (print_utime)\n\t{\n\t int p = std_out->width(5);\n\t *std_out << utime << ':';\n#ifdef DEALII_MEMORY_DEBUG\n\t *std_out << size << ':';\n#endif\n\t std_out->width(p);\n\t}\n if (print_thread_id)\n\t*std_out << '[' << thread << ']';\n\n *std_out << head << ':';\n }\n\n if (file && (prefixes.size() <= file_depth))\n {\n if (print_utime)\n\t{\n\t int p = file->width(6);\n\t *file << utime << ':';\n#ifdef DEALII_MEMORY_DEBUG\n\t *file << size << ':';\n#endif\n\t file->width(p);\n\t}\n if (print_thread_id)\n\t*file << '[' << thread << ']';\n\n *file << head << ':';\n }\n}\n\n\nvoid\nLogStream::timestamp ()\n{\n struct tms current_tms;\n#ifdef HAVE_TIMES\n const clock_t tick = sysconf(_SC_CLK_TCK);\n const double time = 1.\/tick * times(¤t_tms);\n#else\n const double time = 0.;\n const unsigned int tick = 100;\n#endif\n (*this) << \"Wall: \" << time - reference_time_val\n\t << \" User: \" << 1.\/tick * (current_tms.tms_utime - reference_tms.tms_utime)\n\t << \" System: \" << 1.\/tick * (current_tms.tms_stime - reference_tms.tms_stime)\n\t << \" Child-User: \" << 1.\/tick * (current_tms.tms_cutime - reference_tms.tms_cutime)\n\t << \" Child-System: \" << 1.\/tick * (current_tms.tms_cstime - reference_tms.tms_cstime)\n\t << std::endl;\n}\n\n\nstd::size_t\nLogStream::memory_consumption () const\n{\n std::size_t mem = sizeof(*this);\n\t\t\t\t \/\/ to determine size of stack\n\t\t\t\t \/\/ elements, we have to copy the\n\t\t\t\t \/\/ stack since we can't access\n\t\t\t\t \/\/ elements from further below\n std::stack<std::string> tmp = prefixes;\n while (tmp.empty() == false)\n {\n mem += MemoryConsumption::memory_consumption (tmp.top());\n tmp.pop ();\n }\n\n return mem;\n}\n\nDEAL_II_NAMESPACE_CLOSE\n<commit_msg>Simplify code slightly.<commit_after>\/\/---------------------------------------------------------------------------\n\/\/ $Id$\n\/\/ Version: $Name$\n\/\/\n\/\/ Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2008, 2009, 2010, 2011 by the deal.II authors\n\/\/\n\/\/ This file is subject to QPL and may not be distributed\n\/\/ without copyright and license information. Please refer\n\/\/ to the file deal.II\/doc\/license.html for the text and\n\/\/ further information on this license.\n\/\/\n\/\/---------------------------------------------------------------------------\n\n\n#include <deal.II\/base\/logstream.h>\n#include <deal.II\/base\/job_identifier.h>\n#include <deal.II\/base\/memory_consumption.h>\n#include <deal.II\/base\/thread_management.h>\n\n\/\/ include sys\/resource.h for rusage(). Mac OS X needs sys\/time.h then\n\/\/ as well (strange), so include that, too.\n#include <sys\/resource.h>\n#include <sys\/types.h>\n#include <unistd.h>\n#include <iostream>\n#include <iomanip>\n#include <fstream>\n#include <sstream>\n\n\n\/\/ on SunOS 4.x, getrusage is stated in the man pages and exists, but\n\/\/ is not declared in resource.h. declare it ourselves\n#ifdef NO_HAVE_GETRUSAGE\nextern \"C\" {\n int getrusage(int who, struct rusage* ru);\n}\n#endif\n\n\/\/ When modifying the prefix list, we need to lock it just in case\n\/\/ another thread tries to do the same.\nDEAL_II_NAMESPACE_OPEN\n\nnamespace\n{\n Threads::ThreadMutex log_lock;\n Threads::ThreadMutex write_lock;\n}\n\n\nLogStream deallog;\n\n\nLogStream::LogStream()\n\t\t:\n\t\tstd_out(&std::cerr), file(0),\n\t\tstd_depth(10000), file_depth(10000),\n\t\tprint_utime(false), diff_utime(false),\n\t\tlast_time (0.), double_threshold(0.), old_cerr(0)\n{\n prefixes.push(\"DEAL:\");\n std_out->setf(std::ios::showpoint | std::ios::left);\n#ifdef HAVE_TIMES\n reference_time_val = 1.\/sysconf(_SC_CLK_TCK) * times(&reference_tms);\n#endif\n}\n\n\nLogStream::~LogStream()\n{\n\t\t\t\t \/\/ if there was anything left in\n\t\t\t\t \/\/ the stream that is current to\n\t\t\t\t \/\/ this thread, make sure we flush\n\t\t\t\t \/\/ it before it gets lost\n {\n const unsigned int id = Threads::this_thread_id();\n if ((outstreams.find(id) != outstreams.end())\n\t&&\n\t(*outstreams[id] != 0)\n\t&&\n\t(outstreams[id]->str().length() > 0))\n *this << std::endl;\n }\n\n if (old_cerr)\n std::cerr.rdbuf(old_cerr);\n\n\t\t\t\t \/\/ on some systems, destroying the\n\t\t\t\t \/\/ outstreams objects of deallog\n\t\t\t\t \/\/ triggers some sort of memory\n\t\t\t\t \/\/ corruption, in particular when\n\t\t\t\t \/\/ we also link with Trilinos;\n\t\t\t\t \/\/ since this happens at the very\n\t\t\t\t \/\/ end of the program, we take the\n\t\t\t\t \/\/ liberty to simply not do it by\n\t\t\t\t \/\/ putting that object into a\n\t\t\t\t \/\/ deliberate memory leak and\n\t\t\t\t \/\/ instead destroying an empty\n\t\t\t\t \/\/ object\n#ifdef DEAL_II_USE_TRILINOS\n if (this == &deallog)\n {\n stream_map_type * dummy = new stream_map_type();\n dummy->swap (outstreams);\n delete dummy;\n }\n#endif\n}\n\n\nLogStream &\nLogStream::operator<< (std::ostream& (*p) (std::ostream&))\n{\n\t\t\t\t \/\/ do the work that is common to\n\t\t\t\t \/\/ the operator<< functions\n print (p);\n\n\t\t\t\t \/\/ next check whether this is the\n\t\t\t\t \/\/ <tt>endl<\/tt> manipulator, and if so\n\t\t\t\t \/\/ set a flag\n std::ostream & (* const p_endl) (std::ostream&) = &std::endl;\n if (p == p_endl)\n {\n Threads::ThreadMutex::ScopedLock lock(write_lock);\n print_line_head();\n std::ostringstream& stream = get_stream();\n if (prefixes.size() <= std_depth)\n\t*std_out << stream.str();\n\n if (file && (prefixes.size() <= file_depth))\n\t*file << stream.str() << std::flush;\n\n\t\t\t\t \/\/ Start a new string\n stream.str(\"\");\n }\n return *this;\n}\n\n\nstd::ostringstream&\nLogStream::get_stream()\n{\n\/\/TODO: use a ThreadLocalStorage object here\n Threads::ThreadMutex::ScopedLock lock(log_lock);\n const unsigned int id = Threads::this_thread_id();\n\n\t\t\t\t \/\/ if necessary allocate a stream object\n if (outstreams.find (id) == outstreams.end())\n {\n outstreams[id].reset (new std::ostringstream());\n outstreams[id]->setf(std::ios::showpoint | std::ios::left);\n }\n return *outstreams[id];\n}\n\n\n\nvoid\nLogStream::attach(std::ostream& o)\n{\n Threads::ThreadMutex::ScopedLock lock(log_lock);\n file = &o;\n o.setf(std::ios::showpoint | std::ios::left);\n o << dealjobid();\n}\n\n\nvoid LogStream::detach ()\n{\n Threads::ThreadMutex::ScopedLock lock(log_lock);\n file = 0;\n}\n\n\nvoid LogStream::log_cerr ()\n{\n Threads::ThreadMutex::ScopedLock lock(log_lock);\n if (old_cerr == 0)\n {\n old_cerr = std::cerr.rdbuf(file->rdbuf());\n } else {\n std::cerr.rdbuf(old_cerr);\n old_cerr = 0;\n }\n}\n\n\nstd::ostream&\nLogStream::get_console()\n{\n return *std_out;\n}\n\n\nstd::ostream&\nLogStream::get_file_stream()\n{\n Assert(file, ExcNoFileStreamGiven());\n return *file;\n}\n\n\nbool\nLogStream::has_file() const\n{\n return (file != 0);\n}\n\n\nconst std::string&\nLogStream::get_prefix() const\n{\n return prefixes.top();\n}\n\n\nvoid\nLogStream::push (const std::string& text)\n{\n Threads::ThreadMutex::ScopedLock lock(log_lock);\n std::string pre=prefixes.top();\n pre += text;\n pre += std::string(\":\");\n prefixes.push(pre);\n}\n\n\nvoid LogStream::pop ()\n{\n Threads::ThreadMutex::ScopedLock lock(log_lock);\n if (prefixes.size() > 1)\n prefixes.pop();\n}\n\n\nunsigned int\nLogStream::depth_console (const unsigned n)\n{\n Threads::ThreadMutex::ScopedLock lock(log_lock);\n const unsigned int h = std_depth;\n std_depth = n;\n return h;\n}\n\n\nunsigned int\nLogStream::depth_file (const unsigned n)\n{\n Threads::ThreadMutex::ScopedLock lock(log_lock);\n const unsigned int h = file_depth;\n file_depth = n;\n return h;\n}\n\n\nvoid\nLogStream::threshold_double (const double t)\n{\n Threads::ThreadMutex::ScopedLock lock(log_lock);\n double_threshold = t;\n}\n\n\nbool\nLogStream::log_execution_time (const bool flag)\n{\n Threads::ThreadMutex::ScopedLock lock(log_lock);\n const bool h = print_utime;\n print_utime = flag;\n return h;\n}\n\n\nbool\nLogStream::log_time_differences (const bool flag)\n{\n Threads::ThreadMutex::ScopedLock lock(log_lock);\n const bool h = diff_utime;\n diff_utime = flag;\n return h;\n}\n\n\nbool\nLogStream::log_thread_id (const bool flag)\n{\n Threads::ThreadMutex::ScopedLock lock(log_lock);\n const bool h = print_thread_id;\n print_thread_id = flag;\n return h;\n}\n\n\nvoid\nLogStream::print_line_head()\n{\n rusage usage;\n double utime = 0.;\n if (print_utime)\n {\n getrusage(RUSAGE_SELF, &usage);\n utime = usage.ru_utime.tv_sec + 1.e-6 * usage.ru_utime.tv_usec;\n if (diff_utime)\n\t{\n\t double diff = utime - last_time;\n\t last_time = utime;\n\t utime = diff;\n\t}\n }\n\n\/*\n * The following lines were used for debugging a memory leak.\n * They work on Linux, not on Solaris, since the \/proc filesystem\n * on Solaris is quite cryptic. For other systems, we don't know.\n *\n * Unfortunately, the information in \/proc\/pid\/stat is updated slowly,\n * therefore, the information is quite unreliable.\n *\n * Furthermore, the constructor of ifstream caused another memory leak.\n *\n * Still, this code might be useful sometimes, so I kept it here.\n * When we have more information about the kernel, this should be\n * incorporated properly. Suggestions are welcome!\n *\/\n\n#ifdef DEALII_MEMORY_DEBUG\n static const pid_t id = getpid();\n\n std::ostringstream statname;\n statname << \"\/proc\/\" << id << \"\/stat\";\n\n static long size;\n static string dummy;\n ifstream stat(statname.str());\n\t\t\t\t \/\/ ignore 22 values\n stat >> dummy >> dummy >> dummy >> dummy >> dummy >> dummy >>\n dummy >> dummy >> dummy >> dummy >> dummy >>\n dummy >> dummy >> dummy >> dummy >> dummy >> dummy >>\n dummy >> dummy >> dummy >> dummy >> dummy >> size;\n#endif\n\n const std::string& head = get_prefix();\n const unsigned int thread = Threads::this_thread_id();\n\n if (prefixes.size() <= std_depth)\n {\n if (print_utime)\n\t{\n\t int p = std_out->width(5);\n\t *std_out << utime << ':';\n#ifdef DEALII_MEMORY_DEBUG\n\t *std_out << size << ':';\n#endif\n\t std_out->width(p);\n\t}\n if (print_thread_id)\n\t*std_out << '[' << thread << ']';\n\n *std_out << head << ':';\n }\n\n if (file && (prefixes.size() <= file_depth))\n {\n if (print_utime)\n\t{\n\t int p = file->width(6);\n\t *file << utime << ':';\n#ifdef DEALII_MEMORY_DEBUG\n\t *file << size << ':';\n#endif\n\t file->width(p);\n\t}\n if (print_thread_id)\n\t*file << '[' << thread << ']';\n\n *file << head << ':';\n }\n}\n\n\nvoid\nLogStream::timestamp ()\n{\n struct tms current_tms;\n#ifdef HAVE_TIMES\n const clock_t tick = sysconf(_SC_CLK_TCK);\n const double time = 1.\/tick * times(¤t_tms);\n#else\n const double time = 0.;\n const unsigned int tick = 100;\n#endif\n (*this) << \"Wall: \" << time - reference_time_val\n\t << \" User: \" << 1.\/tick * (current_tms.tms_utime - reference_tms.tms_utime)\n\t << \" System: \" << 1.\/tick * (current_tms.tms_stime - reference_tms.tms_stime)\n\t << \" Child-User: \" << 1.\/tick * (current_tms.tms_cutime - reference_tms.tms_cutime)\n\t << \" Child-System: \" << 1.\/tick * (current_tms.tms_cstime - reference_tms.tms_cstime)\n\t << std::endl;\n}\n\n\nstd::size_t\nLogStream::memory_consumption () const\n{\n std::size_t mem = sizeof(*this);\n\t\t\t\t \/\/ to determine size of stack\n\t\t\t\t \/\/ elements, we have to copy the\n\t\t\t\t \/\/ stack since we can't access\n\t\t\t\t \/\/ elements from further below\n std::stack<std::string> tmp = prefixes;\n while (tmp.empty() == false)\n {\n mem += MemoryConsumption::memory_consumption (tmp.top());\n tmp.pop ();\n }\n\n return mem;\n}\n\nDEAL_II_NAMESPACE_CLOSE\n<|endoftext|>"} {"text":"<commit_before>\/\/---------------------------------------------------------------------------\n\/\/ $Id$\n\/\/ Version: $Name$\n\/\/\n\/\/ Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2008, 2009, 2010, 2011, 2012 by the deal.II authors\n\/\/\n\/\/ This file is subject to QPL and may not be distributed\n\/\/ without copyright and license information. Please refer\n\/\/ to the file deal.II\/doc\/license.html for the text and\n\/\/ further information on this license.\n\/\/\n\/\/---------------------------------------------------------------------------\n\n\n#include <deal.II\/base\/logstream.h>\n#include <deal.II\/base\/job_identifier.h>\n#include <deal.II\/base\/memory_consumption.h>\n#include <deal.II\/base\/thread_management.h>\n\n#ifdef HAVE_SYS_RESOURCE_H\n# include <sys\/resource.h>\n#endif\n\n#ifdef HAVE_UNISTD_H\n# include <unistd.h>\n#endif\n\n#include <iostream>\n#include <iomanip>\n#include <fstream>\n#include <sstream>\n\n\nDEAL_II_NAMESPACE_OPEN\n\nnamespace\n{\n Threads::Mutex log_lock;\n Threads::Mutex write_lock;\n}\n\n\n\/\/ The standard log object of deal.II:\nLogStream deallog;\n\n\nLogStream::LogStream()\n :\n std_out(&std::cerr),\n file(0),\n std_depth(10000),\n file_depth(10000),\n print_utime(false),\n diff_utime(false),\n last_time (0.),\n double_threshold(0.),\n float_threshold(0.),\n offset(0),\n old_cerr(0),\n at_newline(true)\n{\n get_prefixes().push(\"DEAL:\");\n\n#if defined(HAVE_UNISTD_H) && defined(HAVE_TIMES)\n reference_time_val = 1.\/sysconf(_SC_CLK_TCK) * times(&reference_tms);\n#endif\n\n}\n\n\nLogStream::~LogStream()\n{\n \/\/ if there was anything left in the stream that is current to this\n \/\/ thread, make sure we flush it before it gets lost\n {\n if (get_stream().str().length() > 0)\n {\n \/\/ except the situation is not quite that simple. if this object is\n \/\/ the 'deallog' object, then it is destroyed upon exit of the\n \/\/ program. since it's defined in a shared library that depends on\n \/\/ libstdc++.so, destruction happens before destruction of\n \/\/ std::cout\/cerr, but after all file variables defined in user\n \/\/ programs have been destroyed. in other words, if we get here and\n \/\/ the object being destroyed is 'deallog' and if 'deallog' is\n \/\/ associated with a file stream, then we're in trouble: we'll try\n \/\/ to write to a file that doesn't exist any more, and we're likely\n \/\/ going to crash (this is tested by base\/log_crash_01). rather\n \/\/ than letting it come to this, print a message to the screen\n \/\/ (note that we can't issue an assertion here either since Assert\n \/\/ may want to write to 'deallog' itself, and AssertThrow will\n \/\/ throw an exception that can't be caught)\n if ((this == &deallog) && file)\n std::cerr << (\"You still have content that was written to 'deallog' \"\n \"but not flushed to the screen or a file while the \"\n \"program is being terminated. This would lead to a \"\n \"segmentation fault. Make sure you flush the \"\n \"content of the 'deallog' object using 'std::endl' \"\n \"before the end of the program.\")\n << std::endl;\n else\n *this << std::endl;\n }\n }\n\n if (old_cerr)\n std::cerr.rdbuf(old_cerr);\n}\n\n\nvoid\nLogStream::test_mode(bool on)\n{\n Threads::Mutex::ScopedLock lock(log_lock);\n if (on)\n {\n double_threshold = 1.e-10;\n float_threshold = 1.e-7;\n offset = 1.e-7;\n }\n else\n {\n double_threshold = 0.;\n float_threshold = 0.;\n offset = 0.;\n }\n}\n\n\nLogStream &\nLogStream::operator<< (std::ostream& (*p) (std::ostream &))\n{\n std::ostringstream &stream = get_stream();\n\n \/\/ Print to the internal stringstream:\n stream << p;\n\n \/\/ Next check whether this is the <tt>flush<\/tt> or <tt>endl<\/tt>\n \/\/ manipulator, and if so print out the message.\n std::ostream & (* const p_flush) (std::ostream &) = &std::flush;\n std::ostream & (* const p_endl) (std::ostream &) = &std::endl;\n if (p == p_flush || p == p_endl)\n {\n Threads::Mutex::ScopedLock lock(write_lock);\n\n \/\/ Print the line head in case of a newline:\n if (at_newline)\n print_line_head();\n\n if(p == p_flush)\n at_newline = false;\n\n if(p == p_endl)\n at_newline = true;\n\n if (get_prefixes().size() <= std_depth)\n *std_out << stream.str();\n\n if (file && (get_prefixes().size() <= file_depth))\n *file << stream.str() << std::flush;\n\n \/\/ Start a new string\n stream.str(\"\");\n }\n\n return *this;\n}\n\n\nvoid\nLogStream::attach(std::ostream &o)\n{\n Threads::Mutex::ScopedLock lock(log_lock);\n file = &o;\n o.setf(std::ios::showpoint | std::ios::left);\n o << dealjobid();\n}\n\n\nvoid LogStream::detach ()\n{\n Threads::Mutex::ScopedLock lock(log_lock);\n file = 0;\n}\n\n\nvoid LogStream::log_cerr ()\n{\n Threads::Mutex::ScopedLock lock(log_lock);\n if (old_cerr == 0)\n {\n old_cerr = std::cerr.rdbuf(file->rdbuf());\n }\n else\n {\n std::cerr.rdbuf(old_cerr);\n old_cerr = 0;\n }\n}\n\n\nstd::ostream &\nLogStream::get_console()\n{\n return *std_out;\n}\n\n\nstd::ostream &\nLogStream::get_file_stream()\n{\n Assert(file, ExcNoFileStreamGiven());\n return *file;\n}\n\n\nbool\nLogStream::has_file() const\n{\n return (file != 0);\n}\n\n\nconst std::string &\nLogStream::get_prefix() const\n{\n return get_prefixes().top();\n}\n\n\nvoid\nLogStream::push (const std::string &text)\n{\n std::string pre=get_prefixes().top();\n pre += text;\n pre += std::string(\":\");\n get_prefixes().push(pre);\n}\n\n\nvoid LogStream::pop ()\n{\n if (get_prefixes().size() > 1)\n get_prefixes().pop();\n}\n\n\nunsigned int\nLogStream::depth_console (const unsigned int n)\n{\n Threads::Mutex::ScopedLock lock(log_lock);\n const unsigned int h = std_depth;\n std_depth = n;\n return h;\n}\n\n\nunsigned int\nLogStream::depth_file (const unsigned int n)\n{\n Threads::Mutex::ScopedLock lock(log_lock);\n const unsigned int h = file_depth;\n file_depth = n;\n return h;\n}\n\n\nvoid\nLogStream::threshold_double (const double t)\n{\n Threads::Mutex::ScopedLock lock(log_lock);\n double_threshold = t;\n}\n\n\nvoid\nLogStream::threshold_float (const float t)\n{\n Threads::Mutex::ScopedLock lock(log_lock);\n float_threshold = t;\n}\n\n\nbool\nLogStream::log_execution_time (const bool flag)\n{\n Threads::Mutex::ScopedLock lock(log_lock);\n const bool h = print_utime;\n print_utime = flag;\n return h;\n}\n\n\nbool\nLogStream::log_time_differences (const bool flag)\n{\n Threads::Mutex::ScopedLock lock(log_lock);\n const bool h = diff_utime;\n diff_utime = flag;\n return h;\n}\n\n\nbool\nLogStream::log_thread_id (const bool flag)\n{\n Threads::Mutex::ScopedLock lock(log_lock);\n const bool h = print_thread_id;\n print_thread_id = flag;\n return h;\n}\n\nstd::stack<std::string> &\nLogStream::get_prefixes() const\n{\n#ifdef DEAL_II_WITH_THREADS\n bool exists = false;\n std::stack<std::string> &local_prefixes = prefixes.get(exists);\n\n \/\/ If this is a new locally stored stack, copy the \"blessed\" prefixes\n \/\/ from the initial thread that created logstream.\n if(! exists)\n {\n const tbb::enumerable_thread_specific<std::stack<std::string> > &impl\n = prefixes.get_implementation();\n\n \/\/ The thread that created this LogStream object should be the first\n \/\/ in tbb's enumerable_thread_specific containter.\n const tbb::enumerable_thread_specific<std::stack<std::string> >::const_iterator first_elem\n = impl.begin();\n\n if (first_elem != impl.end())\n {\n local_prefixes = *first_elem;\n }\n }\n\n return local_prefixes;\n\n#else\n return prefixes.get();\n#endif\n}\n\n\nvoid\nLogStream::print_line_head()\n{\n#ifdef HAVE_SYS_RESOURCE_H\n rusage usage;\n double utime = 0.;\n if (print_utime)\n {\n getrusage(RUSAGE_SELF, &usage);\n utime = usage.ru_utime.tv_sec + 1.e-6 * usage.ru_utime.tv_usec;\n if (diff_utime)\n {\n double diff = utime - last_time;\n last_time = utime;\n utime = diff;\n }\n }\n#else\n\/\/TODO[BG]: Do something useful here\n double utime = 0.;\n#endif\n\n \/*\n * The following lines were used for debugging a memory leak.\n * They work on Linux, not on Solaris, since the \/proc filesystem\n * on Solaris is quite cryptic. For other systems, we don't know.\n *\n * Unfortunately, the information in \/proc\/pid\/stat is updated slowly,\n * therefore, the information is quite unreliable.\n *\n * Furthermore, the constructor of ifstream caused another memory leak.\n *\n * Still, this code might be useful sometimes, so I kept it here.\n * When we have more information about the kernel, this should be\n * incorporated properly. Suggestions are welcome!\n *\/\n\n#ifdef DEALII_MEMORY_DEBUG\n static const pid_t id = getpid();\n\n std::ostringstream statname;\n statname << \"\/proc\/\" << id << \"\/stat\";\n\n static long size;\n static string dummy;\n ifstream stat(statname.str());\n \/\/ ignore 22 values\n stat >> dummy >> dummy >> dummy >> dummy >> dummy >> dummy >>\n dummy >> dummy >> dummy >> dummy >> dummy >>\n dummy >> dummy >> dummy >> dummy >> dummy >> dummy >>\n dummy >> dummy >> dummy >> dummy >> dummy >> size;\n#endif\n\n const std::string &head = get_prefix();\n const unsigned int thread = Threads::this_thread_id();\n\n if (get_prefixes().size() <= std_depth)\n {\n if (print_utime)\n {\n int p = std_out->width(5);\n *std_out << utime << ':';\n#ifdef DEALII_MEMORY_DEBUG\n *std_out << size << ':';\n#endif\n std_out->width(p);\n }\n if (print_thread_id)\n *std_out << '[' << thread << ']';\n\n *std_out << head << ':';\n }\n\n if (file && (get_prefixes().size() <= file_depth))\n {\n if (print_utime)\n {\n int p = file->width(6);\n *file << utime << ':';\n#ifdef DEALII_MEMORY_DEBUG\n *file << size << ':';\n#endif\n file->width(p);\n }\n if (print_thread_id)\n *file << '[' << thread << ']';\n\n *file << head << ':';\n }\n}\n\n\nvoid\nLogStream::timestamp ()\n{\n struct tms current_tms;\n#if defined(HAVE_UNISTD_H) && defined(HAVE_TIMES)\n const clock_t tick = sysconf(_SC_CLK_TCK);\n const double time = 1.\/tick * times(¤t_tms);\n#else\n const double time = 0.;\n const unsigned int tick = 100;\n#endif\n (*this) << \"Wall: \" << time - reference_time_val\n << \" User: \" << 1.\/tick * (current_tms.tms_utime - reference_tms.tms_utime)\n << \" System: \" << 1.\/tick * (current_tms.tms_stime - reference_tms.tms_stime)\n << \" Child-User: \" << 1.\/tick * (current_tms.tms_cutime - reference_tms.tms_cutime)\n << \" Child-System: \" << 1.\/tick * (current_tms.tms_cstime - reference_tms.tms_cstime)\n << std::endl;\n}\n\n\nstd::size_t\nLogStream::memory_consumption () const\n{\n \/\/ TODO\n Assert(false, ExcNotImplemented());\n\n std::size_t mem = sizeof(*this);\n \/\/ to determine size of stack\n \/\/ elements, we have to copy the\n \/\/ stack since we can't access\n \/\/ elements from further below\n\/\/ std::stack<std::string> tmp = prefixes;\n\/\/ while (tmp.empty() == false)\n\/\/ {\n\/\/ mem += MemoryConsumption::memory_consumption (tmp.top());\n\/\/ tmp.pop ();\n\/\/ }\n\n return mem;\n}\n\nDEAL_II_NAMESPACE_CLOSE\n<commit_msg>Commit the second part of Fahad's patch that was accidentally forgotten :-(<commit_after>\/\/---------------------------------------------------------------------------\n\/\/ $Id$\n\/\/ Version: $Name$\n\/\/\n\/\/ Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2008, 2009, 2010, 2011, 2012 by the deal.II authors\n\/\/\n\/\/ This file is subject to QPL and may not be distributed\n\/\/ without copyright and license information. Please refer\n\/\/ to the file deal.II\/doc\/license.html for the text and\n\/\/ further information on this license.\n\/\/\n\/\/---------------------------------------------------------------------------\n\n\n#include <deal.II\/base\/logstream.h>\n#include <deal.II\/base\/job_identifier.h>\n#include <deal.II\/base\/memory_consumption.h>\n#include <deal.II\/base\/thread_management.h>\n\n#ifdef HAVE_SYS_RESOURCE_H\n# include <sys\/resource.h>\n#endif\n\n#ifdef HAVE_UNISTD_H\n# include <unistd.h>\n#endif\n\n#include <iostream>\n#include <iomanip>\n#include <fstream>\n#include <sstream>\n\n\nDEAL_II_NAMESPACE_OPEN\n\nnamespace\n{\n Threads::Mutex log_lock;\n Threads::Mutex write_lock;\n}\n\n\n\/\/ The standard log object of deal.II:\nLogStream deallog;\n\n\nLogStream::LogStream()\n :\n std_out(&std::cerr),\n file(0),\n std_depth(10000),\n file_depth(10000),\n print_utime(false),\n diff_utime(false),\n last_time (0.),\n double_threshold(0.),\n float_threshold(0.),\n offset(0),\n old_cerr(0),\n at_newline(true),\n stream_flags(std::ios::showpoint | std::ios::left),\n stream_width(std::cout.width()),\n stream_precision(std::cout.precision())\n{\n get_prefixes().push(\"DEAL:\");\n\n#if defined(HAVE_UNISTD_H) && defined(HAVE_TIMES)\n reference_time_val = 1.\/sysconf(_SC_CLK_TCK) * times(&reference_tms);\n#endif\n\n}\n\n\nLogStream::~LogStream()\n{\n \/\/ if there was anything left in the stream that is current to this\n \/\/ thread, make sure we flush it before it gets lost\n {\n if (get_stream().str().length() > 0)\n {\n \/\/ except the situation is not quite that simple. if this object is\n \/\/ the 'deallog' object, then it is destroyed upon exit of the\n \/\/ program. since it's defined in a shared library that depends on\n \/\/ libstdc++.so, destruction happens before destruction of\n \/\/ std::cout\/cerr, but after all file variables defined in user\n \/\/ programs have been destroyed. in other words, if we get here and\n \/\/ the object being destroyed is 'deallog' and if 'deallog' is\n \/\/ associated with a file stream, then we're in trouble: we'll try\n \/\/ to write to a file that doesn't exist any more, and we're likely\n \/\/ going to crash (this is tested by base\/log_crash_01). rather\n \/\/ than letting it come to this, print a message to the screen\n \/\/ (note that we can't issue an assertion here either since Assert\n \/\/ may want to write to 'deallog' itself, and AssertThrow will\n \/\/ throw an exception that can't be caught)\n if ((this == &deallog) && file)\n std::cerr << (\"You still have content that was written to 'deallog' \"\n \"but not flushed to the screen or a file while the \"\n \"program is being terminated. This would lead to a \"\n \"segmentation fault. Make sure you flush the \"\n \"content of the 'deallog' object using 'std::endl' \"\n \"before the end of the program.\")\n << std::endl;\n else\n *this << std::endl;\n }\n }\n\n if (old_cerr)\n std::cerr.rdbuf(old_cerr);\n}\n\n\nvoid\nLogStream::test_mode(bool on)\n{\n Threads::Mutex::ScopedLock lock(log_lock);\n if (on)\n {\n double_threshold = 1.e-10;\n float_threshold = 1.e-7;\n offset = 1.e-7;\n }\n else\n {\n double_threshold = 0.;\n float_threshold = 0.;\n offset = 0.;\n }\n}\n\n\nLogStream &\nLogStream::operator<< (std::ostream& (*p) (std::ostream &))\n{\n\n std::ostringstream &stream = get_stream();\n \/\/ save the state of out stream\n std::ios::fmtflags old_flags = stream.flags(stream_flags);\n unsigned int old_precision = stream.precision (stream_precision);\n unsigned int old_width = stream.width (stream_width);\n\n \/\/ Print to the internal stringstream:\n stream << p;\n\n \/\/ Next check whether this is the <tt>flush<\/tt> or <tt>endl<\/tt>\n \/\/ manipulator, and if so print out the message.\n std::ostream & (* const p_flush) (std::ostream &) = &std::flush;\n std::ostream & (* const p_endl) (std::ostream &) = &std::endl;\n if (p == p_flush || p == p_endl)\n {\n Threads::Mutex::ScopedLock lock(write_lock);\n\n \/\/ Print the line head in case of a newline:\n if (at_newline)\n print_line_head();\n\n if(p == p_flush)\n at_newline = false;\n\n if(p == p_endl)\n at_newline = true;\n\n if (get_prefixes().size() <= std_depth)\n *std_out << stream.str();\n\n if (file && (get_prefixes().size() <= file_depth))\n *file << stream.str() << std::flush;\n\n \/\/ Start a new string\n stream.str(\"\");\n }\n\n \/\/ reset output format\n stream.flags (old_flags);\n stream.precision(old_precision);\n stream.width(old_width);\n\n return *this;\n}\n\n\nvoid\nLogStream::attach(std::ostream &o)\n{\n Threads::Mutex::ScopedLock lock(log_lock);\n file = &o;\n o.setf(std::ios::showpoint | std::ios::left);\n o << dealjobid();\n}\n\n\nvoid LogStream::detach ()\n{\n Threads::Mutex::ScopedLock lock(log_lock);\n file = 0;\n}\n\n\nvoid LogStream::log_cerr ()\n{\n Threads::Mutex::ScopedLock lock(log_lock);\n if (old_cerr == 0)\n {\n old_cerr = std::cerr.rdbuf(file->rdbuf());\n }\n else\n {\n std::cerr.rdbuf(old_cerr);\n old_cerr = 0;\n }\n}\n\n\nstd::ostream &\nLogStream::get_console()\n{\n return *std_out;\n}\n\n\nstd::ostream &\nLogStream::get_file_stream()\n{\n Assert(file, ExcNoFileStreamGiven());\n return *file;\n}\n\n\nbool\nLogStream::has_file() const\n{\n return (file != 0);\n}\n\n\nconst std::string &\nLogStream::get_prefix() const\n{\n return get_prefixes().top();\n}\n\n\nvoid\nLogStream::push (const std::string &text)\n{\n std::string pre=get_prefixes().top();\n pre += text;\n pre += std::string(\":\");\n get_prefixes().push(pre);\n}\n\n\nvoid LogStream::pop ()\n{\n if (get_prefixes().size() > 1)\n get_prefixes().pop();\n}\n\n\nstd::ios::fmtflags\nLogStream::flags(const std::ios::fmtflags f)\n{\n std::ios::fmtflags tmp = stream_flags;\n stream_flags = f;\n return tmp;\n}\n\n\nstd::streamsize\nLogStream::precision (const std::streamsize prec)\n{\n std::streamsize tmp = stream_precision;\n stream_precision = prec;\n return tmp;\n}\n\n\nstd::streamsize\nLogStream::width (const std::streamsize wide)\n{\n std::streamsize tmp = stream_width;\n stream_width = wide;\n return tmp;\n}\n\n\nunsigned int\nLogStream::depth_console (const unsigned int n)\n{\n Threads::Mutex::ScopedLock lock(log_lock);\n const unsigned int h = std_depth;\n std_depth = n;\n return h;\n}\n\n\nunsigned int\nLogStream::depth_file (const unsigned int n)\n{\n Threads::Mutex::ScopedLock lock(log_lock);\n const unsigned int h = file_depth;\n file_depth = n;\n return h;\n}\n\n\nvoid\nLogStream::threshold_double (const double t)\n{\n Threads::Mutex::ScopedLock lock(log_lock);\n double_threshold = t;\n}\n\n\nvoid\nLogStream::threshold_float (const float t)\n{\n Threads::Mutex::ScopedLock lock(log_lock);\n float_threshold = t;\n}\n\n\nbool\nLogStream::log_execution_time (const bool flag)\n{\n Threads::Mutex::ScopedLock lock(log_lock);\n const bool h = print_utime;\n print_utime = flag;\n return h;\n}\n\n\nbool\nLogStream::log_time_differences (const bool flag)\n{\n Threads::Mutex::ScopedLock lock(log_lock);\n const bool h = diff_utime;\n diff_utime = flag;\n return h;\n}\n\n\nbool\nLogStream::log_thread_id (const bool flag)\n{\n Threads::Mutex::ScopedLock lock(log_lock);\n const bool h = print_thread_id;\n print_thread_id = flag;\n return h;\n}\n\nstd::stack<std::string> &\nLogStream::get_prefixes() const\n{\n#ifdef DEAL_II_WITH_THREADS\n bool exists = false;\n std::stack<std::string> &local_prefixes = prefixes.get(exists);\n\n \/\/ If this is a new locally stored stack, copy the \"blessed\" prefixes\n \/\/ from the initial thread that created logstream.\n if(! exists)\n {\n const tbb::enumerable_thread_specific<std::stack<std::string> > &impl\n = prefixes.get_implementation();\n\n \/\/ The thread that created this LogStream object should be the first\n \/\/ in tbb's enumerable_thread_specific containter.\n const tbb::enumerable_thread_specific<std::stack<std::string> >::const_iterator first_elem\n = impl.begin();\n\n if (first_elem != impl.end())\n {\n local_prefixes = *first_elem;\n }\n }\n\n return local_prefixes;\n\n#else\n return prefixes.get();\n#endif\n}\n\n\nvoid\nLogStream::print_line_head()\n{\n#ifdef HAVE_SYS_RESOURCE_H\n rusage usage;\n double utime = 0.;\n if (print_utime)\n {\n getrusage(RUSAGE_SELF, &usage);\n utime = usage.ru_utime.tv_sec + 1.e-6 * usage.ru_utime.tv_usec;\n if (diff_utime)\n {\n double diff = utime - last_time;\n last_time = utime;\n utime = diff;\n }\n }\n#else\n\/\/TODO[BG]: Do something useful here\n double utime = 0.;\n#endif\n\n \/*\n * The following lines were used for debugging a memory leak.\n * They work on Linux, not on Solaris, since the \/proc filesystem\n * on Solaris is quite cryptic. For other systems, we don't know.\n *\n * Unfortunately, the information in \/proc\/pid\/stat is updated slowly,\n * therefore, the information is quite unreliable.\n *\n * Furthermore, the constructor of ifstream caused another memory leak.\n *\n * Still, this code might be useful sometimes, so I kept it here.\n * When we have more information about the kernel, this should be\n * incorporated properly. Suggestions are welcome!\n *\/\n\n#ifdef DEALII_MEMORY_DEBUG\n static const pid_t id = getpid();\n\n std::ostringstream statname;\n statname << \"\/proc\/\" << id << \"\/stat\";\n\n static long size;\n static string dummy;\n ifstream stat(statname.str());\n \/\/ ignore 22 values\n stat >> dummy >> dummy >> dummy >> dummy >> dummy >> dummy >>\n dummy >> dummy >> dummy >> dummy >> dummy >>\n dummy >> dummy >> dummy >> dummy >> dummy >> dummy >>\n dummy >> dummy >> dummy >> dummy >> dummy >> size;\n#endif\n\n const std::string &head = get_prefix();\n const unsigned int thread = Threads::this_thread_id();\n\n if (get_prefixes().size() <= std_depth)\n {\n if (print_utime)\n {\n int p = std_out->width(5);\n *std_out << utime << ':';\n#ifdef DEALII_MEMORY_DEBUG\n *std_out << size << ':';\n#endif\n std_out->width(p);\n }\n if (print_thread_id)\n *std_out << '[' << thread << ']';\n\n *std_out << head << ':';\n }\n\n if (file && (get_prefixes().size() <= file_depth))\n {\n if (print_utime)\n {\n int p = file->width(6);\n *file << utime << ':';\n#ifdef DEALII_MEMORY_DEBUG\n *file << size << ':';\n#endif\n file->width(p);\n }\n if (print_thread_id)\n *file << '[' << thread << ']';\n\n *file << head << ':';\n }\n}\n\n\nvoid\nLogStream::timestamp ()\n{\n struct tms current_tms;\n#if defined(HAVE_UNISTD_H) && defined(HAVE_TIMES)\n const clock_t tick = sysconf(_SC_CLK_TCK);\n const double time = 1.\/tick * times(¤t_tms);\n#else\n const double time = 0.;\n const unsigned int tick = 100;\n#endif\n (*this) << \"Wall: \" << time - reference_time_val\n << \" User: \" << 1.\/tick * (current_tms.tms_utime - reference_tms.tms_utime)\n << \" System: \" << 1.\/tick * (current_tms.tms_stime - reference_tms.tms_stime)\n << \" Child-User: \" << 1.\/tick * (current_tms.tms_cutime - reference_tms.tms_cutime)\n << \" Child-System: \" << 1.\/tick * (current_tms.tms_cstime - reference_tms.tms_cstime)\n << std::endl;\n}\n\n\nstd::size_t\nLogStream::memory_consumption () const\n{\n \/\/ TODO\n Assert(false, ExcNotImplemented());\n\n std::size_t mem = sizeof(*this);\n \/\/ to determine size of stack\n \/\/ elements, we have to copy the\n \/\/ stack since we can't access\n \/\/ elements from further below\n\/\/ std::stack<std::string> tmp = prefixes;\n\/\/ while (tmp.empty() == false)\n\/\/ {\n\/\/ mem += MemoryConsumption::memory_consumption (tmp.top());\n\/\/ tmp.pop ();\n\/\/ }\n\n return mem;\n}\n\nDEAL_II_NAMESPACE_CLOSE\n<|endoftext|>"} {"text":"<commit_before>\/**\n* @version GrPPI v0.1\n* @copyright Copyright (C) 2017 Universidad Carlos III de Madrid. All rights reserved.\n* @license GNU\/GPL, see LICENSE.txt\n* This program is free software: you can redistribute it and\/or modify\n* it under the terms of the GNU General Public License as published by\n* the Free Software Foundation, either version 3 of the License, or\n* (at your option) any later version.\n*\n* This program is distributed in the hope that it will be useful,\n* but WITHOUT ANY WARRANTY; without even the implied warranty of\n* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n* GNU General Public License for more details.\n*\n* You have received a copy of the GNU General Public License in LICENSE.txt\n* also available in <http:\/\/www.gnu.org\/licenses\/gpl.html>.\n*\n* See COPYRIGHT.txt for copyright notices and details.\n*\/\n\/\/ Standard library\n#include <iostream>\n#include <vector>\n#include <fstream>\n#include <chrono>\n#include <string>\n#include <numeric>\n#include <stdexcept>\n#include <random>\n\n\/\/ grppi\n#include \"divideconquer.h\"\n\n\/\/ Samples shared utilities\n#include \"..\/..\/util\/util.h\"\n\nstruct range {\n std::vector<int>::iterator first, last;\n \n auto size() const { return distance(first,last); }\n friend std::ostream & operator<<(std::ostream & os, const range & r);\n};\n\nstd::ostream & operator<<(std::ostream & os, const range & r) {\n os << \"(size= \" << r.size() << \") \";\n std::copy(r.first, r.last, std::ostream_iterator<int>(std::cerr, \" \"));\n return os;\n}\n\nstd::vector<range> divide(range r) {\n auto mid = r.first + distance(r.first,r.last)\/2;\n return { {r.first,mid} , {mid, r.last} };\n}\n\nvoid sort_sequence(grppi::polymorphic_execution & exec, int n) {\n using namespace std;\n\n std::random_device rdev;\n std::uniform_int_distribution<> gen{1,1000};\n\n vector<int> v;\n for (int i=0; i<n; ++i) {\n v.push_back(gen(rdev));\n }\n \n range problem{begin(v), end(v)};\n\n\/*\n auto res = grppi::divide_conquer(exec,\n problem,\n [](auto r) -> vector<range> {\n if (1>=r.size()) { return {r}; }\n else { return divide(r); }\n },\n [](auto x) { return x; },\n [](auto r1, auto r2) {\n std::inplace_merge(r1.first, r1.last, r2.last);\n return range{r1.first, r2.last};\n }\n );\n*\/\n\n copy(begin(v), end(v), ostream_iterator<int>(cout, \" \"));\n cout << endl;\n}\n\nvoid print_message(const std::string & prog, const std::string & msg) {\n using namespace std;\n\n cerr << msg << endl;\n cerr << \"Usage: \" << prog << \" size mode\" << endl;\n cerr << \" size: Integer value with problem size\" << endl;\n cerr << \" mode:\" << endl;\n print_available_modes(cerr);\n}\n\n\nint main(int argc, char **argv) {\n \n using namespace std;\n\n if(argc < 3){\n print_message(argv[0], \"Invalid number of arguments.\");\n return -1;\n }\n\n int n = stoi(argv[1]);\n if(n <= 0){\n print_message(argv[0], \"Invalid problem size. Use a positive number.\");\n return -1;\n }\n\n if (!run_test(argv[2], sort_sequence, n)) {\n print_message(argv[0], \"Invalid policy.\");\n return -1;\n }\n\n return 0;\n}\n<commit_msg>Uncomented call to divide\/conquer<commit_after>\/**\n* @version GrPPI v0.1\n* @copyright Copyright (C) 2017 Universidad Carlos III de Madrid. All rights reserved.\n* @license GNU\/GPL, see LICENSE.txt\n* This program is free software: you can redistribute it and\/or modify\n* it under the terms of the GNU General Public License as published by\n* the Free Software Foundation, either version 3 of the License, or\n* (at your option) any later version.\n*\n* This program is distributed in the hope that it will be useful,\n* but WITHOUT ANY WARRANTY; without even the implied warranty of\n* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n* GNU General Public License for more details.\n*\n* You have received a copy of the GNU General Public License in LICENSE.txt\n* also available in <http:\/\/www.gnu.org\/licenses\/gpl.html>.\n*\n* See COPYRIGHT.txt for copyright notices and details.\n*\/\n\/\/ Standard library\n#include <iostream>\n#include <vector>\n#include <fstream>\n#include <chrono>\n#include <string>\n#include <numeric>\n#include <stdexcept>\n#include <random>\n\n\/\/ grppi\n#include \"divideconquer.h\"\n\n\/\/ Samples shared utilities\n#include \"..\/..\/util\/util.h\"\n\nstruct range {\n std::vector<int>::iterator first, last;\n \n auto size() const { return distance(first,last); }\n friend std::ostream & operator<<(std::ostream & os, const range & r);\n};\n\nstd::ostream & operator<<(std::ostream & os, const range & r) {\n os << \"(size= \" << r.size() << \") \";\n std::copy(r.first, r.last, std::ostream_iterator<int>(std::cerr, \" \"));\n return os;\n}\n\nstd::vector<range> divide(range r) {\n auto mid = r.first + distance(r.first,r.last)\/2;\n return { {r.first,mid} , {mid, r.last} };\n}\n\nvoid sort_sequence(grppi::polymorphic_execution & exec, int n) {\n using namespace std;\n\n std::random_device rdev;\n std::uniform_int_distribution<> gen{1,1000};\n\n vector<int> v;\n for (int i=0; i<n; ++i) {\n v.push_back(gen(rdev));\n }\n \n range problem{begin(v), end(v)};\n\n auto res = grppi::divide_conquer(exec,\n problem,\n [](auto r) -> vector<range> {\n if (1>=r.size()) { return {r}; }\n else { return divide(r); }\n },\n [](auto x) { return x; },\n [](auto r1, auto r2) {\n std::inplace_merge(r1.first, r1.last, r2.last);\n return range{r1.first, r2.last};\n }\n );\n\n copy(begin(v), end(v), ostream_iterator<int>(cout, \" \"));\n cout << endl;\n}\n\nvoid print_message(const std::string & prog, const std::string & msg) {\n using namespace std;\n\n cerr << msg << endl;\n cerr << \"Usage: \" << prog << \" size mode\" << endl;\n cerr << \" size: Integer value with problem size\" << endl;\n cerr << \" mode:\" << endl;\n print_available_modes(cerr);\n}\n\n\nint main(int argc, char **argv) {\n \n using namespace std;\n\n if(argc < 3){\n print_message(argv[0], \"Invalid number of arguments.\");\n return -1;\n }\n\n int n = stoi(argv[1]);\n if(n <= 0){\n print_message(argv[0], \"Invalid problem size. Use a positive number.\");\n return -1;\n }\n\n if (!run_test(argv[2], sort_sequence, n)) {\n print_message(argv[0], \"Invalid policy.\");\n return -1;\n }\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>#include <openssl\/evp.h>\n#include <openssl\/rand.h>\n\n#include <common\/factory.h>\n\n#include <crypto\/crypto_random.h>\n\nnamespace {\n\ttypedef\tint (RAND_func)(unsigned char *, int);\n}\n\nclass CryptoRandomSessionRAND : public CryptoRandomSession {\n\tLogHandle log_;\n\tconst RAND_func *func_;\npublic:\n\tCryptoRandomSessionRAND(const RAND_func *func)\n\t: log_(\"\/crypto\/random\/session\/openssl\"),\n\t func_(func)\n\t{ }\n\n\t~CryptoRandomSessionRAND()\n\t{ }\n\n\tAction *generate(size_t len, EventCallback *cb)\n\t{\n\t\tASSERT(log_, len != 0);\n\n\t\t\/*\n\t\t * We process a single, large, linear byte buffer here rather\n\t\t * than going a BufferSegment at a time, even though the byte\n\t\t * buffer is less efficient than some alternatives, because\n\t\t * I am a bad person and I should feel bad.\n\t\t *\/\n\t\tuint8_t bytes[len];\n\t\tint rv = func_(bytes, sizeof bytes);\n\t\tif (rv == 0) {\n\t\t\tcb->param(Event::Error);\n\t\t\treturn (cb->schedule());\n\t\t}\n\t\tcb->param(Event(Event::Done, Buffer(bytes, sizeof bytes)));\n\t\treturn (cb->schedule());\n\t}\n};\n\nclass CryptoRandomMethodOpenSSL : public CryptoRandomMethod {\n\tLogHandle log_;\n\tstd::map<CryptoRandomType, const RAND_func *> func_map_;\npublic:\n\tCryptoRandomMethodOpenSSL(void)\n\t: log_(\"\/crypto\/random\/openssl\"),\n\t func_map_()\n\t{\n\t\tOpenSSL_add_all_algorithms();\n\n\t\tfunc_map_[CryptoTypeRNG] = RAND_bytes;\n\t\tfunc_map_[CryptoTypePRNG] = RAND_pseudo_bytes;\n\n\t\t\/* XXX Register. *\/\n\t}\n\n\t~CryptoRandomMethodOpenSSL()\n\t{\n\t\t\/* XXX Unregister. *\/\n\t}\n\n\t\/*\n\t * Synchronous randomness generation. May not succeed.\n\t *\/\n\tbool generate(CryptoRandomType func, size_t len, Buffer *out) const\n\t{\n\t\tstd::map<CryptoRandomType, const RAND_func *>::const_iterator it;\n\n\t\tit = func_map_.find(func);\n\t\tif (it == func_map_.end())\n\t\t\treturn (false);\n\n\t\tuint8_t bytes[len];\n\t\tint rv = it->second(bytes, sizeof bytes);\n\t\tif (rv == 0)\n\t\t\treturn (false);\n\n\t\tout->append(bytes, sizeof bytes);\n\t\treturn (true);\n\t}\n\n\tCryptoRandomSession *session(CryptoRandomType func) const\n\t{\n\t\tstd::map<CryptoRandomType, const RAND_func *>::const_iterator it;\n\n\t\tit = func_map_.find(func);\n\t\tif (it != func_map_.end())\n\t\t\treturn (new CryptoRandomSessionRAND(it->second));\n\t\treturn (NULL);\n\t}\n};\n\nnamespace {\n\tstatic CryptoRandomMethodOpenSSL crypto_random_method_openssl;\n}\nconst CryptoRandomMethod *CryptoRandomMethod::default_method = &crypto_random_method_openssl; \/* XXX *\/\n<commit_msg>Soothe clang's unease over my gratuitous and flagrant use of the const qualifier.<commit_after>#include <openssl\/evp.h>\n#include <openssl\/rand.h>\n\n#include <common\/factory.h>\n\n#include <crypto\/crypto_random.h>\n\nnamespace {\n\ttypedef\tint (RAND_func)(unsigned char *, int);\n}\n\nclass CryptoRandomSessionRAND : public CryptoRandomSession {\n\tLogHandle log_;\n\tRAND_func *func_;\npublic:\n\tCryptoRandomSessionRAND(RAND_func *func)\n\t: log_(\"\/crypto\/random\/session\/openssl\"),\n\t func_(func)\n\t{ }\n\n\t~CryptoRandomSessionRAND()\n\t{ }\n\n\tAction *generate(size_t len, EventCallback *cb)\n\t{\n\t\tASSERT(log_, len != 0);\n\n\t\t\/*\n\t\t * We process a single, large, linear byte buffer here rather\n\t\t * than going a BufferSegment at a time, even though the byte\n\t\t * buffer is less efficient than some alternatives, because\n\t\t * I am a bad person and I should feel bad.\n\t\t *\/\n\t\tuint8_t bytes[len];\n\t\tint rv = func_(bytes, sizeof bytes);\n\t\tif (rv == 0) {\n\t\t\tcb->param(Event::Error);\n\t\t\treturn (cb->schedule());\n\t\t}\n\t\tcb->param(Event(Event::Done, Buffer(bytes, sizeof bytes)));\n\t\treturn (cb->schedule());\n\t}\n};\n\nclass CryptoRandomMethodOpenSSL : public CryptoRandomMethod {\n\tLogHandle log_;\n\tstd::map<CryptoRandomType, RAND_func *> func_map_;\npublic:\n\tCryptoRandomMethodOpenSSL(void)\n\t: log_(\"\/crypto\/random\/openssl\"),\n\t func_map_()\n\t{\n\t\tOpenSSL_add_all_algorithms();\n\n\t\tfunc_map_[CryptoTypeRNG] = RAND_bytes;\n\t\tfunc_map_[CryptoTypePRNG] = RAND_pseudo_bytes;\n\n\t\t\/* XXX Register. *\/\n\t}\n\n\t~CryptoRandomMethodOpenSSL()\n\t{\n\t\t\/* XXX Unregister. *\/\n\t}\n\n\t\/*\n\t * Synchronous randomness generation. May not succeed.\n\t *\/\n\tbool generate(CryptoRandomType func, size_t len, Buffer *out) const\n\t{\n\t\tstd::map<CryptoRandomType, RAND_func *>::const_iterator it;\n\n\t\tit = func_map_.find(func);\n\t\tif (it == func_map_.end())\n\t\t\treturn (false);\n\n\t\tuint8_t bytes[len];\n\t\tint rv = it->second(bytes, sizeof bytes);\n\t\tif (rv == 0)\n\t\t\treturn (false);\n\n\t\tout->append(bytes, sizeof bytes);\n\t\treturn (true);\n\t}\n\n\tCryptoRandomSession *session(CryptoRandomType func) const\n\t{\n\t\tstd::map<CryptoRandomType, RAND_func *>::const_iterator it;\n\n\t\tit = func_map_.find(func);\n\t\tif (it != func_map_.end())\n\t\t\treturn (new CryptoRandomSessionRAND(it->second));\n\t\treturn (NULL);\n\t}\n};\n\nnamespace {\n\tstatic CryptoRandomMethodOpenSSL crypto_random_method_openssl;\n}\nconst CryptoRandomMethod *CryptoRandomMethod::default_method = &crypto_random_method_openssl; \/* XXX *\/\n<|endoftext|>"} {"text":"<commit_before>\/*=========================================================================\n\n Program: Visualization Toolkit\n Module: vtkImageToStructuredPoints.cxx\n\n Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen\n All rights reserved.\n See Copyright.txt or http:\/\/www.kitware.com\/Copyright.htm for details.\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notice for more information.\n\n=========================================================================*\/\n#include \"vtkImageToStructuredPoints.h\"\n\n#include \"vtkCellData.h\"\n#include \"vtkFieldData.h\"\n#include \"vtkObjectFactory.h\"\n#include \"vtkPointData.h\"\n#include \"vtkStructuredPoints.h\"\n\n#include <math.h>\n\nvtkCxxRevisionMacro(vtkImageToStructuredPoints, \"1.54\");\nvtkStandardNewMacro(vtkImageToStructuredPoints);\n\n\/\/----------------------------------------------------------------------------\nvtkImageToStructuredPoints::vtkImageToStructuredPoints()\n{\n this->Translate[0] = this->Translate[1] = this->Translate[2] = 0;\n this->NumberOfRequiredInputs = 1;\n this->SetNthOutput(0,vtkStructuredPoints::New());\n this->Outputs[0]->Delete();\n}\n\n\/\/----------------------------------------------------------------------------\nvtkImageToStructuredPoints::~vtkImageToStructuredPoints()\n{\n}\n\n\n\/\/----------------------------------------------------------------------------\nvoid vtkImageToStructuredPoints::PrintSelf(ostream& os, vtkIndent indent)\n{\n this->Superclass::PrintSelf(os,indent);\n}\n\n\/\/----------------------------------------------------------------------------\nvtkStructuredPoints *vtkImageToStructuredPoints::GetOutput()\n{\n if (this->NumberOfOutputs < 1)\n {\n return NULL;\n }\n \n return (vtkStructuredPoints *)(this->Outputs[0]);\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkImageToStructuredPoints::SetInput(vtkImageData *input)\n{\n this->vtkProcessObject::SetNthInput(0, input);\n}\n\n\/\/----------------------------------------------------------------------------\nvtkImageData *vtkImageToStructuredPoints::GetInput()\n{\n if (this->NumberOfInputs < 1)\n {\n return NULL;\n }\n \n return (vtkImageData *)(this->Inputs[0]);\n}\n\n\n\/\/----------------------------------------------------------------------------\nvoid vtkImageToStructuredPoints::SetVectorInput(vtkImageData *input)\n{\n this->vtkProcessObject::SetNthInput(1, input);\n}\n\n\/\/----------------------------------------------------------------------------\nvtkImageData *vtkImageToStructuredPoints::GetVectorInput()\n{\n if (this->NumberOfInputs < 2)\n {\n return NULL;\n }\n \n return (vtkImageData *)(this->Inputs[1]);\n}\n\n\n\n\n\/\/----------------------------------------------------------------------------\nvoid vtkImageToStructuredPoints::Execute()\n{\n int uExtent[6];\n int *wExtent;\n\n int idxX, idxY, idxZ;\n int maxX = 0;\n int maxY = 0;\n int maxZ = 0;;\n int inIncX, inIncY, inIncZ, rowLength;\n unsigned char *inPtr1, *inPtr, *outPtr;\n vtkStructuredPoints *output = this->GetOutput();\n vtkImageData *data = this->GetInput();\n vtkImageData *vData = this->GetVectorInput();\n \n if (!data && !vData)\n {\n vtkErrorMacro(\"Unable to generate data!\");\n return;\n }\n\n output->GetUpdateExtent(uExtent);\n output->SetExtent(uExtent);\n\n uExtent[0] += this->Translate[0];\n uExtent[1] += this->Translate[0];\n uExtent[2] += this->Translate[1];\n uExtent[3] += this->Translate[1];\n uExtent[4] += this->Translate[2];\n uExtent[5] += this->Translate[2];\n \n \/\/ if the data extent matches the update extent then just pass the data\n \/\/ otherwise we must reformat and copy the data\n if (data)\n {\n wExtent = data->GetExtent();\n if (wExtent[0] == uExtent[0] && wExtent[1] == uExtent[1] &&\n wExtent[2] == uExtent[2] && wExtent[3] == uExtent[3] &&\n wExtent[4] == uExtent[4] && wExtent[5] == uExtent[5])\n {\n if (data->GetPointData())\n {\n output->GetPointData()->PassData(data->GetPointData());\n }\n if (data->GetCellData())\n {\n output->GetCellData()->PassData(data->GetCellData());\n }\n if (data->GetFieldData())\n {\n output->GetFieldData()->ShallowCopy(data->GetFieldData());\n }\n }\n else\n {\n inPtr = (unsigned char *) data->GetScalarPointerForExtent(uExtent);\n outPtr = (unsigned char *) output->GetScalarPointer();\n \n \/\/ Get increments to march through data \n data->GetIncrements(inIncX, inIncY, inIncZ);\n \n \/\/ find the region to loop over\n rowLength = (uExtent[1] - uExtent[0]+1)*inIncX*data->GetScalarSize();\n maxX = uExtent[1] - uExtent[0]; \n maxY = uExtent[3] - uExtent[2]; \n maxZ = uExtent[5] - uExtent[4];\n inIncY *= data->GetScalarSize();\n inIncZ *= data->GetScalarSize();\n \n \/\/ Loop through output pixels\n for (idxZ = 0; idxZ <= maxZ; idxZ++)\n {\n inPtr1 = inPtr + idxZ*inIncZ;\n for (idxY = 0; idxY <= maxY; idxY++)\n {\n memcpy(outPtr,inPtr1,rowLength);\n inPtr1 += inIncY;\n outPtr += rowLength;\n }\n }\n }\n }\n \n if (vData)\n {\n \/\/ if the data extent matches the update extent then just pass the data\n \/\/ otherwise we must reformat and copy the data\n wExtent = vData->GetExtent();\n if (wExtent[0] == uExtent[0] && wExtent[1] == uExtent[1] &&\n wExtent[2] == uExtent[2] && wExtent[3] == uExtent[3] &&\n wExtent[4] == uExtent[4] && wExtent[5] == uExtent[5])\n {\n output->GetPointData()->SetVectors(vData->GetPointData()->GetScalars());\n }\n else\n {\n vtkDataArray *fv = vtkDataArray::CreateDataArray(vData->GetScalarType());\n float *inPtr2 = (float *)(vData->GetScalarPointerForExtent(uExtent));\n \n fv->SetNumberOfComponents(3);\n fv->SetNumberOfTuples((maxZ+1)*(maxY+1)*(maxX+1));\n vData->GetContinuousIncrements(uExtent, inIncX, inIncY, inIncZ);\n int numComp = vData->GetNumberOfScalarComponents();\n int idx = 0;\n \n \/\/ Loop through ouput pixels\n for (idxZ = 0; idxZ <= maxZ; idxZ++)\n {\n for (idxY = 0; idxY <= maxY; idxY++)\n {\n for (idxX = 0; idxX <= maxX; idxX++)\n {\n fv->SetTuple(idx,inPtr2);\n inPtr2 += numComp;\n idx++;\n }\n inPtr2 += inIncY;\n }\n inPtr2 += inIncZ;\n }\n output->GetPointData()->SetVectors(fv);\n fv->Delete();\n }\n }\n}\n\n\/\/----------------------------------------------------------------------------\n\/\/ Copy WholeExtent, Spacing and Origin.\nvoid vtkImageToStructuredPoints::ExecuteInformation()\n{\n vtkImageData *input = this->GetInput();\n vtkImageData *vInput = this->GetVectorInput();\n vtkStructuredPoints *output = this->GetOutput();\n int whole[6], *tmp;\n double *spacing, origin[3];\n \n if (output == NULL)\n {\n return;\n }\n \n if (input)\n {\n output->SetScalarType(input->GetScalarType());\n output->SetNumberOfScalarComponents(input->GetNumberOfScalarComponents());\n input->GetWholeExtent(whole); \n spacing = input->GetSpacing();\n input->GetOrigin(origin);\n }\n else if (vInput)\n {\n whole[0] = whole[2] = whole[4] = -VTK_LARGE_INTEGER;\n whole[1] = whole[3] = whole[5] = VTK_LARGE_INTEGER;\n spacing = vInput->GetSpacing();\n vInput->GetOrigin(origin);\n }\n else\n {\n return;\n }\n \/\/ intersections for whole extent\n if (vInput)\n {\n tmp = vInput->GetWholeExtent();\n if (tmp[0] > whole[0]) {whole[0] = tmp[0];}\n if (tmp[2] > whole[2]) {whole[2] = tmp[2];}\n if (tmp[4] > whole[4]) {whole[4] = tmp[4];}\n if (tmp[1] < whole[1]) {whole[1] = tmp[1];}\n if (tmp[3] < whole[1]) {whole[3] = tmp[3];}\n if (tmp[5] < whole[1]) {whole[5] = tmp[5];}\n }\n \n \/\/ slide min extent to 0,0,0 (I Hate this !!!!)\n this->Translate[0] = whole[0];\n this->Translate[1] = whole[2];\n this->Translate[2] = whole[4];\n \n origin[0] += spacing[0] * whole[0];\n origin[1] += spacing[1] * whole[2];\n origin[2] += spacing[2] * whole[4];\n whole[1] -= whole[0];\n whole[3] -= whole[2];\n whole[5] -= whole[4];\n whole[0] = whole[2] = whole[4] = 0;\n \n output->SetWholeExtent(whole);\n \/\/ Now should Origin and Spacing really be part of information?\n \/\/ How about xyx arrays in RectilinearGrid of Points in StructuredGrid?\n output->SetOrigin(origin);\n output->SetSpacing(spacing);\n}\n\n\/\/----------------------------------------------------------------------------\nvtkStructuredPoints *vtkImageToStructuredPoints::GetOutput(int idx)\n{\n return (vtkStructuredPoints *) this->vtkSource::GetOutput(idx); \n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkImageToStructuredPoints::ComputeInputUpdateExtents(vtkDataObject *data)\n{\n vtkStructuredPoints *output = (vtkStructuredPoints*)data;\n int ext[6];\n vtkImageData *input;\n\n output->GetUpdateExtent(ext);\n ext[0] += this->Translate[0];\n ext[1] += this->Translate[0];\n ext[2] += this->Translate[1];\n ext[3] += this->Translate[1];\n ext[4] += this->Translate[2];\n ext[5] += this->Translate[2];\n \n input = this->GetInput();\n if (input)\n {\n input->SetUpdateExtent(ext);\n }\n\n input = this->GetVectorInput();\n if (input)\n {\n input->SetUpdateExtent(ext);\n }\n}\n\n\n\n\n<commit_msg>BUG: Do not crash if input has no arrays.<commit_after>\/*=========================================================================\n\n Program: Visualization Toolkit\n Module: vtkImageToStructuredPoints.cxx\n\n Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen\n All rights reserved.\n See Copyright.txt or http:\/\/www.kitware.com\/Copyright.htm for details.\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notice for more information.\n\n=========================================================================*\/\n#include \"vtkImageToStructuredPoints.h\"\n\n#include \"vtkCellData.h\"\n#include \"vtkFieldData.h\"\n#include \"vtkObjectFactory.h\"\n#include \"vtkPointData.h\"\n#include \"vtkStructuredPoints.h\"\n\n#include <math.h>\n\nvtkCxxRevisionMacro(vtkImageToStructuredPoints, \"1.55\");\nvtkStandardNewMacro(vtkImageToStructuredPoints);\n\n\/\/----------------------------------------------------------------------------\nvtkImageToStructuredPoints::vtkImageToStructuredPoints()\n{\n this->Translate[0] = this->Translate[1] = this->Translate[2] = 0;\n this->NumberOfRequiredInputs = 1;\n this->SetNthOutput(0,vtkStructuredPoints::New());\n this->Outputs[0]->Delete();\n}\n\n\/\/----------------------------------------------------------------------------\nvtkImageToStructuredPoints::~vtkImageToStructuredPoints()\n{\n}\n\n\n\/\/----------------------------------------------------------------------------\nvoid vtkImageToStructuredPoints::PrintSelf(ostream& os, vtkIndent indent)\n{\n this->Superclass::PrintSelf(os,indent);\n}\n\n\/\/----------------------------------------------------------------------------\nvtkStructuredPoints *vtkImageToStructuredPoints::GetOutput()\n{\n if (this->NumberOfOutputs < 1)\n {\n return NULL;\n }\n \n return (vtkStructuredPoints *)(this->Outputs[0]);\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkImageToStructuredPoints::SetInput(vtkImageData *input)\n{\n this->vtkProcessObject::SetNthInput(0, input);\n}\n\n\/\/----------------------------------------------------------------------------\nvtkImageData *vtkImageToStructuredPoints::GetInput()\n{\n if (this->NumberOfInputs < 1)\n {\n return NULL;\n }\n \n return (vtkImageData *)(this->Inputs[0]);\n}\n\n\n\/\/----------------------------------------------------------------------------\nvoid vtkImageToStructuredPoints::SetVectorInput(vtkImageData *input)\n{\n this->vtkProcessObject::SetNthInput(1, input);\n}\n\n\/\/----------------------------------------------------------------------------\nvtkImageData *vtkImageToStructuredPoints::GetVectorInput()\n{\n if (this->NumberOfInputs < 2)\n {\n return NULL;\n }\n \n return (vtkImageData *)(this->Inputs[1]);\n}\n\n\n\n\n\/\/----------------------------------------------------------------------------\nvoid vtkImageToStructuredPoints::Execute()\n{\n int uExtent[6];\n int *wExtent;\n\n int idxX, idxY, idxZ;\n int maxX = 0;\n int maxY = 0;\n int maxZ = 0;;\n int inIncX, inIncY, inIncZ, rowLength;\n unsigned char *inPtr1, *inPtr, *outPtr;\n vtkStructuredPoints *output = this->GetOutput();\n vtkImageData *data = this->GetInput();\n vtkImageData *vData = this->GetVectorInput();\n \n if (!data && !vData)\n {\n vtkErrorMacro(\"Unable to generate data!\");\n return;\n }\n\n output->GetUpdateExtent(uExtent);\n output->SetExtent(uExtent);\n\n uExtent[0] += this->Translate[0];\n uExtent[1] += this->Translate[0];\n uExtent[2] += this->Translate[1];\n uExtent[3] += this->Translate[1];\n uExtent[4] += this->Translate[2];\n uExtent[5] += this->Translate[2];\n \n \/\/ if the data extent matches the update extent then just pass the data\n \/\/ otherwise we must reformat and copy the data\n if (data)\n {\n wExtent = data->GetExtent();\n if (wExtent[0] == uExtent[0] && wExtent[1] == uExtent[1] &&\n wExtent[2] == uExtent[2] && wExtent[3] == uExtent[3] &&\n wExtent[4] == uExtent[4] && wExtent[5] == uExtent[5])\n {\n if (data->GetPointData())\n {\n output->GetPointData()->PassData(data->GetPointData());\n }\n if (data->GetCellData())\n {\n output->GetCellData()->PassData(data->GetCellData());\n }\n if (data->GetFieldData())\n {\n output->GetFieldData()->ShallowCopy(data->GetFieldData());\n }\n }\n else\n {\n inPtr = (unsigned char *) data->GetScalarPointerForExtent(uExtent);\n outPtr = (unsigned char *) output->GetScalarPointer();\n\n \/\/ Make sure there are data.\n if(!inPtr || !outPtr)\n {\n output->Initialize();\n return;\n }\n\n \/\/ Get increments to march through data \n data->GetIncrements(inIncX, inIncY, inIncZ);\n \n \/\/ find the region to loop over\n rowLength = (uExtent[1] - uExtent[0]+1)*inIncX*data->GetScalarSize();\n maxX = uExtent[1] - uExtent[0]; \n maxY = uExtent[3] - uExtent[2]; \n maxZ = uExtent[5] - uExtent[4];\n inIncY *= data->GetScalarSize();\n inIncZ *= data->GetScalarSize();\n \n \/\/ Loop through output pixels\n for (idxZ = 0; idxZ <= maxZ; idxZ++)\n {\n inPtr1 = inPtr + idxZ*inIncZ;\n for (idxY = 0; idxY <= maxY; idxY++)\n {\n memcpy(outPtr,inPtr1,rowLength);\n inPtr1 += inIncY;\n outPtr += rowLength;\n }\n }\n }\n }\n \n if (vData)\n {\n \/\/ if the data extent matches the update extent then just pass the data\n \/\/ otherwise we must reformat and copy the data\n wExtent = vData->GetExtent();\n if (wExtent[0] == uExtent[0] && wExtent[1] == uExtent[1] &&\n wExtent[2] == uExtent[2] && wExtent[3] == uExtent[3] &&\n wExtent[4] == uExtent[4] && wExtent[5] == uExtent[5])\n {\n output->GetPointData()->SetVectors(vData->GetPointData()->GetScalars());\n }\n else\n {\n vtkDataArray *fv = vtkDataArray::CreateDataArray(vData->GetScalarType());\n float *inPtr2 = (float *)(vData->GetScalarPointerForExtent(uExtent));\n\n \/\/ Make sure there are data.\n if(!inPtr2)\n {\n output->Initialize();\n return;\n }\n\n fv->SetNumberOfComponents(3);\n fv->SetNumberOfTuples((maxZ+1)*(maxY+1)*(maxX+1));\n vData->GetContinuousIncrements(uExtent, inIncX, inIncY, inIncZ);\n int numComp = vData->GetNumberOfScalarComponents();\n int idx = 0;\n \n \/\/ Loop through ouput pixels\n for (idxZ = 0; idxZ <= maxZ; idxZ++)\n {\n for (idxY = 0; idxY <= maxY; idxY++)\n {\n for (idxX = 0; idxX <= maxX; idxX++)\n {\n fv->SetTuple(idx,inPtr2);\n inPtr2 += numComp;\n idx++;\n }\n inPtr2 += inIncY;\n }\n inPtr2 += inIncZ;\n }\n output->GetPointData()->SetVectors(fv);\n fv->Delete();\n }\n }\n}\n\n\/\/----------------------------------------------------------------------------\n\/\/ Copy WholeExtent, Spacing and Origin.\nvoid vtkImageToStructuredPoints::ExecuteInformation()\n{\n vtkImageData *input = this->GetInput();\n vtkImageData *vInput = this->GetVectorInput();\n vtkStructuredPoints *output = this->GetOutput();\n int whole[6], *tmp;\n double *spacing, origin[3];\n \n if (output == NULL)\n {\n return;\n }\n \n if (input)\n {\n output->SetScalarType(input->GetScalarType());\n output->SetNumberOfScalarComponents(input->GetNumberOfScalarComponents());\n input->GetWholeExtent(whole); \n spacing = input->GetSpacing();\n input->GetOrigin(origin);\n }\n else if (vInput)\n {\n whole[0] = whole[2] = whole[4] = -VTK_LARGE_INTEGER;\n whole[1] = whole[3] = whole[5] = VTK_LARGE_INTEGER;\n spacing = vInput->GetSpacing();\n vInput->GetOrigin(origin);\n }\n else\n {\n return;\n }\n \/\/ intersections for whole extent\n if (vInput)\n {\n tmp = vInput->GetWholeExtent();\n if (tmp[0] > whole[0]) {whole[0] = tmp[0];}\n if (tmp[2] > whole[2]) {whole[2] = tmp[2];}\n if (tmp[4] > whole[4]) {whole[4] = tmp[4];}\n if (tmp[1] < whole[1]) {whole[1] = tmp[1];}\n if (tmp[3] < whole[1]) {whole[3] = tmp[3];}\n if (tmp[5] < whole[1]) {whole[5] = tmp[5];}\n }\n \n \/\/ slide min extent to 0,0,0 (I Hate this !!!!)\n this->Translate[0] = whole[0];\n this->Translate[1] = whole[2];\n this->Translate[2] = whole[4];\n \n origin[0] += spacing[0] * whole[0];\n origin[1] += spacing[1] * whole[2];\n origin[2] += spacing[2] * whole[4];\n whole[1] -= whole[0];\n whole[3] -= whole[2];\n whole[5] -= whole[4];\n whole[0] = whole[2] = whole[4] = 0;\n \n output->SetWholeExtent(whole);\n \/\/ Now should Origin and Spacing really be part of information?\n \/\/ How about xyx arrays in RectilinearGrid of Points in StructuredGrid?\n output->SetOrigin(origin);\n output->SetSpacing(spacing);\n}\n\n\/\/----------------------------------------------------------------------------\nvtkStructuredPoints *vtkImageToStructuredPoints::GetOutput(int idx)\n{\n return (vtkStructuredPoints *) this->vtkSource::GetOutput(idx); \n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkImageToStructuredPoints::ComputeInputUpdateExtents(vtkDataObject *data)\n{\n vtkStructuredPoints *output = (vtkStructuredPoints*)data;\n int ext[6];\n vtkImageData *input;\n\n output->GetUpdateExtent(ext);\n ext[0] += this->Translate[0];\n ext[1] += this->Translate[0];\n ext[2] += this->Translate[1];\n ext[3] += this->Translate[1];\n ext[4] += this->Translate[2];\n ext[5] += this->Translate[2];\n \n input = this->GetInput();\n if (input)\n {\n input->SetUpdateExtent(ext);\n }\n\n input = this->GetVectorInput();\n if (input)\n {\n input->SetUpdateExtent(ext);\n }\n}\n\n\n\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n*\n* Zero-config node ID negotiation\n* -------------------------------\n*\n* A heartbeat message is a message with a 8 byte unique serial number as payload.\n* A regular message is any message that is not a heartbeat message.\n*\n* All nodes MUST obey these four rules:\n*\n* a) At a given point in time, a node MUST consider a node ID taken (by others)\n* if any of the following is true:\n* - the node received a (not self-emitted) heartbeat message with that node ID\n* within the last second\n* - the node attempted and failed at sending a heartbeat message with that\n* node ID within the last second (failed in the sense of not ACK'd)\n*\n* b) At a given point in time, a node MUST NOT consider a node ID self-assigned\n* if, within the last second, it did not succeed in sending a heartbeat\n* message with that node ID.\n*\n* c) At a given point in time, a node MUST NOT send any heartbeat message with\n* a node ID that is taken.\n*\n* d) At a given point in time, a node MUST NOT send any regular message with\n* a node ID that is not self-assigned.\n*\n* Hardware allocation\n* -------------------\n* RX FIFO0:\n* - filter bank 0: heartbeat messages\n*\/\n\n#include \"interface_can.hpp\"\n#include <unordered_map>\n#include \"fibre\/crc.hpp\"\n#include \"freertos_vars.h\"\n#include \"utils.h\"\n\n#include <can.h>\n#include <cmsis_os.h>\n#include <stm32f4xx_hal.h>\n\n#include <odrive_main.h>\n\nstd::unordered_map<CAN_HandleTypeDef *, ODriveCAN *> ctxMap;\n\n\/\/ Constructor is called by communication.cpp and the handle is assigned appropriately\nODriveCAN::ODriveCAN(CAN_HandleTypeDef *handle, ODriveCAN::Config_t &config)\n : handle_{handle},\n config_{config} {\n ctxMap[handle_] = this;\n}\n\nvoid ODriveCAN::can_server_thread() {\n CAN_message_t heartbeat;\n heartbeat.id = 0x700 + config_.node_id;\n uint32_t lastHeartbeatTick = osKernelSysTick();\n\n for (;;) {\n CAN_message_t rxmsg;\n\n osSemaphoreWait(sem_can, 10);\n while (available()) {\n read(rxmsg);\n write(rxmsg);\n }\n\n \/\/ Handle heartbeat message\n heartbeat.buf[0] = axes[0]->error_;\n heartbeat.buf[1] = axes[0]->current_state_;\n heartbeat.buf[2] = axes[1]->error_;\n heartbeat.buf[3] = axes[2]->current_state_;\n uint32_t now = osKernelSysTick();\n if(now - lastHeartbeatTick >= 100){\n write(heartbeat);\n lastHeartbeatTick = now;\n }\n \n HAL_CAN_ActivateNotification(handle_, CAN_IT_RX_FIFO0_MSG_PENDING);\n }\n}\n\nstatic void can_server_thread_wrapper(void *ctx) {\n reinterpret_cast<ODriveCAN *>(ctx)->can_server_thread();\n reinterpret_cast<ODriveCAN *>(ctx)->thread_id_valid_ = false;\n}\n\nbool ODriveCAN::start_can_server() {\n HAL_StatusTypeDef status;\n\n set_baud_rate(config_.baud);\n status = HAL_CAN_Init(handle_);\n if (status != HAL_OK)\n return false;\n\n CAN_FilterTypeDef filter;\n filter.FilterActivation = ENABLE;\n filter.FilterBank = 0;\n filter.FilterFIFOAssignment = CAN_RX_FIFO0;\n filter.FilterIdHigh = 0x0000;\n filter.FilterIdLow = 0x0000;\n filter.FilterMaskIdHigh = 0x0000;\n filter.FilterMaskIdLow = 0x0000;\n filter.FilterMode = CAN_FILTERMODE_IDMASK;\n filter.FilterScale = CAN_FILTERSCALE_32BIT;\n\n status = HAL_CAN_ConfigFilter(handle_, &filter);\n if (status != HAL_OK)\n return false;\n\n status = HAL_CAN_Start(handle_);\n if (status != HAL_OK)\n return false;\n\n status = HAL_CAN_ActivateNotification(handle_,\n \/\/ CAN_IT_TX_MAILBOX_EMPTY |\n CAN_IT_RX_FIFO0_MSG_PENDING | CAN_IT_RX_FIFO1_MSG_PENDING \/* we probably only want this *\/\n \/\/ CAN_IT_RX_FIFO0_FULL | CAN_IT_RX_FIFO1_FULL\n \/\/ CAN_IT_RX_FIFO0_OVERRUN | CAN_IT_RX_FIFO1_OVERRUN |\n \/\/ CAN_IT_WAKEUP | CAN_IT_SLEEP_ACK |\n \/\/ CAN_IT_ERROR_WARNING | CAN_IT_ERROR_PASSIVE |\n \/\/ CAN_IT_BUSOFF | CAN_IT_LAST_ERROR_CODE |\n \/\/ | CAN_IT_ERROR\n );\n if (status != HAL_OK)\n return false;\n\n osThreadDef(can_server_thread_def, can_server_thread_wrapper, osPriorityNormal, 0, 512);\n thread_id_ = osThreadCreate(osThread(can_server_thread_def), this);\n thread_id_valid_ = true;\n\n return true;\n}\n\n\n\n\/\/ Send a CAN message on the bus\nuint32_t ODriveCAN::write(CAN_message_t &txmsg) {\n CAN_TxHeaderTypeDef header;\n header.StdId = txmsg.id;\n header.ExtId = txmsg.id;\n header.IDE = txmsg.isExt ? CAN_ID_EXT : CAN_ID_STD;\n header.RTR = CAN_RTR_DATA;\n header.DLC = txmsg.len;\n header.TransmitGlobalTime = FunctionalState::DISABLE;\n\n uint32_t retTxMailbox;\n if (HAL_CAN_GetTxMailboxesFreeLevel(handle_) > 0)\n HAL_CAN_AddTxMessage(handle_, &header, txmsg.buf, &retTxMailbox);\n\n return retTxMailbox;\n}\n\nuint32_t ODriveCAN::available() {\n return (HAL_CAN_GetRxFifoFillLevel(handle_, CAN_RX_FIFO0) + HAL_CAN_GetRxFifoFillLevel(handle_, CAN_RX_FIFO1));\n}\n\nbool ODriveCAN::read(CAN_message_t &rxmsg) {\n CAN_RxHeaderTypeDef header;\n bool validRead = false;\n if (HAL_CAN_GetRxFifoFillLevel(handle_, CAN_RX_FIFO0) > 0) {\n HAL_CAN_GetRxMessage(handle_, CAN_RX_FIFO0, &header, rxmsg.buf);\n validRead = true;\n } else if (HAL_CAN_GetRxFifoFillLevel(handle_, CAN_RX_FIFO1) > 0) {\n HAL_CAN_GetRxMessage(handle_, CAN_RX_FIFO1, &header, rxmsg.buf);\n validRead = true;\n }\n\n rxmsg.isExt = header.IDE;\n rxmsg.id = rxmsg.isExt ? header.ExtId : header.StdId; \/\/ If it's an extended message, pass the extended ID\n rxmsg.len = header.DLC;\n\n return validRead;\n}\n\n\n\/\/ Set one of only a few common baud rates. CAN doesn't do arbitrary baud rates well due to the time-quanta issue. \n\/\/ 21 TQ allows for easy sampling at exactly 80% (recommended by Vector Informatik GmbH for high reliability systems)\n\/\/ Conveniently, the CAN peripheral's 42MHz clock lets us easily create 21TQs for all common baud rates\nvoid ODriveCAN::set_baud_rate(uint32_t baudRate) {\n switch (baudRate) {\n case CAN_BAUD_125K:\n handle_->Init.Prescaler = 16; \/\/ 21 TQ's\n config_.baud = baudRate;\n break;\n\n case CAN_BAUD_250K:\n handle_->Init.Prescaler = 8; \/\/ 21 TQ's\n config_.baud = baudRate;\n break;\n\n case CAN_BAUD_500K:\n handle_->Init.Prescaler = 4; \/\/ 21 TQ's\n config_.baud = baudRate;\n break;\n\n case CAN_BAUD_1000K:\n handle_->Init.Prescaler = 2; \/\/ 21 TQ's\n config_.baud = baudRate;\n break;\n\n default:\n break; \/\/ baudRate is invalid, so do nothing\n }\n}\n\nvoid ODriveCAN::set_node_id(uint8_t nodeID) {\n \/\/ Allow for future nodeID validation by making this a set function\n config_.node_id = nodeID;\n}\n\nvoid HAL_CAN_TxMailbox0CompleteCallback(CAN_HandleTypeDef *hcan) {}\nvoid HAL_CAN_TxMailbox1CompleteCallback(CAN_HandleTypeDef *hcan) {}\nvoid HAL_CAN_TxMailbox2CompleteCallback(CAN_HandleTypeDef *hcan) {}\nvoid HAL_CAN_TxMailbox0AbortCallback(CAN_HandleTypeDef *hcan) {}\nvoid HAL_CAN_TxMailbox1AbortCallback(CAN_HandleTypeDef *hcan) {}\nvoid HAL_CAN_TxMailbox2AbortCallback(CAN_HandleTypeDef *hcan) {}\nvoid HAL_CAN_RxFifo0MsgPendingCallback(CAN_HandleTypeDef *hcan) {\n HAL_CAN_DeactivateNotification(hcan, CAN_IT_RX_FIFO0_MSG_PENDING);\n osSemaphoreRelease(sem_can);\n}\nvoid HAL_CAN_RxFifo0FullCallback(CAN_HandleTypeDef *hcan) {\n \/\/ osSemaphoreRelease(sem_can);\n}\nvoid HAL_CAN_RxFifo1MsgPendingCallback(CAN_HandleTypeDef *hcan) {}\nvoid HAL_CAN_RxFifo1FullCallback(CAN_HandleTypeDef *hcan) {}\nvoid HAL_CAN_SleepCallback(CAN_HandleTypeDef *hcan) {}\nvoid HAL_CAN_WakeUpFromRxMsgCallback(CAN_HandleTypeDef *hcan) {}\nvoid HAL_CAN_ErrorCallback(CAN_HandleTypeDef *hcan) {\n HAL_CAN_ResetError(hcan);\n}\n<commit_msg>We don't have an axis 2...<commit_after>\/*\n*\n* Zero-config node ID negotiation\n* -------------------------------\n*\n* A heartbeat message is a message with a 8 byte unique serial number as payload.\n* A regular message is any message that is not a heartbeat message.\n*\n* All nodes MUST obey these four rules:\n*\n* a) At a given point in time, a node MUST consider a node ID taken (by others)\n* if any of the following is true:\n* - the node received a (not self-emitted) heartbeat message with that node ID\n* within the last second\n* - the node attempted and failed at sending a heartbeat message with that\n* node ID within the last second (failed in the sense of not ACK'd)\n*\n* b) At a given point in time, a node MUST NOT consider a node ID self-assigned\n* if, within the last second, it did not succeed in sending a heartbeat\n* message with that node ID.\n*\n* c) At a given point in time, a node MUST NOT send any heartbeat message with\n* a node ID that is taken.\n*\n* d) At a given point in time, a node MUST NOT send any regular message with\n* a node ID that is not self-assigned.\n*\n* Hardware allocation\n* -------------------\n* RX FIFO0:\n* - filter bank 0: heartbeat messages\n*\/\n\n#include \"interface_can.hpp\"\n#include <unordered_map>\n#include \"fibre\/crc.hpp\"\n#include \"freertos_vars.h\"\n#include \"utils.h\"\n\n#include <can.h>\n#include <cmsis_os.h>\n#include <stm32f4xx_hal.h>\n\n#include <odrive_main.h>\n\nstd::unordered_map<CAN_HandleTypeDef *, ODriveCAN *> ctxMap;\n\n\/\/ Constructor is called by communication.cpp and the handle is assigned appropriately\nODriveCAN::ODriveCAN(CAN_HandleTypeDef *handle, ODriveCAN::Config_t &config)\n : handle_{handle},\n config_{config} {\n ctxMap[handle_] = this;\n}\n\nvoid ODriveCAN::can_server_thread() {\n CAN_message_t heartbeat;\n heartbeat.id = 0x700 + config_.node_id;\n uint32_t lastHeartbeatTick = osKernelSysTick();\n\n for (;;) {\n CAN_message_t rxmsg;\n\n osSemaphoreWait(sem_can, 10);\n while (available()) {\n read(rxmsg);\n write(rxmsg);\n }\n\n \/\/ Handle heartbeat message\n heartbeat.buf[0] = axes[0]->error_;\n heartbeat.buf[1] = axes[0]->current_state_;\n heartbeat.buf[2] = axes[1]->error_;\n heartbeat.buf[3] = axes[1]->current_state_;\n uint32_t now = osKernelSysTick();\n if(now - lastHeartbeatTick >= 100){\n write(heartbeat);\n lastHeartbeatTick = now;\n }\n \n HAL_CAN_ActivateNotification(handle_, CAN_IT_RX_FIFO0_MSG_PENDING);\n }\n}\n\nstatic void can_server_thread_wrapper(void *ctx) {\n reinterpret_cast<ODriveCAN *>(ctx)->can_server_thread();\n reinterpret_cast<ODriveCAN *>(ctx)->thread_id_valid_ = false;\n}\n\nbool ODriveCAN::start_can_server() {\n HAL_StatusTypeDef status;\n\n set_baud_rate(config_.baud);\n status = HAL_CAN_Init(handle_);\n if (status != HAL_OK)\n return false;\n\n CAN_FilterTypeDef filter;\n filter.FilterActivation = ENABLE;\n filter.FilterBank = 0;\n filter.FilterFIFOAssignment = CAN_RX_FIFO0;\n filter.FilterIdHigh = 0x0000;\n filter.FilterIdLow = 0x0000;\n filter.FilterMaskIdHigh = 0x0000;\n filter.FilterMaskIdLow = 0x0000;\n filter.FilterMode = CAN_FILTERMODE_IDMASK;\n filter.FilterScale = CAN_FILTERSCALE_32BIT;\n\n status = HAL_CAN_ConfigFilter(handle_, &filter);\n if (status != HAL_OK)\n return false;\n\n status = HAL_CAN_Start(handle_);\n if (status != HAL_OK)\n return false;\n\n status = HAL_CAN_ActivateNotification(handle_,\n \/\/ CAN_IT_TX_MAILBOX_EMPTY |\n CAN_IT_RX_FIFO0_MSG_PENDING | CAN_IT_RX_FIFO1_MSG_PENDING \/* we probably only want this *\/\n \/\/ CAN_IT_RX_FIFO0_FULL | CAN_IT_RX_FIFO1_FULL\n \/\/ CAN_IT_RX_FIFO0_OVERRUN | CAN_IT_RX_FIFO1_OVERRUN |\n \/\/ CAN_IT_WAKEUP | CAN_IT_SLEEP_ACK |\n \/\/ CAN_IT_ERROR_WARNING | CAN_IT_ERROR_PASSIVE |\n \/\/ CAN_IT_BUSOFF | CAN_IT_LAST_ERROR_CODE |\n \/\/ | CAN_IT_ERROR\n );\n if (status != HAL_OK)\n return false;\n\n osThreadDef(can_server_thread_def, can_server_thread_wrapper, osPriorityNormal, 0, 512);\n thread_id_ = osThreadCreate(osThread(can_server_thread_def), this);\n thread_id_valid_ = true;\n\n return true;\n}\n\n\n\n\/\/ Send a CAN message on the bus\nuint32_t ODriveCAN::write(CAN_message_t &txmsg) {\n CAN_TxHeaderTypeDef header;\n header.StdId = txmsg.id;\n header.ExtId = txmsg.id;\n header.IDE = txmsg.isExt ? CAN_ID_EXT : CAN_ID_STD;\n header.RTR = CAN_RTR_DATA;\n header.DLC = txmsg.len;\n header.TransmitGlobalTime = FunctionalState::DISABLE;\n\n uint32_t retTxMailbox;\n if (HAL_CAN_GetTxMailboxesFreeLevel(handle_) > 0)\n HAL_CAN_AddTxMessage(handle_, &header, txmsg.buf, &retTxMailbox);\n\n return retTxMailbox;\n}\n\nuint32_t ODriveCAN::available() {\n return (HAL_CAN_GetRxFifoFillLevel(handle_, CAN_RX_FIFO0) + HAL_CAN_GetRxFifoFillLevel(handle_, CAN_RX_FIFO1));\n}\n\nbool ODriveCAN::read(CAN_message_t &rxmsg) {\n CAN_RxHeaderTypeDef header;\n bool validRead = false;\n if (HAL_CAN_GetRxFifoFillLevel(handle_, CAN_RX_FIFO0) > 0) {\n HAL_CAN_GetRxMessage(handle_, CAN_RX_FIFO0, &header, rxmsg.buf);\n validRead = true;\n } else if (HAL_CAN_GetRxFifoFillLevel(handle_, CAN_RX_FIFO1) > 0) {\n HAL_CAN_GetRxMessage(handle_, CAN_RX_FIFO1, &header, rxmsg.buf);\n validRead = true;\n }\n\n rxmsg.isExt = header.IDE;\n rxmsg.id = rxmsg.isExt ? header.ExtId : header.StdId; \/\/ If it's an extended message, pass the extended ID\n rxmsg.len = header.DLC;\n\n return validRead;\n}\n\n\n\/\/ Set one of only a few common baud rates. CAN doesn't do arbitrary baud rates well due to the time-quanta issue. \n\/\/ 21 TQ allows for easy sampling at exactly 80% (recommended by Vector Informatik GmbH for high reliability systems)\n\/\/ Conveniently, the CAN peripheral's 42MHz clock lets us easily create 21TQs for all common baud rates\nvoid ODriveCAN::set_baud_rate(uint32_t baudRate) {\n switch (baudRate) {\n case CAN_BAUD_125K:\n handle_->Init.Prescaler = 16; \/\/ 21 TQ's\n config_.baud = baudRate;\n break;\n\n case CAN_BAUD_250K:\n handle_->Init.Prescaler = 8; \/\/ 21 TQ's\n config_.baud = baudRate;\n break;\n\n case CAN_BAUD_500K:\n handle_->Init.Prescaler = 4; \/\/ 21 TQ's\n config_.baud = baudRate;\n break;\n\n case CAN_BAUD_1000K:\n handle_->Init.Prescaler = 2; \/\/ 21 TQ's\n config_.baud = baudRate;\n break;\n\n default:\n break; \/\/ baudRate is invalid, so do nothing\n }\n}\n\nvoid ODriveCAN::set_node_id(uint8_t nodeID) {\n \/\/ Allow for future nodeID validation by making this a set function\n config_.node_id = nodeID;\n}\n\nvoid HAL_CAN_TxMailbox0CompleteCallback(CAN_HandleTypeDef *hcan) {}\nvoid HAL_CAN_TxMailbox1CompleteCallback(CAN_HandleTypeDef *hcan) {}\nvoid HAL_CAN_TxMailbox2CompleteCallback(CAN_HandleTypeDef *hcan) {}\nvoid HAL_CAN_TxMailbox0AbortCallback(CAN_HandleTypeDef *hcan) {}\nvoid HAL_CAN_TxMailbox1AbortCallback(CAN_HandleTypeDef *hcan) {}\nvoid HAL_CAN_TxMailbox2AbortCallback(CAN_HandleTypeDef *hcan) {}\nvoid HAL_CAN_RxFifo0MsgPendingCallback(CAN_HandleTypeDef *hcan) {\n HAL_CAN_DeactivateNotification(hcan, CAN_IT_RX_FIFO0_MSG_PENDING);\n osSemaphoreRelease(sem_can);\n}\nvoid HAL_CAN_RxFifo0FullCallback(CAN_HandleTypeDef *hcan) {\n \/\/ osSemaphoreRelease(sem_can);\n}\nvoid HAL_CAN_RxFifo1MsgPendingCallback(CAN_HandleTypeDef *hcan) {}\nvoid HAL_CAN_RxFifo1FullCallback(CAN_HandleTypeDef *hcan) {}\nvoid HAL_CAN_SleepCallback(CAN_HandleTypeDef *hcan) {}\nvoid HAL_CAN_WakeUpFromRxMsgCallback(CAN_HandleTypeDef *hcan) {}\nvoid HAL_CAN_ErrorCallback(CAN_HandleTypeDef *hcan) {\n HAL_CAN_ResetError(hcan);\n}\n<|endoftext|>"} {"text":"<commit_before>#include <mutex>\n#include <future>\n#include <utility>\n#include <atomic>\n#include <set>\n#include <iostream>\n#include <csignal>\n#include <thread>\n#include <chrono>\n#include \"zmq.hpp\"\n#include \"json.hpp\"\n#include \"easylogging++.h\"\n#include \"network.hpp\"\n\nINITIALIZE_EASYLOGGINGPP\n\nstd::atomic<bool> interruptedBySignal;\nusing json = nlohmann::json;\n\nvoid handleSignal(int sig)\n{\n interruptedBySignal = true;\n}\n\nvoid initialiseSignalHandler()\n{\n std::signal(SIGINT, handleSignal);\n std::signal(SIGTERM, handleSignal);\n}\n\n\/\/ Note that the mutex is intended to lock both the mapData and the ids\nvoid collectClients(zmq::context_t& context, std::set<std::string>& ids,\n std::mutex& mutex, const std::string& mapData)\n{\n uint msWait = 1;\n zmq::socket_t socket(context, ZMQ_ROUTER);\n socket.bind(\"tcp:\/\/*:5557\");\n std::vector<zmq::pollitem_t> pollList = { {&socket, 0, ZMQ_POLLIN, 0} };\n \n auto newMsg = [&]() {return pollList[0].revents & ZMQ_POLLIN;};\n \n while (!interruptedBySignal)\n {\n zmq::poll(&(pollList[0]), pollList.size(), msWait);\n while (newMsg())\n {\n auto msg = receive(socket);\n if (msg.size() == 3)\n {\n std::lock_guard<std::mutex> lock(mutex);\n if (!ids.count(msg[2]))\n {\n ids.insert(msg[2]);\n LOG(INFO) << \"New Player! ID: \" << msg[2];\n send(socket, {msg[0], \"\", mapData});\n }\n else\n {\n LOG(INFO) << \"Player trying to join with existing ID\";\n send(socket,{msg[0], \"\", \"ERROR: ID Taken. Please try something else.\"});\n }\n }\n else\n {\n LOG(INFO) << \"Client sent mal-formed connection message\";\n send(socket,{msg[0], \"\", \"ERROR: Please connect with single msg frame as your ID\"});\n }\n }\n }\n}\n\nint main(int ac, char* av[])\n{\n int major, minor, patch;\n zmq::version (&major, &minor, &patch); printf (\"Current ØMQ version is %d.%d.%d\\n\", major, minor, patch);\n zmq::context_t* context = new zmq::context_t(1);\n\n initialiseSignalHandler();\n\n LOG(INFO) << \"Initialising sockets\";\n\n zmq::socket_t logSocket(*context, ZMQ_PUB);\n zmq::socket_t stateSocket(*context, ZMQ_PUB);\n\n logSocket.bind(\"tcp:\/\/*:5555\");\n stateSocket.bind(\"tcp:\/\/*:5556\");\n\n LOG(INFO) << \"Starting main loop\";\n\n std::mutex mapDataMutex;\n std::string nextMapData = \"nextMapData\";\n std::string currentMapData = \"currentMapData\";\n std::set<std::string> nextPlayers;\n std::set<std::string> currentPlayers;\n \n std::future<void> controlThread = std::async(std::launch::async, collectClients, \n std::ref(*context), \n std::ref(nextPlayers),\n std::ref(mapDataMutex), \n std::cref(nextMapData));\n\n while(!interruptedBySignal)\n {\n \/\/ waiting period between games\n std::this_thread::sleep_for(std::chrono::seconds(30));\n\n \/\/get the game started\n {\n std::lock_guard<std::mutex> lock(mapDataMutex);\n currentPlayers.clear();\n std::swap(currentPlayers, nextPlayers);\n currentMapData = nextMapData;\n nextMapData = \"somenewmapdata\";\n }\n\n \/\/now play the game\n \/\/ finish off the game\n }\n\n \/\/ auto start = std::chrono::high_resolution_clock::now();\n \/\/ uint elapsedTime = 0;\n \/\/ while (elapsedTime < timeoutSecs)\n \n \/\/ elapsedTime = std::chrono::duration_cast<std::chrono::seconds>(\n \/\/ std::chrono::high_resolution_clock::now() - start).count();\n\n controlThread.wait();\n \n LOG(INFO) << \"Closing sockets\";\n\n logSocket.close();\n stateSocket.close();\n\n LOG(INFO) << \"Deleting context\";\n delete context;\n context = nullptr; \/\/ just in case\n\n LOG(INFO) << \"Thankyou for playing spacerace!\";\n return 0;\n\n}\n<commit_msg>bugfix: was not creating polllist properly<commit_after>#include <mutex>\n#include <future>\n#include <utility>\n#include <atomic>\n#include <set>\n#include <iostream>\n#include <csignal>\n#include <thread>\n#include <chrono>\n#include \"zmq.hpp\"\n#include \"json.hpp\"\n#include \"easylogging++.h\"\n#include \"network.hpp\"\n\nINITIALIZE_EASYLOGGINGPP\n\nstd::atomic<bool> interruptedBySignal;\nusing json = nlohmann::json;\n\nvoid handleSignal(int sig)\n{\n interruptedBySignal = true;\n}\n\nvoid initialiseSignalHandler()\n{\n std::signal(SIGINT, handleSignal);\n std::signal(SIGTERM, handleSignal);\n}\n\n\/\/ Note that the mutex is intended to lock both the mapData and the ids\nvoid collectClients(zmq::context_t& context, std::set<std::string>& ids,\n std::mutex& mutex, const std::string& mapData)\n{\n LOG(INFO) << \"starting player management thread\";\n \/\/ -1 implies wait until message\n int msWait = -1;\n int linger = 0;\n \n zmq::socket_t socket(context, ZMQ_ROUTER);\n socket.setsockopt(ZMQ_LINGER, &linger, sizeof(int));\n std::string address = \"tcp:\/\/*:5557\";\n socket.bind(address.c_str());\n\n \/\/ note the void* cast is a weird part of the zmq api\n zmq::pollitem_t pollList [] = {{(void*)socket, 0, ZMQ_POLLIN, 0}};\n while (!interruptedBySignal)\n {\n LOG(INFO) << \"polling...\";\n zmq::poll(pollList, 1, msWait);\n \n bool newMsg = pollList[0].revents & ZMQ_POLLIN;\n if (newMsg)\n {\n LOG(INFO) << \"New message received!!\";\n auto msg = receive(socket);\n if (msg.size() == 3)\n {\n std::lock_guard<std::mutex> lock(mutex);\n if (!ids.count(msg[2]))\n {\n ids.insert(msg[2]);\n LOG(INFO) << \"New Player! ID: \" << msg[2];\n send(socket, {msg[0], \"\", mapData});\n }\n else\n {\n LOG(INFO) << \"Player trying to join with existing ID\";\n send(socket,{msg[0], \"\", \"ERROR: ID Taken. Please try something else.\"});\n }\n }\n else\n {\n LOG(INFO) << \"Client sent mal-formed connection message\";\n send(socket,{msg[0], \"\", \"ERROR: Please connect with single msg frame as your ID\"});\n }\n }\n }\n}\n\nint main(int ac, char* av[])\n{\n zmq::context_t* context = new zmq::context_t(1);\n\n initialiseSignalHandler();\n\n LOG(INFO) << \"Initialising sockets\";\n\n zmq::socket_t logSocket(*context, ZMQ_PUB);\n zmq::socket_t stateSocket(*context, ZMQ_PUB);\n\n logSocket.bind(\"tcp:\/\/*:5555\");\n stateSocket.bind(\"tcp:\/\/*:5556\");\n\n LOG(INFO) << \"Starting main loop\";\n\n std::mutex mapDataMutex;\n std::string nextMapData = \"nextMapData\";\n std::string currentMapData = \"currentMapData\";\n std::set<std::string> nextPlayers;\n std::set<std::string> currentPlayers;\n \n std::future<void> controlThread = std::async(std::launch::async, collectClients, \n std::ref(*context), \n std::ref(nextPlayers),\n std::ref(mapDataMutex), \n std::cref(nextMapData));\n\n while(!interruptedBySignal)\n {\n \/\/ waiting period between games\n \/\/ need to do lots of short sleeps in a loop else ctrlc doesn't work\n std::this_thread::sleep_for(std::chrono::seconds(30));\n\n \/\/get the game started\n {\n std::lock_guard<std::mutex> lock(mapDataMutex);\n currentPlayers.clear();\n std::swap(currentPlayers, nextPlayers);\n currentMapData = nextMapData;\n nextMapData = \"somenewmapdata\";\n }\n\n \/\/now play the game\n \/\/ finish off the game\n }\n\n \/\/ auto start = std::chrono::high_resolution_clock::now();\n \/\/ uint elapsedTime = 0;\n \/\/ while (elapsedTime < timeoutSecs)\n \n \/\/ elapsedTime = std::chrono::duration_cast<std::chrono::seconds>(\n \/\/ std::chrono::high_resolution_clock::now() - start).count();\n\n controlThread.wait();\n \n LOG(INFO) << \"Closing sockets\";\n\n logSocket.close();\n stateSocket.close();\n\n LOG(INFO) << \"Deleting context\";\n delete context;\n context = nullptr; \/\/ just in case\n\n LOG(INFO) << \"Thankyou for playing spacerace!\";\n return 0;\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/*-----------------------------------------------------------------------------\n This source file is part of Hopsan NG\n\n Copyright (c) 2011 \n Mikael Axin, Robert Braun, Alessandro Dell'Amico, Björn Eriksson,\n Peter Nordin, Karl Pettersson, Petter Krus, Ingo Staack\n\n This file is provided \"as is\", with no guarantee or warranty for the\n functionality or reliability of the contents. All contents in this file is\n the original work of the copyright holders at the Division of Fluid and\n Mechatronic Systems (Flumes) at Linköping University. Modifying, using or\n redistributing any part of this file is prohibited without explicit\n permission from the copyright holders.\n-----------------------------------------------------------------------------*\/\n\n\/\/!\n\/\/! @file GUIPortAppearance.cpp\n\/\/! @author Flumes <flumes@lists.iei.liu.se>\n\/\/! @date 2010-01-01\n\/\/!\n\/\/! @brief Contains the GUIPortAppearance class\n\/\/!\n\/\/$Id$\n\n#include \"MainWindow.h\"\n#include \"GUIPortAppearance.h\"\n#include \"common.h\"\n\nPortAppearance::PortAppearance()\n{\n \/\/Default values\n mVisible = true;\n}\n\n\/\/! @brief Contains hardcoded appearance for different hopsancore ports\n\/\/! @todo maybe this should be placed in som more generic external .txt file in som way\nvoid PortAppearance::selectPortIcon(QString CQSType, QString porttype, QString nodetype)\n{\n mMainIconPath.clear();\n\n mMainIconPath = QString(PORTICONPATH);\n if (nodetype == \"NodeSignal\")\n {\n mMainIconPath.append(\"SignalPort\");\n if ( porttype == \"READPORT\" || porttype == \"READMULTIPORT\")\n {\n mMainIconPath.append(\"_read\");\n }\n else\n {\n mMainIconPath.append(\"_write\");\n }\n mCQSOverlayPath.clear();\n }\n else\n {\n if (nodetype == \"NodeMechanic\")\n {\n mMainIconPath.append(\"MechanicPort\");\n }\n else if (nodetype == \"NodeMechanicRotational\")\n {\n mMainIconPath.append(\"RotationalMechanicPort\");\n }\n else if (nodetype == \"NodeHydraulic\")\n {\n mMainIconPath.append(\"HydraulicPort\");\n }\n else if (nodetype == \"NodeElectric\")\n {\n mMainIconPath.append(\"ElectricPort\");\n }\n else\n {\n \/\/SystemPort is a blank port (that is why we use it here)\n mMainIconPath.append(\"SystemPort\");\n }\n\n \/\/Select cqs overlay icon path depending on cqs type\n if (CQSType == \"C\")\n {\n mCQSOverlayPath = (QString(PORTICONPATH) + \"PortOverlayC.svg\");\n }\n else if (CQSType == \"Q\")\n {\n mCQSOverlayPath = (QString(PORTICONPATH) + \"PortOverlayQ.svg\");\n }\n else if (CQSType == \"UNDEFINEDCQSTYPE\")\n {\n mCQSOverlayPath = (QString(PORTICONPATH) + \"PortOverlayUnknown.svg\");\n }\n else\n {\n mCQSOverlayPath.clear();\n }\n }\n mMainIconPath.append(\".svg\");\n\n \/\/Check if we need to add multiport overlay\n if (porttype.contains(\"MULTIPORT\"))\n {\n mMultiPortOverlayPath = (QString(PORTICONPATH) + \"MultiPortOverlay.svg\");\n }\n else\n {\n mMultiPortOverlayPath.clear();\n }\n}\n\n<commit_msg>NodePneumatic added<commit_after>\/*-----------------------------------------------------------------------------\n This source file is part of Hopsan NG\n\n Copyright (c) 2011 \n Mikael Axin, Robert Braun, Alessandro Dell'Amico, Björn Eriksson,\n Peter Nordin, Karl Pettersson, Petter Krus, Ingo Staack\n\n This file is provided \"as is\", with no guarantee or warranty for the\n functionality or reliability of the contents. All contents in this file is\n the original work of the copyright holders at the Division of Fluid and\n Mechatronic Systems (Flumes) at Linköping University. Modifying, using or\n redistributing any part of this file is prohibited without explicit\n permission from the copyright holders.\n-----------------------------------------------------------------------------*\/\n\n\/\/!\n\/\/! @file GUIPortAppearance.cpp\n\/\/! @author Flumes <flumes@lists.iei.liu.se>\n\/\/! @date 2010-01-01\n\/\/!\n\/\/! @brief Contains the GUIPortAppearance class\n\/\/!\n\/\/$Id$\n\n#include \"MainWindow.h\"\n#include \"GUIPortAppearance.h\"\n#include \"common.h\"\n\nPortAppearance::PortAppearance()\n{\n \/\/Default values\n mVisible = true;\n}\n\n\/\/! @brief Contains hardcoded appearance for different hopsancore ports\n\/\/! @todo maybe this should be placed in som more generic external .txt file in som way\nvoid PortAppearance::selectPortIcon(QString CQSType, QString porttype, QString nodetype)\n{\n mMainIconPath.clear();\n\n mMainIconPath = QString(PORTICONPATH);\n if (nodetype == \"NodeSignal\")\n {\n mMainIconPath.append(\"SignalPort\");\n if ( porttype == \"READPORT\" || porttype == \"READMULTIPORT\")\n {\n mMainIconPath.append(\"_read\");\n }\n else\n {\n mMainIconPath.append(\"_write\");\n }\n mCQSOverlayPath.clear();\n }\n else\n {\n if (nodetype == \"NodeMechanic\")\n {\n mMainIconPath.append(\"MechanicPort\");\n }\n else if (nodetype == \"NodeMechanicRotational\")\n {\n mMainIconPath.append(\"RotationalMechanicPort\");\n }\n else if (nodetype == \"NodeHydraulic\")\n {\n mMainIconPath.append(\"HydraulicPort\");\n }\n else if (nodetype == \"NodePneumatic\")\n {\n mMainIconPath.append(\"PneumaticPort\");\n }\n else if (nodetype == \"NodeElectric\")\n {\n mMainIconPath.append(\"ElectricPort\");\n }\n else\n {\n \/\/SystemPort is a blank port (that is why we use it here)\n mMainIconPath.append(\"SystemPort\");\n }\n\n \/\/Select cqs overlay icon path depending on cqs type\n if (CQSType == \"C\")\n {\n mCQSOverlayPath = (QString(PORTICONPATH) + \"PortOverlayC.svg\");\n }\n else if (CQSType == \"Q\")\n {\n mCQSOverlayPath = (QString(PORTICONPATH) + \"PortOverlayQ.svg\");\n }\n else if (CQSType == \"UNDEFINEDCQSTYPE\")\n {\n mCQSOverlayPath = (QString(PORTICONPATH) + \"PortOverlayUnknown.svg\");\n }\n else\n {\n mCQSOverlayPath.clear();\n }\n }\n mMainIconPath.append(\".svg\");\n\n \/\/Check if we need to add multiport overlay\n if (porttype.contains(\"MULTIPORT\"))\n {\n mMultiPortOverlayPath = (QString(PORTICONPATH) + \"MultiPortOverlay.svg\");\n }\n else\n {\n mMultiPortOverlayPath.clear();\n }\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/*=========================================================================\n\n Program: Visualization Toolkit\n Module: vtkTreeDifferenceFilter.cxx\n\n Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen\n All rights reserved.\n See Copyright.txt or http:\/\/www.kitware.com\/Copyright.htm for details.\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notice for more information.\n\n=========================================================================*\/\n\n#include \"vtkTreeDifferenceFilter.h\"\n\n#include \"vtkDataSetAttributes.h\"\n#include \"vtkDoubleArray.h\"\n#include \"vtkInformation.h\"\n#include \"vtkInformationVector.h\"\n#include \"vtkMath.h\"\n#include \"vtkNew.h\"\n#include \"vtkObjectFactory.h\"\n#include \"vtkStringArray.h\"\n#include \"vtkTree.h\"\n\nvtkStandardNewMacro(vtkTreeDifferenceFilter);\n\n\/\/---------------------------------------------------------------------------\nvtkTreeDifferenceFilter::vtkTreeDifferenceFilter()\n{\n this->SetNumberOfInputPorts(2);\n this->SetNumberOfOutputPorts(1);\n\n this->IdArrayName = 0;\n this->ComparisonArrayName = 0;\n this->OutputArrayName = 0;\n this->ComparisonArrayIsVertexData = false;\n}\n\n\/\/---------------------------------------------------------------------------\nvtkTreeDifferenceFilter::~vtkTreeDifferenceFilter()\n{\n \/\/ release memory\n this->SetIdArrayName(0);\n this->SetComparisonArrayName(0);\n this->SetOutputArrayName(0);\n}\n\n\/\/---------------------------------------------------------------------------\nint vtkTreeDifferenceFilter::FillInputPortInformation(int port, vtkInformation *info)\n{\n if(port == 0)\n {\n info->Set(vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE(), \"vtkTree\");\n }\n else if(port == 1)\n {\n info->Set(vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE(), \"vtkTree\");\n info->Set(vtkAlgorithm::INPUT_IS_OPTIONAL(), 1);\n }\n\n return 1;\n}\n\n\/\/---------------------------------------------------------------------------\nint vtkTreeDifferenceFilter::RequestData(\n vtkInformation*,\n vtkInformationVector** inputVector,\n vtkInformationVector* outputVector)\n{\n vtkInformation* tree1_info = inputVector[0]->GetInformationObject(0);\n vtkTree* tree1 = vtkTree::SafeDownCast(\n tree1_info->Get(vtkDataObject::DATA_OBJECT()));\n\n \/\/ Copy the structure into the output.\n vtkTree* outputTree = vtkTree::GetData(outputVector);\n\n vtkInformation* tree2_info = inputVector[1]->GetInformationObject(0);\n if(!tree2_info)\n {\n \/\/ If no second tree provided, we're done\n outputTree->CheckedShallowCopy(tree1);\n return 0;\n }\n\n vtkTree* tree2 = vtkTree::SafeDownCast(\n tree2_info->Get(vtkDataObject::DATA_OBJECT()));\n\n if (this->IdArrayName != 0)\n {\n if (!this->GenerateMapping(tree1, tree2))\n {\n return 0;\n }\n }\n else\n {\n this->VertexMap.clear();\n for (vtkIdType vertex = 0; vertex < tree1->GetNumberOfVertices(); ++vertex)\n {\n this->VertexMap[vertex] = vertex;\n }\n\n this->EdgeMap.clear();\n for (vtkIdType edge = 0; edge < tree1->GetNumberOfEdges(); ++edge)\n {\n this->EdgeMap[edge] = edge;\n }\n }\n\n this->ComputeDifference(tree1, tree2);\n\n if (!outputTree->CheckedShallowCopy(tree1))\n {\n vtkErrorMacro(<<\"Invalid tree structure.\");\n return 0;\n }\n return 1;\n}\n\n\/\/---------------------------------------------------------------------------\nbool vtkTreeDifferenceFilter::GenerateMapping(vtkTree *tree1, vtkTree *tree2)\n{\n this->VertexMap.clear();\n this->VertexMap.assign(tree1->GetNumberOfVertices(), -1);\n\n this->EdgeMap.clear();\n this->EdgeMap.assign(tree1->GetNumberOfEdges(), -1);\n\n vtkStringArray *nodeNames1 = vtkStringArray::SafeDownCast(\n tree1->GetVertexData()->GetAbstractArray(this->IdArrayName));\n if (nodeNames1 == NULL)\n {\n vtkErrorMacro(\"tree #1's VertexData does not have a vtkStringArray named \"\n << this->IdArrayName);\n return false;\n }\n\n vtkStringArray *nodeNames2 = vtkStringArray::SafeDownCast(\n tree2->GetVertexData()->GetAbstractArray(this->IdArrayName));\n if (nodeNames2 == NULL)\n {\n vtkErrorMacro(\"tree #2's VertexData does not have a vtkStringArray named \"\n << this->IdArrayName);\n return false;\n }\n\n vtkIdType root1 = tree1->GetRoot();\n vtkIdType root2 = tree2->GetRoot();\n\n vtkIdType edgeId1 = -1;\n vtkIdType edgeId2 = -1;\n\n \/\/ iterate over the vertex names for tree #1, finding the corresponding\n \/\/ vertex in tree #2.\n for (vtkIdType vertexItr = 0; vertexItr < nodeNames1->GetNumberOfTuples();\n ++vertexItr)\n {\n vtkIdType vertexId1 = vertexItr;\n std::string nodeName = nodeNames1->GetValue(vertexId1);\n if (nodeName.compare(\"\") == 0)\n {\n continue;\n }\n\n \/\/ record this correspondence in the maps\n vtkIdType vertexId2 = nodeNames2->LookupValue(nodeName);\n if (vertexId2 == -1)\n {\n vtkWarningMacro(\"tree #2 does not contain a vertex named \" << nodeName);\n continue;\n }\n this->VertexMap[vertexId1] = vertexId2;\n\n if (vertexId1 == root1 || vertexId2 == root2)\n {\n continue;\n }\n\n edgeId1 = tree1->GetEdgeId(tree1->GetParent(vertexId1), vertexId1);\n edgeId2 = tree2->GetEdgeId(tree2->GetParent(vertexId2), vertexId2);\n this->EdgeMap[edgeId1] = edgeId2;\n\n \/\/ descend the tree until we reach the root, mapping parent vertices to\n \/\/ each other along the way.\n while (tree1->GetParent(vertexId1) != root1 &&\n tree2->GetParent(vertexId2) != root2)\n {\n vertexId1 = tree1->GetParent(vertexId1);\n vertexId2 = tree2->GetParent(vertexId2);\n if (this->VertexMap[vertexId1] == -1)\n {\n this->VertexMap[vertexId1] = vertexId2;\n edgeId1 = tree1->GetEdgeId(tree1->GetParent(vertexId1), vertexId1);\n edgeId2 = tree2->GetEdgeId(tree2->GetParent(vertexId2), vertexId2);\n this->EdgeMap[edgeId1] = edgeId2;\n }\n }\n }\n\n return true;\n}\n\n\/\/---------------------------------------------------------------------------\nvoid vtkTreeDifferenceFilter::ComputeDifference(vtkTree *tree1, vtkTree *tree2)\n{\n if (this->ComparisonArrayName == 0)\n {\n vtkErrorMacro(\"ComparisonArrayName has not been set.\");\n return;\n }\n\n vtkDataSetAttributes *treeData1, *treeData2;\n const char *dataName;\n if (this->ComparisonArrayIsVertexData)\n {\n treeData1 = tree1->GetVertexData();\n treeData2 = tree2->GetVertexData();\n dataName = \"VertexData\";\n }\n else\n {\n treeData1 = tree1->GetEdgeData();\n treeData2 = tree2->GetEdgeData();\n dataName = \"EdgeData\";\n }\n\n vtkDoubleArray *arrayToCompare1 = vtkDoubleArray::SafeDownCast(\n treeData1->GetAbstractArray(this->ComparisonArrayName));\n if (arrayToCompare1 == NULL)\n {\n vtkErrorMacro(\"tree #1's \" << dataName <<\n \" does not have a vtkDoubleArray named \" << this->IdArrayName);\n return;\n }\n\n vtkDoubleArray *arrayToCompare2 = vtkDoubleArray::SafeDownCast(\n treeData2->GetAbstractArray(this->ComparisonArrayName));\n if (arrayToCompare2 == NULL)\n {\n vtkErrorMacro(\"tree #2's \" << dataName <<\n \" does not have a vtkDoubleArray named \" << this->IdArrayName);\n return;\n }\n\n vtkNew<vtkDoubleArray> resultArray;\n resultArray->SetNumberOfValues(arrayToCompare1->GetNumberOfTuples());\n resultArray->FillComponent(0, vtkMath::Nan());\n\n if (this->OutputArrayName == 0)\n {\n resultArray->SetName(\"difference\");\n }\n else\n {\n resultArray->SetName(this->OutputArrayName);\n }\n\n vtkIdType treeId2;\n for (vtkIdType treeId1 = 0; treeId1 < arrayToCompare1->GetNumberOfTuples();\n ++treeId1)\n {\n if (this->ComparisonArrayIsVertexData)\n {\n treeId2 = this->VertexMap[treeId1];\n }\n else\n {\n treeId2 = this->EdgeMap[treeId1];\n }\n double result =\n arrayToCompare1->GetValue(treeId1) - arrayToCompare2->GetValue(treeId2);\n resultArray->SetValue(treeId1, result);\n }\n\n treeData1->AddArray(resultArray.GetPointer());\n}\n\n\/\/---------------------------------------------------------------------------\nvoid vtkTreeDifferenceFilter::PrintSelf(ostream& os, vtkIndent indent)\n{\n this->Superclass::PrintSelf(os, indent);\n}\n<commit_msg>address Gerrit feedback<commit_after>\/*=========================================================================\n\n Program: Visualization Toolkit\n Module: vtkTreeDifferenceFilter.cxx\n\n Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen\n All rights reserved.\n See Copyright.txt or http:\/\/www.kitware.com\/Copyright.htm for details.\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notice for more information.\n\n=========================================================================*\/\n\n#include \"vtkTreeDifferenceFilter.h\"\n\n#include \"vtkDataSetAttributes.h\"\n#include \"vtkDoubleArray.h\"\n#include \"vtkInformation.h\"\n#include \"vtkInformationVector.h\"\n#include \"vtkMath.h\"\n#include \"vtkNew.h\"\n#include \"vtkObjectFactory.h\"\n#include \"vtkStringArray.h\"\n#include \"vtkTree.h\"\n\nvtkStandardNewMacro(vtkTreeDifferenceFilter);\n\n\/\/---------------------------------------------------------------------------\nvtkTreeDifferenceFilter::vtkTreeDifferenceFilter()\n{\n this->SetNumberOfInputPorts(2);\n this->SetNumberOfOutputPorts(1);\n\n this->IdArrayName = 0;\n this->ComparisonArrayName = 0;\n this->OutputArrayName = 0;\n this->ComparisonArrayIsVertexData = false;\n}\n\n\/\/---------------------------------------------------------------------------\nvtkTreeDifferenceFilter::~vtkTreeDifferenceFilter()\n{\n \/\/ release memory\n this->SetIdArrayName(0);\n this->SetComparisonArrayName(0);\n this->SetOutputArrayName(0);\n}\n\n\/\/---------------------------------------------------------------------------\nint vtkTreeDifferenceFilter::FillInputPortInformation(int port, vtkInformation *info)\n{\n if(port == 0)\n {\n info->Set(vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE(), \"vtkTree\");\n }\n else if(port == 1)\n {\n info->Set(vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE(), \"vtkTree\");\n info->Set(vtkAlgorithm::INPUT_IS_OPTIONAL(), 1);\n }\n\n return 1;\n}\n\n\/\/---------------------------------------------------------------------------\nint vtkTreeDifferenceFilter::RequestData(\n vtkInformation*,\n vtkInformationVector** inputVector,\n vtkInformationVector* outputVector)\n{\n vtkInformation* tree1_info = inputVector[0]->GetInformationObject(0);\n vtkTree* tree1 = vtkTree::SafeDownCast(\n tree1_info->Get(vtkDataObject::DATA_OBJECT()));\n\n \/\/ Copy the structure into the output.\n vtkTree* outputTree = vtkTree::GetData(outputVector);\n\n vtkInformation* tree2_info = inputVector[1]->GetInformationObject(0);\n if(!tree2_info)\n {\n \/\/ If no second tree provided, we're done\n outputTree->CheckedShallowCopy(tree1);\n return 0;\n }\n\n vtkTree* tree2 = vtkTree::SafeDownCast(\n tree2_info->Get(vtkDataObject::DATA_OBJECT()));\n\n if (this->IdArrayName != 0)\n {\n if (!this->GenerateMapping(tree1, tree2))\n {\n return 0;\n }\n }\n else\n {\n this->VertexMap.clear();\n for (vtkIdType vertex = 0; vertex < tree1->GetNumberOfVertices(); ++vertex)\n {\n this->VertexMap[vertex] = vertex;\n }\n\n this->EdgeMap.clear();\n for (vtkIdType edge = 0; edge < tree1->GetNumberOfEdges(); ++edge)\n {\n this->EdgeMap[edge] = edge;\n }\n }\n\n this->ComputeDifference(tree1, tree2);\n\n if (!outputTree->CheckedShallowCopy(tree1))\n {\n vtkErrorMacro(<<\"Invalid tree structure.\");\n return 0;\n }\n return 1;\n}\n\n\/\/---------------------------------------------------------------------------\nbool vtkTreeDifferenceFilter::GenerateMapping(vtkTree *tree1, vtkTree *tree2)\n{\n this->VertexMap.clear();\n this->VertexMap.assign(tree1->GetNumberOfVertices(), -1);\n\n this->EdgeMap.clear();\n this->EdgeMap.assign(tree1->GetNumberOfEdges(), -1);\n\n vtkStringArray *nodeNames1 = vtkStringArray::SafeDownCast(\n tree1->GetVertexData()->GetAbstractArray(this->IdArrayName));\n if (nodeNames1 == NULL)\n {\n vtkErrorMacro(\"tree #1's VertexData does not have a vtkStringArray named \"\n << this->IdArrayName);\n return false;\n }\n\n vtkStringArray *nodeNames2 = vtkStringArray::SafeDownCast(\n tree2->GetVertexData()->GetAbstractArray(this->IdArrayName));\n if (nodeNames2 == NULL)\n {\n vtkErrorMacro(\"tree #2's VertexData does not have a vtkStringArray named \"\n << this->IdArrayName);\n return false;\n }\n\n vtkIdType root1 = tree1->GetRoot();\n vtkIdType root2 = tree2->GetRoot();\n\n vtkIdType edgeId1 = -1;\n vtkIdType edgeId2 = -1;\n\n \/\/ iterate over the vertex names for tree #1, finding the corresponding\n \/\/ vertex in tree #2.\n for (vtkIdType vertexItr = 0; vertexItr < nodeNames1->GetNumberOfTuples();\n ++vertexItr)\n {\n vtkIdType vertexId1 = vertexItr;\n std::string nodeName = nodeNames1->GetValue(vertexId1);\n if (nodeName.compare(\"\") == 0)\n {\n continue;\n }\n\n \/\/ record this correspondence in the maps\n vtkIdType vertexId2 = nodeNames2->LookupValue(nodeName);\n if (vertexId2 == -1)\n {\n vtkWarningMacro(\"tree #2 does not contain a vertex named \" << nodeName);\n continue;\n }\n this->VertexMap[vertexId1] = vertexId2;\n\n if (vertexId1 == root1 || vertexId2 == root2)\n {\n continue;\n }\n\n edgeId1 = tree1->GetEdgeId(tree1->GetParent(vertexId1), vertexId1);\n edgeId2 = tree2->GetEdgeId(tree2->GetParent(vertexId2), vertexId2);\n this->EdgeMap[edgeId1] = edgeId2;\n\n \/\/ ascend the tree until we reach the root, mapping parent vertices to\n \/\/ each other along the way.\n while (tree1->GetParent(vertexId1) != root1 &&\n tree2->GetParent(vertexId2) != root2)\n {\n vertexId1 = tree1->GetParent(vertexId1);\n vertexId2 = tree2->GetParent(vertexId2);\n if (this->VertexMap[vertexId1] == -1)\n {\n this->VertexMap[vertexId1] = vertexId2;\n edgeId1 = tree1->GetEdgeId(tree1->GetParent(vertexId1), vertexId1);\n edgeId2 = tree2->GetEdgeId(tree2->GetParent(vertexId2), vertexId2);\n this->EdgeMap[edgeId1] = edgeId2;\n }\n }\n }\n\n return true;\n}\n\n\/\/---------------------------------------------------------------------------\nvoid vtkTreeDifferenceFilter::ComputeDifference(vtkTree *tree1, vtkTree *tree2)\n{\n if (this->ComparisonArrayName == 0)\n {\n vtkErrorMacro(\"ComparisonArrayName has not been set.\");\n return;\n }\n\n vtkDataSetAttributes *treeData1, *treeData2;\n const char *dataName;\n if (this->ComparisonArrayIsVertexData)\n {\n treeData1 = tree1->GetVertexData();\n treeData2 = tree2->GetVertexData();\n dataName = \"VertexData\";\n }\n else\n {\n treeData1 = tree1->GetEdgeData();\n treeData2 = tree2->GetEdgeData();\n dataName = \"EdgeData\";\n }\n\n vtkDataArray *arrayToCompare1 =\n treeData1->GetArray(this->ComparisonArrayName);\n if (arrayToCompare1 == NULL)\n {\n vtkErrorMacro(\"tree #1's \" << dataName <<\n \" does not have a vtkDoubleArray named \" << this->IdArrayName);\n return;\n }\n\n vtkDataArray *arrayToCompare2 =\n treeData2->GetArray(this->ComparisonArrayName);\n if (arrayToCompare2 == NULL)\n {\n vtkErrorMacro(\"tree #2's \" << dataName <<\n \" does not have a vtkDoubleArray named \" << this->IdArrayName);\n return;\n }\n\n vtkNew<vtkDoubleArray> resultArray;\n resultArray->SetNumberOfValues(arrayToCompare1->GetNumberOfTuples());\n resultArray->FillComponent(0, vtkMath::Nan());\n\n if (this->OutputArrayName == 0)\n {\n resultArray->SetName(\"difference\");\n }\n else\n {\n resultArray->SetName(this->OutputArrayName);\n }\n\n vtkIdType treeId2;\n for (vtkIdType treeId1 = 0; treeId1 < arrayToCompare1->GetNumberOfTuples();\n ++treeId1)\n {\n if (this->ComparisonArrayIsVertexData)\n {\n treeId2 = this->VertexMap[treeId1];\n }\n else\n {\n treeId2 = this->EdgeMap[treeId1];\n }\n double result =\n arrayToCompare1->GetTuple1(treeId1) - arrayToCompare2->GetTuple1(treeId2);\n resultArray->SetValue(treeId1, result);\n }\n\n treeData1->AddArray(resultArray.GetPointer());\n}\n\n\/\/---------------------------------------------------------------------------\nvoid vtkTreeDifferenceFilter::PrintSelf(ostream& os, vtkIndent indent)\n{\n this->Superclass::PrintSelf(os, indent);\n os << indent << \"IdArrayName: \" << this->IdArrayName << endl;\n os << indent << \"ComparisonArrayName: \" << this->ComparisonArrayName << endl;\n os << indent << \"OutputArrayName: \" << this->OutputArrayName << endl;\n os << indent << \"ComparisonArrayIsVertexData: \" << this->ComparisonArrayIsVertexData << endl;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n Print.cpp - Base class that provides print() and println()\n Copyright (c) 2008 David A. Mellis. All right reserved.\n \n This library is free software; you can redistribute it and\/or\n modify it under the terms of the GNU Lesser General Public\n License as published by the Free Software Foundation; either\n version 2.1 of the License, or (at your option) any later version.\n \n This library is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n Lesser General Public License for more details.\n \n You should have received a copy of the GNU Lesser General Public\n License along with this library; if not, write to the Free Software\n Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n \n Modified 23 November 2006 by David A. Mellis\n *\/\n\n#include <stdlib.h>\n#include <stdio.h>\n#include <string.h>\n#include <math.h>\n#include \"Arduino.h\"\n\n#include \"Print.h\"\n\n\/\/ Public Methods \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/* default implementation: may be overridden *\/\nsize_t Print::write(const uint8_t *buffer, size_t size)\n{\n size_t n = 0;\n while (size--) {\n n += write(*buffer++);\n }\n return n;\n}\n\nsize_t Print::print(const __FlashStringHelper *ifsh)\n{\n const char PROGMEM *p = (const char PROGMEM *)ifsh;\n size_t n = 0;\n while (1) {\n unsigned char c = pgm_read_byte(p++);\n if (c == 0) break;\n n += write(c);\n }\n return n;\n}\n\nsize_t Print::print(const String &s)\n{\n size_t n = 0;\n for (uint16_t i = 0; i < s.length(); i++) {\n n += write(s[i]);\n }\n return n;\n}\n\nsize_t Print::print(const char str[])\n{\n return write(str);\n}\n\nsize_t Print::print(char c)\n{\n return write(c);\n}\n\nsize_t Print::print(unsigned char b, int base)\n{\n return print((unsigned long) b, base);\n}\n\nsize_t Print::print(int n, int base)\n{\n return print((long) n, base);\n}\n\nsize_t Print::print(unsigned int n, int base)\n{\n return print((unsigned long) n, base);\n}\n\nsize_t Print::print(long n, int base)\n{\n if (base == 0) {\n return write(n);\n } else if (base == 10) {\n if (n < 0) {\n int t = print('-');\n n = -n;\n return printNumber(n, 10) + t;\n }\n return printNumber(n, 10);\n } else {\n return printNumber(n, base);\n }\n}\n\nsize_t Print::print(unsigned long n, int base)\n{\n if (base == 0) return write(n);\n else return printNumber(n, base);\n}\n\nsize_t Print::print(double n, int digits)\n{\n return printFloat(n, digits);\n}\n\nsize_t Print::println(const __FlashStringHelper *ifsh)\n{\n size_t n = print(ifsh);\n n += println();\n return n;\n}\n\nsize_t Print::print(const Printable& x)\n{\n return x.printTo(*this);\n}\n\nsize_t Print::println(void)\n{\n size_t n = print('\\r');\n n += print('\\n');\n return n;\n}\n\nsize_t Print::println(const String &s)\n{\n size_t n = print(s);\n n += println();\n return n;\n}\n\nsize_t Print::println(const char c[])\n{\n size_t n = print(c);\n n += println();\n return n;\n}\n\nsize_t Print::println(char c)\n{\n size_t n = print(c);\n n += println();\n return n;\n}\n\nsize_t Print::println(unsigned char b, int base)\n{\n size_t n = print(b, base);\n n += println();\n return n;\n}\n\nsize_t Print::println(int num, int base)\n{\n size_t n = print(num, base);\n n += println();\n return n;\n}\n\nsize_t Print::println(unsigned int num, int base)\n{\n size_t n = print(num, base);\n n += println();\n return n;\n}\n\nsize_t Print::println(long num, int base)\n{\n size_t n = print(num, base);\n n += println();\n return n;\n}\n\nsize_t Print::println(unsigned long num, int base)\n{\n size_t n = print(num, base);\n n += println();\n return n;\n}\n\nsize_t Print::println(double num, int digits)\n{\n size_t n = print(num, digits);\n n += println();\n return n;\n}\n\nsize_t Print::println(const Printable& x)\n{\n size_t n = print(x);\n n += println();\n return n;\n}\n\n\/\/ Private Methods \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nsize_t Print::printNumber(unsigned long n, uint8_t base) {\n char buf[8 * sizeof(long) + 1]; \/\/ Assumes 8-bit chars plus zero byte.\n char *str = &buf[sizeof(buf) - 1];\n\n *str = '\\0';\n\n \/\/ prevent crash if called with base == 1\n if (base < 2) base = 10;\n\n do {\n unsigned long m = n;\n n \/= base;\n char c = m - base * n;\n *--str = c < 10 ? c + '0' : c + 'A' - 10;\n } while(n);\n\n return write(str);\n}\n\nsize_t Print::printFloat(double number, uint8_t digits) \n{ \n size_t n = 0;\n \n if (isnan(number)) return print(\"nan\");\n if (isinf(number)) return print(\"inf\");\n if (number > 4294967040.0) return print (\"ovf\"); \/\/ constant determined empirically\n if (number <-4294967040.0) return print (\"ovf\"); \/\/ constant determined empirically\n \n \/\/ Handle negative numbers\n if (number < 0.0)\n {\n n += print('-');\n number = -number;\n }\n\n \/\/ Round correctly so that print(1.999, 2) prints as \"2.00\"\n double rounding = 0.5;\n for (uint8_t i=0; i<digits; ++i)\n rounding \/= 10.0;\n \n number += rounding;\n\n \/\/ Extract the integer part of the number and print it\n unsigned long int_part = (unsigned long)number;\n double remainder = number - (double)int_part;\n n += print(int_part);\n\n \/\/ Print the decimal point, but only if there are digits beyond\n if (digits > 0) {\n n += print(\".\"); \n }\n\n \/\/ Extract digits from the remainder one at a time\n while (digits-- > 0)\n {\n remainder *= 10.0;\n int toPrint = int(remainder);\n n += print(toPrint);\n remainder -= toPrint; \n } \n \n return n;\n}\n<commit_msg>Print.print optimization. Closes #1760<commit_after>\/*\n Print.cpp - Base class that provides print() and println()\n Copyright (c) 2008 David A. Mellis. All right reserved.\n \n This library is free software; you can redistribute it and\/or\n modify it under the terms of the GNU Lesser General Public\n License as published by the Free Software Foundation; either\n version 2.1 of the License, or (at your option) any later version.\n \n This library is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n Lesser General Public License for more details.\n \n You should have received a copy of the GNU Lesser General Public\n License along with this library; if not, write to the Free Software\n Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n \n Modified 23 November 2006 by David A. Mellis\n *\/\n\n#include <stdlib.h>\n#include <stdio.h>\n#include <string.h>\n#include <math.h>\n#include \"Arduino.h\"\n\n#include \"Print.h\"\n\n\/\/ Public Methods \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/* default implementation: may be overridden *\/\nsize_t Print::write(const uint8_t *buffer, size_t size)\n{\n size_t n = 0;\n while (size--) {\n n += write(*buffer++);\n }\n return n;\n}\n\nsize_t Print::print(const __FlashStringHelper *ifsh)\n{\n const char PROGMEM *p = (const char PROGMEM *)ifsh;\n size_t n = 0;\n while (1) {\n unsigned char c = pgm_read_byte(p++);\n if (c == 0) break;\n n += write(c);\n }\n return n;\n}\n\nsize_t Print::print(const String &s)\n{\n return write(reinterpret_cast<const uint8_t*>(s.c_str()), s.length());\n}\n\nsize_t Print::print(const char str[])\n{\n return write(str);\n}\n\nsize_t Print::print(char c)\n{\n return write(c);\n}\n\nsize_t Print::print(unsigned char b, int base)\n{\n return print((unsigned long) b, base);\n}\n\nsize_t Print::print(int n, int base)\n{\n return print((long) n, base);\n}\n\nsize_t Print::print(unsigned int n, int base)\n{\n return print((unsigned long) n, base);\n}\n\nsize_t Print::print(long n, int base)\n{\n if (base == 0) {\n return write(n);\n } else if (base == 10) {\n if (n < 0) {\n int t = print('-');\n n = -n;\n return printNumber(n, 10) + t;\n }\n return printNumber(n, 10);\n } else {\n return printNumber(n, base);\n }\n}\n\nsize_t Print::print(unsigned long n, int base)\n{\n if (base == 0) return write(n);\n else return printNumber(n, base);\n}\n\nsize_t Print::print(double n, int digits)\n{\n return printFloat(n, digits);\n}\n\nsize_t Print::println(const __FlashStringHelper *ifsh)\n{\n size_t n = print(ifsh);\n n += println();\n return n;\n}\n\nsize_t Print::print(const Printable& x)\n{\n return x.printTo(*this);\n}\n\nsize_t Print::println(void)\n{\n size_t n = print('\\r');\n n += print('\\n');\n return n;\n}\n\nsize_t Print::println(const String &s)\n{\n size_t n = print(s);\n n += println();\n return n;\n}\n\nsize_t Print::println(const char c[])\n{\n size_t n = print(c);\n n += println();\n return n;\n}\n\nsize_t Print::println(char c)\n{\n size_t n = print(c);\n n += println();\n return n;\n}\n\nsize_t Print::println(unsigned char b, int base)\n{\n size_t n = print(b, base);\n n += println();\n return n;\n}\n\nsize_t Print::println(int num, int base)\n{\n size_t n = print(num, base);\n n += println();\n return n;\n}\n\nsize_t Print::println(unsigned int num, int base)\n{\n size_t n = print(num, base);\n n += println();\n return n;\n}\n\nsize_t Print::println(long num, int base)\n{\n size_t n = print(num, base);\n n += println();\n return n;\n}\n\nsize_t Print::println(unsigned long num, int base)\n{\n size_t n = print(num, base);\n n += println();\n return n;\n}\n\nsize_t Print::println(double num, int digits)\n{\n size_t n = print(num, digits);\n n += println();\n return n;\n}\n\nsize_t Print::println(const Printable& x)\n{\n size_t n = print(x);\n n += println();\n return n;\n}\n\n\/\/ Private Methods \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nsize_t Print::printNumber(unsigned long n, uint8_t base) {\n char buf[8 * sizeof(long) + 1]; \/\/ Assumes 8-bit chars plus zero byte.\n char *str = &buf[sizeof(buf) - 1];\n\n *str = '\\0';\n\n \/\/ prevent crash if called with base == 1\n if (base < 2) base = 10;\n\n do {\n unsigned long m = n;\n n \/= base;\n char c = m - base * n;\n *--str = c < 10 ? c + '0' : c + 'A' - 10;\n } while(n);\n\n return write(str);\n}\n\nsize_t Print::printFloat(double number, uint8_t digits) \n{ \n size_t n = 0;\n \n if (isnan(number)) return print(\"nan\");\n if (isinf(number)) return print(\"inf\");\n if (number > 4294967040.0) return print (\"ovf\"); \/\/ constant determined empirically\n if (number <-4294967040.0) return print (\"ovf\"); \/\/ constant determined empirically\n \n \/\/ Handle negative numbers\n if (number < 0.0)\n {\n n += print('-');\n number = -number;\n }\n\n \/\/ Round correctly so that print(1.999, 2) prints as \"2.00\"\n double rounding = 0.5;\n for (uint8_t i=0; i<digits; ++i)\n rounding \/= 10.0;\n \n number += rounding;\n\n \/\/ Extract the integer part of the number and print it\n unsigned long int_part = (unsigned long)number;\n double remainder = number - (double)int_part;\n n += print(int_part);\n\n \/\/ Print the decimal point, but only if there are digits beyond\n if (digits > 0) {\n n += print(\".\"); \n }\n\n \/\/ Extract digits from the remainder one at a time\n while (digits-- > 0)\n {\n remainder *= 10.0;\n int toPrint = int(remainder);\n n += print(toPrint);\n remainder -= toPrint; \n } \n \n return n;\n}\n<|endoftext|>"} {"text":"<commit_before>\n\n\/\/\n\/\/ Copyright (c) 2011 Limit Point Systems, Inc.\n\/\/\n\n\/\/\/ @file\n\/\/\/ Implementation for class hub_index_space_iterator\n\n#include \"hub_index_space_iterator.h\"\n\n#include \"assert_contract.h\"\n#include \"explicit_index_space_handle.h\"\n#include \"index_space_family.h\"\n#include \"interval_set_iterator.h\"\n#include \"primary_sum_index_space_state.h\"\n\n\/\/ ===========================================================\n\/\/ HUB_INDEX_SPACE_ITERATOR FACET\n\/\/ ===========================================================\n\n\/\/ PUBLIC MEMBER FUNCTIONS\n\nsheaf::hub_index_space_iterator::\nhub_index_space_iterator()\n{\n \/\/ Preconditions:\n\n \/\/ Body:\n\n _mbr_itr = 0;\n\n \/\/ Postconditions:\n\n ensure(invariant());\n ensure(!is_attached());\n\n \/\/ Exit:\n\n return;\n}\n\nsheaf::hub_index_space_iterator::\nhub_index_space_iterator(const hub_index_space_iterator& xother)\n{\n \/\/ Preconditions:\n\n \/\/ Body:\n\n *this = xother;\n\n \/\/ Postconditions:\n\n ensure(invariant());\n ensure((*this) == xother);\n\n \/\/ Exit:\n\n return;\n}\n\nsheaf::hub_index_space_iterator::\nhub_index_space_iterator(const index_space_family& xid_spaces,\n\t\t\t pod_type xindex)\n{\n \/\/ Preconditions:\n\n require(conforms_to_state(xid_spaces, xindex));\n\n \/\/ Body:\n\n attach_to(xid_spaces, xindex);\n\n \/\/ Postconditions:\n\n ensure(invariant());\n ensure(is_attached());\n ensure(&id_spaces() == &xid_spaces);\n ensure(index() == xindex);\n\n \/\/ Exit:\n\n return;\n}\n\nsheaf::hub_index_space_iterator::\nhub_index_space_iterator(const index_space_family& xid_spaces,\n\t\t\t const string& xname)\n{\n \/\/ Preconditions:\n\n require(conforms_to_state(xid_spaces, xname));\n\n \/\/ Body:\n\n attach_to(xid_spaces, xname);\n\n \/\/ Postconditions:\n\n ensure(invariant());\n ensure(is_attached());\n ensure(&id_spaces() == &xid_spaces);\n ensure(name() == xname);\n\n \/\/ Exit:\n\n return;\n}\n\nsheaf::hub_index_space_iterator&\nsheaf::hub_index_space_iterator::\noperator=(const hub_index_space_iterator& xother)\n{\n \/\/ Preconditions:\n\n \/\/ Body:\n\n _mbr_itr = new interval_set_iterator(*xother._mbr_itr);\n _rem = xother._rem;\n\n (void) explicit_index_space_iterator::operator=(xother);\n\n \/\/ Postconditions:\n\n ensure(invariant());\n ensure((*this) == xother);\n\n \/\/ Exit\n\n return *this;\n}\n\nsheaf::hub_index_space_iterator::\n~hub_index_space_iterator()\n{\n \/\/ Preconditions:\n\n \/\/ Body:\n\n if(_mbr_itr != 0)\n {\n delete _mbr_itr;\n }\n \n \/\/ Postconditions:\n\n \/\/ Exit:\n\n return;\n}\n\n\/\/ PROTECTED MEMBER FUNCTIONS\n\n\/\/ PRIVATE MEMBER FUNCTIONS\n\n\n\/\/ ===========================================================\n\/\/ EXPLICIT_INDEX_SPACE_ITERATOR FACET\n\/\/ ===========================================================\n\n\/\/ PUBLIC MEMBER FUNCTIONS\n\n\/\/ PROTECTED MEMBER FUNCTIONS\n\n\/\/ PRIVATE MAMBER FUNCTIONS\n\n\n\/\/ ===========================================================\n\/\/ INDEX_SPACE_ITERATOR FACET\n\/\/ ===========================================================\n\n\/\/ PUBLIC MEMBER FUNCTIONS\n\nsheaf::hub_index_space_iterator&\nsheaf::hub_index_space_iterator::\noperator=(const index_space_iterator& xother)\n{\n \/\/ Preconditions:\n\n require(is_ancestor_of(&xother));\n\n \/\/ Body:\n\n const hub_index_space_iterator& lother =\n dynamic_cast<const hub_index_space_iterator&>(xother);\n\n\n (void) this->operator=(lother);\n\n \/\/ Postconditions:\n\n ensure(invariant());\n ensure((*this) == xother);\n\n \/\/ Exit\n\n return *this;\n}\n\nbool\nsheaf::hub_index_space_iterator::\noperator==(const index_space_iterator& xother) const\n{\n \/\/ Preconditions:\n\n require(is_ancestor_of(&xother));\n\n \/\/ Body:\n\n bool result = explicit_index_space_iterator::operator==(xother);\n if(result && is_attached())\n {\n const hub_index_space_iterator& lother =\n dynamic_cast<const hub_index_space_iterator&>(xother);\n\n result = result && (*_mbr_itr == *lother._mbr_itr);\n result = result && (_rem == lother._rem);\n }\n \n \/\/ Postconditions:\n\n ensure(invariant());\n\n \/\/ Exit\n\n return result;\n}\n\nsheaf::hub_index_space_iterator*\nsheaf::hub_index_space_iterator::\nclone() const\n{\n hub_index_space_iterator* result;\n\n \/\/ Preconditions:\n\n \/\/ Body:\n\n result = new hub_index_space_iterator(*this);\n\n \/\/ Postconditions:\n\n ensure(result != 0);\n ensure(is_same_type(result));\n ensure(*result == *this);\n\n \/\/ Exit:\n\n return result;\n}\n\n\/\/ PROTECTED MEMBER FUNCTIONS\n\n\/\/ PRIVATE MAMBER FUNCTIONS\n\n\n\/\/ ===========================================================\n\/\/ ITERATOR FACET\n\/\/ ===========================================================\n\n\/\/ PUBLIC MEMBER FUNCTIONS\n\nvoid\nsheaf::hub_index_space_iterator::\nnext()\n{\n \/\/ Preconditions:\n\n require(is_attached());\n require(!is_done());\n\n \/\/ Body:\n\n define_old_variable(pod_type old_pod = pod());\n define_old_variable(pod_type old_hub_pod = hub_pod());\n\n \/\/ Iterate to the next member.\n \n _mbr_itr->next();\n\n if(_mbr_itr->is_done())\n {\n \/\/ The iteration is done.\n\n invalidate_ids();\n }\n else\n {\n \/\/ Still iterating over member ids;\n \/\/ set the ids.\n\n _pod = _mbr_itr->item();\n _hub_pod = _pod;\n }\n \n \/\/ Postconditions:\n\n ensure(invariant());\n ensure(is_done() || pod() > old_pod);\n ensure(is_done() || hub_pod() > old_hub_pod);\n\n \/\/ Exit:\n\n return;\n}\n\nvoid\nsheaf::hub_index_space_iterator::\nreset()\n{\n \/\/ Preconditions:\n\n require(is_attached());\n\n \/\/ Body:\n\n _mbr_itr->reset();\n \n if(_mbr_itr->is_done())\n {\n \/\/ The member set is empty, the iteration is done.\n\n invalidate_ids();\n }\n else\n {\n \/\/ There's at least one entry, the iteration is not done.\n\n _is_done = false;\n _pod = _mbr_itr->item();\n _hub_pod = _pod;\n }\n \n \/\/ Postconditions:\n\n ensure(invariant());\n\n \/\/ Exit:\n\n return;\n}\n\n\/\/ PROTECTED MEMBER FUNCTIONS\n\n\/\/ PRIVATE MEMBER FUNCTIONS\n\n\n\/\/ ===========================================================\n\/\/ HANDLE FACET\n\/\/ ===========================================================\n\n\/\/ PUBLIC MEMBER FUNCTIONS\n\nvoid\nsheaf::hub_index_space_iterator::\nattach_to(explicit_index_space_state* xstate)\n{\n \/\/ Preconditions:\n\n require(xstate != 0);\n require(conforms_to_state(xstate));\n\n \/\/ Body:\n\n \/\/ Assign the state information.\n\n primary_sum_index_space_state* lstate =\n reinterpret_cast<primary_sum_index_space_state*>(xstate);\n\n _state = xstate;\n _mbr_itr = lstate->_members.iterator(true);\n _rem = &lstate->_rem;\n\n \/\/ Start at the first id.\n\n reset();\n\n \/\/ Postconditions:\n\n ensure(invariant());\n ensure(is_attached());\n ensure(&state() == xstate);\n\n \/\/ Exit:\n\n return;\n}\n\nbool\nsheaf::hub_index_space_iterator::\nconforms_to_state(explicit_index_space_state* xstate) const\n{\n \/\/ Preconditions:\n\n \/\/ Body:\n\n bool result = (dynamic_cast<primary_sum_index_space_state*>(xstate) != 0);\n\n \/\/ Postconditions:\n\n ensure(is_basic_query);\n\n \/\/ Exit:\n\n return result;\n}\n\n\/\/ PROTECTED MEMBER FUNCTIONS\n\n\/\/ PRIVATE MAMBER FUNCTIONS\n\n\n\/\/ ===========================================================\n\/\/ ANY FACET\n\/\/ ===========================================================\n\n\/\/ PUBLIC MEMBER FUNCTIONS\n\nbool\nsheaf::hub_index_space_iterator::\nis_ancestor_of(const any *other) const\n{\n \/\/ Preconditions:\n\n require(other != 0);\n\n \/\/ Body:\n\n \/\/ True if other conforms to this\n\n bool result =\n dynamic_cast<const hub_index_space_iterator*>(other) != 0;\n\n \/\/ Postconditions:\n\n return result;\n}\n\nbool\nsheaf::hub_index_space_iterator::\ninvariant() const\n{\n bool result = true;\n\n if(invariant_check())\n {\n \/\/ Must satisfy base class invariant\n\n invariance(explicit_index_space_iterator::invariant());\n\n \/\/ Prevent recursive calls to invariant\n\n disable_invariant_check();\n\n \/\/ Invariances for this class:\n\n invariance(is_done() || pod() == hub_pod());\n\n \/\/ Finished, turn invariant checking back on.\n\n enable_invariant_check();\n }\n\n \/\/ Exit\n\n return result;\n}\n\n\/\/ PROTECTED MEMBER FUNCTIONS\n\n\/\/ PRIVATE MEMBER FUNCTIONS\n\n\n\/\/ ===========================================================\n\/\/ NON-MEMBER FUNCTIONS\n\/\/ ===========================================================\n\n\n<commit_msg>Fixed memory leak in hub_index_space_iterator. Was not deleting _mbr_itr when attaching to a new state. This has nothing to do with the current crash on Windows but was found during the valgrind tests.<commit_after>\n\n\/\/\n\/\/ Copyright (c) 2011 Limit Point Systems, Inc.\n\/\/\n\n\/\/\/ @file\n\/\/\/ Implementation for class hub_index_space_iterator\n\n#include \"hub_index_space_iterator.h\"\n\n#include \"assert_contract.h\"\n#include \"explicit_index_space_handle.h\"\n#include \"index_space_family.h\"\n#include \"interval_set_iterator.h\"\n#include \"primary_sum_index_space_state.h\"\n\n\/\/ ===========================================================\n\/\/ HUB_INDEX_SPACE_ITERATOR FACET\n\/\/ ===========================================================\n\n\/\/ PUBLIC MEMBER FUNCTIONS\n\nsheaf::hub_index_space_iterator::\nhub_index_space_iterator()\n : _mbr_itr(0)\n{\n \/\/ Preconditions:\n\n \/\/ Body:\n\n \/\/ Postconditions:\n\n ensure(invariant());\n ensure(!is_attached());\n\n \/\/ Exit:\n\n return;\n}\n\nsheaf::hub_index_space_iterator::\nhub_index_space_iterator(const hub_index_space_iterator& xother)\n{\n \/\/ Preconditions:\n\n \/\/ Body:\n\n *this = xother;\n\n \/\/ Postconditions:\n\n ensure(invariant());\n ensure((*this) == xother);\n\n \/\/ Exit:\n\n return;\n}\n\nsheaf::hub_index_space_iterator::\nhub_index_space_iterator(const index_space_family& xid_spaces,\n\t\t\t pod_type xindex)\n : _mbr_itr(0)\n{\n \/\/ Preconditions:\n\n require(conforms_to_state(xid_spaces, xindex));\n\n \/\/ Body:\n\n attach_to(xid_spaces, xindex);\n\n \/\/ Postconditions:\n\n ensure(invariant());\n ensure(is_attached());\n ensure(&id_spaces() == &xid_spaces);\n ensure(index() == xindex);\n\n \/\/ Exit:\n\n return;\n}\n\nsheaf::hub_index_space_iterator::\nhub_index_space_iterator(const index_space_family& xid_spaces,\n\t\t\t const string& xname)\n : _mbr_itr(0)\n{\n \/\/ Preconditions:\n\n require(conforms_to_state(xid_spaces, xname));\n\n \/\/ Body:\n\n attach_to(xid_spaces, xname);\n\n \/\/ Postconditions:\n\n ensure(invariant());\n ensure(is_attached());\n ensure(&id_spaces() == &xid_spaces);\n ensure(name() == xname);\n\n \/\/ Exit:\n\n return;\n}\n\nsheaf::hub_index_space_iterator&\nsheaf::hub_index_space_iterator::\noperator=(const hub_index_space_iterator& xother)\n{\n \/\/ Preconditions:\n\n \/\/ Body:\n\n _mbr_itr = new interval_set_iterator(*xother._mbr_itr);\n _rem = xother._rem;\n\n (void) explicit_index_space_iterator::operator=(xother);\n\n \/\/ Postconditions:\n\n ensure(invariant());\n ensure((*this) == xother);\n\n \/\/ Exit\n\n return *this;\n}\n\nsheaf::hub_index_space_iterator::\n~hub_index_space_iterator()\n{\n \/\/ Preconditions:\n\n \/\/ Body:\n\n if(_mbr_itr != 0)\n {\n delete _mbr_itr;\n }\n \n \/\/ Postconditions:\n\n \/\/ Exit:\n\n return;\n}\n\n\/\/ PROTECTED MEMBER FUNCTIONS\n\n\/\/ PRIVATE MEMBER FUNCTIONS\n\n\n\/\/ ===========================================================\n\/\/ EXPLICIT_INDEX_SPACE_ITERATOR FACET\n\/\/ ===========================================================\n\n\/\/ PUBLIC MEMBER FUNCTIONS\n\n\/\/ PROTECTED MEMBER FUNCTIONS\n\n\/\/ PRIVATE MAMBER FUNCTIONS\n\n\n\/\/ ===========================================================\n\/\/ INDEX_SPACE_ITERATOR FACET\n\/\/ ===========================================================\n\n\/\/ PUBLIC MEMBER FUNCTIONS\n\nsheaf::hub_index_space_iterator&\nsheaf::hub_index_space_iterator::\noperator=(const index_space_iterator& xother)\n{\n \/\/ Preconditions:\n\n require(is_ancestor_of(&xother));\n\n \/\/ Body:\n\n const hub_index_space_iterator& lother =\n dynamic_cast<const hub_index_space_iterator&>(xother);\n\n\n (void) this->operator=(lother);\n\n \/\/ Postconditions:\n\n ensure(invariant());\n ensure((*this) == xother);\n\n \/\/ Exit\n\n return *this;\n}\n\nbool\nsheaf::hub_index_space_iterator::\noperator==(const index_space_iterator& xother) const\n{\n \/\/ Preconditions:\n\n require(is_ancestor_of(&xother));\n\n \/\/ Body:\n\n bool result = explicit_index_space_iterator::operator==(xother);\n if(result && is_attached())\n {\n const hub_index_space_iterator& lother =\n dynamic_cast<const hub_index_space_iterator&>(xother);\n\n result = result && (*_mbr_itr == *lother._mbr_itr);\n result = result && (_rem == lother._rem);\n }\n \n \/\/ Postconditions:\n\n ensure(invariant());\n\n \/\/ Exit\n\n return result;\n}\n\nsheaf::hub_index_space_iterator*\nsheaf::hub_index_space_iterator::\nclone() const\n{\n hub_index_space_iterator* result;\n\n \/\/ Preconditions:\n\n \/\/ Body:\n\n result = new hub_index_space_iterator(*this);\n\n \/\/ Postconditions:\n\n ensure(result != 0);\n ensure(is_same_type(result));\n ensure(*result == *this);\n\n \/\/ Exit:\n\n return result;\n}\n\n\/\/ PROTECTED MEMBER FUNCTIONS\n\n\/\/ PRIVATE MAMBER FUNCTIONS\n\n\n\/\/ ===========================================================\n\/\/ ITERATOR FACET\n\/\/ ===========================================================\n\n\/\/ PUBLIC MEMBER FUNCTIONS\n\nvoid\nsheaf::hub_index_space_iterator::\nnext()\n{\n \/\/ Preconditions:\n\n require(is_attached());\n require(!is_done());\n\n \/\/ Body:\n\n define_old_variable(pod_type old_pod = pod());\n define_old_variable(pod_type old_hub_pod = hub_pod());\n\n \/\/ Iterate to the next member.\n \n _mbr_itr->next();\n\n if(_mbr_itr->is_done())\n {\n \/\/ The iteration is done.\n\n invalidate_ids();\n }\n else\n {\n \/\/ Still iterating over member ids;\n \/\/ set the ids.\n\n _pod = _mbr_itr->item();\n _hub_pod = _pod;\n }\n \n \/\/ Postconditions:\n\n ensure(invariant());\n ensure(is_done() || pod() > old_pod);\n ensure(is_done() || hub_pod() > old_hub_pod);\n\n \/\/ Exit:\n\n return;\n}\n\nvoid\nsheaf::hub_index_space_iterator::\nreset()\n{\n \/\/ Preconditions:\n\n require(is_attached());\n\n \/\/ Body:\n\n _mbr_itr->reset();\n \n if(_mbr_itr->is_done())\n {\n \/\/ The member set is empty, the iteration is done.\n\n invalidate_ids();\n }\n else\n {\n \/\/ There's at least one entry, the iteration is not done.\n\n _is_done = false;\n _pod = _mbr_itr->item();\n _hub_pod = _pod;\n }\n \n \/\/ Postconditions:\n\n ensure(invariant());\n\n \/\/ Exit:\n\n return;\n}\n\n\/\/ PROTECTED MEMBER FUNCTIONS\n\n\/\/ PRIVATE MEMBER FUNCTIONS\n\n\n\/\/ ===========================================================\n\/\/ HANDLE FACET\n\/\/ ===========================================================\n\n\/\/ PUBLIC MEMBER FUNCTIONS\n\nvoid\nsheaf::hub_index_space_iterator::\nattach_to(explicit_index_space_state* xstate)\n{\n \/\/ Preconditions:\n\n require(xstate != 0);\n require(conforms_to_state(xstate));\n\n \/\/ Body:\n\n \/\/ Assign the state information.\n\n primary_sum_index_space_state* lstate =\n reinterpret_cast<primary_sum_index_space_state*>(xstate);\n\n if(_mbr_itr != 0)\n {\n delete _mbr_itr;\n }\n\n _state = xstate;\n _mbr_itr = lstate->_members.iterator(true);\n _rem = &lstate->_rem;\n\n \/\/ Start at the first id.\n\n reset();\n\n \/\/ Postconditions:\n\n ensure(invariant());\n ensure(is_attached());\n ensure(&state() == xstate);\n\n \/\/ Exit:\n\n return;\n}\n\nbool\nsheaf::hub_index_space_iterator::\nconforms_to_state(explicit_index_space_state* xstate) const\n{\n \/\/ Preconditions:\n\n \/\/ Body:\n\n bool result = (dynamic_cast<primary_sum_index_space_state*>(xstate) != 0);\n\n \/\/ Postconditions:\n\n ensure(is_basic_query);\n\n \/\/ Exit:\n\n return result;\n}\n\n\/\/ PROTECTED MEMBER FUNCTIONS\n\n\/\/ PRIVATE MAMBER FUNCTIONS\n\n\n\/\/ ===========================================================\n\/\/ ANY FACET\n\/\/ ===========================================================\n\n\/\/ PUBLIC MEMBER FUNCTIONS\n\nbool\nsheaf::hub_index_space_iterator::\nis_ancestor_of(const any *other) const\n{\n \/\/ Preconditions:\n\n require(other != 0);\n\n \/\/ Body:\n\n \/\/ True if other conforms to this\n\n bool result =\n dynamic_cast<const hub_index_space_iterator*>(other) != 0;\n\n \/\/ Postconditions:\n\n return result;\n}\n\nbool\nsheaf::hub_index_space_iterator::\ninvariant() const\n{\n bool result = true;\n\n if(invariant_check())\n {\n \/\/ Must satisfy base class invariant\n\n invariance(explicit_index_space_iterator::invariant());\n\n \/\/ Prevent recursive calls to invariant\n\n disable_invariant_check();\n\n \/\/ Invariances for this class:\n\n invariance(is_done() || pod() == hub_pod());\n\n \/\/ Finished, turn invariant checking back on.\n\n enable_invariant_check();\n }\n\n \/\/ Exit\n\n return result;\n}\n\n\/\/ PROTECTED MEMBER FUNCTIONS\n\n\/\/ PRIVATE MEMBER FUNCTIONS\n\n\n\/\/ ===========================================================\n\/\/ NON-MEMBER FUNCTIONS\n\/\/ ===========================================================\n\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2015 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"sky\/shell\/platform\/mojo\/platform_view_mojo.h\"\n\n#include \"base\/bind.h\"\n#include \"base\/location.h\"\n#include \"base\/single_thread_task_runner.h\"\n#include \"mojo\/public\/cpp\/application\/connect.h\"\n#include \"sky\/shell\/gpu\/mojo\/rasterizer_mojo.h\"\n\nnamespace sky {\nnamespace shell {\nnamespace {\n\npointer::PointerType GetTypeFromAction(mojo::EventType type) {\n switch (type) {\n case mojo::EventType::POINTER_CANCEL:\n return pointer::PointerType::CANCEL;\n case mojo::EventType::POINTER_DOWN:\n return pointer::PointerType::DOWN;\n case mojo::EventType::POINTER_MOVE:\n return pointer::PointerType::MOVE;\n case mojo::EventType::POINTER_UP:\n return pointer::PointerType::UP;\n default:\n DCHECK(false);\n return pointer::PointerType::CANCEL;\n }\n}\n\npointer::PointerKind GetKindFromKind(mojo::PointerKind kind) {\n switch (kind) {\n case mojo::PointerKind::TOUCH:\n return pointer::PointerKind::TOUCH;\n case mojo::PointerKind::MOUSE:\n return pointer::PointerKind::MOUSE;\n }\n DCHECK(false);\n return pointer::PointerKind::TOUCH;\n}\n\n} \/\/ namespace\n\nPlatformView* PlatformView::Create(const Config& config) {\n return new PlatformViewMojo(config);\n}\n\nPlatformViewMojo::PlatformViewMojo(const Config& config)\n : PlatformView(config), dispatcher_binding_(this) {\n}\n\nPlatformViewMojo::~PlatformViewMojo() {\n}\n\nvoid PlatformViewMojo::Init(mojo::Shell* shell) {\n mojo::ConnectToService(shell, \"mojo:native_viewport_service\", &viewport_);\n\n \/\/ Grab the application connector so that we can connect to services later\n shell->CreateApplicationConnector(GetProxy(&connector_));\n\n mojo::NativeViewportEventDispatcherPtr ptr;\n dispatcher_binding_.Bind(GetProxy(&ptr));\n viewport_->SetEventDispatcher(ptr.Pass());\n\n mojo::SizePtr size = mojo::Size::New();\n size->width = 320;\n size->height = 640;\n\n viewport_->Create(\n size.Clone(),\n mojo::SurfaceConfiguration::New(),\n [this](mojo::ViewportMetricsPtr metrics) {\n OnMetricsChanged(metrics.Pass());\n });\n viewport_->Show();\n\n mojo::ContextProviderPtr context_provider;\n viewport_->GetContextProvider(GetProxy(&context_provider));\n\n mojo::InterfacePtrInfo<mojo::ContextProvider> context_provider_info = context_provider.PassInterface();\n\n RasterizerMojo* rasterizer = static_cast<RasterizerMojo*>(config_.rasterizer);\n config_.ui_task_runner->PostTask(\n FROM_HERE, base::Bind(&UIDelegate::OnOutputSurfaceCreated,\n config_.ui_delegate,\n base::Bind(&RasterizerMojo::OnContextProviderAvailable,\n rasterizer->GetWeakPtr(), base::Passed(&context_provider_info))));\n\n ConnectToEngine(GetProxy(&sky_engine_));\n\n}\n\nvoid PlatformViewMojo::Run(const mojo::String& url,\n ServicesDataPtr services,\n mojo::asset_bundle::AssetBundlePtr bundle) {\n\n mojo::ServiceProviderPtr services_provided_by_embedder;\n service_provider_.Bind(GetProxy(&services_provided_by_embedder));\n service_provider_.AddService<keyboard::KeyboardService>(this);\n services->services_provided_by_embedder = services_provided_by_embedder.Pass();\n\n sky_engine_->SetServices(services.Pass());\n sky_engine_->RunFromAssetBundle(url, bundle.Pass());\n}\n\nvoid PlatformViewMojo::OnMetricsChanged(mojo::ViewportMetricsPtr metrics) {\n DCHECK(metrics);\n viewport_->RequestMetrics(\n [this](mojo::ViewportMetricsPtr metrics) {\n OnMetricsChanged(metrics.Pass());\n });\n\n sky::ViewportMetricsPtr sky_metrics = sky::ViewportMetrics::New();\n sky_metrics->physical_width = metrics->size->width;\n sky_metrics->physical_height = metrics->size->height;\n sky_metrics->device_pixel_ratio = metrics->device_pixel_ratio;\n sky_engine_->OnViewportMetricsChanged(sky_metrics.Pass());\n}\n\nvoid PlatformViewMojo::OnEvent(mojo::EventPtr event,\n const mojo::Callback<void()>& callback) {\n DCHECK(event);\n switch (event->action) {\n case mojo::EventType::POINTER_CANCEL:\n case mojo::EventType::POINTER_DOWN:\n case mojo::EventType::POINTER_MOVE:\n case mojo::EventType::POINTER_UP: {\n mojo::PointerDataPtr data = event->pointer_data.Pass();\n if (!data)\n break;\n pointer::PointerPacketPtr packet;\n int packetIndex = 0;\n if (pointer_positions_.count(data->pointer_id) > 0) {\n if (event->action == mojo::EventType::POINTER_UP ||\n event->action == mojo::EventType::POINTER_CANCEL) {\n std::pair<float, float> last_position = pointer_positions_[data->pointer_id];\n if (last_position.first != data->x || last_position.second != data->y) {\n packet = pointer::PointerPacket::New();\n packet->pointers = mojo::Array<pointer::PointerPtr>::New(2);\n packet->pointers[packetIndex] = CreateEvent(pointer::PointerType::MOVE, event.get(), data.get());\n packetIndex += 1;\n }\n pointer_positions_.erase(data->pointer_id);\n }\n } else {\n \/\/ We don't currently support hover moves.\n \/\/ If we want to support those, we have to first implement\n \/\/ added\/removed events for pointers.\n \/\/ See: https:\/\/github.com\/flutter\/flutter\/issues\/720\n if (event->action != mojo::EventType::POINTER_DOWN)\n break;\n }\n if (packetIndex == 0) {\n packet = pointer::PointerPacket::New();\n packet->pointers = mojo::Array<pointer::PointerPtr>::New(1);\n }\n packet->pointers[packetIndex] = CreateEvent(GetTypeFromAction(event->action), event.get(), data.get());\n sky_engine_->OnPointerPacket(packet.Pass());\n break;\n }\n case mojo::EventType::KEY_PRESSED:\n case mojo::EventType::KEY_RELEASED:\n if (key_event_dispatcher_) {\n key_event_dispatcher_->OnEvent(event.Pass(), callback);\n return; \/\/ key_event_dispatcher_ will invoke callback\n }\n default:\n break;\n }\n\n callback.Run();\n}\n\npointer::PointerPtr PlatformViewMojo::CreateEvent(pointer::PointerType type, mojo::Event* event, mojo::PointerData* data) {\n DCHECK(data);\n pointer::PointerPtr pointer = pointer::Pointer::New();\n pointer->time_stamp = event->time_stamp;\n pointer->pointer = data->pointer_id;\n pointer->type = type;\n pointer->kind = GetKindFromKind(data->kind);\n pointer->x = data->x;\n pointer->y = data->y;\n pointer->buttons = static_cast<int32_t>(event->flags);\n pointer->pressure = data->pressure;\n pointer->radius_major = data->radius_major;\n pointer->radius_minor = data->radius_minor;\n pointer->orientation = data->orientation;\n if (event->action != mojo::EventType::POINTER_UP ||\n event->action != mojo::EventType::POINTER_CANCEL)\n pointer_positions_[data->pointer_id] = { data->x, data->y };\n return pointer.Pass();\n}\n\nvoid PlatformViewMojo::Create(\n mojo::ApplicationConnection* connection,\n mojo::InterfaceRequest<keyboard::KeyboardService> request) {\n\n mojo::ServiceProviderPtr keyboard_service_provider;\n connector_->ConnectToApplication(\n \"mojo:keyboard\",\n GetProxy(&keyboard_service_provider),\n nullptr);\n\n#if defined(OS_LINUX)\n keyboard::KeyboardServiceFactoryPtr factory;\n mojo::ConnectToService(keyboard_service_provider.get(), &factory);\n factory->CreateKeyboardService(GetProxy(&key_event_dispatcher_), request.Pass());\n#else\n keyboard_service_provider->ConnectToService(\n keyboard::KeyboardService::Name_,\n request.PassMessagePipe());\n#endif\n}\n\n} \/\/ namespace shell\n} \/\/ namespace sky\n<commit_msg>Fix mouse on linux.<commit_after>\/\/ Copyright 2015 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"sky\/shell\/platform\/mojo\/platform_view_mojo.h\"\n\n#include \"base\/bind.h\"\n#include \"base\/location.h\"\n#include \"base\/single_thread_task_runner.h\"\n#include \"mojo\/public\/cpp\/application\/connect.h\"\n#include \"sky\/shell\/gpu\/mojo\/rasterizer_mojo.h\"\n\nnamespace sky {\nnamespace shell {\nnamespace {\n\npointer::PointerType GetTypeFromAction(mojo::EventType type) {\n switch (type) {\n case mojo::EventType::POINTER_CANCEL:\n return pointer::PointerType::CANCEL;\n case mojo::EventType::POINTER_DOWN:\n return pointer::PointerType::DOWN;\n case mojo::EventType::POINTER_MOVE:\n return pointer::PointerType::MOVE;\n case mojo::EventType::POINTER_UP:\n return pointer::PointerType::UP;\n default:\n DCHECK(false);\n return pointer::PointerType::CANCEL;\n }\n}\n\npointer::PointerKind GetKindFromKind(mojo::PointerKind kind) {\n switch (kind) {\n case mojo::PointerKind::TOUCH:\n return pointer::PointerKind::TOUCH;\n case mojo::PointerKind::MOUSE:\n return pointer::PointerKind::MOUSE;\n }\n DCHECK(false);\n return pointer::PointerKind::TOUCH;\n}\n\n} \/\/ namespace\n\nPlatformView* PlatformView::Create(const Config& config) {\n return new PlatformViewMojo(config);\n}\n\nPlatformViewMojo::PlatformViewMojo(const Config& config)\n : PlatformView(config), dispatcher_binding_(this) {\n}\n\nPlatformViewMojo::~PlatformViewMojo() {\n}\n\nvoid PlatformViewMojo::Init(mojo::Shell* shell) {\n mojo::ConnectToService(shell, \"mojo:native_viewport_service\", &viewport_);\n\n \/\/ Grab the application connector so that we can connect to services later\n shell->CreateApplicationConnector(GetProxy(&connector_));\n\n mojo::NativeViewportEventDispatcherPtr ptr;\n dispatcher_binding_.Bind(GetProxy(&ptr));\n viewport_->SetEventDispatcher(ptr.Pass());\n\n mojo::SizePtr size = mojo::Size::New();\n size->width = 320;\n size->height = 640;\n\n viewport_->Create(\n size.Clone(),\n mojo::SurfaceConfiguration::New(),\n [this](mojo::ViewportMetricsPtr metrics) {\n OnMetricsChanged(metrics.Pass());\n });\n viewport_->Show();\n\n mojo::ContextProviderPtr context_provider;\n viewport_->GetContextProvider(GetProxy(&context_provider));\n\n mojo::InterfacePtrInfo<mojo::ContextProvider> context_provider_info = context_provider.PassInterface();\n\n RasterizerMojo* rasterizer = static_cast<RasterizerMojo*>(config_.rasterizer);\n config_.ui_task_runner->PostTask(\n FROM_HERE, base::Bind(&UIDelegate::OnOutputSurfaceCreated,\n config_.ui_delegate,\n base::Bind(&RasterizerMojo::OnContextProviderAvailable,\n rasterizer->GetWeakPtr(), base::Passed(&context_provider_info))));\n\n ConnectToEngine(GetProxy(&sky_engine_));\n\n}\n\nvoid PlatformViewMojo::Run(const mojo::String& url,\n ServicesDataPtr services,\n mojo::asset_bundle::AssetBundlePtr bundle) {\n\n mojo::ServiceProviderPtr services_provided_by_embedder;\n service_provider_.Bind(GetProxy(&services_provided_by_embedder));\n service_provider_.AddService<keyboard::KeyboardService>(this);\n services->services_provided_by_embedder = services_provided_by_embedder.Pass();\n\n sky_engine_->SetServices(services.Pass());\n sky_engine_->RunFromAssetBundle(url, bundle.Pass());\n}\n\nvoid PlatformViewMojo::OnMetricsChanged(mojo::ViewportMetricsPtr metrics) {\n DCHECK(metrics);\n viewport_->RequestMetrics(\n [this](mojo::ViewportMetricsPtr metrics) {\n OnMetricsChanged(metrics.Pass());\n });\n\n sky::ViewportMetricsPtr sky_metrics = sky::ViewportMetrics::New();\n sky_metrics->physical_width = metrics->size->width;\n sky_metrics->physical_height = metrics->size->height;\n sky_metrics->device_pixel_ratio = metrics->device_pixel_ratio;\n sky_engine_->OnViewportMetricsChanged(sky_metrics.Pass());\n}\n\nvoid PlatformViewMojo::OnEvent(mojo::EventPtr event,\n const mojo::Callback<void()>& callback) {\n DCHECK(event);\n switch (event->action) {\n case mojo::EventType::POINTER_CANCEL:\n case mojo::EventType::POINTER_DOWN:\n case mojo::EventType::POINTER_MOVE:\n case mojo::EventType::POINTER_UP: {\n mojo::PointerDataPtr data = event->pointer_data.Pass();\n if (!data)\n break;\n pointer::PointerPacketPtr packet;\n int packetIndex = 0;\n if (pointer_positions_.count(data->pointer_id) > 0) {\n if (event->action == mojo::EventType::POINTER_UP ||\n event->action == mojo::EventType::POINTER_CANCEL) {\n std::pair<float, float> last_position = pointer_positions_[data->pointer_id];\n if (last_position.first != data->x || last_position.second != data->y) {\n packet = pointer::PointerPacket::New();\n packet->pointers = mojo::Array<pointer::PointerPtr>::New(2);\n packet->pointers[packetIndex] = CreateEvent(pointer::PointerType::MOVE, event.get(), data.get());\n packetIndex += 1;\n }\n pointer_positions_.erase(data->pointer_id);\n }\n } else {\n \/\/ We don't currently support hover moves.\n \/\/ If we want to support those, we have to first implement\n \/\/ added\/removed events for pointers.\n \/\/ See: https:\/\/github.com\/flutter\/flutter\/issues\/720\n if (event->action != mojo::EventType::POINTER_DOWN)\n break;\n }\n if (packetIndex == 0) {\n packet = pointer::PointerPacket::New();\n packet->pointers = mojo::Array<pointer::PointerPtr>::New(1);\n }\n packet->pointers[packetIndex] = CreateEvent(GetTypeFromAction(event->action), event.get(), data.get());\n sky_engine_->OnPointerPacket(packet.Pass());\n break;\n }\n case mojo::EventType::KEY_PRESSED:\n case mojo::EventType::KEY_RELEASED:\n if (key_event_dispatcher_) {\n key_event_dispatcher_->OnEvent(event.Pass(), callback);\n return; \/\/ key_event_dispatcher_ will invoke callback\n }\n default:\n break;\n }\n\n callback.Run();\n}\n\npointer::PointerPtr PlatformViewMojo::CreateEvent(pointer::PointerType type, mojo::Event* event, mojo::PointerData* data) {\n DCHECK(data);\n pointer::PointerPtr pointer = pointer::Pointer::New();\n pointer->time_stamp = event->time_stamp;\n pointer->pointer = data->pointer_id;\n pointer->type = type;\n pointer->kind = GetKindFromKind(data->kind);\n pointer->x = data->x;\n pointer->y = data->y;\n pointer->buttons = static_cast<int32_t>(event->flags);\n pointer->pressure = data->pressure;\n pointer->radius_major = data->radius_major;\n pointer->radius_minor = data->radius_minor;\n pointer->orientation = data->orientation;\n if (event->action != mojo::EventType::POINTER_UP &&\n event->action != mojo::EventType::POINTER_CANCEL)\n pointer_positions_[data->pointer_id] = { data->x, data->y };\n return pointer.Pass();\n}\n\nvoid PlatformViewMojo::Create(\n mojo::ApplicationConnection* connection,\n mojo::InterfaceRequest<keyboard::KeyboardService> request) {\n\n mojo::ServiceProviderPtr keyboard_service_provider;\n connector_->ConnectToApplication(\n \"mojo:keyboard\",\n GetProxy(&keyboard_service_provider),\n nullptr);\n\n#if defined(OS_LINUX)\n keyboard::KeyboardServiceFactoryPtr factory;\n mojo::ConnectToService(keyboard_service_provider.get(), &factory);\n factory->CreateKeyboardService(GetProxy(&key_event_dispatcher_), request.Pass());\n#else\n keyboard_service_provider->ConnectToService(\n keyboard::KeyboardService::Name_,\n request.PassMessagePipe());\n#endif\n}\n\n} \/\/ namespace shell\n} \/\/ namespace sky\n<|endoftext|>"} {"text":"<commit_before>\/\/ -*- Mode: C++; tab-width: 2; -*-\n\/\/ vi: set ts=2:\n\/\/\n\n#include <BALL\/KERNEL\/bond.h>\n#include <BALL\/KERNEL\/molecule.h>\n#include <BALL\/KERNEL\/PTE.h>\n#include <BALL\/KERNEL\/selector.h>\n#include <BALL\/FORMAT\/molFileFactory.h>\n#include <BALL\/FORMAT\/dockResultFile.h>\n#include <BALL\/FORMAT\/commandlineParser.h>\n#include <BALL\/STRUCTURE\/molecularSimilarity.h>\n\n#include <boost\/unordered_map.hpp>\n\n#include <openbabel\/mol.h>\n#include <openbabel\/builder.h>\n#include <openbabel\/forcefield.h>\n#include \"version.h\"\n\n\nusing namespace BALL;\nusing namespace std;\n\n\n\/\/ Check whether the given molecule really contains only one molecule\nvoid checkBonds(const Atom* atom, set<const Atom*>& visited_atoms)\n{\n\tif (visited_atoms.find(atom) != visited_atoms.end())\n\t{\n\t\treturn;\n\t}\n\t\n\tvisited_atoms.insert(atom);\n\tfor (Atom::BondConstIterator b_it = atom->beginBond(); +b_it; b_it++)\n\t{\n\t\tcheckBonds(b_it->getPartner(*atom), visited_atoms);\n\t}\n}\n\n\n\/\/ Check if a molecule has atoms, is single connected component and has elements defined\nbool basicMoleculeCheck(Molecule* mol)\n{\n\t\/\/ Check if it molecule has no atoms\n\tif (mol->countAtoms() == 0)\n\t{\n\t\treturn false;\n\t}\n\t\n\t\/\/ Check if molecule is a contains a single fragment\n\tset<const Atom*> visited_atoms;\n\tcheckBonds(&*mol->beginAtom(), visited_atoms);\n\tif (visited_atoms.size() != mol->countAtoms())\n\t{\n\t\treturn false;\n\t}\n\t\n\t\/\/ Check if there are undefined elements\n\tfor (AtomConstIterator it=mol->beginAtom(); it!=mol->endAtom(); ++it)\n\t{\n\t\tif (it->getElement().getName() == BALL_ELEMENT_NAME_DEFAULT)\n\t\t{\n\t\t\treturn false;\n\t\t}\n\t}\n\t\n\treturn true;\n}\n\n\n\/\/ Basic check if a ligand contains a hydrogen and thus can be regarded as \"protonated\"\nbool hasHydrogensCheck(Molecule* mol)\n{\n\tfor (AtomConstIterator it = mol->beginAtom(); +it; it++)\n\t{\n\t\tif (it->getElement().getSymbol() == \"H\")\n\t\t{\n\t\t\treturn true;\n\t\t}\n\t}\n\t\n\treturn false;\n}\n\n\n\/\/ Check if a valid molecule is ready for docking\nbool advancedMoleculeCheck(Molecule* mol)\n{\n\tbool all_x_zero = true;\n\tbool all_y_zero = true;\n\tbool all_z_zero = true;\n\t\n\tfor (AtomConstIterator it = mol->beginAtom(); +it; it++)\n\t{\n\t\tif (fabs(it->getCharge()) > 5)\n\t\t{\n\t\t\treturn false;\n\t\t}\n\t\t\n\t\tfor (Atom::BondConstIterator b_it = it->beginBond(); +b_it; b_it++)\n\t\t{\n\t\t\tif (b_it->getLength() < 0.7 || b_it->getLength() > 2.5)\n\t\t\t{\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t\t\n\t\tconst TVector3<float>& pos = it->getPosition();\n\t\tif (all_x_zero)\n\t\t{\n\t\t\tif (fabs(pos[0]) > 0.001)\n\t\t\t{\n\t\t\t\tall_x_zero = false;\n\t\t\t}\n\t\t}\n\t\tif (all_y_zero)\n\t\t{\n\t\t\tif (fabs(pos[1]) > 0.001)\n\t\t\t{\n\t\t\t\tall_y_zero = false;\n\t\t\t}\n\t\t}\n\t\tif (all_z_zero)\n\t\t{\n\t\t\tif (fabs(pos[2]) > 0.001)\n\t\t\t{\n\t\t\t\tall_z_zero = false;\n\t\t\t}\n\t\t}\n\t}\n\t\n\tif (all_x_zero || all_y_zero || all_z_zero)\n\t{\n\t\treturn false;\n\t}\n\telse\n\t{\n\t\treturn true;\n\t}\n}\n\n\nint main(int argc, char* argv[])\n{\n\tCommandlineParser parpars(\"Ligand3DGenerator\", \"generate 3D coordinates for small molecules\", VERSION, String(__DATE__), \"Preparation\");\n\tparpars.registerParameter(\"i\", \"input file\", INFILE, true);\n\tparpars.registerParameter(\"o\", \"output file\", OUTFILE, true);\n\tparpars.registerParameter(\"ph\", \"pH-value for pH-dep. protonation\", DOUBLE, false, \"7.0\");\n\tparpars.registerFlag(\"rm\", \"remove input file when finished\");\n\tparpars.registerFlag(\"k\", \"keep existing 3D coordinates (flag precedes '-kp')\");\n\tparpars.registerFlag(\"kp\", \"keep existing 3D coordinates but re-protonate compound in a pH dependent manner (flag is preceded by '-k')\");\n\tString man = String(\"This tool takes input molecules and generates a single 3D conformation which is ready for docking. The input has to be a chemical file\\n\\\ncontaining valid topologies and conistent bond order assignements. 2D coordinates in the input file are overwritten, 3D coordinates can be kept ('-k' or '-kp').\\n\\n\\\n '-k': 3D coordinates are tried to be kept. Molecules with non-zero coordinates in all three dimensions are passed through without modifications. \\n\\\n However, if a molecule is not ready for docking (i.e. unusual bond leghts, unusual charges), the molecule will be rebuild and new \\n\\\n 3D coordinates are assigned. If only hydrogens are missing, the coordinates of non-hydrogen atoms are kept but the molecule gets newly protonated.\\n\\\n '-kp': 3D coordinates are tried to be kept as for the '-k' flag but the molecule will be newly protonated.\\n\\n\\\nPlease note that the main purpose of this tool is to generate valid starting conformations for docking or other optimization procedures.\\n\\\nTherefore, the generated 3D coordinates for each fragment should be all right, but in extreme cases (i.e. very large and\/or complex molecules) \\n\\\ndifferent fragments might still overlap with each other.\\n\\n\\\nSupported formats are \") + MolFileFactory::getSupportedFormats() + String(\".\");\n\tparpars.setToolManual(man);\n\tparpars.setSupportedFormats(\"i\",MolFileFactory::getSupportedFormats());\n\tparpars.setSupportedFormats(\"o\",MolFileFactory::getSupportedFormats());\n\tparpars.setOutputFormatSource(\"o\",\"i\");\n\tparpars.parse(argc, argv);\n\t\n\tGenericMolFile* input = MolFileFactory::open(parpars.get(\"i\"), ios::in);\n\tGenericMolFile* output = MolFileFactory::open(parpars.get(\"o\"), ios::out, input);\n\tDockResultFile* drf_output = dynamic_cast<DockResultFile*>(output);\n\tif (drf_output)\n\t{\n\t\tdrf_output->setToolInfo(parpars.getStartCommand(), parpars.getStartTime());\n\t}\n\t\n\tdouble pH = 7.4;\n\tif (parpars.get(\"ph\") != CommandlineParser::NOT_FOUND)\n\t{\n\t\tpH = parpars.get(\"ph\").toDouble();\n\t}\n\t\n\tbool keep3Dcoords = false;\n\tif (parpars.has(\"k\"))\n\t{\n\t\tkeep3Dcoords = true;\n\t}\n\t\n\tbool keep3DcoordsProtonate = false;\n\tif (parpars.has(\"kp\"))\n\t{\n\t\tkeep3DcoordsProtonate = true;\n\t}\n\t\n\tOpenBabel::OBForceField* pFF = OpenBabel::OBForceField::FindForceField(\"MMFF94\");\n\tif (!pFF)\n\t{\n\t\tcerr << \"[Error:] Openbabel MMFF force-field could not be found.\\nPlease make sure to link this executable to plugin_forcefields.so, \/otherwise the openbabel forcefield-plugins cannot be used!\" << endl;\n\t\texit(1);\n\t}\n\t\n\tString mol_name;\n\tbool setup_ok;\n\tbool ob_error;\n\tbool rebuild_mol;\n\tint no_written = 0;\n\tint no_ignored = 0;\n\tMolecule *mol, *new_mol;\n\tOpenBabel::OBMol *obmol;\n\tboost::unordered_map<unsigned int, OpenBabel::vector3> coord_backup;\n\tfor (Size i=1; (mol = input->read()); i++)\n\t{\n\t\tif (no_written%5 == 0)\n\t\t{\n\t\t\tLog.level(20) << \"\\r\" << no_written << \" molecules\";\n\t\t\tLog.flush();\n\t\t}\n\t\t\n\t\tmol_name = mol->getName();\n\t\tif (mol_name==\"\")\n\t\t{\n\t\t\tmol_name = \"?\";\n\t\t}\n\t\t\n\t\t\/\/ Check if molecule fulfills minimal validity criteria\n\t\tif (!basicMoleculeCheck(mol))\n\t\t{\n\t\t\tno_ignored++;\n\t\t\t\n\t\t\tLog.level(20) << \"Error \" << mol_name << \" is skipped because of either containing no atoms, multiple fragments or undefined elements.\" << endl;\n\t\t\t\n\t\t\tdelete mol;\n\t\t\t\n\t\t\tcontinue;\n\t\t}\n\t\t\n\t\t\n\t\tif (keep3Dcoords || keep3DcoordsProtonate)\n\t\t{\n\t\t\tif (advancedMoleculeCheck(mol))\n\t\t\t{\n\t\t\t\trebuild_mol = false;\n\t\t\t\t\n\t\t\t\tif (keep3Dcoords)\n\t\t\t\t{\n\t\t\t\t\tif (hasHydrogensCheck(mol))\n\t\t\t\t\t{\n\t\t\t\t\t\tif (output->write(*mol)) \n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tno_written++;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse \n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tno_ignored++;\n\t\t\t\t\t\t}\n\t\t\t\t\t\t\n\t\t\t\t\t\tdelete mol;\n\t\t\t\t\t\t\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\tLog.level(20) << \"Molecule <\" << mol_name << \"> is newly protonated because of missing hydrogens (non-hydrogen atoms keep their 3D coordinates).\" << endl;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\trebuild_mol = true;\n\t\t\t\t\n\t\t\t\tLog.level(20) << \"Molecule <\" << mol_name << \"> is rebuild because of either missing 3D coordinates, unusual charges or unusual bond lengths.\" << endl;\n\t\t\t}\n\t\t}\n\t\t\n\t\t\n\t\t\/\/ Rebuild or re-protonate and minimze molecule using OpenBabel tools\n\t\t\n\t\t\/\/ Note: Openbabel::OpGen3D::Do() is NOT used directly here, because it re-assigns hydrogens for a static ph of 7.4, \n\t\t\/\/ i.e. the pH can not be specified. Furthermore, it does also not remove hydrogens before using OBBuilder, resulting in hydrogens sometimes having more than one bond!\n\t\tobmol = MolecularSimilarity::createOBMol(*mol);\n\t\t\n\t\tob_error = false;\n\t\ttry\n\t\t{\n\t\t\t\/\/ Remove all hydrogens before using OBBuilder, otherwise hydrogens end up having more than one bond! (Sigh!)\n\t\t\tobmol->DeleteHydrogens();\n\t\t\t\n\t\t\t\/\/ Backup original atom coordinates\n\t\t\tcoord_backup.clear();\n\t\t\tif (!rebuild_mol && keep3DcoordsProtonate)\n\t\t\t{\n\t\t\t\tfor(OpenBabel::OBAtomIterator a_it=obmol->BeginAtoms(); a_it!=obmol->EndAtoms(); ++a_it)\n\t\t\t\t{\n\t\t\t\t\tcoord_backup.insert(make_pair((*a_it)->GetIdx(), (*a_it)->GetVector()));\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\t\n\t\t\t\/\/ Create 3D coordinates for individual fragments using template library\n\t\t\tOpenBabel::OBBuilder builder;\n\t\t\tbuilder.Build(*obmol);\n\t\t\tobmol->SetDimension(3);\n\t\t\t\n\t\t\t\n\t\t\t\/\/ Set up a constraints object for OpenBabel minimization\n\t\t\t\/\/ It is used to set positional constraints on non-hydrogen atoms when only hydrogens should be minimized\n\t\t\tOpenBabel::OBFFConstraints constraints;\n\t\t\t\n\t\t\t\n\t\t\t\/\/ Reset original coordinates and set positional constraints on non-hydrogen atoms\n\t\t\tif (!rebuild_mol && keep3DcoordsProtonate)\n\t\t\t{\n\t\t\t\tfor(OpenBabel::OBAtomIterator a_it=obmol->BeginAtoms(); a_it!=obmol->EndAtoms(); ++a_it)\n\t\t\t\t{\n\t\t\t\t\t(*a_it)->SetVector(coord_backup[(*a_it)->GetIdx()]);\n\t\t\t\t\t\n\t\t\t\t\tconstraints.AddAtomConstraint((*a_it)->GetIdx());\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\t\n\t\t\t\/\/ Now add hydrogens\n\t\t\tobmol->AddHydrogens(false, true, pH);\n\t\t\t\n\t\t\t\n\t\t\t\/\/ Setup MMFF94 force-field\n\t\t\tsetup_ok = pFF->Setup(*obmol, constraints);\n\t\t\t\n\t\t\t\n\t\t\tif (setup_ok)\n\t\t\t{\n\t\t\t\t\/\/ Optimize bond-lengths and torsions\n\t\t\t\tpFF->SteepestDescent(70, 1.0e-4); \/\/ 250, 1e-04\n\t\t\t\t\n\t\t\t\t\/\/ Rotate fragments around rotatable bonds\n\t\t\t\tpFF->WeightedRotorSearch(10, 5); \/\/ 200, 25\n\t\t\t\t\n\t\t\t\t\/\/ Optimize bond-lengths and torsions again\n\t\t\t\tpFF->ConjugateGradients(70, 1.0e-4); \/\/ 250, 1e-06\n\t\t\t\tpFF->UpdateCoordinates(*obmol);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tLog.level(20) << \"[Warning:] Openbabel force-field setup failed for molecule \" << i << \". Will only use template-based approach without force-field optimization for this molecule!\" << endl;\n\t\t\t}\n\t\t}\n\t\tcatch (...)\n\t\t{\n\t\t\tLog.level(20) << \"Error while trying to generate 3D coordinates for molecule \" << i<< \" \";\n\t\t\tif (mol->getName() != \"\")\n\t\t\t{\n\t\t\t\tLog.level(20) << \"'\" << mol->getName() << \"'\";\n\t\t\t}\n\t\t\tLog.level(20) << \". Will write unmodified input coordinates to output-file.\" << endl;\n\t\t\t\n\t\t\tdelete obmol;\n\t\t\t\n\t\t\tob_error = true;\n\t\t\t\n\t\t\tif (output->write(*mol))\n\t\t\t{\n\t\t\t\tno_written++;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tno_ignored++;\n\t\t\t}\n\t\t}\n\t\t\n\t\tif (!ob_error)\n\t\t{\n\t\t\t\/\/ Fetch final 3D coordinates\n\t\t\tnew_mol = MolecularSimilarity::createMolecule(*obmol);\n\t\t\tfor (NamedPropertyIterator it=mol->beginNamedProperty(); it!=mol->endNamedProperty(); it++)\n\t\t\t{\n\t\t\t\tnew_mol->setProperty(*it);\n\t\t\t}\n\t\t\tnew_mol->setName(mol->getName());\n\t\t\t\n\t\t\tif (output->write(*new_mol)) \n\t\t\t{\n\t\t\t\tno_written++;\n\t\t\t}\n\t\t\telse \n\t\t\t{\n\t\t\t\tno_ignored++;\n\t\t\t}\n\t\t\t\n\t\t\tdelete mol;\n\t\t\tdelete obmol;\n\t\t\tdelete new_mol;\n\t\t}\n\t}\n\t\n\tLog.level(20) << \"\\r\";\n\tif (no_ignored > 0) \n\t{\n\t\tLog.level(20) << \"ignored \" << no_ignored << \" identical molecules!\" << endl;\n\t}\n\tLog.level(20) << \"wrote \" << no_written << \" molecules.\" << endl;\n\t\n\tinput->close();\n\toutput->close();\n\t\n\tdelete input;\n\tdelete output;\n\t\n\tif (parpars.has(\"rm\"))\n\t{\n\t\tFile::remove(parpars.get(\"i\"));\n\t}\n}\n\n<commit_msg>source\/APPLICATIONS\/TOOLS\/Ligand3DGenerator.C: Incorporated changes from Daniel to load OpenBabel's ForceField Plugin.<commit_after>\/\/ -*- Mode: C++; tab-width: 2; -*-\n\/\/ vi: set ts=2:\n\/\/\n\n#include <BALL\/KERNEL\/bond.h>\n#include <BALL\/KERNEL\/molecule.h>\n#include <BALL\/KERNEL\/PTE.h>\n#include <BALL\/KERNEL\/selector.h>\n#include <BALL\/FORMAT\/molFileFactory.h>\n#include <BALL\/FORMAT\/dockResultFile.h>\n#include <BALL\/FORMAT\/commandlineParser.h>\n#include <BALL\/STRUCTURE\/molecularSimilarity.h>\n\n#include <boost\/unordered_map.hpp>\n\n#include <openbabel\/mol.h>\n#include <openbabel\/builder.h>\n#include <openbabel\/forcefield.h>\n#include <openbabel\/plugin.h>\n#include <openbabel\/obconversion.h>\n#include \"version.h\"\n\n\nusing namespace BALL;\nusing namespace std;\n\n\n\/\/ Check whether the given molecule really contains only one molecule\nvoid checkBonds(const Atom* atom, set<const Atom*>& visited_atoms)\n{\n\tif (visited_atoms.find(atom) != visited_atoms.end())\n\t{\n\t\treturn;\n\t}\n\t\n\tvisited_atoms.insert(atom);\n\tfor (Atom::BondConstIterator b_it = atom->beginBond(); +b_it; b_it++)\n\t{\n\t\tcheckBonds(b_it->getPartner(*atom), visited_atoms);\n\t}\n}\n\n\n\/\/ Check if a molecule has atoms, is single connected component and has elements defined\nbool basicMoleculeCheck(Molecule* mol)\n{\n\t\/\/ Check if it molecule has no atoms\n\tif (mol->countAtoms() == 0)\n\t{\n\t\treturn false;\n\t}\n\t\n\t\/\/ Check if molecule is a contains a single fragment\n\tset<const Atom*> visited_atoms;\n\tcheckBonds(&*mol->beginAtom(), visited_atoms);\n\tif (visited_atoms.size() != mol->countAtoms())\n\t{\n\t\treturn false;\n\t}\n\t\n\t\/\/ Check if there are undefined elements\n\tfor (AtomConstIterator it=mol->beginAtom(); it!=mol->endAtom(); ++it)\n\t{\n\t\tif (it->getElement().getName() == BALL_ELEMENT_NAME_DEFAULT)\n\t\t{\n\t\t\treturn false;\n\t\t}\n\t}\n\t\n\treturn true;\n}\n\n\n\/\/ Basic check if a ligand contains a hydrogen and thus can be regarded as \"protonated\"\nbool hasHydrogensCheck(Molecule* mol)\n{\n\tfor (AtomConstIterator it = mol->beginAtom(); +it; it++)\n\t{\n\t\tif (it->getElement().getSymbol() == \"H\")\n\t\t{\n\t\t\treturn true;\n\t\t}\n\t}\n\t\n\treturn false;\n}\n\n\n\/\/ Check if a valid molecule is ready for docking\nbool advancedMoleculeCheck(Molecule* mol)\n{\n\tbool all_x_zero = true;\n\tbool all_y_zero = true;\n\tbool all_z_zero = true;\n\t\n\tfor (AtomConstIterator it = mol->beginAtom(); +it; it++)\n\t{\n\t\tif (fabs(it->getCharge()) > 5)\n\t\t{\n\t\t\treturn false;\n\t\t}\n\t\t\n\t\tfor (Atom::BondConstIterator b_it = it->beginBond(); +b_it; b_it++)\n\t\t{\n\t\t\tif (b_it->getLength() < 0.7 || b_it->getLength() > 2.5)\n\t\t\t{\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t\t\n\t\tconst TVector3<float>& pos = it->getPosition();\n\t\tif (all_x_zero)\n\t\t{\n\t\t\tif (fabs(pos[0]) > 0.001)\n\t\t\t{\n\t\t\t\tall_x_zero = false;\n\t\t\t}\n\t\t}\n\t\tif (all_y_zero)\n\t\t{\n\t\t\tif (fabs(pos[1]) > 0.001)\n\t\t\t{\n\t\t\t\tall_y_zero = false;\n\t\t\t}\n\t\t}\n\t\tif (all_z_zero)\n\t\t{\n\t\t\tif (fabs(pos[2]) > 0.001)\n\t\t\t{\n\t\t\t\tall_z_zero = false;\n\t\t\t}\n\t\t}\n\t}\n\t\n\tif (all_x_zero || all_y_zero || all_z_zero)\n\t{\n\t\treturn false;\n\t}\n\telse\n\t{\n\t\treturn true;\n\t}\n}\n\n\nint main(int argc, char* argv[])\n{\n\tCommandlineParser parpars(\"Ligand3DGenerator\", \"generate 3D coordinates for small molecules\", VERSION, String(__DATE__), \"Preparation\");\n\tparpars.registerParameter(\"i\", \"input file\", INFILE, true);\n\tparpars.registerParameter(\"o\", \"output file\", OUTFILE, true);\n\tparpars.registerParameter(\"ph\", \"pH-value for pH-dep. protonation\", DOUBLE, false, \"7.0\");\n\tparpars.registerParameter(\"ff\", \"Forcefield to use for optimization (any available OpenBabel plugin)\", STRING, false, \"MMFF94\");\n\tparpars.registerFlag(\"rm\", \"remove input file when finished\");\n\tparpars.registerFlag(\"k\", \"keep existing 3D coordinates (flag precedes '-kp')\");\n\tparpars.registerFlag(\"kp\", \"keep existing 3D coordinates but re-protonate compound in a pH dependent manner (flag is preceded by '-k')\");\n\tString man = String(\"This tool takes input molecules and generates a single 3D conformation which is ready for docking. The input has to be a chemical file\\n\\\ncontaining valid topologies and conistent bond order assignements. 2D coordinates in the input file are overwritten, 3D coordinates can be kept ('-k' or '-kp').\\n\\n\\\n '-k': 3D coordinates are tried to be kept. Molecules with non-zero coordinates in all three dimensions are passed through without modifications. \\n\\\n However, if a molecule is not ready for docking (i.e. unusual bond leghts, unusual charges), the molecule will be rebuild and new \\n\\\n 3D coordinates are assigned. If only hydrogens are missing, the coordinates of non-hydrogen atoms are kept but the molecule gets newly protonated.\\n\\\n '-kp': 3D coordinates are tried to be kept as for the '-k' flag but the molecule will be newly protonated.\\n\\n\\\nPlease note that the main purpose of this tool is to generate valid starting conformations for docking or other optimization procedures.\\n\\\nTherefore, the generated 3D coordinates for each fragment should be all right, but in extreme cases (i.e. very large and\/or complex molecules) \\n\\\ndifferent fragments might still overlap with each other.\\n\\n\\\nSupported formats are \") + MolFileFactory::getSupportedFormats() + String(\".\");\n\tparpars.setToolManual(man);\n\tparpars.setSupportedFormats(\"i\",MolFileFactory::getSupportedFormats());\n\tparpars.setSupportedFormats(\"o\",MolFileFactory::getSupportedFormats());\n\tparpars.setOutputFormatSource(\"o\",\"i\");\n\tparpars.parse(argc, argv);\n\t\n\t\/\/ Create a dummy OBConversion object, that loads the available plugins.\n\t\/\/ If you know another, more elegant way to teach OpenBabel to do so\n\t\/\/ be my guest\n\tOpenBabel::OBConversion();\n\n\tGenericMolFile* input = MolFileFactory::open(parpars.get(\"i\"), ios::in);\n\tGenericMolFile* output = MolFileFactory::open(parpars.get(\"o\"), ios::out, input);\n\tDockResultFile* drf_output = dynamic_cast<DockResultFile*>(output);\n\tif (drf_output)\n\t{\n\t\tdrf_output->setToolInfo(parpars.getStartCommand(), parpars.getStartTime());\n\t}\n\t\n\tdouble pH = 7.4;\n\tif (parpars.get(\"ph\") != CommandlineParser::NOT_FOUND)\n\t{\n\t\tpH = parpars.get(\"ph\").toDouble();\n\t}\n\t\n\tbool keep3Dcoords = false;\n\tif (parpars.has(\"k\"))\n\t{\n\t\tkeep3Dcoords = true;\n\t}\n\t\n\tbool keep3DcoordsProtonate = false;\n\tif (parpars.has(\"kp\"))\n\t{\n\t\tkeep3DcoordsProtonate = true;\n\t}\n\t\n\tstd::string ff = parpars.get(\"ff\");\n\tOpenBabel::OBPlugin* plugin = OpenBabel::OBPlugin::GetPlugin(\"forcefields\", ff.c_str());\n\n\tif(!plugin)\n\t{\n\t\tstd::vector<std::string> forcefields;\n\t\tOpenBabel::OBPlugin::ListAsVector(\"forcefields\", ff.c_str(), forcefields);\n\n\t\tcerr << \"[Error:] No OpenBabel plugin containing the specified force field could be found. \"\n\t\t \"Available forcefields are:\\n\";\n\n\t\tfor(std::vector<std::string>::iterator it = forcefields.begin(); it != forcefields.end(); ++it)\n\t\t{\n\t\t\tstd::cerr << \"\\t\" << *it << \"\\n\";\n\t\t}\n\n\t\tcerr << \"Please make sure that the plugin is installed and BABEL_LIBDIR is set accordingly.\"\n\t\t \"\\nYo can verify this by typing \\\"obabel -L forcefields\\\"\" << endl;\n\n\t\treturn 1;\n\t}\n\n\tOpenBabel::OBForceField* pFF = dynamic_cast<OpenBabel::OBForceField*>(plugin);\n\tif (!pFF)\n\t{\n\t\tcerr << \"[Error:] Could not convert the provided plugin to a OBForceField. This is most likely a problem with OpenBabel.\\n\"\n\t\t \"If you can rule this out, please report a bug on the BALL bugtracker.\" << std::endl;\n\t\treturn 1;\n\t}\n\t\n\tString mol_name;\n\tbool setup_ok;\n\tbool ob_error;\n\tbool rebuild_mol;\n\tint no_written = 0;\n\tint no_ignored = 0;\n\tMolecule *mol, *new_mol;\n\tOpenBabel::OBMol *obmol;\n\tboost::unordered_map<unsigned int, OpenBabel::vector3> coord_backup;\n\tfor (Size i=1; (mol = input->read()); i++)\n\t{\n\t\tif (no_written%5 == 0)\n\t\t{\n\t\t\tLog.level(20) << \"\\r\" << no_written << \" molecules\";\n\t\t\tLog.flush();\n\t\t}\n\t\t\n\t\tmol_name = mol->getName();\n\t\tif (mol_name==\"\")\n\t\t{\n\t\t\tmol_name = \"?\";\n\t\t}\n\t\t\n\t\t\/\/ Check if molecule fulfills minimal validity criteria\n\t\tif (!basicMoleculeCheck(mol))\n\t\t{\n\t\t\tno_ignored++;\n\t\t\t\n\t\t\tLog.level(20) << \"Error \" << mol_name << \" is skipped because of either containing no atoms, multiple fragments or undefined elements.\" << endl;\n\t\t\t\n\t\t\tdelete mol;\n\t\t\t\n\t\t\tcontinue;\n\t\t}\n\t\t\n\t\t\n\t\tif (keep3Dcoords || keep3DcoordsProtonate)\n\t\t{\n\t\t\tif (advancedMoleculeCheck(mol))\n\t\t\t{\n\t\t\t\trebuild_mol = false;\n\t\t\t\t\n\t\t\t\tif (keep3Dcoords)\n\t\t\t\t{\n\t\t\t\t\tif (hasHydrogensCheck(mol))\n\t\t\t\t\t{\n\t\t\t\t\t\tif (output->write(*mol)) \n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tno_written++;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse \n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tno_ignored++;\n\t\t\t\t\t\t}\n\t\t\t\t\t\t\n\t\t\t\t\t\tdelete mol;\n\t\t\t\t\t\t\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\tLog.level(20) << \"Molecule <\" << mol_name << \"> is newly protonated because of missing hydrogens (non-hydrogen atoms keep their 3D coordinates).\" << endl;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\trebuild_mol = true;\n\t\t\t\t\n\t\t\t\tLog.level(20) << \"Molecule <\" << mol_name << \"> is rebuild because of either missing 3D coordinates, unusual charges or unusual bond lengths.\" << endl;\n\t\t\t}\n\t\t}\n\t\t\n\t\t\n\t\t\/\/ Rebuild or re-protonate and minimze molecule using OpenBabel tools\n\t\t\n\t\t\/\/ Note: Openbabel::OpGen3D::Do() is NOT used directly here, because it re-assigns hydrogens for a static ph of 7.4, \n\t\t\/\/ i.e. the pH can not be specified. Furthermore, it does also not remove hydrogens before using OBBuilder, resulting in hydrogens sometimes having more than one bond!\n\t\tobmol = MolecularSimilarity::createOBMol(*mol);\n\t\t\n\t\tob_error = false;\n\t\ttry\n\t\t{\n\t\t\t\/\/ Remove all hydrogens before using OBBuilder, otherwise hydrogens end up having more than one bond! (Sigh!)\n\t\t\tobmol->DeleteHydrogens();\n\t\t\t\n\t\t\t\/\/ Backup original atom coordinates\n\t\t\tcoord_backup.clear();\n\t\t\tif (!rebuild_mol && keep3DcoordsProtonate)\n\t\t\t{\n\t\t\t\tfor(OpenBabel::OBAtomIterator a_it=obmol->BeginAtoms(); a_it!=obmol->EndAtoms(); ++a_it)\n\t\t\t\t{\n\t\t\t\t\tcoord_backup.insert(make_pair((*a_it)->GetIdx(), (*a_it)->GetVector()));\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\t\n\t\t\t\/\/ Create 3D coordinates for individual fragments using template library\n\t\t\tOpenBabel::OBBuilder builder;\n\t\t\tbuilder.Build(*obmol);\n\t\t\tobmol->SetDimension(3);\n\t\t\t\n\t\t\t\n\t\t\t\/\/ Set up a constraints object for OpenBabel minimization\n\t\t\t\/\/ It is used to set positional constraints on non-hydrogen atoms when only hydrogens should be minimized\n\t\t\tOpenBabel::OBFFConstraints constraints;\n\t\t\t\n\t\t\t\n\t\t\t\/\/ Reset original coordinates and set positional constraints on non-hydrogen atoms\n\t\t\tif (!rebuild_mol && keep3DcoordsProtonate)\n\t\t\t{\n\t\t\t\tfor(OpenBabel::OBAtomIterator a_it=obmol->BeginAtoms(); a_it!=obmol->EndAtoms(); ++a_it)\n\t\t\t\t{\n\t\t\t\t\t(*a_it)->SetVector(coord_backup[(*a_it)->GetIdx()]);\n\t\t\t\t\t\n\t\t\t\t\tconstraints.AddAtomConstraint((*a_it)->GetIdx());\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\t\n\t\t\t\/\/ Now add hydrogens\n\t\t\tobmol->AddHydrogens(false, true, pH);\n\t\t\t\n\t\t\t\n\t\t\t\/\/ Setup MMFF94 force-field\n\t\t\tsetup_ok = pFF->Setup(*obmol, constraints);\n\t\t\t\n\t\t\t\n\t\t\tif (setup_ok)\n\t\t\t{\n\t\t\t\t\/\/ Optimize bond-lengths and torsions\n\t\t\t\tpFF->SteepestDescent(70, 1.0e-4); \/\/ 250, 1e-04\n\t\t\t\t\n\t\t\t\t\/\/ Rotate fragments around rotatable bonds\n\t\t\t\tpFF->WeightedRotorSearch(10, 5); \/\/ 200, 25\n\t\t\t\t\n\t\t\t\t\/\/ Optimize bond-lengths and torsions again\n\t\t\t\tpFF->ConjugateGradients(70, 1.0e-4); \/\/ 250, 1e-06\n\t\t\t\tpFF->UpdateCoordinates(*obmol);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tLog.level(20) << \"[Warning:] Openbabel force-field setup failed for molecule \" << i << \". Will only use template-based approach without force-field optimization for this molecule!\" << endl;\n\t\t\t}\n\t\t}\n\t\tcatch (...)\n\t\t{\n\t\t\tLog.level(20) << \"Error while trying to generate 3D coordinates for molecule \" << i<< \" \";\n\t\t\tif (mol->getName() != \"\")\n\t\t\t{\n\t\t\t\tLog.level(20) << \"'\" << mol->getName() << \"'\";\n\t\t\t}\n\t\t\tLog.level(20) << \". Will write unmodified input coordinates to output-file.\" << endl;\n\t\t\t\n\t\t\tdelete obmol;\n\t\t\t\n\t\t\tob_error = true;\n\t\t\t\n\t\t\tif (output->write(*mol))\n\t\t\t{\n\t\t\t\tno_written++;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tno_ignored++;\n\t\t\t}\n\t\t}\n\t\t\n\t\tif (!ob_error)\n\t\t{\n\t\t\t\/\/ Fetch final 3D coordinates\n\t\t\tnew_mol = MolecularSimilarity::createMolecule(*obmol);\n\t\t\tfor (NamedPropertyIterator it=mol->beginNamedProperty(); it!=mol->endNamedProperty(); it++)\n\t\t\t{\n\t\t\t\tnew_mol->setProperty(*it);\n\t\t\t}\n\t\t\tnew_mol->setName(mol->getName());\n\t\t\t\n\t\t\tif (output->write(*new_mol)) \n\t\t\t{\n\t\t\t\tno_written++;\n\t\t\t}\n\t\t\telse \n\t\t\t{\n\t\t\t\tno_ignored++;\n\t\t\t}\n\t\t\t\n\t\t\tdelete mol;\n\t\t\tdelete obmol;\n\t\t\tdelete new_mol;\n\t\t}\n\t}\n\t\n\tLog.level(20) << \"\\r\";\n\tif (no_ignored > 0) \n\t{\n\t\tLog.level(20) << \"ignored \" << no_ignored << \" identical molecules!\" << endl;\n\t}\n\tLog.level(20) << \"wrote \" << no_written << \" molecules.\" << endl;\n\t\n\tinput->close();\n\toutput->close();\n\t\n\tdelete input;\n\tdelete output;\n\t\n\tif (parpars.has(\"rm\"))\n\t{\n\t\tFile::remove(parpars.get(\"i\"));\n\t}\n}\n\n<|endoftext|>"} {"text":"<commit_before>\n#include <cppexpose\/reflection\/Object.h>\n\n#include <cassert>\n#include <typeinfo>\n\n#include <unordered_set>\n\n#include <cppassist\/string\/manipulation.h>\n\n#include <cppexpose\/json\/JSON.h>\n\n\nnamespace\n{\n const char g_separator = '.';\n const std::string g_separatorString = \".\";\n const std::string g_parent = \"parent\";\n}\n\n\nnamespace cppexpose\n{\n\n\nObject::Object()\n: Object(\"\")\n{\n}\n\nObject::Object(const std::string & name)\n: m_className(\"Object\")\n{\n initProperty(name, nullptr);\n}\n\nObject::~Object()\n{\n clear();\n}\n\nconst std::string & Object::className() const\n{\n return m_className;\n}\n\nvoid Object::setClassName(const std::string & className)\n{\n m_className = className;\n}\n\nvoid Object::clear()\n{\n \/\/ Remove properties\n \/\/ removeProperty() modifies m_properties, so don't use iterators here!\n while (!m_properties.empty())\n {\n removeProperty(m_properties.back());\n }\n}\n\nconst std::unordered_map<std::string, AbstractProperty *> & Object::properties() const\n{\n return m_propertiesMap;\n}\n\nbool Object::propertyExists(const std::string & name) const\n{\n return m_propertiesMap.find(name) != m_propertiesMap.end();\n}\n\nAbstractProperty * Object::property(size_t index)\n{\n if (index < m_properties.size()) {\n return m_properties[index];\n }\n\n return nullptr;\n}\n\nconst AbstractProperty * Object::property(size_t index) const\n{\n if (index < m_properties.size()) {\n return m_properties[index];\n }\n\n return nullptr;\n}\n\nAbstractProperty * Object::property(const std::string & path)\n{\n std::vector<std::string> splittedPath = cppassist::string::split(path, g_separator);\n return const_cast<AbstractProperty *>(findProperty(splittedPath));\n}\n\nconst AbstractProperty * Object::property(const std::string & path) const\n{\n std::vector<std::string> splittedPath = cppassist::string::split(path, g_separator);\n return findProperty(splittedPath);\n}\n\nbool Object::addProperty(AbstractProperty * property)\n{\n \/\/ Reject properties that have no name, or whose name already exists,\n \/\/ or that already have a parent object.\n if (!property || this->propertyExists(property->name()) || property->parent() != nullptr)\n {\n return false;\n }\n\n \/\/ Set parent\n property->setParent(this);\n\n \/\/ Invoke callback\n auto newIndex = m_properties.size();\n beforeAdd(newIndex, property);\n\n \/\/ Add property\n m_properties.push_back(property);\n m_propertiesMap.insert(std::make_pair(property->name(), property));\n\n \/\/ Invoke callback\n afterAdd(newIndex, property);\n\n \/\/ Success\n return true;\n}\n\n\nbool Object::addProperty(std::unique_ptr<AbstractProperty> && property)\n{\n const auto success = addProperty(property.get());\n if (success)\n {\n m_managedProperties.push_back(std::move(property));\n }\n\n return success;\n}\n\n\nbool Object::removeProperty(AbstractProperty * property)\n{\n \/\/ Reject properties that are not part of the object\n if (!property || property->parent() != this)\n {\n return false;\n }\n\n \/\/ Find property in object\n auto it = std::find(m_properties.begin(), m_properties.end(), property);\n if (it == m_properties.end())\n {\n return false;\n }\n\n \/\/ Get property index\n size_t index = std::distance(m_properties.begin(), it);\n\n \/\/ Invoke callback\n beforeRemove(index, property);\n\n \/\/ Remove property from object\n m_properties.erase(it);\n m_propertiesMap.erase(property->name());\n\n \/\/ Reset property parent\n property->setParent(nullptr);\n\n \/\/ Invoke callback\n afterRemove(index, property);\n\n \/\/ Remove from managed list (deletes the property)\n auto it2 = std::find_if(m_managedProperties.begin(), m_managedProperties.end(), [property](const std::unique_ptr<AbstractProperty> & managedProperty) { return managedProperty.get() == property; });\n if (it2 != m_managedProperties.end())\n {\n m_managedProperties.erase(it2);\n }\n\n \/\/ Success\n return true;\n}\n\nconst std::vector<Method> & Object::functions() const\n{\n return m_functions;\n}\n\nbool Object::isObject() const\n{\n return true;\n}\n\nstd::unique_ptr<AbstractTyped> Object::clone() const\n{\n \/\/ [TODO]\n return cppassist::make_unique<Object>(name());\n}\n\nconst std::type_info & Object::type() const\n{\n return typeid(Object);\n}\n\nstd::string Object::typeName() const\n{\n return \"Object\";\n}\n\nbool Object::isReadOnly() const\n{\n return false;\n}\n\nbool Object::isComposite() const\n{\n return true;\n}\n\nsize_t Object::numSubValues() const\n{\n return m_properties.size();\n}\n\nAbstractTyped * Object::subValue(size_t index)\n{\n if (index < m_properties.size()) {\n return m_properties[index];\n }\n\n return nullptr;\n}\n\nbool Object::isEnum() const\n{\n return false;\n}\n\nbool Object::isArray() const\n{\n return false;\n}\n\nbool Object::isVariant() const\n{\n return false;\n}\n\nbool Object::isString() const\n{\n return false;\n}\n\nbool Object::isBool() const\n{\n return false;\n}\n\nbool Object::isNumber() const\n{\n return false;\n}\n\nbool Object::isIntegral() const\n{\n return false;\n}\n\nbool Object::isSignedIntegral() const\n{\n return false;\n}\n\nbool Object::isUnsignedIntegral() const\n{\n return false;\n}\n\nbool Object::isFloatingPoint() const\n{\n return false;\n}\n\nVariant Object::toVariant() const\n{\n \/\/ Create variant map from all properties in the object\n Variant map = Variant::map();\n for (const auto & it : m_propertiesMap) {\n \/\/ Get name and property\n const std::string & name = it.first;\n AbstractProperty * prop = it.second;\n\n \/\/ Add to variant map\n (*map.asMap())[name] = prop->toVariant();\n }\n\n \/\/ Return variant representation\n return map;\n}\n\nbool Object::fromVariant(const Variant & value)\n{\n \/\/ Check if variant is a map\n if (!value.isVariantMap()) {\n return false;\n }\n\n \/\/ Get all values from variant map\n for (const auto & it : *value.asMap()) {\n \/\/ Get name and value\n const std::string & name = it.first;\n const Variant & var = it.second;\n\n \/\/ If this names an existing property, set its value\n AbstractProperty * prop = this->property(name);\n if (prop) {\n prop->fromVariant(var);\n }\n }\n\n \/\/ Done\n return true;\n}\n\nstd::string Object::toString() const\n{\n \/\/ Convert object into JSON\n return JSON::stringify(this->toVariant());\n}\n\nbool Object::fromString(const std::string & str)\n{\n \/\/ Convert from JSON\n Variant values;\n if (JSON::parse(values, str)) {\n return fromVariant(values);\n }\n\n \/\/ Error\n return false;\n}\n\nbool Object::toBool() const\n{\n return false;\n}\n\nbool Object::fromBool(bool)\n{\n return false;\n}\n\nlong long Object::toLongLong() const\n{\n return 0ll;\n}\n\nbool Object::fromLongLong(long long)\n{\n return false;\n}\n\nunsigned long long Object::toULongLong() const\n{\n return 0ull;\n}\n\nbool Object::fromULongLong(unsigned long long)\n{\n return false;\n}\n\ndouble Object::toDouble() const\n{\n return 0.0;\n}\n\nbool Object::fromDouble(double)\n{\n return false;\n}\n\nstd::string Object::relativePathTo(const Object * const other) const\n{\n \/\/ Return \".\" if the objects are the same\n if (this == other) {\n return g_separatorString;\n }\n\n \/\/ Find all ancestors of \"this\"\n std::unordered_set<const Object*> ancestors;\n\n const Object * curObject = this;\n while (curObject)\n {\n ancestors.insert(curObject);\n curObject = curObject->parent();\n }\n\n \/\/ Find the common parent from \"other\"\n std::vector<std::string> otherPath;\n const Object * commonParent = nullptr;\n\n curObject = other;\n while (curObject)\n {\n if (ancestors.count(curObject))\n {\n commonParent = curObject;\n break;\n }\n\n otherPath.push_back(curObject->name());\n curObject = curObject->parent();\n }\n\n \/\/ Abort if no common parent has been found\n if (!commonParent) {\n return \"\";\n }\n\n \/\/ Count number of steps from this to the common parent\n curObject = this;\n size_t numParents = 0;\n while (curObject != commonParent)\n {\n numParents++;\n curObject = curObject->parent();\n }\n\n \/\/ Compose string\n std::string relativePath = \"\";\n\n for (size_t i = 0; i < numParents; i++)\n {\n relativePath += (i == 0) ? \"parent\" : \".parent\";\n }\n\n for (size_t i = 0; i < otherPath.size(); i++)\n {\n relativePath += \".\" + otherPath[otherPath.size() - 1 - i];\n }\n\n return relativePath;\n}\n\nconst AbstractProperty * Object::findProperty(const std::vector<std::string> & path) const\n{\n \/\/ Find property\n const AbstractProperty * property = this;\n\n auto current = path.begin();\n const auto end = path.end();\n\n while (current != end)\n {\n \/\/ Get property name (first part of the path)\n const std::string & name = *current;\n\n if (name == g_parent)\n {\n \/\/ Parent property\n property = property->m_parent;\n }\n else\n {\n \/\/ Sub-property\n auto object = static_cast<const Object *>(property);\n const auto it = object->m_propertiesMap.find(name);\n\n if (it != object->m_propertiesMap.end())\n {\n property = it->second;\n }\n else\n {\n property = nullptr;\n }\n }\n\n \/\/ Check if property exists\n if (!property) {\n return nullptr;\n }\n\n \/\/ Compute next path segment\n ++current;\n\n \/\/ If there are no more sub-paths, return the found property\n if (current == end) {\n return property;\n }\n\n \/\/ Otherwise, it is an element in the middle of the path, so ensure it is an object\n if (!property->isObject()) {\n return nullptr;\n }\n }\n\n return nullptr;\n}\n\n\n} \/\/ namespace cppexpose\n<commit_msg>Explicit string::split parameters<commit_after>\n#include <cppexpose\/reflection\/Object.h>\n\n#include <cassert>\n#include <typeinfo>\n\n#include <unordered_set>\n\n#include <cppassist\/string\/manipulation.h>\n\n#include <cppexpose\/json\/JSON.h>\n\n\nnamespace\n{\n const char g_separator = '.';\n const std::string g_separatorString = \".\";\n const std::string g_parent = \"parent\";\n}\n\n\nnamespace cppexpose\n{\n\n\nObject::Object()\n: Object(\"\")\n{\n}\n\nObject::Object(const std::string & name)\n: m_className(\"Object\")\n{\n initProperty(name, nullptr);\n}\n\nObject::~Object()\n{\n clear();\n}\n\nconst std::string & Object::className() const\n{\n return m_className;\n}\n\nvoid Object::setClassName(const std::string & className)\n{\n m_className = className;\n}\n\nvoid Object::clear()\n{\n \/\/ Remove properties\n \/\/ removeProperty() modifies m_properties, so don't use iterators here!\n while (!m_properties.empty())\n {\n removeProperty(m_properties.back());\n }\n}\n\nconst std::unordered_map<std::string, AbstractProperty *> & Object::properties() const\n{\n return m_propertiesMap;\n}\n\nbool Object::propertyExists(const std::string & name) const\n{\n return m_propertiesMap.find(name) != m_propertiesMap.end();\n}\n\nAbstractProperty * Object::property(size_t index)\n{\n if (index < m_properties.size()) {\n return m_properties[index];\n }\n\n return nullptr;\n}\n\nconst AbstractProperty * Object::property(size_t index) const\n{\n if (index < m_properties.size()) {\n return m_properties[index];\n }\n\n return nullptr;\n}\n\nAbstractProperty * Object::property(const std::string & path)\n{\n std::vector<std::string> splittedPath = cppassist::string::split(path, g_separator, true);\n return const_cast<AbstractProperty *>(findProperty(splittedPath));\n}\n\nconst AbstractProperty * Object::property(const std::string & path) const\n{\n std::vector<std::string> splittedPath = cppassist::string::split(path, g_separator, true);\n return findProperty(splittedPath);\n}\n\nbool Object::addProperty(AbstractProperty * property)\n{\n \/\/ Reject properties that have no name, or whose name already exists,\n \/\/ or that already have a parent object.\n if (!property || this->propertyExists(property->name()) || property->parent() != nullptr)\n {\n return false;\n }\n\n \/\/ Set parent\n property->setParent(this);\n\n \/\/ Invoke callback\n auto newIndex = m_properties.size();\n beforeAdd(newIndex, property);\n\n \/\/ Add property\n m_properties.push_back(property);\n m_propertiesMap.insert(std::make_pair(property->name(), property));\n\n \/\/ Invoke callback\n afterAdd(newIndex, property);\n\n \/\/ Success\n return true;\n}\n\n\nbool Object::addProperty(std::unique_ptr<AbstractProperty> && property)\n{\n const auto success = addProperty(property.get());\n if (success)\n {\n m_managedProperties.push_back(std::move(property));\n }\n\n return success;\n}\n\n\nbool Object::removeProperty(AbstractProperty * property)\n{\n \/\/ Reject properties that are not part of the object\n if (!property || property->parent() != this)\n {\n return false;\n }\n\n \/\/ Find property in object\n auto it = std::find(m_properties.begin(), m_properties.end(), property);\n if (it == m_properties.end())\n {\n return false;\n }\n\n \/\/ Get property index\n size_t index = std::distance(m_properties.begin(), it);\n\n \/\/ Invoke callback\n beforeRemove(index, property);\n\n \/\/ Remove property from object\n m_properties.erase(it);\n m_propertiesMap.erase(property->name());\n\n \/\/ Reset property parent\n property->setParent(nullptr);\n\n \/\/ Invoke callback\n afterRemove(index, property);\n\n \/\/ Remove from managed list (deletes the property)\n auto it2 = std::find_if(m_managedProperties.begin(), m_managedProperties.end(), [property](const std::unique_ptr<AbstractProperty> & managedProperty) { return managedProperty.get() == property; });\n if (it2 != m_managedProperties.end())\n {\n m_managedProperties.erase(it2);\n }\n\n \/\/ Success\n return true;\n}\n\nconst std::vector<Method> & Object::functions() const\n{\n return m_functions;\n}\n\nbool Object::isObject() const\n{\n return true;\n}\n\nstd::unique_ptr<AbstractTyped> Object::clone() const\n{\n \/\/ [TODO]\n return cppassist::make_unique<Object>(name());\n}\n\nconst std::type_info & Object::type() const\n{\n return typeid(Object);\n}\n\nstd::string Object::typeName() const\n{\n return \"Object\";\n}\n\nbool Object::isReadOnly() const\n{\n return false;\n}\n\nbool Object::isComposite() const\n{\n return true;\n}\n\nsize_t Object::numSubValues() const\n{\n return m_properties.size();\n}\n\nAbstractTyped * Object::subValue(size_t index)\n{\n if (index < m_properties.size()) {\n return m_properties[index];\n }\n\n return nullptr;\n}\n\nbool Object::isEnum() const\n{\n return false;\n}\n\nbool Object::isArray() const\n{\n return false;\n}\n\nbool Object::isVariant() const\n{\n return false;\n}\n\nbool Object::isString() const\n{\n return false;\n}\n\nbool Object::isBool() const\n{\n return false;\n}\n\nbool Object::isNumber() const\n{\n return false;\n}\n\nbool Object::isIntegral() const\n{\n return false;\n}\n\nbool Object::isSignedIntegral() const\n{\n return false;\n}\n\nbool Object::isUnsignedIntegral() const\n{\n return false;\n}\n\nbool Object::isFloatingPoint() const\n{\n return false;\n}\n\nVariant Object::toVariant() const\n{\n \/\/ Create variant map from all properties in the object\n Variant map = Variant::map();\n for (const auto & it : m_propertiesMap) {\n \/\/ Get name and property\n const std::string & name = it.first;\n AbstractProperty * prop = it.second;\n\n \/\/ Add to variant map\n (*map.asMap())[name] = prop->toVariant();\n }\n\n \/\/ Return variant representation\n return map;\n}\n\nbool Object::fromVariant(const Variant & value)\n{\n \/\/ Check if variant is a map\n if (!value.isVariantMap()) {\n return false;\n }\n\n \/\/ Get all values from variant map\n for (const auto & it : *value.asMap()) {\n \/\/ Get name and value\n const std::string & name = it.first;\n const Variant & var = it.second;\n\n \/\/ If this names an existing property, set its value\n AbstractProperty * prop = this->property(name);\n if (prop) {\n prop->fromVariant(var);\n }\n }\n\n \/\/ Done\n return true;\n}\n\nstd::string Object::toString() const\n{\n \/\/ Convert object into JSON\n return JSON::stringify(this->toVariant());\n}\n\nbool Object::fromString(const std::string & str)\n{\n \/\/ Convert from JSON\n Variant values;\n if (JSON::parse(values, str)) {\n return fromVariant(values);\n }\n\n \/\/ Error\n return false;\n}\n\nbool Object::toBool() const\n{\n return false;\n}\n\nbool Object::fromBool(bool)\n{\n return false;\n}\n\nlong long Object::toLongLong() const\n{\n return 0ll;\n}\n\nbool Object::fromLongLong(long long)\n{\n return false;\n}\n\nunsigned long long Object::toULongLong() const\n{\n return 0ull;\n}\n\nbool Object::fromULongLong(unsigned long long)\n{\n return false;\n}\n\ndouble Object::toDouble() const\n{\n return 0.0;\n}\n\nbool Object::fromDouble(double)\n{\n return false;\n}\n\nstd::string Object::relativePathTo(const Object * const other) const\n{\n \/\/ Return \".\" if the objects are the same\n if (this == other) {\n return g_separatorString;\n }\n\n \/\/ Find all ancestors of \"this\"\n std::unordered_set<const Object*> ancestors;\n\n const Object * curObject = this;\n while (curObject)\n {\n ancestors.insert(curObject);\n curObject = curObject->parent();\n }\n\n \/\/ Find the common parent from \"other\"\n std::vector<std::string> otherPath;\n const Object * commonParent = nullptr;\n\n curObject = other;\n while (curObject)\n {\n if (ancestors.count(curObject))\n {\n commonParent = curObject;\n break;\n }\n\n otherPath.push_back(curObject->name());\n curObject = curObject->parent();\n }\n\n \/\/ Abort if no common parent has been found\n if (!commonParent) {\n return \"\";\n }\n\n \/\/ Count number of steps from this to the common parent\n curObject = this;\n size_t numParents = 0;\n while (curObject != commonParent)\n {\n numParents++;\n curObject = curObject->parent();\n }\n\n \/\/ Compose string\n std::string relativePath = \"\";\n\n for (size_t i = 0; i < numParents; i++)\n {\n relativePath += (i == 0) ? \"parent\" : \".parent\";\n }\n\n for (size_t i = 0; i < otherPath.size(); i++)\n {\n relativePath += \".\" + otherPath[otherPath.size() - 1 - i];\n }\n\n return relativePath;\n}\n\nconst AbstractProperty * Object::findProperty(const std::vector<std::string> & path) const\n{\n \/\/ Find property\n const AbstractProperty * property = this;\n\n auto current = path.begin();\n const auto end = path.end();\n\n while (current != end)\n {\n \/\/ Get property name (first part of the path)\n const std::string & name = *current;\n\n if (name == g_parent)\n {\n \/\/ Parent property\n property = property->m_parent;\n }\n else\n {\n \/\/ Sub-property\n auto object = static_cast<const Object *>(property);\n const auto it = object->m_propertiesMap.find(name);\n\n if (it != object->m_propertiesMap.end())\n {\n property = it->second;\n }\n else\n {\n property = nullptr;\n }\n }\n\n \/\/ Check if property exists\n if (!property) {\n return nullptr;\n }\n\n \/\/ Compute next path segment\n ++current;\n\n \/\/ If there are no more sub-paths, return the found property\n if (current == end) {\n return property;\n }\n\n \/\/ Otherwise, it is an element in the middle of the path, so ensure it is an object\n if (!property->isObject()) {\n return nullptr;\n }\n }\n\n return nullptr;\n}\n\n\n} \/\/ namespace cppexpose\n<|endoftext|>"} {"text":"<commit_before>\/****************************************************************************\/\n\/* Copyright 2005-2006, Francis Russell *\/\n\/* *\/\n\/* Licensed under the Apache License, Version 2.0 (the License); *\/\n\/* you may not use this file except in compliance with the License. *\/\n\/* You may obtain a copy of the License at *\/\n\/* *\/\n\/* http:\/\/www.apache.org\/licenses\/LICENSE-2.0 *\/\n\/* *\/\n\/* Unless required by applicable law or agreed to in writing, software *\/\n\/* distributed under the License is distributed on an AS IS BASIS, *\/\n\/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. *\/\n\/* See the License for the specific language governing permissions and *\/\n\/* limitations under the License. *\/\n\/* *\/\n\/****************************************************************************\/\n\n#ifndef DESOLIN_PROFILING_HASHING_VISITOR_HPP\n#define DESOLIN_PROFILING_HASHING_VISITOR_HPP\n\n#include \"Desolin_profiling_fwd.hpp\"\n#include <cstddef>\n#include <typeinfo>\n#include <string>\n#include <cstring>\n#include <map>\n#include <vector>\n#include <cassert>\n#include <boost\/functional\/hash.hpp>\n\nnamespace desolin\n{\n\nnamespace detail\n{\n\ntemplate<typename T_element>\nclass PHashingVisitor : public PExpressionNodeVisitor<T_element>\n{\nprivate:\n const std::map<const PExpressionNode<T_element>*, int> nodeNumberings;\n std::size_t hash;\n \n template<typename exprType>\n inline std::size_t hashExprNode(const PExprNode<exprType, T_element>& node) const\n {\n const char* nodeTypeString = typeid(node).name();\n return boost::hash_range(nodeTypeString, nodeTypeString+strlen(nodeTypeString));\n }\n\n template<typename resultType, typename exprType>\n std::size_t hashUnOp(const PUnOp<resultType, exprType, T_element>& unop) const\n {\n std::size_t seed = hashExprNode(unop);\n const typename std::map<const PExpressionNode<T_element>*, int>::const_iterator operand = nodeNumberings.find(&unop.getOperand());\n assert(operand != nodeNumberings.end());\n boost::hash_combine(seed, operand->second);\n return seed;\n }\n\n template<typename resultType, typename leftType, typename rightType>\n std::size_t hashBinOp(const PBinOp<resultType, leftType, rightType, T_element>& binop) const\n {\n std::size_t seed = hashExprNode(binop);\n const typename std::map<const PExpressionNode<T_element>*, int>::const_iterator left = nodeNumberings.find(&binop.getLeft());\n const typename std::map<const PExpressionNode<T_element>*, int>::const_iterator right = nodeNumberings.find(&binop.getRight());\n assert(left != nodeNumberings.end());\n assert(right != nodeNumberings.end());\n boost::hash_combine(seed, left->second);\n boost::hash_combine(seed, right->second);\n return seed;\n }\n\n template<typename exprType>\n std::size_t hashElementSet(const PElementSet<exprType, T_element>& node) const\n {\n std::size_t seed = hashUnOp(node);\n const std::vector<const PExprNode<scalar, T_element>*> assignments(node.getAssignments());\n typedef typename std::vector<const PExprNode<scalar, T_element>*>::const_iterator ConstIterator;\n \n for(ConstIterator assignment = assignments.begin(); assignment!=assignments.end(); ++assignment)\n {\n const typename std::map<const PExpressionNode<T_element>*, int>::const_iterator numbering = nodeNumberings.find(*assignment);\n assert(numbering != nodeNumberings.end());\n boost::hash_combine(seed, numbering->second);\n }\n return seed;\n }\n\n template<typename exprType>\n std::size_t hashPairwise(const PPairwise<exprType, T_element>& node) const\n {\n std::size_t seed = hashBinOp(node);\n boost::hash_combine(seed, node.getOperation());\n return seed;\n }\n\n template<typename exprType>\n std::size_t hashScalarPiecewise(const PScalarPiecewise<exprType, T_element>& node) const\n {\n std::size_t seed = hashBinOp(node);\n boost::hash_combine(seed, node.getOperation());\n return seed;\n }\n \npublic:\n\n PHashingVisitor(const std::map<const PExpressionNode<T_element>*, int>& numberings) : nodeNumberings(numberings)\n {\n }\n \n inline std::size_t getHash() const\n {\n return hash;\n }\n \n virtual void visit(PElementGet<vector, T_element>& e)\n {\n boost::hash_combine(hash, hashUnOp(e));\n }\n \n virtual void visit(PElementGet<matrix, T_element>& e)\n {\n boost::hash_combine(hash, hashUnOp(e));\n }\n\n virtual void visit(PElementSet<vector, T_element>& e)\n {\n boost::hash_combine(hash, hashElementSet(e));\n }\n \n virtual void visit(PElementSet<matrix, T_element>& e)\n {\n boost::hash_combine(hash, hashElementSet(e));\n }\n\n virtual void visit(PLiteral<scalar, T_element>& e)\n {\n boost::hash_combine(hash, hashExprNode(e));\n }\n \n virtual void visit(PLiteral<vector, T_element>& e)\n {\n boost::hash_combine(hash, hashExprNode(e));\n }\n \n virtual void visit(PLiteral<matrix, T_element>& e)\n {\n boost::hash_combine(hash, hashExprNode(e));\n }\n\n virtual void visit(PMatrixMult<T_element>& e)\n {\n boost::hash_combine(hash, hashBinOp(e));\n }\n \n virtual void visit(PMatrixVectorMult<T_element>& e)\n {\n boost::hash_combine(hash, hashBinOp(e));\n }\n \n virtual void visit(PTransposeMatrixVectorMult<T_element>& e)\n {\n boost::hash_combine(hash, hashBinOp(e));\n }\n \n virtual void visit(PVectorDot<T_element>& e)\n {\n boost::hash_combine(hash, hashBinOp(e));\n }\n \n virtual void visit(PVectorCross<T_element>& e)\n {\n boost::hash_combine(hash, hashBinOp(e));\n }\n \n virtual void visit(PVectorTwoNorm<T_element>& e)\n {\n boost::hash_combine(hash, hashUnOp(e));\n }\n \n virtual void visit(PMatrixTranspose<T_element>& e)\n {\n boost::hash_combine(hash, hashUnOp(e));\n }\n\n virtual void visit(PPairwise<scalar, T_element>& e)\n {\n boost::hash_combine(hash, hashBinOp(e));\n }\n \n virtual void visit(PPairwise<vector, T_element>& e)\n {\n boost::hash_combine(hash, hashBinOp(e));\n }\n \n virtual void visit(PPairwise<matrix, T_element>& e) \n {\n boost::hash_combine(hash, hashBinOp(e));\n }\n\n virtual void visit(PScalarPiecewise<scalar, T_element>& e)\n {\n boost::hash_combine(hash, hashBinOp(e));\n }\n \n virtual void visit(PScalarPiecewise<vector, T_element>& e) \n {\n boost::hash_combine(hash, hashBinOp(e));\n }\n \n virtual void visit(PScalarPiecewise<matrix, T_element>& e)\n {\n boost::hash_combine(hash, hashBinOp(e));\n }\n\n virtual void visit(PNegate<scalar, T_element>& e)\n {\n boost::hash_combine(hash, hashUnOp(e));\n }\n \n virtual void visit(PNegate<vector, T_element>& e)\n {\n boost::hash_combine(hash, hashUnOp(e));\n }\n \n virtual void visit(PNegate<matrix, T_element>& e)\n {\n boost::hash_combine(hash, hashUnOp(e));\n }\n\n virtual void visit(PAbsolute<T_element>& e)\n {\n boost::hash_combine(hash, hashUnOp(e));\n }\n \n virtual void visit(PSquareRoot<T_element>& e)\n {\n boost::hash_combine(hash, hashUnOp(e));\n }\n};\n\n}\n\n}\n\n#endif\n<commit_msg>Fix profiling hashing visitor.<commit_after>\/****************************************************************************\/\n\/* Copyright 2005-2006, Francis Russell *\/\n\/* *\/\n\/* Licensed under the Apache License, Version 2.0 (the License); *\/\n\/* you may not use this file except in compliance with the License. *\/\n\/* You may obtain a copy of the License at *\/\n\/* *\/\n\/* http:\/\/www.apache.org\/licenses\/LICENSE-2.0 *\/\n\/* *\/\n\/* Unless required by applicable law or agreed to in writing, software *\/\n\/* distributed under the License is distributed on an AS IS BASIS, *\/\n\/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. *\/\n\/* See the License for the specific language governing permissions and *\/\n\/* limitations under the License. *\/\n\/* *\/\n\/****************************************************************************\/\n\n#ifndef DESOLIN_PROFILING_HASHING_VISITOR_HPP\n#define DESOLIN_PROFILING_HASHING_VISITOR_HPP\n\n#include \"Desolin_profiling_fwd.hpp\"\n#include <cstddef>\n#include <typeinfo>\n#include <string>\n#include <cstring>\n#include <map>\n#include <vector>\n#include <cassert>\n#include <boost\/functional\/hash.hpp>\n\nnamespace desolin\n{\n\nnamespace detail\n{\n\ntemplate<typename T_element>\nclass PHashingVisitor : public PExpressionNodeVisitor<T_element>\n{\nprivate:\n const std::map<const PExpressionNode<T_element>*, int> nodeNumberings;\n std::size_t hash;\n \n template<typename exprType>\n inline std::size_t hashExprNode(const PExprNode<exprType, T_element>& node) const\n {\n const char* nodeTypeString = typeid(node).name();\n return boost::hash_range(nodeTypeString, nodeTypeString+strlen(nodeTypeString));\n }\n\n template<typename resultType, typename exprType>\n std::size_t hashUnOp(const PUnOp<resultType, exprType, T_element>& unop) const\n {\n std::size_t seed = hashExprNode(unop);\n const typename std::map<const PExpressionNode<T_element>*, int>::const_iterator operand = nodeNumberings.find(&unop.getOperand());\n assert(operand != nodeNumberings.end());\n boost::hash_combine(seed, operand->second);\n return seed;\n }\n\n template<typename resultType, typename leftType, typename rightType>\n std::size_t hashBinOp(const PBinOp<resultType, leftType, rightType, T_element>& binop) const\n {\n std::size_t seed = hashExprNode(binop);\n const typename std::map<const PExpressionNode<T_element>*, int>::const_iterator left = nodeNumberings.find(&binop.getLeft());\n const typename std::map<const PExpressionNode<T_element>*, int>::const_iterator right = nodeNumberings.find(&binop.getRight());\n assert(left != nodeNumberings.end());\n assert(right != nodeNumberings.end());\n boost::hash_combine(seed, left->second);\n boost::hash_combine(seed, right->second);\n return seed;\n }\n\n template<typename exprType>\n std::size_t hashElementSet(const PElementSet<exprType, T_element>& node) const\n {\n std::size_t seed = hashUnOp(node);\n const std::vector<const PExprNode<scalar, T_element>*> assignments(node.getAssignments());\n typedef typename std::vector<const PExprNode<scalar, T_element>*>::const_iterator ConstIterator;\n \n for(ConstIterator assignment = assignments.begin(); assignment!=assignments.end(); ++assignment)\n {\n const typename std::map<const PExpressionNode<T_element>*, int>::const_iterator numbering = nodeNumberings.find(*assignment);\n assert(numbering != nodeNumberings.end());\n boost::hash_combine(seed, numbering->second);\n }\n return seed;\n }\n\n template<typename exprType>\n std::size_t hashPairwise(const PPairwise<exprType, T_element>& node) const\n {\n std::size_t seed = hashBinOp(node);\n boost::hash_combine(seed, node.getOperation());\n return seed;\n }\n\n template<typename exprType>\n std::size_t hashScalarPiecewise(const PScalarPiecewise<exprType, T_element>& node) const\n {\n std::size_t seed = hashBinOp(node);\n boost::hash_combine(seed, node.getOperation());\n return seed;\n }\n \npublic:\n\n PHashingVisitor(const std::map<const PExpressionNode<T_element>*, int>& numberings) : nodeNumberings(numberings), hash(0)\n {\n }\n \n inline std::size_t getHash() const\n {\n return hash;\n }\n \n virtual void visit(PElementGet<vector, T_element>& e)\n {\n boost::hash_combine(hash, hashUnOp(e));\n }\n \n virtual void visit(PElementGet<matrix, T_element>& e)\n {\n boost::hash_combine(hash, hashUnOp(e));\n }\n\n virtual void visit(PElementSet<vector, T_element>& e)\n {\n boost::hash_combine(hash, hashElementSet(e));\n }\n \n virtual void visit(PElementSet<matrix, T_element>& e)\n {\n boost::hash_combine(hash, hashElementSet(e));\n }\n\n virtual void visit(PLiteral<scalar, T_element>& e)\n {\n boost::hash_combine(hash, hashExprNode(e));\n }\n \n virtual void visit(PLiteral<vector, T_element>& e)\n {\n boost::hash_combine(hash, hashExprNode(e));\n }\n \n virtual void visit(PLiteral<matrix, T_element>& e)\n {\n boost::hash_combine(hash, hashExprNode(e));\n }\n\n virtual void visit(PMatrixMult<T_element>& e)\n {\n boost::hash_combine(hash, hashBinOp(e));\n }\n \n virtual void visit(PMatrixVectorMult<T_element>& e)\n {\n boost::hash_combine(hash, hashBinOp(e));\n }\n \n virtual void visit(PTransposeMatrixVectorMult<T_element>& e)\n {\n boost::hash_combine(hash, hashBinOp(e));\n }\n \n virtual void visit(PVectorDot<T_element>& e)\n {\n boost::hash_combine(hash, hashBinOp(e));\n }\n \n virtual void visit(PVectorCross<T_element>& e)\n {\n boost::hash_combine(hash, hashBinOp(e));\n }\n \n virtual void visit(PVectorTwoNorm<T_element>& e)\n {\n boost::hash_combine(hash, hashUnOp(e));\n }\n \n virtual void visit(PMatrixTranspose<T_element>& e)\n {\n boost::hash_combine(hash, hashUnOp(e));\n }\n\n virtual void visit(PPairwise<scalar, T_element>& e)\n {\n boost::hash_combine(hash, hashPairwise(e));\n }\n \n virtual void visit(PPairwise<vector, T_element>& e)\n {\n boost::hash_combine(hash, hashPairwise(e));\n }\n \n virtual void visit(PPairwise<matrix, T_element>& e) \n {\n boost::hash_combine(hash, hashPairwise(e));\n }\n\n virtual void visit(PScalarPiecewise<scalar, T_element>& e)\n {\n boost::hash_combine(hash, hashScalarPiecewise(e));\n }\n \n virtual void visit(PScalarPiecewise<vector, T_element>& e) \n {\n boost::hash_combine(hash, hashScalarPiecewise(e));\n }\n \n virtual void visit(PScalarPiecewise<matrix, T_element>& e)\n {\n boost::hash_combine(hash, hashScalarPiecewise(e));\n }\n\n virtual void visit(PNegate<scalar, T_element>& e)\n {\n boost::hash_combine(hash, hashUnOp(e));\n }\n \n virtual void visit(PNegate<vector, T_element>& e)\n {\n boost::hash_combine(hash, hashUnOp(e));\n }\n \n virtual void visit(PNegate<matrix, T_element>& e)\n {\n boost::hash_combine(hash, hashUnOp(e));\n }\n\n virtual void visit(PAbsolute<T_element>& e)\n {\n boost::hash_combine(hash, hashUnOp(e));\n }\n \n virtual void visit(PSquareRoot<T_element>& e)\n {\n boost::hash_combine(hash, hashUnOp(e));\n }\n};\n\n}\n\n}\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/\/=======================================================================\n\/\/ Copyright (c) 2014-2017 Baptiste Wicht\n\/\/ Distributed under the terms of the MIT License.\n\/\/ (See accompanying file LICENSE or copy at\n\/\/ http:\/\/opensource.org\/licenses\/MIT)\n\/\/=======================================================================\n\n#pragma once\n\nnamespace dll {\n\n\/*!\n * \\brief A descriptor for an activation layer.\n *\n * Such a layer only applies an activation function to its inputs\n * and has no weights.\n *\/\ntemplate <typename... Parameters>\nstruct activation_layer_desc {\n \/*!\n * A list of all the parameters of the descriptor\n *\/\n using parameters = cpp::type_list<Parameters...>;\n\n \/*!\n * \\brief The layer's activation function\n *\/\n static constexpr function activation_function = detail::get_value<activation<function::SIGMOID>, Parameters...>::value;\n\n \/*!\n * The layer type\n *\/\n using layer_t = activation_layer<activation_layer_desc<Parameters...>>;\n\n \/*!\n * The dynamic layer type\n *\/\n using dyn_layer_t = activation_layer<activation_layer_desc<Parameters...>>;\n\n \/\/Make sure only valid types are passed to the configuration list\n static_assert(\n detail::is_valid<cpp::type_list<activation_id>, Parameters...>::value,\n \"Invalid parameters type for activation_layer_desc\");\n};\n\n} \/\/end of dll namespace\n<commit_msg>Simplify activation layer descriptors<commit_after>\/\/=======================================================================\n\/\/ Copyright (c) 2014-2017 Baptiste Wicht\n\/\/ Distributed under the terms of the MIT License.\n\/\/ (See accompanying file LICENSE or copy at\n\/\/ http:\/\/opensource.org\/licenses\/MIT)\n\/\/=======================================================================\n\n#pragma once\n\nnamespace dll {\n\n\/*!\n * \\brief A descriptor for an activation layer.\n *\n * Such a layer only applies an activation function to its inputs\n * and has no weights.\n *\/\ntemplate <dll::function F = dll::function::SIGMOID>\nstruct activation_layer_desc {\n \/*!\n * \\brief The layer's activation function\n *\/\n static constexpr function activation_function = F;\n\n \/*!\n * The layer type\n *\/\n using layer_t = activation_layer<activation_layer_desc<F>>;\n\n \/*!\n * The dynamic layer type\n *\/\n using dyn_layer_t = activation_layer<activation_layer_desc<F>>;\n};\n\n} \/\/end of dll namespace\n<|endoftext|>"} {"text":"<commit_before>\/** \n * @file llspeakingindicatormanager.cpp\n * @author Mike Antipov\n * @brief Implementation of SpeackerIndicatorManager class to process registered LLSpeackerIndicator\n * depend on avatars are in the same voice channel.\n *\n * $LicenseInfo:firstyear=2010&license=viewergpl$\n * \n * Copyright (c) 2010, Linden Research, Inc.\n * \n * Second Life Viewer Source Code\n * The source code in this file (\"Source Code\") is provided by Linden Lab\n * to you under the terms of the GNU General Public License, version 2.0\n * (\"GPL\"), unless you have obtained a separate licensing agreement\n * (\"Other License\"), formally executed by you and Linden Lab. Terms of\n * the GPL can be found in doc\/GPL-license.txt in this distribution, or\n * online at http:\/\/secondlifegrid.net\/programs\/open_source\/licensing\/gplv2\n * \n * There are special exceptions to the terms and conditions of the GPL as\n * it is applied to this Source Code. View the full text of the exception\n * in the file doc\/FLOSS-exception.txt in this software distribution, or\n * online at\n * http:\/\/secondlifegrid.net\/programs\/open_source\/licensing\/flossexception\n * \n * By copying, modifying or distributing this software, you acknowledge\n * that you have read and understood your obligations described above,\n * and agree to abide by those obligations.\n * \n * ALL LINDEN LAB SOURCE CODE IS PROVIDED \"AS IS.\" LINDEN LAB MAKES NO\n * WARRANTIES, EXPRESS, IMPLIED OR OTHERWISE, REGARDING ITS ACCURACY,\n * COMPLETENESS OR PERFORMANCE.\n * $\/LicenseInfo$\n *\/\n\n#include \"llviewerprecompiledheaders.h\"\n#include \"llspeakingindicatormanager.h\"\n\n\n#include \"llagentdata.h\"\n#include \"llvoicechannel.h\"\n#include \"llvoiceclient.h\"\n\n\/**\n * This class intended to control visibility of avatar speaking indicators depend on whether avatars\n * are in the same voice channel.\n *\n * Speaking indicator should be visible for avatars in the same voice channel. See EXT-3976.\n *\n * It stores passed instances of LLOutputMonitorCtrl in a multimap by avatar LLUUID.\n * It observes changing of voice channel and changing of participant list in voice channel.\n * When voice channel or voice participant list is changed it updates visibility of an appropriate \n * speaking indicator.\n *\n * Several indicators can be registered for the same avatar.\n *\/\nclass SpeakingIndicatorManager : public LLSingleton<SpeakingIndicatorManager>, LLVoiceClientParticipantObserver\n{\n\tLOG_CLASS(SpeakingIndicatorManager);\npublic:\n\n\t\/**\n\t * Stores passed speaking indicator to control its visibility.\n\t *\n\t * Registered indicator is set visible if an appropriate avatar is in the same voice channel with Agent.\n\t * It ignores instances of Agent's indicator.\n\t *\n\t * @param speaker_id LLUUID of an avatar whose speaking indicator is registered.\n\t * @param speaking_indicator instance of the speaking indicator to be registered.\n\t *\/\n\tvoid registerSpeakingIndicator(const LLUUID& speaker_id, LLSpeakingIndicator* const speaking_indicator);\n\n\t\/**\n\t * Removes passed speaking indicator from observing.\n\t *\n\t * @param speaker_id LLUUID of an avatar whose speaking indicator should be unregistered.\n\t * @param speaking_indicator instance of the speaking indicator to be unregistered.\n\t *\/\n\tvoid unregisterSpeakingIndicator(const LLUUID& speaker_id, const LLSpeakingIndicator* const speaking_indicator);\n\nprivate:\n\ttypedef std::set<LLUUID> speaker_ids_t;\n\ttypedef std::multimap<LLUUID, LLSpeakingIndicator*> speaking_indicators_mmap_t;\n\ttypedef speaking_indicators_mmap_t::value_type speaking_indicator_value_t;\n\ttypedef speaking_indicators_mmap_t::const_iterator indicator_const_iterator;\n\ttypedef std::pair<indicator_const_iterator, indicator_const_iterator> indicator_range_t;\n\n\tfriend class LLSingleton<SpeakingIndicatorManager>;\n\tSpeakingIndicatorManager();\n\t~SpeakingIndicatorManager();\n\n\t\/**\n\t * Callback to determine when voice channel is changed.\n\t *\n\t * It switches all registered speaking indicators off.\n\t * To reduce overheads only switched on indicators are processed.\n\t *\/\n\tvoid sOnCurrentChannelChanged(const LLUUID& session_id);\n\n\t\/**\n\t * Callback of changing voice participant list (from LLVoiceClientParticipantObserver).\n\t *\n\t * Switches off indicators had been switched on and switches on indicators of current participants list.\n\t * There is only a few indicators in lists should be switched off\/on.\n\t * So, method does not calculate difference between these list it only switches off already \n\t * switched on indicators and switches on indicators of voice channel participants\n\t *\/\n\tvoid onChange();\n\n\t\/**\n\t * Changes state of indicators specified by LLUUIDs\n\t *\n\t * @param speakers_uuids - avatars' LLUUIDs whose speaking indicators should be switched\n\t * @param switch_on - if TRUE specified indicator will be switched on, off otherwise.\n\t *\/\n\tvoid switchSpeakerIndicators(const speaker_ids_t& speakers_uuids, BOOL switch_on);\n\n\t\/**\n\t * Multimap with all registered speaking indicators\n\t *\/\n\tspeaking_indicators_mmap_t mSpeakingIndicators;\n\n\t\/**\n\t * LUUIDs of avatar for which we have speaking indicators switched on.\n\t *\n\t * Is used to switch off all previously ON indicators when voice participant list is changed.\n\t *\n\t * @see onChange()\n\t *\/\n\tspeaker_ids_t mSwitchedIndicatorsOn;\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ PUBLIC SECTION\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid SpeakingIndicatorManager::registerSpeakingIndicator(const LLUUID& speaker_id, LLSpeakingIndicator* const speaking_indicator)\n{\n\tif (speaker_id == gAgentID) return;\n\n\tLL_DEBUGS(\"SpeakingIndicator\") << \"Registering indicator: \" << speaker_id << LL_ENDL;\n\tspeaking_indicator_value_t value_type(speaker_id, speaking_indicator);\n\tmSpeakingIndicators.insert(value_type);\n\n\tspeaker_ids_t speakers_uuids;\n\tBOOL is_in_same_voice = LLVoiceClient::getInstance()->findParticipantByID(speaker_id) != NULL;\n\n\tspeakers_uuids.insert(speaker_id);\n\tswitchSpeakerIndicators(speakers_uuids, is_in_same_voice);\n}\n\nvoid SpeakingIndicatorManager::unregisterSpeakingIndicator(const LLUUID& speaker_id, const LLSpeakingIndicator* const speaking_indicator)\n{\n\tspeaking_indicators_mmap_t::iterator it;\n\tit = mSpeakingIndicators.find(speaker_id);\n\tfor (;it != mSpeakingIndicators.end(); ++it)\n\t{\n\t\tif (it->second == speaking_indicator)\n\t\t{\n\t\t\tmSpeakingIndicators.erase(it);\n\t\t\tbreak;\n\t\t}\n\t}\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ PRIVATE SECTION\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nSpeakingIndicatorManager::SpeakingIndicatorManager()\n{\n\tLLVoiceChannel::setCurrentVoiceChannelChangedCallback(boost::bind(&SpeakingIndicatorManager::sOnCurrentChannelChanged, this, _1));\n\tLLVoiceClient::getInstance()->addObserver(this);\n}\n\nSpeakingIndicatorManager::~SpeakingIndicatorManager()\n{\n\t\/\/ Don't use LLVoiceClient::getInstance() here without check\n\t\/\/ singleton MAY have already been destroyed.\n\tif(LLVoiceClient::instanceExists())\n\t{\n\t\tLLVoiceClient::getInstance()->removeObserver(this);\n\t}\n}\n\nvoid SpeakingIndicatorManager::sOnCurrentChannelChanged(const LLUUID& \/*session_id*\/)\n{\n\tswitchSpeakerIndicators(mSwitchedIndicatorsOn, FALSE);\n\tmSwitchedIndicatorsOn.clear();\n}\n\nvoid SpeakingIndicatorManager::onChange()\n{\n\tLL_DEBUGS(\"SpeakingIndicator\") << \"Voice participant list was changed, updating indicators\" << LL_ENDL;\n\n\tspeaker_ids_t speakers_uuids;\n\tLLVoiceClient::getInstance()->getParticipantsUUIDSet(speakers_uuids);\n\n\tLL_DEBUGS(\"SpeakingIndicator\") << \"Switching all OFF, count: \" << mSwitchedIndicatorsOn.size() << LL_ENDL;\n\t\/\/ switch all indicators off\n\tswitchSpeakerIndicators(mSwitchedIndicatorsOn, FALSE);\n\tmSwitchedIndicatorsOn.clear();\n\n\tLL_DEBUGS(\"SpeakingIndicator\") << \"Switching all ON, count: \" << speakers_uuids.size() << LL_ENDL;\n\t\/\/ then switch current voice participants indicators on\n\tswitchSpeakerIndicators(speakers_uuids, TRUE);\n}\n\nvoid SpeakingIndicatorManager::switchSpeakerIndicators(const speaker_ids_t& speakers_uuids, BOOL switch_on)\n{\n\tspeaker_ids_t::const_iterator it_uuid = speakers_uuids.begin(); \n\tfor (; it_uuid != speakers_uuids.end(); ++it_uuid)\n\t{\n\t\tLL_DEBUGS(\"SpeakingIndicator\") << \"Looking for indicator: \" << *it_uuid << LL_ENDL;\n\t\tindicator_range_t it_range = mSpeakingIndicators.equal_range(*it_uuid);\n\t\tindicator_const_iterator it_indicator = it_range.first;\n\t\tbool was_found = false;\n\t\tfor (; it_indicator != it_range.second; ++it_indicator)\n\t\t{\n\t\t\twas_found = true;\n\t\t\tLLSpeakingIndicator* indicator = (*it_indicator).second;\n\t\t\tindicator->switchIndicator(switch_on);\n\t\t}\n\n\t\tif (was_found)\n\t\t{\n\t\t\tLL_DEBUGS(\"SpeakingIndicator\") << mSpeakingIndicators.count(*it_uuid) << \" indicators where found\" << LL_ENDL;\n\n\t\t\tif (switch_on)\n\t\t\t{\n\t\t\t\t\/\/ store switched on indicator to be able switch it off\n\t\t\t\tmSwitchedIndicatorsOn.insert(*it_uuid);\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tLL_WARNS(\"SpeakingIndicator\") << \"indicator was not found among registered: \" << *it_uuid << LL_ENDL;\n\t\t}\n\t}\n}\n\n\/************************************************************************\/\n\/* LLSpeakingIndicatorManager namespace implementation *\/\n\/************************************************************************\/\n\nvoid LLSpeakingIndicatorManager::registerSpeakingIndicator(const LLUUID& speaker_id, LLSpeakingIndicator* const speaking_indicator)\n{\n\tSpeakingIndicatorManager::instance().registerSpeakingIndicator(speaker_id, speaking_indicator);\n}\n\nvoid LLSpeakingIndicatorManager::unregisterSpeakingIndicator(const LLUUID& speaker_id, const LLSpeakingIndicator* const speaking_indicator)\n{\n\tSpeakingIndicatorManager::instance().unregisterSpeakingIndicator(speaker_id, speaking_indicator);\n}\n\n\/\/ EOF\n\n<commit_msg>Related to EXT-3976 (Voice chat speaking indicators should only display when users are in the same voice channel) -- cleanup: remove logging of unnecessary warning messages if there are no any registered speaking indicators for voice participant<commit_after>\/** \n * @file llspeakingindicatormanager.cpp\n * @author Mike Antipov\n * @brief Implementation of SpeackerIndicatorManager class to process registered LLSpeackerIndicator\n * depend on avatars are in the same voice channel.\n *\n * $LicenseInfo:firstyear=2010&license=viewergpl$\n * \n * Copyright (c) 2010, Linden Research, Inc.\n * \n * Second Life Viewer Source Code\n * The source code in this file (\"Source Code\") is provided by Linden Lab\n * to you under the terms of the GNU General Public License, version 2.0\n * (\"GPL\"), unless you have obtained a separate licensing agreement\n * (\"Other License\"), formally executed by you and Linden Lab. Terms of\n * the GPL can be found in doc\/GPL-license.txt in this distribution, or\n * online at http:\/\/secondlifegrid.net\/programs\/open_source\/licensing\/gplv2\n * \n * There are special exceptions to the terms and conditions of the GPL as\n * it is applied to this Source Code. View the full text of the exception\n * in the file doc\/FLOSS-exception.txt in this software distribution, or\n * online at\n * http:\/\/secondlifegrid.net\/programs\/open_source\/licensing\/flossexception\n * \n * By copying, modifying or distributing this software, you acknowledge\n * that you have read and understood your obligations described above,\n * and agree to abide by those obligations.\n * \n * ALL LINDEN LAB SOURCE CODE IS PROVIDED \"AS IS.\" LINDEN LAB MAKES NO\n * WARRANTIES, EXPRESS, IMPLIED OR OTHERWISE, REGARDING ITS ACCURACY,\n * COMPLETENESS OR PERFORMANCE.\n * $\/LicenseInfo$\n *\/\n\n#include \"llviewerprecompiledheaders.h\"\n#include \"llspeakingindicatormanager.h\"\n\n\n#include \"llagentdata.h\"\n#include \"llvoicechannel.h\"\n#include \"llvoiceclient.h\"\n\n\/**\n * This class intended to control visibility of avatar speaking indicators depend on whether avatars\n * are in the same voice channel.\n *\n * Speaking indicator should be visible for avatars in the same voice channel. See EXT-3976.\n *\n * It stores passed instances of LLOutputMonitorCtrl in a multimap by avatar LLUUID.\n * It observes changing of voice channel and changing of participant list in voice channel.\n * When voice channel or voice participant list is changed it updates visibility of an appropriate \n * speaking indicator.\n *\n * Several indicators can be registered for the same avatar.\n *\/\nclass SpeakingIndicatorManager : public LLSingleton<SpeakingIndicatorManager>, LLVoiceClientParticipantObserver\n{\n\tLOG_CLASS(SpeakingIndicatorManager);\npublic:\n\n\t\/**\n\t * Stores passed speaking indicator to control its visibility.\n\t *\n\t * Registered indicator is set visible if an appropriate avatar is in the same voice channel with Agent.\n\t * It ignores instances of Agent's indicator.\n\t *\n\t * @param speaker_id LLUUID of an avatar whose speaking indicator is registered.\n\t * @param speaking_indicator instance of the speaking indicator to be registered.\n\t *\/\n\tvoid registerSpeakingIndicator(const LLUUID& speaker_id, LLSpeakingIndicator* const speaking_indicator);\n\n\t\/**\n\t * Removes passed speaking indicator from observing.\n\t *\n\t * @param speaker_id LLUUID of an avatar whose speaking indicator should be unregistered.\n\t * @param speaking_indicator instance of the speaking indicator to be unregistered.\n\t *\/\n\tvoid unregisterSpeakingIndicator(const LLUUID& speaker_id, const LLSpeakingIndicator* const speaking_indicator);\n\nprivate:\n\ttypedef std::set<LLUUID> speaker_ids_t;\n\ttypedef std::multimap<LLUUID, LLSpeakingIndicator*> speaking_indicators_mmap_t;\n\ttypedef speaking_indicators_mmap_t::value_type speaking_indicator_value_t;\n\ttypedef speaking_indicators_mmap_t::const_iterator indicator_const_iterator;\n\ttypedef std::pair<indicator_const_iterator, indicator_const_iterator> indicator_range_t;\n\n\tfriend class LLSingleton<SpeakingIndicatorManager>;\n\tSpeakingIndicatorManager();\n\t~SpeakingIndicatorManager();\n\n\t\/**\n\t * Callback to determine when voice channel is changed.\n\t *\n\t * It switches all registered speaking indicators off.\n\t * To reduce overheads only switched on indicators are processed.\n\t *\/\n\tvoid sOnCurrentChannelChanged(const LLUUID& session_id);\n\n\t\/**\n\t * Callback of changing voice participant list (from LLVoiceClientParticipantObserver).\n\t *\n\t * Switches off indicators had been switched on and switches on indicators of current participants list.\n\t * There is only a few indicators in lists should be switched off\/on.\n\t * So, method does not calculate difference between these list it only switches off already \n\t * switched on indicators and switches on indicators of voice channel participants\n\t *\/\n\tvoid onChange();\n\n\t\/**\n\t * Changes state of indicators specified by LLUUIDs\n\t *\n\t * @param speakers_uuids - avatars' LLUUIDs whose speaking indicators should be switched\n\t * @param switch_on - if TRUE specified indicator will be switched on, off otherwise.\n\t *\/\n\tvoid switchSpeakerIndicators(const speaker_ids_t& speakers_uuids, BOOL switch_on);\n\n\t\/**\n\t * Multimap with all registered speaking indicators\n\t *\/\n\tspeaking_indicators_mmap_t mSpeakingIndicators;\n\n\t\/**\n\t * LUUIDs of avatar for which we have speaking indicators switched on.\n\t *\n\t * Is used to switch off all previously ON indicators when voice participant list is changed.\n\t *\n\t * @see onChange()\n\t *\/\n\tspeaker_ids_t mSwitchedIndicatorsOn;\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ PUBLIC SECTION\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid SpeakingIndicatorManager::registerSpeakingIndicator(const LLUUID& speaker_id, LLSpeakingIndicator* const speaking_indicator)\n{\n\tif (speaker_id == gAgentID) return;\n\n\tLL_DEBUGS(\"SpeakingIndicator\") << \"Registering indicator: \" << speaker_id << LL_ENDL;\n\tspeaking_indicator_value_t value_type(speaker_id, speaking_indicator);\n\tmSpeakingIndicators.insert(value_type);\n\n\tspeaker_ids_t speakers_uuids;\n\tBOOL is_in_same_voice = LLVoiceClient::getInstance()->findParticipantByID(speaker_id) != NULL;\n\n\tspeakers_uuids.insert(speaker_id);\n\tswitchSpeakerIndicators(speakers_uuids, is_in_same_voice);\n}\n\nvoid SpeakingIndicatorManager::unregisterSpeakingIndicator(const LLUUID& speaker_id, const LLSpeakingIndicator* const speaking_indicator)\n{\n\tspeaking_indicators_mmap_t::iterator it;\n\tit = mSpeakingIndicators.find(speaker_id);\n\tfor (;it != mSpeakingIndicators.end(); ++it)\n\t{\n\t\tif (it->second == speaking_indicator)\n\t\t{\n\t\t\tmSpeakingIndicators.erase(it);\n\t\t\tbreak;\n\t\t}\n\t}\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ PRIVATE SECTION\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nSpeakingIndicatorManager::SpeakingIndicatorManager()\n{\n\tLLVoiceChannel::setCurrentVoiceChannelChangedCallback(boost::bind(&SpeakingIndicatorManager::sOnCurrentChannelChanged, this, _1));\n\tLLVoiceClient::getInstance()->addObserver(this);\n}\n\nSpeakingIndicatorManager::~SpeakingIndicatorManager()\n{\n\t\/\/ Don't use LLVoiceClient::getInstance() here without check\n\t\/\/ singleton MAY have already been destroyed.\n\tif(LLVoiceClient::instanceExists())\n\t{\n\t\tLLVoiceClient::getInstance()->removeObserver(this);\n\t}\n}\n\nvoid SpeakingIndicatorManager::sOnCurrentChannelChanged(const LLUUID& \/*session_id*\/)\n{\n\tswitchSpeakerIndicators(mSwitchedIndicatorsOn, FALSE);\n\tmSwitchedIndicatorsOn.clear();\n}\n\nvoid SpeakingIndicatorManager::onChange()\n{\n\tLL_DEBUGS(\"SpeakingIndicator\") << \"Voice participant list was changed, updating indicators\" << LL_ENDL;\n\n\tspeaker_ids_t speakers_uuids;\n\tLLVoiceClient::getInstance()->getParticipantsUUIDSet(speakers_uuids);\n\n\tLL_DEBUGS(\"SpeakingIndicator\") << \"Switching all OFF, count: \" << mSwitchedIndicatorsOn.size() << LL_ENDL;\n\t\/\/ switch all indicators off\n\tswitchSpeakerIndicators(mSwitchedIndicatorsOn, FALSE);\n\tmSwitchedIndicatorsOn.clear();\n\n\tLL_DEBUGS(\"SpeakingIndicator\") << \"Switching all ON, count: \" << speakers_uuids.size() << LL_ENDL;\n\t\/\/ then switch current voice participants indicators on\n\tswitchSpeakerIndicators(speakers_uuids, TRUE);\n}\n\nvoid SpeakingIndicatorManager::switchSpeakerIndicators(const speaker_ids_t& speakers_uuids, BOOL switch_on)\n{\n\tspeaker_ids_t::const_iterator it_uuid = speakers_uuids.begin(); \n\tfor (; it_uuid != speakers_uuids.end(); ++it_uuid)\n\t{\n\t\tLL_DEBUGS(\"SpeakingIndicator\") << \"Looking for indicator: \" << *it_uuid << LL_ENDL;\n\t\tindicator_range_t it_range = mSpeakingIndicators.equal_range(*it_uuid);\n\t\tindicator_const_iterator it_indicator = it_range.first;\n\t\tbool was_found = false;\n\t\tfor (; it_indicator != it_range.second; ++it_indicator)\n\t\t{\n\t\t\twas_found = true;\n\t\t\tLLSpeakingIndicator* indicator = (*it_indicator).second;\n\t\t\tindicator->switchIndicator(switch_on);\n\t\t}\n\n\t\tif (was_found)\n\t\t{\n\t\t\tLL_DEBUGS(\"SpeakingIndicator\") << mSpeakingIndicators.count(*it_uuid) << \" indicators where found\" << LL_ENDL;\n\n\t\t\tif (switch_on)\n\t\t\t{\n\t\t\t\t\/\/ store switched on indicator to be able switch it off\n\t\t\t\tmSwitchedIndicatorsOn.insert(*it_uuid);\n\t\t\t}\n\t\t}\n\t}\n}\n\n\/************************************************************************\/\n\/* LLSpeakingIndicatorManager namespace implementation *\/\n\/************************************************************************\/\n\nvoid LLSpeakingIndicatorManager::registerSpeakingIndicator(const LLUUID& speaker_id, LLSpeakingIndicator* const speaking_indicator)\n{\n\tSpeakingIndicatorManager::instance().registerSpeakingIndicator(speaker_id, speaking_indicator);\n}\n\nvoid LLSpeakingIndicatorManager::unregisterSpeakingIndicator(const LLUUID& speaker_id, const LLSpeakingIndicator* const speaking_indicator)\n{\n\tSpeakingIndicatorManager::instance().unregisterSpeakingIndicator(speaker_id, speaking_indicator);\n}\n\n\/\/ EOF\n\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: thread.hxx,v $\n *\n * $Revision: 1.4 $\n *\n * last change: $Author: rt $ $Date: 2005-09-08 08:47:30 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n#ifndef _CPPU_THREADPOOL_THREAD_HXX\n#define _CPPU_THREADPOOL_THREAD_HXX\n\n#include <list>\n\n#ifndef _SAL_TYPES_H_\n#include <sal\/types.h>\n#endif\n\n#include <osl\/thread.h>\n\n#include \"jobqueue.hxx\"\n\nnamespace cppu_threadpool {\n\n class JobQueue;\n\n \/\/-----------------------------------------\n \/\/ private thread class for the threadpool\n \/\/ independent from vos\n \/\/-----------------------------------------\n class ORequestThread\n {\n public:\n ORequestThread( JobQueue * ,\n const ::rtl::ByteSequence &aThreadId,\n sal_Bool bAsynchron );\n ~ORequestThread();\n\n void setTask( JobQueue * , const ::rtl::ByteSequence & aThreadId , sal_Bool bAsynchron );\n\n sal_Bool create();\n void join();\n void onTerminated();\n void run();\n inline void setDeleteSelf( sal_Bool b )\n { m_bDeleteSelf = b; }\n\n private:\n oslThread m_thread;\n JobQueue *m_pQueue;\n ::rtl::ByteSequence m_aThreadId;\n sal_Bool m_bAsynchron;\n sal_Bool m_bDeleteSelf;\n };\n\n class ThreadAdmin\n {\n public:\n ~ThreadAdmin ();\n static ThreadAdmin *getInstance();\n void add( ORequestThread * );\n void remove( ORequestThread * );\n void join();\n\n private:\n ::osl::Mutex m_mutex;\n ::std::list< ORequestThread * > m_lst;\n };\n\n} \/\/ end cppu_threadpool\n\n\n#endif\n\n<commit_msg>INTEGRATION: CWS sb49 (1.4.40); FILE MERGED 2006\/03\/22 10:14:06 sb 1.4.40.1: #i63397# Keep objects alive long enough so that threads still running while atexit handlers are processed do not access dead objects.<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: thread.hxx,v $\n *\n * $Revision: 1.5 $\n *\n * last change: $Author: hr $ $Date: 2006-04-19 13:49:20 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n#ifndef _CPPU_THREADPOOL_THREAD_HXX\n#define _CPPU_THREADPOOL_THREAD_HXX\n\n#include <list>\n\n#ifndef _RTL_REF_HXX_\n#include \"rtl\/ref.hxx\"\n#endif\n#ifndef _SAL_TYPES_H_\n#include <sal\/types.h>\n#endif\n\n#include <osl\/thread.h>\n\n#include \"jobqueue.hxx\"\n\nnamespace cppu_threadpool {\n\n class JobQueue;\n class ThreadPool;\n\n \/\/-----------------------------------------\n \/\/ private thread class for the threadpool\n \/\/ independent from vos\n \/\/-----------------------------------------\n class ORequestThread\n {\n public:\n ORequestThread( rtl::Reference< ThreadPool > const & threadPool,\n JobQueue * pQueue,\n const ::rtl::ByteSequence &aThreadId,\n sal_Bool bAsynchron );\n ~ORequestThread();\n\n void setTask( JobQueue * , const ::rtl::ByteSequence & aThreadId , sal_Bool bAsynchron );\n\n sal_Bool create();\n void join();\n void onTerminated();\n void run();\n inline void setDeleteSelf( sal_Bool b )\n { m_bDeleteSelf = b; }\n\n private:\n oslThread m_thread;\n rtl::Reference< ThreadPool > m_threadPool;\n JobQueue *m_pQueue;\n ::rtl::ByteSequence m_aThreadId;\n sal_Bool m_bAsynchron;\n sal_Bool m_bDeleteSelf;\n };\n\n class ThreadAdmin\n {\n public:\n ~ThreadAdmin ();\n static ThreadAdmin *getInstance();\n void add( ORequestThread * );\n void remove( ORequestThread * );\n void join();\n\n private:\n ::osl::Mutex m_mutex;\n ::std::list< ORequestThread * > m_lst;\n };\n\n} \/\/ end cppu_threadpool\n\n\n#endif\n\n<|endoftext|>"} {"text":"<commit_before>\/*RF implementation: setting up the transceiver AX5042\n * It uses the SPI library\n * \n * The circuit:\n * - Pins 2, 7, 20, 26 of AX5042 connected to 2,5V Power Supply\n * - Pins\n * - Pin 16 (MISO)of AX5042 connected to MISO (digital pin 50)\n * - Pin 17 (MOSI)of AX5042 connected to MOSI (digital pin 51)\n * - Pin 15 (CLK) of AX5042 connected to SCK (digital pin 52)\n * - Pin 14 (SEL) of AX5042 connected to SS (digital pin 49)\n * \n * All the programming has be done following the AX5042 Programming Manual\n*\/\n\n#include \"comms.h\"\n\nconst int chip_select_pin = 49;\n\n\/*Setting up the transceiver*\/\nvoid configure() {\npinMode(chip_select_pin, OUTPUT);\n SPI.begin(); \n write_register(AGCTARGET, 0x0E);\n write_register(PLLRNG, (read_register(PLLRNG) | 0x01));\n write_register(RXMISC, ((read_register(RXMISC) | 0x01)& 0xFD)\/\/write 01 in the last 2 bits\n configure_PLLLOOP(BANDSEL);\n configure_FREQ(FCARRIER);\n configure_TXPWR();\n configure_IFFREQ(FXTAL);\n configure_FSKDEV(BITRATE);\n configure_TXRATE(BITRATE);\n configure_CICDEC(BITRATE);\n configure_MODULATION(MODdefault);\n uint32_t fskmul = configure_FSKMUL(BITRATE,TMGCORRFRAC);\n uint32_t datarate = configure_DATARATE(BITRATE);\n \/\/we need the values of fskmul and datarate for TMGGAIN config\n configure_TMGGAIN(fskmul,datarate,TMGCORRFRAC);\n configure_AGCATTACK(BITRATE);\n configure_AGCDECAY(BITRATE);\n configure_PHASEGAIN();\n configure_FREQGAIN();\n configure_FREQGAIN2();\n configure_AMPLGAIN();\n configure_AMPLGAIN();\n\n \/*LACKS ENCODING PROGRAMMING*\/\n \n int fabort = 0; \/* '1' to abort packet*\/\n byte frmmode = 010; \/*HDLC*\/\n frmmode = frmmode << 1;\n byte crcmode = 001; \/*CRC-16*\/\n crcmode = crcmode <<4;\n byte framing = crcmode |frmmode | fabort;\n write_register(FRAMING, framing);\n\n write_register(IFMODE, 0x00); \/*Frame Mode*\/\n \n \/*IRQ and DCLK control the switches: '00' OFF, '01' Rx, '10' Tx*\/ \n byte irq_txenz = 11011111;\n byte dclkz= 10111111;\n byte pincfg1 = read_register(PINCFG1);\n pincfg1 = pincfg1 & dclkz & irq_txenz; \n write_register(PINCFG1, pincfg1);\n \n byte pincfg2 = 01110110;\n write_register(PINCFG2, pincfg2);\n}\n\nvoid tx(char *data,int data_size){\n write_register(PWRMODE, 0x60);\n delay (3);\n uint8_t freq0;\n uint32_t freq = FCARRIER\/FXTAL*2^24 + 1\/2;\n freq0 = freq >> 24;\n write_register(FREQ3, freq0);\n freq0 = freq >> 16;\n write_register(FREQ2, freq0);\n freq0 = freq >> 8;\n write_register(FREQ1, freq0);\n freq0 = freq;\n write_register(FREQ0, freq0);\n\n \/*LACKS ENCODING*\/\n\n write_register(PWRMODE, 0x6C);\n delay (0.05);\n auto_ranging();\n write_register(PWRMODE, 0x6D);\n delay (0.05);\n hdlc_tx(data, data_size);\n write_register(PWRMODE, 0x00);\n\n}\n\nchar *rx(){ \n write_register(PWRMODE, 0x60);\n delay (3);\n int fcarrier=433;\n int fxtal=16.3;\n uint8_t freq0;\n uint32_t freq = fcarrier\/fxtal*2^24 + 1\/2;\n freq0 = freq >> 24;\n write_register(FREQ3, freq0);\n freq0 = freq >> 16;\n write_register(FREQ2, freq0);\n freq0 = freq >> 8;\n write_register(FREQ1, freq0);\n freq0 = freq;\n write_register(FREQ0, freq0);\n \n \/*LACKS ENCODING*\/\n\n write_register(PWRMODE, 0x68);\n delay (0.05);\n auto_ranging();\n write_register(PWRMODE, 0x69);\n delay (0.05);\n char *data = hdlc_rx();\n write_register(PWRMODE, 0x00);\n return data;\n }\n\n\/*It has to be especified the value of each case when the protocol\n would be written*\/\nvoid change_x(int parameter, int value) {\n switch(parameter) {\n case FREQUENCY:\n uint8_t freq0;\n uint32_t freq = value\/FXTAL*2^24 + 1\/2;\n freq0 = freq >> 24;\n write_register(FREQ3, freq0);\n freq0 = freq >> 16;\n write_register(FREQ2, freq0);\n freq0 = freq >> 8;\n write_register(FREQ1, freq0);\n freq0 = freq;\n write_register(FREQ0, freq0);\n break;\n case BITRATE:\n int fdev=H\/2*value;\n uint8_t fsk0;\n uint32_t fsk = fdev\/FXTAL*2^24 + 1\/2;\n fsk0 = fsk >> 16;\n write_register(FSKDEV2, fsk0);\n fsk0 = fsk >> 8;\n write_register(FSKDEV1, fsk0);\n fsk0 = fsk;\n write_register(FSKDEV0, fsk0);\n break;\n }\n }\n\n\/*Read a register*\/\nunsigned int read_register(byte this_register) {\n unsigned int result = 0; \/\/ result to return\n byte reading = 0b01111111;\n byte data_to_send = reading & this_register;\n Serial.println(this_register, BIN);\n digitalWrite(chip_select_pin, LOW);\n SPI.transfer(data_to_send);\n result = SPI.transfer(0x00);\n digitalWrite(chip_select_pin, HIGH);\n return (result);\n}\n\n\/*Function to write a determinated value in a determinated Register*\/\nvoid write_register(byte this_register, byte this_value) {\n byte writing = 0b10000000;\n byte data_to_send = writing | this_register;\n digitalWrite(chip_select_pin, LOW);\n SPI.transfer(data_to_send); \n SPI.transfer(this_value);\n digitalWrite(chip_select_pin, HIGH);\n}\n\n\/*Auto range needed after initialize or setting chip in SYNTHRX or SYNTHTX*\/\nvoid auto_ranging(){\n write_register(PLLRANGING,0x08);\n}\n\n\/*------------------CONFIGURATION FUNCTIONS---------------------*\/\n\/*This function configures register PLLLOOP*\/\nvoid configure_PLLLOOP(int band){\n bandsel = band << 8;\n byte pllloop = bandsel | 0b00001111;\n write_register(PLLLOOP, pllloop);\n}\n\n\/*The parameter \"freq\" is supposed to be in Hz.\n *This function configures registers FREQ3, FREQ2,\n *FREQ1, FREQ0*\/\nvoid configure_FREQ(int freq){\n uint8_t freq0;\n uint32_t freq = freq\/FXTAL*2^24 + 1\/2;\n freq0 = freq >> 24;\n write_register(FREQ3, freq0);\n freq0 = freq >> 16;\n write_register(FREQ2, freq0);\n freq0 = freq >> 8;\n write_register(FREQ1, freq0);\n freq0 = freq;\n write_register(FREQ0, freq0); \n}\n\n\/*This function configures register TXPWR*\/\nvoid configure_TXPWR(){\n write_register(TXPWR, 0x0F);\n}\n\n\/*This function configures register IFFREQHI, IFFREQLO*\/\nvoid configure_IFFREQ(){\n int fif=1;\n uint8_t iffreq0;\n uint32_t iffreq = fif\/FXTAL*2^17 + 1\/2;\n iffreq0 = iffreq >> 8;\n write_register(IFFREQHI, iffreq0);\n iffreq0 = iffreq;\n write_register(IFFREQLO, iffreq0)\n}\n\n\/*This function configures registers FSKDEV2, FSKDEV1,\n*FSKDEV0*\/\nvoid configure_FSKDEV(int bitrate){\n int fdev=H\/2*bitrate;\n uint8_t fsk0;\n uint32_t fsk = fdev\/FXTAL*2^24 + 1\/2;\n fsk0 = fsk >> 16;\n write_register(FSKDEV2, fsk0);\n fsk0 = fsk >> 8;\n write_register(FSKDEV1, fsk0);\n fsk0 = fsk;\n write_register(FSKDEV0, fsk0);\n}\n\n\/*This function configures registers TXRATEHI, TXRATEMID,\n*TXRATELO*\/\nvoid configure_TXRATE(int bitrate){\n uint8_t txr0;\n uint32_t txr = bitrate\/FXTAL*2^24 + 1\/2;\n txr0 = txr >> 16;\n write_register(TXRATEHI, txr0);\n txr0 = txr >> 8;\n write_register(TXRATEMID, txr0);\n txr0 = txr;\n write_register(TXRATELO, txr0);\n}\n\n\/*This function configures registers CICDECHI, CICDECLO*\/\nvoid configure_CICDEC(int bitrate){\n uint8_t cicdec0;\n uint32_t cicdec = 1.5*FXTAL\/(8*1.2*(1+H)*bitrate);\n cicdec0 = cicdec >> 8;\n write_register(CICDECHI, cicdec0);\n cicdec0 = cicdec;\n write_register(CICDECLO, cicdec0);\n }\n\n\/*This function configures register MODULATION*\/\nvoid configure_MODULATION(String modulation){\n uint8_t modValue = getModulationReg(modulation);\n write_register(MODULATION, modValue); \n}\n\n\/*This function configures register FSKMUL*\/\nuint32_t configure_FSKMUL(int bitrate, int tmgcorrfrac, String modulationValue){\n unsigned int = fskmul;\n if(getModulationReg(modulationValue) < 8){\n fskmul = 1;\n }else{\n unsigned int comprovacion = FXTAL\/(4*bitrate*cicdec);\n if(tmgcorrfrac >= comprovacion){\n fskmul = 1\/(4*bitrate*cicdec\/FXTAL+1\/tmgcorrfrac);\n }\n\t}\n write_register(FSKMUL,fskmul);\n return fskmul;\n}\n\n\/*This function configures register DATARATE*\/\nuint32_t configure_DATARATE(int bitrate){\n uint8_t datarate0;\n uint32_t datarate = 2^10*FXTAL\/(2*169*bitrate)+1\/2;\n datarate0 = datarate >> 8;\n write_register(DATARATEHI, datarate0);\n datarate0 = datarate;\n write_register(DATARATELO, datarate0);\n return datarate;\n}\n\n\/*This function configures registers TMGGAINHI, TMGGAINLO*\/\nvoid configure_TMGGAIN(uint32_t fskmul,uint32_t datarate,int tmgcorrfrac){\n uint8_t tmggain0;\n uint32_t tmggain = fskmul*datarate\/tmgcorrfrac + 1\/2;\n tmggain0 = tmggain >> 8;\n write_register(TMGGAINHI, tmggain0);\n tmggain0 = tmggain;\n write_register(TMGGAINLO, tmggain0);\n}\n\n\/*This function configures registers AGCATTACK*\/\nvoid configure_AGCATTACK(int bitrate){\n uint32_t modValue = read_register(MODULATION);\n uint32_t agcattack;\n if(modValue == 0){\n agcattack = 27 + log(bitrate\/(10*FXTAL))\/log(2);\n }else{\n agcattack = 27 + log(bitrate\/FXTAL)\/log(2);\n }\n write_register(AGCATTACK, agcattack);\n}\n\n\/*This function configures registers AGCDECAY*\/\nvoid configure_AGCDECAY(int bitrate){\n uint32_t modValue = read_register(MODULATION);\n uint32_t agcdecay;\n if(modValue == 0){\n agcdecay = 27 + log(bitrate\/(100*FXTAL))\/log(2);\n }else{\n agcdecay = 27 + log(bitrate\/(10*FXTAL))\/log(2);\n }\n write_register(AGCDECAY, agcdecay);\n}\n\n\/*This function configures registers PHASEGAIN*\/\nvoid configure_PHASEGAIN(){\n uint32_t modValue = read_register(MODULATION);\n if(modValue == 0){\n write_register(PHASEGAIN, 0x00);\n }else{\n write_register(PHASEGAIN, 0x03);\n }\n}\n\n\/*This function configures registers FREQGAIN*\/\nvoid configure_FREQGAIN(){\n modValue = read_register(MODULATION);\n if(modValue < 7){\n write_register(FREQGAIN, 0x06);\n }else{\n write_register(FREQGAINEQ, 0x03);\n }\n}\n\n\/*This function configures registers FREQGAIN2*\/\nvoid configure_FREQGAIN2(){\n write_register(FREQGAIN2, 0x06);\n}\n\n\/*This function configures registers AMPLGAIN*\/\nvoid configure_AMPLGAIN(){\n write_register(AMPLGAIN, 0x06); \n}\n\n\/*--------------------------------------------------------------*\/\n\n\/*This function translates the String modulation into the value to be assigned\n*to the register in hexadecimal*\/\nuint8_t getModulationReg(String modulation){\n switch (modulation){\n case \"ASK\":\n modValue = 0x00;\n break;\n case \"PSK\":\n modValue = 0x04;\n break;\n case \"OQPSK\":\n modValue = 0x06;\n break;\n case \"MSK\":\n modValue = 0x07;\n break;\n case \"FSK\":\n modValue = 0x0B;\n break;\n case \"GFSK\":\n\t\t modValue = 0x0F;\n break;\n }\n return modValue;\n}<commit_msg>Adapted transmission and reception functions<commit_after>\/*RF implementation: setting up the transceiver AX5042\n * It uses the SPI library\n * \n * The circuit:\n * - Pins 2, 7, 20, 26 of AX5042 connected to 2,5V Power Supply\n * - Pins\n * - Pin 16 (MISO)of AX5042 connected to MISO (digital pin 50)\n * - Pin 17 (MOSI)of AX5042 connected to MOSI (digital pin 51)\n * - Pin 15 (CLK) of AX5042 connected to SCK (digital pin 52)\n * - Pin 14 (SEL) of AX5042 connected to SS (digital pin 49)\n * \n * All the programming has be done following the AX5042 Programming Manual\n*\/\n\n#include \"comms.h\"\n\nconst int chip_select_pin = 49;\n\n\/*The next variables save the changes on the default ones*\/\nint frequency;\nint bitrate;\nString modulationValue; \n\n\/*Setting up the transceiver*\/\nvoid configure() {\npinMode(chip_select_pin, OUTPUT);\n SPI.begin(); \n write_register(AGCTARGET, 0x0E);\n write_register(PLLRNG, (read_register(PLLRNG) | 0x01));\n write_register(RXMISC, ((read_register(RXMISC) | 0x01)& 0xFD)\/\/write 01 in the last 2 bits\n configure_PLLLOOP(BANDSEL);\n configure_FREQ(FCARRIER);\n configure_TXPWR();\n configure_IFFREQ(FXTAL);\n configure_FSKDEV(BITRATE);\n configure_TXRATE(BITRATE);\n configure_CICDEC(BITRATE);\n configure_MODULATION(MODdefault);\n uint32_t fskmul = configure_FSKMUL(BITRATE,TMGCORRFRAC);\n uint32_t datarate = configure_DATARATE(BITRATE);\n \/\/we need the values of fskmul and datarate for TMGGAIN config\n configure_TMGGAIN(fskmul,datarate,TMGCORRFRAC);\n configure_AGCATTACK(BITRATE);\n configure_AGCDECAY(BITRATE);\n configure_PHASEGAIN();\n configure_FREQGAIN();\n configure_FREQGAIN2();\n configure_AMPLGAIN();\n configure_AMPLGAIN();\n\n \/*LACKS ENCODING PROGRAMMING*\/\n \n int fabort = 0; \/* '1' to abort packet*\/\n byte frmmode = 010; \/*HDLC*\/\n frmmode = frmmode << 1;\n byte crcmode = 001; \/*CRC-16*\/\n crcmode = crcmode <<4;\n byte framing = crcmode |frmmode | fabort;\n write_register(FRAMING, framing);\n\n write_register(IFMODE, 0x00); \/*Frame Mode*\/\n \n \/*IRQ and DCLK control the switches: '00' OFF, '01' Rx, '10' Tx*\/ \n byte irq_txenz = 11011111;\n byte dclkz= 10111111;\n byte pincfg1 = read_register(PINCFG1);\n pincfg1 = pincfg1 & dclkz & irq_txenz; \n write_register(PINCFG1, pincfg1);\n \n byte pincfg2 = 01110110;\n write_register(PINCFG2, pincfg2);\n}\n\nvoid tx(char *data,int data_size){\n write_register(PWRMODE, 0x60);\n delay (3);\n if(frequency == NULL){\n configure_FREQ(FCARRIER);\n }else{\n configure_FREQ(frequency);\n }\n\n \/*LACKS ENCODING*\/\n\n write_register(PWRMODE, 0x6C);\n delay (0.05);\n auto_ranging();\n write_register(PWRMODE, 0x6D);\n delay (0.05);\n hdlc_tx(data, data_size);\n write_register(PWRMODE, 0x00);\n\n}\n\nchar *rx(){ \n write_register(PWRMODE, 0x60);\n delay (3);\n if(frequency == NULL){\n configure_FREQ(FCARRIER);\n }else{\n configure_FREQ(frequency);\n\t}\n \n \/*LACKS ENCODING*\/\n\n write_register(PWRMODE, 0x68);\n delay (0.05);\n auto_ranging();\n write_register(PWRMODE, 0x69);\n delay (0.05);\n char *data = hdlc_rx();\n write_register(PWRMODE, 0x00);\n return data;\n }\n\n\/*It has to be specified the value of each case when the protocol\n would be written*\/\nvoid change_x(int parameter, int value) {\n switch(parameter) {\n case FREQUENCY:\n uint8_t freq0;\n uint32_t freq = value\/FXTAL*2^24 + 1\/2;\n freq0 = freq >> 24;\n write_register(FREQ3, freq0);\n freq0 = freq >> 16;\n write_register(FREQ2, freq0);\n freq0 = freq >> 8;\n write_register(FREQ1, freq0);\n freq0 = freq;\n write_register(FREQ0, freq0);\n break;\n case BITRATE:\n int fdev=H\/2*value;\n uint8_t fsk0;\n uint32_t fsk = fdev\/FXTAL*2^24 + 1\/2;\n fsk0 = fsk >> 16;\n write_register(FSKDEV2, fsk0);\n fsk0 = fsk >> 8;\n write_register(FSKDEV1, fsk0);\n fsk0 = fsk;\n write_register(FSKDEV0, fsk0);\n break;\n }\n }\n\n\/*Read a register*\/\nunsigned int read_register(byte this_register) {\n unsigned int result = 0; \/\/ result to return\n byte reading = 0b01111111;\n byte data_to_send = reading & this_register;\n Serial.println(this_register, BIN);\n digitalWrite(chip_select_pin, LOW);\n SPI.transfer(data_to_send);\n result = SPI.transfer(0x00);\n digitalWrite(chip_select_pin, HIGH);\n return (result);\n}\n\n\/*Function to write a determinated value in a determinated Register*\/\nvoid write_register(byte this_register, byte this_value) {\n byte writing = 0b10000000;\n byte data_to_send = writing | this_register;\n digitalWrite(chip_select_pin, LOW);\n SPI.transfer(data_to_send); \n SPI.transfer(this_value);\n digitalWrite(chip_select_pin, HIGH);\n}\n\n\/*Auto range needed after initialize or setting chip in SYNTHRX or SYNTHTX*\/\nvoid auto_ranging(){\n write_register(PLLRANGING,0x08);\n}\n\n\/*------------------CONFIGURATION FUNCTIONS---------------------*\/\n\/*This function configures register PLLLOOP*\/\nvoid configure_PLLLOOP(int band){\n bandsel = band << 8;\n byte pllloop = bandsel | 0b00001111;\n write_register(PLLLOOP, pllloop);\n}\n\n\/*The parameter \"freq\" is supposed to be in Hz.\n *This function configures registers FREQ3, FREQ2,\n *FREQ1, FREQ0*\/\nvoid configure_FREQ(int freq){\n uint8_t freq0;\n uint32_t freq = freq\/FXTAL*2^24 + 1\/2;\n freq0 = freq >> 24;\n write_register(FREQ3, freq0);\n freq0 = freq >> 16;\n write_register(FREQ2, freq0);\n freq0 = freq >> 8;\n write_register(FREQ1, freq0);\n freq0 = freq;\n write_register(FREQ0, freq0); \n}\n\n\/*This function configures register TXPWR*\/\nvoid configure_TXPWR(){\n write_register(TXPWR, 0x0F);\n}\n\n\/*This function configures register IFFREQHI, IFFREQLO*\/\nvoid configure_IFFREQ(){\n int fif=1;\n uint8_t iffreq0;\n uint32_t iffreq = fif\/FXTAL*2^17 + 1\/2;\n iffreq0 = iffreq >> 8;\n write_register(IFFREQHI, iffreq0);\n iffreq0 = iffreq;\n write_register(IFFREQLO, iffreq0)\n}\n\n\/*This function configures registers FSKDEV2, FSKDEV1,\n*FSKDEV0*\/\nvoid configure_FSKDEV(int bitrate){\n int fdev=H\/2*bitrate;\n uint8_t fsk0;\n uint32_t fsk = fdev\/FXTAL*2^24 + 1\/2;\n fsk0 = fsk >> 16;\n write_register(FSKDEV2, fsk0);\n fsk0 = fsk >> 8;\n write_register(FSKDEV1, fsk0);\n fsk0 = fsk;\n write_register(FSKDEV0, fsk0);\n}\n\n\/*This function configures registers TXRATEHI, TXRATEMID,\n*TXRATELO*\/\nvoid configure_TXRATE(int bitrate){\n uint8_t txr0;\n uint32_t txr = bitrate\/FXTAL*2^24 + 1\/2;\n txr0 = txr >> 16;\n write_register(TXRATEHI, txr0);\n txr0 = txr >> 8;\n write_register(TXRATEMID, txr0);\n txr0 = txr;\n write_register(TXRATELO, txr0);\n}\n\n\/*This function configures registers CICDECHI, CICDECLO*\/\nvoid configure_CICDEC(int bitrate){\n uint8_t cicdec0;\n uint32_t cicdec = 1.5*FXTAL\/(8*1.2*(1+H)*bitrate);\n cicdec0 = cicdec >> 8;\n write_register(CICDECHI, cicdec0);\n cicdec0 = cicdec;\n write_register(CICDECLO, cicdec0);\n }\n\n\/*This function configures register MODULATION*\/\nvoid configure_MODULATION(String modulation){\n uint8_t modValue = getModulationReg(modulation);\n write_register(MODULATION, modValue); \n}\n\n\/*This function configures register FSKMUL*\/\nuint32_t configure_FSKMUL(int bitrate, int tmgcorrfrac, String modulationValue){\n unsigned int = fskmul;\n if(getModulationReg(modulationValue) < 8){\n fskmul = 1;\n }else{\n unsigned int comprovacion = FXTAL\/(4*bitrate*cicdec);\n if(tmgcorrfrac >= comprovacion){\n fskmul = 1\/(4*bitrate*cicdec\/FXTAL+1\/tmgcorrfrac);\n }\n\t}\n write_register(FSKMUL,fskmul);\n return fskmul;\n}\n\n\/*This function configures register DATARATE*\/\nuint32_t configure_DATARATE(int bitrate){\n uint8_t datarate0;\n uint32_t datarate = 2^10*FXTAL\/(2*169*bitrate)+1\/2;\n datarate0 = datarate >> 8;\n write_register(DATARATEHI, datarate0);\n datarate0 = datarate;\n write_register(DATARATELO, datarate0);\n return datarate;\n}\n\n\/*This function configures registers TMGGAINHI, TMGGAINLO*\/\nvoid configure_TMGGAIN(uint32_t fskmul,uint32_t datarate,int tmgcorrfrac){\n uint8_t tmggain0;\n uint32_t tmggain = fskmul*datarate\/tmgcorrfrac + 1\/2;\n tmggain0 = tmggain >> 8;\n write_register(TMGGAINHI, tmggain0);\n tmggain0 = tmggain;\n write_register(TMGGAINLO, tmggain0);\n}\n\n\/*This function configures registers AGCATTACK*\/\nvoid configure_AGCATTACK(int bitrate){\n uint32_t modValue = read_register(MODULATION);\n uint32_t agcattack;\n if(modValue == 0){\n agcattack = 27 + log(bitrate\/(10*FXTAL))\/log(2);\n }else{\n agcattack = 27 + log(bitrate\/FXTAL)\/log(2);\n }\n write_register(AGCATTACK, agcattack);\n}\n\n\/*This function configures registers AGCDECAY*\/\nvoid configure_AGCDECAY(int bitrate){\n uint32_t modValue = read_register(MODULATION);\n uint32_t agcdecay;\n if(modValue == 0){\n agcdecay = 27 + log(bitrate\/(100*FXTAL))\/log(2);\n }else{\n agcdecay = 27 + log(bitrate\/(10*FXTAL))\/log(2);\n }\n write_register(AGCDECAY, agcdecay);\n}\n\n\/*This function configures registers PHASEGAIN*\/\nvoid configure_PHASEGAIN(){\n uint32_t modValue = read_register(MODULATION);\n if(modValue == 0){\n write_register(PHASEGAIN, 0x00);\n }else{\n write_register(PHASEGAIN, 0x03);\n }\n}\n\n\/*This function configures registers FREQGAIN*\/\nvoid configure_FREQGAIN(){\n modValue = read_register(MODULATION);\n if(modValue < 7){\n write_register(FREQGAIN, 0x06);\n }else{\n write_register(FREQGAINEQ, 0x03);\n }\n}\n\n\/*This function configures registers FREQGAIN2*\/\nvoid configure_FREQGAIN2(){\n write_register(FREQGAIN2, 0x06);\n}\n\n\/*This function configures registers AMPLGAIN*\/\nvoid configure_AMPLGAIN(){\n write_register(AMPLGAIN, 0x06); \n}\n\n\/*--------------------------------------------------------------*\/\n\n\/*This function translates the String modulation into the value to be assigned\n*to the register in hexadecimal*\/\nuint8_t getModulationReg(String modulation){\n switch (modulation){\n case \"ASK\":\n modValue = 0x00;\n break;\n case \"PSK\":\n modValue = 0x04;\n break;\n case \"OQPSK\":\n modValue = 0x06;\n break;\n case \"MSK\":\n modValue = 0x07;\n break;\n case \"FSK\":\n modValue = 0x0B;\n break;\n case \"GFSK\":\n\t\t modValue = 0x0F;\n break;\n }\n return modValue;\n}<|endoftext|>"} {"text":"<commit_before>\/\/ LICENSE\/*{{{*\/\n\/*\n sxc - Simple Xmpp Client\n Copyright (C) 2008 Dennis Felsing, Andreas Waidler\n\n This program is free software: you can redistribute it and\/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation, either version 3 of the License, or\n (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n\/*}}}*\/\n\n\/\/ INCLUDES\/*{{{*\/\n\n#ifdef HAVE_CONFIG_H\n# include <config.hxx>\n# include <print.hxx>\n#endif\n\n#include <string>\n#include <Control\/Control.hxx>\n#include <Control\/File\/Output.hxx>\n#include <Control\/Command\/Command.hxx>\n#include <libsxc\/Exception\/Exception.hxx>\n#include <Time\/Timestamp.hxx>\n#include <Time\/LocalDateTime.hxx>\n#include <Time\/IsoDateTimeFormat.hxx>\n\n\/*}}}*\/\n\nnamespace Control\n{\n namespace File\n {\n Output::Output(const std::string &accountName)\/*{{{*\/\n : _accountName(accountName)\n {\n }\n\n\/*}}}*\/\n std::string Output::_createPath() const\/*{{{*\/\n {\n return _accountName + \"\/out\";\n }\n\n\/*}}}*\/\n std::string Output::_format(const std::string &output) const\/*{{{*\/\n {\n Time::LocalDateTime date = Time::LocalDateTime(Time::Timestamp());\n Time::IsoDateTimeFormat format(&date);\n return format.string() + ' ' + output;\n }\n\n\/*}}}*\/\n }\n}\n\n\/\/ Use no tabs at all; four spaces indentation; max. eighty chars per line.\n\/\/ vim: et ts=4 sw=4 tw=80 fo+=c fdm=marker\n<commit_msg>Removed unnecessary includes.<commit_after>\/\/ LICENSE\/*{{{*\/\n\/*\n sxc - Simple Xmpp Client\n Copyright (C) 2008 Dennis Felsing, Andreas Waidler\n\n This program is free software: you can redistribute it and\/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation, either version 3 of the License, or\n (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n\/*}}}*\/\n\n\/\/ INCLUDES\/*{{{*\/\n\n#ifdef HAVE_CONFIG_H\n# include <config.hxx>\n# include <print.hxx>\n#endif\n\n#include <string>\n#include <Control\/File\/Output.hxx>\n#include <Time\/Timestamp.hxx>\n#include <Time\/LocalDateTime.hxx>\n#include <Time\/IsoDateTimeFormat.hxx>\n\n\/*}}}*\/\n\nnamespace Control\n{\n namespace File\n {\n Output::Output(const std::string &accountName)\/*{{{*\/\n : _accountName(accountName)\n {\n }\n\n\/*}}}*\/\n std::string Output::_createPath() const\/*{{{*\/\n {\n return _accountName + \"\/out\";\n }\n\n\/*}}}*\/\n std::string Output::_format(const std::string &output) const\/*{{{*\/\n {\n Time::LocalDateTime date = Time::LocalDateTime(Time::Timestamp());\n Time::IsoDateTimeFormat format(&date);\n return format.string() + ' ' + output;\n }\n\n\/*}}}*\/\n }\n}\n\n\/\/ Use no tabs at all; four spaces indentation; max. eighty chars per line.\n\/\/ vim: et ts=4 sw=4 tw=80 fo+=c fdm=marker\n<|endoftext|>"} {"text":"<commit_before>\/\/===-- WriteInst.cpp - Functions for writing instructions -------*- C++ -*--=\/\/\n\/\/\n\/\/ This file implements the routines for encoding instruction opcodes to a \n\/\/ bytecode stream.\n\/\/\n\/\/ Note that the performance of this library is not terribly important, because\n\/\/ it shouldn't be used by JIT type applications... so it is not a huge focus\n\/\/ at least. :)\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"WriterInternals.h\"\n#include \"llvm\/Module.h\"\n#include \"llvm\/Function.h\"\n#include \"llvm\/BasicBlock.h\"\n#include \"llvm\/DerivedTypes.h\"\n#include \"llvm\/iOther.h\"\n#include \"llvm\/iTerminators.h\"\n#include <algorithm>\n\ntypedef unsigned char uchar;\n\n\/\/ outputInstructionFormat0 - Output those wierd instructions that have a large\n\/\/ number of operands or have large operands themselves...\n\/\/\n\/\/ Format: [opcode] [type] [numargs] [arg0] [arg1] ... [arg<numargs-1>]\n\/\/\nstatic void outputInstructionFormat0(const Instruction *I,\n\t\t\t\t const SlotCalculator &Table,\n\t\t\t\t unsigned Type, std::deque<uchar> &Out) {\n \/\/ Opcode must have top two bits clear...\n output_vbr(I->getOpcode() << 2, Out); \/\/ Instruction Opcode ID\n output_vbr(Type, Out); \/\/ Result type\n\n unsigned NumArgs = I->getNumOperands();\n output_vbr(NumArgs + isa<CastInst>(I), Out);\n\n for (unsigned i = 0; i < NumArgs; ++i) {\n int Slot = Table.getValSlot(I->getOperand(i));\n assert(Slot >= 0 && \"No slot number for value!?!?\"); \n output_vbr((unsigned)Slot, Out);\n }\n\n if (isa<CastInst>(I)) {\n int Slot = Table.getValSlot(I->getType());\n assert(Slot != -1 && \"Cast return type unknown?\");\n output_vbr((unsigned)Slot, Out);\n }\n\n align32(Out); \/\/ We must maintain correct alignment!\n}\n\n\n\/\/ outputInstrVarArgsCall - Output the obsurdly annoying varargs function calls.\n\/\/ This are more annoying than most because the signature of the call does not\n\/\/ tell us anything about the types of the arguments in the varargs portion.\n\/\/ Because of this, we encode (as type 0) all of the argument types explicitly\n\/\/ before the argument value. This really sucks, but you shouldn't be using\n\/\/ varargs functions in your code! *death to printf*!\n\/\/\n\/\/ Format: [opcode] [type] [numargs] [arg0] [arg1] ... [arg<numargs-1>]\n\/\/\nstatic void outputInstrVarArgsCall(const Instruction *I,\n\t\t\t\t const SlotCalculator &Table, unsigned Type,\n\t\t\t\t std::deque<uchar> &Out) {\n assert(isa<CallInst>(I) || isa<InvokeInst>(I));\n \/\/ Opcode must have top two bits clear...\n output_vbr(I->getOpcode() << 2, Out); \/\/ Instruction Opcode ID\n output_vbr(Type, Out); \/\/ Result type (varargs type)\n\n unsigned NumArgs = I->getNumOperands();\n output_vbr(NumArgs*2, Out);\n \/\/ TODO: Don't need to emit types for the fixed types of the varargs function\n \/\/ prototype...\n\n \/\/ The type for the function has already been emitted in the type field of the\n \/\/ instruction. Just emit the slot # now.\n int Slot = Table.getValSlot(I->getOperand(0));\n assert(Slot >= 0 && \"No slot number for value!?!?\"); \n output_vbr((unsigned)Slot, Out);\n\n \/\/ Output a dummy field to fill Arg#2 in the reader that is currently unused\n \/\/ for varargs calls. This is a gross hack to make the code simpler, but we\n \/\/ aren't really doing very small bytecode for varargs calls anyways.\n \/\/ FIXME in the future: Smaller bytecode for varargs calls\n output_vbr(0, Out);\n\n for (unsigned i = 1; i < NumArgs; ++i) {\n \/\/ Output Arg Type ID\n Slot = Table.getValSlot(I->getOperand(i)->getType());\n assert(Slot >= 0 && \"No slot number for value!?!?\"); \n output_vbr((unsigned)Slot, Out);\n\n \/\/ Output arg ID itself\n Slot = Table.getValSlot(I->getOperand(i));\n assert(Slot >= 0 && \"No slot number for value!?!?\"); \n output_vbr((unsigned)Slot, Out);\n }\n align32(Out); \/\/ We must maintain correct alignment!\n}\n\n\n\/\/ outputInstructionFormat1 - Output one operand instructions, knowing that no\n\/\/ operand index is >= 2^12.\n\/\/\nstatic void outputInstructionFormat1(const Instruction *I, \n\t\t\t\t const SlotCalculator &Table, int *Slots,\n\t\t\t\t unsigned Type, std::deque<uchar> &Out) {\n unsigned Opcode = I->getOpcode(); \/\/ Instruction Opcode ID\n \n \/\/ bits Instruction format:\n \/\/ --------------------------\n \/\/ 01-00: Opcode type, fixed to 1.\n \/\/ 07-02: Opcode\n \/\/ 19-08: Resulting type plane\n \/\/ 31-20: Operand #1 (if set to (2^12-1), then zero operands)\n \/\/\n unsigned Bits = 1 | (Opcode << 2) | (Type << 8) | (Slots[0] << 20);\n \/\/ cerr << \"1 \" << IType << \" \" << Type << \" \" << Slots[0] << endl;\n output(Bits, Out);\n}\n\n\n\/\/ outputInstructionFormat2 - Output two operand instructions, knowing that no\n\/\/ operand index is >= 2^8.\n\/\/\nstatic void outputInstructionFormat2(const Instruction *I, \n\t\t\t\t const SlotCalculator &Table, int *Slots,\n\t\t\t\t unsigned Type, std::deque<uchar> &Out) {\n unsigned Opcode = I->getOpcode(); \/\/ Instruction Opcode ID\n\n \/\/ bits Instruction format:\n \/\/ --------------------------\n \/\/ 01-00: Opcode type, fixed to 2.\n \/\/ 07-02: Opcode\n \/\/ 15-08: Resulting type plane\n \/\/ 23-16: Operand #1\n \/\/ 31-24: Operand #2 \n \/\/\n unsigned Bits = 2 | (Opcode << 2) | (Type << 8) |\n (Slots[0] << 16) | (Slots[1] << 24);\n \/\/ cerr << \"2 \" << IType << \" \" << Type << \" \" << Slots[0] << \" \" \n \/\/ << Slots[1] << endl;\n output(Bits, Out);\n}\n\n\n\/\/ outputInstructionFormat3 - Output three operand instructions, knowing that no\n\/\/ operand index is >= 2^6.\n\/\/\nstatic void outputInstructionFormat3(const Instruction *I, \n\t\t\t\t const SlotCalculator &Table, int *Slots,\n\t\t\t\t unsigned Type, std::deque<uchar> &Out) {\n unsigned Opcode = I->getOpcode(); \/\/ Instruction Opcode ID\n\n \/\/ bits Instruction format:\n \/\/ --------------------------\n \/\/ 01-00: Opcode type, fixed to 3.\n \/\/ 07-02: Opcode\n \/\/ 13-08: Resulting type plane\n \/\/ 19-14: Operand #1\n \/\/ 25-20: Operand #2\n \/\/ 31-26: Operand #3\n \/\/\n unsigned Bits = 3 | (Opcode << 2) | (Type << 8) |\n (Slots[0] << 14) | (Slots[1] << 20) | (Slots[2] << 26);\n \/\/cerr << \"3 \" << IType << \" \" << Type << \" \" << Slots[0] << \" \" \n \/\/ << Slots[1] << \" \" << Slots[2] << endl;\n output(Bits, Out);\n}\n\nvoid BytecodeWriter::processInstruction(const Instruction *I) {\n assert(I->getOpcode() < 64 && \"Opcode too big???\");\n\n unsigned NumOperands = I->getNumOperands();\n int MaxOpSlot = 0;\n int Slots[3]; Slots[0] = (1 << 12)-1; \/\/ Marker to signify 0 operands\n\n for (unsigned i = 0; i < NumOperands; ++i) {\n const Value *Def = I->getOperand(i);\n int slot = Table.getValSlot(Def);\n assert(slot != -1 && \"Broken bytecode!\");\n if (slot > MaxOpSlot) MaxOpSlot = slot;\n if (i < 3) Slots[i] = slot;\n }\n\n \/\/ Figure out which type to encode with the instruction. Typically we want\n \/\/ the type of the first parameter, as opposed to the type of the instruction\n \/\/ (for example, with setcc, we always know it returns bool, but the type of\n \/\/ the first param is actually interesting). But if we have no arguments\n \/\/ we take the type of the instruction itself. \n \/\/\n const Type *Ty;\n switch (I->getOpcode()) {\n case Instruction::Malloc:\n case Instruction::Alloca:\n Ty = I->getType(); \/\/ Malloc & Alloca ALWAYS want to encode the return type\n break;\n case Instruction::Store:\n Ty = I->getOperand(1)->getType(); \/\/ Encode the pointer type...\n assert(isa<PointerType>(Ty) && \"Store to nonpointer type!?!?\");\n break;\n default: \/\/ Otherwise use the default behavior...\n Ty = NumOperands ? I->getOperand(0)->getType() : I->getType();\n break;\n }\n\n unsigned Type;\n int Slot = Table.getValSlot(Ty);\n assert(Slot != -1 && \"Type not available!!?!\");\n Type = (unsigned)Slot;\n\n \/\/ Make sure that we take the type number into consideration. We don't want\n \/\/ to overflow the field size for the instruction format we select.\n \/\/\n if (Slot > MaxOpSlot) MaxOpSlot = Slot;\n\n \/\/ Handle the special case for cast...\n if (isa<CastInst>(I)) {\n \/\/ Cast has to encode the destination type as the second argument in the\n \/\/ packet, or else we won't know what type to cast to!\n Slots[1] = Table.getValSlot(I->getType());\n assert(Slots[1] != -1 && \"Cast return type unknown?\");\n if (Slots[1] > MaxOpSlot) MaxOpSlot = Slots[1];\n NumOperands++;\n } else if (const CallInst *CI = dyn_cast<CallInst>(I)) {\/\/ Handle VarArg calls\n PointerType *Ty = cast<PointerType>(CI->getCalledValue()->getType());\n if (cast<FunctionType>(Ty->getElementType())->isVarArg()) {\n outputInstrVarArgsCall(I, Table, Type, Out);\n return;\n }\n } else if (const InvokeInst *II = dyn_cast<InvokeInst>(I)) { \/\/ ... & Invokes\n PointerType *Ty = cast<PointerType>(II->getCalledValue()->getType());\n if (cast<FunctionType>(Ty->getElementType())->isVarArg()) {\n outputInstrVarArgsCall(I, Table, Type, Out);\n return;\n }\n }\n\n \/\/ Decide which instruction encoding to use. This is determined primarily by\n \/\/ the number of operands, and secondarily by whether or not the max operand\n \/\/ will fit into the instruction encoding. More operands == fewer bits per\n \/\/ operand.\n \/\/\n switch (NumOperands) {\n case 0:\n case 1:\n if (MaxOpSlot < (1 << 12)-1) { \/\/ -1 because we use 4095 to indicate 0 ops\n outputInstructionFormat1(I, Table, Slots, Type, Out);\n return;\n }\n break;\n\n case 2:\n if (MaxOpSlot < (1 << 8)) {\n outputInstructionFormat2(I, Table, Slots, Type, Out);\n return;\n }\n break;\n\n case 3:\n if (MaxOpSlot < (1 << 6)) {\n outputInstructionFormat3(I, Table, Slots, Type, Out);\n return;\n }\n break;\n }\n\n \/\/ If we weren't handled before here, we either have a large number of\n \/\/ operands or a large operand index that we are refering to.\n outputInstructionFormat0(I, Table, Type, Out);\n}\n<commit_msg>Fix constness problem<commit_after>\/\/===-- WriteInst.cpp - Functions for writing instructions -------*- C++ -*--=\/\/\n\/\/\n\/\/ This file implements the routines for encoding instruction opcodes to a \n\/\/ bytecode stream.\n\/\/\n\/\/ Note that the performance of this library is not terribly important, because\n\/\/ it shouldn't be used by JIT type applications... so it is not a huge focus\n\/\/ at least. :)\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"WriterInternals.h\"\n#include \"llvm\/Module.h\"\n#include \"llvm\/Function.h\"\n#include \"llvm\/BasicBlock.h\"\n#include \"llvm\/DerivedTypes.h\"\n#include \"llvm\/iOther.h\"\n#include \"llvm\/iTerminators.h\"\n#include <algorithm>\n\ntypedef unsigned char uchar;\n\n\/\/ outputInstructionFormat0 - Output those wierd instructions that have a large\n\/\/ number of operands or have large operands themselves...\n\/\/\n\/\/ Format: [opcode] [type] [numargs] [arg0] [arg1] ... [arg<numargs-1>]\n\/\/\nstatic void outputInstructionFormat0(const Instruction *I,\n\t\t\t\t const SlotCalculator &Table,\n\t\t\t\t unsigned Type, std::deque<uchar> &Out) {\n \/\/ Opcode must have top two bits clear...\n output_vbr(I->getOpcode() << 2, Out); \/\/ Instruction Opcode ID\n output_vbr(Type, Out); \/\/ Result type\n\n unsigned NumArgs = I->getNumOperands();\n output_vbr(NumArgs + isa<CastInst>(I), Out);\n\n for (unsigned i = 0; i < NumArgs; ++i) {\n int Slot = Table.getValSlot(I->getOperand(i));\n assert(Slot >= 0 && \"No slot number for value!?!?\"); \n output_vbr((unsigned)Slot, Out);\n }\n\n if (isa<CastInst>(I)) {\n int Slot = Table.getValSlot(I->getType());\n assert(Slot != -1 && \"Cast return type unknown?\");\n output_vbr((unsigned)Slot, Out);\n }\n\n align32(Out); \/\/ We must maintain correct alignment!\n}\n\n\n\/\/ outputInstrVarArgsCall - Output the obsurdly annoying varargs function calls.\n\/\/ This are more annoying than most because the signature of the call does not\n\/\/ tell us anything about the types of the arguments in the varargs portion.\n\/\/ Because of this, we encode (as type 0) all of the argument types explicitly\n\/\/ before the argument value. This really sucks, but you shouldn't be using\n\/\/ varargs functions in your code! *death to printf*!\n\/\/\n\/\/ Format: [opcode] [type] [numargs] [arg0] [arg1] ... [arg<numargs-1>]\n\/\/\nstatic void outputInstrVarArgsCall(const Instruction *I,\n\t\t\t\t const SlotCalculator &Table, unsigned Type,\n\t\t\t\t std::deque<uchar> &Out) {\n assert(isa<CallInst>(I) || isa<InvokeInst>(I));\n \/\/ Opcode must have top two bits clear...\n output_vbr(I->getOpcode() << 2, Out); \/\/ Instruction Opcode ID\n output_vbr(Type, Out); \/\/ Result type (varargs type)\n\n unsigned NumArgs = I->getNumOperands();\n output_vbr(NumArgs*2, Out);\n \/\/ TODO: Don't need to emit types for the fixed types of the varargs function\n \/\/ prototype...\n\n \/\/ The type for the function has already been emitted in the type field of the\n \/\/ instruction. Just emit the slot # now.\n int Slot = Table.getValSlot(I->getOperand(0));\n assert(Slot >= 0 && \"No slot number for value!?!?\"); \n output_vbr((unsigned)Slot, Out);\n\n \/\/ Output a dummy field to fill Arg#2 in the reader that is currently unused\n \/\/ for varargs calls. This is a gross hack to make the code simpler, but we\n \/\/ aren't really doing very small bytecode for varargs calls anyways.\n \/\/ FIXME in the future: Smaller bytecode for varargs calls\n output_vbr(0, Out);\n\n for (unsigned i = 1; i < NumArgs; ++i) {\n \/\/ Output Arg Type ID\n Slot = Table.getValSlot(I->getOperand(i)->getType());\n assert(Slot >= 0 && \"No slot number for value!?!?\"); \n output_vbr((unsigned)Slot, Out);\n\n \/\/ Output arg ID itself\n Slot = Table.getValSlot(I->getOperand(i));\n assert(Slot >= 0 && \"No slot number for value!?!?\"); \n output_vbr((unsigned)Slot, Out);\n }\n align32(Out); \/\/ We must maintain correct alignment!\n}\n\n\n\/\/ outputInstructionFormat1 - Output one operand instructions, knowing that no\n\/\/ operand index is >= 2^12.\n\/\/\nstatic void outputInstructionFormat1(const Instruction *I, \n\t\t\t\t const SlotCalculator &Table, int *Slots,\n\t\t\t\t unsigned Type, std::deque<uchar> &Out) {\n unsigned Opcode = I->getOpcode(); \/\/ Instruction Opcode ID\n \n \/\/ bits Instruction format:\n \/\/ --------------------------\n \/\/ 01-00: Opcode type, fixed to 1.\n \/\/ 07-02: Opcode\n \/\/ 19-08: Resulting type plane\n \/\/ 31-20: Operand #1 (if set to (2^12-1), then zero operands)\n \/\/\n unsigned Bits = 1 | (Opcode << 2) | (Type << 8) | (Slots[0] << 20);\n \/\/ cerr << \"1 \" << IType << \" \" << Type << \" \" << Slots[0] << endl;\n output(Bits, Out);\n}\n\n\n\/\/ outputInstructionFormat2 - Output two operand instructions, knowing that no\n\/\/ operand index is >= 2^8.\n\/\/\nstatic void outputInstructionFormat2(const Instruction *I, \n\t\t\t\t const SlotCalculator &Table, int *Slots,\n\t\t\t\t unsigned Type, std::deque<uchar> &Out) {\n unsigned Opcode = I->getOpcode(); \/\/ Instruction Opcode ID\n\n \/\/ bits Instruction format:\n \/\/ --------------------------\n \/\/ 01-00: Opcode type, fixed to 2.\n \/\/ 07-02: Opcode\n \/\/ 15-08: Resulting type plane\n \/\/ 23-16: Operand #1\n \/\/ 31-24: Operand #2 \n \/\/\n unsigned Bits = 2 | (Opcode << 2) | (Type << 8) |\n (Slots[0] << 16) | (Slots[1] << 24);\n \/\/ cerr << \"2 \" << IType << \" \" << Type << \" \" << Slots[0] << \" \" \n \/\/ << Slots[1] << endl;\n output(Bits, Out);\n}\n\n\n\/\/ outputInstructionFormat3 - Output three operand instructions, knowing that no\n\/\/ operand index is >= 2^6.\n\/\/\nstatic void outputInstructionFormat3(const Instruction *I, \n\t\t\t\t const SlotCalculator &Table, int *Slots,\n\t\t\t\t unsigned Type, std::deque<uchar> &Out) {\n unsigned Opcode = I->getOpcode(); \/\/ Instruction Opcode ID\n\n \/\/ bits Instruction format:\n \/\/ --------------------------\n \/\/ 01-00: Opcode type, fixed to 3.\n \/\/ 07-02: Opcode\n \/\/ 13-08: Resulting type plane\n \/\/ 19-14: Operand #1\n \/\/ 25-20: Operand #2\n \/\/ 31-26: Operand #3\n \/\/\n unsigned Bits = 3 | (Opcode << 2) | (Type << 8) |\n (Slots[0] << 14) | (Slots[1] << 20) | (Slots[2] << 26);\n \/\/cerr << \"3 \" << IType << \" \" << Type << \" \" << Slots[0] << \" \" \n \/\/ << Slots[1] << \" \" << Slots[2] << endl;\n output(Bits, Out);\n}\n\nvoid BytecodeWriter::processInstruction(const Instruction *I) {\n assert(I->getOpcode() < 64 && \"Opcode too big???\");\n\n unsigned NumOperands = I->getNumOperands();\n int MaxOpSlot = 0;\n int Slots[3]; Slots[0] = (1 << 12)-1; \/\/ Marker to signify 0 operands\n\n for (unsigned i = 0; i < NumOperands; ++i) {\n const Value *Def = I->getOperand(i);\n int slot = Table.getValSlot(Def);\n assert(slot != -1 && \"Broken bytecode!\");\n if (slot > MaxOpSlot) MaxOpSlot = slot;\n if (i < 3) Slots[i] = slot;\n }\n\n \/\/ Figure out which type to encode with the instruction. Typically we want\n \/\/ the type of the first parameter, as opposed to the type of the instruction\n \/\/ (for example, with setcc, we always know it returns bool, but the type of\n \/\/ the first param is actually interesting). But if we have no arguments\n \/\/ we take the type of the instruction itself. \n \/\/\n const Type *Ty;\n switch (I->getOpcode()) {\n case Instruction::Malloc:\n case Instruction::Alloca:\n Ty = I->getType(); \/\/ Malloc & Alloca ALWAYS want to encode the return type\n break;\n case Instruction::Store:\n Ty = I->getOperand(1)->getType(); \/\/ Encode the pointer type...\n assert(isa<PointerType>(Ty) && \"Store to nonpointer type!?!?\");\n break;\n default: \/\/ Otherwise use the default behavior...\n Ty = NumOperands ? I->getOperand(0)->getType() : I->getType();\n break;\n }\n\n unsigned Type;\n int Slot = Table.getValSlot(Ty);\n assert(Slot != -1 && \"Type not available!!?!\");\n Type = (unsigned)Slot;\n\n \/\/ Make sure that we take the type number into consideration. We don't want\n \/\/ to overflow the field size for the instruction format we select.\n \/\/\n if (Slot > MaxOpSlot) MaxOpSlot = Slot;\n\n \/\/ Handle the special case for cast...\n if (isa<CastInst>(I)) {\n \/\/ Cast has to encode the destination type as the second argument in the\n \/\/ packet, or else we won't know what type to cast to!\n Slots[1] = Table.getValSlot(I->getType());\n assert(Slots[1] != -1 && \"Cast return type unknown?\");\n if (Slots[1] > MaxOpSlot) MaxOpSlot = Slots[1];\n NumOperands++;\n } else if (const CallInst *CI = dyn_cast<CallInst>(I)) {\/\/ Handle VarArg calls\n const PointerType *Ty = cast<PointerType>(CI->getCalledValue()->getType());\n if (cast<FunctionType>(Ty->getElementType())->isVarArg()) {\n outputInstrVarArgsCall(I, Table, Type, Out);\n return;\n }\n } else if (const InvokeInst *II = dyn_cast<InvokeInst>(I)) { \/\/ ... & Invokes\n const PointerType *Ty = cast<PointerType>(II->getCalledValue()->getType());\n if (cast<FunctionType>(Ty->getElementType())->isVarArg()) {\n outputInstrVarArgsCall(I, Table, Type, Out);\n return;\n }\n }\n\n \/\/ Decide which instruction encoding to use. This is determined primarily by\n \/\/ the number of operands, and secondarily by whether or not the max operand\n \/\/ will fit into the instruction encoding. More operands == fewer bits per\n \/\/ operand.\n \/\/\n switch (NumOperands) {\n case 0:\n case 1:\n if (MaxOpSlot < (1 << 12)-1) { \/\/ -1 because we use 4095 to indicate 0 ops\n outputInstructionFormat1(I, Table, Slots, Type, Out);\n return;\n }\n break;\n\n case 2:\n if (MaxOpSlot < (1 << 8)) {\n outputInstructionFormat2(I, Table, Slots, Type, Out);\n return;\n }\n break;\n\n case 3:\n if (MaxOpSlot < (1 << 6)) {\n outputInstructionFormat3(I, Table, Slots, Type, Out);\n return;\n }\n break;\n }\n\n \/\/ If we weren't handled before here, we either have a large number of\n \/\/ operands or a large operand index that we are refering to.\n outputInstructionFormat0(I, Table, Type, Out);\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"instrumentation_factories.h\"\n\n#include <complex>\n#include <vector>\n\n#include <deal.II\/base\/conditional_ostream.h>\n\n#include \"convergence\/status.h\"\n#include \"instrumentation\/basic_instrument.h\"\n#include \"instrumentation\/instrument.h\"\n#include \"instrumentation\/converter\/convergence_to_string.h\"\n#include \"instrumentation\/converter\/int_vector_complex_pair_to_string.h\"\n#include \"instrumentation\/converter\/int_double_pair_to_string.h\"\n#include \"instrumentation\/converter\/string_color_pair_to_string.h\"\n#include \"instrumentation\/outstream\/to_conditional_ostream.h\"\n#include \"instrumentation\/outstream\/to_ostream.h\"\n#include \"utility\/colors.h\"\n\nnamespace bart {\n\nnamespace instrumentation {\n\nnamespace factory {\n\ntemplate<typename InputType>\nstd::unique_ptr<InstrumentType<InputType>> MakeBasicInstrument(std::unique_ptr<\n OutstreamType<InputType>> outstream_ptr_) {\n using ReturnType = instrumentation::BasicInstrument<InputType>;\n return std::make_unique<ReturnType>(std::move(outstream_ptr_));\n}\n\n\/\/ MAKE CONVERTER ==============================================================\n\ntemplate <>\nstd::unique_ptr<ConverterType<convergence::Status, std::string>>\nMakeConverter<convergence::Status, std::string>() {\n using ReturnType = instrumentation::converter::ConvergenceToString;\n return std::make_unique<ReturnType>();\n}\n\ntemplate <>\nauto MakeConverter<std::pair<int, std::vector<std::complex<double>>>, std::string, int> (const int precision)\n-> std::unique_ptr<ConverterType<std::pair<int, std::vector<std::complex<double>>>, std::string>>{\n using ReturnType = instrumentation::converter::IntVectorComplexPairToString;\n auto return_ptr = std::make_unique<ReturnType>();\n return_ptr->set_precision(precision);\n return return_ptr;\n}\n\ntemplate <>\nstd::unique_ptr<ConverterType<std::pair<int, double>, std::string>>\nMakeConverter<std::pair<int, double>, std::string, int>(const int precision) {\n using ReturnType = instrumentation::converter::IntDoublePairToString;\n auto return_ptr = std::make_unique<ReturnType>();\n return_ptr->set_precision(precision);\n return return_ptr;\n}\n\ntemplate <>\nstd::unique_ptr<ConverterType<std::pair<std::string, utility::Color>, std::string>>\nMakeConverter<std::pair<std::string, utility::Color>, std::string>() {\n using ReturnType = instrumentation::converter::StringColorPairToString;\n auto return_ptr = std::make_unique<ReturnType>();\n return return_ptr;\n}\n\n\/\/ MAKE INSTRUMENT =============================================================\n\ntemplate <typename InputType, typename OutputType>\nstd::unique_ptr<InstrumentType<InputType>> MakeInstrument(\n std::unique_ptr<ConverterType<InputType, OutputType>> converter_ptr_,\n std::unique_ptr<OutstreamType<OutputType>> outstream_ptr_) {\n using ReturnType = instrumentation::Instrument<InputType, OutputType>;\n return std::make_unique<ReturnType>(std::move(converter_ptr_),\n std::move(outstream_ptr_));\n}\n\n\/\/ MAKE OUTSTREAM ==============================================================\n\ntemplate <>\nstd::unique_ptr<OutstreamType<std::string>>\nMakeOutstream<std::string, std::unique_ptr<dealii::ConditionalOStream>>(\n std::unique_ptr<dealii::ConditionalOStream> conditional_ostream_ptr) {\n using ReturnType = instrumentation::outstream::ToConditionalOstream;\n return std::make_unique<ReturnType>(std::move(conditional_ostream_ptr));\n}\n\ntemplate <>\nstd::unique_ptr<OutstreamType<std::string>>\nMakeOutstream<std::string, std::unique_ptr<std::ostream>>(\n std::unique_ptr<std::ostream> ostream_ptr) {\n using ReturnType = instrumentation::outstream::ToOstream;\n return std::make_unique<ReturnType>(std::move(ostream_ptr));\n}\n\ntemplate std::unique_ptr<InstrumentType<convergence::Status>> MakeInstrument(std::unique_ptr<ConverterType<convergence::Status, std::string>>, std::unique_ptr<OutstreamType<std::string>>);\ntemplate std::unique_ptr<InstrumentType<std::pair<int, double>>> MakeInstrument(std::unique_ptr<ConverterType<std::pair<int, double>, std::string>>, std::unique_ptr<OutstreamType<std::string>>);\ntemplate std::unique_ptr<InstrumentType<std::pair<std::string, utility::Color>>> MakeInstrument(std::unique_ptr<ConverterType<std::pair<std::string, utility::Color>, std::string>>, std::unique_ptr<OutstreamType<std::string>>);\ntemplate std::unique_ptr<InstrumentType<std::string>> MakeBasicInstrument(std::unique_ptr<OutstreamType<std::string>>);\n\n} \/\/ namespace factory\n\n} \/\/ namespace instrumentation\n\n} \/\/ namespace bart\n<commit_msg>Added some aliases to make converter factory functions easier to read.<commit_after>#include \"instrumentation_factories.h\"\n\n#include <complex>\n#include <vector>\n\n#include <deal.II\/base\/conditional_ostream.h>\n\n#include \"convergence\/status.h\"\n#include \"instrumentation\/basic_instrument.h\"\n#include \"instrumentation\/instrument.h\"\n#include \"instrumentation\/converter\/convergence_to_string.h\"\n#include \"instrumentation\/converter\/int_vector_complex_pair_to_string.h\"\n#include \"instrumentation\/converter\/int_double_pair_to_string.h\"\n#include \"instrumentation\/converter\/string_color_pair_to_string.h\"\n#include \"instrumentation\/outstream\/to_conditional_ostream.h\"\n#include \"instrumentation\/outstream\/to_ostream.h\"\n#include \"utility\/colors.h\"\n\nnamespace bart {\n\nnamespace instrumentation {\n\nnamespace factory {\n\n\ntemplate<typename InputType>\nstd::unique_ptr<InstrumentType<InputType>> MakeBasicInstrument(std::unique_ptr<\n OutstreamType<InputType>> outstream_ptr_) {\n using ReturnType = instrumentation::BasicInstrument<InputType>;\n return std::make_unique<ReturnType>(std::move(outstream_ptr_));\n}\n\n\/\/ MAKE CONVERTER ==============================================================\n\nnamespace {\n \/\/ types used by converters\nusing IntComplexVectorPair = std::pair<int, std::vector<std::complex<double>>>;\nusing IntDoublePair = std::pair<int, double>;\nusing StringColorPair = std::pair<std::string, utility::Color>;\n\ntemplate <typename InputType>\nusing ConvertThisToStringPtr = std::unique_ptr<ConverterType<InputType, std::string>>;\n} \/\/ namespace\n\ntemplate <>\nstd::unique_ptr<ConverterType<convergence::Status, std::string>>\nMakeConverter<convergence::Status, std::string>() {\n using ReturnType = instrumentation::converter::ConvergenceToString;\n return std::make_unique<ReturnType>();\n}\n\ntemplate <>\nauto MakeConverter<IntComplexVectorPair, std::string, int> (const int precision)\n-> ConvertThisToStringPtr<IntComplexVectorPair> {\n using ReturnType = instrumentation::converter::IntVectorComplexPairToString;\n auto return_ptr = std::make_unique<ReturnType>();\n return_ptr->set_precision(precision);\n return return_ptr;\n}\n\ntemplate <>\nConvertThisToStringPtr<IntDoublePair>\nMakeConverter<IntDoublePair, std::string, int>(const int precision) {\n using ReturnType = instrumentation::converter::IntDoublePairToString;\n auto return_ptr = std::make_unique<ReturnType>();\n return_ptr->set_precision(precision);\n return return_ptr;\n}\n\ntemplate <>\nConvertThisToStringPtr<StringColorPair>\nMakeConverter<StringColorPair, std::string>() {\n using ReturnType = instrumentation::converter::StringColorPairToString;\n auto return_ptr = std::make_unique<ReturnType>();\n return return_ptr;\n}\n\n\/\/ MAKE INSTRUMENT =============================================================\n\ntemplate <typename InputType, typename OutputType>\nstd::unique_ptr<InstrumentType<InputType>> MakeInstrument(\n std::unique_ptr<ConverterType<InputType, OutputType>> converter_ptr_,\n std::unique_ptr<OutstreamType<OutputType>> outstream_ptr_) {\n using ReturnType = instrumentation::Instrument<InputType, OutputType>;\n return std::make_unique<ReturnType>(std::move(converter_ptr_),\n std::move(outstream_ptr_));\n}\n\n\/\/ MAKE OUTSTREAM ==============================================================\n\ntemplate <>\nstd::unique_ptr<OutstreamType<std::string>>\nMakeOutstream<std::string, std::unique_ptr<dealii::ConditionalOStream>>(\n std::unique_ptr<dealii::ConditionalOStream> conditional_ostream_ptr) {\n using ReturnType = instrumentation::outstream::ToConditionalOstream;\n return std::make_unique<ReturnType>(std::move(conditional_ostream_ptr));\n}\n\ntemplate <>\nstd::unique_ptr<OutstreamType<std::string>>\nMakeOutstream<std::string, std::unique_ptr<std::ostream>>(\n std::unique_ptr<std::ostream> ostream_ptr) {\n using ReturnType = instrumentation::outstream::ToOstream;\n return std::make_unique<ReturnType>(std::move(ostream_ptr));\n}\n\ntemplate std::unique_ptr<InstrumentType<convergence::Status>> MakeInstrument(std::unique_ptr<ConverterType<convergence::Status, std::string>>, std::unique_ptr<OutstreamType<std::string>>);\ntemplate std::unique_ptr<InstrumentType<std::pair<int, double>>> MakeInstrument(std::unique_ptr<ConverterType<std::pair<int, double>, std::string>>, std::unique_ptr<OutstreamType<std::string>>);\ntemplate std::unique_ptr<InstrumentType<std::pair<std::string, utility::Color>>> MakeInstrument(std::unique_ptr<ConverterType<std::pair<std::string, utility::Color>, std::string>>, std::unique_ptr<OutstreamType<std::string>>);\ntemplate std::unique_ptr<InstrumentType<std::string>> MakeBasicInstrument(std::unique_ptr<OutstreamType<std::string>>);\n\n} \/\/ namespace factory\n\n} \/\/ namespace instrumentation\n\n} \/\/ namespace bart\n<|endoftext|>"} {"text":"<commit_before>\/***************************************************************************\n constraintactivitiesendstudentsdayform.cpp - description\n -------------------\n begin : 2008\n copyright : (C) 2008 by Lalescu Liviu\n email : Please see http:\/\/lalescu.ro\/liviu\/ for details about contacting Liviu Lalescu (in particular, you can find here the e-mail address)\n ***************************************************************************\/\n\n\/***************************************************************************\n * *\n * This program is free software: you can redistribute it and\/or modify *\n * it under the terms of the GNU Affero General Public License as *\n * published by the Free Software Foundation, either version 3 of the *\n * License, or (at your option) any later version. *\n * *\n ***************************************************************************\/\n\n#include \"constraintactivitiesendstudentsdayform.h\"\n#include \"addconstraintactivitiesendstudentsdayform.h\"\n#include \"modifyconstraintactivitiesendstudentsdayform.h\"\n\n#include <QListWidget>\n#include <QScrollBar>\n#include <QAbstractItemView>\n\nConstraintActivitiesEndStudentsDayForm::ConstraintActivitiesEndStudentsDayForm(QWidget* parent): ConstraintBaseDialog(parent)\n{\n\t\/\/: This is the title of the dialog to see the list of all constraints of this type\n\tsetWindowTitle(QCoreApplication::translate(\"ConstraintActivitiesEndStudentsDayForm_template\", \"Constraints activities end students day\"));\n\/\/\tpopulateFilters();\n\tfilterChanged();\n}\n\nbool ConstraintActivitiesEndStudentsDayForm::filterOk(const TimeConstraint* ctr) const\n{\n\tif(ctr->type==CONSTRAINT_ACTIVITIES_END_STUDENTS_DAY)\n\t\treturn true;\n\telse\n\t\treturn false;\n}\n\nQDialog * ConstraintActivitiesEndStudentsDayForm::createAddDialog()\n{\n\treturn new AddConstraintActivitiesEndStudentsDayForm(this);\n}\n\nQDialog * ConstraintActivitiesEndStudentsDayForm::createModifyDialog(TimeConstraint *ctr)\n{\n\treturn new ModifyConstraintActivitiesEndStudentsDayForm(this, (ConstraintActivitiesEndStudentsDay*)ctr);\n}\n<commit_msg>remove unused includes<commit_after>\/***************************************************************************\n constraintactivitiesendstudentsdayform.cpp - description\n -------------------\n begin : 2008\n copyright : (C) 2008 by Lalescu Liviu\n email : Please see http:\/\/lalescu.ro\/liviu\/ for details about contacting Liviu Lalescu (in particular, you can find here the e-mail address)\n ***************************************************************************\/\n\n\/***************************************************************************\n * *\n * This program is free software: you can redistribute it and\/or modify *\n * it under the terms of the GNU Affero General Public License as *\n * published by the Free Software Foundation, either version 3 of the *\n * License, or (at your option) any later version. *\n * *\n ***************************************************************************\/\n\n#include \"constraintactivitiesendstudentsdayform.h\"\n#include \"addconstraintactivitiesendstudentsdayform.h\"\n#include \"modifyconstraintactivitiesendstudentsdayform.h\"\n\nConstraintActivitiesEndStudentsDayForm::ConstraintActivitiesEndStudentsDayForm(QWidget* parent): ConstraintBaseDialog(parent)\n{\n\t\/\/: This is the title of the dialog to see the list of all constraints of this type\n\tsetWindowTitle(QCoreApplication::translate(\"ConstraintActivitiesEndStudentsDayForm_template\", \"Constraints activities end students day\"));\n\/\/\tpopulateFilters();\n\tfilterChanged();\n}\n\nbool ConstraintActivitiesEndStudentsDayForm::filterOk(const TimeConstraint* ctr) const\n{\n\tif(ctr->type==CONSTRAINT_ACTIVITIES_END_STUDENTS_DAY)\n\t\treturn true;\n\telse\n\t\treturn false;\n}\n\nQDialog * ConstraintActivitiesEndStudentsDayForm::createAddDialog()\n{\n\treturn new AddConstraintActivitiesEndStudentsDayForm(this);\n}\n\nQDialog * ConstraintActivitiesEndStudentsDayForm::createModifyDialog(TimeConstraint *ctr)\n{\n\treturn new ModifyConstraintActivitiesEndStudentsDayForm(this, (ConstraintActivitiesEndStudentsDay*)ctr);\n}\n<|endoftext|>"} {"text":"<commit_before>#include <Core\/Tasks\/Task.hpp>\n#include <Core\/Tasks\/TaskQueue.hpp>\n\n#include <algorithm>\n#include <iostream>\n#include <stack>\n\nnamespace Ra {\nnamespace Core {\n\nTaskQueue::TaskQueue( uint numThreads ) : m_processingTasks( 0 ), m_shuttingDown( false ) {\n CORE_ASSERT( numThreads > 0, \" You need at least one thread\" );\n m_workerThreads.reserve( numThreads );\n for ( uint i = 0; i < numThreads; ++i )\n {\n m_workerThreads.emplace_back( &TaskQueue::runThread, this, i );\n }\n}\n\nTaskQueue::~TaskQueue() {\n flushTaskQueue();\n m_shuttingDown = true;\n m_threadNotifier.notify_all();\n for ( auto& t : m_workerThreads )\n {\n t.join();\n }\n}\n\nTaskQueue::TaskId TaskQueue::registerTask( Task* task ) {\n m_tasks.emplace_back( std::unique_ptr<Task>( task ) );\n m_dependencies.push_back( std::vector<TaskId>() );\n m_remainingDependencies.push_back( 0 );\n TimerData tdata;\n tdata.taskName = task->getName();\n m_timerData.push_back( tdata );\n\n CORE_ASSERT( m_tasks.size() == m_dependencies.size(), \"Inconsistent task list\" );\n CORE_ASSERT( m_tasks.size() == m_remainingDependencies.size(), \"Inconsistent task list\" );\n CORE_ASSERT( m_tasks.size() == m_timerData.size(), \"Inconsistent task list\" );\n return TaskId( m_tasks.size() - 1 );\n}\n\nvoid TaskQueue::addDependency( TaskQueue::TaskId predecessor, TaskQueue::TaskId successor ) {\n CORE_ASSERT( predecessor.isValid() && ( predecessor < m_tasks.size() ),\n \"Invalid predecessor task\" );\n CORE_ASSERT( successor.isValid() && ( successor < m_tasks.size() ), \"Invalid successor task\" );\n CORE_ASSERT( predecessor != successor, \"Cannot add self-dependency\" );\n\n CORE_ASSERT( std::find( m_dependencies[predecessor].begin(),\n m_dependencies[predecessor].end(),\n successor ) == m_dependencies[predecessor].end(),\n \"Cannot add a dependency twice\" );\n\n m_dependencies[predecessor].push_back( successor );\n ++m_remainingDependencies[successor];\n}\n\nbool TaskQueue::addDependency( const std::string& predecessors, TaskQueue::TaskId successor ) {\n bool added = false;\n for ( uint i = 0; i < m_tasks.size(); ++i )\n {\n if ( m_tasks[i]->getName() == predecessors )\n {\n added = true;\n addDependency( TaskId( i ), successor );\n }\n }\n return added;\n}\n\nbool TaskQueue::addDependency( TaskQueue::TaskId predecessor, const std::string& successors ) {\n bool added = false;\n for ( uint i = 0; i < m_tasks.size(); ++i )\n {\n if ( m_tasks[i]->getName() == successors )\n {\n added = true;\n addDependency( predecessor, TaskId( i ) );\n }\n }\n return added;\n}\n\nvoid TaskQueue::addPendingDependency( const std::string& predecessors,\n TaskQueue::TaskId successor ) {\n m_pendingDepsSucc.emplace_back( predecessors, successor );\n}\n\nvoid TaskQueue::addPendingDependency( TaskId predecessor, const std::string& successors ) {\n m_pendingDepsPre.emplace_back( predecessor, successors );\n}\n\nvoid TaskQueue::resolveDependencies() {\n for ( const auto& pre : m_pendingDepsPre )\n {\n ON_ASSERT( bool result = ) addDependency( pre.first, pre.second );\n CORE_WARN_IF( !result,\n \"Pending dependency unresolved : \" << m_tasks[pre.first]->getName() << \" -> (\"\n << pre.second << \")\" );\n }\n for ( const auto& pre : m_pendingDepsSucc )\n {\n ON_ASSERT( bool result = ) addDependency( pre.first, pre.second );\n CORE_WARN_IF( !result,\n \"Pending dependency unresolved : (\" << pre.first << \") -> \"\n << m_tasks[pre.second]->getName() );\n }\n m_pendingDepsPre.clear();\n m_pendingDepsSucc.clear();\n}\n\nvoid TaskQueue::queueTask( TaskQueue::TaskId task ) {\n CORE_ASSERT( m_remainingDependencies[task] == 0,\n \" Task\" << m_tasks[task]->getName() << \"has unmet dependencies\" );\n m_taskQueue.push_front( task );\n}\n\nvoid TaskQueue::detectCycles() {\n#if defined( CORE_DEBUG )\n \/\/ Do a depth-first search of the nodes.\n std::vector<bool> visited( m_tasks.size(), false );\n std::stack<TaskId> pending;\n\n for ( uint id = 0; id < m_tasks.size(); ++id )\n {\n if ( m_dependencies[id].size() == 0 ) { pending.push( TaskId( id ) ); }\n }\n\n \/\/ If you hit this assert, there are tasks in the list but\n \/\/ all tasks have dependencies so no task can start.\n CORE_ASSERT( m_tasks.empty() || !pending.empty(), \"No free tasks.\" );\n\n while ( !pending.empty() )\n {\n TaskId id = pending.top();\n pending.pop();\n\n \/\/ The task has already been visited. It means there is a cycle in the task graph.\n CORE_ASSERT( !( visited[id] ), \"Cycle detected in tasks !\" );\n\n visited[id] = true;\n for ( const auto& dep : m_dependencies[id] )\n {\n pending.push( dep );\n }\n }\n#endif\n}\n\nvoid TaskQueue::startTasks() {\n \/\/ Add pending dependencies.\n resolveDependencies();\n\n \/\/ Do a debug check\n detectCycles();\n\n \/\/ Enqueue all tasks with no dependencies.\n for ( uint t = 0; t < m_tasks.size(); ++t )\n {\n if ( m_remainingDependencies[t] == 0 ) { queueTask( TaskId( t ) ); }\n }\n\n \/\/ Wake up all threads.\n m_threadNotifier.notify_all();\n}\n\nvoid TaskQueue::waitForTasks() {\n bool isFinished = false;\n while ( !isFinished )\n {\n \/\/ TODO : use a notifier for task queue empty.\n m_taskQueueMutex.lock();\n isFinished = ( m_taskQueue.empty() && m_processingTasks == 0 );\n m_taskQueueMutex.unlock();\n if ( !isFinished ) { std::this_thread::yield(); }\n }\n}\n\nconst std::vector<TaskQueue::TimerData>& TaskQueue::getTimerData() {\n return m_timerData;\n}\n\nvoid TaskQueue::flushTaskQueue() {\n CORE_ASSERT( m_processingTasks == 0, \"You have tasks still in process\" );\n CORE_ASSERT( m_taskQueue.empty(), \" You have unprocessed tasks \" );\n m_tasks.clear();\n m_dependencies.clear();\n m_timerData.clear();\n m_remainingDependencies.clear();\n}\n\nvoid TaskQueue::runThread( uint id ) {\n while ( true )\n {\n TaskId task;\n\n \/\/ Acquire mutex.\n {\n std::unique_lock<std::mutex> lock( m_taskQueueMutex );\n\n \/\/ Wait for a new task\n \/\/ TODO : use the second form of wait()\n while ( !m_shuttingDown && m_taskQueue.empty() )\n {\n m_threadNotifier.wait( lock );\n }\n \/\/ If the task queue is shutting down we quit, releasing\n \/\/ the lock.\n if ( m_shuttingDown ) { return; }\n\n \/\/ If we are here it means we got a task\n task = m_taskQueue.back();\n m_taskQueue.pop_back();\n ++m_processingTasks;\n CORE_ASSERT( task.isValid() && task < m_tasks.size(), \"Invalid task\" );\n }\n \/\/ Release mutex.\n\n \/\/ Run task\n m_timerData[task].start = Utils::Clock::now();\n m_timerData[task].threadId = id;\n m_tasks[task]->process();\n m_timerData[task].end = Utils::Clock::now();\n\n \/\/ Critical section : mark task as finished and en-queue dependencies.\n uint newTasks = 0;\n {\n std::unique_lock<std::mutex> lock( m_taskQueueMutex );\n for ( auto t : m_dependencies[task] )\n {\n uint& nDepends = m_remainingDependencies[t];\n CORE_ASSERT( nDepends > 0, \"Inconsistency in dependencies\" );\n --nDepends;\n if ( nDepends == 0 )\n {\n queueTask( t );\n ++newTasks;\n }\n \/\/ TODO :Easy optimization : grab one of the new task and process it immediately.\n }\n --m_processingTasks;\n }\n \/\/ If we added new tasks, we wake up one thread to execute it.\n if ( newTasks > 0 ) { m_threadNotifier.notify_one(); }\n } \/\/ End of while(true)\n}\n\nvoid TaskQueue::printTaskGraph( std::ostream& output ) const {\n output << \"digraph tasks {\" << std::endl;\n\n for ( const auto& t : m_tasks )\n {\n output << \"\\\"\" << t->getName() << \"\\\"\" << std::endl;\n }\n\n for ( uint i = 0; i < m_dependencies.size(); ++i )\n {\n const auto& task1 = m_tasks[i];\n for ( const auto& dep : m_dependencies[i] )\n {\n const auto& task2 = m_tasks[dep];\n output << \"\\\"\" << task1->getName() << \"\\\"\"\n << \" -> \";\n output << \"\\\"\" << task2->getName() << \"\\\"\" << std::endl;\n }\n }\n\n for ( const auto& preDep : m_pendingDepsPre )\n {\n const auto& task1 = m_tasks[preDep.first];\n std::string t2name = preDep.second;\n\n if ( std::find_if( m_tasks.begin(), m_tasks.end(), [=]( const auto& task ) {\n return task->getName() == t2name;\n } ) == m_tasks.end() )\n { t2name += \"?\"; }\n output << \"\\\"\" << task1->getName() << \"\\\"\"\n << \" -> \";\n output << \"\\\"\" << t2name << \"\\\"\" << std::endl;\n }\n\n for ( const auto& postDep : m_pendingDepsSucc )\n {\n std::string t1name = postDep.first;\n const auto& t2 = m_tasks[postDep.second];\n\n if ( std::find_if( m_tasks.begin(), m_tasks.end(), [=]( const auto& task ) {\n return task->getName() == t1name;\n } ) == m_tasks.end() )\n { t1name += \"?\"; }\n output << \"\\\"\" << t1name << \"\\\"\"\n << \" -> \";\n output << \"\\\"\" << t2->getName() << \"\\\"\" << std::endl;\n }\n\n output << \"}\" << std::endl;\n}\n} \/\/ namespace Core\n} \/\/ namespace Ra\n<commit_msg>[core] fix access to potentially invalid ptr (from codacy).<commit_after>#include <Core\/Tasks\/Task.hpp>\n#include <Core\/Tasks\/TaskQueue.hpp>\n\n#include <algorithm>\n#include <iostream>\n#include <stack>\n\nnamespace Ra {\nnamespace Core {\n\nTaskQueue::TaskQueue( uint numThreads ) : m_processingTasks( 0 ), m_shuttingDown( false ) {\n CORE_ASSERT( numThreads > 0, \" You need at least one thread\" );\n m_workerThreads.reserve( numThreads );\n for ( uint i = 0; i < numThreads; ++i )\n {\n m_workerThreads.emplace_back( &TaskQueue::runThread, this, i );\n }\n}\n\nTaskQueue::~TaskQueue() {\n flushTaskQueue();\n m_shuttingDown = true;\n m_threadNotifier.notify_all();\n for ( auto& t : m_workerThreads )\n {\n t.join();\n }\n}\n\nTaskQueue::TaskId TaskQueue::registerTask( Task* task ) {\n TimerData tdata;\n \/\/ init tdata with task name before moving ownership\n tdata.taskName = task->getName();\n m_timerData.push_back( tdata );\n\n m_tasks.emplace_back( std::unique_ptr<Task>( task ) );\n m_dependencies.push_back( std::vector<TaskId>() );\n m_remainingDependencies.push_back( 0 );\n\n CORE_ASSERT( m_tasks.size() == m_dependencies.size(), \"Inconsistent task list\" );\n CORE_ASSERT( m_tasks.size() == m_remainingDependencies.size(), \"Inconsistent task list\" );\n CORE_ASSERT( m_tasks.size() == m_timerData.size(), \"Inconsistent task list\" );\n return TaskId( m_tasks.size() - 1 );\n}\n\nvoid TaskQueue::addDependency( TaskQueue::TaskId predecessor, TaskQueue::TaskId successor ) {\n CORE_ASSERT( predecessor.isValid() && ( predecessor < m_tasks.size() ),\n \"Invalid predecessor task\" );\n CORE_ASSERT( successor.isValid() && ( successor < m_tasks.size() ), \"Invalid successor task\" );\n CORE_ASSERT( predecessor != successor, \"Cannot add self-dependency\" );\n\n CORE_ASSERT( std::find( m_dependencies[predecessor].begin(),\n m_dependencies[predecessor].end(),\n successor ) == m_dependencies[predecessor].end(),\n \"Cannot add a dependency twice\" );\n\n m_dependencies[predecessor].push_back( successor );\n ++m_remainingDependencies[successor];\n}\n\nbool TaskQueue::addDependency( const std::string& predecessors, TaskQueue::TaskId successor ) {\n bool added = false;\n for ( uint i = 0; i < m_tasks.size(); ++i )\n {\n if ( m_tasks[i]->getName() == predecessors )\n {\n added = true;\n addDependency( TaskId( i ), successor );\n }\n }\n return added;\n}\n\nbool TaskQueue::addDependency( TaskQueue::TaskId predecessor, const std::string& successors ) {\n bool added = false;\n for ( uint i = 0; i < m_tasks.size(); ++i )\n {\n if ( m_tasks[i]->getName() == successors )\n {\n added = true;\n addDependency( predecessor, TaskId( i ) );\n }\n }\n return added;\n}\n\nvoid TaskQueue::addPendingDependency( const std::string& predecessors,\n TaskQueue::TaskId successor ) {\n m_pendingDepsSucc.emplace_back( predecessors, successor );\n}\n\nvoid TaskQueue::addPendingDependency( TaskId predecessor, const std::string& successors ) {\n m_pendingDepsPre.emplace_back( predecessor, successors );\n}\n\nvoid TaskQueue::resolveDependencies() {\n for ( const auto& pre : m_pendingDepsPre )\n {\n ON_ASSERT( bool result = ) addDependency( pre.first, pre.second );\n CORE_WARN_IF( !result,\n \"Pending dependency unresolved : \" << m_tasks[pre.first]->getName() << \" -> (\"\n << pre.second << \")\" );\n }\n for ( const auto& pre : m_pendingDepsSucc )\n {\n ON_ASSERT( bool result = ) addDependency( pre.first, pre.second );\n CORE_WARN_IF( !result,\n \"Pending dependency unresolved : (\" << pre.first << \") -> \"\n << m_tasks[pre.second]->getName() );\n }\n m_pendingDepsPre.clear();\n m_pendingDepsSucc.clear();\n}\n\nvoid TaskQueue::queueTask( TaskQueue::TaskId task ) {\n CORE_ASSERT( m_remainingDependencies[task] == 0,\n \" Task\" << m_tasks[task]->getName() << \"has unmet dependencies\" );\n m_taskQueue.push_front( task );\n}\n\nvoid TaskQueue::detectCycles() {\n#if defined( CORE_DEBUG )\n \/\/ Do a depth-first search of the nodes.\n std::vector<bool> visited( m_tasks.size(), false );\n std::stack<TaskId> pending;\n\n for ( uint id = 0; id < m_tasks.size(); ++id )\n {\n if ( m_dependencies[id].size() == 0 ) { pending.push( TaskId( id ) ); }\n }\n\n \/\/ If you hit this assert, there are tasks in the list but\n \/\/ all tasks have dependencies so no task can start.\n CORE_ASSERT( m_tasks.empty() || !pending.empty(), \"No free tasks.\" );\n\n while ( !pending.empty() )\n {\n TaskId id = pending.top();\n pending.pop();\n\n \/\/ The task has already been visited. It means there is a cycle in the task graph.\n CORE_ASSERT( !( visited[id] ), \"Cycle detected in tasks !\" );\n\n visited[id] = true;\n for ( const auto& dep : m_dependencies[id] )\n {\n pending.push( dep );\n }\n }\n#endif\n}\n\nvoid TaskQueue::startTasks() {\n \/\/ Add pending dependencies.\n resolveDependencies();\n\n \/\/ Do a debug check\n detectCycles();\n\n \/\/ Enqueue all tasks with no dependencies.\n for ( uint t = 0; t < m_tasks.size(); ++t )\n {\n if ( m_remainingDependencies[t] == 0 ) { queueTask( TaskId( t ) ); }\n }\n\n \/\/ Wake up all threads.\n m_threadNotifier.notify_all();\n}\n\nvoid TaskQueue::waitForTasks() {\n bool isFinished = false;\n while ( !isFinished )\n {\n \/\/ TODO : use a notifier for task queue empty.\n m_taskQueueMutex.lock();\n isFinished = ( m_taskQueue.empty() && m_processingTasks == 0 );\n m_taskQueueMutex.unlock();\n if ( !isFinished ) { std::this_thread::yield(); }\n }\n}\n\nconst std::vector<TaskQueue::TimerData>& TaskQueue::getTimerData() {\n return m_timerData;\n}\n\nvoid TaskQueue::flushTaskQueue() {\n CORE_ASSERT( m_processingTasks == 0, \"You have tasks still in process\" );\n CORE_ASSERT( m_taskQueue.empty(), \" You have unprocessed tasks \" );\n m_tasks.clear();\n m_dependencies.clear();\n m_timerData.clear();\n m_remainingDependencies.clear();\n}\n\nvoid TaskQueue::runThread( uint id ) {\n while ( true )\n {\n TaskId task;\n\n \/\/ Acquire mutex.\n {\n std::unique_lock<std::mutex> lock( m_taskQueueMutex );\n\n \/\/ Wait for a new task\n \/\/ TODO : use the second form of wait()\n while ( !m_shuttingDown && m_taskQueue.empty() )\n {\n m_threadNotifier.wait( lock );\n }\n \/\/ If the task queue is shutting down we quit, releasing\n \/\/ the lock.\n if ( m_shuttingDown ) { return; }\n\n \/\/ If we are here it means we got a task\n task = m_taskQueue.back();\n m_taskQueue.pop_back();\n ++m_processingTasks;\n CORE_ASSERT( task.isValid() && task < m_tasks.size(), \"Invalid task\" );\n }\n \/\/ Release mutex.\n\n \/\/ Run task\n m_timerData[task].start = Utils::Clock::now();\n m_timerData[task].threadId = id;\n m_tasks[task]->process();\n m_timerData[task].end = Utils::Clock::now();\n\n \/\/ Critical section : mark task as finished and en-queue dependencies.\n uint newTasks = 0;\n {\n std::unique_lock<std::mutex> lock( m_taskQueueMutex );\n for ( auto t : m_dependencies[task] )\n {\n uint& nDepends = m_remainingDependencies[t];\n CORE_ASSERT( nDepends > 0, \"Inconsistency in dependencies\" );\n --nDepends;\n if ( nDepends == 0 )\n {\n queueTask( t );\n ++newTasks;\n }\n \/\/ TODO :Easy optimization : grab one of the new task and process it immediately.\n }\n --m_processingTasks;\n }\n \/\/ If we added new tasks, we wake up one thread to execute it.\n if ( newTasks > 0 ) { m_threadNotifier.notify_one(); }\n } \/\/ End of while(true)\n}\n\nvoid TaskQueue::printTaskGraph( std::ostream& output ) const {\n output << \"digraph tasks {\" << std::endl;\n\n for ( const auto& t : m_tasks )\n {\n output << \"\\\"\" << t->getName() << \"\\\"\" << std::endl;\n }\n\n for ( uint i = 0; i < m_dependencies.size(); ++i )\n {\n const auto& task1 = m_tasks[i];\n for ( const auto& dep : m_dependencies[i] )\n {\n const auto& task2 = m_tasks[dep];\n output << \"\\\"\" << task1->getName() << \"\\\"\"\n << \" -> \";\n output << \"\\\"\" << task2->getName() << \"\\\"\" << std::endl;\n }\n }\n\n for ( const auto& preDep : m_pendingDepsPre )\n {\n const auto& task1 = m_tasks[preDep.first];\n std::string t2name = preDep.second;\n\n if ( std::find_if( m_tasks.begin(), m_tasks.end(), [=]( const auto& task ) {\n return task->getName() == t2name;\n } ) == m_tasks.end() )\n { t2name += \"?\"; }\n output << \"\\\"\" << task1->getName() << \"\\\"\"\n << \" -> \";\n output << \"\\\"\" << t2name << \"\\\"\" << std::endl;\n }\n\n for ( const auto& postDep : m_pendingDepsSucc )\n {\n std::string t1name = postDep.first;\n const auto& t2 = m_tasks[postDep.second];\n\n if ( std::find_if( m_tasks.begin(), m_tasks.end(), [=]( const auto& task ) {\n return task->getName() == t1name;\n } ) == m_tasks.end() )\n { t1name += \"?\"; }\n output << \"\\\"\" << t1name << \"\\\"\"\n << \" -> \";\n output << \"\\\"\" << t2->getName() << \"\\\"\" << std::endl;\n }\n\n output << \"}\" << std::endl;\n}\n} \/\/ namespace Core\n} \/\/ namespace Ra\n<|endoftext|>"} {"text":"<commit_before>\/********** tell emacs we use -*- c++ -*- style comments *******************\n $Revision: 1.5 $ $Author: trey $ $Date: 2006-04-28 17:57:41 $\n \n @file testSpec.cc\n @brief No brief\n\n Copyright (c) 2002-2005, Trey Smith. All rights reserved.\n\n Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n not use this file except in compliance with the License. You may\n obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n implied. See the License for the specific language governing\n permissions and limitations under the License.\n\n ***************************************************************************\/\n\n\/***************************************************************************\n * INCLUDES\n ***************************************************************************\/\n\n#include <assert.h>\n#include <stdlib.h>\n#include <unistd.h>\n#include <stdio.h>\n\n#include <iostream>\nusing namespace std;\n\n#include \"pomdpCassandraWrapper.h\"\n\nvoid usage(void) {\n cerr <<\n \"usage: testSpec OPTIONS <foo.POMDP>\\n\"\n \" -h or --help Display this help\\n\";\n exit(EXIT_FAILURE);\n}\n\nint main(int argc, char *argv[]) {\n int argi;\n char *pomdpFileName = 0;\n for (argi=1; argi < argc; argi++) {\n if (0 == strcmp(\"-h\",argv[argi]) || 0 == strcmp(\"--help\",argv[argi])) {\n usage();\n } else if (0 == pomdpFileName) {\n pomdpFileName = argv[argi];\n } else {\n cerr << \"too many arguments\" << endl;\n usage();\n }\n }\n if ( 0 == pomdpFileName ) {\n usage();\n }\n\n \/\/ read it in\n PomdpCassandraWrapper p;\n p.readFromFile(pomdpFileName);\n\n \/\/ print out stats\n cout << \"numStates = \" << p.numStates() << endl;\n cout << \"numActions = \" << p.numActions() << endl;\n cout << \"numObservations = \" << p.numObservations() << endl;\n cout << \"discount = \" << p.discount() << endl;\n cout << endl;\n\n int s, sp, a, o;\n\n cout << \"R(s,a) matrix = \" << endl;\n for (s=0; s < p.numStates(); s++) {\n for (a=0; a < p.numActions(); a++) {\n printf(\"%9.2f \", p.R(s,a));\n }\n cout << endl;\n }\n cout << endl;\n\n for (a=0; a < p.numActions(); a++) {\n cout << \"T(s,\" << a << \",sp) matrix = \" << endl;\n for (s=0; s < p.numStates(); s++) {\n for (sp=0; sp < p.numStates(); sp++) {\n\tprintf(\"%5.3f \", p.T(s,a,sp));\n }\n cout << endl;\n }\n cout << endl;\n }\n\n for (a=0; a < p.numActions(); a++) {\n cout << \"O(sp,\" << a << \",o) matrix = \" << endl;\n for (sp=0; sp < p.numStates(); sp++) {\n for (o=0; o < p.numObservations(); o++) {\n\tprintf(\"%5.3f \", p.O(sp,a,o));\n }\n cout << endl;\n }\n cout << endl;\n }\n}\n\n\n\/***************************************************************************\n * REVISION HISTORY:\n * $Log: not supported by cvs2svn $\n * Revision 1.4 2005\/10\/28 03:54:39 trey\n * simplified license\n *\n * Revision 1.3 2005\/10\/28 03:05:27 trey\n * added copyright header\n *\n * Revision 1.2 2005\/10\/27 21:37:17 trey\n * brought names up to date\n *\n * Revision 1.1.1.1 2004\/11\/09 16:18:56 trey\n * imported hsvi into new repository\n *\n * Revision 1.1.1.1 2003\/01\/07 19:19:41 trey\n * Imported sources\n *\n *\n ***************************************************************************\/\n<commit_msg>removed test code, out of date<commit_after><|endoftext|>"} {"text":"<commit_before>\/*********************************************************************************\n *\n * Inviwo - Interactive Visualization Workshop\n *\n * Copyright (c) 2014-2021 Inviwo Foundation\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * 1. Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR\n * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n *********************************************************************************\/\n\n#include <modules\/basegl\/processors\/volumeprocessing\/volumecombiner.h>\n#include <modules\/opengl\/volume\/volumegl.h>\n#include <modules\/opengl\/texture\/textureunit.h>\n#include <inviwo\/core\/util\/shuntingyard.h>\n#include <inviwo\/core\/util\/zip.h>\n#include <modules\/opengl\/texture\/textureutils.h>\n#include <modules\/opengl\/shader\/shaderutils.h>\n#include <modules\/opengl\/volume\/volumeutils.h>\n\nnamespace {\nstd::string idToString(const size_t& id) {\n if (id == 0) return \"\";\n return inviwo::toString(id);\n}\n} \/\/ namespace\n\nnamespace inviwo {\n\nconst ProcessorInfo VolumeCombiner::processorInfo_{\n \"org.inviwo.VolumeCombiner\", \/\/ Class identifier\n \"Volume Combiner\", \/\/ Display name\n \"Volume Operation\", \/\/ Category\n CodeState::Experimental, \/\/ Code state\n Tags::GL, \/\/ Tags\n};\nconst ProcessorInfo VolumeCombiner::getProcessorInfo() const { return processorInfo_; }\n\nVolumeCombiner::VolumeCombiner()\n : Processor()\n , inport_(\"inport\")\n , outport_(\"outport\")\n , description_(\"description\", \"Volumes\")\n , eqn_(\"eqn\", \"Equation\", \"v1\")\n , normalizationMode_(\n \"normalizationMode\", \"Normalization Mode\",\n {{\"normalized\", \"Normalize volumes\", NormalizationMode::Normalized},\n {\"signedNormalized\", \"Normalize volumes with sign\", NormalizationMode::SignedNormalized},\n {\"noNormalization\", \"No normalization\", NormalizationMode::NotNormalized}},\n 0)\n , scales_(\"scales\", \"Scale factors\")\n , addScale_(\"addScale\", \"Add Scale Factor\")\n , removeScale_(\"removeScale\", \"Remove Scale Factor\")\n , useWorldSpace_(\"useWorldSpaceCoordinateSystem\", \"World Space\", false)\n , borderValue_(\"borderValue\", \"Border value\", vec4(0.f), vec4(0.f), vec4(1.f), vec4(0.1f))\n , dataRange_(\"dataRange\", \"Data Range\")\n , rangeMode_(\"rangeMode\", \"Mode\")\n , outputDataRange_(\"outputDataRange\", \"Output Data Range\", 0.0, 1.0,\n std::numeric_limits<double>::lowest(), std::numeric_limits<double>::max(),\n 0.01, 0.0, InvalidationLevel::Valid, PropertySemantics::Text)\n , outputValueRange_(\"outputValueRange\", \"Output ValueRange\", 0.0, 1.0,\n std::numeric_limits<double>::lowest(), std::numeric_limits<double>::max(),\n 0.01, 0.0, InvalidationLevel::Valid, PropertySemantics::Text)\n , customRange_(\"customRange\", \"Custom Range\")\n , customDataRange_(\"customDataRange\", \"Custom Data Range\", 0.0, 1.0,\n std::numeric_limits<double>::lowest(), std::numeric_limits<double>::max(),\n 0.01, 0.0, InvalidationLevel::InvalidOutput, PropertySemantics::Text)\n , customValueRange_(\"customValueRange\", \"Custom Value Range\", 0.0, 1.0,\n std::numeric_limits<double>::lowest(), std::numeric_limits<double>::max(),\n 0.01, 0.0, InvalidationLevel::InvalidOutput, PropertySemantics::Text)\n , fragment_{std::make_shared<StringShaderResource>(\"volumecombiner.frag\", \"\")}\n , shader_({{ShaderType::Vertex, utilgl::findShaderResource(\"volume_gpu.vert\")},\n {ShaderType::Geometry, utilgl::findShaderResource(\"volume_gpu.geom\")},\n {ShaderType::Fragment, fragment_}},\n Shader::Build::No)\n , fbo_() {\n\n description_.setSemantics(PropertySemantics::Multiline);\n description_.setReadOnly(true);\n description_.setCurrentStateAsDefault();\n\n isReady_.setUpdate([this]() { return allInportsAreReady() && (valid_ || dirty_); });\n\n addPort(inport_);\n addPort(outport_);\n addProperty(description_);\n addProperty(eqn_);\n addProperty(normalizationMode_);\n addProperty(addScale_);\n addProperty(removeScale_);\n addProperty(scales_);\n addProperty(useWorldSpace_);\n\n useWorldSpace_.addProperty(borderValue_);\n\n addProperty(dataRange_);\n dataRange_.addProperties(rangeMode_, outputDataRange_, outputValueRange_, customRange_,\n customDataRange_, customValueRange_);\n\n outputDataRange_.setReadOnly(true);\n outputValueRange_.setReadOnly(true);\n\n customRange_.onChange([&]() {\n customDataRange_.setReadOnly(!customRange_.get());\n customValueRange_.setReadOnly(!customRange_.get());\n });\n customDataRange_.setReadOnly(!customRange_.get());\n customValueRange_.setReadOnly(!customRange_.get());\n\n normalizationMode_.onChange([&]() { dirty_ = true; });\n\n addScale_.onChange([&]() {\n size_t i = scales_.size();\n auto p = std::make_unique<FloatProperty>(\"scale\" + toString(i), \"s\" + toString(i + 1), 1.0f,\n -2.f, 2.f, 0.01f);\n p->setSerializationMode(PropertySerializationMode::All);\n scales_.addProperty(p.release());\n });\n\n removeScale_.onChange([&]() {\n if (scales_.size() > 0) {\n dirty_ = true;\n delete scales_.removeProperty(scales_.getProperties().back());\n isReady_.update();\n }\n });\n\n eqn_.onChange([&]() {\n dirty_ = true;\n isReady_.update();\n });\n\n inport_.onConnect([&]() {\n dirty_ = true;\n updateProperties();\n isReady_.update();\n });\n inport_.onDisconnect([&]() {\n dirty_ = true;\n updateProperties();\n isReady_.update();\n });\n\n useWorldSpace_.onChange([this]() {\n dirty_ = true;\n isReady_.update();\n });\n}\n\nstd::string VolumeCombiner::buildEquation() const {\n std::map<std::string, double> vars = {};\n std::map<std::string, std::string> symbols;\n\n for (auto&& i : util::enumerate(inport_)) {\n symbols[\"s\" + toString(i.first() + 1)] = \"scale\" + toString(i.first());\n symbols[\"v\" + toString(i.first() + 1)] = \"vol\" + toString(i.first());\n }\n\n return shuntingyard::Calculator::shaderCode(eqn_.get(), vars, symbols);\n}\n\nvoid VolumeCombiner::buildShader(const std::string& eqn) {\n std::stringstream ss;\n ss << \"#include \\\"utils\/structs.glsl\\\"\\n\";\n ss << \"#include \\\"utils\/sampler3d.glsl\\\"\\n\\n\";\n ss << \"in vec4 texCoord_;\\n\";\n\n ss << \"uniform vec4 \" << borderValue_.getIdentifier() << \";\\n\";\n\n for (auto&& i : util::enumerate(inport_)) {\n ss << \"uniform sampler3D volume\" << idToString(i.first()) << \";\\n\";\n ss << \"uniform VolumeParameters volume\" << idToString(i.first()) << \"Parameters;\\n\";\n }\n for (auto prop : scales_.getProperties()) {\n ss << \"uniform float \" << prop->getIdentifier() << \";\\n\";\n }\n\n ss << \"\\nvoid main() {\\n\";\n\n \/\/ Determine which normalization mode should be used\n std::string getVoxel;\n auto mode = normalizationMode_.get();\n if (mode == NormalizationMode::Normalized)\n getVoxel = \"getNormalizedVoxel\";\n else if (mode == NormalizationMode::SignedNormalized)\n getVoxel = \"getSignNormalizedVoxel\";\n else\n getVoxel = \"getVoxel\";\n\n for (auto&& i : util::enumerate(inport_)) {\n const std::string vol = \"vol\" + toString(i.first());\n const std::string v = \"volume\" + idToString(i.first());\n const std::string vp = \"volume\" + idToString(i.first()) + \"Parameters\";\n if (useWorldSpace_) {\n const std::string coord = \"coord\" + toString(i.first());\n \/\/ Retrieve data from world space and use border value if outside of volume\n ss << \" vec3 \" << coord << \" = (\" << vp << \".worldToTexture * \"\n << \"volumeParameters.textureToWorld * texCoord_).xyz;\\n\";\n ss << \" vec4 \" << vol << \";\\n\";\n ss << \" if (all(greaterThanEqual(\" << coord << \", vec3(0))) &&\"\n << \" all(lessThanEqual(\" << coord << \", vec3(1)))) {\\n\";\n ss << \" \" << vol << \" = \" << getVoxel << \"(\" << v << \", \" << vp << \", \" << coord\n << \");\\n\";\n ss << \" } else {\\n\";\n ss << \" \" << vol << \" = borderValue;\\n\";\n ss << \" }\\n\\n\";\n } else {\n ss << \" vec4 \" << vol << \" = \" << getVoxel << \"(\" << v << \", \" << vp\n << \", texCoord_.xyz);\\n\";\n }\n }\n\n ss << \" FragData0 = \" << eqn << \";\\n\";\n ss << \" gl_FragDepth = 1.0;\\n\";\n ss << \"}\\n\";\n\n fragment_->setSource(ss.str());\n shader_.build();\n}\n\nvoid VolumeCombiner::updateProperties() {\n std::stringstream desc;\n std::vector<OptionPropertyIntOption> options;\n for (auto&& p : util::enumerate(inport_.getConnectedOutports())) {\n const std::string str =\n \"v\" + toString(p.first() + 1) + \": \" + p.second()->getProcessor()->getDisplayName();\n desc << str << \"\\n\";\n options.emplace_back(\"v\" + toString(p.first() + 1), str, static_cast<int>(p.first()));\n }\n options.emplace_back(\"maxRange\", \"min\/max {v1, v2, ...}\", -1);\n description_.set(desc.str());\n\n rangeMode_.replaceOptions(options);\n}\n\nvoid VolumeCombiner::process() {\n if (inport_.isChanged()) {\n volume_ = std::make_shared<Volume>(*inport_.getData(), noData);\n }\n\n updateDataRange();\n\n if (dirty_) {\n dirty_ = false;\n try {\n buildShader(buildEquation());\n valid_ = true;\n } catch (Exception& e) {\n valid_ = false;\n isReady_.update();\n throw Exception(e.getMessage() + \": \" + eqn_.get(), IVW_CONTEXT);\n }\n }\n\n shader_.activate();\n\n TextureUnitContainer cont;\n int i = 0;\n for (const auto& vol : inport_) {\n utilgl::bindAndSetUniforms(shader_, cont, *vol, \"volume\" + idToString(i));\n ++i;\n }\n\n utilgl::setUniforms(shader_, borderValue_);\n for (auto prop : scales_.getProperties()) {\n utilgl::setUniforms(shader_, *static_cast<FloatProperty*>(prop));\n }\n\n const size3_t dim{inport_.getData()->getDimensions()};\n fbo_.activate();\n glViewport(0, 0, static_cast<GLsizei>(dim.x), static_cast<GLsizei>(dim.y));\n\n \/\/ We always need to ask for a editable representation\n \/\/ this will invalidate any other representations\n VolumeGL* outVolumeGL = volume_->getEditableRepresentation<VolumeGL>();\n if (inport_.isChanged()) {\n fbo_.attachColorTexture(outVolumeGL->getTexture().get(), 0);\n }\n\n utilgl::multiDrawImagePlaneRect(static_cast<int>(dim.z));\n\n shader_.deactivate();\n fbo_.deactivate();\n isReady_.update();\n}\n\nvoid VolumeCombiner::updateDataRange() {\n dvec2 dataRange = inport_.getData()->dataMap_.dataRange;\n dvec2 valueRange = inport_.getData()->dataMap_.valueRange;\n\n if (rangeMode_.getSelectedIdentifier() == \"maxRange\") {\n auto minmax = [](const dvec2& a, const dvec2& b) {\n return dvec2{std::min(a.x, b.x), std::max(a.y, b.y)};\n };\n\n for (const auto& vol : inport_) {\n dataRange = minmax(dataRange, vol->dataMap_.dataRange);\n valueRange = minmax(valueRange, vol->dataMap_.valueRange);\n }\n } else {\n dataRange = inport_.getVectorData()[rangeMode_.getSelectedValue()]->dataMap_.dataRange;\n valueRange = inport_.getVectorData()[rangeMode_.getSelectedValue()]->dataMap_.valueRange;\n }\n outputDataRange_.set(dataRange);\n outputValueRange_.set(valueRange);\n\n if (customRange_) {\n dataRange = customDataRange_;\n valueRange = customValueRange_;\n }\n\n volume_->dataMap_.dataRange = dataRange;\n volume_->dataMap_.valueRange = valueRange;\n}\n\n} \/\/ namespace inviwo\n<commit_msg>BaseGL: VolumeCombiner fix<commit_after>\/*********************************************************************************\n *\n * Inviwo - Interactive Visualization Workshop\n *\n * Copyright (c) 2014-2021 Inviwo Foundation\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * 1. Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR\n * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n *********************************************************************************\/\n\n#include <modules\/basegl\/processors\/volumeprocessing\/volumecombiner.h>\n#include <modules\/opengl\/volume\/volumegl.h>\n#include <modules\/opengl\/texture\/textureunit.h>\n#include <inviwo\/core\/util\/shuntingyard.h>\n#include <inviwo\/core\/util\/zip.h>\n#include <modules\/opengl\/texture\/textureutils.h>\n#include <modules\/opengl\/shader\/shaderutils.h>\n#include <modules\/opengl\/volume\/volumeutils.h>\n\nnamespace {\nstd::string idToString(const size_t& id) {\n if (id == 0) return \"\";\n return inviwo::toString(id);\n}\n} \/\/ namespace\n\nnamespace inviwo {\n\nconst ProcessorInfo VolumeCombiner::processorInfo_{\n \"org.inviwo.VolumeCombiner\", \/\/ Class identifier\n \"Volume Combiner\", \/\/ Display name\n \"Volume Operation\", \/\/ Category\n CodeState::Experimental, \/\/ Code state\n Tags::GL, \/\/ Tags\n};\nconst ProcessorInfo VolumeCombiner::getProcessorInfo() const { return processorInfo_; }\n\nVolumeCombiner::VolumeCombiner()\n : Processor()\n , inport_(\"inport\")\n , outport_(\"outport\")\n , description_(\"description\", \"Volumes\")\n , eqn_(\"eqn\", \"Equation\", \"v1\")\n , normalizationMode_(\n \"normalizationMode\", \"Normalization Mode\",\n {{\"normalized\", \"Normalize volumes\", NormalizationMode::Normalized},\n {\"signedNormalized\", \"Normalize volumes with sign\", NormalizationMode::SignedNormalized},\n {\"noNormalization\", \"No normalization\", NormalizationMode::NotNormalized}},\n 0)\n , scales_(\"scales\", \"Scale factors\")\n , addScale_(\"addScale\", \"Add Scale Factor\")\n , removeScale_(\"removeScale\", \"Remove Scale Factor\")\n , useWorldSpace_(\"useWorldSpaceCoordinateSystem\", \"World Space\", false)\n , borderValue_(\"borderValue\", \"Border value\", vec4(0.f), vec4(0.f), vec4(1.f), vec4(0.1f))\n , dataRange_(\"dataRange\", \"Data Range\")\n , rangeMode_(\"rangeMode\", \"Mode\")\n , outputDataRange_(\"outputDataRange\", \"Output Data Range\", 0.0, 1.0,\n std::numeric_limits<double>::lowest(), std::numeric_limits<double>::max(),\n 0.01, 0.0, InvalidationLevel::Valid, PropertySemantics::Text)\n , outputValueRange_(\"outputValueRange\", \"Output ValueRange\", 0.0, 1.0,\n std::numeric_limits<double>::lowest(), std::numeric_limits<double>::max(),\n 0.01, 0.0, InvalidationLevel::Valid, PropertySemantics::Text)\n , customRange_(\"customRange\", \"Custom Range\")\n , customDataRange_(\"customDataRange\", \"Custom Data Range\", 0.0, 1.0,\n std::numeric_limits<double>::lowest(), std::numeric_limits<double>::max(),\n 0.01, 0.0, InvalidationLevel::InvalidOutput, PropertySemantics::Text)\n , customValueRange_(\"customValueRange\", \"Custom Value Range\", 0.0, 1.0,\n std::numeric_limits<double>::lowest(), std::numeric_limits<double>::max(),\n 0.01, 0.0, InvalidationLevel::InvalidOutput, PropertySemantics::Text)\n , fragment_{std::make_shared<StringShaderResource>(\"volumecombiner.frag\", \"\")}\n , shader_({{ShaderType::Vertex, utilgl::findShaderResource(\"volume_gpu.vert\")},\n {ShaderType::Geometry, utilgl::findShaderResource(\"volume_gpu.geom\")},\n {ShaderType::Fragment, fragment_}},\n Shader::Build::No)\n , fbo_() {\n\n description_.setSemantics(PropertySemantics::Multiline);\n description_.setReadOnly(true);\n description_.setCurrentStateAsDefault();\n\n isReady_.setUpdate([this]() { return allInportsAreReady() && (valid_ || dirty_); });\n\n addPort(inport_);\n addPort(outport_);\n addProperty(description_);\n addProperty(eqn_);\n addProperty(normalizationMode_);\n addProperty(addScale_);\n addProperty(removeScale_);\n addProperty(scales_);\n addProperty(useWorldSpace_);\n\n useWorldSpace_.addProperty(borderValue_);\n\n addProperty(dataRange_);\n dataRange_.addProperties(rangeMode_, outputDataRange_, outputValueRange_, customRange_,\n customDataRange_, customValueRange_);\n\n outputDataRange_.setReadOnly(true);\n outputValueRange_.setReadOnly(true);\n\n customRange_.onChange([&]() {\n customDataRange_.setReadOnly(!customRange_.get());\n customValueRange_.setReadOnly(!customRange_.get());\n });\n customDataRange_.setReadOnly(!customRange_.get());\n customValueRange_.setReadOnly(!customRange_.get());\n\n normalizationMode_.onChange([&]() { dirty_ = true; });\n\n addScale_.onChange([&]() {\n size_t i = scales_.size();\n auto p = std::make_unique<FloatProperty>(\"scale\" + toString(i), \"s\" + toString(i + 1), 1.0f,\n -2.f, 2.f, 0.01f);\n p->setSerializationMode(PropertySerializationMode::All);\n scales_.addProperty(p.release());\n });\n\n removeScale_.onChange([&]() {\n if (scales_.size() > 0) {\n dirty_ = true;\n delete scales_.removeProperty(scales_.getProperties().back());\n isReady_.update();\n }\n });\n\n eqn_.onChange([&]() {\n dirty_ = true;\n isReady_.update();\n });\n\n inport_.onConnect([&]() {\n dirty_ = true;\n updateProperties();\n isReady_.update();\n });\n inport_.onDisconnect([&]() {\n dirty_ = true;\n updateProperties();\n isReady_.update();\n });\n\n useWorldSpace_.onChange([this]() {\n dirty_ = true;\n isReady_.update();\n });\n}\n\nstd::string VolumeCombiner::buildEquation() const {\n std::map<std::string, double> vars = {};\n std::map<std::string, std::string> symbols;\n\n for (auto&& i : util::enumerate(inport_)) {\n symbols[\"s\" + toString(i.first() + 1)] = \"scale\" + toString(i.first());\n symbols[\"v\" + toString(i.first() + 1)] = \"vol\" + toString(i.first());\n }\n\n return shuntingyard::Calculator::shaderCode(eqn_.get(), vars, symbols);\n}\n\nvoid VolumeCombiner::buildShader(const std::string& eqn) {\n std::stringstream ss;\n ss << \"#include \\\"utils\/structs.glsl\\\"\\n\";\n ss << \"#include \\\"utils\/sampler3d.glsl\\\"\\n\\n\";\n ss << \"in vec4 texCoord_;\\n\";\n\n ss << \"uniform vec4 \" << borderValue_.getIdentifier() << \";\\n\";\n\n for (auto&& i : util::enumerate(inport_)) {\n ss << \"uniform sampler3D volume\" << idToString(i.first()) << \";\\n\";\n ss << \"uniform VolumeParameters volume\" << idToString(i.first()) << \"Parameters;\\n\";\n }\n for (auto prop : scales_.getProperties()) {\n ss << \"uniform float \" << prop->getIdentifier() << \";\\n\";\n }\n\n ss << \"\\nvoid main() {\\n\";\n\n \/\/ Determine which normalization mode should be used\n std::string getVoxel;\n auto mode = normalizationMode_.get();\n if (mode == NormalizationMode::Normalized)\n getVoxel = \"getNormalizedVoxel\";\n else if (mode == NormalizationMode::SignedNormalized)\n getVoxel = \"getSignNormalizedVoxel\";\n else\n getVoxel = \"getVoxel\";\n\n for (auto&& i : util::enumerate(inport_)) {\n const std::string vol = \"vol\" + toString(i.first());\n const std::string v = \"volume\" + idToString(i.first());\n const std::string vp = \"volume\" + idToString(i.first()) + \"Parameters\";\n if (useWorldSpace_) {\n const std::string coord = \"coord\" + toString(i.first());\n \/\/ Retrieve data from world space and use border value if outside of volume\n ss << \" vec3 \" << coord << \" = (\" << vp << \".worldToTexture * \"\n << \"volumeParameters.textureToWorld * texCoord_).xyz;\\n\";\n ss << \" vec4 \" << vol << \";\\n\";\n ss << \" if (all(greaterThanEqual(\" << coord << \", vec3(0))) &&\"\n << \" all(lessThanEqual(\" << coord << \", vec3(1)))) {\\n\";\n ss << \" \" << vol << \" = \" << getVoxel << \"(\" << v << \", \" << vp << \", \" << coord\n << \");\\n\";\n ss << \" } else {\\n\";\n ss << \" \" << vol << \" = borderValue;\\n\";\n ss << \" }\\n\\n\";\n } else {\n ss << \" vec4 \" << vol << \" = \" << getVoxel << \"(\" << v << \", \" << vp\n << \", texCoord_.xyz);\\n\";\n }\n }\n\n ss << \" FragData0 = \" << eqn << \";\\n\";\n ss << \" gl_FragDepth = 1.0;\\n\";\n ss << \"}\\n\";\n\n fragment_->setSource(ss.str());\n shader_.build();\n}\n\nvoid VolumeCombiner::updateProperties() {\n std::stringstream desc;\n std::vector<OptionPropertyIntOption> options;\n for (auto&& p : util::enumerate(inport_.getConnectedOutports())) {\n const std::string str =\n \"v\" + toString(p.first() + 1) + \": \" + p.second()->getProcessor()->getDisplayName();\n desc << str << \"\\n\";\n options.emplace_back(\"v\" + toString(p.first() + 1), str, static_cast<int>(p.first()));\n }\n options.emplace_back(\"maxRange\", \"min\/max {v1, v2, ...}\", -1);\n description_.set(desc.str());\n\n rangeMode_.replaceOptions(options);\n}\n\nvoid VolumeCombiner::process() {\n if (inport_.isChanged()) {\n volume_ = std::make_shared<Volume>(*inport_.getData(), noData);\n outport_.setData(volume_);\n }\n\n updateDataRange();\n\n if (dirty_) {\n dirty_ = false;\n try {\n buildShader(buildEquation());\n valid_ = true;\n } catch (Exception& e) {\n valid_ = false;\n isReady_.update();\n throw Exception(e.getMessage() + \": \" + eqn_.get(), IVW_CONTEXT);\n }\n }\n\n shader_.activate();\n\n TextureUnitContainer cont;\n int i = 0;\n for (const auto& vol : inport_) {\n utilgl::bindAndSetUniforms(shader_, cont, *vol, \"volume\" + idToString(i));\n ++i;\n }\n\n utilgl::setUniforms(shader_, borderValue_);\n for (auto prop : scales_.getProperties()) {\n utilgl::setUniforms(shader_, *static_cast<FloatProperty*>(prop));\n }\n\n const size3_t dim{inport_.getData()->getDimensions()};\n fbo_.activate();\n glViewport(0, 0, static_cast<GLsizei>(dim.x), static_cast<GLsizei>(dim.y));\n\n \/\/ We always need to ask for a editable representation\n \/\/ this will invalidate any other representations\n VolumeGL* outVolumeGL = volume_->getEditableRepresentation<VolumeGL>();\n if (inport_.isChanged()) {\n fbo_.attachColorTexture(outVolumeGL->getTexture().get(), 0);\n }\n\n utilgl::multiDrawImagePlaneRect(static_cast<int>(dim.z));\n\n shader_.deactivate();\n fbo_.deactivate();\n isReady_.update();\n}\n\nvoid VolumeCombiner::updateDataRange() {\n dvec2 dataRange = inport_.getData()->dataMap_.dataRange;\n dvec2 valueRange = inport_.getData()->dataMap_.valueRange;\n\n if (rangeMode_.getSelectedIdentifier() == \"maxRange\") {\n auto minmax = [](const dvec2& a, const dvec2& b) {\n return dvec2{std::min(a.x, b.x), std::max(a.y, b.y)};\n };\n\n for (const auto& vol : inport_) {\n dataRange = minmax(dataRange, vol->dataMap_.dataRange);\n valueRange = minmax(valueRange, vol->dataMap_.valueRange);\n }\n } else {\n dataRange = inport_.getVectorData()[rangeMode_.getSelectedValue()]->dataMap_.dataRange;\n valueRange = inport_.getVectorData()[rangeMode_.getSelectedValue()]->dataMap_.valueRange;\n }\n outputDataRange_.set(dataRange);\n outputValueRange_.set(valueRange);\n\n if (customRange_) {\n dataRange = customDataRange_;\n valueRange = customValueRange_;\n }\n\n volume_->dataMap_.dataRange = dataRange;\n volume_->dataMap_.valueRange = valueRange;\n}\n\n} \/\/ namespace inviwo\n<|endoftext|>"} {"text":"<commit_before>\/* Copyright (C) 2014 Slawomir Cygan <slawomir.cygan@gmail.com>\r\n*\r\n* Licensed under the Apache License, Version 2.0 (the \"License\");\r\n* you may not use this file except in compliance with the License.\r\n* You may obtain a copy of the License at\r\n*\r\n* http:\/\/www.apache.org\/licenses\/LICENSE-2.0\r\n*\r\n* Unless required by applicable law or agreed to in writing, software\r\n* distributed under the License is distributed on an \"AS IS\" BASIS,\r\n* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n* See the License for the specific language governing permissions and\r\n* limitations under the License.\r\n*\/\r\n\r\n#include \"backtrace.h\"\r\n#include \"dl-intercept.h\"\r\n#include \"dl.h\"\r\n#include \"globalstate.h\"\r\n\r\n#include <DGLCommon\/os.h>\r\n\r\n#ifdef __ANDROID__\r\nclass BackTraceImpl: public BackTrace {\r\npublic:\r\n BackTraceImpl():m_Supported(false) {\r\n \r\n if (!s_CorkscrewDSO) {\r\n try {\r\n s_CorkscrewDSO = EarlyGlobalState::getDynLoader().getLibrary(\"libcorkscrew.so\");\r\n } catch (const std::runtime_error& e) {\r\n Os::info(e.what());\r\n }\r\n }\r\n if (s_CorkscrewDSO && (!p_unwind_backtrace || !p_get_backtrace_symbols || !p_free_backtrace_symbols)) {\r\n p_unwind_backtrace = reinterpret_cast<t_unwind_backtrace>(s_CorkscrewDSO->getFunction(\"unwind_backtrace\"));\r\n p_get_backtrace_symbols = reinterpret_cast<t_get_backtrace_symbols>(s_CorkscrewDSO->getFunction(\"get_backtrace_symbols\"));\r\n p_free_backtrace_symbols = reinterpret_cast<t_free_backtrace_symbols>(s_CorkscrewDSO->getFunction(\"free_backtrace_symbols\"));\r\n };\r\n\r\n m_Supported = (p_unwind_backtrace && p_get_backtrace_symbols && p_free_backtrace_symbols);\r\n } \r\n\r\n \/*\r\n * Describes a single frame of a backtrace.\r\n *\/\r\n typedef struct {\r\n uintptr_t absolute_pc; \/* absolute PC offset *\/\r\n uintptr_t stack_top; \/* top of stack for this frame *\/\r\n size_t stack_size; \/* size of this stack frame *\/\r\n } backtrace_frame_t;\r\n\r\n \/*\r\n * Describes the symbols associated with a backtrace frame.\r\n *\/\r\n typedef struct {\r\n uintptr_t relative_pc; \/* relative frame PC offset from the start of the library,\r\n or the absolute PC if the library is unknown *\/\r\n uintptr_t relative_symbol_addr; \/* relative offset of the symbol from the start of the\r\n library or 0 if the library is unknown *\/\r\n char* map_name; \/* executable or library name, or NULL if unknown *\/\r\n char* symbol_name; \/* symbol name, or NULL if unknown *\/\r\n char* demangled_name; \/* demangled symbol name, or NULL if unknown *\/\r\n } backtrace_symbol_t;\r\n\r\n\r\n\r\n typedef ssize_t (* t_unwind_backtrace)(backtrace_frame_t* backtrace, size_t ignore_depth, size_t max_depth);\r\n typedef void (* t_get_backtrace_symbols)(const backtrace_frame_t* backtrace, size_t frames,\r\n backtrace_symbol_t* backtrace_symbols);\r\n typedef void (*t_format_backtrace_line)(unsigned frameNumber, const backtrace_frame_t* frame,\r\n const backtrace_symbol_t* symbol, char* buffer, size_t bufferSize);\r\n \r\n typedef void (* t_free_backtrace_symbols)(backtrace_symbol_t* backtrace_symbols, size_t frames);\r\n\r\nprivate:\r\n enum {\r\n MAX_DEPTH = 31,\r\n MAX_BACKTRACE_LINE_LENGTH = 800\r\n };\r\n\r\n virtual void streamTo(std::vector<std::string>& str) override {\r\n\r\n if (!m_Supported) {\r\n throw std::runtime_error(\"Backtrace support not implemented on this platform.\");\r\n }\r\n\r\n backtrace_frame_t frames[MAX_DEPTH];\r\n\r\n const int ignoreDepth = 1;\r\n\r\n ssize_t count = p_unwind_backtrace(frames, ignoreDepth + 1, MAX_DEPTH);\r\n\r\n void* currentLibraryAddress = DynamicLoader::getCurrentLibraryBaseAddress();\r\n\r\n if (count > 0) {\r\n std::vector<backtrace_symbol_t> symbols(count);\r\n p_get_backtrace_symbols(frames, count, &symbols[0]);\r\n for (ssize_t i = 0; i < count; i++) {\r\n\r\n Dl_info symbolInfo; \r\n dladdr(reinterpret_cast<void*>(frames[i].absolute_pc), &symbolInfo);\r\n Os::info(\"XXX %x == %x\\n\", symbolInfo.dli_fbase, currentLibraryAddress);\r\n if (symbolInfo.dli_fbase == currentLibraryAddress) {\r\n \/\/we assume, that removing current library symbols from backtrace\r\n \/\/is enough, to filter out DGL from backtrace. This implies no 3rd party\r\n \/\/libraries should be called from exporter to get here.\r\n continue;\r\n }\r\n\r\n\r\n std::stringstream line;\r\n\r\n if (!symbols[i].map_name) {\r\n line << \"<unknown module>\";\r\n } else {\r\n line << symbols[i].map_name;\r\n }\r\n line << '!';\r\n line << \"0x\" << std::hex << (int) frames[i].absolute_pc << std::dec << ' ';\r\n\r\n if (symbols[i].demangled_name) {\r\n line << symbols[i].demangled_name;\r\n } else if (symbols[i].symbol_name) {\r\n line << symbols[i].symbol_name;\r\n } else {\r\n line << \"<unknown function>\";\r\n }\r\n\r\n uint32_t pc_offset = symbols[i].relative_pc - symbols[i].relative_symbol_addr;\r\n\r\n if (pc_offset) {\r\n line << \" +\" << pc_offset;\r\n }\r\n\r\n str.push_back(line.str());\r\n }\r\n p_free_backtrace_symbols(&symbols[0], count);\r\n }\r\n }\r\n\r\n bool m_Supported;\r\n\r\n static DynamicLibrary* s_CorkscrewDSO;\r\n static t_unwind_backtrace p_unwind_backtrace;\r\n static t_get_backtrace_symbols p_get_backtrace_symbols;\r\n static t_free_backtrace_symbols p_free_backtrace_symbols;\r\n\r\n};\r\nDynamicLibrary* BackTraceImpl::s_CorkscrewDSO = nullptr;\r\nBackTraceImpl::t_unwind_backtrace BackTraceImpl::p_unwind_backtrace = nullptr;\r\nBackTraceImpl::t_get_backtrace_symbols BackTraceImpl::p_get_backtrace_symbols = nullptr;\r\nBackTraceImpl::t_free_backtrace_symbols BackTraceImpl::p_free_backtrace_symbols = nullptr;\r\n\r\n#else\r\n#ifdef _WIN32\r\n\r\n#include \"external\/StackWalker\/StackWalker.h\"\r\n#include \"Psapi.h\"\r\n#include <sstream>\r\n#include <boost\/noncopyable.hpp>\r\n\r\nclass BackTraceImpl: public BackTrace {\r\n\r\n class DGLStackWalker: public StackWalker, boost::noncopyable {\r\n public:\r\n DGLStackWalker(std::vector<std::string>& buffer): m_buffer(buffer) {\r\n MODULEINFO modInfo;\r\n if (GetModuleInformation(GetCurrentProcess(), (HMODULE)Os::getCurrentModuleHandle(), &modInfo, sizeof(modInfo))) {\r\n m_BoundsOfDGLLibrary[0] = reinterpret_cast<intptr_t>(modInfo.lpBaseOfDll);\r\n m_BoundsOfDGLLibrary[1] = reinterpret_cast<intptr_t>(reinterpret_cast<char*>(modInfo.lpBaseOfDll) + modInfo.SizeOfImage);\r\n }\r\n }\r\n\r\n virtual void OnCallstackEntry(CallstackEntryType eType, CallstackEntry &entry) {\r\n\r\n \/\/we assume, that removing current library symbols from backtrace\r\n \/\/is enough, to filter out DGL from backtrace. This implies no 3rd party\r\n \/\/libraries should be called from exporter to get here.\r\n bool outSideOfCurrentLibrary = ((intptr_t)entry.offset < m_BoundsOfDGLLibrary[0] ||\r\n (intptr_t)entry.offset >= m_BoundsOfDGLLibrary[1]);\r\n\r\n if ( (eType != lastEntry) && (entry.offset != 0) && outSideOfCurrentLibrary)\r\n {\r\n std::stringstream line;\r\n\r\n if (entry.moduleName[0] == 0 && entry.loadedImageName == 0) {\r\n line << \"<unknown module>\";\r\n } else {\r\n const char* moduleName;\r\n if (!entry.moduleName) {\r\n \/\/use full filepath\r\n moduleName = entry.loadedImageName;\r\n } else {\r\n \/\/use module name\r\n moduleName = entry.moduleName;\r\n\r\n if (entry.loadedImageName) {\r\n \/\/if we have both, use full file path to obtain file ext.\r\n const char* offset = strstr(entry.loadedImageName, entry.moduleName);\r\n while (offset) {\r\n moduleName = offset;\r\n offset = strstr(offset + 1, entry.moduleName);\r\n }\r\n }\r\n }\r\n line << moduleName;\r\n }\r\n line << '!';\r\n line << \"0x\" << std::hex << (int) entry.offset << std::dec << ' ';\r\n\r\n if (entry.undFullName[0] != 0) {\r\n line << entry.undFullName;\r\n } else if (entry.undName[0] != 0) {\r\n line << entry.undName;\r\n } else if (entry.name[0] != 0) {\r\n line << entry.name;\r\n } else {\r\n line << \"<unknown function>\";\r\n }\r\n line << ' ';\r\n\r\n if (entry.lineFileName[0] == 0) {\r\n line << \"<unknown source file>\";\r\n } else {\r\n line << entry.lineFileName;\r\n if (entry.lineNumber) {\r\n line << \" Line \" << entry.lineNumber;\r\n }\r\n }\r\n m_buffer.push_back(line.str());\r\n }\r\n StackWalker::OnCallstackEntry(eType, entry);\r\n }\r\n std::vector<std::string>& m_buffer;\r\n intptr_t m_BoundsOfDGLLibrary[2];\r\n };\r\n\r\n virtual void streamTo(std::vector<std::string>& str) override {\r\n DGLStackWalker sw(str);\r\n sw.ShowCallstack(); \r\n }\r\n};\r\n\r\n#else\r\n#ifdef __linux__\r\n\r\n#include <execinfo.h>\r\n\r\nclass BackTraceImpl: public BackTrace {\r\n virtual void streamTo(std::vector<std::string>& ret) override {\r\n ret.resize(20);\r\n std::vector<void*> buffer;\r\n int nptrs = backtrace(&buffer[0], buffer.size());\r\n while (nptrs > 0 && nptrs == static_cast<int>(buffer.size())) {\r\n buffer.resize(buffer.size() * 2);\r\n nptrs = backtrace(&buffer[0], buffer.size());\r\n }\r\n char** strings = backtrace_symbols(&buffer[0], buffer.size());\r\n if (!strings) {\r\n throw std::runtime_error(\"Cannot get backtrace: backtrace_symbols failed.\");\r\n }\r\n ret.resize(buffer.size());\r\n for (size_t i = 0; i < ret.size(); i++) {\r\n ret[i] = strings[i];\r\n }\r\n free(strings);\r\n }\r\n};\r\n\r\n#else\r\nclass BackTraceImpl: public BackTrace {\r\n virtual void streamTo(std::vector<std::string>&) override {\r\n throw std::runtime_error(\"Backtrace support not implemented on this platform.\");\r\n }\r\n};\r\n#endif\r\n#endif\r\n#endif\r\n\r\nstd::shared_ptr<BackTrace> BackTrace::Get() {\r\n return std::make_shared<BackTraceImpl>();\r\n}\r\n<commit_msg>Backtrace filtering and fixes for linux<commit_after>\/* Copyright (C) 2014 Slawomir Cygan <slawomir.cygan@gmail.com>\r\n*\r\n* Licensed under the Apache License, Version 2.0 (the \"License\");\r\n* you may not use this file except in compliance with the License.\r\n* You may obtain a copy of the License at\r\n*\r\n* http:\/\/www.apache.org\/licenses\/LICENSE-2.0\r\n*\r\n* Unless required by applicable law or agreed to in writing, software\r\n* distributed under the License is distributed on an \"AS IS\" BASIS,\r\n* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n* See the License for the specific language governing permissions and\r\n* limitations under the License.\r\n*\/\r\n\r\n#include \"backtrace.h\"\r\n#include \"dl-intercept.h\"\r\n#include \"dl.h\"\r\n#include \"globalstate.h\"\r\n\r\n#include <DGLCommon\/os.h>\r\n\r\n#ifdef __ANDROID__\r\nclass BackTraceImpl: public BackTrace {\r\npublic:\r\n BackTraceImpl():m_Supported(false) {\r\n \r\n if (!s_CorkscrewDSO) {\r\n try {\r\n s_CorkscrewDSO = EarlyGlobalState::getDynLoader().getLibrary(\"libcorkscrew.so\");\r\n } catch (const std::runtime_error& e) {\r\n Os::info(e.what());\r\n }\r\n }\r\n if (s_CorkscrewDSO && (!p_unwind_backtrace || !p_get_backtrace_symbols || !p_free_backtrace_symbols)) {\r\n p_unwind_backtrace = reinterpret_cast<t_unwind_backtrace>(s_CorkscrewDSO->getFunction(\"unwind_backtrace\"));\r\n p_get_backtrace_symbols = reinterpret_cast<t_get_backtrace_symbols>(s_CorkscrewDSO->getFunction(\"get_backtrace_symbols\"));\r\n p_free_backtrace_symbols = reinterpret_cast<t_free_backtrace_symbols>(s_CorkscrewDSO->getFunction(\"free_backtrace_symbols\"));\r\n };\r\n\r\n m_Supported = (p_unwind_backtrace && p_get_backtrace_symbols && p_free_backtrace_symbols);\r\n } \r\n\r\n \/*\r\n * Describes a single frame of a backtrace.\r\n *\/\r\n typedef struct {\r\n uintptr_t absolute_pc; \/* absolute PC offset *\/\r\n uintptr_t stack_top; \/* top of stack for this frame *\/\r\n size_t stack_size; \/* size of this stack frame *\/\r\n } backtrace_frame_t;\r\n\r\n \/*\r\n * Describes the symbols associated with a backtrace frame.\r\n *\/\r\n typedef struct {\r\n uintptr_t relative_pc; \/* relative frame PC offset from the start of the library,\r\n or the absolute PC if the library is unknown *\/\r\n uintptr_t relative_symbol_addr; \/* relative offset of the symbol from the start of the\r\n library or 0 if the library is unknown *\/\r\n char* map_name; \/* executable or library name, or NULL if unknown *\/\r\n char* symbol_name; \/* symbol name, or NULL if unknown *\/\r\n char* demangled_name; \/* demangled symbol name, or NULL if unknown *\/\r\n } backtrace_symbol_t;\r\n\r\n\r\n\r\n typedef ssize_t (* t_unwind_backtrace)(backtrace_frame_t* backtrace, size_t ignore_depth, size_t max_depth);\r\n typedef void (* t_get_backtrace_symbols)(const backtrace_frame_t* backtrace, size_t frames,\r\n backtrace_symbol_t* backtrace_symbols);\r\n typedef void (*t_format_backtrace_line)(unsigned frameNumber, const backtrace_frame_t* frame,\r\n const backtrace_symbol_t* symbol, char* buffer, size_t bufferSize);\r\n \r\n typedef void (* t_free_backtrace_symbols)(backtrace_symbol_t* backtrace_symbols, size_t frames);\r\n\r\nprivate:\r\n enum {\r\n MAX_DEPTH = 31,\r\n MAX_BACKTRACE_LINE_LENGTH = 800\r\n };\r\n\r\n virtual void streamTo(std::vector<std::string>& str) override {\r\n\r\n if (!m_Supported) {\r\n throw std::runtime_error(\"Backtrace support not implemented on this platform.\");\r\n }\r\n\r\n backtrace_frame_t frames[MAX_DEPTH];\r\n\r\n const int ignoreDepth = 1;\r\n\r\n ssize_t count = p_unwind_backtrace(frames, ignoreDepth + 1, MAX_DEPTH);\r\n\r\n void* currentLibraryAddress = DynamicLoader::getCurrentLibraryBaseAddress();\r\n\r\n if (count > 0) {\r\n std::vector<backtrace_symbol_t> symbols(count);\r\n p_get_backtrace_symbols(frames, count, &symbols[0]);\r\n for (ssize_t i = 0; i < count; i++) {\r\n\r\n Dl_info symbolInfo; \r\n dladdr(reinterpret_cast<void*>(frames[i].absolute_pc), &symbolInfo);\r\n if (symbolInfo.dli_fbase == currentLibraryAddress) {\r\n \/\/we assume, that removing current library symbols from backtrace\r\n \/\/is enough, to filter out DGL from backtrace. This implies no 3rd party\r\n \/\/libraries should be called from exporter to get here.\r\n continue;\r\n }\r\n\r\n\r\n std::stringstream line;\r\n\r\n if (!symbols[i].map_name) {\r\n line << \"<unknown module>\";\r\n } else {\r\n line << symbols[i].map_name;\r\n }\r\n line << '!';\r\n line << \"0x\" << std::hex << (int) frames[i].absolute_pc << std::dec << ' ';\r\n\r\n if (symbols[i].demangled_name) {\r\n line << symbols[i].demangled_name;\r\n } else if (symbols[i].symbol_name) {\r\n line << symbols[i].symbol_name;\r\n } else {\r\n line << \"<unknown function>\";\r\n }\r\n\r\n uint32_t pc_offset = symbols[i].relative_pc - symbols[i].relative_symbol_addr;\r\n\r\n if (pc_offset) {\r\n line << \" +\" << pc_offset;\r\n }\r\n\r\n str.push_back(line.str());\r\n }\r\n p_free_backtrace_symbols(&symbols[0], count);\r\n }\r\n }\r\n\r\n bool m_Supported;\r\n\r\n static DynamicLibrary* s_CorkscrewDSO;\r\n static t_unwind_backtrace p_unwind_backtrace;\r\n static t_get_backtrace_symbols p_get_backtrace_symbols;\r\n static t_free_backtrace_symbols p_free_backtrace_symbols;\r\n\r\n};\r\nDynamicLibrary* BackTraceImpl::s_CorkscrewDSO = nullptr;\r\nBackTraceImpl::t_unwind_backtrace BackTraceImpl::p_unwind_backtrace = nullptr;\r\nBackTraceImpl::t_get_backtrace_symbols BackTraceImpl::p_get_backtrace_symbols = nullptr;\r\nBackTraceImpl::t_free_backtrace_symbols BackTraceImpl::p_free_backtrace_symbols = nullptr;\r\n\r\n#else\r\n#ifdef _WIN32\r\n\r\n#include \"external\/StackWalker\/StackWalker.h\"\r\n#include \"Psapi.h\"\r\n#include <sstream>\r\n#include <boost\/noncopyable.hpp>\r\n\r\nclass BackTraceImpl: public BackTrace {\r\n\r\n class DGLStackWalker: public StackWalker, boost::noncopyable {\r\n public:\r\n DGLStackWalker(std::vector<std::string>& buffer): m_buffer(buffer) {\r\n MODULEINFO modInfo;\r\n if (GetModuleInformation(GetCurrentProcess(), (HMODULE)Os::getCurrentModuleHandle(), &modInfo, sizeof(modInfo))) {\r\n m_BoundsOfDGLLibrary[0] = reinterpret_cast<intptr_t>(modInfo.lpBaseOfDll);\r\n m_BoundsOfDGLLibrary[1] = reinterpret_cast<intptr_t>(reinterpret_cast<char*>(modInfo.lpBaseOfDll) + modInfo.SizeOfImage);\r\n }\r\n }\r\n\r\n virtual void OnCallstackEntry(CallstackEntryType eType, CallstackEntry &entry) {\r\n\r\n \/\/we assume, that removing current library symbols from backtrace\r\n \/\/is enough, to filter out DGL from backtrace. This implies no 3rd party\r\n \/\/libraries should be called from exporter to get here.\r\n bool outSideOfCurrentLibrary = ((intptr_t)entry.offset < m_BoundsOfDGLLibrary[0] ||\r\n (intptr_t)entry.offset >= m_BoundsOfDGLLibrary[1]);\r\n\r\n if ( (eType != lastEntry) && (entry.offset != 0) && outSideOfCurrentLibrary)\r\n {\r\n std::stringstream line;\r\n\r\n if (entry.moduleName[0] == 0 && entry.loadedImageName == 0) {\r\n line << \"<unknown module>\";\r\n } else {\r\n const char* moduleName;\r\n if (!entry.moduleName) {\r\n \/\/use full filepath\r\n moduleName = entry.loadedImageName;\r\n } else {\r\n \/\/use module name\r\n moduleName = entry.moduleName;\r\n\r\n if (entry.loadedImageName) {\r\n \/\/if we have both, use full file path to obtain file ext.\r\n const char* offset = strstr(entry.loadedImageName, entry.moduleName);\r\n while (offset) {\r\n moduleName = offset;\r\n offset = strstr(offset + 1, entry.moduleName);\r\n }\r\n }\r\n }\r\n line << moduleName;\r\n }\r\n line << '!';\r\n line << \"0x\" << std::hex << (int) entry.offset << std::dec << ' ';\r\n\r\n if (entry.undFullName[0] != 0) {\r\n line << entry.undFullName;\r\n } else if (entry.undName[0] != 0) {\r\n line << entry.undName;\r\n } else if (entry.name[0] != 0) {\r\n line << entry.name;\r\n } else {\r\n line << \"<unknown function>\";\r\n }\r\n line << ' ';\r\n\r\n if (entry.lineFileName[0] == 0) {\r\n line << \"<unknown source file>\";\r\n } else {\r\n line << entry.lineFileName;\r\n if (entry.lineNumber) {\r\n line << \" Line \" << entry.lineNumber;\r\n }\r\n }\r\n m_buffer.push_back(line.str());\r\n }\r\n StackWalker::OnCallstackEntry(eType, entry);\r\n }\r\n std::vector<std::string>& m_buffer;\r\n intptr_t m_BoundsOfDGLLibrary[2];\r\n };\r\n\r\n virtual void streamTo(std::vector<std::string>& str) override {\r\n DGLStackWalker sw(str);\r\n sw.ShowCallstack(); \r\n }\r\n};\r\n\r\n#else\r\n#ifdef __linux__\r\n\r\n#include <execinfo.h>\r\n\r\nclass BackTraceImpl: public BackTrace {\r\n virtual void streamTo(std::vector<std::string>& ret) override {\r\n std::vector<void*> buffer(20);\r\n int nptrs = backtrace(&buffer[0], buffer.size());\r\n while (nptrs > 0 && nptrs == static_cast<int>(buffer.size())) {\r\n buffer.resize(buffer.size() * 2);\r\n nptrs = backtrace(&buffer[0], buffer.size());\r\n }\r\n char** strings = backtrace_symbols(&buffer[0], buffer.size());\r\n if (!strings) {\r\n throw std::runtime_error(\"Cannot get backtrace: backtrace_symbols failed.\");\r\n }\r\n\r\n void* currentLibraryAddress = DynamicLoader::getCurrentLibraryBaseAddress();\r\n\r\n ret.resize(nptrs);\r\n\r\n int realNptrs = 0;\r\n\r\n for (size_t i = 0; i < ret.size(); i++) {\r\n Dl_info symbolInfo;\r\n dladdr(reinterpret_cast<void*>(buffer[i]), &symbolInfo);\r\n Os::info(\"XXX %x == %x\\n\", symbolInfo.dli_fbase, currentLibraryAddress);\r\n if (symbolInfo.dli_fbase == currentLibraryAddress) {\r\n \/\/we assume, that removing current library symbols from backtrace\r\n \/\/is enough, to filter out DGL from backtrace. This implies no 3rd party\r\n \/\/libraries should be called from exporter to get here.\r\n continue;\r\n }\r\n ret[realNptrs++] = strings[i];\r\n }\r\n free(strings);\r\n ret.resize(realNptrs);\r\n }\r\n};\r\n\r\n#else\r\nclass BackTraceImpl: public BackTrace {\r\n virtual void streamTo(std::vector<std::string>&) override {\r\n throw std::runtime_error(\"Backtrace support not implemented on this platform.\");\r\n }\r\n};\r\n#endif\r\n#endif\r\n#endif\r\n\r\nstd::shared_ptr<BackTrace> BackTrace::Get() {\r\n return std::make_shared<BackTraceImpl>();\r\n}\r\n<|endoftext|>"} {"text":"<commit_before>\/** @file\n @brief Comprehensive example: Implementation of a dummy Hardware Detect\n Callback that creates a dummy device when it is \"detected\"\n\n @date 2014\n\n @author\n Sensics, Inc.\n <http:\/\/sensics.com\/osvr>\n*\/\n\n\/\/ Copyright 2014 Sensics, Inc.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n\/\/ Internal Includes\n#include <osvr\/PluginKit\/PluginKit.h>\n#include <osvr\/PluginKit\/AnalogInterfaceC.h>\n#include <osvr\/PluginKit\/ButtonInterfaceC.h>\n#include <osvr\/PluginKit\/TrackerInterfaceC.h>\n\n\/\/ Generated JSON header file\n#include \"NodOSVR.h\"\n#include \"NodPlugin.h\"\n\n#pragma comment(lib, \"OpenSpatialDll.lib\")\n\n\/\/ Library\/third-party includes\n\/\/ - none\n\n\/\/ Standard includes\n#include <iostream>\n\n\/\/ Global device count for path incrementation\nint deviceCount = 0;\n\n\/\/ Anonymous namespace to avoid symbol collision\nnamespace {\n\nclass Backspin {\n public:\n Backspin(OSVR_PluginRegContext ctx) {\n \/\/\/ Create the initialization options\n OSVR_DeviceInitOptions opts = osvrDeviceCreateInitOptions(ctx);\n\n \/\/\/ config channels\n osvrDeviceAnalogConfigure(opts, &m_analog, 3);\n osvrDeviceButtonConfigure(opts, &m_button, 10);\n osvrDeviceTrackerConfigure(opts, &m_orientation);\n \/\/\/ Create the device token with the options\n m_dev.initAsync(ctx, std::to_string(deviceCount).c_str(), opts);\n\n \/\/\/ Send JSON descriptor\n m_dev.sendJsonDescriptor(NodOSVR);\n\n \/\/\/ Register update callback\n m_dev.registerUpdateCallback(this);\n \n \/\/ initialize orientation\n m_orientationval.data[0] = 0.0;\n m_orientationval.data[1] = 0.0;\n m_orientationval.data[2] = 0.0;\n m_orientationval.data[3] = 0.0;\n }\n int flip = 1;\n OSVR_ReturnCode update() {\n\n \/\/\/ send trigger, joystick x and joystick y\n osvrDeviceAnalogSetValues(m_dev, m_analog, m_analogval, 3);\n\n \/\/ Don't send the first value of the button (plugin was sending 0 when it started up)\n if (buttonPressed)\n {\n \/\/send all buttons (proto1 10 buttons)\n osvrDeviceButtonSetValues(m_dev, m_button, m_buttons, 10);\n }\n\n \/\/ send orientation quaternion and 0,0,0 for position (could just send orientation, but\n \/\/ pose is expected by most programs\n OSVR_Pose3 pose;\n pose.rotation = m_orientationval;\n pose.translation = { 0,0,0 };\n osvrDeviceTrackerSendPose(m_dev, m_orientation, &pose, 0);\n\n return OSVR_RETURN_SUCCESS;\n }\n\n OSVR_AnalogState m_analogval[3] = { 255, 128, 128 };\n OSVR_ButtonState m_buttons[10] = { 0,0,0,0,0,0,0,0,0,0 };\n OSVR_OrientationState m_orientationval;\n bool buttonPressed = false;\n private:\n osvr::pluginkit::DeviceToken m_dev;\n OSVR_AnalogDeviceInterface m_analog;\n OSVR_ButtonDeviceInterface m_button;\n OSVR_TrackerDeviceInterface m_orientation;\n};\n\nstd::vector<Backspin*> devices;\n\nvoid euler(const float& pitch, const float& roll, const float& yaw, double* mData)\n{\n const float sinHalfYaw = (float)sin(yaw \/ 2.0f);\n const float cosHalfYaw = (float)cos(yaw \/ 2.0f);\n const float sinHalfPitch = (float)sin(pitch \/ 2.0f);\n const float cosHalfPitch = (float)cos(pitch \/ 2.0f);\n const float sinHalfRoll = (float)sin(roll \/ 2.0f);\n const float cosHalfRoll = (float)cos(roll \/ 2.0f);\n\n mData[0] = -cosHalfRoll * sinHalfPitch * sinHalfYaw\n + cosHalfPitch * cosHalfYaw * sinHalfRoll;\n mData[1] = cosHalfRoll * cosHalfYaw * sinHalfPitch\n + sinHalfRoll * cosHalfPitch * sinHalfYaw;\n mData[2] = cosHalfRoll * cosHalfPitch * sinHalfYaw\n - sinHalfRoll * cosHalfYaw * sinHalfPitch;\n mData[3] = cosHalfRoll * cosHalfPitch * cosHalfYaw\n + sinHalfRoll * sinHalfPitch * sinHalfYaw;\n}\n\nvoid OpenSpatialEventFired(NodEvent ev)\n{\n if (ev.type == EventType::ServiceReady)\n {\n std::cout << \"[NOD PLUGIN] Service Ready\" << std::endl;\n NodSubscribe(Modality::GameControlMode, \"nod2-004008\");\n NodSubscribe(Modality::ButtonMode, \"nod2-004008\");\n NodSubscribe(Modality::EulerMode, \"nod2-004008\");\n }\n if (ev.type == EventType::AnalogData)\n {\n Backspin* dev = devices.at(0);\n dev->m_analogval[0] = ev.trigger;\n dev->m_analogval[1] = ev.x;\n dev->m_analogval[2] = ev.y;\n }\n if (ev.type == EventType::Button)\n {\n Backspin* dev = devices.at(0);\n int index = ev.buttonID;\n dev->buttonPressed = true;\n dev->m_buttons[index] = (ev.buttonState == UP) ? 0 : 1;\n }\n if (ev.type == EventType::EulerAngles)\n {\n Backspin* dev = devices.at(0);\n double val[4];\n euler(ev.pitch, ev.roll, ev.yaw, val);\n dev->m_orientationval.data[0] = val[0];\n dev->m_orientationval.data[1] = val[1];\n dev->m_orientationval.data[2] = val[2];\n dev->m_orientationval.data[3] = val[3];\n }\n}\n\nclass HardwareDetection {\n public:\n HardwareDetection() : m_found(false) { NodInitialize(OpenSpatialEventFired); }\n OSVR_ReturnCode operator()(OSVR_PluginRegContext ctx) {\n std::cout << \"[NOD PLUGIN] Got a hardware detection request\" << std::endl;\n if (!m_found)\n {\n if (NodNumRings() > 0)\n {\n std::cout << \"[NOD PLUGIN] found device\" << std::endl;\n for (int i = 0; i < NodNumRings(); i++)\n {\n Backspin* dev = new Backspin(ctx);\n devices.push_back(dev);\n osvr::pluginkit::registerObjectForDeletion(\n ctx, dev);\n m_found = true;\n }\n }\n else\n {\n std::cout << \"[NOD PLUGIN]: no devices found\" << std::endl;\n }\n }\n return OSVR_RETURN_SUCCESS;\n }\n\n private:\n \/\/\/ @brief Have we found our device yet? (this limits the plugin to one\n \/\/\/ instance)\n bool m_found;\n};\n} \/\/ namespace\n\nOSVR_PLUGIN(com_osvr_example_selfcontained) {\n osvr::pluginkit::PluginContext context(ctx);\n\n \/\/\/ Register a detection callback function object.\n context.registerHardwareDetectCallback(new HardwareDetection());\n\n return OSVR_RETURN_SUCCESS;\n}\n<commit_msg>Fixes + Multiple devices<commit_after>\/** @file\n @brief Comprehensive example: Implementation of a dummy Hardware Detect\n Callback that creates a dummy device when it is \"detected\"\n\n @date 2014\n\n @author\n Sensics, Inc.\n <http:\/\/sensics.com\/osvr>\n*\/\n\n\/\/ Copyright 2014 Sensics, Inc.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n\/\/ Internal Includes\n#include <osvr\/PluginKit\/PluginKit.h>\n#include <osvr\/PluginKit\/AnalogInterfaceC.h>\n#include <osvr\/PluginKit\/ButtonInterfaceC.h>\n#include <osvr\/PluginKit\/TrackerInterfaceC.h>\n\n\/\/ Generated JSON header file\n#include \"NodOSVR.h\"\n#include \"NodPlugin.h\"\n\n#pragma comment(lib, \"OpenSpatialDll.lib\")\n\n\/\/ Library\/third-party includes\n\/\/ - none\n\n\/\/ Standard includes\n#include <iostream>\n\n\/\/ Global device count for path incrementation\nint deviceCount = 0;\nstd::vector<Backspin*> devices;\n\n\/\/ Anonymous namespace to avoid symbol collision\nnamespace {\n\nclass Backspin {\n public:\n Backspin(OSVR_PluginRegContext ctx) {\n \/\/\/ Create the initialization options\n OSVR_DeviceInitOptions opts = osvrDeviceCreateInitOptions(ctx);\n\n \/\/\/ config channels\n osvrDeviceAnalogConfigure(opts, &m_analog, 3);\n osvrDeviceButtonConfigure(opts, &m_button, 10);\n osvrDeviceTrackerConfigure(opts, &m_orientation);\n \/\/\/ Create the device token with the options\n m_dev.initAsync(ctx, std::to_string(deviceCount).c_str(), opts);\n deviceCount++;\n\n \/\/\/ Send JSON descriptor\n m_dev.sendJsonDescriptor(NodOSVR);\n\n \/\/\/ Register update callback\n m_dev.registerUpdateCallback(this);\n \n \/\/ initialize orientation\n m_orientationval.data[0] = 0.0;\n m_orientationval.data[1] = 0.0;\n m_orientationval.data[2] = 0.0;\n m_orientationval.data[3] = 0.0;\n }\n int flip = 1;\n OSVR_ReturnCode update() {\n\n \/\/\/ send trigger, joystick x and joystick y\n osvrDeviceAnalogSetValues(m_dev, m_analog, m_analogval, 3);\n\n \/\/ Don't send the first value of the button (plugin was sending 0 when it started up)\n if (buttonPressed)\n {\n \/\/send all buttons (proto1 10 buttons)\n osvrDeviceButtonSetValues(m_dev, m_button, m_buttons, 10);\n }\n\n \/\/ send orientation quaternion and 0,0,0 for position (could just send orientation, but\n \/\/ pose is expected by most programs\n OSVR_Pose3 pose;\n pose.rotation = m_orientationval;\n pose.translation = { 0,0,0 };\n osvrDeviceTrackerSendPose(m_dev, m_orientation, &pose, 0);\n\n return OSVR_RETURN_SUCCESS;\n }\n\n OSVR_AnalogState m_analogval[3] = { 255, 128, 128 };\n OSVR_ButtonState m_buttons[10] = { 0,0,0,0,0,0,0,0,0,0 };\n OSVR_OrientationState m_orientationval;\n bool buttonPressed = false;\n private:\n osvr::pluginkit::DeviceToken m_dev;\n OSVR_AnalogDeviceInterface m_analog;\n OSVR_ButtonDeviceInterface m_button;\n OSVR_TrackerDeviceInterface m_orientation;\n};\n\n\nvoid euler(const float& pitch, const float& roll, const float& yaw, double* mData)\n{\n const float sinHalfYaw = (float)sin(yaw \/ 2.0f);\n const float cosHalfYaw = (float)cos(yaw \/ 2.0f);\n const float sinHalfPitch = (float)sin(pitch \/ 2.0f);\n const float cosHalfPitch = (float)cos(pitch \/ 2.0f);\n const float sinHalfRoll = (float)sin(roll \/ 2.0f);\n const float cosHalfRoll = (float)cos(roll \/ 2.0f);\n\n mData[0] = -cosHalfRoll * sinHalfPitch * sinHalfYaw\n + cosHalfPitch * cosHalfYaw * sinHalfRoll;\n mData[1] = cosHalfRoll * cosHalfYaw * sinHalfPitch\n + sinHalfRoll * cosHalfPitch * sinHalfYaw;\n mData[2] = cosHalfRoll * cosHalfPitch * sinHalfYaw\n - sinHalfRoll * cosHalfYaw * sinHalfPitch;\n mData[3] = cosHalfRoll * cosHalfPitch * cosHalfYaw\n + sinHalfRoll * sinHalfPitch * sinHalfYaw;\n}\n\nvoid OpenSpatialEventFired(NodEvent ev)\n{\n if (ev.type == EventType::ServiceReady)\n {\n std::cout << \"[NOD PLUGIN] Service Ready\" << std::endl;\n for (int i = 0; i < NodNumRings(); i++)\n {\n NodSubscribe(Modality::GameControlMode, NodGetRingName(i));\n NodSubscribe(Modality::ButtonMode, NodGetRingName(i));\n NodSubscribe(Modality::EulerMode, NodGetRingName(i));\n }\n }\n if (ev.type == EventType::AnalogData)\n {\n Backspin* dev = devices.at(ev.sender);\n dev->m_analogval[0] = ev.trigger;\n dev->m_analogval[1] = ev.x;\n dev->m_analogval[2] = ev.y;\n }\n if (ev.type == EventType::Button)\n {\n Backspin* dev = devices.at(ev.sender);\n int index = ev.buttonID;\n dev->buttonPressed = true;\n dev->m_buttons[index] = (ev.buttonState == UP) ? 0 : 1;\n }\n if (ev.type == EventType::EulerAngles)\n {\n Backspin* dev = devices.at(ev.sender);\n double val[4];\n euler(ev.pitch, ev.roll, ev.yaw, val);\n dev->m_orientationval.data[0] = val[0];\n dev->m_orientationval.data[1] = val[1];\n dev->m_orientationval.data[2] = val[2];\n dev->m_orientationval.data[3] = val[3];\n }\n}\n\nclass HardwareDetection {\n public:\n HardwareDetection() : m_found(false) { NodInitialize(OpenSpatialEventFired); }\n OSVR_ReturnCode operator()(OSVR_PluginRegContext ctx) {\n std::cout << \"[NOD PLUGIN] Got a hardware detection request\" << std::endl;\n if (!m_found)\n {\n if (NodNumRings() > 0)\n {\n std::cout << \"[NOD PLUGIN] found device\" << std::endl;\n for (int i = 0; i < NodNumRings(); i++)\n {\n Backspin* dev = new Backspin(ctx);\n devices.push_back(dev);\n osvr::pluginkit::registerObjectForDeletion(\n ctx, dev);\n m_found = true;\n }\n }\n else\n {\n std::cout << \"[NOD PLUGIN]: no devices found\" << std::endl;\n }\n }\n return OSVR_RETURN_SUCCESS;\n }\n\n private:\n \/\/\/ @brief Have we found our device yet? (this limits the plugin to one\n \/\/\/ instance)\n bool m_found;\n};\n} \/\/ namespace\n\nOSVR_PLUGIN(com_osvr_example_selfcontained) {\n osvr::pluginkit::PluginContext context(ctx);\n\n \/\/\/ Register a detection callback function object.\n context.registerHardwareDetectCallback(new HardwareDetection());\n\n return OSVR_RETURN_SUCCESS;\n}\n<|endoftext|>"} {"text":"<commit_before>\/**\n * The MIT License (MIT)\n *\n * Copyright (c) 2016 by Daniel Eichhorn\n * Copyright (c) 2016 by Fabrice Weinberg\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n *\n *\/\n\n#include \"OLEDDisplayUi.h\"\n\nOLEDDisplayUi::OLEDDisplayUi(OLEDDisplay *display) {\n this->display = display;\n}\n\nvoid OLEDDisplayUi::init() {\n this->display->init();\n}\n\nvoid OLEDDisplayUi::setTargetFPS(uint8_t fps){\n float oldInterval = this->updateInterval;\n this->updateInterval = ((float) 1.0 \/ (float) fps) * 1000;\n\n \/\/ Calculate new ticksPerFrame\n float changeRatio = oldInterval \/ (float) this->updateInterval;\n this->ticksPerFrame *= changeRatio;\n this->ticksPerTransition *= changeRatio;\n}\n\n\/\/ -\/------ Automatic controll ------\\-\n\nvoid OLEDDisplayUi::enableAutoTransition(){\n this->autoTransition = true;\n}\nvoid OLEDDisplayUi::disableAutoTransition(){\n this->autoTransition = false;\n}\nvoid OLEDDisplayUi::setAutoTransitionForwards(){\n this->state.frameTransitionDirection = 1;\n this->lastTransitionDirection = 1;\n}\nvoid OLEDDisplayUi::setAutoTransitionBackwards(){\n this->state.frameTransitionDirection = -1;\n this->lastTransitionDirection = -1;\n}\nvoid OLEDDisplayUi::setTimePerFrame(uint16_t time){\n this->ticksPerFrame = (int) ( (float) time \/ (float) updateInterval);\n}\nvoid OLEDDisplayUi::setTimePerTransition(uint16_t time){\n this->ticksPerTransition = (int) ( (float) time \/ (float) updateInterval);\n}\n\n\/\/ -\/------ Customize indicator position and style -------\\-\nvoid OLEDDisplayUi::enableIndicator(){\n this->state.isIndicatorDrawen = true;\n}\n\nvoid OLEDDisplayUi::disableIndicator(){\n this->state.isIndicatorDrawen = false;\n}\n\nvoid OLEDDisplayUi::enableAllIndicators(){\n this->shouldDrawIndicators = true;\n}\n\nvoid OLEDDisplayUi::disableAllIndicators(){\n this->shouldDrawIndicators = false;\n}\n\nvoid OLEDDisplayUi::setIndicatorPosition(IndicatorPosition pos) {\n this->indicatorPosition = pos;\n}\nvoid OLEDDisplayUi::setIndicatorDirection(IndicatorDirection dir) {\n this->indicatorDirection = dir;\n}\nvoid OLEDDisplayUi::setActiveSymbol(const char* symbol) {\n this->activeSymbol = symbol;\n}\nvoid OLEDDisplayUi::setInactiveSymbol(const char* symbol) {\n this->inactiveSymbol = symbol;\n}\n\n\n\/\/ -\/----- Frame settings -----\\-\nvoid OLEDDisplayUi::setFrameAnimation(AnimationDirection dir) {\n this->frameAnimationDirection = dir;\n}\nvoid OLEDDisplayUi::setFrames(FrameCallback* frameFunctions, uint8_t frameCount) {\n this->frameFunctions = frameFunctions;\n this->frameCount = frameCount;\n this->resetState();\n}\n\n\/\/ -\/----- Overlays ------\\-\nvoid OLEDDisplayUi::setOverlays(OverlayCallback* overlayFunctions, uint8_t overlayCount){\n this->overlayFunctions = overlayFunctions;\n this->overlayCount = overlayCount;\n}\n\n\/\/ -\/----- Loading Process -----\\-\n\nvoid OLEDDisplayUi::runLoadingProcess(LoadingStage* stages, uint8_t stagesCount) {\n uint8_t progress = 0;\n uint8_t increment = 100 \/ stagesCount;\n\n for (uint8_t i = 0; i < stagesCount; i++) {\n display->clear();\n this->loadingDrawFunction(this->display, &stages[i], progress);\n display->display();\n\n stages[i].callback();\n\n progress += increment;\n yield();\n }\n\n display->clear();\n this->loadingDrawFunction(this->display, &stages[stagesCount-1], progress);\n display->display();\n\n delay(150);\n}\n\n\/\/ -\/----- Manuel control -----\\-\nvoid OLEDDisplayUi::nextFrame() {\n if (this->state.frameState != IN_TRANSITION) {\n this->state.manuelControll = true;\n this->state.frameState = IN_TRANSITION;\n this->state.ticksSinceLastStateSwitch = 0;\n this->lastTransitionDirection = this->state.frameTransitionDirection;\n this->state.frameTransitionDirection = 1;\n }\n}\nvoid OLEDDisplayUi::previousFrame() {\n if (this->state.frameState != IN_TRANSITION) {\n this->state.manuelControll = true;\n this->state.frameState = IN_TRANSITION;\n this->state.ticksSinceLastStateSwitch = 0;\n this->lastTransitionDirection = this->state.frameTransitionDirection;\n this->state.frameTransitionDirection = -1;\n }\n}\n\nvoid OLEDDisplayUi::switchToFrame(uint8_t frame) {\n if (frame >= this->frameCount) return;\n this->state.ticksSinceLastStateSwitch = 0;\n if (frame == this->state.currentFrame) return;\n this->state.frameState = FIXED;\n this->state.currentFrame = frame;\n this->state.isIndicatorDrawen = true;\n}\n\nvoid OLEDDisplayUi::transitionToFrame(uint8_t frame) {\n if (frame >= this->frameCount) return;\n this->state.ticksSinceLastStateSwitch = 0;\n if (frame == this->state.currentFrame) return;\n this->nextFrameNumber = frame;\n this->lastTransitionDirection = this->state.frameTransitionDirection;\n this->state.manuelControll = true;\n this->state.frameState = IN_TRANSITION;\n this->state.frameTransitionDirection = frame < this->state.currentFrame ? -1 : 1;\n}\n\n\n\/\/ -\/----- State information -----\\-\nOLEDDisplayUiState* OLEDDisplayUi::getUiState(){\n return &this->state;\n}\n\n\nint8_t OLEDDisplayUi::update(){\n long frameStart = millis();\n int8_t timeBudget = this->updateInterval - (frameStart - this->state.lastUpdate);\n if ( timeBudget <= 0) {\n \/\/ Implement frame skipping to ensure time budget is keept\n if (this->autoTransition && this->state.lastUpdate != 0) this->state.ticksSinceLastStateSwitch += ceil(-timeBudget \/ this->updateInterval);\n\n this->state.lastUpdate = frameStart;\n this->tick();\n }\n return this->updateInterval - (millis() - frameStart);\n}\n\n\nvoid OLEDDisplayUi::tick() {\n this->state.ticksSinceLastStateSwitch++;\n\n switch (this->state.frameState) {\n case IN_TRANSITION:\n if (this->state.ticksSinceLastStateSwitch >= this->ticksPerTransition){\n this->state.frameState = FIXED;\n this->state.currentFrame = getNextFrameNumber();\n this->state.ticksSinceLastStateSwitch = 0;\n this->nextFrameNumber = -1;\n }\n break;\n case FIXED:\n \/\/ Revert manuelControll\n if (this->state.manuelControll) {\n this->state.frameTransitionDirection = this->lastTransitionDirection;\n this->state.manuelControll = false;\n }\n if (this->state.ticksSinceLastStateSwitch >= this->ticksPerFrame){\n if (this->autoTransition){\n this->state.frameState = IN_TRANSITION;\n }\n this->state.ticksSinceLastStateSwitch = 0;\n }\n break;\n }\n\n this->display->clear();\n this->drawFrame();\n if (shouldDrawIndicators) {\n this->drawIndicator();\n }\n this->drawOverlays();\n this->display->display();\n}\n\nvoid OLEDDisplayUi::resetState() {\n this->state.lastUpdate = 0;\n this->state.ticksSinceLastStateSwitch = 0;\n this->state.frameState = FIXED;\n this->state.currentFrame = 0;\n this->state.isIndicatorDrawen = true;\n}\n\nvoid OLEDDisplayUi::drawFrame(){\n switch (this->state.frameState){\n case IN_TRANSITION: {\n float progress = (float) this->state.ticksSinceLastStateSwitch \/ (float) this->ticksPerTransition;\n int16_t x, y, x1, y1;\n switch(this->frameAnimationDirection){\n case SLIDE_LEFT:\n x = -128 * progress;\n y = 0;\n x1 = x + 128;\n y1 = 0;\n break;\n case SLIDE_RIGHT:\n x = 128 * progress;\n y = 0;\n x1 = x - 128;\n y1 = 0;\n break;\n case SLIDE_UP:\n x = 0;\n y = -64 * progress;\n x1 = 0;\n y1 = y + 64;\n break;\n case SLIDE_DOWN:\n x = 0;\n y = 64 * progress;\n x1 = 0;\n y1 = y - 64;\n break;\n }\n\n \/\/ Invert animation if direction is reversed.\n int8_t dir = this->state.frameTransitionDirection >= 0 ? 1 : -1;\n x *= dir; y *= dir; x1 *= dir; y1 *= dir;\n\n bool drawenCurrentFrame;\n\n\n \/\/ Prope each frameFunction for the indicator Drawen state\n this->enableIndicator();\n (this->frameFunctions[this->state.currentFrame])(this->display, &this->state, x, y);\n drawenCurrentFrame = this->state.isIndicatorDrawen;\n\n this->enableIndicator();\n (this->frameFunctions[this->getNextFrameNumber()])(this->display, &this->state, x1, y1);\n\n \/\/ Build up the indicatorDrawState\n if (drawenCurrentFrame && !this->state.isIndicatorDrawen) {\n \/\/ Drawen now but not next\n this->indicatorDrawState = 2;\n } else if (!drawenCurrentFrame && this->state.isIndicatorDrawen) {\n \/\/ Not drawen now but next\n this->indicatorDrawState = 1;\n } else if (!drawenCurrentFrame && !this->state.isIndicatorDrawen) {\n \/\/ Not drawen in both frames\n this->indicatorDrawState = 3;\n }\n\n \/\/ If the indicator isn't draw in the current frame\n \/\/ reflect it in state.isIndicatorDrawen\n if (!drawenCurrentFrame) this->state.isIndicatorDrawen = false;\n\n break;\n }\n case FIXED:\n \/\/ Always assume that the indicator is drawn!\n \/\/ And set indicatorDrawState to \"not known yet\"\n this->indicatorDrawState = 0;\n this->enableIndicator();\n (this->frameFunctions[this->state.currentFrame])(this->display, &this->state, 0, 0);\n break;\n }\n}\n\nvoid OLEDDisplayUi::drawIndicator() {\n\n \/\/ Only draw if the indicator is invisible\n \/\/ for both frames or\n \/\/ the indiactor is shown and we are IN_TRANSITION\n if (this->indicatorDrawState == 3 || (!this->state.isIndicatorDrawen && this->state.frameState != IN_TRANSITION)) {\n return;\n }\n\n uint8_t posOfHighlightFrame;\n float indicatorFadeProgress = 0;\n\n \/\/ if the indicator needs to be slided in we want to\n \/\/ highlight the next frame in the transition\n uint8_t frameToHighlight = this->indicatorDrawState == 1 ? this->getNextFrameNumber() : this->state.currentFrame;\n\n \/\/ Calculate the frame that needs to be highlighted\n \/\/ based on the Direction the indiactor is drawn\n switch (this->indicatorDirection){\n case LEFT_RIGHT:\n posOfHighlightFrame = frameToHighlight;\n break;\n case RIGHT_LEFT:\n posOfHighlightFrame = this->frameCount - frameToHighlight;\n break;\n }\n\n switch (this->indicatorDrawState) {\n case 1: \/\/ Indicator was not drawn in this frame but will be in next\n \/\/ Slide IN\n indicatorFadeProgress = 1 - ((float) this->state.ticksSinceLastStateSwitch \/ (float) this->ticksPerTransition);\n break;\n case 2: \/\/ Indicator was drawn in this frame but not in next\n \/\/ Slide OUT\n indicatorFadeProgress = ((float) this->state.ticksSinceLastStateSwitch \/ (float) this->ticksPerTransition);\n break;\n }\n\n uint16_t frameStartPos = (12 * frameCount \/ 2);\n const char *image;\n uint16_t x,y;\n for (byte i = 0; i < this->frameCount; i++) {\n\n switch (this->indicatorPosition){\n case TOP:\n y = 0 - (8 * indicatorFadeProgress);\n x = 64 - frameStartPos + 12 * i;\n break;\n case BOTTOM:\n y = 56 + (8 * indicatorFadeProgress);\n x = 64 - frameStartPos + 12 * i;\n break;\n case RIGHT:\n x = 120 + (8 * indicatorFadeProgress);\n y = 32 - frameStartPos + 12 * i;\n break;\n case LEFT:\n x = 0 - (8 * indicatorFadeProgress);\n y = 32 - frameStartPos + 12 * i;\n break;\n }\n\n if (posOfHighlightFrame == i) {\n image = this->activeSymbol;\n } else {\n image = this->inactiveSymbol;\n }\n\n this->display->drawFastImage(x, y, 8, 8, image);\n }\n}\n\nvoid OLEDDisplayUi::drawOverlays() {\n for (uint8_t i=0;i<this->overlayCount;i++){\n (this->overlayFunctions[i])(this->display, &this->state);\n }\n}\n\nuint8_t OLEDDisplayUi::getNextFrameNumber(){\n if (this->nextFrameNumber != -1) return this->nextFrameNumber;\n return (this->state.currentFrame + this->frameCount + this->state.frameTransitionDirection) % this->frameCount;\n}\n<commit_msg>Use screen geometry for transitions and indicators<commit_after>\/**\n * The MIT License (MIT)\n *\n * Copyright (c) 2016 by Daniel Eichhorn\n * Copyright (c) 2016 by Fabrice Weinberg\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n *\n *\/\n\n#include \"OLEDDisplayUi.h\"\n\nOLEDDisplayUi::OLEDDisplayUi(OLEDDisplay *display) {\n this->display = display;\n}\n\nvoid OLEDDisplayUi::init() {\n this->display->init();\n}\n\nvoid OLEDDisplayUi::setTargetFPS(uint8_t fps){\n float oldInterval = this->updateInterval;\n this->updateInterval = ((float) 1.0 \/ (float) fps) * 1000;\n\n \/\/ Calculate new ticksPerFrame\n float changeRatio = oldInterval \/ (float) this->updateInterval;\n this->ticksPerFrame *= changeRatio;\n this->ticksPerTransition *= changeRatio;\n}\n\n\/\/ -\/------ Automatic controll ------\\-\n\nvoid OLEDDisplayUi::enableAutoTransition(){\n this->autoTransition = true;\n}\nvoid OLEDDisplayUi::disableAutoTransition(){\n this->autoTransition = false;\n}\nvoid OLEDDisplayUi::setAutoTransitionForwards(){\n this->state.frameTransitionDirection = 1;\n this->lastTransitionDirection = 1;\n}\nvoid OLEDDisplayUi::setAutoTransitionBackwards(){\n this->state.frameTransitionDirection = -1;\n this->lastTransitionDirection = -1;\n}\nvoid OLEDDisplayUi::setTimePerFrame(uint16_t time){\n this->ticksPerFrame = (int) ( (float) time \/ (float) updateInterval);\n}\nvoid OLEDDisplayUi::setTimePerTransition(uint16_t time){\n this->ticksPerTransition = (int) ( (float) time \/ (float) updateInterval);\n}\n\n\/\/ -\/------ Customize indicator position and style -------\\-\nvoid OLEDDisplayUi::enableIndicator(){\n this->state.isIndicatorDrawen = true;\n}\n\nvoid OLEDDisplayUi::disableIndicator(){\n this->state.isIndicatorDrawen = false;\n}\n\nvoid OLEDDisplayUi::enableAllIndicators(){\n this->shouldDrawIndicators = true;\n}\n\nvoid OLEDDisplayUi::disableAllIndicators(){\n this->shouldDrawIndicators = false;\n}\n\nvoid OLEDDisplayUi::setIndicatorPosition(IndicatorPosition pos) {\n this->indicatorPosition = pos;\n}\nvoid OLEDDisplayUi::setIndicatorDirection(IndicatorDirection dir) {\n this->indicatorDirection = dir;\n}\nvoid OLEDDisplayUi::setActiveSymbol(const char* symbol) {\n this->activeSymbol = symbol;\n}\nvoid OLEDDisplayUi::setInactiveSymbol(const char* symbol) {\n this->inactiveSymbol = symbol;\n}\n\n\n\/\/ -\/----- Frame settings -----\\-\nvoid OLEDDisplayUi::setFrameAnimation(AnimationDirection dir) {\n this->frameAnimationDirection = dir;\n}\nvoid OLEDDisplayUi::setFrames(FrameCallback* frameFunctions, uint8_t frameCount) {\n this->frameFunctions = frameFunctions;\n this->frameCount = frameCount;\n this->resetState();\n}\n\n\/\/ -\/----- Overlays ------\\-\nvoid OLEDDisplayUi::setOverlays(OverlayCallback* overlayFunctions, uint8_t overlayCount){\n this->overlayFunctions = overlayFunctions;\n this->overlayCount = overlayCount;\n}\n\n\/\/ -\/----- Loading Process -----\\-\n\nvoid OLEDDisplayUi::runLoadingProcess(LoadingStage* stages, uint8_t stagesCount) {\n uint8_t progress = 0;\n uint8_t increment = 100 \/ stagesCount;\n\n for (uint8_t i = 0; i < stagesCount; i++) {\n display->clear();\n this->loadingDrawFunction(this->display, &stages[i], progress);\n display->display();\n\n stages[i].callback();\n\n progress += increment;\n yield();\n }\n\n display->clear();\n this->loadingDrawFunction(this->display, &stages[stagesCount-1], progress);\n display->display();\n\n delay(150);\n}\n\n\/\/ -\/----- Manuel control -----\\-\nvoid OLEDDisplayUi::nextFrame() {\n if (this->state.frameState != IN_TRANSITION) {\n this->state.manuelControll = true;\n this->state.frameState = IN_TRANSITION;\n this->state.ticksSinceLastStateSwitch = 0;\n this->lastTransitionDirection = this->state.frameTransitionDirection;\n this->state.frameTransitionDirection = 1;\n }\n}\nvoid OLEDDisplayUi::previousFrame() {\n if (this->state.frameState != IN_TRANSITION) {\n this->state.manuelControll = true;\n this->state.frameState = IN_TRANSITION;\n this->state.ticksSinceLastStateSwitch = 0;\n this->lastTransitionDirection = this->state.frameTransitionDirection;\n this->state.frameTransitionDirection = -1;\n }\n}\n\nvoid OLEDDisplayUi::switchToFrame(uint8_t frame) {\n if (frame >= this->frameCount) return;\n this->state.ticksSinceLastStateSwitch = 0;\n if (frame == this->state.currentFrame) return;\n this->state.frameState = FIXED;\n this->state.currentFrame = frame;\n this->state.isIndicatorDrawen = true;\n}\n\nvoid OLEDDisplayUi::transitionToFrame(uint8_t frame) {\n if (frame >= this->frameCount) return;\n this->state.ticksSinceLastStateSwitch = 0;\n if (frame == this->state.currentFrame) return;\n this->nextFrameNumber = frame;\n this->lastTransitionDirection = this->state.frameTransitionDirection;\n this->state.manuelControll = true;\n this->state.frameState = IN_TRANSITION;\n this->state.frameTransitionDirection = frame < this->state.currentFrame ? -1 : 1;\n}\n\n\n\/\/ -\/----- State information -----\\-\nOLEDDisplayUiState* OLEDDisplayUi::getUiState(){\n return &this->state;\n}\n\n\nint8_t OLEDDisplayUi::update(){\n long frameStart = millis();\n int8_t timeBudget = this->updateInterval - (frameStart - this->state.lastUpdate);\n if ( timeBudget <= 0) {\n \/\/ Implement frame skipping to ensure time budget is keept\n if (this->autoTransition && this->state.lastUpdate != 0) this->state.ticksSinceLastStateSwitch += ceil(-timeBudget \/ this->updateInterval);\n\n this->state.lastUpdate = frameStart;\n this->tick();\n }\n return this->updateInterval - (millis() - frameStart);\n}\n\n\nvoid OLEDDisplayUi::tick() {\n this->state.ticksSinceLastStateSwitch++;\n\n switch (this->state.frameState) {\n case IN_TRANSITION:\n if (this->state.ticksSinceLastStateSwitch >= this->ticksPerTransition){\n this->state.frameState = FIXED;\n this->state.currentFrame = getNextFrameNumber();\n this->state.ticksSinceLastStateSwitch = 0;\n this->nextFrameNumber = -1;\n }\n break;\n case FIXED:\n \/\/ Revert manuelControll\n if (this->state.manuelControll) {\n this->state.frameTransitionDirection = this->lastTransitionDirection;\n this->state.manuelControll = false;\n }\n if (this->state.ticksSinceLastStateSwitch >= this->ticksPerFrame){\n if (this->autoTransition){\n this->state.frameState = IN_TRANSITION;\n }\n this->state.ticksSinceLastStateSwitch = 0;\n }\n break;\n }\n\n this->display->clear();\n this->drawFrame();\n if (shouldDrawIndicators) {\n this->drawIndicator();\n }\n this->drawOverlays();\n this->display->display();\n}\n\nvoid OLEDDisplayUi::resetState() {\n this->state.lastUpdate = 0;\n this->state.ticksSinceLastStateSwitch = 0;\n this->state.frameState = FIXED;\n this->state.currentFrame = 0;\n this->state.isIndicatorDrawen = true;\n}\n\nvoid OLEDDisplayUi::drawFrame(){\n switch (this->state.frameState){\n case IN_TRANSITION: {\n float progress = (float) this->state.ticksSinceLastStateSwitch \/ (float) this->ticksPerTransition;\n int16_t x, y, x1, y1;\n switch(this->frameAnimationDirection){\n case SLIDE_LEFT:\n x = -(this->display->getWidth()) * progress;\n y = 0;\n x1 = x + this->display->getWidth();\n y1 = 0;\n break;\n case SLIDE_RIGHT:\n x = this->display->getWidth() * progress;\n y = 0;\n x1 = x - this->display->getWidth();\n y1 = 0;\n break;\n case SLIDE_UP:\n x = 0;\n y = -(this->display->getHeight()) * progress;\n x1 = 0;\n y1 = y + (this->display->getHeight());\n break;\n case SLIDE_DOWN:\n x = 0;\n y = (this->display->getHeight()) * progress;\n x1 = 0;\n y1 = y - (this->display->getHeight());\n break;\n }\n\n \/\/ Invert animation if direction is reversed.\n int8_t dir = this->state.frameTransitionDirection >= 0 ? 1 : -1;\n x *= dir; y *= dir; x1 *= dir; y1 *= dir;\n\n bool drawenCurrentFrame;\n\n\n \/\/ Prope each frameFunction for the indicator Drawen state\n this->enableIndicator();\n (this->frameFunctions[this->state.currentFrame])(this->display, &this->state, x, y);\n drawenCurrentFrame = this->state.isIndicatorDrawen;\n\n this->enableIndicator();\n (this->frameFunctions[this->getNextFrameNumber()])(this->display, &this->state, x1, y1);\n\n \/\/ Build up the indicatorDrawState\n if (drawenCurrentFrame && !this->state.isIndicatorDrawen) {\n \/\/ Drawen now but not next\n this->indicatorDrawState = 2;\n } else if (!drawenCurrentFrame && this->state.isIndicatorDrawen) {\n \/\/ Not drawen now but next\n this->indicatorDrawState = 1;\n } else if (!drawenCurrentFrame && !this->state.isIndicatorDrawen) {\n \/\/ Not drawen in both frames\n this->indicatorDrawState = 3;\n }\n\n \/\/ If the indicator isn't draw in the current frame\n \/\/ reflect it in state.isIndicatorDrawen\n if (!drawenCurrentFrame) this->state.isIndicatorDrawen = false;\n\n break;\n }\n case FIXED:\n \/\/ Always assume that the indicator is drawn!\n \/\/ And set indicatorDrawState to \"not known yet\"\n this->indicatorDrawState = 0;\n this->enableIndicator();\n (this->frameFunctions[this->state.currentFrame])(this->display, &this->state, 0, 0);\n break;\n }\n}\n\nvoid OLEDDisplayUi::drawIndicator() {\n\n \/\/ Only draw if the indicator is invisible\n \/\/ for both frames or\n \/\/ the indiactor is shown and we are IN_TRANSITION\n if (this->indicatorDrawState == 3 || (!this->state.isIndicatorDrawen && this->state.frameState != IN_TRANSITION)) {\n return;\n }\n\n uint8_t posOfHighlightFrame;\n float indicatorFadeProgress = 0;\n\n \/\/ if the indicator needs to be slided in we want to\n \/\/ highlight the next frame in the transition\n uint8_t frameToHighlight = this->indicatorDrawState == 1 ? this->getNextFrameNumber() : this->state.currentFrame;\n\n \/\/ Calculate the frame that needs to be highlighted\n \/\/ based on the Direction the indiactor is drawn\n switch (this->indicatorDirection){\n case LEFT_RIGHT:\n posOfHighlightFrame = frameToHighlight;\n break;\n case RIGHT_LEFT:\n posOfHighlightFrame = this->frameCount - frameToHighlight;\n break;\n }\n\n switch (this->indicatorDrawState) {\n case 1: \/\/ Indicator was not drawn in this frame but will be in next\n \/\/ Slide IN\n indicatorFadeProgress = 1 - ((float) this->state.ticksSinceLastStateSwitch \/ (float) this->ticksPerTransition);\n break;\n case 2: \/\/ Indicator was drawn in this frame but not in next\n \/\/ Slide OUT\n indicatorFadeProgress = ((float) this->state.ticksSinceLastStateSwitch \/ (float) this->ticksPerTransition);\n break;\n }\n\n \/\/Space between indicators - reduce for small screen sizes\n uint16_t indicatorSpacing = 12;\n if (this->display->getHeight() < 64 && (this->indicatorPosition == RIGHT || this->indicatorPosition == LEFT)) {\n indicatorSpacing = 6;\n }\n \n uint16_t frameStartPos = (indicatorSpacing * frameCount \/ 2);\n const char *image;\n uint16_t x,y;\n for (byte i = 0; i < this->frameCount; i++) {\n\n switch (this->indicatorPosition){\n case TOP:\n y = 0 - (8 * indicatorFadeProgress);\n x = (this->display->getWidth() \/ 2) - frameStartPos + indicatorSpacing * i;\n break;\n case BOTTOM:\n y = (this->display->getHeight() - 8) + (8 * indicatorFadeProgress);\n x = (this->display->getWidth() \/ 2) - frameStartPos + indicatorSpacing * i;\n break;\n case RIGHT:\n x = (this->display->getWidth() - 8) + (8 * indicatorFadeProgress);\n y = (this->display->getHeight() \/ 2) - frameStartPos + indicatorSpacing * i;\n break;\n case LEFT:\n x = 0 - (8 * indicatorFadeProgress);\n y = (this->display->getHeight() \/ 2) - frameStartPos + indicatorSpacing * i;\n break;\n }\n\n if (posOfHighlightFrame == i) {\n image = this->activeSymbol;\n } else {\n image = this->inactiveSymbol;\n }\n\n this->display->drawFastImage(x, y, 8, 8, image);\n }\n}\n\nvoid OLEDDisplayUi::drawOverlays() {\n for (uint8_t i=0;i<this->overlayCount;i++){\n (this->overlayFunctions[i])(this->display, &this->state);\n }\n}\n\nuint8_t OLEDDisplayUi::getNextFrameNumber(){\n if (this->nextFrameNumber != -1) return this->nextFrameNumber;\n return (this->state.currentFrame + this->frameCount + this->state.frameTransitionDirection) % this->frameCount;\n}\n<|endoftext|>"} {"text":"<commit_before>\/******************************************************************************\n * Copyright 2017 The Apollo Authors. All Rights Reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *****************************************************************************\/\n\n#include \"modules\/drivers\/canbus\/can_client\/hermes_can\/hermes_can_client.h\"\n\n#include <stdio.h>\n#include <string.h>\n#include <vector>\n\n#include <iostream>\n\nnamespace apollo {\nnamespace drivers {\nnamespace canbus {\nnamespace can {\n\nusing apollo::common::ErrorCode;\n\nHermesCanClient::~HermesCanClient() {\n if (_dev_handler) {\n Stop();\n }\n}\n\nbool HermesCanClient::Init(const CANCardParameter ¶meter) {\n if (!parameter.has_channel_id()) {\n AERROR << \"Init CAN failed: parameter does not have channel id. The \"\n \"parameter is \"\n << parameter.DebugString();\n return false;\n } else {\n _card_port = parameter.channel_id();\n return true;\n }\n}\n\nErrorCode HermesCanClient::Start() {\n if (_is_init) {\n return ErrorCode::OK;\n }\n\n if (_card_port > MAX_CAN_PORT || _card_port < 0) {\n AERROR << \"can port number [\" << _card_port << \"] is out of the range [0,\"\n << MAX_CAN_PORT << \"]\";\n return ErrorCode::CAN_CLIENT_ERROR_BASE;\n }\n \/\/ open device\n int32_t ret = bcan_open(_card_port, 0,\n 5, \/\/ 5ms for rx timeout\n 5, \/\/ 5ms for tx timeout\n &_dev_handler);\n\n if (ret != ErrorCode::OK) {\n AERROR << \"Open device error code: \" << ret\n << \", channel id: \" << _card_port;\n return ErrorCode::CAN_CLIENT_ERROR_BASE;\n }\n AERROR << \"Open device succ code: \" << ret << \", channel id: \" << _card_port;\n\n \/\/ 1. set baudrate to 500k\n ret = bcan_set_baudrate(_dev_handler, BCAN_BAUDRATE_500K);\n if (ret != ErrorCode::OK) {\n AERROR << \"Set baudrate error Code: \" << ret;\n return ErrorCode::CAN_CLIENT_ERROR_BASE;\n }\n\n \/\/ 2. start receive\n ret = bcan_start(_dev_handler);\n if (ret != ErrorCode::OK) {\n AERROR << \"Start hermes can card failed: \" << ret;\n return ErrorCode::CAN_CLIENT_ERROR_BASE;\n }\n\n _is_init = true;\n return ErrorCode::OK;\n}\n\nvoid HermesCanClient::Stop() {\n if (_is_init) {\n _is_init = false;\n int32_t ret = bcan_close(_dev_handler);\n if (ret != ErrorCode::OK) {\n AERROR << \"close error code: \" << ret;\n }\n }\n}\n\n\/\/ Synchronous transmission of CAN messages\napollo::common::ErrorCode HermesCanClient::Send(\n const std::vector<CanFrame> &frames, int32_t *const frame_num) {\n \/*\n typedef struct bcan_msg {\n uint32_t bcan_msg_id; \/\/ source CAN node id\n uint8_t bcan_msg_datalen; \/\/ message data length\n uint8_t bcan_msg_rsv[3]; \/\/ reserved\n uint8_t bcan_msg_data[8]; \/\/ message data\n uint64_t bcan_msg_timestamp; \/\/ TBD\n } bcan_msg_t;\n *\/\n CHECK_NOTNULL(frame_num);\n CHECK_EQ(frames.size(), static_cast<size_t>(*frame_num));\n\n if (!_is_init) {\n AERROR << \"Hermes can client is not init! Please init first!\";\n return ErrorCode::CAN_CLIENT_ERROR_SEND_FAILED;\n }\n \/\/ if (*frame_num > MAX_CAN_SEND_FRAME_LEN || *frame_num < 0) {\n \/\/ AERROR << \"send can frame num not in range[0, \"\n \/\/ << MAX_CAN_SEND_FRAME_LEN << \"], frame_num:\" << *frame_num;\n \/\/ return ErrorCode::CAN_CLIENT_ERROR_FRAME_NUM;\n \/\/ }\n for (int i = 0; i < *frame_num; ++i) {\n _send_frames[i].bcan_msg_id = frames[i].id;\n _send_frames[i].bcan_msg_datalen = frames[i].len;\n memcpy(_send_frames[i].bcan_msg_data, frames[i].data, frames[i].len);\n }\n\n \/\/ Synchronous transmission of CAN messages\n int32_t send_num = *frame_num;\n int32_t ret = bcan_send(_dev_handler, _send_frames, send_num);\n if (ret < 0) {\n int ret_send_error = bcan_get_status(_dev_handler);\n AERROR << \"send message failed, error code: \" << ret\n << \", send error: \" << ret_send_error;\n return ErrorCode::CAN_CLIENT_ERROR_SEND_FAILED;\n }\n *frame_num = ret;\n return ErrorCode::OK;\n}\n\n\/\/ buf size must be 8 bytes, every time, we receive only one frame\nconst int RX_TIMEOUT = -7;\napollo::common::ErrorCode HermesCanClient::Receive(\n std::vector<CanFrame> *const frames, int32_t *const frame_num) {\n if (!_is_init) {\n AERROR << \"Hermes can client is not init! Please init first!\";\n return ErrorCode::CAN_CLIENT_ERROR_RECV_FAILED;\n }\n if (*frame_num > MAX_CAN_RECV_FRAME_LEN || *frame_num < 0) {\n AERROR << \"recv can frame num not in range[0, \" << MAX_CAN_RECV_FRAME_LEN\n << \"], frame_num:\" << *frame_num;\n return ErrorCode::CAN_CLIENT_ERROR_FRAME_NUM;\n }\n\n int32_t ret = bcan_recv(_dev_handler, _recv_frames, *frame_num);\n \/\/ don't log timeout\n if (ret == RX_TIMEOUT) {\n *frame_num = 0;\n return ErrorCode::OK;\n }\n if (ret < 0) {\n int ret_rece_error = bcan_get_status(_dev_handler);\n AERROR << \"receive message failed, error code:\" << ret\n << \"receive error:\" << ret_rece_error;\n return ErrorCode::CAN_CLIENT_ERROR_RECV_FAILED;\n }\n *frame_num = ret;\n\n \/\/ is ret num is equal *frame_num?\n for (int i = 0; i < *frame_num; ++i) {\n CanFrame cf;\n cf.id = _recv_frames[i].bcan_msg_id;\n cf.len = _recv_frames[i].bcan_msg_datalen;\n cf.timestamp.tv_sec = _recv_frames[i].bcan_msg_timestamp.tv_sec;\n cf.timestamp.tv_usec = _recv_frames[i].bcan_msg_timestamp.tv_usec;\n memcpy(cf.data, _recv_frames[i].bcan_msg_data, cf.len);\n frames->push_back(cf);\n }\n\n return ErrorCode::OK;\n}\n\nstd::string HermesCanClient::GetErrorString(int32_t ntstatus) { return \"\"; }\n\nvoid HermesCanClient::SetInited(bool init) { _is_init = init; }\n\n} \/\/ namespace can\n} \/\/ namespace canbus\n} \/\/ namespace drivers\n} \/\/ namespace apollo\n\n\/* vim: set expandtab ts=4 sw=4 sts=4 tw=100: *\/\n<commit_msg>canbus: fix inappropriate log level (#343)<commit_after>\/******************************************************************************\n * Copyright 2017 The Apollo Authors. All Rights Reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *****************************************************************************\/\n\n#include \"modules\/drivers\/canbus\/can_client\/hermes_can\/hermes_can_client.h\"\n\n#include <stdio.h>\n#include <string.h>\n#include <vector>\n\n#include <iostream>\n\nnamespace apollo {\nnamespace drivers {\nnamespace canbus {\nnamespace can {\n\nusing apollo::common::ErrorCode;\n\nHermesCanClient::~HermesCanClient() {\n if (_dev_handler) {\n Stop();\n }\n}\n\nbool HermesCanClient::Init(const CANCardParameter ¶meter) {\n if (!parameter.has_channel_id()) {\n AERROR << \"Init CAN failed: parameter does not have channel id. The \"\n \"parameter is \"\n << parameter.DebugString();\n return false;\n } else {\n _card_port = parameter.channel_id();\n return true;\n }\n}\n\nErrorCode HermesCanClient::Start() {\n if (_is_init) {\n return ErrorCode::OK;\n }\n\n if (_card_port > MAX_CAN_PORT || _card_port < 0) {\n AERROR << \"can port number [\" << _card_port << \"] is out of the range [0,\"\n << MAX_CAN_PORT << \"]\";\n return ErrorCode::CAN_CLIENT_ERROR_BASE;\n }\n \/\/ open device\n int32_t ret = bcan_open(_card_port, 0,\n 5, \/\/ 5ms for rx timeout\n 5, \/\/ 5ms for tx timeout\n &_dev_handler);\n\n if (ret != ErrorCode::OK) {\n AERROR << \"Open device error code: \" << ret\n << \", channel id: \" << _card_port;\n return ErrorCode::CAN_CLIENT_ERROR_BASE;\n }\n AINFO << \"Open device succ code: \" << ret << \", channel id: \" << _card_port;\n\n \/\/ 1. set baudrate to 500k\n ret = bcan_set_baudrate(_dev_handler, BCAN_BAUDRATE_500K);\n if (ret != ErrorCode::OK) {\n AERROR << \"Set baudrate error Code: \" << ret;\n return ErrorCode::CAN_CLIENT_ERROR_BASE;\n }\n\n \/\/ 2. start receive\n ret = bcan_start(_dev_handler);\n if (ret != ErrorCode::OK) {\n AERROR << \"Start hermes can card failed: \" << ret;\n return ErrorCode::CAN_CLIENT_ERROR_BASE;\n }\n\n _is_init = true;\n return ErrorCode::OK;\n}\n\nvoid HermesCanClient::Stop() {\n if (_is_init) {\n _is_init = false;\n int32_t ret = bcan_close(_dev_handler);\n if (ret != ErrorCode::OK) {\n AERROR << \"close error code: \" << ret;\n }\n }\n}\n\n\/\/ Synchronous transmission of CAN messages\napollo::common::ErrorCode HermesCanClient::Send(\n const std::vector<CanFrame> &frames, int32_t *const frame_num) {\n \/*\n typedef struct bcan_msg {\n uint32_t bcan_msg_id; \/\/ source CAN node id\n uint8_t bcan_msg_datalen; \/\/ message data length\n uint8_t bcan_msg_rsv[3]; \/\/ reserved\n uint8_t bcan_msg_data[8]; \/\/ message data\n uint64_t bcan_msg_timestamp; \/\/ TBD\n } bcan_msg_t;\n *\/\n CHECK_NOTNULL(frame_num);\n CHECK_EQ(frames.size(), static_cast<size_t>(*frame_num));\n\n if (!_is_init) {\n AERROR << \"Hermes can client is not init! Please init first!\";\n return ErrorCode::CAN_CLIENT_ERROR_SEND_FAILED;\n }\n \/\/ if (*frame_num > MAX_CAN_SEND_FRAME_LEN || *frame_num < 0) {\n \/\/ AERROR << \"send can frame num not in range[0, \"\n \/\/ << MAX_CAN_SEND_FRAME_LEN << \"], frame_num:\" << *frame_num;\n \/\/ return ErrorCode::CAN_CLIENT_ERROR_FRAME_NUM;\n \/\/ }\n for (int i = 0; i < *frame_num; ++i) {\n _send_frames[i].bcan_msg_id = frames[i].id;\n _send_frames[i].bcan_msg_datalen = frames[i].len;\n memcpy(_send_frames[i].bcan_msg_data, frames[i].data, frames[i].len);\n }\n\n \/\/ Synchronous transmission of CAN messages\n int32_t send_num = *frame_num;\n int32_t ret = bcan_send(_dev_handler, _send_frames, send_num);\n if (ret < 0) {\n int ret_send_error = bcan_get_status(_dev_handler);\n AERROR << \"send message failed, error code: \" << ret\n << \", send error: \" << ret_send_error;\n return ErrorCode::CAN_CLIENT_ERROR_SEND_FAILED;\n }\n *frame_num = ret;\n return ErrorCode::OK;\n}\n\n\/\/ buf size must be 8 bytes, every time, we receive only one frame\nconst int RX_TIMEOUT = -7;\napollo::common::ErrorCode HermesCanClient::Receive(\n std::vector<CanFrame> *const frames, int32_t *const frame_num) {\n if (!_is_init) {\n AERROR << \"Hermes can client is not init! Please init first!\";\n return ErrorCode::CAN_CLIENT_ERROR_RECV_FAILED;\n }\n if (*frame_num > MAX_CAN_RECV_FRAME_LEN || *frame_num < 0) {\n AERROR << \"recv can frame num not in range[0, \" << MAX_CAN_RECV_FRAME_LEN\n << \"], frame_num:\" << *frame_num;\n return ErrorCode::CAN_CLIENT_ERROR_FRAME_NUM;\n }\n\n int32_t ret = bcan_recv(_dev_handler, _recv_frames, *frame_num);\n \/\/ don't log timeout\n if (ret == RX_TIMEOUT) {\n *frame_num = 0;\n return ErrorCode::OK;\n }\n if (ret < 0) {\n int ret_rece_error = bcan_get_status(_dev_handler);\n AERROR << \"receive message failed, error code:\" << ret\n << \"receive error:\" << ret_rece_error;\n return ErrorCode::CAN_CLIENT_ERROR_RECV_FAILED;\n }\n *frame_num = ret;\n\n \/\/ is ret num is equal *frame_num?\n for (int i = 0; i < *frame_num; ++i) {\n CanFrame cf;\n cf.id = _recv_frames[i].bcan_msg_id;\n cf.len = _recv_frames[i].bcan_msg_datalen;\n cf.timestamp.tv_sec = _recv_frames[i].bcan_msg_timestamp.tv_sec;\n cf.timestamp.tv_usec = _recv_frames[i].bcan_msg_timestamp.tv_usec;\n memcpy(cf.data, _recv_frames[i].bcan_msg_data, cf.len);\n frames->push_back(cf);\n }\n\n return ErrorCode::OK;\n}\n\nstd::string HermesCanClient::GetErrorString(int32_t ntstatus) { return \"\"; }\n\nvoid HermesCanClient::SetInited(bool init) { _is_init = init; }\n\n} \/\/ namespace can\n} \/\/ namespace canbus\n} \/\/ namespace drivers\n} \/\/ namespace apollo\n\n\/* vim: set expandtab ts=4 sw=4 sts=4 tw=100: *\/\n<|endoftext|>"} {"text":"<commit_before>\/**\n * The MIT License (MIT)\n *\n * Copyright (c) 2016 by Daniel Eichhorn\n * Copyright (c) 2016 by Fabrice Weinberg\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n *\n *\/\n\n#include \"OLEDDisplayUi.h\"\n\nOLEDDisplayUi::OLEDDisplayUi(OLEDDisplay *display) {\n this->display = display;\n}\n\nvoid OLEDDisplayUi::init() {\n this->display->init();\n}\n\nvoid OLEDDisplayUi::setTargetFPS(uint8_t fps){\n float oldInterval = this->updateInterval;\n this->updateInterval = ((float) 1.0 \/ (float) fps) * 1000;\n\n \/\/ Calculate new ticksPerFrame\n float changeRatio = oldInterval \/ (float) this->updateInterval;\n this->ticksPerFrame *= changeRatio;\n this->ticksPerTransition *= changeRatio;\n}\n\n\/\/ -\/------ Automatic controll ------\\-\n\nvoid OLEDDisplayUi::enableAutoTransition(){\n this->autoTransition = true;\n}\nvoid OLEDDisplayUi::disableAutoTransition(){\n this->autoTransition = false;\n}\nvoid OLEDDisplayUi::setAutoTransitionForwards(){\n this->state.frameTransitionDirection = 1;\n this->lastTransitionDirection = 1;\n}\nvoid OLEDDisplayUi::setAutoTransitionBackwards(){\n this->state.frameTransitionDirection = -1;\n this->lastTransitionDirection = -1;\n}\nvoid OLEDDisplayUi::setTimePerFrame(uint16_t time){\n this->ticksPerFrame = (int) ( (float) time \/ (float) updateInterval);\n}\nvoid OLEDDisplayUi::setTimePerTransition(uint16_t time){\n this->ticksPerTransition = (int) ( (float) time \/ (float) updateInterval);\n}\n\n\/\/ -\/------ Customize indicator position and style -------\\-\nvoid OLEDDisplayUi::enableIndicator(){\n this->state.isIndicatorDrawen = true;\n}\n\nvoid OLEDDisplayUi::disableIndicator(){\n this->state.isIndicatorDrawen = false;\n}\n\nvoid OLEDDisplayUi::setIndicatorPosition(IndicatorPosition pos) {\n this->indicatorPosition = pos;\n}\nvoid OLEDDisplayUi::setIndicatorDirection(IndicatorDirection dir) {\n this->indicatorDirection = dir;\n}\nvoid OLEDDisplayUi::setActiveSymbol(const char* symbol) {\n this->activeSymbol = symbol;\n}\nvoid OLEDDisplayUi::setInactiveSymbol(const char* symbol) {\n this->inactiveSymbol = symbol;\n}\n\n\n\/\/ -\/----- Frame settings -----\\-\nvoid OLEDDisplayUi::setFrameAnimation(AnimationDirection dir) {\n this->frameAnimationDirection = dir;\n}\nvoid OLEDDisplayUi::setFrames(FrameCallback* frameFunctions, uint8_t frameCount) {\n this->frameFunctions = frameFunctions;\n this->frameCount = frameCount;\n this->resetState();\n}\n\n\/\/ -\/----- Overlays ------\\-\nvoid OLEDDisplayUi::setOverlays(OverlayCallback* overlayFunctions, uint8_t overlayCount){\n this->overlayFunctions = overlayFunctions;\n this->overlayCount = overlayCount;\n}\n\n\/\/ -\/----- Loading Process -----\\-\n\nvoid OLEDDisplayUi::runLoadingProcess(LoadingStage* stages, uint8_t stagesCount) {\n uint8_t progress = 0;\n uint8_t increment = 100 \/ stagesCount;\n\n for (uint8_t i = 0; i < stagesCount; i++) {\n display->clear();\n this->loadingDrawFunction(this->display, &stages[i], progress);\n display->display();\n\n stages[i].callback();\n\n progress += increment;\n yield();\n }\n\n display->clear();\n this->loadingDrawFunction(this->display, &stages[stagesCount-1], progress);\n display->display();\n\n delay(150);\n}\n\n\/\/ -\/----- Manuel control -----\\-\nvoid OLEDDisplayUi::nextFrame() {\n if (this->state.frameState != IN_TRANSITION) {\n this->state.manuelControll = true;\n this->state.frameState = IN_TRANSITION;\n this->state.ticksSinceLastStateSwitch = 0;\n this->lastTransitionDirection = this->state.frameTransitionDirection;\n this->state.frameTransitionDirection = 1;\n }\n}\nvoid OLEDDisplayUi::previousFrame() {\n if (this->state.frameState != IN_TRANSITION) {\n this->state.manuelControll = true;\n this->state.frameState = IN_TRANSITION;\n this->state.ticksSinceLastStateSwitch = 0;\n this->lastTransitionDirection = this->state.frameTransitionDirection;\n this->state.frameTransitionDirection = -1;\n }\n}\n\nvoid OLEDDisplayUi::switchToFrame(uint8_t frame) {\n if (frame >= this->frameCount || frame != this->state.currentFrame) return;\n this->state.lastUpdate = 0;\n this->state.ticksSinceLastStateSwitch = 0;\n this->state.frameState = FIXED;\n this->state.currentFrame = frame;\n this->state.isIndicatorDrawen = true;\n}\n\nvoid OLEDDisplayUi::transitionToFrame(uint8_t frame) {\n if (frame >= this->frameCount || frame != this->state.currentFrame) return;\n this->nextFrameNumber = frame;\n this->lastTransitionDirection = this->state.frameTransitionDirection;\n this->state.manuelControll = true;\n this->state.frameState = IN_TRANSITION;\n this->state.ticksSinceLastStateSwitch = 0;\n this->state.frameTransitionDirection = frame < this->state.currentFrame ? -1 : 1;\n}\n\n\n\/\/ -\/----- State information -----\\-\nOLEDDisplayUiState* OLEDDisplayUi::getUiState(){\n return &this->state;\n}\n\n\nint8_t OLEDDisplayUi::update(){\n long frameStart = millis();\n int8_t timeBudget = this->updateInterval - (frameStart - this->state.lastUpdate);\n if ( timeBudget <= 0) {\n \/\/ Implement frame skipping to ensure time budget is keept\n if (this->autoTransition && this->state.lastUpdate != 0) this->state.ticksSinceLastStateSwitch += ceil(-timeBudget \/ this->updateInterval);\n\n this->state.lastUpdate = frameStart;\n this->tick();\n }\n return this->updateInterval - (millis() - frameStart);\n}\n\n\nvoid OLEDDisplayUi::tick() {\n this->state.ticksSinceLastStateSwitch++;\n\n switch (this->state.frameState) {\n case IN_TRANSITION:\n if (this->state.ticksSinceLastStateSwitch >= this->ticksPerTransition){\n this->state.frameState = FIXED;\n this->state.currentFrame = getNextFrameNumber();\n this->state.ticksSinceLastStateSwitch = 0;\n this->nextFrameNumber = -1;\n }\n break;\n case FIXED:\n \/\/ Revert manuelControll\n if (this->state.manuelControll) {\n this->state.frameTransitionDirection = this->lastTransitionDirection;\n this->state.manuelControll = false;\n }\n if (this->state.ticksSinceLastStateSwitch >= this->ticksPerFrame){\n if (this->autoTransition){\n this->state.frameState = IN_TRANSITION;\n }\n this->state.ticksSinceLastStateSwitch = 0;\n }\n break;\n }\n\n this->display->clear();\n this->drawFrame();\n this->drawIndicator();\n this->drawOverlays();\n this->display->display();\n}\n\nvoid OLEDDisplayUi::resetState() {\n this->state.lastUpdate = 0;\n this->state.ticksSinceLastStateSwitch = 0;\n this->state.frameState = FIXED;\n this->state.currentFrame = 0;\n this->state.isIndicatorDrawen = true;\n}\n\nvoid OLEDDisplayUi::drawFrame(){\n switch (this->state.frameState){\n case IN_TRANSITION: {\n float progress = (float) this->state.ticksSinceLastStateSwitch \/ (float) this->ticksPerTransition;\n int16_t x, y, x1, y1;\n switch(this->frameAnimationDirection){\n case SLIDE_LEFT:\n x = -128 * progress;\n y = 0;\n x1 = x + 128;\n y1 = 0;\n break;\n case SLIDE_RIGHT:\n x = 128 * progress;\n y = 0;\n x1 = x - 128;\n y1 = 0;\n break;\n case SLIDE_UP:\n x = 0;\n y = -64 * progress;\n x1 = 0;\n y1 = y + 64;\n break;\n case SLIDE_DOWN:\n x = 0;\n y = 64 * progress;\n x1 = 0;\n y1 = y - 64;\n break;\n }\n\n \/\/ Invert animation if direction is reversed.\n int8_t dir = this->state.frameTransitionDirection >= 0 ? 1 : -1;\n x *= dir; y *= dir; x1 *= dir; y1 *= dir;\n\n bool drawenCurrentFrame;\n\n\n \/\/ Prope each frameFunction for the indicator Drawen state\n this->enableIndicator();\n (this->frameFunctions[this->state.currentFrame])(this->display, &this->state, x, y);\n drawenCurrentFrame = this->state.isIndicatorDrawen;\n\n this->enableIndicator();\n (this->frameFunctions[this->getNextFrameNumber()])(this->display, &this->state, x1, y1);\n\n \/\/ Build up the indicatorDrawState\n if (drawenCurrentFrame && !this->state.isIndicatorDrawen) {\n \/\/ Drawen now but not next\n this->indicatorDrawState = 2;\n } else if (!drawenCurrentFrame && this->state.isIndicatorDrawen) {\n \/\/ Not drawen now but next\n this->indicatorDrawState = 1;\n } else if (!drawenCurrentFrame && !this->state.isIndicatorDrawen) {\n \/\/ Not drawen in both frames\n this->indicatorDrawState = 3;\n }\n\n \/\/ If the indicator isn't draw in the current frame\n \/\/ reflect it in state.isIndicatorDrawen\n if (!drawenCurrentFrame) this->state.isIndicatorDrawen = false;\n\n break;\n }\n case FIXED:\n \/\/ Always assume that the indicator is drawn!\n \/\/ And set indicatorDrawState to \"not known yet\"\n this->indicatorDrawState = 0;\n this->enableIndicator();\n (this->frameFunctions[this->state.currentFrame])(this->display, &this->state, 0, 0);\n break;\n }\n}\n\nvoid OLEDDisplayUi::drawIndicator() {\n\n \/\/ Only draw if the indicator is invisible\n \/\/ for both frames or\n \/\/ the indiactor is shown and we are IN_TRANSITION\n if (this->indicatorDrawState == 3 || (!this->state.isIndicatorDrawen && this->state.frameState != IN_TRANSITION)) {\n return;\n }\n\n uint8_t posOfHighlightFrame;\n float indicatorFadeProgress = 0;\n\n \/\/ if the indicator needs to be slided in we want to\n \/\/ highlight the next frame in the transition\n uint8_t frameToHighlight = this->indicatorDrawState == 1 ? this->getNextFrameNumber() : this->state.currentFrame;\n\n \/\/ Calculate the frame that needs to be highlighted\n \/\/ based on the Direction the indiactor is drawn\n switch (this->indicatorDirection){\n case LEFT_RIGHT:\n posOfHighlightFrame = frameToHighlight;\n break;\n case RIGHT_LEFT:\n posOfHighlightFrame = this->frameCount - frameToHighlight;\n break;\n }\n\n switch (this->indicatorDrawState) {\n case 1: \/\/ Indicator was not drawn in this frame but will be in next\n \/\/ Slide IN\n indicatorFadeProgress = 1 - ((float) this->state.ticksSinceLastStateSwitch \/ (float) this->ticksPerTransition);\n break;\n case 2: \/\/ Indicator was drawn in this frame but not in next\n \/\/ Slide OUT\n indicatorFadeProgress = ((float) this->state.ticksSinceLastStateSwitch \/ (float) this->ticksPerTransition);\n break;\n }\n\n uint16_t frameStartPos = (12 * frameCount \/ 2);\n const char *image;\n uint16_t x,y;\n for (byte i = 0; i < this->frameCount; i++) {\n\n switch (this->indicatorPosition){\n case TOP:\n y = 0 - (8 * indicatorFadeProgress);\n x = 64 - frameStartPos + 12 * i;\n break;\n case BOTTOM:\n y = 56 + (8 * indicatorFadeProgress);\n x = 64 - frameStartPos + 12 * i;\n break;\n case RIGHT:\n x = 120 + (8 * indicatorFadeProgress);\n y = 32 - frameStartPos + 12 * i;\n break;\n case LEFT:\n x = 0 - (8 * indicatorFadeProgress);\n y = 32 - frameStartPos + 12 * i;\n break;\n }\n\n if (posOfHighlightFrame == i) {\n image = this->activeSymbol;\n } else {\n image = this->inactiveSymbol;\n }\n\n this->display->drawFastImage(x, y, 8, 8, image);\n }\n}\n\nvoid OLEDDisplayUi::drawOverlays() {\n for (uint8_t i=0;i<this->overlayCount;i++){\n (this->overlayFunctions[i])(this->display, &this->state);\n }\n}\n\nuint8_t OLEDDisplayUi::getNextFrameNumber(){\n if (this->nextFrameNumber != -1) return this->nextFrameNumber;\n return (this->state.currentFrame + this->frameCount + this->state.frameTransitionDirection) % this->frameCount;\n}\n<commit_msg>Fixes #58<commit_after>\/**\n * The MIT License (MIT)\n *\n * Copyright (c) 2016 by Daniel Eichhorn\n * Copyright (c) 2016 by Fabrice Weinberg\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n *\n *\/\n\n#include \"OLEDDisplayUi.h\"\n\nOLEDDisplayUi::OLEDDisplayUi(OLEDDisplay *display) {\n this->display = display;\n}\n\nvoid OLEDDisplayUi::init() {\n this->display->init();\n}\n\nvoid OLEDDisplayUi::setTargetFPS(uint8_t fps){\n float oldInterval = this->updateInterval;\n this->updateInterval = ((float) 1.0 \/ (float) fps) * 1000;\n\n \/\/ Calculate new ticksPerFrame\n float changeRatio = oldInterval \/ (float) this->updateInterval;\n this->ticksPerFrame *= changeRatio;\n this->ticksPerTransition *= changeRatio;\n}\n\n\/\/ -\/------ Automatic controll ------\\-\n\nvoid OLEDDisplayUi::enableAutoTransition(){\n this->autoTransition = true;\n}\nvoid OLEDDisplayUi::disableAutoTransition(){\n this->autoTransition = false;\n}\nvoid OLEDDisplayUi::setAutoTransitionForwards(){\n this->state.frameTransitionDirection = 1;\n this->lastTransitionDirection = 1;\n}\nvoid OLEDDisplayUi::setAutoTransitionBackwards(){\n this->state.frameTransitionDirection = -1;\n this->lastTransitionDirection = -1;\n}\nvoid OLEDDisplayUi::setTimePerFrame(uint16_t time){\n this->ticksPerFrame = (int) ( (float) time \/ (float) updateInterval);\n}\nvoid OLEDDisplayUi::setTimePerTransition(uint16_t time){\n this->ticksPerTransition = (int) ( (float) time \/ (float) updateInterval);\n}\n\n\/\/ -\/------ Customize indicator position and style -------\\-\nvoid OLEDDisplayUi::enableIndicator(){\n this->state.isIndicatorDrawen = true;\n}\n\nvoid OLEDDisplayUi::disableIndicator(){\n this->state.isIndicatorDrawen = false;\n}\n\nvoid OLEDDisplayUi::setIndicatorPosition(IndicatorPosition pos) {\n this->indicatorPosition = pos;\n}\nvoid OLEDDisplayUi::setIndicatorDirection(IndicatorDirection dir) {\n this->indicatorDirection = dir;\n}\nvoid OLEDDisplayUi::setActiveSymbol(const char* symbol) {\n this->activeSymbol = symbol;\n}\nvoid OLEDDisplayUi::setInactiveSymbol(const char* symbol) {\n this->inactiveSymbol = symbol;\n}\n\n\n\/\/ -\/----- Frame settings -----\\-\nvoid OLEDDisplayUi::setFrameAnimation(AnimationDirection dir) {\n this->frameAnimationDirection = dir;\n}\nvoid OLEDDisplayUi::setFrames(FrameCallback* frameFunctions, uint8_t frameCount) {\n this->frameFunctions = frameFunctions;\n this->frameCount = frameCount;\n this->resetState();\n}\n\n\/\/ -\/----- Overlays ------\\-\nvoid OLEDDisplayUi::setOverlays(OverlayCallback* overlayFunctions, uint8_t overlayCount){\n this->overlayFunctions = overlayFunctions;\n this->overlayCount = overlayCount;\n}\n\n\/\/ -\/----- Loading Process -----\\-\n\nvoid OLEDDisplayUi::runLoadingProcess(LoadingStage* stages, uint8_t stagesCount) {\n uint8_t progress = 0;\n uint8_t increment = 100 \/ stagesCount;\n\n for (uint8_t i = 0; i < stagesCount; i++) {\n display->clear();\n this->loadingDrawFunction(this->display, &stages[i], progress);\n display->display();\n\n stages[i].callback();\n\n progress += increment;\n yield();\n }\n\n display->clear();\n this->loadingDrawFunction(this->display, &stages[stagesCount-1], progress);\n display->display();\n\n delay(150);\n}\n\n\/\/ -\/----- Manuel control -----\\-\nvoid OLEDDisplayUi::nextFrame() {\n if (this->state.frameState != IN_TRANSITION) {\n this->state.manuelControll = true;\n this->state.frameState = IN_TRANSITION;\n this->state.ticksSinceLastStateSwitch = 0;\n this->lastTransitionDirection = this->state.frameTransitionDirection;\n this->state.frameTransitionDirection = 1;\n }\n}\nvoid OLEDDisplayUi::previousFrame() {\n if (this->state.frameState != IN_TRANSITION) {\n this->state.manuelControll = true;\n this->state.frameState = IN_TRANSITION;\n this->state.ticksSinceLastStateSwitch = 0;\n this->lastTransitionDirection = this->state.frameTransitionDirection;\n this->state.frameTransitionDirection = -1;\n }\n}\n\nvoid OLEDDisplayUi::switchToFrame(uint8_t frame) {\n if (frame >= this->frameCount) return\n this->state.ticksSinceLastStateSwitch = 0;\n if (frame == this->state.currentFrame) return;\n this->state.frameState = FIXED;\n this->state.currentFrame = frame;\n this->state.isIndicatorDrawen = true;\n}\n\nvoid OLEDDisplayUi::transitionToFrame(uint8_t frame) {\n if (frame >= this->frameCount) return\n this->state.ticksSinceLastStateSwitch = 0;\n if (frame == this->state.currentFrame) return;\n this->nextFrameNumber = frame;\n this->lastTransitionDirection = this->state.frameTransitionDirection;\n this->state.manuelControll = true;\n this->state.frameState = IN_TRANSITION;\n this->state.frameTransitionDirection = frame < this->state.currentFrame ? -1 : 1;\n}\n\n\n\/\/ -\/----- State information -----\\-\nOLEDDisplayUiState* OLEDDisplayUi::getUiState(){\n return &this->state;\n}\n\n\nint8_t OLEDDisplayUi::update(){\n long frameStart = millis();\n int8_t timeBudget = this->updateInterval - (frameStart - this->state.lastUpdate);\n if ( timeBudget <= 0) {\n \/\/ Implement frame skipping to ensure time budget is keept\n if (this->autoTransition && this->state.lastUpdate != 0) this->state.ticksSinceLastStateSwitch += ceil(-timeBudget \/ this->updateInterval);\n\n this->state.lastUpdate = frameStart;\n this->tick();\n }\n return this->updateInterval - (millis() - frameStart);\n}\n\n\nvoid OLEDDisplayUi::tick() {\n this->state.ticksSinceLastStateSwitch++;\n\n switch (this->state.frameState) {\n case IN_TRANSITION:\n if (this->state.ticksSinceLastStateSwitch >= this->ticksPerTransition){\n this->state.frameState = FIXED;\n this->state.currentFrame = getNextFrameNumber();\n this->state.ticksSinceLastStateSwitch = 0;\n this->nextFrameNumber = -1;\n }\n break;\n case FIXED:\n \/\/ Revert manuelControll\n if (this->state.manuelControll) {\n this->state.frameTransitionDirection = this->lastTransitionDirection;\n this->state.manuelControll = false;\n }\n if (this->state.ticksSinceLastStateSwitch >= this->ticksPerFrame){\n if (this->autoTransition){\n this->state.frameState = IN_TRANSITION;\n }\n this->state.ticksSinceLastStateSwitch = 0;\n }\n break;\n }\n\n this->display->clear();\n this->drawFrame();\n this->drawIndicator();\n this->drawOverlays();\n this->display->display();\n}\n\nvoid OLEDDisplayUi::resetState() {\n this->state.lastUpdate = 0;\n this->state.ticksSinceLastStateSwitch = 0;\n this->state.frameState = FIXED;\n this->state.currentFrame = 0;\n this->state.isIndicatorDrawen = true;\n}\n\nvoid OLEDDisplayUi::drawFrame(){\n switch (this->state.frameState){\n case IN_TRANSITION: {\n float progress = (float) this->state.ticksSinceLastStateSwitch \/ (float) this->ticksPerTransition;\n int16_t x, y, x1, y1;\n switch(this->frameAnimationDirection){\n case SLIDE_LEFT:\n x = -128 * progress;\n y = 0;\n x1 = x + 128;\n y1 = 0;\n break;\n case SLIDE_RIGHT:\n x = 128 * progress;\n y = 0;\n x1 = x - 128;\n y1 = 0;\n break;\n case SLIDE_UP:\n x = 0;\n y = -64 * progress;\n x1 = 0;\n y1 = y + 64;\n break;\n case SLIDE_DOWN:\n x = 0;\n y = 64 * progress;\n x1 = 0;\n y1 = y - 64;\n break;\n }\n\n \/\/ Invert animation if direction is reversed.\n int8_t dir = this->state.frameTransitionDirection >= 0 ? 1 : -1;\n x *= dir; y *= dir; x1 *= dir; y1 *= dir;\n\n bool drawenCurrentFrame;\n\n\n \/\/ Prope each frameFunction for the indicator Drawen state\n this->enableIndicator();\n (this->frameFunctions[this->state.currentFrame])(this->display, &this->state, x, y);\n drawenCurrentFrame = this->state.isIndicatorDrawen;\n\n this->enableIndicator();\n (this->frameFunctions[this->getNextFrameNumber()])(this->display, &this->state, x1, y1);\n\n \/\/ Build up the indicatorDrawState\n if (drawenCurrentFrame && !this->state.isIndicatorDrawen) {\n \/\/ Drawen now but not next\n this->indicatorDrawState = 2;\n } else if (!drawenCurrentFrame && this->state.isIndicatorDrawen) {\n \/\/ Not drawen now but next\n this->indicatorDrawState = 1;\n } else if (!drawenCurrentFrame && !this->state.isIndicatorDrawen) {\n \/\/ Not drawen in both frames\n this->indicatorDrawState = 3;\n }\n\n \/\/ If the indicator isn't draw in the current frame\n \/\/ reflect it in state.isIndicatorDrawen\n if (!drawenCurrentFrame) this->state.isIndicatorDrawen = false;\n\n break;\n }\n case FIXED:\n \/\/ Always assume that the indicator is drawn!\n \/\/ And set indicatorDrawState to \"not known yet\"\n this->indicatorDrawState = 0;\n this->enableIndicator();\n (this->frameFunctions[this->state.currentFrame])(this->display, &this->state, 0, 0);\n break;\n }\n}\n\nvoid OLEDDisplayUi::drawIndicator() {\n\n \/\/ Only draw if the indicator is invisible\n \/\/ for both frames or\n \/\/ the indiactor is shown and we are IN_TRANSITION\n if (this->indicatorDrawState == 3 || (!this->state.isIndicatorDrawen && this->state.frameState != IN_TRANSITION)) {\n return;\n }\n\n uint8_t posOfHighlightFrame;\n float indicatorFadeProgress = 0;\n\n \/\/ if the indicator needs to be slided in we want to\n \/\/ highlight the next frame in the transition\n uint8_t frameToHighlight = this->indicatorDrawState == 1 ? this->getNextFrameNumber() : this->state.currentFrame;\n\n \/\/ Calculate the frame that needs to be highlighted\n \/\/ based on the Direction the indiactor is drawn\n switch (this->indicatorDirection){\n case LEFT_RIGHT:\n posOfHighlightFrame = frameToHighlight;\n break;\n case RIGHT_LEFT:\n posOfHighlightFrame = this->frameCount - frameToHighlight;\n break;\n }\n\n switch (this->indicatorDrawState) {\n case 1: \/\/ Indicator was not drawn in this frame but will be in next\n \/\/ Slide IN\n indicatorFadeProgress = 1 - ((float) this->state.ticksSinceLastStateSwitch \/ (float) this->ticksPerTransition);\n break;\n case 2: \/\/ Indicator was drawn in this frame but not in next\n \/\/ Slide OUT\n indicatorFadeProgress = ((float) this->state.ticksSinceLastStateSwitch \/ (float) this->ticksPerTransition);\n break;\n }\n\n uint16_t frameStartPos = (12 * frameCount \/ 2);\n const char *image;\n uint16_t x,y;\n for (byte i = 0; i < this->frameCount; i++) {\n\n switch (this->indicatorPosition){\n case TOP:\n y = 0 - (8 * indicatorFadeProgress);\n x = 64 - frameStartPos + 12 * i;\n break;\n case BOTTOM:\n y = 56 + (8 * indicatorFadeProgress);\n x = 64 - frameStartPos + 12 * i;\n break;\n case RIGHT:\n x = 120 + (8 * indicatorFadeProgress);\n y = 32 - frameStartPos + 12 * i;\n break;\n case LEFT:\n x = 0 - (8 * indicatorFadeProgress);\n y = 32 - frameStartPos + 12 * i;\n break;\n }\n\n if (posOfHighlightFrame == i) {\n image = this->activeSymbol;\n } else {\n image = this->inactiveSymbol;\n }\n\n this->display->drawFastImage(x, y, 8, 8, image);\n }\n}\n\nvoid OLEDDisplayUi::drawOverlays() {\n for (uint8_t i=0;i<this->overlayCount;i++){\n (this->overlayFunctions[i])(this->display, &this->state);\n }\n}\n\nuint8_t OLEDDisplayUi::getNextFrameNumber(){\n if (this->nextFrameNumber != -1) return this->nextFrameNumber;\n return (this->state.currentFrame + this->frameCount + this->state.frameTransitionDirection) % this->frameCount;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/===--- FrontendInputsAndOutputs.cpp -------------------------------------===\/\/\n\/\/\n\/\/ This source file is part of the Swift.org open source project\n\/\/\n\/\/ Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors\n\/\/ Licensed under Apache License v2.0 with Runtime Library Exception\n\/\/\n\/\/ See https:\/\/swift.org\/LICENSE.txt for license information\n\/\/ See https:\/\/swift.org\/CONTRIBUTORS.txt for the list of Swift project authors\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"swift\/Frontend\/FrontendInputsAndOutputs.h\"\n\n#include \"swift\/AST\/DiagnosticsFrontend.h\"\n#include \"swift\/Frontend\/FrontendOptions.h\"\n#include \"swift\/Option\/Options.h\"\n#include \"swift\/Parse\/Lexer.h\"\n#include \"swift\/Strings.h\"\n#include \"llvm\/Option\/Arg.h\"\n#include \"llvm\/Option\/ArgList.h\"\n#include \"llvm\/Option\/Option.h\"\n#include \"llvm\/Support\/ErrorHandling.h\"\n#include \"llvm\/Support\/FileSystem.h\"\n#include \"llvm\/Support\/LineIterator.h\"\n#include \"llvm\/Support\/Path.h\"\n\nusing namespace swift;\nusing namespace llvm::opt;\n\n\/\/ Constructors\n\nFrontendInputsAndOutputs::FrontendInputsAndOutputs(\n const FrontendInputsAndOutputs &other) {\n for (InputFile input : other.AllInputs)\n addInput(input);\n}\n\nFrontendInputsAndOutputs &FrontendInputsAndOutputs::\noperator=(const FrontendInputsAndOutputs &other) {\n clearInputs();\n for (InputFile input : other.AllInputs)\n addInput(input);\n return *this;\n}\n\n\/\/ All inputs:\n\nstd::vector<std::string> FrontendInputsAndOutputs::getInputFilenames() const {\n std::vector<std::string> filenames;\n for (auto &input : AllInputs) {\n filenames.push_back(input.file());\n }\n return filenames;\n}\n\nbool FrontendInputsAndOutputs::isReadingFromStdin() const {\n return hasSingleInput() && getFilenameOfFirstInput() == \"-\";\n}\n\nStringRef FrontendInputsAndOutputs::getFilenameOfFirstInput() const {\n assert(hasInputs());\n const InputFile &inp = AllInputs[0];\n StringRef f = inp.file();\n assert(!f.empty());\n return f;\n}\n\nvoid FrontendInputsAndOutputs::forEachInput(\n llvm::function_ref<void(const InputFile &)> fn) const {\n for (const InputFile &input : AllInputs)\n fn(input);\n}\n\n\/\/ Primaries:\n\nconst InputFile &FrontendInputsAndOutputs::firstPrimaryInput() const {\n assert(!PrimaryInputs.empty());\n for (const auto &f : AllInputs)\n if (f.isPrimary())\n return f;\n llvm_unreachable(\"no first primary?!\");\n}\n\nconst InputFile &FrontendInputsAndOutputs::lastPrimaryInput() const {\n assert(!PrimaryInputs.empty());\n for (const auto &f : reversed(AllInputs))\n if (f.isPrimary())\n return f;\n llvm_unreachable(\"no last primary?!\");\n}\n\nvoid FrontendInputsAndOutputs::forEachPrimaryInput(\n llvm::function_ref<void(const InputFile &)> fn) const {\n for (auto &f : AllInputs)\n if (f.isPrimary())\n fn(f);\n}\n\nvoid FrontendInputsAndOutputs::assertMustNotBeMoreThanOnePrimaryInput() const {\n assert(primaryInputCount() < 2 &&\n \"have not implemented >1 primary input yet\");\n}\n\nconst InputFile *FrontendInputsAndOutputs::getUniquePrimaryInput() const {\n assertMustNotBeMoreThanOnePrimaryInput();\n const auto b = PrimaryInputs.begin();\n return b == PrimaryInputs.end() ? nullptr : &AllInputs[b->second];\n}\n\nconst InputFile &\nFrontendInputsAndOutputs::getRequiredUniquePrimaryInput() const {\n if (const auto *input = getUniquePrimaryInput())\n return *input;\n llvm_unreachable(\"No primary when one is required\");\n}\n\nStringRef FrontendInputsAndOutputs::getNameOfUniquePrimaryInputFile() const {\n const auto *input = getUniquePrimaryInput();\n return input == nullptr ? StringRef() : input->file();\n}\n\nbool FrontendInputsAndOutputs::isInputPrimary(StringRef file) const {\n auto iterator = PrimaryInputs.find(file);\n return iterator != PrimaryInputs.end() &&\n AllInputs[iterator->second].isPrimary();\n}\n\nunsigned FrontendInputsAndOutputs::numberOfPrimaryInputsEndingWith(\n const char *extension) const {\n return count_if(\n PrimaryInputs, [&](const llvm::StringMapEntry<unsigned> &elem) -> bool {\n StringRef filename = AllInputs[elem.second].file();\n\n return llvm::sys::path::extension(filename).endswith(extension);\n });\n}\n\n\/\/ Input queries\n\nbool FrontendInputsAndOutputs::shouldTreatAsLLVM() const {\n if (hasSingleInput()) {\n StringRef Input(getFilenameOfFirstInput());\n return llvm::sys::path::extension(Input).endswith(LLVM_BC_EXTENSION) ||\n llvm::sys::path::extension(Input).endswith(LLVM_IR_EXTENSION);\n }\n return false;\n}\n\nbool FrontendInputsAndOutputs::shouldTreatAsSIL() const {\n if (hasSingleInput()) {\n \/\/ If we have exactly one input filename, and its extension is \"sil\",\n \/\/ treat the input as SIL.\n StringRef Input(getFilenameOfFirstInput());\n return llvm::sys::path::extension(Input).endswith(SIL_EXTENSION);\n }\n \/\/ If we have one primary input and it's a filename with extension \"sil\",\n \/\/ treat the input as SIL.\n unsigned silPrimaryCount = numberOfPrimaryInputsEndingWith(SIL_EXTENSION);\n if (silPrimaryCount == 0)\n return false;\n if (silPrimaryCount == primaryInputCount()) {\n \/\/ Not clear what to do someday with multiple primaries\n assertMustNotBeMoreThanOnePrimaryInput();\n return true;\n }\n llvm_unreachable(\"Either all primaries or none must end with .sil\");\n}\n\nbool FrontendInputsAndOutputs::areAllNonPrimariesSIB() const {\n for (const InputFile &input : AllInputs) {\n if (input.isPrimary())\n continue;\n if (!llvm::sys::path::extension(input.file()).endswith(SIB_EXTENSION)) {\n return false;\n }\n }\n return true;\n}\n\nbool FrontendInputsAndOutputs::verifyInputs(DiagnosticEngine &diags,\n bool treatAsSIL,\n bool isREPLRequested,\n bool isNoneRequested) const {\n if (isREPLRequested) {\n if (hasInputs()) {\n diags.diagnose(SourceLoc(), diag::error_repl_requires_no_input_files);\n return true;\n }\n } else if (treatAsSIL) {\n if (isWholeModule()) {\n if (inputCount() != 1) {\n diags.diagnose(SourceLoc(), diag::error_mode_requires_one_input_file);\n return true;\n }\n } else {\n assertMustNotBeMoreThanOnePrimaryInput();\n \/\/ If we have the SIL as our primary input, we can waive the one file\n \/\/ requirement as long as all the other inputs are SIBs.\n if (!areAllNonPrimariesSIB()) {\n diags.diagnose(SourceLoc(),\n diag::error_mode_requires_one_sil_multi_sib);\n return true;\n }\n }\n } else if (!isNoneRequested && !hasInputs()) {\n diags.diagnose(SourceLoc(), diag::error_mode_requires_an_input_file);\n return true;\n }\n return false;\n}\n\n\/\/ Changing inputs\n\nvoid FrontendInputsAndOutputs::clearInputs() {\n AllInputs.clear();\n PrimaryInputs.clear();\n}\n\nvoid FrontendInputsAndOutputs::addInput(const InputFile &input) {\n if (!input.file().empty() && input.isPrimary())\n PrimaryInputs.insert(std::make_pair(input.file(), AllInputs.size()));\n AllInputs.push_back(input);\n}\n\nvoid FrontendInputsAndOutputs::addInputFile(StringRef file,\n llvm::MemoryBuffer *buffer) {\n addInput(InputFile(file, false, buffer));\n}\n\nvoid FrontendInputsAndOutputs::addPrimaryInputFile(StringRef file,\n llvm::MemoryBuffer *buffer) {\n addInput(InputFile(file, true, buffer));\n}\n<commit_msg>Change conjunction to assertion in isInputPrimary to check consistency.<commit_after>\/\/===--- FrontendInputsAndOutputs.cpp -------------------------------------===\/\/\n\/\/\n\/\/ This source file is part of the Swift.org open source project\n\/\/\n\/\/ Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors\n\/\/ Licensed under Apache License v2.0 with Runtime Library Exception\n\/\/\n\/\/ See https:\/\/swift.org\/LICENSE.txt for license information\n\/\/ See https:\/\/swift.org\/CONTRIBUTORS.txt for the list of Swift project authors\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"swift\/Frontend\/FrontendInputsAndOutputs.h\"\n\n#include \"swift\/AST\/DiagnosticsFrontend.h\"\n#include \"swift\/Frontend\/FrontendOptions.h\"\n#include \"swift\/Option\/Options.h\"\n#include \"swift\/Parse\/Lexer.h\"\n#include \"swift\/Strings.h\"\n#include \"llvm\/Option\/Arg.h\"\n#include \"llvm\/Option\/ArgList.h\"\n#include \"llvm\/Option\/Option.h\"\n#include \"llvm\/Support\/ErrorHandling.h\"\n#include \"llvm\/Support\/FileSystem.h\"\n#include \"llvm\/Support\/LineIterator.h\"\n#include \"llvm\/Support\/Path.h\"\n\nusing namespace swift;\nusing namespace llvm::opt;\n\n\/\/ Constructors\n\nFrontendInputsAndOutputs::FrontendInputsAndOutputs(\n const FrontendInputsAndOutputs &other) {\n for (InputFile input : other.AllInputs)\n addInput(input);\n}\n\nFrontendInputsAndOutputs &FrontendInputsAndOutputs::\noperator=(const FrontendInputsAndOutputs &other) {\n clearInputs();\n for (InputFile input : other.AllInputs)\n addInput(input);\n return *this;\n}\n\n\/\/ All inputs:\n\nstd::vector<std::string> FrontendInputsAndOutputs::getInputFilenames() const {\n std::vector<std::string> filenames;\n for (auto &input : AllInputs) {\n filenames.push_back(input.file());\n }\n return filenames;\n}\n\nbool FrontendInputsAndOutputs::isReadingFromStdin() const {\n return hasSingleInput() && getFilenameOfFirstInput() == \"-\";\n}\n\nStringRef FrontendInputsAndOutputs::getFilenameOfFirstInput() const {\n assert(hasInputs());\n const InputFile &inp = AllInputs[0];\n StringRef f = inp.file();\n assert(!f.empty());\n return f;\n}\n\nvoid FrontendInputsAndOutputs::forEachInput(\n llvm::function_ref<void(const InputFile &)> fn) const {\n for (const InputFile &input : AllInputs)\n fn(input);\n}\n\n\/\/ Primaries:\n\nconst InputFile &FrontendInputsAndOutputs::firstPrimaryInput() const {\n assert(!PrimaryInputs.empty());\n for (const auto &f : AllInputs)\n if (f.isPrimary())\n return f;\n llvm_unreachable(\"no first primary?!\");\n}\n\nconst InputFile &FrontendInputsAndOutputs::lastPrimaryInput() const {\n assert(!PrimaryInputs.empty());\n for (const auto &f : reversed(AllInputs))\n if (f.isPrimary())\n return f;\n llvm_unreachable(\"no last primary?!\");\n}\n\nvoid FrontendInputsAndOutputs::forEachPrimaryInput(\n llvm::function_ref<void(const InputFile &)> fn) const {\n for (auto &f : AllInputs)\n if (f.isPrimary())\n fn(f);\n}\n\nvoid FrontendInputsAndOutputs::assertMustNotBeMoreThanOnePrimaryInput() const {\n assert(primaryInputCount() < 2 &&\n \"have not implemented >1 primary input yet\");\n}\n\nconst InputFile *FrontendInputsAndOutputs::getUniquePrimaryInput() const {\n assertMustNotBeMoreThanOnePrimaryInput();\n const auto b = PrimaryInputs.begin();\n return b == PrimaryInputs.end() ? nullptr : &AllInputs[b->second];\n}\n\nconst InputFile &\nFrontendInputsAndOutputs::getRequiredUniquePrimaryInput() const {\n if (const auto *input = getUniquePrimaryInput())\n return *input;\n llvm_unreachable(\"No primary when one is required\");\n}\n\nStringRef FrontendInputsAndOutputs::getNameOfUniquePrimaryInputFile() const {\n const auto *input = getUniquePrimaryInput();\n return input == nullptr ? StringRef() : input->file();\n}\n\nbool FrontendInputsAndOutputs::isInputPrimary(StringRef file) const {\n auto iterator = PrimaryInputs.find(file);\n if (iterator == PrimaryInputs.end())\n return false;\n assert(AllInputs[iterator->second].isPrimary() &&\n \"PrimaryInputs should only hold primaries\");\n return true;\n}\n\nunsigned FrontendInputsAndOutputs::numberOfPrimaryInputsEndingWith(\n const char *extension) const {\n return count_if(\n PrimaryInputs, [&](const llvm::StringMapEntry<unsigned> &elem) -> bool {\n StringRef filename = AllInputs[elem.second].file();\n\n return llvm::sys::path::extension(filename).endswith(extension);\n });\n}\n\n\/\/ Input queries\n\nbool FrontendInputsAndOutputs::shouldTreatAsLLVM() const {\n if (hasSingleInput()) {\n StringRef Input(getFilenameOfFirstInput());\n return llvm::sys::path::extension(Input).endswith(LLVM_BC_EXTENSION) ||\n llvm::sys::path::extension(Input).endswith(LLVM_IR_EXTENSION);\n }\n return false;\n}\n\nbool FrontendInputsAndOutputs::shouldTreatAsSIL() const {\n if (hasSingleInput()) {\n \/\/ If we have exactly one input filename, and its extension is \"sil\",\n \/\/ treat the input as SIL.\n StringRef Input(getFilenameOfFirstInput());\n return llvm::sys::path::extension(Input).endswith(SIL_EXTENSION);\n }\n \/\/ If we have one primary input and it's a filename with extension \"sil\",\n \/\/ treat the input as SIL.\n unsigned silPrimaryCount = numberOfPrimaryInputsEndingWith(SIL_EXTENSION);\n if (silPrimaryCount == 0)\n return false;\n if (silPrimaryCount == primaryInputCount()) {\n \/\/ Not clear what to do someday with multiple primaries\n assertMustNotBeMoreThanOnePrimaryInput();\n return true;\n }\n llvm_unreachable(\"Either all primaries or none must end with .sil\");\n}\n\nbool FrontendInputsAndOutputs::areAllNonPrimariesSIB() const {\n for (const InputFile &input : AllInputs) {\n if (input.isPrimary())\n continue;\n if (!llvm::sys::path::extension(input.file()).endswith(SIB_EXTENSION)) {\n return false;\n }\n }\n return true;\n}\n\nbool FrontendInputsAndOutputs::verifyInputs(DiagnosticEngine &diags,\n bool treatAsSIL,\n bool isREPLRequested,\n bool isNoneRequested) const {\n if (isREPLRequested) {\n if (hasInputs()) {\n diags.diagnose(SourceLoc(), diag::error_repl_requires_no_input_files);\n return true;\n }\n } else if (treatAsSIL) {\n if (isWholeModule()) {\n if (inputCount() != 1) {\n diags.diagnose(SourceLoc(), diag::error_mode_requires_one_input_file);\n return true;\n }\n } else {\n assertMustNotBeMoreThanOnePrimaryInput();\n \/\/ If we have the SIL as our primary input, we can waive the one file\n \/\/ requirement as long as all the other inputs are SIBs.\n if (!areAllNonPrimariesSIB()) {\n diags.diagnose(SourceLoc(),\n diag::error_mode_requires_one_sil_multi_sib);\n return true;\n }\n }\n } else if (!isNoneRequested && !hasInputs()) {\n diags.diagnose(SourceLoc(), diag::error_mode_requires_an_input_file);\n return true;\n }\n return false;\n}\n\n\/\/ Changing inputs\n\nvoid FrontendInputsAndOutputs::clearInputs() {\n AllInputs.clear();\n PrimaryInputs.clear();\n}\n\nvoid FrontendInputsAndOutputs::addInput(const InputFile &input) {\n if (!input.file().empty() && input.isPrimary())\n PrimaryInputs.insert(std::make_pair(input.file(), AllInputs.size()));\n AllInputs.push_back(input);\n}\n\nvoid FrontendInputsAndOutputs::addInputFile(StringRef file,\n llvm::MemoryBuffer *buffer) {\n addInput(InputFile(file, false, buffer));\n}\n\nvoid FrontendInputsAndOutputs::addPrimaryInputFile(StringRef file,\n llvm::MemoryBuffer *buffer) {\n addInput(InputFile(file, true, buffer));\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/------------------------------------------------------------------------------\n\/\/ CLING - the C++ LLVM-based InterpreterG :)\n\/\/ version: $Id$\n\/\/ author: Vassil Vassilev <vasil.georgiev.vasilev@cern.ch>\n\/\/------------------------------------------------------------------------------\n\n#include \"cling\/Interpreter\/DynamicLibraryManager.h\"\n#include \"cling\/Interpreter\/InvocationOptions.h\"\n\n#include \"llvm\/Support\/DynamicLibrary.h\"\n#include \"llvm\/Support\/FileSystem.h\"\n#include \"llvm\/Support\/Path.h\"\n#include \"llvm\/Support\/raw_ostream.h\"\n\n#include <stdlib.h>\n\n#ifdef WIN32\n#include <Windows.h>\n#else\n#include <limits.h> \/* PATH_MAX *\/\n#include <dlfcn.h>\n#endif\n\nnamespace cling {\n DynamicLibraryManager::DynamicLibraryManager(const InvocationOptions& Opts) \n : m_Opts(Opts) { }\n\n DynamicLibraryManager::~DynamicLibraryManager() {}\n\n static bool isSharedLib(llvm::StringRef LibName, bool& exists) {\n using namespace llvm::sys::fs;\n file_magic Magic;\n llvm::error_code Error = identify_magic(LibName, Magic);\n exists = (Error == llvm::errc::success);\n return exists &&\n#ifdef __APPLE__\n (Magic == file_magic::macho_fixed_virtual_memory_shared_lib\n || Magic == file_magic::macho_dynamically_linked_shared_lib\n || Magic == file_magic::macho_dynamically_linked_shared_lib_stub)\n#elif defined(LLVM_ON_UNIX)\n Magic == file_magic::elf_shared_object\n#elif defined(LLVM_ON_WIN32)\n# error \"Windows DLLs not yet implemented!\"\n \/\/Magic == file_magic::pecoff_executable?\n#else\n# error \"Unsupported platform.\"\n#endif\n ;\n }\n\n static void\n findSharedLibrary(llvm::StringRef fileStem,\n const llvm::SmallVectorImpl<std::string>& Paths,\n llvm::SmallString<512>& FoundDyLib,\n bool& exists, bool& isDyLib) {\n for (llvm::SmallVectorImpl<std::string>::const_iterator\n IPath = Paths.begin(), EPath = Paths.end(); IPath != EPath; ++IPath) {\n llvm::SmallString<512> ThisPath(*IPath);\n llvm::sys::path::append(ThisPath, fileStem);\n isDyLib = isSharedLib(ThisPath.str(), exists);\n if (isDyLib)\n ThisPath.swap(FoundDyLib);\n if (exists)\n return;\n }\n }\n\n#if defined(LLVM_ON_UNIX)\n static void GetSystemLibraryPaths(llvm::SmallVectorImpl<std::string>& Paths) {\n char* env_var = getenv(\"LD_LIBRARY_PATH\");\n#if __APPLE__\n if (!env_var)\n env_var = getenv(\"DYLD_LIBRARY_PATH\");\n if (!env_var)\n env_var = getenv(\"DYLD_FALLBACK_LIBRARY_PATH\");\n#endif\n if (env_var != 0) {\n static const char PathSeparator = ':';\n const char* at = env_var;\n const char* delim = strchr(at, PathSeparator);\n while (delim != 0) {\n std::string tmp(at, size_t(delim-at));\n if (llvm::sys::fs::is_directory(tmp.c_str()))\n Paths.push_back(tmp);\n at = delim + 1;\n delim = strchr(at, PathSeparator);\n }\n\n if (*at != 0)\n if (llvm::sys::fs::is_directory(llvm::StringRef(at)))\n Paths.push_back(at);\n }\n\n Paths.push_back(\"\/usr\/local\/lib\/\");\n Paths.push_back(\"\/usr\/X11R6\/lib\/\");\n Paths.push_back(\"\/usr\/lib\/\");\n Paths.push_back(\"\/lib\/\");\n }\n#elif defined(LLVM_ON_WIN32)\n static void GetSystemLibraryPaths(llvm::SmallVectorImpl<std::string>& Paths) {\n char buff[MAX_PATH];\n \/\/ Generic form of C:\\Windows\\System32\n HRESULT res = SHGetFolderPathA(NULL,\n CSIDL_FLAG_CREATE | CSIDL_SYSTEM,\n NULL,\n SHGFP_TYPE_CURRENT,\n buff);\n if (res != S_OK) {\n assert(0 && \"Failed to get system directory\");\n return;\n }\n Paths.push_back(buff);\n\n \/\/ Reset buff.\n buff[0] = 0;\n \/\/ Generic form of C:\\Windows\n res = SHGetFolderPathA(NULL,\n CSIDL_FLAG_CREATE | CSIDL_WINDOWS,\n NULL,\n SHGFP_TYPE_CURRENT,\n buff);\n if (res != S_OK) {\n assert(0 && \"Failed to get windows directory\");\n return;\n }\n Paths.push_back(buff);\n }\n#else\n# error \"Unsupported platform.\"\n#endif\n\n DynamicLibraryManager::LoadLibResult\n DynamicLibraryManager::tryLinker(const std::string& filename, bool permanent,\n bool isAbsolute, bool& exists,\n bool& isDyLib) {\n using namespace llvm::sys;\n exists = false;\n isDyLib = false;\n\n llvm::SmallString<512> FoundDyLib;\n\n if (isAbsolute) {\n isDyLib = isSharedLib(filename, exists);\n if (isDyLib)\n FoundDyLib = filename;\n } else {\n llvm::SmallVector<std::string, 16>\n SearchPaths(m_Opts.LibSearchPath.begin(), m_Opts.LibSearchPath.end());\n GetSystemLibraryPaths(SearchPaths);\n\n findSharedLibrary(filename, SearchPaths, FoundDyLib, exists, isDyLib);\n\n if (!exists) {\n \/\/ Add DyLib extension:\n llvm::SmallString<512> filenameWithExt(filename);\n#if defined(LLVM_ON_UNIX)\n#ifdef __APPLE__\n llvm::SmallString<512>::iterator IStemEnd = filenameWithExt.end() - 1;\n#endif\n static const char* DyLibExt = \".so\";\n#elif defined(LLVM_ON_WIN32)\n static const char* DyLibExt = \".dll\";\n#else\n# error \"Unsupported platform.\"\n#endif\n filenameWithExt += DyLibExt;\n findSharedLibrary(filenameWithExt, SearchPaths, FoundDyLib, exists,\n isDyLib);\n#ifdef __APPLE__\n if (!exists) {\n filenameWithExt.erase(IStemEnd + 1, filenameWithExt.end());\n filenameWithExt += \".dylib\";\n findSharedLibrary(filenameWithExt, SearchPaths, FoundDyLib, exists,\n isDyLib);\n }\n#endif\n }\n }\n\n if (!isDyLib)\n return kLoadLibError;\n \n assert(!FoundDyLib.empty() && \"The shared lib exists but can't find it!\");\n\n \/\/ get canonical path name and check if already loaded\n#ifdef WIN32\n llvm::SmallString<_MAX_PATH> FullPath;\n FullPath.set_size(_MAX_PATH);\n char *res = _fullpath((char *)FullPath.data(), FoundDyLib.c_str(), _MAX_PATH);\n#else\n llvm::SmallString<PATH_MAX+1> FullPath;\n FullPath.set_size(PATH_MAX+1);\n char *res = realpath(FoundDyLib.c_str(), (char *)FullPath.data());\n#endif\n if (res == 0) {\n llvm::errs() << \"cling::Interpreter::tryLinker(): error getting real (canonical) path\\n\";\n return kLoadLibError;\n }\n FullPath.set_size(strlen(res));\n if (m_loadedLibraries.find(FullPath) != m_loadedLibraries.end())\n return kLoadLibExists;\n\n \/\/ TODO: !permanent case\n#ifdef WIN32\n# error \"Windows DLL opening still needs to be implemented!\"\n void* dyLibHandle = needs to be implemented!;\n std::string errMsg;\n#else\n const void* dyLibHandle = dlopen(FullPath.c_str(), RTLD_LAZY|RTLD_GLOBAL);\n std::string errMsg;\n if (const char* DyLibError = dlerror()) {\n errMsg = DyLibError;\n }\n#endif\n if (!dyLibHandle) {\n llvm::errs() << \"cling::Interpreter::tryLinker(): \" << errMsg << '\\n';\n return kLoadLibError;\n }\n std::pair<DyLibs::iterator, bool> insRes\n = m_DyLibs.insert(std::pair<DyLibHandle, std::string>(dyLibHandle,\n FullPath.str()));\n if (!insRes.second)\n return kLoadLibExists;\n m_loadedLibraries.insert(FullPath);\n return kLoadLibSuccess;\n }\n\n DynamicLibraryManager::LoadLibResult\n DynamicLibraryManager::loadLibrary(const std::string& filename,\n bool permanent, bool* tryCode) {\n llvm::SmallString<128> Absolute((llvm::StringRef(filename)));\n llvm::sys::fs::make_absolute(Absolute);\n bool isAbsolute = filename == Absolute.c_str();\n bool exists = false;\n bool isDyLib = false;\n LoadLibResult res = tryLinker(filename, permanent, isAbsolute, exists,\n isDyLib);\n if (tryCode) {\n *tryCode = !isDyLib;\n if (isAbsolute)\n *tryCode &= exists;\n }\n if (exists)\n return res;\n\n if (!isAbsolute && filename.compare(0, 3, \"lib\")) {\n \/\/ try with \"lib\" prefix:\n res = tryLinker(\"lib\" + filename, permanent, false, exists, isDyLib);\n if (tryCode) {\n *tryCode = !isDyLib;\n if (isAbsolute)\n *tryCode &= exists;\n }\n if (res != kLoadLibError)\n return res;\n }\n return kLoadLibError;\n }\n\n bool\n DynamicLibraryManager::isDynamicLibraryLoaded(llvm::StringRef fullPath) const {\n \/\/ get canonical path name and check if already loaded\n#ifdef WIN32\n char buf[_MAX_PATH];\n char *res = _fullpath(buf, fullPath.str().c_str(), _MAX_PATH);\n#else\n char buf[PATH_MAX+1];\n char *res = realpath(fullPath.str().c_str(), buf);\n#endif\n if (res == 0) {\n llvm::errs() << \"cling::Interpreter::isDynamicLibraryLoaded(): error getting real (canonical) path\\n\";\n return false;\n }\n if (m_loadedLibraries.find(buf) != m_loadedLibraries.end()) return true;\n return false;\n }\n\n void DynamicLibraryManager::ExposeHiddenSharedLibrarySymbols(void* handle) {\n llvm::sys::DynamicLibrary::addPermanentLibrary(const_cast<void*>(handle));\n }\n} \/\/ end namespace cling\n<commit_msg>Another attempt to fix a buffer overflow error on ubuntu (optimized mode only, making it hard to debug...)<commit_after>\/\/------------------------------------------------------------------------------\n\/\/ CLING - the C++ LLVM-based InterpreterG :)\n\/\/ version: $Id$\n\/\/ author: Vassil Vassilev <vasil.georgiev.vasilev@cern.ch>\n\/\/------------------------------------------------------------------------------\n\n#include \"cling\/Interpreter\/DynamicLibraryManager.h\"\n#include \"cling\/Interpreter\/InvocationOptions.h\"\n\n#include \"llvm\/Support\/DynamicLibrary.h\"\n#include \"llvm\/Support\/FileSystem.h\"\n#include \"llvm\/Support\/Path.h\"\n#include \"llvm\/Support\/raw_ostream.h\"\n\n#include <stdlib.h>\n\n#ifdef WIN32\n#include <Windows.h>\n#else\n#include <limits.h> \/* PATH_MAX *\/\n#include <dlfcn.h>\n#endif\n\nnamespace cling {\n DynamicLibraryManager::DynamicLibraryManager(const InvocationOptions& Opts) \n : m_Opts(Opts) { }\n\n DynamicLibraryManager::~DynamicLibraryManager() {}\n\n static bool isSharedLib(llvm::StringRef LibName, bool& exists) {\n using namespace llvm::sys::fs;\n file_magic Magic;\n llvm::error_code Error = identify_magic(LibName, Magic);\n exists = (Error == llvm::errc::success);\n return exists &&\n#ifdef __APPLE__\n (Magic == file_magic::macho_fixed_virtual_memory_shared_lib\n || Magic == file_magic::macho_dynamically_linked_shared_lib\n || Magic == file_magic::macho_dynamically_linked_shared_lib_stub)\n#elif defined(LLVM_ON_UNIX)\n Magic == file_magic::elf_shared_object\n#elif defined(LLVM_ON_WIN32)\n# error \"Windows DLLs not yet implemented!\"\n \/\/Magic == file_magic::pecoff_executable?\n#else\n# error \"Unsupported platform.\"\n#endif\n ;\n }\n\n static void\n findSharedLibrary(llvm::StringRef fileStem,\n const llvm::SmallVectorImpl<std::string>& Paths,\n llvm::SmallString<512>& FoundDyLib,\n bool& exists, bool& isDyLib) {\n for (llvm::SmallVectorImpl<std::string>::const_iterator\n IPath = Paths.begin(), EPath = Paths.end(); IPath != EPath; ++IPath) {\n llvm::SmallString<512> ThisPath(*IPath);\n llvm::sys::path::append(ThisPath, fileStem);\n isDyLib = isSharedLib(ThisPath.str(), exists);\n if (isDyLib)\n ThisPath.swap(FoundDyLib);\n if (exists)\n return;\n }\n }\n\n#if defined(LLVM_ON_UNIX)\n static void GetSystemLibraryPaths(llvm::SmallVectorImpl<std::string>& Paths) {\n char* env_var = getenv(\"LD_LIBRARY_PATH\");\n#if __APPLE__\n if (!env_var)\n env_var = getenv(\"DYLD_LIBRARY_PATH\");\n if (!env_var)\n env_var = getenv(\"DYLD_FALLBACK_LIBRARY_PATH\");\n#endif\n if (env_var != 0) {\n static const char PathSeparator = ':';\n const char* at = env_var;\n const char* delim = strchr(at, PathSeparator);\n while (delim != 0) {\n std::string tmp(at, size_t(delim-at));\n if (llvm::sys::fs::is_directory(tmp.c_str()))\n Paths.push_back(tmp);\n at = delim + 1;\n delim = strchr(at, PathSeparator);\n }\n\n if (*at != 0)\n if (llvm::sys::fs::is_directory(llvm::StringRef(at)))\n Paths.push_back(at);\n }\n\n Paths.push_back(\"\/usr\/local\/lib\/\");\n Paths.push_back(\"\/usr\/X11R6\/lib\/\");\n Paths.push_back(\"\/usr\/lib\/\");\n Paths.push_back(\"\/lib\/\");\n }\n#elif defined(LLVM_ON_WIN32)\n static void GetSystemLibraryPaths(llvm::SmallVectorImpl<std::string>& Paths) {\n char buff[MAX_PATH];\n \/\/ Generic form of C:\\Windows\\System32\n HRESULT res = SHGetFolderPathA(NULL,\n CSIDL_FLAG_CREATE | CSIDL_SYSTEM,\n NULL,\n SHGFP_TYPE_CURRENT,\n buff);\n if (res != S_OK) {\n assert(0 && \"Failed to get system directory\");\n return;\n }\n Paths.push_back(buff);\n\n \/\/ Reset buff.\n buff[0] = 0;\n \/\/ Generic form of C:\\Windows\n res = SHGetFolderPathA(NULL,\n CSIDL_FLAG_CREATE | CSIDL_WINDOWS,\n NULL,\n SHGFP_TYPE_CURRENT,\n buff);\n if (res != S_OK) {\n assert(0 && \"Failed to get windows directory\");\n return;\n }\n Paths.push_back(buff);\n }\n#else\n# error \"Unsupported platform.\"\n#endif\n\n DynamicLibraryManager::LoadLibResult\n DynamicLibraryManager::tryLinker(const std::string& filename, bool permanent,\n bool isAbsolute, bool& exists,\n bool& isDyLib) {\n using namespace llvm::sys;\n exists = false;\n isDyLib = false;\n\n llvm::SmallString<512> FoundDyLib;\n\n if (isAbsolute) {\n isDyLib = isSharedLib(filename, exists);\n if (isDyLib)\n FoundDyLib = filename;\n } else {\n llvm::SmallVector<std::string, 16>\n SearchPaths(m_Opts.LibSearchPath.begin(), m_Opts.LibSearchPath.end());\n GetSystemLibraryPaths(SearchPaths);\n\n findSharedLibrary(filename, SearchPaths, FoundDyLib, exists, isDyLib);\n\n if (!exists) {\n \/\/ Add DyLib extension:\n llvm::SmallString<512> filenameWithExt(filename);\n#if defined(LLVM_ON_UNIX)\n#ifdef __APPLE__\n llvm::SmallString<512>::iterator IStemEnd = filenameWithExt.end() - 1;\n#endif\n static const char* DyLibExt = \".so\";\n#elif defined(LLVM_ON_WIN32)\n static const char* DyLibExt = \".dll\";\n#else\n# error \"Unsupported platform.\"\n#endif\n filenameWithExt += DyLibExt;\n findSharedLibrary(filenameWithExt, SearchPaths, FoundDyLib, exists,\n isDyLib);\n#ifdef __APPLE__\n if (!exists) {\n filenameWithExt.erase(IStemEnd + 1, filenameWithExt.end());\n filenameWithExt += \".dylib\";\n findSharedLibrary(filenameWithExt, SearchPaths, FoundDyLib, exists,\n isDyLib);\n }\n#endif\n }\n }\n\n if (!isDyLib)\n return kLoadLibError;\n \n assert(!FoundDyLib.empty() && \"The shared lib exists but can't find it!\");\n\n \/\/ get canonical path name and check if already loaded\n#ifdef WIN32\n llvm::SmallString<_MAX_PATH> FullPath(\"\");\n char *res = _fullpath((char *)FullPath.data(), FoundDyLib.c_str(), _MAX_PATH);\n#else\n llvm::SmallString<PATH_MAX+1> FullPath(\"\");\n char *res = realpath(FoundDyLib.c_str(), (char *)FullPath.data());\n#endif\n if (res == 0) {\n llvm::errs() << \"cling::Interpreter::tryLinker(): error getting real (canonical) path\\n\";\n return kLoadLibError;\n }\n FullPath.set_size(strlen(res));\n if (m_loadedLibraries.find(FullPath) != m_loadedLibraries.end())\n return kLoadLibExists;\n\n \/\/ TODO: !permanent case\n#ifdef WIN32\n# error \"Windows DLL opening still needs to be implemented!\"\n void* dyLibHandle = needs to be implemented!;\n std::string errMsg;\n#else\n const void* dyLibHandle = dlopen(FullPath.c_str(), RTLD_LAZY|RTLD_GLOBAL);\n std::string errMsg;\n if (const char* DyLibError = dlerror()) {\n errMsg = DyLibError;\n }\n#endif\n if (!dyLibHandle) {\n llvm::errs() << \"cling::Interpreter::tryLinker(): \" << errMsg << '\\n';\n return kLoadLibError;\n }\n std::pair<DyLibs::iterator, bool> insRes\n = m_DyLibs.insert(std::pair<DyLibHandle, std::string>(dyLibHandle,\n FullPath.str()));\n if (!insRes.second)\n return kLoadLibExists;\n m_loadedLibraries.insert(FullPath);\n return kLoadLibSuccess;\n }\n\n DynamicLibraryManager::LoadLibResult\n DynamicLibraryManager::loadLibrary(const std::string& filename,\n bool permanent, bool* tryCode) {\n llvm::SmallString<128> Absolute((llvm::StringRef(filename)));\n llvm::sys::fs::make_absolute(Absolute);\n bool isAbsolute = filename == Absolute.c_str();\n bool exists = false;\n bool isDyLib = false;\n LoadLibResult res = tryLinker(filename, permanent, isAbsolute, exists,\n isDyLib);\n if (tryCode) {\n *tryCode = !isDyLib;\n if (isAbsolute)\n *tryCode &= exists;\n }\n if (exists)\n return res;\n\n if (!isAbsolute && filename.compare(0, 3, \"lib\")) {\n \/\/ try with \"lib\" prefix:\n res = tryLinker(\"lib\" + filename, permanent, false, exists, isDyLib);\n if (tryCode) {\n *tryCode = !isDyLib;\n if (isAbsolute)\n *tryCode &= exists;\n }\n if (res != kLoadLibError)\n return res;\n }\n return kLoadLibError;\n }\n\n bool\n DynamicLibraryManager::isDynamicLibraryLoaded(llvm::StringRef fullPath) const {\n \/\/ get canonical path name and check if already loaded\n#ifdef WIN32\n char buf[_MAX_PATH];\n char *res = _fullpath(buf, fullPath.str().c_str(), _MAX_PATH);\n#else\n char buf[PATH_MAX+1];\n char *res = realpath(fullPath.str().c_str(), buf);\n#endif\n if (res == 0) {\n llvm::errs() << \"cling::Interpreter::isDynamicLibraryLoaded(): error getting real (canonical) path\\n\";\n return false;\n }\n if (m_loadedLibraries.find(buf) != m_loadedLibraries.end()) return true;\n return false;\n }\n\n void DynamicLibraryManager::ExposeHiddenSharedLibrarySymbols(void* handle) {\n llvm::sys::DynamicLibrary::addPermanentLibrary(const_cast<void*>(handle));\n }\n} \/\/ end namespace cling\n<|endoftext|>"} {"text":"<commit_before>#include \"Entity.hpp\"\n\n#include <glm\/gtc\/matrix_transform.hpp>\n#include \"..\/Component\/Animation.hpp\"\n#include \"..\/Component\/Lens.hpp\"\n#include \"..\/Component\/Mesh.hpp\"\n#include \"..\/Component\/Material.hpp\"\n#include \"..\/Component\/DirectionalLight.hpp\"\n#include \"..\/Component\/PointLight.hpp\"\n#include \"..\/Component\/SpotLight.hpp\"\n#include \"..\/Component\/Physics.hpp\"\n#include \"..\/Component\/Listener.hpp\"\n#include \"..\/Component\/Script.hpp\"\n#include \"..\/Component\/SoundSource.hpp\"\n#include \"..\/Component\/ParticleEmitter.hpp\"\n#include \"..\/Util\/Json.hpp\"\n#include \"..\/Util\/FileSystem.hpp\"\n#include <Utility\/Log.hpp>\n#include \"..\/Hymn.hpp\"\n#include <fstream>\n#include \"..\/Manager\/Managers.hpp\"\n#include \"..\/Manager\/ParticleManager.hpp\"\n#include \"..\/Manager\/PhysicsManager.hpp\"\n#include \"..\/Manager\/RenderManager.hpp\"\n#include \"..\/Manager\/ScriptManager.hpp\"\n#include \"..\/Manager\/SoundManager.hpp\"\n\nEntity::Entity(World* world, const std::string& name) : name ( name ) {\n this->world = world;\n}\n\nEntity::~Entity() {\n \n}\n\nEntity* Entity::GetParent() const {\n return parent;\n}\n\nEntity* Entity::AddChild(const std::string& name) {\n Entity* child = world->CreateEntity(name);\n child->parent = this;\n children.push_back(child);\n return child;\n}\n\nbool Entity::SetParent(Entity* newParent) {\n \/\/We make sure we're not trying to put the root as a child.\n if (parent != nullptr) {\n \/\/We make sure we're not trying to set a parent as a child to one of it's own children.\n if (!HasChild(newParent)) {\n parent->RemoveChild(this);\n parent = newParent;\n newParent->children.push_back(this);\n \n return true;\n }\n }\n \n return false;\n}\n\nbool Entity::HasChild(const Entity* check_child, bool deep) const {\n for (Entity* child : children) {\n if (child->name == check_child->name)\n return true;\n else if (deep)\n child->HasChild(check_child);\n }\n\n return false;\n}\n\nEntity* Entity::InstantiateScene(const std::string& name) {\n Entity* child = AddChild();\n \n \/\/ Load scene.\n std::string filename = Hymn().GetPath() + FileSystem::DELIMITER + \"Scenes\" + FileSystem::DELIMITER + name + \".json\";\n if (FileSystem::FileExists(filename.c_str())) {\n Json::Value root;\n std::ifstream file(filename);\n file >> root;\n file.close();\n child->Load(root);\n \n child->scene = true;\n child->sceneName = name;\n } else {\n child->name = \"Error loading scene\";\n Log() << \"Couldn't find scene to load.\";\n }\n \n return child;\n}\n\nconst std::vector<Entity*>& Entity::GetChildren() const {\n return children;\n}\n\nEntity* Entity::GetChild(const std::string& name) const {\n for (Entity* child : children) {\n if (child->name == name)\n return child;\n }\n \n return nullptr;\n}\n\nbool Entity::RemoveChild(Entity* child) {\n for (auto it = children.begin(); it != children.end(); ++it) {\n if (*it == child) {\n children.erase(it);\n return true;\n }\n }\n \n return false;\n}\n\nbool Entity::IsScene() const {\n return scene;\n}\n\nvoid Entity::Kill() {\n KillHelper();\n \n \/\/ Remove this entity from the parent's list of children.\n if (parent != nullptr)\n parent->RemoveChild(this);\n}\n\nbool Entity::IsKilled() const {\n return killed;\n}\n\nJson::Value Entity::Save() const {\n Json::Value entity;\n entity[\"name\"] = name;\n entity[\"position\"] = Json::SaveVec3(position);\n entity[\"scale\"] = Json::SaveVec3(scale);\n entity[\"rotation\"] = Json::SaveVec3(rotation);\n entity[\"scene\"] = scene;\n entity[\"uid\"] = uniqueIdentifier;\n \n if (scene) {\n entity[\"sceneName\"] = sceneName;\n } else {\n \/\/ Save components.\n Save<Component::Animation>(entity, \"Animation\");\n Save<Component::Lens>(entity, \"Lens\");\n Save<Component::Mesh>(entity, \"Mesh\");\n Save<Component::Material>(entity, \"Material\");\n Save<Component::DirectionalLight>(entity, \"DirectionalLight\");\n Save<Component::PointLight>(entity, \"PointLight\");\n Save<Component::SpotLight>(entity, \"SpotLight\");\n Save<Component::Physics>(entity, \"Physics\");\n Save<Component::Listener>(entity, \"Listener\");\n Save<Component::Script>(entity, \"Script\");\n Save<Component::SoundSource>(entity, \"SoundSource\");\n Save<Component::ParticleEmitter>(entity, \"ParticleEmitter\");\n \n \/\/ Save children.\n Json::Value childNodes;\n for (Entity* child : children)\n childNodes.append(child->Save());\n entity[\"children\"] = childNodes;\n }\n \n return entity;\n}\n\nvoid Entity::Load(const Json::Value& node) {\n scene = node[\"scene\"].asBool();\n \n if (scene) {\n sceneName = node[\"sceneName\"].asString();\n \n \/\/ Load scene.\n std::string filename = Hymn().GetPath() + FileSystem::DELIMITER + \"Scenes\" + FileSystem::DELIMITER + sceneName + \".json\";\n Json::Value root;\n std::ifstream file(filename);\n file >> root;\n file.close();\n Load(root);\n \n scene = true;\n } else {\n \/\/ Load components.\n Load<Component::Animation>(node, \"Animation\");\n Load<Component::Lens>(node, \"Lens\");\n Load<Component::Mesh>(node, \"Mesh\");\n Load<Component::Material>(node, \"Material\");\n Load<Component::DirectionalLight>(node, \"DirectionalLight\");\n Load<Component::PointLight>(node, \"PointLight\");\n Load<Component::SpotLight>(node, \"SpotLight\");\n Load<Component::Physics>(node, \"Physics\");\n Load<Component::Listener>(node, \"Listener\");\n Load<Component::Script>(node, \"Script\");\n Load<Component::SoundSource>(node, \"SoundSource\");\n Load<Component::ParticleEmitter>(node, \"ParticleEmitter\");\n \n \/\/ Load children.\n for (unsigned int i=0; i < node[\"children\"].size(); ++i) {\n Entity* entity = AddChild(\"\");\n entity->Load(node[\"children\"][i]);\n }\n }\n \n name = node.get(\"name\", \"\").asString();\n position = Json::LoadVec3(node[\"position\"]);\n scale = Json::LoadVec3(node[\"scale\"]);\n rotation = Json::LoadVec3(node[\"rotation\"]);\n uniqueIdentifier = node.get(\"uid\", 0).asUInt();\n \n}\n\nglm::mat4 Entity::GetModelMatrix() const {\n glm::mat4 matrix = glm::translate(glm::mat4(), position) * GetOrientation() * glm::scale(glm::mat4(), scale);\n \n if (parent != nullptr)\n matrix = parent->GetModelMatrix() * matrix;\n \n return matrix;\n}\n\nglm::mat4 Entity::GetOrientation() const {\n glm::mat4 orientation;\n orientation = glm::rotate(orientation, glm::radians(rotation.x), glm::vec3(0.f, 1.f, 0.f));\n orientation = glm::rotate(orientation, glm::radians(rotation.y), glm::vec3(1.f, 0.f, 0.f));\n return glm::rotate(orientation, glm::radians(rotation.z), glm::vec3(0.f, 0.f, 1.f));\n}\n\nglm::mat4 Entity::GetCameraOrientation() const {\n glm::mat4 orientation;\n orientation = glm::rotate(orientation, glm::radians(rotation.z), glm::vec3(0.f, 0.f, 1.f));\n orientation = glm::rotate(orientation, glm::radians(rotation.y), glm::vec3(1.f, 0.f, 0.f));\n return glm::rotate(orientation, glm::radians(rotation.x), glm::vec3(0.f, 1.f, 0.f));\n}\n\nglm::vec3 Entity::GetDirection() const {\n return glm::normalize(glm::vec3(GetOrientation() * glm::vec4(0.f, 0.f, -1.f, 0.f)));\n}\n\nglm::vec3 Entity::GetWorldPosition() const {\n if (parent != nullptr)\n return glm::vec3(parent->GetModelMatrix() * glm::vec4(position, 1.f));\n \n return position;\n}\n\nunsigned int Entity::GetUniqueIdentifier() const {\n return uniqueIdentifier;\n}\n\nvoid Entity::SetUniqueIdentifier(unsigned int UID) {\n uniqueIdentifier = UID;\n}\n\nComponent::SuperComponent* Entity::AddComponent(const std::type_info* componentType) {\n Component::SuperComponent* component;\n \n \/\/ Create a component in the correct manager.\n if (*componentType == typeid(Component::Animation*))\n component = Managers().renderManager->CreateAnimation();\n else if (*componentType == typeid(Component::DirectionalLight*))\n component = Managers().renderManager->CreateDirectionalLight();\n else if (*componentType == typeid(Component::Lens*))\n component = Managers().renderManager->CreateLens();\n else if (*componentType == typeid(Component::Listener*))\n component = Managers().soundManager->CreateListener();\n else if (*componentType == typeid(Component::Material*))\n component = Managers().renderManager->CreateMaterial();\n else if (*componentType == typeid(Component::Mesh*))\n component = Managers().renderManager->CreateMesh();\n else if (*componentType == typeid(Component::ParticleEmitter*))\n component = Managers().particleManager->CreateParticleEmitter();\n else if (*componentType == typeid(Component::Physics*))\n component = Managers().physicsManager->CreatePhysics();\n else if (*componentType == typeid(Component::PointLight*))\n component = Managers().renderManager->CreatePointLight();\n else if (*componentType == typeid(Component::Script*))\n component = Managers().scriptManager->CreateScript();\n else if (*componentType == typeid(Component::SoundSource*))\n component = Managers().soundManager->CreateSoundSource();\n else if (*componentType == typeid(Component::SpotLight*))\n component = Managers().renderManager->CreateSpotLight();\n else\n Log() << componentType->name() << \" not assigned to a manager!\" << \"\\n\";\n \n \/\/ Add component to our map.\n components[componentType] = component;\n \n \/\/ Set ourselves as the owner.\n component->entity = this;\n \n return component;\n}\n\nvoid Entity::LoadComponent(const std::type_info* componentType, const Json::Value& node) {\n Component::SuperComponent* component;\n \n \/\/ Create a component in the correct manager.\n if (*componentType == typeid(Component::Animation*))\n component = Managers().renderManager->CreateAnimation(node);\n else if (*componentType == typeid(Component::DirectionalLight*))\n component = Managers().renderManager->CreateDirectionalLight(node);\n else if (*componentType == typeid(Component::Lens*))\n component = Managers().renderManager->CreateLens(node);\n else if (*componentType == typeid(Component::Listener*))\n component = Managers().soundManager->CreateListener(node);\n else if (*componentType == typeid(Component::Material*))\n component = Managers().renderManager->CreateMaterial(node);\n else if (*componentType == typeid(Component::Mesh*))\n component = Managers().renderManager->CreateMesh(node);\n else if (*componentType == typeid(Component::ParticleEmitter*))\n component = Managers().particleManager->CreateParticleEmitter(node);\n else if (*componentType == typeid(Component::Physics*))\n component = Managers().physicsManager->CreatePhysics(node);\n else if (*componentType == typeid(Component::PointLight*))\n component = Managers().renderManager->CreatePointLight(node);\n else if (*componentType == typeid(Component::Script*))\n component = Managers().scriptManager->CreateScript(node);\n else if (*componentType == typeid(Component::SoundSource*))\n component = Managers().soundManager->CreateSoundSource(node);\n else if (*componentType == typeid(Component::SpotLight*))\n component = Managers().renderManager->CreateSpotLight(node);\n else\n Log() << componentType->name() << \" not assigned to a manager!\" << \"\\n\";\n \n \/\/ Add component to our map.\n components[componentType] = component;\n \n \/\/ Set ourselves as the owner.\n component->entity = this;\n}\n\nvoid Entity::KillHelper() {\n killed = true;\n \n for (auto& it : components)\n it.second->Kill();\n \n for (Entity* child : children) {\n child->KillHelper();\n }\n}\n<commit_msg>Fix potential use of unintialized variable<commit_after>#include \"Entity.hpp\"\n\n#include <glm\/gtc\/matrix_transform.hpp>\n#include \"..\/Component\/Animation.hpp\"\n#include \"..\/Component\/Lens.hpp\"\n#include \"..\/Component\/Mesh.hpp\"\n#include \"..\/Component\/Material.hpp\"\n#include \"..\/Component\/DirectionalLight.hpp\"\n#include \"..\/Component\/PointLight.hpp\"\n#include \"..\/Component\/SpotLight.hpp\"\n#include \"..\/Component\/Physics.hpp\"\n#include \"..\/Component\/Listener.hpp\"\n#include \"..\/Component\/Script.hpp\"\n#include \"..\/Component\/SoundSource.hpp\"\n#include \"..\/Component\/ParticleEmitter.hpp\"\n#include \"..\/Util\/Json.hpp\"\n#include \"..\/Util\/FileSystem.hpp\"\n#include <Utility\/Log.hpp>\n#include \"..\/Hymn.hpp\"\n#include <fstream>\n#include \"..\/Manager\/Managers.hpp\"\n#include \"..\/Manager\/ParticleManager.hpp\"\n#include \"..\/Manager\/PhysicsManager.hpp\"\n#include \"..\/Manager\/RenderManager.hpp\"\n#include \"..\/Manager\/ScriptManager.hpp\"\n#include \"..\/Manager\/SoundManager.hpp\"\n\nEntity::Entity(World* world, const std::string& name) : name ( name ) {\n this->world = world;\n}\n\nEntity::~Entity() {\n \n}\n\nEntity* Entity::GetParent() const {\n return parent;\n}\n\nEntity* Entity::AddChild(const std::string& name) {\n Entity* child = world->CreateEntity(name);\n child->parent = this;\n children.push_back(child);\n return child;\n}\n\nbool Entity::SetParent(Entity* newParent) {\n \/\/We make sure we're not trying to put the root as a child.\n if (parent != nullptr) {\n \/\/We make sure we're not trying to set a parent as a child to one of it's own children.\n if (!HasChild(newParent)) {\n parent->RemoveChild(this);\n parent = newParent;\n newParent->children.push_back(this);\n \n return true;\n }\n }\n \n return false;\n}\n\nbool Entity::HasChild(const Entity* check_child, bool deep) const {\n for (Entity* child : children) {\n if (child->name == check_child->name)\n return true;\n else if (deep)\n child->HasChild(check_child);\n }\n\n return false;\n}\n\nEntity* Entity::InstantiateScene(const std::string& name) {\n Entity* child = AddChild();\n \n \/\/ Load scene.\n std::string filename = Hymn().GetPath() + FileSystem::DELIMITER + \"Scenes\" + FileSystem::DELIMITER + name + \".json\";\n if (FileSystem::FileExists(filename.c_str())) {\n Json::Value root;\n std::ifstream file(filename);\n file >> root;\n file.close();\n child->Load(root);\n \n child->scene = true;\n child->sceneName = name;\n } else {\n child->name = \"Error loading scene\";\n Log() << \"Couldn't find scene to load.\";\n }\n \n return child;\n}\n\nconst std::vector<Entity*>& Entity::GetChildren() const {\n return children;\n}\n\nEntity* Entity::GetChild(const std::string& name) const {\n for (Entity* child : children) {\n if (child->name == name)\n return child;\n }\n \n return nullptr;\n}\n\nbool Entity::RemoveChild(Entity* child) {\n for (auto it = children.begin(); it != children.end(); ++it) {\n if (*it == child) {\n children.erase(it);\n return true;\n }\n }\n \n return false;\n}\n\nbool Entity::IsScene() const {\n return scene;\n}\n\nvoid Entity::Kill() {\n KillHelper();\n \n \/\/ Remove this entity from the parent's list of children.\n if (parent != nullptr)\n parent->RemoveChild(this);\n}\n\nbool Entity::IsKilled() const {\n return killed;\n}\n\nJson::Value Entity::Save() const {\n Json::Value entity;\n entity[\"name\"] = name;\n entity[\"position\"] = Json::SaveVec3(position);\n entity[\"scale\"] = Json::SaveVec3(scale);\n entity[\"rotation\"] = Json::SaveVec3(rotation);\n entity[\"scene\"] = scene;\n entity[\"uid\"] = uniqueIdentifier;\n \n if (scene) {\n entity[\"sceneName\"] = sceneName;\n } else {\n \/\/ Save components.\n Save<Component::Animation>(entity, \"Animation\");\n Save<Component::Lens>(entity, \"Lens\");\n Save<Component::Mesh>(entity, \"Mesh\");\n Save<Component::Material>(entity, \"Material\");\n Save<Component::DirectionalLight>(entity, \"DirectionalLight\");\n Save<Component::PointLight>(entity, \"PointLight\");\n Save<Component::SpotLight>(entity, \"SpotLight\");\n Save<Component::Physics>(entity, \"Physics\");\n Save<Component::Listener>(entity, \"Listener\");\n Save<Component::Script>(entity, \"Script\");\n Save<Component::SoundSource>(entity, \"SoundSource\");\n Save<Component::ParticleEmitter>(entity, \"ParticleEmitter\");\n \n \/\/ Save children.\n Json::Value childNodes;\n for (Entity* child : children)\n childNodes.append(child->Save());\n entity[\"children\"] = childNodes;\n }\n \n return entity;\n}\n\nvoid Entity::Load(const Json::Value& node) {\n scene = node[\"scene\"].asBool();\n \n if (scene) {\n sceneName = node[\"sceneName\"].asString();\n \n \/\/ Load scene.\n std::string filename = Hymn().GetPath() + FileSystem::DELIMITER + \"Scenes\" + FileSystem::DELIMITER + sceneName + \".json\";\n Json::Value root;\n std::ifstream file(filename);\n file >> root;\n file.close();\n Load(root);\n \n scene = true;\n } else {\n \/\/ Load components.\n Load<Component::Animation>(node, \"Animation\");\n Load<Component::Lens>(node, \"Lens\");\n Load<Component::Mesh>(node, \"Mesh\");\n Load<Component::Material>(node, \"Material\");\n Load<Component::DirectionalLight>(node, \"DirectionalLight\");\n Load<Component::PointLight>(node, \"PointLight\");\n Load<Component::SpotLight>(node, \"SpotLight\");\n Load<Component::Physics>(node, \"Physics\");\n Load<Component::Listener>(node, \"Listener\");\n Load<Component::Script>(node, \"Script\");\n Load<Component::SoundSource>(node, \"SoundSource\");\n Load<Component::ParticleEmitter>(node, \"ParticleEmitter\");\n \n \/\/ Load children.\n for (unsigned int i=0; i < node[\"children\"].size(); ++i) {\n Entity* entity = AddChild(\"\");\n entity->Load(node[\"children\"][i]);\n }\n }\n \n name = node.get(\"name\", \"\").asString();\n position = Json::LoadVec3(node[\"position\"]);\n scale = Json::LoadVec3(node[\"scale\"]);\n rotation = Json::LoadVec3(node[\"rotation\"]);\n uniqueIdentifier = node.get(\"uid\", 0).asUInt();\n \n}\n\nglm::mat4 Entity::GetModelMatrix() const {\n glm::mat4 matrix = glm::translate(glm::mat4(), position) * GetOrientation() * glm::scale(glm::mat4(), scale);\n \n if (parent != nullptr)\n matrix = parent->GetModelMatrix() * matrix;\n \n return matrix;\n}\n\nglm::mat4 Entity::GetOrientation() const {\n glm::mat4 orientation;\n orientation = glm::rotate(orientation, glm::radians(rotation.x), glm::vec3(0.f, 1.f, 0.f));\n orientation = glm::rotate(orientation, glm::radians(rotation.y), glm::vec3(1.f, 0.f, 0.f));\n return glm::rotate(orientation, glm::radians(rotation.z), glm::vec3(0.f, 0.f, 1.f));\n}\n\nglm::mat4 Entity::GetCameraOrientation() const {\n glm::mat4 orientation;\n orientation = glm::rotate(orientation, glm::radians(rotation.z), glm::vec3(0.f, 0.f, 1.f));\n orientation = glm::rotate(orientation, glm::radians(rotation.y), glm::vec3(1.f, 0.f, 0.f));\n return glm::rotate(orientation, glm::radians(rotation.x), glm::vec3(0.f, 1.f, 0.f));\n}\n\nglm::vec3 Entity::GetDirection() const {\n return glm::normalize(glm::vec3(GetOrientation() * glm::vec4(0.f, 0.f, -1.f, 0.f)));\n}\n\nglm::vec3 Entity::GetWorldPosition() const {\n if (parent != nullptr)\n return glm::vec3(parent->GetModelMatrix() * glm::vec4(position, 1.f));\n \n return position;\n}\n\nunsigned int Entity::GetUniqueIdentifier() const {\n return uniqueIdentifier;\n}\n\nvoid Entity::SetUniqueIdentifier(unsigned int UID) {\n uniqueIdentifier = UID;\n}\n\nComponent::SuperComponent* Entity::AddComponent(const std::type_info* componentType) {\n Component::SuperComponent* component;\n \n \/\/ Create a component in the correct manager.\n if (*componentType == typeid(Component::Animation*))\n component = Managers().renderManager->CreateAnimation();\n else if (*componentType == typeid(Component::DirectionalLight*))\n component = Managers().renderManager->CreateDirectionalLight();\n else if (*componentType == typeid(Component::Lens*))\n component = Managers().renderManager->CreateLens();\n else if (*componentType == typeid(Component::Listener*))\n component = Managers().soundManager->CreateListener();\n else if (*componentType == typeid(Component::Material*))\n component = Managers().renderManager->CreateMaterial();\n else if (*componentType == typeid(Component::Mesh*))\n component = Managers().renderManager->CreateMesh();\n else if (*componentType == typeid(Component::ParticleEmitter*))\n component = Managers().particleManager->CreateParticleEmitter();\n else if (*componentType == typeid(Component::Physics*))\n component = Managers().physicsManager->CreatePhysics();\n else if (*componentType == typeid(Component::PointLight*))\n component = Managers().renderManager->CreatePointLight();\n else if (*componentType == typeid(Component::Script*))\n component = Managers().scriptManager->CreateScript();\n else if (*componentType == typeid(Component::SoundSource*))\n component = Managers().soundManager->CreateSoundSource();\n else if (*componentType == typeid(Component::SpotLight*))\n component = Managers().renderManager->CreateSpotLight();\n else {\n Log() << componentType->name() << \" not assigned to a manager!\" << \"\\n\";\n return nullptr;\n }\n \n \/\/ Add component to our map.\n components[componentType] = component;\n \n \/\/ Set ourselves as the owner.\n component->entity = this;\n \n return component;\n}\n\nvoid Entity::LoadComponent(const std::type_info* componentType, const Json::Value& node) {\n Component::SuperComponent* component;\n \n \/\/ Create a component in the correct manager.\n if (*componentType == typeid(Component::Animation*))\n component = Managers().renderManager->CreateAnimation(node);\n else if (*componentType == typeid(Component::DirectionalLight*))\n component = Managers().renderManager->CreateDirectionalLight(node);\n else if (*componentType == typeid(Component::Lens*))\n component = Managers().renderManager->CreateLens(node);\n else if (*componentType == typeid(Component::Listener*))\n component = Managers().soundManager->CreateListener(node);\n else if (*componentType == typeid(Component::Material*))\n component = Managers().renderManager->CreateMaterial(node);\n else if (*componentType == typeid(Component::Mesh*))\n component = Managers().renderManager->CreateMesh(node);\n else if (*componentType == typeid(Component::ParticleEmitter*))\n component = Managers().particleManager->CreateParticleEmitter(node);\n else if (*componentType == typeid(Component::Physics*))\n component = Managers().physicsManager->CreatePhysics(node);\n else if (*componentType == typeid(Component::PointLight*))\n component = Managers().renderManager->CreatePointLight(node);\n else if (*componentType == typeid(Component::Script*))\n component = Managers().scriptManager->CreateScript(node);\n else if (*componentType == typeid(Component::SoundSource*))\n component = Managers().soundManager->CreateSoundSource(node);\n else if (*componentType == typeid(Component::SpotLight*))\n component = Managers().renderManager->CreateSpotLight(node);\n else {\n Log() << componentType->name() << \" not assigned to a manager!\" << \"\\n\";\n return;\n }\n \n \/\/ Add component to our map.\n components[componentType] = component;\n \n \/\/ Set ourselves as the owner.\n component->entity = this;\n}\n\nvoid Entity::KillHelper() {\n killed = true;\n \n for (auto& it : components)\n it.second->Kill();\n \n for (Entity* child : children) {\n child->KillHelper();\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/===- FunctionResolution.cpp - Resolve declarations to implementations ---===\/\/\n\/\/\n\/\/ Loop over the functions that are in the module and look for functions that\n\/\/ have the same name. More often than not, there will be things like:\n\/\/\n\/\/ declare void %foo(...)\n\/\/ void %foo(int, int) { ... }\n\/\/\n\/\/ because of the way things are declared in C. If this is the case, patch\n\/\/ things up.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/Transforms\/IPO.h\"\n#include \"llvm\/Module.h\"\n#include \"llvm\/SymbolTable.h\"\n#include \"llvm\/DerivedTypes.h\"\n#include \"llvm\/Pass.h\"\n#include \"llvm\/iOther.h\"\n#include \"llvm\/Constants.h\"\n#include \"llvm\/Assembly\/Writer.h\" \/\/ FIXME: remove when varargs implemented\n#include \"Support\/Statistic.h\"\n#include <algorithm>\n\nnamespace {\n Statistic<>NumResolved(\"funcresolve\", \"Number of varargs functions resolved\");\n Statistic<> NumGlobals(\"funcresolve\", \"Number of global variables resolved\");\n\n struct FunctionResolvingPass : public Pass {\n bool run(Module &M);\n };\n RegisterOpt<FunctionResolvingPass> X(\"funcresolve\", \"Resolve Functions\");\n}\n\nPass *createFunctionResolvingPass() {\n return new FunctionResolvingPass();\n}\n\n\/\/ ConvertCallTo - Convert a call to a varargs function with no arg types\n\/\/ specified to a concrete nonvarargs function.\n\/\/\nstatic void ConvertCallTo(CallInst *CI, Function *Dest) {\n const FunctionType::ParamTypes &ParamTys =\n Dest->getFunctionType()->getParamTypes();\n BasicBlock *BB = CI->getParent();\n\n \/\/ Keep an iterator to where we want to insert cast instructions if the\n \/\/ argument types don't agree.\n \/\/\n BasicBlock::iterator BBI = CI;\n unsigned NumArgsToCopy = CI->getNumOperands()-1;\n if (NumArgsToCopy != ParamTys.size() &&\n !(NumArgsToCopy > ParamTys.size() &&\n Dest->getFunctionType()->isVarArg())) {\n std::cerr << \"WARNING: Call arguments do not match expected number of\"\n << \" parameters.\\n\";\n std::cerr << \"WARNING: In function '\"\n << CI->getParent()->getParent()->getName() << \"': call: \" << *CI;\n std::cerr << \"Function resolved to: \";\n WriteAsOperand(std::cerr, Dest);\n std::cerr << \"\\n\";\n if (NumArgsToCopy > ParamTys.size())\n NumArgsToCopy = ParamTys.size();\n }\n\n std::vector<Value*> Params;\n\n \/\/ Convert all of the call arguments over... inserting cast instructions if\n \/\/ the types are not compatible.\n for (unsigned i = 1; i <= NumArgsToCopy; ++i) {\n Value *V = CI->getOperand(i);\n\n if (i-1 < ParamTys.size() && V->getType() != ParamTys[i-1]) {\n \/\/ Must insert a cast...\n V = new CastInst(V, ParamTys[i-1], \"argcast\", BBI);\n }\n\n Params.push_back(V);\n }\n\n \/\/ Replace the old call instruction with a new call instruction that calls\n \/\/ the real function.\n \/\/\n Instruction *NewCall = new CallInst(Dest, Params, \"\", BBI);\n\n \/\/ Remove the old call instruction from the program...\n BB->getInstList().remove(BBI);\n\n \/\/ Transfer the name over...\n if (NewCall->getType() != Type::VoidTy)\n NewCall->setName(CI->getName());\n\n \/\/ Replace uses of the old instruction with the appropriate values...\n \/\/\n if (NewCall->getType() == CI->getType()) {\n CI->replaceAllUsesWith(NewCall);\n NewCall->setName(CI->getName());\n\n } else if (NewCall->getType() == Type::VoidTy) {\n \/\/ Resolved function does not return a value but the prototype does. This\n \/\/ often occurs because undefined functions default to returning integers.\n \/\/ Just replace uses of the call (which are broken anyway) with dummy\n \/\/ values.\n CI->replaceAllUsesWith(Constant::getNullValue(CI->getType()));\n } else if (CI->getType() == Type::VoidTy) {\n \/\/ If we are gaining a new return value, we don't have to do anything\n \/\/ special here, because it will automatically be ignored.\n } else {\n \/\/ Insert a cast instruction to convert the return value of the function\n \/\/ into it's new type. Of course we only need to do this if the return\n \/\/ value of the function is actually USED.\n \/\/\n if (!CI->use_empty()) {\n \/\/ Insert the new cast instruction...\n CastInst *NewCast = new CastInst(NewCall, CI->getType(),\n NewCall->getName(), BBI);\n CI->replaceAllUsesWith(NewCast);\n }\n }\n\n \/\/ The old instruction is no longer needed, destroy it!\n delete CI;\n}\n\n\nstatic bool ResolveFunctions(Module &M, std::vector<GlobalValue*> &Globals,\n Function *Concrete) {\n bool Changed = false;\n for (unsigned i = 0; i != Globals.size(); ++i)\n if (Globals[i] != Concrete) {\n Function *Old = cast<Function>(Globals[i]);\n const FunctionType *OldMT = Old->getFunctionType();\n const FunctionType *ConcreteMT = Concrete->getFunctionType();\n \n assert(OldMT->getParamTypes().size() <=\n ConcreteMT->getParamTypes().size() &&\n \"Concrete type must have more specified parameters!\");\n \n \/\/ Check to make sure that if there are specified types, that they\n \/\/ match...\n \/\/\n for (unsigned i = 0; i < OldMT->getParamTypes().size(); ++i)\n if (OldMT->getParamTypes()[i] != ConcreteMT->getParamTypes()[i]) {\n std::cerr << \"funcresolve: Function [\" << Old->getName()\n << \"]: Parameter types conflict for: '\" << OldMT\n << \"' and '\" << ConcreteMT << \"'\\n\";\n return Changed;\n }\n \n \/\/ Attempt to convert all of the uses of the old function to the\n \/\/ concrete form of the function. If there is a use of the fn that\n \/\/ we don't understand here we punt to avoid making a bad\n \/\/ transformation.\n \/\/\n \/\/ At this point, we know that the return values are the same for\n \/\/ our two functions and that the Old function has no varargs fns\n \/\/ specified. In otherwords it's just <retty> (...)\n \/\/\n for (unsigned i = 0; i < Old->use_size(); ) {\n User *U = *(Old->use_begin()+i);\n if (CastInst *CI = dyn_cast<CastInst>(U)) {\n \/\/ Convert casts directly\n assert(CI->getOperand(0) == Old);\n CI->setOperand(0, Concrete);\n Changed = true;\n ++NumResolved;\n } else if (CallInst *CI = dyn_cast<CallInst>(U)) {\n \/\/ Can only fix up calls TO the argument, not args passed in.\n if (CI->getCalledValue() == Old) {\n ConvertCallTo(CI, Concrete);\n Changed = true;\n ++NumResolved;\n } else {\n std::cerr << \"Couldn't cleanup this function call, must be an\"\n << \" argument or something!\" << CI;\n ++i;\n }\n } else {\n std::cerr << \"Cannot convert use of function: \" << U << \"\\n\";\n ++i;\n }\n }\n }\n return Changed;\n}\n\n\nstatic bool ResolveGlobalVariables(Module &M,\n std::vector<GlobalValue*> &Globals,\n GlobalVariable *Concrete) {\n bool Changed = false;\n assert(isa<ArrayType>(Concrete->getType()->getElementType()) &&\n \"Concrete version should be an array type!\");\n\n \/\/ Get the type of the things that may be resolved to us...\n const Type *AETy =\n cast<ArrayType>(Concrete->getType()->getElementType())->getElementType();\n\n std::vector<Constant*> Args;\n Args.push_back(Constant::getNullValue(Type::LongTy));\n Args.push_back(Constant::getNullValue(Type::LongTy));\n ConstantExpr *Replacement =\n ConstantExpr::getGetElementPtr(ConstantPointerRef::get(Concrete), Args);\n \n for (unsigned i = 0; i != Globals.size(); ++i)\n if (Globals[i] != Concrete) {\n GlobalVariable *Old = cast<GlobalVariable>(Globals[i]);\n if (Old->getType()->getElementType() != AETy) {\n std::cerr << \"WARNING: Two global variables exist with the same name \"\n << \"that cannot be resolved!\\n\";\n return false;\n }\n\n \/\/ In this case, Old is a pointer to T, Concrete is a pointer to array of\n \/\/ T. Because of this, replace all uses of Old with a constantexpr\n \/\/ getelementptr that returns the address of the first element of the\n \/\/ array.\n \/\/\n Old->replaceAllUsesWith(Replacement);\n \/\/ Since there are no uses of Old anymore, remove it from the module.\n M.getGlobalList().erase(Old);\n\n ++NumGlobals;\n Changed = true;\n }\n return Changed;\n}\n\nstatic bool ProcessGlobalsWithSameName(Module &M,\n std::vector<GlobalValue*> &Globals) {\n assert(!Globals.empty() && \"Globals list shouldn't be empty here!\");\n\n bool isFunction = isa<Function>(Globals[0]); \/\/ Is this group all functions?\n bool Changed = false;\n GlobalValue *Concrete = 0; \/\/ The most concrete implementation to resolve to\n\n assert((isFunction ^ isa<GlobalVariable>(Globals[0])) &&\n \"Should either be function or gvar!\");\n\n for (unsigned i = 0; i != Globals.size(); ) {\n if (isa<Function>(Globals[i]) != isFunction) {\n std::cerr << \"WARNING: Found function and global variable with the \"\n << \"same name: '\" << Globals[i]->getName() << \"'.\\n\";\n return false; \/\/ Don't know how to handle this, bail out!\n }\n\n if (isFunction) {\n \/\/ For functions, we look to merge functions definitions of \"int (...)\"\n \/\/ to 'int (int)' or 'int ()' or whatever else is not completely generic.\n \/\/\n Function *F = cast<Function>(Globals[i]);\n if (!F->isExternal()) {\n if (Concrete && !Concrete->isExternal())\n return false; \/\/ Found two different functions types. Can't choose!\n \n Concrete = Globals[i];\n } else if (Concrete) {\n if (Concrete->isExternal()) \/\/ If we have multiple external symbols...x\n if (F->getFunctionType()->getNumParams() > \n cast<Function>(Concrete)->getFunctionType()->getNumParams())\n Concrete = F; \/\/ We are more concrete than \"Concrete\"!\n\n } else {\n Concrete = F;\n }\n ++i;\n } else {\n \/\/ For global variables, we have to merge C definitions int A[][4] with\n \/\/ int[6][4]\n GlobalVariable *GV = cast<GlobalVariable>(Globals[i]);\n if (Concrete == 0) {\n if (isa<ArrayType>(GV->getType()->getElementType()))\n Concrete = GV;\n } else { \/\/ Must have different types... one is an array of the other?\n const ArrayType *AT =\n dyn_cast<ArrayType>(GV->getType()->getElementType());\n\n \/\/ If GV is an array of Concrete, then GV is the array.\n if (AT && AT->getElementType() == Concrete->getType()->getElementType())\n Concrete = GV;\n else {\n \/\/ Concrete must be an array type, check to see if the element type of\n \/\/ concrete is already GV.\n AT = cast<ArrayType>(Concrete->getType()->getElementType());\n if (AT->getElementType() != GV->getType()->getElementType())\n Concrete = 0; \/\/ Don't know how to handle it!\n }\n }\n \n ++i;\n }\n }\n\n if (Globals.size() > 1) { \/\/ Found a multiply defined global...\n \/\/ We should find exactly one concrete function definition, which is\n \/\/ probably the implementation. Change all of the function definitions and\n \/\/ uses to use it instead.\n \/\/\n if (!Concrete) {\n std::cerr << \"WARNING: Found function types that are not compatible:\\n\";\n for (unsigned i = 0; i < Globals.size(); ++i) {\n std::cerr << \"\\t\" << Globals[i]->getType()->getDescription() << \" %\"\n << Globals[i]->getName() << \"\\n\";\n }\n std::cerr << \" No linkage of globals named '\" << Globals[0]->getName()\n << \"' performed!\\n\";\n return Changed;\n }\n\n if (isFunction)\n return Changed | ResolveFunctions(M, Globals, cast<Function>(Concrete));\n else\n return Changed | ResolveGlobalVariables(M, Globals,\n cast<GlobalVariable>(Concrete));\n }\n return Changed;\n}\n\nbool FunctionResolvingPass::run(Module &M) {\n SymbolTable &ST = M.getSymbolTable();\n\n std::map<std::string, std::vector<GlobalValue*> > Globals;\n\n \/\/ Loop over the entries in the symbol table. If an entry is a func pointer,\n \/\/ then add it to the Functions map. We do a two pass algorithm here to avoid\n \/\/ problems with iterators getting invalidated if we did a one pass scheme.\n \/\/\n for (SymbolTable::iterator I = ST.begin(), E = ST.end(); I != E; ++I)\n if (const PointerType *PT = dyn_cast<PointerType>(I->first)) {\n SymbolTable::VarMap &Plane = I->second;\n for (SymbolTable::type_iterator PI = Plane.begin(), PE = Plane.end();\n PI != PE; ++PI) {\n GlobalValue *GV = cast<GlobalValue>(PI->second);\n assert(PI->first == GV->getName() &&\n \"Global name and symbol table do not agree!\");\n if (GV->hasExternalLinkage()) \/\/ Only resolve decls to external fns\n Globals[PI->first].push_back(GV);\n }\n }\n\n bool Changed = false;\n\n \/\/ Now we have a list of all functions with a particular name. If there is\n \/\/ more than one entry in a list, merge the functions together.\n \/\/\n for (std::map<std::string, std::vector<GlobalValue*> >::iterator\n I = Globals.begin(), E = Globals.end(); I != E; ++I)\n Changed |= ProcessGlobalsWithSameName(M, I->second);\n\n \/\/ Now loop over all of the globals, checking to see if any are trivially\n \/\/ dead. If so, remove them now.\n\n for (Module::iterator I = M.begin(), E = M.end(); I != E; )\n if (I->isExternal() && I->use_empty()) {\n Function *F = I;\n ++I;\n M.getFunctionList().erase(F);\n ++NumResolved;\n Changed = true;\n } else {\n ++I;\n }\n\n for (Module::giterator I = M.gbegin(), E = M.gend(); I != E; )\n if (I->isExternal() && I->use_empty()) {\n GlobalVariable *GV = I;\n ++I;\n M.getGlobalList().erase(GV);\n ++NumGlobals;\n Changed = true;\n } else {\n ++I;\n }\n\n return Changed;\n}\n<commit_msg>Replace assertion with a handler.<commit_after>\/\/===- FunctionResolution.cpp - Resolve declarations to implementations ---===\/\/\n\/\/\n\/\/ Loop over the functions that are in the module and look for functions that\n\/\/ have the same name. More often than not, there will be things like:\n\/\/\n\/\/ declare void %foo(...)\n\/\/ void %foo(int, int) { ... }\n\/\/\n\/\/ because of the way things are declared in C. If this is the case, patch\n\/\/ things up.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/Transforms\/IPO.h\"\n#include \"llvm\/Module.h\"\n#include \"llvm\/SymbolTable.h\"\n#include \"llvm\/DerivedTypes.h\"\n#include \"llvm\/Pass.h\"\n#include \"llvm\/iOther.h\"\n#include \"llvm\/Constants.h\"\n#include \"llvm\/Assembly\/Writer.h\" \/\/ FIXME: remove when varargs implemented\n#include \"Support\/Statistic.h\"\n#include <algorithm>\n\nnamespace {\n Statistic<>NumResolved(\"funcresolve\", \"Number of varargs functions resolved\");\n Statistic<> NumGlobals(\"funcresolve\", \"Number of global variables resolved\");\n\n struct FunctionResolvingPass : public Pass {\n bool run(Module &M);\n };\n RegisterOpt<FunctionResolvingPass> X(\"funcresolve\", \"Resolve Functions\");\n}\n\nPass *createFunctionResolvingPass() {\n return new FunctionResolvingPass();\n}\n\n\/\/ ConvertCallTo - Convert a call to a varargs function with no arg types\n\/\/ specified to a concrete nonvarargs function.\n\/\/\nstatic void ConvertCallTo(CallInst *CI, Function *Dest) {\n const FunctionType::ParamTypes &ParamTys =\n Dest->getFunctionType()->getParamTypes();\n BasicBlock *BB = CI->getParent();\n\n \/\/ Keep an iterator to where we want to insert cast instructions if the\n \/\/ argument types don't agree.\n \/\/\n unsigned NumArgsToCopy = CI->getNumOperands()-1;\n if (NumArgsToCopy != ParamTys.size() &&\n !(NumArgsToCopy > ParamTys.size() &&\n Dest->getFunctionType()->isVarArg())) {\n std::cerr << \"WARNING: Call arguments do not match expected number of\"\n << \" parameters.\\n\";\n std::cerr << \"WARNING: In function '\"\n << CI->getParent()->getParent()->getName() << \"': call: \" << *CI;\n std::cerr << \"Function resolved to: \";\n WriteAsOperand(std::cerr, Dest);\n std::cerr << \"\\n\";\n if (NumArgsToCopy > ParamTys.size())\n NumArgsToCopy = ParamTys.size();\n }\n\n std::vector<Value*> Params;\n\n \/\/ Convert all of the call arguments over... inserting cast instructions if\n \/\/ the types are not compatible.\n for (unsigned i = 1; i <= NumArgsToCopy; ++i) {\n Value *V = CI->getOperand(i);\n\n if (i-1 < ParamTys.size() && V->getType() != ParamTys[i-1]) {\n \/\/ Must insert a cast...\n V = new CastInst(V, ParamTys[i-1], \"argcast\", CI);\n }\n\n Params.push_back(V);\n }\n\n \/\/ Replace the old call instruction with a new call instruction that calls\n \/\/ the real function.\n \/\/\n Instruction *NewCall = new CallInst(Dest, Params, \"\", CI);\n std::string Name = CI->getName(); CI->setName(\"\");\n\n \/\/ Transfer the name over...\n if (NewCall->getType() != Type::VoidTy)\n NewCall->setName(Name);\n\n \/\/ Replace uses of the old instruction with the appropriate values...\n \/\/\n if (NewCall->getType() == CI->getType()) {\n CI->replaceAllUsesWith(NewCall);\n NewCall->setName(Name);\n\n } else if (NewCall->getType() == Type::VoidTy) {\n \/\/ Resolved function does not return a value but the prototype does. This\n \/\/ often occurs because undefined functions default to returning integers.\n \/\/ Just replace uses of the call (which are broken anyway) with dummy\n \/\/ values.\n CI->replaceAllUsesWith(Constant::getNullValue(CI->getType()));\n } else if (CI->getType() == Type::VoidTy) {\n \/\/ If we are gaining a new return value, we don't have to do anything\n \/\/ special here, because it will automatically be ignored.\n } else {\n \/\/ Insert a cast instruction to convert the return value of the function\n \/\/ into it's new type. Of course we only need to do this if the return\n \/\/ value of the function is actually USED.\n \/\/\n if (!CI->use_empty()) {\n \/\/ Insert the new cast instruction...\n CastInst *NewCast = new CastInst(NewCall, CI->getType(), Name, CI);\n CI->replaceAllUsesWith(NewCast);\n }\n }\n\n \/\/ The old instruction is no longer needed, destroy it!\n BB->getInstList().erase(CI);\n}\n\n\nstatic bool ResolveFunctions(Module &M, std::vector<GlobalValue*> &Globals,\n Function *Concrete) {\n bool Changed = false;\n for (unsigned i = 0; i != Globals.size(); ++i)\n if (Globals[i] != Concrete) {\n Function *Old = cast<Function>(Globals[i]);\n const FunctionType *OldMT = Old->getFunctionType();\n const FunctionType *ConcreteMT = Concrete->getFunctionType();\n \n if (OldMT->getParamTypes().size() <= ConcreteMT->getParamTypes().size())\n if (!Old->use_empty()) {\n std::cerr << \"WARNING: Linking function '\" << Old->getName()\n << \"' is causing arguments to be dropped.\\n\";\n std::cerr << \"WARNING: Prototype: \";\n WriteAsOperand(std::cerr, Old);\n std::cerr << \" resolved to \";\n WriteAsOperand(std::cerr, Concrete);\n std::cerr << \"\\n\";\n }\n \n \/\/ Check to make sure that if there are specified types, that they\n \/\/ match...\n \/\/\n unsigned NumArguments = std::min(OldMT->getParamTypes().size(),\n ConcreteMT->getParamTypes().size());\n\n for (unsigned i = 0; i < NumArguments; ++i)\n if (OldMT->getParamTypes()[i] != ConcreteMT->getParamTypes()[i]) {\n std::cerr << \"funcresolve: Function [\" << Old->getName()\n << \"]: Parameter types conflict for: '\" << OldMT\n << \"' and '\" << ConcreteMT << \"'\\n\";\n return Changed;\n }\n \n \/\/ Attempt to convert all of the uses of the old function to the\n \/\/ concrete form of the function. If there is a use of the fn that\n \/\/ we don't understand here we punt to avoid making a bad\n \/\/ transformation.\n \/\/\n \/\/ At this point, we know that the return values are the same for\n \/\/ our two functions and that the Old function has no varargs fns\n \/\/ specified. In otherwords it's just <retty> (...)\n \/\/\n for (unsigned i = 0; i < Old->use_size(); ) {\n User *U = *(Old->use_begin()+i);\n if (CastInst *CI = dyn_cast<CastInst>(U)) {\n \/\/ Convert casts directly\n assert(CI->getOperand(0) == Old);\n CI->setOperand(0, Concrete);\n Changed = true;\n ++NumResolved;\n } else if (CallInst *CI = dyn_cast<CallInst>(U)) {\n \/\/ Can only fix up calls TO the argument, not args passed in.\n if (CI->getCalledValue() == Old) {\n ConvertCallTo(CI, Concrete);\n Changed = true;\n ++NumResolved;\n } else {\n std::cerr << \"Couldn't cleanup this function call, must be an\"\n << \" argument or something!\" << CI;\n ++i;\n }\n } else {\n std::cerr << \"Cannot convert use of function: \" << U << \"\\n\";\n ++i;\n }\n }\n }\n return Changed;\n}\n\n\nstatic bool ResolveGlobalVariables(Module &M,\n std::vector<GlobalValue*> &Globals,\n GlobalVariable *Concrete) {\n bool Changed = false;\n assert(isa<ArrayType>(Concrete->getType()->getElementType()) &&\n \"Concrete version should be an array type!\");\n\n \/\/ Get the type of the things that may be resolved to us...\n const Type *AETy =\n cast<ArrayType>(Concrete->getType()->getElementType())->getElementType();\n\n std::vector<Constant*> Args;\n Args.push_back(Constant::getNullValue(Type::LongTy));\n Args.push_back(Constant::getNullValue(Type::LongTy));\n ConstantExpr *Replacement =\n ConstantExpr::getGetElementPtr(ConstantPointerRef::get(Concrete), Args);\n \n for (unsigned i = 0; i != Globals.size(); ++i)\n if (Globals[i] != Concrete) {\n GlobalVariable *Old = cast<GlobalVariable>(Globals[i]);\n if (Old->getType()->getElementType() != AETy) {\n std::cerr << \"WARNING: Two global variables exist with the same name \"\n << \"that cannot be resolved!\\n\";\n return false;\n }\n\n \/\/ In this case, Old is a pointer to T, Concrete is a pointer to array of\n \/\/ T. Because of this, replace all uses of Old with a constantexpr\n \/\/ getelementptr that returns the address of the first element of the\n \/\/ array.\n \/\/\n Old->replaceAllUsesWith(Replacement);\n \/\/ Since there are no uses of Old anymore, remove it from the module.\n M.getGlobalList().erase(Old);\n\n ++NumGlobals;\n Changed = true;\n }\n return Changed;\n}\n\nstatic bool ProcessGlobalsWithSameName(Module &M,\n std::vector<GlobalValue*> &Globals) {\n assert(!Globals.empty() && \"Globals list shouldn't be empty here!\");\n\n bool isFunction = isa<Function>(Globals[0]); \/\/ Is this group all functions?\n bool Changed = false;\n GlobalValue *Concrete = 0; \/\/ The most concrete implementation to resolve to\n\n assert((isFunction ^ isa<GlobalVariable>(Globals[0])) &&\n \"Should either be function or gvar!\");\n\n for (unsigned i = 0; i != Globals.size(); ) {\n if (isa<Function>(Globals[i]) != isFunction) {\n std::cerr << \"WARNING: Found function and global variable with the \"\n << \"same name: '\" << Globals[i]->getName() << \"'.\\n\";\n return false; \/\/ Don't know how to handle this, bail out!\n }\n\n if (isFunction) {\n \/\/ For functions, we look to merge functions definitions of \"int (...)\"\n \/\/ to 'int (int)' or 'int ()' or whatever else is not completely generic.\n \/\/\n Function *F = cast<Function>(Globals[i]);\n if (!F->isExternal()) {\n if (Concrete && !Concrete->isExternal())\n return false; \/\/ Found two different functions types. Can't choose!\n \n Concrete = Globals[i];\n } else if (Concrete) {\n if (Concrete->isExternal()) \/\/ If we have multiple external symbols...x\n if (F->getFunctionType()->getNumParams() > \n cast<Function>(Concrete)->getFunctionType()->getNumParams())\n Concrete = F; \/\/ We are more concrete than \"Concrete\"!\n\n } else {\n Concrete = F;\n }\n ++i;\n } else {\n \/\/ For global variables, we have to merge C definitions int A[][4] with\n \/\/ int[6][4]\n GlobalVariable *GV = cast<GlobalVariable>(Globals[i]);\n if (Concrete == 0) {\n if (isa<ArrayType>(GV->getType()->getElementType()))\n Concrete = GV;\n } else { \/\/ Must have different types... one is an array of the other?\n const ArrayType *AT =\n dyn_cast<ArrayType>(GV->getType()->getElementType());\n\n \/\/ If GV is an array of Concrete, then GV is the array.\n if (AT && AT->getElementType() == Concrete->getType()->getElementType())\n Concrete = GV;\n else {\n \/\/ Concrete must be an array type, check to see if the element type of\n \/\/ concrete is already GV.\n AT = cast<ArrayType>(Concrete->getType()->getElementType());\n if (AT->getElementType() != GV->getType()->getElementType())\n Concrete = 0; \/\/ Don't know how to handle it!\n }\n }\n \n ++i;\n }\n }\n\n if (Globals.size() > 1) { \/\/ Found a multiply defined global...\n \/\/ We should find exactly one concrete function definition, which is\n \/\/ probably the implementation. Change all of the function definitions and\n \/\/ uses to use it instead.\n \/\/\n if (!Concrete) {\n std::cerr << \"WARNING: Found function types that are not compatible:\\n\";\n for (unsigned i = 0; i < Globals.size(); ++i) {\n std::cerr << \"\\t\" << Globals[i]->getType()->getDescription() << \" %\"\n << Globals[i]->getName() << \"\\n\";\n }\n std::cerr << \" No linkage of globals named '\" << Globals[0]->getName()\n << \"' performed!\\n\";\n return Changed;\n }\n\n if (isFunction)\n return Changed | ResolveFunctions(M, Globals, cast<Function>(Concrete));\n else\n return Changed | ResolveGlobalVariables(M, Globals,\n cast<GlobalVariable>(Concrete));\n }\n return Changed;\n}\n\nbool FunctionResolvingPass::run(Module &M) {\n SymbolTable &ST = M.getSymbolTable();\n\n std::map<std::string, std::vector<GlobalValue*> > Globals;\n\n \/\/ Loop over the entries in the symbol table. If an entry is a func pointer,\n \/\/ then add it to the Functions map. We do a two pass algorithm here to avoid\n \/\/ problems with iterators getting invalidated if we did a one pass scheme.\n \/\/\n for (SymbolTable::iterator I = ST.begin(), E = ST.end(); I != E; ++I)\n if (const PointerType *PT = dyn_cast<PointerType>(I->first)) {\n SymbolTable::VarMap &Plane = I->second;\n for (SymbolTable::type_iterator PI = Plane.begin(), PE = Plane.end();\n PI != PE; ++PI) {\n GlobalValue *GV = cast<GlobalValue>(PI->second);\n assert(PI->first == GV->getName() &&\n \"Global name and symbol table do not agree!\");\n if (GV->hasExternalLinkage()) \/\/ Only resolve decls to external fns\n Globals[PI->first].push_back(GV);\n }\n }\n\n bool Changed = false;\n\n \/\/ Now we have a list of all functions with a particular name. If there is\n \/\/ more than one entry in a list, merge the functions together.\n \/\/\n for (std::map<std::string, std::vector<GlobalValue*> >::iterator\n I = Globals.begin(), E = Globals.end(); I != E; ++I)\n Changed |= ProcessGlobalsWithSameName(M, I->second);\n\n \/\/ Now loop over all of the globals, checking to see if any are trivially\n \/\/ dead. If so, remove them now.\n\n for (Module::iterator I = M.begin(), E = M.end(); I != E; )\n if (I->isExternal() && I->use_empty()) {\n Function *F = I;\n ++I;\n M.getFunctionList().erase(F);\n ++NumResolved;\n Changed = true;\n } else {\n ++I;\n }\n\n for (Module::giterator I = M.gbegin(), E = M.gend(); I != E; )\n if (I->isExternal() && I->use_empty()) {\n GlobalVariable *GV = I;\n ++I;\n M.getGlobalList().erase(GV);\n ++NumGlobals;\n Changed = true;\n } else {\n ++I;\n }\n\n return Changed;\n}\n<|endoftext|>"} {"text":"<commit_before>#include <cmath>\n#include <istream>\n#include <ostream>\n#include <sstream>\n#include <time.h>\n\n#include \"PosixTimespec.hpp\"\n\nconst unsigned int PosixTimespec::nanoseconds_per_second = 1000000000;\n\n\/\/==============================================================================\n\/\/ Initializes to 0s 0ns\n\/\/==============================================================================\nPosixTimespec::PosixTimespec()\n{\n tp.tv_sec = 0;\n tp.tv_nsec = 0;\n}\n\n\/\/==============================================================================\n\/\/ Saves the provided timespec internally\n\/\/==============================================================================\nPosixTimespec::PosixTimespec(const timespec& tp) :\n tp(tp)\n{\n}\n\n\/\/==============================================================================\n\/\/ Converts to timespec before saving\n\/\/==============================================================================\nPosixTimespec::PosixTimespec(double tp_sec)\n{\n setDouble(tp_sec);\n}\n\n\/\/==============================================================================\n\/\/ Does nothing\n\/\/==============================================================================\nPosixTimespec::~PosixTimespec()\n{\n}\n\n\/\/==============================================================================\n\/\/ Returns double-precision floating point representation of timespec\n\/\/==============================================================================\ndouble PosixTimespec::getDouble() const\n{\n return static_cast<double>(this->tp.tv_sec) +\n (static_cast<double>(this->tp.tv_nsec) \/\n static_cast<double>(nanoseconds_per_second));\n}\n\n\/\/==============================================================================\n\/\/ Sets timespec based on provided double-precision floating point number\n\/\/==============================================================================\nbool PosixTimespec::setDouble(double tp_dbl)\n{\n \/\/ This class can't represent values less than zero\n if (tp_dbl < 0.0)\n {\n return false;\n }\n\n double fractional_part = 0.0;\n this->tp.tv_sec = std::modf(tp_dbl, &fractional_part);\n this->tp.tv_nsec = fractional_part *\n static_cast<double>(nanoseconds_per_second);\n\n return true;\n}\n\n\/\/==============================================================================\n\/\/ Does what you would expect\n\/\/==============================================================================\nPosixTimespec& PosixTimespec::operator=(const timespec& tp)\n{\n this->tp.tv_sec = tp.tv_sec;\n this->tp.tv_nsec = tp.tv_nsec;\n\n return *this;\n}\n\n\/\/==============================================================================\n\/\/ Performs integer addition so no data loss occurs; tv_nsec overflows and adds\n\/\/ to tv_sec as one would expect\n\/\/==============================================================================\nPosixTimespec& PosixTimespec::operator+=(const timespec& tp)\n{\n this->tp.tv_sec += tp.tv_sec;\n this->tp.tv_nsec += tp.tv_nsec;\n\n if (this->tp.tv_nsec >= nanoseconds_per_second)\n {\n this->tp.tv_nsec -= nanoseconds_per_second;\n this->tp.tv_sec += 1;\n }\n\n return *this;\n}\n\n\/\/==============================================================================\n\/\/ Does what you would expect\n\/\/==============================================================================\nPosixTimespec& PosixTimespec::operator+=(const PosixTimespec& tp)\n{\n timespec tp_temp;\n tp.getTimespec(tp_temp);\n\n return operator+=(tp_temp);\n}\n\n\/\/==============================================================================\n\/\/ Does what you would expect\n\/\/==============================================================================\nPosixTimespec& PosixTimespec::operator-=(const timespec& tp)\n{\n}\n\n\/\/==============================================================================\n\/\/ Does what you would expect\n\/\/==============================================================================\nPosixTimespec& PosixTimespec::operator-=(const PosixTimespec& tp)\n{\n}\n\n\/\/==============================================================================\n\/\/ Does what you would expect\n\/\/==============================================================================\nPosixTimespec operator+(PosixTimespec lhs, const PosixTimespec& rhs)\n{\n lhs += rhs;\n return lhs;\n}\n\n\/\/==============================================================================\n\/\/ Does what you would expect\n\/\/==============================================================================\nPosixTimespec operator+(PosixTimespec lhs, const timespec& rhs)\n{\n lhs += rhs;\n return lhs;\n}\n\n\/\/==============================================================================\n\/\/ Does what you would expect\n\/\/==============================================================================\nPosixTimespec operator+(timespec lhs, const PosixTimespec& rhs)\n{\n \/\/ Addition is symmetric\n return operator+(rhs, lhs);\n}\n\n\/\/==============================================================================\n\/\/ Does what you would expect\n\/\/==============================================================================\nPosixTimespec operator-(PosixTimespec lhs, const PosixTimespec& rhs)\n{\n lhs -= rhs;\n return lhs;\n}\n\n\/\/==============================================================================\n\/\/ Does what you would expect\n\/\/==============================================================================\nPosixTimespec operator-(PosixTimespec lhs, const timespec& rhs)\n{\n lhs -= rhs;\n return lhs;\n}\n\n\/\/==============================================================================\n\/\/ Does what you would expect\n\/\/==============================================================================\nPosixTimespec operator-(timespec lhs, const PosixTimespec& rhs)\n{\n lhs -= rhs;\n return lhs;\n}\n\n\/\/==============================================================================\n\/\/ Does what you would expect\n\/\/==============================================================================\nbool operator==(const PosixTimespec& lhs, const PosixTimespec& rhs)\n{\n timespec lhs_tp;\n timespec rhs_tp;\n\n lhs.getTimespec(lhs_tp);\n rhs.getTimespec(rhs_tp);\n\n return lhs_tp.tv_sec == rhs_tp.tv_sec && lhs_tp.tv_nsec == rhs_tp.tv_nsec;\n}\n\n\/\/==============================================================================\n\/\/ Does what you would expect\n\/\/==============================================================================\nbool operator==(const PosixTimespec& lhs, const timespec& rhs)\n{\n return lhs == PosixTimespec(rhs);\n}\n\n\/\/==============================================================================\n\/\/ Does what you would expect\n\/\/==============================================================================\nbool operator==(const timespec& lhs, const PosixTimespec& rhs)\n{\n return PosixTimespec(lhs) == rhs;\n}\n\n\/\/==============================================================================\n\/\/ Does what you would expect\n\/\/==============================================================================\nbool operator!=(const PosixTimespec& lhs, const PosixTimespec& rhs)\n{\n return !(lhs == rhs);\n}\n\n\/\/==============================================================================\n\/\/ Does what you would expect\n\/\/==============================================================================\nbool operator!=(const PosixTimespec& lhs, const timespec& rhs)\n{\n return !(lhs == rhs);\n}\n\n\/\/==============================================================================\n\/\/ Does what you would expect\n\/\/==============================================================================\nbool operator!=(const timespec& lhs, const PosixTimespec& rhs)\n{\n return !(lhs == rhs);\n}\n\n\n\/\/==============================================================================\n\/\/ Writes a string representation\n\/\/==============================================================================\nstd::ostream& operator<<(std::ostream& os, PosixTimespec& posix_timespec)\n{\n return os << posix_timespec.getDouble();\n}\n\n\/\/==============================================================================\n\/\/ Reads a string representation\n\/\/==============================================================================\nstd::istream& operator>>(std::istream& is, PosixTimespec& posix_timespec)\n{\n \/\/ Get the number as a string\n std::string posix_timespec_str;\n is >> posix_timespec_str;\n\n \/\/ Convert to double and internalize\n std::istringstream to_double(posix_timespec_str);\n double posix_timespec_dbl = 0.0;\n to_double >> posix_timespec_dbl;\n\n posix_timespec.setDouble(posix_timespec_dbl);\n\n return is;\n}\n<commit_msg>Subtraction implemented, not tested<commit_after>#include <cmath>\n#include <istream>\n#include <ostream>\n#include <sstream>\n#include <time.h>\n\n#include \"PosixTimespec.hpp\"\n\nconst unsigned int PosixTimespec::nanoseconds_per_second = 1000000000;\n\n\/\/==============================================================================\n\/\/ Initializes to 0s 0ns\n\/\/==============================================================================\nPosixTimespec::PosixTimespec()\n{\n tp.tv_sec = 0;\n tp.tv_nsec = 0;\n}\n\n\/\/==============================================================================\n\/\/ Saves the provided timespec internally\n\/\/==============================================================================\nPosixTimespec::PosixTimespec(const timespec& tp) :\n tp(tp)\n{\n}\n\n\/\/==============================================================================\n\/\/ Converts to timespec before saving\n\/\/==============================================================================\nPosixTimespec::PosixTimespec(double tp_sec)\n{\n setDouble(tp_sec);\n}\n\n\/\/==============================================================================\n\/\/ Does nothing\n\/\/==============================================================================\nPosixTimespec::~PosixTimespec()\n{\n}\n\n\/\/==============================================================================\n\/\/ Returns double-precision floating point representation of timespec\n\/\/==============================================================================\ndouble PosixTimespec::getDouble() const\n{\n return static_cast<double>(this->tp.tv_sec) +\n (static_cast<double>(this->tp.tv_nsec) \/\n static_cast<double>(nanoseconds_per_second));\n}\n\n\/\/==============================================================================\n\/\/ Sets timespec based on provided double-precision floating point number\n\/\/==============================================================================\nbool PosixTimespec::setDouble(double tp_dbl)\n{\n \/\/ This class can't represent values less than zero\n if (tp_dbl < 0.0)\n {\n return false;\n }\n\n double fractional_part = 0.0;\n this->tp.tv_sec = std::modf(tp_dbl, &fractional_part);\n this->tp.tv_nsec = fractional_part *\n static_cast<double>(nanoseconds_per_second);\n\n return true;\n}\n\n\/\/==============================================================================\n\/\/ Does what you would expect\n\/\/==============================================================================\nPosixTimespec& PosixTimespec::operator=(const timespec& tp)\n{\n this->tp.tv_sec = tp.tv_sec;\n this->tp.tv_nsec = tp.tv_nsec;\n\n return *this;\n}\n\n\/\/==============================================================================\n\/\/ Performs integer addition so no data loss occurs; tv_nsec overflows and adds\n\/\/ to tv_sec as one would expect\n\/\/==============================================================================\nPosixTimespec& PosixTimespec::operator+=(const timespec& tp)\n{\n this->tp.tv_sec += tp.tv_sec;\n this->tp.tv_nsec += tp.tv_nsec;\n\n if (this->tp.tv_nsec >= nanoseconds_per_second)\n {\n this->tp.tv_nsec -= nanoseconds_per_second;\n this->tp.tv_sec += 1;\n }\n\n return *this;\n}\n\n\/\/==============================================================================\n\/\/ Does what you would expect\n\/\/==============================================================================\nPosixTimespec& PosixTimespec::operator+=(const PosixTimespec& tp)\n{\n timespec tp_temp;\n tp.getTimespec(tp_temp);\n\n return operator+=(tp_temp);\n}\n\n\/\/==============================================================================\n\/\/ Does what you would expect\n\/\/==============================================================================\nPosixTimespec& PosixTimespec::operator-=(const timespec& tp)\n{\n this->tp.tv_sec -= tp.tv_sec;\n\n if (tp.tv_nsec > this->tp.tv_nsec)\n {\n this->tp.tv_sec -= 1;\n this->tp.tv_nsec = nanoseconds_per_second -\n (tp.tv_nsec - this->tp.tv_nsec);\n }\n\n return *this;\n}\n\n\/\/==============================================================================\n\/\/ Does what you would expect\n\/\/==============================================================================\nPosixTimespec& PosixTimespec::operator-=(const PosixTimespec& tp)\n{\n timespec tp_temp;\n tp.getTimespec(tp_temp);\n\n return operator-=(tp_temp);\n}\n\n\/\/==============================================================================\n\/\/ Does what you would expect\n\/\/==============================================================================\nPosixTimespec operator+(PosixTimespec lhs, const PosixTimespec& rhs)\n{\n lhs += rhs;\n return lhs;\n}\n\n\/\/==============================================================================\n\/\/ Does what you would expect\n\/\/==============================================================================\nPosixTimespec operator+(PosixTimespec lhs, const timespec& rhs)\n{\n lhs += rhs;\n return lhs;\n}\n\n\/\/==============================================================================\n\/\/ Does what you would expect\n\/\/==============================================================================\nPosixTimespec operator+(timespec lhs, const PosixTimespec& rhs)\n{\n \/\/ Addition is symmetric\n return operator+(rhs, lhs);\n}\n\n\/\/==============================================================================\n\/\/ Does what you would expect\n\/\/==============================================================================\nPosixTimespec operator-(PosixTimespec lhs, const PosixTimespec& rhs)\n{\n lhs -= rhs;\n return lhs;\n}\n\n\/\/==============================================================================\n\/\/ Does what you would expect\n\/\/==============================================================================\nPosixTimespec operator-(PosixTimespec lhs, const timespec& rhs)\n{\n lhs -= rhs;\n return lhs;\n}\n\n\/\/==============================================================================\n\/\/ Does what you would expect\n\/\/==============================================================================\nPosixTimespec operator-(timespec lhs, const PosixTimespec& rhs)\n{\n PosixTimespec lhs_ts(lhs);\n return operator-(lhs_ts, rhs);\n}\n\n\/\/==============================================================================\n\/\/ Does what you would expect\n\/\/==============================================================================\nbool operator==(const PosixTimespec& lhs, const PosixTimespec& rhs)\n{\n timespec lhs_tp;\n timespec rhs_tp;\n\n lhs.getTimespec(lhs_tp);\n rhs.getTimespec(rhs_tp);\n\n return lhs_tp.tv_sec == rhs_tp.tv_sec && lhs_tp.tv_nsec == rhs_tp.tv_nsec;\n}\n\n\/\/==============================================================================\n\/\/ Does what you would expect\n\/\/==============================================================================\nbool operator==(const PosixTimespec& lhs, const timespec& rhs)\n{\n return lhs == PosixTimespec(rhs);\n}\n\n\/\/==============================================================================\n\/\/ Does what you would expect\n\/\/==============================================================================\nbool operator==(const timespec& lhs, const PosixTimespec& rhs)\n{\n return PosixTimespec(lhs) == rhs;\n}\n\n\/\/==============================================================================\n\/\/ Does what you would expect\n\/\/==============================================================================\nbool operator!=(const PosixTimespec& lhs, const PosixTimespec& rhs)\n{\n return !(lhs == rhs);\n}\n\n\/\/==============================================================================\n\/\/ Does what you would expect\n\/\/==============================================================================\nbool operator!=(const PosixTimespec& lhs, const timespec& rhs)\n{\n return !(lhs == rhs);\n}\n\n\/\/==============================================================================\n\/\/ Does what you would expect\n\/\/==============================================================================\nbool operator!=(const timespec& lhs, const PosixTimespec& rhs)\n{\n return !(lhs == rhs);\n}\n\n\n\/\/==============================================================================\n\/\/ Writes a string representation\n\/\/==============================================================================\nstd::ostream& operator<<(std::ostream& os, PosixTimespec& posix_timespec)\n{\n return os << posix_timespec.getDouble();\n}\n\n\/\/==============================================================================\n\/\/ Reads a string representation\n\/\/==============================================================================\nstd::istream& operator>>(std::istream& is, PosixTimespec& posix_timespec)\n{\n \/\/ Get the number as a string\n std::string posix_timespec_str;\n is >> posix_timespec_str;\n\n \/\/ Convert to double and internalize\n std::istringstream to_double(posix_timespec_str);\n double posix_timespec_dbl = 0.0;\n to_double >> posix_timespec_dbl;\n\n posix_timespec.setDouble(posix_timespec_dbl);\n\n return is;\n}\n<|endoftext|>"} {"text":"<commit_before>\/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- *\/\n\/*\n * This file is part of the LibreOffice project.\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\n * This file incorporates work covered by the following license notice:\n *\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed\n * with this work for additional information regarding copyright\n * ownership. The ASF licenses this file to you under the Apache\n * License, Version 2.0 (the \"License\"); you may not use this file\n * except in compliance with the License. You may obtain a copy of\n * the License at http:\/\/www.apache.org\/licenses\/LICENSE-2.0 .\n *\/\n\n#include \"fucopy.hxx\"\n#include <sfx2\/progress.hxx>\n#include <svx\/svxids.hrc>\n\n#include \"sdresid.hxx\"\n#include \"sdattr.hxx\"\n#include \"strings.hrc\"\n#include \"ViewShell.hxx\"\n#include \"View.hxx\"\n#include \"drawdoc.hxx\"\n#include \"DrawDocShell.hxx\"\n#include <vcl\/wrkwin.hxx>\n#include <svx\/svdobj.hxx>\n#include <vcl\/msgbox.hxx>\n#include <sfx2\/app.hxx>\n#include <svx\/xcolit.hxx>\n#include <svx\/xflclit.hxx>\n#include <svx\/xdef.hxx>\n#include <svx\/xfillit0.hxx>\n#include <sfx2\/request.hxx>\n#include \"sdabstdlg.hxx\"\nnamespace sd {\n\nTYPEINIT1( FuCopy, FuPoor );\n\n\nFuCopy::FuCopy (\n ViewShell* pViewSh,\n ::sd::Window* pWin,\n ::sd::View* pView,\n SdDrawDocument* pDoc,\n SfxRequest& rReq)\n : FuPoor(pViewSh, pWin, pView, pDoc, rReq)\n{\n}\n\nrtl::Reference<FuPoor> FuCopy::Create( ViewShell* pViewSh, ::sd::Window* pWin, ::sd::View* pView, SdDrawDocument* pDoc, SfxRequest& rReq )\n{\n rtl::Reference<FuPoor> xFunc( new FuCopy( pViewSh, pWin, pView, pDoc, rReq ) );\n xFunc->DoExecute(rReq);\n return xFunc;\n}\n\nvoid FuCopy::DoExecute( SfxRequest& rReq )\n{\n if( mpView->AreObjectsMarked() )\n {\n \/\/ Undo\n OUString aString( mpView->GetDescriptionOfMarkedObjects() );\n aString += \" \" + SD_RESSTR( STR_UNDO_COPYOBJECTS );\n mpView->BegUndo( aString );\n\n const SfxItemSet* pArgs = rReq.GetArgs();\n\n if( !pArgs )\n {\n SfxItemSet aSet( mpViewShell->GetPool(),\n ATTR_COPY_START, ATTR_COPY_END, 0 );\n\n \/\/ indicate color attribute\n SfxItemSet aAttr( mpDoc->GetPool() );\n mpView->GetAttributes( aAttr );\n const SfxPoolItem* pPoolItem = NULL;\n\n if( SFX_ITEM_SET == aAttr.GetItemState( XATTR_FILLSTYLE, true, &pPoolItem ) )\n {\n XFillStyle eStyle = ( ( const XFillStyleItem* ) pPoolItem )->GetValue();\n\n if( eStyle == XFILL_SOLID &&\n SFX_ITEM_SET == aAttr.GetItemState( XATTR_FILLCOLOR, true, &pPoolItem ) )\n {\n const XFillColorItem* pItem = ( const XFillColorItem* ) pPoolItem;\n XColorItem aXColorItem( ATTR_COPY_START_COLOR, pItem->GetName(),\n pItem->GetColorValue() );\n aSet.Put( aXColorItem );\n\n }\n }\n\n SdAbstractDialogFactory* pFact = SdAbstractDialogFactory::Create();\n if( pFact )\n {\n AbstractCopyDlg* pDlg = pFact->CreateCopyDlg(NULL, aSet, mpDoc->GetColorList(), mpView );\n if( pDlg )\n {\n sal_uInt16 nResult = pDlg->Execute();\n\n switch( nResult )\n {\n case RET_OK:\n pDlg->GetAttr( aSet );\n rReq.Done( aSet );\n pArgs = rReq.GetArgs();\n break;\n\n default:\n {\n delete pDlg;\n mpView->EndUndo();\n }\n return; \/\/ Cancel\n }\n delete( pDlg );\n }\n }\n }\n\n Rectangle aRect;\n sal_Int32 lWidth = 0, lHeight = 0, lSizeX = 0L, lSizeY = 0L, lAngle = 0L;\n sal_uInt16 nNumber = 0;\n Color aStartColor, aEndColor;\n sal_Bool bColor = sal_False;\n const SfxPoolItem* pPoolItem = NULL;\n\n \/\/ Count\n if( SFX_ITEM_SET == pArgs->GetItemState( ATTR_COPY_NUMBER, true, &pPoolItem ) )\n nNumber = ( ( const SfxUInt16Item* ) pPoolItem )->GetValue();\n\n \/\/ translation\n if( SFX_ITEM_SET == pArgs->GetItemState( ATTR_COPY_MOVE_X, true, &pPoolItem ) )\n lSizeX = ( ( const SfxInt32Item* ) pPoolItem )->GetValue();\n if( SFX_ITEM_SET == pArgs->GetItemState( ATTR_COPY_MOVE_Y, true, &pPoolItem ) )\n lSizeY = ( ( const SfxInt32Item* ) pPoolItem )->GetValue();\n if( SFX_ITEM_SET == pArgs->GetItemState( ATTR_COPY_ANGLE, true, &pPoolItem ) )\n lAngle = ( ( const SfxInt32Item* )pPoolItem )->GetValue();\n\n \/\/ scale\n if( SFX_ITEM_SET == pArgs->GetItemState( ATTR_COPY_WIDTH, true, &pPoolItem ) )\n lWidth = ( ( const SfxInt32Item* ) pPoolItem )->GetValue();\n if( SFX_ITEM_SET == pArgs->GetItemState( ATTR_COPY_HEIGHT, true, &pPoolItem ) )\n lHeight = ( ( const SfxInt32Item* ) pPoolItem )->GetValue();\n\n \/\/ start\/end color\n if( SFX_ITEM_SET == pArgs->GetItemState( ATTR_COPY_START_COLOR, true, &pPoolItem ) )\n {\n aStartColor = ( ( const XColorItem* ) pPoolItem )->GetColorValue();\n bColor = sal_True;\n }\n if( SFX_ITEM_SET == pArgs->GetItemState( ATTR_COPY_END_COLOR, true, &pPoolItem ) )\n {\n aEndColor = ( ( const XColorItem* ) pPoolItem )->GetColorValue();\n if( aStartColor == aEndColor )\n bColor = sal_False;\n }\n else\n bColor = sal_False;\n\n \/\/ remove handles\n \/\/HMHmpView->HideMarkHdl();\n\n SfxProgress* pProgress = NULL;\n sal_Bool bWaiting = sal_False;\n\n if( nNumber > 1 )\n {\n OUString aStr( SD_RESSTR( STR_OBJECTS ) );\n aStr += \" \" + SD_RESSTR( STR_UNDO_COPYOBJECTS );\n\n pProgress = new SfxProgress( mpDocSh, aStr, nNumber );\n mpDocSh->SetWaitCursor( sal_True );\n bWaiting = sal_True;\n }\n\n const SdrMarkList aMarkList( mpView->GetMarkedObjectList() );\n const sal_uLong nMarkCount = aMarkList.GetMarkCount();\n SdrObject* pObj = NULL;\n\n \/\/ calculate number of possible copies\n aRect = mpView->GetAllMarkedRect();\n\n if( lWidth < 0L )\n {\n long nTmp = ( aRect.Right() - aRect.Left() ) \/ -lWidth;\n nNumber = (sal_uInt16) std::min( nTmp, (long)nNumber );\n }\n\n if( lHeight < 0L )\n {\n long nTmp = ( aRect.Bottom() - aRect.Top() ) \/ -lHeight;\n nNumber = (sal_uInt16) std::min( nTmp, (long)nNumber );\n }\n\n for( sal_uInt16 i = 1; i <= nNumber; i++ )\n {\n if( pProgress )\n pProgress->SetState( i );\n\n aRect = mpView->GetAllMarkedRect();\n\n if( ( 1 == i ) && bColor )\n {\n SfxItemSet aNewSet( mpViewShell->GetPool(), XATTR_FILLSTYLE, XATTR_FILLCOLOR, 0L );\n aNewSet.Put( XFillStyleItem( XFILL_SOLID ) );\n aNewSet.Put( XFillColorItem( OUString(), aStartColor ) );\n mpView->SetAttributes( aNewSet );\n }\n\n \/\/ make a copy of selected objects\n mpView->CopyMarked();\n\n \/\/ get newly selected objects\n SdrMarkList aCopyMarkList( mpView->GetMarkedObjectList() );\n sal_uLong j, nCopyMarkCount = aMarkList.GetMarkCount();\n\n \/\/ set protection flags at marked copies to null\n for( j = 0; j < nCopyMarkCount; j++ )\n {\n pObj = aCopyMarkList.GetMark( j )->GetMarkedSdrObj();\n\n if( pObj )\n {\n pObj->SetMoveProtect( false );\n pObj->SetResizeProtect( false );\n }\n }\n\n Fraction aWidth( aRect.Right() - aRect.Left() + lWidth, aRect.Right() - aRect.Left() );\n Fraction aHeight( aRect.Bottom() - aRect.Top() + lHeight, aRect.Bottom() - aRect.Top() );\n\n if( mpView->IsResizeAllowed() )\n mpView->ResizeAllMarked( aRect.TopLeft(), aWidth, aHeight );\n\n if( mpView->IsRotateAllowed() )\n mpView->RotateAllMarked( aRect.Center(), lAngle * 100 );\n\n if( mpView->IsMoveAllowed() )\n mpView->MoveAllMarked( Size( lSizeX, lSizeY ) );\n\n \/\/ set protection flags at marked copies to original values\n if( nMarkCount == nCopyMarkCount )\n {\n for( j = 0; j < nMarkCount; j++ )\n {\n SdrObject* pSrcObj = aMarkList.GetMark( j )->GetMarkedSdrObj();\n SdrObject* pDstObj = aCopyMarkList.GetMark( j )->GetMarkedSdrObj();\n\n if( pSrcObj && pDstObj &&\n ( pSrcObj->GetObjInventor() == pDstObj->GetObjInventor() ) &&\n ( pSrcObj->GetObjIdentifier() == pDstObj->GetObjIdentifier() ) )\n {\n pDstObj->SetMoveProtect( pSrcObj->IsMoveProtect() );\n pDstObj->SetResizeProtect( pSrcObj->IsResizeProtect() );\n }\n }\n }\n\n if( bColor )\n {\n \/\/ probably room for optimizations, but may can lead to rounding errors\n sal_uInt8 nRed = aStartColor.GetRed() + (sal_uInt8) ( ( (long) aEndColor.GetRed() - (long) aStartColor.GetRed() ) * (long) i \/ (long) nNumber );\n sal_uInt8 nGreen = aStartColor.GetGreen() + (sal_uInt8) ( ( (long) aEndColor.GetGreen() - (long) aStartColor.GetGreen() ) * (long) i \/ (long) nNumber );\n sal_uInt8 nBlue = aStartColor.GetBlue() + (sal_uInt8) ( ( (long) aEndColor.GetBlue() - (long) aStartColor.GetBlue() ) * (long) i \/ (long) nNumber );\n Color aNewColor( nRed, nGreen, nBlue );\n SfxItemSet aNewSet( mpViewShell->GetPool(), XATTR_FILLSTYLE, XATTR_FILLCOLOR, 0L );\n aNewSet.Put( XFillStyleItem( XFILL_SOLID ) );\n aNewSet.Put( XFillColorItem( OUString(), aNewColor ) );\n mpView->SetAttributes( aNewSet );\n }\n }\n\n if ( pProgress )\n delete pProgress;\n\n if ( bWaiting )\n mpDocSh->SetWaitCursor( sal_False );\n\n \/\/ show handles\n mpView->AdjustMarkHdl(); \/\/HMH sal_True );\n \/\/HMHpView->ShowMarkHdl();\n\n mpView->EndUndo();\n }\n}\n\n} \/\/ end of namespace\n\n\/* vim:set shiftwidth=4 softtabstop=4 expandtab: *\/\n<commit_msg>coverity#704748 Dereference after null check<commit_after>\/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- *\/\n\/*\n * This file is part of the LibreOffice project.\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\n * This file incorporates work covered by the following license notice:\n *\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed\n * with this work for additional information regarding copyright\n * ownership. The ASF licenses this file to you under the Apache\n * License, Version 2.0 (the \"License\"); you may not use this file\n * except in compliance with the License. You may obtain a copy of\n * the License at http:\/\/www.apache.org\/licenses\/LICENSE-2.0 .\n *\/\n\n#include \"fucopy.hxx\"\n#include <sfx2\/progress.hxx>\n#include <svx\/svxids.hrc>\n\n#include \"sdresid.hxx\"\n#include \"sdattr.hxx\"\n#include \"strings.hrc\"\n#include \"ViewShell.hxx\"\n#include \"View.hxx\"\n#include \"drawdoc.hxx\"\n#include \"DrawDocShell.hxx\"\n#include <vcl\/wrkwin.hxx>\n#include <svx\/svdobj.hxx>\n#include <vcl\/msgbox.hxx>\n#include <sfx2\/app.hxx>\n#include <svx\/xcolit.hxx>\n#include <svx\/xflclit.hxx>\n#include <svx\/xdef.hxx>\n#include <svx\/xfillit0.hxx>\n#include <sfx2\/request.hxx>\n#include \"sdabstdlg.hxx\"\nnamespace sd {\n\nTYPEINIT1( FuCopy, FuPoor );\n\n\nFuCopy::FuCopy (\n ViewShell* pViewSh,\n ::sd::Window* pWin,\n ::sd::View* pView,\n SdDrawDocument* pDoc,\n SfxRequest& rReq)\n : FuPoor(pViewSh, pWin, pView, pDoc, rReq)\n{\n}\n\nrtl::Reference<FuPoor> FuCopy::Create( ViewShell* pViewSh, ::sd::Window* pWin, ::sd::View* pView, SdDrawDocument* pDoc, SfxRequest& rReq )\n{\n rtl::Reference<FuPoor> xFunc( new FuCopy( pViewSh, pWin, pView, pDoc, rReq ) );\n xFunc->DoExecute(rReq);\n return xFunc;\n}\n\nvoid FuCopy::DoExecute( SfxRequest& rReq )\n{\n if( mpView->AreObjectsMarked() )\n {\n \/\/ Undo\n OUString aString( mpView->GetDescriptionOfMarkedObjects() );\n aString += \" \" + SD_RESSTR( STR_UNDO_COPYOBJECTS );\n mpView->BegUndo( aString );\n\n const SfxItemSet* pArgs = rReq.GetArgs();\n\n if( !pArgs )\n {\n SfxItemSet aSet( mpViewShell->GetPool(),\n ATTR_COPY_START, ATTR_COPY_END, 0 );\n\n \/\/ indicate color attribute\n SfxItemSet aAttr( mpDoc->GetPool() );\n mpView->GetAttributes( aAttr );\n const SfxPoolItem* pPoolItem = NULL;\n\n if( SFX_ITEM_SET == aAttr.GetItemState( XATTR_FILLSTYLE, true, &pPoolItem ) )\n {\n XFillStyle eStyle = ( ( const XFillStyleItem* ) pPoolItem )->GetValue();\n\n if( eStyle == XFILL_SOLID &&\n SFX_ITEM_SET == aAttr.GetItemState( XATTR_FILLCOLOR, true, &pPoolItem ) )\n {\n const XFillColorItem* pItem = ( const XFillColorItem* ) pPoolItem;\n XColorItem aXColorItem( ATTR_COPY_START_COLOR, pItem->GetName(),\n pItem->GetColorValue() );\n aSet.Put( aXColorItem );\n\n }\n }\n\n SdAbstractDialogFactory* pFact = SdAbstractDialogFactory::Create();\n if( pFact )\n {\n AbstractCopyDlg* pDlg = pFact->CreateCopyDlg(NULL, aSet, mpDoc->GetColorList(), mpView );\n if (!pDlg)\n return;\n\n sal_uInt16 nResult = pDlg->Execute();\n\n switch( nResult )\n {\n case RET_OK:\n pDlg->GetAttr( aSet );\n rReq.Done( aSet );\n pArgs = rReq.GetArgs();\n break;\n\n default:\n {\n delete pDlg;\n mpView->EndUndo();\n }\n return; \/\/ Cancel\n }\n delete pDlg;\n }\n }\n\n Rectangle aRect;\n sal_Int32 lWidth = 0, lHeight = 0, lSizeX = 0L, lSizeY = 0L, lAngle = 0L;\n sal_uInt16 nNumber = 0;\n Color aStartColor, aEndColor;\n sal_Bool bColor = sal_False;\n const SfxPoolItem* pPoolItem = NULL;\n\n \/\/ Count\n if( SFX_ITEM_SET == pArgs->GetItemState( ATTR_COPY_NUMBER, true, &pPoolItem ) )\n nNumber = ( ( const SfxUInt16Item* ) pPoolItem )->GetValue();\n\n \/\/ translation\n if( SFX_ITEM_SET == pArgs->GetItemState( ATTR_COPY_MOVE_X, true, &pPoolItem ) )\n lSizeX = ( ( const SfxInt32Item* ) pPoolItem )->GetValue();\n if( SFX_ITEM_SET == pArgs->GetItemState( ATTR_COPY_MOVE_Y, true, &pPoolItem ) )\n lSizeY = ( ( const SfxInt32Item* ) pPoolItem )->GetValue();\n if( SFX_ITEM_SET == pArgs->GetItemState( ATTR_COPY_ANGLE, true, &pPoolItem ) )\n lAngle = ( ( const SfxInt32Item* )pPoolItem )->GetValue();\n\n \/\/ scale\n if( SFX_ITEM_SET == pArgs->GetItemState( ATTR_COPY_WIDTH, true, &pPoolItem ) )\n lWidth = ( ( const SfxInt32Item* ) pPoolItem )->GetValue();\n if( SFX_ITEM_SET == pArgs->GetItemState( ATTR_COPY_HEIGHT, true, &pPoolItem ) )\n lHeight = ( ( const SfxInt32Item* ) pPoolItem )->GetValue();\n\n \/\/ start\/end color\n if( SFX_ITEM_SET == pArgs->GetItemState( ATTR_COPY_START_COLOR, true, &pPoolItem ) )\n {\n aStartColor = ( ( const XColorItem* ) pPoolItem )->GetColorValue();\n bColor = sal_True;\n }\n if( SFX_ITEM_SET == pArgs->GetItemState( ATTR_COPY_END_COLOR, true, &pPoolItem ) )\n {\n aEndColor = ( ( const XColorItem* ) pPoolItem )->GetColorValue();\n if( aStartColor == aEndColor )\n bColor = sal_False;\n }\n else\n bColor = sal_False;\n\n \/\/ remove handles\n \/\/HMHmpView->HideMarkHdl();\n\n SfxProgress* pProgress = NULL;\n sal_Bool bWaiting = sal_False;\n\n if( nNumber > 1 )\n {\n OUString aStr( SD_RESSTR( STR_OBJECTS ) );\n aStr += \" \" + SD_RESSTR( STR_UNDO_COPYOBJECTS );\n\n pProgress = new SfxProgress( mpDocSh, aStr, nNumber );\n mpDocSh->SetWaitCursor( sal_True );\n bWaiting = sal_True;\n }\n\n const SdrMarkList aMarkList( mpView->GetMarkedObjectList() );\n const sal_uLong nMarkCount = aMarkList.GetMarkCount();\n SdrObject* pObj = NULL;\n\n \/\/ calculate number of possible copies\n aRect = mpView->GetAllMarkedRect();\n\n if( lWidth < 0L )\n {\n long nTmp = ( aRect.Right() - aRect.Left() ) \/ -lWidth;\n nNumber = (sal_uInt16) std::min( nTmp, (long)nNumber );\n }\n\n if( lHeight < 0L )\n {\n long nTmp = ( aRect.Bottom() - aRect.Top() ) \/ -lHeight;\n nNumber = (sal_uInt16) std::min( nTmp, (long)nNumber );\n }\n\n for( sal_uInt16 i = 1; i <= nNumber; i++ )\n {\n if( pProgress )\n pProgress->SetState( i );\n\n aRect = mpView->GetAllMarkedRect();\n\n if( ( 1 == i ) && bColor )\n {\n SfxItemSet aNewSet( mpViewShell->GetPool(), XATTR_FILLSTYLE, XATTR_FILLCOLOR, 0L );\n aNewSet.Put( XFillStyleItem( XFILL_SOLID ) );\n aNewSet.Put( XFillColorItem( OUString(), aStartColor ) );\n mpView->SetAttributes( aNewSet );\n }\n\n \/\/ make a copy of selected objects\n mpView->CopyMarked();\n\n \/\/ get newly selected objects\n SdrMarkList aCopyMarkList( mpView->GetMarkedObjectList() );\n sal_uLong j, nCopyMarkCount = aMarkList.GetMarkCount();\n\n \/\/ set protection flags at marked copies to null\n for( j = 0; j < nCopyMarkCount; j++ )\n {\n pObj = aCopyMarkList.GetMark( j )->GetMarkedSdrObj();\n\n if( pObj )\n {\n pObj->SetMoveProtect( false );\n pObj->SetResizeProtect( false );\n }\n }\n\n Fraction aWidth( aRect.Right() - aRect.Left() + lWidth, aRect.Right() - aRect.Left() );\n Fraction aHeight( aRect.Bottom() - aRect.Top() + lHeight, aRect.Bottom() - aRect.Top() );\n\n if( mpView->IsResizeAllowed() )\n mpView->ResizeAllMarked( aRect.TopLeft(), aWidth, aHeight );\n\n if( mpView->IsRotateAllowed() )\n mpView->RotateAllMarked( aRect.Center(), lAngle * 100 );\n\n if( mpView->IsMoveAllowed() )\n mpView->MoveAllMarked( Size( lSizeX, lSizeY ) );\n\n \/\/ set protection flags at marked copies to original values\n if( nMarkCount == nCopyMarkCount )\n {\n for( j = 0; j < nMarkCount; j++ )\n {\n SdrObject* pSrcObj = aMarkList.GetMark( j )->GetMarkedSdrObj();\n SdrObject* pDstObj = aCopyMarkList.GetMark( j )->GetMarkedSdrObj();\n\n if( pSrcObj && pDstObj &&\n ( pSrcObj->GetObjInventor() == pDstObj->GetObjInventor() ) &&\n ( pSrcObj->GetObjIdentifier() == pDstObj->GetObjIdentifier() ) )\n {\n pDstObj->SetMoveProtect( pSrcObj->IsMoveProtect() );\n pDstObj->SetResizeProtect( pSrcObj->IsResizeProtect() );\n }\n }\n }\n\n if( bColor )\n {\n \/\/ probably room for optimizations, but may can lead to rounding errors\n sal_uInt8 nRed = aStartColor.GetRed() + (sal_uInt8) ( ( (long) aEndColor.GetRed() - (long) aStartColor.GetRed() ) * (long) i \/ (long) nNumber );\n sal_uInt8 nGreen = aStartColor.GetGreen() + (sal_uInt8) ( ( (long) aEndColor.GetGreen() - (long) aStartColor.GetGreen() ) * (long) i \/ (long) nNumber );\n sal_uInt8 nBlue = aStartColor.GetBlue() + (sal_uInt8) ( ( (long) aEndColor.GetBlue() - (long) aStartColor.GetBlue() ) * (long) i \/ (long) nNumber );\n Color aNewColor( nRed, nGreen, nBlue );\n SfxItemSet aNewSet( mpViewShell->GetPool(), XATTR_FILLSTYLE, XATTR_FILLCOLOR, 0L );\n aNewSet.Put( XFillStyleItem( XFILL_SOLID ) );\n aNewSet.Put( XFillColorItem( OUString(), aNewColor ) );\n mpView->SetAttributes( aNewSet );\n }\n }\n\n if ( pProgress )\n delete pProgress;\n\n if ( bWaiting )\n mpDocSh->SetWaitCursor( sal_False );\n\n \/\/ show handles\n mpView->AdjustMarkHdl(); \/\/HMH sal_True );\n \/\/HMHpView->ShowMarkHdl();\n\n mpView->EndUndo();\n }\n}\n\n} \/\/ end of namespace\n\n\/* vim:set shiftwidth=4 softtabstop=4 expandtab: *\/\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: bmcache.hxx,v $\n *\n * $Revision: 1.2 $\n *\n * last change: $Author: ka $ $Date: 2001-09-24 13:18:14 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef _SD_BMCACHE_HXX\n#define _SD_BMCACHE_HXX\n\n#ifndef _LIST_HXX \/\/autogen\n#include <tools\/list.hxx>\n#endif\n\n\nclass SdPage;\nclass GraphicObject;\n\nclass BitmapCache\n{\n ULONG nMaxSize;\n ULONG nCurSize;\n List aEntries;\n\npublic:\n BitmapCache(ULONG nMaxSizeKB)\n : nMaxSize(nMaxSizeKB), nCurSize(0) {}\n virtual ~BitmapCache();\n\n void Add(const SdPage* pPage, const Bitmap& rBmp, long nZoomPercent);\n const GraphicObject* Get(const SdPage* pPage, long& rZoomPercent, long nZoomTolerancePercent);\n void Remove(const SdPage* pPage);\n};\n\n#endif \/\/ _SD_BMCACHE_HXX\n\n<commit_msg>INTEGRATION: CWS ooo19126 (1.2.908); FILE MERGED 2005\/09\/05 13:22:54 rt 1.2.908.1: #i54170# Change license header: remove SISSL<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: bmcache.hxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: rt $ $Date: 2005-09-09 05:22:25 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef _SD_BMCACHE_HXX\n#define _SD_BMCACHE_HXX\n\n#ifndef _LIST_HXX \/\/autogen\n#include <tools\/list.hxx>\n#endif\n\n\nclass SdPage;\nclass GraphicObject;\n\nclass BitmapCache\n{\n ULONG nMaxSize;\n ULONG nCurSize;\n List aEntries;\n\npublic:\n BitmapCache(ULONG nMaxSizeKB)\n : nMaxSize(nMaxSizeKB), nCurSize(0) {}\n virtual ~BitmapCache();\n\n void Add(const SdPage* pPage, const Bitmap& rBmp, long nZoomPercent);\n const GraphicObject* Get(const SdPage* pPage, long& rZoomPercent, long nZoomTolerancePercent);\n void Remove(const SdPage* pPage);\n};\n\n#endif \/\/ _SD_BMCACHE_HXX\n\n<|endoftext|>"} {"text":"<commit_before>#include \"TextWindow.h\"\n#include <string.h>\n#include <errno.h>\n\nusing namespace input;\n\nnamespace video{\n void TextWindow::newLine(){\n _curs.x = 0;\n if(_curs.y + 1 == _lineBuffer.size()){\n if(_lineBuffer.size() == LineNum){\n _lineBuffer.pop_front();\n }\n else{\n ++_curs.y;\n }\n _lineBuffer.push_back(Line());\n }\n else ++_curs.y;\n }\n\n void TextWindow::addPrintableChar(char c){\n assert(_curs.x <= _width);\n if(_curs.x == _width) newLine();\n \/\/fprintf(stderr,\"pos %d %d %d %d %d\\n\",_curs.x, _curs.y,_cursFormat.fg.R,\n \/\/_cursFormat.fg.G,_cursFormat.fg.B);\n _lineBuffer.at(_curs.y).write(_curs.x,FormatedChar(c,_cursFormat));\n ++_curs.x;\n }\n\n size_t TextWindow::write(const void* buf, size_t count){\n fprintf(stderr,\"write TextWindow\\n\");\n const char* buf2 = reinterpret_cast<const char*>(buf);\n const size_t limit = 1024;\n if(count > limit) count = limit;\n for(size_t i = 0 ; i < count ; ++i){\n putChar(buf2[i]);\n }\n return count;\n }\n\n void TextWindow::error(){\n _state = NORMAL;\n putChar('~');\n putChar('~');\n }\n\n void TextWindow::putChar(char c){\n fprintf(stderr,\"putChar('%c'); with %d in win %d\\n\",c,_state,getWID());\n switch(_state){\n case WAITINGOB:\n if(c != '['){\n error();\n putChar(c);\n }\n else {\n _stack.clear();\n _stack.push_back(0);\n _state = ESCAPE;\n }\n return;\n\n\n case ESCAPE:\n if(c < 32 or c > 126) {\n error();\n putChar(c);\n return;\n }\n\n if(c >= '0' and c <= '9'){\n _stack.back() *=10;\n _stack.back() += (c - '0');\n return;\n }\n\n switch(c){\n case ';':\n _stack.push_back(0);\n return;\n case 'm':\n SGR();\n _state = NORMAL;\n return;\n default:\n error();\n putChar(c);\n return;\n }\n\n\n case NORMAL:\n if(c == 27){\n _state = WAITINGOB;\n return;\n }\n\n uint val;\n switch(c){\n case '\\n':\n \/\/fprintf(stderr,\" new line \\n\");\n newLine();\n return;\n\n case '\\t':\n \/\/ A clean way to do it.\n val = _curs.x%4;\n for(uint i = 0 ; i < 4-val ; ++i){\n addPrintableChar(' ');\n }\n return;\n\n case '\\b':\n if(_curs.x == 0){\n if(_curs.y > 0) --_curs.y;\n _curs.x = _width -1;\n }\n else --_curs.x;\n return;\n\n case '\\r':\n _curs.x = 0;\n return;\n\n case '\\f':\n val = _curs.x;\n newLine();\n _curs.x = val;\n return;\n\n default:\n if(c < 32 and c >= EOF){\n error();\n return;\n }\n addPrintableChar(c);\n return;\n }\n }\n }\n\n \/**\n @brief Handles SGR Commands\n\n @todo Add Blinking.\n *\/\n\n void TextWindow::SGR(){\n \/\/fprintf(stderr,\"SGR %d\\n\",_stack.size());\n if(_stack.size() == 0){\n _cursFormat = Format();\n return;\n }\n\n uint command = _stack[0];\n if(command == 0){\n _cursFormat = Format();\n }\n else if(command == 1){\n _bright = true;\n }\n else if(command == 2){\n _bright = false;\n }\n else if(command == 4){\n _cursFormat.underline = true;\n }\n else if(command == 7){\n std::swap(_cursFormat.fg,_cursFormat.bg);\n }\n else if(command == 24){\n _cursFormat.underline = false;\n }\n\n else if(command >=30 and command <= 37){\n _cursFormat.fg = getByNum(command -30);\n }\n else if(command == 38){\n if(_stack.size() < 5){\n error();\n return;\n }\n if(_stack[1] != 2){\n error();\n return;\n }\n _cursFormat.fg.R = _stack[3];\n _cursFormat.fg.G = _stack[4];\n _cursFormat.fg.B = _stack[5];\n }\n else if(command == 39){\n _cursFormat.fg = Color24::lwhite;\n }\n\n else if(command >=40 and command <= 47){\n _cursFormat.bg = getByNum(command -40);\n }\n else if(command == 48){\n if(_stack.size() < 5){\n error();\n return;\n }\n if(_stack[1] != 2){\n error();\n return;\n }\n _cursFormat.bg.R = _stack[3];\n _cursFormat.bg.G = _stack[4];\n _cursFormat.bg.B = _stack[5];\n }\n else if(command == 49){\n _cursFormat.bg = Color24::black;\n }\n }\n\n void TextWindow::send() const{\n \/\/fprintf(stderr,\"hey !\\n\");\n if(!_active) return;\n \/\/fprintf(stderr,\"hoy !\\n\");\n size_t s = _lineBuffer.size();\n size_t offset = max(i64(s - _height),i64(0));\n \/\/if(getWID()>=2) fprintf(stderr,\"number line %llu and height %llu and offset \\n\",s,_height);\n for(size_t i = 0; i < min(s,(size_t)_height) ; ++i){\n \/\/fprintf(stderr,\"printing line %llu \\n\",i + offset);\n size_t j = 0;\n \/\/fprintf(stderr,\"of size %d \\n\",_lineBuffer[i + offset].data.size());\n for(auto fmc : _lineBuffer[i + offset].data){\n \/\/fprintf(stderr,\"printing %llu %llu\\n\",i,j);\n drawFMC({j,i},fmc);\n ++j;\n }\n }\n\n }\n void TextWindow::drawFMC(Vec2u pos, FormatedChar fmc) const{\n screen.putChar(fmc.c,_offset.x + pos.x*8+1,_offset.y + pos.y*16 + 1,*_font,fmc.fg,fmc.bg);\n if(fmc.underline){\n for(uint k = 0 ; k < 8 ; ++k){\n screen.set(_offset.x + pos.x*8+1+k, _offset.y + pos.y*16+16,fmc.fg);\n }\n }\n }\n\n bool TextWindow::handleEvent(input::Event e){\n if(e.type == Event::KEYBOARD){\n if(e.kcode.symbol and !e.kcode.scanCode.release and allowInput){\n char sym = e.kcode.symbol;\n if(sym == '\\b' ){\n if(!_keyboardBuffer.empty()){\n _keyboardBuffer.pop_back();\n putChar('\\b');\n putChar(' ');\n putChar('\\b');\n }\n }\n else if(sym == '\\n'){\n for(auto c : _keyboardBuffer){\n _inputBuffer.push_back(c);\n }\n _keyboardBuffer.clear();\n _inputBuffer.push_back('\\n');\n putChar('\\n');\n }\n else{\n _keyboardBuffer.push_back(sym);\n putChar(sym);\n }\n }\n }\n return true;\n }\n\n size_t TextWindow::read(void* buf, size_t count){\n char* buf2 = reinterpret_cast<char*>(buf);\n if(count > 1000) count = 1000;\n size_t reallyRead =0;\n while(!_inputBuffer.empty() and reallyRead < count){\n *buf2 = _inputBuffer.front();\n _inputBuffer.pop_front();\n ++reallyRead;\n ++buf2;\n }\n return reallyRead;\n }\n\n};\n<commit_msg>Removed TextWindow debug logs<commit_after>#include \"TextWindow.h\"\n#include <string.h>\n#include <errno.h>\n\nusing namespace input;\n\nnamespace video{\n void TextWindow::newLine(){\n _curs.x = 0;\n if(_curs.y + 1 == _lineBuffer.size()){\n if(_lineBuffer.size() == LineNum){\n _lineBuffer.pop_front();\n }\n else{\n ++_curs.y;\n }\n _lineBuffer.push_back(Line());\n }\n else ++_curs.y;\n }\n\n void TextWindow::addPrintableChar(char c){\n assert(_curs.x <= _width);\n if(_curs.x == _width) newLine();\n \/\/fprintf(stderr,\"pos %d %d %d %d %d\\n\",_curs.x, _curs.y,_cursFormat.fg.R,\n \/\/_cursFormat.fg.G,_cursFormat.fg.B);\n _lineBuffer.at(_curs.y).write(_curs.x,FormatedChar(c,_cursFormat));\n ++_curs.x;\n }\n\n size_t TextWindow::write(const void* buf, size_t count){\n \/\/fprintf(stderr,\"write TextWindow\\n\");\n const char* buf2 = reinterpret_cast<const char*>(buf);\n const size_t limit = 1024;\n if(count > limit) count = limit;\n for(size_t i = 0 ; i < count ; ++i){\n putChar(buf2[i]);\n }\n return count;\n }\n\n void TextWindow::error(){\n _state = NORMAL;\n putChar('~');\n putChar('~');\n }\n\n void TextWindow::putChar(char c){\n \/\/fprintf(stderr,\"putChar('%c'); with %d in win %d\\n\",c,_state,getWID());\n switch(_state){\n case WAITINGOB:\n if(c != '['){\n error();\n putChar(c);\n }\n else {\n _stack.clear();\n _stack.push_back(0);\n _state = ESCAPE;\n }\n return;\n\n\n case ESCAPE:\n if(c < 32 or c > 126) {\n error();\n putChar(c);\n return;\n }\n\n if(c >= '0' and c <= '9'){\n _stack.back() *=10;\n _stack.back() += (c - '0');\n return;\n }\n\n switch(c){\n case ';':\n _stack.push_back(0);\n return;\n case 'm':\n SGR();\n _state = NORMAL;\n return;\n default:\n error();\n putChar(c);\n return;\n }\n\n\n case NORMAL:\n if(c == 27){\n _state = WAITINGOB;\n return;\n }\n\n uint val;\n switch(c){\n case '\\n':\n \/\/fprintf(stderr,\" new line \\n\");\n newLine();\n return;\n\n case '\\t':\n \/\/ A clean way to do it.\n val = _curs.x%4;\n for(uint i = 0 ; i < 4-val ; ++i){\n addPrintableChar(' ');\n }\n return;\n\n case '\\b':\n if(_curs.x == 0){\n if(_curs.y > 0) --_curs.y;\n _curs.x = _width -1;\n }\n else --_curs.x;\n return;\n\n case '\\r':\n _curs.x = 0;\n return;\n\n case '\\f':\n val = _curs.x;\n newLine();\n _curs.x = val;\n return;\n\n default:\n if(c < 32 and c >= EOF){\n error();\n return;\n }\n addPrintableChar(c);\n return;\n }\n }\n }\n\n \/**\n @brief Handles SGR Commands\n\n @todo Add Blinking.\n *\/\n\n void TextWindow::SGR(){\n \/\/fprintf(stderr,\"SGR %d\\n\",_stack.size());\n if(_stack.size() == 0){\n _cursFormat = Format();\n return;\n }\n\n uint command = _stack[0];\n if(command == 0){\n _cursFormat = Format();\n }\n else if(command == 1){\n _bright = true;\n }\n else if(command == 2){\n _bright = false;\n }\n else if(command == 4){\n _cursFormat.underline = true;\n }\n else if(command == 7){\n std::swap(_cursFormat.fg,_cursFormat.bg);\n }\n else if(command == 24){\n _cursFormat.underline = false;\n }\n\n else if(command >=30 and command <= 37){\n _cursFormat.fg = getByNum(command -30);\n }\n else if(command == 38){\n if(_stack.size() < 5){\n error();\n return;\n }\n if(_stack[1] != 2){\n error();\n return;\n }\n _cursFormat.fg.R = _stack[3];\n _cursFormat.fg.G = _stack[4];\n _cursFormat.fg.B = _stack[5];\n }\n else if(command == 39){\n _cursFormat.fg = Color24::lwhite;\n }\n\n else if(command >=40 and command <= 47){\n _cursFormat.bg = getByNum(command -40);\n }\n else if(command == 48){\n if(_stack.size() < 5){\n error();\n return;\n }\n if(_stack[1] != 2){\n error();\n return;\n }\n _cursFormat.bg.R = _stack[3];\n _cursFormat.bg.G = _stack[4];\n _cursFormat.bg.B = _stack[5];\n }\n else if(command == 49){\n _cursFormat.bg = Color24::black;\n }\n }\n\n void TextWindow::send() const{\n \/\/fprintf(stderr,\"hey !\\n\");\n if(!_active) return;\n \/\/fprintf(stderr,\"hoy !\\n\");\n size_t s = _lineBuffer.size();\n size_t offset = max(i64(s - _height),i64(0));\n \/\/if(getWID()>=2) fprintf(stderr,\"number line %llu and height %llu and offset \\n\",s,_height);\n for(size_t i = 0; i < min(s,(size_t)_height) ; ++i){\n \/\/fprintf(stderr,\"printing line %llu \\n\",i + offset);\n size_t j = 0;\n \/\/fprintf(stderr,\"of size %d \\n\",_lineBuffer[i + offset].data.size());\n for(auto fmc : _lineBuffer[i + offset].data){\n \/\/fprintf(stderr,\"printing %llu %llu\\n\",i,j);\n drawFMC({j,i},fmc);\n ++j;\n }\n }\n\n }\n void TextWindow::drawFMC(Vec2u pos, FormatedChar fmc) const{\n screen.putChar(fmc.c,_offset.x + pos.x*8+1,_offset.y + pos.y*16 + 1,*_font,fmc.fg,fmc.bg);\n if(fmc.underline){\n for(uint k = 0 ; k < 8 ; ++k){\n screen.set(_offset.x + pos.x*8+1+k, _offset.y + pos.y*16+16,fmc.fg);\n }\n }\n }\n\n bool TextWindow::handleEvent(input::Event e){\n if(e.type == Event::KEYBOARD){\n if(e.kcode.symbol and !e.kcode.scanCode.release and allowInput){\n char sym = e.kcode.symbol;\n if(sym == '\\b' ){\n if(!_keyboardBuffer.empty()){\n _keyboardBuffer.pop_back();\n putChar('\\b');\n putChar(' ');\n putChar('\\b');\n }\n }\n else if(sym == '\\n'){\n for(auto c : _keyboardBuffer){\n _inputBuffer.push_back(c);\n }\n _keyboardBuffer.clear();\n _inputBuffer.push_back('\\n');\n putChar('\\n');\n }\n else{\n _keyboardBuffer.push_back(sym);\n putChar(sym);\n }\n }\n }\n return true;\n }\n\n size_t TextWindow::read(void* buf, size_t count){\n char* buf2 = reinterpret_cast<char*>(buf);\n if(count > 1000) count = 1000;\n size_t reallyRead =0;\n while(!_inputBuffer.empty() and reallyRead < count){\n *buf2 = _inputBuffer.front();\n _inputBuffer.pop_front();\n ++reallyRead;\n ++buf2;\n }\n return reallyRead;\n }\n\n};\n<|endoftext|>"} {"text":"<commit_before>\n\/*\n\n poedit, a wxWindows i18n catalogs editor\n\n ---------------\n chooselang.cpp\n \n Language chooser\n \n (c) Vaclav Slavik, 2003, 2004\n\n*\/\n\n#include <wx\/wxprec.h>\n\n#include <wx\/wx.h>\n#include <wx\/config.h>\n\n#include \"chooselang.h\"\n\nstatic void SaveUILanguage(wxLanguage lang)\n{\n if (lang == wxLANGUAGE_UNKNOWN)\n return;\n if (lang == wxLANGUAGE_DEFAULT)\n wxConfig::Get()->Write(_T(\"ui_language\"), _T(\"default\"));\n else\n wxConfig::Get()->Write(_T(\"ui_language\"),\n wxLocale::GetLanguageInfo(lang)->CanonicalName);\n}\n\nwxLanguage GetUILanguage()\n{\n#if defined(__UNIX__) || !wxCHECK_VERSION(2,5,0)\n return wxLANGUAGE_DEFAULT;\n#else\n wxLanguage lang(wxLANGUAGE_DEFAULT);\n wxString lng = wxConfig::Get()->Read(_T(\"ui_language\"));\n if (lng.empty())\n {\n lang = ChooseLanguage();\n if (lang != wxLANGUAGE_UNKNOWN)\n SaveUILanguage(lang);\n else\n lang = wxLANGUAGE_DEFAULT;\n }\n else if (lng != _T(\"default\"))\n {\n const wxLanguageInfo *info = wxLocale::FindLanguageInfo(lng);\n if (info != NULL)\n lang = (wxLanguage)info->Language;\n else\n wxLogError(_(\"Uknown locale code '%s' in registry.\"), lng.c_str());\n }\n return lang;\n#endif\n}\n\n#ifndef __UNIX__\nwxLanguage ChooseLanguage()\n{\n struct LangInfo\n {\n const wxChar *name;\n wxLanguage code;\n };\n\n LangInfo langs[] = \n {\n { _(\"(Use default language)\"), wxLANGUAGE_DEFAULT },\n\n { _T(\"Afrikaans\"), wxLANGUAGE_AFRIKAANS },\n { _T(\"Albanian\"), wxLANGUAGE_ALBANIAN },\n { _T(\"Amharic\"), wxLANGUAGE_AMHARIC },\n { _T(\"Bangla\"), wxLANGUAGE_BENGALI },\n { _T(\"Belarusian\"), wxLANGUAGE_BELARUSIAN },\n { _T(\"Breton\"), wxLANGUAGE_BRETON },\n { _T(\"Bulgarian\"), wxLANGUAGE_BULGARIAN },\n { _T(\"Catalan\"), wxLANGUAGE_CATALAN },\n { _T(\"Chinese (Traditional)\"), wxLANGUAGE_CHINESE_TRADITIONAL },\n { _T(\"Chinese (Simplified)\"), wxLANGUAGE_CHINESE_SIMPLIFIED },\n { _T(\"Croatian\"), wxLANGUAGE_CROATIAN },\n { _T(\"Czech\"), wxLANGUAGE_CZECH },\n { _T(\"Danish\"), wxLANGUAGE_DANISH },\n { _T(\"Dutch\"), wxLANGUAGE_DUTCH },\n { _T(\"English\"), wxLANGUAGE_ENGLISH },\n { _T(\"Estonian\"), wxLANGUAGE_ESTONIAN },\n { _T(\"Esperanto\"), wxLANGUAGE_ESPERANTO },\n { _T(\"Farsi\"), wxLANGUAGE_FARSI },\n { _T(\"French\"), wxLANGUAGE_FRENCH },\n { _T(\"Georgian\"), wxLANGUAGE_GEORGIAN },\n { _T(\"German\"), wxLANGUAGE_GERMAN },\n { _T(\"Greek\"), wxLANGUAGE_GREEK },\n { _T(\"Hebrew\"), wxLANGUAGE_HEBREW },\n { _T(\"Hindi\"), wxLANGUAGE_HINDI },\n { _T(\"Hungarian\"), wxLANGUAGE_HUNGARIAN },\n { _T(\"Icelandic\"), wxLANGUAGE_ICELANDIC },\n { _T(\"Italian\"), wxLANGUAGE_ITALIAN },\n { _T(\"Japanese\"), wxLANGUAGE_JAPANESE },\n { _T(\"Korean\"), wxLANGUAGE_KOREAN },\n { _T(\"Kyrgyz\"), wxLANGUAGE_KIRGHIZ },\n { _T(\"Latvian\"), wxLANGUAGE_LATVIAN },\n { _T(\"Lithuanian\"), wxLANGUAGE_LITHUANIAN },\n { _T(\"Mongolian\"), wxLANGUAGE_MONGOLIAN },\n { _T(\"Norwegian Nynorsk\"), wxLANGUAGE_NORWEGIAN_NYNORSK },\n { _T(\"Norwegian Bokmal\"), wxLANGUAGE_NORWEGIAN_BOKMAL },\n { _T(\"Polish\"), wxLANGUAGE_POLISH },\n { _T(\"Portuguese\"), wxLANGUAGE_PORTUGUESE },\n { _T(\"Portuguese (Brazilian)\"), wxLANGUAGE_PORTUGUESE_BRAZILIAN },\n { _T(\"Punjabi\"), wxLANGUAGE_PUNJABI },\n { _T(\"Romanian\"), wxLANGUAGE_ROMANIAN },\n { _T(\"Russian\"), wxLANGUAGE_RUSSIAN },\n { _T(\"Serbian\"), wxLANGUAGE_SERBIAN },\n { _T(\"Slovak\"), wxLANGUAGE_SLOVAK },\n { _T(\"Slovenian\"), wxLANGUAGE_SLOVENIAN },\n { _T(\"Spanish\"), wxLANGUAGE_SPANISH },\n { _T(\"Spanish (Puerto Rico)\"), wxLANGUAGE_SPANISH_PUERTO_RICO },\n { _T(\"Swedish\"), wxLANGUAGE_SWEDISH },\n { _T(\"Turkish\"), wxLANGUAGE_TURKISH },\n { _T(\"Tamil\"), wxLANGUAGE_TAMIL },\n { _T(\"Ukrainian\"), wxLANGUAGE_UKRAINIAN },\n\n { NULL, wxLANGUAGE_UNKNOWN }\n };\n\n wxArrayString arr;\n for (int i = 0; langs[i].name; i++)\n arr.Add(langs[i].name);\n\n int choice = wxGetSingleChoiceIndex(\n _(\"Select your prefered language\"),\n _(\"Language selection\"),\n arr);\n if (choice == -1)\n return wxLANGUAGE_UNKNOWN;\n else\n return langs[choice].code;\n}\n\nvoid ChangeUILanguage()\n{\n wxLanguage lang = ChooseLanguage();\n if (lang == wxLANGUAGE_UNKNOWN)\n return;\n SaveUILanguage(lang);\n wxMessageBox(_(\"You must restart poEdit for this change to take effect.\"),\n _T(\"poEdit\"),\n wxOK | wxCENTRE | wxICON_INFORMATION);\n}\n\n#endif\n<commit_msg>Basque was missing<commit_after>\n\/*\n\n poedit, a wxWindows i18n catalogs editor\n\n ---------------\n chooselang.cpp\n \n Language chooser\n \n (c) Vaclav Slavik, 2003-2005\n\n*\/\n\n#include <wx\/wxprec.h>\n\n#include <wx\/wx.h>\n#include <wx\/config.h>\n\n#include \"chooselang.h\"\n\nstatic void SaveUILanguage(wxLanguage lang)\n{\n if (lang == wxLANGUAGE_UNKNOWN)\n return;\n if (lang == wxLANGUAGE_DEFAULT)\n wxConfig::Get()->Write(_T(\"ui_language\"), _T(\"default\"));\n else\n wxConfig::Get()->Write(_T(\"ui_language\"),\n wxLocale::GetLanguageInfo(lang)->CanonicalName);\n}\n\nwxLanguage GetUILanguage()\n{\n#if defined(__UNIX__) || !wxCHECK_VERSION(2,5,0)\n return wxLANGUAGE_DEFAULT;\n#else\n wxLanguage lang(wxLANGUAGE_DEFAULT);\n wxString lng = wxConfig::Get()->Read(_T(\"ui_language\"));\n if (lng.empty())\n {\n lang = ChooseLanguage();\n if (lang != wxLANGUAGE_UNKNOWN)\n SaveUILanguage(lang);\n else\n lang = wxLANGUAGE_DEFAULT;\n }\n else if (lng != _T(\"default\"))\n {\n const wxLanguageInfo *info = wxLocale::FindLanguageInfo(lng);\n if (info != NULL)\n lang = (wxLanguage)info->Language;\n else\n wxLogError(_(\"Uknown locale code '%s' in registry.\"), lng.c_str());\n }\n return lang;\n#endif\n}\n\n#ifndef __UNIX__\nwxLanguage ChooseLanguage()\n{\n struct LangInfo\n {\n const wxChar *name;\n wxLanguage code;\n };\n\n LangInfo langs[] = \n {\n { _(\"(Use default language)\"), wxLANGUAGE_DEFAULT },\n\n { _T(\"Afrikaans\"), wxLANGUAGE_AFRIKAANS },\n { _T(\"Albanian\"), wxLANGUAGE_ALBANIAN },\n { _T(\"Amharic\"), wxLANGUAGE_AMHARIC },\n { _T(\"Bangla\"), wxLANGUAGE_BENGALI },\n { _T(\"Basque\"), wxLANGUAGE_BASQUE },\n { _T(\"Belarusian\"), wxLANGUAGE_BELARUSIAN },\n { _T(\"Breton\"), wxLANGUAGE_BRETON },\n { _T(\"Bulgarian\"), wxLANGUAGE_BULGARIAN },\n { _T(\"Catalan\"), wxLANGUAGE_CATALAN },\n { _T(\"Chinese (Traditional)\"), wxLANGUAGE_CHINESE_TRADITIONAL },\n { _T(\"Chinese (Simplified)\"), wxLANGUAGE_CHINESE_SIMPLIFIED },\n { _T(\"Croatian\"), wxLANGUAGE_CROATIAN },\n { _T(\"Czech\"), wxLANGUAGE_CZECH },\n { _T(\"Danish\"), wxLANGUAGE_DANISH },\n { _T(\"Dutch\"), wxLANGUAGE_DUTCH },\n { _T(\"English\"), wxLANGUAGE_ENGLISH },\n { _T(\"Estonian\"), wxLANGUAGE_ESTONIAN },\n { _T(\"Esperanto\"), wxLANGUAGE_ESPERANTO },\n { _T(\"Farsi\"), wxLANGUAGE_FARSI },\n { _T(\"French\"), wxLANGUAGE_FRENCH },\n { _T(\"Georgian\"), wxLANGUAGE_GEORGIAN },\n { _T(\"German\"), wxLANGUAGE_GERMAN },\n { _T(\"Greek\"), wxLANGUAGE_GREEK },\n { _T(\"Hebrew\"), wxLANGUAGE_HEBREW },\n { _T(\"Hindi\"), wxLANGUAGE_HINDI },\n { _T(\"Hungarian\"), wxLANGUAGE_HUNGARIAN },\n { _T(\"Icelandic\"), wxLANGUAGE_ICELANDIC },\n { _T(\"Italian\"), wxLANGUAGE_ITALIAN },\n { _T(\"Japanese\"), wxLANGUAGE_JAPANESE },\n { _T(\"Korean\"), wxLANGUAGE_KOREAN },\n { _T(\"Kyrgyz\"), wxLANGUAGE_KIRGHIZ },\n { _T(\"Latvian\"), wxLANGUAGE_LATVIAN },\n { _T(\"Lithuanian\"), wxLANGUAGE_LITHUANIAN },\n { _T(\"Mongolian\"), wxLANGUAGE_MONGOLIAN },\n { _T(\"Norwegian Nynorsk\"), wxLANGUAGE_NORWEGIAN_NYNORSK },\n { _T(\"Norwegian Bokmal\"), wxLANGUAGE_NORWEGIAN_BOKMAL },\n { _T(\"Polish\"), wxLANGUAGE_POLISH },\n { _T(\"Portuguese\"), wxLANGUAGE_PORTUGUESE },\n { _T(\"Portuguese (Brazilian)\"), wxLANGUAGE_PORTUGUESE_BRAZILIAN },\n { _T(\"Punjabi\"), wxLANGUAGE_PUNJABI },\n { _T(\"Romanian\"), wxLANGUAGE_ROMANIAN },\n { _T(\"Russian\"), wxLANGUAGE_RUSSIAN },\n { _T(\"Serbian\"), wxLANGUAGE_SERBIAN },\n { _T(\"Slovak\"), wxLANGUAGE_SLOVAK },\n { _T(\"Slovenian\"), wxLANGUAGE_SLOVENIAN },\n { _T(\"Spanish\"), wxLANGUAGE_SPANISH },\n { _T(\"Spanish (Puerto Rico)\"), wxLANGUAGE_SPANISH_PUERTO_RICO },\n { _T(\"Swedish\"), wxLANGUAGE_SWEDISH },\n { _T(\"Turkish\"), wxLANGUAGE_TURKISH },\n { _T(\"Tamil\"), wxLANGUAGE_TAMIL },\n { _T(\"Ukrainian\"), wxLANGUAGE_UKRAINIAN },\n\n { NULL, wxLANGUAGE_UNKNOWN }\n };\n\n wxArrayString arr;\n for (int i = 0; langs[i].name; i++)\n arr.Add(langs[i].name);\n\n int choice = wxGetSingleChoiceIndex(\n _(\"Select your prefered language\"),\n _(\"Language selection\"),\n arr);\n if (choice == -1)\n return wxLANGUAGE_UNKNOWN;\n else\n return langs[choice].code;\n}\n\nvoid ChangeUILanguage()\n{\n wxLanguage lang = ChooseLanguage();\n if (lang == wxLANGUAGE_UNKNOWN)\n return;\n SaveUILanguage(lang);\n wxMessageBox(_(\"You must restart poEdit for this change to take effect.\"),\n _T(\"poEdit\"),\n wxOK | wxCENTRE | wxICON_INFORMATION);\n}\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>#ifndef DISSENT_MESSAGING_RPC_HANDLER_H_GUARD\n#define DISSENT_MESSAGING_RPC_HANDLER_H_GUARD\n\n#include <QByteArray>\n#include <QDebug>\n#include <QHash>\n#include <QObject>\n#include <QString>\n#include <QSharedPointer>\n\n#include \"Utils\/TimerCallback.hpp\"\n#include \"Utils\/TimerEvent.hpp\"\n\n#include \"ISender.hpp\"\n#include \"ISinkObject.hpp\"\n#include \"Request.hpp\"\n#include \"RequestHandler.hpp\"\n#include \"RequestResponder.hpp\"\n#include \"Response.hpp\"\n#include \"ResponseHandler.hpp\"\n\nnamespace Dissent {\nnamespace Messaging {\n class RequestState;\n\n \/**\n * Rpc mechanism assumes a reliable sending mechanism\n *\/\n class RpcHandler : public ISinkObject {\n Q_OBJECT\n\n public:\n typedef Utils::TimerMethod<RpcHandler, int> TimerCallback;\n static const int TimeoutDelta = 60000;\n\n inline static QSharedPointer<RpcHandler> GetEmpty()\n {\n static QSharedPointer<RpcHandler> handler(new RpcHandler());\n return handler;\n }\n\n \/**\n * The constructor\n *\/\n explicit RpcHandler();\n\n \/**\n * The destructor\n *\/\n virtual ~RpcHandler();\n\n \/**\n * Handle an incoming Rpc request\n * @param from a return path to the requestor\n * @param data serialized request message\n *\/\n virtual void HandleData(const QSharedPointer<ISender> &from,\n const QByteArray &data);\n\n \/**\n * Handle an incoming Rpc request\n * @param from a return path to the requestor\n * @param container deserialized request message\n *\/\n void HandleData(const QSharedPointer<ISender> &from,\n const QVariantList &container);\n\n \/**\n * Send a request\n * @param to the destination for the notification\n * @param method the remote method\n * @param data the input data for that method\n * @returns the id of the request so that the callback can be cancelled\n *\/\n void SendNotification(const QSharedPointer<ISender> &to,\n const QString &method, const QVariant &data);\n\n \/**\n * Send a request\n * @param to the destination for the request\n * @param method the remote method\n * @param data the input data for that method\n * @param callback called when the request is complete\n * @param timeout specifies whether or not to let the request timeout.\n * It is a temporary parameter that will be phased out in the future,\n * all future Rpc Methods should be implemented with potential timeouts\n * in mind.\n * @returns the id of the request so that the callback can be cancelled\n *\/\n int SendRequest(const QSharedPointer<ISender> &to, const QString &method,\n const QVariant &data, const QSharedPointer<ResponseHandler> &callback,\n bool timeout = false);\n\n \/**\n * Register a callback\n * @param name The string to match it with\n * @param cb Method callback to register\n *\/\n bool Register(const QString &name,\n const QSharedPointer<RequestHandler> &cb);\n\n \/**\n * Register a callback into the specified object\n * @param name The string to match it with\n * @param obj with the method name\n *\/\n bool Register(const QString &name, const QObject *obj,\n const char *method);\n\n \/**\n * Unregister a callback\n * @param name name of method to remove\n *\/\n bool Unregister(const QString &name);\n\n \/**\n * Used to cancel handling a request result\n * @param id the id of the request\n *\/\n bool CancelRequest(int id)\n {\n return _requests.remove(id) != 0;\n }\n\n public slots:\n \/**\n * Send a response for a request\n * @param request the original request\n * @param data the data for the remote side\n *\/\n void SendResponse(const Request &request, const QVariant &data);\n\n \/**\n * Send a response for a request\n * @param request the original request\n * @param reason the reason for the failure\n *\/\n void SendFailedResponse(const Request &request,\n Response::ErrorTypes error, const QString &reason,\n const QVariant &error_data = QVariant());\n\n private:\n void StartTimer();\n void Timeout(const int &);\n\n \/**\n * Handle an incoming request\n * @param request the request\n *\/\n void HandleRequest(const Request &request);\n\n \/**\n * Handle an incoming response\n * @param response the response\n *\/\n void HandleResponse(const Response &response);\n\n \/**\n * Returns the _current_id and increments it to the next\n *\/\n inline int IncrementId();\n\n \/**\n * Maps a string to a method to call\n *\/\n QHash<QString, QSharedPointer<RequestHandler> > _callbacks;\n\n \/**\n * Maps id to a callback method to handle responses\n *\/\n QMap<int, QSharedPointer<RequestState> > _requests;\n\n \/**\n * Next request id\n *\/\n int _current_id;\n\n \/**\n * Used to asynchronously respond to requests\n *\/\n QSharedPointer<RequestResponder> _responder;\n\n QSharedPointer<TimerCallback> _timer_callback;\n Utils::TimerEvent _next_call;\n };\n\n class RequestState {\n public:\n RequestState(const QSharedPointer<ISender> sender,\n const QSharedPointer<ResponseHandler> &res_h,\n qint64 start_time, const Utils::TimerEvent &timer, bool timeout) :\n _sender(sender),\n _res_h(res_h),\n _start_time(start_time),\n _timer(timer),\n _timeout(timeout)\n {\n }\n\n ~RequestState()\n {\n _timer.Stop();\n }\n\n inline QSharedPointer<ISender> GetSender() const { return _sender; }\n\n inline QSharedPointer<ResponseHandler> GetResponseHandler() const\n {\n return _res_h;\n }\n\n inline qint64 GetStartTime() const { return _start_time; }\n\n void StopTimer() { _timer.Stop(); }\n\n bool TimeoutCapable() const { return _timeout; }\n\n private:\n QSharedPointer<ISender> _sender;\n QSharedPointer<ResponseHandler> _res_h;\n qint64 _start_time;\n Utils::TimerEvent _timer;\n bool _timeout;\n };\n}\n}\n\n#endif\n<commit_msg>[Messaging] Updated comments<commit_after>#ifndef DISSENT_MESSAGING_RPC_HANDLER_H_GUARD\n#define DISSENT_MESSAGING_RPC_HANDLER_H_GUARD\n\n#include <QByteArray>\n#include <QDebug>\n#include <QHash>\n#include <QObject>\n#include <QString>\n#include <QSharedPointer>\n\n#include \"Utils\/TimerCallback.hpp\"\n#include \"Utils\/TimerEvent.hpp\"\n\n#include \"ISender.hpp\"\n#include \"ISinkObject.hpp\"\n#include \"Request.hpp\"\n#include \"RequestHandler.hpp\"\n#include \"RequestResponder.hpp\"\n#include \"Response.hpp\"\n#include \"ResponseHandler.hpp\"\n\nnamespace Dissent {\nnamespace Messaging {\n class RequestState;\n\n \/**\n * Rpc mechanism assumes a reliable sending mechanism\n *\/\n class RpcHandler : public ISinkObject {\n Q_OBJECT\n\n public:\n typedef Utils::TimerMethod<RpcHandler, int> TimerCallback;\n static const int TimeoutDelta = 60000;\n\n inline static QSharedPointer<RpcHandler> GetEmpty()\n {\n static QSharedPointer<RpcHandler> handler(new RpcHandler());\n return handler;\n }\n\n \/**\n * The constructor\n *\/\n explicit RpcHandler();\n\n \/**\n * The destructor\n *\/\n virtual ~RpcHandler();\n\n \/**\n * Handle an incoming Rpc request\n * @param from a return path to the requestor\n * @param data serialized request message\n *\/\n virtual void HandleData(const QSharedPointer<ISender> &from,\n const QByteArray &data);\n\n \/**\n * Handle an incoming Rpc request\n * @param from a return path to the requestor\n * @param container deserialized request message\n *\/\n void HandleData(const QSharedPointer<ISender> &from,\n const QVariantList &container);\n\n \/**\n * Send a request\n * @param to the destination for the notification\n * @param method the remote method\n * @param data the input data for that method\n * @returns the id of the request so that the callback can be cancelled\n *\/\n void SendNotification(const QSharedPointer<ISender> &to,\n const QString &method, const QVariant &data);\n\n \/**\n * Send a request\n * @param to the destination for the request\n * @param method the remote method\n * @param data the input data for that method\n * @param callback called when the request is complete\n * @param timeout specifies whether or not to let the request timeout.\n * It is a temporary parameter that will be phased out in the future,\n * all future Rpc Methods should be implemented with potential timeouts\n * in mind.\n * @returns the id of the request so that the callback can be cancelled\n *\/\n int SendRequest(const QSharedPointer<ISender> &to, const QString &method,\n const QVariant &data, const QSharedPointer<ResponseHandler> &callback,\n bool timeout = false);\n\n \/**\n * Register a callback\n * @param name The string to match it with\n * @param cb Method callback to register\n *\/\n bool Register(const QString &name,\n const QSharedPointer<RequestHandler> &cb);\n\n \/**\n * Register a callback into the specified object\n * @param name The string to match it with\n * @param obj with the method name\n * @param method name of method\n *\/\n bool Register(const QString &name, const QObject *obj,\n const char *method);\n\n \/**\n * Unregister a callback\n * @param name name of method to remove\n *\/\n bool Unregister(const QString &name);\n\n \/**\n * Used to cancel handling a request result\n * @param id the id of the request\n *\/\n bool CancelRequest(int id)\n {\n return _requests.remove(id) != 0;\n }\n\n public slots:\n \/**\n * Send a response for a request\n * @param request the original request\n * @param data the data for the remote side\n *\/\n void SendResponse(const Request &request, const QVariant &data);\n\n \/**\n * Send a response for a request\n * @param request the original request\n * @param reason the reason for the failure\n *\/\n void SendFailedResponse(const Request &request,\n Response::ErrorTypes error, const QString &reason,\n const QVariant &error_data = QVariant());\n\n private:\n void StartTimer();\n void Timeout(const int &);\n\n \/**\n * Handle an incoming request\n * @param request the request\n *\/\n void HandleRequest(const Request &request);\n\n \/**\n * Handle an incoming response\n * @param response the response\n *\/\n void HandleResponse(const Response &response);\n\n \/**\n * Returns the _current_id and increments it to the next\n *\/\n inline int IncrementId();\n\n \/**\n * Maps a string to a method to call\n *\/\n QHash<QString, QSharedPointer<RequestHandler> > _callbacks;\n\n \/**\n * Maps id to a callback method to handle responses\n *\/\n QMap<int, QSharedPointer<RequestState> > _requests;\n\n \/**\n * Next request id\n *\/\n int _current_id;\n\n \/**\n * Used to asynchronously respond to requests\n *\/\n QSharedPointer<RequestResponder> _responder;\n\n QSharedPointer<TimerCallback> _timer_callback;\n Utils::TimerEvent _next_call;\n };\n\n class RequestState {\n public:\n RequestState(const QSharedPointer<ISender> sender,\n const QSharedPointer<ResponseHandler> &res_h,\n qint64 start_time, const Utils::TimerEvent &timer, bool timeout) :\n _sender(sender),\n _res_h(res_h),\n _start_time(start_time),\n _timer(timer),\n _timeout(timeout)\n {\n }\n\n ~RequestState()\n {\n _timer.Stop();\n }\n\n inline QSharedPointer<ISender> GetSender() const { return _sender; }\n\n inline QSharedPointer<ResponseHandler> GetResponseHandler() const\n {\n return _res_h;\n }\n\n inline qint64 GetStartTime() const { return _start_time; }\n\n void StopTimer() { _timer.Stop(); }\n\n bool TimeoutCapable() const { return _timeout; }\n\n private:\n QSharedPointer<ISender> _sender;\n QSharedPointer<ResponseHandler> _res_h;\n qint64 _start_time;\n Utils::TimerEvent _timer;\n bool _timeout;\n };\n}\n}\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/**\n * This file is part of the CernVM File System.\n *\/\n#include \"helpers.h\"\n\n#ifdef __GLIBC__\n#include <gnu\/libc-version.h>\n#endif\n#include <stdio.h>\n#include <sys\/time.h>\n#include <sys\/types.h>\n#include <utime.h>\n\n\/\/ #include <attr\/xattr.h> \/\/ NOLINT\n\/\/ Necessary because xattr.h does not import sys\/types.h\n\n#include <string>\n#include <vector>\n\n#include \"data_dir_mgmt.h\"\n#include \"garbage_collector.h\"\n#include \"logging.h\"\n#include \"platform.h\"\n#include \"shrinkwrap\/fs_traversal_interface.h\"\n#include \"util\/posix.h\"\n#include \"xattr.h\"\n\n#ifdef __GLIBC__\n #if __GLIBC_MINOR__ < 6\n #warning No lutimes support, glibc >= 2.6 required\n #else\n #define CVMFS_HAS_LUTIMES 1\n #endif\n#else\n #define CVMFS_HAS_LUTIMES 1\n#endif\n\n\nvoid InitialFsOperations(struct fs_traversal_context *ctx) {\n InitializeDataDirectory(ctx);\n InitializeWarningFile(ctx);\n InitializeGarbageCollection(ctx);\n}\n\nvoid FinalizeFsOperations(struct fs_traversal_context *ctx) {\n FinalizeGarbageCollection(ctx);\n}\n\nvoid InitializeWarningFile(struct fs_traversal_context *ctx) {\n const char *warning = WARNING_FILE_NAME;\n FILE *f = fopen(BuildPath(ctx, \"\/\" WARNING_FILE_NAME).c_str(), \"w\");\n if (f != NULL) {\n fwrite(warning, sizeof(char), strlen(warning), f);\n fclose(f);\n } else {\n LogCvmfs(kLogCvmfs, kLogStderr,\n \"Could not write warning file for posix file system!\");\n }\n}\n\nstd::string BuildPath(struct fs_traversal_context *ctx,\n const char *dir) {\n std::string result = ctx->base;\n result += ctx->repo;\n if (dir[0] != '\/') {\n result += \"\/\";\n }\n result += dir;\n return result;\n}\n\nstd::string BuildHiddenPath(struct fs_traversal_context *ctx,\n const char *ident) {\n std::string cur_path = ctx->data;\n cur_path += ident;\n return cur_path;\n}\n\nint PosixSetMeta(const char *path,\n const struct cvmfs_attr *stat_info, bool set_permissions\/* = true*\/) {\n int res = 0;\n if (set_permissions) {\n res = chmod(path, stat_info->st_mode);\n if (res != 0) return -1;\n res = chown(path, stat_info->st_uid, stat_info->st_gid);\n if (res != 0) return -1;\n }\n std::string path_str = std::string(path);\n if (stat_info->cvm_xattrs != NULL) {\n XattrList *xlist = reinterpret_cast<XattrList *>(stat_info->cvm_xattrs);\n if (xlist) {\n std::vector<std::string> v = xlist->ListKeys();\n std::string val;\n if (set_permissions) {\n for (std::vector<std::string>::iterator it = v.begin();\n it != v.end();\n ++it) {\n xlist->Get(*it, &val);\n bool res = platform_lsetxattr(path_str, *it, val);\n if (!res) return -1;\n }\n }\n }\n }\n#ifdef CVMFS_HAS_LUTIMES\n const struct timeval times[2] = {\n {stat_info->mtime, 0},\n {stat_info->mtime, 0}\n };\n res = utimes(path, times);\n if (res != 0) return -1;\n#endif\n return 0;\n}\n\nbool BackupMtimes(std::string path, struct utimbuf *mtimes) {\n \/\/ According to valgrind this is necessary due to struct paddings here...\n struct stat stat_buf;\n int res = stat(path.c_str(), &stat_buf);\n if (res != 0) return false;\n mtimes->actime = stat_buf.st_mtime;\n mtimes->modtime = stat_buf.st_mtime;\n return true;\n}\n<commit_msg>fix typo<commit_after>\/**\n * This file is part of the CernVM File System.\n *\/\n#include \"helpers.h\"\n\n#ifdef __GLIBC__\n#include <gnu\/libc-version.h>\n#endif\n#include <stdio.h>\n#include <sys\/time.h>\n#include <sys\/types.h>\n#include <utime.h>\n\n\/\/ #include <attr\/xattr.h> \/\/ NOLINT\n\/\/ Necessary because xattr.h does not import sys\/types.h\n\n#include <string>\n#include <vector>\n\n#include \"data_dir_mgmt.h\"\n#include \"garbage_collector.h\"\n#include \"logging.h\"\n#include \"platform.h\"\n#include \"shrinkwrap\/fs_traversal_interface.h\"\n#include \"util\/posix.h\"\n#include \"xattr.h\"\n\n#ifdef __GLIBC__\n #if __GLIBC_MINOR__ < 6\n #warning No lutimes support, glibc >= 2.6 required\n #else\n #define CVMFS_HAS_LUTIMES 1\n #endif\n#else\n #define CVMFS_HAS_LUTIMES 1\n#endif\n\n\nvoid InitialFsOperations(struct fs_traversal_context *ctx) {\n InitializeDataDirectory(ctx);\n InitializeWarningFile(ctx);\n InitializeGarbageCollection(ctx);\n}\n\nvoid FinalizeFsOperations(struct fs_traversal_context *ctx) {\n FinalizeGarbageCollection(ctx);\n}\n\nvoid InitializeWarningFile(struct fs_traversal_context *ctx) {\n const char *warning = WARNING_FILE_NAME;\n FILE *f = fopen(BuildPath(ctx, \"\/\" WARNING_FILE_NAME).c_str(), \"w\");\n if (f != NULL) {\n fwrite(warning, sizeof(char), strlen(warning), f);\n fclose(f);\n } else {\n LogCvmfs(kLogCvmfs, kLogStderr,\n \"Could not write warning file for posix file system!\");\n }\n}\n\nstd::string BuildPath(struct fs_traversal_context *ctx,\n const char *dir) {\n std::string result = ctx->base;\n result += ctx->repo;\n if (dir[0] != '\/') {\n result += \"\/\";\n }\n result += dir;\n return result;\n}\n\nstd::string BuildHiddenPath(struct fs_traversal_context *ctx,\n const char *ident) {\n std::string cur_path = ctx->data;\n cur_path += ident;\n return cur_path;\n}\n\nint PosixSetMeta(const char *path,\n const struct cvmfs_attr *stat_info, bool set_permissions\/* = true*\/) {\n int res = 0;\n if (set_permissions) {\n res = chmod(path, stat_info->st_mode);\n if (res != 0) return -1;\n res = chown(path, stat_info->st_uid, stat_info->st_gid);\n if (res != 0) return -1;\n }\n std::string path_str = std::string(path);\n if (stat_info->cvm_xattrs != NULL) {\n XattrList *xlist = reinterpret_cast<XattrList *>(stat_info->cvm_xattrs);\n if (xlist) {\n std::vector<std::string> v = xlist->ListKeys();\n std::string val;\n if (set_permissions) {\n for (std::vector<std::string>::iterator it = v.begin();\n it != v.end();\n ++it) {\n xlist->Get(*it, &val);\n bool res = platform_lsetxattr(path_str, *it, val);\n if (!res) return -1;\n }\n }\n }\n }\n#ifdef CVMFS_HAS_LUTIMES\n const struct timeval times[2] = {\n {stat_info->mtime, 0},\n {stat_info->mtime, 0}\n };\n res = lutimes(path, times);\n if (res != 0) return -1;\n#endif\n return 0;\n}\n\nbool BackupMtimes(std::string path, struct utimbuf *mtimes) {\n \/\/ According to valgrind this is necessary due to struct paddings here...\n struct stat stat_buf;\n int res = stat(path.c_str(), &stat_buf);\n if (res != 0) return false;\n mtimes->actime = stat_buf.st_mtime;\n mtimes->modtime = stat_buf.st_mtime;\n return true;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*********************************************************************************\n *\n * Inviwo - Interactive Visualization Workshop\n *\n * Copyright (c) 2014-2015 Inviwo Foundation\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * 1. Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR\n * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n *********************************************************************************\/\n\n#include <modules\/python3\/pythonincluder.h>\n#include <inviwo\/core\/common\/inviwoapplication.h>\n#include \"pyinviwo.h\"\n\n#include <modules\/python3\/python3module.h>\n\n#include <modules\/python3\/pythonscript.h>\n#include <modules\/python3\/pythonexecutionoutputobservable.h>\n\n#include <modules\/python3\/pythoninterface\/pymodule.h>\n\n#include <modules\/python3\/pyinviwoobserver.h>\n\n#include \"defaultinterface\/pyproperties.h\"\n#include \"defaultinterface\/pycamera.h\"\n#include \"defaultinterface\/pycanvas.h\"\n#include \"defaultinterface\/pylist.h\"\n#include \"defaultinterface\/pyutil.h\"\n#include \"defaultinterface\/pyvolume.h\"\n\nnamespace inviwo {\nstatic PyObject* py_stdout(PyObject* \/*self*\/, PyObject* args);\nclass PyStdOutCatcher : public PyMethod {\npublic:\n virtual std::string getName() const override { return \"ivwPrint\"; }\n virtual std::string getDesc() const override {\n return \" Only for internal use. Redirect std output to python editor widget.\";\n }\n virtual PyCFunction getFunc() override { return py_stdout; }\n};\n\nstatic PyObject* py_stdout(PyObject* \/*self*\/, PyObject* args) {\n char* msg;\n int len;\n int isStderr;\n\n if (!PyArg_ParseTuple(args, \"s#i\", &msg, &len, &isStderr)) {\n LogWarnCustom(\"inviwo.Python.py_print\", \"failed to parse log message\");\n } else {\n if (len != 0) {\n if (!(len == 1 && (msg[0] == '\\n' || msg[0] == '\\r' || msg[0] == '\\0')))\n PythonExecutionOutputObservable::getPtr()->pythonExecutionOutputEvent(\n msg, (isStderr == 0) ? sysstdout : sysstderr);\n }\n }\n\n Py_RETURN_NONE;\n}\n\nPyInviwo::PyInviwo()\n : isInit_(false)\n , inviwoPyModule_(nullptr)\n , inviwoInternalPyModule_(nullptr)\n , mainDict_(nullptr)\n , modulesDict_(nullptr) {\n init(this);\n\n initPythonCInterface();\n}\n\nPyInviwo::~PyInviwo() {\n delete inviwoPyModule_;\n delete inviwoInternalPyModule_;\n}\n\nvoid PyInviwo::registerPyModule(PyModule* pyModule) {\n if (Py_IsInitialized()) {\n struct PyModuleDef moduleDef = {PyModuleDef_HEAD_INIT, pyModule->getModuleName(), nullptr,\n -1, pyModule->getPyMethodDefs()};\n\n PyObject* obj = PyModule_Create(&moduleDef);\n\n if (!obj) {\n LogWarn(\"Failed to init python module '\" << pyModule->getModuleName() << \"' \");\n }\n PyDict_SetItemString(modulesDict_, pyModule->getModuleName(), obj);\n\n pyModule->setPyObject(obj);\n registeredModules_.push_back(pyModule);\n\n for (ObserverSet::reverse_iterator it = observers_->rbegin(); it != observers_->rend();\n ++it) {\n static_cast<PyInviwoObserver*>(*it)->onModuleRegistered(pyModule);\n }\n } else {\n LogError(\"Python environment not initialized\");\n }\n}\n\nvoid PyInviwo::addModulePath(const std::string& path) {\n if (!Py_IsInitialized()) {\n LogWarn(\"addModulePath(): not initialized\");\n return;\n }\n\n std::string pathConv = path;\n replaceInString(pathConv, \"\\\\\", \"\/\");\n std::string runString = \"import sys\\n\";\n runString.append(std::string(\"sys.path.append('\") + pathConv + std::string(\"')\"));\n int ret = PyRun_SimpleString(runString.c_str());\n\n if (ret != 0) LogWarn(\"Failed to add '\" + pathConv + \"' to Python module search path\");\n}\n\nvoid PyInviwo::initPythonCInterface() {\n if (isInit_) return;\n\n isInit_ = true;\n LogInfo(\"Python version: \" + toString(Py_GetVersion()));\n wchar_t programName[] = L\"PyInviwo\";\n Py_SetProgramName(programName);\n#ifdef WIN32\n Py_NoSiteFlag = 1;\n#endif\n Py_InitializeEx(false);\n\n if (!Py_IsInitialized()) {\n LogError(\"Python is not Initialized\");\n return;\n }\n\n PyEval_InitThreads();\n mainDict_ = PyDict_New();\n modulesDict_ = PyImport_GetModuleDict();\n importModule(\"builtins\");\n importModule(\"sys\");\n importModule(\"os\");\n importModule(\"glob\");\n importModule(\"random\");\n\n\n addModulePath(InviwoApplication::getPtr()->getBasePath() + \"\/modules\/python3\/scripts\");\n\n initDefaultInterfaces();\n\n initOutputRedirector();\n}\n\nvoid PyInviwo::importModule(const std::string &moduleName){\n const static std::string __key__ = \"__\";\n char * key = new char[moduleName.size() + 5];\n sprintf(key,\"__%s__\", moduleName.c_str());\n if (PyDict_GetItemString(mainDict_, key) == nullptr) {\n PyObject* pMod = PyImport_ImportModule(moduleName.c_str());\n if (nullptr != pMod) {\n PyDict_SetItemString(mainDict_, key, pMod);\n LogInfo(\"Imported python module: \" << moduleName);\n }\n else{\n LogWarn(\"Failed to import python module: \" << moduleName);\n }\n }\n delete [] key;\n}\n\nvoid PyInviwo::initDefaultInterfaces() {\n inviwoInternalPyModule_ = new PyModule(\"inviwo_internal\");\n inviwoInternalPyModule_->addMethod(new PyStdOutCatcher());\n\n inviwoPyModule_ = new PyModule(\"inviwo\");\n inviwoPyModule_->addMethod(new PySetPropertyValueMethod());\n inviwoPyModule_->addMethod(new PySetPropertyMaxValueMethod());\n inviwoPyModule_->addMethod(new PySetPropertyMinValueMethod());\n inviwoPyModule_->addMethod(new PyGetPropertyValueMethod());\n inviwoPyModule_->addMethod(new PyGetPropertyMaxValueMethod());\n inviwoPyModule_->addMethod(new PyGetPropertyMinValueMethod());\n inviwoPyModule_->addMethod(new PyClickButtonMethod());\n inviwoPyModule_->addMethod(new PySetCameraFocusMethod());\n inviwoPyModule_->addMethod(new PySetCameraUpMethod());\n inviwoPyModule_->addMethod(new PySetCameraPosMethod());\n inviwoPyModule_->addMethod(new PyListPropertiesMethod());\n inviwoPyModule_->addMethod(new PyListProcessorsMethod());\n inviwoPyModule_->addMethod(new PyCanvasCountMethod());\n inviwoPyModule_->addMethod(new PyResizeCanvasMethod());\n inviwoPyModule_->addMethod(new PySnapshotMethod());\n inviwoPyModule_->addMethod(new PySnapshotCanvasMethod());\n inviwoPyModule_->addMethod(new PyGetBasePathMethod());\n inviwoPyModule_->addMethod(new PyGetWorkspaceSavePathMethod());\n inviwoPyModule_->addMethod(new PyGetVolumePathMethod());\n inviwoPyModule_->addMethod(new PyGetDataPathMethod());\n inviwoPyModule_->addMethod(new PyGetImagePathMethod());\n inviwoPyModule_->addMethod(new PyGetModulePathMethod());\n inviwoPyModule_->addMethod(new PyGetTransferFunctionPath());\n inviwoPyModule_->addMethod(new PyGetMemoryUsage());\n inviwoPyModule_->addMethod(new PyClearResourceManage());\n inviwoPyModule_->addMethod(new PyEnableEvaluation());\n inviwoPyModule_->addMethod(new PyDisableEvaluation());\n inviwoPyModule_->addMethod(new PySaveTransferFunction());\n inviwoPyModule_->addMethod(new PyLoadTransferFunction());\n inviwoPyModule_->addMethod(new PyClearTransferfunction());\n inviwoPyModule_->addMethod(new PyAddTransferFunction());\n\n registerPyModule(inviwoPyModule_);\n registerPyModule(inviwoInternalPyModule_);\n}\n\nvoid PyInviwo::initOutputRedirector() {\n std::string directorFileName =\n InviwoApplication::getPtr()->getModuleByType<Python3Module>()->getPath() +\n \"\/scripts\/outputredirector.py\";\n\n if (!filesystem::fileExists(directorFileName)) {\n LogError(\"Could not open outputredirector.py\");\n return;\n }\n\n std::ifstream file(directorFileName.c_str());\n std::string text((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>());\n file.close();\n \n\n PythonScript outputCatcher; \n outputCatcher.setSource(text);\n\n if (!outputCatcher.run(false)) {\n LogWarn(\"Python init script failed to run\");\n }\n}\n\n} \/\/ namespace\n<commit_msg>Python: Removed info message<commit_after>\/*********************************************************************************\n *\n * Inviwo - Interactive Visualization Workshop\n *\n * Copyright (c) 2014-2015 Inviwo Foundation\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * 1. Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR\n * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n *********************************************************************************\/\n\n#include <modules\/python3\/pythonincluder.h>\n#include <inviwo\/core\/common\/inviwoapplication.h>\n#include \"pyinviwo.h\"\n\n#include <modules\/python3\/python3module.h>\n\n#include <modules\/python3\/pythonscript.h>\n#include <modules\/python3\/pythonexecutionoutputobservable.h>\n\n#include <modules\/python3\/pythoninterface\/pymodule.h>\n\n#include <modules\/python3\/pyinviwoobserver.h>\n\n#include \"defaultinterface\/pyproperties.h\"\n#include \"defaultinterface\/pycamera.h\"\n#include \"defaultinterface\/pycanvas.h\"\n#include \"defaultinterface\/pylist.h\"\n#include \"defaultinterface\/pyutil.h\"\n#include \"defaultinterface\/pyvolume.h\"\n\nnamespace inviwo {\nstatic PyObject* py_stdout(PyObject* \/*self*\/, PyObject* args);\nclass PyStdOutCatcher : public PyMethod {\npublic:\n virtual std::string getName() const override { return \"ivwPrint\"; }\n virtual std::string getDesc() const override {\n return \" Only for internal use. Redirect std output to python editor widget.\";\n }\n virtual PyCFunction getFunc() override { return py_stdout; }\n};\n\nstatic PyObject* py_stdout(PyObject* \/*self*\/, PyObject* args) {\n char* msg;\n int len;\n int isStderr;\n\n if (!PyArg_ParseTuple(args, \"s#i\", &msg, &len, &isStderr)) {\n LogWarnCustom(\"inviwo.Python.py_print\", \"failed to parse log message\");\n } else {\n if (len != 0) {\n if (!(len == 1 && (msg[0] == '\\n' || msg[0] == '\\r' || msg[0] == '\\0')))\n PythonExecutionOutputObservable::getPtr()->pythonExecutionOutputEvent(\n msg, (isStderr == 0) ? sysstdout : sysstderr);\n }\n }\n\n Py_RETURN_NONE;\n}\n\nPyInviwo::PyInviwo()\n : isInit_(false)\n , inviwoPyModule_(nullptr)\n , inviwoInternalPyModule_(nullptr)\n , mainDict_(nullptr)\n , modulesDict_(nullptr) {\n init(this);\n\n initPythonCInterface();\n}\n\nPyInviwo::~PyInviwo() {\n delete inviwoPyModule_;\n delete inviwoInternalPyModule_;\n}\n\nvoid PyInviwo::registerPyModule(PyModule* pyModule) {\n if (Py_IsInitialized()) {\n struct PyModuleDef moduleDef = {PyModuleDef_HEAD_INIT, pyModule->getModuleName(), nullptr,\n -1, pyModule->getPyMethodDefs()};\n\n PyObject* obj = PyModule_Create(&moduleDef);\n\n if (!obj) {\n LogWarn(\"Failed to init python module '\" << pyModule->getModuleName() << \"' \");\n }\n PyDict_SetItemString(modulesDict_, pyModule->getModuleName(), obj);\n\n pyModule->setPyObject(obj);\n registeredModules_.push_back(pyModule);\n\n for (ObserverSet::reverse_iterator it = observers_->rbegin(); it != observers_->rend();\n ++it) {\n static_cast<PyInviwoObserver*>(*it)->onModuleRegistered(pyModule);\n }\n } else {\n LogError(\"Python environment not initialized\");\n }\n}\n\nvoid PyInviwo::addModulePath(const std::string& path) {\n if (!Py_IsInitialized()) {\n LogWarn(\"addModulePath(): not initialized\");\n return;\n }\n\n std::string pathConv = path;\n replaceInString(pathConv, \"\\\\\", \"\/\");\n std::string runString = \"import sys\\n\";\n runString.append(std::string(\"sys.path.append('\") + pathConv + std::string(\"')\"));\n int ret = PyRun_SimpleString(runString.c_str());\n\n if (ret != 0) LogWarn(\"Failed to add '\" + pathConv + \"' to Python module search path\");\n}\n\nvoid PyInviwo::initPythonCInterface() {\n if (isInit_) return;\n\n isInit_ = true;\n LogInfo(\"Python version: \" + toString(Py_GetVersion()));\n wchar_t programName[] = L\"PyInviwo\";\n Py_SetProgramName(programName);\n#ifdef WIN32\n Py_NoSiteFlag = 1;\n#endif\n Py_InitializeEx(false);\n\n if (!Py_IsInitialized()) {\n LogError(\"Python is not Initialized\");\n return;\n }\n\n PyEval_InitThreads();\n mainDict_ = PyDict_New();\n modulesDict_ = PyImport_GetModuleDict();\n importModule(\"builtins\");\n importModule(\"sys\");\n importModule(\"os\");\n importModule(\"glob\");\n importModule(\"random\");\n\n\n addModulePath(InviwoApplication::getPtr()->getBasePath() + \"\/modules\/python3\/scripts\");\n\n initDefaultInterfaces();\n\n initOutputRedirector();\n}\n\nvoid PyInviwo::importModule(const std::string &moduleName){\n const static std::string __key__ = \"__\";\n char * key = new char[moduleName.size() + 5];\n sprintf(key,\"__%s__\", moduleName.c_str());\n if (PyDict_GetItemString(mainDict_, key) == nullptr) {\n PyObject* pMod = PyImport_ImportModule(moduleName.c_str());\n if (nullptr != pMod) {\n PyDict_SetItemString(mainDict_, key, pMod);\n }\n else{\n LogWarn(\"Failed to import python module: \" << moduleName);\n }\n }\n delete [] key;\n}\n\nvoid PyInviwo::initDefaultInterfaces() {\n inviwoInternalPyModule_ = new PyModule(\"inviwo_internal\");\n inviwoInternalPyModule_->addMethod(new PyStdOutCatcher());\n\n inviwoPyModule_ = new PyModule(\"inviwo\");\n inviwoPyModule_->addMethod(new PySetPropertyValueMethod());\n inviwoPyModule_->addMethod(new PySetPropertyMaxValueMethod());\n inviwoPyModule_->addMethod(new PySetPropertyMinValueMethod());\n inviwoPyModule_->addMethod(new PyGetPropertyValueMethod());\n inviwoPyModule_->addMethod(new PyGetPropertyMaxValueMethod());\n inviwoPyModule_->addMethod(new PyGetPropertyMinValueMethod());\n inviwoPyModule_->addMethod(new PyClickButtonMethod());\n inviwoPyModule_->addMethod(new PySetCameraFocusMethod());\n inviwoPyModule_->addMethod(new PySetCameraUpMethod());\n inviwoPyModule_->addMethod(new PySetCameraPosMethod());\n inviwoPyModule_->addMethod(new PyListPropertiesMethod());\n inviwoPyModule_->addMethod(new PyListProcessorsMethod());\n inviwoPyModule_->addMethod(new PyCanvasCountMethod());\n inviwoPyModule_->addMethod(new PyResizeCanvasMethod());\n inviwoPyModule_->addMethod(new PySnapshotMethod());\n inviwoPyModule_->addMethod(new PySnapshotCanvasMethod());\n inviwoPyModule_->addMethod(new PyGetBasePathMethod());\n inviwoPyModule_->addMethod(new PyGetWorkspaceSavePathMethod());\n inviwoPyModule_->addMethod(new PyGetVolumePathMethod());\n inviwoPyModule_->addMethod(new PyGetDataPathMethod());\n inviwoPyModule_->addMethod(new PyGetImagePathMethod());\n inviwoPyModule_->addMethod(new PyGetModulePathMethod());\n inviwoPyModule_->addMethod(new PyGetTransferFunctionPath());\n inviwoPyModule_->addMethod(new PyGetMemoryUsage());\n inviwoPyModule_->addMethod(new PyClearResourceManage());\n inviwoPyModule_->addMethod(new PyEnableEvaluation());\n inviwoPyModule_->addMethod(new PyDisableEvaluation());\n inviwoPyModule_->addMethod(new PySaveTransferFunction());\n inviwoPyModule_->addMethod(new PyLoadTransferFunction());\n inviwoPyModule_->addMethod(new PyClearTransferfunction());\n inviwoPyModule_->addMethod(new PyAddTransferFunction());\n\n registerPyModule(inviwoPyModule_);\n registerPyModule(inviwoInternalPyModule_);\n}\n\nvoid PyInviwo::initOutputRedirector() {\n std::string directorFileName =\n InviwoApplication::getPtr()->getModuleByType<Python3Module>()->getPath() +\n \"\/scripts\/outputredirector.py\";\n\n if (!filesystem::fileExists(directorFileName)) {\n LogError(\"Could not open outputredirector.py\");\n return;\n }\n\n std::ifstream file(directorFileName.c_str());\n std::string text((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>());\n file.close();\n \n\n PythonScript outputCatcher; \n outputCatcher.setSource(text);\n\n if (!outputCatcher.run(false)) {\n LogWarn(\"Python init script failed to run\");\n }\n}\n\n} \/\/ namespace\n<|endoftext|>"} {"text":"<commit_before>\/\/ This file is part of Eigen, a lightweight C++ template library\n\/\/ for linear algebra.\n\/\/\n\/\/ Copyright (C) 2006-2008 Benoit Jacob <jacob.benoit.1@gmail.com>\n\/\/\n\/\/ Eigen is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU Lesser General Public\n\/\/ License as published by the Free Software Foundation; either\n\/\/ version 3 of the License, or (at your option) any later version.\n\/\/\n\/\/ Alternatively, you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU General Public License as\n\/\/ published by the Free Software Foundation; either version 2 of\n\/\/ the License, or (at your option) any later version.\n\/\/\n\/\/ Eigen is distributed in the hope that it will be useful, but WITHOUT ANY\n\/\/ WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n\/\/ FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the\n\/\/ GNU General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License and a copy of the GNU General Public License along with\n\/\/ Eigen. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n\n#include \"main.h\"\n#include <Eigen\/Array>\n\ntemplate<typename MatrixType> void product_extra(const MatrixType& m)\n{\n typedef typename MatrixType::Scalar Scalar;\n typedef typename NumTraits<Scalar>::FloatingPoint FloatingPoint;\n typedef Matrix<Scalar, 1, Dynamic> RowVectorType;\n typedef Matrix<Scalar, Dynamic, 1> ColVectorType;\n typedef Matrix<Scalar, Dynamic, Dynamic,\n MatrixType::Flags&RowMajorBit> OtherMajorMatrixType;\n\n int rows = m.rows();\n int cols = m.cols();\n\n MatrixType m1 = MatrixType::Random(rows, cols),\n m2 = MatrixType::Random(rows, cols),\n m3(rows, cols),\n mzero = MatrixType::Zero(rows, cols),\n identity = MatrixType::Identity(rows, rows),\n square = MatrixType::Random(rows, rows),\n res = MatrixType::Random(rows, rows),\n square2 = MatrixType::Random(cols, cols),\n res2 = MatrixType::Random(cols, cols);\n RowVectorType v1 = RowVectorType::Random(rows), vrres(rows);\n ColVectorType vc2 = ColVectorType::Random(cols), vcres(cols);\n OtherMajorMatrixType tm1 = m1;\n\n Scalar s1 = ei_random<Scalar>(),\n s2 = ei_random<Scalar>(),\n s3 = ei_random<Scalar>();\n\n\/\/ int c0 = ei_random<int>(0,cols\/2-1),\n\/\/ c1 = ei_random<int>(cols\/2,cols),\n\/\/ r0 = ei_random<int>(0,rows\/2-1),\n\/\/ r1 = ei_random<int>(rows\/2,rows);\n\n VERIFY_IS_APPROX(m3.noalias() = m1 * m2.adjoint(), m1 * m2.adjoint().eval());\n VERIFY_IS_APPROX(m3.noalias() = m1.adjoint() * square.adjoint(), m1.adjoint().eval() * square.adjoint().eval());\n VERIFY_IS_APPROX(m3.noalias() = m1.adjoint() * m2, m1.adjoint().eval() * m2);\n VERIFY_IS_APPROX(m3.noalias() = (s1 * m1.adjoint()) * m2, (s1 * m1.adjoint()).eval() * m2);\n VERIFY_IS_APPROX(m3.noalias() = (- m1.adjoint() * s1) * (s3 * m2), (- m1.adjoint() * s1).eval() * (s3 * m2).eval());\n VERIFY_IS_APPROX(m3.noalias() = (s2 * m1.adjoint() * s1) * m2, (s2 * m1.adjoint() * s1).eval() * m2);\n VERIFY_IS_APPROX(m3.noalias() = (-m1*s2) * s1*m2.adjoint(), (-m1*s2).eval() * (s1*m2.adjoint()).eval());\n\n \/\/ a very tricky case where a scale factor has to be automatically conjugated:\n VERIFY_IS_APPROX( m1.adjoint() * (s1*m2).conjugate(), (m1.adjoint()).eval() * ((s1*m2).conjugate()).eval());\n\n\n \/\/ test all possible conjugate combinations for the four matrix-vector product cases:\n\n VERIFY_IS_APPROX((-m1.conjugate() * s2) * (s1 * vc2),\n (-m1.conjugate()*s2).eval() * (s1 * vc2).eval());\n VERIFY_IS_APPROX((-m1 * s2) * (s1 * vc2.conjugate()),\n (-m1*s2).eval() * (s1 * vc2.conjugate()).eval());\n VERIFY_IS_APPROX((-m1.conjugate() * s2) * (s1 * vc2.conjugate()),\n (-m1.conjugate()*s2).eval() * (s1 * vc2.conjugate()).eval());\n\n VERIFY_IS_APPROX((s1 * vc2.transpose()) * (-m1.adjoint() * s2),\n (s1 * vc2.transpose()).eval() * (-m1.adjoint()*s2).eval());\n VERIFY_IS_APPROX((s1 * vc2.adjoint()) * (-m1.transpose() * s2),\n (s1 * vc2.adjoint()).eval() * (-m1.transpose()*s2).eval());\n VERIFY_IS_APPROX((s1 * vc2.adjoint()) * (-m1.adjoint() * s2),\n (s1 * vc2.adjoint()).eval() * (-m1.adjoint()*s2).eval());\n\n VERIFY_IS_APPROX((-m1.adjoint() * s2) * (s1 * v1.transpose()),\n (-m1.adjoint()*s2).eval() * (s1 * v1.transpose()).eval());\n VERIFY_IS_APPROX((-m1.transpose() * s2) * (s1 * v1.adjoint()),\n (-m1.transpose()*s2).eval() * (s1 * v1.adjoint()).eval());\n VERIFY_IS_APPROX((-m1.adjoint() * s2) * (s1 * v1.adjoint()),\n (-m1.adjoint()*s2).eval() * (s1 * v1.adjoint()).eval());\n\n VERIFY_IS_APPROX((s1 * v1) * (-m1.conjugate() * s2),\n (s1 * v1).eval() * (-m1.conjugate()*s2).eval());\n VERIFY_IS_APPROX((s1 * v1.conjugate()) * (-m1 * s2),\n (s1 * v1.conjugate()).eval() * (-m1*s2).eval());\n VERIFY_IS_APPROX((s1 * v1.conjugate()) * (-m1.conjugate() * s2),\n (s1 * v1.conjugate()).eval() * (-m1.conjugate()*s2).eval());\n\n VERIFY_IS_APPROX((-m1.adjoint() * s2) * (s1 * v1.adjoint()),\n (-m1.adjoint()*s2).eval() * (s1 * v1.adjoint()).eval());\n\n}\n\nvoid test_product_extra()\n{\n for(int i = 0; i < g_repeat; i++) {\n CALL_SUBTEST( product_extra(MatrixXf(ei_random<int>(1,320), ei_random<int>(1,320))) );\n CALL_SUBTEST( product_extra(MatrixXcf(ei_random<int>(50,50), ei_random<int>(50,50))) );\n CALL_SUBTEST( product_extra(Matrix<std::complex<double>,Dynamic,Dynamic,RowMajor>(ei_random<int>(1,50), ei_random<int>(1,50))) );\n }\n}\n<commit_msg>improve coverage of matrix-vector product<commit_after>\/\/ This file is part of Eigen, a lightweight C++ template library\n\/\/ for linear algebra.\n\/\/\n\/\/ Copyright (C) 2006-2008 Benoit Jacob <jacob.benoit.1@gmail.com>\n\/\/\n\/\/ Eigen is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU Lesser General Public\n\/\/ License as published by the Free Software Foundation; either\n\/\/ version 3 of the License, or (at your option) any later version.\n\/\/\n\/\/ Alternatively, you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU General Public License as\n\/\/ published by the Free Software Foundation; either version 2 of\n\/\/ the License, or (at your option) any later version.\n\/\/\n\/\/ Eigen is distributed in the hope that it will be useful, but WITHOUT ANY\n\/\/ WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n\/\/ FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the\n\/\/ GNU General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License and a copy of the GNU General Public License along with\n\/\/ Eigen. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n\n#include \"main.h\"\n#include <Eigen\/Array>\n\ntemplate<typename MatrixType> void product_extra(const MatrixType& m)\n{\n typedef typename MatrixType::Scalar Scalar;\n typedef typename NumTraits<Scalar>::FloatingPoint FloatingPoint;\n typedef Matrix<Scalar, 1, Dynamic> RowVectorType;\n typedef Matrix<Scalar, Dynamic, 1> ColVectorType;\n typedef Matrix<Scalar, Dynamic, Dynamic,\n MatrixType::Flags&RowMajorBit> OtherMajorMatrixType;\n\n int rows = m.rows();\n int cols = m.cols();\n\n MatrixType m1 = MatrixType::Random(rows, cols),\n m2 = MatrixType::Random(rows, cols),\n m3(rows, cols),\n mzero = MatrixType::Zero(rows, cols),\n identity = MatrixType::Identity(rows, rows),\n square = MatrixType::Random(rows, rows),\n res = MatrixType::Random(rows, rows),\n square2 = MatrixType::Random(cols, cols),\n res2 = MatrixType::Random(cols, cols);\n RowVectorType v1 = RowVectorType::Random(rows), vrres(rows);\n ColVectorType vc2 = ColVectorType::Random(cols), vcres(cols);\n OtherMajorMatrixType tm1 = m1;\n\n Scalar s1 = ei_random<Scalar>(),\n s2 = ei_random<Scalar>(),\n s3 = ei_random<Scalar>();\n\n\/\/ int c0 = ei_random<int>(0,cols\/2-1),\n\/\/ c1 = ei_random<int>(cols\/2,cols),\n\/\/ r0 = ei_random<int>(0,rows\/2-1),\n\/\/ r1 = ei_random<int>(rows\/2,rows);\n\n VERIFY_IS_APPROX(m3.noalias() = m1 * m2.adjoint(), m1 * m2.adjoint().eval());\n VERIFY_IS_APPROX(m3.noalias() = m1.adjoint() * square.adjoint(), m1.adjoint().eval() * square.adjoint().eval());\n VERIFY_IS_APPROX(m3.noalias() = m1.adjoint() * m2, m1.adjoint().eval() * m2);\n VERIFY_IS_APPROX(m3.noalias() = (s1 * m1.adjoint()) * m2, (s1 * m1.adjoint()).eval() * m2);\n VERIFY_IS_APPROX(m3.noalias() = (- m1.adjoint() * s1) * (s3 * m2), (- m1.adjoint() * s1).eval() * (s3 * m2).eval());\n VERIFY_IS_APPROX(m3.noalias() = (s2 * m1.adjoint() * s1) * m2, (s2 * m1.adjoint() * s1).eval() * m2);\n VERIFY_IS_APPROX(m3.noalias() = (-m1*s2) * s1*m2.adjoint(), (-m1*s2).eval() * (s1*m2.adjoint()).eval());\n\n \/\/ a very tricky case where a scale factor has to be automatically conjugated:\n VERIFY_IS_APPROX( m1.adjoint() * (s1*m2).conjugate(), (m1.adjoint()).eval() * ((s1*m2).conjugate()).eval());\n\n\n \/\/ test all possible conjugate combinations for the four matrix-vector product cases:\n\n VERIFY_IS_APPROX((-m1.conjugate() * s2) * (s1 * vc2),\n (-m1.conjugate()*s2).eval() * (s1 * vc2).eval());\n VERIFY_IS_APPROX((-m1 * s2) * (s1 * vc2.conjugate()),\n (-m1*s2).eval() * (s1 * vc2.conjugate()).eval());\n VERIFY_IS_APPROX((-m1.conjugate() * s2) * (s1 * vc2.conjugate()),\n (-m1.conjugate()*s2).eval() * (s1 * vc2.conjugate()).eval());\n\n VERIFY_IS_APPROX((s1 * vc2.transpose()) * (-m1.adjoint() * s2),\n (s1 * vc2.transpose()).eval() * (-m1.adjoint()*s2).eval());\n VERIFY_IS_APPROX((s1 * vc2.adjoint()) * (-m1.transpose() * s2),\n (s1 * vc2.adjoint()).eval() * (-m1.transpose()*s2).eval());\n VERIFY_IS_APPROX((s1 * vc2.adjoint()) * (-m1.adjoint() * s2),\n (s1 * vc2.adjoint()).eval() * (-m1.adjoint()*s2).eval());\n\n VERIFY_IS_APPROX((-m1.adjoint() * s2) * (s1 * v1.transpose()),\n (-m1.adjoint()*s2).eval() * (s1 * v1.transpose()).eval());\n VERIFY_IS_APPROX((-m1.transpose() * s2) * (s1 * v1.adjoint()),\n (-m1.transpose()*s2).eval() * (s1 * v1.adjoint()).eval());\n VERIFY_IS_APPROX((-m1.adjoint() * s2) * (s1 * v1.adjoint()),\n (-m1.adjoint()*s2).eval() * (s1 * v1.adjoint()).eval());\n\n VERIFY_IS_APPROX((s1 * v1) * (-m1.conjugate() * s2),\n (s1 * v1).eval() * (-m1.conjugate()*s2).eval());\n VERIFY_IS_APPROX((s1 * v1.conjugate()) * (-m1 * s2),\n (s1 * v1.conjugate()).eval() * (-m1*s2).eval());\n VERIFY_IS_APPROX((s1 * v1.conjugate()) * (-m1.conjugate() * s2),\n (s1 * v1.conjugate()).eval() * (-m1.conjugate()*s2).eval());\n\n VERIFY_IS_APPROX((-m1.adjoint() * s2) * (s1 * v1.adjoint()),\n (-m1.adjoint()*s2).eval() * (s1 * v1.adjoint()).eval());\n\n \/\/ test the vector-matrix product with non aligned starts\n int i = ei_random<int>(0,m1.rows()-2);\n int j = ei_random<int>(0,m1.cols()-2);\n int r = ei_random<int>(1,m1.rows()-i);\n int c = ei_random<int>(1,m1.cols()-j);\n int i2 = ei_random<int>(0,m1.rows()-1);\n int j2 = ei_random<int>(0,m1.cols()-1);\n\n VERIFY_IS_APPROX(m1.col(j2).adjoint() * m1.block(0,j,m1.rows(),c), m1.col(j2).adjoint().eval() * m1.block(0,j,m1.rows(),c).eval());\n VERIFY_IS_APPROX(m1.block(i,0,r,m1.cols()) * m1.row(i2).adjoint(), m1.block(i,0,r,m1.cols()).eval() * m1.row(i2).adjoint().eval());\n\n}\n\nvoid test_product_extra()\n{\n for(int i = 0; i < g_repeat; i++) {\n CALL_SUBTEST( product_extra(MatrixXf(ei_random<int>(2,320), ei_random<int>(2,320))) );\n CALL_SUBTEST( product_extra(MatrixXcf(ei_random<int>(50,50), ei_random<int>(50,50))) );\n CALL_SUBTEST( product_extra(Matrix<std::complex<double>,Dynamic,Dynamic,RowMajor>(ei_random<int>(2,50), ei_random<int>(2,50))) );\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n OpenDeck MIDI platform firmware\n Copyright (C) 2015-2018 Igor Petrovic\n\n This program is free software: you can redistribute it and\/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation, either version 3 of the License, or\n (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n*\/\n\n#include \"board\/Board.h\"\n#include \"interface\/Interface.h\"\n#include \"Version.h\"\n#include \"interface\/midi\/Handlers.h\"\n\nMIDI midi;\nbool processingEnabled;\nmidiClockStatus_t midiClockStatus;\n\nvoid init()\n{\n board.init();\n database.init();\n sysEx.init();\n\n #ifdef DIN_MIDI_SUPPORTED\n if (database.read(DB_BLOCK_MIDI, dbSection_midi_feature, midiFeatureDinEnabled))\n {\n setupMIDIoverUART(UART_MIDI_CHANNEL);\n\n \/\/use recursive parsing when merging is active\n if (database.read(DB_BLOCK_MIDI, dbSection_midi_feature, midiFeatureMergeEnabled))\n midi.useRecursiveParsing(true);\n else\n midi.useRecursiveParsing(false);\n }\n #endif\n\n \/\/enable uart-to-usb link when usb isn't supported directly\n #ifndef USB_SUPPORTED\n setupMIDIoverUART_OD(UART_USB_LINK_CHANNEL);\n #endif\n\n midi.setInputChannel(MIDI_CHANNEL_OMNI);\n midi.setNoteOffMode((noteOffType_t)database.read(DB_BLOCK_MIDI, dbSection_midi_feature, midiFeatureStandardNoteOff));\n midi.setRunningStatusState(database.read(DB_BLOCK_MIDI, dbSection_midi_feature, midiFeatureRunningStatus));\n midi.setChannelSendZeroStart(true);\n\n board.ledFlashStartup(board.checkNewRevision());\n\n \/\/enable global interrupts\n sei();\n\n #ifdef LEDS_SUPPORTED\n leds.init();\n #endif\n\n #ifdef DISPLAY_SUPPORTED\n if (database.read(DB_BLOCK_DISPLAY, dbSection_display_features, displayFeatureEnable))\n {\n if (display.init((displayController_t)database.read(DB_BLOCK_DISPLAY, dbSection_display_hw, displayHwController), (displayResolution_t)database.read(DB_BLOCK_DISPLAY, dbSection_display_hw, displayHwResolution)))\n {\n display.setDirectWriteState(true);\n\n if (database.read(DB_BLOCK_DISPLAY, dbSection_display_features, displayFeatureWelcomeMsg))\n display.displayWelcomeMessage();\n\n if (database.read(DB_BLOCK_DISPLAY, dbSection_display_features, displayFeatureVInfoMsg))\n display.displayVinfo(false);\n\n display.setDirectWriteState(false);\n\n display.displayHome();\n display.setRetentionState(database.read(DB_BLOCK_DISPLAY, dbSection_display_features, displayFeatureMIDIeventRetention));\n display.setRetentionTime(database.read(DB_BLOCK_DISPLAY, dbSection_display_features, displayFeatureMIDIeventTime) * 1000);\n display.setAlternateNoteDisplay(database.read(DB_BLOCK_DISPLAY, dbSection_display_features, displayFeatureMIDInotesAlternate));\n }\n }\n #endif\n\n processingEnabled = true;\n midiClockStatus = midiClockStop;\n\n #ifdef BOARD_BERGAMOT\n touchscreen.init(ts_sdw);\n touchscreen.setPage(1);\n #endif\n}\n\nint main()\n{\n init();\n\n #ifdef USB_SUPPORTED\n \/\/wait a bit before checking if usb is connected\n wait_ms(1500);\n\n if (board.isUSBconnected())\n {\n \/\/this board is connected to usb, check if din is enabled\n if (database.read(DB_BLOCK_MIDI, dbSection_midi_feature, midiFeatureDinEnabled) && !database.read(DB_BLOCK_MIDI, dbSection_midi_feature, midiFeatureMergeEnabled))\n {\n \/\/start daisy-chain auto-config\n \/\/format message as special request so that it's parsed on other boards\n sysExParameter_t daisyChainMessage[] =\n {\n SYSEX_CR_DAISY_CHAIN_MASTER,\n };\n\n sysEx.sendCustomMessage(usbMessage.sysexArray, daisyChainMessage, 1, false);\n }\n }\n #endif\n\n while(1)\n {\n \/\/note: mega\/uno\n \/\/\"fake\" usbInterface - din data is stored as usb data so use usb callback to read the usb\n \/\/packet stored in midi object\n if (midi.read(usbInterface))\n {\n \/\/new message on usb\n midiMessageType_t messageType = midi.getType(usbInterface);\n #if defined(LEDS_SUPPORTED) || defined(DISPLAY_SUPPORTED)\n uint8_t data1 = midi.getData1(usbInterface);\n uint8_t data2 = midi.getData2(usbInterface);\n uint8_t channel = midi.getChannel(usbInterface);\n #endif\n\n switch(messageType)\n {\n case midiMessageSystemExclusive:\n \/\/don't handle sysex on slave boards in daisy-chain setup\n #ifdef BOARD_OPEN_DECK\n if (board.isUSBconnected())\n #endif\n sysEx.handleMessage(midi.getSysExArray(usbInterface), midi.getSysExArrayLength(usbInterface));\n break;\n\n case midiMessageNoteOn:\n case midiMessageNoteOff:\n case midiMessageControlChange:\n case midiMessageProgramChange:\n #if defined(LEDS_SUPPORTED) || defined(DISPLAY_SUPPORTED)\n if (messageType == midiMessageNoteOff)\n data2 = 0;\n #endif\n #ifdef LEDS_SUPPORTED\n leds.midiToState(messageType, data1, data2, channel);\n #endif\n #ifdef DISPLAY_SUPPORTED\n display.displayMIDIevent(displayEventIn, midiMessageNoteOn_display, data1, data2, channel+1);\n #endif\n break;\n\n case midiMessageClock:\n midiClockStatus = midiClockChange;\n break;\n\n case midiMessageStart:\n midiClockStatus = midiClockReset;\n break;\n\n case midiMessageStop:\n midiClockStatus = midiClockStop;\n break;\n\n default:\n break;\n }\n }\n\n #ifdef BOARD_OPEN_DECK\n if (database.read(DB_BLOCK_MIDI, dbSection_midi_feature, midiFeatureDinEnabled))\n {\n \/\/check for incoming MIDI messages on UART\n \/\/merging is supported on opendeck board only at the moment\n if (!database.read(DB_BLOCK_MIDI, dbSection_midi_feature, midiFeatureMergeEnabled))\n {\n \/\/daisy-chained opendeck boards\n if (!board.getUARTloopbackState(UART_MIDI_CHANNEL))\n {\n if (!board.isUSBconnected())\n {\n \/\/in this case, board is slave, check only for sysex from master\n if (midi.read(dinInterface))\n {\n midiMessageType_t messageType = midi.getType(dinInterface);\n\n if (messageType == midiMessageSystemExclusive)\n {\n sysEx.handleMessage(midi.getSysExArray(dinInterface), midi.getSysExArrayLength(dinInterface));\n }\n }\n }\n else\n {\n \/\/master opendeck - dump everything from MIDI in to USB MIDI out\n if (uartReadMIDI_OD(UART_MIDI_CHANNEL))\n Board::usbWriteMIDI(usbMIDIpacket);\n }\n }\n else\n {\n \/\/all incoming data is forwarded automatically (inner slave)\n }\n }\n else\n {\n switch(database.read(DB_BLOCK_MIDI, dbSection_midi_merge, midiMergeToInterface))\n {\n case midiMergeToInterfaceUSB:\n \/\/dump everything from DIN MIDI in to USB MIDI out\n midi.read(dinInterface, THRU_FULL_USB);\n break;\n\n default:\n break;\n }\n }\n }\n #endif\n\n if (processingEnabled)\n {\n digitalInput.update();\n analog.update();\n #ifdef LEDS_SUPPORTED\n leds.update();\n #endif\n\n #ifdef DISPLAY_SUPPORTED\n display.update();\n #endif\n\n #ifdef TOUCHSCREEN_SUPPORTED\n touchscreen.update();\n #endif\n }\n }\n}\n<commit_msg>fix incorrect uart init order<commit_after>\/*\n OpenDeck MIDI platform firmware\n Copyright (C) 2015-2018 Igor Petrovic\n\n This program is free software: you can redistribute it and\/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation, either version 3 of the License, or\n (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n*\/\n\n#include \"board\/Board.h\"\n#include \"interface\/Interface.h\"\n#include \"Version.h\"\n#include \"interface\/midi\/Handlers.h\"\n\nMIDI midi;\nbool processingEnabled;\nmidiClockStatus_t midiClockStatus;\n\nvoid init()\n{\n board.init();\n database.init();\n sysEx.init();\n\n \/\/enable uart-to-usb link when usb isn't supported directly\n #ifndef USB_SUPPORTED\n setupMIDIoverUART_OD(UART_USB_LINK_CHANNEL);\n #endif\n\n #ifdef DIN_MIDI_SUPPORTED\n if (database.read(DB_BLOCK_MIDI, dbSection_midi_feature, midiFeatureDinEnabled))\n {\n setupMIDIoverUART(UART_MIDI_CHANNEL);\n\n \/\/use recursive parsing when merging is active\n if (database.read(DB_BLOCK_MIDI, dbSection_midi_feature, midiFeatureMergeEnabled))\n midi.useRecursiveParsing(true);\n else\n midi.useRecursiveParsing(false);\n }\n #endif\n\n midi.setInputChannel(MIDI_CHANNEL_OMNI);\n midi.setNoteOffMode((noteOffType_t)database.read(DB_BLOCK_MIDI, dbSection_midi_feature, midiFeatureStandardNoteOff));\n midi.setRunningStatusState(database.read(DB_BLOCK_MIDI, dbSection_midi_feature, midiFeatureRunningStatus));\n midi.setChannelSendZeroStart(true);\n\n board.ledFlashStartup(board.checkNewRevision());\n\n \/\/enable global interrupts\n sei();\n\n #ifdef LEDS_SUPPORTED\n leds.init();\n #endif\n\n #ifdef DISPLAY_SUPPORTED\n if (database.read(DB_BLOCK_DISPLAY, dbSection_display_features, displayFeatureEnable))\n {\n if (display.init((displayController_t)database.read(DB_BLOCK_DISPLAY, dbSection_display_hw, displayHwController), (displayResolution_t)database.read(DB_BLOCK_DISPLAY, dbSection_display_hw, displayHwResolution)))\n {\n display.setDirectWriteState(true);\n\n if (database.read(DB_BLOCK_DISPLAY, dbSection_display_features, displayFeatureWelcomeMsg))\n display.displayWelcomeMessage();\n\n if (database.read(DB_BLOCK_DISPLAY, dbSection_display_features, displayFeatureVInfoMsg))\n display.displayVinfo(false);\n\n display.setDirectWriteState(false);\n\n display.displayHome();\n display.setRetentionState(database.read(DB_BLOCK_DISPLAY, dbSection_display_features, displayFeatureMIDIeventRetention));\n display.setRetentionTime(database.read(DB_BLOCK_DISPLAY, dbSection_display_features, displayFeatureMIDIeventTime) * 1000);\n display.setAlternateNoteDisplay(database.read(DB_BLOCK_DISPLAY, dbSection_display_features, displayFeatureMIDInotesAlternate));\n }\n }\n #endif\n\n processingEnabled = true;\n midiClockStatus = midiClockStop;\n\n #ifdef BOARD_BERGAMOT\n touchscreen.init(ts_sdw);\n touchscreen.setPage(1);\n #endif\n}\n\nint main()\n{\n init();\n\n #ifdef USB_SUPPORTED\n \/\/wait a bit before checking if usb is connected\n wait_ms(1500);\n\n if (board.isUSBconnected())\n {\n \/\/this board is connected to usb, check if din is enabled\n if (database.read(DB_BLOCK_MIDI, dbSection_midi_feature, midiFeatureDinEnabled) && !database.read(DB_BLOCK_MIDI, dbSection_midi_feature, midiFeatureMergeEnabled))\n {\n \/\/start daisy-chain auto-config\n \/\/format message as special request so that it's parsed on other boards\n sysExParameter_t daisyChainMessage[] =\n {\n SYSEX_CR_DAISY_CHAIN_MASTER,\n };\n\n sysEx.sendCustomMessage(usbMessage.sysexArray, daisyChainMessage, 1, false);\n }\n }\n #endif\n\n while(1)\n {\n \/\/note: mega\/uno\n \/\/\"fake\" usbInterface - din data is stored as usb data so use usb callback to read the usb\n \/\/packet stored in midi object\n if (midi.read(usbInterface))\n {\n \/\/new message on usb\n midiMessageType_t messageType = midi.getType(usbInterface);\n #if defined(LEDS_SUPPORTED) || defined(DISPLAY_SUPPORTED)\n uint8_t data1 = midi.getData1(usbInterface);\n uint8_t data2 = midi.getData2(usbInterface);\n uint8_t channel = midi.getChannel(usbInterface);\n #endif\n\n switch(messageType)\n {\n case midiMessageSystemExclusive:\n \/\/don't handle sysex on slave boards in daisy-chain setup\n #ifdef BOARD_OPEN_DECK\n if (board.isUSBconnected())\n #endif\n sysEx.handleMessage(midi.getSysExArray(usbInterface), midi.getSysExArrayLength(usbInterface));\n break;\n\n case midiMessageNoteOn:\n case midiMessageNoteOff:\n case midiMessageControlChange:\n case midiMessageProgramChange:\n #if defined(LEDS_SUPPORTED) || defined(DISPLAY_SUPPORTED)\n if (messageType == midiMessageNoteOff)\n data2 = 0;\n #endif\n #ifdef LEDS_SUPPORTED\n leds.midiToState(messageType, data1, data2, channel);\n #endif\n #ifdef DISPLAY_SUPPORTED\n display.displayMIDIevent(displayEventIn, midiMessageNoteOn_display, data1, data2, channel+1);\n #endif\n break;\n\n case midiMessageClock:\n midiClockStatus = midiClockChange;\n break;\n\n case midiMessageStart:\n midiClockStatus = midiClockReset;\n break;\n\n case midiMessageStop:\n midiClockStatus = midiClockStop;\n break;\n\n default:\n break;\n }\n }\n\n #ifdef BOARD_OPEN_DECK\n if (database.read(DB_BLOCK_MIDI, dbSection_midi_feature, midiFeatureDinEnabled))\n {\n \/\/check for incoming MIDI messages on UART\n \/\/merging is supported on opendeck board only at the moment\n if (!database.read(DB_BLOCK_MIDI, dbSection_midi_feature, midiFeatureMergeEnabled))\n {\n \/\/daisy-chained opendeck boards\n if (!board.getUARTloopbackState(UART_MIDI_CHANNEL))\n {\n if (!board.isUSBconnected())\n {\n \/\/in this case, board is slave, check only for sysex from master\n if (midi.read(dinInterface))\n {\n midiMessageType_t messageType = midi.getType(dinInterface);\n\n if (messageType == midiMessageSystemExclusive)\n {\n sysEx.handleMessage(midi.getSysExArray(dinInterface), midi.getSysExArrayLength(dinInterface));\n }\n }\n }\n else\n {\n \/\/master opendeck - dump everything from MIDI in to USB MIDI out\n if (uartReadMIDI_OD(UART_MIDI_CHANNEL))\n Board::usbWriteMIDI(usbMIDIpacket);\n }\n }\n else\n {\n \/\/all incoming data is forwarded automatically (inner slave)\n }\n }\n else\n {\n switch(database.read(DB_BLOCK_MIDI, dbSection_midi_merge, midiMergeToInterface))\n {\n case midiMergeToInterfaceUSB:\n \/\/dump everything from DIN MIDI in to USB MIDI out\n midi.read(dinInterface, THRU_FULL_USB);\n break;\n\n default:\n break;\n }\n }\n }\n #endif\n\n if (processingEnabled)\n {\n digitalInput.update();\n analog.update();\n #ifdef LEDS_SUPPORTED\n leds.update();\n #endif\n\n #ifdef DISPLAY_SUPPORTED\n display.update();\n #endif\n\n #ifdef TOUCHSCREEN_SUPPORTED\n touchscreen.update();\n #endif\n }\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 2006 The Regents of The University of Michigan\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met: redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer;\n * redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution;\n * neither the name of the copyright holders nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n * Authors: Steve Reinhardt\n * Kevin Lim\n *\/\n\n#ifndef __ARCH_ALPHA_INTERRUPT_HH__\n#define __ARCH_ALPHA_INTERRUPT_HH__\n\n#include \"arch\/alpha\/faults.hh\"\n#include \"arch\/alpha\/isa_traits.hh\"\n#include \"cpu\/thread_context.hh\"\n\nnamespace AlphaISA\n{\n class Interrupts\n {\n protected:\n uint64_t interrupts[NumInterruptLevels];\n uint64_t intstatus;\n\n public:\n Interrupts()\n {\n memset(interrupts, 0, sizeof(interrupts));\n intstatus = 0;\n newInfoSet = false;\n }\n\n void post(int int_num, int index)\n {\n DPRINTF(Interrupt, \"Interrupt %d:%d posted\\n\", int_num, index);\n\n if (int_num < 0 || int_num >= NumInterruptLevels)\n panic(\"int_num out of bounds\\n\");\n\n if (index < 0 || index >= sizeof(uint64_t) * 8)\n panic(\"int_num out of bounds\\n\");\n\n interrupts[int_num] |= 1 << index;\n intstatus |= (ULL(1) << int_num);\n }\n\n void clear(int int_num, int index)\n {\n DPRINTF(Interrupt, \"Interrupt %d:%d cleared\\n\", int_num, index);\n\n if (int_num < 0 || int_num >= TheISA::NumInterruptLevels)\n panic(\"int_num out of bounds\\n\");\n\n if (index < 0 || index >= sizeof(uint64_t) * 8)\n panic(\"int_num out of bounds\\n\");\n\n interrupts[int_num] &= ~(1 << index);\n if (interrupts[int_num] == 0)\n intstatus &= ~(ULL(1) << int_num);\n }\n\n void clear_all()\n {\n DPRINTF(Interrupt, \"Interrupts all cleared\\n\");\n\n memset(interrupts, 0, sizeof(interrupts));\n intstatus = 0;\n }\n\n void serialize(std::ostream &os)\n {\n SERIALIZE_ARRAY(interrupts, NumInterruptLevels);\n SERIALIZE_SCALAR(intstatus);\n }\n\n void unserialize(Checkpoint *cp, const std::string §ion)\n {\n UNSERIALIZE_ARRAY(interrupts, NumInterruptLevels);\n UNSERIALIZE_SCALAR(intstatus);\n }\n\n bool check_interrupts(ThreadContext * tc) const\n {\n return (intstatus != 0) && !(tc->readPC() & 0x3);\n }\n\n Fault getInterrupt(ThreadContext * tc)\n {\n int ipl = 0;\n int summary = 0;\n\n if (tc->readMiscReg(IPR_ASTRR))\n panic(\"asynchronous traps not implemented\\n\");\n\n if (tc->readMiscReg(IPR_SIRR)) {\n for (int i = INTLEVEL_SOFTWARE_MIN;\n i < INTLEVEL_SOFTWARE_MAX; i++) {\n if (tc->readMiscReg(IPR_SIRR) & (ULL(1) << i)) {\n \/\/ See table 4-19 of 21164 hardware reference\n ipl = (i - INTLEVEL_SOFTWARE_MIN) + 1;\n summary |= (ULL(1) << i);\n }\n }\n }\n\n uint64_t interrupts = intstatus;\n if (interrupts) {\n for (int i = INTLEVEL_EXTERNAL_MIN;\n i < INTLEVEL_EXTERNAL_MAX; i++) {\n if (interrupts & (ULL(1) << i)) {\n \/\/ See table 4-19 of 21164 hardware reference\n ipl = i;\n summary |= (ULL(1) << i);\n }\n }\n }\n\n if (ipl && ipl > tc->readMiscReg(IPR_IPLR)) {\n\/\/ assert(!newInfoSet);\n newIpl = ipl;\n newSummary = newSummary;\n newInfoSet = true;\n DPRINTF(Flow, \"Interrupt! IPLR=%d ipl=%d summary=%x\\n\",\n tc->readMiscReg(IPR_IPLR), ipl, summary);\n\n return new InterruptFault;\n } else {\n return NoFault;\n }\n }\n\n void updateIntrInfo(ThreadContext *tc)\n {\n assert(newInfoSet);\n tc->setMiscReg(IPR_ISR, newSummary);\n tc->setMiscReg(IPR_INTID, newIpl);\n newInfoSet = false;\n }\n\n private:\n bool newInfoSet;\n int newIpl;\n int newSummary;\n };\n}\n\n#endif\n\n<commit_msg>Fix typo.<commit_after>\/*\n * Copyright (c) 2006 The Regents of The University of Michigan\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met: redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer;\n * redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution;\n * neither the name of the copyright holders nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n * Authors: Steve Reinhardt\n * Kevin Lim\n *\/\n\n#ifndef __ARCH_ALPHA_INTERRUPT_HH__\n#define __ARCH_ALPHA_INTERRUPT_HH__\n\n#include \"arch\/alpha\/faults.hh\"\n#include \"arch\/alpha\/isa_traits.hh\"\n#include \"cpu\/thread_context.hh\"\n\nnamespace AlphaISA\n{\n class Interrupts\n {\n protected:\n uint64_t interrupts[NumInterruptLevels];\n uint64_t intstatus;\n\n public:\n Interrupts()\n {\n memset(interrupts, 0, sizeof(interrupts));\n intstatus = 0;\n newInfoSet = false;\n }\n\n void post(int int_num, int index)\n {\n DPRINTF(Interrupt, \"Interrupt %d:%d posted\\n\", int_num, index);\n\n if (int_num < 0 || int_num >= NumInterruptLevels)\n panic(\"int_num out of bounds\\n\");\n\n if (index < 0 || index >= sizeof(uint64_t) * 8)\n panic(\"int_num out of bounds\\n\");\n\n interrupts[int_num] |= 1 << index;\n intstatus |= (ULL(1) << int_num);\n }\n\n void clear(int int_num, int index)\n {\n DPRINTF(Interrupt, \"Interrupt %d:%d cleared\\n\", int_num, index);\n\n if (int_num < 0 || int_num >= TheISA::NumInterruptLevels)\n panic(\"int_num out of bounds\\n\");\n\n if (index < 0 || index >= sizeof(uint64_t) * 8)\n panic(\"int_num out of bounds\\n\");\n\n interrupts[int_num] &= ~(1 << index);\n if (interrupts[int_num] == 0)\n intstatus &= ~(ULL(1) << int_num);\n }\n\n void clear_all()\n {\n DPRINTF(Interrupt, \"Interrupts all cleared\\n\");\n\n memset(interrupts, 0, sizeof(interrupts));\n intstatus = 0;\n }\n\n void serialize(std::ostream &os)\n {\n SERIALIZE_ARRAY(interrupts, NumInterruptLevels);\n SERIALIZE_SCALAR(intstatus);\n }\n\n void unserialize(Checkpoint *cp, const std::string §ion)\n {\n UNSERIALIZE_ARRAY(interrupts, NumInterruptLevels);\n UNSERIALIZE_SCALAR(intstatus);\n }\n\n bool check_interrupts(ThreadContext * tc) const\n {\n return (intstatus != 0) && !(tc->readPC() & 0x3);\n }\n\n Fault getInterrupt(ThreadContext * tc)\n {\n int ipl = 0;\n int summary = 0;\n\n if (tc->readMiscReg(IPR_ASTRR))\n panic(\"asynchronous traps not implemented\\n\");\n\n if (tc->readMiscReg(IPR_SIRR)) {\n for (int i = INTLEVEL_SOFTWARE_MIN;\n i < INTLEVEL_SOFTWARE_MAX; i++) {\n if (tc->readMiscReg(IPR_SIRR) & (ULL(1) << i)) {\n \/\/ See table 4-19 of 21164 hardware reference\n ipl = (i - INTLEVEL_SOFTWARE_MIN) + 1;\n summary |= (ULL(1) << i);\n }\n }\n }\n\n uint64_t interrupts = intstatus;\n if (interrupts) {\n for (int i = INTLEVEL_EXTERNAL_MIN;\n i < INTLEVEL_EXTERNAL_MAX; i++) {\n if (interrupts & (ULL(1) << i)) {\n \/\/ See table 4-19 of 21164 hardware reference\n ipl = i;\n summary |= (ULL(1) << i);\n }\n }\n }\n\n if (ipl && ipl > tc->readMiscReg(IPR_IPLR)) {\n newIpl = ipl;\n newSummary = summary;\n newInfoSet = true;\n DPRINTF(Flow, \"Interrupt! IPLR=%d ipl=%d summary=%x\\n\",\n tc->readMiscReg(IPR_IPLR), ipl, summary);\n\n return new InterruptFault;\n } else {\n return NoFault;\n }\n }\n\n void updateIntrInfo(ThreadContext *tc)\n {\n assert(newInfoSet);\n tc->setMiscReg(IPR_ISR, newSummary);\n tc->setMiscReg(IPR_INTID, newIpl);\n newInfoSet = false;\n }\n\n private:\n bool newInfoSet;\n int newIpl;\n int newSummary;\n };\n}\n\n#endif\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2012-2017 The Bitcoin Core developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include <bench\/bench.h>\n#include <wallet\/wallet.h>\n#include <wallet\/coinselection.h>\n\n#include <set>\n\nstatic void addCoin(const CAmount& nValue, const CWallet& wallet, std::vector<COutput>& vCoins)\n{\n int nInput = 0;\n\n static int nextLockTime = 0;\n CMutableTransaction tx;\n tx.nLockTime = nextLockTime++; \/\/ so all transactions get different hashes\n tx.vout.resize(nInput + 1);\n tx.vout[nInput].nValue = nValue;\n CWalletTx* wtx = new CWalletTx(&wallet, MakeTransactionRef(std::move(tx)));\n\n int nAge = 6 * 24;\n COutput output(wtx, nInput, nAge, true \/* spendable *\/, true \/* solvable *\/, true \/* safe *\/);\n vCoins.push_back(output);\n}\n\n\/\/ Simple benchmark for wallet coin selection. Note that it maybe be necessary\n\/\/ to build up more complicated scenarios in order to get meaningful\n\/\/ measurements of performance. From laanwj, \"Wallet coin selection is probably\n\/\/ the hardest, as you need a wider selection of scenarios, just testing the\n\/\/ same one over and over isn't too useful. Generating random isn't useful\n\/\/ either for measurements.\"\n\/\/ (https:\/\/github.com\/bitcoin\/bitcoin\/issues\/7883#issuecomment-224807484)\nstatic void CoinSelection(benchmark::State& state)\n{\n const CWallet wallet(\"dummy\", WalletDatabase::CreateDummy());\n std::vector<COutput> vCoins;\n LOCK(wallet.cs_wallet);\n\n while (state.KeepRunning()) {\n \/\/ Add coins.\n for (int i = 0; i < 1000; i++)\n addCoin(1000 * COIN, wallet, vCoins);\n addCoin(3 * COIN, wallet, vCoins);\n\n std::set<CInputCoin> setCoinsRet;\n CAmount nValueRet;\n bool bnb_used;\n CoinEligibilityFilter filter_standard(1, 6, 0);\n CoinSelectionParams coin_selection_params(false, 34, 148, CFeeRate(0), 0);\n bool success = wallet.SelectCoinsMinConf(1003 * COIN, filter_standard, vCoins, setCoinsRet, nValueRet, coin_selection_params, bnb_used)\n || wallet.SelectCoinsMinConf(1003 * COIN, filter_standard, vCoins, setCoinsRet, nValueRet, coin_selection_params, bnb_used);\n assert(success);\n assert(nValueRet == 1003 * COIN);\n assert(setCoinsRet.size() == 2);\n\n \/\/ Empty wallet.\n for (COutput& output : vCoins) {\n delete output.tx;\n }\n vCoins.clear();\n }\n}\n\ntypedef std::set<CInputCoin> CoinSet;\n\n\/\/ Copied from src\/wallet\/test\/coinselector_tests.cpp\nstatic void add_coin(const CAmount& nValue, int nInput, std::vector<CInputCoin>& set)\n{\n CMutableTransaction tx;\n tx.vout.resize(nInput + 1);\n tx.vout[nInput].nValue = nValue;\n set.emplace_back(MakeTransactionRef(tx), nInput);\n}\n\/\/ Copied from src\/wallet\/test\/coinselector_tests.cpp\nstatic CAmount make_hard_case(int utxos, std::vector<CInputCoin>& utxo_pool)\n{\n utxo_pool.clear();\n CAmount target = 0;\n for (int i = 0; i < utxos; ++i) {\n target += (CAmount)1 << (utxos+i);\n add_coin((CAmount)1 << (utxos+i), 2*i, utxo_pool);\n add_coin(((CAmount)1 << (utxos+i)) + ((CAmount)1 << (utxos-1-i)), 2*i + 1, utxo_pool);\n }\n return target;\n}\n\nstatic void BnBExhaustion(benchmark::State& state)\n{\n \/\/ Setup\n std::vector<CInputCoin> utxo_pool;\n CoinSet selection;\n CAmount value_ret = 0;\n CAmount not_input_fees = 0;\n\n while (state.KeepRunning()) {\n \/\/ Benchmark\n CAmount target = make_hard_case(17, utxo_pool);\n SelectCoinsBnB(utxo_pool, target, 0, selection, value_ret, not_input_fees); \/\/ Should exhaust\n\n \/\/ Cleanup\n utxo_pool.clear();\n selection.clear();\n }\n}\n\nBENCHMARK(CoinSelection, 650);\nBENCHMARK(BnBExhaustion, 650);\n<commit_msg>bench: Simplify CoinSelection<commit_after>\/\/ Copyright (c) 2012-2017 The Bitcoin Core developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include <bench\/bench.h>\n#include <wallet\/wallet.h>\n#include <wallet\/coinselection.h>\n\n#include <set>\n\nstatic void addCoin(const CAmount& nValue, const CWallet& wallet, std::vector<COutput>& vCoins)\n{\n int nInput = 0;\n\n static int nextLockTime = 0;\n CMutableTransaction tx;\n tx.nLockTime = nextLockTime++; \/\/ so all transactions get different hashes\n tx.vout.resize(nInput + 1);\n tx.vout[nInput].nValue = nValue;\n CWalletTx* wtx = new CWalletTx(&wallet, MakeTransactionRef(std::move(tx)));\n\n int nAge = 6 * 24;\n COutput output(wtx, nInput, nAge, true \/* spendable *\/, true \/* solvable *\/, true \/* safe *\/);\n vCoins.push_back(output);\n}\n\n\/\/ Simple benchmark for wallet coin selection. Note that it maybe be necessary\n\/\/ to build up more complicated scenarios in order to get meaningful\n\/\/ measurements of performance. From laanwj, \"Wallet coin selection is probably\n\/\/ the hardest, as you need a wider selection of scenarios, just testing the\n\/\/ same one over and over isn't too useful. Generating random isn't useful\n\/\/ either for measurements.\"\n\/\/ (https:\/\/github.com\/bitcoin\/bitcoin\/issues\/7883#issuecomment-224807484)\nstatic void CoinSelection(benchmark::State& state)\n{\n const CWallet wallet(\"dummy\", WalletDatabase::CreateDummy());\n LOCK(wallet.cs_wallet);\n\n \/\/ Add coins.\n std::vector<COutput> vCoins;\n for (int i = 0; i < 1000; ++i) {\n addCoin(1000 * COIN, wallet, vCoins);\n }\n addCoin(3 * COIN, wallet, vCoins);\n\n const CoinEligibilityFilter filter_standard(1, 6, 0);\n const CoinSelectionParams coin_selection_params(true, 34, 148, CFeeRate(0), 0);\n while (state.KeepRunning()) {\n std::set<CInputCoin> setCoinsRet;\n CAmount nValueRet;\n bool bnb_used;\n bool success = wallet.SelectCoinsMinConf(1003 * COIN, filter_standard, vCoins, setCoinsRet, nValueRet, coin_selection_params, bnb_used);\n assert(success);\n assert(nValueRet == 1003 * COIN);\n assert(setCoinsRet.size() == 2);\n }\n}\n\ntypedef std::set<CInputCoin> CoinSet;\n\n\/\/ Copied from src\/wallet\/test\/coinselector_tests.cpp\nstatic void add_coin(const CAmount& nValue, int nInput, std::vector<CInputCoin>& set)\n{\n CMutableTransaction tx;\n tx.vout.resize(nInput + 1);\n tx.vout[nInput].nValue = nValue;\n set.emplace_back(MakeTransactionRef(tx), nInput);\n}\n\/\/ Copied from src\/wallet\/test\/coinselector_tests.cpp\nstatic CAmount make_hard_case(int utxos, std::vector<CInputCoin>& utxo_pool)\n{\n utxo_pool.clear();\n CAmount target = 0;\n for (int i = 0; i < utxos; ++i) {\n target += (CAmount)1 << (utxos+i);\n add_coin((CAmount)1 << (utxos+i), 2*i, utxo_pool);\n add_coin(((CAmount)1 << (utxos+i)) + ((CAmount)1 << (utxos-1-i)), 2*i + 1, utxo_pool);\n }\n return target;\n}\n\nstatic void BnBExhaustion(benchmark::State& state)\n{\n \/\/ Setup\n std::vector<CInputCoin> utxo_pool;\n CoinSet selection;\n CAmount value_ret = 0;\n CAmount not_input_fees = 0;\n\n while (state.KeepRunning()) {\n \/\/ Benchmark\n CAmount target = make_hard_case(17, utxo_pool);\n SelectCoinsBnB(utxo_pool, target, 0, selection, value_ret, not_input_fees); \/\/ Should exhaust\n\n \/\/ Cleanup\n utxo_pool.clear();\n selection.clear();\n }\n}\n\nBENCHMARK(CoinSelection, 650);\nBENCHMARK(BnBExhaustion, 650);\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Funambol is a mobile platform developed by Funambol, Inc.\n * Copyright (C) 2003 - 2007 Funambol, Inc.\n *\n * This program is free software; you can redistribute it and\/or modify it under\n * the terms of the GNU Affero General Public License version 3 as published by\n * the Free Software Foundation with the addition of the following permission\n * added to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED\n * WORK IN WHICH THE COPYRIGHT IS OWNED BY FUNAMBOL, FUNAMBOL DISCLAIMS THE\n * WARRANTY OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.\n *\n * This program is distributed in the hope that it will be useful, but WITHOUT\n * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more\n * details.\n *\n * You should have received a copy of the GNU Affero General Public License\n * along with this program; if not, see http:\/\/www.gnu.org\/licenses or write to\n * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,\n * MA 02110-1301 USA.\n *\n * You can contact Funambol, Inc. headquarters at 643 Bair Island Road, Suite\n * 305, Redwood City, CA 94063, USA, or at email address info@funambol.com.\n *\n * The interactive user interfaces in modified source and object code versions\n * of this program must display Appropriate Legal Notices, as required under\n * Section 5 of the GNU Affero General Public License version 3.\n *\n * In accordance with Section 7(b) of the GNU Affero General Public License\n * version 3, these Appropriate Legal Notices must retain the display of the\n * \"Powered by Funambol\" logo. If the display of the logo is not reasonably\n * feasible for technical reasons, the Appropriate Legal Notices must display\n * the words \"Powered by Funambol\".\n *\/\n\n#include <eikenv.h>\n#include <e32cmn.h>\n#include \"base\/SymbianLog.h\"\n#include \"base\/util\/symbianUtils.h\"\n#include \"base\/util\/stringUtils.h\"\n#include \"base\/util\/timeUtils.h\"\n#include \"base\/globalsdef.h\"\n\nUSE_NAMESPACE\n\n\n\/\/ Formats for date&time printed into log.\n_LIT(KFormatDateAndTime, \"%*D%*N%Y%1-%2-%3 %:0%J%:1%T%:2%S\");\n_LIT(KFormatOnlyTime, \"%:0%J%:1%T%:2%S\");\n\n\/\/ The name of the semaphore\n_LIT(KLogSemaphoreName, \"FLogSemaphore\");\n\n\nSymbianLog::SymbianLog(bool resetLog, const char* path, const char* name) \n{\n TInt err = KErrNone;\n iLogName.Assign(charToNewBuf(SYMBIAN_LOG_NAME));\n \n \/\/ Create a semaphore, to avoid accessing the FileSystem at\n \/\/ the same time by different threads.\n \/\/ The semaphore is global, so that it could be used also by\n \/\/ other processes that (in future) will use this Log.\n err = iSemaphore.CreateGlobal(KLogSemaphoreName, 1);\n if (err != KErrNone) {\n setError(ERR_SEMAPHORE_CREATION, ERR_SEMAPHORE_CREATION_MSG);\n }\n iSemaphore.Wait();\n\n \n \/\/ Connect to the file server session.\n fsSession.Connect(); \n \n if (resetLog) {\n err = file.Replace(fsSession, iLogName, EFileWrite|EFileShareAny);\n }\n else {\n err = file.Open(fsSession, iLogName, EFileWrite|EFileShareAny);\n if (err == KErrNotFound) {\n err = file.Create(fsSession, iLogName, EFileWrite|EFileShareAny);\n }\n else {\n \/\/ Log file existing, and not resetted. Will append data.\n TInt pos;\n file.Seek(ESeekEnd, pos);\n }\n }\n if (err != KErrNone) {\n return;\n }\n \n \/\/ Write the Header\n StringBuffer header = createHeader();\n RBuf8 data;\n data.Assign(stringBufferToNewBuf8(header));\n file.Write(data);\n\n file.Close();\n fsSession.Close();\n \n iSemaphore.Signal();\n return;\n}\n\nSymbianLog::~SymbianLog() { \n}\n\nvoid SymbianLog::setLogPath(const char* configLogPath) {\n\/\/ TODO: implement\n}\n\nvoid SymbianLog::setLogName(const char* configLogName) {\n\/\/ TODO: implement\n}\n\n\n\nStringBuffer SymbianLog::createHeader(const char* title) \n{\n const char *t = (title)? title : SYMBIAN_LOG_HEADER;\n \n StringBuffer header = createCurrentTime(true); \/\/ e.g. \"2008\/04\/02 10:58:03 GMT +2:00\"\n header += \" - \";\n header += t;\n header += \"\\n\";\n\n return header;\n}\n\nStringBuffer SymbianLog::createCurrentTime(bool complete) \n{\n if (iFormattedBias.length() == 0) {\n \/\/ Create the string e.g. \"GMT +2:00\" only once (it's always the same)\n createFormattedBias();\n }\n \n TTime local;\n local.HomeTime();\n \n TBuf<50> formattedTime;\n if (complete) { local.FormatL(formattedTime, KFormatDateAndTime); }\n else { local.FormatL(formattedTime, KFormatOnlyTime); }\n \n StringBuffer ret;\n const char* date = bufToNewChar(formattedTime);\n ret.sprintf(\"%s %s\", date, iFormattedBias.c_str());\n delete [] date;\n return ret;\n}\n\n\nvoid SymbianLog::createFormattedBias() \n{\n TTime local, utc;\n TTimeIntervalMinutes bias;\n \n local.HomeTime();\n utc.UniversalTime();\n local.MinutesFrom(utc, bias);\n\n TInt totalMinutes = bias.Int();\n TInt hours = totalMinutes \/ 60;\n TInt minutes = totalMinutes % 60;\n \n if (totalMinutes >= 0) { iFormattedBias.sprintf(\"GMT +%d:%02d\", hours, minutes); }\n else { iFormattedBias.sprintf(\"GMT %d:%02d\", hours, minutes); }\n}\n\n\n\nvoid SymbianLog::error(const char* msg, ...) \n{\n PLATFORM_VA_LIST argList;\n PLATFORM_VA_START (argList, msg);\n printMessage(LOG_ERROR, msg, argList);\n PLATFORM_VA_END(argList);\n}\nvoid SymbianLog::info (const char* msg, ...) \n{\n if (isLoggable(LOG_LEVEL_INFO)) {\n PLATFORM_VA_LIST argList;\n PLATFORM_VA_START (argList, msg);\n printMessage(LOG_INFO, msg, argList);\n PLATFORM_VA_END(argList);\n }\n}\nvoid SymbianLog::debug(const char* msg, ...) \n{\n if (isLoggable(LOG_LEVEL_DEBUG)) {\n PLATFORM_VA_LIST argList;\n PLATFORM_VA_START (argList, msg);\n printMessage(LOG_DEBUG, msg, argList);\n PLATFORM_VA_END(argList);\n }\n}\nvoid SymbianLog::developer(const char* msg, ...) \n{\n if (isLoggable(LOG_LEVEL_INFO)) {\n PLATFORM_VA_LIST argList;\n PLATFORM_VA_START (argList, msg);\n printMessage(LOG_DEBUG, msg, argList);\n PLATFORM_VA_END(argList);\n }\n}\n\nvoid SymbianLog::printMessage(const char* level, const char* msg, PLATFORM_VA_LIST argList) \n{\n iSemaphore.Wait();\n \n StringBuffer currentTime = createCurrentTime(false);\n \n fsSession.Connect();\n TInt err = file.Open(fsSession, iLogName, EFileWrite|EFileShareAny);\n if (err != KErrNone) {\n return;\n }\n \n TInt pos = 0;\n err = file.Seek(ESeekEnd, pos);\n if (err != KErrNone) {\n return;\n }\n\n \/\/ Write the data\n StringBuffer line, data;\n line.sprintf(\"%s -%s- %s\", currentTime.c_str(), level, msg);\n data.vsprintf(line.c_str(), argList);\n data.append(\"\\n\");\n \n RBuf8 buf;\n buf.Assign(stringBufferToNewBuf8(data));\n file.Write(buf);\n \n file.Close();\n fsSession.Close();\n iSemaphore.Signal();\n}\n\nvoid SymbianLog::reset(const char* title) \n{\n iSemaphore.Wait();\n \n fsSession.Connect();\n TInt err = file.Replace(fsSession, iLogName, EFileWrite|EFileShareAny);\n if (err != KErrNone) {\n return;\n }\n \n \/\/ Write the Header\n StringBuffer header = createHeader(title);\n RBuf8 buf;\n buf.Assign(stringBufferToNewBuf8(header));\n file.Write(buf);\n \n file.Close();\n fsSession.Close();\n iSemaphore.Signal();\n}\n\n\nsize_t SymbianLog::getLogSize() \n{\n iSemaphore.Wait();\n fsSession.Connect();\n \n TInt size = 0;\n TInt err = file.Size(size);\n if (err != KErrNone) {\n return (size_t)-1;\n }\n\n file.Close();\n fsSession.Close();\n iSemaphore.Signal();\n \n return (size_t)size;\n}\n\n\n\nLog *Log::logger;\n\nLog &Log::instance() {\n if (!logger) {\n logger = new SymbianLog();\n }\n return *logger;\n}\n<commit_msg>- Share the FileServer session (RFs). So it's not necessary to connect\/close RFs every time. - Changed the createCurrentTime(), GMT+xx is appended only when time format is complete (date & time)<commit_after>\/*\n * Funambol is a mobile platform developed by Funambol, Inc.\n * Copyright (C) 2003 - 2007 Funambol, Inc.\n *\n * This program is free software; you can redistribute it and\/or modify it under\n * the terms of the GNU Affero General Public License version 3 as published by\n * the Free Software Foundation with the addition of the following permission\n * added to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED\n * WORK IN WHICH THE COPYRIGHT IS OWNED BY FUNAMBOL, FUNAMBOL DISCLAIMS THE\n * WARRANTY OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.\n *\n * This program is distributed in the hope that it will be useful, but WITHOUT\n * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more\n * details.\n *\n * You should have received a copy of the GNU Affero General Public License\n * along with this program; if not, see http:\/\/www.gnu.org\/licenses or write to\n * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,\n * MA 02110-1301 USA.\n *\n * You can contact Funambol, Inc. headquarters at 643 Bair Island Road, Suite\n * 305, Redwood City, CA 94063, USA, or at email address info@funambol.com.\n *\n * The interactive user interfaces in modified source and object code versions\n * of this program must display Appropriate Legal Notices, as required under\n * Section 5 of the GNU Affero General Public License version 3.\n *\n * In accordance with Section 7(b) of the GNU Affero General Public License\n * version 3, these Appropriate Legal Notices must retain the display of the\n * \"Powered by Funambol\" logo. If the display of the logo is not reasonably\n * feasible for technical reasons, the Appropriate Legal Notices must display\n * the words \"Powered by Funambol\".\n *\/\n\n#include <eikenv.h>\n#include <e32cmn.h>\n#include \"base\/SymbianLog.h\"\n#include \"base\/util\/symbianUtils.h\"\n#include \"base\/util\/stringUtils.h\"\n#include \"base\/util\/timeUtils.h\"\n#include \"base\/globalsdef.h\"\n\nUSE_NAMESPACE\n\n\n\/\/ Formats for date&time printed into log.\n_LIT(KFormatDateAndTime, \"%*D%*N%Y%1-%2-%3 %:0%J%:1%T%:2%S\");\n_LIT(KFormatOnlyTime, \"%:0%J%:1%T%:2%S\");\n\n\/\/ The name of the semaphore\n_LIT(KLogSemaphoreName, \"FLogSemaphore\");\n\n\nSymbianLog::SymbianLog(bool resetLog, const char* path, const char* name) \n{\n TInt err = KErrNone;\n iLogName.Assign(charToNewBuf(SYMBIAN_LOG_NAME));\n \n \/\/ Create a semaphore, to avoid accessing the FileSystem at\n \/\/ the same time by different threads.\n \/\/ The semaphore is global, so that it could be used also by\n \/\/ other processes that (in future) will use this Log.\n err = iSemaphore.CreateGlobal(KLogSemaphoreName, 1);\n if (err != KErrNone) {\n setError(ERR_SEMAPHORE_CREATION, ERR_SEMAPHORE_CREATION_MSG);\n }\n iSemaphore.Wait();\n\n \n \/\/ Connect to the file server session.\n fsSession.Connect();\n err = fsSession.ShareAuto();\n if (err != KErrNone) {\n setErrorF(err, \"SymbianLog error: unable to share RFs session (code %d)\", err);\n return;\n }\n \n if (resetLog) {\n err = file.Replace(fsSession, iLogName, EFileWrite|EFileShareAny);\n }\n else {\n err = file.Open(fsSession, iLogName, EFileWrite|EFileShareAny);\n if (err == KErrNotFound) {\n err = file.Create(fsSession, iLogName, EFileWrite|EFileShareAny);\n }\n else {\n \/\/ Log file existing, and not resetted. Will append data.\n TInt pos;\n file.Seek(ESeekEnd, pos);\n }\n }\n if (err != KErrNone) {\n setErrorF(err, \"SymbianLog: could not open the log file '%ls'\", iLogName.Ptr());\n return;\n }\n \n \/\/ Write the Header\n StringBuffer header = createHeader();\n RBuf8 data;\n data.Assign(stringBufferToNewBuf8(header));\n file.Write(data);\n\n file.Close();\n iSemaphore.Signal();\n return;\n}\n\nSymbianLog::~SymbianLog() { \n}\n\nvoid SymbianLog::setLogPath(const char* configLogPath) {\n\/\/ TODO: implement\n}\n\nvoid SymbianLog::setLogName(const char* configLogName) {\n\/\/ TODO: implement\n}\n\n\n\nStringBuffer SymbianLog::createHeader(const char* title) \n{\n const char *t = (title)? title : SYMBIAN_LOG_HEADER;\n \n StringBuffer header = createCurrentTime(true); \/\/ e.g. \"2008\/04\/02 10:58:03 GMT +2:00\"\n header += \" - \";\n header += t;\n header += \"\\n\";\n\n return header;\n}\n\nStringBuffer SymbianLog::createCurrentTime(bool complete) \n{\n if (iFormattedBias.length() == 0) {\n \/\/ Create the string e.g. \"GMT +2:00\" only once (it's always the same)\n createFormattedBias();\n }\n \n TTime local;\n StringBuffer ret;\n TBuf<50> formattedTime;\n \n local.HomeTime();\n\n if (complete) { \n local.FormatL(formattedTime, KFormatDateAndTime); \n StringBuffer date = bufToStringBuffer(formattedTime);\n ret.sprintf(\"%s %s\", date.c_str(), iFormattedBias.c_str());\n }\n else { \n local.FormatL(formattedTime, KFormatOnlyTime);\n ret = bufToStringBuffer(formattedTime);\n }\n return ret;\n}\n\n\nvoid SymbianLog::createFormattedBias() \n{\n TTime local, utc;\n TTimeIntervalMinutes bias;\n \n local.HomeTime();\n utc.UniversalTime();\n local.MinutesFrom(utc, bias);\n\n TInt totalMinutes = bias.Int();\n TInt hours = totalMinutes \/ 60;\n TInt minutes = totalMinutes % 60;\n \n if (totalMinutes >= 0) { iFormattedBias.sprintf(\"GMT +%d:%02d\", hours, minutes); }\n else { iFormattedBias.sprintf(\"GMT %d:%02d\", hours, minutes); }\n}\n\n\n\nvoid SymbianLog::error(const char* msg, ...) \n{\n PLATFORM_VA_LIST argList;\n PLATFORM_VA_START (argList, msg);\n printMessage(LOG_ERROR, msg, argList);\n PLATFORM_VA_END(argList);\n}\nvoid SymbianLog::info (const char* msg, ...) \n{\n if (isLoggable(LOG_LEVEL_INFO)) {\n PLATFORM_VA_LIST argList;\n PLATFORM_VA_START (argList, msg);\n printMessage(LOG_INFO, msg, argList);\n PLATFORM_VA_END(argList);\n }\n}\nvoid SymbianLog::debug(const char* msg, ...) \n{\n if (isLoggable(LOG_LEVEL_DEBUG)) {\n PLATFORM_VA_LIST argList;\n PLATFORM_VA_START (argList, msg);\n printMessage(LOG_DEBUG, msg, argList);\n PLATFORM_VA_END(argList);\n }\n}\nvoid SymbianLog::developer(const char* msg, ...) \n{\n if (isLoggable(LOG_LEVEL_INFO)) {\n PLATFORM_VA_LIST argList;\n PLATFORM_VA_START (argList, msg);\n printMessage(LOG_DEBUG, msg, argList);\n PLATFORM_VA_END(argList);\n }\n}\n\nvoid SymbianLog::printMessage(const char* level, const char* msg, PLATFORM_VA_LIST argList) \n{\n iSemaphore.Wait();\n \n StringBuffer currentTime = createCurrentTime(false);\n \n TInt err = file.Open(fsSession, iLogName, EFileWrite|EFileShareAny);\n if (err != KErrNone) {\n setErrorF(err, \"SymbianLog: could not open log file (code %d)\", err);\n return;\n }\n \n TInt pos = 0;\n err = file.Seek(ESeekEnd, pos);\n if (err != KErrNone) {\n setErrorF(err, \"SymbianLog: seek error on log file (code %d)\", err);\n return;\n }\n\n \/\/ Write the data\n StringBuffer line, data;\n line.sprintf(\"%s -%s- %s\", currentTime.c_str(), level, msg);\n data.vsprintf(line.c_str(), argList);\n data.append(\"\\n\");\n \n RBuf8 buf;\n buf.Assign(stringBufferToNewBuf8(data));\n file.Write(buf);\n \n file.Close();\n iSemaphore.Signal();\n}\n\nvoid SymbianLog::reset(const char* title) \n{\n iSemaphore.Wait();\n \n TInt err = file.Replace(fsSession, iLogName, EFileWrite|EFileShareAny);\n if (err != KErrNone) {\n setErrorF(err, \"SymbianLog: error resetting the log file (code %d)\", err);\n return;\n }\n \n \/\/ Write the Header\n StringBuffer header = createHeader(title);\n RBuf8 buf;\n buf.Assign(stringBufferToNewBuf8(header));\n file.Write(buf);\n \n file.Close();\n iSemaphore.Signal();\n}\n\n\nsize_t SymbianLog::getLogSize() \n{\n iSemaphore.Wait();\n \n TInt size = 0;\n TInt err = file.Size(size);\n if (err != KErrNone) {\n setErrorF(err, \"SymbianLog: error getting the log size (code %d)\", err);\n return (size_t)-1;\n }\n\n file.Close();\n iSemaphore.Signal();\n \n return (size_t)size;\n}\n\n\n\nLog *Log::logger;\n\nLog &Log::instance() {\n if (!logger) {\n logger = new SymbianLog();\n }\n return *logger;\n}\n<|endoftext|>"} {"text":"<commit_before>\/***************************************************************\n *\n * Copyright (C) 1990-2007, Condor Team, Computer Sciences Department,\n * University of Wisconsin-Madison, WI.\n * \n * Licensed under the Apache License, Version 2.0 (the \"License\"); you\n * may not use this file except in compliance with the License. You may\n * obtain a copy of the License at\n * \n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n ***************************************************************\/\n\n\n#if HAVE_CONFIG_H\n#include \"config.h\"\n#endif\n#include \"classad\/common.h\"\n#include \"classad\/util.h\"\n#include <limits.h>\n\nusing namespace std;\n\n#if HAVE_LONG_TIMEZONE\nextern DLL_IMPORT_MAGIC long timezone;\n#endif\n\nBEGIN_NAMESPACE( classad )\n\n#ifdef WIN32\n#define BIGGEST_RANDOM_INT RAND_MAX\nint get_random_integer(void)\n{\n static char initialized = 0;\n\n\tif (!initialized) {\n int seed = time(NULL);\n srand(seed);\n initialized = 1;\n\t}\n\n\treturn rand();\n}\n#else\n#define BIGGEST_RANDOM_INT INT_MAX\nint get_random_integer(void)\n{\n static char initialized = 0;\n\n\tif (!initialized) {\n int seed = time(NULL);\n srand48(seed);\n initialized = 1;\n\t}\n\treturn (int) (lrand48() & INT_MAX);\n}\n#endif\n\ndouble get_random_real(void)\n{\n return (get_random_integer() \/ (double) BIGGEST_RANDOM_INT);\n}\n\nlong timezone_offset(void)\n{\n#if HAVE_LONG_TIMEZONE\n return ::timezone;\n#else\n static long tz_offset = 0;\n static bool have_tz_offset = false;\n\n if (!have_tz_offset) {\n struct tm *tms;\n time_t clock;\n\n time(&clock);\n tms = localtime(&clock);\n tz_offset = -tms->tm_gmtoff;\n if (0 != tms->tm_isdst) {\n tz_offset += 3600;\n }\n }\n return tz_offset;\n#endif\n}\n\nvoid convert_escapes(string &text, bool &validStr)\n{\n\tchar *copy;\n\tint length;\n\tint source, dest;\n\n\t\/\/ We now it will be no longer than the original.\n\tlength = text.length();\n\tcopy = new char[length + 1];\n\t\n\t\/\/ We scan up to one less than the length, because we ignore\n\t\/\/ a terminating slash: it can't be an escape. \n\tdest = 0;\n\tfor (source = 0; source < length - 1; source++) {\n\t\tif (text[source] != '\\\\' || source == length - 1) {\n\t\t\tcopy[dest++]= text[source]; \n\t\t}\n\t\telse {\n\t\t\tsource++;\n\n\t\t\tchar new_char;\n\t\t\tswitch(text[source]) {\n\t\t\tcase 'a':\tnew_char = '\\a'; break;\n\t\t\tcase 'b':\tnew_char = '\\b'; break;\n\t\t\tcase 'f':\tnew_char = '\\f'; break;\n\t\t\tcase 'n':\tnew_char = '\\n'; break;\n\t\t\tcase 'r':\tnew_char = '\\r'; break;\n\t\t\tcase 't':\tnew_char = '\\t'; break;\n\t\t\tcase 'v':\tnew_char = '\\v'; break;\n\t\t\tcase '\\\\':\tnew_char = '\\\\'; break;\n\t\t\tcase '\\?':\tnew_char = '\\?'; break;\n\t\t\tcase '\\'':\tnew_char = '\\''; break;\n\t\t\tcase '\\\"':\tnew_char = '\\\"'; break;\n\t\t\tdefault: \n\t\t\t\tif (isodigit(text[source])) {\n\t\t\t\t\tunsigned int number;\n\t\t\t\t\t\/\/ There are three allowed ways to have octal escape characters:\n\t\t\t\t\t\/\/ \\[0..3]nn or \\nn or \\n. We check for them in that order.\n\t\t\t\t\tif ( source <= length - 3\n\t\t\t\t\t\t&& text[source] >= '0' && text[source] <= '3'\n\t\t\t\t\t\t&& isodigit(text[source+1])\n\t\t\t\t\t\t&& isodigit(text[source+2])) {\n\n\t\t\t\t\t\t\/\/ We have the \\[0..3]nn case\n\t\t\t\t\t\tchar octal[4];\n\t\t\t\t\t\toctal[0] = text[source];\n\t\t\t\t\t\toctal[1] = text[source+1];\n\t\t\t\t\t\toctal[2] = text[source+2];\n\t\t\t\t\t\toctal[3] = 0;\n\t\t\t\t\t\tsscanf(octal, \"%o\", &number);\n\t\t\t\t\t\tnew_char = number;\n\t\t\t\t\t\tsource += 2; \/\/ to account for the two extra digits\n\t\t\t\t\t} else if ( source <= length -2\n\t\t\t\t\t\t\t && isodigit(text[source+1])) {\n\n\t\t\t\t\t\t\/\/ We have the \\nn case\n\t\t\t\t\t\tchar octal[3];\n\t\t\t\t\t\toctal[0] = text[source];\n\t\t\t\t\t\toctal[1] = text[source+1];\n\t\t\t\t\t\toctal[2] = 0;\n\t\t\t\t\t\tsscanf(octal, \"%o\", &number);\n\t\t\t\t\t\tnew_char = number;\n\t\t\t\t\t\tsource += 1; \/\/ to account for the extra digit\n\t\t\t\t\t} else if (source <= length - 1) {\n\t\t\t\t\t\tchar octal[2];\n\t\t\t\t\t\toctal[0] = text[source];\n\t\t\t\t\t\toctal[1] = 0;\n\t\t\t\t\t\tsscanf(octal, \"%o\", &number);\n\t\t\t\t\t\tnew_char = number;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tnew_char = text[source];\n\t\t\t\t\t}\n\t\t\t\t\tif(number == 0) { \/\/ \"\\\\0\" is an invalid substring within a string literal\n\t\t\t\t\t validStr = false;\n\t\t\t\t\t delete [] copy;\n\t\t\t\t\t return;\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tnew_char = text[source];\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcopy[dest++] = new_char;\n\t\t}\n\t}\n\tcopy[dest] = 0;\n\ttext = copy;\n\tdelete [] copy;\n\treturn;\n}\n\nvoid \ngetLocalTime(time_t *now, struct tm *localtm) \n{\n\n#ifndef WIN32\n\tlocaltime_r( now, localtm );\n#else\n\t\/\/ there is no localtime_r() on Windows, so for now\n\t\/\/ we just call localtime() and deep copy the result.\n\n\tstruct tm *lt_ptr; \n\n\tlt_ptr = localtime(now);\n\n\tif (localtm == NULL) { return; } \n\n\tlocaltm->tm_sec = lt_ptr->tm_sec; \/* seconds *\/\n\tlocaltm->tm_min = lt_ptr->tm_min; \/* minutes *\/\n\tlocaltm->tm_hour = lt_ptr->tm_hour; \/* hours *\/\n\tlocaltm->tm_mday = lt_ptr->tm_mday; \/* day of the month *\/\n\tlocaltm->tm_mon = lt_ptr->tm_mon; \/* month *\/\n\tlocaltm->tm_year = lt_ptr->tm_year; \/* year *\/\n\tlocaltm->tm_wday = lt_ptr->tm_wday; \/* day of the week *\/\n\tlocaltm->tm_yday = lt_ptr->tm_yday; \/* day in the year *\/\n\tlocaltm->tm_isdst = lt_ptr->tm_isdst; \/* daylight saving time *\/\n\t\n#endif\n\treturn;\n}\n\nvoid \ngetGMTime(time_t *now, struct tm *gtm) \n{\n\n#ifndef WIN32\n\tgmtime_r( now, gtm );\n#else\n\t\/\/ there is no localtime_r() on Windows, so for now\n\t\/\/ we just call localtime() and deep copy the result.\n\n\tstruct tm *gt_ptr; \n\n\tgt_ptr = gmtime(now);\n\n\tif (gtm == NULL) { return; } \n\n\tgtm->tm_sec = gt_ptr->tm_sec; \/* seconds *\/\n\tgtm->tm_min = gt_ptr->tm_min; \/* minutes *\/\n\tgtm->tm_hour = gt_ptr->tm_hour; \/* hours *\/\n\tgtm->tm_mday = gt_ptr->tm_mday; \/* day of the month *\/\n\tgtm->tm_mon = gt_ptr->tm_mon; \/* month *\/\n\tgtm->tm_year = gt_ptr->tm_year; \/* year *\/\n\tgtm->tm_wday = gt_ptr->tm_wday; \/* day of the week *\/\n\tgtm->tm_yday = gt_ptr->tm_yday; \/* day in the year *\/\n\tgtm->tm_isdst = gt_ptr->tm_isdst; \/* daylight saving time *\/\n\t\n#endif\n\treturn;\n}\n\nvoid absTimeToString(const abstime_t &atime, string &buffer)\n{\n int tzsecs;\n time_t epoch_time;\n char timebuf[32], sign;\n struct tm tms;\n\n tzsecs = atime.offset; \n epoch_time = atime.secs;\n if (tzsecs > 0) { \n sign = '+'; \/\/ timezone offset's sign\n } else {\n sign = '-';\n tzsecs = -tzsecs;\n }\n getGMTime(&epoch_time, &tms);\n strftime(timebuf, sizeof(timebuf), \"%Y-%m-%dT%H:%M:%S\", &tms);\n buffer += timebuf;\n sprintf(timebuf, \"%c%02d%02d\", sign, tzsecs \/ 3600, (tzsecs \/ 60) % 60);\n buffer += timebuf;\n return;\n}\n\nvoid relTimeToString(double rsecs, string &buffer)\n{\n double fractional_seconds;\n int days, hrs, mins;\n double secs;\n char timebuf[128];\n \n if( rsecs < 0 ) {\n buffer += \"-\";\n rsecs = -rsecs;\n }\n fractional_seconds = rsecs - floor(rsecs);\n\n days = (int) rsecs;\n hrs = days % 86400;\n mins = hrs % 3600;\n secs = (mins % 60) + fractional_seconds;\n days = days \/ 86400;\n hrs = hrs \/ 3600;\n mins = mins \/ 60;\n \n if (days) {\n if (fractional_seconds == 0) {\n sprintf(timebuf, \"%d+%02d:%02d:%02d\", days, hrs, mins, (int) secs);\n } else {\n sprintf(timebuf, \"%d+%02d:%02d:%02g\", days, hrs, mins, secs);\n }\n buffer += timebuf;\n } else if (hrs) {\n if (fractional_seconds == 0) {\n sprintf(timebuf, \"%02d:%02d:%02d\", hrs, mins, (int) secs);\n } else {\n sprintf(timebuf, \"%02d:%02d:%02g\", hrs, mins, secs);\n }\n buffer += timebuf;\n } else if (mins) {\n if (fractional_seconds == 0) {\n sprintf(timebuf, \"%02d:%02d\", mins, (int) secs);\n } else {\n sprintf(timebuf, \"%02d:%02g\", mins, secs);\n }\n buffer += timebuf;\n return;\n } else {\n if (fractional_seconds == 0) {\n sprintf(timebuf, \"%02d\", (int) secs);\n } else {\n sprintf(timebuf, \"%02g\", secs);\n }\n buffer += timebuf;\n }\n return;\n}\n\nvoid day_numbers(int year, int month, int day, int &weekday, int &yearday)\n{\n int fixed = fixed_from_gregorian(year, month, day);\n int jan1_fixed = fixed_from_gregorian(year, 1, 1);\n weekday = fixed % 7;\n yearday = fixed - jan1_fixed;\n return;\n}\n\nint fixed_from_gregorian(int year, int month, int day)\n{\n int fixed;\n int month_adjustment;\n\n if (month <= 2) {\n month_adjustment = 0;\n } else if (is_leap_year(year)) {\n month_adjustment = -1;\n } else {\n month_adjustment = -2;\n }\n fixed = 365 * (year -1)\n + ((year - 1) \/ 4)\n - ((year - 1) \/ 100)\n + ((year - 1) \/ 400)\n + ((367 * month - 362) \/ 12)\n + month_adjustment\n + day;\n return fixed;\n}\n\nbool is_leap_year(int year)\n{\n int mod4;\n int mod400;\n bool leap_year;\n\n mod4 = year % 4;\n mod400 = year % 400;\n\n if (mod4 == 0 && mod400 != 100 && mod400 != 200 && mod400 != 300) {\n leap_year = true;\n } else {\n leap_year = false;\n }\n return leap_year;\n}\n\n#ifdef WIN32\nint classad_isinf(double x) \n{\n\n\tint result;\n\tresult = _fpclass(x);\n\n\tif (result == _FPCLASS_NINF ) {\n\t\t\/* negative infinity *\/\n\t\treturn -1;\n\t} else if ( result == _FPCLASS_PINF ) {\n\t\t\/* positive infinity *\/\n\t\treturn 1;\n\t} else {\n\t\t\/* otherwise *\/\n\t\treturn 0;\n\t}\n}\n#elif (defined (__SVR4) && defined (__sun)) || defined(__APPLE_CC__)\n#ifndef __APPLE_CC__\n#include <ieeefp.h>\n#endif\nint classad_isinf(double x) \n{ \n if (finite(x) || x != x) {\n return 0;\n } else if (x > 0) {\n return 1;\n } else {\n return -1;\n }\n}\n#else\nint classad_isinf(double x)\n{\n if (!isinf(x) || x != x) {\n return 0;\n } else if (x > 0) {\n return 1;\n } else {\n return -1;\n }\n}\n#endif \n\n#ifdef __APPLE_CC__\nint classad_isnan(double x)\n{\n return __isnan(x);\n}\n#else\nint classad_isnan(double x)\n{\n return isnan(x);\n}\n#endif\n\nEND_NAMESPACE \/\/ classad\n\n<commit_msg>Portable isinf() and isnan() macros, needed for HPUX.<commit_after>\/***************************************************************\n *\n * Copyright (C) 1990-2007, Condor Team, Computer Sciences Department,\n * University of Wisconsin-Madison, WI.\n * \n * Licensed under the Apache License, Version 2.0 (the \"License\"); you\n * may not use this file except in compliance with the License. You may\n * obtain a copy of the License at\n * \n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n ***************************************************************\/\n\n\n#if HAVE_CONFIG_H\n#include \"config.h\"\n#endif\n#include \"classad\/common.h\"\n#include \"classad\/util.h\"\n#include <limits.h>\n#include <math.h>\n\nusing namespace std;\n\n#if HAVE_LONG_TIMEZONE\nextern DLL_IMPORT_MAGIC long timezone;\n#endif\n\n\/\/ The following definitions of isnan() and isinf() are recommended here:\n\/\/ http:\/\/www.gnu.org\/software\/libtool\/manual\/autoconf\/Function-Portability.html\n\/\/ We have observed isinf(HUGE_VAL) to return 0 on HPUX, but only apparently\n\/\/ because of an errant #pragma extern applied to this constant in the system\n\/\/ header files. When passed a normal variable assigned to HUGE_VAL, isinf()\n\/\/ does the right thing on that platform.\n\n#ifndef isnan\n# define isnan(x) \\\n (sizeof (x) == sizeof (long double) ? isnan_ld (x) \\\n : sizeof (x) == sizeof (double) ? isnan_d (x) \\\n : isnan_f (x))\nstatic inline int isnan_f (float x) { return x != x; }\nstatic inline int isnan_d (double x) { return x != x; }\nstatic inline int isnan_ld (long double x) { return x != x; }\n#endif\n \n#ifndef isinf\n# define isinf(x) \\\n (sizeof (x) == sizeof (long double) ? isinf_ld (x) \\\n : sizeof (x) == sizeof (double) ? isinf_d (x) \\\n : isinf_f (x))\nstatic inline int isinf_f (float x) { return isnan (x - x); }\nstatic inline int isinf_d (double x) { return isnan (x - x); }\nstatic inline int isinf_ld (long double x) { return isnan (x - x); }\n#endif\n\nBEGIN_NAMESPACE( classad )\n\n#ifdef WIN32\n#define BIGGEST_RANDOM_INT RAND_MAX\nint get_random_integer(void)\n{\n static char initialized = 0;\n\n\tif (!initialized) {\n int seed = time(NULL);\n srand(seed);\n initialized = 1;\n\t}\n\n\treturn rand();\n}\n#else\n#define BIGGEST_RANDOM_INT INT_MAX\nint get_random_integer(void)\n{\n static char initialized = 0;\n\n\tif (!initialized) {\n int seed = time(NULL);\n srand48(seed);\n initialized = 1;\n\t}\n\treturn (int) (lrand48() & INT_MAX);\n}\n#endif\n\ndouble get_random_real(void)\n{\n return (get_random_integer() \/ (double) BIGGEST_RANDOM_INT);\n}\n\nlong timezone_offset(void)\n{\n#if HAVE_LONG_TIMEZONE\n return ::timezone;\n#else\n static long tz_offset = 0;\n static bool have_tz_offset = false;\n\n if (!have_tz_offset) {\n struct tm *tms;\n time_t clock;\n\n time(&clock);\n tms = localtime(&clock);\n tz_offset = -tms->tm_gmtoff;\n if (0 != tms->tm_isdst) {\n tz_offset += 3600;\n }\n }\n return tz_offset;\n#endif\n}\n\nvoid convert_escapes(string &text, bool &validStr)\n{\n\tchar *copy;\n\tint length;\n\tint source, dest;\n\n\t\/\/ We now it will be no longer than the original.\n\tlength = text.length();\n\tcopy = new char[length + 1];\n\t\n\t\/\/ We scan up to one less than the length, because we ignore\n\t\/\/ a terminating slash: it can't be an escape. \n\tdest = 0;\n\tfor (source = 0; source < length - 1; source++) {\n\t\tif (text[source] != '\\\\' || source == length - 1) {\n\t\t\tcopy[dest++]= text[source]; \n\t\t}\n\t\telse {\n\t\t\tsource++;\n\n\t\t\tchar new_char;\n\t\t\tswitch(text[source]) {\n\t\t\tcase 'a':\tnew_char = '\\a'; break;\n\t\t\tcase 'b':\tnew_char = '\\b'; break;\n\t\t\tcase 'f':\tnew_char = '\\f'; break;\n\t\t\tcase 'n':\tnew_char = '\\n'; break;\n\t\t\tcase 'r':\tnew_char = '\\r'; break;\n\t\t\tcase 't':\tnew_char = '\\t'; break;\n\t\t\tcase 'v':\tnew_char = '\\v'; break;\n\t\t\tcase '\\\\':\tnew_char = '\\\\'; break;\n\t\t\tcase '\\?':\tnew_char = '\\?'; break;\n\t\t\tcase '\\'':\tnew_char = '\\''; break;\n\t\t\tcase '\\\"':\tnew_char = '\\\"'; break;\n\t\t\tdefault: \n\t\t\t\tif (isodigit(text[source])) {\n\t\t\t\t\tunsigned int number;\n\t\t\t\t\t\/\/ There are three allowed ways to have octal escape characters:\n\t\t\t\t\t\/\/ \\[0..3]nn or \\nn or \\n. We check for them in that order.\n\t\t\t\t\tif ( source <= length - 3\n\t\t\t\t\t\t&& text[source] >= '0' && text[source] <= '3'\n\t\t\t\t\t\t&& isodigit(text[source+1])\n\t\t\t\t\t\t&& isodigit(text[source+2])) {\n\n\t\t\t\t\t\t\/\/ We have the \\[0..3]nn case\n\t\t\t\t\t\tchar octal[4];\n\t\t\t\t\t\toctal[0] = text[source];\n\t\t\t\t\t\toctal[1] = text[source+1];\n\t\t\t\t\t\toctal[2] = text[source+2];\n\t\t\t\t\t\toctal[3] = 0;\n\t\t\t\t\t\tsscanf(octal, \"%o\", &number);\n\t\t\t\t\t\tnew_char = number;\n\t\t\t\t\t\tsource += 2; \/\/ to account for the two extra digits\n\t\t\t\t\t} else if ( source <= length -2\n\t\t\t\t\t\t\t && isodigit(text[source+1])) {\n\n\t\t\t\t\t\t\/\/ We have the \\nn case\n\t\t\t\t\t\tchar octal[3];\n\t\t\t\t\t\toctal[0] = text[source];\n\t\t\t\t\t\toctal[1] = text[source+1];\n\t\t\t\t\t\toctal[2] = 0;\n\t\t\t\t\t\tsscanf(octal, \"%o\", &number);\n\t\t\t\t\t\tnew_char = number;\n\t\t\t\t\t\tsource += 1; \/\/ to account for the extra digit\n\t\t\t\t\t} else if (source <= length - 1) {\n\t\t\t\t\t\tchar octal[2];\n\t\t\t\t\t\toctal[0] = text[source];\n\t\t\t\t\t\toctal[1] = 0;\n\t\t\t\t\t\tsscanf(octal, \"%o\", &number);\n\t\t\t\t\t\tnew_char = number;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tnew_char = text[source];\n\t\t\t\t\t}\n\t\t\t\t\tif(number == 0) { \/\/ \"\\\\0\" is an invalid substring within a string literal\n\t\t\t\t\t validStr = false;\n\t\t\t\t\t delete [] copy;\n\t\t\t\t\t return;\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tnew_char = text[source];\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcopy[dest++] = new_char;\n\t\t}\n\t}\n\tcopy[dest] = 0;\n\ttext = copy;\n\tdelete [] copy;\n\treturn;\n}\n\nvoid \ngetLocalTime(time_t *now, struct tm *localtm) \n{\n\n#ifndef WIN32\n\tlocaltime_r( now, localtm );\n#else\n\t\/\/ there is no localtime_r() on Windows, so for now\n\t\/\/ we just call localtime() and deep copy the result.\n\n\tstruct tm *lt_ptr; \n\n\tlt_ptr = localtime(now);\n\n\tif (localtm == NULL) { return; } \n\n\tlocaltm->tm_sec = lt_ptr->tm_sec; \/* seconds *\/\n\tlocaltm->tm_min = lt_ptr->tm_min; \/* minutes *\/\n\tlocaltm->tm_hour = lt_ptr->tm_hour; \/* hours *\/\n\tlocaltm->tm_mday = lt_ptr->tm_mday; \/* day of the month *\/\n\tlocaltm->tm_mon = lt_ptr->tm_mon; \/* month *\/\n\tlocaltm->tm_year = lt_ptr->tm_year; \/* year *\/\n\tlocaltm->tm_wday = lt_ptr->tm_wday; \/* day of the week *\/\n\tlocaltm->tm_yday = lt_ptr->tm_yday; \/* day in the year *\/\n\tlocaltm->tm_isdst = lt_ptr->tm_isdst; \/* daylight saving time *\/\n\t\n#endif\n\treturn;\n}\n\nvoid \ngetGMTime(time_t *now, struct tm *gtm) \n{\n\n#ifndef WIN32\n\tgmtime_r( now, gtm );\n#else\n\t\/\/ there is no localtime_r() on Windows, so for now\n\t\/\/ we just call localtime() and deep copy the result.\n\n\tstruct tm *gt_ptr; \n\n\tgt_ptr = gmtime(now);\n\n\tif (gtm == NULL) { return; } \n\n\tgtm->tm_sec = gt_ptr->tm_sec; \/* seconds *\/\n\tgtm->tm_min = gt_ptr->tm_min; \/* minutes *\/\n\tgtm->tm_hour = gt_ptr->tm_hour; \/* hours *\/\n\tgtm->tm_mday = gt_ptr->tm_mday; \/* day of the month *\/\n\tgtm->tm_mon = gt_ptr->tm_mon; \/* month *\/\n\tgtm->tm_year = gt_ptr->tm_year; \/* year *\/\n\tgtm->tm_wday = gt_ptr->tm_wday; \/* day of the week *\/\n\tgtm->tm_yday = gt_ptr->tm_yday; \/* day in the year *\/\n\tgtm->tm_isdst = gt_ptr->tm_isdst; \/* daylight saving time *\/\n\t\n#endif\n\treturn;\n}\n\nvoid absTimeToString(const abstime_t &atime, string &buffer)\n{\n int tzsecs;\n time_t epoch_time;\n char timebuf[32], sign;\n struct tm tms;\n\n tzsecs = atime.offset; \n epoch_time = atime.secs;\n if (tzsecs > 0) { \n sign = '+'; \/\/ timezone offset's sign\n } else {\n sign = '-';\n tzsecs = -tzsecs;\n }\n getGMTime(&epoch_time, &tms);\n strftime(timebuf, sizeof(timebuf), \"%Y-%m-%dT%H:%M:%S\", &tms);\n buffer += timebuf;\n sprintf(timebuf, \"%c%02d%02d\", sign, tzsecs \/ 3600, (tzsecs \/ 60) % 60);\n buffer += timebuf;\n return;\n}\n\nvoid relTimeToString(double rsecs, string &buffer)\n{\n double fractional_seconds;\n int days, hrs, mins;\n double secs;\n char timebuf[128];\n \n if( rsecs < 0 ) {\n buffer += \"-\";\n rsecs = -rsecs;\n }\n fractional_seconds = rsecs - floor(rsecs);\n\n days = (int) rsecs;\n hrs = days % 86400;\n mins = hrs % 3600;\n secs = (mins % 60) + fractional_seconds;\n days = days \/ 86400;\n hrs = hrs \/ 3600;\n mins = mins \/ 60;\n \n if (days) {\n if (fractional_seconds == 0) {\n sprintf(timebuf, \"%d+%02d:%02d:%02d\", days, hrs, mins, (int) secs);\n } else {\n sprintf(timebuf, \"%d+%02d:%02d:%02g\", days, hrs, mins, secs);\n }\n buffer += timebuf;\n } else if (hrs) {\n if (fractional_seconds == 0) {\n sprintf(timebuf, \"%02d:%02d:%02d\", hrs, mins, (int) secs);\n } else {\n sprintf(timebuf, \"%02d:%02d:%02g\", hrs, mins, secs);\n }\n buffer += timebuf;\n } else if (mins) {\n if (fractional_seconds == 0) {\n sprintf(timebuf, \"%02d:%02d\", mins, (int) secs);\n } else {\n sprintf(timebuf, \"%02d:%02g\", mins, secs);\n }\n buffer += timebuf;\n return;\n } else {\n if (fractional_seconds == 0) {\n sprintf(timebuf, \"%02d\", (int) secs);\n } else {\n sprintf(timebuf, \"%02g\", secs);\n }\n buffer += timebuf;\n }\n return;\n}\n\nvoid day_numbers(int year, int month, int day, int &weekday, int &yearday)\n{\n int fixed = fixed_from_gregorian(year, month, day);\n int jan1_fixed = fixed_from_gregorian(year, 1, 1);\n weekday = fixed % 7;\n yearday = fixed - jan1_fixed;\n return;\n}\n\nint fixed_from_gregorian(int year, int month, int day)\n{\n int fixed;\n int month_adjustment;\n\n if (month <= 2) {\n month_adjustment = 0;\n } else if (is_leap_year(year)) {\n month_adjustment = -1;\n } else {\n month_adjustment = -2;\n }\n fixed = 365 * (year -1)\n + ((year - 1) \/ 4)\n - ((year - 1) \/ 100)\n + ((year - 1) \/ 400)\n + ((367 * month - 362) \/ 12)\n + month_adjustment\n + day;\n return fixed;\n}\n\nbool is_leap_year(int year)\n{\n int mod4;\n int mod400;\n bool leap_year;\n\n mod4 = year % 4;\n mod400 = year % 400;\n\n if (mod4 == 0 && mod400 != 100 && mod400 != 200 && mod400 != 300) {\n leap_year = true;\n } else {\n leap_year = false;\n }\n return leap_year;\n}\n\n#ifdef WIN32\nint classad_isinf(double x) \n{\n\n\tint result;\n\tresult = _fpclass(x);\n\n\tif (result == _FPCLASS_NINF ) {\n\t\t\/* negative infinity *\/\n\t\treturn -1;\n\t} else if ( result == _FPCLASS_PINF ) {\n\t\t\/* positive infinity *\/\n\t\treturn 1;\n\t} else {\n\t\t\/* otherwise *\/\n\t\treturn 0;\n\t}\n}\n#elif (defined (__SVR4) && defined (__sun)) || defined(__APPLE_CC__)\n#ifndef __APPLE_CC__\n#include <ieeefp.h>\n#endif\nint classad_isinf(double x) \n{ \n if (finite(x) || x != x) {\n return 0;\n } else if (x > 0) {\n return 1;\n } else {\n return -1;\n }\n}\n#else\nint classad_isinf(double x)\n{\n if (!isinf(x) || x != x) {\n return 0;\n } else if (x > 0) {\n return 1;\n } else {\n return -1;\n }\n}\n#endif \n\n#ifdef __APPLE_CC__\nint classad_isnan(double x)\n{\n return __isnan(x);\n}\n#else\nint classad_isnan(double x)\n{\n return isnan(x);\n}\n#endif\n\nEND_NAMESPACE \/\/ classad\n\n<|endoftext|>"} {"text":"<commit_before>#include <sys\/types.h>\n#include <sys\/wait.h>\n\n#include \"condor_debug.h\"\n#include \"condor_types.h\"\n#include \"condor_expressions.h\"\n#include \"condor_mach_status.h\"\n#include \"sched.h\"\n\n#include \"cdefs.h\"\n#include \"event.h\"\n#include \"state.h\"\n#include \"resource.h\"\n#include \"resmgr.h\"\n\n#include \"CondorPrefExps.h\"\n#include \"CondorPendingJobs.h\"\n\n\/*\n * Handle async events coming in to the startd.\n *\/\n\nint command_startjob(Sock *, struct sockaddr_in *, resource_id_t,bool JobAlreadyGot=false);\nint command_reqservice __P((Sock *, struct sockaddr_in *, resource_id_t)); \nint MatchInfo(resource_info_t* rip, char* str);\n\nextern int polls_per_update;\nextern int last_timeout;\nextern int capab_timeout;\nextern char *collector_host;\nextern char *alt_collector_host;\nextern int coll_sock;\n\n\/\/ CHANGE -> N ANANd\n\/\/extern CONTEXT *template_context;\nextern ClassAd* template_ClassAd;\n\nextern ClassAd *resource_context __P((resource_info_t *));\n\nextern \"C\" void event_timeout(int sig);\n\nvolatile int want_reconfig = 0;\nint polls = 0;\n\nstatic char *_FileName_ = __FILE__;\n\nvoid update_central_mgr __P((void));\n\nstatic int eval_state(resource_info_t* rip)\n{\n int start = FALSE, tmp;\n resource_context(rip);\n if (rip->r_state == SYSTEM)\n resmgr_changestate(rip->r_rid, NO_JOB);\n if (rip->r_state == NO_JOB)\n {\n (rip->r_context)->EvalBool(\"START\",template_ClassAd,start);\n if(CondorPendingJobs::AreTherePendingJobs(rip->r_rid))\n {\n dprintf(D_ALWAYS,\"Identified a pending job\\n\");\n if(MatchInfo(rip,CondorPendingJobs::CapabString(rip->r_rid)))\n\tdprintf(D_ALWAYS,\"Match Info FAILED!!!\\n\");\n else\n {\n\tSock* sock=CondorPendingJobs::RetSock(rip->r_rid);\n\tstruct sockaddr_in* from = CondorPendingJobs::RespondAddr(rip->r_rid);\n\tCondorPendingJobs::Status status = \n\t CondorPendingJobs::Client(rip->r_rid,rip->r_client);\n\tCondorPendingJobs::Status status1 =\n\t CondorPendingJobs::ScheddInterval(rip->r_rid,rip->r_interval);\n\t\n\tif((status!=CondorPendingJobs::eOK)||(status1!=CondorPendingJobs::eOK))\n\t dprintf(D_ALWAYS,\"Simulated Request Service FAILED!!!\\n\"); \n\telse\n\t dprintf(D_ALWAYS,\"Simulated Request Service succeeded!\\n\");\n\n\tCondorPendingJobs::ClientMachine(rip->r_rid,rip->r_clientmachine);\n\tcommand_startjob(sock,from,rip->r_rid, true);\n }\n }\n }\n if (rip->r_pid != NO_PID && !rip->r_jobcontext) \n {\n EXCEPT(\"resource allocated, but no job context.\\n\");\n }\n\n if (!rip->r_jobcontext)\n return 0;\n \n if (rip->r_state == CHECKPOINTING) \n {\n if (rip->r_universe == VANILLA) \n {\n if(((rip->r_context)->EvalBool(\"KILL_VANILLA\",rip->r_jobcontext,tmp))==0 \n\t &&((rip->r_context)->EvalBool(\"KILL\",rip->r_context,tmp))==0 )\n {\n\tEXCEPT(\"Can't evaluate KILL\\n\");\n }\n } \n else \n {\n if(((rip->r_context)->EvalBool(\"KILL\",rip->r_jobcontext,tmp))==0)\n {\n\tEXCEPT(\"Can't evaluate KILL\\n\");\n }\n }\n if (tmp) \n {\n event_killall(rip->r_rid, NO_JID, NO_TID);\n return 0;\n }\n }\n\n if (rip->r_state == SUSPENDED) \n {\n if (rip->r_universe == VANILLA) \n {\n if(((((rip->r_context)->EvalBool(\"VACATE_VANILLA\",rip->r_jobcontext,tmp))==0))&&(((rip->r_context)->EvalBool(\"VACATE\",rip->r_jobcontext,tmp))==0))\n {\n\tEXCEPT(\"Can't evaluate VACATE\\n\");\n }\n } \n else \n {\n if (((rip->r_context)->EvalBool(\"VACATE\",rip->r_jobcontext,tmp))==0)\n {\n\tEXCEPT(\"Can't evaluate VACATE\\n\");\n }\n }\n if (tmp) \n {\n event_vacate(rip->r_rid, NO_JID, NO_TID);\n return 0;\n }\n }\n\n if (rip->r_state == JOB_RUNNING) \n {\n if (rip->r_universe == VANILLA) \n {\n if((((rip->r_context)->EvalBool(\"SUSPEND_VANILLA\",rip->r_jobcontext,tmp))==0)&&((rip->r_context)->EvalBool(\"SUSPEND\",rip->r_jobcontext,tmp))==0)\n {\n\t\t EXCEPT(\"Can't evaluate SUSPEND\\n\");\n }\n } \n else \n {\n if(((rip->r_context)->EvalBool(\"SUSPEND\",rip->r_jobcontext,tmp))==0)\n {\n\t\t EXCEPT(\"Can't evaluate SUSPEND\\n\");\n }\n }\n if (tmp) \n {\n#if 0\n if (rip->r_claimed)\t\t\/* Why call vacate_client here? *\/\n\t\t vacate_client(rip->r_rid);\n#endif\n event_suspend(rip->r_rid, NO_JID, NO_TID);\n return 0;\n }\n }\n\n if (rip->r_state == SUSPENDED)\n {\n if (rip->r_universe == VANILLA) \n {\n if((((rip->r_context)->EvalBool(\"CONTINUE_VANILLA\",rip->r_jobcontext,tmp))==0)&&((rip->r_context)->EvalBool(\"CONTINUE\",rip->r_jobcontext,tmp))==0)\n {\n\tEXCEPT(\"Can't evaluate CONTINUE\\n\");\n }\n } \n else \n {\n if(((rip->r_context)->EvalBool(\"CONTINUE\",rip->r_jobcontext,tmp))==0)\n {\n\tEXCEPT(\"Can't evaluate CONTINUE\\n\");\n }\n }\n if (tmp) \n {\n event_continue(rip->r_rid, NO_JID, NO_TID);\n return 0;\n }\n }\n return 0;\n}\n\nstatic int\ncheck_claims(resource_info_t* rip)\n{\n\tif (rip->r_claimed == TRUE) {\n\t\tif ((time(NULL) - rip->r_receivetime) > 2 * rip->r_interval) {\n\t\t\tdprintf(D_ALWAYS, \"Capability (%s) timed out\\n\",\n\t\t\t\trip->r_capab);\n\t\t\trip->r_claimed = FALSE;\n\t\t\tfree(rip->r_capab);\n\t\t\tfree(rip->r_client);\n\t\t\trip->r_capab = NULL;\n\t\t\trip->r_client = NULL;\t\n\t\t}\n\t} else if (rip->r_capab) {\n\t\tif (time(NULL) - rip->r_captime > capab_timeout) {\n\t\t\tdprintf(D_ALWAYS, \"Capability (%s) timed out\\n\",\n\t\t\t\trip->r_capab);\n\t\t\trip->r_claimed = FALSE;\n\t\t\tfree(rip->r_capab);\n\t\t\tfree(rip->r_client);\n\t\t\trip->r_capab = NULL;\n\t\t\trip->r_client = NULL;\n\t\t}\n\t}\n\treturn 0;\n}\n\nvoid\nevent_timeout(int sig)\n{\n\tresmgr_walk(eval_state);\n\tresmgr_walk(check_claims);\n\tif (polls == 0)\n\t\tupdate_central_mgr();\n\tif (++polls >= polls_per_update)\n\t\tpolls = 0;\n\tlast_timeout = (int)time((time_t *)0);\n}\n\nvoid\nevent_sigchld(int sig)\n{\n\tint pid, status;\n\tresource_id_t rid;\n\tresource_info_t *rip;\n\tchar tmp[80];\n\tdprintf(D_ALWAYS,\"Handling SIGCHLD\\n\");\n\n\twhile ((pid = waitpid(-1, &status, WNOHANG|WUNTRACED)) > 0 ) {\n\t\tif (WIFSTOPPED(status)) {\n\t\t\tdprintf(D_ALWAYS, \"pid %d stopped.\\n\", pid);\n\t\t\tcontinue;\n\t\t}\n\t\trip = resmgr_getbypid(pid);\n\t\tif (rip == NULL) {\n\t\t\tEXCEPT(\"SIGCHLD from job on non-existing resource??\");\n\t\t}\n\t\tif (WIFSIGNALED(status))\n\t\t\tdprintf(D_ALWAYS, \"pid %d died on signal %d\\n\",\n\t\t\t\tpid, WTERMSIG(status));\n\t\telse\n\t\t\tdprintf(D_ALWAYS, \"pid %d exitex with status %d\\n\",\n\t\t\t\tpid, WEXITSTATUS(status));\n\t\tsprintf(tmp,\"RemoteUser=%s\",(rip->r_user));\n\t\t(rip->r_context)->Insert(tmp);\n\t\tresmgr_changestate(rip->r_rid, NO_JOB);\n\t\tevent_exited(rip->r_rid, NO_JID, NO_TID);\n\t}\n}\n\n\/\/ void\n\/\/ event_sigchld(sig)\n\/\/ \tint sig;\n\/\/ {\n\/\/ \tint pid, status;\n\/\/ \tresource_id_t rid;\n\/\/ \tresource_info_t *rip;\n\/\/ \tELEM tmp;\n\n\/\/ \twhile ((pid = waitpid(-1, &status, WNOHANG|WUNTRACED)) > 0 ) {\n\/\/ \t\tif (WIFSTOPPED(status)) {\n\/\/ \t\t\tdprintf(D_ALWAYS, \"pid %d stopped.\\n\", pid);\n\/\/ \t\t\tcontinue;\n\/\/ \t\t}\n\/\/ \t\trip = resmgr_getbypid(pid);\n\/\/ \t\tif (rip == NULL) {\n\/\/ \t\t\tEXCEPT(\"SIGCHLD from job on non-existing resource??\");\n\/\/ \t\t}\n\/\/ \t\tif (WIFSIGNALED(status))\n\/\/ \t\t\tdprintf(D_ALWAYS, \"pid %d died on signal %d\\n\",\n\/\/ \t\t\t\tpid, WTERMSIG(status));\n\/\/ \t\telse\n\/\/ \t\t\tdprintf(D_ALWAYS, \"pid %d exitex with status %d\\n\",\n\/\/ \t\t\t\tpid, WEXITSTATUS(status));\n\/\/ \t\ttmp.type = STRING;\n\/\/ \t\trip->r_user = \"\";\n\/\/ \t\ttmp.s_val = rip->r_user;\n\/\/ \t\tstore_stmt(build_expr(\"RemoteUser\", &tmp), rip->r_context);\n\/\/ \t\tresmgr_changestate(rip->r_rid, NO_JOB);\n\/\/ \t\tevent_exited(rip->r_rid, NO_JID, NO_TID);\n\/\/ \t}\n\/\/ }\n\nvoid\nevent_sighup(int sig)\n{\n\twant_reconfig = 1;\n}\n\nvoid\nevent_sigterm(int sig)\n{\n\tdprintf(D_ALWAYS, \"Got SIGTERM. Freeing resources and exiting.\\n\");\n\tresmgr_vacateall();\n}\n\nvoid event_sigint(int sig)\t\/* sigint_handler *\/\n{\n\tdprintf(D_ALWAYS, \"Killed by SIGINT\\n\");\n\texit(0);\n}\n\nvoid AccountForPrefExps(resource_info_t* rip)\n{\n if(rip->r_state!=JOB_RUNNING)\n {\n \/\/ nothing to be done: possibly restore the\n \/\/ Requirements expression\n CondorPrefExps::RestoreReqEx(rip->r_context);\n return;\n }\n \n \/\/ A job is running, we need to modify the Requirements expression of \n \/\/ our ad suitably\n\n ClassAd* job = rip->r_jobcontext;\n ClassAd* mc = rip->r_context;\n\n CondorPrefExps::ModifyReqEx(mc,job);\n}\n\nstatic int send_resource_context(resource_info_t* rip)\n{\n\tClassAd *cp;\n\n\tdprintf(D_ALWAYS, \"send_resource_context called.\\n\");\n\tAccountForPrefExps(rip);\n\t\/*ForDebugging(rip);*\/\n\tcp = resource_context(rip);\n\tsend_classad_to_machine(collector_host, COLLECTOR_UDP_COMM_PORT,\n\t\t\t\t\t\t\tcoll_sock, cp);\n\tif (alt_collector_host)\n\t\tsend_classad_to_machine(alt_collector_host, COLLECTOR_UDP_COMM_PORT,\n\t\t\t\t\t\t\t\tcoll_sock, cp);\n\treturn 0;\n}\n\nvoid update_central_mgr()\n{\n\tdprintf(D_ALWAYS, \"update_central_manager called.\\n\");\n\tresmgr_walk(send_resource_context);\n}\n<commit_msg>use constants from condor_attributes.h; evaluate Requirements rather than START; don't update RemoteUser when it can be NULL<commit_after>#include <sys\/types.h>\n#include <sys\/wait.h>\n\n#include \"condor_debug.h\"\n#include \"condor_types.h\"\n#include \"condor_attributes.h\"\n#include \"condor_expressions.h\"\n#include \"condor_mach_status.h\"\n#include \"sched.h\"\n\n#include \"cdefs.h\"\n#include \"event.h\"\n#include \"state.h\"\n#include \"resource.h\"\n#include \"resmgr.h\"\n\n#include \"CondorPrefExps.h\"\n#include \"CondorPendingJobs.h\"\n\n\/*\n * Handle async events coming in to the startd.\n *\/\n\nint command_startjob(Sock *, struct sockaddr_in *, resource_id_t,bool JobAlreadyGot=false);\nint command_reqservice __P((Sock *, struct sockaddr_in *, resource_id_t)); \nint MatchInfo(resource_info_t* rip, char* str);\n\nextern int polls_per_update;\nextern int last_timeout;\nextern int capab_timeout;\nextern char *collector_host;\nextern char *alt_collector_host;\nextern int coll_sock;\n\n\/\/ CHANGE -> N ANANd\n\/\/extern CONTEXT *template_context;\nextern ClassAd* template_ClassAd;\n\nextern ClassAd *resource_context __P((resource_info_t *));\n\nextern \"C\" void event_timeout(int sig);\n\nvolatile int want_reconfig = 0;\nint polls = 0;\n\nstatic char *_FileName_ = __FILE__;\n\nvoid update_central_mgr __P((void));\n\nstatic int eval_state(resource_info_t* rip)\n{\n int start = FALSE, tmp;\n resource_context(rip);\n if (rip->r_state == SYSTEM)\n resmgr_changestate(rip->r_rid, NO_JOB);\n if (rip->r_state == NO_JOB)\n {\n (rip->r_context)->EvalBool(ATTR_REQUIREMENTS,template_ClassAd,start);\n if(CondorPendingJobs::AreTherePendingJobs(rip->r_rid))\n {\n dprintf(D_ALWAYS,\"Identified a pending job\\n\");\n if(MatchInfo(rip,CondorPendingJobs::CapabString(rip->r_rid)))\n\tdprintf(D_ALWAYS,\"Match Info FAILED!!!\\n\");\n else\n {\n\tSock* sock=CondorPendingJobs::RetSock(rip->r_rid);\n\tstruct sockaddr_in* from = CondorPendingJobs::RespondAddr(rip->r_rid);\n\tCondorPendingJobs::Status status = \n\t CondorPendingJobs::Client(rip->r_rid,rip->r_client);\n\tCondorPendingJobs::Status status1 =\n\t CondorPendingJobs::ScheddInterval(rip->r_rid,rip->r_interval);\n\t\n\tif((status!=CondorPendingJobs::eOK)||(status1!=CondorPendingJobs::eOK))\n\t dprintf(D_ALWAYS,\"Simulated Request Service FAILED!!!\\n\"); \n\telse\n\t dprintf(D_ALWAYS,\"Simulated Request Service succeeded!\\n\");\n\n\tCondorPendingJobs::ClientMachine(rip->r_rid,rip->r_clientmachine);\n\tcommand_startjob(sock,from,rip->r_rid, true);\n }\n }\n }\n if (rip->r_pid != NO_PID && !rip->r_jobcontext) \n {\n EXCEPT(\"resource allocated, but no job context.\\n\");\n }\n\n if (!rip->r_jobcontext)\n return 0;\n \n if (rip->r_state == CHECKPOINTING) \n {\n if (rip->r_universe == VANILLA) \n {\n if(((rip->r_context)->EvalBool(\"KILL_VANILLA\",rip->r_jobcontext,tmp))==0 \n\t &&((rip->r_context)->EvalBool(\"KILL\",rip->r_context,tmp))==0 )\n {\n\tEXCEPT(\"Can't evaluate KILL\\n\");\n }\n } \n else \n {\n if(((rip->r_context)->EvalBool(\"KILL\",rip->r_jobcontext,tmp))==0)\n {\n\tEXCEPT(\"Can't evaluate KILL\\n\");\n }\n }\n if (tmp) \n {\n event_killall(rip->r_rid, NO_JID, NO_TID);\n return 0;\n }\n }\n\n if (rip->r_state == SUSPENDED) \n {\n if (rip->r_universe == VANILLA) \n {\n if(((((rip->r_context)->EvalBool(\"VACATE_VANILLA\",rip->r_jobcontext,tmp))==0))&&(((rip->r_context)->EvalBool(\"VACATE\",rip->r_jobcontext,tmp))==0))\n {\n\tEXCEPT(\"Can't evaluate VACATE\\n\");\n }\n } \n else \n {\n if (((rip->r_context)->EvalBool(\"VACATE\",rip->r_jobcontext,tmp))==0)\n {\n\tEXCEPT(\"Can't evaluate VACATE\\n\");\n }\n }\n if (tmp) \n {\n event_vacate(rip->r_rid, NO_JID, NO_TID);\n return 0;\n }\n }\n\n if (rip->r_state == JOB_RUNNING) \n {\n if (rip->r_universe == VANILLA) \n {\n if((((rip->r_context)->EvalBool(\"SUSPEND_VANILLA\",rip->r_jobcontext,tmp))==0)&&((rip->r_context)->EvalBool(\"SUSPEND\",rip->r_jobcontext,tmp))==0)\n {\n\t\t EXCEPT(\"Can't evaluate SUSPEND\\n\");\n }\n } \n else \n {\n if(((rip->r_context)->EvalBool(\"SUSPEND\",rip->r_jobcontext,tmp))==0)\n {\n\t\t EXCEPT(\"Can't evaluate SUSPEND\\n\");\n }\n }\n if (tmp) \n {\n#if 0\n if (rip->r_claimed)\t\t\/* Why call vacate_client here? *\/\n\t\t vacate_client(rip->r_rid);\n#endif\n event_suspend(rip->r_rid, NO_JID, NO_TID);\n return 0;\n }\n }\n\n if (rip->r_state == SUSPENDED)\n {\n if (rip->r_universe == VANILLA) \n {\n if((((rip->r_context)->EvalBool(\"CONTINUE_VANILLA\",rip->r_jobcontext,tmp))==0)&&((rip->r_context)->EvalBool(\"CONTINUE\",rip->r_jobcontext,tmp))==0)\n {\n\tEXCEPT(\"Can't evaluate CONTINUE\\n\");\n }\n } \n else \n {\n if(((rip->r_context)->EvalBool(\"CONTINUE\",rip->r_jobcontext,tmp))==0)\n {\n\tEXCEPT(\"Can't evaluate CONTINUE\\n\");\n }\n }\n if (tmp) \n {\n event_continue(rip->r_rid, NO_JID, NO_TID);\n return 0;\n }\n }\n return 0;\n}\n\nstatic int\ncheck_claims(resource_info_t* rip)\n{\n\tif (rip->r_claimed == TRUE) {\n\t\tif ((time(NULL) - rip->r_receivetime) > 2 * rip->r_interval) {\n\t\t\tdprintf(D_ALWAYS, \"Capability (%s) timed out\\n\",\n\t\t\t\trip->r_capab);\n\t\t\trip->r_claimed = FALSE;\n\t\t\tfree(rip->r_capab);\n\t\t\tfree(rip->r_client);\n\t\t\trip->r_capab = NULL;\n\t\t\trip->r_client = NULL;\t\n\t\t}\n\t} else if (rip->r_capab) {\n\t\tif (time(NULL) - rip->r_captime > capab_timeout) {\n\t\t\tdprintf(D_ALWAYS, \"Capability (%s) timed out\\n\",\n\t\t\t\trip->r_capab);\n\t\t\trip->r_claimed = FALSE;\n\t\t\tfree(rip->r_capab);\n\t\t\tfree(rip->r_client);\n\t\t\trip->r_capab = NULL;\n\t\t\trip->r_client = NULL;\n\t\t}\n\t}\n\treturn 0;\n}\n\nvoid\nevent_timeout(int sig)\n{\n\tresmgr_walk(eval_state);\n\tresmgr_walk(check_claims);\n\tif (polls == 0)\n\t\tupdate_central_mgr();\n\tif (++polls >= polls_per_update)\n\t\tpolls = 0;\n\tlast_timeout = (int)time((time_t *)0);\n}\n\nvoid\nevent_sigchld(int sig)\n{\n\tint pid, status;\n\tresource_id_t rid;\n\tresource_info_t *rip;\n\tchar tmp[80];\n\tdprintf(D_ALWAYS,\"Handling SIGCHLD\\n\");\n\n\twhile ((pid = waitpid(-1, &status, WNOHANG|WUNTRACED)) > 0 ) {\n\t\tif (WIFSTOPPED(status)) {\n\t\t\tdprintf(D_ALWAYS, \"pid %d stopped.\\n\", pid);\n\t\t\tcontinue;\n\t\t}\n\t\trip = resmgr_getbypid(pid);\n\t\tif (rip == NULL) {\n\t\t\tEXCEPT(\"SIGCHLD from job on non-existing resource??\");\n\t\t}\n\t\tif (WIFSIGNALED(status))\n\t\t\tdprintf(D_ALWAYS, \"pid %d died on signal %d\\n\",\n\t\t\t\tpid, WTERMSIG(status));\n\t\telse\n\t\t\tdprintf(D_ALWAYS, \"pid %d exitex with status %d\\n\",\n\t\t\t\tpid, WEXITSTATUS(status));\n#if 0\n\t\t\/\/ ??? Why update RemoteUser here? rip->r_user could be NULL!\n\t\tsprintf(tmp,\"RemoteUser=%s\",(rip->r_user));\n\t\t(rip->r_context)->Insert(tmp);\n#endif\n\t\tresmgr_changestate(rip->r_rid, NO_JOB);\n\t\tevent_exited(rip->r_rid, NO_JID, NO_TID);\n\t}\n}\n\n\/\/ void\n\/\/ event_sigchld(sig)\n\/\/ \tint sig;\n\/\/ {\n\/\/ \tint pid, status;\n\/\/ \tresource_id_t rid;\n\/\/ \tresource_info_t *rip;\n\/\/ \tELEM tmp;\n\n\/\/ \twhile ((pid = waitpid(-1, &status, WNOHANG|WUNTRACED)) > 0 ) {\n\/\/ \t\tif (WIFSTOPPED(status)) {\n\/\/ \t\t\tdprintf(D_ALWAYS, \"pid %d stopped.\\n\", pid);\n\/\/ \t\t\tcontinue;\n\/\/ \t\t}\n\/\/ \t\trip = resmgr_getbypid(pid);\n\/\/ \t\tif (rip == NULL) {\n\/\/ \t\t\tEXCEPT(\"SIGCHLD from job on non-existing resource??\");\n\/\/ \t\t}\n\/\/ \t\tif (WIFSIGNALED(status))\n\/\/ \t\t\tdprintf(D_ALWAYS, \"pid %d died on signal %d\\n\",\n\/\/ \t\t\t\tpid, WTERMSIG(status));\n\/\/ \t\telse\n\/\/ \t\t\tdprintf(D_ALWAYS, \"pid %d exitex with status %d\\n\",\n\/\/ \t\t\t\tpid, WEXITSTATUS(status));\n\/\/ \t\ttmp.type = STRING;\n\/\/ \t\trip->r_user = \"\";\n\/\/ \t\ttmp.s_val = rip->r_user;\n\/\/ \t\tstore_stmt(build_expr(\"RemoteUser\", &tmp), rip->r_context);\n\/\/ \t\tresmgr_changestate(rip->r_rid, NO_JOB);\n\/\/ \t\tevent_exited(rip->r_rid, NO_JID, NO_TID);\n\/\/ \t}\n\/\/ }\n\nvoid\nevent_sighup(int sig)\n{\n\twant_reconfig = 1;\n}\n\nvoid\nevent_sigterm(int sig)\n{\n\tdprintf(D_ALWAYS, \"Got SIGTERM. Freeing resources and exiting.\\n\");\n\tresmgr_vacateall();\n}\n\nvoid event_sigint(int sig)\t\/* sigint_handler *\/\n{\n\tdprintf(D_ALWAYS, \"Killed by SIGINT\\n\");\n\texit(0);\n}\n\nvoid AccountForPrefExps(resource_info_t* rip)\n{\n if(rip->r_state!=JOB_RUNNING)\n {\n \/\/ nothing to be done: possibly restore the\n \/\/ Requirements expression\n CondorPrefExps::RestoreReqEx(rip->r_context);\n return;\n }\n \n \/\/ A job is running, we need to modify the Requirements expression of \n \/\/ our ad suitably\n\n ClassAd* job = rip->r_jobcontext;\n ClassAd* mc = rip->r_context;\n\n CondorPrefExps::ModifyReqEx(mc,job);\n}\n\nstatic int send_resource_context(resource_info_t* rip)\n{\n\tClassAd *cp;\n\n\tdprintf(D_ALWAYS, \"send_resource_context called.\\n\");\n\tAccountForPrefExps(rip);\n\t\/*ForDebugging(rip);*\/\n\tcp = resource_context(rip);\n\tsend_classad_to_machine(collector_host, COLLECTOR_UDP_COMM_PORT,\n\t\t\t\t\t\t\tcoll_sock, cp);\n\tif (alt_collector_host)\n\t\tsend_classad_to_machine(alt_collector_host, COLLECTOR_UDP_COMM_PORT,\n\t\t\t\t\t\t\t\tcoll_sock, cp);\n\treturn 0;\n}\n\nvoid update_central_mgr()\n{\n\tdprintf(D_ALWAYS, \"update_central_manager called.\\n\");\n\tresmgr_walk(send_resource_context);\n}\n<|endoftext|>"} {"text":"<commit_before>#pragma once\n\n#if defined(_WIN32)\n#include <windows.h>\n#elif !defined(EMSCRIPTEN)\n#include <dlfcn.h>\n#endif\n\n#include <string>\n\n#ifndef EMSCRIPTEN\nnamespace processwarp {\nnamespace DynamicLibrary {\n\n\/** Type for dynamic link library handler. *\/\n#ifdef _WIN32\ntypedef HMODULE lib_handler_t;\n#else\ntypedef void* lib_handler_t;\n#endif\n\/** Type for external function pointer. *\/\ntypedef void (*external_func_t)();\n\nlib_handler_t open_lib(const std::string& name);\nexternal_func_t get_func(lib_handler_t handler, const std::string& name);\nvoid close_lib(lib_handler_t handler);\n\n} \/\/ namespace DynamicLibrary\n} \/\/ namespace processwarp\n#endif\n<commit_msg>fix a wrong parameter name<commit_after>#pragma once\n\n#if defined(_WIN32)\n#include <windows.h>\n#elif !defined(EMSCRIPTEN)\n#include <dlfcn.h>\n#endif\n\n#include <string>\n\n#ifndef EMSCRIPTEN\nnamespace processwarp {\nnamespace DynamicLibrary {\n\n\/** Type for dynamic link library handler. *\/\n#ifdef _WIN32\ntypedef HMODULE lib_handler_t;\n#else\ntypedef void* lib_handler_t;\n#endif\n\/** Type for external function pointer. *\/\ntypedef void (*external_func_t)();\n\nlib_handler_t open_lib(const std::string& fname);\nexternal_func_t get_func(lib_handler_t handler, const std::string& name);\nvoid close_lib(lib_handler_t handler);\n\n} \/\/ namespace DynamicLibrary\n} \/\/ namespace processwarp\n#endif\n<|endoftext|>"} {"text":"<commit_before>#include <fstream>\n#include <json\/json.h>\n#include \"GraphSerializer.hpp\"\n\nnamespace tsp\n{\n static bool validateGraph(const Json::Value &root)\n {\n return root.isObject() && root[\"nodes\"].isArray() && root[\"edges\"].isArray();\n }\n\n bool GraphSerializer::deserialize(Graph &graph, std::istream& is)\n {\n Json::Value root;\n Json::Reader reader;\n\n if(!reader.parse(is, root, false))\n return false;\n if(!validateGraph(root))\n return false;\n\n \/\/ deserialize nodes\n Json::Value &nodes = root[\"nodes\"];\n graph.resize(nodes.size());\n for(unsigned int i = 0; nodes.size(); ++i)\n graph[i] = Node(nodes[i][\"id\"].asInt(), nodes[i][\"x\"].asInt(), nodes[i][\"y\"].asInt());\n\n return true;\n }\n\n bool GraphSerializer::serialize(Graph &graph, std::ostream& os)\n {\n Json::StyledStreamWriter writer;\n Json::Value root;\n\n root[\"nodes\"] = Json::Value(Json::arrayValue);\n \/\/ serialize nodes\n root[\"nodes\"].resize(graph.size());\n Json::Value &nodes = root[\"nodes\"];\n for(unsigned int i = 0; i < nodes.size(); ++i)\n {\n nodes[i][\"id\"] = graph[i].id();\n nodes[i][\"x\"] = graph[i].x();\n nodes[i][\"y\"] = graph[i].y();\n }\n\n writer.write(os, root);\n\n return true;\n }\n\n bool GraphSerializer::load(Graph &graph, const std::string& file)\n {\n std::ifstream is(file);\n return deserialize(graph, is);\n }\n\n bool GraphSerializer::save(Graph &graph, const std::string& file)\n {\n std::ofstream os(file);\n return serialize(graph, os);\n }\n}\n\n\n<commit_msg>Fix Graph validation<commit_after>#include <fstream>\n#include <json\/json.h>\n#include \"GraphSerializer.hpp\"\n\nnamespace tsp\n{\n static bool validateGraph(const Json::Value &root)\n {\n return root.isObject() && root[\"nodes\"].isArray();\n }\n\n bool GraphSerializer::deserialize(Graph &graph, std::istream& is)\n {\n Json::Value root;\n Json::Reader reader;\n\n if(!reader.parse(is, root, false))\n return false;\n if(!validateGraph(root))\n return false;\n\n \/\/ deserialize nodes\n Json::Value &nodes = root[\"nodes\"];\n graph.resize(nodes.size());\n for(unsigned int i = 0; nodes.size(); ++i)\n graph[i] = Node(nodes[i][\"id\"].asInt(), nodes[i][\"x\"].asInt(), nodes[i][\"y\"].asInt());\n\n return true;\n }\n\n bool GraphSerializer::serialize(Graph &graph, std::ostream& os)\n {\n Json::StyledStreamWriter writer;\n Json::Value root;\n\n root[\"nodes\"] = Json::Value(Json::arrayValue);\n \/\/ serialize nodes\n root[\"nodes\"].resize(graph.size());\n Json::Value &nodes = root[\"nodes\"];\n for(unsigned int i = 0; i < nodes.size(); ++i)\n {\n nodes[i][\"id\"] = graph[i].id();\n nodes[i][\"x\"] = graph[i].x();\n nodes[i][\"y\"] = graph[i].y();\n }\n\n writer.write(os, root);\n\n return true;\n }\n\n bool GraphSerializer::load(Graph &graph, const std::string& file)\n {\n std::ifstream is(file);\n return deserialize(graph, is);\n }\n\n bool GraphSerializer::save(Graph &graph, const std::string& file)\n {\n std::ofstream os(file);\n return serialize(graph, os);\n }\n}\n\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n\n This macro will add histograms from a list of root files and write them\n to a target root file. The target file is newly created and must not be\n identical to one of the source files.\n\n Syntax:\n\n hist_add targetfile source1 source2 ...\n\n Author: Sven A. Schmidt, sven.schmidt@cern.ch\n Date: 13.2.2001\n\n This code is based on the hadd.C example by Rene Brun and Dirk Geppert,\n which had a problem with directories more than one level deep.\n (see macro hadd_old.C for this previous implementation).\n \n I have tested this macro on rootfiles with one and two dimensional \n histograms, and two levels of subdirectories. Feel free to send comments \n or bug reports to me.\n\n *\/\n\n\n#include <TROOT.h>\n#include \"TFile.h\"\n#include \"TH1.h\"\n#include \"TTree.h\"\n#include \"TKey.h\"\n#include <string.h>\n#include <iostream.h>\n\nTROOT Root( \"hist_add\", \"Histogram Merger\" );\n\nTList *FileList;\nTFile *Target;\n\nvoid MergeRootfile( TDirectory *target, TList *sourcelist );\n\n\nint main( int argc, char **argv ) {\n\n FileList = new TList();\n\n if ( argc < 4 ) {\n cout << \"Usage: \" << argv[0] << \" <target> <source1> <source2> ...\\n\";\n cout << \"supply at least two source files for this to make sense... ;-)\\n\";\n exit( -1 );\n }\n\n cout << \"Target file: \" << argv[1] << endl;\n Target = TFile::Open( argv[1], \"RECREATE\" );\n\n for ( int i = 2; i < argc; i++ ) {\n cout << \"Source file \" << i-1 << \": \" << argv[i] << endl;\n FileList->Add( TFile::Open( argv[i] ) );\n }\n\n MergeRootfile( Target, FileList );\n\n}\n\n\n\n\/\/ Merge all files from sourcelist into the target directory.\n\/\/ The directory level (depth) is determined by the target directory's\n\/\/ current level\nvoid MergeRootfile( TDirectory *target, TList *sourcelist ) {\n\n \/\/ cout << \"Target path: \" << target->GetPath() << endl;\n TString path( (char*)strstr( target->GetPath(), \":\" ) );\n path.Remove( 0, 2 );\n\n TFile *first_source = (TFile*)sourcelist->First();\n first_source->cd( path );\n TDirectory *current_sourcedir = gDirectory;\n\n \/\/ loop over all keys in this directory\n TIter nextkey( current_sourcedir->GetListOfKeys() );\n while ( TKey *key = (TKey*)nextkey() ) {\n\n \/\/ read object from first source file\n first_source->cd( path );\n TObject *obj = key->ReadObj();\n\n if ( obj->IsA()->InheritsFrom( \"TH1\" ) ) {\n \/\/ descendant of TH1 -> merge it\n\n \/\/ cout << \"Merging histogram \" << obj->GetName() << endl;\n TH1 *h1 = (TH1*)obj;\n\n \/\/ loop over all source files and add the content of the\n \/\/ correspondant histogram to the one pointed to by \"h1\"\n TFile *nextsource = (TFile*)sourcelist->After( first_source );\n while ( nextsource ) {\n \n \/\/ make sure we are at the correct directory level by cd'ing to path\n nextsource->cd( path );\n TH1 *h2 = (TH1*)gDirectory->Get( h1->GetName() );\n if ( h2 ) {\n h1->Add( h2 );\n delete h2; \/\/ don't know if this is necessary, i.e. if \n \/\/ h2 is created by the call to gDirectory above.\n }\n\n nextsource = (TFile*)sourcelist->After( nextsource );\n }\n\n } else if ( obj->IsA()->InheritsFrom( \"TDirectory\" ) ) {\n \/\/ it's a subdirectory\n\n cout << \"Found subdirectory \" << obj->GetName() << endl;\n\n \/\/ create a new subdir of same name and title in the target file\n target->cd();\n TDirectory *newdir = target->mkdir( obj->GetName(), obj->GetTitle() );\n\n \/\/ newdir is now the starting point of another round of merging\n \/\/ newdir still knows its depth within the target file via\n \/\/ GetPath(), so we can still figure out where we are in the recursion\n MergeRootfile( newdir, sourcelist );\n\n } else {\n \/\/ object is of no type that we know or can handle\n cout << \"Unknown object type, name: \" \n << obj->GetName() << \" title: \" << obj->GetTitle() << endl;\n }\n\n \/\/ now write the merged histogram (which is \"in\" obj) to the target file\n \/\/ note that this will just store obj in the current directory level,\n \/\/ which is not persistent until the complete directory itself is stored\n \/\/ by \"target->Write()\" below\n if ( obj ) {\n target->cd();\n obj->Write( key->GetName() );\n }\n\n } \/\/ while ( ( TKey *key = (TKey*)nextkey() ) )\n\n \/\/ save modifications to target file\n target->Write();\n\n}\n<commit_msg>Remove the statement calling the TROOT constructor.<commit_after>\/*\n\n This macro will add histograms from a list of root files and write them\n to a target root file. The target file is newly created and must not be\n identical to one of the source files.\n\n Syntax:\n\n hist_add targetfile source1 source2 ...\n\n Author: Sven A. Schmidt, sven.schmidt@cern.ch\n Date: 13.2.2001\n\n This code is based on the hadd.C example by Rene Brun and Dirk Geppert,\n which had a problem with directories more than one level deep.\n (see macro hadd_old.C for this previous implementation).\n \n I have tested this macro on rootfiles with one and two dimensional \n histograms, and two levels of subdirectories. Feel free to send comments \n or bug reports to me.\n\n *\/\n\n\n#include \"TFile.h\"\n#include \"TH1.h\"\n#include \"TTree.h\"\n#include \"TKey.h\"\n#include <string.h>\n#include <iostream.h>\n\nTList *FileList;\nTFile *Target;\n\nvoid MergeRootfile( TDirectory *target, TList *sourcelist );\n\n\nint main( int argc, char **argv ) {\n\n FileList = new TList();\n\n if ( argc < 4 ) {\n cout << \"Usage: \" << argv[0] << \" <target> <source1> <source2> ...\\n\";\n cout << \"supply at least two source files for this to make sense... ;-)\\n\";\n exit( -1 );\n }\n\n cout << \"Target file: \" << argv[1] << endl;\n Target = TFile::Open( argv[1], \"RECREATE\" );\n\n for ( int i = 2; i < argc; i++ ) {\n cout << \"Source file \" << i-1 << \": \" << argv[i] << endl;\n FileList->Add( TFile::Open( argv[i] ) );\n }\n\n MergeRootfile( Target, FileList );\n\n}\n\n\n\n\/\/ Merge all files from sourcelist into the target directory.\n\/\/ The directory level (depth) is determined by the target directory's\n\/\/ current level\nvoid MergeRootfile( TDirectory *target, TList *sourcelist ) {\n\n \/\/ cout << \"Target path: \" << target->GetPath() << endl;\n TString path( (char*)strstr( target->GetPath(), \":\" ) );\n path.Remove( 0, 2 );\n\n TFile *first_source = (TFile*)sourcelist->First();\n first_source->cd( path );\n TDirectory *current_sourcedir = gDirectory;\n\n \/\/ loop over all keys in this directory\n TIter nextkey( current_sourcedir->GetListOfKeys() );\n while ( TKey *key = (TKey*)nextkey() ) {\n\n \/\/ read object from first source file\n first_source->cd( path );\n TObject *obj = key->ReadObj();\n\n if ( obj->IsA()->InheritsFrom( \"TH1\" ) ) {\n \/\/ descendant of TH1 -> merge it\n\n \/\/ cout << \"Merging histogram \" << obj->GetName() << endl;\n TH1 *h1 = (TH1*)obj;\n\n \/\/ loop over all source files and add the content of the\n \/\/ correspondant histogram to the one pointed to by \"h1\"\n TFile *nextsource = (TFile*)sourcelist->After( first_source );\n while ( nextsource ) {\n \n \/\/ make sure we are at the correct directory level by cd'ing to path\n nextsource->cd( path );\n TH1 *h2 = (TH1*)gDirectory->Get( h1->GetName() );\n if ( h2 ) {\n h1->Add( h2 );\n delete h2; \/\/ don't know if this is necessary, i.e. if \n \/\/ h2 is created by the call to gDirectory above.\n }\n\n nextsource = (TFile*)sourcelist->After( nextsource );\n }\n\n } else if ( obj->IsA()->InheritsFrom( \"TDirectory\" ) ) {\n \/\/ it's a subdirectory\n\n cout << \"Found subdirectory \" << obj->GetName() << endl;\n\n \/\/ create a new subdir of same name and title in the target file\n target->cd();\n TDirectory *newdir = target->mkdir( obj->GetName(), obj->GetTitle() );\n\n \/\/ newdir is now the starting point of another round of merging\n \/\/ newdir still knows its depth within the target file via\n \/\/ GetPath(), so we can still figure out where we are in the recursion\n MergeRootfile( newdir, sourcelist );\n\n } else {\n \/\/ object is of no type that we know or can handle\n cout << \"Unknown object type, name: \" \n << obj->GetName() << \" title: \" << obj->GetTitle() << endl;\n }\n\n \/\/ now write the merged histogram (which is \"in\" obj) to the target file\n \/\/ note that this will just store obj in the current directory level,\n \/\/ which is not persistent until the complete directory itself is stored\n \/\/ by \"target->Write()\" below\n if ( obj ) {\n target->cd();\n obj->Write( key->GetName() );\n }\n\n } \/\/ while ( ( TKey *key = (TKey*)nextkey() ) )\n\n \/\/ save modifications to target file\n target->Write();\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/*********************************************************************\n* Software License Agreement (BSD License)\n*\n* Copyright (c) 2012, Willow Garage, Inc.\n* All rights reserved.\n*\n* Redistribution and use in source and binary forms, with or without\n* modification, are permitted provided that the following conditions\n* are met:\n*\n* * Redistributions of source code must retain the above copyright\n* notice, this list of conditions and the following disclaimer.\n* * Redistributions in binary form must reproduce the above\n* copyright notice, this list of conditions and the following\n* disclaimer in the documentation and\/or other materials provided\n* with the distribution.\n* * Neither the name of the Willow Garage nor the names of its\n* contributors may be used to endorse or promote products derived\n* from this software without specific prior written permission.\n*\n* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n* \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n* POSSIBILITY OF SUCH DAMAGE.\n*********************************************************************\/\n\n\/* Author: Ioan Sucan *\/\n\n#include <moveit\/pick_place\/approach_and_translate_stage.h>\n#include <moveit\/trajectory_processing\/trajectory_tools.h>\n#include <eigen_conversions\/eigen_msg.h>\n#include <ros\/console.h>\n\nnamespace pick_place\n{\n\n\/\/ the amount of time (maximum) to wait for achieving a grasp posture\nstatic const double GRASP_POSTURE_COMPLETION_DURATION = 7.0; \/\/ seconds\n\nApproachAndTranslateStage::ApproachAndTranslateStage(const planning_scene::PlanningSceneConstPtr &pre_grasp_scene,\n const planning_scene::PlanningSceneConstPtr &post_grasp_scene,\n const collision_detection::AllowedCollisionMatrixConstPtr &collision_matrix) :\n ManipulationStage(\"approach & translate\"),\n pre_grasp_planning_scene_(pre_grasp_scene),\n post_grasp_planning_scene_(post_grasp_scene),\n collision_matrix_(collision_matrix),\n max_goal_count_(5),\n max_fail_(3),\n max_step_(0.02),\n jump_factor_(3.0)\n{\n}\n\nnamespace\n{\n\nbool isStateCollisionFree(const planning_scene::PlanningScene *planning_scene, \n const collision_detection::AllowedCollisionMatrix *collision_matrix,\n const sensor_msgs::JointState *grasp_posture, \n kinematic_state::JointStateGroup *joint_state_group,\n const std::vector<double> &joint_group_variable_values)\n{\n joint_state_group->setVariableValues(joint_group_variable_values);\n \/\/ apply the grasp posture for the end effector (we always apply it here since it could be the case the sampler changes this posture)\n joint_state_group->getKinematicState()->setStateValues(*grasp_posture);\n return !planning_scene->isStateColliding(*joint_state_group->getKinematicState(), joint_state_group->getName()) && \n planning_scene->isStateFeasible(*joint_state_group->getKinematicState());\n}\n\nbool samplePossibleGoalStates(const ManipulationPlanPtr &plan, const kinematic_state::KinematicState &reference_state, double min_distance, unsigned int attempts) \n{\n \/\/ initialize with scene state \n kinematic_state::KinematicStatePtr token_state(new kinematic_state::KinematicState(reference_state));\n kinematic_state::JointStateGroup *jsg = token_state->getJointStateGroup(plan->planning_group_);\n for (unsigned int j = 0 ; j < attempts ; ++j)\n {\n double min_d = std::numeric_limits<double>::infinity();\n if (plan->goal_sampler_->sample(jsg, *token_state, plan->sampling_attempts_))\n {\n for (std::size_t i = 0 ; i < plan->possible_goal_states_.size() ; ++i)\n {\n double d = plan->possible_goal_states_[i]->getJointStateGroup(plan->planning_group_)->distance(jsg);\n if (d < min_d)\n min_d = d;\n }\n if (min_d >= min_distance)\n {\n plan->possible_goal_states_.push_back(token_state);\n return true;\n }\n }\n }\n return false;\n}\n\nvoid addGraspTrajectory(const ManipulationPlanPtr &plan, const sensor_msgs::JointState &grasp_posture, const std::string &name) \n{\n if (!grasp_posture.name.empty())\n {\n moveit_msgs::RobotTrajectory grasp_traj;\n grasp_traj.joint_trajectory.header = grasp_posture.header;\n grasp_traj.joint_trajectory.joint_names = grasp_posture.name;\n grasp_traj.joint_trajectory.points.resize(1);\n grasp_traj.joint_trajectory.points[0].positions = grasp_posture.position;\n grasp_traj.joint_trajectory.points[0].velocities = grasp_posture.velocity;\n grasp_traj.joint_trajectory.points[0].time_from_start = ros::Duration(GRASP_POSTURE_COMPLETION_DURATION);\n \n plan->trajectories_.push_back(grasp_traj);\n plan->trajectory_descriptions_.push_back(name);\n }\n}\n\n}\n\nbool ApproachAndTranslateStage::evaluate(const ManipulationPlanPtr &plan) const\n{\n \/\/ compute what the maximum distance reported between any two states in the planning group could be\n double min_distance = 0.0;\n const kinematic_model::JointModelGroup *jmg = pre_grasp_planning_scene_->getKinematicModel()->getJointModelGroup(plan->planning_group_);\n const std::vector<const kinematic_model::JointModel*> &jmodels = jmg->getJointModels();\n for (std::size_t j = 0 ; j < jmodels.size() ; ++j)\n min_distance += jmodels[j]->getMaximumExtent() * jmodels[j]->getDistanceFactor();\n \/\/ now remember the value that is 5% of that maximum distance; this is the minimum we would like goal states to vary,\n \/\/ to consider them during the evaluation process\n min_distance *= 0.05;\n \n \/\/ convert approach direction and translation direction to Eigen structures\n Eigen::Vector3d approach_direction, translation_direction;\n tf::vectorMsgToEigen(plan->grasp_.approach_direction, approach_direction);\n tf::vectorMsgToEigen(plan->grasp_.translation_direction, translation_direction);\n \n \/\/ state validity checking during the approach must ensure that the gripper posture is that for pre-grasping\n kinematic_state::StateValidityCallbackFn approach_validCallback = boost::bind(&isStateCollisionFree, pre_grasp_planning_scene_.get(), \n collision_matrix_.get(), &plan->grasp_.pre_grasp_posture, _1, _2);\n \n \/\/ state validity checking during the translation after the grasp must ensure the gripper posture is that of the actual grasp\n kinematic_state::StateValidityCallbackFn translation_validCallback = boost::bind(&isStateCollisionFree, post_grasp_planning_scene_.get(),\n collision_matrix_.get(), &plan->grasp_.grasp_posture, _1, _2);\n do \n {\n for (std::size_t i = 0 ; i < plan->possible_goal_states_.size() && !signal_stop_ ; ++i)\n {\n \/\/ try to compute a straight line path that arrives at the goal using the specified approach direction\n moveit_msgs::RobotTrajectory approach_traj;\n kinematic_state::KinematicStatePtr first_approach_state(new kinematic_state::KinematicState(*plan->possible_goal_states_[i]));\n double d_approach = first_approach_state->getJointStateGroup(plan->planning_group_)->computeCartesianPath(approach_traj, plan->ik_link_name_, -approach_direction,\n false, plan->grasp_.desired_approach_distance, \n max_step_, jump_factor_, approach_validCallback);\n \n \/\/ if we were able to follow the approach direction for sufficient length, try to compute a translation direction\n if (d_approach > plan->grasp_.min_approach_distance && !signal_stop_)\n {\n if (plan->grasp_.desired_translation_distance > 0.0)\n {\n \n \/\/ try to compute a straight line path that moves from the goal in a desired direction\n moveit_msgs::RobotTrajectory translation_traj;\n kinematic_state::KinematicStatePtr last_translation_state(new kinematic_state::KinematicState(*plan->possible_goal_states_[i]));\n double d_translation = last_translation_state->getJointStateGroup(plan->planning_group_)->computeCartesianPath(translation_traj, plan->ik_link_name_, \n translation_direction, true, \n plan->grasp_.desired_translation_distance, \n max_step_, jump_factor_, translation_validCallback);\n \/\/ if sufficient progress was made in the desired direction, we have a goal state that we can consider for future stages\n if (d_translation > plan->grasp_.min_translation_distance && !signal_stop_)\n {\n addGraspTrajectory(plan, plan->grasp_.pre_grasp_posture, \"pre_grasp\");\n \n plan->approach_state_.swap(first_approach_state);\n plan->translation_state_.swap(last_translation_state);\n trajectory_processing::reverseTrajectory(approach_traj);\n trajectory_processing::unwindJointTrajectory(pre_grasp_planning_scene_->getKinematicModel(), approach_traj.joint_trajectory);\n trajectory_processing::unwindJointTrajectory(pre_grasp_planning_scene_->getKinematicModel(), translation_traj.joint_trajectory);\n\n const kinematic_model::JointModelGroup *jmg = pre_grasp_planning_scene_->getKinematicModel()->getJointModelGroup(plan->planning_group_);\n if (jmg)\n {\n const std::vector<moveit_msgs::JointLimits> &jlim = jmg->getVariableLimits();\n time_param_.computeTimeStamps(approach_traj.joint_trajectory, jlim); \n time_param_.computeTimeStamps(translation_traj.joint_trajectory, jlim);\n }\n \n plan->trajectories_.push_back(approach_traj);\n plan->trajectory_descriptions_.push_back(\"approach\");\n \n addGraspTrajectory(plan, plan->grasp_.grasp_posture, \"grasp\");\n \n plan->trajectories_.push_back(translation_traj);\n plan->trajectory_descriptions_.push_back(\"translation\");\n \n return true; \n }\n }\n else\n {\n addGraspTrajectory(plan, plan->grasp_.pre_grasp_posture, \"pre_grasp\");\n \n plan->approach_state_.swap(first_approach_state);\n trajectory_processing::reverseTrajectory(approach_traj);\n trajectory_processing::unwindJointTrajectory(pre_grasp_planning_scene_->getKinematicModel(), approach_traj.joint_trajectory);\n\n const kinematic_model::JointModelGroup *jmg = pre_grasp_planning_scene_->getKinematicModel()->getJointModelGroup(plan->planning_group_);\n if (jmg)\n time_param_.computeTimeStamps(approach_traj.joint_trajectory, jmg->getVariableLimits()); \n \n plan->trajectories_.push_back(approach_traj);\n plan->trajectory_descriptions_.push_back(\"approach\");\n \n addGraspTrajectory(plan, plan->grasp_.grasp_posture, \"grasp\");\n \n return true; \n }\n }\n \n }\n }\n while (plan->possible_goal_states_.size() < max_goal_count_ && !signal_stop_ && samplePossibleGoalStates(plan, pre_grasp_planning_scene_->getCurrentState(), min_distance, max_fail_));\n plan->error_code_.val = moveit_msgs::MoveItErrorCodes::PLANNING_FAILED;\n \n return false;\n}\n\n}\n<commit_msg>reducing default jump factor<commit_after>\/*********************************************************************\n* Software License Agreement (BSD License)\n*\n* Copyright (c) 2012, Willow Garage, Inc.\n* All rights reserved.\n*\n* Redistribution and use in source and binary forms, with or without\n* modification, are permitted provided that the following conditions\n* are met:\n*\n* * Redistributions of source code must retain the above copyright\n* notice, this list of conditions and the following disclaimer.\n* * Redistributions in binary form must reproduce the above\n* copyright notice, this list of conditions and the following\n* disclaimer in the documentation and\/or other materials provided\n* with the distribution.\n* * Neither the name of the Willow Garage nor the names of its\n* contributors may be used to endorse or promote products derived\n* from this software without specific prior written permission.\n*\n* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n* \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n* POSSIBILITY OF SUCH DAMAGE.\n*********************************************************************\/\n\n\/* Author: Ioan Sucan *\/\n\n#include <moveit\/pick_place\/approach_and_translate_stage.h>\n#include <moveit\/trajectory_processing\/trajectory_tools.h>\n#include <eigen_conversions\/eigen_msg.h>\n#include <ros\/console.h>\n\nnamespace pick_place\n{\n\n\/\/ the amount of time (maximum) to wait for achieving a grasp posture\nstatic const double GRASP_POSTURE_COMPLETION_DURATION = 7.0; \/\/ seconds\n\nApproachAndTranslateStage::ApproachAndTranslateStage(const planning_scene::PlanningSceneConstPtr &pre_grasp_scene,\n const planning_scene::PlanningSceneConstPtr &post_grasp_scene,\n const collision_detection::AllowedCollisionMatrixConstPtr &collision_matrix) :\n ManipulationStage(\"approach & translate\"),\n pre_grasp_planning_scene_(pre_grasp_scene),\n post_grasp_planning_scene_(post_grasp_scene),\n collision_matrix_(collision_matrix),\n max_goal_count_(5),\n max_fail_(3),\n max_step_(0.02),\n jump_factor_(2.0)\n{\n}\n\nnamespace\n{\n\nbool isStateCollisionFree(const planning_scene::PlanningScene *planning_scene, \n const collision_detection::AllowedCollisionMatrix *collision_matrix,\n const sensor_msgs::JointState *grasp_posture, \n kinematic_state::JointStateGroup *joint_state_group,\n const std::vector<double> &joint_group_variable_values)\n{\n joint_state_group->setVariableValues(joint_group_variable_values);\n \/\/ apply the grasp posture for the end effector (we always apply it here since it could be the case the sampler changes this posture)\n joint_state_group->getKinematicState()->setStateValues(*grasp_posture);\n return !planning_scene->isStateColliding(*joint_state_group->getKinematicState(), joint_state_group->getName()) && \n planning_scene->isStateFeasible(*joint_state_group->getKinematicState());\n}\n\nbool samplePossibleGoalStates(const ManipulationPlanPtr &plan, const kinematic_state::KinematicState &reference_state, double min_distance, unsigned int attempts) \n{\n \/\/ initialize with scene state \n kinematic_state::KinematicStatePtr token_state(new kinematic_state::KinematicState(reference_state));\n kinematic_state::JointStateGroup *jsg = token_state->getJointStateGroup(plan->planning_group_);\n for (unsigned int j = 0 ; j < attempts ; ++j)\n {\n double min_d = std::numeric_limits<double>::infinity();\n if (plan->goal_sampler_->sample(jsg, *token_state, plan->sampling_attempts_))\n {\n for (std::size_t i = 0 ; i < plan->possible_goal_states_.size() ; ++i)\n {\n double d = plan->possible_goal_states_[i]->getJointStateGroup(plan->planning_group_)->distance(jsg);\n if (d < min_d)\n min_d = d;\n }\n if (min_d >= min_distance)\n {\n plan->possible_goal_states_.push_back(token_state);\n return true;\n }\n }\n }\n return false;\n}\n\nvoid addGraspTrajectory(const ManipulationPlanPtr &plan, const sensor_msgs::JointState &grasp_posture, const std::string &name) \n{\n if (!grasp_posture.name.empty())\n {\n moveit_msgs::RobotTrajectory grasp_traj;\n grasp_traj.joint_trajectory.header = grasp_posture.header;\n grasp_traj.joint_trajectory.joint_names = grasp_posture.name;\n grasp_traj.joint_trajectory.points.resize(1);\n grasp_traj.joint_trajectory.points[0].positions = grasp_posture.position;\n grasp_traj.joint_trajectory.points[0].velocities = grasp_posture.velocity;\n grasp_traj.joint_trajectory.points[0].time_from_start = ros::Duration(GRASP_POSTURE_COMPLETION_DURATION);\n \n plan->trajectories_.push_back(grasp_traj);\n plan->trajectory_descriptions_.push_back(name);\n }\n}\n\n}\n\nbool ApproachAndTranslateStage::evaluate(const ManipulationPlanPtr &plan) const\n{\n \/\/ compute what the maximum distance reported between any two states in the planning group could be\n double min_distance = 0.0;\n const kinematic_model::JointModelGroup *jmg = pre_grasp_planning_scene_->getKinematicModel()->getJointModelGroup(plan->planning_group_);\n const std::vector<const kinematic_model::JointModel*> &jmodels = jmg->getJointModels();\n for (std::size_t j = 0 ; j < jmodels.size() ; ++j)\n min_distance += jmodels[j]->getMaximumExtent() * jmodels[j]->getDistanceFactor();\n \/\/ now remember the value that is 5% of that maximum distance; this is the minimum we would like goal states to vary,\n \/\/ to consider them during the evaluation process\n min_distance *= 0.05;\n \n \/\/ convert approach direction and translation direction to Eigen structures\n Eigen::Vector3d approach_direction, translation_direction;\n tf::vectorMsgToEigen(plan->grasp_.approach_direction, approach_direction);\n tf::vectorMsgToEigen(plan->grasp_.translation_direction, translation_direction);\n \n \/\/ state validity checking during the approach must ensure that the gripper posture is that for pre-grasping\n kinematic_state::StateValidityCallbackFn approach_validCallback = boost::bind(&isStateCollisionFree, pre_grasp_planning_scene_.get(), \n collision_matrix_.get(), &plan->grasp_.pre_grasp_posture, _1, _2);\n \n \/\/ state validity checking during the translation after the grasp must ensure the gripper posture is that of the actual grasp\n kinematic_state::StateValidityCallbackFn translation_validCallback = boost::bind(&isStateCollisionFree, post_grasp_planning_scene_.get(),\n collision_matrix_.get(), &plan->grasp_.grasp_posture, _1, _2);\n do \n {\n for (std::size_t i = 0 ; i < plan->possible_goal_states_.size() && !signal_stop_ ; ++i)\n {\n \/\/ try to compute a straight line path that arrives at the goal using the specified approach direction\n moveit_msgs::RobotTrajectory approach_traj;\n kinematic_state::KinematicStatePtr first_approach_state(new kinematic_state::KinematicState(*plan->possible_goal_states_[i]));\n double d_approach = first_approach_state->getJointStateGroup(plan->planning_group_)->computeCartesianPath(approach_traj, plan->ik_link_name_, -approach_direction,\n false, plan->grasp_.desired_approach_distance, \n max_step_, jump_factor_, approach_validCallback);\n \n \/\/ if we were able to follow the approach direction for sufficient length, try to compute a translation direction\n if (d_approach > plan->grasp_.min_approach_distance && !signal_stop_)\n {\n if (plan->grasp_.desired_translation_distance > 0.0)\n {\n \n \/\/ try to compute a straight line path that moves from the goal in a desired direction\n moveit_msgs::RobotTrajectory translation_traj;\n kinematic_state::KinematicStatePtr last_translation_state(new kinematic_state::KinematicState(*plan->possible_goal_states_[i]));\n double d_translation = last_translation_state->getJointStateGroup(plan->planning_group_)->computeCartesianPath(translation_traj, plan->ik_link_name_, \n translation_direction, true, \n plan->grasp_.desired_translation_distance, \n max_step_, jump_factor_, translation_validCallback);\n \/\/ if sufficient progress was made in the desired direction, we have a goal state that we can consider for future stages\n if (d_translation > plan->grasp_.min_translation_distance && !signal_stop_)\n {\n addGraspTrajectory(plan, plan->grasp_.pre_grasp_posture, \"pre_grasp\");\n \n plan->approach_state_.swap(first_approach_state);\n plan->translation_state_.swap(last_translation_state);\n trajectory_processing::reverseTrajectory(approach_traj);\n trajectory_processing::unwindJointTrajectory(pre_grasp_planning_scene_->getKinematicModel(), approach_traj.joint_trajectory);\n trajectory_processing::unwindJointTrajectory(pre_grasp_planning_scene_->getKinematicModel(), translation_traj.joint_trajectory);\n\n const kinematic_model::JointModelGroup *jmg = pre_grasp_planning_scene_->getKinematicModel()->getJointModelGroup(plan->planning_group_);\n if (jmg)\n {\n const std::vector<moveit_msgs::JointLimits> &jlim = jmg->getVariableLimits();\n time_param_.computeTimeStamps(approach_traj.joint_trajectory, jlim); \n time_param_.computeTimeStamps(translation_traj.joint_trajectory, jlim);\n }\n \n plan->trajectories_.push_back(approach_traj);\n plan->trajectory_descriptions_.push_back(\"approach\");\n \n addGraspTrajectory(plan, plan->grasp_.grasp_posture, \"grasp\");\n \n plan->trajectories_.push_back(translation_traj);\n plan->trajectory_descriptions_.push_back(\"translation\");\n \n return true; \n }\n }\n else\n {\n addGraspTrajectory(plan, plan->grasp_.pre_grasp_posture, \"pre_grasp\");\n \n plan->approach_state_.swap(first_approach_state);\n trajectory_processing::reverseTrajectory(approach_traj);\n trajectory_processing::unwindJointTrajectory(pre_grasp_planning_scene_->getKinematicModel(), approach_traj.joint_trajectory);\n\n const kinematic_model::JointModelGroup *jmg = pre_grasp_planning_scene_->getKinematicModel()->getJointModelGroup(plan->planning_group_);\n if (jmg)\n time_param_.computeTimeStamps(approach_traj.joint_trajectory, jmg->getVariableLimits()); \n \n plan->trajectories_.push_back(approach_traj);\n plan->trajectory_descriptions_.push_back(\"approach\");\n \n addGraspTrajectory(plan, plan->grasp_.grasp_posture, \"grasp\");\n \n return true; \n }\n }\n \n }\n }\n while (plan->possible_goal_states_.size() < max_goal_count_ && !signal_stop_ && samplePossibleGoalStates(plan, pre_grasp_planning_scene_->getCurrentState(), min_distance, max_fail_));\n plan->error_code_.val = moveit_msgs::MoveItErrorCodes::PLANNING_FAILED;\n \n return false;\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before>\n#include <ionCore.h>\n#include <catch.hpp>\n\n\nclass Component\n{};\n\nclass AComponent : public Component\n{};\n\nclass BComponent : public Component\n{};\n\nclass CComponent : public AComponent\n{};\n\nTEST_CASE(\"IEntity::AddComponent\")\n{\n\tIEntity<Component> * Entity = new IEntity<Component>();\n\tAComponent * A = new AComponent();\n\tBComponent * B = new BComponent();\n\tCComponent * C = new CComponent();\n\tAComponent * A2 = new CComponent();\n\n\tREQUIRE(A == Entity->AddComponent(A));\n\tREQUIRE(B == Entity->AddComponent(B));\n\tREQUIRE(C == Entity->AddComponent(C));\n\tREQUIRE(A2 == Entity->AddComponent(A2));\n}\n<commit_msg>Add IEntity::GetComponentCount test<commit_after>\n#include <ionCore.h>\n#include <catch.hpp>\n\n\nclass Component\n{};\n\nclass AComponent : public Component\n{};\n\nclass BComponent : public Component\n{};\n\nclass CComponent : public AComponent\n{};\n\nTEST_CASE(\"IEntity::AddComponent\")\n{\n\tIEntity<Component> * Entity = new IEntity<Component>();\n\tAComponent * A = new AComponent();\n\tBComponent * B = new BComponent();\n\tCComponent * C = new CComponent();\n\tAComponent * A2 = new CComponent();\n\n\tREQUIRE(A == Entity->AddComponent(A));\n\tREQUIRE(A == Entity->AddComponent(A));\n\tREQUIRE(B == Entity->AddComponent(B));\n\tREQUIRE(C == Entity->AddComponent(C));\n\tREQUIRE(A2 == Entity->AddComponent(A2));\n}\n\nTEST_CASE(\"IEntity::GetComponentCount\")\n{\n\tIEntity<Component> * Entity = new IEntity<Component>();\n\tAComponent * A = new AComponent();\n\tBComponent * B = new BComponent();\n\tCComponent * C = new CComponent();\n\tAComponent * A2 = new CComponent();\n\n\tREQUIRE(Entity->GetComponentCount<AComponent>() == 0);\n\tREQUIRE(Entity->GetComponentCount<BComponent>() == 0);\n\tREQUIRE(Entity->GetComponentCount<CComponent>() == 0);\n\tEntity->AddComponent(A);\n\tREQUIRE(Entity->GetComponentCount<AComponent>() == 1);\n\tREQUIRE(Entity->GetComponentCount<BComponent>() == 0);\n\tREQUIRE(Entity->GetComponentCount<CComponent>() == 0);\n\tEntity->AddComponent(A);\n\tREQUIRE(Entity->GetComponentCount<AComponent>() == 2);\n\tREQUIRE(Entity->GetComponentCount<BComponent>() == 0);\n\tREQUIRE(Entity->GetComponentCount<CComponent>() == 0);\n\tEntity->AddComponent(B);\n\tREQUIRE(Entity->GetComponentCount<AComponent>() == 2);\n\tREQUIRE(Entity->GetComponentCount<BComponent>() == 1);\n\tREQUIRE(Entity->GetComponentCount<CComponent>() == 0);\n\tEntity->AddComponent(C);\n\tREQUIRE(Entity->GetComponentCount<AComponent>() == 2);\n\tREQUIRE(Entity->GetComponentCount<BComponent>() == 1);\n\tREQUIRE(Entity->GetComponentCount<CComponent>() == 1);\n\tEntity->AddComponent(A2);\n\tREQUIRE(Entity->GetComponentCount<AComponent>() == 3);\n\tREQUIRE(Entity->GetComponentCount<BComponent>() == 1);\n\tREQUIRE(Entity->GetComponentCount<CComponent>() == 1);\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"domain\/mesh_cartesian.h\"\n\n#include <algorithm>\n#include <cmath>\n#include <vector>\n\n#include <deal.II\/base\/point.h>\n#include <deal.II\/grid\/grid_generator.h>\n#include <deal.II\/base\/tensor.h>\n#include <deal.II\/base\/utilities.h>\n\n#include \"problem\/parameter_types.h\"\n\nnamespace bart {\n\nnamespace domain {\n\ntemplate <int dim>\nMeshCartesian<dim>::MeshCartesian(const std::vector<double> spatial_max,\n const std::vector<int> n_cells,\n const std::string material_mapping)\n : MeshCartesian(spatial_max, n_cells) {\n ParseMaterialMap(material_mapping);\n}\n\n\ntemplate <int dim>\nMeshCartesian<dim>::MeshCartesian(const std::vector<double> spatial_max,\n const std::vector<int> n_cells) {\n\n \/\/ Check lengths of spatial max and n_cells\n AssertThrow(spatial_max.size() == dim,\n dealii::ExcMessage(\"MeshCartesian argument error, incorrect spatial vector size\"));\n AssertThrow(n_cells.size() == dim,\n dealii::ExcMessage(\"MeshCartesian argument error, incorrect number of cells vector size\"));\n \n std::copy(n_cells.begin(), n_cells.end(), n_cells_.begin());\n std::copy(spatial_max.begin(), spatial_max.end(), spatial_max_.begin());\n}\n\ntemplate <int dim>\nvoid MeshCartesian<dim>::FillTriangulation(dealii::Triangulation<dim> &to_fill) {\n \n dealii::Point<dim> diagonal;\n dealii::Point<dim> origin;\n\n for (int i = 0; i < dim; ++i)\n diagonal[i] = spatial_max_[i];\n\n std::vector<unsigned int> number_of_cells{n_cells_.begin(), n_cells_.end()};\n dealii::GridGenerator::subdivided_hyper_rectangle(to_fill, number_of_cells,\n origin, diagonal);\n}\n\ntemplate <int dim>\nvoid MeshCartesian<dim>::ParseMaterialMap(std::string material_mapping) {\n using dealii::Utilities::split_string_list;\n using dealii::Utilities::string_to_int;\n using StringVector = std::vector<std::string>;\n\n StringVector z_blocks = split_string_list(material_mapping, \"\\n\\n\");\n\n std::reverse(z_blocks.begin(), z_blocks.end());\n\n for (unsigned k = 0; k < z_blocks.size(); ++k) {\n StringVector y_line = split_string_list(z_blocks.at(k), \"\\n\");\n std::reverse(y_line.begin(), y_line.end());\n for (unsigned j = 0; j < y_line.size(); ++j) {\n StringVector x_positions = split_string_list(y_line.at(j), \" \");\n for (unsigned i = 0; i < x_positions.size(); ++i) {\n std::array<unsigned, 3> index{i, j, k};\n std::array<int, dim> location;\n for (int dir = 0; dir < dim; ++dir)\n location.at(dir) = index.at(dir);\n material_mapping_[location] = string_to_int(x_positions.at(i));\n }\n n_material_cells_.at(0) = x_positions.size();\n }\n if (dim > 1)\n n_material_cells_.at(1) = y_line.size();\n }\n\n if (dim > 2)\n n_material_cells_.at(2) = z_blocks.size();\n}\n\ntemplate <int dim> \nvoid MeshCartesian<dim>::FillMaterialID(dealii::Triangulation<dim> &to_fill) {\n for (auto cell = to_fill.begin_active(); cell != to_fill.end(); ++cell) {\n if (cell->is_locally_owned()) {\n int material_id = GetMaterialID(cell->center());\n cell->set_material_id(material_id);\n }\n }\n}\n\ntemplate <int dim>\nvoid MeshCartesian<dim>::FillBoundaryID(dealii::Triangulation<dim> &to_fill) {\n using Boundary = bart::problem::Boundary;\n int faces_per_cell = dealii::GeometryInfo<dim>::faces_per_cell;\n double zero_tol = 1.0e-14;\n \n for (auto cell = to_fill.begin_active(); cell != to_fill.end(); ++cell) {\n if (cell->is_locally_owned()) {\n for (int face_id = 0; face_id < faces_per_cell; ++face_id) {\n auto face = cell->face(face_id);\n dealii::Point<dim> face_center = face->center();\n switch (dim) {\n case 3: {\n if (std::fabs(face_center[2]) < zero_tol) {\n face->set_boundary_id(static_cast<int>(Boundary::kZMin));\n break;\n } else if (std::fabs(face_center[2] - spatial_max_.at(2) < zero_tol)) {\n face->set_boundary_id(static_cast<int>(Boundary::kZMax));\n break;\n }\n [[fallthrough]];\n }\n case 2: {\n if (std::fabs(face_center[1]) < zero_tol) {\n face->set_boundary_id(static_cast<int>(Boundary::kYMin));\n break;\n } else if (std::fabs(face_center[1] - spatial_max_[1]) < zero_tol) {\n face->set_boundary_id(static_cast<int>(Boundary::kYMax));\n break;\n }\n [[fallthrough]];\n }\n \/\/ Fall through to check x-direction\n case 1: {\n if (std::fabs(face_center[0]) < zero_tol) {\n face->set_boundary_id(static_cast<int>(Boundary::kXMin));\n break;\n } else if (std::fabs(face_center[0] - spatial_max_[0]) < zero_tol) {\n face->set_boundary_id(static_cast<int>(Boundary::kXMax));\n break;\n }\n break;\n }\n default: {\n AssertThrow(false,\n dealii::ExcMessage(\"Unsupported number of dimensions in FillBoundaryID\"));\n }\n }\n }\n }\n }\n}\n \n\ntemplate <int dim>\nint MeshCartesian<dim>::GetMaterialID(dealii::Point<dim> location) {\n std::array<double, dim> array_location;\n for (int i = 0; i < dim; ++i)\n array_location[i] = location[i];\n return GetMaterialID(array_location);\n}\n \ntemplate <int dim>\nint MeshCartesian<dim>::GetMaterialID(std::array<double, dim> location) {\n std::array<int, dim> relative_location;\n\n for (int i = 0; i < dim; ++i) {\n double cell_size = spatial_max_.at(i)\/n_material_cells_.at(i);\n double cell_location = location.at(i) \/ cell_size;\n int cell_index = std::floor(cell_location);\n\n if (static_cast<double>(cell_index) == cell_location && cell_index != 0) {\n relative_location.at(i) = cell_index - 1;\n } else {\n relative_location.at(i) = cell_index;\n }\n }\n \n return material_mapping_[relative_location];\n}\n\ntemplate class MeshCartesian<1>;\ntemplate class MeshCartesian<2>;\ntemplate class MeshCartesian<3>;\n\n} \/\/ namespace domain\n\n} \/\/ namespace bart \n<commit_msg>fixed bug in MeshCartesian::SetBoundaryID<commit_after>#include \"domain\/mesh_cartesian.h\"\n\n#include <algorithm>\n#include <cmath>\n#include <vector>\n\n#include <deal.II\/base\/point.h>\n#include <deal.II\/grid\/grid_generator.h>\n#include <deal.II\/base\/tensor.h>\n#include <deal.II\/base\/utilities.h>\n\n#include \"problem\/parameter_types.h\"\n\nnamespace bart {\n\nnamespace domain {\n\ntemplate <int dim>\nMeshCartesian<dim>::MeshCartesian(const std::vector<double> spatial_max,\n const std::vector<int> n_cells,\n const std::string material_mapping)\n : MeshCartesian(spatial_max, n_cells) {\n ParseMaterialMap(material_mapping);\n}\n\n\ntemplate <int dim>\nMeshCartesian<dim>::MeshCartesian(const std::vector<double> spatial_max,\n const std::vector<int> n_cells) {\n\n \/\/ Check lengths of spatial max and n_cells\n AssertThrow(spatial_max.size() == dim,\n dealii::ExcMessage(\"MeshCartesian argument error, incorrect spatial vector size\"));\n AssertThrow(n_cells.size() == dim,\n dealii::ExcMessage(\"MeshCartesian argument error, incorrect number of cells vector size\"));\n \n std::copy(n_cells.begin(), n_cells.end(), n_cells_.begin());\n std::copy(spatial_max.begin(), spatial_max.end(), spatial_max_.begin());\n}\n\ntemplate <int dim>\nvoid MeshCartesian<dim>::FillTriangulation(dealii::Triangulation<dim> &to_fill) {\n \n dealii::Point<dim> diagonal;\n dealii::Point<dim> origin;\n\n for (int i = 0; i < dim; ++i)\n diagonal[i] = spatial_max_[i];\n\n std::vector<unsigned int> number_of_cells{n_cells_.begin(), n_cells_.end()};\n dealii::GridGenerator::subdivided_hyper_rectangle(to_fill, number_of_cells,\n origin, diagonal);\n}\n\ntemplate <int dim>\nvoid MeshCartesian<dim>::ParseMaterialMap(std::string material_mapping) {\n using dealii::Utilities::split_string_list;\n using dealii::Utilities::string_to_int;\n using StringVector = std::vector<std::string>;\n\n StringVector z_blocks = split_string_list(material_mapping, \"\\n\\n\");\n\n std::reverse(z_blocks.begin(), z_blocks.end());\n\n for (unsigned k = 0; k < z_blocks.size(); ++k) {\n StringVector y_line = split_string_list(z_blocks.at(k), \"\\n\");\n std::reverse(y_line.begin(), y_line.end());\n for (unsigned j = 0; j < y_line.size(); ++j) {\n StringVector x_positions = split_string_list(y_line.at(j), \" \");\n for (unsigned i = 0; i < x_positions.size(); ++i) {\n std::array<unsigned, 3> index{i, j, k};\n std::array<int, dim> location;\n for (int dir = 0; dir < dim; ++dir)\n location.at(dir) = index.at(dir);\n material_mapping_[location] = string_to_int(x_positions.at(i));\n }\n n_material_cells_.at(0) = x_positions.size();\n }\n if (dim > 1)\n n_material_cells_.at(1) = y_line.size();\n }\n\n if (dim > 2)\n n_material_cells_.at(2) = z_blocks.size();\n}\n\ntemplate <int dim> \nvoid MeshCartesian<dim>::FillMaterialID(dealii::Triangulation<dim> &to_fill) {\n for (auto cell = to_fill.begin_active(); cell != to_fill.end(); ++cell) {\n if (cell->is_locally_owned()) {\n int material_id = GetMaterialID(cell->center());\n cell->set_material_id(material_id);\n }\n }\n}\n\ntemplate <int dim>\nvoid MeshCartesian<dim>::FillBoundaryID(dealii::Triangulation<dim> &to_fill) {\n using Boundary = bart::problem::Boundary;\n int faces_per_cell = dealii::GeometryInfo<dim>::faces_per_cell;\n double zero_tol = 1.0e-14;\n \n for (auto cell = to_fill.begin_active(); cell != to_fill.end(); ++cell) {\n if (cell->is_locally_owned()) {\n for (int face_id = 0; face_id < faces_per_cell; ++face_id) {\n auto face = cell->face(face_id);\n dealii::Point<dim> face_center = face->center();\n switch (dim) {\n case 3: {\n if (std::fabs(face_center[2]) < zero_tol) {\n face->set_boundary_id(static_cast<int>(Boundary::kZMin));\n break;\n } else if (std::fabs(face_center[2] - spatial_max_.at(2)) < zero_tol) {\n face->set_boundary_id(static_cast<int>(Boundary::kZMax));\n break;\n }\n [[fallthrough]];\n }\n case 2: {\n if (std::fabs(face_center[1]) < zero_tol) {\n face->set_boundary_id(static_cast<int>(Boundary::kYMin));\n break;\n } else if (std::fabs(face_center[1] - spatial_max_[1]) < zero_tol) {\n face->set_boundary_id(static_cast<int>(Boundary::kYMax));\n break;\n }\n [[fallthrough]];\n }\n \/\/ Fall through to check x-direction\n case 1: {\n if (std::fabs(face_center[0]) < zero_tol) {\n face->set_boundary_id(static_cast<int>(Boundary::kXMin));\n break;\n } else if (std::fabs(face_center[0] - spatial_max_[0]) < zero_tol) {\n face->set_boundary_id(static_cast<int>(Boundary::kXMax));\n break;\n }\n break;\n }\n default: {\n AssertThrow(false,\n dealii::ExcMessage(\"Unsupported number of dimensions in FillBoundaryID\"));\n }\n }\n }\n }\n }\n}\n \n\ntemplate <int dim>\nint MeshCartesian<dim>::GetMaterialID(dealii::Point<dim> location) {\n std::array<double, dim> array_location;\n for (int i = 0; i < dim; ++i)\n array_location[i] = location[i];\n return GetMaterialID(array_location);\n}\n \ntemplate <int dim>\nint MeshCartesian<dim>::GetMaterialID(std::array<double, dim> location) {\n std::array<int, dim> relative_location;\n\n for (int i = 0; i < dim; ++i) {\n double cell_size = spatial_max_.at(i)\/n_material_cells_.at(i);\n double cell_location = location.at(i) \/ cell_size;\n int cell_index = std::floor(cell_location);\n\n if (static_cast<double>(cell_index) == cell_location && cell_index != 0) {\n relative_location.at(i) = cell_index - 1;\n } else {\n relative_location.at(i) = cell_index;\n }\n }\n \n return material_mapping_[relative_location];\n}\n\ntemplate class MeshCartesian<1>;\ntemplate class MeshCartesian<2>;\ntemplate class MeshCartesian<3>;\n\n} \/\/ namespace domain\n\n} \/\/ namespace bart \n<|endoftext|>"} {"text":"<commit_before>\/*\n Copyright (C) 2010 George Kiagiadakis <kiagiadakis.george@gmail.com>\n Copyright (C) 2011 Collabora Ltd.\n @author George Kiagiadakis <george.kiagiadakis@collabora.co.uk>\n\n This library is free software; you can redistribute it and\/or modify\n it under the terms of the GNU Lesser General Public License as published\n by the Free Software Foundation; either version 2.1 of the License, or\n (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU Lesser General Public License\n along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n*\/\n#include \"videowidget.h\"\n#include \"..\/xoverlay.h\"\n#include \"..\/pipeline.h\"\n#include \"..\/bus.h\"\n#include \"..\/message.h\"\n#include \"..\/..\/QGlib\/connect.h\"\n#include <QtCore\/QDebug>\n#include <QtCore\/QMutex>\n#include <QtCore\/QThread>\n#include <QtGui\/QPainter>\n#include <QtGui\/QPaintEvent>\n#include <QtGui\/QResizeEvent>\n#include <QtGui\/QApplication>\n\nnamespace QGst {\nnamespace Ui {\n\nclass AbstractRenderer\n{\npublic:\n static AbstractRenderer *create(const ElementPtr & sink, QWidget *videoWidget);\n\n virtual ~AbstractRenderer() {}\n virtual ElementPtr videoSink() const = 0;\n};\n\n\nclass XOverlayRenderer : public QObject, public AbstractRenderer\n{\npublic:\n XOverlayRenderer(QWidget *parent)\n : QObject(parent)\n {\n m_windowId = widget()->winId(); \/\/create a new X window (if we are on X11 with alien widgets)\n QApplication::syncX(); \/\/inform other applications about the new window (on X11)\n\n widget()->installEventFilter(this);\n widget()->setAttribute(Qt::WA_NoSystemBackground, true);\n widget()->setAttribute(Qt::WA_PaintOnScreen, true);\n widget()->update();\n }\n\n virtual ~XOverlayRenderer()\n {\n if (m_sink) {\n m_sink->setWindowHandle(0);\n }\n widget()->removeEventFilter(this);\n widget()->setAttribute(Qt::WA_NoSystemBackground, false);\n widget()->setAttribute(Qt::WA_PaintOnScreen, false);\n widget()->update();\n }\n\n void setVideoSink(const XOverlayPtr & sink)\n {\n QMutexLocker l(&m_sinkMutex);\n if (m_sink) {\n m_sink->setWindowHandle(0);\n }\n m_sink = sink;\n if (m_sink) {\n m_sink->setWindowHandle(m_windowId);\n }\n }\n\n virtual ElementPtr videoSink() const\n {\n QMutexLocker l(&m_sinkMutex);\n return m_sink.dynamicCast<Element>();\n }\n\nprotected:\n virtual bool eventFilter(QObject *filteredObject, QEvent *event)\n {\n if (filteredObject == parent() && event->type() == QEvent::Paint) {\n QMutexLocker l(&m_sinkMutex);\n State currentState = m_sink ? m_sink.dynamicCast<Element>()->currentState() : StateNull;\n\n if (currentState == StatePlaying || currentState == StatePaused) {\n m_sink->expose();\n } else {\n QPainter p(widget());\n p.fillRect(widget()->rect(), Qt::black);\n }\n return true;\n } else {\n return QObject::eventFilter(filteredObject, event);\n }\n }\n\nprivate:\n inline QWidget *widget() { return static_cast<QWidget*>(parent()); }\n WId m_windowId;\n mutable QMutex m_sinkMutex;\n XOverlayPtr m_sink;\n};\n\n\nclass QWidgetVideoSinkRenderer : public AbstractRenderer\n{\npublic:\n QWidgetVideoSinkRenderer(const ElementPtr & sink, QWidget *parent)\n : m_sink(sink)\n {\n \/\/GValue of G_TYPE_POINTER can only be set as void* in the bindings\n m_sink->setProperty<void*>(\"widget\", parent);\n }\n\n virtual ~QWidgetVideoSinkRenderer()\n {\n m_sink->setProperty<void*>(\"widget\", NULL);\n }\n\n virtual ElementPtr videoSink() const { return m_sink; }\n\nprivate:\n ElementPtr m_sink;\n};\n\n\nclass PipelineWatch : public QObject, public AbstractRenderer\n{\npublic:\n PipelineWatch(const PipelinePtr & pipeline, QWidget *parent)\n : QObject(parent), m_renderer(new XOverlayRenderer(parent)), m_pipeline(pipeline)\n {\n pipeline->bus()->enableSyncMessageEmission();\n QGlib::connect(pipeline->bus(), \"sync-message\",\n this, &PipelineWatch::onBusSyncMessage);\n }\n\n virtual ~PipelineWatch()\n {\n m_pipeline->bus()->disableSyncMessageEmission();\n delete m_renderer;\n }\n\n virtual ElementPtr videoSink() const { return m_renderer->videoSink(); }\n\n void releaseSink() { m_renderer->setVideoSink(XOverlayPtr()); }\n\nprivate:\n void onBusSyncMessage(const MessagePtr & msg)\n {\n switch (msg->type()) {\n case MessageElement:\n if (msg->internalStructure()->name() == QLatin1String(\"prepare-xwindow-id\")) {\n XOverlayPtr overlay = msg->source().dynamicCast<XOverlay>();\n m_renderer->setVideoSink(overlay);\n }\n break;\n case MessageStateChanged:\n \/\/release the sink when it goes back to null state\n if (msg.staticCast<StateChangedMessage>()->newState() == StateNull &&\n msg->source() == m_renderer->videoSink())\n {\n releaseSink();\n }\n default:\n break;\n }\n }\n\nprivate:\n XOverlayRenderer *m_renderer;\n PipelinePtr m_pipeline;\n};\n\n\nAbstractRenderer *AbstractRenderer::create(const ElementPtr & sink, QWidget *videoWidget)\n{\n XOverlayPtr overlay = sink.dynamicCast<XOverlay>();\n if (overlay) {\n XOverlayRenderer *r = new XOverlayRenderer(videoWidget);\n r->setVideoSink(overlay);\n return r;\n }\n\n if (QGlib::Type::fromInstance(sink).name() == QLatin1String(\"GstQWidgetVideoSink\")) {\n return new QWidgetVideoSinkRenderer(sink, videoWidget);\n }\n\n return NULL;\n}\n\n\nVideoWidget::VideoWidget(QWidget *parent, Qt::WindowFlags f)\n : QWidget(parent, f), d(NULL)\n{\n}\n\nVideoWidget::~VideoWidget()\n{\n delete d;\n}\n\nElementPtr VideoWidget::videoSink() const\n{\n return d ? d->videoSink() : ElementPtr();\n}\n\nvoid VideoWidget::setVideoSink(const ElementPtr & sink)\n{\n if (!sink) {\n releaseVideoSink();\n return;\n }\n\n Q_ASSERT(QThread::currentThread() == QApplication::instance()->thread());\n Q_ASSERT(d == NULL);\n\n d = AbstractRenderer::create(sink, this);\n\n if (!d) {\n qCritical() << \"QGst::Ui::VideoWidget: Could not construct a renderer for the specified element\";\n }\n}\n\nvoid VideoWidget::releaseVideoSink()\n{\n Q_ASSERT(QThread::currentThread() == QApplication::instance()->thread());\n\n if (d) {\n PipelineWatch *pw = dynamic_cast<PipelineWatch*>(d);\n if (pw) {\n pw->releaseSink();\n } else {\n delete d;\n d = NULL;\n }\n }\n}\n\nvoid VideoWidget::watchPipeline(const PipelinePtr & pipeline)\n{\n if (!pipeline) {\n stopPipelineWatch();\n return;\n }\n\n Q_ASSERT(QThread::currentThread() == QApplication::instance()->thread());\n Q_ASSERT(d == NULL);\n\n d = new PipelineWatch(pipeline, this);\n}\n\nvoid VideoWidget::stopPipelineWatch()\n{\n Q_ASSERT(QThread::currentThread() == QApplication::instance()->thread());\n\n if (dynamic_cast<PipelineWatch*>(d)) {\n delete d;\n d = NULL;\n }\n}\n\nvoid VideoWidget::paintEvent(QPaintEvent *event)\n{\n QPainter p(this);\n p.fillRect(event->rect(), Qt::black);\n}\n\n} \/\/namespace Ui\n} \/\/namespace QGst\n<commit_msg>VideoWidget: Add support for qtvideosink<commit_after>\/*\n Copyright (C) 2010 George Kiagiadakis <kiagiadakis.george@gmail.com>\n Copyright (C) 2011-2012 Collabora Ltd.\n @author George Kiagiadakis <george.kiagiadakis@collabora.co.uk>\n\n This library is free software; you can redistribute it and\/or modify\n it under the terms of the GNU Lesser General Public License as published\n by the Free Software Foundation; either version 2.1 of the License, or\n (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU Lesser General Public License\n along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n*\/\n#include \"videowidget.h\"\n#include \"..\/xoverlay.h\"\n#include \"..\/pipeline.h\"\n#include \"..\/bus.h\"\n#include \"..\/message.h\"\n#include \"..\/..\/QGlib\/connect.h\"\n#include \"..\/..\/QGlib\/signal.h\"\n#include <QtCore\/QDebug>\n#include <QtCore\/QMutex>\n#include <QtCore\/QThread>\n#include <QtGui\/QPainter>\n#include <QtGui\/QPaintEvent>\n#include <QtGui\/QResizeEvent>\n#include <QtGui\/QApplication>\n\nnamespace QGst {\nnamespace Ui {\n\nclass AbstractRenderer\n{\npublic:\n static AbstractRenderer *create(const ElementPtr & sink, QWidget *videoWidget);\n\n virtual ~AbstractRenderer() {}\n virtual ElementPtr videoSink() const = 0;\n};\n\n\nclass XOverlayRenderer : public QObject, public AbstractRenderer\n{\npublic:\n XOverlayRenderer(QWidget *parent)\n : QObject(parent)\n {\n m_windowId = widget()->winId(); \/\/create a new X window (if we are on X11 with alien widgets)\n QApplication::syncX(); \/\/inform other applications about the new window (on X11)\n\n widget()->installEventFilter(this);\n widget()->setAttribute(Qt::WA_NoSystemBackground, true);\n widget()->setAttribute(Qt::WA_PaintOnScreen, true);\n widget()->update();\n }\n\n virtual ~XOverlayRenderer()\n {\n if (m_sink) {\n m_sink->setWindowHandle(0);\n }\n widget()->removeEventFilter(this);\n widget()->setAttribute(Qt::WA_NoSystemBackground, false);\n widget()->setAttribute(Qt::WA_PaintOnScreen, false);\n widget()->update();\n }\n\n void setVideoSink(const XOverlayPtr & sink)\n {\n QMutexLocker l(&m_sinkMutex);\n if (m_sink) {\n m_sink->setWindowHandle(0);\n }\n m_sink = sink;\n if (m_sink) {\n m_sink->setWindowHandle(m_windowId);\n }\n }\n\n virtual ElementPtr videoSink() const\n {\n QMutexLocker l(&m_sinkMutex);\n return m_sink.dynamicCast<Element>();\n }\n\nprotected:\n virtual bool eventFilter(QObject *filteredObject, QEvent *event)\n {\n if (filteredObject == parent() && event->type() == QEvent::Paint) {\n QMutexLocker l(&m_sinkMutex);\n State currentState = m_sink ? m_sink.dynamicCast<Element>()->currentState() : StateNull;\n\n if (currentState == StatePlaying || currentState == StatePaused) {\n m_sink->expose();\n } else {\n QPainter p(widget());\n p.fillRect(widget()->rect(), Qt::black);\n }\n return true;\n } else {\n return QObject::eventFilter(filteredObject, event);\n }\n }\n\nprivate:\n inline QWidget *widget() { return static_cast<QWidget*>(parent()); }\n WId m_windowId;\n mutable QMutex m_sinkMutex;\n XOverlayPtr m_sink;\n};\n\n\nclass QtVideoSinkRenderer : public QObject, public AbstractRenderer\n{\npublic:\n QtVideoSinkRenderer(const ElementPtr & sink, QWidget *parent)\n : QObject(parent), m_sink(sink)\n {\n QGlib::connect(sink, \"update\", this, &QtVideoSinkRenderer::onUpdate);\n parent->installEventFilter(this);\n parent->setAttribute(Qt::WA_OpaquePaintEvent, true);\n }\n\n virtual ~QtVideoSinkRenderer()\n {\n widget()->removeEventFilter(this);\n widget()->setAttribute(Qt::WA_OpaquePaintEvent, false);\n }\n\n virtual ElementPtr videoSink() const { return m_sink; }\n\nprotected:\n virtual bool eventFilter(QObject *filteredObject, QEvent *event)\n {\n if (filteredObject == parent() && event->type() == QEvent::Paint) {\n QPainter painter(widget());\n QRect targetArea = widget()->rect();\n QGlib::emit<void>(m_sink, \"paint\", (void*) &painter,\n (qreal) targetArea.x(), (qreal) targetArea.y(),\n (qreal) targetArea.width(), (qreal) targetArea.height());\n return true;\n } else {\n return QObject::eventFilter(filteredObject, event);\n }\n }\n\nprivate:\n inline QWidget *widget() { return static_cast<QWidget*>(parent()); }\n void onUpdate() { widget()->update(); }\n\n ElementPtr m_sink;\n};\n\n\nclass QWidgetVideoSinkRenderer : public AbstractRenderer\n{\npublic:\n QWidgetVideoSinkRenderer(const ElementPtr & sink, QWidget *parent)\n : m_sink(sink)\n {\n \/\/GValue of G_TYPE_POINTER can only be set as void* in the bindings\n m_sink->setProperty<void*>(\"widget\", parent);\n }\n\n virtual ~QWidgetVideoSinkRenderer()\n {\n m_sink->setProperty<void*>(\"widget\", NULL);\n }\n\n virtual ElementPtr videoSink() const { return m_sink; }\n\nprivate:\n ElementPtr m_sink;\n};\n\n\nclass PipelineWatch : public QObject, public AbstractRenderer\n{\npublic:\n PipelineWatch(const PipelinePtr & pipeline, QWidget *parent)\n : QObject(parent), m_renderer(new XOverlayRenderer(parent)), m_pipeline(pipeline)\n {\n pipeline->bus()->enableSyncMessageEmission();\n QGlib::connect(pipeline->bus(), \"sync-message\",\n this, &PipelineWatch::onBusSyncMessage);\n }\n\n virtual ~PipelineWatch()\n {\n m_pipeline->bus()->disableSyncMessageEmission();\n delete m_renderer;\n }\n\n virtual ElementPtr videoSink() const { return m_renderer->videoSink(); }\n\n void releaseSink() { m_renderer->setVideoSink(XOverlayPtr()); }\n\nprivate:\n void onBusSyncMessage(const MessagePtr & msg)\n {\n switch (msg->type()) {\n case MessageElement:\n if (msg->internalStructure()->name() == QLatin1String(\"prepare-xwindow-id\")) {\n XOverlayPtr overlay = msg->source().dynamicCast<XOverlay>();\n m_renderer->setVideoSink(overlay);\n }\n break;\n case MessageStateChanged:\n \/\/release the sink when it goes back to null state\n if (msg.staticCast<StateChangedMessage>()->newState() == StateNull &&\n msg->source() == m_renderer->videoSink())\n {\n releaseSink();\n }\n default:\n break;\n }\n }\n\nprivate:\n XOverlayRenderer *m_renderer;\n PipelinePtr m_pipeline;\n};\n\n\nAbstractRenderer *AbstractRenderer::create(const ElementPtr & sink, QWidget *videoWidget)\n{\n XOverlayPtr overlay = sink.dynamicCast<XOverlay>();\n if (overlay) {\n XOverlayRenderer *r = new XOverlayRenderer(videoWidget);\n r->setVideoSink(overlay);\n return r;\n }\n\n if (QGlib::Type::fromInstance(sink).name() == QLatin1String(\"GstQtVideoSink\")) {\n return new QtVideoSinkRenderer(sink, videoWidget);\n }\n\n if (QGlib::Type::fromInstance(sink).name() == QLatin1String(\"GstQWidgetVideoSink\")) {\n return new QWidgetVideoSinkRenderer(sink, videoWidget);\n }\n\n return NULL;\n}\n\n\nVideoWidget::VideoWidget(QWidget *parent, Qt::WindowFlags f)\n : QWidget(parent, f), d(NULL)\n{\n}\n\nVideoWidget::~VideoWidget()\n{\n delete d;\n}\n\nElementPtr VideoWidget::videoSink() const\n{\n return d ? d->videoSink() : ElementPtr();\n}\n\nvoid VideoWidget::setVideoSink(const ElementPtr & sink)\n{\n if (!sink) {\n releaseVideoSink();\n return;\n }\n\n Q_ASSERT(QThread::currentThread() == QApplication::instance()->thread());\n Q_ASSERT(d == NULL);\n\n d = AbstractRenderer::create(sink, this);\n\n if (!d) {\n qCritical() << \"QGst::Ui::VideoWidget: Could not construct a renderer for the specified element\";\n }\n}\n\nvoid VideoWidget::releaseVideoSink()\n{\n Q_ASSERT(QThread::currentThread() == QApplication::instance()->thread());\n\n if (d) {\n PipelineWatch *pw = dynamic_cast<PipelineWatch*>(d);\n if (pw) {\n pw->releaseSink();\n } else {\n delete d;\n d = NULL;\n }\n }\n}\n\nvoid VideoWidget::watchPipeline(const PipelinePtr & pipeline)\n{\n if (!pipeline) {\n stopPipelineWatch();\n return;\n }\n\n Q_ASSERT(QThread::currentThread() == QApplication::instance()->thread());\n Q_ASSERT(d == NULL);\n\n d = new PipelineWatch(pipeline, this);\n}\n\nvoid VideoWidget::stopPipelineWatch()\n{\n Q_ASSERT(QThread::currentThread() == QApplication::instance()->thread());\n\n if (dynamic_cast<PipelineWatch*>(d)) {\n delete d;\n d = NULL;\n }\n}\n\nvoid VideoWidget::paintEvent(QPaintEvent *event)\n{\n QPainter p(this);\n p.fillRect(event->rect(), Qt::black);\n}\n\n} \/\/namespace Ui\n} \/\/namespace QGst\n<|endoftext|>"} {"text":"<commit_before>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Copyright (c) 2012, John Haddon. All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are\n\/\/ met:\n\/\/\n\/\/ * Redistributions of source code must retain the above\n\/\/ copyright notice, this list of conditions and the following\n\/\/ disclaimer.\n\/\/\n\/\/ * Redistributions in binary form must reproduce the above\n\/\/ copyright notice, this list of conditions and the following\n\/\/ disclaimer in the documentation and\/or other materials provided with\n\/\/ the distribution.\n\/\/\n\/\/ * Neither the name of John Haddon nor the names of\n\/\/ any other contributors to this software may be used to endorse or\n\/\/ promote products derived from this software without specific prior\n\/\/ written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS\n\/\/ IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,\n\/\/ THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n\/\/ PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR\n\/\/ CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n\/\/ EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n\/\/ PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n\/\/ PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n\/\/ LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n\/\/ NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n\/\/ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"boost\/python.hpp\"\n\n#include \"GafferBindings\/DependencyNodeBinding.h\"\n\n#include \"GafferArnold\/ArnoldShader.h\"\n#include \"GafferArnold\/ArnoldOptions.h\"\n#include \"GafferArnold\/ArnoldAttributes.h\"\n#include \"GafferArnold\/ArnoldLight.h\"\n\nusing namespace boost::python;\nusing namespace GafferArnold;\n\nBOOST_PYTHON_MODULE( _GafferArnold )\n{\n\n\tGafferBindings::DependencyNodeClass<ArnoldShader>()\n\t\t.def( \"loadShader\", (void (ArnoldShader::*)( const std::string & ) )&ArnoldShader::loadShader )\n\t;\n\n\tGafferBindings::NodeClass<ArnoldLight>()\n\t\t.def( \"loadShader\", (void (ArnoldLight::*)( const std::string & ) )&ArnoldLight::loadShader )\n\t;\n\n\tGafferBindings::DependencyNodeClass<ArnoldOptions>();\n\tGafferBindings::DependencyNodeClass<ArnoldAttributes>();\n\n}\n<commit_msg>GafferArnold bindings : Bind VDBVolume node.<commit_after>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Copyright (c) 2012, John Haddon. All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are\n\/\/ met:\n\/\/\n\/\/ * Redistributions of source code must retain the above\n\/\/ copyright notice, this list of conditions and the following\n\/\/ disclaimer.\n\/\/\n\/\/ * Redistributions in binary form must reproduce the above\n\/\/ copyright notice, this list of conditions and the following\n\/\/ disclaimer in the documentation and\/or other materials provided with\n\/\/ the distribution.\n\/\/\n\/\/ * Neither the name of John Haddon nor the names of\n\/\/ any other contributors to this software may be used to endorse or\n\/\/ promote products derived from this software without specific prior\n\/\/ written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS\n\/\/ IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,\n\/\/ THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n\/\/ PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR\n\/\/ CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n\/\/ EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n\/\/ PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n\/\/ PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n\/\/ LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n\/\/ NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n\/\/ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"boost\/python.hpp\"\n\n#include \"GafferBindings\/DependencyNodeBinding.h\"\n\n#include \"GafferArnold\/ArnoldShader.h\"\n#include \"GafferArnold\/ArnoldOptions.h\"\n#include \"GafferArnold\/ArnoldAttributes.h\"\n#include \"GafferArnold\/ArnoldLight.h\"\n#include \"GafferArnold\/VDBVolume.h\"\n\nusing namespace boost::python;\nusing namespace GafferArnold;\n\nBOOST_PYTHON_MODULE( _GafferArnold )\n{\n\n\tGafferBindings::DependencyNodeClass<ArnoldShader>()\n\t\t.def( \"loadShader\", (void (ArnoldShader::*)( const std::string & ) )&ArnoldShader::loadShader )\n\t;\n\n\tGafferBindings::NodeClass<ArnoldLight>()\n\t\t.def( \"loadShader\", (void (ArnoldLight::*)( const std::string & ) )&ArnoldLight::loadShader )\n\t;\n\n\tGafferBindings::DependencyNodeClass<ArnoldOptions>();\n\tGafferBindings::DependencyNodeClass<ArnoldAttributes>();\n\tGafferBindings::DependencyNodeClass<VDBVolume>();\n\n}\n<|endoftext|>"} {"text":"<commit_before>#include <libprecisegc\/details\/allocators\/gc_pool_allocator.hpp>\n\n#include <tuple>\n#include <iterator>\n\n#include <libprecisegc\/details\/allocators\/gc_box.hpp>\n#include <libprecisegc\/details\/allocators\/memory_index.hpp>\n#include <libprecisegc\/details\/compacting\/fix_ptrs.hpp>\n#include <libprecisegc\/details\/compacting\/two_finger_compactor.hpp>\n#include <libprecisegc\/details\/collectors\/gc_new_stack_entry.hpp>\n\nnamespace precisegc { namespace details { namespace allocators {\n\ngc_pool_allocator::gc_pool_allocator()\n : m_freelist(nullptr)\n , m_top(nullptr)\n , m_end(nullptr)\n{}\n\ngc_pool_allocator::~gc_pool_allocator()\n{\n for (auto it = m_descrs.begin(); it != m_descrs.end(); ) {\n it = destroy_descriptor(it);\n }\n}\n\ngc_alloc::response gc_pool_allocator::allocate(const gc_alloc::request& rqst, size_t aligned_size)\n{\n if (m_top == m_end) {\n return try_expand_and_allocate(aligned_size, rqst, 0);\n }\n return stack_allocation(aligned_size, rqst);\n}\n\ngc_alloc::response gc_pool_allocator::try_expand_and_allocate(size_t size,\n const gc_alloc::request& rqst,\n size_t attempt_num)\n{\n using namespace collectors;\n\n byte* blk;\n size_t blk_size;\n gc_new_stack_entry* stack_entry = reinterpret_cast<gc_new_stack_entry*>(rqst.buffer());\n std::tie(blk, blk_size) = allocate_block(size, stack_entry->zeroing_flag);\n if (blk) {\n create_descriptor(blk, blk_size, size);\n m_top = blk;\n m_end = blk + blk_size;\n return stack_allocation(size, rqst);\n } else if (m_freelist) {\n return freelist_allocation(size, rqst);\n } else {\n if (attempt_num == 0) {\n gc_options opt;\n opt.kind = gc_kind::COLLECT;\n opt.gen = 0;\n gc_initiation_point(initiation_point_type::HEAP_LIMIT_EXCEEDED, opt);\n } else if (attempt_num == 1) {\n gc_expand_heap();\n } else {\n throw gc_bad_alloc();\n }\n return try_expand_and_allocate(size, rqst, ++attempt_num);\n }\n}\n\ngc_alloc::response gc_pool_allocator::stack_allocation(size_t size, const gc_alloc::request& rqst)\n{\n assert(m_top <= m_end - size);\n\n descriptor_t* descr = &m_descrs.back();\n byte* ptr = m_top;\n m_top += size;\n return init_cell(ptr, rqst, descr);\n}\n\ngc_alloc::response gc_pool_allocator::freelist_allocation(size_t size, const gc_alloc::request& rqst)\n{\n using namespace collectors;\n\n assert(m_freelist);\n\n byte* ptr = reinterpret_cast<byte*>(m_freelist);\n m_freelist = reinterpret_cast<byte**>(m_freelist[0]);\n\n assert(contains(ptr));\n\n gc_new_stack_entry* stack_entry = reinterpret_cast<gc_new_stack_entry*>(rqst.buffer());\n if (stack_entry->zeroing_flag) {\n memset(ptr, 0, size);\n }\n descriptor_t* descr = static_cast<descriptor_t*>(memory_index::get_descriptor(ptr).to_gc_descriptor());\n return init_cell(ptr, rqst, descr);\n}\n\ngc_alloc::response gc_pool_allocator::init_cell(byte* cell_start, const gc_alloc::request& rqst, descriptor_t* descr)\n{\n assert(descr);\n assert(cell_start);\n\n collectors::gc_new_stack_entry* stack_entry = reinterpret_cast<collectors::gc_new_stack_entry*>(rqst.buffer());\n stack_entry->descriptor = descr;\n\n byte* obj_start = descr->init_cell(cell_start, rqst.obj_count(), rqst.type_meta());\n return gc_alloc::response(obj_start, cell_start, descr->cell_size(), rqst.buffer());\n}\n\ngc_pool_allocator::iterator_t gc_pool_allocator::create_descriptor(byte* blk, size_t blk_size, size_t cell_size)\n{\n m_descrs.emplace_back(blk, blk_size, cell_size);\n auto last = std::prev(m_descrs.end());\n memory_index::index_gc_heap_memory(blk, blk_size, &(*last));\n return last;\n}\n\ngc_pool_allocator::iterator_t gc_pool_allocator::destroy_descriptor(iterator_t it)\n{\n sweep(*it, false);\n memory_index::deindex(it->memory(), it->size());\n deallocate_block(it->memory(), it->size());\n return m_descrs.erase(it);\n}\n\nstd::pair<byte*, size_t> gc_pool_allocator::allocate_block(size_t cell_size, bool zeroing)\n{\n size_t chunk_size = descriptor_t::chunk_size(cell_size);\n return std::make_pair(gc_core_allocator::allocate(chunk_size, zeroing), chunk_size);\n}\n\nvoid gc_pool_allocator::deallocate_block(byte* ptr, size_t size)\n{\n gc_core_allocator::deallocate(ptr, size);\n}\n\nbool gc_pool_allocator::contains(byte* ptr) const\n{\n for (auto& descr: m_descrs) {\n if (descr.contains(ptr)) {\n return true;\n }\n }\n return false;\n}\n\ngc_heap_stat gc_pool_allocator::collect(compacting::forwarding& frwd)\n{\n if (m_descrs.begin() == m_descrs.end()) {\n return gc_heap_stat();\n }\n\n gc_heap_stat stat;\n shrink(stat);\n gc_decrease_heap_size(stat.mem_freed);\n\n m_top = nullptr;\n m_end = m_top;\n m_freelist = nullptr;\n\n if (is_compaction_required(stat)) {\n compact(frwd, stat);\n } else {\n sweep(stat);\n }\n\n return stat;\n}\n\nvoid gc_pool_allocator::shrink(gc_heap_stat& stat)\n{\n for (iterator_t it = m_descrs.begin(), end = m_descrs.end(); it != end; ) {\n stat.mem_before_gc += it->size();\n if (it->unused()) {\n stat.mem_freed += it->size();\n it = destroy_descriptor(it);\n } else {\n stat.mem_occupied += it->size();\n stat.mem_live += it->cell_size() * it->count_lived();\n stat.pinned_cnt += it->count_pinned();\n ++it;\n }\n }\n}\n\nvoid gc_pool_allocator::sweep(gc_heap_stat& stat)\n{\n for (auto& descr: m_descrs) {\n stat.mem_freed += sweep(descr, true);\n }\n}\n\nsize_t gc_pool_allocator::sweep(descriptor_t& descr, bool add_to_freelist)\n{\n byte* it = descr.memory();\n byte* end = descr.memory() + descr.size();\n size_t size = descr.cell_size();\n\n size_t freed = 0;\n for (size_t i = 0; it < end; it += size, ++i) {\n if (!descr.get_mark(i)) {\n if (descr.is_init(i)) {\n descr.finalize(i);\n freed += size;\n if (add_to_freelist) {\n insert_into_freelist(it);\n }\n } else if (add_to_freelist) {\n insert_into_freelist(it);\n }\n }\n }\n return freed;\n}\n\nvoid gc_pool_allocator::insert_into_freelist(byte* ptr)\n{\n assert(contains(ptr));\n\n byte** next = reinterpret_cast<byte**>(ptr);\n next[0] = reinterpret_cast<byte*>(m_freelist);\n m_freelist = next;\n}\n\nvoid gc_pool_allocator::compact(compacting::forwarding& frwd, gc_heap_stat& stat)\n{\n compacting::two_finger_compactor compactor;\n auto rng = memory_range();\n compactor(rng, frwd, stat);\n}\n\nvoid gc_pool_allocator::fix(const compacting::forwarding& frwd)\n{\n auto rng = memory_range();\n compacting::fix_ptrs(rng.begin(), rng.end(), frwd);\n}\n\nvoid gc_pool_allocator::finalize()\n{\n for (auto& descr: m_descrs) {\n descr.unmark();\n }\n}\n\nbool gc_pool_allocator::empty() const\n{\n return m_descrs.empty();\n}\n\nbool gc_pool_allocator::is_compaction_required(const gc_heap_stat& stat) const\n{\n\/\/ return false;\n return stat.residency() < RESIDENCY_COMPACTING_THRESHOLD;\n\/\/ return stat.residency() < RESIDENCY_COMPACTING_THRESHOLD\n\/\/ || (stat.residency() < RESIDENCY_NON_COMPACTING_THRESHOLD\n\/\/ && std::abs(stat.residency() - m_prev_residency) < RESIDENCY_EPS);\n}\n\ngc_pool_allocator::memory_range_type gc_pool_allocator::memory_range()\n{\n return utils::flatten_range(m_descrs.begin(), m_descrs.end());\n}\n\n}}}<commit_msg>prev residency<commit_after>#include <libprecisegc\/details\/allocators\/gc_pool_allocator.hpp>\n\n#include <tuple>\n#include <iterator>\n\n#include <libprecisegc\/details\/allocators\/gc_box.hpp>\n#include <libprecisegc\/details\/allocators\/memory_index.hpp>\n#include <libprecisegc\/details\/compacting\/fix_ptrs.hpp>\n#include <libprecisegc\/details\/compacting\/two_finger_compactor.hpp>\n#include <libprecisegc\/details\/collectors\/gc_new_stack_entry.hpp>\n\nnamespace precisegc { namespace details { namespace allocators {\n\ngc_pool_allocator::gc_pool_allocator()\n : m_freelist(nullptr)\n , m_top(nullptr)\n , m_end(nullptr)\n , m_prev_residency(0)\n{}\n\ngc_pool_allocator::~gc_pool_allocator()\n{\n for (auto it = m_descrs.begin(); it != m_descrs.end(); ) {\n it = destroy_descriptor(it);\n }\n}\n\ngc_alloc::response gc_pool_allocator::allocate(const gc_alloc::request& rqst, size_t aligned_size)\n{\n if (m_top == m_end) {\n return try_expand_and_allocate(aligned_size, rqst, 0);\n }\n return stack_allocation(aligned_size, rqst);\n}\n\ngc_alloc::response gc_pool_allocator::try_expand_and_allocate(size_t size,\n const gc_alloc::request& rqst,\n size_t attempt_num)\n{\n using namespace collectors;\n\n byte* blk;\n size_t blk_size;\n gc_new_stack_entry* stack_entry = reinterpret_cast<gc_new_stack_entry*>(rqst.buffer());\n std::tie(blk, blk_size) = allocate_block(size, stack_entry->zeroing_flag);\n if (blk) {\n create_descriptor(blk, blk_size, size);\n m_top = blk;\n m_end = blk + blk_size;\n return stack_allocation(size, rqst);\n } else if (m_freelist) {\n return freelist_allocation(size, rqst);\n } else {\n if (attempt_num == 0) {\n gc_options opt;\n opt.kind = gc_kind::COLLECT;\n opt.gen = 0;\n gc_initiation_point(initiation_point_type::HEAP_LIMIT_EXCEEDED, opt);\n } else if (attempt_num == 1) {\n gc_expand_heap();\n } else {\n throw gc_bad_alloc();\n }\n return try_expand_and_allocate(size, rqst, ++attempt_num);\n }\n}\n\ngc_alloc::response gc_pool_allocator::stack_allocation(size_t size, const gc_alloc::request& rqst)\n{\n assert(m_top <= m_end - size);\n\n descriptor_t* descr = &m_descrs.back();\n byte* ptr = m_top;\n m_top += size;\n return init_cell(ptr, rqst, descr);\n}\n\ngc_alloc::response gc_pool_allocator::freelist_allocation(size_t size, const gc_alloc::request& rqst)\n{\n using namespace collectors;\n\n assert(m_freelist);\n\n byte* ptr = reinterpret_cast<byte*>(m_freelist);\n m_freelist = reinterpret_cast<byte**>(m_freelist[0]);\n\n assert(contains(ptr));\n\n gc_new_stack_entry* stack_entry = reinterpret_cast<gc_new_stack_entry*>(rqst.buffer());\n if (stack_entry->zeroing_flag) {\n memset(ptr, 0, size);\n }\n descriptor_t* descr = static_cast<descriptor_t*>(memory_index::get_descriptor(ptr).to_gc_descriptor());\n return init_cell(ptr, rqst, descr);\n}\n\ngc_alloc::response gc_pool_allocator::init_cell(byte* cell_start, const gc_alloc::request& rqst, descriptor_t* descr)\n{\n assert(descr);\n assert(cell_start);\n\n collectors::gc_new_stack_entry* stack_entry = reinterpret_cast<collectors::gc_new_stack_entry*>(rqst.buffer());\n stack_entry->descriptor = descr;\n\n byte* obj_start = descr->init_cell(cell_start, rqst.obj_count(), rqst.type_meta());\n return gc_alloc::response(obj_start, cell_start, descr->cell_size(), rqst.buffer());\n}\n\ngc_pool_allocator::iterator_t gc_pool_allocator::create_descriptor(byte* blk, size_t blk_size, size_t cell_size)\n{\n m_descrs.emplace_back(blk, blk_size, cell_size);\n auto last = std::prev(m_descrs.end());\n memory_index::index_gc_heap_memory(blk, blk_size, &(*last));\n return last;\n}\n\ngc_pool_allocator::iterator_t gc_pool_allocator::destroy_descriptor(iterator_t it)\n{\n sweep(*it, false);\n memory_index::deindex(it->memory(), it->size());\n deallocate_block(it->memory(), it->size());\n return m_descrs.erase(it);\n}\n\nstd::pair<byte*, size_t> gc_pool_allocator::allocate_block(size_t cell_size, bool zeroing)\n{\n size_t chunk_size = descriptor_t::chunk_size(cell_size);\n return std::make_pair(gc_core_allocator::allocate(chunk_size, zeroing), chunk_size);\n}\n\nvoid gc_pool_allocator::deallocate_block(byte* ptr, size_t size)\n{\n gc_core_allocator::deallocate(ptr, size);\n}\n\nbool gc_pool_allocator::contains(byte* ptr) const\n{\n for (auto& descr: m_descrs) {\n if (descr.contains(ptr)) {\n return true;\n }\n }\n return false;\n}\n\ngc_heap_stat gc_pool_allocator::collect(compacting::forwarding& frwd)\n{\n if (m_descrs.begin() == m_descrs.end()) {\n return gc_heap_stat();\n }\n\n gc_heap_stat stat;\n shrink(stat);\n gc_decrease_heap_size(stat.mem_freed);\n\n m_top = nullptr;\n m_end = m_top;\n m_freelist = nullptr;\n\n if (is_compaction_required(stat)) {\n compact(frwd, stat);\n m_prev_residency = 1.0;\n } else {\n sweep(stat);\n m_prev_residency = stat.residency();\n }\n\n return stat;\n}\n\nvoid gc_pool_allocator::shrink(gc_heap_stat& stat)\n{\n for (iterator_t it = m_descrs.begin(), end = m_descrs.end(); it != end; ) {\n stat.mem_before_gc += it->size();\n if (it->unused()) {\n stat.mem_freed += it->size();\n it = destroy_descriptor(it);\n } else {\n stat.mem_occupied += it->size();\n stat.mem_live += it->cell_size() * it->count_lived();\n stat.pinned_cnt += it->count_pinned();\n ++it;\n }\n }\n}\n\nvoid gc_pool_allocator::sweep(gc_heap_stat& stat)\n{\n for (auto& descr: m_descrs) {\n stat.mem_freed += sweep(descr, true);\n }\n}\n\nsize_t gc_pool_allocator::sweep(descriptor_t& descr, bool add_to_freelist)\n{\n byte* it = descr.memory();\n byte* end = descr.memory() + descr.size();\n size_t size = descr.cell_size();\n\n size_t freed = 0;\n for (size_t i = 0; it < end; it += size, ++i) {\n if (!descr.get_mark(i)) {\n if (descr.is_init(i)) {\n descr.finalize(i);\n freed += size;\n if (add_to_freelist) {\n insert_into_freelist(it);\n }\n } else if (add_to_freelist) {\n insert_into_freelist(it);\n }\n }\n }\n return freed;\n}\n\nvoid gc_pool_allocator::insert_into_freelist(byte* ptr)\n{\n assert(contains(ptr));\n\n byte** next = reinterpret_cast<byte**>(ptr);\n next[0] = reinterpret_cast<byte*>(m_freelist);\n m_freelist = next;\n}\n\nvoid gc_pool_allocator::compact(compacting::forwarding& frwd, gc_heap_stat& stat)\n{\n compacting::two_finger_compactor compactor;\n auto rng = memory_range();\n compactor(rng, frwd, stat);\n}\n\nvoid gc_pool_allocator::fix(const compacting::forwarding& frwd)\n{\n auto rng = memory_range();\n compacting::fix_ptrs(rng.begin(), rng.end(), frwd);\n}\n\nvoid gc_pool_allocator::finalize()\n{\n for (auto& descr: m_descrs) {\n descr.unmark();\n }\n}\n\nbool gc_pool_allocator::empty() const\n{\n return m_descrs.empty();\n}\n\nbool gc_pool_allocator::is_compaction_required(const gc_heap_stat& stat) const\n{\n\/\/ return false;\n\/\/ return stat.residency() < RESIDENCY_COMPACTING_THRESHOLD;\n if (stat.residency() < RESIDENCY_COMPACTING_THRESHOLD) {\n return true;\n }\n if (stat.residency() > RESIDENCY_NON_COMPACTING_THRESHOLD) {\n return false;\n }\n if ((m_prev_residency > 0) && std::abs(stat.residency() - m_prev_residency) < RESIDENCY_EPS) {\n return true;\n }\n return false;\n}\n\ngc_pool_allocator::memory_range_type gc_pool_allocator::memory_range()\n{\n return utils::flatten_range(m_descrs.begin(), m_descrs.end());\n}\n\n}}}<|endoftext|>"} {"text":"<commit_before>#include <zlib.h>\n#include <lcm\/lcm-cpp.hpp>\n\n#include <lcmtypes\/bot_core\/planar_lidar_t.hpp>\n#include <lcmtypes\/bot_core\/pointcloud_t.hpp>\n#include <lcmtypes\/bot_core\/pose_t.hpp>\n#include <lcmtypes\/bot_core\/rigid_transform_t.hpp>\n\n#include <boost\/shared_ptr.hpp>\n#include \"lidar-odometry.hpp\"\n#include <ConciseArgs>\n\n#include <bot_param\/param_client.h>\n#include <bot_frames\/bot_frames.h>\n\nusing namespace std;\n\nstruct CommandLineConfig\n{\n bool use_velodyne;\n bool init_with_message; \/\/ initialize off of a pose or vicon\n std::string output_channel;\n std::string init_channel;\n};\n\nclass App{\n public:\n App(boost::shared_ptr<lcm::LCM> &lcm_, const CommandLineConfig& cl_cfg_);\n \n ~App(){\n }\n\n private:\n boost::shared_ptr<lcm::LCM> lcm_;\n const CommandLineConfig cl_cfg_;\n\n BotParam* botparam_;\n BotFrames* botframes_;\n\n void lidarHandler(const lcm::ReceiveBuffer* rbuf, const std::string& channel, const bot_core::planar_lidar_t* msg);\n void pointCloudHandler(const lcm::ReceiveBuffer* rbuf, const std::string& channel, const bot_core::pointcloud_t* msg);\n LidarOdom* lidarOdom_;\n\n Eigen::Isometry3d body_to_lidar_; \/\/ Fixed tf from the lidar to the robot's base link\n Eigen::Isometry3d world_to_body_init_; \/\/ Captures the position of the body frame in world at launch\n Eigen::Isometry3d world_to_body_now_; \/\/ running position estimate\n\n \/\/ Init handlers:\n void rigidTransformInitHandler(const lcm::ReceiveBuffer* rbuf, const std::string& channel, const bot_core::rigid_transform_t* msg);\n void poseInitHandler(const lcm::ReceiveBuffer* rbuf, const std::string& channel, const bot_core::pose_t* msg);\n void initState( const double trans[3], const double quat[4]);\n bool pose_initialized_;\n\n bot_core::pose_t getPoseAsBotPose(Eigen::Isometry3d pose, int64_t utime);\n\n int get_trans_with_utime(BotFrames *bot_frames,\n const char *from_frame, const char *to_frame, int64_t utime,\n Eigen::Isometry3d& mat);\n}; \n\nApp::App(boost::shared_ptr<lcm::LCM> &lcm_, const CommandLineConfig& cl_cfg_) : \n lcm_(lcm_), cl_cfg_(cl_cfg_){\n \n \/\/ Set up frames and config:\n botparam_ = bot_param_new_from_server(lcm_->getUnderlyingLCM(), 0);\n botframes_= bot_frames_get_global(lcm_->getUnderlyingLCM(), botparam_);\n\n if (cl_cfg_.use_velodyne){\n lcm_->subscribe(\"VELODYNE_HORIZONTAL\",&App::pointCloudHandler,this);\n int status = get_trans_with_utime( botframes_ , \"VELODYNE\", \"body\" , 0, body_to_lidar_);\n }else{\n lcm_->subscribe(\"HOKUYO_SCAN\",&App::lidarHandler,this);\n int status = get_trans_with_utime( botframes_ , \"HOKUYO_SCAN\", \"body\" , 0, body_to_lidar_);\n std::cout << \"Body to Lidar from param: \" << std::endl;\n std::cout << body_to_lidar_.matrix() << std::endl;\n\n }\n\n pose_initialized_ = false;\n if (!cl_cfg_.init_with_message){\n std::cout << \"Init internal est using default\\n\";\n world_to_body_init_ = Eigen::Isometry3d::Identity();\n\n \/*\n world_to_body_init_.setIdentity();\n world_to_body_init_.translation() << 1.2, 1.67, 0.32;\n Eigen::Quaterniond q(-0.045668, -0.004891, -0.00909, 0.9989);\n world_to_body_init_.rotate(q);\n bot_core::pose_t pose_msg_body = getPoseAsBotPose( world_to_lidar_init_ , 0);\n lcm_->publish(\"POSE_BODY_ALT\", &pose_msg_body );\n pose_initialized_ = true;\n *\/\n\n pose_initialized_ = true;\n }else{\n lcm_->subscribe(\"VICON_BODY|VICON_FRONTPLATE\",&App::rigidTransformInitHandler,this);\n lcm_->subscribe(cl_cfg_.init_channel,&App::poseInitHandler,this);\n std::cout << \"Waiting for Init message to LIDAR estimator\\n\";\n }\n\n lidarOdom_ = new LidarOdom(lcm_);\n}\n\nint App::get_trans_with_utime(BotFrames *bot_frames,\n const char *from_frame, const char *to_frame, int64_t utime,\n Eigen::Isometry3d & mat){\n int status;\n double matx[16];\n status = bot_frames_get_trans_mat_4x4_with_utime( bot_frames, from_frame, to_frame, utime, matx);\n for (int i = 0; i < 4; ++i) {\n for (int j = 0; j < 4; ++j) {\n mat(i,j) = matx[i*4+j];\n }\n } \n\n return status;\n}\n\nbot_core::pose_t App::getPoseAsBotPose(Eigen::Isometry3d pose, int64_t utime){\n bot_core::pose_t pose_msg;\n pose_msg.utime = utime;\n pose_msg.pos[0] = pose.translation().x();\n pose_msg.pos[1] = pose.translation().y();\n pose_msg.pos[2] = pose.translation().z();\n Eigen::Quaterniond r_x(pose.rotation());\n pose_msg.orientation[0] = r_x.w();\n pose_msg.orientation[1] = r_x.x();\n pose_msg.orientation[2] = r_x.y();\n pose_msg.orientation[3] = r_x.z();\n return pose_msg;\n}\n\n\nvoid App::lidarHandler(const lcm::ReceiveBuffer* rbuf,\n const std::string& channel, const bot_core::planar_lidar_t* msg){\n if (!pose_initialized_){\n std::cout << \"Estimate not initialised, exiting lidarHandler\\n\";\n return;\n }\n\n \/\/ 1. Update LIDAR Odometry\n std::vector<float> ranges_copy = msg->ranges;\n float* ranges = &ranges_copy[0];\n lidarOdom_->doOdometry(ranges, msg->nranges, msg->rad0, msg->radstep, msg->utime);\n\n \/\/ 2. Determine the body position using the LIDAR motion estimate:\n Eigen::Isometry3d lidar_init_to_lidar_now = lidarOdom_->getCurrentPose();\n Eigen::Isometry3d world_to_lidar_now = world_to_body_init_*body_to_lidar_*lidar_init_to_lidar_now;\n world_to_body_now_ = world_to_lidar_now * body_to_lidar_.inverse();\n\n \/\/bot_core::pose_t pose_msg = getPoseAsBotPose( lidar_init_to_lidar_now , msg->utime);\n \/\/lcm_->publish(\"POSE_BODY_ALT\", &pose_msg );\n bot_core::pose_t pose_msg_body = getPoseAsBotPose( world_to_body_now_ , msg->utime);\n lcm_->publish(cl_cfg_.output_channel, &pose_msg_body );\n}\n\n\nvoid App::pointCloudHandler(const lcm::ReceiveBuffer* rbuf,\n const std::string& channel, const bot_core::pointcloud_t* msg){\n if (!pose_initialized_){\n std::cout << \"Estimate not initialised, exiting pointCloudHandler\\n\";\n return;\n }\n\n \/\/ 1. Update LIDAR Odometry\n std::vector<float> x;\n std::vector<float> y;\n for (int i=0;i<msg->n_points; i++){\n x.push_back( msg->points[i][0] );\n y.push_back( msg->points[i][1] );\n }\n\n lidarOdom_->doOdometry(x, y, msg->n_points, msg->utime);\n\n \/\/ 2. Determine the body position using the LIDAR motion estimate:\n Eigen::Isometry3d lidar_init_to_lidar_now = lidarOdom_->getCurrentPose();\n Eigen::Isometry3d world_to_lidar_now = world_to_body_init_*body_to_lidar_*lidar_init_to_lidar_now;\n world_to_body_now_ = world_to_lidar_now * body_to_lidar_.inverse();\n\n \/\/bot_core::pose_t pose_msg = getPoseAsBotPose( world_to_lidar_now , msg->utime);\n \/\/lcm_->publish(\"POSE_BODY_ALT\", &pose_msg );\n bot_core::pose_t pose_msg_body = getPoseAsBotPose( world_to_body_now_ , msg->utime);\n lcm_->publish(cl_cfg_.output_channel, &pose_msg_body );\n}\n\n\nvoid App::initState(const double trans[3], const double quat[4]){\n if ( !cl_cfg_.init_with_message || pose_initialized_ ){\n return;\n }\n\n std::cout << \"Init internal est using rigid transform or pose\\n\";\n \n world_to_body_init_.setIdentity();\n world_to_body_init_.translation() << trans[0], trans[1] , trans[2];\n Eigen::Quaterniond quatE = Eigen::Quaterniond(quat[0], quat[1], \n quat[2], quat[3]);\n world_to_body_init_.rotate(quatE); \n pose_initialized_ = TRUE;\n}\n\nvoid App::rigidTransformInitHandler(const lcm::ReceiveBuffer* rbuf, const std::string& channel, const bot_core::rigid_transform_t* msg){\n initState(msg->trans, msg->quat);\n}\n\nvoid App::poseInitHandler(const lcm::ReceiveBuffer* rbuf, const std::string& channel, const bot_core::pose_t* msg){\n initState(msg->pos, msg->orientation);\n}\n\nint main(int argc, char **argv){\n CommandLineConfig cl_cfg;\n cl_cfg.use_velodyne = false;\n cl_cfg.init_with_message = TRUE;\n cl_cfg.output_channel = \"POSE_BODY\";\n cl_cfg.init_channel = \"POSE_VICON\";\n\n ConciseArgs parser(argc, argv, \"simple-fusion\");\n parser.add(cl_cfg.init_with_message, \"g\", \"init_with_message\", \"Bootstrap internal estimate using VICON or POSE_INIT\");\n parser.add(cl_cfg.output_channel, \"o\", \"output_channel\", \"Output message e.g POSE_BODY\");\n parser.add(cl_cfg.use_velodyne, \"v\", \"use_velodyne\", \"Use a velodyne instead of the LIDAR\");\n parser.add(cl_cfg.init_channel, \"i\", \"init_channel\", \"Read the init message from this channel, e.g., POSE_VICON\");\n parser.parse();\n\n boost::shared_ptr<lcm::LCM> lcm(new lcm::LCM);\n if(!lcm->good()){\n std::cerr <<\"ERROR: lcm is not good()\" <<std::endl;\n }\n App app= App(lcm, cl_cfg);\n while(0 == lcm->handle());\n}\n<commit_msg>make channel an arguement<commit_after>#include <zlib.h>\n#include <lcm\/lcm-cpp.hpp>\n\n#include <lcmtypes\/bot_core\/planar_lidar_t.hpp>\n#include <lcmtypes\/bot_core\/pointcloud_t.hpp>\n#include <lcmtypes\/bot_core\/pose_t.hpp>\n#include <lcmtypes\/bot_core\/rigid_transform_t.hpp>\n\n#include <boost\/shared_ptr.hpp>\n#include \"lidar-odometry.hpp\"\n#include <ConciseArgs>\n\n#include <bot_param\/param_client.h>\n#include <bot_frames\/bot_frames.h>\n\nusing namespace std;\n\nstruct CommandLineConfig\n{\n bool use_velodyne;\n bool init_with_message; \/\/ initialize off of a pose or vicon\n std::string input_channel;\n std::string output_channel;\n std::string init_channel;\n};\n\nclass App{\n public:\n App(boost::shared_ptr<lcm::LCM> &lcm_, const CommandLineConfig& cl_cfg_);\n \n ~App(){\n }\n\n private:\n boost::shared_ptr<lcm::LCM> lcm_;\n const CommandLineConfig cl_cfg_;\n\n BotParam* botparam_;\n BotFrames* botframes_;\n\n void lidarHandler(const lcm::ReceiveBuffer* rbuf, const std::string& channel, const bot_core::planar_lidar_t* msg);\n void pointCloudHandler(const lcm::ReceiveBuffer* rbuf, const std::string& channel, const bot_core::pointcloud_t* msg);\n LidarOdom* lidarOdom_;\n\n Eigen::Isometry3d body_to_lidar_; \/\/ Fixed tf from the lidar to the robot's base link\n Eigen::Isometry3d world_to_body_init_; \/\/ Captures the position of the body frame in world at launch\n Eigen::Isometry3d world_to_body_now_; \/\/ running position estimate\n\n \/\/ Init handlers:\n void rigidTransformInitHandler(const lcm::ReceiveBuffer* rbuf, const std::string& channel, const bot_core::rigid_transform_t* msg);\n void poseInitHandler(const lcm::ReceiveBuffer* rbuf, const std::string& channel, const bot_core::pose_t* msg);\n void initState( const double trans[3], const double quat[4]);\n bool pose_initialized_;\n\n bot_core::pose_t getPoseAsBotPose(Eigen::Isometry3d pose, int64_t utime);\n\n int get_trans_with_utime(BotFrames *bot_frames,\n const char *from_frame, const char *to_frame, int64_t utime,\n Eigen::Isometry3d& mat);\n}; \n\nApp::App(boost::shared_ptr<lcm::LCM> &lcm_, const CommandLineConfig& cl_cfg_) : \n lcm_(lcm_), cl_cfg_(cl_cfg_){\n \n \/\/ Set up frames and config:\n botparam_ = bot_param_new_from_server(lcm_->getUnderlyingLCM(), 0);\n botframes_= bot_frames_get_global(lcm_->getUnderlyingLCM(), botparam_);\n\n if (cl_cfg_.use_velodyne){\n lcm_->subscribe(\"VELODYNE_HORIZONTAL\",&App::pointCloudHandler,this);\n int status = get_trans_with_utime( botframes_ , \"VELODYNE\", \"body\" , 0, body_to_lidar_);\n }else{\n lcm_->subscribe(cl_cfg_.input_channel ,&App::lidarHandler,this);\n int status = get_trans_with_utime( botframes_ , cl_cfg_.input_channel, \"body\" , 0, body_to_lidar_);\n std::cout << \"Body to Lidar from param: \" << std::endl;\n std::cout << body_to_lidar_.matrix() << std::endl;\n\n }\n\n pose_initialized_ = false;\n if (!cl_cfg_.init_with_message){\n std::cout << \"Init internal est using default\\n\";\n world_to_body_init_ = Eigen::Isometry3d::Identity();\n\n \/*\n world_to_body_init_.setIdentity();\n world_to_body_init_.translation() << 1.2, 1.67, 0.32;\n Eigen::Quaterniond q(-0.045668, -0.004891, -0.00909, 0.9989);\n world_to_body_init_.rotate(q);\n bot_core::pose_t pose_msg_body = getPoseAsBotPose( world_to_lidar_init_ , 0);\n lcm_->publish(\"POSE_BODY_ALT\", &pose_msg_body );\n pose_initialized_ = true;\n *\/\n\n pose_initialized_ = true;\n }else{\n lcm_->subscribe(\"VICON_BODY|VICON_FRONTPLATE\",&App::rigidTransformInitHandler,this);\n lcm_->subscribe(cl_cfg_.init_channel,&App::poseInitHandler,this);\n std::cout << \"Waiting for Init message to LIDAR estimator\\n\";\n }\n\n lidarOdom_ = new LidarOdom(lcm_);\n}\n\nint App::get_trans_with_utime(BotFrames *bot_frames,\n const char *from_frame, const char *to_frame, int64_t utime,\n Eigen::Isometry3d & mat){\n int status;\n double matx[16];\n status = bot_frames_get_trans_mat_4x4_with_utime( bot_frames, from_frame, to_frame, utime, matx);\n for (int i = 0; i < 4; ++i) {\n for (int j = 0; j < 4; ++j) {\n mat(i,j) = matx[i*4+j];\n }\n } \n\n return status;\n}\n\nbot_core::pose_t App::getPoseAsBotPose(Eigen::Isometry3d pose, int64_t utime){\n bot_core::pose_t pose_msg;\n pose_msg.utime = utime;\n pose_msg.pos[0] = pose.translation().x();\n pose_msg.pos[1] = pose.translation().y();\n pose_msg.pos[2] = pose.translation().z();\n Eigen::Quaterniond r_x(pose.rotation());\n pose_msg.orientation[0] = r_x.w();\n pose_msg.orientation[1] = r_x.x();\n pose_msg.orientation[2] = r_x.y();\n pose_msg.orientation[3] = r_x.z();\n return pose_msg;\n}\n\n\nvoid App::lidarHandler(const lcm::ReceiveBuffer* rbuf,\n const std::string& channel, const bot_core::planar_lidar_t* msg){\n if (!pose_initialized_){\n std::cout << \"Estimate not initialised, exiting lidarHandler\\n\";\n return;\n }\n\n \/\/ 1. Update LIDAR Odometry\n std::vector<float> ranges_copy = msg->ranges;\n float* ranges = &ranges_copy[0];\n lidarOdom_->doOdometry(ranges, msg->nranges, msg->rad0, msg->radstep, msg->utime);\n\n \/\/ 2. Determine the body position using the LIDAR motion estimate:\n Eigen::Isometry3d lidar_init_to_lidar_now = lidarOdom_->getCurrentPose();\n Eigen::Isometry3d world_to_lidar_now = world_to_body_init_*body_to_lidar_*lidar_init_to_lidar_now;\n world_to_body_now_ = world_to_lidar_now * body_to_lidar_.inverse();\n\n \/\/bot_core::pose_t pose_msg = getPoseAsBotPose( lidar_init_to_lidar_now , msg->utime);\n \/\/lcm_->publish(\"POSE_BODY_ALT\", &pose_msg );\n bot_core::pose_t pose_msg_body = getPoseAsBotPose( world_to_body_now_ , msg->utime);\n lcm_->publish(cl_cfg_.output_channel, &pose_msg_body );\n}\n\n\nvoid App::pointCloudHandler(const lcm::ReceiveBuffer* rbuf,\n const std::string& channel, const bot_core::pointcloud_t* msg){\n if (!pose_initialized_){\n std::cout << \"Estimate not initialised, exiting pointCloudHandler\\n\";\n return;\n }\n\n \/\/ 1. Update LIDAR Odometry\n std::vector<float> x;\n std::vector<float> y;\n for (int i=0;i<msg->n_points; i++){\n x.push_back( msg->points[i][0] );\n y.push_back( msg->points[i][1] );\n }\n\n lidarOdom_->doOdometry(x, y, msg->n_points, msg->utime);\n\n \/\/ 2. Determine the body position using the LIDAR motion estimate:\n Eigen::Isometry3d lidar_init_to_lidar_now = lidarOdom_->getCurrentPose();\n Eigen::Isometry3d world_to_lidar_now = world_to_body_init_*body_to_lidar_*lidar_init_to_lidar_now;\n world_to_body_now_ = world_to_lidar_now * body_to_lidar_.inverse();\n\n \/\/bot_core::pose_t pose_msg = getPoseAsBotPose( world_to_lidar_now , msg->utime);\n \/\/lcm_->publish(\"POSE_BODY_ALT\", &pose_msg );\n bot_core::pose_t pose_msg_body = getPoseAsBotPose( world_to_body_now_ , msg->utime);\n lcm_->publish(cl_cfg_.output_channel, &pose_msg_body );\n}\n\n\nvoid App::initState(const double trans[3], const double quat[4]){\n if ( !cl_cfg_.init_with_message || pose_initialized_ ){\n return;\n }\n\n std::cout << \"Init internal est using rigid transform or pose\\n\";\n \n world_to_body_init_.setIdentity();\n world_to_body_init_.translation() << trans[0], trans[1] , trans[2];\n Eigen::Quaterniond quatE = Eigen::Quaterniond(quat[0], quat[1], \n quat[2], quat[3]);\n world_to_body_init_.rotate(quatE); \n pose_initialized_ = TRUE;\n}\n\nvoid App::rigidTransformInitHandler(const lcm::ReceiveBuffer* rbuf, const std::string& channel, const bot_core::rigid_transform_t* msg){\n initState(msg->trans, msg->quat);\n}\n\nvoid App::poseInitHandler(const lcm::ReceiveBuffer* rbuf, const std::string& channel, const bot_core::pose_t* msg){\n initState(msg->pos, msg->orientation);\n}\n\nint main(int argc, char **argv){\n CommandLineConfig cl_cfg;\n cl_cfg.use_velodyne = false;\n cl_cfg.init_with_message = TRUE;\n cl_cfg.input_channel = \"HOKUYO_SCAN\";\n cl_cfg.output_channel = \"POSE_BODY\";\n cl_cfg.init_channel = \"POSE_VICON\";\n\n ConciseArgs parser(argc, argv, \"simple-fusion\");\n parser.add(cl_cfg.init_with_message, \"g\", \"init_with_message\", \"Bootstrap internal estimate using VICON or POSE_INIT\");\n parser.add(cl_cfg.input_channel, \"s\", \"input_channel\", \"Input LIDAR scan message\");\n parser.add(cl_cfg.output_channel, \"o\", \"output_channel\", \"Output message e.g POSE_BODY\");\n parser.add(cl_cfg.use_velodyne, \"v\", \"use_velodyne\", \"Use a velodyne instead of the LIDAR\");\n parser.add(cl_cfg.init_channel, \"i\", \"init_channel\", \"Read the init message from this channel, e.g., POSE_VICON\");\n parser.parse();\n\n boost::shared_ptr<lcm::LCM> lcm(new lcm::LCM);\n if(!lcm->good()){\n std::cerr <<\"ERROR: lcm is not good()\" <<std::endl;\n }\n App app= App(lcm, cl_cfg);\n while(0 == lcm->handle());\n}\n<|endoftext|>"} {"text":"<commit_before>\/***********************************************************************************************************************\n**\n** Copyright (c) 2011, 2015 ETH Zurich\n** All rights reserved.\n**\n** Redistribution and use in source and binary forms, with or without modification, are permitted provided that the\n** following conditions are met:\n**\n** * Redistributions of source code must retain the above copyright notice, this list of conditions and the following\n** disclaimer.\n** * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the\n** following disclaimer in the documentation and\/or other materials provided with the distribution.\n** * Neither the name of the ETH Zurich nor the names of its contributors may be used to endorse or promote products\n** derived from this software without specific prior written permission.\n**\n**\n** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES,\n** INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n** SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n**\n***********************************************************************************************************************\/\n\n#include \"EnvisionPPCallbacks.h\"\n\n#include <algorithm>\n\n#include <QtCore\/QDebug>\n\n#include <clang\/Lex\/MacroArgs.h>\n\nEnvisionPPCallbacks::EnvisionPPCallbacks(clang::SourceManager& srcManager, std::string fileName,\n\t\t\t\t\t\t\t\t\t\t\t\t\t QHash<QString, QString>& attributes)\n\t: sourceManager_{srcManager}, fileName_{fileName}, attributes_{attributes} {}\n\nvoid EnvisionPPCallbacks::MacroExpands(const clang::Token &MacroNameTok, const clang::MacroDirective *,\n\t\t\t\t\t\t\t\t\t\t\t\t\tclang::SourceRange range, const clang::MacroArgs *Args)\n{\n\t\/\/ We only care about ATTRIBUTE macros:\n\tif (MacroNameTok.getIdentifierInfo()->getName() == \"ATTRIBUTE\" ||\n\t\t MacroNameTok.getIdentifierInfo()->getName() == \"ATTRIBUTE_VALUE_CUSTOM_RETURN\")\n\t{\n\t\t\/\/ We only care about ATTRIBUTES in the currentFile:\n\t\tif (sourceManager_.getFilename(range.getBegin()) != fileName_) return;\n\t\tunsigned numArguments = Args->getNumArguments();\n\t\tQ_ASSERT(numArguments >= 3); \/\/ ATTRIBUTE macros have 3 arguments\n\n\t\tauto attributeName = QString::fromStdString(Args->getUnexpArgument(1u)->getIdentifierInfo()->getName().str());\n\t\tauto attributeSetter = QString::fromStdString(Args->getUnexpArgument(2u)->getIdentifierInfo()->getName().str());\n\n\t\tattributes_.insert(attributeName, attributeSetter);\n\t}\n\telse if (MacroNameTok.getIdentifierInfo()->getName() == \"ATTRIBUTE_OOP_NAME_SYMBOL\")\n\t{\n\t\tattributes_.insert(\"name\", \"setName\");\n\t}\n\n}\n\n<commit_msg>Wrap ATTRIBUTE_VALUE attributes as well<commit_after>\/***********************************************************************************************************************\n**\n** Copyright (c) 2011, 2015 ETH Zurich\n** All rights reserved.\n**\n** Redistribution and use in source and binary forms, with or without modification, are permitted provided that the\n** following conditions are met:\n**\n** * Redistributions of source code must retain the above copyright notice, this list of conditions and the following\n** disclaimer.\n** * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the\n** following disclaimer in the documentation and\/or other materials provided with the distribution.\n** * Neither the name of the ETH Zurich nor the names of its contributors may be used to endorse or promote products\n** derived from this software without specific prior written permission.\n**\n**\n** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES,\n** INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n** SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n**\n***********************************************************************************************************************\/\n\n#include \"EnvisionPPCallbacks.h\"\n\n#include <algorithm>\n\n#include <QtCore\/QDebug>\n\n#include <clang\/Lex\/MacroArgs.h>\n\nEnvisionPPCallbacks::EnvisionPPCallbacks(clang::SourceManager& srcManager, std::string fileName,\n\t\t\t\t\t\t\t\t\t\t\t\t\t QHash<QString, QString>& attributes)\n\t: sourceManager_{srcManager}, fileName_{fileName}, attributes_{attributes} {}\n\nvoid EnvisionPPCallbacks::MacroExpands(const clang::Token &MacroNameTok, const clang::MacroDirective *,\n\t\t\t\t\t\t\t\t\t\t\t\t\tclang::SourceRange range, const clang::MacroArgs *Args)\n{\n\t\/\/ We only care about ATTRIBUTE macros:\n\tif (MacroNameTok.getIdentifierInfo()->getName() == \"ATTRIBUTE\" ||\n\t\t MacroNameTok.getIdentifierInfo()->getName() == \"ATTRIBUTE_VALUE_CUSTOM_RETURN\" ||\n\t\t MacroNameTok.getIdentifierInfo()->getName() == \"ATTRIBUTE_VALUE\")\n\t{\n\t\t\/\/ We only care about ATTRIBUTES in the currentFile:\n\t\tif (sourceManager_.getFilename(range.getBegin()) != fileName_) return;\n\t\tunsigned numArguments = Args->getNumArguments();\n\t\tQ_ASSERT(numArguments >= 3); \/\/ ATTRIBUTE macros have 3 arguments\n\n\t\tauto attributeName = QString::fromStdString(Args->getUnexpArgument(1u)->getIdentifierInfo()->getName().str());\n\t\tauto attributeSetter = QString::fromStdString(Args->getUnexpArgument(2u)->getIdentifierInfo()->getName().str());\n\n\t\tattributes_.insert(attributeName, attributeSetter);\n\t}\n\telse if (MacroNameTok.getIdentifierInfo()->getName() == \"ATTRIBUTE_OOP_NAME_SYMBOL\")\n\t{\n\t\tattributes_.insert(\"name\", \"setName\");\n\t}\n\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/\/Adapted from sites.google.com\/site\/stevenhalim\/home\/material\n\/\/or cpbook.net\n\n#define EPS 0.000000001;\n\nbool equal(double a, double b) { return fabs(a-b) < EPS; }\n\nstruct point;\nstruct line;\nstruct vec;\n\n\/\/ use this whenever possible\n\/\/struct point { int x, y\nstruct point {\n double x,y;\n point();\n point(double _x, double _y);\n bool operator == (const point& o);\n bool operator< (const point& other);\n vec operator- (const point& other);\n point operator+ (const vec& v);\n};\n\ndouble dist(const point& p1, const point& p2) {\n return hypot(p1.x - p2.x, p1.y - p2.y);\n}\n\nstruct line {\n double a, b, c;\n line (const point& p1, const point& p2);\n bool operator== (const line& other);\n \/\/are they parallel\n bool operator|| (const line& other);\n};\n\nbool intersect(const line& l1, const line& l2, point& p) {\n \/\/ all points same\n if (l1 == l2) { return false; }\n \/\/ no intersection\n if (l1 || l2) { return false; }\n\n \/\/ solve system of 2 linear algebraic equations with 2 unknowns\n p.x = (double)(l2.b * l1.c - l1 b * l2.c) \/ (l2.a * l1.b - l1.a * l2.b);\n\n \/\/ test for vertical line (avoid div by zero)\n if (fabs(l1.b) > EPS) { p.y = - (l1.a * p.x + l1.c) \/ l1.b; }\n else { p.y = - (l2.a * p.x + l2.c) \/ l2.b; }\n\n return true;\n}\n\n\n\/\/struct vec { int dx, dy;\nstruct vec {\n double dx, dy, mag;\n vec(double x, double y);\n vec(const point& from, const point& to) \/\/ convert 2 points to vector\n vec normalize();\n vec operator+ (const vec& other);\n \/\/scale\n vec operator* (double s);\n \/\/cross product\n vec operator* (const vec& other);\n};\n\npoint::point() :x(0), y(0) {}\npoint::point(double _x, double _y)\n :x(_x), y(_y)\n{}\nbool point::operator == (const point& o)\n{ return equal(x,o.x) && equal(y,o.y); }\nbool point::operator < (const point& other) {\n if (fabs(x - other.x) > EPS) return x < other.x;\n return y < other.y;\n}\nvec point::operator- (const point& other){ return vec(other,*this); }\npoint point::operator+ (const vec& v){ return point(x+v.dx,y+v.dy); }\n\n\nline::line (const point& p1, const point& p2) {\n \/\/ vertical line is handled nicely below\n \/\/if (p1.x == p2.x) {\n if (equal(p1.x, p2.x)) { \n a = 1.0;\n b = 0.0;\n c = -p1.x;\n }\n\n else {\n a = -(double)(p1.y - p2.y) \/ (p1.x - p2.x);\n b = 1.0;\n c = -(double)(a * p1.x) - (b * p1.y);\n }\n}\n\nbool line::operator== (const line& other) {\n return (*this || other) && (fabs(c - other.c) < EPS);\n}\n\nbool line::operator|| (const line& other){\n \/\/ check coefficient a + b\n return (fabs(a-other.a) < EPS) && (fabs(b-other.b) < EPS);\n}\n\n\nvec::vec(double deltaX, double deltaY)\n : dx(deltaX), dy(deltaY)\n{\n double magX = fabs(dx);\n double magY = fabs(dy);\n if (magX > EPS && magY > EPS) { mag = hypot(magX, magY); }\n else if (magX < EPS) { mag = magY; }\n else if (magY < EPS) { mag = magX; }\n else { mag = 0; }\n}\n\nvec::vec(const point& from, const point& to)\n :vec(to.x - from.x, to.y - from.y)\n{}\nvec::normalize() { return vec(dx \/ mag, dy \/ mag); }\nvec vec::operator+ (const vec & other){\n return vec(dx + other.dx, dy + other.dy);\n}\nvec vec::operator* (double s){ return vec(s * dx, s * dy); }\nvec vec::operator* (const vec & other){\n \n}\n<commit_msg>Added polygon code<commit_after>\/\/Adapted from sites.google.com\/site\/stevenhalim\/home\/material\n\/\/or cpbook.net\n#include <cmath>\n#include <vector>\n\n#define EPS 0.000000001;\n#define COLLINEAR 0\n#define LEFT 1\n#define RIGHT -1\n#define polygon vector<point>\n\nusing namespace std;\n\nbool equal(double a, double b) { return fabs(a-b) < EPS; }\n\nstruct point;\nstruct line;\nstruct vec;\n\n\/\/ use this whenever possible\n\/\/struct point { int x, y\nstruct point {\n double x,y;\n point();\n point(double _x, double _y);\n bool operator == (const point& o);\n bool operator< (const point& other);\n vec operator- (const point& other);\n point operator+ (const vec& v);\n};\n\nstruct line {\n double a, b, c;\n line (const point& p1, const point& p2);\n bool operator== (const line& other);\n \/\/are they parallel\n bool operator|| (const line& other);\n};\n\n\/\/struct vec { int dx, dy;\nstruct vec {\n double dx, dy, mag;\n vec(double x, double y);\n vec(const point& from, const point& to) \/\/ convert 2 points to vector\n vec normalize();\n vec operator+ (const vec& other);\n \/\/scale\n vec operator* (double s);\n \/\/dot product\n double operator* (const vec& other);\n};\n\npoint::point() :x(0), y(0) {}\npoint::point(double _x, double _y)\n :x(_x), y(_y)\n{}\nbool point::operator == (const point& o)\n{ return equal(x,o.x) && equal(y,o.y); }\nbool point::operator < (const point& other) {\n if (fabs(x - other.x) > EPS) return x < other.x;\n return y < other.y;\n}\nvec point::operator- (const point& other){ return vec(other,*this); }\npoint point::operator+ (const vec& v){ return point(x+v.dx,y+v.dy); }\ndouble dist(const point& p1, const point& p2) {\n return hypot(p1.x - p2.x, p1.y - p2.y);\n}\n\nline::line (const point& p1, const point& p2) {\n \/\/ vertical line is handled nicely below\n \/\/if (p1.x == p2.x) {\n if (equal(p1.x, p2.x)) { \n a = 1.0;\n b = 0.0;\n c = -p1.x;\n }\n\n else {\n a = -(double)(p1.y - p2.y) \/ (p1.x - p2.x);\n b = 1.0;\n c = -(double)(a * p1.x) - (b * p1.y);\n }\n}\n\nbool line::operator== (const line& other) {\n return (*this || other) && (fabs(c - other.c) < EPS);\n}\n\nbool line::operator|| (const line& other){\n \/\/ check coefficient a + b\n return (fabs(a-other.a) < EPS) && (fabs(b-other.b) < EPS);\n}\n\nbool intersect(const line& l1, const line& l2, point& p) {\n \/\/ all points same\n if (l1 == l2) { return false; }\n \/\/ no intersection\n if (l1 || l2) { return false; }\n\n \/\/ solve system of 2 linear algebraic equations with 2 unknowns\n p.x = (double)(l2.b * l1.c - l1 b * l2.c) \/ (l2.a * l1.b - l1.a * l2.b);\n\n \/\/ test for vertical line (avoid div by zero)\n if (fabs(l1.b) > EPS) { p.y = - (l1.a * p.x + l1.c) \/ l1.b; }\n else { p.y = - (l2.a * p.x + l2.c) \/ l2.b; }\n\n return true;\n}\n\n\nvec::vec(double deltaX, double deltaY)\n : dx(deltaX), dy(deltaY)\n{\n double magX = fabs(dx);\n double magY = fabs(dy);\n if (magX > EPS && magY > EPS) { mag = hypot(magX, magY); }\n else if (magX < EPS) { mag = magY; }\n else if (magY < EPS) { mag = magX; }\n else { mag = 0; }\n}\n\nvec::vec(const point& from, const point& to)\n :vec(to.x - from.x, to.y - from.y)\n{}\nvec::normalize() { return vec(dx \/ mag, dy \/ mag); }\nvec vec::operator+ (const vec & other){\n return vec(dx + other.dx, dy + other.dy);\n}\nvec vec::operator* (double s){ return vec(s * dx, s * dy); }\ndouble vec::operator* (const vec & other){\n return dx * other.dx + dy * other.dy;\n}\n\n\/\/square of triangle area\n\/*\nint area2(point a, point b, point c) {\n return a.x * b.y - a.y * b.x + b.x * c.y - b.y * c.x + c.x * a.y - c.y * a.x;\n}\n*\/\n\n\/\/ square of distance between 2 points\nint dist2(point a, point b) {\n int dx = a.x - b.x, dy = a.y - b.y; return dx * dx + dy * dy;\n}\n\nint turn(const point& a, const point& b, const point& c) {\n double result = (c.x - b.x) * (a.y - b.y) - (c.y - b.y) * (a.x - b.x);\n\n if (result < 0) return RIGHT; \/\/ a->B->C is a right turn\n if (result > 0) return LEFT; \/\/ a->B->C is a left turn\n\n return COLLINEAR; \/\/ a->B->C is a straight line, i.e. a, B, C are collinear\n}\n\n\/\/important angle-sorting functor\nclass LeftTurnCmp{\nprivate:\n point pivot;\npublic:\n LeftTurnCmp(const point& pivot) :pivot(pivot) {}\n bool operator()(const point& a, const& point b){\n if (turn(pivot, a, b) == COLLINEAR)\n return dist2(pivot, a) < dist2(pivot, b); \/\/ which one closer\n int d1x = a.x - pivot.x, d1y = a.y - pivot.y;\n int d2x = b.x - pivot.x, d2y = b.y - pivot.y;\n return (atan2((double)d1y, (double)d1x)\n\t - atan2((double)d2y, (double)d2x)) < 0;\n }\n};\n\n\/\/Counterclockwise starting from bottom-most point\nvoid orderByAngle(polygon& p){\n \/\/ first, find p0 = point with lowest Y and if tie: rightmost X\n int lowestIndex = 0;\n int n = p.size();\n\n for (int i = 1; i < n; i++) {\n if (p[i].y < p[lowestIndex].y ||\n\t(p[i].y == p[lowestIndex].y && p[i].x > p[lowestIndex].x))\n { lowestIndex = i; }\n }\n\n swap(p[0],p[lowestIndex]);\n\n \/\/ second, sort points by angle w.r.t. lowest\n LeftTurnCmp angle_cmp(p[0]);\n sort(++p.begin(), p.end(), angle_cmp);\n}\n\n\/* The following code assumes you have ordered the points! *\/\n\ndouble perimeter(polygon& p) {\n double result = 0.0;\n\n \/\/double x1, y1, x2, y2, dx, dy;\n for (int i = 0; i < p.size(); i++) {\n result += distance(p[i],p[(i+1)%p.size()]);\n }\n\n return result;\n}\n\ndouble determinant(polygon& p) {\n double result = 0;\n\n double x1, y1, x2, y2;\n for (int i = 0; i < p.size(); i++) {\n x1 = p[i].x; x2 = p[(i + 1) % p.size()].x;\n y1 = p[i].y; y2 = p[(i + 1) % p.size()].y;\n result += (x1 * y2 - x2 * y1);\n }\n\n return result;\n}\n\n\/\/ area is half of the determinant and the result may be a non-integer\ndouble area(polygon& p)\n{ return fabs(determinant(p)) \/ 2.0); }\n\n\/\/n must be >= 3 for this method to work\nvoid getConvexHull(polygon& p, polygon& convexHull){\n int n = p.size();\n\n stack<point> S;\n point prev, now;\n S.push(p[n - 1]); \/\/ put two starting vertices into stack S\n S.push(p[0]);\n\n int i = 1; \/\/ and start checking the rest\n\n while (i < n) {\n \/\/ get the 2nd item from top of S\n now = S.top();\n S.pop();\n prev = S.top();\n S.push(now); \n\n if (turn(prev, now, p[i]) == LEFT) {\n S.push(p[i]); \/\/ accept\n i++;\n }\n\n \/\/ otherwise pop this point until we have a left turn\n else { S.pop(); }\n }\n\n while (!S.empty()) { \/\/ from stack back to vector\n convexHull.push_back(S.top());\n S.pop();\n }\n\n convexHull.pop_back(); \/\/ the last one is a duplicate of first one\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n This file is part of KDE Kontact.\n\n Copyright (c) 2001 Matthias Hoelzer-Kluepfel <mhk@kde.org>\n Copyright (c) 2002-2003 Daniel Molkentin <molkentin@kde.org>\n\n This program is free software; you can redistribute it and\/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation; either version 2 of the License, or\n (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with this program; if not, write to the Free Software\n Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.\n*\/\n\n#include <dcopclient.h>\n#include <kaboutdata.h>\n#include <kcmdlineargs.h>\n#include <kiconloader.h>\n#include <klocale.h>\n#include <kuniqueapplication.h>\n\n#include <qlabel.h>\n#if (QT_VERSION-0 >= 0x030200)\n#include <qsplashscreen.h>\n#else\n#include \"splash.h\"\n#endif\n\n#include \"mainwindow.h\"\n\nstatic const char description[] =\n I18N_NOOP( \"A KDE Personal Information Manager\" );\n\nstatic const char version[] = \"0.7.3 (Beta 1)\";\n\nint main(int argc, char **argv)\n{\n KAboutData about( \"kontact\", I18N_NOOP( \"Kontact\" ), version, description,\n KAboutData::License_GPL, I18N_NOOP(\"(C) 2001-2003 The Kontact developers\"), 0, \"http:\/\/kontact.kde.org\", \"kde-pim@kde.org\" );\n about.addAuthor( \"Daniel Molkentin\", 0, \"molkentin@kde.org\" );\n about.addAuthor( \"Don Sanders\", 0, \"sanders@kde.org\" );\n about.addAuthor( \"Cornelius Schumacher\", 0, \"schumacher@kde.org\" );\n about.addAuthor( \"Tobias Koenig\", 0, \"tokoe@kde.org\" );\n about.addAuthor( \"Sven Lüppken\", 0, \"sven@kde.org\" );\n about.addAuthor( \"Matthias Hoelzer-Kluepfel\", I18N_NOOP(\"Original Author\"), \"mhk@kde.org\" );\n\n KCmdLineArgs::init( argc, argv, &about );\n KUniqueApplication app;\n\n \/\/ show splash\n#if (QT_VERSION-0 >= 0x030200)\n QPixmap splashPixmap( UserIcon( \"splash\" ) );\n\n QSplashScreen *splash = new QSplashScreen( splashPixmap );\n splash->show();\n#else\n Kontact::Splash *splash = new Kontact::Splash( 0, \"splash\" );\n splash->show();\n#endif\n\n \/\/ see if we are starting with session management\n if ( app.isRestored() ) {\n if (Kontact::MainWindow::canBeRestored(1))\n\t \/\/only restore a single main window! (Don);\n\t (new Kontact::MainWindow)->restore(1);\n } else {\n \/\/ no session.. just start up normally\n Kontact::MainWindow *mw = new Kontact::MainWindow;\n mw->show();\n }\n\n \/\/ delete splash\n delete splash;\n\n bool ret = app.exec();\n while (KMainWindow::memberList->first())\n delete KMainWindow::memberList->first();\n return ret;\n}\n<commit_msg>Bring Kontact window to front when you start a new instance but an old one is still running. That fixes #68340.<commit_after>\/*\n This file is part of KDE Kontact.\n\n Copyright (c) 2001 Matthias Hoelzer-Kluepfel <mhk@kde.org>\n Copyright (c) 2002-2003 Daniel Molkentin <molkentin@kde.org>\n\n This program is free software; you can redistribute it and\/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation; either version 2 of the License, or\n (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with this program; if not, write to the Free Software\n Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.\n*\/\n\n#include <dcopclient.h>\n#include <kaboutdata.h>\n#include <kcmdlineargs.h>\n#include <kdebug.h>\n#include <kiconloader.h>\n#include <klocale.h>\n#include <kstartupinfo.h>\n#include <kuniqueapplication.h>\n#include <kwin.h>\n\n#include <qlabel.h>\n#if (QT_VERSION-0 >= 0x030200)\n#include <qsplashscreen.h>\n#else\n#include \"splash.h\"\n#endif\n\n#include \"mainwindow.h\"\n\nstatic const char description[] =\n I18N_NOOP( \"A KDE Personal Information Manager\" );\n\nstatic const char version[] = \"0.7.3 (Beta 1)\";\n\nclass KontactApp : public KUniqueApplication {\n public:\n KontactApp() : mMainWindow( 0 ) {}\n ~KontactApp() {}\n\n int newInstance();\n\n private:\n Kontact::MainWindow *mMainWindow;\n};\n\nint KontactApp::newInstance()\n{\n \/\/ show splash\n#if (QT_VERSION-0 >= 0x030200)\n QPixmap splashPixmap( UserIcon( \"splash\" ) );\n\n QSplashScreen *splash = new QSplashScreen( splashPixmap );\n splash->show();\n#else\n Kontact::Splash *splash = new Kontact::Splash( 0, \"splash\" );\n splash->show();\n#endif\n\n if ( isRestored() ) {\n \/\/ There can only be one main window\n if ( KMainWindow::canBeRestored( 1 ) ) {\n mMainWindow = new Kontact::MainWindow;\n mMainWindow->show();\n mMainWindow->restore( 1 );\n }\n } else {\n if ( mMainWindow ) {\n mMainWindow->show();\n KWin::forceActiveWindow( mMainWindow->winId() );\n KStartupInfo::appStarted();\n } else {\n mMainWindow = new Kontact::MainWindow;\n mMainWindow->show();\n }\n }\n\n delete splash;\n\n return 0;\n}\n\nint main(int argc, char **argv)\n{\n KAboutData about( \"kontact\", I18N_NOOP( \"Kontact\" ), version, description,\n KAboutData::License_GPL, I18N_NOOP(\"(C) 2001-2003 The Kontact developers\"), 0, \"http:\/\/kontact.kde.org\", \"kde-pim@kde.org\" );\n about.addAuthor( \"Daniel Molkentin\", 0, \"molkentin@kde.org\" );\n about.addAuthor( \"Don Sanders\", 0, \"sanders@kde.org\" );\n about.addAuthor( \"Cornelius Schumacher\", 0, \"schumacher@kde.org\" );\n about.addAuthor( \"Tobias Koenig\", 0, \"tokoe@kde.org\" );\n about.addAuthor( \"Sven Lüppken\", 0, \"sven@kde.org\" );\n about.addAuthor( \"Matthias Hoelzer-Kluepfel\", I18N_NOOP(\"Original Author\"), \"mhk@kde.org\" );\n\n KCmdLineArgs::init( argc, argv, &about );\n\n if ( !KontactApp::start() ) {\n kdError() << \"Kontact is already running!\" << endl;\n return 0;\n }\n\n KontactApp app;\n\n bool ret = app.exec();\n while ( KMainWindow::memberList->first() )\n delete KMainWindow::memberList->first();\n\n return ret;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * opencog\/atomspace\/Link.cc\n *\n * Copyright (C) 2008-2010 OpenCog Foundation\n * Copyright (C) 2002-2007 Novamente LLC\n * All Rights Reserved\n *\n * This program is free software; you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License v3 as\n * published by the Free Software Foundation and including the exceptions\n * at http:\/\/opencog.org\/wiki\/Licenses\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public License\n * along with this program; if not, write to:\n * Free Software Foundation, Inc.,\n * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.\n *\/\n\n#include <stdio.h>\n\n#include <opencog\/atomspace\/AtomTable.h>\n#include <opencog\/atomspace\/ClassServer.h>\n#include <opencog\/atomspace\/Node.h>\n#include <opencog\/util\/exceptions.h>\n#include <opencog\/util\/Logger.h>\n\n#include \"Link.h\"\n\n\/\/#define DPRINTF printf\n#define DPRINTF(...)\n\nusing namespace opencog;\n\nstruct HandleComparison\n{\n bool operator()(const Handle& h1, const Handle& h2) const {\n return (Handle::compare(h1, h2) < 0);\n }\n};\n\nvoid Link::resort(void)\n{\n std::sort(_outgoing.begin(), _outgoing.end(), HandleComparison());\n}\n\nvoid Link::init(const std::vector<Handle>& outgoingVector)\n{\n if (not classserver().isA(_type, LINK)) {\n throw InvalidParamException(TRACE_INFO,\n \"Link ctor: Atom type is not a Link: '%d' %s.\",\n _type, classserver().getTypeName(_type).c_str());\n }\n\n _outgoing = outgoingVector;\n \/\/ If the link is unordered, it will be normalized by sorting the\n \/\/ elements in the outgoing list.\n if (classserver().isA(_type, UNORDERED_LINK)) {\n resort();\n }\n}\n\nLink::~Link()\n{\n DPRINTF(\"Deleting link:\\n%s\\n\", this->toString().c_str());\n}\n\nstd::string Link::toShortString(std::string indent)\n{\n std::stringstream answer;\n std::string more_indent = indent + \" \";\n\n answer << indent << \"(\" << classserver().getTypeName(_type);\n answer << \" \" << getTruthValue()->toString() << \"\\n\";\n\n \/\/ Here the target string is made. If a target is a node, its name is\n \/\/ concatenated. If it's a link, all its properties are concatenated.\n for (const Handle& h : _outgoing) {\n if (h.operator->() != NULL)\n answer << h->toShortString(more_indent);\n else\n answer << indent << \"Undefined Atom!\\n\";\n }\n\n answer << indent << \") ; [\" << _uuid << \"]\";\n\n if (_atomTable)\n answer << \"[\" << _atomTable->get_uuid() << \"]\\n\";\n else\n answer << \"[NULL]\\n\";\n\n return answer.str();\n}\n\nstd::string Link::toString(std::string indent)\n{\n std::string answer;\n std::string more_indent = indent + \" \";\n#define BUFSZ 1024\n static char buf[BUFSZ];\n\n snprintf(buf, BUFSZ, \"(%s (av %d %d %d) %s\\n\",\n classserver().getTypeName(_type).c_str(),\n (int)getAttentionValue()->getSTI(),\n (int)getAttentionValue()->getLTI(),\n (int)getAttentionValue()->getVLTI(),\n getTruthValue()->toString().c_str());\n answer = indent + buf;\n \/\/ Here the targets string is made. If a target is a node, its name is\n \/\/ concatenated. If it's a link, all its properties are concatenated.\n for (const Handle& h : _outgoing) {\n if (h.operator->() != NULL)\n answer += h->toString(more_indent);\n else\n answer += indent + \"Undefined Atom!\\n\";\n }\n\n answer += indent + \") ; [\" + \n std::to_string(_uuid).c_str() + \"][\" +\n std::to_string(_atomTable? _atomTable->get_uuid() : -1) +\n \"]\\n\";\n\n return answer;\n}\n\nbool Link::isSource(Handle handle) const\n{\n \/\/ On ordered links, only the first position in the outgoing set is a source\n \/\/ of this link. So, if the handle given is equal to the first position,\n \/\/ true is returned.\n Arity arity = getArity();\n if (classserver().isA(_type, ORDERED_LINK)) {\n return arity > 0 && _outgoing[0] == handle;\n } else if (classserver().isA(_type, UNORDERED_LINK)) {\n \/\/ If the link is unordered, the outgoing set is scanned, and the\n \/\/ method returns true if any position is equal to the handle given.\n for (Arity i = 0; i < arity; i++) {\n if (_outgoing[i] == handle) {\n return true;\n }\n }\n return false;\n } else {\n throw InvalidParamException(TRACE_INFO, \"Link::isSource(Handle) unknown link type %d\", _type);\n }\n return false;\n}\n\nbool Link::isSource(size_t i) const\n{\n \/\/ tests if the int given is valid.\n if (i > getArity()) {\n throw IndexErrorException(TRACE_INFO, \"Link::isSource(size_t) invalid index argument\");\n }\n\n \/\/ on ordered links, only the first position in the outgoing set is a source\n \/\/ of this link. So, if the int passed is 0, true is returned.\n if (classserver().isA(_type, ORDERED_LINK)) {\n return i == 0;\n } else if (classserver().isA(_type, UNORDERED_LINK)) {\n \/\/ on unordered links, the only thing that matters is if the int passed\n \/\/ is valid (if it is within 0..arity).\n return true;\n } else {\n throw InvalidParamException(TRACE_INFO, \"Link::isSource(int) unknown link type %d\", _type);\n }\n}\n\nbool Link::isTarget(Handle handle) const\n{\n \/\/ On ordered links, the first position of the outgoing set defines the\n \/\/ source of the link. The other positions are targets. So, it scans the\n \/\/ outgoing set from the second position searching for the given handle. If\n \/\/ it is found, true is returned.\n Arity arity = getArity();\n if (classserver().isA(_type, ORDERED_LINK)) {\n for (Arity i = 1; i < arity; i++) {\n if (_outgoing[i] == handle) {\n return true;\n }\n }\n return false;\n } else if (classserver().isA(_type, UNORDERED_LINK)) {\n \/\/ If the links is unordered, all the outgoing set is scanned.\n for (Arity i = 0; i < arity; i++) {\n if (_outgoing[i] == handle) {\n return true;\n }\n }\n return false;\n } else {\n throw InvalidParamException(TRACE_INFO, \"Link::isTarget(Handle) unknown link type %d\", _type);\n }\n return false;\n}\n\nbool Link::isTarget(size_t i) const\n{\n \/\/ tests if the int given is valid.\n if (i > getArity()) {\n throw IndexErrorException(TRACE_INFO, \"Link::istarget(int) invalid index argument\");\n }\n\n \/\/ on ordered links, the first position of the outgoing set defines the\n \/\/ source of the link. The other positions are targets.\n if (classserver().isA(_type, ORDERED_LINK)) {\n return i != 0;\n } else if (classserver().isA(_type, UNORDERED_LINK)) {\n \/\/ on unorderd links, the only thing that matter is if the position is\n \/\/ valid.\n return true;\n } else {\n throw InvalidParamException(TRACE_INFO, \"Link::isTarget(int) unkown link type\");\n }\n return false;\n}\n\nbool Link::operator==(const Atom& other) const\n{\n if (getType() != other.getType()) return false;\n const Link& olink = dynamic_cast<const Link&>(other);\n\n Arity arity = getArity();\n if (arity != olink.getArity()) return false;\n for (Arity i = 0; i < arity; i++)\n if (_outgoing[i] != olink._outgoing[i]) return false;\n return true;\n}\n\nbool Link::operator!=(const Atom& other) const\n{\n return !(*this == other);\n}\n\n<commit_msg>Perform an explicit atom compare<commit_after>\/*\n * opencog\/atomspace\/Link.cc\n *\n * Copyright (C) 2008-2010 OpenCog Foundation\n * Copyright (C) 2002-2007 Novamente LLC\n * All Rights Reserved\n *\n * This program is free software; you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License v3 as\n * published by the Free Software Foundation and including the exceptions\n * at http:\/\/opencog.org\/wiki\/Licenses\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public License\n * along with this program; if not, write to:\n * Free Software Foundation, Inc.,\n * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.\n *\/\n\n#include <stdio.h>\n\n#include <opencog\/atomspace\/AtomTable.h>\n#include <opencog\/atomspace\/ClassServer.h>\n#include <opencog\/atomspace\/Node.h>\n#include <opencog\/util\/exceptions.h>\n#include <opencog\/util\/Logger.h>\n\n#include \"Link.h\"\n\n\/\/#define DPRINTF printf\n#define DPRINTF(...)\n\nusing namespace opencog;\n\nstruct HandleComparison\n{\n bool operator()(const Handle& h1, const Handle& h2) const {\n return (Handle::compare(h1, h2) < 0);\n }\n};\n\nvoid Link::resort(void)\n{\n std::sort(_outgoing.begin(), _outgoing.end(), HandleComparison());\n}\n\nvoid Link::init(const std::vector<Handle>& outgoingVector)\n{\n if (not classserver().isA(_type, LINK)) {\n throw InvalidParamException(TRACE_INFO,\n \"Link ctor: Atom type is not a Link: '%d' %s.\",\n _type, classserver().getTypeName(_type).c_str());\n }\n\n _outgoing = outgoingVector;\n \/\/ If the link is unordered, it will be normalized by sorting the\n \/\/ elements in the outgoing list.\n if (classserver().isA(_type, UNORDERED_LINK)) {\n resort();\n }\n}\n\nLink::~Link()\n{\n DPRINTF(\"Deleting link:\\n%s\\n\", this->toString().c_str());\n}\n\nstd::string Link::toShortString(std::string indent)\n{\n std::stringstream answer;\n std::string more_indent = indent + \" \";\n\n answer << indent << \"(\" << classserver().getTypeName(_type);\n answer << \" \" << getTruthValue()->toString() << \"\\n\";\n\n \/\/ Here the target string is made. If a target is a node, its name is\n \/\/ concatenated. If it's a link, all its properties are concatenated.\n for (const Handle& h : _outgoing) {\n if (h.operator->() != NULL)\n answer << h->toShortString(more_indent);\n else\n answer << indent << \"Undefined Atom!\\n\";\n }\n\n answer << indent << \") ; [\" << _uuid << \"]\";\n\n if (_atomTable)\n answer << \"[\" << _atomTable->get_uuid() << \"]\\n\";\n else\n answer << \"[NULL]\\n\";\n\n return answer.str();\n}\n\nstd::string Link::toString(std::string indent)\n{\n std::string answer;\n std::string more_indent = indent + \" \";\n#define BUFSZ 1024\n static char buf[BUFSZ];\n\n snprintf(buf, BUFSZ, \"(%s (av %d %d %d) %s\\n\",\n classserver().getTypeName(_type).c_str(),\n (int)getAttentionValue()->getSTI(),\n (int)getAttentionValue()->getLTI(),\n (int)getAttentionValue()->getVLTI(),\n getTruthValue()->toString().c_str());\n answer = indent + buf;\n \/\/ Here the targets string is made. If a target is a node, its name is\n \/\/ concatenated. If it's a link, all its properties are concatenated.\n for (const Handle& h : _outgoing) {\n if (h.operator->() != NULL)\n answer += h->toString(more_indent);\n else\n answer += indent + \"Undefined Atom!\\n\";\n }\n\n answer += indent + \") ; [\" + \n std::to_string(_uuid).c_str() + \"][\" +\n std::to_string(_atomTable? _atomTable->get_uuid() : -1) +\n \"]\\n\";\n\n return answer;\n}\n\nbool Link::isSource(Handle handle) const\n{\n \/\/ On ordered links, only the first position in the outgoing set is a source\n \/\/ of this link. So, if the handle given is equal to the first position,\n \/\/ true is returned.\n Arity arity = getArity();\n if (classserver().isA(_type, ORDERED_LINK)) {\n return arity > 0 && _outgoing[0] == handle;\n } else if (classserver().isA(_type, UNORDERED_LINK)) {\n \/\/ If the link is unordered, the outgoing set is scanned, and the\n \/\/ method returns true if any position is equal to the handle given.\n for (Arity i = 0; i < arity; i++) {\n if (_outgoing[i] == handle) {\n return true;\n }\n }\n return false;\n } else {\n throw InvalidParamException(TRACE_INFO, \"Link::isSource(Handle) unknown link type %d\", _type);\n }\n return false;\n}\n\nbool Link::isSource(size_t i) const\n{\n \/\/ tests if the int given is valid.\n if (i > getArity()) {\n throw IndexErrorException(TRACE_INFO, \"Link::isSource(size_t) invalid index argument\");\n }\n\n \/\/ on ordered links, only the first position in the outgoing set is a source\n \/\/ of this link. So, if the int passed is 0, true is returned.\n if (classserver().isA(_type, ORDERED_LINK)) {\n return i == 0;\n } else if (classserver().isA(_type, UNORDERED_LINK)) {\n \/\/ on unordered links, the only thing that matters is if the int passed\n \/\/ is valid (if it is within 0..arity).\n return true;\n } else {\n throw InvalidParamException(TRACE_INFO, \"Link::isSource(int) unknown link type %d\", _type);\n }\n}\n\nbool Link::isTarget(Handle handle) const\n{\n \/\/ On ordered links, the first position of the outgoing set defines the\n \/\/ source of the link. The other positions are targets. So, it scans the\n \/\/ outgoing set from the second position searching for the given handle. If\n \/\/ it is found, true is returned.\n Arity arity = getArity();\n if (classserver().isA(_type, ORDERED_LINK)) {\n for (Arity i = 1; i < arity; i++) {\n if (_outgoing[i] == handle) {\n return true;\n }\n }\n return false;\n } else if (classserver().isA(_type, UNORDERED_LINK)) {\n \/\/ If the links is unordered, all the outgoing set is scanned.\n for (Arity i = 0; i < arity; i++) {\n if (_outgoing[i] == handle) {\n return true;\n }\n }\n return false;\n } else {\n throw InvalidParamException(TRACE_INFO, \"Link::isTarget(Handle) unknown link type %d\", _type);\n }\n return false;\n}\n\nbool Link::isTarget(size_t i) const\n{\n \/\/ tests if the int given is valid.\n if (i > getArity()) {\n throw IndexErrorException(TRACE_INFO, \"Link::istarget(int) invalid index argument\");\n }\n\n \/\/ on ordered links, the first position of the outgoing set defines the\n \/\/ source of the link. The other positions are targets.\n if (classserver().isA(_type, ORDERED_LINK)) {\n return i != 0;\n } else if (classserver().isA(_type, UNORDERED_LINK)) {\n \/\/ on unorderd links, the only thing that matter is if the position is\n \/\/ valid.\n return true;\n } else {\n throw InvalidParamException(TRACE_INFO, \"Link::isTarget(int) unkown link type\");\n }\n return false;\n}\n\nbool Link::operator==(const Atom& other) const\n{\n if (getType() != other.getType()) return false;\n const Link& olink = dynamic_cast<const Link&>(other);\n\n Arity arity = getArity();\n if (arity != olink.getArity()) return false;\n for (Arity i = 0; i < arity; i++)\n {\n NodePtr tn(NodeCast(_outgoing[i]));\n NodePtr on(NodeCast(olink._outgoing[i]));\n if (tn and on and *tn != *on) return false;\n\n LinkPtr tl(LinkCast(_outgoing[i]));\n LinkPtr ol(LinkCast(olink._outgoing[i]));\n if (tl and ol and *tl != *ol) return false;\n }\n return true;\n}\n\nbool Link::operator!=(const Atom& other) const\n{\n return !(*this == other);\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/\/------------------------------------------------------------------------------\n\/\/ CLING - the C++ LLVM-based InterpreterG :)\n\/\/\n\/\/ This file is dual-licensed: you can choose to license it under the University\n\/\/ of Illinois Open Source License or the GNU Lesser General Public License. See\n\/\/ LICENSE.TXT for details.\n\/\/------------------------------------------------------------------------------\n\n\/\/ RUN: test \"x`uname -m|sed 's,i.86,i386,'`\" = \"xi386\" || cat %s | %cling -Xclang -verify | FileCheck %s\n\/\/ Not running on 32 bit due to aggregate return in getWithDtor(); see ROOT-5860\n\n#include \"cling\/Interpreter\/Interpreter.h\"\n#include \"cling\/Interpreter\/StoredValueRef.h\"\n\ncling::StoredValueRef V;\nV \/\/ CHECK: (cling::StoredValueRef) <<<invalid>>> @0x{{.*}}\n\ngCling->evaluate(\"return 1;\", V);\nV \/\/ CHECK: (cling::StoredValueRef) boxes [(int) 1]\n\n\/\/ Returns must put the result in the StoredValueRef.\nbool cond = true;\ngCling->evaluate(\"if (cond) return \\\"true\\\"; else return 0;\", V);\nV \/\/ CHECK: (cling::StoredValueRef) boxes [(const char [5]) \"true\"]\ngCling->evaluate(\"cond = false; if (cond) return \\\"true\\\"; else return 0;\", V);\nV \/\/ CHECK: (cling::StoredValueRef) boxes [(int) 0]\n\nlong LongV = 17;\ngCling->evaluate(\"LongV;\", V);\nV \/\/ CHECK: (cling::StoredValueRef) boxes [(long) 17]\n\nint* IntP = (int*)0x12;\ngCling->evaluate(\"IntP;\", V);\nV \/\/ CHECK: (cling::StoredValueRef) boxes [(int *) 0x12]\n\ncling::StoredValueRef Result;\ngCling->evaluate(\"V\", Result);\n\/\/ Here we check what happens for record type like cling::StoredValueRef; they are returned by reference.\nResult \/\/ CHECK: (cling::StoredValueRef) boxes [(cling::StoredValueRef &) &0x{{.*}}]\nV \/\/ CHECK: (cling::StoredValueRef) boxes [(int *) 0x12]\n\n\/\/ Savannah #96277\ngCling->evaluate(\"gCling->declare(\\\"double sin(double);\\\"); double one = sin(3.141\/2);\", V);\nV \/\/ CHECK: (cling::StoredValueRef) boxes [(double) 1.000000e+00]\n\ngCling->process(\"double one = sin(3.141\/2);\", &V);\nV \/\/ CHECK: (cling::StoredValueRef) boxes [(double) 1.000000e+00]\none \/\/ CHECK: (double) 1.000\nint one; \/\/ expected-error {{redefinition of 'one' with a different type: 'int' vs 'double'}} expected-note {{previous definition is here}}\n\n\/\/ Make sure that PR#98434 doesn't get reintroduced.\n.rawInput\nvoid f(int) { return; }\n.rawInput\n\ngCling->evaluate(\"f\", V);\nV.isValid() \/\/CHECK: {{\\([_]B|b}}ool) true\n\/\/ end PR#98434\n\n\/\/ Check lifetime of objects in StoredValue\n.rawInput 1\nstruct WithDtor {\n static int fgCount;\n WithDtor() { ++fgCount; }\n WithDtor(const WithDtor&) { ++fgCount; }\n ~WithDtor() { --fgCount; }\n};\nint WithDtor::fgCount = 0;\nWithDtor getWithDtor() { return WithDtor(); }\n#include <vector>\nstd::vector<WithDtor> getWithDtorVec() { std::vector<WithDtor> ret; ret.resize(7); return ret; }\n.rawInput 0\n\ncling::StoredValueRef* VOnHeap = new cling::StoredValueRef();\ngCling->evaluate(\"getWithDtor()\", *VOnHeap);\n*VOnHeap \/\/CHECK: (cling::StoredValueRef) boxes [(WithDtor) @0x{{.*}}]\nWithDtor::fgCount \/\/CHECK: (int) 1\ndelete VOnHeap;\nWithDtor::fgCount \/\/CHECK: (int) 0\n\n\/\/ Check destructor call for templates\nVOnHeap = new cling::StoredValueRef();\ngCling->evaluate(\"getWithDtorVec()\", *VOnHeap);\n*VOnHeap \/\/CHECK: (cling::StoredValueRef) boxes [(std::vector<WithDtor>) @0x{{.*}}]\nWithDtor::fgCount \/\/CHECK: (int) 7\ndelete VOnHeap;\nWithDtor::fgCount \/\/CHECK: (int) 0\n<commit_msg>We have more accurate results so adjust the test.<commit_after>\/\/------------------------------------------------------------------------------\n\/\/ CLING - the C++ LLVM-based InterpreterG :)\n\/\/\n\/\/ This file is dual-licensed: you can choose to license it under the University\n\/\/ of Illinois Open Source License or the GNU Lesser General Public License. See\n\/\/ LICENSE.TXT for details.\n\/\/------------------------------------------------------------------------------\n\n\/\/ RUN: test \"x`uname -m|sed 's,i.86,i386,'`\" = \"xi386\" || cat %s | %cling -Xclang -verify | FileCheck %s\n\/\/ Not running on 32 bit due to aggregate return in getWithDtor(); see ROOT-5860\n\n#include \"cling\/Interpreter\/Interpreter.h\"\n#include \"cling\/Interpreter\/StoredValueRef.h\"\n\ncling::StoredValueRef V;\nV \/\/ CHECK: (cling::StoredValueRef) <<<invalid>>> @0x{{.*}}\n\ngCling->evaluate(\"return 1;\", V);\nV \/\/ CHECK: (cling::StoredValueRef) boxes [(int) 1]\n\n\/\/ Returns must put the result in the StoredValueRef.\nbool cond = true;\ngCling->evaluate(\"if (cond) return \\\"true\\\"; else return 0;\", V);\nV \/\/ CHECK: (cling::StoredValueRef) boxes [(const char [5]) \"true\"]\ngCling->evaluate(\"cond = false; if (cond) return \\\"true\\\"; else return 0;\", V);\nV \/\/ CHECK: (cling::StoredValueRef) boxes [(int) 0]\n\nlong LongV = 17;\ngCling->evaluate(\"LongV;\", V);\nV \/\/ CHECK: (cling::StoredValueRef) boxes [(long) 17]\n\nint* IntP = (int*)0x12;\ngCling->evaluate(\"IntP;\", V);\nV \/\/ CHECK: (cling::StoredValueRef) boxes [(int *) 0x12]\n\ncling::StoredValueRef Result;\ngCling->evaluate(\"V\", Result);\n\/\/ Here we check what happens for record type like cling::StoredValueRef; they are returned by reference.\nResult \/\/ CHECK: (cling::StoredValueRef) boxes [(cling::StoredValueRef) boxes [(int *) 0x12]]\nV \/\/ CHECK: (cling::StoredValueRef) boxes [(int *) 0x12]\n\n\/\/ Savannah #96277\ngCling->evaluate(\"gCling->declare(\\\"double sin(double);\\\"); double one = sin(3.141\/2);\", V);\nV \/\/ CHECK: (cling::StoredValueRef) boxes [(double) 1.000000e+00]\n\ngCling->process(\"double one = sin(3.141\/2);\", &V);\nV \/\/ CHECK: (cling::StoredValueRef) boxes [(double) 1.000000e+00]\none \/\/ CHECK: (double) 1.000\nint one; \/\/ expected-error {{redefinition of 'one' with a different type: 'int' vs 'double'}} expected-note {{previous definition is here}}\n\n\/\/ Make sure that PR#98434 doesn't get reintroduced.\n.rawInput\nvoid f(int) { return; }\n.rawInput\n\ngCling->evaluate(\"f\", V);\nV.isValid() \/\/CHECK: {{\\([_]B|b}}ool) true\n\/\/ end PR#98434\n\n\/\/ Check lifetime of objects in StoredValue\n.rawInput 1\nstruct WithDtor {\n static int fgCount;\n WithDtor() { ++fgCount; }\n WithDtor(const WithDtor&) { ++fgCount; }\n ~WithDtor() { --fgCount; }\n};\nint WithDtor::fgCount = 0;\nWithDtor getWithDtor() { return WithDtor(); }\n#include <vector>\nstd::vector<WithDtor> getWithDtorVec() { std::vector<WithDtor> ret; ret.resize(7); return ret; }\n.rawInput 0\n\ncling::StoredValueRef* VOnHeap = new cling::StoredValueRef();\ngCling->evaluate(\"getWithDtor()\", *VOnHeap);\n*VOnHeap \/\/CHECK: (cling::StoredValueRef) boxes [(WithDtor) @0x{{.*}}]\nWithDtor::fgCount \/\/CHECK: (int) 1\ndelete VOnHeap;\nWithDtor::fgCount \/\/CHECK: (int) 0\n\n\/\/ Check destructor call for templates\nVOnHeap = new cling::StoredValueRef();\ngCling->evaluate(\"getWithDtorVec()\", *VOnHeap);\n*VOnHeap \/\/CHECK: (cling::StoredValueRef) boxes [(std::vector<WithDtor>) @0x{{.*}}]\nWithDtor::fgCount \/\/CHECK: (int) 7\ndelete VOnHeap;\nWithDtor::fgCount \/\/CHECK: (int) 0\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (C) 2010-2011 Dmitry Marakasov\n *\n * This file is part of glosm.\n *\n * glosm is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * glosm is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with glosm. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n\n#include <glosm\/GeometryOperations.hh>\n#include <glosm\/geomath.h>\n#include <math.h>\n\nbool IntersectSegmentWithHorizontal(const Vector3i& one, const Vector3i& two, osmint_t y, Vector3i& out) {\n\tif (one.y < y && two.y < y)\n\t\treturn false;\n\n\tif (one.y > y && two.y > y)\n\t\treturn false;\n\n\tfloat t = (float)(one.y - y) \/ (float)(one.y - two.y);\n\n\tfloat x = (float)(two.x - one.x) * t;\n\tfloat z = (float)(two.z - one.z) * t;\n\n\tout = Vector3i(one.x + round(x), y, one.z + round(z));\n\treturn true;\n}\n\nbool IntersectSegmentWithVertical(const Vector3i& one, const Vector3i& two, osmint_t x, Vector3i& out) {\n\tif (one.x < x && two.x < x)\n\t\treturn false;\n\n\tif (one.x > x && two.x > x)\n\t\treturn false;\n\n\tfloat t = (float)(one.x - x) \/ (float)(one.x - two.x);\n\n\tfloat y = (float)(two.y - one.y) * t;\n\tfloat z = (float)(two.z - one.z) * t;\n\n\tout = Vector3i(x, one.y + round(y), one.z + round(z));\n\treturn true;\n}\n\nbool IntersectPlaneWithVertical(const Vector3i& a, const Vector3i& b, const Vector3i& c, const Vector2i& xy, Vector3i& out) {\n\t\/* Equation of a plane:\n\t * | x-x1 y-y1 z-z1 |\n\t * | x2-x1 y2-y1 z2-y1 | = 0\n\t * | x3-x1 y3-y1 z3-y1 |\n\t *\n\t * Determinant:\n\t * | a11 a12 a13 |\n\t * | a21 a22 a23 | = a11a22a33 − a11a23a32 − a12a21a33 + a12a23a31 + a13a21a32 − a13a22a31\n\t * | a31 a32 a33 |\n\t *\n\t * In terms of array:\n\t * | 0 1 2 |\n\t * | 3 4 5 | = 0*4*8 - 0*5*7 - 1*3*8 + 1*5*6 + 2*3*7 - 2*4*6\n\t * | 6 7 8 |\n\t *\/\n\tfloat m[9] = {\n\t\t(float)(xy.x - a.x), (float)(xy.y - a.y), 0.0 \/* to find *\/,\n\t\t(float)(b.x - a.x), (float)(b.y - a.y), (float)(b.z - a.z),\n\t\t(float)(c.x - a.x), (float)(c.y - a.y), (float)(c.z - a.z)\n\t};\n\n\tfloat divisor = m[3]*m[7] - m[4]*m[6];\n\n\tif (fabsf(divisor) < std::numeric_limits<float>::epsilon())\n\t\treturn false;\n\n\tfloat divided = -m[0]*m[4]*m[8] + m[0]*m[5]*m[7] + m[1]*m[3]*m[8] - m[1]*m[5]*m[6];\n\n\tout = Vector3i(xy.x, xy.y, (osmint_t)round(divided\/divisor) + a.z);\n\treturn true;\n}\n\nbool IntersectSegmentWithBBoxSide(const Vector3i& one, const Vector3i& two, const BBoxi& bbox, BBoxi::Side side, Vector3i& out) {\n\tswitch (side) {\n\tcase BBoxi::LEFT:\n\t\treturn IntersectSegmentWithVertical(one, two, bbox.left, out);\n\tcase BBoxi::BOTTOM:\n\t\treturn IntersectSegmentWithHorizontal(one, two, bbox.bottom, out);\n\tcase BBoxi::RIGHT:\n\t\treturn IntersectSegmentWithVertical(one, two, bbox.right, out);\n\tcase BBoxi::TOP:\n\t\treturn IntersectSegmentWithHorizontal(one, two, bbox.top, out);\n\tdefault:\n\t\treturn false;\n\t}\n}\n\n\nBBoxi::Side IntersectSegmentWithBBox(const Vector3i& one, const Vector3i& two, const BBoxi& bbox, Vector3i& out) {\n\tif (IntersectSegmentWithVertical(one, two, bbox.left, out) && bbox.Contains(out))\n\t\treturn BBoxi::LEFT;\n\n\tif (IntersectSegmentWithHorizontal(one, two, bbox.bottom, out) && bbox.Contains(out))\n\t\treturn BBoxi::BOTTOM;\n\n\tif (IntersectSegmentWithVertical(one, two, bbox.right, out) && bbox.Contains(out))\n\t\treturn BBoxi::RIGHT;\n\n\tif (IntersectSegmentWithHorizontal(one, two, bbox.top, out) && bbox.Contains(out))\n\t\treturn BBoxi::TOP;\n\n\treturn BBoxi::NONE;\n}\n\nBBoxi::Side IntersectSegmentWithBBox2(const Vector3i& one, const Vector3i& two, const BBoxi& bbox, Vector3i& out) {\n\tif (IntersectSegmentWithHorizontal(one, two, bbox.top, out) && bbox.Contains(out))\n\t\treturn BBoxi::TOP;\n\n\tif (IntersectSegmentWithVertical(one, two, bbox.right, out) && bbox.Contains(out))\n\t\treturn BBoxi::RIGHT;\n\n\tif (IntersectSegmentWithHorizontal(one, two, bbox.bottom, out) && bbox.Contains(out))\n\t\treturn BBoxi::BOTTOM;\n\n\tif (IntersectSegmentWithVertical(one, two, bbox.left, out) && bbox.Contains(out))\n\t\treturn BBoxi::LEFT;\n\n\treturn BBoxi::NONE;\n}\n\nbool CropSegmentByBBox(const Vector3i& one, const Vector3i& two, const BBoxi& bbox, Vector3i& outone, Vector3i& outtwo) {\n\tif (bbox.Contains(one)) {\n\t\t\/* one is in the bbox *\/\n\t\toutone = one;\n\t\tif (bbox.Contains(two)) {\n\t\t\t\/* both points are in the bbox *\/\n\t\t\touttwo = two;\n\t\t} else {\n\t\t\t\/* other point is outside - find intersection *\/\n\t\t\treturn IntersectSegmentWithBBox(one, two, bbox, outtwo);\n\t\t}\n\t} else if (bbox.Contains(two)) {\n\t\t\/* two is inside, one is outside *\/\n\t\touttwo = two;\n\t\treturn IntersectSegmentWithBBox(one, two, bbox, outone);\n\t}\n\n\t\/* both points are outside, find two points of intersection *\/\n\treturn IntersectSegmentWithBBox(one, two, bbox, outone) && IntersectSegmentWithBBox2(one, two, bbox, outtwo);\n}\n\nVector3d ToLocalMetric(Vector3i what, Vector3i ref) {\n\tdouble lat = ref.y\/1800000000.0*M_PI;\n\n\tdouble dx = (double)(what.x - ref.x)\/3600000000.0*WGS84_EARTH_EQ_LENGTH*cos(lat);\n\tdouble dy = (double)(what.y - ref.y)\/3600000000.0*WGS84_EARTH_EQ_LENGTH;\n\tdouble dz = (double)(what.z - ref.z)\/1000.0;\n\n\treturn Vector3f(dx, dy, dz);\n}\n\nVector3i FromLocalMetric(Vector3d what, Vector3i ref) {\n\tdouble lat = ref.y\/1800000000.0*M_PI;\n\n\tint x = ref.x + round(what.x*3600000000.0\/WGS84_EARTH_EQ_LENGTH\/cos(lat));\n\tint y = ref.y + round(what.y*3600000000.0\/WGS84_EARTH_EQ_LENGTH);\n\tint z = ref.z + round(what.z*1000.0);\n\n\treturn Vector3i(x, y, z);\n}\n\n<commit_msg>Fix edge case bug in FromLocalMetric()<commit_after>\/*\n * Copyright (C) 2010-2011 Dmitry Marakasov\n *\n * This file is part of glosm.\n *\n * glosm is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * glosm is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with glosm. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n\n#include <glosm\/GeometryOperations.hh>\n#include <glosm\/geomath.h>\n#include <math.h>\n\nbool IntersectSegmentWithHorizontal(const Vector3i& one, const Vector3i& two, osmint_t y, Vector3i& out) {\n\tif (one.y < y && two.y < y)\n\t\treturn false;\n\n\tif (one.y > y && two.y > y)\n\t\treturn false;\n\n\tfloat t = (float)(one.y - y) \/ (float)(one.y - two.y);\n\n\tfloat x = (float)(two.x - one.x) * t;\n\tfloat z = (float)(two.z - one.z) * t;\n\n\tout = Vector3i(one.x + round(x), y, one.z + round(z));\n\treturn true;\n}\n\nbool IntersectSegmentWithVertical(const Vector3i& one, const Vector3i& two, osmint_t x, Vector3i& out) {\n\tif (one.x < x && two.x < x)\n\t\treturn false;\n\n\tif (one.x > x && two.x > x)\n\t\treturn false;\n\n\tfloat t = (float)(one.x - x) \/ (float)(one.x - two.x);\n\n\tfloat y = (float)(two.y - one.y) * t;\n\tfloat z = (float)(two.z - one.z) * t;\n\n\tout = Vector3i(x, one.y + round(y), one.z + round(z));\n\treturn true;\n}\n\nbool IntersectPlaneWithVertical(const Vector3i& a, const Vector3i& b, const Vector3i& c, const Vector2i& xy, Vector3i& out) {\n\t\/* Equation of a plane:\n\t * | x-x1 y-y1 z-z1 |\n\t * | x2-x1 y2-y1 z2-y1 | = 0\n\t * | x3-x1 y3-y1 z3-y1 |\n\t *\n\t * Determinant:\n\t * | a11 a12 a13 |\n\t * | a21 a22 a23 | = a11a22a33 − a11a23a32 − a12a21a33 + a12a23a31 + a13a21a32 − a13a22a31\n\t * | a31 a32 a33 |\n\t *\n\t * In terms of array:\n\t * | 0 1 2 |\n\t * | 3 4 5 | = 0*4*8 - 0*5*7 - 1*3*8 + 1*5*6 + 2*3*7 - 2*4*6\n\t * | 6 7 8 |\n\t *\/\n\tfloat m[9] = {\n\t\t(float)(xy.x - a.x), (float)(xy.y - a.y), 0.0 \/* to find *\/,\n\t\t(float)(b.x - a.x), (float)(b.y - a.y), (float)(b.z - a.z),\n\t\t(float)(c.x - a.x), (float)(c.y - a.y), (float)(c.z - a.z)\n\t};\n\n\tfloat divisor = m[3]*m[7] - m[4]*m[6];\n\n\tif (fabsf(divisor) < std::numeric_limits<float>::epsilon())\n\t\treturn false;\n\n\tfloat divided = -m[0]*m[4]*m[8] + m[0]*m[5]*m[7] + m[1]*m[3]*m[8] - m[1]*m[5]*m[6];\n\n\tout = Vector3i(xy.x, xy.y, (osmint_t)round(divided\/divisor) + a.z);\n\treturn true;\n}\n\nbool IntersectSegmentWithBBoxSide(const Vector3i& one, const Vector3i& two, const BBoxi& bbox, BBoxi::Side side, Vector3i& out) {\n\tswitch (side) {\n\tcase BBoxi::LEFT:\n\t\treturn IntersectSegmentWithVertical(one, two, bbox.left, out);\n\tcase BBoxi::BOTTOM:\n\t\treturn IntersectSegmentWithHorizontal(one, two, bbox.bottom, out);\n\tcase BBoxi::RIGHT:\n\t\treturn IntersectSegmentWithVertical(one, two, bbox.right, out);\n\tcase BBoxi::TOP:\n\t\treturn IntersectSegmentWithHorizontal(one, two, bbox.top, out);\n\tdefault:\n\t\treturn false;\n\t}\n}\n\n\nBBoxi::Side IntersectSegmentWithBBox(const Vector3i& one, const Vector3i& two, const BBoxi& bbox, Vector3i& out) {\n\tif (IntersectSegmentWithVertical(one, two, bbox.left, out) && bbox.Contains(out))\n\t\treturn BBoxi::LEFT;\n\n\tif (IntersectSegmentWithHorizontal(one, two, bbox.bottom, out) && bbox.Contains(out))\n\t\treturn BBoxi::BOTTOM;\n\n\tif (IntersectSegmentWithVertical(one, two, bbox.right, out) && bbox.Contains(out))\n\t\treturn BBoxi::RIGHT;\n\n\tif (IntersectSegmentWithHorizontal(one, two, bbox.top, out) && bbox.Contains(out))\n\t\treturn BBoxi::TOP;\n\n\treturn BBoxi::NONE;\n}\n\nBBoxi::Side IntersectSegmentWithBBox2(const Vector3i& one, const Vector3i& two, const BBoxi& bbox, Vector3i& out) {\n\tif (IntersectSegmentWithHorizontal(one, two, bbox.top, out) && bbox.Contains(out))\n\t\treturn BBoxi::TOP;\n\n\tif (IntersectSegmentWithVertical(one, two, bbox.right, out) && bbox.Contains(out))\n\t\treturn BBoxi::RIGHT;\n\n\tif (IntersectSegmentWithHorizontal(one, two, bbox.bottom, out) && bbox.Contains(out))\n\t\treturn BBoxi::BOTTOM;\n\n\tif (IntersectSegmentWithVertical(one, two, bbox.left, out) && bbox.Contains(out))\n\t\treturn BBoxi::LEFT;\n\n\treturn BBoxi::NONE;\n}\n\nbool CropSegmentByBBox(const Vector3i& one, const Vector3i& two, const BBoxi& bbox, Vector3i& outone, Vector3i& outtwo) {\n\tif (bbox.Contains(one)) {\n\t\t\/* one is in the bbox *\/\n\t\toutone = one;\n\t\tif (bbox.Contains(two)) {\n\t\t\t\/* both points are in the bbox *\/\n\t\t\touttwo = two;\n\t\t} else {\n\t\t\t\/* other point is outside - find intersection *\/\n\t\t\treturn IntersectSegmentWithBBox(one, two, bbox, outtwo);\n\t\t}\n\t} else if (bbox.Contains(two)) {\n\t\t\/* two is inside, one is outside *\/\n\t\touttwo = two;\n\t\treturn IntersectSegmentWithBBox(one, two, bbox, outone);\n\t}\n\n\t\/* both points are outside, find two points of intersection *\/\n\treturn IntersectSegmentWithBBox(one, two, bbox, outone) && IntersectSegmentWithBBox2(one, two, bbox, outtwo);\n}\n\nVector3d ToLocalMetric(Vector3i what, Vector3i ref) {\n\tconst double coslat = cos(ref.y\/1800000000.0*M_PI);\n\n\tdouble dx = (double)(what.x - ref.x)\/3600000000.0*WGS84_EARTH_EQ_LENGTH*coslat;\n\tdouble dy = (double)(what.y - ref.y)\/3600000000.0*WGS84_EARTH_EQ_LENGTH;\n\tdouble dz = (double)(what.z - ref.z)\/1000.0;\n\n\treturn Vector3f(dx, dy, dz);\n}\n\nVector3i FromLocalMetric(Vector3d what, Vector3i ref) {\n\tconst double coslat = cos(ref.y\/1800000000.0*M_PI);\n\n\tint x = ref.x;\n\tif (coslat > std::numeric_limits<double>::epsilon())\n\t\tx += round(what.x*3600000000.0\/WGS84_EARTH_EQ_LENGTH\/coslat);\n\n\tint y = ref.y + round(what.y*3600000000.0\/WGS84_EARTH_EQ_LENGTH);\n\tint z = ref.z + round(what.z*1000.0);\n\n\treturn Vector3i(x, y, z);\n}\n\n<|endoftext|>"} {"text":"<commit_before>#include \"task_synthetic_shapes.h\"\n#include \"libnanocv\/loss.h\"\n#include \"libnanocv\/util\/math.hpp\"\n#include \"libnanocv\/util\/random.hpp\"\n\nnamespace ncv\n{\n synthetic_shapes_task_t::synthetic_shapes_task_t(const string_t& configuration)\n : task_t(configuration),\n m_rows(math::clamp(text::from_params<size_t>(configuration, \"rows\", 32), 16, 32)),\n m_cols(math::clamp(text::from_params<size_t>(configuration, \"cols\", 32), 16, 32)),\n m_outputs(math::clamp(text::from_params<size_t>(configuration, \"dims\", 4), 2, 16)),\n m_folds(1),\n m_color(text::from_params<color_mode>(configuration, \"color\", color_mode::rgba)),\n m_size(math::clamp(text::from_params<size_t>(configuration, \"size\", 1024), 256, 16 * 1024))\n {\n }\n\n namespace\n {\n rgba_t make_transparent_color()\n {\n return 0;\n }\n\n rgba_t make_light_color()\n {\n random_t<rgba_t> rng_red(175, 255);\n random_t<rgba_t> rng_green(175, 255);\n random_t<rgba_t> rng_blue(175, 255);\n\n return color::make_rgba(rng_red(), rng_green(), rng_blue());\n }\n\n rect_t make_rect(coord_t rows, coord_t cols)\n {\n random_t<coord_t> rng(2, std::min(rows \/ 4, cols \/ 4));\n\n const coord_t dx = rng();\n const coord_t dy = rng();\n const coord_t dw = rng();\n const coord_t dh = rng();\n\n return rect_t(dx, dy, cols - dx - dw, rows - dy - dh);\n }\n\n rect_t make_interior_rect(coord_t x, coord_t y, coord_t w, coord_t h)\n {\n random_t<coord_t> rng(2, std::min(w \/ 4, h \/ 4));\n\n const coord_t dx = rng();\n const coord_t dy = rng();\n const coord_t dw = rng();\n const coord_t dh = rng();\n\n return rect_t(x + dx, y + dy, w - dx - dw, h - dy - dh);\n }\n\n rect_t make_interior_rect(const rect_t& rect)\n {\n return make_interior_rect(rect.left(), rect.top(), rect.width(), rect.height());\n }\n\n image_t make_filled_rect(coord_t rows, coord_t cols)\n {\n const rect_t rect = make_rect(rows, cols);\n\n image_t image(rows, cols, color_mode::rgba);\n\n image.fill(make_transparent_color());\n image.fill(rect, make_light_color());\n\n return image;\n }\n\n image_t make_hollow_rect(coord_t rows, coord_t cols)\n {\n const rect_t rect = make_rect(rows, cols);\n\n image_t image(rows, cols, color_mode::rgba);\n\n image.fill(make_transparent_color());\n image.fill(rect, make_light_color());\n image.fill(make_interior_rect(rect), make_transparent_color());\n\n return image;\n }\n\n void fill_circle(image_t& image, const rect_t& rect)\n {\n const point_t center = rect.center();\n const coord_t cx = center.x();\n const coord_t cy = center.y();\n\n const coord_t radius = (std::min(rect.width(), rect.height()) + 1) \/ 2;\n\n const rgba_t rgba = make_light_color();\n\n for (coord_t x = rect.left(); x < rect.right(); x ++)\n {\n for (coord_t y = rect.top(); y < rect.bottom(); y ++)\n {\n if (math::square(x - cx) + math::square(y - cy) < radius * radius)\n {\n image.set(y, x, rgba);\n }\n }\n }\n }\n\n image_t make_filled_circle(coord_t rows, coord_t cols)\n {\n const rect_t rect = make_rect(rows, cols);\n\n image_t image(rows, cols, color_mode::rgba);\n\n image.fill(make_transparent_color());\n fill_circle(image, rect);\n\n return image;\n }\n }\n\n bool synthetic_shapes_task_t::load(const string_t &)\n {\n random_t<size_t> rng_protocol(1, 10);\n random_t<size_t> rng_output(1, osize());\n\n random_t<scalar_t> rng_gauss(scalar_t(1), math::cast<scalar_t>(icols() + irows()) \/ scalar_t(8));\n\n const coord_t rows = static_cast<coord_t>(irows());\n const coord_t cols = static_cast<coord_t>(icols());\n\n clear_memory(0);\n\n for (size_t f = 0; f < fsize(); f ++)\n {\n for (size_t i = 0; i < m_size; i ++)\n {\n \/\/ random protocol: train vs. test\n const protocol p = (rng_protocol() < 9) ? protocol::train : protocol::test;\n\n \/\/ random output class: #dots\n const size_t o = rng_output();\n\n \/\/ generate random image background\n image_t image(irows(), icols(), color());\n image.fill(make_light_color());\n image.random_noise(color_channel::rgba, -155.0, 55.0, rng_gauss());\n\n \/\/ generate random shapes\n image_t shape;\n\n switch (o)\n {\n case 1: shape = make_filled_rect(rows, cols); break;\n case 2: shape = make_hollow_rect(rows, cols); break;\n case 3: shape = make_filled_circle(rows, cols); break;\n default: break;\n }\n\n image.alpha_blend(shape.rgba());\n\n add_image(image);\n\n \/\/ generate sample\n sample_t sample(n_images() - 1, sample_region(0, 0));\n switch (o)\n {\n case 1: sample.m_label = \"filled_rectangle\"; break;\n case 2: sample.m_label = \"hollow_rectangle\"; break;\n case 3: sample.m_label = \"filled_circle\"; break;\n default: sample.m_label = \"unkown\"; break;\n }\n\n sample.m_target = ncv::class_target(o - 1, osize());\n sample.m_fold = {f, p};\n add_sample(sample);\n }\n }\n\n return true;\n }\n}\n<commit_msg>draw hallow circles<commit_after>#include \"task_synthetic_shapes.h\"\n#include \"libnanocv\/loss.h\"\n#include \"libnanocv\/util\/math.hpp\"\n#include \"libnanocv\/util\/random.hpp\"\n\nnamespace ncv\n{\n synthetic_shapes_task_t::synthetic_shapes_task_t(const string_t& configuration)\n : task_t(configuration),\n m_rows(math::clamp(text::from_params<size_t>(configuration, \"rows\", 32), 16, 32)),\n m_cols(math::clamp(text::from_params<size_t>(configuration, \"cols\", 32), 16, 32)),\n m_outputs(math::clamp(text::from_params<size_t>(configuration, \"dims\", 4), 2, 16)),\n m_folds(1),\n m_color(text::from_params<color_mode>(configuration, \"color\", color_mode::rgba)),\n m_size(math::clamp(text::from_params<size_t>(configuration, \"size\", 1024), 256, 16 * 1024))\n {\n }\n\n namespace\n {\n rgba_t make_transparent_color()\n {\n return 0;\n }\n\n rgba_t make_light_color()\n {\n random_t<rgba_t> rng_red(175, 255);\n random_t<rgba_t> rng_green(175, 255);\n random_t<rgba_t> rng_blue(175, 255);\n\n return color::make_rgba(rng_red(), rng_green(), rng_blue());\n }\n\n rect_t make_rect(coord_t rows, coord_t cols)\n {\n random_t<coord_t> rng(2, std::min(rows \/ 4, cols \/ 4));\n\n const coord_t dx = rng();\n const coord_t dy = rng();\n const coord_t dw = rng();\n const coord_t dh = rng();\n\n return rect_t(dx, dy, cols - dx - dw, rows - dy - dh);\n }\n\n rect_t make_interior_rect(coord_t x, coord_t y, coord_t w, coord_t h)\n {\n random_t<coord_t> rng(2, std::min(w \/ 4, h \/ 4));\n\n const coord_t dx = rng();\n const coord_t dy = rng();\n const coord_t dw = rng();\n const coord_t dh = rng();\n\n return rect_t(x + dx, y + dy, w - dx - dw, h - dy - dh);\n }\n\n rect_t make_interior_rect(const rect_t& rect)\n {\n return make_interior_rect(rect.left(), rect.top(), rect.width(), rect.height());\n }\n\n image_t make_filled_rect(coord_t rows, coord_t cols)\n {\n const rect_t rect = make_rect(rows, cols);\n\n image_t image(rows, cols, color_mode::rgba);\n\n image.fill(make_transparent_color());\n image.fill(rect, make_light_color());\n\n return image;\n }\n\n image_t make_hollow_rect(coord_t rows, coord_t cols)\n {\n const rect_t rect = make_rect(rows, cols);\n\n image_t image(rows, cols, color_mode::rgba);\n\n image.fill(make_transparent_color());\n image.fill(rect, make_light_color());\n image.fill(make_interior_rect(rect), make_transparent_color());\n\n return image;\n }\n\n void fill_circle(image_t& image, const rect_t& rect, rgba_t rgba)\n {\n const point_t center = rect.center();\n const coord_t cx = center.x();\n const coord_t cy = center.y();\n\n const coord_t radius = (std::min(rect.width(), rect.height()) + 1) \/ 2;\n\n for (coord_t x = rect.left(); x < rect.right(); x ++)\n {\n for (coord_t y = rect.top(); y < rect.bottom(); y ++)\n {\n if (math::square(x - cx) + math::square(y - cy) < radius * radius)\n {\n image.set(y, x, rgba);\n }\n }\n }\n }\n\n image_t make_filled_circle(coord_t rows, coord_t cols)\n {\n const rect_t rect = make_rect(rows, cols);\n\n image_t image(rows, cols, color_mode::rgba);\n\n image.fill(make_transparent_color());\n fill_circle(image, rect, make_light_color());\n\n return image;\n }\n\n image_t make_hollow_circle(coord_t rows, coord_t cols)\n {\n const rect_t rect = make_rect(rows, cols);\n\n image_t image(rows, cols, color_mode::rgba);\n\n image.fill(make_transparent_color());\n fill_circle(image, rect, make_light_color());\n fill_circle(image, make_interior_rect(rect), make_transparent_color());\n\n return image;\n }\n }\n\n bool synthetic_shapes_task_t::load(const string_t &)\n {\n random_t<size_t> rng_protocol(1, 10);\n random_t<size_t> rng_output(1, osize());\n\n random_t<scalar_t> rng_gauss(scalar_t(1), math::cast<scalar_t>(icols() + irows()) \/ scalar_t(8));\n\n const coord_t rows = static_cast<coord_t>(irows());\n const coord_t cols = static_cast<coord_t>(icols());\n\n clear_memory(0);\n\n for (size_t f = 0; f < fsize(); f ++)\n {\n for (size_t i = 0; i < m_size; i ++)\n {\n \/\/ random protocol: train vs. test\n const protocol p = (rng_protocol() < 9) ? protocol::train : protocol::test;\n\n \/\/ random output class: #dots\n const size_t o = rng_output();\n\n \/\/ generate random image background\n image_t image(irows(), icols(), color());\n image.fill(make_light_color());\n image.random_noise(color_channel::rgba, -155.0, 55.0, rng_gauss());\n\n \/\/ generate random shapes\n image_t shape;\n\n switch (o)\n {\n case 1: shape = make_filled_rect(rows, cols); break;\n case 2: shape = make_hollow_rect(rows, cols); break;\n case 3: shape = make_filled_circle(rows, cols); break;\n case 4: shape = make_hollow_circle(rows, cols); break;\n default: break;\n }\n\n shape.random_noise(color_channel::rgba, -10.0, +10.0, rng_gauss() * 0.5);\n image.alpha_blend(shape.rgba());\n\n add_image(image);\n\n \/\/ generate sample\n sample_t sample(n_images() - 1, sample_region(0, 0));\n switch (o)\n {\n case 1: sample.m_label = \"filled_rectangle\"; break;\n case 2: sample.m_label = \"hollow_rectangle\"; break;\n case 3: sample.m_label = \"filled_circle\"; break;\n case 4: sample.m_label = \"hollow_circle\"; break;\n default: sample.m_label = \"unkown\"; break;\n }\n\n sample.m_target = ncv::class_target(o - 1, osize());\n sample.m_fold = {f, p};\n add_sample(sample);\n }\n }\n\n return true;\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Author(s):\n * - Chris Kilner <ckilner@aldebaran-robotics.com>\n * - Cedric Gestes <gestes@aldebaran-robotics.com>\n *\n * Copyright (C) 2010, 2011, 2012 Aldebaran Robotics\n *\/\n\n\n#pragma once\n#ifndef _QIMESSAGING_DATASTREAM_HPP_\n#define _QIMESSAGING_DATASTREAM_HPP_\n\n#include <iostream>\n#include <list>\n#include <vector>\n#include <map>\n#include <stdint.h>\n#include <qimessaging\/api.hpp>\n#include <qimessaging\/value.hpp>\n#include <qimessaging\/buffer.hpp>\n\nnamespace qi {\n\n#if 0\n#include <iostream>\n#define __QI_DEBUG_SERIALIZATION_W(x, extra) { \\\n std::string sig = qi::signature< x >::value(); \\\n std::cout << \"write(\" << sig << \")\" << extra << std::endl; \\\n }\n\n#define __QI_DEBUG_SERIALIZATION_R(x, extra) { \\\n std::string sig = qi::signature< x >::value(); \\\n std::cout << \"read (\" << sig << \")\" << extra << std::endl; \\\n }\n\n#define __QI_DEBUG_SERIALIZATION_CONTAINER_W(x, c) { \\\n std::string sig = qi::signature< x >::value(); \\\n std::cout << \"write(\" << sig << \") size: \" << c.size() << std::endl; \\\n }\n\n#define __QI_DEBUG_SERIALIZATION_CONTAINER_R(x, c) { \\\n std::string sig = qi::signature< x >::value(); \\\n std::cout << \"read (\" << sig << \") size: \" << c.size() << std::endl; \\\n }\n#else\n# define __QI_DEBUG_SERIALIZATION_W(x, extra)\n# define __QI_DEBUG_SERIALIZATION_R(x, extra)\n# define __QI_DEBUG_SERIALIZATION_CONTAINER_W(x, c)\n# define __QI_DEBUG_SERIALIZATION_CONTAINER_R(x, c)\n#endif\n\n class QIMESSAGING_API DataStream {\n public:\n\n\n \/\/\/ <summary>Default constructor.<\/summary>\n \/\/\/ <param name=\"data\">The data.<\/param>\n explicit DataStream(const qi::Buffer &buffer);\n explicit DataStream(qi::Buffer &buffer);\n\n size_t read(void *data, size_t len);\n void writeString(const char *str, size_t len);\n\n DataStream& operator<<(bool b);\n DataStream& operator<<(char c);\n DataStream& operator<<(int8_t c);\n DataStream& operator<<(int16_t s);\n DataStream& operator<<(int32_t i);\n DataStream& operator<<(int64_t l);\n\n DataStream& operator<<(uint8_t uc);\n DataStream& operator<<(uint16_t us);\n DataStream& operator<<(uint32_t ui);\n DataStream& operator<<(uint64_t ul);\n DataStream& operator<<(float f);\n DataStream& operator<<(double d);\n DataStream& operator<<(const char *);\n DataStream& operator<<(const std::string& i);\n\n DataStream& operator>>(bool &b);\n DataStream& operator>>(char &c);\n\n DataStream& operator>>(int8_t &c);\n DataStream& operator>>(int16_t &i);\n DataStream& operator>>(int32_t &i);\n DataStream& operator>>(int64_t &l);\n\n DataStream& operator>>(uint8_t &uc);\n DataStream& operator>>(uint16_t &us);\n DataStream& operator>>(uint32_t &ui);\n DataStream& operator>>(uint64_t &ul);\n\n DataStream& operator>>(float &i);\n DataStream& operator>>(double &i);\n DataStream& operator>>(std::string& i);\n\n \/\/\/ <summary>Gets the string. <\/summary>\n \/\/\/ <returns> The string representation of the serialized message<\/returns>\n \/\/void *data() { return _buffer->data(); }\n\n private:\n qi::Buffer _buffer;\n bool _ro;\n\n \/\/\/ <summary>Default constructor. <\/summary>\n DataStream()\n {}\n\n };\n\n\n template<typename T>\n qi::DataStream &operator<<(qi::DataStream &sd, const std::list<T> &v) {\n typedef std::list<T> _typefordebug;\n typename std::list<T>::const_iterator it = v.begin();\n typename std::list<T>::const_iterator end = v.end();\n\n sd << (uint32_t)v.size();\n for (; it != end; ++it) {\n sd << *it;\n }\n __QI_DEBUG_SERIALIZATION_CONTAINER_W(_typefordebug, v);\n return sd;\n }\n\n template<typename T>\n qi::DataStream &operator>>(qi::DataStream &sd, std::list<T> &v) {\n typedef std::list<T> _typefordebug;\n uint32_t sz;\n sd >> sz;\n v.clear();\n if (sz) {\n try {\n v.resize(sz);\n } catch (const std::exception &e) {\n qiLogError(\"qi.DataStream\") << \"std::list<T> serialization error, could not resize to \"\n << sz;\n return sd;\n }\n typename std::list<T>::iterator it = v.begin();\n typename std::list<T>::iterator end = v.end();\n for (; it != end; ++it) {\n sd >> *it;\n }\n }\n __QI_DEBUG_SERIALIZATION_CONTAINER_R(_typefordebug, v);\n return sd;\n }\n\n\n template<typename T>\n qi::DataStream &operator<<(qi::DataStream &sd, const std::vector<T> &v) {\n typedef std::vector<T> _typefordebug;\n typename std::vector<T>::const_iterator it = v.begin();\n typename std::vector<T>::const_iterator end = v.end();\n\n sd << (uint32_t)v.size();\n for (; it != end; ++it) {\n sd << *it;\n }\n __QI_DEBUG_SERIALIZATION_CONTAINER_W(_typefordebug, v);\n return sd;\n }\n\n template<typename T>\n qi::DataStream &operator>>(qi::DataStream &sd, std::vector<T> &v) {\n typedef std::vector<T> _typefordebug;\n uint32_t sz = 0;\n sd >> sz;\n v.clear();\n if (sz) {\n try {\n v.resize(sz);\n } catch (const std::exception &e) {\n qiLogError(\"qi.DataStream\") << \"std::vector<T> serialization error, could not resize to \"\n << sz;\n return sd;\n }\n typename std::vector<T>::iterator it = v.begin();\n typename std::vector<T>::iterator end = v.end();\n for (; it != end; ++it) {\n sd >> *it;\n }\n }\n __QI_DEBUG_SERIALIZATION_CONTAINER_R(_typefordebug, v);\n return sd;\n }\n\n template<typename K, typename V>\n qi::DataStream &operator<<(qi::DataStream &sd, const std::map<K, V> &m) {\n typedef std::map<K,V> _typefordebug;\n typename std::map<K,V>::const_iterator it = m.begin();\n typename std::map<K,V>::const_iterator end = m.end();\n\n sd << (uint32_t)m.size();\n\n for (; it != end; ++it) {\n sd << it->first;\n sd << it->second;\n }\n __QI_DEBUG_SERIALIZATION_CONTAINER_W(_typefordebug, m);\n return sd;\n }\n\n template<typename K, typename V>\n qi::DataStream &operator>>(qi::DataStream &sd, std::map<K, V> &m) {\n typedef std::map<K,V> _typefordebug;\n uint32_t sz;\n sd >> sz;\n m.clear();\n\n for(uint32_t i=0; i < sz; ++i) {\n K k;\n V v;\n sd >> k;\n sd >> v;\n m[k] = v;\n }\n __QI_DEBUG_SERIALIZATION_CONTAINER_R(_typefordebug, m);\n return sd;\n };\n\n QIMESSAGING_API qi::DataStream &operator>>(qi::DataStream &sd, qi::Value &value);\n QIMESSAGING_API qi::DataStream &operator<<(qi::DataStream &sd, const qi::Value &value);\n}\n\n#endif \/\/ _QIMESSAGING_DATASTREAM_HPP_\n<commit_msg>Fix compilation warning on windows<commit_after>\/*\n * Author(s):\n * - Chris Kilner <ckilner@aldebaran-robotics.com>\n * - Cedric Gestes <gestes@aldebaran-robotics.com>\n *\n * Copyright (C) 2010, 2011, 2012 Aldebaran Robotics\n *\/\n\n\n#pragma once\n#ifndef _QIMESSAGING_DATASTREAM_HPP_\n#define _QIMESSAGING_DATASTREAM_HPP_\n\n#include <iostream>\n#include <list>\n#include <vector>\n#include <map>\n#include <stdint.h>\n#include <qimessaging\/api.hpp>\n#include <qimessaging\/value.hpp>\n#include <qimessaging\/buffer.hpp>\n\nnamespace qi {\n\n#if 0\n#include <iostream>\n#define __QI_DEBUG_SERIALIZATION_W(x, extra) { \\\n std::string sig = qi::signature< x >::value(); \\\n std::cout << \"write(\" << sig << \")\" << extra << std::endl; \\\n }\n\n#define __QI_DEBUG_SERIALIZATION_R(x, extra) { \\\n std::string sig = qi::signature< x >::value(); \\\n std::cout << \"read (\" << sig << \")\" << extra << std::endl; \\\n }\n\n#define __QI_DEBUG_SERIALIZATION_CONTAINER_W(x, c) { \\\n std::string sig = qi::signature< x >::value(); \\\n std::cout << \"write(\" << sig << \") size: \" << c.size() << std::endl; \\\n }\n\n#define __QI_DEBUG_SERIALIZATION_CONTAINER_R(x, c) { \\\n std::string sig = qi::signature< x >::value(); \\\n std::cout << \"read (\" << sig << \") size: \" << c.size() << std::endl; \\\n }\n#else\n# define __QI_DEBUG_SERIALIZATION_W(x, extra)\n# define __QI_DEBUG_SERIALIZATION_R(x, extra)\n# define __QI_DEBUG_SERIALIZATION_CONTAINER_W(x, c)\n# define __QI_DEBUG_SERIALIZATION_CONTAINER_R(x, c)\n#endif\n\n class QIMESSAGING_API DataStream {\n public:\n\n\n \/\/\/ <summary>Default constructor.<\/summary>\n \/\/\/ <param name=\"data\">The data.<\/param>\n explicit DataStream(const qi::Buffer &buffer);\n explicit DataStream(qi::Buffer &buffer);\n\n size_t read(void *data, size_t len);\n void writeString(const char *str, size_t len);\n\n DataStream& operator<<(bool b);\n DataStream& operator<<(char c);\n DataStream& operator<<(int8_t c);\n DataStream& operator<<(int16_t s);\n DataStream& operator<<(int32_t i);\n DataStream& operator<<(int64_t l);\n\n DataStream& operator<<(uint8_t uc);\n DataStream& operator<<(uint16_t us);\n DataStream& operator<<(uint32_t ui);\n DataStream& operator<<(uint64_t ul);\n DataStream& operator<<(float f);\n DataStream& operator<<(double d);\n DataStream& operator<<(const char *);\n DataStream& operator<<(const std::string& i);\n\n DataStream& operator>>(bool &b);\n DataStream& operator>>(char &c);\n\n DataStream& operator>>(int8_t &c);\n DataStream& operator>>(int16_t &i);\n DataStream& operator>>(int32_t &i);\n DataStream& operator>>(int64_t &l);\n\n DataStream& operator>>(uint8_t &uc);\n DataStream& operator>>(uint16_t &us);\n DataStream& operator>>(uint32_t &ui);\n DataStream& operator>>(uint64_t &ul);\n\n DataStream& operator>>(float &i);\n DataStream& operator>>(double &i);\n DataStream& operator>>(std::string& i);\n\n \/\/\/ <summary>Gets the string. <\/summary>\n \/\/\/ <returns> The string representation of the serialized message<\/returns>\n \/\/void *data() { return _buffer->data(); }\n\n private:\n qi::Buffer _buffer;\n bool _ro;\n\n \/\/\/ <summary>Default constructor. <\/summary>\n DataStream()\n {}\n\n };\n\n\n template<typename T>\n qi::DataStream &operator<<(qi::DataStream &sd, const std::list<T> &v) {\n typedef std::list<T> _typefordebug;\n typename std::list<T>::const_iterator it = v.begin();\n typename std::list<T>::const_iterator end = v.end();\n\n sd << (uint32_t)v.size();\n for (; it != end; ++it) {\n sd << *it;\n }\n __QI_DEBUG_SERIALIZATION_CONTAINER_W(_typefordebug, v);\n return sd;\n }\n\n template<typename T>\n qi::DataStream &operator>>(qi::DataStream &sd, std::list<T> &v) {\n typedef std::list<T> _typefordebug;\n uint32_t sz;\n sd >> sz;\n v.clear();\n if (sz) {\n try {\n v.resize(sz);\n } catch (const std::exception &) {\n qiLogError(\"qi.DataStream\") << \"std::list<T> serialization error, could not resize to \"\n << sz;\n return sd;\n }\n typename std::list<T>::iterator it = v.begin();\n typename std::list<T>::iterator end = v.end();\n for (; it != end; ++it) {\n sd >> *it;\n }\n }\n __QI_DEBUG_SERIALIZATION_CONTAINER_R(_typefordebug, v);\n return sd;\n }\n\n\n template<typename T>\n qi::DataStream &operator<<(qi::DataStream &sd, const std::vector<T> &v) {\n typedef std::vector<T> _typefordebug;\n typename std::vector<T>::const_iterator it = v.begin();\n typename std::vector<T>::const_iterator end = v.end();\n\n sd << (uint32_t)v.size();\n for (; it != end; ++it) {\n sd << *it;\n }\n __QI_DEBUG_SERIALIZATION_CONTAINER_W(_typefordebug, v);\n return sd;\n }\n\n template<typename T>\n qi::DataStream &operator>>(qi::DataStream &sd, std::vector<T> &v) {\n typedef std::vector<T> _typefordebug;\n uint32_t sz = 0;\n sd >> sz;\n v.clear();\n if (sz) {\n try {\n v.resize(sz);\n } catch (const std::exception &) {\n qiLogError(\"qi.DataStream\") << \"std::vector<T> serialization error, could not resize to \"\n << sz;\n return sd;\n }\n typename std::vector<T>::iterator it = v.begin();\n typename std::vector<T>::iterator end = v.end();\n for (; it != end; ++it) {\n sd >> *it;\n }\n }\n __QI_DEBUG_SERIALIZATION_CONTAINER_R(_typefordebug, v);\n return sd;\n }\n\n template<typename K, typename V>\n qi::DataStream &operator<<(qi::DataStream &sd, const std::map<K, V> &m) {\n typedef std::map<K,V> _typefordebug;\n typename std::map<K,V>::const_iterator it = m.begin();\n typename std::map<K,V>::const_iterator end = m.end();\n\n sd << (uint32_t)m.size();\n\n for (; it != end; ++it) {\n sd << it->first;\n sd << it->second;\n }\n __QI_DEBUG_SERIALIZATION_CONTAINER_W(_typefordebug, m);\n return sd;\n }\n\n template<typename K, typename V>\n qi::DataStream &operator>>(qi::DataStream &sd, std::map<K, V> &m) {\n typedef std::map<K,V> _typefordebug;\n uint32_t sz;\n sd >> sz;\n m.clear();\n\n for(uint32_t i=0; i < sz; ++i) {\n K k;\n V v;\n sd >> k;\n sd >> v;\n m[k] = v;\n }\n __QI_DEBUG_SERIALIZATION_CONTAINER_R(_typefordebug, m);\n return sd;\n };\n\n QIMESSAGING_API qi::DataStream &operator>>(qi::DataStream &sd, qi::Value &value);\n QIMESSAGING_API qi::DataStream &operator<<(qi::DataStream &sd, const qi::Value &value);\n}\n\n#endif \/\/ _QIMESSAGING_DATASTREAM_HPP_\n<|endoftext|>"} {"text":"<commit_before>#include \"LiquidCrystal.h\"\n\n#include <stdio.h>\n#include <string.h>\n#include <inttypes.h>\n#include \"WProgram.h\"\n\n\/\/ When the display powers up, it is configured as follows:\n\/\/\n\/\/ 1. Display clear\n\/\/ 2. Function set: \n\/\/ DL = 1; 8-bit interface data \n\/\/ N = 0; 1-line display \n\/\/ F = 0; 5x8 dot character font \n\/\/ 3. Display on\/off control: \n\/\/ D = 0; Display off \n\/\/ C = 0; Cursor off \n\/\/ B = 0; Blinking off \n\/\/ 4. Entry mode set: \n\/\/ I\/D = 1; Increment by 1 \n\/\/ S = 0; No shift \n\/\/\n\/\/ Note, however, that resetting the Arduino doesn't reset the LCD, so we\n\/\/ can't assume that its in that state when a sketch starts (and the\n\/\/ LiquidCrystal constructor is called).\n\nLiquidCrystal::LiquidCrystal(uint8_t rs, uint8_t rw, uint8_t enable,\n\t\t\t uint8_t d0, uint8_t d1, uint8_t d2, uint8_t d3,\n\t\t\t uint8_t d4, uint8_t d5, uint8_t d6, uint8_t d7)\n{\n init(0, rs, rw, enable, d0, d1, d2, d3, d4, d5, d6, d7);\n}\n\nLiquidCrystal::LiquidCrystal(uint8_t rs, uint8_t enable,\n\t\t\t uint8_t d0, uint8_t d1, uint8_t d2, uint8_t d3,\n\t\t\t uint8_t d4, uint8_t d5, uint8_t d6, uint8_t d7)\n{\n init(0, rs, 255, enable, d0, d1, d2, d3, d4, d5, d6, d7);\n}\n\nLiquidCrystal::LiquidCrystal(uint8_t rs, uint8_t rw, uint8_t enable,\n\t\t\t uint8_t d0, uint8_t d1, uint8_t d2, uint8_t d3)\n{\n init(1, rs, rw, enable, d0, d1, d2, d3, 0, 0, 0, 0);\n}\n\nLiquidCrystal::LiquidCrystal(uint8_t rs, uint8_t enable,\n\t\t\t uint8_t d0, uint8_t d1, uint8_t d2, uint8_t d3)\n{\n init(1, rs, 255, enable, d0, d1, d2, d3, 0, 0, 0, 0);\n}\n\nvoid LiquidCrystal::init(uint8_t fourbitmode, uint8_t rs, uint8_t rw, uint8_t enable,\n\t\t\t uint8_t d0, uint8_t d1, uint8_t d2, uint8_t d3,\n\t\t\t uint8_t d4, uint8_t d5, uint8_t d6, uint8_t d7)\n{\n _rs_pin = rs;\n _rw_pin = rw;\n _enable_pin = enable;\n \n _data_pins[0] = d0;\n _data_pins[1] = d1;\n _data_pins[2] = d2;\n _data_pins[3] = d3; \n _data_pins[4] = d4;\n _data_pins[5] = d5;\n _data_pins[6] = d6;\n _data_pins[7] = d7; \n\n pinMode(_rs_pin, OUTPUT);\n \/\/ we can save 1 pin by not using RW. Indicate by passing 255 instead of pin#\n if (_rw_pin != 255) { \n pinMode(_rw_pin, OUTPUT);\n }\n pinMode(_enable_pin, OUTPUT);\n \n if (fourbitmode)\n _displayfunction = LCD_4BITMODE | LCD_1LINE | LCD_5x8DOTS;\n else \n _displayfunction = LCD_8BITMODE | LCD_1LINE | LCD_5x8DOTS;\n \n begin(16, 1); \n}\n\nvoid LiquidCrystal::begin(uint8_t cols, uint8_t lines, uint8_t dotsize) {\n if (lines > 1) {\n _displayfunction |= LCD_2LINE;\n }\n _numlines = lines;\n _currline = 0;\n\n \/\/ for some 1 line displays you can select a 10 pixel high font\n if ((dotsize != 0) && (lines == 1)) {\n _displayfunction |= LCD_5x10DOTS;\n }\n\n \/\/ SEE PAGE 45\/46 FOR INITIALIZATION SPECIFICATION!\n \/\/ according to datasheet, we need at least 40ms after power rises above 2.7V\n \/\/ before sending commands. Arduino can turn on way befer 4.5V so we'll wait 50\n delayMicroseconds(50000); \n \/\/ Now we pull both RS and R\/W low to begin commands\n digitalWrite(_rs_pin, LOW);\n digitalWrite(_enable_pin, LOW);\n if (_rw_pin != 255) { \n digitalWrite(_rw_pin, LOW);\n }\n \n \/\/put the LCD into 4 bit or 8 bit mode\n if (! (_displayfunction & LCD_8BITMODE)) {\n \/\/ this is according to the hitachi HD44780 datasheet\n \/\/ figure 24, pg 46\n\n \/\/ we start in 8bit mode, try to set 4 bit mode\n write4bits(0x03);\n delayMicroseconds(4500); \/\/ wait min 4.1ms\n\n \/\/ second try\n write4bits(0x03);\n delayMicroseconds(4500); \/\/ wait min 4.1ms\n \n \/\/ third go!\n write4bits(0x03); \n delayMicroseconds(150);\n\n \/\/ finally, set to 8-bit interface\n write4bits(0x02); \n } else {\n \/\/ this is according to the hitachi HD44780 datasheet\n \/\/ page 45 figure 23\n\n \/\/ Send function set command sequence\n command(LCD_FUNCTIONSET | _displayfunction);\n delayMicroseconds(4500); \/\/ wait more than 4.1ms\n\n \/\/ second try\n command(LCD_FUNCTIONSET | _displayfunction);\n delayMicroseconds(150);\n\n \/\/ third go\n command(LCD_FUNCTIONSET | _displayfunction);\n }\n\n \/\/ finally, set # lines, font size, etc.\n command(LCD_FUNCTIONSET | _displayfunction); \n\n \/\/ turn the display on with no cursor or blinking default\n _displaycontrol = LCD_DISPLAYON | LCD_CURSOROFF | LCD_BLINKOFF; \n display();\n\n \/\/ clear it off\n clear();\n\n \/\/ Initialize to default text direction (for romance languages)\n _displaymode = LCD_ENTRYLEFT | LCD_ENTRYSHIFTDECREMENT;\n \/\/ set the entry mode\n command(LCD_ENTRYMODESET | _displaymode);\n\n}\n\n\/********** high level commands, for the user! *\/\nvoid LiquidCrystal::clear()\n{\n command(LCD_CLEARDISPLAY); \/\/ clear display, set cursor position to zero\n delayMicroseconds(2000); \/\/ this command takes a long time!\n}\n\nvoid LiquidCrystal::home()\n{\n command(LCD_RETURNHOME); \/\/ set cursor position to zero\n delayMicroseconds(2000); \/\/ this command takes a long time!\n}\n\nvoid LiquidCrystal::setCursor(uint8_t col, uint8_t row)\n{\n int row_offsets[] = { 0x00, 0x40, 0x14, 0x54 };\n if ( row > _numlines ) {\n row = _numlines-1; \/\/ we count rows starting w\/0\n }\n \n command(LCD_SETDDRAMADDR | (col + row_offsets[row]));\n}\n\n\/\/ Turn the display on\/off (quickly)\nvoid LiquidCrystal::noDisplay() {\n _displaycontrol &= ~LCD_DISPLAYON;\n command(LCD_DISPLAYCONTROL | _displaycontrol);\n}\nvoid LiquidCrystal::display() {\n _displaycontrol |= LCD_DISPLAYON;\n command(LCD_DISPLAYCONTROL | _displaycontrol);\n}\n\n\/\/ Turns the underline cursor on\/off\nvoid LiquidCrystal::noCursor() {\n _displaycontrol &= ~LCD_CURSORON;\n command(LCD_DISPLAYCONTROL | _displaycontrol);\n}\nvoid LiquidCrystal::cursor() {\n _displaycontrol |= LCD_CURSORON;\n command(LCD_DISPLAYCONTROL | _displaycontrol);\n}\n\n\/\/ Turn on and off the blinking cursor\nvoid LiquidCrystal::noBlink() {\n _displaycontrol &= ~LCD_BLINKON;\n command(LCD_DISPLAYCONTROL | _displaycontrol);\n}\nvoid LiquidCrystal::blink() {\n _displaycontrol |= LCD_BLINKON;\n command(LCD_DISPLAYCONTROL | _displaycontrol);\n}\n\n\/\/ These commands scroll the display without changing the RAM\nvoid LiquidCrystal::scrollDisplayLeft(void) {\n command(LCD_CURSORSHIFT | LCD_DISPLAYMOVE | LCD_MOVELEFT);\n}\nvoid LiquidCrystal::scrollDisplayRight(void) {\n command(LCD_CURSORSHIFT | LCD_DISPLAYMOVE | LCD_MOVERIGHT);\n}\n\n\/\/ This is for text that flows Left to Right\nvoid LiquidCrystal::leftToRight(void) {\n _displaymode |= LCD_ENTRYLEFT;\n command(LCD_ENTRYMODESET | _displaymode);\n}\n\n\/\/ This is for text that flows Right to Left\nvoid LiquidCrystal::rightToLeft(void) {\n _displaymode &= ~LCD_ENTRYLEFT;\n command(LCD_ENTRYMODESET | _displaymode);\n}\n\n\/\/ This will 'right justify' text from the cursor\nvoid LiquidCrystal::autoscroll(void) {\n _displaymode |= LCD_ENTRYSHIFTINCREMENT;\n command(LCD_ENTRYMODESET | _displaymode);\n}\n\n\/\/ This will 'left justify' text from the cursor\nvoid LiquidCrystal::noAutoscroll(void) {\n _displaymode &= ~LCD_ENTRYSHIFTINCREMENT;\n command(LCD_ENTRYMODESET | _displaymode);\n}\n\n\/\/ Allows us to fill the first 8 CGRAM locations\n\/\/ with custom characters\nvoid LiquidCrystal::createChar(uint8_t location, uint8_t charmap[]) {\n location &= 0x7; \/\/ we only have 8 locations 0-7\n command(LCD_SETCGRAMADDR | (location << 3));\n for (int i=0; i<8; i++) {\n write(charmap[i]);\n }\n}\n\n\/*********** mid level commands, for sending data\/cmds *\/\n\ninline void LiquidCrystal::command(uint8_t value) {\n send(value, LOW);\n}\n\ninline void LiquidCrystal::write(uint8_t value) {\n send(value, HIGH);\n}\n\n\/************ low level data pushing commands **********\/\n\n\/\/ write either command or data, with automatic 4\/8-bit selection\nvoid LiquidCrystal::send(uint8_t value, uint8_t mode) {\n digitalWrite(_rs_pin, mode);\n\n \/\/ if there is a RW pin indicated, set it low to Write\n if (_rw_pin != 255) { \n digitalWrite(_rw_pin, LOW);\n }\n \n if (_displayfunction & LCD_8BITMODE) {\n write8bits(value); \n } else {\n write4bits(value>>4);\n write4bits(value);\n }\n}\n\nvoid LiquidCrystal::pulseEnable(void) {\n digitalWrite(_enable_pin, LOW);\n delayMicroseconds(1); \n digitalWrite(_enable_pin, HIGH);\n delayMicroseconds(1); \/\/ enable pulse must be >450ns\n digitalWrite(_enable_pin, LOW);\n delayMicroseconds(100); \/\/ commands need > 37us to settle\n}\n\nvoid LiquidCrystal::write4bits(uint8_t value) {\n for (int i = 0; i < 4; i++) {\n pinMode(_data_pins[i], OUTPUT);\n digitalWrite(_data_pins[i], (value >> i) & 0x01);\n }\n\n pulseEnable();\n}\n\nvoid LiquidCrystal::write8bits(uint8_t value) {\n for (int i = 0; i < 8; i++) {\n pinMode(_data_pins[i], OUTPUT);\n digitalWrite(_data_pins[i], (value >> i) & 0x01);\n }\n \n pulseEnable();\n}\n<commit_msg>When initializing LCD, comment specified \"8-bit\" mode when it should day \"4 bit mode\"<commit_after>#include \"LiquidCrystal.h\"\n\n#include <stdio.h>\n#include <string.h>\n#include <inttypes.h>\n#include \"WProgram.h\"\n\n\/\/ When the display powers up, it is configured as follows:\n\/\/\n\/\/ 1. Display clear\n\/\/ 2. Function set: \n\/\/ DL = 1; 8-bit interface data \n\/\/ N = 0; 1-line display \n\/\/ F = 0; 5x8 dot character font \n\/\/ 3. Display on\/off control: \n\/\/ D = 0; Display off \n\/\/ C = 0; Cursor off \n\/\/ B = 0; Blinking off \n\/\/ 4. Entry mode set: \n\/\/ I\/D = 1; Increment by 1 \n\/\/ S = 0; No shift \n\/\/\n\/\/ Note, however, that resetting the Arduino doesn't reset the LCD, so we\n\/\/ can't assume that its in that state when a sketch starts (and the\n\/\/ LiquidCrystal constructor is called).\n\nLiquidCrystal::LiquidCrystal(uint8_t rs, uint8_t rw, uint8_t enable,\n\t\t\t uint8_t d0, uint8_t d1, uint8_t d2, uint8_t d3,\n\t\t\t uint8_t d4, uint8_t d5, uint8_t d6, uint8_t d7)\n{\n init(0, rs, rw, enable, d0, d1, d2, d3, d4, d5, d6, d7);\n}\n\nLiquidCrystal::LiquidCrystal(uint8_t rs, uint8_t enable,\n\t\t\t uint8_t d0, uint8_t d1, uint8_t d2, uint8_t d3,\n\t\t\t uint8_t d4, uint8_t d5, uint8_t d6, uint8_t d7)\n{\n init(0, rs, 255, enable, d0, d1, d2, d3, d4, d5, d6, d7);\n}\n\nLiquidCrystal::LiquidCrystal(uint8_t rs, uint8_t rw, uint8_t enable,\n\t\t\t uint8_t d0, uint8_t d1, uint8_t d2, uint8_t d3)\n{\n init(1, rs, rw, enable, d0, d1, d2, d3, 0, 0, 0, 0);\n}\n\nLiquidCrystal::LiquidCrystal(uint8_t rs, uint8_t enable,\n\t\t\t uint8_t d0, uint8_t d1, uint8_t d2, uint8_t d3)\n{\n init(1, rs, 255, enable, d0, d1, d2, d3, 0, 0, 0, 0);\n}\n\nvoid LiquidCrystal::init(uint8_t fourbitmode, uint8_t rs, uint8_t rw, uint8_t enable,\n\t\t\t uint8_t d0, uint8_t d1, uint8_t d2, uint8_t d3,\n\t\t\t uint8_t d4, uint8_t d5, uint8_t d6, uint8_t d7)\n{\n _rs_pin = rs;\n _rw_pin = rw;\n _enable_pin = enable;\n \n _data_pins[0] = d0;\n _data_pins[1] = d1;\n _data_pins[2] = d2;\n _data_pins[3] = d3; \n _data_pins[4] = d4;\n _data_pins[5] = d5;\n _data_pins[6] = d6;\n _data_pins[7] = d7; \n\n pinMode(_rs_pin, OUTPUT);\n \/\/ we can save 1 pin by not using RW. Indicate by passing 255 instead of pin#\n if (_rw_pin != 255) { \n pinMode(_rw_pin, OUTPUT);\n }\n pinMode(_enable_pin, OUTPUT);\n \n if (fourbitmode)\n _displayfunction = LCD_4BITMODE | LCD_1LINE | LCD_5x8DOTS;\n else \n _displayfunction = LCD_8BITMODE | LCD_1LINE | LCD_5x8DOTS;\n \n begin(16, 1); \n}\n\nvoid LiquidCrystal::begin(uint8_t cols, uint8_t lines, uint8_t dotsize) {\n if (lines > 1) {\n _displayfunction |= LCD_2LINE;\n }\n _numlines = lines;\n _currline = 0;\n\n \/\/ for some 1 line displays you can select a 10 pixel high font\n if ((dotsize != 0) && (lines == 1)) {\n _displayfunction |= LCD_5x10DOTS;\n }\n\n \/\/ SEE PAGE 45\/46 FOR INITIALIZATION SPECIFICATION!\n \/\/ according to datasheet, we need at least 40ms after power rises above 2.7V\n \/\/ before sending commands. Arduino can turn on way befer 4.5V so we'll wait 50\n delayMicroseconds(50000); \n \/\/ Now we pull both RS and R\/W low to begin commands\n digitalWrite(_rs_pin, LOW);\n digitalWrite(_enable_pin, LOW);\n if (_rw_pin != 255) { \n digitalWrite(_rw_pin, LOW);\n }\n \n \/\/put the LCD into 4 bit or 8 bit mode\n if (! (_displayfunction & LCD_8BITMODE)) {\n \/\/ this is according to the hitachi HD44780 datasheet\n \/\/ figure 24, pg 46\n\n \/\/ we start in 8bit mode, try to set 4 bit mode\n write4bits(0x03);\n delayMicroseconds(4500); \/\/ wait min 4.1ms\n\n \/\/ second try\n write4bits(0x03);\n delayMicroseconds(4500); \/\/ wait min 4.1ms\n \n \/\/ third go!\n write4bits(0x03); \n delayMicroseconds(150);\n\n \/\/ finally, set to 4-bit interface\n write4bits(0x02); \n } else {\n \/\/ this is according to the hitachi HD44780 datasheet\n \/\/ page 45 figure 23\n\n \/\/ Send function set command sequence\n command(LCD_FUNCTIONSET | _displayfunction);\n delayMicroseconds(4500); \/\/ wait more than 4.1ms\n\n \/\/ second try\n command(LCD_FUNCTIONSET | _displayfunction);\n delayMicroseconds(150);\n\n \/\/ third go\n command(LCD_FUNCTIONSET | _displayfunction);\n }\n\n \/\/ finally, set # lines, font size, etc.\n command(LCD_FUNCTIONSET | _displayfunction); \n\n \/\/ turn the display on with no cursor or blinking default\n _displaycontrol = LCD_DISPLAYON | LCD_CURSOROFF | LCD_BLINKOFF; \n display();\n\n \/\/ clear it off\n clear();\n\n \/\/ Initialize to default text direction (for romance languages)\n _displaymode = LCD_ENTRYLEFT | LCD_ENTRYSHIFTDECREMENT;\n \/\/ set the entry mode\n command(LCD_ENTRYMODESET | _displaymode);\n\n}\n\n\/********** high level commands, for the user! *\/\nvoid LiquidCrystal::clear()\n{\n command(LCD_CLEARDISPLAY); \/\/ clear display, set cursor position to zero\n delayMicroseconds(2000); \/\/ this command takes a long time!\n}\n\nvoid LiquidCrystal::home()\n{\n command(LCD_RETURNHOME); \/\/ set cursor position to zero\n delayMicroseconds(2000); \/\/ this command takes a long time!\n}\n\nvoid LiquidCrystal::setCursor(uint8_t col, uint8_t row)\n{\n int row_offsets[] = { 0x00, 0x40, 0x14, 0x54 };\n if ( row > _numlines ) {\n row = _numlines-1; \/\/ we count rows starting w\/0\n }\n \n command(LCD_SETDDRAMADDR | (col + row_offsets[row]));\n}\n\n\/\/ Turn the display on\/off (quickly)\nvoid LiquidCrystal::noDisplay() {\n _displaycontrol &= ~LCD_DISPLAYON;\n command(LCD_DISPLAYCONTROL | _displaycontrol);\n}\nvoid LiquidCrystal::display() {\n _displaycontrol |= LCD_DISPLAYON;\n command(LCD_DISPLAYCONTROL | _displaycontrol);\n}\n\n\/\/ Turns the underline cursor on\/off\nvoid LiquidCrystal::noCursor() {\n _displaycontrol &= ~LCD_CURSORON;\n command(LCD_DISPLAYCONTROL | _displaycontrol);\n}\nvoid LiquidCrystal::cursor() {\n _displaycontrol |= LCD_CURSORON;\n command(LCD_DISPLAYCONTROL | _displaycontrol);\n}\n\n\/\/ Turn on and off the blinking cursor\nvoid LiquidCrystal::noBlink() {\n _displaycontrol &= ~LCD_BLINKON;\n command(LCD_DISPLAYCONTROL | _displaycontrol);\n}\nvoid LiquidCrystal::blink() {\n _displaycontrol |= LCD_BLINKON;\n command(LCD_DISPLAYCONTROL | _displaycontrol);\n}\n\n\/\/ These commands scroll the display without changing the RAM\nvoid LiquidCrystal::scrollDisplayLeft(void) {\n command(LCD_CURSORSHIFT | LCD_DISPLAYMOVE | LCD_MOVELEFT);\n}\nvoid LiquidCrystal::scrollDisplayRight(void) {\n command(LCD_CURSORSHIFT | LCD_DISPLAYMOVE | LCD_MOVERIGHT);\n}\n\n\/\/ This is for text that flows Left to Right\nvoid LiquidCrystal::leftToRight(void) {\n _displaymode |= LCD_ENTRYLEFT;\n command(LCD_ENTRYMODESET | _displaymode);\n}\n\n\/\/ This is for text that flows Right to Left\nvoid LiquidCrystal::rightToLeft(void) {\n _displaymode &= ~LCD_ENTRYLEFT;\n command(LCD_ENTRYMODESET | _displaymode);\n}\n\n\/\/ This will 'right justify' text from the cursor\nvoid LiquidCrystal::autoscroll(void) {\n _displaymode |= LCD_ENTRYSHIFTINCREMENT;\n command(LCD_ENTRYMODESET | _displaymode);\n}\n\n\/\/ This will 'left justify' text from the cursor\nvoid LiquidCrystal::noAutoscroll(void) {\n _displaymode &= ~LCD_ENTRYSHIFTINCREMENT;\n command(LCD_ENTRYMODESET | _displaymode);\n}\n\n\/\/ Allows us to fill the first 8 CGRAM locations\n\/\/ with custom characters\nvoid LiquidCrystal::createChar(uint8_t location, uint8_t charmap[]) {\n location &= 0x7; \/\/ we only have 8 locations 0-7\n command(LCD_SETCGRAMADDR | (location << 3));\n for (int i=0; i<8; i++) {\n write(charmap[i]);\n }\n}\n\n\/*********** mid level commands, for sending data\/cmds *\/\n\ninline void LiquidCrystal::command(uint8_t value) {\n send(value, LOW);\n}\n\ninline void LiquidCrystal::write(uint8_t value) {\n send(value, HIGH);\n}\n\n\/************ low level data pushing commands **********\/\n\n\/\/ write either command or data, with automatic 4\/8-bit selection\nvoid LiquidCrystal::send(uint8_t value, uint8_t mode) {\n digitalWrite(_rs_pin, mode);\n\n \/\/ if there is a RW pin indicated, set it low to Write\n if (_rw_pin != 255) { \n digitalWrite(_rw_pin, LOW);\n }\n \n if (_displayfunction & LCD_8BITMODE) {\n write8bits(value); \n } else {\n write4bits(value>>4);\n write4bits(value);\n }\n}\n\nvoid LiquidCrystal::pulseEnable(void) {\n digitalWrite(_enable_pin, LOW);\n delayMicroseconds(1); \n digitalWrite(_enable_pin, HIGH);\n delayMicroseconds(1); \/\/ enable pulse must be >450ns\n digitalWrite(_enable_pin, LOW);\n delayMicroseconds(100); \/\/ commands need > 37us to settle\n}\n\nvoid LiquidCrystal::write4bits(uint8_t value) {\n for (int i = 0; i < 4; i++) {\n pinMode(_data_pins[i], OUTPUT);\n digitalWrite(_data_pins[i], (value >> i) & 0x01);\n }\n\n pulseEnable();\n}\n\nvoid LiquidCrystal::write8bits(uint8_t value) {\n for (int i = 0; i < 8; i++) {\n pinMode(_data_pins[i], OUTPUT);\n digitalWrite(_data_pins[i], (value >> i) & 0x01);\n }\n \n pulseEnable();\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ $Id: fe_hermite_shape_3D.C,v 1.3 2005-09-02 18:48:55 roystgnr Exp $\n\n\/\/ The libMesh Finite Element Library.\n\/\/ Copyright (C) 2002-2005 Benjamin S. Kirk, John W. Peterson\n \n\/\/ This library is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU Lesser General Public\n\/\/ License as published by the Free Software Foundation; either\n\/\/ version 2.1 of the License, or (at your option) any later version.\n \n\/\/ This library is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ Lesser General Public License for more details.\n \n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License along with this library; if not, write to the Free Software\n\/\/ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n\n\n\/\/ C++ inlcludes\n\n\/\/ Local includes\n#include \"fe.h\"\n#include \"elem.h\"\n\n\n\/\/ Anonymous namespace for persistant variables.\n\/\/ This allows us to cache the global-to-local mapping transformation\n\/\/ FIXME: This should also screw up multithreading royally\nnamespace\n{\n static unsigned int old_elem_id = libMesh::invalid_uint;\n static std::vector<std::vector<Real> > dxdxi(3, std::vector<Real>(2, 0));\n#ifdef DEBUG\n static std::vector<Real> dydxi(2), dzdeta(2), dxdzeta(2);\n static std::vector<Real> dzdxi(2), dxdeta(2), dydzeta(2);\n#endif\n\n\n\n\/\/ Compute the static coefficients for an element\nvoid hermite_compute_coefs(const Elem* elem)\n{\n \/\/ Coefficients are cached from old elements\n if (elem->id() == old_elem_id)\n return;\n\n old_elem_id = elem->id();\n\n const Order mapping_order (elem->default_order());\n const ElemType mapping_elem_type (elem->type());\n const int n_mapping_shape_functions =\n FE<3,LAGRANGE>::n_shape_functions(mapping_elem_type,\n\t\t\t\t mapping_order);\n\n std::vector<Point> dofpt;\n dofpt.push_back(Point(-1,-1,-1));\n dofpt.push_back(Point(1,1,1));\n\n for (int p = 0; p != 2; ++p)\n {\n dxdxi[0][p] = 0;\n dxdxi[1][p] = 0;\n dxdxi[2][p] = 0;\n#ifdef DEBUG\n dydxi[p] = 0;\n dzdeta[p] = 0;\n dxdzeta[p] = 0;\n dzdxi[p] = 0;\n dxdeta[p] = 0;\n dydzeta[p] = 0;\n#endif\n for (int i = 0; i != n_mapping_shape_functions; ++i)\n {\n const Real ddxi = FE<3,LAGRANGE>::shape_deriv \n (mapping_elem_type, mapping_order, i, 0, dofpt[p]);\n const Real ddeta = FE<3,LAGRANGE>::shape_deriv \n (mapping_elem_type, mapping_order, i, 1, dofpt[p]);\n const Real ddzeta = FE<3,LAGRANGE>::shape_deriv \n (mapping_elem_type, mapping_order, i, 2, dofpt[p]);\n\n\t \/\/ dxdeta, dxdzeta, dydxi, dydzeta, dzdxi, dzdeta should all\n \/\/ be 0!\n dxdxi[0][p] += elem->point(i)(0) * ddxi;\n dxdxi[1][p] += elem->point(i)(1) * ddeta;\n dxdxi[2][p] += elem->point(i)(2) * ddzeta;\n#ifdef DEBUG\n dydxi[p] += elem->point(i)(1) * ddxi;\n dzdeta[p] += elem->point(i)(2) * ddeta;\n dxdzeta[p] += elem->point(i)(0) * ddzeta;\n dzdxi[p] += elem->point(i)(2) * ddxi;\n dxdeta[p] += elem->point(i)(0) * ddeta;\n dydzeta[p] += elem->point(i)(1) * ddzeta;\n#endif\n }\n \/\/ No singular elements!\n assert(dxdxi[0][p]);\n assert(dxdxi[1][p]);\n assert(dxdxi[2][p]);\n \/\/ No non-rectilinear or non-axis-aligned elements!\n#ifdef DEBUG\n assert(std::abs(dydxi[p]) < 1e-9);\n assert(std::abs(dzdeta[p]) < 1e-9);\n assert(std::abs(dxdzeta[p]) < 1e-9);\n assert(std::abs(dzdxi[p]) < 1e-9);\n assert(std::abs(dxdeta[p]) < 1e-9);\n assert(std::abs(dydzeta[p]) < 1e-9);\n#endif\n }\n}\n\n\n} \/\/ end anonymous namespace\n\n\n\ntemplate <>\nReal FE<3,HERMITE>::shape(const ElemType,\n\t\t\t const Order,\n\t\t\t const unsigned int,\n\t\t\t const Point&)\n{\n std::cerr << \"Hermite elements require the real element\\n\"\n\t << \"to construct gradient-based degrees of freedom.\"\n\t << std::endl;\n \n error();\n return 0.;\n}\n\n\n\ntemplate <>\nReal FE<3,HERMITE>::shape(const Elem* elem,\n\t\t\t const Order order,\n\t\t\t const unsigned int i,\n\t\t\t const Point& p)\n{\n assert (elem != NULL);\n\n hermite_compute_coefs(elem);\n\n const ElemType type = elem->type();\n \n switch (order)\n { \n \/\/ 3rd-order tricubic Hermite functions\n case THIRD:\n {\n\tswitch (type)\n\t {\n\t case HEX8:\n\t case HEX20:\n\t case HEX27:\n\t {\n\t assert (i<64);\n\n std::vector<unsigned int> bases1D;\n\n Real coef = FEHermite<1>::hermite_bases(bases1D, dxdxi, i, 3);\n\n\t return coef *\n FEHermite<1>::hermite_raw_shape(bases1D[0],p(0)) *\n FEHermite<1>::hermite_raw_shape(bases1D[1],p(1)) *\n FEHermite<1>::hermite_raw_shape(bases1D[2],p(2));\n\t }\n\t default:\n std::cerr << \"ERROR: Unsupported element type!\" << std::endl;\n\t error();\n\t }\n }\n \/\/ by default throw an error\n default:\n std::cerr << \"ERROR: Unsupported polynomial order!\" << std::endl;\n error();\n }\n \n error();\n return 0.;\n}\n\n\n\ntemplate <>\nReal FE<3,HERMITE>::shape_deriv(const ElemType,\n\t\t\t\tconst Order,\t\t\t \n\t\t\t\tconst unsigned int,\n\t\t\t\tconst unsigned int,\n\t\t\t\tconst Point&)\n{\n std::cerr << \"Hermite elements require the real element\\n\"\n\t << \"to construct gradient-based degrees of freedom.\"\n\t << std::endl;\n\n error();\n return 0.;\n}\n\n\n\ntemplate <>\nReal FE<3,HERMITE>::shape_deriv(const Elem* elem,\n\t\t\t\tconst Order order,\n\t\t\t\tconst unsigned int i,\n\t\t\t\tconst unsigned int j,\n\t\t\t\tconst Point& p)\n{\n assert (elem != NULL);\n assert (j == 0 || j == 1 || j == 2);\n\n hermite_compute_coefs(elem);\n\n const ElemType type = elem->type();\n \n switch (order)\n { \n \/\/ 3rd-order tricubic Hermite functions\n case THIRD:\n {\n\tswitch (type)\n\t {\n\t case HEX8:\n\t case HEX20:\n\t case HEX27:\n\t {\n\t assert (i<64);\n\n std::vector<unsigned int> bases1D;\n\n Real coef = FEHermite<1>::hermite_bases(bases1D, dxdxi, i, 3);\n\n switch (j) \/\/ Derivative type\n\t\t{\n\t\tcase 0:\n return coef *\n FEHermite<1>::hermite_raw_shape_deriv(bases1D[0],p(0)) * \n FEHermite<1>::hermite_raw_shape(bases1D[1],p(1)) * \n FEHermite<1>::hermite_raw_shape(bases1D[2],p(2));\n break;\n\t\tcase 1:\n return coef *\n FEHermite<1>::hermite_raw_shape(bases1D[0],p(0)) * \n FEHermite<1>::hermite_raw_shape_deriv(bases1D[1],p(1)) * \n FEHermite<1>::hermite_raw_shape(bases1D[2],p(2));\n break;\n\t\tcase 2:\n return coef *\n FEHermite<1>::hermite_raw_shape(bases1D[0],p(0)) * \n FEHermite<1>::hermite_raw_shape(bases1D[1],p(1)) * \n FEHermite<1>::hermite_raw_shape_deriv(bases1D[2],p(2));\n break;\n }\n \n\t }\n\t default:\n std::cerr << \"ERROR: Unsupported element type!\" << std::endl;\n\t error();\n\t }\n }\n \/\/ by default throw an error\n default:\n std::cerr << \"ERROR: Unsupported polynomial order!\" << std::endl;\n error();\n }\n \n error();\n return 0.;\n}\n\n\n\ntemplate <>\nReal FE<3,HERMITE>::shape_second_deriv(const Elem* elem,\n const Order order,\n const unsigned int i,\n const unsigned int j,\n const Point& p)\n{\n assert (elem != NULL);\n\n hermite_compute_coefs(elem);\n\n const ElemType type = elem->type();\n \n switch (order)\n { \n \/\/ 3rd-order tricubic Hermite functions\n case THIRD:\n {\n\tswitch (type)\n\t {\n\t case HEX8:\n\t case HEX20:\n\t case HEX27:\n\t {\n\t assert (i<64);\n\n std::vector<unsigned int> bases1D;\n\n Real coef = FEHermite<1>::hermite_bases(bases1D, dxdxi, i, 3);\n\n switch (j) \/\/ Derivative type\n\t\t{\n\t\tcase 0:\n return coef *\n FEHermite<1>::hermite_raw_shape_second_deriv(bases1D[0],p(0)) * \n FEHermite<1>::hermite_raw_shape(bases1D[1],p(1)) * \n FEHermite<1>::hermite_raw_shape(bases1D[2],p(2));\n break;\n\t\tcase 1:\n return coef *\n FEHermite<1>::hermite_raw_shape_deriv(bases1D[0],p(0)) * \n FEHermite<1>::hermite_raw_shape_deriv(bases1D[1],p(1)) * \n FEHermite<1>::hermite_raw_shape(bases1D[2],p(2));\n break;\n\t\tcase 2:\n return coef *\n FEHermite<1>::hermite_raw_shape_second_deriv(bases1D[0],p(0)) * \n FEHermite<1>::hermite_raw_shape(bases1D[1],p(1)) * \n FEHermite<1>::hermite_raw_shape(bases1D[2],p(2));\n break;\n\t\tcase 3:\n return coef *\n FEHermite<1>::hermite_raw_shape_deriv(bases1D[0],p(0)) * \n FEHermite<1>::hermite_raw_shape(bases1D[1],p(1)) * \n FEHermite<1>::hermite_raw_shape_deriv(bases1D[2],p(2));\n break;\n\t\tcase 4:\n return coef *\n FEHermite<1>::hermite_raw_shape(bases1D[0],p(0)) * \n FEHermite<1>::hermite_raw_shape_deriv(bases1D[1],p(1)) * \n FEHermite<1>::hermite_raw_shape_deriv(bases1D[2],p(2));\n break;\n\t\tcase 5:\n return coef *\n FEHermite<1>::hermite_raw_shape(bases1D[0],p(0)) * \n FEHermite<1>::hermite_raw_shape(bases1D[1],p(1)) * \n FEHermite<1>::hermite_raw_shape_second_deriv(bases1D[2],p(2));\n break;\n }\n \n\t }\n\t default:\n std::cerr << \"ERROR: Unsupported element type!\" << std::endl;\n\t error();\n\t }\n }\n \/\/ by default throw an error\n default:\n std::cerr << \"ERROR: Unsupported polynomial order!\" << std::endl;\n error();\n }\n \n error();\n return 0.;\n}\n<commit_msg>Fixed broken yy derivative calculation<commit_after>\/\/ $Id: fe_hermite_shape_3D.C,v 1.4 2006-02-22 22:30:53 roystgnr Exp $\n\n\/\/ The libMesh Finite Element Library.\n\/\/ Copyright (C) 2002-2005 Benjamin S. Kirk, John W. Peterson\n \n\/\/ This library is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU Lesser General Public\n\/\/ License as published by the Free Software Foundation; either\n\/\/ version 2.1 of the License, or (at your option) any later version.\n \n\/\/ This library is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ Lesser General Public License for more details.\n \n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License along with this library; if not, write to the Free Software\n\/\/ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n\n\n\/\/ C++ inlcludes\n\n\/\/ Local includes\n#include \"fe.h\"\n#include \"elem.h\"\n\n\n\/\/ Anonymous namespace for persistant variables.\n\/\/ This allows us to cache the global-to-local mapping transformation\n\/\/ FIXME: This should also screw up multithreading royally\nnamespace\n{\n static unsigned int old_elem_id = libMesh::invalid_uint;\n static std::vector<std::vector<Real> > dxdxi(3, std::vector<Real>(2, 0));\n#ifdef DEBUG\n static std::vector<Real> dydxi(2), dzdeta(2), dxdzeta(2);\n static std::vector<Real> dzdxi(2), dxdeta(2), dydzeta(2);\n#endif\n\n\n\n\/\/ Compute the static coefficients for an element\nvoid hermite_compute_coefs(const Elem* elem)\n{\n \/\/ Coefficients are cached from old elements\n if (elem->id() == old_elem_id)\n return;\n\n old_elem_id = elem->id();\n\n const Order mapping_order (elem->default_order());\n const ElemType mapping_elem_type (elem->type());\n const int n_mapping_shape_functions =\n FE<3,LAGRANGE>::n_shape_functions(mapping_elem_type,\n\t\t\t\t mapping_order);\n\n std::vector<Point> dofpt;\n dofpt.push_back(Point(-1,-1,-1));\n dofpt.push_back(Point(1,1,1));\n\n for (int p = 0; p != 2; ++p)\n {\n dxdxi[0][p] = 0;\n dxdxi[1][p] = 0;\n dxdxi[2][p] = 0;\n#ifdef DEBUG\n dydxi[p] = 0;\n dzdeta[p] = 0;\n dxdzeta[p] = 0;\n dzdxi[p] = 0;\n dxdeta[p] = 0;\n dydzeta[p] = 0;\n#endif\n for (int i = 0; i != n_mapping_shape_functions; ++i)\n {\n const Real ddxi = FE<3,LAGRANGE>::shape_deriv \n (mapping_elem_type, mapping_order, i, 0, dofpt[p]);\n const Real ddeta = FE<3,LAGRANGE>::shape_deriv \n (mapping_elem_type, mapping_order, i, 1, dofpt[p]);\n const Real ddzeta = FE<3,LAGRANGE>::shape_deriv \n (mapping_elem_type, mapping_order, i, 2, dofpt[p]);\n\n\t \/\/ dxdeta, dxdzeta, dydxi, dydzeta, dzdxi, dzdeta should all\n \/\/ be 0!\n dxdxi[0][p] += elem->point(i)(0) * ddxi;\n dxdxi[1][p] += elem->point(i)(1) * ddeta;\n dxdxi[2][p] += elem->point(i)(2) * ddzeta;\n#ifdef DEBUG\n dydxi[p] += elem->point(i)(1) * ddxi;\n dzdeta[p] += elem->point(i)(2) * ddeta;\n dxdzeta[p] += elem->point(i)(0) * ddzeta;\n dzdxi[p] += elem->point(i)(2) * ddxi;\n dxdeta[p] += elem->point(i)(0) * ddeta;\n dydzeta[p] += elem->point(i)(1) * ddzeta;\n#endif\n }\n \/\/ No singular elements!\n assert(dxdxi[0][p]);\n assert(dxdxi[1][p]);\n assert(dxdxi[2][p]);\n \/\/ No non-rectilinear or non-axis-aligned elements!\n#ifdef DEBUG\n assert(std::abs(dydxi[p]) < 1e-9);\n assert(std::abs(dzdeta[p]) < 1e-9);\n assert(std::abs(dxdzeta[p]) < 1e-9);\n assert(std::abs(dzdxi[p]) < 1e-9);\n assert(std::abs(dxdeta[p]) < 1e-9);\n assert(std::abs(dydzeta[p]) < 1e-9);\n#endif\n }\n}\n\n\n} \/\/ end anonymous namespace\n\n\n\ntemplate <>\nReal FE<3,HERMITE>::shape(const ElemType,\n\t\t\t const Order,\n\t\t\t const unsigned int,\n\t\t\t const Point&)\n{\n std::cerr << \"Hermite elements require the real element\\n\"\n\t << \"to construct gradient-based degrees of freedom.\"\n\t << std::endl;\n \n error();\n return 0.;\n}\n\n\n\ntemplate <>\nReal FE<3,HERMITE>::shape(const Elem* elem,\n\t\t\t const Order order,\n\t\t\t const unsigned int i,\n\t\t\t const Point& p)\n{\n assert (elem != NULL);\n\n hermite_compute_coefs(elem);\n\n const ElemType type = elem->type();\n \n switch (order)\n { \n \/\/ 3rd-order tricubic Hermite functions\n case THIRD:\n {\n\tswitch (type)\n\t {\n\t case HEX8:\n\t case HEX20:\n\t case HEX27:\n\t {\n\t assert (i<64);\n\n std::vector<unsigned int> bases1D;\n\n Real coef = FEHermite<1>::hermite_bases(bases1D, dxdxi, i, 3);\n\n\t return coef *\n FEHermite<1>::hermite_raw_shape(bases1D[0],p(0)) *\n FEHermite<1>::hermite_raw_shape(bases1D[1],p(1)) *\n FEHermite<1>::hermite_raw_shape(bases1D[2],p(2));\n\t }\n\t default:\n std::cerr << \"ERROR: Unsupported element type!\" << std::endl;\n\t error();\n\t }\n }\n \/\/ by default throw an error\n default:\n std::cerr << \"ERROR: Unsupported polynomial order!\" << std::endl;\n error();\n }\n \n error();\n return 0.;\n}\n\n\n\ntemplate <>\nReal FE<3,HERMITE>::shape_deriv(const ElemType,\n\t\t\t\tconst Order,\t\t\t \n\t\t\t\tconst unsigned int,\n\t\t\t\tconst unsigned int,\n\t\t\t\tconst Point&)\n{\n std::cerr << \"Hermite elements require the real element\\n\"\n\t << \"to construct gradient-based degrees of freedom.\"\n\t << std::endl;\n\n error();\n return 0.;\n}\n\n\n\ntemplate <>\nReal FE<3,HERMITE>::shape_deriv(const Elem* elem,\n\t\t\t\tconst Order order,\n\t\t\t\tconst unsigned int i,\n\t\t\t\tconst unsigned int j,\n\t\t\t\tconst Point& p)\n{\n assert (elem != NULL);\n assert (j == 0 || j == 1 || j == 2);\n\n hermite_compute_coefs(elem);\n\n const ElemType type = elem->type();\n \n switch (order)\n { \n \/\/ 3rd-order tricubic Hermite functions\n case THIRD:\n {\n\tswitch (type)\n\t {\n\t case HEX8:\n\t case HEX20:\n\t case HEX27:\n\t {\n\t assert (i<64);\n\n std::vector<unsigned int> bases1D;\n\n Real coef = FEHermite<1>::hermite_bases(bases1D, dxdxi, i, 3);\n\n switch (j) \/\/ Derivative type\n\t\t{\n\t\tcase 0:\n return coef *\n FEHermite<1>::hermite_raw_shape_deriv(bases1D[0],p(0)) * \n FEHermite<1>::hermite_raw_shape(bases1D[1],p(1)) * \n FEHermite<1>::hermite_raw_shape(bases1D[2],p(2));\n break;\n\t\tcase 1:\n return coef *\n FEHermite<1>::hermite_raw_shape(bases1D[0],p(0)) * \n FEHermite<1>::hermite_raw_shape_deriv(bases1D[1],p(1)) * \n FEHermite<1>::hermite_raw_shape(bases1D[2],p(2));\n break;\n\t\tcase 2:\n return coef *\n FEHermite<1>::hermite_raw_shape(bases1D[0],p(0)) * \n FEHermite<1>::hermite_raw_shape(bases1D[1],p(1)) * \n FEHermite<1>::hermite_raw_shape_deriv(bases1D[2],p(2));\n break;\n }\n \n\t }\n\t default:\n std::cerr << \"ERROR: Unsupported element type!\" << std::endl;\n\t error();\n\t }\n }\n \/\/ by default throw an error\n default:\n std::cerr << \"ERROR: Unsupported polynomial order!\" << std::endl;\n error();\n }\n \n error();\n return 0.;\n}\n\n\n\ntemplate <>\nReal FE<3,HERMITE>::shape_second_deriv(const Elem* elem,\n const Order order,\n const unsigned int i,\n const unsigned int j,\n const Point& p)\n{\n assert (elem != NULL);\n\n hermite_compute_coefs(elem);\n\n const ElemType type = elem->type();\n \n switch (order)\n { \n \/\/ 3rd-order tricubic Hermite functions\n case THIRD:\n {\n\tswitch (type)\n\t {\n\t case HEX8:\n\t case HEX20:\n\t case HEX27:\n\t {\n\t assert (i<64);\n\n std::vector<unsigned int> bases1D;\n\n Real coef = FEHermite<1>::hermite_bases(bases1D, dxdxi, i, 3);\n\n switch (j) \/\/ Derivative type\n\t\t{\n\t\tcase 0:\n return coef *\n FEHermite<1>::hermite_raw_shape_second_deriv(bases1D[0],p(0)) * \n FEHermite<1>::hermite_raw_shape(bases1D[1],p(1)) * \n FEHermite<1>::hermite_raw_shape(bases1D[2],p(2));\n break;\n\t\tcase 1:\n return coef *\n FEHermite<1>::hermite_raw_shape_deriv(bases1D[0],p(0)) * \n FEHermite<1>::hermite_raw_shape_deriv(bases1D[1],p(1)) * \n FEHermite<1>::hermite_raw_shape(bases1D[2],p(2));\n break;\n\t\tcase 2:\n return coef *\n FEHermite<1>::hermite_raw_shape(bases1D[0],p(0)) * \n FEHermite<1>::hermite_raw_shape_second_deriv(bases1D[1],p(1)) * \n FEHermite<1>::hermite_raw_shape(bases1D[2],p(2));\n break;\n\t\tcase 3:\n return coef *\n FEHermite<1>::hermite_raw_shape_deriv(bases1D[0],p(0)) * \n FEHermite<1>::hermite_raw_shape(bases1D[1],p(1)) * \n FEHermite<1>::hermite_raw_shape_deriv(bases1D[2],p(2));\n break;\n\t\tcase 4:\n return coef *\n FEHermite<1>::hermite_raw_shape(bases1D[0],p(0)) * \n FEHermite<1>::hermite_raw_shape_deriv(bases1D[1],p(1)) * \n FEHermite<1>::hermite_raw_shape_deriv(bases1D[2],p(2));\n break;\n\t\tcase 5:\n return coef *\n FEHermite<1>::hermite_raw_shape(bases1D[0],p(0)) * \n FEHermite<1>::hermite_raw_shape(bases1D[1],p(1)) * \n FEHermite<1>::hermite_raw_shape_second_deriv(bases1D[2],p(2));\n break;\n }\n \n\t }\n\t default:\n std::cerr << \"ERROR: Unsupported element type!\" << std::endl;\n\t error();\n\t }\n }\n \/\/ by default throw an error\n default:\n std::cerr << \"ERROR: Unsupported polynomial order!\" << std::endl;\n error();\n }\n \n error();\n return 0.;\n}\n<|endoftext|>"} {"text":"<commit_before>\/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- vim:set ts=4 sw=4 sts=4 noet: *\/\n#ifdef HAVE_CONFIG_H\n#include \"config.h\"\n#endif\n\n#include <cstdio>\n#include <cstdlib>\n#include <cstring>\n#include <iostream>\n\n#define BOOST_FILESYSTEM_NO_DEPRECATED\n#include <boost\/filesystem.hpp>\n#include <boost\/scoped_array.hpp>\n#include <boost\/scoped_ptr.hpp>\n\n#include \"database.h\"\n#include \"db\/driver.h\"\n#include \"phml\/combine.h\"\n#include \"phml\/import.h\"\n#include \"sbml\/parser.h\"\n#include \"utf8path.h\"\n\n#include \"system.h\"\n\nusing std::cerr;\nusing std::endl;\nusing std::printf;\nusing std::sprintf;\nusing std::strcmp;\n\nnamespace {\n\nbool SaveFile(const char *uuid, const char *xml_file)\n{\n\tboost::scoped_array<char> db_file(new char[64]);\n\tsprintf(db_file.get(), \"%s.db\", uuid);\n\treturn SaveGivenFile(db_file.get(), xml_file);\n}\n\nint ParseFile(void *data, int argc, char **argv, char **names)\n{\n\t(void)data;\n\t(void)names;\n\tassert(argc == 1);\n\tboost::scoped_array<char> db_file(new char[64]); \/\/ large enough\n\tsprintf(db_file.get(), \"%s.db\", argv[0]);\n\tif (!ParseSbml(db_file.get())) return 1;\n\treturn 0;\n}\n\nint CombineFile(void *data, int argc, char **argv, char **names)\n{\n\t(void)names;\n\tassert(argc == 1);\n\tif (!Combine(argv[0],\n\t\t\t\t ((char **)data)[1],\n\t\t\t\t ((char **)data)[2],\n\t\t\t\t ((char **)data)[3],\n\t\t\t\t ((char **)data)[4],\n\t\t\t\t ((char **)data)[5]))\n\t\treturn 1;\n\treturn 0;\n}\n\nbool TouchFile(const char *file)\n{\n\tFILE *fp = std::fopen(file, \"w\");\n\tif (!fp) {\n\t\tcerr << \"failed to touch \" << file << endl;\n\t\treturn false;\n\t}\n\tstd::fclose(fp);\n\treturn true;\n}\n\nvoid Usage()\n{\n\tcerr << \"usage: flint-combineall DB NAME VALUE FUNCTION ODE\" << endl;\n}\n\n} \/\/ namespace\n\nint main(int argc, char *argv[])\n{\n\tif (argc == 2) {\n\t\tUsage();\n\t\tif (strcmp(\"-h\", argv[1]) == 0 || strcmp(\"--help\", argv[1]) == 0) {\n\t\t\tUsage();\n\t\t\treturn EXIT_SUCCESS;\n\t\t}\n\t\treturn EXIT_FAILURE;\n\t}\n\tif (argc != 6) {\n\t\tUsage();\n\t\treturn EXIT_FAILURE;\n\t}\n\n\tboost::scoped_ptr<db::Driver> driver(new db::Driver(argv[1]));\n\n\tsqlite3_stmt *stmt;\n\tint e = sqlite3_prepare_v2(driver->db(),\n\t\t\t\t\t\t\t \"SELECT m.module_id, i.type, i.ref FROM imports AS i LEFT JOIN modules AS m ON i.module_rowid = m.rowid\",\n\t\t\t\t\t\t\t -1, &stmt, NULL);\n\tif (e != SQLITE_OK) {\n\t\tcerr << \"failed to prepare statement: \" << e << endl;\n\t\treturn EXIT_FAILURE;\n\t}\n\n\tfor (e = sqlite3_step(stmt); e == SQLITE_ROW; e = sqlite3_step(stmt)) {\n\t\tconst unsigned char *uuid = sqlite3_column_text(stmt, 0);\n\t\tconst unsigned char *type = sqlite3_column_text(stmt, 1);\n\t\tconst unsigned char *ref = sqlite3_column_text(stmt, 2);\n\n\t\tif (strcmp((const char *)type, \"external\") == 0) {\n\t\t\tif (!SaveFile((const char *)uuid, (const char *)ref)) return EXIT_FAILURE;\n\t\t} else {\n\t\t\tif (!DumpImport(argv[1], (const char *)uuid)) return EXIT_FAILURE;\n\t\t\tboost::scoped_array<char> xml_file(new char[64]);\n\t\t\tsprintf(xml_file.get(), \"%s.xml\", uuid);\n\t\t\tboost::filesystem::path xml_path = boost::filesystem::absolute(xml_file.get());\n\t\t\tboost::scoped_array<char> xml_utf8(GetUtf8FromPath(xml_path));\n\t\t\tif (!SaveFile((const char *)uuid, xml_utf8.get())) return EXIT_FAILURE;\n\t\t}\n\t}\n\tif (e != SQLITE_DONE) {\n\t\tcerr << \"failed to step statement: \" << e << endl;\n\t\treturn EXIT_FAILURE;\n\t}\n\tsqlite3_finalize(stmt);\n\n\tchar *em;\n\te = sqlite3_exec(driver->db(), \"SELECT m.module_id FROM imports AS i LEFT JOIN modules AS m ON i.module_rowid = m.rowid\",\n\t\t\t\t\t ParseFile, NULL, &em);\n\tif (e != SQLITE_OK) {\n\t\tcerr << e << \": \" << em << endl;\n\t\tsqlite3_free(em);\n\t\treturn EXIT_FAILURE;\n\t}\n\n\tconst char *name_file = argv[2];\n\tconst char *value_file = argv[3];\n\tconst char *function_file = argv[4];\n\tconst char *ode_file = argv[5];\n\tif (!TouchFile(name_file)) return EXIT_FAILURE;\n\tif (!TouchFile(value_file)) return EXIT_FAILURE;\n\tif (!TouchFile(function_file)) return EXIT_FAILURE;\n\tif (!TouchFile(ode_file)) return EXIT_FAILURE;\n\n\te = sqlite3_exec(driver->db(), \"SELECT m.module_id FROM imports AS i LEFT JOIN modules AS m ON i.module_rowid = m.rowid\",\n\t\t\t\t\t CombineFile, argv, &em);\n\tif (e != SQLITE_OK) {\n\t\tcerr << e << \": \" << em << endl;\n\t\tsqlite3_free(em);\n\t\treturn EXIT_FAILURE;\n\t}\n\n\treturn EXIT_SUCCESS;\n}\n<commit_msg>do the same thing in a simpler and faster way<commit_after>\/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- vim:set ts=4 sw=4 sts=4 noet: *\/\n#ifdef HAVE_CONFIG_H\n#include \"config.h\"\n#endif\n\n#include <cstdio>\n#include <cstdlib>\n#include <cstring>\n#include <iostream>\n#include <string>\n#include <vector>\n\n#define BOOST_FILESYSTEM_NO_DEPRECATED\n#include <boost\/filesystem.hpp>\n#include <boost\/scoped_array.hpp>\n#include <boost\/scoped_ptr.hpp>\n\n#include \"database.h\"\n#include \"db\/driver.h\"\n#include \"phml\/combine.h\"\n#include \"phml\/import.h\"\n#include \"sbml\/parser.h\"\n#include \"utf8path.h\"\n\n#include \"system.h\"\n\nusing std::cerr;\nusing std::endl;\nusing std::printf;\nusing std::sprintf;\nusing std::strcmp;\n\nnamespace {\n\nbool SaveFile(const char *uuid, const char *xml_file)\n{\n\tboost::scoped_array<char> db_file(new char[64]);\n\tsprintf(db_file.get(), \"%s.db\", uuid);\n\treturn SaveGivenFile(db_file.get(), xml_file);\n}\n\nbool ParseFile(const char *uuid)\n{\n\tboost::scoped_array<char> db_file(new char[64]); \/\/ large enough\n\tsprintf(db_file.get(), \"%s.db\", uuid);\n\treturn ParseSbml(db_file.get());\n}\n\nbool TouchFile(const char *file)\n{\n\tFILE *fp = std::fopen(file, \"w\");\n\tif (!fp) {\n\t\tcerr << \"failed to touch \" << file << endl;\n\t\treturn false;\n\t}\n\tstd::fclose(fp);\n\treturn true;\n}\n\ntypedef std::vector<std::string> UuidVector;\n\nvoid Usage()\n{\n\tcerr << \"usage: flint-combineall DB NAME VALUE FUNCTION ODE\" << endl;\n}\n\n} \/\/ namespace\n\nint main(int argc, char *argv[])\n{\n\tif (argc == 2) {\n\t\tUsage();\n\t\tif (strcmp(\"-h\", argv[1]) == 0 || strcmp(\"--help\", argv[1]) == 0) {\n\t\t\tUsage();\n\t\t\treturn EXIT_SUCCESS;\n\t\t}\n\t\treturn EXIT_FAILURE;\n\t}\n\tif (argc != 6) {\n\t\tUsage();\n\t\treturn EXIT_FAILURE;\n\t}\n\n\tboost::scoped_ptr<db::Driver> driver(new db::Driver(argv[1]));\n\n\tUuidVector uv;\n\tsqlite3_stmt *stmt;\n\tint e = sqlite3_prepare_v2(driver->db(),\n\t\t\t\t\t\t\t \"SELECT m.module_id, i.type, i.ref FROM imports AS i LEFT JOIN modules AS m ON i.module_rowid = m.rowid\",\n\t\t\t\t\t\t\t -1, &stmt, NULL);\n\tif (e != SQLITE_OK) {\n\t\tcerr << \"failed to prepare statement: \" << e << endl;\n\t\treturn EXIT_FAILURE;\n\t}\n\n\tfor (e = sqlite3_step(stmt); e == SQLITE_ROW; e = sqlite3_step(stmt)) {\n\t\tconst unsigned char *uuid = sqlite3_column_text(stmt, 0);\n\t\tconst unsigned char *type = sqlite3_column_text(stmt, 1);\n\t\tconst unsigned char *ref = sqlite3_column_text(stmt, 2);\n\n\t\tif (strcmp((const char *)type, \"external\") == 0) {\n\t\t\tif (!SaveFile((const char *)uuid, (const char *)ref)) return EXIT_FAILURE;\n\t\t} else {\n\t\t\tif (!DumpImport(argv[1], (const char *)uuid)) return EXIT_FAILURE;\n\t\t\tboost::scoped_array<char> xml_file(new char[64]);\n\t\t\tsprintf(xml_file.get(), \"%s.xml\", uuid);\n\t\t\tboost::filesystem::path xml_path = boost::filesystem::absolute(xml_file.get());\n\t\t\tboost::scoped_array<char> xml_utf8(GetUtf8FromPath(xml_path));\n\t\t\tif (!SaveFile((const char *)uuid, xml_utf8.get())) return EXIT_FAILURE;\n\t\t}\n\t\tuv.push_back((const char *)uuid);\n\t}\n\tif (e != SQLITE_DONE) {\n\t\tcerr << \"failed to step statement: \" << e << endl;\n\t\treturn EXIT_FAILURE;\n\t}\n\tsqlite3_finalize(stmt);\n\n\tfor (UuidVector::const_iterator it=uv.begin();it!=uv.end();++it) {\n\t\tif (!ParseFile(it->c_str())) return EXIT_FAILURE;\n\t}\n\n\tfor (int i=2;i<6;i++) {\n\t\tif (!TouchFile(argv[i])) return EXIT_FAILURE;\n\t}\n\n\tfor (UuidVector::const_iterator it=uv.begin();it!=uv.end();++it) {\n\t\tif (!Combine(it->c_str(),\n\t\t\t\t\t argv[1],\n\t\t\t\t\t argv[2],\n\t\t\t\t\t argv[3],\n\t\t\t\t\t argv[4],\n\t\t\t\t\t argv[5]))\n\t\t\treturn EXIT_FAILURE;\n\t}\n\n\treturn EXIT_SUCCESS;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2014-2017 The Dash Core developers\n\/\/ Copyright (c) 2017-2018 The Syscoin Core developers\n\/\/ Distributed under the MIT\/X11 software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include <governancevalidators.h>\n\n#include <base58.h>\n#include <timedata.h>\n#include <tinyformat.h>\n#include <util\/strencodings.h>\n#include <validation.h>\n#include <key_io.h>\n#include <algorithm>\n\nconst size_t MAX_DATA_SIZE = 512;\nconst size_t MAX_NAME_SIZE = 40;\n\nCProposalValidator::CProposalValidator(const std::string& strHexData) :\n objJSON(UniValue::VOBJ),\n fJSONValid(false),\n strErrorMessages()\n{\n if(!strHexData.empty()) {\n ParseStrHexData(strHexData);\n }\n}\n\nvoid CProposalValidator::ParseStrHexData(const std::string& strHexData)\n{\n std::vector<unsigned char> v = ParseHex(strHexData);\n if (v.size() > MAX_DATA_SIZE) {\n strErrorMessages = strprintf(\"data exceeds %lu characters;\", MAX_DATA_SIZE);\n return;\n }\n ParseJSONData(std::string(v.begin(), v.end()));\n}\n\nbool CProposalValidator::Validate(bool fCheckExpiration)\n{\n if(!fJSONValid) {\n strErrorMessages += \"JSON parsing error;\";\n return false;\n }\n if(!ValidateName()) {\n strErrorMessages += \"Invalid name;\";\n return false;\n }\n if(!ValidateStartEndEpoch(fCheckExpiration)) {\n strErrorMessages += \"Invalid start:end range;\";\n return false;\n }\n if(!ValidatePaymentAmount()) {\n strErrorMessages += \"Invalid payment amount;\";\n return false;\n }\n if(!ValidatePaymentAddress()) {\n strErrorMessages += \"Invalid payment address;\";\n return false;\n }\n if(!ValidateURL()) {\n strErrorMessages += \"Invalid URL;\";\n return false;\n }\n return true;\n}\n\nbool CProposalValidator::ValidateName()\n{\n std::string strName;\n if(!GetDataValue(\"name\", strName)) {\n strErrorMessages += \"name field not found;\";\n return false;\n }\n\n if(strName.size() > MAX_NAME_SIZE) {\n strErrorMessages += strprintf(\"name exceeds %lu characters;\", MAX_NAME_SIZE);\n return false;\n }\n\n static const std::string strAllowedChars = \"-_abcdefghijklmnopqrstuvwxyz0123456789\";\n\n std::transform(strName.begin(), strName.end(), strName.begin(), ToLower);\n\n if(strName.find_first_not_of(strAllowedChars) != std::string::npos) {\n strErrorMessages += \"name contains invalid characters;\";\n return false;\n }\n\n return true;\n}\n\nbool CProposalValidator::ValidateStartEndEpoch(bool fCheckExpiration)\n{\n int64_t nStartEpoch = 0;\n int64_t nEndEpoch = 0;\n\n if(!GetDataValue(\"start_epoch\", nStartEpoch)) {\n strErrorMessages += \"start_epoch field not found;\";\n return false;\n }\n\n if(!GetDataValue(\"end_epoch\", nEndEpoch)) {\n strErrorMessages += \"end_epoch field not found;\";\n return false;\n }\n\n if(nEndEpoch <= nStartEpoch) {\n strErrorMessages += \"end_epoch <= start_epoch;\";\n return false;\n }\n\n if(fCheckExpiration && nEndEpoch <= GetAdjustedTime()) {\n strErrorMessages += \"expired;\";\n return false;\n }\n\n return true;\n}\n\nbool CProposalValidator::ValidatePaymentAmount()\n{\n double dValue = 0.0;\n\n if(!GetDataValue(\"payment_amount\", dValue)) {\n strErrorMessages += \"payment_amount field not found;\";\n return false;\n }\n\n if(dValue <= 0.0) {\n strErrorMessages += \"payment_amount is negative;\";\n return false;\n }\n\n \/\/ TODO: Should check for an amount which exceeds the budget but this is\n \/\/ currently difficult because start and end epochs are defined in terms of\n \/\/ clock time instead of block height.\n\n return true;\n}\n\nbool CProposalValidator::ValidatePaymentAddress()\n{\n std::string strPaymentAddress;\n\n if(!GetDataValue(\"payment_address\", strPaymentAddress)) {\n strErrorMessages += \"payment_address field not found;\";\n return false;\n }\n\n if(std::find_if(strPaymentAddress.begin(), strPaymentAddress.end(), IsSpace) != strPaymentAddress.end()) {\n strErrorMessages += \"payment_address can't have whitespaces;\";\n return false;\n }\n\n const CTxDestination &address = DecodeDestination(strPaymentAddress);\n if(!IsValidDestination(address)) {\n strErrorMessages += \"payment_address is invalid;\";\n return false;\n }\n\n if(boost::get<ScriptHash>(&address) || boost::get<WitnessV0ScriptHash>(&address)) {\n strErrorMessages += \"script addresses are not supported;\";\n return false;\n }\n\n return true;\n}\n\nbool CProposalValidator::ValidateURL()\n{\n std::string strURL;\n if(!GetDataValue(\"url\", strURL)) {\n strErrorMessages += \"url field not found;\";\n return false;\n }\n\n if(std::find_if(strURL.begin(), strURL.end(), IsSpace) != strURL.end()) {\n strErrorMessages += \"url can't have whitespaces;\";\n return false;\n }\n\n if(strURL.size() < 4U) {\n strErrorMessages += \"url too short;\";\n return false;\n }\n\n if(!CheckURL(strURL)) {\n strErrorMessages += \"url invalid;\";\n return false;\n }\n\n return true;\n}\n\nvoid CProposalValidator::ParseJSONData(const std::string& strJSONData)\n{\n fJSONValid = false;\n\n if(strJSONData.empty()) {\n return;\n }\n\n try {\n UniValue obj(UniValue::VOBJ);\n\n obj.read(strJSONData);\n\n if (obj.isObject()) {\n objJSON = obj;\n } else {\n std::vector<UniValue> arr1 = obj.getValues();\n std::vector<UniValue> arr2 = arr1.at(0).getValues();\n objJSON = arr2.at(1);\n }\n\n fJSONValid = true;\n }\n catch(std::exception& e) {\n strErrorMessages += std::string(e.what()) + std::string(\";\");\n }\n catch(...) {\n strErrorMessages += \"Unknown exception;\";\n }\n}\n\nbool CProposalValidator::GetDataValue(const std::string& strKey, std::string& strValueRet)\n{\n bool fOK = false;\n try {\n strValueRet = objJSON[strKey].get_str();\n fOK = true;\n }\n catch(std::exception& e) {\n strErrorMessages += std::string(e.what()) + std::string(\";\");\n }\n catch(...) {\n strErrorMessages += \"Unknown exception;\";\n }\n return fOK;\n}\n\nbool CProposalValidator::GetDataValue(const std::string& strKey, int64_t& nValueRet)\n{\n bool fOK = false;\n try {\n const UniValue uValue = objJSON[strKey];\n switch(uValue.getType()) {\n case UniValue::VNUM:\n nValueRet = uValue.get_int64();\n fOK = true;\n break;\n default:\n break;\n }\n }\n catch(std::exception& e) {\n strErrorMessages += std::string(e.what()) + std::string(\";\");\n }\n catch(...) {\n strErrorMessages += \"Unknown exception;\";\n }\n return fOK;\n}\n\nbool CProposalValidator::GetDataValue(const std::string& strKey, double& dValueRet)\n{\n bool fOK = false;\n try {\n const UniValue uValue = objJSON[strKey];\n switch(uValue.getType()) {\n case UniValue::VNUM:\n dValueRet = uValue.get_real();\n fOK = true;\n break;\n default:\n break;\n }\n }\n catch(std::exception& e) {\n strErrorMessages += std::string(e.what()) + std::string(\";\");\n }\n catch(...) {\n strErrorMessages += \"Unknown exception;\";\n }\n return fOK;\n}\n\n\/*\n The purpose of this function is to replicate the behavior of the\n Python urlparse function used by sentinel (urlparse.py). This function\n should return false whenever urlparse raises an exception and true\n otherwise.\n *\/\nbool CProposalValidator::CheckURL(const std::string& strURLIn)\n{\n std::string strRest(strURLIn);\n std::string::size_type nPos = strRest.find(':');\n\n if(nPos != std::string::npos) {\n \/\/std::string strSchema = strRest.substr(0,nPos);\n\n if(nPos < strRest.size()) {\n strRest = strRest.substr(nPos + 1);\n }\n else {\n strRest = \"\";\n }\n }\n\n \/\/ Process netloc\n if((strRest.size() > 2) && (strRest.substr(0,2) == \"\/\/\")) {\n static const std::string strNetlocDelimiters = \"\/?#\";\n\n strRest = strRest.substr(2);\n\n std::string::size_type nPos2 = strRest.find_first_of(strNetlocDelimiters);\n\n std::string strNetloc = strRest.substr(0,nPos2);\n\n if((strNetloc.find('[') != std::string::npos) && (strNetloc.find(']') == std::string::npos)) {\n return false;\n }\n\n if((strNetloc.find(']') != std::string::npos) && (strNetloc.find('[') == std::string::npos)) {\n return false;\n }\n }\n\n return true;\n}\n<commit_msg>fix tolower<commit_after>\/\/ Copyright (c) 2014-2017 The Dash Core developers\n\/\/ Copyright (c) 2017-2018 The Syscoin Core developers\n\/\/ Distributed under the MIT\/X11 software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include <governancevalidators.h>\n\n#include <base58.h>\n#include <timedata.h>\n#include <tinyformat.h>\n#include <util\/strencodings.h>\n#include <validation.h>\n#include <key_io.h>\n#include <algorithm>\n\nconst size_t MAX_DATA_SIZE = 512;\nconst size_t MAX_NAME_SIZE = 40;\n\nCProposalValidator::CProposalValidator(const std::string& strHexData) :\n objJSON(UniValue::VOBJ),\n fJSONValid(false),\n strErrorMessages()\n{\n if(!strHexData.empty()) {\n ParseStrHexData(strHexData);\n }\n}\n\nvoid CProposalValidator::ParseStrHexData(const std::string& strHexData)\n{\n std::vector<unsigned char> v = ParseHex(strHexData);\n if (v.size() > MAX_DATA_SIZE) {\n strErrorMessages = strprintf(\"data exceeds %lu characters;\", MAX_DATA_SIZE);\n return;\n }\n ParseJSONData(std::string(v.begin(), v.end()));\n}\n\nbool CProposalValidator::Validate(bool fCheckExpiration)\n{\n if(!fJSONValid) {\n strErrorMessages += \"JSON parsing error;\";\n return false;\n }\n if(!ValidateName()) {\n strErrorMessages += \"Invalid name;\";\n return false;\n }\n if(!ValidateStartEndEpoch(fCheckExpiration)) {\n strErrorMessages += \"Invalid start:end range;\";\n return false;\n }\n if(!ValidatePaymentAmount()) {\n strErrorMessages += \"Invalid payment amount;\";\n return false;\n }\n if(!ValidatePaymentAddress()) {\n strErrorMessages += \"Invalid payment address;\";\n return false;\n }\n if(!ValidateURL()) {\n strErrorMessages += \"Invalid URL;\";\n return false;\n }\n return true;\n}\n\nbool CProposalValidator::ValidateName()\n{\n std::string strName;\n if(!GetDataValue(\"name\", strName)) {\n strErrorMessages += \"name field not found;\";\n return false;\n }\n\n if(strName.size() > MAX_NAME_SIZE) {\n strErrorMessages += strprintf(\"name exceeds %lu characters;\", MAX_NAME_SIZE);\n return false;\n }\n\n static const std::string strAllowedChars = \"-_abcdefghijklmnopqrstuvwxyz0123456789\";\n std::string strNameIn = ToLower(strName);\n\n if(strNameIn.find_first_not_of(strAllowedChars) != std::string::npos) {\n strErrorMessages += \"name contains invalid characters;\";\n return false;\n }\n\n return true;\n}\n\nbool CProposalValidator::ValidateStartEndEpoch(bool fCheckExpiration)\n{\n int64_t nStartEpoch = 0;\n int64_t nEndEpoch = 0;\n\n if(!GetDataValue(\"start_epoch\", nStartEpoch)) {\n strErrorMessages += \"start_epoch field not found;\";\n return false;\n }\n\n if(!GetDataValue(\"end_epoch\", nEndEpoch)) {\n strErrorMessages += \"end_epoch field not found;\";\n return false;\n }\n\n if(nEndEpoch <= nStartEpoch) {\n strErrorMessages += \"end_epoch <= start_epoch;\";\n return false;\n }\n\n if(fCheckExpiration && nEndEpoch <= GetAdjustedTime()) {\n strErrorMessages += \"expired;\";\n return false;\n }\n\n return true;\n}\n\nbool CProposalValidator::ValidatePaymentAmount()\n{\n double dValue = 0.0;\n\n if(!GetDataValue(\"payment_amount\", dValue)) {\n strErrorMessages += \"payment_amount field not found;\";\n return false;\n }\n\n if(dValue <= 0.0) {\n strErrorMessages += \"payment_amount is negative;\";\n return false;\n }\n\n \/\/ TODO: Should check for an amount which exceeds the budget but this is\n \/\/ currently difficult because start and end epochs are defined in terms of\n \/\/ clock time instead of block height.\n\n return true;\n}\n\nbool CProposalValidator::ValidatePaymentAddress()\n{\n std::string strPaymentAddress;\n\n if(!GetDataValue(\"payment_address\", strPaymentAddress)) {\n strErrorMessages += \"payment_address field not found;\";\n return false;\n }\n\n if(std::find_if(strPaymentAddress.begin(), strPaymentAddress.end(), IsSpace) != strPaymentAddress.end()) {\n strErrorMessages += \"payment_address can't have whitespaces;\";\n return false;\n }\n\n const CTxDestination &address = DecodeDestination(strPaymentAddress);\n if(!IsValidDestination(address)) {\n strErrorMessages += \"payment_address is invalid;\";\n return false;\n }\n\n if(boost::get<ScriptHash>(&address) || boost::get<WitnessV0ScriptHash>(&address)) {\n strErrorMessages += \"script addresses are not supported;\";\n return false;\n }\n\n return true;\n}\n\nbool CProposalValidator::ValidateURL()\n{\n std::string strURL;\n if(!GetDataValue(\"url\", strURL)) {\n strErrorMessages += \"url field not found;\";\n return false;\n }\n\n if(std::find_if(strURL.begin(), strURL.end(), IsSpace) != strURL.end()) {\n strErrorMessages += \"url can't have whitespaces;\";\n return false;\n }\n\n if(strURL.size() < 4U) {\n strErrorMessages += \"url too short;\";\n return false;\n }\n\n if(!CheckURL(strURL)) {\n strErrorMessages += \"url invalid;\";\n return false;\n }\n\n return true;\n}\n\nvoid CProposalValidator::ParseJSONData(const std::string& strJSONData)\n{\n fJSONValid = false;\n\n if(strJSONData.empty()) {\n return;\n }\n\n try {\n UniValue obj(UniValue::VOBJ);\n\n obj.read(strJSONData);\n\n if (obj.isObject()) {\n objJSON = obj;\n } else {\n std::vector<UniValue> arr1 = obj.getValues();\n std::vector<UniValue> arr2 = arr1.at(0).getValues();\n objJSON = arr2.at(1);\n }\n\n fJSONValid = true;\n }\n catch(std::exception& e) {\n strErrorMessages += std::string(e.what()) + std::string(\";\");\n }\n catch(...) {\n strErrorMessages += \"Unknown exception;\";\n }\n}\n\nbool CProposalValidator::GetDataValue(const std::string& strKey, std::string& strValueRet)\n{\n bool fOK = false;\n try {\n strValueRet = objJSON[strKey].get_str();\n fOK = true;\n }\n catch(std::exception& e) {\n strErrorMessages += std::string(e.what()) + std::string(\";\");\n }\n catch(...) {\n strErrorMessages += \"Unknown exception;\";\n }\n return fOK;\n}\n\nbool CProposalValidator::GetDataValue(const std::string& strKey, int64_t& nValueRet)\n{\n bool fOK = false;\n try {\n const UniValue uValue = objJSON[strKey];\n switch(uValue.getType()) {\n case UniValue::VNUM:\n nValueRet = uValue.get_int64();\n fOK = true;\n break;\n default:\n break;\n }\n }\n catch(std::exception& e) {\n strErrorMessages += std::string(e.what()) + std::string(\";\");\n }\n catch(...) {\n strErrorMessages += \"Unknown exception;\";\n }\n return fOK;\n}\n\nbool CProposalValidator::GetDataValue(const std::string& strKey, double& dValueRet)\n{\n bool fOK = false;\n try {\n const UniValue uValue = objJSON[strKey];\n switch(uValue.getType()) {\n case UniValue::VNUM:\n dValueRet = uValue.get_real();\n fOK = true;\n break;\n default:\n break;\n }\n }\n catch(std::exception& e) {\n strErrorMessages += std::string(e.what()) + std::string(\";\");\n }\n catch(...) {\n strErrorMessages += \"Unknown exception;\";\n }\n return fOK;\n}\n\n\/*\n The purpose of this function is to replicate the behavior of the\n Python urlparse function used by sentinel (urlparse.py). This function\n should return false whenever urlparse raises an exception and true\n otherwise.\n *\/\nbool CProposalValidator::CheckURL(const std::string& strURLIn)\n{\n std::string strRest(strURLIn);\n std::string::size_type nPos = strRest.find(':');\n\n if(nPos != std::string::npos) {\n \/\/std::string strSchema = strRest.substr(0,nPos);\n\n if(nPos < strRest.size()) {\n strRest = strRest.substr(nPos + 1);\n }\n else {\n strRest = \"\";\n }\n }\n\n \/\/ Process netloc\n if((strRest.size() > 2) && (strRest.substr(0,2) == \"\/\/\")) {\n static const std::string strNetlocDelimiters = \"\/?#\";\n\n strRest = strRest.substr(2);\n\n std::string::size_type nPos2 = strRest.find_first_of(strNetlocDelimiters);\n\n std::string strNetloc = strRest.substr(0,nPos2);\n\n if((strNetloc.find('[') != std::string::npos) && (strNetloc.find(']') == std::string::npos)) {\n return false;\n }\n\n if((strNetloc.find(']') != std::string::npos) && (strNetloc.find('[') == std::string::npos)) {\n return false;\n }\n }\n\n return true;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\r\n * fiberrenderer.cpp\r\n *\r\n * Created on: 28.12.2012\r\n * Author: Ralph\r\n *\/\r\n#include \"fiberrenderer.h\"\r\n#include \"fiberrendererthread.h\"\r\n\r\n#include \"glfunctions.h\"\r\n\r\n#include \"..\/..\/data\/enums.h\"\r\n\r\n#include <QtOpenGL\/QGLShaderProgram>\r\n#include <QtCore\/QDebug>\r\n\r\nFiberRenderer::FiberRenderer( QAbstractItemModel* roiModel, QVector< QVector< float > >& data ) :\r\n ObjectRenderer(),\r\n m_roiModel( roiModel ),\r\n vboIds( new GLuint[ 2 ] ),\r\n m_data( data ),\r\n m_numLines( data.size() ),\r\n m_numPoints( 0 ),\r\n m_isInitialized( false ),\r\n m_colorMode( 0 )\r\n{\r\n m_boxMin.resize( 3 );\r\n m_boxMax.resize( 3 );\r\n\r\n connect( m_roiModel, SIGNAL( dataChanged( QModelIndex, QModelIndex ) ), this, SLOT( roiChanged( QModelIndex, QModelIndex ) ) );\r\n connect( m_roiModel, SIGNAL( rowsInserted( QModelIndex, int, int ) ), this, SLOT( roiInserted( QModelIndex, int, int ) ) );\r\n connect( m_roiModel, SIGNAL( rowsRemoved( QModelIndex, int, int ) ), this, SLOT( roiDeleted( QModelIndex, int, int ) ) );\r\n\r\n m_rootfield.resize( m_numLines );\r\n for ( int i = 0; i < m_numLines; ++i )\r\n {\r\n m_rootfield[i] = true;\r\n }\r\n}\r\n\r\nFiberRenderer::~FiberRenderer()\r\n{\r\n glDeleteBuffers(1, &( vboIds[ 0 ] ) );\r\n glDeleteBuffers(1, &( vboIds[ 1 ] ) );\r\n}\r\n\r\nvoid FiberRenderer::init()\r\n{\r\n glGenBuffers( 2, vboIds );\r\n}\r\n\r\nvoid FiberRenderer::draw( QMatrix4x4 mvp_matrix, QMatrix4x4 mv_matrixInvert )\r\n{\r\n GLFunctions::getShader( \"fiber\" )->bind();\r\n \/\/ Set modelview-projection matrix\r\n GLFunctions::getShader( \"fiber\" )->setUniformValue( \"mvp_matrix\", mvp_matrix );\r\n GLFunctions::getShader( \"fiber\" )->setUniformValue( \"mv_matrixInvert\", mv_matrixInvert );\r\n GLFunctions::getShader( \"fiber\" )->setUniformValue( \"u_colorMode\", m_colorMode );\r\n\r\n initGeometry();\r\n\r\n glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, vboIds[ 0 ] );\r\n glBindBuffer( GL_ARRAY_BUFFER, vboIds[ 1 ] );\r\n setShaderVars();\r\n\r\n for ( int i = 0; i < m_data.size(); ++i )\r\n {\r\n if ( m_rootfield[i] )\r\n {\r\n glDrawArrays( GL_LINE_STRIP, m_startIndexes[i], m_pointsPerLine[i] );\r\n }\r\n }\r\n\r\n glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, 0 );\r\n glBindBuffer( GL_ARRAY_BUFFER, 0 );\r\n}\r\n\r\nvoid FiberRenderer::setupTextures()\r\n{\r\n}\r\n\r\nvoid FiberRenderer::setShaderVars()\r\n{\r\n GLFunctions::setShaderVars( \"fiber\", model() );\r\n}\r\n\r\nvoid FiberRenderer::initGeometry()\r\n{\r\n if ( m_isInitialized )\r\n {\r\n return;\r\n }\r\n qDebug() << \"create fiber vbo's...\";\r\n int numThreads = QThread::idealThreadCount();\r\n\r\n QVector<FiberRendererThread*> threads;\r\n \/\/ create threads\r\n for ( int i = 0; i < numThreads; ++i )\r\n {\r\n threads.push_back( new FiberRendererThread( m_data, i ) );\r\n }\r\n\r\n \/\/ run threads\r\n for ( int i = 0; i < numThreads; ++i )\r\n {\r\n threads[i]->start();\r\n }\r\n\r\n \/\/ wait for all threads to finish\r\n for ( int i = 0; i < numThreads; ++i )\r\n {\r\n threads[i]->wait();\r\n }\r\n\r\n QVector<float> verts;\r\n \/\/ combine verts from all threads\r\n for ( int i = 0; i < numThreads; ++i )\r\n {\r\n verts += *( threads[i]->getVerts() );\r\n }\r\n\r\n for ( int i = 0; i < numThreads; ++i )\r\n {\r\n delete threads[i];\r\n }\r\n\r\n glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, vboIds[ 1 ] );\r\n glBufferData( GL_ELEMENT_ARRAY_BUFFER, verts.size() * sizeof(GLfloat), verts.data(), GL_STATIC_DRAW );\r\n\r\n m_pointsPerLine.resize( m_data.size() );\r\n m_startIndexes.resize( m_data.size() );\r\n\r\n int currentStart = 0;\r\n for ( int i = 0; i < m_data.size(); ++i )\r\n {\r\n m_pointsPerLine[i] = m_data[i].size() \/ 3;\r\n m_startIndexes[i] = currentStart;\r\n currentStart += m_pointsPerLine[i];\r\n }\r\n qDebug() << \"create fiber vbo's done\";\r\n\r\n qDebug() << \"start creating kdtree\";\r\n m_numPoints = verts.size() \/ 9;\r\n m_kdVerts.reserve( m_numPoints * 3 );\r\n m_reverseIndexes.reserve( m_numPoints );\r\n for ( int i = 0; i < m_numLines; ++i )\r\n {\r\n for( int k = 0; k < m_data[i].size() \/ 3; ++k )\r\n {\r\n m_kdVerts.push_back( m_data[i][k * 3 ] );\r\n m_kdVerts.push_back( m_data[i][k * 3 + 1] );\r\n m_kdVerts.push_back( m_data[i][k * 3 + 2] );\r\n m_reverseIndexes.push_back( i );\r\n }\r\n }\r\n m_kdTree = new KdTree( m_numPoints, m_kdVerts.data() );\r\n qDebug() << \"end creating kdtree\";\r\n\r\n updatePresentRois();\r\n\r\n m_isInitialized = true;\r\n}\r\n\r\nvoid FiberRenderer::setRenderParams( int colorMode )\r\n{\r\n m_colorMode = colorMode;\r\n}\r\n\r\nvoid FiberRenderer::updatePresentRois()\r\n{\r\n int numBranches = m_roiModel->rowCount( QModelIndex() );\r\n\r\n for ( int i = 0; i < numBranches; ++i )\r\n {\r\n QList<QVector<bool> >newBranch;\r\n QVector<bool>newLeaf( m_numLines );\r\n newBranch.push_back( newLeaf );\r\n m_branchfields.push_back( newLeaf );\r\n m_bitfields.push_back( newBranch );\r\n updateBox( m_bitfields.size() - 1, 0 );\r\n\r\n int leafCount = m_roiModel->rowCount( createIndex( i, 0, 0 ) );\r\n\r\n for ( int k = 0; k < leafCount; ++k )\r\n {\r\n \/\/ inserted child roi\r\n QVector<bool>newLeaf( m_numLines );\r\n m_bitfields[i].push_back( newLeaf );\r\n updateBox( i, k + 1 );\r\n }\r\n }\r\n}\r\n\r\nvoid FiberRenderer::roiChanged( const QModelIndex &topLeft, const QModelIndex &bottomRight )\r\n{\r\n if ( topLeft.row() == -1 ) return;\r\n qDebug() << \"roi changed\" << topLeft.row() << topLeft.column() << topLeft.internalId();\r\n int branch = 0;\r\n int pos = 0;\r\n if ( topLeft.internalId() == -1 )\r\n {\r\n \/\/ top level box\r\n branch = topLeft.row();\r\n }\r\n else\r\n {\r\n \/\/ child box\r\n branch = topLeft.internalId();\r\n pos = topLeft.row() + 1;\r\n }\r\n updateBox( branch, pos );\r\n\r\n}\r\n\r\nvoid FiberRenderer::roiInserted( const QModelIndex &parent, int start, int end )\r\n{\r\n \/\/qDebug() << \"roi inserted\" << parent.row() << start << end;\r\n if ( parent.row() == -1 )\r\n {\r\n \/\/ inserted top level roi\r\n QList<QVector<bool> >newBranch;\r\n QVector<bool>newLeaf( m_numLines );\r\n newBranch.push_back( newLeaf );\r\n m_branchfields.push_back( newLeaf );\r\n m_bitfields.push_back( newBranch );\r\n updateBox( m_bitfields.size() - 1, 0 );\r\n }\r\n else\r\n {\r\n \/\/ inserted child roi\r\n QVector<bool>newLeaf( m_numLines );\r\n m_bitfields[parent.row()].push_back( newLeaf );\r\n updateBox( parent.row(), m_bitfields[parent.row()].size() - 1 );\r\n }\r\n}\r\n\r\nvoid FiberRenderer::roiDeleted( const QModelIndex &parent, int start, int end )\r\n{\r\n qDebug() << \"roi deleted\" << parent.row() << start << end;\r\n if ( parent.row() == -1 )\r\n {\r\n m_bitfields.removeAt( start );\r\n m_branchfields.removeAt( start );\r\n updateRoot();\r\n }\r\n else\r\n {\r\n m_bitfields[parent.row()].removeAt( start + 1 );\r\n updateBranch( parent.row() );\r\n }\r\n}\r\n\r\nQModelIndex FiberRenderer::createIndex( int branch, int pos, int column )\r\n{\r\n int row;\r\n QModelIndex parent;\r\n if ( pos == 0 )\r\n {\r\n row = branch;\r\n }\r\n else\r\n {\r\n row = pos - 1;\r\n parent = m_roiModel->index( branch, 0 );\r\n }\r\n return m_roiModel->index( row, column, parent );\r\n}\r\n\r\nvoid FiberRenderer::updateBox( int branch, int pos )\r\n{\r\n \/\/qDebug() << \"update box\" << branch << pos;\r\n float x, y, z, dx, dy, dz;\r\n\r\n if ( m_roiModel->data( createIndex( branch, pos, (int)Fn::ROI::ACTIVE ), Qt::DisplayRole ).toBool() )\r\n {\r\n x = m_roiModel->data( createIndex( branch, pos, (int)Fn::ROI::X ), Qt::DisplayRole ).toFloat();\r\n y = m_roiModel->data( createIndex( branch, pos, (int)Fn::ROI::Y ), Qt::DisplayRole ).toFloat();\r\n z = m_roiModel->data( createIndex( branch, pos, (int)Fn::ROI::Z ), Qt::DisplayRole ).toFloat();\r\n dx = m_roiModel->data( createIndex( branch, pos, (int)Fn::ROI::DX ), Qt::DisplayRole ).toFloat();\r\n dy = m_roiModel->data( createIndex( branch, pos, (int)Fn::ROI::DY ), Qt::DisplayRole ).toFloat();\r\n dz = m_roiModel->data( createIndex( branch, pos, (int)Fn::ROI::DZ ), Qt::DisplayRole ).toFloat();\r\n m_boxMin[0] = x - dx \/ 2;\r\n m_boxMax[0] = x + dx \/ 2;\r\n m_boxMin[1] = y - dy \/ 2;\r\n m_boxMax[1] = y + dy \/ 2;\r\n m_boxMin[2] = z - dz \/ 2;\r\n m_boxMax[2] = z + dz \/ 2;\r\n\r\n for ( int i = 0; i < m_numLines; ++i )\r\n {\r\n m_bitfields[branch][pos][i] = false;\r\n }\r\n boxTest( m_bitfields[branch][pos], 0, m_numPoints - 1, 0 );\r\n }\r\n else\r\n {\r\n for ( int i = 0; i < m_numLines; ++i )\r\n {\r\n m_bitfields[branch][pos][i] = true;\r\n }\r\n }\r\n\r\n updateBranch( branch );\r\n if ( m_isInitialized )\r\n {\r\n m_roiModel->setData( createIndex( branch, pos, (int)Fn::ROI::UPDATED ), true, Qt::DisplayRole );\r\n }\r\n}\r\n\r\nvoid FiberRenderer::boxTest( QVector<bool>& workfield, int left, int right, int axis )\r\n{\r\n \/\/ abort condition\r\n if ( left > right )\r\n return;\r\n\r\n int root = left + ( ( right - left ) \/ 2 );\r\n int axis1 = ( axis + 1 ) % 3;\r\n int pointIndex = m_kdTree->m_tree[root] * 3;\r\n\r\n if ( m_kdVerts[pointIndex + axis] < m_boxMin[axis] )\r\n {\r\n boxTest( workfield, root + 1, right, axis1 );\r\n }\r\n else if ( m_kdVerts[pointIndex + axis] > m_boxMax[axis] )\r\n {\r\n boxTest( workfield, left, root - 1, axis1 );\r\n }\r\n else\r\n {\r\n int axis2 = ( axis + 2 ) % 3;\r\n if ( m_kdVerts[pointIndex + axis1] <= m_boxMax[axis1] && m_kdVerts[pointIndex + axis1]\r\n >= m_boxMin[axis1] && m_kdVerts[pointIndex + axis2] <= m_boxMax[axis2]\r\n && m_kdVerts[pointIndex + axis2] >= m_boxMin[axis2] )\r\n {\r\n workfield[m_reverseIndexes[ m_kdTree->m_tree[root] ]] = true;\r\n }\r\n boxTest( workfield, left, root - 1, axis1 );\r\n boxTest( workfield, root + 1, right, axis1 );\r\n }\r\n}\r\n\r\n\r\nvoid FiberRenderer::updateBranch( int branch )\r\n{\r\n \/\/qDebug() << \"update branch\" << branch;\r\n int current = 0;\r\n\r\n bool neg = m_roiModel->data( createIndex( branch, current, (int)Fn::ROI::NEG ), Qt::DisplayRole ).toBool();\r\n if ( neg )\r\n {\r\n for ( int k = 0; k < m_numLines; ++k )\r\n {\r\n m_branchfields[branch][k] = !m_bitfields[branch][current][k];\r\n }\r\n }\r\n else\r\n {\r\n for ( int k = 0; k < m_numLines; ++k )\r\n {\r\n m_branchfields[branch][k] = m_bitfields[branch][current][k];\r\n }\r\n }\r\n ++current;\r\n\r\n while ( current < m_bitfields[branch].size() )\r\n {\r\n if ( m_roiModel->data( createIndex( branch, current, (int)Fn::ROI::ACTIVE ), Qt::DisplayRole ).toBool() )\r\n {\r\n bool neg = m_roiModel->data( createIndex( branch, current, (int)Fn::ROI::NEG ), Qt::DisplayRole ).toBool();\r\n if ( neg )\r\n {\r\n for ( int k = 0; k < m_numLines; ++k )\r\n {\r\n m_branchfields[branch][k] &= !m_bitfields[branch][current][k];\r\n }\r\n }\r\n else\r\n {\r\n for ( int k = 0; k < m_numLines; ++k )\r\n {\r\n m_branchfields[branch][k] &= m_bitfields[branch][current][k];\r\n }\r\n }\r\n ++current;\r\n }\r\n else\r\n {\r\n ++current;\r\n }\r\n }\r\n updateRoot();\r\n}\r\n\r\nvoid FiberRenderer::updateRoot()\r\n{\r\n qDebug() << \"update root\";\r\n if ( m_branchfields.size() > 0 )\r\n {\r\n for ( int i = 0; i < m_numLines; ++i )\r\n {\r\n m_rootfield[i] = false;\r\n }\r\n\r\n for ( int i = 0; i < m_branchfields.size(); ++i )\r\n {\r\n if ( m_roiModel->data( createIndex( i, 0, (int)Fn::ROI::ACTIVE ), Qt::DisplayRole ).toBool() )\r\n {\r\n for ( int k = 0; k < m_numLines; ++k )\r\n {\r\n m_rootfield[k] |= m_branchfields[i][k];\r\n }\r\n }\r\n }\r\n }\r\n else\r\n {\r\n for ( int i = 0; i < m_numLines; ++i )\r\n {\r\n m_rootfield[i] = true;\r\n }\r\n }\r\n}\r\n\r\n<commit_msg>removed debug output<commit_after>\/*\r\n * fiberrenderer.cpp\r\n *\r\n * Created on: 28.12.2012\r\n * Author: Ralph\r\n *\/\r\n#include \"fiberrenderer.h\"\r\n#include \"fiberrendererthread.h\"\r\n\r\n#include \"glfunctions.h\"\r\n\r\n#include \"..\/..\/data\/enums.h\"\r\n\r\n#include <QtOpenGL\/QGLShaderProgram>\r\n#include <QtCore\/QDebug>\r\n\r\nFiberRenderer::FiberRenderer( QAbstractItemModel* roiModel, QVector< QVector< float > >& data ) :\r\n ObjectRenderer(),\r\n m_roiModel( roiModel ),\r\n vboIds( new GLuint[ 2 ] ),\r\n m_data( data ),\r\n m_numLines( data.size() ),\r\n m_numPoints( 0 ),\r\n m_isInitialized( false ),\r\n m_colorMode( 0 )\r\n{\r\n m_boxMin.resize( 3 );\r\n m_boxMax.resize( 3 );\r\n\r\n connect( m_roiModel, SIGNAL( dataChanged( QModelIndex, QModelIndex ) ), this, SLOT( roiChanged( QModelIndex, QModelIndex ) ) );\r\n connect( m_roiModel, SIGNAL( rowsInserted( QModelIndex, int, int ) ), this, SLOT( roiInserted( QModelIndex, int, int ) ) );\r\n connect( m_roiModel, SIGNAL( rowsRemoved( QModelIndex, int, int ) ), this, SLOT( roiDeleted( QModelIndex, int, int ) ) );\r\n\r\n m_rootfield.resize( m_numLines );\r\n for ( int i = 0; i < m_numLines; ++i )\r\n {\r\n m_rootfield[i] = true;\r\n }\r\n}\r\n\r\nFiberRenderer::~FiberRenderer()\r\n{\r\n glDeleteBuffers(1, &( vboIds[ 0 ] ) );\r\n glDeleteBuffers(1, &( vboIds[ 1 ] ) );\r\n}\r\n\r\nvoid FiberRenderer::init()\r\n{\r\n glGenBuffers( 2, vboIds );\r\n}\r\n\r\nvoid FiberRenderer::draw( QMatrix4x4 mvp_matrix, QMatrix4x4 mv_matrixInvert )\r\n{\r\n GLFunctions::getShader( \"fiber\" )->bind();\r\n \/\/ Set modelview-projection matrix\r\n GLFunctions::getShader( \"fiber\" )->setUniformValue( \"mvp_matrix\", mvp_matrix );\r\n GLFunctions::getShader( \"fiber\" )->setUniformValue( \"mv_matrixInvert\", mv_matrixInvert );\r\n GLFunctions::getShader( \"fiber\" )->setUniformValue( \"u_colorMode\", m_colorMode );\r\n\r\n initGeometry();\r\n\r\n glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, vboIds[ 0 ] );\r\n glBindBuffer( GL_ARRAY_BUFFER, vboIds[ 1 ] );\r\n setShaderVars();\r\n\r\n for ( int i = 0; i < m_data.size(); ++i )\r\n {\r\n if ( m_rootfield[i] )\r\n {\r\n glDrawArrays( GL_LINE_STRIP, m_startIndexes[i], m_pointsPerLine[i] );\r\n }\r\n }\r\n\r\n glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, 0 );\r\n glBindBuffer( GL_ARRAY_BUFFER, 0 );\r\n}\r\n\r\nvoid FiberRenderer::setupTextures()\r\n{\r\n}\r\n\r\nvoid FiberRenderer::setShaderVars()\r\n{\r\n GLFunctions::setShaderVars( \"fiber\", model() );\r\n}\r\n\r\nvoid FiberRenderer::initGeometry()\r\n{\r\n if ( m_isInitialized )\r\n {\r\n return;\r\n }\r\n qDebug() << \"create fiber vbo's...\";\r\n int numThreads = QThread::idealThreadCount();\r\n\r\n QVector<FiberRendererThread*> threads;\r\n \/\/ create threads\r\n for ( int i = 0; i < numThreads; ++i )\r\n {\r\n threads.push_back( new FiberRendererThread( m_data, i ) );\r\n }\r\n\r\n \/\/ run threads\r\n for ( int i = 0; i < numThreads; ++i )\r\n {\r\n threads[i]->start();\r\n }\r\n\r\n \/\/ wait for all threads to finish\r\n for ( int i = 0; i < numThreads; ++i )\r\n {\r\n threads[i]->wait();\r\n }\r\n\r\n QVector<float> verts;\r\n \/\/ combine verts from all threads\r\n for ( int i = 0; i < numThreads; ++i )\r\n {\r\n verts += *( threads[i]->getVerts() );\r\n }\r\n\r\n for ( int i = 0; i < numThreads; ++i )\r\n {\r\n delete threads[i];\r\n }\r\n\r\n glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, vboIds[ 1 ] );\r\n glBufferData( GL_ELEMENT_ARRAY_BUFFER, verts.size() * sizeof(GLfloat), verts.data(), GL_STATIC_DRAW );\r\n\r\n m_pointsPerLine.resize( m_data.size() );\r\n m_startIndexes.resize( m_data.size() );\r\n\r\n int currentStart = 0;\r\n for ( int i = 0; i < m_data.size(); ++i )\r\n {\r\n m_pointsPerLine[i] = m_data[i].size() \/ 3;\r\n m_startIndexes[i] = currentStart;\r\n currentStart += m_pointsPerLine[i];\r\n }\r\n qDebug() << \"create fiber vbo's done\";\r\n\r\n qDebug() << \"start creating kdtree\";\r\n m_numPoints = verts.size() \/ 9;\r\n m_kdVerts.reserve( m_numPoints * 3 );\r\n m_reverseIndexes.reserve( m_numPoints );\r\n for ( int i = 0; i < m_numLines; ++i )\r\n {\r\n for( int k = 0; k < m_data[i].size() \/ 3; ++k )\r\n {\r\n m_kdVerts.push_back( m_data[i][k * 3 ] );\r\n m_kdVerts.push_back( m_data[i][k * 3 + 1] );\r\n m_kdVerts.push_back( m_data[i][k * 3 + 2] );\r\n m_reverseIndexes.push_back( i );\r\n }\r\n }\r\n m_kdTree = new KdTree( m_numPoints, m_kdVerts.data() );\r\n qDebug() << \"end creating kdtree\";\r\n\r\n updatePresentRois();\r\n\r\n m_isInitialized = true;\r\n}\r\n\r\nvoid FiberRenderer::setRenderParams( int colorMode )\r\n{\r\n m_colorMode = colorMode;\r\n}\r\n\r\nvoid FiberRenderer::updatePresentRois()\r\n{\r\n int numBranches = m_roiModel->rowCount( QModelIndex() );\r\n\r\n for ( int i = 0; i < numBranches; ++i )\r\n {\r\n QList<QVector<bool> >newBranch;\r\n QVector<bool>newLeaf( m_numLines );\r\n newBranch.push_back( newLeaf );\r\n m_branchfields.push_back( newLeaf );\r\n m_bitfields.push_back( newBranch );\r\n updateBox( m_bitfields.size() - 1, 0 );\r\n\r\n int leafCount = m_roiModel->rowCount( createIndex( i, 0, 0 ) );\r\n\r\n for ( int k = 0; k < leafCount; ++k )\r\n {\r\n \/\/ inserted child roi\r\n QVector<bool>newLeaf( m_numLines );\r\n m_bitfields[i].push_back( newLeaf );\r\n updateBox( i, k + 1 );\r\n }\r\n }\r\n}\r\n\r\nvoid FiberRenderer::roiChanged( const QModelIndex &topLeft, const QModelIndex &bottomRight )\r\n{\r\n if ( topLeft.row() == -1 ) return;\r\n \/\/qDebug() << \"roi changed\" << topLeft.row() << topLeft.column() << topLeft.internalId();\r\n int branch = 0;\r\n int pos = 0;\r\n if ( topLeft.internalId() == -1 )\r\n {\r\n \/\/ top level box\r\n branch = topLeft.row();\r\n }\r\n else\r\n {\r\n \/\/ child box\r\n branch = topLeft.internalId();\r\n pos = topLeft.row() + 1;\r\n }\r\n updateBox( branch, pos );\r\n\r\n}\r\n\r\nvoid FiberRenderer::roiInserted( const QModelIndex &parent, int start, int end )\r\n{\r\n \/\/qDebug() << \"roi inserted\" << parent.row() << start << end;\r\n if ( parent.row() == -1 )\r\n {\r\n \/\/ inserted top level roi\r\n QList<QVector<bool> >newBranch;\r\n QVector<bool>newLeaf( m_numLines );\r\n newBranch.push_back( newLeaf );\r\n m_branchfields.push_back( newLeaf );\r\n m_bitfields.push_back( newBranch );\r\n updateBox( m_bitfields.size() - 1, 0 );\r\n }\r\n else\r\n {\r\n \/\/ inserted child roi\r\n QVector<bool>newLeaf( m_numLines );\r\n m_bitfields[parent.row()].push_back( newLeaf );\r\n updateBox( parent.row(), m_bitfields[parent.row()].size() - 1 );\r\n }\r\n}\r\n\r\nvoid FiberRenderer::roiDeleted( const QModelIndex &parent, int start, int end )\r\n{\r\n \/\/qDebug() << \"roi deleted\" << parent.row() << start << end;\r\n if ( parent.row() == -1 )\r\n {\r\n m_bitfields.removeAt( start );\r\n m_branchfields.removeAt( start );\r\n updateRoot();\r\n }\r\n else\r\n {\r\n m_bitfields[parent.row()].removeAt( start + 1 );\r\n updateBranch( parent.row() );\r\n }\r\n}\r\n\r\nQModelIndex FiberRenderer::createIndex( int branch, int pos, int column )\r\n{\r\n int row;\r\n QModelIndex parent;\r\n if ( pos == 0 )\r\n {\r\n row = branch;\r\n }\r\n else\r\n {\r\n row = pos - 1;\r\n parent = m_roiModel->index( branch, 0 );\r\n }\r\n return m_roiModel->index( row, column, parent );\r\n}\r\n\r\nvoid FiberRenderer::updateBox( int branch, int pos )\r\n{\r\n \/\/qDebug() << \"update box\" << branch << pos;\r\n float x, y, z, dx, dy, dz;\r\n\r\n if ( m_roiModel->data( createIndex( branch, pos, (int)Fn::ROI::ACTIVE ), Qt::DisplayRole ).toBool() )\r\n {\r\n x = m_roiModel->data( createIndex( branch, pos, (int)Fn::ROI::X ), Qt::DisplayRole ).toFloat();\r\n y = m_roiModel->data( createIndex( branch, pos, (int)Fn::ROI::Y ), Qt::DisplayRole ).toFloat();\r\n z = m_roiModel->data( createIndex( branch, pos, (int)Fn::ROI::Z ), Qt::DisplayRole ).toFloat();\r\n dx = m_roiModel->data( createIndex( branch, pos, (int)Fn::ROI::DX ), Qt::DisplayRole ).toFloat();\r\n dy = m_roiModel->data( createIndex( branch, pos, (int)Fn::ROI::DY ), Qt::DisplayRole ).toFloat();\r\n dz = m_roiModel->data( createIndex( branch, pos, (int)Fn::ROI::DZ ), Qt::DisplayRole ).toFloat();\r\n m_boxMin[0] = x - dx \/ 2;\r\n m_boxMax[0] = x + dx \/ 2;\r\n m_boxMin[1] = y - dy \/ 2;\r\n m_boxMax[1] = y + dy \/ 2;\r\n m_boxMin[2] = z - dz \/ 2;\r\n m_boxMax[2] = z + dz \/ 2;\r\n\r\n for ( int i = 0; i < m_numLines; ++i )\r\n {\r\n m_bitfields[branch][pos][i] = false;\r\n }\r\n boxTest( m_bitfields[branch][pos], 0, m_numPoints - 1, 0 );\r\n }\r\n else\r\n {\r\n for ( int i = 0; i < m_numLines; ++i )\r\n {\r\n m_bitfields[branch][pos][i] = true;\r\n }\r\n }\r\n\r\n updateBranch( branch );\r\n if ( m_isInitialized )\r\n {\r\n m_roiModel->setData( createIndex( branch, pos, (int)Fn::ROI::UPDATED ), true, Qt::DisplayRole );\r\n }\r\n}\r\n\r\nvoid FiberRenderer::boxTest( QVector<bool>& workfield, int left, int right, int axis )\r\n{\r\n \/\/ abort condition\r\n if ( left > right )\r\n return;\r\n\r\n int root = left + ( ( right - left ) \/ 2 );\r\n int axis1 = ( axis + 1 ) % 3;\r\n int pointIndex = m_kdTree->m_tree[root] * 3;\r\n\r\n if ( m_kdVerts[pointIndex + axis] < m_boxMin[axis] )\r\n {\r\n boxTest( workfield, root + 1, right, axis1 );\r\n }\r\n else if ( m_kdVerts[pointIndex + axis] > m_boxMax[axis] )\r\n {\r\n boxTest( workfield, left, root - 1, axis1 );\r\n }\r\n else\r\n {\r\n int axis2 = ( axis + 2 ) % 3;\r\n if ( m_kdVerts[pointIndex + axis1] <= m_boxMax[axis1] && m_kdVerts[pointIndex + axis1]\r\n >= m_boxMin[axis1] && m_kdVerts[pointIndex + axis2] <= m_boxMax[axis2]\r\n && m_kdVerts[pointIndex + axis2] >= m_boxMin[axis2] )\r\n {\r\n workfield[m_reverseIndexes[ m_kdTree->m_tree[root] ]] = true;\r\n }\r\n boxTest( workfield, left, root - 1, axis1 );\r\n boxTest( workfield, root + 1, right, axis1 );\r\n }\r\n}\r\n\r\n\r\nvoid FiberRenderer::updateBranch( int branch )\r\n{\r\n \/\/qDebug() << \"update branch\" << branch;\r\n int current = 0;\r\n\r\n bool neg = m_roiModel->data( createIndex( branch, current, (int)Fn::ROI::NEG ), Qt::DisplayRole ).toBool();\r\n if ( neg )\r\n {\r\n for ( int k = 0; k < m_numLines; ++k )\r\n {\r\n m_branchfields[branch][k] = !m_bitfields[branch][current][k];\r\n }\r\n }\r\n else\r\n {\r\n for ( int k = 0; k < m_numLines; ++k )\r\n {\r\n m_branchfields[branch][k] = m_bitfields[branch][current][k];\r\n }\r\n }\r\n ++current;\r\n\r\n while ( current < m_bitfields[branch].size() )\r\n {\r\n if ( m_roiModel->data( createIndex( branch, current, (int)Fn::ROI::ACTIVE ), Qt::DisplayRole ).toBool() )\r\n {\r\n bool neg = m_roiModel->data( createIndex( branch, current, (int)Fn::ROI::NEG ), Qt::DisplayRole ).toBool();\r\n if ( neg )\r\n {\r\n for ( int k = 0; k < m_numLines; ++k )\r\n {\r\n m_branchfields[branch][k] &= !m_bitfields[branch][current][k];\r\n }\r\n }\r\n else\r\n {\r\n for ( int k = 0; k < m_numLines; ++k )\r\n {\r\n m_branchfields[branch][k] &= m_bitfields[branch][current][k];\r\n }\r\n }\r\n ++current;\r\n }\r\n else\r\n {\r\n ++current;\r\n }\r\n }\r\n updateRoot();\r\n}\r\n\r\nvoid FiberRenderer::updateRoot()\r\n{\r\n \/\/qDebug() << \"update root\";\r\n if ( m_branchfields.size() > 0 )\r\n {\r\n for ( int i = 0; i < m_numLines; ++i )\r\n {\r\n m_rootfield[i] = false;\r\n }\r\n\r\n for ( int i = 0; i < m_branchfields.size(); ++i )\r\n {\r\n if ( m_roiModel->data( createIndex( i, 0, (int)Fn::ROI::ACTIVE ), Qt::DisplayRole ).toBool() )\r\n {\r\n for ( int k = 0; k < m_numLines; ++k )\r\n {\r\n m_rootfield[k] |= m_branchfields[i][k];\r\n }\r\n }\r\n }\r\n }\r\n else\r\n {\r\n for ( int i = 0; i < m_numLines; ++i )\r\n {\r\n m_rootfield[i] = true;\r\n }\r\n }\r\n}\r\n\r\n<|endoftext|>"} {"text":"<commit_before>\/*\n* Copyright (C) 2008-2013 The Communi Project\n*\n* This program is free software; you can redistribute it and\/or modify\n* it under the terms of the GNU General Public License as published by\n* the Free Software Foundation; either version 2 of the License, or\n* (at your option) any later version.\n*\n* This program is distributed in the hope that it will be useful,\n* but WITHOUT ANY WARRANTY; without even the implied warranty of\n* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n* GNU General Public License for more details.\n*\/\n\n#include \"textbrowser.h\"\n#include <QApplication>\n#include <QScrollBar>\n#include <QPainter>\n#include <QTextBlock>\n#include <QAbstractTextDocumentLayout>\n#include <qmath.h>\n\nTextBrowser::TextBrowser(QWidget* parent) : QTextBrowser(parent)\n{\n d.ub = -1;\n d.bud = 0;\n}\n\nQWidget* TextBrowser::buddy() const\n{\n return d.bud;\n}\n\nvoid TextBrowser::setBuddy(QWidget* buddy)\n{\n d.bud = buddy;\n}\n\nvoid TextBrowser::addMarker(int block)\n{\n d.markers.append(block);\n update();\n}\n\nvoid TextBrowser::removeMarker(int block)\n{\n if (d.markers.removeOne(block))\n update();\n}\n\nQColor TextBrowser::highlightColor() const\n{\n return d.highlightColor;\n}\n\nvoid TextBrowser::setHighlightColor(const QColor& color)\n{\n if (d.highlightColor != color) {\n d.highlightColor = color;\n update();\n }\n}\n\nvoid TextBrowser::append(const QString& text, bool highlight)\n{\n if (!text.isEmpty()) {\n\n QTextBrowser::append(text);\n\n#if QT_VERSION >= 0x040800\n QTextCursor cursor(document());\n cursor.movePosition(QTextCursor::End);\n QTextBlockFormat format = cursor.blockFormat();\n format.setLineHeight(120, QTextBlockFormat::ProportionalHeight);\n cursor.setBlockFormat(format);\n#endif \/\/ QT_VERSION\n\n if (!isVisible() && d.ub == -1)\n d.ub = document()->blockCount() - 1;\n\n if (highlight)\n d.highlights.append(document()->blockCount() - 1);\n }\n}\n\nvoid TextBrowser::hideEvent(QHideEvent* event)\n{\n QTextBrowser::hideEvent(event);\n d.ub = -1;\n}\n\nvoid TextBrowser::keyPressEvent(QKeyEvent* event)\n{\n \/\/ for example:\n \/\/ - Ctrl+C goes to the browser\n \/\/ - Ctrl+V goes to the buddy\n \/\/ - Shift+7 (\"\/\") goes to the buddy\n switch (event->key()) {\n case Qt::Key_Shift:\n case Qt::Key_Control:\n case Qt::Key_Meta:\n case Qt::Key_Alt:\n case Qt::Key_AltGr:\n break;\n default:\n if (!event->matches(QKeySequence::Copy) && !event->matches(QKeySequence::SelectAll)) {\n QApplication::sendEvent(d.bud, event);\n d.bud->setFocus();\n return;\n }\n break;\n }\n QTextBrowser::keyPressEvent(event);\n}\n\nvoid TextBrowser::resizeEvent(QResizeEvent* event)\n{\n QTextBrowser::resizeEvent(event);\n\n \/\/ http:\/\/www.qtsoftware.com\/developer\/task-tracker\/index_html?method=entry&id=240940\n QMetaObject::invokeMethod(this, \"scrollToBottom\", Qt::QueuedConnection);\n}\n\nvoid TextBrowser::scrollToTop()\n{\n verticalScrollBar()->triggerAction(QScrollBar::SliderToMinimum);\n}\n\nvoid TextBrowser::scrollToBottom()\n{\n verticalScrollBar()->triggerAction(QScrollBar::SliderToMaximum);\n}\n\nvoid TextBrowser::scrollToNextPage()\n{\n verticalScrollBar()->triggerAction(QScrollBar::SliderPageStepAdd);\n}\n\nvoid TextBrowser::scrollToPreviousPage()\n{\n verticalScrollBar()->triggerAction(QScrollBar::SliderPageStepSub);\n}\n\nvoid TextBrowser::paintEvent(QPaintEvent* event)\n{\n const QRect bounds = rect().translated(horizontalScrollBar()->value(),\n verticalScrollBar()->value());\n\n if (!d.highlights.isEmpty()) {\n QPainter painter(viewport());\n painter.translate(-horizontalScrollBar()->value(), -verticalScrollBar()->value());\n\n int margin = qCeil(document()->documentMargin());\n foreach (int highlight, d.highlights) {\n QTextBlock block = document()->findBlockByNumber(highlight);\n QRectF br = document()->documentLayout()->blockBoundingRect(block);\n if (bounds.intersects(br.toAlignedRect()))\n painter.fillRect(br.adjusted(-margin, 0, margin, 0), d.highlightColor);\n }\n }\n\n QTextBrowser::paintEvent(event);\n\n QPainter painter(viewport());\n painter.translate(-horizontalScrollBar()->value(), -verticalScrollBar()->value());\n\n int last = -1;\n if (!d.markers.isEmpty()) {\n painter.setPen(QPen(Qt::gray, 1, Qt::DashLine));\n foreach (int marker, d.markers) {\n QTextBlock block = document()->findBlockByNumber(marker);\n QRectF br = document()->documentLayout()->blockBoundingRect(block);\n if (bounds.intersects(br.toAlignedRect())) {\n painter.drawLine(br.topLeft(), br.topRight());\n last = qMax(marker, last);\n }\n }\n }\n\n if (d.ub > 0 && d.ub >= last) {\n painter.setPen(QPen(Qt::black, 1, Qt::DashLine));\n QTextBlock block = document()->findBlockByNumber(d.ub);\n QRectF br = document()->documentLayout()->blockBoundingRect(block);\n if (bounds.intersects(br.toAlignedRect()))\n painter.drawLine(br.topLeft(), br.topRight());\n }\n\n QLinearGradient gradient(0, 0, 0, 3);\n gradient.setColorAt(0.0, palette().color(QPalette::Dark));\n gradient.setColorAt(1.0, Qt::transparent);\n painter.fillRect(0, 0, width(), 3, gradient);\n}\n\nvoid TextBrowser::wheelEvent(QWheelEvent* event)\n{\n#ifdef Q_WS_MACX\n \/\/ disable cmd+wheel zooming on mac\n QAbstractScrollArea::wheelEvent(event);\n#else\n QTextBrowser::wheelEvent(event);\n#endif \/\/ Q_WS_MACX\n}\n\n<commit_msg>TextBrowser: fix the top shadow<commit_after>\/*\n* Copyright (C) 2008-2013 The Communi Project\n*\n* This program is free software; you can redistribute it and\/or modify\n* it under the terms of the GNU General Public License as published by\n* the Free Software Foundation; either version 2 of the License, or\n* (at your option) any later version.\n*\n* This program is distributed in the hope that it will be useful,\n* but WITHOUT ANY WARRANTY; without even the implied warranty of\n* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n* GNU General Public License for more details.\n*\/\n\n#include \"textbrowser.h\"\n#include <QApplication>\n#include <QScrollBar>\n#include <QPainter>\n#include <QTextBlock>\n#include <QAbstractTextDocumentLayout>\n#include <qmath.h>\n\nTextBrowser::TextBrowser(QWidget* parent) : QTextBrowser(parent)\n{\n d.ub = -1;\n d.bud = 0;\n}\n\nQWidget* TextBrowser::buddy() const\n{\n return d.bud;\n}\n\nvoid TextBrowser::setBuddy(QWidget* buddy)\n{\n d.bud = buddy;\n}\n\nvoid TextBrowser::addMarker(int block)\n{\n d.markers.append(block);\n update();\n}\n\nvoid TextBrowser::removeMarker(int block)\n{\n if (d.markers.removeOne(block))\n update();\n}\n\nQColor TextBrowser::highlightColor() const\n{\n return d.highlightColor;\n}\n\nvoid TextBrowser::setHighlightColor(const QColor& color)\n{\n if (d.highlightColor != color) {\n d.highlightColor = color;\n update();\n }\n}\n\nvoid TextBrowser::append(const QString& text, bool highlight)\n{\n if (!text.isEmpty()) {\n\n QTextBrowser::append(text);\n\n#if QT_VERSION >= 0x040800\n QTextCursor cursor(document());\n cursor.movePosition(QTextCursor::End);\n QTextBlockFormat format = cursor.blockFormat();\n format.setLineHeight(120, QTextBlockFormat::ProportionalHeight);\n cursor.setBlockFormat(format);\n#endif \/\/ QT_VERSION\n\n if (!isVisible() && d.ub == -1)\n d.ub = document()->blockCount() - 1;\n\n if (highlight)\n d.highlights.append(document()->blockCount() - 1);\n }\n}\n\nvoid TextBrowser::hideEvent(QHideEvent* event)\n{\n QTextBrowser::hideEvent(event);\n d.ub = -1;\n}\n\nvoid TextBrowser::keyPressEvent(QKeyEvent* event)\n{\n \/\/ for example:\n \/\/ - Ctrl+C goes to the browser\n \/\/ - Ctrl+V goes to the buddy\n \/\/ - Shift+7 (\"\/\") goes to the buddy\n switch (event->key()) {\n case Qt::Key_Shift:\n case Qt::Key_Control:\n case Qt::Key_Meta:\n case Qt::Key_Alt:\n case Qt::Key_AltGr:\n break;\n default:\n if (!event->matches(QKeySequence::Copy) && !event->matches(QKeySequence::SelectAll)) {\n QApplication::sendEvent(d.bud, event);\n d.bud->setFocus();\n return;\n }\n break;\n }\n QTextBrowser::keyPressEvent(event);\n}\n\nvoid TextBrowser::resizeEvent(QResizeEvent* event)\n{\n QTextBrowser::resizeEvent(event);\n\n \/\/ http:\/\/www.qtsoftware.com\/developer\/task-tracker\/index_html?method=entry&id=240940\n QMetaObject::invokeMethod(this, \"scrollToBottom\", Qt::QueuedConnection);\n}\n\nvoid TextBrowser::scrollToTop()\n{\n verticalScrollBar()->triggerAction(QScrollBar::SliderToMinimum);\n}\n\nvoid TextBrowser::scrollToBottom()\n{\n verticalScrollBar()->triggerAction(QScrollBar::SliderToMaximum);\n}\n\nvoid TextBrowser::scrollToNextPage()\n{\n verticalScrollBar()->triggerAction(QScrollBar::SliderPageStepAdd);\n}\n\nvoid TextBrowser::scrollToPreviousPage()\n{\n verticalScrollBar()->triggerAction(QScrollBar::SliderPageStepSub);\n}\n\nvoid TextBrowser::paintEvent(QPaintEvent* event)\n{\n const QRect bounds = rect().translated(horizontalScrollBar()->value(),\n verticalScrollBar()->value());\n\n if (!d.highlights.isEmpty()) {\n QPainter painter(viewport());\n painter.translate(-horizontalScrollBar()->value(), -verticalScrollBar()->value());\n\n int margin = qCeil(document()->documentMargin());\n foreach (int highlight, d.highlights) {\n QTextBlock block = document()->findBlockByNumber(highlight);\n QRectF br = document()->documentLayout()->blockBoundingRect(block);\n if (bounds.intersects(br.toAlignedRect()))\n painter.fillRect(br.adjusted(-margin, 0, margin, 0), d.highlightColor);\n }\n }\n\n QTextBrowser::paintEvent(event);\n\n QPainter painter(viewport());\n painter.save();\n painter.translate(-horizontalScrollBar()->value(), -verticalScrollBar()->value());\n\n int last = -1;\n if (!d.markers.isEmpty()) {\n painter.setPen(QPen(Qt::gray, 1, Qt::DashLine));\n foreach (int marker, d.markers) {\n QTextBlock block = document()->findBlockByNumber(marker);\n QRectF br = document()->documentLayout()->blockBoundingRect(block);\n if (bounds.intersects(br.toAlignedRect())) {\n painter.drawLine(br.topLeft(), br.topRight());\n last = qMax(marker, last);\n }\n }\n }\n\n if (d.ub > 0 && d.ub >= last) {\n painter.setPen(QPen(Qt::black, 1, Qt::DashLine));\n QTextBlock block = document()->findBlockByNumber(d.ub);\n QRectF br = document()->documentLayout()->blockBoundingRect(block);\n if (bounds.intersects(br.toAlignedRect()))\n painter.drawLine(br.topLeft(), br.topRight());\n }\n\n QLinearGradient gradient(0, 0, 0, 3);\n gradient.setColorAt(0.0, palette().color(QPalette::Dark));\n gradient.setColorAt(1.0, Qt::transparent);\n painter.restore();\n painter.fillRect(0, 0, width(), 3, gradient);\n}\n\nvoid TextBrowser::wheelEvent(QWheelEvent* event)\n{\n#ifdef Q_WS_MACX\n \/\/ disable cmd+wheel zooming on mac\n QAbstractScrollArea::wheelEvent(event);\n#else\n QTextBrowser::wheelEvent(event);\n#endif \/\/ Q_WS_MACX\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/**\n * Copyright (c) 2011-2015 libbitcoin developers (see AUTHORS)\n *\n * This file is part of libbitcoin-server.\n *\n * libbitcoin-server is free software: you can redistribute it and\/or\n * modify it under the terms of the GNU Affero General Public License with\n * additional permissions to the one published by the Free Software\n * Foundation, either version 3 of the License, or (at your option)\n * any later version. For more information see LICENSE.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Affero General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public License\n * along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n#include <bitcoin\/server\/interface\/blockchain.hpp>\n\n#include <cstdint>\n#include <cstddef>\n#include <functional>\n#include <bitcoin\/blockchain.hpp>\n#include <bitcoin\/server\/define.hpp>\n#include <bitcoin\/server\/messages\/message.hpp>\n#include <bitcoin\/server\/server_node.hpp>\n#include <bitcoin\/server\/utility\/fetch_helpers.hpp>\n\nnamespace libbitcoin {\nnamespace server {\n\nusing namespace std::placeholders;\nusing namespace bc::blockchain;\nusing namespace bc::chain;\nusing namespace bc::wallet;\n\nvoid blockchain::fetch_history(server_node& node, const message& request,\n send_handler handler)\n{\n static constexpr uint64_t limit = 0;\n uint32_t from_height;\n payment_address address;\n\n if (!unwrap_fetch_history_args(address, from_height, request))\n {\n handler(message(request, error::bad_stream));\n return;\n }\n\n log::debug(LOG_SERVER)\n << \"blockchain.fetch_history(\" << address.encoded()\n << \", from_height=\" << from_height << \")\";\n\n node.chain().fetch_history(address, limit, from_height,\n std::bind(send_history_result,\n _1, _2, request, handler));\n}\n\nvoid blockchain::fetch_transaction(server_node& node, const message& request,\n send_handler handler)\n{\n hash_digest tx_hash;\n\n if (!unwrap_fetch_transaction_args(tx_hash, request))\n {\n handler(message(request, error::bad_stream));\n return;\n }\n\n log::debug(LOG_SERVER)\n << \"blockchain.fetch_transaction(\" << encode_hash(tx_hash) << \")\";\n\n node.chain().fetch_transaction(tx_hash,\n std::bind(transaction_fetched,\n _1, _2, request, handler));\n}\n\nvoid blockchain::fetch_last_height(server_node& node, const message& request,\n send_handler handler)\n{\n const auto& data = request.data();\n\n if (!data.empty())\n {\n handler(message(request, error::bad_stream));\n return;\n }\n\n node.chain().fetch_last_height(\n std::bind(&blockchain::last_height_fetched,\n _1, _2, request, handler));\n}\n\nvoid blockchain::last_height_fetched(const code& ec, size_t last_height,\n const message& request, send_handler handler)\n{\n BITCOIN_ASSERT(last_height <= max_uint32);\n auto last_height32 = static_cast<uint32_t>(last_height);\n\n \/\/ [ code:4 ]\n \/\/ [ heigh:4 ]\n const auto result = build_chunk(\n {\n message::to_bytes(ec),\n to_little_endian(last_height32)\n });\n\n handler(message(request, result));\n}\n\nvoid blockchain::fetch_block_header(server_node& node, const message& request,\n send_handler handler)\n{\n const auto& data = request.data();\n\n if (data.size() == hash_size)\n blockchain::fetch_block_header_by_hash(node, request, handler);\n else if (data.size() == sizeof(uint32_t))\n blockchain::fetch_block_header_by_height(node, request, handler);\n else\n handler(message(request, error::bad_stream));\n}\n\nvoid blockchain::fetch_block_header_by_hash(server_node& node,\n const message& request, send_handler handler)\n{\n const auto& data = request.data();\n BITCOIN_ASSERT(data.size() == hash_size);\n\n auto deserial = make_deserializer(data.begin(), data.end());\n const auto block_hash = deserial.read_hash();\n\n node.chain().fetch_block_header(block_hash,\n std::bind(&blockchain::block_header_fetched,\n _1, _2, request, handler));\n}\n\nvoid blockchain::fetch_block_header_by_height(server_node& node,\n const message& request, send_handler handler)\n{\n const auto& data = request.data();\n BITCOIN_ASSERT(data.size() == sizeof(uint32_t));\n\n auto deserial = make_deserializer(data.begin(), data.end());\n const uint64_t height = deserial.read_4_bytes_little_endian();\n\n node.chain().fetch_block_header(height,\n std::bind(&blockchain::block_header_fetched,\n _1, _2, request, handler));\n}\n\nvoid blockchain::block_header_fetched(const code& ec,\n const chain::header& block, const message& request, send_handler handler)\n{\n \/\/ [ code:4 ]\n \/\/ [ block... ]\n const auto result = build_chunk(\n {\n message::to_bytes(ec),\n block.to_data(false)\n });\n\n handler(message(request, result));\n}\n\nvoid blockchain::fetch_block_transaction_hashes(server_node& node,\n const message& request, send_handler handler)\n{\n const auto& data = request.data();\n\n if (data.size() == hash_size)\n fetch_block_transaction_hashes_by_hash(node, request, handler);\n else if (data.size() == sizeof(uint32_t))\n fetch_block_transaction_hashes_by_height(node, request, handler);\n else\n handler(message(request, error::bad_stream));\n}\n\nvoid blockchain::fetch_block_transaction_hashes_by_hash(server_node& node,\n const message& request, send_handler handler)\n{\n const auto& data = request.data();\n BITCOIN_ASSERT(data.size() == hash_size);\n\n auto deserial = make_deserializer(data.begin(), data.end());\n const auto block_hash = deserial.read_hash();\n node.chain().fetch_block_transaction_hashes(block_hash,\n std::bind(&blockchain::block_transaction_hashes_fetched,\n _1, _2, request, handler));\n}\n\nvoid blockchain::fetch_block_transaction_hashes_by_height(server_node& node,\n const message& request, send_handler handler)\n{\n const auto& data = request.data();\n BITCOIN_ASSERT(data.size() == sizeof(uint32_t));\n\n auto deserial = make_deserializer(data.begin(), data.end());\n const size_t block_height = deserial.read_4_bytes_little_endian();\n node.chain().fetch_block_transaction_hashes(block_height,\n std::bind(&blockchain::block_transaction_hashes_fetched,\n _1, _2, request, handler));\n}\n\nvoid blockchain::block_transaction_hashes_fetched(const code& ec,\n const hash_list& hashes, const message& request, send_handler handler)\n{\n \/\/ [ code:4 ]\n \/\/ [[ hash:32 ]...]\n data_chunk result(code_size + hash_size * hashes.size());\n auto serial = make_serializer(result.begin());\n serial.write_error_code(ec);\n\n for (const auto& tx_hash: hashes)\n serial.write_hash(tx_hash);\n\n handler(message(request, result));\n}\n\nvoid blockchain::fetch_transaction_index(server_node& node,\n const message& request, send_handler handler)\n{\n const auto& data = request.data();\n\n if (data.size() != hash_size)\n {\n handler(message(request, error::bad_stream));\n return;\n }\n\n auto deserial = make_deserializer(data.begin(), data.end());\n const auto tx_hash = deserial.read_hash();\n\n node.chain().fetch_transaction_index(tx_hash,\n std::bind(&blockchain::transaction_index_fetched,\n _1, _2, _3, request, handler));\n}\n\nvoid blockchain::transaction_index_fetched(const code& ec, size_t block_height,\n size_t index, const message& request, send_handler handler)\n{\n BITCOIN_ASSERT(index <= max_uint32);\n BITCOIN_ASSERT(block_height <= max_uint32);\n\n auto index32 = static_cast<uint32_t>(index);\n auto block_height32 = static_cast<uint32_t>(block_height);\n\n \/\/ [ code:4 ]\n \/\/ [ block_height:32 ]\n \/\/ [ tx_index:4 ]\n const auto result = build_chunk(\n {\n message::to_bytes(ec),\n to_little_endian(block_height32),\n to_little_endian(index32)\n });\n\n handler(message(request, result));\n}\n\nvoid blockchain::fetch_spend(server_node& node, const message& request,\n send_handler handler)\n{\n const auto& data = request.data();\n\n if (data.size() != point_size)\n {\n handler(message(request, error::bad_stream));\n return;\n }\n\n using namespace boost::iostreams;\n static const auto fail_bit = stream<byte_source<data_chunk>>::failbit;\n stream<byte_source<data_chunk>> istream(data);\n istream.exceptions(fail_bit);\n chain::output_point outpoint;\n outpoint.from_data(istream);\n\n node.chain().fetch_spend(outpoint,\n std::bind(&blockchain::spend_fetched,\n _1, _2, request, handler));\n}\n\nvoid blockchain::spend_fetched(const code& ec, const chain::input_point& inpoint,\n const message& request, send_handler handler)\n{\n \/\/ [ code:4 ]\n \/\/ [ hash:32 ]\n \/\/ [ index:4 ]\n const auto result = build_chunk(\n {\n message::to_bytes(ec),\n inpoint.to_data()\n });\n\n handler(message(request, result));\n}\n\nvoid blockchain::fetch_block_height(server_node& node,\n const message& request, send_handler handler)\n{\n const auto& data = request.data();\n\n if (data.size() != hash_size)\n {\n handler(message(request, error::bad_stream));\n return;\n }\n\n auto deserial = make_deserializer(data.begin(), data.end());\n const auto block_hash = deserial.read_hash();\n node.chain().fetch_block_height(block_hash,\n std::bind(&blockchain::block_height_fetched,\n _1, _2, request, handler));\n}\n\nvoid blockchain::block_height_fetched(const code& ec, size_t block_height,\n const message& request, send_handler handler)\n{\n BITCOIN_ASSERT(block_height <= max_uint32);\n auto block_height32 = static_cast<uint32_t>(block_height);\n\n \/\/ [ code:4 ]\n \/\/ [ height:4 ]\n const auto result = build_chunk(\n {\n message::to_bytes(ec),\n to_little_endian(block_height32)\n });\n\n handler(message(request, result));\n}\n\nvoid blockchain::fetch_stealth(server_node& node, const message& request,\n send_handler handler)\n{\n const auto& data = request.data();\n\n if (data.empty())\n {\n handler(message(request, error::bad_stream));\n return;\n }\n\n auto deserial = make_deserializer(data.begin(), data.end());\n\n \/\/ number_bits\n const auto bitsize = deserial.read_byte();\n\n if (data.size() != sizeof(uint8_t) + binary::blocks_size(bitsize) +\n sizeof(uint32_t))\n {\n handler(message(request, error::bad_stream));\n return;\n }\n\n \/\/ actual bitfield data\n const auto blocks = deserial.read_data(binary::blocks_size(bitsize));\n const binary prefix(bitsize, blocks);\n\n \/\/ from_height\n const uint64_t from_height = deserial.read_4_bytes_little_endian();\n\n node.chain().fetch_stealth(prefix, from_height,\n std::bind(&blockchain::stealth_fetched,\n _1, _2, request, handler));\n}\n\nvoid blockchain::stealth_fetched(const code& ec,\n const stealth_compact::list& stealth_results, const message& request,\n send_handler handler)\n{\n static constexpr size_t row_size = hash_size + short_hash_size + hash_size;\n\n \/\/ [ code:4 ]\n \/\/ [[ ephemeral_key_hash:32 ][ address_hash:20 ][ tx_hash:32 ]...]\n data_chunk result(code_size + row_size * stealth_results.size());\n auto serial = make_serializer(result.begin());\n serial.write_error_code(ec);\n\n for (const auto& row: stealth_results)\n {\n serial.write_hash(row.ephemeral_public_key_hash);\n serial.write_short_hash(row.public_key_hash);\n serial.write_hash(row.transaction_hash);\n }\n\n handler(message(request, result));\n}\n\nvoid blockchain::fetch_stealth2(server_node& node, const message& request,\n send_handler handler)\n{\n const auto& data = request.data();\n\n if (data.empty())\n {\n handler(message(request, error::bad_stream));\n return;\n }\n\n auto deserial = make_deserializer(data.begin(), data.end());\n\n \/\/ number_bits\n const auto bitsize = deserial.read_byte();\n\n if (data.size() != sizeof(uint8_t) + binary::blocks_size(bitsize) +\n sizeof(uint32_t))\n {\n handler(message(request, error::bad_stream));\n return;\n }\n\n \/\/ actual bitfield data\n const auto blocks = deserial.read_data(binary::blocks_size(bitsize));\n const binary prefix(bitsize, blocks);\n\n \/\/ from_height\n const uint64_t from_height = deserial.read_4_bytes_little_endian();\n\n node.chain().fetch_stealth(prefix, from_height,\n std::bind(&blockchain::stealth_fetched2,\n _1, _2, request, handler));\n}\n\nvoid blockchain::stealth_fetched2(const code& ec,\n const stealth_compact::list& stealth_results, const message& request,\n send_handler handler)\n{\n \/\/ [ code:4 ]\n \/\/ [[ tx_hash:32 ]...]\n data_chunk result(code_size + hash_size * stealth_results.size());\n auto serial = make_serializer(result.begin());\n serial.write_error_code(ec);\n\n for (const auto& row: stealth_results)\n serial.write_hash(row.transaction_hash);\n\n handler(message(request, result));\n}\n\n} \/\/ namespace server\n} \/\/ namespace libbitcoin\n<commit_msg>Avoid bogus compound words (style).<commit_after>\/**\n * Copyright (c) 2011-2015 libbitcoin developers (see AUTHORS)\n *\n * This file is part of libbitcoin-server.\n *\n * libbitcoin-server is free software: you can redistribute it and\/or\n * modify it under the terms of the GNU Affero General Public License with\n * additional permissions to the one published by the Free Software\n * Foundation, either version 3 of the License, or (at your option)\n * any later version. For more information see LICENSE.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Affero General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public License\n * along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n#include <bitcoin\/server\/interface\/blockchain.hpp>\n\n#include <cstdint>\n#include <cstddef>\n#include <functional>\n#include <bitcoin\/blockchain.hpp>\n#include <bitcoin\/server\/define.hpp>\n#include <bitcoin\/server\/messages\/message.hpp>\n#include <bitcoin\/server\/server_node.hpp>\n#include <bitcoin\/server\/utility\/fetch_helpers.hpp>\n\nnamespace libbitcoin {\nnamespace server {\n\nusing namespace std::placeholders;\nusing namespace bc::blockchain;\nusing namespace bc::chain;\nusing namespace bc::wallet;\n\nvoid blockchain::fetch_history(server_node& node, const message& request,\n send_handler handler)\n{\n static constexpr uint64_t limit = 0;\n uint32_t from_height;\n payment_address address;\n\n if (!unwrap_fetch_history_args(address, from_height, request))\n {\n handler(message(request, error::bad_stream));\n return;\n }\n\n log::debug(LOG_SERVER)\n << \"blockchain.fetch_history(\" << address.encoded()\n << \", from_height=\" << from_height << \")\";\n\n node.chain().fetch_history(address, limit, from_height,\n std::bind(send_history_result,\n _1, _2, request, handler));\n}\n\nvoid blockchain::fetch_transaction(server_node& node, const message& request,\n send_handler handler)\n{\n hash_digest tx_hash;\n\n if (!unwrap_fetch_transaction_args(tx_hash, request))\n {\n handler(message(request, error::bad_stream));\n return;\n }\n\n log::debug(LOG_SERVER)\n << \"blockchain.fetch_transaction(\" << encode_hash(tx_hash) << \")\";\n\n node.chain().fetch_transaction(tx_hash,\n std::bind(transaction_fetched,\n _1, _2, request, handler));\n}\n\nvoid blockchain::fetch_last_height(server_node& node, const message& request,\n send_handler handler)\n{\n const auto& data = request.data();\n\n if (!data.empty())\n {\n handler(message(request, error::bad_stream));\n return;\n }\n\n node.chain().fetch_last_height(\n std::bind(&blockchain::last_height_fetched,\n _1, _2, request, handler));\n}\n\nvoid blockchain::last_height_fetched(const code& ec, size_t last_height,\n const message& request, send_handler handler)\n{\n BITCOIN_ASSERT(last_height <= max_uint32);\n auto last_height32 = static_cast<uint32_t>(last_height);\n\n \/\/ [ code:4 ]\n \/\/ [ heigh:4 ]\n const auto result = build_chunk(\n {\n message::to_bytes(ec),\n to_little_endian(last_height32)\n });\n\n handler(message(request, result));\n}\n\nvoid blockchain::fetch_block_header(server_node& node, const message& request,\n send_handler handler)\n{\n const auto& data = request.data();\n\n if (data.size() == hash_size)\n blockchain::fetch_block_header_by_hash(node, request, handler);\n else if (data.size() == sizeof(uint32_t))\n blockchain::fetch_block_header_by_height(node, request, handler);\n else\n handler(message(request, error::bad_stream));\n}\n\nvoid blockchain::fetch_block_header_by_hash(server_node& node,\n const message& request, send_handler handler)\n{\n const auto& data = request.data();\n BITCOIN_ASSERT(data.size() == hash_size);\n\n auto deserial = make_deserializer(data.begin(), data.end());\n const auto block_hash = deserial.read_hash();\n\n node.chain().fetch_block_header(block_hash,\n std::bind(&blockchain::block_header_fetched,\n _1, _2, request, handler));\n}\n\nvoid blockchain::fetch_block_header_by_height(server_node& node,\n const message& request, send_handler handler)\n{\n const auto& data = request.data();\n BITCOIN_ASSERT(data.size() == sizeof(uint32_t));\n\n auto deserial = make_deserializer(data.begin(), data.end());\n const uint64_t height = deserial.read_4_bytes_little_endian();\n\n node.chain().fetch_block_header(height,\n std::bind(&blockchain::block_header_fetched,\n _1, _2, request, handler));\n}\n\nvoid blockchain::block_header_fetched(const code& ec,\n const chain::header& block, const message& request, send_handler handler)\n{\n \/\/ [ code:4 ]\n \/\/ [ block... ]\n const auto result = build_chunk(\n {\n message::to_bytes(ec),\n block.to_data(false)\n });\n\n handler(message(request, result));\n}\n\nvoid blockchain::fetch_block_transaction_hashes(server_node& node,\n const message& request, send_handler handler)\n{\n const auto& data = request.data();\n\n if (data.size() == hash_size)\n fetch_block_transaction_hashes_by_hash(node, request, handler);\n else if (data.size() == sizeof(uint32_t))\n fetch_block_transaction_hashes_by_height(node, request, handler);\n else\n handler(message(request, error::bad_stream));\n}\n\nvoid blockchain::fetch_block_transaction_hashes_by_hash(server_node& node,\n const message& request, send_handler handler)\n{\n const auto& data = request.data();\n BITCOIN_ASSERT(data.size() == hash_size);\n\n auto deserial = make_deserializer(data.begin(), data.end());\n const auto block_hash = deserial.read_hash();\n node.chain().fetch_block_transaction_hashes(block_hash,\n std::bind(&blockchain::block_transaction_hashes_fetched,\n _1, _2, request, handler));\n}\n\nvoid blockchain::fetch_block_transaction_hashes_by_height(server_node& node,\n const message& request, send_handler handler)\n{\n const auto& data = request.data();\n BITCOIN_ASSERT(data.size() == sizeof(uint32_t));\n\n auto deserial = make_deserializer(data.begin(), data.end());\n const size_t block_height = deserial.read_4_bytes_little_endian();\n node.chain().fetch_block_transaction_hashes(block_height,\n std::bind(&blockchain::block_transaction_hashes_fetched,\n _1, _2, request, handler));\n}\n\nvoid blockchain::block_transaction_hashes_fetched(const code& ec,\n const hash_list& hashes, const message& request, send_handler handler)\n{\n \/\/ [ code:4 ]\n \/\/ [[ hash:32 ]...]\n data_chunk result(code_size + hash_size * hashes.size());\n auto serial = make_serializer(result.begin());\n serial.write_error_code(ec);\n\n for (const auto& tx_hash: hashes)\n serial.write_hash(tx_hash);\n\n handler(message(request, result));\n}\n\nvoid blockchain::fetch_transaction_index(server_node& node,\n const message& request, send_handler handler)\n{\n const auto& data = request.data();\n\n if (data.size() != hash_size)\n {\n handler(message(request, error::bad_stream));\n return;\n }\n\n auto deserial = make_deserializer(data.begin(), data.end());\n const auto tx_hash = deserial.read_hash();\n\n node.chain().fetch_transaction_index(tx_hash,\n std::bind(&blockchain::transaction_index_fetched,\n _1, _2, _3, request, handler));\n}\n\nvoid blockchain::transaction_index_fetched(const code& ec, size_t block_height,\n size_t index, const message& request, send_handler handler)\n{\n BITCOIN_ASSERT(index <= max_uint32);\n BITCOIN_ASSERT(block_height <= max_uint32);\n\n auto index32 = static_cast<uint32_t>(index);\n auto block_height32 = static_cast<uint32_t>(block_height);\n\n \/\/ [ code:4 ]\n \/\/ [ block_height:32 ]\n \/\/ [ tx_index:4 ]\n const auto result = build_chunk(\n {\n message::to_bytes(ec),\n to_little_endian(block_height32),\n to_little_endian(index32)\n });\n\n handler(message(request, result));\n}\n\nvoid blockchain::fetch_spend(server_node& node, const message& request,\n send_handler handler)\n{\n const auto& data = request.data();\n\n if (data.size() != point_size)\n {\n handler(message(request, error::bad_stream));\n return;\n }\n\n using namespace boost::iostreams;\n static const auto fail_bit = stream<byte_source<data_chunk>>::failbit;\n stream<byte_source<data_chunk>> istream(data);\n istream.exceptions(fail_bit);\n chain::output_point outpoint;\n outpoint.from_data(istream);\n\n node.chain().fetch_spend(outpoint,\n std::bind(&blockchain::spend_fetched,\n _1, _2, request, handler));\n}\n\nvoid blockchain::spend_fetched(const code& ec, const chain::input_point& inpoint,\n const message& request, send_handler handler)\n{\n \/\/ [ code:4 ]\n \/\/ [ hash:32 ]\n \/\/ [ index:4 ]\n const auto result = build_chunk(\n {\n message::to_bytes(ec),\n inpoint.to_data()\n });\n\n handler(message(request, result));\n}\n\nvoid blockchain::fetch_block_height(server_node& node,\n const message& request, send_handler handler)\n{\n const auto& data = request.data();\n\n if (data.size() != hash_size)\n {\n handler(message(request, error::bad_stream));\n return;\n }\n\n auto deserial = make_deserializer(data.begin(), data.end());\n const auto block_hash = deserial.read_hash();\n node.chain().fetch_block_height(block_hash,\n std::bind(&blockchain::block_height_fetched,\n _1, _2, request, handler));\n}\n\nvoid blockchain::block_height_fetched(const code& ec, size_t block_height,\n const message& request, send_handler handler)\n{\n BITCOIN_ASSERT(block_height <= max_uint32);\n auto block_height32 = static_cast<uint32_t>(block_height);\n\n \/\/ [ code:4 ]\n \/\/ [ height:4 ]\n const auto result = build_chunk(\n {\n message::to_bytes(ec),\n to_little_endian(block_height32)\n });\n\n handler(message(request, result));\n}\n\nvoid blockchain::fetch_stealth(server_node& node, const message& request,\n send_handler handler)\n{\n const auto& data = request.data();\n\n if (data.empty())\n {\n handler(message(request, error::bad_stream));\n return;\n }\n\n auto deserial = make_deserializer(data.begin(), data.end());\n\n \/\/ number_bits\n const auto bit_size = deserial.read_byte();\n\n if (data.size() != sizeof(uint8_t) + binary::blocks_size(bit_size) +\n sizeof(uint32_t))\n {\n handler(message(request, error::bad_stream));\n return;\n }\n\n \/\/ actual bitfield data\n const auto blocks = deserial.read_data(binary::blocks_size(bit_size));\n const binary prefix(bit_size, blocks);\n\n \/\/ from_height\n const uint64_t from_height = deserial.read_4_bytes_little_endian();\n\n node.chain().fetch_stealth(prefix, from_height,\n std::bind(&blockchain::stealth_fetched,\n _1, _2, request, handler));\n}\n\nvoid blockchain::stealth_fetched(const code& ec,\n const stealth_compact::list& stealth_results, const message& request,\n send_handler handler)\n{\n static constexpr size_t row_size = hash_size + short_hash_size + hash_size;\n\n \/\/ [ code:4 ]\n \/\/ [[ ephemeral_key_hash:32 ][ address_hash:20 ][ tx_hash:32 ]...]\n data_chunk result(code_size + row_size * stealth_results.size());\n auto serial = make_serializer(result.begin());\n serial.write_error_code(ec);\n\n for (const auto& row: stealth_results)\n {\n serial.write_hash(row.ephemeral_public_key_hash);\n serial.write_short_hash(row.public_key_hash);\n serial.write_hash(row.transaction_hash);\n }\n\n handler(message(request, result));\n}\n\nvoid blockchain::fetch_stealth2(server_node& node, const message& request,\n send_handler handler)\n{\n const auto& data = request.data();\n\n if (data.empty())\n {\n handler(message(request, error::bad_stream));\n return;\n }\n\n auto deserial = make_deserializer(data.begin(), data.end());\n\n \/\/ number_bits\n const auto bit_size = deserial.read_byte();\n\n if (data.size() != sizeof(uint8_t) + binary::blocks_size(bit_size) +\n sizeof(uint32_t))\n {\n handler(message(request, error::bad_stream));\n return;\n }\n\n \/\/ actual bitfield data\n const auto blocks = deserial.read_data(binary::blocks_size(bit_size));\n const binary prefix(bit_size, blocks);\n\n \/\/ from_height\n const uint64_t from_height = deserial.read_4_bytes_little_endian();\n\n node.chain().fetch_stealth(prefix, from_height,\n std::bind(&blockchain::stealth_fetched2,\n _1, _2, request, handler));\n}\n\nvoid blockchain::stealth_fetched2(const code& ec,\n const stealth_compact::list& stealth_results, const message& request,\n send_handler handler)\n{\n \/\/ [ code:4 ]\n \/\/ [[ tx_hash:32 ]...]\n data_chunk result(code_size + hash_size * stealth_results.size());\n auto serial = make_serializer(result.begin());\n serial.write_error_code(ec);\n\n for (const auto& row: stealth_results)\n serial.write_hash(row.transaction_hash);\n\n handler(message(request, result));\n}\n\n} \/\/ namespace server\n} \/\/ namespace libbitcoin\n<|endoftext|>"} {"text":"<commit_before>\/*\n *\n * Modified by ScyllaDB\n * Copyright (C) 2015-present ScyllaDB\n *\/\n\n\/*\n * SPDX-License-Identifier: (AGPL-3.0-or-later and Apache-2.0)\n *\/\n\n#include \"locator\/gossiping_property_file_snitch.hh\"\n#include \"gms\/versioned_value.hh\"\n#include \"message\/msg_addr.hh\"\n#include \"message\/messaging_service.hh\"\n#include \"gms\/gossiper.hh\"\n\nnamespace locator {\nfuture<bool> gossiping_property_file_snitch::property_file_was_modified() {\n return open_file_dma(_prop_file_name, open_flags::ro)\n .then([this](file f) {\n return do_with(std::move(f), [] (file& f) {\n return f.stat();\n });\n }).then_wrapped([this] (auto&& f) {\n try {\n auto st = f.get0();\n\n if (!_last_file_mod ||\n _last_file_mod->tv_sec != st.st_mtim.tv_sec) {\n _last_file_mod = st.st_mtim;\n return true;\n } else {\n return false;\n }\n } catch (...) {\n logger().error(\"Failed to open {} for read or to get stats\", _prop_file_name);\n throw;\n }\n });\n}\n\ngossiping_property_file_snitch::gossiping_property_file_snitch(\n const sstring& fname, unsigned io_cpuid)\n: production_snitch_base(fname), _file_reader_cpu_id(io_cpuid) {\n if (this_shard_id() == _file_reader_cpu_id) {\n io_cpu_id() = _file_reader_cpu_id;\n }\n}\n\nfuture<> gossiping_property_file_snitch::start() {\n using namespace std::chrono_literals;\n\n _state = snitch_state::initializing;\n\n reset_io_state();\n\n \/\/ Run a timer only on specific CPU\n if (this_shard_id() == _file_reader_cpu_id) {\n \/\/\n \/\/ Here we will create a timer that will read the properties file every\n \/\/ minute and load its contents into the gossiper.endpoint_state_map\n \/\/\n _file_reader.set_callback([this] {\n periodic_reader_callback();\n });\n\n return read_property_file().then([this] {\n start_io();\n set_snitch_ready();\n return make_ready_future<>();\n });\n }\n\n set_snitch_ready();\n return make_ready_future<>();\n}\n\nvoid gossiping_property_file_snitch::periodic_reader_callback() {\n _file_reader_runs = true;\n \/\/FIXME: discarded future.\n (void)property_file_was_modified().then([this] (bool was_modified) {\n\n if (was_modified) {\n return read_property_file();\n }\n\n return make_ready_future<>();\n }).then_wrapped([this] (auto&& f) {\n try {\n f.get();\n } catch (...) {\n logger().error(\"Exception has been thrown when parsing the property file.\");\n }\n\n if (_state == snitch_state::stopping || _state == snitch_state::io_pausing) {\n this->set_stopped();\n } else if (_state != snitch_state::stopped) {\n _file_reader.arm(reload_property_file_period());\n }\n\n _file_reader_runs = false;\n });\n}\n\nfuture<> gossiping_property_file_snitch::gossiper_starting() {\n \/\/\n \/\/ Note: currently gossiper \"main\" instance always runs on CPU0 therefore\n \/\/ this function will be executed on CPU0 only.\n \/\/\n _gossip_started = true;\n return reload_gossiper_state();\n}\n\nstd::list<std::pair<gms::application_state, gms::versioned_value>> gossiping_property_file_snitch::get_app_states() const {\n sstring ip = format(\"{}\", gms::get_local_gossiper().get_local_messaging().listen_address());\n return {\n {gms::application_state::DC, gms::versioned_value::datacenter(_my_dc)},\n {gms::application_state::RACK, gms::versioned_value::rack(_my_rack)},\n {gms::application_state::INTERNAL_IP, gms::versioned_value::internal_ip(std::move(ip))},\n };\n}\n\nfuture<> gossiping_property_file_snitch::read_property_file() {\n using namespace exceptions;\n\n return load_property_file().then([this] {\n return reload_configuration();\n }).then_wrapped([this] (auto&& f) {\n try {\n f.get();\n return make_ready_future<>();\n } catch (...) {\n \/\/\n \/\/ In case of an error:\n \/\/ - Halt if in the constructor.\n \/\/ - Print an error when reloading.\n \/\/\n if (_state == snitch_state::initializing) {\n logger().error(\"Failed to parse a properties file ({}). Halting...\", _prop_file_name);\n throw;\n } else {\n logger().warn(\"Failed to reload a properties file ({}). Using previous values.\", _prop_file_name);\n return make_ready_future<>();\n }\n }\n });\n}\n\nfuture<> gossiping_property_file_snitch::reload_configuration() {\n \/\/ \"prefer_local\" is FALSE by default\n bool new_prefer_local = false;\n sstring new_dc;\n sstring new_rack;\n\n \/\/ Rack and Data Center have to be defined in the properties file!\n if (!_prop_values.contains(dc_property_key) || !_prop_values.contains(rack_property_key)) {\n throw_incomplete_file();\n }\n\n new_dc = _prop_values[dc_property_key];\n new_rack = _prop_values[rack_property_key];\n\n if (_prop_values.contains(prefer_local_property_key)) {\n if (_prop_values[prefer_local_property_key] == \"false\") {\n new_prefer_local = false;\n } else if (_prop_values[prefer_local_property_key] == \"true\") {\n new_prefer_local = true;\n } else {\n throw_bad_format(\"prefer_local configuration is malformed\");\n }\n }\n\n if (_state == snitch_state::initializing || _my_dc != new_dc ||\n _my_rack != new_rack || _prefer_local != new_prefer_local) {\n\n _my_dc = new_dc;\n _my_rack = new_rack;\n _prefer_local = new_prefer_local;\n\n assert(_my_distributed);\n\n return _my_distributed->invoke_on_all(\n [this] (snitch_ptr& local_s) {\n\n \/\/ Distribute the new values on all CPUs but the current one\n if (this_shard_id() != _file_reader_cpu_id) {\n local_s->set_my_dc(_my_dc);\n local_s->set_my_rack(_my_rack);\n local_s->set_prefer_local(_prefer_local);\n }\n }).then([this] {\n return seastar::async([this] {\n \/\/ reload Gossiper state (executed on CPU0 only)\n _my_distributed->invoke_on(0, [] (snitch_ptr& local_snitch_ptr) {\n return local_snitch_ptr->reload_gossiper_state();\n }).get();\n\n _reconfigured();\n\n \/\/ spread the word...\n _my_distributed->invoke_on(0, [] (snitch_ptr& local_snitch_ptr) {\n if (local_snitch_ptr->local_gossiper_started()) {\n return local_snitch_ptr->gossip_snitch_info({});\n }\n\n return make_ready_future<>();\n }).get();\n });\n });\n }\n\n return make_ready_future<>();\n}\n\nvoid gossiping_property_file_snitch::set_stopped() {\n if (_state == snitch_state::stopping) {\n _state = snitch_state::stopped;\n } else {\n _state = snitch_state::io_paused;\n }\n\n _io_is_stopped.set_value();\n}\n\nfuture<> gossiping_property_file_snitch::stop_io() {\n if (this_shard_id() == _file_reader_cpu_id) {\n _file_reader.cancel();\n\n \/\/ If timer is not running then set the STOPPED state right away.\n if (!_file_reader_runs) {\n set_stopped();\n }\n } else {\n set_stopped();\n }\n\n return _io_is_stopped.get_future();\n}\n\nvoid gossiping_property_file_snitch::resume_io() {\n reset_io_state();\n start_io();\n set_snitch_ready();\n}\n\nvoid gossiping_property_file_snitch::start_io() {\n \/\/ Run a timer only on specific CPU\n if (this_shard_id() == _file_reader_cpu_id) {\n _file_reader.arm(reload_property_file_period());\n }\n}\n\nfuture<> gossiping_property_file_snitch::stop() {\n if (_state == snitch_state::stopped || _state == snitch_state::io_paused) {\n return make_ready_future<>();\n }\n\n _state = snitch_state::stopping;\n\n return stop_io();\n}\n\nfuture<> gossiping_property_file_snitch::pause_io() {\n if (_state == snitch_state::stopped || _state == snitch_state::io_paused) {\n return make_ready_future<>();\n }\n\n _state = snitch_state::io_pausing;\n\n return stop_io();\n}\n\n\/\/ should be invoked of CPU0 only\nfuture<> gossiping_property_file_snitch::reload_gossiper_state() {\n if (!_gossip_started) {\n return make_ready_future<>();\n }\n\n future<> ret = make_ready_future<>();\n if (_reconnectable_helper) {\n ret = gms::get_local_gossiper().unregister_(_reconnectable_helper);\n }\n\n if (!_prefer_local) {\n return ret;\n }\n\n return ret.then([this] {\n _reconnectable_helper = ::make_shared<reconnectable_snitch_helper>(_my_dc);\n gms::get_local_gossiper().register_(_reconnectable_helper);\n });\n}\n\nusing registry_2_params = class_registrator<i_endpoint_snitch,\n gossiping_property_file_snitch,\n const sstring&, unsigned>;\nstatic registry_2_params registrator2(\"org.apache.cassandra.locator.GossipingPropertyFileSnitch\");\n\nusing registry_1_param = class_registrator<i_endpoint_snitch,\n gossiping_property_file_snitch,\n const sstring&>;\nstatic registry_1_param registrator1(\"org.apache.cassandra.locator.GossipingPropertyFileSnitch\");\n\nusing registry_default = class_registrator<i_endpoint_snitch,\n gossiping_property_file_snitch>;\nstatic registry_default registrator_default(\"org.apache.cassandra.locator.GossipingPropertyFileSnitch\");\nstatic registry_default registrator_default_short_name(\"GossipingPropertyFileSnitch\");\n} \/\/ namespace locator\n<commit_msg>property-file snitch: Reload state in .start()<commit_after>\/*\n *\n * Modified by ScyllaDB\n * Copyright (C) 2015-present ScyllaDB\n *\/\n\n\/*\n * SPDX-License-Identifier: (AGPL-3.0-or-later and Apache-2.0)\n *\/\n\n#include \"locator\/gossiping_property_file_snitch.hh\"\n#include \"gms\/versioned_value.hh\"\n#include \"message\/msg_addr.hh\"\n#include \"message\/messaging_service.hh\"\n#include \"gms\/gossiper.hh\"\n\nnamespace locator {\nfuture<bool> gossiping_property_file_snitch::property_file_was_modified() {\n return open_file_dma(_prop_file_name, open_flags::ro)\n .then([this](file f) {\n return do_with(std::move(f), [] (file& f) {\n return f.stat();\n });\n }).then_wrapped([this] (auto&& f) {\n try {\n auto st = f.get0();\n\n if (!_last_file_mod ||\n _last_file_mod->tv_sec != st.st_mtim.tv_sec) {\n _last_file_mod = st.st_mtim;\n return true;\n } else {\n return false;\n }\n } catch (...) {\n logger().error(\"Failed to open {} for read or to get stats\", _prop_file_name);\n throw;\n }\n });\n}\n\ngossiping_property_file_snitch::gossiping_property_file_snitch(\n const sstring& fname, unsigned io_cpuid)\n: production_snitch_base(fname), _file_reader_cpu_id(io_cpuid) {\n if (this_shard_id() == _file_reader_cpu_id) {\n io_cpu_id() = _file_reader_cpu_id;\n }\n}\n\nfuture<> gossiping_property_file_snitch::start() {\n using namespace std::chrono_literals;\n\n _state = snitch_state::initializing;\n\n reset_io_state();\n\n \/\/ Run a timer only on specific CPU\n if (this_shard_id() == _file_reader_cpu_id) {\n \/\/\n \/\/ Here we will create a timer that will read the properties file every\n \/\/ minute and load its contents into the gossiper.endpoint_state_map\n \/\/\n _file_reader.set_callback([this] {\n periodic_reader_callback();\n });\n\n return read_property_file().then([this] {\n start_io();\n set_snitch_ready();\n return make_ready_future<>();\n });\n }\n\n set_snitch_ready();\n return make_ready_future<>();\n}\n\nvoid gossiping_property_file_snitch::periodic_reader_callback() {\n _file_reader_runs = true;\n \/\/FIXME: discarded future.\n (void)property_file_was_modified().then([this] (bool was_modified) {\n\n if (was_modified) {\n return read_property_file();\n }\n\n return make_ready_future<>();\n }).then_wrapped([this] (auto&& f) {\n try {\n f.get();\n } catch (...) {\n logger().error(\"Exception has been thrown when parsing the property file.\");\n }\n\n if (_state == snitch_state::stopping || _state == snitch_state::io_pausing) {\n this->set_stopped();\n } else if (_state != snitch_state::stopped) {\n _file_reader.arm(reload_property_file_period());\n }\n\n _file_reader_runs = false;\n });\n}\n\nfuture<> gossiping_property_file_snitch::gossiper_starting() {\n \/\/\n \/\/ Note: currently gossiper \"main\" instance always runs on CPU0 therefore\n \/\/ this function will be executed on CPU0 only.\n \/\/\n _gossip_started = true;\n return make_ready_future<>();\n}\n\nstd::list<std::pair<gms::application_state, gms::versioned_value>> gossiping_property_file_snitch::get_app_states() const {\n sstring ip = format(\"{}\", gms::get_local_gossiper().get_local_messaging().listen_address());\n return {\n {gms::application_state::DC, gms::versioned_value::datacenter(_my_dc)},\n {gms::application_state::RACK, gms::versioned_value::rack(_my_rack)},\n {gms::application_state::INTERNAL_IP, gms::versioned_value::internal_ip(std::move(ip))},\n };\n}\n\nfuture<> gossiping_property_file_snitch::read_property_file() {\n using namespace exceptions;\n\n return load_property_file().then([this] {\n return reload_configuration();\n }).then_wrapped([this] (auto&& f) {\n try {\n f.get();\n return make_ready_future<>();\n } catch (...) {\n \/\/\n \/\/ In case of an error:\n \/\/ - Halt if in the constructor.\n \/\/ - Print an error when reloading.\n \/\/\n if (_state == snitch_state::initializing) {\n logger().error(\"Failed to parse a properties file ({}). Halting...\", _prop_file_name);\n throw;\n } else {\n logger().warn(\"Failed to reload a properties file ({}). Using previous values.\", _prop_file_name);\n return make_ready_future<>();\n }\n }\n });\n}\n\nfuture<> gossiping_property_file_snitch::reload_configuration() {\n \/\/ \"prefer_local\" is FALSE by default\n bool new_prefer_local = false;\n sstring new_dc;\n sstring new_rack;\n\n \/\/ Rack and Data Center have to be defined in the properties file!\n if (!_prop_values.contains(dc_property_key) || !_prop_values.contains(rack_property_key)) {\n throw_incomplete_file();\n }\n\n new_dc = _prop_values[dc_property_key];\n new_rack = _prop_values[rack_property_key];\n\n if (_prop_values.contains(prefer_local_property_key)) {\n if (_prop_values[prefer_local_property_key] == \"false\") {\n new_prefer_local = false;\n } else if (_prop_values[prefer_local_property_key] == \"true\") {\n new_prefer_local = true;\n } else {\n throw_bad_format(\"prefer_local configuration is malformed\");\n }\n }\n\n if (_state == snitch_state::initializing || _my_dc != new_dc ||\n _my_rack != new_rack || _prefer_local != new_prefer_local) {\n\n _my_dc = new_dc;\n _my_rack = new_rack;\n _prefer_local = new_prefer_local;\n\n assert(_my_distributed);\n\n return _my_distributed->invoke_on_all(\n [this] (snitch_ptr& local_s) {\n\n \/\/ Distribute the new values on all CPUs but the current one\n if (this_shard_id() != _file_reader_cpu_id) {\n local_s->set_my_dc(_my_dc);\n local_s->set_my_rack(_my_rack);\n local_s->set_prefer_local(_prefer_local);\n }\n }).then([this] {\n \/\/ FIXME -- tests don't start gossiper\n if (!gms::get_gossiper().local_is_initialized()) {\n return make_ready_future<>();\n }\n\n return seastar::async([this] {\n \/\/ reload Gossiper state (executed on CPU0 only)\n _my_distributed->invoke_on(0, [] (snitch_ptr& local_snitch_ptr) {\n return local_snitch_ptr->reload_gossiper_state();\n }).get();\n\n _reconfigured();\n\n \/\/ spread the word...\n _my_distributed->invoke_on(0, [] (snitch_ptr& local_snitch_ptr) {\n if (local_snitch_ptr->local_gossiper_started()) {\n return local_snitch_ptr->gossip_snitch_info({});\n }\n\n return make_ready_future<>();\n }).get();\n });\n });\n }\n\n return make_ready_future<>();\n}\n\nvoid gossiping_property_file_snitch::set_stopped() {\n if (_state == snitch_state::stopping) {\n _state = snitch_state::stopped;\n } else {\n _state = snitch_state::io_paused;\n }\n\n _io_is_stopped.set_value();\n}\n\nfuture<> gossiping_property_file_snitch::stop_io() {\n if (this_shard_id() == _file_reader_cpu_id) {\n _file_reader.cancel();\n\n \/\/ If timer is not running then set the STOPPED state right away.\n if (!_file_reader_runs) {\n set_stopped();\n }\n } else {\n set_stopped();\n }\n\n return _io_is_stopped.get_future();\n}\n\nvoid gossiping_property_file_snitch::resume_io() {\n reset_io_state();\n start_io();\n set_snitch_ready();\n}\n\nvoid gossiping_property_file_snitch::start_io() {\n \/\/ Run a timer only on specific CPU\n if (this_shard_id() == _file_reader_cpu_id) {\n _file_reader.arm(reload_property_file_period());\n }\n}\n\nfuture<> gossiping_property_file_snitch::stop() {\n if (_state == snitch_state::stopped || _state == snitch_state::io_paused) {\n return make_ready_future<>();\n }\n\n _state = snitch_state::stopping;\n\n return stop_io();\n}\n\nfuture<> gossiping_property_file_snitch::pause_io() {\n if (_state == snitch_state::stopped || _state == snitch_state::io_paused) {\n return make_ready_future<>();\n }\n\n _state = snitch_state::io_pausing;\n\n return stop_io();\n}\n\n\/\/ should be invoked of CPU0 only\nfuture<> gossiping_property_file_snitch::reload_gossiper_state() {\n future<> ret = make_ready_future<>();\n if (_reconnectable_helper) {\n ret = gms::get_local_gossiper().unregister_(_reconnectable_helper);\n }\n\n if (!_prefer_local) {\n return ret;\n }\n\n return ret.then([this] {\n _reconnectable_helper = ::make_shared<reconnectable_snitch_helper>(_my_dc);\n gms::get_local_gossiper().register_(_reconnectable_helper);\n });\n}\n\nusing registry_2_params = class_registrator<i_endpoint_snitch,\n gossiping_property_file_snitch,\n const sstring&, unsigned>;\nstatic registry_2_params registrator2(\"org.apache.cassandra.locator.GossipingPropertyFileSnitch\");\n\nusing registry_1_param = class_registrator<i_endpoint_snitch,\n gossiping_property_file_snitch,\n const sstring&>;\nstatic registry_1_param registrator1(\"org.apache.cassandra.locator.GossipingPropertyFileSnitch\");\n\nusing registry_default = class_registrator<i_endpoint_snitch,\n gossiping_property_file_snitch>;\nstatic registry_default registrator_default(\"org.apache.cassandra.locator.GossipingPropertyFileSnitch\");\nstatic registry_default registrator_default_short_name(\"GossipingPropertyFileSnitch\");\n} \/\/ namespace locator\n<|endoftext|>"} {"text":"<commit_before>\/*\n addcontactwizard.cpp - Kopete's Add Contact Wizard\n\n Copyright (c) 2002 by Nick Betcher <nbetcher@kde.org>\n Copyright (c) 2002 by Duncan Mac-Vicar Prett <duncan@kde.org>\n\n Kopete (c) 2002 by the Kopete developers <kopete-devel@kde.org>\n\n *************************************************************************\n * *\n * This program is free software; you can redistribute it and\/or modify *\n * it under the terms of the GNU General Public License as published by *\n * the Free Software Foundation; either version 2 of the License, or *\n * (at your option) any later version. *\n * *\n *************************************************************************\n*\/\n\n#include <qlayout.h>\n\n#include <kglobal.h>\n#include <klocale.h>\n#include <kiconloader.h>\n#include <klineeditdlg.h>\n#include <kpushbutton.h>\n#include <kstandarddirs.h>\n\n#include \"addcontactpage.h\"\n#include \"addcontactwizard.h\"\n#include \"kopetegroup.h\"\n#include \"kopetecontactlist.h\"\n#include \"kopeteprotocol.h\"\n#include \"pluginloader.h\"\n#include \"protocolboxitem.h\"\n#include \"kopetemetacontact.h\"\n\nAddContactWizard::AddContactWizard( QWidget *parent, const char *name )\n: AddContactWizard_Base( parent, name )\n{\n\tQStringList groups =KopeteContactList::contactList()->groups().toStringList();\n\n\tQStringList::ConstIterator it = groups.begin();\n\tfor( ; it != groups.end(); ++it )\n\t{\n\t\tQString groupname = *it;\n\n\t\tif ( !groupname.isNull() )\n\t\t\tnew QCheckListItem( groupList, groupname, QCheckListItem::CheckBox);\n\t}\n\n\tint pluginCount = 0;\n\tProtocolBoxItem *pluginItem = 0L;\n\n\tQValueList<KopeteLibraryInfo> l = LibraryLoader::pluginLoader()->loaded();\n\tfor (QValueList<KopeteLibraryInfo>::Iterator i = l.begin(); i != l.end(); ++i)\n\t{\n\/\/\t\tkdDebug() << \"AddContactWizard::AddContactWizard :\" <<(*i).name << \" \" << (*i).specfile <<\"\\n\";\n\t\tKopetePlugin *tmpprot = LibraryLoader::pluginLoader()->searchByName( (*i).name );\n\t\tKopeteProtocol *prot = dynamic_cast<KopeteProtocol*>( tmpprot );\n\n\t\tif (prot)\n\t\t{\n\t\t\tpluginItem = new ProtocolBoxItem( protocolListView, (*i).name );\n\t\t\tpluginItem->protocol = prot;\n\t\t\tpluginCount++;\n\t\t}\n\t}\n\n\tif ( pluginCount == 1 )\n\t\tpluginItem->setOn( true );\n\n\tsetNextEnabled(page3, (pluginCount == 1));\n\tsetFinishEnabled(page4, true);\n\n\tconnect( addGroupButton, SIGNAL(clicked()) , SLOT(slotAddGroupClicked()) );\n\tconnect( protocolListView, SIGNAL(clicked(QListViewItem *)), this, SLOT(slotProtocolListClicked(QListViewItem *)));\n}\n\nAddContactWizard::~AddContactWizard()\n{\n}\n\nvoid AddContactWizard::slotProtocolListClicked( QListViewItem *)\n{\n\t\/\/ Just makes sure a protocol is selected before allowing the user to continue\n\tbool oneIsChecked = false;\n\tfor (QListViewItem *listItem = protocolListView->firstChild(); listItem != 0; listItem = listItem->itemBelow())\n\t{\n\t\tQCheckListItem *check = dynamic_cast<QCheckListItem *>(listItem);\n\t\tif (!check)\n\t\t{\n\t\t\tkdDebug() << \"WARNING : AddContactWizard::slotProtocolListClicked : one listItem is not a CheckListItem\" << endl;\n\t\t}\n\t\telse if (check->isOn())\n\t\t{\n\t\t\toneIsChecked = true;\n\t\t\tbreak;\n\t\t}\n\t}\n\tsetNextEnabled(page3,oneIsChecked);\n}\n\nvoid AddContactWizard::slotGroupListClicked( QListViewItem *)\n{\n\t\/\/top-level contacts are allowed\n\/*\n\tbool oneIsChecked = false;\n\tfor (QListViewItem *listItem = groupList->firstChild(); listItem != 0; listItem = listItem->itemBelow())\n\t{\n\t\tQCheckListItem *check = dynamic_cast<QCheckListItem *>(listItem);\n\t\tif (!check) \n\t\t{\n\t\t\tkdDebug() << \"WARNING : AddContactWizard::slotGroupListClicked : one listItem is not a CheckListItem\" << endl;\n\t\t}\n\t\telse \tif (check->isOn())\n\t\t{\n\t\t\toneIsChecked = true;\n\t\t\tbreak;\n\t\t}\n\t}\n\tsetNextEnabled(page2,oneIsChecked);\n *\/\n}\n\nvoid AddContactWizard::slotAddGroupClicked()\n{\n\tbool ok;\n\tQString groupName = KLineEditDlg::getText(\n\t\ti18n( \"New Group - Kopete\" ),\n\t\ti18n( \"Please enter the name for the new group\" ),\n\t\tQString::null, &ok );\n\n\tif ( !groupName.isNull() && ok)\n\t\tnew QCheckListItem( groupList, groupName, QCheckListItem::CheckBox);\n\n}\n\nvoid AddContactWizard::slotRemoveGroupClicked()\n{\n}\n\nvoid AddContactWizard::accept()\n{\n\tKopeteMetaContact *m=new KopeteMetaContact();\n\n\tfor (QListViewItem *listItem = groupList->firstChild(); listItem != 0; listItem = listItem->itemBelow())\n\t{\n\t\tQCheckListItem *check = dynamic_cast<QCheckListItem *>(listItem);\n\t\tif (!check)\n\t\t{\n\t\t\tkdDebug() << \"WARNING : AddContactWizard::slotGroupListClicked : one listItem is not a CheckListItem\" << endl;\n\t\t}\n\t\telse \tif (check->isOn())\n\t\t{\n\t\t\tm->addToGroup(KopeteContactList::contactList()->getGroup(check->text()));\n\t\t}\n\t}\n\n\t\n\tfor (AddContactPage *ePage = protocolPages.first(); ePage ; ePage = protocolPages.next())\n\t{\n\t\tePage->slotFinish(m); \n\t}\n\tKopeteContactList::contactList()->addMetaContact(m);\n\tdelete(this);\n}\n\nvoid AddContactWizard::next()\n{\n\tif (currentPage() == page3)\n\t{\n\n\t\tfor (AddContactPage *ePage = protocolPages.first(); ePage != 0; ePage = protocolPages.first())\n\t\t{\n\t\t\tprotocolPages.remove(ePage);\n\t\t\tif(ePage) delete ePage;\n\t\t}\n\n\t\t\/\/ We don't keep track of this pointer because it gets deleted when the wizard does (which is what we want)\n\t\tfor (ProtocolBoxItem *item = dynamic_cast<ProtocolBoxItem *>(protocolListView->firstChild()); item != 0; item = dynamic_cast<ProtocolBoxItem *>(item->itemBelow()))\n\t\t{\n\t\t\tif (!item) break; \/\/ this shouldn't happen\n\t\t\tif (item->isOn())\n\t\t\t{\n\t\t\t\tif (!item->protocol) break; \/\/ this shouldn't happen either, but I hate crashes\n\t\t\t\tAddContactPage *addPage = item->protocol->createAddContactWidget(this);\n\t\t\t\tif (!addPage) break;\n\t\t\t\tQString title = i18n( \"The protocol name is prepended here\",\n\t\t\t\t\t\"%1 protocol contact information\" ).arg( item->text() );\n\t\t\t\taddPage->show();\n\t\t\t\tinsertPage(addPage, title, indexOf(page4));\n\t\t\t\tprotocolPages.append(addPage);\n\t\t\t}\n\t\t}\n\t\tQWizard::next();\n\t\treturn;\n\t}\n\tif (currentPage() != page1 && currentPage() != page2 && currentPage() != page3 && currentPage() != page4)\n\t{\n\t\tAddContactPage *ePage = dynamic_cast<AddContactPage *>(currentPage());\n\t\tif (!ePage) return;\n\t\tif (!ePage->validateData())\n\t\t\treturn;\n\t\tQWizard::next();\n\t\treturn;\n\t}\n\tQWizard::next();\n}\n\n#include \"addcontactwizard.moc\"\n\n\/\/ vim: set noet ts=4 sts=4 sw=4:\n\n<commit_msg>Use the plugin list from the plugin loader, not the one returning PluginLoader's internals.<commit_after>\/*\n addcontactwizard.cpp - Kopete's Add Contact Wizard\n\n Copyright (c) 2002 by Nick Betcher <nbetcher@kde.org>\n Copyright (c) 2002 by Duncan Mac-Vicar Prett <duncan@kde.org>\n\n Kopete (c) 2002 by the Kopete developers <kopete-devel@kde.org>\n\n *************************************************************************\n * *\n * This program is free software; you can redistribute it and\/or modify *\n * it under the terms of the GNU General Public License as published by *\n * the Free Software Foundation; either version 2 of the License, or *\n * (at your option) any later version. *\n * *\n *************************************************************************\n*\/\n\n#include <qlayout.h>\n\n#include <kglobal.h>\n#include <klocale.h>\n#include <kiconloader.h>\n#include <klineeditdlg.h>\n#include <kpushbutton.h>\n#include <kstandarddirs.h>\n\n#include \"addcontactpage.h\"\n#include \"addcontactwizard.h\"\n#include \"kopetegroup.h\"\n#include \"kopetecontactlist.h\"\n#include \"kopeteprotocol.h\"\n#include \"pluginloader.h\"\n#include \"protocolboxitem.h\"\n#include \"kopetemetacontact.h\"\n\nAddContactWizard::AddContactWizard( QWidget *parent, const char *name )\n: AddContactWizard_Base( parent, name )\n{\n\tQStringList groups =KopeteContactList::contactList()->groups().toStringList();\n\n\tQStringList::ConstIterator it = groups.begin();\n\tfor( ; it != groups.end(); ++it )\n\t{\n\t\tQString groupname = *it;\n\n\t\tif ( !groupname.isNull() )\n\t\t\tnew QCheckListItem( groupList, groupname, QCheckListItem::CheckBox);\n\t}\n\n\tint pluginCount = 0;\n\tProtocolBoxItem *pluginItem = 0L;\n\n\tQPtrList<KopetePlugin> plugins = LibraryLoader::pluginLoader()->plugins();\n\tfor( KopetePlugin *p = plugins.first() ; p ; p = plugins.next() )\n\t{\n\t\tKopeteProtocol *proto = dynamic_cast<KopeteProtocol*>( p );\n\t\tif( proto )\n\t\t{\n\t\t\tpluginItem = new ProtocolBoxItem( protocolListView, proto->pluginId() );\n\t\t\tpluginItem->protocol = proto;\n\t\t\tpluginCount++;\n\t\t}\n\t}\n\n\tif ( pluginCount == 1 )\n\t\tpluginItem->setOn( true );\n\n\tsetNextEnabled(page3, (pluginCount == 1));\n\tsetFinishEnabled(page4, true);\n\n\tconnect( addGroupButton, SIGNAL(clicked()) , SLOT(slotAddGroupClicked()) );\n\tconnect( protocolListView, SIGNAL(clicked(QListViewItem *)), this, SLOT(slotProtocolListClicked(QListViewItem *)));\n}\n\nAddContactWizard::~AddContactWizard()\n{\n}\n\nvoid AddContactWizard::slotProtocolListClicked( QListViewItem *)\n{\n\t\/\/ Just makes sure a protocol is selected before allowing the user to continue\n\tbool oneIsChecked = false;\n\tfor (QListViewItem *listItem = protocolListView->firstChild(); listItem != 0; listItem = listItem->itemBelow())\n\t{\n\t\tQCheckListItem *check = dynamic_cast<QCheckListItem *>(listItem);\n\t\tif (!check)\n\t\t{\n\t\t\tkdDebug() << \"WARNING : AddContactWizard::slotProtocolListClicked : one listItem is not a CheckListItem\" << endl;\n\t\t}\n\t\telse if (check->isOn())\n\t\t{\n\t\t\toneIsChecked = true;\n\t\t\tbreak;\n\t\t}\n\t}\n\tsetNextEnabled(page3,oneIsChecked);\n}\n\nvoid AddContactWizard::slotGroupListClicked( QListViewItem *)\n{\n\t\/\/top-level contacts are allowed\n\/*\n\tbool oneIsChecked = false;\n\tfor (QListViewItem *listItem = groupList->firstChild(); listItem != 0; listItem = listItem->itemBelow())\n\t{\n\t\tQCheckListItem *check = dynamic_cast<QCheckListItem *>(listItem);\n\t\tif (!check) \n\t\t{\n\t\t\tkdDebug() << \"WARNING : AddContactWizard::slotGroupListClicked : one listItem is not a CheckListItem\" << endl;\n\t\t}\n\t\telse \tif (check->isOn())\n\t\t{\n\t\t\toneIsChecked = true;\n\t\t\tbreak;\n\t\t}\n\t}\n\tsetNextEnabled(page2,oneIsChecked);\n *\/\n}\n\nvoid AddContactWizard::slotAddGroupClicked()\n{\n\tbool ok;\n\tQString groupName = KLineEditDlg::getText(\n\t\ti18n( \"New Group - Kopete\" ),\n\t\ti18n( \"Please enter the name for the new group\" ),\n\t\tQString::null, &ok );\n\n\tif ( !groupName.isNull() && ok)\n\t\tnew QCheckListItem( groupList, groupName, QCheckListItem::CheckBox);\n\n}\n\nvoid AddContactWizard::slotRemoveGroupClicked()\n{\n}\n\nvoid AddContactWizard::accept()\n{\n\tKopeteMetaContact *m=new KopeteMetaContact();\n\n\tfor (QListViewItem *listItem = groupList->firstChild(); listItem != 0; listItem = listItem->itemBelow())\n\t{\n\t\tQCheckListItem *check = dynamic_cast<QCheckListItem *>(listItem);\n\t\tif (!check)\n\t\t{\n\t\t\tkdDebug() << \"WARNING : AddContactWizard::slotGroupListClicked : one listItem is not a CheckListItem\" << endl;\n\t\t}\n\t\telse \tif (check->isOn())\n\t\t{\n\t\t\tm->addToGroup(KopeteContactList::contactList()->getGroup(check->text()));\n\t\t}\n\t}\n\n\t\n\tfor (AddContactPage *ePage = protocolPages.first(); ePage ; ePage = protocolPages.next())\n\t{\n\t\tePage->slotFinish(m); \n\t}\n\tKopeteContactList::contactList()->addMetaContact(m);\n\tdelete(this);\n}\n\nvoid AddContactWizard::next()\n{\n\tif (currentPage() == page3)\n\t{\n\n\t\tfor (AddContactPage *ePage = protocolPages.first(); ePage != 0; ePage = protocolPages.first())\n\t\t{\n\t\t\tprotocolPages.remove(ePage);\n\t\t\tif(ePage) delete ePage;\n\t\t}\n\n\t\t\/\/ We don't keep track of this pointer because it gets deleted when the wizard does (which is what we want)\n\t\tfor (ProtocolBoxItem *item = dynamic_cast<ProtocolBoxItem *>(protocolListView->firstChild()); item != 0; item = dynamic_cast<ProtocolBoxItem *>(item->itemBelow()))\n\t\t{\n\t\t\tif (!item) break; \/\/ this shouldn't happen\n\t\t\tif (item->isOn())\n\t\t\t{\n\t\t\t\tif (!item->protocol) break; \/\/ this shouldn't happen either, but I hate crashes\n\t\t\t\tAddContactPage *addPage = item->protocol->createAddContactWidget(this);\n\t\t\t\tif (!addPage) break;\n\t\t\t\tQString title = i18n( \"The protocol name is prepended here\",\n\t\t\t\t\t\"%1 protocol contact information\" ).arg( item->text() );\n\t\t\t\taddPage->show();\n\t\t\t\tinsertPage(addPage, title, indexOf(page4));\n\t\t\t\tprotocolPages.append(addPage);\n\t\t\t}\n\t\t}\n\t\tQWizard::next();\n\t\treturn;\n\t}\n\tif (currentPage() != page1 && currentPage() != page2 && currentPage() != page3 && currentPage() != page4)\n\t{\n\t\tAddContactPage *ePage = dynamic_cast<AddContactPage *>(currentPage());\n\t\tif (!ePage) return;\n\t\tif (!ePage->validateData())\n\t\t\treturn;\n\t\tQWizard::next();\n\t\treturn;\n\t}\n\tQWizard::next();\n}\n\n#include \"addcontactwizard.moc\"\n\n\/\/ vim: set noet ts=4 sts=4 sw=4:\n\n<|endoftext|>"} {"text":"<commit_before>#undef NDEBUG \/\/because we are using assert to check actual operations that cannot be skipped in release mode testing\n#include <boost\/range\/irange.hpp>\n#include <cassert>\n\n#include <exodus\/program.h>\nprograminit()\n\n\tfunction main() {\n\n\t\/\/ Quit if running under make since there are no tests\n\tif (osgetenv(\"MAKELEVEL\")) {\n\t\tprintl();\n\t\tprintl(\"Test passed - skipped because MAKELEVEL is set\");\n\t\treturn 0;\n\t}\n\n\tprintl();\n\n\tint nn = 1000000;\n\tvar setup_time;\n\n\tbool the_truth_hurts = false;\n\tdouble some_dbl\t\t = 1.1;\n\tchar some_char\t = ' ';\n\n\tprintl(\"Exp: 7 ns Time creation+destruction of unassigned var + test within int loop\");\n\t{\n\t\tvar started = ostime();\n\t\tfor (int ii = 0; ii < nn; ii++) {\n\t\t\tthe_truth_hurts = var().assigned();\n\t\t}\n\t\tsetup_time = ostime() - started;\n\t\tprintl(\"Act:\", round((setup_time) \/ nn * 1E9), \"ns\");\n\t}\n\n\tprintl();\n\n\tprintl(\"Exp: 15 ns - Creation+destruction of string var '12345.67' + test within int loop\");\n\t{\n\t\tvar started = ostime();\n\t\tfor (int ii = 0; ii < nn; ii++) {\n\t\t\tthe_truth_hurts = var(\"12345.67\").assigned();\n\t\t}\n\t\tsetup_time = ostime() - started;\n\t\tprintl(\"Act:\", round((setup_time) \/ nn * 1E9), \"ns\");\n\t}\n\tprintl();\n\n\tprintl(\"Exp: 65 ns - Conversion of string var '12345.67' to double (Using fast_float::from_chars on Ubuntu 20.04\/g++v9.3 and Ubuntu 22.04\/g++v11.2)\");\n\t{\n\t\tvar started = ostime();\n\t\tfor (int ii = 0; ii < nn; ii++) {\n\t\t\tsome_dbl = var(\"12345.67\").toDouble();\n\t\t\t\/\/var(\"12345.67\");\n\t\t}\n\t\tprintl(\"Act:\", round((ostime() - started - setup_time) \/ nn * 1E9), \"ns\");\n\t}\n\n\tprintl();\n\n\tprintl(\"Exp: 6 ns - Creation+destruction of double var 12345.67 + test within int loop\");\n\t{\n\t\tvar started = ostime();\n\t\tfor (int ii = 0; ii < nn; ii++) {\n\t\t\tthe_truth_hurts = var(12367).assigned();\n\t\t}\n\t\tsetup_time = ostime() - started;\n\t\tprintl(\"Act:\", round((setup_time) \/ nn * 1E9), \"ns\");\n\t}\n\tprintl();\n\n\tprintl(\"Exp: 650 ns - Conversion of double var 12345.67 to string and return length (Using RYU D2S on Ubuntu 20.04\/g++v9.3 and std::to_chars on Ubuntu 22.04\/g++v11.2)\");\n\t{\n\t\tvar nn\t\t= 10'000'000;\n\t\tvar started = ostime();\n\t\tfor (int ii = 0; ii < nn; ii++) {\n\t\t\tsome_char = var(12345.67).toChar();\n\t\t}\n\t\tprintl(\"Act:\", round((ostime() - started - setup_time) \/ nn * 1E9), \"ns\");\n\t}\n\n\t\/\/ Test integer loops\n\t{\n\t\tprintl();\n\t\tprintl(\"Testing simple integer for loops\");\n\t\tprintl(\"--------------------------------\");\n\n\t\tint firstcasen = COMMAND.f(2);\n\t\tif (not firstcasen)\n\t\t\tfirstcasen = 0;\n\n\t\tint ncases = 20;\n\n\t\tfor (int casen = firstcasen; casen <= ncases; casen++) {\n\n\t\t\tprintl();\n\t\t\tfor (int repeatn = 0; repeatn < 3; repeatn++) {\n\n\t\t\t\tint nn = 100'000'000;\n\n\t\t\t\tint i1 = 1;\n\t\t\t\t\/\/\t\t\tdouble d1 = 0;\n\t\t\t\t\/\/\t\t\tchar c1 = '\\0';\n\t\t\t\t\/\/\t\t\tchar* cp1 = nullptr;\n\t\t\t\tbool\t\tb1\t= true;\n\t\t\t\tvar\t\t\tv1\t= 1;\n\t\t\t\tstd::string ss1 = \"x\";\n\n\t\t\t\tvar started = ostime();\n\n\t\t\t\tswitch (casen) {\n\n\t\t\t\t\tbreak;\n\t\t\t\t\tcase 0:\n\t\t\t\t\t\tif (repeatn eq 0)\n\t\t\t\t\t\t\tprintl(\"Exp: 35 ns - old var method - for (var;;)\");\n\t\t\t\t\t\tnn = 10'000'000;\n\t\t\t\t\t\tfor (var v2 = 0; v2 <= nn; v2++) {\n\t\t\t\t\t\t\ti1 = v2;\n\t\t\t\t\t\t};\n\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 1:\n\t\t\t\t\t\tif (repeatn eq 0)\n\t\t\t\t\t\t\tprintl(\"Exp: 15 ns - new var method - for (var:range)\");\n\t\t\t\t\t\tfor (const var v2 : range(0 to nn)) {\n\t\t\t\t\t\t\ti1 = v2;\n\t\t\t\t\t\t};\n\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 2:\n\t\t\t\t\t\tif (repeatn eq 0)\n\t\t\t\t\t\t\tprintl(\"Exp: 0.840 ns - old int method - for (int;;)\");\n\t\t\t\t\t\tfor (int i2 = 0; i2 <= nn; i2++) {\n\t\t\t\t\t\t\ti1 = i2;\n\t\t\t\t\t\t};\n\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 3:\n\t\t\t\t\t\tif (repeatn eq 0)\n\t\t\t\t\t\t\tprintl(\"Exp: 0.840 ns - new int method - for (int:range)\");\n\t\t\t\t\t\tfor (int i2 : range(0 to nn)) {\n\t\t\t\t\t\t\ti1 = i2;\n\t\t\t\t\t\t};\n\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 4:\n\t\t\t\t\t\tif (repeatn eq 0)\n\t\t\t\t\t\t\tprintl(\"Exp: 0.840 ns - new int method using boost - for (int:range)\");\n\t\t\t\t\t\tfor (int i2 : boost::irange(0, nn)) {\n\t\t\t\t\t\t\ti1 = i2;\n\t\t\t\t\t\t};\n\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 5:\n\t\t\t\t\t\tif (repeatn eq 0)\n\t\t\t\t\t\t\tprintl(\"Exp: 6.5 ns - construct empty var + test\");\n\t\t\t\t\t\tfor (int i2 = 0; i2 <= nn; i2++) {\n\t\t\t\t\t\t\tvar x;\n\t\t\t\t\t\t\tb1 = x.assigned();\n\t\t\t\t\t\t};\n\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 6:\n\t\t\t\t\t\tif (repeatn eq 0)\n\t\t\t\t\t\t\tprintl(\"Exp: 6.5 ns - construct from int + test\");\n\t\t\t\t\t\tfor (int i2 = 0; i2 <= nn; i2++) {\n\t\t\t\t\t\t\tvar i = 123456;\n\t\t\t\t\t\t\tb1\t = i.assigned();\n\t\t\t\t\t\t};\n\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 7:\n\t\t\t\t\t\tif (repeatn eq 0)\n\t\t\t\t\t\t\tprintl(\"Exp: 6.5 ns - construct from bool + test\");\n\t\t\t\t\t\tfor (int i2 = 0; i2 <= nn; i2++) {\n\t\t\t\t\t\t\tvar b = true;\n\t\t\t\t\t\t\tb1\t = b.assigned();\n\t\t\t\t\t\t};\n\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 8:\n\t\t\t\t\t\tif (repeatn eq 0)\n\t\t\t\t\t\t\tprintl(\"Exp: 6.5 ns - construct from double + test\");\n\t\t\t\t\t\tfor (int i2 = 0; i2 <= nn; i2++) {\n\t\t\t\t\t\t\tvar d = 123.456;\n\t\t\t\t\t\t\tb1\t = d.assigned();\n\t\t\t\t\t\t};\n\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 9:\n\t\t\t\t\t\tif (repeatn eq 0)\n\t\t\t\t\t\t\tprintl(\"Exp: 12 ns - construct from cstr + test\");\n\t\t\t\t\t\tfor (int i2 = 0; i2 <= nn; i2++) {\n\t\t\t\t\t\t\tvar s = \"1\";\n\t\t\t\t\t\t\tb1\t = s.assigned();\n\t\t\t\t\t\t};\n\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 10:\n\t\t\t\t\t\tif (repeatn eq 0)\n\t\t\t\t\t\t\tprintl(\"Exp: 12 ns - construct from char + test\");\n\t\t\t\t\t\tfor (int i2 = 0; i2 <= nn; i2++) {\n\t\t\t\t\t\t\tvar s = '1';\n\t\t\t\t\t\t\tb1\t = s.assigned();\n\t\t\t\t\t\t};\n\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 11:\n\t\t\t\t\t\tif (repeatn eq 0)\n\t\t\t\t\t\t\tprintl(\"Exp: 12 ns - construct from std::string + test\");\n\t\t\t\t\t\tfor (int i2 = 0; i2 <= nn; i2++) {\n\t\t\t\t\t\t\tvar s = ss1;\n\t\t\t\t\t\t\tb1\t = s.assigned();\n\t\t\t\t\t\t};\n\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 12:\n\t\t\t\t\t\tif (repeatn eq 0)\n\t\t\t\t\t\t\tprintl(\"Exp: 4.5 ns - pure test\");\n\t\t\t\t\t\tfor (int i2 = 0; i2 <= nn; i2++) {\n\t\t\t\t\t\t\tb1 = v1.assigned();\n\t\t\t\t\t\t};\n\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 13:\n\t\t\t\t\t\tif (repeatn eq 0)\n\t\t\t\t\t\t\tprintl(\"Exp: 0.9 ns - assign from int\");\n\t\t\t\t\t\tfor (int i2 = 0; i2 <= nn; i2++) {\n\t\t\t\t\t\t\tv1 = 123456;\n\t\t\t\t\t\t};\n\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 14:\n\t\t\t\t\t\tif (repeatn eq 0)\n\t\t\t\t\t\t\tprintl(\"Exp: 0.9 ns - assign from bool\");\n\t\t\t\t\t\tfor (int i2 = 0; i2 <= nn; i2++) {\n\t\t\t\t\t\t\tv1 = true;\n\t\t\t\t\t\t};\n\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 15:\n\t\t\t\t\t\tif (repeatn eq 0)\n\t\t\t\t\t\t\tprintl(\"Exp: 1.3 ns - assign from double\");\n\t\t\t\t\t\tfor (int i2 = 0; i2 <= nn; i2++) {\n\t\t\t\t\t\t\tv1 = 123.456;\n\t\t\t\t\t\t};\n\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 16:\n\t\t\t\t\t\tif (repeatn eq 0)\n\t\t\t\t\t\t\tprintl(\"Exp: 13 ns - assign from cstr\");\n\t\t\t\t\t\tfor (int i2 = 0; i2 <= nn; i2++) {\n\t\t\t\t\t\t\tv1 = \"1\";\n\t\t\t\t\t\t};\n\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 17:\n\t\t\t\t\t\tif (repeatn eq 0)\n\t\t\t\t\t\t\tprintl(\"Exp: 11 ns - assign from char\");\n\t\t\t\t\t\tfor (int i2 = 0; i2 <= nn; i2++) {\n\t\t\t\t\t\t\tv1 = '1';\n\t\t\t\t\t\t};\n\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 18:\n\t\t\t\t\t\tif (repeatn eq 0)\n\t\t\t\t\t\t\tprintl(\"Exp: 11 ns - assign from std::string\");\n\t\t\t\t\t\tfor (int i2 = 0; i2 <= nn; i2++) {\n\t\t\t\t\t\t\tv1 = ss1;\n\t\t\t\t\t\t};\n\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 19:\n\t\t\t\t\t\tif (repeatn eq 0)\n\t\t\t\t\t\t\tprintl(\"Exp: 22 ns - var + int + test\");\n\t\t\t\t\t\tfor (int i2 = 0; i2 <= nn; i2++) {\n\t\t\t\t\t\t\tb1 = (v1 + i2).assigned();\n\t\t\t\t\t\t};\n\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 20:\n\t\t\t\t\t\tif (repeatn eq 0)\n\t\t\t\t\t\t\tprintl(\"Exp: 22 ns - var + 0.1 + test\");\n\t\t\t\t\t\tfor (int i2 = 0; i2 <= nn; i2++) {\n\t\t\t\t\t\t\tb1 = (v1 + 0.1).assigned();\n\t\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\tvar ended = ostime();\n\t\t\t\tif (i1 or b1 or v1)\n\t\t\t\t\tprintl(\"Act:\", ((ended - started) \/ int(nn) * 1e9).round(3), \"ns\");\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/ Ensure optimiser doesnt see as unused\n\tprintl(the_truth_hurts, some_dbl, some_char);\n\n\tprintl();\n\tprintl(elapsedtimetext());\n\tprintl(\"Test passed\");\n\n\treturn 0;\n}\n\nprogramexit()\n<commit_msg>Reduce test_perf loops to avoid timeout when testing in debug mode<commit_after>#undef NDEBUG \/\/because we are using assert to check actual operations that cannot be skipped in release mode testing\n#include <boost\/range\/irange.hpp>\n#include <cassert>\n\n#include <exodus\/program.h>\nprograminit()\n\n\tfunction main() {\n\n\t\/\/ Quit if running under make since there are no tests\n\tif (osgetenv(\"MAKELEVEL\")) {\n\t\tprintl();\n\t\tprintl(\"Test passed - skipped because MAKELEVEL is set\");\n\t\treturn 0;\n\t}\n\n\tprintl();\n\n\tint nn = 1'000'000;\n\tvar setup_time;\n\n\tbool the_truth_hurts = false;\n\tdouble some_dbl\t\t = 1.1;\n\tchar some_char\t = ' ';\n\n\tprintl(\"Exp: 7 ns Time creation+destruction of unassigned var + test within int loop\");\n\t{\n\t\tvar started = ostime();\n\t\tfor (int ii = 0; ii < nn; ii++) {\n\t\t\tthe_truth_hurts = var().assigned();\n\t\t}\n\t\tsetup_time = ostime() - started;\n\t\tprintl(\"Act:\", round((setup_time) \/ nn * 1E9), \"ns\");\n\t}\n\n\tprintl();\n\n\tprintl(\"Exp: 15 ns - Creation+destruction of string var '12345.67' + test within int loop\");\n\t{\n\t\tvar started = ostime();\n\t\tfor (int ii = 0; ii < nn; ii++) {\n\t\t\tthe_truth_hurts = var(\"12345.67\").assigned();\n\t\t}\n\t\tsetup_time = ostime() - started;\n\t\tprintl(\"Act:\", round((setup_time) \/ nn * 1E9), \"ns\");\n\t}\n\tprintl();\n\n\tprintl(\"Exp: 65 ns - Conversion of string var '12345.67' to double (Using fast_float::from_chars on Ubuntu 20.04\/g++v9.3 and Ubuntu 22.04\/g++v11.2)\");\n\t{\n\t\tvar started = ostime();\n\t\tfor (int ii = 0; ii < nn; ii++) {\n\t\t\tsome_dbl = var(\"12345.67\").toDouble();\n\t\t\t\/\/var(\"12345.67\");\n\t\t}\n\t\tprintl(\"Act:\", round((ostime() - started - setup_time) \/ nn * 1E9), \"ns\");\n\t}\n\n\tprintl();\n\n\tprintl(\"Exp: 6 ns - Creation+destruction of double var 12345.67 + test within int loop\");\n\t{\n\t\tvar started = ostime();\n\t\tfor (int ii = 0; ii < nn; ii++) {\n\t\t\tthe_truth_hurts = var(12367).assigned();\n\t\t}\n\t\tsetup_time = ostime() - started;\n\t\tprintl(\"Act:\", round((setup_time) \/ nn * 1E9), \"ns\");\n\t}\n\tprintl();\n\n\tprintl(\"Exp: 650 ns - Conversion of double var 12345.67 to string and return length (Using RYU D2S on Ubuntu 20.04\/g++v9.3 and std::to_chars on Ubuntu 22.04\/g++v11.2)\");\n\t{\n\t\tvar nn\t\t= 100'000;\n\t\tvar started = ostime();\n\t\tfor (int ii = 0; ii < nn; ii++) {\n\t\t\tsome_char = var(12345.67).toChar();\n\t\t}\n\t\tprintl(\"Act:\", round((ostime() - started - setup_time) \/ nn * 1E9), \"ns\");\n\t}\n\n\t\/\/ Test integer loops\n\t{\n\t\tprintl();\n\t\tprintl(\"Testing simple integer for loops\");\n\t\tprintl(\"--------------------------------\");\n\n\t\tint firstcasen = COMMAND.f(2);\n\t\tif (not firstcasen)\n\t\t\tfirstcasen = 0;\n\n\t\tint ncases = 20;\n\n\t\tfor (int casen = firstcasen; casen <= ncases; casen++) {\n\n\t\t\tprintl();\n\t\t\tfor (int repeatn = 0; repeatn < 3; repeatn++) {\n\n\t\t\t\tint nn = 1'000'000;\n\n\t\t\t\tint i1 = 1;\n\t\t\t\t\/\/\t\t\tdouble d1 = 0;\n\t\t\t\t\/\/\t\t\tchar c1 = '\\0';\n\t\t\t\t\/\/\t\t\tchar* cp1 = nullptr;\n\t\t\t\tbool\t\tb1\t= true;\n\t\t\t\tvar\t\t\tv1\t= 1;\n\t\t\t\tstd::string ss1 = \"x\";\n\n\t\t\t\tvar started = ostime();\n\n\t\t\t\tswitch (casen) {\n\n\t\t\t\t\tbreak;\n\t\t\t\t\tcase 0:\n\t\t\t\t\t\tif (repeatn eq 0)\n\t\t\t\t\t\t\tprintl(\"Exp: 35 ns - old var method - for (var;;)\");\n\t\t\t\t\t\tnn = 1'000'000;\n\t\t\t\t\t\tfor (var v2 = 0; v2 <= nn; v2++) {\n\t\t\t\t\t\t\ti1 = v2;\n\t\t\t\t\t\t};\n\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 1:\n\t\t\t\t\t\tif (repeatn eq 0)\n\t\t\t\t\t\t\tprintl(\"Exp: 15 ns - new var method - for (var:range)\");\n\t\t\t\t\t\tfor (const var v2 : range(0 to nn)) {\n\t\t\t\t\t\t\ti1 = v2;\n\t\t\t\t\t\t};\n\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 2:\n\t\t\t\t\t\tif (repeatn eq 0)\n\t\t\t\t\t\t\tprintl(\"Exp: 0.840 ns - old int method - for (int;;)\");\n\t\t\t\t\t\tfor (int i2 = 0; i2 <= nn; i2++) {\n\t\t\t\t\t\t\ti1 = i2;\n\t\t\t\t\t\t};\n\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 3:\n\t\t\t\t\t\tif (repeatn eq 0)\n\t\t\t\t\t\t\tprintl(\"Exp: 0.840 ns - new int method - for (int:range)\");\n\t\t\t\t\t\tfor (int i2 : range(0 to nn)) {\n\t\t\t\t\t\t\ti1 = i2;\n\t\t\t\t\t\t};\n\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 4:\n\t\t\t\t\t\tif (repeatn eq 0)\n\t\t\t\t\t\t\tprintl(\"Exp: 0.840 ns - new int method using boost - for (int:range)\");\n\t\t\t\t\t\tfor (int i2 : boost::irange(0, nn)) {\n\t\t\t\t\t\t\ti1 = i2;\n\t\t\t\t\t\t};\n\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 5:\n\t\t\t\t\t\tif (repeatn eq 0)\n\t\t\t\t\t\t\tprintl(\"Exp: 6.5 ns - construct empty var + test\");\n\t\t\t\t\t\tfor (int i2 = 0; i2 <= nn; i2++) {\n\t\t\t\t\t\t\tvar x;\n\t\t\t\t\t\t\tb1 = x.assigned();\n\t\t\t\t\t\t};\n\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 6:\n\t\t\t\t\t\tif (repeatn eq 0)\n\t\t\t\t\t\t\tprintl(\"Exp: 6.5 ns - construct from int + test\");\n\t\t\t\t\t\tfor (int i2 = 0; i2 <= nn; i2++) {\n\t\t\t\t\t\t\tvar i = 123456;\n\t\t\t\t\t\t\tb1\t = i.assigned();\n\t\t\t\t\t\t};\n\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 7:\n\t\t\t\t\t\tif (repeatn eq 0)\n\t\t\t\t\t\t\tprintl(\"Exp: 6.5 ns - construct from bool + test\");\n\t\t\t\t\t\tfor (int i2 = 0; i2 <= nn; i2++) {\n\t\t\t\t\t\t\tvar b = true;\n\t\t\t\t\t\t\tb1\t = b.assigned();\n\t\t\t\t\t\t};\n\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 8:\n\t\t\t\t\t\tif (repeatn eq 0)\n\t\t\t\t\t\t\tprintl(\"Exp: 6.5 ns - construct from double + test\");\n\t\t\t\t\t\tfor (int i2 = 0; i2 <= nn; i2++) {\n\t\t\t\t\t\t\tvar d = 123.456;\n\t\t\t\t\t\t\tb1\t = d.assigned();\n\t\t\t\t\t\t};\n\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 9:\n\t\t\t\t\t\tif (repeatn eq 0)\n\t\t\t\t\t\t\tprintl(\"Exp: 12 ns - construct from cstr + test\");\n\t\t\t\t\t\tfor (int i2 = 0; i2 <= nn; i2++) {\n\t\t\t\t\t\t\tvar s = \"1\";\n\t\t\t\t\t\t\tb1\t = s.assigned();\n\t\t\t\t\t\t};\n\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 10:\n\t\t\t\t\t\tif (repeatn eq 0)\n\t\t\t\t\t\t\tprintl(\"Exp: 12 ns - construct from char + test\");\n\t\t\t\t\t\tfor (int i2 = 0; i2 <= nn; i2++) {\n\t\t\t\t\t\t\tvar s = '1';\n\t\t\t\t\t\t\tb1\t = s.assigned();\n\t\t\t\t\t\t};\n\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 11:\n\t\t\t\t\t\tif (repeatn eq 0)\n\t\t\t\t\t\t\tprintl(\"Exp: 12 ns - construct from std::string + test\");\n\t\t\t\t\t\tfor (int i2 = 0; i2 <= nn; i2++) {\n\t\t\t\t\t\t\tvar s = ss1;\n\t\t\t\t\t\t\tb1\t = s.assigned();\n\t\t\t\t\t\t};\n\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 12:\n\t\t\t\t\t\tif (repeatn eq 0)\n\t\t\t\t\t\t\tprintl(\"Exp: 4.5 ns - pure test\");\n\t\t\t\t\t\tfor (int i2 = 0; i2 <= nn; i2++) {\n\t\t\t\t\t\t\tb1 = v1.assigned();\n\t\t\t\t\t\t};\n\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 13:\n\t\t\t\t\t\tif (repeatn eq 0)\n\t\t\t\t\t\t\tprintl(\"Exp: 0.9 ns - assign from int\");\n\t\t\t\t\t\tfor (int i2 = 0; i2 <= nn; i2++) {\n\t\t\t\t\t\t\tv1 = 123456;\n\t\t\t\t\t\t};\n\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 14:\n\t\t\t\t\t\tif (repeatn eq 0)\n\t\t\t\t\t\t\tprintl(\"Exp: 0.9 ns - assign from bool\");\n\t\t\t\t\t\tfor (int i2 = 0; i2 <= nn; i2++) {\n\t\t\t\t\t\t\tv1 = true;\n\t\t\t\t\t\t};\n\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 15:\n\t\t\t\t\t\tif (repeatn eq 0)\n\t\t\t\t\t\t\tprintl(\"Exp: 1.3 ns - assign from double\");\n\t\t\t\t\t\tfor (int i2 = 0; i2 <= nn; i2++) {\n\t\t\t\t\t\t\tv1 = 123.456;\n\t\t\t\t\t\t};\n\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 16:\n\t\t\t\t\t\tif (repeatn eq 0)\n\t\t\t\t\t\t\tprintl(\"Exp: 13 ns - assign from cstr\");\n\t\t\t\t\t\tfor (int i2 = 0; i2 <= nn; i2++) {\n\t\t\t\t\t\t\tv1 = \"1\";\n\t\t\t\t\t\t};\n\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 17:\n\t\t\t\t\t\tif (repeatn eq 0)\n\t\t\t\t\t\t\tprintl(\"Exp: 11 ns - assign from char\");\n\t\t\t\t\t\tfor (int i2 = 0; i2 <= nn; i2++) {\n\t\t\t\t\t\t\tv1 = '1';\n\t\t\t\t\t\t};\n\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 18:\n\t\t\t\t\t\tif (repeatn eq 0)\n\t\t\t\t\t\t\tprintl(\"Exp: 11 ns - assign from std::string\");\n\t\t\t\t\t\tfor (int i2 = 0; i2 <= nn; i2++) {\n\t\t\t\t\t\t\tv1 = ss1;\n\t\t\t\t\t\t};\n\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 19:\n\t\t\t\t\t\tif (repeatn eq 0)\n\t\t\t\t\t\t\tprintl(\"Exp: 22 ns - var + int + test\");\n\t\t\t\t\t\tfor (int i2 = 0; i2 <= nn; i2++) {\n\t\t\t\t\t\t\tb1 = (v1 + i2).assigned();\n\t\t\t\t\t\t};\n\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 20:\n\t\t\t\t\t\tif (repeatn eq 0)\n\t\t\t\t\t\t\tprintl(\"Exp: 22 ns - var + 0.1 + test\");\n\t\t\t\t\t\tfor (int i2 = 0; i2 <= nn; i2++) {\n\t\t\t\t\t\t\tb1 = (v1 + 0.1).assigned();\n\t\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\tvar ended = ostime();\n\t\t\t\tif (i1 or b1 or v1)\n\t\t\t\t\tprintl(\"Act:\", ((ended - started) \/ int(nn) * 1e9).round(3), \"ns\");\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/ Ensure optimiser doesnt see as unused\n\tprintl(the_truth_hurts, some_dbl, some_char);\n\n\tprintl();\n\tprintl(elapsedtimetext());\n\tprintl(\"Test passed\");\n\n\treturn 0;\n}\n\nprogramexit()\n<|endoftext|>"} {"text":"<commit_before>\/*\n \/\/ Copyright (c) 2015-2016-2016 Pierre Guillot.\n \/\/ For information on usage and redistribution, and for a DISCLAIMER OF ALL\n \/\/ WARRANTIES, see the file, \"LICENSE.txt,\" in this distribution.\n*\/\n\n#include <iostream>\n#include \"test.hpp\"\nextern \"C\"\n{\n#include \"..\/thread\/src\/thd.h\"\n}\n\n#define XPD_TEST_NLOOP 16\n#define XPD_TEST_NTHD 4\n\nclass instance_tester : private xpd::instance\n{\npublic:\n instance_tester() : m_counter(0ul)\n {\n ;\n }\n \n ~instance_tester()\n {\n if(m_patch)\n {\n xpd::instance::close(m_patch);\n }\n }\n \n bool load(std::string const& name)\n {\n if(m_patch)\n {\n xpd::instance::close(m_patch);\n }\n if(m_tto)\n {\n xpd::instance::unbind(m_tto);\n }\n m_patch = xpd::instance::load(name, \"\");\n if(bool(m_patch))\n {\n char uid[512];\n sprintf(uid, \"%i\", int(m_patch.unique_id()));\n m_tfrom = std::string(uid) + std::string(\"-fromxpd\");\n m_tto = std::string(uid) + std::string(\"-toxpd\");\n xpd::instance::bind(m_tto);\n return true;\n }\n return false;\n }\n \n bool prepare(const int nins, const int nouts, const int samplerate, const int nsamples)\n {\n xpd::instance::prepare(nins, nouts, samplerate, nsamples);\n m_blksize = nsamples;\n return xpd::instance::samplerate() == samplerate;\n }\n \n void send(std::vector<xpd::atom> const& vec)\n {\n xpd::instance::send(m_tfrom, xpd::symbol(\"list\"), vec);\n }\n \n void receive(xpd::tie name, xpd::symbol selector, std::vector<xpd::atom> const& atoms) xpd_final\n {\n m_counter++;\n }\n \n void receive(xpd::console::post const& post) xpd_final\n {\n m_counter++;\n }\n \n size_t counter() const xpd_noexcept\n {\n return m_counter;\n }\n \n static void test(instance_tester* inst)\n {\n inst->m_counter = 0ul;\n for(size_t i = 0; i < XPD_TEST_NLOOP; i++)\n {\n inst->perform(inst->m_blksize, 0, NULL, 0, NULL);\n }\n }\n \nprivate:\n xpd::patch m_patch;\n xpd::tie m_tfrom;\n xpd::tie m_tto;\n size_t m_counter;\n size_t m_blksize;\n};\n\nTEST_CASE(\"instance\", \"[instance]\")\n{\n instance_tester inst[XPD_TEST_NTHD];\n thd_thread thd[XPD_TEST_NTHD];\n \n SECTION(\"post\")\n {\n for(size_t i = 0; i < XPD_TEST_NTHD; ++i)\n {\n REQUIRE(inst[i].load(\"test_post.pd\"));\n REQUIRE(inst[i].prepare(0, 0, 44100, 256));\n thd_thread_detach(thd+i, (thd_thread_method)(&instance_tester::test), inst+i);\n }\n \n for(size_t i = 0; i < XPD_TEST_NTHD; ++i)\n {\n thd_thread_join(thd+i);\n CHECK(inst[i].counter() == XPD_TEST_NLOOP);\n }\n }\n\n SECTION(\"message\")\n {\n std::vector<xpd::atom> vec;\n vec.push_back(1.2f);\n vec.push_back(xpd::symbol(\"zaza\"));\n vec.push_back(xpd::symbol(\"zozo\"));\n for(size_t i = 0; i < XPD_TEST_NTHD; ++i)\n {\n REQUIRE(inst[i].load(\"test_message.pd\"));\n REQUIRE(inst[i].prepare(0, 0, 44100, 256));\n inst[i].send(vec);\n thd_thread_detach(thd+i, (thd_thread_method)(&instance_tester::test), inst+i);\n }\n \n for(size_t i = 0; i < XPD_TEST_NTHD; ++i)\n {\n thd_thread_join(thd+i);\n \/\/CHECK(inst[i].counter() == XPD_TEST_NLOOP);\n }\n }\n}\n\n#undef XPD_TEST_NLOOP\n\n\n\n\n<commit_msg>A faire en rentrant à la maison...<commit_after>\/*\n \/\/ Copyright (c) 2015-2016-2016 Pierre Guillot.\n \/\/ For information on usage and redistribution, and for a DISCLAIMER OF ALL\n \/\/ WARRANTIES, see the file, \"LICENSE.txt,\" in this distribution.\n*\/\n\n#include <iostream>\n#include \"test.hpp\"\nextern \"C\"\n{\n#include \"..\/thread\/src\/thd.h\"\n}\n\n#define XPD_TEST_NLOOP 16\n#define XPD_TEST_NTHD 4\n\nstatic xpd::mutex gmutex;\n\nclass instance_tester : private xpd::instance\n{\npublic:\n instance_tester() : m_npost(0ul), m_nmess(0ul)\n {\n ;\n }\n \n ~instance_tester()\n {\n if(m_patch)\n {\n xpd::instance::close(m_patch);\n }\n }\n \n bool load(std::string const& name)\n {\n if(m_patch)\n {\n xpd::instance::close(m_patch);\n }\n if(m_tto)\n {\n xpd::instance::unbind(m_tto);\n }\n m_patch = xpd::instance::load(name, \"\");\n if(bool(m_patch))\n {\n char uid[512];\n sprintf(uid, \"%i\", int(m_patch.unique_id()));\n m_tfrom = std::string(uid) + std::string(\"-fromxpd\");\n m_tto = std::string(uid) + std::string(\"-toxpd\");\n xpd::instance::bind(m_tto);\n return true;\n }\n return false;\n }\n \n bool prepare(const int nins, const int nouts, const int samplerate, const int nsamples)\n {\n xpd::instance::prepare(nins, nouts, samplerate, nsamples);\n m_blksize = nsamples;\n return xpd::instance::samplerate() == samplerate;\n }\n \n void send(std::vector<xpd::atom> const& vec)\n {\n xpd::instance::send(m_tfrom, xpd::symbol(\"list\"), vec);\n }\n \n void receive(xpd::tie name, xpd::symbol selector, std::vector<xpd::atom> const& atoms) xpd_final\n {\n m_counter++;\n }\n \n void receive(xpd::console::post const& post) xpd_final\n {\n m_counter++;\n }\n \n size_t counter() const xpd_noexcept\n {\n return m_counter;\n }\n \n static void test(instance_tester* inst)\n {\n gmutex.lock();\n for(size_t i = 0; i < XPD_TEST_NLOOP; i++)\n {\n inst->perform(inst->m_blksize, 0, NULL, 0, NULL);\n }\n gmutex.unlock();\n }\n \nprivate:\n xpd::patch m_patch;\n xpd::tie m_tfrom;\n xpd::tie m_tto;\n size_t m_npost;\n size_t m_nmess;\n size_t m_blksize;\n};\n\nTEST_CASE(\"instance\", \"[instance]\")\n{\n instance_tester inst[XPD_TEST_NTHD];\n thd_thread thd[XPD_TEST_NTHD];\n \n SECTION(\"post\")\n {\n for(size_t i = 0; i < XPD_TEST_NTHD; ++i)\n {\n REQUIRE(inst[i].load(\"test_post.pd\"));\n REQUIRE(inst[i].prepare(0, 0, 44100, 256));\n thd_thread_detach(thd+i, (thd_thread_method)(&instance_tester::test), inst+i);\n }\n \n for(size_t i = 0; i < XPD_TEST_NTHD; ++i)\n {\n thd_thread_join(thd+i);\n CHECK(inst[i].counter() == XPD_TEST_NLOOP);\n }\n }\n\n SECTION(\"message\")\n {\n std::vector<xpd::atom> vec;\n vec.push_back(1.2f);\n vec.push_back(xpd::symbol(\"zaza\"));\n vec.push_back(xpd::symbol(\"zozo\"));\n for(size_t i = 0; i < XPD_TEST_NTHD; ++i)\n {\n REQUIRE(inst[i].load(\"test_message.pd\"));\n REQUIRE(inst[i].prepare(0, 0, 44100, 256));\n inst[i].send(vec);\n thd_thread_detach(thd+i, (thd_thread_method)(&instance_tester::test), inst+i);\n }\n \n for(size_t i = 0; i < XPD_TEST_NTHD; ++i)\n {\n \/\/thd_thread_join(thd+i);\n CHECK(inst[i].counter() == XPD_TEST_NLOOP);\n }\n }\n}\n\n#undef XPD_TEST_NLOOP\n\n\n\n\n<|endoftext|>"} {"text":"<commit_before>#include \"catch.hpp\"\n#include \"util.h\"\n#include <shl_exception.h>\n#include <tokenizer.h>\n#include <grammar_loader.h>\n\nusing namespace shl;\n\nTEST_CASE(\"Tokenizer Tests\") {\n Tokenizer tokenizer;\n GrammarLoader loader;\n\n SECTION(\"can load grammar and tokenizer string\") {\n string data = load_string(\"fixture\/hello.json\");\n string source = \"hello world!\";\n Grammar g = loader.load(data);\n auto tokens = tokenizer.tokenize(g, source); \n\n REQUIRE( tokens.size() == 4 );\n REQUIRE( tokens[0].first.substr(source) == source );\n REQUIRE( tokens[0].second.name() == \"source.hello\" );\n\n REQUIRE( tokens[1].first.substr(source) == \"hello\" );\n REQUIRE( tokens[1].second.name() == \"source.hello prefix.hello\" );\n\n REQUIRE( tokens[2].first.substr(source) == \"world!\" );\n REQUIRE( tokens[2].second.name() == \"source.hello suffix.hello\" );\n\n REQUIRE( tokens[3].first.substr(source) == \"!\" );\n REQUIRE( tokens[3].second.name() == \"source.hello suffix.hello emphasis.hello\" );\n }\n\n SECTION(\"return a single token when matches a single pattern with no capture groups\") {\n string data = load_string(\"fixture\/coffee-script.json\");\n string source = \"return\";\n Grammar g = loader.load(data);\n auto tokens = tokenizer.tokenize(g, source); \n\n REQUIRE( tokens.size() == 2 );\n REQUIRE( tokens[1].first.substr(source) == \"return\" );\n REQUIRE( tokens[1].second.name() == \"source.coffee keyword.control.coffee\" );\n }\n\n SECTION(\"return several tokens when matches a single pattern with capture gorups\") {\n string data = load_string(\"fixture\/coffee-script.json\");\n string source = \"new foo.bar.Baz\";\n Grammar g = loader.load(data);\n auto tokens = tokenizer.tokenize(g, source); \n\n REQUIRE( tokens.size() == 4 );\n \n REQUIRE( tokens[1].first.substr(source) == source );\n REQUIRE( tokens[1].second.name() == \"source.coffee meta.class.instance.constructor\" );\n \n REQUIRE( tokens[2].first.substr(source) == \"new\" );\n REQUIRE( tokens[2].second.name() == \"source.coffee meta.class.instance.constructor keyword.operator.new.coffee\" );\n\n REQUIRE( tokens[3].first.substr(source) == \"foo.bar.Baz\" );\n REQUIRE( tokens[3].second.name() == \"source.coffee meta.class.instance.constructor entity.name.type.instance.coffee\" );\n }\n\n SECTION(\"return grammar top level token when no match at all\") {\n string data = load_string(\"fixture\/text.json\");\n string source = \" \";\n Grammar g = loader.load(data);\n auto tokens = tokenizer.tokenize(g, source); \n \n REQUIRE( tokens.size() == 1 );\n\n REQUIRE( tokens[0].first.substr(source) == source );\n REQUIRE( tokens[0].second.name() == \"text.plain\" );\n }\n\n SECTION(\"will throw when scope is not properly closed (i.e. source code is malformed)\") {\n string data = load_string(\"fixture\/c.json\");\n string source = \"int main() {\";\n Grammar g = loader.load(data);\n \n REQUIRE_THROWS_AS(tokenizer.tokenize(g, source), InvalidSourceException);\n }\n\n SECTION(\"will not throw when scope is not properly closed, if OPTION_TOLERATE_ERROR is specified\") {\n string data = load_string(\"fixture\/c.json\");\n string source = \"int main() {\";\n Grammar g = loader.load(data);\n Tokenizer tokenizer(Tokenizer::OPTION_TOLERATE_ERROR);\n \n REQUIRE_NOTHROW(tokenizer.tokenize(g, source));\n }\n\n SECTION(\"the enclosing scope will cover the sub-scopes\") {\n string data = load_string(\"fixture\/coffee-script.json\");\n string source = \" return new foo.bar.Baz \";\n Grammar g = loader.load(data);\n auto tokens = tokenizer.tokenize(g, source); \n\n REQUIRE( tokens.size() == 5 );\n REQUIRE (tokens[0].first.substr(source) == source );\n REQUIRE (tokens[0].second.name() == \"source.coffee\" );\n\n REQUIRE (tokens[1].first.substr(source) == \"return\" );\n REQUIRE (tokens[1].second.name() == \"source.coffee keyword.control.coffee\" );\n\n REQUIRE (tokens[2].first.substr(source) == \"new foo.bar.Baz\" );\n REQUIRE (tokens[2].second.name() == \"source.coffee meta.class.instance.constructor\" );\n\n REQUIRE (tokens[3].first.substr(source) == \"new\" );\n REQUIRE (tokens[3].second.name() == \"source.coffee meta.class.instance.constructor keyword.operator.new.coffee\" );\n\n REQUIRE (tokens[4].first.substr(source) == \"foo.bar.Baz\" );\n REQUIRE (tokens[4].second.name() == \"source.coffee meta.class.instance.constructor entity.name.type.instance.coffee\" );\n }\n\n SECTION(\"only return matched capture groups when match rule has an optional captre groups\") {\n string data = load_string(\"fixture\/coffee-script.json\");\n string source = \"class Foo\";\n Grammar g = loader.load(data);\n auto tokens = tokenizer.tokenize(g, source); \n\n REQUIRE( tokens.size() == 4 );\n\n REQUIRE( tokens[0].first.substr(source) == source ); \n REQUIRE (tokens[0].second.name() == \"source.coffee\" );\n\n REQUIRE( tokens[1].first.substr(source) == source ); \n REQUIRE (tokens[1].second.name() == \"source.coffee meta.class.coffee\" );\n\n REQUIRE( tokens[2].first.substr(source) == \"class\" ); \n REQUIRE (tokens[2].second.name() == \"source.coffee meta.class.coffee storage.type.class.coffee\" );\n\n REQUIRE( tokens[3].first.substr(source) == \"Foo\" ); \n REQUIRE (tokens[3].second.name() == \"source.coffee meta.class.coffee entity.name.type.class.coffee\" );\n }\n}\n<commit_msg>test when capture beyond matched range, and has enclosed capture groups<commit_after>#include \"catch.hpp\"\n#include \"util.h\"\n#include <shl_exception.h>\n#include <tokenizer.h>\n#include <grammar_loader.h>\n\nusing namespace shl;\n\nTEST_CASE(\"Tokenizer Tests\") {\n Tokenizer tokenizer;\n GrammarLoader loader;\n\n SECTION(\"can load grammar and tokenizer string\") {\n string data = load_string(\"fixture\/hello.json\");\n string source = \"hello world!\";\n Grammar g = loader.load(data);\n auto tokens = tokenizer.tokenize(g, source); \n\n REQUIRE( tokens.size() == 4 );\n REQUIRE( tokens[0].first.substr(source) == source );\n REQUIRE( tokens[0].second.name() == \"source.hello\" );\n\n REQUIRE( tokens[1].first.substr(source) == \"hello\" );\n REQUIRE( tokens[1].second.name() == \"source.hello prefix.hello\" );\n\n REQUIRE( tokens[2].first.substr(source) == \"world!\" );\n REQUIRE( tokens[2].second.name() == \"source.hello suffix.hello\" );\n\n REQUIRE( tokens[3].first.substr(source) == \"!\" );\n REQUIRE( tokens[3].second.name() == \"source.hello suffix.hello emphasis.hello\" );\n }\n\n SECTION(\"return a single token when matches a single pattern with no capture groups\") {\n string data = load_string(\"fixture\/coffee-script.json\");\n string source = \"return\";\n Grammar g = loader.load(data);\n auto tokens = tokenizer.tokenize(g, source); \n\n REQUIRE( tokens.size() == 2 );\n REQUIRE( tokens[1].first.substr(source) == \"return\" );\n REQUIRE( tokens[1].second.name() == \"source.coffee keyword.control.coffee\" );\n }\n\n SECTION(\"return several tokens when matches a single pattern with capture gorups\") {\n string data = load_string(\"fixture\/coffee-script.json\");\n string source = \"new foo.bar.Baz\";\n Grammar g = loader.load(data);\n auto tokens = tokenizer.tokenize(g, source); \n\n REQUIRE( tokens.size() == 4 );\n \n REQUIRE( tokens[1].first.substr(source) == source );\n REQUIRE( tokens[1].second.name() == \"source.coffee meta.class.instance.constructor\" );\n \n REQUIRE( tokens[2].first.substr(source) == \"new\" );\n REQUIRE( tokens[2].second.name() == \"source.coffee meta.class.instance.constructor keyword.operator.new.coffee\" );\n\n REQUIRE( tokens[3].first.substr(source) == \"foo.bar.Baz\" );\n REQUIRE( tokens[3].second.name() == \"source.coffee meta.class.instance.constructor entity.name.type.instance.coffee\" );\n }\n\n SECTION(\"return grammar top level token when no match at all\") {\n string data = load_string(\"fixture\/text.json\");\n string source = \" \";\n Grammar g = loader.load(data);\n auto tokens = tokenizer.tokenize(g, source); \n \n REQUIRE( tokens.size() == 1 );\n\n REQUIRE( tokens[0].first.substr(source) == source );\n REQUIRE( tokens[0].second.name() == \"text.plain\" );\n }\n\n SECTION(\"will throw when scope is not properly closed (i.e. source code is malformed)\") {\n string data = load_string(\"fixture\/c.json\");\n string source = \"int main() {\";\n Grammar g = loader.load(data);\n \n REQUIRE_THROWS_AS(tokenizer.tokenize(g, source), InvalidSourceException);\n }\n\n SECTION(\"will not throw when scope is not properly closed, if OPTION_TOLERATE_ERROR is specified\") {\n string data = load_string(\"fixture\/c.json\");\n string source = \"int main() {\";\n Grammar g = loader.load(data);\n Tokenizer tokenizer(Tokenizer::OPTION_TOLERATE_ERROR);\n \n REQUIRE_NOTHROW(tokenizer.tokenize(g, source));\n }\n\n SECTION(\"the enclosing scope will cover the sub-scopes\") {\n string data = load_string(\"fixture\/coffee-script.json\");\n string source = \" return new foo.bar.Baz \";\n Grammar g = loader.load(data);\n auto tokens = tokenizer.tokenize(g, source); \n\n REQUIRE( tokens.size() == 5 );\n REQUIRE (tokens[0].first.substr(source) == source );\n REQUIRE (tokens[0].second.name() == \"source.coffee\" );\n\n REQUIRE (tokens[1].first.substr(source) == \"return\" );\n REQUIRE (tokens[1].second.name() == \"source.coffee keyword.control.coffee\" );\n\n REQUIRE (tokens[2].first.substr(source) == \"new foo.bar.Baz\" );\n REQUIRE (tokens[2].second.name() == \"source.coffee meta.class.instance.constructor\" );\n\n REQUIRE (tokens[3].first.substr(source) == \"new\" );\n REQUIRE (tokens[3].second.name() == \"source.coffee meta.class.instance.constructor keyword.operator.new.coffee\" );\n\n REQUIRE (tokens[4].first.substr(source) == \"foo.bar.Baz\" );\n REQUIRE (tokens[4].second.name() == \"source.coffee meta.class.instance.constructor entity.name.type.instance.coffee\" );\n }\n\n SECTION(\"only return matched capture groups when match rule has an optional captre groups\") {\n string data = load_string(\"fixture\/coffee-script.json\");\n string source = \"class Foo\";\n Grammar g = loader.load(data);\n auto tokens = tokenizer.tokenize(g, source); \n\n REQUIRE( tokens.size() == 4 );\n\n REQUIRE( tokens[0].first.substr(source) == source ); \n REQUIRE (tokens[0].second.name() == \"source.coffee\" );\n\n REQUIRE( tokens[1].first.substr(source) == source ); \n REQUIRE (tokens[1].second.name() == \"source.coffee meta.class.coffee\" );\n\n REQUIRE( tokens[2].first.substr(source) == \"class\" ); \n REQUIRE (tokens[2].second.name() == \"source.coffee meta.class.coffee storage.type.class.coffee\" );\n\n REQUIRE( tokens[3].first.substr(source) == \"Foo\" ); \n REQUIRE (tokens[3].second.name() == \"source.coffee meta.class.coffee entity.name.type.class.coffee\" );\n }\n\n \/* The tokens are sorted in the way similar to the in-order traversal of the AST\n * This holds true even for begin_captures\/end_capture\/captures rules, because \n * capture group themselves have hierarchy. Although capture rules are listed in \n * any order, since we simply apply scope to the captured group in ascending order(0,1...N),\n * we are actually apply in the same way of the in-order traversal.\n *\n * e.g. ((()())()), the capture group number are corresponding to below tree\n * 1\n * \/ \\\n * 2 5\n * \/ \\\n * 3 4\n *\/\n SECTION(\"when capture ranges overlap, ensure parent rule appears ahead of child\") {\n string data = load_string(\"fixture\/coffee-script.json\");\n string source = \" destroy: ->\";\n Grammar g = loader.load(data);\n auto tokens = tokenizer.tokenize(g, source); \n\n REQUIRE( tokens.size() == 6 );\n\n REQUIRE( tokens[0].first.substr(source) == source ); \n REQUIRE(tokens[0].second.name() == \"source.coffee\" );\n\n REQUIRE( tokens[1].first.substr(source) == \"destroy\" ); \n REQUIRE (tokens[1].second.name() == \"source.coffee meta.function.coffee\" );\n\n REQUIRE( tokens[2].first.substr(source) == \"destroy\" ); \n REQUIRE(tokens[2].second.name() == \"source.coffee meta.function.coffee entity.name.function.coffee\" );\n\n REQUIRE( tokens[3].first.substr(source) == \"y\" ); \n REQUIRE(tokens[3].second.name() == \"source.coffee meta.function.coffee entity.name.function.coffee entity.name.function.coffee\" );\n\n REQUIRE( tokens[4].first.substr(source) == \":\" ); \n REQUIRE (tokens[4].second.name() == \"source.coffee keyword.operator.coffee\" );\n\n REQUIRE( tokens[5].first.substr(source) == \"->\" ); \n REQUIRE (tokens[5].second.name() == \"source.coffee storage.type.function.coffee\" );\n }\n\n SECTION(\"when capture beyond the matched range (i.e. capture in a look ahead group)\") {\n string data = load_string(\"fixture\/coffee-script.json\");\n string source = \" destroy: ->\";\n Grammar g = loader.load(data);\n auto tokens = tokenizer.tokenize(g, source); \n\n REQUIRE( tokens.size() == 6 );\n\n \/\/ the scope \"source.coffee meta.function.coffee storage.type.function.coffee\" captures\n \/\/ \"->\", which is beyond the matching range. so ignore it.\n REQUIRE_FALSE( tokens[4].first.substr(source) == \"->\" ); \n REQUIRE_FALSE(tokens[4].second.name() == \"source.coffee meta.function.coffee storage.type.function.coffee\" );\n }\n\n SECTION(\"the enclosed capture group will has one additional ScopeName\") {\n string data = load_string(\"fixture\/coffee-script.json\");\n string source = \" destroy: ->\";\n Grammar g = loader.load(data);\n auto tokens = tokenizer.tokenize(g, source); \n\n REQUIRE( tokens.size() == 6 );\n\n REQUIRE( tokens[2].first.substr(source) == \"destroy\" ); \n REQUIRE(tokens[2].second.name() == \"source.coffee meta.function.coffee entity.name.function.coffee\" );\n\n REQUIRE( tokens[3].first.substr(source) == \"y\" ); \n REQUIRE(tokens[3].second.name() == \"source.coffee meta.function.coffee entity.name.function.coffee entity.name.function.coffee\" );\n\n }\n}\n<|endoftext|>"} {"text":"<commit_before>#include <fstream>\n#include <iostream>\n#include <string>\n\n#include <boost\/property_tree\/xml_parser.hpp>\n#include <boost\/property_tree\/ptree.hpp>\n\nvoid print( boost::property_tree::ptree pt, int indent = 0 ){\n for( auto const & element : pt ){\n if( element.first == \"name\" ){\n auto const xmlAttrs = element.second;\n auto const attrs = xmlAttrs.get_child( \"<xmlattr>\" );\n\n auto const elementName = element.first;\n auto const elementValue = xmlAttrs.get_value< std::string >();\n\n std::cout\n << std::string( indent, ' ' )\n << elementName << \" \" << elementValue\n << std::endl;\n\n for( auto const & attr : attrs ){\n auto const attributeName = attr.first;\n auto const attributeValue = attr.second.get_value< std::string >();\n\n std::cout\n << std::string( indent + 4, ' ' )\n << attributeName << \": \" << attributeValue\n << std::endl;\n }\n }\n else{\n print( element.second, indent + 4 );\n }\n }\n}\n\nint main(){\n std::ifstream input( \".\/xml.xml\" );\n\n boost::property_tree::ptree propertyTree;\n read_xml( input, propertyTree );\n print( propertyTree );\n\n return 0;\n}\n\n<commit_msg>boost\/xml<commit_after>\/*\n * Website:\n * https:\/\/github.com\/wo3kie\/dojo\n *\n * Author:\n * Lukasz Czerwinski\n *\n * Compilation:\n * g++ --std=c++11 xml.cpp -o xml\n *\n * Usage:\n * $ .\/xml\n *\/\n\n#include <fstream>\n#include <iostream>\n#include <string>\n\n#include <boost\/property_tree\/xml_parser.hpp>\n#include <boost\/property_tree\/ptree.hpp>\n\nvoid print( boost::property_tree::ptree pt, int indent = 0 ){\n for( auto const & element : pt ){\n if( element.first == \"name\" ){\n auto const xmlAttrs = element.second;\n auto const attrs = xmlAttrs.get_child( \"<xmlattr>\" );\n\n auto const elementName = element.first;\n auto const elementValue = xmlAttrs.get_value< std::string >();\n\n std::cout\n << std::string( indent, ' ' )\n << elementName << \" \" << elementValue\n << std::endl;\n\n for( auto const & attr : attrs ){\n auto const attributeName = attr.first;\n auto const attributeValue = attr.second.get_value< std::string >();\n\n std::cout\n << std::string( indent + 4, ' ' )\n << attributeName << \": \" << attributeValue\n << std::endl;\n }\n }\n else if( element.first == \"doc\" ){\n std::cout\n << std::string( indent, ' ' )\n << element.first\n << std::endl;\n }\n \n print( element.second, indent + 4 );\n }\n}\n\nint main(){\n std::ifstream input( \".\/xml.xml\" );\n\n boost::property_tree::ptree propertyTree;\n read_xml( input, propertyTree );\n print( propertyTree );\n\n return 0;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: splash.cxx,v $\n *\n * $Revision: 1.2 $\n *\n * last change: $Author: hr $ $Date: 2003-03-25 13:52:50 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#include \"splash.hxx\"\n\n#ifndef _UTL_BOOTSTRAP_HXX\n#include <unotools\/bootstrap.hxx>\n#endif\n#ifndef _VOS_PROCESS_HXX_\n#include <vos\/process.hxx>\n#endif\n#ifndef _URLOBJ_HXX\n#include <tools\/urlobj.hxx>\n#endif\n#ifndef _STREAM_HXX\n#include <tools\/stream.hxx>\n#endif\n#ifndef _SFX_HRC\n#include <sfx2\/sfx.hrc>\n#endif\n#ifndef _SV_SVAPP_HXX\n#include <vcl\/svapp.hxx>\n#endif\n\nusing namespace ::rtl;\nusing namespace ::com::sun::star::registry;\n\nnamespace desktop\n{\n\nSplashScreen::SplashScreen(const Reference< XMultiServiceFactory >& rSMgr)\n :\n IntroWindow()\n , _iProgress(0)\n , _iMax(100)\n , _bPaintBitmap(sal_True)\n , _bPaintProgress(sal_False)\n , _xoffset(12)\n , _yoffset(16)\n , _barheight(6)\n , _barspace(2)\n{\n _rFactory = rSMgr;\n\n initBitmap();\n Size aSize = _aIntroBmp.GetSizePixel();\n SetOutputSizePixel( aSize );\n _height = aSize.Height();\n _width = aSize.Width();\n _tlx = _xoffset; \/\/ top-left x\n _tly = _height - _yoffset; \/\/ top-left y\n _barwidth = _width - (2*_yoffset);\n Application::AddEventListener(\n LINK( this, SplashScreen, AppEventListenerHdl ) );\n}\n\nSplashScreen::~SplashScreen()\n{\n Application::RemoveEventListener(\n LINK( this, SplashScreen, AppEventListenerHdl ) );\n Hide();\n}\n\nvoid SAL_CALL SplashScreen::start(const OUString& aText, sal_Int32 nRange)\n throw (RuntimeException)\n{\n _iMax = nRange;\n if (_bVisible) {\n ::vos::OGuard aSolarGuard( Application::GetSolarMutex() );\n Show();\n Paint(Rectangle());\n }\n}\nvoid SAL_CALL SplashScreen::end()\n throw (RuntimeException)\n{\n _iProgress = _iMax;\n updateStatus();\n if (_bVisible) Hide();\n}\nvoid SAL_CALL SplashScreen::reset()\n throw (RuntimeException)\n{\n _iProgress = 0;\n updateStatus();\n}\n\nvoid SAL_CALL SplashScreen::setText(const OUString& aText)\n throw (RuntimeException)\n{\n}\n\nvoid SAL_CALL SplashScreen::setValue(sal_Int32 nValue)\n throw (RuntimeException)\n{\n ::vos::OGuard aSolarGuard( Application::GetSolarMutex() );\n\n if (nValue >= _iMax) _iProgress = _iMax;\n else _iProgress = nValue;\n updateStatus();\n}\n\n\/\/ XInitialize\nvoid SAL_CALL\nSplashScreen::initialize( const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any>& aArguments )\n throw (RuntimeException)\n{\n ::osl::ClearableMutexGuard aGuard( _aMutex );\n if (aArguments.getLength() > 0)\n aArguments[0] >>= _bVisible;\n}\n\nvoid SplashScreen::updateStatus()\n{\n if (!_bVisible) return;\n if (!_bPaintProgress) _bPaintProgress = sal_True;\n _bPaintBitmap=sal_False;\n Paint(Rectangle());\n _bPaintBitmap=sal_True;\n}\n\n\/\/ internal private methods\nIMPL_LINK( SplashScreen, AppEventListenerHdl, VclWindowEvent *, inEvent )\n{\n if ( inEvent != 0 )\n {\n switch ( inEvent->GetId() )\n {\n case VCLEVENT_WINDOW_HIDE:\n Paint( Rectangle() );\n break;\n default:\n break;\n }\n }\n return 0;\n}\n\nvoid SplashScreen::initBitmap()\n{\n String aBmpFileName;\n OUString aIniPath;\n OUString aLogo( RTL_CONSTASCII_USTRINGPARAM( \"1\" ) );\n aLogo = ::utl::Bootstrap::getLogoData( aLogo );\n sal_Bool bLogo = (sal_Bool)aLogo.toInt32();\n if ( bLogo )\n {\n xub_StrLen nIndex = 0;\n aBmpFileName += String( DEFINE_CONST_UNICODE(\"intro.bmp\") );\n \/\/ retrieve our current installation path\n OUString aExecutePath;\n ::vos::OStartupInfo().getExecutableFile( aExecutePath );\n sal_uInt32 lastIndex = aExecutePath.lastIndexOf('\/');\n if ( lastIndex > 0 )\n aExecutePath = aExecutePath.copy( 0, lastIndex+1 );\n INetURLObject aObj( aExecutePath, INET_PROT_FILE );\n aObj.insertName( aBmpFileName );\n SvFileStream aStrm( aObj.PathToFileName(), STREAM_STD_READ );\n if ( !aStrm.GetError() )\n {\n \/\/ Default case, we load the intro bitmap from a seperate file\n \/\/ (e.g. staroffice_intro.bmp or starsuite_intro.bmp)\n aStrm >> _aIntroBmp;\n }\n else\n {\n \/\/ Save case:\n \/\/ Create resource manager for intro bitmap. Due to our problem that we don't have\n \/\/ any language specific information, we have to search for the correct resource\n \/\/ file. The bitmap resource is language independent.\n const USHORT nResId = RID_DEFAULTINTRO;\n LanguageType aLanguageType;\n String aMgrName = String::CreateFromAscii( \"iso\" );\n aMgrName += String::CreateFromInt32(SUPD); \/\/ current build version\n ResMgr* pLabelResMgr = ResMgr::SearchCreateResMgr( U2S( aMgrName ), aLanguageType );\n ResId aIntroBmpRes( nResId, pLabelResMgr );\n _aIntroBmp = Bitmap( aIntroBmpRes );\n delete pLabelResMgr;\n }\n }\n}\n\nvoid SplashScreen::Paint( const Rectangle& )\n{\n if(!_bVisible) return;\n \/\/ draw bitmap\n if (_bPaintBitmap)\n DrawBitmap( Point(), _aIntroBmp );\n\n if (_bPaintProgress) {\n \/\/ draw progress...\n long length = (_iProgress * _barwidth \/ _iMax) - (2 * _barspace);\n if (length < 0) length = 0;\n const Color cBlue(COL_BLUE);\n const Color cGray(COL_LIGHTGRAY);\n\n \/\/ border\n SetFillColor();\n SetLineColor(cGray);\n DrawRect(Rectangle(_tlx, _tly, _tlx+_barwidth,\n _tly+_barheight));\n\n \/\/ progress bar\n SetFillColor(cBlue);\n SetLineColor();\n DrawRect(Rectangle(_tlx+_barspace, _tly+_barspace,\n _tlx+_barspace+length, _tly+_barheight-_barspace));\n }\n Flush();\n}\n\n\n\/\/ get service instance...\nSplashScreen *SplashScreen::_pINSTANCE = NULL;\nosl::Mutex SplashScreen::_aMutex;\n\nReference< XInterface > SplashScreen::getInstance(const Reference< XMultiServiceFactory >& rSMgr)\n{\n if ( _pINSTANCE == 0 )\n {\n osl::MutexGuard guard(_aMutex);\n if (_pINSTANCE == 0)\n return (XComponent*)new SplashScreen(rSMgr);\n }\n\n return (XComponent*)0;\n}\n\n\/\/ static service info...\nconst sal_Char *SplashScreen::serviceName = \"com.sun.star.office.SplashScreen\";\nconst sal_Char *SplashScreen::implementationName = \"com.sun.star.office.comp.SplashScreen\";\nconst sal_Char *SplashScreen::supportedServiceNames[] = {\"com.sun.star.office.SplashScreen\", NULL};\nOUString SplashScreen::impl_getImplementationName()\n{\n return OUString::createFromAscii(implementationName);\n}\nSequence<OUString> SplashScreen::impl_getSupportedServiceNames()\n{\n Sequence<OUString> aSequence;\n for (int i=0; supportedServiceNames[i]!=NULL; i++) {\n aSequence.realloc(i+1);\n aSequence[i]=(OUString::createFromAscii(supportedServiceNames[i]));\n }\n return aSequence;\n}\n\n}\n\n\/\/ component management stuff...\n\/\/ ----------------------------------------------------------------------------\nextern \"C\"\n{\nusing namespace desktop;\n\nvoid SAL_CALL\ncomponent_getImplementationEnvironment(const sal_Char **ppEnvironmentTypeName, uno_Environment **ppEnvironment)\n{\n *ppEnvironmentTypeName = CPPU_CURRENT_LANGUAGE_BINDING_NAME ;\n}\n\nsal_Bool SAL_CALL\ncomponent_writeInfo(void *pServiceManager, void *pRegistryKey)\n{\n Reference< XMultiServiceFactory > xMan(reinterpret_cast< XMultiServiceFactory* >(pServiceManager));\n Reference< XRegistryKey > xKey(reinterpret_cast< XRegistryKey* >(pRegistryKey));\n\n \/\/ register service\n ::rtl::OUString aTempStr;\n ::rtl::OUString aImpl(RTL_CONSTASCII_USTRINGPARAM(\"\/\"));\n aImpl += SplashScreen::impl_getImplementationName();\n aImpl += ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(\"\/UNO\/SERVICES\"));\n Reference< XRegistryKey > xNewKey = xKey->createKey(aImpl);\n xNewKey->createKey(SplashScreen::impl_getSupportedServiceNames()[0]);\n\n return sal_True;\n}\n\nvoid * SAL_CALL\ncomponent_getFactory(const sal_Char *pImplementationName, void *pServiceManager, void *pRegistryKey)\n{\n void* pReturn = NULL ;\n if ( pImplementationName && pServiceManager )\n {\n \/\/ Define variables which are used in following macros.\n Reference< XSingleServiceFactory > xFactory ;\n Reference< XMultiServiceFactory > xServiceManager(\n reinterpret_cast< XMultiServiceFactory* >(pServiceManager));\n\n if (desktop::SplashScreen::impl_getImplementationName().compareToAscii( pImplementationName ) == COMPARE_EQUAL )\n {\n xFactory = Reference< XSingleServiceFactory >(\n cppu::createOneInstanceFactory(\n xServiceManager, SplashScreen::impl_getImplementationName(),\n SplashScreen::getInstance, SplashScreen::impl_getSupportedServiceNames()));\n }\n\n \/\/ Factory is valid - service was found.\n if ( xFactory.is() )\n {\n xFactory->acquire();\n pReturn = xFactory.get();\n }\n }\n\n \/\/ Return with result of this operation.\n return pReturn ;\n}\n\n} \/\/ extern \"C\"\n<commit_msg>INTEGRATION: CWS os9 (1.2.18); FILE MERGED 2003\/04\/29 16:20:38 lo 1.2.18.1: typo<commit_after>\/*************************************************************************\n *\n * $RCSfile: splash.cxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: vg $ $Date: 2003-05-22 08:55:34 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#include \"splash.hxx\"\n\n#ifndef _UTL_BOOTSTRAP_HXX\n#include <unotools\/bootstrap.hxx>\n#endif\n#ifndef _VOS_PROCESS_HXX_\n#include <vos\/process.hxx>\n#endif\n#ifndef _URLOBJ_HXX\n#include <tools\/urlobj.hxx>\n#endif\n#ifndef _STREAM_HXX\n#include <tools\/stream.hxx>\n#endif\n#ifndef _SFX_HRC\n#include <sfx2\/sfx.hrc>\n#endif\n#ifndef _SV_SVAPP_HXX\n#include <vcl\/svapp.hxx>\n#endif\n\nusing namespace ::rtl;\nusing namespace ::com::sun::star::registry;\n\nnamespace desktop\n{\n\nSplashScreen::SplashScreen(const Reference< XMultiServiceFactory >& rSMgr)\n :\n IntroWindow()\n , _iProgress(0)\n , _iMax(100)\n , _bPaintBitmap(sal_True)\n , _bPaintProgress(sal_False)\n , _xoffset(12)\n , _yoffset(16)\n , _barheight(6)\n , _barspace(2)\n{\n _rFactory = rSMgr;\n\n initBitmap();\n Size aSize = _aIntroBmp.GetSizePixel();\n SetOutputSizePixel( aSize );\n _height = aSize.Height();\n _width = aSize.Width();\n _tlx = _xoffset; \/\/ top-left x\n _tly = _height - _yoffset; \/\/ top-left y\n _barwidth = _width - (2*_yoffset);\n Application::AddEventListener(\n LINK( this, SplashScreen, AppEventListenerHdl ) );\n}\n\nSplashScreen::~SplashScreen()\n{\n Application::RemoveEventListener(\n LINK( this, SplashScreen, AppEventListenerHdl ) );\n Hide();\n}\n\nvoid SAL_CALL SplashScreen::start(const OUString& aText, sal_Int32 nRange)\n throw (RuntimeException)\n{\n _iMax = nRange;\n if (_bVisible) {\n ::vos::OGuard aSolarGuard( Application::GetSolarMutex() );\n Show();\n Paint(Rectangle());\n }\n}\nvoid SAL_CALL SplashScreen::end()\n throw (RuntimeException)\n{\n _iProgress = _iMax;\n updateStatus();\n if (_bVisible) Hide();\n}\nvoid SAL_CALL SplashScreen::reset()\n throw (RuntimeException)\n{\n _iProgress = 0;\n updateStatus();\n}\n\nvoid SAL_CALL SplashScreen::setText(const OUString& aText)\n throw (RuntimeException)\n{\n}\n\nvoid SAL_CALL SplashScreen::setValue(sal_Int32 nValue)\n throw (RuntimeException)\n{\n ::vos::OGuard aSolarGuard( Application::GetSolarMutex() );\n\n if (nValue >= _iMax) _iProgress = _iMax;\n else _iProgress = nValue;\n updateStatus();\n}\n\n\/\/ XInitialize\nvoid SAL_CALL\nSplashScreen::initialize( const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any>& aArguments )\n throw (RuntimeException)\n{\n ::osl::ClearableMutexGuard aGuard( _aMutex );\n if (aArguments.getLength() > 0)\n aArguments[0] >>= _bVisible;\n}\n\nvoid SplashScreen::updateStatus()\n{\n if (!_bVisible) return;\n if (!_bPaintProgress) _bPaintProgress = sal_True;\n _bPaintBitmap=sal_False;\n Paint(Rectangle());\n _bPaintBitmap=sal_True;\n}\n\n\/\/ internal private methods\nIMPL_LINK( SplashScreen, AppEventListenerHdl, VclWindowEvent *, inEvent )\n{\n if ( inEvent != 0 )\n {\n switch ( inEvent->GetId() )\n {\n case VCLEVENT_WINDOW_HIDE:\n Paint( Rectangle() );\n break;\n default:\n break;\n }\n }\n return 0;\n}\n\nvoid SplashScreen::initBitmap()\n{\n String aBmpFileName;\n OUString aIniPath;\n OUString aLogo( RTL_CONSTASCII_USTRINGPARAM( \"1\" ) );\n aLogo = ::utl::Bootstrap::getLogoData( aLogo );\n sal_Bool bLogo = (sal_Bool)aLogo.toInt32();\n if ( bLogo )\n {\n xub_StrLen nIndex = 0;\n aBmpFileName += String( DEFINE_CONST_UNICODE(\"intro.bmp\") );\n \/\/ retrieve our current installation path\n OUString aExecutePath;\n ::vos::OStartupInfo().getExecutableFile( aExecutePath );\n sal_uInt32 lastIndex = aExecutePath.lastIndexOf('\/');\n if ( lastIndex > 0 )\n aExecutePath = aExecutePath.copy( 0, lastIndex+1 );\n INetURLObject aObj( aExecutePath, INET_PROT_FILE );\n aObj.insertName( aBmpFileName );\n SvFileStream aStrm( aObj.PathToFileName(), STREAM_STD_READ );\n if ( !aStrm.GetError() )\n {\n \/\/ Default case, we load the intro bitmap from a seperate file\n \/\/ (e.g. staroffice_intro.bmp or starsuite_intro.bmp)\n aStrm >> _aIntroBmp;\n }\n else\n {\n \/\/ Save case:\n \/\/ Create resource manager for intro bitmap. Due to our problem that we don't have\n \/\/ any language specific information, we have to search for the correct resource\n \/\/ file. The bitmap resource is language independent.\n const USHORT nResId = RID_DEFAULTINTRO;\n LanguageType aLanguageType;\n String aMgrName = String::CreateFromAscii( \"iso\" );\n aMgrName += String::CreateFromInt32(SUPD); \/\/ current build version\n ResMgr* pLabelResMgr = ResMgr::SearchCreateResMgr( U2S( aMgrName ), aLanguageType );\n ResId aIntroBmpRes( nResId, pLabelResMgr );\n _aIntroBmp = Bitmap( aIntroBmpRes );\n delete pLabelResMgr;\n }\n }\n}\n\nvoid SplashScreen::Paint( const Rectangle& )\n{\n if(!_bVisible) return;\n \/\/ draw bitmap\n if (_bPaintBitmap)\n DrawBitmap( Point(), _aIntroBmp );\n\n if (_bPaintProgress) {\n \/\/ draw progress...\n long length = (_iProgress * _barwidth \/ _iMax) - (2 * _barspace);\n if (length < 0) length = 0;\n const Color cBlue(COL_BLUE);\n const Color cGray(COL_LIGHTGRAY);\n\n \/\/ border\n SetFillColor();\n SetLineColor(cGray);\n DrawRect(Rectangle(_tlx, _tly, _tlx+_barwidth,\n _tly+_barheight));\n\n \/\/ progress bar\n SetFillColor(cBlue);\n SetLineColor();\n DrawRect(Rectangle(_tlx+_barspace, _tly+_barspace,\n _tlx+_barspace+length, _tly+_barheight-_barspace));\n }\n Flush();\n}\n\n\n\/\/ get service instance...\nSplashScreen *SplashScreen::_pINSTANCE = NULL;\nosl::Mutex SplashScreen::_aMutex;\n\nReference< XInterface > SplashScreen::getInstance(const Reference< XMultiServiceFactory >& rSMgr)\n{\n if ( _pINSTANCE == 0 )\n {\n osl::MutexGuard guard(_aMutex);\n if (_pINSTANCE == 0)\n return (XComponent*)new SplashScreen(rSMgr);\n }\n\n return (XComponent*)0;\n}\n\n\/\/ static service info...\nconst sal_Char *SplashScreen::serviceName = \"com.sun.star.office.SplashScreen\";\nconst sal_Char *SplashScreen::implementationName = \"com.sun.star.office.comp.SplashScreen\";\nconst sal_Char *SplashScreen::supportedServiceNames[] = {\"com.sun.star.office.SplashScreen\", NULL};\nOUString SplashScreen::impl_getImplementationName()\n{\n return OUString::createFromAscii(implementationName);\n}\nSequence<OUString> SplashScreen::impl_getSupportedServiceNames()\n{\n Sequence<OUString> aSequence;\n for (int i=0; supportedServiceNames[i]!=NULL; i++) {\n aSequence.realloc(i+1);\n aSequence[i]=(OUString::createFromAscii(supportedServiceNames[i]));\n }\n return aSequence;\n}\n\n}\n\n\/\/ component management stuff...\n\/\/ ----------------------------------------------------------------------------\nextern \"C\"\n{\nusing namespace desktop;\n\nvoid SAL_CALL\ncomponent_getImplementationEnvironment(const sal_Char **ppEnvironmentTypeName, uno_Environment **ppEnvironment)\n{\n *ppEnvironmentTypeName = CPPU_CURRENT_LANGUAGE_BINDING_NAME ;\n}\n\nsal_Bool SAL_CALL\ncomponent_writeInfo(void *pServiceManager, void *pRegistryKey)\n{\n Reference< XMultiServiceFactory > xMan(reinterpret_cast< XMultiServiceFactory* >(pServiceManager));\n Reference< XRegistryKey > xKey(reinterpret_cast< XRegistryKey* >(pRegistryKey));\n\n \/\/ register service\n ::rtl::OUString aTempStr;\n ::rtl::OUString aImpl(RTL_CONSTASCII_USTRINGPARAM(\"\/\"));\n aImpl += SplashScreen::impl_getImplementationName();\n aImpl += ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(\"\/UNO\/SERVICES\"));\n Reference< XRegistryKey > xNewKey = xKey->createKey(aImpl);\n xNewKey->createKey(SplashScreen::impl_getSupportedServiceNames()[0]);\n\n return sal_True;\n}\n\nvoid * SAL_CALL\ncomponent_getFactory(const sal_Char *pImplementationName, void *pServiceManager, void *pRegistryKey)\n{\n void* pReturn = NULL ;\n if ( pImplementationName && pServiceManager )\n {\n \/\/ Define variables which are used in following macros.\n Reference< XSingleServiceFactory > xFactory;\n Reference< XMultiServiceFactory > xServiceManager(\n reinterpret_cast< XMultiServiceFactory* >(pServiceManager));\n\n if (desktop::SplashScreen::impl_getImplementationName().compareToAscii( pImplementationName ) == COMPARE_EQUAL )\n {\n xFactory = Reference< XSingleServiceFactory >(\n cppu::createOneInstanceFactory(\n xServiceManager, SplashScreen::impl_getImplementationName(),\n SplashScreen::getInstance, SplashScreen::impl_getSupportedServiceNames()));\n }\n\n \/\/ Factory is valid - service was found.\n if ( xFactory.is() )\n {\n xFactory->acquire();\n pReturn = xFactory.get();\n }\n }\n\n \/\/ Return with result of this operation.\n return pReturn ;\n}\n\n} \/\/ extern \"C\"\n<|endoftext|>"} {"text":"<commit_before>#ifndef ITER_ZIP_HPP_\n#define ITER_ZIP_HPP_\n\n#include \"internal\/iterbase.hpp\"\n\n#include <iterator>\n#include <tuple>\n#include <utility>\n\nnamespace iter {\n namespace impl {\n template <typename... RestContainers>\n class Zipped;\n\n template <typename Container, typename... RestContainers>\n class Zipped<Container, RestContainers...>;\n\n template <>\n class Zipped<>;\n }\n\n template <typename... Containers>\n impl::Zipped<Containers...> zip(Containers&&...);\n}\n\n\/\/ specialization for at least 1 template argument\ntemplate <typename Container, typename... RestContainers>\nclass iter::impl::Zipped<Container, RestContainers...> {\n using ZipIterDeref =\n std::tuple<iterator_deref<Container>, iterator_deref<RestContainers>...>;\n\n friend Zipped iter::zip<Container, RestContainers...>(\n Container&&, RestContainers&&...);\n\n template <typename...>\n friend class Zipped;\n\n private:\n Container container;\n Zipped<RestContainers...> rest_zipped;\n Zipped(Container&& in_container, RestContainers&&... rest)\n : container(std::forward<Container>(in_container)),\n rest_zipped{std::forward<RestContainers>(rest)...} {}\n\n public:\n class Iterator : public std::iterator<std::input_iterator_tag, ZipIterDeref> {\n private:\n using RestIter = typename Zipped<RestContainers...>::Iterator;\n\n iterator_type<Container> iter;\n RestIter rest_iter;\n\n public:\n constexpr static const bool is_base_iter = false;\n Iterator(iterator_type<Container>&& it, RestIter&& rest)\n : iter{std::move(it)}, rest_iter{std::move(rest)} {}\n\n Iterator& operator++() {\n ++this->iter;\n ++this->rest_iter;\n return *this;\n }\n\n Iterator operator++(int) {\n auto ret = *this;\n ++*this;\n return ret;\n }\n\n bool operator!=(const Iterator& other) const {\n return this->iter != other.iter\n && (RestIter::is_base_iter || this->rest_iter != other.rest_iter);\n }\n\n bool operator==(const Iterator& other) const {\n return !(*this != other);\n }\n\n auto operator*() -> decltype(std::tuple_cat(\n std::tuple<iterator_deref<Container>>{*this->iter}, *this->rest_iter)) {\n return std::tuple_cat(\n std::tuple<iterator_deref<Container>>{*this->iter}, *this->rest_iter);\n }\n\n auto operator -> () -> ArrowProxy<decltype(**this)> {\n return {**this};\n }\n };\n\n Iterator begin() {\n return {std::begin(this->container), std::begin(this->rest_zipped)};\n }\n\n Iterator end() {\n return {std::end(this->container), std::end(this->rest_zipped)};\n }\n};\n\ntemplate <>\nclass iter::impl::Zipped<> {\n public:\n class Iterator : public std::iterator<std::input_iterator_tag, std::tuple<>> {\n public:\n constexpr static const bool is_base_iter = true;\n\n Iterator& operator++() {\n return *this;\n }\n\n Iterator operator++(int) {\n return *this;\n }\n\n \/\/ if this were to return true, there would be no need\n \/\/ for the is_base_iter static class attribute.\n \/\/ However, returning false causes an empty zip() call\n \/\/ to reach the \"end\" immediately. Returning true here\n \/\/ instead results in an infinite loop in the zip() case\n bool operator!=(const Iterator&) const {\n return false;\n }\n\n bool operator==(const Iterator& other) const {\n return !(*this != other);\n }\n\n std::tuple<> operator*() {\n return std::tuple<>{};\n }\n\n auto operator -> () -> ArrowProxy<decltype(**this)> {\n return {**this};\n }\n };\n\n Iterator begin() {\n return {};\n }\n\n Iterator end() {\n return {};\n }\n};\n\ntemplate <typename... Containers>\niter::impl::Zipped<Containers...> iter::zip(Containers&&... containers) {\n return {std::forward<Containers>(containers)...};\n}\n\n#endif\n<commit_msg>makes zip impl class move-only<commit_after>#ifndef ITER_ZIP_HPP_\n#define ITER_ZIP_HPP_\n\n#include \"internal\/iterbase.hpp\"\n\n#include <iterator>\n#include <tuple>\n#include <utility>\n\nnamespace iter {\n namespace impl {\n template <typename... RestContainers>\n class Zipped;\n\n template <typename Container, typename... RestContainers>\n class Zipped<Container, RestContainers...>;\n\n template <>\n class Zipped<>;\n }\n\n template <typename... Containers>\n impl::Zipped<Containers...> zip(Containers&&...);\n}\n\n\/\/ specialization for at least 1 template argument\ntemplate <typename Container, typename... RestContainers>\nclass iter::impl::Zipped<Container, RestContainers...> {\n using ZipIterDeref =\n std::tuple<iterator_deref<Container>, iterator_deref<RestContainers>...>;\n\n friend Zipped iter::zip<Container, RestContainers...>(\n Container&&, RestContainers&&...);\n\n template <typename...>\n friend class Zipped;\n\n private:\n Container container;\n Zipped<RestContainers...> rest_zipped;\n Zipped(Container&& in_container, RestContainers&&... rest)\n : container(std::forward<Container>(in_container)),\n rest_zipped{std::forward<RestContainers>(rest)...} {}\n\n public:\n Zipped(Zipped&&) = default;\n class Iterator : public std::iterator<std::input_iterator_tag, ZipIterDeref> {\n private:\n using RestIter = typename Zipped<RestContainers...>::Iterator;\n\n iterator_type<Container> iter;\n RestIter rest_iter;\n\n public:\n constexpr static const bool is_base_iter = false;\n Iterator(iterator_type<Container>&& it, RestIter&& rest)\n : iter{std::move(it)}, rest_iter{std::move(rest)} {}\n\n Iterator& operator++() {\n ++this->iter;\n ++this->rest_iter;\n return *this;\n }\n\n Iterator operator++(int) {\n auto ret = *this;\n ++*this;\n return ret;\n }\n\n bool operator!=(const Iterator& other) const {\n return this->iter != other.iter\n && (RestIter::is_base_iter || this->rest_iter != other.rest_iter);\n }\n\n bool operator==(const Iterator& other) const {\n return !(*this != other);\n }\n\n auto operator*() -> decltype(std::tuple_cat(\n std::tuple<iterator_deref<Container>>{*this->iter}, *this->rest_iter)) {\n return std::tuple_cat(\n std::tuple<iterator_deref<Container>>{*this->iter}, *this->rest_iter);\n }\n\n auto operator -> () -> ArrowProxy<decltype(**this)> {\n return {**this};\n }\n };\n\n Iterator begin() {\n return {std::begin(this->container), std::begin(this->rest_zipped)};\n }\n\n Iterator end() {\n return {std::end(this->container), std::end(this->rest_zipped)};\n }\n};\n\ntemplate <>\nclass iter::impl::Zipped<> {\n public:\n Zipped(Zipped&&) = default;\n class Iterator : public std::iterator<std::input_iterator_tag, std::tuple<>> {\n public:\n constexpr static const bool is_base_iter = true;\n\n Iterator& operator++() {\n return *this;\n }\n\n Iterator operator++(int) {\n return *this;\n }\n\n \/\/ if this were to return true, there would be no need\n \/\/ for the is_base_iter static class attribute.\n \/\/ However, returning false causes an empty zip() call\n \/\/ to reach the \"end\" immediately. Returning true here\n \/\/ instead results in an infinite loop in the zip() case\n bool operator!=(const Iterator&) const {\n return false;\n }\n\n bool operator==(const Iterator& other) const {\n return !(*this != other);\n }\n\n std::tuple<> operator*() {\n return std::tuple<>{};\n }\n\n auto operator -> () -> ArrowProxy<decltype(**this)> {\n return {**this};\n }\n };\n\n Iterator begin() {\n return {};\n }\n\n Iterator end() {\n return {};\n }\n};\n\ntemplate <typename... Containers>\niter::impl::Zipped<Containers...> iter::zip(Containers&&... containers) {\n return {std::forward<Containers>(containers)...};\n}\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 2013 The WebRTC project authors. All Rights Reserved.\n *\n * Use of this source code is governed by a BSD-style license\n * that can be found in the LICENSE file in the root of the source\n * tree. An additional intellectual property rights grant can be found\n * in the file PATENTS. All contributing project authors may\n * be found in the AUTHORS file in the root of the source tree.\n *\/\n\n#include \"webrtc\/modules\/desktop_capture\/window_capturer.h\"\n\n#include <assert.h>\n#include <windows.h>\n\n#include \"webrtc\/modules\/desktop_capture\/desktop_frame_win.h\"\n#include \"webrtc\/system_wrappers\/interface\/logging.h\"\n#include \"webrtc\/system_wrappers\/interface\/scoped_ptr.h\"\n\nnamespace webrtc {\n\nnamespace {\n\ntypedef HRESULT (WINAPI *DwmIsCompositionEnabledFunc)(BOOL* enabled);\n\n\/\/ Coverts a zero-terminated UTF-16 string to UTF-8. Returns an empty string if\n\/\/ error occurs.\nstd::string Utf16ToUtf8(const WCHAR* str) {\n int len_utf8 = WideCharToMultiByte(CP_UTF8, 0, str, -1,\n NULL, 0, NULL, NULL);\n if (len_utf8 <= 0)\n return std::string();\n std::string result(len_utf8, '\\0');\n int rv = WideCharToMultiByte(CP_UTF8, 0, str, -1,\n &*(result.begin()), len_utf8, NULL, NULL);\n if (rv != len_utf8)\n assert(false);\n\n return result;\n}\n\nBOOL CALLBACK WindowsEnumerationHandler(HWND hwnd, LPARAM param) {\n WindowCapturer::WindowList* list =\n reinterpret_cast<WindowCapturer::WindowList*>(param);\n\n \/\/ Skip windows that are invisible, minimized, have no title, or are owned,\n \/\/ unless they have the app window style set.\n int len = GetWindowTextLength(hwnd);\n HWND owner = GetWindow(hwnd, GW_OWNER);\n LONG exstyle = GetWindowLong(hwnd, GWL_EXSTYLE);\n if (len == 0 || IsIconic(hwnd) || !IsWindowVisible(hwnd) ||\n (owner && !(exstyle & WS_EX_APPWINDOW))) {\n return TRUE;\n }\n\n \/\/ Skip the Program Manager window and the Start button.\n const size_t kClassLength = 256;\n WCHAR class_name[kClassLength];\n GetClassName(hwnd, class_name, kClassLength);\n \/\/ Skip Program Manager window and the Start button. This is the same logic\n \/\/ that's used in Win32WindowPicker in libjingle. Consider filtering other\n \/\/ windows as well (e.g. toolbars).\n if (wcscmp(class_name, L\"Progman\") == 0 || wcscmp(class_name, L\"Button\") == 0)\n return TRUE;\n\n WindowCapturer::Window window;\n window.id = reinterpret_cast<WindowCapturer::WindowId>(hwnd);\n\n const size_t kTitleLength = 500;\n WCHAR window_title[kTitleLength];\n \/\/ Truncate the title if it's longer than kTitleLength.\n GetWindowText(hwnd, window_title, kTitleLength);\n window.title = Utf16ToUtf8(window_title);\n\n \/\/ Skip windows when we failed to convert the title or it is empty.\n if (window.title.empty())\n return TRUE;\n\n list->push_back(window);\n\n return TRUE;\n}\n\nclass WindowCapturerWin : public WindowCapturer {\n public:\n WindowCapturerWin();\n virtual ~WindowCapturerWin();\n\n \/\/ WindowCapturer interface.\n virtual bool GetWindowList(WindowList* windows) OVERRIDE;\n virtual bool SelectWindow(WindowId id) OVERRIDE;\n\n \/\/ DesktopCapturer interface.\n virtual void Start(Callback* callback) OVERRIDE;\n virtual void Capture(const DesktopRegion& region) OVERRIDE;\n\n private:\n bool IsAeroEnabled();\n\n Callback* callback_;\n\n \/\/ HWND and HDC for the currently selected window or NULL if window is not\n \/\/ selected.\n HWND window_;\n HDC window_dc_;\n\n \/\/ dwmapi.dll is used to determine if desktop compositing is enabled.\n HMODULE dwmapi_library_;\n DwmIsCompositionEnabledFunc is_composition_enabled_func_;\n\n DISALLOW_COPY_AND_ASSIGN(WindowCapturerWin);\n};\n\nWindowCapturerWin::WindowCapturerWin()\n : callback_(NULL),\n window_(NULL),\n window_dc_(NULL) {\n \/\/ Try to load dwmapi.dll dynamically since it is not available on XP.\n dwmapi_library_ = LoadLibrary(L\"dwmapi.dll\");\n if (dwmapi_library_) {\n is_composition_enabled_func_ =\n reinterpret_cast<DwmIsCompositionEnabledFunc>(\n GetProcAddress(dwmapi_library_, \"DwmIsCompositionEnabled\"));\n assert(is_composition_enabled_func_);\n } else {\n is_composition_enabled_func_ = NULL;\n }\n}\n\nWindowCapturerWin::~WindowCapturerWin() {\n if (dwmapi_library_)\n FreeLibrary(dwmapi_library_);\n}\n\nbool WindowCapturerWin::IsAeroEnabled() {\n BOOL result = FALSE;\n if (is_composition_enabled_func_)\n is_composition_enabled_func_(&result);\n return result != FALSE;\n}\n\nbool WindowCapturerWin::GetWindowList(WindowList* windows) {\n WindowList result;\n LPARAM param = reinterpret_cast<LPARAM>(&result);\n if (!EnumWindows(&WindowsEnumerationHandler, param))\n return false;\n windows->swap(result);\n return true;\n}\n\nbool WindowCapturerWin::SelectWindow(WindowId id) {\n if (window_dc_)\n ReleaseDC(window_, window_dc_);\n\n window_ = reinterpret_cast<HWND>(id);\n window_dc_ = GetWindowDC(window_);\n if (!window_dc_) {\n LOG(LS_WARNING) << \"Failed to select window: \" << GetLastError();\n window_ = NULL;\n return false;\n }\n\n return true;\n}\n\nvoid WindowCapturerWin::Start(Callback* callback) {\n assert(!callback_);\n assert(callback);\n\n callback_ = callback;\n}\n\nvoid WindowCapturerWin::Capture(const DesktopRegion& region) {\n if (!window_dc_) {\n LOG(LS_ERROR) << \"Window hasn't been selected: \" << GetLastError();\n callback_->OnCaptureCompleted(NULL);\n return;\n }\n\n \/\/ Stop capturing if the window has been minimized or hidden.\n if (IsIconic(window_) || !IsWindowVisible(window_)) {\n callback_->OnCaptureCompleted(NULL);\n return;\n }\n\n assert(window_);\n\n RECT rect;\n if (!GetWindowRect(window_, &rect)) {\n LOG(LS_WARNING) << \"Failed to get window size: \" << GetLastError();\n callback_->OnCaptureCompleted(NULL);\n return;\n }\n\n scoped_ptr<DesktopFrameWin> frame(DesktopFrameWin::Create(\n DesktopSize(rect.right - rect.left, rect.bottom - rect.top),\n NULL, window_dc_));\n if (!frame.get()) {\n callback_->OnCaptureCompleted(NULL);\n return;\n }\n\n HDC mem_dc = CreateCompatibleDC(window_dc_);\n SelectObject(mem_dc, frame->bitmap());\n BOOL result = FALSE;\n\n \/\/ When desktop composition (Aero) is enabled each window is rendered to a\n \/\/ private buffer allowing BitBlt() to get the window content even if the\n \/\/ window is occluded. PrintWindow() is slower but lets rendering the window\n \/\/ contents to an off-screen device context when Aero is not available.\n \/\/ PrintWindow() is not supported by some applications.\n\n \/\/ If Aero is enabled, we prefer BitBlt() because it's faster and avoids\n \/\/ window flickering. Otherwise, we prefer PrintWindow() because BitBlt() may\n \/\/ render occluding windows on top of the desired window.\n\n if (!IsAeroEnabled())\n result = PrintWindow(window_, mem_dc, 0);\n\n \/\/ Aero is enabled or PrintWindow() failed, use BitBlt.\n if (!result) {\n result = BitBlt(mem_dc, 0, 0, frame->size().width(), frame->size().height(),\n window_dc_, 0, 0, SRCCOPY);\n }\n\n DeleteDC(mem_dc);\n\n if (!result) {\n LOG(LS_ERROR) << \"Both PrintWindow() and BitBlt() failed.\";\n frame.reset();\n }\n\n callback_->OnCaptureCompleted(frame.release());\n}\n\n} \/\/ namespace\n\n\/\/ static\nWindowCapturer* WindowCapturer::Create() {\n return new WindowCapturerWin();\n}\n\n} \/\/ namespace webrtc\n<commit_msg>Fix window capturer not to leak HDC.<commit_after>\/*\n * Copyright (c) 2013 The WebRTC project authors. All Rights Reserved.\n *\n * Use of this source code is governed by a BSD-style license\n * that can be found in the LICENSE file in the root of the source\n * tree. An additional intellectual property rights grant can be found\n * in the file PATENTS. All contributing project authors may\n * be found in the AUTHORS file in the root of the source tree.\n *\/\n\n#include \"webrtc\/modules\/desktop_capture\/window_capturer.h\"\n\n#include <assert.h>\n#include <windows.h>\n\n#include \"webrtc\/modules\/desktop_capture\/desktop_frame_win.h\"\n#include \"webrtc\/system_wrappers\/interface\/logging.h\"\n#include \"webrtc\/system_wrappers\/interface\/scoped_ptr.h\"\n\nnamespace webrtc {\n\nnamespace {\n\ntypedef HRESULT (WINAPI *DwmIsCompositionEnabledFunc)(BOOL* enabled);\n\n\/\/ Coverts a zero-terminated UTF-16 string to UTF-8. Returns an empty string if\n\/\/ error occurs.\nstd::string Utf16ToUtf8(const WCHAR* str) {\n int len_utf8 = WideCharToMultiByte(CP_UTF8, 0, str, -1,\n NULL, 0, NULL, NULL);\n if (len_utf8 <= 0)\n return std::string();\n std::string result(len_utf8, '\\0');\n int rv = WideCharToMultiByte(CP_UTF8, 0, str, -1,\n &*(result.begin()), len_utf8, NULL, NULL);\n if (rv != len_utf8)\n assert(false);\n\n return result;\n}\n\nBOOL CALLBACK WindowsEnumerationHandler(HWND hwnd, LPARAM param) {\n WindowCapturer::WindowList* list =\n reinterpret_cast<WindowCapturer::WindowList*>(param);\n\n \/\/ Skip windows that are invisible, minimized, have no title, or are owned,\n \/\/ unless they have the app window style set.\n int len = GetWindowTextLength(hwnd);\n HWND owner = GetWindow(hwnd, GW_OWNER);\n LONG exstyle = GetWindowLong(hwnd, GWL_EXSTYLE);\n if (len == 0 || IsIconic(hwnd) || !IsWindowVisible(hwnd) ||\n (owner && !(exstyle & WS_EX_APPWINDOW))) {\n return TRUE;\n }\n\n \/\/ Skip the Program Manager window and the Start button.\n const size_t kClassLength = 256;\n WCHAR class_name[kClassLength];\n GetClassName(hwnd, class_name, kClassLength);\n \/\/ Skip Program Manager window and the Start button. This is the same logic\n \/\/ that's used in Win32WindowPicker in libjingle. Consider filtering other\n \/\/ windows as well (e.g. toolbars).\n if (wcscmp(class_name, L\"Progman\") == 0 || wcscmp(class_name, L\"Button\") == 0)\n return TRUE;\n\n WindowCapturer::Window window;\n window.id = reinterpret_cast<WindowCapturer::WindowId>(hwnd);\n\n const size_t kTitleLength = 500;\n WCHAR window_title[kTitleLength];\n \/\/ Truncate the title if it's longer than kTitleLength.\n GetWindowText(hwnd, window_title, kTitleLength);\n window.title = Utf16ToUtf8(window_title);\n\n \/\/ Skip windows when we failed to convert the title or it is empty.\n if (window.title.empty())\n return TRUE;\n\n list->push_back(window);\n\n return TRUE;\n}\n\nclass WindowCapturerWin : public WindowCapturer {\n public:\n WindowCapturerWin();\n virtual ~WindowCapturerWin();\n\n \/\/ WindowCapturer interface.\n virtual bool GetWindowList(WindowList* windows) OVERRIDE;\n virtual bool SelectWindow(WindowId id) OVERRIDE;\n\n \/\/ DesktopCapturer interface.\n virtual void Start(Callback* callback) OVERRIDE;\n virtual void Capture(const DesktopRegion& region) OVERRIDE;\n\n private:\n bool IsAeroEnabled();\n\n Callback* callback_;\n\n \/\/ HWND and HDC for the currently selected window or NULL if window is not\n \/\/ selected.\n HWND window_;\n\n \/\/ dwmapi.dll is used to determine if desktop compositing is enabled.\n HMODULE dwmapi_library_;\n DwmIsCompositionEnabledFunc is_composition_enabled_func_;\n\n DISALLOW_COPY_AND_ASSIGN(WindowCapturerWin);\n};\n\nWindowCapturerWin::WindowCapturerWin()\n : callback_(NULL),\n window_(NULL) {\n \/\/ Try to load dwmapi.dll dynamically since it is not available on XP.\n dwmapi_library_ = LoadLibrary(L\"dwmapi.dll\");\n if (dwmapi_library_) {\n is_composition_enabled_func_ =\n reinterpret_cast<DwmIsCompositionEnabledFunc>(\n GetProcAddress(dwmapi_library_, \"DwmIsCompositionEnabled\"));\n assert(is_composition_enabled_func_);\n } else {\n is_composition_enabled_func_ = NULL;\n }\n}\n\nWindowCapturerWin::~WindowCapturerWin() {\n if (dwmapi_library_)\n FreeLibrary(dwmapi_library_);\n}\n\nbool WindowCapturerWin::IsAeroEnabled() {\n BOOL result = FALSE;\n if (is_composition_enabled_func_)\n is_composition_enabled_func_(&result);\n return result != FALSE;\n}\n\nbool WindowCapturerWin::GetWindowList(WindowList* windows) {\n WindowList result;\n LPARAM param = reinterpret_cast<LPARAM>(&result);\n if (!EnumWindows(&WindowsEnumerationHandler, param))\n return false;\n windows->swap(result);\n return true;\n}\n\nbool WindowCapturerWin::SelectWindow(WindowId id) {\n HWND window = reinterpret_cast<HWND>(id);\n if (!IsWindow(window) || !IsWindowVisible(window) || IsIconic(window))\n return false;\n window_ = window;\n return true;\n}\n\nvoid WindowCapturerWin::Start(Callback* callback) {\n assert(!callback_);\n assert(callback);\n\n callback_ = callback;\n}\n\nvoid WindowCapturerWin::Capture(const DesktopRegion& region) {\n if (!window_) {\n LOG(LS_ERROR) << \"Window hasn't been selected: \" << GetLastError();\n callback_->OnCaptureCompleted(NULL);\n return;\n }\n\n \/\/ Stop capturing if the window has been minimized or hidden.\n if (IsIconic(window_) || !IsWindowVisible(window_)) {\n callback_->OnCaptureCompleted(NULL);\n return;\n }\n\n RECT rect;\n if (!GetWindowRect(window_, &rect)) {\n LOG(LS_WARNING) << \"Failed to get window size: \" << GetLastError();\n callback_->OnCaptureCompleted(NULL);\n return;\n }\n\n HDC window_dc = GetWindowDC(window_);\n if (!window_dc) {\n LOG(LS_WARNING) << \"Failed to get window DC: \" << GetLastError();\n callback_->OnCaptureCompleted(NULL);\n return;\n }\n\n scoped_ptr<DesktopFrameWin> frame(DesktopFrameWin::Create(\n DesktopSize(rect.right - rect.left, rect.bottom - rect.top),\n NULL, window_dc));\n if (!frame.get()) {\n ReleaseDC(window_, window_dc);\n callback_->OnCaptureCompleted(NULL);\n return;\n }\n\n HDC mem_dc = CreateCompatibleDC(window_dc);\n SelectObject(mem_dc, frame->bitmap());\n BOOL result = FALSE;\n\n \/\/ When desktop composition (Aero) is enabled each window is rendered to a\n \/\/ private buffer allowing BitBlt() to get the window content even if the\n \/\/ window is occluded. PrintWindow() is slower but lets rendering the window\n \/\/ contents to an off-screen device context when Aero is not available.\n \/\/ PrintWindow() is not supported by some applications.\n\n \/\/ If Aero is enabled, we prefer BitBlt() because it's faster and avoids\n \/\/ window flickering. Otherwise, we prefer PrintWindow() because BitBlt() may\n \/\/ render occluding windows on top of the desired window.\n\n if (!IsAeroEnabled())\n result = PrintWindow(window_, mem_dc, 0);\n\n \/\/ Aero is enabled or PrintWindow() failed, use BitBlt.\n if (!result) {\n result = BitBlt(mem_dc, 0, 0, frame->size().width(), frame->size().height(),\n window_dc, 0, 0, SRCCOPY);\n }\n\n if (!result) {\n LOG(LS_ERROR) << \"Both PrintWindow() and BitBlt() failed.\";\n frame.reset();\n }\n\n SelectObject(mem_dc, NULL);\n DeleteDC(mem_dc);\n ReleaseDC(window_, window_dc);\n\n callback_->OnCaptureCompleted(frame.release());\n}\n\n} \/\/ namespace\n\n\/\/ static\nWindowCapturer* WindowCapturer::Create() {\n return new WindowCapturerWin();\n}\n\n} \/\/ namespace webrtc\n<|endoftext|>"} {"text":"<commit_before>\/*\n Copyright (c) 2008 Volker Krause <vkrause@kde.org>\n Copyright (C) 2014 Daniel Vrátil <dvraitl@redhat.com>\n\n This library is free software; you can redistribute it and\/or modify it\n under the terms of the GNU Library General Public License as published by\n the Free Software Foundation; either version 2 of the License, or (at your\n option) any later version.\n\n This library is distributed in the hope that it will be useful, but WITHOUT\n ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public\n License for more details.\n\n You should have received a copy of the GNU Library General Public License\n along with this library; see the file COPYING.LIB. If not, write to the\n Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA\n 02110-1301, USA.\n*\/\n\n#include \"intervalcheck.h\"\n#include \"storage\/datastore.h\"\n#include \"storage\/itemretrievalmanager.h\"\n\nusing namespace Akonadi::Server;\n\nstatic int MINIMUM_AUTOSYNC_INTERVAL = 5; \/\/ minutes\nstatic int MINIMUM_COLTREESYNC_INTERVAL = 5; \/\/ minutes\n\nIntervalCheck::IntervalCheck( QObject *parent )\n : CollectionScheduler( parent )\n{\n}\n\nIntervalCheck::~ IntervalCheck()\n{\n}\n\nvoid IntervalCheck::requestCollectionSync( const Collection &collection )\n{\n QMetaObject::invokeMethod( this, \"collectionExpired\",\n Qt::QueuedConnection,\n Q_ARG( Collection, collection ) );\n}\n\nint IntervalCheck::collectionScheduleInterval( const Collection &collection )\n{\n return collection.cachePolicyCheckInterval();\n}\n\nbool IntervalCheck::hasChanged( const Collection &collection, const Collection &changed )\n{\n return collection.cachePolicyCheckInterval() != changed.cachePolicyCheckInterval()\n || collection.subscribed() != changed.subscribed();\n}\n\nbool IntervalCheck::shouldScheduleCollection( const Collection &collection )\n{\n return collection.cachePolicyCheckInterval() > 0\n && collection.subscribed();\n}\n\nvoid IntervalCheck::collectionExpired( const Collection &collection )\n{\n const QDateTime now( QDateTime::currentDateTime() );\n\n if ( collection.parentId() == 0 ) {\n const QString resourceName = collection.resource().name();\n\n const int interval = qMax( MINIMUM_COLTREESYNC_INTERVAL, collection.cachePolicyCheckInterval() );\n\n const QDateTime lastExpectedCheck = now.addSecs( interval * -60 );\n if ( !mLastCollectionTreeSyncs.contains( resourceName ) || mLastCollectionTreeSyncs.value( resourceName ) < lastExpectedCheck ) {\n mLastCollectionTreeSyncs.insert( resourceName, now );\n QMetaObject::invokeMethod( ItemRetrievalManager::instance(), \"triggerCollectionTreeSync\",\n Qt::QueuedConnection,\n Q_ARG( QString, resourceName ) );\n }\n }\n\n \/\/ now on to the actual collection syncing\n const int interval = qMax( MINIMUM_AUTOSYNC_INTERVAL, collection.cachePolicyCheckInterval() );\n\n const QDateTime lastExpectedCheck = now.addSecs( interval * -60 );\n if ( mLastChecks.contains( collection.id() ) && mLastChecks.value( collection.id() ) > lastExpectedCheck ) {\n return;\n }\n mLastChecks.insert( collection.id(), now );\n QMetaObject::invokeMethod( ItemRetrievalManager::instance(), \"triggerCollectionSync\",\n Qt::QueuedConnection,\n Q_ARG( QString, collection.resource().name() ),\n Q_ARG( qint64, collection.id() ) );\n}\n<commit_msg>Only schedule collections for sync that are enabled or have a corresponding preference.<commit_after>\/*\n Copyright (c) 2008 Volker Krause <vkrause@kde.org>\n Copyright (C) 2014 Daniel Vrátil <dvraitl@redhat.com>\n\n This library is free software; you can redistribute it and\/or modify it\n under the terms of the GNU Library General Public License as published by\n the Free Software Foundation; either version 2 of the License, or (at your\n option) any later version.\n\n This library is distributed in the hope that it will be useful, but WITHOUT\n ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public\n License for more details.\n\n You should have received a copy of the GNU Library General Public License\n along with this library; see the file COPYING.LIB. If not, write to the\n Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA\n 02110-1301, USA.\n*\/\n\n#include \"intervalcheck.h\"\n#include \"storage\/datastore.h\"\n#include \"storage\/itemretrievalmanager.h\"\n#include \"storage\/entity.h\"\n\nusing namespace Akonadi::Server;\n\nstatic int MINIMUM_AUTOSYNC_INTERVAL = 5; \/\/ minutes\nstatic int MINIMUM_COLTREESYNC_INTERVAL = 5; \/\/ minutes\n\nIntervalCheck::IntervalCheck( QObject *parent )\n : CollectionScheduler( parent )\n{\n}\n\nIntervalCheck::~ IntervalCheck()\n{\n}\n\nvoid IntervalCheck::requestCollectionSync( const Collection &collection )\n{\n QMetaObject::invokeMethod( this, \"collectionExpired\",\n Qt::QueuedConnection,\n Q_ARG( Collection, collection ) );\n}\n\nint IntervalCheck::collectionScheduleInterval( const Collection &collection )\n{\n return collection.cachePolicyCheckInterval();\n}\n\nbool IntervalCheck::hasChanged( const Collection &collection, const Collection &changed )\n{\n return collection.cachePolicyCheckInterval() != changed.cachePolicyCheckInterval()\n || collection.subscribed() != changed.subscribed()\n || collection.enabled() != changed.enabled()\n || collection.syncPref() != changed.syncPref();\n}\n\nbool IntervalCheck::shouldScheduleCollection( const Collection &collection )\n{\n return collection.cachePolicyCheckInterval() > 0\n && ( collection.subscribed() || ( collection.syncPref() == Tristate::True ) || ( ( collection.syncPref() == Tristate::Undefined ) && collection.enabled() ) );\n}\n\nvoid IntervalCheck::collectionExpired( const Collection &collection )\n{\n const QDateTime now( QDateTime::currentDateTime() );\n\n if ( collection.parentId() == 0 ) {\n const QString resourceName = collection.resource().name();\n\n const int interval = qMax( MINIMUM_COLTREESYNC_INTERVAL, collection.cachePolicyCheckInterval() );\n\n const QDateTime lastExpectedCheck = now.addSecs( interval * -60 );\n if ( !mLastCollectionTreeSyncs.contains( resourceName ) || mLastCollectionTreeSyncs.value( resourceName ) < lastExpectedCheck ) {\n mLastCollectionTreeSyncs.insert( resourceName, now );\n QMetaObject::invokeMethod( ItemRetrievalManager::instance(), \"triggerCollectionTreeSync\",\n Qt::QueuedConnection,\n Q_ARG( QString, resourceName ) );\n }\n }\n\n \/\/ now on to the actual collection syncing\n const int interval = qMax( MINIMUM_AUTOSYNC_INTERVAL, collection.cachePolicyCheckInterval() );\n\n const QDateTime lastExpectedCheck = now.addSecs( interval * -60 );\n if ( mLastChecks.contains( collection.id() ) && mLastChecks.value( collection.id() ) > lastExpectedCheck ) {\n return;\n }\n mLastChecks.insert( collection.id(), now );\n QMetaObject::invokeMethod( ItemRetrievalManager::instance(), \"triggerCollectionSync\",\n Qt::QueuedConnection,\n Q_ARG( QString, collection.resource().name() ),\n Q_ARG( qint64, collection.id() ) );\n}\n<|endoftext|>"} {"text":"<commit_before>#include <fstream>\n\n#include \"main.h\"\n#include \"elf.h\"\n#include \"package.h\"\n#include \"db.h\"\n\n#include \"pkgdepdb.h\"\n\n#include \"capi_algorithm.h\"\n\nusing namespace pkgdepdb;\n\nextern \"C\" {\n\npkgdepdb_pkg* pkgdepdb_pkg_new(void) {\n return reinterpret_cast<pkgdepdb_pkg*>(new Package);\n}\n\npkgdepdb_pkg* pkgdepdb_pkg_load(const char *filename, pkgdepdb_config *cfg_) {\n auto cfg = reinterpret_cast<Config*>(cfg_);\n auto pkg = Package::Open(filename, *cfg);\n return reinterpret_cast<pkgdepdb_pkg*>(pkg);\n}\n\nvoid pkgdepdb_pkg_delete(pkgdepdb_pkg *pkg_) {\n auto pkg = reinterpret_cast<Package*>(pkg_);\n delete pkg;\n}\n\nconst char* pkgdepdb_pkg_name(pkgdepdb_pkg *pkg_) {\n auto pkg = reinterpret_cast<Package*>(pkg_);\n return pkg->name_.c_str();\n}\n\nconst char* pkgdepdb_pkg_version(pkgdepdb_pkg *pkg_) {\n auto pkg = reinterpret_cast<Package*>(pkg_);\n return pkg->version_.c_str();\n}\n\nvoid pkgdepdb_pkg_set_name(pkgdepdb_pkg *pkg_, const char *v) {\n auto pkg = reinterpret_cast<Package*>(pkg_);\n pkg->name_ = v;\n}\n\nvoid pkgdepdb_pkg_set_version(pkgdepdb_pkg *pkg_, const char *v) {\n auto pkg = reinterpret_cast<Package*>(pkg_);\n pkg->version_ = v;\n}\n\nstatic DependList Package::* const kDepMember[] = {\n &Package::depends_,\n &Package::optdepends_,\n &Package::makedepends_,\n &Package::provides_,\n &Package::conflicts_,\n &Package::replaces_,\n};\nstatic const size_t kDepMemberCount = sizeof(kDepMember)\/sizeof(kDepMember[0]);\n\nstatic inline\nsize_t pkg_dependlist_count(const Package& pkg, DependList Package::*member) {\n return (pkg.*member).size();\n}\n\nstatic inline\nsize_t pkg_dependlist_get(const Package& pkg, DependList Package::*member,\n const char **on, const char **oc, size_t off,\n size_t n)\n{\n if (off >= (pkg.*member).size())\n return 0;\n auto i = (pkg.*member).begin() + off;\n auto end = (pkg.*member).end();\n size_t got = 0;\n for (; i != end; ++i) {\n if (!n--)\n return got;\n on[got++] = std::get<0>(*i).c_str();\n oc[got++] = std::get<1>(*i).c_str();\n }\n return got;\n}\n\nstatic inline\nint pkg_dependlist_add(Package& pkg, DependList Package::*member,\n const char *name, const char *constraint)\n{\n (pkg.*member).emplace_back(name, constraint ? constraint : \"\");\n return 1;\n}\n\nstatic inline\nint pkg_dependlist_del_name(Package& pkg, DependList Package::*member,\n const char *name)\n{\n auto i = (pkg.*member).begin();\n auto end = (pkg.*member).end();\n for (; i != end; ++i) {\n if (std::get<0>(*i) == name) {\n (pkg.*member).erase(i);\n return 1;\n }\n }\n return 0;\n}\n\nstatic inline\nint pkg_dependlist_del_full(Package& pkg, DependList Package::*member,\n const char *name, const char *constraint)\n{\n auto i = (pkg.*member).begin();\n auto end = (pkg.*member).end();\n for (; i != end; ++i) {\n if (std::get<0>(*i) == name && std::get<1>(*i) == constraint) {\n (pkg.*member).erase(i);\n return 1;\n }\n }\n return 0;\n}\n\n\nstatic inline\nint pkg_dependlist_del_i(Package& pkg, DependList Package::*member, size_t i) {\n if (i >= (pkg.*member).size())\n return 0;\n (pkg.*member).erase((pkg.*member).begin() + i);\n return 1;\n}\n\nsize_t pkgdepdb_pkg_dep_count(pkgdepdb_pkg *pkg_, unsigned int what) {\n auto pkg = reinterpret_cast<Package*>(pkg_);\n if (what >= kDepMemberCount)\n return 0;\n return pkg_dependlist_count(*pkg, kDepMember[what]);\n}\n\nsize_t pkgdepdb_pkg_dep_get(pkgdepdb_pkg *pkg_, unsigned int what,\n const char **on, const char **oc, size_t off,\n size_t n)\n{\n auto pkg = reinterpret_cast<Package*>(pkg_);\n if (what >= kDepMemberCount)\n return 0;\n return pkg_dependlist_get(*pkg, kDepMember[what], on, oc, off, n);\n}\n\nint pkgdepdb_pkg_dep_add(pkgdepdb_pkg *pkg_, unsigned int what,\n const char *name, const char *constraint)\n{\n auto pkg = reinterpret_cast<Package*>(pkg_);\n if (what >= kDepMemberCount)\n return 0;\n return pkg_dependlist_add(*pkg, kDepMember[what], name, constraint);\n}\n\nint pkgdepdb_pkg_dep_del_name(pkgdepdb_pkg *pkg_, unsigned int what,\n const char *name)\n{\n auto pkg = reinterpret_cast<Package*>(pkg_);\n if (what >= kDepMemberCount)\n return 0;\n return pkg_dependlist_del_name(*pkg, kDepMember[what], name);\n}\n\nint pkgdepdb_pkg_dep_del_full(pkgdepdb_pkg *pkg_, unsigned int what,\n const char *name, const char *constraint)\n{\n auto pkg = reinterpret_cast<Package*>(pkg_);\n if (what >= kDepMemberCount)\n return 0;\n return pkg_dependlist_del_full(*pkg, kDepMember[what], name, constraint);\n}\n\nint pkgdepdb_pkg_dep_del_i(pkgdepdb_pkg *pkg_, unsigned int what, size_t idx) {\n auto pkg = reinterpret_cast<Package*>(pkg_);\n if (what >= kDepMemberCount)\n return 0;\n return pkg_dependlist_del_i(*pkg, kDepMember[what], idx);\n}\n\nsize_t pkgdepdb_pkg_groups_count(pkgdepdb_pkg *pkg_) {\n auto pkg = reinterpret_cast<Package*>(pkg_);\n return pkgdepdb_strlist_count(*pkg, &Package::groups_);\n}\n\nsize_t pkgdepdb_pkg_groups_get(pkgdepdb_pkg *pkg_, const char **o, size_t n) {\n auto pkg = reinterpret_cast<Package*>(pkg_);\n return pkgdepdb_strlist_get(*pkg, &Package::groups_, o, 0, n);\n}\n\nsize_t pkgdepdb_pkg_groups_add(pkgdepdb_pkg *pkg_, const char *v) {\n auto pkg = reinterpret_cast<Package*>(pkg_);\n return pkgdepdb_strlist_add_unique(*pkg, &Package::groups_, v);\n}\n\nsize_t pkgdepdb_pkg_groups_del_s(pkgdepdb_pkg *pkg_, const char *v) {\n auto pkg = reinterpret_cast<Package*>(pkg_);\n return pkgdepdb_strlist_del_s_all(*pkg, &Package::groups_, v);\n}\n\nsize_t pkgdepdb_pkg_groups_del_i(pkgdepdb_pkg *pkg_, size_t index) {\n auto pkg = reinterpret_cast<Package*>(pkg_);\n return pkgdepdb_strlist_del_i(*pkg, &Package::groups_, index);\n}\n\nsize_t pkgdepdb_pkg_filelist_count(pkgdepdb_pkg *pkg_) {\n auto pkg = reinterpret_cast<Package*>(pkg_);\n return pkgdepdb_strlist_count(*pkg, &Package::filelist_);\n}\n\nsize_t pkgdepdb_pkg_filelist_get(pkgdepdb_pkg *pkg_,\n const char **out, size_t off, size_t count)\n{\n auto pkg = reinterpret_cast<Package*>(pkg_);\n return pkgdepdb_strlist_get(*pkg, &Package::filelist_, out, off, count);\n}\n\nsize_t pkgdepdb_pkg_filelist_add(pkgdepdb_pkg *pkg_, const char *v) {\n auto pkg = reinterpret_cast<Package*>(pkg_);\n return pkgdepdb_strlist_add_always(*pkg, &Package::filelist_, v);\n}\n\nsize_t pkgdepdb_pkg_filelist_del_s(pkgdepdb_pkg *pkg_, const char *v) {\n auto pkg = reinterpret_cast<Package*>(pkg_);\n return pkgdepdb_strlist_del_s_one(*pkg, &Package::filelist_, v);\n}\n\nsize_t pkgdepdb_pkg_filelist_del_i(pkgdepdb_pkg *pkg_, size_t index) {\n auto pkg = reinterpret_cast<Package*>(pkg_);\n return pkgdepdb_strlist_del_i(*pkg, &Package::filelist_, index);\n}\n\nvoid pkgdepdb_pkg_guess_version(pkgdepdb_pkg *pkg_, const char *filename) {\n auto pkg = reinterpret_cast<Package*>(pkg_);\n pkg->Guess(filename);\n}\n\nint pkgdepdb_pkg_conflict(pkgdepdb_pkg *subj_, pkgdepdb_pkg *obj_) {\n auto pkg = reinterpret_cast<Package*>(subj_);\n auto obj = reinterpret_cast<Package*>(obj_);\n return pkg->ConflictsWith(*obj);\n}\n\nint pkgdepdb_pkg_replaces(pkgdepdb_pkg *subj_, pkgdepdb_pkg *obj_) {\n auto pkg = reinterpret_cast<Package*>(subj_);\n auto obj = reinterpret_cast<Package*>(obj_);\n return pkg->Replaces(*obj);\n}\n\n} \/\/ extern \"C\"\n<commit_msg>remove double increment<commit_after>#include <fstream>\n\n#include \"main.h\"\n#include \"elf.h\"\n#include \"package.h\"\n#include \"db.h\"\n\n#include \"pkgdepdb.h\"\n\n#include \"capi_algorithm.h\"\n\nusing namespace pkgdepdb;\n\nextern \"C\" {\n\npkgdepdb_pkg* pkgdepdb_pkg_new(void) {\n return reinterpret_cast<pkgdepdb_pkg*>(new Package);\n}\n\npkgdepdb_pkg* pkgdepdb_pkg_load(const char *filename, pkgdepdb_config *cfg_) {\n auto cfg = reinterpret_cast<Config*>(cfg_);\n auto pkg = Package::Open(filename, *cfg);\n return reinterpret_cast<pkgdepdb_pkg*>(pkg);\n}\n\nvoid pkgdepdb_pkg_delete(pkgdepdb_pkg *pkg_) {\n auto pkg = reinterpret_cast<Package*>(pkg_);\n delete pkg;\n}\n\nconst char* pkgdepdb_pkg_name(pkgdepdb_pkg *pkg_) {\n auto pkg = reinterpret_cast<Package*>(pkg_);\n return pkg->name_.c_str();\n}\n\nconst char* pkgdepdb_pkg_version(pkgdepdb_pkg *pkg_) {\n auto pkg = reinterpret_cast<Package*>(pkg_);\n return pkg->version_.c_str();\n}\n\nvoid pkgdepdb_pkg_set_name(pkgdepdb_pkg *pkg_, const char *v) {\n auto pkg = reinterpret_cast<Package*>(pkg_);\n pkg->name_ = v;\n}\n\nvoid pkgdepdb_pkg_set_version(pkgdepdb_pkg *pkg_, const char *v) {\n auto pkg = reinterpret_cast<Package*>(pkg_);\n pkg->version_ = v;\n}\n\nstatic DependList Package::* const kDepMember[] = {\n &Package::depends_,\n &Package::optdepends_,\n &Package::makedepends_,\n &Package::provides_,\n &Package::conflicts_,\n &Package::replaces_,\n};\nstatic const size_t kDepMemberCount = sizeof(kDepMember)\/sizeof(kDepMember[0]);\n\nstatic inline\nsize_t pkg_dependlist_count(const Package& pkg, DependList Package::*member) {\n return (pkg.*member).size();\n}\n\nstatic inline\nsize_t pkg_dependlist_get(const Package& pkg, DependList Package::*member,\n const char **on, const char **oc, size_t off,\n size_t n)\n{\n if (off >= (pkg.*member).size())\n return 0;\n auto i = (pkg.*member).begin() + off;\n auto end = (pkg.*member).end();\n size_t got = 0;\n for (; i != end; ++i) {\n if (!n--)\n return got;\n on[got] = std::get<0>(*i).c_str();\n oc[got] = std::get<1>(*i).c_str();\n ++got;\n }\n return got;\n}\n\nstatic inline\nint pkg_dependlist_add(Package& pkg, DependList Package::*member,\n const char *name, const char *constraint)\n{\n (pkg.*member).emplace_back(name, constraint ? constraint : \"\");\n return 1;\n}\n\nstatic inline\nint pkg_dependlist_del_name(Package& pkg, DependList Package::*member,\n const char *name)\n{\n auto i = (pkg.*member).begin();\n auto end = (pkg.*member).end();\n for (; i != end; ++i) {\n if (std::get<0>(*i) == name) {\n (pkg.*member).erase(i);\n return 1;\n }\n }\n return 0;\n}\n\nstatic inline\nint pkg_dependlist_del_full(Package& pkg, DependList Package::*member,\n const char *name, const char *constraint)\n{\n auto i = (pkg.*member).begin();\n auto end = (pkg.*member).end();\n for (; i != end; ++i) {\n if (std::get<0>(*i) == name && std::get<1>(*i) == constraint) {\n (pkg.*member).erase(i);\n return 1;\n }\n }\n return 0;\n}\n\nstatic inline\nint pkg_dependlist_del_i(Package& pkg, DependList Package::*member, size_t i) {\n if (i >= (pkg.*member).size())\n return 0;\n (pkg.*member).erase((pkg.*member).begin() + i);\n return 1;\n}\n\nsize_t pkgdepdb_pkg_dep_count(pkgdepdb_pkg *pkg_, unsigned int what) {\n auto pkg = reinterpret_cast<Package*>(pkg_);\n if (what >= kDepMemberCount)\n return 0;\n return pkg_dependlist_count(*pkg, kDepMember[what]);\n}\n\nsize_t pkgdepdb_pkg_dep_get(pkgdepdb_pkg *pkg_, unsigned int what,\n const char **on, const char **oc, size_t off,\n size_t n)\n{\n auto pkg = reinterpret_cast<Package*>(pkg_);\n if (what >= kDepMemberCount)\n return 0;\n return pkg_dependlist_get(*pkg, kDepMember[what], on, oc, off, n);\n}\n\nint pkgdepdb_pkg_dep_add(pkgdepdb_pkg *pkg_, unsigned int what,\n const char *name, const char *constraint)\n{\n auto pkg = reinterpret_cast<Package*>(pkg_);\n if (what >= kDepMemberCount)\n return 0;\n return pkg_dependlist_add(*pkg, kDepMember[what], name, constraint);\n}\n\nint pkgdepdb_pkg_dep_del_name(pkgdepdb_pkg *pkg_, unsigned int what,\n const char *name)\n{\n auto pkg = reinterpret_cast<Package*>(pkg_);\n if (what >= kDepMemberCount)\n return 0;\n return pkg_dependlist_del_name(*pkg, kDepMember[what], name);\n}\n\nint pkgdepdb_pkg_dep_del_full(pkgdepdb_pkg *pkg_, unsigned int what,\n const char *name, const char *constraint)\n{\n auto pkg = reinterpret_cast<Package*>(pkg_);\n if (what >= kDepMemberCount)\n return 0;\n return pkg_dependlist_del_full(*pkg, kDepMember[what], name, constraint);\n}\n\nint pkgdepdb_pkg_dep_del_i(pkgdepdb_pkg *pkg_, unsigned int what, size_t idx) {\n auto pkg = reinterpret_cast<Package*>(pkg_);\n if (what >= kDepMemberCount)\n return 0;\n return pkg_dependlist_del_i(*pkg, kDepMember[what], idx);\n}\n\nsize_t pkgdepdb_pkg_groups_count(pkgdepdb_pkg *pkg_) {\n auto pkg = reinterpret_cast<Package*>(pkg_);\n return pkgdepdb_strlist_count(*pkg, &Package::groups_);\n}\n\nsize_t pkgdepdb_pkg_groups_get(pkgdepdb_pkg *pkg_, const char **o, size_t n) {\n auto pkg = reinterpret_cast<Package*>(pkg_);\n return pkgdepdb_strlist_get(*pkg, &Package::groups_, o, 0, n);\n}\n\nsize_t pkgdepdb_pkg_groups_add(pkgdepdb_pkg *pkg_, const char *v) {\n auto pkg = reinterpret_cast<Package*>(pkg_);\n return pkgdepdb_strlist_add_unique(*pkg, &Package::groups_, v);\n}\n\nsize_t pkgdepdb_pkg_groups_del_s(pkgdepdb_pkg *pkg_, const char *v) {\n auto pkg = reinterpret_cast<Package*>(pkg_);\n return pkgdepdb_strlist_del_s_all(*pkg, &Package::groups_, v);\n}\n\nsize_t pkgdepdb_pkg_groups_del_i(pkgdepdb_pkg *pkg_, size_t index) {\n auto pkg = reinterpret_cast<Package*>(pkg_);\n return pkgdepdb_strlist_del_i(*pkg, &Package::groups_, index);\n}\n\nsize_t pkgdepdb_pkg_filelist_count(pkgdepdb_pkg *pkg_) {\n auto pkg = reinterpret_cast<Package*>(pkg_);\n return pkgdepdb_strlist_count(*pkg, &Package::filelist_);\n}\n\nsize_t pkgdepdb_pkg_filelist_get(pkgdepdb_pkg *pkg_,\n const char **out, size_t off, size_t count)\n{\n auto pkg = reinterpret_cast<Package*>(pkg_);\n return pkgdepdb_strlist_get(*pkg, &Package::filelist_, out, off, count);\n}\n\nsize_t pkgdepdb_pkg_filelist_add(pkgdepdb_pkg *pkg_, const char *v) {\n auto pkg = reinterpret_cast<Package*>(pkg_);\n return pkgdepdb_strlist_add_always(*pkg, &Package::filelist_, v);\n}\n\nsize_t pkgdepdb_pkg_filelist_del_s(pkgdepdb_pkg *pkg_, const char *v) {\n auto pkg = reinterpret_cast<Package*>(pkg_);\n return pkgdepdb_strlist_del_s_one(*pkg, &Package::filelist_, v);\n}\n\nsize_t pkgdepdb_pkg_filelist_del_i(pkgdepdb_pkg *pkg_, size_t index) {\n auto pkg = reinterpret_cast<Package*>(pkg_);\n return pkgdepdb_strlist_del_i(*pkg, &Package::filelist_, index);\n}\n\nvoid pkgdepdb_pkg_guess_version(pkgdepdb_pkg *pkg_, const char *filename) {\n auto pkg = reinterpret_cast<Package*>(pkg_);\n pkg->Guess(filename);\n}\n\nint pkgdepdb_pkg_conflict(pkgdepdb_pkg *subj_, pkgdepdb_pkg *obj_) {\n auto pkg = reinterpret_cast<Package*>(subj_);\n auto obj = reinterpret_cast<Package*>(obj_);\n return pkg->ConflictsWith(*obj);\n}\n\nint pkgdepdb_pkg_replaces(pkgdepdb_pkg *subj_, pkgdepdb_pkg *obj_) {\n auto pkg = reinterpret_cast<Package*>(subj_);\n auto obj = reinterpret_cast<Package*>(obj_);\n return pkg->Replaces(*obj);\n}\n\n} \/\/ extern \"C\"\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2017 Adam Smith\n\/\/ \n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/ \n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/ \n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include <cctype>\n#include <sstream>\n#include \"as\/serial_value\/xml.hpp\"\n\n#define ASMITH_SERIAL_PTR \"as::serial_value::pointer_t=\"\n#define ASMITH_SERIAL_XML \"__as_serial_xml_element\"\n\nbool write_attribute(std::ostream& aStream, const std::string& aName, const as::serial_value& aValue) {\n\t\/\/! \\todo Remove chars illegal in XML\n\tswitch (aValue.get_type()) {\n\tcase as::serial_value::NULL_T:\n\t\taStream << aName << '=' << '\"' << \"null\" << '\"';\n\t\treturn true;\n\tcase as::serial_value::CHAR_T:\n\t\taStream << aName << '=' << '\"' << aValue.get_char() << '\"';\n\t\treturn true;\n\tcase as::serial_value::BOOL_T:\n\t\taStream << aName << '=' << '\"' << (aValue.get_bool() ? \"true\" : \"false\") << '\"';\n\t\treturn true;\n\tcase as::serial_value::UNSIGNED_T:\n\t\taStream << aName << '=' << '\"' << aValue.get_unsigned() << '\"';\n\t\treturn true;\n\tcase as::serial_value::SIGNED_T:\n\t\taStream << aName << '=' << '\"' << aValue.get_signed() << '\"';\n\t\treturn true;\n\tcase as::serial_value::FLOAT_T:\n\t\taStream << aName << '=' << '\"' << aValue.get_float() << '\"';\n\t\treturn true;\n\tcase as::serial_value::POINTER_T:\n\t\taStream << aName << '=' << '\"' << ASMITH_SERIAL_PTR << aValue.get_pointer() << '\"';\n\t\treturn true;\n\tcase as::serial_value::STRING_T:\n\t\taStream << aName << '=' << '\"' << aValue.get_string() << '\"';\n\t\treturn true;\n\tdefault:\n\t\treturn false;\n\t}\n}\n\nvoid write_element(std::ostream& aStream, const std::string& aName, const as::serial_value& aValue) {\n\t\/\/! \\todo Remove chars illegal in XML\n\tswitch (aValue.get_type()) {\n\tcase as::serial_value::NULL_T:\n\t\taStream << '<' << aName << '\/' << '>';\n\t\tbreak;\n\tcase as::serial_value::CHAR_T:\n\t\taStream << '<' << aName << '>' << aValue.get_char() << '<' << '\/' << aName << '>';\n\t\tbreak;\n\tcase as::serial_value::BOOL_T:\n\t\taStream << '<' << aName << '>' << (aValue.get_bool() ? \"true\" : \"false\") << '<' << '\/' << aName << '>';\n\t\tbreak;\n\tcase as::serial_value::UNSIGNED_T:\n\t\taStream << '<' << aName << '>' << aValue.get_unsigned() << '<' << '\/' << aName << '>';\n\t\tbreak;\n\tcase as::serial_value::SIGNED_T:\n\t\taStream << '<' << aName << '>' << aValue.get_signed() << '<' << '\/' << aName << '>';\n\t\tbreak;\n\tcase as::serial_value::FLOAT_T:\n\t\taStream << '<' << aName << '>' << aValue.get_float() << '<' << '\/' << aName << '>';\n\t\tbreak;\n\tcase as::serial_value::POINTER_T:\n\t\taStream << '<' << aName << '>' << ASMITH_SERIAL_PTR << aValue.get_pointer() << '<' << '\/' << aName << '>';\n\t\tbreak;\n\tcase as::serial_value::STRING_T:\n\t\taStream << '<' << aName << '>' << aValue.get_string() << '<' << '\/' << aName << '>';\n\t\tbreak;\n\tcase as::serial_value::ARRAY_T:\n\t\t{\n\t\t\taStream << '<' << aName << '>';\n\t\t\tconst as::serial_value::array_t& array_ = aValue.get_array();\n\t\t\tconst size_t s = array_.size();\n\t\t\tfor(size_t i = 0; i < s; ++i) write_element(aStream, std::to_string(i), array_[i]);\n\t\t\taStream << '<' << '\/' << aName << '>';\n\t\t}\n\t\tbreak;\n\tcase as::serial_value::OBJECT_T:\n\t\t{\n\t\t\tconst as::serial_value::object_t& object = aValue.get_object();\n\t\t\taStream << '<' << aName;\n\t\t\tsize_t attributes = 0;\n\t\t\tfor(const auto& i : object) {\n\t\t\t\tconst as::serial_value::type t = i.second.get_type();\n\t\t\t\tif(t != as::serial_value::ARRAY_T && t != as::serial_value::OBJECT_T) {\n\t\t\t\t\twrite_attribute(aStream, i.first, i.second);\n\t\t\t\t\t++attributes;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif(attributes == object.size()) {\n\t\t\t\taStream << '\/' << '>';\n\t\t\t}else {\n\t\t\t\taStream << '>';\n\t\t\t\tfor(const auto& i : object) {\n\t\t\t\t\tconst as::serial_value::type t = i.second.get_type();\n\t\t\t\t\tif(t == as::serial_value::ARRAY_T || t == as::serial_value::OBJECT_T) {\n\t\t\t\t\t\twrite_element(aStream, i.first, i.second);\n\t\t\t\t\t\t++attributes;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\taStream << '<' << '\/' << aName << '>';\n\t\t\t}\n\t\t}\n\t\tbreak;\n\t}\n}\n\nstruct element {\n\tstd::string name;\n\tstd::string body;\n\tstd::map<std::string, std::string> attributes;\n\tstd::vector<element> elements;\n};\n\nvoid ignore_whitespace_x(std::istream& aStream) {\n\tchar c = aStream.peek();\n\twhile (std::isspace(c)) {\n\t\taStream >> c;\n\t\tc = aStream.peek();\n\t}\n}\n\nvoid close_closing_tag(std::istream& aStream, element& e) {\n\t\/\/! \\todo Implement\n}\n\nvoid read_closing_name(std::istream& aStream, element& e) {\n\t\/\/! \\todo Implement\n\tclose_closing_tag(aStream, e);\n}\n\nvoid open_closing_tag(std::istream& aStream, element& e) {\n\t\/\/! \\todo Implement\n\tread_closing_name(aStream, e);\n}\n\nvoid read_elements(std::istream& aStream, element& e) {\n\tconst auto pos = aStream.tellg();\n\tchar c;\n\tc = aStream.peek();\n\tif(c != '<') throw std::runtime_error(\"as::deserialise_xml : Expected element to begin with '<'\");\n\tc = aStream.peek();\n\taStream.seekg(pos);\n\tif(c == '\/') {\n\t\t\/\/ Closing tag of e\n\t\taStream.seekg(pos);\n\t}else {\n\t\telement e2;\n\t\topen_opening_tag(aStream, e2);\n\t\te.elements.push_back(e2);\n\t\t\/\/ Next state\n\t\tread_elements(aStream, e);\n\t}\n}\n\n\nvoid read_body(std::istream& aStream, element& e) {\n\tignore_whitespace_x(aStream);\n\tchar c;\n\n\tc = aStream.peek();\n\tif(c == '<') {\n\t\tread_elements(aStream, e);\n\t}else {\n\t\t while (c != '<') {\n\t\t\t e.body += c;\n\t\t\t aStream >> c;\n\t\t\t c = aStream.peek();\n\t\t }\n\t}\n\n\t\/\/ Next state\n\topen_closing_tag(aStream, e);\n}\n\nvoid close_opening_tag(std::istream&, element&);\n\nvoid read_attribute(std::istream& aStream, element& e) {\n\tstd::string name;\n\tstd::string value;\n\tchar c;\n\n\t\/\/ Read name\n\tignore_whitespace_x(aStream);\n\taStream >> c;\n\twhile(c != '='){\n\t\tname += c;\n\t\taStream >> c;\n\t}\n\n\t\/\/ Read value\n\tignore_whitespace_x(aStream);\n\taStream >> c;\n\tif(c != '\"') throw std::runtime_error(\"as::deserialise_xml : Expected attribute value to begin with '\\\"'\");\n\taStream >> c;\n\twhile(c != '\"') {\n\t\tvalue += c;\n\t\taStream >> c;\n\t}\n\n\t\/\/ Next state\n\te.attributes.emplace(name, value);\n\tclose_opening_tag(aStream, e);\n}\n\nvoid close_opening_tag(std::istream& aStream, element& e) {\n\tignore_whitespace_x(aStream);\n\tchar c = aStream.peek();\n\tif(c == '\/') {\n\t\t\/\/ End element\n\t\taStream >> c;\n\t\taStream >> c;\n\t\tif(c != '>') throw std::runtime_error(\"as::deserialise_xml : Expected closing tag to end with '>'\");\n\t}else if (c == '>') {\n\t\t\/\/ Next state\n\t\tread_body(aStream, e);\n\t}else {\n\t\tread_attribute(aStream, e);\n\t}\n}\n\nvoid read_opening_tag_name(std::istream& aStream, element& e) {\n\tignore_whitespace_x(aStream);\n\tchar c;\n\tignore_whitespace_x(aStream);\n\tc = aStream.peek();\n\twhile(c != '>' && c != '\/' && !std::isspace(c)) {\n\t\te.name += c;\n\t\taStream >> c;\n\t\tc = aStream.peek();\n\t}\n\t\/\/ Next state\n\tclose_opening_tag(aStream, e);\n}\n\nvoid open_opening_tag(std::istream& aStream, element& e) {\n\tignore_whitespace_x(aStream);\n\tchar c;\n\taStream >> c;\n\tif(c != '<') throw std::runtime_error(\"as::deserialise_xml : Expected opening tag to begin with '<'\");\n\t\/\/ Next state\n\tread_opening_tag_name(aStream, e);\n}\n\nas::serial_value convert_element(const element& aElement) {\n\t\/\/ Check if array\n\tsize_t contiguousNames = 0;\n\tconst size_t eCount = aElement.elements.size();\n\tfor(size_t i = 0; i < eCount; ++i) if(aElement.elements[i].name == std::to_string(i)) ++contiguousNames;\n\tif(eCount > 0 && contiguousNames == eCount) {\n\t\t\/\/ Element is an array\n\t\tas::serial_value tmp;\n\t\tas::serial_value::array_t& array_ = tmp.set_array();\n\t\tfor(size_t i = 0; i < eCount; ++i) array_.push_back(convert_element(aElement.elements[i]));\n\t\treturn tmp;\n\t}\n\n\t\/\/ Check if value\n\tif(aElement.elements.empty() && aElement.attributes.empty()) {\n\t\t\/\/ Element is a value\n\t\tif(aElement.body.empty()) return as::serial_value();\n\t\telse return as::serial_value(aElement.body);\n\t}\n\n\t\/\/ Element is an object\n\tas::serial_value tmp;\n\tas::serial_value::object_t& object = tmp.set_object();\n\tif(! aElement.body.empty()) {\n\t\t\/\/! \\todo Handle body\n\t}\n\tfor(const auto& i : aElement.attributes) {\n\t\tobject.emplace(i.first, as::serial_value(i.second));\n\t}\n\tfor(const auto& i : aElement.elements) {\n\t\t\/\/! \\todo Handle for name conflicts\n\t\tobject.emplace(i.name, convert_element(i));\n\t}\n\treturn tmp;\n}\n\nnamespace as {\n\tvoid serialise_xml(std::ostream& aStream, const serial_value& aValue) {\n\t\twrite_element(aStream, ASMITH_SERIAL_XML, aValue);\n\t}\n\n\tserial_value deserialise_xml(std::istream& aStream) {\n\t\t\/\/! \\todo Handle XML header\n\t\t\/\/! \\todo Handle XML comments\n\t\telement e;\n\t\topen_opening_tag(aStream, e);\n\t\treturn convert_element(e);\n\t}\n\n}<commit_msg>Implemented closing tag code<commit_after>\/\/ Copyright 2017 Adam Smith\n\/\/ \n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/ \n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/ \n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include <cctype>\n#include <sstream>\n#include \"as\/serial_value\/xml.hpp\"\n\n#define ASMITH_SERIAL_PTR \"as::serial_value::pointer_t=\"\n#define ASMITH_SERIAL_XML \"__as_serial_xml_element\"\n\nbool write_attribute(std::ostream& aStream, const std::string& aName, const as::serial_value& aValue) {\n\t\/\/! \\todo Remove chars illegal in XML\n\tswitch (aValue.get_type()) {\n\tcase as::serial_value::NULL_T:\n\t\taStream << aName << '=' << '\"' << \"null\" << '\"';\n\t\treturn true;\n\tcase as::serial_value::CHAR_T:\n\t\taStream << aName << '=' << '\"' << aValue.get_char() << '\"';\n\t\treturn true;\n\tcase as::serial_value::BOOL_T:\n\t\taStream << aName << '=' << '\"' << (aValue.get_bool() ? \"true\" : \"false\") << '\"';\n\t\treturn true;\n\tcase as::serial_value::UNSIGNED_T:\n\t\taStream << aName << '=' << '\"' << aValue.get_unsigned() << '\"';\n\t\treturn true;\n\tcase as::serial_value::SIGNED_T:\n\t\taStream << aName << '=' << '\"' << aValue.get_signed() << '\"';\n\t\treturn true;\n\tcase as::serial_value::FLOAT_T:\n\t\taStream << aName << '=' << '\"' << aValue.get_float() << '\"';\n\t\treturn true;\n\tcase as::serial_value::POINTER_T:\n\t\taStream << aName << '=' << '\"' << ASMITH_SERIAL_PTR << aValue.get_pointer() << '\"';\n\t\treturn true;\n\tcase as::serial_value::STRING_T:\n\t\taStream << aName << '=' << '\"' << aValue.get_string() << '\"';\n\t\treturn true;\n\tdefault:\n\t\treturn false;\n\t}\n}\n\nvoid write_element(std::ostream& aStream, const std::string& aName, const as::serial_value& aValue) {\n\t\/\/! \\todo Remove chars illegal in XML\n\tswitch (aValue.get_type()) {\n\tcase as::serial_value::NULL_T:\n\t\taStream << '<' << aName << '\/' << '>';\n\t\tbreak;\n\tcase as::serial_value::CHAR_T:\n\t\taStream << '<' << aName << '>' << aValue.get_char() << '<' << '\/' << aName << '>';\n\t\tbreak;\n\tcase as::serial_value::BOOL_T:\n\t\taStream << '<' << aName << '>' << (aValue.get_bool() ? \"true\" : \"false\") << '<' << '\/' << aName << '>';\n\t\tbreak;\n\tcase as::serial_value::UNSIGNED_T:\n\t\taStream << '<' << aName << '>' << aValue.get_unsigned() << '<' << '\/' << aName << '>';\n\t\tbreak;\n\tcase as::serial_value::SIGNED_T:\n\t\taStream << '<' << aName << '>' << aValue.get_signed() << '<' << '\/' << aName << '>';\n\t\tbreak;\n\tcase as::serial_value::FLOAT_T:\n\t\taStream << '<' << aName << '>' << aValue.get_float() << '<' << '\/' << aName << '>';\n\t\tbreak;\n\tcase as::serial_value::POINTER_T:\n\t\taStream << '<' << aName << '>' << ASMITH_SERIAL_PTR << aValue.get_pointer() << '<' << '\/' << aName << '>';\n\t\tbreak;\n\tcase as::serial_value::STRING_T:\n\t\taStream << '<' << aName << '>' << aValue.get_string() << '<' << '\/' << aName << '>';\n\t\tbreak;\n\tcase as::serial_value::ARRAY_T:\n\t\t{\n\t\t\taStream << '<' << aName << '>';\n\t\t\tconst as::serial_value::array_t& array_ = aValue.get_array();\n\t\t\tconst size_t s = array_.size();\n\t\t\tfor(size_t i = 0; i < s; ++i) write_element(aStream, std::to_string(i), array_[i]);\n\t\t\taStream << '<' << '\/' << aName << '>';\n\t\t}\n\t\tbreak;\n\tcase as::serial_value::OBJECT_T:\n\t\t{\n\t\t\tconst as::serial_value::object_t& object = aValue.get_object();\n\t\t\taStream << '<' << aName;\n\t\t\tsize_t attributes = 0;\n\t\t\tfor(const auto& i : object) {\n\t\t\t\tconst as::serial_value::type t = i.second.get_type();\n\t\t\t\tif(t != as::serial_value::ARRAY_T && t != as::serial_value::OBJECT_T) {\n\t\t\t\t\twrite_attribute(aStream, i.first, i.second);\n\t\t\t\t\t++attributes;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif(attributes == object.size()) {\n\t\t\t\taStream << '\/' << '>';\n\t\t\t}else {\n\t\t\t\taStream << '>';\n\t\t\t\tfor(const auto& i : object) {\n\t\t\t\t\tconst as::serial_value::type t = i.second.get_type();\n\t\t\t\t\tif(t == as::serial_value::ARRAY_T || t == as::serial_value::OBJECT_T) {\n\t\t\t\t\t\twrite_element(aStream, i.first, i.second);\n\t\t\t\t\t\t++attributes;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\taStream << '<' << '\/' << aName << '>';\n\t\t\t}\n\t\t}\n\t\tbreak;\n\t}\n}\n\nstruct element {\n\tstd::string name;\n\tstd::string body;\n\tstd::map<std::string, std::string> attributes;\n\tstd::vector<element> elements;\n};\n\nvoid ignore_whitespace_x(std::istream& aStream) {\n\tchar c = aStream.peek();\n\twhile (std::isspace(c)) {\n\t\taStream >> c;\n\t\tc = aStream.peek();\n\t}\n}\n\nvoid close_closing_tag(std::istream& aStream, element& e) {\n\tignore_whitespace_x(aStream);\n\tchar c;\n\taStream >> c;\n\tif(c != '>') throw std::runtime_error(\"as::deserialise_xml : Expected closing tag to end with '>'\");\n}\n\nvoid read_closing_name(std::istream& aStream, element& e) {\n\tignore_whitespace_x(aStream);\n\tchar c;\n\tignore_whitespace_x(aStream);\n\tc = aStream.peek();\n\tstd::string name;\n\twhile(c != '>' && ! std::isspace(c)) {\n\t\tname += c;\n\t\taStream >> c;\n\t\tc = aStream.peek();\n\t}\n\tif(name != e.name) throw std::runtime_error(\"as::deserialise_xml : Expected closing tag to have same name as opening tag\");\n\t\/\/ Next state\n\tclose_closing_tag(aStream, e);\n}\n\nvoid open_closing_tag(std::istream& aStream, element& e) {\n\tread_closing_name(aStream, e);\n\tchar c;\n\taStream >> c;\n\tif(c != '<') throw std::runtime_error(\"as::deserialise_xml : Expected closing tag to begin with '<\/'\");\n\taStream >> c;\n\tif(c != '\/') throw std::runtime_error(\"as::deserialise_xml : Expected closing tag to begin with '<\/'\");\n\t\/\/ Next state\n\tread_closing_name(aStream, e);\n}\n\nvoid open_opening_tag(std::istream&, element&);\n\nvoid read_elements(std::istream& aStream, element& e) {\n\tconst auto pos = aStream.tellg();\n\tchar c;\n\tc = aStream.peek();\n\tif(c != '<') throw std::runtime_error(\"as::deserialise_xml : Expected element to begin with '<'\");\n\tc = aStream.peek();\n\taStream.seekg(pos);\n\tif(c == '\/') {\n\t\t\/\/ Closing tag of e\n\t\taStream.seekg(pos);\n\t}else {\n\t\telement e2;\n\t\topen_opening_tag(aStream, e2);\n\t\te.elements.push_back(e2);\n\t\t\/\/ Next state\n\t\tread_elements(aStream, e);\n\t}\n}\n\n\nvoid read_body(std::istream& aStream, element& e) {\n\tignore_whitespace_x(aStream);\n\tchar c;\n\n\tc = aStream.peek();\n\tif(c == '<') {\n\t\tread_elements(aStream, e);\n\t}else {\n\t\t while (c != '<') {\n\t\t\t e.body += c;\n\t\t\t aStream >> c;\n\t\t\t c = aStream.peek();\n\t\t }\n\t}\n\n\t\/\/ Next state\n\topen_closing_tag(aStream, e);\n}\n\nvoid close_opening_tag(std::istream&, element&);\n\nvoid read_attribute(std::istream& aStream, element& e) {\n\tstd::string name;\n\tstd::string value;\n\tchar c;\n\n\t\/\/ Read name\n\tignore_whitespace_x(aStream);\n\taStream >> c;\n\twhile(c != '='){\n\t\tname += c;\n\t\taStream >> c;\n\t}\n\n\t\/\/ Read value\n\tignore_whitespace_x(aStream);\n\taStream >> c;\n\tif(c != '\"') throw std::runtime_error(\"as::deserialise_xml : Expected attribute value to begin with '\\\"'\");\n\taStream >> c;\n\twhile(c != '\"') {\n\t\tvalue += c;\n\t\taStream >> c;\n\t}\n\n\t\/\/ Next state\n\te.attributes.emplace(name, value);\n\tclose_opening_tag(aStream, e);\n}\n\nvoid close_opening_tag(std::istream& aStream, element& e) {\n\tignore_whitespace_x(aStream);\n\tchar c = aStream.peek();\n\tif(c == '\/') {\n\t\t\/\/ End element\n\t\taStream >> c;\n\t\taStream >> c;\n\t\tif(c != '>') throw std::runtime_error(\"as::deserialise_xml : Expected closing tag to end with '>'\");\n\t}else if (c == '>') {\n\t\t\/\/ Next state\n\t\tread_body(aStream, e);\n\t}else {\n\t\tread_attribute(aStream, e);\n\t}\n}\n\nvoid read_opening_tag_name(std::istream& aStream, element& e) {\n\tignore_whitespace_x(aStream);\n\tchar c;\n\tignore_whitespace_x(aStream);\n\tc = aStream.peek();\n\twhile(c != '>' && c != '\/' && !std::isspace(c)) {\n\t\te.name += c;\n\t\taStream >> c;\n\t\tc = aStream.peek();\n\t}\n\t\/\/ Next state\n\tclose_opening_tag(aStream, e);\n}\n\nvoid open_opening_tag(std::istream& aStream, element& e) {\n\tignore_whitespace_x(aStream);\n\tchar c;\n\taStream >> c;\n\tif(c != '<') throw std::runtime_error(\"as::deserialise_xml : Expected opening tag to begin with '<'\");\n\t\/\/ Next state\n\tread_opening_tag_name(aStream, e);\n}\n\nas::serial_value convert_element(const element& aElement) {\n\t\/\/ Check if array\n\tsize_t contiguousNames = 0;\n\tconst size_t eCount = aElement.elements.size();\n\tfor(size_t i = 0; i < eCount; ++i) if(aElement.elements[i].name == std::to_string(i)) ++contiguousNames;\n\tif(eCount > 0 && contiguousNames == eCount) {\n\t\t\/\/ Element is an array\n\t\tas::serial_value tmp;\n\t\tas::serial_value::array_t& array_ = tmp.set_array();\n\t\tfor(size_t i = 0; i < eCount; ++i) array_.push_back(convert_element(aElement.elements[i]));\n\t\treturn tmp;\n\t}\n\n\t\/\/ Check if value\n\tif(aElement.elements.empty() && aElement.attributes.empty()) {\n\t\t\/\/ Element is a value\n\t\tif(aElement.body.empty()) return as::serial_value();\n\t\telse return as::serial_value(aElement.body);\n\t}\n\n\t\/\/ Element is an object\n\tas::serial_value tmp;\n\tas::serial_value::object_t& object = tmp.set_object();\n\tif(! aElement.body.empty()) {\n\t\t\/\/! \\todo Handle body\n\t}\n\tfor(const auto& i : aElement.attributes) {\n\t\tobject.emplace(i.first, as::serial_value(i.second));\n\t}\n\tfor(const auto& i : aElement.elements) {\n\t\t\/\/! \\todo Handle for name conflicts\n\t\tobject.emplace(i.name, convert_element(i));\n\t}\n\treturn tmp;\n}\n\nnamespace as {\n\tvoid serialise_xml(std::ostream& aStream, const serial_value& aValue) {\n\t\twrite_element(aStream, ASMITH_SERIAL_XML, aValue);\n\t}\n\n\tserial_value deserialise_xml(std::istream& aStream) {\n\t\t\/\/! \\todo Handle XML header\n\t\t\/\/! \\todo Handle XML comments\n\t\telement e;\n\t\topen_opening_tag(aStream, e);\n\t\treturn convert_element(e);\n\t}\n\n}<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2014 Alessio Sclocco <a.sclocco@vu.nl>\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include <iostream>\n#include <string>\n#include <vector>\n#include <exception>\n#include <fstream>\n#include <iomanip>\n#include <limits>\n#include <ctime>\n\n#include <ArgumentList.hpp>\n#include <Observation.hpp>\n#include <utils.hpp>\n#include <Bins.hpp>\n\ntypedef float dataType;\nstd::string typeName(\"float\");\n\n\nint main(int argc, char *argv[]) {\n bool print = false;\n\tAstroData::Observation observation;\n\n\ttry {\n isa::utils::ArgumentList args(argc, argv);\n print = args.getSwitch(\"-print\");\n observation.setPadding(1);\n observation.setNrSeconds(args.getSwitchArgument< unsigned int >(\"-seconds\"));\n observation.setNrSamplesPerSecond(args.getSwitchArgument< unsigned int >(\"-samples\"));\n observation.setDMRange(args.getSwitchArgument< unsigned int >(\"-dms\"), 0.0, 0.0);\n observation.setPeriodRange(args.getSwitchArgument< unsigned int >(\"-periods\"), args.getSwitchArgument< unsigned int >(\"-first_period\"), args.getSwitchArgument< unsigned int >(\"-period_step\"));\n observation.setNrBins(args.getSwitchArgument< unsigned int >(\"-bins\"));\n\t} catch ( isa::utils::SwitchNotFound &err ) {\n std::cerr << err.what() << std::endl;\n return 1;\n }catch ( std::exception &err ) {\n std::cerr << \"Usage: \" << argv[0] << \" [-print] -seconds ... -samples ... -dms ... -periods ... -bins ... -first_period ... -period_step ...\" << std::endl;\n\t\treturn 1;\n\t}\n\n std::vector< unsigned int > * samplesPerBin = PulsarSearch::getSamplesPerBin(observation);\n\n \/\/ Allocate memory\n std::vector< std::vector< unsigned int > > sequentialMap(observation.getNrSeconds());\n std::vector< std::vector< unsigned int > > parallelMap(observation.getNrSeconds());\n for ( unsigned int second = 0; second < observation.getNrSeconds(); second++ ) {\n sequentialMap[second] = std::vector< unsigned int >(observation.getNrDMs() * observation.getNrPeriods() * observation.getNrSamplesPerSecond());\n parallelMap[second] = std::vector< unsigned int >(observation.getNrDMs() * observation.getNrPeriods() * observation.getNrSamplesPerSecond());\n }\n std::vector< unsigned int > parallelCounter(observation.getNrDMs() * observation.getNrPeriods() * observation.getNrBins());\n\n std::fill(parallelCounter.begin(), parallelCounter.end(), 0);\n\n \/\/ Sequential\n for ( unsigned int dm = 0; dm < observation.getNrDMs(); dm++ ) {\n for ( unsigned int period = 0; period < observation.getNrPeriods(); period++ ) {\n const unsigned int periodValue = observation.getFirstPeriod() + (period * observation.getPeriodStep());\n\n for ( unsigned int second = 0; second < observation.getNrSeconds(); second++ ) {\n for ( unsigned int sample = 0; sample < observation.getNrSamplesPerSecond(); sample++ ) {\n const unsigned int globalSample = (second * observation.getNrSamplesPerSecond()) + sample;\n const float phase = (globalSample \/ static_cast< float >(periodValue)) - (globalSample \/ periodValue);\n const unsigned int bin = static_cast< unsigned int >(phase * static_cast< float >(observation.getNrBins()));\n\n sequentialMap[second][(dm * observation.getNrPeriods() * observation.getNrSamplesPerSecond()) + (period * observation.getNrSamplesPerSecond()) + sample] = bin;\n }\n }\n }\n }\n\n \/\/ Parallel\n for ( unsigned int second = 0; second < observation.getNrSeconds(); second++ ) {\n for ( unsigned int period = 0; period < observation.getNrPeriods(); period++ ) {\n const unsigned int periodValue = observation.getFirstPeriod() + (period * observation.getPeriodStep());\n\n for ( unsigned int bin = 0; bin < observation.getNrBins(); bin++ ) {\n for ( unsigned int dm = 0; dm < observation.getNrDMs(); dm++ ) {\n unsigned int sample = samplesPerBin->at((period * observation.getNrBins() * isa::utils::pad(2, observation.getPadding())) + (bin * isa::utils::pad(2, observation.getPadding())) + 1) + ((parallelCounter[(dm * observation.getNrPeriods() * observation.getNrBins()) + (period * observation.getNrBins()) + bin] \/ samplesPerBin->at((period * observation.getNrBins() * isa::utils::pad(2, observation.getPadding())) + (bin * isa::utils::pad(2, observation.getPadding())))) * periodValue) + (parallelCounter[(dm * observation.getNrPeriods() * observation.getNrBins()) + (period * observation.getNrBins()) + bin] % samplesPerBin->at((period * observation.getNrBins() * isa::utils::pad(2, observation.getPadding())) + (bin * isa::utils::pad(2, observation.getPadding()))));\n\n if ( (sample \/ observation.getNrSamplesPerSecond()) == second ) {\n sample %= observation.getNrSamplesPerSecond();\n }\n while ( sample < observation.getNrSamplesPerSecond() ) {\n parallelMap[second][(dm * observation.getNrPeriods() * observation.getNrSamplesPerSecond()) + (period * observation.getNrSamplesPerSecond()) + sample] = bin;\n parallelCounter[(dm * observation.getNrPeriods() * observation.getNrBins()) + (period * observation.getNrBins()) + bin] += 1;\n if ( parallelCounter[(dm * observation.getNrPeriods() * observation.getNrBins()) + (period * observation.getNrBins()) + bin] % samplesPerBin->at((period * observation.getNrBins() * isa::utils::pad(2, observation.getPadding())) + (bin * isa::utils::pad(2, observation.getPadding()))) == 0 ) {\n sample += periodValue - (samplesPerBin->at((period * observation.getNrBins() * isa::utils::pad(2, observation.getPadding())) + (bin * isa::utils::pad(2, observation.getPadding()))) - 1);\n } else {\n sample++;\n }\n }\n }\n }\n }\n }\n\n for ( unsigned int dm = 0; dm < observation.getNrDMs(); dm++ ) {\n for ( unsigned int period = 0; period < observation.getNrPeriods(); period++ ) {\n for ( unsigned int second = 0; second < observation.getNrSeconds(); second++ ) {\n for ( unsigned int sample = 0; sample < observation.getNrSamplesPerSecond(); sample++ ) {\n if ( sequentialMap[second][(dm * observation.getNrPeriods() * observation.getNrSamplesPerSecond()) + (period * observation.getNrSamplesPerSecond()) + sample] != parallelMap[second][(dm * observation.getNrPeriods() * observation.getNrSamplesPerSecond()) + (period * observation.getNrSamplesPerSecond()) + sample] ) {\n std::cout << \"DM: \" << dm << \", \";\n std::cout << \"Period: \" << period << \", \";\n std::cout << \"Second: \" << second << \", \";\n std::cout << \"Sample: \" << sample << \", \";\n std::cout << \"Bin (seq): \" << sequentialMap[second][(dm * observation.getNrPeriods() * observation.getNrSamplesPerSecond()) + (period * observation.getNrSamplesPerSecond()) + sample] << \", \";\n std::cout << \"Bin (par): \" << parallelMap[second][(dm * observation.getNrPeriods() * observation.getNrSamplesPerSecond()) + (period * observation.getNrSamplesPerSecond()) + sample] << std::endl;\n } else if ( print ) {\n std::cout << \"DM: \" << dm << \", \";\n std::cout << \"Period: \" << period << \", \";\n std::cout << \"Second: \" << second << \", \";\n std::cout << \"Sample: \" << sample << \", \";\n std::cout << \"Bin (seq): \" << sequentialMap[second][(dm * observation.getNrPeriods() * observation.getNrSamplesPerSecond()) + (period * observation.getNrSamplesPerSecond()) + sample] << \", \";\n std::cout << \"Bin (par): \" << parallelMap[second][(dm * observation.getNrPeriods() * observation.getNrSamplesPerSecond()) + (period * observation.getNrSamplesPerSecond()) + sample] << std::endl;\n }\n }\n }\n }\n }\n\n\treturn 0;\n}\n\n<commit_msg>Using two separate counters, like in OpenCL code. A bug may lie there.<commit_after>\/\/ Copyright 2014 Alessio Sclocco <a.sclocco@vu.nl>\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include <iostream>\n#include <string>\n#include <vector>\n#include <exception>\n#include <fstream>\n#include <iomanip>\n#include <limits>\n#include <ctime>\n\n#include <ArgumentList.hpp>\n#include <Observation.hpp>\n#include <utils.hpp>\n#include <Bins.hpp>\n\ntypedef float dataType;\nstd::string typeName(\"float\");\n\n\nint main(int argc, char *argv[]) {\n bool print = false;\n\tAstroData::Observation observation;\n\n\ttry {\n isa::utils::ArgumentList args(argc, argv);\n print = args.getSwitch(\"-print\");\n observation.setPadding(1);\n observation.setNrSeconds(args.getSwitchArgument< unsigned int >(\"-seconds\"));\n observation.setNrSamplesPerSecond(args.getSwitchArgument< unsigned int >(\"-samples\"));\n observation.setDMRange(args.getSwitchArgument< unsigned int >(\"-dms\"), 0.0, 0.0);\n observation.setPeriodRange(args.getSwitchArgument< unsigned int >(\"-periods\"), args.getSwitchArgument< unsigned int >(\"-first_period\"), args.getSwitchArgument< unsigned int >(\"-period_step\"));\n observation.setNrBins(args.getSwitchArgument< unsigned int >(\"-bins\"));\n\t} catch ( isa::utils::SwitchNotFound &err ) {\n std::cerr << err.what() << std::endl;\n return 1;\n }catch ( std::exception &err ) {\n std::cerr << \"Usage: \" << argv[0] << \" [-print] -seconds ... -samples ... -dms ... -periods ... -bins ... -first_period ... -period_step ...\" << std::endl;\n\t\treturn 1;\n\t}\n\n std::vector< unsigned int > * samplesPerBin = PulsarSearch::getSamplesPerBin(observation);\n\n \/\/ Allocate memory\n std::vector< std::vector< unsigned int > > sequentialMap(observation.getNrSeconds());\n std::vector< std::vector< unsigned int > > parallelMap(observation.getNrSeconds());\n for ( unsigned int second = 0; second < observation.getNrSeconds(); second++ ) {\n sequentialMap[second] = std::vector< unsigned int >(observation.getNrDMs() * observation.getNrPeriods() * observation.getNrSamplesPerSecond());\n parallelMap[second] = std::vector< unsigned int >(observation.getNrDMs() * observation.getNrPeriods() * observation.getNrSamplesPerSecond());\n }\n std::vector< unsigned int > parallelCounter0(observation.getNrPeriods() * observation.getNrBins());\n std::vector< unsigned int > parallelCounter1(observation.getNrPeriods() * observation.getNrBins());\n\n std::fill(parallelCounter0.begin(), parallelCounter0.end(), 0);\n std::fill(parallelCounter1.begin(), parallelCounter1.end(), 0);\n\n \/\/ Sequential\n for ( unsigned int dm = 0; dm < observation.getNrDMs(); dm++ ) {\n for ( unsigned int period = 0; period < observation.getNrPeriods(); period++ ) {\n const unsigned int periodValue = observation.getFirstPeriod() + (period * observation.getPeriodStep());\n\n for ( unsigned int second = 0; second < observation.getNrSeconds(); second++ ) {\n for ( unsigned int sample = 0; sample < observation.getNrSamplesPerSecond(); sample++ ) {\n const unsigned int globalSample = (second * observation.getNrSamplesPerSecond()) + sample;\n const float phase = (globalSample \/ static_cast< float >(periodValue)) - (globalSample \/ periodValue);\n const unsigned int bin = static_cast< unsigned int >(phase * static_cast< float >(observation.getNrBins()));\n\n sequentialMap[second][(dm * observation.getNrPeriods() * observation.getNrSamplesPerSecond()) + (period * observation.getNrSamplesPerSecond()) + sample] = bin;\n }\n }\n }\n }\n\n \/\/ Parallel\n for ( unsigned int second = 0; second < observation.getNrSeconds(); second++ ) {\n for ( unsigned int period = 0; period < observation.getNrPeriods(); period++ ) {\n const unsigned int periodValue = observation.getFirstPeriod() + (period * observation.getPeriodStep());\n\n for ( unsigned int bin = 0; bin < observation.getNrBins(); bin++ ) {\n for ( unsigned int dm = 0; dm < observation.getNrDMs(); dm++ ) {\n unsigned int sample = 0;\n\n if ( second % 2 == 0 ) {\n sample = samplesPerBin->at((period * observation.getNrBins() * isa::utils::pad(2, observation.getPadding())) + (bin * isa::utils::pad(2, observation.getPadding())) + 1) + ((parallelCounter0[(dm * observation.getNrPeriods() * observation.getNrBins()) + (period * observation.getNrBins()) + bin] \/ samplesPerBin->at((period * observation.getNrBins() * isa::utils::pad(2, observation.getPadding())) + (bin * isa::utils::pad(2, observation.getPadding())))) * periodValue) + (parallelCounter0[(dm * observation.getNrPeriods() * observation.getNrBins()) + (period * observation.getNrBins()) + bin] % samplesPerBin->at((period * observation.getNrBins() * isa::utils::pad(2, observation.getPadding())) + (bin * isa::utils::pad(2, observation.getPadding()))));\n } else {\n sample = samplesPerBin->at((period * observation.getNrBins() * isa::utils::pad(2, observation.getPadding())) + (bin * isa::utils::pad(2, observation.getPadding())) + 1) + ((parallelCounter1[(dm * observation.getNrPeriods() * observation.getNrBins()) + (period * observation.getNrBins()) + bin] \/ samplesPerBin->at((period * observation.getNrBins() * isa::utils::pad(2, observation.getPadding())) + (bin * isa::utils::pad(2, observation.getPadding())))) * periodValue) + (parallelCounter1[(dm * observation.getNrPeriods() * observation.getNrBins()) + (period * observation.getNrBins()) + bin] % samplesPerBin->at((period * observation.getNrBins() * isa::utils::pad(2, observation.getPadding())) + (bin * isa::utils::pad(2, observation.getPadding()))));\n }\n\n if ( (sample \/ observation.getNrSamplesPerSecond()) == second ) {\n sample %= observation.getNrSamplesPerSecond();\n }\n while ( sample < observation.getNrSamplesPerSecond() ) {\n parallelMap[second][(dm * observation.getNrPeriods() * observation.getNrSamplesPerSecond()) + (period * observation.getNrSamplesPerSecond()) + sample] = bin;\n if ( second % 2 == 0 ) {\n parallelCounter1[(dm * observation.getNrPeriods() * observation.getNrBins()) + (period * observation.getNrBins()) + bin] += 1;\n if ( parallelCounter1[(dm * observation.getNrPeriods() * observation.getNrBins()) + (period * observation.getNrBins()) + bin] % samplesPerBin->at((period * observation.getNrBins() * isa::utils::pad(2, observation.getPadding())) + (bin * isa::utils::pad(2, observation.getPadding()))) == 0 ) {\n sample += periodValue - (samplesPerBin->at((period * observation.getNrBins() * isa::utils::pad(2, observation.getPadding())) + (bin * isa::utils::pad(2, observation.getPadding()))) - 1);\n } else {\n sample++;\n }\n } else {\n parallelCounter0[(dm * observation.getNrPeriods() * observation.getNrBins()) + (period * observation.getNrBins()) + bin] += 1;\n if ( parallelCounter0[(dm * observation.getNrPeriods() * observation.getNrBins()) + (period * observation.getNrBins()) + bin] % samplesPerBin->at((period * observation.getNrBins() * isa::utils::pad(2, observation.getPadding())) + (bin * isa::utils::pad(2, observation.getPadding()))) == 0 ) {\n sample += periodValue - (samplesPerBin->at((period * observation.getNrBins() * isa::utils::pad(2, observation.getPadding())) + (bin * isa::utils::pad(2, observation.getPadding()))) - 1);\n } else {\n sample++;\n }\n }\n }\n }\n }\n }\n }\n\n for ( unsigned int dm = 0; dm < observation.getNrDMs(); dm++ ) {\n for ( unsigned int period = 0; period < observation.getNrPeriods(); period++ ) {\n for ( unsigned int second = 0; second < observation.getNrSeconds(); second++ ) {\n for ( unsigned int sample = 0; sample < observation.getNrSamplesPerSecond(); sample++ ) {\n if ( sequentialMap[second][(dm * observation.getNrPeriods() * observation.getNrSamplesPerSecond()) + (period * observation.getNrSamplesPerSecond()) + sample] != parallelMap[second][(dm * observation.getNrPeriods() * observation.getNrSamplesPerSecond()) + (period * observation.getNrSamplesPerSecond()) + sample] ) {\n std::cout << \"DM: \" << dm << \", \";\n std::cout << \"Period: \" << period << \", \";\n std::cout << \"Second: \" << second << \", \";\n std::cout << \"Sample: \" << sample << \", \";\n std::cout << \"Bin (seq): \" << sequentialMap[second][(dm * observation.getNrPeriods() * observation.getNrSamplesPerSecond()) + (period * observation.getNrSamplesPerSecond()) + sample] << \", \";\n std::cout << \"Bin (par): \" << parallelMap[second][(dm * observation.getNrPeriods() * observation.getNrSamplesPerSecond()) + (period * observation.getNrSamplesPerSecond()) + sample] << std::endl;\n } else if ( print ) {\n std::cout << \"DM: \" << dm << \", \";\n std::cout << \"Period: \" << period << \", \";\n std::cout << \"Second: \" << second << \", \";\n std::cout << \"Sample: \" << sample << \", \";\n std::cout << \"Bin (seq): \" << sequentialMap[second][(dm * observation.getNrPeriods() * observation.getNrSamplesPerSecond()) + (period * observation.getNrSamplesPerSecond()) + sample] << \", \";\n std::cout << \"Bin (par): \" << parallelMap[second][(dm * observation.getNrPeriods() * observation.getNrSamplesPerSecond()) + (period * observation.getNrSamplesPerSecond()) + sample] << std::endl;\n }\n }\n }\n }\n }\n\n\treturn 0;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/***********************************************************************\n * filename: NamedElement.cpp\n * created: 30\/10\/2011\n * author: Martin Preisler\n *************************************************************************\/\n\/***************************************************************************\n * Copyright (C) 2004 - 2011 Paul D Turner & The CEGUI Development Team\n *\n * Permission is hereby granted, free of charge, to any person obtaining\n * a copy of this software and associated documentation files (the\n * \"Software\"), to deal in the Software without restriction, including\n * without limitation the rights to use, copy, modify, merge, publish,\n * distribute, sublicense, and\/or sell copies of the Software, and to\n * permit persons to whom the Software is furnished to do so, subject to\n * the following conditions:\n *\n * The above copyright notice and this permission notice shall be\n * included in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\n * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR\n * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,\n * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\n * OTHER DEALINGS IN THE SOFTWARE.\n ***************************************************************************\/\n\n#include \"CEGUI\/NamedElement.h\"\n\n#include <boost\/test\/unit_test.hpp>\n\nBOOST_AUTO_TEST_SUITE(NamedElement)\n\nBOOST_AUTO_TEST_CASE(Children)\n{\n CEGUI::NamedElement* root = new CEGUI::NamedElement(\"root\");\n BOOST_CHECK_EQUAL(root->getName(), \"root\");\n BOOST_CHECK_EQUAL(root->getProperty(\"Name\"), \"root\");\n CEGUI::NamedElement* child1 = new CEGUI::NamedElement(\"child\");\n CEGUI::NamedElement* child2 = new CEGUI::NamedElement(\"child\");\n root->addChild(child1);\n BOOST_CHECK_THROW(root->addChild(child2), CEGUI::AlreadyExistsException);\n root->removeChild(child1);\n BOOST_CHECK_THROW(root->removeChild(\"child\"), CEGUI::UnknownObjectException);\n root->addChild(child2);\n BOOST_CHECK_THROW(root->addChild(child1), CEGUI::AlreadyExistsException);\n \n delete child2;\n delete child1;\n delete root;\n}\n\nBOOST_AUTO_TEST_CASE(NamePath)\n{\n CEGUI::NamedElement* root = new CEGUI::NamedElement(\"root\");\n CEGUI::NamedElement* child = new CEGUI::NamedElement(\"child\");\n CEGUI::NamedElement* inner_child = new CEGUI::NamedElement(\"inner_child\");\n root->addChild(child);\n child->addChild(inner_child);\n \n BOOST_CHECK_EQUAL(child->getNamePath(), \"root\/child\");\n BOOST_CHECK_EQUAL(child->getProperty(\"NamePath\"), \"root\/child\");\n BOOST_CHECK_EQUAL(inner_child->getNamePath(), \"root\/child\/inner_child\");\n \n BOOST_CHECK_EQUAL(root->getChildElement(\"child\"), child);\n BOOST_CHECK_EQUAL(root->getChildElement(\"child\/inner_child\"), inner_child);\n BOOST_CHECK_EQUAL(child->getChildElement(\"inner_child\"), inner_child);\n BOOST_CHECK_THROW(child->getChildElement(\"nonexistant\"), CEGUI::UnknownObjectException);\n \n delete inner_child;\n delete child;\n delete root;\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n<commit_msg>Test string removeChild in NamedElement tests<commit_after>\/***********************************************************************\n * filename: NamedElement.cpp\n * created: 30\/10\/2011\n * author: Martin Preisler\n *************************************************************************\/\n\/***************************************************************************\n * Copyright (C) 2004 - 2011 Paul D Turner & The CEGUI Development Team\n *\n * Permission is hereby granted, free of charge, to any person obtaining\n * a copy of this software and associated documentation files (the\n * \"Software\"), to deal in the Software without restriction, including\n * without limitation the rights to use, copy, modify, merge, publish,\n * distribute, sublicense, and\/or sell copies of the Software, and to\n * permit persons to whom the Software is furnished to do so, subject to\n * the following conditions:\n *\n * The above copyright notice and this permission notice shall be\n * included in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\n * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR\n * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,\n * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\n * OTHER DEALINGS IN THE SOFTWARE.\n ***************************************************************************\/\n\n#include \"CEGUI\/NamedElement.h\"\n\n#include <boost\/test\/unit_test.hpp>\n\nBOOST_AUTO_TEST_SUITE(NamedElement)\n\nBOOST_AUTO_TEST_CASE(Children)\n{\n CEGUI::NamedElement* root = new CEGUI::NamedElement(\"root\");\n BOOST_CHECK_EQUAL(root->getName(), \"root\");\n BOOST_CHECK_EQUAL(root->getProperty(\"Name\"), \"root\");\n CEGUI::NamedElement* child1 = new CEGUI::NamedElement(\"child\");\n CEGUI::NamedElement* child2 = new CEGUI::NamedElement(\"child\");\n root->addChild(child1);\n BOOST_CHECK_THROW(root->addChild(child2), CEGUI::AlreadyExistsException);\n root->removeChild(\"child\");\n BOOST_CHECK_THROW(root->removeChild(\"child\"), CEGUI::UnknownObjectException);\n root->addChild(child2);\n BOOST_CHECK_THROW(root->addChild(child1), CEGUI::AlreadyExistsException);\n \n delete child2;\n delete child1;\n delete root;\n}\n\nBOOST_AUTO_TEST_CASE(NamePath)\n{\n CEGUI::NamedElement* root = new CEGUI::NamedElement(\"root\");\n CEGUI::NamedElement* child = new CEGUI::NamedElement(\"child\");\n CEGUI::NamedElement* inner_child = new CEGUI::NamedElement(\"inner_child\");\n root->addChild(child);\n child->addChild(inner_child);\n \n BOOST_CHECK_EQUAL(child->getNamePath(), \"root\/child\");\n BOOST_CHECK_EQUAL(child->getProperty(\"NamePath\"), \"root\/child\");\n BOOST_CHECK_EQUAL(inner_child->getNamePath(), \"root\/child\/inner_child\");\n \n BOOST_CHECK_EQUAL(root->getChildElement(\"child\"), child);\n BOOST_CHECK_EQUAL(root->getChildElement(\"child\/inner_child\"), inner_child);\n BOOST_CHECK_EQUAL(child->getChildElement(\"inner_child\"), inner_child);\n BOOST_CHECK_THROW(child->getChildElement(\"nonexistant\"), CEGUI::UnknownObjectException);\n \n delete inner_child;\n delete child;\n delete root;\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright 2014 Google Inc.\n *\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n *\/\n\n#include \"SkPaint.h\"\n#include \"SkPoint.h\"\n#include \"SkTextBlob.h\"\n\n#include \"Test.h\"\n\n\nclass TextBlobTester {\npublic:\n \/\/ This unit test feeds an SkTextBlobBuilder various runs then checks to see if\n \/\/ the result contains the provided data and merges runs when appropriate.\n static void TestBuilder(skiatest::Reporter* reporter) {\n SkTextBlobBuilder builder;\n\n \/\/ empty run set\n RunBuilderTest(reporter, builder, nullptr, 0, nullptr, 0);\n\n RunDef set1[] = {\n { 128, SkTextBlob::kDefault_Positioning, 100, 100 },\n };\n RunBuilderTest(reporter, builder, set1, SK_ARRAY_COUNT(set1), set1, SK_ARRAY_COUNT(set1));\n\n RunDef set2[] = {\n { 128, SkTextBlob::kHorizontal_Positioning, 100, 100 },\n };\n RunBuilderTest(reporter, builder, set2, SK_ARRAY_COUNT(set2), set2, SK_ARRAY_COUNT(set2));\n\n RunDef set3[] = {\n { 128, SkTextBlob::kFull_Positioning, 100, 100 },\n };\n RunBuilderTest(reporter, builder, set3, SK_ARRAY_COUNT(set3), set3, SK_ARRAY_COUNT(set3));\n\n RunDef set4[] = {\n { 128, SkTextBlob::kDefault_Positioning, 100, 150 },\n { 128, SkTextBlob::kDefault_Positioning, 100, 150 },\n { 128, SkTextBlob::kDefault_Positioning, 100, 150 },\n };\n RunBuilderTest(reporter, builder, set4, SK_ARRAY_COUNT(set4), set4, SK_ARRAY_COUNT(set4));\n\n RunDef set5[] = {\n { 128, SkTextBlob::kHorizontal_Positioning, 100, 150 },\n { 128, SkTextBlob::kHorizontal_Positioning, 200, 150 },\n { 128, SkTextBlob::kHorizontal_Positioning, 300, 250 },\n };\n RunDef mergedSet5[] = {\n { 256, SkTextBlob::kHorizontal_Positioning, 0, 150 },\n { 128, SkTextBlob::kHorizontal_Positioning, 0, 250 },\n };\n RunBuilderTest(reporter, builder, set5, SK_ARRAY_COUNT(set5), mergedSet5,\n SK_ARRAY_COUNT(mergedSet5));\n\n RunDef set6[] = {\n { 128, SkTextBlob::kFull_Positioning, 100, 100 },\n { 128, SkTextBlob::kFull_Positioning, 200, 200 },\n { 128, SkTextBlob::kFull_Positioning, 300, 300 },\n };\n RunDef mergedSet6[] = {\n { 384, SkTextBlob::kFull_Positioning, 0, 0 },\n };\n RunBuilderTest(reporter, builder, set6, SK_ARRAY_COUNT(set6), mergedSet6,\n SK_ARRAY_COUNT(mergedSet6));\n\n RunDef set7[] = {\n { 128, SkTextBlob::kDefault_Positioning, 100, 150 },\n { 128, SkTextBlob::kDefault_Positioning, 100, 150 },\n { 128, SkTextBlob::kHorizontal_Positioning, 100, 150 },\n { 128, SkTextBlob::kHorizontal_Positioning, 200, 150 },\n { 128, SkTextBlob::kFull_Positioning, 400, 350 },\n { 128, SkTextBlob::kFull_Positioning, 400, 350 },\n { 128, SkTextBlob::kDefault_Positioning, 100, 450 },\n { 128, SkTextBlob::kDefault_Positioning, 100, 450 },\n { 128, SkTextBlob::kHorizontal_Positioning, 100, 550 },\n { 128, SkTextBlob::kHorizontal_Positioning, 200, 650 },\n { 128, SkTextBlob::kFull_Positioning, 400, 750 },\n { 128, SkTextBlob::kFull_Positioning, 400, 850 },\n };\n RunDef mergedSet7[] = {\n { 128, SkTextBlob::kDefault_Positioning, 100, 150 },\n { 128, SkTextBlob::kDefault_Positioning, 100, 150 },\n { 256, SkTextBlob::kHorizontal_Positioning, 0, 150 },\n { 256, SkTextBlob::kFull_Positioning, 0, 0 },\n { 128, SkTextBlob::kDefault_Positioning, 100, 450 },\n { 128, SkTextBlob::kDefault_Positioning, 100, 450 },\n { 128, SkTextBlob::kHorizontal_Positioning, 0, 550 },\n { 128, SkTextBlob::kHorizontal_Positioning, 0, 650 },\n { 256, SkTextBlob::kFull_Positioning, 0, 0 },\n };\n RunBuilderTest(reporter, builder, set7, SK_ARRAY_COUNT(set7), mergedSet7,\n SK_ARRAY_COUNT(mergedSet7));\n }\n\n \/\/ This unit test verifies blob bounds computation.\n static void TestBounds(skiatest::Reporter* reporter) {\n SkTextBlobBuilder builder;\n SkPaint font;\n font.setTextEncoding(SkPaint::kGlyphID_TextEncoding);\n\n \/\/ Explicit bounds.\n {\n SkAutoTUnref<const SkTextBlob> blob(builder.build());\n REPORTER_ASSERT(reporter, blob->bounds().isEmpty());\n }\n\n {\n SkRect r1 = SkRect::MakeXYWH(10, 10, 20, 20);\n builder.allocRun(font, 16, 0, 0, &r1);\n SkAutoTUnref<const SkTextBlob> blob(builder.build());\n REPORTER_ASSERT(reporter, blob->bounds() == r1);\n }\n\n {\n SkRect r1 = SkRect::MakeXYWH(10, 10, 20, 20);\n builder.allocRunPosH(font, 16, 0, &r1);\n SkAutoTUnref<const SkTextBlob> blob(builder.build());\n REPORTER_ASSERT(reporter, blob->bounds() == r1);\n }\n\n {\n SkRect r1 = SkRect::MakeXYWH(10, 10, 20, 20);\n builder.allocRunPos(font, 16, &r1);\n SkAutoTUnref<const SkTextBlob> blob(builder.build());\n REPORTER_ASSERT(reporter, blob->bounds() == r1);\n }\n\n {\n SkRect r1 = SkRect::MakeXYWH(10, 10, 20, 20);\n SkRect r2 = SkRect::MakeXYWH(15, 20, 50, 50);\n SkRect r3 = SkRect::MakeXYWH(0, 5, 10, 5);\n\n builder.allocRun(font, 16, 0, 0, &r1);\n builder.allocRunPosH(font, 16, 0, &r2);\n builder.allocRunPos(font, 16, &r3);\n\n SkAutoTUnref<const SkTextBlob> blob(builder.build());\n REPORTER_ASSERT(reporter, blob->bounds() == SkRect::MakeXYWH(0, 5, 65, 65));\n }\n\n {\n \/\/ Verify empty blob bounds after building some non-empty blobs.\n SkAutoTUnref<const SkTextBlob> blob(builder.build());\n REPORTER_ASSERT(reporter, blob->bounds().isEmpty());\n }\n\n \/\/ Implicit bounds\n\n {\n \/\/ Exercise the empty bounds path, and ensure that RunRecord-aligned pos buffers\n \/\/ don't trigger asserts (http:\/\/crbug.com\/542643).\n SkPaint p;\n p.setTextSize(0);\n p.setTextEncoding(SkPaint::kGlyphID_TextEncoding);\n\n const char* txt = \"BOOO\";\n const size_t len = strlen(txt);\n const SkTextBlobBuilder::RunBuffer& buffer = builder.allocRunPos(p, (int)len);\n p.textToGlyphs(txt, len, buffer.glyphs);\n memset(buffer.pos, 0, sizeof(SkScalar) * len * 2);\n SkAutoTUnref<const SkTextBlob> blob(builder.build());\n REPORTER_ASSERT(reporter, blob->bounds().isEmpty());\n }\n }\n\nprivate:\n struct RunDef {\n unsigned count;\n SkTextBlob::GlyphPositioning pos;\n SkScalar x, y;\n };\n\n static void RunBuilderTest(skiatest::Reporter* reporter, SkTextBlobBuilder& builder,\n const RunDef in[], unsigned inCount,\n const RunDef out[], unsigned outCount) {\n SkPaint font;\n font.setTextEncoding(SkPaint::kGlyphID_TextEncoding);\n\n unsigned glyphCount = 0;\n unsigned posCount = 0;\n\n for (unsigned i = 0; i < inCount; ++i) {\n AddRun(font, in[i].count, in[i].pos, SkPoint::Make(in[i].x, in[i].y), builder);\n glyphCount += in[i].count;\n posCount += in[i].count * in[i].pos;\n }\n\n SkAutoTUnref<const SkTextBlob> blob(builder.build());\n\n SkTextBlob::RunIterator it(blob);\n for (unsigned i = 0; i < outCount; ++i) {\n REPORTER_ASSERT(reporter, !it.done());\n REPORTER_ASSERT(reporter, out[i].pos == it.positioning());\n REPORTER_ASSERT(reporter, out[i].count == it.glyphCount());\n if (SkTextBlob::kDefault_Positioning == out[i].pos) {\n REPORTER_ASSERT(reporter, out[i].x == it.offset().x());\n REPORTER_ASSERT(reporter, out[i].y == it.offset().y());\n } else if (SkTextBlob::kHorizontal_Positioning == out[i].pos) {\n REPORTER_ASSERT(reporter, out[i].y == it.offset().y());\n }\n\n for (unsigned k = 0; k < it.glyphCount(); ++k) {\n REPORTER_ASSERT(reporter, k % 128 == it.glyphs()[k]);\n if (SkTextBlob::kHorizontal_Positioning == it.positioning()) {\n REPORTER_ASSERT(reporter, SkIntToScalar(k % 128) == it.pos()[k]);\n } else if (SkTextBlob::kFull_Positioning == it.positioning()) {\n REPORTER_ASSERT(reporter, SkIntToScalar(k % 128) == it.pos()[k * 2]);\n REPORTER_ASSERT(reporter, -SkIntToScalar(k % 128) == it.pos()[k * 2 + 1]);\n }\n }\n\n it.next();\n }\n\n REPORTER_ASSERT(reporter, it.done());\n }\n\n static void AddRun(const SkPaint& font, int count, SkTextBlob::GlyphPositioning pos,\n const SkPoint& offset, SkTextBlobBuilder& builder,\n const SkRect* bounds = nullptr) {\n switch (pos) {\n case SkTextBlob::kDefault_Positioning: {\n const SkTextBlobBuilder::RunBuffer& rb = builder.allocRun(font, count, offset.x(),\n offset.y(), bounds);\n for (int i = 0; i < count; ++i) {\n rb.glyphs[i] = i;\n }\n } break;\n case SkTextBlob::kHorizontal_Positioning: {\n const SkTextBlobBuilder::RunBuffer& rb = builder.allocRunPosH(font, count, offset.y(),\n bounds);\n for (int i = 0; i < count; ++i) {\n rb.glyphs[i] = i;\n rb.pos[i] = SkIntToScalar(i);\n }\n } break;\n case SkTextBlob::kFull_Positioning: {\n const SkTextBlobBuilder::RunBuffer& rb = builder.allocRunPos(font, count, bounds);\n for (int i = 0; i < count; ++i) {\n rb.glyphs[i] = i;\n rb.pos[i * 2] = SkIntToScalar(i);\n rb.pos[i * 2 + 1] = -SkIntToScalar(i);\n }\n } break;\n default:\n SkFAIL(\"unhandled positioning value\");\n }\n }\n};\n\nDEF_TEST(TextBlob_builder, reporter) {\n TextBlobTester::TestBuilder(reporter);\n TextBlobTester::TestBounds(reporter);\n}\n<commit_msg>Fix TextBlobTest valgrind error<commit_after>\/*\n * Copyright 2014 Google Inc.\n *\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n *\/\n\n#include \"SkPaint.h\"\n#include \"SkPoint.h\"\n#include \"SkTextBlob.h\"\n\n#include \"Test.h\"\n\nclass TextBlobTester {\npublic:\n \/\/ This unit test feeds an SkTextBlobBuilder various runs then checks to see if\n \/\/ the result contains the provided data and merges runs when appropriate.\n static void TestBuilder(skiatest::Reporter* reporter) {\n SkTextBlobBuilder builder;\n\n \/\/ empty run set\n RunBuilderTest(reporter, builder, nullptr, 0, nullptr, 0);\n\n RunDef set1[] = {\n { 128, SkTextBlob::kDefault_Positioning, 100, 100 },\n };\n RunBuilderTest(reporter, builder, set1, SK_ARRAY_COUNT(set1), set1, SK_ARRAY_COUNT(set1));\n\n RunDef set2[] = {\n { 128, SkTextBlob::kHorizontal_Positioning, 100, 100 },\n };\n RunBuilderTest(reporter, builder, set2, SK_ARRAY_COUNT(set2), set2, SK_ARRAY_COUNT(set2));\n\n RunDef set3[] = {\n { 128, SkTextBlob::kFull_Positioning, 100, 100 },\n };\n RunBuilderTest(reporter, builder, set3, SK_ARRAY_COUNT(set3), set3, SK_ARRAY_COUNT(set3));\n\n RunDef set4[] = {\n { 128, SkTextBlob::kDefault_Positioning, 100, 150 },\n { 128, SkTextBlob::kDefault_Positioning, 100, 150 },\n { 128, SkTextBlob::kDefault_Positioning, 100, 150 },\n };\n RunBuilderTest(reporter, builder, set4, SK_ARRAY_COUNT(set4), set4, SK_ARRAY_COUNT(set4));\n\n RunDef set5[] = {\n { 128, SkTextBlob::kHorizontal_Positioning, 100, 150 },\n { 128, SkTextBlob::kHorizontal_Positioning, 200, 150 },\n { 128, SkTextBlob::kHorizontal_Positioning, 300, 250 },\n };\n RunDef mergedSet5[] = {\n { 256, SkTextBlob::kHorizontal_Positioning, 0, 150 },\n { 128, SkTextBlob::kHorizontal_Positioning, 0, 250 },\n };\n RunBuilderTest(reporter, builder, set5, SK_ARRAY_COUNT(set5), mergedSet5,\n SK_ARRAY_COUNT(mergedSet5));\n\n RunDef set6[] = {\n { 128, SkTextBlob::kFull_Positioning, 100, 100 },\n { 128, SkTextBlob::kFull_Positioning, 200, 200 },\n { 128, SkTextBlob::kFull_Positioning, 300, 300 },\n };\n RunDef mergedSet6[] = {\n { 384, SkTextBlob::kFull_Positioning, 0, 0 },\n };\n RunBuilderTest(reporter, builder, set6, SK_ARRAY_COUNT(set6), mergedSet6,\n SK_ARRAY_COUNT(mergedSet6));\n\n RunDef set7[] = {\n { 128, SkTextBlob::kDefault_Positioning, 100, 150 },\n { 128, SkTextBlob::kDefault_Positioning, 100, 150 },\n { 128, SkTextBlob::kHorizontal_Positioning, 100, 150 },\n { 128, SkTextBlob::kHorizontal_Positioning, 200, 150 },\n { 128, SkTextBlob::kFull_Positioning, 400, 350 },\n { 128, SkTextBlob::kFull_Positioning, 400, 350 },\n { 128, SkTextBlob::kDefault_Positioning, 100, 450 },\n { 128, SkTextBlob::kDefault_Positioning, 100, 450 },\n { 128, SkTextBlob::kHorizontal_Positioning, 100, 550 },\n { 128, SkTextBlob::kHorizontal_Positioning, 200, 650 },\n { 128, SkTextBlob::kFull_Positioning, 400, 750 },\n { 128, SkTextBlob::kFull_Positioning, 400, 850 },\n };\n RunDef mergedSet7[] = {\n { 128, SkTextBlob::kDefault_Positioning, 100, 150 },\n { 128, SkTextBlob::kDefault_Positioning, 100, 150 },\n { 256, SkTextBlob::kHorizontal_Positioning, 0, 150 },\n { 256, SkTextBlob::kFull_Positioning, 0, 0 },\n { 128, SkTextBlob::kDefault_Positioning, 100, 450 },\n { 128, SkTextBlob::kDefault_Positioning, 100, 450 },\n { 128, SkTextBlob::kHorizontal_Positioning, 0, 550 },\n { 128, SkTextBlob::kHorizontal_Positioning, 0, 650 },\n { 256, SkTextBlob::kFull_Positioning, 0, 0 },\n };\n RunBuilderTest(reporter, builder, set7, SK_ARRAY_COUNT(set7), mergedSet7,\n SK_ARRAY_COUNT(mergedSet7));\n }\n\n \/\/ This unit test verifies blob bounds computation.\n static void TestBounds(skiatest::Reporter* reporter) {\n SkTextBlobBuilder builder;\n SkPaint font;\n font.setTextEncoding(SkPaint::kGlyphID_TextEncoding);\n\n \/\/ Explicit bounds.\n {\n SkAutoTUnref<const SkTextBlob> blob(builder.build());\n REPORTER_ASSERT(reporter, blob->bounds().isEmpty());\n }\n\n {\n SkRect r1 = SkRect::MakeXYWH(10, 10, 20, 20);\n builder.allocRun(font, 16, 0, 0, &r1);\n SkAutoTUnref<const SkTextBlob> blob(builder.build());\n REPORTER_ASSERT(reporter, blob->bounds() == r1);\n }\n\n {\n SkRect r1 = SkRect::MakeXYWH(10, 10, 20, 20);\n builder.allocRunPosH(font, 16, 0, &r1);\n SkAutoTUnref<const SkTextBlob> blob(builder.build());\n REPORTER_ASSERT(reporter, blob->bounds() == r1);\n }\n\n {\n SkRect r1 = SkRect::MakeXYWH(10, 10, 20, 20);\n builder.allocRunPos(font, 16, &r1);\n SkAutoTUnref<const SkTextBlob> blob(builder.build());\n REPORTER_ASSERT(reporter, blob->bounds() == r1);\n }\n\n {\n SkRect r1 = SkRect::MakeXYWH(10, 10, 20, 20);\n SkRect r2 = SkRect::MakeXYWH(15, 20, 50, 50);\n SkRect r3 = SkRect::MakeXYWH(0, 5, 10, 5);\n\n builder.allocRun(font, 16, 0, 0, &r1);\n builder.allocRunPosH(font, 16, 0, &r2);\n builder.allocRunPos(font, 16, &r3);\n\n SkAutoTUnref<const SkTextBlob> blob(builder.build());\n REPORTER_ASSERT(reporter, blob->bounds() == SkRect::MakeXYWH(0, 5, 65, 65));\n }\n\n {\n \/\/ Verify empty blob bounds after building some non-empty blobs.\n SkAutoTUnref<const SkTextBlob> blob(builder.build());\n REPORTER_ASSERT(reporter, blob->bounds().isEmpty());\n }\n\n \/\/ Implicit bounds\n\n {\n \/\/ Exercise the empty bounds path, and ensure that RunRecord-aligned pos buffers\n \/\/ don't trigger asserts (http:\/\/crbug.com\/542643).\n SkPaint p;\n p.setTextSize(0);\n p.setTextEncoding(SkPaint::kUTF8_TextEncoding);\n\n const char* txt = \"BOOO\";\n const size_t txtLen = strlen(txt);\n const int glyphCount = p.textToGlyphs(txt, txtLen, nullptr);\n\n p.setTextEncoding(SkPaint::kGlyphID_TextEncoding);\n const SkTextBlobBuilder::RunBuffer& buffer = builder.allocRunPos(p, glyphCount);\n\n p.setTextEncoding(SkPaint::kUTF8_TextEncoding);\n p.textToGlyphs(txt, txtLen, buffer.glyphs);\n\n memset(buffer.pos, 0, sizeof(SkScalar) * glyphCount * 2);\n SkAutoTUnref<const SkTextBlob> blob(builder.build());\n REPORTER_ASSERT(reporter, blob->bounds().isEmpty());\n }\n }\n\nprivate:\n struct RunDef {\n unsigned count;\n SkTextBlob::GlyphPositioning pos;\n SkScalar x, y;\n };\n\n static void RunBuilderTest(skiatest::Reporter* reporter, SkTextBlobBuilder& builder,\n const RunDef in[], unsigned inCount,\n const RunDef out[], unsigned outCount) {\n SkPaint font;\n font.setTextEncoding(SkPaint::kGlyphID_TextEncoding);\n\n unsigned glyphCount = 0;\n unsigned posCount = 0;\n\n for (unsigned i = 0; i < inCount; ++i) {\n AddRun(font, in[i].count, in[i].pos, SkPoint::Make(in[i].x, in[i].y), builder);\n glyphCount += in[i].count;\n posCount += in[i].count * in[i].pos;\n }\n\n SkAutoTUnref<const SkTextBlob> blob(builder.build());\n\n SkTextBlob::RunIterator it(blob);\n for (unsigned i = 0; i < outCount; ++i) {\n REPORTER_ASSERT(reporter, !it.done());\n REPORTER_ASSERT(reporter, out[i].pos == it.positioning());\n REPORTER_ASSERT(reporter, out[i].count == it.glyphCount());\n if (SkTextBlob::kDefault_Positioning == out[i].pos) {\n REPORTER_ASSERT(reporter, out[i].x == it.offset().x());\n REPORTER_ASSERT(reporter, out[i].y == it.offset().y());\n } else if (SkTextBlob::kHorizontal_Positioning == out[i].pos) {\n REPORTER_ASSERT(reporter, out[i].y == it.offset().y());\n }\n\n for (unsigned k = 0; k < it.glyphCount(); ++k) {\n REPORTER_ASSERT(reporter, k % 128 == it.glyphs()[k]);\n if (SkTextBlob::kHorizontal_Positioning == it.positioning()) {\n REPORTER_ASSERT(reporter, SkIntToScalar(k % 128) == it.pos()[k]);\n } else if (SkTextBlob::kFull_Positioning == it.positioning()) {\n REPORTER_ASSERT(reporter, SkIntToScalar(k % 128) == it.pos()[k * 2]);\n REPORTER_ASSERT(reporter, -SkIntToScalar(k % 128) == it.pos()[k * 2 + 1]);\n }\n }\n\n it.next();\n }\n\n REPORTER_ASSERT(reporter, it.done());\n }\n\n static void AddRun(const SkPaint& font, int count, SkTextBlob::GlyphPositioning pos,\n const SkPoint& offset, SkTextBlobBuilder& builder,\n const SkRect* bounds = nullptr) {\n switch (pos) {\n case SkTextBlob::kDefault_Positioning: {\n const SkTextBlobBuilder::RunBuffer& rb = builder.allocRun(font, count, offset.x(),\n offset.y(), bounds);\n for (int i = 0; i < count; ++i) {\n rb.glyphs[i] = i;\n }\n } break;\n case SkTextBlob::kHorizontal_Positioning: {\n const SkTextBlobBuilder::RunBuffer& rb = builder.allocRunPosH(font, count, offset.y(),\n bounds);\n for (int i = 0; i < count; ++i) {\n rb.glyphs[i] = i;\n rb.pos[i] = SkIntToScalar(i);\n }\n } break;\n case SkTextBlob::kFull_Positioning: {\n const SkTextBlobBuilder::RunBuffer& rb = builder.allocRunPos(font, count, bounds);\n for (int i = 0; i < count; ++i) {\n rb.glyphs[i] = i;\n rb.pos[i * 2] = SkIntToScalar(i);\n rb.pos[i * 2 + 1] = -SkIntToScalar(i);\n }\n } break;\n default:\n SkFAIL(\"unhandled positioning value\");\n }\n }\n};\n\nDEF_TEST(TextBlob_builder, reporter) {\n TextBlobTester::TestBuilder(reporter);\n TextBlobTester::TestBounds(reporter);\n}\n<|endoftext|>"} {"text":"<commit_before>#pragma once\n\n#include <ctime>\n#include <initializer_list>\n\n#include \"blackhole\/attribute\/name.hpp\"\n#include \"blackhole\/attribute\/scope.hpp\"\n#include \"blackhole\/attribute\/set.hpp\"\n#include \"blackhole\/attribute\/view.hpp\"\n#include \"blackhole\/attribute\/traits.hpp\"\n#include \"blackhole\/attribute\/value.hpp\"\n#include \"blackhole\/utils\/timeval.hpp\"\n#include \"blackhole\/utils\/types.hpp\"\n#include \"blackhole\/utils\/underlying.hpp\"\n#include \"blackhole\/utils\/noexcept.hpp\"\n\nnamespace blackhole {\n\nnamespace attribute {\n\n\/\/ Simple typedef for attributes initializer list. Useful when specifying local attributes.\ntypedef std::initializer_list<std::pair<std::string, attribute::value_t>> list;\n\n\/\/ Dynamic attribute factory function.\ntemplate<typename T>\ninline attribute::pair_t make(const std::string& name, const T& value, attribute::scope_t scope = attribute::DEFAULT_SCOPE) {\n return std::make_pair(name, attribute_t(value, scope));\n}\n\ntemplate<typename T>\ninline attribute::pair_t make(const std::string& name, T&& value, attribute::scope_t scope = attribute::DEFAULT_SCOPE) {\n return std::make_pair(name, attribute_t(std::move(value), scope));\n}\n\n\/\/ Attribute packing\/unpacking\/extracting.\ntemplate<typename T, class = void>\nstruct traits {\n static inline T pack(const T& value) {\n return value;\n }\n\n static inline T extract(const attribute::set_view_t& attributes, const std::string& name) {\n return boost::get<T>(attributes.at(name).value);\n }\n};\n\ntemplate<typename T>\nstruct traits<T, typename std::enable_if<std::is_enum<T>::value>::type> {\n typedef typename aux::underlying_type<T>::type underlying_type;\n\n static inline underlying_type pack(const T& value) {\n return static_cast<underlying_type>(value);\n }\n\n static inline T extract(const attribute::set_view_t& attributes, const std::string& name) {\n return static_cast<T>(boost::get<underlying_type>(attributes.at(name).value));\n }\n};\n\n} \/\/ namespace attribute\n\n} \/\/ namespace blackhole\n<commit_msg>[Code Style] Using typedefs, offsets, margins and other stuff.<commit_after>#pragma once\n\n#include <ctime>\n#include <initializer_list>\n#include <utility>\n\n#include \"blackhole\/attribute\/name.hpp\"\n#include \"blackhole\/attribute\/scope.hpp\"\n#include \"blackhole\/attribute\/set.hpp\"\n#include \"blackhole\/attribute\/view.hpp\"\n#include \"blackhole\/attribute\/traits.hpp\"\n#include \"blackhole\/attribute\/value.hpp\"\n#include \"blackhole\/utils\/timeval.hpp\"\n#include \"blackhole\/utils\/types.hpp\"\n#include \"blackhole\/utils\/underlying.hpp\"\n#include \"blackhole\/utils\/noexcept.hpp\"\n\nnamespace blackhole {\n\nnamespace attribute {\n\n\/*!\n * Simple typedef for attributes initializer list.\n * Useful when specifying local attributes.\n *\/\ntypedef std::initializer_list<std::pair<name_t, value_t>> list;\n\n\/\/ Dynamic attribute factory function.\ntemplate<typename T>\ninline\npair_t\nmake(const name_t& name, const T& value, scope_t scope = DEFAULT_SCOPE) {\n return std::make_pair(name, attribute_t(value, scope));\n}\n\ntemplate<typename T>\ninline\npair_t\nmake(const name_t& name, T&& value, scope_t scope = DEFAULT_SCOPE) {\n return std::make_pair(name, attribute_t(std::move(value), scope));\n}\n\n\/\/ Attribute packing\/unpacking\/extracting.\ntemplate<typename T, class = void>\nstruct traits {\n static inline T pack(const T& value) {\n return value;\n }\n\n static inline T extract(const set_view_t& attributes, const name_t& name) {\n return boost::get<T>(attributes.at(name).value);\n }\n};\n\ntemplate<typename T>\nstruct traits<T, typename std::enable_if<std::is_enum<T>::value>::type> {\n typedef typename aux::underlying_type<T>::type underlying_type;\n\n static inline underlying_type pack(const T& value) {\n return static_cast<underlying_type>(value);\n }\n\n static inline T extract(const set_view_t& attributes, const name_t& name) {\n return static_cast<T>(boost::get<underlying_type>(attributes.at(name).value));\n }\n};\n\n} \/\/ namespace attribute\n\n} \/\/ namespace blackhole\n<|endoftext|>"} {"text":"<commit_before>#pragma once\n\n#include <cstdint>\n#include <initializer_list>\n#include <unordered_map>\n\n#include <boost\/variant.hpp>\n\nnamespace blackhole {\n\nnamespace log {\n\ntypedef boost::variant<\n std::time_t,\n std::uint8_t,\n std::int32_t,\n std::uint64_t,\n std::int64_t,\n std::double_t,\n std::string\n> attribute_value_t;\n\ntypedef std::pair<\n std::string,\n attribute_value_t\n> attribute_pair_t;\n\ntypedef std::unordered_map<\n attribute_pair_t::first_type,\n attribute_pair_t::second_type\n> attributes_t;\n\n} \/\/ namespace log\n\ninline log::attributes_t merge(const std::initializer_list<log::attributes_t>& args) {\n log::attributes_t summary;\n for (auto it = args.begin(); it != args.end(); ++it) {\n summary.insert(it->begin(), it->end());\n }\n\n return summary;\n}\n\nnamespace attr {\n\ntemplate<typename T>\ninline log::attribute_pair_t make(const std::string& name, const T& value) {\n return std::make_pair(name, value);\n}\n\n} \/\/ namespace attr\n\n} \/\/ namespace blackhole\n<commit_msg>More comments.<commit_after>#pragma once\n\n#include <cstdint>\n#include <initializer_list>\n#include <unordered_map>\n\n#include <boost\/variant.hpp>\n\nnamespace blackhole {\n\nnamespace log {\n\ntypedef boost::variant<\n std::time_t,\n std::uint8_t,\n std::int32_t,\n std::uint64_t,\n std::int64_t,\n std::double_t,\n std::string\n> attribute_value_t;\n\ntypedef std::pair<\n std::string,\n attribute_value_t\n> attribute_pair_t;\n\ntypedef std::unordered_map<\n attribute_pair_t::first_type,\n attribute_pair_t::second_type\n> attributes_t;\n\n} \/\/ namespace log\n\ninline log::attributes_t merge(const std::initializer_list<log::attributes_t>& args) {\n log::attributes_t summary;\n for (auto it = args.begin(); it != args.end(); ++it) {\n summary.insert(it->begin(), it->end());\n }\n\n return summary;\n}\n\nnamespace attr {\n\n\/\/ Dynamic attribute factory function.\ntemplate<typename T>\ninline log::attribute_pair_t make(const std::string& name, const T& value) {\n return std::make_pair(name, value);\n}\n\n} \/\/ namespace attr\n\n} \/\/ namespace blackhole\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (C) 2014 furan\n * Copyright (C) 2016 deipi.com LLC and contributors.\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to\n * deal in the Software without restriction, including without limitation the\n * rights to use, copy, modify, merge, publish, distribute, sublicense, and\/or\n * sell copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n * IN THE SOFTWARE.\n *\/\n\n#include \"Lexer.h\"\n\n#define AND \"AND\"\n#define OR \"OR\"\n#define NOT \"NOT\"\n#define XOR \"XOR\"\n\n#define DOUBLEQUOTE '\"'\n#define SINGLEQUOTE '\\''\n#define LEFT_SQUARE_BRACKET '['\n#define RIGHT_SQUARE_BRACKET ']'\n\n\nLexer::Lexer(ContentReader contentReader)\n{\n\tthis->contentReader = contentReader;\n\tcurrentSymbol = this->contentReader.NextSymbol();\n\n\tInitDictionary();\n}\n\n\nLexer::Lexer(char * input)\n{\n\tContentReader cr(input);\n\tcontentReader = cr;\n\tcurrentSymbol = this->contentReader.NextSymbol();\n\n\tInitDictionary();\n\n}\n\n\nvoid\nLexer::InitDictionary()\n{\n\tsingleSymbolDictionary[\"(\"] = TokenType::LeftParenthesis;\n\tsingleSymbolDictionary[\")\"] = TokenType::RightParenthesis;\n\tsingleSymbolDictionary[\"&\"] = TokenType::And;\n\tsingleSymbolDictionary[\"|\"] = TokenType::Or;\n\tsingleSymbolDictionary[\"~\"] = TokenType::Not;\n}\n\n\nToken\nLexer::NextToken()\n{\n\tstring lexeme = \"\";\n\tLexerState currentState = LexerState::INIT;\n\tToken token;\n\tchar quote;\n\n\tauto upState = currentState;\n\n\tstring symbol;\n\tstring lcSymbol;\n\n\twhile (true) {\n\t\tsymbol.clear();\n\t\tsymbol += currentSymbol.symbol;\n\t\tswitch (currentState) {\n\t\t\tcase LexerState::INIT:\n\t\t\t\tif (currentSymbol.symbol == LEFT_SQUARE_BRACKET)\n\t\t\t\t{\n\t\t\t\t\tlexeme += currentSymbol.symbol;\n\t\t\t\t\tcurrentState = LexerState::INIT_SQUARE_BRACKET;\n\t\t\t\t\tcurrentSymbol = contentReader.NextSymbol();\n\t\t\t\t}\n\t\t\t\telse if (currentSymbol.symbol == SINGLEQUOTE)\n\t\t\t\t{\n\t\t\t\t\tlexeme += currentSymbol.symbol;\n\t\t\t\t\tcurrentState = LexerState::TOKEN_QUOTE;\n\t\t\t\t\tquote = SINGLEQUOTE;\n\t\t\t\t\tcurrentSymbol = contentReader.NextSymbol();\n\t\t\t\t}\n\t\t\t\telse if (currentSymbol.symbol == DOUBLEQUOTE)\n\t\t\t\t{\n\t\t\t\t\tlexeme += currentSymbol.symbol;\n\t\t\t\t\tcurrentState = LexerState::TOKEN_QUOTE;\n\t\t\t\t\tquote = DOUBLEQUOTE;\n\t\t\t\t\tcurrentSymbol = contentReader.NextSymbol();\n\t\t\t\t}\n\t\t\t\telse if(isalnum(currentSymbol.symbol) || currentSymbol.symbol == '_')\n\t\t\t\t{\n\t\t\t\t\tlexeme += currentSymbol.symbol;\n\t\t\t\t\tcurrentState = LexerState::TOKEN;\n\t\t\t\t\tcurrentSymbol = contentReader.NextSymbol();\n\t\t\t\t}\n\t\t\t\telse if (currentSymbol.symbol == '\\0')\n\t\t\t\t{\n\t\t\t\t\tcurrentState = LexerState::EOFILE;\n\t\t\t\t}\n\t\t\t\telse if (isspace(currentSymbol.symbol))\n\t\t\t\t{\n\t\t\t\t\tcurrentState = LexerState::INIT;\n\t\t\t\t\tcurrentSymbol = contentReader.NextSymbol();\n\t\t\t\t}\n\t\t\t\telse if(singleSymbolDictionary.find(symbol) != singleSymbolDictionary.end())\n\t\t\t\t{\n\t\t\t\t\tlexeme += currentSymbol.symbol;\n\t\t\t\t\tcurrentState = LexerState::SYMBOL_OP;\n\t\t\t\t\tcurrentSymbol = contentReader.NextSymbol();\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tstring msj = \"Symbol \" + symbol + \" not expected\";\n\t\t\t\t\tthrow LexicalException(msj.c_str());\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase LexerState::TOKEN:\n\t\t\t\tif (currentSymbol.symbol == DOUBLEQUOTE)\n\t\t\t\t{\n\t\t\t\t\tlexeme += currentSymbol.symbol;\n\t\t\t\t\tcurrentState = LexerState::TOKEN_QUOTE;\n\t\t\t\t\tquote = DOUBLEQUOTE;\n\t\t\t\t\tcurrentSymbol = contentReader.NextSymbol();\n\t\t\t\t}\n\t\t\t\telse if (currentSymbol.symbol == SINGLEQUOTE)\n\t\t\t\t{\n\t\t\t\t\tlexeme += currentSymbol.symbol;\n\t\t\t\t\tcurrentState = LexerState::TOKEN_QUOTE;\n\t\t\t\t\tquote = SINGLEQUOTE;\n\t\t\t\t\tcurrentSymbol = contentReader.NextSymbol();\n\t\t\t\t}\n\t\t\t\telse if (!IsSymbolOp(currentSymbol.symbol) && currentSymbol.symbol != ' ' && currentSymbol.symbol != '\\0')\n\t\t\t\t{\n\t\t\t\t\tlexeme += currentSymbol.symbol;\n\t\t\t\t\tcurrentState = LexerState::TOKEN;\n\t\t\t\t\tcurrentSymbol = contentReader.NextSymbol();\n\t\t\t\t} else\n\t\t\t\t{\n\t\t\t\t\ttoken.lexeme = lexeme;\n\t\t\t\t\ttoken.type = TokenType::Id;\n\t\t\t\t\tIsStringOperator(token);\n\t\t\t\t\treturn token;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase LexerState::TOKEN_QUOTE:\n\t\t\t\tif (currentSymbol.symbol == quote)\n\t\t\t\t{\n\t\t\t\t\tlexeme += currentSymbol.symbol;\n\t\t\t\t\tupState == LexerState::INIT_SQUARE_BRACKET ? currentState = LexerState::END_SQUARE_BRACKET : currentState = LexerState::TOKEN;\n\t\t\t\t\tcurrentSymbol = contentReader.NextSymbol();\n\t\t\t\t}\n\t\t\t\telse if (currentSymbol.symbol == '\\\\')\n\t\t\t\t{\n\t\t\t\t\tlexeme += currentSymbol.symbol;\n\t\t\t\t\tcurrentState = LexerState::ESCAPE;\n\t\t\t\t\tcurrentSymbol = contentReader.NextSymbol();\n\t\t\t\t}\n\t\t\t\telse if (currentSymbol.symbol != '\\0')\n\t\t\t\t{\n\t\t\t\t\tlexeme += currentSymbol.symbol;\n\t\t\t\t\tcurrentSymbol = contentReader.NextSymbol();\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tstring msj = \"Symbol double quote expected\";\n\t\t\t\t\tthrow LexicalException(msj.c_str());\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase LexerState::ESCAPE:\n\t\t\t\tif (currentSymbol.symbol != '\\0')\n\t\t\t\t{\n\t\t\t\t\tlexeme += currentSymbol.symbol;\n\t\t\t\t\tcurrentState = LexerState::TOKEN_QUOTE;\n\t\t\t\t\tcurrentSymbol = contentReader.NextSymbol();\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tstring msj = \"Symbol EOF not expected\";\n\t\t\t\t\tthrow LexicalException(msj.c_str());\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase LexerState::INIT_SQUARE_BRACKET:\n\t\t\t\tif (currentSymbol.symbol == DOUBLEQUOTE)\n\t\t\t\t{\n\t\t\t\t\tlexeme += currentSymbol.symbol;\n\t\t\t\t\tcurrentState = LexerState::TOKEN_QUOTE;\n\t\t\t\t\tupState = LexerState::INIT_SQUARE_BRACKET;\n\t\t\t\t\tquote = DOUBLEQUOTE;\n\t\t\t\t\tcurrentSymbol = contentReader.NextSymbol();\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\telse if (currentSymbol.symbol == SINGLEQUOTE)\n\t\t\t\t{\n\t\t\t\t\tlexeme += currentSymbol.symbol;\n\t\t\t\t\tcurrentState = LexerState::TOKEN_QUOTE;\n\t\t\t\t\tupState = LexerState::INIT_SQUARE_BRACKET;\n\t\t\t\t\tquote = SINGLEQUOTE;\n\t\t\t\t\tcurrentSymbol = contentReader.NextSymbol();\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\telse if (currentSymbol.symbol != RIGHT_SQUARE_BRACKET && currentSymbol.symbol != '\\0')\n\t\t\t\t{\n\t\t\t\t\tlexeme += currentSymbol.symbol;\n\t\t\t\t\tcurrentSymbol = contentReader.NextSymbol();\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\tcase LexerState::END_SQUARE_BRACKET:\n\t\t\t\tif (currentSymbol.symbol == RIGHT_SQUARE_BRACKET)\n\t\t\t\t{\n\t\t\t\t\tlexeme += currentSymbol.symbol;\n\t\t\t\t\tcurrentState = LexerState::TOKEN;\n\t\t\t\t\tcurrentSymbol = contentReader.NextSymbol();\n\t\t\t\t}\n\t\t\t\telse if (currentSymbol.symbol == ',')\n\t\t\t\t{\n\t\t\t\t\tlexeme += currentSymbol.symbol;\n\t\t\t\t\tcurrentState = LexerState::INIT_SQUARE_BRACKET;\n\t\t\t\t\tcurrentSymbol = contentReader.NextSymbol();\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tstring msj = \"Symbol ] expected\";\n\t\t\t\t\tthrow LexicalException(msj.c_str());\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase LexerState::SYMBOL_OP:\n\t\t\t\ttoken.lexeme = lexeme;\n\t\t\t\ttoken.type = singleSymbolDictionary.at(lexeme);\n\t\t\t\treturn token;\n\t\t\tcase LexerState::EOFILE:\n\t\t\t\ttoken.type = TokenType::EndOfFile;\n\t\t\t\treturn token;\n\t\t\tdefault:\n\t\t\t\tbreak;\n\t\t}\n\t}\n\n\treturn token;\n}\n\n\nvoid\nLexer::IsStringOperator(Token& token)\n{\n\tif (!token.lexeme.empty()) {\n\t\tswitch (token.lexeme.at(0)) {\n\t\t\t case 'A':\n\t\t\t\tif (strcmp(token.lexeme.data(), AND) == 0) {\n\t\t\t\t\ttoken.type = TokenType::And;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t case 'O':\n\t\t\t\tif (strcmp(token.lexeme.data(), OR) == 0) {\n\t\t\t\t\ttoken.type = TokenType::Or;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t case 'N':\n\t\t\t\tif (strcmp(token.lexeme.data(), NOT) == 0) {\n\t\t\t\t\ttoken.type = TokenType::Not;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t case 'X':\n\t\t\t\tif (strcmp(token.lexeme.data(), XOR) == 0) {\n\t\t\t\t\ttoken.type = TokenType::Xor;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t default:\n\t\t\t\treturn;\n\t\t}\n\t}\n}\n\n\nbool\nLexer::IsSymbolOp(char c)\n{\n\ttry {\n\t\tsingleSymbolDictionary.at(std::string(1, c));\n\t\treturn true;\n\t} catch (std::out_of_range) {\n\t\treturn false;\n\t}\n}<commit_msg>Improve lexical parser<commit_after>\/*\n * Copyright (C) 2014 furan\n * Copyright (C) 2016 deipi.com LLC and contributors.\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to\n * deal in the Software without restriction, including without limitation the\n * rights to use, copy, modify, merge, publish, distribute, sublicense, and\/or\n * sell copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n * IN THE SOFTWARE.\n *\/\n\n#include \"Lexer.h\"\n\n#define AND \"AND\"\n#define OR \"OR\"\n#define NOT \"NOT\"\n#define XOR \"XOR\"\n\n#define DOUBLEQUOTE '\"'\n#define SINGLEQUOTE '\\''\n#define LEFT_SQUARE_BRACKET '['\n#define RIGHT_SQUARE_BRACKET ']'\n\n\nLexer::Lexer(ContentReader contentReader)\n{\n\tthis->contentReader = contentReader;\n\tcurrentSymbol = this->contentReader.NextSymbol();\n\n\tInitDictionary();\n}\n\n\nLexer::Lexer(char * input)\n{\n\tContentReader cr(input);\n\tcontentReader = cr;\n\tcurrentSymbol = this->contentReader.NextSymbol();\n\n\tInitDictionary();\n\n}\n\n\nvoid\nLexer::InitDictionary()\n{\n\tsingleSymbolDictionary[\"(\"] = TokenType::LeftParenthesis;\n\tsingleSymbolDictionary[\")\"] = TokenType::RightParenthesis;\n\tsingleSymbolDictionary[\"&\"] = TokenType::And;\n\tsingleSymbolDictionary[\"|\"] = TokenType::Or;\n\tsingleSymbolDictionary[\"~\"] = TokenType::Not;\n}\n\n\nToken\nLexer::NextToken()\n{\n\tstring lexeme = \"\";\n\tLexerState currentState = LexerState::INIT;\n\tToken token;\n\tchar quote;\n\n\tauto upState = currentState;\n\n\tstring symbol;\n\tstring lcSymbol;\n\n\twhile (true) {\n\t\tsymbol.clear();\n\t\tsymbol += currentSymbol.symbol;\n\t\tswitch (currentState) {\n\t\t\tcase LexerState::INIT:\n\t\t\t\tswitch(currentSymbol.symbol) {\n\t\t\t\t\tcase LEFT_SQUARE_BRACKET:\n\t\t\t\t\t\tlexeme += currentSymbol.symbol;\n\t\t\t\t\t\tcurrentState = LexerState::INIT_SQUARE_BRACKET;\n\t\t\t\t\t\tcurrentSymbol = contentReader.NextSymbol();\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase SINGLEQUOTE:\n\t\t\t\t\t\tlexeme += currentSymbol.symbol;\n\t\t\t\t\t\tcurrentState = LexerState::TOKEN_QUOTE;\n\t\t\t\t\t\tquote = SINGLEQUOTE;\n\t\t\t\t\t\tcurrentSymbol = contentReader.NextSymbol();\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase DOUBLEQUOTE:\n\t\t\t\t\t\tlexeme += currentSymbol.symbol;\n\t\t\t\t\t\tcurrentState = LexerState::TOKEN_QUOTE;\n\t\t\t\t\t\tquote = DOUBLEQUOTE;\n\t\t\t\t\t\tcurrentSymbol = contentReader.NextSymbol();\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase '\\0':\n\t\t\t\t\t\tcurrentState = LexerState::EOFILE;\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tdefault:\n\t\t\t\t\t\tif(isalnum(currentSymbol.symbol) || currentSymbol.symbol == '_') {\n\t\t\t\t\t\t\tlexeme += currentSymbol.symbol;\n\t\t\t\t\t\t\tcurrentState = LexerState::TOKEN;\n\t\t\t\t\t\t\tcurrentSymbol = contentReader.NextSymbol();\n\t\t\t\t\t\t} else if (isspace(currentSymbol.symbol)) {\n\t\t\t\t\t\t\tcurrentState = LexerState::INIT;\n\t\t\t\t\t\t\tcurrentSymbol = contentReader.NextSymbol();\n\t\t\t\t\t\t} else if(singleSymbolDictionary.find(symbol) != singleSymbolDictionary.end()) {\n\t\t\t\t\t\t\tlexeme += currentSymbol.symbol;\n\t\t\t\t\t\t\tcurrentState = LexerState::SYMBOL_OP;\n\t\t\t\t\t\t\tcurrentSymbol = contentReader.NextSymbol();\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tstring msj = \"Symbol \" + symbol + \" not expected\";\n\t\t\t\t\t\t\tthrow LexicalException(msj.c_str());\n\t\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase LexerState::TOKEN:\n\t\t\t\tswitch(currentSymbol.symbol) {\n\t\t\t\t\tcase DOUBLEQUOTE:\n\t\t\t\t\t\tlexeme += currentSymbol.symbol;\n\t\t\t\t\t\tcurrentState = LexerState::TOKEN_QUOTE;\n\t\t\t\t\t\tquote = DOUBLEQUOTE;\n\t\t\t\t\t\tcurrentSymbol = contentReader.NextSymbol();\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase SINGLEQUOTE:\n\t\t\t\t\t\tlexeme += currentSymbol.symbol;\n\t\t\t\t\t\tcurrentState = LexerState::TOKEN_QUOTE;\n\t\t\t\t\t\tquote = SINGLEQUOTE;\n\t\t\t\t\t\tcurrentSymbol = contentReader.NextSymbol();\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tdefault:\n\t\t\t\t\t\tif (!IsSymbolOp(currentSymbol.symbol) && currentSymbol.symbol != ' ' && currentSymbol.symbol != '\\0') {\n\t\t\t\t\t\t\tlexeme += currentSymbol.symbol;\n\t\t\t\t\t\t\tcurrentState = LexerState::TOKEN;\n\t\t\t\t\t\t\tcurrentSymbol = contentReader.NextSymbol();\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\ttoken.lexeme = lexeme;\n\t\t\t\t\t\t\ttoken.type = TokenType::Id;\n\t\t\t\t\t\t\tIsStringOperator(token);\n\t\t\t\t\t\t\treturn token;\n\t\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase LexerState::TOKEN_QUOTE:\n\t\t\t\tswitch (currentSymbol.symbol) {\n\t\t\t\t\tcase '\\\\':\n\t\t\t\t\t\tlexeme += currentSymbol.symbol;\n\t\t\t\t\t\tcurrentState = LexerState::ESCAPE;\n\t\t\t\t\t\tcurrentSymbol = contentReader.NextSymbol();\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase '\\0': {\n\t\t\t\t\t\tstring msj = \"Symbol double quote expected\";\n\t\t\t\t\t\tthrow LexicalException(msj.c_str());\n\t\t\t\t\t}\n\n\t\t\t\t\tdefault:\n\t\t\t\t\t\tif (currentSymbol.symbol == quote) {\n\t\t\t\t\t\t\tlexeme += currentSymbol.symbol;\n\t\t\t\t\t\t\tupState == LexerState::INIT_SQUARE_BRACKET ? currentState = LexerState::END_SQUARE_BRACKET : currentState = LexerState::TOKEN;\n\t\t\t\t\t\t\tcurrentSymbol = contentReader.NextSymbol();\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tlexeme += currentSymbol.symbol;\n\t\t\t\t\t\t\tcurrentSymbol = contentReader.NextSymbol();\n\t\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase LexerState::ESCAPE:\n\t\t\t\tswitch(currentSymbol.symbol) {\n\t\t\t\t\tcase '\\0': {\n\t\t\t\t\t\tstring msj = \"Symbol EOF not expected\";\n\t\t\t\t\t\tthrow LexicalException(msj.c_str());\n\t\t\t\t\t}\n\n\t\t\t\t\tdefault:\n\t\t\t\t\t\tlexeme += currentSymbol.symbol;\n\t\t\t\t\t\tcurrentState = LexerState::TOKEN_QUOTE;\n\t\t\t\t\t\tcurrentSymbol = contentReader.NextSymbol();\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase LexerState::INIT_SQUARE_BRACKET:\n\t\t\t\tswitch (currentSymbol.symbol) {\n\t\t\t\t\tcase DOUBLEQUOTE:\n\t\t\t\t\t\tlexeme += currentSymbol.symbol;\n\t\t\t\t\t\tcurrentState = LexerState::TOKEN_QUOTE;\n\t\t\t\t\t\tupState = LexerState::INIT_SQUARE_BRACKET;\n\t\t\t\t\t\tquote = DOUBLEQUOTE;\n\t\t\t\t\t\tcurrentSymbol = contentReader.NextSymbol();\n\t\t\t\t\t\tcontinue;\n\n\t\t\t\t\tcase SINGLEQUOTE:\n\t\t\t\t\t\tlexeme += currentSymbol.symbol;\n\t\t\t\t\t\tcurrentState = LexerState::TOKEN_QUOTE;\n\t\t\t\t\t\tupState = LexerState::INIT_SQUARE_BRACKET;\n\t\t\t\t\t\tquote = SINGLEQUOTE;\n\t\t\t\t\t\tcurrentSymbol = contentReader.NextSymbol();\n\t\t\t\t\t\tcontinue;\n\n\t\t\t\t\tdefault:\n\t\t\t\t\t\tif (currentSymbol.symbol != RIGHT_SQUARE_BRACKET && currentSymbol.symbol != '\\0') {\n\t\t\t\t\t\t\tlexeme += currentSymbol.symbol;\n\t\t\t\t\t\t\tcurrentSymbol = contentReader.NextSymbol();\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\tcase LexerState::END_SQUARE_BRACKET:\n\t\t\t\tswitch (currentSymbol.symbol) {\n\t\t\t\t\tcase RIGHT_SQUARE_BRACKET:\n\t\t\t\t\t\tlexeme += currentSymbol.symbol;\n\t\t\t\t\t\tcurrentState = LexerState::TOKEN;\n\t\t\t\t\t\tcurrentSymbol = contentReader.NextSymbol();\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase ',':\n\t\t\t\t\t\tlexeme += currentSymbol.symbol;\n\t\t\t\t\t\tcurrentState = LexerState::INIT_SQUARE_BRACKET;\n\t\t\t\t\t\tcurrentSymbol = contentReader.NextSymbol();\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tdefault:\n\t\t\t\t\t\tstring msj = \"Symbol ] expected\";\n\t\t\t\t\t\tthrow LexicalException(msj.c_str());\n\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase LexerState::SYMBOL_OP:\n\t\t\t\ttoken.lexeme = lexeme;\n\t\t\t\ttoken.type = singleSymbolDictionary.at(lexeme);\n\t\t\t\treturn token;\n\t\t\tcase LexerState::EOFILE:\n\t\t\t\ttoken.type = TokenType::EndOfFile;\n\t\t\t\treturn token;\n\t\t\tdefault:\n\t\t\t\tbreak;\n\t\t}\n\t}\n\n\treturn token;\n}\n\n\nvoid\nLexer::IsStringOperator(Token& token)\n{\n\tif (!token.lexeme.empty()) {\n\t\tswitch (token.lexeme.at(0)) {\n\t\t\t case 'A':\n\t\t\t\tif (strcmp(token.lexeme.data(), AND) == 0) {\n\t\t\t\t\ttoken.type = TokenType::And;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t case 'O':\n\t\t\t\tif (strcmp(token.lexeme.data(), OR) == 0) {\n\t\t\t\t\ttoken.type = TokenType::Or;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t case 'N':\n\t\t\t\tif (strcmp(token.lexeme.data(), NOT) == 0) {\n\t\t\t\t\ttoken.type = TokenType::Not;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t case 'X':\n\t\t\t\tif (strcmp(token.lexeme.data(), XOR) == 0) {\n\t\t\t\t\ttoken.type = TokenType::Xor;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t default:\n\t\t\t\treturn;\n\t\t}\n\t}\n}\n\n\nbool\nLexer::IsSymbolOp(char c)\n{\n\ttry {\n\t\tsingleSymbolDictionary.at(std::string(1, c));\n\t\treturn true;\n\t} catch (std::out_of_range) {\n\t\treturn false;\n\t}\n}<|endoftext|>"} {"text":"<commit_before>\/**\n * Clever programming language\n * Copyright (c) Clever Team\n *\n * This file is distributed under the MIT license. See LICENSE for details.\n *\/\n\n#include <string>\n#include <sstream>\n#include \"types\/str.h\"\n\nnamespace clever {\n\nCLEVER_TYPE_OPERATOR(StrType::add)\n{\n\tif (EXPECTED(rhs->getType() == this)) {\n\t\t\/\/ TODO(Felipe): Do not require CString everywhere (because it stores the\n\t\t\/\/ data in an string table)\n\t\tresult->setStr(CSTRING(*lhs->getStr() + *rhs->getStr()));\n\t}\n}\n\nCLEVER_TYPE_OPERATOR(StrType::sub)\n{\t\n}\n\nCLEVER_TYPE_OPERATOR(StrType::mul)\n{\n\tif (rhs->getType() == CLEVER_INT_TYPE) {\n\t\tstd::ostringstream os;\n\n\t\tfor (long i = 0, j = rhs->getInt(); i < j; ++i) {\n\t\t\tos << *lhs->getStr();\n\t\t}\n\n\t\tresult->setStr(CSTRING(os.str()));\n\t}\n}\n\nCLEVER_TYPE_OPERATOR(StrType::div)\n{\n}\n\nCLEVER_TYPE_OPERATOR(StrType::mod)\n{\t\n}\n\n\/\/ String.subString(string str, [int start, [int count]])\n\/\/ String.subString(int start, [int count])\n\/\/ Returns a substring of the argument or string object referenced using bounds provided\nCLEVER_METHOD(StrType::subString) \n{\n\tconst CString *of = NULL;\n\tint bounds[2];\n\n\tbounds[0]=-1;\n\tbounds[1]=-1;\n\n\tif (CLEVER_THIS()) {\n\t\tof = (const CString*) CLEVER_THIS()->getStr();\n\t\tswitch(CLEVER_ARG_COUNT()) {\n\t\t\tcase 2:\n\t\t\t\tbounds[0]=CLEVER_ARG_INT(0);\n\t\t\t\tbounds[1]=CLEVER_ARG_INT(1);\n\t\t\tbreak;\n\t\t\tcase 1: \n\t\t\t\tbounds[0]=CLEVER_ARG_INT(0);\n\t\t\tbreak;\n\t\t\tdefault: std::cerr << \"String.subString expected at least one argument\";\n\t\t}\n\t} else if (CLEVER_ARG_COUNT()) {\n\t\tof = (const CString*) CLEVER_ARG_CSTR(0);\n\t\tswitch(CLEVER_ARG_COUNT()) {\n\t\t\tcase 3:\n\t\t\t\tbounds[0]=CLEVER_ARG_INT(1);\n\t\t\t\tbounds[1]=CLEVER_ARG_INT(2);\n\t\t\tbreak;\n\t\t\tcase 2: bounds[0]=CLEVER_ARG_INT(1); break;\n\t\t\t\n\t\t\tdefault: std::cerr << \"String.subString expected at least two arguments\";\n\t\t}\n\t}\n\n\tif (of && bounds[0]>-1) {\n\t\tif (bounds[1]>-1) {\n\t\t\tresult->setStr(CSTRING(of->substr(bounds[0], bounds[1])));\n\t\t} else result->setStr(CSTRING(of->substr(bounds[0])));\n\t}\n}\n\n\/\/ String.findString(string haystack, string needle, [int position, [int count]])\n\/\/ String.findString(string needle, [int position, [int count]])\n\/\/ Finds a string in a string returning the position\nCLEVER_METHOD(StrType::find) \n{\n\tconst char *needle;\n\tconst CString *haystack;\n\tint bounds[2];\n\n\tbounds[0]=-1;\n\tbounds[1]=-1;\n\t\n\tif (CLEVER_THIS()) {\n\t\thaystack = (const CString*) CLEVER_THIS()->getStr();\n\t\tswitch (CLEVER_ARG_COUNT()) {\n\t\t\tcase 1:\n\t\t\t\tneedle = CLEVER_ARG_PSTR(0);\n\t\t\tbreak;\n\t\t\tcase 2:\n\t\t\t\tneedle = CLEVER_ARG_PSTR(0);\n\t\t\t\tbounds[0] = CLEVER_ARG_INT(1);\n\t\t\tbreak;\n\t\t\tcase 3:\n\t\t\t\tneedle = CLEVER_ARG_PSTR(0);\n\t\t\t\tbounds[0] = CLEVER_ARG_INT(1);\t\t\n\t\t\t\tbounds[1] = CLEVER_ARG_INT(2);\n\t\t\tbreak;\n\t\t\tdefault: std::cerr << \"String.find expected a maximum of 2 arguments\";\n\t\t}\n\t} else if(CLEVER_ARG_COUNT()) {\n\t\thaystack = (const CString*) CLEVER_ARG_CSTR(0);\n\t\tswitch (CLEVER_ARG_COUNT()) {\n\t\t\tcase 4:\n\t\t\t\tneedle = CLEVER_ARG_PSTR(1);\n\t\t\t\tbounds[0] = CLEVER_ARG_INT(2);\n\t\t\t\tbounds[1] = CLEVER_ARG_INT(3);\n\t\t\tbreak;\n\t\t\tcase 3:\n\t\t\t\tneedle = CLEVER_ARG_PSTR(1);\n\t\t\t\tbounds[0] = CLEVER_ARG_INT(2);\n\t\t\tbreak;\n\t\t\tcase 2:\n\t\t\t\tneedle = CLEVER_ARG_PSTR(1);\n\t\t\tbreak;\n\t\t\tdefault: std::cerr << \"String.find expected at least two arguments\";\n\t\t}\n\t}\t\n\n\tif (needle && haystack) {\n\t\tif (bounds[0]>-1) {\n\t\t\tif (bounds[1]>-1) {\n\t\t\t\tresult->setInt(haystack->find((const char*)needle, bounds[0], bounds[1]));\n\t\t\t} else result->setInt(haystack->find((const char*)needle, bounds[0]));\n\t\t} else result->setInt(haystack->find((const char*)needle));\n\t}\n}\n\nCLEVER_METHOD(StrType::findFirst) \n{\n\tconst char *needle;\n\tconst CString *haystack;\n\tint bounds[2];\n\n\tbounds[0]=-1;\n\tbounds[1]=-1;\n\t\n\tif (CLEVER_THIS()) {\n\t\thaystack = (const CString*) CLEVER_THIS()->getStr();\n\t\tswitch (CLEVER_ARG_COUNT()) {\n\t\t\tcase 1:\n\t\t\t\tneedle = CLEVER_ARG_PSTR(0);\n\t\t\tbreak;\n\t\t\tcase 2:\n\t\t\t\tneedle = CLEVER_ARG_PSTR(0);\n\t\t\t\tbounds[0] = CLEVER_ARG_INT(1);\n\t\t\tbreak;\n\t\t\tcase 3:\n\t\t\t\tneedle = CLEVER_ARG_PSTR(0);\n\t\t\t\tbounds[0] = CLEVER_ARG_INT(1);\t\t\n\t\t\t\tbounds[1] = CLEVER_ARG_INT(2);\n\t\t\tbreak;\n\t\t\tdefault: std::cerr << \"String.findFirst expected a maximum of 2 arguments\";\n\t\t}\n\t} else if(CLEVER_ARG_COUNT()) {\n\t\thaystack = (const CString*) CLEVER_ARG_CSTR(0);\n\t\tswitch (CLEVER_ARG_COUNT()) {\n\t\t\tcase 4:\n\t\t\t\tneedle = CLEVER_ARG_PSTR(1);\n\t\t\t\tbounds[0] = CLEVER_ARG_INT(2);\n\t\t\t\tbounds[1] = CLEVER_ARG_INT(3);\n\t\t\tbreak;\n\t\t\tcase 3:\n\t\t\t\tneedle = CLEVER_ARG_PSTR(1);\n\t\t\t\tbounds[0] = CLEVER_ARG_INT(2);\n\t\t\tbreak;\n\t\t\tcase 2:\n\t\t\t\tneedle = CLEVER_ARG_PSTR(1);\n\t\t\tbreak;\n\t\t\tdefault: std::cerr << \"String.findFirst expected at least two arguments\";\n\t\t}\n\t}\t\n\n\tif (needle && haystack) {\n\t\tif (bounds[0]>-1) {\n\t\t\tif (bounds[1]>-1) {\n\t\t\t\tresult->setInt(haystack->find_first_of((const char*)needle, bounds[0], bounds[1]));\n\t\t\t} else result->setInt(haystack->find_first_of((const char*)needle, bounds[0]));\n\t\t} else result->setInt(haystack->find_first_of((const char*)needle));\n\t}\n}\n\nCLEVER_METHOD(StrType::findLast) \n{\n\tconst char *needle;\n\tconst CString *haystack;\n\tint bounds[2];\n\n\tbounds[0]=-1;\n\tbounds[1]=-1;\n\t\n\tif (CLEVER_THIS()) {\n\t\thaystack = (const CString*) CLEVER_THIS()->getStr();\n\t\tswitch (CLEVER_ARG_COUNT()) {\n\t\t\tcase 1:\n\t\t\t\tneedle = CLEVER_ARG_PSTR(0);\n\t\t\tbreak;\n\t\t\tcase 2:\n\t\t\t\tneedle = CLEVER_ARG_PSTR(0);\n\t\t\t\tbounds[0] = CLEVER_ARG_INT(1);\n\t\t\tbreak;\n\t\t\tcase 3:\n\t\t\t\tneedle = CLEVER_ARG_PSTR(0);\n\t\t\t\tbounds[0] = CLEVER_ARG_INT(1);\t\t\n\t\t\t\tbounds[1] = CLEVER_ARG_INT(2);\n\t\t\tbreak;\n\t\t\tdefault: std::cerr << \"String.findLast expected a maximum of 2 arguments\";\n\t\t}\n\t} else if(CLEVER_ARG_COUNT()) {\n\t\thaystack = (const CString*) CLEVER_ARG_CSTR(0);\n\t\tswitch (CLEVER_ARG_COUNT()) {\n\t\t\tcase 4:\n\t\t\t\tneedle = CLEVER_ARG_PSTR(1);\n\t\t\t\tbounds[0] = CLEVER_ARG_INT(2);\n\t\t\t\tbounds[1] = CLEVER_ARG_INT(3);\n\t\t\tbreak;\n\t\t\tcase 3:\n\t\t\t\tneedle = CLEVER_ARG_PSTR(1);\n\t\t\t\tbounds[0] = CLEVER_ARG_INT(2);\n\t\t\tbreak;\n\t\t\tcase 2:\n\t\t\t\tneedle = CLEVER_ARG_PSTR(1);\n\t\t\tbreak;\n\t\t\tdefault: std::cerr << \"String.findLast expected at least two arguments\";\n\t\t}\n\t}\t\n\n\tif (needle && haystack) {\n\t\tif (bounds[0]>-1) {\n\t\t\tif (bounds[1]>-1) {\n\t\t\t\tresult->setInt(haystack->find_last_of((const char*)needle, bounds[0], bounds[1]));\n\t\t\t} else result->setInt(haystack->find_last_of((const char*)needle, bounds[0]));\n\t\t} else result->setInt(haystack->find_last_of((const char*)needle));\n\t}\n}\n\nCLEVER_METHOD(StrType::getLength)\n{\n\tif (CLEVER_THIS()) {\n\t\tresult->setInt(((const CString*) CLEVER_THIS()->getStr())->length());\n\t} else {\n\t\tif(CLEVER_ARG_COUNT()) {\n\t\t\tresult->setInt(((const CString*) CLEVER_ARG_CSTR(0))->length());\n\t\t} else std::cerr << \"String.getLength expected a string argument\";\n\t}\n}\n\nCLEVER_TYPE_INIT(StrType::init) \n{\n\taddMethod(CSTRING(\"subString\"), \t(MethodPtr) &StrType::subString);\n\taddMethod(CSTRING(\"find\"), \t\t\t(MethodPtr) &StrType::find);\n\taddMethod(CSTRING(\"findFirst\"), \t(MethodPtr) &StrType::findFirst);\n\taddMethod(CSTRING(\"findLast\"), \t\t(MethodPtr) &StrType::findLast);\t\n\taddMethod(CSTRING(\"getLength\"),\t\t(MethodPtr) &StrType::getLength);\n}\n\n} \/\/ clever\n<commit_msg>comments<commit_after>\/**\n * Clever programming language\n * Copyright (c) Clever Team\n *\n * This file is distributed under the MIT license. See LICENSE for details.\n *\/\n\n#include <string>\n#include <sstream>\n#include \"types\/str.h\"\n\nnamespace clever {\n\nCLEVER_TYPE_OPERATOR(StrType::add)\n{\n\tif (EXPECTED(rhs->getType() == this)) {\n\t\t\/\/ TODO(Felipe): Do not require CString everywhere (because it stores the\n\t\t\/\/ data in an string table)\n\t\tresult->setStr(CSTRING(*lhs->getStr() + *rhs->getStr()));\n\t}\n}\n\nCLEVER_TYPE_OPERATOR(StrType::sub)\n{\t\n}\n\nCLEVER_TYPE_OPERATOR(StrType::mul)\n{\n\tif (rhs->getType() == CLEVER_INT_TYPE) {\n\t\tstd::ostringstream os;\n\n\t\tfor (long i = 0, j = rhs->getInt(); i < j; ++i) {\n\t\t\tos << *lhs->getStr();\n\t\t}\n\n\t\tresult->setStr(CSTRING(os.str()));\n\t}\n}\n\nCLEVER_TYPE_OPERATOR(StrType::div)\n{\n}\n\nCLEVER_TYPE_OPERATOR(StrType::mod)\n{\t\n}\n\n\/\/ String.subString(string str, [int start, [int count]])\n\/\/ String.subString(int start, [int count])\n\/\/ Returns a substring of the argument or string object referenced using bounds provided\nCLEVER_METHOD(StrType::subString) \n{\n\tconst CString *of = NULL;\n\tint bounds[2];\n\n\tbounds[0]=-1;\n\tbounds[1]=-1;\n\n\tif (CLEVER_THIS()) {\n\t\tof = (const CString*) CLEVER_THIS()->getStr();\n\t\tswitch(CLEVER_ARG_COUNT()) {\n\t\t\tcase 2:\n\t\t\t\tbounds[0]=CLEVER_ARG_INT(0);\n\t\t\t\tbounds[1]=CLEVER_ARG_INT(1);\n\t\t\tbreak;\n\t\t\tcase 1: \n\t\t\t\tbounds[0]=CLEVER_ARG_INT(0);\n\t\t\tbreak;\n\t\t\tdefault: std::cerr << \"String.subString expected at least one argument\";\n\t\t}\n\t} else if (CLEVER_ARG_COUNT()) {\n\t\tof = (const CString*) CLEVER_ARG_CSTR(0);\n\t\tswitch(CLEVER_ARG_COUNT()) {\n\t\t\tcase 3:\n\t\t\t\tbounds[0]=CLEVER_ARG_INT(1);\n\t\t\t\tbounds[1]=CLEVER_ARG_INT(2);\n\t\t\tbreak;\n\t\t\tcase 2: bounds[0]=CLEVER_ARG_INT(1); break;\n\t\t\t\n\t\t\tdefault: std::cerr << \"String.subString expected at least two arguments\";\n\t\t}\n\t}\n\n\tif (of && bounds[0]>-1) {\n\t\tif (bounds[1]>-1) {\n\t\t\tresult->setStr(CSTRING(of->substr(bounds[0], bounds[1])));\n\t\t} else result->setStr(CSTRING(of->substr(bounds[0])));\n\t}\n}\n\n\/\/ String.find(string haystack, string needle, [int position, [int count]])\n\/\/ String.find(string needle, [int position, [int count]])\n\/\/ Finds a string in a string returning the position\nCLEVER_METHOD(StrType::find) \n{\n\tconst char *needle;\n\tconst CString *haystack;\n\tint bounds[2];\n\n\tbounds[0]=-1;\n\tbounds[1]=-1;\n\t\n\tif (CLEVER_THIS()) {\n\t\thaystack = (const CString*) CLEVER_THIS()->getStr();\n\t\tswitch (CLEVER_ARG_COUNT()) {\n\t\t\tcase 1:\n\t\t\t\tneedle = CLEVER_ARG_PSTR(0);\n\t\t\tbreak;\n\t\t\tcase 2:\n\t\t\t\tneedle = CLEVER_ARG_PSTR(0);\n\t\t\t\tbounds[0] = CLEVER_ARG_INT(1);\n\t\t\tbreak;\n\t\t\tcase 3:\n\t\t\t\tneedle = CLEVER_ARG_PSTR(0);\n\t\t\t\tbounds[0] = CLEVER_ARG_INT(1);\t\t\n\t\t\t\tbounds[1] = CLEVER_ARG_INT(2);\n\t\t\tbreak;\n\t\t\tdefault: std::cerr << \"String.find expected a maximum of 2 arguments\";\n\t\t}\n\t} else if(CLEVER_ARG_COUNT()) {\n\t\thaystack = (const CString*) CLEVER_ARG_CSTR(0);\n\t\tswitch (CLEVER_ARG_COUNT()) {\n\t\t\tcase 4:\n\t\t\t\tneedle = CLEVER_ARG_PSTR(1);\n\t\t\t\tbounds[0] = CLEVER_ARG_INT(2);\n\t\t\t\tbounds[1] = CLEVER_ARG_INT(3);\n\t\t\tbreak;\n\t\t\tcase 3:\n\t\t\t\tneedle = CLEVER_ARG_PSTR(1);\n\t\t\t\tbounds[0] = CLEVER_ARG_INT(2);\n\t\t\tbreak;\n\t\t\tcase 2:\n\t\t\t\tneedle = CLEVER_ARG_PSTR(1);\n\t\t\tbreak;\n\t\t\tdefault: std::cerr << \"String.find expected at least two arguments\";\n\t\t}\n\t}\t\n\n\tif (needle && haystack) {\n\t\tif (bounds[0]>-1) {\n\t\t\tif (bounds[1]>-1) {\n\t\t\t\tresult->setInt(haystack->find((const char*)needle, bounds[0], bounds[1]));\n\t\t\t} else result->setInt(haystack->find((const char*)needle, bounds[0]));\n\t\t} else result->setInt(haystack->find((const char*)needle));\n\t}\n}\n\n\/\/ String.findFirst(string haystack, string needle, [int position, [int count]])\n\/\/ String.findFirst(string needle, [int position, [int count]])\n\/\/ Finds the first occurence of a string in a string returning the position\nCLEVER_METHOD(StrType::findFirst) \n{\n\tconst char *needle;\n\tconst CString *haystack;\n\tint bounds[2];\n\n\tbounds[0]=-1;\n\tbounds[1]=-1;\n\t\n\tif (CLEVER_THIS()) {\n\t\thaystack = (const CString*) CLEVER_THIS()->getStr();\n\t\tswitch (CLEVER_ARG_COUNT()) {\n\t\t\tcase 1:\n\t\t\t\tneedle = CLEVER_ARG_PSTR(0);\n\t\t\tbreak;\n\t\t\tcase 2:\n\t\t\t\tneedle = CLEVER_ARG_PSTR(0);\n\t\t\t\tbounds[0] = CLEVER_ARG_INT(1);\n\t\t\tbreak;\n\t\t\tcase 3:\n\t\t\t\tneedle = CLEVER_ARG_PSTR(0);\n\t\t\t\tbounds[0] = CLEVER_ARG_INT(1);\t\t\n\t\t\t\tbounds[1] = CLEVER_ARG_INT(2);\n\t\t\tbreak;\n\t\t\tdefault: std::cerr << \"String.findFirst expected a maximum of 2 arguments\";\n\t\t}\n\t} else if(CLEVER_ARG_COUNT()) {\n\t\thaystack = (const CString*) CLEVER_ARG_CSTR(0);\n\t\tswitch (CLEVER_ARG_COUNT()) {\n\t\t\tcase 4:\n\t\t\t\tneedle = CLEVER_ARG_PSTR(1);\n\t\t\t\tbounds[0] = CLEVER_ARG_INT(2);\n\t\t\t\tbounds[1] = CLEVER_ARG_INT(3);\n\t\t\tbreak;\n\t\t\tcase 3:\n\t\t\t\tneedle = CLEVER_ARG_PSTR(1);\n\t\t\t\tbounds[0] = CLEVER_ARG_INT(2);\n\t\t\tbreak;\n\t\t\tcase 2:\n\t\t\t\tneedle = CLEVER_ARG_PSTR(1);\n\t\t\tbreak;\n\t\t\tdefault: std::cerr << \"String.findFirst expected at least two arguments\";\n\t\t}\n\t}\t\n\n\tif (needle && haystack) {\n\t\tif (bounds[0]>-1) {\n\t\t\tif (bounds[1]>-1) {\n\t\t\t\tresult->setInt(haystack->find_first_of((const char*)needle, bounds[0], bounds[1]));\n\t\t\t} else result->setInt(haystack->find_first_of((const char*)needle, bounds[0]));\n\t\t} else result->setInt(haystack->find_first_of((const char*)needle));\n\t}\n}\n\/\/ String.findLast(string haystack, string needle, [int position, [int count]])\n\/\/ String.findLast(string needle, [int position, [int count]])\n\/\/ Finds the last occurence of a string in a string returning the position\nCLEVER_METHOD(StrType::findLast) \n{\n\tconst char *needle;\n\tconst CString *haystack;\n\tint bounds[2];\n\n\tbounds[0]=-1;\n\tbounds[1]=-1;\n\t\n\tif (CLEVER_THIS()) {\n\t\thaystack = (const CString*) CLEVER_THIS()->getStr();\n\t\tswitch (CLEVER_ARG_COUNT()) {\n\t\t\tcase 1:\n\t\t\t\tneedle = CLEVER_ARG_PSTR(0);\n\t\t\tbreak;\n\t\t\tcase 2:\n\t\t\t\tneedle = CLEVER_ARG_PSTR(0);\n\t\t\t\tbounds[0] = CLEVER_ARG_INT(1);\n\t\t\tbreak;\n\t\t\tcase 3:\n\t\t\t\tneedle = CLEVER_ARG_PSTR(0);\n\t\t\t\tbounds[0] = CLEVER_ARG_INT(1);\t\t\n\t\t\t\tbounds[1] = CLEVER_ARG_INT(2);\n\t\t\tbreak;\n\t\t\tdefault: std::cerr << \"String.findLast expected a maximum of 2 arguments\";\n\t\t}\n\t} else if(CLEVER_ARG_COUNT()) {\n\t\thaystack = (const CString*) CLEVER_ARG_CSTR(0);\n\t\tswitch (CLEVER_ARG_COUNT()) {\n\t\t\tcase 4:\n\t\t\t\tneedle = CLEVER_ARG_PSTR(1);\n\t\t\t\tbounds[0] = CLEVER_ARG_INT(2);\n\t\t\t\tbounds[1] = CLEVER_ARG_INT(3);\n\t\t\tbreak;\n\t\t\tcase 3:\n\t\t\t\tneedle = CLEVER_ARG_PSTR(1);\n\t\t\t\tbounds[0] = CLEVER_ARG_INT(2);\n\t\t\tbreak;\n\t\t\tcase 2:\n\t\t\t\tneedle = CLEVER_ARG_PSTR(1);\n\t\t\tbreak;\n\t\t\tdefault: std::cerr << \"String.findLast expected at least two arguments\";\n\t\t}\n\t}\t\n\n\tif (needle && haystack) {\n\t\tif (bounds[0]>-1) {\n\t\t\tif (bounds[1]>-1) {\n\t\t\t\tresult->setInt(haystack->find_last_of((const char*)needle, bounds[0], bounds[1]));\n\t\t\t} else result->setInt(haystack->find_last_of((const char*)needle, bounds[0]));\n\t\t} else result->setInt(haystack->find_last_of((const char*)needle));\n\t}\n}\n\n\/\/ String.getLength(string str)\n\/\/ String.getLength()\n\/\/ Returns the length of the string\nCLEVER_METHOD(StrType::getLength)\n{\n\tif (CLEVER_THIS()) {\n\t\tresult->setInt(((const CString*) CLEVER_THIS()->getStr())->length());\n\t} else {\n\t\tif(CLEVER_ARG_COUNT()) {\n\t\t\tresult->setInt(((const CString*) CLEVER_ARG_CSTR(0))->length());\n\t\t} else std::cerr << \"String.getLength expected a string argument\";\n\t}\n}\n\nCLEVER_TYPE_INIT(StrType::init) \n{\n\taddMethod(CSTRING(\"subString\"), \t(MethodPtr) &StrType::subString);\n\taddMethod(CSTRING(\"find\"), \t\t\t(MethodPtr) &StrType::find);\n\taddMethod(CSTRING(\"findFirst\"), \t(MethodPtr) &StrType::findFirst);\n\taddMethod(CSTRING(\"findLast\"), \t\t(MethodPtr) &StrType::findLast);\t\n\taddMethod(CSTRING(\"getLength\"),\t\t(MethodPtr) &StrType::getLength);\n}\n\n} \/\/ clever\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: anminfo.cxx,v $\n *\n * $Revision: 1.14 $\n *\n * last change: $Author: ihi $ $Date: 2006-11-14 14:20:48 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_sd.hxx\"\n\n#ifndef _URLOBJ_HXX\n#include <tools\/urlobj.hxx>\n#endif\n#ifndef _SFXSMPLHINT_HXX \/\/autogen\n#include <svtools\/smplhint.hxx>\n#endif\n#include \"svx\/xtable.hxx\"\n#ifndef _SVDOPATH_HXX \/\/autogen\n#include <svx\/svdopath.hxx>\n#endif\n#include <svtools\/urihelper.hxx>\n\n\n#include \"anminfo.hxx\"\n#include \"glob.hxx\"\n#include \"sdiocmpt.hxx\"\n#include \"drawdoc.hxx\"\n\n\/\/ #90477#\n#ifndef _TOOLS_TENCCVT_HXX\n#include <tools\/tenccvt.hxx>\n#endif\n\nusing namespace ::com::sun::star;\n\nSdAnimationInfo::SdAnimationInfo()\n : SdrObjUserData(SdUDInventor, SD_ANIMATIONINFO_ID, 0),\n mePresObjKind (PRESOBJ_NONE),\n eEffect (presentation::AnimationEffect_NONE),\n eTextEffect (presentation::AnimationEffect_NONE),\n eSpeed (presentation::AnimationSpeed_SLOW),\n bActive (TRUE),\n bDimPrevious (FALSE),\n bIsMovie (FALSE),\n bDimHide (FALSE),\n bSoundOn (FALSE),\n bPlayFull (FALSE),\n pPathObj (NULL),\n eClickAction (presentation::ClickAction_NONE),\n eSecondEffect (presentation::AnimationEffect_NONE),\n eSecondSpeed (presentation::AnimationSpeed_SLOW),\n bSecondSoundOn (FALSE),\n bSecondPlayFull (FALSE),\n nVerb (0),\n nPresOrder (LIST_APPEND)\n{\n aBlueScreen = RGB_Color(COL_LIGHTMAGENTA);\n aDimColor = RGB_Color(COL_LIGHTGRAY);\n}\n\nSdAnimationInfo::SdAnimationInfo(const SdAnimationInfo& rAnmInfo)\n : SdrObjUserData (rAnmInfo),\n mePresObjKind (PRESOBJ_NONE),\n eEffect (rAnmInfo.eEffect),\n eTextEffect (rAnmInfo.eTextEffect),\n eSpeed (rAnmInfo.eSpeed),\n bActive (rAnmInfo.bActive),\n bDimPrevious (rAnmInfo.bDimPrevious),\n bIsMovie (rAnmInfo.bIsMovie),\n bDimHide (rAnmInfo.bDimHide),\n aBlueScreen (rAnmInfo.aBlueScreen),\n aDimColor (rAnmInfo.aDimColor),\n aSoundFile (rAnmInfo.aSoundFile),\n bSoundOn (rAnmInfo.bSoundOn),\n bPlayFull (rAnmInfo.bPlayFull),\n pPathObj (NULL),\n eClickAction (rAnmInfo.eClickAction),\n eSecondEffect (rAnmInfo.eSecondEffect),\n eSecondSpeed (rAnmInfo.eSecondSpeed),\n bSecondSoundOn (rAnmInfo.bSecondSoundOn),\n bSecondPlayFull (rAnmInfo.bSecondPlayFull),\n nVerb (rAnmInfo.nVerb),\n aBookmark (rAnmInfo.aBookmark),\n aSecondSoundFile (rAnmInfo.aSecondSoundFile),\n nPresOrder (LIST_APPEND)\n{\n \/\/ can not be copied\n if (eEffect == presentation::AnimationEffect_PATH)\n eEffect = presentation::AnimationEffect_NONE;\n}\n\n\nSdAnimationInfo::~SdAnimationInfo()\n{\n}\n\nSdrObjUserData* SdAnimationInfo::Clone(SdrObject* pObj) const\n{\n return new SdAnimationInfo(*this);\n}\n<commit_msg>INTEGRATION: CWS sdwarningsbegone (1.13.36); FILE MERGED 2006\/11\/22 14:57:16 cl 1.13.36.2: RESYNC: (1.13-1.14); FILE MERGED 2006\/11\/22 12:41:31 cl 1.13.36.1: #i69285# warning free code changes for unxlngi6.pro<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: anminfo.cxx,v $\n *\n * $Revision: 1.15 $\n *\n * last change: $Author: kz $ $Date: 2006-12-12 16:30:40 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_sd.hxx\"\n\n#ifndef _URLOBJ_HXX\n#include <tools\/urlobj.hxx>\n#endif\n#ifndef _SFXSMPLHINT_HXX \/\/autogen\n#include <svtools\/smplhint.hxx>\n#endif\n#include \"svx\/xtable.hxx\"\n#ifndef _SVDOPATH_HXX \/\/autogen\n#include <svx\/svdopath.hxx>\n#endif\n#include <svtools\/urihelper.hxx>\n\n\n#include \"anminfo.hxx\"\n#include \"glob.hxx\"\n#include \"sdiocmpt.hxx\"\n#include \"drawdoc.hxx\"\n\n\/\/ #90477#\n#ifndef _TOOLS_TENCCVT_HXX\n#include <tools\/tenccvt.hxx>\n#endif\n\nusing namespace ::com::sun::star;\n\nSdAnimationInfo::SdAnimationInfo()\n : SdrObjUserData(SdUDInventor, SD_ANIMATIONINFO_ID, 0),\n mePresObjKind (PRESOBJ_NONE),\n meEffect (presentation::AnimationEffect_NONE),\n meTextEffect (presentation::AnimationEffect_NONE),\n meSpeed (presentation::AnimationSpeed_SLOW),\n mbActive (TRUE),\n mbDimPrevious (FALSE),\n mbIsMovie (FALSE),\n mbDimHide (FALSE),\n mbSoundOn (FALSE),\n mbPlayFull (FALSE),\n mpPathObj (NULL),\n meClickAction (presentation::ClickAction_NONE),\n meSecondEffect (presentation::AnimationEffect_NONE),\n meSecondSpeed (presentation::AnimationSpeed_SLOW),\n mbSecondSoundOn (FALSE),\n mbSecondPlayFull (FALSE),\n mnVerb (0),\n mnPresOrder (LIST_APPEND)\n{\n maBlueScreen = RGB_Color(COL_LIGHTMAGENTA);\n maDimColor = RGB_Color(COL_LIGHTGRAY);\n}\n\nSdAnimationInfo::SdAnimationInfo(const SdAnimationInfo& rAnmInfo)\n : SdrObjUserData (rAnmInfo),\n mePresObjKind (PRESOBJ_NONE),\n meEffect (rAnmInfo.meEffect),\n meTextEffect (rAnmInfo.meTextEffect),\n meSpeed (rAnmInfo.meSpeed),\n mbActive (rAnmInfo.mbActive),\n mbDimPrevious (rAnmInfo.mbDimPrevious),\n mbIsMovie (rAnmInfo.mbIsMovie),\n mbDimHide (rAnmInfo.mbDimHide),\n maBlueScreen (rAnmInfo.maBlueScreen),\n maDimColor (rAnmInfo.maDimColor),\n maSoundFile (rAnmInfo.maSoundFile),\n mbSoundOn (rAnmInfo.mbSoundOn),\n mbPlayFull (rAnmInfo.mbPlayFull),\n mpPathObj (NULL),\n meClickAction (rAnmInfo.meClickAction),\n meSecondEffect (rAnmInfo.meSecondEffect),\n meSecondSpeed (rAnmInfo.meSecondSpeed),\n maSecondSoundFile (rAnmInfo.maSecondSoundFile),\n mbSecondSoundOn (rAnmInfo.mbSecondSoundOn),\n mbSecondPlayFull (rAnmInfo.mbSecondPlayFull),\n maBookmark (rAnmInfo.maBookmark),\n mnVerb (rAnmInfo.mnVerb),\n mnPresOrder (LIST_APPEND)\n{\n \/\/ can not be copied\n if(meEffect == presentation::AnimationEffect_PATH)\n meEffect = presentation::AnimationEffect_NONE;\n}\n\n\nSdAnimationInfo::~SdAnimationInfo()\n{\n}\n\nSdrObjUserData* SdAnimationInfo::Clone(SdrObject*) const\n{\n return new SdAnimationInfo(*this);\n}\n<|endoftext|>"} {"text":"<commit_before>#include<stack>\n#include<iostream>\n#include<iomanip>\n#include<queue>\n#include <fstream>\n#include \"DiskManager.h\"\n#include \"Folder.h\"\n#include \"FileType.h\"\n#include \"Access.h\"\n#include \"FAT.h\"\n#include<direct.h>\n#include<io.h>\n\n\nconst string ACCESS[] = { \"只读\",\"可修改\",\"可执行\" };\nconst string rootPath = \"\/Users\/\";\nqueue<FCB*> persistQueue;\/\/持久化队列\nFAT fat;\nstring blocks[N];\nofstream *out = NULL;\nifstream *in = NULL;\n\n\nusing namespace std;\n\n\nvoid DiskManager::DiskWrite(File * file)\n{\n\t\/\/文件输出流\n\n\tprintf(\"%s\\n\", file->path.c_str());\n\n\t\/\/freopen(file->name.c_str(), \"w\", stdout);\n\n\tout = new ofstream(file->path.c_str());\n\tif (out->is_open())\n\t{\n\t\tout->close();\n\t}\n\n\t\/\/cout << \"hello world\" << endl;\n\n \/\/ fclose(stdout);\/\/关闭文件\n\n}\n\nbool DiskManager::DiskMkdir(string dirName)\n{\n\tprintf(\"%s\\n\",dirName.c_str());\n\treturn _mkdir(dirName.c_str()) == 0;\n\n\n}\n\nbool DiskManager::DiskRmdir(string dirName)\n{\n\t \n\treturn rmdir(dirName.c_str()) == 0;\n}\n\nbool DiskManager::DiskCkdir(string dirName)\n{\n\t\n\tif (_access(dirName.c_str(), 0) == -1)\n\t{\n\t\treturn _mkdir(dirName.c_str()) == 0;\n\t}\n\treturn false;\n}\n\nvoid DiskManager::DiskRmdir(Folder *f)\n{\n\t\/\/DFS删除\n\tfor (int i = 0; i < f->child.size(); i++) {\n\t\tif (f->child[i]->type == DOCUMENT) {\n\t\t\tprintf(\"%s\\n\", f->child[i]->path.c_str());\n\t\t\tremove(f->child[i]->path.c_str());\n\t\t\n\t\t}else {\n\t\t\tthis->DiskRmdir((Folder*)f->child[i]);\n\t\t}\n\t}\n\tprintf(\"%s\\n\", f->path.c_str());\n\tthis->DiskRmdir(f->path.c_str());\n}\n\nDiskManager::DiskManager()\n{\n\tfat.init(blocks);\n\t\n\t\n\n\troot = new Folder(rootPath,FileType::FOLDER);\n\troot->path = rootPath;\n\tthis->DiskMkdir(rootPath);\n\t\/\/设置磁盘根为目录\n\t\/\/设置根节点的父节点为自身\n\troot->father = root;\n\tcout << \"欢迎!!-----------您可输入help获得帮助------------\" << endl<< \"\\n[root@localhost \"+rootPath+\"]# \";\n\tstring opear,cmd;\n\twhile (cin >> cmd) \n\t{\n\t\t if (cmd == \"format\") {\n\t\t\tthis->format(blocks);\n\t\t}\n\t\telse if (cmd == \"mkdir\") {\n\t\t\tthis->Mkdir();\n\t\t}\n\t\telse if (cmd == \"rmdir\") {\n\t\t\tthis->Rmdir();\n\t\t}\n\t\telse if (cmd == \"ls\") {\n\t\t\tthis->ls();\n\t\t}\n\t\telse if (cmd == \"cd\") {\n\t\t\tthis->cd();\n\t\t}\n\t\telse if (cmd == \"create\") {\n\t\t\tthis->create();\n\t\t}\n\t\telse if (cmd == \"open\") {\n\t\t\tthis->open();\n\t\t}\n\t\telse if (cmd == \"close\") {\n\t\t\tthis->close();\n\t\t}\n\t\telse if (cmd == \"rm\") {\n\t\t\tthis->rm();\n\t\t}\n\t\telse if (cmd == \"exit\") {\n\t\t\tprintf(\"%s\\n\", \"再见!\");\n\t\t\tbreak;\n\t\t}\n\t\telse if(cmd==\"help\"){\n\t\t\tcout << \"\\n●format:对文件存储器进行格式化.\\n\"<<\n\t\t\t\t\"●mkdir:用于创建子目录\\n\" <<\n\t\t\t\t\"●rmdir : 用于删除子目录\\n\" <<\n\t\t\t\t\"●ls : 用于显示目录\\n\" <<\n\t\t\t\t\"●cd : 用于更改当前目录\\n\" <<\n\t\t\t\t\"●create : 用于创建文件\\n\" <<\n\t\t\t\t\"●open : 用于打开文件\\n\" <<\n\t\t\t\t\"●close : 用于关闭文件\\n\" <<\n\t\t\t\t\"●write : 用于写文件\\n\" <<\n\t\t\t\t\"●read : 用于读文件\\n\" <<\n\t\t\t\t\"●rm : 用于删除文件\\n\" <<\n\t\t\t\t\"●exit : 退出系统\\n\"\n\t\t\t\t<<endl;\n\t\t}\n\t\telse {\n\t\t\tcout << \"输入指令错误,请重新输入!!\" << endl;\n\t\t}\n\t\tcout << \"\\n[root@localhost \"+this->root->path+\" ]# \";\n\n\t}\n}\n\nDiskManager::~DiskManager()\n{\n\n}\n\nvoid DiskManager::format(string *blocks)\n{\n\tfat.init(blocks);\n\n\t\/\/回退到根目录\n\twhile (root->father != root) {\n\t\tthis->root = (Folder*)(this->root->father);\n\t}\n\n\t\n\tthis->DiskRmdir(this->root);\n\n\troot->child.clear();\n\n\tprintf(\"%s\\n\", \"磁盘格式化成功!\");\n}\n\nvoid DiskManager::Mkdir()\n{\n\tstring name;\n\tcin >> name;\n\n\tFolder *childFile = new Folder(name,FileType::FOLDER);\n\t\n\t\/\/设置父节点\n\tchildFile->father = (this->root);\n\tchildFile->path = this->root->path + name + \"\/\" ;\n\t\/\/判断是否文件重复\n\t\n\tif (this->root->count(childFile)) {\n\t\t\/\/文件重复报错\n\t\tcout << \"创建文件夹失败,文件夹名出现重复\" << endl;\n\t}else {\n\t\tcout << \"创建文件夹成功\" << endl;\n\t\tthis->DiskMkdir(childFile->path);\n\t\tthis->root->addChild(childFile);\n\n\t}\n}\n\nvoid DiskManager::Rmdir()\n{\n\tstring name;\n\tcin >> name;\n\tFolder *childFile =new Folder(name, FOLDER);\n\tchildFile = (Folder*) this->root->find(childFile);\n\tif (this->root->erase(childFile)) {\n\t\t\/\/文件重复报错\n\t\tthis->DiskRmdir(childFile);\n\t\tcout << \"删除文件夹成功\" << endl;\n\t}else {\n\t\tcout << \"无此文件夹 ,删除文件夹失败\" << endl;\n\t\t\n\t}\n}\n\nvoid DiskManager::ls()\n{\n\t\n\tcout << setw(10) << \"访问权限\"\n\t\t<< setw(20) <<\"文件大小\"\n\t\t<< setw(25) << \"修改日期\"\n\t\t<< setw(20) << \"文件名\"\n\t\t<< endl;\n\tint size = this->root->size();\n\t\n\tfor(int i= 0;i<size;i++)\n\t{\n\t\t\n\t\n\t\tcout << setw(10) << ACCESS[this->root->child[i]->access]\n\t\t\t<< setw(20) << (this->root->child[i]->type != FOLDER ? ((File*)this->root->child[i])->toString(blocks).size() : 4096)\n\t\t\t<< setw(25)<<this->root->child[i]->modifyDate\n\t\t\t<< setw(20)<<this->root->child[i]->name\n\t\t\t<<endl;\n\t\t\n\t}\n\t\n}\n\nvoid DiskManager::cd()\n{\n\tstring name;\n\tcin >> name;\n\tif (name == \"..\") {\n\t\tthis->root = (Folder*)(this->root->father);\n\t}\n\telse {\n\t\tif (this->root->count(new Folder(name, FOLDER))) {\n\t\t\t\n\t\t\tif (this->root->find(new Folder(name, FOLDER))->type != FOLDER)\n\t\t\t{\n\t\t\t\tcout << \"无此文件夹\" << endl;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\troot = (Folder*)this->root->find(new Folder(name, FOLDER));\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tcout << \"无此文件夹 \" << endl;\n\t\t}\n\t}\n\t\n}\n\nvoid DiskManager::create()\n{\n\tstring name;\n\tcin >> name;\n\t\n\tFile *childFile = new File( name, DOCUMENT,fat);\n\t\/\/设置父节点\n\tchildFile->father = (this->root);\n\tchildFile->path = this->root->path + name;\n\t\/\/判断是否文件重复\n\tif (this->root->count(childFile)) {\n\t\t\/\/文件重复报错\n\t\tcout << \"创建文件失败,文件名出现重复!!\" << endl;\n\t}\n\telse {\n\t\tcout << \"创建文件成功!\" << endl;\n\t\tthis->root->addChild(childFile);\n\t\tthis->DiskWrite(childFile);\n\t}\n}\n\nvoid DiskManager::open()\n{\n\tstring name,cmd;\n\tcin >> name;\n\t\n File * file = (File*)this->root->find(new File(name, DOCUMENT,fat));\n\tif (file!=NULL) {\n\t\t\n\t\tprintf(\"%s\\n\", \"文件读写流打开成功!\");\n\t\tcout << \"\\n[root@localhost \" + this->root->path + \" ]# \";\n\t\twhile (cin>>cmd) {\n\t\t\tcout << \"\\n[root@localhost \" + this->root->path + \" ]# \";\n\t\t\tif (cmd == \"write\") {\n\t\t\t\tthis->write(file->path.c_str(), file);\n\t\t\t}\n\t\t\telse if (cmd == \"read\") {\n\t\t\t\tthis->read(file->path.c_str());\n\t\t\t}\n\t\t\telse if (cmd == \"close\") {\n\t\t\t\tthis->close();\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\telse {\n\t\tprintf(\"%s\\n\", \"无法打开文件读写流,无此文件!\");\n\t}\n}\n\nvoid DiskManager::close()\n{\n\tif (out == NULL||in==NULL) {\n\t\tprintf(\"%s\\n\", \"无文件读写流需要关闭!\");\n\t}else {\n\t\tout->close();\n\t\tin->close();\n\t\tprintf(\"%s\\n\", \"文件读写流关闭成功!\");\n\t}\n}\n\nvoid DiskManager::write(const char *s, File* file)\n{\n\tstring content;\n\tcin >> content;\n\tif (in != NULL)in->close();\n\t\n\t\n\tfile->addContent(content.c_str(), blocks, fat);\/\/添加内容到文件中\n\n\tcontent = file->toString(blocks);\n\n\tout = new ofstream(s);\n\tif (out->is_open())\n\t{\n\t\t*out << content;\n\t}\n\tout->close();\n}\n\nvoid DiskManager::read(const char *s)\n{\n\tchar *content = new char[N];\n\tif (out != NULL)out->close();\n\tin = new ifstream(s);\n\tif (in->is_open())\n\t{\n\t\t*in >> content;\n\t}\n\tin->close();\n\tcout << content;\n\n}\n\nvoid DiskManager::rm()\n{\n\tstring name;\n\tcin >> name;\n\tFile *childFile = new File(name, DOCUMENT,fat);\n\tif (this->root->count(childFile)) {\n\t\t\/\/文件重复报错\n\t\tchildFile =(File*) this->root->find(childFile);\n\t\tremove(childFile->path.c_str());\n\t\tchildFile->release(fat,blocks);\n\t\tthis->root->erase(childFile);\n\t\t\n\t\tcout << \"删除文件成功!\" << endl;\n\t}\n\telse {\n\t\tcout << \"无此文件 ,删除文件失败\" << endl;\n\t}\n\n}\n<commit_msg>fix: import mkdir method<commit_after>#include<stack>\n#include<iostream>\n#include<iomanip>\n#include<queue>\n#include <fstream>\n#include \"DiskManager.h\"\n#include \"Folder.h\"\n#include \"FileType.h\"\n#include \"Access.h\"\n#include \"FAT.h\"\n\/\/#include<direct.h>\n#include <dirent.h>\n\/\/#include <io.h>\n#include <unistd.h>\n\n#include <sys\/types.h>\n#include <sys\/stat.h>\n\nconst string ACCESS[] = { \"只读\",\"可修改\",\"可执行\" };\nconst string rootPath = \"\/Users\/\";\nqueue<FCB*> persistQueue;\/\/持久化队列\nFAT fat;\nstring blocks[N];\nofstream *out = NULL;\nifstream *in = NULL;\n\n\nusing namespace std;\n\n\nvoid DiskManager::DiskWrite(File * file)\n{\n\t\/\/文件输出流\n\n\tprintf(\"%s\\n\", file->path.c_str());\n\n\t\/\/freopen(file->name.c_str(), \"w\", stdout);\n\n\tout = new ofstream(file->path.c_str());\n\tif (out->is_open())\n\t{\n\t\tout->close();\n\t}\n\n\t\/\/cout << \"hello world\" << endl;\n\n \/\/ fclose(stdout);\/\/关闭文件\n\n}\n\nbool DiskManager::DiskMkdir(string dirName)\n{\n\tprintf(\"%s\\n\",dirName.c_str());\n\treturn mkdir(dirName.c_str(),S_IRWXU) == 0;\n\n\n}\n\nbool DiskManager::DiskRmdir(string dirName)\n{\n\t \n\treturn rmdir(dirName.c_str()) == 0;\n}\n\nbool DiskManager::DiskCkdir(string dirName)\n{\n\t\n\tif (access(dirName.c_str(), 0) == -1)\n\t{\n return mkdir(dirName.c_str(),S_IRWXU) == 0;\n\t}\n\treturn false;\n}\n\nvoid DiskManager::DiskRmdir(Folder *f)\n{\n\t\/\/DFS删除\n\tfor (int i = 0; i < f->child.size(); i++) {\n\t\tif (f->child[i]->type == DOCUMENT) {\n\t\t\tprintf(\"%s\\n\", f->child[i]->path.c_str());\n\t\t\tremove(f->child[i]->path.c_str());\n\t\t\n\t\t}else {\n\t\t\tthis->DiskRmdir((Folder*)f->child[i]);\n\t\t}\n\t}\n\tprintf(\"%s\\n\", f->path.c_str());\n\tthis->DiskRmdir(f->path.c_str());\n}\n\nDiskManager::DiskManager()\n{\n\tfat.init(blocks);\n\t\n\t\n\n\troot = new Folder(rootPath,FileType::FOLDER);\n\troot->path = rootPath;\n\tthis->DiskMkdir(rootPath);\n\t\/\/设置磁盘根为目录\n\t\/\/设置根节点的父节点为自身\n\troot->father = root;\n\tcout << \"欢迎!!-----------您可输入help获得帮助------------\" << endl<< \"\\n[root@localhost \"+rootPath+\"]# \";\n\tstring opear,cmd;\n\twhile (cin >> cmd) \n\t{\n\t\t if (cmd == \"format\") {\n\t\t\tthis->format(blocks);\n\t\t}\n\t\telse if (cmd == \"mkdir\") {\n\t\t\tthis->Mkdir();\n\t\t}\n\t\telse if (cmd == \"rmdir\") {\n\t\t\tthis->Rmdir();\n\t\t}\n\t\telse if (cmd == \"ls\") {\n\t\t\tthis->ls();\n\t\t}\n\t\telse if (cmd == \"cd\") {\n\t\t\tthis->cd();\n\t\t}\n\t\telse if (cmd == \"create\") {\n\t\t\tthis->create();\n\t\t}\n\t\telse if (cmd == \"open\") {\n\t\t\tthis->open();\n\t\t}\n\t\telse if (cmd == \"close\") {\n\t\t\tthis->close();\n\t\t}\n\t\telse if (cmd == \"rm\") {\n\t\t\tthis->rm();\n\t\t}\n\t\telse if (cmd == \"exit\") {\n\t\t\tprintf(\"%s\\n\", \"再见!\");\n\t\t\tbreak;\n\t\t}\n\t\telse if(cmd==\"help\"){\n\t\t\tcout << \"\\n●format:对文件存储器进行格式化.\\n\"<<\n\t\t\t\t\"●mkdir:用于创建子目录\\n\" <<\n\t\t\t\t\"●rmdir : 用于删除子目录\\n\" <<\n\t\t\t\t\"●ls : 用于显示目录\\n\" <<\n\t\t\t\t\"●cd : 用于更改当前目录\\n\" <<\n\t\t\t\t\"●create : 用于创建文件\\n\" <<\n\t\t\t\t\"●open : 用于打开文件\\n\" <<\n\t\t\t\t\"●close : 用于关闭文件\\n\" <<\n\t\t\t\t\"●write : 用于写文件\\n\" <<\n\t\t\t\t\"●read : 用于读文件\\n\" <<\n\t\t\t\t\"●rm : 用于删除文件\\n\" <<\n\t\t\t\t\"●exit : 退出系统\\n\"\n\t\t\t\t<<endl;\n\t\t}\n\t\telse {\n\t\t\tcout << \"输入指令错误,请重新输入!!\" << endl;\n\t\t}\n\t\tcout << \"\\n[root@localhost \"+this->root->path+\" ]# \";\n\n\t}\n}\n\nDiskManager::~DiskManager()\n{\n\n}\n\nvoid DiskManager::format(string *blocks)\n{\n\tfat.init(blocks);\n\n\t\/\/回退到根目录\n\twhile (root->father != root) {\n\t\tthis->root = (Folder*)(this->root->father);\n\t}\n\n\t\n\tthis->DiskRmdir(this->root);\n\n\troot->child.clear();\n\n\tprintf(\"%s\\n\", \"磁盘格式化成功!\");\n}\n\nvoid DiskManager::Mkdir()\n{\n\tstring name;\n\tcin >> name;\n\n\tFolder *childFile = new Folder(name,FileType::FOLDER);\n\t\n\t\/\/设置父节点\n\tchildFile->father = (this->root);\n\tchildFile->path = this->root->path + name + \"\/\" ;\n\t\/\/判断是否文件重复\n\t\n\tif (this->root->count(childFile)) {\n\t\t\/\/文件重复报错\n\t\tcout << \"创建文件夹失败,文件夹名出现重复\" << endl;\n\t}else {\n\t\tcout << \"创建文件夹成功\" << endl;\n\t\tthis->DiskMkdir(childFile->path);\n\t\tthis->root->addChild(childFile);\n\n\t}\n}\n\nvoid DiskManager::Rmdir()\n{\n\tstring name;\n\tcin >> name;\n\tFolder *childFile =new Folder(name, FOLDER);\n\tchildFile = (Folder*) this->root->find(childFile);\n\tif (this->root->erase(childFile)) {\n\t\t\/\/文件重复报错\n\t\tthis->DiskRmdir(childFile);\n\t\tcout << \"删除文件夹成功\" << endl;\n\t}else {\n\t\tcout << \"无此文件夹 ,删除文件夹失败\" << endl;\n\t\t\n\t}\n}\n\nvoid DiskManager::ls()\n{\n\t\n\tcout << setw(10) << \"访问权限\"\n\t\t<< setw(20) <<\"文件大小\"\n\t\t<< setw(25) << \"修改日期\"\n\t\t<< setw(20) << \"文件名\"\n\t\t<< endl;\n\tint size = this->root->size();\n\t\n\tfor(int i= 0;i<size;i++)\n\t{\n\t\t\n\t\n\t\tcout << setw(10) << ACCESS[this->root->child[i]->access]\n\t\t\t<< setw(20) << (this->root->child[i]->type != FOLDER ? ((File*)this->root->child[i])->toString(blocks).size() : 4096)\n\t\t\t<< setw(25)<<this->root->child[i]->modifyDate\n\t\t\t<< setw(20)<<this->root->child[i]->name\n\t\t\t<<endl;\n\t\t\n\t}\n\t\n}\n\nvoid DiskManager::cd()\n{\n\tstring name;\n\tcin >> name;\n\tif (name == \"..\") {\n\t\tthis->root = (Folder*)(this->root->father);\n\t}\n\telse {\n\t\tif (this->root->count(new Folder(name, FOLDER))) {\n\t\t\t\n\t\t\tif (this->root->find(new Folder(name, FOLDER))->type != FOLDER)\n\t\t\t{\n\t\t\t\tcout << \"无此文件夹\" << endl;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\troot = (Folder*)this->root->find(new Folder(name, FOLDER));\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tcout << \"无此文件夹 \" << endl;\n\t\t}\n\t}\n\t\n}\n\nvoid DiskManager::create()\n{\n\tstring name;\n\tcin >> name;\n\t\n\tFile *childFile = new File( name, DOCUMENT,fat);\n\t\/\/设置父节点\n\tchildFile->father = (this->root);\n\tchildFile->path = this->root->path + name;\n\t\/\/判断是否文件重复\n\tif (this->root->count(childFile)) {\n\t\t\/\/文件重复报错\n\t\tcout << \"创建文件失败,文件名出现重复!!\" << endl;\n\t}\n\telse {\n\t\tcout << \"创建文件成功!\" << endl;\n\t\tthis->root->addChild(childFile);\n\t\tthis->DiskWrite(childFile);\n\t}\n}\n\nvoid DiskManager::open()\n{\n\tstring name,cmd;\n\tcin >> name;\n\t\n File * file = (File*)this->root->find(new File(name, DOCUMENT,fat));\n\tif (file!=NULL) {\n\t\t\n\t\tprintf(\"%s\\n\", \"文件读写流打开成功!\");\n\t\tcout << \"\\n[root@localhost \" + this->root->path + \" ]# \";\n\t\twhile (cin>>cmd) {\n\t\t\tcout << \"\\n[root@localhost \" + this->root->path + \" ]# \";\n\t\t\tif (cmd == \"write\") {\n\t\t\t\tthis->write(file->path.c_str(), file);\n\t\t\t}\n\t\t\telse if (cmd == \"read\") {\n\t\t\t\tthis->read(file->path.c_str());\n\t\t\t}\n\t\t\telse if (cmd == \"close\") {\n\t\t\t\tthis->close();\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\telse {\n\t\tprintf(\"%s\\n\", \"无法打开文件读写流,无此文件!\");\n\t}\n}\n\nvoid DiskManager::close()\n{\n\tif (out == NULL||in==NULL) {\n\t\tprintf(\"%s\\n\", \"无文件读写流需要关闭!\");\n\t}else {\n\t\tout->close();\n\t\tin->close();\n\t\tprintf(\"%s\\n\", \"文件读写流关闭成功!\");\n\t}\n}\n\nvoid DiskManager::write(const char *s, File* file)\n{\n\tstring content;\n\tcin >> content;\n\tif (in != NULL)in->close();\n\t\n\t\n\tfile->addContent(content.c_str(), blocks, fat);\/\/添加内容到文件中\n\n\tcontent = file->toString(blocks);\n\n\tout = new ofstream(s);\n\tif (out->is_open())\n\t{\n\t\t*out << content;\n\t}\n\tout->close();\n}\n\nvoid DiskManager::read(const char *s)\n{\n\tchar *content = new char[N];\n\tif (out != NULL)out->close();\n\tin = new ifstream(s);\n\tif (in->is_open())\n\t{\n\t\t*in >> content;\n\t}\n\tin->close();\n\tcout << content;\n\n}\n\nvoid DiskManager::rm()\n{\n\tstring name;\n\tcin >> name;\n\tFile *childFile = new File(name, DOCUMENT,fat);\n\tif (this->root->count(childFile)) {\n\t\t\/\/文件重复报错\n\t\tchildFile =(File*) this->root->find(childFile);\n\t\tremove(childFile->path.c_str());\n\t\tchildFile->release(fat,blocks);\n\t\tthis->root->erase(childFile);\n\t\t\n\t\tcout << \"删除文件成功!\" << endl;\n\t}\n\telse {\n\t\tcout << \"无此文件 ,删除文件失败\" << endl;\n\t}\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (C) 2017 Elviss Strazdins\n\/\/ This file is part of the Ouzel engine.\n\n#include \"core\/Setup.h\"\n\n#if OUZEL_PLATFORM_ANDROID && OUZEL_COMPILE_OPENGL\n\n#include \"RenderDeviceOGLAndroid.hpp\"\n#include \"core\/android\/WindowAndroid.hpp\"\n#include \"core\/Engine.hpp\"\n#include \"utils\/Log.hpp\"\n\nnamespace ouzel\n{\n namespace graphics\n {\n RenderDeviceOGLAndroid::~RenderDeviceOGLAndroid()\n {\n running = false;\n flushCommands();\n if (renderThread.joinable()) renderThread.join();\n\n if (context)\n {\n if (!eglMakeCurrent(display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT))\n {\n Log(Log::Level::ERR) << \"Failed to unset EGL context\";\n }\n\n if (!eglDestroyContext(display, context))\n {\n Log(Log::Level::ERR) << \"Failed to destroy EGL context\";\n }\n }\n\n if (surface)\n {\n if (!eglDestroySurface(display, surface))\n {\n Log(Log::Level::ERR) << \"Failed to destroy EGL surface\";\n }\n }\n\n if (display)\n {\n if (!eglTerminate(display))\n {\n Log(Log::Level::ERR) << \"Failed to terminate EGL\";\n }\n }\n }\n\n bool RenderDeviceOGLAndroid::init(Window* newWindow,\n const Size2&,\n uint32_t newSampleCount,\n Texture::Filter newTextureFilter,\n uint32_t newMaxAnisotropy,\n bool newVerticalSync,\n bool newDepth,\n bool newDebugRenderer)\n {\n display = eglGetDisplay(EGL_DEFAULT_DISPLAY);\n\n if (!display)\n {\n Log(Log::Level::ERR) << \"Failed to get display\";\n return false;\n }\n\n if (!eglInitialize(display, nullptr, nullptr))\n {\n Log(Log::Level::ERR) << \"Failed to initialize EGL\";\n return false;\n }\n\n const EGLint attributeList[] =\n {\n EGL_RED_SIZE, 8,\n EGL_GREEN_SIZE, 8,\n EGL_BLUE_SIZE, 8,\n EGL_ALPHA_SIZE, 8,\n EGL_DEPTH_SIZE, newDepth ? 24 : 0,\n EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT,\n EGL_SURFACE_TYPE, EGL_WINDOW_BIT,\n EGL_SAMPLE_BUFFERS, (newSampleCount > 1) ? 1 : 0,\n EGL_SAMPLES, static_cast<int>(newSampleCount),\n EGL_NONE\n };\n EGLConfig config;\n EGLint numConfig;\n if (!eglChooseConfig(display, attributeList, &config, 1, &numConfig))\n {\n Log(Log::Level::ERR) << \"Failed to choose EGL config\";\n return false;\n }\n\n if (!eglBindAPI(EGL_OPENGL_ES_API))\n {\n Log(Log::Level::ERR) << \"Failed to bind OpenGL ES API\";\n return false;\n }\n\n EGLint format;\n if (!eglGetConfigAttrib(display, config, EGL_NATIVE_VISUAL_ID, &format))\n {\n Log(Log::Level::ERR) << \"Failed to get config attribute \" << eglGetError();\n return false;\n }\n\n WindowAndroid* windowAndroid = static_cast<WindowAndroid*>(newWindow);\n\n ANativeWindow_setBuffersGeometry(windowAndroid->getNativeWindow(), 0, 0, format);\n\n surface = eglCreateWindowSurface(display, config, windowAndroid->getNativeWindow(), nullptr);\n if (surface == EGL_NO_SURFACE)\n {\n Log(Log::Level::ERR) << \"Failed to create EGL window surface\";\n return false;\n }\n\n for (EGLint version = 3; version >= 2; --version)\n {\n std::vector<EGLint> contextAttributes =\n {\n EGL_CONTEXT_CLIENT_VERSION, version\n };\n\n if (newDebugRenderer)\n {\n contextAttributes.push_back(EGL_CONTEXT_FLAGS_KHR);\n contextAttributes.push_back(EGL_CONTEXT_OPENGL_DEBUG_BIT_KHR);\n }\n\n contextAttributes.push_back(EGL_NONE);\n\n context = eglCreateContext(display, config, EGL_NO_CONTEXT, contextAttributes.data());\n\n if (context != EGL_NO_CONTEXT)\n {\n apiMajorVersion = version;\n apiMinorVersion = 0;\n Log(Log::Level::INFO) << \"EGL OpenGL ES \" << version << \" context created\";\n break;\n }\n }\n\n if (context == EGL_NO_CONTEXT)\n {\n Log(Log::Level::ERR) << \"Failed to create EGL context\";\n return false;\n }\n\n if (!eglMakeCurrent(display, surface, surface, context))\n {\n Log(Log::Level::ERR) << \"Failed to set current EGL context\";\n return false;\n }\n\n if (!eglSwapInterval(display, newVerticalSync ? 1 : 0))\n {\n Log(Log::Level::ERR) << \"Failed to set EGL frame interval\";\n return false;\n }\n\n EGLint surfaceWidth;\n EGLint surfaceHeight;\n\n if (!eglQuerySurface(display, surface, EGL_WIDTH, &surfaceWidth) ||\n !eglQuerySurface(display, surface, EGL_HEIGHT, &surfaceHeight))\n {\n Log(Log::Level::ERR) << \"Failed to get query window size \" << eglGetError();\n return false;\n }\n\n frameBufferWidth = surfaceWidth;\n frameBufferHeight = surfaceHeight;\n\n Size2 backBufferSize = Size2(static_cast<float>(frameBufferWidth),\n static_cast<float>(frameBufferHeight));\n\n newWindow->setSize(backBufferSize \/ newWindow->getContentScale());\n\n if (!RenderDeviceOGL::init(newWindow,\n backBufferSize,\n newSampleCount,\n newTextureFilter,\n newMaxAnisotropy,\n newVerticalSync,\n newDepth,\n newDebugRenderer))\n {\n return false;\n }\n\n if (!eglMakeCurrent(display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT))\n {\n Log(Log::Level::ERR) << \"Failed to unset EGL context\";\n }\n\n running = true;\n renderThread = std::thread(&RenderDeviceOGLAndroid::main, this);\n\n return true;\n }\n\n bool RenderDeviceOGLAndroid::reload()\n {\n running = false;\n flushCommands();\n if (renderThread.joinable()) renderThread.join();\n\n const EGLint attributeList[] =\n {\n EGL_RED_SIZE, 8,\n EGL_GREEN_SIZE, 8,\n EGL_BLUE_SIZE, 8,\n EGL_ALPHA_SIZE, 8,\n EGL_DEPTH_SIZE, depth ? 24 : 0,\n EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT,\n EGL_SURFACE_TYPE, EGL_WINDOW_BIT,\n EGL_SAMPLE_BUFFERS, (sampleCount > 1) ? 1 : 0,\n EGL_SAMPLES, static_cast<int>(sampleCount),\n EGL_NONE\n };\n EGLConfig config;\n EGLint numConfig;\n if (!eglChooseConfig(display, attributeList, &config, 1, &numConfig))\n {\n Log(Log::Level::ERR) << \"Failed to choose EGL config\";\n return false;\n }\n\n if (!eglBindAPI(EGL_OPENGL_ES_API))\n {\n Log(Log::Level::ERR) << \"Failed to bind OpenGL ES API\";\n return false;\n }\n\n EGLint format;\n if (!eglGetConfigAttrib(display, config, EGL_NATIVE_VISUAL_ID, &format))\n {\n Log(Log::Level::ERR) << \"Failed to get config attribute \" << eglGetError();\n return false;\n }\n\n WindowAndroid* windowAndroid = static_cast<WindowAndroid*>(sharedEngine->getWindow());\n\n ANativeWindow_setBuffersGeometry(windowAndroid->getNativeWindow(), 0, 0, format);\n\n surface = eglCreateWindowSurface(display, config, windowAndroid->getNativeWindow(), nullptr);\n if (surface == EGL_NO_SURFACE)\n {\n Log(Log::Level::ERR) << \"Failed to create EGL window surface\";\n return false;\n }\n\n for (EGLint version = 3; version >= 2; --version)\n {\n std::vector<EGLint> contextAttributes =\n {\n EGL_CONTEXT_CLIENT_VERSION, version\n };\n\n if (debugRenderer)\n {\n contextAttributes.push_back(EGL_CONTEXT_FLAGS_KHR);\n contextAttributes.push_back(EGL_CONTEXT_OPENGL_DEBUG_BIT_KHR);\n }\n\n contextAttributes.push_back(EGL_NONE);\n\n context = eglCreateContext(display, config, EGL_NO_CONTEXT, contextAttributes.data());\n\n if (context != EGL_NO_CONTEXT)\n {\n apiMajorVersion = version;\n apiMinorVersion = 0;\n Log(Log::Level::INFO) << \"EGL OpenGL ES \" << version << \" context created\";\n break;\n }\n }\n\n if (context == EGL_NO_CONTEXT)\n {\n Log(Log::Level::ERR) << \"Failed to create EGL context\";\n return false;\n }\n\n if (!eglMakeCurrent(display, surface, surface, context))\n {\n Log(Log::Level::ERR) << \"Failed to set current EGL context\";\n return false;\n }\n\n if (!eglSwapInterval(display, verticalSync ? 1 : 0))\n {\n Log(Log::Level::ERR) << \"Failed to set EGL frame interval\";\n return false;\n }\n\n EGLint surfaceWidth;\n EGLint surfaceHeight;\n\n if (!eglQuerySurface(display, surface, EGL_WIDTH, &surfaceWidth) ||\n !eglQuerySurface(display, surface, EGL_HEIGHT, &surfaceHeight))\n {\n Log(Log::Level::ERR) << \"Failed to get query window size \" << eglGetError();\n return false;\n }\n\n frameBufferWidth = surfaceWidth;\n frameBufferHeight = surfaceHeight;\n\n Size2 backBufferSize = Size2(static_cast<float>(frameBufferWidth),\n static_cast<float>(frameBufferHeight));\n\n windowAndroid->setSize(backBufferSize \/ windowAndroid->getContentScale());\n\n stateCache = StateCache();\n\n glDisable(GL_DITHER);\n glDepthFunc(GL_LEQUAL);\n\n if (checkOpenGLError())\n {\n Log(Log::Level::ERR) << \"Failed to set depth function\";\n return false;\n }\n\n {\n std::lock_guard<std::mutex> lock(resourceMutex);\n\n for (const std::unique_ptr<Resource>& resource : resources)\n {\n if (!resource->reload())\n {\n return false;\n }\n }\n }\n\n if (!eglMakeCurrent(display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT))\n {\n Log(Log::Level::ERR) << \"Failed to unset EGL context\";\n }\n\n running = true;\n renderThread = std::thread(&RenderDeviceOGLAndroid::main, this);\n\n return true;\n }\n\n bool RenderDeviceOGLAndroid::destroy()\n {\n running = false;\n flushCommands();\n if (renderThread.joinable()) renderThread.join();\n\n if (context)\n {\n if (!eglMakeCurrent(display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT))\n {\n Log(Log::Level::ERR) << \"Failed to unset EGL context\";\n }\n\n if (!eglDestroyContext(display, context))\n {\n Log(Log::Level::ERR) << \"Failed to destroy EGL context\";\n }\n\n context = nullptr;\n }\n\n if (surface)\n {\n if (!eglDestroySurface(display, surface))\n {\n Log(Log::Level::ERR) << \"Failed to destroy EGL surface\";\n }\n\n surface = nullptr;\n }\n\n return true;\n }\n\n bool RenderDeviceOGLAndroid::lockContext()\n {\n if (!eglMakeCurrent(display, surface, surface, context))\n {\n Log(Log::Level::ERR) << \"Failed to set current EGL context, error: \" << eglGetError();\n return false;\n }\n\n return true;\n }\n\n bool RenderDeviceOGLAndroid::swapBuffers()\n {\n if (eglSwapBuffers(display, surface) != EGL_TRUE)\n {\n Log(Log::Level::ERR) << \"Failed to swap buffers \" << eglGetError();\n return false;\n }\n\n return true;\n }\n\n void RenderDeviceOGLAndroid::main()\n {\n sharedEngine->setCurrentThreadName(\"Render\");\n\n while (running)\n {\n process();\n }\n\n if (!eglMakeCurrent(display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT))\n {\n Log(Log::Level::ERR) << \"Failed to unset EGL context, error: \" << eglGetError();\n }\n }\n } \/\/ namespace graphics\n} \/\/ namespace ouzel\n\n#endif\n<commit_msg>Fix Android build<commit_after>\/\/ Copyright (C) 2017 Elviss Strazdins\n\/\/ This file is part of the Ouzel engine.\n\n#include \"core\/Setup.h\"\n\n#if OUZEL_PLATFORM_ANDROID && OUZEL_COMPILE_OPENGL\n\n#include \"RenderDeviceOGLAndroid.hpp\"\n#include \"core\/android\/WindowAndroid.hpp\"\n#include \"core\/Engine.hpp\"\n#include \"utils\/Log.hpp\"\n\nnamespace ouzel\n{\n namespace graphics\n {\n RenderDeviceOGLAndroid::~RenderDeviceOGLAndroid()\n {\n running = false;\n flushCommands();\n if (renderThread.joinable()) renderThread.join();\n\n if (context)\n {\n if (!eglMakeCurrent(display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT))\n {\n Log(Log::Level::ERR) << \"Failed to unset EGL context\";\n }\n\n if (!eglDestroyContext(display, context))\n {\n Log(Log::Level::ERR) << \"Failed to destroy EGL context\";\n }\n }\n\n if (surface)\n {\n if (!eglDestroySurface(display, surface))\n {\n Log(Log::Level::ERR) << \"Failed to destroy EGL surface\";\n }\n }\n\n if (display)\n {\n if (!eglTerminate(display))\n {\n Log(Log::Level::ERR) << \"Failed to terminate EGL\";\n }\n }\n }\n\n bool RenderDeviceOGLAndroid::init(Window* newWindow,\n const Size2&,\n uint32_t newSampleCount,\n Texture::Filter newTextureFilter,\n uint32_t newMaxAnisotropy,\n bool newVerticalSync,\n bool newDepth,\n bool newDebugRenderer)\n {\n display = eglGetDisplay(EGL_DEFAULT_DISPLAY);\n\n if (!display)\n {\n Log(Log::Level::ERR) << \"Failed to get display\";\n return false;\n }\n\n if (!eglInitialize(display, nullptr, nullptr))\n {\n Log(Log::Level::ERR) << \"Failed to initialize EGL\";\n return false;\n }\n\n const EGLint attributeList[] =\n {\n EGL_RED_SIZE, 8,\n EGL_GREEN_SIZE, 8,\n EGL_BLUE_SIZE, 8,\n EGL_ALPHA_SIZE, 8,\n EGL_DEPTH_SIZE, newDepth ? 24 : 0,\n EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT,\n EGL_SURFACE_TYPE, EGL_WINDOW_BIT,\n EGL_SAMPLE_BUFFERS, (newSampleCount > 1) ? 1 : 0,\n EGL_SAMPLES, static_cast<int>(newSampleCount),\n EGL_NONE\n };\n EGLConfig config;\n EGLint numConfig;\n if (!eglChooseConfig(display, attributeList, &config, 1, &numConfig))\n {\n Log(Log::Level::ERR) << \"Failed to choose EGL config\";\n return false;\n }\n\n if (!eglBindAPI(EGL_OPENGL_ES_API))\n {\n Log(Log::Level::ERR) << \"Failed to bind OpenGL ES API\";\n return false;\n }\n\n EGLint format;\n if (!eglGetConfigAttrib(display, config, EGL_NATIVE_VISUAL_ID, &format))\n {\n Log(Log::Level::ERR) << \"Failed to get config attribute \" << eglGetError();\n return false;\n }\n\n WindowAndroid* windowAndroid = static_cast<WindowAndroid*>(newWindow);\n\n ANativeWindow_setBuffersGeometry(windowAndroid->getNativeWindow(), 0, 0, format);\n\n surface = eglCreateWindowSurface(display, config, windowAndroid->getNativeWindow(), nullptr);\n if (surface == EGL_NO_SURFACE)\n {\n Log(Log::Level::ERR) << \"Failed to create EGL window surface\";\n return false;\n }\n\n for (EGLint version = 3; version >= 2; --version)\n {\n std::vector<EGLint> contextAttributes =\n {\n EGL_CONTEXT_CLIENT_VERSION, version\n };\n\n if (newDebugRenderer)\n {\n contextAttributes.push_back(EGL_CONTEXT_FLAGS_KHR);\n contextAttributes.push_back(EGL_CONTEXT_OPENGL_DEBUG_BIT_KHR);\n }\n\n contextAttributes.push_back(EGL_NONE);\n\n context = eglCreateContext(display, config, EGL_NO_CONTEXT, contextAttributes.data());\n\n if (context != EGL_NO_CONTEXT)\n {\n apiMajorVersion = version;\n apiMinorVersion = 0;\n Log(Log::Level::INFO) << \"EGL OpenGL ES \" << version << \" context created\";\n break;\n }\n }\n\n if (context == EGL_NO_CONTEXT)\n {\n Log(Log::Level::ERR) << \"Failed to create EGL context\";\n return false;\n }\n\n if (!eglMakeCurrent(display, surface, surface, context))\n {\n Log(Log::Level::ERR) << \"Failed to set current EGL context\";\n return false;\n }\n\n if (!eglSwapInterval(display, newVerticalSync ? 1 : 0))\n {\n Log(Log::Level::ERR) << \"Failed to set EGL frame interval\";\n return false;\n }\n\n EGLint surfaceWidth;\n EGLint surfaceHeight;\n\n if (!eglQuerySurface(display, surface, EGL_WIDTH, &surfaceWidth) ||\n !eglQuerySurface(display, surface, EGL_HEIGHT, &surfaceHeight))\n {\n Log(Log::Level::ERR) << \"Failed to get query window size \" << eglGetError();\n return false;\n }\n\n frameBufferWidth = surfaceWidth;\n frameBufferHeight = surfaceHeight;\n\n Size2 backBufferSize = Size2(static_cast<float>(frameBufferWidth),\n static_cast<float>(frameBufferHeight));\n\n newWindow->setSize(backBufferSize);\n\n if (!RenderDeviceOGL::init(newWindow,\n backBufferSize,\n newSampleCount,\n newTextureFilter,\n newMaxAnisotropy,\n newVerticalSync,\n newDepth,\n newDebugRenderer))\n {\n return false;\n }\n\n if (!eglMakeCurrent(display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT))\n {\n Log(Log::Level::ERR) << \"Failed to unset EGL context\";\n }\n\n running = true;\n renderThread = std::thread(&RenderDeviceOGLAndroid::main, this);\n\n return true;\n }\n\n bool RenderDeviceOGLAndroid::reload()\n {\n running = false;\n flushCommands();\n if (renderThread.joinable()) renderThread.join();\n\n const EGLint attributeList[] =\n {\n EGL_RED_SIZE, 8,\n EGL_GREEN_SIZE, 8,\n EGL_BLUE_SIZE, 8,\n EGL_ALPHA_SIZE, 8,\n EGL_DEPTH_SIZE, depth ? 24 : 0,\n EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT,\n EGL_SURFACE_TYPE, EGL_WINDOW_BIT,\n EGL_SAMPLE_BUFFERS, (sampleCount > 1) ? 1 : 0,\n EGL_SAMPLES, static_cast<int>(sampleCount),\n EGL_NONE\n };\n EGLConfig config;\n EGLint numConfig;\n if (!eglChooseConfig(display, attributeList, &config, 1, &numConfig))\n {\n Log(Log::Level::ERR) << \"Failed to choose EGL config\";\n return false;\n }\n\n if (!eglBindAPI(EGL_OPENGL_ES_API))\n {\n Log(Log::Level::ERR) << \"Failed to bind OpenGL ES API\";\n return false;\n }\n\n EGLint format;\n if (!eglGetConfigAttrib(display, config, EGL_NATIVE_VISUAL_ID, &format))\n {\n Log(Log::Level::ERR) << \"Failed to get config attribute \" << eglGetError();\n return false;\n }\n\n WindowAndroid* windowAndroid = static_cast<WindowAndroid*>(sharedEngine->getWindow());\n\n ANativeWindow_setBuffersGeometry(windowAndroid->getNativeWindow(), 0, 0, format);\n\n surface = eglCreateWindowSurface(display, config, windowAndroid->getNativeWindow(), nullptr);\n if (surface == EGL_NO_SURFACE)\n {\n Log(Log::Level::ERR) << \"Failed to create EGL window surface\";\n return false;\n }\n\n for (EGLint version = 3; version >= 2; --version)\n {\n std::vector<EGLint> contextAttributes =\n {\n EGL_CONTEXT_CLIENT_VERSION, version\n };\n\n if (debugRenderer)\n {\n contextAttributes.push_back(EGL_CONTEXT_FLAGS_KHR);\n contextAttributes.push_back(EGL_CONTEXT_OPENGL_DEBUG_BIT_KHR);\n }\n\n contextAttributes.push_back(EGL_NONE);\n\n context = eglCreateContext(display, config, EGL_NO_CONTEXT, contextAttributes.data());\n\n if (context != EGL_NO_CONTEXT)\n {\n apiMajorVersion = version;\n apiMinorVersion = 0;\n Log(Log::Level::INFO) << \"EGL OpenGL ES \" << version << \" context created\";\n break;\n }\n }\n\n if (context == EGL_NO_CONTEXT)\n {\n Log(Log::Level::ERR) << \"Failed to create EGL context\";\n return false;\n }\n\n if (!eglMakeCurrent(display, surface, surface, context))\n {\n Log(Log::Level::ERR) << \"Failed to set current EGL context\";\n return false;\n }\n\n if (!eglSwapInterval(display, verticalSync ? 1 : 0))\n {\n Log(Log::Level::ERR) << \"Failed to set EGL frame interval\";\n return false;\n }\n\n EGLint surfaceWidth;\n EGLint surfaceHeight;\n\n if (!eglQuerySurface(display, surface, EGL_WIDTH, &surfaceWidth) ||\n !eglQuerySurface(display, surface, EGL_HEIGHT, &surfaceHeight))\n {\n Log(Log::Level::ERR) << \"Failed to get query window size \" << eglGetError();\n return false;\n }\n\n frameBufferWidth = surfaceWidth;\n frameBufferHeight = surfaceHeight;\n\n Size2 backBufferSize = Size2(static_cast<float>(frameBufferWidth),\n static_cast<float>(frameBufferHeight));\n\n windowAndroid->setSize(backBufferSize);\n\n stateCache = StateCache();\n\n glDisable(GL_DITHER);\n glDepthFunc(GL_LEQUAL);\n\n if (checkOpenGLError())\n {\n Log(Log::Level::ERR) << \"Failed to set depth function\";\n return false;\n }\n\n {\n std::lock_guard<std::mutex> lock(resourceMutex);\n\n for (const std::unique_ptr<Resource>& resource : resources)\n {\n if (!resource->reload())\n {\n return false;\n }\n }\n }\n\n if (!eglMakeCurrent(display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT))\n {\n Log(Log::Level::ERR) << \"Failed to unset EGL context\";\n }\n\n running = true;\n renderThread = std::thread(&RenderDeviceOGLAndroid::main, this);\n\n return true;\n }\n\n bool RenderDeviceOGLAndroid::destroy()\n {\n running = false;\n flushCommands();\n if (renderThread.joinable()) renderThread.join();\n\n if (context)\n {\n if (!eglMakeCurrent(display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT))\n {\n Log(Log::Level::ERR) << \"Failed to unset EGL context\";\n }\n\n if (!eglDestroyContext(display, context))\n {\n Log(Log::Level::ERR) << \"Failed to destroy EGL context\";\n }\n\n context = nullptr;\n }\n\n if (surface)\n {\n if (!eglDestroySurface(display, surface))\n {\n Log(Log::Level::ERR) << \"Failed to destroy EGL surface\";\n }\n\n surface = nullptr;\n }\n\n return true;\n }\n\n bool RenderDeviceOGLAndroid::lockContext()\n {\n if (!eglMakeCurrent(display, surface, surface, context))\n {\n Log(Log::Level::ERR) << \"Failed to set current EGL context, error: \" << eglGetError();\n return false;\n }\n\n return true;\n }\n\n bool RenderDeviceOGLAndroid::swapBuffers()\n {\n if (eglSwapBuffers(display, surface) != EGL_TRUE)\n {\n Log(Log::Level::ERR) << \"Failed to swap buffers \" << eglGetError();\n return false;\n }\n\n return true;\n }\n\n void RenderDeviceOGLAndroid::main()\n {\n sharedEngine->setCurrentThreadName(\"Render\");\n\n while (running)\n {\n process();\n }\n\n if (!eglMakeCurrent(display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT))\n {\n Log(Log::Level::ERR) << \"Failed to unset EGL context, error: \" << eglGetError();\n }\n }\n } \/\/ namespace graphics\n} \/\/ namespace ouzel\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\r\n#include \"Player.h\"\r\n\r\n#include \"NNAudioSystem.h\"\r\n#include \"NNNetworkSystem.h\"\r\n#include \"NNParticleSystem.h\"\r\n#include \"NNInputSystem.h\"\r\n#include \"NNApplication.h\"\r\n\r\n#include \"EffectManager.h\"\r\n#include \"ATypeEffect.h\"\r\n#include \"AUserEffect.h\"\r\n#include \"BTypeEffect.h\"\r\n#include \"BUserEffect.h\"\r\n#include \"CTypeEffect.h\"\r\n#include \"CUserEffect.h\"\r\n\r\nCPlayer::CPlayer( void )\r\n\t: m_PlayerSprite(NULL),m_MoveDirection(NNPoint(0,0)),\r\n\tm_Hp(100),m_RebirthDelayTime(10)\r\n{\r\n\tTransState(PlayerState::IDLE);\r\n\r\n\tm_PlayerUI = PlayerUI::Create();\r\n\tAddChild( m_PlayerUI );\r\n\r\n\tm_PlayerType = TYPE_A;\r\n\tmemset(m_SkillCount, 0, sizeof(m_SkillCount));\r\n\tmemset(m_SkillCooldown, 0, sizeof(m_SkillCooldown));\r\n}\r\n\r\nCPlayer::~CPlayer( void )\r\n{\r\n}\r\n\r\nvoid CPlayer::CreateSkillEffect(PlayerType type, PlayerState skillType)\r\n{\r\n\tswitch (type)\r\n\t{\r\n\tcase TYPE_A :\r\n\t\tif (skillType == TYPE_ACTIVE_SKILL) EffectManager::GetInstance()->AddEffect(new ATypeEffect(this));\r\n\t\tif (skillType == USER_ACTIVE_SKILL) EffectManager::GetInstance()->AddEffect(new AUserEffect(this));\r\n\t\tbreak;\r\n\r\n\tcase TYPE_B :\r\n\t\tif (skillType == TYPE_ACTIVE_SKILL) EffectManager::GetInstance()->AddEffect(new BTypeEffect(this));\r\n\t\tif (skillType == USER_ACTIVE_SKILL) EffectManager::GetInstance()->AddEffect(new BTypeEffect(this));\r\n\t\tbreak;\r\n\r\n\tcase TYPE_C :\r\n\t\tif (skillType == TYPE_ACTIVE_SKILL) EffectManager::GetInstance()->AddEffect(new CTypeEffect(this));\r\n\t\tif (skillType == USER_ACTIVE_SKILL) EffectManager::GetInstance()->AddEffect(new CTypeEffect(this));\r\n\t\tbreak;\r\n\t}\r\n}\r\nvoid CPlayer::TransState( PlayerState state )\r\n{\r\n\tfloat width = (float)NNApplication::GetInstance()->GetScreenWidth();\r\n\tfloat height = (float)NNApplication::GetInstance()->GetScreenHeight();\r\n\tfloat rotation = m_Rotation;\r\n\r\n\tm_PlayerState = state;\r\n\r\n\tif (m_PlayerSprite != NULL)\r\n\t{\r\n\t\tRemoveChild(m_PlayerSprite);\r\n\t}\r\n\r\n\tstd::wstring imagePath = L\"\";\r\n\r\n\tswitch (state)\r\n\t{\r\n\tcase IDLE:\r\n\t\timagePath = L\"Sprite\/idle_0.png\";\r\n\t\tbreak;\r\n\r\n\tcase WALK:\r\n\t\timagePath = L\"Sprite\/walk_0.png\";\r\n\t\tbreak;\r\n\r\n\tcase ATTAACK:\r\n\t\timagePath = L\"Sprite\/attack_0.png\";\r\n\r\n\t\t\/\/RemoveChild(m_BuffEffect);\r\n\r\n\t\t\/\/m_BuffEffect = NNParticleSystem::Create()\r\n\t\tbreak;\r\n\r\n\tcase DIE:\r\n\t\timagePath = L\"Sprite\/die.png\";\r\n\t\tm_RebirthTimer = NNLabel::Create(L\"~ ~ X 츮 غô\", L\" \", 40.f);\r\n\t\tm_RebirthTimer->SetCenter(width \/ 2, height \/ 2 - 200);\r\n\t\tbreak;\r\n\r\n\tcase USER_ACTIVE_SKILL:\r\n\t\timagePath = L\"Sprite\/skill_0.png\";\r\n\t\tif (GetSkillCooldown(USER_ACTIVE_SKILL) == false)\r\n\t\t{\r\n\t\t\tSetSkillCooldown(true, USER_ACTIVE_SKILL);\r\n\t\t\tCreateSkillEffect(m_PlayerType, USER_ACTIVE_SKILL);\r\n\t\t}\r\n\t\tbreak;\r\n\r\n\tcase TYPE_ACTIVE_SKILL:\r\n\t\timagePath = L\"Sprite\/skill_1.png\";\r\n\t\tif (GetSkillCooldown(TYPE_ACTIVE_SKILL) == false)\r\n\t\t{\r\n\t\t\tSetSkillCooldown(true, TYPE_ACTIVE_SKILL);\r\n\t\t\tCreateSkillEffect(m_PlayerType, TYPE_ACTIVE_SKILL);\r\n\t\t}\r\n\t\tbreak;\r\n\tdefault:\r\n\t\tbreak;\r\n\t}\r\n\r\n\t\/* Player Sprite Setting *\/\r\n\tm_PlayerSprite = NNSprite::Create( imagePath );\r\n\tAddChild( m_PlayerSprite );\r\n\r\n\tm_PlayerSprite->SetCenter( m_PlayerSprite->GetImageWidth()\/2.f, m_PlayerSprite->GetImageHeight()\/2.f );\r\n\t\/\/Sprite ٲٸ Rotation ڵ 0Ǵϱ ٽ \r\n\tm_PlayerSprite->SetRotation(rotation);\r\n\t\/* \/\/ *\/\r\n}\r\n\r\nvoid CPlayer::Update( float dTime )\r\n{\r\n\tNNObject::Update( dTime );\r\n\r\n\tm_PlayerUI->SetHP( m_Hp );\r\n\r\n\tswitch (m_PlayerState)\r\n\t{\r\n\tcase IDLE:\r\n\t\t{\r\n\t\t}\r\n\t\tbreak;\r\n\tcase WALK:\r\n\t\t{\r\n\t\t\t\/\/Move myPlayer with Game Key States.\r\n\t\t\t\/\/Check Moving Input, and set Position to d\r\n\t\t\tSetPosition( GetPosition() + m_MoveDirection * dTime * 100.f );\r\n\t\t\tbreak;\r\n\t\t}\r\n\tcase ATTAACK:\r\n\t\t{\r\n\t\t}\r\n\t\tbreak;\r\n\tcase DIE:\r\n\t\t{\r\n\t\t}\r\n\t\tbreak;\r\n\t\t\/\/ ų ߵ Ű ߰ by mooneegee\r\n\tcase USER_ACTIVE_SKILL:\r\n\t\t{\r\n\r\n\t\t}\r\n\t\tbreak;\r\n\tcase TYPE_ACTIVE_SKILL:\r\n\t\t{\r\n\r\n\t\t}\r\n\t\tbreak;\r\n\tdefault:\r\n\t\tbreak;\r\n\t}\r\n\r\n\t\/*\r\n\tfor (const auto& node : m_ChildList )\r\n\t{\r\n\t\tNNParticleSystem* temp = dynamic_cast<NNParticleSystem*>(node);\r\n\r\n\t\tif ( temp != NULL ) {\r\n\r\n\t\t}\r\n\t}\r\n\tfof;lkJSIf;lug 0v\r\n\t;'dlfjalfjwoefuaoiwnbSv r( *\/\r\n\t\/*\r\n\tm_ParticleSystemList.push_back(* );\r\n\tAd-*+++++++\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t\r\n\tjdkdkdkdfjfdiensk,cxnxcj,zwlhfisjfsdjsdl dkldjfeineifjdkfkjdlfjflvkd6ltjsguqdls2h5g2o2d295dl95didl6di1g9h8dl18d1l8tj8sdk1wale34hg8alwerjfl;askdji;woer fjoaisjkdlfhs;adjjjjjjjjjjjjjjj m dChild(* );\r\n\t\r\n\tfor (auto& iter=m_ParticleSystemList.begin(); iter!=m_ParticleSystemList.end(); iter++ )\r\n\t{\r\n\t\tif ((*iter)->IsAlive() == false)\r\n\t\t{\r\n\t\t\tRemoveChild( *iter );\r\n\t\t\titer = m_ParticleSystemList.erase( iter );\r\n\t\t\tif ( iter == m_ParticleSystemList.end() )\r\n\t\t\t{\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t}\r\n\t}*\/\r\n}\r\n\r\n\r\n\r\nvoid CPlayer::Render()\r\n{\r\n\tNNObject::Render();\r\n}\r\n<commit_msg>@ player.cpp code modified<commit_after>\r\n#include \"Player.h\"\r\n\r\n#include \"NNAudioSystem.h\"\r\n#include \"NNNetworkSystem.h\"\r\n#include \"NNParticleSystem.h\"\r\n#include \"NNInputSystem.h\"\r\n#include \"NNApplication.h\"\r\n#include \"NNAnimation.h\"\r\n\r\n#include \"EffectManager.h\"\r\n#include \"ATypeEffect.h\"\r\n#include \"AUserEffect.h\"\r\n#include \"BTypeEffect.h\"\r\n#include \"BUserEffect.h\"\r\n#include \"CTypeEffect.h\"\r\n#include \"CUserEffect.h\"\r\n\r\nCPlayer::CPlayer( void )\r\n\t: m_PlayerSprite(NULL),m_MoveDirection(NNPoint(0,0)),\r\n\tm_Hp(100),m_RebirthDelayTime(10)\r\n{\r\n\tTransState(PlayerState::IDLE);\r\n\r\n\tm_PlayerUI = PlayerUI::Create();\r\n\tAddChild( m_PlayerUI );\r\n\r\n\tm_PlayerType = TYPE_B;\r\n\tmemset(m_SkillCount, 0, sizeof(m_SkillCount));\r\n\tmemset(m_SkillCooldown, 0, sizeof(m_SkillCooldown));\r\n}\r\n\r\nCPlayer::~CPlayer( void )\r\n{\r\n}\r\n\r\nvoid CPlayer::CreateSkillEffect(PlayerType type, PlayerState skillType)\r\n{\r\n\tswitch (type)\r\n\t{\r\n\tcase TYPE_A :\r\n\t\tif (skillType == TYPE_ACTIVE_SKILL) EffectManager::GetInstance()->AddEffect(new ATypeEffect(this));\r\n\t\tif (skillType == USER_ACTIVE_SKILL) EffectManager::GetInstance()->AddEffect(new AUserEffect(this));\r\n\t\tbreak;\r\n\r\n\tcase TYPE_B :\r\n\t\tif (skillType == TYPE_ACTIVE_SKILL) EffectManager::GetInstance()->AddEffect(new BTypeEffect(this));\r\n\t\tif (skillType == USER_ACTIVE_SKILL) EffectManager::GetInstance()->AddEffect(new BTypeEffect(this));\r\n\t\tbreak;\r\n\r\n\tcase TYPE_C :\r\n\t\tif (skillType == TYPE_ACTIVE_SKILL) EffectManager::GetInstance()->AddEffect(new CTypeEffect(this));\r\n\t\tif (skillType == USER_ACTIVE_SKILL) EffectManager::GetInstance()->AddEffect(new CTypeEffect(this));\r\n\t\tbreak;\r\n\t}\r\n}\r\nvoid CPlayer::TransState( PlayerState state )\r\n{\r\n\tfloat width = (float)NNApplication::GetInstance()->GetScreenWidth();\r\n\tfloat height = (float)NNApplication::GetInstance()->GetScreenHeight();\r\n\tfloat rotation = m_Rotation;\r\n\r\n\tm_PlayerState = state;\r\n\r\n\tif (m_PlayerSprite != NULL)\r\n\t{\r\n\t\tRemoveChild(m_PlayerSprite);\r\n\t}\r\n\r\n\tstd::wstring imagePath = L\"\";\r\n\r\n\tswitch (state)\r\n\t{\r\n\tcase IDLE:\r\n\t\timagePath = L\"Sprite\/idle_0.png\";\r\n\t\tbreak;\r\n\r\n\tcase WALK:\r\n\t\timagePath = L\"Sprite\/walk_0.png\";\r\n\t\tbreak;\r\n\r\n\tcase ATTAACK:\r\n\t\timagePath = L\"Sprite\/attack_0.png\";\r\n\r\n\t\t\/\/RemoveChild(m_BuffEffect);\r\n\r\n\t\t\/\/m_BuffEffect = NNParticleSystem::Create()\r\n\t\tbreak;\r\n\r\n\tcase DIE:\r\n\t\timagePath = L\"Sprite\/die.png\";\r\n\t\tm_RebirthTimer = NNLabel::Create(L\"~ ~ X 츮 غô\", L\" \", 40.f);\r\n\t\tm_RebirthTimer->SetCenter(width \/ 2, height \/ 2 - 200);\r\n\t\tbreak;\r\n\r\n\tcase USER_ACTIVE_SKILL:\r\n\t\timagePath = L\"Sprite\/skill_0.png\";\r\n\t\tif (GetSkillCooldown(USER_ACTIVE_SKILL) == false)\r\n\t\t{\r\n\t\t\tSetSkillCooldown(true, USER_ACTIVE_SKILL);\r\n\t\t\tCreateSkillEffect(m_PlayerType, USER_ACTIVE_SKILL);\r\n\t\t}\r\n\t\tbreak;\r\n\r\n\tcase TYPE_ACTIVE_SKILL:\r\n\t\timagePath = L\"Sprite\/skill_1.png\";\r\n\t\tif (GetSkillCooldown(TYPE_ACTIVE_SKILL) == false)\r\n\t\t{\r\n\t\t\tSetSkillCooldown(true, TYPE_ACTIVE_SKILL);\r\n\t\t\tCreateSkillEffect(m_PlayerType, TYPE_ACTIVE_SKILL);\r\n\t\t}\r\n\t\tbreak;\r\n\tdefault:\r\n\t\tbreak;\r\n\t}\r\n\r\n\t\/* Player Sprite Setting *\/\r\n\tm_PlayerSprite = NNSprite::Create( imagePath );\r\n\tAddChild( m_PlayerSprite );\r\n\r\n\tm_PlayerSprite->SetCenter( m_PlayerSprite->GetImageWidth()\/2.f, m_PlayerSprite->GetImageHeight()\/2.f );\r\n\t\/\/Sprite ٲٸ Rotation ڵ 0Ǵϱ ٽ \r\n\tm_PlayerSprite->SetRotation(rotation);\r\n\t\/* \/\/ *\/\r\n}\r\n\r\nvoid CPlayer::Update( float dTime )\r\n{\r\n\tNNObject::Update( dTime );\r\n\r\n\tm_PlayerUI->SetHP( m_Hp );\r\n\r\n\tswitch (m_PlayerState)\r\n\t{\r\n\tcase IDLE:\r\n\t\t{\r\n\t\t}\r\n\t\tbreak;\r\n\tcase WALK:\r\n\t\t{\r\n\t\t\t\/\/Move myPlayer with Game Key States.\r\n\t\t\t\/\/Check Moving Input, and set Position to d\r\n\t\t\tSetPosition( GetPosition() + m_MoveDirection * dTime * 100.f );\r\n\t\t\tbreak;\r\n\t\t}\r\n\tcase ATTAACK:\r\n\t\t{\r\n\t\t}\r\n\t\tbreak;\r\n\tcase DIE:\r\n\t\t{\r\n\t\t}\r\n\t\tbreak;\r\n\t\t\/\/ ų ߵ Ű ߰ by mooneegee\r\n\tcase USER_ACTIVE_SKILL:\r\n\t\t{\r\n\r\n\t\t}\r\n\t\tbreak;\r\n\tcase TYPE_ACTIVE_SKILL:\r\n\t\t{\r\n\r\n\t\t}\r\n\t\tbreak;\r\n\tdefault:\r\n\t\tbreak;\r\n\t}\r\n\r\n\t\/*\r\n\tfor (const auto& node : m_ChildList )\r\n\t{\r\n\t\tNNParticleSystem* temp = dynamic_cast<NNParticleSystem*>(node);\r\n\r\n\t\tif ( temp != NULL ) {\r\n\r\n\t\t}\r\n\t}\r\n\tfof;lkJSIf;lug 0v\r\n\t;'dlfjalfjwoefuaoiwnbSv r( *\/\r\n\t\/*\r\n\tm_ParticleSystemList.push_back(* );\r\n\tAd-*+++++++\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t\r\n\tjdkdkdkdfjfdiensk,cxnxcj,zwlhfisjfsdjsdl dkldjfeineifjdkfkjdlfjflvkd6ltjsguqdls2h5g2o2d295dl95didl6di1g9h8dl18d1l8tj8sdk1wale34hg8alwerjfl;askdji;woer fjoaisjkdlfhs;adjjjjjjjjjjjjjjj m dChild(* );\r\n\t\r\n\tfor (auto& iter=m_ParticleSystemList.begin(); iter!=m_ParticleSystemList.end(); iter++ )\r\n\t{\r\n\t\tif ((*iter)->IsAlive() == false)\r\n\t\t{\r\n\t\t\tRemoveChild( *iter );\r\n\t\t\titer = m_ParticleSystemList.erase( iter );\r\n\t\t\tif ( iter == m_ParticleSystemList.end() )\r\n\t\t\t{\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t}\r\n\t}*\/\r\n}\r\n\r\n\r\n\r\nvoid CPlayer::Render()\r\n{\r\n\tNNObject::Render();\r\n}\r\n<|endoftext|>"} {"text":"<commit_before>\/\/ @Alan\n\/\/\n\/\/ Exercise 11.18:\n\/\/ Write the type of map_it from the loop on page 430 without using auto or decltype.\n\/\/\n\n#include <iostream>\n#include <map>\n#include <string>\n\nint main()\n{\n std::map<std::string, size_t> word_count;\n\n \/\/ the orignal codes:\n \/\/auto map_it = word_count.cbegin();\n\n\n std::map<std::string, size_t>::const_iterator map_it = word_count.cbegin();\n\/\/ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\/\/ the type ex11.18 required.\n\n \/\/ compare the current iterator to the off-the-end iterator\n while (map_it != word_count.cend())\n {\n \/\/ dereference the iterator to print the element key--value pairs\n std::cout << map_it->first << \" occurs \"\n << map_it->second << \" times\" << std::endl;\n ++map_it; \/\/ increment the iterator to denote the next element\n }\n\n return 0;\n}\n<commit_msg>Update ex11_18.cpp<commit_after>\/\/\n\/\/ @Yue Wang\n\/\/\n\/\/ Exercise 11.18:\n\/\/ Write the type of map_it from the loop on page 430 without using auto or decltype.\n\/\/ std::map<std::string, size_t>::const_iterator\n\/\/\n\nint main()\n{\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\n\/\/ g++ -std=c++11 -DSTANDALONE_TEST -L\/opt\/local\/lib chebyshev_cl.cpp -lOpenCL -lboost_system\n\/\/#include <cstdlib>\n#include \"chebyshev_cl.hpp\"\n\n\/\/ Print elements of vector to stdout\ntemplate<class T>\nvoid printvector(const T &v){\n for(int i=0;i<v.size();++i) {\n std::cout << v[i] << std::endl;\n }\n std::cout << std::endl;\n}\n\n\nChebyshev::Chebyshev(int n)\n : N(n), M(2 * N - 2),\n ctx(\n vex::Filter::Type(CL_DEVICE_TYPE_GPU) &&\n vex::Filter::DoublePrecision &&\n vex::Filter::Count(1)\n ),\n fft(ctx, M), ifft(ctx, M, vex::fft::inverse),\n cplx_ifft(ctx, M, vex::fft::inverse),\n sum(ctx),\n slice(vex::extents[M]),\n X2(ctx, M),\n w0(ctx, N),\n wi(ctx, N-2),\n wN(ctx, N)\n{\n dev_dvec k2(ctx, N);\n\n auto i = vex::tag<1>(vex::element_index());\n\n k2 = 2 * i * i;\n\n \/\/ 2,8,18,...,2*(N-2)^2,(N-1)^2\n k2[N - 1] = (N - 1) * (N - 1);\n\n coeff_to_nodal(k2,w0);\n w0 = w0 \/ (N - 1);\n\n w0[0] = 0.5 * w0[0];\n w0[N - 1] = 0.5 * w0[N - 1];\n\n wN = -vex::permutation(N - 1 - i)(w0);\n wi = 1 \/ ( sin(vex::constants::pi() * (i + 1) \/ (N - 1)) );\n}\n\n\n\n\nstd::string Chebyshev::get_device_name() {\n\n std::ostringstream os;\n\n \/\/ Write device name to output string stream\n os << ctx.queue(0);\n\n \/\/ extract string\n std::string devName = os.str();\n\n return devName;\n}\n\n\n\n\nvoid Chebyshev::catrev(const dev_dvec &a, dev_dvec &A2) {\n\n \/\/ First half of A2 holds a:\n slice[vex::range(0,N)](A2) = a;\n\n \/\/ Second half of A2 holds reversed copy of a (with endpoints removed):\n slice[vex::range(N, M)](A2) = vex::permutation( N - 2 - vex::element_index() )(A2);\n}\n\n\n\nhost_dvec Chebyshev::coeff_to_nodal(const host_dvec &a) {\n\n dev_dvec A(ctx, a);\n dev_dvec B(ctx, N);\n host_dvec b(N);\n coeff_to_nodal(A,B);\n vex::copy(B,b);\n return b;\n}\n\n\n\nvoid Chebyshev::coeff_to_nodal(const dev_dvec &a, dev_dvec &b) {\n\n catrev(a,X2);\n\n X2[0] = 2 * a[0];\n X2[N-1] = 2 * a[N-1];\n\n X2 = fft(X2) \/ 2;\n\n b = slice[vex::range(0,N)](X2);\n}\n\n\n\n\/\/ Compute Chebyshev expansion coefficient from grid values\nvoid Chebyshev::nodal_to_coeff(const dev_dvec &b, dev_dvec &a){\n\n catrev(b, X2);\n\n X2 = ifft(X2) * 2;\n\n a = slice[vex::range(0,N)](X2);\n\n a[0] = 0.5*a[0];\n a[N-1] = 0.5*a[N-1];\n\n}\n\nhost_dvec Chebyshev::nodal_to_coeff(const host_dvec &b) {\n\n dev_dvec B(ctx, b);\n dev_dvec A(ctx,N);\n host_dvec a(N);\n nodal_to_coeff(B,A);\n vex::copy(A,a);\n return a;\n}\n\n\n\/\/ Differentiate a function on the grid\nvoid Chebyshev::nodal_diff(const dev_dvec &u, dev_dvec &v){\n\n catrev(u,X2);\n\n \/\/ 0,1,...,N-1,-(N-1),-(N-2),...,-1\n VEX_FUNCTION(double, kkrev, (ptrdiff_t, N)(ptrdiff_t, i),\n if (i < N) return i;\n return -2 * N + i + 2;\n );\n\n X2 = fft(X2) * kkrev(N, vex::element_index());\n X2[N-1] = 0;\n\n \/\/ Extract imaginary part of vector\n VEX_FUNCTION(double, imag, (cl_double2, c),\n return c.y;\n );\n\n X2 = imag(cplx_ifft(X2));\n\n v[0] = sum(u*w0);\n\n slice[vex::range(1,N-1)](v) = slice[vex::range(1,N-1)](X2) * wi;\n\n v[N-1] = sum(wN*u);\n}\n\nhost_dvec Chebyshev::nodal_diff(const host_dvec &u) {\n\n dev_dvec U(ctx, u);\n dev_dvec V(ctx, N);\n\n host_dvec v(N);\n\n nodal_diff(U,V);\n\n vex::copy(V,v);\n return v;\n}\n\n\n\n\n#ifdef STANDALONE_TEST\nint main(int argc, char* argv[]) {\n\n int N = argc > 1 ? atoi(argv[1]) : 16;\n int k = argc > 2 ? atoi(argv[2]) : 0;\n\n try {\n Chebyshev cheb(N);\n std::cout << cheb.get_device_name() << std::endl;\n\n host_dvec a(N,0);\n a[k] = 1;\n\n auto b = cheb.coeff_to_nodal(a);\n auto bx = cheb.nodal_diff(b);\n auto c = cheb.nodal_to_coeff(bx);\n\n printvector(b);\n printvector(bx);\n\n } catch (const cl::Error &e) {\n std::cerr << \"OpenCL error: \" << e << std::endl;\n } catch (const std::exception &e) {\n std::cerr << \"Error: \" << e.what() << std::endl;\n }\n\n}\n#endif\n<commit_msg>Fix the misleading comment<commit_after>\n\/\/ g++ -std=c++11 -DSTANDALONE_TEST -L\/opt\/local\/lib chebyshev_cl.cpp -lOpenCL -lboost_system\n\/\/#include <cstdlib>\n#include \"chebyshev_cl.hpp\"\n\n\/\/ Print elements of vector to stdout\ntemplate<class T>\nvoid printvector(const T &v){\n for(int i=0;i<v.size();++i) {\n std::cout << v[i] << std::endl;\n }\n std::cout << std::endl;\n}\n\n\nChebyshev::Chebyshev(int n)\n : N(n), M(2 * N - 2),\n ctx(\n vex::Filter::Type(CL_DEVICE_TYPE_GPU) &&\n vex::Filter::DoublePrecision &&\n vex::Filter::Count(1)\n ),\n fft(ctx, M), ifft(ctx, M, vex::fft::inverse),\n cplx_ifft(ctx, M, vex::fft::inverse),\n sum(ctx),\n slice(vex::extents[M]),\n X2(ctx, M),\n w0(ctx, N),\n wi(ctx, N-2),\n wN(ctx, N)\n{\n dev_dvec k2(ctx, N);\n\n auto i = vex::tag<1>(vex::element_index());\n\n k2 = 2 * i * i;\n\n \/\/ 2,8,18,...,2*(N-2)^2,(N-1)^2\n k2[N - 1] = (N - 1) * (N - 1);\n\n coeff_to_nodal(k2,w0);\n w0 = w0 \/ (N - 1);\n\n w0[0] = 0.5 * w0[0];\n w0[N - 1] = 0.5 * w0[N - 1];\n\n wN = -vex::permutation(N - 1 - i)(w0);\n wi = 1 \/ ( sin(vex::constants::pi() * (i + 1) \/ (N - 1)) );\n}\n\n\n\n\nstd::string Chebyshev::get_device_name() {\n\n std::ostringstream os;\n\n \/\/ Write device name to output string stream\n os << ctx.queue(0);\n\n \/\/ extract string\n std::string devName = os.str();\n\n return devName;\n}\n\n\n\n\nvoid Chebyshev::catrev(const dev_dvec &a, dev_dvec &A2) {\n\n \/\/ First half of A2 holds a:\n slice[vex::range(0,N)](A2) = a;\n\n \/\/ Second half of A2 holds reversed copy of a (with endpoints removed):\n slice[vex::range(N, M)](A2) = vex::permutation( N - 2 - vex::element_index() )(A2);\n}\n\n\n\nhost_dvec Chebyshev::coeff_to_nodal(const host_dvec &a) {\n\n dev_dvec A(ctx, a);\n dev_dvec B(ctx, N);\n host_dvec b(N);\n coeff_to_nodal(A,B);\n vex::copy(B,b);\n return b;\n}\n\n\n\nvoid Chebyshev::coeff_to_nodal(const dev_dvec &a, dev_dvec &b) {\n\n catrev(a,X2);\n\n X2[0] = 2 * a[0];\n X2[N-1] = 2 * a[N-1];\n\n X2 = fft(X2) \/ 2;\n\n b = slice[vex::range(0,N)](X2);\n}\n\n\n\n\/\/ Compute Chebyshev expansion coefficient from grid values\nvoid Chebyshev::nodal_to_coeff(const dev_dvec &b, dev_dvec &a){\n\n catrev(b, X2);\n\n X2 = ifft(X2) * 2;\n\n a = slice[vex::range(0,N)](X2);\n\n a[0] = 0.5*a[0];\n a[N-1] = 0.5*a[N-1];\n\n}\n\nhost_dvec Chebyshev::nodal_to_coeff(const host_dvec &b) {\n\n dev_dvec B(ctx, b);\n dev_dvec A(ctx,N);\n host_dvec a(N);\n nodal_to_coeff(B,A);\n vex::copy(A,a);\n return a;\n}\n\n\n\/\/ Differentiate a function on the grid\nvoid Chebyshev::nodal_diff(const dev_dvec &u, dev_dvec &v){\n\n catrev(u,X2);\n\n \/\/ 0,1,...,N-1,-(N-2),...,-1\n VEX_FUNCTION(double, kkrev, (ptrdiff_t, N)(ptrdiff_t, i),\n if (i < N) return i;\n return -2 * N + i + 2;\n );\n\n X2 = fft(X2) * kkrev(N, vex::element_index());\n X2[N-1] = 0;\n\n \/\/ Extract imaginary part of vector\n VEX_FUNCTION(double, imag, (cl_double2, c),\n return c.y;\n );\n\n X2 = imag(cplx_ifft(X2));\n\n v[0] = sum(u*w0);\n\n slice[vex::range(1,N-1)](v) = slice[vex::range(1,N-1)](X2) * wi;\n\n v[N-1] = sum(wN*u);\n}\n\nhost_dvec Chebyshev::nodal_diff(const host_dvec &u) {\n\n dev_dvec U(ctx, u);\n dev_dvec V(ctx, N);\n\n host_dvec v(N);\n\n nodal_diff(U,V);\n\n vex::copy(V,v);\n return v;\n}\n\n\n\n\n#ifdef STANDALONE_TEST\nint main(int argc, char* argv[]) {\n\n int N = argc > 1 ? atoi(argv[1]) : 16;\n int k = argc > 2 ? atoi(argv[2]) : 0;\n\n try {\n Chebyshev cheb(N);\n std::cout << cheb.get_device_name() << std::endl;\n\n host_dvec a(N,0);\n a[k] = 1;\n\n auto b = cheb.coeff_to_nodal(a);\n auto bx = cheb.nodal_diff(b);\n auto c = cheb.nodal_to_coeff(bx);\n\n printvector(b);\n printvector(bx);\n\n } catch (const cl::Error &e) {\n std::cerr << \"OpenCL error: \" << e << std::endl;\n } catch (const std::exception &e) {\n std::cerr << \"Error: \" << e.what() << std::endl;\n }\n\n}\n#endif\n<|endoftext|>"} {"text":"<commit_before>#include <botan\/botan.h>\nusing namespace Botan;\n\n#include \"common.h\"\n#include <time.h>\n\n\/*\n Using clock() or similiar is bad news when using a hardware-based Engine,\n as all the stuff is offloaded and we use zero CPU time, which makes the\n benchmarks and such take forever.\n*\/\n\n#define USE_CLOCK 0\n#define USE_TIMES 0\n#define USE_POSIX_GETTIME 0\n#define USE_RDTSC 1\n\n\/* If using USE_RDTSC, set to your CPU's Mhz *\/\n#define CPU_MHZ 2400\n\n#if USE_CLOCK\n\n u64bit get_clock() { return clock(); }\n u64bit get_ticks() { return CLOCKS_PER_SEC; }\n\n#elif USE_TIMES\n\n #include <sys\/times.h>\n #include <unistd.h>\n u64bit get_clock() { return times(0); }\n u64bit get_ticks() { return sysconf(_SC_CLK_TCK); }\n\n#elif USE_POSIX_GETTIME\n\nu64bit get_clock()\n {\n struct timespec tv;\n clock_gettime(CLOCK_REALTIME, &tv);\n\n return (tv.tv_sec * 1000000000 + tv.tv_nsec) \/ 1000;\n }\n\nu64bit get_ticks() { return 1000000; }\n#elif USE_RDTSC\n\n u64bit get_clock()\n {\n u64bit rtc = 0;\n u32bit rtc_low = 0, rtc_high = 0;\n asm volatile(\"rdtsc\" : \"=d\" (rtc_high), \"=a\" (rtc_low));\n rtc = ((u64bit)rtc_high << 32) | rtc_low;\n return rtc \/ 1000;\n }\n\n u64bit get_ticks() { return CPU_MHZ * 1000; }\n#else\n #error \"Must choose a timing method!\"\n#endif\n<commit_msg>Default to using clock(), not rdtsc<commit_after>#include <botan\/botan.h>\nusing namespace Botan;\n\n#include \"common.h\"\n#include <time.h>\n\n\/*\n Using clock() or similiar is bad news when using a hardware-based Engine,\n as all the stuff is offloaded and we use zero CPU time, which makes the\n benchmarks and such take forever.\n*\/\n\n#define USE_CLOCK 1\n#define USE_TIMES 0\n#define USE_POSIX_GETTIME 0\n#define USE_RDTSC 0\n\n\/* If using USE_RDTSC, set to your CPU's Mhz *\/\n#define CPU_MHZ 2400\n\n#if USE_CLOCK\n\n u64bit get_clock() { return clock(); }\n u64bit get_ticks() { return CLOCKS_PER_SEC; }\n\n#elif USE_TIMES\n\n #include <sys\/times.h>\n #include <unistd.h>\n u64bit get_clock() { return times(0); }\n u64bit get_ticks() { return sysconf(_SC_CLK_TCK); }\n\n#elif USE_POSIX_GETTIME\n\nu64bit get_clock()\n {\n struct timespec tv;\n clock_gettime(CLOCK_REALTIME, &tv);\n\n return (tv.tv_sec * 1000000000 + tv.tv_nsec) \/ 1000;\n }\n\nu64bit get_ticks() { return 1000000; }\n#elif USE_RDTSC\n\n u64bit get_clock()\n {\n u64bit rtc = 0;\n u32bit rtc_low = 0, rtc_high = 0;\n asm volatile(\"rdtsc\" : \"=d\" (rtc_high), \"=a\" (rtc_low));\n rtc = ((u64bit)rtc_high << 32) | rtc_low;\n return rtc \/ 1000;\n }\n\n u64bit get_ticks() { return CPU_MHZ * 1000; }\n#else\n #error \"Must choose a timing method!\"\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/*\n Copyright (c) 2011, The Cinder Project, All rights reserved.\n This code is intended for use with the Cinder C++ library: http:\/\/libcinder.org\n\n Based on the sc-Choreograph CinderBlock by David Wicks: http:\/\/sansumbrella.com\/\n\n Redistribution and use in source and binary forms, with or without modification, are permitted provided that\n the following conditions are met:\n\n * Redistributions of source code must retain the above copyright notice, this list of conditions and\n\tthe following disclaimer.\n * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and\n\tthe following disclaimer in the documentation and\/or other materials provided with the distribution.\n\n THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED\n WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A\n PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR\n ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED\n TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n POSSIBILITY OF SUCH DAMAGE.\n*\/\n\n#include \"cinder\/TimelineItem.h\"\n#include \"cinder\/Timeline.h\"\n#include \"cinder\/CinderMath.h\"\n\t\nnamespace cinder {\n\nTimelineItem::TimelineItem( class Timeline *parent )\n\t: mParent( parent ), mTarget( 0 ), mStartTime( 0 ), mDirtyDuration( false ), mDuration( 0 ), mInvDuration( 0 ), mHasStarted( false ), mHasReverseStarted( false ),\n\t\tmComplete( false ), mReverseComplete( false ), mMarkedForRemoval( false ), mAutoRemove( true ),\n\t\tmInfinite( false ), mLoop( false ), mPingPong( false ), mLastLoopIteration( -1 ), mUseAbsoluteTime( false )\n{\n}\n\nTimelineItem::TimelineItem( Timeline *parent, void *target, float startTime, float duration )\n\t: mParent( parent ), mTarget( target ), mStartTime( startTime ), mDirtyDuration( false ), mDuration( std::max( duration, 0.0f ) ), mInvDuration( duration <= 0 ? 0 : (1 \/ duration) ),\n\t\tmHasStarted( false ), mHasReverseStarted( false ), mComplete( false ), mReverseComplete( false ), mMarkedForRemoval( false ), mAutoRemove( true ),\n\t\tmInfinite( false ), mLoop( false ), mPingPong( false ), mLastLoopIteration( -1 ), mUseAbsoluteTime( false )\n{\n}\n\nvoid TimelineItem::removeSelf()\n{\n\tmMarkedForRemoval = true;\n}\n\nvoid TimelineItem::stepTo( float newTime, bool reverse )\n{\n\tif( mMarkedForRemoval )\n\t\treturn;\n\t\n\tconst float absTime = newTime - mStartTime;\n\tconst float endTime = mStartTime + mDuration;\n\n\tupdateDuration();\n\n\tif( ( ! mHasReverseStarted ) && reverse && ( newTime < mStartTime ) ) {\n\t\t\/\/ first update the current time to be the start time\n\t\tupdate( ( mUseAbsoluteTime ) ? mStartTime : 0 );\n\t\t\/\/ then issue reverse start\n\t\tmHasReverseStarted = true;\n\t\tmHasStarted = false;\n\t\tstart( true );\n\t}\t\n\telse if( newTime >= mStartTime ) {\n\t\tfloat relTime;\n\t\tif( mPingPong ) {\n\t\t\trelTime = math<float>::fmod( absTime * mInvDuration, 2 ); \/\/ varies from 0-2\n\t\t\tif( relTime > 1 )\n\t\t\t\trelTime = ( 2 - relTime );\n\t\t}\n\t\telse if( mLoop ) {\n\t\t\trelTime = math<float>::fmod( absTime * mInvDuration, 1 );\n\t\t}\n\t\telse\n\t\t\trelTime = math<float>::min( absTime * mInvDuration, 1 );\n\t\t\n\t\tif( ( ! mHasStarted ) && ( ! reverse ) ) {\n\t\t\tmHasStarted = true;\n\t\t\tmHasReverseStarted = false;\n\t\t\tmLastLoopIteration = 0;\n\t\t\tloopStart();\n\t\t\tstart( false );\n\t\t}\n\t\t\n\t\tfloat time = ( mUseAbsoluteTime ) ? absTime : relTime;\n\n\t\t\/\/ accommodate a tween with a duration <= 0\n\t\tif( ( ! mUseAbsoluteTime ) && ( mInvDuration <= 0 ) )\n\t\t\ttime = 1.0f;\n\n\t\tif( mLoop || mPingPong ) {\n\t\t\tint32_t loopIteration = static_cast<int32_t>( ( newTime - mStartTime ) * mInvDuration );\n\t\t\tif( loopIteration != mLastLoopIteration ) {\n\t\t\t\tmLastLoopIteration = loopIteration;\n\t\t\t\tloopStart();\n\t\t\t\tupdate( time );\n\t\t\t}\n\t\t\telse\n\t\t\t\tupdate( time );\n\t\t}\n\t\telse\n\t\t\tupdate( time );\n\t}\n\n\tif( newTime < endTime ) {\n\t\tif( ( ! mReverseComplete ) && reverse ) {\n\t\t\tmReverseComplete = true;\n\t\t\tmComplete = false;\n\t\t\tcomplete( true );\n\t\t}\n\t}\n\telse if( ( ! mLoop ) && ( ! mInfinite ) ) { \/\/ newTime >= endTime\n\t\tif( ( ! mComplete ) && ( ! reverse ) ) {\n\t\t\tmComplete = true;\n\t\t\tmReverseComplete = false;\n\t\t\tcomplete( false );\n\t\t}\n\t}\n}\n\nvoid TimelineItem::setStartTime( float time )\n{\n\tmStartTime = time;\n\tif( mParent )\n\t\tmParent->itemTimeChanged( this );\n}\n\nvoid TimelineItem::updateDuration() const\n{\n\tif( mDirtyDuration ) {\n\t\tmDuration = std::max( calcDuration(), 0.0f );\n\t\tmInvDuration = ( mDuration == 0 ) ? 1.0f : ( 1.0f \/ mDuration );\n\t\tmDirtyDuration = false;\n\t}\n}\n\nvoid TimelineItem::setDuration( float duration )\n{\n\tmDuration = duration;\n\tmInvDuration = duration == 0 ? 1 : ( 1 \/ duration );\n\tif( mParent )\n\t\tmParent->itemTimeChanged( this );\n}\n\nfloat TimelineItem::loopTime( float absTime )\n{\n\tfloat result = absTime;\n\t\n\tif( mPingPong ) {\n\t\tresult = math<float>::fmod( result * mInvDuration, 2 ); \/\/ varies from 0-2\n\t\tif( result <= 1 )\n\t\t\tresult *= mDuration;\n\t\telse\n\t\t\tresult = ( 2 - result ) * mDuration;\n\t}\n\telse if( mLoop ) {\n\t\tresult = math<float>::fmod( result * mInvDuration, 1 );\n\t\tresult *= mDuration;\n\t}\n\n\treturn result;\n}\n\n} \/\/ namespace cinder<commit_msg>Fix Timeline::isComplete immediately after changes<commit_after>\/*\n Copyright (c) 2011, The Cinder Project, All rights reserved.\n This code is intended for use with the Cinder C++ library: http:\/\/libcinder.org\n\n Based on the sc-Choreograph CinderBlock by David Wicks: http:\/\/sansumbrella.com\/\n\n Redistribution and use in source and binary forms, with or without modification, are permitted provided that\n the following conditions are met:\n\n * Redistributions of source code must retain the above copyright notice, this list of conditions and\n\tthe following disclaimer.\n * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and\n\tthe following disclaimer in the documentation and\/or other materials provided with the distribution.\n\n THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED\n WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A\n PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR\n ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED\n TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n POSSIBILITY OF SUCH DAMAGE.\n*\/\n\n#include \"cinder\/TimelineItem.h\"\n#include \"cinder\/Timeline.h\"\n#include \"cinder\/CinderMath.h\"\n\t\nnamespace cinder {\n\nTimelineItem::TimelineItem( class Timeline *parent )\n\t: mParent( parent ), mTarget( 0 ), mStartTime( 0 ), mDirtyDuration( false ), mDuration( 0 ), mInvDuration( 0 ), mHasStarted( false ), mHasReverseStarted( false ),\n\t\tmComplete( false ), mReverseComplete( false ), mMarkedForRemoval( false ), mAutoRemove( true ),\n\t\tmInfinite( false ), mLoop( false ), mPingPong( false ), mLastLoopIteration( -1 ), mUseAbsoluteTime( false )\n{\n}\n\nTimelineItem::TimelineItem( Timeline *parent, void *target, float startTime, float duration )\n\t: mParent( parent ), mTarget( target ), mStartTime( startTime ), mDirtyDuration( false ), mDuration( std::max( duration, 0.0f ) ), mInvDuration( duration <= 0 ? 0 : (1 \/ duration) ),\n\t\tmHasStarted( false ), mHasReverseStarted( false ), mComplete( false ), mReverseComplete( false ), mMarkedForRemoval( false ), mAutoRemove( true ),\n\t\tmInfinite( false ), mLoop( false ), mPingPong( false ), mLastLoopIteration( -1 ), mUseAbsoluteTime( false )\n{\n}\n\nvoid TimelineItem::removeSelf()\n{\n\tmMarkedForRemoval = true;\n}\n\nvoid TimelineItem::stepTo( float newTime, bool reverse )\n{\n\tif( mMarkedForRemoval )\n\t\treturn;\n\n\tupdateDuration();\n\n\tconst float absTime = newTime - mStartTime;\n\tconst float endTime = mStartTime + mDuration;\n\n\tif( ( ! mHasReverseStarted ) && reverse && ( newTime < mStartTime ) ) {\n\t\t\/\/ first update the current time to be the start time\n\t\tupdate( ( mUseAbsoluteTime ) ? mStartTime : 0 );\n\t\t\/\/ then issue reverse start\n\t\tmHasReverseStarted = true;\n\t\tmHasStarted = false;\n\t\tstart( true );\n\t}\t\n\telse if( newTime >= mStartTime ) {\n\t\tfloat relTime;\n\t\tif( mPingPong ) {\n\t\t\trelTime = math<float>::fmod( absTime * mInvDuration, 2 ); \/\/ varies from 0-2\n\t\t\tif( relTime > 1 )\n\t\t\t\trelTime = ( 2 - relTime );\n\t\t}\n\t\telse if( mLoop ) {\n\t\t\trelTime = math<float>::fmod( absTime * mInvDuration, 1 );\n\t\t}\n\t\telse\n\t\t\trelTime = math<float>::min( absTime * mInvDuration, 1 );\n\t\t\n\t\tif( ( ! mHasStarted ) && ( ! reverse ) ) {\n\t\t\tmHasStarted = true;\n\t\t\tmHasReverseStarted = false;\n\t\t\tmLastLoopIteration = 0;\n\t\t\tloopStart();\n\t\t\tstart( false );\n\t\t}\n\t\t\n\t\tfloat time = ( mUseAbsoluteTime ) ? absTime : relTime;\n\n\t\t\/\/ accommodate a tween with a duration <= 0\n\t\tif( ( ! mUseAbsoluteTime ) && ( mInvDuration <= 0 ) )\n\t\t\ttime = 1.0f;\n\n\t\tif( mLoop || mPingPong ) {\n\t\t\tint32_t loopIteration = static_cast<int32_t>( ( newTime - mStartTime ) * mInvDuration );\n\t\t\tif( loopIteration != mLastLoopIteration ) {\n\t\t\t\tmLastLoopIteration = loopIteration;\n\t\t\t\tloopStart();\n\t\t\t\tupdate( time );\n\t\t\t}\n\t\t\telse\n\t\t\t\tupdate( time );\n\t\t}\n\t\telse\n\t\t\tupdate( time );\n\t}\n\n\tif( newTime < endTime ) {\n\t\tif( ( ! mReverseComplete ) && reverse ) {\n\t\t\tmReverseComplete = true;\n\t\t\tmComplete = false;\n\t\t\tcomplete( true );\n\t\t}\n\t}\n\telse if( ( ! mLoop ) && ( ! mInfinite ) ) { \/\/ newTime >= endTime\n\t\tif( ( ! mComplete ) && ( ! reverse ) ) {\n\t\t\tmComplete = true;\n\t\t\tmReverseComplete = false;\n\t\t\tcomplete( false );\n\t\t}\n\t}\n}\n\nvoid TimelineItem::setStartTime( float time )\n{\n\tmStartTime = time;\n\tif( mParent )\n\t\tmParent->itemTimeChanged( this );\n}\n\nvoid TimelineItem::updateDuration() const\n{\n\tif( mDirtyDuration ) {\n\t\tmDuration = std::max( calcDuration(), 0.0f );\n\t\tmInvDuration = ( mDuration == 0 ) ? 1.0f : ( 1.0f \/ mDuration );\n\t\tmDirtyDuration = false;\n\t}\n}\n\nvoid TimelineItem::setDuration( float duration )\n{\n\tmDuration = duration;\n\tmInvDuration = duration == 0 ? 1 : ( 1 \/ duration );\n\tif( mParent )\n\t\tmParent->itemTimeChanged( this );\n}\n\nfloat TimelineItem::loopTime( float absTime )\n{\n\tfloat result = absTime;\n\t\n\tif( mPingPong ) {\n\t\tresult = math<float>::fmod( result * mInvDuration, 2 ); \/\/ varies from 0-2\n\t\tif( result <= 1 )\n\t\t\tresult *= mDuration;\n\t\telse\n\t\t\tresult = ( 2 - result ) * mDuration;\n\t}\n\telse if( mLoop ) {\n\t\tresult = math<float>::fmod( result * mInvDuration, 1 );\n\t\tresult *= mDuration;\n\t}\n\n\treturn result;\n}\n\n} \/\/ namespace cinder\n<|endoftext|>"} {"text":"<commit_before>\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ Peloton\n\/\/\n\/\/ aggregation.cpp\n\/\/\n\/\/ Identification: src\/codegen\/aggregation.cpp\n\/\/\n\/\/ Copyright (c) 2015-17, Carnegie Mellon University Database Group\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"codegen\/aggregation.h\"\n#include \"codegen\/if.h\"\n#include \"codegen\/type.h\"\n\nnamespace peloton {\nnamespace codegen {\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ Setup the aggregation storage format given the aggregates the caller wants to\n\/\/ store.\n\/\/===----------------------------------------------------------------------===\/\/\nvoid Aggregation::Setup(\n CodeGen &codegen,\n const std::vector<planner::AggregatePlan::AggTerm> &aggregates) {\n \/\/ Collect the types so we can configure the updateable storage's format\n bool needs_group_count = false;\n bool tracks_group_count = false;\n for (uint32_t i = 0; i < aggregates.size(); i++) {\n const auto agg_term = aggregates[i];\n \/\/ Defense > Offense ?\n PL_ASSERT(agg_term.agg_ai.type != type::Type::TypeId::INVALID);\n\n needs_group_count |= agg_term.aggtype == ExpressionType::AGGREGATE_AVG;\n tracks_group_count |=\n agg_term.aggtype == ExpressionType::AGGREGATE_COUNT_STAR;\n }\n\n \/\/ Add the count(*) aggregate first, if we need to\n if (tracks_group_count || needs_group_count) {\n uint32_t storage_pos = storage_.AddType(type::Type::TypeId::BIGINT);\n AggregateInfo count_agg{\n ExpressionType::AGGREGATE_COUNT_STAR, type::Type::TypeId::BIGINT,\n std::numeric_limits<uint32_t>::max(), storage_pos, true};\n aggregate_infos_.push_back(count_agg);\n }\n\n \/\/ Add the rest\n for (uint32_t source_idx = 0; source_idx < aggregates.size(); source_idx++) {\n const auto agg_term = aggregates[source_idx];\n switch (agg_term.aggtype) {\n case ExpressionType::AGGREGATE_COUNT: {\n \/\/ We're counting instances ... use BIGINT for the count\n const auto count_type = type::Type::TypeId::BIGINT;\n uint32_t storage_pos = storage_.AddType(count_type);\n AggregateInfo aggregate_info{agg_term.aggtype, count_type, source_idx,\n storage_pos, false};\n aggregate_infos_.push_back(aggregate_info);\n break;\n }\n case ExpressionType::AGGREGATE_SUM:\n case ExpressionType::AGGREGATE_MIN:\n case ExpressionType::AGGREGATE_MAX: {\n \/\/ Count() - to check whether there is no item at all\n uint32_t count_storage_pos =\n storage_.AddType(type::Type::TypeId::BIGINT);\n AggregateInfo count_agg{ExpressionType::AGGREGATE_COUNT,\n type::Type::TypeId::BIGINT, source_idx,\n count_storage_pos, true};\n aggregate_infos_.push_back(count_agg);\n\n \/\/ Regular\n const auto value_type = agg_term.expression->GetValueType();\n uint32_t storage_pos = storage_.AddType(value_type);\n AggregateInfo aggregate_info{agg_term.aggtype, value_type, source_idx,\n storage_pos, false};\n aggregate_infos_.push_back(aggregate_info);\n break;\n }\n case ExpressionType::AGGREGATE_AVG: {\n \/\/ We decompose averages (i.e., AVG(c)) into COUNT(c) and SUM(c)\n\n \/\/ SUM() - the type must match the type of the expression\n PL_ASSERT(agg_term.expression != nullptr);\n const auto sum_type = agg_term.expression->GetValueType();\n uint32_t sum_storage_pos = storage_.AddType(sum_type);\n AggregateInfo sum_agg{ExpressionType::AGGREGATE_SUM, sum_type,\n source_idx, sum_storage_pos, true};\n aggregate_infos_.push_back(sum_agg);\n\n \/\/ COUNT() - can use big integer since we're counting instances\n uint32_t count_storage_pos =\n storage_.AddType(type::Type::TypeId::BIGINT);\n AggregateInfo count_agg{ExpressionType::AGGREGATE_COUNT,\n type::Type::TypeId::BIGINT, source_idx,\n count_storage_pos, true};\n aggregate_infos_.push_back(count_agg);\n\n \/\/ AVG()\n \/\/ TODO: Is this always double?\n AggregateInfo avg_agg{agg_term.aggtype, type::Type::TypeId::DECIMAL,\n source_idx, std::numeric_limits<uint32_t>::max(),\n false};\n aggregate_infos_.push_back(avg_agg);\n break;\n }\n case ExpressionType::AGGREGATE_COUNT_STAR: {\n \/\/ count(*)'s are always stored in the first slot, reference that here\n \/\/ NOTE: We've already added the count(*) to the storage format above,\n \/\/ don't do it here\n PL_ASSERT(tracks_group_count);\n AggregateInfo count_agg{agg_term.aggtype, type::Type::TypeId::BIGINT,\n source_idx, 0, false};\n aggregate_infos_.push_back(count_agg);\n break;\n }\n default: {\n std::string message = StringUtil::Format(\n \"Unexpected aggregate type [%s] when preparing aggregator\",\n ExpressionTypeToString(agg_term.aggtype));\n LOG_ERROR(\"%s\", message.c_str());\n throw Exception{EXCEPTION_TYPE_UNKNOWN_TYPE, message};\n }\n }\n }\n\n \/\/ Finalize the storage format\n storage_.Finalize(codegen);\n}\n\n\/\/ Create the initial values of all aggregates based on the the provided values\nvoid Aggregation::CreateInitialValues(\n CodeGen &codegen, llvm::Value *storage_space,\n const std::vector<codegen::Value> &initial) const {\n \/\/ TODO: Handle null\n for (size_t i = 0; i < aggregate_infos_.size(); i++) {\n const auto &aggregate_info = aggregate_infos_[i];\n switch (aggregate_info.aggregate_type) {\n case ExpressionType::AGGREGATE_SUM:\n case ExpressionType::AGGREGATE_MIN:\n case ExpressionType::AGGREGATE_MAX: {\n \/\/ For the above aggregations, the initial value is the attribute value\n uint32_t val_source = aggregate_info.source_index;\n storage_.SetValueAt(codegen, storage_space,\n aggregate_info.storage_index, initial[val_source]);\n break;\n }\n case ExpressionType::AGGREGATE_COUNT:\n case ExpressionType::AGGREGATE_COUNT_STAR: {\n \/\/ TODO: Count(col) needs to check for null values\n \/\/ This aggregate should be moved to the front of the storage area\n storage_.SetValueAt(\n codegen, storage_space, aggregate_info.storage_index,\n codegen::Value{type::Type::TypeId::BIGINT, codegen.Const64(1)});\n break;\n }\n case ExpressionType::AGGREGATE_AVG: {\n \/\/ AVG() aggregates aren't physically stored\n break;\n }\n default: {\n std::string message = StringUtil::Format(\n \"Unexpected aggregate type [%s] when creating initial values\",\n ExpressionTypeToString(aggregate_info.aggregate_type).c_str());\n LOG_ERROR(\"%s\", message.c_str());\n throw Exception{EXCEPTION_TYPE_UNKNOWN_TYPE, message};\n }\n }\n }\n}\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ Advance each of the aggregates stored in the provided storage space. We\n\/\/ use the storage format class to determine the location of each of the\n\/\/ aggregates. Then, depending on the type of aggregation, we advance of their\n\/\/ values, populating the provided next_vals vector with their new values.\n\/\/===----------------------------------------------------------------------===\/\/\nvoid Aggregation::AdvanceValues(\n CodeGen &codegen, llvm::Value *storage_space,\n const std::vector<codegen::Value> &next_vals) const {\n \/\/ TODO: Handle null\n for (const auto &aggregate_info : aggregate_infos_) {\n \/\/ Loop over all aggregates, advancing each\n uint32_t source = aggregate_info.source_index;\n codegen::Value next;\n switch (aggregate_info.aggregate_type) {\n case ExpressionType::AGGREGATE_SUM: {\n PL_ASSERT(source < std::numeric_limits<uint32_t>::max());\n auto curr = storage_.GetValueAt(codegen, storage_space,\n aggregate_info.storage_index);\n next = curr.Add(codegen, next_vals[source]);\n break;\n }\n case ExpressionType::AGGREGATE_MIN: {\n PL_ASSERT(source < std::numeric_limits<uint32_t>::max());\n auto curr = storage_.GetValueAt(codegen, storage_space,\n aggregate_info.storage_index);\n next = curr.Min(codegen, next_vals[source]);\n break;\n }\n case ExpressionType::AGGREGATE_MAX: {\n PL_ASSERT(source < std::numeric_limits<uint32_t>::max());\n auto curr = storage_.GetValueAt(codegen, storage_space,\n aggregate_info.storage_index);\n next = curr.Max(codegen, next_vals[source]);\n break;\n }\n case ExpressionType::AGGREGATE_COUNT: {\n PL_ASSERT(source < std::numeric_limits<uint32_t>::max());\n auto curr = storage_.GetValueAt(codegen, storage_space,\n aggregate_info.storage_index);\n auto delta = Value{type::Type::TypeId::BIGINT, codegen.Const64(1)};\n next = curr.Add(codegen, delta);\n break;\n }\n case ExpressionType::AGGREGATE_COUNT_STAR: {\n \/\/ COUNT(*) is always stored first with a source equal to INT_MAX. All\n \/\/ other COUNT(*)'s refer to that one.\n if (source != std::numeric_limits<uint32_t>::max()) {\n continue;\n }\n auto curr = storage_.GetValueAt(codegen, storage_space,\n aggregate_info.storage_index);\n auto delta = Value{type::Type::TypeId::BIGINT, codegen.Const64(1)};\n next = curr.Add(codegen, delta);\n break;\n }\n case ExpressionType::AGGREGATE_AVG: {\n \/\/ AVG() aggregates aren't physically stored\n continue;\n }\n default: {\n std::string message = StringUtil::Format(\n \"Unexpected aggregate type [%s] when advancing aggregator\",\n ExpressionTypeToString(aggregate_info.aggregate_type).c_str());\n LOG_ERROR(\"%s\", message.c_str());\n throw Exception{EXCEPTION_TYPE_UNKNOWN_TYPE, message};\n }\n }\n\n \/\/ StoreValue the next value in the appropriate slot\n PL_ASSERT(next.GetType() != type::Type::TypeId::INVALID);\n storage_.SetValueAt(codegen, storage_space, aggregate_info.storage_index,\n next);\n }\n}\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ This function will finalize the aggregates stored in the provided storage\n\/\/ space. Finalization essentially means computing the final values of the\n\/\/ aggregates. This is only really necessary for averages. Either way, we\n\/\/ populate the final_vals vector with the final values of all the aggregates.\n\/\/===----------------------------------------------------------------------===\/\/\nvoid Aggregation::FinalizeValues(\n CodeGen &codegen, llvm::Value *storage_space,\n std::vector<codegen::Value> &final_vals) const {\n \/\/ Collect all final values into this map. We need this because some\n \/\/ aggregates are derived from other component aggregates.\n std::map<std::pair<uint32_t, ExpressionType>, codegen::Value> vals;\n\n for (const auto &aggregate_info : aggregate_infos_) {\n uint32_t source = aggregate_info.source_index;\n ExpressionType agg_type = aggregate_info.aggregate_type;\n switch (agg_type) {\n case ExpressionType::AGGREGATE_COUNT: {\n codegen::Value final_val = storage_.GetValueAt(\n codegen, storage_space, aggregate_info.storage_index);\n vals[std::make_pair(source, agg_type)] = final_val;\n if (!aggregate_info.is_internal) {\n final_vals.push_back(final_val);\n }\n break;\n }\n case ExpressionType::AGGREGATE_SUM:\n case ExpressionType::AGGREGATE_MIN:\n case ExpressionType::AGGREGATE_MAX: {\n codegen::Value count =\n vals[std::make_pair(source, ExpressionType::AGGREGATE_COUNT)];\n codegen::Value final_calc = storage_.GetValueAt(\n codegen, storage_space, aggregate_info.storage_index);\n\n vals[std::make_pair(source, agg_type)] = final_calc;\n if (!aggregate_info.is_internal) {\n \/\/ Empty check\n codegen::Value final_null;\n If check_count{codegen, codegen->CreateICmpEQ(count.GetValue(),\n codegen.Const64(0))};\n {\n final_null = Type::GetNullValue(codegen, final_calc.GetType());\n }\n check_count.EndIf();\n auto final_val = check_count.BuildPHI(final_null, final_calc);\n final_vals.push_back(final_val);\n }\n break;\n }\n case ExpressionType::AGGREGATE_AVG: {\n \/\/ Find the sum and count for this aggregate\n codegen::Value count = vals[{source, ExpressionType::AGGREGATE_COUNT}];\n codegen::Value sum = vals[{source, ExpressionType::AGGREGATE_SUM}];\n codegen::Value casted_sum = sum.CastTo(codegen, count.GetType());\n\n codegen::Value final_val =\n casted_sum.Div(codegen, count, Value::OnError::Ignore);\n vals[std::make_pair(source, agg_type)] = final_val;\n final_vals.push_back(final_val);\n break;\n }\n case ExpressionType::AGGREGATE_COUNT_STAR: {\n if (source != std::numeric_limits<uint32_t>::max()) {\n PL_ASSERT(!aggregate_info.is_internal);\n uint32_t count_source = std::numeric_limits<uint32_t>::max();\n final_vals.push_back(vals[std::make_pair(count_source, agg_type)]);\n } else {\n PL_ASSERT(aggregate_info.is_internal);\n codegen::Value final_val = storage_.GetValueAt(\n codegen, storage_space, aggregate_info.storage_index);\n vals[std::make_pair(source, agg_type)] = final_val;\n }\n break;\n }\n default: {\n std::string message = StringUtil::Format(\n \"Unexpected aggregate type [%s] when finalizing aggregator\",\n ExpressionTypeToString(agg_type));\n LOG_ERROR(\"%s\", message.c_str());\n throw Exception{EXCEPTION_TYPE_UNKNOWN_TYPE, message};\n }\n }\n }\n}\n\n} \/\/ namespace codegen\n} \/\/ namespace peloton\n<commit_msg>More compilation problems<commit_after>\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ Peloton\n\/\/\n\/\/ aggregation.cpp\n\/\/\n\/\/ Identification: src\/codegen\/aggregation.cpp\n\/\/\n\/\/ Copyright (c) 2015-17, Carnegie Mellon University Database Group\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"codegen\/aggregation.h\"\n#include \"codegen\/if.h\"\n#include \"codegen\/type.h\"\n\nnamespace peloton {\nnamespace codegen {\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ Setup the aggregation storage format given the aggregates the caller wants to\n\/\/ store.\n\/\/===----------------------------------------------------------------------===\/\/\nvoid Aggregation::Setup(\n CodeGen &codegen,\n const std::vector<planner::AggregatePlan::AggTerm> &aggregates) {\n \/\/ Collect the types so we can configure the updateable storage's format\n bool needs_group_count = false;\n bool tracks_group_count = false;\n for (uint32_t i = 0; i < aggregates.size(); i++) {\n const auto agg_term = aggregates[i];\n \/\/ Defense > Offense ?\n PL_ASSERT(agg_term.agg_ai.type != type::Type::TypeId::INVALID);\n\n needs_group_count |= agg_term.aggtype == ExpressionType::AGGREGATE_AVG;\n tracks_group_count |=\n agg_term.aggtype == ExpressionType::AGGREGATE_COUNT_STAR;\n }\n\n \/\/ Add the count(*) aggregate first, if we need to\n if (tracks_group_count || needs_group_count) {\n uint32_t storage_pos = storage_.AddType(type::Type::TypeId::BIGINT);\n AggregateInfo count_agg{\n ExpressionType::AGGREGATE_COUNT_STAR, type::Type::TypeId::BIGINT,\n std::numeric_limits<uint32_t>::max(), storage_pos, true};\n aggregate_infos_.push_back(count_agg);\n }\n\n \/\/ Add the rest\n for (uint32_t source_idx = 0; source_idx < aggregates.size(); source_idx++) {\n const auto agg_term = aggregates[source_idx];\n switch (agg_term.aggtype) {\n case ExpressionType::AGGREGATE_COUNT: {\n \/\/ We're counting instances ... use BIGINT for the count\n const auto count_type = type::Type::TypeId::BIGINT;\n uint32_t storage_pos = storage_.AddType(count_type);\n AggregateInfo aggregate_info{agg_term.aggtype, count_type, source_idx,\n storage_pos, false};\n aggregate_infos_.push_back(aggregate_info);\n break;\n }\n case ExpressionType::AGGREGATE_SUM:\n case ExpressionType::AGGREGATE_MIN:\n case ExpressionType::AGGREGATE_MAX: {\n \/\/ Count() - to check whether there is no item at all\n uint32_t count_storage_pos =\n storage_.AddType(type::Type::TypeId::BIGINT);\n AggregateInfo count_agg{ExpressionType::AGGREGATE_COUNT,\n type::Type::TypeId::BIGINT, source_idx,\n count_storage_pos, true};\n aggregate_infos_.push_back(count_agg);\n\n \/\/ Regular\n const auto value_type = agg_term.expression->GetValueType();\n uint32_t storage_pos = storage_.AddType(value_type);\n AggregateInfo aggregate_info{agg_term.aggtype, value_type, source_idx,\n storage_pos, false};\n aggregate_infos_.push_back(aggregate_info);\n break;\n }\n case ExpressionType::AGGREGATE_AVG: {\n \/\/ We decompose averages (i.e., AVG(c)) into COUNT(c) and SUM(c)\n\n \/\/ SUM() - the type must match the type of the expression\n PL_ASSERT(agg_term.expression != nullptr);\n const auto sum_type = agg_term.expression->GetValueType();\n uint32_t sum_storage_pos = storage_.AddType(sum_type);\n AggregateInfo sum_agg{ExpressionType::AGGREGATE_SUM, sum_type,\n source_idx, sum_storage_pos, true};\n aggregate_infos_.push_back(sum_agg);\n\n \/\/ COUNT() - can use big integer since we're counting instances\n uint32_t count_storage_pos =\n storage_.AddType(type::Type::TypeId::BIGINT);\n AggregateInfo count_agg{ExpressionType::AGGREGATE_COUNT,\n type::Type::TypeId::BIGINT, source_idx,\n count_storage_pos, true};\n aggregate_infos_.push_back(count_agg);\n\n \/\/ AVG()\n \/\/ TODO: Is this always double?\n AggregateInfo avg_agg{agg_term.aggtype, type::Type::TypeId::DECIMAL,\n source_idx, std::numeric_limits<uint32_t>::max(),\n false};\n aggregate_infos_.push_back(avg_agg);\n break;\n }\n case ExpressionType::AGGREGATE_COUNT_STAR: {\n \/\/ count(*)'s are always stored in the first slot, reference that here\n \/\/ NOTE: We've already added the count(*) to the storage format above,\n \/\/ don't do it here\n PL_ASSERT(tracks_group_count);\n AggregateInfo count_agg{agg_term.aggtype, type::Type::TypeId::BIGINT,\n source_idx, 0, false};\n aggregate_infos_.push_back(count_agg);\n break;\n }\n default: {\n std::string message = StringUtil::Format(\n \"Unexpected aggregate type [%s] when preparing aggregator\",\n ExpressionTypeToString(agg_term.aggtype).c_str());\n LOG_ERROR(\"%s\", message.c_str());\n throw Exception{EXCEPTION_TYPE_UNKNOWN_TYPE, message};\n }\n }\n }\n\n \/\/ Finalize the storage format\n storage_.Finalize(codegen);\n}\n\n\/\/ Create the initial values of all aggregates based on the the provided values\nvoid Aggregation::CreateInitialValues(\n CodeGen &codegen, llvm::Value *storage_space,\n const std::vector<codegen::Value> &initial) const {\n \/\/ TODO: Handle null\n for (size_t i = 0; i < aggregate_infos_.size(); i++) {\n const auto &aggregate_info = aggregate_infos_[i];\n switch (aggregate_info.aggregate_type) {\n case ExpressionType::AGGREGATE_SUM:\n case ExpressionType::AGGREGATE_MIN:\n case ExpressionType::AGGREGATE_MAX: {\n \/\/ For the above aggregations, the initial value is the attribute value\n uint32_t val_source = aggregate_info.source_index;\n storage_.SetValueAt(codegen, storage_space,\n aggregate_info.storage_index, initial[val_source]);\n break;\n }\n case ExpressionType::AGGREGATE_COUNT:\n case ExpressionType::AGGREGATE_COUNT_STAR: {\n \/\/ TODO: Count(col) needs to check for null values\n \/\/ This aggregate should be moved to the front of the storage area\n storage_.SetValueAt(\n codegen, storage_space, aggregate_info.storage_index,\n codegen::Value{type::Type::TypeId::BIGINT, codegen.Const64(1)});\n break;\n }\n case ExpressionType::AGGREGATE_AVG: {\n \/\/ AVG() aggregates aren't physically stored\n break;\n }\n default: {\n std::string message = StringUtil::Format(\n \"Unexpected aggregate type [%s] when creating initial values\",\n ExpressionTypeToString(aggregate_info.aggregate_type).c_str());\n LOG_ERROR(\"%s\", message.c_str());\n throw Exception{EXCEPTION_TYPE_UNKNOWN_TYPE, message};\n }\n }\n }\n}\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ Advance each of the aggregates stored in the provided storage space. We\n\/\/ use the storage format class to determine the location of each of the\n\/\/ aggregates. Then, depending on the type of aggregation, we advance of their\n\/\/ values, populating the provided next_vals vector with their new values.\n\/\/===----------------------------------------------------------------------===\/\/\nvoid Aggregation::AdvanceValues(\n CodeGen &codegen, llvm::Value *storage_space,\n const std::vector<codegen::Value> &next_vals) const {\n \/\/ TODO: Handle null\n for (const auto &aggregate_info : aggregate_infos_) {\n \/\/ Loop over all aggregates, advancing each\n uint32_t source = aggregate_info.source_index;\n codegen::Value next;\n switch (aggregate_info.aggregate_type) {\n case ExpressionType::AGGREGATE_SUM: {\n PL_ASSERT(source < std::numeric_limits<uint32_t>::max());\n auto curr = storage_.GetValueAt(codegen, storage_space,\n aggregate_info.storage_index);\n next = curr.Add(codegen, next_vals[source]);\n break;\n }\n case ExpressionType::AGGREGATE_MIN: {\n PL_ASSERT(source < std::numeric_limits<uint32_t>::max());\n auto curr = storage_.GetValueAt(codegen, storage_space,\n aggregate_info.storage_index);\n next = curr.Min(codegen, next_vals[source]);\n break;\n }\n case ExpressionType::AGGREGATE_MAX: {\n PL_ASSERT(source < std::numeric_limits<uint32_t>::max());\n auto curr = storage_.GetValueAt(codegen, storage_space,\n aggregate_info.storage_index);\n next = curr.Max(codegen, next_vals[source]);\n break;\n }\n case ExpressionType::AGGREGATE_COUNT: {\n PL_ASSERT(source < std::numeric_limits<uint32_t>::max());\n auto curr = storage_.GetValueAt(codegen, storage_space,\n aggregate_info.storage_index);\n auto delta = Value{type::Type::TypeId::BIGINT, codegen.Const64(1)};\n next = curr.Add(codegen, delta);\n break;\n }\n case ExpressionType::AGGREGATE_COUNT_STAR: {\n \/\/ COUNT(*) is always stored first with a source equal to INT_MAX. All\n \/\/ other COUNT(*)'s refer to that one.\n if (source != std::numeric_limits<uint32_t>::max()) {\n continue;\n }\n auto curr = storage_.GetValueAt(codegen, storage_space,\n aggregate_info.storage_index);\n auto delta = Value{type::Type::TypeId::BIGINT, codegen.Const64(1)};\n next = curr.Add(codegen, delta);\n break;\n }\n case ExpressionType::AGGREGATE_AVG: {\n \/\/ AVG() aggregates aren't physically stored\n continue;\n }\n default: {\n std::string message = StringUtil::Format(\n \"Unexpected aggregate type [%s] when advancing aggregator\",\n ExpressionTypeToString(aggregate_info.aggregate_type).c_str());\n LOG_ERROR(\"%s\", message.c_str());\n throw Exception{EXCEPTION_TYPE_UNKNOWN_TYPE, message};\n }\n }\n\n \/\/ StoreValue the next value in the appropriate slot\n PL_ASSERT(next.GetType() != type::Type::TypeId::INVALID);\n storage_.SetValueAt(codegen, storage_space, aggregate_info.storage_index,\n next);\n }\n}\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ This function will finalize the aggregates stored in the provided storage\n\/\/ space. Finalization essentially means computing the final values of the\n\/\/ aggregates. This is only really necessary for averages. Either way, we\n\/\/ populate the final_vals vector with the final values of all the aggregates.\n\/\/===----------------------------------------------------------------------===\/\/\nvoid Aggregation::FinalizeValues(\n CodeGen &codegen, llvm::Value *storage_space,\n std::vector<codegen::Value> &final_vals) const {\n \/\/ Collect all final values into this map. We need this because some\n \/\/ aggregates are derived from other component aggregates.\n std::map<std::pair<uint32_t, ExpressionType>, codegen::Value> vals;\n\n for (const auto &aggregate_info : aggregate_infos_) {\n uint32_t source = aggregate_info.source_index;\n ExpressionType agg_type = aggregate_info.aggregate_type;\n switch (agg_type) {\n case ExpressionType::AGGREGATE_COUNT: {\n codegen::Value final_val = storage_.GetValueAt(\n codegen, storage_space, aggregate_info.storage_index);\n vals[std::make_pair(source, agg_type)] = final_val;\n if (!aggregate_info.is_internal) {\n final_vals.push_back(final_val);\n }\n break;\n }\n case ExpressionType::AGGREGATE_SUM:\n case ExpressionType::AGGREGATE_MIN:\n case ExpressionType::AGGREGATE_MAX: {\n codegen::Value count =\n vals[std::make_pair(source, ExpressionType::AGGREGATE_COUNT)];\n codegen::Value final_calc = storage_.GetValueAt(\n codegen, storage_space, aggregate_info.storage_index);\n\n vals[std::make_pair(source, agg_type)] = final_calc;\n if (!aggregate_info.is_internal) {\n \/\/ Empty check\n codegen::Value final_null;\n If check_count{codegen, codegen->CreateICmpEQ(count.GetValue(),\n codegen.Const64(0))};\n {\n final_null = Type::GetNullValue(codegen, final_calc.GetType());\n }\n check_count.EndIf();\n auto final_val = check_count.BuildPHI(final_null, final_calc);\n final_vals.push_back(final_val);\n }\n break;\n }\n case ExpressionType::AGGREGATE_AVG: {\n \/\/ Find the sum and count for this aggregate\n codegen::Value count = vals[{source, ExpressionType::AGGREGATE_COUNT}];\n codegen::Value sum = vals[{source, ExpressionType::AGGREGATE_SUM}];\n codegen::Value casted_sum = sum.CastTo(codegen, count.GetType());\n\n codegen::Value final_val =\n casted_sum.Div(codegen, count, Value::OnError::Ignore);\n vals[std::make_pair(source, agg_type)] = final_val;\n final_vals.push_back(final_val);\n break;\n }\n case ExpressionType::AGGREGATE_COUNT_STAR: {\n if (source != std::numeric_limits<uint32_t>::max()) {\n PL_ASSERT(!aggregate_info.is_internal);\n uint32_t count_source = std::numeric_limits<uint32_t>::max();\n final_vals.push_back(vals[std::make_pair(count_source, agg_type)]);\n } else {\n PL_ASSERT(aggregate_info.is_internal);\n codegen::Value final_val = storage_.GetValueAt(\n codegen, storage_space, aggregate_info.storage_index);\n vals[std::make_pair(source, agg_type)] = final_val;\n }\n break;\n }\n default: {\n std::string message = StringUtil::Format(\n \"Unexpected aggregate type [%s] when finalizing aggregator\",\n ExpressionTypeToString(agg_type).c_str());\n LOG_ERROR(\"%s\", message.c_str());\n throw Exception{EXCEPTION_TYPE_UNKNOWN_TYPE, message};\n }\n }\n }\n}\n\n} \/\/ namespace codegen\n} \/\/ namespace peloton\n<|endoftext|>"} {"text":"<commit_before>#include <string>\n\n#include <cppunit\/extensions\/HelperMacros.h>\n\n#include \"ecru.h\"\n\nusing namespace std;\n\nclass EcruTest : public CPPUNIT_NS::TestFixture\n{\n\tprivate:\n\t\tCPPUNIT_TEST_SUITE( EcruTest );\n\t\tCPPUNIT_TEST( testStripString );\n\t\tCPPUNIT_TEST( testStripNewLines );\n\t\tCPPUNIT_TEST_SUITE_END();\n\t\n\tpublic:\n\t\tvoid testStripString();\n\t\tvoid testStripNewLines();\n};\n\nCPPUNIT_TEST_SUITE_REGISTRATION( EcruTest );\n\nvoid EcruTest::testStripString()\n{\n\t\/\/ typical usage\n\tstring unstripped = \" somestr \";\n\tstring stripped = ecru::stripString(unstripped);\n\n\tCPPUNIT_ASSERT_EQUAL(unstripped.size(), stripped.size() + 4);\n\tCPPUNIT_ASSERT(stripped == \"somestr\");\n\n\t\/\/ find out what's going on if we pass empty string\n\tstring empty = ecru::stripString(\"\");\n\n\tCPPUNIT_ASSERT(empty == \"\");\n\n\t\/\/ check if it doesn't modify a string that doesn't need \n\t\/\/ to be stripped\n\tstring alreadyStripped;\n\tstring doubleStrip = ecru::stripString(alreadyStripped);\n\t\n\tCPPUNIT_ASSERT(doubleStrip == alreadyStripped);\n}\n\nvoid EcruTest::testStripNewLines()\n{\n\t\/\/ typical usage\n\tstring stringWithNewLines = \"hello\\nhow are\\nyou doing\\n\";\n\tstring stripped = ecru::stripNewLines(stringWithNewLines);\n\t\n\tCPPUNIT_ASSERT(stripped.find(\"\\n\") == string::npos);\n\n\t\/\/ empty\n\tCPPUNIT_ASSERT(\"\" == ecru::stripNewLines(\"\"));\n\n\t\/\/ without new lines\n\tCPPUNIT_ASSERT(\"foo\" == ecru::stripNewLines(\"foo\"));\n}\n<commit_msg>Add a test for executeCommand().<commit_after>#include <string>\n\n#include <cppunit\/extensions\/HelperMacros.h>\n\n#include \"ecru.h\"\n\nusing namespace std;\n\nclass EcruTest : public CPPUNIT_NS::TestFixture\n{\n\tprivate:\n\t\tCPPUNIT_TEST_SUITE( EcruTest );\n\t\tCPPUNIT_TEST( testStripString );\n\t\tCPPUNIT_TEST( testStripNewLines );\n\t\tCPPUNIT_TEST( testExecuteCommandWithValidCommand );\n\t\tCPPUNIT_TEST_SUITE_END();\n\t\n\tpublic:\n\t\tvoid testStripString();\n\t\tvoid testStripNewLines();\n\t\tvoid testExecuteCommandWithValidCommand();\n};\n\nCPPUNIT_TEST_SUITE_REGISTRATION( EcruTest );\n\nvoid EcruTest::testStripString()\n{\n\t\/\/ typical usage\n\tstring unstripped = \" somestr \";\n\tstring stripped = ecru::stripString(unstripped);\n\n\tCPPUNIT_ASSERT_EQUAL(unstripped.size(), stripped.size() + 4);\n\tCPPUNIT_ASSERT(stripped == \"somestr\");\n\n\t\/\/ find out what's going on if we pass empty string\n\tstring empty = ecru::stripString(\"\");\n\n\tCPPUNIT_ASSERT(empty == \"\");\n\n\t\/\/ check if it doesn't modify a string that doesn't need \n\t\/\/ to be stripped\n\tstring alreadyStripped;\n\tstring doubleStrip = ecru::stripString(alreadyStripped);\n\t\n\tCPPUNIT_ASSERT(doubleStrip == alreadyStripped);\n}\n\nvoid EcruTest::testStripNewLines()\n{\n\t\/\/ typical usage\n\tstring stringWithNewLines = \"hello\\nhow are\\nyou doing\\n\";\n\tstring stripped = ecru::stripNewLines(stringWithNewLines);\n\t\n\tCPPUNIT_ASSERT(stripped.find(\"\\n\") == string::npos);\n\n\t\/\/ empty\n\tCPPUNIT_ASSERT(\"\" == ecru::stripNewLines(\"\"));\n\n\t\/\/ without new lines\n\tCPPUNIT_ASSERT(\"foo\" == ecru::stripNewLines(\"foo\"));\n}\n\nvoid EcruTest::testExecuteCommandWithValidCommand()\n{\n\tvector<string> args;\n\n\targs.push_back(\"-a\");\n\n\tint status = ecru::executeCommand(\"\/usr\/bin\/uname\", args);\n\n\tCPPUNIT_ASSERT(status == 0);\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"Game.h\"\n#include \"TextureManager.h\"\n#include \"Player.h\"\n#include \"Enemy.h\"\n#include \"InputHandler.h\"\n#include \"MenuState.h\"\n#include \"PlayState.h\"\n\n\/\/definition for static instance \nGame* Game::s_pInstance = 0;\n\nbool Game::init(const char *title, int xpos, int ypos, int width, int height, bool fullscreen)\n{\t\n\tint flags = 0;\n\tif (fullscreen)\n\t{\n\t\tflags = SDL_WINDOW_FULLSCREEN;\n\t}\n\n\t\/\/attempt to initialize SDL\n\tif (SDL_Init(SDL_INIT_EVERYTHING) == 0)\n\t{\t\n\t\tstd::cout << \"SDL init success\\n\";\n\t\t\/\/init the window\n\t\tm_pWindow = SDL_CreateWindow(title, xpos, ypos, width, height, flags);\n\n\t\tif (m_pWindow != 0)\t\/\/window init success\n\t\t{\n\t\t\tstd::cout << \"Window creation success\\n\";\n\t\t\tm_pRenderer = SDL_CreateRenderer(m_pWindow, -1, 0);\n\n\t\t\tif (m_pRenderer != 0) \/\/renderer init success\n\t\t\t{\n\t\t\t\tstd::cout << \"renderer init success\\n\";\n\t\t\t\tSDL_SetRenderDrawColor(m_pRenderer, 255, 0, 0, 255);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tstd::cout << \"renderer init failed\\n\";\n\t\t\t\treturn false;\t\/\/renderer init fail\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tstd::cout << \"window init fail\\n\";\n\t\t\treturn false;\t\/\/window init fail\n\t\t}\n\t}\n\telse\n\t{\n\t\tstd::cout << \"SDL init fail\\n\";\n\t\treturn false;\t\/\/SDL init fail\n\t}\n\t\n\t\/\/initialise joysticks\n\tTheInputHandler::Instance()->initialiseJoysticks();\n\n\tstd::cout << \"init success\\n\";\n\n\t\/\/load TextureManager\n\tif (!TheTextureManager::Instance()->load(\"assets\/animate-alpha.png\", \"animate\", m_pRenderer))\n\t{\n\t\treturn false;\n\t}\n\n\t\/\/creating and pushing objects\n\tm_gameObjects.push_back(new Player(new LoaderParams(100, 100, 128, 82, \"animate\")));\n\tm_gameObjects.push_back(new Enemy(new LoaderParams(300, 300, 128, 82, \"animate\")));\n\n\tm_bRunning = true;\t\/\/everything inited successfully, start the main loop\n\n\t\/\/load MENU state \n\tm_pGameStateMachine = new GameStateMachine();\n\tm_pGameStateMachine->changeState(new MenuState());\n\n\treturn true;\n}\n\nbool Game::running()\n{\n\treturn m_bRunning;\n}\n\nvoid Game::handleEvents()\n{\t\n\t\/\/waits and listens for a quit event \n\tTheInputHandler::Instance()->update();\n\n\tif (TheInputHandler::Instance()->isKeyDown(SDL_SCANCODE_RETURN))\n\t{\n\t\tm_pGameStateMachine->changeState(new PlayState());\n\t}\n}\n\nvoid Game::update()\n{\n\t\/\/loop through and update our objects\n\tfor (std::vector<GameObject*>::size_type i = 0; i != m_gameObjects.size(); ++i)\n\t{\n\t\tm_gameObjects[i]->update();\n\t}\n}\n\nvoid Game::render()\n{\n\tSDL_RenderClear(m_pRenderer); \/\/clear the renderer to the draw color\n\t\n\t\/\/loop through our objects and draw them\n\tfor (std::vector<GameObject*>::size_type i = 0; i != m_gameObjects.size(); i++)\n\t{\n\t\tm_gameObjects[i]->draw();\n\t}\n\n\tSDL_RenderPresent(m_pRenderer);\t\/\/draw to the screen\n}\n\nvoid Game::clean()\n{\n\tstd::cout << \"cleaning game\\n\";\n\t\n\t\/\/close the joysticks\n\tTheInputHandler::Instance()->clean();\n\n\tSDL_DestroyWindow(m_pWindow);\n\tSDL_DestroyRenderer(m_pRenderer);\n\tSDL_Quit();\n}\n\nvoid Game::quit()\n{\n\tm_bRunning = false;\n}<commit_msg>Game now uses GameStateMachine's update and render function<commit_after>#include \"Game.h\"\n#include \"TextureManager.h\"\n#include \"Player.h\"\n#include \"Enemy.h\"\n#include \"InputHandler.h\"\n#include \"MenuState.h\"\n#include \"PlayState.h\"\n\n\/\/definition for static instance \nGame* Game::s_pInstance = 0;\n\nbool Game::init(const char *title, int xpos, int ypos, int width, int height, bool fullscreen)\n{\t\n\tint flags = 0;\n\tif (fullscreen)\n\t{\n\t\tflags = SDL_WINDOW_FULLSCREEN;\n\t}\n\n\t\/\/attempt to initialize SDL\n\tif (SDL_Init(SDL_INIT_EVERYTHING) == 0)\n\t{\t\n\t\tstd::cout << \"SDL init success\\n\";\n\t\t\/\/init the window\n\t\tm_pWindow = SDL_CreateWindow(title, xpos, ypos, width, height, flags);\n\n\t\tif (m_pWindow != 0)\t\/\/window init success\n\t\t{\n\t\t\tstd::cout << \"Window creation success\\n\";\n\t\t\tm_pRenderer = SDL_CreateRenderer(m_pWindow, -1, 0);\n\n\t\t\tif (m_pRenderer != 0) \/\/renderer init success\n\t\t\t{\n\t\t\t\tstd::cout << \"renderer init success\\n\";\n\t\t\t\tSDL_SetRenderDrawColor(m_pRenderer, 255, 0, 0, 255);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tstd::cout << \"renderer init failed\\n\";\n\t\t\t\treturn false;\t\/\/renderer init fail\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tstd::cout << \"window init fail\\n\";\n\t\t\treturn false;\t\/\/window init fail\n\t\t}\n\t}\n\telse\n\t{\n\t\tstd::cout << \"SDL init fail\\n\";\n\t\treturn false;\t\/\/SDL init fail\n\t}\n\t\n\t\/\/initialise joysticks\n\tTheInputHandler::Instance()->initialiseJoysticks();\n\n\tstd::cout << \"init success\\n\";\n\n\t\/\/load TextureManager\n\tif (!TheTextureManager::Instance()->load(\"assets\/animate-alpha.png\", \"animate\", m_pRenderer))\n\t{\n\t\treturn false;\n\t}\n\n\t\/\/creating and pushing objects\n\tm_gameObjects.push_back(new Player(new LoaderParams(100, 100, 128, 82, \"animate\")));\n\tm_gameObjects.push_back(new Enemy(new LoaderParams(300, 300, 128, 82, \"animate\")));\n\n\tm_bRunning = true;\t\/\/everything inited successfully, start the main loop\n\n\t\/\/load MENU state \n\tm_pGameStateMachine = new GameStateMachine();\n\tm_pGameStateMachine->changeState(new MenuState());\n\n\treturn true;\n}\n\nbool Game::running()\n{\n\treturn m_bRunning;\n}\n\nvoid Game::handleEvents()\n{\t\n\t\/\/waits and listens for a quit event \n\tTheInputHandler::Instance()->update();\n\n\tif (TheInputHandler::Instance()->isKeyDown(SDL_SCANCODE_RETURN))\n\t{\n\t\tm_pGameStateMachine->changeState(new PlayState());\n\t}\n}\n\nvoid Game::update()\n{\n\t\/\/use GameStateMachine's update function\n\tm_pGameStateMachine->update();\n}\n\nvoid Game::render()\n{\n\tSDL_RenderClear(m_pRenderer); \/\/clear the renderer to the draw color\n\t\n\t\/\/use GameStateMachine's render function\n\tm_pGameStateMachine->render();\n\n\tSDL_RenderPresent(m_pRenderer);\t\/\/draw to the screen\n}\n\nvoid Game::clean()\n{\n\tstd::cout << \"cleaning game\\n\";\n\t\n\t\/\/close the joysticks\n\tTheInputHandler::Instance()->clean();\n\n\tSDL_DestroyWindow(m_pWindow);\n\tSDL_DestroyRenderer(m_pRenderer);\n\tSDL_Quit();\n}\n\nvoid Game::quit()\n{\n\tm_bRunning = false;\n}<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n\n#include <SFML\/Graphics.hpp>\n#include \"Game.hpp\"\n#include \"Houses.hpp\"\n\nconst sf::Time Game::TimePerFrame = sf::seconds(1.f\/60.f);\n\nGame::Game():\n playing(true),\n screen(),\n map(nullptr),\n console(),\n actions(screen, console),\n unitRepository(messages)\n{\n sf::ContextSettings settings;\n settings.antialiasingLevel = 8;\n screen.create(sf::VideoMode(800, 600), \"Dune 2 - The Maker\", sf::Style::Close, settings);\n screen.setFramerateLimit(IDEAL_FPS);\n screen.setMouseCursorVisible(false);\n\n if (!init()){\n std::cerr << \"Failed to initialized game.\";\n playing = false;\n }\n}\n\nint Game::execute() {\n\n sf::Clock clock;\n sf::Time timeSinceLastUpdate = sf::Time::Zero;\n\n while(playing) {\n dt = clock.restart();\n timeSinceLastUpdate += dt;\n while (timeSinceLastUpdate > TimePerFrame)\n {\n timeSinceLastUpdate -= TimePerFrame;\n\n updateState(TimePerFrame);\n }\n\n render();\n\n }\n\n return 0;\n}\n\nbool Game::init() {\n if (!terrain.loadFromFile(\"graphics\/terrain.png\")) {\n std::cout << \"Failed to read graphics\/terrain.png data\" << std::endl;\n return false;\n }\n\n sf::Image temp;\n if (!temp.loadFromFile(\"graphics\/shroud_edges.bmp\")) {\n std::cout << \"Failed to read graphics\/shroud_edges.bmp data\" << std::endl;\n return false;\n }\n\n temp.createMaskFromColor(sf::Color(255, 0, 255));\n shroudEdges.loadFromImage(temp);\n\n map.reset(new Map(terrain, shroudEdges, messages));\n map->load(\"maps\/4PL_Mountains.ini\");\n\n camera.reset({0,0,800,600});\n screen.setView(camera);\n\n \/\/init two players\n int idCount = 0;\n players.emplace_back(House::Sardaukar, idCount++);\n players.emplace_back(House::Harkonnen, idCount++);\n\n units.push_back(std::move(unitRepository.create(Unit::Type::Trike, players[0], sf::Vector2f(256, 256))));\n units.push_back(std::move(unitRepository.create(Unit::Type::Quad, players[1], sf::Vector2f(300, 300))));\n\n units.push_back(std::move(unitRepository.create(Unit::Type::Soldier, players[0], sf::Vector2f(400, 500))));\n units.push_back(std::move(unitRepository.create(Unit::Type::Soldier, players[0], sf::Vector2f(410, 500))));\n units.push_back(std::move(unitRepository.create(Unit::Type::Soldier, players[0], sf::Vector2f(220, 500))));\n units.push_back(std::move(unitRepository.create(Unit::Type::Soldier, players[0], sf::Vector2f(430, 500))));\n\n units.push_back(std::move(unitRepository.create(Unit::Type::Devastator, players[1], sf::Vector2f(500, 200))));\n\n \/\/register listeners\n typedef thor::ActionContext<std::string> actionContext;\n\n actions.connect(\"close\", [this](actionContext){playing = false;});\n\n actions.connect(\"boxRelease\", [this](actionContext){\n for (auto& unit : units){\n if (box.intersects(unit.getBounds())){\n selectUnit(unit);\n }\n }\n box.clear();\n });\n\n actions.connect(\"boxStart\", [this](actionContext context) {\n if (mouse.getType() != Mouse::Type::Default) {\n return;\n }\n sf::Vector2f toSet = screen.mapPixelToCoords(mouse.getHotspot(*context.event), camera);\n box.setTopLeft(toSet);\n });\n\n actions.connect(\"singleSelect\", [this](actionContext context){\n sf::Vector2f toCheck = screen.mapPixelToCoords(mouse.getHotspot(*context.event), camera);\n for (auto& unit : units){\n if (unit.getBounds().contains(toCheck))\n selectUnit(unit);\n }\n });\n\n actions.connect(\"deselectAll\", [this](actionContext){\n actions.disconnect(\"orderMove\");\n mouse.setType(Mouse::Type::Default);\n for (auto& unit : units)\n unit.unselect();\n });\n\n actions.connect(\"boxDrag\", [this](actionContext){\n box.setBottomRight(screen.mapPixelToCoords(sf::Mouse::getPosition(screen), camera));\n });\n\n const float cameraSpeed = 700.f;\n\n actions.connect(\"cameraLeft\", [this, cameraSpeed](actionContext) {camera.move(-dt.asSeconds()*cameraSpeed, 0.f);});\n actions.connect(\"cameraRight\", [this, cameraSpeed](actionContext){camera.move(dt.asSeconds()*cameraSpeed, 0.f); });\n actions.connect(\"cameraUp\", [this, cameraSpeed](actionContext) {camera.move(0.f, -dt.asSeconds()*cameraSpeed);});\n actions.connect(\"cameraDown\", [this, cameraSpeed](actionContext) {camera.move(0.f, dt.asSeconds()*cameraSpeed); });\n\n actions.connect(\"toggleConsole\", std::bind(&Console::toggle, &console));\n\n return true;\n}\n\nvoid Game::render() {\n screen.clear();\n\n screen.setView(camera);\n\n screen.draw(*map);\n\n for (const auto& unit : units)\n screen.draw(unit);\n\n map->drawShrouded(screen, sf::RenderStates::Default);\n\n screen.draw(box);\n\n screen.draw(fpsCounter);\n\n screen.setView(camera);\n\n console.display(screen);\n\n screen.draw(mouse);\n\n screen.display();\n}\n\nvoid Game::updateState(sf::Time dt) {\n\n actions.update();\n console.update(dt);\n\n sf::Vector2i mousePosition = sf::Mouse::getPosition(screen);\n\n if (mousePosition.x < 50 ) actions.trigger(\"cameraLeft\");\n else if (mousePosition.y < 50 ) actions.trigger(\"cameraUp\");\n else if (mousePosition.x > 750) actions.trigger(\"cameraRight\");\n else if (mousePosition.y > 550) actions.trigger(\"cameraDown\");\n\n sf::Vector2f half_of_camera = camera.getSize() \/ 2.f;\n sf::Vector2f topLeft = camera.getCenter() - (half_of_camera);\n sf::Vector2f downRight = camera.getCenter() + (half_of_camera);\n\n \/\/ Camera constraints take into account an invisible border of 1 cell\n if (topLeft.x <= Cell::TILE_SIZE) camera.setCenter(half_of_camera.x + Cell::TILE_SIZE, camera.getCenter().y);\n if (topLeft.y <= Cell::TILE_SIZE) camera.setCenter(camera.getCenter().x, half_of_camera.y + Cell::TILE_SIZE);\n\n int max_width = (map->getMaxWidth() -1) * Cell::TILE_SIZE;\n int max_height = (map->getMaxHeight() -1) * Cell::TILE_SIZE;\n\n if (downRight.x >= max_width) camera.setCenter(max_width - half_of_camera.x, camera.getCenter().y);\n if (downRight.y >= max_height) camera.setCenter(camera.getCenter().x, max_height - half_of_camera.y);\n\n mouse.setPosition(screen.mapPixelToCoords(mousePosition,camera));\n\n for (auto& unit: units)\n unit.updateState(units, dt);\n\n fpsCounter.update(dt);\n map->prepare(screen.mapPixelToCoords(sf::Vector2i(0,0)));\n}\n\n\nvoid Game::selectUnit(Unit &unit)\n{\n unit.select();\n actions.connect(\"orderMove\", [this, &unit](thor::ActionContext<std::string> context){\n unit.orderMove(screen.mapPixelToCoords(mouse.getHotspot(*context.event), camera));\n });\n mouse.setType(Mouse::Type::Move); \/\/at least one unit selected...\n}\n<commit_msg>camera movement properly uses the time-step instead of the delta<commit_after>#include <iostream>\n\n#include <SFML\/Graphics.hpp>\n#include \"Game.hpp\"\n#include \"Houses.hpp\"\n\nconst sf::Time Game::TimePerFrame = sf::seconds(1.f\/60.f);\n\nGame::Game():\n playing(true),\n screen(),\n map(nullptr),\n console(),\n actions(screen, console),\n unitRepository(messages)\n{\n sf::ContextSettings settings;\n settings.antialiasingLevel = 8;\n screen.create(sf::VideoMode(800, 600), \"Dune 2 - The Maker\", sf::Style::Close, settings);\n screen.setFramerateLimit(IDEAL_FPS);\n screen.setMouseCursorVisible(false);\n\n if (!init()){\n std::cerr << \"Failed to initialized game.\";\n playing = false;\n }\n}\n\nint Game::execute() {\n\n sf::Clock clock;\n sf::Time timeSinceLastUpdate = sf::Time::Zero;\n\n while(playing) {\n dt = clock.restart();\n timeSinceLastUpdate += dt;\n while (timeSinceLastUpdate > TimePerFrame)\n {\n timeSinceLastUpdate -= TimePerFrame;\n\n updateState(TimePerFrame);\n }\n\n render();\n\n }\n\n return 0;\n}\n\nbool Game::init() {\n if (!terrain.loadFromFile(\"graphics\/terrain.png\")) {\n std::cout << \"Failed to read graphics\/terrain.png data\" << std::endl;\n return false;\n }\n\n sf::Image temp;\n if (!temp.loadFromFile(\"graphics\/shroud_edges.bmp\")) {\n std::cout << \"Failed to read graphics\/shroud_edges.bmp data\" << std::endl;\n return false;\n }\n\n temp.createMaskFromColor(sf::Color(255, 0, 255));\n shroudEdges.loadFromImage(temp);\n\n map.reset(new Map(terrain, shroudEdges, messages));\n map->load(\"maps\/4PL_Mountains.ini\");\n\n camera.reset({0,0,800,600});\n screen.setView(camera);\n\n \/\/init two players\n int idCount = 0;\n players.emplace_back(House::Sardaukar, idCount++);\n players.emplace_back(House::Harkonnen, idCount++);\n\n units.push_back(std::move(unitRepository.create(Unit::Type::Trike, players[0], sf::Vector2f(256, 256))));\n units.push_back(std::move(unitRepository.create(Unit::Type::Quad, players[1], sf::Vector2f(300, 300))));\n\n units.push_back(std::move(unitRepository.create(Unit::Type::Soldier, players[0], sf::Vector2f(400, 500))));\n units.push_back(std::move(unitRepository.create(Unit::Type::Soldier, players[0], sf::Vector2f(410, 500))));\n units.push_back(std::move(unitRepository.create(Unit::Type::Soldier, players[0], sf::Vector2f(220, 500))));\n units.push_back(std::move(unitRepository.create(Unit::Type::Soldier, players[0], sf::Vector2f(430, 500))));\n\n units.push_back(std::move(unitRepository.create(Unit::Type::Devastator, players[1], sf::Vector2f(500, 200))));\n\n \/\/register listeners\n typedef thor::ActionContext<std::string> actionContext;\n\n actions.connect(\"close\", [this](actionContext){playing = false;});\n\n actions.connect(\"boxRelease\", [this](actionContext){\n for (auto& unit : units){\n if (box.intersects(unit.getBounds())){\n selectUnit(unit);\n }\n }\n box.clear();\n });\n\n actions.connect(\"boxStart\", [this](actionContext context) {\n if (mouse.getType() != Mouse::Type::Default) {\n return;\n }\n sf::Vector2f toSet = screen.mapPixelToCoords(mouse.getHotspot(*context.event), camera);\n box.setTopLeft(toSet);\n });\n\n actions.connect(\"singleSelect\", [this](actionContext context){\n sf::Vector2f toCheck = screen.mapPixelToCoords(mouse.getHotspot(*context.event), camera);\n for (auto& unit : units){\n if (unit.getBounds().contains(toCheck))\n selectUnit(unit);\n }\n });\n\n actions.connect(\"deselectAll\", [this](actionContext){\n actions.disconnect(\"orderMove\");\n mouse.setType(Mouse::Type::Default);\n for (auto& unit : units)\n unit.unselect();\n });\n\n actions.connect(\"boxDrag\", [this](actionContext){\n box.setBottomRight(screen.mapPixelToCoords(sf::Mouse::getPosition(screen), camera));\n });\n\n const float cameraSpeed = 700.f;\n\n actions.connect(\"cameraLeft\", [this, cameraSpeed](actionContext) {camera.move(-TimePerFrame.asSeconds()*cameraSpeed, 0.f);});\n actions.connect(\"cameraRight\", [this, cameraSpeed](actionContext){camera.move(TimePerFrame.asSeconds()*cameraSpeed, 0.f); });\n actions.connect(\"cameraUp\", [this, cameraSpeed](actionContext) {camera.move(0.f, -TimePerFrame.asSeconds()*cameraSpeed);});\n actions.connect(\"cameraDown\", [this, cameraSpeed](actionContext) {camera.move(0.f, TimePerFrame.asSeconds()*cameraSpeed); });\n\n actions.connect(\"toggleConsole\", std::bind(&Console::toggle, &console));\n\n return true;\n}\n\nvoid Game::render() {\n screen.clear();\n\n screen.setView(camera);\n\n screen.draw(*map);\n\n for (const auto& unit : units)\n screen.draw(unit);\n\n map->drawShrouded(screen, sf::RenderStates::Default);\n\n screen.draw(box);\n\n screen.draw(fpsCounter);\n\n screen.setView(camera);\n\n console.display(screen);\n\n screen.draw(mouse);\n\n screen.display();\n}\n\nvoid Game::updateState(sf::Time dt) {\n\n actions.update();\n console.update(dt);\n\n sf::Vector2i mousePosition = sf::Mouse::getPosition(screen);\n\n if (mousePosition.x < 50 ) actions.trigger(\"cameraLeft\");\n else if (mousePosition.y < 50 ) actions.trigger(\"cameraUp\");\n else if (mousePosition.x > 750) actions.trigger(\"cameraRight\");\n else if (mousePosition.y > 550) actions.trigger(\"cameraDown\");\n\n sf::Vector2f half_of_camera = camera.getSize() \/ 2.f;\n sf::Vector2f topLeft = camera.getCenter() - (half_of_camera);\n sf::Vector2f downRight = camera.getCenter() + (half_of_camera);\n\n \/\/ Camera constraints take into account an invisible border of 1 cell\n if (topLeft.x <= Cell::TILE_SIZE) camera.setCenter(half_of_camera.x + Cell::TILE_SIZE, camera.getCenter().y);\n if (topLeft.y <= Cell::TILE_SIZE) camera.setCenter(camera.getCenter().x, half_of_camera.y + Cell::TILE_SIZE);\n\n int max_width = (map->getMaxWidth() -1) * Cell::TILE_SIZE;\n int max_height = (map->getMaxHeight() -1) * Cell::TILE_SIZE;\n\n if (downRight.x >= max_width) camera.setCenter(max_width - half_of_camera.x, camera.getCenter().y);\n if (downRight.y >= max_height) camera.setCenter(camera.getCenter().x, max_height - half_of_camera.y);\n\n mouse.setPosition(screen.mapPixelToCoords(mousePosition,camera));\n\n for (auto& unit: units)\n unit.updateState(units, dt);\n\n fpsCounter.update(dt);\n map->prepare(screen.mapPixelToCoords(sf::Vector2i(0,0)));\n}\n\n\nvoid Game::selectUnit(Unit &unit)\n{\n unit.select();\n actions.connect(\"orderMove\", [this, &unit](thor::ActionContext<std::string> context){\n unit.orderMove(screen.mapPixelToCoords(mouse.getHotspot(*context.event), camera));\n });\n mouse.setType(Mouse::Type::Move); \/\/at least one unit selected...\n}\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n#include <vector>\n#include <chrono>\n#include \"..\/htmlfile2.h\"\n#include \"..\/..\/DesktopEditor\/common\/File.h\"\n#include \"..\/..\/DesktopEditor\/common\/Directory.h\"\n#include \"..\/..\/OfficeUtils\/src\/OfficeUtils.h\"\n\nvoid getDirectories(std::wstring sDirectory, std::vector<std::wstring>& arrDirectory)\n{\n arrDirectory.push_back(sDirectory);\n for(std::wstring sT : NSDirectory::GetDirectories(sDirectory))\n getDirectories(sT, arrDirectory);\n}\n\nint main()\n{\n bool bBatchMode = false;\n bool bMhtMode = true;\n if(bBatchMode)\n {\n \/\/ Директория файлов\n std::wstring sDirectory = NSFile::GetProcessDirectory() + L\"\/..\/..\/..\/examples\/html\";\n \/\/ Вложенные директории\n std::vector<std::wstring> arrDirectory;\n getDirectories(sDirectory, arrDirectory);\n COfficeUtils oZip;\n \/\/ Выставляем временную директорию\n std::wstring sTmp = NSFile::GetProcessDirectory() + L\"\/tmp\";\n NSDirectory::DeleteDirectory(sTmp);\n NSDirectory::CreateDirectory(sTmp);\n\n for(std::wstring sD : arrDirectory)\n {\n std::vector<std::wstring> arrFiles = NSDirectory::GetFiles(sD);\n \/\/ Директория, где будем создавать docx\n size_t nPos = sD.find(L\"\/html\");\n std::wstring sOutputDirectory = sD.insert(nPos + 5, L\"-res\");\n NSDirectory::CreateDirectory(sOutputDirectory);\n\n for(std::wstring sFile : arrFiles)\n {\n std::wstring sFileName = NSFile::GetFileName(sFile);\n std::wcout << sFileName << std::endl;\n HRESULT nResConvert;\n CHtmlFile2 oFile;\n oFile.SetTmpDirectory(sTmp);\n std::chrono::system_clock::time_point begin = std::chrono::system_clock::now();\n std::chrono::system_clock::time_point end;\n if(bMhtMode)\n {\n if(!oFile.IsMhtFile(sFile))\n {\n std::cout << \"This isn't a mht file\" << std::endl;\n continue;\n }\n end = std::chrono::system_clock::now();\n nResConvert = oFile.OpenMht(sFile, sTmp);\n }\n else\n {\n if(!oFile.IsHtmlFile(sFile))\n {\n std::cout << \"This isn't a html file\" << std::endl;\n continue;\n }\n end = std::chrono::system_clock::now();\n nResConvert = oFile.OpenHtml(sFile, sTmp);\n }\n std::chrono::duration<long, std::milli> dur1 = std::chrono::duration_cast<std::chrono::milliseconds>(end - begin);\n begin = std::chrono::system_clock::now();\n std::chrono::duration<long, std::milli> dur2 = std::chrono::duration_cast<std::chrono::milliseconds>(begin - end);\n if(nResConvert == S_OK)\n {\n std::cout << \"Success \" << dur1.count() << \" \" << dur2.count() << std::endl;\n oZip.CompressFileOrDirectory(sTmp, sOutputDirectory + L\"\/\" + sFileName + L\".docx\");\n NSDirectory::DeleteDirectory(sTmp + L\"\/word\/media\");\n }\n else\n std::cout << \"Failure\" << std::endl;\n }\n }\n }\n else\n {\n HRESULT nResConvert = S_FALSE;\n \/\/ Директория, где будем создавать docx\n std::wstring sOutputDirectory = NSFile::GetProcessDirectory() + L\"\/res\";\n NSDirectory::DeleteDirectory(sOutputDirectory);\n NSDirectory::CreateDirectory(sOutputDirectory);\n\n CHtmlParams oParams;\n oParams.SetAuthors(L\"last first middle;last2 first2 middle2\");\n oParams.SetGenres(L\"fantazy, drama\");\n oParams.SetTitle(L\"The Last Wish\");\n oParams.SetDate(L\"2010-06-03T04:00:00+00:00\");\n oParams.SetDescription(L\"Description\");\n\n \/\/ Файл, который открываем\n std::wstring sFile = NSFile::GetProcessDirectory() + L\"\/..\/..\/..\/examples\/test.mht\";\n CHtmlFile2 oFile;\n oFile.SetTmpDirectory(sOutputDirectory);\n nResConvert = (bMhtMode ? oFile.OpenMht(sFile, sOutputDirectory, &oParams) : oFile.OpenHtml(sFile, sOutputDirectory, &oParams));\n\n if(nResConvert == S_OK)\n {\n std::cout << \"Success\" << std::endl;\n COfficeUtils oZip;\n oZip.CompressFileOrDirectory(sOutputDirectory, sOutputDirectory + L\"\/Aggregate.docx\");\n }\n else\n std::cout << \"Failure\" << std::endl;\n }\n std::cout << \"THE END\" << std::endl;\n return 0;\n}\n<commit_msg>update test htmlfile2<commit_after>#include <iostream>\n#include <vector>\n#include <chrono>\n#include \"..\/htmlfile2.h\"\n#include \"..\/..\/DesktopEditor\/common\/File.h\"\n#include \"..\/..\/DesktopEditor\/common\/Directory.h\"\n#include \"..\/..\/OfficeUtils\/src\/OfficeUtils.h\"\n\nvoid getDirectories(const std::wstring& sDirectory, std::vector<std::wstring>& arrDirectory)\n{\n arrDirectory.push_back(sDirectory);\n for(const std::wstring& sT : NSDirectory::GetDirectories(sDirectory))\n getDirectories(sT, arrDirectory);\n}\n\nint main()\n{\n bool bBatchMode = false;\n bool bMhtMode = true;\n if(bBatchMode)\n {\n \/\/ Директория файлов\n std::wstring sDirectory = NSFile::GetProcessDirectory() + L\"\/..\/..\/..\/examples\/html\";\n \/\/ Вложенные директории\n std::vector<std::wstring> arrDirectory;\n getDirectories(sDirectory, arrDirectory);\n COfficeUtils oZip;\n \/\/ Выставляем временную директорию\n std::wstring sTmp = NSFile::GetProcessDirectory() + L\"\/tmp\";\n NSDirectory::DeleteDirectory(sTmp);\n NSDirectory::CreateDirectory(sTmp);\n\n for(std::wstring sD : arrDirectory)\n {\n std::vector<std::wstring> arrFiles = NSDirectory::GetFiles(sD);\n \/\/ Директория, где будем создавать docx\n size_t nPos = sD.find(L\"\/html\");\n std::wstring sOutputDirectory = sD.insert(nPos + 5, L\"-res\");\n NSDirectory::CreateDirectory(sOutputDirectory);\n\n for(const std::wstring& sFile : arrFiles)\n {\n std::wstring sFileName = NSFile::GetFileName(sFile);\n std::wcout << sFileName << std::endl;\n HRESULT nResConvert;\n CHtmlFile2 oFile;\n oFile.SetTmpDirectory(sTmp);\n std::chrono::system_clock::time_point begin = std::chrono::system_clock::now();\n std::chrono::system_clock::time_point end;\n if(bMhtMode)\n {\n if(!oFile.IsMhtFile(sFile))\n {\n std::cout << \"This isn't a mht file\" << std::endl;\n continue;\n }\n end = std::chrono::system_clock::now();\n nResConvert = oFile.OpenMht(sFile, sTmp);\n }\n else\n {\n if(!oFile.IsHtmlFile(sFile))\n {\n std::cout << \"This isn't a html file\" << std::endl;\n continue;\n }\n end = std::chrono::system_clock::now();\n nResConvert = oFile.OpenHtml(sFile, sTmp);\n }\n std::chrono::duration<long, std::milli> dur1 = std::chrono::duration_cast<std::chrono::milliseconds>(end - begin);\n begin = std::chrono::system_clock::now();\n std::chrono::duration<long, std::milli> dur2 = std::chrono::duration_cast<std::chrono::milliseconds>(begin - end);\n if(nResConvert == S_OK)\n {\n std::cout << \"Success \" << dur1.count() << \" \" << dur2.count() << std::endl;\n oZip.CompressFileOrDirectory(sTmp, sOutputDirectory + L\"\/\" + sFileName + L\".docx\");\n NSDirectory::DeleteDirectory(sTmp + L\"\/word\/media\");\n }\n else\n std::cout << \"Failure\" << std::endl;\n }\n }\n }\n else\n {\n HRESULT nResConvert = S_FALSE;\n \/\/ Директория, где будем создавать docx\n std::wstring sOutputDirectory = NSFile::GetProcessDirectory() + L\"\/res\";\n NSDirectory::DeleteDirectory(sOutputDirectory);\n NSDirectory::CreateDirectory(sOutputDirectory);\n\n CHtmlParams oParams;\n oParams.SetAuthors(L\"last first middle;last2 first2 middle2\");\n oParams.SetGenres(L\"fantazy, drama\");\n oParams.SetTitle(L\"The Last Wish\");\n oParams.SetDate(L\"2010-06-03T04:00:00+00:00\");\n oParams.SetDescription(L\"Description\");\n\n \/\/ Файл, который открываем\n std::wstring sFile = NSFile::GetProcessDirectory() + L\"\/..\/..\/..\/examples\/test.mht\";\n CHtmlFile2 oFile;\n oFile.SetTmpDirectory(sOutputDirectory);\n nResConvert = (bMhtMode ? oFile.OpenMht(sFile, sOutputDirectory, &oParams) : oFile.OpenHtml(sFile, sOutputDirectory, &oParams));\n\n if(nResConvert == S_OK)\n {\n std::cout << \"Success\" << std::endl;\n COfficeUtils oZip;\n oZip.CompressFileOrDirectory(sOutputDirectory, sOutputDirectory + L\"\/Aggregate.docx\");\n }\n else\n std::cout << \"Failure\" << std::endl;\n }\n std::cout << \"THE END\" << std::endl;\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/******************************************************************************\n * Copyright 2018 The Apollo Authors. All Rights Reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *****************************************************************************\/\n\n\/**\n * @file\n **\/\n\n#include <string>\n#include <vector>\n\n#include \"modules\/planning\/scenarios\/traffic_light\/unprotected_right_turn\/stage_intersection_cruise.h\"\n\n#include \"modules\/perception\/proto\/perception_obstacle.pb.h\"\n\n#include \"cyber\/common\/log.h\"\n#include \"modules\/common\/time\/time.h\"\n#include \"modules\/common\/vehicle_state\/vehicle_state_provider.h\"\n#include \"modules\/planning\/common\/frame.h\"\n#include \"modules\/planning\/common\/planning_context.h\"\n#include \"modules\/planning\/tasks\/deciders\/decider_creep.h\"\n\nnamespace apollo {\nnamespace planning {\nnamespace scenario {\nnamespace traffic_light {\n\nusing common::TrajectoryPoint;\nusing hdmap::PathOverlap;\n\nStage::StageStatus\nTrafficLightUnprotectedRightTurnStageIntersectionCruise::Process(\n\n const TrajectoryPoint& planning_init_point, Frame* frame) {\n ADEBUG << \"stage: IntersectionCruise\";\n CHECK_NOTNULL(frame);\n\n bool plan_ok = ExecuteTaskOnReferenceLine(planning_init_point, frame);\n if (!plan_ok) {\n AERROR << \"TrafficLightUnprotectedRightTurnStageIntersectionCruise \"\n << \"plan error\";\n }\n\n \/* TODO(all): to be fixed\n const auto& reference_line_info = frame->reference_line_info().front();\n\n \/\/ check if the traffic_light is still along reference_line\n std::string traffic_light_overlap_id =\n PlanningContext::GetScenarioInfo()->next_traffic_light_overlap.object_id;\n if (CheckTrafficLightDone(reference_line_info, traffic_light_overlap_id)) {\n return FinishScenario();\n }\n\n \/\/ check pass intersection\n \/\/ TODO(all): update when pnc-junction is ready\n constexpr double kIntersectionLength = 10.0; \/\/ unit: m\n const double adc_back_edge_s = reference_line_info.AdcSlBoundary().start_s();\n const double distance_adc_pass_traffic_light =\n adc_back_edge_s -\n PlanningContext::GetScenarioInfo()->next_traffic_light_overlap.end_s;\n if (distance_adc_pass_traffic_light > kIntersectionLength) {\n return FinishStage();\n }\n *\/\n\n return Stage::RUNNING;\n}\n\nStage::StageStatus\nTrafficLightUnprotectedRightTurnStageIntersectionCruise::FinishStage() {\n return FinishScenario();\n}\n\n} \/\/ namespace traffic_light\n} \/\/ namespace scenario\n} \/\/ namespace planning\n} \/\/ namespace apollo\n<commit_msg>planning: intersection_cruise stage for traffic_light_unprotected_right_turn scenario<commit_after>\/******************************************************************************\n * Copyright 2018 The Apollo Authors. All Rights Reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *****************************************************************************\/\n\n\/**\n * @file\n **\/\n#include \"modules\/planning\/scenarios\/traffic_light\/unprotected_right_turn\/stage_intersection_cruise.h\"\n\n#include \"cyber\/common\/log.h\"\n#include \"modules\/planning\/common\/frame.h\"\n#include \"modules\/planning\/common\/planning_context.h\"\n#include \"modules\/planning\/scenarios\/util\/util.h\"\n\n\nnamespace apollo {\nnamespace planning {\nnamespace scenario {\nnamespace traffic_light {\n\nusing common::TrajectoryPoint;\n\nStage::StageStatus\nTrafficLightUnprotectedRightTurnStageIntersectionCruise::Process(\n const TrajectoryPoint& planning_init_point, Frame* frame) {\n ADEBUG << \"stage: IntersectionCruise\";\n CHECK_NOTNULL(frame);\n\n bool plan_ok = ExecuteTaskOnReferenceLine(planning_init_point, frame);\n if (!plan_ok) {\n AERROR << \"TrafficLightUnprotectedRightTurnStageIntersectionCruise \"\n << \"plan error\";\n }\n\n const auto& reference_line_info = frame->reference_line_info().front();\n\n \/\/ check pass pnc_junction\n \/\/ TODO(all): remove when pnc_junction completely available on map\n const auto& pnc_junction_overlaps =\n reference_line_info.reference_line().map_path().pnc_junction_overlaps();\n if (pnc_junction_overlaps.size() == 0) {\n \/\/ pnc_junction not exist on map, use current traffic_light's end_s\n if (PlanningContext::GetScenarioInfo()\n ->current_traffic_light_overlaps.size() == 0) {\n return FinishStage();\n }\n\n constexpr double kIntersectionPassDist = 20.0; \/\/ unit: m\n const double adc_back_edge_s =\n reference_line_info.AdcSlBoundary().start_s();\n const double traffic_light_end_s = PlanningContext::GetScenarioInfo()\n ->current_traffic_light_overlaps[0].end_s;\n const double distance_adc_pass_traffic_light = adc_back_edge_s -\n traffic_light_end_s;\n ADEBUG << \"distance_adc_pass_traffic_light[\"\n << distance_adc_pass_traffic_light\n << \"] traffic_light_end_s[\" << traffic_light_end_s << \"]\";\n\n if (distance_adc_pass_traffic_light >= kIntersectionPassDist) {\n return FinishStage();\n } else {\n return Stage::RUNNING;\n }\n }\n\n if (!scenario::CheckInsidePnCJunction(reference_line_info)) {\n return FinishStage();\n }\n\n return Stage::RUNNING;\n}\n\nStage::StageStatus\nTrafficLightUnprotectedRightTurnStageIntersectionCruise::FinishStage() {\n return FinishScenario();\n}\n\n} \/\/ namespace traffic_light\n} \/\/ namespace scenario\n} \/\/ namespace planning\n} \/\/ namespace apollo\n<|endoftext|>"} {"text":"<commit_before>\/***********************************************************************************************************************\n **\n ** Copyright (c) 2011, 2015 ETH Zurich\n ** All rights reserved.\n **\n ** Redistribution and use in source and binary forms, with or without modification, are permitted provided that the\n ** following conditions are met:\n **\n ** * Redistributions of source code must retain the above copyright notice, this list of conditions and the\n ** following disclaimer.\n ** * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the\n ** following disclaimer in the documentation and\/or other materials provided with the distribution.\n ** * Neither the name of the ETH Zurich nor the names of its contributors may be used to endorse or promote products\n ** derived from this software without specific prior written permission.\n **\n **\n ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES,\n ** INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n ** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n ** SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n ** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n **\n **********************************************************************************************************************\/\n\n#include \"MacroDefinitions.h\"\n#include \"..\/ClangHelpers.h\"\n\n#include \"OOModel\/src\/expressions\/ReferenceExpression.h\"\n#include \"OOModel\/src\/declarations\/Project.h\"\n\nnamespace CppImport {\n\nMacroDefinitions::MacroDefinitions(ClangHelpers& clang) : clang_{clang}\n{\n\tif (directoryToNamespaceMap_.isEmpty())\n\t{\n\t\tdirectoryToNamespaceMap_.insert(\"ModelBase\", \"Model\");\n\t\tdirectoryToNamespaceMap_.insert(\"VisualizationBase\", \"Visualization\");\n\t\tdirectoryToNamespaceMap_.insert(\"InteractionBase\", \"Interaction\");\n\t}\n}\n\nQString MacroDefinitions::definitionName(const clang::MacroDirective* md) const\n{\n\tauto it = definitions_.find(md);\n\n\treturn it != definitions_.end() ? *it : nullptr;\n}\n\nQString MacroDefinitions::signature(const clang::MacroDirective* md) const\n{\n\tQString namespaceName, fileName;\n\n\tauto parentProject = clang_.projectForLocation(md->getLocation());\n\tif (parentProject != clang_.rootProject())\n\t\treturn parentProject->name() + \"\/\" + definitionName(md);\n\telse\n\t\treturn \"\/ExternalMacro\/\" + definitionName(md);\n}\n\nOOModel::ReferenceExpression* MacroDefinitions::expansionQualifier(const clang::MacroDirective* md) const\n{\n\tauto parentProject = clang_.projectForLocation(md->getLocation());\n\tif (parentProject == clang_.rootProject())\n\t\treturn new OOModel::ReferenceExpression{\"ExternalMacro\"};\n\n\treturn {};\n}\n\n}\n<commit_msg>remove unused variables<commit_after>\/***********************************************************************************************************************\n **\n ** Copyright (c) 2011, 2015 ETH Zurich\n ** All rights reserved.\n **\n ** Redistribution and use in source and binary forms, with or without modification, are permitted provided that the\n ** following conditions are met:\n **\n ** * Redistributions of source code must retain the above copyright notice, this list of conditions and the\n ** following disclaimer.\n ** * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the\n ** following disclaimer in the documentation and\/or other materials provided with the distribution.\n ** * Neither the name of the ETH Zurich nor the names of its contributors may be used to endorse or promote products\n ** derived from this software without specific prior written permission.\n **\n **\n ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES,\n ** INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n ** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n ** SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n ** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n **\n **********************************************************************************************************************\/\n\n#include \"MacroDefinitions.h\"\n#include \"..\/ClangHelpers.h\"\n\n#include \"OOModel\/src\/expressions\/ReferenceExpression.h\"\n#include \"OOModel\/src\/declarations\/Project.h\"\n\nnamespace CppImport {\n\nMacroDefinitions::MacroDefinitions(ClangHelpers& clang) : clang_{clang}\n{\n\tif (directoryToNamespaceMap_.isEmpty())\n\t{\n\t\tdirectoryToNamespaceMap_.insert(\"ModelBase\", \"Model\");\n\t\tdirectoryToNamespaceMap_.insert(\"VisualizationBase\", \"Visualization\");\n\t\tdirectoryToNamespaceMap_.insert(\"InteractionBase\", \"Interaction\");\n\t}\n}\n\nQString MacroDefinitions::definitionName(const clang::MacroDirective* md) const\n{\n\tauto it = definitions_.find(md);\n\n\treturn it != definitions_.end() ? *it : nullptr;\n}\n\nQString MacroDefinitions::signature(const clang::MacroDirective* md) const\n{\n\tauto parentProject = clang_.projectForLocation(md->getLocation());\n\tif (parentProject != clang_.rootProject())\n\t\treturn parentProject->name() + \"\/\" + definitionName(md);\n\telse\n\t\treturn \"\/ExternalMacro\/\" + definitionName(md);\n}\n\nOOModel::ReferenceExpression* MacroDefinitions::expansionQualifier(const clang::MacroDirective* md) const\n{\n\tauto parentProject = clang_.projectForLocation(md->getLocation());\n\tif (parentProject == clang_.rootProject())\n\t\treturn new OOModel::ReferenceExpression{\"ExternalMacro\"};\n\n\treturn {};\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright 2013-2014 gtalent2@gmail.com\n * \n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * \n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n#ifdef WITH_SDL\n#include <vector>\n\n#include <SDL.h>\n\n#include \"_sdlglobs.hpp\"\n#include \"core.hpp\"\n\nnamespace wombat {\nnamespace core {\n\nclass EventQueueSemaphore: public BaseSemaphore {\n\tprivate:\n\t\tstd::queue<Event> m_posts;\n\t\tMutex m_mutex;\n\n\tpublic:\n\t\t\/**\n\t\t * Constructor\n\t\t *\/\n\t\tEventQueueSemaphore();\n\n\t\t\/**\n\t\t * Destructor\n\t\t *\/\n\t\t~EventQueueSemaphore();\n\n\t\tEvent wait();\n\n\t\tEvent wait(uint64 timeout);\n\n\t\tvoid post(Event wakeup = SemaphorePost);\n\n\t\tint popPost(Event &post);\n\n\t\tbool hasPosts();\n\n\t\/\/ disallow copying\n\tprivate:\n\t\tEventQueueSemaphore(const EventQueueSemaphore&);\n\t\tEventQueueSemaphore &operator=(const EventQueueSemaphore&);\n} _mainSemaphore;\n\nTaskProcessor _taskProcessor(&_mainSemaphore);\n\nconst auto Event_DrawEvent = SDL_RegisterEvents(1);\nconst auto Event_SemaporePost = SDL_RegisterEvents(1);\nconst auto Event_SemaporeTimeout = SDL_RegisterEvents(1);\n\nstd::vector<Drawer*> drawers;\nstd::vector<Graphics*> graphicsInstances;\nSDL_Window *display = 0;\nSDL_Renderer *renderer = 0;\n\nextern std::vector<EventHandler> eventHandlers;\nextern bool _running;\n\n\nKey toWombatKey(SDL_Event);\nvoid _updateEventTime();\n\n\/\/ EventQueueSemaphore Implementation\n\nEventQueueSemaphore::EventQueueSemaphore() {\n}\n\nEventQueueSemaphore::~EventQueueSemaphore() {\n}\n\nEvent EventQueueSemaphore::wait() {\n\treturn UnknownEvent;\n}\n\nEvent EventQueueSemaphore::wait(uint64 timeout) {\n\treturn UnknownEvent;\n}\n\nvoid EventQueueSemaphore::post(Event post) {\n\tm_mutex.lock();\n\tm_posts.push(post);\n\tSDL_Event ev;\n\tSDL_zero(ev);\n\tev.type = Event_SemaporePost;\n\tSDL_PushEvent(&ev);\n\tm_mutex.unlock();\n}\n\nint EventQueueSemaphore::popPost(Event &post) {\n\tm_mutex.lock();\n\tif (hasPosts()) {\n\t\tpost = m_posts.front();\n\t\tm_posts.pop();\n\t\tm_mutex.unlock();\n\t\treturn 0;\n\t}\n\tm_mutex.unlock();\n\treturn 1;\n}\n\nbool EventQueueSemaphore::hasPosts() {\n\treturn m_posts.size();\n}\n\n\/\/ Main TaskProcessor modifiers\n\nvoid addTask(std::function<TaskState(Event)> task, TaskState state) {\n\t_taskProcessor.addTask(task, state);\n}\n\nvoid addTask(Task *task, TaskState state) {\n\t_taskProcessor.addTask(task, state);\n}\n\nvoid draw() {\n\tSDL_Event ev;\n\tSDL_zero(ev);\n\tev.type = Event_DrawEvent;\n\tSDL_PushEvent(&ev);\n}\n\nvoid _draw() {\n\tSDL_RenderClear(renderer);\n\tfor (int i = 0; i < drawers.size(); i++) {\n\t\tdrawers[i]->draw(graphicsInstances[i]);\n\t}\n\tSDL_RenderPresent(renderer);\n}\n\nvoid main() {\n\t\/\/ handle events\n\tSDL_Event sev;\n\tTaskState taskState = TaskState::Waiting;\n\twhile (_running) {\n\t\tif (taskState.state == TaskState::Running) {\n\t\t\tif (SDL_WaitEventTimeout(&sev, taskState.sleepDuration) == 0) {\n\t\t\t\t\/\/ yes... SDL_WaitEventTimeout uses 0 indicate failure...\n\t\t\t\tsev.type = Event_SemaporeTimeout;\n\t\t\t}\n\t\t} else {\n\t\t\tSDL_WaitEvent(&sev);\n\t\t}\n\n\t\tconst auto t = sev.type;\n\t\tEvent ev;\n\t\t_updateEventTime();\n\t\tif (t == Event_DrawEvent) {\n\t\t\t_draw();\n\t\t} else if (sev.type == Event_SemaporeTimeout) {\n\t\t\tev.m_type = Timeout;\n\t\t\ttaskState = _taskProcessor.run(ev);\n\t\t} else if (sev.type == Event_SemaporePost) {\n\t\t\tif (_mainSemaphore.popPost(ev) == 0) {\n\t\t\t\ttaskState = _taskProcessor.run(ev);\n\t\t\t}\n\t\t} else {\n\t\t\tif (t == SDL_QUIT) {\n\t\t\t\tev.m_type = QuitEvent;\n\t\t\t} else if (t == SDL_KEYUP) {\n\t\t\t\tev.m_type = KeyUpEvent;\n\t\t\t\tev.m_body.key = toWombatKey(sev);\n\t\t\t} else if (t == SDL_KEYDOWN) {\n\t\t\t\tev.m_type = KeyDownEvent;\n\t\t\t\tev.m_body.key = toWombatKey(sev);\n\t\t\t}\n\n\t\t\tfor (auto f : eventHandlers) {\n\t\t\t\tf(ev);\n\t\t\t}\n\t\t}\n\t}\n}\n\nint init(bool fullscreen, int w, int h) {\n\tif (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_EVENTS | SDL_INIT_TIMER) == -1) {\n\t\treturn -1;\n\t}\n\n\tauto flags = SDL_WINDOW_OPENGL;\n\tif (fullscreen) {\n\t\tflags = (SDL_WindowFlags) (flags | SDL_WINDOW_FULLSCREEN_DESKTOP);\n\t} else {\n\t\tflags = (SDL_WindowFlags) (flags | SDL_WINDOW_RESIZABLE);\n\t}\n\tdisplay = SDL_CreateWindow(\"Wombat\", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, w, h, flags);\n\tif (!display)\n\t\treturn -3;\n\trenderer = SDL_CreateRenderer(display, -1, SDL_RENDERER_ACCELERATED);\n\n\t_running = true; _updateEventTime();\n\treturn 0;\n}\n\nvoid addDrawer(Drawer *d) {\n\tgraphicsInstances.push_back(new Graphics());\n\tdrawers.push_back(d);\n}\n\n}\n}\n\n#endif\n<commit_msg>Fixed event processing not to feed garbage events to event handlers.<commit_after>\/*\n * Copyright 2013-2014 gtalent2@gmail.com\n * \n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * \n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n#ifdef WITH_SDL\n#include <vector>\n\n#include <SDL.h>\n\n#include \"_sdlglobs.hpp\"\n#include \"core.hpp\"\n\nnamespace wombat {\nnamespace core {\n\nclass EventQueueSemaphore: public BaseSemaphore {\n\tprivate:\n\t\tstd::queue<Event> m_posts;\n\t\tMutex m_mutex;\n\n\tpublic:\n\t\t\/**\n\t\t * Constructor\n\t\t *\/\n\t\tEventQueueSemaphore();\n\n\t\t\/**\n\t\t * Destructor\n\t\t *\/\n\t\t~EventQueueSemaphore();\n\n\t\tEvent wait();\n\n\t\tEvent wait(uint64 timeout);\n\n\t\tvoid post(Event wakeup = SemaphorePost);\n\n\t\tint popPost(Event &post);\n\n\t\tbool hasPosts();\n\n\t\/\/ disallow copying\n\tprivate:\n\t\tEventQueueSemaphore(const EventQueueSemaphore&);\n\t\tEventQueueSemaphore &operator=(const EventQueueSemaphore&);\n} _mainSemaphore;\n\nTaskProcessor _taskProcessor(&_mainSemaphore);\n\nconst auto Event_DrawEvent = SDL_RegisterEvents(1);\nconst auto Event_SemaporePost = SDL_RegisterEvents(1);\nconst auto Event_SemaporeTimeout = SDL_RegisterEvents(1);\n\nstd::vector<Drawer*> drawers;\nstd::vector<Graphics*> graphicsInstances;\nSDL_Window *display = 0;\nSDL_Renderer *renderer = 0;\n\nextern std::vector<EventHandler> eventHandlers;\nextern bool _running;\n\n\nKey toWombatKey(SDL_Event);\nvoid _updateEventTime();\n\n\/\/ EventQueueSemaphore Implementation\n\nEventQueueSemaphore::EventQueueSemaphore() {\n}\n\nEventQueueSemaphore::~EventQueueSemaphore() {\n}\n\nEvent EventQueueSemaphore::wait() {\n\treturn UnknownEvent;\n}\n\nEvent EventQueueSemaphore::wait(uint64 timeout) {\n\treturn UnknownEvent;\n}\n\nvoid EventQueueSemaphore::post(Event post) {\n\tm_mutex.lock();\n\tm_posts.push(post);\n\tSDL_Event ev;\n\tSDL_zero(ev);\n\tev.type = Event_SemaporePost;\n\tSDL_PushEvent(&ev);\n\tm_mutex.unlock();\n}\n\nint EventQueueSemaphore::popPost(Event &post) {\n\tm_mutex.lock();\n\tif (hasPosts()) {\n\t\tpost = m_posts.front();\n\t\tm_posts.pop();\n\t\tm_mutex.unlock();\n\t\treturn 0;\n\t}\n\tm_mutex.unlock();\n\treturn 1;\n}\n\nbool EventQueueSemaphore::hasPosts() {\n\treturn m_posts.size();\n}\n\n\/\/ Main TaskProcessor modifiers\n\nvoid addTask(std::function<TaskState(Event)> task, TaskState state) {\n\t_taskProcessor.addTask(task, state);\n}\n\nvoid addTask(Task *task, TaskState state) {\n\t_taskProcessor.addTask(task, state);\n}\n\nvoid draw() {\n\tSDL_Event ev;\n\tSDL_zero(ev);\n\tev.type = Event_DrawEvent;\n\tSDL_PushEvent(&ev);\n}\n\nvoid _draw() {\n\tSDL_RenderClear(renderer);\n\tfor (int i = 0; i < drawers.size(); i++) {\n\t\tdrawers[i]->draw(graphicsInstances[i]);\n\t}\n\tSDL_RenderPresent(renderer);\n}\n\nvoid main() {\n\t\/\/ handle events\n\tSDL_Event sev;\n\tTaskState taskState = TaskState::Waiting;\n\twhile (_running) {\n\t\tif (taskState.state == TaskState::Running) {\n\t\t\tif (SDL_WaitEventTimeout(&sev, taskState.sleepDuration) == 0) {\n\t\t\t\t\/\/ yes... SDL_WaitEventTimeout uses 0 indicate failure...\n\t\t\t\tsev.type = Event_SemaporeTimeout;\n\t\t\t}\n\t\t} else {\n\t\t\tSDL_WaitEvent(&sev);\n\t\t}\n\n\t\tconst auto t = sev.type;\n\t\tEvent ev;\n\t\t_updateEventTime();\n\t\tif (t == Event_DrawEvent) {\n\t\t\t_draw();\n\t\t} else if (sev.type == Event_SemaporeTimeout) {\n\t\t\tev.m_type = Timeout;\n\t\t\ttaskState = _taskProcessor.run(ev);\n\t\t} else if (sev.type == Event_SemaporePost) {\n\t\t\tif (_mainSemaphore.popPost(ev) == 0) {\n\t\t\t\ttaskState = _taskProcessor.run(ev);\n\t\t\t}\n\t\t} else if (t == SDL_QUIT) {\n\t\t\tev.m_type = QuitEvent;\n\n\t\t\tfor (auto f : eventHandlers) {\n\t\t\t\tf(ev);\n\t\t\t}\n\t\t} else if (t == SDL_KEYUP) {\n\t\t\tev.m_type = KeyUpEvent;\n\t\t\tev.m_body.key = toWombatKey(sev);\n\n\t\t\tfor (auto f : eventHandlers) {\n\t\t\t\tf(ev);\n\t\t\t}\n\t\t} else if (t == SDL_KEYDOWN) {\n\t\t\tev.m_type = KeyDownEvent;\n\t\t\tev.m_body.key = toWombatKey(sev);\n\n\t\t\tfor (auto f : eventHandlers) {\n\t\t\t\tf(ev);\n\t\t\t}\n\t\t}\n\t}\n}\n\nint init(bool fullscreen, int w, int h) {\n\tif (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_EVENTS | SDL_INIT_TIMER) == -1) {\n\t\treturn -1;\n\t}\n\n\tauto flags = SDL_WINDOW_OPENGL;\n\tif (fullscreen) {\n\t\tflags = (SDL_WindowFlags) (flags | SDL_WINDOW_FULLSCREEN_DESKTOP);\n\t} else {\n\t\tflags = (SDL_WindowFlags) (flags | SDL_WINDOW_RESIZABLE);\n\t}\n\tdisplay = SDL_CreateWindow(\"Wombat\", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, w, h, flags);\n\tif (!display)\n\t\treturn -3;\n\trenderer = SDL_CreateRenderer(display, -1, SDL_RENDERER_ACCELERATED);\n\n\t_running = true; _updateEventTime();\n\treturn 0;\n}\n\nvoid addDrawer(Drawer *d) {\n\tgraphicsInstances.push_back(new Graphics());\n\tdrawers.push_back(d);\n}\n\n}\n}\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>#include <pybind11\/embed.h>\n\n#include <iostream>\n#include <unistd.h>\n#include <vector>\n\n#ifdef __APPLE__\n#include <util.h>\n#include <sys\/ioctl.h>\n#else\n#include <pty.h>\n#endif\n\n#include <termios.h>\n#include <fcntl.h>\n#include <signal.h>\n\n#include <string.h>\n\n#include <sys\/select.h>\n#include <sys\/wait.h>\n\n#include \"plugin_manager.h\"\n#include \"plugin.h\"\n#include \"term_network.h\"\n#include \"term_data_handler.h\"\n#include \"term_context.h\"\n#include \"term_window.h\"\n\n#include \"PortableThread.h\"\n\n#include \"app_config_impl.h\"\n\nstatic\nvoid delete_data(void * data);\n\nclass TermNetworkPty\n : public virtual Plugin\n , public virtual TermNetwork\n , public virtual PortableThread::IPortableRunnable\n{\npublic:\n TermNetworkPty() :\n Plugin()\n , m_Name(\"term_network_use_pty\")\n , m_Description(\"terminal network plugin using pty\")\n , m_Version(1)\n , m_Rows(0)\n , m_Cols(0)\n , m_MasterFD(-1)\n , m_ReadBuffer(8192)\n , m_PtyReaderThread(this)\n {\n }\n\n virtual ~TermNetworkPty() = default;\n\n MultipleInstancePluginPtr NewInstance() override {\n return MultipleInstancePluginPtr{new TermNetworkPty, delete_data};\n }\n\n bool m_Stopped;\n void Disconnect() override {\n m_Stopped = true;\n\n if (m_MasterFD == -1)\n return;\n\n close(m_MasterFD);\n m_PtyReaderThread.Join();\n }\n\n const char * GetName() override {\n return m_Name.c_str();\n }\n const char * GetDescription() override {\n return m_Description.c_str();\n }\n\n uint32_t GetVersion() override {\n return m_Version;\n }\n\n ContextPtr GetPluginContext() const override {\n return m_Context;\n }\n\n AppConfigPtr GetPluginConfig() const override {\n return m_PluginConfig;\n }\n\n void InitPlugin(ContextPtr context,\n AppConfigPtr plugin_config) override {\n m_Context = context;\n m_PluginConfig = plugin_config;\n }\nprivate:\n std::string m_Name;\n std::string m_Description;\n uint32_t m_Version;\n\nprotected:\n ContextPtr m_Context;\n AppConfigPtr m_PluginConfig;\n\n std::shared_ptr<char> m_TermName;\n std::shared_ptr<char> m_CmdLine;\n std::vector<char *> m_Args;\n\npublic:\n void BuildEnviron() {\n m_Envs.clear();\n\n extern char ** environ;\n\n char ** tmp = environ;\n\n std::string term_name = \"TERM=\" + GetPluginContext()->GetAppConfig()->GetEntry(\"\/term\/term_name\", \"xterm-256color\");\n\n m_TermName = {strdup(term_name.c_str()), [](char * data) {\n free(data);\n }};\n\n bool term_updated = false;\n while(*tmp) {\n if (term_name != \"NOT FOUND\" && !strncmp(*tmp, \"TERM=\", strlen(\"TERM=\")))\n {\n m_Envs.push_back(m_TermName.get());\n term_updated = true;\n }\n else\n {\n m_Envs.push_back(*tmp);\n }\n tmp++;\n }\n\n if (!term_updated) {\n m_Envs.push_back(m_TermName.get());\n }\n\n m_Envs.push_back(NULL);\n }\n\n void BuildCmdLine(const std::string & cmd_line)\n {\n m_CmdLine = {\n strdup(cmd_line.c_str()), [](char * data) {\n free(data);\n }};\n\n char * token = strtok(m_CmdLine.get(), \" \");\n\n m_Args.clear();\n\n while(token != NULL) {\n m_Args.push_back(token);\n token = strtok(NULL, \" \");\n }\n\n m_Args.push_back(NULL);\n }\n\n void Connect(const char * host, int port, const char * user_name, const char * password) override {\n (void)host;\n (void)port;\n (void)user_name;\n (void)password;\n\n m_Stopped = false;\n\n pid_t pid;\n struct winsize ws {\n (unsigned short)m_Rows,\n (unsigned short)m_Cols,\n 0,\n 0\n };\n\n std::string shell = GetPluginConfig()->GetEntry(\"shell\", \"NOT FOUND\");\n\n if (shell == \"NOT FOUND\")\n {\n char * sys_shell = getenv(\"SHELL\");\n\n if (sys_shell)\n shell = std::string(sys_shell);\n else\n shell = std::string(\"\/bin\/bash -i -l\");\n }\n\n BuildEnviron();\n\n BuildCmdLine(shell);\n\n pid = forkpty(&m_MasterFD, NULL, NULL, &ws);\n\n \/\/ impossible to fork\n if (pid < 0) {\n std::cerr << \"pty fork failed\" << std::endl;\n return;\n }\n \/\/ child\n else if (pid == 0) {\n#ifdef __APPLE__\n execve(m_Args[0], &m_Args[0], &m_Envs[0]);\n#else\n execvpe(m_Args[0], &m_Args[0], &m_Envs[0]);\n#endif\n }\n \/\/ parent\n else {\n m_PtyPid = pid;\n int flags = fcntl(m_MasterFD, F_GETFL, 0);\n fcntl(m_MasterFD, F_SETFL, flags | O_NONBLOCK);\n\n m_PtyReaderThread.Start();\n }\n }\n\n void Send(const std::vector<unsigned char> & data, size_t n) override {\n if (write(m_MasterFD, &data[0], n) <= 0) {\n std::cerr << \"write failed:\" << strerror(errno) << std::endl;\n }\n }\n\n void Resize(uint32_t row, uint32_t col) override {\n m_Rows = row;\n m_Cols = col;\n \/*\n struct winsize {\n unsigned short ws_row;\n unsigned short ws_col;\n unsigned short ws_xpixel; \/ unused \/\n unsigned short ws_ypixel; \/ unused \/\n };\n *\/\n\n if (m_MasterFD == -1)\n return;\n\n struct winsize ws {\n (unsigned short)row,\n (unsigned short)col,\n 0,\n 0\n };\n\n int result = ioctl(m_MasterFD, TIOCSWINSZ, &ws);\n if (result) {\n std::cerr << \"resize result:\" << result << \",\" << errno\n << \", \" << EINVAL\n << \", \" << ENOTTY\n << \", \" << EPERM\n << \", \" << strerror(errno)\n << std::endl;\n }\n }\n\n unsigned long Run(void * \/*pArgument*\/) override {\n struct timeval tv;\n\n TermContextPtr context = std::dynamic_pointer_cast<TermContext>(GetPluginContext());\n\n if (!context)\n return 0;\n\n TermDataHandlerPtr term_data_handler =\n context->GetTermDataHandler();\n TermWindowPtr term_window =\n context->GetTermWindow();\n\n for (;;) {\n\n fd_set read_fd;\n fd_set except_fd;\n\n tv.tv_sec = 1;\n tv.tv_usec = 0;\n\n FD_ZERO(&read_fd);\n FD_ZERO(&except_fd);\n\n FD_SET(m_MasterFD, &read_fd);\n FD_SET(m_MasterFD, &except_fd);\n\n int result = select(m_MasterFD+1, &read_fd, NULL, &except_fd, &tv);\n\n if (m_Stopped)\n break;\n\n if (result == -1) {\n if (errno == EINTR) {\n continue;\n }\n\n std::cerr << \"select failed with err:\" << errno << std::endl;\n break;\n } else if (result == 0) {\n \/\/timeout\n continue;\n }\n\n if (FD_ISSET(m_MasterFD, &except_fd))\n {\n term_window->Close();\n break;\n }\n\n if (FD_ISSET(m_MasterFD, &read_fd))\n {\n int count = read(m_MasterFD, &m_ReadBuffer[0], m_ReadBuffer.size());\n if (count == -1) {\n if (errno == EINTR)\n continue;\n\n std::cerr << \"read failed\\n\" << std::endl;\n term_window->Close();\n break;\n }\n\n if (count > 0) {\n term_data_handler->OnData(m_ReadBuffer, count);\n }\n }\n }\n return 0;\n }\nprivate:\n uint32_t m_Rows;\n uint32_t m_Cols;\n int m_MasterFD;\n std::vector<unsigned char> m_ReadBuffer;\n PortableThread::CPortableThread m_PtyReaderThread;\n std::vector<char *> m_Envs;\n pid_t m_PtyPid;\n};\n\nvoid delete_data(void * data) {\n delete (Plugin*)data;\n}\n\nextern \"C\"\nvoid register_plugins(PluginManagerPtr plugin_manager) {\n plugin_manager->RegisterPlugin(PluginPtr {new TermNetworkPty, delete_data});;\n}\n<commit_msg>add tcdrain for write pty<commit_after>#include <pybind11\/embed.h>\n\n#include <iostream>\n#include <unistd.h>\n#include <vector>\n\n#ifdef __APPLE__\n#include <util.h>\n#include <sys\/ioctl.h>\n#else\n#include <pty.h>\n#endif\n\n#include <termios.h>\n#include <fcntl.h>\n#include <signal.h>\n\n#include <string.h>\n\n#include <sys\/select.h>\n#include <sys\/wait.h>\n\n#include \"plugin_manager.h\"\n#include \"plugin.h\"\n#include \"term_network.h\"\n#include \"term_data_handler.h\"\n#include \"term_context.h\"\n#include \"term_window.h\"\n\n#include \"PortableThread.h\"\n\n#include \"app_config_impl.h\"\n\nstatic\nvoid delete_data(void * data);\n\nclass TermNetworkPty\n : public virtual Plugin\n , public virtual TermNetwork\n , public virtual PortableThread::IPortableRunnable\n{\npublic:\n TermNetworkPty() :\n Plugin()\n , m_Name(\"term_network_use_pty\")\n , m_Description(\"terminal network plugin using pty\")\n , m_Version(1)\n , m_Rows(0)\n , m_Cols(0)\n , m_MasterFD(-1)\n , m_ReadBuffer(8192)\n , m_PtyReaderThread(this)\n {\n }\n\n virtual ~TermNetworkPty() = default;\n\n MultipleInstancePluginPtr NewInstance() override {\n return MultipleInstancePluginPtr{new TermNetworkPty, delete_data};\n }\n\n bool m_Stopped;\n void Disconnect() override {\n m_Stopped = true;\n\n if (m_MasterFD == -1)\n return;\n\n close(m_MasterFD);\n m_PtyReaderThread.Join();\n }\n\n const char * GetName() override {\n return m_Name.c_str();\n }\n const char * GetDescription() override {\n return m_Description.c_str();\n }\n\n uint32_t GetVersion() override {\n return m_Version;\n }\n\n ContextPtr GetPluginContext() const override {\n return m_Context;\n }\n\n AppConfigPtr GetPluginConfig() const override {\n return m_PluginConfig;\n }\n\n void InitPlugin(ContextPtr context,\n AppConfigPtr plugin_config) override {\n m_Context = context;\n m_PluginConfig = plugin_config;\n }\nprivate:\n std::string m_Name;\n std::string m_Description;\n uint32_t m_Version;\n\nprotected:\n ContextPtr m_Context;\n AppConfigPtr m_PluginConfig;\n\n std::shared_ptr<char> m_TermName;\n std::shared_ptr<char> m_CmdLine;\n std::vector<char *> m_Args;\n\npublic:\n void BuildEnviron() {\n m_Envs.clear();\n\n extern char ** environ;\n\n char ** tmp = environ;\n\n std::string term_name = \"TERM=\" + GetPluginContext()->GetAppConfig()->GetEntry(\"\/term\/term_name\", \"xterm-256color\");\n\n m_TermName = {strdup(term_name.c_str()), [](char * data) {\n free(data);\n }};\n\n bool term_updated = false;\n while(*tmp) {\n if (term_name != \"NOT FOUND\" && !strncmp(*tmp, \"TERM=\", strlen(\"TERM=\")))\n {\n m_Envs.push_back(m_TermName.get());\n term_updated = true;\n }\n else\n {\n m_Envs.push_back(*tmp);\n }\n tmp++;\n }\n\n if (!term_updated) {\n m_Envs.push_back(m_TermName.get());\n }\n\n m_Envs.push_back(NULL);\n }\n\n void BuildCmdLine(const std::string & cmd_line)\n {\n m_CmdLine = {\n strdup(cmd_line.c_str()), [](char * data) {\n free(data);\n }};\n\n char * token = strtok(m_CmdLine.get(), \" \");\n\n m_Args.clear();\n\n while(token != NULL) {\n m_Args.push_back(token);\n token = strtok(NULL, \" \");\n }\n\n m_Args.push_back(NULL);\n }\n\n void Connect(const char * host, int port, const char * user_name, const char * password) override {\n (void)host;\n (void)port;\n (void)user_name;\n (void)password;\n\n m_Stopped = false;\n\n pid_t pid;\n struct winsize ws {\n (unsigned short)m_Rows,\n (unsigned short)m_Cols,\n 0,\n 0\n };\n\n std::string shell = GetPluginConfig()->GetEntry(\"shell\", \"NOT FOUND\");\n\n if (shell == \"NOT FOUND\")\n {\n char * sys_shell = getenv(\"SHELL\");\n\n if (sys_shell)\n shell = std::string(sys_shell);\n else\n shell = std::string(\"\/bin\/bash -i -l\");\n }\n\n BuildEnviron();\n\n BuildCmdLine(shell);\n\n pid = forkpty(&m_MasterFD, NULL, NULL, &ws);\n\n \/\/ impossible to fork\n if (pid < 0) {\n std::cerr << \"pty fork failed\" << std::endl;\n return;\n }\n \/\/ child\n else if (pid == 0) {\n#ifdef __APPLE__\n execve(m_Args[0], &m_Args[0], &m_Envs[0]);\n#else\n execvpe(m_Args[0], &m_Args[0], &m_Envs[0]);\n#endif\n }\n \/\/ parent\n else {\n m_PtyPid = pid;\n int flags = fcntl(m_MasterFD, F_GETFL, 0);\n fcntl(m_MasterFD, F_SETFL, flags | O_NONBLOCK);\n\n m_PtyReaderThread.Start();\n }\n }\n\n void Send(const std::vector<unsigned char> & data, size_t n) override {\n if (write(m_MasterFD, &data[0], n) <= 0) {\n std::cerr << \"write failed:\" << strerror(errno) << std::endl;\n }\n\n if (tcdrain(m_MasterFD))\n std::cerr << \"tcdrain failed:\" << strerror(errno) << std::endl;\n }\n\n void Resize(uint32_t row, uint32_t col) override {\n m_Rows = row;\n m_Cols = col;\n \/*\n struct winsize {\n unsigned short ws_row;\n unsigned short ws_col;\n unsigned short ws_xpixel; \/ unused \/\n unsigned short ws_ypixel; \/ unused \/\n };\n *\/\n\n if (m_MasterFD == -1)\n return;\n\n struct winsize ws {\n (unsigned short)row,\n (unsigned short)col,\n 0,\n 0\n };\n\n int result = ioctl(m_MasterFD, TIOCSWINSZ, &ws);\n if (result) {\n std::cerr << \"resize result:\" << result << \",\" << errno\n << \", \" << EINVAL\n << \", \" << ENOTTY\n << \", \" << EPERM\n << \", \" << strerror(errno)\n << std::endl;\n }\n }\n\n unsigned long Run(void * \/*pArgument*\/) override {\n struct timeval tv;\n\n TermContextPtr context = std::dynamic_pointer_cast<TermContext>(GetPluginContext());\n\n if (!context)\n return 0;\n\n TermDataHandlerPtr term_data_handler =\n context->GetTermDataHandler();\n TermWindowPtr term_window =\n context->GetTermWindow();\n\n for (;;) {\n\n fd_set read_fd;\n fd_set except_fd;\n\n tv.tv_sec = 1;\n tv.tv_usec = 0;\n\n FD_ZERO(&read_fd);\n FD_ZERO(&except_fd);\n\n FD_SET(m_MasterFD, &read_fd);\n FD_SET(m_MasterFD, &except_fd);\n\n int result = select(m_MasterFD+1, &read_fd, NULL, &except_fd, &tv);\n\n if (m_Stopped)\n break;\n\n if (result == -1) {\n if (errno == EINTR) {\n continue;\n }\n\n std::cerr << \"select failed with err:\" << errno << std::endl;\n break;\n } else if (result == 0) {\n \/\/timeout\n continue;\n }\n\n if (FD_ISSET(m_MasterFD, &except_fd))\n {\n term_window->Close();\n break;\n }\n\n if (FD_ISSET(m_MasterFD, &read_fd))\n {\n int count = read(m_MasterFD, &m_ReadBuffer[0], m_ReadBuffer.size());\n if (count == -1) {\n if (errno == EINTR)\n continue;\n\n std::cerr << \"read failed\\n\" << std::endl;\n term_window->Close();\n break;\n }\n\n if (count > 0) {\n term_data_handler->OnData(m_ReadBuffer, count);\n }\n }\n }\n return 0;\n }\nprivate:\n uint32_t m_Rows;\n uint32_t m_Cols;\n int m_MasterFD;\n std::vector<unsigned char> m_ReadBuffer;\n PortableThread::CPortableThread m_PtyReaderThread;\n std::vector<char *> m_Envs;\n pid_t m_PtyPid;\n};\n\nvoid delete_data(void * data) {\n delete (Plugin*)data;\n}\n\nextern \"C\"\nvoid register_plugins(PluginManagerPtr plugin_manager) {\n plugin_manager->RegisterPlugin(PluginPtr {new TermNetworkPty, delete_data});;\n}\n<|endoftext|>"} {"text":"<commit_before>\/* IBM_PROLOG_BEGIN_TAG *\/\n\/* This is an automatically generated prolog. *\/\n\/* *\/\n\/* $Source: src\/import\/chips\/p9\/procedures\/hwp\/initfiles\/p9_fbc_ioe_dl_scom.C $ *\/\n\/* *\/\n\/* OpenPOWER HostBoot Project *\/\n\/* *\/\n\/* Contributors Listed Below - COPYRIGHT 2016,2019 *\/\n\/* [+] International Business Machines Corp. *\/\n\/* *\/\n\/* *\/\n\/* Licensed under the Apache License, Version 2.0 (the \"License\"); *\/\n\/* you may not use this file except in compliance with the License. *\/\n\/* You may obtain a copy of the License at *\/\n\/* *\/\n\/* http:\/\/www.apache.org\/licenses\/LICENSE-2.0 *\/\n\/* *\/\n\/* Unless required by applicable law or agreed to in writing, software *\/\n\/* distributed under the License is distributed on an \"AS IS\" BASIS, *\/\n\/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or *\/\n\/* implied. See the License for the specific language governing *\/\n\/* permissions and limitations under the License. *\/\n\/* *\/\n\/* IBM_PROLOG_END_TAG *\/\n#include \"p9_fbc_ioe_dl_scom.H\"\n#include <stdint.h>\n#include <stddef.h>\n#include <fapi2.H>\n\nusing namespace fapi2;\n\nconstexpr uint64_t literal_0xE00 = 0xE00;\nconstexpr uint64_t literal_0x0000 = 0x0000;\nconstexpr uint64_t literal_0x0 = 0x0;\nconstexpr uint64_t literal_0b11 = 0b11;\n\nfapi2::ReturnCode p9_fbc_ioe_dl_scom(const fapi2::Target<fapi2::TARGET_TYPE_XBUS>& TGT0,\n const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& TGT1)\n{\n {\n fapi2::ATTR_EC_Type l_chip_ec;\n fapi2::ATTR_NAME_Type l_chip_id;\n FAPI_TRY(FAPI_ATTR_GET_PRIVILEGED(fapi2::ATTR_NAME, TGT1, l_chip_id));\n FAPI_TRY(FAPI_ATTR_GET_PRIVILEGED(fapi2::ATTR_EC, TGT1, l_chip_ec));\n fapi2::buffer<uint64_t> l_scom_buffer;\n {\n FAPI_TRY(fapi2::getScom( TGT0, 0x601180aull, l_scom_buffer ));\n\n constexpr auto l_PB_IOE_LL1_CONFIG_LINK_PAIR_ON = 0x1;\n l_scom_buffer.insert<0, 1, 63, uint64_t>(l_PB_IOE_LL1_CONFIG_LINK_PAIR_ON );\n constexpr auto l_PB_IOE_LL1_CONFIG_CRC_LANE_ID_ON = 0x1;\n l_scom_buffer.insert<2, 1, 63, uint64_t>(l_PB_IOE_LL1_CONFIG_CRC_LANE_ID_ON );\n FAPI_TRY(fapi2::putScom(TGT0, 0x601180aull, l_scom_buffer));\n }\n {\n FAPI_TRY(fapi2::getScom( TGT0, 0x6011818ull, l_scom_buffer ));\n\n l_scom_buffer.insert<8, 3, 61, uint64_t>(literal_0xE00 );\n l_scom_buffer.insert<32, 16, 48, uint64_t>(literal_0x0000 );\n l_scom_buffer.insert<48, 16, 48, uint64_t>(literal_0x0000 );\n l_scom_buffer.insert<4, 4, 60, uint64_t>(literal_0x0 );\n l_scom_buffer.insert<0, 4, 60, uint64_t>(literal_0x0 );\n FAPI_TRY(fapi2::putScom(TGT0, 0x6011818ull, l_scom_buffer));\n }\n {\n FAPI_TRY(fapi2::getScom( TGT0, 0x6011819ull, l_scom_buffer ));\n\n if (((l_chip_id == 0x5) && (l_chip_ec == 0x10)) )\n {\n l_scom_buffer.insert<8, 2, 62, uint64_t>(literal_0b11 );\n }\n else if (((l_chip_id == 0x5) && (l_chip_ec == 0x20)) )\n {\n l_scom_buffer.insert<8, 3, 61, uint64_t>(literal_0b11 );\n }\n\n l_scom_buffer.insert<32, 16, 48, uint64_t>(literal_0x0000 );\n l_scom_buffer.insert<48, 16, 48, uint64_t>(literal_0x0000 );\n l_scom_buffer.insert<4, 4, 60, uint64_t>(literal_0x0 );\n l_scom_buffer.insert<0, 4, 60, uint64_t>(literal_0x0 );\n FAPI_TRY(fapi2::putScom(TGT0, 0x6011819ull, l_scom_buffer));\n }\n\n };\nfapi_try_exit:\n return fapi2::current_err;\n}\n<commit_msg>P9 Cumulus InitCompiler supportis - Part 3<commit_after>\/* IBM_PROLOG_BEGIN_TAG *\/\n\/* This is an automatically generated prolog. *\/\n\/* *\/\n\/* $Source: src\/import\/chips\/p9\/procedures\/hwp\/initfiles\/p9_fbc_ioe_dl_scom.C $ *\/\n\/* *\/\n\/* OpenPOWER HostBoot Project *\/\n\/* *\/\n\/* Contributors Listed Below - COPYRIGHT 2016,2019 *\/\n\/* [+] International Business Machines Corp. *\/\n\/* *\/\n\/* *\/\n\/* Licensed under the Apache License, Version 2.0 (the \"License\"); *\/\n\/* you may not use this file except in compliance with the License. *\/\n\/* You may obtain a copy of the License at *\/\n\/* *\/\n\/* http:\/\/www.apache.org\/licenses\/LICENSE-2.0 *\/\n\/* *\/\n\/* Unless required by applicable law or agreed to in writing, software *\/\n\/* distributed under the License is distributed on an \"AS IS\" BASIS, *\/\n\/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or *\/\n\/* implied. See the License for the specific language governing *\/\n\/* permissions and limitations under the License. *\/\n\/* *\/\n\/* IBM_PROLOG_END_TAG *\/\n#include \"p9_fbc_ioe_dl_scom.H\"\n#include <stdint.h>\n#include <stddef.h>\n#include <fapi2.H>\n\nusing namespace fapi2;\n\nconstexpr uint64_t literal_0xE00 = 0xE00;\nconstexpr uint64_t literal_0x0000 = 0x0000;\nconstexpr uint64_t literal_0x0 = 0x0;\nconstexpr uint64_t literal_0b11 = 0b11;\n\nfapi2::ReturnCode p9_fbc_ioe_dl_scom(const fapi2::Target<fapi2::TARGET_TYPE_XBUS>& TGT0,\n const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& TGT1)\n{\n {\n fapi2::ATTR_EC_Type l_chip_ec;\n fapi2::ATTR_NAME_Type l_chip_id;\n FAPI_TRY(FAPI_ATTR_GET_PRIVILEGED(fapi2::ATTR_NAME, TGT1, l_chip_id));\n FAPI_TRY(FAPI_ATTR_GET_PRIVILEGED(fapi2::ATTR_EC, TGT1, l_chip_ec));\n fapi2::buffer<uint64_t> l_scom_buffer;\n {\n FAPI_TRY(fapi2::getScom( TGT0, 0x601180aull, l_scom_buffer ));\n\n constexpr auto l_PB_IOE_LL1_CONFIG_LINK_PAIR_ON = 0x1;\n l_scom_buffer.insert<0, 1, 63, uint64_t>(l_PB_IOE_LL1_CONFIG_LINK_PAIR_ON );\n constexpr auto l_PB_IOE_LL1_CONFIG_CRC_LANE_ID_ON = 0x1;\n l_scom_buffer.insert<2, 1, 63, uint64_t>(l_PB_IOE_LL1_CONFIG_CRC_LANE_ID_ON );\n FAPI_TRY(fapi2::putScom(TGT0, 0x601180aull, l_scom_buffer));\n }\n {\n FAPI_TRY(fapi2::getScom( TGT0, 0x6011818ull, l_scom_buffer ));\n\n l_scom_buffer.insert<8, 3, 61, uint64_t>(literal_0xE00 );\n l_scom_buffer.insert<32, 16, 48, uint64_t>(literal_0x0000 );\n l_scom_buffer.insert<48, 16, 48, uint64_t>(literal_0x0000 );\n l_scom_buffer.insert<4, 4, 60, uint64_t>(literal_0x0 );\n l_scom_buffer.insert<0, 4, 60, uint64_t>(literal_0x0 );\n FAPI_TRY(fapi2::putScom(TGT0, 0x6011818ull, l_scom_buffer));\n }\n {\n FAPI_TRY(fapi2::getScom( TGT0, 0x6011819ull, l_scom_buffer ));\n\n if (((l_chip_id == 0x5) && (l_chip_ec == 0x10)) )\n {\n l_scom_buffer.insert<8, 2, 62, uint64_t>(literal_0b11 );\n }\n else if (((l_chip_id == 0x5) && (l_chip_ec == 0x20)) || ((l_chip_id == 0x6) && (l_chip_ec == 0x10)) )\n {\n l_scom_buffer.insert<8, 3, 61, uint64_t>(literal_0b11 );\n }\n\n l_scom_buffer.insert<32, 16, 48, uint64_t>(literal_0x0000 );\n l_scom_buffer.insert<48, 16, 48, uint64_t>(literal_0x0000 );\n l_scom_buffer.insert<4, 4, 60, uint64_t>(literal_0x0 );\n l_scom_buffer.insert<0, 4, 60, uint64_t>(literal_0x0 );\n FAPI_TRY(fapi2::putScom(TGT0, 0x6011819ull, l_scom_buffer));\n }\n\n };\nfapi_try_exit:\n return fapi2::current_err;\n}\n<|endoftext|>"} {"text":"<commit_before>\/* IBM_PROLOG_BEGIN_TAG *\/\n\/* This is an automatically generated prolog. *\/\n\/* *\/\n\/* $Source: src\/import\/chips\/p9\/procedures\/hwp\/nest\/p9_revert_sbe_mcs_setup.C $ *\/\n\/* *\/\n\/* OpenPOWER HostBoot Project *\/\n\/* *\/\n\/* Contributors Listed Below - COPYRIGHT 2015,2019 *\/\n\/* [+] International Business Machines Corp. *\/\n\/* *\/\n\/* *\/\n\/* Licensed under the Apache License, Version 2.0 (the \"License\"); *\/\n\/* you may not use this file except in compliance with the License. *\/\n\/* You may obtain a copy of the License at *\/\n\/* *\/\n\/* http:\/\/www.apache.org\/licenses\/LICENSE-2.0 *\/\n\/* *\/\n\/* Unless required by applicable law or agreed to in writing, software *\/\n\/* distributed under the License is distributed on an \"AS IS\" BASIS, *\/\n\/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or *\/\n\/* implied. See the License for the specific language governing *\/\n\/* permissions and limitations under the License. *\/\n\/* *\/\n\/* IBM_PROLOG_END_TAG *\/\n\/\/\/\n\/\/\/ @file p9_revert_sbe_mcs_setup.C\n\/\/\/ @brief Revert MC configuration applied by SBE (FAPI2)\n\n\/\/\/\n\/\/\/ @author Joe McGill <jmcgill@us.ibm.com>\n\/\/\/\n\n\/\/\n\/\/ *HWP HWP Owner: Joe McGill <jmcgill@us.ibm.com>\n\/\/ *HWP FW Owner: Thi Tran <thi@us.ibm.com>\n\/\/ *HWP Team: Nest\n\/\/ *HWP Level: 2\n\/\/ *HWP Consumed by: HB\n\/\/\n\n\/\/------------------------------------------------------------------------------\n\/\/ Includes\n\/\/------------------------------------------------------------------------------\n#include <p9_revert_sbe_mcs_setup.H>\n#include <p9_perv_scom_addresses.H>\n#include <p9_mc_scom_addresses.H>\n#include <p9_mc_scom_addresses_fld.H>\n\n\/\/------------------------------------------------------------------------------\n\/\/ Constant definitions\n\/\/------------------------------------------------------------------------------\n\n\/\/ MCS target type constants\nconst uint8_t NUM_MCS_TARGETS = 4;\n\nconst uint64_t MCS_CPLT_CTRL1_ARR[NUM_MCS_TARGETS] =\n{\n PERV_N3_CPLT_CTRL1,\n PERV_N3_CPLT_CTRL1,\n PERV_N1_CPLT_CTRL1,\n PERV_N1_CPLT_CTRL1\n};\n\nconst uint64_t MCS_CPLT_CTRL1_BIT_ARR[NUM_MCS_TARGETS] =\n{\n 10,\n 10,\n 9,\n 9\n};\n\nconst uint64_t MCS_MCFGP_ARR[NUM_MCS_TARGETS] =\n{\n MCS_0_MCFGP,\n MCS_1_MCFGP,\n MCS_2_MCFGP,\n MCS_3_MCFGP\n};\nconst uint64_t MCS_MCMODE1_ARR[NUM_MCS_TARGETS] =\n{\n MCS_0_MCMODE1,\n MCS_1_MCMODE1,\n MCS_2_MCMODE1,\n MCS_3_MCMODE1\n};\nconst uint64_t MCS_MCFIRMASK_OR_ARR[NUM_MCS_TARGETS] =\n{\n MCS_0_MCFIRMASK_OR,\n MCS_1_MCFIRMASK_OR,\n MCS_2_MCFIRMASK_OR,\n MCS_3_MCFIRMASK_OR\n};\n\n\n\/\/------------------------------------------------------------------------------\n\/\/ Function definitions\n\/\/------------------------------------------------------------------------------\n\n\n\/\/ helper function for MCS target type\nfapi2::ReturnCode\nrevert_mcs_hb_dcbz_config(const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target,\n const uint8_t i_mcs)\n{\n FAPI_DBG(\"Start\");\n fapi2::buffer<uint64_t> l_cplt_ctrl1;\n fapi2::buffer<uint64_t> l_mcfgp;\n fapi2::buffer<uint64_t> l_mcmode1;\n fapi2::buffer<uint64_t> l_mcfirmask;\n\n FAPI_TRY(fapi2::getScom(i_target, MCS_CPLT_CTRL1_ARR[i_mcs], l_cplt_ctrl1),\n \"Error from getscom (CPLT_CTRL1)\");\n\n if (!l_cplt_ctrl1.getBit(MCS_CPLT_CTRL1_BIT_ARR[i_mcs]))\n {\n \/\/ MCFGP -- mark BAR invalid & reset grouping configuration fields\n FAPI_TRY(fapi2::getScom(i_target, MCS_MCFGP_ARR[i_mcs], l_mcfgp),\n \"Error from getScom (MCS%d_MCFGP)\", i_mcs);\n l_mcfgp.clearBit<MCS_MCFGP_VALID>();\n l_mcfgp.clearBit<MCS_MCFGP_MC_CHANNELS_PER_GROUP,\n MCS_MCFGP_MC_CHANNELS_PER_GROUP_LEN>();\n l_mcfgp.clearBit<MCS_MCFGP_CHANNEL_0_GROUP_MEMBER_IDENTIFICATION,\n MCS_MCFGP_CHANNEL_0_GROUP_MEMBER_IDENTIFICATION_LEN>();\n l_mcfgp.clearBit<MCS_MCFGP_GROUP_SIZE, MCS_MCFGP_GROUP_SIZE_LEN>();\n FAPI_TRY(fapi2::putScom(i_target, MCS_MCFGP_ARR[i_mcs], l_mcfgp),\n \"Error from putScom (MCS%d_MCFGP)\", i_mcs);\n\n \/\/ MCMODE1 -- enable speculation\n FAPI_TRY(fapi2::getScom(i_target, MCS_MCMODE1_ARR[i_mcs], l_mcmode1),\n \"Error from getScom (MCS%d_MCMODE1)\", i_mcs);\n l_mcmode1.clearBit<MCS_MCMODE1_DISABLE_ALL_SPEC_OPS>();\n l_mcmode1.clearBit<MCS_MCMODE1_DISABLE_SPEC_OP,\n MCS_MCMODE1_DISABLE_SPEC_OP_LEN>();\n FAPI_TRY(fapi2::putScom(i_target, MCS_MCMODE1_ARR[i_mcs], l_mcmode1),\n \"Error from putScom (MCS%d_MCMODE1)\", i_mcs);\n\n \/\/ Re-mask MCFIR. We want to ensure all MCSs are masked\n \/\/ until the BARs are opened later during IPL.\n l_mcfirmask.flush<1>();\n FAPI_TRY(fapi2::putScom(i_target, MCS_MCFIRMASK, l_mcfirmask),\n \"Error from putScom (MCS_MCFIRMASK)\");\n }\n\nfapi_try_exit:\n FAPI_DBG(\"End\");\n return fapi2::current_err;\n}\n\n\n\/\/ helper function for MI target type\nfapi2::ReturnCode\nrevert_mi_hb_dcbz_config(const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target)\n{\n FAPI_DBG(\"Start\");\n\n \/\/ TODO: implement for Cumulus\/MI target type\n (void) i_target;\n goto fapi_try_exit;\n\nfapi_try_exit:\n FAPI_DBG(\"End\");\n return fapi2::current_err;\n}\n\n\n\/\/ HWP entry point\nfapi2::ReturnCode\np9_revert_sbe_mcs_setup(const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target)\n{\n FAPI_INF(\"Start\");\n\n fapi2::Target<fapi2::TARGET_TYPE_SYSTEM> FAPI_SYSTEM;\n fapi2::ATTR_SYSTEM_IPL_PHASE_Type l_ipl_phase;\n auto l_mcs_chiplets = i_target.getChildren<fapi2::TARGET_TYPE_MCS>(fapi2::TARGET_STATE_PRESENT);\n\n FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_SYSTEM_IPL_PHASE, FAPI_SYSTEM, l_ipl_phase),\n \"Error from FAPI_ATTR_GET (ATTR_SYSTEM_IPL_PHASE)\");\n\n if (l_ipl_phase == fapi2::ENUM_ATTR_SYSTEM_IPL_PHASE_CHIP_CONTAINED)\n {\n FAPI_INF(\"Leaving MC BAR configured for chip contained execution\");\n goto fapi_try_exit;\n }\n\n if (l_mcs_chiplets.size())\n {\n for (uint8_t l_mcs = 0; l_mcs < NUM_MCS_TARGETS; l_mcs++)\n {\n FAPI_TRY(revert_mcs_hb_dcbz_config(i_target, l_mcs),\n \"Error from revert_mcs_hb_dcbz_config\");\n }\n }\n else\n {\n FAPI_TRY(revert_mi_hb_dcbz_config(i_target),\n \"Error from revert_mi_hb_dcbz_config\");\n }\n\nfapi_try_exit:\n FAPI_INF(\"End\");\n return fapi2::current_err;\n}\n<commit_msg>p9_revert_sbe_mcs_setup - Fix incorrect unmask reg addr<commit_after>\/* IBM_PROLOG_BEGIN_TAG *\/\n\/* This is an automatically generated prolog. *\/\n\/* *\/\n\/* $Source: src\/import\/chips\/p9\/procedures\/hwp\/nest\/p9_revert_sbe_mcs_setup.C $ *\/\n\/* *\/\n\/* OpenPOWER HostBoot Project *\/\n\/* *\/\n\/* Contributors Listed Below - COPYRIGHT 2015,2019 *\/\n\/* [+] International Business Machines Corp. *\/\n\/* *\/\n\/* *\/\n\/* Licensed under the Apache License, Version 2.0 (the \"License\"); *\/\n\/* you may not use this file except in compliance with the License. *\/\n\/* You may obtain a copy of the License at *\/\n\/* *\/\n\/* http:\/\/www.apache.org\/licenses\/LICENSE-2.0 *\/\n\/* *\/\n\/* Unless required by applicable law or agreed to in writing, software *\/\n\/* distributed under the License is distributed on an \"AS IS\" BASIS, *\/\n\/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or *\/\n\/* implied. See the License for the specific language governing *\/\n\/* permissions and limitations under the License. *\/\n\/* *\/\n\/* IBM_PROLOG_END_TAG *\/\n\/\/\/\n\/\/\/ @file p9_revert_sbe_mcs_setup.C\n\/\/\/ @brief Revert MC configuration applied by SBE (FAPI2)\n\n\/\/\/\n\/\/\/ @author Joe McGill <jmcgill@us.ibm.com>\n\/\/\/\n\n\/\/\n\/\/ *HWP HWP Owner: Joe McGill <jmcgill@us.ibm.com>\n\/\/ *HWP FW Owner: Thi Tran <thi@us.ibm.com>\n\/\/ *HWP Team: Nest\n\/\/ *HWP Level: 2\n\/\/ *HWP Consumed by: HB\n\/\/\n\n\/\/------------------------------------------------------------------------------\n\/\/ Includes\n\/\/------------------------------------------------------------------------------\n#include <p9_revert_sbe_mcs_setup.H>\n#include <p9_perv_scom_addresses.H>\n#include <p9_mc_scom_addresses.H>\n#include <p9_mc_scom_addresses_fld.H>\n\n\/\/------------------------------------------------------------------------------\n\/\/ Constant definitions\n\/\/------------------------------------------------------------------------------\n\n\/\/ MCS target type constants\nconst uint8_t NUM_MCS_TARGETS = 4;\n\nconst uint64_t MCS_CPLT_CTRL1_ARR[NUM_MCS_TARGETS] =\n{\n PERV_N3_CPLT_CTRL1,\n PERV_N3_CPLT_CTRL1,\n PERV_N1_CPLT_CTRL1,\n PERV_N1_CPLT_CTRL1\n};\n\nconst uint64_t MCS_CPLT_CTRL1_BIT_ARR[NUM_MCS_TARGETS] =\n{\n 10,\n 10,\n 9,\n 9\n};\n\nconst uint64_t MCS_MCFGP_ARR[NUM_MCS_TARGETS] =\n{\n MCS_0_MCFGP,\n MCS_1_MCFGP,\n MCS_2_MCFGP,\n MCS_3_MCFGP\n};\nconst uint64_t MCS_MCMODE1_ARR[NUM_MCS_TARGETS] =\n{\n MCS_0_MCMODE1,\n MCS_1_MCMODE1,\n MCS_2_MCMODE1,\n MCS_3_MCMODE1\n};\nconst uint64_t MCS_MCFIRMASK_OR_ARR[NUM_MCS_TARGETS] =\n{\n MCS_0_MCFIRMASK_OR,\n MCS_1_MCFIRMASK_OR,\n MCS_2_MCFIRMASK_OR,\n MCS_3_MCFIRMASK_OR\n};\n\n\n\/\/------------------------------------------------------------------------------\n\/\/ Function definitions\n\/\/------------------------------------------------------------------------------\n\n\n\/\/ helper function for MCS target type\nfapi2::ReturnCode\nrevert_mcs_hb_dcbz_config(const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target,\n const uint8_t i_mcs)\n{\n FAPI_DBG(\"Start\");\n fapi2::buffer<uint64_t> l_cplt_ctrl1;\n fapi2::buffer<uint64_t> l_mcfgp;\n fapi2::buffer<uint64_t> l_mcmode1;\n fapi2::buffer<uint64_t> l_mcfirmask;\n\n FAPI_TRY(fapi2::getScom(i_target, MCS_CPLT_CTRL1_ARR[i_mcs], l_cplt_ctrl1),\n \"Error from getscom (CPLT_CTRL1)\");\n\n if (!l_cplt_ctrl1.getBit(MCS_CPLT_CTRL1_BIT_ARR[i_mcs]))\n {\n \/\/ MCFGP -- mark BAR invalid & reset grouping configuration fields\n FAPI_TRY(fapi2::getScom(i_target, MCS_MCFGP_ARR[i_mcs], l_mcfgp),\n \"Error from getScom (MCS%d_MCFGP)\", i_mcs);\n l_mcfgp.clearBit<MCS_MCFGP_VALID>();\n l_mcfgp.clearBit<MCS_MCFGP_MC_CHANNELS_PER_GROUP,\n MCS_MCFGP_MC_CHANNELS_PER_GROUP_LEN>();\n l_mcfgp.clearBit<MCS_MCFGP_CHANNEL_0_GROUP_MEMBER_IDENTIFICATION,\n MCS_MCFGP_CHANNEL_0_GROUP_MEMBER_IDENTIFICATION_LEN>();\n l_mcfgp.clearBit<MCS_MCFGP_GROUP_SIZE, MCS_MCFGP_GROUP_SIZE_LEN>();\n FAPI_TRY(fapi2::putScom(i_target, MCS_MCFGP_ARR[i_mcs], l_mcfgp),\n \"Error from putScom (MCS%d_MCFGP)\", i_mcs);\n\n \/\/ MCMODE1 -- enable speculation\n FAPI_TRY(fapi2::getScom(i_target, MCS_MCMODE1_ARR[i_mcs], l_mcmode1),\n \"Error from getScom (MCS%d_MCMODE1)\", i_mcs);\n l_mcmode1.clearBit<MCS_MCMODE1_DISABLE_ALL_SPEC_OPS>();\n l_mcmode1.clearBit<MCS_MCMODE1_DISABLE_SPEC_OP,\n MCS_MCMODE1_DISABLE_SPEC_OP_LEN>();\n FAPI_TRY(fapi2::putScom(i_target, MCS_MCMODE1_ARR[i_mcs], l_mcmode1),\n \"Error from putScom (MCS%d_MCMODE1)\", i_mcs);\n\n \/\/ Re-mask MCFIR. We want to ensure all MCSs are masked\n \/\/ until the BARs are opened later during IPL.\n l_mcfirmask.flush<1>();\n FAPI_TRY(fapi2::putScom(i_target, MCS_MCFIRMASK_OR_ARR[i_mcs], l_mcfirmask),\n \"Error from putScom (MCS%d_MCFIRMASK_OR)\", i_mcs);\n }\n\nfapi_try_exit:\n FAPI_DBG(\"End\");\n return fapi2::current_err;\n}\n\n\n\/\/ helper function for MI target type\nfapi2::ReturnCode\nrevert_mi_hb_dcbz_config(const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target)\n{\n FAPI_DBG(\"Start\");\n\n \/\/ TODO: implement for Cumulus\/MI target type\n (void) i_target;\n goto fapi_try_exit;\n\nfapi_try_exit:\n FAPI_DBG(\"End\");\n return fapi2::current_err;\n}\n\n\n\/\/ HWP entry point\nfapi2::ReturnCode\np9_revert_sbe_mcs_setup(const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target)\n{\n FAPI_INF(\"Start\");\n\n fapi2::Target<fapi2::TARGET_TYPE_SYSTEM> FAPI_SYSTEM;\n fapi2::ATTR_SYSTEM_IPL_PHASE_Type l_ipl_phase;\n auto l_mcs_chiplets = i_target.getChildren<fapi2::TARGET_TYPE_MCS>(fapi2::TARGET_STATE_PRESENT);\n\n FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_SYSTEM_IPL_PHASE, FAPI_SYSTEM, l_ipl_phase),\n \"Error from FAPI_ATTR_GET (ATTR_SYSTEM_IPL_PHASE)\");\n\n if (l_ipl_phase == fapi2::ENUM_ATTR_SYSTEM_IPL_PHASE_CHIP_CONTAINED)\n {\n FAPI_INF(\"Leaving MC BAR configured for chip contained execution\");\n goto fapi_try_exit;\n }\n\n if (l_mcs_chiplets.size())\n {\n for (uint8_t l_mcs = 0; l_mcs < NUM_MCS_TARGETS; l_mcs++)\n {\n FAPI_TRY(revert_mcs_hb_dcbz_config(i_target, l_mcs),\n \"Error from revert_mcs_hb_dcbz_config\");\n }\n }\n else\n {\n FAPI_TRY(revert_mi_hb_dcbz_config(i_target),\n \"Error from revert_mi_hb_dcbz_config\");\n }\n\nfapi_try_exit:\n FAPI_INF(\"End\");\n return fapi2::current_err;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ Video.cpp\n\/\/ Clock Signal\n\/\/\n\/\/ Created by Thomas Harte on 12\/10\/2016.\n\/\/ Copyright © 2016 Thomas Harte. All rights reserved.\n\/\/\n\n#include \"Video.hpp\"\n\nusing namespace Oric;\n\nnamespace {\n\tconst unsigned int PAL50VSyncStartPosition = 256*64;\n\tconst unsigned int PAL60VSyncStartPosition = 234*64;\n\tconst unsigned int PAL50VSyncEndPosition = 259*64;\n\tconst unsigned int PAL60VSyncEndPosition = 238*64;\n\tconst unsigned int PAL50Period = 312*64;\n\tconst unsigned int PAL60Period = 262*64;\n}\n\nVideoOutput::VideoOutput(uint8_t *memory) :\n\t\tram_(memory),\n\t\tframe_counter_(0), counter_(0),\n\t\tis_graphics_mode_(false),\n\t\tcharacter_set_base_address_(0xb400),\n\t\tv_sync_start_position_(PAL50VSyncStartPosition), v_sync_end_position_(PAL50VSyncEndPosition),\n\t\tcounter_period_(PAL50Period), next_frame_is_sixty_hertz_(false),\n\t\tcrt_(new Outputs::CRT::CRT(64*6, 6, Outputs::CRT::DisplayType::PAL50, 2)) {\n\tcrt_->set_rgb_sampling_function(\n\t\t\"vec3 rgb_sample(usampler2D sampler, vec2 coordinate, vec2 icoordinate)\"\n\t\t\"{\"\n\t\t\t\"uint texValue = texture(sampler, coordinate).r;\"\n\t\t\t\"return vec3( uvec3(texValue) & uvec3(4u, 2u, 1u));\"\n\t\t\"}\");\n\tcrt_->set_composite_sampling_function(\n\t\t\"float composite_sample(usampler2D sampler, vec2 coordinate, vec2 icoordinate, float phase, float amplitude)\"\n\t\t\"{\"\n\t\t\t\"uint texValue = uint(dot(texture(sampler, coordinate).rg, uvec2(1, 256)));\"\n\t\t\t\"uint iPhase = uint((phase + 3.141592654 + 0.39269908175) * 2.0 \/ 3.141592654) & 3u;\"\n\t\t\t\"texValue = (texValue >> (4u*(3u - iPhase))) & 15u;\"\n\t\t\t\"return (float(texValue) - 4.0) \/ 20.0;\"\n\t\t\"}\"\n\t);\n\tcrt_->set_composite_function_type(Outputs::CRT::CRT::CompositeSourceType::DiscreteFourSamplesPerCycle, 0.0f);\n\n\tset_output_device(Outputs::CRT::Television);\n\tcrt_->set_visible_area(crt_->get_rect_for_area(50, 224, 16 * 6, 40 * 6, 4.0f \/ 3.0f));\n}\n\nvoid VideoOutput::set_output_device(Outputs::CRT::OutputDevice output_device) {\n\toutput_device_ = output_device;\n\tcrt_->set_output_device(output_device);\n}\n\nvoid VideoOutput::set_colour_rom(const std::vector<uint8_t> &rom) {\n\tfor(size_t c = 0; c < 8; c++) {\n\t\tsize_t index = (c << 2);\n\t\tuint16_t rom_value = (uint16_t)(((uint16_t)rom[index] << 8) | (uint16_t)rom[index+1]);\n\t\trom_value = (rom_value & 0xff00) | ((rom_value >> 4)&0x000f) | ((rom_value << 4)&0x00f0);\n\t\tcolour_forms_[c] = rom_value;\n\t}\n\n\t\/\/ check for big endianness and byte swap if required\n\tuint16_t test_value = 0x0001;\n\tif(*(uint8_t *)&test_value != 0x01) {\n\t\tfor(size_t c = 0; c < 8; c++) {\n\t\t\tcolour_forms_[c] = (uint16_t)((colour_forms_[c] >> 8) | (colour_forms_[c] << 8));\n\t\t}\n\t}\n}\n\nstd::shared_ptr<Outputs::CRT::CRT> VideoOutput::get_crt() {\n\treturn crt_;\n}\n\nvoid VideoOutput::run_for(const Cycles cycles) {\n\t\/\/ Vertical: 0–39: pixels; otherwise blank; 48–53 sync, 54–56 colour burst\n\t\/\/ Horizontal: 0–223: pixels; otherwise blank; 256–259 sync\n\n#define clamp(action)\t\\\n\tif(cycles_run_for <= number_of_cycles) { action; } else cycles_run_for = number_of_cycles;\n\n\tint number_of_cycles = cycles.as_int();\n\twhile(number_of_cycles) {\n\t\tint h_counter = counter_ & 63;\n\t\tint cycles_run_for = 0;\n\n\t\tif(counter_ >= v_sync_start_position_ && counter_ < v_sync_end_position_) {\n\t\t\t\/\/ this is a sync line\n\t\t\tcycles_run_for = v_sync_end_position_ - counter_;\n\t\t\tclamp(crt_->output_sync((unsigned int)(v_sync_end_position_ - v_sync_start_position_) * 6));\n\t\t} else if(counter_ < 224*64 && h_counter < 40) {\n\t\t\t\/\/ this is a pixel line\n\t\t\tif(!h_counter) {\n\t\t\t\tink_ = 0x7;\n\t\t\t\tpaper_ = 0x0;\n\t\t\t\tuse_alternative_character_set_ = use_double_height_characters_ = blink_text_ = false;\n\t\t\t\tset_character_set_base_address();\n\t\t\t\tpixel_target_ = (uint16_t *)crt_->allocate_write_area(240);\n\n\t\t\t\tif(!counter_) {\n\t\t\t\t\tframe_counter_++;\n\n\t\t\t\t\tv_sync_start_position_ = next_frame_is_sixty_hertz_ ? PAL60VSyncStartPosition : PAL50VSyncStartPosition;\n\t\t\t\t\tv_sync_end_position_ = next_frame_is_sixty_hertz_ ? PAL60VSyncEndPosition : PAL50VSyncEndPosition;\n\t\t\t\t\tcounter_period_ = next_frame_is_sixty_hertz_ ? PAL60Period : PAL50Period;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tcycles_run_for = std::min(40 - h_counter, number_of_cycles);\n\t\t\tint columns = cycles_run_for;\n\t\t\tint pixel_base_address = 0xa000 + (counter_ >> 6) * 40;\n\t\t\tint character_base_address = 0xbb80 + (counter_ >> 9) * 40;\n\t\t\tuint8_t blink_mask = (blink_text_ && (frame_counter_&32)) ? 0x00 : 0xff;\n\n\t\t\twhile(columns--) {\n\t\t\t\tuint8_t pixels, control_byte;\n\n\t\t\t\tif(is_graphics_mode_ && counter_ < 200*64) {\n\t\t\t\t\tcontrol_byte = pixels = ram_[pixel_base_address + h_counter];\n\t\t\t\t} else {\n\t\t\t\t\tint address = character_base_address + h_counter;\n\t\t\t\t\tcontrol_byte = ram_[address];\n\t\t\t\t\tint line = use_double_height_characters_ ? ((counter_ >> 7) & 7) : ((counter_ >> 6) & 7);\n\t\t\t\t\tpixels = ram_[character_set_base_address_ + (control_byte&127) * 8 + line];\n\t\t\t\t}\n\n\t\t\t\tuint8_t inverse_mask = (control_byte & 0x80) ? 0x7 : 0x0;\n\t\t\t\tpixels &= blink_mask;\n\n\t\t\t\tif(control_byte & 0x60) {\n\t\t\t\t\tif(pixel_target_) {\n\t\t\t\t\t\tuint16_t colours[2];\n\t\t\t\t\t\tif(output_device_ == Outputs::CRT::Monitor) {\n\t\t\t\t\t\t\tcolours[0] = (uint8_t)(paper_ ^ inverse_mask);\n\t\t\t\t\t\t\tcolours[1] = (uint8_t)(ink_ ^ inverse_mask);\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tcolours[0] = colour_forms_[paper_ ^ inverse_mask];\n\t\t\t\t\t\t\tcolours[1] = colour_forms_[ink_ ^ inverse_mask];\n\t\t\t\t\t\t}\n\t\t\t\t\t\tpixel_target_[0] = colours[(pixels >> 5)&1];\n\t\t\t\t\t\tpixel_target_[1] = colours[(pixels >> 4)&1];\n\t\t\t\t\t\tpixel_target_[2] = colours[(pixels >> 3)&1];\n\t\t\t\t\t\tpixel_target_[3] = colours[(pixels >> 2)&1];\n\t\t\t\t\t\tpixel_target_[4] = colours[(pixels >> 1)&1];\n\t\t\t\t\t\tpixel_target_[5] = colours[(pixels >> 0)&1];\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tswitch(control_byte & 0x1f) {\n\t\t\t\t\t\tcase 0x00:\t\tink_ = 0x0;\tbreak;\n\t\t\t\t\t\tcase 0x01:\t\tink_ = 0x4;\tbreak;\n\t\t\t\t\t\tcase 0x02:\t\tink_ = 0x2;\tbreak;\n\t\t\t\t\t\tcase 0x03:\t\tink_ = 0x6;\tbreak;\n\t\t\t\t\t\tcase 0x04:\t\tink_ = 0x1;\tbreak;\n\t\t\t\t\t\tcase 0x05:\t\tink_ = 0x5;\tbreak;\n\t\t\t\t\t\tcase 0x06:\t\tink_ = 0x3;\tbreak;\n\t\t\t\t\t\tcase 0x07:\t\tink_ = 0x7;\tbreak;\n\n\t\t\t\t\t\tcase 0x08:\tcase 0x09:\tcase 0x0a: case 0x0b:\n\t\t\t\t\t\tcase 0x0c:\tcase 0x0d:\tcase 0x0e: case 0x0f:\n\t\t\t\t\t\t\tuse_alternative_character_set_ = (control_byte&1);\n\t\t\t\t\t\t\tuse_double_height_characters_ = (control_byte&2);\n\t\t\t\t\t\t\tblink_text_ = (control_byte&4);\n\t\t\t\t\t\t\tset_character_set_base_address();\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\t\tcase 0x10:\t\tpaper_ = 0x0;\tbreak;\n\t\t\t\t\t\tcase 0x11:\t\tpaper_ = 0x4;\tbreak;\n\t\t\t\t\t\tcase 0x12:\t\tpaper_ = 0x2;\tbreak;\n\t\t\t\t\t\tcase 0x13:\t\tpaper_ = 0x6;\tbreak;\n\t\t\t\t\t\tcase 0x14:\t\tpaper_ = 0x1;\tbreak;\n\t\t\t\t\t\tcase 0x15:\t\tpaper_ = 0x5;\tbreak;\n\t\t\t\t\t\tcase 0x16:\t\tpaper_ = 0x3;\tbreak;\n\t\t\t\t\t\tcase 0x17:\t\tpaper_ = 0x7;\tbreak;\n\n\t\t\t\t\t\tcase 0x18: case 0x19: case 0x1a: case 0x1b:\n\t\t\t\t\t\tcase 0x1c: case 0x1d: case 0x1e: case 0x1f:\n\t\t\t\t\t\t\tis_graphics_mode_ = (control_byte & 4);\n\t\t\t\t\t\t\tnext_frame_is_sixty_hertz_ = !(control_byte & 2);\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\t\tdefault: break;\n\t\t\t\t\t}\n\t\t\t\t\tif(pixel_target_) {\n\t\t\t\t\t\tpixel_target_[0] = pixel_target_[1] =\n\t\t\t\t\t\tpixel_target_[2] = pixel_target_[3] =\n\t\t\t\t\t\tpixel_target_[4] = pixel_target_[5] =\n\t\t\t\t\t\t\t(output_device_ == Outputs::CRT::Monitor) ? paper_ ^ inverse_mask : colour_forms_[paper_ ^ inverse_mask];\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif(pixel_target_) pixel_target_ += 6;\n\t\t\t\th_counter++;\n\t\t\t}\n\n\t\t\tif(h_counter == 40) {\n\t\t\t\tcrt_->output_data(40 * 6, 1);\n\t\t\t}\n\t\t} else {\n\t\t\t\/\/ this is a blank line (or the equivalent part of a pixel line)\n\t\t\tif(h_counter < 48) {\n\t\t\t\tcycles_run_for = 48 - h_counter;\n\t\t\t\tclamp(\n\t\t\t\t\tint period = (counter_ < 224*64) ? 8 : 48;\n\t\t\t\t\tcrt_->output_blank((unsigned int)period * 6);\n\t\t\t\t);\n\t\t\t} else if(h_counter < 54) {\n\t\t\t\tcycles_run_for = 54 - h_counter;\n\t\t\t\tclamp(crt_->output_sync(6 * 6));\n\t\t\t} else if(h_counter < 56) {\n\t\t\t\tcycles_run_for = 56 - h_counter;\n\t\t\t\tclamp(crt_->output_default_colour_burst(2 * 6));\n\t\t\t} else {\n\t\t\t\tcycles_run_for = 64 - h_counter;\n\t\t\t\tclamp(crt_->output_blank(8 * 6));\n\t\t\t}\n\t\t}\n\n\t\tcounter_ = (counter_ + cycles_run_for)%counter_period_;\n\t\tnumber_of_cycles -= cycles_run_for;\n\t}\n}\n\nvoid VideoOutput::set_character_set_base_address() {\n\tif(is_graphics_mode_) character_set_base_address_ = use_alternative_character_set_ ? 0x9c00 : 0x9800;\n\telse character_set_base_address_ = use_alternative_character_set_ ? 0xb800 : 0xb400;\n}\n<commit_msg>Updates clipped area per latest CRT response to vertical sync.<commit_after>\/\/\n\/\/ Video.cpp\n\/\/ Clock Signal\n\/\/\n\/\/ Created by Thomas Harte on 12\/10\/2016.\n\/\/ Copyright © 2016 Thomas Harte. All rights reserved.\n\/\/\n\n#include \"Video.hpp\"\n\nusing namespace Oric;\n\nnamespace {\n\tconst unsigned int PAL50VSyncStartPosition = 256*64;\n\tconst unsigned int PAL60VSyncStartPosition = 234*64;\n\tconst unsigned int PAL50VSyncEndPosition = 259*64;\n\tconst unsigned int PAL60VSyncEndPosition = 238*64;\n\tconst unsigned int PAL50Period = 312*64;\n\tconst unsigned int PAL60Period = 262*64;\n}\n\nVideoOutput::VideoOutput(uint8_t *memory) :\n\t\tram_(memory),\n\t\tframe_counter_(0), counter_(0),\n\t\tis_graphics_mode_(false),\n\t\tcharacter_set_base_address_(0xb400),\n\t\tv_sync_start_position_(PAL50VSyncStartPosition), v_sync_end_position_(PAL50VSyncEndPosition),\n\t\tcounter_period_(PAL50Period), next_frame_is_sixty_hertz_(false),\n\t\tcrt_(new Outputs::CRT::CRT(64*6, 6, Outputs::CRT::DisplayType::PAL50, 2)) {\n\tcrt_->set_rgb_sampling_function(\n\t\t\"vec3 rgb_sample(usampler2D sampler, vec2 coordinate, vec2 icoordinate)\"\n\t\t\"{\"\n\t\t\t\"uint texValue = texture(sampler, coordinate).r;\"\n\t\t\t\"return vec3( uvec3(texValue) & uvec3(4u, 2u, 1u));\"\n\t\t\"}\");\n\tcrt_->set_composite_sampling_function(\n\t\t\"float composite_sample(usampler2D sampler, vec2 coordinate, vec2 icoordinate, float phase, float amplitude)\"\n\t\t\"{\"\n\t\t\t\"uint texValue = uint(dot(texture(sampler, coordinate).rg, uvec2(1, 256)));\"\n\t\t\t\"uint iPhase = uint((phase + 3.141592654 + 0.39269908175) * 2.0 \/ 3.141592654) & 3u;\"\n\t\t\t\"texValue = (texValue >> (4u*(3u - iPhase))) & 15u;\"\n\t\t\t\"return (float(texValue) - 4.0) \/ 20.0;\"\n\t\t\"}\"\n\t);\n\tcrt_->set_composite_function_type(Outputs::CRT::CRT::CompositeSourceType::DiscreteFourSamplesPerCycle, 0.0f);\n\n\tset_output_device(Outputs::CRT::Television);\n\tcrt_->set_visible_area(crt_->get_rect_for_area(53, 224, 16 * 6, 40 * 6, 4.0f \/ 3.0f));\n}\n\nvoid VideoOutput::set_output_device(Outputs::CRT::OutputDevice output_device) {\n\toutput_device_ = output_device;\n\tcrt_->set_output_device(output_device);\n}\n\nvoid VideoOutput::set_colour_rom(const std::vector<uint8_t> &rom) {\n\tfor(size_t c = 0; c < 8; c++) {\n\t\tsize_t index = (c << 2);\n\t\tuint16_t rom_value = (uint16_t)(((uint16_t)rom[index] << 8) | (uint16_t)rom[index+1]);\n\t\trom_value = (rom_value & 0xff00) | ((rom_value >> 4)&0x000f) | ((rom_value << 4)&0x00f0);\n\t\tcolour_forms_[c] = rom_value;\n\t}\n\n\t\/\/ check for big endianness and byte swap if required\n\tuint16_t test_value = 0x0001;\n\tif(*(uint8_t *)&test_value != 0x01) {\n\t\tfor(size_t c = 0; c < 8; c++) {\n\t\t\tcolour_forms_[c] = (uint16_t)((colour_forms_[c] >> 8) | (colour_forms_[c] << 8));\n\t\t}\n\t}\n}\n\nstd::shared_ptr<Outputs::CRT::CRT> VideoOutput::get_crt() {\n\treturn crt_;\n}\n\nvoid VideoOutput::run_for(const Cycles cycles) {\n\t\/\/ Vertical: 0–39: pixels; otherwise blank; 48–53 sync, 54–56 colour burst\n\t\/\/ Horizontal: 0–223: pixels; otherwise blank; 256–259 sync\n\n#define clamp(action)\t\\\n\tif(cycles_run_for <= number_of_cycles) { action; } else cycles_run_for = number_of_cycles;\n\n\tint number_of_cycles = cycles.as_int();\n\twhile(number_of_cycles) {\n\t\tint h_counter = counter_ & 63;\n\t\tint cycles_run_for = 0;\n\n\t\tif(counter_ >= v_sync_start_position_ && counter_ < v_sync_end_position_) {\n\t\t\t\/\/ this is a sync line\n\t\t\tcycles_run_for = v_sync_end_position_ - counter_;\n\t\t\tclamp(crt_->output_sync((unsigned int)(v_sync_end_position_ - v_sync_start_position_) * 6));\n\t\t} else if(counter_ < 224*64 && h_counter < 40) {\n\t\t\t\/\/ this is a pixel line\n\t\t\tif(!h_counter) {\n\t\t\t\tink_ = 0x7;\n\t\t\t\tpaper_ = 0x0;\n\t\t\t\tuse_alternative_character_set_ = use_double_height_characters_ = blink_text_ = false;\n\t\t\t\tset_character_set_base_address();\n\t\t\t\tpixel_target_ = (uint16_t *)crt_->allocate_write_area(240);\n\n\t\t\t\tif(!counter_) {\n\t\t\t\t\tframe_counter_++;\n\n\t\t\t\t\tv_sync_start_position_ = next_frame_is_sixty_hertz_ ? PAL60VSyncStartPosition : PAL50VSyncStartPosition;\n\t\t\t\t\tv_sync_end_position_ = next_frame_is_sixty_hertz_ ? PAL60VSyncEndPosition : PAL50VSyncEndPosition;\n\t\t\t\t\tcounter_period_ = next_frame_is_sixty_hertz_ ? PAL60Period : PAL50Period;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tcycles_run_for = std::min(40 - h_counter, number_of_cycles);\n\t\t\tint columns = cycles_run_for;\n\t\t\tint pixel_base_address = 0xa000 + (counter_ >> 6) * 40;\n\t\t\tint character_base_address = 0xbb80 + (counter_ >> 9) * 40;\n\t\t\tuint8_t blink_mask = (blink_text_ && (frame_counter_&32)) ? 0x00 : 0xff;\n\n\t\t\twhile(columns--) {\n\t\t\t\tuint8_t pixels, control_byte;\n\n\t\t\t\tif(is_graphics_mode_ && counter_ < 200*64) {\n\t\t\t\t\tcontrol_byte = pixels = ram_[pixel_base_address + h_counter];\n\t\t\t\t} else {\n\t\t\t\t\tint address = character_base_address + h_counter;\n\t\t\t\t\tcontrol_byte = ram_[address];\n\t\t\t\t\tint line = use_double_height_characters_ ? ((counter_ >> 7) & 7) : ((counter_ >> 6) & 7);\n\t\t\t\t\tpixels = ram_[character_set_base_address_ + (control_byte&127) * 8 + line];\n\t\t\t\t}\n\n\t\t\t\tuint8_t inverse_mask = (control_byte & 0x80) ? 0x7 : 0x0;\n\t\t\t\tpixels &= blink_mask;\n\n\t\t\t\tif(control_byte & 0x60) {\n\t\t\t\t\tif(pixel_target_) {\n\t\t\t\t\t\tuint16_t colours[2];\n\t\t\t\t\t\tif(output_device_ == Outputs::CRT::Monitor) {\n\t\t\t\t\t\t\tcolours[0] = (uint8_t)(paper_ ^ inverse_mask);\n\t\t\t\t\t\t\tcolours[1] = (uint8_t)(ink_ ^ inverse_mask);\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tcolours[0] = colour_forms_[paper_ ^ inverse_mask];\n\t\t\t\t\t\t\tcolours[1] = colour_forms_[ink_ ^ inverse_mask];\n\t\t\t\t\t\t}\n\t\t\t\t\t\tpixel_target_[0] = colours[(pixels >> 5)&1];\n\t\t\t\t\t\tpixel_target_[1] = colours[(pixels >> 4)&1];\n\t\t\t\t\t\tpixel_target_[2] = colours[(pixels >> 3)&1];\n\t\t\t\t\t\tpixel_target_[3] = colours[(pixels >> 2)&1];\n\t\t\t\t\t\tpixel_target_[4] = colours[(pixels >> 1)&1];\n\t\t\t\t\t\tpixel_target_[5] = colours[(pixels >> 0)&1];\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tswitch(control_byte & 0x1f) {\n\t\t\t\t\t\tcase 0x00:\t\tink_ = 0x0;\tbreak;\n\t\t\t\t\t\tcase 0x01:\t\tink_ = 0x4;\tbreak;\n\t\t\t\t\t\tcase 0x02:\t\tink_ = 0x2;\tbreak;\n\t\t\t\t\t\tcase 0x03:\t\tink_ = 0x6;\tbreak;\n\t\t\t\t\t\tcase 0x04:\t\tink_ = 0x1;\tbreak;\n\t\t\t\t\t\tcase 0x05:\t\tink_ = 0x5;\tbreak;\n\t\t\t\t\t\tcase 0x06:\t\tink_ = 0x3;\tbreak;\n\t\t\t\t\t\tcase 0x07:\t\tink_ = 0x7;\tbreak;\n\n\t\t\t\t\t\tcase 0x08:\tcase 0x09:\tcase 0x0a: case 0x0b:\n\t\t\t\t\t\tcase 0x0c:\tcase 0x0d:\tcase 0x0e: case 0x0f:\n\t\t\t\t\t\t\tuse_alternative_character_set_ = (control_byte&1);\n\t\t\t\t\t\t\tuse_double_height_characters_ = (control_byte&2);\n\t\t\t\t\t\t\tblink_text_ = (control_byte&4);\n\t\t\t\t\t\t\tset_character_set_base_address();\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\t\tcase 0x10:\t\tpaper_ = 0x0;\tbreak;\n\t\t\t\t\t\tcase 0x11:\t\tpaper_ = 0x4;\tbreak;\n\t\t\t\t\t\tcase 0x12:\t\tpaper_ = 0x2;\tbreak;\n\t\t\t\t\t\tcase 0x13:\t\tpaper_ = 0x6;\tbreak;\n\t\t\t\t\t\tcase 0x14:\t\tpaper_ = 0x1;\tbreak;\n\t\t\t\t\t\tcase 0x15:\t\tpaper_ = 0x5;\tbreak;\n\t\t\t\t\t\tcase 0x16:\t\tpaper_ = 0x3;\tbreak;\n\t\t\t\t\t\tcase 0x17:\t\tpaper_ = 0x7;\tbreak;\n\n\t\t\t\t\t\tcase 0x18: case 0x19: case 0x1a: case 0x1b:\n\t\t\t\t\t\tcase 0x1c: case 0x1d: case 0x1e: case 0x1f:\n\t\t\t\t\t\t\tis_graphics_mode_ = (control_byte & 4);\n\t\t\t\t\t\t\tnext_frame_is_sixty_hertz_ = !(control_byte & 2);\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\t\tdefault: break;\n\t\t\t\t\t}\n\t\t\t\t\tif(pixel_target_) {\n\t\t\t\t\t\tpixel_target_[0] = pixel_target_[1] =\n\t\t\t\t\t\tpixel_target_[2] = pixel_target_[3] =\n\t\t\t\t\t\tpixel_target_[4] = pixel_target_[5] =\n\t\t\t\t\t\t\t(output_device_ == Outputs::CRT::Monitor) ? paper_ ^ inverse_mask : colour_forms_[paper_ ^ inverse_mask];\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif(pixel_target_) pixel_target_ += 6;\n\t\t\t\th_counter++;\n\t\t\t}\n\n\t\t\tif(h_counter == 40) {\n\t\t\t\tcrt_->output_data(40 * 6, 1);\n\t\t\t}\n\t\t} else {\n\t\t\t\/\/ this is a blank line (or the equivalent part of a pixel line)\n\t\t\tif(h_counter < 48) {\n\t\t\t\tcycles_run_for = 48 - h_counter;\n\t\t\t\tclamp(\n\t\t\t\t\tint period = (counter_ < 224*64) ? 8 : 48;\n\t\t\t\t\tcrt_->output_blank((unsigned int)period * 6);\n\t\t\t\t);\n\t\t\t} else if(h_counter < 54) {\n\t\t\t\tcycles_run_for = 54 - h_counter;\n\t\t\t\tclamp(crt_->output_sync(6 * 6));\n\t\t\t} else if(h_counter < 56) {\n\t\t\t\tcycles_run_for = 56 - h_counter;\n\t\t\t\tclamp(crt_->output_default_colour_burst(2 * 6));\n\t\t\t} else {\n\t\t\t\tcycles_run_for = 64 - h_counter;\n\t\t\t\tclamp(crt_->output_blank(8 * 6));\n\t\t\t}\n\t\t}\n\n\t\tcounter_ = (counter_ + cycles_run_for)%counter_period_;\n\t\tnumber_of_cycles -= cycles_run_for;\n\t}\n}\n\nvoid VideoOutput::set_character_set_base_address() {\n\tif(is_graphics_mode_) character_set_base_address_ = use_alternative_character_set_ ? 0x9c00 : 0x9800;\n\telse character_set_base_address_ = use_alternative_character_set_ ? 0xb800 : 0xb400;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * fits.cpp\n *\n * Created on: Jun 19, 2012\n * Author: mpetkova\n *\/\n\n#ifdef WITH_MOKA\n\n#include <MOKAfits.h>\n#include <CCfits\/CCfits>\n\nusing namespace CCfits;\n\nvoid getDims(std::string fn\n\t ,int *nx\n\t ,int *ny){\n\n\ttry{\n\t\tstd::auto_ptr<FITS> ff(new FITS (fn, Read));\n\n\t\tPHDU *h0=&ff->pHDU();\n\n\t\t*nx=h0->axis(0);\n\t\t*ny=h0->axis(1);\n\t}\n\tcatch(FITS::CantOpen){\n\t\tstd::cout << \"can not open \" << fn << std::endl;\n\t\texit(1);\n\t}\n}\n\n\/*\n * reads in the fits file for the MOKA map and saves it in the structure map\n *\/\nvoid readImage(std::string fn\n\t\t,std::valarray<float> *convergence\n\t\t,std::valarray<float> *alpha1\n\t\t,std::valarray<float> *alpha2\n\t\t,std::valarray<float> *gamma1\n\t\t,std::valarray<float> *gamma2\n\t ,struct LensHalo *LH){ \n\n\tint nx,ny;\n\n\tstd::auto_ptr<FITS> ff(new FITS (fn, Read));\n\n\tPHDU *h0=&ff->pHDU();\n\n\tnx=h0->axis(0);\n\tny=h0->axis(1);\n\n\th0->read(*convergence);\n\n\th0->readKey (\"SIDEL\",LH->boxlarcsec);\n\th0->readKey (\"SIDEL2\",LH->boxlMpc);\n\th0->readKey (\"ZLENS\",LH->zl);\n\th0->readKey (\"ZSOURCE\",LH->zs);\n\th0->readKey (\"OMEGA\",LH->omegam);\n\th0->readKey (\"LAMBDA\",LH->omegal);\n\th0->readKey (\"H\",LH->h);\n\th0->readKey (\"W\",LH->wq);\n\th0->readKey (\"MSTAR\",LH->mstar); \n\th0->readKey (\"MVIR\",LH->m); \n\th0->readKey (\"CONCENTRATION\",LH->c);\n\th0->readKey (\"DL\",LH->DL);\n\th0->readKey (\"DLS\",LH->DLS);\n\th0->readKey (\"DS\",LH->DS);\n\n\tExtHDU &h1=ff->extension(1);\n\th1.read(*alpha1);\n\tExtHDU &h2=ff->extension(2);\n\th2.read(*alpha2);\n\tExtHDU &h3=ff->extension(3);\n\th3.read(*gamma1);\n\tExtHDU &h4=ff->extension(4);\n\th4.read(*gamma2);\n\n\tstd::cout << *h0 << h1 << h2 << h3 << h4 << std::endl;\n}\n\n\/*\n * write the fits file of the new MOKA map from the structure map\n *\/\nvoid writeImage(std::string filename\n\t\t,std::valarray<float> convergence\n\t\t,std::valarray<float> gamma1\n\t\t,std::valarray<float> gamma2\n\t\t,std::valarray<float> gamma3\n\t\t,int nx\n\t\t,int ny\n\t\t,struct LensHalo LH){ \n\n\tlong naxis=2;\n\tlong naxes[2]={nx,ny};\n\n\tstd::auto_ptr<FITS> fout(0);\n\n\ttry{\n\t\tfout.reset(new FITS(filename,FLOAT_IMG,naxis,naxes));\n\t}\n\tcatch(FITS::CantCreate){\n\t\texit(1);\n\t}\n\n\tstd::vector<long> naxex(2);\n\tnaxex[0]=nx;\n\tnaxex[1]=ny;\n\n\tPHDU *phout=&fout->pHDU();\n\n\tphout->write( 1,nx*ny,convergence );\n\n\tphout->addKey (\"SIDEL\",LH.boxlarcsec,\"arcsec\");\n\tphout->addKey (\"SIDEL2\",LH.boxlMpc,\"Mpc\/h\");\n\tphout->addKey (\"ZLENS\",LH.zl,\"lens redshift\");\n\tphout->addKey (\"ZSOURCE\",LH.zs, \"source redshift\");\n\tphout->addKey (\"OMEGA\",LH.omegam,\"omega matter\");\n\tphout->addKey (\"LAMBDA\",LH.omegal,\"omega lamda\");\n\tphout->addKey (\"H\",LH.h,\"hubble\/100\");\n\tphout->addKey (\"W\",LH.wq,\"dark energy equation of state parameter\");\n\tphout->addKey (\"MSTAR\",LH.mstar,\"stellar mass of the BCG in Msun\/h\"); \n\tphout->addKey (\"MVIR\",LH.m,\"virial mass of the halo in Msun\/h\"); \n\tphout->addKey (\"CONCENTRATION\",LH.c,\"NFW concentration\");\n\tphout->addKey (\"DL\",LH.DL,\"Mpc\/h\");\n\tphout->addKey (\"DLS\",LH.DLS,\"Mpc\/h\");\n\tphout->addKey (\"DS\",LH.DS,\"Mpc\/h\");\n\t\n\n\tExtHDU *eh1=fout->addImage(\"gamma1\", FLOAT_IMG, naxex);\n\teh1->write(1,nx*ny,gamma1);\n\tExtHDU *eh2=fout->addImage(\"gamma2\", FLOAT_IMG, naxex);\n\teh2->write(1,nx*ny,gamma2);\n\tExtHDU *eh3=fout->addImage(\"gamma3\", FLOAT_IMG, naxex);\n\teh3->write(1,nx*ny,gamma3);\n\n\tstd::cout << *phout << std::endl;\n\n}\n\n\/*\n * routine used by fof to link nearby grid cell points\n *\/\n\nvoid make_friendship(int ii,int ji,int np,std:: vector<int> &friends, std:: vector<double> &pointdist){\n for(int jj=0;jj<np;jj++){\n if(friends[ji+np*jj]!=0){\n if(friends[ji+np*jj]<0){\n\tfriends[ii+np*jj]=-(ii+1);\t\n }\n else{\n\tfriends[ii+np*jj]=(ii+1);\n }\n friends[ji+np*jj]=0;\n }\n } \n friends[ii+np*ji]=-(ii+1);\n}\n\n\/*\n * given a a set of grid points xci and yci and an interpixeld distance l return the id of the \n * fof group of each cell point\n *\/\n\nint fof(double l,std:: vector<double> xci, std:: vector<double> yci, std:: vector<int> &groupid){\n int np = xci.size();\n std:: vector<int> friends(np*np);\n std:: vector<double> pointdist(np*np);\n for(int ii = 0;ii<np; ii++) for(int ji = 0;ji<np; ji++){\n pointdist[ii+np*ji] = sqrt( pow(xci[ii] - xci[ji],2) + pow(yci[ii] - yci[ji],2));\n groupid[ii] = 0;\n friends[ii+np*ji]=0;\n }\n for(int ii=0;ii<np;ii++) for(int ji = 0;ji<np; ji++){\n \/\/ consider as friends grid points less distant than 1.5 x l\n if(pointdist[ii+np*ji]<=1.5*l) friends[ii+np*ji] = ii+1;\n }\n for(int ii=0;ii<np;ii++){\n int r = 0;\n while(r==0){\n r=1;\n for(int ji=0;ji<np;ji++){\n\tif(friends[ii+np*ji]>0){\n\t if(ii!=ji){\n\t make_friendship(ii,ji,np,friends,pointdist);\n\t r=0;\n\t }\n\t}\n }\n }\n }\n for(int ii=0;ii<np;ii++){\n int p=0;\n for(int ji=0;ji<np;ji++){\n if(friends[ji+np*ii]!=0) p++;\n if(p==2){\n\tstd:: cout << ji << \" \" << ii << \": \" << friends[ji+np*ii] << \" \" << friends[ii+np*ji] << std:: endl;\n\texit(1);\n }\n }\n }\n \/\/ count the particles in each group\n int kt = 0;\n int ng= 0;\n for(int ii=0;ii<np;ii++){\n int k = 0;\n for(int ji=0;ji<np;ji++){\n if(friends[ii+np*ji]!=0){\n\tk++;\n\tgroupid[ji]=ii+1;\n }\n }\n if(k>0){\n ng++;\n }\n kt = kt + k;\n }\n if(kt != np){\n std:: cout << \" number of screaned particles : \" << kt << std:: endl;\n std:: cout << \" differes from the number of particles : \" << np << std:: endl;\n std:: cout << \" number of group found : \" << ng << std:: endl;\n std:: cout << \" \" << std:: endl;\n std:: cout << \" I will STOP here!!! \" << std:: endl;\n exit(1);\n }\n \/* Make a histogram of the data *\/\n std::vector< int > histogram(np,0);\n std::vector< int >::iterator it = groupid.begin();\n while(it != groupid.end()) histogram[*it++]++;\n int mode = std::max_element(histogram.begin(),histogram.end()) - histogram.begin();\n return mode;\n}\n\n#endif\n<commit_msg>check if noisy fits file exists...if so it stop<commit_after>\/*\n * fits.cpp\n *\n * Created on: Jun 19, 2012\n * Author: mpetkova\n *\/\n\n#ifdef WITH_MOKA\n\n#include <MOKAfits.h>\n#include <fstream>\n#include <CCfits\/CCfits>\n\nusing namespace CCfits;\n\nvoid getDims(std::string fn\n\t ,int *nx\n\t ,int *ny){\n\n\ttry{\n\t\tstd::auto_ptr<FITS> ff(new FITS (fn, Read));\n\n\t\tPHDU *h0=&ff->pHDU();\n\n\t\t*nx=h0->axis(0);\n\t\t*ny=h0->axis(1);\n\t}\n\tcatch(FITS::CantOpen){\n\t\tstd::cout << \"can not open \" << fn << std::endl;\n\t\texit(1);\n\t}\n}\n\n\/*\n * reads in the fits file for the MOKA map and saves it in the structure map\n *\/\nvoid readImage(std::string fn\n\t\t,std::valarray<float> *convergence\n\t\t,std::valarray<float> *alpha1\n\t\t,std::valarray<float> *alpha2\n\t\t,std::valarray<float> *gamma1\n\t\t,std::valarray<float> *gamma2\n\t ,struct LensHalo *LH){ \n\n\tint nx,ny;\n\n\tstd:: cout << \" reading MOKA file: \" << fn << std:: endl;\n\n\tstd::ostringstream checkfout;\n\tcheckfout << fn << \"_noisy.fits\";\t\n\tstd:: string checkfilenameout = checkfout.str();\n\tstd:: ifstream checkfileout;\n\tcheckfileout.open(checkfilenameout.c_str());\n\tif(checkfileout.is_open()){\n\t std:: cout << checkfilenameout << \" exists I will STOP here \" << std:: endl;\n\t std:: cout << \" halo already processed! \" << std:: endl;\n\t exit(1);\n\t}\n\n\tstd::auto_ptr<FITS> ff(new FITS (fn, Read));\n\n\tPHDU *h0=&ff->pHDU();\n\n\tnx=h0->axis(0);\n\tny=h0->axis(1);\n\n\th0->read(*convergence);\n\n\th0->readKey (\"SIDEL\",LH->boxlarcsec);\n\th0->readKey (\"SIDEL2\",LH->boxlMpc);\n\th0->readKey (\"ZLENS\",LH->zl);\n\th0->readKey (\"ZSOURCE\",LH->zs);\n\th0->readKey (\"OMEGA\",LH->omegam);\n\th0->readKey (\"LAMBDA\",LH->omegal);\n\th0->readKey (\"H\",LH->h);\n\th0->readKey (\"W\",LH->wq);\n\th0->readKey (\"MSTAR\",LH->mstar); \n\th0->readKey (\"MVIR\",LH->m); \n\th0->readKey (\"CONCENTRATION\",LH->c);\n\th0->readKey (\"DL\",LH->DL);\n\th0->readKey (\"DLS\",LH->DLS);\n\th0->readKey (\"DS\",LH->DS);\n\n\tExtHDU &h1=ff->extension(1);\n\th1.read(*alpha1);\n\tExtHDU &h2=ff->extension(2);\n\th2.read(*alpha2);\n\tExtHDU &h3=ff->extension(3);\n\th3.read(*gamma1);\n\tExtHDU &h4=ff->extension(4);\n\th4.read(*gamma2);\n\n\tstd::cout << *h0 << h1 << h2 << h3 << h4 << std::endl;\n}\n\n\/*\n * write the fits file of the new MOKA map from the structure map\n *\/\nvoid writeImage(std::string filename\n\t\t,std::valarray<float> convergence\n\t\t,std::valarray<float> gamma1\n\t\t,std::valarray<float> gamma2\n\t\t,std::valarray<float> gamma3\n\t\t,int nx\n\t\t,int ny\n\t\t,struct LensHalo LH){ \n\n\tlong naxis=2;\n\tlong naxes[2]={nx,ny};\n\n\tstd::auto_ptr<FITS> fout(0);\n\n\ttry{\n\t\tfout.reset(new FITS(filename,FLOAT_IMG,naxis,naxes));\n\t}\n\tcatch(FITS::CantCreate){\n\t\texit(1);\n\t}\n\n\tstd::vector<long> naxex(2);\n\tnaxex[0]=nx;\n\tnaxex[1]=ny;\n\n\tPHDU *phout=&fout->pHDU();\n\n\tphout->write( 1,nx*ny,convergence );\n\n\tphout->addKey (\"SIDEL\",LH.boxlarcsec,\"arcsec\");\n\tphout->addKey (\"SIDEL2\",LH.boxlMpc,\"Mpc\/h\");\n\tphout->addKey (\"ZLENS\",LH.zl,\"lens redshift\");\n\tphout->addKey (\"ZSOURCE\",LH.zs, \"source redshift\");\n\tphout->addKey (\"OMEGA\",LH.omegam,\"omega matter\");\n\tphout->addKey (\"LAMBDA\",LH.omegal,\"omega lamda\");\n\tphout->addKey (\"H\",LH.h,\"hubble\/100\");\n\tphout->addKey (\"W\",LH.wq,\"dark energy equation of state parameter\");\n\tphout->addKey (\"MSTAR\",LH.mstar,\"stellar mass of the BCG in Msun\/h\"); \n\tphout->addKey (\"MVIR\",LH.m,\"virial mass of the halo in Msun\/h\"); \n\tphout->addKey (\"CONCENTRATION\",LH.c,\"NFW concentration\");\n\tphout->addKey (\"DL\",LH.DL,\"Mpc\/h\");\n\tphout->addKey (\"DLS\",LH.DLS,\"Mpc\/h\");\n\tphout->addKey (\"DS\",LH.DS,\"Mpc\/h\");\n\t\n\n\tExtHDU *eh1=fout->addImage(\"gamma1\", FLOAT_IMG, naxex);\n\teh1->write(1,nx*ny,gamma1);\n\tExtHDU *eh2=fout->addImage(\"gamma2\", FLOAT_IMG, naxex);\n\teh2->write(1,nx*ny,gamma2);\n\tExtHDU *eh3=fout->addImage(\"gamma3\", FLOAT_IMG, naxex);\n\teh3->write(1,nx*ny,gamma3);\n\n\tstd::cout << *phout << std::endl;\n\n}\n\n\/*\n * routine used by fof to link nearby grid cell points\n *\/\n\nvoid make_friendship(int ii,int ji,int np,std:: vector<int> &friends, std:: vector<double> &pointdist){\n for(int jj=0;jj<np;jj++){\n if(friends[ji+np*jj]!=0){\n if(friends[ji+np*jj]<0){\n\tfriends[ii+np*jj]=-(ii+1);\t\n }\n else{\n\tfriends[ii+np*jj]=(ii+1);\n }\n friends[ji+np*jj]=0;\n }\n } \n friends[ii+np*ji]=-(ii+1);\n}\n\n\/*\n * given a a set of grid points xci and yci and an interpixeld distance l return the id of the \n * fof group of each cell point\n *\/\n\nint fof(double l,std:: vector<double> xci, std:: vector<double> yci, std:: vector<int> &groupid){\n int np = xci.size();\n std:: vector<int> friends(np*np);\n std:: vector<double> pointdist(np*np);\n for(int ii = 0;ii<np; ii++) for(int ji = 0;ji<np; ji++){\n pointdist[ii+np*ji] = sqrt( pow(xci[ii] - xci[ji],2) + pow(yci[ii] - yci[ji],2));\n groupid[ii] = 0;\n friends[ii+np*ji]=0;\n }\n for(int ii=0;ii<np;ii++) for(int ji = 0;ji<np; ji++){\n \/\/ consider as friends grid points less distant than 1.5 x l\n if(pointdist[ii+np*ji]<=1.5*l) friends[ii+np*ji] = ii+1;\n }\n for(int ii=0;ii<np;ii++){\n int r = 0;\n while(r==0){\n r=1;\n for(int ji=0;ji<np;ji++){\n\tif(friends[ii+np*ji]>0){\n\t if(ii!=ji){\n\t make_friendship(ii,ji,np,friends,pointdist);\n\t r=0;\n\t }\n\t}\n }\n }\n }\n for(int ii=0;ii<np;ii++){\n int p=0;\n for(int ji=0;ji<np;ji++){\n if(friends[ji+np*ii]!=0) p++;\n if(p==2){\n\tstd:: cout << ji << \" \" << ii << \": \" << friends[ji+np*ii] << \" \" << friends[ii+np*ji] << std:: endl;\n\texit(1);\n }\n }\n }\n \/\/ count the particles in each group\n int kt = 0;\n int ng= 0;\n for(int ii=0;ii<np;ii++){\n int k = 0;\n for(int ji=0;ji<np;ji++){\n if(friends[ii+np*ji]!=0){\n\tk++;\n\tgroupid[ji]=ii+1;\n }\n }\n if(k>0){\n ng++;\n }\n kt = kt + k;\n }\n if(kt != np){\n std:: cout << \" number of screaned particles : \" << kt << std:: endl;\n std:: cout << \" differes from the number of particles : \" << np << std:: endl;\n std:: cout << \" number of group found : \" << ng << std:: endl;\n std:: cout << \" \" << std:: endl;\n std:: cout << \" I will STOP here!!! \" << std:: endl;\n exit(1);\n }\n \/* Make a histogram of the data *\/\n std::vector< int > histogram(np,0);\n std::vector< int >::iterator it = groupid.begin();\n while(it != groupid.end()) histogram[*it++]++;\n int mode = std::max_element(histogram.begin(),histogram.end()) - histogram.begin();\n return mode;\n}\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/*****************************************************************************\n * ctrl_text.cpp\n *****************************************************************************\n * Copyright (C) 2003 the VideoLAN team\n * $Id$\n *\n * Authors: Cyril Deguet <asmax@via.ecp.fr>\n * Olivier Teulière <ipkiss@via.ecp.fr>\n * Erwan Tulou <erwan10 At videolan Dot org<\n *\n * This program is free software; you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.\n *****************************************************************************\/\n\n#include \"ctrl_text.hpp\"\n#include \"..\/events\/evt_generic.hpp\"\n#include \"..\/events\/evt_mouse.hpp\"\n#include \"..\/src\/generic_bitmap.hpp\"\n#include \"..\/src\/generic_font.hpp\"\n#include \"..\/src\/os_factory.hpp\"\n#include \"..\/src\/os_graphics.hpp\"\n#include \"..\/src\/os_timer.hpp\"\n#include \"..\/utils\/position.hpp\"\n#include \"..\/utils\/ustring.hpp\"\n#include \"..\/utils\/var_text.hpp\"\n\n\n#define MOVING_TEXT_STEP 1\n#define MOVING_TEXT_DELAY 30\n#define SEPARATOR_STRING \" \"\n\n\nCtrlText::CtrlText( intf_thread_t *pIntf, VarText &rVariable,\n const GenericFont &rFont, const UString &rHelp,\n uint32_t color, VarBool *pVisible, VarBool *pFocus,\n Scrolling_t scrollMode, Align_t alignment ):\n CtrlGeneric( pIntf, rHelp, pVisible ), m_fsm( pIntf ),\n m_rVariable( rVariable ), m_cmdToManual( this ),\n m_cmdManualMoving( this ), m_cmdManualStill( this ),\n m_cmdMove( this ), m_pEvt( NULL ), m_rFont( rFont ),\n m_color( color ), m_scrollMode( scrollMode ), m_alignment( alignment ),\n m_pFocus( pFocus), m_pImg( NULL ), m_pImgDouble( NULL ),\n m_pCurrImg( NULL ), m_xPos( 0 ), m_xOffset( 0 ),\n m_cmdUpdateText( this )\n{\n m_pTimer = OSFactory::instance( pIntf )->createOSTimer( m_cmdUpdateText );\n\n \/\/ States\n m_fsm.addState( \"still\" );\n m_fsm.addState( \"moving\" );\n m_fsm.addState( \"manual1\" );\n m_fsm.addState( \"manual2\" );\n m_fsm.addState( \"outStill\" );\n m_fsm.addState( \"outMoving\" );\n\n \/\/ Transitions\n m_fsm.addTransition( \"still\", \"leave\", \"outStill\" );\n m_fsm.addTransition( \"outStill\", \"enter\", \"still\" );\n if( m_scrollMode == kManual )\n {\n m_fsm.addTransition( \"still\", \"mouse:left:down\", \"manual1\",\n &m_cmdToManual );\n m_fsm.addTransition( \"manual1\", \"mouse:left:up\", \"still\",\n &m_cmdManualStill );\n m_fsm.addTransition( \"manual1\", \"motion\", \"manual1\", &m_cmdMove );\n }\n else if( m_scrollMode == kAutomatic )\n {\n m_fsm.addTransition( \"still\", \"mouse:left:down\", \"manual1\",\n &m_cmdToManual );\n m_fsm.addTransition( \"manual1\", \"mouse:left:up\", \"moving\",\n &m_cmdManualMoving );\n m_fsm.addTransition( \"moving\", \"mouse:left:down\", \"manual2\",\n &m_cmdToManual );\n m_fsm.addTransition( \"manual2\", \"mouse:left:up\", \"still\",\n &m_cmdManualStill );\n m_fsm.addTransition( \"manual1\", \"motion\", \"manual1\", &m_cmdMove );\n m_fsm.addTransition( \"manual2\", \"motion\", \"manual2\", &m_cmdMove );\n m_fsm.addTransition( \"moving\", \"leave\", \"outMoving\" );\n m_fsm.addTransition( \"outMoving\", \"enter\", \"moving\" );\n }\n\n \/\/ Initial state\n m_fsm.setState( (m_scrollMode != kAutomatic) ? \"outStill\" : \"outMoving\" );\n\n \/\/ Observe the variable\n m_rVariable.addObserver( this );\n\n \/\/ initialize pictures\n setPictures( m_rVariable.get() );\n}\n\n\nCtrlText::~CtrlText()\n{\n m_rVariable.delObserver( this );\n delete m_pTimer;\n delete m_pImg;\n delete m_pImgDouble;\n}\n\n\nvoid CtrlText::handleEvent( EvtGeneric &rEvent )\n{\n \/\/ Save the event to use it in callbacks\n m_pEvt = &rEvent;\n\n m_fsm.handleTransition( rEvent.getAsString() );\n}\n\n\nbool CtrlText::mouseOver( int x, int y ) const\n{\n if( !m_pFocus->get() )\n return false;\n\n if( m_pCurrImg )\n {\n \/\/ We have 3 different ways of deciding when to return true here:\n \/\/ 1) the mouse is exactly over the text (so if you click between two\n \/\/ letters, the text control doesn't catch the event)\n \/\/ 2) the mouse is over the rectangle of the control\n \/\/ 3) the mouse is over the rectangle of the visible text\n \/\/ I don't know which one is the best...\n#if 0\n return( x >= 0 && x < getPosition()->getWidth()\n && m_pCurrImg->hit( x - m_xPos, y ) );\n#endif\n#if 1\n return( x >= 0 && x < getPosition()->getWidth()\n && y >= 0 && y < getPosition()->getHeight() );\n#endif\n#if 0\n return( x >= 0 && x < getPosition()->getWidth()\n && y >= 0 && y < getPosition()->getHeight()\n && x < m_pCurrImg->getWidth() && x < m_pCurrImg->getHeight() );\n#endif\n }\n else\n {\n return false;\n }\n}\n\n\nvoid CtrlText::draw( OSGraphics &rImage, int xDest, int yDest, int w, int h )\n{\n rect clip( xDest, yDest, w, h );\n const Position *pPos = getPosition();\n if( m_pCurrImg )\n {\n \/\/ Compute the dimensions to draw\n int width = min( m_pCurrImg->getWidth() + m_xPos,\n getPosition()->getWidth() );\n int height = min( m_pCurrImg->getHeight(), getPosition()->getHeight() );\n \/\/ Draw the current image\n if( width > 0 && height > 0 )\n {\n int offset = 0;\n if( m_alignment == kLeft )\n {\n \/\/ We align to the left\n offset = 0;\n }\n else if( m_alignment == kRight &&\n width < getPosition()->getWidth() )\n\n {\n \/\/ The text is shorter than the width of the control, so we\n \/\/ can align it to the right\n offset = getPosition()->getWidth() - width;\n }\n else if( m_alignment == kCenter &&\n width < getPosition()->getWidth() )\n {\n \/\/ The text is shorter than the width of the control, so we\n \/\/ can center it\n offset = (getPosition()->getWidth() - width) \/ 2;\n }\n rect region( pPos->getLeft() + offset,\n pPos->getTop(), width, height );\n rect inter;\n if( rect::intersect( region, clip, &inter ) )\n rImage.drawBitmap( *m_pCurrImg, -m_xPos + inter.x - region.x,\n inter.y - region.y,\n inter.x, inter.y,\n inter.width, inter.height, true );\n }\n }\n}\n\n\nvoid CtrlText::setText( const UString &rText, uint32_t color )\n{\n \/\/ Change the color\n if( color != 0xFFFFFFFF )\n {\n m_color = color;\n }\n\n \/\/ Change the text\n m_rVariable.set( rText );\n}\n\n\nvoid CtrlText::onUpdate( Subject<VarText> &rVariable, void* arg )\n{\n (void)rVariable; (void)arg;\n if( isVisible() )\n {\n setPictures( m_rVariable.get() );\n updateContext();\n notifyLayout( getPosition()->getWidth(), getPosition()->getHeight() );\n }\n}\n\n\nvoid CtrlText::onUpdate( Subject<VarBool> &rVariable, void *arg )\n{\n (void)arg;\n \/\/ Visibility changed\n if( &rVariable == m_pVisible )\n {\n if( isVisible() )\n {\n setPictures( m_rVariable.get() );\n updateContext();\n notifyLayout( getPosition()->getWidth(), getPosition()->getHeight() );\n }\n }\n}\n\n\nvoid CtrlText::setPictures( const UString &rText )\n{\n \/\/ reset the images ('normal' and 'double') from the text\n \/\/ 'Normal' image\n delete m_pImg;\n m_pImg = m_rFont.drawString( rText, m_color );\n if( !m_pImg )\n return;\n\n \/\/ 'Double' image\n const UString doubleStringWithSep = rText + SEPARATOR_STRING + rText;\n delete m_pImgDouble;\n m_pImgDouble = m_rFont.drawString( doubleStringWithSep, m_color );\n}\n\n\nvoid CtrlText::updateContext()\n{\n if( !m_pImg || !getPosition() )\n return;\n\n if( m_pImg->getWidth() < getPosition()->getWidth() )\n {\n m_pCurrImg = m_pImg;\n\n \/\/ When the control becomes wide enough for the text to display,\n \/\/ make sure to stop any scrolling effect\n m_pTimer->stop();\n m_xPos = 0;\n }\n else\n {\n m_pCurrImg = m_pImgDouble;\n }\n\n \/\/ If the control is in the moving state,\n \/\/ automatically start or stop the timer accordingly\n const string &rState = m_fsm.getState();\n if( rState == \"moving\" || rState == \"outMoving\" )\n {\n if( m_pCurrImg == m_pImgDouble )\n {\n m_pTimer->start( MOVING_TEXT_DELAY, false );\n }\n else\n {\n m_pTimer->stop();\n }\n }\n\n \/\/ compute alignment\n if( m_alignment == kRight &&\n getPosition()->getWidth() < m_pImg->getWidth() )\n {\n m_xPos = getPosition()->getWidth() - m_pImg->getWidth();\n }\n else if( m_alignment == kCenter &&\n getPosition()->getWidth() < m_pImg->getWidth() )\n {\n m_xPos = (getPosition()->getWidth() - m_pImg->getWidth()) \/ 2;\n }\n else\n {\n m_xPos = 0;\n }\n}\n\n\nvoid CtrlText::onPositionChange()\n{\n updateContext();\n}\n\n\nvoid CtrlText::onResize()\n{\n updateContext();\n}\n\n\nvoid CtrlText::CmdToManual::execute()\n{\n EvtMouse *pEvtMouse = (EvtMouse*)m_pParent->m_pEvt;\n\n \/\/ Compute the offset\n m_pParent->m_xOffset = pEvtMouse->getXPos() - m_pParent->m_xPos;\n\n m_pParent->m_pTimer->stop();\n m_pParent->captureMouse();\n}\n\n\nvoid CtrlText::CmdManualMoving::execute()\n{\n m_pParent->releaseMouse();\n\n \/\/ Start the automatic movement, but only if the text is wider than the\n \/\/ control and if the control can scroll (either in manual or automatic\n \/\/ mode)\n if( m_pParent->m_pCurrImg &&\n m_pParent->m_pCurrImg == m_pParent->m_pImgDouble )\n {\n m_pParent->m_pTimer->start( MOVING_TEXT_DELAY, false );\n }\n}\n\n\nvoid CtrlText::CmdManualStill::execute()\n{\n m_pParent->releaseMouse();\n}\n\n\nvoid CtrlText::CmdMove::execute()\n{\n EvtMouse *pEvtMouse = (EvtMouse*)m_pParent->m_pEvt;\n\n \/\/ Move text only when it is larger than the control\n if( m_pParent->m_pCurrImg &&\n m_pParent->m_pCurrImg == m_pParent->m_pImgDouble )\n {\n \/\/ Compute the new position of the left side, and make sure it is\n \/\/ in the correct range\n m_pParent->m_xPos = (pEvtMouse->getXPos() - m_pParent->m_xOffset);\n m_pParent->adjust( m_pParent->m_xPos );\n\n m_pParent->notifyLayout( m_pParent->getPosition()->getWidth(),\n m_pParent->getPosition()->getHeight() );\n }\n}\n\n\nvoid CtrlText::CmdUpdateText::execute()\n{\n m_pParent->m_xPos -= MOVING_TEXT_STEP;\n m_pParent->adjust( m_pParent->m_xPos );\n\n m_pParent->notifyLayout( m_pParent->getPosition()->getWidth(),\n m_pParent->getPosition()->getHeight() );\n}\n\n\nvoid CtrlText::adjust( int &position )\n{\n if( !m_pImg || !m_pImgDouble )\n return;\n\n \/\/ {m_pImgDouble->getWidth() - m_pImg->getWidth()} is the period of the\n \/\/ bitmap; remember that the string used to generate m_pImgDouble is of the\n \/\/ form: \"foo foo\", the number of spaces being a parameter\n position %= m_pImgDouble->getWidth() - m_pImg->getWidth();\n if( position > 0 )\n {\n position -= m_pImgDouble->getWidth() - m_pImg->getWidth();\n }\n}\n\n<commit_msg>skins2: fix forgotten notify in text control<commit_after>\/*****************************************************************************\n * ctrl_text.cpp\n *****************************************************************************\n * Copyright (C) 2003 the VideoLAN team\n * $Id$\n *\n * Authors: Cyril Deguet <asmax@via.ecp.fr>\n * Olivier Teulière <ipkiss@via.ecp.fr>\n * Erwan Tulou <erwan10 At videolan Dot org<\n *\n * This program is free software; you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.\n *****************************************************************************\/\n\n#include \"ctrl_text.hpp\"\n#include \"..\/events\/evt_generic.hpp\"\n#include \"..\/events\/evt_mouse.hpp\"\n#include \"..\/src\/generic_bitmap.hpp\"\n#include \"..\/src\/generic_font.hpp\"\n#include \"..\/src\/os_factory.hpp\"\n#include \"..\/src\/os_graphics.hpp\"\n#include \"..\/src\/os_timer.hpp\"\n#include \"..\/utils\/position.hpp\"\n#include \"..\/utils\/ustring.hpp\"\n#include \"..\/utils\/var_text.hpp\"\n\n\n#define MOVING_TEXT_STEP 1\n#define MOVING_TEXT_DELAY 30\n#define SEPARATOR_STRING \" \"\n\n\nCtrlText::CtrlText( intf_thread_t *pIntf, VarText &rVariable,\n const GenericFont &rFont, const UString &rHelp,\n uint32_t color, VarBool *pVisible, VarBool *pFocus,\n Scrolling_t scrollMode, Align_t alignment ):\n CtrlGeneric( pIntf, rHelp, pVisible ), m_fsm( pIntf ),\n m_rVariable( rVariable ), m_cmdToManual( this ),\n m_cmdManualMoving( this ), m_cmdManualStill( this ),\n m_cmdMove( this ), m_pEvt( NULL ), m_rFont( rFont ),\n m_color( color ), m_scrollMode( scrollMode ), m_alignment( alignment ),\n m_pFocus( pFocus), m_pImg( NULL ), m_pImgDouble( NULL ),\n m_pCurrImg( NULL ), m_xPos( 0 ), m_xOffset( 0 ),\n m_cmdUpdateText( this )\n{\n m_pTimer = OSFactory::instance( pIntf )->createOSTimer( m_cmdUpdateText );\n\n \/\/ States\n m_fsm.addState( \"still\" );\n m_fsm.addState( \"moving\" );\n m_fsm.addState( \"manual1\" );\n m_fsm.addState( \"manual2\" );\n m_fsm.addState( \"outStill\" );\n m_fsm.addState( \"outMoving\" );\n\n \/\/ Transitions\n m_fsm.addTransition( \"still\", \"leave\", \"outStill\" );\n m_fsm.addTransition( \"outStill\", \"enter\", \"still\" );\n if( m_scrollMode == kManual )\n {\n m_fsm.addTransition( \"still\", \"mouse:left:down\", \"manual1\",\n &m_cmdToManual );\n m_fsm.addTransition( \"manual1\", \"mouse:left:up\", \"still\",\n &m_cmdManualStill );\n m_fsm.addTransition( \"manual1\", \"motion\", \"manual1\", &m_cmdMove );\n }\n else if( m_scrollMode == kAutomatic )\n {\n m_fsm.addTransition( \"still\", \"mouse:left:down\", \"manual1\",\n &m_cmdToManual );\n m_fsm.addTransition( \"manual1\", \"mouse:left:up\", \"moving\",\n &m_cmdManualMoving );\n m_fsm.addTransition( \"moving\", \"mouse:left:down\", \"manual2\",\n &m_cmdToManual );\n m_fsm.addTransition( \"manual2\", \"mouse:left:up\", \"still\",\n &m_cmdManualStill );\n m_fsm.addTransition( \"manual1\", \"motion\", \"manual1\", &m_cmdMove );\n m_fsm.addTransition( \"manual2\", \"motion\", \"manual2\", &m_cmdMove );\n m_fsm.addTransition( \"moving\", \"leave\", \"outMoving\" );\n m_fsm.addTransition( \"outMoving\", \"enter\", \"moving\" );\n }\n\n \/\/ Initial state\n m_fsm.setState( (m_scrollMode != kAutomatic) ? \"outStill\" : \"outMoving\" );\n\n \/\/ Observe the variable\n m_rVariable.addObserver( this );\n\n \/\/ initialize pictures\n setPictures( m_rVariable.get() );\n}\n\n\nCtrlText::~CtrlText()\n{\n m_rVariable.delObserver( this );\n delete m_pTimer;\n delete m_pImg;\n delete m_pImgDouble;\n}\n\n\nvoid CtrlText::handleEvent( EvtGeneric &rEvent )\n{\n \/\/ Save the event to use it in callbacks\n m_pEvt = &rEvent;\n\n m_fsm.handleTransition( rEvent.getAsString() );\n}\n\n\nbool CtrlText::mouseOver( int x, int y ) const\n{\n if( !m_pFocus->get() )\n return false;\n\n if( m_pCurrImg )\n {\n \/\/ We have 3 different ways of deciding when to return true here:\n \/\/ 1) the mouse is exactly over the text (so if you click between two\n \/\/ letters, the text control doesn't catch the event)\n \/\/ 2) the mouse is over the rectangle of the control\n \/\/ 3) the mouse is over the rectangle of the visible text\n \/\/ I don't know which one is the best...\n#if 0\n return( x >= 0 && x < getPosition()->getWidth()\n && m_pCurrImg->hit( x - m_xPos, y ) );\n#endif\n#if 1\n return( x >= 0 && x < getPosition()->getWidth()\n && y >= 0 && y < getPosition()->getHeight() );\n#endif\n#if 0\n return( x >= 0 && x < getPosition()->getWidth()\n && y >= 0 && y < getPosition()->getHeight()\n && x < m_pCurrImg->getWidth() && x < m_pCurrImg->getHeight() );\n#endif\n }\n else\n {\n return false;\n }\n}\n\n\nvoid CtrlText::draw( OSGraphics &rImage, int xDest, int yDest, int w, int h )\n{\n rect clip( xDest, yDest, w, h );\n const Position *pPos = getPosition();\n if( m_pCurrImg )\n {\n \/\/ Compute the dimensions to draw\n int width = min( m_pCurrImg->getWidth() + m_xPos,\n getPosition()->getWidth() );\n int height = min( m_pCurrImg->getHeight(), getPosition()->getHeight() );\n \/\/ Draw the current image\n if( width > 0 && height > 0 )\n {\n int offset = 0;\n if( m_alignment == kLeft )\n {\n \/\/ We align to the left\n offset = 0;\n }\n else if( m_alignment == kRight &&\n width < getPosition()->getWidth() )\n\n {\n \/\/ The text is shorter than the width of the control, so we\n \/\/ can align it to the right\n offset = getPosition()->getWidth() - width;\n }\n else if( m_alignment == kCenter &&\n width < getPosition()->getWidth() )\n {\n \/\/ The text is shorter than the width of the control, so we\n \/\/ can center it\n offset = (getPosition()->getWidth() - width) \/ 2;\n }\n rect region( pPos->getLeft() + offset,\n pPos->getTop(), width, height );\n rect inter;\n if( rect::intersect( region, clip, &inter ) )\n rImage.drawBitmap( *m_pCurrImg, -m_xPos + inter.x - region.x,\n inter.y - region.y,\n inter.x, inter.y,\n inter.width, inter.height, true );\n }\n }\n}\n\n\nvoid CtrlText::setText( const UString &rText, uint32_t color )\n{\n \/\/ Change the color\n if( color != 0xFFFFFFFF )\n {\n m_color = color;\n }\n\n \/\/ Change the text\n m_rVariable.set( rText );\n}\n\n\nvoid CtrlText::onUpdate( Subject<VarText> &rVariable, void* arg )\n{\n (void)rVariable; (void)arg;\n if( isVisible() )\n {\n setPictures( m_rVariable.get() );\n updateContext();\n notifyLayout( getPosition()->getWidth(), getPosition()->getHeight() );\n }\n}\n\n\nvoid CtrlText::onUpdate( Subject<VarBool> &rVariable, void *arg )\n{\n (void)arg;\n \/\/ Visibility changed\n if( &rVariable == m_pVisible )\n {\n if( isVisible() )\n {\n setPictures( m_rVariable.get() );\n updateContext();\n }\n\n \/\/ notify in any case\n notifyLayout( getPosition()->getWidth(), getPosition()->getHeight() );\n }\n}\n\n\nvoid CtrlText::setPictures( const UString &rText )\n{\n \/\/ reset the images ('normal' and 'double') from the text\n \/\/ 'Normal' image\n delete m_pImg;\n m_pImg = m_rFont.drawString( rText, m_color );\n if( !m_pImg )\n return;\n\n \/\/ 'Double' image\n const UString doubleStringWithSep = rText + SEPARATOR_STRING + rText;\n delete m_pImgDouble;\n m_pImgDouble = m_rFont.drawString( doubleStringWithSep, m_color );\n}\n\n\nvoid CtrlText::updateContext()\n{\n if( !m_pImg || !getPosition() )\n return;\n\n if( m_pImg->getWidth() < getPosition()->getWidth() )\n {\n m_pCurrImg = m_pImg;\n\n \/\/ When the control becomes wide enough for the text to display,\n \/\/ make sure to stop any scrolling effect\n m_pTimer->stop();\n m_xPos = 0;\n }\n else\n {\n m_pCurrImg = m_pImgDouble;\n }\n\n \/\/ If the control is in the moving state,\n \/\/ automatically start or stop the timer accordingly\n const string &rState = m_fsm.getState();\n if( rState == \"moving\" || rState == \"outMoving\" )\n {\n if( m_pCurrImg == m_pImgDouble )\n {\n m_pTimer->start( MOVING_TEXT_DELAY, false );\n }\n else\n {\n m_pTimer->stop();\n }\n }\n\n \/\/ compute alignment\n if( m_alignment == kRight &&\n getPosition()->getWidth() < m_pImg->getWidth() )\n {\n m_xPos = getPosition()->getWidth() - m_pImg->getWidth();\n }\n else if( m_alignment == kCenter &&\n getPosition()->getWidth() < m_pImg->getWidth() )\n {\n m_xPos = (getPosition()->getWidth() - m_pImg->getWidth()) \/ 2;\n }\n else\n {\n m_xPos = 0;\n }\n}\n\n\nvoid CtrlText::onPositionChange()\n{\n updateContext();\n}\n\n\nvoid CtrlText::onResize()\n{\n updateContext();\n}\n\n\nvoid CtrlText::CmdToManual::execute()\n{\n EvtMouse *pEvtMouse = (EvtMouse*)m_pParent->m_pEvt;\n\n \/\/ Compute the offset\n m_pParent->m_xOffset = pEvtMouse->getXPos() - m_pParent->m_xPos;\n\n m_pParent->m_pTimer->stop();\n m_pParent->captureMouse();\n}\n\n\nvoid CtrlText::CmdManualMoving::execute()\n{\n m_pParent->releaseMouse();\n\n \/\/ Start the automatic movement, but only if the text is wider than the\n \/\/ control and if the control can scroll (either in manual or automatic\n \/\/ mode)\n if( m_pParent->m_pCurrImg &&\n m_pParent->m_pCurrImg == m_pParent->m_pImgDouble )\n {\n m_pParent->m_pTimer->start( MOVING_TEXT_DELAY, false );\n }\n}\n\n\nvoid CtrlText::CmdManualStill::execute()\n{\n m_pParent->releaseMouse();\n}\n\n\nvoid CtrlText::CmdMove::execute()\n{\n EvtMouse *pEvtMouse = (EvtMouse*)m_pParent->m_pEvt;\n\n \/\/ Move text only when it is larger than the control\n if( m_pParent->m_pCurrImg &&\n m_pParent->m_pCurrImg == m_pParent->m_pImgDouble )\n {\n \/\/ Compute the new position of the left side, and make sure it is\n \/\/ in the correct range\n m_pParent->m_xPos = (pEvtMouse->getXPos() - m_pParent->m_xOffset);\n m_pParent->adjust( m_pParent->m_xPos );\n\n m_pParent->notifyLayout( m_pParent->getPosition()->getWidth(),\n m_pParent->getPosition()->getHeight() );\n }\n}\n\n\nvoid CtrlText::CmdUpdateText::execute()\n{\n m_pParent->m_xPos -= MOVING_TEXT_STEP;\n m_pParent->adjust( m_pParent->m_xPos );\n\n m_pParent->notifyLayout( m_pParent->getPosition()->getWidth(),\n m_pParent->getPosition()->getHeight() );\n}\n\n\nvoid CtrlText::adjust( int &position )\n{\n if( !m_pImg || !m_pImgDouble )\n return;\n\n \/\/ {m_pImgDouble->getWidth() - m_pImg->getWidth()} is the period of the\n \/\/ bitmap; remember that the string used to generate m_pImgDouble is of the\n \/\/ form: \"foo foo\", the number of spaces being a parameter\n position %= m_pImgDouble->getWidth() - m_pImg->getWidth();\n if( position > 0 )\n {\n position -= m_pImgDouble->getWidth() - m_pImg->getWidth();\n }\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/* This file is part of Text Fairy.\n \n Text Fairy is free software: you can redistribute it and\/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation, either version 3 of the License, or\n (at your option) any later version.\n \n Text Fairy is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n \n You should have received a copy of the GNU General Public License\n along with Text Fairy. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n\n\/*\n * pageseg.cpp\n *\n * Created on: Mar 1, 2012\n * Author: renard\n *\/\n\n#include \"pageseg.h\"\n\nusing namespace std;\n\nl_int32 renderTransformedBoxa(PIX *pixt, BOXA *boxa, l_int32 i) {\n\tl_int32 j, n, rval, gval, bval;\n\tBOX *box;\n\n\tn = boxaGetCount(boxa);\n\trval = (1413 * i) % 256;\n\tgval = (4917 * i) % 256;\n\tbval = (7341 * i) % 256;\n\tfor (j = 0; j < n; j++) {\n\t\tbox = boxaGetBox(boxa, j, L_CLONE);\n\t\tpixRenderHashBoxArb(pixt, box, 10, 3, i % 4, 1, rval, gval, bval);\n\t\tboxDestroy(&box);\n\t}\n\treturn 0;\n}\n\nl_int32 getMedianComponentHeight(Pix* pixtl, bool debug) {\n\tostringstream s;\n\tPixa* comp;\n\tBoxa* tl = pixConnComp(pixtl, &comp, 4);\n\tNUMA* na = pixaCountPixels(comp);\n\n\tBox* b;\n\tint n = boxaGetCount(tl);\n\tfloat cc = 0;\n\tfor (int i = 0; i < n; i++) {\n\t\tb = boxaGetBox(tl, i, L_CLONE);\n\t\tfloat c;\n\t\tnumaGetFValue(na, i, &c);\n\t\tc \/= b->w;\n\t\tnumaSetValue(na, i, c);\n\t\tcc += c;\n\t\tboxDestroy(&b);\n\t}\n\tif (n > 0) {\n\t\tcc \/= n;\n\t}\n\n\tfloat median = 0;\n\tnumaGetRankValue(na, 0.75, &median);\n\t\/\/numaGetMedian(na, &median);\n\tnumaDestroy(&na);\n\tpixaDestroy(&comp);\n\tboxaDestroy(&tl);\n\tif (debug) {\n\t\tstd::cout << \"average: \" << cc << \"\\n\" << \"median: \" << median << \"\\n\";\n\t}\n\treturn median;\n}\n\nvoid growTextBounds(Boxa* textBounds) {\n\tint n = boxaGetCount(textBounds);\n\tBOX *box;\n\tfor (int j = 0; j < n; j++) {\n\t\tbox = boxaGetBox(textBounds, j, L_CLONE);\n\t\tboxAdjustSides(box,box,-5,5,-5,5);\n\t\tboxDestroy(&box);\n\t}\n}\n\nPixa* pagesegGetColumns(Pix* pixtext, bool debug) {\n\tostringstream s;\n\tPIX *pixb, *pixBinary;\n\tif (debug) {\n\t\tstartTimer();\n\t}\n\tint w = pixGetHeight(pixtext);\n\n\ts << \"o1.20+c5.20+d10.5+o1.\" << w \/ 10;\n\n\t\/*remove long vertical lines*\/\n\tPix* pixvl = pixMorphCompSequence(pixtext, s.str().c_str(), 0);\n\tpixSetMasked(pixtext, pixvl, 0);\n\tpixDestroy(&pixvl);\n\n\tpixBinary = pixReduceRankBinaryCascade(pixtext, 1, 0, 0, 0);\n\n\n\t\/*remove long horizontal lines*\/\n\tPix* pixhl = pixMorphCompSequence(pixBinary, \"o70.1+c20.5+d5.10\", 0);\n\tpixSetMasked(pixBinary, pixhl, 0);\n\tpixDestroy(&pixhl);\n\n\tpixb = pixInvert(NULL, pixBinary);\n\n\t\/*create vertical whitespace mask*\/\n\t\/\/Pix *pixvws = pixMorphCompSequence(pixb, \"o1.100+c2.1+o7.1+c7.10+c1.50\", 0);\n\tPix *pixvws = pixMorphCompSequence(pixb, \"o1.100+c2.1+o7.1+c7.10\", 0);\n\n\t\/* Three steps to getting text line mask:\n\t * (1) close the characters and words in the textlines\n\t * (2) open the vertical whitespace corridors back up\n\t * (3) small opening to remove noise *\/\n\tpixCloseSafeBrick(pixBinary, pixBinary, 60, 1);\n\tpixDisplay(pixBinary,0,0);\n\tpixSubtract(pixBinary, pixBinary, pixvws);\n\tpixOpenBrick(pixBinary, pixBinary, 1, 3);\n\tPix* pixtl = pixMorphCompSequence(pixBinary, \"o1.3+o25.1\", 0);\n\tpixDestroy(&pixBinary);\n\n\t\/*make a guess at the text size*\/\n\tint ts = getMedianComponentHeight(pixtl, debug);\n\tpixBinary = pixtl;\n\n\t\/*close inter word spacing*\/\n\tpixCloseBrick(pixtl, pixtl, ts * 2, 1);\n\tpixOpenBrick(pixvws, pixvws, ts * 1.2, 1);\n\n\t\/*make a guess at the line spacing*\/\n\t\/*create components for vertical white space between text lines *\/\n\ts.str(\"\");\n\ts << \"c1.\" << ts * 3;\n\tPix* pixls = pixMorphCompSequence(pixtl, s.str().c_str(), 0);\n\tpixSubtract(pixls, pixls, pixtl);\n\t\/*small opening to remove noise*\/\n\tpixOpenBrick(pixls, pixls, 2, 2);\n\tint ls = getMedianComponentHeight(pixls, debug);\n\tpixDestroy(&pixls);\n\n\t\/*create horizontal whitespace mask*\/\n\ts.str(\"\");\n\ts << \"o50.1\";\n\tPix *pixhws = pixMorphCompSequence(pixb, s.str().c_str(), 0);\n\tpixDestroy(&pixb);\n\t\/\/\tpixOpenBrick(pixhws, pixhws, 1, ls * 1.6);\n\tpixOpenBrick(pixhws, pixhws, 1, ls * 1.5);\n\n\t\/* Join pixels vertically to make a textblock mask *\/\n\ts.str(\"\");\n\ts << \"c\" << ts << \".\" << ts * 8 << \"+ o4.1\";\n\tpixb = pixBinary;\n\tpixBinary = pixMorphSequence(pixb, s.str().c_str(), 0);\n\tpixDestroy(&pixb);\n\tpixSubtract(pixBinary, pixBinary, pixhws);\n\tpixDestroy(&pixhws);\n\n\n\t\/* Solidify the textblock mask and remove noise:\n\t * (1) For each cc, close the blocks and dilate slightly to form a solid mask.\n\t * (2) Small horizontal closing between components.\n\t * (3) Open the white space between columns, again.\n\t * (4) Remove small components. *\/\n\ts.str(\"\");\n\ts << \"c\" << ts << \".\" << ts << \"+d3.3\";\n\tPix* pixt2 = pixMorphSequenceByComponent(pixBinary, s.str().c_str(), 8, 0, 0, NULL);\n\tpixDestroy(&pixBinary);\n\tpixCloseSafeBrick(pixt2, pixt2, 10, 1);\n\tpixSubtract(pixt2, pixt2, pixvws);\n\n\tPix* pixd = pixSelectBySize(pixt2, ts * 5, ts, 4, L_SELECT_IF_EITHER, L_SELECT_IF_GTE, NULL);\n\tpixDestroy(&pixvws);\n\tpixDestroy(&pixt2);\n\n\t\/*separate connected columns*\/\n\t\/\/\ts.str(\"\");\n\t\/\/\ts<<\"c1.30\"<<\"+o1.\"<<ts*20;\n\t\/\/\tPix* pixsep = pixMorphSequenceByComponent(pixd,\"c1.30+o1.130\",4,ts,ts*10,NULL);\n\t\/\/\tPix* pixsep2 = pixMorphCompSequence(pixsep,\"c50.1\",0);\n\t\/\/\tpixSubtract(pixsep2,pixsep2,pixsep);\n\t\/\/\tpixDestroy(&pixsep);\n\t\/\/\tpixSubtract(pixd,pixd,pixsep2);\n\t\/\/\tpixDestroy(&pixsep2);\n\t\/* Expand mask to full resolution, and do filling or\n\t * small dilations for better coverage. *\/\n\tpixBinary = pixExpandReplicate(pixd, 2);\n\tpixDestroy(&pixd);\n\tpixDilateBrick(pixBinary, pixBinary, 3, 3);\n\n\tBoxa* boxatext = pixConnCompBB(pixBinary, 8);\n\n\t\/\/growTextBounds(boxatext);\n\n\tpixDestroy(&pixBinary);\n\tPixa* pixaText = pixaCreateFromBoxa(pixtext, boxatext, NULL);\n\tboxaDestroy(&boxatext);\n\tif (debug) {\n\t\tPix* pixdisplay = pixaDisplay(pixaText, 0, 0);\n\t\tpixDisplay(pixdisplay, 0, 0);\n\t\tstd::cout << \"pagesegmentation took: \" << stopTimer() << std::endl;\n\t}\n\treturn pixaText;\n}\n\n\n\n\n\n\nvoid segmentComplexLayout(Pix* pixOrg,Pix* pixhm, Pix* pixb, Pixa** pixaImage, Pixa** pixaText,void(*callback) (const Pix*), bool debug) {\n\tostringstream debugstring;\n\n\tif (debug) {\n\t\tstartTimer();\n\t}\n\n\tif (debug) {\n\t\tdebugstring << \"Image-Text separation: \" << stopTimer() << std::endl;\n\t\tstartTimer();\n\t}\n\t\/*create preview image*\/\n\tPix* pixpreview = NULL;\n\tif (pixhm != NULL) {\n\t\tPix* pixb2 = pixReduceBinary2(pixb, NULL);\n\t\tPix* pixhm2 = pixReduceBinary2(pixhm, NULL);\n\t\tPix* pixtext32 = pixConvertTo32(pixb2);\n\t\tPix* pixOrg2 = pixScale(pixOrg, 0.5, 0.5);\n\t\tpixDestroy(&pixb2);\n\t\tpixInvert(pixhm2, pixhm2);\n\t\tpixPaintThroughMask(pixOrg2, pixhm2, 0, 0, 0);\n\t\tpixDestroy(&pixhm2);\n\t\tPix* pixmask = pixConvertTo1(pixOrg2, 1);\n\t\tpixCombineMasked(pixOrg2, pixtext32, pixmask);\n\t\tpixDestroy(&pixmask);\n\t\tpixDestroy(&pixtext32);\n\t\tpixpreview = pixOrg2;\n\t} else {\n\t\tPix* pixb2 = pixReduceBinary2(pixb, NULL);\n\t\tPix* pixtext32 = pixConvertTo32(pixb2);\n\t\tpixDestroy(&pixb2);\n\t\tpixpreview = pixtext32;\n\t}\n\n\tif (debug) {\n\t\tdebugstring << \"Preview-Image generation: \" << stopTimer() << std::endl;\n\t}\n\n\tcallback(pixpreview);\n\n\tif (debug) {\n\t\tstartTimer();\n\n\t}\n\t*pixaText = pagesegGetColumns(pixb, false);\n\tpixDestroy(&pixb);\n\n\tif (pixhm != NULL) {\n\t\tBoxa* boxa = pixConnCompBB(pixhm, 8);\n\t\t*pixaImage = pixaCreateFromBoxa(pixOrg, boxa, NULL);\n\t\tboxaDestroy(&boxa);\n\t\tpixDestroy(&pixhm);\n\t} else {\n\t\t*pixaImage = NULL;\n\t}\n\n\tif (debug) {\n\t\tdebugstring << \"Page Segmentation: \" << stopTimer() << std::endl;\n\t\tprintf(\"%s\",debugstring.str().c_str());\n\t}\n}\n\n\n\nvoid extractImages(Pix* pixOrg, Pix** pixhm, Pix** pixg) {\n\n\t\/*do a quick and dirty binarization*\/\n\t\/* Convert the RGB image to grayscale. *\/\n\t\/\/*pixg = pixConvertRGBToGrayFast(pixOrg);\n\tint depth = pixGetDepth(pixOrg);\n\tif (depth == 32) {\n\t\t*pixg = pixConvertRGBToLuminance(pixOrg);\n\t} else {\n\t\t*pixg = pixOrg;\n\t}\n\n\tostringstream s;\n\tint width = pixGetWidth(*pixg);\n\tint scale = 1;\n\tif (width > 512 && width < 2048) {\n\t\tscale = 2;\n\t} else if (width > 2048) {\n\t\tscale = 4;\n\t}\n\n\tPix* pixsgc = pixScaleGrayRank2(*pixg, scale);\n\n\t\/\/Pix* pixb2 = pixMaskedThreshOnBackgroundNorm(pixsgc,NULL,10,15,25,10,2,2,0.1,NULL);\n\tPix* pixb2 = pixOtsuThreshOnBackgroundNorm(pixsgc, NULL, 20, 30, 100, 100, 250, 2, 2, 0.43, NULL);\n\t\/\/Pix* pixb2 = pixOtsuThreshOnBackgroundNorm(pixsgc, NULL, 20, 30, 100, 100, 200, 8, 8, 0.1, NULL);\n\tpixDestroy(&pixsgc);\n\n\t\/*find 'colourful' pixels*\/\n\/\/\tPix* pixColOrg = pixScaleByIntSubsampling(pixOrg,4);\n\/\/\tpixGetAverageMaskedRGB(pixColOrg,NULL,0,0,1, L_MEAN_ABSVAL,&r,&g,&b);\n\/\/\tPix* pixcol = pixColorMagnitude(pixColOrg,abs(r),abs(g),abs(b),L_MAX_DIFF_FROM_AVERAGE_2);\n\/\/\tpixDestroy(&pixColOrg);\n\/\/\tpixInvert(pixcol,pixcol);\n\/\/\tPix *pixmask2 = pixOtsuThreshOnBackgroundNorm(pixcol, NULL, 20, 30, 20, 100, 200, 0, 0, 0.1, NULL);\n\/\/\n\/\/\tpixDestroy(&pixcol);\n\/\/\tPix* pixmask = pixExpandBinaryPower2(pixmask2,2);\n\/\/\tpixDestroy(&pixmask2);\n\/\/\tpixOr(pixb2,pixb2,pixmask);\n\/\/\tpixDestroy(&pixmask);\n\t\/*create image mask*\/\n\t\/* Get seed for halftone parts *\/\n\tPix* pixt1 = pixReduceRankBinaryCascade(pixb2, 4, 4, 3, 0);\n\tPix* pixt2 = pixOpenBrick(NULL, pixt1, 3, 3);\n\tint hasNoImages;\n\tpixZero(pixt2, &hasNoImages);\n\tif (!hasNoImages) {\n\t\tPix* pixhs = pixExpandBinaryPower2(pixt2, 8);\n\n\t\tpixDestroy(&pixt1);\n\t\tpixDestroy(&pixt2);\n\t\t\/* Get mask for connected regions *\/\n\t\tPix* pixm = pixCloseSafeBrick(NULL, pixb2, 4, 4);\n\t\t\/* Fill seed into mask to get halftone mask *\/\n\t\tPix* pixhm1 = pixSeedfillBinary(NULL, pixhs, pixm, 4);\n\t\tpixDestroy(&pixhs);\n\t\tpixDestroy(&pixm);\n\t\t\/*expand mask*\/\n\t\tpixCloseBrickDwa(pixhm1, pixhm1, 30, 30);\n\t\tPix* pixhm2 = pixFillClosedBorders(pixhm1, 4);\n\t\tpixDestroy(&pixhm1);\n\t\t*pixhm = pixExpandBinaryPower2(pixhm2, 2);\n\t\tpixDestroy(&pixhm2);\n\t} else {\n\t\t*pixhm = NULL;\n\t\tpixDestroy(&pixt1);\n\t\tpixDestroy(&pixt2);\n\t}\n\tpixDestroy(&pixb2);\n}\n\n\n<commit_msg>theoretically i could use the binary image to mask the text areas so that each column does not contain text from adjactend columns<commit_after>\/* This file is part of Text Fairy.\n \n Text Fairy is free software: you can redistribute it and\/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation, either version 3 of the License, or\n (at your option) any later version.\n \n Text Fairy is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n \n You should have received a copy of the GNU General Public License\n along with Text Fairy. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n\n\/*\n * pageseg.cpp\n *\n * Created on: Mar 1, 2012\n * Author: renard\n *\/\n\n#include \"pageseg.h\"\n\nusing namespace std;\n\nl_int32 renderTransformedBoxa(PIX *pixt, BOXA *boxa, l_int32 i) {\n\tl_int32 j, n, rval, gval, bval;\n\tBOX *box;\n\n\tn = boxaGetCount(boxa);\n\trval = (1413 * i) % 256;\n\tgval = (4917 * i) % 256;\n\tbval = (7341 * i) % 256;\n\tfor (j = 0; j < n; j++) {\n\t\tbox = boxaGetBox(boxa, j, L_CLONE);\n\t\tpixRenderHashBoxArb(pixt, box, 10, 3, i % 4, 1, rval, gval, bval);\n\t\tboxDestroy(&box);\n\t}\n\treturn 0;\n}\n\nl_int32 getMedianComponentHeight(Pix* pixtl, bool debug) {\n\tostringstream s;\n\tPixa* comp;\n\tBoxa* tl = pixConnComp(pixtl, &comp, 4);\n\tNUMA* na = pixaCountPixels(comp);\n\n\tBox* b;\n\tint n = boxaGetCount(tl);\n\tfloat cc = 0;\n\tfor (int i = 0; i < n; i++) {\n\t\tb = boxaGetBox(tl, i, L_CLONE);\n\t\tfloat c;\n\t\tnumaGetFValue(na, i, &c);\n\t\tc \/= b->w;\n\t\tnumaSetValue(na, i, c);\n\t\tcc += c;\n\t\tboxDestroy(&b);\n\t}\n\tif (n > 0) {\n\t\tcc \/= n;\n\t}\n\n\tfloat median = 0;\n\tnumaGetRankValue(na, 0.75, &median);\n\t\/\/numaGetMedian(na, &median);\n\tnumaDestroy(&na);\n\tpixaDestroy(&comp);\n\tboxaDestroy(&tl);\n\tif (debug) {\n\t\tstd::cout << \"average: \" << cc << \"\\n\" << \"median: \" << median << \"\\n\";\n\t}\n\treturn median;\n}\n\nvoid growTextBounds(Boxa* textBounds) {\n\tint n = boxaGetCount(textBounds);\n\tBOX *box;\n\tfor (int j = 0; j < n; j++) {\n\t\tbox = boxaGetBox(textBounds, j, L_CLONE);\n\t\tboxAdjustSides(box,box,-5,5,-5,5);\n\t\tboxDestroy(&box);\n\t}\n}\n\nPixa* pagesegGetColumns(Pix* pixtext, bool debug) {\n\tostringstream s;\n\tPIX *pixb, *pixBinary;\n\tif (debug) {\n\t\tstartTimer();\n\t}\n\tint w = pixGetHeight(pixtext);\n\n\ts << \"o1.20+c5.20+d10.5+o1.\" << w \/ 10;\n\n\t\/*remove long vertical lines*\/\n\tPix* pixvl = pixMorphCompSequence(pixtext, s.str().c_str(), 0);\n\tpixSetMasked(pixtext, pixvl, 0);\n\tpixDestroy(&pixvl);\n\n\tpixBinary = pixReduceRankBinaryCascade(pixtext, 1, 0, 0, 0);\n\n\n\t\/*remove long horizontal lines*\/\n\tPix* pixhl = pixMorphCompSequence(pixBinary, \"o70.1+c20.5+d5.10\", 0);\n\tpixSetMasked(pixBinary, pixhl, 0);\n\tpixDestroy(&pixhl);\n\n\tpixb = pixInvert(NULL, pixBinary);\n\n\t\/*create vertical whitespace mask*\/\n\t\/\/Pix *pixvws = pixMorphCompSequence(pixb, \"o1.100+c2.1+o7.1+c7.10+c1.50\", 0);\n\tPix *pixvws = pixMorphCompSequence(pixb, \"o1.100+c2.1+o7.1+c7.10\", 0);\n\n\t\/* Three steps to getting text line mask:\n\t * (1) close the characters and words in the textlines\n\t * (2) open the vertical whitespace corridors back up\n\t * (3) small opening to remove noise *\/\n\tpixCloseSafeBrick(pixBinary, pixBinary, 60, 1);\n\tpixDisplay(pixBinary,0,0);\n\tpixSubtract(pixBinary, pixBinary, pixvws);\n\tpixOpenBrick(pixBinary, pixBinary, 1, 3);\n\tPix* pixtl = pixMorphCompSequence(pixBinary, \"o1.3+o25.1\", 0);\n\tpixDestroy(&pixBinary);\n\n\t\/*make a guess at the text size*\/\n\tint ts = getMedianComponentHeight(pixtl, debug);\n\tpixBinary = pixtl;\n\n\t\/*close inter word spacing*\/\n\tpixCloseBrick(pixtl, pixtl, ts * 2, 1);\n\tpixOpenBrick(pixvws, pixvws, ts * 1.2, 1);\n\n\t\/*make a guess at the line spacing*\/\n\t\/*create components for vertical white space between text lines *\/\n\ts.str(\"\");\n\ts << \"c1.\" << ts * 3;\n\tPix* pixls = pixMorphCompSequence(pixtl, s.str().c_str(), 0);\n\tpixSubtract(pixls, pixls, pixtl);\n\t\/*small opening to remove noise*\/\n\tpixOpenBrick(pixls, pixls, 2, 2);\n\tint ls = getMedianComponentHeight(pixls, debug);\n\tpixDestroy(&pixls);\n\n\t\/*create horizontal whitespace mask*\/\n\ts.str(\"\");\n\ts << \"o50.1\";\n\tPix *pixhws = pixMorphCompSequence(pixb, s.str().c_str(), 0);\n\tpixDestroy(&pixb);\n\t\/\/\tpixOpenBrick(pixhws, pixhws, 1, ls * 1.6);\n\tpixOpenBrick(pixhws, pixhws, 1, ls * 1.5);\n\n\t\/* Join pixels vertically to make a textblock mask *\/\n\ts.str(\"\");\n\ts << \"c\" << ts << \".\" << ts * 8 << \"+ o4.1\";\n\tpixb = pixBinary;\n\tpixBinary = pixMorphSequence(pixb, s.str().c_str(), 0);\n\tpixDestroy(&pixb);\n\tpixSubtract(pixBinary, pixBinary, pixhws);\n\tpixDestroy(&pixhws);\n\n\n\t\/* Solidify the textblock mask and remove noise:\n\t * (1) For each cc, close the blocks and dilate slightly to form a solid mask.\n\t * (2) Small horizontal closing between components.\n\t * (3) Open the white space between columns, again.\n\t * (4) Remove small components. *\/\n\ts.str(\"\");\n\ts << \"c\" << ts << \".\" << ts << \"+d3.3\";\n\tPix* pixt2 = pixMorphSequenceByComponent(pixBinary, s.str().c_str(), 8, 0, 0, NULL);\n\tpixDestroy(&pixBinary);\n\tpixCloseSafeBrick(pixt2, pixt2, 10, 1);\n\tpixSubtract(pixt2, pixt2, pixvws);\n\n\tPix* pixd = pixSelectBySize(pixt2, ts * 5, ts, 4, L_SELECT_IF_EITHER, L_SELECT_IF_GTE, NULL);\n\tpixDestroy(&pixvws);\n\tpixDestroy(&pixt2);\n\n\t\/*separate connected columns*\/\n\t\/\/\ts.str(\"\");\n\t\/\/\ts<<\"c1.30\"<<\"+o1.\"<<ts*20;\n\t\/\/\tPix* pixsep = pixMorphSequenceByComponent(pixd,\"c1.30+o1.130\",4,ts,ts*10,NULL);\n\t\/\/\tPix* pixsep2 = pixMorphCompSequence(pixsep,\"c50.1\",0);\n\t\/\/\tpixSubtract(pixsep2,pixsep2,pixsep);\n\t\/\/\tpixDestroy(&pixsep);\n\t\/\/\tpixSubtract(pixd,pixd,pixsep2);\n\t\/\/\tpixDestroy(&pixsep2);\n\t\/* Expand mask to full resolution, and do filling or\n\t * small dilations for better coverage. *\/\n\tpixBinary = pixExpandReplicate(pixd, 2);\n\tpixDestroy(&pixd);\n\tpixDilateBrick(pixBinary, pixBinary, 3, 3);\n\n\tBoxa* boxatext = pixConnCompBB(pixBinary, 8);\n\t\/\/growTextBounds(boxatext);\n\tPixa* pixaText = pixaCreateFromBoxa(pixtext, boxatext, NULL);\n\t\/\/substract\n\tpixDestroy(&pixBinary);\n\tboxaDestroy(&boxatext);\n\tif (debug) {\n\t\tPix* pixdisplay = pixaDisplay(pixaText, 0, 0);\n\t\tpixDisplay(pixdisplay, 0, 0);\n\t\tstd::cout << \"pagesegmentation took: \" << stopTimer() << std::endl;\n\t}\n\treturn pixaText;\n}\n\n\n\n\n\n\nvoid segmentComplexLayout(Pix* pixOrg,Pix* pixhm, Pix* pixb, Pixa** pixaImage, Pixa** pixaText,void(*callback) (const Pix*), bool debug) {\n\tostringstream debugstring;\n\n\tif (debug) {\n\t\tstartTimer();\n\t}\n\n\tif (debug) {\n\t\tdebugstring << \"Image-Text separation: \" << stopTimer() << std::endl;\n\t\tstartTimer();\n\t}\n\t\/*create preview image*\/\n\tPix* pixpreview = NULL;\n\tif (pixhm != NULL) {\n\t\tPix* pixb2 = pixReduceBinary2(pixb, NULL);\n\t\tPix* pixhm2 = pixReduceBinary2(pixhm, NULL);\n\t\tPix* pixtext32 = pixConvertTo32(pixb2);\n\t\tPix* pixOrg2 = pixScale(pixOrg, 0.5, 0.5);\n\t\tpixDestroy(&pixb2);\n\t\tpixInvert(pixhm2, pixhm2);\n\t\tpixPaintThroughMask(pixOrg2, pixhm2, 0, 0, 0);\n\t\tpixDestroy(&pixhm2);\n\t\tPix* pixmask = pixConvertTo1(pixOrg2, 1);\n\t\tpixCombineMasked(pixOrg2, pixtext32, pixmask);\n\t\tpixDestroy(&pixmask);\n\t\tpixDestroy(&pixtext32);\n\t\tpixpreview = pixOrg2;\n\t} else {\n\t\tPix* pixb2 = pixReduceBinary2(pixb, NULL);\n\t\tPix* pixtext32 = pixConvertTo32(pixb2);\n\t\tpixDestroy(&pixb2);\n\t\tpixpreview = pixtext32;\n\t}\n\n\tif (debug) {\n\t\tdebugstring << \"Preview-Image generation: \" << stopTimer() << std::endl;\n\t}\n\n\tcallback(pixpreview);\n\n\tif (debug) {\n\t\tstartTimer();\n\n\t}\n\t*pixaText = pagesegGetColumns(pixb, false);\n\tpixDestroy(&pixb);\n\n\tif (pixhm != NULL) {\n\t\tBoxa* boxa = pixConnCompBB(pixhm, 8);\n\t\t*pixaImage = pixaCreateFromBoxa(pixOrg, boxa, NULL);\n\t\tboxaDestroy(&boxa);\n\t\tpixDestroy(&pixhm);\n\t} else {\n\t\t*pixaImage = NULL;\n\t}\n\n\tif (debug) {\n\t\tdebugstring << \"Page Segmentation: \" << stopTimer() << std::endl;\n\t\tprintf(\"%s\",debugstring.str().c_str());\n\t}\n}\n\n\n\nvoid extractImages(Pix* pixOrg, Pix** pixhm, Pix** pixg) {\n\n\t\/*do a quick and dirty binarization*\/\n\t\/* Convert the RGB image to grayscale. *\/\n\t\/\/*pixg = pixConvertRGBToGrayFast(pixOrg);\n\tint depth = pixGetDepth(pixOrg);\n\tif (depth == 32) {\n\t\t*pixg = pixConvertRGBToLuminance(pixOrg);\n\t} else {\n\t\t*pixg = pixOrg;\n\t}\n\n\tostringstream s;\n\tint width = pixGetWidth(*pixg);\n\tint scale = 1;\n\tif (width > 512 && width < 2048) {\n\t\tscale = 2;\n\t} else if (width > 2048) {\n\t\tscale = 4;\n\t}\n\n\tPix* pixsgc = pixScaleGrayRank2(*pixg, scale);\n\n\t\/\/Pix* pixb2 = pixMaskedThreshOnBackgroundNorm(pixsgc,NULL,10,15,25,10,2,2,0.1,NULL);\n\tPix* pixb2 = pixOtsuThreshOnBackgroundNorm(pixsgc, NULL, 20, 30, 100, 100, 250, 2, 2, 0.43, NULL);\n\t\/\/Pix* pixb2 = pixOtsuThreshOnBackgroundNorm(pixsgc, NULL, 20, 30, 100, 100, 200, 8, 8, 0.1, NULL);\n\tpixDestroy(&pixsgc);\n\n\t\/*find 'colourful' pixels*\/\n\/\/\tPix* pixColOrg = pixScaleByIntSubsampling(pixOrg,4);\n\/\/\tpixGetAverageMaskedRGB(pixColOrg,NULL,0,0,1, L_MEAN_ABSVAL,&r,&g,&b);\n\/\/\tPix* pixcol = pixColorMagnitude(pixColOrg,abs(r),abs(g),abs(b),L_MAX_DIFF_FROM_AVERAGE_2);\n\/\/\tpixDestroy(&pixColOrg);\n\/\/\tpixInvert(pixcol,pixcol);\n\/\/\tPix *pixmask2 = pixOtsuThreshOnBackgroundNorm(pixcol, NULL, 20, 30, 20, 100, 200, 0, 0, 0.1, NULL);\n\/\/\n\/\/\tpixDestroy(&pixcol);\n\/\/\tPix* pixmask = pixExpandBinaryPower2(pixmask2,2);\n\/\/\tpixDestroy(&pixmask2);\n\/\/\tpixOr(pixb2,pixb2,pixmask);\n\/\/\tpixDestroy(&pixmask);\n\t\/*create image mask*\/\n\t\/* Get seed for halftone parts *\/\n\tPix* pixt1 = pixReduceRankBinaryCascade(pixb2, 4, 4, 3, 0);\n\tPix* pixt2 = pixOpenBrick(NULL, pixt1, 3, 3);\n\tint hasNoImages;\n\tpixZero(pixt2, &hasNoImages);\n\tif (!hasNoImages) {\n\t\tPix* pixhs = pixExpandBinaryPower2(pixt2, 8);\n\n\t\tpixDestroy(&pixt1);\n\t\tpixDestroy(&pixt2);\n\t\t\/* Get mask for connected regions *\/\n\t\tPix* pixm = pixCloseSafeBrick(NULL, pixb2, 4, 4);\n\t\t\/* Fill seed into mask to get halftone mask *\/\n\t\tPix* pixhm1 = pixSeedfillBinary(NULL, pixhs, pixm, 4);\n\t\tpixDestroy(&pixhs);\n\t\tpixDestroy(&pixm);\n\t\t\/*expand mask*\/\n\t\tpixCloseBrickDwa(pixhm1, pixhm1, 30, 30);\n\t\tPix* pixhm2 = pixFillClosedBorders(pixhm1, 4);\n\t\tpixDestroy(&pixhm1);\n\t\t*pixhm = pixExpandBinaryPower2(pixhm2, 2);\n\t\tpixDestroy(&pixhm2);\n\t} else {\n\t\t*pixhm = NULL;\n\t\tpixDestroy(&pixt1);\n\t\tpixDestroy(&pixt2);\n\t}\n\tpixDestroy(&pixb2);\n}\n\n\n<|endoftext|>"} {"text":"<commit_before>#include <chrono>\n#include \"fss-common.h\"\n#include \"fss-server.h\"\n#include \"fss-client.h\"\n\nint main()\n{\n \/\/ Set up variables\n uint64_t a = 3;\n uint64_t b = 2;\n Fss fClient, fServer;\n ServerKeyEq k0;\n ServerKeyEq k1;\n\n \/\/ Initialize client, use 10 bits in domain as example\n initializeClient(&fClient, 10, 2); \n \n \/\/ Equality FSS test\n generateTreeEq(&fClient, &k0, &k1, a, b);\n \n \/\/ Initialize server\n initializeServer(&fServer, &fClient);\n mpz_class ans0, ans1, fin;\n \n ans0 = evaluateEq(&fServer, &k0, a);\n ans1 = evaluateEq(&fServer, &k1, a);\n fin = ans0 - ans1;\n cout << \"FSS Eq Match (should be non-zero): \" << fin << endl;\n \n ans0 = evaluateEq(&fServer, &k0, (a-1));\n ans1 = evaluateEq(&fServer, &k1, (a-1));\n fin = ans0 - ans1;\n cout << \"FSS Eq No Match (should be 0): \" << fin << endl;\n\n \/\/ Less than FSS test\n ServerKeyLt lt_k0;\n ServerKeyLt lt_k1;\n \n initializeClient(&fClient, 10, 2);\n generateTreeLt(&fClient, <_k0, <_k1, a, b);\n\n initializeServer(&fServer, &fClient);\n uint64_t lt_ans0, lt_ans1, lt_fin;\n\n lt_ans0 = evaluateLt(&fServer, <_k0, (a-1));\n lt_ans1 = evaluateLt(&fServer, <_k1, (a-1));\n lt_fin = lt_ans0 - lt_ans1;\n cout << \"FSS Lt Match (should be non-zero): \" << lt_fin << endl;\n\n lt_ans0 = evaluateLt(&fServer, <_k0, a);\n lt_ans1 = evaluateLt(&fServer, <_k1, a);\n lt_fin = lt_ans0 - lt_ans1;\n cout << \"FSS Lt No Match (should be 0): \" << lt_fin << endl;\n\n \/\/ Equality FSS test for multi-parties\n MPKey mp_keys[3];\n initializeClient(&fClient, 10, 3);\n generateTreeEqMParty(&fClient, a, b, mp_keys);\n\n initializeServer(&fServer, &fClient);\n uint32_t mp_ans0 = evaluateEqMParty(&fServer, &mp_keys[0], a);\n uint32_t mp_ans1 = evaluateEqMParty(&fServer, &mp_keys[1], a);\n uint32_t mp_ans2 = evaluateEqMParty(&fServer, &mp_keys[2], a);\n uint32_t xor_mp = mp_ans0 ^ mp_ans1 ^ mp_ans2;\n cout << \"FSS Eq Multi-Party Match (should be non-zero): \" << xor_mp << endl;\n\n mp_ans0 = evaluateEqMParty(&fServer, &mp_keys[0], (a+1));\n mp_ans1 = evaluateEqMParty(&fServer, &mp_keys[1], (a+1));\n mp_ans2 = evaluateEqMParty(&fServer, &mp_keys[2], (a+1));\n xor_mp = mp_ans0 ^ mp_ans1 ^ mp_ans2;\n cout << \"FSS Eq Multi-Party No Match (should be 0): \" << xor_mp << endl;\n\n size_t rounds = 100000;\n auto t_begin = std::chrono::high_resolution_clock::now();\n for(size_t i=0; i<rounds; i++) {\n volatile auto x = evaluateEq(&fServer, &k0, i);\n }\n for(size_t i=0; i<rounds; i++) {\n volatile auto x = evaluateLt(&fServer, <_k0, i);\n }\n auto t_end = std::chrono::high_resolution_clock::now();\n std::cout << \"Benchmark result: \" <<\n std::chrono::duration<double, std::milli>(t_end - t_begin).count()\n << \" ms\" << endl;\n return 1;\n}\n<commit_msg>Add benchmark for muli-party evaluation.<commit_after>#include <chrono>\n#include \"fss-common.h\"\n#include \"fss-server.h\"\n#include \"fss-client.h\"\n\nint main()\n{\n \/\/ Set up variables\n uint64_t a = 3;\n uint64_t b = 2;\n Fss fClient, fServer;\n ServerKeyEq k0;\n ServerKeyEq k1;\n\n \/\/ Initialize client, use 10 bits in domain as example\n initializeClient(&fClient, 10, 2); \n \n \/\/ Equality FSS test\n generateTreeEq(&fClient, &k0, &k1, a, b);\n \n \/\/ Initialize server\n initializeServer(&fServer, &fClient);\n mpz_class ans0, ans1, fin;\n \n ans0 = evaluateEq(&fServer, &k0, a);\n ans1 = evaluateEq(&fServer, &k1, a);\n fin = ans0 - ans1;\n cout << \"FSS Eq Match (should be non-zero): \" << fin << endl;\n \n ans0 = evaluateEq(&fServer, &k0, (a-1));\n ans1 = evaluateEq(&fServer, &k1, (a-1));\n fin = ans0 - ans1;\n cout << \"FSS Eq No Match (should be 0): \" << fin << endl;\n\n \/\/ Less than FSS test\n ServerKeyLt lt_k0;\n ServerKeyLt lt_k1;\n \n initializeClient(&fClient, 10, 2);\n generateTreeLt(&fClient, <_k0, <_k1, a, b);\n\n initializeServer(&fServer, &fClient);\n uint64_t lt_ans0, lt_ans1, lt_fin;\n\n lt_ans0 = evaluateLt(&fServer, <_k0, (a-1));\n lt_ans1 = evaluateLt(&fServer, <_k1, (a-1));\n lt_fin = lt_ans0 - lt_ans1;\n cout << \"FSS Lt Match (should be non-zero): \" << lt_fin << endl;\n\n lt_ans0 = evaluateLt(&fServer, <_k0, a);\n lt_ans1 = evaluateLt(&fServer, <_k1, a);\n lt_fin = lt_ans0 - lt_ans1;\n cout << \"FSS Lt No Match (should be 0): \" << lt_fin << endl;\n\n \/\/ Equality FSS test for multi-parties\n MPKey mp_keys[3];\n initializeClient(&fClient, 10, 3);\n generateTreeEqMParty(&fClient, a, b, mp_keys);\n\n initializeServer(&fServer, &fClient);\n uint32_t mp_ans0 = evaluateEqMParty(&fServer, &mp_keys[0], a);\n uint32_t mp_ans1 = evaluateEqMParty(&fServer, &mp_keys[1], a);\n uint32_t mp_ans2 = evaluateEqMParty(&fServer, &mp_keys[2], a);\n uint32_t xor_mp = mp_ans0 ^ mp_ans1 ^ mp_ans2;\n cout << \"FSS Eq Multi-Party Match (should be non-zero): \" << xor_mp << endl;\n\n mp_ans0 = evaluateEqMParty(&fServer, &mp_keys[0], (a+1));\n mp_ans1 = evaluateEqMParty(&fServer, &mp_keys[1], (a+1));\n mp_ans2 = evaluateEqMParty(&fServer, &mp_keys[2], (a+1));\n xor_mp = mp_ans0 ^ mp_ans1 ^ mp_ans2;\n cout << \"FSS Eq Multi-Party No Match (should be 0): \" << xor_mp << endl;\n\n size_t rounds = 100000;\n auto t_begin = std::chrono::high_resolution_clock::now();\n for(size_t i=0; i<rounds; i++) {\n volatile auto x = evaluateEq(&fServer, &k0, i);\n }\n for(size_t i=0; i<rounds; i++) {\n volatile auto x = evaluateLt(&fServer, <_k0, i);\n }\n for(size_t i=0; i<rounds; i++) {\n volatile auto x = evaluateEqMParty(&fServer, &mp_keys[1], a);\n }\n auto t_end = std::chrono::high_resolution_clock::now();\n std::cout << \"Benchmark result: \" <<\n std::chrono::duration<double, std::milli>(t_end - t_begin).count()\n << \" ms\" << endl;\n return 1;\n}\n<|endoftext|>"} {"text":"<commit_before>\/******************************************************************************\n * This file is part of the Gluon Development Platform\n * Copyright (c) 2010-2011 Arjen Hiemstra <ahiemstra@heimr.nl>\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n *\/\n\n#include \"mainwindow.h\"\n\n#include <unistd.h>\n\n#include <QtGui\/QSplashScreen>\n\n#include <KDE\/KApplication>\n#include <KDE\/KAboutData>\n#include <KDE\/KCmdLineArgs>\n#include <KDE\/KStandardDirs>\n\n#include <core\/gluon_global.h>\n\n#include \"aboutdata.h\"\n\nint main( int argc, char** argv )\n{\n KAboutData aboutData = GluonCreator::aboutData();\n\n KCmdLineArgs::init( argc, argv, &aboutData );\n KCmdLineOptions options;\n options.add( \"+project\", ki18n( \"Project to open\" ) );\n KCmdLineArgs::addCmdLineOptions( options );\n\n KApplication app;\n KCmdLineArgs* args = KCmdLineArgs::parsedArgs();\n\n \/\/Create and show a splashscreen\n QPixmap splashImage( KGlobal::dirs()->locate( \"appdata\", \"gluon-creator-splash.png\" ) );\n QSplashScreen splash( splashImage );\n splash.show();\n app.processEvents();\n\n \/\/Create the main window\n GluonCreator::MainWindow* window;\n if( args->count() )\n {\n window = new GluonCreator::MainWindow( args->arg( 0 ) );\n }\n else\n {\n window = new GluonCreator::MainWindow();\n }\n\n \/\/Dirty hack to make the splashscreen at least visible.\n sleep( 1 );\n\n window->show();\n splash.finish( window );\n\n app.exec();\n}\n<commit_msg>Creator: Cleanup main a bit more.<commit_after>\/******************************************************************************\n * This file is part of the Gluon Development Platform\n * Copyright (c) 2010-2011 Arjen Hiemstra <ahiemstra@heimr.nl>\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n *\/\n\n#include \"mainwindow.h\"\n\n#include <unistd.h>\n\n#include <KDE\/KSplashScreen>\n#include <KDE\/KApplication>\n#include <KDE\/KAboutData>\n#include <KDE\/KCmdLineArgs>\n#include <KDE\/KStandardDirs>\n\n#include <core\/gluon_global.h>\n\n#include \"aboutdata.h\"\n\nint main( int argc, char** argv )\n{\n KAboutData aboutData = GluonCreator::aboutData();\n\n KCmdLineArgs::init( argc, argv, &aboutData );\n KCmdLineOptions options;\n options.add( \"+project\", ki18n( \"Project to open\" ) );\n KCmdLineArgs::addCmdLineOptions( options );\n\n KApplication app;\n KCmdLineArgs* args = KCmdLineArgs::parsedArgs();\n\n \/\/Create and show a splashscreen\n KSplashScreen splash( QPixmap( KGlobal::dirs()->locate( \"appdata\", \"gluon-creator-splash.png\" ) ) );\n splash.show();\n app.processEvents();\n\n \/\/Create the main window\n GluonCreator::MainWindow* window = new GluonCreator::MainWindow( args->count() > 0 ? args->arg( 0 ) : QString() );\n\n \/\/Dirty hack to make the splashscreen at least visible.\n sleep( 1 );\n\n window->show();\n splash.finish( window );\n\n app.exec();\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n* This source file is part of ArkGameFrame\n* For the latest info, see https:\/\/github.com\/ArkGame\n*\n* Copyright (c) 2013-2018 ArkGame authors.\n*\n* Licensed under the Apache License, Version 2.0 (the \"License\");\n* you may not use this file except in compliance with the License.\n* You may obtain a copy of the License at\n*\n* http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n*\n* Unless required by applicable law or agreed to in writing, software\n* distributed under the License is distributed on an \"AS IS\" BASIS,\n* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n* See the License for the specific language governing permissions and\n* limitations under the License.\n*\n*\/\n\n#include \"AFCLogModule.h\"\n#include \"SDK\/Interface\/AFIPluginManager.h\"\n#include \"spdlog\/contrib\/sinks\/date_and_hour_file_sink.h\"\n\nAFCLogModule::AFCLogModule(AFIPluginManager* p)\n{\n pPluginManager = p;\n\n \/\/Create spdlog\n try\n {\n CreateLogger();\n }\n catch (std::system_error& error)\n {\n CONSOLE_LOG_NO_FILE << \"Create logger failed, error = \" << error.what() << std::endl;\n ARK_ASSERT_NO_EFFECT(0);\n }\n}\n\nbool AFCLogModule::Shut()\n{\n spdlog::drop_all();\n return true;\n}\n\nconst std::shared_ptr<spdlog::async_logger>& AFCLogModule::GetLogger()\n{\n return mxLogger;\n}\n\nvoid AFCLogModule::CreateLogger()\n{\n std::vector<spdlog::sink_ptr> sinks_vec;\n std::string log_name;\n#if ARK_PLATFORM == PLATFORM_WIN\n log_name = ARK_FORMAT(\"..\\\\log\\\\{}.log\", pPluginManager->AppName());\n#else\n log_name = ARK_FORMAT(\"..\/log\/{}.log\", pPluginManager->AppName());\n#endif\n\n auto date_and_hour_sink = std::make_shared<spdlog::sinks::date_and_hour_file_sink_mt>(log_name);\n#if ARK_RUN_MODE == ARK_RUN_MODE_DEBUG\n#if ARK_PLATFORM == PLATFORM_WIN\n auto color_sink = std::make_shared<spdlog::sinks::wincolor_stdout_sink_mt>();\n#else\n auto color_sink = std::make_shared<spdlog::sinks::ansicolor_stdout_sink_mt>();\n#endif\n\n sinks_vec.push_back(color_sink);\n#endif\n sinks_vec.push_back(date_and_hour_sink);\n\n mxLogger = std::make_shared<spdlog::async_logger>(pPluginManager->AppName(), std::begin(sinks_vec), std::end(sinks_vec), 8 * 1024, spdlog::async_overflow_policy::block_retry, nullptr, std::chrono::seconds(5));\n\n#if ARK_RUN_MODE == ARK_RUN_MODE_DEBUG\n mxLogger->set_level(spdlog::level::level_enum::trace);\n mxLogger->set_pattern(\"%^[%Y%m%d %H:%M:%S.%e][%l]%v%$\");\n#else\n mxLogger->set_pattern(\"[%Y%m%d %H:%M:%S.%e][%l]%v\");\n#endif\n\n spdlog::register_logger(mxLogger);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nAFCDynamicLogModule::AFCDynamicLogModule(AFIPluginManager* p)\n{\n pPluginManager = p;\n}\n\nbool AFCDynamicLogModule::Shut()\n{\n spdlog::drop_all();\n return true;\n}\n\nconst std::shared_ptr<spdlog::async_logger>& AFCDynamicLogModule::GetLogger(const int id, const char* name)\n{\n auto iter = _dynamic_loggers.find(std::make_pair(id, name));\n\n if (iter != _dynamic_loggers.end())\n {\n return iter->second;\n }\n else\n {\n \/\/Create spdlog\n try\n {\n CreateLogger(id, name);\n }\n catch (std::system_error& error)\n {\n CONSOLE_LOG_NO_FILE << \"Create logger failed, error = \" << error.what() << std::endl;\n ARK_ASSERT_NO_EFFECT(0);\n }\n\n \/\/find twice\n iter = _dynamic_loggers.find(std::make_pair(id, name));\n\n if (iter != _dynamic_loggers.end())\n {\n return iter->second;\n }\n else\n {\n return _null_logger;\n }\n }\n}\n\nvoid AFCDynamicLogModule::CreateLogger(const int id, const char* name)\n{\n std::vector<spdlog::sink_ptr> sinks_vec;\n std::string log_name;\n#if ARK_PLATFORM == PLATFORM_WIN\n log_name = fmt::format(\"..\\\\log\\\\{}\\\\{}.log\", id, name);\n#else\n log_name = fmt::format(\"..\/log\/{}\/{}.log\", id, name);\n#endif\n\n auto date_and_hour_sink = std::make_shared<spdlog::sinks::date_and_hour_file_sink_mt>(log_name);\n#if ARK_RUN_MODE == ARK_RUN_MODE_DEBUG\n#if ARK_PLATFORM == PLATFORM_WIN\n auto color_sink = std::make_shared<spdlog::sinks::wincolor_stdout_sink_mt>();\n#else\n auto color_sink = std::make_shared<spdlog::sinks::ansicolor_stdout_sink_mt>();\n#endif\n\n sinks_vec.push_back(color_sink);\n#endif\n sinks_vec.push_back(date_and_hour_sink);\n\n auto dynamic_logger = std::make_shared<spdlog::async_logger>(name, std::begin(sinks_vec), std::end(sinks_vec), 8 * 1024, spdlog::async_overflow_policy::block_retry, nullptr, std::chrono::seconds(5));\n\n#if ARK_RUN_MODE == ARK_RUN_MODE_DEBUG\n dynamic_logger->set_level(spdlog::level::level_enum::trace);\n dynamic_logger->set_pattern(\"%^[%Y%m%d %H:%M:%S.%e][%l]%v%$\");\n#else\n dynamic_logger->set_pattern(\"[%Y%m%d %H:%M:%S.%e][%l]%v\");\n#endif\n\n spdlog::register_logger(dynamic_logger);\n _dynamic_loggers.insert(std::make_pair(std::make_pair(id, name), dynamic_logger));\n}<commit_msg>set log flush immediately when log err+ level<commit_after>\/*\n* This source file is part of ArkGameFrame\n* For the latest info, see https:\/\/github.com\/ArkGame\n*\n* Copyright (c) 2013-2018 ArkGame authors.\n*\n* Licensed under the Apache License, Version 2.0 (the \"License\");\n* you may not use this file except in compliance with the License.\n* You may obtain a copy of the License at\n*\n* http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n*\n* Unless required by applicable law or agreed to in writing, software\n* distributed under the License is distributed on an \"AS IS\" BASIS,\n* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n* See the License for the specific language governing permissions and\n* limitations under the License.\n*\n*\/\n\n#include \"AFCLogModule.h\"\n#include \"SDK\/Interface\/AFIPluginManager.h\"\n#include \"spdlog\/contrib\/sinks\/date_and_hour_file_sink.h\"\n\nAFCLogModule::AFCLogModule(AFIPluginManager* p)\n{\n pPluginManager = p;\n\n \/\/Create spdlog\n try\n {\n CreateLogger();\n }\n catch (std::system_error& error)\n {\n CONSOLE_LOG_NO_FILE << \"Create logger failed, error = \" << error.what() << std::endl;\n ARK_ASSERT_NO_EFFECT(0);\n }\n}\n\nbool AFCLogModule::Shut()\n{\n spdlog::drop_all();\n return true;\n}\n\nconst std::shared_ptr<spdlog::async_logger>& AFCLogModule::GetLogger()\n{\n return mxLogger;\n}\n\nvoid AFCLogModule::CreateLogger()\n{\n std::vector<spdlog::sink_ptr> sinks_vec;\n std::string log_name;\n#if ARK_PLATFORM == PLATFORM_WIN\n log_name = ARK_FORMAT(\"..\\\\log\\\\{}.log\", pPluginManager->AppName());\n#else\n log_name = ARK_FORMAT(\"..\/log\/{}.log\", pPluginManager->AppName());\n#endif\n\n auto date_and_hour_sink = std::make_shared<spdlog::sinks::date_and_hour_file_sink_mt>(log_name);\n#if ARK_RUN_MODE == ARK_RUN_MODE_DEBUG\n#if ARK_PLATFORM == PLATFORM_WIN\n auto color_sink = std::make_shared<spdlog::sinks::wincolor_stdout_sink_mt>();\n#else\n auto color_sink = std::make_shared<spdlog::sinks::ansicolor_stdout_sink_mt>();\n#endif\n\n sinks_vec.push_back(color_sink);\n#endif\n sinks_vec.push_back(date_and_hour_sink);\n\n mxLogger = std::make_shared<spdlog::async_logger>(pPluginManager->AppName(), std::begin(sinks_vec), std::end(sinks_vec), 1024);\n\n#if ARK_RUN_MODE == ARK_RUN_MODE_DEBUG\n mxLogger->set_level(spdlog::level::level_enum::trace);\n mxLogger->set_pattern(\"%^[%Y%m%d %H:%M:%S.%e][%l]%v%$\");\n#else\n mxLogger->set_pattern(\"[%Y%m%d %H:%M:%S.%e][%l]%v\");\n#endif\n\n mxLogger->flush_on(spdlog::level::err);\n\n spdlog::register_logger(mxLogger);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nAFCDynamicLogModule::AFCDynamicLogModule(AFIPluginManager* p)\n{\n pPluginManager = p;\n}\n\nbool AFCDynamicLogModule::Shut()\n{\n spdlog::drop_all();\n return true;\n}\n\nconst std::shared_ptr<spdlog::async_logger>& AFCDynamicLogModule::GetLogger(const int id, const char* name)\n{\n auto iter = _dynamic_loggers.find(std::make_pair(id, name));\n\n if (iter != _dynamic_loggers.end())\n {\n return iter->second;\n }\n else\n {\n \/\/Create spdlog\n try\n {\n CreateLogger(id, name);\n }\n catch (std::system_error& error)\n {\n CONSOLE_LOG_NO_FILE << \"Create logger failed, error = \" << error.what() << std::endl;\n ARK_ASSERT_NO_EFFECT(0);\n }\n\n \/\/find twice\n iter = _dynamic_loggers.find(std::make_pair(id, name));\n\n if (iter != _dynamic_loggers.end())\n {\n return iter->second;\n }\n else\n {\n return _null_logger;\n }\n }\n}\n\nvoid AFCDynamicLogModule::CreateLogger(const int id, const char* name)\n{\n std::vector<spdlog::sink_ptr> sinks_vec;\n std::string log_name;\n#if ARK_PLATFORM == PLATFORM_WIN\n log_name = fmt::format(\"..\\\\log\\\\{}\\\\{}.log\", id, name);\n#else\n log_name = fmt::format(\"..\/log\/{}\/{}.log\", id, name);\n#endif\n\n auto date_and_hour_sink = std::make_shared<spdlog::sinks::date_and_hour_file_sink_mt>(log_name);\n#if ARK_RUN_MODE == ARK_RUN_MODE_DEBUG\n#if ARK_PLATFORM == PLATFORM_WIN\n auto color_sink = std::make_shared<spdlog::sinks::wincolor_stdout_sink_mt>();\n#else\n auto color_sink = std::make_shared<spdlog::sinks::ansicolor_stdout_sink_mt>();\n#endif\n\n sinks_vec.push_back(color_sink);\n#endif\n sinks_vec.push_back(date_and_hour_sink);\n\n auto dynamic_logger = std::make_shared<spdlog::async_logger>(name, std::begin(sinks_vec), std::end(sinks_vec), 1024);\n\n#if ARK_RUN_MODE == ARK_RUN_MODE_DEBUG\n dynamic_logger->set_level(spdlog::level::level_enum::trace);\n dynamic_logger->set_pattern(\"%^[%Y%m%d %H:%M:%S.%e][%l]%v%$\");\n#else\n dynamic_logger->set_pattern(\"[%Y%m%d %H:%M:%S.%e][%l]%v\");\n#endif\n dynamic_logger->flush_on(spdlog::level::err);\n\n spdlog::register_logger(dynamic_logger);\n _dynamic_loggers.insert(std::make_pair(std::make_pair(id, name), dynamic_logger));\n}<|endoftext|>"} {"text":"<commit_before>\/**\n * 6.3.3 返回数组指针\n * @Author Bob\n * @Eamil 0haizhu0@gmail.com\n * @Date 2017\/8\/12\n *\/\nint main(){\n \/**\n * 函数返回值不能直接返回数组,但可以返回指向数组的指针\n *\/\n typedef int arrT[10]; \/\/ arrT是一个类型别名,它表示的类型是含有10个整数的数组\n using arrtT = int[10]; \/\/ arrT的等价声明,参见 2.5.1\n arrT* func(int i); \/\/ func返回一个指向含有10个整数的数组的指针\n\n \/**\n * 声明一个返回数组指针的函数:想要在声明函数时不使用类型别名,必须牢记定义的数组的维度\n * 格式:Type (*function(parameter_list))[dimension]\n *\/\n\n \/\/ 回顾\n int arr[10]; \/\/ arr是一个含有10个整数的数组\n int *p1[10]; \/\/ p1是一个含所有10个指针的数组\n int (*p2)[10] = &arr; \/\/ p2 是一个指针,它指向含有10个整数的数组\n\n \/\/ 定义范例\n \/\/ 分步骤解析:\n \/\/ func(int):调用函数时需要一个int型实参\n \/\/ (*func(int)):可以对函数的返回结果执行解引用操作\n \/\/ (*func(int))[10]:解引用func的调用将得到一个大小是10的数组\n \/\/ int (*func(int))[10]:数组中的元素是int类型\n int (*func(int i))[10];\n\n \/**\n * 使用尾置返回类型\n *\/\n\n return 0;\n}\n<commit_msg>6.3.3 返回数组指针<commit_after>\/**\n * 6.3.3 返回数组指针\n * @Author Bob\n * @Eamil 0haizhu0@gmail.com\n * @Date 2017\/8\/12\n *\/\nint main() {\n \/**\n * 函数返回值不能直接返回数组,但可以返回指向数组的指针\n *\/\n typedef int arrT[10]; \/\/ arrT是一个类型别名,它表示的类型是含有10个整数的数组\n using arrtT = int[10]; \/\/ arrT的等价声明,参见 2.5.1\n arrT *func(int i); \/\/ func返回一个指向含有10个整数的数组的指针\n\n \/**\n * 声明一个返回数组指针的函数:想要在声明函数时不使用类型别名,必须牢记定义的数组的维度\n * 格式:Type (*function(parameter_list))[dimension]\n *\/\n\n \/\/ 回顾\n int arr[10]; \/\/ arr是一个含有10个整数的数组\n int *p1[10]; \/\/ p1是一个含所有10个指针的数组\n int (*p2)[10] = &arr; \/\/ p2 是一个指针,它指向含有10个整数的数组\n\n \/\/ 定义范例\n \/\/ 分步骤解析:\n \/\/ func(int):调用函数时需要一个int型实参\n \/\/ (*func(int)):可以对函数的返回结果执行解引用操作\n \/\/ (*func(int))[10]:解引用func的调用将得到一个大小是10的数组\n \/\/ int (*func(int))[10]:数组中的元素是int类型\n int (*func(int i))[10];\n\n \/**\n * 使用尾置返回类型:在本应该出现返回类型的地方放置一个auto,然后使用 -> 跟上返回类型\n * 如下所示:函数返回一个指针,并且此指针指向了含有10个整数的数组。\n *\/\n auto func(int i) -> int (*)[10];\n\n \/**\n * 使用decltype:如果知道函数返回的指针将指向哪个数组,就可以使用decltype关键字声明返回类型\n * 范例:odd是含有5个整数的数组,也就是函数的返回值类型,但decltype不负责把数组转换为指针,\n * 所以decltype的结果是个数组,想要表示arrPtr返回指针需要在函数声明时加上 * 。\n *\/\n int odd[] = {1, 3, 5, 7, 9};\n int even[] = {0, 2, 4, 6, 8};\n decltype(odd) *arrPtr(int i) {\n return (i % 2) ? &odd : &even;\n }\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"OrbitTest.h\"\n\n#include <iostream>\n#include <thread>\n#include <chrono>\n#include <stdio.h>\n#include <sstream>\n\nstatic const uint32_t NUM_THREADS = 10;\nstatic const uint32_t NUM_RECURSIVE_CALLS = 10;\n\n#if __linux__\n#define NO_INLINE __attribute__ ((noinline))\n#else\n#define NO_INLINE __declspec(noinline)\n#endif\n\n\/\/-----------------------------------------------------------------------------\nuint64_t GetThreadID()\n{\n std::stringstream ss;\n ss << std::this_thread::get_id();\n uint64_t id = std::stoull(ss.str());\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid SetThreadName(const std::string& a_Name)\n{\n#if __linux__\n pthread_setname_np(pthread_self(), a_Name.c_str());\n#endif\n}\n\n\/\/-----------------------------------------------------------------------------\nOrbitTest::OrbitTest()\n{\n}\n\n\/\/-----------------------------------------------------------------------------\nOrbitTest::~OrbitTest()\n{\n m_ExitRequested = true;\n\n for (uint32_t i = 0; i < NUM_THREADS; ++i)\n {\n m_Threads[i]->join();\n }\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid OrbitTest::Start()\n{\n for (uint32_t i = 0; i < NUM_THREADS; ++i)\n {\n auto thread = std::make_shared<std::thread>(&OrbitTest::Loop, this);\n m_Threads.push_back(thread);\n }\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid OrbitTest::Loop()\n{\n SetThreadName(std::string(\"OrbitThread_\") + std::to_string(GetThreadID()));\n\n while (!m_ExitRequested)\n {\n TestFunc();\n }\n}\n\/\/-----------------------------------------------------------------------------\nvoid NO_INLINE OrbitTest::TestFunc(uint32_t a_Depth)\n{\n if (a_Depth == NUM_RECURSIVE_CALLS)\n return;\n\n TestFunc(a_Depth + 1);\n\n std::this_thread::sleep_for(std::chrono::milliseconds(100));\n}\n<commit_msg>Fix GetThreadID() in OrbitTest.cpp.<commit_after>#include \"OrbitTest.h\"\n\n#include <iostream>\n#include <thread>\n#include <chrono>\n#include <stdio.h>\n#include <sstream>\n\nstatic const uint32_t NUM_THREADS = 10;\nstatic const uint32_t NUM_RECURSIVE_CALLS = 10;\n\n#if __linux__\n#define NO_INLINE __attribute__ ((noinline))\n#else\n#define NO_INLINE __declspec(noinline)\n#endif\n\n\/\/-----------------------------------------------------------------------------\nuint64_t GetThreadID()\n{\n std::stringstream ss;\n ss << std::this_thread::get_id();\n return std::stoull(ss.str());\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid SetThreadName(const std::string& a_Name)\n{\n#if __linux__\n pthread_setname_np(pthread_self(), a_Name.c_str());\n#endif\n}\n\n\/\/-----------------------------------------------------------------------------\nOrbitTest::OrbitTest()\n{\n}\n\n\/\/-----------------------------------------------------------------------------\nOrbitTest::~OrbitTest()\n{\n m_ExitRequested = true;\n\n for (uint32_t i = 0; i < NUM_THREADS; ++i)\n {\n m_Threads[i]->join();\n }\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid OrbitTest::Start()\n{\n for (uint32_t i = 0; i < NUM_THREADS; ++i)\n {\n auto thread = std::make_shared<std::thread>(&OrbitTest::Loop, this);\n m_Threads.push_back(thread);\n }\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid OrbitTest::Loop()\n{\n SetThreadName(std::string(\"OrbitThread_\") + std::to_string(GetThreadID()));\n\n while (!m_ExitRequested)\n {\n TestFunc();\n }\n}\n\/\/-----------------------------------------------------------------------------\nvoid NO_INLINE OrbitTest::TestFunc(uint32_t a_Depth)\n{\n if (a_Depth == NUM_RECURSIVE_CALLS)\n return;\n\n TestFunc(a_Depth + 1);\n\n std::this_thread::sleep_for(std::chrono::milliseconds(100));\n}\n<|endoftext|>"} {"text":"<commit_before>\/*-------------------------------\nPASA LA CALCULADORA\nAutores: \nJaime Sevilla Molina\nVictor Gonzalez\nFecha\n2014\/11\nVersion: 2.0\n---------------------------------*\/\n\n\/\/BIBLIOTECAS\n#include <iostream>\n#include <cstdlib>\n#include <string>\n#include <ctime>\n#include <fstream>\n#include <iomanip>\n\nusing namespace std;\n\n\/\/TIPOS PROPIOS\ntypedef enum tJugador\n{\n\tNadie,\n\tJugador,\n\tAutomata\n};\n\ntypedef enum tDificultad\n{\n\t\tFacil,\n\t\tDificil,\n\t\tImposible\n};\n\n\/\/FUNCIONES\n\/\/FUNCIONES DE JUEGO\n\nstring saludar ();\nvoid despedirse (tJugador ganador, string nombre);\nint menu();\nbool acerca();\ntJugador pasaCalculadora();\ntJugador quienEmpieza();\n\ntDificultad seleccionar_dificultad();\nbool mismaFila(int ultimo, int nuevo);\nbool mismaColumna(int ultimo, int nuevo);\nbool digitoValido(int ultimo, int nuevo);\n\n\/\/FUNCIONES DE IA NIVEL 1\nint digitoAleatorio();\n\nint digitoAutomata(int ultimo);\n\n\/\/FUNCIONES DE JUGADOR\n\nint digitoPersona();\n\nint digitoPersona(int ultimo);\n\nchar mNumero(int ultimo, int n);\n\nvoid mostrarCalculadora(int ultimo);\n\n\n\/* Las funciones a continuacion se implementaran en un futuro\n\/\/FUNCIONES DE INFORME\n\/\/Actualiza el archivo informePC.txt con los tres argumentos. En caso de no encontrar\n\/\/el archivo, lo crea y devuelve false; en otro caso devuelve true.\nbool actInforme(int jugadas, int ganadas, int abandonos);\n*\/\n\n\/\/FUNCIONES DE DIFICULTAD AVANZADA\nint botDificil(int ultimo);\n\n\nint main()\n{\n\ttJugador ganador;\n\tint opcion;\n\t\n\tstring nombre = saludar();\t\n\t\/\/Bucle Menu\n\tdo\n\t{\n\t\topcion = menu();\n\t\tif(opcion == 1){\t\n\t\t\tganador = pasaCalculadora();\n\t\t\tdespedirse(ganador, nombre);\n\t\t}\n\t\telse if(opcion == 2) acerca();\n\t\n\t}\n\twhile(opcion != 0);\n\t\n\tcout << \"Hasta la proxima \" << nombre << \"(pulsa enter)\";\n\tcin;\n\n\treturn 0;\n}\n\t\n\/\/Saluda al jugador y le pregunta su nombre\nstring saludar()\n{\n\tstring nombre;\n\tcout << \"Bienvenido a Pasa la calculadora!\" << endl;\n\tcout << \"Como te llamas? \";\n\tcin >> nombre;\n\tcout << \"Hola \" << nombre << endl << endl;\n\treturn nombre;\n}\n\n\/\/Se despide del jugador, la despedida varia segun gane el jugador, el automata o ninguno de ellos (el jugador abandone)\nvoid despedirse(tJugador ganador, string nombre)\n{\n\tif (ganador == Nadie){\n\t\tcout << \"Abandonas, \" << nombre << \"? Ohhh...\" << endl << endl;\n\t}\n\telse if (ganador == Jugador){\n\t\tcout << \"Enhorabuena \" << nombre << \", has ganado!\" << endl << endl;\n\t}\n\telse \/*if (ganador == Automata)*\/{\n\t\tcout << \"Lo siento \" << nombre << \", he ganado\" << endl << endl;\n\t}\n}\n\n\/\/Proporciona al jugador la posibilidad de jugar, ver las instrucciones del juego o salir.\nint menu()\n{\n\tint seleccionar = -1; \/\/Error flag\n\tcout << \"1 - Jugar\" << endl;\n\tcout << \"2 - Acerca de\" << endl;\n\tcout << \"0 - Salir\" << endl;\n\t\n\tdo\n\t{\n\t\tcin.sync(); \/\/Por si quedan datos basura en el buffer\n\t\tcin >> seleccionar;\n\n\t\tif(cin.fail())\n\t\t{\n\t\t\tcout << \"Error! Introduce un digito\" << endl;\n\t\t\tcin.clear();\n\t\t}\n\n\t\telse if (seleccionar < 0 || seleccionar > 2)\n\t\t{\n\t\t\tcout << \"Error! Introduce un digito entre 0 y 2\" << endl;\n\t\t\tseleccionar = -1;\n\t\t}\n\t\t\n\t}\n\twhile (seleccionar == -1);\n\n\treturn seleccionar;\n}\n\n\/\/Muestra el archivo \"acerca.txt\" siempre que este no contenga errores\nbool acerca()\n{\n\n\tbool ok;\n\tifstream acerca;\n\tchar c;\n\n\tacerca.open(\"acerca.txt\");\n\t\n\tif(acerca.is_open())\n\t{\n\t\tacerca.get(c); \/\/Lee el primer caracter\n\n\t\twhile(!acerca.fail()) \/\/Mientras la lectura no falle\n\t\t{\n\t\t\tcout << c;\n\t\t\tacerca.get(c); \/\/Lee el siguiente caracter\n\t\t}\n\n\t\tok = true;\n\t\tacerca.close();\n\n\t}\n\telse\n\t{\n\t\tok = false;\n\t\tcout << \"Error, el archivo 'acerca.txt' no existe\" << endl;\n\t}\n\n\treturn ok;\n}\n\n\/\/Conduce el desarrollo del juego y devuelve el ganador. \n\/\/Si se abandona, devuelve Nadie.\ntJugador pasaCalculadora()\n{\n\t\/\/Variables\n\ttJugador turno; tDificultad dificultad;\n\tint total = 0, ultimoDigito = 0;\n\tconst int META=31;\n\t\t\/\/Inicializar partida\n\n\tdificultad = seleccionar_dificultad();\n\n\tsrand(time(NULL));\/\/Semilla\n\tturno = quienEmpieza();\n\n\t\/\/Bucle de juego\n\tdo\n\t{\n\t\t\/\/Turno jugador\n\t\tif (turno == Jugador)\n\t\t{\n\t\t\tultimoDigito = digitoPersona(ultimoDigito);\n\t\t\tturno = Automata;\n\t\t}\n\t\t\/\/Turno bot\n\t\telse \/*if (turno == Automata)*\/\n\t\t{\n\t\t\tultimoDigito = digitoAutomata(ultimoDigito);\n\t\t\tturno = Jugador;\n\t\t}\n\t\ttotal += ultimoDigito;\n\t\tcout << \"Total = \" << total << endl;\n\t}\n\twhile ((total < META) && (ultimoDigito != 0));\n\t\n\tif (ultimoDigito == 0) turno = Nadie; \n\t\/\/Si el jugador abandona, no gana nadie\n\n\treturn turno;\n}\n\n\/\/Decide aleatoriamente quien empieza la partida, si el automata o el jugador\ntJugador quienEmpieza()\n{\n\tif (rand() % 2)\n\t{\n\t\tcout << \"Tu empiezas\" << endl;\n\t\treturn Jugador;\n\t}\n\telse\n\t{\n\t\tcout << \"Empiezo yo\" << endl;\n\t\treturn Automata;\n\t}\n}\n\n\/\/Define que numeros se encuentran en la misma fila que el ultimo pulsado\nbool mismaFila(int ultimo, int nuevo)\n{\n\tint filaUltimo, filaNuevo;\n\tfilaUltimo = ((ultimo - 1)\/3);\n\tfilaNuevo = ((nuevo - 1)\/3);\n\treturn (filaUltimo) == (filaNuevo);\n}\n\n\/\/Define que numeros se encuentran en la misma columna que el ultimo\nbool mismaColumna(int ultimo, int nuevo)\n{\n\tint columnaUltimo, columnaNuevo;\n\tcolumnaUltimo = (ultimo % 3);\n\tcolumnaNuevo = (nuevo % 3);\n\treturn columnaUltimo == columnaNuevo;\n}\n\n\/\/Determina que digitos se pueden pulsar en funcion de las reglas del juego\nbool digitoValido(int ultimo, int nuevo) \/\/hay un bug\n{\n\tif (ultimo == 0) return true;\/\/Si es el primer turno, todos los numeros valen\n\n\treturn ((mismaFila(ultimo, nuevo))||(mismaColumna(ultimo, nuevo)))&&(ultimo!=nuevo);\n}\n\n\/\/Genera un digito aleatorio\nint digitoAleatorio()\n{\n\treturn (rand() % 9) + 1;\n}\n\n\/\/Devuelve un digito que cumpla las reglas del juego con respecto a ultimo.\nint digitoAutomata(int ultimo)\n{\n\tint digito;\n\n\tdo\n\t{\n\tdigito = digitoAleatorio();\n\t}\n\twhile (!digitoValido(ultimo, digito));\n\n\tcout << \"Elijo el numero \" << digito << endl;\n\n\treturn digito;\n}\n\n\/\/Pide un digito al jugador. Solo devolvera un valor valido (entre 0 y 9).\n\/\/Para un valor no valido, mostrara un error.\nint digitoPersona()\n{\n\tint digito = -1;\n\n\tdo\n\t{\n\t\tcin.sync(); \/\/Por si quedan datos basura en el buffer\n\t\tcin >> digito;\n\n\t\tif (cin.fail())\n\t\t{\n\t\t\tcout << \"Error! Introduce un digito\" << endl;\n\t\t\tcin.clear();\n\t\t}\n\n\t\telse if (digito < 0 || digito > 9) \n\t\t{\n\t\tcout << \"Error! Introduce un digito entre 0 y 9\" << endl;\n\t\tdigito = -1;\n\t\t}\n\t\t\n\t}\n\twhile (digito == -1);\n\n\treturn digito;\n}\n\n\/\/Pide un digito al jugador mostrando el teclado. Solo devolvera un valor \n\/\/que cumpla las reglas del juego o 0. Para un valor no valido, mostrara un error.\nint digitoPersona(int ultimo)\n{\n\tint digito = -1; \/\/-1 es mi error flag\n\t\n\tmostrarCalculadora(ultimo);\n\n\tdo\n\t{\n\t\tdigito = digitoPersona();\n\t\tif (!digitoValido(ultimo, digito))\n\t\t{\n\t\t\tcout << \"Error! El digito debe estar en la misma fila y columna que el ultimo\" << endl;\n\t\t\tdigito = -1;\n\t\t}\n\t}\n\twhile (digito == -1);\n\n\tcout << \"Has elegido el \" << digito << endl;\n\n\treturn digito;\n}\n\n\/\/Determina si el numero de la calculadora se muestra o no, en funcion de si es valido\nchar mNumero(int ultimo, int n)\n{\n\tif(digitoValido(ultimo, n))\n\t{\n\t\t\/\/system (\"color 02\");\n\t\treturn char (n+int('0'));\n\t\t\n\t}\n\telse\n\t{\n\t\t\/\/system (\"color 04\");\n\t\treturn ' ';\n\t}\n}\n\n\/\/Muestra los botones de la calculadora (solo los que se pueden pulsar en cada turno)\nvoid mostrarCalculadora(int ultimo)\n{\n\tfor (int i = 7; i<10; i++)\n\t{\n\t\tcout << setw(3) << mNumero(ultimo, i);\n\t}\n\tcout << endl;\n\tfor (int i = 4; i<7; i++)\n\t{\n\t\tcout << setw(3) << mNumero(ultimo, i);\n\t}\n\tcout << endl;\n\tfor (int i = 1; i<4; i++)\n\t{\n\t\tcout << setw(3) << mNumero(ultimo, i);\n\t}\n\tcout << endl;\n\t\/\/system (\"color 07\");\n}\n\ntDificultad seleccionar_dificultad(){\n\tcout << \"Elige dificultad:\" << endl;\n\tcout << \"1 - Facil\" << endl;\n\tcout << \"2 - Dificil\" << endl;\n\tcout << \"3 - Imposible\" << endl;\n\n\tif \n\n\nint botDificil(int total, int ultimo)\n{\n\tfor (int i=1, i<10, i++)\n\t{\n\t\tif digitoValido(ultimo, i)\n\t\t{\n\t\t\tif (total + i == 30) return i; \/\/Intenta ganar dejando la suma en 30\n\t\t\telse if ((total + i == 29) && (!digitoValido(i, 1))) return i; \n\t\t\t\/\/Si la suma queda en 29 y el adversario no puede coger el 1, ganamos\n\t\t\telse if ((total + i == 28) && (i==6 || i==9)) return i; \n\t\t\t\/\/Si la suma queda en 28 y el adv no puede coger el 1 o el 2, ganamos\n\t\t}\n\t}\n\treturn digitoAutomata(ultimo);\n}<commit_msg>Implementado digito_entre()<commit_after>\/*-------------------------------\nPASA LA CALCULADORA\nAutores: \nJaime Sevilla Molina\nVictor Gonzalez\nFecha\n2014\/11\nVersion: 2.0\n---------------------------------*\/\n\n\/\/BIBLIOTECAS\n#include <iostream>\n#include <cstdlib>\n#include <string>\n#include <ctime>\n#include <fstream>\n#include <iomanip>\n\nusing namespace std;\n\n\/\/TIPOS PROPIOS\ntypedef enum tJugador\n{\n\tNadie,\n\tJugador,\n\tAutomata\n};\n\ntypedef enum tDificultad\n{\n\t\tFacil,\n\t\tDificil,\n\t\tImposible\n};\n\n\/\/FUNCIONES\n\/\/FUNCIONES DE JUEGO\n\nstring saludar();\nvoid despedirse (tJugador ganador, string nombre);\nint menu();\nbool acerca();\ntJugador pasaCalculadora();\ntJugador quienEmpieza();\n\ntDificultad seleccionar_dificultad();\nbool mismaFila(int ultimo, int nuevo);\nbool mismaColumna(int ultimo, int nuevo);\nbool digitoValido(int ultimo, int nuevo);\n\n\/\/FUNCIONES DE IA NIVEL 1\nint digitoAleatorio();\n\nint digitoAutomata(int ultimo);\n\n\/\/FUNCIONES DE JUGADOR\n\nint digitoEntre(int a, int b);\n\nint digitoPersona(int ultimo);\n\nchar mNumero(int ultimo, int n);\n\nvoid mostrarCalculadora(int ultimo);\n\n\n\/* Las funciones a continuacion se implementaran en un futuro\n\/\/FUNCIONES DE INFORME\n\/\/Actualiza el archivo informePC.txt con los tres argumentos. En caso de no encontrar\n\/\/el archivo, lo crea y devuelve false; en otro caso devuelve true.\nbool actInforme(int jugadas, int ganadas, int abandonos);\n*\/\n\n\/\/FUNCIONES DE DIFICULTAD AVANZADA\nint botDificil(int ultimo);\n\n\nint main()\n{\n\ttJugador ganador;\n\tint opcion;\n\t\n\tstring nombre = saludar();\t\n\t\/\/Bucle Menu\n\tdo\n\t{\n\t\topcion = menu();\n\t\tif(opcion == 1){\t\n\t\t\tganador = pasaCalculadora();\n\t\t\tdespedirse(ganador, nombre);\n\t\t}\n\t\telse if(opcion == 2) acerca();\n\t\n\t}\n\twhile(opcion != 0);\n\t\n\tcout << \"Hasta la proxima \" << nombre << \"(pulsa enter)\";\n\tcin;\n\n\treturn 0;\n}\n\t\n\/\/Saluda al jugador y le pregunta su nombre\nstring saludar()\n{\n\tstring nombre;\n\tcout << \"Bienvenido a Pasa la calculadora!\" << endl;\n\tcout << \"Como te llamas? \";\n\tcin >> nombre;\n\tcout << \"Hola \" << nombre << endl << endl;\n\treturn nombre;\n}\n\n\/\/Se despide del jugador, la despedida varia segun gane el jugador, el automata o ninguno de ellos (el jugador abandone)\nvoid despedirse(tJugador ganador, string nombre)\n{\n\tif (ganador == Nadie){\n\t\tcout << \"Abandonas, \" << nombre << \"? Ohhh...\" << endl << endl;\n\t}\n\telse if (ganador == Jugador){\n\t\tcout << \"Enhorabuena \" << nombre << \", has ganado!\" << endl << endl;\n\t}\n\telse \/*if (ganador == Automata)*\/{\n\t\tcout << \"Lo siento \" << nombre << \", he ganado\" << endl << endl;\n\t}\n}\n\n\/\/Proporciona al jugador la posibilidad de jugar, ver las instrucciones del juego o salir.\nint menu()\n{\n\tint seleccionar = -1; \/\/Error flag\n\tcout << \"1 - Jugar\" << endl;\n\tcout << \"2 - Acerca de\" << endl;\n\tcout << \"0 - Salir\" << endl;\n\t\n\tseleccionar = digitoEntre(0,2);\n\n\treturn seleccionar;\n}\n\n\/\/Muestra el archivo \"acerca.txt\" siempre que este no contenga errores\nbool acerca()\n{\n\n\tbool ok;\n\tifstream acerca;\n\tchar c;\n\n\tacerca.open(\"acerca.txt\");\n\t\n\tif(acerca.is_open())\n\t{\n\t\tacerca.get(c); \/\/Lee el primer caracter\n\n\t\twhile(!acerca.fail()) \/\/Mientras la lectura no falle\n\t\t{\n\t\t\tcout << c;\n\t\t\tacerca.get(c); \/\/Lee el siguiente caracter\n\t\t}\n\n\t\tok = true;\n\t\tacerca.close();\n\n\t}\n\telse\n\t{\n\t\tok = false;\n\t\tcout << \"Error, el archivo 'acerca.txt' no existe\" << endl;\n\t}\n\n\treturn ok;\n}\n\n\/\/Conduce el desarrollo del juego y devuelve el ganador. \n\/\/Si se abandona, devuelve Nadie.\ntJugador pasaCalculadora()\n{\n\t\/\/Variables\n\ttJugador turno; tDificultad dificultad;\n\tint total = 0, ultimoDigito = 0;\n\tconst int META=31;\n\t\t\/\/Inicializar partida\n\n\tdificultad = seleccionar_dificultad();\n\n\tsrand(time(NULL));\/\/Semilla\n\tturno = quienEmpieza();\n\n\t\/\/Bucle de juego\n\tdo\n\t{\n\t\t\/\/Turno jugador\n\t\tif (turno == Jugador)\n\t\t{\n\t\t\tultimoDigito = digitoPersona(ultimoDigito);\n\t\t\tturno = Automata;\n\t\t}\n\t\t\/\/Turno bot\n\t\telse \/*if (turno == Automata)*\/\n\t\t{\n\t\t\tultimoDigito = digitoAutomata(ultimoDigito);\n\t\t\tturno = Jugador;\n\t\t}\n\t\ttotal += ultimoDigito;\n\t\tcout << \"Total = \" << total << endl;\n\t}\n\twhile ((total < META) && (ultimoDigito != 0));\n\t\n\tif (ultimoDigito == 0) turno = Nadie; \n\t\/\/Si el jugador abandona, no gana nadie\n\n\treturn turno;\n}\n\n\/\/Decide aleatoriamente quien empieza la partida, si el automata o el jugador\ntJugador quienEmpieza()\n{\n\tif (rand() % 2)\n\t{\n\t\tcout << \"Tu empiezas\" << endl;\n\t\treturn Jugador;\n\t}\n\telse\n\t{\n\t\tcout << \"Empiezo yo\" << endl;\n\t\treturn Automata;\n\t}\n}\n\n\/\/Define que numeros se encuentran en la misma fila que el ultimo pulsado\nbool mismaFila(int ultimo, int nuevo)\n{\n\tint filaUltimo, filaNuevo;\n\tfilaUltimo = ((ultimo - 1)\/3);\n\tfilaNuevo = ((nuevo - 1)\/3);\n\treturn (filaUltimo) == (filaNuevo);\n}\n\n\/\/Define que numeros se encuentran en la misma columna que el ultimo\nbool mismaColumna(int ultimo, int nuevo)\n{\n\tint columnaUltimo, columnaNuevo;\n\tcolumnaUltimo = (ultimo % 3);\n\tcolumnaNuevo = (nuevo % 3);\n\treturn columnaUltimo == columnaNuevo;\n}\n\n\/\/Determina que digitos se pueden pulsar en funcion de las reglas del juego\nbool digitoValido(int ultimo, int nuevo) \/\/hay un bug\n{\n\tif (ultimo == 0) return true;\/\/Si es el primer turno, todos los numeros valen\n\n\treturn ((mismaFila(ultimo, nuevo))||(mismaColumna(ultimo, nuevo)))&&(ultimo!=nuevo);\n}\n\n\/\/Genera un digito aleatorio\nint digitoAleatorio()\n{\n\treturn (rand() % 9) + 1;\n}\n\n\/\/Devuelve un digito que cumpla las reglas del juego con respecto a ultimo.\nint digitoAutomata(int ultimo)\n{\n\tint digito;\n\n\tdo\n\t{\n\tdigito = digitoAleatorio();\n\t}\n\twhile (!digitoValido(ultimo, digito));\n\n\tcout << \"Elijo el numero \" << digito << endl;\n\n\treturn digito;\n}\n\n\/\/Pide un digito al jugador. Solo devolvera un valor valido (entre 0 y 9).\n\/\/Para un valor no valido, mostrara un error.\nint digitoEntre(int a, int b)\n{\n\tint digito = -1;\n\n\tdo\n\t{\n\t\tcin.sync(); \/\/Por si quedan datos basura en el buffer\n\t\tcin >> digito;\n\n\t\tif (cin.fail())\n\t\t{\n\t\t\tcout << \"Error! Introduce un digito\" << endl;\n\t\t\tcin.clear();\n\t\t}\n\n\t\telse if (digito < a || digito > b)\n\t\t{\n\t\tcout << \"Error! Introduce un digito entre \" << a << \" y \" << b << endl;\n\t\tdigito = -1;\n\t\t}\n\t\t\n\t}\n\twhile (digito == -1);\n\n\treturn digito;\n}\n\n\/\/Pide un digito al jugador mostrando el teclado. Solo devolvera un valor \n\/\/que cumpla las reglas del juego o 0. Para un valor no valido, mostrara un error.\nint digitoPersona(int ultimo)\n{\n\tint digito = -1; \/\/-1 es mi error flag\n\t\n\tmostrarCalculadora(ultimo);\n\n\tdo\n\t{\n\t\tdigito = digitoEntre(0,9);\n\t\tif (!digitoValido(ultimo, digito))\n\t\t{\n\t\t\tcout << \"Error! El digito debe estar en la misma fila y columna que el ultimo\" << endl;\n\t\t\tdigito = -1;\n\t\t}\n\t}\n\twhile (digito == -1);\n\n\tcout << \"Has elegido el \" << digito << endl;\n\n\treturn digito;\n}\n\n\/\/Determina si el numero de la calculadora se muestra o no, en funcion de si es valido\nchar mNumero(int ultimo, int n)\n{\n\tif(digitoValido(ultimo, n))\n\t{\n\t\t\/\/system (\"color 02\");\n\t\treturn char (n+int('0'));\n\t\t\n\t}\n\telse\n\t{\n\t\t\/\/system (\"color 04\");\n\t\treturn ' ';\n\t}\n}\n\n\/\/Muestra los botones de la calculadora (solo los que se pueden pulsar en cada turno)\nvoid mostrarCalculadora(int ultimo)\n{\n\tfor (int i = 7; i<10; i++)\n\t{\n\t\tcout << setw(3) << mNumero(ultimo, i);\n\t}\n\tcout << endl;\n\tfor (int i = 4; i<7; i++)\n\t{\n\t\tcout << setw(3) << mNumero(ultimo, i);\n\t}\n\tcout << endl;\n\tfor (int i = 1; i<4; i++)\n\t{\n\t\tcout << setw(3) << mNumero(ultimo, i);\n\t}\n\tcout << endl;\n\t\/\/system (\"color 07\");\n}\n\ntDificultad seleccionar_dificultad()\n{\n\tcout << \"Elige dificultad:\" << endl;\n\tcout << \"1 - Facil\" << endl;\n\tcout << \"2 - Dificil\" << endl;\n\tcout << \"3 - Imposible\" << endl;\n\n\tint opcion = digitoEntre(1,3);\n\n\tif (opcion == 1) return Facil;\n\telse if (opcion == 2) return Dificil;\n\telse \/*if (opcion == 3)*\/ return Imposible;\n}\n\nint botDificil(int total, int ultimo)\n{\n\tfor (int i=1; i<10; i++)\n\t{\n\t\tif (digitoValido(ultimo, i))\n\t\t{\n\t\t\tif (total + i == 30) return i; \/\/Intenta ganar dejando la suma en 30\n\t\t\telse if ((total + i == 29) && (!digitoValido(i, 1))) return i; \n\t\t\t\/\/Si la suma queda en 29 y el adversario no puede coger el 1, ganamos\n\t\t\telse if ((total + i == 28) && (i==6 || i==9)) return i; \n\t\t\t\/\/Si la suma queda en 28 y el adv no puede coger el 1 o el 2, ganamos\n\t\t}\n\t}\n\treturn digitoAutomata(ultimo);\n}<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ Sequencer.cpp\n\/\/ WISTSample\n\/\/\n\/\/ Created by Nobuhisa Okamura on 11\/05\/19.\n\/\/ Copyright 2011 KORG INC. All rights reserved.\n\/\/\n\n#include <vector>\n#include <mutex>\n#include <algorithm>\n\n#include <mach\/mach_time.h>\n\n#include \"Sequencer.h\"\n#include \"AudioIO.h\"\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ Sequencer::Sequencer\n\/\/ ---------------------------------------------------------------------------\nSequencer::Sequencer(float samplingRate, int numberOfTracks, int numberOfSteps, int stepsPerBeat) :\nsamplingRate_(samplingRate),\nnumberOfTracks_(numberOfTracks),\nnumberOfSteps_(numberOfSteps),\nstepsPerBeat_(stepsPerBeat),\nisRunning_(false),\ncurrentStep_(0),\nstepFrameLength_(0),\ncurrentFrame_(0),\ntrigger_(false),\nseq_(),\ncommands_(),\nlisteners_(),\ncommandsMutex_()\n{\n \/\/ 各ステップの再生有無をstd::vector<bool>で記憶するトラックを4本作成\n SetupTracks();\n}\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ Sequencer::~Sequencer\n\/\/ ---------------------------------------------------------------------------\nSequencer::~Sequencer(void)\n{\n}\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ Sequencer::SetupTracks\n\/\/ ---------------------------------------------------------------------------\nvoid\nSequencer::SetupTracks()\n{\n seq_.clear();\n for (int trackNo = 0; trackNo < numberOfTracks_; ++trackNo)\n {\n std::vector<bool> partSeq(numberOfSteps_, false);\n seq_.push_back(partSeq);\n }\n}\n\nenum\n{\n kSeqCommand_Start = 0,\n kSeqCommand_Stop,\n kSeqCommand_UpdateTempo,\n kSeqCommand_UpdateNumSteps,\n};\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ Sequencer::ProcessCommand\n\/\/ ---------------------------------------------------------------------------\ninline void\nSequencer::ProcessCommand(SeqCommandEvent& event)\n{\n switch (event.command)\n {\n case kSeqCommand_Start:\n if (!isRunning_)\n {\n const float tempo = event.floatValue;\n currentStep_ = 0;\n currentFrame_ = 0;\n stepFrameLength_ = samplingRate_ * 60.0f \/ tempo \/ stepsPerBeat_;\n trigger_ = true;\n isRunning_ = true;\n }\n break;\n case kSeqCommand_Stop:\n if (isRunning_)\n {\n isRunning_ = false;\n }\n break;\n case kSeqCommand_UpdateTempo:\n if (1)\n {\n const float tempo = event.floatValue;\n stepFrameLength_ = samplingRate_ * 60.0f \/ tempo \/ stepsPerBeat_;\n }\n break;\n case kSeqCommand_UpdateNumSteps:\n if (1) {\n const int numberOfSteps = static_cast<int>(event.floatValue);\n if (numberOfSteps != numberOfSteps_) {\n numberOfSteps_ = numberOfSteps;\n SetupTracks();\n }\n }\n break;\n default:\n break;\n }\n}\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ Sequencer::ProcessCommands\n\/\/ ---------------------------------------------------------------------------\ninline int\nSequencer::ProcessCommands(AudioIO* io, int offset, int length)\n{\n if (!commands_.empty())\n {\n const uint64_t hostTime = (io != NULL) ? io->GetHostTime() : 0;\n const uint64_t latency = (io != NULL) ? io->GetLatency() : 0;\n mach_timebase_info_data_t timeInfo;\n ::mach_timebase_info(&timeInfo);\n {\n std::lock_guard<std::mutex> lock(commandsMutex_);\n std::sort(commands_.begin(), commands_.end(), Sequencer::SortEventFunctor);\n for (auto ite = commands_.begin(); ite != commands_.end();)\n {\n bool doProcess = false;\n if (ite->hostTime == 0) \/\/ now\n {\n doProcess = true;\n }\n else if (io != NULL)\n {\n const int64_t delta = ite->hostTime - hostTime;\n const int64_t deltaNanosec = delta * timeInfo.numer \/ timeInfo.denom + latency;\n const int32_t sampleOffset = static_cast<int32_t>(static_cast<double>(deltaNanosec) * samplingRate_ \/ 1000000000);\n if (sampleOffset < offset + length)\n {\n const int eventFrame = sampleOffset - offset;\n if (eventFrame > 0)\n {\n return eventFrame;\n }\n doProcess = true;\n }\n }\n if (doProcess)\n {\n this->ProcessCommand(*ite);\n ite = commands_.erase(ite);\n }\n else\n {\n ++ite;\n }\n }\n }\n }\n return length;\n}\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ Sequencer::ProcessTrigger\n\/\/ ---------------------------------------------------------------------------\ninline void\nSequencer::ProcessTrigger(int offset, const std::vector<int> &trackIndexes)\n{\n for (auto listener : listeners_)\n {\n listener->NoteOnViaSequencer(offset, trackIndexes, currentStep_);\n }\n}\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ Sequencer::ProcessTrigger\n\/\/ ---------------------------------------------------------------------------\ninline void\nSequencer::ProcessTrigger(int offset)\n{\n if (trigger_ && (currentFrame_ >= 0))\n {\n if ((currentStep_ >= 0) && (currentStep_ < numberOfSteps_))\n {\n \/\/ ここでONトラック(int)だけを集めてProcessTriggerに渡す\n std::vector<int> triggeredTracks;\n const int numOfTrack = static_cast<const int>(seq_.size());\n for (int trackNo = 0; trackNo < numOfTrack; ++trackNo)\n {\n const auto& partSeq = seq_[trackNo];\n if (partSeq[currentStep_])\n {\n triggeredTracks.push_back(trackNo);\n }\n }\n this->ProcessTrigger(offset + currentFrame_, triggeredTracks);\n }\n trigger_ = false;\n }\n}\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ Sequencer::ProcessSequence\n\/\/ ---------------------------------------------------------------------------\ninline void\nSequencer::ProcessSequence(int offset, int length)\n{\n int rest = length;\n int startFrame = offset;\n while (rest > 0)\n {\n const int processedLen = std::min<int>(rest, std::max<int>(stepFrameLength_ - currentFrame_, 1));\n this->ProcessTrigger(startFrame);\n currentFrame_ += processedLen;\n rest -= processedLen;\n startFrame += processedLen;\n if (currentFrame_ >= stepFrameLength_)\n {\n currentFrame_ -= stepFrameLength_;\n ++currentStep_;\n if (currentStep_ > numberOfSteps_ - 1)\n {\n currentStep_ = 0;\n }\n trigger_ = true;\n }\n }\n}\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ Sequencer::Process\n\/\/ ---------------------------------------------------------------------------\nint\nSequencer::Process(AudioIO* io, int offset, int length)\n{\n const int result = this->ProcessCommands(io, offset, length);\n if (isRunning_ && (result > 0))\n {\n this->ProcessSequence(offset, result);\n }\n return result;\n}\n\n#pragma mark -\n\/\/ ---------------------------------------------------------------------------\n\/\/ Sequencer::AddListener\n\/\/ ---------------------------------------------------------------------------\nvoid\nSequencer::AddListener(SequencerListener* listener)\n{\n listeners_.push_back(listener);\n}\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ Sequencer::RemoveListener\n\/\/ ---------------------------------------------------------------------------\nvoid\nSequencer::RemoveListener(SequencerListener* listener)\n{\n listeners_.erase(std::remove(std::begin(listeners_),\n std::end(listeners_),\n listener), std::end(listeners_));\n}\n\n#pragma mark -\n\/\/ ---------------------------------------------------------------------------\n\/\/ Sequencer::AddCommand\n\/\/ ---------------------------------------------------------------------------\nvoid\nSequencer::AddCommand(const uint64_t hostTime, const int cmd, const float param0)\n{\n std::lock_guard<std::mutex> lock(commandsMutex_);\n const SeqCommandEvent event = { hostTime, cmd, param0 };\n commands_.push_back(event);\n}\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ Sequencer::Start\n\/\/ ---------------------------------------------------------------------------\nvoid\nSequencer::Start(const uint64_t hostTime, const float tempo)\n{\n this->AddCommand(hostTime, kSeqCommand_Start, tempo);\n}\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ Sequencer::Stop\n\/\/ ---------------------------------------------------------------------------\nvoid\nSequencer::Stop(const uint64_t hostTime)\n{\n this->AddCommand(hostTime, kSeqCommand_Stop, 0.0f\/* ignore *\/);\n}\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ Sequencer::UpdateTempo\n\/\/ ---------------------------------------------------------------------------\nvoid\nSequencer::UpdateTempo(const uint64_t hostTime, const float tempo)\n{\n this->AddCommand(hostTime, kSeqCommand_UpdateTempo, tempo);\n}\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ Sequencer::UpdateNumSteps\n\/\/ ---------------------------------------------------------------------------\nvoid\nSequencer::UpdateNumSteps(const uint64_t hostTime, const int numberOfSteps)\n{\n this->AddCommand(hostTime, kSeqCommand_UpdateNumSteps, numberOfSteps);\n}\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ Sequencer::UpdateTrack\n\/\/ ---------------------------------------------------------------------------\nvoid\nSequencer::UpdateTrack(const int trackNo, const std::vector<bool> &sequence)\n{\n if ((trackNo >= 0) && (trackNo < static_cast<int>(seq_.size())))\n {\n seq_[trackNo] = sequence;\n }\n}\n<commit_msg>Refactoring<commit_after>\/\/\n\/\/ Sequencer.cpp\n\/\/ WISTSample\n\/\/\n\/\/ Created by Nobuhisa Okamura on 11\/05\/19.\n\/\/ Copyright 2011 KORG INC. All rights reserved.\n\/\/\n\n#include <vector>\n#include <mutex>\n#include <algorithm>\n\n#include <mach\/mach_time.h>\n\n#include \"Sequencer.h\"\n#include \"AudioIO.h\"\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ Sequencer::Sequencer\n\/\/ ---------------------------------------------------------------------------\nSequencer::Sequencer(float samplingRate, int numberOfTracks, int numberOfSteps, int stepsPerBeat) :\nsamplingRate_(samplingRate),\nnumberOfTracks_(numberOfTracks),\nnumberOfSteps_(numberOfSteps),\nstepsPerBeat_(stepsPerBeat),\nisRunning_(false),\ncurrentStep_(0),\nstepFrameLength_(0),\ncurrentFrame_(0),\ntrigger_(false),\nseq_(),\ncommands_(),\nlisteners_(),\ncommandsMutex_()\n{\n \/\/ 各ステップの再生有無をstd::vector<bool>で記憶するトラックを4本作成\n SetupTracks();\n}\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ Sequencer::~Sequencer\n\/\/ ---------------------------------------------------------------------------\nSequencer::~Sequencer(void)\n{\n}\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ Sequencer::SetupTracks\n\/\/ ---------------------------------------------------------------------------\nvoid\nSequencer::SetupTracks()\n{\n seq_.clear();\n for (int trackNo = 0; trackNo < numberOfTracks_; ++trackNo)\n {\n std::vector<bool> partSeq(numberOfSteps_, false);\n seq_.push_back(partSeq);\n }\n}\n\nenum\n{\n kSeqCommand_Start = 0,\n kSeqCommand_Stop,\n kSeqCommand_UpdateTempo,\n kSeqCommand_UpdateNumSteps,\n};\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ Sequencer::ProcessCommand\n\/\/ ---------------------------------------------------------------------------\ninline void\nSequencer::ProcessCommand(SeqCommandEvent& event)\n{\n switch (event.command)\n {\n case kSeqCommand_Start:\n if (!isRunning_)\n {\n const float tempo = event.floatValue;\n currentStep_ = 0;\n currentFrame_ = 0;\n stepFrameLength_ = samplingRate_ * 60.0f \/ tempo \/ stepsPerBeat_;\n trigger_ = true;\n isRunning_ = true;\n }\n break;\n case kSeqCommand_Stop:\n if (isRunning_)\n {\n isRunning_ = false;\n }\n break;\n case kSeqCommand_UpdateTempo:\n if (1)\n {\n const float tempo = event.floatValue;\n stepFrameLength_ = samplingRate_ * 60.0f \/ tempo \/ stepsPerBeat_;\n }\n break;\n case kSeqCommand_UpdateNumSteps:\n if (1) {\n const int numberOfSteps = static_cast<int>(event.floatValue);\n if (numberOfSteps != numberOfSteps_) {\n numberOfSteps_ = numberOfSteps;\n SetupTracks();\n }\n }\n break;\n default:\n break;\n }\n}\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ Sequencer::ProcessCommands\n\/\/ ---------------------------------------------------------------------------\ninline int\nSequencer::ProcessCommands(AudioIO* io, int offset, int length)\n{\n if (!commands_.empty())\n {\n const uint64_t hostTime = (io != NULL) ? io->GetHostTime() : 0;\n const uint64_t latency = (io != NULL) ? io->GetLatency() : 0;\n mach_timebase_info_data_t timeInfo;\n ::mach_timebase_info(&timeInfo);\n {\n std::lock_guard<std::mutex> lock(commandsMutex_);\n std::sort(commands_.begin(), commands_.end(), Sequencer::SortEventFunctor);\n for (auto ite = commands_.begin(); ite != commands_.end();)\n {\n bool doProcess = false;\n if (ite->hostTime == 0) \/\/ now\n {\n doProcess = true;\n }\n else if (io != NULL)\n {\n const int64_t delta = ite->hostTime - hostTime;\n const int64_t deltaNanosec = delta * timeInfo.numer \/ timeInfo.denom + latency;\n const int32_t sampleOffset = static_cast<int32_t>(static_cast<double>(deltaNanosec) * samplingRate_ \/ 1000000000);\n if (sampleOffset < offset + length)\n {\n const int eventFrame = sampleOffset - offset;\n if (eventFrame > 0)\n {\n return eventFrame;\n }\n doProcess = true;\n }\n }\n if (doProcess)\n {\n this->ProcessCommand(*ite);\n ite = commands_.erase(ite);\n }\n else\n {\n ++ite;\n }\n }\n }\n }\n return length;\n}\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ Sequencer::ProcessTrigger\n\/\/ ---------------------------------------------------------------------------\ninline void\nSequencer::ProcessTrigger(int offset, const std::vector<int> &trackIndexes)\n{\n for (auto listener : listeners_)\n {\n listener->NoteOnViaSequencer(offset + currentFrame_, trackIndexes, currentStep_);\n }\n}\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ Sequencer::ProcessTrigger\n\/\/ ---------------------------------------------------------------------------\ninline void\nSequencer::ProcessTrigger(int offset)\n{\n if (trigger_ && (currentFrame_ >= 0))\n {\n if ((currentStep_ >= 0) && (currentStep_ < numberOfSteps_))\n {\n \/\/ ここでONトラック(int)だけを集めてProcessTriggerに渡す\n std::vector<int> triggeredTracks;\n const int numOfTrack = static_cast<const int>(seq_.size());\n for (int trackNo = 0; trackNo < numOfTrack; ++trackNo)\n {\n const auto& partSeq = seq_[trackNo];\n if (partSeq[currentStep_])\n {\n triggeredTracks.push_back(trackNo);\n }\n }\n this->ProcessTrigger(offset, triggeredTracks);\n }\n trigger_ = false;\n }\n}\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ Sequencer::ProcessSequence\n\/\/ ---------------------------------------------------------------------------\ninline void\nSequencer::ProcessSequence(int offset, int length)\n{\n int rest = length;\n int startFrame = offset;\n while (rest > 0)\n {\n const int processedLen = std::min<int>(rest, std::max<int>(stepFrameLength_ - currentFrame_, 1));\n this->ProcessTrigger(startFrame);\n currentFrame_ += processedLen;\n rest -= processedLen;\n startFrame += processedLen;\n if (currentFrame_ >= stepFrameLength_)\n {\n currentFrame_ -= stepFrameLength_;\n ++currentStep_;\n if (currentStep_ > numberOfSteps_ - 1)\n {\n currentStep_ = 0;\n }\n trigger_ = true;\n }\n }\n}\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ Sequencer::Process\n\/\/ ---------------------------------------------------------------------------\nint\nSequencer::Process(AudioIO* io, int offset, int length)\n{\n const int result = this->ProcessCommands(io, offset, length);\n if (isRunning_ && (result > 0))\n {\n this->ProcessSequence(offset, result);\n }\n return result;\n}\n\n#pragma mark -\n\/\/ ---------------------------------------------------------------------------\n\/\/ Sequencer::AddListener\n\/\/ ---------------------------------------------------------------------------\nvoid\nSequencer::AddListener(SequencerListener* listener)\n{\n listeners_.push_back(listener);\n}\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ Sequencer::RemoveListener\n\/\/ ---------------------------------------------------------------------------\nvoid\nSequencer::RemoveListener(SequencerListener* listener)\n{\n listeners_.erase(std::remove(std::begin(listeners_),\n std::end(listeners_),\n listener), std::end(listeners_));\n}\n\n#pragma mark -\n\/\/ ---------------------------------------------------------------------------\n\/\/ Sequencer::AddCommand\n\/\/ ---------------------------------------------------------------------------\nvoid\nSequencer::AddCommand(const uint64_t hostTime, const int cmd, const float param0)\n{\n std::lock_guard<std::mutex> lock(commandsMutex_);\n const SeqCommandEvent event = { hostTime, cmd, param0 };\n commands_.push_back(event);\n}\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ Sequencer::Start\n\/\/ ---------------------------------------------------------------------------\nvoid\nSequencer::Start(const uint64_t hostTime, const float tempo)\n{\n this->AddCommand(hostTime, kSeqCommand_Start, tempo);\n}\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ Sequencer::Stop\n\/\/ ---------------------------------------------------------------------------\nvoid\nSequencer::Stop(const uint64_t hostTime)\n{\n this->AddCommand(hostTime, kSeqCommand_Stop, 0.0f\/* ignore *\/);\n}\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ Sequencer::UpdateTempo\n\/\/ ---------------------------------------------------------------------------\nvoid\nSequencer::UpdateTempo(const uint64_t hostTime, const float tempo)\n{\n this->AddCommand(hostTime, kSeqCommand_UpdateTempo, tempo);\n}\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ Sequencer::UpdateNumSteps\n\/\/ ---------------------------------------------------------------------------\nvoid\nSequencer::UpdateNumSteps(const uint64_t hostTime, const int numberOfSteps)\n{\n this->AddCommand(hostTime, kSeqCommand_UpdateNumSteps, numberOfSteps);\n}\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ Sequencer::UpdateTrack\n\/\/ ---------------------------------------------------------------------------\nvoid\nSequencer::UpdateTrack(const int trackNo, const std::vector<bool> &sequence)\n{\n if ((trackNo >= 0) && (trackNo < static_cast<int>(seq_.size())))\n {\n seq_[trackNo] = sequence;\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/*=========================================================================\n\n Program: Visualization Toolkit\n Module: vtkTreeDifferenceFilter.cxx\n\n Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen\n All rights reserved.\n See Copyright.txt or http:\/\/www.kitware.com\/Copyright.htm for details.\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notice for more information.\n\n=========================================================================*\/\n\n#include \"vtkTreeDifferenceFilter.h\"\n\n#include \"vtkDataSetAttributes.h\"\n#include \"vtkDoubleArray.h\"\n#include \"vtkInformation.h\"\n#include \"vtkInformationVector.h\"\n#include \"vtkMath.h\"\n#include \"vtkNew.h\"\n#include \"vtkObjectFactory.h\"\n#include \"vtkStringArray.h\"\n#include \"vtkTree.h\"\n\nvtkStandardNewMacro(vtkTreeDifferenceFilter);\n\n\/\/---------------------------------------------------------------------------\nvtkTreeDifferenceFilter::vtkTreeDifferenceFilter()\n{\n this->SetNumberOfInputPorts(2);\n this->SetNumberOfOutputPorts(1);\n\n this->IdArrayName = 0;\n this->ComparisonArrayName = 0;\n this->OutputArrayName = 0;\n this->ComparisonArrayIsVertexData = false;\n}\n\n\/\/---------------------------------------------------------------------------\nvtkTreeDifferenceFilter::~vtkTreeDifferenceFilter()\n{\n \/\/ release memory\n this->SetIdArrayName(0);\n this->SetComparisonArrayName(0);\n this->SetOutputArrayName(0);\n}\n\n\/\/---------------------------------------------------------------------------\nint vtkTreeDifferenceFilter::FillInputPortInformation(int port, vtkInformation *info)\n{\n if(port == 0)\n {\n info->Set(vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE(), \"vtkTree\");\n }\n else if(port == 1)\n {\n info->Set(vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE(), \"vtkTree\");\n info->Set(vtkAlgorithm::INPUT_IS_OPTIONAL(), 1);\n }\n\n return 1;\n}\n\n\/\/---------------------------------------------------------------------------\nint vtkTreeDifferenceFilter::RequestData(\n vtkInformation*,\n vtkInformationVector** inputVector,\n vtkInformationVector* outputVector)\n{\n vtkInformation* tree1_info = inputVector[0]->GetInformationObject(0);\n vtkTree* tree1 = vtkTree::SafeDownCast(\n tree1_info->Get(vtkDataObject::DATA_OBJECT()));\n\n \/\/ Copy the structure into the output.\n vtkTree* outputTree = vtkTree::GetData(outputVector);\n\n vtkInformation* tree2_info = inputVector[1]->GetInformationObject(0);\n if(!tree2_info)\n {\n \/\/ If no second tree provided, we're done\n outputTree->CheckedShallowCopy(tree1);\n return 0;\n }\n\n vtkTree* tree2 = vtkTree::SafeDownCast(\n tree2_info->Get(vtkDataObject::DATA_OBJECT()));\n\n if (this->IdArrayName != 0)\n {\n if (!this->GenerateMapping(tree1, tree2))\n {\n return 0;\n }\n }\n else\n {\n this->VertexMap.clear();\n for (vtkIdType vertex = 0; vertex < tree1->GetNumberOfVertices(); ++vertex)\n {\n this->VertexMap[vertex] = vertex;\n }\n\n this->EdgeMap.clear();\n for (vtkIdType edge = 0; edge < tree1->GetNumberOfEdges(); ++edge)\n {\n this->EdgeMap[edge] = edge;\n }\n }\n\n vtkSmartPointer<vtkDoubleArray> resultArray =\n this->ComputeDifference(tree1, tree2);\n\n if (!outputTree->CheckedShallowCopy(tree1))\n {\n vtkErrorMacro(<<\"Invalid tree structure.\");\n return 0;\n }\n\n if (this->ComparisonArrayIsVertexData)\n {\n outputTree->GetVertexData()->AddArray(resultArray);\n }\n else\n {\n outputTree->GetEdgeData()->AddArray(resultArray);\n }\n\n return 1;\n}\n\n\/\/---------------------------------------------------------------------------\nbool vtkTreeDifferenceFilter::GenerateMapping(vtkTree *tree1, vtkTree *tree2)\n{\n this->VertexMap.clear();\n this->VertexMap.assign(tree1->GetNumberOfVertices(), -1);\n\n this->EdgeMap.clear();\n this->EdgeMap.assign(tree1->GetNumberOfEdges(), -1);\n\n vtkStringArray *nodeNames1 = vtkStringArray::SafeDownCast(\n tree1->GetVertexData()->GetAbstractArray(this->IdArrayName));\n if (nodeNames1 == NULL)\n {\n vtkErrorMacro(\"tree #1's VertexData does not have a vtkStringArray named \"\n << this->IdArrayName);\n return false;\n }\n\n vtkStringArray *nodeNames2 = vtkStringArray::SafeDownCast(\n tree2->GetVertexData()->GetAbstractArray(this->IdArrayName));\n if (nodeNames2 == NULL)\n {\n vtkErrorMacro(\"tree #2's VertexData does not have a vtkStringArray named \"\n << this->IdArrayName);\n return false;\n }\n\n vtkIdType root1 = tree1->GetRoot();\n vtkIdType root2 = tree2->GetRoot();\n\n vtkIdType edgeId1 = -1;\n vtkIdType edgeId2 = -1;\n\n \/\/ iterate over the vertex names for tree #1, finding the corresponding\n \/\/ vertex in tree #2.\n for (vtkIdType vertexItr = 0; vertexItr < nodeNames1->GetNumberOfTuples();\n ++vertexItr)\n {\n vtkIdType vertexId1 = vertexItr;\n std::string nodeName = nodeNames1->GetValue(vertexId1);\n if (nodeName.compare(\"\") == 0)\n {\n continue;\n }\n\n \/\/ record this correspondence in the maps\n vtkIdType vertexId2 = nodeNames2->LookupValue(nodeName);\n if (vertexId2 == -1)\n {\n vtkWarningMacro(\"tree #2 does not contain a vertex named \" << nodeName);\n continue;\n }\n this->VertexMap[vertexId1] = vertexId2;\n\n if (vertexId1 == root1 || vertexId2 == root2)\n {\n continue;\n }\n\n edgeId1 = tree1->GetEdgeId(tree1->GetParent(vertexId1), vertexId1);\n edgeId2 = tree2->GetEdgeId(tree2->GetParent(vertexId2), vertexId2);\n this->EdgeMap[edgeId1] = edgeId2;\n\n \/\/ ascend the tree until we reach the root, mapping parent vertices to\n \/\/ each other along the way.\n while (tree1->GetParent(vertexId1) != root1 &&\n tree2->GetParent(vertexId2) != root2)\n {\n vertexId1 = tree1->GetParent(vertexId1);\n vertexId2 = tree2->GetParent(vertexId2);\n if (this->VertexMap[vertexId1] == -1)\n {\n this->VertexMap[vertexId1] = vertexId2;\n edgeId1 = tree1->GetEdgeId(tree1->GetParent(vertexId1), vertexId1);\n edgeId2 = tree2->GetEdgeId(tree2->GetParent(vertexId2), vertexId2);\n this->EdgeMap[edgeId1] = edgeId2;\n }\n }\n }\n\n return true;\n}\n\n\/\/---------------------------------------------------------------------------\nvtkSmartPointer<vtkDoubleArray>\nvtkTreeDifferenceFilter::ComputeDifference(vtkTree *tree1, vtkTree *tree2)\n{\n if (this->ComparisonArrayName == 0)\n {\n vtkErrorMacro(\"ComparisonArrayName has not been set.\");\n return NULL;\n }\n\n vtkDataSetAttributes *treeData1, *treeData2;\n const char *dataName;\n if (this->ComparisonArrayIsVertexData)\n {\n treeData1 = tree1->GetVertexData();\n treeData2 = tree2->GetVertexData();\n dataName = \"VertexData\";\n }\n else\n {\n treeData1 = tree1->GetEdgeData();\n treeData2 = tree2->GetEdgeData();\n dataName = \"EdgeData\";\n }\n\n vtkDataArray *arrayToCompare1 =\n treeData1->GetArray(this->ComparisonArrayName);\n if (arrayToCompare1 == NULL)\n {\n vtkErrorMacro(\"tree #1's \" << dataName <<\n \" does not have a vtkDoubleArray named \" << this->IdArrayName);\n return NULL;\n }\n\n vtkDataArray *arrayToCompare2 =\n treeData2->GetArray(this->ComparisonArrayName);\n if (arrayToCompare2 == NULL)\n {\n vtkErrorMacro(\"tree #2's \" << dataName <<\n \" does not have a vtkDoubleArray named \" << this->IdArrayName);\n return NULL;\n }\n\n vtkSmartPointer<vtkDoubleArray> resultArray =\n vtkSmartPointer<vtkDoubleArray>::New();\n resultArray->SetNumberOfValues(arrayToCompare1->GetNumberOfTuples());\n resultArray->FillComponent(0, vtkMath::Nan());\n\n if (this->OutputArrayName == 0)\n {\n resultArray->SetName(\"difference\");\n }\n else\n {\n resultArray->SetName(this->OutputArrayName);\n }\n\n vtkIdType treeId2;\n for (vtkIdType treeId1 = 0; treeId1 < arrayToCompare1->GetNumberOfTuples();\n ++treeId1)\n {\n if (this->ComparisonArrayIsVertexData)\n {\n treeId2 = this->VertexMap[treeId1];\n }\n else\n {\n treeId2 = this->EdgeMap[treeId1];\n }\n double result =\n arrayToCompare1->GetTuple1(treeId1) - arrayToCompare2->GetTuple1(treeId2);\n resultArray->SetValue(treeId1, result);\n }\n\n return resultArray;\n}\n\n\/\/---------------------------------------------------------------------------\nvoid vtkTreeDifferenceFilter::PrintSelf(ostream& os, vtkIndent indent)\n{\n this->Superclass::PrintSelf(os, indent);\n if (this->IdArrayName)\n {\n os << indent << \"IdArrayName: \"\n << this->IdArrayName << std::endl;\n }\n else\n {\n os << indent << \"IdArrayName: \"\n << \"(None)\" << std::endl;\n }\n if (this->ComparisonArrayName)\n {\n os << indent << \"ComparisonArrayName: \"\n << this->ComparisonArrayName << std::endl;\n }\n else\n {\n os << indent << \"ComparisonArrayName: \"\n << \"(None)\" << std::endl;\n }\n if (this->OutputArrayName)\n {\n os << indent << \"OutputArrayName: \"\n << this->OutputArrayName << std::endl;\n }\n else\n {\n os << indent << \"OutputArrayName: \"\n << \"(None)\" << std::endl;\n }\n os << indent << \"ComparisonArrayIsVertexData: \"\n << this->ComparisonArrayIsVertexData << std::endl;\n}\n<commit_msg>fix error message<commit_after>\/*=========================================================================\n\n Program: Visualization Toolkit\n Module: vtkTreeDifferenceFilter.cxx\n\n Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen\n All rights reserved.\n See Copyright.txt or http:\/\/www.kitware.com\/Copyright.htm for details.\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notice for more information.\n\n=========================================================================*\/\n\n#include \"vtkTreeDifferenceFilter.h\"\n\n#include \"vtkDataSetAttributes.h\"\n#include \"vtkDoubleArray.h\"\n#include \"vtkInformation.h\"\n#include \"vtkInformationVector.h\"\n#include \"vtkMath.h\"\n#include \"vtkNew.h\"\n#include \"vtkObjectFactory.h\"\n#include \"vtkStringArray.h\"\n#include \"vtkTree.h\"\n\nvtkStandardNewMacro(vtkTreeDifferenceFilter);\n\n\/\/---------------------------------------------------------------------------\nvtkTreeDifferenceFilter::vtkTreeDifferenceFilter()\n{\n this->SetNumberOfInputPorts(2);\n this->SetNumberOfOutputPorts(1);\n\n this->IdArrayName = 0;\n this->ComparisonArrayName = 0;\n this->OutputArrayName = 0;\n this->ComparisonArrayIsVertexData = false;\n}\n\n\/\/---------------------------------------------------------------------------\nvtkTreeDifferenceFilter::~vtkTreeDifferenceFilter()\n{\n \/\/ release memory\n this->SetIdArrayName(0);\n this->SetComparisonArrayName(0);\n this->SetOutputArrayName(0);\n}\n\n\/\/---------------------------------------------------------------------------\nint vtkTreeDifferenceFilter::FillInputPortInformation(int port, vtkInformation *info)\n{\n if(port == 0)\n {\n info->Set(vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE(), \"vtkTree\");\n }\n else if(port == 1)\n {\n info->Set(vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE(), \"vtkTree\");\n info->Set(vtkAlgorithm::INPUT_IS_OPTIONAL(), 1);\n }\n\n return 1;\n}\n\n\/\/---------------------------------------------------------------------------\nint vtkTreeDifferenceFilter::RequestData(\n vtkInformation*,\n vtkInformationVector** inputVector,\n vtkInformationVector* outputVector)\n{\n vtkInformation* tree1_info = inputVector[0]->GetInformationObject(0);\n vtkTree* tree1 = vtkTree::SafeDownCast(\n tree1_info->Get(vtkDataObject::DATA_OBJECT()));\n\n \/\/ Copy the structure into the output.\n vtkTree* outputTree = vtkTree::GetData(outputVector);\n\n vtkInformation* tree2_info = inputVector[1]->GetInformationObject(0);\n if(!tree2_info)\n {\n \/\/ If no second tree provided, we're done\n outputTree->CheckedShallowCopy(tree1);\n return 0;\n }\n\n vtkTree* tree2 = vtkTree::SafeDownCast(\n tree2_info->Get(vtkDataObject::DATA_OBJECT()));\n\n if (this->IdArrayName != 0)\n {\n if (!this->GenerateMapping(tree1, tree2))\n {\n return 0;\n }\n }\n else\n {\n this->VertexMap.clear();\n for (vtkIdType vertex = 0; vertex < tree1->GetNumberOfVertices(); ++vertex)\n {\n this->VertexMap[vertex] = vertex;\n }\n\n this->EdgeMap.clear();\n for (vtkIdType edge = 0; edge < tree1->GetNumberOfEdges(); ++edge)\n {\n this->EdgeMap[edge] = edge;\n }\n }\n\n vtkSmartPointer<vtkDoubleArray> resultArray =\n this->ComputeDifference(tree1, tree2);\n\n if (!outputTree->CheckedShallowCopy(tree1))\n {\n vtkErrorMacro(<<\"Invalid tree structure.\");\n return 0;\n }\n\n if (this->ComparisonArrayIsVertexData)\n {\n outputTree->GetVertexData()->AddArray(resultArray);\n }\n else\n {\n outputTree->GetEdgeData()->AddArray(resultArray);\n }\n\n return 1;\n}\n\n\/\/---------------------------------------------------------------------------\nbool vtkTreeDifferenceFilter::GenerateMapping(vtkTree *tree1, vtkTree *tree2)\n{\n this->VertexMap.clear();\n this->VertexMap.assign(tree1->GetNumberOfVertices(), -1);\n\n this->EdgeMap.clear();\n this->EdgeMap.assign(tree1->GetNumberOfEdges(), -1);\n\n vtkStringArray *nodeNames1 = vtkStringArray::SafeDownCast(\n tree1->GetVertexData()->GetAbstractArray(this->IdArrayName));\n if (nodeNames1 == NULL)\n {\n vtkErrorMacro(\"tree #1's VertexData does not have a vtkStringArray named \"\n << this->IdArrayName);\n return false;\n }\n\n vtkStringArray *nodeNames2 = vtkStringArray::SafeDownCast(\n tree2->GetVertexData()->GetAbstractArray(this->IdArrayName));\n if (nodeNames2 == NULL)\n {\n vtkErrorMacro(\"tree #2's VertexData does not have a vtkStringArray named \"\n << this->IdArrayName);\n return false;\n }\n\n vtkIdType root1 = tree1->GetRoot();\n vtkIdType root2 = tree2->GetRoot();\n\n vtkIdType edgeId1 = -1;\n vtkIdType edgeId2 = -1;\n\n \/\/ iterate over the vertex names for tree #1, finding the corresponding\n \/\/ vertex in tree #2.\n for (vtkIdType vertexItr = 0; vertexItr < nodeNames1->GetNumberOfTuples();\n ++vertexItr)\n {\n vtkIdType vertexId1 = vertexItr;\n std::string nodeName = nodeNames1->GetValue(vertexId1);\n if (nodeName.compare(\"\") == 0)\n {\n continue;\n }\n\n \/\/ record this correspondence in the maps\n vtkIdType vertexId2 = nodeNames2->LookupValue(nodeName);\n if (vertexId2 == -1)\n {\n vtkWarningMacro(\"tree #2 does not contain a vertex named \" << nodeName);\n continue;\n }\n this->VertexMap[vertexId1] = vertexId2;\n\n if (vertexId1 == root1 || vertexId2 == root2)\n {\n continue;\n }\n\n edgeId1 = tree1->GetEdgeId(tree1->GetParent(vertexId1), vertexId1);\n edgeId2 = tree2->GetEdgeId(tree2->GetParent(vertexId2), vertexId2);\n this->EdgeMap[edgeId1] = edgeId2;\n\n \/\/ ascend the tree until we reach the root, mapping parent vertices to\n \/\/ each other along the way.\n while (tree1->GetParent(vertexId1) != root1 &&\n tree2->GetParent(vertexId2) != root2)\n {\n vertexId1 = tree1->GetParent(vertexId1);\n vertexId2 = tree2->GetParent(vertexId2);\n if (this->VertexMap[vertexId1] == -1)\n {\n this->VertexMap[vertexId1] = vertexId2;\n edgeId1 = tree1->GetEdgeId(tree1->GetParent(vertexId1), vertexId1);\n edgeId2 = tree2->GetEdgeId(tree2->GetParent(vertexId2), vertexId2);\n this->EdgeMap[edgeId1] = edgeId2;\n }\n }\n }\n\n return true;\n}\n\n\/\/---------------------------------------------------------------------------\nvtkSmartPointer<vtkDoubleArray>\nvtkTreeDifferenceFilter::ComputeDifference(vtkTree *tree1, vtkTree *tree2)\n{\n if (this->ComparisonArrayName == 0)\n {\n vtkErrorMacro(\"ComparisonArrayName has not been set.\");\n return NULL;\n }\n\n vtkDataSetAttributes *treeData1, *treeData2;\n const char *dataName;\n if (this->ComparisonArrayIsVertexData)\n {\n treeData1 = tree1->GetVertexData();\n treeData2 = tree2->GetVertexData();\n dataName = \"VertexData\";\n }\n else\n {\n treeData1 = tree1->GetEdgeData();\n treeData2 = tree2->GetEdgeData();\n dataName = \"EdgeData\";\n }\n\n vtkDataArray *arrayToCompare1 =\n treeData1->GetArray(this->ComparisonArrayName);\n if (arrayToCompare1 == NULL)\n {\n vtkErrorMacro(\"tree #1's \" << dataName <<\n \" does not have a vtkDoubleArray named \" << this->ComparisonArrayName);\n return NULL;\n }\n\n vtkDataArray *arrayToCompare2 =\n treeData2->GetArray(this->ComparisonArrayName);\n if (arrayToCompare2 == NULL)\n {\n vtkErrorMacro(\"tree #2's \" << dataName <<\n \" does not have a vtkDoubleArray named \" << this->ComparisonArrayName);\n return NULL;\n }\n\n vtkSmartPointer<vtkDoubleArray> resultArray =\n vtkSmartPointer<vtkDoubleArray>::New();\n resultArray->SetNumberOfValues(arrayToCompare1->GetNumberOfTuples());\n resultArray->FillComponent(0, vtkMath::Nan());\n\n if (this->OutputArrayName == 0)\n {\n resultArray->SetName(\"difference\");\n }\n else\n {\n resultArray->SetName(this->OutputArrayName);\n }\n\n vtkIdType treeId2;\n for (vtkIdType treeId1 = 0; treeId1 < arrayToCompare1->GetNumberOfTuples();\n ++treeId1)\n {\n if (this->ComparisonArrayIsVertexData)\n {\n treeId2 = this->VertexMap[treeId1];\n }\n else\n {\n treeId2 = this->EdgeMap[treeId1];\n }\n double result =\n arrayToCompare1->GetTuple1(treeId1) - arrayToCompare2->GetTuple1(treeId2);\n resultArray->SetValue(treeId1, result);\n }\n\n return resultArray;\n}\n\n\/\/---------------------------------------------------------------------------\nvoid vtkTreeDifferenceFilter::PrintSelf(ostream& os, vtkIndent indent)\n{\n this->Superclass::PrintSelf(os, indent);\n if (this->IdArrayName)\n {\n os << indent << \"IdArrayName: \"\n << this->IdArrayName << std::endl;\n }\n else\n {\n os << indent << \"IdArrayName: \"\n << \"(None)\" << std::endl;\n }\n if (this->ComparisonArrayName)\n {\n os << indent << \"ComparisonArrayName: \"\n << this->ComparisonArrayName << std::endl;\n }\n else\n {\n os << indent << \"ComparisonArrayName: \"\n << \"(None)\" << std::endl;\n }\n if (this->OutputArrayName)\n {\n os << indent << \"OutputArrayName: \"\n << this->OutputArrayName << std::endl;\n }\n else\n {\n os << indent << \"OutputArrayName: \"\n << \"(None)\" << std::endl;\n }\n os << indent << \"ComparisonArrayIsVertexData: \"\n << this->ComparisonArrayIsVertexData << std::endl;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"vector.h\"\r\n#include \"..\/nullc.h\"\r\n#include \"typeinfo.h\"\r\n\r\n#include <memory>\r\n\r\nnamespace NULLCVector\r\n{\r\n#pragma pack(push, 4)\r\n\tstruct vector\r\n\t{\r\n\t\tunsigned int\telemType;\r\n\t\tunsigned int\tflags;\r\n\t\tunsigned int\telemSize;\r\n\t\tNULLCAutoArray\tdata;\r\n\t\tunsigned int\tsize;\r\n\t};\r\n\r\n\tstruct vector_iterator\r\n\t{\r\n\t\tvector*\t\t\tarr;\r\n\t\tunsigned int\tpos;\r\n\t};\r\n#pragma pack(pop)\r\n\r\n\tvoid ConstructVector(vector* vec, unsigned int type, int reserved)\r\n\t{\r\n\t\tvec->elemType = type;\r\n\t\tvec->flags = nullcIsPointer(type);\r\n\t\tvec->size = 0;\r\n\t\tvec->elemSize = nullcGetTypeSize(type);\r\n\t\tvec->data.typeID = type;\r\n\t\tif(reserved)\r\n\t\t{\r\n\t\t\tvec->data.ptr = (char*)nullcAllocate(vec->elemSize * reserved);\r\n\t\t\tvec->data.len = reserved;\r\n\t\t}else{\r\n\t\t\tvec->data.ptr = NULL;\r\n\t\t\tvec->data.len = 0;\r\n\t\t}\r\n\t}\r\n\r\n\tvoid VectorPushBack(NULLCRef val, vector* vec)\r\n\t{\r\n\t\t\/\/ Check that we received type that is equal to array element type\r\n\t\tif(val.typeID != (vec->flags ? nullcGetSubType(vec->elemType) : vec->elemType))\r\n\t\t{\r\n\t\t\tnullcThrowError(\"vector::push_back received value (%s) that is different from vector type (%s)\", nullcGetTypeName(val.typeID), nullcGetTypeName(vec->elemType));\r\n\t\t\treturn;\r\n\t\t}\r\n\t\t\/\/ If not enough space\r\n\t\tif(vec->size == vec->data.len)\r\n\t\t{\r\n\t\t\t\/\/ Allocate new\r\n\t\t\tunsigned int newSize = 32 > vec->data.len ? 32 : (vec->data.len << 1) + vec->data.len;\r\n\t\t\tchar *newData = (char*)nullcAllocate(vec->elemSize * newSize);\r\n\t\t\tmemcpy(newData, vec->data.ptr, vec->elemSize * vec->data.len);\r\n\t\t\tvec->data.len = newSize;\r\n\t\t\tvec->data.ptr = newData;\r\n\t\t}\r\n\t\tmemcpy(vec->data.ptr + vec->elemSize * vec->size, vec->flags ? (char*)&val.ptr : val.ptr, vec->elemSize);\r\n\t\tvec->size++;\r\n\t}\r\n\r\n\tvoid VectorPopBack(vector* vec)\r\n\t{\r\n\t\tif(!vec->size)\r\n\t\t{\r\n\t\t\tnullcThrowError(\"vector::pop_back called on an empty vector\");\r\n\t\t\treturn;\r\n\t\t}\r\n\t\tvec->size--;\r\n\t}\r\n\r\n\tNULLCRef VectorFront(vector* vec)\r\n\t{\r\n\t\tNULLCRef ret = { 0, 0 };\r\n\t\tif(!vec->size)\r\n\t\t{\r\n\t\t\tnullcThrowError(\"vector::front called on an empty vector\");\r\n\t\t\treturn ret;\r\n\t\t}\r\n\t\tret.typeID = (vec->flags ? nullcGetSubType(vec->elemType) : vec->elemType);\r\n\t\tret.ptr = vec->flags ? *(char**)vec->data.ptr : vec->data.ptr;\r\n\t\treturn ret;\r\n\t}\r\n\r\n\tNULLCRef VectorBack(vector* vec)\r\n\t{\r\n\t\tNULLCRef ret = { 0, 0 };\r\n\t\tif(!vec->size)\r\n\t\t{\r\n\t\t\tnullcThrowError(\"vector::back called on an empty vector\");\r\n\t\t\treturn ret;\r\n\t\t}\r\n\t\tret.typeID = (vec->flags ? nullcGetSubType(vec->elemType) : vec->elemType);\r\n\t\tret.ptr = vec->flags ? ((char**)vec->data.ptr)[vec->size - 1] : (vec->data.ptr + vec->elemSize * (vec->size - 1));\r\n\t\treturn ret;\r\n\t}\r\n\r\n\tNULLCRef VectorIndex(vector* vec, unsigned int index)\r\n\t{\r\n\t\tNULLCRef ret = { 0, 0 };\r\n\t\tif(index >= vec->size)\r\n\t\t{\r\n\t\t\tnullcThrowError(\"operator[] array index out of bounds\");\r\n\t\t\treturn ret;\r\n\t\t}\r\n\t\tret.typeID = (vec->flags ? nullcGetSubType(vec->elemType) : vec->elemType);\r\n\t\tret.ptr = vec->flags ? ((char**)vec->data.ptr)[index] : (vec->data.ptr + vec->elemSize * index);\r\n\t\treturn ret;\r\n\t}\r\n\r\n\tvoid VectorReserve(unsigned int size, vector* vec)\r\n\t{\r\n\t\t\/\/ If not enough space\r\n\t\tif(size > vec->data.len)\r\n\t\t{\r\n\t\t\t\/\/ Allocate new\r\n\t\t\tchar *newData = (char*)nullcAllocate(vec->elemSize * size);\r\n\t\t\tmemcpy(newData, vec->data.ptr, vec->elemSize * vec->data.len);\r\n\t\t\tvec->data.len = size;\r\n\t\t\tvec->data.ptr = newData;\r\n\t\t}\r\n\t}\r\n\r\n\tvoid VectorResize(unsigned int size, vector* vec)\r\n\t{\r\n\t\tVectorReserve(size, vec);\r\n\t\tvec->size = size;\r\n\t}\r\n\r\n\tvoid VectorClear(vector* vec)\r\n\t{\r\n\t\tvec->size = 0;\r\n\t}\r\n\r\n\tvoid VectorDestroy(vector* vec)\r\n\t{\r\n\t\tvec->size = 0;\r\n\t\tvec->data.len = 0;\r\n\t\tvec->data.ptr = NULL;\r\n\t}\r\n\r\n\tint VectorSize(vector* vec)\r\n\t{\r\n\t\treturn vec->size;\r\n\t}\r\n\r\n\tint VectorCapacity(vector* vec)\r\n\t{\r\n\t\treturn vec->data.len;\r\n\t}\r\n\r\n\tNULLCRef VectorNext(vector_iterator* iter)\r\n\t{\r\n\t\tNULLCRef ret;\r\n\t\tret.typeID = (iter->arr->flags ? nullcGetSubType(iter->arr->elemType) : iter->arr->elemType);\r\n\t\tret.ptr = iter->arr->flags ? ((char**)iter->arr->data.ptr)[iter->pos] : iter->arr->data.ptr + iter->arr->elemSize * iter->pos;\r\n\t\titer->pos++;\r\n\t\treturn ret;\r\n\t}\r\n\tint VectorHasNext(vector_iterator* iter)\r\n\t{\r\n\t\treturn iter->arr && iter->pos < iter->arr->size;\r\n\t}\r\n\r\n}\r\n\r\n#define REGISTER_FUNC(funcPtr, name, index) if(!nullcBindModuleFunction(\"old.vector\", (void(*)())NULLCVector::funcPtr, name, index)) return false;\r\nbool\tnullcInitVectorModule()\r\n{\r\n\tREGISTER_FUNC(ConstructVector, \"cConstructVector\", 0);\r\n\r\n\tREGISTER_FUNC(VectorPushBack, \"vector::push_back\", 0);\r\n\tREGISTER_FUNC(VectorPopBack, \"vector::pop_back\", 0);\r\n\tREGISTER_FUNC(VectorFront, \"vector::front\", 0);\r\n\tREGISTER_FUNC(VectorBack, \"vector::back\", 0);\r\n\tREGISTER_FUNC(VectorIndex, \"[]\", 0);\r\n\tREGISTER_FUNC(VectorReserve, \"vector::reserve\", 0);\r\n\tREGISTER_FUNC(VectorResize, \"vector::resize\", 0);\r\n\tREGISTER_FUNC(VectorClear, \"vector::clear\", 0);\r\n\tREGISTER_FUNC(VectorDestroy, \"vector::destroy\", 0);\r\n\tREGISTER_FUNC(VectorSize, \"vector::size\", 0);\r\n\tREGISTER_FUNC(VectorCapacity, \"vector::capacity\", 0);\r\n\r\n\tREGISTER_FUNC(VectorNext, \"vector_iterator::next\", 0);\r\n\tREGISTER_FUNC(VectorHasNext, \"vector_iterator::hasnext\", 0);\r\n\r\n\treturn true;\r\n}\r\n<commit_msg>linux: compilation fix<commit_after>#include \"vector.h\"\r\n#include \"..\/nullc.h\"\r\n#include \"typeinfo.h\"\r\n\r\n#include <memory>\r\n#include <memory.h>\r\n\r\nnamespace NULLCVector\r\n{\r\n#pragma pack(push, 4)\r\n\tstruct vector\r\n\t{\r\n\t\tunsigned int\telemType;\r\n\t\tunsigned int\tflags;\r\n\t\tunsigned int\telemSize;\r\n\t\tNULLCAutoArray\tdata;\r\n\t\tunsigned int\tsize;\r\n\t};\r\n\r\n\tstruct vector_iterator\r\n\t{\r\n\t\tvector*\t\t\tarr;\r\n\t\tunsigned int\tpos;\r\n\t};\r\n#pragma pack(pop)\r\n\r\n\tvoid ConstructVector(vector* vec, unsigned int type, int reserved)\r\n\t{\r\n\t\tvec->elemType = type;\r\n\t\tvec->flags = nullcIsPointer(type);\r\n\t\tvec->size = 0;\r\n\t\tvec->elemSize = nullcGetTypeSize(type);\r\n\t\tvec->data.typeID = type;\r\n\t\tif(reserved)\r\n\t\t{\r\n\t\t\tvec->data.ptr = (char*)nullcAllocate(vec->elemSize * reserved);\r\n\t\t\tvec->data.len = reserved;\r\n\t\t}else{\r\n\t\t\tvec->data.ptr = NULL;\r\n\t\t\tvec->data.len = 0;\r\n\t\t}\r\n\t}\r\n\r\n\tvoid VectorPushBack(NULLCRef val, vector* vec)\r\n\t{\r\n\t\t\/\/ Check that we received type that is equal to array element type\r\n\t\tif(val.typeID != (vec->flags ? nullcGetSubType(vec->elemType) : vec->elemType))\r\n\t\t{\r\n\t\t\tnullcThrowError(\"vector::push_back received value (%s) that is different from vector type (%s)\", nullcGetTypeName(val.typeID), nullcGetTypeName(vec->elemType));\r\n\t\t\treturn;\r\n\t\t}\r\n\t\t\/\/ If not enough space\r\n\t\tif(vec->size == vec->data.len)\r\n\t\t{\r\n\t\t\t\/\/ Allocate new\r\n\t\t\tunsigned int newSize = 32 > vec->data.len ? 32 : (vec->data.len << 1) + vec->data.len;\r\n\t\t\tchar *newData = (char*)nullcAllocate(vec->elemSize * newSize);\r\n\t\t\tmemcpy(newData, vec->data.ptr, vec->elemSize * vec->data.len);\r\n\t\t\tvec->data.len = newSize;\r\n\t\t\tvec->data.ptr = newData;\r\n\t\t}\r\n\t\tmemcpy(vec->data.ptr + vec->elemSize * vec->size, vec->flags ? (char*)&val.ptr : val.ptr, vec->elemSize);\r\n\t\tvec->size++;\r\n\t}\r\n\r\n\tvoid VectorPopBack(vector* vec)\r\n\t{\r\n\t\tif(!vec->size)\r\n\t\t{\r\n\t\t\tnullcThrowError(\"vector::pop_back called on an empty vector\");\r\n\t\t\treturn;\r\n\t\t}\r\n\t\tvec->size--;\r\n\t}\r\n\r\n\tNULLCRef VectorFront(vector* vec)\r\n\t{\r\n\t\tNULLCRef ret = { 0, 0 };\r\n\t\tif(!vec->size)\r\n\t\t{\r\n\t\t\tnullcThrowError(\"vector::front called on an empty vector\");\r\n\t\t\treturn ret;\r\n\t\t}\r\n\t\tret.typeID = (vec->flags ? nullcGetSubType(vec->elemType) : vec->elemType);\r\n\t\tret.ptr = vec->flags ? *(char**)vec->data.ptr : vec->data.ptr;\r\n\t\treturn ret;\r\n\t}\r\n\r\n\tNULLCRef VectorBack(vector* vec)\r\n\t{\r\n\t\tNULLCRef ret = { 0, 0 };\r\n\t\tif(!vec->size)\r\n\t\t{\r\n\t\t\tnullcThrowError(\"vector::back called on an empty vector\");\r\n\t\t\treturn ret;\r\n\t\t}\r\n\t\tret.typeID = (vec->flags ? nullcGetSubType(vec->elemType) : vec->elemType);\r\n\t\tret.ptr = vec->flags ? ((char**)vec->data.ptr)[vec->size - 1] : (vec->data.ptr + vec->elemSize * (vec->size - 1));\r\n\t\treturn ret;\r\n\t}\r\n\r\n\tNULLCRef VectorIndex(vector* vec, unsigned int index)\r\n\t{\r\n\t\tNULLCRef ret = { 0, 0 };\r\n\t\tif(index >= vec->size)\r\n\t\t{\r\n\t\t\tnullcThrowError(\"operator[] array index out of bounds\");\r\n\t\t\treturn ret;\r\n\t\t}\r\n\t\tret.typeID = (vec->flags ? nullcGetSubType(vec->elemType) : vec->elemType);\r\n\t\tret.ptr = vec->flags ? ((char**)vec->data.ptr)[index] : (vec->data.ptr + vec->elemSize * index);\r\n\t\treturn ret;\r\n\t}\r\n\r\n\tvoid VectorReserve(unsigned int size, vector* vec)\r\n\t{\r\n\t\t\/\/ If not enough space\r\n\t\tif(size > vec->data.len)\r\n\t\t{\r\n\t\t\t\/\/ Allocate new\r\n\t\t\tchar *newData = (char*)nullcAllocate(vec->elemSize * size);\r\n\t\t\tmemcpy(newData, vec->data.ptr, vec->elemSize * vec->data.len);\r\n\t\t\tvec->data.len = size;\r\n\t\t\tvec->data.ptr = newData;\r\n\t\t}\r\n\t}\r\n\r\n\tvoid VectorResize(unsigned int size, vector* vec)\r\n\t{\r\n\t\tVectorReserve(size, vec);\r\n\t\tvec->size = size;\r\n\t}\r\n\r\n\tvoid VectorClear(vector* vec)\r\n\t{\r\n\t\tvec->size = 0;\r\n\t}\r\n\r\n\tvoid VectorDestroy(vector* vec)\r\n\t{\r\n\t\tvec->size = 0;\r\n\t\tvec->data.len = 0;\r\n\t\tvec->data.ptr = NULL;\r\n\t}\r\n\r\n\tint VectorSize(vector* vec)\r\n\t{\r\n\t\treturn vec->size;\r\n\t}\r\n\r\n\tint VectorCapacity(vector* vec)\r\n\t{\r\n\t\treturn vec->data.len;\r\n\t}\r\n\r\n\tNULLCRef VectorNext(vector_iterator* iter)\r\n\t{\r\n\t\tNULLCRef ret;\r\n\t\tret.typeID = (iter->arr->flags ? nullcGetSubType(iter->arr->elemType) : iter->arr->elemType);\r\n\t\tret.ptr = iter->arr->flags ? ((char**)iter->arr->data.ptr)[iter->pos] : iter->arr->data.ptr + iter->arr->elemSize * iter->pos;\r\n\t\titer->pos++;\r\n\t\treturn ret;\r\n\t}\r\n\tint VectorHasNext(vector_iterator* iter)\r\n\t{\r\n\t\treturn iter->arr && iter->pos < iter->arr->size;\r\n\t}\r\n\r\n}\r\n\r\n#define REGISTER_FUNC(funcPtr, name, index) if(!nullcBindModuleFunction(\"old.vector\", (void(*)())NULLCVector::funcPtr, name, index)) return false;\r\nbool\tnullcInitVectorModule()\r\n{\r\n\tREGISTER_FUNC(ConstructVector, \"cConstructVector\", 0);\r\n\r\n\tREGISTER_FUNC(VectorPushBack, \"vector::push_back\", 0);\r\n\tREGISTER_FUNC(VectorPopBack, \"vector::pop_back\", 0);\r\n\tREGISTER_FUNC(VectorFront, \"vector::front\", 0);\r\n\tREGISTER_FUNC(VectorBack, \"vector::back\", 0);\r\n\tREGISTER_FUNC(VectorIndex, \"[]\", 0);\r\n\tREGISTER_FUNC(VectorReserve, \"vector::reserve\", 0);\r\n\tREGISTER_FUNC(VectorResize, \"vector::resize\", 0);\r\n\tREGISTER_FUNC(VectorClear, \"vector::clear\", 0);\r\n\tREGISTER_FUNC(VectorDestroy, \"vector::destroy\", 0);\r\n\tREGISTER_FUNC(VectorSize, \"vector::size\", 0);\r\n\tREGISTER_FUNC(VectorCapacity, \"vector::capacity\", 0);\r\n\r\n\tREGISTER_FUNC(VectorNext, \"vector_iterator::next\", 0);\r\n\tREGISTER_FUNC(VectorHasNext, \"vector_iterator::hasnext\", 0);\r\n\r\n\treturn true;\r\n}\r\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ file : function.hpp\n\/\/ in : file:\/\/\/home\/tim\/projects\/nsched\/nsched\/tools\/function.hpp\n\/\/\n\/\/ created by : Timothée Feuillet on linux.site\n\/\/ date: 17\/07\/2014 11:59:09\n\/\/\n\/\/\n\/\/ Copyright (C) 2014 Timothée Feuillet\n\/\/\n\/\/ This program is free software; you can redistribute it and\/or modify\n\/\/ it under the terms of the GNU General Public License as published by\n\/\/ the Free Software Foundation; either version 2 of the License, or\n\/\/ (at your option) any later version.\n\/\/\n\/\/ This program is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n\/\/ GNU General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU General Public License along\n\/\/ with this program; if not, write to the Free Software Foundation, Inc.,\n\/\/ 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.\n\/\/\n\n\/\/ ATTENTION NOT FINISHED YET !!!\n\n#ifndef __N_2111737739159269973_1204098121__FUNCTION_HPP__\n# define __N_2111737739159269973_1204098121__FUNCTION_HPP__\n\n#include \"ct_list.hpp\"\n#include \"execute_pack.hpp\" \/\/ some magic\n#include \"constructor_call.hpp\"\n#include \"param.hpp\"\n\nnamespace neam\n{\n namespace ct\n {\n template<typename Ptr>\n struct is_function_pointer\n {\n static constexpr bool value = false;\n };\n template<typename Ret, typename... Params>\n struct is_function_pointer<Ret(*)(Params...)>\n {\n static constexpr bool value = true;\n };\n template<typename Ret, typename Class, typename... Params>\n struct is_function_pointer<Ret(Class::*)(Params...)>\n {\n static constexpr bool value = true;\n };\n template<typename Ret, typename... Params>\n struct is_function_pointer<Ret(&)(Params...)>\n {\n static constexpr bool value = true;\n };\n\n \/\/ \/\/\/ \/\/\/\n \/\/ for a ct function wrapper\n \/\/ \/\/\/ \/\/\/\n\n \/\/ the wrappers\n template<typename PtrType, PtrType Ptr, typename... Args> struct function_wrapper {}; \/\/ the one that wrap\n template<typename PtrType, PtrType Ptr, typename... Args> struct _sub_function_wrapper {}; \/\/ the result one\n\n \/\/ for C functions\n template<typename PtrType, PtrType Ptr, typename Return, typename... FuncArgList>\n struct function_wrapper<PtrType, Ptr, Return, type_list<FuncArgList...>>\n {\n template<typename... Types>\n static constexpr _sub_function_wrapper<PtrType, Ptr, Return, type_list<FuncArgList...>, type_list<Types...>> wrap(Types... values)\n {\n return _sub_function_wrapper<PtrType, Ptr, Return, type_list<FuncArgList...>, type_list<Types...>>(values...);\n }\n };\n\n template<typename PtrType, PtrType Ptr, typename Return, typename... FuncArgList, typename... ArgList>\n struct _sub_function_wrapper<PtrType, Ptr, Return, type_list<FuncArgList...>, type_list<ArgList...>>\n {\n static_assert(sizeof...(FuncArgList) == sizeof...(ArgList), \"the number of supplied argument does not match the function's arity\");\n\n\/\/ constexpr _sub_function_wrapper(ArgList... values)\n\/\/ \n\/\/ {\n\/\/ }\n };\n\n \/\/ \/\/\/ \/\/\/\n \/\/ function traits\n \/\/ \/\/\/ \/\/\/\n\n template<typename FunctionType>\n struct function_traits\n {\n static constexpr bool is_function = false;\n };\n template<typename FunctionType>\n constexpr bool function_traits<FunctionType>::is_function;\n\n \/\/ standard function\n template<typename Return, typename... Parameters>\n struct function_traits<Return (Parameters...)>\n {\n static constexpr bool is_function = true;\n static constexpr bool is_member = false;\n using return_type = Return;\n using ptr_type = Return (*)(Parameters...);\n using arg_list = type_list<Parameters...>;\n\n template<ptr_type ptr>\n using create_wrapper = function_wrapper<ptr_type, ptr, Return, \/*Class,*\/ arg_list>;\n };\n template<typename Return, typename... Parameters>\n constexpr bool function_traits<Return (Parameters...)>::is_function;\n template<typename Return, typename... Parameters>\n constexpr bool function_traits<Return (Parameters...)>::is_member;\n\n \/\/ class member function\n template<typename Return, typename Class,typename... Parameters>\n struct function_traits<Return (Class::*)(Parameters...)>\n {\n static constexpr bool is_function = true;\n static constexpr bool is_member = true;\n static constexpr bool is_const = false;\n static constexpr bool is_volatile = false;\n using return_type = Return;\n using class_type = Class;\n using ptr_type = Return (Class::*)(Parameters...);\n using arg_list = type_list<Parameters...>;\n };\n template<typename Return, typename Class, typename... Parameters>\n constexpr bool function_traits<Return (Class::*)(Parameters...)>::is_function;\n template<typename Return, typename Class, typename... Parameters>\n constexpr bool function_traits<Return (Class::*)(Parameters...)>::is_member;\n template<typename Return, typename Class, typename... Parameters>\n constexpr bool function_traits<Return (Class::*)(Parameters...)>::is_const;\n template<typename Return, typename Class, typename... Parameters>\n constexpr bool function_traits<Return (Class::*)(Parameters...)>::is_volatile;\n\n template<typename Return, typename Class, typename... Parameters>\n struct function_traits<Return (Class::*)(Parameters...) const>\n {\n static constexpr bool is_function = true;\n static constexpr bool is_member = true;\n static constexpr bool is_const = true;\n static constexpr bool is_volatile = false;\n using return_type = Return;\n using class_type = Class;\n using ptr_type = Return (Class::*)(Parameters...) const;\n using arg_list = type_list<Parameters...>;\n };\n template<typename Return, typename Class, typename... Parameters>\n constexpr bool function_traits<Return (Class::*)(Parameters...) const>::is_function;\n template<typename Return, typename Class, typename... Parameters>\n constexpr bool function_traits<Return (Class::*)(Parameters...) const>::is_member;\n template<typename Return, typename Class, typename... Parameters>\n constexpr bool function_traits<Return (Class::*)(Parameters...) const>::is_const;\n template<typename Return, typename Class, typename... Parameters>\n constexpr bool function_traits<Return (Class::*)(Parameters...) const>::is_volatile;\n\n template<typename Return, typename Class, typename... Parameters>\n struct function_traits<Return (Class::*)(Parameters...) volatile>\n {\n static constexpr bool is_function = true;\n static constexpr bool is_member = true;\n static constexpr bool is_const = false;\n static constexpr bool is_volatile = true;\n using return_type = Return;\n using class_type = Class;\n using ptr_type = Return (Class::*)(Parameters...) volatile;\n using arg_list = type_list<Parameters...>;\n };\n template<typename Return, typename Class, typename... Parameters>\n constexpr bool function_traits<Return (Class::*)(Parameters...) volatile>::is_function;\n template<typename Return, typename Class, typename... Parameters>\n constexpr bool function_traits<Return (Class::*)(Parameters...) volatile>::is_member;\n template<typename Return, typename Class, typename... Parameters>\n constexpr bool function_traits<Return (Class::*)(Parameters...) volatile>::is_const;\n template<typename Return, typename Class, typename... Parameters>\n constexpr bool function_traits<Return (Class::*)(Parameters...) volatile>::is_volatile;\n\n template<typename Return, typename Class, typename... Parameters>\n struct function_traits<Return (Class::*)(Parameters...) const volatile>\n {\n static constexpr bool is_function = true;\n static constexpr bool is_member = true;\n static constexpr bool is_const = false;\n static constexpr bool is_volatile = true;\n using return_type = Return;\n using class_type = Class;\n using ptr_type = Return (Class::*)(Parameters...) const volatile;\n using arg_list = type_list<Parameters...>;\n };\n template<typename Return, typename Class, typename... Parameters>\n constexpr bool function_traits<Return (Class::*)(Parameters...) const volatile>::is_function;\n template<typename Return, typename Class, typename... Parameters>\n constexpr bool function_traits<Return (Class::*)(Parameters...) const volatile>::is_member;\n template<typename Return, typename Class, typename... Parameters>\n constexpr bool function_traits<Return (Class::*)(Parameters...) const volatile>::is_const;\n template<typename Return, typename Class, typename... Parameters>\n constexpr bool function_traits<Return (Class::*)(Parameters...) const volatile>::is_volatile;\n\n\n \n\n \n } \/\/ namespace ct\n} \/\/ namespace neam\n\n#endif \/*__N_2111737739159269973_1204098121__FUNCTION_HPP__*\/\n\n\/\/ kate: indent-mode cstyle; indent-width 2; replace-tabs on; \n\n<commit_msg>[TOOLS\/TRAITS\/FUNCTION]: fix some issues with function pointers. (it was using signatures instead of pointers)<commit_after>\/\/\n\/\/ file : function.hpp\n\/\/ in : file:\/\/\/home\/tim\/projects\/nsched\/nsched\/tools\/function.hpp\n\/\/\n\/\/ created by : Timothée Feuillet on linux.site\n\/\/ date: 17\/07\/2014 11:59:09\n\/\/\n\/\/\n\/\/ Copyright (C) 2014 Timothée Feuillet\n\/\/\n\/\/ This program is free software; you can redistribute it and\/or modify\n\/\/ it under the terms of the GNU General Public License as published by\n\/\/ the Free Software Foundation; either version 2 of the License, or\n\/\/ (at your option) any later version.\n\/\/\n\/\/ This program is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n\/\/ GNU General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU General Public License along\n\/\/ with this program; if not, write to the Free Software Foundation, Inc.,\n\/\/ 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.\n\/\/\n\n\/\/ ATTENTION NOT FINISHED YET !!!\n\n#ifndef __N_2111737739159269973_1204098121__FUNCTION_HPP__\n# define __N_2111737739159269973_1204098121__FUNCTION_HPP__\n\n#include \"ct_list.hpp\"\n#include \"execute_pack.hpp\" \/\/ some magic\n#include \"constructor_call.hpp\"\n#include \"param.hpp\"\n\nnamespace neam\n{\n namespace ct\n {\n template<typename Ptr>\n struct is_function_pointer\n {\n static constexpr bool value = false;\n };\n template<typename Ret, typename... Params>\n struct is_function_pointer<Ret(*)(Params...)>\n {\n static constexpr bool value = true;\n };\n template<typename Ret, typename Class, typename... Params>\n struct is_function_pointer<Ret(Class::*)(Params...)>\n {\n static constexpr bool value = true;\n };\n template<typename Ret, typename... Params>\n struct is_function_pointer<Ret(&)(Params...)>\n {\n static constexpr bool value = true;\n };\n\n \/\/ \/\/\/ \/\/\/\n \/\/ for a ct function wrapper\n \/\/ \/\/\/ \/\/\/\n\n \/\/ the wrappers\n template<typename PtrType, PtrType Ptr, typename... Args> struct function_wrapper {}; \/\/ the one that wrap\n template<typename PtrType, PtrType Ptr, typename... Args> struct _sub_function_wrapper {}; \/\/ the result one\n\n \/\/ for C functions\n template<typename PtrType, PtrType Ptr, typename Return, typename... FuncArgList>\n struct function_wrapper<PtrType, Ptr, Return, type_list<FuncArgList...>>\n {\n template<typename... Types>\n static constexpr _sub_function_wrapper<PtrType, Ptr, Return, type_list<FuncArgList...>, type_list<Types...>> wrap(Types... values)\n {\n return _sub_function_wrapper<PtrType, Ptr, Return, type_list<FuncArgList...>, type_list<Types...>>(values...);\n }\n };\n\n template<typename PtrType, PtrType Ptr, typename Return, typename... FuncArgList, typename... ArgList>\n struct _sub_function_wrapper<PtrType, Ptr, Return, type_list<FuncArgList...>, type_list<ArgList...>>\n {\n static_assert(sizeof...(FuncArgList) == sizeof...(ArgList), \"the number of supplied argument does not match the function's arity\");\n\n\/\/ constexpr _sub_function_wrapper(ArgList... values)\n\/\/ \n\/\/ {\n\/\/ }\n };\n\n \/\/ \/\/\/ \/\/\/\n \/\/ function traits\n \/\/ \/\/\/ \/\/\/\n\n template<typename FunctionType>\n struct function_traits\n {\n static constexpr bool is_function = false;\n#ifdef IN_IDE_PARSER\n static constexpr bool is_member = false;\n using return_type = void;\n using ptr_type = void; \/\/ not a pointer\n using arg_list = type_list<>;\n#endif\n };\n\n template<typename FunctionType>\n constexpr bool function_traits<FunctionType>::is_function;\n\n \/\/ standard function\n template<typename Return, typename... Parameters>\n struct function_traits<Return(*)(Parameters...)>\n {\n static constexpr bool is_function = true;\n static constexpr bool is_member = false;\n using return_type = Return;\n using ptr_type = Return (*)(Parameters...);\n using arg_list = type_list<Parameters...>;\n\n template<ptr_type ptr>\n using create_wrapper = function_wrapper<ptr_type, ptr, Return, \/*Class,*\/ arg_list>;\n };\n template<typename Return, typename... Parameters>\n constexpr bool function_traits<Return(*)(Parameters...)>::is_function;\n template<typename Return, typename... Parameters>\n constexpr bool function_traits<Return(*)(Parameters...)>::is_member;\n\n \/\/ class member function\n template<typename Return, typename Class,typename... Parameters>\n struct function_traits<Return (Class::*)(Parameters...)>\n {\n static constexpr bool is_function = true;\n static constexpr bool is_member = true;\n static constexpr bool is_const = false;\n static constexpr bool is_volatile = false;\n using return_type = Return;\n using class_type = Class;\n using ptr_type = Return (Class::*)(Parameters...);\n using arg_list = type_list<Parameters...>;\n };\n template<typename Return, typename Class, typename... Parameters>\n constexpr bool function_traits<Return (Class::*)(Parameters...)>::is_function;\n template<typename Return, typename Class, typename... Parameters>\n constexpr bool function_traits<Return (Class::*)(Parameters...)>::is_member;\n template<typename Return, typename Class, typename... Parameters>\n constexpr bool function_traits<Return (Class::*)(Parameters...)>::is_const;\n template<typename Return, typename Class, typename... Parameters>\n constexpr bool function_traits<Return (Class::*)(Parameters...)>::is_volatile;\n\n template<typename Return, typename Class, typename... Parameters>\n struct function_traits<Return (Class::*)(Parameters...) const>\n {\n static constexpr bool is_function = true;\n static constexpr bool is_member = true;\n static constexpr bool is_const = true;\n static constexpr bool is_volatile = false;\n using return_type = Return;\n using class_type = Class;\n using ptr_type = Return (Class::*)(Parameters...) const;\n using arg_list = type_list<Parameters...>;\n };\n template<typename Return, typename Class, typename... Parameters>\n constexpr bool function_traits<Return (Class::*)(Parameters...) const>::is_function;\n template<typename Return, typename Class, typename... Parameters>\n constexpr bool function_traits<Return (Class::*)(Parameters...) const>::is_member;\n template<typename Return, typename Class, typename... Parameters>\n constexpr bool function_traits<Return (Class::*)(Parameters...) const>::is_const;\n template<typename Return, typename Class, typename... Parameters>\n constexpr bool function_traits<Return (Class::*)(Parameters...) const>::is_volatile;\n\n template<typename Return, typename Class, typename... Parameters>\n struct function_traits<Return (Class::*)(Parameters...) volatile>\n {\n static constexpr bool is_function = true;\n static constexpr bool is_member = true;\n static constexpr bool is_const = false;\n static constexpr bool is_volatile = true;\n using return_type = Return;\n using class_type = Class;\n using ptr_type = Return (Class::*)(Parameters...) volatile;\n using arg_list = type_list<Parameters...>;\n };\n template<typename Return, typename Class, typename... Parameters>\n constexpr bool function_traits<Return (Class::*)(Parameters...) volatile>::is_function;\n template<typename Return, typename Class, typename... Parameters>\n constexpr bool function_traits<Return (Class::*)(Parameters...) volatile>::is_member;\n template<typename Return, typename Class, typename... Parameters>\n constexpr bool function_traits<Return (Class::*)(Parameters...) volatile>::is_const;\n template<typename Return, typename Class, typename... Parameters>\n constexpr bool function_traits<Return (Class::*)(Parameters...) volatile>::is_volatile;\n\n template<typename Return, typename Class, typename... Parameters>\n struct function_traits<Return (Class::*)(Parameters...) const volatile>\n {\n static constexpr bool is_function = true;\n static constexpr bool is_member = true;\n static constexpr bool is_const = false;\n static constexpr bool is_volatile = true;\n using return_type = Return;\n using class_type = Class;\n using ptr_type = Return (Class::*)(Parameters...) const volatile;\n using arg_list = type_list<Parameters...>;\n };\n template<typename Return, typename Class, typename... Parameters>\n constexpr bool function_traits<Return (Class::*)(Parameters...) const volatile>::is_function;\n template<typename Return, typename Class, typename... Parameters>\n constexpr bool function_traits<Return (Class::*)(Parameters...) const volatile>::is_member;\n template<typename Return, typename Class, typename... Parameters>\n constexpr bool function_traits<Return (Class::*)(Parameters...) const volatile>::is_const;\n template<typename Return, typename Class, typename... Parameters>\n constexpr bool function_traits<Return (Class::*)(Parameters...) const volatile>::is_volatile;\n\n\n \n\n \n } \/\/ namespace ct\n} \/\/ namespace neam\n\n#endif \/*__N_2111737739159269973_1204098121__FUNCTION_HPP__*\/\n\n\/\/ kate: indent-mode cstyle; indent-width 2; replace-tabs on; \n\n<|endoftext|>"} {"text":"<commit_before>#include \"StdAfx.h\"\r\n#include \"FileReader.h\"\r\n#ifdef __unix__\r\n#include <sys\/types.h>\r\n#include <sys\/stat.h>\r\n#include <unistd.h>\r\n#include <fcntl.h>\r\n\/\/#include <sys\/mman.h>\r\n#endif \/\/ __unix__\r\n\/*\r\n RawSpeed - RAW file decoder.\r\n\r\n Copyright (C) 2009 Klaus Post\r\n\r\n This library is free software; you can redistribute it and\/or\r\n modify it under the terms of the GNU Lesser General Public\r\n License as published by the Free Software Foundation; either\r\n version 2 of the License, or (at your option) any later version.\r\n\r\n This library is distributed in the hope that it will be useful,\r\n but WITHOUT ANY WARRANTY; without even the implied warranty of\r\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\r\n Lesser General Public License for more details.\r\n\r\n You should have received a copy of the GNU Lesser General Public\r\n License along with this library; if not, write to the Free Software\r\n Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\r\n\r\n http:\/\/www.klauspost.com\r\n*\/\r\n\r\nnamespace RawSpeed {\r\n\r\nFileReader::FileReader(LPCWSTR _filename) : mFilename(_filename) {\r\n}\r\n\r\nFileMap* FileReader::readFile() {\r\n#ifdef __unix__\r\n struct stat st;\r\n int bytes_read = 0;\r\n int fd;\r\n char *dest;\r\n\r\n fd = open(mFilename, O_RDONLY);\r\n if (fd < 0)\r\n throw FileIOException(\"Could not open file.\");\r\n if (fstat(fd, &st) < 0)\r\n\tthrow FileIOException(\"Could not read size of file (check permissions)\");\r\n if (st.st_size == 0)\r\n\tthrow FileIOException(\"File is 0 bytes.\");\r\n\r\n#if 0\r\n \/\/ Not used, as it is slower than sync read\r\n\r\n uchar8* pa = (uchar8*)mmap(0, st.st_size, PROT_READ | PROT_WRITE, MAP_PRIVATE, fd, 0);\r\n FileMap *fileData = new FileMap(pa, st.st_size);\r\n\r\n#else\r\n FileMap *fileData = new FileMap(st.st_size);\r\n\r\n while ((st.st_size > 0) && (bytes_read < st.st_size)) {\r\n dest = (char *) fileData->getDataWrt(bytes_read);\r\n bytes_read += read(fd, dest, st.st_size - bytes_read);\r\n }\r\n close(fd);\r\n#endif\r\n\r\n#else \/\/ __unix__\r\n HANDLE file_h; \/\/ File handle\r\n file_h = CreateFile(mFilename, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_FLAG_SEQUENTIAL_SCAN, NULL);\r\n if (file_h == INVALID_HANDLE_VALUE) {\r\n throw FileIOException(\"Could not open file.\");\r\n }\r\n\r\n LARGE_INTEGER f_size;\r\n GetFileSizeEx(file_h , &f_size);\r\n\r\n FileMap *fileData = new FileMap(f_size.LowPart);\r\n\r\n DWORD bytes_read;\r\n if (! ReadFile(file_h, fileData->getDataWrt(0), fileData->getSize(), &bytes_read, NULL)) {\r\n CloseHandle(file_h);\r\n delete fileData;\r\n throw FileIOException(\"Could not read file.\");\r\n }\r\n CloseHandle(file_h);\r\n\r\n#endif \/\/ __unix__\r\n return fileData;\r\n}\r\n\r\nFileReader::~FileReader(void) {\r\n\r\n}\r\n\r\n} \/\/ namespace RawSpeed\r\n<commit_msg>Use another way of determining file size on unix.<commit_after>#include \"StdAfx.h\"\r\n#include \"FileReader.h\"\r\n#ifdef __unix__\r\n#include <sys\/types.h>\r\n#include <sys\/stat.h>\r\n#include <unistd.h>\r\n#include <fcntl.h>\r\n\/\/#include <sys\/mman.h>\r\n#endif \/\/ __unix__\r\n\/*\r\n RawSpeed - RAW file decoder.\r\n\r\n Copyright (C) 2009 Klaus Post\r\n\r\n This library is free software; you can redistribute it and\/or\r\n modify it under the terms of the GNU Lesser General Public\r\n License as published by the Free Software Foundation; either\r\n version 2 of the License, or (at your option) any later version.\r\n\r\n This library is distributed in the hope that it will be useful,\r\n but WITHOUT ANY WARRANTY; without even the implied warranty of\r\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\r\n Lesser General Public License for more details.\r\n\r\n You should have received a copy of the GNU Lesser General Public\r\n License along with this library; if not, write to the Free Software\r\n Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\r\n\r\n http:\/\/www.klauspost.com\r\n*\/\r\n\r\nnamespace RawSpeed {\r\n\r\nFileReader::FileReader(LPCWSTR _filename) : mFilename(_filename) {\r\n}\r\n\r\nFileMap* FileReader::readFile() {\r\n#ifdef __unix__\r\n int bytes_read = 0;\r\n FILE *file;\r\n char *dest;\r\n long size;\r\n\r\n file = fopen(mFilename, \"rb\");\r\n if (file == NULL)\r\n throw FileIOException(\"Could not open file.\");\r\n fseek(file, 0, SEEK_END);\r\n size = ftell(file);\r\n if (size <= 0) {\r\n fclose(file);\r\n throw FileIOException(\"File is 0 bytes.\");\r\n }\r\n fseek(file, 0, SEEK_SET);\r\n\r\n#if 0\r\n \/\/ Not used, as it is slower than sync read\r\n\r\n uchar8* pa = (uchar8*)mmap(0, size, PROT_READ | PROT_WRITE, MAP_PRIVATE, fd, 0);\r\n FileMap *fileData = new FileMap(pa, size);\r\n\r\n#else\r\n FileMap *fileData = new FileMap(size);\r\n\r\n dest = (char *)fileData->getDataWrt(0);\r\n bytes_read = fread(dest, 1, size, file);\r\n fclose(file);\r\n if (size != bytes_read) {\r\n delete fileData;\r\n throw FileIOException(\"Could not read file.\");\r\n }\r\n#endif\r\n\r\n#else \/\/ __unix__\r\n HANDLE file_h; \/\/ File handle\r\n file_h = CreateFile(mFilename, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_FLAG_SEQUENTIAL_SCAN, NULL);\r\n if (file_h == INVALID_HANDLE_VALUE) {\r\n throw FileIOException(\"Could not open file.\");\r\n }\r\n\r\n LARGE_INTEGER f_size;\r\n GetFileSizeEx(file_h , &f_size);\r\n\r\n FileMap *fileData = new FileMap(f_size.LowPart);\r\n\r\n DWORD bytes_read;\r\n if (! ReadFile(file_h, fileData->getDataWrt(0), fileData->getSize(), &bytes_read, NULL)) {\r\n CloseHandle(file_h);\r\n delete fileData;\r\n throw FileIOException(\"Could not read file.\");\r\n }\r\n CloseHandle(file_h);\r\n\r\n#endif \/\/ __unix__\r\n return fileData;\r\n}\r\n\r\nFileReader::~FileReader(void) {\r\n\r\n}\r\n\r\n} \/\/ namespace RawSpeed\r\n<|endoftext|>"} {"text":"<commit_before>#include \"StdAfx.h\"\r\n#include \"PefDecoder.h\"\r\n\/*\r\n RawSpeed - RAW file decoder.\r\n\r\n Copyright (C) 2009 Klaus Post\r\n\r\n This library is free software; you can redistribute it and\/or\r\n modify it under the terms of the GNU Lesser General Public\r\n License as published by the Free Software Foundation; either\r\n version 2 of the License, or (at your option) any later version.\r\n\r\n This library is distributed in the hope that it will be useful,\r\n but WITHOUT ANY WARRANTY; without even the implied warranty of\r\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\r\n Lesser General Public License for more details.\r\n\r\n You should have received a copy of the GNU Lesser General Public\r\n License along with this library; if not, write to the Free Software\r\n Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\r\n\r\n http:\/\/www.klauspost.com\r\n*\/\r\n\r\nnamespace RawSpeed {\r\n\r\nPefDecoder::PefDecoder(TiffIFD *rootIFD, FileMap* file) :\r\n RawDecoder(file), mRootIFD(rootIFD) {\r\n decoderVersion = 2;\r\n}\r\n\r\nPefDecoder::~PefDecoder(void) {\r\n if (mRootIFD)\r\n delete mRootIFD;\r\n mRootIFD = NULL;\r\n}\r\n\r\nRawImage PefDecoder::decodeRawInternal() {\r\n vector<TiffIFD*> data = mRootIFD->getIFDsWithTag(STRIPOFFSETS);\r\n\r\n if (data.empty())\r\n ThrowRDE(\"PEF Decoder: No image data found\");\r\n\r\n TiffIFD* raw = data[0];\r\n\r\n int compression = raw->getEntry(COMPRESSION)->getInt();\r\n\r\n if (1 == compression) {\r\n decodeUncompressed(raw, true);\r\n return mRaw;\r\n }\r\n\r\n if (65535 != compression)\r\n ThrowRDE(\"PEF Decoder: Unsupported compression\");\r\n\r\n TiffEntry *offsets = raw->getEntry(STRIPOFFSETS);\r\n TiffEntry *counts = raw->getEntry(STRIPBYTECOUNTS);\r\n\r\n if (offsets->count != 1) {\r\n ThrowRDE(\"PEF Decoder: Multiple Strips found: %u\", offsets->count);\r\n }\r\n if (counts->count != offsets->count) {\r\n ThrowRDE(\"PEF Decoder: Byte count number does not match strip size: count:%u, strips:%u \", counts->count, offsets->count);\r\n }\r\n if (!mFile->isValid(offsets->getInt() + counts->getInt()))\r\n ThrowRDE(\"PEF Decoder: Truncated file.\");\r\n\r\n uint32 width = raw->getEntry(IMAGEWIDTH)->getInt();\r\n uint32 height = raw->getEntry(IMAGELENGTH)->getInt();\r\n\r\n mRaw->dim = iPoint2D(width, height);\r\n mRaw->createData();\r\n try {\r\n PentaxDecompressor l(mFile, mRaw);\r\n l.decodePentax(mRootIFD, offsets->getInt(), counts->getInt());\r\n } catch (IOException &e) {\r\n mRaw->setError(e.what());\r\n \/\/ Let's ignore it, it may have delivered somewhat useful data.\r\n }\r\n\r\n return mRaw;\r\n}\r\n\r\nvoid PefDecoder::checkSupportInternal(CameraMetaData *meta) {\r\n vector<TiffIFD*> data = mRootIFD->getIFDsWithTag(MODEL);\r\n if (data.empty())\r\n ThrowRDE(\"PEF Support check: Model name found\");\r\n if (!data[0]->hasEntry(MAKE))\r\n ThrowRDE(\"PEF Support: Make name not found\");\r\n\r\n string make = data[0]->getEntry(MAKE)->getString();\r\n string model = data[0]->getEntry(MODEL)->getString();\r\n this->checkCameraSupported(meta, make, model, \"\");\r\n}\r\n\r\nvoid PefDecoder::decodeMetaDataInternal(CameraMetaData *meta) {\r\n int iso = 0;\r\n mRaw->cfa.setCFA(CFA_RED, CFA_GREEN, CFA_GREEN2, CFA_BLUE);\r\n vector<TiffIFD*> data = mRootIFD->getIFDsWithTag(MODEL);\r\n\r\n if (data.empty())\r\n ThrowRDE(\"PEF Meta Decoder: Model name found\");\r\n\r\n TiffIFD* raw = data[0];\r\n\r\n string make = raw->getEntry(MAKE)->getString();\r\n string model = raw->getEntry(MODEL)->getString();\r\n\r\n if (mRootIFD->hasEntryRecursive(ISOSPEEDRATINGS))\r\n iso = mRootIFD->getEntryRecursive(ISOSPEEDRATINGS)->getInt();\r\n\r\n setMetaData(meta, make, model, \"\", iso);\r\n}\r\n\r\n} \/\/ namespace RawSpeed\r\n<commit_msg>Read black level from PEF files. Should affect most Pentax cameras.<commit_after>#include \"StdAfx.h\"\r\n#include \"PefDecoder.h\"\r\n\/*\r\n RawSpeed - RAW file decoder.\r\n\r\n Copyright (C) 2009 Klaus Post\r\n\r\n This library is free software; you can redistribute it and\/or\r\n modify it under the terms of the GNU Lesser General Public\r\n License as published by the Free Software Foundation; either\r\n version 2 of the License, or (at your option) any later version.\r\n\r\n This library is distributed in the hope that it will be useful,\r\n but WITHOUT ANY WARRANTY; without even the implied warranty of\r\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\r\n Lesser General Public License for more details.\r\n\r\n You should have received a copy of the GNU Lesser General Public\r\n License along with this library; if not, write to the Free Software\r\n Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\r\n\r\n http:\/\/www.klauspost.com\r\n*\/\r\n\r\nnamespace RawSpeed {\r\n\r\nPefDecoder::PefDecoder(TiffIFD *rootIFD, FileMap* file) :\r\n RawDecoder(file), mRootIFD(rootIFD) {\r\n decoderVersion = 2;\r\n}\r\n\r\nPefDecoder::~PefDecoder(void) {\r\n if (mRootIFD)\r\n delete mRootIFD;\r\n mRootIFD = NULL;\r\n}\r\n\r\nRawImage PefDecoder::decodeRawInternal() {\r\n vector<TiffIFD*> data = mRootIFD->getIFDsWithTag(STRIPOFFSETS);\r\n\r\n if (data.empty())\r\n ThrowRDE(\"PEF Decoder: No image data found\");\r\n\r\n TiffIFD* raw = data[0];\r\n\r\n int compression = raw->getEntry(COMPRESSION)->getInt();\r\n\r\n if (1 == compression) {\r\n decodeUncompressed(raw, true);\r\n return mRaw;\r\n }\r\n\r\n if (65535 != compression)\r\n ThrowRDE(\"PEF Decoder: Unsupported compression\");\r\n\r\n TiffEntry *offsets = raw->getEntry(STRIPOFFSETS);\r\n TiffEntry *counts = raw->getEntry(STRIPBYTECOUNTS);\r\n\r\n if (offsets->count != 1) {\r\n ThrowRDE(\"PEF Decoder: Multiple Strips found: %u\", offsets->count);\r\n }\r\n if (counts->count != offsets->count) {\r\n ThrowRDE(\"PEF Decoder: Byte count number does not match strip size: count:%u, strips:%u \", counts->count, offsets->count);\r\n }\r\n if (!mFile->isValid(offsets->getInt() + counts->getInt()))\r\n ThrowRDE(\"PEF Decoder: Truncated file.\");\r\n\r\n uint32 width = raw->getEntry(IMAGEWIDTH)->getInt();\r\n uint32 height = raw->getEntry(IMAGELENGTH)->getInt();\r\n\r\n mRaw->dim = iPoint2D(width, height);\r\n mRaw->createData();\r\n try {\r\n PentaxDecompressor l(mFile, mRaw);\r\n l.decodePentax(mRootIFD, offsets->getInt(), counts->getInt());\r\n } catch (IOException &e) {\r\n mRaw->setError(e.what());\r\n \/\/ Let's ignore it, it may have delivered somewhat useful data.\r\n }\r\n\r\n return mRaw;\r\n}\r\n\r\nvoid PefDecoder::checkSupportInternal(CameraMetaData *meta) {\r\n vector<TiffIFD*> data = mRootIFD->getIFDsWithTag(MODEL);\r\n if (data.empty())\r\n ThrowRDE(\"PEF Support check: Model name found\");\r\n if (!data[0]->hasEntry(MAKE))\r\n ThrowRDE(\"PEF Support: Make name not found\");\r\n\r\n string make = data[0]->getEntry(MAKE)->getString();\r\n string model = data[0]->getEntry(MODEL)->getString();\r\n this->checkCameraSupported(meta, make, model, \"\");\r\n}\r\n\r\nvoid PefDecoder::decodeMetaDataInternal(CameraMetaData *meta) {\r\n int iso = 0;\r\n mRaw->cfa.setCFA(CFA_RED, CFA_GREEN, CFA_GREEN2, CFA_BLUE);\r\n vector<TiffIFD*> data = mRootIFD->getIFDsWithTag(MODEL);\r\n\r\n if (data.empty())\r\n ThrowRDE(\"PEF Meta Decoder: Model name found\");\r\n\r\n TiffIFD* raw = data[0];\r\n\r\n string make = raw->getEntry(MAKE)->getString();\r\n string model = raw->getEntry(MODEL)->getString();\r\n\r\n if (mRootIFD->hasEntryRecursive(ISOSPEEDRATINGS))\r\n iso = mRootIFD->getEntryRecursive(ISOSPEEDRATINGS)->getInt();\r\n\r\n setMetaData(meta, make, model, \"\", iso);\r\n\r\n \/\/ Read black level\r\n if (mRootIFD->hasEntryRecursive((TiffTag)0x200)) {\r\n TiffEntry *black = mRootIFD->getEntryRecursive((TiffTag)0x200);\r\n const ushort16 *levels = black->getShortArray();\r\n for (int i = 0; i < 4; i++)\r\n mRaw->blackLevelSeparate[i] = levels[i];\r\n }\r\n}\r\n\r\n} \/\/ namespace RawSpeed\r\n<|endoftext|>"} {"text":"<commit_before>\/*=========================================================================\n\n Program: Visualization Toolkit\n Module: vtkMapper.cxx\n\n Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen\n All rights reserved.\n See Copyright.txt or http:\/\/www.kitware.com\/Copyright.htm for details.\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notice for more information.\n\n=========================================================================*\/\n#include \"vtkMapper.h\"\n\n#include \"vtkDataSet.h\"\n#include \"vtkLookupTable.h\"\n#include \"vtkMath.h\"\n\nvtkCxxRevisionMacro(vtkMapper, \"1.110\");\n\n\/\/ Initialize static member that controls global immediate mode rendering\nstatic int vtkMapperGlobalImmediateModeRendering = 0;\n\n\/\/ Initialize static member that controls global coincidence resolution\nstatic int vtkMapperGlobalResolveCoincidentTopology = VTK_RESOLVE_OFF;\nstatic double vtkMapperGlobalResolveCoincidentTopologyZShift = 0.01;\nstatic double vtkMapperGlobalResolveCoincidentTopologyPolygonOffsetFactor = 1.0;\nstatic double vtkMapperGlobalResolveCoincidentTopologyPolygonOffsetUnits = 1.0;\n\n\/\/ Construct with initial range (0,1).\nvtkMapper::vtkMapper()\n{\n this->Colors = NULL;\n\n this->LookupTable = NULL;\n\n this->ScalarVisibility = 1;\n this->ScalarRange[0] = 0.0; this->ScalarRange[1] = 1.0;\n this->UseLookupTableScalarRange = 0;\n\n this->ImmediateModeRendering = 0;\n\n this->ColorMode = VTK_COLOR_MODE_DEFAULT;\n this->ScalarMode = VTK_SCALAR_MODE_DEFAULT;\n this->ScalarMaterialMode = VTK_MATERIALMODE_DEFAULT;\n \n vtkMath::UninitializeBounds(this->Bounds);\n this->Center[0] = this->Center[1] = this->Center[2] = 0.0;\n \n this->RenderTime = 0.0;\n \n strcpy(this->ArrayName, \"\");\n this->ArrayId = -1;\n this->ArrayComponent = 0;\n this->ArrayAccessMode = VTK_GET_ARRAY_BY_ID;\n}\n\nvtkMapper::~vtkMapper()\n{\n if (this->LookupTable)\n {\n this->LookupTable->UnRegister(this);\n }\n if ( this->Colors != NULL )\n {\n this->Colors->UnRegister(this);\n }\n}\n\n\/\/ Get the bounds for the input of this mapper as \n\/\/ (Xmin,Xmax,Ymin,Ymax,Zmin,Zmax).\ndouble *vtkMapper::GetBounds()\n{\n static double bounds[] = {-1.0,1.0, -1.0,1.0, -1.0,1.0};\n\n if ( ! this->GetInput() ) \n {\n return bounds;\n }\n else\n {\n this->Update();\n this->GetInput()->GetBounds(this->Bounds);\n return this->Bounds;\n }\n}\n\nvtkDataSet *vtkMapper::GetInput()\n{\n if (this->NumberOfInputs < 1)\n {\n return NULL;\n }\n \n return (vtkDataSet *)(this->Inputs[0]);\n}\n\nvoid vtkMapper::SetGlobalImmediateModeRendering(int val)\n{\n if (val == vtkMapperGlobalImmediateModeRendering)\n {\n return;\n }\n vtkMapperGlobalImmediateModeRendering = val;\n}\n\nint vtkMapper::GetGlobalImmediateModeRendering()\n{\n return vtkMapperGlobalImmediateModeRendering;\n}\n\nvoid vtkMapper::SetResolveCoincidentTopology(int val)\n{\n if (val == vtkMapperGlobalResolveCoincidentTopology)\n {\n return;\n }\n vtkMapperGlobalResolveCoincidentTopology = val;\n}\n\nint vtkMapper::GetResolveCoincidentTopology()\n{\n return vtkMapperGlobalResolveCoincidentTopology;\n}\n\nvoid vtkMapper::SetResolveCoincidentTopologyToDefault()\n{\n vtkMapperGlobalResolveCoincidentTopology = VTK_RESOLVE_OFF;\n}\n\nvoid vtkMapper::SetResolveCoincidentTopologyZShift(double val)\n{\n if (val == vtkMapperGlobalResolveCoincidentTopologyZShift)\n {\n return;\n }\n vtkMapperGlobalResolveCoincidentTopologyZShift = val;\n}\n\ndouble vtkMapper::GetResolveCoincidentTopologyZShift()\n{\n return vtkMapperGlobalResolveCoincidentTopologyZShift;\n}\n\nvoid vtkMapper::SetResolveCoincidentTopologyPolygonOffsetParameters(\n double factor, double units)\n{\n if (factor == vtkMapperGlobalResolveCoincidentTopologyPolygonOffsetFactor &&\n units == vtkMapperGlobalResolveCoincidentTopologyPolygonOffsetUnits )\n {\n return;\n }\n vtkMapperGlobalResolveCoincidentTopologyPolygonOffsetFactor = factor;\n vtkMapperGlobalResolveCoincidentTopologyPolygonOffsetUnits = units;\n}\n\nvoid vtkMapper::GetResolveCoincidentTopologyPolygonOffsetParameters(\n double& factor, double& units)\n{\n factor = vtkMapperGlobalResolveCoincidentTopologyPolygonOffsetFactor;\n units = vtkMapperGlobalResolveCoincidentTopologyPolygonOffsetUnits;\n}\n\n\/\/ Overload standard modified time function. If lookup table is modified,\n\/\/ then this object is modified as well.\nunsigned long vtkMapper::GetMTime()\n{\n \/\/unsigned long mTime=this->MTime.GetMTime();\n unsigned long mTime=vtkAbstractMapper::GetMTime();\n unsigned long lutMTime;\n\n if ( this->LookupTable != NULL )\n {\n lutMTime = this->LookupTable->GetMTime();\n mTime = ( lutMTime > mTime ? lutMTime : mTime );\n }\n\n return mTime;\n}\n\nvoid vtkMapper::ShallowCopy(vtkAbstractMapper *mapper)\n{\n vtkMapper *m = vtkMapper::SafeDownCast(mapper);\n if ( m != NULL )\n {\n this->SetLookupTable(m->GetLookupTable());\n this->SetScalarVisibility(m->GetScalarVisibility());\n this->SetScalarRange(m->GetScalarRange());\n this->SetColorMode(m->GetColorMode());\n this->SetScalarMode(m->GetScalarMode());\n this->SetScalarMaterialMode(m->GetScalarMaterialMode());\n this->SetImmediateModeRendering(m->GetImmediateModeRendering());\n this->SetUseLookupTableScalarRange(m->GetUseLookupTableScalarRange());\n if ( m->GetArrayAccessMode() == VTK_GET_ARRAY_BY_ID )\n {\n this->ColorByArrayComponent(m->GetArrayId(),m->GetArrayComponent());\n }\n else\n {\n this->ColorByArrayComponent(m->GetArrayName(),m->GetArrayComponent());\n }\n }\n\n \/\/ Now do superclass\n this->vtkAbstractMapper3D::ShallowCopy(mapper);\n\n}\n\n\/\/ a side effect of this is that this->Colors is also set\n\/\/ to the return value\nvtkUnsignedCharArray *vtkMapper::MapScalars(double alpha)\n{\n \/\/ Lets try to resuse the old colors.\n if (this->ScalarVisibility && this->Colors)\n {\n if (this->LookupTable && this->LookupTable->GetAlpha() == alpha)\n {\n vtkDataArray *scalars = vtkAbstractMapper::\n GetScalars(this->GetInput(), this->ScalarMode, this->ArrayAccessMode,\n this->ArrayId, this->ArrayName, this->ArrayComponent);\n if (this->GetMTime() < this->Colors->GetMTime() &&\n this->GetInput() && \n this->GetInput()->GetMTime() < this->Colors->GetMTime())\n {\n return this->Colors;\n }\n }\n }\n \n \/\/ Get rid of old colors\n if ( this->Colors )\n {\n this->Colors->UnRegister(this);\n this->Colors = NULL;\n }\n \n \/\/ map scalars if necessary\n if ( this->ScalarVisibility )\n {\n vtkDataArray *scalars = vtkAbstractMapper::\n GetScalars(this->GetInput(), this->ScalarMode, this->ArrayAccessMode,\n this->ArrayId, this->ArrayName, this->ArrayComponent);\n if ( scalars )\n {\n if ( scalars->GetLookupTable() )\n {\n this->SetLookupTable(scalars->GetLookupTable());\n }\n else\n {\n \/\/ make sure we have a lookup table\n if ( this->LookupTable == NULL )\n {\n this->CreateDefaultLookupTable();\n }\n this->LookupTable->Build();\n }\n if ( !this->UseLookupTableScalarRange )\n {\n this->LookupTable->SetRange(this->ScalarRange);\n }\n this->LookupTable->SetAlpha(alpha);\n this->Colors = this->LookupTable->\n MapScalars(scalars, this->ColorMode, this->ArrayComponent);\n \/\/ Consistent register and unregisters\n this->Colors->Register(this);\n this->Colors->Delete();\n }\n }\n\n return this->Colors;\n}\n\n\nvoid vtkMapper::SelectColorArray(int arrayNum)\n{\n this->ColorByArrayComponent(arrayNum, -1);\n}\n \n\nvoid vtkMapper::SelectColorArray(const char* arrayName)\n{\n this->ColorByArrayComponent(arrayName, -1);\n}\n\n\nvoid vtkMapper::ColorByArrayComponent(int arrayNum, int component)\n{\n if (this->ArrayId == arrayNum && component == this->ArrayComponent &&\n this->ArrayAccessMode == VTK_GET_ARRAY_BY_ID)\n {\n return;\n }\n this->Modified();\n \n this->ArrayId = arrayNum;\n this->ArrayComponent = component;\n this->ArrayAccessMode = VTK_GET_ARRAY_BY_ID;\n}\n\nvoid vtkMapper::ColorByArrayComponent(const char* arrayName, int component)\n{\n if (!arrayName || \n ( strcmp(this->ArrayName, arrayName) == 0 &&\n component == this->ArrayComponent &&\n this->ArrayAccessMode == VTK_GET_ARRAY_BY_ID ))\n {\n return;\n }\n this->Modified();\n \n strcpy(this->ArrayName, arrayName);\n this->ArrayComponent = component;\n this->ArrayAccessMode = VTK_GET_ARRAY_BY_NAME;\n}\n\n\/\/ Specify a lookup table for the mapper to use.\nvoid vtkMapper::SetLookupTable(vtkScalarsToColors *lut)\n{\n if ( this->LookupTable != lut ) \n {\n if ( this->LookupTable) \n {\n this->LookupTable->UnRegister(this);\n }\n this->LookupTable = lut;\n if (lut)\n {\n lut->Register(this);\n }\n this->Modified();\n }\n}\n\nvtkScalarsToColors *vtkMapper::GetLookupTable()\n{\n if ( this->LookupTable == NULL )\n {\n this->CreateDefaultLookupTable();\n }\n return this->LookupTable;\n}\n\nvoid vtkMapper::CreateDefaultLookupTable()\n{\n if ( this->LookupTable) \n {\n this->LookupTable->UnRegister(this);\n }\n this->LookupTable = vtkLookupTable::New();\n \/\/ Consistent Register\/UnRegisters.\n this->LookupTable->Register(this);\n this->LookupTable->Delete();\n}\n\n\/\/ Update the network connected to this mapper.\nvoid vtkMapper::Update()\n{\n if ( this->GetInput() )\n {\n this->GetInput()->Update();\n }\n}\n\n\/\/ Return the method of coloring scalar data.\nconst char *vtkMapper::GetColorModeAsString(void)\n{\n if ( this->ColorMode == VTK_COLOR_MODE_MAP_SCALARS ) \n {\n return \"MapScalars\";\n }\n else \n {\n return \"Default\";\n }\n}\n\n\/\/ Return the method for obtaining scalar data.\nconst char *vtkMapper::GetScalarModeAsString(void)\n{\n if ( this->ScalarMode == VTK_SCALAR_MODE_USE_CELL_DATA )\n {\n return \"UseCellData\";\n }\n else if ( this->ScalarMode == VTK_SCALAR_MODE_USE_POINT_DATA ) \n {\n return \"UsePointData\";\n }\n else if ( this->ScalarMode == VTK_SCALAR_MODE_USE_POINT_FIELD_DATA )\n {\n return \"UsePointFieldData\";\n }\n else if ( this->ScalarMode == VTK_SCALAR_MODE_USE_CELL_FIELD_DATA )\n {\n return \"UseCellFieldData\";\n }\n else \n {\n return \"Default\";\n }\n}\n\nconst char *vtkMapper::GetScalarMaterialModeAsString(void)\n{\n if ( this->ColorMode == VTK_MATERIALMODE_AMBIENT )\n {\n return \"Ambient\";\n }\n else if ( this->ColorMode == VTK_MATERIALMODE_DIFFUSE )\n {\n return \"Diffuse\";\n }\n else if ( this->ColorMode == VTK_MATERIALMODE_AMBIENT_AND_DIFFUSE )\n {\n return \"Ambient and Diffuse\";\n }\n else\n {\n return \"Default\";\n }\n}\n\nvoid vtkMapper::PrintSelf(ostream& os, vtkIndent indent)\n{\n this->Superclass::PrintSelf(os,indent);\n\n if ( this->LookupTable )\n {\n os << indent << \"Lookup Table:\\n\";\n this->LookupTable->PrintSelf(os,indent.GetNextIndent());\n }\n else\n {\n os << indent << \"Lookup Table: (none)\\n\";\n }\n\n os << indent << \"Immediate Mode Rendering: \" \n << (this->ImmediateModeRendering ? \"On\\n\" : \"Off\\n\");\n os << indent << \"Global Immediate Mode Rendering: \" << \n (vtkMapperGlobalImmediateModeRendering ? \"On\\n\" : \"Off\\n\");\n\n os << indent << \"Scalar Visibility: \" \n << (this->ScalarVisibility ? \"On\\n\" : \"Off\\n\");\n\n double *range = this->GetScalarRange();\n os << indent << \"Scalar Range: (\" << range[0] << \", \" << range[1] << \")\\n\";\n\n os << indent << \"UseLookupTableScalarRange: \" \n << this->UseLookupTableScalarRange << \"\\n\";\n\n os << indent << \"Color Mode: \" << this->GetColorModeAsString() << endl;\n\n os << indent << \"Scalar Mode: \" << this->GetScalarModeAsString() << endl;\n\n os << indent << \"LM Color Mode: \" \n << this->GetScalarMaterialModeAsString() << endl;\n\n os << indent << \"RenderTime: \" << this->RenderTime << endl;\n\n os << indent << \"Resolve Coincident Topology: \";\n if ( vtkMapperGlobalResolveCoincidentTopology == VTK_RESOLVE_OFF )\n {\n os << \"Off\" << endl;\n }\n else if ( vtkMapperGlobalResolveCoincidentTopology == VTK_RESOLVE_POLYGON_OFFSET )\n {\n os << \"Polygon Offset\" << endl;\n }\n else\n {\n os << \"Shift Z-Buffer\" << endl;\n }\n}\n<commit_msg>Fixed warning<commit_after>\/*=========================================================================\n\n Program: Visualization Toolkit\n Module: vtkMapper.cxx\n\n Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen\n All rights reserved.\n See Copyright.txt or http:\/\/www.kitware.com\/Copyright.htm for details.\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notice for more information.\n\n=========================================================================*\/\n#include \"vtkMapper.h\"\n\n#include \"vtkDataSet.h\"\n#include \"vtkLookupTable.h\"\n#include \"vtkMath.h\"\n\nvtkCxxRevisionMacro(vtkMapper, \"1.111\");\n\n\/\/ Initialize static member that controls global immediate mode rendering\nstatic int vtkMapperGlobalImmediateModeRendering = 0;\n\n\/\/ Initialize static member that controls global coincidence resolution\nstatic int vtkMapperGlobalResolveCoincidentTopology = VTK_RESOLVE_OFF;\nstatic double vtkMapperGlobalResolveCoincidentTopologyZShift = 0.01;\nstatic double vtkMapperGlobalResolveCoincidentTopologyPolygonOffsetFactor = 1.0;\nstatic double vtkMapperGlobalResolveCoincidentTopologyPolygonOffsetUnits = 1.0;\n\n\/\/ Construct with initial range (0,1).\nvtkMapper::vtkMapper()\n{\n this->Colors = NULL;\n\n this->LookupTable = NULL;\n\n this->ScalarVisibility = 1;\n this->ScalarRange[0] = 0.0; this->ScalarRange[1] = 1.0;\n this->UseLookupTableScalarRange = 0;\n\n this->ImmediateModeRendering = 0;\n\n this->ColorMode = VTK_COLOR_MODE_DEFAULT;\n this->ScalarMode = VTK_SCALAR_MODE_DEFAULT;\n this->ScalarMaterialMode = VTK_MATERIALMODE_DEFAULT;\n \n vtkMath::UninitializeBounds(this->Bounds);\n this->Center[0] = this->Center[1] = this->Center[2] = 0.0;\n \n this->RenderTime = 0.0;\n \n strcpy(this->ArrayName, \"\");\n this->ArrayId = -1;\n this->ArrayComponent = 0;\n this->ArrayAccessMode = VTK_GET_ARRAY_BY_ID;\n}\n\nvtkMapper::~vtkMapper()\n{\n if (this->LookupTable)\n {\n this->LookupTable->UnRegister(this);\n }\n if ( this->Colors != NULL )\n {\n this->Colors->UnRegister(this);\n }\n}\n\n\/\/ Get the bounds for the input of this mapper as \n\/\/ (Xmin,Xmax,Ymin,Ymax,Zmin,Zmax).\ndouble *vtkMapper::GetBounds()\n{\n static double bounds[] = {-1.0,1.0, -1.0,1.0, -1.0,1.0};\n\n if ( ! this->GetInput() ) \n {\n return bounds;\n }\n else\n {\n this->Update();\n this->GetInput()->GetBounds(this->Bounds);\n return this->Bounds;\n }\n}\n\nvtkDataSet *vtkMapper::GetInput()\n{\n if (this->NumberOfInputs < 1)\n {\n return NULL;\n }\n \n return (vtkDataSet *)(this->Inputs[0]);\n}\n\nvoid vtkMapper::SetGlobalImmediateModeRendering(int val)\n{\n if (val == vtkMapperGlobalImmediateModeRendering)\n {\n return;\n }\n vtkMapperGlobalImmediateModeRendering = val;\n}\n\nint vtkMapper::GetGlobalImmediateModeRendering()\n{\n return vtkMapperGlobalImmediateModeRendering;\n}\n\nvoid vtkMapper::SetResolveCoincidentTopology(int val)\n{\n if (val == vtkMapperGlobalResolveCoincidentTopology)\n {\n return;\n }\n vtkMapperGlobalResolveCoincidentTopology = val;\n}\n\nint vtkMapper::GetResolveCoincidentTopology()\n{\n return vtkMapperGlobalResolveCoincidentTopology;\n}\n\nvoid vtkMapper::SetResolveCoincidentTopologyToDefault()\n{\n vtkMapperGlobalResolveCoincidentTopology = VTK_RESOLVE_OFF;\n}\n\nvoid vtkMapper::SetResolveCoincidentTopologyZShift(double val)\n{\n if (val == vtkMapperGlobalResolveCoincidentTopologyZShift)\n {\n return;\n }\n vtkMapperGlobalResolveCoincidentTopologyZShift = val;\n}\n\ndouble vtkMapper::GetResolveCoincidentTopologyZShift()\n{\n return vtkMapperGlobalResolveCoincidentTopologyZShift;\n}\n\nvoid vtkMapper::SetResolveCoincidentTopologyPolygonOffsetParameters(\n double factor, double units)\n{\n if (factor == vtkMapperGlobalResolveCoincidentTopologyPolygonOffsetFactor &&\n units == vtkMapperGlobalResolveCoincidentTopologyPolygonOffsetUnits )\n {\n return;\n }\n vtkMapperGlobalResolveCoincidentTopologyPolygonOffsetFactor = factor;\n vtkMapperGlobalResolveCoincidentTopologyPolygonOffsetUnits = units;\n}\n\nvoid vtkMapper::GetResolveCoincidentTopologyPolygonOffsetParameters(\n double& factor, double& units)\n{\n factor = vtkMapperGlobalResolveCoincidentTopologyPolygonOffsetFactor;\n units = vtkMapperGlobalResolveCoincidentTopologyPolygonOffsetUnits;\n}\n\n\/\/ Overload standard modified time function. If lookup table is modified,\n\/\/ then this object is modified as well.\nunsigned long vtkMapper::GetMTime()\n{\n \/\/unsigned long mTime=this->MTime.GetMTime();\n unsigned long mTime=vtkAbstractMapper::GetMTime();\n unsigned long lutMTime;\n\n if ( this->LookupTable != NULL )\n {\n lutMTime = this->LookupTable->GetMTime();\n mTime = ( lutMTime > mTime ? lutMTime : mTime );\n }\n\n return mTime;\n}\n\nvoid vtkMapper::ShallowCopy(vtkAbstractMapper *mapper)\n{\n vtkMapper *m = vtkMapper::SafeDownCast(mapper);\n if ( m != NULL )\n {\n this->SetLookupTable(m->GetLookupTable());\n this->SetScalarVisibility(m->GetScalarVisibility());\n this->SetScalarRange(m->GetScalarRange());\n this->SetColorMode(m->GetColorMode());\n this->SetScalarMode(m->GetScalarMode());\n this->SetScalarMaterialMode(m->GetScalarMaterialMode());\n this->SetImmediateModeRendering(m->GetImmediateModeRendering());\n this->SetUseLookupTableScalarRange(m->GetUseLookupTableScalarRange());\n if ( m->GetArrayAccessMode() == VTK_GET_ARRAY_BY_ID )\n {\n this->ColorByArrayComponent(m->GetArrayId(),m->GetArrayComponent());\n }\n else\n {\n this->ColorByArrayComponent(m->GetArrayName(),m->GetArrayComponent());\n }\n }\n\n \/\/ Now do superclass\n this->vtkAbstractMapper3D::ShallowCopy(mapper);\n\n}\n\n\/\/ a side effect of this is that this->Colors is also set\n\/\/ to the return value\nvtkUnsignedCharArray *vtkMapper::MapScalars(double alpha)\n{\n \/\/ Lets try to resuse the old colors.\n if (this->ScalarVisibility && this->Colors)\n {\n if (this->LookupTable && this->LookupTable->GetAlpha() == alpha)\n {\n GetScalars(this->GetInput(), this->ScalarMode, this->ArrayAccessMode,\n this->ArrayId, this->ArrayName, this->ArrayComponent);\n if (this->GetMTime() < this->Colors->GetMTime() &&\n this->GetInput() && \n this->GetInput()->GetMTime() < this->Colors->GetMTime())\n {\n return this->Colors;\n }\n }\n }\n \n \/\/ Get rid of old colors\n if ( this->Colors )\n {\n this->Colors->UnRegister(this);\n this->Colors = NULL;\n }\n \n \/\/ map scalars if necessary\n if ( this->ScalarVisibility )\n {\n vtkDataArray *scalars = vtkAbstractMapper::\n GetScalars(this->GetInput(), this->ScalarMode, this->ArrayAccessMode,\n this->ArrayId, this->ArrayName, this->ArrayComponent);\n if ( scalars )\n {\n if ( scalars->GetLookupTable() )\n {\n this->SetLookupTable(scalars->GetLookupTable());\n }\n else\n {\n \/\/ make sure we have a lookup table\n if ( this->LookupTable == NULL )\n {\n this->CreateDefaultLookupTable();\n }\n this->LookupTable->Build();\n }\n if ( !this->UseLookupTableScalarRange )\n {\n this->LookupTable->SetRange(this->ScalarRange);\n }\n this->LookupTable->SetAlpha(alpha);\n this->Colors = this->LookupTable->\n MapScalars(scalars, this->ColorMode, this->ArrayComponent);\n \/\/ Consistent register and unregisters\n this->Colors->Register(this);\n this->Colors->Delete();\n }\n }\n\n return this->Colors;\n}\n\n\nvoid vtkMapper::SelectColorArray(int arrayNum)\n{\n this->ColorByArrayComponent(arrayNum, -1);\n}\n \n\nvoid vtkMapper::SelectColorArray(const char* arrayName)\n{\n this->ColorByArrayComponent(arrayName, -1);\n}\n\n\nvoid vtkMapper::ColorByArrayComponent(int arrayNum, int component)\n{\n if (this->ArrayId == arrayNum && component == this->ArrayComponent &&\n this->ArrayAccessMode == VTK_GET_ARRAY_BY_ID)\n {\n return;\n }\n this->Modified();\n \n this->ArrayId = arrayNum;\n this->ArrayComponent = component;\n this->ArrayAccessMode = VTK_GET_ARRAY_BY_ID;\n}\n\nvoid vtkMapper::ColorByArrayComponent(const char* arrayName, int component)\n{\n if (!arrayName || \n ( strcmp(this->ArrayName, arrayName) == 0 &&\n component == this->ArrayComponent &&\n this->ArrayAccessMode == VTK_GET_ARRAY_BY_ID ))\n {\n return;\n }\n this->Modified();\n \n strcpy(this->ArrayName, arrayName);\n this->ArrayComponent = component;\n this->ArrayAccessMode = VTK_GET_ARRAY_BY_NAME;\n}\n\n\/\/ Specify a lookup table for the mapper to use.\nvoid vtkMapper::SetLookupTable(vtkScalarsToColors *lut)\n{\n if ( this->LookupTable != lut ) \n {\n if ( this->LookupTable) \n {\n this->LookupTable->UnRegister(this);\n }\n this->LookupTable = lut;\n if (lut)\n {\n lut->Register(this);\n }\n this->Modified();\n }\n}\n\nvtkScalarsToColors *vtkMapper::GetLookupTable()\n{\n if ( this->LookupTable == NULL )\n {\n this->CreateDefaultLookupTable();\n }\n return this->LookupTable;\n}\n\nvoid vtkMapper::CreateDefaultLookupTable()\n{\n if ( this->LookupTable) \n {\n this->LookupTable->UnRegister(this);\n }\n this->LookupTable = vtkLookupTable::New();\n \/\/ Consistent Register\/UnRegisters.\n this->LookupTable->Register(this);\n this->LookupTable->Delete();\n}\n\n\/\/ Update the network connected to this mapper.\nvoid vtkMapper::Update()\n{\n if ( this->GetInput() )\n {\n this->GetInput()->Update();\n }\n}\n\n\/\/ Return the method of coloring scalar data.\nconst char *vtkMapper::GetColorModeAsString(void)\n{\n if ( this->ColorMode == VTK_COLOR_MODE_MAP_SCALARS ) \n {\n return \"MapScalars\";\n }\n else \n {\n return \"Default\";\n }\n}\n\n\/\/ Return the method for obtaining scalar data.\nconst char *vtkMapper::GetScalarModeAsString(void)\n{\n if ( this->ScalarMode == VTK_SCALAR_MODE_USE_CELL_DATA )\n {\n return \"UseCellData\";\n }\n else if ( this->ScalarMode == VTK_SCALAR_MODE_USE_POINT_DATA ) \n {\n return \"UsePointData\";\n }\n else if ( this->ScalarMode == VTK_SCALAR_MODE_USE_POINT_FIELD_DATA )\n {\n return \"UsePointFieldData\";\n }\n else if ( this->ScalarMode == VTK_SCALAR_MODE_USE_CELL_FIELD_DATA )\n {\n return \"UseCellFieldData\";\n }\n else \n {\n return \"Default\";\n }\n}\n\nconst char *vtkMapper::GetScalarMaterialModeAsString(void)\n{\n if ( this->ColorMode == VTK_MATERIALMODE_AMBIENT )\n {\n return \"Ambient\";\n }\n else if ( this->ColorMode == VTK_MATERIALMODE_DIFFUSE )\n {\n return \"Diffuse\";\n }\n else if ( this->ColorMode == VTK_MATERIALMODE_AMBIENT_AND_DIFFUSE )\n {\n return \"Ambient and Diffuse\";\n }\n else\n {\n return \"Default\";\n }\n}\n\nvoid vtkMapper::PrintSelf(ostream& os, vtkIndent indent)\n{\n this->Superclass::PrintSelf(os,indent);\n\n if ( this->LookupTable )\n {\n os << indent << \"Lookup Table:\\n\";\n this->LookupTable->PrintSelf(os,indent.GetNextIndent());\n }\n else\n {\n os << indent << \"Lookup Table: (none)\\n\";\n }\n\n os << indent << \"Immediate Mode Rendering: \" \n << (this->ImmediateModeRendering ? \"On\\n\" : \"Off\\n\");\n os << indent << \"Global Immediate Mode Rendering: \" << \n (vtkMapperGlobalImmediateModeRendering ? \"On\\n\" : \"Off\\n\");\n\n os << indent << \"Scalar Visibility: \" \n << (this->ScalarVisibility ? \"On\\n\" : \"Off\\n\");\n\n double *range = this->GetScalarRange();\n os << indent << \"Scalar Range: (\" << range[0] << \", \" << range[1] << \")\\n\";\n\n os << indent << \"UseLookupTableScalarRange: \" \n << this->UseLookupTableScalarRange << \"\\n\";\n\n os << indent << \"Color Mode: \" << this->GetColorModeAsString() << endl;\n\n os << indent << \"Scalar Mode: \" << this->GetScalarModeAsString() << endl;\n\n os << indent << \"LM Color Mode: \" \n << this->GetScalarMaterialModeAsString() << endl;\n\n os << indent << \"RenderTime: \" << this->RenderTime << endl;\n\n os << indent << \"Resolve Coincident Topology: \";\n if ( vtkMapperGlobalResolveCoincidentTopology == VTK_RESOLVE_OFF )\n {\n os << \"Off\" << endl;\n }\n else if ( vtkMapperGlobalResolveCoincidentTopology == VTK_RESOLVE_POLYGON_OFFSET )\n {\n os << \"Polygon Offset\" << endl;\n }\n else\n {\n os << \"Shift Z-Buffer\" << endl;\n }\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"FilesApi_p.hpp\"\n\n#include \"ApiUtils.hpp\"\n#include \"ClientBackend.hpp\"\n#include \"ClientConnection.hpp\"\n#include \"ClientRpcLayer.hpp\"\n#include \"ConnectionApi_p.hpp\"\n#include \"DataStorage_p.hpp\"\n#include \"Debug_p.hpp\"\n#include \"Operations\/ConnectionOperation.hpp\"\n#include \"Operations\/FileOperation_p.hpp\"\n#include \"RpcLayers\/ClientRpcUploadLayer.hpp\"\n\n#include <QIODevice>\n#include <QLoggingCategory>\n#include <QTimer>\n\nQ_LOGGING_CATEGORY(lcFilesApi, \"telegram.client.api.files\", QtWarningMsg)\n\nnamespace Telegram {\n\nnamespace Client {\n\nFilesApiPrivate::FilesApiPrivate(FilesApi *parent) :\n ClientApiPrivate(parent)\n{\n m_uploadLayer = new UploadRpcLayer(this);\n\n if (lcFilesApi().isDebugEnabled()) {\n m_monitorTimer = new QTimer(this);\n m_monitorTimer->setInterval(5000);\n m_monitorTimer->setSingleShot(false);\n connect(m_monitorTimer, &QTimer::timeout, this, &FilesApiPrivate::dumpCurrentState);\n m_monitorTimer->start();\n }\n}\n\nFilesApiPrivate *FilesApiPrivate::get(FilesApi *parent)\n{\n return reinterpret_cast<FilesApiPrivate*>(parent->d);\n}\n\n\/* Download FileOperation does not fail on network errors.\n * FileOperation fails if:\n * - the file location is not valid. E.g.\n * - if we has no such DC in DC Configuration or\n * - the server returns InvalidLocation or similar error\n *\/\nFileOperation *FilesApiPrivate::downloadFile(const QString &fileId, QIODevice *output)\n{\n const FileInfo::Private info = FileInfo::Private::fromFileId(fileId);\n if (!info.isValid()) {\n return PendingOperation::failOperation<FileOperation>\n (QLatin1String(\"Invalid RemoteFile for getFile()\"), this);\n }\n\n FileInfo *file = new FileInfo();\n FileInfo::Private *filePriv = FileInfo::Private::get(file);\n *filePriv = info;\n\n const FileRequestDescriptor descriptor = FileRequestDescriptor::downloadRequest(info.dcId(), info.getInputFileLocation(), info.size());\n FileOperation *operation = addFileRequest(descriptor, output);\n FileOperationPrivate *privOperation = FileOperationPrivate::get(operation);\n privOperation->m_fileInfo = file;\n return operation;\n}\n\nFileOperation *FilesApiPrivate::downloadFile(const FileInfo *file, QIODevice *output)\n{\n if (!file->isValid()) {\n return PendingOperation::failOperation<FileOperation>\n (QLatin1String(\"Invalid FileInfo for getFile()\"), this);\n }\n\n const FileInfo::Private *filePriv = FileInfo::Private::get(file);\n const FileRequestDescriptor descriptor = FileRequestDescriptor::downloadRequest(filePriv->dcId(), filePriv->getInputFileLocation(), filePriv->size());\n FileOperation *operation = addFileRequest(descriptor, output);\n FileOperationPrivate *privOperation = FileOperationPrivate::get(operation);\n privOperation->m_fileInfo = new FileInfo(*file);\n return operation;\n}\n\nFileOperation *FilesApiPrivate::uploadFile(const QByteArray &fileContent, const QString &fileName)\n{\n return PendingOperation::failOperation<FileOperation>\n (QLatin1String(\"Not implemented\"), this);\n}\n\nFileOperation *FilesApiPrivate::uploadFile(QIODevice *source, const QString &fileName)\n{\n return PendingOperation::failOperation<FileOperation>\n (QLatin1String(\"Not implemented\"), this);\n}\n\nFileOperation *FilesApiPrivate::addFileRequest(const FileRequestDescriptor &descriptor, QIODevice *device)\n{\n if (descriptor.type() == FileRequestDescriptor::Download) {\n qCDebug(lcFilesApi) << __func__ << descriptor.dcId() << descriptor.inputLocation().tlType;\n } else if (descriptor.type() == FileRequestDescriptor::Upload) {\n qCDebug(lcFilesApi) << __func__ << descriptor.dcId() << descriptor.fileId();\n }\n\n if (!descriptor.isValid()) {\n qCDebug(lcFilesApi) << __func__ << \"Invalid descriptor\";\n return PendingOperation::failOperation<FileOperation>\n (QLatin1String(\"Unable to addFileRequest(): Invalid FileRequestDescriptor\"), this);\n }\n\n FileOperation *operation = new FileOperation(this);\n FileOperationPrivate *privOperation = FileOperationPrivate::get(operation);\n privOperation->m_descriptor = descriptor;\n privOperation->ensureDeviceIsSet(device);\n m_fileRequests.enqueue(operation);\n\n if (!m_currentOperation) {\n processNextRequest();\n }\n\n return operation;\n}\n\nvoid FilesApiPrivate::dumpCurrentState() const\n{\n if (m_currentOperation) {\n qCInfo(lcFilesApi) << \"Current operation:\" << m_currentOperation;\n const FileOperationPrivate *privOperation = FileOperationPrivate::get(m_currentOperation);\n qCInfo(lcFilesApi) << \" Child:\" << privOperation->m_childOperation;\n qCInfo(lcFilesApi) << \" Status:\" << privOperation->m_transferStatus;\n } else {\n qCInfo(lcFilesApi) << \"No current operation\";\n }\n if (m_fileRequests.isEmpty()) {\n qCInfo(lcFilesApi) << \"No file requests in queue\";\n } else {\n qCInfo(lcFilesApi) << m_fileRequests.count() << \"requests in queue\";\n }\n}\n\nvoid FilesApiPrivate::processNextRequest()\n{\n if (m_fileRequests.isEmpty()) {\n m_currentOperation = nullptr;\n return;\n }\n\n m_currentOperation = m_fileRequests.dequeue();\n connect(m_currentOperation, &FileOperation::finished,\n this, &FilesApiPrivate::onFileOperationFinished);\n\n qCDebug(lcFilesApi) << __func__ << \"Current operation:\" << m_currentOperation;\n FileOperationPrivate *privOperation = FileOperationPrivate::get(m_currentOperation);\n privOperation->prepareForDownload();\n\n processCurrentRequest();\n}\n\nvoid FilesApiPrivate::processCurrentRequest()\n{\n qCDebug(lcFilesApi) << __func__;\n FileOperationPrivate *privOperation = FileOperationPrivate::get(m_currentOperation);\n ConnectOperation *connectionOperation = ensureConnection(privOperation->dcId());\n privOperation->m_childOperation = connectionOperation;\n\n if (connectionOperation->isFinished()) {\n onConnectOperationFinished(connectionOperation);\n } else {\n connectionOperation->connectToFinished(this, &FilesApiPrivate::onConnectOperationFinished,\n connectionOperation);\n }\n}\n\nbool FilesApiPrivate::isConnectionNeeded(quint32 dcId) const\n{\n if (m_currentOperation) {\n const FileOperationPrivate *privOperation = FileOperationPrivate::get(m_currentOperation);\n if (privOperation->dcId() == dcId) {\n return true;\n }\n }\n\n\/\/ Wanted to parallel operations:\n\/\/ for (const FileOperation *operation : m_fileRequests) {\n\/\/ const FileOperationPrivate *privOperation = FileOperationPrivate::get(operation);\n\/\/ if (privOperation->dcId() == dcId) {\n\/\/ return true;\n\/\/ }\n\/\/ }\n\n return false;\n}\n\nConnectOperation *FilesApiPrivate::ensureConnection(quint32 dcId)\n{\n ConnectionApiPrivate *privConnectionApi = ConnectionApiPrivate::get(backend()->connectionApi());\n const ConnectionSpec spec(dcId, ConnectionSpec::RequestFlag::MediaOnly);\n return privConnectionApi->connectToExtraDc(spec);\n}\n\nvoid FilesApiPrivate::processFileRequestForConnection(FileOperation *operation, Connection *connection)\n{\n FileOperationPrivate *privOperation = FileOperationPrivate::get(operation);\n privOperation->m_transferStatus = FileOperationPrivate::TransferStatus::TransferringBytes;\n const FileRequestDescriptor &descriptor = privOperation->m_descriptor;\n UploadRpcLayer::PendingUploadFile *rpcOperation = nullptr;\n rpcOperation = uploadLayer()->getFile(descriptor.inputLocation(), descriptor.offset(), descriptor.chunkSize());\n qCDebug(lcFilesApi) << __func__ << operation << connection->dcOption().id << rpcOperation;\n privOperation->m_childOperation = rpcOperation;\n connection->rpcLayer()->sendRpc(rpcOperation);\n rpcOperation->connectToFinished(this, &FilesApiPrivate::onGetFileResult, operation, rpcOperation);\n}\n\nvoid FilesApiPrivate::onGetFileResult(FileOperation *operation, UploadRpcLayer::PendingUploadFile *rpcOperation)\n{\n qCDebug(lcFilesApi) << __func__ << operation;\n TLUploadFile result;\n if (rpcOperation->isFailed()) {\n qCDebug(lcFilesApi) << __func__ << \"failed\" << rpcOperation->errorDetails();\n if (rpcOperation->errorDetails().contains(Connection::c_statusKey())) {\n \/\/ The operation failed due to connection lost\n \/\/ Schedule full retry\n if (m_currentOperation == operation) {\n \/\/ We can work only with one queue ATM\n QMetaObject::invokeMethod(this, \"processCurrentRequest\", Qt::QueuedConnection); \/\/ Invoke after return\n return;\n } else {\n qCCritical(lcFilesApi) << __func__ << \"Unprocessed failed operation\" << operation << rpcOperation;\n }\n }\n\n operation->setFinishedWithError(rpcOperation->errorDetails());\n return;\n }\n rpcOperation->getResult(&result);\n\n FileOperationPrivate *privOperation = FileOperationPrivate::get(operation);\n static const QVector<TLValue> badTypes = {\n TLValue::StorageFileUnknown,\n TLValue::StorageFilePartial,\n };\n if (result.type.isValid() && !badTypes.contains(result.type.tlType)) {\n \/\/ has type!\n const QString typeStr = Utils::mimeTypeByStorageFileType(result.type.tlType);\n if (!typeStr.isEmpty()) {\n FileInfo *fileInfo = privOperation->m_fileInfo;\n FileInfo::Private::get(fileInfo)->setMimeType(typeStr);\n }\n }\n operation->device()->write(result.bytes);\n\n FileRequestDescriptor &descriptor = privOperation->m_descriptor;\n const quint32 totalBytesDownloaded = descriptor.offset() + result.bytes.size();\n privOperation->m_totalTransferredBytes = totalBytesDownloaded;\n\n#ifdef DEVELOPER_BUILD\n qCDebug(lcFilesApi).nospace() << operation\n << \" download progress: \"\n << totalBytesDownloaded << '\/' << descriptor.size();\n#endif \/\/ DEVELOPER_BUILD\n\n bool finished = false;\n if (descriptor.size()) {\n if (result.bytes.isEmpty()) {\n static const QString text = QLatin1String(\"Invalid download: zero bytes received\");\n operation->setFinishedWithTextError(text);\n qCWarning(lcFilesApi) << __func__ << text;\n return;\n }\n\n finished = totalBytesDownloaded == descriptor.size();\n } else {\n finished = result.bytes.isEmpty() || (result.bytes.size() % 1024);\n }\n\n if (finished) {\n descriptor.setSize(totalBytesDownloaded);\n }\n\n if (finished) {\n privOperation->m_transferStatus = FileOperationPrivate::TransferStatus::Finished;\n privOperation->finalizeDownload();\n operation->setFinished();\n return;\n }\n\n descriptor.setOffset(totalBytesDownloaded);\n\n Connection *connection = Connection::fromOperation(rpcOperation);\n processFileRequestForConnection(operation, connection);\n}\n\nvoid FilesApiPrivate::onOperationCanceled(PendingOperation *operation)\n{\n \/\/ TODO\n}\n\nvoid FilesApiPrivate::onConnectOperationFinished(ConnectOperation *operation)\n{\n Connection *connection = operation->connection();\n qCDebug(lcFilesApi) << __func__ << operation << operation->errorDetails() << connection;\n\n if (!m_currentOperation) {\n return;\n }\n\n FileOperationPrivate *privOperation = FileOperationPrivate::get(m_currentOperation);\n if (privOperation->m_childOperation != operation) {\n qCWarning(lcFilesApi) << __func__ << \"Unexpected connection operation\" << operation\n << \"for\" << m_currentOperation;\n return;\n }\n\n if (connection->dcOption().id != privOperation->dcId()) {\n qCWarning(lcFilesApi) << \"Invalid operation dcOption\";\n return;\n }\n\n privOperation->m_childOperation = nullptr;\n if (operation->isFailed()) {\n qCDebug(lcFilesApi) << __func__ << m_currentOperation\n << \"failed due to connection\" << operation->errorDetails();\n\n privOperation->m_transferStatus = FileOperationPrivate::TransferStatus::Finished;\n m_currentOperation->setFinishedWithError(operation->errorDetails());\n return;\n }\n\n privOperation->m_transferStatus = FileOperationPrivate::TransferStatus::WaitingForAuthorization;\n\n connect(connection, &Connection::statusChanged, this, &FilesApiPrivate::onConnectionStatusChanged, Qt::UniqueConnection);\n processConnectionStatus(connection);\n}\n\nvoid FilesApiPrivate::onFileOperationFinished(PendingOperation *operation)\n{\n if (operation != m_currentOperation) {\n return;\n }\n m_currentOperation = nullptr;\n processNextRequest();\n}\n\nvoid FilesApiPrivate::onConnectionStatusChanged()\n{\n processConnectionStatus(qobject_cast<Connection *>(sender()));\n}\n\nvoid FilesApiPrivate::processConnectionStatus(Connection *connection)\n{\n if (!connection) {\n \/\/ Invalid call\n return;\n }\n\n if (!m_currentOperation) {\n return;\n }\n\n qCDebug(lcFilesApi) << __func__ << connection << connection->status();\n\n const bool mediaConnection = connection->dcOption().flags & DcOption::MediaOnly;\n if (!mediaConnection) {\n qCDebug(lcFilesApi) << __func__ << \"not media\";\n return;\n }\n quint32 dcId = connection->dcOption().id;\n if (!isConnectionNeeded(dcId)) {\n qCDebug(lcFilesApi) << __func__ << \"dc not needed\";\n return;\n }\n \/\/ DC needed.\n\n switch (connection->status()) {\n case Connection::Status::Signed:\n processFileRequestForConnection(m_currentOperation, connection);\n break;\n case Connection::Status::Disconnected:\n ensureConnection(dcId);\n break;\n default:\n break;\n }\n}\n\n\/*!\n \\class Telegram::Client::FilesApi\n \\brief Provides an API to work download and upload files.\n\n \\inmodule TelegramQt\n \\ingroup Client\n*\/\nFilesApi::FilesApi(QObject *parent) :\n ClientApi(parent)\n{\n d = new FilesApiPrivate(this);\n}\n\nFileOperation *FilesApi::downloadFile(const QString &fileId, QIODevice *output)\n{\n Q_D(FilesApi);\n return d->downloadFile(fileId, output);\n}\n\nFileOperation *FilesApi::downloadFile(const FileInfo *file, QIODevice *output)\n{\n Q_D(FilesApi);\n return d->downloadFile(file, output);\n}\n\nFileOperation *FilesApi::uploadFile(const QByteArray &data, const QString &fileName)\n{\n Q_D(FilesApi);\n return d->uploadFile(data, fileName);\n}\n\nFileOperation *FilesApi::uploadFile(QIODevice *input, const QString &fileName)\n{\n Q_D(FilesApi);\n return d->uploadFile(input, fileName);\n}\n\n} \/\/ Client namespace\n\n} \/\/ Telegram namespace\n<commit_msg>FilesApi: Fix GetFile() for Qt 5.10+<commit_after>#include \"FilesApi_p.hpp\"\n\n#include \"ApiUtils.hpp\"\n#include \"ClientBackend.hpp\"\n#include \"ClientConnection.hpp\"\n#include \"ClientRpcLayer.hpp\"\n#include \"ConnectionApi_p.hpp\"\n#include \"DataStorage_p.hpp\"\n#include \"Debug_p.hpp\"\n#include \"Operations\/ConnectionOperation.hpp\"\n#include \"Operations\/FileOperation_p.hpp\"\n#include \"RpcLayers\/ClientRpcUploadLayer.hpp\"\n\n#include <QIODevice>\n#include <QLoggingCategory>\n#include <QTimer>\n\nQ_LOGGING_CATEGORY(lcFilesApi, \"telegram.client.api.files\", QtWarningMsg)\n\nnamespace Telegram {\n\nnamespace Client {\n\nFilesApiPrivate::FilesApiPrivate(FilesApi *parent) :\n ClientApiPrivate(parent)\n{\n m_uploadLayer = new UploadRpcLayer(this);\n\n if (lcFilesApi().isDebugEnabled()) {\n m_monitorTimer = new QTimer(this);\n m_monitorTimer->setInterval(5000);\n m_monitorTimer->setSingleShot(false);\n connect(m_monitorTimer, &QTimer::timeout, this, &FilesApiPrivate::dumpCurrentState);\n m_monitorTimer->start();\n }\n}\n\nFilesApiPrivate *FilesApiPrivate::get(FilesApi *parent)\n{\n return reinterpret_cast<FilesApiPrivate*>(parent->d);\n}\n\n\/* Download FileOperation does not fail on network errors.\n * FileOperation fails if:\n * - the file location is not valid. E.g.\n * - if we has no such DC in DC Configuration or\n * - the server returns InvalidLocation or similar error\n *\/\nFileOperation *FilesApiPrivate::downloadFile(const QString &fileId, QIODevice *output)\n{\n const FileInfo::Private info = FileInfo::Private::fromFileId(fileId);\n if (!info.isValid()) {\n return PendingOperation::failOperation<FileOperation>\n (QLatin1String(\"Invalid RemoteFile for getFile()\"), this);\n }\n\n FileInfo *file = new FileInfo();\n FileInfo::Private *filePriv = FileInfo::Private::get(file);\n *filePriv = info;\n\n const FileRequestDescriptor descriptor = FileRequestDescriptor::downloadRequest(info.dcId(), info.getInputFileLocation(), info.size());\n FileOperation *operation = addFileRequest(descriptor, output);\n FileOperationPrivate *privOperation = FileOperationPrivate::get(operation);\n privOperation->m_fileInfo = file;\n return operation;\n}\n\nFileOperation *FilesApiPrivate::downloadFile(const FileInfo *file, QIODevice *output)\n{\n if (!file->isValid()) {\n return PendingOperation::failOperation<FileOperation>\n (QLatin1String(\"Invalid FileInfo for getFile()\"), this);\n }\n\n const FileInfo::Private *filePriv = FileInfo::Private::get(file);\n const FileRequestDescriptor descriptor = FileRequestDescriptor::downloadRequest(filePriv->dcId(), filePriv->getInputFileLocation(), filePriv->size());\n FileOperation *operation = addFileRequest(descriptor, output);\n FileOperationPrivate *privOperation = FileOperationPrivate::get(operation);\n privOperation->m_fileInfo = new FileInfo(*file);\n return operation;\n}\n\nFileOperation *FilesApiPrivate::uploadFile(const QByteArray &fileContent, const QString &fileName)\n{\n return PendingOperation::failOperation<FileOperation>\n (QLatin1String(\"Not implemented\"), this);\n}\n\nFileOperation *FilesApiPrivate::uploadFile(QIODevice *source, const QString &fileName)\n{\n return PendingOperation::failOperation<FileOperation>\n (QLatin1String(\"Not implemented\"), this);\n}\n\nFileOperation *FilesApiPrivate::addFileRequest(const FileRequestDescriptor &descriptor, QIODevice *device)\n{\n if (descriptor.type() == FileRequestDescriptor::Download) {\n qCDebug(lcFilesApi) << __func__ << descriptor.dcId() << descriptor.inputLocation().tlType;\n } else if (descriptor.type() == FileRequestDescriptor::Upload) {\n qCDebug(lcFilesApi) << __func__ << descriptor.dcId() << descriptor.fileId();\n }\n\n if (!descriptor.isValid()) {\n qCDebug(lcFilesApi) << __func__ << \"Invalid descriptor\";\n return PendingOperation::failOperation<FileOperation>\n (QLatin1String(\"Unable to addFileRequest(): Invalid FileRequestDescriptor\"), this);\n }\n\n FileOperation *operation = new FileOperation(this);\n FileOperationPrivate *privOperation = FileOperationPrivate::get(operation);\n privOperation->m_descriptor = descriptor;\n privOperation->ensureDeviceIsSet(device);\n m_fileRequests.enqueue(operation);\n\n if (!m_currentOperation) {\n processNextRequest();\n }\n\n return operation;\n}\n\nvoid FilesApiPrivate::dumpCurrentState() const\n{\n if (m_currentOperation) {\n qCInfo(lcFilesApi) << \"Current operation:\" << m_currentOperation;\n const FileOperationPrivate *privOperation = FileOperationPrivate::get(m_currentOperation);\n qCInfo(lcFilesApi) << \" Child:\" << privOperation->m_childOperation;\n qCInfo(lcFilesApi) << \" Status:\" << privOperation->m_transferStatus;\n } else {\n qCInfo(lcFilesApi) << \"No current operation\";\n }\n if (m_fileRequests.isEmpty()) {\n qCInfo(lcFilesApi) << \"No file requests in queue\";\n } else {\n qCInfo(lcFilesApi) << m_fileRequests.count() << \"requests in queue\";\n }\n}\n\nvoid FilesApiPrivate::processNextRequest()\n{\n if (m_fileRequests.isEmpty()) {\n m_currentOperation = nullptr;\n return;\n }\n\n m_currentOperation = m_fileRequests.dequeue();\n connect(m_currentOperation, &FileOperation::finished,\n this, &FilesApiPrivate::onFileOperationFinished);\n\n qCDebug(lcFilesApi) << __func__ << \"Current operation:\" << m_currentOperation;\n FileOperationPrivate *privOperation = FileOperationPrivate::get(m_currentOperation);\n privOperation->prepareForDownload();\n\n processCurrentRequest();\n}\n\nvoid FilesApiPrivate::processCurrentRequest()\n{\n qCDebug(lcFilesApi) << __func__;\n FileOperationPrivate *privOperation = FileOperationPrivate::get(m_currentOperation);\n ConnectOperation *connectionOperation = ensureConnection(privOperation->dcId());\n privOperation->m_childOperation = connectionOperation;\n\n if (connectionOperation->isFinished()) {\n onConnectOperationFinished(connectionOperation);\n } else {\n connectionOperation->connectToFinished(this, &FilesApiPrivate::onConnectOperationFinished,\n connectionOperation);\n }\n}\n\nbool FilesApiPrivate::isConnectionNeeded(quint32 dcId) const\n{\n if (m_currentOperation) {\n const FileOperationPrivate *privOperation = FileOperationPrivate::get(m_currentOperation);\n if (privOperation->dcId() == dcId) {\n return true;\n }\n }\n\n\/\/ Wanted to parallel operations:\n\/\/ for (const FileOperation *operation : m_fileRequests) {\n\/\/ const FileOperationPrivate *privOperation = FileOperationPrivate::get(operation);\n\/\/ if (privOperation->dcId() == dcId) {\n\/\/ return true;\n\/\/ }\n\/\/ }\n\n return false;\n}\n\nConnectOperation *FilesApiPrivate::ensureConnection(quint32 dcId)\n{\n ConnectionApiPrivate *privConnectionApi = ConnectionApiPrivate::get(backend()->connectionApi());\n const ConnectionSpec spec(dcId, ConnectionSpec::RequestFlag::MediaOnly);\n return privConnectionApi->connectToExtraDc(spec);\n}\n\nvoid FilesApiPrivate::processFileRequestForConnection(FileOperation *operation, Connection *connection)\n{\n FileOperationPrivate *privOperation = FileOperationPrivate::get(operation);\n privOperation->m_transferStatus = FileOperationPrivate::TransferStatus::TransferringBytes;\n const FileRequestDescriptor &descriptor = privOperation->m_descriptor;\n UploadRpcLayer::PendingUploadFile *rpcOperation = nullptr;\n rpcOperation = uploadLayer()->getFile(descriptor.inputLocation(), descriptor.offset(), descriptor.chunkSize());\n qCDebug(lcFilesApi) << __func__ << operation << connection->dcOption().id << rpcOperation;\n privOperation->m_childOperation = rpcOperation;\n connection->rpcLayer()->sendRpc(rpcOperation);\n rpcOperation->connectToFinished(this, &FilesApiPrivate::onGetFileResult, operation, rpcOperation);\n}\n\nvoid FilesApiPrivate::onGetFileResult(FileOperation *operation, UploadRpcLayer::PendingUploadFile *rpcOperation)\n{\n qCDebug(lcFilesApi) << __func__ << operation;\n TLUploadFile result;\n if (rpcOperation->isFailed()) {\n qCDebug(lcFilesApi) << __func__ << \"failed\" << rpcOperation->errorDetails();\n if (rpcOperation->errorDetails().contains(Connection::c_statusKey())) {\n \/\/ The operation failed due to connection lost\n \/\/ Schedule full retry\n if (m_currentOperation == operation) {\n \/\/ We can work only with one queue ATM\n \/\/ Invoke after return\n#if QT_VERSION < QT_VERSION_CHECK(5, 10, 0)\n QMetaObject::invokeMethod(this, \"processCurrentRequest\", Qt::QueuedConnection);\n#else\n QMetaObject::invokeMethod(this, &FilesApiPrivate::processCurrentRequest, Qt::QueuedConnection);\n#endif\n return;\n } else {\n qCCritical(lcFilesApi) << __func__ << \"Unprocessed failed operation\" << operation << rpcOperation;\n }\n }\n\n operation->setFinishedWithError(rpcOperation->errorDetails());\n return;\n }\n rpcOperation->getResult(&result);\n\n FileOperationPrivate *privOperation = FileOperationPrivate::get(operation);\n static const QVector<TLValue> badTypes = {\n TLValue::StorageFileUnknown,\n TLValue::StorageFilePartial,\n };\n if (result.type.isValid() && !badTypes.contains(result.type.tlType)) {\n \/\/ has type!\n const QString typeStr = Utils::mimeTypeByStorageFileType(result.type.tlType);\n if (!typeStr.isEmpty()) {\n FileInfo *fileInfo = privOperation->m_fileInfo;\n FileInfo::Private::get(fileInfo)->setMimeType(typeStr);\n }\n }\n operation->device()->write(result.bytes);\n\n FileRequestDescriptor &descriptor = privOperation->m_descriptor;\n const quint32 totalBytesDownloaded = descriptor.offset() + result.bytes.size();\n privOperation->m_totalTransferredBytes = totalBytesDownloaded;\n\n#ifdef DEVELOPER_BUILD\n qCDebug(lcFilesApi).nospace() << operation\n << \" download progress: \"\n << totalBytesDownloaded << '\/' << descriptor.size();\n#endif \/\/ DEVELOPER_BUILD\n\n bool finished = false;\n if (descriptor.size()) {\n if (result.bytes.isEmpty()) {\n static const QString text = QLatin1String(\"Invalid download: zero bytes received\");\n operation->setFinishedWithTextError(text);\n qCWarning(lcFilesApi) << __func__ << text;\n return;\n }\n\n finished = totalBytesDownloaded == descriptor.size();\n } else {\n finished = result.bytes.isEmpty() || (result.bytes.size() % 1024);\n }\n\n if (finished) {\n descriptor.setSize(totalBytesDownloaded);\n }\n\n if (finished) {\n privOperation->m_transferStatus = FileOperationPrivate::TransferStatus::Finished;\n privOperation->finalizeDownload();\n operation->setFinished();\n return;\n }\n\n descriptor.setOffset(totalBytesDownloaded);\n\n Connection *connection = Connection::fromOperation(rpcOperation);\n processFileRequestForConnection(operation, connection);\n}\n\nvoid FilesApiPrivate::onOperationCanceled(PendingOperation *operation)\n{\n \/\/ TODO\n}\n\nvoid FilesApiPrivate::onConnectOperationFinished(ConnectOperation *operation)\n{\n Connection *connection = operation->connection();\n qCDebug(lcFilesApi) << __func__ << operation << operation->errorDetails() << connection;\n\n if (!m_currentOperation) {\n return;\n }\n\n FileOperationPrivate *privOperation = FileOperationPrivate::get(m_currentOperation);\n if (privOperation->m_childOperation != operation) {\n qCWarning(lcFilesApi) << __func__ << \"Unexpected connection operation\" << operation\n << \"for\" << m_currentOperation;\n return;\n }\n\n if (connection->dcOption().id != privOperation->dcId()) {\n qCWarning(lcFilesApi) << \"Invalid operation dcOption\";\n return;\n }\n\n privOperation->m_childOperation = nullptr;\n if (operation->isFailed()) {\n qCDebug(lcFilesApi) << __func__ << m_currentOperation\n << \"failed due to connection\" << operation->errorDetails();\n\n privOperation->m_transferStatus = FileOperationPrivate::TransferStatus::Finished;\n m_currentOperation->setFinishedWithError(operation->errorDetails());\n return;\n }\n\n privOperation->m_transferStatus = FileOperationPrivate::TransferStatus::WaitingForAuthorization;\n\n connect(connection, &Connection::statusChanged, this, &FilesApiPrivate::onConnectionStatusChanged, Qt::UniqueConnection);\n processConnectionStatus(connection);\n}\n\nvoid FilesApiPrivate::onFileOperationFinished(PendingOperation *operation)\n{\n if (operation != m_currentOperation) {\n return;\n }\n m_currentOperation = nullptr;\n processNextRequest();\n}\n\nvoid FilesApiPrivate::onConnectionStatusChanged()\n{\n processConnectionStatus(qobject_cast<Connection *>(sender()));\n}\n\nvoid FilesApiPrivate::processConnectionStatus(Connection *connection)\n{\n if (!connection) {\n \/\/ Invalid call\n return;\n }\n\n if (!m_currentOperation) {\n return;\n }\n\n qCDebug(lcFilesApi) << __func__ << connection << connection->status();\n\n const bool mediaConnection = connection->dcOption().flags & DcOption::MediaOnly;\n if (!mediaConnection) {\n qCDebug(lcFilesApi) << __func__ << \"not media\";\n return;\n }\n quint32 dcId = connection->dcOption().id;\n if (!isConnectionNeeded(dcId)) {\n qCDebug(lcFilesApi) << __func__ << \"dc not needed\";\n return;\n }\n \/\/ DC needed.\n\n switch (connection->status()) {\n case Connection::Status::Signed:\n processFileRequestForConnection(m_currentOperation, connection);\n break;\n case Connection::Status::Disconnected:\n ensureConnection(dcId);\n break;\n default:\n break;\n }\n}\n\n\/*!\n \\class Telegram::Client::FilesApi\n \\brief Provides an API to work download and upload files.\n\n \\inmodule TelegramQt\n \\ingroup Client\n*\/\nFilesApi::FilesApi(QObject *parent) :\n ClientApi(parent)\n{\n d = new FilesApiPrivate(this);\n}\n\nFileOperation *FilesApi::downloadFile(const QString &fileId, QIODevice *output)\n{\n Q_D(FilesApi);\n return d->downloadFile(fileId, output);\n}\n\nFileOperation *FilesApi::downloadFile(const FileInfo *file, QIODevice *output)\n{\n Q_D(FilesApi);\n return d->downloadFile(file, output);\n}\n\nFileOperation *FilesApi::uploadFile(const QByteArray &data, const QString &fileName)\n{\n Q_D(FilesApi);\n return d->uploadFile(data, fileName);\n}\n\nFileOperation *FilesApi::uploadFile(QIODevice *input, const QString &fileName)\n{\n Q_D(FilesApi);\n return d->uploadFile(input, fileName);\n}\n\n} \/\/ Client namespace\n\n} \/\/ Telegram namespace\n<|endoftext|>"} {"text":"<commit_before>\/**\n * This file is part of TelepathyQt4\n *\n * @copyright Copyright (C) 2010 Collabora Ltd. <http:\/\/www.collabora.co.uk\/>\n * @copyright Copyright (C) 2010 Nokia Corporation\n * @license LGPL 2.1\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n *\/\n\n#include <TelepathyQt4\/Object>\n\n#include \"TelepathyQt4\/_gen\/object.moc.hpp\"\n\nnamespace Tp\n{\n\n\/**\n * \\class Object\n * \\ingroup clientobject\n * \\headerfile TelepathyQt4\/object.h <TelepathyQt4\/Object>\n *\n * \\brief The Object class provides an object with property notification.\n *\/\n\n\/**\n * Construct a new Object object.\n *\/\nObject::Object()\n : QObject()\n{\n}\n\n\/**\n * Class destructor.\n *\/\nObject::~Object()\n{\n}\n\n\/**\n * Notify that a property named \\a propertyName changed.\n *\n * This method will emit propertyChanged() for \\a propertyName.\n *\/\nvoid Object::notify(const char *propertyName)\n{\n emit propertyChanged(QLatin1String(propertyName));\n}\n\n} \/\/ Tp\n<commit_msg>Tp::Object: Add \\todo to use for more classes<commit_after>\/**\n * This file is part of TelepathyQt4\n *\n * @copyright Copyright (C) 2010 Collabora Ltd. <http:\/\/www.collabora.co.uk\/>\n * @copyright Copyright (C) 2010 Nokia Corporation\n * @license LGPL 2.1\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n *\/\n\n#include <TelepathyQt4\/Object>\n\n#include \"TelepathyQt4\/_gen\/object.moc.hpp\"\n\nnamespace Tp\n{\n\n\/**\n * \\class Object\n * \\ingroup clientobject\n * \\headerfile TelepathyQt4\/object.h <TelepathyQt4\/Object>\n *\n * \\brief The Object class provides an object with property notification.\n *\n * \\todo Use for more classes beyond Account. Most importantly Contact.\n *\/\n\n\/**\n * Construct a new Object object.\n *\/\nObject::Object()\n : QObject()\n{\n}\n\n\/**\n * Class destructor.\n *\/\nObject::~Object()\n{\n}\n\n\/**\n * Notify that a property named \\a propertyName changed.\n *\n * This method will emit propertyChanged() for \\a propertyName.\n *\/\nvoid Object::notify(const char *propertyName)\n{\n emit propertyChanged(QLatin1String(propertyName));\n}\n\n} \/\/ Tp\n<|endoftext|>"} {"text":"<commit_before>\/\/ -------------------------------------------------------------------------\r\n\/\/ @FileName : NFPluginLoader.cpp\r\n\/\/ @Author : LvSheng.Huang\r\n\/\/ @Date :\r\n\/\/ @Module : NFPluginLoader\r\n\/\/\r\n\/\/ -------------------------------------------------------------------------\r\n\r\n\/\/#include <crtdbg.h>\r\n#include <time.h>\r\n#include <stdio.h>\r\n#include <iostream>\r\n#include <utility>\r\n#include <thread>\r\n#include <chrono>\r\n#include <functional>\r\n#include <atomic>\r\n#include \"NFCActorManager.h\"\r\n#include \"NFComm\/Config\/NFConfig.h\"\r\n#include \"NFComm\/NFPluginModule\/NFPlatform.h\"\r\n#include \"boost\/thread.hpp\"\r\n\r\n#if NF_PLATFORM == NF_PLATFORM_LINUX\r\n#include <netdb.h>\n#include <arpa\/inet.h>\n#include <signal.h>\r\n#endif\r\n\r\n#pragma comment( lib, \"DbgHelp\" )\r\n\r\n#if NF_PLATFORM == NF_PLATFORM_WIN\r\n\r\n\/\/ Dumpļ\r\nvoid CreateDumpFile(const std::string& strDumpFilePathName, EXCEPTION_POINTERS* pException)\r\n{\r\n \/\/ Dumpļ\r\n HANDLE hDumpFile = CreateFile(strDumpFilePathName.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);\r\n\r\n \/\/ DumpϢ\r\n MINIDUMP_EXCEPTION_INFORMATION dumpInfo;\r\n dumpInfo.ExceptionPointers = pException;\r\n dumpInfo.ThreadId = GetCurrentThreadId();\r\n dumpInfo.ClientPointers = TRUE;\r\n\r\n \/\/ дDumpļ\r\n MiniDumpWriteDump(GetCurrentProcess(), GetCurrentProcessId(), hDumpFile, MiniDumpNormal, &dumpInfo, NULL, NULL);\r\n\r\n CloseHandle(hDumpFile);\r\n}\r\n\r\n\/\/ Unhandled ExceptionĻص\r\nlong ApplicationCrashHandler(EXCEPTION_POINTERS* pException)\r\n{\r\n time_t t = time(0);\r\n char szDmupName[MAX_PATH];\r\n tm* ptm = localtime(&t);\r\n\r\n sprintf(szDmupName, \"%d_%d_%d_%d_%d_%d.dmp\", ptm->tm_year + 1900, ptm->tm_mon, ptm->tm_mday, ptm->tm_hour, ptm->tm_min, ptm->tm_sec);\r\n CreateDumpFile(szDmupName, pException);\r\n\r\n FatalAppExit(-1, szDmupName);\r\n\r\n return EXCEPTION_EXECUTE_HANDLER;\r\n}\r\n#endif\r\n\r\nvoid CloseXButton()\r\n{\r\n#if NF_PLATFORM == NF_PLATFORM_WIN\r\n\r\n HWND hWnd = GetConsoleWindow();\r\n if(hWnd)\r\n {\r\n HMENU hMenu = GetSystemMenu(hWnd, FALSE);\r\n EnableMenuItem(hMenu, SC_CLOSE, MF_DISABLED | MF_BYCOMMAND);\r\n }\r\n\r\n#endif\r\n}\r\n\r\nbool bExitApp = false;\r\nboost::thread gThread;\r\n\r\nvoid ThreadFunc()\r\n{\r\n while ( !bExitApp )\r\n {\r\n std::this_thread::sleep_for(std::chrono::milliseconds(1000));\r\n\r\n std::string s;\r\n std::cin >> s;\r\n if ( 0 == stricmp( s.c_str(), \"exit\" ) )\r\n {\r\n bExitApp = true;\r\n }\r\n }\r\n}\r\n\r\nvoid CreateBackThread()\r\n{\r\n gThread = boost::thread(boost::bind(&ThreadFunc));\r\n \/\/std::cout << \"CreateBackThread, thread ID = \" << gThread.get_id() << std::endl;\r\n}\r\n\r\nvoid InitDaemon()\r\n{\r\n#if NF_PLATFORM == NF_PLATFORM_LINUX\r\n\tdaemon(1, 0);\r\n\r\n\t\/\/ ignore signals\r\n\tsignal(SIGINT, SIG_IGN);\r\n\tsignal(SIGHUP, SIG_IGN);\r\n\tsignal(SIGQUIT, SIG_IGN);\r\n\tsignal(SIGPIPE, SIG_IGN);\r\n\tsignal(SIGTTOU, SIG_IGN);\r\n\tsignal(SIGTTIN, SIG_IGN);\r\n\tsignal(SIGTERM, SIG_IGN);\r\n#endif\r\n}\n\r\nvoid PrintfLogo()\r\n{\n#if NF_PLATFORM == NF_PLATFORM_WIN\r\n std::cout << \"\\n\" << std::endl;\r\n\r\n SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_INTENSITY | FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE);\r\n\r\n std::cout << \"\" << std::endl;\r\n std::cout << \" \" << std::endl;\r\n std::cout << \" NoahFrame \" << std::endl;\r\n std::cout << \" Copyright (c) 2011-2015 NFrame Studio \" << std::endl;\r\n std::cout << \" All rights reserved. \" << std::endl;\r\n std::cout << \" \" << std::endl;\r\n std::cout << \"\" << std::endl;\r\n\r\n SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_INTENSITY | FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE);\r\n\r\n std::cout << \"\\n\" << std::endl;\n#endif \/\/ NF_PLATFORM\r\n}\r\n\nunsigned long unStartTickTime = 0;\r\nunsigned long unLastTickTime = 0;\r\n\r\n#if NF_PLATFORM == NF_PLATFORM_WIN || NF_PLATFORM == NF_PLATFORM_LINUX || NF_PLATFORM == NF_PLATFORM_APPLE\r\nint main(int argc, char* argv[])\r\n#elif NF_PLATFORM == NF_PLATFORM_ANDROID || NF_PLATFORM == NF_PLATFORM_APPLE_IOS\r\n\r\n#endif\r\n{\n#if NF_PLATFORM == NF_PLATFORM_WIN\r\n SetUnhandledExceptionFilter((LPTOP_LEVEL_EXCEPTION_FILTER)ApplicationCrashHandler);\r\n#else if NF_PLATFORM == NF_PLATFORM_LINUX\r\n\tbool bDaemon = false;\r\n\r\n\tif (argc > 1)\r\n\t{\r\n\t\tif (0 == NFSTRICMP((const char*)argv[1], \"-d\"))\r\n\t\t{\r\n\t\t\tbDaemon = true;\r\n\t\t}\r\n\t}\r\n\r\n\tif (bDaemon)\r\n\t{\r\n\t\tInitDaemon();\r\n\t}\r\n\r\n\r\n#endif\r\n\tNFCActorManager::GetSingletonPtr()->Init();\r\n\tNFCActorManager::GetSingletonPtr()->AfterInit();\r\n NFCActorManager::GetSingletonPtr()->CheckConfig();\r\n\r\n PrintfLogo();\r\n\r\n CloseXButton();\r\n CreateBackThread();\r\n\r\n unStartTickTime = ::NF_GetTickCount();\r\n unLastTickTime = unStartTickTime;\r\n\r\n while (!bExitApp) \/\/DEBUG汾RELEASE\r\n {\r\n while (true)\r\n {\r\n\t\t\tstd::this_thread::sleep_for(std::chrono::milliseconds(1));\r\n\r\n if (bExitApp)\r\n {\r\n break;\r\n }\r\n\r\n\t\t\tunsigned long unNowTickTime = ::NF_GetTickCount();\r\n\t\t\tfloat fStartedTime = float(unNowTickTime - unStartTickTime) \/ 1000;\r\n\t\t\tfloat fLastTime = float(unNowTickTime - unLastTickTime) \/ 1000;\r\n\r\n\t\t\tif (fStartedTime < 0.001f)\r\n\t\t\t{\r\n\t\t\t\tfStartedTime = 0.0f;\r\n\t\t\t}\r\n\n#if NF_PLATFORM == NF_PLATFORM_WIN\r\n __try\r\n {\n#endif\n NFCActorManager::GetSingletonPtr()->Execute(fLastTime, fStartedTime);\r\n\t\t\t\tunLastTickTime = unNowTickTime;\n#if NF_PLATFORM == NF_PLATFORM_WIN\n }\r\n __except (ApplicationCrashHandler(GetExceptionInformation()))\r\n {\r\n }\n#endif\r\n }\r\n }\r\n\r\n\tNFCActorManager::GetSingletonPtr()->BeforeShut();\r\n\tNFCActorManager::GetSingletonPtr()->Shut();\r\n\r\n NFCActorManager::GetSingletonPtr()->ReleaseInstance();\r\n\r\n return 0;\r\n}\n<commit_msg>fix warning<commit_after>\/\/ -------------------------------------------------------------------------\r\n\/\/ @FileName : NFPluginLoader.cpp\r\n\/\/ @Author : LvSheng.Huang\r\n\/\/ @Date :\r\n\/\/ @Module : NFPluginLoader\r\n\/\/\r\n\/\/ -------------------------------------------------------------------------\r\n\r\n\/\/#include <crtdbg.h>\r\n#include <time.h>\r\n#include <stdio.h>\r\n#include <iostream>\r\n#include <utility>\r\n#include <thread>\r\n#include <chrono>\r\n#include <functional>\r\n#include <atomic>\r\n#include \"NFCActorManager.h\"\r\n#include \"NFComm\/Config\/NFConfig.h\"\r\n#include \"NFComm\/NFPluginModule\/NFPlatform.h\"\r\n#include \"boost\/thread.hpp\"\r\n\r\n#if NF_PLATFORM == NF_PLATFORM_LINUX\r\n#include <netdb.h>\n#include <arpa\/inet.h>\n#include <signal.h>\r\n#endif\r\n\r\n#pragma comment( lib, \"DbgHelp\" )\r\n\r\n#if NF_PLATFORM == NF_PLATFORM_WIN\r\n\r\n\/\/ Dumpļ\r\nvoid CreateDumpFile(const std::string& strDumpFilePathName, EXCEPTION_POINTERS* pException)\r\n{\r\n \/\/ Dumpļ\r\n HANDLE hDumpFile = CreateFile(strDumpFilePathName.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);\r\n\r\n \/\/ DumpϢ\r\n MINIDUMP_EXCEPTION_INFORMATION dumpInfo;\r\n dumpInfo.ExceptionPointers = pException;\r\n dumpInfo.ThreadId = GetCurrentThreadId();\r\n dumpInfo.ClientPointers = TRUE;\r\n\r\n \/\/ дDumpļ\r\n MiniDumpWriteDump(GetCurrentProcess(), GetCurrentProcessId(), hDumpFile, MiniDumpNormal, &dumpInfo, NULL, NULL);\r\n\r\n CloseHandle(hDumpFile);\r\n}\r\n\r\n\/\/ Unhandled ExceptionĻص\r\nlong ApplicationCrashHandler(EXCEPTION_POINTERS* pException)\r\n{\r\n time_t t = time(0);\r\n char szDmupName[MAX_PATH];\r\n tm* ptm = localtime(&t);\r\n\r\n sprintf(szDmupName, \"%d_%d_%d_%d_%d_%d.dmp\", ptm->tm_year + 1900, ptm->tm_mon, ptm->tm_mday, ptm->tm_hour, ptm->tm_min, ptm->tm_sec);\r\n CreateDumpFile(szDmupName, pException);\r\n\r\n FatalAppExit(-1, szDmupName);\r\n\r\n return EXCEPTION_EXECUTE_HANDLER;\r\n}\r\n#endif\r\n\r\nvoid CloseXButton()\r\n{\r\n#if NF_PLATFORM == NF_PLATFORM_WIN\r\n\r\n HWND hWnd = GetConsoleWindow();\r\n if(hWnd)\r\n {\r\n HMENU hMenu = GetSystemMenu(hWnd, FALSE);\r\n EnableMenuItem(hMenu, SC_CLOSE, MF_DISABLED | MF_BYCOMMAND);\r\n }\r\n\r\n#endif\r\n}\r\n\r\nbool bExitApp = false;\r\nboost::thread gThread;\r\n\r\nvoid ThreadFunc()\r\n{\r\n while ( !bExitApp )\r\n {\r\n std::this_thread::sleep_for(std::chrono::milliseconds(1000));\r\n\r\n std::string s;\r\n std::cin >> s;\r\n if ( 0 == stricmp( s.c_str(), \"exit\" ) )\r\n {\r\n bExitApp = true;\r\n }\r\n }\r\n}\r\n\r\nvoid CreateBackThread()\r\n{\r\n gThread = boost::thread(boost::bind(&ThreadFunc));\r\n \/\/std::cout << \"CreateBackThread, thread ID = \" << gThread.get_id() << std::endl;\r\n}\r\n\r\nvoid InitDaemon()\r\n{\r\n#if NF_PLATFORM == NF_PLATFORM_LINUX\r\n\tdaemon(1, 0);\r\n\r\n\t\/\/ ignore signals\r\n\tsignal(SIGINT, SIG_IGN);\r\n\tsignal(SIGHUP, SIG_IGN);\r\n\tsignal(SIGQUIT, SIG_IGN);\r\n\tsignal(SIGPIPE, SIG_IGN);\r\n\tsignal(SIGTTOU, SIG_IGN);\r\n\tsignal(SIGTTIN, SIG_IGN);\r\n\tsignal(SIGTERM, SIG_IGN);\r\n#endif\r\n}\n\r\nvoid PrintfLogo()\r\n{\n#if NF_PLATFORM == NF_PLATFORM_WIN\r\n std::cout << \"\\n\" << std::endl;\r\n\r\n SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_INTENSITY | FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE);\r\n\r\n std::cout << \"\" << std::endl;\r\n std::cout << \" \" << std::endl;\r\n std::cout << \" NoahFrame \" << std::endl;\r\n std::cout << \" Copyright (c) 2011-2015 NFrame Studio \" << std::endl;\r\n std::cout << \" All rights reserved. \" << std::endl;\r\n std::cout << \" \" << std::endl;\r\n std::cout << \"\" << std::endl;\r\n\r\n SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_INTENSITY | FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE);\r\n\r\n std::cout << \"\\n\" << std::endl;\n#endif \/\/ NF_PLATFORM\r\n}\r\n\nunsigned long unStartTickTime = 0;\r\nunsigned long unLastTickTime = 0;\r\n\r\n#if NF_PLATFORM == NF_PLATFORM_WIN || NF_PLATFORM == NF_PLATFORM_LINUX || NF_PLATFORM == NF_PLATFORM_APPLE\r\nint main(int argc, char* argv[])\r\n#elif NF_PLATFORM == NF_PLATFORM_ANDROID || NF_PLATFORM == NF_PLATFORM_APPLE_IOS\r\n\r\n#endif\r\n{\n#if NF_PLATFORM == NF_PLATFORM_WIN\r\n SetUnhandledExceptionFilter((LPTOP_LEVEL_EXCEPTION_FILTER)ApplicationCrashHandler);\r\n#elif NF_PLATFORM == NF_PLATFORM_LINUX\r\n\tbool bDaemon = false;\r\n\r\n\tif (argc > 1)\r\n\t{\r\n\t\tif (0 == NFSTRICMP((const char*)argv[1], \"-d\"))\r\n\t\t{\r\n\t\t\tbDaemon = true;\r\n\t\t}\r\n\t}\r\n\r\n\tif (bDaemon)\r\n\t{\r\n\t\tInitDaemon();\r\n\t}\r\n\r\n\r\n#endif\r\n\tNFCActorManager::GetSingletonPtr()->Init();\r\n\tNFCActorManager::GetSingletonPtr()->AfterInit();\r\n NFCActorManager::GetSingletonPtr()->CheckConfig();\r\n\r\n PrintfLogo();\r\n\r\n CloseXButton();\r\n CreateBackThread();\r\n\r\n unStartTickTime = ::NF_GetTickCount();\r\n unLastTickTime = unStartTickTime;\r\n\r\n while (!bExitApp) \/\/DEBUG汾RELEASE\r\n {\r\n while (true)\r\n {\r\n\t\t\tstd::this_thread::sleep_for(std::chrono::milliseconds(1));\r\n\r\n if (bExitApp)\r\n {\r\n break;\r\n }\r\n\r\n\t\t\tunsigned long unNowTickTime = ::NF_GetTickCount();\r\n\t\t\tfloat fStartedTime = float(unNowTickTime - unStartTickTime) \/ 1000;\r\n\t\t\tfloat fLastTime = float(unNowTickTime - unLastTickTime) \/ 1000;\r\n\r\n\t\t\tif (fStartedTime < 0.001f)\r\n\t\t\t{\r\n\t\t\t\tfStartedTime = 0.0f;\r\n\t\t\t}\r\n\n#if NF_PLATFORM == NF_PLATFORM_WIN\r\n __try\r\n {\n#endif\n NFCActorManager::GetSingletonPtr()->Execute(fLastTime, fStartedTime);\r\n\t\t\t\tunLastTickTime = unNowTickTime;\n#if NF_PLATFORM == NF_PLATFORM_WIN\n }\r\n __except (ApplicationCrashHandler(GetExceptionInformation()))\r\n {\r\n }\n#endif\r\n }\r\n }\r\n\r\n\tNFCActorManager::GetSingletonPtr()->BeforeShut();\r\n\tNFCActorManager::GetSingletonPtr()->Shut();\r\n\r\n NFCActorManager::GetSingletonPtr()->ReleaseInstance();\r\n\r\n return 0;\r\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ -------------------------------------------------------------------------\r\n\/\/ @FileName : NFPluginLoader.cpp\r\n\/\/ @Author : LvSheng.Huang\r\n\/\/ @Date :\r\n\/\/ @Module : NFPluginLoader\r\n\/\/\r\n\/\/ -------------------------------------------------------------------------\r\n\r\n\/\/#include <crtdbg.h>\r\n#include <time.h>\r\n#include <stdio.h>\r\n#include <iostream>\r\n#include <utility>\r\n#include <thread>\r\n#include <chrono>\r\n#include <functional>\r\n#include <atomic>\r\n#include \"NFCActorManager.h\"\r\n#include \"NFComm\/Config\/NFConfig.h\"\r\n#include \"NFComm\/NFPluginModule\/NFPlatform.h\"\r\n\r\n#if NF_PLATFORM == NF_PLATFORM_LINUX\r\n#include <unistd.h>\r\n#include <netdb.h>\r\n#include <arpa\/inet.h>\r\n#include <signal.h>\r\n#endif\r\n\r\n#if NF_PLATFORM == NF_PLATFORM_WIN\r\n\r\n#pragma comment( lib, \"DbgHelp\" )\r\n\/\/ Dumpļ\r\nvoid CreateDumpFile(const std::string& strDumpFilePathName, EXCEPTION_POINTERS* pException)\r\n{\r\n \/\/ Dumpļ\r\n HANDLE hDumpFile = CreateFile(strDumpFilePathName.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);\r\n\r\n \/\/ DumpϢ\r\n MINIDUMP_EXCEPTION_INFORMATION dumpInfo;\r\n dumpInfo.ExceptionPointers = pException;\r\n dumpInfo.ThreadId = GetCurrentThreadId();\r\n dumpInfo.ClientPointers = TRUE;\r\n\r\n \/\/ дDumpļ\r\n MiniDumpWriteDump(GetCurrentProcess(), GetCurrentProcessId(), hDumpFile, MiniDumpNormal, &dumpInfo, NULL, NULL);\r\n\r\n CloseHandle(hDumpFile);\r\n}\r\n\r\n\/\/ Unhandled ExceptionĻص\r\nlong ApplicationCrashHandler(EXCEPTION_POINTERS* pException)\r\n{\r\n time_t t = time(0);\r\n char szDmupName[MAX_PATH];\r\n tm* ptm = localtime(&t);\r\n\r\n sprintf_s(szDmupName, \"%04d_%02d_%02d_%02d_%02d_%02d.dmp\", ptm->tm_year + 1900, ptm->tm_mon + 1, ptm->tm_mday, ptm->tm_hour, ptm->tm_min, ptm->tm_sec);\r\n CreateDumpFile(szDmupName, pException);\r\n\r\n FatalAppExit(-1, szDmupName);\r\n\r\n return EXCEPTION_EXECUTE_HANDLER;\r\n}\r\n#endif\r\n\r\nvoid CloseXButton()\r\n{\r\n#if NF_PLATFORM == NF_PLATFORM_WIN\r\n\r\n HWND hWnd = GetConsoleWindow();\r\n if (hWnd)\r\n {\r\n HMENU hMenu = GetSystemMenu(hWnd, FALSE);\r\n EnableMenuItem(hMenu, SC_CLOSE, MF_DISABLED | MF_BYCOMMAND);\r\n }\r\n\r\n#endif\r\n}\r\n\r\nbool bExitApp = false;\r\nstd::thread gThread;\r\n\r\nvoid ThreadFunc()\r\n{\r\n while (!bExitApp)\r\n {\r\n \/\/std::this_thread::sleep_for(std::chrono::milliseconds(1000));\r\n\r\n \/\/ std::string s;\r\n \/\/ std::cin >> s;\r\n \/\/ if ( 0 == stricmp( s.c_str(), \"exit\" ) )\r\n \/\/ {\r\n \/\/ bExitApp = true;\r\n \/\/ }\r\n }\r\n}\r\n\r\nvoid CreateBackThread()\r\n{\r\n \/\/gThread = std::thread(std::bind(&ThreadFunc));\r\n \/\/auto f = std::async (std::launch::async, std::bind(ThreadFunc));\r\n \/\/std::cout << \"CreateBackThread, thread ID = \" << gThread.get_id() << std::endl;\r\n}\r\n\r\nvoid InitDaemon()\r\n{\r\n#if NF_PLATFORM == NF_PLATFORM_LINUX\r\n daemon(1, 0);\r\n\r\n \/\/ ignore signals\r\n signal(SIGINT, SIG_IGN);\r\n signal(SIGHUP, SIG_IGN);\r\n signal(SIGQUIT, SIG_IGN);\r\n signal(SIGPIPE, SIG_IGN);\r\n signal(SIGTTOU, SIG_IGN);\r\n signal(SIGTTIN, SIG_IGN);\r\n signal(SIGTERM, SIG_IGN);\r\n#endif\r\n}\r\n\r\nvoid PrintfLogo()\r\n{\r\n#if NF_PLATFORM == NF_PLATFORM_WIN\r\n SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_INTENSITY | FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE);\r\n#endif\r\n\r\n std::cout << \"\\n\" << std::endl;\r\n std::cout << \"\" << std::endl;\r\n std::cout << \" \" << std::endl;\r\n std::cout << \" NoahFrame \" << std::endl;\r\n std::cout << \" Copyright (c) 2011-2016 NFrame Studio \" << std::endl;\r\n std::cout << \" All rights reserved. \" << std::endl;\r\n std::cout << \" \" << std::endl;\r\n std::cout << \"\" << std::endl;\r\n std::cout << \"\\n\" << std::endl;\r\n\r\n#if NF_PLATFORM == NF_PLATFORM_WIN\r\n SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_INTENSITY | FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE);\r\n#endif \/\/ NF_PLATFORM\r\n}\r\n\r\n#if NF_PLATFORM == NF_PLATFORM_WIN || NF_PLATFORM == NF_PLATFORM_LINUX || NF_PLATFORM == NF_PLATFORM_APPLE\r\nint main(int argc, char* argv[])\r\n#elif NF_PLATFORM == NF_PLATFORM_ANDROID || NF_PLATFORM == NF_PLATFORM_APPLE_IOS\r\n\r\n#endif\r\n{\r\n#if NF_PLATFORM == NF_PLATFORM_WIN\r\n SetUnhandledExceptionFilter((LPTOP_LEVEL_EXCEPTION_FILTER)ApplicationCrashHandler);\r\n#elif NF_PLATFORM == NF_PLATFORM_LINUX\r\n bool bDaemon = false;\r\n\r\n if (argc > 1)\r\n {\r\n if (0 == NFSTRICMP((const char*)argv[1], \"-d\"))\r\n {\r\n bDaemon = true;\r\n }\r\n }\r\n\r\n if (bDaemon)\r\n {\r\n InitDaemon();\r\n }\r\n\r\n signal(SIGPIPE, SIG_IGN);\r\n signal(SIGCHLD, SIG_IGN);\r\n\r\n#endif\r\n NFCActorManager::GetSingletonPtr()->Init();\r\n NFCActorManager::GetSingletonPtr()->AfterInit();\r\n NFCActorManager::GetSingletonPtr()->CheckConfig();\r\n\r\n PrintfLogo();\r\n\r\n CloseXButton();\r\n CreateBackThread();\r\n\r\n while (!bExitApp) \/\/DEBUG汾RELEASE\r\n {\r\n while (true)\r\n {\r\n std::this_thread::sleep_for(std::chrono::milliseconds(1));\r\n\r\n if (bExitApp)\r\n {\r\n break;\r\n }\r\n\r\n#if NF_PLATFORM == NF_PLATFORM_WIN\r\n __try\r\n {\r\n#endif\r\n NFCActorManager::GetSingletonPtr()->Execute();\r\n#if NF_PLATFORM == NF_PLATFORM_WIN\r\n }\r\n __except (ApplicationCrashHandler(GetExceptionInformation()))\r\n {\r\n }\r\n#endif\r\n }\r\n }\r\n\r\n NFCActorManager::GetSingletonPtr()->BeforeShut();\r\n NFCActorManager::GetSingletonPtr()->Shut();\r\n\r\n NFCActorManager::GetSingletonPtr()->ReleaseInstance();\r\n\r\n return 0;\r\n}\r\n<commit_msg>show the x button when it run in debug mode<commit_after>\/\/ -------------------------------------------------------------------------\r\n\/\/ @FileName : NFPluginLoader.cpp\r\n\/\/ @Author : LvSheng.Huang\r\n\/\/ @Date :\r\n\/\/ @Module : NFPluginLoader\r\n\/\/\r\n\/\/ -------------------------------------------------------------------------\r\n\r\n\/\/#include <crtdbg.h>\r\n#include <time.h>\r\n#include <stdio.h>\r\n#include <iostream>\r\n#include <utility>\r\n#include <thread>\r\n#include <chrono>\r\n#include <functional>\r\n#include <atomic>\r\n#include \"NFCActorManager.h\"\r\n#include \"NFComm\/Config\/NFConfig.h\"\r\n#include \"NFComm\/NFPluginModule\/NFPlatform.h\"\r\n\r\n#if NF_PLATFORM == NF_PLATFORM_LINUX\r\n#include <unistd.h>\r\n#include <netdb.h>\r\n#include <arpa\/inet.h>\r\n#include <signal.h>\r\n#endif\r\n\r\n#if NF_PLATFORM == NF_PLATFORM_WIN\r\n\r\n#pragma comment( lib, \"DbgHelp\" )\r\n\/\/ Dumpļ\r\nvoid CreateDumpFile(const std::string& strDumpFilePathName, EXCEPTION_POINTERS* pException)\r\n{\r\n \/\/ Dumpļ\r\n HANDLE hDumpFile = CreateFile(strDumpFilePathName.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);\r\n\r\n \/\/ DumpϢ\r\n MINIDUMP_EXCEPTION_INFORMATION dumpInfo;\r\n dumpInfo.ExceptionPointers = pException;\r\n dumpInfo.ThreadId = GetCurrentThreadId();\r\n dumpInfo.ClientPointers = TRUE;\r\n\r\n \/\/ дDumpļ\r\n MiniDumpWriteDump(GetCurrentProcess(), GetCurrentProcessId(), hDumpFile, MiniDumpNormal, &dumpInfo, NULL, NULL);\r\n\r\n CloseHandle(hDumpFile);\r\n}\r\n\r\n\/\/ Unhandled ExceptionĻص\r\nlong ApplicationCrashHandler(EXCEPTION_POINTERS* pException)\r\n{\r\n time_t t = time(0);\r\n char szDmupName[MAX_PATH];\r\n tm* ptm = localtime(&t);\r\n\r\n sprintf_s(szDmupName, \"%04d_%02d_%02d_%02d_%02d_%02d.dmp\", ptm->tm_year + 1900, ptm->tm_mon + 1, ptm->tm_mday, ptm->tm_hour, ptm->tm_min, ptm->tm_sec);\r\n CreateDumpFile(szDmupName, pException);\r\n\r\n FatalAppExit(-1, szDmupName);\r\n\r\n return EXCEPTION_EXECUTE_HANDLER;\r\n}\r\n#endif\r\n\r\nvoid CloseXButton()\r\n{\r\n#if defined(NF_DEBUG_MODE)\r\n#if NF_PLATFORM == NF_PLATFORM_WIN\r\n\tHWND hWnd = GetConsoleWindow();\r\n\tif (hWnd)\r\n\t{\r\n\t\tHMENU hMenu = GetSystemMenu(hWnd, FALSE);\r\n\t\tEnableMenuItem(hMenu, SC_CLOSE, MF_DISABLED | MF_BYCOMMAND);\r\n\t}\r\n#endif\r\n#endif\r\n}\r\n\r\nbool bExitApp = false;\r\nstd::thread gThread;\r\n\r\nvoid ThreadFunc()\r\n{\r\n while (!bExitApp)\r\n {\r\n \/\/std::this_thread::sleep_for(std::chrono::milliseconds(1000));\r\n\r\n \/\/ std::string s;\r\n \/\/ std::cin >> s;\r\n \/\/ if ( 0 == stricmp( s.c_str(), \"exit\" ) )\r\n \/\/ {\r\n \/\/ bExitApp = true;\r\n \/\/ }\r\n }\r\n}\r\n\r\nvoid CreateBackThread()\r\n{\r\n \/\/gThread = std::thread(std::bind(&ThreadFunc));\r\n \/\/auto f = std::async (std::launch::async, std::bind(ThreadFunc));\r\n \/\/std::cout << \"CreateBackThread, thread ID = \" << gThread.get_id() << std::endl;\r\n}\r\n\r\nvoid InitDaemon()\r\n{\r\n#if NF_PLATFORM == NF_PLATFORM_LINUX\r\n daemon(1, 0);\r\n\r\n \/\/ ignore signals\r\n signal(SIGINT, SIG_IGN);\r\n signal(SIGHUP, SIG_IGN);\r\n signal(SIGQUIT, SIG_IGN);\r\n signal(SIGPIPE, SIG_IGN);\r\n signal(SIGTTOU, SIG_IGN);\r\n signal(SIGTTIN, SIG_IGN);\r\n signal(SIGTERM, SIG_IGN);\r\n#endif\r\n}\r\n\r\nvoid PrintfLogo()\r\n{\r\n#if NF_PLATFORM == NF_PLATFORM_WIN\r\n SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_INTENSITY | FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE);\r\n#endif\r\n\r\n std::cout << \"\\n\" << std::endl;\r\n std::cout << \"\" << std::endl;\r\n std::cout << \" \" << std::endl;\r\n std::cout << \" NoahFrame \" << std::endl;\r\n std::cout << \" Copyright (c) 2011-2016 NFrame Studio \" << std::endl;\r\n std::cout << \" All rights reserved. \" << std::endl;\r\n std::cout << \" \" << std::endl;\r\n std::cout << \"\" << std::endl;\r\n std::cout << \"\\n\" << std::endl;\r\n\r\n#if NF_PLATFORM == NF_PLATFORM_WIN\r\n SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_INTENSITY | FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE);\r\n#endif \/\/ NF_PLATFORM\r\n}\r\n\r\n#if NF_PLATFORM == NF_PLATFORM_WIN || NF_PLATFORM == NF_PLATFORM_LINUX || NF_PLATFORM == NF_PLATFORM_APPLE\r\nint main(int argc, char* argv[])\r\n#elif NF_PLATFORM == NF_PLATFORM_ANDROID || NF_PLATFORM == NF_PLATFORM_APPLE_IOS\r\n\r\n#endif\r\n{\r\n#if NF_PLATFORM == NF_PLATFORM_WIN\r\n SetUnhandledExceptionFilter((LPTOP_LEVEL_EXCEPTION_FILTER)ApplicationCrashHandler);\r\n#elif NF_PLATFORM == NF_PLATFORM_LINUX\r\n bool bDaemon = false;\r\n\r\n if (argc > 1)\r\n {\r\n if (0 == NFSTRICMP((const char*)argv[1], \"-d\"))\r\n {\r\n bDaemon = true;\r\n }\r\n }\r\n\r\n if (bDaemon)\r\n {\r\n InitDaemon();\r\n }\r\n\r\n signal(SIGPIPE, SIG_IGN);\r\n signal(SIGCHLD, SIG_IGN);\r\n\r\n#endif\r\n NFCActorManager::GetSingletonPtr()->Init();\r\n NFCActorManager::GetSingletonPtr()->AfterInit();\r\n NFCActorManager::GetSingletonPtr()->CheckConfig();\r\n\r\n PrintfLogo();\r\n\r\n CloseXButton();\r\n CreateBackThread();\r\n\r\n while (!bExitApp) \/\/DEBUG汾RELEASE\r\n {\r\n while (true)\r\n {\r\n std::this_thread::sleep_for(std::chrono::milliseconds(1));\r\n\r\n if (bExitApp)\r\n {\r\n break;\r\n }\r\n\r\n#if NF_PLATFORM == NF_PLATFORM_WIN\r\n __try\r\n {\r\n#endif\r\n NFCActorManager::GetSingletonPtr()->Execute();\r\n#if NF_PLATFORM == NF_PLATFORM_WIN\r\n }\r\n __except (ApplicationCrashHandler(GetExceptionInformation()))\r\n {\r\n }\r\n#endif\r\n }\r\n }\r\n\r\n NFCActorManager::GetSingletonPtr()->BeforeShut();\r\n NFCActorManager::GetSingletonPtr()->Shut();\r\n\r\n NFCActorManager::GetSingletonPtr()->ReleaseInstance();\r\n\r\n return 0;\r\n}\r\n<|endoftext|>"} {"text":"<commit_before>\/\/ -------------------------------------------------------------------------\n\/\/ @FileName\t\t\t: NFCChatModule.h\n\/\/ @Author : LvSheng.Huang\n\/\/ @Date : 2016-12-18\n\/\/ @Module : NFCChatModule\n\/\/ @Desc :\n\n#include \"NFCChatModule.h\"\n#include \"NFComm\/NFMessageDefine\/NFProtocolDefine.hpp\"\n#include \"NFComm\/NFPluginModule\/NFIEventModule.h\"\n\nbool NFCChatModule::Init()\n{\n\treturn true;\n}\n\nbool NFCChatModule::AfterInit()\n{\n\tm_pKernelModule = pPluginManager->FindModule<NFIKernelModule>();\n\tm_pClassModule = pPluginManager->FindModule<NFIClassModule>();\n\tm_pElementModule = pPluginManager->FindModule<NFIElementModule>();\n\tm_pLogModule = pPluginManager->FindModule<NFILogModule>();\n\tm_pEventModule = pPluginManager->FindModule<NFIEventModule>();\n\tm_pSceneAOIModule = pPluginManager->FindModule<NFISceneAOIModule>();\n\tm_pGameServerNet_ServerModule = pPluginManager->FindModule<NFIGameServerNet_ServerModule>();\n m_pNetClientModule = pPluginManager->FindModule<NFIGameServerToWorldModule>();\n\n\tm_pNetModule->AddReceiveCallBack(NFMsg::EGMI_REQ_CHAT, this, &NFCChatModule::OnClienChatProcess);\n\n\treturn true;\n}\n\nbool NFCChatModule::Shut()\n{\n\n\treturn true;\n}\n\nbool NFCChatModule::Execute()\n{\n\treturn true;\n}\n\nvoid NFCChatModule::OnClienChatProcess(const int nSockIndex, const int nMsgID, const char* msg, const uint32_t nLen)\n{\n\tCLIENT_MSG_PROCESS(nSockIndex, nMsgID, msg, nLen, NFMsg::ReqAckPlayerChat);\n\n\tswitch (xMsg.chat_type())\n\t{\n\tcase NFMsg::ReqAckPlayerChat_EGameChatType::ReqAckPlayerChat_EGameChatType_EGCT_WORLD:\n\t{\n\t\tm_pNetModule->SendMsgPBToAllClient(NFMsg::EGMI_ACK_CHAT, xMsg);\n\t}\n\tbreak;\n\tcase NFMsg::ReqAckPlayerChat_EGameChatType::ReqAckPlayerChat_EGameChatType_EGCT_GUILD:\n\t{\n\t\tNFGUID xGuildID = m_pKernelModule->GetPropertyObject(nPlayerID, NFrame::Player::GuildID());\n\t\tif (!xGuildID.IsNull())\n\t\t{\n\t\t}\n\t}\n\tbreak;\n\tcase NFMsg::ReqAckPlayerChat_EGameChatType::ReqAckPlayerChat_EGameChatType_EGCT_PRIVATE:\n\tcase NFMsg::ReqAckPlayerChat_EGameChatType::ReqAckPlayerChat_EGameChatType_EGCT_TEAM:\n\t{\n\t\tif (xMsg.has_target_id())\n\t\t{\n\t\t\tNFGUID xTargetID = NFINetModule::PBToNF(xMsg.target_id());\n\t\t\tif (!xTargetID.IsNull())\n\t\t\t{\n\t\t\t}\n\t\t}\n\t}\n\tbreak;\n\tdefault:\n\t\tbreak;;\n\t}\n}<commit_msg>fixed crash problem when you forget to get the net module<commit_after>\/\/ -------------------------------------------------------------------------\n\/\/ @FileName\t\t\t: NFCChatModule.h\n\/\/ @Author : LvSheng.Huang\n\/\/ @Date : 2016-12-18\n\/\/ @Module : NFCChatModule\n\/\/ @Desc :\n\/\/ -------------------------------------------------------------------------\n\n#include \"NFCChatModule.h\"\n#include \"NFComm\/NFMessageDefine\/NFProtocolDefine.hpp\"\n#include \"NFComm\/NFPluginModule\/NFIEventModule.h\"\n\nbool NFCChatModule::Init()\n{\n\tm_pNetModule = pPluginManager->FindModule<NFINetModule>();\n\tm_pKernelModule = pPluginManager->FindModule<NFIKernelModule>();\n\tm_pClassModule = pPluginManager->FindModule<NFIClassModule>();\n\tm_pElementModule = pPluginManager->FindModule<NFIElementModule>();\n\tm_pLogModule = pPluginManager->FindModule<NFILogModule>();\n\tm_pEventModule = pPluginManager->FindModule<NFIEventModule>();\n\tm_pSceneAOIModule = pPluginManager->FindModule<NFISceneAOIModule>();\n\tm_pGameServerNet_ServerModule = pPluginManager->FindModule<NFIGameServerNet_ServerModule>();\n\tm_pNetClientModule = pPluginManager->FindModule<NFIGameServerToWorldModule>();\n\n\treturn true;\n}\n\nbool NFCChatModule::AfterInit()\n{\n\tm_pNetModule->AddReceiveCallBack(NFMsg::EGMI_REQ_CHAT, this, &NFCChatModule::OnClienChatProcess);\n\n\treturn true;\n}\n\nbool NFCChatModule::Shut()\n{\n\n\treturn true;\n}\n\nbool NFCChatModule::Execute()\n{\n\treturn true;\n}\n\nvoid NFCChatModule::OnClienChatProcess(const int nSockIndex, const int nMsgID, const char* msg, const uint32_t nLen)\n{\n\tCLIENT_MSG_PROCESS(nSockIndex, nMsgID, msg, nLen, NFMsg::ReqAckPlayerChat);\n\n\tswitch (xMsg.chat_type())\n\t{\n\tcase NFMsg::ReqAckPlayerChat_EGameChatType::ReqAckPlayerChat_EGameChatType_EGCT_WORLD:\n\t{\n\t\tm_pNetModule->SendMsgPBToAllClient(NFMsg::EGMI_ACK_CHAT, xMsg);\n\t}\n\tbreak;\n\tcase NFMsg::ReqAckPlayerChat_EGameChatType::ReqAckPlayerChat_EGameChatType_EGCT_GUILD:\n\t{\n\t\tNFGUID xGuildID = m_pKernelModule->GetPropertyObject(nPlayerID, NFrame::Player::GuildID());\n\t\tif (!xGuildID.IsNull())\n\t\t{\n\t\t}\n\t}\n\tbreak;\n\tcase NFMsg::ReqAckPlayerChat_EGameChatType::ReqAckPlayerChat_EGameChatType_EGCT_PRIVATE:\n\tcase NFMsg::ReqAckPlayerChat_EGameChatType::ReqAckPlayerChat_EGameChatType_EGCT_TEAM:\n\t{\n\t\tif (xMsg.has_target_id())\n\t\t{\n\t\t\tNFGUID xTargetID = NFINetModule::PBToNF(xMsg.target_id());\n\t\t\tif (!xTargetID.IsNull())\n\t\t\t{\n\t\t\t}\n\t\t}\n\t}\n\tbreak;\n\tdefault:\n\t\tbreak;;\n\t}\n}<|endoftext|>"} {"text":"<commit_before>#include <QtCore>\n#include <QtNetwork>\n#include <obs.h>\n#include \"nicolive.h\"\n\n\/\/ class NicoLive\nclass NicoLive : public QObject\n{\n\t\/\/ Q_OBJECT\npublic:\n\tstatic const QUrl LOGIN_URL;\n\tstatic const QUrl MYLIVE_URL;\n\tstatic const QString FMEPROF_URL_PRE;\nprivate:\n\tQString session;\n\tQString mail;\n\tQString password;\n\tQString live_id;\n\tQString live_url;\n\tQString live_key;\n\tQStringList live_list;\n\tQNetworkAccessManager* mLoginManager;\n\tQNetworkAccessManager* mRawMyLiveManager;\npublic:\n\tNicoLive();\n\tvoid set_session(const char *session);\n\tvoid set_account(const char *mail, const char *password);\n\tconst char *get_session();\n\tconst char *get_live_id();\n\tconst char *get_live_url(const char *live_id);\n\tconst char *get_live_key(const char *live_id);\n\tbool check_session();\n\tQVariant makePostData(const QString &session_id);\n\tQByteArray get_web(const QUrl);\n\t\/\/ Access Niconico Site\n\tbool site_login();\n\tbool site_live_my();\n\tbool site_live_prof();\n};\n\nconst QUrl NicoLive::LOGIN_URL =\n\t\tQUrl(\"https:\/\/secure.nicovideo.jp\/secure\/login?site=nicolive\");\nconst QUrl NicoLive::MYLIVE_URL =\n\t\tQUrl(\"http:\/\/live.nicovideo.jp\/my\");\nconst QString FMEPROF_URL_PRE =\n\t\t\"http:\/\/live.nicovideo.jp\/api\/getfmeprofile?v=\";\n\nNicoLive::NicoLive()\n{\n}\n\nvoid NicoLive::set_session(const char *session)\n{\n\tdebug_call_func();\n\tthis->session = session;\n}\n\nvoid NicoLive::set_account(const char *mail, const char *password)\n{\n\tdebug_call_func();\n\tthis->mail = mail;\n\tthis->password = password;\n}\n\nconst char *NicoLive::get_session()\n{\n\tdebug_call_func();\n\treturn this->session.toStdString().c_str();\n}\n\nconst char *NicoLive::get_live_id()\n{\n\tdebug_call_func();\n\tif (this->site_live_my()) {\n\t\tif (this->site_live_prof()) {\n\t\t\treturn this->live_id.toStdString().c_str();\n\t\t}\n\t}\n\treturn NULL;\n}\n\nconst char *NicoLive::get_live_url(const char *live_id)\n{\n\tdebug_call_func();\n\tif (this->live_id == live_id) {\n\t\treturn this->live_url.toStdString().c_str();\n\t}\n\treturn NULL;\n}\n\nconst char *NicoLive::get_live_key(const char *live_id)\n{\n\tdebug_call_func();\n\tif (this->live_id == live_id) {\n\t\treturn this->live_key.toStdString().c_str();\n\t}\n\treturn NULL;\n}\n\nbool NicoLive::check_session()\n{\n\tdebug_call_func();\n\treturn this->site_live_my();\n}\n\nQVariant NicoLive::makePostData(const QString &session_id)\n{\n\tdebug_call_func();\n\t\/*\n\toriginal code by https:\/\/github.com\/diginatu\/Viqo\n\tfile: src\/NicoLiveManager\/nicolivemanager.cpp\n\tLicensed under the MIT License Copyright (c) 2014 diginatu\n\tsee https:\/\/github.com\/diginatu\/Viqo\/raw\/master\/LICENSE\n\t*\/\n\tQVariant postData;\n\n\t\/\/ make cookies\n\tQList <QNetworkCookie> cookies;\n\tQNetworkCookie ck;\n\tck.toRawForm(QNetworkCookie::NameAndValueOnly);\n\tck.setName(\"user_session\");\n\n\tQByteArray user_id_ba;\n\tuser_id_ba.append(session_id);\n\n\tck.setValue(user_id_ba);\n\tcookies.append(ck);\n\n\tpostData.setValue(cookies);\n\treturn postData;\n}\n\nbool NicoLive::site_login()\n{\n\tdebug_call_func();\n\t\/*\n\toriginal code by https:\/\/github.com\/diginatu\/Viqo\n\t\t\tfile: src\/NicoLiveManager\/loginapi.cpp\n\tLicensed under the MIT License Copyright (c) 2014 diginatu\n\tsee https:\/\/github.com\/diginatu\/Viqo\/raw\/master\/LICENSE\n\t*\/\n\tif(mLoginManager!=nullptr) delete mLoginManager;\n\tmLoginManager = new QNetworkAccessManager(this);\n\n\tQNetworkRequest rq(QUrl(\n\t\t\t\"https:\/\/secure.nicovideo.jp\/secure\/login?site=nicolive\"));\n\trq.setHeader(QNetworkRequest::ContentTypeHeader,\n\t\t\t\"application\/x-www-form-urlencoded\");\n\n\tQUrlQuery params;\n\tparams.addQueryItem(\"next_url\", \"\");\n\tparams.addQueryItem(\"show_button_facebook\", \"0\");\n\tparams.addQueryItem(\"show_button_twitter\", \"0\");\n\tparams.addQueryItem(\"nolinks\", \"0\");\n\tparams.addQueryItem(\"_use_valid_error_code\", \"0\");\n\tparams.addQueryItem(\"mail\", QUrl::toPercentEncoding(this->mail));\n\tparams.addQueryItem(\"password\", QUrl::toPercentEncoding(this->password));\n\n\tQNetworkReply *netReply = mLoginManager->post(rq,\n\t\t\tparams.toString(QUrl::FullyEncoded).toUtf8());\n\n\tinfo(\"login start\");\n\n\t\/\/ wait reply\n\tQEventLoop loop;\n\tconnect(netReply, SIGNAL(finished()), &loop, SLOT(quit()));\n\tloop.exec();\n\n\tinfo(\"login finished\");\n\n\t\/\/ finished reply\n\tauto headers = netReply->rawHeaderPairs();\n\n\tbool success = false;\n\tforeach (auto header, headers) {\n\t\tif (header.first == \"Set-Cookie\") {\n\t\t\tauto cookies = QNetworkCookie::parseCookies(header.second);\n\t\t\tforeach (auto cookie, cookies) {\n\t\t\t\tif (cookie.name() == \"user_session\" &&\n\t\t\t\t\t\tcookie.value() != \"deleted\" &&\n\t\t\t\t\t\tcookie.value() != \"\") {\n\t\t\t\t\tthis->session = cookie.value();\n\t\t\t\t\tsuccess = true;\n\t\t\t\t\tinfo(\"login succeeded: %20s...\", this->session.toStdString().c_str());\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\tinfo(\"[nicolive] login failed\");\n\t}\n\n\tnetReply->deleteLater();\n\treturn success;\n}\n\nQByteArray NicoLive::get_web(const QUrl)\n{\n\tdebug_call_func();\n\t\/\/ get http:\/\/live.nicovideo.jp\/my\n\t\/*\n\toriginal code by https:\/\/github.com\/diginatu\/Viqo\n\tfile: src\/NicoLiveManager\/rawmylivewaku.cpp\n\tLicensed under the MIT License Copyright (c) 2014 diginatu\n\tsee https:\/\/github.com\/diginatu\/Viqo\/raw\/master\/LICENSE\n\t*\/\n\tif(mRawMyLiveManager!=nullptr) delete mRawMyLiveManager;\n\tmRawMyLiveManager = new QNetworkAccessManager(this);\n\n\tif (this->session.isEmpty()) {\n\t\treturn \"\";\n\t}\n\n\t\/\/ make request\n\tQNetworkRequest rq;\n\tQVariant postData = makePostData(this->session);\n\trq.setHeader(QNetworkRequest::CookieHeader, postData);\n\trq.setUrl(NicoLive::MYLIVE_URL);\n\n\tQNetworkReply * netReply = mRawMyLiveManager->get(rq);\n\n\tinfo(\"get my live start\");\n\n\t\/\/ wait reply\n\tQEventLoop loop;\n\tconnect(netReply, SIGNAL(finished()), &loop, SLOT(quit()));\n\tloop.exec();\n\n\tinfo(\"get my live finished\");\n\n\t\/\/ finished reply\n\tQByteArray repdata = netReply->readAll();\n\tnetReply->deleteLater();\n\treturn repdata;\n}\n\nbool NicoLive::site_live_my()\n{\n\tQXmlStreamReader reader(this->get_web(NicoLive::MYLIVE_URL));\n\n QString id_str(\"id\");\n\tQString class_str(\"class\");\n\tbool logined = false;\n\tbool live_onair = false;\n\twhile (!reader.atEnd()) {\n\t\tif (reader.isStartElement() && reader.name() == \"div\" &&\n\t\t\t\treader.attributes().value(id_str) == \"liveItemsWrap\") {\n\t\t\t\/\/ <div id=\"liveItemsWrap\">\n\t\t\tinfo(\"[nicolive] session alive\");\n\t\t\tlogined = true;\n\t\t\twhile (!reader.atEnd()) {\n\t\t\t\tif (reader.isStartElement() && reader.name() == \"div\") {\n\t\t\t\t\tif (reader.attributes().value(class_str) == \"liveItemImg\") {\n\t\t\t\t\t\twhile (!reader.atEnd()) {\n\t\t\t\t\t\t\tif (reader.isStartElement()) {\n\t\t\t\t\t\t\t\tif (reader.name() == \"img\") {\n\t\t\t\t\t\t\t\t\tif (reader.attributes().value(\"alt\") == \"ONAIR\") {\n\t\t\t\t\t\t\t\t\t\tlive_onair = true;\n\t\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t\t\/\/ not onair\n\t\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t} else if (live_onair && reader.name() == \"a\") {\n\t\t\t\t\t\t\t\t\t\/\/ strlen(\"http:\/\/live.nicovideo.jp\/editstream\/\") == 36\n\t\t\t\t\t\t\t\t\tthis->live_id =\n\t\t\t\t\t\t\t\t\t\t\treader.attributes().value(\"href\").mid(36).toString();\n\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t} else if (reader.name() == \"a\" &&\n\t\t\t\t\t\t\t\t\t\treader.attributes().value(class_str) == \"liveItemTxt\") {\n\t\t\t\t\t\t\t\t\twarn(\"invalid html\");\n\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\treader.atEnd() || reader.readNext();\n\t\t\t\t\t\t} \/\/ end while\n\t\t\t\t\t} else if (reader.attributes().value(\"class\") == \"pager\") {\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treader.atEnd() || reader.readNext();\n\t\t\t} \/\/ end while\n\t\t\tbreak;\n\t\t}\n\t\treader.atEnd() || reader.readNext();\n\t} \/\/ end while\n\n\tif (!live_onair) {\n\t\tthis->live_id = QString();\n\t}\n\n\treturn logined;\n}\n\nbool NicoLive::site_live_prof() {\n\tdebug_call_func();\n\t\/\/ TODO: 後で\n\treturn false;\n}\n\/\/ end of NicoLive class\n\nstatic NicoLive nicolive;\n\nextern \"C\" bool nicolive_chek_session_n(const char *session)\n{\n\tdebug_call_func();\n\tnicolive.set_session(session);\n\treturn nicolive.check_session();\n}\n\nextern \"C\" const char *nicolive_get_session(const char *mail,\n\tconst char *password)\n{\n\tdebug_call_func();\n\tnicolive.set_account(mail, password);\n\tif (nicolive.site_login()) {\n\t\treturn nicolive.get_session();\n\t} else {\n\t\treturn NULL;\n\t}\n}\n\nextern \"C\" const char *nicolive_get_live_id(const char *session)\n{\n\tdebug_call_func();\n\tnicolive.set_session(session);\n\treturn nicolive.get_live_id();\n}\n\nextern \"C\" const char *nicolive_get_live_url(const char *session,\n\t\tconst char *live_id)\n{\n\tdebug_call_func();\n\tnicolive.set_session(session);\n\treturn nicolive.get_live_url(live_id);\n}\n\nextern \"C\" const char *nicolive_get_live_key(const char *session,\n\t\tconst char *live_id)\n{\n\tdebug_call_func();\n\tnicolive.set_session(session);\n\treturn nicolive.get_live_key(live_id);\n}\n<commit_msg>完成!!!!でも、コンパイル通っただけ。<commit_after>#include <QtCore>\n#include <QtNetwork>\n#include <obs.h>\n#include \"nicolive.h\"\n\n\/\/ class NicoLive\nclass NicoLive : public QObject\n{\n\t\/\/ Q_OBJECT\npublic:\n\tstatic const QUrl LOGIN_URL;\n\tstatic const QUrl MYLIVE_URL;\n\tstatic const QString FMEPROF_URL_PRE;\nprivate:\n\tQString session;\n\tQString mail;\n\tQString password;\n\tQString live_id;\n\tQString live_url;\n\tQString live_key;\n\tQNetworkAccessManager* qnam;\npublic:\n\tNicoLive();\n\tvoid set_session(const char *session);\n\tvoid set_account(const char *mail, const char *password);\n\tconst char *get_session();\n\tconst char *get_live_id();\n\tconst char *get_live_url(const char *live_id);\n\tconst char *get_live_key(const char *live_id);\n\tbool check_session();\n\tQVariant make_cookie_data(const QString &session_id);\n\tQByteArray get_web(const QUrl);\n\t\/\/ Access Niconico Site\n\tbool site_login();\n\tbool site_live_my();\n\tbool site_live_prof();\n};\n\nconst QUrl NicoLive::LOGIN_URL =\n\t\tQUrl(\"https:\/\/secure.nicovideo.jp\/secure\/login?site=nicolive\");\nconst QUrl NicoLive::MYLIVE_URL =\n\t\tQUrl(\"http:\/\/live.nicovideo.jp\/my\");\nconst QString NicoLive::FMEPROF_URL_PRE =\n\t\t\"http:\/\/live.nicovideo.jp\/api\/getfmeprofile?v=\";\n\nNicoLive::NicoLive()\n{\n\tqnam = new QNetworkAccessManager(this);\n}\n\nvoid NicoLive::set_session(const char *session)\n{\n\tdebug_call_func();\n\tthis->session = session;\n}\n\nvoid NicoLive::set_account(const char *mail, const char *password)\n{\n\tdebug_call_func();\n\tthis->mail = mail;\n\tthis->password = password;\n}\n\nconst char *NicoLive::get_session()\n{\n\tdebug_call_func();\n\treturn this->session.toStdString().c_str();\n}\n\nconst char *NicoLive::get_live_id()\n{\n\tdebug_call_func();\n\tif (this->site_live_my()) {\n\t\tif (this->site_live_prof()) {\n\t\t\treturn this->live_id.toStdString().c_str();\n\t\t}\n\t}\n\treturn NULL;\n}\n\nconst char *NicoLive::get_live_url(const char *live_id)\n{\n\tdebug_call_func();\n\tif (this->live_id == live_id) {\n\t\treturn this->live_url.toStdString().c_str();\n\t}\n\treturn NULL;\n}\n\nconst char *NicoLive::get_live_key(const char *live_id)\n{\n\tdebug_call_func();\n\tif (this->live_id == live_id) {\n\t\treturn this->live_key.toStdString().c_str();\n\t}\n\treturn NULL;\n}\n\nbool NicoLive::check_session()\n{\n\tdebug_call_func();\n\treturn this->site_live_my();\n}\n\n\/*\noriginal code by https:\/\/github.com\/diginatu\/Viqo\nfile: src\/NicoLiveManager\/nicolivemanager.cpp\nLicensed under the MIT License Copyright (c) 2014 diginatu\nsee https:\/\/github.com\/diginatu\/Viqo\/raw\/master\/LICENSE\n*\/\nQVariant NicoLive::make_cookie_data(const QString &session_id)\n{\n\tdebug_call_func();\n\tQVariant cookieData;\n\n\t\/\/ make cookies\n\tQList <QNetworkCookie> cookies;\n\tQNetworkCookie ck;\n\tck.toRawForm(QNetworkCookie::NameAndValueOnly);\n\tck.setName(\"user_session\");\n\n\tQByteArray user_id_ba;\n\tuser_id_ba.append(session_id);\n\n\tck.setValue(user_id_ba);\n\tcookies.append(ck);\n\n\tcookieData.setValue(cookies);\n\treturn cookieData;\n}\n\n\/*\noriginal code by https:\/\/github.com\/diginatu\/Viqo\nfile: src\/NicoLiveManager\/loginapi.cpp\nLicensed under the MIT License Copyright (c) 2014 diginatu\nsee https:\/\/github.com\/diginatu\/Viqo\/raw\/master\/LICENSE\n*\/\nbool NicoLive::site_login()\n{\n\tdebug_call_func();\n\tQNetworkRequest rq(QUrl(\n\t\t\t\"https:\/\/secure.nicovideo.jp\/secure\/login?site=nicolive\"));\n\trq.setHeader(QNetworkRequest::ContentTypeHeader,\n\t\t\t\"application\/x-www-form-urlencoded\");\n\n\tQUrlQuery params;\n\tparams.addQueryItem(\"next_url\", \"\");\n\tparams.addQueryItem(\"show_button_facebook\", \"0\");\n\tparams.addQueryItem(\"show_button_twitter\", \"0\");\n\tparams.addQueryItem(\"nolinks\", \"0\");\n\tparams.addQueryItem(\"_use_valid_error_code\", \"0\");\n\tparams.addQueryItem(\"mail\", QUrl::toPercentEncoding(this->mail));\n\tparams.addQueryItem(\"password\", QUrl::toPercentEncoding(this->password));\n\n\tQNetworkReply *netReply = qnam->post(rq,\n\t\t\tparams.toString(QUrl::FullyEncoded).toUtf8());\n\n\tinfo(\"login start\");\n\n\t\/\/ wait reply\n\tQEventLoop loop;\n\tconnect(netReply, SIGNAL(finished()), &loop, SLOT(quit()));\n\tloop.exec();\n\n\tinfo(\"login finished\");\n\n\t\/\/ finished reply\n\tauto headers = netReply->rawHeaderPairs();\n\n\tbool success = false;\n\tforeach (auto header, headers) {\n\t\tif (header.first == \"Set-Cookie\") {\n\t\t\tauto cookies = QNetworkCookie::parseCookies(header.second);\n\t\t\tforeach (auto cookie, cookies) {\n\t\t\t\tif (cookie.name() == \"user_session\" &&\n\t\t\t\t\t\tcookie.value() != \"deleted\" &&\n\t\t\t\t\t\tcookie.value() != \"\") {\n\t\t\t\t\tthis->session = cookie.value();\n\t\t\t\t\tsuccess = true;\n\t\t\t\t\tinfo(\"login succeeded: %20s...\", this->session.toStdString().c_str());\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\tinfo(\"[nicolive] login failed\");\n\t}\n\n\tnetReply->deleteLater();\n\treturn success;\n}\n\n\/*\noriginal code by https:\/\/github.com\/diginatu\/Viqo\nfile: src\/NicoLiveManager\/rawmylivewaku.cpp\nLicensed under the MIT License Copyright (c) 2014 diginatu\nsee https:\/\/github.com\/diginatu\/Viqo\/raw\/master\/LICENSE\n*\/\nQByteArray NicoLive::get_web(const QUrl url)\n{\n\tdebug_call_func();\n\n\tif (this->session.isEmpty()) {\n\t\treturn \"\";\n\t}\n\n\t\/\/ make request\n\tQNetworkRequest rq;\n\tQVariant cookieData = this->make_cookie_data(this->session);\n\trq.setHeader(QNetworkRequest::CookieHeader, cookieData);\n\trq.setUrl(url);\n\n\tQNetworkReply * netReply = qnam->get(rq);\n\n\tinfo(\"web get start\");\n\n\t\/\/ wait reply\n\tQEventLoop loop;\n\tconnect(netReply, SIGNAL(finished()), &loop, SLOT(quit()));\n\tloop.exec();\n\n\tinfo(\"web get finished\");\n\n\t\/\/ finished reply\n\tQByteArray repdata = netReply->readAll();\n\tnetReply->deleteLater();\n\treturn repdata;\n}\n\nbool NicoLive::site_live_my()\n{\n\tdebug_call_func();\n\n\tif (this->session.isEmpty()) {\n\t\tthis->live_id = QString();\n\t\treturn false;\n\t}\n\n\tQXmlStreamReader reader(this->get_web(NicoLive::MYLIVE_URL));\n\n\tbool success = false;\n\tbool live_onair = false;\n\twhile (!reader.atEnd()) {\n\t\tif (reader.isStartElement() && reader.name() == \"div\" &&\n\t\t\t\treader.attributes().value(\"id\") == \"liveItemsWrap\") {\n\t\t\t\/\/ <div id=\"liveItemsWrap\">\n\t\t\tinfo(\"[nicolive] session alive\");\n\t\t\tsuccess = true;\n\t\t\twhile (!reader.atEnd()) {\n\t\t\t\tif (reader.isStartElement() && reader.name() == \"div\") {\n\t\t\t\t\tif (reader.attributes().value(\"class\") == \"liveItemImg\") {\n\t\t\t\t\t\twhile (!reader.atEnd()) {\n\t\t\t\t\t\t\tif (reader.isStartElement()) {\n\t\t\t\t\t\t\t\tif (reader.name() == \"img\") {\n\t\t\t\t\t\t\t\t\tif (reader.attributes().value(\"alt\") == \"ONAIR\") {\n\t\t\t\t\t\t\t\t\t\tlive_onair = true;\n\t\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t\t\/\/ not onair\n\t\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t} else if (live_onair && reader.name() == \"a\") {\n\t\t\t\t\t\t\t\t\t\/\/ strlen(\"http:\/\/live.nicovideo.jp\/editstream\/\") == 36\n\t\t\t\t\t\t\t\t\tthis->live_id =\n\t\t\t\t\t\t\t\t\t\t\treader.attributes().value(\"href\").mid(36).toString();\n\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t} else if (reader.name() == \"a\" &&\n\t\t\t\t\t\t\t\t\t\treader.attributes().value(\"class\") == \"liveItemTxt\") {\n\t\t\t\t\t\t\t\t\twarn(\"invalid html\");\n\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\treader.atEnd() || reader.readNext();\n\t\t\t\t\t\t} \/\/ end while\n\t\t\t\t\t} else if (reader.attributes().value(\"class\") == \"pager\") {\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treader.atEnd() || reader.readNext();\n\t\t\t} \/\/ end while\n\t\t\tbreak;\n\t\t}\n\t\treader.atEnd() || reader.readNext();\n\t} \/\/ end while\n\n\tif (!live_onair) {\n\t\tthis->live_id = QString();\n\t}\n\n\treturn success;\n}\n\nbool NicoLive::site_live_prof() {\n\tdebug_call_func();\n\n\tif (this->live_id.isEmpty()) {\n\t\tthis->live_url = QString();\n\t\tthis->live_key = QString();\n\t\treturn false;\n\t}\n\n\tQString live_prof_url;\n\tlive_prof_url += NicoLive::FMEPROF_URL_PRE;\n\tlive_prof_url += this->live_id;\n\n\tQXmlStreamReader reader(this->get_web(QUrl(live_prof_url)));\n\n\tbool success_url = false;\n\tbool success_key = false;\n\twhile (!reader.atEnd()) {\n\t\tif (reader.isStartElement() && reader.name() == \"rtmp\") {\n\t\t\twhile (!reader.atEnd()) {\n\t\t\t\tif (reader.isStartElement() && reader.name() == \"url\") {\n\t\t\t\t\treader.readNext();\n\t\t\t\t\tif (reader.isCharacters()) {\n\t\t\t\t\t\tthis->live_url = reader.text().toString();\n\t\t\t\t\t\tsuccess_url = true;\n\t\t\t\t\t} else {\n\t\t\t\t\t\terror(\"invalid xml: rtmp->url next not contents\");\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t} else if (reader.isStartElement() && reader.name() == \"stream\") {\n\t\t\t\t\tif (reader.isCharacters()) {\n\t\t\t\t\t\tthis->live_key = reader.text().toString();\n\t\t\t\t\t\tsuccess_key = true;\n\t\t\t\t\t} else {\n\t\t\t\t\t\terror(\"invalid xml: rtmp->stream next not contents\");\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t} else if (reader.isEndElement() && reader.name() == \"rtmp\") {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\treader.atEnd() || reader.readNext();\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\treader.atEnd() || reader.readNext();\n\t} \/\/ end while\n\n\tif (success_url && success_key) {\n\t\treturn true;\n\t} else {\n\t\tthis->live_url = QString();\n\t\tthis->live_key = QString();\n\t\treturn false;\n\t}\n}\n\/\/ end of NicoLive class\n\nstatic NicoLive nicolive;\n\nextern \"C\" bool nicolive_chek_session_n(const char *session)\n{\n\tdebug_call_func();\n\tnicolive.set_session(session);\n\treturn nicolive.check_session();\n}\n\nextern \"C\" const char *nicolive_get_session(const char *mail,\n\tconst char *password)\n{\n\tdebug_call_func();\n\tnicolive.set_account(mail, password);\n\tif (nicolive.site_login()) {\n\t\treturn nicolive.get_session();\n\t} else {\n\t\treturn NULL;\n\t}\n}\n\nextern \"C\" const char *nicolive_get_live_id(const char *session)\n{\n\tdebug_call_func();\n\tnicolive.set_session(session);\n\treturn nicolive.get_live_id();\n}\n\nextern \"C\" const char *nicolive_get_live_url(const char *session,\n\t\tconst char *live_id)\n{\n\tdebug_call_func();\n\tnicolive.set_session(session);\n\treturn nicolive.get_live_url(live_id);\n}\n\nextern \"C\" const char *nicolive_get_live_key(const char *session,\n\t\tconst char *live_id)\n{\n\tdebug_call_func();\n\tnicolive.set_session(session);\n\treturn nicolive.get_live_key(live_id);\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Author: Enrico Guiraud, Danilo Piparo CERN 12\/2016\n\n\/*************************************************************************\n * Copyright (C) 1995-2016, Rene Brun and Fons Rademakers. *\n * All rights reserved. *\n * *\n * For the licensing terms see $ROOTSYS\/LICENSE. *\n * For the list of contributors see $ROOTSYS\/README\/CREDITS. *\n *************************************************************************\/\n\n#ifndef ROOT_TDFUTILS\n#define ROOT_TDFUTILS\n\n#include \"ROOT\/RArrayView.hxx\"\n#include \"TH1.h\"\n#include \"TTreeReaderArray.h\"\n#include \"TTreeReaderValue.h\"\n\n#include <array>\n#include <cstddef> \/\/ std::size_t\n#include <functional>\n#include <memory>\n#include <string>\n#include <type_traits> \/\/ std::decay\n#include <vector>\nclass TTree;\nclass TTreeReader;\n\n\/\/\/ \\cond HIDDEN_SYMBOLS\n\nnamespace ROOT {\n\n\/\/ fwd declaration for IsV7Hist\nnamespace Experimental {\ntemplate <int D, typename P, template <int, typename, template <typename> class> class... S>\nclass THist;\n} \/\/ ns Experimental\n\nnamespace Detail {\nnamespace TDF {\nusing ColumnNames_t = std::vector<std::string>;\nclass TCustomColumnBase; \/\/ fwd decl for ColumnName2ColumnTypeName\nstruct TInferType {\n};\n} \/\/ end ns Detail\n} \/\/ end ns TDF\n\nnamespace Internal {\nnamespace TDF {\nusing namespace ROOT::Detail::TDF;\n\n\/\/\/ Compile-time integer sequence generator\n\/\/\/ e.g. calling GenStaticSeq<3>::type() instantiates a StaticSeq<0,1,2>\ntemplate <int...>\nstruct StaticSeq {\n};\n\ntemplate <int N, int... S>\nstruct GenStaticSeq : GenStaticSeq<N - 1, N - 1, S...> {\n};\n\ntemplate <int... S>\nstruct GenStaticSeq<0, S...> {\n using type = StaticSeq<S...>;\n};\n\ntemplate <int... S>\nusing GenStaticSeq_t = typename GenStaticSeq<S...>::type;\n\n\/\/ return wrapper around f that prepends an `unsigned int slot` parameter\ntemplate <typename R, typename F, typename... Args>\nstd::function<R(unsigned int, Args...)> AddSlotParameter(F &f, TTypeList<Args...>)\n{\n return [f](unsigned int, Args... a) -> R { return f(a...); };\n}\n\ntemplate <typename BranchType, typename... Rest>\nstruct TNeedJitting {\n static constexpr bool value = TNeedJitting<Rest...>::value;\n};\n\ntemplate <typename... Rest>\nstruct TNeedJitting<TInferType, Rest...> {\n static constexpr bool value = true;\n};\n\ntemplate <typename T>\nstruct TNeedJitting<T> {\n static constexpr bool value = false;\n};\n\ntemplate <>\nstruct TNeedJitting<TInferType> {\n static constexpr bool value = true;\n};\n\nusing TVBPtr_t = std::shared_ptr<TTreeReaderValueBase>;\nusing TVBVec_t = std::vector<TVBPtr_t>;\n\nstd::string ColumnName2ColumnTypeName(const std::string &colName, TTree *, TCustomColumnBase *);\n\nconst char *ToConstCharPtr(const char *s);\nconst char *ToConstCharPtr(const std::string s);\nunsigned int GetNSlots();\n\n\/\/\/ Choose between TTreeReader{Array,Value} depending on whether the branch type\n\/\/\/ T is a `std::array_view<T>` or any other type (respectively).\ntemplate <typename T>\nstruct TReaderValueOrArray {\n using Proxy_t = TTreeReaderValue<T>;\n};\n\ntemplate <typename T>\nstruct TReaderValueOrArray<std::array_view<T>> {\n using Proxy_t = TTreeReaderArray<T>;\n};\n\ntemplate <typename T>\nusing ReaderValueOrArray_t = typename TReaderValueOrArray<T>::Proxy_t;\n\n\/\/\/ Initialize a tuple of TColumnValues.\n\/\/\/ For real TTree branches a TTreeReader{Array,Value} is built and passed to the\n\/\/\/ TColumnValue. For temporary columns a pointer to the corresponding variable\n\/\/\/ is passed instead.\ntemplate <typename TDFValueTuple, int... S>\nvoid InitTDFValues(unsigned int slot, TDFValueTuple &valueTuple, TTreeReader *r, const ColumnNames_t &bn,\n const ColumnNames_t &tmpbn,\n const std::map<std::string, std::shared_ptr<TCustomColumnBase>> &tmpBranches, TStaticSeq<S...>)\n{\n \/\/ isTmpBranch has length bn.size(). Elements are true if the corresponding\n \/\/ branch is a temporary branch created with Define, false if they are\n \/\/ actual branches present in the TTree.\n std::array<bool, sizeof...(S)> isTmpColumn;\n for (auto i = 0u; i < isTmpColumn.size(); ++i)\n isTmpColumn[i] = std::find(tmpbn.begin(), tmpbn.end(), bn.at(i)) != tmpbn.end();\n\n \/\/ hack to expand a parameter pack without c++17 fold expressions.\n \/\/ The statement defines a variable with type std::initializer_list<int>, containing all zeroes, and SetTmpColumn or\n \/\/ SetProxy are conditionally executed as the braced init list is expanded. The final ... expands S.\n std::initializer_list<int> expander{(isTmpColumn[S]\n ? std::get<S>(valueTuple).SetTmpColumn(slot, tmpBranches.at(bn.at(S)).get())\n : std::get<S>(valueTuple).MakeProxy(r, bn.at(S)),\n 0)...};\n (void)expander; \/\/ avoid \"unused variable\" warnings for expander on gcc4.9\n (void)slot; \/\/ avoid _bogus_ \"unused variable\" warnings for slot on gcc 4.9\n (void)r; \/\/ avoid \"unused variable\" warnings for r on gcc5.2\n}\n\ntemplate <typename Filter>\nvoid CheckFilter(Filter &)\n{\n using FilterRet_t = typename TDF::TFunctionTraits<Filter>::Ret_t;\n static_assert(std::is_same<FilterRet_t, bool>::value, \"filter functions must return a bool\");\n}\n\nvoid CheckTmpBranch(std::string_view branchName, TTree *treePtr);\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Check that the callable passed to TInterface::Reduce:\n\/\/\/ - takes exactly two arguments of the same type\n\/\/\/ - has a return value of the same type as the arguments\ntemplate <typename F, typename T>\nvoid CheckReduce(F &, TTypeList<T, T>)\n{\n using Ret_t = typename TFunctionTraits<F>::Ret_t;\n static_assert(std::is_same<Ret_t, T>::value, \"reduce function must have return type equal to argument type\");\n return;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ This overload of CheckReduce is called if T is not a TTypeList<T,T>\ntemplate <typename F, typename T>\nvoid CheckReduce(F &, T)\n{\n static_assert(sizeof(F) == 0, \"reduce function must take exactly two arguments of the same type\");\n}\n\n\/\/\/ Returns local BranchNames or default BranchNames according to which one should be used\nconst ColumnNames_t &PickBranchNames(unsigned int nArgs, const ColumnNames_t &bl, const ColumnNames_t &defBl);\n\nnamespace ActionTypes {\nstruct Histo1D {\n};\nstruct Histo2D {\n};\nstruct Histo3D {\n};\nstruct Profile1D {\n};\nstruct Profile2D {\n};\nstruct Min {\n};\nstruct Max {\n};\nstruct Mean {\n};\nstruct Fill {\n};\n}\n\n\/\/\/ Check whether a histogram type is a classic or v7 histogram.\ntemplate <typename T>\nstruct IsV7Hist : public std::false_type {\n static_assert(std::is_base_of<TH1, T>::value, \"not implemented for this type\");\n};\n\ntemplate <int D, typename P, template <int, typename, template <typename> class> class... S>\nstruct IsV7Hist<ROOT::Experimental::THist<D, P, S...>> : public std::true_type {\n};\n\ntemplate <typename T, bool ISV7HISTO = IsV7Hist<T>::value>\nstruct HistoUtils {\n static void SetCanExtendAllAxes(T &h) { h.SetCanExtend(::TH1::kAllAxes); }\n static bool HasAxisLimits(T &h)\n {\n auto xaxis = h.GetXaxis();\n return !(xaxis->GetXmin() == 0. && xaxis->GetXmax() == 0.);\n }\n};\n\ntemplate <typename T>\nstruct HistoUtils<T, true> {\n static void SetCanExtendAllAxes(T &) {}\n static bool HasAxisLimits(T &) { return true; }\n};\n\n} \/\/ end NS TDF\n} \/\/ end NS Internal\n} \/\/ end NS ROOT\n\n\/\/\/ \\endcond\n\n#endif \/\/ TDFUTILS\n<commit_msg>[TDF] Update TDFUtils.hxx to use ROOT\/TypeTraits.hxx<commit_after>\/\/ Author: Enrico Guiraud, Danilo Piparo CERN 12\/2016\n\n\/*************************************************************************\n * Copyright (C) 1995-2016, Rene Brun and Fons Rademakers. *\n * All rights reserved. *\n * *\n * For the licensing terms see $ROOTSYS\/LICENSE. *\n * For the list of contributors see $ROOTSYS\/README\/CREDITS. *\n *************************************************************************\/\n\n#ifndef ROOT_TDFUTILS\n#define ROOT_TDFUTILS\n\n#include \"ROOT\/TypeTraits.hxx\"\n#include \"ROOT\/RArrayView.hxx\"\n#include \"TH1.h\"\n#include \"TTreeReaderArray.h\"\n#include \"TTreeReaderValue.h\"\n\n#include <array>\n#include <cstddef> \/\/ std::size_t\n#include <functional>\n#include <memory>\n#include <string>\n#include <type_traits> \/\/ std::decay\n#include <vector>\nclass TTree;\nclass TTreeReader;\n\n\/\/\/ \\cond HIDDEN_SYMBOLS\n\nnamespace ROOT {\n\n\/\/ fwd declaration for IsV7Hist\nnamespace Experimental {\ntemplate <int D, typename P, template <int, typename, template <typename> class> class... S>\nclass THist;\n} \/\/ ns Experimental\n\nnamespace Detail {\nnamespace TDF {\nusing ColumnNames_t = std::vector<std::string>;\n\n\/\/ fwd decl for ColumnName2ColumnTypeName\nclass TCustomColumnBase;\n\n\/\/ type used for tag dispatching\nstruct TInferType {\n};\n} \/\/ end ns Detail\n} \/\/ end ns TDF\n\nnamespace Internal {\nnamespace TDF {\nusing namespace ROOT::TypeTraits;\nusing namespace ROOT::Detail::TDF;\n\n\/\/\/ Compile-time integer sequence generator\n\/\/\/ e.g. calling GenStaticSeq<3>::type() instantiates a StaticSeq<0,1,2>\ntemplate <int...>\nstruct StaticSeq {\n};\n\ntemplate <int N, int... S>\nstruct GenStaticSeq : GenStaticSeq<N - 1, N - 1, S...> {\n};\n\ntemplate <int... S>\nstruct GenStaticSeq<0, S...> {\n using type = StaticSeq<S...>;\n};\n\ntemplate <int... S>\nusing GenStaticSeq_t = typename GenStaticSeq<S...>::type;\n\n\/\/ return wrapper around f that prepends an `unsigned int slot` parameter\ntemplate <typename R, typename F, typename... Args>\nstd::function<R(unsigned int, Args...)> AddSlotParameter(F &f, TypeList<Args...>)\n{\n return [f](unsigned int, Args... a) -> R { return f(a...); };\n}\n\ntemplate <typename BranchType, typename... Rest>\nstruct TNeedJitting {\n static constexpr bool value = TNeedJitting<Rest...>::value;\n};\n\ntemplate <typename... Rest>\nstruct TNeedJitting<TInferType, Rest...> {\n static constexpr bool value = true;\n};\n\ntemplate <typename T>\nstruct TNeedJitting<T> {\n static constexpr bool value = false;\n};\n\ntemplate <>\nstruct TNeedJitting<TInferType> {\n static constexpr bool value = true;\n};\n\nusing TVBPtr_t = std::shared_ptr<TTreeReaderValueBase>;\nusing TVBVec_t = std::vector<TVBPtr_t>;\n\nstd::string ColumnName2ColumnTypeName(const std::string &colName, TTree *, TCustomColumnBase *);\n\nconst char *ToConstCharPtr(const char *s);\nconst char *ToConstCharPtr(const std::string s);\nunsigned int GetNSlots();\n\n\/\/\/ Choose between TTreeReader{Array,Value} depending on whether the branch type\n\/\/\/ T is a `std::array_view<T>` or any other type (respectively).\ntemplate <typename T>\nstruct TReaderValueOrArray {\n using Proxy_t = TTreeReaderValue<T>;\n};\n\ntemplate <typename T>\nstruct TReaderValueOrArray<std::array_view<T>> {\n using Proxy_t = TTreeReaderArray<T>;\n};\n\ntemplate <typename T>\nusing ReaderValueOrArray_t = typename TReaderValueOrArray<T>::Proxy_t;\n\n\/\/\/ Initialize a tuple of TColumnValues.\n\/\/\/ For real TTree branches a TTreeReader{Array,Value} is built and passed to the\n\/\/\/ TColumnValue. For temporary columns a pointer to the corresponding variable\n\/\/\/ is passed instead.\ntemplate <typename TDFValueTuple, int... S>\nvoid InitTDFValues(unsigned int slot, TDFValueTuple &valueTuple, TTreeReader *r, const ColumnNames_t &bn,\n const ColumnNames_t &tmpbn,\n const std::map<std::string, std::shared_ptr<TCustomColumnBase>> &tmpBranches, StaticSeq<S...>)\n{\n \/\/ isTmpBranch has length bn.size(). Elements are true if the corresponding\n \/\/ branch is a temporary branch created with Define, false if they are\n \/\/ actual branches present in the TTree.\n std::array<bool, sizeof...(S)> isTmpColumn;\n for (auto i = 0u; i < isTmpColumn.size(); ++i)\n isTmpColumn[i] = std::find(tmpbn.begin(), tmpbn.end(), bn.at(i)) != tmpbn.end();\n\n \/\/ hack to expand a parameter pack without c++17 fold expressions.\n \/\/ The statement defines a variable with type std::initializer_list<int>, containing all zeroes, and SetTmpColumn or\n \/\/ SetProxy are conditionally executed as the braced init list is expanded. The final ... expands S.\n std::initializer_list<int> expander{(isTmpColumn[S]\n ? std::get<S>(valueTuple).SetTmpColumn(slot, tmpBranches.at(bn.at(S)).get())\n : std::get<S>(valueTuple).MakeProxy(r, bn.at(S)),\n 0)...};\n (void)expander; \/\/ avoid \"unused variable\" warnings for expander on gcc4.9\n (void)slot; \/\/ avoid _bogus_ \"unused variable\" warnings for slot on gcc 4.9\n (void)r; \/\/ avoid \"unused variable\" warnings for r on gcc5.2\n}\n\ntemplate <typename Filter>\nvoid CheckFilter(Filter &)\n{\n using FilterRet_t = typename TDF::CallableTraits<Filter>::ret_type;\n static_assert(std::is_same<FilterRet_t, bool>::value, \"filter functions must return a bool\");\n}\n\nvoid CheckTmpBranch(std::string_view branchName, TTree *treePtr);\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Check that the callable passed to TInterface::Reduce:\n\/\/\/ - takes exactly two arguments of the same type\n\/\/\/ - has a return value of the same type as the arguments\ntemplate <typename F, typename T>\nvoid CheckReduce(F &, TypeList<T, T>)\n{\n using ret_type = typename CallableTraits<F>::ret_type;\n static_assert(std::is_same<ret_type, T>::value, \"reduce function must have return type equal to argument type\");\n return;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ This overload of CheckReduce is called if T is not a TypeList<T,T>\ntemplate <typename F, typename T>\nvoid CheckReduce(F &, T)\n{\n static_assert(sizeof(F) == 0, \"reduce function must take exactly two arguments of the same type\");\n}\n\n\/\/\/ Returns local BranchNames or default BranchNames according to which one should be used\nconst ColumnNames_t &PickBranchNames(unsigned int nArgs, const ColumnNames_t &bl, const ColumnNames_t &defBl);\n\nnamespace ActionTypes {\nstruct Histo1D {\n};\nstruct Histo2D {\n};\nstruct Histo3D {\n};\nstruct Profile1D {\n};\nstruct Profile2D {\n};\nstruct Min {\n};\nstruct Max {\n};\nstruct Mean {\n};\nstruct Fill {\n};\n}\n\n\/\/\/ Check whether a histogram type is a classic or v7 histogram.\ntemplate <typename T>\nstruct IsV7Hist : public std::false_type {\n static_assert(std::is_base_of<TH1, T>::value, \"not implemented for this type\");\n};\n\ntemplate <int D, typename P, template <int, typename, template <typename> class> class... S>\nstruct IsV7Hist<ROOT::Experimental::THist<D, P, S...>> : public std::true_type {\n};\n\ntemplate <typename T, bool ISV7HISTO = IsV7Hist<T>::value>\nstruct HistoUtils {\n static void SetCanExtendAllAxes(T &h) { h.SetCanExtend(::TH1::kAllAxes); }\n static bool HasAxisLimits(T &h)\n {\n auto xaxis = h.GetXaxis();\n return !(xaxis->GetXmin() == 0. && xaxis->GetXmax() == 0.);\n }\n};\n\ntemplate <typename T>\nstruct HistoUtils<T, true> {\n static void SetCanExtendAllAxes(T &) {}\n static bool HasAxisLimits(T &) { return true; }\n};\n\n} \/\/ end NS TDF\n} \/\/ end NS Internal\n} \/\/ end NS ROOT\n\n\/\/\/ \\endcond\n\n#endif \/\/ TDFUTILS\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: cachemaptest.cxx,v $\n *\n * $Revision: 1.1 $\n *\n * last change: $Author: sb $ $Date: 2001-06-11 13:03:12 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef INCLUDED_UCB_CACHEMAPOBJECT1_HXX\n#include \"cachemapobject1.hxx\"\n#endif\n#ifndef INCLUDED_UCB_CACHEMAPOBJECT2_HXX\n#include \"cachemapobject2.hxx\"\n#endif\n#ifndef INCLUDED_UCB_CACHEMAPOBJECT3_HXX\n#include \"cachemapobject3.hxx\"\n#endif\n#ifndef INCLUDED_UCB_CACHEMAPOBJECTCONTAINER2_HXX\n#include \"cachemapobjectcontainer2.hxx\"\n#endif\n\n#ifndef _SOL_TIME_H_\n#include \"osl\/time.h\"\n#endif\n#ifndef _RTL_REF_HXX_\n#include \"rtl\/ref.hxx\"\n#endif\n#ifndef _RTL_USTRING_HXX_\n#include \"rtl\/ustring.hxx\"\n#endif\n\n#ifndef INCLUDED_CSTDLIB\n#include <cstdlib>\n#define INCLUDED_CSTDLIB\n#endif\n#ifndef INCLUDED_MEMORY\n#include <memory>\n#define INCLUDED_MEMORY\n#endif\n#ifndef INCLUDED_STDIO_H\n#include <stdio.h> \/\/ <iostream> or <cstdio> do not work well on all platforms\n#define INCLUDED_STDIO_H\n#endif\n\nusing ucb::cachemap::Object1;\nusing ucb::cachemap::Object2;\nusing ucb::cachemap::Object3;\nusing ucb::cachemap::ObjectContainer1;\nusing ucb::cachemap::ObjectContainer2;\nusing ucb::cachemap::ObjectContainer3;\n\nnamespace {\n\n\/\/ Give template function a dummy parameter, to work around MSVC++ bug:\ntemplate< typename Cont, typename ContRef, typename Obj >\nsal_uInt32 test(Obj *)\n{\n ContRef xCont(new Cont);\n rtl::OUString aPrefix(RTL_CONSTASCII_USTRINGPARAM(\"key\"));\n sal_uInt32 nTimer = osl_getGlobalTimer();\n for (int i = 0; i < 100000; i += 5)\n {\n rtl::OUString\n aKey0(aPrefix\n + rtl::OUString::valueOf(static_cast< sal_Int32 >(\n i % 100)));\n rtl::Reference< Obj > xObj01(xCont->get(aKey0));\n {for (int j = 0; j < 50; ++j)\n rtl::Reference< Obj > xRef(xObj01);\n }\n rtl::Reference< Obj > xObj02(xCont->get(aKey0));\n {for (int j = 0; j < 50; ++j)\n rtl::Reference< Obj > xRef(xObj02);\n }\n\n rtl::OUString\n aKey1(aPrefix\n + rtl::OUString::valueOf(static_cast< sal_Int32 >(\n (i + 1) % 100)));\n rtl::Reference< Obj > xObj11(xCont->get(aKey1));\n {for (int j = 0; j < 50; ++j)\n rtl::Reference< Obj > xRef(xObj11);\n }\n rtl::Reference< Obj > xObj12(xCont->get(aKey1));\n {for (int j = 0; j < 50; ++j)\n rtl::Reference< Obj > xRef(xObj12);\n }\n\n rtl::OUString\n aKey2(aPrefix\n + rtl::OUString::valueOf(static_cast< sal_Int32 >(\n (i + 2) % 100)));\n rtl::Reference< Obj > xObj21(xCont->get(aKey2));\n {for (int j = 0; j < 50; ++j)\n rtl::Reference< Obj > xRef(xObj21);\n }\n rtl::Reference< Obj > xObj22(xCont->get(aKey2));\n {for (int j = 0; j < 50; ++j)\n rtl::Reference< Obj > xRef(xObj22);\n }\n\n rtl::OUString\n aKey3(aPrefix\n + rtl::OUString::valueOf(static_cast< sal_Int32 >(\n (i + 3) % 100)));\n rtl::Reference< Obj > xObj31(xCont->get(aKey3));\n {for (int j = 0; j < 50; ++j)\n rtl::Reference< Obj > xRef(xObj31);\n }\n rtl::Reference< Obj > xObj32(xCont->get(aKey3));\n {for (int j = 0; j < 50; ++j)\n rtl::Reference< Obj > xRef(xObj32);\n }\n\n rtl::OUString\n aKey4(aPrefix\n + rtl::OUString::valueOf(static_cast< sal_Int32 >(\n (i + 4) % 100)));\n rtl::Reference< Obj > xObj41(xCont->get(aKey4));\n {for (int j = 0; j < 50; ++j)\n rtl::Reference< Obj > xRef(xObj41);\n }\n rtl::Reference< Obj > xObj42(xCont->get(aKey4));\n {for (int j = 0; j < 50; ++j)\n rtl::Reference< Obj > xRef(xObj42);\n }\n }\n return osl_getGlobalTimer() - nTimer;\n}\n\n}\n\nint\n#if defined WNT\n__cdecl\n#endif \/\/ WNT\nmain()\n{\n \/\/ Use the second set of measurements, to avoid startup inaccuracies:\n for (int i = 0; i < 2; ++i)\n printf(\"Version 1: %lu ms.\\nVersion 2: %lu ms.\\nVersion 3: %lu ms.\\n\",\n static_cast< unsigned long >(\n test< ObjectContainer1,\n rtl::Reference< ObjectContainer1 >,\n Object1 >(0)),\n static_cast< unsigned long >(\n test< ObjectContainer2,\n std::auto_ptr< ObjectContainer2 >,\n Object2 >(0)),\n static_cast< unsigned long >(\n test< ObjectContainer3,\n rtl::Reference< ObjectContainer3 >,\n Object3 >(0)));\n return EXIT_SUCCESS;\n}\n\n\/\/ unxsols3.pro: Version 1: 9137 ms.\n\/\/ Version 2: 8634 ms.\n\/\/ Version 3: 3166 ms.\n\/\/\n\/\/ wntmsci7.pro: Version 1: 3846 ms.\n\/\/ Version 2: 5598 ms.\n\/\/ Version 3: 2704 ms.\n<commit_msg>Removed obsolete special handling of main() on WNT.<commit_after>\/*************************************************************************\n *\n * $RCSfile: cachemaptest.cxx,v $\n *\n * $Revision: 1.2 $\n *\n * last change: $Author: sb $ $Date: 2001-06-26 09:53:10 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef INCLUDED_UCB_CACHEMAPOBJECT1_HXX\n#include \"cachemapobject1.hxx\"\n#endif\n#ifndef INCLUDED_UCB_CACHEMAPOBJECT2_HXX\n#include \"cachemapobject2.hxx\"\n#endif\n#ifndef INCLUDED_UCB_CACHEMAPOBJECT3_HXX\n#include \"cachemapobject3.hxx\"\n#endif\n#ifndef INCLUDED_UCB_CACHEMAPOBJECTCONTAINER2_HXX\n#include \"cachemapobjectcontainer2.hxx\"\n#endif\n\n#ifndef _SOL_TIME_H_\n#include \"osl\/time.h\"\n#endif\n#ifndef _RTL_REF_HXX_\n#include \"rtl\/ref.hxx\"\n#endif\n#ifndef _RTL_USTRING_HXX_\n#include \"rtl\/ustring.hxx\"\n#endif\n\n#ifndef INCLUDED_CSTDLIB\n#include <cstdlib>\n#define INCLUDED_CSTDLIB\n#endif\n#ifndef INCLUDED_MEMORY\n#include <memory>\n#define INCLUDED_MEMORY\n#endif\n#ifndef INCLUDED_STDIO_H\n#include <stdio.h> \/\/ <iostream> or <cstdio> do not work well on all platforms\n#define INCLUDED_STDIO_H\n#endif\n\nusing ucb::cachemap::Object1;\nusing ucb::cachemap::Object2;\nusing ucb::cachemap::Object3;\nusing ucb::cachemap::ObjectContainer1;\nusing ucb::cachemap::ObjectContainer2;\nusing ucb::cachemap::ObjectContainer3;\n\nnamespace {\n\n\/\/ Give template function a dummy parameter, to work around MSVC++ bug:\ntemplate< typename Cont, typename ContRef, typename Obj >\nsal_uInt32 test(Obj *)\n{\n ContRef xCont(new Cont);\n rtl::OUString aPrefix(RTL_CONSTASCII_USTRINGPARAM(\"key\"));\n sal_uInt32 nTimer = osl_getGlobalTimer();\n for (int i = 0; i < 100000; i += 5)\n {\n rtl::OUString\n aKey0(aPrefix\n + rtl::OUString::valueOf(static_cast< sal_Int32 >(\n i % 100)));\n rtl::Reference< Obj > xObj01(xCont->get(aKey0));\n {for (int j = 0; j < 50; ++j)\n rtl::Reference< Obj > xRef(xObj01);\n }\n rtl::Reference< Obj > xObj02(xCont->get(aKey0));\n {for (int j = 0; j < 50; ++j)\n rtl::Reference< Obj > xRef(xObj02);\n }\n\n rtl::OUString\n aKey1(aPrefix\n + rtl::OUString::valueOf(static_cast< sal_Int32 >(\n (i + 1) % 100)));\n rtl::Reference< Obj > xObj11(xCont->get(aKey1));\n {for (int j = 0; j < 50; ++j)\n rtl::Reference< Obj > xRef(xObj11);\n }\n rtl::Reference< Obj > xObj12(xCont->get(aKey1));\n {for (int j = 0; j < 50; ++j)\n rtl::Reference< Obj > xRef(xObj12);\n }\n\n rtl::OUString\n aKey2(aPrefix\n + rtl::OUString::valueOf(static_cast< sal_Int32 >(\n (i + 2) % 100)));\n rtl::Reference< Obj > xObj21(xCont->get(aKey2));\n {for (int j = 0; j < 50; ++j)\n rtl::Reference< Obj > xRef(xObj21);\n }\n rtl::Reference< Obj > xObj22(xCont->get(aKey2));\n {for (int j = 0; j < 50; ++j)\n rtl::Reference< Obj > xRef(xObj22);\n }\n\n rtl::OUString\n aKey3(aPrefix\n + rtl::OUString::valueOf(static_cast< sal_Int32 >(\n (i + 3) % 100)));\n rtl::Reference< Obj > xObj31(xCont->get(aKey3));\n {for (int j = 0; j < 50; ++j)\n rtl::Reference< Obj > xRef(xObj31);\n }\n rtl::Reference< Obj > xObj32(xCont->get(aKey3));\n {for (int j = 0; j < 50; ++j)\n rtl::Reference< Obj > xRef(xObj32);\n }\n\n rtl::OUString\n aKey4(aPrefix\n + rtl::OUString::valueOf(static_cast< sal_Int32 >(\n (i + 4) % 100)));\n rtl::Reference< Obj > xObj41(xCont->get(aKey4));\n {for (int j = 0; j < 50; ++j)\n rtl::Reference< Obj > xRef(xObj41);\n }\n rtl::Reference< Obj > xObj42(xCont->get(aKey4));\n {for (int j = 0; j < 50; ++j)\n rtl::Reference< Obj > xRef(xObj42);\n }\n }\n return osl_getGlobalTimer() - nTimer;\n}\n\n}\n\nint main()\n{\n \/\/ Use the second set of measurements, to avoid startup inaccuracies:\n for (int i = 0; i < 2; ++i)\n printf(\"Version 1: %lu ms.\\nVersion 2: %lu ms.\\nVersion 3: %lu ms.\\n\",\n static_cast< unsigned long >(\n test< ObjectContainer1,\n rtl::Reference< ObjectContainer1 >,\n Object1 >(0)),\n static_cast< unsigned long >(\n test< ObjectContainer2,\n std::auto_ptr< ObjectContainer2 >,\n Object2 >(0)),\n static_cast< unsigned long >(\n test< ObjectContainer3,\n rtl::Reference< ObjectContainer3 >,\n Object3 >(0)));\n return EXIT_SUCCESS;\n}\n\n\/\/ unxsols3.pro: Version 1: 9137 ms.\n\/\/ Version 2: 8634 ms.\n\/\/ Version 3: 3166 ms.\n\/\/\n\/\/ wntmsci7.pro: Version 1: 3846 ms.\n\/\/ Version 2: 5598 ms.\n\/\/ Version 3: 2704 ms.\n<|endoftext|>"} {"text":"<commit_before>\/**\n * Copyright 2013 Da Zheng\n *\n * This file is part of SA-GraphLib.\n *\n * SA-GraphLib is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * SA-GraphLib is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with SA-GraphLib. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n\n#include <signal.h>\n#include <google\/profiler.h>\n\n#include \"thread.h\"\n#include \"io_interface.h\"\n\n#include \"graph_engine.h\"\n#include \"graph_config.h\"\n\natomic_number<long> num_triangles;\natomic_number<long> num_working_vertices;\natomic_number<long> num_completed_vertices;\n\nclass triangle_vertex: public compute_vertex\n{\n\t\/\/ The number of required vertices to join with this vertex.\n\tint num_required;\n\t\/\/ The number of vertices that have joined with the vertex.\n\tint num_joined;\n\t\/\/ The number of vertices that have been asked to fetch.\n\tint num_fetched;\n\t\/\/ The number of triangles per vertex.\n\tint num_pv_triangles;\n\t\/\/ It contains part of in-edges.\n\t\/\/ We only use the neighbors whose ID is smaller than this vertex.\n\tstd::vector<vertex_id_t> in_edges;\n\t\/\/ It contains part of out-edges.\n\t\/\/ We only read neighbors whose ID is smaller than this vertex.\n\tstd::vector<vertex_id_t> out_edges;\npublic:\n\ttriangle_vertex(): compute_vertex(-1, -1, 0) {\n\t\tnum_required = 0;\n\t\tnum_joined = 0;\n\t\tnum_fetched = 0;\n\t\tnum_pv_triangles = 0;\n\t}\n\n\ttriangle_vertex(vertex_id_t id, off_t off, int size): compute_vertex(\n\t\t\tid, off, size) {\n\t\tnum_required = 0;\n\t\tnum_joined = 0;\n\t\tnum_fetched = 0;\n\t\tnum_pv_triangles = 0;\n\t}\n\n\tint count_triangle(const ext_mem_vertex &neighbor) const;\n\n\tvirtual bool has_required_vertices() const {\n\t\treturn num_fetched < num_required;\n\t}\n\n\tvirtual vertex_id_t get_next_required_vertex() {\n\t\treturn out_edges[num_fetched++];\n\t}\n\n\t\/\/ We only use the neighbors whose ID is smaller than this vertex.\n\tint get_required_edges(edge_type type, std::vector<vertex_id_t> &edges) {\n\t\tpage_byte_array::const_iterator<vertex_id_t> it = get_neigh_begin(type);\n\t\tpage_byte_array::const_iterator<vertex_id_t> end = get_neigh_end(type);\n\t\tint num = 0;\n\t\tfor (; it != end; ++it) {\n\t\t\tvertex_id_t id = *it;\n\t\t\tif (id < get_id()) {\n\t\t\t\tedges.push_back(id);\n\t\t\t\tnum++;\n\t\t\t}\n\t\t}\n\t\treturn num;\n\t}\n\n\tvoid run(graph_engine &graph, const page_vertex *vertices[], int num);\n};\n\nvoid triangle_vertex::run(graph_engine &graph, const page_vertex *vertices[],\n\t\t\tint num)\n{\n\t\/\/ If there aren't neighbors passed to the vertex's user code,\n\t\/\/ it's because the vertex doesn't have neighbors.\n\tif (num == 0) {\n\t\tassert(in_edges.size() == 0);\n\t\tassert(out_edges.size() == 0);\n\n\t\tlong ret = num_working_vertices.inc(1);\n\t\tif (ret % 100000 == 0)\n\t\t\tprintf(\"%ld working vertices\\n\", ret);\n\t\t\/\/ A vertex has to have in-edges and out-edges in order to form\n\t\t\/\/ a triangle. so we can simply skip the vertices that don't have\n\t\t\/\/ either of them.\n\t\tif (get_num_edges(edge_type::OUT_EDGE) == 0\n\t\t\t\t|| get_num_edges(edge_type::IN_EDGE) == 0) {\n\t\t\tlong ret = num_completed_vertices.inc(1);\n\t\t\tif (ret % 100000 == 0)\n\t\t\t\tprintf(\"%ld completed vertices, %ld triangles\\n\",\n\t\t\t\t\t\tret, num_triangles.get());\n\t\t\treturn;\n\t\t}\n\n\t\tthis->get_required_edges(edge_type::IN_EDGE, in_edges);\n\t\tthis->get_required_edges(edge_type::OUT_EDGE, out_edges);\n\t\tnum_required = out_edges.size();\n\t\tnum_joined = 0;\n\t\tnum_fetched = 0;\n\n\t\tif (in_edges.empty() || out_edges.empty()) {\n\t\t\tnum_required = 0;\n\t\t\tlong ret = num_completed_vertices.inc(1);\n\t\t\tif (ret % 100000 == 0)\n\t\t\t\tprintf(\"%ld completed vertices, %ld triangles\\n\",\n\t\t\t\t\t\tret, num_triangles.get());\n\t\t\tin_edges = std::vector<vertex_id_t>();\n\t\t\tout_edges = std::vector<vertex_id_t>();\n\t\t}\n\t\treturn;\n\t}\n\n\tnum_joined++;\n\tfor (int i = 0; i < num; i++) {\n\t\tconst page_vertex *v = vertices[i];\n\t\tstd::vector<vertex_id_t>::const_iterator this_it = in_edges.begin();\n\t\tstd::vector<vertex_id_t>::const_iterator this_end = in_edges.end();\n\t\tassert(v->get_id() != this->get_id());\n\n\t\tpage_byte_array::const_iterator<vertex_id_t> other_it\n\t\t\t= v->get_neigh_begin(edge_type::OUT_EDGE);\n\t\tpage_byte_array::const_iterator<vertex_id_t> other_end\n\t\t\t= v->get_neigh_end(edge_type::OUT_EDGE);\n\t\twhile (this_it != this_end && other_it != other_end) {\n\t\t\tvertex_id_t this_neighbor = *this_it;\n\t\t\tvertex_id_t neigh_neighbor = *other_it;\n\t\t\tif (this_neighbor == neigh_neighbor) {\n\t\t\t\t\/\/ skip loop\n\t\t\t\tif (neigh_neighbor != v->get_id()\n\t\t\t\t\t\t&& neigh_neighbor != this->get_id())\n\t\t\t\t\tnum_pv_triangles++;\n\t\t\t\t++this_it;\n\t\t\t\t++other_it;\n\t\t\t}\n\t\t\telse if (this_neighbor < neigh_neighbor)\n\t\t\t\t++this_it;\n\t\t\telse\n\t\t\t\t++other_it;\n\t\t}\n\t}\n\n\t\/\/ If we have seen all required neighbors, we have complete\n\t\/\/ the computation. We can release the memory now.\n\tif (num_joined == num_required) {\n\t\tlong ret = num_completed_vertices.inc(1);\n\t\tif (ret % 100000 == 0)\n\t\t\tprintf(\"%ld completed vertices, %ld triangles\\n\",\n\t\t\t\t\tret, num_triangles.get());\n\t\tin_edges = std::vector<vertex_id_t>();\n\t\tout_edges = std::vector<vertex_id_t>();\n\t\tnum_triangles.inc(num_pv_triangles);\n\t}\n}\n\nvoid int_handler(int sig_num)\n{\n\tif (!graph_conf.get_prof_file().empty())\n\t\tProfilerStop();\n\texit(0);\n}\n\nint main(int argc, char *argv[])\n{\n\tif (argc < 5) {\n\t\tfprintf(stderr, \"triangle-counting conf_file graph_file index_file directed\\n\");\n\t\tgraph_conf.print_help();\n\t\tparams.print_help();\n\t\texit(-1);\n\t}\n\n\tstd::string conf_file = argv[1];\n\tstd::string graph_file = argv[2];\n\tstd::string index_file = argv[3];\n\tbool directed = atoi(argv[4]);\n\n\tconfig_map configs(conf_file);\n\tconfigs.add_options(argv + 5, argc - 5);\n\tgraph_conf.init(configs);\n\tgraph_conf.print();\n\n\tsignal(SIGINT, int_handler);\n\tinit_io_system(configs);\n\n\tgraph_index *index = graph_index_impl<triangle_vertex>::create(index_file);\n\tgraph_engine *graph = graph_engine::create(graph_conf.get_num_threads(),\n\t\t\tparams.get_num_nodes(), graph_file, index, directed);\n\tgraph->set_required_neighbor_type(edge_type::OUT_EDGE);\n\tprintf(\"triangle counting starts\\n\");\n\tprintf(\"prof_file: %s\\n\", graph_conf.get_prof_file().c_str());\n\tif (!graph_conf.get_prof_file().empty())\n\t\tProfilerStart(graph_conf.get_prof_file().c_str());\n\n\tstruct timeval start, end;\n\tgettimeofday(&start, NULL);\n\tgraph->start_all();\n\tgraph->wait4complete();\n\tgettimeofday(&end, NULL);\n\n\tif (!graph_conf.get_prof_file().empty())\n\t\tProfilerStop();\n\tif (graph_conf.get_print_io_stat())\n\t\tprint_io_thread_stat();\n\tgraph->cleanup();\n\tprintf(\"There are %ld vertices\\n\", index->get_num_vertices());\n\tprintf(\"process %ld vertices and complete %ld vertices\\n\",\n\t\t\tnum_working_vertices.get(), num_completed_vertices.get());\n\tprintf(\"there are %ld triangles. It takes %f seconds\\n\",\n\t\t\tnum_triangles.get(), time_diff(start, end));\n}\n<commit_msg>[Graph]: check the state of a vertex in triangle counting.<commit_after>\/**\n * Copyright 2013 Da Zheng\n *\n * This file is part of SA-GraphLib.\n *\n * SA-GraphLib is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * SA-GraphLib is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with SA-GraphLib. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n\n#include <signal.h>\n#include <google\/profiler.h>\n\n#include \"thread.h\"\n#include \"io_interface.h\"\n\n#include \"graph_engine.h\"\n#include \"graph_config.h\"\n\natomic_number<long> num_triangles;\natomic_number<long> num_working_vertices;\natomic_number<long> num_completed_vertices;\n\nclass triangle_vertex: public compute_vertex\n{\n\t\/\/ The number of required vertices to join with this vertex.\n\tint num_required;\n\t\/\/ The number of vertices that have joined with the vertex.\n\tint num_joined;\n\t\/\/ The number of vertices that have been asked to fetch.\n\tint num_fetched;\n\t\/\/ The number of triangles per vertex.\n\tint num_pv_triangles;\n\t\/\/ It contains part of in-edges.\n\t\/\/ We only use the neighbors whose ID is smaller than this vertex.\n\tstd::vector<vertex_id_t> in_edges;\n\t\/\/ It contains part of out-edges.\n\t\/\/ We only read neighbors whose ID is smaller than this vertex.\n\tstd::vector<vertex_id_t> out_edges;\npublic:\n\ttriangle_vertex(): compute_vertex(-1, -1, 0) {\n\t\tnum_required = 0;\n\t\tnum_joined = 0;\n\t\tnum_fetched = 0;\n\t\tnum_pv_triangles = 0;\n\t}\n\n\ttriangle_vertex(vertex_id_t id, off_t off, int size): compute_vertex(\n\t\t\tid, off, size) {\n\t\tnum_required = 0;\n\t\tnum_joined = 0;\n\t\tnum_fetched = 0;\n\t\tnum_pv_triangles = 0;\n\t}\n\n\tint count_triangle(const ext_mem_vertex &neighbor) const;\n\n\tvirtual bool has_required_vertices() const {\n\t\treturn num_fetched < num_required;\n\t}\n\n\tvirtual vertex_id_t get_next_required_vertex() {\n\t\treturn out_edges[num_fetched++];\n\t}\n\n\t\/\/ We only use the neighbors whose ID is smaller than this vertex.\n\tint get_required_edges(edge_type type, std::vector<vertex_id_t> &edges) {\n\t\tpage_byte_array::const_iterator<vertex_id_t> it = get_neigh_begin(type);\n\t\tpage_byte_array::const_iterator<vertex_id_t> end = get_neigh_end(type);\n\t\tint num = 0;\n\t\tfor (; it != end; ++it) {\n\t\t\tvertex_id_t id = *it;\n\t\t\tif (id < get_id()) {\n\t\t\t\tedges.push_back(id);\n\t\t\t\tnum++;\n\t\t\t}\n\t\t}\n\t\treturn num;\n\t}\n\n\tvoid run(graph_engine &graph, const page_vertex *vertices[], int num);\n};\n\nvoid triangle_vertex::run(graph_engine &graph, const page_vertex *vertices[],\n\t\t\tint num)\n{\n\t\/\/ If there aren't neighbors passed to the vertex's user code,\n\t\/\/ it's because the vertex doesn't have neighbors.\n\tif (num == 0) {\n\t\tassert(in_edges.size() == 0);\n\t\tassert(out_edges.size() == 0);\n\t\tassert(num_joined == 0);\n\t\tassert(num_fetched == 0);\n\n\t\tlong ret = num_working_vertices.inc(1);\n\t\tif (ret % 100000 == 0)\n\t\t\tprintf(\"%ld working vertices\\n\", ret);\n\t\t\/\/ A vertex has to have in-edges and out-edges in order to form\n\t\t\/\/ a triangle. so we can simply skip the vertices that don't have\n\t\t\/\/ either of them.\n\t\tif (get_num_edges(edge_type::OUT_EDGE) == 0\n\t\t\t\t|| get_num_edges(edge_type::IN_EDGE) == 0) {\n\t\t\tlong ret = num_completed_vertices.inc(1);\n\t\t\tif (ret % 100000 == 0)\n\t\t\t\tprintf(\"%ld completed vertices, %ld triangles\\n\",\n\t\t\t\t\t\tret, num_triangles.get());\n\t\t\treturn;\n\t\t}\n\n\t\tthis->get_required_edges(edge_type::IN_EDGE, in_edges);\n\t\tthis->get_required_edges(edge_type::OUT_EDGE, out_edges);\n\t\tnum_required = out_edges.size();\n\n\t\tif (in_edges.empty() || out_edges.empty()) {\n\t\t\tnum_required = 0;\n\t\t\tlong ret = num_completed_vertices.inc(1);\n\t\t\tif (ret % 100000 == 0)\n\t\t\t\tprintf(\"%ld completed vertices, %ld triangles\\n\",\n\t\t\t\t\t\tret, num_triangles.get());\n\t\t\tin_edges = std::vector<vertex_id_t>();\n\t\t\tout_edges = std::vector<vertex_id_t>();\n\t\t}\n\t\treturn;\n\t}\n\n\tnum_joined++;\n\tfor (int i = 0; i < num; i++) {\n\t\tconst page_vertex *v = vertices[i];\n\t\tstd::vector<vertex_id_t>::const_iterator this_it = in_edges.begin();\n\t\tstd::vector<vertex_id_t>::const_iterator this_end = in_edges.end();\n\t\tassert(v->get_id() != this->get_id());\n\n\t\tpage_byte_array::const_iterator<vertex_id_t> other_it\n\t\t\t= v->get_neigh_begin(edge_type::OUT_EDGE);\n\t\tpage_byte_array::const_iterator<vertex_id_t> other_end\n\t\t\t= v->get_neigh_end(edge_type::OUT_EDGE);\n\t\twhile (this_it != this_end && other_it != other_end) {\n\t\t\tvertex_id_t this_neighbor = *this_it;\n\t\t\tvertex_id_t neigh_neighbor = *other_it;\n\t\t\tif (this_neighbor == neigh_neighbor) {\n\t\t\t\t\/\/ skip loop\n\t\t\t\tif (neigh_neighbor != v->get_id()\n\t\t\t\t\t\t&& neigh_neighbor != this->get_id())\n\t\t\t\t\tnum_pv_triangles++;\n\t\t\t\t++this_it;\n\t\t\t\t++other_it;\n\t\t\t}\n\t\t\telse if (this_neighbor < neigh_neighbor)\n\t\t\t\t++this_it;\n\t\t\telse\n\t\t\t\t++other_it;\n\t\t}\n\t}\n\n\t\/\/ If we have seen all required neighbors, we have complete\n\t\/\/ the computation. We can release the memory now.\n\tif (num_joined == num_required) {\n\t\tlong ret = num_completed_vertices.inc(1);\n\t\tif (ret % 100000 == 0)\n\t\t\tprintf(\"%ld completed vertices, %ld triangles\\n\",\n\t\t\t\t\tret, num_triangles.get());\n\t\tin_edges = std::vector<vertex_id_t>();\n\t\tout_edges = std::vector<vertex_id_t>();\n\t\tnum_triangles.inc(num_pv_triangles);\n\t}\n}\n\nvoid int_handler(int sig_num)\n{\n\tif (!graph_conf.get_prof_file().empty())\n\t\tProfilerStop();\n\texit(0);\n}\n\nint main(int argc, char *argv[])\n{\n\tif (argc < 5) {\n\t\tfprintf(stderr, \"triangle-counting conf_file graph_file index_file directed\\n\");\n\t\tgraph_conf.print_help();\n\t\tparams.print_help();\n\t\texit(-1);\n\t}\n\n\tstd::string conf_file = argv[1];\n\tstd::string graph_file = argv[2];\n\tstd::string index_file = argv[3];\n\tbool directed = atoi(argv[4]);\n\n\tconfig_map configs(conf_file);\n\tconfigs.add_options(argv + 5, argc - 5);\n\tgraph_conf.init(configs);\n\tgraph_conf.print();\n\n\tsignal(SIGINT, int_handler);\n\tinit_io_system(configs);\n\n\tgraph_index *index = graph_index_impl<triangle_vertex>::create(index_file);\n\tgraph_engine *graph = graph_engine::create(graph_conf.get_num_threads(),\n\t\t\tparams.get_num_nodes(), graph_file, index, directed);\n\tgraph->set_required_neighbor_type(edge_type::OUT_EDGE);\n\tprintf(\"triangle counting starts\\n\");\n\tprintf(\"prof_file: %s\\n\", graph_conf.get_prof_file().c_str());\n\tif (!graph_conf.get_prof_file().empty())\n\t\tProfilerStart(graph_conf.get_prof_file().c_str());\n\n\tstruct timeval start, end;\n\tgettimeofday(&start, NULL);\n\tgraph->start_all();\n\tgraph->wait4complete();\n\tgettimeofday(&end, NULL);\n\n\tif (!graph_conf.get_prof_file().empty())\n\t\tProfilerStop();\n\tif (graph_conf.get_print_io_stat())\n\t\tprint_io_thread_stat();\n\tgraph->cleanup();\n\tprintf(\"There are %ld vertices\\n\", index->get_num_vertices());\n\tprintf(\"process %ld vertices and complete %ld vertices\\n\",\n\t\t\tnum_working_vertices.get(), num_completed_vertices.get());\n\tprintf(\"there are %ld triangles. It takes %f seconds\\n\",\n\t\t\tnum_triangles.get(), time_diff(start, end));\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Convert any file descriptor to a pipe by splicing.\n *\n * author: Max Kellermann <mk@cm4all.com>\n *\/\n\n#ifdef __linux\n\n#include \"istream_pipe.hxx\"\n#include \"istream_internal.hxx\"\n#include \"fd_util.h\"\n#include \"direct.hxx\"\n#include \"pipe_stock.hxx\"\n#include \"stock.hxx\"\n#include \"gerrno.h\"\n#include \"util\/Cast.hxx\"\n\n#include <daemon\/log.h>\n\n#include <assert.h>\n#include <errno.h>\n#include <string.h>\n#include <fcntl.h>\n#include <unistd.h>\n\nstruct istream_pipe {\n struct istream output;\n struct istream *input;\n Stock *stock;\n StockItem *stock_item;\n int fds[2];\n size_t piped;\n};\n\nstatic void\npipe_close(struct istream_pipe *p)\n{\n if (p->stock != nullptr) {\n if (p->stock_item != nullptr)\n \/* reuse the pipe only if it's empty *\/\n stock_put(*p->stock_item, p->piped > 0);\n } else {\n if (p->fds[0] >= 0) {\n close(p->fds[0]);\n p->fds[0] = -1;\n }\n\n if (p->fds[1] >= 0) {\n close(p->fds[1]);\n p->fds[1] = -1;\n }\n }\n}\n\nstatic void\npipe_abort(struct istream_pipe *p, GError *error)\n{\n pipe_close(p);\n\n if (p->input != nullptr)\n istream_close_handler(p->input);\n\n istream_deinit_abort(&p->output, error);\n}\n\nstatic ssize_t\npipe_consume(struct istream_pipe *p)\n{\n ssize_t nbytes;\n\n assert(p->fds[0] >= 0);\n assert(p->piped > 0);\n assert(p->stock_item != nullptr || p->stock == nullptr);\n\n nbytes = istream_invoke_direct(&p->output, FdType::FD_PIPE, p->fds[0], p->piped);\n if (unlikely(nbytes == ISTREAM_RESULT_BLOCKING ||\n nbytes == ISTREAM_RESULT_CLOSED))\n \/* handler blocks (-2) or pipe was closed (-3) *\/\n return nbytes;\n\n if (unlikely(nbytes == ISTREAM_RESULT_ERRNO && errno != EAGAIN)) {\n GError *error = new_error_errno_msg(\"read from pipe failed\");\n pipe_abort(p, error);\n return ISTREAM_RESULT_CLOSED;\n }\n\n if (nbytes > 0) {\n assert((size_t)nbytes <= p->piped);\n p->piped -= (size_t)nbytes;\n\n if (p->piped == 0 && p->stock != nullptr) {\n \/* if the pipe was drained, return it to the stock, to\n make it available to other streams *\/\n\n stock_put(*p->stock_item, false);\n p->stock_item = nullptr;\n p->fds[0] = -1;\n p->fds[1] = -1;\n }\n\n if (p->piped == 0 && p->input == nullptr) {\n \/* p->input has already reported EOF, and we have been\n waiting for the pipe buffer to become empty *\/\n pipe_close(p);\n istream_deinit_eof(&p->output);\n return ISTREAM_RESULT_CLOSED;\n }\n }\n\n return nbytes;\n}\n\n\n\/*\n * istream handler\n *\n *\/\n\nstatic size_t\npipe_input_data(const void *data, size_t length, void *ctx)\n{\n struct istream_pipe *p = (struct istream_pipe *)ctx;\n\n assert(p->output.handler != nullptr);\n\n if (p->piped > 0) {\n ssize_t nbytes = pipe_consume(p);\n if (nbytes == ISTREAM_RESULT_CLOSED)\n return 0;\n\n if (p->piped > 0 || p->output.handler == nullptr)\n return 0;\n }\n\n assert(p->piped == 0);\n\n return istream_invoke_data(&p->output, data, length);\n}\n\nstatic bool\npipe_create(struct istream_pipe *p)\n{\n int ret;\n\n assert(p->fds[0] < 0);\n assert(p->fds[1] < 0);\n\n if (p->stock != nullptr) {\n assert(p->stock_item == nullptr);\n\n GError *error = nullptr;\n p->stock_item = stock_get_now(*p->stock, *p->output.pool, nullptr,\n &error);\n if (p->stock_item == nullptr) {\n daemon_log(1, \"%s\\n\", error->message);\n g_error_free(error);\n return false;\n }\n\n pipe_stock_item_get(p->stock_item, p->fds);\n } else {\n ret = pipe_cloexec_nonblock(p->fds);\n if (ret < 0) {\n daemon_log(1, \"pipe() failed: %s\\n\", strerror(errno));\n return false;\n }\n }\n\n return true;\n}\n\nstatic ssize_t\npipe_input_direct(FdType type, int fd, size_t max_length, void *ctx)\n{\n struct istream_pipe *p = (struct istream_pipe *)ctx;\n ssize_t nbytes;\n\n assert(p->output.handler != nullptr);\n assert(p->output.handler->direct != nullptr);\n assert(istream_check_direct(&p->output, FdType::FD_PIPE));\n\n if (p->piped > 0) {\n nbytes = pipe_consume(p);\n if (nbytes <= 0)\n return nbytes;\n\n if (p->piped > 0)\n \/* if the pipe still isn't empty, we can't start reading\n new input *\/\n return ISTREAM_RESULT_BLOCKING;\n }\n\n if (istream_check_direct(&p->output, type))\n \/* already supported by handler (maybe already a pipe) - no\n need for wrapping it into a pipe *\/\n return istream_invoke_direct(&p->output, type, fd, max_length);\n\n assert((type & ISTREAM_TO_PIPE) == type);\n\n if (p->fds[1] < 0 && !pipe_create(p))\n return ISTREAM_RESULT_CLOSED;\n\n nbytes = splice(fd, nullptr, p->fds[1], nullptr, max_length,\n SPLICE_F_NONBLOCK | SPLICE_F_MOVE);\n \/* don't check EAGAIN here (and don't return -2). We assume that\n splicing to the pipe cannot possibly block, since we flushed\n the pipe; assume that it can only be the source file which is\n blocking *\/\n if (nbytes <= 0)\n return nbytes;\n\n assert(p->piped == 0);\n p->piped = (size_t)nbytes;\n\n if (pipe_consume(p) == ISTREAM_RESULT_CLOSED)\n return ISTREAM_RESULT_CLOSED;\n\n return nbytes;\n}\n\nstatic void\npipe_input_eof(void *ctx)\n{\n struct istream_pipe *p = (struct istream_pipe *)ctx;\n\n p->input = nullptr;\n\n if (p->stock == nullptr && p->fds[1] >= 0) {\n close(p->fds[1]);\n p->fds[1] = -1;\n }\n\n if (p->piped == 0) {\n pipe_close(p);\n istream_deinit_eof(&p->output);\n }\n}\n\nstatic void\npipe_input_abort(GError *error, void *ctx)\n{\n struct istream_pipe *p = (struct istream_pipe *)ctx;\n\n pipe_close(p);\n\n p->input = nullptr;\n istream_deinit_abort(&p->output, error);\n}\n\nstatic const struct istream_handler pipe_input_handler = {\n .data = pipe_input_data,\n .direct = pipe_input_direct,\n .eof = pipe_input_eof,\n .abort = pipe_input_abort,\n};\n\n\n\/*\n * istream implementation\n *\n *\/\n\nstatic inline struct istream_pipe *\nistream_to_pipe(struct istream *istream)\n{\n return &ContainerCast2(*istream, &istream_pipe::output);\n}\n\nstatic off_t\nistream_pipe_available(struct istream *istream, bool partial)\n{\n struct istream_pipe *p = istream_to_pipe(istream);\n\n if (likely(p->input != nullptr)) {\n off_t available = istream_available(p->input, partial);\n if (p->piped > 0) {\n if (available != -1)\n available += p->piped;\n else if (partial)\n available = p->piped;\n }\n\n return available;\n } else {\n assert(p->piped > 0);\n\n return p->piped;\n }\n}\n\nstatic void\nistream_pipe_read(struct istream *istream)\n{\n struct istream_pipe *p = istream_to_pipe(istream);\n\n if (p->piped > 0 && (pipe_consume(p) <= 0 || p->piped > 0))\n return;\n\n \/* at this point, the pipe must be flushed - if the pipe is\n flushed, this stream is either closed or there must be an input\n stream *\/\n assert(p->input != nullptr);\n\n auto mask = p->output.handler_direct;\n if (mask & FdType::FD_PIPE)\n \/* if the handler supports the pipe, we offer our services *\/\n mask |= ISTREAM_TO_PIPE;\n\n istream_handler_set_direct(p->input, mask);\n istream_read(p->input);\n}\n\nstatic int\nistream_pipe_as_fd(struct istream *istream)\n{\n struct istream_pipe *p = istream_to_pipe(istream);\n\n if (p->piped > 0)\n \/* need to flush the pipe buffer first *\/\n return -1;\n\n int fd = istream_as_fd(p->input);\n if (fd >= 0) {\n pipe_close(p);\n istream_deinit(&p->output);\n }\n\n return fd;\n}\n\nstatic void\nistream_pipe_close(struct istream *istream)\n{\n struct istream_pipe *p = istream_to_pipe(istream);\n\n pipe_close(p);\n\n if (p->input != nullptr)\n istream_close_handler(p->input);\n\n istream_deinit(&p->output);\n}\n\nstatic const struct istream_class istream_pipe = {\n .available = istream_pipe_available,\n .read = istream_pipe_read,\n .as_fd = istream_pipe_as_fd,\n .close = istream_pipe_close,\n};\n\n\n\/*\n * constructor\n *\n *\/\n\nstruct istream *\nistream_pipe_new(struct pool *pool, struct istream *input,\n Stock *pipe_stock)\n{\n struct istream_pipe *p = istream_new_macro(pool, pipe);\n\n assert(input != nullptr);\n assert(!istream_has_handler(input));\n\n p->stock = pipe_stock;\n p->stock_item = nullptr;\n p->fds[0] = -1;\n p->fds[1] = -1;\n p->piped = 0;\n\n istream_assign_handler(&p->input, input,\n &pipe_input_handler, p,\n 0);\n\n return &p->output;\n}\n\n#endif\n<commit_msg>istream\/pipe: make variables more local<commit_after>\/*\n * Convert any file descriptor to a pipe by splicing.\n *\n * author: Max Kellermann <mk@cm4all.com>\n *\/\n\n#ifdef __linux\n\n#include \"istream_pipe.hxx\"\n#include \"istream_internal.hxx\"\n#include \"fd_util.h\"\n#include \"direct.hxx\"\n#include \"pipe_stock.hxx\"\n#include \"stock.hxx\"\n#include \"gerrno.h\"\n#include \"util\/Cast.hxx\"\n\n#include <daemon\/log.h>\n\n#include <assert.h>\n#include <errno.h>\n#include <string.h>\n#include <fcntl.h>\n#include <unistd.h>\n\nstruct istream_pipe {\n struct istream output;\n struct istream *input;\n Stock *stock;\n StockItem *stock_item;\n int fds[2];\n size_t piped;\n};\n\nstatic void\npipe_close(struct istream_pipe *p)\n{\n if (p->stock != nullptr) {\n if (p->stock_item != nullptr)\n \/* reuse the pipe only if it's empty *\/\n stock_put(*p->stock_item, p->piped > 0);\n } else {\n if (p->fds[0] >= 0) {\n close(p->fds[0]);\n p->fds[0] = -1;\n }\n\n if (p->fds[1] >= 0) {\n close(p->fds[1]);\n p->fds[1] = -1;\n }\n }\n}\n\nstatic void\npipe_abort(struct istream_pipe *p, GError *error)\n{\n pipe_close(p);\n\n if (p->input != nullptr)\n istream_close_handler(p->input);\n\n istream_deinit_abort(&p->output, error);\n}\n\nstatic ssize_t\npipe_consume(struct istream_pipe *p)\n{\n assert(p->fds[0] >= 0);\n assert(p->piped > 0);\n assert(p->stock_item != nullptr || p->stock == nullptr);\n\n ssize_t nbytes = istream_invoke_direct(&p->output, FdType::FD_PIPE,\n p->fds[0], p->piped);\n if (unlikely(nbytes == ISTREAM_RESULT_BLOCKING ||\n nbytes == ISTREAM_RESULT_CLOSED))\n \/* handler blocks (-2) or pipe was closed (-3) *\/\n return nbytes;\n\n if (unlikely(nbytes == ISTREAM_RESULT_ERRNO && errno != EAGAIN)) {\n GError *error = new_error_errno_msg(\"read from pipe failed\");\n pipe_abort(p, error);\n return ISTREAM_RESULT_CLOSED;\n }\n\n if (nbytes > 0) {\n assert((size_t)nbytes <= p->piped);\n p->piped -= (size_t)nbytes;\n\n if (p->piped == 0 && p->stock != nullptr) {\n \/* if the pipe was drained, return it to the stock, to\n make it available to other streams *\/\n\n stock_put(*p->stock_item, false);\n p->stock_item = nullptr;\n p->fds[0] = -1;\n p->fds[1] = -1;\n }\n\n if (p->piped == 0 && p->input == nullptr) {\n \/* p->input has already reported EOF, and we have been\n waiting for the pipe buffer to become empty *\/\n pipe_close(p);\n istream_deinit_eof(&p->output);\n return ISTREAM_RESULT_CLOSED;\n }\n }\n\n return nbytes;\n}\n\n\n\/*\n * istream handler\n *\n *\/\n\nstatic size_t\npipe_input_data(const void *data, size_t length, void *ctx)\n{\n struct istream_pipe *p = (struct istream_pipe *)ctx;\n\n assert(p->output.handler != nullptr);\n\n if (p->piped > 0) {\n ssize_t nbytes = pipe_consume(p);\n if (nbytes == ISTREAM_RESULT_CLOSED)\n return 0;\n\n if (p->piped > 0 || p->output.handler == nullptr)\n return 0;\n }\n\n assert(p->piped == 0);\n\n return istream_invoke_data(&p->output, data, length);\n}\n\nstatic bool\npipe_create(struct istream_pipe *p)\n{\n assert(p->fds[0] < 0);\n assert(p->fds[1] < 0);\n\n if (p->stock != nullptr) {\n assert(p->stock_item == nullptr);\n\n GError *error = nullptr;\n p->stock_item = stock_get_now(*p->stock, *p->output.pool, nullptr,\n &error);\n if (p->stock_item == nullptr) {\n daemon_log(1, \"%s\\n\", error->message);\n g_error_free(error);\n return false;\n }\n\n pipe_stock_item_get(p->stock_item, p->fds);\n } else {\n if (pipe_cloexec_nonblock(p->fds) < 0) {\n daemon_log(1, \"pipe() failed: %s\\n\", strerror(errno));\n return false;\n }\n }\n\n return true;\n}\n\nstatic ssize_t\npipe_input_direct(FdType type, int fd, size_t max_length, void *ctx)\n{\n struct istream_pipe *p = (struct istream_pipe *)ctx;\n\n assert(p->output.handler != nullptr);\n assert(p->output.handler->direct != nullptr);\n assert(istream_check_direct(&p->output, FdType::FD_PIPE));\n\n if (p->piped > 0) {\n ssize_t nbytes = pipe_consume(p);\n if (nbytes <= 0)\n return nbytes;\n\n if (p->piped > 0)\n \/* if the pipe still isn't empty, we can't start reading\n new input *\/\n return ISTREAM_RESULT_BLOCKING;\n }\n\n if (istream_check_direct(&p->output, type))\n \/* already supported by handler (maybe already a pipe) - no\n need for wrapping it into a pipe *\/\n return istream_invoke_direct(&p->output, type, fd, max_length);\n\n assert((type & ISTREAM_TO_PIPE) == type);\n\n if (p->fds[1] < 0 && !pipe_create(p))\n return ISTREAM_RESULT_CLOSED;\n\n ssize_t nbytes = splice(fd, nullptr, p->fds[1], nullptr, max_length,\n SPLICE_F_NONBLOCK | SPLICE_F_MOVE);\n \/* don't check EAGAIN here (and don't return -2). We assume that\n splicing to the pipe cannot possibly block, since we flushed\n the pipe; assume that it can only be the source file which is\n blocking *\/\n if (nbytes <= 0)\n return nbytes;\n\n assert(p->piped == 0);\n p->piped = (size_t)nbytes;\n\n if (pipe_consume(p) == ISTREAM_RESULT_CLOSED)\n return ISTREAM_RESULT_CLOSED;\n\n return nbytes;\n}\n\nstatic void\npipe_input_eof(void *ctx)\n{\n struct istream_pipe *p = (struct istream_pipe *)ctx;\n\n p->input = nullptr;\n\n if (p->stock == nullptr && p->fds[1] >= 0) {\n close(p->fds[1]);\n p->fds[1] = -1;\n }\n\n if (p->piped == 0) {\n pipe_close(p);\n istream_deinit_eof(&p->output);\n }\n}\n\nstatic void\npipe_input_abort(GError *error, void *ctx)\n{\n struct istream_pipe *p = (struct istream_pipe *)ctx;\n\n pipe_close(p);\n\n p->input = nullptr;\n istream_deinit_abort(&p->output, error);\n}\n\nstatic const struct istream_handler pipe_input_handler = {\n .data = pipe_input_data,\n .direct = pipe_input_direct,\n .eof = pipe_input_eof,\n .abort = pipe_input_abort,\n};\n\n\n\/*\n * istream implementation\n *\n *\/\n\nstatic inline struct istream_pipe *\nistream_to_pipe(struct istream *istream)\n{\n return &ContainerCast2(*istream, &istream_pipe::output);\n}\n\nstatic off_t\nistream_pipe_available(struct istream *istream, bool partial)\n{\n struct istream_pipe *p = istream_to_pipe(istream);\n\n if (likely(p->input != nullptr)) {\n off_t available = istream_available(p->input, partial);\n if (p->piped > 0) {\n if (available != -1)\n available += p->piped;\n else if (partial)\n available = p->piped;\n }\n\n return available;\n } else {\n assert(p->piped > 0);\n\n return p->piped;\n }\n}\n\nstatic void\nistream_pipe_read(struct istream *istream)\n{\n struct istream_pipe *p = istream_to_pipe(istream);\n\n if (p->piped > 0 && (pipe_consume(p) <= 0 || p->piped > 0))\n return;\n\n \/* at this point, the pipe must be flushed - if the pipe is\n flushed, this stream is either closed or there must be an input\n stream *\/\n assert(p->input != nullptr);\n\n auto mask = p->output.handler_direct;\n if (mask & FdType::FD_PIPE)\n \/* if the handler supports the pipe, we offer our services *\/\n mask |= ISTREAM_TO_PIPE;\n\n istream_handler_set_direct(p->input, mask);\n istream_read(p->input);\n}\n\nstatic int\nistream_pipe_as_fd(struct istream *istream)\n{\n struct istream_pipe *p = istream_to_pipe(istream);\n\n if (p->piped > 0)\n \/* need to flush the pipe buffer first *\/\n return -1;\n\n int fd = istream_as_fd(p->input);\n if (fd >= 0) {\n pipe_close(p);\n istream_deinit(&p->output);\n }\n\n return fd;\n}\n\nstatic void\nistream_pipe_close(struct istream *istream)\n{\n struct istream_pipe *p = istream_to_pipe(istream);\n\n pipe_close(p);\n\n if (p->input != nullptr)\n istream_close_handler(p->input);\n\n istream_deinit(&p->output);\n}\n\nstatic const struct istream_class istream_pipe = {\n .available = istream_pipe_available,\n .read = istream_pipe_read,\n .as_fd = istream_pipe_as_fd,\n .close = istream_pipe_close,\n};\n\n\n\/*\n * constructor\n *\n *\/\n\nstruct istream *\nistream_pipe_new(struct pool *pool, struct istream *input,\n Stock *pipe_stock)\n{\n struct istream_pipe *p = istream_new_macro(pool, pipe);\n\n assert(input != nullptr);\n assert(!istream_has_handler(input));\n\n p->stock = pipe_stock;\n p->stock_item = nullptr;\n p->fds[0] = -1;\n p->fds[1] = -1;\n p->piped = 0;\n\n istream_assign_handler(&p->input, input,\n &pipe_input_handler, p,\n 0);\n\n return &p->output;\n}\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ This file is part of the Marble Desktop Globe.\n\/\/\n\/\/ This program is free software licensed under the GNU LGPL. You can\n\/\/ find a copy of this license in LICENSE.txt in the top directory of\n\/\/ the source code.\n\/\/\n\/\/ Copyright 2007 Andrew Manson <g.real.ate@gmail.com>\n\/\/ Copyright 2009 Eckhart Wörner <ewoerner@kde.org>\n\/\/ Copyright 2010 Thibaut Gridel <tgridel@free.fr>\n\/\/\n\n#include \"PositionTracking.h\"\n\n#include \"GeoDataDocument.h\"\n#include \"GeoDataPlacemark.h\"\n#include \"GeoDataStyle.h\"\n#include \"GeoDataStyleMap.h\"\n#include \"AbstractProjection.h\"\n#include \"FileManager.h\"\n#include \"MarbleMath.h\"\n#include \"MarbleDebug.h\"\n#include \"PositionProviderPlugin.h\"\n\n#include \"PositionTracking_p.h\"\n\nusing namespace Marble;\n\nvoid PositionTrackingPrivate::setPosition( GeoDataCoordinates position,\n GeoDataAccuracy accuracy )\n{\n Q_UNUSED( accuracy );\n if ( m_positionProvider && m_positionProvider->status() ==\n PositionProviderStatusAvailable )\n {\n GeoDataPlacemark *placemark = static_cast<GeoDataPlacemark*>(m_document->child(m_document->size()-1));\n \/\/GeoDataMultiGeometry *geometry = static_cast<GeoDataMultiGeometry*>(placemark->geometry());\n m_currentLineString->append(position);\n\n \/\/if the position has moved then update the current position\n if ( !( m_gpsCurrentPosition ==\n position ) )\n {\n placemark = static_cast<GeoDataPlacemark*>(m_document->child(0));\n placemark->setCoordinate(position);\n m_gpsCurrentPosition = position;\n qreal speed = m_positionProvider->speed();\n emit gpsLocation( position, speed );\n }\n }\n}\n\n\nvoid PositionTrackingPrivate::setStatus( PositionProviderStatus status )\n{\n if (status == PositionProviderStatusAvailable) {\n Q_ASSERT(m_document);\n GeoDataPlacemark *placemark = static_cast<GeoDataPlacemark*>(m_document->child(m_document->size()-1));\n GeoDataMultiGeometry *multiGeometry = static_cast<GeoDataMultiGeometry*>(placemark->geometry());\n m_currentLineString = new GeoDataLineString;\n multiGeometry->append(m_currentLineString);\n }\n\n emit statusChanged( status );\n}\n\nPositionTracking::PositionTracking( FileManager *fileManager,\n QObject *parent )\n : QObject( parent ), d (new PositionTrackingPrivate(fileManager, parent))\n{\n\n connect( d, SIGNAL( gpsLocation(GeoDataCoordinates,qreal) ),\n this, SIGNAL( gpsLocation(GeoDataCoordinates,qreal) ));\n connect( d, SIGNAL( statusChanged(PositionProviderStatus)),\n this, SIGNAL( statusChanged(PositionProviderStatus) ) );\n\n d->m_document = new GeoDataDocument();\n d->m_document->setName(\"Position Tracking\");\n\n \/\/ First point is current position\n GeoDataPlacemark *placemark = new GeoDataPlacemark;\n placemark->setName(\"Current Position\");\n placemark->setVisible(false);\n d->m_document->append(placemark);\n\n \/\/ Second point is position track\n placemark = new GeoDataPlacemark;\n GeoDataMultiGeometry *multiGeometry = new GeoDataMultiGeometry;\n d->m_currentLineString = new GeoDataLineString;\n\n multiGeometry->append(d->m_currentLineString);\n placemark->setGeometry(multiGeometry);\n placemark->setName(\"Current Track\");\n\n GeoDataStyle style;\n GeoDataLineStyle lineStyle;\n lineStyle.setColor( oxygenBrickRed4 );\n lineStyle.setWidth(2);\n style.setLineStyle(lineStyle);\n style.setStyleId(\"track\");\n\n GeoDataStyleMap styleMap;\n styleMap.setStyleId(\"map-track\");\n styleMap.insert(\"normal\", QString(\"#\").append(style.styleId()));\n d->m_document->addStyleMap(styleMap);\n d->m_document->addStyle(style);\n\n placemark->setStyleUrl(QString(\"#\").append(styleMap.styleId()));\n d->m_document->append(placemark);\n\n d->m_fileManager->addGeoDataDocument(d->m_document);\n}\n\n\nPositionTracking::~PositionTracking()\n{\n delete d;\n}\n\nvoid PositionTracking::setPositionProviderPlugin( PositionProviderPlugin* plugin )\n{\n if ( d->m_positionProvider ) {\n d->m_positionProvider->deleteLater();\n }\n\n d->m_positionProvider = plugin;\n\n if ( d->m_positionProvider ) {\n d->m_positionProvider->setParent( this );\n mDebug() << \"Initializing position provider:\" << d->m_positionProvider->name();\n connect( d->m_positionProvider, SIGNAL( statusChanged( PositionProviderStatus ) ),\n d, SLOT( setStatus(PositionProviderStatus) ) );\n connect( d->m_positionProvider, SIGNAL( positionChanged( GeoDataCoordinates,GeoDataAccuracy ) ),\n d, SLOT( setPosition( GeoDataCoordinates,GeoDataAccuracy ) ) );\n\n d->m_positionProvider->initialize();\n }\n emit positionProviderPluginChanged( plugin );\n}\n\nQString PositionTracking::error() const\n{\n return d->m_positionProvider ? d->m_positionProvider->error() : QString();\n}\n\n\n\/\/get speed from provider\nqreal PositionTracking::speed() const\n{\n return d->m_positionProvider ? d->m_positionProvider->speed() : 0 ;\n}\n\n\/\/get direction from provider\nqreal PositionTracking::direction() const\n{\n return d->m_positionProvider ? d->m_positionProvider->direction() : 0 ;\n}\n\nbool PositionTracking::trackVisible() const\n{\n return d->m_document->isVisible();\n}\n\nvoid PositionTracking::setTrackVisible( bool visible )\n{\n d->m_document->setVisible( visible );\n}\n\nvoid PositionTracking::clearTrack()\n{\n GeoDataPlacemark *placemark = static_cast<GeoDataPlacemark*>(d->m_document->child(d->m_document->size()-1));\n GeoDataMultiGeometry *multiGeometry = static_cast<GeoDataMultiGeometry*>(placemark->geometry());\n d->m_currentLineString = new GeoDataLineString;\n multiGeometry->clear();\n multiGeometry->append(d->m_currentLineString);\n\n}\n\n#include \"PositionTracking.moc\"\n#include \"PositionTracking_p.moc\"\n<commit_msg>Use an alpha value and a width of the track that match the parameters of the route.<commit_after>\/\/\n\/\/ This file is part of the Marble Desktop Globe.\n\/\/\n\/\/ This program is free software licensed under the GNU LGPL. You can\n\/\/ find a copy of this license in LICENSE.txt in the top directory of\n\/\/ the source code.\n\/\/\n\/\/ Copyright 2007 Andrew Manson <g.real.ate@gmail.com>\n\/\/ Copyright 2009 Eckhart Wörner <ewoerner@kde.org>\n\/\/ Copyright 2010 Thibaut Gridel <tgridel@free.fr>\n\/\/\n\n#include \"PositionTracking.h\"\n\n#include \"GeoDataDocument.h\"\n#include \"GeoDataPlacemark.h\"\n#include \"GeoDataStyle.h\"\n#include \"GeoDataStyleMap.h\"\n#include \"AbstractProjection.h\"\n#include \"FileManager.h\"\n#include \"MarbleMath.h\"\n#include \"MarbleDebug.h\"\n#include \"PositionProviderPlugin.h\"\n\n#include \"PositionTracking_p.h\"\n\nusing namespace Marble;\n\nvoid PositionTrackingPrivate::setPosition( GeoDataCoordinates position,\n GeoDataAccuracy accuracy )\n{\n Q_UNUSED( accuracy );\n if ( m_positionProvider && m_positionProvider->status() ==\n PositionProviderStatusAvailable )\n {\n GeoDataPlacemark *placemark = static_cast<GeoDataPlacemark*>(m_document->child(m_document->size()-1));\n \/\/GeoDataMultiGeometry *geometry = static_cast<GeoDataMultiGeometry*>(placemark->geometry());\n m_currentLineString->append(position);\n\n \/\/if the position has moved then update the current position\n if ( !( m_gpsCurrentPosition ==\n position ) )\n {\n placemark = static_cast<GeoDataPlacemark*>(m_document->child(0));\n placemark->setCoordinate(position);\n m_gpsCurrentPosition = position;\n qreal speed = m_positionProvider->speed();\n emit gpsLocation( position, speed );\n }\n }\n}\n\n\nvoid PositionTrackingPrivate::setStatus( PositionProviderStatus status )\n{\n if (status == PositionProviderStatusAvailable) {\n Q_ASSERT(m_document);\n GeoDataPlacemark *placemark = static_cast<GeoDataPlacemark*>(m_document->child(m_document->size()-1));\n GeoDataMultiGeometry *multiGeometry = static_cast<GeoDataMultiGeometry*>(placemark->geometry());\n m_currentLineString = new GeoDataLineString;\n multiGeometry->append(m_currentLineString);\n }\n\n emit statusChanged( status );\n}\n\nPositionTracking::PositionTracking( FileManager *fileManager,\n QObject *parent )\n : QObject( parent ), d (new PositionTrackingPrivate(fileManager, parent))\n{\n\n connect( d, SIGNAL( gpsLocation(GeoDataCoordinates,qreal) ),\n this, SIGNAL( gpsLocation(GeoDataCoordinates,qreal) ));\n connect( d, SIGNAL( statusChanged(PositionProviderStatus)),\n this, SIGNAL( statusChanged(PositionProviderStatus) ) );\n\n d->m_document = new GeoDataDocument();\n d->m_document->setName(\"Position Tracking\");\n\n \/\/ First point is current position\n GeoDataPlacemark *placemark = new GeoDataPlacemark;\n placemark->setName(\"Current Position\");\n placemark->setVisible(false);\n d->m_document->append(placemark);\n\n \/\/ Second point is position track\n placemark = new GeoDataPlacemark;\n GeoDataMultiGeometry *multiGeometry = new GeoDataMultiGeometry;\n d->m_currentLineString = new GeoDataLineString;\n\n multiGeometry->append(d->m_currentLineString);\n placemark->setGeometry(multiGeometry);\n placemark->setName(\"Current Track\");\n\n GeoDataStyle style;\n GeoDataLineStyle lineStyle;\n QColor transparentRed = oxygenBrickRed4;\n transparentRed.setAlpha( 200 );\n lineStyle.setColor( transparentRed );\n lineStyle.setWidth( 4 );\n style.setLineStyle(lineStyle);\n style.setStyleId(\"track\");\n\n GeoDataStyleMap styleMap;\n styleMap.setStyleId(\"map-track\");\n styleMap.insert(\"normal\", QString(\"#\").append(style.styleId()));\n d->m_document->addStyleMap(styleMap);\n d->m_document->addStyle(style);\n\n placemark->setStyleUrl(QString(\"#\").append(styleMap.styleId()));\n d->m_document->append(placemark);\n\n d->m_fileManager->addGeoDataDocument(d->m_document);\n}\n\n\nPositionTracking::~PositionTracking()\n{\n delete d;\n}\n\nvoid PositionTracking::setPositionProviderPlugin( PositionProviderPlugin* plugin )\n{\n if ( d->m_positionProvider ) {\n d->m_positionProvider->deleteLater();\n }\n\n d->m_positionProvider = plugin;\n\n if ( d->m_positionProvider ) {\n d->m_positionProvider->setParent( this );\n mDebug() << \"Initializing position provider:\" << d->m_positionProvider->name();\n connect( d->m_positionProvider, SIGNAL( statusChanged( PositionProviderStatus ) ),\n d, SLOT( setStatus(PositionProviderStatus) ) );\n connect( d->m_positionProvider, SIGNAL( positionChanged( GeoDataCoordinates,GeoDataAccuracy ) ),\n d, SLOT( setPosition( GeoDataCoordinates,GeoDataAccuracy ) ) );\n\n d->m_positionProvider->initialize();\n }\n emit positionProviderPluginChanged( plugin );\n}\n\nQString PositionTracking::error() const\n{\n return d->m_positionProvider ? d->m_positionProvider->error() : QString();\n}\n\n\n\/\/get speed from provider\nqreal PositionTracking::speed() const\n{\n return d->m_positionProvider ? d->m_positionProvider->speed() : 0 ;\n}\n\n\/\/get direction from provider\nqreal PositionTracking::direction() const\n{\n return d->m_positionProvider ? d->m_positionProvider->direction() : 0 ;\n}\n\nbool PositionTracking::trackVisible() const\n{\n return d->m_document->isVisible();\n}\n\nvoid PositionTracking::setTrackVisible( bool visible )\n{\n d->m_document->setVisible( visible );\n}\n\nvoid PositionTracking::clearTrack()\n{\n GeoDataPlacemark *placemark = static_cast<GeoDataPlacemark*>(d->m_document->child(d->m_document->size()-1));\n GeoDataMultiGeometry *multiGeometry = static_cast<GeoDataMultiGeometry*>(placemark->geometry());\n d->m_currentLineString = new GeoDataLineString;\n multiGeometry->clear();\n multiGeometry->append(d->m_currentLineString);\n\n}\n\n#include \"PositionTracking.moc\"\n#include \"PositionTracking_p.moc\"\n<|endoftext|>"} {"text":"<commit_before>\/**\n * This file is part of the Marble Desktop Globe.\n *\n * Copyright 2005-2007 Torsten Rahn <tackat@kde.org>\"\n * Copyright 2007 Inge Wallin <ingwa@kde.org>\"\n * Copyright 2008 Patrick Spendrin <ps_ml@gmx.de>\"\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Library General Public\n * License as published by the Free Software Foundation; either\n * version 2 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Library General Public License for more details.\n *\n * You should have received a copy of the GNU Library General Public License\n * along with this library; see the file COPYING.LIB. If not, write to\n * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,\n * Boston, MA 02110-1301, USA.\n *\/\n\n#include \"TileLoaderHelper.h\"\n\n#include <cmath>\n\n#include <QtCore\/QDebug>\n\n#include \"GeoSceneTexture.h\"\n#include \"global.h\"\n\nint TileLoaderHelper::levelToRow( int level )\n{\n if ( level < 0 ) {\n qDebug() << QString( \"TileLoaderHelper::levelToRow(): Invalid level: %1\" )\n .arg( level );\n return 0;\n }\n return (int)std::pow( 2.0, (double)( level ) );\n}\n\nint TileLoaderHelper::levelToColumn( int level )\n{\n if ( level < 0 ) {\n qDebug() << QString( \"TileLoaderHelper::levelToColumn(): Invalid level: %1\" )\n .arg( level );\n return 0;\n }\n return (int)std::pow( 2.0, (double)( level + 1 ) );\n}\n\nint TileLoaderHelper::rowToLevel( int row )\n{\n if ( row < 1 ) {\n qDebug() << QString( \"TileLoaderHelper::rowToLevel(): Invalid number of rows: %1\" )\n .arg( row );\n return 0;\n }\n return (int)( std::log( (double)row ) \/ std::log( (double)2.0 ) );\n}\n\nint TileLoaderHelper::columnToLevel( int column )\n{\n if ( column < 2 ) {\n qDebug() << QString( \"TileLoaderHelper::columnToLevel(): Invalid number of columns: %1\" )\n .arg( column );\n return 0;\n }\n return (int)( std::log( (double)(column \/ 2) ) \/ std::log( (double)2.0 ) );\n}\n\nQString TileLoaderHelper::relativeTileFileName( GeoSceneTexture *textureLayer, int level, int x,\n int y )\n{\n QString relFileName;\n if ( textureLayer ) {\n const QString suffix = textureLayer->fileFormat().toLower();\n switch ( textureLayer->storageLayoutMode() ) {\n case GeoSceneTexture::Marble:\n \/\/ FIXME: use format information from GeoSceneTexturex\n relFileName = QString( \"%1\/%2\/%3\/%3_%4.%5\" )\n .arg( themeStr( textureLayer ) )\n .arg( level )\n .arg( y, tileDigits, 10, QChar('0') )\n .arg( x, tileDigits, 10, QChar('0') )\n .arg( suffix );\n break;\n case GeoSceneTexture::OpenStreetMap:\n \/\/ FIXME: use format information from GeoSceneTexturex\n relFileName = QString( \"%1\/%2\/%3\/%4.%5\" )\n .arg( themeStr( textureLayer ) )\n .arg( level )\n .arg( x )\n .arg( y )\n .arg( suffix );\n break;\n }\n }\n return relFileName;\n}\n\nQString TileLoaderHelper::themeStr( GeoSceneTexture *textureLayer )\n{\n QString oldThemeStr;\n\n if ( textureLayer ) {\n oldThemeStr = \"maps\/\" + textureLayer->sourceDir();\n }\n\n return oldThemeStr;\n}\n<commit_msg>Remove FIXME comments.<commit_after>\/**\n * This file is part of the Marble Desktop Globe.\n *\n * Copyright 2005-2007 Torsten Rahn <tackat@kde.org>\"\n * Copyright 2007 Inge Wallin <ingwa@kde.org>\"\n * Copyright 2008 Patrick Spendrin <ps_ml@gmx.de>\"\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Library General Public\n * License as published by the Free Software Foundation; either\n * version 2 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Library General Public License for more details.\n *\n * You should have received a copy of the GNU Library General Public License\n * along with this library; see the file COPYING.LIB. If not, write to\n * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,\n * Boston, MA 02110-1301, USA.\n *\/\n\n#include \"TileLoaderHelper.h\"\n\n#include <cmath>\n\n#include <QtCore\/QDebug>\n\n#include \"GeoSceneTexture.h\"\n#include \"global.h\"\n\nint TileLoaderHelper::levelToRow( int level )\n{\n if ( level < 0 ) {\n qDebug() << QString( \"TileLoaderHelper::levelToRow(): Invalid level: %1\" )\n .arg( level );\n return 0;\n }\n return (int)std::pow( 2.0, (double)( level ) );\n}\n\nint TileLoaderHelper::levelToColumn( int level )\n{\n if ( level < 0 ) {\n qDebug() << QString( \"TileLoaderHelper::levelToColumn(): Invalid level: %1\" )\n .arg( level );\n return 0;\n }\n return (int)std::pow( 2.0, (double)( level + 1 ) );\n}\n\nint TileLoaderHelper::rowToLevel( int row )\n{\n if ( row < 1 ) {\n qDebug() << QString( \"TileLoaderHelper::rowToLevel(): Invalid number of rows: %1\" )\n .arg( row );\n return 0;\n }\n return (int)( std::log( (double)row ) \/ std::log( (double)2.0 ) );\n}\n\nint TileLoaderHelper::columnToLevel( int column )\n{\n if ( column < 2 ) {\n qDebug() << QString( \"TileLoaderHelper::columnToLevel(): Invalid number of columns: %1\" )\n .arg( column );\n return 0;\n }\n return (int)( std::log( (double)(column \/ 2) ) \/ std::log( (double)2.0 ) );\n}\n\nQString TileLoaderHelper::relativeTileFileName( GeoSceneTexture *textureLayer, int level, int x,\n int y )\n{\n QString relFileName;\n if ( textureLayer ) {\n const QString suffix = textureLayer->fileFormat().toLower();\n switch ( textureLayer->storageLayoutMode() ) {\n case GeoSceneTexture::Marble:\n relFileName = QString( \"%1\/%2\/%3\/%3_%4.%5\" )\n .arg( themeStr( textureLayer ) )\n .arg( level )\n .arg( y, tileDigits, 10, QChar('0') )\n .arg( x, tileDigits, 10, QChar('0') )\n .arg( suffix );\n break;\n case GeoSceneTexture::OpenStreetMap:\n relFileName = QString( \"%1\/%2\/%3\/%4.%5\" )\n .arg( themeStr( textureLayer ) )\n .arg( level )\n .arg( x )\n .arg( y )\n .arg( suffix );\n break;\n }\n }\n return relFileName;\n}\n\nQString TileLoaderHelper::themeStr( GeoSceneTexture *textureLayer )\n{\n QString oldThemeStr;\n\n if ( textureLayer ) {\n oldThemeStr = \"maps\/\" + textureLayer->sourceDir();\n }\n\n return oldThemeStr;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"nar-accessor.hh\"\n#include \"archive.hh\"\n\n#include <map>\n\nnamespace nix {\n\nstruct NarMember\n{\n FSAccessor::Type type;\n\n bool isExecutable;\n\n \/* If this is a regular file, position of the contents of this\n file in the NAR. *\/\n size_t start, size;\n\n std::string target;\n};\n\nstruct NarIndexer : ParseSink, StringSource\n{\n \/\/ FIXME: should store this as a tree. Now we're vulnerable to\n \/\/ O(nm) memory consumption (e.g. for x_0\/...\/x_n\/{y_0..y_m}).\n typedef std::map<Path, NarMember> Members;\n Members members;\n\n Path currentPath;\n std::string currentStart;\n bool isExec;\n\n NarIndexer(const std::string & nar) : StringSource(nar)\n {\n }\n\n void createDirectory(const Path & path) override\n {\n members.emplace(path,\n NarMember{FSAccessor::Type::tDirectory, false, 0, 0});\n }\n\n void createRegularFile(const Path & path) override\n {\n currentPath = path;\n }\n\n void isExecutable() override\n {\n isExec = true;\n }\n\n void preallocateContents(unsigned long long size) override\n {\n currentStart = string(s, pos, 16);\n members.emplace(currentPath,\n NarMember{FSAccessor::Type::tRegular, isExec, pos, size});\n }\n\n void receiveContents(unsigned char * data, unsigned int len) override\n {\n \/\/ Sanity check\n if (!currentStart.empty()) {\n assert(len < 16 || currentStart == string((char *) data, 16));\n currentStart.clear();\n }\n }\n\n void createSymlink(const Path & path, const string & target) override\n {\n members.emplace(path,\n NarMember{FSAccessor::Type::tSymlink, false, 0, 0, target});\n }\n\n Members::iterator find(const Path & path)\n {\n auto i = members.find(path);\n if (i == members.end())\n throw Error(format(\"NAR file does not contain path ‘%1%’\") % path);\n return i;\n }\n};\n\nstruct NarAccessor : public FSAccessor\n{\n ref<const std::string> nar;\n NarIndexer indexer;\n\n NarAccessor(ref<const std::string> nar) : nar(nar), indexer(*nar)\n {\n parseDump(indexer, indexer);\n }\n\n Stat stat(const Path & path) override\n {\n auto i = indexer.members.find(path);\n if (i == indexer.members.end())\n return {FSAccessor::Type::tMissing, 0, false};\n return {i->second.type, i->second.size, i->second.isExecutable};\n }\n\n StringSet readDirectory(const Path & path) override\n {\n auto i = indexer.find(path);\n\n if (i->second.type != FSAccessor::Type::tDirectory)\n throw Error(format(\"path ‘%1%’ inside NAR file is not a directory\") % path);\n\n ++i;\n StringSet res;\n while (i != indexer.members.end() && isInDir(i->first, path)) {\n \/\/ FIXME: really bad performance.\n if (i->first.find('\/', path.size() + 1) == std::string::npos)\n res.insert(std::string(i->first, path.size() + 1));\n ++i;\n }\n return res;\n }\n\n std::string readFile(const Path & path) override\n {\n auto i = indexer.find(path);\n if (i->second.type != FSAccessor::Type::tRegular)\n throw Error(format(\"path ‘%1%’ inside NAR file is not a regular file\") % path);\n return std::string(*nar, i->second.start, i->second.size);\n }\n\n std::string readLink(const Path & path) override\n {\n auto i = indexer.find(path);\n if (i->second.type != FSAccessor::Type::tSymlink)\n throw Error(format(\"path ‘%1%’ inside NAR file is not a symlink\") % path);\n return i->second.target;\n }\n};\n\nref<FSAccessor> makeNarAccessor(ref<const std::string> nar)\n{\n return make_ref<NarAccessor>(nar);\n}\n\n}\n<commit_msg>NarAccessor: Fix handling of non-executable files<commit_after>#include \"nar-accessor.hh\"\n#include \"archive.hh\"\n\n#include <map>\n\nnamespace nix {\n\nstruct NarMember\n{\n FSAccessor::Type type;\n\n bool isExecutable;\n\n \/* If this is a regular file, position of the contents of this\n file in the NAR. *\/\n size_t start, size;\n\n std::string target;\n};\n\nstruct NarIndexer : ParseSink, StringSource\n{\n \/\/ FIXME: should store this as a tree. Now we're vulnerable to\n \/\/ O(nm) memory consumption (e.g. for x_0\/...\/x_n\/{y_0..y_m}).\n typedef std::map<Path, NarMember> Members;\n Members members;\n\n Path currentPath;\n std::string currentStart;\n bool isExec = false;\n\n NarIndexer(const std::string & nar) : StringSource(nar)\n {\n }\n\n void createDirectory(const Path & path) override\n {\n members.emplace(path,\n NarMember{FSAccessor::Type::tDirectory, false, 0, 0});\n }\n\n void createRegularFile(const Path & path) override\n {\n currentPath = path;\n }\n\n void isExecutable() override\n {\n isExec = true;\n }\n\n void preallocateContents(unsigned long long size) override\n {\n currentStart = string(s, pos, 16);\n members.emplace(currentPath,\n NarMember{FSAccessor::Type::tRegular, isExec, pos, size});\n }\n\n void receiveContents(unsigned char * data, unsigned int len) override\n {\n \/\/ Sanity check\n if (!currentStart.empty()) {\n assert(len < 16 || currentStart == string((char *) data, 16));\n currentStart.clear();\n }\n }\n\n void createSymlink(const Path & path, const string & target) override\n {\n members.emplace(path,\n NarMember{FSAccessor::Type::tSymlink, false, 0, 0, target});\n }\n\n Members::iterator find(const Path & path)\n {\n auto i = members.find(path);\n if (i == members.end())\n throw Error(format(\"NAR file does not contain path ‘%1%’\") % path);\n return i;\n }\n};\n\nstruct NarAccessor : public FSAccessor\n{\n ref<const std::string> nar;\n NarIndexer indexer;\n\n NarAccessor(ref<const std::string> nar) : nar(nar), indexer(*nar)\n {\n parseDump(indexer, indexer);\n }\n\n Stat stat(const Path & path) override\n {\n auto i = indexer.members.find(path);\n if (i == indexer.members.end())\n return {FSAccessor::Type::tMissing, 0, false};\n return {i->second.type, i->second.size, i->second.isExecutable};\n }\n\n StringSet readDirectory(const Path & path) override\n {\n auto i = indexer.find(path);\n\n if (i->second.type != FSAccessor::Type::tDirectory)\n throw Error(format(\"path ‘%1%’ inside NAR file is not a directory\") % path);\n\n ++i;\n StringSet res;\n while (i != indexer.members.end() && isInDir(i->first, path)) {\n \/\/ FIXME: really bad performance.\n if (i->first.find('\/', path.size() + 1) == std::string::npos)\n res.insert(std::string(i->first, path.size() + 1));\n ++i;\n }\n return res;\n }\n\n std::string readFile(const Path & path) override\n {\n auto i = indexer.find(path);\n if (i->second.type != FSAccessor::Type::tRegular)\n throw Error(format(\"path ‘%1%’ inside NAR file is not a regular file\") % path);\n return std::string(*nar, i->second.start, i->second.size);\n }\n\n std::string readLink(const Path & path) override\n {\n auto i = indexer.find(path);\n if (i->second.type != FSAccessor::Type::tSymlink)\n throw Error(format(\"path ‘%1%’ inside NAR file is not a symlink\") % path);\n return i->second.target;\n }\n};\n\nref<FSAccessor> makeNarAccessor(ref<const std::string> nar)\n{\n return make_ref<NarAccessor>(nar);\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"linear_interpolate_d.hpp\"\n\n#include <cmath>\n\n#include <algorithm>\n#include <map>\n#include <numeric>\n#include <limits>\n#include <string>\n#include <tuple>\n#include <vector>\n\n\nstd::vector<double> find_barycentric_coords(std::size_t size,\n Point const & point,\n std::vector<Point> const & simplex)\n{\n std::vector<double> a(size * size);\n for (size_t i = 0; i < size; ++i)\n {\n for (size_t j = 0; j < size; ++j)\n {\n a[i*size+j] = *(simplex[i].cartesian_begin()+j) - *(simplex[size].cartesian_begin()+j);\n }\n }\n\n std::vector<double> b(size + 1);\n for (size_t i = 0; i < size; ++i)\n {\n b[i] = *(point.cartesian_begin()+i) - *(simplex[size].cartesian_begin()+i);\n }\n\n \/\/ additional variables needed for LAPACK\n std::vector<int> ipiv(size);\n int info;\n int size_int = size;\n int b_size = 1;\n\n \/\/ solve a*x = b\n \/\/ result will be in b\n F77_NAME(dgesv)(&size_int, &b_size, &a[0], &size_int, &ipiv[0],\n &b[0], &size_int, &info);\n\n if (info != 0)\n {\n error(\"Bad matrix\");\n }\n\n \/\/ calculate last coordinate\n b[size] = 1 - std::accumulate(b.begin(), b.end() - 1, 0.);\n\n return b;\n}\n\n\/\/ returns beta_1, ..., beta_d+1, beta_0\nstd::vector<double> linear_coef(size_t d,\n const std::vector<Point> &points,\n const std::vector<double> &values) {\n std::vector<double> a((d+1) * (d+1));\n for (size_t i = 0; i <= d; ++i) {\n for (size_t j = 0; j < d; ++j) {\n a[i + j*(d+1)] = *(points[i].cartesian_begin() + j);\n }\n\n a[i + d*(d+1)] = 1;\n }\n\n std::vector<double> b(values);\n\n for (auto el : b) {\n if (ISNAN(el)) {\n return b;\n }\n }\n\n \/\/ additional variables needed for LAPACK\n std::vector<int> ipiv(d + 1);\n int info;\n int size_int = d + 1;\n int b_size = 1;\n\n \/\/ solve a*x = b\n \/\/ result will be in b\n F77_NAME(dgesv)(&size_int, &b_size, &a[0], &size_int, &ipiv[0],\n &b[0], &size_int, &info);\n\n if (info != 0)\n {\n \/\/ error(\"Bad matrix\");\n }\n\n return b;\n}\n\n\nclass LinearInterpolator_d {\npublic:\n LinearInterpolator_d(int d,\n const double *points,\n const double *values,\n size_t npoints) : d{d}, triangulation{d}, npoints{npoints} {\n for (size_t i{0}; i < npoints; ++i) {\n Point point(d, points + i*d, points + (i + 1)*d);\n Vertex_handle vertex_handle = triangulation.insert(point);\n vertices_to_values[vertex_handle] = values[i];\n }\n\n\n for (const auto &simplex : triangulation.all_simplices()) {\n if (simplex == Delaunay::Simplex_handle()) continue;\n\n std::vector<Point> vertices;\n std::vector<double> vertex_values;\n bool flag = true;\n for (size_t i{0}; i <= d; ++i) {\n auto vertex = triangulation.vertex_of_simplex(simplex, i);\n double vertex_val = vertices_to_values[vertex];\n if (vertex == Delaunay::Vertex_handle()) {\n flag = false;\n break;\n }\n vertices.push_back(vertex->point());\n vertex_values.push_back(vertex_val);\n }\n if (!flag) continue;\n m[simplex] = linear_coef(d, vertices, vertex_values);\n }\n }\n\n double get(const double *x) {\n const double double_fill_value = NA_REAL;\n\n Point point(d, x, x + d);\n auto simplex = triangulation.locate(point);\n if (!m.count(simplex)) {\n return double_fill_value;\n }\n\n auto beta = m[simplex];\n return std::inner_product(x, x + d, beta.begin(), beta[d]);\n }\n\n double operator()(const double *x) {\n const double double_fill_value = NA_REAL;\n\n Point point(d, x, x + d);\n auto simplex = triangulation.locate(point);\n if (simplex == Delaunay::Simplex_handle()) {\n return double_fill_value;\n }\n std::vector<Point> vertices(d + 1);\n std::vector<double> vertex_values(d + 1);\n for (size_t i{0}; i <= triangulation.current_dimension(); ++i) {\n auto vertex = triangulation.vertex_of_simplex(simplex, i);\n double vertex_val = vertices_to_values[vertex];\n if (ISNAN(vertex_val)) {\n return double_fill_value;\n }\n vertices[i] = triangulation.associated_point(vertex);\n vertex_values[i] = vertex_val;\n }\n auto barycentric = find_barycentric_coords(triangulation.current_dimension(), point, vertices);\n return std::inner_product(vertex_values.begin(), vertex_values.end(), barycentric.begin(), 0.);\n }\n\nprivate:\n const int d;\n size_t npoints;\n Delaunay triangulation;\n std::map<Vertex_handle, double> vertices_to_values;\n std::map<Delaunay::Simplex_handle, std::vector<double>> m;\n};\n\nSEXP linear_interpolate_d(SEXP dimentions,\n SEXP points,\n SEXP values,\n SEXP xi) {\n int d = INTEGER(dimentions)[0];\n\n LinearInterpolator_d li(d, REAL(points), REAL(values), length(values));\n\n int result_length = length(xi) \/ d;\n SEXP results = PROTECT(allocVector(REALSXP, result_length));\n\n for (size_t i{0}; i < result_length; ++i) {\n \/\/ REAL(results)[i] = li(REAL(xi) + i*d);\n REAL(results)[i] = li.get(REAL(xi) + i*d);\n }\n\n UNPROTECT(1);\n return results;\n}\n<commit_msg>Make function local<commit_after>#include \"linear_interpolate_d.hpp\"\n\n#include <cmath>\n\n#include <algorithm>\n#include <map>\n#include <numeric>\n#include <limits>\n#include <string>\n#include <tuple>\n#include <vector>\n\n\nstatic std::vector<double> find_barycentric_coords(std::size_t size,\n Point const & point,\n std::vector<Point> const & simplex)\n{\n std::vector<double> a(size * size);\n for (size_t i = 0; i < size; ++i)\n {\n for (size_t j = 0; j < size; ++j)\n {\n a[i*size+j] = *(simplex[i].cartesian_begin()+j) - *(simplex[size].cartesian_begin()+j);\n }\n }\n\n std::vector<double> b(size + 1);\n for (size_t i = 0; i < size; ++i)\n {\n b[i] = *(point.cartesian_begin()+i) - *(simplex[size].cartesian_begin()+i);\n }\n\n \/\/ additional variables needed for LAPACK\n std::vector<int> ipiv(size);\n int info;\n int size_int = size;\n int b_size = 1;\n\n \/\/ solve a*x = b\n \/\/ result will be in b\n F77_NAME(dgesv)(&size_int, &b_size, &a[0], &size_int, &ipiv[0],\n &b[0], &size_int, &info);\n\n if (info != 0)\n {\n error(\"Bad matrix\");\n }\n\n \/\/ calculate last coordinate\n b[size] = 1 - std::accumulate(b.begin(), b.end() - 1, 0.);\n\n return b;\n}\n\n\/\/ returns beta_1, ..., beta_d+1, beta_0\nstd::vector<double> linear_coef(size_t d,\n const std::vector<Point> &points,\n const std::vector<double> &values) {\n std::vector<double> a((d+1) * (d+1));\n for (size_t i = 0; i <= d; ++i) {\n for (size_t j = 0; j < d; ++j) {\n a[i + j*(d+1)] = *(points[i].cartesian_begin() + j);\n }\n\n a[i + d*(d+1)] = 1;\n }\n\n std::vector<double> b(values);\n\n for (auto el : b) {\n if (ISNAN(el)) {\n return b;\n }\n }\n\n \/\/ additional variables needed for LAPACK\n std::vector<int> ipiv(d + 1);\n int info;\n int size_int = d + 1;\n int b_size = 1;\n\n \/\/ solve a*x = b\n \/\/ result will be in b\n F77_NAME(dgesv)(&size_int, &b_size, &a[0], &size_int, &ipiv[0],\n &b[0], &size_int, &info);\n\n if (info != 0)\n {\n \/\/ error(\"Bad matrix\");\n }\n\n return b;\n}\n\n\nclass LinearInterpolator_d {\npublic:\n LinearInterpolator_d(int d,\n const double *points,\n const double *values,\n size_t npoints) : d{d}, triangulation{d}, npoints{npoints} {\n for (size_t i{0}; i < npoints; ++i) {\n Point point(d, points + i*d, points + (i + 1)*d);\n Vertex_handle vertex_handle = triangulation.insert(point);\n vertices_to_values[vertex_handle] = values[i];\n }\n\n\n for (const auto &simplex : triangulation.all_simplices()) {\n if (simplex == Delaunay::Simplex_handle()) continue;\n\n std::vector<Point> vertices;\n std::vector<double> vertex_values;\n bool flag = true;\n for (size_t i{0}; i <= d; ++i) {\n auto vertex = triangulation.vertex_of_simplex(simplex, i);\n double vertex_val = vertices_to_values[vertex];\n if (vertex == Delaunay::Vertex_handle()) {\n flag = false;\n break;\n }\n vertices.push_back(vertex->point());\n vertex_values.push_back(vertex_val);\n }\n if (!flag) continue;\n m[simplex] = linear_coef(d, vertices, vertex_values);\n }\n }\n\n double get(const double *x) {\n const double double_fill_value = NA_REAL;\n\n Point point(d, x, x + d);\n auto simplex = triangulation.locate(point);\n if (!m.count(simplex)) {\n return double_fill_value;\n }\n\n auto beta = m[simplex];\n return std::inner_product(x, x + d, beta.begin(), beta[d]);\n }\n\n double operator()(const double *x) {\n const double double_fill_value = NA_REAL;\n\n Point point(d, x, x + d);\n auto simplex = triangulation.locate(point);\n if (simplex == Delaunay::Simplex_handle()) {\n return double_fill_value;\n }\n std::vector<Point> vertices(d + 1);\n std::vector<double> vertex_values(d + 1);\n for (size_t i{0}; i <= triangulation.current_dimension(); ++i) {\n auto vertex = triangulation.vertex_of_simplex(simplex, i);\n double vertex_val = vertices_to_values[vertex];\n if (ISNAN(vertex_val)) {\n return double_fill_value;\n }\n vertices[i] = triangulation.associated_point(vertex);\n vertex_values[i] = vertex_val;\n }\n auto barycentric = find_barycentric_coords(triangulation.current_dimension(), point, vertices);\n return std::inner_product(vertex_values.begin(), vertex_values.end(), barycentric.begin(), 0.);\n }\n\nprivate:\n const int d;\n size_t npoints;\n Delaunay triangulation;\n std::map<Vertex_handle, double> vertices_to_values;\n std::map<Delaunay::Simplex_handle, std::vector<double>> m;\n};\n\nSEXP linear_interpolate_d(SEXP dimentions,\n SEXP points,\n SEXP values,\n SEXP xi) {\n int d = INTEGER(dimentions)[0];\n\n LinearInterpolator_d li(d, REAL(points), REAL(values), length(values));\n\n int result_length = length(xi) \/ d;\n SEXP results = PROTECT(allocVector(REALSXP, result_length));\n\n for (size_t i{0}; i < result_length; ++i) {\n \/\/ REAL(results)[i] = li(REAL(xi) + i*d);\n REAL(results)[i] = li.get(REAL(xi) + i*d);\n }\n\n UNPROTECT(1);\n return results;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (C) 2005-2007 Brian Paul All Rights Reserved.\n * Copyright (C) 2008 VMware, Inc. All Rights Reserved.\n * Copyright © 2010 Intel Corporation\n *\n * Permission is hereby granted, free of charge, to any person obtaining a\n * copy of this software and associated documentation files (the \"Software\"),\n * to deal in the Software without restriction, including without limitation\n * the rights to use, copy, modify, merge, publish, distribute, sublicense,\n * and\/or sell copies of the Software, and to permit persons to whom the\n * Software is furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice (including the next\n * paragraph) shall be included in all copies or substantial portions of the\n * Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n * DEALINGS IN THE SOFTWARE.\n *\/\n\n#include \"ir.h\"\n#include \"glsl_types.h\"\n#include \"ir_visitor.h\"\n#include \"..\/glsl\/program.h\"\n#include \"ir_uniform.h\"\n\n#include \"main\/mtypes.h\"\n#include \"program\/hash_table.h\"\n#include \"program\/prog_parameter.h\"\n#include \"program\/program.h\"\n\n\nclass get_sampler_name : public ir_hierarchical_visitor\n{\npublic:\n get_sampler_name(ir_dereference *last,\n\t\t struct gl_shader_program *shader_program)\n {\n this->mem_ctx = ralloc_context(NULL);\n this->shader_program = shader_program;\n this->name = NULL;\n this->offset = 0;\n this->last = last;\n }\n\n ~get_sampler_name()\n {\n ralloc_free(this->mem_ctx);\n }\n\n virtual ir_visitor_status visit(ir_dereference_variable *ir)\n {\n this->name = ir->var->name;\n return visit_continue;\n }\n\n virtual ir_visitor_status visit_leave(ir_dereference_record *ir)\n {\n this->name = ralloc_asprintf(mem_ctx, \"%s.%s\", name, ir->field);\n return visit_continue;\n }\n\n virtual ir_visitor_status visit_leave(ir_dereference_array *ir)\n {\n ir_constant *index = ir->array_index->as_constant();\n int i;\n\n if (index) {\n\t i = index->value.i[0];\n } else {\n\t \/* GLSL 1.10 and 1.20 allowed variable sampler array indices,\n\t * while GLSL 1.30 requires that the array indices be\n\t * constant integer expressions. We don't expect any driver\n\t * to actually work with a really variable array index, so\n\t * all that would work would be an unrolled loop counter that ends\n\t * up being constant above.\n\t *\/\n\t ralloc_strcat(&shader_program->InfoLog,\n\t\t \"warning: Variable sampler array index unsupported.\\n\"\n\t\t \"This feature of the language was removed in GLSL 1.20 \"\n\t\t \"and is unlikely to be supported for 1.10 in Mesa.\\n\");\n\t i = 0;\n }\n if (ir != last) {\n\t this->name = ralloc_asprintf(mem_ctx, \"%s[%d]\", name, i);\n } else {\n\t offset = i;\n }\n return visit_continue;\n }\n\n struct gl_shader_program *shader_program;\n const char *name;\n void *mem_ctx;\n int offset;\n ir_dereference *last;\n};\n\n\nint\n_mesa_get_sampler_uniform_value(class ir_dereference *sampler,\n\t\t\t\tstruct gl_shader_program *shader_program,\n\t\t\t\tconst struct gl_program *prog)\n{\n get_sampler_name getname(sampler, shader_program);\n\n GLuint shader = _mesa_program_enum_to_shader_stage(prog->Target);\n\n sampler->accept(&getname);\n\n unsigned location;\n if (!shader_program->UniformHash->get(location, getname.name)) {\n linker_error(shader_program,\n\t\t \"failed to find sampler named %s.\\n\", getname.name);\n return 0;\n }\n\n if (!shader_program->UniformStorage[location].sampler[shader].active) {\n assert(0 && \"cannot return a sampler\");\n linker_error(shader_program,\n\t\t \"cannot return a sampler named %s, because it is not \"\n \"used in this shader stage. This is a driver bug.\\n\",\n getname.name);\n return 0;\n }\n\n return shader_program->UniformStorage[location].sampler[shader].index +\n getname.offset;\n}\n\n\nclass ir_rvalue *\n_mesa_get_sampler_array_nonconst_index(class ir_dereference *sampler)\n{\n ir_dereference_array *deref_arr = sampler->as_dereference_array();\n if (!deref_arr || deref_arr->array_index->as_constant())\n return NULL;\n\n return deref_arr->array_index;\n}\n<commit_msg>mesa: clean up #includes in sampler.cpp<commit_after>\/*\n * Copyright (C) 2005-2007 Brian Paul All Rights Reserved.\n * Copyright (C) 2008 VMware, Inc. All Rights Reserved.\n * Copyright © 2010 Intel Corporation\n *\n * Permission is hereby granted, free of charge, to any person obtaining a\n * copy of this software and associated documentation files (the \"Software\"),\n * to deal in the Software without restriction, including without limitation\n * the rights to use, copy, modify, merge, publish, distribute, sublicense,\n * and\/or sell copies of the Software, and to permit persons to whom the\n * Software is furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice (including the next\n * paragraph) shall be included in all copies or substantial portions of the\n * Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n * DEALINGS IN THE SOFTWARE.\n *\/\n\n#include \"main\/mtypes.h\"\n#include \"glsl\/glsl_types.h\"\n#include \"glsl\/ir.h\"\n#include \"glsl\/ir_uniform.h\"\n#include \"glsl\/ir_visitor.h\"\n#include \"glsl\/program.h\"\n#include \"program\/hash_table.h\"\n#include \"program\/prog_parameter.h\"\n#include \"program\/program.h\"\n\n\nclass get_sampler_name : public ir_hierarchical_visitor\n{\npublic:\n get_sampler_name(ir_dereference *last,\n\t\t struct gl_shader_program *shader_program)\n {\n this->mem_ctx = ralloc_context(NULL);\n this->shader_program = shader_program;\n this->name = NULL;\n this->offset = 0;\n this->last = last;\n }\n\n ~get_sampler_name()\n {\n ralloc_free(this->mem_ctx);\n }\n\n virtual ir_visitor_status visit(ir_dereference_variable *ir)\n {\n this->name = ir->var->name;\n return visit_continue;\n }\n\n virtual ir_visitor_status visit_leave(ir_dereference_record *ir)\n {\n this->name = ralloc_asprintf(mem_ctx, \"%s.%s\", name, ir->field);\n return visit_continue;\n }\n\n virtual ir_visitor_status visit_leave(ir_dereference_array *ir)\n {\n ir_constant *index = ir->array_index->as_constant();\n int i;\n\n if (index) {\n\t i = index->value.i[0];\n } else {\n\t \/* GLSL 1.10 and 1.20 allowed variable sampler array indices,\n\t * while GLSL 1.30 requires that the array indices be\n\t * constant integer expressions. We don't expect any driver\n\t * to actually work with a really variable array index, so\n\t * all that would work would be an unrolled loop counter that ends\n\t * up being constant above.\n\t *\/\n\t ralloc_strcat(&shader_program->InfoLog,\n\t\t \"warning: Variable sampler array index unsupported.\\n\"\n\t\t \"This feature of the language was removed in GLSL 1.20 \"\n\t\t \"and is unlikely to be supported for 1.10 in Mesa.\\n\");\n\t i = 0;\n }\n if (ir != last) {\n\t this->name = ralloc_asprintf(mem_ctx, \"%s[%d]\", name, i);\n } else {\n\t offset = i;\n }\n return visit_continue;\n }\n\n struct gl_shader_program *shader_program;\n const char *name;\n void *mem_ctx;\n int offset;\n ir_dereference *last;\n};\n\n\nint\n_mesa_get_sampler_uniform_value(class ir_dereference *sampler,\n\t\t\t\tstruct gl_shader_program *shader_program,\n\t\t\t\tconst struct gl_program *prog)\n{\n get_sampler_name getname(sampler, shader_program);\n\n GLuint shader = _mesa_program_enum_to_shader_stage(prog->Target);\n\n sampler->accept(&getname);\n\n unsigned location;\n if (!shader_program->UniformHash->get(location, getname.name)) {\n linker_error(shader_program,\n\t\t \"failed to find sampler named %s.\\n\", getname.name);\n return 0;\n }\n\n if (!shader_program->UniformStorage[location].sampler[shader].active) {\n assert(0 && \"cannot return a sampler\");\n linker_error(shader_program,\n\t\t \"cannot return a sampler named %s, because it is not \"\n \"used in this shader stage. This is a driver bug.\\n\",\n getname.name);\n return 0;\n }\n\n return shader_program->UniformStorage[location].sampler[shader].index +\n getname.offset;\n}\n\n\nclass ir_rvalue *\n_mesa_get_sampler_array_nonconst_index(class ir_dereference *sampler)\n{\n ir_dereference_array *deref_arr = sampler->as_dereference_array();\n if (!deref_arr || deref_arr->array_index->as_constant())\n return NULL;\n\n return deref_arr->array_index;\n}\n<|endoftext|>"} {"text":"<commit_before>#include <Riostream.h>\n#include \"TFluka.h\"\n#ifndef WIN32\n# define usdraw usdraw_\n#else\n# define usdraw USDRAW\n#endif\nextern \"C\" {\nvoid usdraw(Int_t& icode, Int_t& mreg, \n Double_t& xsco, Double_t& ysco, Double_t& zsco)\n{\n ((TFluka*) gMC)->SetIcode(icode);\n ((TFluka*) gMC)->SetMreg(mreg);\n ((TFluka*) gMC)->SetXsco(xsco);\n ((TFluka*) gMC)->SetYsco(ysco);\n ((TFluka*) gMC)->SetZsco(zsco);\n cout << endl << \" !!! I am in usdraw\" << endl;\n ((TFluka*) gMC)->FutoTest();\n} \/\/ end of usdraw\n} \/\/ end of extern \"C\"\n\n<commit_msg>print statement commented<commit_after>#include <Riostream.h>\n#include \"TFluka.h\"\n#ifndef WIN32\n# define usdraw usdraw_\n#else\n# define usdraw USDRAW\n#endif\nextern \"C\" {\nvoid usdraw(Int_t& icode, Int_t& mreg, \n Double_t& xsco, Double_t& ysco, Double_t& zsco)\n{\n ((TFluka*) gMC)->SetIcode(icode);\n ((TFluka*) gMC)->SetMreg(mreg);\n ((TFluka*) gMC)->SetXsco(xsco);\n ((TFluka*) gMC)->SetYsco(ysco);\n ((TFluka*) gMC)->SetZsco(zsco);\n ((TFluka*) gMC)->FutoTest();\n\/\/ cout << endl << \" !!! I am in usdraw - calling Stepping()\" << mreg << endl;\n} \/\/ end of usdraw\n} \/\/ end of extern \"C\"\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright(c) Sophist Solutions Inc. 1990-2013. All rights reserved\n *\/\n\/\/ TEST Foundation::Containers::SortedTally\n\/\/ STATUS very minimal\/incomplete\n#include \"Stroika\/Foundation\/StroikaPreComp.h\"\n\n#include \"Stroika\/Foundation\/Containers\/SortedMapping.h\"\n#include \"Stroika\/Foundation\/Containers\/Concrete\/SortedMapping_stdmap.h\"\n#include \"Stroika\/Foundation\/Debug\/Assertions.h\"\n#include \"Stroika\/Foundation\/Debug\/Trace.h\"\n\n\n#include \"..\/TestHarness\/SimpleClass.h\"\n#include \"..\/TestHarness\/TestHarness.h\"\n\n\n\nusing namespace Stroika;\nusing namespace Stroika::Foundation;\nusing namespace Stroika::Foundation::Containers;\n\n\nusing Concrete::SortedMapping_stdmap;\n\n\nnamespace {\n template <typename MappingOfKeyT>\n void SimpleTest_1_ (MappingOfKeyT m)\n {\n MappingOfKeyT s;\n }\n}\n\n\nnamespace {\n template <typename MappingOfKeyT>\n void SimpleTest_2_ (MappingOfKeyT m)\n {\n m.Add (1, 2);\n VerifyTestResult (m.size () == 1);\n Verify (m.Lookup (1, nullptr));\n Verify (not m.Lookup (2, nullptr));\n m.Add (1, 2);\n VerifyTestResult (m.size () == 1);\n m.Remove (1);\n VerifyTestResult (m.size () == 0);\n m.RemoveAll ();\n VerifyTestResult (m.size () == 0);\n }\n}\n\n\nnamespace {\n template <typename MappingOfKeyT>\n void SimpleTest_3_Iteration_ (MappingOfKeyT m)\n {\n m.Add (1, 2);\n VerifyTestResult (m.size () == 1);\n for (auto i : m) {\n VerifyTestResult (i.first == 1);\n VerifyTestResult (i.second == 2);\n }\n m.Add (1, 2);\n VerifyTestResult (m.size () == 1);\n for (auto i : m) {\n VerifyTestResult (i.first == 1);\n VerifyTestResult (i.second == 2);\n }\n m.Remove (1);\n VerifyTestResult (m.size () == 0);\n for (auto i : m) {\n VerifyTestResult (false);\n }\n m.Add (2, 3);\n m.Add (1, 2);\n m.Add (3, 4);\n unsigned int cnt = 0;\n for (auto i : m) {\n cnt++;\n if (cnt == 1) {\n VerifyTestResult (i.first == 1);\n VerifyTestResult (i.second == 2);\n }\n if (cnt == 2) {\n VerifyTestResult (i.first == 2);\n VerifyTestResult (i.second == 3);\n }\n if (cnt == 3) {\n VerifyTestResult (i.first == 3);\n VerifyTestResult (i.second == 4);\n }\n }\n VerifyTestResult (cnt == 3);\n m.RemoveAll ();\n VerifyTestResult (m.size () == 0);\n }\n}\n\n\nnamespace {\n template <typename MappingOfKeyT>\n void SimpleMappingTest_All_For_Type ()\n {\n MappingOfKeyT m;\n SimpleTest_1_ (m);\n SimpleTest_2_ (m);\n SimpleTest_3_Iteration_ (m);\n }\n}\n\n\nnamespace {\n void DoRegressionTests_ ()\n {\n SimpleMappingTest_All_For_Type<SortedMapping<size_t, size_t>> ();\n SimpleMappingTest_All_For_Type<SortedMapping<SimpleClass, SimpleClass>> ();\n\n SimpleMappingTest_All_For_Type<SortedMapping_stdmap<size_t, size_t>> ();\n SimpleMappingTest_All_For_Type<SortedMapping_stdmap<SimpleClass, SimpleClass>> ();\n }\n}\n\n\nint main (int argc, const char* argv[])\n{\n Stroika::TestHarness::Setup ();\n Stroika::TestHarness::PrintPassOrFail (DoRegressionTests_);\n return EXIT_SUCCESS;\n}\n<commit_msg>draft of Tests for sortedtally - though no sorted tally class yet<commit_after>\/*\n * Copyright(c) Sophist Solutions Inc. 1990-2013. All rights reserved\n *\/\n\/\/ TEST Foundation::Containers::SortedTally\n\/\/ STATUS very minimal\/incomplete\n#include \"Stroika\/Foundation\/StroikaPreComp.h\"\n\n\n\/\/\/ WRONG - we dont have SortedTally Yet - but when we do!!!\n#include \"Stroika\/Foundation\/Containers\/Tally.h\"\n#include \"Stroika\/Foundation\/Containers\/Concrete\/Tally_Array.h\"\n#include \"Stroika\/Foundation\/Containers\/Concrete\/Tally_LinkedList.h\"\n#include \"Stroika\/Foundation\/Debug\/Assertions.h\"\n#include \"Stroika\/Foundation\/Debug\/Trace.h\"\n\n#include \"..\/TestCommon\/CommonTests_Tally.h\"\n#include \"..\/TestHarness\/SimpleClass.h\"\n#include \"..\/TestHarness\/TestHarness.h\"\n\n\n#include \"..\/TestCommon\/CommonTests_Tally.h\"\n#include \"..\/TestHarness\/SimpleClass.h\"\n#include \"..\/TestHarness\/TestHarness.h\"\n\n\nusing namespace Stroika;\nusing namespace Stroika::Foundation;\nusing namespace Stroika::Foundation::Containers;\n\n\nusing Concrete::Tally_Array;\nusing Concrete::Tally_LinkedList;\n\n\nnamespace {\n\n void DoRegressionTests_ ()\n {\n using namespace CommonTests::TallyTests;\n\n SimpleTallyTest_All_For_Type<size_t, Tally_LinkedList<size_t>> ();\n SimpleTallyTest_All_For_Type<SimpleClass, Tally_LinkedList<SimpleClass>> ();\n\n SimpleTallyTest_All_For_Type<size_t, Tally_Array<size_t>> ();\n SimpleTallyTest_All_For_Type<SimpleClass, Tally_Array<SimpleClass>> ();\n\n SimpleTallyTest_All_For_Type<size_t, Tally<size_t>> ();\n SimpleTallyTest_All_For_Type<SimpleClass, Tally<SimpleClass>> ();\n }\n\n}\n\n\n\nint main (int argc, const char* argv[])\n{\n Stroika::TestHarness::Setup ();\n Stroika::TestHarness::PrintPassOrFail (DoRegressionTests_);\n return EXIT_SUCCESS;\n}\n<|endoftext|>"} {"text":"<commit_before>\n\/\/ Includes.\n#include \"UI\/MainWindow.h\"\n#include \"UI\/NodeItem.h\"\n#include \"UI\/ConnectionItem.h\"\n#include \"UI\/ParametersDialog.h\"\n#include \"App\/App.h\"\n#include \"App\/Boundary\/NodeProxy.h\"\n#include \"App\/Boundary\/ConnectionProxy.h\"\n\n\/\/ Qt.\n#include <QGraphicsView>\n#include <QGraphicsScene>\n#include <QVBoxLayout>\n#include <QHBoxLayout>\n#include <QInputDialog>\n#include <QMessageBox>\n#include <QPushButton>\n#include <QTextEdit>\n#include <QListWidget>\n#include <QStringListModel>\n#include <QGraphicsLineItem>\n#include <QMouseEvent>\n#include <QDrag>\n#include <QMimeData>\n#include <QCheckBox>\n\nclass TypesWidget : public QListWidget\n{\npublic:\n TypesWidget(QWidget* parent = nullptr) : QListWidget(parent) {}\n\nprotected:\n\n virtual void mousePressEvent(QMouseEvent* e)\n {\n QListWidget::mousePressEvent(e);\n if (e->button() == Qt::LeftButton)\n {\n drag_start_position_ = e->pos();\n }\n }\n\n virtual void mouseMoveEvent(QMouseEvent *e)\n {\n QListWidget::mouseMoveEvent(e);\n\n if ((e->buttons() & Qt::LeftButton) == 0)\n {\n return;\n }\n else\n {\n QDrag *drag = new QDrag(this);\n QMimeData *mimeData = new QMimeData;\n\n QListWidgetItem* item = itemAt(e->pos());\n if (item != nullptr)\n {\n QString text = item->text();\n mimeData->setData(\"node\/type\", text.toUtf8());\n drag->setMimeData(mimeData);\n drag->exec(Qt::CopyAction | Qt::MoveAction);\n }\n }\n }\n\nprivate:\n\n QPoint drag_start_position_;\n\n};\n\nMainWindow::MainWindow(App *app, QWidget *parent)\n : QMainWindow(parent)\n , types_list_(nullptr)\n , scene_view_(nullptr)\n , log_view_(nullptr)\n , show_types_box_(nullptr)\n , scene_(nullptr)\n , app_(app)\n , temp_line_item_(new QGraphicsLineItem)\n , selected_connector_on_press_(false)\n , selected_output_node_id_(\"\")\n , selected_output_index_(-1)\n , selected_input_node_id_(\"\")\n , selected_input_index_(-1)\n{\n scene_ = new QGraphicsScene;\n\n QPushButton* add_node_button = new QPushButton(tr(\"Add node\"));\n connect(add_node_button, &QPushButton::clicked, this, &MainWindow::addNodeClicked);\n QPushButton* execute_button = new QPushButton(tr(\"Execute\"));\n connect(execute_button, &QPushButton::clicked, this, &MainWindow::executeClicked);\n QPushButton* clear_button = new QPushButton(tr(\"Clear\"));\n connect(clear_button, &QPushButton::clicked, this, &MainWindow::clearClicked);\n QPushButton* test_button = new QPushButton(tr(\"Test\"));\n connect(test_button, &QPushButton::clicked, this, &MainWindow::testClicked);\n show_types_box_ = new QCheckBox(tr(\"Show types\"));\n connect(show_types_box_, &QCheckBox::stateChanged, this, &MainWindow::showTypes);\n\n\n QHBoxLayout* toolbar_layout = new QHBoxLayout;\n toolbar_layout->addWidget(add_node_button);\n toolbar_layout->addWidget(execute_button);\n toolbar_layout->addWidget(clear_button);\n toolbar_layout->addWidget(test_button);\n toolbar_layout->addWidget(show_types_box_);\n toolbar_layout->addStretch();\n\n scene_view_ = new NetworkSceneView(scene_);\n scene_view_->setDelegate(this);\n scene_view_->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Preferred);\n scene_view_->setAcceptDrops(true);\n\n QStringList types;\n std::vector<std::string> available_types = app->availableNodeTypes();\n for (int i = 0; i < (int)available_types.size(); ++i)\n {\n types << QString::fromStdString(available_types[i]);\n }\n types_list_ = new TypesWidget;\n types_list_->setMaximumWidth(150);\n types_list_->setSizePolicy(QSizePolicy::Maximum, QSizePolicy::Preferred);\n types_list_->addItems(types);\n types_list_->setSelectionMode(QAbstractItemView::SingleSelection);\n\n QHBoxLayout* central_layout = new QHBoxLayout;\n central_layout->addWidget(types_list_);\n central_layout->addWidget(scene_view_);\n\n log_view_ = new QTextEdit();\n log_view_->setReadOnly(true);\n log_view_->setMaximumHeight(200);\n log_view_->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Maximum);\n\n QVBoxLayout* main_layout = new QVBoxLayout;\n main_layout->addLayout(toolbar_layout);\n main_layout->addLayout(central_layout);\n main_layout->addWidget(log_view_);\n\n QWidget* central_widget = new QWidget;\n central_widget->setLayout(main_layout);\n setCentralWidget(central_widget);\n\n Logger::instance().addDelegate(this);\n}\n\nMainWindow::~MainWindow()\n{\n scene_view_->setScene(nullptr);\n delete scene_;\n delete temp_line_item_;\n node_items_.clear();\n connection_items_.clear();\n\n Logger::instance().removeDelegate(this);\n}\n\nstd::string MainWindow::promptString(const std::string &message)\n{\n std::string text = QInputDialog::getText(this, tr(\"Enter Input:\"), QString::fromStdString(message)).toStdString();\n return text;\n}\n\nbool MainWindow::promptBool(const std::string &message)\n{\n QMessageBox::StandardButton button = QMessageBox::question(this, tr(\"Enter Input:\"), QString::fromStdString(message));\n return button == QMessageBox::Yes;\n}\n\nstd::map<std::string, std::string> MainWindow::promptParameters(const std::vector<std::string> ¶meters)\n{\n ParametersDialog dialog(parameters, this);\n dialog.setWindowTitle(tr(\"Enter parameters:\"));\n\n int result = dialog.exec();\n if (result == QDialog::Accepted)\n {\n return dialog.parameterValues();\n }\n else\n {\n return std::map<std::string, std::string>();\n }\n}\n\nvoid MainWindow::displayError(const std::string &message)\n{\n QMessageBox::critical(this, \"Error!\", QString::fromStdString(message));\n}\n\nvoid MainWindow::nodeAdded(NodeProxy node)\n{\n addNode(node, this->last_drop_pos_);\n}\n\nvoid MainWindow::connectionAdded(ConnectionProxy connection)\n{\n NodeItem* output_node_item = node_items_.value(connection.outputNodeID());\n NodeItem* input_node_item = node_items_.value(connection.inputNodeID());\n\n ConnectionItem* item = new ConnectionItem(output_node_item, connection.outputIndex(),\n input_node_item, connection.inputIndex());\n scene_->addItem(item);\n\n QString connection_id = createConnectionID(connection.outputNodeID(), connection.outputIndex(),\n connection.inputNodeID(), connection.inputIndex());\n connection_items_.insert(connection_id, item);\n}\n\nvoid MainWindow::connectionRemoved(ConnectionProxy connection)\n{\n QString connection_id = createConnectionID(connection.outputNodeID(), connection.outputIndex(),\n connection.inputNodeID(), connection.inputIndex());\n ConnectionItem* item = connection_items_[connection_id];\n connection_items_.remove(connection_id);\n\n scene_->removeItem(item);\n scene_->views().at(0)->repaint();\n\n delete item;\n}\n\nvoid MainWindow::logMessage(const std::string &message)\n{\n log_view_->setTextColor(QColor(Qt::black));\n log_view_->append(QString::fromStdString(message));\n}\n\nvoid MainWindow::logError(const std::string &message)\n{\n log_view_->setTextColor(QColor(Qt::red));\n log_view_->append(QString::fromStdString(message));\n}\n\nvoid MainWindow::networkSceneViewPressedAt(const QPoint &pos)\n{\n selected_input_index_ = -1;\n selected_input_node_id_ = \"\";\n selected_output_index_ = -1;\n selected_output_node_id_ = \"\";\n\n selected_connector_on_press_ = selectInputIfUnderPos(pos) || selectOutputIfUnderPos(pos);\n\n if (selected_connector_on_press_)\n {\n QPointF item_pos = temp_line_item_->mapFromScene(scene_view_->mapToScene(pos));\n\n temp_line_.setPoints(item_pos, item_pos);\n temp_line_item_->setLine(temp_line_);\n scene_->addItem(temp_line_item_);\n }\n}\n\nvoid MainWindow::networkSceneViewReleasedAt(const QPoint &pos)\n{\n if (temp_line_item_->scene() == scene_)\n {\n scene_->removeItem(temp_line_item_);\n }\n bool selected_connector_on_release = selectInputIfUnderPos(pos) || selectOutputIfUnderPos(pos);\n\n if (selected_connector_on_press_ && selected_connector_on_release)\n {\n addConnectionBetweenSelectedNodes();\n }\n\n selected_connector_on_press_ = false;\n}\n\nvoid MainWindow::networkSceneViewMoved(const QPoint &pos)\n{\n if (selected_connector_on_press_)\n {\n QPointF item_pos = temp_line_item_->mapFromScene(scene_view_->mapToScene(pos));\n temp_line_.setP2(item_pos);\n temp_line_item_->setLine(temp_line_);\n }\n}\n\nvoid MainWindow::networkSceneViewNodeTypeDroppedAt(const QString &type, const QPoint &pos)\n{\n std::string type_str = type.toStdString();\n last_drop_pos_ = pos;\n app_->createNode(type_str);\n}\n\nvoid MainWindow::nodeMoved(NodeItem *item)\n{\n scene_->update(scene_view_->sceneRect());\n}\n\nbool MainWindow::selectInputIfUnderPos(const QPoint &pos)\n{\n QPointF scene_pos = scene_view_->mapToScene(pos);\n NodeItem* item_under_pos = dynamic_cast<NodeItem*>(scene_->itemAt(scene_pos, scene_view_->transform()));\n\n if (item_under_pos != nullptr)\n {\n QPointF item_pos = item_under_pos->mapFromScene(scene_pos);\n\n int input_index = item_under_pos->indexOfInputUnder(item_pos);\n if (input_index != -1)\n {\n selected_input_index_ = input_index;\n selected_input_node_id_ = item_under_pos->nodeID();\n return true;\n }\n else\n {\n return false;\n }\n }\n else\n {\n return false;\n }\n}\n\nbool MainWindow::selectOutputIfUnderPos(const QPoint& pos)\n{\n QPointF scene_pos = scene_view_->mapToScene(pos);\n NodeItem* item_under_pos = dynamic_cast<NodeItem*>(scene_->itemAt(scene_pos, scene_view_->transform()));\n\n if (item_under_pos != nullptr)\n {\n QPointF item_pos = item_under_pos->mapFromScene(scene_pos);\n\n int output_index = item_under_pos->indexOfOutputUnder(item_pos);\n if (output_index != -1)\n {\n selected_output_index_ = output_index;\n selected_output_node_id_ = item_under_pos->nodeID();\n return true;\n }\n else\n {\n return false;\n }\n }\n else\n {\n return false;\n }\n}\n\nvoid MainWindow::addNodeClicked()\n{\n foreach (QListWidgetItem* item, types_list_->selectedItems())\n {\n std::string type = item->text().toStdString();\n last_drop_pos_ = QPoint(0,0);\n app_->createNode(type);\n }\n}\n\nvoid MainWindow::addNode(const NodeProxy &node, const QPoint &pos)\n{\n NodeItem* node_item = new NodeItem(node, show_types_box_->isChecked());\n\n QPointF scene_pos = scene_view_->mapToScene(pos);\n QTransform transform;\n transform.translate(scene_pos.x(),scene_pos.y());\n node_item->setTransform(transform);\n\n scene_->addItem(node_item);\n node_items_.insert(node.id(), node_item);\n node_item->addDelegate(this);\n}\n\nvoid MainWindow::addConnectionBetweenSelectedNodes()\n{\n if (selected_input_node_id_.empty() || selected_input_index_ == -1 ||\n selected_output_node_id_.empty() || selected_output_index_ == -1)\n {\n return;\n }\n else\n {\n app_->connectNodes(selected_output_node_id_,\n selected_output_index_,\n selected_input_node_id_,\n selected_input_index_);\n }\n\n}\n\nQString MainWindow::createConnectionID(const std::string& outputNodeID, int outputIndex,\n const std::string& inputNodeID, int inputIndex) const\n{\n QStringList list;\n\n list << QString::fromStdString(outputNodeID);\n list << QString::number(outputIndex);\n list << QString::fromStdString(inputNodeID);\n list << QString::number(inputIndex);\n\n return list.join(\",\");\n}\n\nvoid MainWindow::executeClicked()\n{\n app_->executeTerminalNodes();\n}\n\nvoid MainWindow::clearClicked()\n{\n bool ok = app_->clearAllNodes();\n\n if (ok)\n {\n scene_view_->setScene(nullptr);\n delete scene_;\n node_items_.clear();\n connection_items_.clear();\n \n scene_ = new QGraphicsScene;\n scene_view_->setScene(scene_);\n }\n}\n\nvoid MainWindow::testClicked()\n{\n app_->addTestScenario();\n}\n\nvoid MainWindow::showTypes(int state)\n{\n foreach (NodeItem* item, node_items_.values())\n {\n item->setShowIONames(state == Qt::Checked);\n }\n scene_->update(scene_view_->sceneRect());\n}\n<commit_msg>Remove TypesWidget implementation from MainWindow and use the copied implementation.<commit_after>\n\/\/ Includes.\n#include \"UI\/MainWindow.h\"\n#include \"UI\/NodeItem.h\"\n#include \"UI\/ConnectionItem.h\"\n#include \"UI\/ParametersDialog.h\"\n#include \"UI\/TypesWidget.h\"\n#include \"App\/App.h\"\n#include \"App\/Boundary\/NodeProxy.h\"\n#include \"App\/Boundary\/ConnectionProxy.h\"\n\n\/\/ Qt.\n#include <QGraphicsView>\n#include <QGraphicsScene>\n#include <QVBoxLayout>\n#include <QHBoxLayout>\n#include <QInputDialog>\n#include <QMessageBox>\n#include <QPushButton>\n#include <QTextEdit>\n#include <QStringListModel>\n#include <QGraphicsLineItem>\n#include <QCheckBox>\n\nMainWindow::MainWindow(App *app, QWidget *parent)\n : QMainWindow(parent)\n , types_list_(nullptr)\n , scene_view_(nullptr)\n , log_view_(nullptr)\n , show_types_box_(nullptr)\n , scene_(nullptr)\n , app_(app)\n , temp_line_item_(new QGraphicsLineItem)\n , selected_connector_on_press_(false)\n , selected_output_node_id_(\"\")\n , selected_output_index_(-1)\n , selected_input_node_id_(\"\")\n , selected_input_index_(-1)\n{\n scene_ = new QGraphicsScene;\n\n QPushButton* add_node_button = new QPushButton(tr(\"Add node\"));\n connect(add_node_button, &QPushButton::clicked, this, &MainWindow::addNodeClicked);\n QPushButton* execute_button = new QPushButton(tr(\"Execute\"));\n connect(execute_button, &QPushButton::clicked, this, &MainWindow::executeClicked);\n QPushButton* clear_button = new QPushButton(tr(\"Clear\"));\n connect(clear_button, &QPushButton::clicked, this, &MainWindow::clearClicked);\n QPushButton* test_button = new QPushButton(tr(\"Test\"));\n connect(test_button, &QPushButton::clicked, this, &MainWindow::testClicked);\n show_types_box_ = new QCheckBox(tr(\"Show types\"));\n connect(show_types_box_, &QCheckBox::stateChanged, this, &MainWindow::showTypes);\n\n\n QHBoxLayout* toolbar_layout = new QHBoxLayout;\n toolbar_layout->addWidget(add_node_button);\n toolbar_layout->addWidget(execute_button);\n toolbar_layout->addWidget(clear_button);\n toolbar_layout->addWidget(test_button);\n toolbar_layout->addWidget(show_types_box_);\n toolbar_layout->addStretch();\n\n scene_view_ = new NetworkSceneView(scene_);\n scene_view_->setDelegate(this);\n scene_view_->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Preferred);\n scene_view_->setAcceptDrops(true);\n\n QStringList types;\n std::vector<std::string> available_types = app->availableNodeTypes();\n for (int i = 0; i < (int)available_types.size(); ++i)\n {\n types << QString::fromStdString(available_types[i]);\n }\n types_list_ = new TypesWidget;\n types_list_->setMaximumWidth(150);\n types_list_->setSizePolicy(QSizePolicy::Maximum, QSizePolicy::Preferred);\n types_list_->addItems(types);\n types_list_->setSelectionMode(QAbstractItemView::SingleSelection);\n\n QHBoxLayout* central_layout = new QHBoxLayout;\n central_layout->addWidget(types_list_);\n central_layout->addWidget(scene_view_);\n\n log_view_ = new QTextEdit();\n log_view_->setReadOnly(true);\n log_view_->setMaximumHeight(200);\n log_view_->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Maximum);\n\n QVBoxLayout* main_layout = new QVBoxLayout;\n main_layout->addLayout(toolbar_layout);\n main_layout->addLayout(central_layout);\n main_layout->addWidget(log_view_);\n\n QWidget* central_widget = new QWidget;\n central_widget->setLayout(main_layout);\n setCentralWidget(central_widget);\n\n Logger::instance().addDelegate(this);\n}\n\nMainWindow::~MainWindow()\n{\n scene_view_->setScene(nullptr);\n delete scene_;\n delete temp_line_item_;\n node_items_.clear();\n connection_items_.clear();\n\n Logger::instance().removeDelegate(this);\n}\n\nstd::string MainWindow::promptString(const std::string &message)\n{\n std::string text = QInputDialog::getText(this, tr(\"Enter Input:\"), QString::fromStdString(message)).toStdString();\n return text;\n}\n\nbool MainWindow::promptBool(const std::string &message)\n{\n QMessageBox::StandardButton button = QMessageBox::question(this, tr(\"Enter Input:\"), QString::fromStdString(message));\n return button == QMessageBox::Yes;\n}\n\nstd::map<std::string, std::string> MainWindow::promptParameters(const std::vector<std::string> ¶meters)\n{\n ParametersDialog dialog(parameters, this);\n dialog.setWindowTitle(tr(\"Enter parameters:\"));\n\n int result = dialog.exec();\n if (result == QDialog::Accepted)\n {\n return dialog.parameterValues();\n }\n else\n {\n return std::map<std::string, std::string>();\n }\n}\n\nvoid MainWindow::displayError(const std::string &message)\n{\n QMessageBox::critical(this, \"Error!\", QString::fromStdString(message));\n}\n\nvoid MainWindow::nodeAdded(NodeProxy node)\n{\n addNode(node, this->last_drop_pos_);\n}\n\nvoid MainWindow::connectionAdded(ConnectionProxy connection)\n{\n NodeItem* output_node_item = node_items_.value(connection.outputNodeID());\n NodeItem* input_node_item = node_items_.value(connection.inputNodeID());\n\n ConnectionItem* item = new ConnectionItem(output_node_item, connection.outputIndex(),\n input_node_item, connection.inputIndex());\n scene_->addItem(item);\n\n QString connection_id = createConnectionID(connection.outputNodeID(), connection.outputIndex(),\n connection.inputNodeID(), connection.inputIndex());\n connection_items_.insert(connection_id, item);\n}\n\nvoid MainWindow::connectionRemoved(ConnectionProxy connection)\n{\n QString connection_id = createConnectionID(connection.outputNodeID(), connection.outputIndex(),\n connection.inputNodeID(), connection.inputIndex());\n ConnectionItem* item = connection_items_[connection_id];\n connection_items_.remove(connection_id);\n\n scene_->removeItem(item);\n scene_->views().at(0)->repaint();\n\n delete item;\n}\n\nvoid MainWindow::logMessage(const std::string &message)\n{\n log_view_->setTextColor(QColor(Qt::black));\n log_view_->append(QString::fromStdString(message));\n}\n\nvoid MainWindow::logError(const std::string &message)\n{\n log_view_->setTextColor(QColor(Qt::red));\n log_view_->append(QString::fromStdString(message));\n}\n\nvoid MainWindow::networkSceneViewPressedAt(const QPoint &pos)\n{\n selected_input_index_ = -1;\n selected_input_node_id_ = \"\";\n selected_output_index_ = -1;\n selected_output_node_id_ = \"\";\n\n selected_connector_on_press_ = selectInputIfUnderPos(pos) || selectOutputIfUnderPos(pos);\n\n if (selected_connector_on_press_)\n {\n QPointF item_pos = temp_line_item_->mapFromScene(scene_view_->mapToScene(pos));\n\n temp_line_.setPoints(item_pos, item_pos);\n temp_line_item_->setLine(temp_line_);\n scene_->addItem(temp_line_item_);\n }\n}\n\nvoid MainWindow::networkSceneViewReleasedAt(const QPoint &pos)\n{\n if (temp_line_item_->scene() == scene_)\n {\n scene_->removeItem(temp_line_item_);\n }\n bool selected_connector_on_release = selectInputIfUnderPos(pos) || selectOutputIfUnderPos(pos);\n\n if (selected_connector_on_press_ && selected_connector_on_release)\n {\n addConnectionBetweenSelectedNodes();\n }\n\n selected_connector_on_press_ = false;\n}\n\nvoid MainWindow::networkSceneViewMoved(const QPoint &pos)\n{\n if (selected_connector_on_press_)\n {\n QPointF item_pos = temp_line_item_->mapFromScene(scene_view_->mapToScene(pos));\n temp_line_.setP2(item_pos);\n temp_line_item_->setLine(temp_line_);\n }\n}\n\nvoid MainWindow::networkSceneViewNodeTypeDroppedAt(const QString &type, const QPoint &pos)\n{\n std::string type_str = type.toStdString();\n last_drop_pos_ = pos;\n app_->createNode(type_str);\n}\n\nvoid MainWindow::nodeMoved(NodeItem *item)\n{\n scene_->update(scene_view_->sceneRect());\n}\n\nbool MainWindow::selectInputIfUnderPos(const QPoint &pos)\n{\n QPointF scene_pos = scene_view_->mapToScene(pos);\n NodeItem* item_under_pos = dynamic_cast<NodeItem*>(scene_->itemAt(scene_pos, scene_view_->transform()));\n\n if (item_under_pos != nullptr)\n {\n QPointF item_pos = item_under_pos->mapFromScene(scene_pos);\n\n int input_index = item_under_pos->indexOfInputUnder(item_pos);\n if (input_index != -1)\n {\n selected_input_index_ = input_index;\n selected_input_node_id_ = item_under_pos->nodeID();\n return true;\n }\n else\n {\n return false;\n }\n }\n else\n {\n return false;\n }\n}\n\nbool MainWindow::selectOutputIfUnderPos(const QPoint& pos)\n{\n QPointF scene_pos = scene_view_->mapToScene(pos);\n NodeItem* item_under_pos = dynamic_cast<NodeItem*>(scene_->itemAt(scene_pos, scene_view_->transform()));\n\n if (item_under_pos != nullptr)\n {\n QPointF item_pos = item_under_pos->mapFromScene(scene_pos);\n\n int output_index = item_under_pos->indexOfOutputUnder(item_pos);\n if (output_index != -1)\n {\n selected_output_index_ = output_index;\n selected_output_node_id_ = item_under_pos->nodeID();\n return true;\n }\n else\n {\n return false;\n }\n }\n else\n {\n return false;\n }\n}\n\nvoid MainWindow::addNodeClicked()\n{\n foreach (QListWidgetItem* item, types_list_->selectedItems())\n {\n std::string type = item->text().toStdString();\n last_drop_pos_ = QPoint(0,0);\n app_->createNode(type);\n }\n}\n\nvoid MainWindow::addNode(const NodeProxy &node, const QPoint &pos)\n{\n NodeItem* node_item = new NodeItem(node, show_types_box_->isChecked());\n\n QPointF scene_pos = scene_view_->mapToScene(pos);\n QTransform transform;\n transform.translate(scene_pos.x(),scene_pos.y());\n node_item->setTransform(transform);\n\n scene_->addItem(node_item);\n node_items_.insert(node.id(), node_item);\n node_item->addDelegate(this);\n}\n\nvoid MainWindow::addConnectionBetweenSelectedNodes()\n{\n if (selected_input_node_id_.empty() || selected_input_index_ == -1 ||\n selected_output_node_id_.empty() || selected_output_index_ == -1)\n {\n return;\n }\n else\n {\n app_->connectNodes(selected_output_node_id_,\n selected_output_index_,\n selected_input_node_id_,\n selected_input_index_);\n }\n\n}\n\nQString MainWindow::createConnectionID(const std::string& outputNodeID, int outputIndex,\n const std::string& inputNodeID, int inputIndex) const\n{\n QStringList list;\n\n list << QString::fromStdString(outputNodeID);\n list << QString::number(outputIndex);\n list << QString::fromStdString(inputNodeID);\n list << QString::number(inputIndex);\n\n return list.join(\",\");\n}\n\nvoid MainWindow::executeClicked()\n{\n app_->executeTerminalNodes();\n}\n\nvoid MainWindow::clearClicked()\n{\n bool ok = app_->clearAllNodes();\n\n if (ok)\n {\n scene_view_->setScene(nullptr);\n delete scene_;\n node_items_.clear();\n connection_items_.clear();\n \n scene_ = new QGraphicsScene;\n scene_view_->setScene(scene_);\n }\n}\n\nvoid MainWindow::testClicked()\n{\n app_->addTestScenario();\n}\n\nvoid MainWindow::showTypes(int state)\n{\n foreach (NodeItem* item, node_items_.values())\n {\n item->setShowIONames(state == Qt::Checked);\n }\n scene_->update(scene_view_->sceneRect());\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ Created by volundr on 7\/6\/16.\n\/\/\n\n#include \"UartInterface.h\"\n\nnamespace bno055 {\n\n \/**\n * Opens communications with the UART device found at location 'deviceFile'\n * This code was taken from the 'Using the UART' tutorial page found at\n * http:\/\/www.raspberry-projects.com\/pi\/programming-in-c\/uart-serial-port\/using-the-uart\n *\/\n bool UartInterface::openPort(const char* deviceFile, tcflag_t baudRate) {\n \/*\n * Close any existing serial communications\n *\/\n closePort();\n \/*\n * OPEN THE UART\n * The flags (defined in fcntl.h):\n * \tAccess modes (use 1 of these):\n * \t\tO_RDONLY - Open for reading only.\n * \t\tO_RDWR - Open for reading and writing.\n * \t\tO_WRONLY - Open for writing only.\n *\n * \tO_NDELAY \/ O_NONBLOCK (same function) -\n * \tEnables nonblocking mode. When set read requests on the file can return immediately with a failure status\n * \tif there is no input immediately available (instead of blocking). Likewise, sendData requests can also return\n * \timmediately with a failure status if the output can't be written immediately.\n *\n * \tO_NOCTTY -\n * \tWhen set and path identifies a terminal device, open() shall not cause the terminal device to become the\n * \tcontrolling terminal for the process.\n *\/\n\/\/ uartFile = open(deviceFile, O_RDWR | O_NOCTTY | O_SYNC);\t\t\/\/Open in synchronous mode\n uartFile = open(deviceFile, O_RDWR | O_NOCTTY | O_NONBLOCK);\t\t\/\/Open in asynchronous mode\n if (uartFile == -1) {\n return false;\n }\n\n \/*\n * CONFIGURE THE UART\n * The flags (defined in \/usr\/include\/termios.h -\n * see http:\/\/pubs.opengroup.org\/onlinepubs\/007908799\/xsh\/termios.h.html):\n *\n * \tBaud rate: B1200, B2400, B4800, B9600, B19200, B38400, B57600, B115200, B230400, B460800, B500000, B576000,\n * \t B921600, B1000000, B1152000, B1500000, B2000000, B2500000, B3000000, B3500000, B4000000\n * \tCSIZE : CS5, CS6, CS7, CS8\n * \tCLOCAL : Ignore modem status lines\n * \tCREAD : Enable receiver\n * \tIGNPAR : Ignore characters with parity errors\n * \tICRNL : Map CR to NL on input (Use for ASCII comms where you want to auto correct end of line characters\n * \t - don't use for bianry comms!)\n * \tPARENB : Parity enable\n * \tPARODD : Odd parity (else even)\n *\/\n struct termios options;\n tcgetattr(uartFile, &options);\n options.c_cflag = baudRate | CS8 | CLOCAL | CREAD | CSTOPB;\t\t\/\/<Set baud rate\n options.c_iflag = IGNPAR;\n options.c_oflag = 0;\n options.c_lflag = 0;\n tcflush(uartFile, TCIOFLUSH);\n tcsetattr(uartFile, TCSANOW, &options);\n\n return true;\n }\n\n bool UartInterface::closePort() {\n if (uartFile != -1) {\n close(uartFile);\n uartFile = -1;\n return true;\n }\n return false;\n }\n\n UartInterface::~UartInterface() {\n if (uartFile != -1) {\n close(uartFile);\n }\n }\n\n int64_t UartInterface::sendData(uint8_t* data, uint32_t length) {\n if (uartFile == -1) {\n return -1;\n } else {\n return (int64_t)write(uartFile, data, length);\n }\n }\n\n int64_t UartInterface::recvData(uint8_t* empty, uint32_t maxLength) {\n if (uartFile == -1) {\n return -1;\n } else {\n return (int64_t)read(uartFile, (void*)empty, maxLength);\n }\n }\n\n}\n<commit_msg>removed second stop bit<commit_after>\/\/\n\/\/ Created by volundr on 7\/6\/16.\n\/\/\n\n#include \"UartInterface.h\"\n\nnamespace bno055 {\n\n \/**\n * Opens communications with the UART device found at location 'deviceFile'\n * This code was taken from the 'Using the UART' tutorial page found at\n * http:\/\/www.raspberry-projects.com\/pi\/programming-in-c\/uart-serial-port\/using-the-uart\n *\/\n bool UartInterface::openPort(const char* deviceFile, tcflag_t baudRate) {\n \/*\n * Close any existing serial communications\n *\/\n closePort();\n \/*\n * OPEN THE UART\n * The flags (defined in fcntl.h):\n * \tAccess modes (use 1 of these):\n * \t\tO_RDONLY - Open for reading only.\n * \t\tO_RDWR - Open for reading and writing.\n * \t\tO_WRONLY - Open for writing only.\n *\n * \tO_NDELAY \/ O_NONBLOCK (same function) -\n * \tEnables nonblocking mode. When set read requests on the file can return immediately with a failure status\n * \tif there is no input immediately available (instead of blocking). Likewise, sendData requests can also return\n * \timmediately with a failure status if the output can't be written immediately.\n *\n * \tO_NOCTTY -\n * \tWhen set and path identifies a terminal device, open() shall not cause the terminal device to become the\n * \tcontrolling terminal for the process.\n *\/\n\/\/ uartFile = open(deviceFile, O_RDWR | O_NOCTTY | O_SYNC);\t\t\/\/Open in synchronous mode\n uartFile = open(deviceFile, O_RDWR | O_NOCTTY | O_NONBLOCK);\t\t\/\/Open in asynchronous mode\n if (uartFile == -1) {\n return false;\n }\n\n \/*\n * CONFIGURE THE UART\n * The flags (defined in \/usr\/include\/termios.h -\n * see http:\/\/pubs.opengroup.org\/onlinepubs\/007908799\/xsh\/termios.h.html):\n *\n * \tBaud rate: B1200, B2400, B4800, B9600, B19200, B38400, B57600, B115200, B230400, B460800, B500000, B576000,\n * \t B921600, B1000000, B1152000, B1500000, B2000000, B2500000, B3000000, B3500000, B4000000\n * \tCSIZE : CS5, CS6, CS7, CS8\n * \tCLOCAL : Ignore modem status lines\n * \tCREAD : Enable receiver\n * \tIGNPAR : Ignore characters with parity errors\n * \tICRNL : Map CR to NL on input (Use for ASCII comms where you want to auto correct end of line characters\n * \t - don't use for bianry comms!)\n * \tPARENB : Parity enable\n * \tPARODD : Odd parity (else even)\n *\/\n struct termios options;\n tcgetattr(uartFile, &options);\n options.c_cflag = baudRate | CS8 | CLOCAL | CREAD;\t\t\/\/<Set baud rate\n options.c_iflag = IGNPAR;\n options.c_oflag = 0;\n options.c_lflag = 0;\n tcflush(uartFile, TCIOFLUSH);\n tcsetattr(uartFile, TCSANOW, &options);\n\n return true;\n }\n\n bool UartInterface::closePort() {\n if (uartFile != -1) {\n close(uartFile);\n uartFile = -1;\n return true;\n }\n return false;\n }\n\n UartInterface::~UartInterface() {\n if (uartFile != -1) {\n close(uartFile);\n }\n }\n\n int64_t UartInterface::sendData(uint8_t* data, uint32_t length) {\n if (uartFile == -1) {\n return -1;\n } else {\n return (int64_t)write(uartFile, data, length);\n }\n }\n\n int64_t UartInterface::recvData(uint8_t* empty, uint32_t maxLength) {\n if (uartFile == -1) {\n return -1;\n } else {\n return (int64_t)read(uartFile, (void*)empty, maxLength);\n }\n }\n\n}\n<|endoftext|>"} {"text":"<commit_before>#include <SFML\/Graphics.hpp>\n#include \"grid.h\"\n#include \"cell.h\"\n#include <iostream>\n\n\nusing namespace sf;\n\nint main()\n{\n\t\/\/Calling grid here\n\t\/\/this will be 1027 \/ 32 which is defend in grid.cpp \n\tint gridWidth = grid::windowWidth \/ grid::x;\n\t\/\/this will be 720 \/ 32 which also defend in grid.cpp\n\tint gridHeight = grid::windowHeight \/ grid::y;\n\t\/\/Calling cell setup \n\tcell::Setup(gridWidth, gridHeight);\n\tint drawingCells[32][32];\n\t\/\/starting with the window \n\tsf::RenderWindow window(sf::VideoMode(grid::windowWidth, grid::windowHeight), \"Welcome to Mohanad's Game Of Life\");\n\tbool Gamestart = false;\n\twhile (window.isOpen())\n\t{\n\t\tsf::Event event;\n\t\twhile (window.pollEvent(event))\n\t\t{\n\t\t\tif (event.type == sf::Event::Closed)\n\t\t\t\twindow.close();\n\t\t\tif (event.type == Event::KeyPressed) {\n\t\t\t\tswitch (event.key.code) {\n\t\t\t\tcase Keyboard::Escape:\n\t\t\t\t\tprintf(\"Bye Bye and see you next time \\n\");\n\t\t\t\t\texit(0);\n\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (event.type == sf::Event::MouseButtonPressed) {\n\n\t\t\t\tint clickX = (event.mouseButton.x \/ gridWidth);\n\t\t\t\tint clickY = (event.mouseButton.y \/ gridHeight);\n\t\t\t\tdrawingCells[clickX][clickY] = drawingCells[clickX][clickY] == 1 ? 0.5 : 1;\n\n\t\t\t\t\/\/checking is the mouse clicked or not\n\t\t\t\tprintf(\"mouse clicked \\n\");\n\t\t\t}\n\t\t\t\/\/this will run the game \n\t\t\tif (event.type == sf::Event::KeyPressed && event.key.code == sf::Keyboard::R)\n\t\t\t{\n\n\t\t\t\tif (Gamestart = true) {\n\t\t\t\t\tfor (size_t row = 0; row < gridHeight; row++)\n\t\t\t\t\t{\n\n\t\t\t\t\t\tint count = 0;\n\t\t\t\t\t\tif (drawingCells[32 - 1][32 - 1]) {\n\t\t\t\t\t\t\t++count;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (drawingCells[32 - 1][32 - 1]) {\n\t\t\t\t\t\t\t++count;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (drawingCells[32 + 1][32 - 1]) {\n\t\t\t\t\t\t\t++count;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (drawingCells[32 + 1][32]) {\n\t\t\t\t\t\t\t++count;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (drawingCells[32 + 1][32 + 1]) {\n\t\t\t\t\t\t\t++count;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (drawingCells[32][32 + 1]) {\n\t\t\t\t\t\t\t++count;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (drawingCells[32 - 1][32 + 1]) {\n\t\t\t\t\t\t\t++count;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (drawingCells[32 - 1][32]) {\n\t\t\t\t\t\t\t++count;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\n\t\t\t\t\t\t\tfor (int x = 0; x < gridWidth; x++) {\n\t\t\t\t\t\t\t\tfor (int y = 0; y < gridHeight; y++) {\n\t\t\t\t\t\t\t\t\tdrawingCells[x][y] = drawingCells[x][y];\n\t\t\t\t\t\t\t\t}\n\n\n\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tprintf(\"Start \\n\");\n\t\t\t\t\t}\n\n\n\t\t\t\t\twindow.clear();\n\n\t\t\t\t\tfor (size_t row = 0; row < grid::x; row++)\n\t\t\t\t\t{\n\t\t\t\t\t\tfor (size_t column = 0; column < grid::y; column++)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tint state = drawingCells[row][column];\n\t\t\t\t\t\t\tif (state == 1) {\n\t\t\t\t\t\t\t\tcell::Setcolor(Color::White);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse if (state == 0) {\n\t\t\t\t\t\t\t\tcell::Setcolor(Color::Blue);\n\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tcell::Setposition((column * gridWidth), (row * gridHeight));\n\t\t\t\t\t\t\twindow.draw(cell::target);\n\n\t\t\t\t\t\t}\n\n\t\t\t\t\t}\n\t\t\t\t\twindow.display();\n\n\t\t\t\t}\n\n\n\t\t\t}\n\n\t\t}\n\t}\n}\n<commit_msg>Adding the mouse<commit_after>#include <SFML\/Graphics.hpp>\n#include \"grid.h\"\n#include \"cell.h\"\n#include <iostream>\n\n\nusing namespace sf;\n\nint main()\n{\n\t\/\/Calling grid here\n\t\/\/this will be 1027 \/ 32 which is defend in grid.cpp \n\tint gridWidth = grid::windowWidth \/ grid::x;\n\t\/\/this will be 720 \/ 32 which also defend in grid.cpp\n\tint gridHeight = grid::windowHeight \/ grid::y;\n\t\/\/Calling cell setup \n\tcell::Setup(gridWidth, gridHeight);\n\tint drawingCells[32][32];\n\t\/\/starting with the window \n\tsf::RenderWindow window(sf::VideoMode(grid::windowWidth, grid::windowHeight), \"Welcome to Mohanad's Game Of Life\");\n\tbool Gamestart = false;\n\twhile (window.isOpen())\n\t{\n\t\tsf::Event event;\n\t\twhile (window.pollEvent(event))\n\t\t{\n\t\t\tif (event.type == sf::Event::Closed)\n\t\t\t\twindow.close();\n\t\t\tif (event.type == Event::KeyPressed) {\n\t\t\t\tswitch (event.key.code) {\n\t\t\t\tcase Keyboard::Escape:\n\t\t\t\t\tprintf(\"Bye Bye and see you next time \\n\");\n\t\t\t\t\texit(0);\n\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (event.type == sf::Event::MouseButtonPressed) {\n\t\t\t\tint cell = 0;\n\t\t\t\tint clickX = (event.mouseButton.x \/ gridWidth);\n\t\t\t\tint clickY = (event.mouseButton.y \/ gridHeight);\n\t\t\t\t\tif (Mouse::isButtonPressed(Mouse::Left)) {\n\t\t\t\t\t\tdrawingCells[clickX][clickY] = drawingCells[clickX][clickY] == 1 ? 0.5 : 1;\n\t\t\t\t\t\tcell += (clickX + clickY ? 1 : 0);\n\t\t\t\t\t\tdrawingCells[event.mouseButton.x][event.mouseButton.y];\n\t\t\t\t\t\t\/\/checking is the mouse clicked or not\n\t\t\t\t\t\tprintf(\"mouse clicked \\n\");\n\t\t\t\t\t\t\n\t\t\t\t\t}\n\t\t\t}\n\t\t\t\/\/this will run the game \n\t\t\tif (event.type == sf::Event::KeyPressed && event.key.code == sf::Keyboard::R)\n\t\t\t{\n\n\t\t\t\tif (Gamestart = true) {\n\t\t\t\t\tfor (size_t row = 0; row < gridHeight; row++)\n\t\t\t\t\t{\n\n\t\t\t\t\t\tint count = 0;\n\t\t\t\t\t\tif (drawingCells[32 - 1][32 - 1]) {\n\t\t\t\t\t\t\t++count;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (drawingCells[32 - 1][32 - 1]) {\n\t\t\t\t\t\t\t++count;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (drawingCells[32 + 1][32 - 1]) {\n\t\t\t\t\t\t\t++count;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (drawingCells[32 + 1][32]) {\n\t\t\t\t\t\t\t++count;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (drawingCells[32 + 1][32 + 1]) {\n\t\t\t\t\t\t\t++count;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (drawingCells[32][32 + 1]) {\n\t\t\t\t\t\t\t++count;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (drawingCells[32 - 1][32 + 1]) {\n\t\t\t\t\t\t\t++count;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (drawingCells[32 - 1][32]) {\n\t\t\t\t\t\t\t++count;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\n\t\t\t\t\t\t\tfor (int x = 0; x < gridWidth; x++) {\n\t\t\t\t\t\t\t\tfor (int y = 0; y < gridHeight; y++) {\n\t\t\t\t\t\t\t\t\tdrawingCells[x][y] = drawingCells[x][y];\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tprintf(\"Start \\n\");\n\t\t\t\t\t}\n\n\n\t\t\t\t\twindow.clear();\n\n\t\t\t\t\tfor (size_t row = 0; row < grid::x; row++)\n\t\t\t\t\t{\n\t\t\t\t\t\tfor (size_t column = 0; column < grid::y; column++)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tint state = drawingCells[row][column];\n\t\t\t\t\t\t\tif (state == 1) {\n\t\t\t\t\t\t\t\tcell::Setcolor(Color::White);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse if (state == 0) {\n\t\t\t\t\t\t\t\tcell::Setcolor(Color::Blue);\n\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tcell::Setposition((column * gridWidth), (row * gridHeight));\n\t\t\t\t\t\t\twindow.draw(cell::target);\n\n\t\t\t\t\t\t}\n\n\t\t\t\t\t}\n\t\t\t\t\twindow.display();\n\n\t\t\t\t}\n\n\n\t\t\t}\n\n\t\t}\n\t}\n}\n<|endoftext|>"} {"text":"<commit_before>#include <SFML\/Graphics.hpp>\n#include \"grid.h\"\n#include \"cell.h\"\n\nusing namespace sf;\n\nint main()\n{\n\t\/\/Calling grid here\n\tint gridWidth = grid::windowWidth \/ grid::x;\n\tint gridHeight = grid::windowHeight \/ grid::y;\n\t\/\/Calling cell setup \n\tcell::Setup(gridWidth, gridHeight);\n\tint drawingCells[32][32];\n\t\/\/starting with the window \n\tsf::RenderWindow window(sf::VideoMode(grid::windowWidth, grid::windowHeight), \"Welcome to Mohanad Game Of Life\");\n\tsf::Event windowEvent;\n\tcell::Setup(gridWidth, gridHeight);\n\twhile (window.isOpen())\n\t{\n\t\tsf::Event event;\n\t\twhile (window.pollEvent(event))\n\t\t{\n\t\t\tif (event.type == sf::Event::Closed)\n\t\t\t\twindow.close();\n\t\t}\n\t\tfor (rsize_t row = 0; row < grid::x; row++)\n\t\t{\n\t\t\tfor (rsize_t column = 0; column < grid::y; column++)\n\t\t\t{\n\t\t\t\tint total = drawingCells[32][32];\n\n\t\t\t\tif (total == 1) {\n\t\t\t\t\tcell::Setcolor(Color::White);\n\t\t\t\t}\n\t\t\t\telse if (total == 0) {\n\t\t\t\t\tcell::Setcolor(Color::Blue);\n\t\t\t\t}\n\t\t\t\tcell::Setposition((column * gridWidth), (row * gridHeight));\n\t\t\t\twindow.draw(cell::target);\n\t\t\t\twindow.setActive();\n\t\t\t\twindow.display();\n\t\t\t}\n\t\t}\n\t}\n}<commit_msg>Adding the key pressed<commit_after>#include <SFML\/Graphics.hpp>\n#include \"grid.h\"\n#include \"cell.h\"\n\nusing namespace sf;\n\nint main()\n{\n\t\/\/Calling grid here\n\tint gridWidth = grid::windowWidth \/ grid::x;\n\tint gridHeight = grid::windowHeight \/ grid::y;\n\t\/\/Calling cell setup \n\tcell::Setup(gridWidth, gridHeight);\n\tint drawingCells[32][32];\n\t\/\/starting with the window \n\tsf::RenderWindow window(sf::VideoMode(grid::windowWidth, grid::windowHeight), \"Welcome to Mohanad Game Of Life\");\n\tcell::Setup(gridWidth, gridHeight);\n\n\n\twhile (window.isOpen())\n\t{\n\t\tsf::Event event;\n\t\twhile (window.pollEvent(event))\n\t\t{\n\t\t\tif (event.type == sf::Event::Closed)\n\t\t\t\twindow.close();\n\t\t\tif (event.type == Event::KeyPressed) {\n\t\t\t\tswitch (event.key.code) {\n\t\t\t\tcase Keyboard::Escape:\n\t\t\t\t\texit(0);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\t\t\tfor (rsize_t row = 0; row < grid::x; row++)\n\t\t\t\t\t{\n\t\t\t\t\t\tfor (rsize_t column = 0; column < grid::y; column++)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tint total = drawingCells[32][32];\n\n\t\t\t\t\t\t\tif (total == 1) {\n\t\t\t\t\t\t\t\tcell::Setcolor(Color::White);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse if (total == 0) {\n\t\t\t\t\t\t\t\tcell::Setcolor(Color::Blue);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tcell::Setposition((column * gridWidth), (row * gridHeight));\n\t\t\t\t\t\t\twindow.draw(cell::target);\n\t\t\t\t\t\t\twindow.setActive();\n\t\t\t\t\t\t\twindow.display();\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n#include <cstdlib>\n#include <string>\n#include <vector>\n#include <array>\n#include <cmath>\n#include <opencv2\/opencv.hpp>\n#include <opencv2\/highgui.hpp>\n#include <opencv2\/imgproc.hpp>\n#include <ApplicationServices\/ApplicationServices.h>\n#include <unistd.h>\nusing namespace cv;\nCGEventRef move;\nint main()\n{\n\twhile(true)\n\t{\n\t\tmoveCursor(getEyePos());\n\t}\n\treturn 0;\n}\nvoid moveCursor(int x, y)\n{\n\tmove = CGEventCreateMouseEvent(NULL, kCGEventMouseMoved, CGPointMake(200, 200), kCGMouseButtonLeft);\n}\nstd::array<int, 2> getEyePos(std::string LR)\n{\n\tstd::array eyePosition;\n\treturn eyePosition;\n}<commit_msg>TempStash<commit_after>#include <iostream>\n#include <cstdlib>\n#include <string>\n#include <vector>\n#include <array>\n#include <cmath>\n#include <opencv2\/opencv.hpp>\n#include <opencv2\/highgui.hpp>\n#include <opencv2\/imgproc.hpp>\n#include <ApplicationServices\/ApplicationServices.h>\n#include <unistd.h>\nusing namespace cv;\nCGEventRef move;\nint main()\n{\n\tstd::cout << \"Program initiated by user\" << std::endl;\n\tVideoCapture cap(0);\n\tif (!cap.isOpened())\n\t{\n\t\tstd::cout << \"ERROR: Webcam failed to initialize\"\n\t\treturn -1;\n\t}\n\telse\n\t\tstd::cout << \"Webcam initiated\" << std::endl;\n\tnamedWindow(\"Hack NJIT 2016\", CV_WINDOW_AUTOSIZE);\n\twhile(true)\n\t{\n\t\tmoveCursor(getEyePos());\n\t}\n\treturn 0;\n}\nvoid moveCursor(int x, y)\n{\n\tmove = CGEventCreateMouseEvent(NULL, kCGEventMouseMoved, CGPointMake(200, 200), kCGMouseButtonLeft);\n}\nstd::array<int, 2> getEyePos(std::string LR)\n{\n\tstd::array eyePosition;\n\treturn eyePosition;\n}<|endoftext|>"} {"text":"<commit_before>\/* Begin CVS Header\n $Source: \/Volumes\/Home\/Users\/shoops\/cvs\/copasi_dev\/copasi\/CopasiSE\/CopasiSE.cpp,v $\n $Revision: 1.9 $\n $Name: $\n $Author: shoops $ \n $Date: 2005\/02\/18 16:20:37 $\n End CVS Header *\/\n\n\/\/ Main\n\/\/\n\/\/ (C) Stefan Hoops 2002\n\/\/\n\n#include <stdlib.h>\n#include <sstream>\n#include <string>\n#include <iostream>\n\n#define COPASI_MAIN\n#define COPASI_TRACE_CONSTRUCTION\n\n#include \"copasi.h\"\n#include \"CopasiDataModel\/CCopasiDataModel.h\"\n#include \"utilities\/CCopasiMessage.h\"\n#include \"utilities\/CCopasiException.h\"\n#include \"utilities\/CCopasiTask.h\"\n#include \"commandline\/COptionParser.h\"\n#include \"commandline\/COptions.h\"\n#include \"function\/CFunctionDB.h\"\n\nint main(int argc, char *argv[])\n{\n try\n {\n \/\/ Parse the commandline options\n COptions::init(argc, argv);\n }\n\n catch (copasi::autoexcept &e)\n {\n switch (e.get_autothrow_id())\n {\n case copasi::autothrow_help:\n std::cout << \"Usage: \" << argv[0] << \" [options]\\n\";\n std::cout << e.what();\n }\n\n return 1;\n }\n\n catch (copasi::option_error &e)\n {\n std::cerr << argv[0] << \": \" << e.what() << \"\\n\";\n std::cerr << e.get_help_comment() << std::endl;\n\n return 1;\n }\n\n \/\/ Create the root container.\n CCopasiContainer::init();\n\n \/\/ Create the global data model.\n CCopasiDataModel::Global = new CCopasiDataModel;\n\n const COptions::nonOptionType & Files = COptions::getNonOptions();\n\n if (!COptions::compareValue(\"ImportSBML\", std::string(\"\")))\n {\n \/\/ Import the SBML File\n std::string ImportSBML;\n COptions::getValue(\"ImportSBML\", ImportSBML);\n CCopasiDataModel::Global->importSBML(ImportSBML);\n\n \/\/ Save the COPASI File, which is the only thing to do.\n std::string Save;\n COptions::getValue(\"Save\", Save);\n CCopasiDataModel::Global->saveModel(Save);\n }\n\n COptions::nonOptionType::const_iterator it = Files.begin();\n COptions::nonOptionType::const_iterator end = Files.end();\n\n for (; it != end; ++it)\n {\n CCopasiDataModel::Global->loadModel(*it);\n\n \/\/ Check whether exporting to SBML is requested.\n if (!COptions::compareValue(\"ExportSBML\", std::string(\"\")))\n {\n \/\/ Export the SBML File\n std::string ExportSBML;\n COptions::getValue(\"ExportSBML\", ExportSBML);\n CCopasiDataModel::Global->exportSBML(ExportSBML);\n\n \/\/ Since only one export file name can be specified we\n \/\/ stop execution.\n return 0;\n }\n\n CCopasiVectorN< CCopasiTask > & TaskList = * CCopasiDataModel::Global->getTaskList();\n unsigned C_INT32 i, imax = TaskList.size();\n\n for (i = 0; i < imax; i++)\n if (TaskList[i]->isScheduled())\n {\n TaskList[i]->initialize();\n TaskList[i]->process();\n TaskList[i]->restore();\n }\n\n \/\/ Check whether a file for saving the resulting model is given\n if (!COptions::compareValue(\"Save\", std::string(\"\")))\n {\n std::string Save;\n COptions::getValue(\"Save\", Save);\n CCopasiDataModel::Global->saveModel(Save);\n\n \/\/ Since only one save file name can be specified we\n \/\/ stop execution.\n return 0;\n }\n\n CCopasiDataModel::Global->saveModel(\"\");\n }\n\n \/\/ catch (CCopasiException Exception)\n \/\/ {\n \/\/ std::cout << Exception.getMessage().getText() << std::endl;\n \/\/}\n\n pdelete(CCopasiDataModel::Global);\n pdelete(CCopasiContainer::Root);\n\n std::cout << \"Leaving main program.\" << std::endl;\n return 0;\n}\n<commit_msg>Set the model of the problem of task before task initialization.<commit_after>\/* Begin CVS Header\n $Source: \/Volumes\/Home\/Users\/shoops\/cvs\/copasi_dev\/copasi\/CopasiSE\/CopasiSE.cpp,v $\n $Revision: 1.10 $\n $Name: $\n $Author: shoops $ \n $Date: 2005\/02\/25 01:51:46 $\n End CVS Header *\/\n\n\/\/ Main\n\/\/\n\/\/ (C) Stefan Hoops 2002\n\/\/\n\n#include <stdlib.h>\n#include <sstream>\n#include <string>\n#include <iostream>\n\n#define COPASI_MAIN\n#define COPASI_TRACE_CONSTRUCTION\n\n#include \"copasi.h\"\n#include \"CopasiDataModel\/CCopasiDataModel.h\"\n#include \"utilities\/CCopasiMessage.h\"\n#include \"utilities\/CCopasiException.h\"\n#include \"utilities\/CCopasiTask.h\"\n#include \"utilities\/CCopasiProblem.h\"\n#include \"commandline\/COptionParser.h\"\n#include \"commandline\/COptions.h\"\n#include \"function\/CFunctionDB.h\"\n\nint main(int argc, char *argv[])\n{\n try\n {\n \/\/ Parse the commandline options\n COptions::init(argc, argv);\n }\n\n catch (copasi::autoexcept &e)\n {\n switch (e.get_autothrow_id())\n {\n case copasi::autothrow_help:\n std::cout << \"Usage: \" << argv[0] << \" [options]\\n\";\n std::cout << e.what();\n }\n\n return 1;\n }\n\n catch (copasi::option_error &e)\n {\n std::cerr << argv[0] << \": \" << e.what() << \"\\n\";\n std::cerr << e.get_help_comment() << std::endl;\n\n return 1;\n }\n\n \/\/ Create the root container.\n CCopasiContainer::init();\n\n \/\/ Create the global data model.\n CCopasiDataModel::Global = new CCopasiDataModel;\n\n const COptions::nonOptionType & Files = COptions::getNonOptions();\n\n if (!COptions::compareValue(\"ImportSBML\", std::string(\"\")))\n {\n \/\/ Import the SBML File\n std::string ImportSBML;\n COptions::getValue(\"ImportSBML\", ImportSBML);\n CCopasiDataModel::Global->importSBML(ImportSBML);\n\n \/\/ Save the COPASI File, which is the only thing to do.\n std::string Save;\n COptions::getValue(\"Save\", Save);\n CCopasiDataModel::Global->saveModel(Save);\n }\n\n COptions::nonOptionType::const_iterator it = Files.begin();\n COptions::nonOptionType::const_iterator end = Files.end();\n\n for (; it != end; ++it)\n {\n CCopasiDataModel::Global->loadModel(*it);\n\n \/\/ Check whether exporting to SBML is requested.\n if (!COptions::compareValue(\"ExportSBML\", std::string(\"\")))\n {\n \/\/ Export the SBML File\n std::string ExportSBML;\n COptions::getValue(\"ExportSBML\", ExportSBML);\n CCopasiDataModel::Global->exportSBML(ExportSBML);\n\n \/\/ Since only one export file name can be specified we\n \/\/ stop execution.\n return 0;\n }\n\n CCopasiVectorN< CCopasiTask > & TaskList = * CCopasiDataModel::Global->getTaskList();\n unsigned C_INT32 i, imax = TaskList.size();\n\n for (i = 0; i < imax; i++)\n if (TaskList[i]->isScheduled())\n {\n TaskList[i]->getProblem()->setModel(CCopasiDataModel::Global->getModel());\n\n TaskList[i]->initialize();\n TaskList[i]->process();\n TaskList[i]->restore();\n }\n\n \/\/ Check whether a file for saving the resulting model is given\n if (!COptions::compareValue(\"Save\", std::string(\"\")))\n {\n std::string Save;\n COptions::getValue(\"Save\", Save);\n CCopasiDataModel::Global->saveModel(Save);\n\n \/\/ Since only one save file name can be specified we\n \/\/ stop execution.\n return 0;\n }\n\n CCopasiDataModel::Global->saveModel(\"\");\n }\n\n \/\/ catch (CCopasiException Exception)\n \/\/ {\n \/\/ std::cout << Exception.getMessage().getText() << std::endl;\n \/\/}\n\n pdelete(CCopasiDataModel::Global);\n pdelete(CCopasiContainer::Root);\n\n std::cout << \"Leaving main program.\" << std::endl;\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Begin CVS Header\n\/\/ $Source: \/Volumes\/Home\/Users\/shoops\/cvs\/copasi_dev\/copasi\/model\/CModelValue.cpp,v $\n\/\/ $Revision: 1.45 $\n\/\/ $Name: $\n\/\/ $Author: shoops $\n\/\/ $Date: 2007\/10\/02 18:18:05 $\n\/\/ End CVS Header\n\n\/\/ Copyright (C) 2007 by Pedro Mendes, Virginia Tech Intellectual\n\/\/ Properties, Inc. and EML Research, gGmbH.\n\/\/ All rights reserved.\n\n#include <iostream>\n#include <string>\n#include <vector>\n#include <limits>\n\n#include \"copasi.h\"\n\n#include \"CModel.h\"\n#include \"CModelValue.h\"\n\n#include \"CopasiDataModel\/CCopasiDataModel.h\"\n#include \"function\/CExpression.h\"\n#include \"report\/CCopasiObjectReference.h\"\n#include \"report\/CKeyFactory.h\"\n#include \"utilities\/utility.h\"\n\n\/\/static\nconst std::string CModelEntity::StatusName[] =\n {\n \"fixed\",\n \"assignment\",\n \"reactions\",\n \"ode\",\n \"time\",\n \"\"\n };\n\n\/\/static\nconst char * CModelEntity::XMLStatus[] =\n {\n \"fixed\",\n \"assignment\",\n \"reactions\",\n \"ode\",\n \"time\",\n NULL\n };\n\n\/\/ the \"variable\" keyword is used for compatibility reasons. It actually means \"this metab is part\n\/\/ of the reaction network, copasi needs to figure out if it is independent, dependent (moieties) or unused.\"\n\nCModelEntity::CModelEntity(const std::string & name,\n const CCopasiContainer * pParent,\n const std::string & type,\n const unsigned C_INT32 & flag):\n CCopasiContainer(name, pParent, type, (flag | CCopasiObject::Container | CCopasiObject::ValueDbl | CCopasiObject::ModelEntity)),\n mKey(\"\"),\n mpValueData(NULL),\n mpValueAccess(NULL),\n mpIValue(NULL),\n mRate(0.0),\n mpExpression(NULL),\n mpInitialExpression(NULL),\n mStatus(FIXED),\n mUsed(false),\n mUsedOnce(false),\n mpModel(NULL)\n{\n initObjects();\n\n *mpIValue = 1.0;\n *mpValueData = std::numeric_limits<C_FLOAT64>::quiet_NaN();\n\n CONSTRUCTOR_TRACE;\n}\n\nCModelEntity::CModelEntity(const CModelEntity & src,\n const CCopasiContainer * pParent):\n CCopasiContainer(src, pParent),\n mKey(\"\"),\n mpValueData(NULL),\n mpValueAccess(NULL),\n mpIValue(NULL),\n mRate(src.mRate),\n mpExpression(new CExpression(*src.mpExpression)),\n mpInitialExpression(new CExpression(*src.mpInitialExpression)),\n mStatus(FIXED),\n mUsed(false),\n mUsedOnce(false),\n mpModel(NULL)\n{\n initObjects();\n\n setStatus(src.mStatus);\n\n *mpValueData = *src.mpValueData;\n *mpIValue = *src.mpIValue;\n\n CONSTRUCTOR_TRACE;\n}\n\nCModelEntity::~CModelEntity()\n{\n if (mpModel)\n mpModel->getStateTemplate().remove(this);\n\n \/\/ After the above call we definitely own the data and\n \/\/ therfore must destroy them.\n\n pdelete(mpValueData);\n pdelete(mpIValue);\n pdelete(mpExpression);\n pdelete(mpInitialExpression);\n\n DESTRUCTOR_TRACE;\n}\n\nconst std::string & CModelEntity::getKey() const {return mKey;}\n\nconst C_FLOAT64 & CModelEntity::getValue() const {return *mpValueAccess;}\n\nconst C_FLOAT64 & CModelEntity::getInitialValue() const\n {\n if (mpInitialExpression != NULL)\n const_cast< CModelEntity * >(this)->refreshInitialValue();\n\n return *mpIValue;\n }\n\nconst CModelEntity::Status & CModelEntity::getStatus() const {return mStatus;}\n\nbool CModelEntity::compile()\n{\n bool success = true;\n\n std::set< const CCopasiObject * > NoDependencies;\n std::vector< CCopasiContainer * > listOfContainer;\n\n switch (mStatus)\n {\n case ASSIGNMENT:\n listOfContainer.push_back(getObjectAncestor(\"Model\"));\n\n success &= mpExpression->compile(listOfContainer);\n mpValueReference->setDirectDependencies(mpExpression->getDirectDependencies());\n\n pdelete(mpInitialExpression);\n mpInitialExpression = CExpression::createInitialExpression(*mpExpression);\n\n if (mpInitialExpression != NULL)\n {\n success &= mpInitialExpression->compile(listOfContainer);\n mpIValueReference->setDirectDependencies(mpInitialExpression->getDirectDependencies());\n mpIValueReference->setRefresh(this, &CModelEntity::refreshInitialValue);\n }\n else\n {\n mpIValueReference->setDirectDependencies(NoDependencies);\n mpIValueReference->clearRefresh();\n }\n\n break;\n\n case ODE:\n mpValueReference->addDirectDependency(this);\n\n listOfContainer.push_back(getObjectAncestor(\"Model\"));\n success &= mpExpression->compile(listOfContainer);\n mpRateReference->setDirectDependencies(mpExpression->getDirectDependencies());\n\n break;\n\n default:\n break;\n }\n\n return success;\n}\n\nvoid CModelEntity::calculate()\n{\n switch (mStatus)\n {\n case ASSIGNMENT:\n *mpValueData = mpExpression->calcValue();\n break;\n\n case ODE:\n mRate = mpExpression->calcValue();\n break;\n\n default:\n break;\n }\n}\n\nvoid CModelEntity::refreshInitialValue()\n{\n switch (mStatus)\n {\n case ASSIGNMENT:\n *mpIValue = mpInitialExpression->calcValue();\n break;\n\n default:\n break;\n }\n}\n\nbool CModelEntity::setExpression(const std::string & expression)\n{\n if (isFixed()) return false;\n\n if (mpExpression == NULL)\n mpExpression = new CExpression;\n\n if (mpModel)\n mpModel->setCompileFlag(true);\n\n if (!mpExpression->setInfix(expression)) return false;\n\n return compile();\n}\n\nstd::string CModelEntity::getExpression() const\n {\n if (isFixed() || mpExpression == NULL)\n return \"\";\n\n mpExpression->updateInfix();\n return mpExpression->getInfix();\n }\n\nCExpression* CModelEntity::getExpressionPtr()\n{\n return mpExpression;\n}\n\nconst CExpression* CModelEntity::getExpressionPtr() const\n {\n return mpExpression;\n }\n\nbool CModelEntity::setExpressionPtr(CExpression* pExpression)\n{\n if (isFixed()) return false;\n\n if (mpExpression)\n pdelete(mpExpression);\n\n mpExpression = pExpression;\n\n if (mpModel)\n mpModel->setCompileFlag(true);\n\n return compile();\n}\n\nCExpression* CModelEntity::getInitialExpressionPtr()\n{\n return mpInitialExpression;\n}\n\nconst CExpression* CModelEntity::getInitialExpressionPtr() const\n {\n return mpInitialExpression;\n }\n\nbool CModelEntity::setInitialExpressionPtr(CExpression* pExpression)\n{\n if (mStatus == ASSIGNMENT) return false;\n\n if (mpInitialExpression)\n pdelete(mpInitialExpression);\n\n mpInitialExpression = pExpression;\n\n return compile();\n}\n\nbool CModelEntity::setInitialExpression(const std::string & expression)\n{\n if (mStatus == ASSIGNMENT) return false;\n\n if (mpInitialExpression == NULL)\n mpInitialExpression = new CExpression;\n\n return mpInitialExpression->setInfix(expression);\n}\n\nstd::string CModelEntity::getInitialExpression() const\n {\n if (mStatus == ASSIGNMENT || mpInitialExpression == NULL)\n return \"\";\n\n return mpInitialExpression->getInfix();\n }\n\n\/**\n * Return rate of production of this entity\n *\/\nconst C_FLOAT64 & CModelEntity::getRate() const\n {\n return mRate;\n }\n\nCCopasiObject * CModelEntity::getInitialValueReference() const\n {return mpIValueReference;}\n\nCCopasiObject * CModelEntity::getValueReference() const\n {return mpValueReference;}\n\nCCopasiObject * CModelEntity::getRateReference() const\n {return mpRateReference;}\n\n\/\/***********\n\nvoid CModelEntity::setValue(const C_FLOAT64 & value)\n{\n if (mStatus == FIXED) return;\n\n *mpValueData = value;\n\n#ifdef COPASI_DEBUG\n \/\/if (mStatus == FIXED)\n \/\/std::cout << \"warning: set the transient concentration on a fixed entity\" << std::endl;\n#endif\n}\n\nvoid CModelEntity::setInitialValue(const C_FLOAT64 & initialValue)\n{\n *mpIValue = initialValue;\n}\n\nvoid CModelEntity::setRate(const C_FLOAT64 & rate)\n{\n mRate = rate;\n}\n\n\/\/ ******************\n\nvoid CModelEntity::setStatus(const CModelEntity::Status & status)\n{\n if (mStatus != status)\n {\n if (mpModel != NULL)\n mpModel->setCompileFlag(true);\n\n mStatus = status;\n this->setValuePtr(mpValueData);\n\n if (mpModel != NULL)\n mpModel->setCompileFlag(true);\n\n std::set< const CCopasiObject * > NoDependencies;\n\n setDirectDependencies(NoDependencies);\n clearRefresh();\n\n pdelete(mpInitialExpression);\n\n mpIValueReference->setDirectDependencies(NoDependencies);\n mpIValueReference->clearRefresh();\n\n mpValueReference->setDirectDependencies(NoDependencies);\n mpValueReference->clearRefresh();\n\n mpRateReference->setDirectDependencies(NoDependencies);\n mpRateReference->clearRefresh();\n\n switch (mStatus)\n {\n case ASSIGNMENT:\n if (mpExpression == NULL)\n mpExpression = new CExpression;\n\n mpValueReference->setDirectDependencies(mpExpression->getDirectDependencies());\n mpValueReference->setRefresh(this, &CModelEntity::calculate);\n\n mRate = std::numeric_limits<C_FLOAT64>::quiet_NaN();\n\n mUsed = true;\n mUsedOnce = false;\n break;\n\n case ODE:\n if (mpExpression == NULL)\n mpExpression = new CExpression;\n\n mpRateReference->setDirectDependencies(mpExpression->getDirectDependencies());\n mpRateReference->setRefresh(this, &CModelEntity::calculate);\n\n mUsed = true;\n mUsedOnce = false;\n break;\n\n case REACTIONS:\n pdelete(mpExpression);\n\n mUsed = true;\n mUsedOnce = false;\n break;\n\n case TIME:\n pdelete(mpExpression);\n\n mUsed = true;\n mUsedOnce = false;\n break;\n\n case FIXED:\n pdelete(mpExpression);\n\n mRate = 0.0;\n\n mUsed = false;\n mUsedOnce = false;\n break;\n }\n }\n}\n\nvoid * CModelEntity::getValuePointer() const\n{return const_cast<C_FLOAT64 *>(mpValueAccess);}\n\nvoid CModelEntity::initObjects()\n{\n C_FLOAT64 Dummy;\n\n mpValueReference =\n static_cast<CCopasiObjectReference<C_FLOAT64> *>(addObjectReference(\"Value\",\n Dummy,\n CCopasiObject::ValueDbl));\n mpIValueReference =\n static_cast<CCopasiObjectReference<C_FLOAT64> *>(addObjectReference(\"InitialValue\",\n Dummy,\n CCopasiObject::ValueDbl));\n\n mpRateReference =\n static_cast<CCopasiObjectReference<C_FLOAT64> *>(addObjectReference(\"Rate\", mRate, CCopasiObject::ValueDbl));\n\n addObjectReference(\"SBMLId\", mSBMLId, CCopasiObject::ValueString);\n\n mpModel = static_cast<CModel *>(getObjectAncestor(\"Model\"));\n\n if (mpModel)\n {\n mpModel->getStateTemplate().add(this);\n }\n else\n {\n \/\/ This creates the needed values.\n setInitialValuePtr(NULL);\n setValuePtr(NULL);\n }\n}\n\nvoid CModelEntity::setInitialValuePtr(C_FLOAT64 * pInitialValue)\n{\n mpIValue = pInitialValue;\n if (!mpIValue) mpIValue = new C_FLOAT64;\n mpIValueReference->setReference(*mpIValue);\n}\n\nvoid CModelEntity::setValuePtr(C_FLOAT64 * pValue)\n{\n mpValueData = pValue;\n if (!mpValueData) mpValueData = new C_FLOAT64;\n\n if (mStatus == FIXED)\n mpValueAccess = mpIValue;\n else\n mpValueAccess = mpValueData;\n\n mpValueReference->setReference(*mpValueAccess);\n}\n\nbool CModelEntity::setObjectParent(const CCopasiContainer * pParent)\n{\n CCopasiContainer::setObjectParent(pParent);\n CModel * pNewModel = static_cast<CModel *>(getObjectAncestor(\"Model\"));\n\n if (mpModel == pNewModel) return true;\n\n C_FLOAT64 InitialValue = *mpIValue;\n C_FLOAT64 Value = *mpValueData;\n\n if (mpModel)\n {\n mpModel->getStateTemplate().remove(this);\n }\n else\n {\n pdelete(mpIValue);\n pdelete(mpValueData);\n }\n\n if (pNewModel)\n {\n pNewModel->getStateTemplate().add(this);\n }\n else\n {\n mpValueData = new C_FLOAT64;\n mpIValue = new C_FLOAT64;\n }\n\n mpModel = pNewModel;\n *mpIValue = InitialValue;\n *mpValueData = Value;\n\n return true;\n}\n\nstd::set< const CCopasiObject * > CModelEntity::getDeletedObjects() const\n {\n std::set< const CCopasiObject * > Deleted;\n\n Deleted.insert(this);\n Deleted.insert(mpIValueReference);\n Deleted.insert(mpValueReference);\n Deleted.insert(mpRateReference);\n\n return Deleted;\n }\n\nvoid CModelEntity::setSBMLId(const std::string& id)\n{\n this->mSBMLId = id;\n}\n\nconst std::string& CModelEntity::getSBMLId() const\n {\n return this->mSBMLId;\n }\n\nvoid CModelEntity::setUsed(const bool & used)\n{mUsed = used;}\n\nconst bool & CModelEntity::isUsed() const\n {return mUsed;}\n\nvoid CModelEntity::setUsedOnce(const bool & usedOnce)\n{mUsedOnce = usedOnce;}\n\nconst bool & CModelEntity::isUsedOnce() const\n {return mUsedOnce;}\n\n\/\/********************************************************************+\n\nCModelValue::CModelValue(const std::string & name,\n const CCopasiContainer * pParent):\n CModelEntity(name, pParent, \"ModelValue\")\n{\n mKey = GlobalKeys.add(\"ModelValue\", this);\n initObjects();\n\n CONSTRUCTOR_TRACE;\n}\n\nCModelValue::CModelValue(const CModelValue & src,\n const CCopasiContainer * pParent):\n CModelEntity(src, pParent)\n{\n mKey = GlobalKeys.add(\"ModelValue\", this);\n initObjects();\n CONSTRUCTOR_TRACE;\n}\n\nCModelValue::~CModelValue()\n{\n GlobalKeys.remove(mKey);\n\n DESTRUCTOR_TRACE;\n}\n\nvoid CModelValue::initObjects()\n{}\n\nstd::ostream & operator<<(std::ostream &os, const CModelValue & d)\n{\n os << \" ++++CModelValue: \" << d.getObjectName() << std::endl;\n os << \" mValue \" << *d.mpValueAccess << \" mIValue \" << *d.mpIValue << std::endl;\n os << \" mRate \" << d.mRate << \" mStatus \" << d.getStatus() << std::endl;\n os << \" ----CModelValue \" << std::endl;\n\n return os;\n}\n<commit_msg>Fixed Bug 779. CModelEntity supports now initial expressions. This includes hdnling them in setStatus() and compile().<commit_after>\/\/ Begin CVS Header\n\/\/ $Source: \/Volumes\/Home\/Users\/shoops\/cvs\/copasi_dev\/copasi\/model\/CModelValue.cpp,v $\n\/\/ $Revision: 1.46 $\n\/\/ $Name: $\n\/\/ $Author: shoops $\n\/\/ $Date: 2007\/10\/09 19:07:23 $\n\/\/ End CVS Header\n\n\/\/ Copyright (C) 2007 by Pedro Mendes, Virginia Tech Intellectual\n\/\/ Properties, Inc. and EML Research, gGmbH.\n\/\/ All rights reserved.\n\n#include <iostream>\n#include <string>\n#include <vector>\n#include <limits>\n\n#include \"copasi.h\"\n\n#include \"CModel.h\"\n#include \"CModelValue.h\"\n\n#include \"CopasiDataModel\/CCopasiDataModel.h\"\n#include \"function\/CExpression.h\"\n#include \"report\/CCopasiObjectReference.h\"\n#include \"report\/CKeyFactory.h\"\n#include \"utilities\/utility.h\"\n\n\/\/static\nconst std::string CModelEntity::StatusName[] =\n {\n \"fixed\",\n \"assignment\",\n \"reactions\",\n \"ode\",\n \"time\",\n \"\"\n };\n\n\/\/static\nconst char * CModelEntity::XMLStatus[] =\n {\n \"fixed\",\n \"assignment\",\n \"reactions\",\n \"ode\",\n \"time\",\n NULL\n };\n\n\/\/ the \"variable\" keyword is used for compatibility reasons. It actually means \"this metab is part\n\/\/ of the reaction network, copasi needs to figure out if it is independent, dependent (moieties) or unused.\"\n\nCModelEntity::CModelEntity(const std::string & name,\n const CCopasiContainer * pParent,\n const std::string & type,\n const unsigned C_INT32 & flag):\n CCopasiContainer(name, pParent, type, (flag | CCopasiObject::Container | CCopasiObject::ValueDbl | CCopasiObject::ModelEntity)),\n mKey(\"\"),\n mpValueData(NULL),\n mpValueAccess(NULL),\n mpIValue(NULL),\n mRate(0.0),\n mpExpression(NULL),\n mpInitialExpression(NULL),\n mStatus(FIXED),\n mUsed(false),\n mUsedOnce(false),\n mpModel(NULL)\n{\n initObjects();\n\n *mpIValue = 1.0;\n *mpValueData = std::numeric_limits<C_FLOAT64>::quiet_NaN();\n\n CONSTRUCTOR_TRACE;\n}\n\nCModelEntity::CModelEntity(const CModelEntity & src,\n const CCopasiContainer * pParent):\n CCopasiContainer(src, pParent),\n mKey(\"\"),\n mpValueData(NULL),\n mpValueAccess(NULL),\n mpIValue(NULL),\n mRate(src.mRate),\n mpExpression(new CExpression(*src.mpExpression)),\n mpInitialExpression(new CExpression(*src.mpInitialExpression)),\n mStatus(FIXED),\n mUsed(false),\n mUsedOnce(false),\n mpModel(NULL)\n{\n initObjects();\n\n setStatus(src.mStatus);\n\n *mpValueData = *src.mpValueData;\n *mpIValue = *src.mpIValue;\n\n CONSTRUCTOR_TRACE;\n}\n\nCModelEntity::~CModelEntity()\n{\n if (mpModel)\n mpModel->getStateTemplate().remove(this);\n\n \/\/ After the above call we definitely own the data and\n \/\/ therfore must destroy them.\n\n pdelete(mpValueData);\n pdelete(mpIValue);\n pdelete(mpExpression);\n pdelete(mpInitialExpression);\n\n DESTRUCTOR_TRACE;\n}\n\nconst std::string & CModelEntity::getKey() const {return mKey;}\n\nconst C_FLOAT64 & CModelEntity::getValue() const {return *mpValueAccess;}\n\nconst C_FLOAT64 & CModelEntity::getInitialValue() const\n {\n if (mpInitialExpression != NULL)\n const_cast< CModelEntity * >(this)->refreshInitialValue();\n\n return *mpIValue;\n }\n\nconst CModelEntity::Status & CModelEntity::getStatus() const {return mStatus;}\n\nbool CModelEntity::compile()\n{\n bool success = true;\n\n std::set< const CCopasiObject * > NoDependencies;\n std::vector< CCopasiContainer * > listOfContainer;\n listOfContainer.push_back(mpModel);\n\n switch (mStatus)\n {\n case ASSIGNMENT:\n success &= mpExpression->compile(listOfContainer);\n mpValueReference->setDirectDependencies(mpExpression->getDirectDependencies());\n\n pdelete(mpInitialExpression);\n mpInitialExpression = CExpression::createInitialExpression(*mpExpression);\n\n break;\n\n case ODE:\n mpValueReference->addDirectDependency(this);\n\n success &= mpExpression->compile(listOfContainer);\n mpRateReference->setDirectDependencies(mpExpression->getDirectDependencies());\n\n default:\n break;\n }\n\n \/\/ Here we handle initial expressions for all types.\n if (getInitialExpression() != \"\")\n {\n success &= mpInitialExpression->compile(listOfContainer);\n mpIValueReference->setDirectDependencies(mpInitialExpression->getDirectDependencies());\n mpIValueReference->setRefresh(this, &CModelEntity::refreshInitialValue);\n }\n else\n {\n mpIValueReference->setDirectDependencies(NoDependencies);\n mpIValueReference->clearRefresh();\n }\n\n return success;\n}\n\nvoid CModelEntity::calculate()\n{\n switch (mStatus)\n {\n case ASSIGNMENT:\n *mpValueData = mpExpression->calcValue();\n break;\n\n case ODE:\n mRate = mpExpression->calcValue();\n break;\n\n default:\n break;\n }\n}\n\nvoid CModelEntity::refreshInitialValue()\n{\n switch (mStatus)\n {\n case ASSIGNMENT:\n *mpIValue = mpInitialExpression->calcValue();\n break;\n\n default:\n break;\n }\n}\n\nbool CModelEntity::setExpression(const std::string & expression)\n{\n if (isFixed()) return false;\n\n if (mpExpression == NULL)\n mpExpression = new CExpression;\n\n if (mpModel)\n mpModel->setCompileFlag(true);\n\n if (!mpExpression->setInfix(expression)) return false;\n\n return compile();\n}\n\nstd::string CModelEntity::getExpression() const\n {\n if (isFixed() || mpExpression == NULL)\n return \"\";\n\n mpExpression->updateInfix();\n return mpExpression->getInfix();\n }\n\nCExpression* CModelEntity::getExpressionPtr()\n{\n return mpExpression;\n}\n\nconst CExpression* CModelEntity::getExpressionPtr() const\n {\n return mpExpression;\n }\n\nbool CModelEntity::setExpressionPtr(CExpression* pExpression)\n{\n if (isFixed()) return false;\n\n if (mpExpression)\n pdelete(mpExpression);\n\n mpExpression = pExpression;\n\n if (mpModel)\n mpModel->setCompileFlag(true);\n\n return compile();\n}\n\nCExpression* CModelEntity::getInitialExpressionPtr()\n{\n return mpInitialExpression;\n}\n\nconst CExpression* CModelEntity::getInitialExpressionPtr() const\n {\n return mpInitialExpression;\n }\n\nbool CModelEntity::setInitialExpressionPtr(CExpression* pExpression)\n{\n if (mStatus == ASSIGNMENT) return false;\n\n if (mpInitialExpression)\n pdelete(mpInitialExpression);\n\n mpInitialExpression = pExpression;\n\n return compile();\n}\n\nbool CModelEntity::setInitialExpression(const std::string & expression)\n{\n if (mStatus == ASSIGNMENT) return false;\n\n if (mpInitialExpression == NULL)\n mpInitialExpression = new CExpression;\n\n return mpInitialExpression->setInfix(expression);\n}\n\nstd::string CModelEntity::getInitialExpression() const\n {\n if (mStatus == ASSIGNMENT || mpInitialExpression == NULL)\n return \"\";\n\n mpInitialExpression->updateInfix();\n return mpInitialExpression->getInfix();\n }\n\n\/**\n * Return rate of production of this entity\n *\/\nconst C_FLOAT64 & CModelEntity::getRate() const\n {\n return mRate;\n }\n\nCCopasiObject * CModelEntity::getInitialValueReference() const\n {return mpIValueReference;}\n\nCCopasiObject * CModelEntity::getValueReference() const\n {return mpValueReference;}\n\nCCopasiObject * CModelEntity::getRateReference() const\n {return mpRateReference;}\n\n\/\/***********\n\nvoid CModelEntity::setValue(const C_FLOAT64 & value)\n{\n if (mStatus == FIXED) return;\n\n *mpValueData = value;\n\n#ifdef COPASI_DEBUG\n \/\/if (mStatus == FIXED)\n \/\/std::cout << \"warning: set the transient concentration on a fixed entity\" << std::endl;\n#endif\n}\n\nvoid CModelEntity::setInitialValue(const C_FLOAT64 & initialValue)\n{\n *mpIValue = initialValue;\n}\n\nvoid CModelEntity::setRate(const C_FLOAT64 & rate)\n{\n mRate = rate;\n}\n\n\/\/ ******************\n\nvoid CModelEntity::setStatus(const CModelEntity::Status & status)\n{\n if (mStatus != status)\n {\n if (mpModel != NULL)\n mpModel->setCompileFlag(true);\n\n mStatus = status;\n this->setValuePtr(mpValueData);\n\n if (mpModel != NULL)\n mpModel->setCompileFlag(true);\n\n std::set< const CCopasiObject * > NoDependencies;\n\n setDirectDependencies(NoDependencies);\n clearRefresh();\n\n mpIValueReference->setDirectDependencies(NoDependencies);\n mpIValueReference->clearRefresh();\n\n mpValueReference->setDirectDependencies(NoDependencies);\n mpValueReference->clearRefresh();\n\n mpRateReference->setDirectDependencies(NoDependencies);\n mpRateReference->clearRefresh();\n\n switch (mStatus)\n {\n case ASSIGNMENT:\n if (mpExpression == NULL)\n mpExpression = new CExpression;\n\n pdelete(mpInitialExpression);\n mpInitialExpression = CExpression::createInitialExpression(*mpExpression);\n\n mpValueReference->setDirectDependencies(mpExpression->getDirectDependencies());\n mpValueReference->setRefresh(this, &CModelEntity::calculate);\n\n mRate = std::numeric_limits<C_FLOAT64>::quiet_NaN();\n\n mUsed = true;\n mUsedOnce = false;\n break;\n\n case ODE:\n if (mpExpression == NULL)\n mpExpression = new CExpression;\n\n mpRateReference->setDirectDependencies(mpExpression->getDirectDependencies());\n mpRateReference->setRefresh(this, &CModelEntity::calculate);\n\n mUsed = true;\n mUsedOnce = false;\n break;\n\n case REACTIONS:\n pdelete(mpExpression);\n\n mUsed = true;\n mUsedOnce = false;\n break;\n\n case TIME:\n pdelete(mpExpression);\n\n mUsed = true;\n mUsedOnce = false;\n break;\n\n case FIXED:\n pdelete(mpExpression);\n\n mRate = 0.0;\n\n mUsed = false;\n mUsedOnce = false;\n break;\n }\n }\n}\n\nvoid * CModelEntity::getValuePointer() const\n{return const_cast<C_FLOAT64 *>(mpValueAccess);}\n\nvoid CModelEntity::initObjects()\n{\n C_FLOAT64 Dummy;\n\n mpValueReference =\n static_cast<CCopasiObjectReference<C_FLOAT64> *>(addObjectReference(\"Value\",\n Dummy,\n CCopasiObject::ValueDbl));\n mpIValueReference =\n static_cast<CCopasiObjectReference<C_FLOAT64> *>(addObjectReference(\"InitialValue\",\n Dummy,\n CCopasiObject::ValueDbl));\n\n mpRateReference =\n static_cast<CCopasiObjectReference<C_FLOAT64> *>(addObjectReference(\"Rate\", mRate, CCopasiObject::ValueDbl));\n\n addObjectReference(\"SBMLId\", mSBMLId, CCopasiObject::ValueString);\n\n mpModel = static_cast<CModel *>(getObjectAncestor(\"Model\"));\n\n if (mpModel)\n {\n mpModel->getStateTemplate().add(this);\n }\n else\n {\n \/\/ This creates the needed values.\n setInitialValuePtr(NULL);\n setValuePtr(NULL);\n }\n}\n\nvoid CModelEntity::setInitialValuePtr(C_FLOAT64 * pInitialValue)\n{\n mpIValue = pInitialValue;\n if (!mpIValue) mpIValue = new C_FLOAT64;\n mpIValueReference->setReference(*mpIValue);\n}\n\nvoid CModelEntity::setValuePtr(C_FLOAT64 * pValue)\n{\n mpValueData = pValue;\n if (!mpValueData) mpValueData = new C_FLOAT64;\n\n if (mStatus == FIXED)\n mpValueAccess = mpIValue;\n else\n mpValueAccess = mpValueData;\n\n mpValueReference->setReference(*mpValueAccess);\n}\n\nbool CModelEntity::setObjectParent(const CCopasiContainer * pParent)\n{\n CCopasiContainer::setObjectParent(pParent);\n CModel * pNewModel = static_cast<CModel *>(getObjectAncestor(\"Model\"));\n\n if (mpModel == pNewModel) return true;\n\n C_FLOAT64 InitialValue = *mpIValue;\n C_FLOAT64 Value = *mpValueData;\n\n if (mpModel)\n {\n mpModel->getStateTemplate().remove(this);\n }\n else\n {\n pdelete(mpIValue);\n pdelete(mpValueData);\n }\n\n if (pNewModel)\n {\n pNewModel->getStateTemplate().add(this);\n }\n else\n {\n mpValueData = new C_FLOAT64;\n mpIValue = new C_FLOAT64;\n }\n\n mpModel = pNewModel;\n *mpIValue = InitialValue;\n *mpValueData = Value;\n\n return true;\n}\n\nstd::set< const CCopasiObject * > CModelEntity::getDeletedObjects() const\n {\n std::set< const CCopasiObject * > Deleted;\n\n Deleted.insert(this);\n Deleted.insert(mpIValueReference);\n Deleted.insert(mpValueReference);\n Deleted.insert(mpRateReference);\n\n return Deleted;\n }\n\nvoid CModelEntity::setSBMLId(const std::string& id)\n{\n this->mSBMLId = id;\n}\n\nconst std::string& CModelEntity::getSBMLId() const\n {\n return this->mSBMLId;\n }\n\nvoid CModelEntity::setUsed(const bool & used)\n{mUsed = used;}\n\nconst bool & CModelEntity::isUsed() const\n {return mUsed;}\n\nvoid CModelEntity::setUsedOnce(const bool & usedOnce)\n{mUsedOnce = usedOnce;}\n\nconst bool & CModelEntity::isUsedOnce() const\n {return mUsedOnce;}\n\n\/\/********************************************************************+\n\nCModelValue::CModelValue(const std::string & name,\n const CCopasiContainer * pParent):\n CModelEntity(name, pParent, \"ModelValue\")\n{\n mKey = GlobalKeys.add(\"ModelValue\", this);\n initObjects();\n\n CONSTRUCTOR_TRACE;\n}\n\nCModelValue::CModelValue(const CModelValue & src,\n const CCopasiContainer * pParent):\n CModelEntity(src, pParent)\n{\n mKey = GlobalKeys.add(\"ModelValue\", this);\n initObjects();\n CONSTRUCTOR_TRACE;\n}\n\nCModelValue::~CModelValue()\n{\n GlobalKeys.remove(mKey);\n\n DESTRUCTOR_TRACE;\n}\n\nvoid CModelValue::initObjects()\n{}\n\nstd::ostream & operator<<(std::ostream &os, const CModelValue & d)\n{\n os << \" ++++CModelValue: \" << d.getObjectName() << std::endl;\n os << \" mValue \" << *d.mpValueAccess << \" mIValue \" << *d.mpIValue << std::endl;\n os << \" mRate \" << d.mRate << \" mStatus \" << d.getStatus() << std::endl;\n os << \" ----CModelValue \" << std::endl;\n\n return os;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ @(#)root\/cont:$Id$\n\/\/ Author: Rene Brun 28\/09\/2001\n\n\/*************************************************************************\n * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *\n * All rights reserved. *\n * *\n * For the licensing terms see $ROOTSYS\/LICENSE. *\n * For the list of contributors see $ROOTSYS\/README\/CREDITS. *\n *************************************************************************\/\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ TProcessID\n\/\/\n\/\/ A TProcessID identifies a ROOT job in a unique way in time and space.\n\/\/ The TProcessID title consists of a TUUID object which provides a globally\n\/\/ unique identifier (for more see TUUID.h).\n\/\/\n\/\/ A TProcessID is automatically created by the TROOT constructor.\n\/\/ When a TFile contains referenced objects (see TRef), the TProcessID\n\/\/ object is written to the file.\n\/\/ If a file has been written in multiple sessions (same machine or not),\n\/\/ a TProcessID is written for each session.\n\/\/ These objects are used by the class TRef to uniquely identified\n\/\/ any TObject pointed by a TRef.\n\/\/\n\/\/ When a referenced object is read from a file (its bit kIsReferenced is set),\n\/\/ this object is entered into the objects table of the corresponding TProcessID.\n\/\/ Each TFile has a list of TProcessIDs (see TFile::fProcessIDs) also\n\/\/ accessible via TProcessID::fgPIDs (for all files).\n\/\/ When this object is deleted, it is removed from the table via the cleanup\n\/\/ mechanism invoked by the TObject destructor.\n\/\/\n\/\/ Each TProcessID has a table (TObjArray *fObjects) that keeps track\n\/\/ of all referenced objects. If a referenced object has a fUniqueID set,\n\/\/ a pointer to this unique object may be found via fObjects->At(fUniqueID).\n\/\/ In the same way, when a TRef::GetObject is called, GetObject uses\n\/\/ its own fUniqueID to find the pointer to the referenced object.\n\/\/ See TProcessID::GetObjectWithID and PutObjectWithID.\n\/\/\n\/\/ When a referenced object is deleted, its slot in fObjects is set to null.\n\/\/\n\/\/ See also TProcessUUID: a specialized TProcessID to manage the single list\n\/\/ of TUUIDs.\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"TProcessID.h\"\n#include \"TROOT.h\"\n#include \"TObjArray.h\"\n#include \"TExMap.h\"\n#include \"TVirtualMutex.h\"\n\nTObjArray *TProcessID::fgPIDs = 0; \/\/pointer to the list of TProcessID\nTProcessID *TProcessID::fgPID = 0; \/\/pointer to the TProcessID of the current session\nUInt_t TProcessID::fgNumber = 0; \/\/Current referenced object instance count\nTExMap *TProcessID::fgObjPIDs= 0; \/\/Table (pointer,pids)\nClassImp(TProcessID)\n\n\/\/______________________________________________________________________________\nstatic inline ULong_t Void_Hash(const void *ptr)\n{\n \/\/ Return hash value for this object.\n\n return TString::Hash(&ptr, sizeof(void*));\n}\n\n\/\/______________________________________________________________________________\nTProcessID::TProcessID()\n{\n \/\/ Default constructor.\n\n fCount = 0;\n fObjects = 0;\n}\n\n\/\/______________________________________________________________________________\nTProcessID::~TProcessID()\n{\n \/\/ Destructor.\n\n delete fObjects;\n fObjects = 0;\n R__LOCKGUARD2(gROOTMutex);\n fgPIDs->Remove(this);\n}\n\n\/\/______________________________________________________________________________\nTProcessID *TProcessID::AddProcessID()\n{\n \/\/ Static function to add a new TProcessID to the list of PIDs.\n\n R__LOCKGUARD2(gROOTMutex);\n\n TProcessID *pid = new TProcessID();\n\n if (!fgPIDs) {\n fgPID = pid;\n fgPIDs = new TObjArray(10);\n gROOT->GetListOfCleanups()->Add(fgPIDs);\n }\n UShort_t apid = fgPIDs->GetEntriesFast();\n pid->IncrementCount();\n\n fgPIDs->Add(pid);\n char name[20];\n sprintf(name,\"ProcessID%d\",apid);\n pid->SetName(name);\n TUUID u;\n apid = fgPIDs->GetEntriesFast();\n pid->SetTitle(u.AsString());\n return pid;\n}\n\n\/\/______________________________________________________________________________\nUInt_t TProcessID::AssignID(TObject *obj)\n{\n \/\/ static function returning the ID assigned to obj\n \/\/ If the object is not yet referenced, its kIsReferenced bit is set\n \/\/ and its fUniqueID set to the current number of referenced objects so far.\n\n R__LOCKGUARD2(gROOTMutex);\n\n UInt_t uid = obj->GetUniqueID() & 0xffffff;\n if (obj == fgPID->GetObjectWithID(uid)) return uid;\n if (obj->TestBit(kIsReferenced)) {\n fgPID->PutObjectWithID(obj,uid);\n return uid;\n }\n fgNumber++;\n obj->SetBit(kIsReferenced);\n uid = fgNumber;\n obj->SetUniqueID(uid);\n fgPID->PutObjectWithID(obj,uid);\n return uid;\n}\n\n\/\/______________________________________________________________________________\nvoid TProcessID::CheckInit()\n{\n \/\/ Initialize fObjects.\n if (!fObjects) fObjects = new TObjArray(100);\n}\n\n\/\/______________________________________________________________________________\nvoid TProcessID::Cleanup()\n{\n \/\/ static function (called by TROOT destructor) to delete all TProcessIDs\n\n R__LOCKGUARD2(gROOTMutex);\n\n fgPIDs->Delete();\n gROOT->GetListOfCleanups()->Remove(fgPIDs);\n delete fgPIDs;\n}\n\n\/\/______________________________________________________________________________\nvoid TProcessID::Clear(Option_t *)\n{\n \/\/ delete the TObjArray pointing to referenced objects\n \/\/ this function is called by TFile::Close(\"R\")\n\n delete fObjects; fObjects = 0;\n}\n\n\/\/______________________________________________________________________________\nInt_t TProcessID::DecrementCount()\n{\n\n \/\/ the reference fCount is used to delete the TProcessID\n \/\/ in the TFile destructor when fCount = 0\n\n fCount--;\n if (fCount < 0) fCount = 0;\n return fCount;\n}\n\n\/\/______________________________________________________________________________\nTProcessID *TProcessID::GetProcessID(UShort_t pid)\n{\n \/\/ static function returning a pointer to TProcessID number pid in fgPIDs\n\n return (TProcessID*)fgPIDs->At(pid);\n}\n\n\/\/______________________________________________________________________________\nUInt_t TProcessID::GetNProcessIDs()\n{\n \/\/ Return the (static) number of process IDs.\n return fgPIDs ? fgPIDs->GetLast()+1 : 0;\n}\n\n\/\/______________________________________________________________________________\nTProcessID *TProcessID::GetProcessWithUID(UInt_t uid, const void *obj)\n{\n \/\/ static function returning a pointer to TProcessID with its pid\n \/\/ encoded in the highest byte of uid\n\n R__LOCKGUARD2(gROOTMutex);\n\n Int_t pid = (uid>>24)&0xff;\n if (pid==0xff) {\n \/\/ Look up the pid in the table (pointer,pid)\n if (fgObjPIDs==0) return 0;\n ULong_t hash = Void_Hash(obj);\n pid = fgObjPIDs->GetValue(hash,(Long_t)obj);\n }\n return (TProcessID*)fgPIDs->At(pid);\n}\n\n\/\/______________________________________________________________________________\nTProcessID *TProcessID::GetProcessWithUID(const TObject *obj)\n{\n \/\/ static function returning a pointer to TProcessID with its pid\n \/\/ encoded in the highest byte of obj->GetUniqueID()\n\n return GetProcessWithUID(obj->GetUniqueID(),obj);\n}\n\n\/\/______________________________________________________________________________\nTProcessID *TProcessID::GetSessionProcessID()\n{\n \/\/ static function returning the pointer to the session TProcessID\n\n return fgPID;\n}\n\n\/\/______________________________________________________________________________\nInt_t TProcessID::IncrementCount()\n{\n \/\/ Increase the reference count to this object.\n\n if (!fObjects) fObjects = new TObjArray(100);\n fCount++;\n return fCount;\n}\n\n\/\/______________________________________________________________________________\nUInt_t TProcessID::GetObjectCount()\n{\n \/\/ Return the current referenced object count\n \/\/ fgNumber is incremented everytime a new object is referenced\n\n return fgNumber;\n}\n\n\/\/______________________________________________________________________________\nTObject *TProcessID::GetObjectWithID(UInt_t uidd)\n{\n \/\/returns the TObject with unique identifier uid in the table of objects\n\n Int_t uid = uidd & 0xffffff; \/\/take only the 24 lower bits\n\n if (fObjects==0 || uid >= fObjects->GetSize()) return 0;\n return fObjects->UncheckedAt(uid);\n}\n\n\/\/______________________________________________________________________________\nTProcessID *TProcessID::GetPID()\n{\n \/\/static: returns pointer to current TProcessID\n \n return fgPID;\n}\n\n\/\/______________________________________________________________________________\nTObjArray *TProcessID::GetPIDs()\n{\n \/\/static: returns array of TProcessIDs\n \n return fgPIDs;\n}\n\n\n\/\/______________________________________________________________________________\nBool_t TProcessID::IsValid(TProcessID *pid)\n{\n \/\/ static function. return kTRUE if pid is a valid TProcessID\n\n R__LOCKGUARD2(gROOTMutex);\n\n if (fgPIDs->IndexOf(pid) >= 0) return kTRUE;\n if (pid == (TProcessID*)gROOT->GetUUIDs()) return kTRUE;\n return kFALSE;\n}\n\n\/\/______________________________________________________________________________\nvoid TProcessID::PutObjectWithID(TObject *obj, UInt_t uid)\n{\n \/\/stores the object at the uid th slot in the table of objects\n \/\/The object uniqueid is set as well as its kMustCleanup bit\n\n if (uid == 0) uid = obj->GetUniqueID() & 0xffffff;\n\n if (!fObjects) fObjects = new TObjArray(100);\n fObjects->AddAtAndExpand(obj,uid);\n\n obj->SetBit(kMustCleanup);\n if ( (obj->GetUniqueID()&0xff000000)==0xff000000 ) {\n \/\/ We have more than 255 pids we need to store this\n \/\/ pointer in the table(pointer,pid) since there is no\n \/\/ more space in fUniqueID\n if (fgObjPIDs==0) fgObjPIDs = new TExMap;\n ULong_t hash = Void_Hash(obj);\n\n \/\/ We use operator() rather than Add() because\n \/\/ if the address has already been registered, we want to\n \/\/ update it's uniqueID (this can easily happen when the\n \/\/ referenced obejct have been stored in a TClonesArray.\n (*fgObjPIDs)(hash, (Long_t)obj) = GetUniqueID();\n }\n}\n\n\/\/______________________________________________________________________________\nvoid TProcessID::RecursiveRemove(TObject *obj)\n{\n \/\/ called by the object destructor\n \/\/ remove reference to obj from the current table if it is referenced\n\n if (!fObjects) return;\n if (!obj->TestBit(kIsReferenced)) return;\n UInt_t uid = obj->GetUniqueID() & 0xffffff;\n if (obj == GetObjectWithID(uid)) fObjects->RemoveAt(uid);\n}\n\n\n\/\/______________________________________________________________________________\nvoid TProcessID::SetObjectCount(UInt_t number)\n{\n \/\/ static function to set the current referenced object count\n \/\/ fgNumber is incremented everytime a new object is referenced\n\n fgNumber = number;\n}\n<commit_msg>Fix typo in the documentation<commit_after>\/\/ @(#)root\/cont:$Id$\n\/\/ Author: Rene Brun 28\/09\/2001\n\n\/*************************************************************************\n * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *\n * All rights reserved. *\n * *\n * For the licensing terms see $ROOTSYS\/LICENSE. *\n * For the list of contributors see $ROOTSYS\/README\/CREDITS. *\n *************************************************************************\/\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ TProcessID\n\/\/\n\/\/ A TProcessID identifies a ROOT job in a unique way in time and space.\n\/\/ The TProcessID title consists of a TUUID object which provides a globally\n\/\/ unique identifier (for more see TUUID.h).\n\/\/\n\/\/ A TProcessID is automatically created by the TROOT constructor.\n\/\/ When a TFile contains referenced objects (see TRef), the TProcessID\n\/\/ object is written to the file.\n\/\/ If a file has been written in multiple sessions (same machine or not),\n\/\/ a TProcessID is written for each session.\n\/\/ These objects are used by the class TRef to uniquely identified\n\/\/ any TObject pointed by a TRef.\n\/\/\n\/\/ When a referenced object is read from a file (its bit kIsReferenced is set),\n\/\/ this object is entered into the objects table of the corresponding TProcessID.\n\/\/ Each TFile has a list of TProcessIDs (see TFile::fProcessIDs) also\n\/\/ accessible via TProcessID::fgPIDs (for all files).\n\/\/ When this object is deleted, it is removed from the table via the cleanup\n\/\/ mechanism invoked by the TObject destructor.\n\/\/\n\/\/ Each TProcessID has a table (TObjArray *fObjects) that keeps track\n\/\/ of all referenced objects. If a referenced object has a fUniqueID set,\n\/\/ a pointer to this unique object may be found via fObjects->At(fUniqueID).\n\/\/ In the same way, when a TRef::GetObject is called, GetObject uses\n\/\/ its own fUniqueID to find the pointer to the referenced object.\n\/\/ See TProcessID::GetObjectWithID and PutObjectWithID.\n\/\/\n\/\/ When a referenced object is deleted, its slot in fObjects is set to null.\n\/\/\n\/\/ See also TProcessUUID: a specialized TProcessID to manage the single list\n\/\/ of TUUIDs.\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"TProcessID.h\"\n#include \"TROOT.h\"\n#include \"TObjArray.h\"\n#include \"TExMap.h\"\n#include \"TVirtualMutex.h\"\n\nTObjArray *TProcessID::fgPIDs = 0; \/\/pointer to the list of TProcessID\nTProcessID *TProcessID::fgPID = 0; \/\/pointer to the TProcessID of the current session\nUInt_t TProcessID::fgNumber = 0; \/\/Current referenced object instance count\nTExMap *TProcessID::fgObjPIDs= 0; \/\/Table (pointer,pids)\nClassImp(TProcessID)\n\n\/\/______________________________________________________________________________\nstatic inline ULong_t Void_Hash(const void *ptr)\n{\n \/\/ Return hash value for this object.\n\n return TString::Hash(&ptr, sizeof(void*));\n}\n\n\/\/______________________________________________________________________________\nTProcessID::TProcessID()\n{\n \/\/ Default constructor.\n\n fCount = 0;\n fObjects = 0;\n}\n\n\/\/______________________________________________________________________________\nTProcessID::~TProcessID()\n{\n \/\/ Destructor.\n\n delete fObjects;\n fObjects = 0;\n R__LOCKGUARD2(gROOTMutex);\n fgPIDs->Remove(this);\n}\n\n\/\/______________________________________________________________________________\nTProcessID *TProcessID::AddProcessID()\n{\n \/\/ Static function to add a new TProcessID to the list of PIDs.\n\n R__LOCKGUARD2(gROOTMutex);\n\n TProcessID *pid = new TProcessID();\n\n if (!fgPIDs) {\n fgPID = pid;\n fgPIDs = new TObjArray(10);\n gROOT->GetListOfCleanups()->Add(fgPIDs);\n }\n UShort_t apid = fgPIDs->GetEntriesFast();\n pid->IncrementCount();\n\n fgPIDs->Add(pid);\n char name[20];\n sprintf(name,\"ProcessID%d\",apid);\n pid->SetName(name);\n TUUID u;\n apid = fgPIDs->GetEntriesFast();\n pid->SetTitle(u.AsString());\n return pid;\n}\n\n\/\/______________________________________________________________________________\nUInt_t TProcessID::AssignID(TObject *obj)\n{\n \/\/ static function returning the ID assigned to obj\n \/\/ If the object is not yet referenced, its kIsReferenced bit is set\n \/\/ and its fUniqueID set to the current number of referenced objects so far.\n\n R__LOCKGUARD2(gROOTMutex);\n\n UInt_t uid = obj->GetUniqueID() & 0xffffff;\n if (obj == fgPID->GetObjectWithID(uid)) return uid;\n if (obj->TestBit(kIsReferenced)) {\n fgPID->PutObjectWithID(obj,uid);\n return uid;\n }\n fgNumber++;\n obj->SetBit(kIsReferenced);\n uid = fgNumber;\n obj->SetUniqueID(uid);\n fgPID->PutObjectWithID(obj,uid);\n return uid;\n}\n\n\/\/______________________________________________________________________________\nvoid TProcessID::CheckInit()\n{\n \/\/ Initialize fObjects.\n if (!fObjects) fObjects = new TObjArray(100);\n}\n\n\/\/______________________________________________________________________________\nvoid TProcessID::Cleanup()\n{\n \/\/ static function (called by TROOT destructor) to delete all TProcessIDs\n\n R__LOCKGUARD2(gROOTMutex);\n\n fgPIDs->Delete();\n gROOT->GetListOfCleanups()->Remove(fgPIDs);\n delete fgPIDs;\n}\n\n\/\/______________________________________________________________________________\nvoid TProcessID::Clear(Option_t *)\n{\n \/\/ delete the TObjArray pointing to referenced objects\n \/\/ this function is called by TFile::Close(\"R\")\n\n delete fObjects; fObjects = 0;\n}\n\n\/\/______________________________________________________________________________\nInt_t TProcessID::DecrementCount()\n{\n\n \/\/ the reference fCount is used to delete the TProcessID\n \/\/ in the TFile destructor when fCount = 0\n\n fCount--;\n if (fCount < 0) fCount = 0;\n return fCount;\n}\n\n\/\/______________________________________________________________________________\nTProcessID *TProcessID::GetProcessID(UShort_t pid)\n{\n \/\/ static function returning a pointer to TProcessID number pid in fgPIDs\n\n return (TProcessID*)fgPIDs->At(pid);\n}\n\n\/\/______________________________________________________________________________\nUInt_t TProcessID::GetNProcessIDs()\n{\n \/\/ Return the (static) number of process IDs.\n return fgPIDs ? fgPIDs->GetLast()+1 : 0;\n}\n\n\/\/______________________________________________________________________________\nTProcessID *TProcessID::GetProcessWithUID(UInt_t uid, const void *obj)\n{\n \/\/ static function returning a pointer to TProcessID with its pid\n \/\/ encoded in the highest byte of uid\n\n R__LOCKGUARD2(gROOTMutex);\n\n Int_t pid = (uid>>24)&0xff;\n if (pid==0xff) {\n \/\/ Look up the pid in the table (pointer,pid)\n if (fgObjPIDs==0) return 0;\n ULong_t hash = Void_Hash(obj);\n pid = fgObjPIDs->GetValue(hash,(Long_t)obj);\n }\n return (TProcessID*)fgPIDs->At(pid);\n}\n\n\/\/______________________________________________________________________________\nTProcessID *TProcessID::GetProcessWithUID(const TObject *obj)\n{\n \/\/ static function returning a pointer to TProcessID with its pid\n \/\/ encoded in the highest byte of obj->GetUniqueID()\n\n return GetProcessWithUID(obj->GetUniqueID(),obj);\n}\n\n\/\/______________________________________________________________________________\nTProcessID *TProcessID::GetSessionProcessID()\n{\n \/\/ static function returning the pointer to the session TProcessID\n\n return fgPID;\n}\n\n\/\/______________________________________________________________________________\nInt_t TProcessID::IncrementCount()\n{\n \/\/ Increase the reference count to this object.\n\n if (!fObjects) fObjects = new TObjArray(100);\n fCount++;\n return fCount;\n}\n\n\/\/______________________________________________________________________________\nUInt_t TProcessID::GetObjectCount()\n{\n \/\/ Return the current referenced object count\n \/\/ fgNumber is incremented everytime a new object is referenced\n\n return fgNumber;\n}\n\n\/\/______________________________________________________________________________\nTObject *TProcessID::GetObjectWithID(UInt_t uidd)\n{\n \/\/returns the TObject with unique identifier uid in the table of objects\n\n Int_t uid = uidd & 0xffffff; \/\/take only the 24 lower bits\n\n if (fObjects==0 || uid >= fObjects->GetSize()) return 0;\n return fObjects->UncheckedAt(uid);\n}\n\n\/\/______________________________________________________________________________\nTProcessID *TProcessID::GetPID()\n{\n \/\/static: returns pointer to current TProcessID\n \n return fgPID;\n}\n\n\/\/______________________________________________________________________________\nTObjArray *TProcessID::GetPIDs()\n{\n \/\/static: returns array of TProcessIDs\n \n return fgPIDs;\n}\n\n\n\/\/______________________________________________________________________________\nBool_t TProcessID::IsValid(TProcessID *pid)\n{\n \/\/ static function. return kTRUE if pid is a valid TProcessID\n\n R__LOCKGUARD2(gROOTMutex);\n\n if (fgPIDs->IndexOf(pid) >= 0) return kTRUE;\n if (pid == (TProcessID*)gROOT->GetUUIDs()) return kTRUE;\n return kFALSE;\n}\n\n\/\/______________________________________________________________________________\nvoid TProcessID::PutObjectWithID(TObject *obj, UInt_t uid)\n{\n \/\/stores the object at the uid th slot in the table of objects\n \/\/The object uniqueid is set as well as its kMustCleanup bit\n\n if (uid == 0) uid = obj->GetUniqueID() & 0xffffff;\n\n if (!fObjects) fObjects = new TObjArray(100);\n fObjects->AddAtAndExpand(obj,uid);\n\n obj->SetBit(kMustCleanup);\n if ( (obj->GetUniqueID()&0xff000000)==0xff000000 ) {\n \/\/ We have more than 255 pids we need to store this\n \/\/ pointer in the table(pointer,pid) since there is no\n \/\/ more space in fUniqueID\n if (fgObjPIDs==0) fgObjPIDs = new TExMap;\n ULong_t hash = Void_Hash(obj);\n\n \/\/ We use operator() rather than Add() because\n \/\/ if the address has already been registered, we want to\n \/\/ update it's uniqueID (this can easily happen when the\n \/\/ referenced object have been stored in a TClonesArray.\n (*fgObjPIDs)(hash, (Long_t)obj) = GetUniqueID();\n }\n}\n\n\/\/______________________________________________________________________________\nvoid TProcessID::RecursiveRemove(TObject *obj)\n{\n \/\/ called by the object destructor\n \/\/ remove reference to obj from the current table if it is referenced\n\n if (!fObjects) return;\n if (!obj->TestBit(kIsReferenced)) return;\n UInt_t uid = obj->GetUniqueID() & 0xffffff;\n if (obj == GetObjectWithID(uid)) fObjects->RemoveAt(uid);\n}\n\n\n\/\/______________________________________________________________________________\nvoid TProcessID::SetObjectCount(UInt_t number)\n{\n \/\/ static function to set the current referenced object count\n \/\/ fgNumber is incremented everytime a new object is referenced\n\n fgNumber = number;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ @(#)root\/base:$Id$\n\/\/ Author: Fons Rademakers 11\/10\/95\n\n\/*************************************************************************\n * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *\n * All rights reserved. *\n * *\n * For the licensing terms see $ROOTSYS\/LICENSE. *\n * For the list of contributors see $ROOTSYS\/README\/CREDITS. *\n *************************************************************************\/\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ \/\/\n\/\/ TStopwatch \/\/\n\/\/ \/\/\n\/\/ Stopwatch class. This class returns the real and cpu time between \/\/\n\/\/ the start and stop events. \/\/\n\/\/ \/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"TStopwatch.h\"\n#include \"TTimeStamp.h\"\n#include \"TString.h\"\n\n#if defined(R__UNIX)\n# include <sys\/times.h>\n# include <unistd.h>\nstatic Double_t gTicks = 0;\n#elif defined(WIN32)\n# include \"TError.h\"\nconst Double_t gTicks = 1.0e-7;\n# include \"Windows4Root.h\"\n#endif\n\n\nClassImp(TStopwatch)\n\n\/\/______________________________________________________________________________\nTStopwatch::TStopwatch()\n{\n \/\/ Create a stopwatch and start it.\n\n#ifdef R__UNIX\n if (gTicks <= 0.0)\n gTicks = (Double_t)sysconf(_SC_CLK_TCK);\n#endif\n\n fStopRealTime = 0;\n fStopCpuTime = 0;\n\n Start();\n}\n\n\/\/______________________________________________________________________________\nvoid TStopwatch::Start(Bool_t reset)\n{\n \/\/ Start the stopwatch. If reset is kTRUE reset the stopwatch before\n \/\/ starting it (including the stopwatch counter).\n \/\/ Use kFALSE to continue timing after a Stop() without\n \/\/ resetting the stopwatch.\n\n if (reset) {\n fState = kUndefined;\n fTotalCpuTime = 0;\n fTotalRealTime = 0;\n fCounter = 0;\n }\n if (fState != kRunning) {\n fStartRealTime = GetRealTime();\n fStartCpuTime = GetCPUTime();\n }\n fState = kRunning;\n fCounter++;\n}\n\n\/\/______________________________________________________________________________\nvoid TStopwatch::Stop()\n{\n \/\/ Stop the stopwatch.\n\n fStopRealTime = GetRealTime();\n fStopCpuTime = GetCPUTime();\n\n if (fState == kRunning) {\n fTotalCpuTime += fStopCpuTime - fStartCpuTime;\n fTotalRealTime += fStopRealTime - fStartRealTime;\n }\n fState = kStopped;\n}\n\n\/\/______________________________________________________________________________\nvoid TStopwatch::Continue()\n{\n \/\/ Resume a stopped stopwatch. The stopwatch continues counting from the last\n \/\/ Start() onwards (this is like the laptimer function).\n\n if (fState == kUndefined)\n Error(\"Continue\", \"stopwatch not started\");\n\n if (fState == kStopped) {\n fTotalCpuTime -= fStopCpuTime - fStartCpuTime;\n fTotalRealTime -= fStopRealTime - fStartRealTime;\n }\n\n fState = kRunning;\n}\n\n\/\/______________________________________________________________________________\nDouble_t TStopwatch::RealTime()\n{\n \/\/ Return the realtime passed between the start and stop events. If the\n \/\/ stopwatch was still running stop it first.\n\n if (fState == kUndefined)\n Error(\"RealTime\", \"stopwatch not started\");\n\n if (fState == kRunning)\n Stop();\n\n return fTotalRealTime;\n}\n\n\/\/______________________________________________________________________________\nDouble_t TStopwatch::CpuTime()\n{\n \/\/ Return the cputime passed between the start and stop events. If the\n \/\/ stopwatch was still running stop it first.\n\n if (fState == kUndefined)\n Error(\"CpuTime\", \"stopwatch not started\");\n\n if (fState == kRunning)\n Stop();\n\n return fTotalCpuTime;\n}\n\n\/\/______________________________________________________________________________\nDouble_t TStopwatch::GetRealTime()\n{\n \/\/ Private static method returning system realtime.\n\n#if defined(R__UNIX)\n return TTimeStamp();\n#elif defined(WIN32)\n union {\n FILETIME ftFileTime;\n __int64 ftInt64;\n } ftRealTime; \/\/ time the process has spent in kernel mode\n SYSTEMTIME st;\n GetSystemTime(&st);\n SystemTimeToFileTime(&st,&ftRealTime.ftFileTime);\n return (Double_t)ftRealTime.ftInt64 * gTicks;\n#endif\n}\n\n\/\/______________________________________________________________________________\nDouble_t TStopwatch::GetCPUTime()\n{\n \/\/ Private static method returning system CPU time.\n\n#if defined(R__UNIX)\n struct tms cpt;\n times(&cpt);\n return (Double_t)(cpt.tms_utime+cpt.tms_stime) \/ gTicks;\n#elif defined(WIN32)\n\n OSVERSIONINFO OsVersionInfo;\n\n \/\/ Value Platform\n \/\/----------------------------------------------------\n \/\/ VER_PLATFORM_WIN32s Win32s on Windows 3.1\n \/\/ VER_PLATFORM_WIN32_WINDOWS Win32 on Windows 95\n \/\/ VER_PLATFORM_WIN32_NT Windows NT\n \/\/\n OsVersionInfo.dwOSVersionInfoSize=sizeof(OSVERSIONINFO);\n GetVersionEx(&OsVersionInfo);\n if (OsVersionInfo.dwPlatformId == VER_PLATFORM_WIN32_NT) {\n DWORD ret;\n FILETIME ftCreate, \/\/ when the process was created\n ftExit; \/\/ when the process exited\n\n union {\n FILETIME ftFileTime;\n __int64 ftInt64;\n } ftKernel; \/\/ time the process has spent in kernel mode\n\n union {\n FILETIME ftFileTime;\n __int64 ftInt64;\n } ftUser; \/\/ time the process has spent in user mode\n\n HANDLE hThread = GetCurrentThread();\n ret = GetThreadTimes (hThread, &ftCreate, &ftExit,\n &ftKernel.ftFileTime,\n &ftUser.ftFileTime);\n if (ret != TRUE) {\n ret = GetLastError ();\n ::Error (\"GetCPUTime\", \" Error on GetProcessTimes 0x%lx\", (int)ret);\n }\n\n \/\/ Process times are returned in a 64-bit structure, as the number of\n \/\/ 100 nanosecond ticks since 1 January 1601. User mode and kernel mode\n \/\/ times for this process are in separate 64-bit structures.\n \/\/ To convert to floating point seconds, we will:\n \/\/\n \/\/ Convert sum of high 32-bit quantities to 64-bit int\n\n return (Double_t) (ftKernel.ftInt64 + ftUser.ftInt64) * gTicks;\n } else\n return GetRealTime();\n#endif\n}\n\n\/\/______________________________________________________________________________\nvoid TStopwatch::Print(Option_t *opt) const\n{\n \/\/ Print the real and cpu time passed between the start and stop events.\n \/\/ and the number of times (slices) this TStopwatch was called\n \/\/ (if this number > 1). If opt=\"m\" print out realtime in milli second\n \/\/ precision. If opt=\"u\" print out realtime in micro second precision.\n\n Double_t realt = const_cast<TStopwatch*>(this)->RealTime();\n Double_t cput = const_cast<TStopwatch*>(this)->CpuTime();\n\n Int_t hours = Int_t(realt \/ 3600);\n realt -= hours * 3600;\n Int_t min = Int_t(realt \/ 60);\n realt -= min * 60;\n Int_t sec = Int_t(realt);\n\n if (realt < 0) realt = 0;\n if (cput < 0) cput = 0;\n\n if (opt && *opt == 'm') {\n if (Counter() > 1) {\n Printf(\"Real time %d:%02d:%06.3f, CP time %.3f, %d slices\", hours, min, realt, cput, Counter());\n } else {\n Printf(\"Real time %d:%02d:%06.3f, CP time %.3f\", hours, min, realt, cput);\n }\n } else if (opt && *opt == 'u') {\n if (Counter() > 1) {\n Printf(\"Real time %d:%02d:%09.6f, CP time %.3f, %d slices\", hours, min, realt, cput, Counter());\n } else {\n Printf(\"Real time %d:%02d:%09.6f, CP time %.3f\", hours, min, realt, cput);\n }\n } else {\n if (Counter() > 1) {\n Printf(\"Real time %d:%02d:%02d, CP time %.3f, %d slices\", hours, min, sec, cput, Counter());\n } else {\n Printf(\"Real time %d:%02d:%02d, CP time %.3f\", hours, min, sec, cput);\n }\n }\n}\n<commit_msg>From Thiemo Nagel: correction in doc.<commit_after>\/\/ @(#)root\/base:$Id$\n\/\/ Author: Fons Rademakers 11\/10\/95\n\n\/*************************************************************************\n * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *\n * All rights reserved. *\n * *\n * For the licensing terms see $ROOTSYS\/LICENSE. *\n * For the list of contributors see $ROOTSYS\/README\/CREDITS. *\n *************************************************************************\/\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ \/\/\n\/\/ TStopwatch \/\/\n\/\/ \/\/\n\/\/ Stopwatch class. This class returns the real and cpu time between \/\/\n\/\/ the start and stop events. \/\/\n\/\/ \/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"TStopwatch.h\"\n#include \"TTimeStamp.h\"\n#include \"TString.h\"\n\n#if defined(R__UNIX)\n# include <sys\/times.h>\n# include <unistd.h>\nstatic Double_t gTicks = 0;\n#elif defined(WIN32)\n# include \"TError.h\"\nconst Double_t gTicks = 1.0e-7;\n# include \"Windows4Root.h\"\n#endif\n\n\nClassImp(TStopwatch)\n\n\/\/______________________________________________________________________________\nTStopwatch::TStopwatch()\n{\n \/\/ Create a stopwatch and start it.\n\n#ifdef R__UNIX\n if (gTicks <= 0.0)\n gTicks = (Double_t)sysconf(_SC_CLK_TCK);\n#endif\n\n fStopRealTime = 0;\n fStopCpuTime = 0;\n\n Start();\n}\n\n\/\/______________________________________________________________________________\nvoid TStopwatch::Start(Bool_t reset)\n{\n \/\/ Start the stopwatch. If reset is kTRUE reset the stopwatch before\n \/\/ starting it (including the stopwatch counter).\n \/\/ Use kFALSE to continue timing after a Stop() without\n \/\/ resetting the stopwatch.\n\n if (reset) {\n fState = kUndefined;\n fTotalCpuTime = 0;\n fTotalRealTime = 0;\n fCounter = 0;\n }\n if (fState != kRunning) {\n fStartRealTime = GetRealTime();\n fStartCpuTime = GetCPUTime();\n }\n fState = kRunning;\n fCounter++;\n}\n\n\/\/______________________________________________________________________________\nvoid TStopwatch::Stop()\n{\n \/\/ Stop the stopwatch.\n\n fStopRealTime = GetRealTime();\n fStopCpuTime = GetCPUTime();\n\n if (fState == kRunning) {\n fTotalCpuTime += fStopCpuTime - fStartCpuTime;\n fTotalRealTime += fStopRealTime - fStartRealTime;\n }\n fState = kStopped;\n}\n\n\/\/______________________________________________________________________________\nvoid TStopwatch::Continue()\n{\n \/\/ Resume a stopped stopwatch. The stopwatch continues counting from the last\n \/\/ Start() onwards (this is like the laptimer function).\n\n if (fState == kUndefined)\n Error(\"Continue\", \"stopwatch not started\");\n\n if (fState == kStopped) {\n fTotalCpuTime -= fStopCpuTime - fStartCpuTime;\n fTotalRealTime -= fStopRealTime - fStartRealTime;\n }\n\n fState = kRunning;\n}\n\n\/\/______________________________________________________________________________\nDouble_t TStopwatch::RealTime()\n{\n \/\/ Stop the stopwatch (if it is running) and return the realtime (in\n \/\/ seconds) passed between the start and stop events.\n\n if (fState == kUndefined)\n Error(\"RealTime\", \"stopwatch not started\");\n\n if (fState == kRunning)\n Stop();\n\n return fTotalRealTime;\n}\n\n\/\/______________________________________________________________________________\nDouble_t TStopwatch::CpuTime()\n{\n \/\/ Stop the stopwatch (if it is running) and return the cputime (in\n \/\/ seconds) passed between the start and stop events.\n\n if (fState == kUndefined)\n Error(\"CpuTime\", \"stopwatch not started\");\n\n if (fState == kRunning)\n Stop();\n\n return fTotalCpuTime;\n}\n\n\/\/______________________________________________________________________________\nDouble_t TStopwatch::GetRealTime()\n{\n \/\/ Private static method returning system realtime.\n\n#if defined(R__UNIX)\n return TTimeStamp();\n#elif defined(WIN32)\n union {\n FILETIME ftFileTime;\n __int64 ftInt64;\n } ftRealTime; \/\/ time the process has spent in kernel mode\n SYSTEMTIME st;\n GetSystemTime(&st);\n SystemTimeToFileTime(&st,&ftRealTime.ftFileTime);\n return (Double_t)ftRealTime.ftInt64 * gTicks;\n#endif\n}\n\n\/\/______________________________________________________________________________\nDouble_t TStopwatch::GetCPUTime()\n{\n \/\/ Private static method returning system CPU time.\n\n#if defined(R__UNIX)\n struct tms cpt;\n times(&cpt);\n return (Double_t)(cpt.tms_utime+cpt.tms_stime) \/ gTicks;\n#elif defined(WIN32)\n\n OSVERSIONINFO OsVersionInfo;\n\n \/\/ Value Platform\n \/\/----------------------------------------------------\n \/\/ VER_PLATFORM_WIN32s Win32s on Windows 3.1\n \/\/ VER_PLATFORM_WIN32_WINDOWS Win32 on Windows 95\n \/\/ VER_PLATFORM_WIN32_NT Windows NT\n \/\/\n OsVersionInfo.dwOSVersionInfoSize=sizeof(OSVERSIONINFO);\n GetVersionEx(&OsVersionInfo);\n if (OsVersionInfo.dwPlatformId == VER_PLATFORM_WIN32_NT) {\n DWORD ret;\n FILETIME ftCreate, \/\/ when the process was created\n ftExit; \/\/ when the process exited\n\n union {\n FILETIME ftFileTime;\n __int64 ftInt64;\n } ftKernel; \/\/ time the process has spent in kernel mode\n\n union {\n FILETIME ftFileTime;\n __int64 ftInt64;\n } ftUser; \/\/ time the process has spent in user mode\n\n HANDLE hThread = GetCurrentThread();\n ret = GetThreadTimes (hThread, &ftCreate, &ftExit,\n &ftKernel.ftFileTime,\n &ftUser.ftFileTime);\n if (ret != TRUE) {\n ret = GetLastError ();\n ::Error (\"GetCPUTime\", \" Error on GetProcessTimes 0x%lx\", (int)ret);\n }\n\n \/\/ Process times are returned in a 64-bit structure, as the number of\n \/\/ 100 nanosecond ticks since 1 January 1601. User mode and kernel mode\n \/\/ times for this process are in separate 64-bit structures.\n \/\/ To convert to floating point seconds, we will:\n \/\/\n \/\/ Convert sum of high 32-bit quantities to 64-bit int\n\n return (Double_t) (ftKernel.ftInt64 + ftUser.ftInt64) * gTicks;\n } else\n return GetRealTime();\n#endif\n}\n\n\/\/______________________________________________________________________________\nvoid TStopwatch::Print(Option_t *opt) const\n{\n \/\/ Print the real and cpu time passed between the start and stop events.\n \/\/ and the number of times (slices) this TStopwatch was called\n \/\/ (if this number > 1). If opt=\"m\" print out realtime in milli second\n \/\/ precision. If opt=\"u\" print out realtime in micro second precision.\n\n Double_t realt = const_cast<TStopwatch*>(this)->RealTime();\n Double_t cput = const_cast<TStopwatch*>(this)->CpuTime();\n\n Int_t hours = Int_t(realt \/ 3600);\n realt -= hours * 3600;\n Int_t min = Int_t(realt \/ 60);\n realt -= min * 60;\n Int_t sec = Int_t(realt);\n\n if (realt < 0) realt = 0;\n if (cput < 0) cput = 0;\n\n if (opt && *opt == 'm') {\n if (Counter() > 1) {\n Printf(\"Real time %d:%02d:%06.3f, CP time %.3f, %d slices\", hours, min, realt, cput, Counter());\n } else {\n Printf(\"Real time %d:%02d:%06.3f, CP time %.3f\", hours, min, realt, cput);\n }\n } else if (opt && *opt == 'u') {\n if (Counter() > 1) {\n Printf(\"Real time %d:%02d:%09.6f, CP time %.3f, %d slices\", hours, min, realt, cput, Counter());\n } else {\n Printf(\"Real time %d:%02d:%09.6f, CP time %.3f\", hours, min, realt, cput);\n }\n } else {\n if (Counter() > 1) {\n Printf(\"Real time %d:%02d:%02d, CP time %.3f, %d slices\", hours, min, sec, cput, Counter());\n } else {\n Printf(\"Real time %d:%02d:%02d, CP time %.3f\", hours, min, sec, cput);\n }\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/\/ \\file TLogger.cxx\n\/\/\/ \\ingroup Base ROOT7\n\/\/\/ \\author Axel Naumann <axel@cern.ch>\n\/\/\/ \\date 2015-07-07\n\/\/\/ \\warning This is part of the ROOT 7 prototype! It will change without notice. It might trigger earthquakes. Feedback\n\/\/\/ is welcome!\n\n\/*************************************************************************\n * Copyright (C) 1995-2015, Rene Brun and Fons Rademakers. *\n * All rights reserved. *\n * *\n * For the licensing terms see $ROOTSYS\/LICENSE. *\n * For the list of contributors see $ROOTSYS\/README\/CREDITS. *\n *************************************************************************\/\n\n#include \"ROOT\/TLogger.hxx\"\n#include <iostream>\n\n\/\/ pin vtable\nROOT::Experimental::TLogHandler::~TLogHandler() {}\n\nnamespace {\nclass TLogHandlerDefault: public ROOT::Experimental::TLogHandler {\npublic:\n \/\/ Returns false if further emission of this log entry should be suppressed.\n bool Emit(const ROOT::Experimental::TLogEntry &entry) override;\n};\n\nbool TLogHandlerDefault::Emit(const ROOT::Experimental::TLogEntry &entry)\n{\n constexpr static std::array<const char *, 5> sTag{{\"Debug\", \"Info\", \"Warning\", \"Log\", \"FATAL\"}};\n std::cerr << \"ROOT \";\n if (!entry.fGroup.empty())\n std::cerr << '[' << entry.fGroup << \"] \";\n std::cerr << sTag[static_cast<int>(entry.fLevel)];\n\n if (!entry.fFile.empty())\n std::cerr << \" \" << entry.fFile << ':' << entry.fLine;\n if (!entry.fFuncName.empty())\n std::cerr << \" in \" << entry.fFuncName;\n std::cerr << \":\\n\"\n << \" \" << entry.str();\n return true;\n}\n} \/\/ unnamed namespace\n\nROOT::Experimental::TLogManager &ROOT::Experimental::TLogManager::Get()\n{\n static TLogManager instance(std::make_unique<TLogHandlerDefault>());\n return instance;\n}\n<commit_msg>Always add a trailing newline to the message.<commit_after>\/\/\/ \\file TLogger.cxx\n\/\/\/ \\ingroup Base ROOT7\n\/\/\/ \\author Axel Naumann <axel@cern.ch>\n\/\/\/ \\date 2015-07-07\n\/\/\/ \\warning This is part of the ROOT 7 prototype! It will change without notice. It might trigger earthquakes. Feedback\n\/\/\/ is welcome!\n\n\/*************************************************************************\n * Copyright (C) 1995-2015, Rene Brun and Fons Rademakers. *\n * All rights reserved. *\n * *\n * For the licensing terms see $ROOTSYS\/LICENSE. *\n * For the list of contributors see $ROOTSYS\/README\/CREDITS. *\n *************************************************************************\/\n\n#include \"ROOT\/TLogger.hxx\"\n#include <iostream>\n\n\/\/ pin vtable\nROOT::Experimental::TLogHandler::~TLogHandler() {}\n\nnamespace {\nclass TLogHandlerDefault: public ROOT::Experimental::TLogHandler {\npublic:\n \/\/ Returns false if further emission of this log entry should be suppressed.\n bool Emit(const ROOT::Experimental::TLogEntry &entry) override;\n};\n\nbool TLogHandlerDefault::Emit(const ROOT::Experimental::TLogEntry &entry)\n{\n constexpr static std::array<const char *, 5> sTag{{\"Debug\", \"Info\", \"Warning\", \"Log\", \"FATAL\"}};\n std::cerr << \"ROOT \";\n if (!entry.fGroup.empty())\n std::cerr << '[' << entry.fGroup << \"] \";\n std::cerr << sTag[static_cast<int>(entry.fLevel)];\n\n if (!entry.fFile.empty())\n std::cerr << \" \" << entry.fFile << ':' << entry.fLine;\n if (!entry.fFuncName.empty())\n std::cerr << \" in \" << entry.fFuncName;\n std::cerr << \":\\n\"\n << \" \" << entry.str() << '\\n';\n return true;\n}\n} \/\/ unnamed namespace\n\nROOT::Experimental::TLogManager &ROOT::Experimental::TLogManager::Get()\n{\n static TLogManager instance(std::make_unique<TLogHandlerDefault>());\n return instance;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 2013, Hernan Saez\n * All rights reserved.\n * \n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution.\n * * Neither the name of the <organization> nor the\n * names of its contributors may be used to endorse or promote products\n * derived from this software without specific prior written permission.\n * \n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY\n * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \"Node.hpp\"\n#include \"Group.hpp\"\n\n#include \"Boundings\/AABBBoundingVolume.hpp\"\n\nusing namespace crimild;\n\nNode::Node( std::string name )\n\t: NamedObject( name ),\n\t _worldIsCurrent( false ),\n\t _localBound( crimild::alloc< AABBBoundingVolume >( Vector3f( 0.0f, 0.0f, 0.0f ), 0.5f ) ),\n\t _worldBound( crimild::alloc< AABBBoundingVolume >( Vector3f( 0.0f, 0.0f, 0.0f ), 0.5f ) )\n{\n\n}\n\nNode::~Node( void )\n{\n\tdetachAllComponents();\n}\n\nNodePtr Node::getRootParent( void )\n{\n auto root = getParent();\n if ( root != nullptr ) {\n while ( root->hasParent() ) {\n root = root->getParent();\n }\n }\n \n return root;\n}\n\nNodePtr Node::detachFromParent( void )\n{\n auto node = getShared< Node >();\n \n GroupPtr parent = getParent< Group >();\n if ( parent != nullptr ) {\n parent->detachNode( node );\n }\n\n return node;\n}\n\nvoid Node::perform( NodeVisitor &visitor )\n{\n\tvisitor.traverse( getShared< Node >() );\n}\n\nvoid Node::perform( const NodeVisitor &visitor )\n{\n\tconst_cast< NodeVisitor & >( visitor ).traverse( getShared< Node >() );\n}\n\nvoid Node::accept( NodeVisitor &visitor )\n{\n\tvisitor.visitNode( getShared< Node >() );\n}\n\nvoid Node::attachComponent( NodeComponentPtr const &component )\n{\n\tif ( component->getNode() == this ) {\n\t\t\/\/ the component is already attached to this node\n\t\treturn;\n\t}\n\n\tdetachComponentWithName( component->getComponentName() );\n\tcomponent->setNode( this );\n\t_components[ component->getComponentName() ] = component;\n\tcomponent->onAttach();\n}\n\nvoid Node::detachComponent( NodeComponentPtr const &component )\n{\n\tif ( component->getNode() != this ) {\n\t\t\/\/ the component is not attached to this node\n\t\treturn;\n\t}\n\n\tdetachComponentWithName( component->getComponentName() );\n}\n\nvoid Node::detachComponentWithName( std::string name )\n{\n\tif ( _components.find( name ) != _components.end() ) {\n auto current = _components[ name ];\n if ( current != nullptr ) {\n current->onDetach();\n current->setNode( nullptr );\n }\n\n _components[ name ] = nullptr;\n\t\t_components.erase( name );\n\t}\n}\n\nNodeComponentPtr Node::getComponentWithName( std::string name )\n{\n\treturn _components[ name ];\n}\n\nvoid Node::detachAllComponents( void )\n{\n auto cs = _components;\n\tfor ( auto cmp : cs ) {\n\t\tif ( cmp.second != nullptr ) {\n\t\t\tcmp.second->onDetach();\n\t\t\tcmp.second->setNode( nullptr );\n\t\t}\n\t}\n\n\t_components.clear();\n}\n\nvoid Node::startComponents( void )\n{\n\tforeachComponent( [&]( NodeComponentPtr const &component ) {\n\t\tcomponent->start();\n\t});\n}\n\nvoid Node::updateComponents( const Time &t )\n{\n foreachComponent( [&]( NodeComponentPtr const &component ) {\n\t\tcomponent->update( t );\n\t});\n}\n\nvoid Node::foreachComponent( std::function< void ( NodeComponentPtr const & ) > callback )\n{\n\t\/\/ create a copy of the component's collection\n\t\/\/ to prevent errors when attaching or detaching\n\t\/\/ components during an update pass\n\tauto cs = _components;\n\tfor ( auto cmp : cs ) {\n\t\tif ( cmp.second != nullptr ) {\n\t\t\tcallback( cmp.second );\n\t\t}\n\t}\n}\n\n<commit_msg>Increased default bounding volume size<commit_after>\/*\n * Copyright (c) 2013, Hernan Saez\n * All rights reserved.\n * \n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution.\n * * Neither the name of the <organization> nor the\n * names of its contributors may be used to endorse or promote products\n * derived from this software without specific prior written permission.\n * \n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY\n * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \"Node.hpp\"\n#include \"Group.hpp\"\n\n#include \"Boundings\/AABBBoundingVolume.hpp\"\n\nusing namespace crimild;\n\nNode::Node( std::string name )\n\t: NamedObject( name ),\n\t _worldIsCurrent( false ),\n\t _localBound( crimild::alloc< AABBBoundingVolume >( Vector3f( 0.0f, 0.0f, 0.0f ), 1.0f ) ),\n\t _worldBound( crimild::alloc< AABBBoundingVolume >( Vector3f( 0.0f, 0.0f, 0.0f ), 1.0f ) )\n{\n\n}\n\nNode::~Node( void )\n{\n\tdetachAllComponents();\n}\n\nNodePtr Node::getRootParent( void )\n{\n auto root = getParent();\n if ( root != nullptr ) {\n while ( root->hasParent() ) {\n root = root->getParent();\n }\n }\n \n return root;\n}\n\nNodePtr Node::detachFromParent( void )\n{\n auto node = getShared< Node >();\n \n GroupPtr parent = getParent< Group >();\n if ( parent != nullptr ) {\n parent->detachNode( node );\n }\n\n return node;\n}\n\nvoid Node::perform( NodeVisitor &visitor )\n{\n\tvisitor.traverse( getShared< Node >() );\n}\n\nvoid Node::perform( const NodeVisitor &visitor )\n{\n\tconst_cast< NodeVisitor & >( visitor ).traverse( getShared< Node >() );\n}\n\nvoid Node::accept( NodeVisitor &visitor )\n{\n\tvisitor.visitNode( getShared< Node >() );\n}\n\nvoid Node::attachComponent( NodeComponentPtr const &component )\n{\n\tif ( component->getNode() == this ) {\n\t\t\/\/ the component is already attached to this node\n\t\treturn;\n\t}\n\n\tdetachComponentWithName( component->getComponentName() );\n\tcomponent->setNode( this );\n\t_components[ component->getComponentName() ] = component;\n\tcomponent->onAttach();\n}\n\nvoid Node::detachComponent( NodeComponentPtr const &component )\n{\n\tif ( component->getNode() != this ) {\n\t\t\/\/ the component is not attached to this node\n\t\treturn;\n\t}\n\n\tdetachComponentWithName( component->getComponentName() );\n}\n\nvoid Node::detachComponentWithName( std::string name )\n{\n\tif ( _components.find( name ) != _components.end() ) {\n auto current = _components[ name ];\n if ( current != nullptr ) {\n current->onDetach();\n current->setNode( nullptr );\n }\n\n _components[ name ] = nullptr;\n\t\t_components.erase( name );\n\t}\n}\n\nNodeComponentPtr Node::getComponentWithName( std::string name )\n{\n\treturn _components[ name ];\n}\n\nvoid Node::detachAllComponents( void )\n{\n auto cs = _components;\n\tfor ( auto cmp : cs ) {\n\t\tif ( cmp.second != nullptr ) {\n\t\t\tcmp.second->onDetach();\n\t\t\tcmp.second->setNode( nullptr );\n\t\t}\n\t}\n\n\t_components.clear();\n}\n\nvoid Node::startComponents( void )\n{\n\tforeachComponent( [&]( NodeComponentPtr const &component ) {\n\t\tcomponent->start();\n\t});\n}\n\nvoid Node::updateComponents( const Time &t )\n{\n foreachComponent( [&]( NodeComponentPtr const &component ) {\n\t\tcomponent->update( t );\n\t});\n}\n\nvoid Node::foreachComponent( std::function< void ( NodeComponentPtr const & ) > callback )\n{\n\t\/\/ create a copy of the component's collection\n\t\/\/ to prevent errors when attaching or detaching\n\t\/\/ components during an update pass\n\tauto cs = _components;\n\tfor ( auto cmp : cs ) {\n\t\tif ( cmp.second != nullptr ) {\n\t\t\tcallback( cmp.second );\n\t\t}\n\t}\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 2002-present, H. Hernan Saez\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution.\n * * Neither the name of the <organization> nor the\n * names of its contributors may be used to endorse or promote products\n * derived from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY\n * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#ifndef CRIMILD_SCENE_GRAPH_NODE_\n#define CRIMILD_SCENE_GRAPH_NODE_\n\n#include \"Boundings\/BoundingVolume.hpp\"\n#include \"Coding\/Codable.hpp\"\n#include \"Components\/NodeComponent.hpp\"\n#include \"Foundation\/NamedObject.hpp\"\n#include \"Foundation\/SharedObject.hpp\"\n#include \"Mathematics\/Transformation.hpp\"\n#include \"Mathematics\/Transformation_constants.hpp\"\n#include \"Visitors\/NodeVisitor.hpp\"\n\n#include <map>\n\nnamespace crimild {\n\n \/**\n\t\t\\brief Base class for any object that can be attached to the scene graph\n\t*\/\n class Node\n : public NamedObject,\n public coding::Codable {\n CRIMILD_IMPLEMENT_RTTI( crimild::Node )\n\n public:\n explicit Node( std::string name = \"\" );\n virtual ~Node( void );\n\n public:\n bool hasParent( void ) const { return _parent != nullptr; }\n\n Node *getParent( void ) { return _parent; }\n\n template< class NodeClass >\n NodeClass *getParent( void )\n {\n return static_cast< NodeClass * >( _parent );\n }\n\n void setParent( Node *parent ) { _parent = parent; }\n\n SharedPointer< Node > detachFromParent( void );\n\n Node *getRootParent( void );\n\n template< class NodeClass >\n NodeClass *getRootParent( void )\n {\n return static_cast< NodeClass * >( getRootParent() );\n }\n\n private:\n \/**\n\t\t\t\\brief A node's parent\n\n\t\t\tEvery node if linked with its parent in the node hierarchy (provided\n\t\t\tone is available).\n\t\t*\/\n Node *_parent = nullptr;\n\n public:\n void perform( NodeVisitor &visitor );\n void perform( const NodeVisitor &visitor );\n\n virtual void accept( NodeVisitor &visitor );\n\n public:\n NodeComponent *getComponentWithName( std::string name )\n {\n return crimild::get_ptr( _components[ name ] );\n }\n\n template< class NODE_COMPONENT_CLASS >\n NODE_COMPONENT_CLASS *getComponent( void )\n {\n return static_cast< NODE_COMPONENT_CLASS * >( getComponentWithName( NODE_COMPONENT_CLASS::__CLASS_NAME ) );\n }\n\n bool hasComponent( SharedPointer< NodeComponent > const &component )\n {\n return hasComponent( crimild::get_ptr( component ) );\n }\n\n bool hasComponent( NodeComponent *component )\n {\n auto it = _components.find( component->getComponentName() );\n return ( it != _components.end() && crimild::get_ptr( it->second ) == component );\n }\n\n void attachComponent( NodeComponent *component );\n void attachComponent( SharedPointer< NodeComponent > const &component );\n\n template< typename T, typename... Args >\n T *attachComponent( Args &&...args )\n {\n auto cmp = crimild::alloc< T >( std::forward< Args >( args )... );\n attachComponent( cmp );\n return crimild::get_ptr( cmp );\n }\n\n void detachComponent( NodeComponent *component );\n void detachComponent( SharedPointer< NodeComponent > const &component );\n\n SharedPointer< NodeComponent > detachComponentWithName( std::string name );\n\n void detachAllComponents( void );\n\n void startComponents( void );\n\n void updateComponents( const Clock &clock );\n\n void forEachComponent( std::function< void( NodeComponent * ) > callback );\n\n private:\n std::map< std::string, SharedPointer< NodeComponent > > _components;\n\n public:\n void setLocal( const Transformation &t ) { _local = t; }\n const Transformation &getLocal( void ) const { return _local; }\n Transformation &local( void ) { return _local; }\n\n void setWorld( const Transformation &t ) { _world = t; }\n const Transformation &getWorld( void ) const { return _world; }\n Transformation &world( void ) { return _world; }\n\n bool worldIsCurrent( void ) const { return _worldIsCurrent; }\n void setWorldIsCurrent( bool isCurrent ) { _worldIsCurrent = isCurrent; }\n\n private:\n Transformation _local = Transformation::Constants::IDENTITY;\n Transformation _world = Transformation::Constants::IDENTITY;\n\n \/**\n\t\t\t\\brief Indicates if the world transformation needs to be updated automatically\n\n\t\t\tThis flag can be used to avoid the automatic update of world transformations.\n\t\t\tBy default, the engine will compute the world transformation for a node as\n\t\t\ta function of its parent's one. If this flag is set to 'true' (default is 'false'),\n\t\t\tyou need to provide a valid world matrix manually\n\t\t*\/\n bool _worldIsCurrent;\n\n public:\n BoundingVolume *localBound( void ) { return crimild::get_ptr( _localBound ); }\n const BoundingVolume *getLocalBound( void ) const { return crimild::get_ptr( _localBound ); }\n void setLocalBound( BoundingVolume *bound ) { _localBound = crimild::retain( bound ); }\n void setLocalBound( SharedPointer< BoundingVolume > const &bound ) { _localBound = bound; }\n\n BoundingVolume *worldBound( void ) { return crimild::get_ptr( _worldBound ); }\n const BoundingVolume *getWorldBound( void ) const { return crimild::get_ptr( _worldBound ); }\n void setWorldBound( BoundingVolume *bound ) { _worldBound = crimild::retain( bound ); }\n void setWorldBound( SharedPointer< BoundingVolume > const &bound ) { _worldBound = bound; }\n\n private:\n SharedPointer< BoundingVolume > _localBound;\n SharedPointer< BoundingVolume > _worldBound;\n\n public:\n void setEnabled( bool enabled ) { _enabled = enabled; }\n bool isEnabled( void ) { return _enabled; }\n\n private:\n bool _enabled = true;\n\n \/**\n\t\t \\name Layers\n\t\t*\/\n \/\/@{\n\n public:\n \/**\n\t\t \\brief Node layers\n\n\t\t Layers are defined as integers so users can create their own in between\n\t\t the default ones.\n\t\t *\/\n struct Layer {\n enum {\n DEFAULT = 0,\n SKYBOX = 1 << 10,\n SCREEN = 1 << 12\n };\n\n using Impl = crimild::Int32;\n };\n\n inline Layer::Impl getLayer( void ) const { return _layer; }\n void setLayer( Layer::Impl value ) { _layer = value; }\n\n private:\n Layer::Impl _layer = Layer::DEFAULT;\n\n \/\/@}\n\n \/**\n\t\t \\name Cull flag\n\t\t *\/\n \/\/@{\n public:\n struct CullMode {\n enum {\n NEVER,\n DEFAULT,\n ALWAYS,\n };\n\n using Impl = crimild::Int32;\n };\n\n inline CullMode::Impl getCullMode( void ) const { return _cullMode; }\n void setCullMode( CullMode::Impl value ) { _cullMode = value; }\n\n private:\n CullMode::Impl _cullMode = CullMode::DEFAULT;\n\n \/\/@}\n\n \/**\n \\name Coding support\n *\/\n \/\/@{\n public:\n virtual void encode( coding::Encoder &encoder ) override;\n virtual void decode( coding::Decoder &decoder ) override;\n\n \/\/@}\n };\n\n}\n\n#endif\n<commit_msg>New perform function for Nodes<commit_after>\/*\n * Copyright (c) 2002-present, H. Hernan Saez\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution.\n * * Neither the name of the <organization> nor the\n * names of its contributors may be used to endorse or promote products\n * derived from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY\n * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#ifndef CRIMILD_SCENE_GRAPH_NODE_\n#define CRIMILD_SCENE_GRAPH_NODE_\n\n#include \"Boundings\/BoundingVolume.hpp\"\n#include \"Coding\/Codable.hpp\"\n#include \"Components\/NodeComponent.hpp\"\n#include \"Foundation\/NamedObject.hpp\"\n#include \"Foundation\/SharedObject.hpp\"\n#include \"Mathematics\/Transformation.hpp\"\n#include \"Mathematics\/Transformation_constants.hpp\"\n#include \"Visitors\/NodeVisitor.hpp\"\n\n#include <map>\n\nnamespace crimild {\n\n \/**\n\t\t\\brief Base class for any object that can be attached to the scene graph\n\t*\/\n class Node\n : public NamedObject,\n public coding::Codable {\n CRIMILD_IMPLEMENT_RTTI( crimild::Node )\n\n public:\n explicit Node( std::string name = \"\" );\n virtual ~Node( void );\n\n public:\n bool hasParent( void ) const { return _parent != nullptr; }\n\n Node *getParent( void ) { return _parent; }\n\n template< class NodeClass >\n NodeClass *getParent( void )\n {\n return static_cast< NodeClass * >( _parent );\n }\n\n void setParent( Node *parent ) { _parent = parent; }\n\n SharedPointer< Node > detachFromParent( void );\n\n Node *getRootParent( void );\n\n template< class NodeClass >\n NodeClass *getRootParent( void )\n {\n return static_cast< NodeClass * >( getRootParent() );\n }\n\n private:\n \/**\n\t\t\t\\brief A node's parent\n\n\t\t\tEvery node if linked with its parent in the node hierarchy (provided\n\t\t\tone is available).\n\t\t*\/\n Node *_parent = nullptr;\n\n public:\n void perform( NodeVisitor &visitor );\n void perform( const NodeVisitor &visitor );\n\n template< typename VisitorType, typename... Args >\n typename VisitorType::Result perform( Args &&...args ) noexcept\n {\n VisitorType visitor( std::forward< Args >( args )... );\n perform( visitor );\n return visitor.getResult();\n }\n\n virtual void accept( NodeVisitor &visitor );\n\n public:\n NodeComponent *getComponentWithName( std::string name )\n {\n return crimild::get_ptr( _components[ name ] );\n }\n\n template< class NODE_COMPONENT_CLASS >\n NODE_COMPONENT_CLASS *getComponent( void )\n {\n return static_cast< NODE_COMPONENT_CLASS * >( getComponentWithName( NODE_COMPONENT_CLASS::__CLASS_NAME ) );\n }\n\n bool hasComponent( SharedPointer< NodeComponent > const &component )\n {\n return hasComponent( crimild::get_ptr( component ) );\n }\n\n bool hasComponent( NodeComponent *component )\n {\n auto it = _components.find( component->getComponentName() );\n return ( it != _components.end() && crimild::get_ptr( it->second ) == component );\n }\n\n void attachComponent( NodeComponent *component );\n void attachComponent( SharedPointer< NodeComponent > const &component );\n\n template< typename T, typename... Args >\n T *attachComponent( Args &&...args )\n {\n auto cmp = crimild::alloc< T >( std::forward< Args >( args )... );\n attachComponent( cmp );\n return crimild::get_ptr( cmp );\n }\n\n void detachComponent( NodeComponent *component );\n void detachComponent( SharedPointer< NodeComponent > const &component );\n\n SharedPointer< NodeComponent > detachComponentWithName( std::string name );\n\n void detachAllComponents( void );\n\n void startComponents( void );\n\n void updateComponents( const Clock &clock );\n\n void forEachComponent( std::function< void( NodeComponent * ) > callback );\n\n private:\n std::map< std::string, SharedPointer< NodeComponent > > _components;\n\n public:\n void setLocal( const Transformation &t ) { _local = t; }\n const Transformation &getLocal( void ) const { return _local; }\n Transformation &local( void ) { return _local; }\n\n void setWorld( const Transformation &t ) { _world = t; }\n const Transformation &getWorld( void ) const { return _world; }\n Transformation &world( void ) { return _world; }\n\n bool worldIsCurrent( void ) const { return _worldIsCurrent; }\n void setWorldIsCurrent( bool isCurrent ) { _worldIsCurrent = isCurrent; }\n\n private:\n Transformation _local = Transformation::Constants::IDENTITY;\n Transformation _world = Transformation::Constants::IDENTITY;\n\n \/**\n\t\t\t\\brief Indicates if the world transformation needs to be updated automatically\n\n\t\t\tThis flag can be used to avoid the automatic update of world transformations.\n\t\t\tBy default, the engine will compute the world transformation for a node as\n\t\t\ta function of its parent's one. If this flag is set to 'true' (default is 'false'),\n\t\t\tyou need to provide a valid world matrix manually\n\t\t*\/\n bool _worldIsCurrent;\n\n public:\n BoundingVolume *localBound( void ) { return crimild::get_ptr( _localBound ); }\n const BoundingVolume *getLocalBound( void ) const { return crimild::get_ptr( _localBound ); }\n void setLocalBound( BoundingVolume *bound ) { _localBound = crimild::retain( bound ); }\n void setLocalBound( SharedPointer< BoundingVolume > const &bound ) { _localBound = bound; }\n\n BoundingVolume *worldBound( void ) { return crimild::get_ptr( _worldBound ); }\n const BoundingVolume *getWorldBound( void ) const { return crimild::get_ptr( _worldBound ); }\n void setWorldBound( BoundingVolume *bound ) { _worldBound = crimild::retain( bound ); }\n void setWorldBound( SharedPointer< BoundingVolume > const &bound ) { _worldBound = bound; }\n\n private:\n SharedPointer< BoundingVolume > _localBound;\n SharedPointer< BoundingVolume > _worldBound;\n\n public:\n void setEnabled( bool enabled ) { _enabled = enabled; }\n bool isEnabled( void ) { return _enabled; }\n\n private:\n bool _enabled = true;\n\n \/**\n\t\t \\name Layers\n\t\t*\/\n \/\/@{\n\n public:\n \/**\n\t\t \\brief Node layers\n\n\t\t Layers are defined as integers so users can create their own in between\n\t\t the default ones.\n\t\t *\/\n struct Layer {\n enum {\n DEFAULT = 0,\n SKYBOX = 1 << 10,\n SCREEN = 1 << 12\n };\n\n using Impl = crimild::Int32;\n };\n\n inline Layer::Impl getLayer( void ) const { return _layer; }\n void setLayer( Layer::Impl value ) { _layer = value; }\n\n private:\n Layer::Impl _layer = Layer::DEFAULT;\n\n \/\/@}\n\n \/**\n\t\t \\name Cull flag\n\t\t *\/\n \/\/@{\n public:\n struct CullMode {\n enum {\n NEVER,\n DEFAULT,\n ALWAYS,\n };\n\n using Impl = crimild::Int32;\n };\n\n inline CullMode::Impl getCullMode( void ) const { return _cullMode; }\n void setCullMode( CullMode::Impl value ) { _cullMode = value; }\n\n private:\n CullMode::Impl _cullMode = CullMode::DEFAULT;\n\n \/\/@}\n\n \/**\n \\name Coding support\n *\/\n \/\/@{\n public:\n virtual void encode( coding::Encoder &encoder ) override;\n virtual void decode( coding::Decoder &decoder ) override;\n\n \/\/@}\n };\n\n}\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2014 Kerem KAT \r\n\/\/ \r\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy of\r\n\/\/ this software and associated documentation files(the \"Software\"), to deal in\r\n\/\/ the Software without restriction, including without limitation the rights to\r\n\/\/ use, copy, modify, merge, publish, distribute, sublicense, and \/ or sell copies of\r\n\/\/ the Software, and to permit persons to whom the Software is furnished to do so,\r\n\/\/ subject to the following conditions :\r\n\/\/ \r\n\/\/ The above copyright notice and this permission notice shall be included in all\r\n\/\/ copies or substantial portions of the Software.\r\n\/\/ \r\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS\r\n\/\/ FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR\r\n\/\/ COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\r\n\/\/ IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\r\n\/\/ CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\r\n\/\/ \r\n\/\/ Do not hesisate to contact me about usage of the code or to make comments \r\n\/\/ about the code. Your feedback will be appreciated.\r\n\/\/\r\n\/\/ http:\/\/dissipatedheat.com\/\r\n\/\/ http:\/\/github.com\/krk\/\r\n\r\n#include <vector>\r\n#include <iostream>\r\n#include \"LPModel.h\"\r\n#include <boost\/range\/algorithm\/set_algorithm.hpp>\r\n#include <chrono>\r\n#include <boost\/program_options.hpp>\r\n\r\n#define TIMING\r\n\r\n#ifdef TIMING\r\n#define INIT_TIMER auto start = std::chrono::high_resolution_clock::now()\r\n#define START_TIMER start = std::chrono::high_resolution_clock::now()\r\n#define STOP_TIMER() ( \\\r\n\tstd::chrono::duration_cast<std::chrono::milliseconds>( \\\r\n\tstd::chrono::high_resolution_clock::now()-start \\\r\n\t).count())\r\n#define STOP_TIMER_SEC() (STOP_TIMER() \/ 60)\r\n#else\r\n#define INIT_TIMER\r\n#define START_TIMER\r\n#define STOP_TIMER() (0)\r\n#define STOP_TIMER_SEC() (0)\r\n#endif\r\n\r\nusing std::cout;\r\nusing std::endl;\r\nusing lpcompare::LPModel;\r\n\r\n\/**\r\n\\file lpcompare.cpp\r\nHandles command line arguments and has the main method.\r\n*\/\r\n\r\nnamespace po = boost::program_options;\r\n\r\ntemplate <typename T>\r\nvoid printCounts(std::string detail_name, std::vector<T> &vec, std::vector<T> &vecother);\r\n\r\ntemplate <>\r\nvoid printCounts(std::string detail_name, std::vector<lpcompare::Bound> &vec, std::vector<lpcompare::Bound> &vecother);\r\n\r\ntemplate <>\r\nvoid printCounts(std::string detail_name, std::vector<lpcompare::Constraint> &vec, std::vector<lpcompare::Constraint> &vecother);\r\n\r\ntemplate <typename T>\r\nvoid printCountsWithSort(std::string detail_name, std::vector<T> &vec, std::vector<T> &vecother);\r\n\r\nvoid printStats(LPModel *model);\r\n\r\ntemplate <typename T>\r\nvoid dumpdiff_if_requested(std::string detail_name, std::vector<T> &set1Except2, std::vector<T> &set2Except1);\r\n\r\nstd::string first_filename; \/**< Filename of the first LP model. *\/\r\nstd::string second_filename; \/**< Filename of the second LP model. *\/\r\n\r\npo::variables_map vm; \/**< Variable map for boost::program_options. *\/\r\n\r\n\/**\r\nParses program arguments using boost program_options.\r\n\r\n\\param argc argument count.\r\n\\param argv argument list.\r\n*\/\r\nvoid setup_options(int argc, char *argv []) {\r\n\r\n\tpo::positional_options_description p;\r\n\tp.add(\"first\", 1);\r\n\tp.add(\"second\", 1);\r\n\r\n\tpo::options_description desc(\"Usage\");\r\n\tdesc.add_options()\r\n\t\t(\"help\", \"show usage information\")\r\n\t\t(\"first\", po::value<std::string>(&first_filename)->required(), \"model 1 cplex lp file\")\r\n\t\t(\"second\", po::value<std::string>(&second_filename)->required(), \"model 2 cplex lp file\")\r\n\t\t(\"dump-prefix\", po::value<std::string>()->default_value(\"diffdump\"), \"filename prefix for difference dumps\")\r\n\t\t(\"dump-diffs\", po::value<bool>()->default_value(true), \"filename prefix for difference dumps\")\r\n\t\t;\r\n\r\n\ttry\r\n\t{\r\n\t\tpo::store(po::command_line_parser(argc, argv).\r\n\t\t\toptions(desc).positional(p).run(), vm);\r\n\r\n\t\tif (vm.count(\"help\")) {\r\n\t\t\tcout << desc << \"\\n\";\r\n\t\t\texit(1);\r\n\t\t}\r\n\r\n\t\tpo::notify(vm);\r\n\t}\r\n\tcatch (po::required_option& e)\r\n\t{\r\n\t\tstd::cerr << \"Error: \" << e.what() << std::endl << std::endl;\r\n\r\n\t\tcout << desc << \"\\n\";\r\n\t\texit(1);\r\n\t}\r\n}\r\n\r\n\/**\r\nCreates a filename to dump differences into.\r\n\r\n\\param model Model name.\r\n\\param detail Model detail.\r\n\\return dump filename.\r\n*\/\r\nstd::string get_dump_filename(std::string model, std::string detail) {\r\n\treturn vm[\"dump-prefix\"].as<std::string>() + \"-\" + model + \"-\" + detail + \".log\";\r\n}\r\n\r\n\/**\r\nChecks if diff dumps are requested.\r\n\r\n\\return true if diff dumps are requested.\r\n*\/\r\nbool is_diffdumps_requested() {\r\n\treturn vm[\"dump-diffs\"].as<bool>();\r\n}\r\n\r\nint main(int argc, char *argv [])\r\n{\r\n\tINIT_TIMER;\r\n\r\n\tcout << \"lpcompare: Compares two LP files created in cplex format and dumps differences to files.\" << endl;\r\n\r\n\tsetup_options(argc, argv);\r\n\r\n\tLPModel* model1 = new LPModel();\r\n\tLPModel* model2 = new LPModel();\r\n\r\n\tSTART_TIMER;\r\n\tcout << \"Reading first model: \" << first_filename << endl;\r\n\tif (!model1->ReadModel(first_filename)) {\r\n\t\texit(1);\r\n\t}\r\n\tcout << \" First model:\" << endl;\r\n\tprintStats(model1);\r\n\tauto first_model_read_sec = STOP_TIMER_SEC();\r\n\tcout << \" Model read in \" << first_model_read_sec << \" s\" << endl;\r\n\r\n\tSTART_TIMER;\r\n\tcout << \"Reading second model: \" << second_filename << endl;\r\n\tif (!model2->ReadModel(second_filename)) {\r\n\t\texit(1);\r\n\t}\r\n\tcout << \" Second Model:\" << endl;\r\n\tprintStats(model2);\r\n\tauto second_model_read_sec = STOP_TIMER_SEC();\r\n\tcout << \" Model read in \" << second_model_read_sec << \" s\" << endl;\r\n\r\n\tcout << endl;\r\n\r\n\tprintCounts(\"Generals\", model1->Generals, model2->Generals);\r\n\tprintCounts(\"Binaries\", model1->Binaries, model2->Binaries);\r\n\tprintCounts(\"SosVars\", model1->SosVars, model2->SosVars);\r\n\r\n\tSTART_TIMER;\r\n\tprintCounts(\"Bounds\", model1->Bounds, model2->Bounds);\r\n\tauto bounds_check_sec = STOP_TIMER_SEC();\r\n\tcout << \" Bounds check completed in \" << bounds_check_sec << \" s\" << endl;\r\n\r\n\tSTART_TIMER;\r\n\tprintCounts(\"Constraints\", model1->Constraints, model2->Constraints);\r\n\tauto cons_check_sec = STOP_TIMER_SEC();\r\n\tcout << \" Constraints check completed in \" << cons_check_sec << \" s\" << endl;\r\n\r\n\treturn 0;\r\n}\r\n\r\n\/**\r\nPrints statistics for a model.\r\n\r\n\\param model Model.\r\n*\/\r\nvoid printStats(LPModel *model) {\r\n\tcout << \"Binaries: \" << model->Binaries.size() << endl;\r\n\tcout << \"Bounds: \" << model->Bounds.size() << endl;\r\n\tcout << \"Constraints: \" << model->Constraints.size() << endl;\r\n\tcout << \"Generals: \" << model->Generals.size() << endl;\r\n\tcout << \"SosVars: \" << model->SosVars.size() << endl;\r\n}\r\n\r\n\/**\r\nDumps diffs to a file if dumping is requested.\r\n\r\n\\param set1Except2 List of elements that are in the first model but not in the second model.\r\n\\param set2Except1 List of elements that are in the second model but not in the first model.\r\n*\/\r\ntemplate <typename T>\r\nvoid dumpdiff_if_requested(std::string detail_name, std::vector<T> &set1Except2, std::vector<T> &set2Except1) {\r\n\r\n\tif (!is_diffdumps_requested())\r\n\t\treturn;\r\n\r\n\tif (set1Except2.size() > 0) {\r\n\r\n\t\tauto filename1e2 = get_dump_filename(\"firstEXCEPTsecond\", detail_name);\r\n\t\tstd::ofstream out_file_1(filename1e2);\r\n\r\n\t\tif (!out_file_1) {\r\n\t\t\tcout << \"Cannot open or create file for writing: \" << filename1e2;\r\n\t\t\treturn;\r\n\t\t}\r\n\r\n\t\tout_file_1 << \"firstEXCEPTsecond \" << detail_name << std::endl;\r\n\t\tfor (auto item : set1Except2) {\r\n\t\t\tout_file_1 << item << std::endl;\r\n\t\t}\r\n\r\n\t\tout_file_1.flush();\r\n\t\tout_file_1.close();\r\n\r\n\t\tcout << \"firstEXCEPTsecond diff written for \" << detail_name << \" to \" << filename1e2 << std::endl;\r\n\t}\r\n\r\n\tif (set2Except1.size() > 0) {\r\n\r\n\t\tauto filename2e1 = get_dump_filename(\"secondEXCEPTfirst\", detail_name);\r\n\t\tstd::ofstream out_file_2(filename2e1);\r\n\r\n\t\tif (!out_file_2) {\r\n\t\t\tcout << \"Cannot open or create file for writing: \" << filename2e1;\r\n\t\t\treturn;\r\n\t\t}\r\n\r\n\t\tout_file_2 << \"secondEXCEPTfirst \" << detail_name << std::endl;\r\n\t\tfor (auto item : set2Except1) {\r\n\t\t\tout_file_2 << item << std::endl;\r\n\t\t}\r\n\r\n\t\tout_file_2.flush();\r\n\t\tout_file_2.close();\r\n\r\n\t\tcout << \"secondEXCEPTfirst diff written for \" << detail_name << \" to \" << filename2e1 << std::endl;\r\n\t}\r\n}\r\n\r\n\/**\r\nPrints count of a given detail for both models, including differences.\r\n\r\n\\param detail_name Given name of the detail.\r\n\\param vec List of elements that are in the first model.\r\n\\param vecother List of elements that are in the second model.\r\n*\/\r\ntemplate <typename T>\r\nvoid printCounts(std::string detail_name, std::vector<T> &vec, std::vector<T> &vecother)\r\n{\r\n\tcout << detail_name << \" First Model: \" << vec.size() << endl;\r\n\tcout << detail_name << \" Second Model: \" << vecother.size() << endl;\r\n\r\n\tstd::vector<T> set1Except2;\r\n\tstd::set_difference(vec.begin(), vec.end(), vecother.begin(), vecother.end(), std::back_inserter(set1Except2));\r\n\r\n\tstd::vector<T> set2Except1;\r\n\tstd::set_difference(vecother.begin(), vecother.end(), vec.begin(), vec.end(), std::back_inserter(set2Except1));\r\n\r\n\tauto size1e2 = set1Except2.size();\r\n\tauto size2e1 = set1Except2.size();\r\n\r\n\tif (size1e2 == 0 && size2e1 == 0) {\r\n\t\tcout << detail_name << \" are equivalent.\" << endl;\r\n\t}\r\n\telse {\r\n\t\tcout << detail_name << \" First except Second: \" << set1Except2.size() << endl;\r\n\t\tcout << detail_name << \" Second except First: \" << set2Except1.size() << endl;\r\n\t}\r\n\r\n\tdumpdiff_if_requested(detail_name, set1Except2, set2Except1);\r\n}\r\n\r\n\/**\r\nPrints count of a given detail for both models, including differences.\r\nPerforms in-place sorting of vec and vecother.\r\n\\param detail_name Given name of the detail.\r\n\\param vec List of elements that are in the first model.\r\n\\param vecother List of elements that are in the second model.\r\n*\/\r\ntemplate <typename T>\r\nvoid printCountsWithSort(std::string name, std::vector<T> &vec, std::vector<T> &vecother)\r\n{\r\n\tcout << name << \" First Model: \" << vec.size() << endl;\r\n\tcout << name << \" Second Model: \" << vecother.size() << endl;\r\n\r\n\tstd::vector<T> set1Except2;\r\n\tstd::vector<T> set2Except1;\r\n\r\n\tstd::sort(vec.begin(), vec.end());\r\n\tstd::sort(vecother.begin(), vecother.end());\r\n\r\n\tauto it = vec.begin();\r\n\tauto ot = vecother.begin();\r\n\r\n\twhile (it != vec.end() && ot != vecother.end())\r\n\t{\r\n\t\tauto item = *it;\r\n\t\tauto other = *ot;\r\n\r\n\t\tif (item == other) {\r\n\t\t\t++it;\r\n\t\t\t++ot;\r\n\t\t}\r\n\t\telse if (item < other) {\r\n\t\t\tset1Except2.push_back(item);\r\n\t\t\t++it;\r\n\t\t}\r\n\t\telse {\r\n\t\t\tset2Except1.push_back(other);\r\n\t\t\t++ot;\r\n\t\t}\r\n\t}\r\n\r\n\twhile (it != vec.end())\r\n\t{\r\n\t\tset1Except2.push_back(*it);\r\n\t\t++it;\r\n\t}\r\n\r\n\twhile (ot != vecother.end())\r\n\t{\r\n\t\tset2Except1.push_back(*ot);\r\n\t\t++ot;\r\n\t}\r\n\r\n\tauto size1e2 = set1Except2.size();\r\n\tauto size2e1 = set2Except1.size();\r\n\r\n\tif (size1e2 == 0 && size2e1 == 0) {\r\n\t\tcout << name << \" are equivalent.\" << endl;\r\n\t}\r\n\telse {\r\n\t\tcout << name << \" First except Second: \" << set1Except2.size() << endl;\r\n\t\tcout << name << \" Second except First: \" << set2Except1.size() << endl;\r\n\t}\r\n\r\n\tdumpdiff_if_requested(name, set1Except2, set2Except1);\r\n}\r\n\r\n\/**\r\nprintCounts specialization for Constraints, which will be sorted before set operations.\r\n\r\n\\param detail_name Given name of the detail.\r\n\\param vec List of elements that are in the first model.\r\n\\param vecother List of elements that are in the second model.\r\n*\/\r\ntemplate <>\r\nvoid printCounts(std::string detail_name, std::vector<lpcompare::Constraint> &vec, std::vector<lpcompare::Constraint> &vecother)\r\n{\r\n\tprintCountsWithSort(detail_name, vec, vecother);\r\n}\r\n\r\n\/**\r\nprintCounts specialization for Bounds, which will be sorted before set operations.\r\n\r\n\\param detail_name Given name of the detail.\r\n\\param vec List of elements that are in the first model.\r\n\\param vecother List of elements that are in the second model.\r\n*\/\r\ntemplate <>\r\nvoid printCounts(std::string detail_name, std::vector<lpcompare::Bound> &vec, std::vector<lpcompare::Bound> &vecother)\r\n{\r\n\tprintCountsWithSort(detail_name, vec, vecother);\r\n}\r\n<commit_msg>Fix: set_difference requires sorted input.<commit_after>\/\/ Copyright (c) 2014 Kerem KAT \r\n\/\/ \r\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy of\r\n\/\/ this software and associated documentation files(the \"Software\"), to deal in\r\n\/\/ the Software without restriction, including without limitation the rights to\r\n\/\/ use, copy, modify, merge, publish, distribute, sublicense, and \/ or sell copies of\r\n\/\/ the Software, and to permit persons to whom the Software is furnished to do so,\r\n\/\/ subject to the following conditions :\r\n\/\/ \r\n\/\/ The above copyright notice and this permission notice shall be included in all\r\n\/\/ copies or substantial portions of the Software.\r\n\/\/ \r\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS\r\n\/\/ FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR\r\n\/\/ COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\r\n\/\/ IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\r\n\/\/ CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\r\n\/\/ \r\n\/\/ Do not hesisate to contact me about usage of the code or to make comments \r\n\/\/ about the code. Your feedback will be appreciated.\r\n\/\/\r\n\/\/ http:\/\/dissipatedheat.com\/\r\n\/\/ http:\/\/github.com\/krk\/\r\n\r\n#include <vector>\r\n#include <iostream>\r\n#include \"LPModel.h\"\r\n#include <boost\/range\/algorithm\/set_algorithm.hpp>\r\n#include <chrono>\r\n#include <boost\/program_options.hpp>\r\n\r\n#define TIMING\r\n\r\n#ifdef TIMING\r\n#define INIT_TIMER auto start = std::chrono::high_resolution_clock::now()\r\n#define START_TIMER start = std::chrono::high_resolution_clock::now()\r\n#define STOP_TIMER() ( \\\r\n\tstd::chrono::duration_cast<std::chrono::milliseconds>( \\\r\n\tstd::chrono::high_resolution_clock::now()-start \\\r\n\t).count())\r\n#define STOP_TIMER_SEC() (STOP_TIMER() \/ 60)\r\n#else\r\n#define INIT_TIMER\r\n#define START_TIMER\r\n#define STOP_TIMER() (0)\r\n#define STOP_TIMER_SEC() (0)\r\n#endif\r\n\r\nusing std::cout;\r\nusing std::endl;\r\nusing lpcompare::LPModel;\r\n\r\n\/**\r\n\\file lpcompare.cpp\r\nHandles command line arguments and has the main method.\r\n*\/\r\n\r\nnamespace po = boost::program_options;\r\n\r\ntemplate <typename T>\r\nvoid printCounts(std::string detail_name, std::vector<T> &vec, std::vector<T> &vecother);\r\n\r\ntemplate <>\r\nvoid printCounts(std::string detail_name, std::vector<lpcompare::Bound> &vec, std::vector<lpcompare::Bound> &vecother);\r\n\r\ntemplate <>\r\nvoid printCounts(std::string detail_name, std::vector<lpcompare::Constraint> &vec, std::vector<lpcompare::Constraint> &vecother);\r\n\r\ntemplate <typename T>\r\nvoid printCountsWithSort(std::string detail_name, std::vector<T> &vec, std::vector<T> &vecother);\r\n\r\nvoid printStats(LPModel *model);\r\n\r\ntemplate <typename T>\r\nvoid dumpdiff_if_requested(std::string detail_name, std::vector<T> &set1Except2, std::vector<T> &set2Except1);\r\n\r\nstd::string first_filename; \/**< Filename of the first LP model. *\/\r\nstd::string second_filename; \/**< Filename of the second LP model. *\/\r\n\r\npo::variables_map vm; \/**< Variable map for boost::program_options. *\/\r\n\r\n\/**\r\nParses program arguments using boost program_options.\r\n\r\n\\param argc argument count.\r\n\\param argv argument list.\r\n*\/\r\nvoid setup_options(int argc, char *argv []) {\r\n\r\n\tpo::positional_options_description p;\r\n\tp.add(\"first\", 1);\r\n\tp.add(\"second\", 1);\r\n\r\n\tpo::options_description desc(\"Usage\");\r\n\tdesc.add_options()\r\n\t\t(\"help\", \"show usage information\")\r\n\t\t(\"first\", po::value<std::string>(&first_filename)->required(), \"model 1 cplex lp file\")\r\n\t\t(\"second\", po::value<std::string>(&second_filename)->required(), \"model 2 cplex lp file\")\r\n\t\t(\"dump-prefix\", po::value<std::string>()->default_value(\"diffdump\"), \"filename prefix for difference dumps\")\r\n\t\t(\"dump-diffs\", po::value<bool>()->default_value(true), \"filename prefix for difference dumps\")\r\n\t\t;\r\n\r\n\ttry\r\n\t{\r\n\t\tpo::store(po::command_line_parser(argc, argv).\r\n\t\t\toptions(desc).positional(p).run(), vm);\r\n\r\n\t\tif (vm.count(\"help\")) {\r\n\t\t\tcout << desc << \"\\n\";\r\n\t\t\texit(1);\r\n\t\t}\r\n\r\n\t\tpo::notify(vm);\r\n\t}\r\n\tcatch (po::required_option& e)\r\n\t{\r\n\t\tstd::cerr << \"Error: \" << e.what() << std::endl << std::endl;\r\n\r\n\t\tcout << desc << \"\\n\";\r\n\t\texit(1);\r\n\t}\r\n}\r\n\r\n\/**\r\nCreates a filename to dump differences into.\r\n\r\n\\param model Model name.\r\n\\param detail Model detail.\r\n\\return dump filename.\r\n*\/\r\nstd::string get_dump_filename(std::string model, std::string detail) {\r\n\treturn vm[\"dump-prefix\"].as<std::string>() + \"-\" + model + \"-\" + detail + \".log\";\r\n}\r\n\r\n\/**\r\nChecks if diff dumps are requested.\r\n\r\n\\return true if diff dumps are requested.\r\n*\/\r\nbool is_diffdumps_requested() {\r\n\treturn vm[\"dump-diffs\"].as<bool>();\r\n}\r\n\r\nint main(int argc, char *argv [])\r\n{\r\n\tINIT_TIMER;\r\n\r\n\tcout << \"lpcompare: Compares two LP files created in cplex format and dumps differences to files.\" << endl;\r\n\r\n\tsetup_options(argc, argv);\r\n\r\n\tLPModel* model1 = new LPModel();\r\n\tLPModel* model2 = new LPModel();\r\n\r\n\tSTART_TIMER;\r\n\tcout << \"Reading first model: \" << first_filename << endl;\r\n\tif (!model1->ReadModel(first_filename)) {\r\n\t\texit(1);\r\n\t}\r\n\tcout << \" First model:\" << endl;\r\n\tprintStats(model1);\r\n\tauto first_model_read_sec = STOP_TIMER_SEC();\r\n\tcout << \" Model read in \" << first_model_read_sec << \" s\" << endl;\r\n\r\n\tSTART_TIMER;\r\n\tcout << \"Reading second model: \" << second_filename << endl;\r\n\tif (!model2->ReadModel(second_filename)) {\r\n\t\texit(1);\r\n\t}\r\n\tcout << \" Second Model:\" << endl;\r\n\tprintStats(model2);\r\n\tauto second_model_read_sec = STOP_TIMER_SEC();\r\n\tcout << \" Model read in \" << second_model_read_sec << \" s\" << endl;\r\n\r\n\tcout << endl;\r\n\r\n\tprintCounts(\"Generals\", model1->Generals, model2->Generals);\r\n\tprintCounts(\"Binaries\", model1->Binaries, model2->Binaries);\r\n\tprintCounts(\"SosVars\", model1->SosVars, model2->SosVars);\r\n\r\n\tSTART_TIMER;\r\n\tprintCounts(\"Bounds\", model1->Bounds, model2->Bounds);\r\n\tauto bounds_check_sec = STOP_TIMER_SEC();\r\n\tcout << \" Bounds check completed in \" << bounds_check_sec << \" s\" << endl;\r\n\r\n\tSTART_TIMER;\r\n\tprintCounts(\"Constraints\", model1->Constraints, model2->Constraints);\r\n\tauto cons_check_sec = STOP_TIMER_SEC();\r\n\tcout << \" Constraints check completed in \" << cons_check_sec << \" s\" << endl;\r\n\r\n\treturn 0;\r\n}\r\n\r\n\/**\r\nPrints statistics for a model.\r\n\r\n\\param model Model.\r\n*\/\r\nvoid printStats(LPModel *model) {\r\n\tcout << \"Binaries: \" << model->Binaries.size() << endl;\r\n\tcout << \"Bounds: \" << model->Bounds.size() << endl;\r\n\tcout << \"Constraints: \" << model->Constraints.size() << endl;\r\n\tcout << \"Generals: \" << model->Generals.size() << endl;\r\n\tcout << \"SosVars: \" << model->SosVars.size() << endl;\r\n}\r\n\r\n\/**\r\nDumps diffs to a file if dumping is requested.\r\n\r\n\\param set1Except2 List of elements that are in the first model but not in the second model.\r\n\\param set2Except1 List of elements that are in the second model but not in the first model.\r\n*\/\r\ntemplate <typename T>\r\nvoid dumpdiff_if_requested(std::string detail_name, std::vector<T> &set1Except2, std::vector<T> &set2Except1) {\r\n\r\n\tif (!is_diffdumps_requested())\r\n\t\treturn;\r\n\r\n\tif (set1Except2.size() > 0) {\r\n\r\n\t\tauto filename1e2 = get_dump_filename(\"firstEXCEPTsecond\", detail_name);\r\n\t\tstd::ofstream out_file_1(filename1e2);\r\n\r\n\t\tif (!out_file_1) {\r\n\t\t\tcout << \"Cannot open or create file for writing: \" << filename1e2;\r\n\t\t\treturn;\r\n\t\t}\r\n\r\n\t\tout_file_1 << \"firstEXCEPTsecond \" << detail_name << std::endl;\r\n\t\tfor (auto item : set1Except2) {\r\n\t\t\tout_file_1 << item << std::endl;\r\n\t\t}\r\n\r\n\t\tout_file_1.flush();\r\n\t\tout_file_1.close();\r\n\r\n\t\tcout << \"firstEXCEPTsecond diff written for \" << detail_name << \" to \" << filename1e2 << std::endl;\r\n\t}\r\n\r\n\tif (set2Except1.size() > 0) {\r\n\r\n\t\tauto filename2e1 = get_dump_filename(\"secondEXCEPTfirst\", detail_name);\r\n\t\tstd::ofstream out_file_2(filename2e1);\r\n\r\n\t\tif (!out_file_2) {\r\n\t\t\tcout << \"Cannot open or create file for writing: \" << filename2e1;\r\n\t\t\treturn;\r\n\t\t}\r\n\r\n\t\tout_file_2 << \"secondEXCEPTfirst \" << detail_name << std::endl;\r\n\t\tfor (auto item : set2Except1) {\r\n\t\t\tout_file_2 << item << std::endl;\r\n\t\t}\r\n\r\n\t\tout_file_2.flush();\r\n\t\tout_file_2.close();\r\n\r\n\t\tcout << \"secondEXCEPTfirst diff written for \" << detail_name << \" to \" << filename2e1 << std::endl;\r\n\t}\r\n}\r\n\r\n\/**\r\nPrints count of a given detail for both models, including differences.\r\n\r\n\\param detail_name Given name of the detail.\r\n\\param vec List of elements that are in the first model.\r\n\\param vecother List of elements that are in the second model.\r\n*\/\r\ntemplate <typename T>\r\nvoid printCounts(std::string detail_name, std::vector<T> &vec, std::vector<T> &vecother)\r\n{\r\n\tcout << detail_name << \" First Model: \" << vec.size() << endl;\r\n\tcout << detail_name << \" Second Model: \" << vecother.size() << endl;\r\n\r\n\tstd::sort(vec.begin(), vec.end());\r\n\tstd::sort(vecother.begin(), vecother.end());\r\n\r\n\tstd::vector<T> set1Except2;\r\n\tstd::set_difference(vec.begin(), vec.end(), vecother.begin(), vecother.end(), std::back_inserter(set1Except2));\r\n\r\n\tstd::vector<T> set2Except1;\r\n\tstd::set_difference(vecother.begin(), vecother.end(), vec.begin(), vec.end(), std::back_inserter(set2Except1));\r\n\r\n\tauto size1e2 = set1Except2.size();\r\n\tauto size2e1 = set1Except2.size();\r\n\r\n\tif (size1e2 == 0 && size2e1 == 0) {\r\n\t\tcout << detail_name << \" are equivalent.\" << endl;\r\n\t}\r\n\telse {\r\n\t\tcout << detail_name << \" First except Second: \" << set1Except2.size() << endl;\r\n\t\tcout << detail_name << \" Second except First: \" << set2Except1.size() << endl;\r\n\t}\r\n\r\n\tdumpdiff_if_requested(detail_name, set1Except2, set2Except1);\r\n}\r\n\r\n\/**\r\nPrints count of a given detail for both models, including differences.\r\nPerforms in-place sorting of vec and vecother.\r\n\\param detail_name Given name of the detail.\r\n\\param vec List of elements that are in the first model.\r\n\\param vecother List of elements that are in the second model.\r\n*\/\r\ntemplate <typename T>\r\nvoid printCountsWithSort(std::string name, std::vector<T> &vec, std::vector<T> &vecother)\r\n{\r\n\tcout << name << \" First Model: \" << vec.size() << endl;\r\n\tcout << name << \" Second Model: \" << vecother.size() << endl;\r\n\r\n\tstd::vector<T> set1Except2;\r\n\tstd::vector<T> set2Except1;\r\n\r\n\tstd::sort(vec.begin(), vec.end());\r\n\tstd::sort(vecother.begin(), vecother.end());\r\n\r\n\tauto it = vec.begin();\r\n\tauto ot = vecother.begin();\r\n\r\n\twhile (it != vec.end() && ot != vecother.end())\r\n\t{\r\n\t\tauto item = *it;\r\n\t\tauto other = *ot;\r\n\r\n\t\tif (item == other) {\r\n\t\t\t++it;\r\n\t\t\t++ot;\r\n\t\t}\r\n\t\telse if (item < other) {\r\n\t\t\tset1Except2.push_back(item);\r\n\t\t\t++it;\r\n\t\t}\r\n\t\telse {\r\n\t\t\tset2Except1.push_back(other);\r\n\t\t\t++ot;\r\n\t\t}\r\n\t}\r\n\r\n\twhile (it != vec.end())\r\n\t{\r\n\t\tset1Except2.push_back(*it);\r\n\t\t++it;\r\n\t}\r\n\r\n\twhile (ot != vecother.end())\r\n\t{\r\n\t\tset2Except1.push_back(*ot);\r\n\t\t++ot;\r\n\t}\r\n\r\n\tauto size1e2 = set1Except2.size();\r\n\tauto size2e1 = set2Except1.size();\r\n\r\n\tif (size1e2 == 0 && size2e1 == 0) {\r\n\t\tcout << name << \" are equivalent.\" << endl;\r\n\t}\r\n\telse {\r\n\t\tcout << name << \" First except Second: \" << set1Except2.size() << endl;\r\n\t\tcout << name << \" Second except First: \" << set2Except1.size() << endl;\r\n\t}\r\n\r\n\tdumpdiff_if_requested(name, set1Except2, set2Except1);\r\n}\r\n\r\n\/**\r\nprintCounts specialization for Constraints, which will be sorted before set operations.\r\n\r\n\\param detail_name Given name of the detail.\r\n\\param vec List of elements that are in the first model.\r\n\\param vecother List of elements that are in the second model.\r\n*\/\r\ntemplate <>\r\nvoid printCounts(std::string detail_name, std::vector<lpcompare::Constraint> &vec, std::vector<lpcompare::Constraint> &vecother)\r\n{\r\n\tprintCountsWithSort(detail_name, vec, vecother);\r\n}\r\n\r\n\/**\r\nprintCounts specialization for Bounds, which will be sorted before set operations.\r\n\r\n\\param detail_name Given name of the detail.\r\n\\param vec List of elements that are in the first model.\r\n\\param vecother List of elements that are in the second model.\r\n*\/\r\ntemplate <>\r\nvoid printCounts(std::string detail_name, std::vector<lpcompare::Bound> &vec, std::vector<lpcompare::Bound> &vecother)\r\n{\r\n\tprintCountsWithSort(detail_name, vec, vecother);\r\n}\r\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2020 ASMlover. All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions\n\/\/ are met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright\n\/\/ notice, this list ofconditions and the following disclaimer.\n\/\/\n\/\/ * Redistributions in binary form must reproduce the above copyright\n\/\/ notice, this list of conditions and the following disclaimer in\n\/\/ the documentation and\/or other materialsprovided with the\n\/\/ distribution.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\/\/ \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n\/\/ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n\/\/ FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n\/\/ COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n\/\/ INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n\/\/ BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n\/\/ LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n\/\/ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n\/\/ LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n\/\/ ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n\/\/ POSSIBILITY OF SUCH DAMAGE.\n#include <iostream>\n#include \"lexer.hh\"\n#include \"vm.hh\"\n#include \"string_object.hh\"\n#include \"parser.hh\"\n\nnamespace tadpole {\n\nGlobalParser::GlobalParser(VM& vm, Lexer& lex) noexcept\n : vm_(vm), lex_(lex) {\n}\n\nvoid GlobalParser::mark_parser() {\n for (FunCompiler* c = curr_compiler_; c != nullptr; c = c->enclosing())\n vm_.mark_object(c->fn());\n}\n\nFunctionObject* GlobalParser::compile() {\n FunCompiler compiler;\n init_compiler(&compiler, 0, FunType::TOPLEVEL);\n\n advance();\n while (!check(TokenKind::TK_EOF))\n declaration();\n FunctionObject* fn = finish_compiler();\n\n return had_error_ ? nullptr : fn;\n}\n\nconst ParseRule& GlobalParser::get_rule(TokenKind kind) const noexcept {\n#define _RULE(fn) [](GlobalParser& p, bool b) { p.fn(b); }\n\n static const ParseRule _rules[] = {\n {_RULE(grouping), _RULE(call), Precedence::CALL}, \/\/ PUNCTUATOR(LPAREN, \"(\")\n {nullptr, nullptr, Precedence::NONE}, \/\/ PUNCTUATOR(RPAREN, \")\")\n {nullptr, nullptr, Precedence::NONE}, \/\/ PUNCTUATOR(LBRACE, \"{\")\n {nullptr, nullptr, Precedence::NONE}, \/\/ PUNCTUATOR(RBRACE, \"}\")\n {nullptr, nullptr, Precedence::NONE}, \/\/ PUNCTUATOR(COMMA, \",\")\n {nullptr, _RULE(binary), Precedence::TERM}, \/\/ PUNCTUATOR(MINUS, \"-\")\n {nullptr, _RULE(binary), Precedence::TERM}, \/\/ PUNCTUATOR(PLUS, \"+\")\n {nullptr, nullptr, Precedence::NONE}, \/\/ PUNCTUATOR(SEMI, \";\")\n {nullptr, _RULE(binary), Precedence::FACTOR}, \/\/ PUNCTUATOR(SLASH, \"\/\")\n {nullptr, _RULE(binary), Precedence::FACTOR}, \/\/ PUNCTUATOR(STAR, \"*\")\n {nullptr, nullptr, Precedence::NONE}, \/\/ PUNCTUATOR(EQ, \"=\")\n\n {_RULE(variable), nullptr, Precedence::NONE}, \/\/ TOKEN(IDENTIFIER, \"Identifier\")\n {_RULE(numeric), nullptr, Precedence::NONE}, \/\/ TOKEN(NUMERIC, \"Numeric\")\n {_RULE(string), nullptr, Precedence::NONE}, \/\/ TOKEN(STRING, \"String\")\n\n {_RULE(literal), nullptr, Precedence::NONE}, \/\/ KEYWORD(FALSE, \"false\")\n {nullptr, nullptr, Precedence::NONE}, \/\/ KEYWORD(FN, \"fn\")\n {_RULE(literal), nullptr, Precedence::NONE}, \/\/ KEYWORD(NIL, \"nil\")\n {_RULE(literal), nullptr, Precedence::NONE}, \/\/ KEYWORD(TRUE, \"true\")\n {nullptr, nullptr, Precedence::NONE}, \/\/ KEYWORD(VAR, \"var\")\n\n {nullptr, nullptr, Precedence::NONE}, \/\/ TOKEN(EOF, \"Eof\")\n {nullptr, nullptr, Precedence::NONE}, \/\/ TOKEN(ERR, \"Error\")\n };\n\n#undef _RULE\n return _rules[as_type<int>(kind)];\n}\n\nvoid GlobalParser::error_at(const Token& tok, const str_t& msg) noexcept {\n if (panic_mode_)\n return;\n panic_mode_ = true;\n\n std::cerr\n << \"SyntaxError:\" << std::endl\n << \" [LINE: \" << tok.lineno() << \"] ERROR \";\n if (tok.kind() == TokenKind::TK_EOF)\n std::cerr << \"at end \";\n else if (tok.kind() == TokenKind::TK_ERR)\n (void)0;\n else\n std::cerr << \"at `\" << tok.literal() << \"` \";\n std::cerr << \": \" << msg << std::endl;\n\n had_error_ = true;\n}\n\nvoid GlobalParser::advance() {\n prev_ = curr_;\n\n for (;;) {\n curr_ = lex_.next_token();\n if (!check(TokenKind::TK_ERR))\n break;\n\n error_at_current(curr_.as_string());\n }\n}\n\nvoid GlobalParser::consume(TokenKind kind, const str_t& msg) {\n if (check(kind))\n advance();\n else\n error_at_current(msg);\n}\n\nbool GlobalParser::match(TokenKind kind) {\n if (check(kind)) {\n advance();\n return true;\n }\n return false;\n}\n\nvoid GlobalParser::init_compiler(FunCompiler* compiler, int scope_depth, FunType fn_type) {\n StringObject* func_name{};\n if (fn_type == FunType::FUNCTION)\n func_name = StringObject::create(vm_, prev_.as_string());\n\n compiler->set_compiler(\n curr_compiler_,\n FunctionObject::create(vm_, func_name),\n fn_type,\n scope_depth);\n curr_compiler_ = compiler;\n\n curr_compiler_->append_local(LocalVar(Token::make(\"\"), curr_compiler_->scope_depth(), false));\n}\n\nFunctionObject* GlobalParser::finish_compiler() {\n emit_return();\n\n FunctionObject* fn = curr_compiler_->fn();\n\n#if defined(_TADPOLE_DEBUG_VM)\n if (!had_error_)\n curr_chunk()->dis(fn->name_asstr());\n#endif\n\n curr_compiler_ = curr_compiler_->enclosing();\n return fn;\n}\n\nvoid GlobalParser::enter_scope() {\n curr_compiler_->enter_scope();\n}\n\nvoid GlobalParser::leave_scope() {\n curr_compiler_->leave_scope([this](const LocalVar& var) {\n emit_byte(var.is_upvalue ? Code::CLOSE_UPVALUE : Code::POP);\n });\n}\n\nu8_t GlobalParser::identifier_constant(const Token& name) noexcept {\n return curr_chunk()->add_constant(StringObject::create(vm_, name.as_string()));\n}\n\nu8_t GlobalParser::parse_variable(const str_t& msg) {\n consume(TokenKind::TK_IDENTIFIER, msg);\n\n curr_compiler_->declare_localvar(prev_, [this](const str_t& m) { error(m); });\n if (curr_compiler_->scope_depth() > 0)\n return 0;\n return identifier_constant(prev_);\n}\n\nvoid GlobalParser::mark_initialized() {\n if (curr_compiler_->scope_depth() == 0)\n return;\n curr_compiler_->peek_local().depth = curr_compiler_->scope_depth();\n}\n\nvoid GlobalParser::define_global(u8_t global) {\n if (curr_compiler_->scope_depth() > 0) {\n mark_initialized();\n return;\n }\n emit_bytes(Code::DEF_GLOBAL, global);\n}\n\nu8_t GlobalParser::arguments() {\n u8_t argc = 0;\n if (!check(TokenKind::TK_RPAREN)) {\n do {\n expression();\n ++argc;\n\n if (argc > kMaxArgs)\n error(from_fmt(\"cannot have more than `%d` arguments\", kMaxArgs));\n } while (match(TokenKind::TK_COMMA));\n }\n consume(TokenKind::TK_RPAREN, \"expect `;` after function arguments\");\n\n return argc;\n}\n\nvoid GlobalParser::named_variable(const Token& name, bool can_assign) {\n auto errfn = [this](const str_t& msg) { error(msg); };\n\n Code getop, setop;\n int arg = curr_compiler_->resolve_local(name, errfn);\n if (arg != -1) {\n getop = Code::GET_LOCAL;\n setop = Code::SET_LOCAL;\n }\n else if (arg = curr_compiler_->resolve_upvalue(name, errfn); arg != -1) {\n getop = Code::GET_UPVALUE;\n setop = Code::SET_UPVALUE;\n }\n else {\n arg = identifier_constant(name);\n getop = Code::GET_GLOBAL;\n setop = Code::SET_GLOBAL;\n }\n\n if (can_assign && match(TokenKind::TK_EQ)) {\n expression();\n emit_bytes(setop, arg);\n }\n else {\n emit_bytes(getop, arg);\n }\n}\n\nvoid GlobalParser::parse_precedence(Precedence precedence) {\n advance();\n auto& prefix_fn = get_rule(prev_.kind()).prefix;\n if (!prefix_fn) {\n error(\"expect expression\");\n return;\n }\n\n bool can_assign = precedence <= Precedence::ASSIGN;\n prefix_fn(*this, can_assign);\n\n while (precedence <= get_rule(curr_.kind()).precedence) {\n advance();\n auto& infix_fn = get_rule(prev_.kind()).infix;\n\n if (infix_fn)\n infix_fn(*this, can_assign);\n }\n\n if (can_assign && match(TokenKind::TK_EQ)) {\n error(\"invalid assignment target\");\n expression();\n }\n}\n\nvoid GlobalParser::binary(bool can_assign) {\n TokenKind op = prev_.kind();\n\n parse_precedence(get_rule(op).precedence + 1);\n switch (op) {\n case TokenKind::TK_PLUS: emit_byte(Code::ADD); break;\n case TokenKind::TK_MINUS: emit_byte(Code::SUB); break;\n case TokenKind::TK_STAR: emit_byte(Code::MUL); break;\n case TokenKind::TK_SLASH: emit_byte(Code::DIV); break;\n }\n}\n\nvoid GlobalParser::call(bool can_assign) {\n emit_byte(Code::CALL_0 + arguments());\n}\n\nvoid GlobalParser::grouping(bool can_assign) {\n expression();\n consume(TokenKind::TK_RPAREN, \"expect `)` after grouping expression\");\n}\n\nvoid GlobalParser::literal(bool can_assign) {\n switch (prev_.kind()) {\n case TokenKind::KW_NIL: emit_byte(Code::NIL); break;\n case TokenKind::KW_TRUE: emit_byte(Code::TRUE); break;\n case TokenKind::KW_FALSE: emit_byte(Code::FALSE); break;\n }\n}\n\nvoid GlobalParser::variable(bool can_assign) {\n named_variable(prev_, can_assign);\n}\n\nvoid GlobalParser::numeric(bool can_assign) {\n emit_constant(prev_.as_numeric());\n}\n\nvoid GlobalParser::string(bool can_assign) {\n emit_constant(StringObject::create(vm_, prev_.as_string()));\n}\n\nvoid GlobalParser::block() {\n while (!check(TokenKind::TK_EOF) && !check(TokenKind::TK_RBRACE))\n declaration();\n consume(TokenKind::TK_RBRACE, \"expect `}` after block body\");\n}\n\nvoid GlobalParser::function(FunType fn_type) {}\nvoid GlobalParser::synchronize() {}\nvoid GlobalParser::expression() {}\nvoid GlobalParser::declaration() {}\nvoid GlobalParser::statement() {}\nvoid GlobalParser::fn_decl() {}\nvoid GlobalParser::var_decl() {}\nvoid GlobalParser::expr_stmt() {}\n\n}\n<commit_msg>:construction: chore(function): udpated the implementation of function<commit_after>\/\/ Copyright (c) 2020 ASMlover. All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions\n\/\/ are met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright\n\/\/ notice, this list ofconditions and the following disclaimer.\n\/\/\n\/\/ * Redistributions in binary form must reproduce the above copyright\n\/\/ notice, this list of conditions and the following disclaimer in\n\/\/ the documentation and\/or other materialsprovided with the\n\/\/ distribution.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\/\/ \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n\/\/ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n\/\/ FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n\/\/ COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n\/\/ INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n\/\/ BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n\/\/ LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n\/\/ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n\/\/ LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n\/\/ ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n\/\/ POSSIBILITY OF SUCH DAMAGE.\n#include <iostream>\n#include \"lexer.hh\"\n#include \"vm.hh\"\n#include \"string_object.hh\"\n#include \"parser.hh\"\n\nnamespace tadpole {\n\nGlobalParser::GlobalParser(VM& vm, Lexer& lex) noexcept\n : vm_(vm), lex_(lex) {\n}\n\nvoid GlobalParser::mark_parser() {\n for (FunCompiler* c = curr_compiler_; c != nullptr; c = c->enclosing())\n vm_.mark_object(c->fn());\n}\n\nFunctionObject* GlobalParser::compile() {\n FunCompiler compiler;\n init_compiler(&compiler, 0, FunType::TOPLEVEL);\n\n advance();\n while (!check(TokenKind::TK_EOF))\n declaration();\n FunctionObject* fn = finish_compiler();\n\n return had_error_ ? nullptr : fn;\n}\n\nconst ParseRule& GlobalParser::get_rule(TokenKind kind) const noexcept {\n#define _RULE(fn) [](GlobalParser& p, bool b) { p.fn(b); }\n\n static const ParseRule _rules[] = {\n {_RULE(grouping), _RULE(call), Precedence::CALL}, \/\/ PUNCTUATOR(LPAREN, \"(\")\n {nullptr, nullptr, Precedence::NONE}, \/\/ PUNCTUATOR(RPAREN, \")\")\n {nullptr, nullptr, Precedence::NONE}, \/\/ PUNCTUATOR(LBRACE, \"{\")\n {nullptr, nullptr, Precedence::NONE}, \/\/ PUNCTUATOR(RBRACE, \"}\")\n {nullptr, nullptr, Precedence::NONE}, \/\/ PUNCTUATOR(COMMA, \",\")\n {nullptr, _RULE(binary), Precedence::TERM}, \/\/ PUNCTUATOR(MINUS, \"-\")\n {nullptr, _RULE(binary), Precedence::TERM}, \/\/ PUNCTUATOR(PLUS, \"+\")\n {nullptr, nullptr, Precedence::NONE}, \/\/ PUNCTUATOR(SEMI, \";\")\n {nullptr, _RULE(binary), Precedence::FACTOR}, \/\/ PUNCTUATOR(SLASH, \"\/\")\n {nullptr, _RULE(binary), Precedence::FACTOR}, \/\/ PUNCTUATOR(STAR, \"*\")\n {nullptr, nullptr, Precedence::NONE}, \/\/ PUNCTUATOR(EQ, \"=\")\n\n {_RULE(variable), nullptr, Precedence::NONE}, \/\/ TOKEN(IDENTIFIER, \"Identifier\")\n {_RULE(numeric), nullptr, Precedence::NONE}, \/\/ TOKEN(NUMERIC, \"Numeric\")\n {_RULE(string), nullptr, Precedence::NONE}, \/\/ TOKEN(STRING, \"String\")\n\n {_RULE(literal), nullptr, Precedence::NONE}, \/\/ KEYWORD(FALSE, \"false\")\n {nullptr, nullptr, Precedence::NONE}, \/\/ KEYWORD(FN, \"fn\")\n {_RULE(literal), nullptr, Precedence::NONE}, \/\/ KEYWORD(NIL, \"nil\")\n {_RULE(literal), nullptr, Precedence::NONE}, \/\/ KEYWORD(TRUE, \"true\")\n {nullptr, nullptr, Precedence::NONE}, \/\/ KEYWORD(VAR, \"var\")\n\n {nullptr, nullptr, Precedence::NONE}, \/\/ TOKEN(EOF, \"Eof\")\n {nullptr, nullptr, Precedence::NONE}, \/\/ TOKEN(ERR, \"Error\")\n };\n\n#undef _RULE\n return _rules[as_type<int>(kind)];\n}\n\nvoid GlobalParser::error_at(const Token& tok, const str_t& msg) noexcept {\n if (panic_mode_)\n return;\n panic_mode_ = true;\n\n std::cerr\n << \"SyntaxError:\" << std::endl\n << \" [LINE: \" << tok.lineno() << \"] ERROR \";\n if (tok.kind() == TokenKind::TK_EOF)\n std::cerr << \"at end \";\n else if (tok.kind() == TokenKind::TK_ERR)\n (void)0;\n else\n std::cerr << \"at `\" << tok.literal() << \"` \";\n std::cerr << \": \" << msg << std::endl;\n\n had_error_ = true;\n}\n\nvoid GlobalParser::advance() {\n prev_ = curr_;\n\n for (;;) {\n curr_ = lex_.next_token();\n if (!check(TokenKind::TK_ERR))\n break;\n\n error_at_current(curr_.as_string());\n }\n}\n\nvoid GlobalParser::consume(TokenKind kind, const str_t& msg) {\n if (check(kind))\n advance();\n else\n error_at_current(msg);\n}\n\nbool GlobalParser::match(TokenKind kind) {\n if (check(kind)) {\n advance();\n return true;\n }\n return false;\n}\n\nvoid GlobalParser::init_compiler(FunCompiler* compiler, int scope_depth, FunType fn_type) {\n StringObject* func_name{};\n if (fn_type == FunType::FUNCTION)\n func_name = StringObject::create(vm_, prev_.as_string());\n\n compiler->set_compiler(\n curr_compiler_,\n FunctionObject::create(vm_, func_name),\n fn_type,\n scope_depth);\n curr_compiler_ = compiler;\n\n curr_compiler_->append_local(LocalVar(Token::make(\"\"), curr_compiler_->scope_depth(), false));\n}\n\nFunctionObject* GlobalParser::finish_compiler() {\n emit_return();\n\n FunctionObject* fn = curr_compiler_->fn();\n\n#if defined(_TADPOLE_DEBUG_VM)\n if (!had_error_)\n curr_chunk()->dis(fn->name_asstr());\n#endif\n\n curr_compiler_ = curr_compiler_->enclosing();\n return fn;\n}\n\nvoid GlobalParser::enter_scope() {\n curr_compiler_->enter_scope();\n}\n\nvoid GlobalParser::leave_scope() {\n curr_compiler_->leave_scope([this](const LocalVar& var) {\n emit_byte(var.is_upvalue ? Code::CLOSE_UPVALUE : Code::POP);\n });\n}\n\nu8_t GlobalParser::identifier_constant(const Token& name) noexcept {\n return curr_chunk()->add_constant(StringObject::create(vm_, name.as_string()));\n}\n\nu8_t GlobalParser::parse_variable(const str_t& msg) {\n consume(TokenKind::TK_IDENTIFIER, msg);\n\n curr_compiler_->declare_localvar(prev_, [this](const str_t& m) { error(m); });\n if (curr_compiler_->scope_depth() > 0)\n return 0;\n return identifier_constant(prev_);\n}\n\nvoid GlobalParser::mark_initialized() {\n if (curr_compiler_->scope_depth() == 0)\n return;\n curr_compiler_->peek_local().depth = curr_compiler_->scope_depth();\n}\n\nvoid GlobalParser::define_global(u8_t global) {\n if (curr_compiler_->scope_depth() > 0) {\n mark_initialized();\n return;\n }\n emit_bytes(Code::DEF_GLOBAL, global);\n}\n\nu8_t GlobalParser::arguments() {\n u8_t argc = 0;\n if (!check(TokenKind::TK_RPAREN)) {\n do {\n expression();\n ++argc;\n\n if (argc > kMaxArgs)\n error(from_fmt(\"cannot have more than `%d` arguments\", kMaxArgs));\n } while (match(TokenKind::TK_COMMA));\n }\n consume(TokenKind::TK_RPAREN, \"expect `;` after function arguments\");\n\n return argc;\n}\n\nvoid GlobalParser::named_variable(const Token& name, bool can_assign) {\n auto errfn = [this](const str_t& msg) { error(msg); };\n\n Code getop, setop;\n int arg = curr_compiler_->resolve_local(name, errfn);\n if (arg != -1) {\n getop = Code::GET_LOCAL;\n setop = Code::SET_LOCAL;\n }\n else if (arg = curr_compiler_->resolve_upvalue(name, errfn); arg != -1) {\n getop = Code::GET_UPVALUE;\n setop = Code::SET_UPVALUE;\n }\n else {\n arg = identifier_constant(name);\n getop = Code::GET_GLOBAL;\n setop = Code::SET_GLOBAL;\n }\n\n if (can_assign && match(TokenKind::TK_EQ)) {\n expression();\n emit_bytes(setop, arg);\n }\n else {\n emit_bytes(getop, arg);\n }\n}\n\nvoid GlobalParser::parse_precedence(Precedence precedence) {\n advance();\n auto& prefix_fn = get_rule(prev_.kind()).prefix;\n if (!prefix_fn) {\n error(\"expect expression\");\n return;\n }\n\n bool can_assign = precedence <= Precedence::ASSIGN;\n prefix_fn(*this, can_assign);\n\n while (precedence <= get_rule(curr_.kind()).precedence) {\n advance();\n auto& infix_fn = get_rule(prev_.kind()).infix;\n\n if (infix_fn)\n infix_fn(*this, can_assign);\n }\n\n if (can_assign && match(TokenKind::TK_EQ)) {\n error(\"invalid assignment target\");\n expression();\n }\n}\n\nvoid GlobalParser::binary(bool can_assign) {\n TokenKind op = prev_.kind();\n\n parse_precedence(get_rule(op).precedence + 1);\n switch (op) {\n case TokenKind::TK_PLUS: emit_byte(Code::ADD); break;\n case TokenKind::TK_MINUS: emit_byte(Code::SUB); break;\n case TokenKind::TK_STAR: emit_byte(Code::MUL); break;\n case TokenKind::TK_SLASH: emit_byte(Code::DIV); break;\n }\n}\n\nvoid GlobalParser::call(bool can_assign) {\n emit_byte(Code::CALL_0 + arguments());\n}\n\nvoid GlobalParser::grouping(bool can_assign) {\n expression();\n consume(TokenKind::TK_RPAREN, \"expect `)` after grouping expression\");\n}\n\nvoid GlobalParser::literal(bool can_assign) {\n switch (prev_.kind()) {\n case TokenKind::KW_NIL: emit_byte(Code::NIL); break;\n case TokenKind::KW_TRUE: emit_byte(Code::TRUE); break;\n case TokenKind::KW_FALSE: emit_byte(Code::FALSE); break;\n }\n}\n\nvoid GlobalParser::variable(bool can_assign) {\n named_variable(prev_, can_assign);\n}\n\nvoid GlobalParser::numeric(bool can_assign) {\n emit_constant(prev_.as_numeric());\n}\n\nvoid GlobalParser::string(bool can_assign) {\n emit_constant(StringObject::create(vm_, prev_.as_string()));\n}\n\nvoid GlobalParser::block() {\n while (!check(TokenKind::TK_EOF) && !check(TokenKind::TK_RBRACE))\n declaration();\n consume(TokenKind::TK_RBRACE, \"expect `}` after block body\");\n}\n\nvoid GlobalParser::function(FunType fn_type) {\n FunCompiler fn_compiler;\n init_compiler(&fn_compiler, 1, fn_type);\n\n consume(TokenKind::TK_LPAREN, \"expect `(` after function name\");\n if (!check(TokenKind::TK_RPAREN)) {\n do {\n u8_t param_constant = parse_variable(\"expect function parameter's name\");\n define_global(param_constant);\n\n curr_compiler_->fn()->inc_arity();\n if (curr_compiler_->fn()->arity() > kMaxArgs)\n error(from_fmt(\"cannot have more than `%d` parameters\", kMaxArgs));\n } while (match(TokenKind::TK_COMMA));\n }\n consume(TokenKind::TK_RPAREN, \"expect `)` after function parameters\");\n\n consume(TokenKind::TK_LBRACE, \"expect `{` before function body\");\n block();\n\n leave_scope();\n FunctionObject* fn = finish_compiler();\n\n emit_bytes(Code::CLOSURE, curr_chunk()->add_constant(fn));\n for (sz_t i = 0; i < fn->upvalues_count(); ++i) {\n auto& upvalue = fn_compiler.get_upvalue(i);\n emit_bytes(upvalue.is_local ? 1 : 0, upvalue.index);\n }\n}\n\nvoid GlobalParser::synchronize() {}\nvoid GlobalParser::expression() {}\nvoid GlobalParser::declaration() {}\nvoid GlobalParser::statement() {}\nvoid GlobalParser::fn_decl() {}\nvoid GlobalParser::var_decl() {}\nvoid GlobalParser::expr_stmt() {}\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/--\n\/\/ This file is part of Sonic Pi: http:\/\/sonic-pi.net\n\/\/ Full project source: https:\/\/github.com\/samaaron\/sonic-pi\n\/\/ License: https:\/\/github.com\/samaaron\/sonic-pi\/blob\/master\/LICENSE.md\n\/\/\n\/\/ Copyright 2013, 2014 by Sam Aaron (http:\/\/sam.aaron.name).\n\/\/ All rights reserved.\n\/\/\n\/\/ Permission is granted for use, copying, modification, distribution,\n\/\/ and distribution of modified versions of this work as long as this\n\/\/ notice is included.\n\/\/++\n\n#include <QApplication>\n#include <QSplashScreen>\n#include <QPixmap>\n#include <QBitmap>\n\n#include \"mainwindow.h\"\nint main(int argc, char *argv[])\n{\n Q_INIT_RESOURCE(application);\n\n QApplication app(argc, argv);\n app.setStyle(\"gtk\");\n QPixmap pixmap(\":\/images\/splash.png\");\n QSplashScreen splash(pixmap);\n splash.setMask(pixmap.mask());\n splash.show();\n\n \/\/ QIcon icon(\":images\/app.icns\");\n MainWindow mainWin(app, splash);\n\n \/\/ mainWin.setWindowIcon(icon);\n return app.exec();\n}\n<commit_msg>update main.cpp to use csplashscreen<commit_after>\/\/--\n\/\/ This file is part of Sonic Pi: http:\/\/sonic-pi.net\n\/\/ Full project source: https:\/\/github.com\/samaaron\/sonic-pi\n\/\/ License: https:\/\/github.com\/samaaron\/sonic-pi\/blob\/master\/LICENSE.md\n\/\/\n\/\/ Copyright 2013, 2014 by Sam Aaron (http:\/\/sam.aaron.name).\n\/\/ All rights reserved.\n\/\/\n\/\/ Permission is granted for use, copying, modification, distribution,\n\/\/ and distribution of modified versions of this work as long as this\n\/\/ notice is included.\n\/\/++\n\n#include <QApplication>\n#include <QSplashScreen>\n#include <QPixmap>\n#include <QBitmap>\n#include \"csplashscreen.h\"\n\n#include \"mainwindow.h\"\nint main(int argc, char *argv[])\n{\n Q_INIT_RESOURCE(application);\n\n QApplication app(argc, argv);\n app.setStyle(\"gtk\");\n\n\n QPixmap pixmap(\":\/images\/splash.png\");\n CSplashScreen* splash = new CSplashScreen(pixmap);\n splash->show();\n\n \/\/ QIcon icon(\":images\/app.icns\");\n MainWindow mainWin(app, splash);\n\n \/\/ mainWin.setWindowIcon(icon);\n return app.exec();\n}\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: appquit.cxx,v $\n *\n * $Revision: 1.23 $\n *\n * last change: $Author: rt $ $Date: 2003-09-19 07:56:44 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef _BASMGR_HXX \/\/autogen\n#include <basic\/basmgr.hxx>\n#endif\n#ifndef _SB_SBSTAR_HXX \/\/autogen\n#include <basic\/sbstar.hxx>\n#endif\n\n#ifdef WIN\n#define _TL_LANG_SPECIAL\n#endif\n\n#ifndef _SVDDE_HXX \/\/autogen\n#include <svtools\/svdde.hxx>\n#endif\n#ifndef _MSGBOX_HXX \/\/autogen\n#include <vcl\/msgbox.hxx>\n#endif\n\n#ifndef _SFXENUMITEM_HXX\n#include <svtools\/eitem.hxx>\n#endif\n\n#include <svtools\/inethist.hxx>\n#include <svtools\/saveopt.hxx>\n\n#pragma hdrstop\n\n#include \"app.hrc\"\n#include \"app.hxx\"\n#include \"unoctitm.hxx\"\n#include \"appdata.hxx\"\n#include \"viewsh.hxx\"\n#include \"dispatch.hxx\"\n#include \"printer.hxx\"\n#include \"plugobj.hxx\"\n#include \"arrdecl.hxx\"\n#include \"sfxresid.hxx\"\n#include \"newhdl.hxx\"\n#include \"cfgmgr.hxx\"\n#include \"accmgr.hxx\"\n#include \"event.hxx\"\n#include \"macrconf.hxx\"\n#include \"mnumgr.hxx\"\n#include \"imgmgr.hxx\"\n#include \"templdlg.hxx\"\n#include \"tbxconf.hxx\"\n#include \"msgpool.hxx\"\n#include \"frameobj.hxx\"\n#include \"docfile.hxx\"\n#include \"sfxtypes.hxx\"\n#include \"appimp.hxx\"\n#include \"sfxlocal.hrc\"\n#include \"dataurl.hxx\"\n#include \"fcontnr.hxx\"\n#include \"nochaos.hxx\"\n#include \"appuno.hxx\"\n#include \"doctempl.hxx\"\n#include \"viewfrm.hxx\"\n#include \"bmkmenu.hxx\"\n#include \"objsh.hxx\"\n#include \"dlgcont.hxx\"\n#include \"scriptcont.hxx\"\n#include <misccfg.hxx>\n#include \"docfac.hxx\"\n\n#ifndef PRODUCT\nDECLARE_LIST( SfxFrameWindowFactoryArray_Impl, SfxFrameWindowFactory* )\nSV_DECL_PTRARR(SfxInitLinkList, Link*, 2, 2);\n#endif\n\n\/\/===================================================================\n\/*\nvoid SfxApplication::Quit()\n{\n QueryExit_Impl();\n}\n*\/\n\/\/--------------------------------------------------------------------\nBOOL SfxApplication::QueryExit_Impl()\n\n\/* [Beschreibung]\n\n Liefert FALSE, wenn entweder ein modaler Dialog offen ist, oder\n der Printer einer SfxViewShell einen laufenden Druckjob hat.\n\n [Anmerkung]\n\n Wenn diese aus StarView stammende virtuelle Methode vom Applikations-\n entwickler \"uberladen wird, mu\"s diese SfxApplication::QueryExit() rufen\n und falls diese FALSE zur\"uckgibt, ebenfalls FALSE zur\"uckgeben.\n*\/\n\n{\n SaveConfiguration();\n BOOL bQuit = TRUE;\n\n\/*\n BOOL bPrinting = FALSE;\n for ( SfxViewShell *pViewSh = SfxViewShell::GetFirst();\n !bPrinting && pViewSh;\n pViewSh = SfxViewShell::GetNext(*pViewSh) )\n {\n SfxPrinter *pPrinter = pViewSh->GetPrinter();\n bPrinting = pPrinter && pPrinter->IsPrinting();\n }\n\n if ( bPrinting )\n {\n \/\/ Benutzer fragen, ob abgebrochen werden soll\n if ( RET_OK == QueryBox( 0, SfxResId( MSG_ISPRINTING_QUERYABORT ) ).Execute() )\n {\n \/\/ alle Jobs canceln\n for ( SfxViewShell *pViewSh = SfxViewShell::GetFirst();\n !bPrinting && pViewSh;\n pViewSh = SfxViewShell::GetNext(*pViewSh) )\n {\n SfxPrinter *pPrinter = pViewSh->GetPrinter();\n if ( pPrinter && pPrinter->IsPrinting() )\n pPrinter->AbortJob();\n }\n\n \/\/ da das Canceln asynchron ist, Quit erstmal wieder verlassen\n GetDispatcher_Impl()->Execute( SID_QUITAPP, SFX_CALLMODE_ASYNCHRON );\n DBG_TRACE( \"QueryExit => FALSE (printing)\" );\n return FALSE;\n }\n }\n*\/\n \/\/ alles canceln was zu canceln ist\n GetCancelManager()->Cancel(TRUE);\n\n\/*\n SfxObjectShell *pLastDocSh = SfxObjectShell::GetFirst();\n if ( bQuit )\n {\n \/\/ Jetzt zur Sicherheit auch hidden Frames abr\"aumen\n SfxViewFrame::CloseHiddenFrames_Impl();\n pLastDocSh = SfxObjectShell::GetFirst();\n }\n*\/\n \/\/ will trotzdem noch jemand, den man nicht abschiessen kann, die App haben?\n if ( !bQuit )\n {\n \/\/ nicht wirklich beenden, nur minimieren\n pAppData_Impl->bOLEResize = TRUE;\n InfoBox aInfoBox( NULL, SfxResId(MSG_CANT_QUIT) );\n aInfoBox.Execute();\n DBG_TRACE( \"QueryExit => FALSE (in use)\" );\n return FALSE;\n }\n\n return TRUE;\n}\n\n\/\/-------------------------------------------------------------------------\n\nvoid SfxApplication::Deinitialize()\n{\n if ( bDowning )\n return;\n\n \/\/ Falls man nochmal beim Runterfahren in ein Reschedule l\"auft\n pAppData_Impl->EndListening( *this );\n if ( pAppData_Impl->pCancelMgr )\n pAppData_Impl->EndListening( *pAppData_Impl->pCancelMgr );\n\n \/\/!Wait();\n StarBASIC::Stop();\n\n \/\/ ggf. BASIC speichern\n if ( pImp->pBasicMgr && pImp->pBasicMgr->IsModified() )\n SaveBasicManager();\n\n SaveBasicContainer();\n SaveDialogContainer();\n\n bDowning = TRUE; \/\/ wegen Timer aus DecAliveCount und QueryExit\n\n DELETEZ( pAppData_Impl->pTemplates );\n\n DELETEZ(pImp->pTemplateDlg);\n SetViewFrame(0);\n bDowning = FALSE;\n DBG_ASSERT( !SfxViewFrame::GetFirst(),\n \"existing SfxViewFrame after Execute\" );\n DBG_ASSERT( !SfxObjectShell::GetFirst(),\n \"existing SfxObjectShell after Execute\" );\n pAppDispat->Pop( *this, SFX_SHELL_POP_UNTIL );\n pAppDispat->Flush();\n bDowning = TRUE;\n pAppDispat->DoDeactivate_Impl( TRUE );\n\n INetURLHistory::Delete();\n\n \/\/ call derived application-exit\n bInExit = TRUE;\n Exit();\n\n \/\/ Controller u.\"a. freigeben\n \/\/ dabei sollten auch restliche Komponenten ( Beamer! ) verschwinden\n DELETEZ(pMenuMgr);\n DELETEZ(pAcceleratorMgr);\n SfxObjectFactory::ClearAll_Impl();\n DELETEZ( pImp->pBasicMgr );\n if( pImp->pBasicLibContainer )\n pImp->pBasicLibContainer->release();\n if( pImp->pDialogLibContainer )\n pImp->pDialogLibContainer->release();\n\n bInExit = FALSE;\n\n DBG_ASSERT( pViewFrame == 0, \"active foreign ViewFrame\" );\n\n delete[] pInterfaces, pInterfaces = 0;\n DELETEZ(pImageMgr);\n\n \/\/ free administration managers\n DELETEZ(pImp->pAutoSaveTimer);\n DELETEZ(pAppDispat);\n DELETEZ(pImp->pSfxResManager);\n DELETEZ(pImp->pOfaResMgr);\n\n \/\/ ab hier d\"urfen keine SvObjects mehr existieren\n DELETEX(pAppData_Impl->pMatcher);\n DELETEX(pAppData_Impl->pSfxFrameObjectFactoryPtr);\n DELETEX(pAppData_Impl->pSfxPluginObjectFactoryPtr);\n\n delete pAppData_Impl->pLabelResMgr;\n\n#ifndef PRODUCT\n DELETEX(pSlotPool);\n DELETEX(pAppData_Impl->pEventConfig);\n DELETEX(pAppData_Impl->pMiscConfig);\n SfxMacroConfig::Release_Impl();\n DELETEX(pAppData_Impl->pVerbs);\n DELETEX(pAppData_Impl->pFactArr);\n DELETEX(pAppData_Impl->pInitLinkList);\n#endif\n\n#ifndef PRODUCT\n DELETEX(pImp->pTbxCtrlFac);\n DELETEX(pImp->pStbCtrlFac);\n DELETEX(pImp->pMenuCtrlFac);\n DELETEX(pImp->pEventHdl);\n SfxNewHdl::Delete();\n DELETEX(pImp->pAutoSaveTimer);\n DELETEX(pImp->pViewFrames);\n DELETEX(pImp->pViewShells);\n DELETEX(pImp->pObjShells);\n#endif\n\n NoChaos::ReleaseItemPool();\n pAppData_Impl->pPool = NULL;\n}\n<commit_msg>INTEGRATION: CWS dialogdiet (1.23.28); FILE MERGED 2003\/11\/28 16:22:41 mba 1.23.28.1: #i22972#: misccfg moved to svtools; ResMgr now static<commit_after>\/*************************************************************************\n *\n * $RCSfile: appquit.cxx,v $\n *\n * $Revision: 1.24 $\n *\n * last change: $Author: hr $ $Date: 2004-02-03 19:53:41 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef _BASMGR_HXX \/\/autogen\n#include <basic\/basmgr.hxx>\n#endif\n#ifndef _SB_SBSTAR_HXX \/\/autogen\n#include <basic\/sbstar.hxx>\n#endif\n\n#ifdef WIN\n#define _TL_LANG_SPECIAL\n#endif\n\n#ifndef _SVDDE_HXX \/\/autogen\n#include <svtools\/svdde.hxx>\n#endif\n#ifndef _MSGBOX_HXX \/\/autogen\n#include <vcl\/msgbox.hxx>\n#endif\n\n#ifndef _SFXENUMITEM_HXX\n#include <svtools\/eitem.hxx>\n#endif\n\n#include <svtools\/inethist.hxx>\n#include <svtools\/saveopt.hxx>\n\n#pragma hdrstop\n\n#include \"app.hrc\"\n#include \"app.hxx\"\n#include \"unoctitm.hxx\"\n#include \"appdata.hxx\"\n#include \"viewsh.hxx\"\n#include \"dispatch.hxx\"\n#include \"printer.hxx\"\n#include \"plugobj.hxx\"\n#include \"arrdecl.hxx\"\n#include \"sfxresid.hxx\"\n#include \"newhdl.hxx\"\n#include \"cfgmgr.hxx\"\n#include \"accmgr.hxx\"\n#include \"event.hxx\"\n#include \"macrconf.hxx\"\n#include \"mnumgr.hxx\"\n#include \"imgmgr.hxx\"\n#include \"templdlg.hxx\"\n#include \"tbxconf.hxx\"\n#include \"msgpool.hxx\"\n#include \"frameobj.hxx\"\n#include \"docfile.hxx\"\n#include \"sfxtypes.hxx\"\n#include \"appimp.hxx\"\n#include \"sfxlocal.hrc\"\n#include \"dataurl.hxx\"\n#include \"fcontnr.hxx\"\n#include \"nochaos.hxx\"\n#include \"appuno.hxx\"\n#include \"doctempl.hxx\"\n#include \"viewfrm.hxx\"\n#include \"bmkmenu.hxx\"\n#include \"objsh.hxx\"\n#include \"dlgcont.hxx\"\n#include \"scriptcont.hxx\"\n#include <svtools\/misccfg.hxx>\n#include \"docfac.hxx\"\n\n#ifndef PRODUCT\nDECLARE_LIST( SfxFrameWindowFactoryArray_Impl, SfxFrameWindowFactory* )\nSV_DECL_PTRARR(SfxInitLinkList, Link*, 2, 2);\n#endif\n\n\/\/===================================================================\n\/*\nvoid SfxApplication::Quit()\n{\n QueryExit_Impl();\n}\n*\/\n\/\/--------------------------------------------------------------------\nBOOL SfxApplication::QueryExit_Impl()\n\n\/* [Beschreibung]\n\n Liefert FALSE, wenn entweder ein modaler Dialog offen ist, oder\n der Printer einer SfxViewShell einen laufenden Druckjob hat.\n\n [Anmerkung]\n\n Wenn diese aus StarView stammende virtuelle Methode vom Applikations-\n entwickler \"uberladen wird, mu\"s diese SfxApplication::QueryExit() rufen\n und falls diese FALSE zur\"uckgibt, ebenfalls FALSE zur\"uckgeben.\n*\/\n\n{\n SaveConfiguration();\n BOOL bQuit = TRUE;\n\n\/*\n BOOL bPrinting = FALSE;\n for ( SfxViewShell *pViewSh = SfxViewShell::GetFirst();\n !bPrinting && pViewSh;\n pViewSh = SfxViewShell::GetNext(*pViewSh) )\n {\n SfxPrinter *pPrinter = pViewSh->GetPrinter();\n bPrinting = pPrinter && pPrinter->IsPrinting();\n }\n\n if ( bPrinting )\n {\n \/\/ Benutzer fragen, ob abgebrochen werden soll\n if ( RET_OK == QueryBox( 0, SfxResId( MSG_ISPRINTING_QUERYABORT ) ).Execute() )\n {\n \/\/ alle Jobs canceln\n for ( SfxViewShell *pViewSh = SfxViewShell::GetFirst();\n !bPrinting && pViewSh;\n pViewSh = SfxViewShell::GetNext(*pViewSh) )\n {\n SfxPrinter *pPrinter = pViewSh->GetPrinter();\n if ( pPrinter && pPrinter->IsPrinting() )\n pPrinter->AbortJob();\n }\n\n \/\/ da das Canceln asynchron ist, Quit erstmal wieder verlassen\n GetDispatcher_Impl()->Execute( SID_QUITAPP, SFX_CALLMODE_ASYNCHRON );\n DBG_TRACE( \"QueryExit => FALSE (printing)\" );\n return FALSE;\n }\n }\n*\/\n \/\/ alles canceln was zu canceln ist\n GetCancelManager()->Cancel(TRUE);\n\n\/*\n SfxObjectShell *pLastDocSh = SfxObjectShell::GetFirst();\n if ( bQuit )\n {\n \/\/ Jetzt zur Sicherheit auch hidden Frames abr\"aumen\n SfxViewFrame::CloseHiddenFrames_Impl();\n pLastDocSh = SfxObjectShell::GetFirst();\n }\n*\/\n \/\/ will trotzdem noch jemand, den man nicht abschiessen kann, die App haben?\n if ( !bQuit )\n {\n \/\/ nicht wirklich beenden, nur minimieren\n pAppData_Impl->bOLEResize = TRUE;\n InfoBox aInfoBox( NULL, SfxResId(MSG_CANT_QUIT) );\n aInfoBox.Execute();\n DBG_TRACE( \"QueryExit => FALSE (in use)\" );\n return FALSE;\n }\n\n return TRUE;\n}\n\n\/\/-------------------------------------------------------------------------\n\nvoid SfxApplication::Deinitialize()\n{\n if ( bDowning )\n return;\n\n \/\/ Falls man nochmal beim Runterfahren in ein Reschedule l\"auft\n pAppData_Impl->EndListening( *this );\n if ( pAppData_Impl->pCancelMgr )\n pAppData_Impl->EndListening( *pAppData_Impl->pCancelMgr );\n\n \/\/!Wait();\n StarBASIC::Stop();\n\n \/\/ ggf. BASIC speichern\n if ( pImp->pBasicMgr && pImp->pBasicMgr->IsModified() )\n SaveBasicManager();\n\n SaveBasicContainer();\n SaveDialogContainer();\n\n bDowning = TRUE; \/\/ wegen Timer aus DecAliveCount und QueryExit\n\n DELETEZ( pAppData_Impl->pTemplates );\n\n DELETEZ(pImp->pTemplateDlg);\n SetViewFrame(0);\n bDowning = FALSE;\n DBG_ASSERT( !SfxViewFrame::GetFirst(),\n \"existing SfxViewFrame after Execute\" );\n DBG_ASSERT( !SfxObjectShell::GetFirst(),\n \"existing SfxObjectShell after Execute\" );\n pAppDispat->Pop( *this, SFX_SHELL_POP_UNTIL );\n pAppDispat->Flush();\n bDowning = TRUE;\n pAppDispat->DoDeactivate_Impl( TRUE );\n\n INetURLHistory::Delete();\n\n \/\/ call derived application-exit\n bInExit = TRUE;\n Exit();\n\n \/\/ Controller u.\"a. freigeben\n \/\/ dabei sollten auch restliche Komponenten ( Beamer! ) verschwinden\n DELETEZ(pMenuMgr);\n DELETEZ(pAcceleratorMgr);\n SfxObjectFactory::ClearAll_Impl();\n DELETEZ( pImp->pBasicMgr );\n if( pImp->pBasicLibContainer )\n pImp->pBasicLibContainer->release();\n if( pImp->pDialogLibContainer )\n pImp->pDialogLibContainer->release();\n\n bInExit = FALSE;\n\n DBG_ASSERT( pViewFrame == 0, \"active foreign ViewFrame\" );\n\n delete[] pInterfaces, pInterfaces = 0;\n DELETEZ(pImageMgr);\n\n \/\/ free administration managers\n DELETEZ(pImp->pAutoSaveTimer);\n DELETEZ(pAppDispat);\n SfxResId::DeleteResMgr();\n DELETEZ(pImp->pOfaResMgr);\n\n \/\/ ab hier d\"urfen keine SvObjects mehr existieren\n DELETEX(pAppData_Impl->pMatcher);\n DELETEX(pAppData_Impl->pSfxFrameObjectFactoryPtr);\n DELETEX(pAppData_Impl->pSfxPluginObjectFactoryPtr);\n\n delete pAppData_Impl->pLabelResMgr;\n\n#ifndef PRODUCT\n DELETEX(pSlotPool);\n DELETEX(pAppData_Impl->pEventConfig);\n DELETEX(pAppData_Impl->pMiscConfig);\n SfxMacroConfig::Release_Impl();\n DELETEX(pAppData_Impl->pVerbs);\n DELETEX(pAppData_Impl->pFactArr);\n DELETEX(pAppData_Impl->pInitLinkList);\n#endif\n\n#ifndef PRODUCT\n DELETEX(pImp->pTbxCtrlFac);\n DELETEX(pImp->pStbCtrlFac);\n DELETEX(pImp->pMenuCtrlFac);\n DELETEX(pImp->pEventHdl);\n SfxNewHdl::Delete();\n DELETEX(pImp->pAutoSaveTimer);\n DELETEX(pImp->pViewFrames);\n DELETEX(pImp->pViewShells);\n DELETEX(pImp->pObjShells);\n#endif\n\n NoChaos::ReleaseItemPool();\n pAppData_Impl->pPool = NULL;\n}\n<|endoftext|>"} {"text":"<commit_before>#ifndef __BH_VE_CPU_BLOCK\n#define __BH_VE_CPU_BLOCK\n#include <string>\n#include <map>\n\n#include \"bh.h\"\n#include \"tac.h\"\n#include \"symbol_table.hpp\"\n#include \"utils.hpp\"\n\nnamespace bohrium{\nnamespace core{\n\nclass Block {\npublic:\n Block(SymbolTable& globals, std::vector<tac_t>& program);\n ~Block();\n\n \/**\n * Clear the composed block, does not de-allocate or remove\n * the associated globals, program and memory allocated for the\n * block.\n * It simply clears it for reuse.\n *\/\n void clear(void);\n\n \/**\n * Compose the block based based on a subset of program instructions.\n *\n * @param prg_begin Start of the subset.\n * @param prg_end End of the subset, to and including prg_end.\n *\/\n void compose(size_t prg_begin, size_t prg_end);\n\n \/**\n * Compose the block based based on a subset of program instructions.\n *\n * TODO: Document\n *\n * @param prg_begin Start of the subset.\n * @param prg_end End of the subset, to and including prg_end.\n *\/\n void compose(bh_ir_kernel& krnl);\n\n \/**\n * Return the block-local operand-index corresponding \n * to the given global operand-index.\n *\n * @param global_idx The global operand-index to resolve\n * @return The block-local operand-index\n *\/\n size_t global_to_local(size_t global_idx) const;\n\n \/**\n * Return the global operand-index corresponding \n * to the given local operand-index.\n *\n * @param local_idx The local operand-index to resolve\n * @return The global operand-index\n *\/\n size_t local_to_global(size_t local_idx) const;\n\n \/**\n * Create an operand with block scope based on the operand in global scope.\n *\n * Reuses operands of equivalent meta-data.\n *\n * @param global_idx Global index of the operand to add to block scope.\n *\n * @returns The block-scoped index.\n *\/\n size_t localize(size_t global_idx);\n\n \/**\n * Create a symbol for the block.\n *\n * The textual version of the symbol looks something like::\n * \n * symbol_text = ZIP-ADD-2D~1~2~3_~1Cf~2Cf~3Cf\n *\n * Which will be hashed to some uint32_t value::\n *\n * symbol = 2111321312412321432424\n *\n * NOTE: System and extension operations are ignored.\n * If a block consists of nothing but system and\/or extension\n * opcodes then the symbol will be the empty string \"\".\n *\/\n bool symbolize(void);\n\n \/\/\n \/\/ Getters\n \/\/\n\n \/**\n * Returns the operand with local in block-scope.\n *\n * @param local_idx Index \/ name in the block-scope of the operand.\n * @param A reference to the requested operand.\n *\/\n operand_t& operand(size_t local_idx);\n\n \/**\n * Return the array of pointer-operands.\n *\/\n operand_t** operands(void);\n\n \/**\n * Count of operands in the block.\n *\/\n size_t noperands(void) const;\n\n \/**\n * Return the tac-instance with the given index.\n *\/\n tac_t& tac(size_t idx) const;\n tac_t& array_tac(size_t idx) const;\n\n \/**\n * Count of tacs in the block.\n *\/\n size_t ntacs(void) const;\n\n \/**\n * Count of array-tacs in the block.\n *\/\n size_t narray_tacs(void) const;\n\n std::string symbol(void) const;\n std::string symbol_text(void) const;\n\n \/**\n * Returns the iteration space of the block.\n *\/\n iterspace_t& iterspace(void);\n\n \/**\n * Update the iteration space of the block.\n *\n * This means determing the \"dominating\" LAYOUT, ndim, shape,\n * and number of elements of an operation within the block.\n *\n * That is choosing the \"worst\" LAYOUT, highest ndim, and then\n * choosing the shape of the operand with chose characteristics.\n *\n * Since this is what will be the upper-bounds used in when\n * generating \/ specializing code, primarily for fusion \/ contraction.\n *\n * NOTE: This should be done after applying array contraction or \n * any other changes to tacs and operands.\n *\/\n void update_iterspace(void);\n\n \/**\n * Returns a textual representation of the block in dot-format.\n *\/\n std::string dot(void) const;\n\n \/**\n * Returns a plaintext representation of the block.\n *\/\n std::string text(void);\n\n uint32_t omask(void); \n\nprivate:\n\n Block();\n\n SymbolTable& globals_; \/\/ A reference to the global symbol table\n std::vector<tac_t>& program_; \/\/ A reference to the entire bytecode program\n\n iterspace_t iterspace_; \/\/ The iteration-space of the block\n\n std::vector<tac_t*> tacs_; \/\/ A subset of the tac-program reprensting the block.\n std::vector<tac_t*> array_tacs_;\/\/ A subset of the tac-program containing only array ops.\n\n \/\/SymbolTable locals_; \/\/ A symbol table with block-scope\n operand_t** operands_;\n size_t noperands_;\n std::map<size_t, size_t> global_to_local_; \/\/ Mapping from global to block-local scope.\n std::map<size_t, size_t> local_to_global_; \/\/ Mapping from global to block-local scope.\n\n std::string symbol_text_; \/\/ Textual representation of the block\n std::string symbol_; \/\/ Hash of textual representation\n\n uint32_t omask;\n\n static const char TAG[];\n};\n\n}}\n#endif\n<commit_msg>cpu: Fix (omask->omask_) name of omask var.<commit_after>#ifndef __BH_VE_CPU_BLOCK\n#define __BH_VE_CPU_BLOCK\n#include <string>\n#include <map>\n\n#include \"bh.h\"\n#include \"tac.h\"\n#include \"symbol_table.hpp\"\n#include \"utils.hpp\"\n\nnamespace bohrium{\nnamespace core{\n\nclass Block {\npublic:\n Block(SymbolTable& globals, std::vector<tac_t>& program);\n ~Block();\n\n \/**\n * Clear the composed block, does not de-allocate or remove\n * the associated globals, program and memory allocated for the\n * block.\n * It simply clears it for reuse.\n *\/\n void clear(void);\n\n \/**\n * Compose the block based based on a subset of program instructions.\n *\n * @param prg_begin Start of the subset.\n * @param prg_end End of the subset, to and including prg_end.\n *\/\n void compose(size_t prg_begin, size_t prg_end);\n\n \/**\n * Compose the block based based on a subset of program instructions.\n *\n * TODO: Document\n *\n * @param prg_begin Start of the subset.\n * @param prg_end End of the subset, to and including prg_end.\n *\/\n void compose(bh_ir_kernel& krnl);\n\n \/**\n * Return the block-local operand-index corresponding \n * to the given global operand-index.\n *\n * @param global_idx The global operand-index to resolve\n * @return The block-local operand-index\n *\/\n size_t global_to_local(size_t global_idx) const;\n\n \/**\n * Return the global operand-index corresponding \n * to the given local operand-index.\n *\n * @param local_idx The local operand-index to resolve\n * @return The global operand-index\n *\/\n size_t local_to_global(size_t local_idx) const;\n\n \/**\n * Create an operand with block scope based on the operand in global scope.\n *\n * Reuses operands of equivalent meta-data.\n *\n * @param global_idx Global index of the operand to add to block scope.\n *\n * @returns The block-scoped index.\n *\/\n size_t localize(size_t global_idx);\n\n \/**\n * Create a symbol for the block.\n *\n * The textual version of the symbol looks something like::\n * \n * symbol_text = ZIP-ADD-2D~1~2~3_~1Cf~2Cf~3Cf\n *\n * Which will be hashed to some uint32_t value::\n *\n * symbol = 2111321312412321432424\n *\n * NOTE: System and extension operations are ignored.\n * If a block consists of nothing but system and\/or extension\n * opcodes then the symbol will be the empty string \"\".\n *\/\n bool symbolize(void);\n\n \/\/\n \/\/ Getters\n \/\/\n\n \/**\n * Returns the operand with local in block-scope.\n *\n * @param local_idx Index \/ name in the block-scope of the operand.\n * @param A reference to the requested operand.\n *\/\n operand_t& operand(size_t local_idx);\n\n \/**\n * Return the array of pointer-operands.\n *\/\n operand_t** operands(void);\n\n \/**\n * Count of operands in the block.\n *\/\n size_t noperands(void) const;\n\n \/**\n * Return the tac-instance with the given index.\n *\/\n tac_t& tac(size_t idx) const;\n tac_t& array_tac(size_t idx) const;\n\n \/**\n * Count of tacs in the block.\n *\/\n size_t ntacs(void) const;\n\n \/**\n * Count of array-tacs in the block.\n *\/\n size_t narray_tacs(void) const;\n\n std::string symbol(void) const;\n std::string symbol_text(void) const;\n\n \/**\n * Returns the iteration space of the block.\n *\/\n iterspace_t& iterspace(void);\n\n \/**\n * Update the iteration space of the block.\n *\n * This means determing the \"dominating\" LAYOUT, ndim, shape,\n * and number of elements of an operation within the block.\n *\n * That is choosing the \"worst\" LAYOUT, highest ndim, and then\n * choosing the shape of the operand with chose characteristics.\n *\n * Since this is what will be the upper-bounds used in when\n * generating \/ specializing code, primarily for fusion \/ contraction.\n *\n * NOTE: This should be done after applying array contraction or \n * any other changes to tacs and operands.\n *\/\n void update_iterspace(void);\n\n \/**\n * Returns a textual representation of the block in dot-format.\n *\/\n std::string dot(void) const;\n\n \/**\n * Returns a plaintext representation of the block.\n *\/\n std::string text(void);\n\n uint32_t omask(void); \n\nprivate:\n\n Block();\n\n SymbolTable& globals_; \/\/ A reference to the global symbol table\n std::vector<tac_t>& program_; \/\/ A reference to the entire bytecode program\n\n iterspace_t iterspace_; \/\/ The iteration-space of the block\n\n std::vector<tac_t*> tacs_; \/\/ A subset of the tac-program reprensting the block.\n std::vector<tac_t*> array_tacs_;\/\/ A subset of the tac-program containing only array ops.\n\n \/\/SymbolTable locals_; \/\/ A symbol table with block-scope\n operand_t** operands_;\n size_t noperands_;\n std::map<size_t, size_t> global_to_local_; \/\/ Mapping from global to block-local scope.\n std::map<size_t, size_t> local_to_global_; \/\/ Mapping from global to block-local scope.\n\n std::string symbol_text_; \/\/ Textual representation of the block\n std::string symbol_; \/\/ Hash of textual representation\n\n uint32_t omask_;\n\n static const char TAG[];\n};\n\n}}\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/\/ \n\/\/ \n\/\/ Copyright (C) 2005 SIPfoundry Inc.\n\/\/ Licensed by SIPfoundry under the LGPL license.\n\/\/ \n\/\/ Copyright (C) 2005 Pingtel Corp.\n\/\/ Licensed to SIPfoundry under a Contributor Agreement.\n\/\/ \n\/\/ $$\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/ SYSTEM INCLUDES\n#include <string.h>\n#include <sys\/types.h>\n#include <sys\/types.h>\n#include <regex.h>\n\n\/\/ APPLICATION INCLUDES\n#include \"os\/OsSysLog.h\"\n#include \"os\/OsDefs.h\"\n#include \"SipRedirectorISN.h\"\n#include \"net\/SipSrvLookup.h\"\n#include \"net\/Url.h\"\n\n#if defined(_WIN32)\n# include \"resparse\/wnt\/sysdep.h\"\n# include <resparse\/wnt\/netinet\/in.h>\n# include <resparse\/wnt\/arpa\/nameser.h>\n# include <resparse\/wnt\/resolv\/resolv.h>\n# include <winsock.h>\nextern \"C\" {\n# include \"resparse\/wnt\/inet_aton.h\" \n}\n#elif defined(_VXWORKS)\n# include <stdio.h>\n# include <netdb.h>\n# include <netinet\/in.h>\n# include <vxWorks.h>\n\/* Use local lnameser.h for info missing from VxWorks version --GAT *\/\n\/* lnameser.h is a subset of resparse\/wnt\/arpa\/nameser.h *\/\n# include <resolv\/nameser.h>\n# include <resparse\/vxw\/arpa\/lnameser.h>\n\/* Use local lresolv.h for info missing from VxWorks version --GAT *\/\n\/* lresolv.h is a subset of resparse\/wnt\/resolv\/resolv.h *\/\n# include <resolv\/resolv.h>\n# include <resparse\/vxw\/resolv\/lresolv.h>\n\/* #include <sys\/socket.h> used sockLib.h instead --GAT *\/\n# include <sockLib.h>\n# include <resolvLib.h>\n# include <resparse\/vxw\/hd_string.h>\n#elif defined(__pingtel_on_posix__)\n# include <arpa\/inet.h>\n# include <netinet\/in.h>\n# include <sys\/socket.h>\n# include <resolv.h>\n# include <netdb.h>\n#else\n# error Unsupported target platform.\n#endif\n\n#ifndef __pingtel_on_posix__\nextern struct __res_state _sip_res;\n#endif\n\n#include \"resparse\/rr.h\"\n\n\/\/ The space allocated for returns from res_query.\n#define DNS_RESPONSE_SIZE 4096\n\n\/\/ DEFINES\n\/\/ MACROS\n\/\/ EXTERNAL FUNCTIONS\n\/\/ EXTERNAL VARIABLES\n\/\/ CONSTANTS\n\/\/ STRUCTS\n\/\/ TYPEDEFS\n\/\/ FORWARD DECLARATIONS\n\n\/\/ Static factory function.\nextern \"C\" RedirectPlugin* getRedirectPlugin(const UtlString& instanceName)\n{\n return new SipRedirectorISN(instanceName);\n}\n\n\/\/ Constructor\nSipRedirectorISN::SipRedirectorISN(const UtlString& instanceName) :\n RedirectPlugin(instanceName)\n{\n}\n\n\/\/ Destructor\nSipRedirectorISN::~SipRedirectorISN()\n{\n}\n\n\/\/ Read config information.\nvoid SipRedirectorISN::readConfig(OsConfigDb& configDb)\n{\n if (configDb.get(\"BASE_DOMAIN\", mBaseDomain) != OS_SUCCESS ||\n mBaseDomain.isNull())\n {\n OsSysLog::add(FAC_SIP, PRI_CRIT,\n \"SipRedirectorISN::readConfig \"\n \"BASE_DOMAIN parameter missing or empty\");\n }\n else\n {\n OsSysLog::add(FAC_SIP, PRI_INFO,\n \"SipRedirectorISN::readConfig \"\n \"BASE_DOMAIN is '%s'\", mBaseDomain.data());\n }\n\n if (configDb.get(\"PREFIX\", mPrefix) != OS_SUCCESS ||\n mPrefix.isNull())\n {\n OsSysLog::add(FAC_SIP, PRI_INFO,\n \"SipRedirectorISN::readConfig \"\n \"dialing prefix is empty\");\n }\n else\n {\n OsSysLog::add(FAC_SIP, PRI_INFO,\n \"SipRedirectorISN::readConfig \"\n \"dialing prefix is '%s'\", mPrefix.data());\n }\n}\n\n\/\/ Initializer\nOsStatus\nSipRedirectorISN::initialize(OsConfigDb& configDb,\n SipUserAgent* pSipUserAgent,\n int redirectorNo,\n const UtlString& localDomainHost)\n{\n return mBaseDomain.isNull() ? OS_FAILED : OS_SUCCESS;\n}\n\n\/\/ Finalizer\nvoid\nSipRedirectorISN::finalize()\n{\n}\n\nRedirectPlugin::LookUpStatus\nSipRedirectorISN::lookUp(\n const SipMessage& message,\n const UtlString& requestString,\n const Url& requestUri,\n const UtlString& method,\n SipMessage& response,\n RequestSeqNo requestSeqNo,\n int redirectorNo,\n SipRedirectorPrivateStorage*& privateStorage)\n{\n bool status = false;\n\n \/\/ Get the user part.\n UtlString userId;\n requestUri.getUserId(userId);\n\n \/\/ Test if the user part is in the right format -- prefix followed by digits*digits\n const char* user = userId.data();\n int prefix_length = mPrefix.length();\n \/\/ Compare the prefix.\n int i; \/\/ Length of the extension part.\n if (strncmp(user, mPrefix.data(), prefix_length) == 0)\n {\n \/\/ Effectively delete the prefix from the user part.\n user += prefix_length;\n \/\/ Check the syntax of the remainder of the user.\n i = strspn(user, \"0123456789\");\n int j = 0;\n if (i > 0)\n {\n if (user[i] == '*')\n {\n j = strspn(user + i + 1, \"0123456789\");\n if (user[i + 1 + j] == '\\0')\n {\n status = true;\n }\n }\n }\n }\n\n if (status)\n {\n \/\/ Format of user part is correct. Look for NAPTR records.\n\n \/\/ Create the domain to look up.\n char domain[2 * strlen(user) + mBaseDomain.length()];\n {\n char* p = &domain[0];\n \/\/ Copy the extension, reversing it and following each digit with a period.\n for (int k = i; --k >= 0; )\n {\n *p++ = user[k];\n *p++ = '.';\n }\n \/\/ Append the ITAD and a period.\n strcpy(p, user + i + 1);\n strcat(p, \".\");\n \/\/ Append the ITAD root domain.\n strcpy(p, mBaseDomain.data());\n }\n OsSysLog::add(FAC_SIP, PRI_DEBUG,\n \"SipRedirectorISN::lookUp user '%s' has ISN format, domain is '%s'\",\n user, domain);\n\n \/\/ To hold the return of res_query_and_parse.\n res_response* dns_response;\n const char* canonical_name;\n \n \/\/ Make the query and parse the response.\n SipSrvLookup::res_query_and_parse(domain, T_NAPTR, NULL, canonical_name, dns_response);\n\n if (dns_response != NULL)\n {\n \/\/ Search the list of RRs for the 'best' answer.\n \/\/ Initialize to values at least 2**16.\n int lowest_order_seen = 1 << 16, lowest_preference_seen = 1 << 16;\n int best_response = -1; \/\/ No response found..\n \/\/ Search the answer list.\n for (unsigned int i = 0; i < dns_response->header.ancount; i++)\n {\n if (dns_response->answer[i]->rclass == C_IN &&\n dns_response->answer[i]->type == T_NAPTR &&\n \/\/ Note we look for the canonical name now.\n strcasecmp(canonical_name, dns_response->answer[i]->name) == 0)\n {\n \/\/ A NAPTR record has been found.\n OsSysLog::add(FAC_SIP, PRI_DEBUG,\n \"SipRedirectorISN::LookUp \"\n \"NAPTR record found '%s' %d %d %d %d '%s' '%s' '%s' '%s'\",\n dns_response->answer[i]->name,\n dns_response->answer[i]->rclass,\n dns_response->answer[i]->type,\n dns_response->answer[i]->rdata.naptr.order,\n dns_response->answer[i]->rdata.naptr.preference,\n dns_response->answer[i]->rdata.naptr.flags,\n dns_response->answer[i]->rdata.naptr.services,\n dns_response->answer[i]->rdata.naptr.regexp,\n dns_response->answer[i]->rdata.naptr.replacement);\n \/\/ Accept the record if flags are 'u' and services are 'E2U+sip'.\n \/\/ Note that the value 'E2U+sip' is defined by RFC 3764\n \/\/ (SIP enumservice) not RFC 2915 (the original NAPTR RFC).\n if (strcasecmp(dns_response->answer[i]->rdata.naptr.flags, \"u\") == 0 &&\n strcasecmp(dns_response->answer[i]->rdata.naptr.services, \"E2U+sip\") == 0)\n {\n \/\/ Check that it has the lowest order and preference values seen so far.\n if (dns_response->answer[i]->rdata.naptr.order < lowest_order_seen ||\n (dns_response->answer[i]->rdata.naptr.order == lowest_order_seen &&\n dns_response->answer[i]->rdata.naptr.preference < lowest_preference_seen))\n {\n best_response = i;\n lowest_order_seen = dns_response->answer[i]->rdata.naptr.order;\n lowest_preference_seen = dns_response->answer[i]->rdata.naptr.preference;\n }\n }\n }\n }\n\n \/\/ At this point, best_response (if any) is the response we chose.\n if (best_response != -1)\n {\n char* p = dns_response->answer[best_response]->rdata.naptr.regexp;\n OsSysLog::add(FAC_SIP, PRI_DEBUG,\n \"SipRedirectorISN::LookUp Using NAPTR rewrite '%s' for '%s'\",\n p, domain);\n \/\/ Enough space for the 'match' part of the regexp field.\n char match[strlen(p) + 1];\n \/\/ Pointer to the 'replace' part of the regexp field.\n char delim;\n const char* replace;\n int i_flag;\n if (res_naptr_split_regexp(p, &delim, match, &replace, &i_flag))\n {\n OsSysLog::add(FAC_SIP, PRI_DEBUG,\n \"SipRedirectorISN::LookUp match = '%s', replace = '%s', i_flag = %d\",\n match, replace, i_flag);\n \/\/ Split operation was successful. Try to match.\n regex_t reg;\n int ret = regcomp(®, match, REG_EXTENDED | (i_flag ? REG_ICASE : 0));\n if (ret == 0)\n {\n \/\/ NAPTR matches can have only 9 substitutions.\n regmatch_t pmatch[9];\n \/\/ regexec returns 0 for success.\n \/\/ Though RFC 3761 and the ISN Cookbook don't say, it appears\n \/\/ that the regexp is matched against the user-part of the SIP URI.\n if (regexec(®, user, 9, pmatch, 0) == 0)\n {\n \/\/ Match was successful. Construct the replacement string.\n \/\/ Current usage is that the replacement string is the resulting URI,\n \/\/ not the replacement into the original application-string.\n char* result = res_naptr_replace(replace, delim, pmatch, user, 0);\n OsSysLog::add(FAC_SIP, PRI_DEBUG,\n \"SipRedirectorISN::LookUp result = '%s'\",\n result);\n \/\/ Note that the replacement string is not\n \/\/ substituted back into the original string, but used\n \/\/ alone as the destination URI.\n \/\/ Parse result string into URI.\n Url contact(result, TRUE);\n \/\/ Almost all strings are parsable as SIP URIs with a sufficient\n \/\/ number of components missing. Be we can check that a scheme\n \/\/ was identified, and that a host name was found.\n \/\/ (A string with sufficiently few punctuation characters appears to\n \/\/ be a sip: URI with the scheme missing and only a host name, but\n \/\/ the legal character set for host names is fairly narrow.)\n UtlString h;\n contact.getHostAddress(h);\n if (contact.getScheme() != Url::UnknownUrlScheme && !h.isNull())\n {\n RedirectPlugin::addContact(response, requestString,\n contact, \"ISN\");\n\n }\n else\n {\n OsSysLog::add(FAC_SIP, PRI_ERR,\n \"SipRedirectorISN::LookUp Bad result string '%s' - \"\n \"could not identify URI scheme and\/or host name is null - \"\n \"for ISN translation of '%s'\",\n result, requestString.data());\n }\n \/\/ Free the result string.\n free(result);\n }\n else\n {\n OsSysLog::add(FAC_SIP, PRI_WARNING,\n \"SipRedirectorISN::LookUp NAPTR regexp '%s' does not match \"\n \"for ISN translation of '%s' - no contact generated\",\n match, requestString.data());\n }\n \/\/ Free the parsed regexp structure.\n regfree(®);\n }\n else\n {\n OsSysLog::add(FAC_SIP, PRI_WARNING,\n \"SipRedirectorISN::LookUp NAPTR regexp '%s' is syntactially invalid \"\n \"for ISN translation of '%s'\",\n match, requestString.data());\n }\n }\n else\n {\n OsSysLog::add(FAC_SIP, PRI_ERR,\n \"SipRedirectorISN::LookUp cannot parse NAPTR regexp field '%s' \"\n \"for ISN translation of '%s'\",\n p, requestString.data());\n }\n }\n else\n {\n OsSysLog::add(FAC_SIP, PRI_WARNING,\n \"SipRedirectorISN::LookUp No usable NAPTR found for '%s'\"\n \"for ISN translation of '%s'\",\n domain, requestString.data());\n } \n }\n else\n {\n OsSysLog::add(FAC_SIP, PRI_WARNING,\n \"SipRedirectorISN::LookUp no NAPTR record found for domain '%s' \"\n \"for ISN translation of '%s'\",\n domain, requestString.data());\n }\n \n \/\/ Free the result of res_parse if necessary.\n if (dns_response != NULL)\n {\n res_free(dns_response);\n }\n if (canonical_name != NULL && canonical_name != domain)\n {\n free((void*) canonical_name);\n }\n }\n\n return RedirectPlugin::LOOKUP_SUCCESS;\n}\n<commit_msg>Correct how the ITAD is applied to the NAPTR domain name when processing ISN numbers.<commit_after>\/\/ \n\/\/ \n\/\/ Copyright (C) 2005 SIPfoundry Inc.\n\/\/ Licensed by SIPfoundry under the LGPL license.\n\/\/ \n\/\/ Copyright (C) 2005 Pingtel Corp.\n\/\/ Licensed to SIPfoundry under a Contributor Agreement.\n\/\/ \n\/\/ $$\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/ SYSTEM INCLUDES\n#include <string.h>\n#include <sys\/types.h>\n#include <sys\/types.h>\n#include <regex.h>\n\n\/\/ APPLICATION INCLUDES\n#include \"os\/OsSysLog.h\"\n#include \"os\/OsDefs.h\"\n#include \"SipRedirectorISN.h\"\n#include \"net\/SipSrvLookup.h\"\n#include \"net\/Url.h\"\n\n#if defined(_WIN32)\n# include \"resparse\/wnt\/sysdep.h\"\n# include <resparse\/wnt\/netinet\/in.h>\n# include <resparse\/wnt\/arpa\/nameser.h>\n# include <resparse\/wnt\/resolv\/resolv.h>\n# include <winsock.h>\nextern \"C\" {\n# include \"resparse\/wnt\/inet_aton.h\" \n}\n#elif defined(_VXWORKS)\n# include <stdio.h>\n# include <netdb.h>\n# include <netinet\/in.h>\n# include <vxWorks.h>\n\/* Use local lnameser.h for info missing from VxWorks version --GAT *\/\n\/* lnameser.h is a subset of resparse\/wnt\/arpa\/nameser.h *\/\n# include <resolv\/nameser.h>\n# include <resparse\/vxw\/arpa\/lnameser.h>\n\/* Use local lresolv.h for info missing from VxWorks version --GAT *\/\n\/* lresolv.h is a subset of resparse\/wnt\/resolv\/resolv.h *\/\n# include <resolv\/resolv.h>\n# include <resparse\/vxw\/resolv\/lresolv.h>\n\/* #include <sys\/socket.h> used sockLib.h instead --GAT *\/\n# include <sockLib.h>\n# include <resolvLib.h>\n# include <resparse\/vxw\/hd_string.h>\n#elif defined(__pingtel_on_posix__)\n# include <arpa\/inet.h>\n# include <netinet\/in.h>\n# include <sys\/socket.h>\n# include <resolv.h>\n# include <netdb.h>\n#else\n# error Unsupported target platform.\n#endif\n\n#ifndef __pingtel_on_posix__\nextern struct __res_state _sip_res;\n#endif\n\n#include \"resparse\/rr.h\"\n\n\/\/ The space allocated for returns from res_query.\n#define DNS_RESPONSE_SIZE 4096\n\n\/\/ DEFINES\n\/\/ MACROS\n\/\/ EXTERNAL FUNCTIONS\n\/\/ EXTERNAL VARIABLES\n\/\/ CONSTANTS\n\/\/ STRUCTS\n\/\/ TYPEDEFS\n\/\/ FORWARD DECLARATIONS\n\n\/\/ Static factory function.\nextern \"C\" RedirectPlugin* getRedirectPlugin(const UtlString& instanceName)\n{\n return new SipRedirectorISN(instanceName);\n}\n\n\/\/ Constructor\nSipRedirectorISN::SipRedirectorISN(const UtlString& instanceName) :\n RedirectPlugin(instanceName)\n{\n}\n\n\/\/ Destructor\nSipRedirectorISN::~SipRedirectorISN()\n{\n}\n\n\/\/ Read config information.\nvoid SipRedirectorISN::readConfig(OsConfigDb& configDb)\n{\n if (configDb.get(\"BASE_DOMAIN\", mBaseDomain) != OS_SUCCESS ||\n mBaseDomain.isNull())\n {\n OsSysLog::add(FAC_SIP, PRI_CRIT,\n \"SipRedirectorISN::readConfig \"\n \"BASE_DOMAIN parameter missing or empty\");\n }\n else\n {\n OsSysLog::add(FAC_SIP, PRI_INFO,\n \"SipRedirectorISN::readConfig \"\n \"BASE_DOMAIN is '%s'\", mBaseDomain.data());\n }\n\n if (configDb.get(\"PREFIX\", mPrefix) != OS_SUCCESS ||\n mPrefix.isNull())\n {\n OsSysLog::add(FAC_SIP, PRI_INFO,\n \"SipRedirectorISN::readConfig \"\n \"dialing prefix is empty\");\n }\n else\n {\n OsSysLog::add(FAC_SIP, PRI_INFO,\n \"SipRedirectorISN::readConfig \"\n \"dialing prefix is '%s'\", mPrefix.data());\n }\n}\n\n\/\/ Initializer\nOsStatus\nSipRedirectorISN::initialize(OsConfigDb& configDb,\n SipUserAgent* pSipUserAgent,\n int redirectorNo,\n const UtlString& localDomainHost)\n{\n return mBaseDomain.isNull() ? OS_FAILED : OS_SUCCESS;\n}\n\n\/\/ Finalizer\nvoid\nSipRedirectorISN::finalize()\n{\n}\n\nRedirectPlugin::LookUpStatus\nSipRedirectorISN::lookUp(\n const SipMessage& message,\n const UtlString& requestString,\n const Url& requestUri,\n const UtlString& method,\n SipMessage& response,\n RequestSeqNo requestSeqNo,\n int redirectorNo,\n SipRedirectorPrivateStorage*& privateStorage)\n{\n bool status = false;\n\n \/\/ Get the user part.\n UtlString userId;\n requestUri.getUserId(userId);\n\n \/\/ Test if the user part is in the right format -- prefix followed by digits*digits\n const char* user = userId.data();\n int prefix_length = mPrefix.length();\n \/\/ Compare the prefix.\n int i; \/\/ Length of the extension part.\n if (strncmp(user, mPrefix.data(), prefix_length) == 0)\n {\n \/\/ Effectively delete the prefix from the user part.\n user += prefix_length;\n \/\/ Check the syntax of the remainder of the user.\n i = strspn(user, \"0123456789\");\n int j = 0;\n if (i > 0)\n {\n if (user[i] == '*')\n {\n j = strspn(user + i + 1, \"0123456789\");\n if (user[i + 1 + j] == '\\0')\n {\n status = true;\n }\n }\n }\n }\n\n if (status)\n {\n \/\/ Format of user part is correct. Look for NAPTR records.\n\n \/\/ Create the domain to look up.\n char domain[2 * strlen(user) + mBaseDomain.length()];\n {\n char* p = &domain[0];\n \/\/ Copy the extension, reversing it and following each digit with a period.\n for (int k = i; --k >= 0; )\n {\n *p++ = user[k];\n *p++ = '.';\n }\n \/\/ Append the ITAD and a period.\n strcpy(p, user + i + 1);\n strcat(p, \".\");\n \/\/ Append the ITAD root domain.\n strcat(p, mBaseDomain.data());\n }\n OsSysLog::add(FAC_SIP, PRI_DEBUG,\n \"SipRedirectorISN::lookUp user '%s' has ISN format, domain is '%s'\",\n user, domain);\n\n \/\/ To hold the return of res_query_and_parse.\n res_response* dns_response;\n const char* canonical_name;\n \n \/\/ Make the query and parse the response.\n SipSrvLookup::res_query_and_parse(domain, T_NAPTR, NULL, canonical_name, dns_response);\n\n if (dns_response != NULL)\n {\n \/\/ Search the list of RRs for the 'best' answer.\n \/\/ Initialize to values at least 2**16.\n int lowest_order_seen = 1 << 16, lowest_preference_seen = 1 << 16;\n int best_response = -1; \/\/ No response found..\n \/\/ Search the answer list.\n for (unsigned int i = 0; i < dns_response->header.ancount; i++)\n {\n if (dns_response->answer[i]->rclass == C_IN &&\n dns_response->answer[i]->type == T_NAPTR &&\n \/\/ Note we look for the canonical name now.\n strcasecmp(canonical_name, dns_response->answer[i]->name) == 0)\n {\n \/\/ A NAPTR record has been found.\n OsSysLog::add(FAC_SIP, PRI_DEBUG,\n \"SipRedirectorISN::LookUp \"\n \"NAPTR record found '%s' %d %d %d %d '%s' '%s' '%s' '%s'\",\n dns_response->answer[i]->name,\n dns_response->answer[i]->rclass,\n dns_response->answer[i]->type,\n dns_response->answer[i]->rdata.naptr.order,\n dns_response->answer[i]->rdata.naptr.preference,\n dns_response->answer[i]->rdata.naptr.flags,\n dns_response->answer[i]->rdata.naptr.services,\n dns_response->answer[i]->rdata.naptr.regexp,\n dns_response->answer[i]->rdata.naptr.replacement);\n \/\/ Accept the record if flags are 'u' and services are 'E2U+sip'.\n \/\/ Note that the value 'E2U+sip' is defined by RFC 3764\n \/\/ (SIP enumservice) not RFC 2915 (the original NAPTR RFC).\n if (strcasecmp(dns_response->answer[i]->rdata.naptr.flags, \"u\") == 0 &&\n strcasecmp(dns_response->answer[i]->rdata.naptr.services, \"E2U+sip\") == 0)\n {\n \/\/ Check that it has the lowest order and preference values seen so far.\n if (dns_response->answer[i]->rdata.naptr.order < lowest_order_seen ||\n (dns_response->answer[i]->rdata.naptr.order == lowest_order_seen &&\n dns_response->answer[i]->rdata.naptr.preference < lowest_preference_seen))\n {\n best_response = i;\n lowest_order_seen = dns_response->answer[i]->rdata.naptr.order;\n lowest_preference_seen = dns_response->answer[i]->rdata.naptr.preference;\n }\n }\n }\n }\n\n \/\/ At this point, best_response (if any) is the response we chose.\n if (best_response != -1)\n {\n char* p = dns_response->answer[best_response]->rdata.naptr.regexp;\n OsSysLog::add(FAC_SIP, PRI_DEBUG,\n \"SipRedirectorISN::LookUp Using NAPTR rewrite '%s' for '%s'\",\n p, domain);\n \/\/ Enough space for the 'match' part of the regexp field.\n char match[strlen(p) + 1];\n \/\/ Pointer to the 'replace' part of the regexp field.\n char delim;\n const char* replace;\n int i_flag;\n if (res_naptr_split_regexp(p, &delim, match, &replace, &i_flag))\n {\n OsSysLog::add(FAC_SIP, PRI_DEBUG,\n \"SipRedirectorISN::LookUp match = '%s', replace = '%s', i_flag = %d\",\n match, replace, i_flag);\n \/\/ Split operation was successful. Try to match.\n regex_t reg;\n int ret = regcomp(®, match, REG_EXTENDED | (i_flag ? REG_ICASE : 0));\n if (ret == 0)\n {\n \/\/ NAPTR matches can have only 9 substitutions.\n regmatch_t pmatch[9];\n \/\/ regexec returns 0 for success.\n \/\/ Though RFC 3761 and the ISN Cookbook don't say, it appears\n \/\/ that the regexp is matched against the user-part of the SIP URI.\n if (regexec(®, user, 9, pmatch, 0) == 0)\n {\n \/\/ Match was successful. Construct the replacement string.\n \/\/ Current usage is that the replacement string is the resulting URI,\n \/\/ not the replacement into the original application-string.\n char* result = res_naptr_replace(replace, delim, pmatch, user, 0);\n OsSysLog::add(FAC_SIP, PRI_DEBUG,\n \"SipRedirectorISN::LookUp result = '%s'\",\n result);\n \/\/ Note that the replacement string is not\n \/\/ substituted back into the original string, but used\n \/\/ alone as the destination URI.\n \/\/ Parse result string into URI.\n Url contact(result, TRUE);\n \/\/ Almost all strings are parsable as SIP URIs with a sufficient\n \/\/ number of components missing. Be we can check that a scheme\n \/\/ was identified, and that a host name was found.\n \/\/ (A string with sufficiently few punctuation characters appears to\n \/\/ be a sip: URI with the scheme missing and only a host name, but\n \/\/ the legal character set for host names is fairly narrow.)\n UtlString h;\n contact.getHostAddress(h);\n if (contact.getScheme() != Url::UnknownUrlScheme && !h.isNull())\n {\n RedirectPlugin::addContact(response, requestString,\n contact, \"ISN\");\n\n }\n else\n {\n OsSysLog::add(FAC_SIP, PRI_ERR,\n \"SipRedirectorISN::LookUp Bad result string '%s' - \"\n \"could not identify URI scheme and\/or host name is null - \"\n \"for ISN translation of '%s'\",\n result, requestString.data());\n }\n \/\/ Free the result string.\n free(result);\n }\n else\n {\n OsSysLog::add(FAC_SIP, PRI_WARNING,\n \"SipRedirectorISN::LookUp NAPTR regexp '%s' does not match \"\n \"for ISN translation of '%s' - no contact generated\",\n match, requestString.data());\n }\n \/\/ Free the parsed regexp structure.\n regfree(®);\n }\n else\n {\n OsSysLog::add(FAC_SIP, PRI_WARNING,\n \"SipRedirectorISN::LookUp NAPTR regexp '%s' is syntactially invalid \"\n \"for ISN translation of '%s'\",\n match, requestString.data());\n }\n }\n else\n {\n OsSysLog::add(FAC_SIP, PRI_ERR,\n \"SipRedirectorISN::LookUp cannot parse NAPTR regexp field '%s' \"\n \"for ISN translation of '%s'\",\n p, requestString.data());\n }\n }\n else\n {\n OsSysLog::add(FAC_SIP, PRI_WARNING,\n \"SipRedirectorISN::LookUp No usable NAPTR found for '%s'\"\n \"for ISN translation of '%s'\",\n domain, requestString.data());\n } \n }\n else\n {\n OsSysLog::add(FAC_SIP, PRI_WARNING,\n \"SipRedirectorISN::LookUp no NAPTR record found for domain '%s' \"\n \"for ISN translation of '%s'\",\n domain, requestString.data());\n }\n \n \/\/ Free the result of res_parse if necessary.\n if (dns_response != NULL)\n {\n res_free(dns_response);\n }\n if (canonical_name != NULL && canonical_name != domain)\n {\n free((void*) canonical_name);\n }\n }\n\n return RedirectPlugin::LOOKUP_SUCCESS;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ File Monodomain.cpp\n\/\/\n\/\/ For more information, please see: http:\/\/www.nektar.info\n\/\/\n\/\/ The MIT License\n\/\/\n\/\/ Copyright (c) 2006 Division of Applied Mathematics, Brown University (USA),\n\/\/ Department of Aeronautics, Imperial College London (UK), and Scientific\n\/\/ Computing and Imaging Institute, University of Utah (USA).\n\/\/\n\/\/ License for the specific language governing rights and limitations under\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a\n\/\/ copy of this software and associated documentation files (the \"Software\"),\n\/\/ to deal in the Software without restriction, including without limitation\n\/\/ the rights to use, copy, modify, merge, publish, distribute, sublicense,\n\/\/ and\/or sell copies of the Software, and to permit persons to whom the\n\/\/ Software is furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included\n\/\/ in all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n\/\/ OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n\/\/ THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n\/\/ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n\/\/ DEALINGS IN THE SOFTWARE.\n\/\/\n\/\/ Description: Monodomain cardiac electrophysiology homogenised model.\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include <iostream>\n\n#include <CardiacEPSolver\/EquationSystems\/Monodomain.h>\n\nnamespace Nektar\n{\n \/**\n * @class Monodomain\n *\n * Base model of cardiac electrophysiology of the form\n * \\f{align*}{\n * \\frac{\\partial u}{\\partial t} = \\nabla^2 u + J_{ion},\n * \\f}\n * where the reaction term, \\f$J_{ion}\\f$ is defined by a specific cell\n * model.\n *\n * This implementation, at present, treats the reaction terms explicitly\n * and the diffusive element implicitly.\n *\/\n\n \/**\n * Registers the class with the Factory.\n *\/\n string Monodomain::className\n = GetEquationSystemFactory().RegisterCreatorFunction(\n \"Monodomain\",\n Monodomain::create,\n \"Monodomain model of cardiac electrophysiology.\");\n\n\n \/**\n *\n *\/\n Monodomain::Monodomain(\n const LibUtilities::SessionReaderSharedPtr& pSession)\n : UnsteadySystem(pSession)\n {\n }\n\n void Monodomain::v_InitObject()\n {\n UnsteadySystem::v_InitObject();\n\n m_session->LoadParameter(\"Chi\", m_chi);\n m_session->LoadParameter(\"Cm\", m_capMembrane);\n\n std::string vCellModel;\n m_session->LoadSolverInfo(\"CELLMODEL\", vCellModel, \"\");\n\n ASSERTL0(vCellModel != \"\", \"Cell Model not specified.\");\n\n m_cell = GetCellModelFactory().CreateInstance(vCellModel, m_session, m_fields[0]);\n\n m_intVariables.push_back(0);\n\n \/\/ Load variable coefficients\n StdRegions::VarCoeffType varCoeffEnum[3] = {\n StdRegions::eVarCoeffD00,\n StdRegions::eVarCoeffD11,\n StdRegions::eVarCoeffD22\n };\n std::string varName = \"intensity\";\n std::string varCoeffs[3] = {\n \"AnisotropicConductivityX\",\n \"AnisotropicConductivityY\",\n \"AnisotropicConductivityZ\"\n };\n\n Array<OneD, NekDouble> vTemp;\n if (m_session->DefinesFunction(\"IsotropicConductivity\"))\n {\n EvaluateFunction(varName, vTemp, \"IsotropicConductivity\");\n for (int i = 0; i < m_spacedim; ++i)\n {\n m_vardiff[varCoeffEnum[i]] = vTemp;\n }\n }\n else if (m_session->DefinesFunction(varCoeffs[0]))\n {\n for (int i = 0; i < m_spacedim; ++i)\n {\n ASSERTL0(m_session->DefinesFunction(varCoeffs[i], varName),\n \"Function '\" + varCoeffs[i] + \"' not correctly defined.\");\n EvaluateFunction(varName, vTemp, varCoeffs[i]);\n m_vardiff[varCoeffEnum[i]] = vTemp;\n }\n }\n\n for (int i = 0; i < m_spacedim; ++i)\n {\n if (m_session->DefinesParameter(\"d_min\"))\n {\n \/\/ Normalise and invert\n int nq = m_fields[0]->GetNpoints();\n NekDouble f_min = m_session->GetParameter(\"d_min\");\n NekDouble f_max = m_session->GetParameter(\"d_max\");\n NekDouble f_range = f_max - f_min;\n NekDouble o_min = m_session->GetParameter(\"o_min\");\n NekDouble o_max = m_session->GetParameter(\"o_max\");\n Vmath::Sadd(nq, -f_min, m_vardiff[varCoeffEnum[i]], 1, m_vardiff[varCoeffEnum[i]], 1);\n for (int j = 0; j < nq; ++j)\n {\n if (m_vardiff[varCoeffEnum[i]][j] < 0)\n {\n m_vardiff[varCoeffEnum[i]][j] = 0.0;\n }\n if (m_vardiff[varCoeffEnum[i]][j] > f_range)\n {\n m_vardiff[varCoeffEnum[i]][j] = f_range;\n }\n }\n Vmath::Smul(nq, -1.0\/f_range, m_vardiff[varCoeffEnum[i]], 1, m_vardiff[varCoeffEnum[i]], 1);\n Vmath::Sadd(nq, 1.0, m_vardiff[varCoeffEnum[i]], 1, m_vardiff[varCoeffEnum[i]], 1);\n Vmath::Smul(nq, o_max-o_min, m_vardiff[varCoeffEnum[i]], 1, m_vardiff[varCoeffEnum[i]], 1);\n Vmath::Sadd(nq, o_min, m_vardiff[varCoeffEnum[i]], 1, m_vardiff[varCoeffEnum[i]], 1);\n }\n\n m_fields[0]->FwdTrans_IterPerExp(m_vardiff[varCoeffEnum[i]],\n m_fields[0]->UpdateCoeffs());\n std::stringstream filename;\n filename << varCoeffs[i];\n if (m_comm->GetSize() > 1)\n {\n filename << \"_P\" << m_comm->GetRank();\n }\n filename << \".fld\";\n WriteFld(filename.str());\n\n }\n\n if (m_session->DefinesParameter(\"StimulusDuration\"))\n {\n ASSERTL0(m_session->DefinesFunction(\"Stimulus\", \"u\"),\n \"Stimulus function not defined.\");\n m_session->LoadParameter(\"StimulusDuration\", m_stimDuration);\n }\n else\n {\n m_stimDuration = 0;\n }\n\n if (!m_explicitDiffusion)\n {\n m_ode.DefineImplicitSolve (&Monodomain::DoImplicitSolve, this);\n }\n m_ode.DefineOdeRhs(&Monodomain::DoOdeRhs, this);\n }\n\n\n \/**\n *\n *\/\n Monodomain::~Monodomain()\n {\n\n }\n\n\n \/**\n * @param inarray Input array.\n * @param outarray Output array.\n * @param time Current simulation time.\n * @param lambda Timestep.\n *\/\n void Monodomain::DoImplicitSolve(\n const Array<OneD, const Array<OneD, NekDouble> >&inarray,\n Array<OneD, Array<OneD, NekDouble> >&outarray,\n const NekDouble time,\n const NekDouble lambda)\n {\n int nvariables = inarray.num_elements();\n int ncoeffs = inarray[0].num_elements();\n int nq = m_fields[0]->GetNpoints();\n StdRegions::ConstFactorMap factors;\n \/\/ lambda = \\Delta t\n factors[StdRegions::eFactorLambda] = 1.0\/lambda*m_chi*m_capMembrane;\n\n \/\/ We solve ( \\nabla^2 - HHlambda ) Y[i] = rhs [i]\n \/\/ inarray = input: \\hat{rhs} -> output: \\hat{Y}\n \/\/ outarray = output: nabla^2 \\hat{Y}\n \/\/ where \\hat = modal coeffs\n for (int i = 0; i < nvariables; ++i)\n {\n \/\/ Multiply 1.0\/timestep\n Vmath::Smul(nq, -factors[StdRegions::eFactorLambda], inarray[i], 1,\n m_fields[i]->UpdatePhys(), 1);\n\n \/\/ Solve a system of equations with Helmholtz solver and transform\n \/\/ back into physical space.\n m_fields[i]->HelmSolve(m_fields[i]->GetPhys(),\n m_fields[i]->UpdateCoeffs(), NullFlagList,\n factors, m_vardiff);\n\n m_fields[i]->BwdTrans( m_fields[i]->GetCoeffs(),\n m_fields[i]->UpdatePhys());\n m_fields[i]->SetPhysState(true);\n\n \/\/ Copy the solution vector (required as m_fields must be set).\n outarray[i] = m_fields[i]->GetPhys();\n }\n }\n\n\n void Monodomain::DoOdeRhs(\n const Array<OneD, const Array<OneD, NekDouble> >&inarray,\n Array<OneD, Array<OneD, NekDouble> >&outarray,\n const NekDouble time)\n {\n int nq = m_fields[0]->GetNpoints();\n int nvar = inarray.num_elements();\n\n m_cell->TimeIntegrate(inarray, outarray, time);\n\n if (m_stimDuration > 0 && time < m_stimDuration)\n {\n Array<OneD,NekDouble> x0(nq);\n Array<OneD,NekDouble> x1(nq);\n Array<OneD,NekDouble> x2(nq);\n Array<OneD,NekDouble> result(nq);\n\n \/\/ get the coordinates\n m_fields[0]->GetCoords(x0,x1,x2);\n\n LibUtilities::EquationSharedPtr ifunc\n = m_session->GetFunction(\"Stimulus\", \"u\");\n ifunc->Evaluate(x0,x1,x2,time, result);\n\n Vmath::Vadd(nq, outarray[0], 1, result, 1, outarray[0], 1);\n }\n Vmath::Smul(nq, 1.0\/m_capMembrane, outarray[0], 1, outarray[0], 1);\n }\n\n\n void Monodomain::v_SetInitialConditions(NekDouble initialtime,\n bool dumpInitialConditions)\n {\n EquationSystem::v_SetInitialConditions(initialtime, dumpInitialConditions);\n m_cell->Initialise();\n }\n\n\n \/**\n *\n *\/\n void Monodomain::v_PrintSummary(std::ostream &out)\n {\n UnsteadySystem::v_PrintSummary(out);\n if (m_session->DefinesFunction(\"d00\") &&\n m_session->GetFunctionType(\"d00\", \"intensity\") == LibUtilities::eFunctionTypeExpression)\n {\n out << \"\\tDiffusivity-x : \"\n << m_session->GetFunction(\"d00\", \"intensity\")->GetExpression()\n << endl;\n }\n if (m_session->DefinesFunction(\"d11\") &&\n m_session->GetFunctionType(\"d11\", \"intensity\") == LibUtilities::eFunctionTypeExpression)\n {\n out << \"\\tDiffusivity-x : \"\n << m_session->GetFunction(\"d11\", \"intensity\")->GetExpression()\n << endl;\n }\n if (m_session->DefinesFunction(\"d22\") &&\n m_session->GetFunctionType(\"d22\", \"intensity\") == LibUtilities::eFunctionTypeExpression)\n {\n out << \"\\tDiffusivity-x : \"\n << m_session->GetFunction(\"d22\", \"intensity\")->GetExpression()\n << endl;\n }\n m_cell->PrintSummary(out);\n }\n\n}\n<commit_msg>Added missing check when setting up variable coefficients.<commit_after>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ File Monodomain.cpp\n\/\/\n\/\/ For more information, please see: http:\/\/www.nektar.info\n\/\/\n\/\/ The MIT License\n\/\/\n\/\/ Copyright (c) 2006 Division of Applied Mathematics, Brown University (USA),\n\/\/ Department of Aeronautics, Imperial College London (UK), and Scientific\n\/\/ Computing and Imaging Institute, University of Utah (USA).\n\/\/\n\/\/ License for the specific language governing rights and limitations under\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a\n\/\/ copy of this software and associated documentation files (the \"Software\"),\n\/\/ to deal in the Software without restriction, including without limitation\n\/\/ the rights to use, copy, modify, merge, publish, distribute, sublicense,\n\/\/ and\/or sell copies of the Software, and to permit persons to whom the\n\/\/ Software is furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included\n\/\/ in all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n\/\/ OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n\/\/ THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n\/\/ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n\/\/ DEALINGS IN THE SOFTWARE.\n\/\/\n\/\/ Description: Monodomain cardiac electrophysiology homogenised model.\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include <iostream>\n\n#include <CardiacEPSolver\/EquationSystems\/Monodomain.h>\n\nnamespace Nektar\n{\n \/**\n * @class Monodomain\n *\n * Base model of cardiac electrophysiology of the form\n * \\f{align*}{\n * \\frac{\\partial u}{\\partial t} = \\nabla^2 u + J_{ion},\n * \\f}\n * where the reaction term, \\f$J_{ion}\\f$ is defined by a specific cell\n * model.\n *\n * This implementation, at present, treats the reaction terms explicitly\n * and the diffusive element implicitly.\n *\/\n\n \/**\n * Registers the class with the Factory.\n *\/\n string Monodomain::className\n = GetEquationSystemFactory().RegisterCreatorFunction(\n \"Monodomain\",\n Monodomain::create,\n \"Monodomain model of cardiac electrophysiology.\");\n\n\n \/**\n *\n *\/\n Monodomain::Monodomain(\n const LibUtilities::SessionReaderSharedPtr& pSession)\n : UnsteadySystem(pSession)\n {\n }\n\n void Monodomain::v_InitObject()\n {\n UnsteadySystem::v_InitObject();\n\n m_session->LoadParameter(\"Chi\", m_chi);\n m_session->LoadParameter(\"Cm\", m_capMembrane);\n\n std::string vCellModel;\n m_session->LoadSolverInfo(\"CELLMODEL\", vCellModel, \"\");\n\n ASSERTL0(vCellModel != \"\", \"Cell Model not specified.\");\n\n m_cell = GetCellModelFactory().CreateInstance(vCellModel, m_session, m_fields[0]);\n\n m_intVariables.push_back(0);\n\n \/\/ Load variable coefficients\n StdRegions::VarCoeffType varCoeffEnum[3] = {\n StdRegions::eVarCoeffD00,\n StdRegions::eVarCoeffD11,\n StdRegions::eVarCoeffD22\n };\n std::string varName = \"intensity\";\n std::string varCoeffs[3] = {\n \"AnisotropicConductivityX\",\n \"AnisotropicConductivityY\",\n \"AnisotropicConductivityZ\"\n };\n\n Array<OneD, NekDouble> vTemp;\n if (m_session->DefinesFunction(\"IsotropicConductivity\"))\n {\n EvaluateFunction(varName, vTemp, \"IsotropicConductivity\");\n for (int i = 0; i < m_spacedim; ++i)\n {\n m_vardiff[varCoeffEnum[i]] = vTemp;\n }\n }\n else if (m_session->DefinesFunction(varCoeffs[0]))\n {\n for (int i = 0; i < m_spacedim; ++i)\n {\n ASSERTL0(m_session->DefinesFunction(varCoeffs[i], varName),\n \"Function '\" + varCoeffs[i] + \"' not correctly defined.\");\n EvaluateFunction(varName, vTemp, varCoeffs[i]);\n m_vardiff[varCoeffEnum[i]] = vTemp;\n }\n }\n\n if (!m_vardiff.empty())\n {\n \/\/ Process each of the defined variable coefficients\n for (int i = 0; i < m_spacedim; ++i)\n {\n \/\/ If scaling parameters defined, do scaling\n if (m_session->DefinesParameter(\"d_min\"))\n {\n \/\/ Normalise and invert\n int nq = m_fields[0]->GetNpoints();\n NekDouble f_min = m_session->GetParameter(\"d_min\");\n NekDouble f_max = m_session->GetParameter(\"d_max\");\n NekDouble f_range = f_max - f_min;\n NekDouble o_min = m_session->GetParameter(\"o_min\");\n NekDouble o_max = m_session->GetParameter(\"o_max\");\n Vmath::Sadd(nq, -f_min, m_vardiff[varCoeffEnum[i]], 1, m_vardiff[varCoeffEnum[i]], 1);\n for (int j = 0; j < nq; ++j)\n {\n if (m_vardiff[varCoeffEnum[i]][j] < 0)\n {\n m_vardiff[varCoeffEnum[i]][j] = 0.0;\n }\n if (m_vardiff[varCoeffEnum[i]][j] > f_range)\n {\n m_vardiff[varCoeffEnum[i]][j] = f_range;\n }\n }\n Vmath::Smul(nq, -1.0\/f_range, m_vardiff[varCoeffEnum[i]], 1, m_vardiff[varCoeffEnum[i]], 1);\n Vmath::Sadd(nq, 1.0, m_vardiff[varCoeffEnum[i]], 1, m_vardiff[varCoeffEnum[i]], 1);\n Vmath::Smul(nq, o_max-o_min, m_vardiff[varCoeffEnum[i]], 1, m_vardiff[varCoeffEnum[i]], 1);\n Vmath::Sadd(nq, o_min, m_vardiff[varCoeffEnum[i]], 1, m_vardiff[varCoeffEnum[i]], 1);\n }\n\n \/\/ Transform variable coefficient and write out to file.\n m_fields[0]->FwdTrans_IterPerExp(m_vardiff[varCoeffEnum[i]],\n m_fields[0]->UpdateCoeffs());\n std::stringstream filename;\n filename << varCoeffs[i];\n if (m_comm->GetSize() > 1)\n {\n filename << \"_P\" << m_comm->GetRank();\n }\n filename << \".fld\";\n WriteFld(filename.str());\n }\n }\n\n if (m_session->DefinesParameter(\"StimulusDuration\"))\n {\n ASSERTL0(m_session->DefinesFunction(\"Stimulus\", \"u\"),\n \"Stimulus function not defined.\");\n m_session->LoadParameter(\"StimulusDuration\", m_stimDuration);\n }\n else\n {\n m_stimDuration = 0;\n }\n\n if (!m_explicitDiffusion)\n {\n m_ode.DefineImplicitSolve (&Monodomain::DoImplicitSolve, this);\n }\n m_ode.DefineOdeRhs(&Monodomain::DoOdeRhs, this);\n }\n\n\n \/**\n *\n *\/\n Monodomain::~Monodomain()\n {\n\n }\n\n\n \/**\n * @param inarray Input array.\n * @param outarray Output array.\n * @param time Current simulation time.\n * @param lambda Timestep.\n *\/\n void Monodomain::DoImplicitSolve(\n const Array<OneD, const Array<OneD, NekDouble> >&inarray,\n Array<OneD, Array<OneD, NekDouble> >&outarray,\n const NekDouble time,\n const NekDouble lambda)\n {\n int nvariables = inarray.num_elements();\n int ncoeffs = inarray[0].num_elements();\n int nq = m_fields[0]->GetNpoints();\n StdRegions::ConstFactorMap factors;\n \/\/ lambda = \\Delta t\n factors[StdRegions::eFactorLambda] = 1.0\/lambda*m_chi*m_capMembrane;\n\n \/\/ We solve ( \\nabla^2 - HHlambda ) Y[i] = rhs [i]\n \/\/ inarray = input: \\hat{rhs} -> output: \\hat{Y}\n \/\/ outarray = output: nabla^2 \\hat{Y}\n \/\/ where \\hat = modal coeffs\n for (int i = 0; i < nvariables; ++i)\n {\n \/\/ Multiply 1.0\/timestep\n Vmath::Smul(nq, -factors[StdRegions::eFactorLambda], inarray[i], 1,\n m_fields[i]->UpdatePhys(), 1);\n\n \/\/ Solve a system of equations with Helmholtz solver and transform\n \/\/ back into physical space.\n m_fields[i]->HelmSolve(m_fields[i]->GetPhys(),\n m_fields[i]->UpdateCoeffs(), NullFlagList,\n factors, m_vardiff);\n\n m_fields[i]->BwdTrans( m_fields[i]->GetCoeffs(),\n m_fields[i]->UpdatePhys());\n m_fields[i]->SetPhysState(true);\n\n \/\/ Copy the solution vector (required as m_fields must be set).\n outarray[i] = m_fields[i]->GetPhys();\n }\n }\n\n\n void Monodomain::DoOdeRhs(\n const Array<OneD, const Array<OneD, NekDouble> >&inarray,\n Array<OneD, Array<OneD, NekDouble> >&outarray,\n const NekDouble time)\n {\n int nq = m_fields[0]->GetNpoints();\n int nvar = inarray.num_elements();\n\n m_cell->TimeIntegrate(inarray, outarray, time);\n\n if (m_stimDuration > 0 && time < m_stimDuration)\n {\n Array<OneD,NekDouble> x0(nq);\n Array<OneD,NekDouble> x1(nq);\n Array<OneD,NekDouble> x2(nq);\n Array<OneD,NekDouble> result(nq);\n\n \/\/ get the coordinates\n m_fields[0]->GetCoords(x0,x1,x2);\n\n LibUtilities::EquationSharedPtr ifunc\n = m_session->GetFunction(\"Stimulus\", \"u\");\n ifunc->Evaluate(x0,x1,x2,time, result);\n\n Vmath::Vadd(nq, outarray[0], 1, result, 1, outarray[0], 1);\n }\n Vmath::Smul(nq, 1.0\/m_capMembrane, outarray[0], 1, outarray[0], 1);\n }\n\n\n void Monodomain::v_SetInitialConditions(NekDouble initialtime,\n bool dumpInitialConditions)\n {\n EquationSystem::v_SetInitialConditions(initialtime, dumpInitialConditions);\n m_cell->Initialise();\n }\n\n\n \/**\n *\n *\/\n void Monodomain::v_PrintSummary(std::ostream &out)\n {\n UnsteadySystem::v_PrintSummary(out);\n if (m_session->DefinesFunction(\"d00\") &&\n m_session->GetFunctionType(\"d00\", \"intensity\") == LibUtilities::eFunctionTypeExpression)\n {\n out << \"\\tDiffusivity-x : \"\n << m_session->GetFunction(\"d00\", \"intensity\")->GetExpression()\n << endl;\n }\n if (m_session->DefinesFunction(\"d11\") &&\n m_session->GetFunctionType(\"d11\", \"intensity\") == LibUtilities::eFunctionTypeExpression)\n {\n out << \"\\tDiffusivity-x : \"\n << m_session->GetFunction(\"d11\", \"intensity\")->GetExpression()\n << endl;\n }\n if (m_session->DefinesFunction(\"d22\") &&\n m_session->GetFunctionType(\"d22\", \"intensity\") == LibUtilities::eFunctionTypeExpression)\n {\n out << \"\\tDiffusivity-x : \"\n << m_session->GetFunction(\"d22\", \"intensity\")->GetExpression()\n << endl;\n }\n m_cell->PrintSummary(out);\n }\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ File Monodomain.cpp\n\/\/\n\/\/ For more information, please see: http:\/\/www.nektar.info\n\/\/\n\/\/ The MIT License\n\/\/\n\/\/ Copyright (c) 2006 Division of Applied Mathematics, Brown University (USA),\n\/\/ Department of Aeronautics, Imperial College London (UK), and Scientific\n\/\/ Computing and Imaging Institute, University of Utah (USA).\n\/\/\n\/\/ License for the specific language governing rights and limitations under\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a\n\/\/ copy of this software and associated documentation files (the \"Software\"),\n\/\/ to deal in the Software without restriction, including without limitation\n\/\/ the rights to use, copy, modify, merge, publish, distribute, sublicense,\n\/\/ and\/or sell copies of the Software, and to permit persons to whom the\n\/\/ Software is furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included\n\/\/ in all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n\/\/ OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n\/\/ THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n\/\/ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n\/\/ DEALINGS IN THE SOFTWARE.\n\/\/\n\/\/ Description: Monodomain cardiac electrophysiology homogenised model.\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include <iostream>\n\n#include <CardiacEPSolver\/EquationSystems\/Monodomain.h>\n#include <CardiacEPSolver\/Filters\/FilterCheckpointCellModel.h>\n\nnamespace Nektar\n{\n \/**\n * @class Monodomain\n *\n * Base model of cardiac electrophysiology of the form\n * \\f{align*}{\n * \\frac{\\partial u}{\\partial t} = \\nabla^2 u + J_{ion},\n * \\f}\n * where the reaction term, \\f$J_{ion}\\f$ is defined by a specific cell\n * model.\n *\n * This implementation, at present, treats the reaction terms explicitly\n * and the diffusive element implicitly.\n *\/\n\n \/**\n * Registers the class with the Factory.\n *\/\n string Monodomain::className\n = GetEquationSystemFactory().RegisterCreatorFunction(\n \"Monodomain\",\n Monodomain::create,\n \"Monodomain model of cardiac electrophysiology.\");\n\n\n \/**\n *\n *\/\n Monodomain::Monodomain(\n const LibUtilities::SessionReaderSharedPtr& pSession)\n : UnsteadySystem(pSession)\n {\n }\n\n\n \/**\n *\n *\/\n void Monodomain::v_InitObject()\n {\n UnsteadySystem::v_InitObject();\n\n m_session->LoadParameter(\"Chi\", m_chi);\n m_session->LoadParameter(\"Cm\", m_capMembrane);\n\n std::string vCellModel;\n m_session->LoadSolverInfo(\"CELLMODEL\", vCellModel, \"\");\n\n ASSERTL0(vCellModel != \"\", \"Cell Model not specified.\");\n\n m_cell = GetCellModelFactory().CreateInstance(\n vCellModel, m_session, m_fields[0]);\n\n m_intVariables.push_back(0);\n\n \/\/ Load variable coefficients\n StdRegions::VarCoeffType varCoeffEnum[6] = {\n StdRegions::eVarCoeffD00,\n StdRegions::eVarCoeffD01,\n StdRegions::eVarCoeffD11,\n StdRegions::eVarCoeffD02,\n StdRegions::eVarCoeffD12,\n StdRegions::eVarCoeffD22\n };\n std::string varName = \"intensity\";\n std::string aniso_var[3] = {\n \"fx\", \"fy\", \"fz\"\n };\n int nq = m_fields[0]->GetNpoints();\n Array<OneD, NekDouble> vTemp;\n Array<OneD, NekDouble> vTemp_i;\n Array<OneD, NekDouble> vTemp_j;\n\n \/\/ Allocate storage for variable coeffs and initialize to 1.\n for (int i = 0; i < m_spacedim*(m_spacedim+1)\/2; ++i)\n {\n m_vardiff[varCoeffEnum[i]] = Array<OneD, NekDouble>(nq, 1.0);\n }\n\n \/\/ Apply fibre map f \\in [0,1], scale to conductivity range\n \/\/ [o_min,o_max], specified by the session parameters o_min and o_max\n if (m_session->DefinesFunction(\"AnisotropicConductivity\"))\n {\n if (m_session->DefinesCmdLineArgument(\"verbose\"))\n {\n cout << \"Loading Anisotropic Fibre map.\" << endl;\n }\n\n NekDouble o_min = m_session->GetParameter(\"o_min\");\n NekDouble o_max = m_session->GetParameter(\"o_max\");\n\n int k = 0;\n\n \/*\n * Diffusivity matrix is upper triangular and defined as\n * d_00 d_01 d_02\n * d_11 d_12\n * d_22\n *\n * Given a principle fibre direction _f_ the diffusivity is given\n * by\n * d_ij = { D_2 + (D_1 - D_2) f_i f_j if i==j\n * { (D_1 - D_2) f_i f_j if i!=j\n *\n * The vector _f_ is given in terms of the variables fx,fy,fz in the\n * function AnisotropicConductivity. The values of D_1 and D_2 are\n * the parameters o_max and o_min, respectively.\n *\/\n\n \/\/ Loop through columns of D\n for (int j = 0; j < m_spacedim; ++j)\n {\n ASSERTL0(m_session->DefinesFunction(\"AnisotropicConductivity\",\n aniso_var[j]),\n \"Function 'AnisotropicConductivity' not correctly \"\n \"defined.\");\n EvaluateFunction(aniso_var[j], vTemp_j,\n \"AnisotropicConductivity\");\n\n \/\/ Loop through rows of D\n for (int i = 0; i < j + 1; ++i)\n {\n ASSERTL0(m_session->DefinesFunction(\"AnisotropicConductivity\",\n aniso_var[i]),\n \"Function 'AnisotropicConductivity' not correctly \"\n \"defined.\");\n EvaluateFunction(aniso_var[i], vTemp_i,\n \"AnisotropicConductivity\");\n\n Vmath::Vmul(nq, vTemp_i, 1, vTemp_j, 1,\n m_vardiff[varCoeffEnum[k]], 1);\n\n Vmath::Smul(nq, o_max-o_min,\n m_vardiff[varCoeffEnum[k]], 1,\n m_vardiff[varCoeffEnum[k]], 1);\n\n if (i == j)\n {\n Vmath::Sadd(nq, o_min, m_vardiff[varCoeffEnum[k]], 1,\n m_vardiff[varCoeffEnum[k]], 1);\n }\n\n ++k;\n }\n }\n }\n\n \/\/ Scale by scar map (range 0->1) derived from intensity map\n \/\/ (range d_min -> d_max)\n if (m_session->DefinesFunction(\"IsotropicConductivity\"))\n {\n if (m_session->DefinesCmdLineArgument(\"verbose\"))\n {\n cout << \"Loading Isotropic Conductivity map.\" << endl;\n }\n\n NekDouble f_min = m_session->GetParameter(\"d_min\");\n NekDouble f_max = m_session->GetParameter(\"d_max\");\n\n EvaluateFunction(varName, vTemp, \"IsotropicConductivity\");\n\n \/\/ Threshold based on d_min, d_max\n for (int j = 0; j < nq; ++j)\n {\n vTemp[j] = (vTemp[j] < f_min ? f_min : vTemp[j]);\n vTemp[j] = (vTemp[j] > f_max ? f_max : vTemp[j]);\n }\n\n \/\/ Rescale to s \\in [0,1] (0 maps to d_max, 1 maps to d_min)\n Vmath::Sadd(nq, -f_min, vTemp, 1, vTemp, 1);\n Vmath::Smul(nq, -1.0\/(f_max-f_min), vTemp, 1, vTemp, 1);\n Vmath::Sadd(nq, 1.0, vTemp, 1, vTemp, 1);\n\n \/\/ Scale anisotropic conductivity values\n for (int i = 0; i < m_spacedim; ++i)\n {\n Vmath::Vmul(nq, vTemp, 1,\n m_vardiff[varCoeffEnum[i]], 1,\n m_vardiff[varCoeffEnum[i]], 1);\n }\n }\n\n\n \/\/ Write out conductivity values\n for (int i = 0; i < m_spacedim; ++i)\n {\n \/\/ Transform variable coefficient and write out to file.\n m_fields[0]->FwdTrans_IterPerExp(m_vardiff[varCoeffEnum[i]],\n m_fields[0]->UpdateCoeffs());\n std::stringstream filename;\n filename << \"Conductivity_\" << aniso_var[i];\n if (m_comm->GetSize() > 1)\n {\n filename << \"_P\" << m_comm->GetRank();\n }\n filename << \".fld\";\n WriteFld(filename.str());\n }\n\n \/\/ Search through the loaded filters and pass the cell model to any\n \/\/ CheckpointCellModel filters loaded.\n int k = 0;\n const LibUtilities::FilterMap& f = m_session->GetFilters();\n LibUtilities::FilterMap::const_iterator x;\n for (x = f.begin(); x != f.end(); ++x, ++k)\n {\n if (x->first == \"CheckpointCellModel\")\n {\n boost::shared_ptr<FilterCheckpointCellModel> c\n = boost::dynamic_pointer_cast<FilterCheckpointCellModel>(\n m_filters[k]);\n c->SetCellModel(m_cell);\n }\n }\n\n \/\/ Load stimuli\n m_stimulus = Stimulus::LoadStimuli(m_session, m_fields[0]);\n\n if (!m_explicitDiffusion)\n {\n m_ode.DefineImplicitSolve (&Monodomain::DoImplicitSolve, this);\n }\n m_ode.DefineOdeRhs(&Monodomain::DoOdeRhs, this);\n }\n\n\n \/**\n *\n *\/\n Monodomain::~Monodomain()\n {\n\n }\n\n\n \/**\n * @param inarray Input array.\n * @param outarray Output array.\n * @param time Current simulation time.\n * @param lambda Timestep.\n *\/\n void Monodomain::DoImplicitSolve(\n const Array<OneD, const Array<OneD, NekDouble> >&inarray,\n Array<OneD, Array<OneD, NekDouble> >&outarray,\n const NekDouble time,\n const NekDouble lambda)\n {\n int nvariables = inarray.num_elements();\n int nq = m_fields[0]->GetNpoints();\n StdRegions::ConstFactorMap factors;\n \/\/ lambda = \\Delta t\n factors[StdRegions::eFactorLambda] = 1.0\/lambda*m_chi*m_capMembrane;\n\n \/\/ We solve ( \\nabla^2 - HHlambda ) Y[i] = rhs [i]\n \/\/ inarray = input: \\hat{rhs} -> output: \\hat{Y}\n \/\/ outarray = output: nabla^2 \\hat{Y}\n \/\/ where \\hat = modal coeffs\n for (int i = 0; i < nvariables; ++i)\n {\n \/\/ Multiply 1.0\/timestep\n Vmath::Smul(nq, -factors[StdRegions::eFactorLambda], inarray[i], 1,\n m_fields[i]->UpdatePhys(), 1);\n\n \/\/ Solve a system of equations with Helmholtz solver and transform\n \/\/ back into physical space.\n m_fields[i]->HelmSolve(m_fields[i]->GetPhys(),\n m_fields[i]->UpdateCoeffs(), NullFlagList,\n factors, m_vardiff);\n\n m_fields[i]->BwdTrans( m_fields[i]->GetCoeffs(),\n m_fields[i]->UpdatePhys());\n m_fields[i]->SetPhysState(true);\n\n \/\/ Copy the solution vector (required as m_fields must be set).\n outarray[i] = m_fields[i]->GetPhys();\n }\n }\n\n\n \/**\n *\n *\/\n void Monodomain::DoOdeRhs(\n const Array<OneD, const Array<OneD, NekDouble> >&inarray,\n Array<OneD, Array<OneD, NekDouble> >&outarray,\n const NekDouble time)\n {\n \/\/ Compute I_ion\n m_cell->TimeIntegrate(inarray, outarray, time);\n\n \/\/ Compute I_stim\n for (unsigned int i = 0; i < m_stimulus.size(); ++i)\n { \n m_stimulus[i]->Update(outarray, time);\n }\n }\n\n\n \/**\n *\n *\/\n void Monodomain::v_SetInitialConditions(NekDouble initialtime,\n bool dumpInitialConditions)\n {\n EquationSystem::v_SetInitialConditions(initialtime,\n dumpInitialConditions);\n m_cell->Initialise();\n }\n\n\n \/**\n *\n *\/\n void Monodomain::v_PrintSummary(std::ostream &out)\n {\n UnsteadySystem::v_PrintSummary(out);\n if (m_session->DefinesFunction(\"d00\") &&\n m_session->GetFunctionType(\"d00\", \"intensity\") \n == LibUtilities::eFunctionTypeExpression)\n {\n out << \"\\tDiffusivity-x : \"\n << m_session->GetFunction(\"d00\", \"intensity\")->GetExpression()\n << endl;\n }\n if (m_session->DefinesFunction(\"d11\") &&\n m_session->GetFunctionType(\"d11\", \"intensity\") \n == LibUtilities::eFunctionTypeExpression)\n {\n out << \"\\tDiffusivity-x : \"\n << m_session->GetFunction(\"d11\", \"intensity\")->GetExpression()\n << endl;\n }\n if (m_session->DefinesFunction(\"d22\") &&\n m_session->GetFunctionType(\"d22\", \"intensity\") \n == LibUtilities::eFunctionTypeExpression)\n {\n out << \"\\tDiffusivity-x : \"\n << m_session->GetFunction(\"d22\", \"intensity\")->GetExpression()\n << endl;\n }\n m_cell->PrintSummary(out);\n }\n}\n<commit_msg>Tidy up code.<commit_after>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ File Monodomain.cpp\n\/\/\n\/\/ For more information, please see: http:\/\/www.nektar.info\n\/\/\n\/\/ The MIT License\n\/\/\n\/\/ Copyright (c) 2006 Division of Applied Mathematics, Brown University (USA),\n\/\/ Department of Aeronautics, Imperial College London (UK), and Scientific\n\/\/ Computing and Imaging Institute, University of Utah (USA).\n\/\/\n\/\/ License for the specific language governing rights and limitations under\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a\n\/\/ copy of this software and associated documentation files (the \"Software\"),\n\/\/ to deal in the Software without restriction, including without limitation\n\/\/ the rights to use, copy, modify, merge, publish, distribute, sublicense,\n\/\/ and\/or sell copies of the Software, and to permit persons to whom the\n\/\/ Software is furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included\n\/\/ in all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n\/\/ OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n\/\/ THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n\/\/ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n\/\/ DEALINGS IN THE SOFTWARE.\n\/\/\n\/\/ Description: Monodomain cardiac electrophysiology homogenised model.\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include <iostream>\n\n#include <CardiacEPSolver\/EquationSystems\/Monodomain.h>\n#include <CardiacEPSolver\/Filters\/FilterCheckpointCellModel.h>\n\nnamespace Nektar\n{\n \/**\n * @class Monodomain\n *\n * Base model of cardiac electrophysiology of the form\n * \\f{align*}{\n * \\frac{\\partial u}{\\partial t} = \\nabla^2 u + J_{ion},\n * \\f}\n * where the reaction term, \\f$J_{ion}\\f$ is defined by a specific cell\n * model.\n *\n * This implementation, at present, treats the reaction terms explicitly\n * and the diffusive element implicitly.\n *\/\n\n \/**\n * Registers the class with the Factory.\n *\/\n string Monodomain::className\n = GetEquationSystemFactory().RegisterCreatorFunction(\n \"Monodomain\",\n Monodomain::create,\n \"Monodomain model of cardiac electrophysiology.\");\n\n\n \/**\n *\n *\/\n Monodomain::Monodomain(\n const LibUtilities::SessionReaderSharedPtr& pSession)\n : UnsteadySystem(pSession)\n {\n }\n\n\n \/**\n *\n *\/\n void Monodomain::v_InitObject()\n {\n UnsteadySystem::v_InitObject();\n\n m_session->LoadParameter(\"Chi\", m_chi);\n m_session->LoadParameter(\"Cm\", m_capMembrane);\n\n std::string vCellModel;\n m_session->LoadSolverInfo(\"CELLMODEL\", vCellModel, \"\");\n\n ASSERTL0(vCellModel != \"\", \"Cell Model not specified.\");\n\n m_cell = GetCellModelFactory().CreateInstance(\n vCellModel, m_session, m_fields[0]);\n\n m_intVariables.push_back(0);\n\n \/\/ Load variable coefficients\n StdRegions::VarCoeffType varCoeffEnum[6] = {\n StdRegions::eVarCoeffD00,\n StdRegions::eVarCoeffD01,\n StdRegions::eVarCoeffD11,\n StdRegions::eVarCoeffD02,\n StdRegions::eVarCoeffD12,\n StdRegions::eVarCoeffD22\n };\n\n const int nq = m_fields[0]->GetNpoints();\n const int nVarDiffCmpts = m_spacedim * (m_spacedim + 1) \/ 2;\n\n \/\/ Allocate storage for variable coeffs and initialize to 1.\n for (int i = 0; i < nVarDiffCmpts; ++i)\n {\n m_vardiff[varCoeffEnum[i]] = Array<OneD, NekDouble>(nq, 1.0);\n }\n\n \/\/ Apply fibre map f \\in [0,1], scale to conductivity range\n \/\/ [o_min,o_max], specified by the session parameters o_min and o_max\n if (m_session->DefinesFunction(\"AnisotropicConductivity\"))\n {\n if (m_session->DefinesCmdLineArgument(\"verbose\"))\n {\n cout << \"Loading Anisotropic Fibre map.\" << endl;\n }\n\n std::string aniso_var[3] = {\"fx\", \"fy\", \"fz\"};\n NekDouble o_min = m_session->GetParameter(\"o_min\");\n NekDouble o_max = m_session->GetParameter(\"o_max\");\n int k = 0;\n\n Array<OneD, NekDouble> vTemp_i;\n Array<OneD, NekDouble> vTemp_j;\n\n \/*\n * Diffusivity matrix D is upper triangular and defined as\n * d_00 d_01 d_02\n * d_11 d_12\n * d_22\n *\n * Given a principle fibre direction _f_ the diffusivity is given\n * by\n * d_ij = { D_2 + (D_1 - D_2) f_i f_j if i==j\n * { (D_1 - D_2) f_i f_j if i!=j\n *\n * The vector _f_ is given in terms of the variables fx,fy,fz in the\n * function AnisotropicConductivity. The values of D_1 and D_2 are\n * the parameters o_max and o_min, respectively.\n *\/\n\n \/\/ Loop through columns of D\n for (int j = 0; j < m_spacedim; ++j)\n {\n ASSERTL0(m_session->DefinesFunction(\"AnisotropicConductivity\",\n aniso_var[j]),\n \"Function 'AnisotropicConductivity' not correctly \"\n \"defined.\");\n EvaluateFunction(aniso_var[j], vTemp_j,\n \"AnisotropicConductivity\");\n\n \/\/ Loop through rows of D\n for (int i = 0; i < j + 1; ++i)\n {\n ASSERTL0(m_session->DefinesFunction(\n \"AnisotropicConductivity\",aniso_var[i]),\n \"Function 'AnisotropicConductivity' not correctly \"\n \"defined.\");\n EvaluateFunction(aniso_var[i], vTemp_i,\n \"AnisotropicConductivity\");\n\n Vmath::Vmul(nq, vTemp_i, 1, vTemp_j, 1,\n m_vardiff[varCoeffEnum[k]], 1);\n\n Vmath::Smul(nq, o_max-o_min,\n m_vardiff[varCoeffEnum[k]], 1,\n m_vardiff[varCoeffEnum[k]], 1);\n\n if (i == j)\n {\n Vmath::Sadd(nq, o_min,\n m_vardiff[varCoeffEnum[k]], 1,\n m_vardiff[varCoeffEnum[k]], 1);\n }\n\n ++k;\n }\n }\n }\n\n \/\/ Scale by scar map (range 0->1) derived from intensity map\n \/\/ (range d_min -> d_max)\n if (m_session->DefinesFunction(\"IsotropicConductivity\"))\n {\n if (m_session->DefinesCmdLineArgument(\"verbose\"))\n {\n cout << \"Loading Isotropic Conductivity map.\" << endl;\n }\n\n std::string varName = \"intensity\";\n NekDouble f_min = m_session->GetParameter(\"d_min\");\n NekDouble f_max = m_session->GetParameter(\"d_max\");\n\n Array<OneD, NekDouble> vTemp;\n EvaluateFunction(varName, vTemp, \"IsotropicConductivity\");\n\n \/\/ Threshold based on d_min, d_max\n for (int j = 0; j < nq; ++j)\n {\n vTemp[j] = (vTemp[j] < f_min ? f_min : vTemp[j]);\n vTemp[j] = (vTemp[j] > f_max ? f_max : vTemp[j]);\n }\n\n \/\/ Rescale to s \\in [0,1] (0 maps to d_max, 1 maps to d_min)\n Vmath::Sadd(nq, -f_min, vTemp, 1, vTemp, 1);\n Vmath::Smul(nq, -1.0\/(f_max-f_min), vTemp, 1, vTemp, 1);\n Vmath::Sadd(nq, 1.0, vTemp, 1, vTemp, 1);\n\n \/\/ Scale anisotropic conductivity values\n for (int i = 0; i < m_spacedim; ++i)\n {\n Vmath::Vmul(nq, vTemp, 1,\n m_vardiff[varCoeffEnum[i]], 1,\n m_vardiff[varCoeffEnum[i]], 1);\n }\n }\n\n\n \/\/ Write out conductivity values\n for (int i = 0; i < m_spacedim; ++i)\n {\n \/\/ Transform variable coefficient and write out to file.\n m_fields[0]->FwdTrans_IterPerExp(m_vardiff[varCoeffEnum[i]],\n m_fields[0]->UpdateCoeffs());\n std::stringstream filename;\n filename << \"Conductivity_\" << aniso_var[i];\n if (m_comm->GetSize() > 1)\n {\n filename << \"_P\" << m_comm->GetRank();\n }\n filename << \".fld\";\n WriteFld(filename.str());\n }\n\n \/\/ Search through the loaded filters and pass the cell model to any\n \/\/ CheckpointCellModel filters loaded.\n int k = 0;\n const LibUtilities::FilterMap& f = m_session->GetFilters();\n LibUtilities::FilterMap::const_iterator x;\n for (x = f.begin(); x != f.end(); ++x, ++k)\n {\n if (x->first == \"CheckpointCellModel\")\n {\n boost::shared_ptr<FilterCheckpointCellModel> c\n = boost::dynamic_pointer_cast<FilterCheckpointCellModel>(\n m_filters[k]);\n c->SetCellModel(m_cell);\n }\n }\n\n \/\/ Load stimuli\n m_stimulus = Stimulus::LoadStimuli(m_session, m_fields[0]);\n\n if (!m_explicitDiffusion)\n {\n m_ode.DefineImplicitSolve (&Monodomain::DoImplicitSolve, this);\n }\n m_ode.DefineOdeRhs(&Monodomain::DoOdeRhs, this);\n }\n\n\n \/**\n *\n *\/\n Monodomain::~Monodomain()\n {\n\n }\n\n\n \/**\n * @param inarray Input array.\n * @param outarray Output array.\n * @param time Current simulation time.\n * @param lambda Timestep.\n *\/\n void Monodomain::DoImplicitSolve(\n const Array<OneD, const Array<OneD, NekDouble> >&inarray,\n Array<OneD, Array<OneD, NekDouble> >&outarray,\n const NekDouble time,\n const NekDouble lambda)\n {\n int nvariables = inarray.num_elements();\n int nq = m_fields[0]->GetNpoints();\n StdRegions::ConstFactorMap factors;\n \/\/ lambda = \\Delta t\n factors[StdRegions::eFactorLambda] = 1.0\/lambda*m_chi*m_capMembrane;\n\n \/\/ We solve ( \\nabla^2 - HHlambda ) Y[i] = rhs [i]\n \/\/ inarray = input: \\hat{rhs} -> output: \\hat{Y}\n \/\/ outarray = output: nabla^2 \\hat{Y}\n \/\/ where \\hat = modal coeffs\n for (int i = 0; i < nvariables; ++i)\n {\n \/\/ Multiply 1.0\/timestep\n Vmath::Smul(nq, -factors[StdRegions::eFactorLambda], inarray[i], 1,\n m_fields[i]->UpdatePhys(), 1);\n\n \/\/ Solve a system of equations with Helmholtz solver and transform\n \/\/ back into physical space.\n m_fields[i]->HelmSolve(m_fields[i]->GetPhys(),\n m_fields[i]->UpdateCoeffs(), NullFlagList,\n factors, m_vardiff);\n\n m_fields[i]->BwdTrans( m_fields[i]->GetCoeffs(),\n m_fields[i]->UpdatePhys());\n m_fields[i]->SetPhysState(true);\n\n \/\/ Copy the solution vector (required as m_fields must be set).\n outarray[i] = m_fields[i]->GetPhys();\n }\n }\n\n\n \/**\n *\n *\/\n void Monodomain::DoOdeRhs(\n const Array<OneD, const Array<OneD, NekDouble> >&inarray,\n Array<OneD, Array<OneD, NekDouble> >&outarray,\n const NekDouble time)\n {\n \/\/ Compute I_ion\n m_cell->TimeIntegrate(inarray, outarray, time);\n\n \/\/ Compute I_stim\n for (unsigned int i = 0; i < m_stimulus.size(); ++i)\n { \n m_stimulus[i]->Update(outarray, time);\n }\n }\n\n\n \/**\n *\n *\/\n void Monodomain::v_SetInitialConditions(NekDouble initialtime,\n bool dumpInitialConditions)\n {\n EquationSystem::v_SetInitialConditions(initialtime,\n dumpInitialConditions);\n m_cell->Initialise();\n }\n\n\n \/**\n *\n *\/\n void Monodomain::v_PrintSummary(std::ostream &out)\n {\n UnsteadySystem::v_PrintSummary(out);\n if (m_session->DefinesFunction(\"d00\") &&\n m_session->GetFunctionType(\"d00\", \"intensity\") \n == LibUtilities::eFunctionTypeExpression)\n {\n out << \"\\tDiffusivity-x : \"\n << m_session->GetFunction(\"d00\", \"intensity\")->GetExpression()\n << endl;\n }\n if (m_session->DefinesFunction(\"d11\") &&\n m_session->GetFunctionType(\"d11\", \"intensity\") \n == LibUtilities::eFunctionTypeExpression)\n {\n out << \"\\tDiffusivity-x : \"\n << m_session->GetFunction(\"d11\", \"intensity\")->GetExpression()\n << endl;\n }\n if (m_session->DefinesFunction(\"d22\") &&\n m_session->GetFunctionType(\"d22\", \"intensity\") \n == LibUtilities::eFunctionTypeExpression)\n {\n out << \"\\tDiffusivity-x : \"\n << m_session->GetFunction(\"d22\", \"intensity\")->GetExpression()\n << endl;\n }\n m_cell->PrintSummary(out);\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (C) 2010-2013 Joshua Boyce.\r\n\/\/ See the file COPYING for copying permission.\r\n\r\n#include <hadesmem\/find_pattern.hpp>\r\n\r\n#define BOOST_TEST_MODULE find_pattern\r\n#include <hadesmem\/detail\/warning_disable_prefix.hpp>\r\n#include <boost\/test\/unit_test.hpp>\r\n#include <hadesmem\/detail\/warning_disable_suffix.hpp>\r\n\r\n#include <hadesmem\/error.hpp>\r\n#include <hadesmem\/config.hpp>\r\n#include <hadesmem\/process.hpp>\r\n#include <hadesmem\/detail\/initialize.hpp>\r\n\r\n\/\/ Boost.Test causes the following warning under GCC:\r\n\/\/ error: base class 'struct boost::unit_test::ut_detail::nil_t' has a \r\n\/\/ non-virtual destructor [-Werror=effc++]\r\n#if defined(HADESMEM_GCC)\r\n#pragma GCC diagnostic ignored \"-Weffc++\"\r\n#endif \/\/ #if defined(HADESMEM_GCC)\r\n\r\n\/\/ Boost.Test causes the following warning under Clang:\r\n\/\/ error: declaration requires a global constructor \r\n\/\/ [-Werror,-Wglobal-constructors]\r\n#if defined(HADESMEM_CLANG)\r\n#pragma GCC diagnostic ignored \"-Wglobal-constructors\"\r\n#endif \/\/ #if defined(HADESMEM_CLANG)\r\n\r\n\/\/ TODO: Clean up, expand, fix, etc these tests.\r\n\/\/ TODO: Add more tests (e.g. stream overload tests).\r\n\r\nBOOST_AUTO_TEST_CASE(initialize)\r\n{\r\n hadesmem::detail::InitializeAll();\r\n}\r\n\r\n\/\/ Using an underscore to avoid a variable shadowing waring under Clang \r\n\/\/ and GCC.\r\n\/\/ TODO: Fix this.\r\nBOOST_AUTO_TEST_CASE(find_pattern_)\r\n{\r\n hadesmem::Process const process(::GetCurrentProcessId());\r\n\r\n HMODULE const self = GetModuleHandle(nullptr);\r\n BOOST_REQUIRE(self != nullptr);\r\n\r\n hadesmem::FindPattern find_pattern(process, self);\r\n\r\n \/\/ Create pattern scanner targetting self (using default constructor this \r\n \/\/ time)\r\n find_pattern = hadesmem::FindPattern(process, nullptr);\r\n \/\/ Ensure constructor throws if an invalid module handle is specified\r\n \/\/ TODO: Fix this.\r\n \/\/BOOST_CHECK_THROW(find_pattern = hadesmem::FindPattern(process, \r\n \/\/ reinterpret_cast<HMODULE>(-1)), hadesmem::Error);\r\n\r\n \/\/ Scan for predicatable byte mask\r\n auto const nop = find_pattern.Find(L\"90\", \r\n hadesmem::FindPatternFlags::kNone);\r\n \/\/ Ensure pattern was found\r\n BOOST_CHECK(nop != nullptr);\r\n \/\/ Ensure pattern address is valid\r\n BOOST_CHECK_GT(nop, self);\r\n \/\/ Scan again for same pattern, this time specifying a name\r\n find_pattern.Find(L\"90\", L\"Nop\", hadesmem::FindPatternFlags::kNone);\r\n \/\/ Ensure pattern is found, is added to the named map, and is equal to \r\n \/\/ the previously found instance\r\n BOOST_CHECK_EQUAL(nop, find_pattern[L\"Nop\"]);\r\n \/\/ Ensure named map is the expected size\r\n BOOST_CHECK_EQUAL(find_pattern.GetAddresses().size(), 1UL);\r\n \/\/ Scan again for same pattern, this time specifying the relative address \r\n \/\/ flag\r\n auto const nop_rel = find_pattern.Find(L\"90\",\r\n hadesmem::FindPatternFlags::kRelativeAddress);\r\n \/\/ Ensure the relative address is correct\r\n BOOST_CHECK_EQUAL(static_cast<PBYTE>(nop_rel)+\r\n reinterpret_cast<DWORD_PTR>(self), nop);\r\n \/\/ Test stream-based pattern scanner by scanning for the same pattern, \r\n \/\/ with a different name\r\n hadesmem::Pattern nop_pattern(find_pattern, L\"90\", L\"NopPlus1\",\r\n hadesmem::FindPatternFlags::kNone);\r\n \/\/ Apply 'Add' manipulator to pattern and save back to parent\r\n nop_pattern << hadesmem::pattern_manipulators::Add(1) <<\r\n hadesmem::pattern_manipulators::Save();\r\n \/\/ Ensure manipulator was correctly applied\r\n BOOST_CHECK_EQUAL(nop_pattern.GetAddress(), static_cast<PBYTE>(nop)+1);\r\n \/\/ Ensure pattern result was saved back to parent\r\n BOOST_CHECK_EQUAL(nop_pattern.GetAddress(), find_pattern[L\"NopPlus1\"]);\r\n \/\/ Ensure named map is the expected size\r\n BOOST_CHECK_EQUAL(find_pattern.GetAddresses().size(), 2UL);\r\n\r\n \/\/ Scan for predictable byte mask (including wildcard)\r\n auto const zeros = find_pattern.Find(L\"00 ?? 00\",\r\n hadesmem::FindPatternFlags::kNone);\r\n \/\/ Ensure pattern was found\r\n BOOST_CHECK(zeros != nullptr);\r\n \/\/ Ensure pattern address is valid\r\n BOOST_CHECK_GT(zeros, GetModuleHandle(nullptr));\r\n \/\/ Scan again for same pattern, this time specifying a name\r\n find_pattern.Find(L\"00 ?? 00\", L\"Zeros\",\r\n hadesmem::FindPatternFlags::kNone);\r\n \/\/ Ensure pattern is found, is added to the named map, and is equal to \r\n \/\/ the previously found instance\r\n BOOST_CHECK_EQUAL(zeros, find_pattern[L\"Zeros\"]);\r\n \/\/ Ensure named map is the expected size\r\n BOOST_CHECK_EQUAL(find_pattern.GetAddresses().size(), 3UL);\r\n \/\/ Ensure this pattern (00 ?? 00) does not match the earlier pattern (90) \r\n BOOST_CHECK(nop != zeros);\r\n \/\/ Scan again for same pattern, this time specifying the relative address \r\n \/\/ flag\r\n auto const zeros_rel = find_pattern.Find(L\"00 ?? 00\",\r\n hadesmem::FindPatternFlags::kRelativeAddress);\r\n \/\/ Ensure the relative address is correct\r\n BOOST_CHECK_EQUAL(static_cast<PBYTE>(zeros_rel)+\r\n reinterpret_cast<DWORD_PTR>(self), zeros);\r\n \/\/ Test stream-based pattern scanner by scanning for the same pattern, \r\n \/\/ with a different name \r\n hadesmem::Pattern zeros_pattern(find_pattern, L\"00 ?? 00\", \r\n L\"ZerosMinus1\", hadesmem::FindPatternFlags::kNone);\r\n \/\/ Apply 'Sub' manipulator to pattern and save back to parent\r\n zeros_pattern << hadesmem::pattern_manipulators::Sub(1) <<\r\n hadesmem::pattern_manipulators::Save();\r\n \/\/ Ensure manipulator was correctly applied\r\n BOOST_CHECK_EQUAL(static_cast<PVOID>(zeros_pattern.GetAddress()), \r\n static_cast<PVOID>(static_cast<PBYTE>(zeros)-1));\r\n \/\/ Ensure pattern result was saved back to parent\r\n BOOST_CHECK_EQUAL(zeros_pattern.GetAddress(), \r\n find_pattern[L\"ZerosMinus1\"]);\r\n \/\/ Ensure named map is the expected size\r\n BOOST_CHECK_EQUAL(find_pattern.GetAddresses().size(), 4UL);\r\n\r\n \/\/ Test stream-based pattern scanner by scanning for an instruction with \r\n \/\/ a known relative operand. We should ensure that we're not going to hit \r\n \/\/ this particular byte accidently as part of the operand of another \r\n \/\/ instruction, but for now lets just ignore that possibility. The test \r\n \/\/ will (or should) fail in that case.\r\n hadesmem::Pattern call_pattern(find_pattern, L\"E8\",\r\n hadesmem::FindPatternFlags::kRelativeAddress);\r\n \/\/ Ensure pattern was found\r\n BOOST_CHECK(call_pattern.GetAddress() != nullptr);\r\n \/\/ The instruction is a 'Call' instruction, so add one byte to move \r\n \/\/ past the instruction, then perform a relative dereference using the \r\n \/\/ instruction size and operand offset (5 and 1 respectively in this \r\n \/\/ case, for a 32-bit relative call).\r\n call_pattern << hadesmem::pattern_manipulators::Add(1) <<\r\n hadesmem::pattern_manipulators::Rel(5, 1);\r\n \/\/ Ensure pattern was found\r\n BOOST_CHECK(call_pattern.GetAddress() != nullptr);\r\n\r\n \/\/ Todo: pattern_manipulators::Lea test\r\n\r\n \/\/ Test pattern file, including scan flags, pattern matching, and \r\n \/\/ optional manipulators. Use the same patterns we have been using \r\n \/\/ already so we can check their validity.\r\n std::wstring const pattern_file_data =\r\n LR\"(\r\n<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<HadesMem>\r\n <FindPattern>\r\n <Flag Name=\"RelativeAddress\"><\/Flag>\r\n <Flag Name=\"ThrowOnUnmatch\"><\/Flag>\r\n <Pattern Name=\"First Call\" Data=\"E8\">\r\n <Manipulator Name=\"Add\" Operand1=\"1\"><\/Manipulator>\r\n <Manipulator Name=\"Rel\" Operand1=\"5\" Operand2=\"1\"><\/Manipulator>\r\n <\/Pattern>\r\n <Pattern Name=\"Zeros New\" Data=\"00 ?? 00\">\r\n <Manipulator Name=\"Add\" Operand1=\"1\"><\/Manipulator>\r\n <Manipulator Name=\"Sub\" Operand1=\"1\"><\/Manipulator>\r\n <\/Pattern>\r\n <Pattern Name=\"Nop Other\" Data=\"90\"><\/Pattern>\r\n <\/FindPattern>\r\n<\/HadesMem>\r\n)\";\r\n find_pattern.LoadFileMemory(pattern_file_data);\r\n \/\/ Ensure all patterns match previous scans\r\n BOOST_CHECK_EQUAL(find_pattern.Lookup(L\"First Call\"), \r\n call_pattern.GetAddress());\r\n BOOST_CHECK_EQUAL(find_pattern.Lookup(L\"First Call\"), \r\n find_pattern[L\"First Call\"]);\r\n BOOST_CHECK_EQUAL(find_pattern.Lookup(L\"Zeros New\"), \r\n zeros_rel);\r\n BOOST_CHECK_EQUAL(find_pattern.Lookup(L\"Zeros New\"), \r\n find_pattern[L\"Zeros New\"]);\r\n BOOST_CHECK_EQUAL(find_pattern.Lookup(L\"Nop Other\"), \r\n nop_rel);\r\n BOOST_CHECK_EQUAL(find_pattern.Lookup(L\"Nop Other\"), \r\n find_pattern[L\"Nop Other\"]);\r\n\r\n \/\/ Test pattern file, using various types of invalid input.\r\n std::wstring const pattern_file_data_invalid1 =\r\n LR\"(\r\n<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<HadesMem>\r\n <FindPattern>\r\n <Flag>InvalidFlag<\/Flag>\r\n <\/FindPattern>\r\n<\/HadesMem>\r\n)\";\r\n BOOST_CHECK_THROW(find_pattern.LoadFileMemory(\r\n pattern_file_data_invalid1), \r\n hadesmem::Error);\r\n std::wstring const pattern_file_data_invalid2 =\r\n LR\"(\r\n<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<HadesMem>\r\n <FindPattern>\r\n <Flag>RelativeAddress<\/Flag>\r\n <Flag>ThrowOnUnmatch<\/Flag>\r\n <Manipulator Name=\"Add\" Operand1=\"1\"><\/Manipulator>\r\n <\/FindPattern>\r\n<\/HadesMem>\r\n)\";\r\n BOOST_CHECK_THROW(find_pattern.LoadFileMemory(\r\n pattern_file_data_invalid2), \r\n hadesmem::Error);\r\n std::wstring const pattern_file_data_invalid3 =\r\n LR\"(\r\n<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<HadesMem>\r\n <FindPattern>\r\n <Flag>RelativeAddress<\/Flag>\r\n <Flag>ThrowOnUnmatch<\/Flag>\r\n <Pattern Name=\"Foo\" Data=\"ZZ\"><\/Pattern>\r\n <\/FindPattern>\r\n<\/HadesMem>\r\n)\";\r\n BOOST_CHECK_THROW(find_pattern.LoadFileMemory(\r\n pattern_file_data_invalid3), \r\n hadesmem::Error);\r\n std::wstring const pattern_file_data_invalid4 =\r\n LR\"(\r\n<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<HadesMem>\r\n <FindPattern>\r\n <Flag>RelativeAddress<\/Flag>\r\n <Flag>ThrowOnUnmatch<\/Flag>\r\n <Pattern><\/Pattern>\r\n <\/FindPattern>\r\n<\/HadesMem>\r\n)\";\r\n BOOST_CHECK_THROW(find_pattern.LoadFileMemory(\r\n pattern_file_data_invalid4),\r\n hadesmem::Error);\r\n\r\n \/\/ Todo: LoadFile test\r\n\r\n \/\/ Perform a full wildcard scan twice and ensure that both scans return \r\n \/\/ the same address\r\n auto const nops_any = find_pattern.Find(L\"?? ?? ?? ?? ??\",\r\n hadesmem::FindPatternFlags::kNone);\r\n auto const int3s_any = find_pattern.Find(L\"?? ?? ?? ?? ??\",\r\n hadesmem::FindPatternFlags::kNone);\r\n BOOST_CHECK_EQUAL(nops_any, int3s_any);\r\n \/\/ Ensure address is valid\r\n BOOST_CHECK_GT(nops_any, GetModuleHandle(nullptr));\r\n \/\/ Perform scan again with relative address flag\r\n auto const nops_any_rel = find_pattern.Find(L\"?? ?? ?? ?? ??\",\r\n hadesmem::FindPatternFlags::kRelativeAddress);\r\n \/\/ Ensure address is valid\r\n BOOST_CHECK_EQUAL(static_cast<PBYTE>(nops_any_rel)+\r\n reinterpret_cast<DWORD_PTR>(self), nops_any);\r\n\r\n \/\/ Check ThrowOnUnmatch flag\r\n BOOST_CHECK_THROW(find_pattern.Find(L\"AA BB CC DD EE FF 11 22 33 44 55 \"\r\n L\"66 77 88 99 00 11 33 33 77\", \r\n hadesmem::FindPatternFlags::kThrowOnUnmatch),\r\n hadesmem::Error);\r\n\r\n \/\/ Check ScanData flag\r\n \/\/ Note: Pattern is for narrow string 'FindPattern' (without quotes)\r\n auto const find_pattern_str = find_pattern.Find(L\"46 69 6E 64 50 61 74 \"\r\n L\"65 72 6E\", hadesmem::FindPatternFlags::kScanData);\r\n BOOST_CHECK(find_pattern_str != nullptr);\r\n\r\n \/\/ Check conversion failures throw\r\n BOOST_CHECK_THROW(find_pattern.Find(L\"ZZ\",\r\n hadesmem::FindPatternFlags::kNone), hadesmem::Error);\r\n\r\n \/\/ Check conversion failures throw\r\n \/\/ Code changes now mean this causes an assert.\r\n \/\/BOOST_CHECK_THROW(find_pattern.Find(L\"\", \r\n \/\/ hadesmem::FindPatternFlags::kNone), hadesmem::Error);\r\n}\r\n<commit_msg>* [FindPattern] Fix test.<commit_after>\/\/ Copyright (C) 2010-2013 Joshua Boyce.\r\n\/\/ See the file COPYING for copying permission.\r\n\r\n#include <hadesmem\/find_pattern.hpp>\r\n\r\n#define BOOST_TEST_MODULE find_pattern\r\n#include <hadesmem\/detail\/warning_disable_prefix.hpp>\r\n#include <boost\/test\/unit_test.hpp>\r\n#include <hadesmem\/detail\/warning_disable_suffix.hpp>\r\n\r\n#include <hadesmem\/error.hpp>\r\n#include <hadesmem\/config.hpp>\r\n#include <hadesmem\/process.hpp>\r\n#include <hadesmem\/detail\/initialize.hpp>\r\n\r\n\/\/ Boost.Test causes the following warning under GCC:\r\n\/\/ error: base class 'struct boost::unit_test::ut_detail::nil_t' has a \r\n\/\/ non-virtual destructor [-Werror=effc++]\r\n#if defined(HADESMEM_GCC)\r\n#pragma GCC diagnostic ignored \"-Weffc++\"\r\n#endif \/\/ #if defined(HADESMEM_GCC)\r\n\r\n\/\/ Boost.Test causes the following warning under Clang:\r\n\/\/ error: declaration requires a global constructor \r\n\/\/ [-Werror,-Wglobal-constructors]\r\n#if defined(HADESMEM_CLANG)\r\n#pragma GCC diagnostic ignored \"-Wglobal-constructors\"\r\n#endif \/\/ #if defined(HADESMEM_CLANG)\r\n\r\n\/\/ TODO: Clean up, expand, fix, etc these tests.\r\n\/\/ TODO: Add more tests (e.g. stream overload tests).\r\n\r\nBOOST_AUTO_TEST_CASE(initialize)\r\n{\r\n hadesmem::detail::InitializeAll();\r\n}\r\n\r\n\/\/ Using an underscore to avoid a variable shadowing waring under Clang \r\n\/\/ and GCC.\r\n\/\/ TODO: Fix this.\r\nBOOST_AUTO_TEST_CASE(find_pattern_)\r\n{\r\n hadesmem::Process const process(::GetCurrentProcessId());\r\n\r\n HMODULE const self = GetModuleHandle(nullptr);\r\n BOOST_REQUIRE(self != nullptr);\r\n\r\n hadesmem::FindPattern find_pattern(process, self);\r\n\r\n \/\/ Create pattern scanner targetting self (using default constructor this \r\n \/\/ time)\r\n find_pattern = hadesmem::FindPattern(process, nullptr);\r\n \/\/ Ensure constructor throws if an invalid module handle is specified\r\n \/\/ TODO: Fix this.\r\n \/\/BOOST_CHECK_THROW(find_pattern = hadesmem::FindPattern(process, \r\n \/\/ reinterpret_cast<HMODULE>(-1)), hadesmem::Error);\r\n\r\n \/\/ Scan for predicatable byte mask\r\n auto const nop = find_pattern.Find(L\"90\", \r\n hadesmem::FindPatternFlags::kNone);\r\n \/\/ Ensure pattern was found\r\n BOOST_CHECK(nop != nullptr);\r\n \/\/ Ensure pattern address is valid\r\n BOOST_CHECK_GT(nop, self);\r\n \/\/ Scan again for same pattern, this time specifying a name\r\n find_pattern.Find(L\"90\", L\"Nop\", hadesmem::FindPatternFlags::kNone);\r\n \/\/ Ensure pattern is found, is added to the named map, and is equal to \r\n \/\/ the previously found instance\r\n BOOST_CHECK_EQUAL(nop, find_pattern[L\"Nop\"]);\r\n \/\/ Ensure named map is the expected size\r\n BOOST_CHECK_EQUAL(find_pattern.GetAddresses().size(), 1UL);\r\n \/\/ Scan again for same pattern, this time specifying the relative address \r\n \/\/ flag\r\n auto const nop_rel = find_pattern.Find(L\"90\",\r\n hadesmem::FindPatternFlags::kRelativeAddress);\r\n \/\/ Ensure the relative address is correct\r\n BOOST_CHECK_EQUAL(static_cast<PBYTE>(nop_rel)+\r\n reinterpret_cast<DWORD_PTR>(self), nop);\r\n \/\/ Test stream-based pattern scanner by scanning for the same pattern, \r\n \/\/ with a different name\r\n hadesmem::Pattern nop_pattern(find_pattern, L\"90\", L\"NopPlus1\",\r\n hadesmem::FindPatternFlags::kNone);\r\n \/\/ Apply 'Add' manipulator to pattern and save back to parent\r\n nop_pattern << hadesmem::pattern_manipulators::Add(1) <<\r\n hadesmem::pattern_manipulators::Save();\r\n \/\/ Ensure manipulator was correctly applied\r\n BOOST_CHECK_EQUAL(nop_pattern.GetAddress(), static_cast<PBYTE>(nop)+1);\r\n \/\/ Ensure pattern result was saved back to parent\r\n BOOST_CHECK_EQUAL(nop_pattern.GetAddress(), find_pattern[L\"NopPlus1\"]);\r\n \/\/ Ensure named map is the expected size\r\n BOOST_CHECK_EQUAL(find_pattern.GetAddresses().size(), 2UL);\r\n\r\n \/\/ Scan for predictable byte mask (including wildcard)\r\n auto const zeros = find_pattern.Find(L\"00 ?? 00\",\r\n hadesmem::FindPatternFlags::kNone);\r\n \/\/ Ensure pattern was found\r\n BOOST_CHECK(zeros != nullptr);\r\n \/\/ Ensure pattern address is valid\r\n BOOST_CHECK_GT(zeros, GetModuleHandle(nullptr));\r\n \/\/ Scan again for same pattern, this time specifying a name\r\n find_pattern.Find(L\"00 ?? 00\", L\"Zeros\",\r\n hadesmem::FindPatternFlags::kNone);\r\n \/\/ Ensure pattern is found, is added to the named map, and is equal to \r\n \/\/ the previously found instance\r\n BOOST_CHECK_EQUAL(zeros, find_pattern[L\"Zeros\"]);\r\n \/\/ Ensure named map is the expected size\r\n BOOST_CHECK_EQUAL(find_pattern.GetAddresses().size(), 3UL);\r\n \/\/ Ensure this pattern (00 ?? 00) does not match the earlier pattern (90) \r\n BOOST_CHECK(nop != zeros);\r\n \/\/ Scan again for same pattern, this time specifying the relative address \r\n \/\/ flag\r\n auto const zeros_rel = find_pattern.Find(L\"00 ?? 00\",\r\n hadesmem::FindPatternFlags::kRelativeAddress);\r\n \/\/ Ensure the relative address is correct\r\n BOOST_CHECK_EQUAL(static_cast<PBYTE>(zeros_rel)+\r\n reinterpret_cast<DWORD_PTR>(self), zeros);\r\n \/\/ Test stream-based pattern scanner by scanning for the same pattern, \r\n \/\/ with a different name \r\n hadesmem::Pattern zeros_pattern(find_pattern, L\"00 ?? 00\", \r\n L\"ZerosMinus1\", hadesmem::FindPatternFlags::kNone);\r\n \/\/ Apply 'Sub' manipulator to pattern and save back to parent\r\n zeros_pattern << hadesmem::pattern_manipulators::Sub(1) <<\r\n hadesmem::pattern_manipulators::Save();\r\n \/\/ Ensure manipulator was correctly applied\r\n BOOST_CHECK_EQUAL(static_cast<PVOID>(zeros_pattern.GetAddress()), \r\n static_cast<PVOID>(static_cast<PBYTE>(zeros)-1));\r\n \/\/ Ensure pattern result was saved back to parent\r\n BOOST_CHECK_EQUAL(zeros_pattern.GetAddress(), \r\n find_pattern[L\"ZerosMinus1\"]);\r\n \/\/ Ensure named map is the expected size\r\n BOOST_CHECK_EQUAL(find_pattern.GetAddresses().size(), 4UL);\r\n\r\n \/\/ Test stream-based pattern scanner by scanning for an instruction with \r\n \/\/ a known relative operand. We should ensure that we're not going to hit \r\n \/\/ this particular byte accidently as part of the operand of another \r\n \/\/ instruction, but for now lets just ignore that possibility. The test \r\n \/\/ will (or should) fail in that case.\r\n hadesmem::Pattern call_pattern(find_pattern, L\"E8\",\r\n hadesmem::FindPatternFlags::kRelativeAddress);\r\n \/\/ Ensure pattern was found\r\n BOOST_CHECK(call_pattern.GetAddress() != nullptr);\r\n \/\/ The instruction is a 'Call' instruction, so add one byte to move \r\n \/\/ past the instruction, then perform a relative dereference using the \r\n \/\/ instruction size and operand offset (5 and 1 respectively in this \r\n \/\/ case, for a 32-bit relative call).\r\n call_pattern << hadesmem::pattern_manipulators::Add(1) <<\r\n hadesmem::pattern_manipulators::Rel(5, 1);\r\n \/\/ Ensure pattern was found\r\n BOOST_CHECK(call_pattern.GetAddress() != nullptr);\r\n\r\n \/\/ Todo: pattern_manipulators::Lea test\r\n\r\n \/\/ Test pattern file, including scan flags, pattern matching, and \r\n \/\/ optional manipulators. Use the same patterns we have been using \r\n \/\/ already so we can check their validity.\r\n std::wstring const pattern_file_data =\r\n LR\"(\r\n<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<HadesMem>\r\n <FindPattern>\r\n <Flag Name=\"RelativeAddress\"\/>\r\n <Flag Name=\"ThrowOnUnmatch\"\/>\r\n <Pattern Name=\"First Call\" Data=\"E8\">\r\n <Manipulator Name=\"Add\" Operand1=\"1\"><\/Manipulator>\r\n <Manipulator Name=\"Rel\" Operand1=\"5\" Operand2=\"1\"><\/Manipulator>\r\n <\/Pattern>\r\n <Pattern Name=\"Zeros New\" Data=\"00 ?? 00\">\r\n <Manipulator Name=\"Add\" Operand1=\"1\"><\/Manipulator>\r\n <Manipulator Name=\"Sub\" Operand1=\"1\"><\/Manipulator>\r\n <\/Pattern>\r\n <Pattern Name=\"Nop Other\" Data=\"90\"\/>\r\n <\/FindPattern>\r\n<\/HadesMem>\r\n)\";\r\n find_pattern.LoadFileMemory(pattern_file_data);\r\n \/\/ Ensure all patterns match previous scans\r\n BOOST_CHECK_EQUAL(find_pattern.Lookup(L\"First Call\"), \r\n call_pattern.GetAddress());\r\n BOOST_CHECK_EQUAL(find_pattern.Lookup(L\"First Call\"), \r\n find_pattern[L\"First Call\"]);\r\n BOOST_CHECK_EQUAL(find_pattern.Lookup(L\"Zeros New\"), \r\n zeros_rel);\r\n BOOST_CHECK_EQUAL(find_pattern.Lookup(L\"Zeros New\"), \r\n find_pattern[L\"Zeros New\"]);\r\n BOOST_CHECK_EQUAL(find_pattern.Lookup(L\"Nop Other\"), \r\n nop_rel);\r\n BOOST_CHECK_EQUAL(find_pattern.Lookup(L\"Nop Other\"), \r\n find_pattern[L\"Nop Other\"]);\r\n\r\n \/\/ Test pattern file, using various types of invalid input.\r\n \/\/ TODO: Fix the test to ensure we get the error we're expecting, rather \r\n \/\/ than just any error.\r\n std::wstring const pattern_file_data_invalid1 =\r\n LR\"(\r\n<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<HadesMem>\r\n <FindPattern>\r\n <Flag Name=\"InvalidFlag\"><\/Flag>\r\n <\/FindPattern>\r\n<\/HadesMem>\r\n)\";\r\n BOOST_CHECK_THROW(find_pattern.LoadFileMemory(\r\n pattern_file_data_invalid1), \r\n hadesmem::Error);\r\n\r\n std::wstring const pattern_file_data_invalid2 =\r\n LR\"(\r\n<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<HadesMem>\r\n <FindPattern>\r\n <Flag Name=\"RelativeAddress\"><\/Flag>\r\n <Flag Name=\"ThrowOnUnmatch\"><\/Flag>\r\n <Pattern Name=\"Foo\" Data=\"ZZ\"><\/Pattern>\r\n <\/FindPattern>\r\n<\/HadesMem>\r\n)\";\r\n BOOST_CHECK_THROW(find_pattern.LoadFileMemory(\r\n pattern_file_data_invalid2), \r\n hadesmem::Error);\r\n\r\n std::wstring const pattern_file_data_invalid3 =\r\n LR\"(\r\n<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<HadesMem>\r\n <FindPattern>\r\n <Flag Name=\"RelativeAddress\"><\/Flag>\r\n <Flag Name=\"ThrowOnUnmatch\"><\/Flag>\r\n <Pattern><\/Pattern>\r\n <\/FindPattern>\r\n<\/HadesMem>\r\n)\";\r\n BOOST_CHECK_THROW(find_pattern.LoadFileMemory(\r\n pattern_file_data_invalid3),\r\n hadesmem::Error);\r\n\r\n \/\/ Todo: LoadFile test\r\n\r\n \/\/ Perform a full wildcard scan twice and ensure that both scans return \r\n \/\/ the same address\r\n auto const nops_any = find_pattern.Find(L\"?? ?? ?? ?? ??\",\r\n hadesmem::FindPatternFlags::kNone);\r\n auto const int3s_any = find_pattern.Find(L\"?? ?? ?? ?? ??\",\r\n hadesmem::FindPatternFlags::kNone);\r\n BOOST_CHECK_EQUAL(nops_any, int3s_any);\r\n \/\/ Ensure address is valid\r\n BOOST_CHECK_GT(nops_any, GetModuleHandle(nullptr));\r\n \/\/ Perform scan again with relative address flag\r\n auto const nops_any_rel = find_pattern.Find(L\"?? ?? ?? ?? ??\",\r\n hadesmem::FindPatternFlags::kRelativeAddress);\r\n \/\/ Ensure address is valid\r\n BOOST_CHECK_EQUAL(static_cast<PBYTE>(nops_any_rel)+\r\n reinterpret_cast<DWORD_PTR>(self), nops_any);\r\n\r\n \/\/ Check ThrowOnUnmatch flag\r\n BOOST_CHECK_THROW(find_pattern.Find(L\"AA BB CC DD EE FF 11 22 33 44 55 \"\r\n L\"66 77 88 99 00 11 33 33 77\", \r\n hadesmem::FindPatternFlags::kThrowOnUnmatch),\r\n hadesmem::Error);\r\n\r\n \/\/ Check ScanData flag\r\n \/\/ Note: Pattern is for narrow string 'FindPattern' (without quotes)\r\n auto const find_pattern_str = find_pattern.Find(L\"46 69 6E 64 50 61 74 \"\r\n L\"74 65 72 6E\", hadesmem::FindPatternFlags::kScanData);\r\n BOOST_CHECK(find_pattern_str != nullptr);\r\n\r\n \/\/ Check conversion failures throw\r\n BOOST_CHECK_THROW(find_pattern.Find(L\"ZZ\",\r\n hadesmem::FindPatternFlags::kNone), hadesmem::Error);\r\n\r\n \/\/ Check conversion failures throw\r\n \/\/ Code changes now mean this causes an assert.\r\n \/\/BOOST_CHECK_THROW(find_pattern.Find(L\"\", \r\n \/\/ hadesmem::FindPatternFlags::kNone), hadesmem::Error);\r\n}\r\n<|endoftext|>"} {"text":"<commit_before>#ifndef NUMTYPE_ADAPTERS_EIGEN_HPP_G9DJMXVS\n#define NUMTYPE_ADAPTERS_EIGEN_HPP_G9DJMXVS\n\n#include <ndata\/algorithm\/numtype_adapter_fundamental.hpp>\n\nnamespace ndata {\nnamespace helpers {\n\ntemplate <typename EigenT>\nusing DerivedOf = typename std::result_of<typename EigenT::derived>::type;\n\ntemplate <typename EigenT>\nusing DenseBaseParent = Eigen::DenseBase<DerivedOf<EigenT>>;\n\ntemplate <typename T>\nstruct numtype_adapter<\n T,\n typename std::enable_if<\n std::is_base_of<\n Eigen::EigenBase<T>,\n T\n >::value\n >::type\n>\n{\n\n static const\n T ZERO;\n\n};\n\ntemplate <typename T>\nconst T\nnumtype_adapter<\n T,\n typename std::enable_if<\n std::is_base_of<\n Eigen::EigenBase<T>,\n T\n >::value\n >::type\n>::ZERO = T::Zero();\n\n} \/\/end namespace ndata\n} \/\/end namespace helpers\n\n\n\n\n#endif \/* end of include guard: NUMTYPE_ADAPTERS_EIGEN_HPP_G9DJMXVS *\/ \n<commit_msg>minor<commit_after>#ifndef NUMTYPE_ADAPTERS_EIGEN_HPP_G9DJMXVS\n#define NUMTYPE_ADAPTERS_EIGEN_HPP_G9DJMXVS\n\n#include <ndata\/algorithm\/numtype_adapter_fundamental.hpp>\n\n\/\/TODO test this with interp\n\nnamespace ndata {\nnamespace helpers {\n\ntemplate <typename EigenT>\nusing DerivedOf = typename std::result_of<typename EigenT::derived>::type;\n\ntemplate <typename EigenT>\nusing DenseBaseParent = Eigen::DenseBase<DerivedOf<EigenT>>;\n\ntemplate <typename T>\nstruct numtype_adapter<\n T,\n typename std::enable_if<\n std::is_base_of<\n Eigen::EigenBase<T>,\n T\n >::value\n >::type\n>\n{\n\n static const\n T ZERO;\n\n};\n\ntemplate <typename T>\nconst T\nnumtype_adapter<\n T,\n typename std::enable_if<\n std::is_base_of<\n Eigen::EigenBase<T>,\n T\n >::value\n >::type\n>::ZERO = T::Zero();\n\n} \/\/end namespace ndata\n} \/\/end namespace helpers\n\n\n\n\n#endif \/* end of include guard: NUMTYPE_ADAPTERS_EIGEN_HPP_G9DJMXVS *\/ \n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 2014 Gamoeba Ltd\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *\/\n\n#include \"glwidget.h\"\n#include <QPainter>\n#include <QPaintEngine>\n#include <QMouseEvent>\n#include <math.h>\n#include <map>\n\nGLWidget::GLWidget(QWidget *parent)\n : QGLWidget(parent)\n{\n qtLogo = true;\n m_fScale = 1.0;\n setAttribute(Qt::WA_PaintOnScreen);\n setAttribute(Qt::WA_NoSystemBackground);\n setAutoBufferSwap(false);\n\n mTranslateX = 0;\n mTranslateY = 0;\n mDragX = 0;\n mDragY = 0;\n mSelectionIndex=0;\n mShowScreenShot = false;\n mDragging = false;\n\n connect(&mAnimationTimer,SIGNAL(timeout()),SLOT(animate()));\n setMouseTracking(true);\n\n mLogo = QPixmap(\":\/stagehand\/splash.png\");\n\n}\n\nGLWidget::~GLWidget()\n{\n}\n\nvoid GLWidget::setProjectionMatrix(QMatrix4x4 projMatrix)\n{\n mProjectionMatrix = projMatrix;\n}\n\nvoid GLWidget::setViewMatrix(QMatrix4x4 viewMatrix)\n{\n mViewMatrix = viewMatrix;\n}\n\nvoid GLWidget::setAspectRatio(double aspectRatio) {\n mAspectRatio = aspectRatio;\n}\n\nvoid GLWidget::addObject(int id, SceneObject so, bool \/*selected*\/)\n{\n mObjects[id] = so;\n}\n\nvoid GLWidget::clear()\n{\n mObjects.clear();\n}\n\nvoid GLWidget::zoomIn()\n{\n if (mAnimationTimer.isActive()) {\n mAnimationTimer.stop();\n m_fScale = mEndScale;\n update();\n }\n mAnimationLengthms = 500;\n mStartScale = m_fScale;\n mEndScale = m_fScale * 2;\n mElapsedTimer.start();\n mAnimationTimer.start(10);\n}\n\nvoid GLWidget::zoomOut()\n{\n if (mAnimationTimer.isActive()) {\n mAnimationTimer.stop();\n m_fScale = mEndScale;\n update();\n }\n\n mAnimationLengthms = 500;\n mStartScale = m_fScale;\n mEndScale = m_fScale \/ 2.0;\n mElapsedTimer.start();\n mAnimationTimer.start(10);\n}\n\nvoid GLWidget::setScreenShot(QImage img)\n{\n mScreenShot = img;\n}\n\nvoid GLWidget::setSelection(int id)\n{\n mSelectedIds.clear();\n mSelectedIds.push_back(id);\n mSelectionIndex=0;\n update();\n}\n\nvoid GLWidget::animate()\n{\n float step = mEndScale - mStartScale;\n qint64 elapsedTimems = mElapsedTimer.nsecsElapsed()\/1000000;\n float scalefac = ((float)(elapsedTimems)\/(float)mAnimationLengthms);\n m_fScale = mStartScale + scalefac*step;\n if (mElapsedTimer.hasExpired(mAnimationLengthms)) {\n m_fScale = mEndScale;\n mAnimationTimer.stop();\n }\n update();\n}\n\nvoid GLWidget::drawRect()\n{\n glBindTexture(GL_TEXTURE_2D, m_uiTexture);\n GLfloat afVertices[] = {\n -0.5, 0.5, 0.5, 0.5,-0.5,0.5,-0.5,-0.5,0.5,\n 0.5, -0.5, 0.5, -0.5,0.5,0.5,0.5,0.5,0.5\n };\n program.setAttributeArray(vertexAttr, afVertices, 3);\n\n GLfloat afTexCoord[] = {\n 0.0f,0.0f, 1.0f,1.0f, 0.0f,1.0f,\n 1.0f,1.0f, 0.0f,0.0f, 1.0f,0.0f\n };\n program.setAttributeArray(texCoordAttr, afTexCoord, 2);\n\n GLfloat afNormals[] = {\n\n 0,0,-1, 0,0,-1, 0,0,-1,\n 0,0,-1, 0,0,-1, 0,0,-1\n };\n program.setAttributeArray(normalAttr, afNormals, 3);\n\n program.setUniformValue(textureUniform, 0); \/\/ use texture unit 0\n\n program.enableAttributeArray(vertexAttr);\n program.enableAttributeArray(normalAttr);\n program.enableAttributeArray(texCoordAttr);\n\n glDrawArrays(GL_TRIANGLES, 0, 6);\n\n program.disableAttributeArray(vertexAttr);\n program.disableAttributeArray(normalAttr);\n program.disableAttributeArray(texCoordAttr);\n}\n\nvoid GLWidget::initializeGL ()\n{\n glClearColor(0.1f, 0.1f, 0.2f, 1.0f);\n\n glGenTextures(1, &m_uiTexture);\n\n QGLShader *vshader = new QGLShader(QGLShader::Vertex);\n vshader->compileSourceFile(\":\/stagehand\/shader.vsh\");\n\n QGLShader *fshader = new QGLShader(QGLShader::Fragment);\n fshader->compileSourceFile(\":\/stagehand\/shader.fsh\");\n\n program.addShader(vshader);\n program.addShader(fshader);\n program.link();\n\n vertexAttr = program.attributeLocation(\"vertex\");\n normalAttr = program.attributeLocation(\"normal\");\n texCoordAttr = program.attributeLocation(\"texCoord\");\n matrixUniform = program.uniformLocation(\"matrix\");\n textureUniform = program.uniformLocation(\"tex\");\n selectedUniform = program.uniformLocation(\"selected\");\n screenShotUniform = program.uniformLocation(\"screenshot\");\n drawTextureUniform = program.uniformLocation(\"drawTexture\");\n xthresholdUniform = program.uniformLocation(\"xthreshold\");\n ythresholdUniform = program.uniformLocation(\"ythreshold\");\n\n\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );\n\n\n m_fAngle = 0;\n}\n\nvoid GLWidget::paintGL()\n{\n QPainter painter;\n painter.begin(this);\n\n painter.beginNativePainting();\n glClearColor(0.1f, 0.1f, 0.2f, 1.0f);\n\n glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);\n\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );\n\n glFrontFace(GL_CW);\n glCullFace(GL_FRONT);\n glDisable(GL_CULL_FACE);\n glDisable(GL_DEPTH_TEST);\n glEnable(GL_BLEND);\n glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA);\n\n\n\n if (mObjects.size()>0) {\n\n m_uiTexture = bindTexture(mScreenShot);\n program.bind();\n mModelView = mProjectionMatrix * mViewMatrix;\n mModelView.translate(mTranslateX + mDragX ,mTranslateY + mDragY ,0);\n mModelView.scale(mAspectRatio, 1.0, 1.0);\n mModelView.scale(m_fScale,m_fScale,1.0);\n\n int selectionId = 0;\n if (mSelectionIndex < mSelectedIds.size()) {\n selectionId = mSelectedIds[mSelectionIndex];\n }\n\n std::map<int, SceneObject>::iterator iter;\n for (iter = mObjects.begin();iter != mObjects.end();iter++) {\n SceneObject so = (*iter).second;\n QMatrix4x4 objectMatrix = so.mWorldMatrix;\n\n QVector3D size = so.mSize;\n objectMatrix.scale(size);\n objectMatrix = mModelView * objectMatrix;\n objectMatrix.scale(1.0f, 1.0f, 0.05f);\n\n QVector3D tl(-0.5, 0.5,0.0);\n QVector3D br(0.5, -0.5,0.0);\n tl = objectMatrix*tl;\n br = objectMatrix*br;\n float xpixels = (float)width() * (br.x()-tl.x())\/2.0;\n float xthreshold = 1.0\/xpixels;\n float ypixels = (float)height() * (br.y()-tl.y())\/2.0;\n float ythreshold = 1.0\/ypixels;\n\n program.setUniformValue(drawTextureUniform, mShowScreenShot && (*iter).first == 1);\n program.setUniformValue(matrixUniform, objectMatrix);\n program.setUniformValue(selectedUniform, (*iter).first == selectionId);\n program.setUniformValue(screenShotUniform, mShowScreenShot);\n program.setUniformValue(xthresholdUniform, xthreshold);\n program.setUniformValue(ythresholdUniform, ythreshold);\n\n drawRect();\n\n }\n program.release();\n } else {\n drawLogo();\n }\n\n\n glDisable(GL_CULL_FACE);\n\n painter.endNativePainting();\n\n painter.end();\n\n swapBuffers();\n}\n\nvoid GLWidget::drawLogo() {\n QMatrix4x4 objectMatrix;\n float ratio = (float)mLogo.height()\/(float)mLogo.width();\n objectMatrix.scale(1.0f, -ratio, 1.0f);\n m_uiTexture = bindTexture(mLogo);\n program.bind();\n program.setUniformValue(drawTextureUniform, true);\n program.setUniformValue(matrixUniform, objectMatrix);\n program.setUniformValue(selectedUniform, false);\n program.setUniformValue(screenShotUniform, true);\n program.setUniformValue(xthresholdUniform, 0.2f);\n program.setUniformValue(ythresholdUniform, 0.2f);\n\n drawRect();\n program.release();\n}\n\nvoid GLWidget::mouseMoveEvent(QMouseEvent* event) {\n QPoint currpoint = event->pos();\n if (mDragging) {\n currpoint -= mStartPoint;\n mDragX = currpoint.x();\n mDragY = currpoint.y();\n update();\n } else {\n \/\/ assume that the first node has the screen size\n\n if (mObjects.size()>0) {\n float x = (float)event->pos().x()\/(float)width()*2.0f -1.0f;\n float y = (float)event->pos().y()\/(float)height()*-2.0f + 1.0f;\n SceneObject so = mObjects[1];\n\n QMatrix4x4 objectMatrix = so.mWorldMatrix;\n\n QVector3D size = so.mSize;\n objectMatrix.scale(size);\n objectMatrix = mModelView * objectMatrix;\n objectMatrix.scale(1.0f, 1.0f, 0.05f);\n QVector3D tl(-0.5, 0.5,0.0);\n QVector3D br(0.5, -0.5,0.0);\n tl = objectMatrix*tl;\n br = objectMatrix*br;\n if (x >= tl.x() && y >= tl.y() &&\n x <= br.x() && y <= br.y()) {\n x-= tl.x();\n y-= tl.y();\n x \/= br.x() - tl.x();\n y \/= br.y() - tl.y();\n y = 1 - y; \/\/flip axis\n mousePosition((int)(x*size.x()), (int)(y*size.y()));\n } else {\n mousePosition(-1, -1);\n }\n\n }\n\n\n }\n}\n\nvoid GLWidget::mousePressEvent(QMouseEvent *eventPress){\n mStartPoint = eventPress->pos();\n mDragging = true;\n}\n\nvoid GLWidget::mouseReleaseEvent(QMouseEvent *releaseEvent){\n mTranslateX += mDragX;\n mTranslateY += mDragY;\n mDragX = mDragY = 0;\n\n if (releaseEvent->pos() == mStartPoint) {\n QPoint pos = releaseEvent->pos();\n float x = (float)pos.x()\/(float)width()*2.0f -1.0f;\n float y = (float)pos.y()\/(float)height()*-2.0f + 1.0f;\n select(x,y);\n }\n mDragging = false;\n update();\n}\n\nvoid GLWidget::select(float x, float y) {\n std::vector<int> ids;\n std::map<int, SceneObject>::iterator iter;\n for (iter = mObjects.begin();iter != mObjects.end();iter++) {\n SceneObject so = (*iter).second;\n QMatrix4x4 objectMatrix = so.mWorldMatrix;\n\n QVector3D size = so.mSize;\n objectMatrix.scale(size);\n objectMatrix = mModelView * objectMatrix;\n objectMatrix.scale(1.0f, 1.0f, 0.05f);\n QVector3D tl(-0.5, 0.5,0.0);\n QVector3D br(0.5, -0.5,0.0);\n tl = objectMatrix*tl;\n br = objectMatrix*br;\n if (x >= tl.x() && y >= tl.y() &&\n x <= br.x() && y <= br.y()) {\n ids.insert(ids.begin(), (*iter).first);\n }\n\n }\n bool is_equal = false;\n if ( ids.size() > 0 && ids.size() == mSelectedIds.size() )\n is_equal = std::equal ( ids.begin(), ids.end(), mSelectedIds.begin() );\n\n if (is_equal) {\n mSelectionIndex++;\n mSelectionIndex %= mSelectedIds.size();\n } else {\n mSelectedIds = ids;\n mSelectionIndex = 0;\n }\n\n if (mSelectionIndex < mSelectedIds.size()) {\n emit selectedId(mSelectedIds[mSelectionIndex]);\n }\n}\n<commit_msg>Correctly find root node, even when it has a different index from 1<commit_after>\/*\n * Copyright (c) 2014 Gamoeba Ltd\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *\/\n\n#include \"glwidget.h\"\n#include <QPainter>\n#include <QPaintEngine>\n#include <QMouseEvent>\n#include <math.h>\n#include <map>\n\nGLWidget::GLWidget(QWidget *parent)\n : QGLWidget(parent)\n{\n qtLogo = true;\n m_fScale = 1.0;\n setAttribute(Qt::WA_PaintOnScreen);\n setAttribute(Qt::WA_NoSystemBackground);\n setAutoBufferSwap(false);\n\n mTranslateX = 0;\n mTranslateY = 0;\n mDragX = 0;\n mDragY = 0;\n mSelectionIndex=0;\n mShowScreenShot = false;\n mDragging = false;\n\n connect(&mAnimationTimer,SIGNAL(timeout()),SLOT(animate()));\n setMouseTracking(true);\n\n mLogo = QPixmap(\":\/stagehand\/splash.png\");\n\n}\n\nGLWidget::~GLWidget()\n{\n}\n\nvoid GLWidget::setProjectionMatrix(QMatrix4x4 projMatrix)\n{\n mProjectionMatrix = projMatrix;\n}\n\nvoid GLWidget::setViewMatrix(QMatrix4x4 viewMatrix)\n{\n mViewMatrix = viewMatrix;\n}\n\nvoid GLWidget::setAspectRatio(double aspectRatio) {\n mAspectRatio = aspectRatio;\n}\n\nvoid GLWidget::addObject(int id, SceneObject so, bool \/*selected*\/)\n{\n mObjects[id] = so;\n}\n\nvoid GLWidget::clear()\n{\n mObjects.clear();\n}\n\nvoid GLWidget::zoomIn()\n{\n if (mAnimationTimer.isActive()) {\n mAnimationTimer.stop();\n m_fScale = mEndScale;\n update();\n }\n mAnimationLengthms = 500;\n mStartScale = m_fScale;\n mEndScale = m_fScale * 2;\n mElapsedTimer.start();\n mAnimationTimer.start(10);\n}\n\nvoid GLWidget::zoomOut()\n{\n if (mAnimationTimer.isActive()) {\n mAnimationTimer.stop();\n m_fScale = mEndScale;\n update();\n }\n\n mAnimationLengthms = 500;\n mStartScale = m_fScale;\n mEndScale = m_fScale \/ 2.0;\n mElapsedTimer.start();\n mAnimationTimer.start(10);\n}\n\nvoid GLWidget::setScreenShot(QImage img)\n{\n mScreenShot = img;\n}\n\nvoid GLWidget::setSelection(int id)\n{\n mSelectedIds.clear();\n mSelectedIds.push_back(id);\n mSelectionIndex=0;\n update();\n}\n\nvoid GLWidget::animate()\n{\n float step = mEndScale - mStartScale;\n qint64 elapsedTimems = mElapsedTimer.nsecsElapsed()\/1000000;\n float scalefac = ((float)(elapsedTimems)\/(float)mAnimationLengthms);\n m_fScale = mStartScale + scalefac*step;\n if (mElapsedTimer.hasExpired(mAnimationLengthms)) {\n m_fScale = mEndScale;\n mAnimationTimer.stop();\n }\n update();\n}\n\nvoid GLWidget::drawRect()\n{\n glBindTexture(GL_TEXTURE_2D, m_uiTexture);\n GLfloat afVertices[] = {\n -0.5, 0.5, 0.5, 0.5,-0.5,0.5,-0.5,-0.5,0.5,\n 0.5, -0.5, 0.5, -0.5,0.5,0.5,0.5,0.5,0.5\n };\n program.setAttributeArray(vertexAttr, afVertices, 3);\n\n GLfloat afTexCoord[] = {\n 0.0f,0.0f, 1.0f,1.0f, 0.0f,1.0f,\n 1.0f,1.0f, 0.0f,0.0f, 1.0f,0.0f\n };\n program.setAttributeArray(texCoordAttr, afTexCoord, 2);\n\n GLfloat afNormals[] = {\n\n 0,0,-1, 0,0,-1, 0,0,-1,\n 0,0,-1, 0,0,-1, 0,0,-1\n };\n program.setAttributeArray(normalAttr, afNormals, 3);\n\n program.setUniformValue(textureUniform, 0); \/\/ use texture unit 0\n\n program.enableAttributeArray(vertexAttr);\n program.enableAttributeArray(normalAttr);\n program.enableAttributeArray(texCoordAttr);\n\n glDrawArrays(GL_TRIANGLES, 0, 6);\n\n program.disableAttributeArray(vertexAttr);\n program.disableAttributeArray(normalAttr);\n program.disableAttributeArray(texCoordAttr);\n}\n\nvoid GLWidget::initializeGL ()\n{\n glClearColor(0.1f, 0.1f, 0.2f, 1.0f);\n\n glGenTextures(1, &m_uiTexture);\n\n QGLShader *vshader = new QGLShader(QGLShader::Vertex);\n vshader->compileSourceFile(\":\/stagehand\/shader.vsh\");\n\n QGLShader *fshader = new QGLShader(QGLShader::Fragment);\n fshader->compileSourceFile(\":\/stagehand\/shader.fsh\");\n\n program.addShader(vshader);\n program.addShader(fshader);\n program.link();\n\n vertexAttr = program.attributeLocation(\"vertex\");\n normalAttr = program.attributeLocation(\"normal\");\n texCoordAttr = program.attributeLocation(\"texCoord\");\n matrixUniform = program.uniformLocation(\"matrix\");\n textureUniform = program.uniformLocation(\"tex\");\n selectedUniform = program.uniformLocation(\"selected\");\n screenShotUniform = program.uniformLocation(\"screenshot\");\n drawTextureUniform = program.uniformLocation(\"drawTexture\");\n xthresholdUniform = program.uniformLocation(\"xthreshold\");\n ythresholdUniform = program.uniformLocation(\"ythreshold\");\n\n\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );\n\n\n m_fAngle = 0;\n}\n\nvoid GLWidget::paintGL()\n{\n QPainter painter;\n painter.begin(this);\n\n painter.beginNativePainting();\n glClearColor(0.1f, 0.1f, 0.2f, 1.0f);\n\n glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);\n\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );\n\n glFrontFace(GL_CW);\n glCullFace(GL_FRONT);\n glDisable(GL_CULL_FACE);\n glDisable(GL_DEPTH_TEST);\n glEnable(GL_BLEND);\n glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA);\n\n\n\n if (mObjects.size()>0) {\n\n m_uiTexture = bindTexture(mScreenShot);\n program.bind();\n mModelView = mProjectionMatrix * mViewMatrix;\n mModelView.translate(mTranslateX + mDragX ,mTranslateY + mDragY ,0);\n mModelView.scale(mAspectRatio, 1.0, 1.0);\n mModelView.scale(m_fScale,m_fScale,1.0);\n\n int selectionId = 0;\n if (mSelectionIndex < mSelectedIds.size()) {\n selectionId = mSelectedIds[mSelectionIndex];\n }\n\n std::map<int, SceneObject>::iterator iter;\n for (iter = mObjects.begin();iter != mObjects.end();iter++) {\n SceneObject so = (*iter).second;\n QMatrix4x4 objectMatrix = so.mWorldMatrix;\n\n QVector3D size = so.mSize;\n objectMatrix.scale(size);\n objectMatrix = mModelView * objectMatrix;\n objectMatrix.scale(1.0f, 1.0f, 0.05f);\n\n QVector3D tl(-0.5, 0.5,0.0);\n QVector3D br(0.5, -0.5,0.0);\n tl = objectMatrix*tl;\n br = objectMatrix*br;\n float xpixels = (float)width() * (br.x()-tl.x())\/2.0;\n float xthreshold = 1.0\/xpixels;\n float ypixels = (float)height() * (br.y()-tl.y())\/2.0;\n float ythreshold = 1.0\/ypixels;\n\n program.setUniformValue(drawTextureUniform, mShowScreenShot && (*iter).first == 1);\n program.setUniformValue(matrixUniform, objectMatrix);\n program.setUniformValue(selectedUniform, (*iter).first == selectionId);\n program.setUniformValue(screenShotUniform, mShowScreenShot);\n program.setUniformValue(xthresholdUniform, xthreshold);\n program.setUniformValue(ythresholdUniform, ythreshold);\n\n drawRect();\n\n }\n program.release();\n } else {\n drawLogo();\n }\n\n\n glDisable(GL_CULL_FACE);\n\n painter.endNativePainting();\n\n painter.end();\n\n swapBuffers();\n}\n\nvoid GLWidget::drawLogo() {\n QMatrix4x4 objectMatrix;\n float ratio = (float)mLogo.height()\/(float)mLogo.width();\n objectMatrix.scale(1.0f, -ratio, 1.0f);\n m_uiTexture = bindTexture(mLogo);\n program.bind();\n program.setUniformValue(drawTextureUniform, true);\n program.setUniformValue(matrixUniform, objectMatrix);\n program.setUniformValue(selectedUniform, false);\n program.setUniformValue(screenShotUniform, true);\n program.setUniformValue(xthresholdUniform, 0.2f);\n program.setUniformValue(ythresholdUniform, 0.2f);\n\n drawRect();\n program.release();\n}\n\nvoid GLWidget::mouseMoveEvent(QMouseEvent* event) {\n QPoint currpoint = event->pos();\n if (mDragging) {\n currpoint -= mStartPoint;\n mDragX = currpoint.x();\n mDragY = currpoint.y();\n update();\n } else {\n \/\/ assume that the first node has the screen size\n\n if (mObjects.size()>0) {\n float x = (float)event->pos().x()\/(float)width()*2.0f -1.0f;\n float y = (float)event->pos().y()\/(float)height()*-2.0f + 1.0f;\n\n SceneObject so = mObjects.begin()->second;\n\n QMatrix4x4 objectMatrix = so.mWorldMatrix;\n\n QVector3D size = so.mSize;\n objectMatrix.scale(size);\n objectMatrix = mModelView * objectMatrix;\n objectMatrix.scale(1.0f, 1.0f, 0.05f);\n QVector3D tl(-0.5, 0.5,0.0);\n QVector3D br(0.5, -0.5,0.0);\n tl = objectMatrix*tl;\n br = objectMatrix*br;\n if (x >= tl.x() && y >= tl.y() &&\n x <= br.x() && y <= br.y()) {\n x-= tl.x();\n y-= tl.y();\n x \/= br.x() - tl.x();\n y \/= br.y() - tl.y();\n y = 1 - y; \/\/flip axis\n mousePosition((int)(x*size.x()), (int)(y*size.y()));\n } else {\n mousePosition(-1, -1);\n }\n\n }\n\n\n }\n}\n\nvoid GLWidget::mousePressEvent(QMouseEvent *eventPress){\n mStartPoint = eventPress->pos();\n mDragging = true;\n}\n\nvoid GLWidget::mouseReleaseEvent(QMouseEvent *releaseEvent){\n mTranslateX += mDragX;\n mTranslateY += mDragY;\n mDragX = mDragY = 0;\n\n if (releaseEvent->pos() == mStartPoint) {\n QPoint pos = releaseEvent->pos();\n float x = (float)pos.x()\/(float)width()*2.0f -1.0f;\n float y = (float)pos.y()\/(float)height()*-2.0f + 1.0f;\n select(x,y);\n }\n mDragging = false;\n update();\n}\n\nvoid GLWidget::select(float x, float y) {\n std::vector<int> ids;\n std::map<int, SceneObject>::iterator iter;\n for (iter = mObjects.begin();iter != mObjects.end();iter++) {\n SceneObject so = (*iter).second;\n QMatrix4x4 objectMatrix = so.mWorldMatrix;\n\n QVector3D size = so.mSize;\n objectMatrix.scale(size);\n objectMatrix = mModelView * objectMatrix;\n objectMatrix.scale(1.0f, 1.0f, 0.05f);\n QVector3D tl(-0.5, 0.5,0.0);\n QVector3D br(0.5, -0.5,0.0);\n tl = objectMatrix*tl;\n br = objectMatrix*br;\n if (x >= tl.x() && y >= tl.y() &&\n x <= br.x() && y <= br.y()) {\n ids.insert(ids.begin(), (*iter).first);\n }\n\n }\n bool is_equal = false;\n if ( ids.size() > 0 && ids.size() == mSelectedIds.size() )\n is_equal = std::equal ( ids.begin(), ids.end(), mSelectedIds.begin() );\n\n if (is_equal) {\n mSelectionIndex++;\n mSelectionIndex %= mSelectedIds.size();\n } else {\n mSelectedIds = ids;\n mSelectionIndex = 0;\n }\n\n if (mSelectionIndex < mSelectedIds.size()) {\n emit selectedId(mSelectedIds[mSelectionIndex]);\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\n#pragma once\n\n#include \"numerics\/quadrature.hpp\"\n\n#include <memory>\n#include <vector>\n\n#include \"base\/bits.hpp\"\n#include \"geometry\/hilbert.hpp\"\n#include \"numerics\/fast_fourier_transform.hpp\"\n#include \"numerics\/gauss_legendre_weights.mathematica.h\"\n#include \"numerics\/legendre_roots.mathematica.h\"\n#include \"quantities\/elementary_functions.hpp\"\n\nnamespace principia {\nnamespace numerics {\nnamespace quadrature {\nnamespace internal_quadrature {\n\nusing base::BitReversedIncrement;\nusing base::FloorLog2;\nusing geometry::Hilbert;\nusing quantities::Angle;\nusing quantities::Cos;\nusing quantities::Difference;\nusing quantities::si::Radian;\n\ntemplate<int points, typename Argument, typename Function>\nPrimitive<std::invoke_result_t<Function, Argument>, Argument> Gauss(\n Function const& f,\n Argument const& lower_bound,\n Argument const& upper_bound,\n double const* const nodes,\n double const* const weights) {\n Difference<Argument> half_width = (upper_bound - lower_bound) \/ 2;\n std::invoke_result_t<Function, Argument> result{};\n for (int i = 0; i < points; ++i) {\n Argument const scaled_node = lower_bound + half_width * (nodes[i] + 1);\n \/\/ TODO(phl): Consider compensated summation.\n result += weights[i] * f(scaled_node);\n }\n return result * half_width;\n}\n\ntemplate<int points, typename Argument, typename Function>\nPrimitive<std::invoke_result_t<Function, Argument>, Argument> GaussLegendre(\n Function const& f,\n Argument const& lower_bound,\n Argument const& upper_bound) {\n static_assert(points < LegendreRoots.size,\n \"No table for Gauss-Legendre with the chosen number of points\");\n return Gauss<points>(f,\n lower_bound,\n upper_bound,\n LegendreRoots[points],\n GaussLegendreWeights[points]);\n}\n\n\/\/ Our automatic Cleshaw-Curtis implementation doubles the number of points\n\/\/ repeatedly until it reaches a suitable exit criterion. Naïvely evaluating\n\/\/ the function N times for each iteration would be wasteful. Assume that we\n\/\/ have already evaluated the function at 0\/2 and 1\/2 (that is, s = 0 and 1 for\n\/\/ N = 2), we would evaluate it again at 0\/4 and 2\/4 for N = 4, and then proceed\n\/\/ with evaluations at 1\/4 and 3\/4. Overall, we would do roughly twice the\n\/\/ work.\n\/\/ Therefore, we cache the past evaluations. However, we do not want to use a\n\/\/ map and we do not want to do insertion in a vector, say, to squeeze 1\/4\n\/\/ between 0\/2 and 1\/2. So we append the result of evaluations to the cache\n\/\/ vector as we perform them. To fill the cache for N points, we recursively\n\/\/ fill it for N\/2 points (which yields all the values at s\/N for s even) and\n\/\/ then we append the values at s\/N for s odd. The order of the second part\n\/\/ matters. It is done by taking the indices of the first part (covering\n\/\/ [0\/N, (N\/2-1)\/N[) in bit-reversed order and for each index s appending the\n\/\/ value at (2 s + 1)\/N. This ensures that the entire array follows\n\/\/ bit-reversed ordering.\n\/\/ There is an extra wart: we need the value at N\/N, but it does not fit nicely\n\/\/ in the bit-reversed ordering. So we store it at position 0 in the cache, and\n\/\/ the regular cache starts at index 1.\n\/\/ Clients are expected to reserve (at least) points entries in the cache vector\n\/\/ for efficient heap allocation.\ntemplate<int points, typename Argument, typename Function>\nvoid FillClenshawCurtisCache(\n Function const& f,\n Argument const& lower_bound,\n Argument const& upper_bound,\n std::vector<std::invoke_result_t<Function, Argument>>&\n f_cos_N⁻¹π_bit_reversed) {\n \/\/ If we identify [lower_bound, upper_bound] with [-1, 1],\n \/\/ f_cos_N⁻¹π_bit_reversed contains f(cos πs\/N) in bit-reversed order of s.\n \/\/ We use a discrete Fourier transform rather than a cosine transform, see\n \/\/ [Gen72c], equation (3).\n\n \/\/ The cache already has all the data we need.\n if (f_cos_N⁻¹π_bit_reversed.size() >= points) {\n return;\n }\n\n constexpr int N = points - 1;\n static_assert(N >= 1);\n constexpr int log2_N = FloorLog2(N);\n static_assert(N == 1 << log2_N);\n\n Difference<Argument> const half_width = (upper_bound - lower_bound) \/ 2;\n constexpr Angle N⁻¹π = π * Radian \/ N;\n\n if constexpr (N == 1) {\n DCHECK(f_cos_N⁻¹π_bit_reversed.empty());\n \/\/ See above for the magic entry at index 0. The entry at index 1 is a bona\n \/\/ fide entry which will be used by the recursive calls.\n f_cos_N⁻¹π_bit_reversed.push_back(f(lower_bound)); \/\/ s = N.\n f_cos_N⁻¹π_bit_reversed.push_back(f(upper_bound)); \/\/ s = 0.\n } else {\n \/\/ Fill the first half of the cache, corresponding to s even for this value\n \/\/ of N.\n FillClenshawCurtisCache<N \/ 2 + 1>(f,\n lower_bound, upper_bound,\n f_cos_N⁻¹π_bit_reversed);\n \/\/ N\/2 evaluations for f(cos πs\/N) with s odd. Note the need to preserve\n \/\/ bit-reversed ordering.\n int reverse = 0;\n for (int evaluations = 0;\n evaluations < N \/ 2;\n ++evaluations, reverse = BitReversedIncrement(reverse, log2_N - 1)) {\n int const s = 2 * reverse + 1;\n f_cos_N⁻¹π_bit_reversed.push_back(\n f(lower_bound + half_width * (1 + Cos(N⁻¹π * s))));\n }\n }\n}\n\ntemplate<int points, typename Argument, typename Function>\nPrimitive<std::invoke_result_t<Function, Argument>, Argument>\nAutomaticClenshawCurtisImplementation(\n Function const& f,\n Argument const& lower_bound,\n Argument const& upper_bound,\n std::optional<double> const max_relative_error,\n std::optional<int> const max_points,\n Primitive<std::invoke_result_t<Function, Argument>, Argument> const\n previous_estimate,\n std::vector<std::invoke_result_t<Function, Argument>>&\n f_cos_N⁻¹π_bit_reversed) {\n using Result = Primitive<std::invoke_result_t<Function, Argument>, Argument>;\n\n Result const estimate =\n ClenshawCurtisImplementation<points>(\n f, lower_bound, upper_bound, f_cos_N⁻¹π_bit_reversed);\n\n \/\/ This is the naïve estimate mentioned in [Gen72b], p. 339.\n auto const absolute_error_estimate =\n Hilbert<Result>::Norm(previous_estimate - estimate);\n\n if ((!max_relative_error.has_value() ||\n absolute_error_estimate >\n max_relative_error.value() * Hilbert<Result>::Norm(estimate)) &&\n (!max_points.has_value() || points <= max_points.value())) {\n if constexpr (points > 1 << 24) {\n LOG(FATAL) << \"Too many refinements while integrating from \"\n << lower_bound << \" to \" << upper_bound;\n } else {\n f_cos_N⁻¹π_bit_reversed.reserve(2 * points - 1);\n return AutomaticClenshawCurtisImplementation<2 * points - 1>(\n f,\n lower_bound, upper_bound,\n max_relative_error, max_points,\n estimate,\n f_cos_N⁻¹π_bit_reversed);\n }\n }\n return estimate;\n}\n\ntemplate<int points, typename Argument, typename Function>\nPrimitive<std::invoke_result_t<Function, Argument>, Argument>\nClenshawCurtisImplementation(\n Function const& f,\n Argument const& lower_bound,\n Argument const& upper_bound,\n std::vector<std::invoke_result_t<Function, Argument>>&\n f_cos_N⁻¹π_bit_reversed) {\n \/\/ We follow the notation from [Gen72b] and [Gen72c].\n using Value = std::invoke_result_t<Function, Argument>;\n\n constexpr int N = points - 1;\n constexpr int log2_N = FloorLog2(N);\n\n Difference<Argument> const half_width = (upper_bound - lower_bound) \/ 2;\n constexpr Angle N⁻¹π = π * Radian \/ N;\n\n FillClenshawCurtisCache<points>(\n f, lower_bound, upper_bound, f_cos_N⁻¹π_bit_reversed);\n\n \/\/ TODO(phl): If might be possible to avoid copies since\n \/\/ f_cos_N⁻¹π_bit_reversed is tantalizing close to the order needed for the\n \/\/ FFT.\n std::vector<Value> f_cos_N⁻¹π;\n f_cos_N⁻¹π.resize(2 * N);\n \/\/ An index in f_cos_N⁻¹π in the order described by [Gen72b] and [Gen72c].\n int s = 0;\n \/\/ An index in f_cos_N⁻¹π_bit_reversed, corresponding to the order in which\n \/\/ the values were put in the cache. Note that entry 0 is special and holds\n \/\/ the value corresponding to s = N.\n for (int bit_reversed_s = 1;\n bit_reversed_s <= N;\n ++bit_reversed_s, s = BitReversedIncrement(s, log2_N)) {\n f_cos_N⁻¹π[s] = f_cos_N⁻¹π_bit_reversed[bit_reversed_s];\n if (s > 0) {\n f_cos_N⁻¹π[2 * N - s] = f_cos_N⁻¹π[s]; \/\/ [Gen72c] (5).\n }\n }\n f_cos_N⁻¹π[N] = f_cos_N⁻¹π_bit_reversed[0];\n\n auto const fft = std::make_unique<FastFourierTransform<Value, Angle, 2 * N>>(\n f_cos_N⁻¹π, N⁻¹π);\n auto const& a = *fft;\n\n \/\/ [Gen72b] equation (7), factoring out the division by N.\n Value Σʺ{};\n for (std::int64_t n = 0; n <= N; n += 2) {\n \/\/ The notation g is from [OLBC10], 3.5.17.\n int const gₙ = n == 0 || n == N ? 1 : 2;\n Σʺ += a[n].real_part() * gₙ \/ (1 - n * n);\n }\n Σʺ \/= N;\n\n return Σʺ * half_width;\n}\n\ntemplate<int initial_points, typename Argument, typename Function>\nPrimitive<std::invoke_result_t<Function, Argument>, Argument>\nAutomaticClenshawCurtis(\n Function const& f,\n Argument const& lower_bound,\n Argument const& upper_bound,\n std::optional<double> const max_relative_error,\n std::optional<int> const max_points) {\n using Result = Primitive<std::invoke_result_t<Function, Argument>, Argument>;\n using Value = std::invoke_result_t<Function, Argument>;\n std::vector<Value> f_cos_N⁻¹π_bit_reversed;\n f_cos_N⁻¹π_bit_reversed.reserve(2 * initial_points - 1);\n Result const estimate = ClenshawCurtisImplementation<initial_points>(\n f, lower_bound, upper_bound, f_cos_N⁻¹π_bit_reversed);\n return AutomaticClenshawCurtisImplementation<2 * initial_points - 1>(\n f,\n lower_bound, upper_bound,\n max_relative_error, max_points,\n estimate,\n f_cos_N⁻¹π_bit_reversed);\n}\n\ntemplate<int points, typename Argument, typename Function>\nPrimitive<std::invoke_result_t<Function, Argument>, Argument> ClenshawCurtis(\n Function const& f,\n Argument const& lower_bound,\n Argument const& upper_bound) {\n using Value = std::invoke_result_t<Function, Argument>;\n std::vector<Value> f_cos_N⁻¹π_bit_reversed;\n f_cos_N⁻¹π_bit_reversed.reserve(points);\n return ClenshawCurtisImplementation<points>(\n f, lower_bound, upper_bound, f_cos_N⁻¹π_bit_reversed);\n}\n\ntemplate<typename Argument, typename Function>\nPrimitive<std::invoke_result_t<Function, Argument>, Argument> Midpoint(\n Function const& f,\n Argument const& lower_bound,\n Argument const& upper_bound,\n int const intervals) {\n Difference<Argument> const h = (upper_bound - lower_bound) \/ intervals;\n Primitive<std::invoke_result_t<Function, Argument>, Argument> result{};\n for (int i = 0; i < intervals; ++i) {\n result += f(lower_bound + (i + 0.5) * h) * h;\n }\n return result;\n}\n\n} \/\/ namespace internal_quadrature\n} \/\/ namespace quadrature\n} \/\/ namespace numerics\n} \/\/ namespace principia\n<commit_msg>Declare and reorder functions.<commit_after>\n#pragma once\n\n#include \"numerics\/quadrature.hpp\"\n\n#include <memory>\n#include <vector>\n\n#include \"base\/bits.hpp\"\n#include \"geometry\/hilbert.hpp\"\n#include \"numerics\/fast_fourier_transform.hpp\"\n#include \"numerics\/gauss_legendre_weights.mathematica.h\"\n#include \"numerics\/legendre_roots.mathematica.h\"\n#include \"quantities\/elementary_functions.hpp\"\n\nnamespace principia {\nnamespace numerics {\nnamespace quadrature {\nnamespace internal_quadrature {\n\nusing base::BitReversedIncrement;\nusing base::FloorLog2;\nusing geometry::Hilbert;\nusing quantities::Angle;\nusing quantities::Cos;\nusing quantities::Difference;\nusing quantities::si::Radian;\n\ntemplate<int points, typename Argument, typename Function>\nPrimitive<std::invoke_result_t<Function, Argument>, Argument> Gauss(\n Function const& f,\n Argument const& lower_bound,\n Argument const& upper_bound,\n double const* const nodes,\n double const* const weights) {\n Difference<Argument> half_width = (upper_bound - lower_bound) \/ 2;\n std::invoke_result_t<Function, Argument> result{};\n for (int i = 0; i < points; ++i) {\n Argument const scaled_node = lower_bound + half_width * (nodes[i] + 1);\n \/\/ TODO(phl): Consider compensated summation.\n result += weights[i] * f(scaled_node);\n }\n return result * half_width;\n}\n\ntemplate<int points, typename Argument, typename Function>\nvoid FillClenshawCurtisCache(\n Function const& f,\n Argument const& lower_bound,\n Argument const& upper_bound,\n std::vector<std::invoke_result_t<Function, Argument>>&\n f_cos_N⁻¹π_bit_reversed);\n\ntemplate<int points, typename Argument, typename Function>\nPrimitive<std::invoke_result_t<Function, Argument>, Argument>\nAutomaticClenshawCurtisImplementation(\n Function const& f,\n Argument const& lower_bound,\n Argument const& upper_bound,\n std::optional<double> const max_relative_error,\n std::optional<int> const max_points,\n Primitive<std::invoke_result_t<Function, Argument>, Argument> const\n previous_estimate,\n std::vector<std::invoke_result_t<Function, Argument>>&\n f_cos_N⁻¹π_bit_reversed);\n\ntemplate<int points, typename Argument, typename Function>\nPrimitive<std::invoke_result_t<Function, Argument>, Argument>\nClenshawCurtisImplementation(\n Function const& f,\n Argument const& lower_bound,\n Argument const& upper_bound,\n std::vector<std::invoke_result_t<Function, Argument>>&\n f_cos_N⁻¹π_bit_reversed);\n\n\/\/ Our automatic Cleshaw-Curtis implementation doubles the number of points\n\/\/ repeatedly until it reaches a suitable exit criterion. Naïvely evaluating\n\/\/ the function N times for each iteration would be wasteful. Assume that we\n\/\/ have already evaluated the function at 0\/2 and 1\/2 (that is, s = 0 and 1 for\n\/\/ N = 2), we would evaluate it again at 0\/4 and 2\/4 for N = 4, and then proceed\n\/\/ with evaluations at 1\/4 and 3\/4. Overall, we would do roughly twice the\n\/\/ work.\n\/\/ Therefore, we cache the past evaluations. However, we do not want to use a\n\/\/ map and we do not want to do insertion in a vector, say, to squeeze 1\/4\n\/\/ between 0\/2 and 1\/2. So we append the result of evaluations to the cache\n\/\/ vector as we perform them. To fill the cache for N points, we recursively\n\/\/ fill it for N\/2 points (which yields all the values at s\/N for s even) and\n\/\/ then we append the values at s\/N for s odd. The order of the second part\n\/\/ matters. It is done by taking the indices of the first part (covering\n\/\/ [0\/N, (N\/2-1)\/N[) in bit-reversed order and for each index s appending the\n\/\/ value at (2 s + 1)\/N. This ensures that the entire array follows\n\/\/ bit-reversed ordering.\n\/\/ There is an extra wart: we need the value at N\/N, but it does not fit nicely\n\/\/ in the bit-reversed ordering. So we store it at position 0 in the cache, and\n\/\/ the regular cache starts at index 1.\n\/\/ Clients are expected to reserve (at least) points entries in the cache vector\n\/\/ for efficient heap allocation.\ntemplate<int points, typename Argument, typename Function>\nvoid FillClenshawCurtisCache(\n Function const& f,\n Argument const& lower_bound,\n Argument const& upper_bound,\n std::vector<std::invoke_result_t<Function, Argument>>&\n f_cos_N⁻¹π_bit_reversed) {\n \/\/ If we identify [lower_bound, upper_bound] with [-1, 1],\n \/\/ f_cos_N⁻¹π_bit_reversed contains f(cos πs\/N) in bit-reversed order of s.\n \/\/ We use a discrete Fourier transform rather than a cosine transform, see\n \/\/ [Gen72c], equation (3).\n\n \/\/ The cache already has all the data we need.\n if (f_cos_N⁻¹π_bit_reversed.size() >= points) {\n return;\n }\n\n constexpr int N = points - 1;\n static_assert(N >= 1);\n constexpr int log2_N = FloorLog2(N);\n static_assert(N == 1 << log2_N);\n\n Difference<Argument> const half_width = (upper_bound - lower_bound) \/ 2;\n constexpr Angle N⁻¹π = π * Radian \/ N;\n\n if constexpr (N == 1) {\n DCHECK(f_cos_N⁻¹π_bit_reversed.empty());\n \/\/ See above for the magic entry at index 0. The entry at index 1 is a bona\n \/\/ fide entry which will be used by the recursive calls.\n f_cos_N⁻¹π_bit_reversed.push_back(f(lower_bound)); \/\/ s = N.\n f_cos_N⁻¹π_bit_reversed.push_back(f(upper_bound)); \/\/ s = 0.\n } else {\n \/\/ Fill the first half of the cache, corresponding to s even for this value\n \/\/ of N.\n FillClenshawCurtisCache<N \/ 2 + 1>(f,\n lower_bound, upper_bound,\n f_cos_N⁻¹π_bit_reversed);\n \/\/ N\/2 evaluations for f(cos πs\/N) with s odd. Note the need to preserve\n \/\/ bit-reversed ordering.\n int reverse = 0;\n for (int evaluations = 0;\n evaluations < N \/ 2;\n ++evaluations, reverse = BitReversedIncrement(reverse, log2_N - 1)) {\n int const s = 2 * reverse + 1;\n f_cos_N⁻¹π_bit_reversed.push_back(\n f(lower_bound + half_width * (1 + Cos(N⁻¹π * s))));\n }\n }\n}\n\ntemplate<int points, typename Argument, typename Function>\nPrimitive<std::invoke_result_t<Function, Argument>, Argument>\nAutomaticClenshawCurtisImplementation(\n Function const& f,\n Argument const& lower_bound,\n Argument const& upper_bound,\n std::optional<double> const max_relative_error,\n std::optional<int> const max_points,\n Primitive<std::invoke_result_t<Function, Argument>, Argument> const\n previous_estimate,\n std::vector<std::invoke_result_t<Function, Argument>>&\n f_cos_N⁻¹π_bit_reversed) {\n using Result = Primitive<std::invoke_result_t<Function, Argument>, Argument>;\n\n Result const estimate =\n ClenshawCurtisImplementation<points>(\n f, lower_bound, upper_bound, f_cos_N⁻¹π_bit_reversed);\n\n \/\/ This is the naïve estimate mentioned in [Gen72b], p. 339.\n auto const absolute_error_estimate =\n Hilbert<Result>::Norm(previous_estimate - estimate);\n\n if ((!max_relative_error.has_value() ||\n absolute_error_estimate >\n max_relative_error.value() * Hilbert<Result>::Norm(estimate)) &&\n (!max_points.has_value() || points <= max_points.value())) {\n if constexpr (points > 1 << 24) {\n LOG(FATAL) << \"Too many refinements while integrating from \"\n << lower_bound << \" to \" << upper_bound;\n } else {\n f_cos_N⁻¹π_bit_reversed.reserve(2 * points - 1);\n return AutomaticClenshawCurtisImplementation<2 * points - 1>(\n f,\n lower_bound, upper_bound,\n max_relative_error, max_points,\n estimate,\n f_cos_N⁻¹π_bit_reversed);\n }\n }\n return estimate;\n}\n\ntemplate<int points, typename Argument, typename Function>\nPrimitive<std::invoke_result_t<Function, Argument>, Argument>\nClenshawCurtisImplementation(\n Function const& f,\n Argument const& lower_bound,\n Argument const& upper_bound,\n std::vector<std::invoke_result_t<Function, Argument>>&\n f_cos_N⁻¹π_bit_reversed) {\n \/\/ We follow the notation from [Gen72b] and [Gen72c].\n using Value = std::invoke_result_t<Function, Argument>;\n\n constexpr int N = points - 1;\n constexpr int log2_N = FloorLog2(N);\n\n Difference<Argument> const half_width = (upper_bound - lower_bound) \/ 2;\n constexpr Angle N⁻¹π = π * Radian \/ N;\n\n FillClenshawCurtisCache<points>(\n f, lower_bound, upper_bound, f_cos_N⁻¹π_bit_reversed);\n\n \/\/ TODO(phl): If might be possible to avoid copies since\n \/\/ f_cos_N⁻¹π_bit_reversed is tantalizing close to the order needed for the\n \/\/ FFT.\n std::vector<Value> f_cos_N⁻¹π;\n f_cos_N⁻¹π.resize(2 * N);\n \/\/ An index in f_cos_N⁻¹π in the order described by [Gen72b] and [Gen72c].\n int s = 0;\n \/\/ An index in f_cos_N⁻¹π_bit_reversed, corresponding to the order in which\n \/\/ the values were put in the cache. Note that entry 0 is special and holds\n \/\/ the value corresponding to s = N.\n for (int bit_reversed_s = 1;\n bit_reversed_s <= N;\n ++bit_reversed_s, s = BitReversedIncrement(s, log2_N)) {\n f_cos_N⁻¹π[s] = f_cos_N⁻¹π_bit_reversed[bit_reversed_s];\n if (s > 0) {\n f_cos_N⁻¹π[2 * N - s] = f_cos_N⁻¹π[s]; \/\/ [Gen72c] (5).\n }\n }\n f_cos_N⁻¹π[N] = f_cos_N⁻¹π_bit_reversed[0];\n\n auto const fft = std::make_unique<FastFourierTransform<Value, Angle, 2 * N>>(\n f_cos_N⁻¹π, N⁻¹π);\n auto const& a = *fft;\n\n \/\/ [Gen72b] equation (7), factoring out the division by N.\n Value Σʺ{};\n for (std::int64_t n = 0; n <= N; n += 2) {\n \/\/ The notation g is from [OLBC10], 3.5.17.\n int const gₙ = n == 0 || n == N ? 1 : 2;\n Σʺ += a[n].real_part() * gₙ \/ (1 - n * n);\n }\n Σʺ \/= N;\n\n return Σʺ * half_width;\n}\n\ntemplate<int points, typename Argument, typename Function>\nPrimitive<std::invoke_result_t<Function, Argument>, Argument> GaussLegendre(\n Function const& f,\n Argument const& lower_bound,\n Argument const& upper_bound) {\n static_assert(points < LegendreRoots.size,\n \"No table for Gauss-Legendre with the chosen number of points\");\n return Gauss<points>(f,\n lower_bound,\n upper_bound,\n LegendreRoots[points],\n GaussLegendreWeights[points]);\n}\n\ntemplate<int initial_points, typename Argument, typename Function>\nPrimitive<std::invoke_result_t<Function, Argument>, Argument>\nAutomaticClenshawCurtis(\n Function const& f,\n Argument const& lower_bound,\n Argument const& upper_bound,\n std::optional<double> const max_relative_error,\n std::optional<int> const max_points) {\n using Result = Primitive<std::invoke_result_t<Function, Argument>, Argument>;\n using Value = std::invoke_result_t<Function, Argument>;\n std::vector<Value> f_cos_N⁻¹π_bit_reversed;\n f_cos_N⁻¹π_bit_reversed.reserve(2 * initial_points - 1);\n Result const estimate = ClenshawCurtisImplementation<initial_points>(\n f, lower_bound, upper_bound, f_cos_N⁻¹π_bit_reversed);\n return AutomaticClenshawCurtisImplementation<2 * initial_points - 1>(\n f,\n lower_bound, upper_bound,\n max_relative_error, max_points,\n estimate,\n f_cos_N⁻¹π_bit_reversed);\n}\n\ntemplate<int points, typename Argument, typename Function>\nPrimitive<std::invoke_result_t<Function, Argument>, Argument> ClenshawCurtis(\n Function const& f,\n Argument const& lower_bound,\n Argument const& upper_bound) {\n using Value = std::invoke_result_t<Function, Argument>;\n std::vector<Value> f_cos_N⁻¹π_bit_reversed;\n f_cos_N⁻¹π_bit_reversed.reserve(points);\n return ClenshawCurtisImplementation<points>(\n f, lower_bound, upper_bound, f_cos_N⁻¹π_bit_reversed);\n}\n\ntemplate<typename Argument, typename Function>\nPrimitive<std::invoke_result_t<Function, Argument>, Argument> Midpoint(\n Function const& f,\n Argument const& lower_bound,\n Argument const& upper_bound,\n int const intervals) {\n Difference<Argument> const h = (upper_bound - lower_bound) \/ intervals;\n Primitive<std::invoke_result_t<Function, Argument>, Argument> result{};\n for (int i = 0; i < intervals; ++i) {\n result += f(lower_bound + (i + 0.5) * h) * h;\n }\n return result;\n}\n\n} \/\/ namespace internal_quadrature\n} \/\/ namespace quadrature\n} \/\/ namespace numerics\n} \/\/ namespace principia\n<|endoftext|>"} {"text":"<commit_before>\/*\n This file is part of Magnum.\n\n Copyright © 2010, 2011, 2012, 2013, 2014, 2015\n Vladimír Vondruš <mosra@centrum.cz>\n\n Permission is hereby granted, free of charge, to any person obtaining a\n copy of this software and associated documentation files (the \"Software\"),\n to deal in the Software without restriction, including without limitation\n the rights to use, copy, modify, merge, publish, distribute, sublicense,\n and\/or sell copies of the Software, and to permit persons to whom the\n Software is furnished to do so, subject to the following conditions:\n\n The above copyright notice and this permission notice shall be included\n in all copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n DEALINGS IN THE SOFTWARE.\n*\/\n\n#include <sstream>\n#include <Corrade\/Containers\/ArrayView.h>\n#include <Corrade\/TestSuite\/Tester.h>\n#include <Corrade\/Utility\/Directory.h>\n\n#include \"Magnum\/ColorFormat.h\"\n#include \"Magnum\/Trade\/ImageData.h\"\n#include \"MagnumPlugins\/TgaImporter\/TgaImporter.h\"\n\n#include \"configure.h\"\n\nnamespace Magnum { namespace Trade { namespace Test {\n\nclass TgaImporterTest: public TestSuite::Tester {\n public:\n TgaImporterTest();\n\n void openNonexistent();\n void openShort();\n void paletted();\n void compressed();\n\n void colorBits16();\n void colorBits24();\n void colorBits32();\n\n void grayscaleBits8();\n void grayscaleBits16();\n\n void file();\n};\n\nTgaImporterTest::TgaImporterTest() {\n addTests({&TgaImporterTest::openNonexistent,\n &TgaImporterTest::openShort,\n &TgaImporterTest::paletted,\n &TgaImporterTest::compressed,\n\n &TgaImporterTest::colorBits16,\n &TgaImporterTest::colorBits24,\n &TgaImporterTest::colorBits32,\n\n &TgaImporterTest::grayscaleBits8,\n &TgaImporterTest::grayscaleBits16,\n\n &TgaImporterTest::file});\n}\n\nvoid TgaImporterTest::openNonexistent() {\n std::ostringstream debug;\n Error::setOutput(&debug);\n\n TgaImporter importer;\n CORRADE_VERIFY(!importer.openFile(\"nonexistent.file\"));\n CORRADE_COMPARE(debug.str(), \"Trade::TgaImporter::openFile(): cannot open file nonexistent.file\\n\");\n}\n\nvoid TgaImporterTest::openShort() {\n TgaImporter importer;\n const char data[] = { 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };\n CORRADE_VERIFY(importer.openData(data));\n\n std::ostringstream debug;\n Error::setOutput(&debug);\n CORRADE_VERIFY(!importer.image2D(0));\n CORRADE_COMPARE(debug.str(), \"Trade::TgaImporter::image2D(): the file is too short: 17 bytes\\n\");\n}\n\nvoid TgaImporterTest::paletted() {\n TgaImporter importer;\n const char data[] = { 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };\n CORRADE_VERIFY(importer.openData(data));\n\n std::ostringstream debug;\n Error::setOutput(&debug);\n CORRADE_VERIFY(!importer.image2D(0));\n CORRADE_COMPARE(debug.str(), \"Trade::TgaImporter::image2D(): paletted files are not supported\\n\");\n}\n\nvoid TgaImporterTest::compressed() {\n TgaImporter importer;\n const char data[] = { 0, 0, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };\n CORRADE_VERIFY(importer.openData(data));\n\n std::ostringstream debug;\n Error::setOutput(&debug);\n CORRADE_VERIFY(!importer.image2D(0));\n CORRADE_COMPARE(debug.str(), \"Trade::TgaImporter::image2D(): unsupported (compressed?) image type: 9\\n\");\n}\n\nvoid TgaImporterTest::colorBits16() {\n TgaImporter importer;\n const char data[] = { 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 16, 0 };\n CORRADE_VERIFY(importer.openData(data));\n\n std::ostringstream debug;\n Error::setOutput(&debug);\n CORRADE_VERIFY(!importer.image2D(0));\n CORRADE_COMPARE(debug.str(), \"Trade::TgaImporter::image2D(): unsupported color bits-per-pixel: 16\\n\");\n}\n\nvoid TgaImporterTest::colorBits24() {\n TgaImporter importer;\n const char data[] = {\n 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 3, 0, 24, 0,\n 1, 2, 3, 2, 3, 4,\n 3, 4, 5, 4, 5, 6,\n 5, 6, 7, 6, 7, 8\n };\n const char pixels[] = {\n 3, 2, 1, 4, 3, 2,\n 5, 4, 3, 6, 5, 4,\n 7, 6, 5, 8, 7, 6\n };\n CORRADE_VERIFY(importer.openData(data));\n\n std::optional<Trade::ImageData2D> image = importer.image2D(0);\n CORRADE_VERIFY(image);\n CORRADE_COMPARE(image->format(), ColorFormat::RGB);\n CORRADE_COMPARE(image->size(), Vector2i(2, 3));\n CORRADE_COMPARE(image->type(), ColorType::UnsignedByte);\n CORRADE_COMPARE((std::string{image->data(), 2*3*3}),\n (std::string{pixels, 2*3*3}));\n}\n\nvoid TgaImporterTest::colorBits32() {\n TgaImporter importer;\n const char data[] = {\n 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 3, 0, 32, 0,\n 1, 2, 3, 1, 2, 3, 4, 1,\n 3, 4, 5, 1, 4, 5, 6, 1,\n 5, 6, 7, 1, 6, 7, 8, 1\n };\n const char pixels[] = {\n 3, 2, 1, 1, 4, 3, 2, 1,\n 5, 4, 3, 1, 6, 5, 4, 1,\n 7, 6, 5, 1, 8, 7, 6, 1\n };\n CORRADE_VERIFY(importer.openData(data));\n\n std::optional<Trade::ImageData2D> image = importer.image2D(0);\n CORRADE_VERIFY(image);\n CORRADE_COMPARE(image->format(), ColorFormat::RGBA);\n CORRADE_COMPARE(image->size(), Vector2i(2, 3));\n CORRADE_COMPARE(image->type(), ColorType::UnsignedByte);\n CORRADE_COMPARE((std::string{image->data(), 2*3*3}),\n (std::string{pixels, 2*3*3}));\n}\n\nvoid TgaImporterTest::grayscaleBits8() {\n TgaImporter importer;\n const char data[] = {\n 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 3, 0, 8, 0,\n 1, 2,\n 3, 4,\n 5, 6\n };\n CORRADE_VERIFY(importer.openData(data));\n\n std::optional<Trade::ImageData2D> image = importer.image2D(0);\n CORRADE_VERIFY(image);\n #ifndef MAGNUM_TARGET_GLES2\n CORRADE_COMPARE(image->format(), ColorFormat::Red);\n #else\n CORRADE_COMPARE(image->format(), ColorFormat::Luminance);\n #endif\n CORRADE_COMPARE(image->size(), Vector2i(2, 3));\n CORRADE_COMPARE(image->type(), ColorType::UnsignedByte);\n CORRADE_COMPARE((std::string{image->data(), 2*3}),\n (std::string{data + 18, 2*3}));\n}\n\nvoid TgaImporterTest::grayscaleBits16() {\n TgaImporter importer;\n const char data[] = { 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 16, 0 };\n CORRADE_VERIFY(importer.openData(data));\n\n std::ostringstream debug;\n Error::setOutput(&debug);\n CORRADE_VERIFY(!importer.image2D(0));\n CORRADE_COMPARE(debug.str(), \"Trade::TgaImporter::image2D(): unsupported grayscale bits-per-pixel: 16\\n\");\n}\n\nvoid TgaImporterTest::file() {\n TgaImporter importer;\n const char data[] = {\n 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 3, 0, 8, 0,\n 1, 2,\n 3, 4,\n 5, 6\n };\n CORRADE_VERIFY(importer.openFile(Utility::Directory::join(TGAIMPORTER_TEST_DIR, \"file.tga\")));\n\n std::optional<Trade::ImageData2D> image = importer.image2D(0);\n CORRADE_VERIFY(image);\n #ifndef MAGNUM_TARGET_GLES2\n CORRADE_COMPARE(image->format(), ColorFormat::Red);\n #else\n CORRADE_COMPARE(image->format(), ColorFormat::Luminance);\n #endif\n CORRADE_COMPARE(image->size(), Vector2i(2, 3));\n CORRADE_COMPARE(image->type(), ColorType::UnsignedByte);\n CORRADE_COMPARE((std::string{image->data(), 2*3}),\n (std::string{data + 18, 2*3}));\n}\n\n}}}\n\nCORRADE_TEST_MAIN(Magnum::Trade::Test::TgaImporterTest)\n<commit_msg>TgaImporter: simplified data comparison in test.<commit_after>\/*\n This file is part of Magnum.\n\n Copyright © 2010, 2011, 2012, 2013, 2014, 2015\n Vladimír Vondruš <mosra@centrum.cz>\n\n Permission is hereby granted, free of charge, to any person obtaining a\n copy of this software and associated documentation files (the \"Software\"),\n to deal in the Software without restriction, including without limitation\n the rights to use, copy, modify, merge, publish, distribute, sublicense,\n and\/or sell copies of the Software, and to permit persons to whom the\n Software is furnished to do so, subject to the following conditions:\n\n The above copyright notice and this permission notice shall be included\n in all copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n DEALINGS IN THE SOFTWARE.\n*\/\n\n#include <sstream>\n#include <Corrade\/Containers\/ArrayView.h>\n#include <Corrade\/TestSuite\/Tester.h>\n#include <Corrade\/TestSuite\/Compare\/Container.h>\n#include <Corrade\/Utility\/Directory.h>\n\n#include \"Magnum\/ColorFormat.h\"\n#include \"Magnum\/Trade\/ImageData.h\"\n#include \"MagnumPlugins\/TgaImporter\/TgaImporter.h\"\n\n#include \"configure.h\"\n\nnamespace Magnum { namespace Trade { namespace Test {\n\nclass TgaImporterTest: public TestSuite::Tester {\n public:\n TgaImporterTest();\n\n void openNonexistent();\n void openShort();\n void paletted();\n void compressed();\n\n void colorBits16();\n void colorBits24();\n void colorBits32();\n\n void grayscaleBits8();\n void grayscaleBits16();\n\n void file();\n};\n\nTgaImporterTest::TgaImporterTest() {\n addTests({&TgaImporterTest::openNonexistent,\n &TgaImporterTest::openShort,\n &TgaImporterTest::paletted,\n &TgaImporterTest::compressed,\n\n &TgaImporterTest::colorBits16,\n &TgaImporterTest::colorBits24,\n &TgaImporterTest::colorBits32,\n\n &TgaImporterTest::grayscaleBits8,\n &TgaImporterTest::grayscaleBits16,\n\n &TgaImporterTest::file});\n}\n\nvoid TgaImporterTest::openNonexistent() {\n std::ostringstream debug;\n Error::setOutput(&debug);\n\n TgaImporter importer;\n CORRADE_VERIFY(!importer.openFile(\"nonexistent.file\"));\n CORRADE_COMPARE(debug.str(), \"Trade::TgaImporter::openFile(): cannot open file nonexistent.file\\n\");\n}\n\nvoid TgaImporterTest::openShort() {\n TgaImporter importer;\n const char data[] = { 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };\n CORRADE_VERIFY(importer.openData(data));\n\n std::ostringstream debug;\n Error::setOutput(&debug);\n CORRADE_VERIFY(!importer.image2D(0));\n CORRADE_COMPARE(debug.str(), \"Trade::TgaImporter::image2D(): the file is too short: 17 bytes\\n\");\n}\n\nvoid TgaImporterTest::paletted() {\n TgaImporter importer;\n const char data[] = { 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };\n CORRADE_VERIFY(importer.openData(data));\n\n std::ostringstream debug;\n Error::setOutput(&debug);\n CORRADE_VERIFY(!importer.image2D(0));\n CORRADE_COMPARE(debug.str(), \"Trade::TgaImporter::image2D(): paletted files are not supported\\n\");\n}\n\nvoid TgaImporterTest::compressed() {\n TgaImporter importer;\n const char data[] = { 0, 0, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };\n CORRADE_VERIFY(importer.openData(data));\n\n std::ostringstream debug;\n Error::setOutput(&debug);\n CORRADE_VERIFY(!importer.image2D(0));\n CORRADE_COMPARE(debug.str(), \"Trade::TgaImporter::image2D(): unsupported (compressed?) image type: 9\\n\");\n}\n\nvoid TgaImporterTest::colorBits16() {\n TgaImporter importer;\n const char data[] = { 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 16, 0 };\n CORRADE_VERIFY(importer.openData(data));\n\n std::ostringstream debug;\n Error::setOutput(&debug);\n CORRADE_VERIFY(!importer.image2D(0));\n CORRADE_COMPARE(debug.str(), \"Trade::TgaImporter::image2D(): unsupported color bits-per-pixel: 16\\n\");\n}\n\nvoid TgaImporterTest::colorBits24() {\n TgaImporter importer;\n const char data[] = {\n 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 3, 0, 24, 0,\n 1, 2, 3, 2, 3, 4,\n 3, 4, 5, 4, 5, 6,\n 5, 6, 7, 6, 7, 8\n };\n const char pixels[] = {\n 3, 2, 1, 4, 3, 2,\n 5, 4, 3, 6, 5, 4,\n 7, 6, 5, 8, 7, 6\n };\n CORRADE_VERIFY(importer.openData(data));\n\n std::optional<Trade::ImageData2D> image = importer.image2D(0);\n CORRADE_VERIFY(image);\n CORRADE_COMPARE(image->format(), ColorFormat::RGB);\n CORRADE_COMPARE(image->size(), Vector2i(2, 3));\n CORRADE_COMPARE(image->type(), ColorType::UnsignedByte);\n CORRADE_COMPARE_AS(image->data(), Containers::ArrayView<const char>{pixels},\n TestSuite::Compare::Container);\n}\n\nvoid TgaImporterTest::colorBits32() {\n TgaImporter importer;\n const char data[] = {\n 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 3, 0, 32, 0,\n 1, 2, 3, 1, 2, 3, 4, 1,\n 3, 4, 5, 1, 4, 5, 6, 1,\n 5, 6, 7, 1, 6, 7, 8, 1\n };\n const char pixels[] = {\n 3, 2, 1, 1, 4, 3, 2, 1,\n 5, 4, 3, 1, 6, 5, 4, 1,\n 7, 6, 5, 1, 8, 7, 6, 1\n };\n CORRADE_VERIFY(importer.openData(data));\n\n std::optional<Trade::ImageData2D> image = importer.image2D(0);\n CORRADE_VERIFY(image);\n CORRADE_COMPARE(image->format(), ColorFormat::RGBA);\n CORRADE_COMPARE(image->size(), Vector2i(2, 3));\n CORRADE_COMPARE(image->type(), ColorType::UnsignedByte);\n CORRADE_COMPARE_AS(image->data(), Containers::ArrayView<const char>{pixels},\n TestSuite::Compare::Container);\n}\n\nvoid TgaImporterTest::grayscaleBits8() {\n TgaImporter importer;\n const char data[] = {\n 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 3, 0, 8, 0,\n 1, 2,\n 3, 4,\n 5, 6\n };\n CORRADE_VERIFY(importer.openData(data));\n\n std::optional<Trade::ImageData2D> image = importer.image2D(0);\n CORRADE_VERIFY(image);\n #ifndef MAGNUM_TARGET_GLES2\n CORRADE_COMPARE(image->format(), ColorFormat::Red);\n #else\n CORRADE_COMPARE(image->format(), ColorFormat::Luminance);\n #endif\n CORRADE_COMPARE(image->size(), Vector2i(2, 3));\n CORRADE_COMPARE(image->type(), ColorType::UnsignedByte);\n CORRADE_COMPARE_AS(image->data(), Containers::ArrayView<const char>{data}.suffix(18),\n TestSuite::Compare::Container);\n}\n\nvoid TgaImporterTest::grayscaleBits16() {\n TgaImporter importer;\n const char data[] = { 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 16, 0 };\n CORRADE_VERIFY(importer.openData(data));\n\n std::ostringstream debug;\n Error::setOutput(&debug);\n CORRADE_VERIFY(!importer.image2D(0));\n CORRADE_COMPARE(debug.str(), \"Trade::TgaImporter::image2D(): unsupported grayscale bits-per-pixel: 16\\n\");\n}\n\nvoid TgaImporterTest::file() {\n TgaImporter importer;\n const char data[] = {\n 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 3, 0, 8, 0,\n 1, 2,\n 3, 4,\n 5, 6\n };\n CORRADE_VERIFY(importer.openFile(Utility::Directory::join(TGAIMPORTER_TEST_DIR, \"file.tga\")));\n\n std::optional<Trade::ImageData2D> image = importer.image2D(0);\n CORRADE_VERIFY(image);\n #ifndef MAGNUM_TARGET_GLES2\n CORRADE_COMPARE(image->format(), ColorFormat::Red);\n #else\n CORRADE_COMPARE(image->format(), ColorFormat::Luminance);\n #endif\n CORRADE_COMPARE(image->size(), Vector2i(2, 3));\n CORRADE_COMPARE(image->type(), ColorType::UnsignedByte);\n CORRADE_COMPARE_AS(image->data(), Containers::ArrayView<const char>{data}.suffix(18),\n TestSuite::Compare::Container);\n}\n\n}}}\n\nCORRADE_TEST_MAIN(Magnum::Trade::Test::TgaImporterTest)\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: gtkobject.hxx,v $\n *\n * $Revision: 1.4 $\n *\n * last change: $Author: rt $ $Date: 2005-09-09 12:52:22 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef _VCL_GTKOBJECT_HXX\n#define _VCL_GTKOBJECT_HXX\n\n#ifndef _SV_SV_H\n#include <sv.h>\n#endif\n#ifndef _SV_SYSDATA_HXX\n#include <sysdata.hxx>\n#endif\n#ifndef _SV_SALOBJ_HXX\n#include <salobj.hxx>\n#endif\n#ifndef _VCL_GTKFRAME_HXX\n#include <plugins\/gtk\/gtkframe.hxx>\n#endif\n\nclass GtkSalObject : public SalObject\n{\n SystemChildData m_aSystemData;\n GtkWidget* m_pSocket;\n GdkRegion* m_pRegion;\n\n \/\/ signals\n static gboolean signalButton( GtkWidget*, GdkEventButton*, gpointer );\n static gboolean signalFocus( GtkWidget*, GdkEventFocus*, gpointer );\n static void signalDestroy( GtkObject*, gpointer );\npublic:\n GtkSalObject( GtkSalFrame* pParent );\n virtual ~GtkSalObject();\n\n \/\/ overload all pure virtual methods\n virtual void ResetClipRegion();\n virtual USHORT GetClipRegionType();\n virtual void BeginSetClipRegion( ULONG nRects );\n virtual void UnionClipRegion( long nX, long nY, long nWidth, long nHeight );\n virtual void EndSetClipRegion();\n\n virtual void SetPosSize( long nX, long nY, long nWidth, long nHeight );\n virtual void Show( BOOL bVisible );\n virtual void Enable( BOOL nEnable );\n virtual void GrabFocus();\n\n virtual void SetBackground();\n virtual void SetBackground( SalColor nSalColor );\n\n virtual const SystemEnvData* GetSystemData() const;\n\n};\n\n#endif \/\/ _SV_SALOBJ_H\n<commit_msg>INTEGRATION: CWS vgbugs07 (1.4.606); FILE MERGED 2007\/06\/04 13:29:58 vg 1.4.606.1: #i76605# Remove -I ...\/inc\/module hack introduced by hedaburemove01<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: gtkobject.hxx,v $\n *\n * $Revision: 1.5 $\n *\n * last change: $Author: hr $ $Date: 2007-06-27 20:45:02 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef _VCL_GTKOBJECT_HXX\n#define _VCL_GTKOBJECT_HXX\n\n#ifndef _SV_SV_H\n#include <vcl\/sv.h>\n#endif\n#ifndef _SV_SYSDATA_HXX\n#include <sysdata.hxx>\n#endif\n#ifndef _SV_SALOBJ_HXX\n#include <vcl\/salobj.hxx>\n#endif\n#ifndef _VCL_GTKFRAME_HXX\n#include <plugins\/gtk\/gtkframe.hxx>\n#endif\n\nclass GtkSalObject : public SalObject\n{\n SystemChildData m_aSystemData;\n GtkWidget* m_pSocket;\n GdkRegion* m_pRegion;\n\n \/\/ signals\n static gboolean signalButton( GtkWidget*, GdkEventButton*, gpointer );\n static gboolean signalFocus( GtkWidget*, GdkEventFocus*, gpointer );\n static void signalDestroy( GtkObject*, gpointer );\npublic:\n GtkSalObject( GtkSalFrame* pParent );\n virtual ~GtkSalObject();\n\n \/\/ overload all pure virtual methods\n virtual void ResetClipRegion();\n virtual USHORT GetClipRegionType();\n virtual void BeginSetClipRegion( ULONG nRects );\n virtual void UnionClipRegion( long nX, long nY, long nWidth, long nHeight );\n virtual void EndSetClipRegion();\n\n virtual void SetPosSize( long nX, long nY, long nWidth, long nHeight );\n virtual void Show( BOOL bVisible );\n virtual void Enable( BOOL nEnable );\n virtual void GrabFocus();\n\n virtual void SetBackground();\n virtual void SetBackground( SalColor nSalColor );\n\n virtual const SystemEnvData* GetSystemData() const;\n\n};\n\n#endif \/\/ _SV_SALOBJ_H\n<|endoftext|>"} {"text":"<commit_before>#include \"GLBlaat\/GL.h\"\r\n\r\n#include \"NQVTKWidget.h\"\r\n#include \"NQVTKWidget.moc\"\r\n\r\n#include \"Math\/Vector3.h\"\r\n\r\n#include \"Rendering\/Renderer.h\"\r\n#include \"Rendering\/Camera.h\"\r\n#include \"Rendering\/PolyData.h\"\r\n#include \"Rendering\/ImageDataTexture3D.h\"\r\n\r\n#include \"Styles\/DepthPeeling.h\"\r\n#include \"Styles\/IBIS.h\"\r\n#include \"Styles\/DistanceFields.h\"\r\n\r\n#include <vtkSmartPointer.h>\r\n#include <vtkXMLPolyDataReader.h>\r\n#include <vtkXMLImageDataReader.h>\r\n\r\n#include <QKeyEvent>\r\n#include <QMouseEvent>\r\n#include <QApplication>\r\n#include <QStringList>\r\n#include <QGLFormat>\r\n#include <QDateTime>\r\n\r\n#include <algorithm>\r\n\r\n\/\/ ----------------------------------------------------------------------------\r\nNQVTKWidget::NQVTKWidget(QWidget *parent \/* = 0 *\/)\r\n: QGLWidget(QGLFormat(QGL::AlphaChannel), parent), renderer(0), initialized(false)\r\n{\r\n\tsetMouseTracking(true);\r\n}\r\n\r\n\/\/ ----------------------------------------------------------------------------\r\nNQVTKWidget::~NQVTKWidget()\r\n{\r\n\tif (renderer) delete renderer;\r\n}\r\n\r\n\/\/ ----------------------------------------------------------------------------\r\nvoid NQVTKWidget::initializeGL()\r\n{\r\n\tif (glewInit() != GLEW_OK)\r\n\t{\r\n\t\tqDebug(\"Failed to initialize GLEW!\");\r\n\t\treturn;\r\n\t}\r\n\r\n\tqDebug(\"Initializing renderer...\");\r\n\tif (!renderer) renderer = new NQVTK::Renderer();\r\n\tNQVTK::Styles::DistanceFields *style = new NQVTK::Styles::DistanceFields();\r\n\tthis->distfieldstyle = style;\r\n\trenderer->SetStyle(style);\r\n\tinitialized = renderer->Initialize();\r\n\r\n\tif (!initialized)\r\n\t{\r\n\t\tqDebug(\"Failed to initialize renderer...\");\r\n\t}\r\n\t\r\n\tqDebug(\"Creating and adding renderables...\");\r\n\tQStringList args = qApp->arguments();\r\n\tif (args.size() < 2) \r\n\t{\r\n\t\tqDebug(\"No arguments supplied, using default data...\");\r\n\t\t\/\/ Set default testing data (on Vliet)\r\n\t\t\/\/* - msdata\r\n\t\targs.append(\"D:\/Data\/msdata\/T2W\/T2W_images_normalized\/T2W_normalized_GM\/Gwn0200-TP_2004_07_08-T2-textured.vtp\");\r\n\t\targs.append(\"D:\/Data\/msdata\/T2W\/T2W_images_normalized\/T2W_normalized_GM\/Gwn0200-TP_2004_08_02-T2-textured.vtp\");\r\n\t\t\/\/*\/\r\n\t\t\/* Cartilage\r\n\t\targs.append(\"D:\/Data\/Cartilage\/Lorena\/femoral2.vtp\");\r\n\t\targs.append(\"D:\/Data\/Cartilage\/Lorena\/femoral1.vtp\");\r\n\t\t\/\/*\/\r\n\t}\r\n\t\/\/ Load the polydata\r\n\tNQVTK::Vector3 colors[] = {\r\n\t\tNQVTK::Vector3(1.0, 0.9, 0.4), \r\n\t\tNQVTK::Vector3(0.3, 0.6, 1.0)\r\n\t};\r\n\tint i = 0;\r\n\tfor (QStringList::const_iterator it = args.begin() + 1; it != args.end(); ++it)\r\n\t{\r\n\t\tqDebug(\"Loading #%d...\", i);\r\n\t\tvtkSmartPointer<vtkXMLPolyDataReader> reader = \r\n\t\t\tvtkSmartPointer<vtkXMLPolyDataReader>::New();\r\n\t\treader->SetFileName(it->toUtf8());\r\n\t\treader->Update();\r\n\t\tNQVTK::Renderable *renderable = new NQVTK::PolyData(reader->GetOutput());\r\n\t\trenderable->color = colors[std::min(i, 1)];\r\n\t\trenderable->opacity = 0.3;\r\n\t\trenderer->AddRenderable(renderable);\r\n\t\t++i;\r\n\t}\r\n\r\n\t\/\/* For testing purposes: load and set the distance fields\r\n\t\/\/ NOTE: assingments are flipped because object 1 should use distfield 0\r\n\t{\r\n\t\tqDebug(\"Loading distance field 0...\");\r\n\t\tvtkSmartPointer<vtkXMLImageDataReader> reader = \r\n\t\t\tvtkSmartPointer<vtkXMLImageDataReader>::New();\r\n\t\treader->SetFileName(\r\n\t\t\t\"D:\/Data\/msdata\/T2W\/T2W_images_normalized\/T2W_normalized_GM\/Gwn0200-TP_2004_07_08-T2-dist256.vti\");\r\n\t\treader->Update();\r\n\t\tGLTexture *tex = NQVTK::ImageDataTexture3D::New(reader->GetOutput());\r\n\t\tassert(tex);\r\n\t\tstyle->SetDistanceField(1, tex);\r\n\t}\r\n\t{\r\n\t\tqDebug(\"Loading distance field 1...\");\r\n\t\tvtkSmartPointer<vtkXMLImageDataReader> reader = \r\n\t\t\tvtkSmartPointer<vtkXMLImageDataReader>::New();\r\n\t\treader->SetFileName(\r\n\t\t\t\"D:\/Data\/msdata\/T2W\/T2W_images_normalized\/T2W_normalized_GM\/Gwn0200-TP_2004_08_02-T2-dist256.vti\");\r\n\t\treader->Update();\r\n\t\tGLTexture *tex = NQVTK::ImageDataTexture3D::New(reader->GetOutput());\r\n\t\tassert(tex);\r\n\t\tstyle->SetDistanceField(0, tex);\r\n\t}\r\n\t\/\/*\/\r\n\r\n\t\/\/ Render-on-idle timer\r\n\tstartTimer(0);\r\n\t\/\/ FPS display timer\r\n\tfpsTimerId = startTimer(1000);\r\n\tframes = 0;\r\n\r\n\tqDebug(\"Init done!\");\r\n}\r\n\r\n\/\/ ----------------------------------------------------------------------------\r\nvoid NQVTKWidget::resizeGL(int w, int h)\r\n{\r\n\trenderer->Resize(w, h);\r\n}\r\n\r\n\/\/ ----------------------------------------------------------------------------\r\nvoid NQVTKWidget::paintGL()\r\n{\r\n\tif (initialized) \r\n\t{\r\n\t\trenderer->Draw();\r\n\t}\r\n\telse\r\n\t{\r\n\t\trenderer->Clear();\r\n\t}\r\n\t++frames;\r\n}\r\n\r\n\/\/ ----------------------------------------------------------------------------\r\nvoid NQVTKWidget::timerEvent(QTimerEvent *event)\r\n{\r\n\tif (event->timerId() == fpsTimerId)\r\n\t{\r\n\t\t\/\/ Update FPS display\r\n\t\temit fpsChanged(frames);\r\n\t\tframes = 0;\r\n\t}\r\n\telse\r\n\t{\r\n\t\t\/\/ Update on idle\r\n\t\tupdateGL();\r\n\t}\r\n}\r\n\r\n\/\/ ----------------------------------------------------------------------------\r\nvoid NQVTKWidget::keyPressEvent(QKeyEvent *event)\r\n{\r\n\t\/\/ Quit on Escape\r\n\tswitch (event->key())\r\n\t{\r\n\tcase Qt::Key_Escape:\r\n\t\tqApp->quit();\r\n\t\tbreak;\r\n\tcase Qt::Key_C:\r\n\t\t{\r\n\t\t\tQDateTime now = QDateTime::currentDateTime();\r\n\t\t\tQImage screenshot = this->grabFrameBuffer(true);\r\n\t\t\t\/\/ Fix alpha values\r\n\t\t\tscreenshot.invertPixels(QImage::InvertRgba);\r\n\t\t\tscreenshot.invertPixels(QImage::InvertRgb);\r\n\t\t\t\/\/ Save it\r\n\t\t\tscreenshot.save(QString(\"NQVTK-%1.png\").arg(\r\n\t\t\t\tnow.toString(\"yyMMdd-hhmmss\")), \"PNG\");\r\n\t\t\tbreak;\r\n\t\t}\r\n\tcase Qt::Key_R:\r\n\t\trenderer->ResetRenderables();\r\n\t\tbreak;\r\n\tcase Qt::Key_1:\r\n\t\t{\r\n\t\t\tNQVTK::Renderable *ren = renderer->GetRenderable(0);\r\n\t\t\tif (ren) ren->visible = !ren->visible;\r\n\t\t}\r\n\t\tbreak;\r\n\tcase Qt::Key_2:\r\n\t\t{\r\n\t\t\tNQVTK::Renderable *ren = renderer->GetRenderable(1);\r\n\t\t\tif (ren) ren->visible = !ren->visible;\r\n\t\t}\r\n\t\tbreak;\r\n\tcase Qt::Key_F1:\r\n\t\tinitialized = renderer->SetStyle(new NQVTK::Styles::DepthPeeling());\r\n\t\tbreak;\r\n\tcase Qt::Key_F2:\r\n\t\tinitialized = renderer->SetStyle(new NQVTK::Styles::IBIS());\r\n\t\tbreak;\r\n\tcase Qt::Key_F3:\r\n\t\tdistfieldstyle = new NQVTK::Styles::DistanceFields();\r\n\t\tinitialized = renderer->SetStyle(distfieldstyle);\r\n\t\tbreak;\r\n\tdefault:\r\n\t\tevent->ignore();\r\n\t\treturn;\r\n\t}\r\n\tevent->accept();\r\n}\r\n\r\n\/\/ ----------------------------------------------------------------------------\r\nvoid NQVTKWidget::mouseMoveEvent(QMouseEvent *event)\r\n{\r\n\tif (event->modifiers() & Qt::ControlModifier) \r\n\t{\r\n\t\tNQVTK::Renderable *renderable = renderer->GetRenderable(0);\r\n\t\t\/\/ Mouse controls object 0\r\n\t\tif (renderable && event->buttons() & Qt::LeftButton)\r\n\t\t{\r\n\t\t\t\/\/ Rotate\r\n\t\t\trenderable->rotateY += event->x() - lastX;\r\n\t\t\trenderable->rotateX -= event->y() - lastY;\r\n\r\n\t\t\tif (renderable->rotateX > 80.0) \r\n\t\t\t{\r\n\t\t\t\trenderable->rotateX = 80.0;\r\n\t\t\t}\r\n\t\t\tif (renderable->rotateX < -80.0) \r\n\t\t\t{\r\n\t\t\t\trenderable->rotateX = -80.0;\r\n\t\t\t}\r\n\t\t}\r\n\t\tif (renderable && event->buttons() & Qt::MidButton)\r\n\t\t{\r\n\t\t\t\/\/ TODO: make translation relative to window\r\n\t\t\tNQVTK::Vector3 right = NQVTK::Vector3(1.0, 0.0, 0.0);\r\n\t\t\tNQVTK::Vector3 up = NQVTK::Vector3(0.0, 1.0, 0.0);\r\n\t\t\tdouble factor = 0.6;\r\n\t\t\t\/\/ Translate\r\n\t\t\trenderable->position += \r\n\t\t\t\t(lastX - event->x()) * factor * right +\r\n\t\t\t\t(lastY - event->y()) * factor * up;\r\n\t\t}\r\n\t}\r\n\telse\r\n\t{\r\n\t\t\/\/ Mouse controls camera\r\n\t\tif (event->buttons() & Qt::LeftButton)\r\n\t\t{\r\n\t\t\t\/\/ Rotate\r\n\t\t\trenderer->GetCamera()->rotateY += event->x() - lastX;\r\n\t\t\trenderer->GetCamera()->rotateX -= event->y() - lastY;\r\n\r\n\t\t\tif (renderer->GetCamera()->rotateX > 80.0) \r\n\t\t\t{\r\n\t\t\t\trenderer->GetCamera()->rotateX = 80.0;\r\n\t\t\t}\r\n\t\t\tif (renderer->GetCamera()->rotateX < -80.0) \r\n\t\t\t{\r\n\t\t\t\trenderer->GetCamera()->rotateX = -80.0;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tif (event->buttons() & Qt::RightButton)\r\n\t\t{\r\n\t\t\t\/\/ Zoom\r\n\t\t\trenderer->GetCamera()->zoom += (event->y() - lastY) * 0.01f;\r\n\t\t\tif (renderer->GetCamera()->zoom < 0.05) \r\n\t\t\t{\r\n\t\t\t\trenderer->GetCamera()->zoom = 0.05;\r\n\t\t\t}\r\n\t\t\tif (renderer->GetCamera()->zoom > 20.0) \r\n\t\t\t{\r\n\t\t\t\trenderer->GetCamera()->zoom = 20.0;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\tlastX = event->x();\r\n\tlastY = event->y();\r\n\r\n\tevent->accept();\r\n}\r\n<commit_msg>Added command line parsing for distance fields.<commit_after>#include \"GLBlaat\/GL.h\"\r\n\r\n#include \"NQVTKWidget.h\"\r\n#include \"NQVTKWidget.moc\"\r\n\r\n#include \"Math\/Vector3.h\"\r\n\r\n#include \"Rendering\/Renderer.h\"\r\n#include \"Rendering\/Camera.h\"\r\n#include \"Rendering\/PolyData.h\"\r\n#include \"Rendering\/ImageDataTexture3D.h\"\r\n\r\n#include \"Styles\/DepthPeeling.h\"\r\n#include \"Styles\/IBIS.h\"\r\n#include \"Styles\/DistanceFields.h\"\r\n\r\n#include <vtkSmartPointer.h>\r\n#include <vtkXMLPolyDataReader.h>\r\n#include <vtkXMLImageDataReader.h>\r\n\r\n#include <QKeyEvent>\r\n#include <QMouseEvent>\r\n#include <QApplication>\r\n#include <QStringList>\r\n#include <QGLFormat>\r\n#include <QDateTime>\r\n\r\n#include <algorithm>\r\n\r\n\/\/ ----------------------------------------------------------------------------\r\nNQVTKWidget::NQVTKWidget(QWidget *parent \/* = 0 *\/)\r\n: QGLWidget(QGLFormat(QGL::AlphaChannel), parent), renderer(0), initialized(false)\r\n{\r\n\tsetMouseTracking(true);\r\n}\r\n\r\n\/\/ ----------------------------------------------------------------------------\r\nNQVTKWidget::~NQVTKWidget()\r\n{\r\n\tif (renderer) delete renderer;\r\n}\r\n\r\n\/\/ ----------------------------------------------------------------------------\r\nvoid NQVTKWidget::initializeGL()\r\n{\r\n\tif (glewInit() != GLEW_OK)\r\n\t{\r\n\t\tqDebug(\"Failed to initialize GLEW!\");\r\n\t\treturn;\r\n\t}\r\n\r\n\tqDebug(\"Initializing renderer...\");\r\n\tif (!renderer) renderer = new NQVTK::Renderer();\r\n\tNQVTK::Styles::DistanceFields *style = new NQVTK::Styles::DistanceFields();\r\n\tthis->distfieldstyle = style;\r\n\trenderer->SetStyle(style);\r\n\tinitialized = renderer->Initialize();\r\n\r\n\tif (!initialized)\r\n\t{\r\n\t\tqDebug(\"Failed to initialize renderer...\");\r\n\t}\r\n\t\r\n\tqDebug(\"Creating and adding renderables...\");\r\n\tQStringList args = qApp->arguments();\r\n\tif (args.size() < 2) \r\n\t{\r\n\t\tqDebug(\"No arguments supplied, using default data...\");\r\n\t\t\/\/ Set default testing data (on Vliet)\r\n\t\t\/\/* - msdata\r\n\t\targs.append(\"D:\/Data\/msdata\/T2W\/T2W_images_normalized\/T2W_normalized_GM\/Gwn0200-TP_2004_07_08-T2-textured.vtp\");\r\n\t\targs.append(\"D:\/Data\/msdata\/T2W\/T2W_images_normalized\/T2W_normalized_GM\/Gwn0200-TP_2004_08_02-T2-textured.vtp\");\r\n\t\targs.append(\"-\"); \/\/ distance field marker\r\n\t\t\/\/ NOTE: fields are flipped because object 1 should use distfield 0\r\n\t\targs.append(\"D:\/Data\/msdata\/T2W\/T2W_images_normalized\/T2W_normalized_GM\/Gwn0200-TP_2004_08_02-T2-dist256.vti\");\r\n\t\targs.append(\"D:\/Data\/msdata\/T2W\/T2W_images_normalized\/T2W_normalized_GM\/Gwn0200-TP_2004_07_08-T2-dist256.vti\");\r\n\t\t\/\/*\/\r\n\t\t\/* Cartilage\r\n\t\targs.append(\"D:\/Data\/Cartilage\/Lorena\/femoral2.vtp\");\r\n\t\targs.append(\"D:\/Data\/Cartilage\/Lorena\/femoral1.vtp\");\r\n\t\t\/\/*\/\r\n\t}\r\n\t\/\/ Load the polydata\r\n\tNQVTK::Vector3 colors[] = {\r\n\t\tNQVTK::Vector3(1.0, 0.9, 0.4), \r\n\t\tNQVTK::Vector3(0.3, 0.6, 1.0)\r\n\t};\r\n\tint i = 0;\r\n\tbool distFields = false;\r\n\tfor (QStringList::const_iterator it = args.begin() + 1; it != args.end(); ++it)\r\n\t{\r\n\t\tqDebug(\"Loading %s #%d...\", (distFields ? \"distance field\" : \"surface\"), i);\r\n\t\tif (QString(\"-\") == *it)\r\n\t\t{\r\n\t\t\tdistFields = true;\r\n\t\t\ti = 0;\r\n\t\t\tcontinue;\r\n\t\t}\r\n\t\tif (!distFields)\r\n\t\t{\r\n\t\t\t\/\/ Load surface\r\n\t\t\tvtkSmartPointer<vtkXMLPolyDataReader> reader = \r\n\t\t\t\tvtkSmartPointer<vtkXMLPolyDataReader>::New();\r\n\t\t\treader->SetFileName(it->toUtf8());\r\n\t\t\treader->Update();\r\n\t\t\tNQVTK::Renderable *renderable = new NQVTK::PolyData(reader->GetOutput());\r\n\t\t\trenderable->color = colors[std::min(i, 1)];\r\n\t\t\trenderable->opacity = 0.3;\r\n\t\t\trenderer->AddRenderable(renderable);\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\t\/\/ Load distance field\r\n\t\t\tvtkSmartPointer<vtkXMLImageDataReader> reader = \r\n\t\t\t\tvtkSmartPointer<vtkXMLImageDataReader>::New();\r\n\t\t\treader->SetFileName(it->toUtf8());\r\n\t\t\treader->Update();\r\n\t\t\tGLTexture *tex = NQVTK::ImageDataTexture3D::New(reader->GetOutput());\r\n\t\t\tassert(tex);\r\n\t\t\tdistfieldstyle->SetDistanceField(i, tex);\r\n\t\t}\r\n\t\t++i;\r\n\t}\r\n\r\n\t\/\/ Render-on-idle timer\r\n\tstartTimer(0);\r\n\t\/\/ FPS display timer\r\n\tfpsTimerId = startTimer(1000);\r\n\tframes = 0;\r\n\r\n\tqDebug(\"Init done!\");\r\n}\r\n\r\n\/\/ ----------------------------------------------------------------------------\r\nvoid NQVTKWidget::resizeGL(int w, int h)\r\n{\r\n\trenderer->Resize(w, h);\r\n}\r\n\r\n\/\/ ----------------------------------------------------------------------------\r\nvoid NQVTKWidget::paintGL()\r\n{\r\n\tif (initialized) \r\n\t{\r\n\t\trenderer->Draw();\r\n\t}\r\n\telse\r\n\t{\r\n\t\trenderer->Clear();\r\n\t}\r\n\t++frames;\r\n}\r\n\r\n\/\/ ----------------------------------------------------------------------------\r\nvoid NQVTKWidget::timerEvent(QTimerEvent *event)\r\n{\r\n\tif (event->timerId() == fpsTimerId)\r\n\t{\r\n\t\t\/\/ Update FPS display\r\n\t\temit fpsChanged(frames);\r\n\t\tframes = 0;\r\n\t}\r\n\telse\r\n\t{\r\n\t\t\/\/ Update on idle\r\n\t\tupdateGL();\r\n\t}\r\n}\r\n\r\n\/\/ ----------------------------------------------------------------------------\r\nvoid NQVTKWidget::keyPressEvent(QKeyEvent *event)\r\n{\r\n\t\/\/ Quit on Escape\r\n\tswitch (event->key())\r\n\t{\r\n\tcase Qt::Key_Escape:\r\n\t\tqApp->quit();\r\n\t\tbreak;\r\n\tcase Qt::Key_C:\r\n\t\t{\r\n\t\t\tQDateTime now = QDateTime::currentDateTime();\r\n\t\t\tQImage screenshot = this->grabFrameBuffer(true);\r\n\t\t\t\/\/ Fix alpha values\r\n\t\t\tscreenshot.invertPixels(QImage::InvertRgba);\r\n\t\t\tscreenshot.invertPixels(QImage::InvertRgb);\r\n\t\t\t\/\/ Save it\r\n\t\t\tscreenshot.save(QString(\"NQVTK-%1.png\").arg(\r\n\t\t\t\tnow.toString(\"yyMMdd-hhmmss\")), \"PNG\");\r\n\t\t\tbreak;\r\n\t\t}\r\n\tcase Qt::Key_R:\r\n\t\trenderer->ResetRenderables();\r\n\t\tbreak;\r\n\tcase Qt::Key_1:\r\n\t\t{\r\n\t\t\tNQVTK::Renderable *ren = renderer->GetRenderable(0);\r\n\t\t\tif (ren) ren->visible = !ren->visible;\r\n\t\t}\r\n\t\tbreak;\r\n\tcase Qt::Key_2:\r\n\t\t{\r\n\t\t\tNQVTK::Renderable *ren = renderer->GetRenderable(1);\r\n\t\t\tif (ren) ren->visible = !ren->visible;\r\n\t\t}\r\n\t\tbreak;\r\n\tcase Qt::Key_F1:\r\n\t\tinitialized = renderer->SetStyle(new NQVTK::Styles::DepthPeeling());\r\n\t\tbreak;\r\n\tcase Qt::Key_F2:\r\n\t\tinitialized = renderer->SetStyle(new NQVTK::Styles::IBIS());\r\n\t\tbreak;\r\n\tcase Qt::Key_F3:\r\n\t\tdistfieldstyle = new NQVTK::Styles::DistanceFields();\r\n\t\tinitialized = renderer->SetStyle(distfieldstyle);\r\n\t\tbreak;\r\n\tdefault:\r\n\t\tevent->ignore();\r\n\t\treturn;\r\n\t}\r\n\tevent->accept();\r\n}\r\n\r\n\/\/ ----------------------------------------------------------------------------\r\nvoid NQVTKWidget::mouseMoveEvent(QMouseEvent *event)\r\n{\r\n\tif (event->modifiers() & Qt::ControlModifier) \r\n\t{\r\n\t\tNQVTK::Renderable *renderable = renderer->GetRenderable(0);\r\n\t\t\/\/ Mouse controls object 0\r\n\t\tif (renderable && event->buttons() & Qt::LeftButton)\r\n\t\t{\r\n\t\t\t\/\/ Rotate\r\n\t\t\trenderable->rotateY += event->x() - lastX;\r\n\t\t\trenderable->rotateX -= event->y() - lastY;\r\n\r\n\t\t\tif (renderable->rotateX > 80.0) \r\n\t\t\t{\r\n\t\t\t\trenderable->rotateX = 80.0;\r\n\t\t\t}\r\n\t\t\tif (renderable->rotateX < -80.0) \r\n\t\t\t{\r\n\t\t\t\trenderable->rotateX = -80.0;\r\n\t\t\t}\r\n\t\t}\r\n\t\tif (renderable && event->buttons() & Qt::MidButton)\r\n\t\t{\r\n\t\t\t\/\/ TODO: make translation relative to window\r\n\t\t\tNQVTK::Vector3 right = NQVTK::Vector3(1.0, 0.0, 0.0);\r\n\t\t\tNQVTK::Vector3 up = NQVTK::Vector3(0.0, 1.0, 0.0);\r\n\t\t\tdouble factor = 0.6;\r\n\t\t\t\/\/ Translate\r\n\t\t\trenderable->position += \r\n\t\t\t\t(lastX - event->x()) * factor * right +\r\n\t\t\t\t(lastY - event->y()) * factor * up;\r\n\t\t}\r\n\t}\r\n\telse\r\n\t{\r\n\t\t\/\/ Mouse controls camera\r\n\t\tif (event->buttons() & Qt::LeftButton)\r\n\t\t{\r\n\t\t\t\/\/ Rotate\r\n\t\t\trenderer->GetCamera()->rotateY += event->x() - lastX;\r\n\t\t\trenderer->GetCamera()->rotateX -= event->y() - lastY;\r\n\r\n\t\t\tif (renderer->GetCamera()->rotateX > 80.0) \r\n\t\t\t{\r\n\t\t\t\trenderer->GetCamera()->rotateX = 80.0;\r\n\t\t\t}\r\n\t\t\tif (renderer->GetCamera()->rotateX < -80.0) \r\n\t\t\t{\r\n\t\t\t\trenderer->GetCamera()->rotateX = -80.0;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tif (event->buttons() & Qt::RightButton)\r\n\t\t{\r\n\t\t\t\/\/ Zoom\r\n\t\t\trenderer->GetCamera()->zoom += (event->y() - lastY) * 0.01f;\r\n\t\t\tif (renderer->GetCamera()->zoom < 0.05) \r\n\t\t\t{\r\n\t\t\t\trenderer->GetCamera()->zoom = 0.05;\r\n\t\t\t}\r\n\t\t\tif (renderer->GetCamera()->zoom > 20.0) \r\n\t\t\t{\r\n\t\t\t\trenderer->GetCamera()->zoom = 20.0;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\tlastX = event->x();\r\n\tlastY = event->y();\r\n\r\n\tevent->accept();\r\n}\r\n<|endoftext|>"} {"text":"<commit_before>\/* Sirikata Network Utilities\n * ASIOStreamBuilder.cpp\n *\n * Copyright (c) 2009, Daniel Reiter Horn\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in\n * the documentation and\/or other materials provided with the\n * distribution.\n * * Neither the name of Sirikata nor the names of its contributors may\n * be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS\n * IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED\n * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A\n * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER\n * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include <sirikata\/core\/util\/Platform.hpp>\n#include <sirikata\/core\/network\/Asio.hpp>\n#include \"TCPStream.hpp\"\n#include \"ASIOSocketWrapper.hpp\"\n#include \"MultiplexedSocket.hpp\"\n#include \"TCPSetCallbacks.hpp\"\n#include \"TCPStreamListener.hpp\"\n#include \"ASIOReadBuffer.hpp\"\n\n#include <boost\/lexical_cast.hpp>\n#include <openssl\/md5.h>\n\nnamespace Sirikata {\nnamespace Network {\nnamespace ASIOStreamBuilder{\n\ntypedef Array<uint8,TCPStream::MaxWebSocketHeaderSize> TcpSstHeaderArray;\n\nclass IncompleteStreamState {\npublic:\n int mNumSockets;\n std::vector<TCPSocket*>mSockets;\n std::map<TCPSocket*, std::string> mWebSocketResponses;\n};\n\nnamespace {\ntypedef std::map<UUID,IncompleteStreamState> IncompleteStreamMap;\nstd::deque<UUID> sStaleUUIDs;\nIncompleteStreamMap sIncompleteStreams;\n\nint64 getObscuredNumber(const std::string& key) {\n std::string filtered;\n for(int32 i = 0; i < (int)key.size(); i++)\n if (key[i] >= '0' && key[i] <= '9')\n filtered.push_back(key[i]);\n return boost::lexical_cast<int64>(filtered);\n}\n\nint64 getNumSpaces(const std::string& key) {\n int32 result = 0;\n for(int32 i = 0; i < (int)key.size(); i++)\n if (key[i] == ' ') result++;\n return result;\n}\n\nstd::string getWebSocketSecReply(const std::string& key1, const std::string& key2, const std::string key3) {\n char magic_concat[16];\n int32* magic_1 = (int32*)magic_concat;\n int32* magic_2 = (int32*)(magic_concat + 4);\n char* magic_bytes = magic_concat + 8;\n\n *magic_1 = htonl(getObscuredNumber(key1) \/ getNumSpaces(key1));\n *magic_2 = htonl(getObscuredNumber(key2) \/ getNumSpaces(key2));\n assert(key3.size() == 8);\n memcpy(magic_bytes, &(key3[0]), 8);\n\n \/\/ FIXME md5 hash\n unsigned char result[MD5_DIGEST_LENGTH];\n MD5((unsigned char*) magic_concat, 16, result);\n\n return std::string((const char*)result, MD5_DIGEST_LENGTH);\n}\n\n}\n\n\/\/\/gets called when a complete 24 byte header is actually received: uses the UUID within to match up appropriate sockets\nvoid buildStream(TcpSstHeaderArray *buffer,\n TCPSocket *socket,\n std::tr1::shared_ptr<TCPStreamListener::Data> data,\n const boost::system::error_code &error,\n std::size_t bytes_transferred)\n{\n \/\/ Buffer always needs to be cleaned up when we get out of this method\n std::auto_ptr<TcpSstHeaderArray> buffer_ptr(buffer);\n\n \/\/ Sanity check start\n if (error || bytes_transferred < 5 || std::string((const char*)buffer->begin(), 5) != std::string(\"GET \/\")) {\n SILOG(tcpsst,warning,\"Connection received with truncated header: \"<<error);\n delete socket;\n return;\n }\n\n \/\/ Sanity check end: 8 bytes from WebSocket spec after headers, then\n \/\/ \\r\\n\\r\\n before that.\n std::string buffer_str((const char*)buffer->begin(), bytes_transferred);\n if (buffer_str[ bytes_transferred - 12] != '\\r' ||\n buffer_str[ bytes_transferred - 11] != '\\n' ||\n buffer_str[ bytes_transferred - 10] != '\\r' ||\n buffer_str[ bytes_transferred - 9] != '\\n')\n {\n SILOG(tcpsst,warning,\"Request doesn't end properly:\\n\" << buffer_str << \"\\n\");\n delete socket;\n return;\n }\n\n std::string headers_str = buffer_str.substr(0, bytes_transferred - 10);\n \/\/ Parse headers\n UUID context;\n std::map<std::string, std::string> headers;\n std::string::size_type offset = 0;\n while(offset < headers_str.size()) {\n std::string::size_type last_offset = offset;\n offset = headers_str.find(\"\\r\\n\", offset);\n if (offset == std::string::npos) {\n SILOG(tcpsst,warning,\"Error parsing headers.\");\n delete socket;\n return;\n }\n\n std::string line = headers_str.substr(last_offset, offset - last_offset);\n\n \/\/ Special case the initial GET line\n if (line.substr(0, 5) == \"GET \/\") {\n std::string::size_type uuid_end = line.find(' ', 5);\n if (uuid_end == std::string::npos) {\n SILOG(tcpsst,warning,\"Error parsing headers: invalid get line.\");\n delete socket;\n return;\n }\n std::string uuid_str = line.substr(5, uuid_end - 5);\n try {\n context = UUID(uuid_str,UUID::HumanReadable());\n } catch(...) {\n SILOG(tcpsst,warning,\"Error parsing headers: invalid get uuid.\");\n delete socket;\n return;\n }\n\n offset += 2;\n continue;\n }\n\n std::string::size_type colon = line.find(\":\");\n if (colon == std::string::npos) {\n SILOG(tcpsst,warning,\"Error parsing headers: missing colon.\");\n delete socket;\n return;\n }\n std::string head = line.substr(0, colon);\n std::string val = line.substr(colon+2);\n\n headers[head] = val;\n\n \/\/ Advance to get past the \\r\\n\n offset += 2;\n }\n\n if (headers.find(\"Host\") == headers.end() ||\n headers.find(\"Origin\") == headers.end() ||\n headers.find(\"Sec-WebSocket-Key1\") == headers.end() ||\n headers.find(\"Sec-WebSocket-Key2\") == headers.end())\n {\n SILOG(tcpsst,warning,\"Connection request didn't specify all required fields.\");\n delete socket;\n return;\n }\n\n std::string host = headers[\"Host\"];\n std::string origin = headers[\"Origin\"];\n std::string protocol = \"wssst1\";\n if (headers.find(\"Sec-WebSocket-Protocol\") != headers.end())\n protocol = headers[\"Sec-WebSocket-Protocol\"];\n std::string key1 = headers[\"Sec-WebSocket-Key1\"];\n std::string key2 = headers[\"Sec-WebSocket-Key2\"];\n std::string key3 = buffer_str.substr(bytes_transferred - 8);\n assert(key3.size() == 8);\n\n std::string reply_str = getWebSocketSecReply(key1, key2, key3);\n\n bool binaryStream=protocol.find(\"sst\")==0;\n bool base64Stream=!binaryStream;\n boost::asio::ip::tcp::no_delay option(data->mNoDelay);\n socket->set_option(option);\n IncompleteStreamMap::iterator where=sIncompleteStreams.find(context);\n\n unsigned int numConnections=1;\n\n for (std::string::iterator i=protocol.begin(),ie=protocol.end();i!=ie;++i) {\n if (*i>='0'&&*i<='9') {\n char* endptr=NULL;\n const char *start=protocol.c_str();\n size_t offset=(i-protocol.begin());\n start+=offset;\n numConnections=strtol(start,&endptr,10);\n size_t numberlen=endptr-start;\n if (numConnections>data->mMaxSimultaneousSockets) {\n numConnections=data->mMaxSimultaneousSockets;\n char numcon[256];\n sprintf(numcon,\"%d\",numConnections);\n protocol=protocol.substr(0,offset)+numcon+protocol.substr(offset+numberlen);\n }\n break;\n }\n }\n\n if (where==sIncompleteStreams.end()){\n sIncompleteStreams[context].mNumSockets=numConnections;\n where=sIncompleteStreams.find(context);\n assert(where!=sIncompleteStreams.end());\n }\n if ((int)numConnections!=where->second.mNumSockets) {\n SILOG(tcpsst,warning,\"Single client disagrees on number of connections to establish: \"<<numConnections<<\" != \"<<where->second.mNumSockets);\n sIncompleteStreams.erase(where);\n }else {\n where->second.mSockets.push_back(socket);\n where->second.mWebSocketResponses[socket] = reply_str;\n if (numConnections==(unsigned int)where->second.mSockets.size()) {\n MultiplexedSocketPtr shared_socket(\n MultiplexedSocket::construct<MultiplexedSocket>(data->strand,context,data->cb,base64Stream));\n shared_socket->initFromSockets(where->second.mSockets,data->mSendBufferSize);\n std::string port=shared_socket->getASIOSocketWrapper(0).getLocalEndpoint().getService();\n std::string resource_name='\/'+context.toString();\n MultiplexedSocket::sendAllProtocolHeaders(shared_socket,origin,host,port,resource_name,protocol, where->second.mWebSocketResponses);\n sIncompleteStreams.erase(where);\n\n\n Stream::StreamID newID=Stream::StreamID(1);\n TCPStream * strm=new TCPStream(shared_socket,newID);\n\n TCPSetCallbacks setCallbackFunctor(&*shared_socket,strm);\n data->cb(strm,setCallbackFunctor);\n if (setCallbackFunctor.mCallbacks==NULL) {\n SILOG(tcpsst,error,\"Client code for stream \"<<newID.read()<<\" did not set listener on socket\");\n shared_socket->closeStream(shared_socket,newID);\n }\n }else{\n sStaleUUIDs.push_back(context);\n }\n }\n}\n\nnamespace {\nclass CheckWebSocketRequest {\n const Array<uint8,TCPStream::MaxWebSocketHeaderSize> *mArray;\n typedef boost::system::error_code ErrorCode;\n uint32 mTotal;\npublic:\n CheckWebSocketRequest(const Array<uint8,TCPStream::MaxWebSocketHeaderSize>*array) {\n mArray=array;\n mTotal = 0;\n }\n size_t operator() (const ErrorCode& error, size_t bytes_transferred) {\n if (error) return 0;\n\n mTotal += bytes_transferred;\n\n if (mTotal >= 12 &&\n (*mArray)[mTotal - 12] == '\\r' &&\n (*mArray)[mTotal - 11] == '\\n' &&\n (*mArray)[mTotal - 10] == '\\r' &&\n (*mArray)[mTotal - 9] == '\\n')\n {\n return 0;\n }\n return 65536;\n }\n};\n} \/\/ namespace\n\nvoid beginNewStream(TCPSocket*socket, std::tr1::shared_ptr<TCPStreamListener::Data> data) {\n\n TcpSstHeaderArray *buffer = new TcpSstHeaderArray;\n\n boost::asio::async_read(*socket,\n boost::asio::buffer(buffer->begin(),(int)TCPStream::MaxWebSocketHeaderSize>(int)ASIOReadBuffer::sBufferLength?(int)ASIOReadBuffer::sBufferLength:(int)TCPStream::MaxWebSocketHeaderSize),\n CheckWebSocketRequest (buffer),\n std::tr1::bind(&ASIOStreamBuilder::buildStream,buffer,socket,data,_1,_2));\n}\n\n} \/\/ namespace ASIOStreamBuilder\n} \/\/ namespace Network\n} \/\/ namespace Sirikata\n<commit_msg>Add missing strand wrapping in TCPSST to fix crash triggered when two read callbacks from sockets for the same TCPSST connection were invoked at the same time.<commit_after>\/* Sirikata Network Utilities\n * ASIOStreamBuilder.cpp\n *\n * Copyright (c) 2009, Daniel Reiter Horn\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in\n * the documentation and\/or other materials provided with the\n * distribution.\n * * Neither the name of Sirikata nor the names of its contributors may\n * be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS\n * IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED\n * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A\n * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER\n * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include <sirikata\/core\/util\/Platform.hpp>\n#include <sirikata\/core\/network\/Asio.hpp>\n#include <sirikata\/core\/network\/IOStrandImpl.hpp>\n#include \"TCPStream.hpp\"\n#include \"ASIOSocketWrapper.hpp\"\n#include \"MultiplexedSocket.hpp\"\n#include \"TCPSetCallbacks.hpp\"\n#include \"TCPStreamListener.hpp\"\n#include \"ASIOReadBuffer.hpp\"\n\n#include <boost\/lexical_cast.hpp>\n#include <openssl\/md5.h>\n\nnamespace Sirikata {\nnamespace Network {\nnamespace ASIOStreamBuilder{\n\ntypedef Array<uint8,TCPStream::MaxWebSocketHeaderSize> TcpSstHeaderArray;\n\nclass IncompleteStreamState {\npublic:\n int mNumSockets;\n std::vector<TCPSocket*>mSockets;\n std::map<TCPSocket*, std::string> mWebSocketResponses;\n};\n\nnamespace {\ntypedef std::map<UUID,IncompleteStreamState> IncompleteStreamMap;\nstd::deque<UUID> sStaleUUIDs;\nIncompleteStreamMap sIncompleteStreams;\n\nint64 getObscuredNumber(const std::string& key) {\n std::string filtered;\n for(int32 i = 0; i < (int)key.size(); i++)\n if (key[i] >= '0' && key[i] <= '9')\n filtered.push_back(key[i]);\n return boost::lexical_cast<int64>(filtered);\n}\n\nint64 getNumSpaces(const std::string& key) {\n int32 result = 0;\n for(int32 i = 0; i < (int)key.size(); i++)\n if (key[i] == ' ') result++;\n return result;\n}\n\nstd::string getWebSocketSecReply(const std::string& key1, const std::string& key2, const std::string key3) {\n char magic_concat[16];\n int32* magic_1 = (int32*)magic_concat;\n int32* magic_2 = (int32*)(magic_concat + 4);\n char* magic_bytes = magic_concat + 8;\n\n *magic_1 = htonl(getObscuredNumber(key1) \/ getNumSpaces(key1));\n *magic_2 = htonl(getObscuredNumber(key2) \/ getNumSpaces(key2));\n assert(key3.size() == 8);\n memcpy(magic_bytes, &(key3[0]), 8);\n\n \/\/ FIXME md5 hash\n unsigned char result[MD5_DIGEST_LENGTH];\n MD5((unsigned char*) magic_concat, 16, result);\n\n return std::string((const char*)result, MD5_DIGEST_LENGTH);\n}\n\n}\n\n\/\/\/gets called when a complete 24 byte header is actually received: uses the UUID within to match up appropriate sockets\nvoid buildStream(TcpSstHeaderArray *buffer,\n TCPSocket *socket,\n std::tr1::shared_ptr<TCPStreamListener::Data> data,\n const boost::system::error_code &error,\n std::size_t bytes_transferred)\n{\n \/\/ Buffer always needs to be cleaned up when we get out of this method\n std::auto_ptr<TcpSstHeaderArray> buffer_ptr(buffer);\n\n \/\/ Sanity check start\n if (error || bytes_transferred < 5 || std::string((const char*)buffer->begin(), 5) != std::string(\"GET \/\")) {\n SILOG(tcpsst,warning,\"Connection received with truncated header: \"<<error);\n delete socket;\n return;\n }\n\n \/\/ Sanity check end: 8 bytes from WebSocket spec after headers, then\n \/\/ \\r\\n\\r\\n before that.\n std::string buffer_str((const char*)buffer->begin(), bytes_transferred);\n if (buffer_str[ bytes_transferred - 12] != '\\r' ||\n buffer_str[ bytes_transferred - 11] != '\\n' ||\n buffer_str[ bytes_transferred - 10] != '\\r' ||\n buffer_str[ bytes_transferred - 9] != '\\n')\n {\n SILOG(tcpsst,warning,\"Request doesn't end properly:\\n\" << buffer_str << \"\\n\");\n delete socket;\n return;\n }\n\n std::string headers_str = buffer_str.substr(0, bytes_transferred - 10);\n \/\/ Parse headers\n UUID context;\n std::map<std::string, std::string> headers;\n std::string::size_type offset = 0;\n while(offset < headers_str.size()) {\n std::string::size_type last_offset = offset;\n offset = headers_str.find(\"\\r\\n\", offset);\n if (offset == std::string::npos) {\n SILOG(tcpsst,warning,\"Error parsing headers.\");\n delete socket;\n return;\n }\n\n std::string line = headers_str.substr(last_offset, offset - last_offset);\n\n \/\/ Special case the initial GET line\n if (line.substr(0, 5) == \"GET \/\") {\n std::string::size_type uuid_end = line.find(' ', 5);\n if (uuid_end == std::string::npos) {\n SILOG(tcpsst,warning,\"Error parsing headers: invalid get line.\");\n delete socket;\n return;\n }\n std::string uuid_str = line.substr(5, uuid_end - 5);\n try {\n context = UUID(uuid_str,UUID::HumanReadable());\n } catch(...) {\n SILOG(tcpsst,warning,\"Error parsing headers: invalid get uuid.\");\n delete socket;\n return;\n }\n\n offset += 2;\n continue;\n }\n\n std::string::size_type colon = line.find(\":\");\n if (colon == std::string::npos) {\n SILOG(tcpsst,warning,\"Error parsing headers: missing colon.\");\n delete socket;\n return;\n }\n std::string head = line.substr(0, colon);\n std::string val = line.substr(colon+2);\n\n headers[head] = val;\n\n \/\/ Advance to get past the \\r\\n\n offset += 2;\n }\n\n if (headers.find(\"Host\") == headers.end() ||\n headers.find(\"Origin\") == headers.end() ||\n headers.find(\"Sec-WebSocket-Key1\") == headers.end() ||\n headers.find(\"Sec-WebSocket-Key2\") == headers.end())\n {\n SILOG(tcpsst,warning,\"Connection request didn't specify all required fields.\");\n delete socket;\n return;\n }\n\n std::string host = headers[\"Host\"];\n std::string origin = headers[\"Origin\"];\n std::string protocol = \"wssst1\";\n if (headers.find(\"Sec-WebSocket-Protocol\") != headers.end())\n protocol = headers[\"Sec-WebSocket-Protocol\"];\n std::string key1 = headers[\"Sec-WebSocket-Key1\"];\n std::string key2 = headers[\"Sec-WebSocket-Key2\"];\n std::string key3 = buffer_str.substr(bytes_transferred - 8);\n assert(key3.size() == 8);\n\n std::string reply_str = getWebSocketSecReply(key1, key2, key3);\n\n bool binaryStream=protocol.find(\"sst\")==0;\n bool base64Stream=!binaryStream;\n boost::asio::ip::tcp::no_delay option(data->mNoDelay);\n socket->set_option(option);\n IncompleteStreamMap::iterator where=sIncompleteStreams.find(context);\n\n unsigned int numConnections=1;\n\n for (std::string::iterator i=protocol.begin(),ie=protocol.end();i!=ie;++i) {\n if (*i>='0'&&*i<='9') {\n char* endptr=NULL;\n const char *start=protocol.c_str();\n size_t offset=(i-protocol.begin());\n start+=offset;\n numConnections=strtol(start,&endptr,10);\n size_t numberlen=endptr-start;\n if (numConnections>data->mMaxSimultaneousSockets) {\n numConnections=data->mMaxSimultaneousSockets;\n char numcon[256];\n sprintf(numcon,\"%d\",numConnections);\n protocol=protocol.substr(0,offset)+numcon+protocol.substr(offset+numberlen);\n }\n break;\n }\n }\n\n if (where==sIncompleteStreams.end()){\n sIncompleteStreams[context].mNumSockets=numConnections;\n where=sIncompleteStreams.find(context);\n assert(where!=sIncompleteStreams.end());\n }\n if ((int)numConnections!=where->second.mNumSockets) {\n SILOG(tcpsst,warning,\"Single client disagrees on number of connections to establish: \"<<numConnections<<\" != \"<<where->second.mNumSockets);\n sIncompleteStreams.erase(where);\n }else {\n where->second.mSockets.push_back(socket);\n where->second.mWebSocketResponses[socket] = reply_str;\n if (numConnections==(unsigned int)where->second.mSockets.size()) {\n MultiplexedSocketPtr shared_socket(\n MultiplexedSocket::construct<MultiplexedSocket>(data->strand,context,data->cb,base64Stream));\n shared_socket->initFromSockets(where->second.mSockets,data->mSendBufferSize);\n std::string port=shared_socket->getASIOSocketWrapper(0).getLocalEndpoint().getService();\n std::string resource_name='\/'+context.toString();\n MultiplexedSocket::sendAllProtocolHeaders(shared_socket,origin,host,port,resource_name,protocol, where->second.mWebSocketResponses);\n sIncompleteStreams.erase(where);\n\n\n Stream::StreamID newID=Stream::StreamID(1);\n TCPStream * strm=new TCPStream(shared_socket,newID);\n\n TCPSetCallbacks setCallbackFunctor(&*shared_socket,strm);\n data->cb(strm,setCallbackFunctor);\n if (setCallbackFunctor.mCallbacks==NULL) {\n SILOG(tcpsst,error,\"Client code for stream \"<<newID.read()<<\" did not set listener on socket\");\n shared_socket->closeStream(shared_socket,newID);\n }\n }else{\n sStaleUUIDs.push_back(context);\n }\n }\n}\n\nnamespace {\nclass CheckWebSocketRequest {\n const Array<uint8,TCPStream::MaxWebSocketHeaderSize> *mArray;\n typedef boost::system::error_code ErrorCode;\n uint32 mTotal;\npublic:\n CheckWebSocketRequest(const Array<uint8,TCPStream::MaxWebSocketHeaderSize>*array) {\n mArray=array;\n mTotal = 0;\n }\n size_t operator() (const ErrorCode& error, size_t bytes_transferred) {\n if (error) return 0;\n\n mTotal += bytes_transferred;\n\n if (mTotal >= 12 &&\n (*mArray)[mTotal - 12] == '\\r' &&\n (*mArray)[mTotal - 11] == '\\n' &&\n (*mArray)[mTotal - 10] == '\\r' &&\n (*mArray)[mTotal - 9] == '\\n')\n {\n return 0;\n }\n return 65536;\n }\n};\n} \/\/ namespace\n\nvoid beginNewStream(TCPSocket*socket, std::tr1::shared_ptr<TCPStreamListener::Data> data) {\n\n TcpSstHeaderArray *buffer = new TcpSstHeaderArray;\n\n boost::asio::async_read(*socket,\n boost::asio::buffer(buffer->begin(),(int)TCPStream::MaxWebSocketHeaderSize>(int)ASIOReadBuffer::sBufferLength?(int)ASIOReadBuffer::sBufferLength:(int)TCPStream::MaxWebSocketHeaderSize),\n CheckWebSocketRequest (buffer),\n data->strand->wrap( std::tr1::bind(&ASIOStreamBuilder::buildStream,buffer,socket,data,_1,_2) )\n );\n}\n\n} \/\/ namespace ASIOStreamBuilder\n} \/\/ namespace Network\n} \/\/ namespace Sirikata\n<|endoftext|>"} {"text":"<commit_before>AliFemtoK0Analysis *AddTaskK0Femto(bool SignDep = kFALSE, bool FieldPositive = kTRUE, bool OnlineCase = kTRUE, bool MeritCase = kTRUE, float MinDL = 0.0, int MeritCutChoice = 4, float MinSep = 5.0, TString nameSpec = \"NoSpec\"){\n\n AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();\n if (!mgr) {\n ::Error(\"AddTaskBF\", \"No analysis manager to connect to.\");\n return NULL;\n }\n\n AliFemtoK0Analysis *K0Task = new AliFemtoK0Analysis(\"K0Task\", SignDep, FieldPositive, OnlineCase, MeritCase, MinDL, MeritCutChoice, MinSep);\n if(!K0Task) exit(-1);\n mgr->AddTask(K0Task);\n\n TString outputFileName = AliAnalysisManager::GetCommonFileName();\n outputFileName += \":PWGCF.outputK0Analysis_\";\n outputFileName += nameSpec;\n if(SignDep){\n if(FieldPositive) outputFileName += \"_FieldPos.root\";\n else outputFileName += \"_FieldNeg.root\";\n }\n AliAnalysisDataContainer *coutputK0 = mgr->CreateContainer(\"MyList\", TList::Class(), AliAnalysisManager::kOutputContainer, outputFileName.Data());\n\n mgr->ConnectInput(K0Task, 0, mgr->GetCommonInputContainer());\n mgr->ConnectOutput(K0Task, 1, coutputK0);\n\n return K0Task;\n}\n\n\n \n<commit_msg>K0s code update (Matt Steinpreis)<commit_after>AliFemtoK0Analysis *AddTaskK0Femto(bool SignDep = kFALSE, bool FieldPositive = kTRUE, bool OnlineCase = kTRUE, bool MeritCase = kTRUE, bool Case3D = kFALSE, float MinDL = 0.0, int MeritCutChoice = 4, float MinSep = 5.0, TString nameSpec = \"NoSpec\"){\n\n AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();\n if (!mgr) {\n ::Error(\"AddTaskBF\", \"No analysis manager to connect to.\");\n return NULL;\n }\n\n AliFemtoK0Analysis *K0Task = new AliFemtoK0Analysis(\"K0Task\", SignDep, FieldPositive, OnlineCase, MeritCase, Case3D, MinDL, MeritCutChoice, MinSep);\n if(!K0Task) exit(-1);\n mgr->AddTask(K0Task);\n\n TString outputFileName = AliAnalysisManager::GetCommonFileName();\n outputFileName += \":PWGCF.outputK0Analysis_\";\n outputFileName += nameSpec;\n if(SignDep){\n if(FieldPositive) outputFileName += \"_FieldPos.root\";\n else outputFileName += \"_FieldNeg.root\";\n }\n AliAnalysisDataContainer *coutputK0 = mgr->CreateContainer(\"MyList\", TList::Class(), AliAnalysisManager::kOutputContainer, outputFileName.Data());\n\n mgr->ConnectInput(K0Task, 0, mgr->GetCommonInputContainer());\n mgr->ConnectOutput(K0Task, 1, coutputK0);\n\n return K0Task;\n}\n\n\n \n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (C) 2010-2011 Dmitry Marakasov\n *\n * This file is part of glosm.\n *\n * glosm is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * glosm is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with glosm. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n\n#ifndef ORTHOVIEWER_HH\n#define ORTHOVIEWER_HH\n\n#include <glosm\/Viewer.hh>\n#include <glosm\/BBox.hh>\n\n\/**\n * Viewer describing orthographic projection.\n *\n * This viewer is useful for tile rendering.\n *\/\nclass OrthoViewer : public Viewer {\npublic:\n\tOrthoViewer();\n\n\tvirtual void SetupViewerMatrix(const Projection& projection) const;\n\tvirtual Vector3i GetPos(const Projection& projection) const;\n\n\t\/**\n\t * Sets bounding box of a viewport in global coordinades\n\t *\/\n\tvoid SetBBox(const BBoxi& pos);\n\n\t\/**\n\t * Sets bounding box for specific tile in mapnik format.\n\t *\n\t * @param nx X coordinate of a desired tile\n\t * @param ny Y coordinate of a desired tile\n\t * @param zoom zoom level of a desired tile\n\t *\/\n\tvoid SetBBoxForTile(int nx, int ny, int zoom);\n\n\t\/**\n\t * Sets skew for pseudo-3D effect.\n\t *\n\t * To retain tile proportions, we can't do proper 3D by\n\t * changing viewing angle, but we can 'skew' objects that\n\t * have height so their sides appear on a top-down view.\n\t * Skew factor may be described as a tangent of desired\n\t * viewing angle, 1.0 is equal to 45 degrees.\n\t *\n\t * @param skew skew ratio\n\t *\/\n\tvoid SetSkew(float skew);\n\nprotected:\n\tBBoxi bbox_;\n\tfloat skew_;\n};\n\n#endif\n<commit_msg>Remove unneeded OrthoViewer method<commit_after>\/*\n * Copyright (C) 2010-2011 Dmitry Marakasov\n *\n * This file is part of glosm.\n *\n * glosm is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * glosm is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with glosm. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n\n#ifndef ORTHOVIEWER_HH\n#define ORTHOVIEWER_HH\n\n#include <glosm\/Viewer.hh>\n#include <glosm\/BBox.hh>\n\n\/**\n * Viewer describing orthographic projection.\n *\n * This viewer is useful for tile rendering.\n *\/\nclass OrthoViewer : public Viewer {\npublic:\n\tOrthoViewer();\n\n\tvirtual void SetupViewerMatrix(const Projection& projection) const;\n\tvirtual Vector3i GetPos(const Projection& projection) const;\n\n\t\/**\n\t * Sets bounding box of a viewport in global coordinades\n\t *\/\n\tvoid SetBBox(const BBoxi& pos);\n\n\t\/**\n\t * Sets skew for pseudo-3D effect.\n\t *\n\t * To retain tile proportions, we can't do proper 3D by\n\t * changing viewing angle, but we can 'skew' objects that\n\t * have height so their sides appear on a top-down view.\n\t * Skew factor may be described as a tangent of desired\n\t * viewing angle, 1.0 is equal to 45 degrees.\n\t *\n\t * @param skew skew ratio\n\t *\/\n\tvoid SetSkew(float skew);\n\nprotected:\n\tBBoxi bbox_;\n\tfloat skew_;\n};\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>#pragma once\n#include <string>\n#include <fc\/reflect\/reflect.hpp>\n#include <fc\/exception\/exception.hpp>\n#include <eosio\/chain\/exceptions.hpp>\n#include <iosfwd>\n\nnamespace eosio::chain {\n struct name;\n}\nnamespace fc {\n class variant;\n void to_variant(const eosio::chain::name& c, fc::variant& v);\n void from_variant(const fc::variant& v, eosio::chain::name& check);\n} \/\/ fc\n\nnamespace eosio::chain {\n static constexpr uint64_t char_to_symbol( char c ) {\n if( c >= 'a' && c <= 'z' )\n return (c - 'a') + 6;\n if( c >= '1' && c <= '5' )\n return (c - '1') + 1;\n else if( c == '.')\n return 0;\n \n EOS_ASSERT(0, name_type_exception, \"Name contains invalid character: (${c}) \", (\"c\", std::string(1, c)));\n \n \/\/unreachable\n return 0;\n }\n\n static constexpr uint64_t string_to_uint64_t( std::string_view str ) {\n EOS_ASSERT(str.size() <= 13, name_type_exception, \"Name is longer than 13 characters (${name}) \", (\"name\", std::string(str)));\n\n uint64_t n = 0;\n int i = 0;\n for ( ; str[i] && i < 12; ++i) {\n \/\/ NOTE: char_to_symbol() returns char type, and without this explicit\n \/\/ expansion to uint64 type, the compilation fails at the point of usage\n \/\/ of string_to_name(), where the usage requires constant (compile time) expression.\n n |= char_to_symbol(str[i]) << (64 - 5 * (i + 1));\n }\n\n \/\/ The for-loop encoded up to 60 high bits into uint64 'name' variable,\n \/\/ if (strlen(str) > 12) then encode str[12] into the low (remaining)\n \/\/ 4 bits of 'name'\n if (i == 12 && str[12])\n {\n uint64_t cur_v = char_to_symbol(str[12]);\n EOS_ASSERT(cur_v <= 0x0Full, name_type_exception, \"invalid 13th character: (${c})\", (\"c\", std::string(1, str[12])));\n n |= cur_v;\n }\n return n;\n }\n\n \/\/\/ Immutable except for fc::from_variant.\n struct name {\n private:\n uint64_t value = 0;\n\n friend struct fc::reflector<name>;\n friend void fc::from_variant(const fc::variant& v, eosio::chain::name& check);\n\n void set( std::string_view str );\n\n public:\n constexpr bool empty()const { return 0 == value; }\n constexpr bool good()const { return !empty(); }\n\n explicit name( std::string_view str ) { set( str ); }\n constexpr explicit name( uint64_t v ) : value(v) {}\n constexpr name() = default;\n\n std::string to_string()const;\n constexpr uint64_t to_uint64_t()const { return value; }\n\n friend std::ostream& operator << ( std::ostream& out, const name& n ) {\n return out << n.to_string();\n }\n\n friend constexpr bool operator < ( const name& a, const name& b ) { return a.value < b.value; }\n friend constexpr bool operator > ( const name& a, const name& b ) { return a.value > b.value; }\n friend constexpr bool operator <= ( const name& a, const name& b ) { return a.value <= b.value; }\n friend constexpr bool operator >= ( const name& a, const name& b ) { return a.value >= b.value; }\n friend constexpr bool operator == ( const name& a, const name& b ) { return a.value == b.value; }\n friend constexpr bool operator != ( const name& a, const name& b ) { return a.value != b.value; }\n\n friend constexpr bool operator == ( const name& a, uint64_t b ) { return a.value == b; }\n friend constexpr bool operator != ( const name& a, uint64_t b ) { return a.value != b; }\n\n constexpr explicit operator bool()const { return value != 0; }\n };\n\n \/\/ Each char of the string is encoded into 5-bit chunk and left-shifted\n \/\/ to its 5-bit slot starting with the highest slot for the first char.\n \/\/ The 13th char, if str is long enough, is encoded into 4-bit chunk\n \/\/ and placed in the lowest 4 bits. 64 = 12 * 5 + 4\n static constexpr name string_to_name( std::string_view str )\n {\n return name( string_to_uint64_t( str ) );\n }\n\n#define N(X) eosio::chain::string_to_name(#X)\n\n} \/\/ eosio::chain\n\nnamespace std {\n template<> struct hash<eosio::chain::name> : private hash<uint64_t> {\n typedef eosio::chain::name argument_type;\n size_t operator()(const argument_type& name) const noexcept\n {\n return hash<uint64_t>::operator()(name.to_uint64_t());\n }\n };\n};\n\nFC_REFLECT( eosio::chain::name, (value) )\n<commit_msg>fix compatability with gcc 8.3.1<commit_after>#pragma once\n#include <string>\n#include <fc\/reflect\/reflect.hpp>\n#include <fc\/exception\/exception.hpp>\n#include <eosio\/chain\/exceptions.hpp>\n#include <iosfwd>\n\nnamespace eosio::chain {\n struct name;\n}\nnamespace fc {\n class variant;\n void to_variant(const eosio::chain::name& c, fc::variant& v);\n void from_variant(const fc::variant& v, eosio::chain::name& check);\n} \/\/ fc\n\nnamespace eosio::chain {\n static constexpr uint64_t char_to_symbol( char c ) {\n if( c >= 'a' && c <= 'z' )\n return (c - 'a') + 6;\n if( c >= '1' && c <= '5' )\n return (c - '1') + 1;\n else if( c == '.')\n return 0;\n else\n FC_THROW_EXCEPTION(name_type_exception, \"Name contains invalid character: (${c}) \", (\"c\", std::string(1, c)));\n \n \/\/unreachable\n return 0;\n }\n\n static constexpr uint64_t string_to_uint64_t( std::string_view str ) {\n EOS_ASSERT(str.size() <= 13, name_type_exception, \"Name is longer than 13 characters (${name}) \", (\"name\", std::string(str)));\n\n uint64_t n = 0;\n int i = 0;\n for ( ; str[i] && i < 12; ++i) {\n \/\/ NOTE: char_to_symbol() returns char type, and without this explicit\n \/\/ expansion to uint64 type, the compilation fails at the point of usage\n \/\/ of string_to_name(), where the usage requires constant (compile time) expression.\n n |= char_to_symbol(str[i]) << (64 - 5 * (i + 1));\n }\n\n \/\/ The for-loop encoded up to 60 high bits into uint64 'name' variable,\n \/\/ if (strlen(str) > 12) then encode str[12] into the low (remaining)\n \/\/ 4 bits of 'name'\n if (i == 12 && str[12])\n {\n uint64_t cur_v = char_to_symbol(str[12]);\n EOS_ASSERT(cur_v <= 0x0Full, name_type_exception, \"invalid 13th character: (${c})\", (\"c\", std::string(1, str[12])));\n n |= cur_v;\n }\n return n;\n }\n\n \/\/\/ Immutable except for fc::from_variant.\n struct name {\n private:\n uint64_t value = 0;\n\n friend struct fc::reflector<name>;\n friend void fc::from_variant(const fc::variant& v, eosio::chain::name& check);\n\n void set( std::string_view str );\n\n public:\n constexpr bool empty()const { return 0 == value; }\n constexpr bool good()const { return !empty(); }\n\n explicit name( std::string_view str ) { set( str ); }\n constexpr explicit name( uint64_t v ) : value(v) {}\n constexpr name() = default;\n\n std::string to_string()const;\n constexpr uint64_t to_uint64_t()const { return value; }\n\n friend std::ostream& operator << ( std::ostream& out, const name& n ) {\n return out << n.to_string();\n }\n\n friend constexpr bool operator < ( const name& a, const name& b ) { return a.value < b.value; }\n friend constexpr bool operator > ( const name& a, const name& b ) { return a.value > b.value; }\n friend constexpr bool operator <= ( const name& a, const name& b ) { return a.value <= b.value; }\n friend constexpr bool operator >= ( const name& a, const name& b ) { return a.value >= b.value; }\n friend constexpr bool operator == ( const name& a, const name& b ) { return a.value == b.value; }\n friend constexpr bool operator != ( const name& a, const name& b ) { return a.value != b.value; }\n\n friend constexpr bool operator == ( const name& a, uint64_t b ) { return a.value == b; }\n friend constexpr bool operator != ( const name& a, uint64_t b ) { return a.value != b; }\n\n constexpr explicit operator bool()const { return value != 0; }\n };\n\n \/\/ Each char of the string is encoded into 5-bit chunk and left-shifted\n \/\/ to its 5-bit slot starting with the highest slot for the first char.\n \/\/ The 13th char, if str is long enough, is encoded into 4-bit chunk\n \/\/ and placed in the lowest 4 bits. 64 = 12 * 5 + 4\n static constexpr name string_to_name( std::string_view str )\n {\n return name( string_to_uint64_t( str ) );\n }\n\n#define N(X) eosio::chain::string_to_name(#X)\n\n} \/\/ eosio::chain\n\nnamespace std {\n template<> struct hash<eosio::chain::name> : private hash<uint64_t> {\n typedef eosio::chain::name argument_type;\n size_t operator()(const argument_type& name) const noexcept\n {\n return hash<uint64_t>::operator()(name.to_uint64_t());\n }\n };\n};\n\nFC_REFLECT( eosio::chain::name, (value) )\n<|endoftext|>"} {"text":"<commit_before>\/*\n Template of calibration\/filtering macro using ESD:\n - requires AliESDs.root and AliESDfriend.root\n - requires OCDB access (default set to \"raw:\/\/\")\n - requires run number as argument to init OCDB\n - calls LoadLibraries.C, ConfigCalibTrain.C and AddTaskTPCCalib.C macros\n - output AliESDfriends_v1.root with TPC and TRD calibration objects are created\n\n Example:\n .L $ALICE_ROOT\/ANALYSIS\/macros\/runCalibTrain.C\n runCalibTrain(\"104892\");\n*\/\n\nvoid runCalibTrain(Int_t runNumber, const char *inFileName = \"AliESDs.root\", const char *ocdb=\"raw:\/\/\")\n{\n \/\/\n \/\/ macro to run TPC calibration train \n \/\/\n AliSysInfo::SetVerbose(kTRUE);\n AliLog::SetGlobalLogLevel(AliLog::kError); \n gROOT->Macro(\"$ALICE_PHYSICS\/PWGPP\/CalibMacros\/CPass1\/LoadLibraries.C\");\n gROOT->LoadMacro(\"$ALICE_PHYSICS\/PWGPP\/CalibMacros\/CPass1\/ConfigCalibTrain.C\");\n gSystem->SetIncludePath(\"-I$ALICE_PHYSICS\/include -I$ALICE_ROOT\/include\"); \n \/*\n if (gSystem->Exec(\"cp $ALICE_PHYSICS\/PWGPP\/CalibMacros\/commonMacros\/CleanGeom.C .\/\") ||\n gROOT->LoadMacro(\"CleanGeom.C++\")) { \/\/ comple local copy only\n printf(\"Failed to load\/compile CleanGeom, exit\\n\");\n return;\n }\n *\/\n \/\/ detector tasks\n gROOT->LoadMacro(\"$ALICE_PHYSICS\/PWGPP\/CalibMacros\/CPass1\/AddTaskTPCCalib.C\");\n gROOT->LoadMacro(\"$ALICE_PHYSICS\/PWGPP\/CalibMacros\/CPass1\/AddTaskTRDCalib.C\");\n gROOT->LoadMacro(\"$ALICE_PHYSICS\/PWGPP\/CalibMacros\/CPass1\/AddTOFAnalysisTaskCalibPass0.C\");\n gROOT->LoadMacro(\"$ALICE_PHYSICS\/PWGPP\/CalibMacros\/CPass1\/AddTOFAnalysisTaskCalibTree.C\");\n gROOT->LoadMacro(\"$ALICE_PHYSICS\/PWGPP\/CalibMacros\/CPass1\/AddTaskT0Calib.C\");\n gROOT->LoadMacro(\"$ALICE_PHYSICS\/PWGPP\/CalibMacros\/CPass1\/AddTaskT0Analysis.C\");\n \/\/ gROOT->LoadMacro(\"$ALICE_PHYSICS\/PWGPP\/CalibMacros\/CPass1\/AddTaskMeanVertexCalib.C\");\n gROOT->LoadMacro(\"$ALICE_PHYSICS\/PWGPP\/CalibMacros\/CPass1\/AddTaskSDDCalib.C\"); \n\n \/\/ switch off debug \n AliLog::SetClassDebugLevel(\"AliESDEvent\",0);\n \n \/\/ steering input chain\n TChain *chain = new TChain(\"esdTree\");\n chain->Add(inFileName);\n\n \/\/ config calibration train\n \/\/ setting geometry and B-field from GRP\n printf(\"runNumber from runCalibTrain = %d\\n\",runNumber);\n printf(\"ocdb from runCalibTrain = %s\\n\",ocdb);\n AliSysInfo::AddStamp(\"BeforeConfiguringCalibTrain\");\n ConfigCalibTrain(runNumber, ocdb);\n AliSysInfo::AddStamp(\"AfterConfiguringCalibTrain\"); \n \n if (gROOT->LoadMacro(\"localOCDBaccessConfig.C\")==0) {\n localOCDBaccessConfig();\n }\n \n \/\/\n \/\/ check the presence of the detectors\n AliCDBEntry* entry = AliCDBManager::Instance()->Get(\"GRP\/GRP\/Data\");\n AliGRPObject* grpData = dynamic_cast<AliGRPObject*>(entry->GetObject()); \n if (!grpData) {printf(\"Failed to get GRP data for run\",runNumber); return;}\n Int_t activeDetectors = grpData->GetDetectorMask(); \n TString detStr = AliDAQ::ListOfTriggeredDetectors(activeDetectors);\n printf(\"Detectors in the data:\\n%s\\n\",detStr.Data());\n\n \/\/ setup analysis\n \/\/\n AliAnalysisManager *mgr = new AliAnalysisManager(\"ESD to ESD\", \"Analysis Manager\");\n \/\/ mgr->SetDebugLevel(3);\n mgr->SetNSysInfo(50); \n mgr->SetCacheSize(0);\n\n \/\/ Input\n AliESDInputHandler* inpHandler = new AliESDInputHandler();\n inpHandler->SetReadFriends(1);\n mgr->SetInputEventHandler(inpHandler);\n \n \/\/ Output\n const char *outFile = \"AliESDfriends_v1.root\";\n AliESDHandler* esdHandler = new AliESDHandler();\n mgr->SetOutputEventHandler(esdHandler);\n esdHandler->SetOutputFileName(outFile);\n mgr->SetCommonFileName(outFile);\n \/\/ \n \/\/ Detector Tasks\n \/\/\n AliSysInfo::AddStamp(\"BeforeTPC\");\n if ( detStr.Contains(\"TPC\")) AddTaskTPCCalib(runNumber);\n\n AliSysInfo::AddStamp(\"BeforeTRD\");\n if ( detStr.Contains(\"TRD\") && detStr.Contains(\"TPC\")) AddTaskTRDCalib(runNumber);\n\n AliSysInfo::AddStamp(\"BeforeTOF\");\n if ( detStr.Contains(\"TOF\") && detStr.Contains(\"TPC\")) {\n AddTOFAnalysisTaskCalibPass0();\n AddTOFAnalysisTaskCalibTree();\n }\n\n AliSysInfo::AddStamp(\"BeforeT0\");\n if ( detStr.Contains(\"T0\")) {\n AddTaskT0Calib(runNumber);\n AddTaskT0Analysis();\n }\n\n \/\/if ( detStr.Contains(\"ITSSPD\")) tMeanVtx = AddTaskMeanVertexCalib();\n \/\/\n Bool_t okTPC = detStr.Contains(\"TPC\");\n Bool_t useTPCcrv=kFALSE;\n Bool_t writeITSTP = kFALSE;\n if (!okTPC) useTPCcrv = kFALSE;\n AliSysInfo::AddStamp(\"BeforeSDD\");\n AliAnalysisTaskITSAlignQA *itsAlign = AddTaskSDDCalib(0,writeITSTP,useTPCcrv,detStr.Contains(\"TOF\") ? 10.0:-1);\n if (!okTPC) itsAlign->SetUseITSstandaloneTracks(kTRUE);\n if (grpData->GetL3Current()[0] < 300) itsAlign->SetMinPt(0.001); \n \/\/\n \/\/ dummy task to clean geometry in Terminate >>>>\n \/\/CleanGeom* clgmTask = new CleanGeom(\"cleanGeom\");\n \/\/mgr->AddTask(clgmTask);\n \/\/ AliAnalysisDataContainer *dummyInp = mgr->GetCommonInputContainer();\n \/\/ if (dummyInp) mgr->ConnectInput(clgmTask,0,dummyInp);\n\n \/\/ Run the analysis\n AliSysInfo::AddStamp(\"BeforeInitAnalysis\");\n if (!mgr->InitAnalysis()) {\n printf(\"Analysis cannot be started, returning\\n\");\n return;\n }\n \n mgr->PrintStatus();\n AliSysInfo::AddStamp(\"BeforeStartAnalysis\");\n mgr->StartAnalysis(\"local\", chain);\n \n return;\n}\n<commit_msg>Restoring use of CleanGeom task<commit_after>\/*\n Template of calibration\/filtering macro using ESD:\n - requires AliESDs.root and AliESDfriend.root\n - requires OCDB access (default set to \"raw:\/\/\")\n - requires run number as argument to init OCDB\n - calls LoadLibraries.C, ConfigCalibTrain.C and AddTaskTPCCalib.C macros\n - output AliESDfriends_v1.root with TPC and TRD calibration objects are created\n\n Example:\n .L $ALICE_ROOT\/ANALYSIS\/macros\/runCalibTrain.C\n runCalibTrain(\"104892\");\n*\/\n\nvoid runCalibTrain(Int_t runNumber, const char *inFileName = \"AliESDs.root\", const char *ocdb=\"raw:\/\/\")\n{\n \/\/\n \/\/ macro to run TPC calibration train \n \/\/\n AliSysInfo::SetVerbose(kTRUE);\n AliLog::SetGlobalLogLevel(AliLog::kError); \n gROOT->Macro(\"$ALICE_PHYSICS\/PWGPP\/CalibMacros\/CPass1\/LoadLibraries.C\");\n gROOT->LoadMacro(\"$ALICE_PHYSICS\/PWGPP\/CalibMacros\/CPass1\/ConfigCalibTrain.C\");\n gSystem->SetIncludePath(\"-I$ALICE_PHYSICS\/include -I$ALICE_ROOT\/include\"); \n if (gSystem->Exec(\"cp $ALICE_PHYSICS\/PWGPP\/CalibMacros\/commonMacros\/CleanGeom.C .\/\") ||\n gROOT->LoadMacro(\"CleanGeom.C++\")) { \/\/ comple local copy only\n printf(\"Failed to load\/compile CleanGeom, exit\\n\");\n return;\n }\n \/\/ detector tasks\n gROOT->LoadMacro(\"$ALICE_PHYSICS\/PWGPP\/CalibMacros\/CPass1\/AddTaskTPCCalib.C\");\n gROOT->LoadMacro(\"$ALICE_PHYSICS\/PWGPP\/CalibMacros\/CPass1\/AddTaskTRDCalib.C\");\n gROOT->LoadMacro(\"$ALICE_PHYSICS\/PWGPP\/CalibMacros\/CPass1\/AddTOFAnalysisTaskCalibPass0.C\");\n gROOT->LoadMacro(\"$ALICE_PHYSICS\/PWGPP\/CalibMacros\/CPass1\/AddTOFAnalysisTaskCalibTree.C\");\n gROOT->LoadMacro(\"$ALICE_PHYSICS\/PWGPP\/CalibMacros\/CPass1\/AddTaskT0Calib.C\");\n gROOT->LoadMacro(\"$ALICE_PHYSICS\/PWGPP\/CalibMacros\/CPass1\/AddTaskT0Analysis.C\");\n \/\/ gROOT->LoadMacro(\"$ALICE_PHYSICS\/PWGPP\/CalibMacros\/CPass1\/AddTaskMeanVertexCalib.C\");\n gROOT->LoadMacro(\"$ALICE_PHYSICS\/PWGPP\/CalibMacros\/CPass1\/AddTaskSDDCalib.C\"); \n\n \/\/ switch off debug \n AliLog::SetClassDebugLevel(\"AliESDEvent\",0);\n \n \/\/ steering input chain\n TChain *chain = new TChain(\"esdTree\");\n chain->Add(inFileName);\n\n \/\/ config calibration train\n \/\/ setting geometry and B-field from GRP\n printf(\"runNumber from runCalibTrain = %d\\n\",runNumber);\n printf(\"ocdb from runCalibTrain = %s\\n\",ocdb);\n AliSysInfo::AddStamp(\"BeforeConfiguringCalibTrain\");\n ConfigCalibTrain(runNumber, ocdb);\n AliSysInfo::AddStamp(\"AfterConfiguringCalibTrain\"); \n \n if (gROOT->LoadMacro(\"localOCDBaccessConfig.C\")==0) {\n localOCDBaccessConfig();\n }\n \n \/\/\n \/\/ check the presence of the detectors\n AliCDBEntry* entry = AliCDBManager::Instance()->Get(\"GRP\/GRP\/Data\");\n AliGRPObject* grpData = dynamic_cast<AliGRPObject*>(entry->GetObject()); \n if (!grpData) {printf(\"Failed to get GRP data for run\",runNumber); return;}\n Int_t activeDetectors = grpData->GetDetectorMask(); \n TString detStr = AliDAQ::ListOfTriggeredDetectors(activeDetectors);\n printf(\"Detectors in the data:\\n%s\\n\",detStr.Data());\n\n \/\/ setup analysis\n \/\/\n AliAnalysisManager *mgr = new AliAnalysisManager(\"ESD to ESD\", \"Analysis Manager\");\n \/\/ mgr->SetDebugLevel(3);\n mgr->SetNSysInfo(50); \n mgr->SetCacheSize(0);\n\n \/\/ Input\n AliESDInputHandler* inpHandler = new AliESDInputHandler();\n inpHandler->SetReadFriends(1);\n mgr->SetInputEventHandler(inpHandler);\n \n \/\/ Output\n const char *outFile = \"AliESDfriends_v1.root\";\n AliESDHandler* esdHandler = new AliESDHandler();\n mgr->SetOutputEventHandler(esdHandler);\n esdHandler->SetOutputFileName(outFile);\n mgr->SetCommonFileName(outFile);\n \/\/ \n \/\/ Detector Tasks\n \/\/\n AliSysInfo::AddStamp(\"BeforeTPC\");\n if ( detStr.Contains(\"TPC\")) AddTaskTPCCalib(runNumber);\n\n AliSysInfo::AddStamp(\"BeforeTRD\");\n if ( detStr.Contains(\"TRD\") && detStr.Contains(\"TPC\")) AddTaskTRDCalib(runNumber);\n\n AliSysInfo::AddStamp(\"BeforeTOF\");\n if ( detStr.Contains(\"TOF\") && detStr.Contains(\"TPC\")) {\n AddTOFAnalysisTaskCalibPass0();\n AddTOFAnalysisTaskCalibTree();\n }\n\n AliSysInfo::AddStamp(\"BeforeT0\");\n if ( detStr.Contains(\"T0\")) {\n AddTaskT0Calib(runNumber);\n AddTaskT0Analysis();\n }\n\n \/\/if ( detStr.Contains(\"ITSSPD\")) tMeanVtx = AddTaskMeanVertexCalib();\n \/\/\n Bool_t okTPC = detStr.Contains(\"TPC\");\n Bool_t useTPCcrv=kFALSE;\n Bool_t writeITSTP = kFALSE;\n if (!okTPC) useTPCcrv = kFALSE;\n AliSysInfo::AddStamp(\"BeforeSDD\");\n AliAnalysisTaskITSAlignQA *itsAlign = AddTaskSDDCalib(0,writeITSTP,useTPCcrv,detStr.Contains(\"TOF\") ? 10.0:-1);\n if (!okTPC) itsAlign->SetUseITSstandaloneTracks(kTRUE);\n if (grpData->GetL3Current()[0] < 300) itsAlign->SetMinPt(0.001); \n \/\/\n \/\/ dummy task to clean geometry in Terminate >>>>\n CleanGeom* clgmTask = new CleanGeom(\"cleanGeom\");\n mgr->AddTask(clgmTask);\n AliAnalysisDataContainer *dummyInp = mgr->GetCommonInputContainer();\n if (dummyInp) mgr->ConnectInput(clgmTask,0,dummyInp);\n\n \/\/ Run the analysis\n AliSysInfo::AddStamp(\"BeforeInitAnalysis\");\n if (!mgr->InitAnalysis()) {\n printf(\"Analysis cannot be started, returning\\n\");\n return;\n }\n \n mgr->PrintStatus();\n AliSysInfo::AddStamp(\"BeforeStartAnalysis\");\n mgr->StartAnalysis(\"local\", chain);\n \n return;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Qt includes\n#include <QUrl>\n#include <QRegExp>\n#include <QStringRef>\n\n#include <xbmcvideochecker\/XBMCVideoChecker.h>\n\n\/\/ Request player example:\n\/\/ {\"jsonrpc\":\"2.0\",\"method\":\"Player.GetActivePlayers\", \"id\":666}\n\/\/ {\"id\":666,\"jsonrpc\":\"2.0\",\"result\":[{\"playerid\":1,\"type\":\"video\"}]}\n\n\/\/ Request playing item example:\n\/\/ {\"id\":667,\"jsonrpc\":\"2.0\",\"method\":\"Player.GetItem\",\"params\":{\"playerid\":1,\"properties\":[\"file\"]}}\n\/\/ {\"id\":667,\"jsonrpc\":\"2.0\",\"result\":{\"item\":{\"file\":\"smb:\/\/xbmc:xbmc@192.168.53.12\/video\/Movies\/Avatar (2009)\/Avatar.mkv\",\"label\":\"Avatar\",\"type\":\"unknown\"}}}\n\n\/\/ Request if screensaver is on\n\/\/ {\"id\":668,\"jsonrpc\":\"2.0\",\"method\":\"XBMC.GetInfoBooleans\",\"params\":{\"booleans\":[\"System.ScreenSaverActive\"]}}\n\/\/ {\"id\":668,\"jsonrpc\":\"2.0\",\"result\":{\"System.ScreenSaverActive\":false}}\n\n\/\/ Request stereoscopicmode example:\n\/\/ {\"jsonrpc\":\"2.0\",\"method\":\"GUI.GetProperties\",\"params\":{\"properties\":[\"stereoscopicmode\"]},\"id\":669}\n\/\/ {\"id\":669,\"jsonrpc\":\"2.0\",\"result\":{\"stereoscopicmode\":{\"label\":\"Nebeneinander\",\"mode\":\"split_vertical\"}}}\n\nXBMCVideoChecker::XBMCVideoChecker(const std::string & address, uint16_t port, bool grabVideo, bool grabPhoto, bool grabAudio, bool grabMenu, bool grabScreensaver, bool enable3DDetection) :\n\tQObject(),\n\t_address(QString::fromStdString(address)),\n\t_port(port),\n\t_activePlayerRequest(R\"({\"jsonrpc\":\"2.0\",\"method\":\"Player.GetActivePlayers\", \"id\":666})\"),\n\t_currentPlayingItemRequest(R\"({\"id\":667,\"jsonrpc\":\"2.0\",\"method\":\"Player.GetItem\",\"params\":{\"playerid\":%1,\"properties\":[\"file\"]}})\"),\n\t_checkScreensaverRequest(R\"({\"id\":668,\"jsonrpc\":\"2.0\",\"method\":\"XBMC.GetInfoBooleans\",\"params\":{\"booleans\":[\"System.ScreenSaverActive\"]}})\"),\n\t_getStereoscopicMode(R\"({\"jsonrpc\":\"2.0\",\"method\":\"GUI.GetProperties\",\"params\":{\"properties\":[\"stereoscopicmode\"]},\"id\":669})\"),\n\t_getXbmcVersion(R\"({\"jsonrpc\":\"2.0\",\"method\":\"Application.GetProperties\",\"params\":{\"properties\":[\"version\"]},\"id\":670})\"),\n\t_socket(),\n\t_grabVideo(grabVideo),\n\t_grabPhoto(grabPhoto),\n\t_grabAudio(grabAudio),\n\t_grabMenu(grabMenu),\n\t_grabScreensaver(grabScreensaver),\n\t_enable3DDetection(enable3DDetection),\n\t_previousScreensaverMode(false),\n\t_previousGrabbingMode(GRABBINGMODE_INVALID),\n\t_previousVideoMode(VIDEO_2D),\n\t_xbmcVersion(0)\n{\n\t\/\/ setup socket\n\tconnect(&_socket, SIGNAL(readyRead()), this, SLOT(receiveReply()));\n\tconnect(&_socket, SIGNAL(disconnected()), this, SLOT(disconnected()));\n\tconnect(&_socket, SIGNAL(connected()), this, SLOT(connected()));\n\tconnect(&_socket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(connectionError(QAbstractSocket::SocketError)));\n}\n\nvoid XBMCVideoChecker::start()\n{\n\treconnect();\n}\n\nvoid XBMCVideoChecker::receiveReply()\n{\n\t\/\/ expect that the reply is received as a single message. Probably oke considering the size of the expected reply\n\tQString reply(_socket.readAll());\n\n\tstd::cout << \"KODICHECK INFO: Kodi Message: \" << reply.toStdString() << std::endl;\n\n\tif (reply.contains(\"\\\"method\\\":\\\"Player.OnPlay\\\"\") || reply.contains(\"\\\"method\\\":\\\"Playlist.OnAdd\\\"\"))\n\t{\n\t\t\/\/ send a request for the current player state\n\t\t_socket.write(_activePlayerRequest.toUtf8());\n\t\treturn;\n\t}\n\telse if (reply.contains(\"\\\"method\\\":\\\"Player.OnStop\\\"\"))\n\t{\n\t\t\/\/ the player has stopped\n\t\tsetGrabbingMode(_grabMenu ? GRABBINGMODE_MENU : GRABBINGMODE_OFF);\n\t\tsetVideoMode(VIDEO_2D);\n\t}\n\telse if (reply.contains(\"\\\"method\\\":\\\"GUI.OnScreensaverActivated\\\"\"))\n\t{\n\t\tsetScreensaverMode(!_grabScreensaver);\n\t}\n\telse if (reply.contains(\"\\\"method\\\":\\\"GUI.OnScreensaverDeactivated\\\"\"))\n\t{\n\t\tsetScreensaverMode(false);\n\t}\n\telse if (reply.contains(\"\\\"id\\\":666\"))\n\t{\n\t\t\/\/ Result of Player.GetActivePlayers\n\n\t\t\/\/ always start a new video in 2D mode\n\t\temit videoMode(VIDEO_2D);\n\n\t\tif (reply.contains(\"video\"))\n\t\t{\n\t\t\t\/\/ video is playing\n\t\t\tsetGrabbingMode(_grabVideo ? GRABBINGMODE_VIDEO : GRABBINGMODE_OFF);\n\n\t\t\t\/\/ we need to get the filename\n\t\t\t\/\/ first retrieve the playerid\n\t\t\tQString key = \"\\\"playerid\\\":\";\n\t\t\tQRegExp regex(key + \"(\\\\d+)\");\n\t\t\tint pos = regex.indexIn(reply);\n\t\t\tif (pos > 0)\n\t\t\t{\n\t\t\t\t\/\/ now request info of the playing item\n\t\t\t\tQStringRef idText(&reply, pos + key.length(), regex.matchedLength() - key.length());\n\t\t\t\t_socket.write(_currentPlayingItemRequest.arg(idText.toString()).toUtf8());\n\t\t\t}\n\t\t}\n\t\telse if (reply.contains(\"picture\"))\n\t\t{\n\t\t\t\/\/ picture viewer is playing\n\t\t\tsetGrabbingMode(_grabPhoto ? GRABBINGMODE_PHOTO : GRABBINGMODE_OFF);\n\t\t}\n\t\telse if (reply.contains(\"audio\"))\n\t\t{\n\t\t\t\/\/ audio is playing\n\t\t\tsetGrabbingMode(_grabAudio ? GRABBINGMODE_AUDIO : GRABBINGMODE_OFF);\n\t\t}\n\t\telse\n\t\t{\n\t\t\t\/\/ Nothing is playing.\n\t\t\tsetGrabbingMode(_grabMenu ? GRABBINGMODE_MENU : GRABBINGMODE_OFF);\n\t\t}\n\t}\n\telse if (reply.contains(\"\\\"id\\\":667\"))\n\t{\n\t\tif (_xbmcVersion >= 13)\n\t\t{\n\t\t\t\/\/ check of active stereoscopicmode\n\t\t\t_socket.write(_getStereoscopicMode.toUtf8());\n\t\t}\n\t\telse\n\t\t{\n\t\t\t\/\/ result of Player.GetItem\n\t\t\t\/\/ TODO: what if the filename contains a '\"'. In Json this should have been escaped\n\t\t\tQRegExp regex(\"\\\"file\\\":\\\"((?!\\\").)*\\\"\");\n\t\t\tint pos = regex.indexIn(reply);\n\t\t\tif (pos > 0)\n\t\t\t{\n\t\t\t\tQStringRef filename = QStringRef(&reply, pos+8, regex.matchedLength()-9);\n\t\t\t\tif (filename.contains(\"3DSBS\", Qt::CaseInsensitive) || filename.contains(\"HSBS\", Qt::CaseInsensitive))\n\t\t\t\t{\n\t\t\t\t\tsetVideoMode(VIDEO_3DSBS);\n\t\t\t\t}\n\t\t\t\telse if (filename.contains(\"3DTAB\", Qt::CaseInsensitive) || filename.contains(\"HTAB\", Qt::CaseInsensitive))\n\t\t\t\t{\n\t\t\t\t\tsetVideoMode(VIDEO_3DTAB);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tsetVideoMode(VIDEO_2D);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\telse if (reply.contains(\"\\\"id\\\":668\"))\n\t{\n\t\t\/\/ result of System.ScreenSaverActive\n\t\tbool active = reply.contains(\"\\\"System.ScreenSaverActive\\\":true\");\n\t\tsetScreensaverMode(!_grabScreensaver && active);\n\n\t\t\/\/ check here xbmc version\n\t\tif (_socket.state() == QTcpSocket::ConnectedState)\n\t\t{\n\t\t\tif (_xbmcVersion == 0)\n\t\t\t{\n\t\t\t\t_socket.write(_getXbmcVersion.toUtf8());\n\t\t\t}\n\t\t}\n\t}\n\telse if (reply.contains(\"\\\"id\\\":669\"))\n\t{\n\t\tQRegExp regex(\"\\\"mode\\\":\\\"(split_vertical|split_horizontal)\\\"\");\n\t\tint pos = regex.indexIn(reply);\n\t\tif (pos > 0)\n\t\t{\n\t\t\tQString sMode = regex.cap(1);\n\t\t\tif (sMode == \"split_vertical\")\n\t\t\t{\n\t\t\t\tsetVideoMode(VIDEO_3DSBS);\n\t\t\t}\n\t\t\telse if (sMode == \"split_horizontal\")\n\t\t\t{\n\t\t\t\tsetVideoMode(VIDEO_3DTAB);\n\t\t\t}\n\t\t}\n\t}\n\telse if (reply.contains(\"\\\"id\\\":670\"))\n\t{\n\t\tQRegExp regex(\"\\\"major\\\":(\\\\d+)\");\n\t\tint pos = regex.indexIn(reply);\n\t\tif (pos > 0)\n\t\t{\n\t\t\t_xbmcVersion = regex.cap(1).toInt();\n\t\t}\n\t}\n}\n\nvoid XBMCVideoChecker::connected()\n{\n\tstd::cout << \"KODICHECK INFO: Kodi Connected\" << std::endl;\n\n\t\/\/ send a request for the current player state\n\t_socket.write(_activePlayerRequest.toUtf8());\n\t_socket.write(_checkScreensaverRequest.toUtf8());\n}\n\nvoid XBMCVideoChecker::disconnected()\n{\n\tstd::cout << \"KODICHECK INFO: Kodi Disconnected\" << std::endl;\n\treconnect();\n}\n\nvoid XBMCVideoChecker::reconnect()\n{\n\tif (_socket.state() == QTcpSocket::ConnectedState)\n\t{\n\t\treturn;\n\t}\n\n\t\/\/ try to connect\n\tswitch (_socket.state())\n\t{\n\tcase QTcpSocket::ConnectingState:\n\t\t\/\/ Somehow when XBMC restarts we get stuck in connecting state\n\t\t\/\/ If we get here we tried to connect already for 5 seconds. abort and try again in 1 second.\n\t\t_socket.reset();\n\t\t_socket.waitForDisconnected(50);\n\t\tQTimer::singleShot(1000, this, SLOT(reconnect()));\n\t\tbreak;\n\tcase QTcpSocket::UnconnectedState:\n\t\t_socket.connectToHost(_address, _port);\n\t\tQTimer::singleShot(10000, this, SLOT(reconnect()));\n\t\tbreak;\n\tdefault:\n\t\tQTimer::singleShot(10000, this, SLOT(reconnect()));\n\t\tbreak;\n\t}\n}\n\nvoid XBMCVideoChecker::connectionError(QAbstractSocket::SocketError error)\n{\n\tstd::cout << \"KODICHECK ERROR: Kodi Connection error (\" << error << \")\" << std::endl;\n\n\t\/\/ close the socket\n\t_socket.close();\n}\n\nvoid XBMCVideoChecker::setGrabbingMode(GrabbingMode newGrabbingMode)\n{\n\tif (newGrabbingMode == _previousGrabbingMode)\n\t{\n\t\t\/\/ no change\n\t\treturn;\n\t}\n\n\tswitch (newGrabbingMode)\n\t{\n\tcase GRABBINGMODE_VIDEO:\n\t\tstd::cout << \"KODICHECK INFO: switching to VIDEO mode\" << std::endl;\n\t\tbreak;\n\tcase GRABBINGMODE_PHOTO:\n\t\tstd::cout << \"KODICHECK INFO: switching to PHOTO mode\" << std::endl;\n\t\tbreak;\n\tcase GRABBINGMODE_AUDIO:\n\t\tstd::cout << \"KODICHECK INFO: switching to AUDIO mode\" << std::endl;\n\t\tbreak;\n\tcase GRABBINGMODE_MENU:\n\t\tstd::cout << \"KODICHECK INFO: switching to MENU mode\" << std::endl;\n\t\tbreak;\n\tcase GRABBINGMODE_OFF:\n\t\tstd::cout << \"KODICHECK INFO: switching to OFF mode\" << std::endl;\n\t\tbreak;\n\tcase GRABBINGMODE_INVALID:\n\t\tstd::cout << \"KODICHECK INFO: switching to INVALID mode\" << std::endl;\n\t\tbreak;\n\t}\n\n\t\/\/ only emit the new state when we want to grab in screensaver mode or when the screensaver is deactivated\n\tif (!_previousScreensaverMode)\n\t{\n\t\temit grabbingMode(newGrabbingMode);\n\t}\n\t_previousGrabbingMode = newGrabbingMode;\n}\n\nvoid XBMCVideoChecker::setScreensaverMode(bool isOnScreensaver)\n{\n\tif (isOnScreensaver == _previousScreensaverMode)\n\t{\n\t\t\/\/ no change\n\t\treturn;\n\t}\n\n\temit grabbingMode(isOnScreensaver ? GRABBINGMODE_OFF : _previousGrabbingMode);\n\t_previousScreensaverMode = isOnScreensaver;\n}\n\nvoid XBMCVideoChecker::setVideoMode(VideoMode newVideoMode)\n{\n\tif (newVideoMode == _previousVideoMode)\n\t{\n\t\t\/\/ no change\n\t\treturn;\n\t}\n\n\tswitch (newVideoMode)\n\t{\n\tcase VIDEO_2D:\n\t\tstd::cout << \"KODICHECK INFO: switching to 2D mode\" << std::endl;\n\t\tbreak;\n\tcase VIDEO_3DSBS:\n\t\tstd::cout << \"KODICHECK INFO: switching to 3D SBS mode\" << std::endl;\n\t\tbreak;\n\tcase VIDEO_3DTAB:\n\t\tstd::cout << \"KODICHECK INFO: switching to 3D TAB mode\" << std::endl;\n\t\tbreak;\n\t}\n\n\temit videoMode(newVideoMode);\n\t_previousVideoMode = newVideoMode;\n}\n<commit_msg>xbmc checker fix (3)<commit_after>\/\/ Qt includes\n#include <QUrl>\n#include <QRegExp>\n#include <QStringRef>\n\n#include <xbmcvideochecker\/XBMCVideoChecker.h>\n\n\/\/ Request player example:\n\/\/ {\"jsonrpc\":\"2.0\",\"method\":\"Player.GetActivePlayers\", \"id\":666}\n\/\/ {\"id\":666,\"jsonrpc\":\"2.0\",\"result\":[{\"playerid\":1,\"type\":\"video\"}]}\n\n\/\/ Request playing item example:\n\/\/ {\"id\":667,\"jsonrpc\":\"2.0\",\"method\":\"Player.GetItem\",\"params\":{\"playerid\":1,\"properties\":[\"file\"]}}\n\/\/ {\"id\":667,\"jsonrpc\":\"2.0\",\"result\":{\"item\":{\"file\":\"smb:\/\/xbmc:xbmc@192.168.53.12\/video\/Movies\/Avatar (2009)\/Avatar.mkv\",\"label\":\"Avatar\",\"type\":\"unknown\"}}}\n\n\/\/ Request if screensaver is on\n\/\/ {\"id\":668,\"jsonrpc\":\"2.0\",\"method\":\"XBMC.GetInfoBooleans\",\"params\":{\"booleans\":[\"System.ScreenSaverActive\"]}}\n\/\/ {\"id\":668,\"jsonrpc\":\"2.0\",\"result\":{\"System.ScreenSaverActive\":false}}\n\n\/\/ Request stereoscopicmode example:\n\/\/ {\"jsonrpc\":\"2.0\",\"method\":\"GUI.GetProperties\",\"params\":{\"properties\":[\"stereoscopicmode\"]},\"id\":669}\n\/\/ {\"id\":669,\"jsonrpc\":\"2.0\",\"result\":{\"stereoscopicmode\":{\"label\":\"Nebeneinander\",\"mode\":\"split_vertical\"}}}\n\nXBMCVideoChecker::XBMCVideoChecker(const std::string & address, uint16_t port, bool grabVideo, bool grabPhoto, bool grabAudio, bool grabMenu, bool grabScreensaver, bool enable3DDetection) :\n\tQObject(),\n\t_address(QString::fromStdString(address)),\n\t_port(port),\n\t_activePlayerRequest(R\"({\"jsonrpc\":\"2.0\",\"method\":\"Player.GetActivePlayers\", \"id\":666})\"),\n\t_currentPlayingItemRequest(R\"({\"id\":667,\"jsonrpc\":\"2.0\",\"method\":\"Player.GetItem\",\"params\":{\"playerid\":%1,\"properties\":[\"file\"]}})\"),\n\t_checkScreensaverRequest(R\"({\"id\":668,\"jsonrpc\":\"2.0\",\"method\":\"XBMC.GetInfoBooleans\",\"params\":{\"booleans\":[\"System.ScreenSaverActive\"]}})\"),\n\t_getStereoscopicMode(R\"({\"jsonrpc\":\"2.0\",\"method\":\"GUI.GetProperties\",\"params\":{\"properties\":[\"stereoscopicmode\"]},\"id\":669})\"),\n\t_getXbmcVersion(R\"({\"jsonrpc\":\"2.0\",\"method\":\"Application.GetProperties\",\"params\":{\"properties\":[\"version\"]},\"id\":670})\"),\n\t_socket(),\n\t_grabVideo(grabVideo),\n\t_grabPhoto(grabPhoto),\n\t_grabAudio(grabAudio),\n\t_grabMenu(grabMenu),\n\t_grabScreensaver(grabScreensaver),\n\t_enable3DDetection(enable3DDetection),\n\t_previousScreensaverMode(false),\n\t_previousGrabbingMode(GRABBINGMODE_INVALID),\n\t_previousVideoMode(VIDEO_2D),\n\t_xbmcVersion(0)\n{\n\t\/\/ setup socket\n\tconnect(&_socket, SIGNAL(readyRead()), this, SLOT(receiveReply()));\n\tconnect(&_socket, SIGNAL(disconnected()), this, SLOT(disconnected()));\n\tconnect(&_socket, SIGNAL(connected()), this, SLOT(connected()));\n\tconnect(&_socket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(connectionError(QAbstractSocket::SocketError)));\n}\n\nvoid XBMCVideoChecker::start()\n{\n\treconnect();\n}\n\nvoid XBMCVideoChecker::receiveReply()\n{\n\t\/\/ expect that the reply is received as a single message. Probably oke considering the size of the expected reply\n\tQString reply(_socket.readAll());\n\n\tstd::cout << \"KODICHECK INFO: Kodi Message: \" << reply.toStdString() << std::endl;\n\n\tif (reply.contains(\"\\\"method\\\":\\\"Player.OnPlay\\\"\"))\n\t{\n\t\t\/\/ send a request for the current player state\n\t\t_socket.write(_activePlayerRequest.toUtf8());\n\t\treturn;\n\t}\n\telse if (reply.contains(\"\\\"method\\\":\\\"Player.OnStop\\\"\"))\n\t{\n\t\t\/\/ the player has stopped\n\t\tsetGrabbingMode(_grabMenu ? GRABBINGMODE_MENU : GRABBINGMODE_OFF);\n\t\tsetVideoMode(VIDEO_2D);\n\t}\n\telse if (reply.contains(\"\\\"method\\\":\\\"GUI.OnScreensaverActivated\\\"\"))\n\t{\n\t\tsetScreensaverMode(!_grabScreensaver);\n\t}\n\telse if (reply.contains(\"\\\"method\\\":\\\"GUI.OnScreensaverDeactivated\\\"\"))\n\t{\n\t\tsetScreensaverMode(false);\n\t}\n\telse if (reply.contains(\"\\\"id\\\":666\"))\n\t{\n\t\t\/\/ Result of Player.GetActivePlayers\n\n\t\t\/\/ always start a new video in 2D mode\n\t\temit videoMode(VIDEO_2D);\n\n\t\tif (reply.contains(\"video\"))\n\t\t{\n\t\t\t\/\/ video is playing\n\t\t\tsetGrabbingMode(_grabVideo ? GRABBINGMODE_VIDEO : GRABBINGMODE_OFF);\n\n\t\t\t\/\/ we need to get the filename\n\t\t\t\/\/ first retrieve the playerid\n\t\t\tQString key = \"\\\"playerid\\\":\";\n\t\t\tQRegExp regex(key + \"(\\\\d+)\");\n\t\t\tint pos = regex.indexIn(reply);\n\t\t\tif (pos > 0)\n\t\t\t{\n\t\t\t\t\/\/ now request info of the playing item\n\t\t\t\tQStringRef idText(&reply, pos + key.length(), regex.matchedLength() - key.length());\n\t\t\t\t_socket.write(_currentPlayingItemRequest.arg(idText.toString()).toUtf8());\n\t\t\t}\n\t\t}\n\t\telse if (reply.contains(\"picture\"))\n\t\t{\n\t\t\t\/\/ picture viewer is playing\n\t\t\tsetGrabbingMode(_grabPhoto ? GRABBINGMODE_PHOTO : GRABBINGMODE_OFF);\n\t\t}\n\t\telse if (reply.contains(\"audio\"))\n\t\t{\n\t\t\t\/\/ audio is playing\n\t\t\tsetGrabbingMode(_grabAudio ? GRABBINGMODE_AUDIO : GRABBINGMODE_OFF);\n\t\t}\n\t\telse\n\t\t{\n\t\t\t\/\/ Nothing is playing.\n\t\t\tsetGrabbingMode(_grabMenu ? GRABBINGMODE_MENU : GRABBINGMODE_OFF);\n\t\t}\n\t}\n\telse if (reply.contains(\"\\\"id\\\":667\"))\n\t{\n\t\tif (_xbmcVersion >= 13)\n\t\t{\n\t\t\t\/\/ check of active stereoscopicmode\n\t\t\t_socket.write(_getStereoscopicMode.toUtf8());\n\t\t}\n\t\telse\n\t\t{\n\t\t\t\/\/ result of Player.GetItem\n\t\t\t\/\/ TODO: what if the filename contains a '\"'. In Json this should have been escaped\n\t\t\tQRegExp regex(\"\\\"file\\\":\\\"((?!\\\").)*\\\"\");\n\t\t\tint pos = regex.indexIn(reply);\n\t\t\tif (pos > 0)\n\t\t\t{\n\t\t\t\tQStringRef filename = QStringRef(&reply, pos+8, regex.matchedLength()-9);\n\t\t\t\tif (filename.contains(\"3DSBS\", Qt::CaseInsensitive) || filename.contains(\"HSBS\", Qt::CaseInsensitive))\n\t\t\t\t{\n\t\t\t\t\tsetVideoMode(VIDEO_3DSBS);\n\t\t\t\t}\n\t\t\t\telse if (filename.contains(\"3DTAB\", Qt::CaseInsensitive) || filename.contains(\"HTAB\", Qt::CaseInsensitive))\n\t\t\t\t{\n\t\t\t\t\tsetVideoMode(VIDEO_3DTAB);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tsetVideoMode(VIDEO_2D);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\telse if (reply.contains(\"\\\"id\\\":668\"))\n\t{\n\t\t\/\/ result of System.ScreenSaverActive\n\t\tbool active = reply.contains(\"\\\"System.ScreenSaverActive\\\":true\");\n\t\tsetScreensaverMode(!_grabScreensaver && active);\n\n\t\t\/\/ check here xbmc version\n\t\tif (_socket.state() == QTcpSocket::ConnectedState)\n\t\t{\n\t\t\tif (_xbmcVersion == 0)\n\t\t\t{\n\t\t\t\t_socket.write(_getXbmcVersion.toUtf8());\n\t\t\t}\n\t\t}\n\t}\n\telse if (reply.contains(\"\\\"id\\\":669\"))\n\t{\n\t\tQRegExp regex(\"\\\"mode\\\":\\\"(split_vertical|split_horizontal)\\\"\");\n\t\tint pos = regex.indexIn(reply);\n\t\tif (pos > 0)\n\t\t{\n\t\t\tQString sMode = regex.cap(1);\n\t\t\tif (sMode == \"split_vertical\")\n\t\t\t{\n\t\t\t\tsetVideoMode(VIDEO_3DSBS);\n\t\t\t}\n\t\t\telse if (sMode == \"split_horizontal\")\n\t\t\t{\n\t\t\t\tsetVideoMode(VIDEO_3DTAB);\n\t\t\t}\n\t\t}\n\t}\n\telse if (reply.contains(\"\\\"id\\\":670\"))\n\t{\n\t\tQRegExp regex(\"\\\"major\\\":(\\\\d+)\");\n\t\tint pos = regex.indexIn(reply);\n\t\tif (pos > 0)\n\t\t{\n\t\t\t_xbmcVersion = regex.cap(1).toInt();\n\t\t}\n\t}\n\telse if (reply.contains(\"picture\") && reply.contains(\"\\\"method\\\":\\\"Playlist.OnAdd\\\"\"))\n\t{\n\t\t\/\/ picture viewer is playing\n\t\tsetGrabbingMode(_grabPhoto ? GRABBINGMODE_PHOTO : GRABBINGMODE_OFF);\n\t}\n}\n\nvoid XBMCVideoChecker::connected()\n{\n\tstd::cout << \"KODICHECK INFO: Kodi Connected\" << std::endl;\n\n\t\/\/ send a request for the current player state\n\t_socket.write(_activePlayerRequest.toUtf8());\n\t_socket.write(_checkScreensaverRequest.toUtf8());\n}\n\nvoid XBMCVideoChecker::disconnected()\n{\n\tstd::cout << \"KODICHECK INFO: Kodi Disconnected\" << std::endl;\n\treconnect();\n}\n\nvoid XBMCVideoChecker::reconnect()\n{\n\tif (_socket.state() == QTcpSocket::ConnectedState)\n\t{\n\t\treturn;\n\t}\n\n\t\/\/ try to connect\n\tswitch (_socket.state())\n\t{\n\tcase QTcpSocket::ConnectingState:\n\t\t\/\/ Somehow when XBMC restarts we get stuck in connecting state\n\t\t\/\/ If we get here we tried to connect already for 5 seconds. abort and try again in 1 second.\n\t\t_socket.reset();\n\t\t_socket.waitForDisconnected(50);\n\t\tQTimer::singleShot(1000, this, SLOT(reconnect()));\n\t\tbreak;\n\tcase QTcpSocket::UnconnectedState:\n\t\t_socket.connectToHost(_address, _port);\n\t\tQTimer::singleShot(10000, this, SLOT(reconnect()));\n\t\tbreak;\n\tdefault:\n\t\tQTimer::singleShot(10000, this, SLOT(reconnect()));\n\t\tbreak;\n\t}\n}\n\nvoid XBMCVideoChecker::connectionError(QAbstractSocket::SocketError error)\n{\n\tstd::cout << \"KODICHECK ERROR: Kodi Connection error (\" << error << \")\" << std::endl;\n\n\t\/\/ close the socket\n\t_socket.close();\n}\n\nvoid XBMCVideoChecker::setGrabbingMode(GrabbingMode newGrabbingMode)\n{\n\tif (newGrabbingMode == _previousGrabbingMode)\n\t{\n\t\t\/\/ no change\n\t\treturn;\n\t}\n\n\tswitch (newGrabbingMode)\n\t{\n\tcase GRABBINGMODE_VIDEO:\n\t\tstd::cout << \"KODICHECK INFO: switching to VIDEO mode\" << std::endl;\n\t\tbreak;\n\tcase GRABBINGMODE_PHOTO:\n\t\tstd::cout << \"KODICHECK INFO: switching to PHOTO mode\" << std::endl;\n\t\tbreak;\n\tcase GRABBINGMODE_AUDIO:\n\t\tstd::cout << \"KODICHECK INFO: switching to AUDIO mode\" << std::endl;\n\t\tbreak;\n\tcase GRABBINGMODE_MENU:\n\t\tstd::cout << \"KODICHECK INFO: switching to MENU mode\" << std::endl;\n\t\tbreak;\n\tcase GRABBINGMODE_OFF:\n\t\tstd::cout << \"KODICHECK INFO: switching to OFF mode\" << std::endl;\n\t\tbreak;\n\tcase GRABBINGMODE_INVALID:\n\t\tstd::cout << \"KODICHECK INFO: switching to INVALID mode\" << std::endl;\n\t\tbreak;\n\t}\n\n\t\/\/ only emit the new state when we want to grab in screensaver mode or when the screensaver is deactivated\n\tif (!_previousScreensaverMode)\n\t{\n\t\temit grabbingMode(newGrabbingMode);\n\t}\n\t_previousGrabbingMode = newGrabbingMode;\n}\n\nvoid XBMCVideoChecker::setScreensaverMode(bool isOnScreensaver)\n{\n\tif (isOnScreensaver == _previousScreensaverMode)\n\t{\n\t\t\/\/ no change\n\t\treturn;\n\t}\n\n\temit grabbingMode(isOnScreensaver ? GRABBINGMODE_OFF : _previousGrabbingMode);\n\t_previousScreensaverMode = isOnScreensaver;\n}\n\nvoid XBMCVideoChecker::setVideoMode(VideoMode newVideoMode)\n{\n\tif (newVideoMode == _previousVideoMode)\n\t{\n\t\t\/\/ no change\n\t\treturn;\n\t}\n\n\tswitch (newVideoMode)\n\t{\n\tcase VIDEO_2D:\n\t\tstd::cout << \"KODICHECK INFO: switching to 2D mode\" << std::endl;\n\t\tbreak;\n\tcase VIDEO_3DSBS:\n\t\tstd::cout << \"KODICHECK INFO: switching to 3D SBS mode\" << std::endl;\n\t\tbreak;\n\tcase VIDEO_3DTAB:\n\t\tstd::cout << \"KODICHECK INFO: switching to 3D TAB mode\" << std::endl;\n\t\tbreak;\n\t}\n\n\temit videoMode(newVideoMode);\n\t_previousVideoMode = newVideoMode;\n}\n<|endoftext|>"} {"text":"<commit_before>\n\/\/\n\/\/ This source file is part of appleseed.\n\/\/ Visit http:\/\/appleseedhq.net\/ for additional information and resources.\n\/\/\n\/\/ This software is released under the MIT license.\n\/\/\n\/\/ Copyright (c) 2014 Luis B. Barrancos, The appleseedhq Organization\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n\/\/ THE SOFTWARE.\n\/\/\n\n\/\/ Interface header.\n#include \"orennayarbrdf.h\"\n\n\/\/ appleseed.renderer headers.\n#include \"renderer\/modeling\/bsdf\/bsdf.h\"\n#include \"renderer\/modeling\/bsdf\/bsdfwrapper.h\"\n\n\/\/ appleseed.foundation headers.\n#include \"foundation\/math\/basis.h\"\n#include \"foundation\/math\/sampling.h\"\n#include \"foundation\/math\/scalar.h\"\n#include \"foundation\/math\/vector.h\"\n#include \"foundation\/utility\/containers\/dictionary.h\"\n#include \"foundation\/utility\/containers\/specializedarrays.h\"\n\n\/\/ Standard headers.\n#include <algorithm>\n#include <cmath>\n\n\/\/ Forward declarations.\nnamespace foundation { class AbortSwitch; }\nnamespace renderer { class Assembly; }\nnamespace renderer { class Project; }\n\nusing namespace foundation;\nusing namespace std;\n\nnamespace renderer\n{\n\nnamespace\n{\n \/\/\n \/\/ Oren-Nayar BRDF.\n \/\/\n\n const char* Model = \"orennayar_brdf\";\n\n class OrenNayarBRDFImpl\n : public BSDF\n {\n public:\n OrenNayarBRDFImpl(\n const char* name,\n const ParamArray& params)\n : BSDF(name, Reflective, Diffuse, params)\n {\n m_inputs.declare(\"reflectance\", InputFormatSpectralReflectance);\n m_inputs.declare(\"reflectance_multiplier\", InputFormatScalar, \"1.0\");\n m_inputs.declare(\"roughness\" , InputFormatScalar, \"0.1\");\n }\n\n virtual void release() OVERRIDE\n {\n delete this;\n }\n\n virtual const char* get_model() const OVERRIDE\n {\n return Model;\n }\n\n FORCE_INLINE virtual Mode sample(\n SamplingContext& sampling_context,\n const void* data,\n const bool adjoint,\n const bool cosine_mult,\n const Vector3d& geometric_normal,\n const Basis3d& shading_basis,\n const Vector3d& outgoing,\n Vector3d& incoming,\n Spectrum& value,\n double& probability) const\n {\n \/\/ No reflection below the shading surface.\n const Vector3d& n = shading_basis.get_normal();\n const double cos_on = dot(outgoing, n);\n if (cos_on < 0.0)\n return Absorption;\n\n \/\/ Compute the incoming direction in local space.\n sampling_context.split_in_place(2, 1);\n const Vector2d s = sampling_context.next_vector2<2>();\n const Vector3d wi = sample_hemisphere_cosine(s);\n\n \/\/ Transform the incoming direction to parent space.\n incoming = shading_basis.transform_to_parent(wi);\n\n \/\/ No reflection below the shading surface.\n const double cos_in = dot(incoming, n);\n if (cos_in < 0.0)\n return Absorption;\n\n \/\/ Compute the BRDF value.\n const InputValues* values = static_cast<const InputValues*>(data);\n\n if (values->m_roughness != 0)\n oren_nayar_qualitative(cos_on, cos_in, values->m_roughness, values->m_reflectance, outgoing, incoming, n, value);\n else\n value = values->m_reflectance;\n\n value *= static_cast<float>(values->m_reflectance_multiplier * RcpPi);\n\n \/\/ Compute the probability density of the sampled direction.\n probability = wi.y * RcpPi;\n\n \/\/ Return the scattering mode.\n return Diffuse;\n }\n\n FORCE_INLINE virtual double evaluate(\n const void* data,\n const bool adjoint,\n const bool cosine_mult,\n const Vector3d& geometric_normal,\n const Basis3d& shading_basis,\n const Vector3d& outgoing,\n const Vector3d& incoming,\n const int modes,\n Spectrum& value) const\n {\n if (!(modes & Diffuse))\n return 0.0;\n\n \/\/ No reflection below the shading surface.\n const Vector3d& n = shading_basis.get_normal();\n const double cos_in = dot(incoming, n);\n const double cos_on = dot(outgoing, n);\n if (cos_in < 0.0 || cos_on < 0.0)\n return 0.0;\n\n \/\/ Compute the BRDF value.\n const InputValues* values = static_cast<const InputValues*>(data);\n\n if (values->m_roughness != 0)\n oren_nayar_qualitative(cos_on, cos_in, values->m_roughness, values->m_reflectance, outgoing, incoming, n, value);\n else\n value = values->m_reflectance;\n\n value *= static_cast<float>(values->m_reflectance_multiplier * RcpPi );\n\n \/\/ Return the probability density of the sampled direction.\n return cos_in * RcpPi;\n }\n\n FORCE_INLINE virtual double evaluate_pdf(\n const void* data,\n const Vector3d& geometric_normal,\n const Basis3d& shading_basis,\n const Vector3d& outgoing,\n const Vector3d& incoming,\n const int modes) const\n {\n if (!(modes & Diffuse))\n return 0.0;\n\n \/\/ No reflection below the shading surface.\n const Vector3d& n = shading_basis.get_normal();\n const double cos_in = dot(incoming, n);\n const double cos_on = min(dot(outgoing, n), 1.0);\n if (cos_in < 0.0 || cos_on < 0.0)\n return 0.0;\n\n return cos_in * RcpPi;\n }\n\n void oren_nayar_qualitative(\n const double cos_on,\n const double cos_in,\n const double roughness,\n const Spectrum& reflectance,\n const Vector3d& outgoing,\n const Vector3d& incoming,\n const Vector3d& n,\n Spectrum& value) const\n {\n const double theta_r = min(HalfPi, acos(cos_on));\n const double theta_i = acos(cos_in);\n const double alpha = max(theta_i, theta_r);\n const double beta = min(theta_i, theta_r);\n\n const double sigma2 = square(roughness);\n\n const double C1 = 1.0 - 0.5 * (sigma2 \/ (sigma2 + 0.33));\n\n double C2 = 0.45 * sigma2 \/ (sigma2 + 0.09);\n\n const Vector3d V_perp_N = normalize(outgoing - n * dot(outgoing, n));\n\n const double cos_phi_diff = dot(V_perp_N, normalize(incoming - n * cos_in));\n\n if (cos_phi_diff >= 0.0)\n C2 *= sin(alpha);\n else\n {\n const double temp = 2.0 * beta * RcpPi;\n C2 *= sin(alpha) - square(temp) * temp;\n }\n\n const double C3 = 0.125 * (sigma2 \/ (sigma2 + 0.09) * square(4.0 * alpha * beta * RcpPiSq)) * tan((alpha + beta) * 0.5);\n\n value = reflectance ;\n value *= static_cast<float>(C1 + (abs(cos_phi_diff) * C2 * tan(beta)) + (1 - abs(cos_phi_diff)) * C3);\n value += square(reflectance) * static_cast<float>(0.17 * cos_in * (sigma2 \/ (sigma2 + 0.13)) *\n (1 - cos_phi_diff * square(2 * beta * RcpPi)));\n }\n\n private:\n typedef OrenNayarBRDFInputValues InputValues;\n };\n\n typedef BSDFWrapper<OrenNayarBRDFImpl> OrenNayarBRDF;\n}\n\n\n\/\/\n\/\/ OrenNayarBRDFFactory class implementation.\n\/\/\n\nconst char* OrenNayarBRDFFactory::get_model() const\n{\n return Model;\n}\n\nconst char* OrenNayarBRDFFactory::get_human_readable_model() const\n{\n return \"Oren-Nayar BRDF\";\n}\n\nDictionaryArray OrenNayarBRDFFactory::get_input_metadata() const\n{\n DictionaryArray metadata;\n\n metadata.push_back(\n Dictionary()\n .insert(\"name\", \"reflectance\")\n .insert(\"label\", \"Reflectance\")\n .insert(\"type\", \"colormap\")\n .insert(\"entity_types\",\n Dictionary()\n .insert(\"color\", \"Colors\")\n .insert(\"texture_instance\", \"Textures\"))\n .insert(\"use\", \"required\")\n .insert(\"default\", \"0.5\"));\n\n metadata.push_back(\n Dictionary()\n .insert(\"name\", \"reflectance_multiplier\")\n .insert(\"label\", \"Reflectance Multiplier\")\n .insert(\"type\", \"colormap\")\n .insert(\"entity_types\",\n Dictionary().insert(\"texture_instance\", \"Textures\"))\n .insert(\"use\", \"optional\")\n .insert(\"default\", \"1.0\"));\n\n metadata.push_back(\n Dictionary()\n .insert(\"name\", \"roughness\")\n .insert(\"label\", \"Roughness\")\n .insert(\"type\", \"colormap\")\n .insert(\"entity_types\",\n Dictionary().insert(\"texture_instance\", \"Textures\"))\n .insert(\"use\", \"required\")\n .insert(\"default\", \"0.1\"));\n\n return metadata;\n}\n\nauto_release_ptr<BSDF> OrenNayarBRDFFactory::create(\n const char* name,\n const ParamArray& params) const\n{\n return auto_release_ptr<BSDF>(new OrenNayarBRDF(name, params));\n}\n\n} \/\/ namespace renderer\n<commit_msg>Added assertions to the 2nd and 3rd coefficients.<commit_after>\n\/\/\n\/\/ This source file is part of appleseed.\n\/\/ Visit http:\/\/appleseedhq.net\/ for additional information and resources.\n\/\/\n\/\/ This software is released under the MIT license.\n\/\/\n\/\/ Copyright (c) 2014 Luis B. Barrancos, The appleseedhq Organization\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n\/\/ THE SOFTWARE.\n\/\/\n\n\/\/ Interface header.\n#include \"orennayarbrdf.h\"\n\n\/\/ appleseed.renderer headers.\n#include \"renderer\/modeling\/bsdf\/bsdf.h\"\n#include \"renderer\/modeling\/bsdf\/bsdfwrapper.h\"\n\n\/\/ appleseed.foundation headers.\n#include \"foundation\/math\/basis.h\"\n#include \"foundation\/math\/sampling.h\"\n#include \"foundation\/math\/scalar.h\"\n#include \"foundation\/math\/vector.h\"\n#include \"foundation\/utility\/containers\/dictionary.h\"\n#include \"foundation\/utility\/containers\/specializedarrays.h\"\n\n\/\/ Standard headers.\n#include <algorithm>\n#include <cmath>\n\n\/\/ Forward declarations.\nnamespace foundation { class AbortSwitch; }\nnamespace renderer { class Assembly; }\nnamespace renderer { class Project; }\n\nusing namespace foundation;\nusing namespace std;\n\nnamespace renderer\n{\n\nnamespace\n{\n \/\/\n \/\/ Oren-Nayar BRDF.\n \/\/\n\n const char* Model = \"orennayar_brdf\";\n\n class OrenNayarBRDFImpl\n : public BSDF\n {\n public:\n OrenNayarBRDFImpl(\n const char* name,\n const ParamArray& params)\n : BSDF(name, Reflective, Diffuse, params)\n {\n m_inputs.declare(\"reflectance\", InputFormatSpectralReflectance);\n m_inputs.declare(\"reflectance_multiplier\", InputFormatScalar, \"1.0\");\n m_inputs.declare(\"roughness\" , InputFormatScalar, \"0.1\");\n }\n\n virtual void release() OVERRIDE\n {\n delete this;\n }\n\n virtual const char* get_model() const OVERRIDE\n {\n return Model;\n }\n\n FORCE_INLINE virtual Mode sample(\n SamplingContext& sampling_context,\n const void* data,\n const bool adjoint,\n const bool cosine_mult,\n const Vector3d& geometric_normal,\n const Basis3d& shading_basis,\n const Vector3d& outgoing,\n Vector3d& incoming,\n Spectrum& value,\n double& probability) const\n {\n \/\/ No reflection below the shading surface.\n const Vector3d& n = shading_basis.get_normal();\n const double cos_on = dot(outgoing, n);\n if (cos_on < 0.0)\n return Absorption;\n\n \/\/ Compute the incoming direction in local space.\n sampling_context.split_in_place(2, 1);\n const Vector2d s = sampling_context.next_vector2<2>();\n const Vector3d wi = sample_hemisphere_cosine(s);\n\n \/\/ Transform the incoming direction to parent space.\n incoming = shading_basis.transform_to_parent(wi);\n\n \/\/ No reflection below the shading surface.\n const double cos_in = dot(incoming, n);\n if (cos_in < 0.0)\n return Absorption;\n\n \/\/ Compute the BRDF value.\n const InputValues* values = static_cast<const InputValues*>(data);\n\n if (values->m_roughness != 0)\n oren_nayar_qualitative(cos_on, cos_in, values->m_roughness, values->m_reflectance, outgoing, incoming, n, value);\n else\n value = values->m_reflectance;\n\n value *= static_cast<float>(values->m_reflectance_multiplier * RcpPi);\n\n \/\/ Compute the probability density of the sampled direction.\n probability = wi.y * RcpPi;\n\n \/\/ Return the scattering mode.\n return Diffuse;\n }\n\n FORCE_INLINE virtual double evaluate(\n const void* data,\n const bool adjoint,\n const bool cosine_mult,\n const Vector3d& geometric_normal,\n const Basis3d& shading_basis,\n const Vector3d& outgoing,\n const Vector3d& incoming,\n const int modes,\n Spectrum& value) const\n {\n if (!(modes & Diffuse))\n return 0.0;\n\n \/\/ No reflection below the shading surface.\n const Vector3d& n = shading_basis.get_normal();\n const double cos_in = dot(incoming, n);\n const double cos_on = dot(outgoing, n);\n if (cos_in < 0.0 || cos_on < 0.0)\n return 0.0;\n\n \/\/ Compute the BRDF value.\n const InputValues* values = static_cast<const InputValues*>(data);\n\n if (values->m_roughness != 0)\n oren_nayar_qualitative(cos_on, cos_in, values->m_roughness, values->m_reflectance, outgoing, incoming, n, value);\n else\n value = values->m_reflectance;\n\n value *= static_cast<float>(values->m_reflectance_multiplier * RcpPi );\n\n \/\/ Return the probability density of the sampled direction.\n return cos_in * RcpPi;\n }\n\n FORCE_INLINE virtual double evaluate_pdf(\n const void* data,\n const Vector3d& geometric_normal,\n const Basis3d& shading_basis,\n const Vector3d& outgoing,\n const Vector3d& incoming,\n const int modes) const\n {\n if (!(modes & Diffuse))\n return 0.0;\n\n \/\/ No reflection below the shading surface.\n const Vector3d& n = shading_basis.get_normal();\n const double cos_in = dot(incoming, n);\n const double cos_on = dot(outgoing, n);\n if (cos_in < 0.0 || cos_on < 0.0)\n return 0.0;\n\n return cos_in * RcpPi;\n }\n\n void oren_nayar_qualitative(\n const double cos_on,\n const double cos_in,\n const double roughness,\n const Spectrum& reflectance,\n const Vector3d& outgoing,\n const Vector3d& incoming,\n const Vector3d& n,\n Spectrum& value) const\n {\n const double theta_r = min(HalfPi, acos(cos_on));\n const double theta_i = acos(cos_in);\n const double alpha = max(theta_i, theta_r);\n const double beta = min(theta_i, theta_r);\n\n const double sigma2 = square(roughness);\n\n const double C1 = 1.0 - 0.5 * (sigma2 \/ (sigma2 + 0.33));\n\n double C2 = 0.45 * sigma2 \/ (sigma2 + 0.09);\n\n const Vector3d V_perp_N = normalize(outgoing - n * dot(outgoing, n));\n\n const double cos_phi_diff = dot(V_perp_N, normalize(incoming - n * cos_in));\n\n if (cos_phi_diff >= 0.0)\n C2 *= sin(alpha);\n else\n {\n const double temp = 2.0 * beta * RcpPi;\n C2 *= sin(alpha) - square(temp) * temp;\n }\n assert(C2 >= 0.0);\n\n const double C3 = 0.125 * (sigma2 \/ (sigma2 + 0.09) * square(4.0 * alpha * beta * RcpPiSq)) * tan((alpha + beta) * 0.5);\n assert(C3 >= 0.0);\n\n value = reflectance ;\n value *= static_cast<float>(C1 + (abs(cos_phi_diff) * C2 * tan(beta)) + (1 - abs(cos_phi_diff)) * C3);\n value += square(reflectance) * static_cast<float>(0.17 * cos_in * (sigma2 \/ (sigma2 + 0.13)) *\n (1 - cos_phi_diff * square(2 * beta * RcpPi)));\n }\n\n private:\n typedef OrenNayarBRDFInputValues InputValues;\n };\n\n typedef BSDFWrapper<OrenNayarBRDFImpl> OrenNayarBRDF;\n}\n\n\n\/\/\n\/\/ OrenNayarBRDFFactory class implementation.\n\/\/\n\nconst char* OrenNayarBRDFFactory::get_model() const\n{\n return Model;\n}\n\nconst char* OrenNayarBRDFFactory::get_human_readable_model() const\n{\n return \"Oren-Nayar BRDF\";\n}\n\nDictionaryArray OrenNayarBRDFFactory::get_input_metadata() const\n{\n DictionaryArray metadata;\n\n metadata.push_back(\n Dictionary()\n .insert(\"name\", \"reflectance\")\n .insert(\"label\", \"Reflectance\")\n .insert(\"type\", \"colormap\")\n .insert(\"entity_types\",\n Dictionary()\n .insert(\"color\", \"Colors\")\n .insert(\"texture_instance\", \"Textures\"))\n .insert(\"use\", \"required\")\n .insert(\"default\", \"0.5\"));\n\n metadata.push_back(\n Dictionary()\n .insert(\"name\", \"reflectance_multiplier\")\n .insert(\"label\", \"Reflectance Multiplier\")\n .insert(\"type\", \"colormap\")\n .insert(\"entity_types\",\n Dictionary().insert(\"texture_instance\", \"Textures\"))\n .insert(\"use\", \"optional\")\n .insert(\"default\", \"1.0\"));\n\n metadata.push_back(\n Dictionary()\n .insert(\"name\", \"roughness\")\n .insert(\"label\", \"Roughness\")\n .insert(\"type\", \"colormap\")\n .insert(\"entity_types\",\n Dictionary().insert(\"texture_instance\", \"Textures\"))\n .insert(\"use\", \"required\")\n .insert(\"default\", \"0.1\"));\n\n return metadata;\n}\n\nauto_release_ptr<BSDF> OrenNayarBRDFFactory::create(\n const char* name,\n const ParamArray& params) const\n{\n return auto_release_ptr<BSDF>(new OrenNayarBRDF(name, params));\n}\n\n} \/\/ namespace renderer\n<|endoftext|>"} {"text":"<commit_before>\/***********************************************************************\n filename: FontDemo.cpp\n created: 17\/6\/2006\n author: Paul D Turner\n*************************************************************************\/\n\/***************************************************************************\n * Copyright (C) 2004 - 2006 Paul D Turner & The CEGUI Development Team\n *\n * Permission is hereby granted, free of charge, to any person obtaining\n * a copy of this software and associated documentation files (the\n * \"Software\"), to deal in the Software without restriction, including\n * without limitation the rights to use, copy, modify, merge, publish,\n * distribute, sublicense, and\/or sell copies of the Software, and to\n * permit persons to whom the Software is furnished to do so, subject to\n * the following conditions:\n *\n * The above copyright notice and this permission notice shall be\n * included in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\n * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR\n * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,\n * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\n * OTHER DEALINGS IN THE SOFTWARE.\n ***************************************************************************\/\n#include \"CEGuiSample.h\"\n#include \"CEGUI.h\"\n#include \"CEGUIPropertyHelper.h\"\n\nusing namespace CEGUI;\n\nstatic char *FontList [] =\n{\n \"DejaVuSans-10\",\n \"Commonwealth-10\",\n \"Iconified-12\",\n \"fkp-16\",\n \"FairChar-30\"\n};\n\nstatic struct\n{\n utf8 *Language;\n\tutf8 *Text;\n} LangList [] =\n{\n\t\/\/ A list of strings in different languages\n\t\/\/ Feel free to add your own language here (UTF-8 ONLY!)...\n { (utf8 *)\"English\",\n\t (utf8 *)\"THIS IS SOME TEXT IN UPPERCASE\\n\"\n \"and this is lowercase...\\n\"\n \"Try Catching The Brown Fox While It's Jumping Over The Lazy Dog\" },\n { (utf8 *)\"Русский\",\n\t (utf8 *)\"ПРЕВЕД, КРОСАВЧЕГИ!\\n\"\n \"Съешь еще этих чёртовых помидоров, меня от них уже тошнит\\n\"\n \"Как Хорошо, Что Дырочку Для Клизмы\\nИмеют Все Живые Организмы\\n\" },\n { (utf8 *)\"Română\",\n (utf8 *)\"CEI PATRU APOSTOLI\\n\"\n \"au fost trei:\\n\"\n \"Luca şi Matfei\\n\" },\n { (utf8 *)\"Dansk\",\n (utf8 *)\"FARLIGE STORE BOGSTAVER\\n\"\n \"og flere men små...\\n\"\n \"Quizdeltagerne spiste jordbær med fløde, mens cirkusklovnen Walther spillede på xylofon\\n\" }\n};\n\n#define MIN_POINT_SIZE 6.0f\n\n\/\/ Sample sub-class for ListboxTextItem that auto-sets the selection brush\n\/\/ image. This saves doing it manually every time in the code.\nclass MyListItem : public ListboxTextItem\n{\npublic:\n MyListItem (const String& text) : ListboxTextItem(text)\n {\n setSelectionBrushImage(\"TaharezLook\", \"MultiListSelectionBrush\");\n }\n};\n\n\/\/ Sample class\nclass FontDemo : public CEGuiSample\n{\npublic:\n \/\/ method to initialse the samples windows and events.\n bool initialiseSample ()\n\t{\n \/\/ we will use of the WindowManager.\n WindowManager& winMgr = WindowManager::getSingleton ();\n\n \/\/ load scheme and set up defaults\n SchemeManager::getSingleton().loadScheme (\"TaharezLook.scheme\");\n System::getSingleton().setDefaultMouseCursor (\"TaharezLook\", \"MouseArrow\");\n\n \/\/ load all the fonts except Commonwealth which has been already loaded\n for (size_t i = 0; i < (sizeof (FontList) \/ sizeof (FontList [0])); i++)\n FontManager::getSingleton().createFont (String (FontList [i]) + \".font\");\n\n \/\/ load an image to use as a background\n ImagesetManager::getSingleton().createImagesetFromImageFile(\"BackgroundImage\", \"GPN-2000-001437.tga\");\n\n \/\/ here we will use a StaticImage as the root, then we can use it to place a background image\n Window* background = winMgr.createWindow (\"TaharezLook\/StaticImage\");\n \/\/ set area rectangle\n background->setArea (URect (cegui_reldim (0), cegui_reldim (0),\n cegui_reldim (1), cegui_reldim (1)));\n \/\/ disable frame and standard background\n background->setProperty (\"FrameEnabled\", \"false\");\n background->setProperty (\"BackgroundEnabled\", \"false\");\n \/\/ set the background image\n background->setProperty (\"Image\", \"set:BackgroundImage image:full_image\");\n \/\/ install this as the root GUI sheet\n System::getSingleton ().setGUISheet (background);\n\n \/\/ set tooltip styles (by default there is none)\n System::getSingleton ().setDefaultTooltip (\"TaharezLook\/Tooltip\");\n\n \/\/ load some demo windows and attach to the background 'root'\n background->addChildWindow (winMgr.loadWindowLayout (\"FontDemo.layout\"));\n\n \/\/ Add the font names to the listbox\n Listbox *lbox = static_cast<Listbox *> (winMgr.getWindow (\"FontDemo\/FontList\"));\n for (size_t i = 0; i < (sizeof (FontList) \/ sizeof (FontList [0])); i++)\n lbox->addItem (new MyListItem (FontList [i]));\n \/\/ set up the font listbox callback\n lbox->subscribeEvent (Listbox::EventSelectionChanged,\n Event::Subscriber (&FontDemo::handleFontSelection, this));\n \/\/ select the first font\n lbox->setItemSelectState (size_t (0), true);\n\n \/\/ Add language list to the listbox\n lbox = static_cast<Listbox *> (winMgr.getWindow (\"FontDemo\/LangList\"));\n for (size_t i = 0; i < (sizeof (LangList) \/ sizeof (LangList [0])); i++)\n lbox->addItem (new MyListItem (LangList [i].Language));\n \/\/ set up the language listbox callback\n lbox->subscribeEvent (Listbox::EventSelectionChanged,\n Event::Subscriber (&FontDemo::handleLangSelection, this));\n \/\/ select the first language\n lbox->setItemSelectState (size_t (0), true);\n\n winMgr.getWindow(\"FontDemo\/AutoScaled\")->subscribeEvent (\n Checkbox::EventCheckStateChanged,\n Event::Subscriber (&FontDemo::handleAutoScaled, this));\n winMgr.getWindow(\"FontDemo\/Antialiased\")->subscribeEvent (\n Checkbox::EventCheckStateChanged,\n Event::Subscriber (&FontDemo::handleAntialiased, this));\n winMgr.getWindow(\"FontDemo\/PointSize\")->subscribeEvent (\n Scrollbar::EventScrollPositionChanged,\n Event::Subscriber (&FontDemo::handlePointSize, this));\n\n return true;\n\t}\n\n \/\/ method to perform any required cleanup operations.\n void cleanupSample ()\n {\n \/\/ me? cleanup? what?\n }\n\n void setFontDesc ()\n {\n WindowManager& winMgr = WindowManager::getSingleton ();\n\n MultiLineEditbox *mle = static_cast<MultiLineEditbox *>\n (winMgr.getWindow(\"FontDemo\/FontSample\"));\n\n Font *f = mle->getFont ();\n\n String s = f->getProperty (\"Name\");\n if (f->isPropertyPresent (\"PointSize\"))\n s += \".\" + f->getProperty (\"PointSize\");\n\n winMgr.getWindow(\"FontDemo\/FontDesc\")->setText (s);\n }\n\n bool handleFontSelection (const EventArgs& e)\n {\n Listbox *lbox = static_cast<Listbox*> (\n static_cast<const WindowEventArgs&> (e).window);\n\n if (lbox->getFirstSelectedItem ())\n\t\t{\n Font *f = FontManager::getSingleton ().getFont (\n lbox->getFirstSelectedItem ()->getText ());\n\n WindowManager& winMgr = WindowManager::getSingleton ();\n winMgr.getWindow(\"FontDemo\/FontSample\")->setFont (f);\n\n bool b = f->isPropertyPresent (\"AutoScaled\");\n Checkbox *cb = static_cast<Checkbox *> (winMgr.getWindow(\"FontDemo\/AutoScaled\"));\n cb->setEnabled (b);\n if (b)\n cb->setSelected (PropertyHelper::stringToBool (f->getProperty (\"AutoScaled\")));\n\n b = f->isPropertyPresent (\"Antialiased\");\n cb = static_cast<Checkbox *> (winMgr.getWindow(\"FontDemo\/Antialiased\"));\n cb->setEnabled (b);\n if (b)\n cb->setSelected (PropertyHelper::stringToBool (f->getProperty (\"Antialiased\")));\n\n b = f->isPropertyPresent (\"PointSize\");\n Scrollbar *sb = static_cast<Scrollbar *> (\n winMgr.getWindow(\"FontDemo\/PointSize\"));\n sb->setEnabled (b);\n if (b)\n sb->setScrollPosition (\n PropertyHelper::stringToFloat (f->getProperty (\"PointSize\")) - MIN_POINT_SIZE);\n\n setFontDesc ();\n\t\t}\n\n return true;\n }\n\n bool handleAutoScaled (const EventArgs& e)\n {\n WindowManager& winMgr = WindowManager::getSingleton ();\n\n Checkbox *cb = static_cast<Checkbox *> (\n static_cast<const WindowEventArgs&> (e).window);\n\n MultiLineEditbox *mle = static_cast<MultiLineEditbox *>\n (winMgr.getWindow(\"FontDemo\/FontSample\"));\n\n Font *f = mle->getFont ();\n f->setProperty (\"AutoScaled\",\n PropertyHelper::boolToString (cb->isSelected ()));\n\n return true;\n }\n\n bool handleAntialiased (const EventArgs& e)\n {\n WindowManager& winMgr = WindowManager::getSingleton ();\n\n Checkbox *cb = static_cast<Checkbox *> (\n static_cast<const WindowEventArgs&> (e).window);\n\n MultiLineEditbox *mle = static_cast<MultiLineEditbox *>\n (winMgr.getWindow(\"FontDemo\/FontSample\"));\n\n Font *f = mle->getFont ();\n f->setProperty (\"Antialiased\",\n PropertyHelper::boolToString (cb->isSelected ()));\n\n return true;\n }\n\n bool handlePointSize (const EventArgs& e)\n {\n WindowManager& winMgr = WindowManager::getSingleton ();\n\n Scrollbar *sb = static_cast<Scrollbar *> (\n static_cast<const WindowEventArgs&> (e).window);\n\n Font *f = winMgr.getWindow (\"FontDemo\/FontSample\")->getFont ();\n\n f->setProperty (\"PointSize\",\n PropertyHelper::intToString (\n int (MIN_POINT_SIZE + sb->getScrollPosition ())));\n\n setFontDesc ();\n\n return true;\n }\n\n bool handleLangSelection (const EventArgs& e)\n {\n Listbox *lbox = static_cast<Listbox *> (\n static_cast<const WindowEventArgs&> (e).window);\n\n if (lbox->getFirstSelectedItem ())\n {\n size_t idx = lbox->getItemIndex (lbox->getFirstSelectedItem ());\n WindowManager& winMgr = WindowManager::getSingleton ();\n winMgr.getWindow (\"FontDemo\/FontSample\")->setText (LangList [idx].Text);\n }\n\n return true;\n }\n};\n\nint main(int argc, char *argv[])\n{\n \/\/ This is a basic start-up for the sample application which is\n \/\/ object orientated in nature, so we just need an instance of\n \/\/ the CEGuiSample based object and then tell that sample application\n \/\/ to run. All of the samples will use code similar to this in the\n \/\/ main\/WinMain function.\n FontDemo app;\n return app.run ();\n}\n<commit_msg>Changed Russian text in FontDemo sample - the old text apparently potentially offensive. Thanks to 'Sanya' for the updated text.<commit_after>\/***********************************************************************\n filename: FontDemo.cpp\n created: 17\/6\/2006\n author: Paul D Turner\n*************************************************************************\/\n\/***************************************************************************\n * Copyright (C) 2004 - 2006 Paul D Turner & The CEGUI Development Team\n *\n * Permission is hereby granted, free of charge, to any person obtaining\n * a copy of this software and associated documentation files (the\n * \"Software\"), to deal in the Software without restriction, including\n * without limitation the rights to use, copy, modify, merge, publish,\n * distribute, sublicense, and\/or sell copies of the Software, and to\n * permit persons to whom the Software is furnished to do so, subject to\n * the following conditions:\n *\n * The above copyright notice and this permission notice shall be\n * included in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\n * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR\n * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,\n * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\n * OTHER DEALINGS IN THE SOFTWARE.\n ***************************************************************************\/\n#include \"CEGuiSample.h\"\n#include \"CEGUI.h\"\n#include \"CEGUIPropertyHelper.h\"\n\nusing namespace CEGUI;\n\nstatic char *FontList [] =\n{\n \"DejaVuSans-10\",\n \"Commonwealth-10\",\n \"Iconified-12\",\n \"fkp-16\",\n \"FairChar-30\"\n};\n\nstatic struct\n{\n utf8 *Language;\n\tutf8 *Text;\n} LangList [] =\n{\n\t\/\/ A list of strings in different languages\n\t\/\/ Feel free to add your own language here (UTF-8 ONLY!)...\n { (utf8 *)\"English\",\n\t (utf8 *)\"THIS IS SOME TEXT IN UPPERCASE\\n\"\n \"and this is lowercase...\\n\"\n \"Try Catching The Brown Fox While It's Jumping Over The Lazy Dog\" },\n { (utf8 *)\"Русский\",\n\t (utf8 *)\"Всё ускоряющаяся эволюция компьютерных технологий предъявила жёсткие требования к производителям как собственно вычислительной техники, так и периферийных устройств.\\n\"\n \"\\nЗавершён ежегодный съезд эрудированных школьников, мечтающих глубоко проникнуть в тайны физических явлений и химических реакций.\\n\"\n \"\\nавтор панграмм -- Андрей Николаев\\n\" },\n { (utf8 *)\"Română\",\n (utf8 *)\"CEI PATRU APOSTOLI\\n\"\n \"au fost trei:\\n\"\n \"Luca şi Matfei\\n\" },\n { (utf8 *)\"Dansk\",\n (utf8 *)\"FARLIGE STORE BOGSTAVER\\n\"\n \"og flere men små...\\n\"\n \"Quizdeltagerne spiste jordbær med fløde, mens cirkusklovnen Walther spillede på xylofon\\n\" }\n};\n\n#define MIN_POINT_SIZE 6.0f\n\n\/\/ Sample sub-class for ListboxTextItem that auto-sets the selection brush\n\/\/ image. This saves doing it manually every time in the code.\nclass MyListItem : public ListboxTextItem\n{\npublic:\n MyListItem (const String& text) : ListboxTextItem(text)\n {\n setSelectionBrushImage(\"TaharezLook\", \"MultiListSelectionBrush\");\n }\n};\n\n\/\/ Sample class\nclass FontDemo : public CEGuiSample\n{\npublic:\n \/\/ method to initialse the samples windows and events.\n bool initialiseSample ()\n\t{\n \/\/ we will use of the WindowManager.\n WindowManager& winMgr = WindowManager::getSingleton ();\n\n \/\/ load scheme and set up defaults\n SchemeManager::getSingleton().loadScheme (\"TaharezLook.scheme\");\n System::getSingleton().setDefaultMouseCursor (\"TaharezLook\", \"MouseArrow\");\n\n \/\/ load all the fonts except Commonwealth which has been already loaded\n for (size_t i = 0; i < (sizeof (FontList) \/ sizeof (FontList [0])); i++)\n FontManager::getSingleton().createFont (String (FontList [i]) + \".font\");\n\n \/\/ load an image to use as a background\n ImagesetManager::getSingleton().createImagesetFromImageFile(\"BackgroundImage\", \"GPN-2000-001437.tga\");\n\n \/\/ here we will use a StaticImage as the root, then we can use it to place a background image\n Window* background = winMgr.createWindow (\"TaharezLook\/StaticImage\");\n \/\/ set area rectangle\n background->setArea (URect (cegui_reldim (0), cegui_reldim (0),\n cegui_reldim (1), cegui_reldim (1)));\n \/\/ disable frame and standard background\n background->setProperty (\"FrameEnabled\", \"false\");\n background->setProperty (\"BackgroundEnabled\", \"false\");\n \/\/ set the background image\n background->setProperty (\"Image\", \"set:BackgroundImage image:full_image\");\n \/\/ install this as the root GUI sheet\n System::getSingleton ().setGUISheet (background);\n\n \/\/ set tooltip styles (by default there is none)\n System::getSingleton ().setDefaultTooltip (\"TaharezLook\/Tooltip\");\n\n \/\/ load some demo windows and attach to the background 'root'\n background->addChildWindow (winMgr.loadWindowLayout (\"FontDemo.layout\"));\n\n \/\/ Add the font names to the listbox\n Listbox *lbox = static_cast<Listbox *> (winMgr.getWindow (\"FontDemo\/FontList\"));\n for (size_t i = 0; i < (sizeof (FontList) \/ sizeof (FontList [0])); i++)\n lbox->addItem (new MyListItem (FontList [i]));\n \/\/ set up the font listbox callback\n lbox->subscribeEvent (Listbox::EventSelectionChanged,\n Event::Subscriber (&FontDemo::handleFontSelection, this));\n \/\/ select the first font\n lbox->setItemSelectState (size_t (0), true);\n\n \/\/ Add language list to the listbox\n lbox = static_cast<Listbox *> (winMgr.getWindow (\"FontDemo\/LangList\"));\n for (size_t i = 0; i < (sizeof (LangList) \/ sizeof (LangList [0])); i++)\n lbox->addItem (new MyListItem (LangList [i].Language));\n \/\/ set up the language listbox callback\n lbox->subscribeEvent (Listbox::EventSelectionChanged,\n Event::Subscriber (&FontDemo::handleLangSelection, this));\n \/\/ select the first language\n lbox->setItemSelectState (size_t (0), true);\n\n winMgr.getWindow(\"FontDemo\/AutoScaled\")->subscribeEvent (\n Checkbox::EventCheckStateChanged,\n Event::Subscriber (&FontDemo::handleAutoScaled, this));\n winMgr.getWindow(\"FontDemo\/Antialiased\")->subscribeEvent (\n Checkbox::EventCheckStateChanged,\n Event::Subscriber (&FontDemo::handleAntialiased, this));\n winMgr.getWindow(\"FontDemo\/PointSize\")->subscribeEvent (\n Scrollbar::EventScrollPositionChanged,\n Event::Subscriber (&FontDemo::handlePointSize, this));\n\n return true;\n\t}\n\n \/\/ method to perform any required cleanup operations.\n void cleanupSample ()\n {\n \/\/ me? cleanup? what?\n }\n\n void setFontDesc ()\n {\n WindowManager& winMgr = WindowManager::getSingleton ();\n\n MultiLineEditbox *mle = static_cast<MultiLineEditbox *>\n (winMgr.getWindow(\"FontDemo\/FontSample\"));\n\n Font *f = mle->getFont ();\n\n String s = f->getProperty (\"Name\");\n if (f->isPropertyPresent (\"PointSize\"))\n s += \".\" + f->getProperty (\"PointSize\");\n\n winMgr.getWindow(\"FontDemo\/FontDesc\")->setText (s);\n }\n\n bool handleFontSelection (const EventArgs& e)\n {\n Listbox *lbox = static_cast<Listbox*> (\n static_cast<const WindowEventArgs&> (e).window);\n\n if (lbox->getFirstSelectedItem ())\n\t\t{\n Font *f = FontManager::getSingleton ().getFont (\n lbox->getFirstSelectedItem ()->getText ());\n\n WindowManager& winMgr = WindowManager::getSingleton ();\n winMgr.getWindow(\"FontDemo\/FontSample\")->setFont (f);\n\n bool b = f->isPropertyPresent (\"AutoScaled\");\n Checkbox *cb = static_cast<Checkbox *> (winMgr.getWindow(\"FontDemo\/AutoScaled\"));\n cb->setEnabled (b);\n if (b)\n cb->setSelected (PropertyHelper::stringToBool (f->getProperty (\"AutoScaled\")));\n\n b = f->isPropertyPresent (\"Antialiased\");\n cb = static_cast<Checkbox *> (winMgr.getWindow(\"FontDemo\/Antialiased\"));\n cb->setEnabled (b);\n if (b)\n cb->setSelected (PropertyHelper::stringToBool (f->getProperty (\"Antialiased\")));\n\n b = f->isPropertyPresent (\"PointSize\");\n Scrollbar *sb = static_cast<Scrollbar *> (\n winMgr.getWindow(\"FontDemo\/PointSize\"));\n sb->setEnabled (b);\n if (b)\n sb->setScrollPosition (\n PropertyHelper::stringToFloat (f->getProperty (\"PointSize\")) - MIN_POINT_SIZE);\n\n setFontDesc ();\n\t\t}\n\n return true;\n }\n\n bool handleAutoScaled (const EventArgs& e)\n {\n WindowManager& winMgr = WindowManager::getSingleton ();\n\n Checkbox *cb = static_cast<Checkbox *> (\n static_cast<const WindowEventArgs&> (e).window);\n\n MultiLineEditbox *mle = static_cast<MultiLineEditbox *>\n (winMgr.getWindow(\"FontDemo\/FontSample\"));\n\n Font *f = mle->getFont ();\n f->setProperty (\"AutoScaled\",\n PropertyHelper::boolToString (cb->isSelected ()));\n\n return true;\n }\n\n bool handleAntialiased (const EventArgs& e)\n {\n WindowManager& winMgr = WindowManager::getSingleton ();\n\n Checkbox *cb = static_cast<Checkbox *> (\n static_cast<const WindowEventArgs&> (e).window);\n\n MultiLineEditbox *mle = static_cast<MultiLineEditbox *>\n (winMgr.getWindow(\"FontDemo\/FontSample\"));\n\n Font *f = mle->getFont ();\n f->setProperty (\"Antialiased\",\n PropertyHelper::boolToString (cb->isSelected ()));\n\n return true;\n }\n\n bool handlePointSize (const EventArgs& e)\n {\n WindowManager& winMgr = WindowManager::getSingleton ();\n\n Scrollbar *sb = static_cast<Scrollbar *> (\n static_cast<const WindowEventArgs&> (e).window);\n\n Font *f = winMgr.getWindow (\"FontDemo\/FontSample\")->getFont ();\n\n f->setProperty (\"PointSize\",\n PropertyHelper::intToString (\n int (MIN_POINT_SIZE + sb->getScrollPosition ())));\n\n setFontDesc ();\n\n return true;\n }\n\n bool handleLangSelection (const EventArgs& e)\n {\n Listbox *lbox = static_cast<Listbox *> (\n static_cast<const WindowEventArgs&> (e).window);\n\n if (lbox->getFirstSelectedItem ())\n {\n size_t idx = lbox->getItemIndex (lbox->getFirstSelectedItem ());\n WindowManager& winMgr = WindowManager::getSingleton ();\n winMgr.getWindow (\"FontDemo\/FontSample\")->setText (LangList [idx].Text);\n }\n\n return true;\n }\n};\n\nint main(int argc, char *argv[])\n{\n \/\/ This is a basic start-up for the sample application which is\n \/\/ object orientated in nature, so we just need an instance of\n \/\/ the CEGuiSample based object and then tell that sample application\n \/\/ to run. All of the samples will use code similar to this in the\n \/\/ main\/WinMain function.\n FontDemo app;\n return app.run ();\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ The MIT License (MIT)\r\n\/\/\r\n\/\/ \tCopyright (c) 2015 Sergey Makeev, Vadim Slyusarev\r\n\/\/\r\n\/\/ \tPermission is hereby granted, free of charge, to any person obtaining a copy\r\n\/\/ \tof this software and associated documentation files (the \"Software\"), to deal\r\n\/\/ \tin the Software without restriction, including without limitation the rights\r\n\/\/ \tto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\r\n\/\/ \tcopies of the Software, and to permit persons to whom the Software is\r\n\/\/ \tfurnished to do so, subject to the following conditions:\r\n\/\/\r\n\/\/ The above copyright notice and this permission notice shall be included in\r\n\/\/ \tall copies or substantial portions of the Software.\r\n\/\/\r\n\/\/ \tTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\n\/\/ \tIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\n\/\/ \tFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r\n\/\/ \tAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\n\/\/ \tLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r\n\/\/ \tOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\r\n\/\/ \tTHE SOFTWARE.\r\n#include <MTConfig.h>\r\n#include <MTAppInterop.h>\r\n#include <MTTools.h>\r\n\r\n#include <stdio.h>\r\n\r\n#if MT_SSE_INTRINSICS_SUPPORTED\r\n#include <xmmintrin.h>\r\n#else\r\n#include <malloc.h>\r\n#endif\r\n\r\n\r\n\r\n\r\n#if MT_PLATFORM_WINDOWS \r\n\r\ninline void ThrowException()\r\n{\r\n\t__debugbreak();\r\n}\r\n\r\n#elif MT_PLATFORM_POSIX || MT_PLATFORM_OSX\r\n\r\n#define _DARWIN_C_SOURCE\r\n#include<signal.h>\r\ninline void ThrowException()\r\n{\r\n\traise(SIGTRAP);\r\n\t\/\/ force access violation error\r\n\tchar* pBadAddr = (char*)0x0;\r\n\t*pBadAddr = 0;\r\n}\r\n\r\n#else\r\n\r\n#error Platform is not supported!\r\n\r\n#endif\r\n\r\n\r\n\r\nnamespace MT\r\n{\r\n\r\n\tvoid* Memory::Alloc(size_t size, size_t align)\r\n\t{\r\n\t\tvoid* p = nullptr;\r\n#if MT_SSE_INTRINSICS_SUPPORTED\r\n\t\tp = _mm_malloc(size, align);\r\n#else\r\n\t\tp = memalign(size, align);\r\n#endif\r\n\t\tMT_ASSERT(p, \"Can't allocate memory\");\r\n\t\treturn p;\r\n\t}\r\n\r\n\tvoid Memory::Free(void* p)\r\n\t{\r\n#if MT_SSE_INTRINSICS_SUPPORTED\r\n\t\t_mm_free(p);\r\n#else\r\n\t\tfree(p);\r\n#endif\r\n\t}\r\n\r\n\tMemory::StackDesc Memory::AllocStack(size_t size)\r\n\t{\r\n\t\tStackDesc desc;\r\n\r\n#if MT_PLATFORM_WINDOWS \r\n\r\n\t\tMW_SYSTEM_INFO systemInfo;\r\n\t\tGetSystemInfo(&systemInfo);\r\n\r\n\t\tint pageSize = (int)systemInfo.dwPageSize;\r\n\t\tint pagesCount = (int)size \/ pageSize;\r\n\r\n\t\t\/\/need additional page for stack guard\r\n\t\tif ((size % pageSize) > 0)\r\n\t\t{\r\n\t\t\tpagesCount++;\r\n\t\t}\r\n\r\n\t\t\/\/protected guard page\r\n\t\tpagesCount++;\r\n\r\n\t\tdesc.stackMemoryBytesCount = pagesCount * pageSize;\r\n\t\tdesc.stackMemory = (char*)VirtualAlloc(NULL, desc.stackMemoryBytesCount, MW_MEM_COMMIT, MW_PAGE_READWRITE);\r\n\t\tMT_ASSERT(desc.stackMemory != NULL, \"Can't allocate memory\");\r\n\r\n\t\tdesc.stackBottom = desc.stackMemory + pageSize;\r\n\t\tdesc.stackTop = desc.stackMemory + desc.stackMemoryBytesCount;\r\n\r\n\t\tMW_DWORD oldProtect = 0;\r\n\t\tMW_BOOL res = VirtualProtect(desc.stackMemory, pageSize, MW_PAGE_NOACCESS, &oldProtect);\r\n\t\tMT_USED_IN_ASSERT(res);\r\n\t\tMT_ASSERT(res != 0, \"Can't protect memory\");\r\n\r\n#elif MT_PLATFORM_POSIX || MT_PLATFORM_OSX\r\n\r\n\t\tint pageSize = sysconf(_SC_PAGE_SIZE);\r\n\t\tint pagesCount = size \/ pageSize;\r\n\r\n\t\t\/\/need additional page for stack tail\r\n\t\tif ((size % pageSize) > 0)\r\n\t\t{\r\n\t\t\tpagesCount++;\r\n\t\t}\r\n\r\n\t\t\/\/protected guard page\r\n\t\tpagesCount++;\r\n\r\n\t\tdesc.stackMemoryBytesCount = pagesCount * pageSize;\r\n\t\tdesc.stackMemory = (char*)mmap(NULL, desc.stackMemoryBytesCount, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS | MAP_STACK, -1, 0);\r\n\r\n\t\tMT_ASSERT((void *)desc.stackMemory != (void *)-1, \"Can't allocate memory\");\r\n\r\n\t\tdesc.stackBottom = desc.stackMemory + pageSize;\r\n\t\tdesc.stackTop = desc.stackMemory + desc.stackMemoryBytesCount;\r\n\r\n\t\tint res = mprotect(desc.stackMemory, pageSize, PROT_NONE);\r\n\t\tMT_USED_IN_ASSERT(res);\r\n\t\tMT_ASSERT(res == 0, \"Can't protect memory\");\r\n#else\r\n\t\t#error Platform is not supported!\r\n#endif\r\n\r\n\t\treturn desc;\r\n\t}\r\n\r\n\tvoid Memory::FreeStack(const Memory::StackDesc & desc)\r\n\t{\r\n#if MT_PLATFORM_WINDOWS \r\n\r\n\t\tint res = VirtualFree(desc.stackMemory, 0, MW_MEM_RELEASE);\r\n\t\tMT_USED_IN_ASSERT(res);\r\n\t\tMT_ASSERT(res != 0, \"Can't free memory\");\r\n\r\n#elif MT_PLATFORM_POSIX || MT_PLATFORM_OSX\r\n\r\n\t\tint res = munmap(desc.stackMemory, desc.stackMemoryBytesCount);\r\n\t\tMT_USED_IN_ASSERT(res);\r\n\t\tMT_ASSERT(res == 0, \"Can't free memory\");\r\n#else\r\n\t\t#error Platform is not supported!\r\n#endif\r\n\t}\r\n\r\n\tvoid Diagnostic::ReportAssert(const char* condition, const char* description, const char* sourceFile, int sourceLine)\r\n\t{\r\n\t\tprintf(\"Assertion failed : %s. File %s, line %d. Condition %s\\n\", description, sourceFile, sourceLine, condition);\r\n\t\tThrowException();\r\n\t}\r\n\r\n\r\n\r\n\r\n}\r\n<commit_msg>Fixed OSX compilation<commit_after>\/\/ The MIT License (MIT)\r\n\/\/\r\n\/\/ \tCopyright (c) 2015 Sergey Makeev, Vadim Slyusarev\r\n\/\/\r\n\/\/ \tPermission is hereby granted, free of charge, to any person obtaining a copy\r\n\/\/ \tof this software and associated documentation files (the \"Software\"), to deal\r\n\/\/ \tin the Software without restriction, including without limitation the rights\r\n\/\/ \tto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\r\n\/\/ \tcopies of the Software, and to permit persons to whom the Software is\r\n\/\/ \tfurnished to do so, subject to the following conditions:\r\n\/\/\r\n\/\/ The above copyright notice and this permission notice shall be included in\r\n\/\/ \tall copies or substantial portions of the Software.\r\n\/\/\r\n\/\/ \tTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\n\/\/ \tIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\n\/\/ \tFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r\n\/\/ \tAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\n\/\/ \tLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r\n\/\/ \tOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\r\n\/\/ \tTHE SOFTWARE.\r\n#include <MTConfig.h>\r\n#include <MTAppInterop.h>\r\n#include <MTTools.h>\r\n\r\n#include <stdio.h>\r\n\r\n#if MT_SSE_INTRINSICS_SUPPORTED\r\n#include <xmmintrin.h>\r\n#else\r\n#include <malloc.h>\r\n#endif\r\n\r\n\r\n\r\n\r\n#if MT_PLATFORM_WINDOWS \r\n\r\ninline void ThrowException()\r\n{\r\n\t__debugbreak();\r\n}\r\n\r\n#elif MT_PLATFORM_POSIX\r\n\r\n#include<signal.h>\r\ninline void ThrowException()\r\n{\r\n\traise(SIGTRAP);\r\n\t\/\/ force access violation error\r\n\tchar* pBadAddr = (char*)0x0;\r\n\t*pBadAddr = 0;\r\n}\r\n\r\n#elif MT_PLATFORM_OSX\r\n\r\ninline void ThrowException()\r\n{\r\n\t__builtin_trap();\r\n}\r\n\r\n#else\r\n\r\n#error Platform is not supported!\r\n\r\n#endif\r\n\r\n\r\n\r\nnamespace MT\r\n{\r\n\r\n\tvoid* Memory::Alloc(size_t size, size_t align)\r\n\t{\r\n\t\tvoid* p = nullptr;\r\n#if MT_SSE_INTRINSICS_SUPPORTED\r\n\t\tp = _mm_malloc(size, align);\r\n#else\r\n\t\tp = memalign(size, align);\r\n#endif\r\n\t\tMT_ASSERT(p, \"Can't allocate memory\");\r\n\t\treturn p;\r\n\t}\r\n\r\n\tvoid Memory::Free(void* p)\r\n\t{\r\n#if MT_SSE_INTRINSICS_SUPPORTED\r\n\t\t_mm_free(p);\r\n#else\r\n\t\tfree(p);\r\n#endif\r\n\t}\r\n\r\n\tMemory::StackDesc Memory::AllocStack(size_t size)\r\n\t{\r\n\t\tStackDesc desc;\r\n\r\n#if MT_PLATFORM_WINDOWS \r\n\r\n\t\tMW_SYSTEM_INFO systemInfo;\r\n\t\tGetSystemInfo(&systemInfo);\r\n\r\n\t\tint pageSize = (int)systemInfo.dwPageSize;\r\n\t\tint pagesCount = (int)size \/ pageSize;\r\n\r\n\t\t\/\/need additional page for stack guard\r\n\t\tif ((size % pageSize) > 0)\r\n\t\t{\r\n\t\t\tpagesCount++;\r\n\t\t}\r\n\r\n\t\t\/\/protected guard page\r\n\t\tpagesCount++;\r\n\r\n\t\tdesc.stackMemoryBytesCount = pagesCount * pageSize;\r\n\t\tdesc.stackMemory = (char*)VirtualAlloc(NULL, desc.stackMemoryBytesCount, MW_MEM_COMMIT, MW_PAGE_READWRITE);\r\n\t\tMT_ASSERT(desc.stackMemory != NULL, \"Can't allocate memory\");\r\n\r\n\t\tdesc.stackBottom = desc.stackMemory + pageSize;\r\n\t\tdesc.stackTop = desc.stackMemory + desc.stackMemoryBytesCount;\r\n\r\n\t\tMW_DWORD oldProtect = 0;\r\n\t\tMW_BOOL res = VirtualProtect(desc.stackMemory, pageSize, MW_PAGE_NOACCESS, &oldProtect);\r\n\t\tMT_USED_IN_ASSERT(res);\r\n\t\tMT_ASSERT(res != 0, \"Can't protect memory\");\r\n\r\n#elif MT_PLATFORM_POSIX || MT_PLATFORM_OSX\r\n\r\n\t\tint pageSize = sysconf(_SC_PAGE_SIZE);\r\n\t\tint pagesCount = size \/ pageSize;\r\n\r\n\t\t\/\/need additional page for stack tail\r\n\t\tif ((size % pageSize) > 0)\r\n\t\t{\r\n\t\t\tpagesCount++;\r\n\t\t}\r\n\r\n\t\t\/\/protected guard page\r\n\t\tpagesCount++;\r\n\r\n\t\tdesc.stackMemoryBytesCount = pagesCount * pageSize;\r\n\t\tdesc.stackMemory = (char*)mmap(NULL, desc.stackMemoryBytesCount, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS | MAP_STACK, -1, 0);\r\n\r\n\t\tMT_ASSERT((void *)desc.stackMemory != (void *)-1, \"Can't allocate memory\");\r\n\r\n\t\tdesc.stackBottom = desc.stackMemory + pageSize;\r\n\t\tdesc.stackTop = desc.stackMemory + desc.stackMemoryBytesCount;\r\n\r\n\t\tint res = mprotect(desc.stackMemory, pageSize, PROT_NONE);\r\n\t\tMT_USED_IN_ASSERT(res);\r\n\t\tMT_ASSERT(res == 0, \"Can't protect memory\");\r\n#else\r\n\t\t#error Platform is not supported!\r\n#endif\r\n\r\n\t\treturn desc;\r\n\t}\r\n\r\n\tvoid Memory::FreeStack(const Memory::StackDesc & desc)\r\n\t{\r\n#if MT_PLATFORM_WINDOWS \r\n\r\n\t\tint res = VirtualFree(desc.stackMemory, 0, MW_MEM_RELEASE);\r\n\t\tMT_USED_IN_ASSERT(res);\r\n\t\tMT_ASSERT(res != 0, \"Can't free memory\");\r\n\r\n#elif MT_PLATFORM_POSIX || MT_PLATFORM_OSX\r\n\r\n\t\tint res = munmap(desc.stackMemory, desc.stackMemoryBytesCount);\r\n\t\tMT_USED_IN_ASSERT(res);\r\n\t\tMT_ASSERT(res == 0, \"Can't free memory\");\r\n#else\r\n\t\t#error Platform is not supported!\r\n#endif\r\n\t}\r\n\r\n\tvoid Diagnostic::ReportAssert(const char* condition, const char* description, const char* sourceFile, int sourceLine)\r\n\t{\r\n\t\tprintf(\"Assertion failed : %s. File %s, line %d. Condition %s\\n\", description, sourceFile, sourceLine, condition);\r\n\t\tThrowException();\r\n\t}\r\n\r\n\r\n\r\n\r\n}\r\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\/\n\/* ScreenList.cpp *\/\n\/*************************************************************************\/\n\/* This file is part of: *\/\n\/* Xenro Engine *\/\n\/* https:\/\/github.com\/Jmiller7023\/Xenro-Engine *\/\n\/*************************************************************************\/\n\/* Copyright 11-3-2017 Joseph Miller. *\/\n\/* *\/\n\/* Permission is hereby granted, free of charge, to any person obtaining *\/\n\/* a copy of this software and associated documentation files (the *\/\n\/* \"Software\"), to deal in the Software without restriction, including *\/\n\/* without limitation the rights to use, copy, modify, merge, publish, *\/\n\/* distribute, sublicense, and\/or sell copies of the Software, and to *\/\n\/* permit persons to whom the Software is furnished to do so, subject to *\/\n\/* the following conditions: *\/\n\/* *\/\n\/* The above copyright notice and this permission notice shall be *\/\n\/* included in all copies or substantial portions of the Software. *\/\n\/* *\/\n\/* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, *\/\n\/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF *\/\n\/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*\/\n\/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY *\/\n\/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, *\/\n\/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE *\/\n\/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *\/\n\/*************************************************************************\/\n\n#include \"ScreenList.h\"\n#include \"IScreen.h\"\n#include \"Errormessages.h\"\n\nnamespace Xenro{\n\nScreenList::ScreenList(Game* game) \n\t:m_game(game)\n{\n\t\/\/Empty\n}\n\nScreenList::~ScreenList() {\n\tdestroyScreen();\n}\n\nIScreen* ScreenList::moveNext() {\n\n\tIScreen* currScreen = getCurrScreen();\n\tif (currScreen->getScreenIndex() != NO_CURRENT_SCREEN_INDEX) {\n\t\tm_currScreenIndex = currScreen->getNextScreenIndex();\n\t\treturn getCurrScreen();\n\t}\n\t\/\/There was no next screen so return nullptr.\n\treturn nullptr;\n}\n\nIScreen* ScreenList::movePrevious() {\n\n\tIScreen* currScreen = getCurrScreen();\n\tif (currScreen->getScreenIndex() != NO_CURRENT_SCREEN_INDEX) {\n\t\tm_currScreenIndex = currScreen->getPrevScrenIndex();\n\t\treturn getCurrScreen();\n\t}\n\n\t\/\/There was no next screen so return nullptr.\n\treturn nullptr;\n}\n\nIScreen* ScreenList::moveToParticular(int nextScreen) {\n\n\tIScreen* currScreen = getCurrScreen();\n\tif (currScreen->getScreenIndex() != NO_CURRENT_SCREEN_INDEX) {\n\t\tm_currScreenIndex = nextScreen;\n\t\treturn getCurrScreen();\n\t}\n\n\t\/\/There was no next screen so return nullptr.\n\treturn nullptr;\n\n}\n\nvoid ScreenList::setScreen(int nextScreen) {\n\tm_currScreenIndex = nextScreen;\n}\n\nvoid ScreenList::addScreen(IScreen* newScreen) {\n\n\t\/\/Error checking\n\tif (newScreen == nullptr) {\n\t\tfatalError(\"Forgot to initialize screen!\");\n\t}\n\n\tnewScreen->m_screenIndex = m_screens.size();\n\tm_screens.push_back(newScreen);\n\tnewScreen->create();\n\tnewScreen->setGame(m_game);\n}\n\nvoid ScreenList::destroyScreen() {\n\tfor (size_t i = 0; i < m_screens.size(); i++) {\n\t\tm_screens[i]->destroy();\n\t\tdelete m_screens[i];\n\t\tm_screens[i] = nullptr;\n\t}\n\tm_screens.resize(0);\n\tm_currScreenIndex = NO_CURRENT_SCREEN_INDEX;\n}\n\nvoid ScreenList::destroyScreen(int screen) {\n\tif (screen > 0 && (size_t)screen < m_screens.size()) {\n\t\tstd::swap(m_screens[screen], m_screens.back());\n\t\tdelete m_screens[(int)m_screens.size() - 1];\n\t\tm_screens.pop_back();\n\t}\n\n\twarning(\"Passed in invalid screen index\");\n}\n\nIScreen* ScreenList::getCurrScreen() {\n\n\tif(m_currScreenIndex != NO_CURRENT_SCREEN_INDEX){\n\t\treturn m_screens[m_currScreenIndex];\n\t}\n\n\tfatalError(\"Forgot to initialize screen!\");\n\treturn nullptr;\n}\n\n}<commit_msg>Made it so that the game was set in each screen before create was called.<commit_after>\/*************************************************************************\/\n\/* ScreenList.cpp *\/\n\/*************************************************************************\/\n\/* This file is part of: *\/\n\/* Xenro Engine *\/\n\/* https:\/\/github.com\/Jmiller7023\/Xenro-Engine *\/\n\/*************************************************************************\/\n\/* Copyright 11-3-2017 Joseph Miller. *\/\n\/* *\/\n\/* Permission is hereby granted, free of charge, to any person obtaining *\/\n\/* a copy of this software and associated documentation files (the *\/\n\/* \"Software\"), to deal in the Software without restriction, including *\/\n\/* without limitation the rights to use, copy, modify, merge, publish, *\/\n\/* distribute, sublicense, and\/or sell copies of the Software, and to *\/\n\/* permit persons to whom the Software is furnished to do so, subject to *\/\n\/* the following conditions: *\/\n\/* *\/\n\/* The above copyright notice and this permission notice shall be *\/\n\/* included in all copies or substantial portions of the Software. *\/\n\/* *\/\n\/* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, *\/\n\/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF *\/\n\/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*\/\n\/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY *\/\n\/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, *\/\n\/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE *\/\n\/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *\/\n\/*************************************************************************\/\n\n#include \"ScreenList.h\"\n#include \"IScreen.h\"\n#include \"Errormessages.h\"\n\nnamespace Xenro{\n\nScreenList::ScreenList(Game* game) \n\t:m_game(game)\n{\n\t\/\/Empty\n}\n\nScreenList::~ScreenList() {\n\tdestroyScreen();\n}\n\nIScreen* ScreenList::moveNext() {\n\n\tIScreen* currScreen = getCurrScreen();\n\tif (currScreen->getScreenIndex() != NO_CURRENT_SCREEN_INDEX) {\n\t\tm_currScreenIndex = currScreen->getNextScreenIndex();\n\t\treturn getCurrScreen();\n\t}\n\t\/\/There was no next screen so return nullptr.\n\treturn nullptr;\n}\n\nIScreen* ScreenList::movePrevious() {\n\n\tIScreen* currScreen = getCurrScreen();\n\tif (currScreen->getScreenIndex() != NO_CURRENT_SCREEN_INDEX) {\n\t\tm_currScreenIndex = currScreen->getPrevScrenIndex();\n\t\treturn getCurrScreen();\n\t}\n\n\t\/\/There was no next screen so return nullptr.\n\treturn nullptr;\n}\n\nIScreen* ScreenList::moveToParticular(int nextScreen) {\n\n\tIScreen* currScreen = getCurrScreen();\n\tif (currScreen->getScreenIndex() != NO_CURRENT_SCREEN_INDEX) {\n\t\tm_currScreenIndex = nextScreen;\n\t\treturn getCurrScreen();\n\t}\n\n\t\/\/There was no next screen so return nullptr.\n\treturn nullptr;\n\n}\n\nvoid ScreenList::setScreen(int nextScreen) {\n\tm_currScreenIndex = nextScreen;\n}\n\nvoid ScreenList::addScreen(IScreen* newScreen) {\n\n\t\/\/Error checking\n\tif (newScreen == nullptr) {\n\t\tfatalError(\"Forgot to initialize screen!\");\n\t}\n\n\tnewScreen->setGame(m_game);\n\tnewScreen->m_screenIndex = m_screens.size();\n\tm_screens.push_back(newScreen);\n\tnewScreen->create();\n}\n\nvoid ScreenList::destroyScreen() {\n\tfor (size_t i = 0; i < m_screens.size(); i++) {\n\t\tm_screens[i]->destroy();\n\t\tdelete m_screens[i];\n\t\tm_screens[i] = nullptr;\n\t}\n\tm_screens.resize(0);\n\tm_currScreenIndex = NO_CURRENT_SCREEN_INDEX;\n}\n\nvoid ScreenList::destroyScreen(int screen) {\n\tif (screen > 0 && (size_t)screen < m_screens.size()) {\n\t\tstd::swap(m_screens[screen], m_screens.back());\n\t\tdelete m_screens[(int)m_screens.size() - 1];\n\t\tm_screens.pop_back();\n\t}\n\n\twarning(\"Passed in invalid screen index\");\n}\n\nIScreen* ScreenList::getCurrScreen() {\n\n\tif(m_currScreenIndex != NO_CURRENT_SCREEN_INDEX){\n\t\treturn m_screens[m_currScreenIndex];\n\t}\n\n\tfatalError(\"Forgot to initialize screen!\");\n\treturn nullptr;\n}\n\n}<|endoftext|>"} {"text":"<commit_before>\/* The MIT License\n\n Copyright (c) 2014 Adrian Tan <atks@umich.edu>\n\n Permission is hereby granted, free of charge, to any person obtaining a copy\n of this software and associated documentation files (the \"Software\"), to deal\n in the Software without restriction, including without limitation the rights\n to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n copies of the Software, and to permit persons to whom the Software is\n furnished to do so, subject to the following conditions:\n\n The above copyright notice and this permission notice shall be included in\n all copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n THE SOFTWARE.\n*\/\n\n#include \"profile_mendel_errors.h\"\n\nnamespace\n{\n\nclass Igor : Program\n{\n public:\n\n std::string version;\n\n \/\/\/\/\/\/\/\/\/\/\/\n \/\/options\/\/\n \/\/\/\/\/\/\/\/\/\/\/\n std::string input_vcf_file;\n std::string input_ped_file;\n std::string ref_fasta_file; \n std::vector<GenomeInterval> intervals;\n std::string interval_list;\n int32_t min_depth;\n float_t min_gq;\n\n \/\/\/\/\/\/\/\n \/\/i\/o\/\/\n \/\/\/\/\/\/\/\n BCFOrderedReader *odr;\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/general use\/\/\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n kstring_t variant;\n\n \/\/\/\/\/\/\/\/\/\n \/\/stats\/\/\n \/\/\/\/\/\/\/\/\/\n uint32_t no_trios;\n uint32_t no_variants;\n\n uint32_t no_00;\n uint32_t no_00_00;\n uint32_t no_00_01;\n uint32_t no_00_11;\n\n uint32_t no_11;\n uint32_t no_11_00;\n uint32_t no_11_01;\n uint32_t no_11_11;\n\n\n int32_t trio_genotypes[3][3][3];\n\n \/\/\/\/\/\/\/\/\/\n \/\/tools\/\/\n \/\/\/\/\/\/\/\/\/\n Pedigree *pedigree;\n VariantManip *vm;\n\n Igor(int argc, char ** argv)\n {\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/options initialization\/\/\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n try\n {\n std::string desc = \"Profile Mendel Errors.\";\n\n version = \"0.5\";\n TCLAP::CmdLine cmd(desc, ' ', version);\n VTOutput my; cmd.setOutput(&my);\n TCLAP::ValueArg<std::string> arg_intervals(\"i\", \"i\", \"intervals\", false, \"\", \"str\", cmd);\n TCLAP::ValueArg<std::string> arg_interval_list(\"I\", \"I\", \"file containing list of intervals []\", false, \"\", \"str\", cmd);\n TCLAP::ValueArg<std::string> arg_input_ped_file(\"p\", \"p\", \"pedigree file\", true, \"\", \"str\", cmd);\n TCLAP::ValueArg<std::string> arg_ref_fasta_file(\"r\", \"r\", \"reference sequence fasta file []\", true, \"\", \"str\", cmd);\n TCLAP::ValueArg<int32_t> arg_min_depth(\"d\", \"d\", \"minimum depth\", false, 5, \"str\", cmd);\n TCLAP::ValueArg<float> arg_min_gq(\"q\", \"q\", \"minimum genotype quality\", false, 2, \"str\", cmd);\n\n TCLAP::UnlabeledValueArg<std::string> arg_input_vcf_file(\"<in.vcf>\", \"input VCF file\", true, \"\",\"file\", cmd);\n\n cmd.parse(argc, argv);\n\n input_vcf_file = arg_input_vcf_file.getValue();\n input_ped_file = arg_input_ped_file.getValue();\n min_depth = arg_min_depth.getValue();\n min_gq = arg_min_gq.getValue();\n parse_intervals(intervals, arg_interval_list.getValue(), arg_intervals.getValue());\n }\n catch (TCLAP::ArgException &e)\n {\n std::cerr << \"error: \" << e.error() << \" for arg \" << e.argId() << \"\\n\";\n abort();\n }\n };\n\n void initialize()\n {\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/i\/o initialization\/\/\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n odr = new BCFOrderedReader(input_vcf_file, intervals);\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ped file initialization\/\/\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n pedigree = new Pedigree(input_ped_file);\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/general use\/\/\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n variant = {0,0,0};\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/stats initialization\/\/\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n no_trios = 0;\n no_variants = 0;\n\n for (int32_t i=0; i<3; ++i)\n { \n for (int32_t j=0; j<3; ++j)\n { \n for (int32_t k=0; k<3; ++k)\n {\n trio_genotypes[i][j][k] = 0;\n } \n } \n } \n \n \/\/\/\/\/\/\/\/\/\n \/\/tools\/\/\n \/\/\/\/\/\/\/\/\/\n vm = new VariantManip(ref_fasta_file);\n }\n\n void profile_mendel_errors()\n {\n bcf_hdr_t *h = odr->hdr;\n bcf1_t *v = bcf_init1();\n\n Variant variant;\n\n std::vector<Trio>& trios = pedigree->trios;\n no_trios = trios.size();\n\n int32_t missing = 0;\n int32_t mendel_homalt_err = 0;\n\n while(odr->read(v))\n {\n bcf_unpack(v, BCF_UN_STR);\n int32_t vtype = vm->classify_variant(odr->hdr, v, variant);\n \n if (bcf_get_n_allele(v)!=2 || abs(variant.alleles[0].dlen)==1)\n {\n continue;\n } \n \n int32_t *gts = NULL;\n int32_t n = 0;\n int k = bcf_get_genotypes(h, v, >s, &n);\n\n \n int32_t *pls = NULL;\n n = 0;\n k = bcf_get_format_int(h, v, \"PL\", &pls, &n);\n\n bool variant_used = false;\n int32_t pl[3];\n\n for (int32_t i =0; i< trios.size(); ++i)\n {\n int32_t j = bcf_hdr_id2int(h, BCF_DT_SAMPLE, trios[i].father.c_str());\n int32_t f1 = bcf_gt_allele(gts[j*2]);\n int32_t f2 = bcf_gt_allele(gts[j*2+1]);\n\/\/ pl[0] = pls[j*3];\n\/\/ pl[1] = pls[j*3+1];\n\/\/ pl[2] = pls[j*3+2];\n\/\/ \n\/\/ if ((f1+f2==0 && (pl[1]<10 || pl[2]<10)) ||\n\/\/ (f1+f2==1 && (pl[0]<10 || pl[2]<10)) ||\n\/\/ (f1+f2==2 && (pl[0]<10 || pl[1]<10)) )\n\/\/ {\n\/\/ f1 = -1;\n\/\/ f2 = -1;\n\/\/ }\n\n j = bcf_hdr_id2int(h, BCF_DT_SAMPLE, trios[i].mother.c_str());\n int32_t m1 = bcf_gt_allele(gts[j*2]);\n int32_t m2 = bcf_gt_allele(gts[j*2+1]);\n\/\/ pl[0] = pls[j*3];\n\/\/ pl[1] = pls[j*3+1];\n\/\/ pl[2] = pls[j*3+2];\n\/\/ \n\/\/ if ((m1+m2==0 && (pl[1]<10 || pl[2]<10)) ||\n\/\/ (m1+m2==1 && (pl[0]<10 || pl[2]<10)) ||\n\/\/ (m1+m2==2 && (pl[0]<10 || pl[1]<10)) )\n\/\/ {\n\/\/ m1 = -1;\n\/\/ m2 = -1;\n\/\/ }\n\n j = bcf_hdr_id2int(h, BCF_DT_SAMPLE, trios[i].child.c_str());\n int32_t c1 = bcf_gt_allele(gts[j*2]);\n int32_t c2 = bcf_gt_allele(gts[j*2+1]);\n\/\/ pl[0] = pls[j*3];\n\/\/ pl[1] = pls[j*3+1];\n\/\/ pl[2] = pls[j*3+2];\n\/\/ \n\/\/ if ((c1+c2==0 && (pl[1]<10 || pl[2]<10)) ||\n\/\/ (c1+c2==1 && (pl[0]<10 || pl[2]<10)) ||\n\/\/ (c1+c2==2 && (pl[0]<10 || pl[1]<10)) )\n\/\/ {\n\/\/ c1 = -1;\n\/\/ c2 = -1;\n\/\/ } \n \n if (!(f1<0 || f2<0 || m1<0 || m2<0 || c1<0 || c2<0))\n {\n printf(\"%d\/%d %d\/%d %d\/%d\\n\", f1,f2,m1,m2,c1,c2);\n ++trio_genotypes[f1+f2][m1+m2][c1+c2];\n\n variant_used = true;\n }\n }\n ++no_variants;\n\n free(gts);\n\/\/ free(dps);\n\/\/ free(pls);\n }\n\n odr->close();\n };\n\n void print_options()\n {\n std::clog << \"merge_candidate_variants v\" << version << \"\\n\\n\";\n std::clog << \"options: input VCF file \" << input_vcf_file << \"\\n\";\n std::clog << \" [p] input PED file \" << input_ped_file << \"\\n\";\n print_ref_op(\" [r] ref FASTA file \", ref_fasta_file);\n print_int_op(\" [i] intervals \", intervals);\n std::clog << \"\\n\";\n }\n\n float get_error_rate(int32_t ***gt, int32_t f, int32_t m)\n {\n float total = gt[f][m][0] + gt[f][m][1] + gt[f][m][2];\n float error_count = 0;\n if (f==0 && m==0)\n {\n error_count = gt[f][m][1] + gt[f][m][2];\n }\n else if (f==0 && m==1)\n {\n error_count = gt[f][m][2];\n }\n else if (f==0 && m==2)\n {\n error_count = gt[f][m][0] + gt[f][m][2];\n }\n else if (f==1 && m==0)\n {\n error_count = gt[f][m][1] + gt[f][m][2];\n }\n else if (f==0 && m==1)\n {\n error_count = gt[f][m][1] + gt[f][m][2];\n }\n else if (f==0 && m==1)\n {\n error_count = gt[f][m][1] + gt[f][m][2];\n }\n else if (f==0 && m==1)\n {\n error_count = gt[f][m][1] + gt[f][m][2];\n }\n else if (f==0 && m==1)\n {\n error_count = gt[f][m][1] + gt[f][m][2];\n }\n else if (f==0 && m==1)\n {\n error_count = gt[f][m][1] + gt[f][m][2];\n }\n return 1;\n }; \n\n void print_stats()\n {\n fprintf(stderr, \"\\n\");\n fprintf(stderr, \" Mendelian Errors\\n\");\n std::string g2s[3] = {\"R\/R\",\"R\/A\",\"A\/A\"};\n \n fprintf(stderr, \" R\/R R\/A A\/A Total\\n\");\n for (int32_t i=0; i<3; ++i)\n {\n for (int32_t j=0; j<3; ++j)\n {\n fprintf(stderr, \" %s %s %5d %5d %5d \\n\", g2s[i].c_str(), g2s[j].c_str(), trio_genotypes[i][j][0], trio_genotypes[i][j][1], trio_genotypes[i][j][2]);\n }\n }\n fprintf(stderr, \"\\n\");\n fprintf(stderr, \" no. of trios : %d\\n\", no_trios);\n fprintf(stderr, \" no. of variants : %d\\n\", no_variants);\n fprintf(stderr, \"\\n\");\n };\n\n ~Igor()\n {\n };\n\n private:\n};\n\n}\n\nvoid profile_mendel_errors(int argc, char ** argv)\n{\n Igor igor(argc, argv);\n igor.print_options();\n igor.initialize();\n igor.profile_mendel_errors();\n igor.print_stats();\n}\n\n<commit_msg>added a collapsed table for mendelian errors<commit_after>\/* The MIT License\n\n Copyright (c) 2014 Adrian Tan <atks@umich.edu>\n\n Permission is hereby granted, free of charge, to any person obtaining a copy\n of this software and associated documentation files (the \"Software\"), to deal\n in the Software without restriction, including without limitation the rights\n to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n copies of the Software, and to permit persons to whom the Software is\n furnished to do so, subject to the following conditions:\n\n The above copyright notice and this permission notice shall be included in\n all copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n THE SOFTWARE.\n*\/\n\n#include \"profile_mendel_errors.h\"\n\nnamespace\n{\n\nclass Igor : Program\n{\n public:\n\n std::string version;\n\n \/\/\/\/\/\/\/\/\/\/\/\n \/\/options\/\/\n \/\/\/\/\/\/\/\/\/\/\/\n std::string input_vcf_file;\n std::string input_ped_file;\n std::string ref_fasta_file; \n std::vector<GenomeInterval> intervals;\n std::string interval_list;\n int32_t min_depth;\n float_t min_gq;\n\n \/\/\/\/\/\/\/\n \/\/i\/o\/\/\n \/\/\/\/\/\/\/\n BCFOrderedReader *odr;\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/general use\/\/\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n kstring_t variant;\n\n \/\/\/\/\/\/\/\/\/\n \/\/stats\/\/\n \/\/\/\/\/\/\/\/\/\n uint32_t no_trios;\n uint32_t no_variants;\n\n uint32_t no_00;\n uint32_t no_00_00;\n uint32_t no_00_01;\n uint32_t no_00_11;\n\n uint32_t no_11;\n uint32_t no_11_00;\n uint32_t no_11_01;\n uint32_t no_11_11;\n\n\n int32_t trio_genotypes[3][3][3];\n\n \/\/\/\/\/\/\/\/\/\n \/\/tools\/\/\n \/\/\/\/\/\/\/\/\/\n Pedigree *pedigree;\n VariantManip *vm;\n\n Igor(int argc, char ** argv)\n {\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/options initialization\/\/\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n try\n {\n std::string desc = \"Profile Mendel Errors.\";\n\n version = \"0.5\";\n TCLAP::CmdLine cmd(desc, ' ', version);\n VTOutput my; cmd.setOutput(&my);\n TCLAP::ValueArg<std::string> arg_intervals(\"i\", \"i\", \"intervals\", false, \"\", \"str\", cmd);\n TCLAP::ValueArg<std::string> arg_interval_list(\"I\", \"I\", \"file containing list of intervals []\", false, \"\", \"str\", cmd);\n TCLAP::ValueArg<std::string> arg_input_ped_file(\"p\", \"p\", \"pedigree file\", true, \"\", \"str\", cmd);\n TCLAP::ValueArg<std::string> arg_ref_fasta_file(\"r\", \"r\", \"reference sequence fasta file []\", true, \"\", \"str\", cmd);\n TCLAP::ValueArg<int32_t> arg_min_depth(\"d\", \"d\", \"minimum depth\", false, 5, \"str\", cmd);\n TCLAP::ValueArg<float> arg_min_gq(\"q\", \"q\", \"minimum genotype quality\", false, 2, \"str\", cmd);\n\n TCLAP::UnlabeledValueArg<std::string> arg_input_vcf_file(\"<in.vcf>\", \"input VCF file\", true, \"\",\"file\", cmd);\n\n cmd.parse(argc, argv);\n\n input_vcf_file = arg_input_vcf_file.getValue();\n input_ped_file = arg_input_ped_file.getValue();\n min_depth = arg_min_depth.getValue();\n min_gq = arg_min_gq.getValue();\n parse_intervals(intervals, arg_interval_list.getValue(), arg_intervals.getValue());\n }\n catch (TCLAP::ArgException &e)\n {\n std::cerr << \"error: \" << e.error() << \" for arg \" << e.argId() << \"\\n\";\n abort();\n }\n };\n\n void initialize()\n {\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/i\/o initialization\/\/\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n odr = new BCFOrderedReader(input_vcf_file, intervals);\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ped file initialization\/\/\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n pedigree = new Pedigree(input_ped_file);\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/general use\/\/\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n variant = {0,0,0};\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/stats initialization\/\/\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n no_trios = 0;\n no_variants = 0;\n\n for (int32_t i=0; i<3; ++i)\n { \n for (int32_t j=0; j<3; ++j)\n { \n for (int32_t k=0; k<3; ++k)\n {\n trio_genotypes[i][j][k] = 0;\n } \n } \n } \n \n \/\/\/\/\/\/\/\/\/\n \/\/tools\/\/\n \/\/\/\/\/\/\/\/\/\n vm = new VariantManip(ref_fasta_file);\n }\n\n void profile_mendel_errors()\n {\n bcf_hdr_t *h = odr->hdr;\n bcf1_t *v = bcf_init1();\n\n Variant variant;\n\n std::vector<Trio>& trios = pedigree->trios;\n no_trios = trios.size();\n\n int32_t missing = 0;\n int32_t mendel_homalt_err = 0;\n\n while(odr->read(v))\n {\n bcf_unpack(v, BCF_UN_STR);\n int32_t vtype = vm->classify_variant(odr->hdr, v, variant);\n \n if (bcf_get_n_allele(v)!=2 || abs(variant.alleles[0].dlen)==1)\n {\n continue;\n } \n \n int32_t *gts = NULL;\n int32_t n = 0;\n int k = bcf_get_genotypes(h, v, >s, &n);\n\n \n int32_t *pls = NULL;\n n = 0;\n k = bcf_get_format_int(h, v, \"PL\", &pls, &n);\n\n bool variant_used = false;\n int32_t pl[3];\n\n for (int32_t i =0; i< trios.size(); ++i)\n {\n int32_t j = bcf_hdr_id2int(h, BCF_DT_SAMPLE, trios[i].father.c_str());\n int32_t f1 = bcf_gt_allele(gts[j*2]);\n int32_t f2 = bcf_gt_allele(gts[j*2+1]);\n\/\/ pl[0] = pls[j*3];\n\/\/ pl[1] = pls[j*3+1];\n\/\/ pl[2] = pls[j*3+2];\n\/\/ \n\/\/ if ((f1+f2==0 && (pl[1]<10 || pl[2]<10)) ||\n\/\/ (f1+f2==1 && (pl[0]<10 || pl[2]<10)) ||\n\/\/ (f1+f2==2 && (pl[0]<10 || pl[1]<10)) )\n\/\/ {\n\/\/ f1 = -1;\n\/\/ f2 = -1;\n\/\/ }\n\n j = bcf_hdr_id2int(h, BCF_DT_SAMPLE, trios[i].mother.c_str());\n int32_t m1 = bcf_gt_allele(gts[j*2]);\n int32_t m2 = bcf_gt_allele(gts[j*2+1]);\n\/\/ pl[0] = pls[j*3];\n\/\/ pl[1] = pls[j*3+1];\n\/\/ pl[2] = pls[j*3+2];\n\/\/ \n\/\/ if ((m1+m2==0 && (pl[1]<10 || pl[2]<10)) ||\n\/\/ (m1+m2==1 && (pl[0]<10 || pl[2]<10)) ||\n\/\/ (m1+m2==2 && (pl[0]<10 || pl[1]<10)) )\n\/\/ {\n\/\/ m1 = -1;\n\/\/ m2 = -1;\n\/\/ }\n\n j = bcf_hdr_id2int(h, BCF_DT_SAMPLE, trios[i].child.c_str());\n int32_t c1 = bcf_gt_allele(gts[j*2]);\n int32_t c2 = bcf_gt_allele(gts[j*2+1]);\n\/\/ pl[0] = pls[j*3];\n\/\/ pl[1] = pls[j*3+1];\n\/\/ pl[2] = pls[j*3+2];\n\/\/ \n\/\/ if ((c1+c2==0 && (pl[1]<10 || pl[2]<10)) ||\n\/\/ (c1+c2==1 && (pl[0]<10 || pl[2]<10)) ||\n\/\/ (c1+c2==2 && (pl[0]<10 || pl[1]<10)) )\n\/\/ {\n\/\/ c1 = -1;\n\/\/ c2 = -1;\n\/\/ } \n \n if (!(f1<0 || f2<0 || m1<0 || m2<0 || c1<0 || c2<0))\n {\n \/\/printf(\"%d\/%d %d\/%d %d\/%d\\n\", f1,f2,m1,m2,c1,c2);\n ++trio_genotypes[f1+f2][m1+m2][c1+c2];\n\n variant_used = true;\n }\n }\n if (variant_used) ++no_variants;\n\n free(gts);\n\/\/ free(dps);\n\/\/ free(pls);\n }\n\n odr->close();\n };\n\n void print_options()\n {\n std::clog << \"merge_candidate_variants v\" << version << \"\\n\\n\";\n std::clog << \"options: input VCF file \" << input_vcf_file << \"\\n\";\n std::clog << \" [p] input PED file \" << input_ped_file << \"\\n\";\n print_ref_op(\" [r] ref FASTA file \", ref_fasta_file);\n print_int_op(\" [i] intervals \", intervals);\n std::clog << \"\\n\";\n }\n\n float get_error_rate(int32_t gt[3][3][3], int32_t f, int32_t m, bool collapse)\n {\n float total = gt[f][m][0] + gt[f][m][1] + gt[f][m][2];\n float error_count = 0;\n if (f==m && f!=1)\/\/0\/0,2\/2\n {\n error_count = gt[f][m][1] + gt[f][m][2-f];\n }\n else if (abs(f-m)==2) \/\/0\/2,2\/0\n {\n error_count = gt[f][m][0] + gt[f][m][2];\n if (collapse)\n {\n total += gt[m][f][0] + gt[m][f][1] + gt[m][f][2];\n error_count += gt[m][f][0] + gt[m][f][2];\n } \n }\n else if (abs(f-m)==1)\/\/1\/2,2\/1,1\/0,0\/1\n {\n error_count = gt[f][m][f==1?2-m:2-f];\n if (collapse)\n {\n total += gt[m][f][0] + gt[m][f][1] + gt[m][f][2];\n error_count += gt[m][f][f==1?2-m:2-f];\n } \n }\n else if (f==1 && m==1)\/\/1\/1\n {\n error_count = 0;\n }\n\n return error_count\/total*100;\n }; \n\n float get_homhet_ratio(int32_t gt[3][3][3], int32_t f, int32_t m, bool collapse)\n {\n float hom = 0;\n float het = 0;\n if (f==m && f!=1)\/\/0\/0,2\/2\n {\n \n }\n else if (abs(f-m)==2) \/\/0\/2,2\/0\n {\n \n }\n else if (abs(f-m)==1)\/\/1\/2,2\/1,1\/0,0\/1\n {\n hom = gt[f][m][f==1?m:f];\n het = gt[f][m][1];\n if (collapse)\n {\n hom += gt[m][f][f==1?m:f];\n het += gt[m][f][1];\n } \n }\n else if (f==1 && m==1)\/\/1\/1\n {\n hom = gt[f][m][0]+gt[f][m][2];\n het = gt[f][m][1];\n }\n \n return hom\/het;\n }; \n\n\n void print_stats()\n {\n std::string g2s[3] = {\"R\/R\",\"R\/A\",\"A\/A\"};\n \n fprintf(stderr, \"\\n\");\n fprintf(stderr, \" Mendelian Errors\\n\");\n fprintf(stderr, \"\\n\");\n fprintf(stderr, \" Father Mother R\/R R\/A A\/A Error(%%) HomHet\\n\");\n for (int32_t i=0; i<3; ++i)\n {\n for (int32_t j=0; j<3; ++j)\n {\n fprintf(stderr, \" %s %s %10d %10d %10d %5.2f %4.2f\\n\", g2s[i].c_str(), g2s[j].c_str(), trio_genotypes[i][j][0], trio_genotypes[i][j][1], trio_genotypes[i][j][2], get_error_rate(trio_genotypes, i, j, false), get_homhet_ratio(trio_genotypes, i, j, false));\n }\n }\n fprintf(stderr, \"\\n\");\n fprintf(stderr, \" Parental R\/R R\/A A\/A Error(%%) HomHet\\n\");\n for (int32_t i=0; i<3; ++i)\n {\n for (int32_t j=0; j<3; ++j)\n {\n if (i!=j)\n {\n if (i<j)\n {\n int32_t rr = trio_genotypes[i][j][0] + trio_genotypes[j][i][0];\n int32_t ra = trio_genotypes[i][j][1] + trio_genotypes[j][i][1];\n int32_t aa = trio_genotypes[i][j][2] + trio_genotypes[j][i][2];\n fprintf(stderr, \" %s %s %10d %10d %10d %5.2f %4.2f\\n\", g2s[i].c_str(), g2s[j].c_str(), rr, ra, aa, get_error_rate(trio_genotypes, i, j, true), get_homhet_ratio(trio_genotypes, i, j, true));\n }\n }\n else\n {\n fprintf(stderr, \" %s %s %10d %10d %10d %5.2f %4.2f\\n\", g2s[i].c_str(), g2s[j].c_str(), trio_genotypes[i][j][0], trio_genotypes[i][j][1], trio_genotypes[i][j][2], get_error_rate(trio_genotypes, i, j, true), get_homhet_ratio(trio_genotypes, i, j, true));\n }\n }\n }\n fprintf(stderr, \"\\n\");\n fprintf(stderr, \" no. of trios : %d\\n\", no_trios);\n fprintf(stderr, \" no. of variants : %d\\n\", no_variants);\n fprintf(stderr, \"\\n\");\n };\n\n ~Igor()\n {\n };\n\n private:\n};\n\n}\n\nvoid profile_mendel_errors(int argc, char ** argv)\n{\n Igor igor(argc, argv);\n igor.print_options();\n igor.initialize();\n igor.profile_mendel_errors();\n igor.print_stats();\n}\n\n<|endoftext|>"} {"text":"<commit_before>#include \"doofit\/plotting\/Plot\/PlotSimultaneous.h\"\n\n\/\/ STL\n#include <vector>\n#include <string>\n\n\/\/ boost\n\n\/\/ ROOT\n#include \"TList.h\"\n#include \"TIterator.h\"\n#include \"TCanvas.h\"\n#include \"TPaveText.h\"\n\n\/\/ from RooFit\n#include \"RooSimultaneous.h\"\n#include \"RooAbsData.h\"\n#include \"RooAbsRealLValue.h\"\n#include \"RooAbsCategoryLValue.h\"\n#include \"RooCatType.h\"\n#include \"RooDataHist.h\"\n#include \"RooSuperCategory.h\"\n#include \"RooCategory.h\"\n\n\/\/ from DooCore\n#include \"doocore\/io\/MsgStream.h\"\n#include \"doocore\/lutils\/lutils.h\"\n\n\/\/ from Project\n\nusing namespace ROOT;\nusing namespace RooFit;\nusing namespace doocore::io;\n\nnamespace doofit {\nnamespace plotting {\n\nPlotSimultaneous::PlotSimultaneous(const PlotConfig& cfg_plot, const RooAbsRealLValue& dimension, const RooAbsData& dataset, const RooSimultaneous& pdf, const std::vector<std::string>& components, const std::string& plot_name)\n: Plot(cfg_plot, dimension, dataset, pdf, components, plot_name),\n components_regexps_(components)\n{\n \n}\n\nvoid PlotSimultaneous::PlotHandler(ScaleType sc_y, std::string suffix) const {\n const RooSimultaneous& pdf = *dynamic_cast<const RooSimultaneous*>(pdf_);\n const RooAbsData& data = *datasets_.front();\n RooAbsCategoryLValue& sim_cat = const_cast<RooAbsCategoryLValue&>(pdf.indexCat());\n TList* data_split = data.split(sim_cat);\n std::string plot_name;\n \n RooCatType* sim_cat_type = NULL;\n TIterator* sim_cat_type_iter = sim_cat.typeIterator();\n int num_slices = 0;\n while((sim_cat_type=dynamic_cast<RooCatType*>(sim_cat_type_iter->Next()))) {\n RooAbsPdf& sub_pdf = *(pdf.getPdf(sim_cat_type->GetName()));\n if (&sub_pdf != NULL) {\n RooAbsData& sub_data = *dynamic_cast<RooAbsData*>(data_split->FindObject(sim_cat_type->GetName()));\n \n \n sim_cat.setIndex(sim_cat_type->getVal());\n \n std::string cut_string = \"\";\n const RooSuperCategory* super_cat = dynamic_cast<const RooSuperCategory*>(&sim_cat);\n const RooCategory* std_cat = dynamic_cast<const RooCategory*>(&sim_cat);\n if (super_cat != NULL) {\n RooLinkedListIter* it = (RooLinkedListIter*)super_cat->inputCatList().createIterator();\n RooAbsArg* arg = NULL;\n \n while ((arg=(RooAbsArg*)it->Next())) {\n RooCategory* cat = dynamic_cast<RooCategory*>(arg);\n if (cat != NULL) {\n if (cut_string.length() > 0) cut_string = cut_string + \"&&\";\n cut_string = cut_string + cat->GetName() + \"==\" + std::to_string(cat->getIndex());\n } else {\n serr << \"Error in PlotSimultaneous::PlotHandler(...): Cannot handle category component \" << arg->GetName() << endmsg;\n }\n }\n \n sdebug << \"Cut string: \" << cut_string << endmsg;\n \n delete it;\n } else if (std_cat != NULL) {\n cut_string = std::string(std_cat->GetName()) + \"==\" + std::to_string(std_cat->getIndex());\n sdebug << \"Cut string: \" << cut_string << endmsg;\n }\n\n RooAbsData& sub_data2 = data.reduce(Cut(cut_string.c_str()));\n sub_data.Print();\n sub_data2.Print();\n \n if (&sub_data == NULL) {\n serr << \"PlotSimultaneous::PlotHandler(...): sub dataset for category \" << sim_cat_type->GetName() << \" empty. Will not plot. \" << endmsg;\n } else {\n double min,max;\n RooRealVar var(dynamic_cast<const RooRealVar&>(dimension_));\n sub_data.getRange(var, min, max);\n \/\/sdebug << \"Range: \" << min << \",\" << max << endmsg;\n \n \/\/plot_name = std::string(dimension_.GetName()) + \"_\" + sim_cat_type->GetName();\n plot_name = plot_name_ + \"_\" + sim_cat_type->GetName();\n Plot plot(config_plot_, dimension_, sub_data, sub_pdf, components_regexps_, plot_name);\n plot.plot_args_ = this->plot_args_;\n plot.plot_range_ = this->plot_range_;\n \n \/\/ 20130905 FK: deactivated this manual setting of the plot range as it\n \/\/ can dramatically increase plot time. Maybe need to\n \/\/ rethink that later\n \/\/plot.AddPlotArg(Range(min,max));\n \n \/\/ go through supplied cmd args and if necessary adapt ProjWData argument\n bool project_arg_found = false;\n RooArgSet* set_project = NULL;\n RooAbsData* data_reduced = NULL;\n const RooAbsData* data_project = NULL;\n bool binned_projection = false;\n for (std::vector<RooCmdArg>::iterator it = plot.plot_args_.begin();\n it != plot.plot_args_.end(); ++it) {\n if (std::string(it->GetName()) == \"ProjData\") {\n sinfo << \"Found ProjWData() argument. Will change projection dataset accordingly.\" << endmsg;\n project_arg_found = true;\n binned_projection = it->getInt(0);\n \n \/\/ check for binned projection and if so generate binned dataset here to\n \/\/ accelerate projection\n if (binned_projection) {\n set_project = new RooArgSet(*dynamic_cast<const RooArgSet*>(it->getObject(0)));\n \n sinfo << \" Binned projection is requested. Will generate a binned dataset to accelerate projection.\" << endmsg;\n\n\n data_reduced = sub_data.reduce(*set_project);\n std::string name_data_hist = std::string(sub_data.GetName()) + \"_hist\" + sim_cat_type->GetName();\n data_project = new RooDataHist(name_data_hist.c_str(), \"binned projection dataset\", *data_reduced->get(), *data_reduced);\n \n sinfo << \" Created binned dataset with \" << data_project->numEntries() << \" bins.\" << endmsg;\n } else {\n data_project = &sub_data;\n }\n\n \n \/\/ create the new projection argument\n *it = ProjWData(*dynamic_cast<const RooArgSet*>(it->getObject(0)),\n *data_project,\n it->getInt(0));\n }\n }\n \n doocore::lutils::setStyle(\"LHCb\");\n config_plot_.OnDemandOpenPlotStack();\n TCanvas c1(\"c1\",\"c1\",900,900);\n std::string label_text1 = std::string(\"Next plots: dimension \") + dimension_.GetName() + \", category \" + sim_cat_type->GetName();\n std::string label_text2 = std::string(\" (\") + plot_name + \")\";\n TPaveText label(0.1, 0.25, 0.9, 0.75);\n label.SetTextSize(0.03);\n label.AddText(label_text1.c_str());\n label.AddText(label_text2.c_str());\n label.SetLineWidth(0.0);\n label.SetTextAlign(13);\n label.SetFillColor(0);\n label.Draw();\n c1.Print(std::string(config_plot_.plot_directory()+\"\/pdf\/AllPlots\"+config_plot_.plot_appendix()+\".pdf\").c_str());\n \n plot.PlotHandler(sc_y, suffix);\n \n if (set_project != NULL) delete set_project;\n if (binned_projection) {\n delete data_project;\n delete data_reduced;\n }\n \n ++num_slices;\n }\n }\n }\n \n if (num_slices > 1) {\n TCanvas c1(\"c1\",\"c1\",900,900);\n std::string label_text1 = std::string(\"Next plots: dimension \") + dimension_.GetName() + \", summed all categories \";\n std::string label_text2 = std::string(\" (\") + plot_name + \")\";\n TPaveText label(0.1, 0.25, 0.9, 0.75);\n label.SetTextSize(0.03);\n label.AddText(label_text1.c_str());\n label.AddText(label_text2.c_str());\n label.SetLineWidth(0.0);\n label.SetTextAlign(13);\n label.SetFillColor(0);\n label.Draw();\n c1.Print(std::string(config_plot_.plot_directory()+\"\/pdf\/AllPlots\"+config_plot_.plot_appendix()+\".pdf\").c_str());\n \n \/\/ plot_name = std::string(dimension_.GetName()) + \"_summed\";\n plot_name = plot_name_ + \"_summed\";\n Plot plot(config_plot_, dimension_, data, *pdf_, components_regexps_, plot_name);\n plot.plot_args_ = this->plot_args_;\n plot.plot_range_ = this->plot_range_;\n \n \/\/ go through supplied cmd args and if necessary merge ProjWData arguments\n bool project_arg_found = false;\n RooArgSet* set_project = NULL;\n RooAbsData* data_reduced = NULL;\n const RooAbsData* data_project = NULL;\n bool binned_projection = false;\n for (std::vector<RooCmdArg>::iterator it = plot.plot_args_.begin();\n it != plot.plot_args_.end(); ++it) {\n if (std::string(it->GetName()) == \"ProjData\") {\n sinfo << \"Found ProjWData() argument. Will join with \" << sim_cat.GetName() << \" on same dataset.\" << endmsg;\n project_arg_found = true;\n binned_projection = it->getInt(0);\n \n \/\/ copy argset for projection and add simultaneous category variables\n set_project = new RooArgSet(*dynamic_cast<const RooArgSet*>(it->getObject(0)));\n const RooSuperCategory* super_sim_cat = &dynamic_cast<const RooSuperCategory&>(sim_cat);\n if (super_sim_cat) {\n \/\/ The simultaneous category is a super category and will not be in the\n \/\/ supplied dataset. Add input categories instead.\n set_project->add(super_sim_cat->inputCatList());\n } else {\n set_project->add(sim_cat);\n }\n \n \/\/ check for binned projection and if so generate binned dataset here to\n \/\/ accelerate projection\n if (binned_projection) {\n sinfo << \" Binned projection is requested. Will generate a binned dataset to accelerate projection.\" << endmsg;\n \n RooAbsData* data_proj = const_cast<RooAbsData*>(dynamic_cast<const RooAbsData*>(it->getObject(1)));\n std::string name_data_hist = std::string(data_proj->GetName()) + \"_hist\";\n data_reduced = data_proj->reduce(*set_project);\n data_project = new RooDataHist(name_data_hist.c_str(), \"binned projection dataset\", *data_reduced->get(), *data_reduced);\n \n sinfo << \" Created binned dataset with \" << data_project->numEntries() << \" bins.\" << endmsg;\n } else {\n data_project = dynamic_cast<const RooAbsData*>(it->getObject(1));\n }\n \n \/\/ create the new projection argument\n *it = ProjWData(*set_project,\n *data_project,\n it->getInt(0));\n }\n }\n if (!project_arg_found) plot.AddPlotArg(ProjWData(sim_cat,data));\n \n plot.PlotHandler(sc_y, suffix);\n\n if (set_project != NULL) delete set_project;\n if (binned_projection) {\n delete data_reduced;\n delete data_project;\n }\n }\n \n TIter next(data_split);\n TObject *obj = NULL;\n while ((obj = next())) {\n delete obj;\n }\n}\n \n} \/\/ namespace plotting\n} \/\/ namespace doofit\n<commit_msg>PlotSimultaneous: Using hand-made sub datasets<commit_after>#include \"doofit\/plotting\/Plot\/PlotSimultaneous.h\"\n\n\/\/ STL\n#include <vector>\n#include <string>\n\n\/\/ boost\n\n\/\/ ROOT\n#include \"TList.h\"\n#include \"TIterator.h\"\n#include \"TCanvas.h\"\n#include \"TPaveText.h\"\n\n\/\/ from RooFit\n#include \"RooSimultaneous.h\"\n#include \"RooAbsData.h\"\n#include \"RooAbsRealLValue.h\"\n#include \"RooAbsCategoryLValue.h\"\n#include \"RooCatType.h\"\n#include \"RooDataHist.h\"\n#include \"RooSuperCategory.h\"\n#include \"RooCategory.h\"\n\n\/\/ from DooCore\n#include \"doocore\/io\/MsgStream.h\"\n#include \"doocore\/lutils\/lutils.h\"\n\n\/\/ from Project\n\nusing namespace ROOT;\nusing namespace RooFit;\nusing namespace doocore::io;\n\nnamespace doofit {\nnamespace plotting {\n\nPlotSimultaneous::PlotSimultaneous(const PlotConfig& cfg_plot, const RooAbsRealLValue& dimension, const RooAbsData& dataset, const RooSimultaneous& pdf, const std::vector<std::string>& components, const std::string& plot_name)\n: Plot(cfg_plot, dimension, dataset, pdf, components, plot_name),\n components_regexps_(components)\n{\n \n}\n\nvoid PlotSimultaneous::PlotHandler(ScaleType sc_y, std::string suffix) const {\n const RooSimultaneous& pdf = *dynamic_cast<const RooSimultaneous*>(pdf_);\n const RooAbsData& data = *datasets_.front();\n RooAbsData& data_nonconst_fucking_roofit = const_cast<RooAbsData&>(data);\n RooAbsCategoryLValue& sim_cat = const_cast<RooAbsCategoryLValue&>(pdf.indexCat());\n \/\/TList* data_split = data.split(sim_cat);\n std::string plot_name;\n \n RooCatType* sim_cat_type = NULL;\n TIterator* sim_cat_type_iter = sim_cat.typeIterator();\n int num_slices = 0;\n while((sim_cat_type=dynamic_cast<RooCatType*>(sim_cat_type_iter->Next()))) {\n RooAbsPdf& sub_pdf = *(pdf.getPdf(sim_cat_type->GetName()));\n if (&sub_pdf != NULL) {\n \/\/RooAbsData& sub_data = *dynamic_cast<RooAbsData*>(data_split->FindObject(sim_cat_type->GetName()));\n \n \n sim_cat.setIndex(sim_cat_type->getVal());\n \n std::string cut_string = \"\";\n const RooSuperCategory* super_cat = dynamic_cast<const RooSuperCategory*>(&sim_cat);\n const RooCategory* std_cat = dynamic_cast<const RooCategory*>(&sim_cat);\n if (super_cat != NULL) {\n RooLinkedListIter* it = (RooLinkedListIter*)super_cat->inputCatList().createIterator();\n RooAbsArg* arg = NULL;\n \n while ((arg=(RooAbsArg*)it->Next())) {\n RooCategory* cat = dynamic_cast<RooCategory*>(arg);\n if (cat != NULL) {\n if (cut_string.length() > 0) cut_string = cut_string + \"&&\";\n cut_string = cut_string + cat->GetName() + \"==\" + std::to_string(cat->getIndex());\n } else {\n serr << \"Error in PlotSimultaneous::PlotHandler(...): Cannot handle category component \" << arg->GetName() << endmsg;\n }\n }\n \n sdebug << \"Cut string: \" << cut_string << endmsg;\n \n delete it;\n } else if (std_cat != NULL) {\n cut_string = std::string(std_cat->GetName()) + \"==\" + std::to_string(std_cat->getIndex());\n sdebug << \"Cut string: \" << cut_string << endmsg;\n }\n\n RooAbsData* sub_data2 = data_nonconst_fucking_roofit.reduce(Cut(cut_string.c_str()));\n RooAbsData& sub_data = *sub_data2;\n \n if (&sub_data == NULL) {\n serr << \"PlotSimultaneous::PlotHandler(...): sub dataset for category \" << sim_cat_type->GetName() << \" empty. Will not plot. \" << endmsg;\n } else {\n double min,max;\n RooRealVar var(dynamic_cast<const RooRealVar&>(dimension_));\n sub_data.getRange(var, min, max);\n \/\/sdebug << \"Range: \" << min << \",\" << max << endmsg;\n \n \/\/plot_name = std::string(dimension_.GetName()) + \"_\" + sim_cat_type->GetName();\n plot_name = plot_name_ + \"_\" + sim_cat_type->GetName();\n Plot plot(config_plot_, dimension_, sub_data, sub_pdf, components_regexps_, plot_name);\n plot.plot_args_ = this->plot_args_;\n plot.plot_range_ = this->plot_range_;\n \n \/\/ 20130905 FK: deactivated this manual setting of the plot range as it\n \/\/ can dramatically increase plot time. Maybe need to\n \/\/ rethink that later\n \/\/plot.AddPlotArg(Range(min,max));\n \n \/\/ go through supplied cmd args and if necessary adapt ProjWData argument\n bool project_arg_found = false;\n RooArgSet* set_project = NULL;\n RooAbsData* data_reduced = NULL;\n const RooAbsData* data_project = NULL;\n bool binned_projection = false;\n for (std::vector<RooCmdArg>::iterator it = plot.plot_args_.begin();\n it != plot.plot_args_.end(); ++it) {\n if (std::string(it->GetName()) == \"ProjData\") {\n sinfo << \"Found ProjWData() argument. Will change projection dataset accordingly.\" << endmsg;\n project_arg_found = true;\n binned_projection = it->getInt(0);\n \n \/\/ check for binned projection and if so generate binned dataset here to\n \/\/ accelerate projection\n if (binned_projection) {\n set_project = new RooArgSet(*dynamic_cast<const RooArgSet*>(it->getObject(0)));\n \n sinfo << \" Binned projection is requested. Will generate a binned dataset to accelerate projection.\" << endmsg;\n\n\n data_reduced = sub_data.reduce(*set_project);\n std::string name_data_hist = std::string(sub_data.GetName()) + \"_hist\" + sim_cat_type->GetName();\n data_project = new RooDataHist(name_data_hist.c_str(), \"binned projection dataset\", *data_reduced->get(), *data_reduced);\n \n sinfo << \" Created binned dataset with \" << data_project->numEntries() << \" bins.\" << endmsg;\n } else {\n data_project = &sub_data;\n }\n\n \n \/\/ create the new projection argument\n *it = ProjWData(*dynamic_cast<const RooArgSet*>(it->getObject(0)),\n *data_project,\n it->getInt(0));\n }\n }\n \n doocore::lutils::setStyle(\"LHCb\");\n config_plot_.OnDemandOpenPlotStack();\n TCanvas c1(\"c1\",\"c1\",900,900);\n std::string label_text1 = std::string(\"Next plots: dimension \") + dimension_.GetName() + \", category \" + sim_cat_type->GetName();\n std::string label_text2 = std::string(\" (\") + plot_name + \")\";\n TPaveText label(0.1, 0.25, 0.9, 0.75);\n label.SetTextSize(0.03);\n label.AddText(label_text1.c_str());\n label.AddText(label_text2.c_str());\n label.SetLineWidth(0.0);\n label.SetTextAlign(13);\n label.SetFillColor(0);\n label.Draw();\n c1.Print(std::string(config_plot_.plot_directory()+\"\/pdf\/AllPlots\"+config_plot_.plot_appendix()+\".pdf\").c_str());\n \n plot.PlotHandler(sc_y, suffix);\n \n if (set_project != NULL) delete set_project;\n if (binned_projection) {\n delete data_project;\n delete data_reduced;\n }\n \n ++num_slices;\n }\n \n if (sub_data2 != NULL) {\n delete sub_data2;\n }\n }\n }\n \n if (num_slices > 1) {\n TCanvas c1(\"c1\",\"c1\",900,900);\n std::string label_text1 = std::string(\"Next plots: dimension \") + dimension_.GetName() + \", summed all categories \";\n std::string label_text2 = std::string(\" (\") + plot_name + \")\";\n TPaveText label(0.1, 0.25, 0.9, 0.75);\n label.SetTextSize(0.03);\n label.AddText(label_text1.c_str());\n label.AddText(label_text2.c_str());\n label.SetLineWidth(0.0);\n label.SetTextAlign(13);\n label.SetFillColor(0);\n label.Draw();\n c1.Print(std::string(config_plot_.plot_directory()+\"\/pdf\/AllPlots\"+config_plot_.plot_appendix()+\".pdf\").c_str());\n \n \/\/ plot_name = std::string(dimension_.GetName()) + \"_summed\";\n plot_name = plot_name_ + \"_summed\";\n Plot plot(config_plot_, dimension_, data, *pdf_, components_regexps_, plot_name);\n plot.plot_args_ = this->plot_args_;\n plot.plot_range_ = this->plot_range_;\n \n \/\/ go through supplied cmd args and if necessary merge ProjWData arguments\n bool project_arg_found = false;\n RooArgSet* set_project = NULL;\n RooAbsData* data_reduced = NULL;\n const RooAbsData* data_project = NULL;\n bool binned_projection = false;\n for (std::vector<RooCmdArg>::iterator it = plot.plot_args_.begin();\n it != plot.plot_args_.end(); ++it) {\n if (std::string(it->GetName()) == \"ProjData\") {\n sinfo << \"Found ProjWData() argument. Will join with \" << sim_cat.GetName() << \" on same dataset.\" << endmsg;\n project_arg_found = true;\n binned_projection = it->getInt(0);\n \n \/\/ copy argset for projection and add simultaneous category variables\n set_project = new RooArgSet(*dynamic_cast<const RooArgSet*>(it->getObject(0)));\n const RooSuperCategory* super_sim_cat = &dynamic_cast<const RooSuperCategory&>(sim_cat);\n if (super_sim_cat) {\n \/\/ The simultaneous category is a super category and will not be in the\n \/\/ supplied dataset. Add input categories instead.\n set_project->add(super_sim_cat->inputCatList());\n } else {\n set_project->add(sim_cat);\n }\n \n \/\/ check for binned projection and if so generate binned dataset here to\n \/\/ accelerate projection\n if (binned_projection) {\n sinfo << \" Binned projection is requested. Will generate a binned dataset to accelerate projection.\" << endmsg;\n \n RooAbsData* data_proj = const_cast<RooAbsData*>(dynamic_cast<const RooAbsData*>(it->getObject(1)));\n std::string name_data_hist = std::string(data_proj->GetName()) + \"_hist\";\n data_reduced = data_proj->reduce(*set_project);\n data_project = new RooDataHist(name_data_hist.c_str(), \"binned projection dataset\", *data_reduced->get(), *data_reduced);\n \n sinfo << \" Created binned dataset with \" << data_project->numEntries() << \" bins.\" << endmsg;\n } else {\n data_project = dynamic_cast<const RooAbsData*>(it->getObject(1));\n }\n \n \/\/ create the new projection argument\n *it = ProjWData(*set_project,\n *data_project,\n it->getInt(0));\n }\n }\n if (!project_arg_found) plot.AddPlotArg(ProjWData(sim_cat,data));\n \n plot.PlotHandler(sc_y, suffix);\n\n if (set_project != NULL) delete set_project;\n if (binned_projection) {\n delete data_reduced;\n delete data_project;\n }\n }\n \n TIter next(data_split);\n TObject *obj = NULL;\n while ((obj = next())) {\n delete obj;\n }\n}\n \n} \/\/ namespace plotting\n} \/\/ namespace doofit\n<|endoftext|>"} {"text":"<commit_before>\/*!\n *\n * Copyright (C) 2012 Jolla Ltd.\n *\n * Contact: Mohammed Hassan <mohammed.hassan@jollamobile.com>\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n *\/\n\n#include \"grilodatasource.h\"\n#include \"grilomedia.h\"\n#include \"grilomodel.h\"\n#include \"griloregistry.h\"\n#include <QDebug>\n\n#include <QTimerEvent>\n\nstatic void fill_key_id(gpointer data, gpointer user_data) {\n QVariantList *varList = static_cast<QVariantList *>(user_data);\n varList->append(GriloDataSource::MetadataKeys(GRLPOINTER_TO_KEYID(data)));\n}\n\nGriloDataSource::GriloDataSource(QObject *parent) :\n QObject(parent),\n m_opId(0),\n m_registry(0),\n m_count(0),\n m_skip(0),\n m_insertIndex(0),\n m_updateScheduled(false) {\n\n m_metadataKeys << Title;\n m_typeFilter << None;\n}\n\nGriloDataSource::~GriloDataSource() {\n cancelRefresh();\n m_models.clear();\n}\n\nconst QList<GriloMedia *> *GriloDataSource::media() const {\n return &m_media;\n}\n\nvoid GriloDataSource::addModel(GriloModel *model) {\n if (m_models.indexOf(model) == -1) {\n m_models << model;\n }\n}\n\nvoid GriloDataSource::removeModel(GriloModel *model) {\n if (int index = m_models.indexOf(model) != -1) {\n m_models.removeAt(index);\n }\n}\n\nvoid GriloDataSource::prefill(GriloModel *model) {\n if (m_media.isEmpty()) {\n return;\n }\n\n model->beginInsertRows(QModelIndex(), 0, m_media.size() - 1);\n model->endInsertRows();\n\n emit model->countChanged();\n}\n\nvoid GriloDataSource::addMedia(GrlMedia *media) {\n GriloMedia *wrappedMedia = 0;\n\n if (m_insertIndex < m_media.count()) {\n wrappedMedia = m_hash.value(QString::fromUtf8(grl_media_get_id(media)), 0);\n }\n\n if (wrappedMedia) {\n \/\/ If the media was already queried by a previous fetch update its position and refresh\n \/\/ the data instead of creating another item.\n bool dataChanged = false;\n int index = m_media.indexOf(wrappedMedia);\n if (index == m_insertIndex) {\n dataChanged = true;\n } else if (index != -1) {\n dataChanged = true;\n foreach (GriloModel *model, m_models) {\n model->beginMoveRows(QModelIndex(), index, index, QModelIndex(), m_insertIndex);\n }\n m_media.move(index, m_insertIndex);\n foreach (GriloModel *model, m_models) {\n model->endMoveRows();\n }\n }\n\n if (dataChanged) {\n wrappedMedia->setMedia(media);\n foreach (GriloModel *model, m_models) {\n QModelIndex modelIndex = model->index(m_insertIndex, 0);\n model->dataChanged(modelIndex, modelIndex);\n }\n ++m_insertIndex;\n return;\n }\n }\n\n wrappedMedia = new GriloMedia(media);\n\n foreach (GriloModel *model, m_models) {\n model->beginInsertRows(QModelIndex(), m_insertIndex, m_insertIndex);\n }\n\n m_media.insert(m_insertIndex, wrappedMedia);\n ++m_insertIndex;\n\n QString id = wrappedMedia->id();\n if (!id.isEmpty()) {\n m_hash.insert(id, wrappedMedia);\n }\n\n foreach (GriloModel *model, m_models) {\n model->endInsertRows();\n emit model->countChanged();\n }\n\n}\n\nvoid GriloDataSource::removeMedia(GrlMedia *media) {\n QString id = QString::fromUtf8(grl_media_get_id(media));\n\n if (id.isEmpty() || !m_hash.contains(id)) {\n \/\/ We really cannot do much.\n return;\n }\n\n GriloMedia *wrapper = m_hash[id];\n int index = m_media.indexOf(wrapper);\n if (index < m_insertIndex) {\n --m_insertIndex;\n }\n\n \/\/ remove from models:\n foreach (GriloModel *model, m_models) {\n model->beginRemoveRows(QModelIndex(), index, index);\n }\n\n \/\/ remove from hash\n m_hash.take(id);\n\n \/\/ remove from list\n m_media.takeAt(index);\n\n \/\/ destroy\n wrapper->deleteLater();\n\n foreach (GriloModel *model, m_models) {\n model->endRemoveRows();\n emit model->countChanged();\n }\n}\n\nvoid GriloDataSource::clearMedia() {\n if (m_media.isEmpty()) {\n return;\n }\n\n int size = m_media.size();\n\n foreach (GriloModel *model, m_models) {\n model->beginRemoveRows(QModelIndex(), 0, size - 1);\n }\n\n qDeleteAll(m_media);\n m_media.clear();\n m_hash.clear();\n\n foreach (GriloModel *model, m_models) {\n model->endRemoveRows();\n emit model->countChanged();\n }\n}\n\nGriloRegistry *GriloDataSource::registry() const {\n return m_registry;\n}\n\nvoid GriloDataSource::setRegistry(GriloRegistry *registry) {\n \/\/ Registry change is not allowed for now.\n\n if (!m_registry && registry != m_registry) {\n\n m_registry = registry;\n\n QObject::connect(m_registry, SIGNAL(availableSourcesChanged()),\n\t\t this, SLOT(availableSourcesChanged()));\n QObject::connect(m_registry, SIGNAL(contentChanged(QString,GrlSourceChangeType,GPtrArray*)),\n this, SLOT(contentChanged(QString,GrlSourceChangeType,GPtrArray*)));\n\n emit registryChanged();\n }\n}\n\nint GriloDataSource::count() const {\n return m_count;\n}\n\nvoid GriloDataSource::setCount(int count) {\n if (m_count != count) {\n m_count = count;\n emit countChanged();\n }\n}\n\nint GriloDataSource::skip() const {\n return m_skip;\n}\n\nvoid GriloDataSource::setSkip(int skip) {\n if (m_skip != skip) {\n m_skip = skip;\n emit skipChanged();\n }\n}\n\nQVariantList GriloDataSource::metadataKeys() const {\n return m_metadataKeys;\n}\n\nvoid GriloDataSource::setMetadataKeys(const QVariantList& keys) {\n if (m_metadataKeys != keys) {\n m_metadataKeys = keys;\n emit metadataKeysChanged();\n }\n}\n\nQVariantList GriloDataSource::typeFilter() const {\n return m_typeFilter;\n}\n\nvoid GriloDataSource::setTypeFilter(const QVariantList& filter) {\n if (m_typeFilter != filter) {\n m_typeFilter = filter;\n emit typeFilterChanged();\n }\n}\n\nGrlOperationOptions *GriloDataSource::operationOptions(GrlSource *src, const OperationType& type) {\n GrlCaps *caps = NULL;\n\n if (src) {\n caps = grl_source_get_caps(src, (GrlSupportedOps)type);\n }\n\n GrlOperationOptions *options = grl_operation_options_new(caps);\n\n grl_operation_options_set_flags(options, GRL_RESOLVE_IDLE_RELAY); \/\/ TODO: hardcoded\n grl_operation_options_set_skip(options, m_skip);\n\n if (m_count != 0) {\n grl_operation_options_set_count(options, m_count);\n }\n\n int typeFilter = 0;\n foreach (const QVariant& var, m_typeFilter) {\n if (var.canConvert<int>()) {\n typeFilter |= var.toInt();\n }\n }\n\n grl_operation_options_set_type_filter(options, (GrlTypeFilter)typeFilter);\n\n return options;\n}\n\nGList *GriloDataSource::keysAsList() {\n \/\/ TODO: Check why using grl_metadata_key_list_new() produces a symbol error.\n GList *keys = NULL;\n\n foreach (const QVariant& var, m_metadataKeys) {\n if (var.canConvert<int>()) {\n keys = g_list_append(keys, GRLKEYID_TO_POINTER(var.toInt()));\n }\n }\n\n return keys;\n}\n\nvoid GriloDataSource::cancelRefresh() {\n if (m_opId != 0) {\n grl_operation_cancel(m_opId);\n m_opId = 0;\n }\n\n m_insertIndex = 0;\n m_updateScheduled = false;\n m_updateTimer.stop();\n}\n\nvoid GriloDataSource::grilo_source_result_cb(GrlSource *source, guint op_id,\n\t\t\t\t\t GrlMedia *media, guint remaining,\n\t\t\t\t\t gpointer user_data, const GError *error) {\n\n Q_UNUSED(source);\n\n \/\/ We get an error if the operation has been canceled:\n if (error) {\n if (error->domain != GRL_CORE_ERROR || error->code != GRL_CORE_ERROR_OPERATION_CANCELLED) {\n \/\/ TODO: error reporting?\n qCritical() << \"Operation failed\" << error->message;\n }\n }\n\n GriloDataSource *that = static_cast<GriloDataSource *>(user_data);\n\n if (that->m_opId != op_id) {\n qWarning() << \"Got results belonging to an unknown browse id\";\n\n if (media) {\n g_object_unref(media);\n }\n\n return;\n }\n\n if (media) {\n that->addMedia(media);\n }\n\n if (remaining == 0) {\n emit that->finished();\n that->m_opId = 0;\n\n if (that->m_updateScheduled) {\n that->m_updateTimer.start(100, that);\n }\n\n \/\/ If there are items from a previous fetch still remaining remove them.\n if (that->m_insertIndex < that->m_media.count()) {\n foreach (GriloModel *model, that->m_models) {\n model->beginRemoveRows(QModelIndex(), that->m_insertIndex, that->m_media.count() - 1);\n }\n while (that->m_media.count() > that->m_insertIndex) {\n GriloMedia *media = that->m_media.takeLast();\n that->m_hash.remove(media->id());\n delete media;\n }\n foreach (GriloModel *model, that->m_models) {\n model->endRemoveRows();\n emit model->countChanged();\n }\n }\n }\n}\n\nvoid GriloDataSource::contentChanged(const QString &source, GrlSourceChangeType change_type,\n GPtrArray *changed_media)\n{\n Q_UNUSED(source);\n Q_UNUSED(change_type);\n Q_UNUSED(changed_media);\n}\n\nvoid GriloDataSource::updateContent(GrlSourceChangeType change_type, GPtrArray *changed_media)\n{\n switch (change_type) {\n case GRL_CONTENT_CHANGED:\n case GRL_CONTENT_ADDED:\n if (!m_updateScheduled) {\n m_updateScheduled = true;\n if (m_opId == 0) {\n m_updateTimer.start(100, this);\n }\n }\n break;\n case GRL_CONTENT_REMOVED:\n for (uint i = 0; i < changed_media->len; ++i) {\n removeMedia((GrlMedia *)g_ptr_array_index(changed_media, i));\n }\n break;\n default:\n break;\n }\n}\n\nQVariantList GriloDataSource::listToVariantList(const GList *keys) const {\n QVariantList varList;\n\n g_list_foreach(const_cast<GList *>(keys), fill_key_id, &varList);\n\n return varList;\n}\n\nvoid GriloDataSource::timerEvent(QTimerEvent *event) {\n if (event->timerId() == m_updateTimer.timerId()) {\n m_updateTimer.stop();\n emit contentUpdated();\n }\n}\n<commit_msg>[datasource] Callback returns immediately on canceled refresh<commit_after>\/*!\n *\n * Copyright (C) 2012 Jolla Ltd.\n *\n * Contact: Mohammed Hassan <mohammed.hassan@jollamobile.com>\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n *\/\n\n#include \"grilodatasource.h\"\n#include \"grilomedia.h\"\n#include \"grilomodel.h\"\n#include \"griloregistry.h\"\n#include <QDebug>\n\n#include <QTimerEvent>\n\nstatic void fill_key_id(gpointer data, gpointer user_data) {\n QVariantList *varList = static_cast<QVariantList *>(user_data);\n varList->append(GriloDataSource::MetadataKeys(GRLPOINTER_TO_KEYID(data)));\n}\n\nGriloDataSource::GriloDataSource(QObject *parent) :\n QObject(parent),\n m_opId(0),\n m_registry(0),\n m_count(0),\n m_skip(0),\n m_insertIndex(0),\n m_updateScheduled(false) {\n\n m_metadataKeys << Title;\n m_typeFilter << None;\n}\n\nGriloDataSource::~GriloDataSource() {\n cancelRefresh();\n m_models.clear();\n}\n\nconst QList<GriloMedia *> *GriloDataSource::media() const {\n return &m_media;\n}\n\nvoid GriloDataSource::addModel(GriloModel *model) {\n if (m_models.indexOf(model) == -1) {\n m_models << model;\n }\n}\n\nvoid GriloDataSource::removeModel(GriloModel *model) {\n if (int index = m_models.indexOf(model) != -1) {\n m_models.removeAt(index);\n }\n}\n\nvoid GriloDataSource::prefill(GriloModel *model) {\n if (m_media.isEmpty()) {\n return;\n }\n\n model->beginInsertRows(QModelIndex(), 0, m_media.size() - 1);\n model->endInsertRows();\n\n emit model->countChanged();\n}\n\nvoid GriloDataSource::addMedia(GrlMedia *media) {\n GriloMedia *wrappedMedia = 0;\n\n if (m_insertIndex < m_media.count()) {\n wrappedMedia = m_hash.value(QString::fromUtf8(grl_media_get_id(media)), 0);\n }\n\n if (wrappedMedia) {\n \/\/ If the media was already queried by a previous fetch update its position and refresh\n \/\/ the data instead of creating another item.\n bool dataChanged = false;\n int index = m_media.indexOf(wrappedMedia);\n if (index == m_insertIndex) {\n dataChanged = true;\n } else if (index != -1) {\n dataChanged = true;\n foreach (GriloModel *model, m_models) {\n model->beginMoveRows(QModelIndex(), index, index, QModelIndex(), m_insertIndex);\n }\n m_media.move(index, m_insertIndex);\n foreach (GriloModel *model, m_models) {\n model->endMoveRows();\n }\n }\n\n if (dataChanged) {\n wrappedMedia->setMedia(media);\n foreach (GriloModel *model, m_models) {\n QModelIndex modelIndex = model->index(m_insertIndex, 0);\n model->dataChanged(modelIndex, modelIndex);\n }\n ++m_insertIndex;\n return;\n }\n }\n\n wrappedMedia = new GriloMedia(media);\n\n foreach (GriloModel *model, m_models) {\n model->beginInsertRows(QModelIndex(), m_insertIndex, m_insertIndex);\n }\n\n m_media.insert(m_insertIndex, wrappedMedia);\n ++m_insertIndex;\n\n QString id = wrappedMedia->id();\n if (!id.isEmpty()) {\n m_hash.insert(id, wrappedMedia);\n }\n\n foreach (GriloModel *model, m_models) {\n model->endInsertRows();\n emit model->countChanged();\n }\n\n}\n\nvoid GriloDataSource::removeMedia(GrlMedia *media) {\n QString id = QString::fromUtf8(grl_media_get_id(media));\n\n if (id.isEmpty() || !m_hash.contains(id)) {\n \/\/ We really cannot do much.\n return;\n }\n\n GriloMedia *wrapper = m_hash[id];\n int index = m_media.indexOf(wrapper);\n if (index < m_insertIndex) {\n --m_insertIndex;\n }\n\n \/\/ remove from models:\n foreach (GriloModel *model, m_models) {\n model->beginRemoveRows(QModelIndex(), index, index);\n }\n\n \/\/ remove from hash\n m_hash.take(id);\n\n \/\/ remove from list\n m_media.takeAt(index);\n\n \/\/ destroy\n wrapper->deleteLater();\n\n foreach (GriloModel *model, m_models) {\n model->endRemoveRows();\n emit model->countChanged();\n }\n}\n\nvoid GriloDataSource::clearMedia() {\n if (m_media.isEmpty()) {\n return;\n }\n\n int size = m_media.size();\n\n foreach (GriloModel *model, m_models) {\n model->beginRemoveRows(QModelIndex(), 0, size - 1);\n }\n\n qDeleteAll(m_media);\n m_media.clear();\n m_hash.clear();\n\n foreach (GriloModel *model, m_models) {\n model->endRemoveRows();\n emit model->countChanged();\n }\n}\n\nGriloRegistry *GriloDataSource::registry() const {\n return m_registry;\n}\n\nvoid GriloDataSource::setRegistry(GriloRegistry *registry) {\n \/\/ Registry change is not allowed for now.\n\n if (!m_registry && registry != m_registry) {\n\n m_registry = registry;\n\n QObject::connect(m_registry, SIGNAL(availableSourcesChanged()),\n\t\t this, SLOT(availableSourcesChanged()));\n QObject::connect(m_registry, SIGNAL(contentChanged(QString,GrlSourceChangeType,GPtrArray*)),\n this, SLOT(contentChanged(QString,GrlSourceChangeType,GPtrArray*)));\n\n emit registryChanged();\n }\n}\n\nint GriloDataSource::count() const {\n return m_count;\n}\n\nvoid GriloDataSource::setCount(int count) {\n if (m_count != count) {\n m_count = count;\n emit countChanged();\n }\n}\n\nint GriloDataSource::skip() const {\n return m_skip;\n}\n\nvoid GriloDataSource::setSkip(int skip) {\n if (m_skip != skip) {\n m_skip = skip;\n emit skipChanged();\n }\n}\n\nQVariantList GriloDataSource::metadataKeys() const {\n return m_metadataKeys;\n}\n\nvoid GriloDataSource::setMetadataKeys(const QVariantList& keys) {\n if (m_metadataKeys != keys) {\n m_metadataKeys = keys;\n emit metadataKeysChanged();\n }\n}\n\nQVariantList GriloDataSource::typeFilter() const {\n return m_typeFilter;\n}\n\nvoid GriloDataSource::setTypeFilter(const QVariantList& filter) {\n if (m_typeFilter != filter) {\n m_typeFilter = filter;\n emit typeFilterChanged();\n }\n}\n\nGrlOperationOptions *GriloDataSource::operationOptions(GrlSource *src, const OperationType& type) {\n GrlCaps *caps = NULL;\n\n if (src) {\n caps = grl_source_get_caps(src, (GrlSupportedOps)type);\n }\n\n GrlOperationOptions *options = grl_operation_options_new(caps);\n\n grl_operation_options_set_flags(options, GRL_RESOLVE_IDLE_RELAY); \/\/ TODO: hardcoded\n grl_operation_options_set_skip(options, m_skip);\n\n if (m_count != 0) {\n grl_operation_options_set_count(options, m_count);\n }\n\n int typeFilter = 0;\n foreach (const QVariant& var, m_typeFilter) {\n if (var.canConvert<int>()) {\n typeFilter |= var.toInt();\n }\n }\n\n grl_operation_options_set_type_filter(options, (GrlTypeFilter)typeFilter);\n\n return options;\n}\n\nGList *GriloDataSource::keysAsList() {\n \/\/ TODO: Check why using grl_metadata_key_list_new() produces a symbol error.\n GList *keys = NULL;\n\n foreach (const QVariant& var, m_metadataKeys) {\n if (var.canConvert<int>()) {\n keys = g_list_append(keys, GRLKEYID_TO_POINTER(var.toInt()));\n }\n }\n\n return keys;\n}\n\nvoid GriloDataSource::cancelRefresh() {\n if (m_opId != 0) {\n grl_operation_cancel(m_opId);\n m_opId = 0;\n }\n\n m_insertIndex = 0;\n m_updateScheduled = false;\n m_updateTimer.stop();\n}\n\nvoid GriloDataSource::grilo_source_result_cb(GrlSource *source, guint op_id,\n\t\t\t\t\t GrlMedia *media, guint remaining,\n\t\t\t\t\t gpointer user_data, const GError *error) {\n\n Q_UNUSED(source);\n\n \/\/ We get an error if the operation has been canceled:\n if (error) {\n if (error->domain != GRL_CORE_ERROR || error->code != GRL_CORE_ERROR_OPERATION_CANCELLED) {\n \/\/ TODO: error reporting?\n qCritical() << \"Operation failed\" << error->message;\n } else {\n \/\/ Cancelled operation notification. Nothing else to be done.\n return;\n }\n }\n\n GriloDataSource *that = static_cast<GriloDataSource *>(user_data);\n\n if (that->m_opId != op_id) {\n qWarning() << \"Got results belonging to an unknown browse id\";\n\n if (media) {\n g_object_unref(media);\n }\n\n return;\n }\n\n if (media) {\n that->addMedia(media);\n }\n\n if (remaining == 0) {\n emit that->finished();\n that->m_opId = 0;\n\n if (that->m_updateScheduled) {\n that->m_updateTimer.start(100, that);\n }\n\n \/\/ If there are items from a previous fetch still remaining remove them.\n if (that->m_insertIndex < that->m_media.count()) {\n foreach (GriloModel *model, that->m_models) {\n model->beginRemoveRows(QModelIndex(), that->m_insertIndex, that->m_media.count() - 1);\n }\n while (that->m_media.count() > that->m_insertIndex) {\n GriloMedia *media = that->m_media.takeLast();\n that->m_hash.remove(media->id());\n delete media;\n }\n foreach (GriloModel *model, that->m_models) {\n model->endRemoveRows();\n emit model->countChanged();\n }\n }\n }\n}\n\nvoid GriloDataSource::contentChanged(const QString &source, GrlSourceChangeType change_type,\n GPtrArray *changed_media)\n{\n Q_UNUSED(source);\n Q_UNUSED(change_type);\n Q_UNUSED(changed_media);\n}\n\nvoid GriloDataSource::updateContent(GrlSourceChangeType change_type, GPtrArray *changed_media)\n{\n switch (change_type) {\n case GRL_CONTENT_CHANGED:\n case GRL_CONTENT_ADDED:\n if (!m_updateScheduled) {\n m_updateScheduled = true;\n if (m_opId == 0) {\n m_updateTimer.start(100, this);\n }\n }\n break;\n case GRL_CONTENT_REMOVED:\n for (uint i = 0; i < changed_media->len; ++i) {\n removeMedia((GrlMedia *)g_ptr_array_index(changed_media, i));\n }\n break;\n default:\n break;\n }\n}\n\nQVariantList GriloDataSource::listToVariantList(const GList *keys) const {\n QVariantList varList;\n\n g_list_foreach(const_cast<GList *>(keys), fill_key_id, &varList);\n\n return varList;\n}\n\nvoid GriloDataSource::timerEvent(QTimerEvent *event) {\n if (event->timerId() == m_updateTimer.timerId()) {\n m_updateTimer.stop();\n emit contentUpdated();\n }\n}\n<|endoftext|>"} {"text":"<commit_before>#include <sys\/types.h>\n#include <sys\/errno.h>\n#include <sys\/uio.h>\n#include <fcntl.h>\n#include <limits.h>\n#include <stdint.h>\n#include <stdio.h>\n#include <unistd.h>\n\n#include <map>\n#include <vector>\n\n#include <common\/buffer.h>\n#include <common\/endian.h>\n\n#include <xcodec\/xcodec.h>\n\n#define\tXCDUMP_IOVEC_SIZE\t(IOV_MAX)\n\nstatic void dump(int, int);\nstatic bool fill(int, Buffer *);\nstatic void flush(int, Buffer *);\nstatic void process_files(int, char *[]);\nstatic void usage(void);\n\nint\nmain(int argc, char *argv[])\n{\n\tint ch;\n\n\twhile ((ch = getopt(argc, argv, \"?\")) != -1) {\n\t\tswitch (ch) {\n\t\tcase '?':\n\t\tdefault:\n\t\t\tusage();\n\t\t}\n\t}\n\targc -= optind;\n\targv += optind;\n\n\tprocess_files(argc, argv);\n\n\treturn (0);\n}\n\nstatic void\ndump(int ifd, int ofd)\n{\n\tBuffer input, output;\n\n\twhile (fill(ifd, &input)) {\n\t\tBufferSegment *seg;\n\t\tuint64_t hash;\n\t\tsize_t inlen;\n\t\tuint8_t ch;\n\n\t\tinlen = input.length();\n\t\twhile (inlen != 0) {\n\t\t\tch = input.peek();\n\n\t\t\twhile (!XCODEC_CHAR_SPECIAL(ch)) {\n\t\t\t\tinlen--;\n\t\t\t\tinput.skip(1);\n\t\t\t\toutput.append(\"<literal \/>\\n\");\n\n\t\t\t\tif (inlen == 0)\n\t\t\t\t\tbreak;\n\n\t\t\t\tch = input.peek();\n\t\t\t}\n\n\t\t\tASSERT(inlen == input.length());\n\n\t\t\tif (inlen == 0)\n\t\t\t\tbreak;\n\n\t\t\tswitch (ch) {\n\t\t\tcase XCODEC_HASHREF_CHAR:\n\t\t\t\tif (inlen < 9)\n\t\t\t\t\tbreak;\n\n\t\t\t\tinput.moveout((uint8_t *)&hash, 1, sizeof hash);\n\t\t\t\thash = LittleEndian::decode(hash);\n\n\t\t\t\toutput.append(\"<hash-reference \/>\\n\");\n\t\t\t\toutput.append(\"<window-declare \/>\\n\");\n\t\t\t\tinlen -= 9;\n\t\t\t\tcontinue;\n\n\t\t\tcase XCODEC_ESCAPE_CHAR:\n\t\t\t\tif (inlen < 2)\n\t\t\t\t\tbreak;\n\t\t\t\tinput.skip(1);\n\t\t\t\toutput.append(\"<escape \/>\\n\");\n\t\t\t\tinput.skip(1);\n\t\t\t\tinlen -= 2;\n\t\t\t\tcontinue;\n\n\t\t\tcase XCODEC_DECLARE_CHAR:\n\t\t\t\tif (inlen < 9 + XCODEC_SEGMENT_LENGTH)\n\t\t\t\t\tbreak;\n\n\t\t\t\tinput.moveout((uint8_t *)&hash, 1, sizeof hash);\n\t\t\t\thash = LittleEndian::decode(hash);\n\n\t\t\t\tinput.copyout(&seg, XCODEC_SEGMENT_LENGTH);\n\t\t\t\tinput.skip(XCODEC_SEGMENT_LENGTH);\n\n\t\t\t\toutput.append(\"<hash-declare \/>\\n\");\n\t\t\t\toutput.append(\"<window-declare \/>\\n\");\n\n\t\t\t\tseg->unref();\n\t\t\t\tinlen -= 9 + XCODEC_SEGMENT_LENGTH;\n\t\t\t\tcontinue;\n\n\t\t\tcase XCODEC_BACKREF_CHAR:\n\t\t\t\tif (inlen < 2)\n\t\t\t\t\tbreak;\n\t\t\t\tinput.skip(1);\n\t\t\t\tch = input.peek();\n\t\t\t\tinput.skip(1);\n\n\t\t\t\toutput.append(\"<window-reference \/>\\n\");\n\n\t\t\t\tinlen -= 2;\n\t\t\t\tcontinue;\n\n\t\t\tdefault:\n\t\t\t\tNOTREACHED();\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\n\t\tflush(ofd, &output);\n\t}\n\tASSERT(input.empty());\n\tASSERT(output.empty());\n}\n\nstatic bool\nfill(int fd, Buffer *input)\n{\n\tBufferSegment *segments[XCDUMP_IOVEC_SIZE];\n\tstruct iovec iov[XCDUMP_IOVEC_SIZE];\n\tBufferSegment *seg;\n\tssize_t len;\n\tunsigned i;\n\n\tfor (i = 0; i < XCDUMP_IOVEC_SIZE; i++) {\n\t\tseg = new BufferSegment();\n\t\tiov[i].iov_base = seg->head();\n\t\tiov[i].iov_len = BUFFER_SEGMENT_SIZE;\n\t\tsegments[i] = seg;\n\t}\n\n\tlen = readv(fd, iov, XCDUMP_IOVEC_SIZE);\n\tif (len == -1)\n\t\tHALT(\"\/fill\") << \"read failed.\";\n\tfor (i = 0; i < XCDUMP_IOVEC_SIZE; i++) {\n\t\tseg = segments[i];\n\t\tif (len > 0) {\n\t\t\tif (len > BUFFER_SEGMENT_SIZE) {\n\t\t\t\tseg->set_length(BUFFER_SEGMENT_SIZE);\n\t\t\t\tlen -= BUFFER_SEGMENT_SIZE;\n\t\t\t} else {\n\t\t\t\tseg->set_length((size_t)len);\n\t\t\t\tlen = 0;\n\t\t\t}\n\t\t\tinput->append(seg);\n\t\t}\n\t\tseg->unref();\n\t}\n\tif (input->empty())\n\t\treturn (false);\n\treturn (true);\n}\n\nstatic void\nflush(int fd, Buffer *output)\n{\n\tssize_t len;\n\n\tif (fd == -1) {\n\t\toutput->clear();\n\t\treturn;\n\t}\n\n\tfor (;;) {\n\t\tBuffer::SegmentIterator iter = output->segments();\n\t\tif (iter.end())\n\t\t\tbreak;\n\n\t\tconst BufferSegment *seg = *iter;\n\n\t\tlen = write(fd, seg->data(), seg->length());\n\t\tif (len != (ssize_t)seg->length())\n\t\t\tHALT(\"\/output\") << \"write failed.\";\n\t\toutput->skip((size_t)len);\n\t}\n\tASSERT(output->empty());\n}\n\nstatic void\nprocess_files(int argc, char *argv[])\n{\n\tint ifd, ofd;\n\n\tif (argc == 0) {\n\t\tifd = STDIN_FILENO;\n\t\tofd = STDOUT_FILENO;\n\n\t\tdump(ifd, ofd);\n\t} else {\n\t\twhile (argc--) {\n\t\t\tconst char *file = *argv++;\n\t\t\t\n\t\t\tifd = open(file, O_RDONLY);\n\t\t\tASSERT(ifd != -1);\n\t\t\tofd = STDOUT_FILENO;\n\n\t\t\tdump(ifd, ofd);\n\t\t}\n\t}\n}\n\nstatic void\nusage(void)\n{\n\tfprintf(stderr,\n\"usage: xcdump [file ...]\\n\");\n\texit(1);\n}\n<commit_msg>o) Add verbosity levels, at 1+, display hashes and single characters, at 2+, display hexdumps of entire segments in hash declarations.<commit_after>#include <sys\/types.h>\n#include <sys\/errno.h>\n#include <sys\/uio.h>\n#include <fcntl.h>\n#include <limits.h>\n#include <stdint.h>\n#include <stdio.h>\n#include <unistd.h>\n\n#include <map>\n#include <vector>\n\n#include <common\/buffer.h>\n#include <common\/endian.h>\n\n#include <xcodec\/xcodec.h>\n\n#define\tXCDUMP_IOVEC_SIZE\t(IOV_MAX)\n\nstatic int dump_verbosity;\n\nstatic void bhexdump(Buffer *, const uint8_t *, size_t);\nstatic void bprintf(Buffer *, const char *, ...);\nstatic void dump(int, int);\nstatic bool fill(int, Buffer *);\nstatic void flush(int, Buffer *);\nstatic void process_files(int, char *[]);\nstatic void usage(void);\n\nint\nmain(int argc, char *argv[])\n{\n\tint ch;\n\n\twhile ((ch = getopt(argc, argv, \"?v\")) != -1) {\n\t\tswitch (ch) {\n\t\tcase 'v':\n\t\t\tdump_verbosity++;\n\t\t\tbreak;\n\t\tcase '?':\n\t\tdefault:\n\t\t\tusage();\n\t\t}\n\t}\n\targc -= optind;\n\targv += optind;\n\n\tprocess_files(argc, argv);\n\n\treturn (0);\n}\n\nstatic void\nbhexdump(Buffer *output, const uint8_t *data, size_t len)\n{\n\twhile (len--)\n\t\tbprintf(output, \"%02x\", *data++);\n}\n\nstatic void\nbprintf(Buffer *output, const char *fmt, ...)\n{\n\tchar buf[65536];\n\tva_list ap;\n\n\tva_start(ap, fmt);\n\tvsnprintf(buf, sizeof buf, fmt, ap);\n\tva_end(ap);\n\n\toutput->append(std::string(buf));\n}\n\nstatic void\ndump(int ifd, int ofd)\n{\n\tBuffer input, output;\n\n\twhile (fill(ifd, &input)) {\n\t\tBufferSegment *seg;\n\t\tuint64_t hash;\n\t\tsize_t inlen;\n\t\tuint8_t ch;\n\n\t\tinlen = input.length();\n\t\twhile (inlen != 0) {\n\t\t\tch = input.peek();\n\n\t\t\twhile (!XCODEC_CHAR_SPECIAL(ch)) {\n\t\t\t\tinlen--;\n\t\t\t\tinput.skip(1);\n\t\t\t\tbprintf(&output, \"<literal\");\n\t\t\t\tif (dump_verbosity > 0)\n\t\t\t\t\tbprintf(&output, \" character=\\\"0x%02x\\\"\", ch);\n\t\t\t\tbprintf(&output, \"\/>\\n\");\n\n\t\t\t\tif (inlen == 0)\n\t\t\t\t\tbreak;\n\n\t\t\t\tch = input.peek();\n\t\t\t}\n\n\t\t\tASSERT(inlen == input.length());\n\n\t\t\tif (inlen == 0)\n\t\t\t\tbreak;\n\n\t\t\tswitch (ch) {\n\t\t\tcase XCODEC_HASHREF_CHAR:\n\t\t\t\tif (inlen < 9)\n\t\t\t\t\tbreak;\n\n\t\t\t\tinput.moveout((uint8_t *)&hash, 1, sizeof hash);\n\t\t\t\thash = LittleEndian::decode(hash);\n\n\t\t\t\tbprintf(&output, \"<hash-reference\");\n\t\t\t\tif (dump_verbosity > 0)\n\t\t\t\t\tbprintf(&output, \" hash=\\\"0x%016jx\\\"\", (uintmax_t)hash);\n\t\t\t\tbprintf(&output, \"\/>\\n\");\n\t\t\t\tinlen -= 9;\n\t\t\t\tcontinue;\n\n\t\t\tcase XCODEC_ESCAPE_CHAR:\n\t\t\t\tif (inlen < 2)\n\t\t\t\t\tbreak;\n\t\t\t\tinput.skip(1);\n\t\t\t\tch = input.peek();\n\t\t\t\tbprintf(&output, \"<escape\");\n\t\t\t\tif (dump_verbosity > 0)\n\t\t\t\t\tbprintf(&output, \" character=\\\"0x%02x\\\"\", ch);\n\t\t\t\tbprintf(&output, \"\/>\\n\");\n\t\t\t\tinput.skip(1);\n\t\t\t\tinlen -= 2;\n\t\t\t\tcontinue;\n\n\t\t\tcase XCODEC_DECLARE_CHAR:\n\t\t\t\tif (inlen < 9 + XCODEC_SEGMENT_LENGTH)\n\t\t\t\t\tbreak;\n\n\t\t\t\tinput.moveout((uint8_t *)&hash, 1, sizeof hash);\n\t\t\t\thash = LittleEndian::decode(hash);\n\n\t\t\t\tinput.copyout(&seg, XCODEC_SEGMENT_LENGTH);\n\t\t\t\tinput.skip(XCODEC_SEGMENT_LENGTH);\n\n\t\t\t\tbprintf(&output, \"<hash-declare\");\n\t\t\t\tif (dump_verbosity > 0) {\n\t\t\t\t\tbprintf(&output, \" hash=\\\"0x%016jx\\\"\", (uintmax_t)hash);\n\t\t\t\t\tif (dump_verbosity > 1) {\n\t\t\t\t\t\tbprintf(&output, \" data=\\\"\");\n\t\t\t\t\t\tbhexdump(&output, seg->data(), seg->length());\n\t\t\t\t\t\tbprintf(&output, \"\\\"\");\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbprintf(&output, \"\/>\\n\");\n\n\t\t\t\tseg->unref();\n\t\t\t\tinlen -= 9 + XCODEC_SEGMENT_LENGTH;\n\t\t\t\tcontinue;\n\n\t\t\tcase XCODEC_BACKREF_CHAR:\n\t\t\t\tif (inlen < 2)\n\t\t\t\t\tbreak;\n\t\t\t\tinput.skip(1);\n\t\t\t\tch = input.peek();\n\t\t\t\tinput.skip(1);\n\n\t\t\t\tbprintf(&output, \"<back-reference\");\n\t\t\t\tif (dump_verbosity > 0)\n\t\t\t\t\tbprintf(&output, \" offset=\\\"%u\\\"\", ch);\n\t\t\t\tbprintf(&output, \"\/>\\n\");\n\n\t\t\t\tinlen -= 2;\n\t\t\t\tcontinue;\n\n\t\t\tdefault:\n\t\t\t\tNOTREACHED();\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\n\t\tflush(ofd, &output);\n\t}\n\tASSERT(input.empty());\n\tASSERT(output.empty());\n}\n\nstatic bool\nfill(int fd, Buffer *input)\n{\n\tBufferSegment *segments[XCDUMP_IOVEC_SIZE];\n\tstruct iovec iov[XCDUMP_IOVEC_SIZE];\n\tBufferSegment *seg;\n\tssize_t len;\n\tunsigned i;\n\n\tfor (i = 0; i < XCDUMP_IOVEC_SIZE; i++) {\n\t\tseg = new BufferSegment();\n\t\tiov[i].iov_base = seg->head();\n\t\tiov[i].iov_len = BUFFER_SEGMENT_SIZE;\n\t\tsegments[i] = seg;\n\t}\n\n\tlen = readv(fd, iov, XCDUMP_IOVEC_SIZE);\n\tif (len == -1)\n\t\tHALT(\"\/fill\") << \"read failed.\";\n\tfor (i = 0; i < XCDUMP_IOVEC_SIZE; i++) {\n\t\tseg = segments[i];\n\t\tif (len > 0) {\n\t\t\tif (len > BUFFER_SEGMENT_SIZE) {\n\t\t\t\tseg->set_length(BUFFER_SEGMENT_SIZE);\n\t\t\t\tlen -= BUFFER_SEGMENT_SIZE;\n\t\t\t} else {\n\t\t\t\tseg->set_length((size_t)len);\n\t\t\t\tlen = 0;\n\t\t\t}\n\t\t\tinput->append(seg);\n\t\t}\n\t\tseg->unref();\n\t}\n\tif (input->empty())\n\t\treturn (false);\n\treturn (true);\n}\n\nstatic void\nflush(int fd, Buffer *output)\n{\n\tssize_t len;\n\n\tif (fd == -1) {\n\t\toutput->clear();\n\t\treturn;\n\t}\n\n\tfor (;;) {\n\t\tBuffer::SegmentIterator iter = output->segments();\n\t\tif (iter.end())\n\t\t\tbreak;\n\n\t\tconst BufferSegment *seg = *iter;\n\n\t\tlen = write(fd, seg->data(), seg->length());\n\t\tif (len != (ssize_t)seg->length())\n\t\t\tHALT(\"\/output\") << \"write failed.\";\n\t\toutput->skip((size_t)len);\n\t}\n\tASSERT(output->empty());\n}\n\nstatic void\nprocess_files(int argc, char *argv[])\n{\n\tint ifd, ofd;\n\n\tif (argc == 0) {\n\t\tifd = STDIN_FILENO;\n\t\tofd = STDOUT_FILENO;\n\n\t\tdump(ifd, ofd);\n\t} else {\n\t\twhile (argc--) {\n\t\t\tconst char *file = *argv++;\n\t\t\t\n\t\t\tifd = open(file, O_RDONLY);\n\t\t\tASSERT(ifd != -1);\n\t\t\tofd = STDOUT_FILENO;\n\n\t\t\tdump(ifd, ofd);\n\t\t}\n\t}\n}\n\nstatic void\nusage(void)\n{\n\tfprintf(stderr,\n\"usage: xcdump [-v] [file ...]\\n\");\n\texit(1);\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ Copyright (c) 2017 The Khronos Group Inc.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/\n#include \"..\/testBase.h\"\n#include \"..\/common.h\"\n\nextern int gTypesToTest;\nextern bool gTestReadWrite;\n\nextern int test_read_image_set_1D( cl_device_id device, cl_context context, cl_command_queue queue, cl_image_format *format, image_sampler_data *imageSampler, ExplicitType outputType );\nextern int test_read_image_set_1D_buffer( cl_device_id device, cl_context context, cl_command_queue queue, cl_image_format *format, image_sampler_data *imageSampler, ExplicitType outputType );\nextern int test_read_image_set_2D( cl_device_id device, cl_context context, cl_command_queue queue, cl_image_format *format, image_sampler_data *imageSampler, ExplicitType outputType );\nextern int test_read_image_set_3D( cl_device_id device, cl_context context, cl_command_queue queue, cl_image_format *format, image_sampler_data *imageSampler, ExplicitType outputType );\nextern int test_read_image_set_1D_array( cl_device_id device, cl_context context, cl_command_queue queue, cl_image_format *format, image_sampler_data *imageSampler, ExplicitType outputType );\nextern int test_read_image_set_2D_array( cl_device_id device, cl_context context, cl_command_queue queue, cl_image_format *format, image_sampler_data *imageSampler, ExplicitType outputType );\n\nint test_read_image_type( cl_device_id device, cl_context context, cl_command_queue queue, cl_image_format *format,\n image_sampler_data *imageSampler, ExplicitType outputType, cl_mem_object_type imageType )\n{\n int ret = 0;\n imageSampler->addressing_mode = CL_ADDRESS_NONE;\n\n print_read_header( format, imageSampler, false );\n\n gTestCount++;\n\n switch (imageType)\n {\n case CL_MEM_OBJECT_IMAGE1D:\n ret = test_read_image_set_1D( device, context, queue, format, imageSampler, outputType );\n break;\n case CL_MEM_OBJECT_IMAGE1D_BUFFER:\n ret += test_read_image_set_1D_buffer( device, context, queue, format, imageSampler, outputType );\n break;\n case CL_MEM_OBJECT_IMAGE2D:\n ret = test_read_image_set_2D( device, context, queue, format, imageSampler, outputType );\n break;\n case CL_MEM_OBJECT_IMAGE3D:\n ret = test_read_image_set_3D( device, context, queue, format, imageSampler, outputType );\n break;\n case CL_MEM_OBJECT_IMAGE1D_ARRAY:\n ret = test_read_image_set_1D_array( device, context, queue, format, imageSampler, outputType );\n break;\n case CL_MEM_OBJECT_IMAGE2D_ARRAY:\n ret = test_read_image_set_2D_array( device, context, queue, format, imageSampler, outputType );\n break;\n }\n\n if ( ret != 0 )\n {\n gFailCount++;\n log_error( \"FAILED: \" );\n print_read_header( format, imageSampler, true );\n log_info( \"\\n\" );\n }\n return ret;\n}\n\nint test_read_image_formats( cl_device_id device, cl_context context, cl_command_queue queue, cl_image_format *formatList, bool *filterFlags, unsigned int numFormats,\n image_sampler_data *imageSampler, ExplicitType outputType, cl_mem_object_type imageType )\n{\n int ret = 0;\n imageSampler->normalized_coords = false;\n log_info( \"read_image (%s coords, %s results) *****************************\\n\",\n \"integer\", get_explicit_type_name( outputType ) );\n\n for ( unsigned int i = 0; i < numFormats; i++ )\n {\n if ( filterFlags[i] )\n continue;\n\n cl_image_format &imageFormat = formatList[ i ];\n\n ret |= test_read_image_type( device, context, queue, &imageFormat, imageSampler, outputType, imageType );\n }\n return ret;\n}\n\n\nint test_image_set( cl_device_id device, cl_context context, cl_command_queue queue, cl_mem_object_type imageType )\n{\n int ret = 0;\n static int printedFormatList = -1;\n\n \/\/ Grab the list of supported image formats\n cl_image_format *formatList;\n bool *filterFlags;\n unsigned int numFormats;\n\n if (gTestReadWrite && checkForReadWriteImageSupport(device))\n {\n return TEST_SKIPPED_ITSELF;\n }\n\n \/\/ This flag is only for querying the list of supported formats\n \/\/ The flag for creating image will be set explicitly in test functions\n cl_mem_flags flags = (gTestReadWrite)? CL_MEM_KERNEL_READ_AND_WRITE : CL_MEM_READ_ONLY;\n\n if ( get_format_list( context, imageType, formatList, numFormats, flags ) )\n return -1;\n\n filterFlags = new bool[ numFormats ];\n if ( filterFlags == NULL )\n {\n log_error( \"ERROR: Out of memory allocating filter flags list!\\n\" );\n return -1;\n }\n memset( filterFlags, 0, sizeof( bool ) * numFormats );\n\n \/\/ First time through, we'll go ahead and print the formats supported, regardless of type\n if ( printedFormatList != (int)imageType )\n {\n log_info( \"---- Supported %s read formats for this device ---- \\n\", convert_image_type_to_string(imageType) );\n for ( unsigned int f = 0; f < numFormats; f++ )\n log_info( \" %-7s %-24s %d\\n\", GetChannelOrderName( formatList[ f ].image_channel_order ),\n GetChannelTypeName( formatList[ f ].image_channel_data_type ),\n (int)get_format_channel_count( &formatList[ f ] ) );\n log_info( \"------------------------------------------- \\n\" );\n printedFormatList = imageType;\n }\n\n image_sampler_data imageSampler;\n\n for (auto test : imageTestTypes)\n {\n if (gTypesToTest & test.type)\n {\n if (filter_formats(formatList, filterFlags, numFormats,\n test.channelTypes)\n == 0)\n {\n log_info(\"No formats supported for %s type\\n\", test.name);\n }\n else\n {\n imageSampler.filter_mode = CL_FILTER_NEAREST;\n ret += test_read_image_formats(\n device, context, queue, formatList, filterFlags, numFormats,\n &imageSampler, test.explicitType, imageType);\n }\n }\n }\n\n delete[] filterFlags;\n delete[] formatList;\n\n return ret;\n}\n<commit_msg>Fix samplerlessReads read_write (#329) (#1016)<commit_after>\/\/\n\/\/ Copyright (c) 2017 The Khronos Group Inc.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/\n#include \"..\/testBase.h\"\n#include \"..\/common.h\"\n\nextern int gTypesToTest;\nextern bool gTestReadWrite;\n\nextern int test_read_image_set_1D( cl_device_id device, cl_context context, cl_command_queue queue, cl_image_format *format, image_sampler_data *imageSampler, ExplicitType outputType );\nextern int test_read_image_set_1D_buffer( cl_device_id device, cl_context context, cl_command_queue queue, cl_image_format *format, image_sampler_data *imageSampler, ExplicitType outputType );\nextern int test_read_image_set_2D( cl_device_id device, cl_context context, cl_command_queue queue, cl_image_format *format, image_sampler_data *imageSampler, ExplicitType outputType );\nextern int test_read_image_set_3D( cl_device_id device, cl_context context, cl_command_queue queue, cl_image_format *format, image_sampler_data *imageSampler, ExplicitType outputType );\nextern int test_read_image_set_1D_array( cl_device_id device, cl_context context, cl_command_queue queue, cl_image_format *format, image_sampler_data *imageSampler, ExplicitType outputType );\nextern int test_read_image_set_2D_array( cl_device_id device, cl_context context, cl_command_queue queue, cl_image_format *format, image_sampler_data *imageSampler, ExplicitType outputType );\n\nint test_read_image_type( cl_device_id device, cl_context context, cl_command_queue queue, cl_image_format *format,\n image_sampler_data *imageSampler, ExplicitType outputType, cl_mem_object_type imageType )\n{\n int ret = 0;\n imageSampler->addressing_mode = CL_ADDRESS_NONE;\n\n print_read_header( format, imageSampler, false );\n\n gTestCount++;\n\n switch (imageType)\n {\n case CL_MEM_OBJECT_IMAGE1D:\n ret = test_read_image_set_1D( device, context, queue, format, imageSampler, outputType );\n break;\n case CL_MEM_OBJECT_IMAGE1D_BUFFER:\n ret += test_read_image_set_1D_buffer( device, context, queue, format, imageSampler, outputType );\n break;\n case CL_MEM_OBJECT_IMAGE2D:\n ret = test_read_image_set_2D( device, context, queue, format, imageSampler, outputType );\n break;\n case CL_MEM_OBJECT_IMAGE3D:\n ret = test_read_image_set_3D( device, context, queue, format, imageSampler, outputType );\n break;\n case CL_MEM_OBJECT_IMAGE1D_ARRAY:\n ret = test_read_image_set_1D_array( device, context, queue, format, imageSampler, outputType );\n break;\n case CL_MEM_OBJECT_IMAGE2D_ARRAY:\n ret = test_read_image_set_2D_array( device, context, queue, format, imageSampler, outputType );\n break;\n }\n\n if ( ret != 0 )\n {\n gFailCount++;\n log_error( \"FAILED: \" );\n print_read_header( format, imageSampler, true );\n log_info( \"\\n\" );\n }\n return ret;\n}\n\nint test_read_image_formats( cl_device_id device, cl_context context, cl_command_queue queue, cl_image_format *formatList, bool *filterFlags, unsigned int numFormats,\n image_sampler_data *imageSampler, ExplicitType outputType, cl_mem_object_type imageType )\n{\n int ret = 0;\n imageSampler->normalized_coords = false;\n log_info( \"read_image (%s coords, %s results) *****************************\\n\",\n \"integer\", get_explicit_type_name( outputType ) );\n\n for ( unsigned int i = 0; i < numFormats; i++ )\n {\n if ( filterFlags[i] )\n continue;\n\n cl_image_format &imageFormat = formatList[ i ];\n\n ret |= test_read_image_type( device, context, queue, &imageFormat, imageSampler, outputType, imageType );\n }\n return ret;\n}\n\n\nint test_image_set( cl_device_id device, cl_context context, cl_command_queue queue, cl_mem_object_type imageType )\n{\n int ret = 0;\n static int printedFormatList = -1;\n\n \/\/ Grab the list of supported image formats\n cl_image_format *formatList;\n unsigned int numFormats;\n\n if (gTestReadWrite && checkForReadWriteImageSupport(device))\n {\n return TEST_SKIPPED_ITSELF;\n }\n\n cl_image_format *readOnlyFormats;\n unsigned int numReadOnlyFormats;\n\n if (get_format_list(context, imageType, readOnlyFormats, numReadOnlyFormats,\n CL_MEM_READ_ONLY))\n return -1;\n\n if (gTestReadWrite)\n {\n cl_image_format *readWriteFormats;\n unsigned int numReadWriteFormats;\n\n if (get_format_list(context, imageType, readWriteFormats,\n numReadWriteFormats, CL_MEM_KERNEL_READ_AND_WRITE))\n return -1;\n\n numFormats = numReadOnlyFormats;\n formatList = new cl_image_format[numFormats];\n unsigned int k = 0;\n\n \/\/ Keep only intersecting formats with read only and read write flags\n for (unsigned int i = 0; i < numReadOnlyFormats; i++)\n {\n for (unsigned int j = 0; j < numReadWriteFormats; j++)\n {\n if (readOnlyFormats[i].image_channel_data_type\n == readWriteFormats[j].image_channel_data_type\n && readOnlyFormats[i].image_channel_order\n == readWriteFormats[j].image_channel_order)\n {\n formatList[k].image_channel_data_type =\n readOnlyFormats[i].image_channel_data_type;\n formatList[k].image_channel_order =\n readOnlyFormats[i].image_channel_order;\n k++;\n break;\n }\n }\n }\n\n numFormats = k;\n\n delete[] readOnlyFormats;\n delete[] readWriteFormats;\n }\n else\n {\n numFormats = numReadOnlyFormats;\n formatList = readOnlyFormats;\n }\n\n bool *filterFlags = new bool[numFormats];\n if ( filterFlags == NULL )\n {\n log_error( \"ERROR: Out of memory allocating filter flags list!\\n\" );\n return -1;\n }\n memset( filterFlags, 0, sizeof( bool ) * numFormats );\n\n \/\/ First time through, we'll go ahead and print the formats supported, regardless of type\n if ( printedFormatList != (int)imageType )\n {\n log_info( \"---- Supported %s read formats for this device ---- \\n\", convert_image_type_to_string(imageType) );\n for ( unsigned int f = 0; f < numFormats; f++ )\n log_info( \" %-7s %-24s %d\\n\", GetChannelOrderName( formatList[ f ].image_channel_order ),\n GetChannelTypeName( formatList[ f ].image_channel_data_type ),\n (int)get_format_channel_count( &formatList[ f ] ) );\n log_info( \"------------------------------------------- \\n\" );\n printedFormatList = imageType;\n }\n\n image_sampler_data imageSampler;\n\n for (auto test : imageTestTypes)\n {\n if (gTypesToTest & test.type)\n {\n if (filter_formats(formatList, filterFlags, numFormats,\n test.channelTypes)\n == 0)\n {\n log_info(\"No formats supported for %s type\\n\", test.name);\n }\n else\n {\n imageSampler.filter_mode = CL_FILTER_NEAREST;\n ret += test_read_image_formats(\n device, context, queue, formatList, filterFlags, numFormats,\n &imageSampler, test.explicitType, imageType);\n }\n }\n }\n\n delete[] filterFlags;\n delete[] formatList;\n\n return ret;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Copyright (c) 2004-2019 musikcube team\n\/\/\n\/\/ All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright notice,\n\/\/ this list of conditions and the following disclaimer.\n\/\/\n\/\/ * Redistributions in binary form must reproduce the above copyright\n\/\/ notice, this list of conditions and the following disclaimer in the\n\/\/ documentation and\/or other materials provided with the distribution.\n\/\/\n\/\/ * Neither the name of the author nor the names of other contributors may\n\/\/ be used to endorse or promote products derived from this software\n\/\/ without specific prior written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n\/\/ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\/\/ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\/\/ ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\n\/\/ LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n\/\/ CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n\/\/ SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n\/\/ INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n\/\/ CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n\/\/ ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n\/\/ POSSIBILITY OF SUCH DAMAGE.\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"pch.hpp\"\n#include <core\/support\/Common.h>\n#include <core\/config.h>\n#include <utf8\/utf8.h>\n#include <cstdlib>\n#include <iostream>\n#include <fstream>\n#include <functional>\n#include <vector>\n#include <string>\n#include <cctype>\n#include <algorithm>\n\n#ifdef WIN32\n #include <shellapi.h>\n#elif __APPLE__\n #include <mach-o\/dyld.h>\n#else\n #include <sys\/types.h>\n #include <unistd.h>\n #include <sys\/stat.h>\n #include <limits.h>\n#endif\n\n\/\/ given the #ifdef\/#else above, the following is not required.\n\/\/ Nor it is the #if FreeBSD below. \n#ifdef __OpenBSD__\n\t#include <sys\/types.h>\n\t#include <sys\/sysctl.h>\n\t#include <unistd.h>\n\t#include <limits.h>\n#endif\n\n#ifdef __FreeBSD__\n #include <sys\/types.h>\n #include <sys\/sysctl.h>\n#endif\n\nstatic std::string GetHomeDirectory() {\n std::string directory;\n\n#ifdef WIN32\n DWORD bufferSize = GetEnvironmentVariable(L\"APPDATA\", 0, 0);\n wchar_t *buffer = new wchar_t[bufferSize + 2];\n GetEnvironmentVariable(L\"APPDATA\", buffer, bufferSize);\n directory.assign(u16to8(buffer));\n delete[] buffer;\n#else\n directory = std::string(std::getenv(\"HOME\"));\n#endif\n\n return directory;\n}\n\nstatic std::string getDataDirectoryRoot() {\n#ifdef WIN32\n return GetHomeDirectory();\n#else\n return GetHomeDirectory() + \"\/.config\";\n#endif\n}\n\nstatic inline void silentDelete(const std::string fn) {\n boost::system::error_code ec;\n boost::filesystem::remove(boost::filesystem::path(fn), ec);\n}\n\nnamespace musik { namespace core {\n\n std::string GetPluginDirectory() {\n std::string path(GetApplicationDirectory());\n path.append(\"\/plugins\/\");\n return path;\n }\n\n std::string GetApplicationDirectory() {\n std::string result;\n\n #ifdef WIN32\n wchar_t widePath[2048];\n int length = GetModuleFileName(NULL, widePath, 2048);\n if (length != 0 && length < 2048) {\n result.assign(GetPath(u16to8(widePath).c_str()));\n }\n #elif __APPLE__\n char pathbuf[PATH_MAX + 1];\n uint32_t bufsize = sizeof(pathbuf);\n _NSGetExecutablePath(pathbuf, &bufsize);\n result.assign(pathbuf);\n size_t last = result.find_last_of(\"\/\");\n result = result.substr(0, last); \/* remove filename component *\/\n #else\n char pathbuf[PATH_MAX + 1] = { 0 };\n\n #ifdef __FreeBSD__\n int mib[4];\n mib[0] = CTL_KERN;\n mib[1] = KERN_PROC;\n mib[2] = KERN_PROC_PATHNAME;\n mib[3] = -1;\n size_t bufsize = sizeof(pathbuf);\n sysctl(mib, 4, pathbuf, &bufsize, nullptr, 0);\n #elif defined __OpenBSD__\n\t\t\t int mib[4];\n\t\t\t char **argv;\n\t\t\t size_t len = ARG_MAX;\n\n\t\t\t mib[0] = CTL_KERN;\n\t\t\t mib[1] = KERN_PROC_ARGS;\n\t\t\t mib[2] = getpid();\n\t\t\t mib[3] = KERN_PROC_ARGV;\n\n\t\t\t argv = new char*[len];\n\t\t\t if (sysctl(mib, 4, argv, &len, nullptr, 0) < 0) abort();\n\n\t\t\t boost::filesystem::path command = boost::filesystem::system_complete(argv[0]);\n\t\t\t realpath(command.c_str(), pathbuf);\n\t\t\t delete[] argv;\n\t #endif\n\n result.assign(pathbuf);\n size_t last = result.find_last_of(\"\/\");\n result = result.substr(0, last); \/* remove filename component *\/\n #endif\n\n return result;\n }\n\n std::string GetHomeDirectory() {\n std::string directory;\n\n #ifdef WIN32\n DWORD bufferSize = GetEnvironmentVariable(L\"USERPROFILE\", 0, 0);\n wchar_t *buffer = new wchar_t[bufferSize + 2];\n GetEnvironmentVariable(L\"USERPROFILE\", buffer, bufferSize);\n directory.assign(u16to8(buffer));\n delete[] buffer;\n #else\n directory = std::string(std::getenv(\"HOME\"));\n #endif\n\n return directory;\n }\n\n std::string GetDataDirectory(bool create) {\n std::string directory = getDataDirectoryRoot() + std::string(\"\/musikcube\/\");\n\n if (create) {\n try {\n boost::filesystem::path path(directory);\n if (!boost::filesystem::exists(path)) {\n boost::filesystem::create_directories(path);\n }\n }\n catch (...) {\n \/* ugh, fixme *\/\n }\n }\n\n return directory;\n }\n\n std::string GetPath(const std::string &sFile) {\n std::string sPath;\n int length;\n\n #ifdef WIN32\n wchar_t widePath[2048];\n wchar_t *szFile = NULL;\n\n length = GetFullPathName(u8to16(sFile).c_str(), 2048, widePath, &szFile);\n if(length != 0 && length < 2048) {\n sPath.assign(u16to8(widePath).c_str());\n if(szFile!=0) {\n std::string sTheFile = u16to8(szFile);\n sPath.assign(sPath.substr(0,length-sTheFile.length()));\n }\n }\n else {\n sPath.assign(sFile);\n }\n #else\n char* szDir;\n sPath.assign(getcwd((char*)szDir, (size_t) length));\n #endif\n\n return sPath;\n }\n\n int64_t Checksum(char *data,unsigned int bytes) {\n int64_t sum = 0;\n for(unsigned int i = 0; i < bytes; ++i) {\n char ch = *(data + i);\n sum += (int64_t) ch;\n }\n return sum;\n }\n\n size_t CopyString(const std::string& src, char* dst, size_t size) {\n size_t len = src.size() + 1; \/* space for the null terminator *\/\n if (dst) {\n size_t copied = src.copy(dst, size - 1);\n dst[copied] = '\\0';\n return copied + 1;\n }\n return len;\n }\n\n bool FileToByteArray(const std::string& path, char** target, int& size, bool nullTerminate) {\n #ifdef WIN32\n std::wstring u16fn = u8to16(path);\n FILE* file = _wfopen(u16fn.c_str(), L\"rb\");\n #else\n FILE* file = fopen(path.c_str(), \"rb\");\n #endif\n\n *target = nullptr;\n size = 0;\n\n if (!file) {\n return false;\n }\n\n bool success = false;\n\n if (fseek(file, 0L, SEEK_END) == 0) {\n long fileSize = ftell(file);\n if (fileSize == -1) {\n goto close_and_return;\n }\n\n if (fseek(file, 0L, SEEK_SET) != 0) {\n goto close_and_return;\n }\n\n *target = (char*)malloc(sizeof(char) * (fileSize + (nullTerminate ? 1 : 0)));\n size = fread(*target, sizeof(char), fileSize, file);\n\n if (size == fileSize) {\n if (nullTerminate) {\n (*target)[size] = 0;\n }\n\n success = true;\n }\n }\n\n close_and_return:\n fclose(file);\n\n if (!success) {\n free(*target);\n }\n\n return success;\n }\n\n std::string NormalizeDir(std::string path) {\n path = boost::filesystem::path(path).make_preferred().string();\n\n std::string sep(1, boost::filesystem::path::preferred_separator);\n if (path.size() && path.substr(path.size() - 1, 1) != sep) {\n path += sep;\n }\n\n return path;\n }\n\n void ReplaceAll(std::string& input, const std::string& find, const std::string& replace) {\n size_t pos = input.find(find);\n while (pos != std::string::npos) {\n input.replace(pos, find.size(), replace);\n pos = input.find(find, pos + replace.size());\n }\n }\n\n std::string Trim(const std::string& str) {\n std::string s(str);\n s.erase(s.begin(), std::find_if(s.begin(), s.end(),\n std::not1(std::ptr_fun<int, int>(std::isspace))));\n s.erase(std::find_if(s.rbegin(), s.rend(),\n std::not1(std::ptr_fun<int, int>(std::isspace))).base(), s.end());\n return s;\n }\n\n std::vector<std::string> Split(\n const std::string& in, const std::string& delim)\n {\n std::vector<std::string> result;\n size_t last = 0, next = 0;\n while ((next = in.find(delim, last)) != std::string::npos) {\n result.push_back(std::move(Trim(in.substr(last, next - last))));\n last = next + 1;\n }\n result.push_back(std::move(Trim(in.substr(last))));\n return result;\n }\n\n void OpenFile(const std::string& path) {\n #ifdef WIN32\n ShellExecuteA(nullptr, nullptr, path.c_str(), nullptr, nullptr, SW_SHOWNORMAL);\n #elif __APPLE__\n std::string command = \"open '\" + path + \"' > \/dev\/null 2> \/dev\/null\";\n system(command.c_str());\n #else\n std::string command = \"xdg-open '\" + path + \"' > \/dev\/null 2> \/dev\/null\";\n system(command.c_str());\n #endif\n }\n\n bool CopyFile(const std::string& from, const std::string& to) {\n if (from.size() && to.size() && from != to) {\n std::ifstream in(from);\n if (in.is_open()) {\n std::ofstream out(to);\n if (out.is_open()) {\n out << in.rdbuf();\n return true;\n }\n }\n }\n return false;\n }\n\n} }\n<commit_msg>restore accidentally removed Linux #ifdef case<commit_after>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Copyright (c) 2004-2019 musikcube team\n\/\/\n\/\/ All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright notice,\n\/\/ this list of conditions and the following disclaimer.\n\/\/\n\/\/ * Redistributions in binary form must reproduce the above copyright\n\/\/ notice, this list of conditions and the following disclaimer in the\n\/\/ documentation and\/or other materials provided with the distribution.\n\/\/\n\/\/ * Neither the name of the author nor the names of other contributors may\n\/\/ be used to endorse or promote products derived from this software\n\/\/ without specific prior written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n\/\/ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\/\/ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\/\/ ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\n\/\/ LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n\/\/ CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n\/\/ SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n\/\/ INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n\/\/ CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n\/\/ ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n\/\/ POSSIBILITY OF SUCH DAMAGE.\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"pch.hpp\"\n#include <core\/support\/Common.h>\n#include <core\/config.h>\n#include <utf8\/utf8.h>\n#include <cstdlib>\n#include <iostream>\n#include <fstream>\n#include <functional>\n#include <vector>\n#include <string>\n#include <cctype>\n#include <algorithm>\n\n#ifdef WIN32\n #include <shellapi.h>\n#elif __APPLE__\n #include <mach-o\/dyld.h>\n#else\n #include <sys\/types.h>\n #include <unistd.h>\n #include <sys\/stat.h>\n #include <limits.h>\n#endif\n\n\/\/ given the #ifdef\/#else above, the following is not required.\n\/\/ Nor it is the #if FreeBSD below. \n#ifdef __OpenBSD__\n\t#include <sys\/types.h>\n\t#include <sys\/sysctl.h>\n\t#include <unistd.h>\n\t#include <limits.h>\n#endif\n\n#ifdef __FreeBSD__\n #include <sys\/types.h>\n #include <sys\/sysctl.h>\n#endif\n\nstatic std::string GetHomeDirectory() {\n std::string directory;\n\n#ifdef WIN32\n DWORD bufferSize = GetEnvironmentVariable(L\"APPDATA\", 0, 0);\n wchar_t *buffer = new wchar_t[bufferSize + 2];\n GetEnvironmentVariable(L\"APPDATA\", buffer, bufferSize);\n directory.assign(u16to8(buffer));\n delete[] buffer;\n#else\n directory = std::string(std::getenv(\"HOME\"));\n#endif\n\n return directory;\n}\n\nstatic std::string getDataDirectoryRoot() {\n#ifdef WIN32\n return GetHomeDirectory();\n#else\n return GetHomeDirectory() + \"\/.config\";\n#endif\n}\n\nstatic inline void silentDelete(const std::string fn) {\n boost::system::error_code ec;\n boost::filesystem::remove(boost::filesystem::path(fn), ec);\n}\n\nnamespace musik { namespace core {\n\n std::string GetPluginDirectory() {\n std::string path(GetApplicationDirectory());\n path.append(\"\/plugins\/\");\n return path;\n }\n\n std::string GetApplicationDirectory() {\n std::string result;\n\n #ifdef WIN32\n wchar_t widePath[2048];\n int length = GetModuleFileName(NULL, widePath, 2048);\n if (length != 0 && length < 2048) {\n result.assign(GetPath(u16to8(widePath).c_str()));\n }\n #elif __APPLE__\n char pathbuf[PATH_MAX + 1];\n uint32_t bufsize = sizeof(pathbuf);\n _NSGetExecutablePath(pathbuf, &bufsize);\n result.assign(pathbuf);\n size_t last = result.find_last_of(\"\/\");\n result = result.substr(0, last); \/* remove filename component *\/\n #else\n char pathbuf[PATH_MAX + 1] = { 0 };\n\n #ifdef __FreeBSD__\n int mib[4];\n mib[0] = CTL_KERN;\n mib[1] = KERN_PROC;\n mib[2] = KERN_PROC_PATHNAME;\n mib[3] = -1;\n size_t bufsize = sizeof(pathbuf);\n sysctl(mib, 4, pathbuf, &bufsize, nullptr, 0);\n #elif defined __OpenBSD__\n\t\t\t int mib[4];\n\t\t\t char **argv;\n\t\t\t size_t len = ARG_MAX;\n\n\t\t\t mib[0] = CTL_KERN;\n\t\t\t mib[1] = KERN_PROC_ARGS;\n\t\t\t mib[2] = getpid();\n\t\t\t mib[3] = KERN_PROC_ARGV;\n\n\t\t\t argv = new char*[len];\n\t\t\t if (sysctl(mib, 4, argv, &len, nullptr, 0) < 0) abort();\n\n\t\t\t boost::filesystem::path command = boost::filesystem::system_complete(argv[0]);\n\t\t\t realpath(command.c_str(), pathbuf);\n\t\t\t delete[] argv;\n #else\n std::string pathToProc = u8fmt(\"\/proc\/%d\/exe\", (int) getpid());\n readlink(pathToProc.c_str(), pathbuf, PATH_MAX);\n\t #endif\n\n result.assign(pathbuf);\n size_t last = result.find_last_of(\"\/\");\n result = result.substr(0, last); \/* remove filename component *\/\n #endif\n\n return result;\n }\n\n std::string GetHomeDirectory() {\n std::string directory;\n\n #ifdef WIN32\n DWORD bufferSize = GetEnvironmentVariable(L\"USERPROFILE\", 0, 0);\n wchar_t *buffer = new wchar_t[bufferSize + 2];\n GetEnvironmentVariable(L\"USERPROFILE\", buffer, bufferSize);\n directory.assign(u16to8(buffer));\n delete[] buffer;\n #else\n directory = std::string(std::getenv(\"HOME\"));\n #endif\n\n return directory;\n }\n\n std::string GetDataDirectory(bool create) {\n std::string directory = getDataDirectoryRoot() + std::string(\"\/musikcube\/\");\n\n if (create) {\n try {\n boost::filesystem::path path(directory);\n if (!boost::filesystem::exists(path)) {\n boost::filesystem::create_directories(path);\n }\n }\n catch (...) {\n \/* ugh, fixme *\/\n }\n }\n\n return directory;\n }\n\n std::string GetPath(const std::string &sFile) {\n std::string sPath;\n int length;\n\n #ifdef WIN32\n wchar_t widePath[2048];\n wchar_t *szFile = NULL;\n\n length = GetFullPathName(u8to16(sFile).c_str(), 2048, widePath, &szFile);\n if(length != 0 && length < 2048) {\n sPath.assign(u16to8(widePath).c_str());\n if(szFile!=0) {\n std::string sTheFile = u16to8(szFile);\n sPath.assign(sPath.substr(0,length-sTheFile.length()));\n }\n }\n else {\n sPath.assign(sFile);\n }\n #else\n char* szDir;\n sPath.assign(getcwd((char*)szDir, (size_t) length));\n #endif\n\n return sPath;\n }\n\n int64_t Checksum(char *data,unsigned int bytes) {\n int64_t sum = 0;\n for(unsigned int i = 0; i < bytes; ++i) {\n char ch = *(data + i);\n sum += (int64_t) ch;\n }\n return sum;\n }\n\n size_t CopyString(const std::string& src, char* dst, size_t size) {\n size_t len = src.size() + 1; \/* space for the null terminator *\/\n if (dst) {\n size_t copied = src.copy(dst, size - 1);\n dst[copied] = '\\0';\n return copied + 1;\n }\n return len;\n }\n\n bool FileToByteArray(const std::string& path, char** target, int& size, bool nullTerminate) {\n #ifdef WIN32\n std::wstring u16fn = u8to16(path);\n FILE* file = _wfopen(u16fn.c_str(), L\"rb\");\n #else\n FILE* file = fopen(path.c_str(), \"rb\");\n #endif\n\n *target = nullptr;\n size = 0;\n\n if (!file) {\n return false;\n }\n\n bool success = false;\n\n if (fseek(file, 0L, SEEK_END) == 0) {\n long fileSize = ftell(file);\n if (fileSize == -1) {\n goto close_and_return;\n }\n\n if (fseek(file, 0L, SEEK_SET) != 0) {\n goto close_and_return;\n }\n\n *target = (char*)malloc(sizeof(char) * (fileSize + (nullTerminate ? 1 : 0)));\n size = fread(*target, sizeof(char), fileSize, file);\n\n if (size == fileSize) {\n if (nullTerminate) {\n (*target)[size] = 0;\n }\n\n success = true;\n }\n }\n\n close_and_return:\n fclose(file);\n\n if (!success) {\n free(*target);\n }\n\n return success;\n }\n\n std::string NormalizeDir(std::string path) {\n path = boost::filesystem::path(path).make_preferred().string();\n\n std::string sep(1, boost::filesystem::path::preferred_separator);\n if (path.size() && path.substr(path.size() - 1, 1) != sep) {\n path += sep;\n }\n\n return path;\n }\n\n void ReplaceAll(std::string& input, const std::string& find, const std::string& replace) {\n size_t pos = input.find(find);\n while (pos != std::string::npos) {\n input.replace(pos, find.size(), replace);\n pos = input.find(find, pos + replace.size());\n }\n }\n\n std::string Trim(const std::string& str) {\n std::string s(str);\n s.erase(s.begin(), std::find_if(s.begin(), s.end(),\n std::not1(std::ptr_fun<int, int>(std::isspace))));\n s.erase(std::find_if(s.rbegin(), s.rend(),\n std::not1(std::ptr_fun<int, int>(std::isspace))).base(), s.end());\n return s;\n }\n\n std::vector<std::string> Split(\n const std::string& in, const std::string& delim)\n {\n std::vector<std::string> result;\n size_t last = 0, next = 0;\n while ((next = in.find(delim, last)) != std::string::npos) {\n result.push_back(std::move(Trim(in.substr(last, next - last))));\n last = next + 1;\n }\n result.push_back(std::move(Trim(in.substr(last))));\n return result;\n }\n\n void OpenFile(const std::string& path) {\n #ifdef WIN32\n ShellExecuteA(nullptr, nullptr, path.c_str(), nullptr, nullptr, SW_SHOWNORMAL);\n #elif __APPLE__\n std::string command = \"open '\" + path + \"' > \/dev\/null 2> \/dev\/null\";\n system(command.c_str());\n #else\n std::string command = \"xdg-open '\" + path + \"' > \/dev\/null 2> \/dev\/null\";\n system(command.c_str());\n #endif\n }\n\n bool CopyFile(const std::string& from, const std::string& to) {\n if (from.size() && to.size() && from != to) {\n std::ifstream in(from);\n if (in.is_open()) {\n std::ofstream out(to);\n if (out.is_open()) {\n out << in.rdbuf();\n return true;\n }\n }\n }\n return false;\n }\n\n} }\n<|endoftext|>"} {"text":"<commit_before>#include \"config.h\"\n\n#include \"network_manager.hpp\"\n#include \"rtnetlink_server.hpp\"\n#include \"types.hpp\"\n#ifdef SYNC_MAC_FROM_INVENTORY\n#include \"util.hpp\"\n#endif\n\n#include <linux\/netlink.h>\n\n#include <filesystem>\n#include <fstream>\n#include <functional>\n#include <memory>\n#ifdef SYNC_MAC_FROM_INVENTORY\n#include <nlohmann\/json.hpp>\n#endif\n#include <phosphor-logging\/elog-errors.hpp>\n#include <phosphor-logging\/log.hpp>\n#include <sdbusplus\/bus.hpp>\n#include <sdbusplus\/bus\/match.hpp>\n#include <sdbusplus\/server\/manager.hpp>\n#include <sdeventplus\/event.hpp>\n#include <xyz\/openbmc_project\/Common\/error.hpp>\n\nusing phosphor::logging::elog;\nusing phosphor::logging::entry;\nusing phosphor::logging::level;\nusing phosphor::logging::log;\nusing sdbusplus::xyz::openbmc_project::Common::Error::InternalFailure;\nusing DbusObjectPath = std::string;\nusing DbusInterface = std::string;\nusing PropertyValue = std::string;\n\nconstexpr char NETWORK_CONF_DIR[] = \"\/etc\/systemd\/network\";\n\nconstexpr char DEFAULT_OBJPATH[] = \"\/xyz\/openbmc_project\/network\";\n\nconstexpr auto firstBootPath = \"\/var\/lib\/network\/firstBoot_\";\nconstexpr auto configFile = \"\/usr\/share\/network\/config.json\";\n\nconstexpr auto invNetworkIntf =\n \"xyz.openbmc_project.Inventory.Item.NetworkInterface\";\n\nnamespace phosphor\n{\nnamespace network\n{\n\nstd::unique_ptr<phosphor::network::Manager> manager = nullptr;\nstd::unique_ptr<Timer> refreshObjectTimer = nullptr;\nstd::unique_ptr<Timer> reloadTimer = nullptr;\n\n#ifdef SYNC_MAC_FROM_INVENTORY\nstd::unique_ptr<sdbusplus::bus::match_t> EthInterfaceMatch = nullptr;\nstd::vector<std::string> first_boot_status;\n\nbool setInventoryMACOnSystem(sdbusplus::bus_t& bus,\n const nlohmann::json& configJson,\n const std::string& intfname)\n{\n try\n {\n auto inventoryMAC = mac_address::getfromInventory(bus, intfname);\n if (!mac_address::toString(inventoryMAC).empty())\n {\n log<level::INFO>(\"Mac Address in Inventory on \"),\n entry(\"Interface : \", intfname.c_str()),\n entry(\"MAC Address :\",\n (mac_address::toString(inventoryMAC)).c_str());\n manager->setFistBootMACOnInterface(std::make_pair(\n intfname.c_str(), mac_address::toString(inventoryMAC)));\n first_boot_status.push_back(intfname.c_str());\n bool status = true;\n for (const auto& keys : configJson.items())\n {\n if (!(std::find(first_boot_status.begin(),\n first_boot_status.end(),\n keys.key()) != first_boot_status.end()))\n {\n log<level::INFO>(\"Interface MAC is NOT set from VPD\"),\n entry(\"INTERFACE\", keys.key().c_str());\n status = false;\n }\n }\n if (status)\n {\n log<level::INFO>(\"Removing the match for ethernet interfaces\");\n phosphor::network::EthInterfaceMatch = nullptr;\n }\n }\n else\n {\n log<level::INFO>(\"Nothing is present in Inventory\");\n return false;\n }\n }\n catch (const std::exception& e)\n {\n log<level::ERR>(\"Exception occurred during getting of MAC \"\n \"address from Inventory\");\n return false;\n }\n return true;\n}\n\n\/\/ register the macthes to be monitored from inventory manager\nvoid registerSignals(sdbusplus::bus_t& bus, const nlohmann::json& configJson)\n{\n log<level::INFO>(\"Registering the Inventory Signals Matcher\");\n\n static std::unique_ptr<sdbusplus::bus::match_t> MacAddressMatch;\n\n auto callback = [&](sdbusplus::message_t& m) {\n std::map<DbusObjectPath,\n std::map<DbusInterface, std::variant<PropertyValue>>>\n interfacesProperties;\n\n sdbusplus::message::object_path objPath;\n std::pair<std::string, std::string> ethPair;\n m.read(objPath, interfacesProperties);\n\n for (const auto& pattern : configJson.items())\n {\n if (objPath.str.find(pattern.value()) != std::string::npos)\n {\n for (auto& interface : interfacesProperties)\n {\n if (interface.first == invNetworkIntf)\n {\n for (const auto& property : interface.second)\n {\n if (property.first == \"MACAddress\")\n {\n ethPair = std::make_pair(\n pattern.key(),\n std::get<std::string>(property.second));\n break;\n }\n }\n break;\n }\n }\n if (!(ethPair.first.empty() || ethPair.second.empty()))\n {\n manager->setFistBootMACOnInterface(ethPair);\n }\n }\n }\n };\n\n MacAddressMatch = std::make_unique<sdbusplus::bus::match_t>(\n bus,\n \"interface='org.freedesktop.DBus.ObjectManager',type='signal',\"\n \"member='InterfacesAdded',path='\/xyz\/openbmc_project\/\"\n \"inventory'\",\n callback);\n}\n\nvoid watchEthernetInterface(sdbusplus::bus_t& bus,\n const nlohmann::json& configJson)\n{\n auto mycallback = [&](sdbusplus::message_t& m) {\n std::map<DbusObjectPath,\n std::map<DbusInterface, std::variant<PropertyValue>>>\n interfacesProperties;\n\n sdbusplus::message::object_path objPath;\n std::pair<std::string, std::string> ethPair;\n m.read(objPath, interfacesProperties);\n for (const auto& interfaces : interfacesProperties)\n {\n if (interfaces.first ==\n \"xyz.openbmc_project.Network.EthernetInterface\")\n {\n for (const auto& property : interfaces.second)\n {\n if (property.first == \"InterfaceName\")\n {\n std::string infname =\n std::get<std::string>(property.second);\n\n if (configJson.find(infname) == configJson.end())\n {\n \/\/ ethernet interface not found in configJSON\n \/\/ check if it is not sit0 interface, as it is\n \/\/ expected.\n if (infname != \"sit0\")\n {\n log<level::ERR>(\n \"Wrong Interface Name in Config Json\");\n }\n }\n else\n {\n if (!phosphor::network::setInventoryMACOnSystem(\n bus, configJson, infname))\n {\n phosphor::network::registerSignals(bus,\n configJson);\n phosphor::network::EthInterfaceMatch = nullptr;\n }\n }\n break;\n }\n }\n break;\n }\n }\n };\n \/\/ Incase if phosphor-inventory-manager started early and the VPD is already\n \/\/ collected by the time network service has come up, better to check the\n \/\/ VPD directly and set the MAC Address on the respective Interface.\n\n bool registeredSignals = false;\n for (const auto& interfaceString : configJson.items())\n {\n if (!std::filesystem::exists(firstBootPath + interfaceString.key()) &&\n !registeredSignals)\n {\n\n log<level::INFO>(\n \"First boot file is not present, check VPD for MAC\");\n phosphor::network::EthInterfaceMatch = std::make_unique<\n sdbusplus::bus::match_t>(\n bus,\n \"interface='org.freedesktop.DBus.ObjectManager',type='signal',\"\n \"member='InterfacesAdded',path='\/xyz\/openbmc_project\/network'\",\n mycallback);\n registeredSignals = true;\n }\n }\n}\n\n#endif\n\n\/** @brief refresh the network objects. *\/\nvoid refreshObjects()\n{\n if (manager)\n {\n log<level::INFO>(\"Refreshing the objects.\");\n manager->createChildObjects();\n log<level::INFO>(\"Refreshing complete.\");\n }\n}\n\nvoid reloadNetworkd()\n{\n if (manager)\n {\n log<level::INFO>(\"Sending networkd reload\");\n manager->doReloadConfigs();\n log<level::INFO>(\"Done networkd reload\");\n }\n}\n\nvoid initializeTimers()\n{\n auto event = sdeventplus::Event::get_default();\n refreshObjectTimer =\n std::make_unique<Timer>(event, std::bind(refreshObjects));\n reloadTimer = std::make_unique<Timer>(event, std::bind(reloadNetworkd));\n}\n\n} \/\/ namespace network\n} \/\/ namespace phosphor\n\nint main(int \/*argc*\/, char** \/*argv*\/)\n{\n phosphor::network::initializeTimers();\n\n auto bus = sdbusplus::bus::new_default();\n\n \/\/ Need sd_event to watch for OCC device errors\n sd_event* event = nullptr;\n auto r = sd_event_default(&event);\n if (r < 0)\n {\n log<level::ERR>(\"Error creating a default sd_event handler\");\n return r;\n }\n\n phosphor::network::EventPtr eventPtr{event};\n event = nullptr;\n\n \/\/ Attach the bus to sd_event to service user requests\n bus.attach_event(eventPtr.get(), SD_EVENT_PRIORITY_NORMAL);\n\n \/\/ Add sdbusplus Object Manager for the 'root' path of the network manager.\n sdbusplus::server::manager_t objManager(bus, DEFAULT_OBJPATH);\n bus.request_name(DEFAULT_BUSNAME);\n\n phosphor::network::manager = std::make_unique<phosphor::network::Manager>(\n bus, DEFAULT_OBJPATH, NETWORK_CONF_DIR);\n\n \/\/ create the default network files if the network file\n \/\/ is not there for any interface.\n if (phosphor::network::manager->createDefaultNetworkFiles())\n {\n phosphor::network::manager->reloadConfigs();\n }\n\n \/\/ RTNETLINK event handler\n phosphor::network::rtnetlink::Server svr(eventPtr);\n\n#ifdef SYNC_MAC_FROM_INVENTORY\n std::ifstream in(configFile);\n nlohmann::json configJson;\n in >> configJson;\n phosphor::network::watchEthernetInterface(bus, configJson);\n#endif\n\n \/\/ Trigger the initial object scan\n \/\/ This is intentionally deferred, to ensure that systemd-networkd is\n \/\/ fully configured.\n phosphor::network::refreshObjectTimer->restartOnce(\n phosphor::network::refreshTimeout);\n\n sd_event_loop(eventPtr.get());\n}\n<commit_msg>main: Catch and handle all exceptions<commit_after>#include \"config.h\"\n\n#include \"network_manager.hpp\"\n#include \"rtnetlink_server.hpp\"\n#include \"types.hpp\"\n#ifdef SYNC_MAC_FROM_INVENTORY\n#include \"util.hpp\"\n#endif\n\n#include <fmt\/format.h>\n#include <linux\/netlink.h>\n\n#include <filesystem>\n#include <fstream>\n#include <functional>\n#include <memory>\n#ifdef SYNC_MAC_FROM_INVENTORY\n#include <nlohmann\/json.hpp>\n#endif\n#include <phosphor-logging\/elog-errors.hpp>\n#include <phosphor-logging\/log.hpp>\n#include <sdbusplus\/bus.hpp>\n#include <sdbusplus\/bus\/match.hpp>\n#include <sdbusplus\/server\/manager.hpp>\n#include <sdeventplus\/event.hpp>\n#include <xyz\/openbmc_project\/Common\/error.hpp>\n\nusing phosphor::logging::elog;\nusing phosphor::logging::entry;\nusing phosphor::logging::level;\nusing phosphor::logging::log;\nusing sdbusplus::xyz::openbmc_project::Common::Error::InternalFailure;\nusing DbusObjectPath = std::string;\nusing DbusInterface = std::string;\nusing PropertyValue = std::string;\n\nconstexpr char NETWORK_CONF_DIR[] = \"\/etc\/systemd\/network\";\n\nconstexpr char DEFAULT_OBJPATH[] = \"\/xyz\/openbmc_project\/network\";\n\nconstexpr auto firstBootPath = \"\/var\/lib\/network\/firstBoot_\";\nconstexpr auto configFile = \"\/usr\/share\/network\/config.json\";\n\nconstexpr auto invNetworkIntf =\n \"xyz.openbmc_project.Inventory.Item.NetworkInterface\";\n\nnamespace phosphor\n{\nnamespace network\n{\n\nstd::unique_ptr<Manager> manager = nullptr;\nstd::unique_ptr<Timer> refreshObjectTimer = nullptr;\nstd::unique_ptr<Timer> reloadTimer = nullptr;\n\n#ifdef SYNC_MAC_FROM_INVENTORY\nstd::unique_ptr<sdbusplus::bus::match_t> EthInterfaceMatch = nullptr;\nstd::vector<std::string> first_boot_status;\n\nbool setInventoryMACOnSystem(sdbusplus::bus_t& bus,\n const nlohmann::json& configJson,\n const std::string& intfname)\n{\n try\n {\n auto inventoryMAC = mac_address::getfromInventory(bus, intfname);\n if (!mac_address::toString(inventoryMAC).empty())\n {\n log<level::INFO>(\"Mac Address in Inventory on \"),\n entry(\"Interface : \", intfname.c_str()),\n entry(\"MAC Address :\",\n (mac_address::toString(inventoryMAC)).c_str());\n manager->setFistBootMACOnInterface(std::make_pair(\n intfname.c_str(), mac_address::toString(inventoryMAC)));\n first_boot_status.push_back(intfname.c_str());\n bool status = true;\n for (const auto& keys : configJson.items())\n {\n if (!(std::find(first_boot_status.begin(),\n first_boot_status.end(),\n keys.key()) != first_boot_status.end()))\n {\n log<level::INFO>(\"Interface MAC is NOT set from VPD\"),\n entry(\"INTERFACE\", keys.key().c_str());\n status = false;\n }\n }\n if (status)\n {\n log<level::INFO>(\"Removing the match for ethernet interfaces\");\n EthInterfaceMatch = nullptr;\n }\n }\n else\n {\n log<level::INFO>(\"Nothing is present in Inventory\");\n return false;\n }\n }\n catch (const std::exception& e)\n {\n log<level::ERR>(\"Exception occurred during getting of MAC \"\n \"address from Inventory\");\n return false;\n }\n return true;\n}\n\n\/\/ register the macthes to be monitored from inventory manager\nvoid registerSignals(sdbusplus::bus_t& bus, const nlohmann::json& configJson)\n{\n log<level::INFO>(\"Registering the Inventory Signals Matcher\");\n\n static std::unique_ptr<sdbusplus::bus::match_t> MacAddressMatch;\n\n auto callback = [&](sdbusplus::message_t& m) {\n std::map<DbusObjectPath,\n std::map<DbusInterface, std::variant<PropertyValue>>>\n interfacesProperties;\n\n sdbusplus::message::object_path objPath;\n std::pair<std::string, std::string> ethPair;\n m.read(objPath, interfacesProperties);\n\n for (const auto& pattern : configJson.items())\n {\n if (objPath.str.find(pattern.value()) != std::string::npos)\n {\n for (auto& interface : interfacesProperties)\n {\n if (interface.first == invNetworkIntf)\n {\n for (const auto& property : interface.second)\n {\n if (property.first == \"MACAddress\")\n {\n ethPair = std::make_pair(\n pattern.key(),\n std::get<std::string>(property.second));\n break;\n }\n }\n break;\n }\n }\n if (!(ethPair.first.empty() || ethPair.second.empty()))\n {\n manager->setFistBootMACOnInterface(ethPair);\n }\n }\n }\n };\n\n MacAddressMatch = std::make_unique<sdbusplus::bus::match_t>(\n bus,\n \"interface='org.freedesktop.DBus.ObjectManager',type='signal',\"\n \"member='InterfacesAdded',path='\/xyz\/openbmc_project\/\"\n \"inventory'\",\n callback);\n}\n\nvoid watchEthernetInterface(sdbusplus::bus_t& bus,\n const nlohmann::json& configJson)\n{\n auto mycallback = [&](sdbusplus::message_t& m) {\n std::map<DbusObjectPath,\n std::map<DbusInterface, std::variant<PropertyValue>>>\n interfacesProperties;\n\n sdbusplus::message::object_path objPath;\n std::pair<std::string, std::string> ethPair;\n m.read(objPath, interfacesProperties);\n for (const auto& interfaces : interfacesProperties)\n {\n if (interfaces.first ==\n \"xyz.openbmc_project.Network.EthernetInterface\")\n {\n for (const auto& property : interfaces.second)\n {\n if (property.first == \"InterfaceName\")\n {\n std::string infname =\n std::get<std::string>(property.second);\n\n if (configJson.find(infname) == configJson.end())\n {\n \/\/ ethernet interface not found in configJSON\n \/\/ check if it is not sit0 interface, as it is\n \/\/ expected.\n if (infname != \"sit0\")\n {\n log<level::ERR>(\n \"Wrong Interface Name in Config Json\");\n }\n }\n else\n {\n if (!setInventoryMACOnSystem(bus, configJson,\n infname))\n {\n registerSignals(bus, configJson);\n EthInterfaceMatch = nullptr;\n }\n }\n break;\n }\n }\n break;\n }\n }\n };\n \/\/ Incase if phosphor-inventory-manager started early and the VPD is already\n \/\/ collected by the time network service has come up, better to check the\n \/\/ VPD directly and set the MAC Address on the respective Interface.\n\n bool registeredSignals = false;\n for (const auto& interfaceString : configJson.items())\n {\n if (!std::filesystem::exists(firstBootPath + interfaceString.key()) &&\n !registeredSignals)\n {\n\n log<level::INFO>(\n \"First boot file is not present, check VPD for MAC\");\n EthInterfaceMatch = std::make_unique<sdbusplus::bus::match_t>(\n bus,\n \"interface='org.freedesktop.DBus.ObjectManager',type='signal',\"\n \"member='InterfacesAdded',path='\/xyz\/openbmc_project\/network'\",\n mycallback);\n registeredSignals = true;\n }\n }\n}\n\n#endif\n\n\/** @brief refresh the network objects. *\/\nvoid refreshObjects()\n{\n if (manager)\n {\n log<level::INFO>(\"Refreshing the objects.\");\n manager->createChildObjects();\n log<level::INFO>(\"Refreshing complete.\");\n }\n}\n\nvoid reloadNetworkd()\n{\n if (manager)\n {\n log<level::INFO>(\"Sending networkd reload\");\n manager->doReloadConfigs();\n log<level::INFO>(\"Done networkd reload\");\n }\n}\n\nvoid initializeTimers()\n{\n auto event = sdeventplus::Event::get_default();\n refreshObjectTimer =\n std::make_unique<Timer>(event, std::bind(refreshObjects));\n reloadTimer = std::make_unique<Timer>(event, std::bind(reloadNetworkd));\n}\n\nint main()\n{\n initializeTimers();\n\n auto bus = sdbusplus::bus::new_default();\n\n \/\/ Need sd_event to watch for OCC device errors\n sd_event* event = nullptr;\n auto r = sd_event_default(&event);\n if (r < 0)\n {\n log<level::ERR>(\"Error creating a default sd_event handler\");\n return r;\n }\n\n EventPtr eventPtr{event};\n event = nullptr;\n\n \/\/ Attach the bus to sd_event to service user requests\n bus.attach_event(eventPtr.get(), SD_EVENT_PRIORITY_NORMAL);\n\n \/\/ Add sdbusplus Object Manager for the 'root' path of the network manager.\n sdbusplus::server::manager_t objManager(bus, DEFAULT_OBJPATH);\n bus.request_name(DEFAULT_BUSNAME);\n\n manager = std::make_unique<Manager>(bus, DEFAULT_OBJPATH, NETWORK_CONF_DIR);\n\n \/\/ create the default network files if the network file\n \/\/ is not there for any interface.\n if (manager->createDefaultNetworkFiles())\n {\n manager->reloadConfigs();\n }\n\n \/\/ RTNETLINK event handler\n rtnetlink::Server svr(eventPtr);\n\n#ifdef SYNC_MAC_FROM_INVENTORY\n std::ifstream in(configFile);\n nlohmann::json configJson;\n in >> configJson;\n watchEthernetInterface(bus, configJson);\n#endif\n\n \/\/ Trigger the initial object scan\n \/\/ This is intentionally deferred, to ensure that systemd-networkd is\n \/\/ fully configured.\n refreshObjectTimer->restartOnce(refreshTimeout);\n\n return sd_event_loop(eventPtr.get());\n}\n\n} \/\/ namespace network\n} \/\/ namespace phosphor\n\nint main(int \/*argc*\/, char** \/*argv*\/)\n{\n try\n {\n return phosphor::network::main();\n }\n catch (const std::exception& e)\n {\n auto msg = fmt::format(\"FAILED: {}\", e.what());\n log<level::ERR>(msg.c_str(), entry(\"ERROR\", e.what()));\n return 1;\n }\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"formulation\/updater\/diffusion_updater.hpp\"\n\nnamespace bart {\n\nnamespace formulation {\n\nnamespace updater {\n\ntemplate<int dim>\nDiffusionUpdater<dim>::DiffusionUpdater(\n std::unique_ptr<DiffusionFormulationType> formulation_ptr,\n std::shared_ptr<StamperType> stamper_ptr,\n std::unordered_set<problem::Boundary> reflective_boundaries)\n : FixedUpdater<dim>(stamper_ptr),\n formulation_ptr_(std::move(formulation_ptr)),\n stamper_ptr_(stamper_ptr),\n reflective_boundaries_(reflective_boundaries) {\n AssertThrow(formulation_ptr_ != nullptr,\n dealii::ExcMessage(\"Error in constructor of DiffusionUpdater, \"\n \"formulation pointer passed is null\"))\n AssertThrow(stamper_ptr_ != nullptr,\n dealii::ExcMessage(\"Error in constructor of DiffusionUpdater, \"\n \"stamper pointer passed is null\"))\n this->set_description(\"diffusion formulation updater\",\n utility::DefaultImplementation(true));\n\n if (!reflective_boundaries_.empty()) {\n this->set_description(this->description() + \" (reflective BCs)\",\n utility::DefaultImplementation(true));\n }\n}\n\ntemplate<int dim>\nauto DiffusionUpdater<dim>::SetUpFixedFunctions(system::System& \/*to_update*\/,\n system::EnergyGroup group,\n quadrature::QuadraturePointIndex \/*index*\/) -> void {\n this->fixed_matrix_functions_ = {};\n this->fixed_vector_functions_ = {};\n this->fixed_matrix_boundary_functions_ = {};\n this->fixed_vector_boundary_functions_ = {};\n\n const auto streaming_term_function = [&, group](formulation::FullMatrix& cell_matrix, const CellPtr& cell_ptr) -> void {\n formulation_ptr_->FillCellStreamingTerm(cell_matrix, cell_ptr, group.get()); };\n const auto collision_term_function = [&, group](formulation::FullMatrix& cell_matrix, const CellPtr& cell_ptr) -> void {\n formulation_ptr_->FillCellCollisionTerm(cell_matrix, cell_ptr, group.get()); };\n this->fixed_matrix_functions_.push_back(streaming_term_function);\n this->fixed_matrix_functions_.push_back(collision_term_function);\n\n auto fixed_term_function = [&, group](formulation::Vector& cell_vector, const CellPtr& cell_ptr) -> void {\n formulation_ptr_->FillCellFixedSource(cell_vector, cell_ptr, group.get()); };\n this->fixed_vector_functions_.push_back(fixed_term_function);\n if (this->rhs_constant_vector_ptr_ != nullptr) {\n auto constant_term_function = [=](formulation::Vector& cell_vector, const CellPtr& cell_ptr) -> void {\n formulation_ptr_->FillCellConstantTerm(cell_vector, cell_ptr, *this->rhs_constant_vector_ptr_); };\n this->fixed_vector_functions_.push_back(constant_term_function);\n }\n\n auto boundary_function = [&](formulation::FullMatrix& cell_matrix, const domain::FaceIndex face_index,\n const CellPtr& cell_ptr) -> void {\n using DiffusionBoundaryType = typename formulation::scalar::DiffusionI<dim>::BoundaryType;\n\n DiffusionBoundaryType boundary_type = DiffusionBoundaryType::kInterior;\n\n if (cell_ptr->at_boundary()) {\n problem::Boundary boundary = static_cast<problem::Boundary>(cell_ptr->face(face_index.get())->boundary_id());\n if (reflective_boundaries_.count(boundary) == 1) {\n boundary_type = DiffusionBoundaryType::kReflective;\n } else {\n boundary_type = DiffusionBoundaryType::kVacuum;\n }\n }\n\n formulation_ptr_->FillBoundaryTerm(cell_matrix, cell_ptr,face_index.get(), boundary_type);\n };\n this->fixed_matrix_boundary_functions_.push_back(boundary_function);\n}\n\ntemplate<int dim>\nvoid DiffusionUpdater<dim>::UpdateScatteringSource(system::System &to_update, const system::EnergyGroup energy_group,\n quadrature::QuadraturePointIndex \/*index*\/) {\n using system::terms::VariableLinearTerms;\n using CellPtr = typename domain::CellPtr<dim>;\n const int group = energy_group.get();\n auto scattering_source_ptr = to_update.right_hand_side_ptr_->GetVariableTermPtr({group, 0}, VariableLinearTerms::kScatteringSource);\n *scattering_source_ptr = 0;\n const auto& current_moments = to_update.current_moments->moments();\n auto scattering_source_function = [&](formulation::Vector& cell_vector, const CellPtr& cell_ptr) -> void {\n formulation_ptr_->FillCellScatteringSource(cell_vector, cell_ptr, group, current_moments);\n };\n stamper_ptr_->StampVector(*scattering_source_ptr, scattering_source_function);\n}\ntemplate<int dim>\nvoid DiffusionUpdater<dim>::UpdateFissionSource(system::System &to_update,system::EnergyGroup energy_group,\n quadrature::QuadraturePointIndex \/*index*\/) {\n using system::terms::VariableLinearTerms;\n using CellPtr = typename domain::CellPtr<dim>;\n const int group = energy_group.get();\n auto fission_source_ptr = to_update.right_hand_side_ptr_->GetVariableTermPtr({group, 0}, VariableLinearTerms::kFissionSource);\n *fission_source_ptr = 0;\n const auto& current_moments = to_update.current_moments->moments();\n const auto& in_group_moment = current_moments.at({group, 0, 0});\n auto fission_source_function = [&](formulation::Vector& cell_vector, const CellPtr& cell_ptr) -> void {\n formulation_ptr_->FillCellFissionSource(cell_vector, cell_ptr, group, to_update.k_effective.value(),\n in_group_moment, current_moments);\n };\n stamper_ptr_->StampVector(*fission_source_ptr, fission_source_function);\n}\ntemplate<int dim>\nvoid DiffusionUpdater<dim>::UpdateFixedSource(\n system::System &to_update,\n system::EnergyGroup energy_group,\n quadrature::QuadraturePointIndex \/*index*\/) {\n int group = energy_group.get();\n auto fixed_source_ptr =\n to_update.right_hand_side_ptr_->GetFixedTermPtr({group, 0});\n *fixed_source_ptr = 0;\n auto fixed_source_function =\n [&](formulation::Vector& cell_vector,\n const domain::CellPtr<dim> &cell_ptr) -> void {\n formulation_ptr_->FillCellFixedSource(cell_vector,\n cell_ptr, group);\n };\n stamper_ptr_->StampVector(*fixed_source_ptr, fixed_source_function);\n}\n\ntemplate class DiffusionUpdater<1>;\ntemplate class DiffusionUpdater<2>;\ntemplate class DiffusionUpdater<3>;\n\n} \/\/ namespace updater\n\n} \/\/ namespace formulation\n\n} \/\/ namespace bart\n<commit_msg>Removed extraneous check for boundary term in DiffusionUpdater.<commit_after>#include \"formulation\/updater\/diffusion_updater.hpp\"\n\nnamespace bart {\n\nnamespace formulation {\n\nnamespace updater {\n\ntemplate<int dim>\nDiffusionUpdater<dim>::DiffusionUpdater(\n std::unique_ptr<DiffusionFormulationType> formulation_ptr,\n std::shared_ptr<StamperType> stamper_ptr,\n std::unordered_set<problem::Boundary> reflective_boundaries)\n : FixedUpdater<dim>(stamper_ptr),\n formulation_ptr_(std::move(formulation_ptr)),\n stamper_ptr_(stamper_ptr),\n reflective_boundaries_(reflective_boundaries) {\n AssertThrow(formulation_ptr_ != nullptr,\n dealii::ExcMessage(\"Error in constructor of DiffusionUpdater, \"\n \"formulation pointer passed is null\"))\n AssertThrow(stamper_ptr_ != nullptr,\n dealii::ExcMessage(\"Error in constructor of DiffusionUpdater, \"\n \"stamper pointer passed is null\"))\n this->set_description(\"diffusion formulation updater\",\n utility::DefaultImplementation(true));\n\n if (!reflective_boundaries_.empty()) {\n this->set_description(this->description() + \" (reflective BCs)\",\n utility::DefaultImplementation(true));\n }\n}\n\ntemplate<int dim>\nauto DiffusionUpdater<dim>::SetUpFixedFunctions(system::System& \/*to_update*\/,\n system::EnergyGroup group,\n quadrature::QuadraturePointIndex \/*index*\/) -> void {\n this->fixed_matrix_functions_ = {};\n this->fixed_vector_functions_ = {};\n this->fixed_matrix_boundary_functions_ = {};\n this->fixed_vector_boundary_functions_ = {};\n\n const auto streaming_term_function = [&, group](formulation::FullMatrix& cell_matrix, const CellPtr& cell_ptr) -> void {\n formulation_ptr_->FillCellStreamingTerm(cell_matrix, cell_ptr, group.get()); };\n const auto collision_term_function = [&, group](formulation::FullMatrix& cell_matrix, const CellPtr& cell_ptr) -> void {\n formulation_ptr_->FillCellCollisionTerm(cell_matrix, cell_ptr, group.get()); };\n this->fixed_matrix_functions_.push_back(streaming_term_function);\n this->fixed_matrix_functions_.push_back(collision_term_function);\n\n auto fixed_term_function = [&, group](formulation::Vector& cell_vector, const CellPtr& cell_ptr) -> void {\n formulation_ptr_->FillCellFixedSource(cell_vector, cell_ptr, group.get()); };\n this->fixed_vector_functions_.push_back(fixed_term_function);\n if (this->rhs_constant_vector_ptr_ != nullptr) {\n auto constant_term_function = [=](formulation::Vector& cell_vector, const CellPtr& cell_ptr) -> void {\n formulation_ptr_->FillCellConstantTerm(cell_vector, cell_ptr, *this->rhs_constant_vector_ptr_); };\n this->fixed_vector_functions_.push_back(constant_term_function);\n }\n\n auto boundary_function = [&](formulation::FullMatrix& cell_matrix, const domain::FaceIndex face_index,\n const CellPtr& cell_ptr) -> void {\n using DiffusionBoundaryType = typename formulation::scalar::DiffusionI<dim>::BoundaryType;\n\n DiffusionBoundaryType boundary_type = DiffusionBoundaryType::kVacuum;\n\n if (cell_ptr->at_boundary()) {\n problem::Boundary boundary = static_cast<problem::Boundary>(cell_ptr->face(face_index.get())->boundary_id());\n if (reflective_boundaries_.count(boundary) == 1)\n boundary_type = DiffusionBoundaryType::kReflective;\n formulation_ptr_->FillBoundaryTerm(cell_matrix, cell_ptr,face_index.get(), boundary_type);\n }\n };\n this->fixed_matrix_boundary_functions_.push_back(boundary_function);\n}\n\ntemplate<int dim>\nvoid DiffusionUpdater<dim>::UpdateScatteringSource(system::System &to_update, const system::EnergyGroup energy_group,\n quadrature::QuadraturePointIndex \/*index*\/) {\n using system::terms::VariableLinearTerms;\n using CellPtr = typename domain::CellPtr<dim>;\n const int group = energy_group.get();\n auto scattering_source_ptr = to_update.right_hand_side_ptr_->GetVariableTermPtr({group, 0}, VariableLinearTerms::kScatteringSource);\n *scattering_source_ptr = 0;\n const auto& current_moments = to_update.current_moments->moments();\n auto scattering_source_function = [&](formulation::Vector& cell_vector, const CellPtr& cell_ptr) -> void {\n formulation_ptr_->FillCellScatteringSource(cell_vector, cell_ptr, group, current_moments);\n };\n stamper_ptr_->StampVector(*scattering_source_ptr, scattering_source_function);\n}\ntemplate<int dim>\nvoid DiffusionUpdater<dim>::UpdateFissionSource(system::System &to_update,system::EnergyGroup energy_group,\n quadrature::QuadraturePointIndex \/*index*\/) {\n using system::terms::VariableLinearTerms;\n using CellPtr = typename domain::CellPtr<dim>;\n const int group = energy_group.get();\n auto fission_source_ptr = to_update.right_hand_side_ptr_->GetVariableTermPtr({group, 0}, VariableLinearTerms::kFissionSource);\n *fission_source_ptr = 0;\n const auto& current_moments = to_update.current_moments->moments();\n const auto& in_group_moment = current_moments.at({group, 0, 0});\n auto fission_source_function = [&](formulation::Vector& cell_vector, const CellPtr& cell_ptr) -> void {\n formulation_ptr_->FillCellFissionSource(cell_vector, cell_ptr, group, to_update.k_effective.value(),\n in_group_moment, current_moments);\n };\n stamper_ptr_->StampVector(*fission_source_ptr, fission_source_function);\n}\ntemplate<int dim>\nvoid DiffusionUpdater<dim>::UpdateFixedSource(\n system::System &to_update,\n system::EnergyGroup energy_group,\n quadrature::QuadraturePointIndex \/*index*\/) {\n int group = energy_group.get();\n auto fixed_source_ptr =\n to_update.right_hand_side_ptr_->GetFixedTermPtr({group, 0});\n *fixed_source_ptr = 0;\n auto fixed_source_function =\n [&](formulation::Vector& cell_vector,\n const domain::CellPtr<dim> &cell_ptr) -> void {\n formulation_ptr_->FillCellFixedSource(cell_vector,\n cell_ptr, group);\n };\n stamper_ptr_->StampVector(*fixed_source_ptr, fixed_source_function);\n}\n\ntemplate class DiffusionUpdater<1>;\ntemplate class DiffusionUpdater<2>;\ntemplate class DiffusionUpdater<3>;\n\n} \/\/ namespace updater\n\n} \/\/ namespace formulation\n\n} \/\/ namespace bart\n<|endoftext|>"} {"text":"<commit_before>\/*\nCopyright (c) 2014 Microsoft Corporation. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\n\nAuthor: Leonardo de Moura\n*\/\n#include \"util\/lazy_list_fn.h\"\n#include \"util\/flet.h\"\n#include \"kernel\/instantiate.h\"\n#include \"kernel\/abstract.h\"\n#include \"library\/unifier.h\"\n#include \"library\/reducible.h\"\n#include \"library\/metavar_closure.h\"\n#include \"library\/error_handling\/error_handling.h\"\n#include \"frontends\/lean\/util.h\"\n#include \"frontends\/lean\/class.h\"\n#include \"frontends\/lean\/tactic_hint.h\"\n#include \"frontends\/lean\/local_context.h\"\n#include \"frontends\/lean\/choice_iterator.h\"\n\nnamespace lean {\n\/** \\brief Context for handling placeholder metavariable choice constraint *\/\nstruct placeholder_context {\n io_state m_ios;\n name_generator m_ngen;\n type_checker_ptr m_tc;\n local_context m_ctx;\n bool m_relax;\n bool m_use_local_instances;\n placeholder_context(environment const & env, io_state const & ios, local_context const & ctx,\n name const & prefix, bool relax, bool use_local_instances):\n m_ios(ios),\n m_ngen(prefix),\n m_tc(mk_type_checker(env, m_ngen.mk_child(), relax)),\n m_ctx(ctx),\n m_relax(relax),\n m_use_local_instances(use_local_instances) {\n }\n\n environment const & env() const { return m_tc->env(); }\n io_state const & ios() const { return m_ios; }\n bool use_local_instances() const { return m_use_local_instances; }\n type_checker & tc() const { return *m_tc; }\n};\n\npair<expr, constraint> mk_placeholder_elaborator(std::shared_ptr<placeholder_context> const & C,\n bool is_strict, optional<expr> const & type, tag g);\n\n\/** \\brief Whenever the elaborator finds a placeholder '_' or introduces an\n implicit argument, it creates a metavariable \\c ?m. It also creates a\n delayed choice constraint (?m in fn).\n\n The function \\c fn produces a stream of alternative solutions for ?m.\n In this case, \\c fn will do the following:\n 1) if the elaborated type of ?m is a 'class' C, then the stream will start with\n a) all local instances of class C (if elaborator.local_instances == true)\n b) solutions produced by tactic_hints for class C\n\n 2) if the elaborated type of ?m is not a class, then the stream will only contain\n the solutions produced by tactic_hints.\n\n The unifier only process delayed choice constraints when there are no other kind\n of constraint to be processed.\n\n This is a helper class for implementing this choice function.\n*\/\nstruct placeholder_elaborator : public choice_iterator {\n std::shared_ptr<placeholder_context> m_C;\n expr m_meta;\n \/\/ elaborated type of the metavariable\n expr m_meta_type;\n \/\/ local instances that should also be included in the\n \/\/ class-instance resolution.\n \/\/ This information is retrieved from the local context\n list<expr> m_local_instances;\n \/\/ global declaration names that are class instances.\n \/\/ This information is retrieved using #get_class_instances.\n list<name> m_instances;\n \/\/ Tactic hints for the class\n list<tactic_hint_entry> m_tactics;\n \/\/ result produce by last executed tactic.\n proof_state_seq m_tactic_result;\n justification m_jst;\n\n placeholder_elaborator(std::shared_ptr<placeholder_context> const & C,\n expr const & meta, expr const & meta_type,\n list<expr> const & local_insts, list<name> const & instances,\n list<tactic_hint_entry> const & tacs,\n justification const & j, bool ignore_failure):\n choice_iterator(ignore_failure), m_C(C),\n m_meta(meta), m_meta_type(meta_type),\n m_local_instances(local_insts), m_instances(instances),\n m_tactics(tacs),\n m_jst(j) {\n }\n\n constraints mk_constraints(constraint const & c, buffer<constraint> const & cs) {\n return cons(c, to_list(cs.begin(), cs.end()));\n }\n\n optional<constraints> try_instance(expr const & inst, expr const & inst_type) {\n type_checker & tc = m_C->tc();\n name_generator & ngen = m_C->m_ngen;\n tag g = inst.get_tag();\n local_context & ctx = m_C->m_ctx;\n try {\n flet<local_context> scope(ctx, ctx);\n buffer<expr> locals;\n expr meta_type = m_meta_type;\n while (true) {\n meta_type = tc.whnf(meta_type).first;\n if (!is_pi(meta_type))\n break;\n expr local = mk_local(ngen.next(), binding_name(meta_type),\n binding_domain(meta_type), binding_info(meta_type));\n ctx.add_local(local);\n locals.push_back(local);\n meta_type = instantiate(binding_body(meta_type), local);\n }\n expr type = inst_type;\n expr r = inst;\n buffer<constraint> cs;\n while (true) {\n type = tc.whnf(type).first;\n if (!is_pi(type))\n break;\n bool is_strict = true;\n pair<expr, constraint> ac = mk_placeholder_elaborator(m_C, is_strict,\n some_expr(binding_domain(type)), g);\n expr arg = ac.first;\n cs.push_back(ac.second);\n r = mk_app(r, arg).set_tag(g);\n type = instantiate(binding_body(type), arg);\n }\n r = Fun(locals, r);\n bool relax = m_C->m_relax;\n constraint c = mk_eq_cnstr(m_meta, r, m_jst, relax);\n return optional<constraints>(mk_constraints(c, cs));\n } catch (exception &) {\n return optional<constraints>();\n }\n }\n\n optional<constraints> try_instance(name const & inst) {\n environment const & env = m_C->env();\n if (auto decl = env.find(inst)) {\n name_generator & ngen = m_C->m_ngen;\n buffer<level> ls_buffer;\n unsigned num_univ_ps = length(decl->get_univ_params());\n for (unsigned i = 0; i < num_univ_ps; i++)\n ls_buffer.push_back(mk_meta_univ(ngen.next()));\n levels ls = to_list(ls_buffer.begin(), ls_buffer.end());\n expr inst_cnst = copy_tag(m_meta, mk_constant(inst, ls));\n expr inst_type = instantiate_type_univ_params(*decl, ls);\n return try_instance(inst_cnst, inst_type);\n } else {\n return optional<constraints>();\n }\n }\n\n optional<constraints> get_next_tactic_result() {\n while (auto next = m_tactic_result.pull()) {\n m_tactic_result = next->second;\n if (!empty(next->first.get_goals()))\n continue; \/\/ has unsolved goals\n substitution subst = next->first.get_subst();\n expr const & mvar = get_app_fn(m_meta);\n bool relax = m_C->m_relax;\n constraints cs = metavar_closure(m_meta_type).mk_constraints(subst, m_jst, relax);\n constraint c = mk_eq_cnstr(mvar, subst.instantiate(mvar), m_jst, relax);\n return some(cons(c, cs));\n }\n return optional<constraints>();\n }\n\n virtual optional<constraints> next() {\n while (!empty(m_local_instances)) {\n expr inst = head(m_local_instances);\n m_local_instances = tail(m_local_instances);\n if (!is_local(inst))\n continue;\n if (auto r = try_instance(inst, mlocal_type(inst)))\n return r;\n }\n while (!empty(m_instances)) {\n name inst = head(m_instances);\n m_instances = tail(m_instances);\n if (auto cs = try_instance(inst))\n return cs;\n }\n if (auto cs = get_next_tactic_result())\n return cs;\n while (!empty(m_tactics)) {\n tactic const & tac = head(m_tactics).get_tactic();\n m_tactics = tail(m_tactics);\n proof_state ps(goals(goal(m_meta, m_meta_type)), substitution(), m_C->m_ngen.mk_child());\n try {\n m_tactic_result = tac(m_C->env(), m_C->ios(), ps);\n if (auto cs = get_next_tactic_result())\n return cs;\n } catch (exception &) {}\n }\n return optional<constraints>();\n }\n};\n\n\nconstraint mk_placeholder_cnstr(std::shared_ptr<placeholder_context> const & C, expr const & m, bool is_strict) {\n environment const & env = C->env();\n justification j = mk_failed_to_synthesize_jst(env, m);\n auto choice_fn = [=](expr const & meta, expr const & meta_type, substitution const & s,\n name_generator const & \/* ngen *\/) {\n expr const & mvar = get_app_fn(meta);\n if (auto cls_name_it = is_ext_class(C->tc(), meta_type)) {\n name cls_name = *cls_name_it;\n list<expr> const & ctx = C->m_ctx.get_data();\n list<expr> local_insts;\n if (C->use_local_instances())\n local_insts = get_local_instances(C->tc(), ctx, cls_name);\n list<name> insts = get_class_instances(env, cls_name);\n list<tactic_hint_entry> tacs;\n if (!s.is_assigned(mvar))\n tacs = get_tactic_hints(env, cls_name);\n if (empty(local_insts) && empty(insts) && empty(tacs))\n return lazy_list<constraints>(); \/\/ nothing to be done\n \/\/ we are always strict with placeholders associated with classes\n bool ignore_failure = false;\n return choose(std::make_shared<placeholder_elaborator>(C, meta, meta_type, local_insts, insts, tacs,\n j, ignore_failure));\n } else if (s.is_assigned(mvar)) {\n \/\/ if the metavariable is assigned and it is not a class, then we just ignore it, and return\n \/\/ the an empty set of constraints.\n return lazy_list<constraints>(constraints());\n } else {\n list<tactic_hint_entry> tacs = get_tactic_hints(env);\n bool ignore_failure = !is_strict;\n return choose(std::make_shared<placeholder_elaborator>(C, meta, meta_type, list<expr>(), list<name>(),\n tacs, j, ignore_failure));\n }\n };\n bool owner = false;\n bool relax = C->m_relax;\n return mk_choice_cnstr(m, choice_fn, to_delay_factor(cnstr_group::ClassInstance),\n owner, j, relax);\n}\n\npair<expr, constraint> mk_placeholder_elaborator(std::shared_ptr<placeholder_context> const & C,\n bool is_strict, optional<expr> const & type, tag g) {\n expr m = C->m_ctx.mk_meta(C->m_ngen, type, g);\n constraint c = mk_placeholder_cnstr(C, m, is_strict);\n return mk_pair(m, c);\n}\n\nconstraint mk_placeholder_root_cnstr(std::shared_ptr<placeholder_context> const & C, expr const & m, bool is_strict,\n unifier_config const & cfg, unsigned delay_factor) {\n environment const & env = C->env();\n justification j = mk_failed_to_synthesize_jst(env, m);\n auto choice_fn = [=](expr const & meta, expr const & meta_type, substitution const & s,\n name_generator const & ngen) {\n if (has_expr_metavar(meta_type)) {\n if (delay_factor < to_delay_factor(cnstr_group::ClassInstance)) {\n constraint delayed_c = mk_placeholder_root_cnstr(C, m, is_strict, cfg, delay_factor+1);\n return lazy_list<constraints>(constraints(delayed_c));\n }\n }\n expr const & mvar = get_app_fn(meta);\n if (!is_ext_class(C->tc(), meta_type) && s.is_assigned(mvar)) {\n \/\/ see mk_placeholder_cnstr\n return lazy_list<constraints>(constraints());\n }\n pair<expr, justification> mj = update_meta(meta, s);\n expr new_meta = mj.first;\n justification new_j = mj.second;\n constraint c = mk_placeholder_cnstr(C, new_meta, is_strict);\n unifier_config new_cfg(cfg);\n new_cfg.m_discard = false;\n new_cfg.m_use_exceptions = false;\n unify_result_seq seq = unify(env, 1, &c, ngen, new_cfg);\n return map2<constraints>(seq, [=](pair<substitution, constraints> const & p) {\n substitution new_s = p.first;\n if (!new_s.is_expr_assigned(mlocal_name(get_app_fn(new_meta))))\n constraints();\n constraints postponed = map(p.second,\n [&](constraint const & c) {\n \/\/ we erase internal justifications\n return update_justification(c, new_j);\n });\n metavar_closure cls(new_meta);\n cls.add(meta_type);\n bool relax = C->m_relax;\n constraints cs = cls.mk_constraints(new_s, new_j, relax);\n return append(cs, postponed);\n });\n };\n bool owner = false;\n bool relax = C->m_relax;\n return mk_choice_cnstr(m, choice_fn, delay_factor, owner, j, relax);\n}\n\n\/** \\brief Create a metavariable, and attach choice constraint for generating\n solutions using class-instances and tactic-hints.\n*\/\npair<expr, constraint> mk_placeholder_elaborator(\n environment const & env, io_state const & ios, local_context const & ctx,\n name const & prefix, bool relax, bool use_local_instances,\n bool is_strict, optional<expr> const & type, tag g, unifier_config const & cfg) {\n auto C = std::make_shared<placeholder_context>(env, ios, ctx, prefix, relax, use_local_instances);\n expr m = C->m_ctx.mk_meta(C->m_ngen, type, g);\n constraint c = mk_placeholder_root_cnstr(C, m, is_strict, cfg, to_delay_factor(cnstr_group::Basic));\n return mk_pair(m, c);\n}\n}\n<commit_msg>fix(frontends\/lean\/placeholder_elaborator): missing 'return'<commit_after>\/*\nCopyright (c) 2014 Microsoft Corporation. All rights reserved.\nReleased under Apache 2.0 license as described in the file LICENSE.\n\nAuthor: Leonardo de Moura\n*\/\n#include \"util\/lazy_list_fn.h\"\n#include \"util\/flet.h\"\n#include \"kernel\/instantiate.h\"\n#include \"kernel\/abstract.h\"\n#include \"library\/unifier.h\"\n#include \"library\/reducible.h\"\n#include \"library\/metavar_closure.h\"\n#include \"library\/error_handling\/error_handling.h\"\n#include \"frontends\/lean\/util.h\"\n#include \"frontends\/lean\/class.h\"\n#include \"frontends\/lean\/tactic_hint.h\"\n#include \"frontends\/lean\/local_context.h\"\n#include \"frontends\/lean\/choice_iterator.h\"\n\nnamespace lean {\n\/** \\brief Context for handling placeholder metavariable choice constraint *\/\nstruct placeholder_context {\n io_state m_ios;\n name_generator m_ngen;\n type_checker_ptr m_tc;\n local_context m_ctx;\n bool m_relax;\n bool m_use_local_instances;\n placeholder_context(environment const & env, io_state const & ios, local_context const & ctx,\n name const & prefix, bool relax, bool use_local_instances):\n m_ios(ios),\n m_ngen(prefix),\n m_tc(mk_type_checker(env, m_ngen.mk_child(), relax)),\n m_ctx(ctx),\n m_relax(relax),\n m_use_local_instances(use_local_instances) {\n }\n\n environment const & env() const { return m_tc->env(); }\n io_state const & ios() const { return m_ios; }\n bool use_local_instances() const { return m_use_local_instances; }\n type_checker & tc() const { return *m_tc; }\n};\n\npair<expr, constraint> mk_placeholder_elaborator(std::shared_ptr<placeholder_context> const & C,\n bool is_strict, optional<expr> const & type, tag g);\n\n\/** \\brief Whenever the elaborator finds a placeholder '_' or introduces an\n implicit argument, it creates a metavariable \\c ?m. It also creates a\n delayed choice constraint (?m in fn).\n\n The function \\c fn produces a stream of alternative solutions for ?m.\n In this case, \\c fn will do the following:\n 1) if the elaborated type of ?m is a 'class' C, then the stream will start with\n a) all local instances of class C (if elaborator.local_instances == true)\n b) solutions produced by tactic_hints for class C\n\n 2) if the elaborated type of ?m is not a class, then the stream will only contain\n the solutions produced by tactic_hints.\n\n The unifier only process delayed choice constraints when there are no other kind\n of constraint to be processed.\n\n This is a helper class for implementing this choice function.\n*\/\nstruct placeholder_elaborator : public choice_iterator {\n std::shared_ptr<placeholder_context> m_C;\n expr m_meta;\n \/\/ elaborated type of the metavariable\n expr m_meta_type;\n \/\/ local instances that should also be included in the\n \/\/ class-instance resolution.\n \/\/ This information is retrieved from the local context\n list<expr> m_local_instances;\n \/\/ global declaration names that are class instances.\n \/\/ This information is retrieved using #get_class_instances.\n list<name> m_instances;\n \/\/ Tactic hints for the class\n list<tactic_hint_entry> m_tactics;\n \/\/ result produce by last executed tactic.\n proof_state_seq m_tactic_result;\n justification m_jst;\n\n placeholder_elaborator(std::shared_ptr<placeholder_context> const & C,\n expr const & meta, expr const & meta_type,\n list<expr> const & local_insts, list<name> const & instances,\n list<tactic_hint_entry> const & tacs,\n justification const & j, bool ignore_failure):\n choice_iterator(ignore_failure), m_C(C),\n m_meta(meta), m_meta_type(meta_type),\n m_local_instances(local_insts), m_instances(instances),\n m_tactics(tacs),\n m_jst(j) {\n }\n\n constraints mk_constraints(constraint const & c, buffer<constraint> const & cs) {\n return cons(c, to_list(cs.begin(), cs.end()));\n }\n\n optional<constraints> try_instance(expr const & inst, expr const & inst_type) {\n type_checker & tc = m_C->tc();\n name_generator & ngen = m_C->m_ngen;\n tag g = inst.get_tag();\n local_context & ctx = m_C->m_ctx;\n try {\n flet<local_context> scope(ctx, ctx);\n buffer<expr> locals;\n expr meta_type = m_meta_type;\n while (true) {\n meta_type = tc.whnf(meta_type).first;\n if (!is_pi(meta_type))\n break;\n expr local = mk_local(ngen.next(), binding_name(meta_type),\n binding_domain(meta_type), binding_info(meta_type));\n ctx.add_local(local);\n locals.push_back(local);\n meta_type = instantiate(binding_body(meta_type), local);\n }\n expr type = inst_type;\n expr r = inst;\n buffer<constraint> cs;\n while (true) {\n type = tc.whnf(type).first;\n if (!is_pi(type))\n break;\n bool is_strict = true;\n pair<expr, constraint> ac = mk_placeholder_elaborator(m_C, is_strict,\n some_expr(binding_domain(type)), g);\n expr arg = ac.first;\n cs.push_back(ac.second);\n r = mk_app(r, arg).set_tag(g);\n type = instantiate(binding_body(type), arg);\n }\n r = Fun(locals, r);\n bool relax = m_C->m_relax;\n constraint c = mk_eq_cnstr(m_meta, r, m_jst, relax);\n return optional<constraints>(mk_constraints(c, cs));\n } catch (exception &) {\n return optional<constraints>();\n }\n }\n\n optional<constraints> try_instance(name const & inst) {\n environment const & env = m_C->env();\n if (auto decl = env.find(inst)) {\n name_generator & ngen = m_C->m_ngen;\n buffer<level> ls_buffer;\n unsigned num_univ_ps = length(decl->get_univ_params());\n for (unsigned i = 0; i < num_univ_ps; i++)\n ls_buffer.push_back(mk_meta_univ(ngen.next()));\n levels ls = to_list(ls_buffer.begin(), ls_buffer.end());\n expr inst_cnst = copy_tag(m_meta, mk_constant(inst, ls));\n expr inst_type = instantiate_type_univ_params(*decl, ls);\n return try_instance(inst_cnst, inst_type);\n } else {\n return optional<constraints>();\n }\n }\n\n optional<constraints> get_next_tactic_result() {\n while (auto next = m_tactic_result.pull()) {\n m_tactic_result = next->second;\n if (!empty(next->first.get_goals()))\n continue; \/\/ has unsolved goals\n substitution subst = next->first.get_subst();\n expr const & mvar = get_app_fn(m_meta);\n bool relax = m_C->m_relax;\n constraints cs = metavar_closure(m_meta_type).mk_constraints(subst, m_jst, relax);\n constraint c = mk_eq_cnstr(mvar, subst.instantiate(mvar), m_jst, relax);\n return some(cons(c, cs));\n }\n return optional<constraints>();\n }\n\n virtual optional<constraints> next() {\n while (!empty(m_local_instances)) {\n expr inst = head(m_local_instances);\n m_local_instances = tail(m_local_instances);\n if (!is_local(inst))\n continue;\n if (auto r = try_instance(inst, mlocal_type(inst)))\n return r;\n }\n while (!empty(m_instances)) {\n name inst = head(m_instances);\n m_instances = tail(m_instances);\n if (auto cs = try_instance(inst))\n return cs;\n }\n if (auto cs = get_next_tactic_result())\n return cs;\n while (!empty(m_tactics)) {\n tactic const & tac = head(m_tactics).get_tactic();\n m_tactics = tail(m_tactics);\n proof_state ps(goals(goal(m_meta, m_meta_type)), substitution(), m_C->m_ngen.mk_child());\n try {\n m_tactic_result = tac(m_C->env(), m_C->ios(), ps);\n if (auto cs = get_next_tactic_result())\n return cs;\n } catch (exception &) {}\n }\n return optional<constraints>();\n }\n};\n\n\nconstraint mk_placeholder_cnstr(std::shared_ptr<placeholder_context> const & C, expr const & m, bool is_strict) {\n environment const & env = C->env();\n justification j = mk_failed_to_synthesize_jst(env, m);\n auto choice_fn = [=](expr const & meta, expr const & meta_type, substitution const & s,\n name_generator const & \/* ngen *\/) {\n expr const & mvar = get_app_fn(meta);\n if (auto cls_name_it = is_ext_class(C->tc(), meta_type)) {\n name cls_name = *cls_name_it;\n list<expr> const & ctx = C->m_ctx.get_data();\n list<expr> local_insts;\n if (C->use_local_instances())\n local_insts = get_local_instances(C->tc(), ctx, cls_name);\n list<name> insts = get_class_instances(env, cls_name);\n list<tactic_hint_entry> tacs;\n if (!s.is_assigned(mvar))\n tacs = get_tactic_hints(env, cls_name);\n if (empty(local_insts) && empty(insts) && empty(tacs))\n return lazy_list<constraints>(); \/\/ nothing to be done\n \/\/ we are always strict with placeholders associated with classes\n bool ignore_failure = false;\n return choose(std::make_shared<placeholder_elaborator>(C, meta, meta_type, local_insts, insts, tacs,\n j, ignore_failure));\n } else if (s.is_assigned(mvar)) {\n \/\/ if the metavariable is assigned and it is not a class, then we just ignore it, and return\n \/\/ the an empty set of constraints.\n return lazy_list<constraints>(constraints());\n } else {\n list<tactic_hint_entry> tacs = get_tactic_hints(env);\n bool ignore_failure = !is_strict;\n return choose(std::make_shared<placeholder_elaborator>(C, meta, meta_type, list<expr>(), list<name>(),\n tacs, j, ignore_failure));\n }\n };\n bool owner = false;\n bool relax = C->m_relax;\n return mk_choice_cnstr(m, choice_fn, to_delay_factor(cnstr_group::ClassInstance),\n owner, j, relax);\n}\n\npair<expr, constraint> mk_placeholder_elaborator(std::shared_ptr<placeholder_context> const & C,\n bool is_strict, optional<expr> const & type, tag g) {\n expr m = C->m_ctx.mk_meta(C->m_ngen, type, g);\n constraint c = mk_placeholder_cnstr(C, m, is_strict);\n return mk_pair(m, c);\n}\n\nconstraint mk_placeholder_root_cnstr(std::shared_ptr<placeholder_context> const & C, expr const & m, bool is_strict,\n unifier_config const & cfg, unsigned delay_factor) {\n environment const & env = C->env();\n justification j = mk_failed_to_synthesize_jst(env, m);\n auto choice_fn = [=](expr const & meta, expr const & meta_type, substitution const & s,\n name_generator const & ngen) {\n if (has_expr_metavar(meta_type)) {\n if (delay_factor < to_delay_factor(cnstr_group::ClassInstance)) {\n constraint delayed_c = mk_placeholder_root_cnstr(C, m, is_strict, cfg, delay_factor+1);\n return lazy_list<constraints>(constraints(delayed_c));\n }\n }\n expr const & mvar = get_app_fn(meta);\n if (!is_ext_class(C->tc(), meta_type) && s.is_assigned(mvar)) {\n \/\/ see mk_placeholder_cnstr\n return lazy_list<constraints>(constraints());\n }\n pair<expr, justification> mj = update_meta(meta, s);\n expr new_meta = mj.first;\n justification new_j = mj.second;\n constraint c = mk_placeholder_cnstr(C, new_meta, is_strict);\n unifier_config new_cfg(cfg);\n new_cfg.m_discard = false;\n new_cfg.m_use_exceptions = false;\n unify_result_seq seq = unify(env, 1, &c, ngen, new_cfg);\n return map2<constraints>(seq, [=](pair<substitution, constraints> const & p) {\n substitution new_s = p.first;\n if (!new_s.is_expr_assigned(mlocal_name(get_app_fn(new_meta))))\n return constraints();\n constraints postponed = map(p.second,\n [&](constraint const & c) {\n \/\/ we erase internal justifications\n return update_justification(c, new_j);\n });\n metavar_closure cls(new_meta);\n cls.add(meta_type);\n bool relax = C->m_relax;\n constraints cs = cls.mk_constraints(new_s, new_j, relax);\n return append(cs, postponed);\n });\n };\n bool owner = false;\n bool relax = C->m_relax;\n return mk_choice_cnstr(m, choice_fn, delay_factor, owner, j, relax);\n}\n\n\/** \\brief Create a metavariable, and attach choice constraint for generating\n solutions using class-instances and tactic-hints.\n*\/\npair<expr, constraint> mk_placeholder_elaborator(\n environment const & env, io_state const & ios, local_context const & ctx,\n name const & prefix, bool relax, bool use_local_instances,\n bool is_strict, optional<expr> const & type, tag g, unifier_config const & cfg) {\n auto C = std::make_shared<placeholder_context>(env, ios, ctx, prefix, relax, use_local_instances);\n expr m = C->m_ctx.mk_meta(C->m_ngen, type, g);\n constraint c = mk_placeholder_root_cnstr(C, m, is_strict, cfg, to_delay_factor(cnstr_group::Basic));\n return mk_pair(m, c);\n}\n}\n<|endoftext|>"} {"text":"<commit_before>\/* IBM_PROLOG_BEGIN_TAG *\/\n\/* This is an automatically generated prolog. *\/\n\/* *\/\n\/* $Source: src\/import\/chips\/p9\/utils\/imageProcs\/p9_tor.H $ *\/\n\/* *\/\n\/* OpenPOWER HostBoot Project *\/\n\/* *\/\n\/* Contributors Listed Below - COPYRIGHT 2016,2019 *\/\n\/* [+] International Business Machines Corp. *\/\n\/* *\/\n\/* *\/\n\/* Licensed under the Apache License, Version 2.0 (the \"License\"); *\/\n\/* you may not use this file except in compliance with the License. *\/\n\/* You may obtain a copy of the License at *\/\n\/* *\/\n\/* http:\/\/www.apache.org\/licenses\/LICENSE-2.0 *\/\n\/* *\/\n\/* Unless required by applicable law or agreed to in writing, software *\/\n\/* distributed under the License is distributed on an \"AS IS\" BASIS, *\/\n\/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or *\/\n\/* implied. See the License for the specific language governing *\/\n\/* permissions and limitations under the License. *\/\n\/* *\/\n\/* IBM_PROLOG_END_TAG *\/\n#ifndef _P9_TOR_H_\n#define _P9_TOR_H_\n\n#include \"p9_ring_identification.H\"\n#include \"p9_ringId.H\"\n\nnamespace P9_TOR\n{\n\n#define NUM_RING_IDS P9_NUM_RINGS\n\ntypedef struct\n{\n uint32_t sizeOfThis;\n uint16_t sizeOfCmsk;\n uint16_t sizeOfMeta; \/\/ Exact size of meta data. Arbitrary size. Not null terminated.\n} RingLayout_t;\n\n\n\/\/\n\/\/ Temporary define until in TOR header by Giri.\n\/\/\n\/\/\n\/\/ Temporary define until in TOR header by Giri.\n\/\/\ntypedef struct\n{\n uint32_t TorNumDdLevels;\n uint32_t reserved;\n} TorNumDdLevels_t;\n\ntypedef struct\n{\n uint32_t TorDdLevelAndOffset;\n uint32_t TorDdBlockSize;\n} TorDdLevelBlock_t;\n\ntypedef struct\n{\n uint32_t TorPpeTypeOffset;\n uint32_t TorPpeBlockSize;\n} TorPpeBlock_t;\n\n\n#define IMGBUILD_TGR_RING_FOUND 0\n#define IMGBUILD_TGR_RING_BLOCKS_FOUND 0\n#define IMGBUILD_TGR_RING_NOT_FOUND 1 \/\/ Ring is not found in HW image.\n#define IMGBUILD_TGR_INVALID_RING_ID 2 \/\/ Ring is invalid or mismatch.\n#define IMGBUILD_TGR_AMBIGUOUS_API_PARMS 3 \/\/ Ring search in HW iamge got ambiguous condition.\n#define IMGBUILD_TGR_SECTION_NOT_FOUND 4\n#define IMGBUILD_TGR_DD_LVL_INFO_NOT_FOUND 5\n#define IMGBUILD_TGR_OP_BUFFER_INVALID 6\n#define IMGBUILD_TGR_OP_BUFFER_SIZE_EXCEEDED 7\n#define IMGBUILD_INVALID_INSTANCEID 8\n#define IMGBUILD_TGR_IMAGE_DOES_NOT_SUPPORT_CME 10\n#define IMGBUILD_TGR_IMAGE_DOES_NOT_SUPPORT_SGPE 11\n#define IMGBUILD_TGR_IMAGE_DOES_NOT_SUPPORT_DD_LEVEL 12\n#define IMGBUILD_TGR_IMAGE_DOES_NOT_SUPPORT_PPE_LEVEL 13\n\n\nextern const char* ringVariantName[];\nextern const char* ppeTypeName[];\n\n\ntypedef enum\nRingBlockType \/\/ Different options to extract data using tor_get_ring API\n{\n SINGLE_RING = 0x00,\n DD_LEVEL_RINGS = 0x01,\n PPE_LEVEL_RINGS = 0x02,\n CPLT_LEVEL_RINGS = 0x03\n} RingBlockType_t;\n\n\ntypedef enum RingType \/\/ Different type of Rings\n{\n COMMON = 0x00,\n INSTANCE = 0x01,\n ALLRING = 0x02\n} RingType_t;\n\n\n\ntypedef enum RingVariant \/\/ Base variables\n{\n BASE = 0x00,\n CC = 0x01,\n RL = 0x02,\n OVERRIDE = 0x03,\n OVERLAY = 0x04,\n NUM_RING_VARIANTS = 0x05,\n NOT_VALID = 0xff\n} RingVariant_t;\n\n\n\/\/\n\/\/ PPE types\n\/\/\ntypedef enum PpeType\n{\n SBE = 0x00, \/\/ Ppe type partition in Ringsection\n CME = 0x01,\n SGPE = 0x02,\n NUM_PPE_TYPES = 0x03\n} PpeType_t;\n\n\n\ntypedef enum RingSectionId\n{\n SECTION_RING = 0x00, \/\/.ring section ID\n SECTION_OVRD = 0x01, \/\/.Override section ID\n SECTION_OVRL = 0x02 \/\/.Overlay section ID\n} RingSectionId_t;\n\ntypedef enum SbeTorId\n{\n PERV_CPLT = 0,\n N0_CPLT = 1,\n N1_CPLT = 2,\n N2_CPLT = 3,\n N3_CPLT = 4,\n XB_CPLT = 5,\n MC_CPLT = 6,\n OB0_CPLT = 7,\n OB1_CPLT = 8,\n OB2_CPLT = 9,\n OB3_CPLT = 10,\n PCI0_CPLT = 11,\n PCI1_CPLT = 12,\n PCI2_CPLT = 13,\n EQ_CPLT = 14,\n EC_CPLT = 15,\n SBE_NOOF_CHIPLETS = 16\n} SbeTorId_t;\ntypedef enum CmeTorId\n{\n CME0_CPLT = 0,\n CME1_CPLT = 1,\n CME2_CPLT = 2,\n CME3_CPLT = 3,\n CME4_CPLT = 4,\n CME5_CPLT = 5,\n CME6_CPLT = 6,\n CME7_CPLT = 7,\n CME8_CPLT = 8,\n CME9_CPLT = 9,\n CME10_CPLT = 10,\n CME11_CPLT = 11,\n CME_NOOF_CHIPLETS = 12\n} CmeTorId_t;\n\/\/\/\n\/\/\/ ****************************************************************************\n\/\/\/ Function declares.\n\/\/\/ ****************************************************************************\n\/\/\/\n\n\nint get_ring_from_sbe_image ( void*\n i_ringSectionPtr, \/\/ Image pointer\n uint64_t i_magic, \/\/ Image Magic Number\n RingID i_ringId, \/\/ Unique ring ID\n uint16_t i_ddLevel, \/\/ DD level details\n RingType_t& io_RingType, \/\/ 0: Common 1: Instance\n RingVariant_t i_RingVariant, \/\/ Base, cache contained, Risk level,\n \/\/ Override and Overlay\n uint8_t& io_instanceId, \/\/ required Instance\n RingBlockType_t RingBlockType, \/\/ 0: single ring, 1: ddLevel block\n void** io_ringBlockPtr, \/\/ RS4 Container data or block data\n uint32_t& io_ringBlockSize, \/\/ size of data copied into ring block pointer\n char* o_ringName, \/\/ Name of ring\n uint32_t dbgl); \/\/ Debug option\n\nint get_ring_from_sgpe_image ( void*\n i_ringSectionPtr, \/\/ Image pointer\n RingID i_ringId, \/\/ Unique ring ID\n uint16_t i_ddLevel, \/\/ DD level details\n RingType_t& io_RingType, \/\/ 0: Common 1: Instance\n RingVariant_t i_RingVariant, \/\/ Base, cache contained, Risk level,\n \/\/ Override and Overlay\n uint8_t& io_instanceId, \/\/ required Instance\n RingBlockType_t RingBlockType, \/\/ 0: single ring, 1: ddLevel block\n void** io_ringBlockPtr, \/\/ RS4 Container data or block data\n uint32_t& io_ringBlockSize, \/\/ size of data copied into ring block pointer\n char* o_ringName, \/\/ Name of ring\n uint32_t dbgl); \/\/ Debug option\n\nint get_ring_from_cme_image ( void* i_ringSectionPtr, \/\/ Image pointer\n RingID i_ringId, \/\/ Unique ring ID\n uint16_t i_ddLevel, \/\/ DD level details\n RingType_t& io_RingType, \/\/ 0: Common 1: Instance\n RingVariant_t i_RingVariant, \/\/ Base, cache contained, Risk level,\n \/\/ Override and Overlay\n uint8_t& io_instanceId, \/\/ required Instance\n RingBlockType_t RingBlockType, \/\/ 0: single ring, 1: ddLevel block\n void** io_ringBlockPtr, \/\/ RS4 Container data or block data\n uint32_t& io_ringBlockSize, \/\/ size of data copied into ring block pointer\n char* o_ringName, \/\/ Name of ring\n uint32_t dbgl); \/\/ Debug option\n\nint tor_get_ring( void*\n i_ringSectionPtr, \/\/ Ring address Ptr any of .rings, .overrides and .overlays.\n uint64_t i_magic, \/\/ Image Magic Number\n RingID i_ringId, \/\/ Unique ring ID\n uint16_t i_ddLevel, \/\/ DD level info\n PpeType_t i_PpeType, \/\/ PPE type : SBE, CME, etc\n RingType_t& io_RingType, \/\/ 0: Common 1: Instance\n RingVariant_t i_RingVariant, \/\/ Base, Cache etc\n uint8_t& io_instanceId, \/\/ chiplet instance ID\n RingBlockType_t i_RingBlockType, \/\/ 0: single ring, 1: ring block\n void** io_ringBlockPtr, \/\/ Addr of ring buffer\n uint32_t& io_ringBlockSize, \/\/ size of ring data\n char* o_ringName, \/\/ Ring name\n uint32_t i_dbgl = 0); \/\/ Debug option\n\nint tor_get_single_ring ( void*\n i_ringSectionPt, \/\/ Ring address Ptr any of .rings, .overrides and .overlays.\n uint16_t i_ddLevel, \/\/ DD level info\n RingID i_ringId, \/\/ Unique ring ID\n PpeType_t i_PpeType, \/\/ ppe Type\n RingVariant_t i_RingVariant, \/\/ Base, cache contained, etc\n uint8_t i_instanceId, \/\/ Chiplet Instance ID\n void** io_ringBlockPtr, \/\/ Addr of ring buffer\n uint32_t& io_ringBlockSize, \/\/ size of ring data\n uint32_t i_dbgl = 0); \/\/ Debug option\n\nint tor_get_block_of_rings ( void*\n i_ringSectionPt, \/\/ Ring address Ptr any of .rings, .overrides and .overlays.\n uint16_t i_ddLevel, \/\/ DD level\n PpeType_t i_PpeType, \/\/ ppe Type\n RingType_t i_RingType, \/\/ Common Or Instance\n RingVariant_t i_RingVariant, \/\/ base,cache,etc\n uint8_t i_instanceId, \/\/ Chiplet Instance ID\n void** io_ringBlockPtr, \/\/ Addr of ring buffer\n uint32_t& io_ringBlockSize, \/\/ size of ring data\n uint32_t i_dbgl = 0); \/\/ Debug option\n};\n\n#endif \/\/_P9_TOR_H_\n<commit_msg>Rename tor_get_ring API as tor_access_ring<commit_after>\/* IBM_PROLOG_BEGIN_TAG *\/\n\/* This is an automatically generated prolog. *\/\n\/* *\/\n\/* $Source: src\/import\/chips\/p9\/utils\/imageProcs\/p9_tor.H $ *\/\n\/* *\/\n\/* OpenPOWER HostBoot Project *\/\n\/* *\/\n\/* Contributors Listed Below - COPYRIGHT 2016,2019 *\/\n\/* [+] International Business Machines Corp. *\/\n\/* *\/\n\/* *\/\n\/* Licensed under the Apache License, Version 2.0 (the \"License\"); *\/\n\/* you may not use this file except in compliance with the License. *\/\n\/* You may obtain a copy of the License at *\/\n\/* *\/\n\/* http:\/\/www.apache.org\/licenses\/LICENSE-2.0 *\/\n\/* *\/\n\/* Unless required by applicable law or agreed to in writing, software *\/\n\/* distributed under the License is distributed on an \"AS IS\" BASIS, *\/\n\/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or *\/\n\/* implied. See the License for the specific language governing *\/\n\/* permissions and limitations under the License. *\/\n\/* *\/\n\/* IBM_PROLOG_END_TAG *\/\n#ifndef _P9_TOR_H_\n#define _P9_TOR_H_\n\n#include \"p9_ring_identification.H\"\n#include \"p9_ringId.H\"\n\nnamespace P9_TOR\n{\n\n#define NUM_RING_IDS P9_NUM_RINGS\n\ntypedef struct\n{\n uint32_t sizeOfThis;\n uint16_t sizeOfCmsk;\n uint16_t sizeOfMeta; \/\/ Exact size of meta data. Arbitrary size. Not null terminated.\n} RingLayout_t;\n\n\n\/\/\n\/\/ Temporary define until in TOR header by Giri.\n\/\/\n\/\/\n\/\/ Temporary define until in TOR header by Giri.\n\/\/\ntypedef struct\n{\n uint32_t TorNumDdLevels;\n uint32_t reserved;\n} TorNumDdLevels_t;\n\ntypedef struct\n{\n uint32_t TorDdLevelAndOffset;\n uint32_t TorDdBlockSize;\n} TorDdLevelBlock_t;\n\ntypedef struct\n{\n uint32_t TorPpeTypeOffset;\n uint32_t TorPpeBlockSize;\n} TorPpeBlock_t;\n\n\n#define IMGBUILD_TGR_RING_FOUND 0\n#define IMGBUILD_TGR_RING_BLOCKS_FOUND 0\n#define IMGBUILD_TGR_RING_NOT_FOUND 1 \/\/ Ring is not found in HW image.\n#define IMGBUILD_TGR_INVALID_RING_ID 2 \/\/ Ring is invalid or mismatch.\n#define IMGBUILD_TGR_AMBIGUOUS_API_PARMS 3 \/\/ Ring search in HW iamge got ambiguous condition.\n#define IMGBUILD_TGR_SECTION_NOT_FOUND 4\n#define IMGBUILD_TGR_DD_LVL_INFO_NOT_FOUND 5\n#define IMGBUILD_TGR_OP_BUFFER_INVALID 6\n#define IMGBUILD_TGR_OP_BUFFER_SIZE_EXCEEDED 7\n#define IMGBUILD_INVALID_INSTANCEID 8\n#define IMGBUILD_TGR_IMAGE_DOES_NOT_SUPPORT_CME 10\n#define IMGBUILD_TGR_IMAGE_DOES_NOT_SUPPORT_SGPE 11\n#define IMGBUILD_TGR_IMAGE_DOES_NOT_SUPPORT_DD_LEVEL 12\n#define IMGBUILD_TGR_IMAGE_DOES_NOT_SUPPORT_PPE_LEVEL 13\n\n\nextern const char* ringVariantName[];\nextern const char* ppeTypeName[];\n\n\ntypedef enum\nRingBlockType \/\/ Different options to extract data using tor_access_ring API\n{\n SINGLE_RING = 0x00,\n DD_LEVEL_RINGS = 0x01,\n PPE_LEVEL_RINGS = 0x02,\n CPLT_LEVEL_RINGS = 0x03\n} RingBlockType_t;\n\n\ntypedef enum RingType \/\/ Different type of Rings\n{\n COMMON = 0x00,\n INSTANCE = 0x01,\n ALLRING = 0x02\n} RingType_t;\n\n\n\ntypedef enum RingVariant \/\/ Base variables\n{\n BASE = 0x00,\n CC = 0x01,\n RL = 0x02,\n OVERRIDE = 0x03,\n OVERLAY = 0x04,\n NUM_RING_VARIANTS = 0x05,\n NOT_VALID = 0xff\n} RingVariant_t;\n\n\n\/\/\n\/\/ PPE types\n\/\/\ntypedef enum PpeType\n{\n SBE = 0x00, \/\/ Ppe type partition in Ringsection\n CME = 0x01,\n SGPE = 0x02,\n NUM_PPE_TYPES = 0x03\n} PpeType_t;\n\n\n\ntypedef enum RingSectionId\n{\n SECTION_RING = 0x00, \/\/.ring section ID\n SECTION_OVRD = 0x01, \/\/.Override section ID\n SECTION_OVRL = 0x02 \/\/.Overlay section ID\n} RingSectionId_t;\n\ntypedef enum SbeTorId\n{\n PERV_CPLT = 0,\n N0_CPLT = 1,\n N1_CPLT = 2,\n N2_CPLT = 3,\n N3_CPLT = 4,\n XB_CPLT = 5,\n MC_CPLT = 6,\n OB0_CPLT = 7,\n OB1_CPLT = 8,\n OB2_CPLT = 9,\n OB3_CPLT = 10,\n PCI0_CPLT = 11,\n PCI1_CPLT = 12,\n PCI2_CPLT = 13,\n EQ_CPLT = 14,\n EC_CPLT = 15,\n SBE_NOOF_CHIPLETS = 16\n} SbeTorId_t;\ntypedef enum CmeTorId\n{\n CME0_CPLT = 0,\n CME1_CPLT = 1,\n CME2_CPLT = 2,\n CME3_CPLT = 3,\n CME4_CPLT = 4,\n CME5_CPLT = 5,\n CME6_CPLT = 6,\n CME7_CPLT = 7,\n CME8_CPLT = 8,\n CME9_CPLT = 9,\n CME10_CPLT = 10,\n CME11_CPLT = 11,\n CME_NOOF_CHIPLETS = 12\n} CmeTorId_t;\n\/\/\/\n\/\/\/ ****************************************************************************\n\/\/\/ Function declares.\n\/\/\/ ****************************************************************************\n\/\/\/\n\n\nint get_ring_from_sbe_image ( void*\n i_ringSectionPtr, \/\/ Image pointer\n uint64_t i_magic, \/\/ Image Magic Number\n RingID i_ringId, \/\/ Unique ring ID\n uint16_t i_ddLevel, \/\/ DD level details\n RingType_t& io_RingType, \/\/ 0: Common 1: Instance\n RingVariant_t i_RingVariant, \/\/ Base, cache contained, Risk level,\n \/\/ Override and Overlay\n uint8_t& io_instanceId, \/\/ required Instance\n RingBlockType_t RingBlockType, \/\/ 0: single ring, 1: ddLevel block\n void** io_ringBlockPtr, \/\/ RS4 Container data or block data\n uint32_t& io_ringBlockSize, \/\/ size of data copied into ring block pointer\n char* o_ringName, \/\/ Name of ring\n uint32_t dbgl); \/\/ Debug option\n\nint get_ring_from_sgpe_image ( void*\n i_ringSectionPtr, \/\/ Image pointer\n RingID i_ringId, \/\/ Unique ring ID\n uint16_t i_ddLevel, \/\/ DD level details\n RingType_t& io_RingType, \/\/ 0: Common 1: Instance\n RingVariant_t i_RingVariant, \/\/ Base, cache contained, Risk level,\n \/\/ Override and Overlay\n uint8_t& io_instanceId, \/\/ required Instance\n RingBlockType_t RingBlockType, \/\/ 0: single ring, 1: ddLevel block\n void** io_ringBlockPtr, \/\/ RS4 Container data or block data\n uint32_t& io_ringBlockSize, \/\/ size of data copied into ring block pointer\n char* o_ringName, \/\/ Name of ring\n uint32_t dbgl); \/\/ Debug option\n\nint get_ring_from_cme_image ( void* i_ringSectionPtr, \/\/ Image pointer\n RingID i_ringId, \/\/ Unique ring ID\n uint16_t i_ddLevel, \/\/ DD level details\n RingType_t& io_RingType, \/\/ 0: Common 1: Instance\n RingVariant_t i_RingVariant, \/\/ Base, cache contained, Risk level,\n \/\/ Override and Overlay\n uint8_t& io_instanceId, \/\/ required Instance\n RingBlockType_t RingBlockType, \/\/ 0: single ring, 1: ddLevel block\n void** io_ringBlockPtr, \/\/ RS4 Container data or block data\n uint32_t& io_ringBlockSize, \/\/ size of data copied into ring block pointer\n char* o_ringName, \/\/ Name of ring\n uint32_t dbgl); \/\/ Debug option\n\nint tor_access_ring( void*\n i_ringSectionPtr, \/\/ Ring address Ptr any of .rings, .overrides and .overlays.\n uint64_t i_magic, \/\/ Image Magic Number\n RingID i_ringId, \/\/ Unique ring ID\n uint16_t i_ddLevel, \/\/ DD level info\n PpeType_t i_PpeType, \/\/ PPE type : SBE, CME, etc\n RingType_t& io_RingType, \/\/ 0: Common 1: Instance\n RingVariant_t i_RingVariant, \/\/ Base, Cache etc\n uint8_t& io_instanceId, \/\/ chiplet instance ID\n RingBlockType_t i_RingBlockType, \/\/ 0: single ring, 1: ring block\n void** io_ringBlockPtr, \/\/ Addr of ring buffer\n uint32_t& io_ringBlockSize, \/\/ size of ring data\n char* o_ringName, \/\/ Ring name\n uint32_t i_dbgl = 0); \/\/ Debug option\n\nint tor_get_single_ring ( void*\n i_ringSectionPt, \/\/ Ring address Ptr any of .rings, .overrides and .overlays.\n uint16_t i_ddLevel, \/\/ DD level info\n RingID i_ringId, \/\/ Unique ring ID\n PpeType_t i_PpeType, \/\/ ppe Type\n RingVariant_t i_RingVariant, \/\/ Base, cache contained, etc\n uint8_t i_instanceId, \/\/ Chiplet Instance ID\n void** io_ringBlockPtr, \/\/ Addr of ring buffer\n uint32_t& io_ringBlockSize, \/\/ size of ring data\n uint32_t i_dbgl = 0); \/\/ Debug option\n\nint tor_get_block_of_rings ( void*\n i_ringSectionPt, \/\/ Ring address Ptr any of .rings, .overrides and .overlays.\n uint16_t i_ddLevel, \/\/ DD level\n PpeType_t i_PpeType, \/\/ ppe Type\n RingType_t i_RingType, \/\/ Common Or Instance\n RingVariant_t i_RingVariant, \/\/ base,cache,etc\n uint8_t i_instanceId, \/\/ Chiplet Instance ID\n void** io_ringBlockPtr, \/\/ Addr of ring buffer\n uint32_t& io_ringBlockSize, \/\/ size of ring data\n uint32_t i_dbgl = 0); \/\/ Debug option\n};\n\n#endif \/\/_P9_TOR_H_\n<|endoftext|>"} {"text":"<commit_before>\/** \\copyright\n * Copyright (c) 2014, Balazs Racz\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * - Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n *\n * - Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n * \\file TractionDefs.hxx\n *\n * Static definitions for implementations of the NMRAnet Traction and Traction\n * Proxy protocols.\n *\n * @author Balazs Racz\n * @date 5 May 2014\n *\/\n\n#ifndef _NMRANET_TRACTIONDEFS_HXX_\n#define _NMRANET_TRACTIONDEFS_HXX_\n\n#include <cmath>\n#include <stdint.h>\n\n#include \"nmranet\/Velocity.hxx\"\n#include \"nmranet\/Payload.hxx\"\n\nnamespace nmranet {\n\ntypedef Velocity SpeedType;\n\n\/** Parses a SpeedType value from an unaligned memory address, typically from\n * the input buffer. *\/\nSpeedType fp16_to_speed(const void *fp16);\n\n\/** Renders a SpeedType value to an unaligned memory address, typically to the\n * output buffer.\n *\n * @param speed is the speed to write\n * @param fp16 is an unaligned two-byte location to write the float16 value\n * to.*\/\nvoid speed_to_fp16(SpeedType speed, void *fp16);\n\n\/** @returns NAN as speed. *\/\ninline SpeedType nan_to_speed() {\n SpeedType s;\n s.set_wire(0xFFFFU);\n return s;\n}\n\n\/\/\/ Static constants and helper functions for the Traciton protocol family.\nstruct TractionDefs {\n \/\/\/ This event should be produced by train nodes.\n static const uint64_t IS_TRAIN_EVENT = 0x0101000000000303ULL;\n \/\/\/ This event should be produced by traction proxy nodes.\n static const uint64_t IS_PROXY_EVENT = 0x0101000000000304ULL;\n \/\/\/ Producing this event causes all operations to stop (usually by turning\n \/\/\/ off the command station power output).\n \/\/\/ @TODO : there is a mistake in this constant. It should start with\n \/\/\/ 0100 by the standard (instead of 0101).\n static const uint64_t EMERGENCY_STOP_EVENT = 0x010000000000FFFFULL;\n \/\/\/ Producing this event resumes all operations (usually by turning power\n \/\/\/ back on).\n static const uint64_t CLEAR_EMERGENCY_STOP_EVENT = 0x010000000000FFFEULL;\n\n \/\/\/ Node ID space allocated for DC blocks.\n static const uint64_t NODE_ID_DC_BLOCK = 0x060000000000ULL;\n \/\/\/ Node ID space allocated for DCC locomotives.\n static const uint64_t NODE_ID_DCC = 0x060100000000ULL;\n \/\/\/ Node ID space allocated for TMCC protocol.\n static const uint64_t NODE_ID_TMCC = 0x060200000000ULL;\n \/\/\/ Node ID space allocated for the Marklin-Motorola protocol.\n static const uint64_t NODE_ID_MARKLIN_MOTOROLA = 0x060300000000ULL;\n \/\/\/ Node ID space allocated for the MTH DCS protocol.\n static const uint64_t NODE_ID_MTH_DCS = 0x060400000000ULL;\n\n enum {\n \/\/ Byte 0 of request commands.\n REQ_SET_SPEED = 0x00,\n REQ_SET_FN = 0x01,\n REQ_EMERGENCY_STOP = 0x02,\n\n REQ_QUERY_SPEED = 0x10,\n REQ_QUERY_FN = 0x11,\n\n REQ_CONTROLLER_CONFIG = 0x20,\n REQ_CONSIST_CONFIG = 0x30,\n REQ_TRACTION_MGMT = 0x40,\n\n \/\/ Byte 1 of REQ_CONTROLLER_CONFIG command\n CTRLREQ_ASSIGN_CONTROLLER = 0x01,\n CTRLREQ_RELEASE_CONTROLLER = 0x02,\n CTRLREQ_QUERY_CONTROLLER = 0x03,\n CTRLREQ_NOTIFY_CONTROLLER_CHANGED = 0x04,\n\n \/\/ Byte 1 of REQ_CONSIST_CONFIG command\n CNSTREQ_ATTACH_NODE = 0x01,\n CNSTREQ_DETACH_NODE = 0x02,\n CNSTREQ_QUERY_NODES = 0x03,\n\n \/\/ Byte 1 of REQ_TRACTION_MGMT command\n MGMTREQ_RESERVE = 0x01,\n MGMTREQ_RELEASE = 0x02,\n \/\/ Byte 0 of response commands\n RESP_QUERY_SPEED = REQ_QUERY_SPEED,\n RESP_QUERY_FN = REQ_QUERY_FN,\n RESP_CONTROLLER_CONFIG = REQ_CONTROLLER_CONFIG,\n RESP_CONSISST_CONFIG = REQ_CONSIST_CONFIG,\n RESP_TRACTION_MGMT = REQ_TRACTION_MGMT,\n\n \/\/ Byte 1 of Controller Configuration response\n CTRLRESP_ASSIGN_CONTROLLER = CTRLREQ_ASSIGN_CONTROLLER,\n CTRLRESP_QUERY_CONTROLLER = CTRLREQ_QUERY_CONTROLLER,\n CTRLRESP_NOTIFY_CONTROLLER_CHANGED = CTRLREQ_NOTIFY_CONTROLLER_CHANGED,\n\n \/\/ Byte 2 of assign controller response\n CTRLRESP_ASSIGN_ERROR_TRAIN = 0x02,\n CTRLRESP_ASSIGN_ERROR_CONTROLLER = 0x01,\n\n \/\/ Byte 1 of Consist Configuration response\n CNSTRESP_ATTACH_NODE = CNSTREQ_ATTACH_NODE,\n CNSTRESP_DETACH_NODE = CNSTREQ_DETACH_NODE,\n CNSTRESP_QUERY_NODES = CNSTREQ_QUERY_NODES,\n\n \/\/ Byte 1 of Traction Management replies\n MGMTRESP_RESERVE = MGMTREQ_RESERVE,\n\n\n PROXYREQ_ALLOCATE = 0x01,\n PROXYREQ_ATTACH = 0x02,\n PROXYREQ_DETACH = 0x03,\n PROXYREQ_MANAGE = 0x80,\n\n PROXYRESP_ALLOCATE = PROXYREQ_ALLOCATE,\n PROXYRESP_ATTACH = PROXYREQ_ATTACH,\n PROXYRESP_MANAGE = PROXYREQ_MANAGE,\n\n \/\/ byte 1 of PROXYREQ_MANAGE commands\n PROXYREQ_MANAGE_RESERVE = 0x01,\n PROXYREQ_MANAGE_RELEASE = 0x02,\n\n PROXYRESP_MANAGE_RESERVE_REPLY = 0x01,\n\n \/\/ Legacy Technology IDs from the GenTractionProxyWN.\n PROXYTYPE_DCC = 1,\n PROXYTYPE_DC = 2,\n PROXYTYPE_MARKLIN_DIGITAL = 3,\n PROXYTYPE_MARKLIN_DELTA = 4,\n PROXYTYPE_MARKLIN_MFX = 5,\n PROXYTYPE_SELECTRIX = 6,\n PROXYTYPE_MTH_DCS = 7,\n PROXYTYPE_LIONEL_TMCC = 8,\n \n\n \/** This is the memory space number for accessing an NMRA DCC\n * locomotive's functions via the memory config protocol. *\/\n FUNCTION_CONFIG_MEMORY_SPACE = 0xF9,\n \/\/ These declare the configuration space layout. They are always the\n \/\/ third byte of the address in the configuration memory space, aka\n \/\/ address = type << 16 + offset.\n \/** F0-F28 are at offset 0 to 28 here. *\/\n FNCONFIG_FN = 0x0,\n \/** Binary State Control Instruction long form. Offset 0 to 32767 *\/\n FNCONFIG_BINARYSTATE_LONG = 0x1,\n \/** Binary State Control Instruction short form. Offset 0 to 127 *\/\n FNCONFIG_BINARYSTATE_SHORT = 0x2,\n \/** Analog outputs, defined by NMRA DCC WG Topic 9910241. Offset 0-255,\n * values 0-255 each. *\/\n FNCONFIG_ANALOG_OUTPUT = 0x3\n };\n\n static Payload speed_set_payload(Velocity v) {\n Payload p(3, 0);\n p[0] = REQ_SET_SPEED;\n speed_to_fp16(v, &p[1]);\n return p;\n }\n\n static Payload speed_get_payload() {\n Payload p(1, 0);\n p[0] = REQ_QUERY_SPEED;\n return p;\n }\n\n \/** Parses the response payload of a GET_SPEED packet.\n * @returns true if the last_set_speed value was present and non-NaN.\n * @param p is the response payload.\n * @param v is the velocity that will be set to the speed value. *\/\n static bool speed_get_parse_last(const Payload &p, Velocity *v)\n {\n if (p.size() < 3)\n {\n return false;\n }\n *v = fp16_to_speed(p.data() + 1);\n if (std::isnan(v->speed()))\n {\n return false;\n }\n return true;\n }\n\n static Payload fn_set_payload(unsigned address, uint16_t value) {\n Payload p(6, 0);\n p[0] = REQ_SET_FN;\n p[1] = (address >> 16) & 0xff;\n p[2] = (address >> 8) & 0xff;\n p[3] = address & 0xff;\n p[4] = (value >> 8) & 0xff;\n p[5] = value & 0xff;\n return p;\n }\n\n static Payload fn_get_payload(unsigned address) {\n Payload p(4, 0);\n p[0] = REQ_QUERY_FN;\n p[1] = (address >> 16) & 0xff;\n p[2] = (address >> 8) & 0xff;\n p[3] = address & 0xff;\n return p;\n }\n\n \/** Parses the response payload of a GET_FN packet.\n * @returns true if there is a valid function value.\n * @param p is the response payload.\n * @param value will be set to the output value. *\/\n static bool fn_get_parse(const Payload &p, uint16_t *value)\n {\n if (p.size() < 6)\n {\n return false;\n }\n *value = (((uint16_t)p[4]) << 8) | p[5];\n return true;\n }\n};\n\n} \/\/ namespace nmranet\n\n#endif \/\/_NMRANET_TRACTIONDEFS_HXX_\n<commit_msg>Adds assign and release controller generation helpers.<commit_after>\/** \\copyright\n * Copyright (c) 2014, Balazs Racz\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * - Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n *\n * - Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n * \\file TractionDefs.hxx\n *\n * Static definitions for implementations of the NMRAnet Traction and Traction\n * Proxy protocols.\n *\n * @author Balazs Racz\n * @date 5 May 2014\n *\/\n\n#ifndef _NMRANET_TRACTIONDEFS_HXX_\n#define _NMRANET_TRACTIONDEFS_HXX_\n\n#include <cmath>\n#include <stdint.h>\n\n#include \"nmranet\/Velocity.hxx\"\n#include \"nmranet\/Payload.hxx\"\n#include \"nmranet\/If.hxx\"\n\nnamespace nmranet {\n\ntypedef Velocity SpeedType;\n\n\/** Parses a SpeedType value from an unaligned memory address, typically from\n * the input buffer. *\/\nSpeedType fp16_to_speed(const void *fp16);\n\n\/** Renders a SpeedType value to an unaligned memory address, typically to the\n * output buffer.\n *\n * @param speed is the speed to write\n * @param fp16 is an unaligned two-byte location to write the float16 value\n * to.*\/\nvoid speed_to_fp16(SpeedType speed, void *fp16);\n\n\/** @returns NAN as speed. *\/\ninline SpeedType nan_to_speed() {\n SpeedType s;\n s.set_wire(0xFFFFU);\n return s;\n}\n\n\/\/\/ Static constants and helper functions for the Traciton protocol family.\nstruct TractionDefs {\n \/\/\/ This event should be produced by train nodes.\n static const uint64_t IS_TRAIN_EVENT = 0x0101000000000303ULL;\n \/\/\/ This event should be produced by traction proxy nodes.\n static const uint64_t IS_PROXY_EVENT = 0x0101000000000304ULL;\n \/\/\/ Producing this event causes all operations to stop (usually by turning\n \/\/\/ off the command station power output).\n \/\/\/ @TODO : there is a mistake in this constant. It should start with\n \/\/\/ 0100 by the standard (instead of 0101).\n static const uint64_t EMERGENCY_STOP_EVENT = 0x010000000000FFFFULL;\n \/\/\/ Producing this event resumes all operations (usually by turning power\n \/\/\/ back on).\n static const uint64_t CLEAR_EMERGENCY_STOP_EVENT = 0x010000000000FFFEULL;\n\n \/\/\/ Node ID space allocated for DC blocks.\n static const uint64_t NODE_ID_DC_BLOCK = 0x060000000000ULL;\n \/\/\/ Node ID space allocated for DCC locomotives.\n static const uint64_t NODE_ID_DCC = 0x060100000000ULL;\n \/\/\/ Node ID space allocated for TMCC protocol.\n static const uint64_t NODE_ID_TMCC = 0x060200000000ULL;\n \/\/\/ Node ID space allocated for the Marklin-Motorola protocol.\n static const uint64_t NODE_ID_MARKLIN_MOTOROLA = 0x060300000000ULL;\n \/\/\/ Node ID space allocated for the MTH DCS protocol.\n static const uint64_t NODE_ID_MTH_DCS = 0x060400000000ULL;\n\n enum {\n \/\/ Byte 0 of request commands.\n REQ_SET_SPEED = 0x00,\n REQ_SET_FN = 0x01,\n REQ_EMERGENCY_STOP = 0x02,\n\n REQ_QUERY_SPEED = 0x10,\n REQ_QUERY_FN = 0x11,\n\n REQ_CONTROLLER_CONFIG = 0x20,\n REQ_CONSIST_CONFIG = 0x30,\n REQ_TRACTION_MGMT = 0x40,\n\n \/\/ Byte 1 of REQ_CONTROLLER_CONFIG command\n CTRLREQ_ASSIGN_CONTROLLER = 0x01,\n CTRLREQ_RELEASE_CONTROLLER = 0x02,\n CTRLREQ_QUERY_CONTROLLER = 0x03,\n CTRLREQ_NOTIFY_CONTROLLER_CHANGED = 0x04,\n\n \/\/ Byte 1 of REQ_CONSIST_CONFIG command\n CNSTREQ_ATTACH_NODE = 0x01,\n CNSTREQ_DETACH_NODE = 0x02,\n CNSTREQ_QUERY_NODES = 0x03,\n\n \/\/ Byte 1 of REQ_TRACTION_MGMT command\n MGMTREQ_RESERVE = 0x01,\n MGMTREQ_RELEASE = 0x02,\n \/\/ Byte 0 of response commands\n RESP_QUERY_SPEED = REQ_QUERY_SPEED,\n RESP_QUERY_FN = REQ_QUERY_FN,\n RESP_CONTROLLER_CONFIG = REQ_CONTROLLER_CONFIG,\n RESP_CONSISST_CONFIG = REQ_CONSIST_CONFIG,\n RESP_TRACTION_MGMT = REQ_TRACTION_MGMT,\n\n \/\/ Byte 1 of Controller Configuration response\n CTRLRESP_ASSIGN_CONTROLLER = CTRLREQ_ASSIGN_CONTROLLER,\n CTRLRESP_QUERY_CONTROLLER = CTRLREQ_QUERY_CONTROLLER,\n CTRLRESP_NOTIFY_CONTROLLER_CHANGED = CTRLREQ_NOTIFY_CONTROLLER_CHANGED,\n\n \/\/ Byte 2 of assign controller response\n CTRLRESP_ASSIGN_ERROR_TRAIN = 0x02,\n CTRLRESP_ASSIGN_ERROR_CONTROLLER = 0x01,\n\n \/\/ Byte 1 of Consist Configuration response\n CNSTRESP_ATTACH_NODE = CNSTREQ_ATTACH_NODE,\n CNSTRESP_DETACH_NODE = CNSTREQ_DETACH_NODE,\n CNSTRESP_QUERY_NODES = CNSTREQ_QUERY_NODES,\n\n \/\/ Byte 1 of Traction Management replies\n MGMTRESP_RESERVE = MGMTREQ_RESERVE,\n\n\n PROXYREQ_ALLOCATE = 0x01,\n PROXYREQ_ATTACH = 0x02,\n PROXYREQ_DETACH = 0x03,\n PROXYREQ_MANAGE = 0x80,\n\n PROXYRESP_ALLOCATE = PROXYREQ_ALLOCATE,\n PROXYRESP_ATTACH = PROXYREQ_ATTACH,\n PROXYRESP_MANAGE = PROXYREQ_MANAGE,\n\n \/\/ byte 1 of PROXYREQ_MANAGE commands\n PROXYREQ_MANAGE_RESERVE = 0x01,\n PROXYREQ_MANAGE_RELEASE = 0x02,\n\n PROXYRESP_MANAGE_RESERVE_REPLY = 0x01,\n\n \/\/ Legacy Technology IDs from the GenTractionProxyWN.\n PROXYTYPE_DCC = 1,\n PROXYTYPE_DC = 2,\n PROXYTYPE_MARKLIN_DIGITAL = 3,\n PROXYTYPE_MARKLIN_DELTA = 4,\n PROXYTYPE_MARKLIN_MFX = 5,\n PROXYTYPE_SELECTRIX = 6,\n PROXYTYPE_MTH_DCS = 7,\n PROXYTYPE_LIONEL_TMCC = 8,\n \n\n \/** This is the memory space number for accessing an NMRA DCC\n * locomotive's functions via the memory config protocol. *\/\n FUNCTION_CONFIG_MEMORY_SPACE = 0xF9,\n \/\/ These declare the configuration space layout. They are always the\n \/\/ third byte of the address in the configuration memory space, aka\n \/\/ address = type << 16 + offset.\n \/** F0-F28 are at offset 0 to 28 here. *\/\n FNCONFIG_FN = 0x0,\n \/** Binary State Control Instruction long form. Offset 0 to 32767 *\/\n FNCONFIG_BINARYSTATE_LONG = 0x1,\n \/** Binary State Control Instruction short form. Offset 0 to 127 *\/\n FNCONFIG_BINARYSTATE_SHORT = 0x2,\n \/** Analog outputs, defined by NMRA DCC WG Topic 9910241. Offset 0-255,\n * values 0-255 each. *\/\n FNCONFIG_ANALOG_OUTPUT = 0x3\n };\n\n static Payload speed_set_payload(Velocity v) {\n Payload p(3, 0);\n p[0] = REQ_SET_SPEED;\n speed_to_fp16(v, &p[1]);\n return p;\n }\n\n static Payload speed_get_payload() {\n Payload p(1, 0);\n p[0] = REQ_QUERY_SPEED;\n return p;\n }\n\n \/** Parses the response payload of a GET_SPEED packet.\n * @returns true if the last_set_speed value was present and non-NaN.\n * @param p is the response payload.\n * @param v is the velocity that will be set to the speed value. *\/\n static bool speed_get_parse_last(const Payload &p, Velocity *v)\n {\n if (p.size() < 3)\n {\n return false;\n }\n *v = fp16_to_speed(p.data() + 1);\n if (std::isnan(v->speed()))\n {\n return false;\n }\n return true;\n }\n\n static Payload fn_set_payload(unsigned address, uint16_t value) {\n Payload p(6, 0);\n p[0] = REQ_SET_FN;\n p[1] = (address >> 16) & 0xff;\n p[2] = (address >> 8) & 0xff;\n p[3] = address & 0xff;\n p[4] = (value >> 8) & 0xff;\n p[5] = value & 0xff;\n return p;\n }\n\n static Payload fn_get_payload(unsigned address) {\n Payload p(4, 0);\n p[0] = REQ_QUERY_FN;\n p[1] = (address >> 16) & 0xff;\n p[2] = (address >> 8) & 0xff;\n p[3] = address & 0xff;\n return p;\n }\n\n \/** Parses the response payload of a GET_FN packet.\n * @returns true if there is a valid function value.\n * @param p is the response payload.\n * @param value will be set to the output value. *\/\n static bool fn_get_parse(const Payload &p, uint16_t *value)\n {\n if (p.size() < 6)\n {\n return false;\n }\n *value = (((uint16_t)p[4]) << 8) | p[5];\n return true;\n }\n\n static Payload assign_controller_payload(Node* ctrl) {\n Payload p(9, 0);\n p[0] = REQ_CONTROLLER_CONFIG;\n p[1] = CTRLREQ_ASSIGN_CONTROLLER;\n p[2] = 0;\n node_id_to_data(ctrl->node_id(), &p[3]);\n return p;\n }\n\n static Payload release_controller_payload(Node* ctrl) {\n Payload p(9, 0);\n p[0] = REQ_CONTROLLER_CONFIG;\n p[1] = CTRLREQ_RELEASE_CONTROLLER;\n p[2] = 0;\n node_id_to_data(ctrl->node_id(), &p[3]);\n return p;\n }\n};\n\n} \/\/ namespace nmranet\n\n#endif \/\/_NMRANET_TRACTIONDEFS_HXX_\n<|endoftext|>"} {"text":"<commit_before>\/*\n ChibiOS - Copyright (C) 2006..2015 Giovanni Di Sirio\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n*\/\n\n#include \"ch.h\"\n#include \"hal.h\"\n\n#include \"blink.h\"\n#include \"usbconfig.h\"\n#include \"printf.h\"\n#include \"gitsha1.h\"\n\n#include \"bicycle.h\"\n#include \"kalman.h\"\n#include \"parameters.h\"\n\n#include \"analog.h\"\n#include \"encoder.h\"\n#include <boost\/math\/constants\/constants.hpp>\n\n#include \"printstate.h\"\n#include \"packet\/serialize.h\"\n#include \"packet\/framing.h\"\n\n#include <type_traits>\n\n\nnamespace {\n using bicycle_t = model::Bicycle;\n using kalman_t = observer::Kalman<bicycle_t>;\n\n const float fs = 200; \/\/ sample rate [Hz]\n const float dt = 1.0\/fs; \/\/ sample time [s]\n const float v0 = 5.0; \/\/ forward speed [m\/s]\n\n \/* Kalman filter variance values *\/\n const float sigma0 = 1 * constants::as_radians; \/\/ yaw angle measurement noise variance\n const float sigma1 = 0.008 * constants::as_radians; \/\/ steer angle measurement noise variance\n\n bicycle_t::input_t u; \/* roll torque, steer torque *\/\n bicycle_t::state_t x; \/* yaw angle, roll angle, steer angle, roll rate, steer rate *\/\n bicycle_t::output_t z; \/* yaw angle, steer angle *\/\n\n \/* sensors *\/\n Analog analog;\n Encoder encoder(&GPTD5, \/* CH1, CH2 connected to PA0, PA1 and NOT enabled by board.h *\/\n {PAL_NOLINE, \/* no index channel *\/\n 152000, \/* counts per revolution *\/\n EncoderConfig::filter_t::CAPTURE_64}); \/* 64 * 42 MHz (TIM3 on APB1) = 1.52 us\n * for valid edge *\/\n\n const float max_kistler_torque = 25.0f; \/* maximum measured steer torque *\/\n \/*\n * The voltage output of the Kistler torque sensor is ±10V. With the 12-bit ADC,\n * resolution for LSB is 4.88 mV\/bit or 12.2 mNm\/bit.\n *\/\n const float max_kollmorgen_torque = 10.0f; \/* max torque at 1.00 Arms\/V *\/\n\n const DACConfig dac1cfg1 = {\n .init = 2047U, \/\/ max value is 4095 (12-bit)\n .datamode = DAC_DHRM_12BIT_RIGHT\n };\n\n model::real_t wrap_angle(model::real_t angle) {\n model::real_t a = std::fmod(angle, boost::math::constants::two_pi<model::real_t>());\n if (a >= boost::math::constants::pi<model::real_t>()) {\n a -= boost::math::constants::two_pi<model::real_t>();\n }\n if (a < -boost::math::constants::pi<model::real_t>()) {\n a += boost::math::constants::two_pi<model::real_t>();\n }\n return a;\n }\n\n float rad_to_deg(float angle) {\n return angle * 360 \/ boost::math::constants::two_pi<float>();\n }\n\n std::array<uint8_t, BicyclePose_size> encode_buffer;\n std::array<uint8_t, BicyclePose_size + 1> frame_buffer;\n} \/\/ namespace\n\n\/*\n * Application entry point.\n *\/\nint main(void) {\n\n \/*\n * System initializations.\n * - HAL initialization, this also initializes the configured device drivers\n * and performs the board-specific initializations.\n * - Kernel initialization, the main() function becomes a thread and the\n * RTOS is active.\n *\/\n halInit();\n chSysInit();\n\n \/*\n * Initialize a serial-over-USB CDC driver.\n *\/\n sduObjectInit(&SDU1);\n sduStart(&SDU1, &serusbcfg);\n\n \/*\n * Activate the USB driver and then the USB bus pull-up on D+.\n * Note, a delay is inserted in order to not have to disconnect the cable\n * after a reset.\n *\/\n board_usb_lld_disconnect_bus(); \/\/usbDisconnectBus(serusbcfg.usbp);\n chThdSleepMilliseconds(1500);\n usbStart(serusbcfg.usbp, &usbcfg);\n board_usb_lld_connect_bus(); \/\/usbConnectBus(serusbcfg.usbp);\n\n \/* create the blink thread and print state monitor *\/\n chBlinkThreadCreateStatic();\n \/*\n * Use LINE_TIM4_CH2 (PB7, EXT1-15, J4-B) as a button by\n * connecting\/disconnecting it to ground.\n * *\/\n palSetLineMode(LINE_TIM4_CH2, PAL_MODE_INPUT_PULLUP);\n enablePrintStateMonitor(LINE_TIM4_CH2);\n\n \/*\n * Start sensors.\n * Encoder:\n * Initialize encoder driver 5 on pins PA0, PA1 (EXT2-4, EXT2-8).\n *\/\n palSetLineMode(LINE_TIM5_CH1, PAL_MODE_ALTERNATE(2) | PAL_STM32_PUPDR_FLOATING);\n palSetLineMode(LINE_TIM5_CH2, PAL_MODE_ALTERNATE(2) | PAL_STM32_PUPDR_FLOATING);\n encoder.start();\n analog.start(1000); \/* trigger ADC conversion at 1 kHz *\/\n\n\n \/*\n * Set torque measurement enable line low.\n * The output of the Kistler torque sensor is not valid until after a falling edge\n * on the measurement line and it is held low. The 'LINE_TORQUE_MEAS_EN' line is\n * reversed due to NPN switch Q1.\n *\/\n palClearLine(LINE_TORQUE_MEAS_EN);\n chThdSleepMilliseconds(1);\n palSetLine(LINE_TORQUE_MEAS_EN);\n\n \/*\n * Start DAC1 driver and set output pin as analog as suggested in Reference Manual.\n * The default line configuration is OUTPUT_OPENDRAIN_PULLUP for SPI1_ENC1_NSS\n * and must be changed to use as analog output.\n *\/\n palSetLineMode(LINE_KOLLM_ACTL_TORQUE, PAL_MODE_INPUT_ANALOG);\n dacStart(&DACD1, &dac1cfg1);\n\n \/* initialize bicycle model and states *\/\n model::Bicycle bicycle(v0, dt);\n x.setZero();\n\n \/* initialize Kalman filter *\/\n kalman_t kalman(bicycle,\n parameters::defaultvalue::kalman::Q(dt), \/* process noise cov *\/\n (kalman_t::measurement_noise_covariance_t() <<\n sigma0, 0,\n 0, sigma1).finished(),\n bicycle_t::state_t::Zero(), \/* set initial state estimate to zero *\/\n std::pow(x[1]\/2, 2) * bicycle_t::state_matrix_t::Identity()); \/* error cov *\/\n\n \/*\n * Normal main() thread activity, in this demo it simulates the bicycle\n * dynamics in real-time (roughly).\n *\/\n rtcnt_t kalman_update_time = 0;\n bool print_version_string = true;\n u.setZero(); \/* set both roll and steer torques to zero *\/\n BicyclePose pose = BicyclePose_init_zero;\n while (true) {\n u[1] = static_cast<float>(analog.get_adc12()*2.0f*max_kistler_torque\/4096 -\n max_kistler_torque);\n \/\/float motor_torque = static_cast<float>(\n \/\/ analog.get_adc13()*2.0f*max_kollmorgen_torque\/4096 -\n \/\/ max_kollmorgen_torque);\n\n \/* set measurement vector *\/\n z[0] = wrap_angle(x[0]); \/* yaw angle, just use previous state value *\/\n\n \/*\n * Steer angle, read from encoder (enccnt_t is uint32_t)\n * Convert angle from enccnt_t (unsigned) to corresponding signed type and use negative\n * values for any count over half a revolution.\n *\/\n auto position = static_cast<std::make_signed<enccnt_t>::type>(encoder.count());\n auto rev = static_cast<std::make_signed<enccnt_t>::type>(encoder.config().counts_per_rev);\n if (position > rev \/ 2) {\n position -= rev;\n }\n z[1] = static_cast<float>(position) \/ rev *\n boost::math::constants::two_pi<float>();\n\n \/* observer time\/measurement update (~80 us with real_t = float) *\/\n kalman_update_time = chSysGetRealtimeCounterX();\n kalman.time_update(u);\n kalman.measurement_update(z);\n x = kalman.x();\n x[0] = wrap_angle(x[0]);\n x[1] = wrap_angle(x[1]);\n x[2] = wrap_angle(x[2]);\n kalman_update_time = chSysGetRealtimeCounterX() - kalman_update_time;\n\n \/* generate an example torque output for testing *\/\n float torque = 10.0f * std::sin(\n boost::math::constants::two_pi<float>() *\n ST2S(static_cast<float>(chVTGetSystemTime())));\n dacsample_t aout = static_cast<dacsample_t>(\n (torque\/21.0f * 2048) + 2048); \/* reduce output to half of full range *\/\n dacPutChannelX(&DACD1, 0, aout);\n\n uint8_t bytes_written;\n pose.x = 1;\n pose.y = 2;\n pose.yaw = x[0];\n pose.roll = x[1];\n pose.steer = x[2];\n bytes_written = packet::serialize::encode_bicycle_pose(pose,\n encode_buffer.data(), encode_buffer.size());\n packet::framing::stuff(encode_buffer.data(), frame_buffer.data(), bytes_written);\n\n printst_t s = getPrintState();\n if (s == printst_t::VERSION) {\n if (print_version_string) {\n printf(\"Running firmware version %.7s\\r\\n\", g_GITSHA1);\n print_version_string = false;\n }\n } else if (s == printst_t::NORMAL) {\n packet::framing::unstuff(frame_buffer.data(), encode_buffer.data(), encode_buffer.size());\n if (packet::serialize::decode_bicycle_pose(encode_buffer.data(), &pose, bytes_written)) {\n printf(\"bicycle pose:\\r\\n\\\n \\tx:\\t%0.3f\\r\\n\\\n \\ty:\\t%0.3f\\r\\n\\\n \\tyaw:\\t%0.3f\\r\\n\\\n \\troll:\\t%0.3f\\r\\n\\\n \\tsteer:\\t%0.3f\\r\\n\",\n pose.x, pose.y, pose.yaw, pose.roll, pose.steer);\n }\n \/\/printf(\"encoder count:\\t%u\\r\\n\", encoder.count());\n \/\/printf(\"sensors:\\t%0.3f\\t%0.3f\\t%0.3f\\t%0.3f\\r\\n\",\n \/\/ u[1], motor_torque, rad_to_deg(z[0]), rad_to_deg(z[1]));\n \/\/printf(\"state:\\t%0.2f\\t%0.2f\\t%0.2f\\t%0.2f\\t%0.2f\\r\\n\",\n \/\/ rad_to_deg(x[0]), rad_to_deg(x[1]), rad_to_deg(x[2]), rad_to_deg(x[3]), rad_to_deg(x[4]));\n \/\/printf(\"kalman update time: %U us\\r\\n\",\n \/\/ RTC2US(STM32_SYSCLK, kalman_update_time));\n } else if (s == printst_t::NONE) {\n \/* reset printing of version string *\/\n print_version_string = true;\n }\n chThdSleepMilliseconds(static_cast<systime_t>(1000*dt));\n }\n}\n<commit_msg>Print units for bicycle pose fields<commit_after>\/*\n ChibiOS - Copyright (C) 2006..2015 Giovanni Di Sirio\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n*\/\n\n#include \"ch.h\"\n#include \"hal.h\"\n\n#include \"blink.h\"\n#include \"usbconfig.h\"\n#include \"printf.h\"\n#include \"gitsha1.h\"\n\n#include \"bicycle.h\"\n#include \"kalman.h\"\n#include \"parameters.h\"\n\n#include \"analog.h\"\n#include \"encoder.h\"\n#include <boost\/math\/constants\/constants.hpp>\n\n#include \"printstate.h\"\n#include \"packet\/serialize.h\"\n#include \"packet\/framing.h\"\n\n#include <type_traits>\n\n\nnamespace {\n using bicycle_t = model::Bicycle;\n using kalman_t = observer::Kalman<bicycle_t>;\n\n const float fs = 200; \/\/ sample rate [Hz]\n const float dt = 1.0\/fs; \/\/ sample time [s]\n const float v0 = 5.0; \/\/ forward speed [m\/s]\n\n \/* Kalman filter variance values *\/\n const float sigma0 = 1 * constants::as_radians; \/\/ yaw angle measurement noise variance\n const float sigma1 = 0.008 * constants::as_radians; \/\/ steer angle measurement noise variance\n\n bicycle_t::input_t u; \/* roll torque, steer torque *\/\n bicycle_t::state_t x; \/* yaw angle, roll angle, steer angle, roll rate, steer rate *\/\n bicycle_t::output_t z; \/* yaw angle, steer angle *\/\n\n \/* sensors *\/\n Analog analog;\n Encoder encoder(&GPTD5, \/* CH1, CH2 connected to PA0, PA1 and NOT enabled by board.h *\/\n {PAL_NOLINE, \/* no index channel *\/\n 152000, \/* counts per revolution *\/\n EncoderConfig::filter_t::CAPTURE_64}); \/* 64 * 42 MHz (TIM3 on APB1) = 1.52 us\n * for valid edge *\/\n\n const float max_kistler_torque = 25.0f; \/* maximum measured steer torque *\/\n \/*\n * The voltage output of the Kistler torque sensor is ±10V. With the 12-bit ADC,\n * resolution for LSB is 4.88 mV\/bit or 12.2 mNm\/bit.\n *\/\n const float max_kollmorgen_torque = 10.0f; \/* max torque at 1.00 Arms\/V *\/\n\n const DACConfig dac1cfg1 = {\n .init = 2047U, \/\/ max value is 4095 (12-bit)\n .datamode = DAC_DHRM_12BIT_RIGHT\n };\n\n model::real_t wrap_angle(model::real_t angle) {\n model::real_t a = std::fmod(angle, boost::math::constants::two_pi<model::real_t>());\n if (a >= boost::math::constants::pi<model::real_t>()) {\n a -= boost::math::constants::two_pi<model::real_t>();\n }\n if (a < -boost::math::constants::pi<model::real_t>()) {\n a += boost::math::constants::two_pi<model::real_t>();\n }\n return a;\n }\n\n float rad_to_deg(float angle) {\n return angle * 360 \/ boost::math::constants::two_pi<float>();\n }\n\n std::array<uint8_t, BicyclePose_size> encode_buffer;\n std::array<uint8_t, BicyclePose_size + 1> frame_buffer;\n} \/\/ namespace\n\n\/*\n * Application entry point.\n *\/\nint main(void) {\n\n \/*\n * System initializations.\n * - HAL initialization, this also initializes the configured device drivers\n * and performs the board-specific initializations.\n * - Kernel initialization, the main() function becomes a thread and the\n * RTOS is active.\n *\/\n halInit();\n chSysInit();\n\n \/*\n * Initialize a serial-over-USB CDC driver.\n *\/\n sduObjectInit(&SDU1);\n sduStart(&SDU1, &serusbcfg);\n\n \/*\n * Activate the USB driver and then the USB bus pull-up on D+.\n * Note, a delay is inserted in order to not have to disconnect the cable\n * after a reset.\n *\/\n board_usb_lld_disconnect_bus(); \/\/usbDisconnectBus(serusbcfg.usbp);\n chThdSleepMilliseconds(1500);\n usbStart(serusbcfg.usbp, &usbcfg);\n board_usb_lld_connect_bus(); \/\/usbConnectBus(serusbcfg.usbp);\n\n \/* create the blink thread and print state monitor *\/\n chBlinkThreadCreateStatic();\n \/*\n * Use LINE_TIM4_CH2 (PB7, EXT1-15, J4-B) as a button by\n * connecting\/disconnecting it to ground.\n * *\/\n palSetLineMode(LINE_TIM4_CH2, PAL_MODE_INPUT_PULLUP);\n enablePrintStateMonitor(LINE_TIM4_CH2);\n\n \/*\n * Start sensors.\n * Encoder:\n * Initialize encoder driver 5 on pins PA0, PA1 (EXT2-4, EXT2-8).\n *\/\n palSetLineMode(LINE_TIM5_CH1, PAL_MODE_ALTERNATE(2) | PAL_STM32_PUPDR_FLOATING);\n palSetLineMode(LINE_TIM5_CH2, PAL_MODE_ALTERNATE(2) | PAL_STM32_PUPDR_FLOATING);\n encoder.start();\n analog.start(1000); \/* trigger ADC conversion at 1 kHz *\/\n\n\n \/*\n * Set torque measurement enable line low.\n * The output of the Kistler torque sensor is not valid until after a falling edge\n * on the measurement line and it is held low. The 'LINE_TORQUE_MEAS_EN' line is\n * reversed due to NPN switch Q1.\n *\/\n palClearLine(LINE_TORQUE_MEAS_EN);\n chThdSleepMilliseconds(1);\n palSetLine(LINE_TORQUE_MEAS_EN);\n\n \/*\n * Start DAC1 driver and set output pin as analog as suggested in Reference Manual.\n * The default line configuration is OUTPUT_OPENDRAIN_PULLUP for SPI1_ENC1_NSS\n * and must be changed to use as analog output.\n *\/\n palSetLineMode(LINE_KOLLM_ACTL_TORQUE, PAL_MODE_INPUT_ANALOG);\n dacStart(&DACD1, &dac1cfg1);\n\n \/* initialize bicycle model and states *\/\n model::Bicycle bicycle(v0, dt);\n x.setZero();\n\n \/* initialize Kalman filter *\/\n kalman_t kalman(bicycle,\n parameters::defaultvalue::kalman::Q(dt), \/* process noise cov *\/\n (kalman_t::measurement_noise_covariance_t() <<\n sigma0, 0,\n 0, sigma1).finished(),\n bicycle_t::state_t::Zero(), \/* set initial state estimate to zero *\/\n std::pow(x[1]\/2, 2) * bicycle_t::state_matrix_t::Identity()); \/* error cov *\/\n\n \/*\n * Normal main() thread activity, in this demo it simulates the bicycle\n * dynamics in real-time (roughly).\n *\/\n rtcnt_t kalman_update_time = 0;\n bool print_version_string = true;\n u.setZero(); \/* set both roll and steer torques to zero *\/\n BicyclePose pose = BicyclePose_init_zero;\n while (true) {\n u[1] = static_cast<float>(analog.get_adc12()*2.0f*max_kistler_torque\/4096 -\n max_kistler_torque);\n \/\/float motor_torque = static_cast<float>(\n \/\/ analog.get_adc13()*2.0f*max_kollmorgen_torque\/4096 -\n \/\/ max_kollmorgen_torque);\n\n \/* set measurement vector *\/\n z[0] = wrap_angle(x[0]); \/* yaw angle, just use previous state value *\/\n\n \/*\n * Steer angle, read from encoder (enccnt_t is uint32_t)\n * Convert angle from enccnt_t (unsigned) to corresponding signed type and use negative\n * values for any count over half a revolution.\n *\/\n auto position = static_cast<std::make_signed<enccnt_t>::type>(encoder.count());\n auto rev = static_cast<std::make_signed<enccnt_t>::type>(encoder.config().counts_per_rev);\n if (position > rev \/ 2) {\n position -= rev;\n }\n z[1] = static_cast<float>(position) \/ rev *\n boost::math::constants::two_pi<float>();\n\n \/* observer time\/measurement update (~80 us with real_t = float) *\/\n kalman_update_time = chSysGetRealtimeCounterX();\n kalman.time_update(u);\n kalman.measurement_update(z);\n x = kalman.x();\n x[0] = wrap_angle(x[0]);\n x[1] = wrap_angle(x[1]);\n x[2] = wrap_angle(x[2]);\n kalman_update_time = chSysGetRealtimeCounterX() - kalman_update_time;\n\n \/* generate an example torque output for testing *\/\n float torque = 10.0f * std::sin(\n boost::math::constants::two_pi<float>() *\n ST2S(static_cast<float>(chVTGetSystemTime())));\n dacsample_t aout = static_cast<dacsample_t>(\n (torque\/21.0f * 2048) + 2048); \/* reduce output to half of full range *\/\n dacPutChannelX(&DACD1, 0, aout);\n\n uint8_t bytes_written;\n pose.x = 1;\n pose.y = 2;\n pose.yaw = x[0];\n pose.roll = x[1];\n pose.steer = x[2];\n bytes_written = packet::serialize::encode_bicycle_pose(pose,\n encode_buffer.data(), encode_buffer.size());\n packet::framing::stuff(encode_buffer.data(), frame_buffer.data(), bytes_written);\n\n printst_t s = getPrintState();\n if (s == printst_t::VERSION) {\n if (print_version_string) {\n printf(\"Running firmware version %.7s\\r\\n\", g_GITSHA1);\n print_version_string = false;\n }\n } else if (s == printst_t::NORMAL) {\n packet::framing::unstuff(frame_buffer.data(), encode_buffer.data(), encode_buffer.size());\n pose = BicyclePose_init_zero;\n if (packet::serialize::decode_bicycle_pose(encode_buffer.data(), &pose, bytes_written)) {\n printf(\"bicycle pose:\\r\\n\"\n \"\\tx:\\t%0.3f m\\r\\n\"\n \"\\ty:\\t%0.3f m\\r\\n\",\n pose.x, pose.y);\n printf(\"\\tyaw:\\t%0.3f deg\\r\\n\"\n \"\\troll:\\t%0.3f deg\\r\\n\"\n \"\\tsteer:\\t%0.3f deg\\r\\n\",\n rad_to_deg(pose.yaw), rad_to_deg(pose.roll), rad_to_deg(pose.steer));\n }\n \/\/printf(\"encoder count:\\t%u\\r\\n\", encoder.count());\n \/\/printf(\"sensors:\\t%0.3f\\t%0.3f\\t%0.3f\\t%0.3f\\r\\n\",\n \/\/ u[1], motor_torque, rad_to_deg(z[0]), rad_to_deg(z[1]));\n \/\/printf(\"state:\\t%0.2f\\t%0.2f\\t%0.2f\\t%0.2f\\t%0.2f\\r\\n\",\n \/\/ rad_to_deg(x[0]), rad_to_deg(x[1]), rad_to_deg(x[2]), rad_to_deg(x[3]), rad_to_deg(x[4]));\n \/\/printf(\"kalman update time: %U us\\r\\n\",\n \/\/ RTC2US(STM32_SYSCLK, kalman_update_time));\n } else if (s == printst_t::NONE) {\n \/* reset printing of version string *\/\n print_version_string = true;\n }\n chThdSleepMilliseconds(static_cast<systime_t>(1000*dt));\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n ChibiOS - Copyright (C) 2006..2015 Giovanni Di Sirio\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n*\/\n\n#include \"ch.h\"\n#include \"hal.h\"\n#include \"chprintf.h\"\n\n#include \"blink.h\"\n#include \"usbconfig.h\"\n#include \"bicycle.h\"\n#include \"kalman.h\"\n#include \"parameters.h\"\n\n#include \"analog.h\"\n#include \"encoder.h\"\n#include <boost\/math\/constants\/constants.hpp>\n\n#include <type_traits>\n\nnamespace {\n using bicycle_t = model::Bicycle;\n using kalman_t = observer::Kalman<bicycle_t>;\n\n const float fs = 200; \/\/ sample rate [Hz]\n const float dt = 1.0\/fs; \/\/ sample time [s]\n const float v0 = 5.0; \/\/ forward speed [m\/s]\n\n \/* Kalman filter variance values *\/\n const float sigma0 = 1 * constants::as_radians; \/\/ yaw angle measurement noise variance\n const float sigma1 = 0.008 * constants::as_radians; \/\/ steer angle measurement noise variance\n\n bicycle_t::input_t u; \/* roll torque, steer torque *\/\n bicycle_t::state_t x; \/* yaw angle, roll angle, steer angle, roll rate, steer rate *\/\n bicycle_t::output_t z; \/* yaw angle, steer angle *\/\n\n \/* sensors *\/\n Analog analog;\n Encoder encoder(&GPTD5, \/* CH1, CH2 connected to PA0, PA1 and NOT enabled by board.h *\/\n {PAL_NOLINE, \/* no index channel *\/\n 152000, \/* counts per revolution *\/\n EncoderConfig::filter_t::CAPTURE_64}); \/* 64 * 42 MHz (TIM3 on APB1) = 1.52 us\n * for valid edge *\/\n const float max_kistler_torque = 25.0f; \/* maximum measured steer torque *\/\n\n model::real_t wrap_angle(model::real_t angle) {\n \/*\n * Angle magnitude is assumed to small enough to NOT require multiple\n * additions\/subtractions of 2pi.\n *\/\n if (angle >= boost::math::constants::pi<float>()) {\n angle -= boost::math::constants::two_pi<float>();\n }\n if (angle < -boost::math::constants::pi<float>()) {\n angle += boost::math::constants::two_pi<float>();\n }\n return angle;\n }\n} \/\/ namespace\n\n\/*\n * Application entry point.\n *\/\nint main(void) {\n\n \/*\n * System initializations.\n * - HAL initialization, this also initializes the configured device drivers\n * and performs the board-specific initializations.\n * - Kernel initialization, the main() function becomes a thread and the\n * RTOS is active.\n *\/\n halInit();\n chSysInit();\n\n \/*\n * Initializes a serial-over-USB CDC driver.\n *\/\n sduObjectInit(&SDU1);\n sduStart(&SDU1, &serusbcfg);\n\n \/*\n * Activates the USB driver and then the USB bus pull-up on D+.\n * Note, a delay is inserted in order to not have to disconnect the cable\n * after a reset.\n *\/\n board_usb_lld_disconnect_bus(); \/\/usbDisconnectBus(serusbcfg.usbp);\n chThdSleepMilliseconds(1500);\n usbStart(serusbcfg.usbp, &usbcfg);\n board_usb_lld_connect_bus(); \/\/usbConnectBus(serusbcfg.usbp);\n\n \/* create the example thread *\/\n chBlinkThreadCreateStatic();\n\n \/* initialize bicycle model and states *\/\n model::Bicycle bicycle(v0, dt);\n x.setZero();\n\n \/* initialize Kalman filter *\/\n kalman_t kalman(bicycle,\n parameters::defaultvalue::kalman::Q(dt), \/* process noise cov *\/\n (kalman_t::measurement_noise_covariance_t() <<\n sigma0, 0,\n 0, sigma1).finished(),\n bicycle_t::state_t::Zero(), \/* set initial state estimate to zero *\/\n std::pow(x[1]\/2, 2) * bicycle_t::state_matrix_t::Identity()); \/* error cov *\/\n\n \/*\n * Start sensors.\n * Encoder:\n * Initialize encoder driver 5 on pins PA0, PA1 (EXT2-4, EXT2-8).\n *\/\n palSetLineMode(LINE_TIM5_CH1, PAL_MODE_ALTERNATE(2) | PAL_STM32_PUPDR_FLOATING);\n palSetLineMode(LINE_TIM5_CH2, PAL_MODE_ALTERNATE(2) | PAL_STM32_PUPDR_FLOATING);\n encoder.start();\n analog.start(1000);\n\n \/*\n * Set torque measurement enable line low.\n * The output of the Kistler torque sensor is not valid until after a falling edge\n * on the measurement line and it is held low. The 'LINE_TORQUE_MEAS_EN' line is\n * reversed due to NPN switch Q1.\n *\/\n palClearLine(LINE_TORQUE_MEAS_EN);\n chThdSleepMilliseconds(1);\n palSetLine(LINE_TORQUE_MEAS_EN);\n\n \/*\n * Normal main() thread activity, in this demo it simulates the bicycle\n * dynamics in real-time (roughly).\n *\/\n rtcnt_t kalman_update_time = 0;\n while (true) {\n u.setZero(); \/* set both roll and steer torques to zero *\/\n \/* pulse torque measure signal and read steer torque value *\/\n u[1] = static_cast<float>(analog.get_adc12()*2.0f*max_kistler_torque\/4096 -\n max_kistler_torque);\n\n \/* set measurement vector *\/\n z[0] = x[0]; \/* yaw angle, just use previous state value *\/\n\n \/*\n * Steer angle, read from encoder (enccnt_t is uint32_t)\n * Convert angle from enccnt_t (unsigned) to corresponding signed type and use negative\n * values for any count over half a revolution.\n *\/\n auto position = static_cast<std::make_signed<enccnt_t>::type>(encoder.count());\n auto rev = static_cast<std::make_signed<enccnt_t>::type>(encoder.config().counts_per_rev);\n if (position > rev \/ 2) {\n position -= rev;\n }\n z[1] = static_cast<float>(position) \/\n boost::math::constants::two_pi<float>();\n\n \/* observer time\/measurement update (~80 us with real_t = float) *\/\n kalman_update_time = chSysGetRealtimeCounterX();\n kalman.time_update(u);\n kalman.measurement_update(z);\n x = kalman.x();\n x[0] = wrap_angle(x[0]);\n x[1] = wrap_angle(x[1]);\n x[2] = wrap_angle(x[2]);\n kalman_update_time = chSysGetRealtimeCounterX() - kalman_update_time;\n\n chprintf((BaseSequentialStream*)&SDU1,\n \"sensors:\\t%0.2f\\t%0.2f\\t%0.2f\\r\\n\",\n u[1], z[0], z[1]);\n chprintf((BaseSequentialStream*)&SDU1,\n \"state:\\t%0.2f\\t%0.2f\\t%0.2f\\t%0.2f\\t%0.2f\\r\\n\",\n x[0], x[1], x[2], x[3], x[4]);\n chprintf((BaseSequentialStream*)&SDU1,\n \"kalman update time: %d us\\r\\n\",\n RTC2US(STM32_SYSCLK, kalman_update_time));\n chThdSleepMilliseconds(static_cast<systime_t>(1000*dt));\n }\n}\n<commit_msg>Add note on Kistler torque sensor resolution<commit_after>\/*\n ChibiOS - Copyright (C) 2006..2015 Giovanni Di Sirio\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n*\/\n\n#include \"ch.h\"\n#include \"hal.h\"\n#include \"chprintf.h\"\n\n#include \"blink.h\"\n#include \"usbconfig.h\"\n#include \"bicycle.h\"\n#include \"kalman.h\"\n#include \"parameters.h\"\n\n#include \"analog.h\"\n#include \"encoder.h\"\n#include <boost\/math\/constants\/constants.hpp>\n\n#include <type_traits>\n\nnamespace {\n using bicycle_t = model::Bicycle;\n using kalman_t = observer::Kalman<bicycle_t>;\n\n const float fs = 200; \/\/ sample rate [Hz]\n const float dt = 1.0\/fs; \/\/ sample time [s]\n const float v0 = 5.0; \/\/ forward speed [m\/s]\n\n \/* Kalman filter variance values *\/\n const float sigma0 = 1 * constants::as_radians; \/\/ yaw angle measurement noise variance\n const float sigma1 = 0.008 * constants::as_radians; \/\/ steer angle measurement noise variance\n\n bicycle_t::input_t u; \/* roll torque, steer torque *\/\n bicycle_t::state_t x; \/* yaw angle, roll angle, steer angle, roll rate, steer rate *\/\n bicycle_t::output_t z; \/* yaw angle, steer angle *\/\n\n \/* sensors *\/\n Analog analog;\n Encoder encoder(&GPTD5, \/* CH1, CH2 connected to PA0, PA1 and NOT enabled by board.h *\/\n {PAL_NOLINE, \/* no index channel *\/\n 152000, \/* counts per revolution *\/\n EncoderConfig::filter_t::CAPTURE_64}); \/* 64 * 42 MHz (TIM3 on APB1) = 1.52 us\n * for valid edge *\/\n\n const float max_kistler_torque = 25.0f; \/* maximum measured steer torque *\/\n \/*\n * The voltage output of the Kistler torque sensor is ±10V. With the 12-bit ADC,\n * resolution for LSB is 4.88 mV\/bit or 12.2 mNm\/bit.\n *\/\n\n model::real_t wrap_angle(model::real_t angle) {\n \/*\n * Angle magnitude is assumed to small enough to NOT require multiple\n * additions\/subtractions of 2pi.\n *\/\n if (angle >= boost::math::constants::pi<float>()) {\n angle -= boost::math::constants::two_pi<float>();\n }\n if (angle < -boost::math::constants::pi<float>()) {\n angle += boost::math::constants::two_pi<float>();\n }\n return angle;\n }\n} \/\/ namespace\n\n\/*\n * Application entry point.\n *\/\nint main(void) {\n\n \/*\n * System initializations.\n * - HAL initialization, this also initializes the configured device drivers\n * and performs the board-specific initializations.\n * - Kernel initialization, the main() function becomes a thread and the\n * RTOS is active.\n *\/\n halInit();\n chSysInit();\n\n \/*\n * Initializes a serial-over-USB CDC driver.\n *\/\n sduObjectInit(&SDU1);\n sduStart(&SDU1, &serusbcfg);\n\n \/*\n * Activates the USB driver and then the USB bus pull-up on D+.\n * Note, a delay is inserted in order to not have to disconnect the cable\n * after a reset.\n *\/\n board_usb_lld_disconnect_bus(); \/\/usbDisconnectBus(serusbcfg.usbp);\n chThdSleepMilliseconds(1500);\n usbStart(serusbcfg.usbp, &usbcfg);\n board_usb_lld_connect_bus(); \/\/usbConnectBus(serusbcfg.usbp);\n\n \/* create the example thread *\/\n chBlinkThreadCreateStatic();\n\n \/* initialize bicycle model and states *\/\n model::Bicycle bicycle(v0, dt);\n x.setZero();\n\n \/* initialize Kalman filter *\/\n kalman_t kalman(bicycle,\n parameters::defaultvalue::kalman::Q(dt), \/* process noise cov *\/\n (kalman_t::measurement_noise_covariance_t() <<\n sigma0, 0,\n 0, sigma1).finished(),\n bicycle_t::state_t::Zero(), \/* set initial state estimate to zero *\/\n std::pow(x[1]\/2, 2) * bicycle_t::state_matrix_t::Identity()); \/* error cov *\/\n\n \/*\n * Start sensors.\n * Encoder:\n * Initialize encoder driver 5 on pins PA0, PA1 (EXT2-4, EXT2-8).\n *\/\n palSetLineMode(LINE_TIM5_CH1, PAL_MODE_ALTERNATE(2) | PAL_STM32_PUPDR_FLOATING);\n palSetLineMode(LINE_TIM5_CH2, PAL_MODE_ALTERNATE(2) | PAL_STM32_PUPDR_FLOATING);\n encoder.start();\n analog.start(1000);\n\n \/*\n * Set torque measurement enable line low.\n * The output of the Kistler torque sensor is not valid until after a falling edge\n * on the measurement line and it is held low. The 'LINE_TORQUE_MEAS_EN' line is\n * reversed due to NPN switch Q1.\n *\/\n palClearLine(LINE_TORQUE_MEAS_EN);\n chThdSleepMilliseconds(1);\n palSetLine(LINE_TORQUE_MEAS_EN);\n\n \/*\n * Normal main() thread activity, in this demo it simulates the bicycle\n * dynamics in real-time (roughly).\n *\/\n rtcnt_t kalman_update_time = 0;\n while (true) {\n u.setZero(); \/* set both roll and steer torques to zero *\/\n \/* pulse torque measure signal and read steer torque value *\/\n u[1] = static_cast<float>(analog.get_adc12()*2.0f*max_kistler_torque\/4096 -\n max_kistler_torque);\n\n \/* set measurement vector *\/\n z[0] = x[0]; \/* yaw angle, just use previous state value *\/\n\n \/*\n * Steer angle, read from encoder (enccnt_t is uint32_t)\n * Convert angle from enccnt_t (unsigned) to corresponding signed type and use negative\n * values for any count over half a revolution.\n *\/\n auto position = static_cast<std::make_signed<enccnt_t>::type>(encoder.count());\n auto rev = static_cast<std::make_signed<enccnt_t>::type>(encoder.config().counts_per_rev);\n if (position > rev \/ 2) {\n position -= rev;\n }\n z[1] = static_cast<float>(position) \/\n boost::math::constants::two_pi<float>();\n\n \/* observer time\/measurement update (~80 us with real_t = float) *\/\n kalman_update_time = chSysGetRealtimeCounterX();\n kalman.time_update(u);\n kalman.measurement_update(z);\n x = kalman.x();\n x[0] = wrap_angle(x[0]);\n x[1] = wrap_angle(x[1]);\n x[2] = wrap_angle(x[2]);\n kalman_update_time = chSysGetRealtimeCounterX() - kalman_update_time;\n\n chprintf((BaseSequentialStream*)&SDU1,\n \"sensors:\\t%0.2f\\t%0.2f\\t%0.2f\\r\\n\",\n u[1], z[0], z[1]);\n chprintf((BaseSequentialStream*)&SDU1,\n \"state:\\t%0.2f\\t%0.2f\\t%0.2f\\t%0.2f\\t%0.2f\\r\\n\",\n x[0], x[1], x[2], x[3], x[4]);\n chprintf((BaseSequentialStream*)&SDU1,\n \"kalman update time: %d us\\r\\n\",\n RTC2US(STM32_SYSCLK, kalman_update_time));\n chThdSleepMilliseconds(static_cast<systime_t>(1000*dt));\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/*=========================================================================\n\n medInria\n\n Copyright (c) INRIA 2013. All rights reserved.\n See LICENSE.txt for details.\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE.\n\n=========================================================================*\/\n\n#include <medViewContainerSplitter.h>\n\n#include <QDebug>\n\n#include <medDataManager.h>\n#include <medViewContainer.h>\n#include <medAbstractData.h>\n#include <QUuid>\n\nmedViewContainerSplitter::medViewContainerSplitter(QWidget *parent)\n{\n this->setOrientation(Qt::Horizontal);\n this->setHandleWidth(1);\n this->setContentsMargins(0,0,0,0);\n this->setOpaqueResize(false);\n}\n\nmedViewContainerSplitter::~medViewContainerSplitter()\n{\n\n}\n\nvoid medViewContainerSplitter::hSplit()\n{\n this->split(Qt::AlignBottom);\n}\n\nvoid medViewContainerSplitter::vSplit()\n{\n this->split(Qt::AlignRight);\n}\n\nmedViewContainer *medViewContainerSplitter::split(Qt::AlignmentFlag alignement)\n{\n medViewContainer* container = dynamic_cast<medViewContainer*>(this->sender());\n if(!container)\n return NULL;\n int index = this->indexOf(container);\n int newSize = this->sizes()[index] \/ 2;\n\n medViewContainer *newContainer = new medViewContainer;\n\n switch(alignement)\n {\n case Qt::AlignLeft:\n if(this->orientation() == Qt::Horizontal)\n {\n this->insertViewContainer(index, newContainer);\n this->recomputeSizes(index + 1, index, newSize);\n }\n else\n this->insertNestedSplitter(index, newContainer, container);\n break;\n case Qt::AlignBottom:\n if(this->orientation() == Qt::Vertical)\n {\n this->insertViewContainer(index + 1, newContainer);\n this->recomputeSizes(index, index + 1, newSize);\n }\n else\n this->insertNestedSplitter(index, container, newContainer);\n break;\n case Qt::AlignRight:\n if(this->orientation() == Qt::Horizontal)\n {\n this->insertViewContainer(index + 1, newContainer);\n this->recomputeSizes(index, index + 1, newSize);\n }\n else\n this->insertNestedSplitter(index, container, newContainer);\n break;\n case Qt::AlignTop:\n if(this->orientation() == Qt::Vertical)\n {\n this->insertViewContainer(index, newContainer);\n this->recomputeSizes(index + 1, index, newSize);\n }\n else\n this->insertNestedSplitter(index, newContainer, container);\n break;\n }\n\n return newContainer;\n}\n\nvoid medViewContainerSplitter::split(medDataIndex index, Qt::AlignmentFlag alignement)\n{\n medViewContainer *newContainer = this->split(alignement);\n newContainer->addData(medDataManager::instance()->data(index));\n}\n\nvoid medViewContainerSplitter::checkIfStillDeserveToLive()\n{\n if(this->count() < 1)\n this->~medViewContainerSplitter();\n}\n\nvoid medViewContainerSplitter::insertViewContainer(int index, medViewContainer *container)\n{\n connect(container, SIGNAL(hSplitRequest()), this, SLOT(hSplit()));\n connect(container, SIGNAL(vSplitRequest()), this, SLOT(vSplit()));\n connect(container, SIGNAL(splitRequest(medDataIndex, Qt::AlignmentFlag)),\n this, SLOT(split(medDataIndex, Qt::AlignmentFlag)));\n connect(container, SIGNAL(destroyed()), this, SLOT(checkIfStillDeserveToLive()));\n connect(container, SIGNAL(destroyed()), this, SIGNAL(containerRemoved()));\n\n\n emit newContainer(container->uuid());\n\n this->insertWidget(index, container);\n this->setCollapsible(index, false);\n}\n\nvoid medViewContainerSplitter::addViewContainer(medViewContainer *container)\n{ \n int newSize = 0;\n if(this->count() > 0)\n newSize = this->sizes()[this->count() - 1] \/ 2;\n\n this->insertViewContainer(this->count(), container);\n if(this->count() > 1)\n this->recomputeSizes(this->count() - 2, this->count() - 1, newSize);\n}\n\nvoid medViewContainerSplitter::recomputeSizes(int requestIndex, int newIndex, int newSize)\n{\n if(requestIndex < 0 || newIndex < 0)\n return;\n\n QList <int> newSizes = this->sizes();\n if(requestIndex >= newSizes.size() || newIndex >= newSizes.size())\n return;\n\n newSizes.replace(requestIndex, newSize);\n newSizes.replace(newIndex, newSize);\n this->setSizes(newSizes);\n}\n\nvoid medViewContainerSplitter::insertNestedSplitter(int index,\n medViewContainer *oldContainer,\n medViewContainer *newContainer)\n{\n Qt::Orientation ori = Qt::Vertical;\n if(this->orientation() == Qt::Vertical)\n ori = Qt::Horizontal;\n\n QList<int> savedSizes = this->sizes();\n oldContainer->disconnect(this);\n medViewContainerSplitter *splitter = new medViewContainerSplitter;\n splitter->setOrientation(ori);\n connect(splitter, SIGNAL(newContainer(QUuid)), this, SIGNAL(newContainer(QUuid)));\n connect(splitter, SIGNAL(containerRemoved()), this, SIGNAL(containerRemoved()));\n connect(splitter, SIGNAL(destroyed()), this, SLOT(checkIfStillDeserveToLive()));\n splitter->addViewContainer(oldContainer);\n splitter->addViewContainer(newContainer);\n this->insertWidget(index, splitter);\n this->setCollapsible(index, false);\n this->setSizes(savedSizes);\n}\n<commit_msg>correct resize of the splitter when adding a qvtkWidget2 directly in a new created nested splitter<commit_after>\/*=========================================================================\n\n medInria\n\n Copyright (c) INRIA 2013. All rights reserved.\n See LICENSE.txt for details.\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE.\n\n=========================================================================*\/\n\n#include <medViewContainerSplitter.h>\n\n#include <QDebug>\n\n#include <medDataManager.h>\n#include <medViewContainer.h>\n#include <medAbstractData.h>\n#include <QUuid>\n\nmedViewContainerSplitter::medViewContainerSplitter(QWidget *parent)\n{\n this->setOrientation(Qt::Horizontal);\n this->setHandleWidth(1);\n this->setContentsMargins(0,0,0,0);\n this->setOpaqueResize(false);\n}\n\nmedViewContainerSplitter::~medViewContainerSplitter()\n{\n\n}\n\nvoid medViewContainerSplitter::hSplit()\n{\n this->split(Qt::AlignBottom);\n}\n\nvoid medViewContainerSplitter::vSplit()\n{\n this->split(Qt::AlignRight);\n}\n\nmedViewContainer *medViewContainerSplitter::split(Qt::AlignmentFlag alignement)\n{\n medViewContainer* container = dynamic_cast<medViewContainer*>(this->sender());\n if(!container)\n return NULL;\n int index = this->indexOf(container);\n int newSize = this->sizes()[index] \/ 2;\n\n medViewContainer *newContainer = new medViewContainer;\n\n switch(alignement)\n {\n case Qt::AlignLeft:\n if(this->orientation() == Qt::Horizontal)\n {\n this->insertViewContainer(index, newContainer);\n this->recomputeSizes(index + 1, index, newSize);\n }\n else\n this->insertNestedSplitter(index, newContainer, container);\n break;\n case Qt::AlignBottom:\n if(this->orientation() == Qt::Vertical)\n {\n this->insertViewContainer(index + 1, newContainer);\n this->recomputeSizes(index, index + 1, newSize);\n }\n else\n this->insertNestedSplitter(index, container, newContainer);\n break;\n case Qt::AlignRight:\n if(this->orientation() == Qt::Horizontal)\n {\n this->insertViewContainer(index + 1, newContainer);\n this->recomputeSizes(index, index + 1, newSize);\n }\n else\n this->insertNestedSplitter(index, container, newContainer);\n break;\n case Qt::AlignTop:\n if(this->orientation() == Qt::Vertical)\n {\n this->insertViewContainer(index, newContainer);\n this->recomputeSizes(index + 1, index, newSize);\n }\n else\n this->insertNestedSplitter(index, newContainer, container);\n break;\n }\n\n return newContainer;\n}\n\nvoid medViewContainerSplitter::split(medDataIndex index, Qt::AlignmentFlag alignement)\n{\n medViewContainer *newContainer = this->split(alignement);\n newContainer->addData(medDataManager::instance()->data(index));\n}\n\nvoid medViewContainerSplitter::checkIfStillDeserveToLive()\n{\n if(this->count() < 1)\n this->~medViewContainerSplitter();\n}\n\nvoid medViewContainerSplitter::insertViewContainer(int index, medViewContainer *container)\n{\n connect(container, SIGNAL(hSplitRequest()), this, SLOT(hSplit()));\n connect(container, SIGNAL(vSplitRequest()), this, SLOT(vSplit()));\n connect(container, SIGNAL(splitRequest(medDataIndex, Qt::AlignmentFlag)),\n this, SLOT(split(medDataIndex, Qt::AlignmentFlag)));\n connect(container, SIGNAL(destroyed()), this, SLOT(checkIfStillDeserveToLive()));\n connect(container, SIGNAL(destroyed()), this, SIGNAL(containerRemoved()));\n\n\n emit newContainer(container->uuid());\n\n this->insertWidget(index, container);\n this->setCollapsible(index, false);\n}\n\nvoid medViewContainerSplitter::addViewContainer(medViewContainer *container)\n{ \n int newSize = 0;\n if(this->count() > 0)\n newSize = this->sizes()[this->count() - 1] \/ 2;\n\n this->insertViewContainer(this->count(), container);\n if(this->count() > 1)\n this->recomputeSizes(this->count() - 2, this->count() - 1, newSize);\n}\n\nvoid medViewContainerSplitter::recomputeSizes(int requestIndex, int newIndex, int newSize)\n{\n if(requestIndex < 0 || newIndex < 0)\n return;\n\n QList <int> newSizes = this->sizes();\n if(requestIndex >= newSizes.size() || newIndex >= newSizes.size())\n return;\n\n newSizes.replace(requestIndex, newSize);\n newSizes.replace(newIndex, newSize);\n this->setSizes(newSizes);\n}\n\nvoid medViewContainerSplitter::insertNestedSplitter(int index,\n medViewContainer *oldContainer,\n medViewContainer *newContainer)\n{\n Qt::Orientation ori = Qt::Vertical;\n if(this->orientation() == Qt::Vertical)\n ori = Qt::Horizontal;\n\n QList<int> savedSizes = this->sizes();\n oldContainer->disconnect(this);\n medViewContainerSplitter *splitter = new medViewContainerSplitter;\n splitter->setOrientation(ori);\n connect(splitter, SIGNAL(newContainer(QUuid)), this, SIGNAL(newContainer(QUuid)));\n connect(splitter, SIGNAL(containerRemoved()), this, SIGNAL(containerRemoved()));\n connect(splitter, SIGNAL(destroyed()), this, SLOT(checkIfStillDeserveToLive()));\n this->insertWidget(index, splitter);\n this->setCollapsible(index, false);\n splitter->addViewContainer(oldContainer);\n splitter->addViewContainer(newContainer);\n this->setSizes(savedSizes);\n\n\/\/ int newSize = 0;\n\/\/ if(splitter->orientation() == Qt::Vertical)\n\/\/ newSize = splitter->width() \/ 2;\n\/\/ else\n\/\/ newSize = splitter->height() \/ 2;\n\/\/ splitter->recomputeSizes(0, 1, newSize);\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/** \\file MediaTypeUtil.cc\n * \\brief Implementation of Media Type utility functions.\n * \\author Dr. Gordon W. Paynter\n * \\author Dr. Johannes Ruscheinski\n *\/\n\n\/*\n * Copyright 2004-2008 Project iVia.\n * Copyright 2004-2008 The Regents of The University of California.\n * Copyright 2016 Universitätsbibliothek Tübingen.\n *\n * This file is part of the libiViaCore package.\n *\n * The libiViaCore package is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public License as published\n * by the Free Software Foundation; either version 2 of the License, or\n * (at your option) any later version.\n *\n * libiViaCore is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public License\n * along with libiViaCore; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n *\/\n\n#include \"MediaTypeUtil.h\"\n#include <stdexcept>\n#include <cctype>\n#include <alloca.h>\n#include <magic.h>\n#include \"File.h\"\n#include \"HttpHeader.h\"\n#include \"PerlCompatRegExp.h\"\n#include \"StringUtil.h\"\n#include \"Url.h\"\n#include \"WebUtil.h\"\n\n\nnamespace MediaTypeUtil {\n\n\nstd::string GetHtmlMediaType(const std::string &document) {\n static const PerlCompatRegExp doctype_regexp(\"^\\\\s*<(?:!DOCTYPE\\\\s+HTML\\\\s+PUBLIC\\\\s+\\\"-\/\/W3C\/\/DTD\\\\s+){0,1}(X?HTML)\",\n PerlCompatRegExp::OPTIMIZE_FOR_MULTIPLE_USE, PCRE_CASELESS);\n\n \/\/ If we have a match we have either HTML or XHTML...\n std::string matched_substring;\n if (doctype_regexp.match(document) and doctype_regexp.getMatchedSubstring(1, &matched_substring))\n return matched_substring.length() == 4 ? \"text\/html\" : \"text\/xhtml\";\n\n \/\/ ...otherwise we have no idea what we have:\n return \"\";\n}\n\n\nstatic std::string LZ4_MAGIC(\"\\000\\042\\115\\030\");\n\n\n\/\/ GetMediaType -- Get the media type of a document.\n\/\/\nstd::string GetMediaType(const std::string &document, const bool auto_simplify) {\n if (document.empty())\n return \"\";\n\n \/\/ 1. See if we have (X)HTML:\n std::string media_type(GetHtmlMediaType(document));\n if (not media_type.empty())\n return media_type;\n\n \/\/ 2. Check for LZ4 compression:\n if (document.substr(0, 4) == LZ4_MAGIC)\n return \"application\/lz4\";\n\n \/\/ 3. Next try libmagic:\n const magic_t cookie = ::magic_open(MAGIC_MIME);\n if (unlikely(cookie == nullptr))\n throw std::runtime_error(\"in MediaTypeUtil::GetMediaType: could not open libmagic!\");\n\n \/\/ Load the default \"magic\" definitions file:\n if (unlikely(::magic_load(cookie, nullptr \/* use default magic file *\/) != 0)) {\n ::magic_close(cookie);\n throw std::runtime_error(\"in MediaTypeUtil::GetMediaType: could not load libmagic (\"\n + std::string(::magic_error(cookie)) + \").\");\n }\n\n \/\/ Use magic to get the mime type of the buffer:\n const char *magic_mime_type = ::magic_buffer(cookie, document.c_str(), document.length());\n if (unlikely(magic_mime_type == nullptr)) {\n ::magic_close(cookie);\n throw std::runtime_error(\"in MediaTypeUtil::GetMediaType: error in libmagic (\"\n + std::string(::magic_error(cookie)) + \").\");\n }\n\n \/\/ Attempt to remove possible leading junk (no idea why libmagic behaves in this manner every now and then):\n if (std::strncmp(magic_mime_type, \"\\\\012- \", 6) == 0)\n magic_mime_type += 6;\n\n \/\/ Close the library:\n media_type = magic_mime_type;\n ::magic_close(cookie);\n\n \/\/ 4. If the libmagic could not determine the document's MIME type, test for XML:\n if (media_type.empty() and document.size() > 5)\n return std::strncmp(document.c_str(), \"<?xml\", 5) == 0 ? \"text\/xml\" : \"\";\n\n if (auto_simplify)\n SimplifyMediaType(&media_type);\n\n return media_type;\n}\n\n\nstd::string GetFileMediaType(const std::string &filename, const bool auto_simplify) {\n const magic_t cookie = ::magic_open(MAGIC_MIME | MAGIC_SYMLINK);\n if (unlikely(cookie == nullptr))\n throw std::runtime_error(\"in MediaTypeUtil::GetMediaType: could not open libmagic!\");\n\n \/\/ Load the default \"magic\" definitions file:\n if (unlikely(::magic_load(cookie, nullptr \/* use default magic file *\/) != 0)) {\n ::magic_close(cookie);\n throw std::runtime_error(\"in MediaTypeUtil::GetMediaType: could not load libmagic (\"\n + std::string(::magic_error(cookie)) + \").\");\n }\n\n \/\/ Use magic to get the mime type of the buffer:\n const char *magic_mime_type(::magic_file(cookie, filename.c_str()));\n if (unlikely(magic_mime_type == nullptr)) {\n ::magic_close(cookie);\n throw std::runtime_error(\"in MediaTypeUtil::GetFileMediaType: error in libmagic (\"\n + std::string(::magic_error(cookie)) + \").\");\n }\n\n \/\/ Attempt to remove possible leading junk (no idea why libmagic behaves in this manner every now and then):\n if (std::strncmp(magic_mime_type, \"\\\\012- \", 6) == 0)\n magic_mime_type += 6;\n\n \/\/ Close the library:\n std::string media_type(magic_mime_type);\n ::magic_close(cookie);\n\n if (auto_simplify)\n SimplifyMediaType(&media_type);\n\n if (StringUtil::StartsWith(media_type, \"application\/octet-stream\")) {\n File input(filename, \"rb\");\n char *buf = reinterpret_cast<char *>(::alloca(LZ4_MAGIC.size()));\n if ((input.read(buf, sizeof(buf)) == sizeof(buf)) and std::strncmp(LZ4_MAGIC.c_str(), buf, LZ4_MAGIC.size()) == 0)\n return \"application\/lz4\";\n }\n\n return media_type;\n}\n\n\n\/\/ GetMediaType -- get the media type of a Web page.\n\/\/\nstd::string GetMediaType(const std::string &page_header, const std::string &page_body, const bool auto_simplify) {\n \/\/ First, attempt to find the media type in the header:\n HttpHeader http_header(page_header);\n if (http_header.isValid()) {\n std::string media_type(http_header.getMediaType());\n if (not media_type.empty()) {\n StringUtil::ToLower(&media_type);\n if (auto_simplify)\n SimplifyMediaType(&media_type);\n return media_type;\n }\n }\n\n \/\/ Otherwise, check the content:\n return GetMediaType(page_body, auto_simplify);\n}\n\n\n\/\/ GetMediaType -- Get the MediaType of the page. Returns true if \"media_type\" is known and set.\n\/\/\nbool GetMediaType(const Url &url, const HttpHeader &http_header, const std::string &page_content,\n std::string * const media_type, const bool auto_simplify)\n{\n \/\/ First, attempt to find the media type in the header:\n if (http_header.isValid()) {\n *media_type = http_header.getMediaType();\n if (not media_type->empty()) {\n if (auto_simplify)\n SimplifyMediaType(media_type);\n return true;\n }\n }\n\n \/\/ Second, attempt to use the \"magic\" library (libmagic) to analyse the page:\n *media_type = MediaTypeUtil::GetMediaType(page_content);\n if (not media_type->empty()) {\n if (auto_simplify)\n SimplifyMediaType(media_type);\n return true;\n }\n\n \/\/ Third, guess based on URL:\n *media_type = WebUtil::GuessMediaType(url);\n if (not media_type->empty() and auto_simplify)\n SimplifyMediaType(media_type);\n return not media_type->empty();\n}\n\n\nstd::string GetMediaType(const HttpHeader &http_header, const std::string &page_body, const bool auto_simplify) {\n std::string media_type;\n\n \/\/ First, attempt to find the media type in the header:\n if (http_header.isValid()) {\n media_type = http_header.getMediaType();\n if (not media_type.empty()) {\n StringUtil::ToLower(&media_type);\n if (auto_simplify)\n SimplifyMediaType(&media_type);\n return media_type;\n }\n }\n\n \/\/ Second, attempt to use the \"magic\" library (libmagic) to analyse the page:\n media_type = MediaTypeUtil::GetMediaType(page_body, auto_simplify);\n\n return media_type;\n}\n\n\nbool GetMediaType(const std::string &url, const HttpHeader &http_header, const std::string &page_content,\n std::string * const media_type, const bool auto_simplify)\n{\n return GetMediaType(Url(url), http_header, page_content, media_type, auto_simplify);\n}\n\n\nbool SimplifyMediaType(std::string * const media_type) {\n if (media_type->empty())\n return false;\n\n \/\/ This is the format of the Content-Type field for Web pages:\n \/\/ media-type = type \"\/\" subtype *( \";\" parameter )\n \/\/ type = token\n \/\/ subtype = token\n \/\/ See: http:\/\/www.w3.org\/Protocols\/rfc2616\/rfc2616-sec3.html#sec3.7\n\n const std::string initial_media_type(*media_type);\n\n \/\/ Search for a semicolon and delete any 'parameter' parts:\n const std::string::size_type semicolon_pos(media_type->find(';'));\n if (semicolon_pos != std::string::npos)\n media_type->resize(semicolon_pos);\n else { \/\/ Try a space instead of a semicolon.\n const std::string::size_type space_pos(media_type->find(' '));\n if (space_pos != std::string::npos)\n media_type->resize(space_pos);\n }\n\n StringUtil::TrimWhite(media_type);\n\n \/\/ Return if \"media_type\" has changed:\n return initial_media_type != *media_type;\n}\n\n\n} \/\/ namespace MediaTypeUtil\n<commit_msg>Our File class does not support the \"rb\" open mode.<commit_after>\/** \\file MediaTypeUtil.cc\n * \\brief Implementation of Media Type utility functions.\n * \\author Dr. Gordon W. Paynter\n * \\author Dr. Johannes Ruscheinski\n *\/\n\n\/*\n * Copyright 2004-2008 Project iVia.\n * Copyright 2004-2008 The Regents of The University of California.\n * Copyright 2016 Universitätsbibliothek Tübingen.\n *\n * This file is part of the libiViaCore package.\n *\n * The libiViaCore package is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public License as published\n * by the Free Software Foundation; either version 2 of the License, or\n * (at your option) any later version.\n *\n * libiViaCore is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public License\n * along with libiViaCore; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n *\/\n\n#include \"MediaTypeUtil.h\"\n#include <stdexcept>\n#include <cctype>\n#include <alloca.h>\n#include <magic.h>\n#include \"File.h\"\n#include \"HttpHeader.h\"\n#include \"PerlCompatRegExp.h\"\n#include \"StringUtil.h\"\n#include \"Url.h\"\n#include \"util.h\"\n#include \"WebUtil.h\"\n\n\nnamespace MediaTypeUtil {\n\n\nstd::string GetHtmlMediaType(const std::string &document) {\n static const PerlCompatRegExp doctype_regexp(\"^\\\\s*<(?:!DOCTYPE\\\\s+HTML\\\\s+PUBLIC\\\\s+\\\"-\/\/W3C\/\/DTD\\\\s+){0,1}(X?HTML)\",\n PerlCompatRegExp::OPTIMIZE_FOR_MULTIPLE_USE, PCRE_CASELESS);\n\n \/\/ If we have a match we have either HTML or XHTML...\n std::string matched_substring;\n if (doctype_regexp.match(document) and doctype_regexp.getMatchedSubstring(1, &matched_substring))\n return matched_substring.length() == 4 ? \"text\/html\" : \"text\/xhtml\";\n\n \/\/ ...otherwise we have no idea what we have:\n return \"\";\n}\n\n\nstatic std::string LZ4_MAGIC(\"\\000\\042\\115\\030\");\n\n\n\/\/ GetMediaType -- Get the media type of a document.\n\/\/\nstd::string GetMediaType(const std::string &document, const bool auto_simplify) {\n if (document.empty())\n return \"\";\n\n \/\/ 1. See if we have (X)HTML:\n std::string media_type(GetHtmlMediaType(document));\n if (not media_type.empty())\n return media_type;\n\n \/\/ 2. Check for LZ4 compression:\n if (document.substr(0, 4) == LZ4_MAGIC)\n return \"application\/lz4\";\n\n \/\/ 3. Next try libmagic:\n const magic_t cookie = ::magic_open(MAGIC_MIME);\n if (unlikely(cookie == nullptr))\n throw std::runtime_error(\"in MediaTypeUtil::GetMediaType: could not open libmagic!\");\n\n \/\/ Load the default \"magic\" definitions file:\n if (unlikely(::magic_load(cookie, nullptr \/* use default magic file *\/) != 0)) {\n ::magic_close(cookie);\n throw std::runtime_error(\"in MediaTypeUtil::GetMediaType: could not load libmagic (\"\n + std::string(::magic_error(cookie)) + \").\");\n }\n\n \/\/ Use magic to get the mime type of the buffer:\n const char *magic_mime_type = ::magic_buffer(cookie, document.c_str(), document.length());\n if (unlikely(magic_mime_type == nullptr)) {\n ::magic_close(cookie);\n throw std::runtime_error(\"in MediaTypeUtil::GetMediaType: error in libmagic (\"\n + std::string(::magic_error(cookie)) + \").\");\n }\n\n \/\/ Attempt to remove possible leading junk (no idea why libmagic behaves in this manner every now and then):\n if (std::strncmp(magic_mime_type, \"\\\\012- \", 6) == 0)\n magic_mime_type += 6;\n\n \/\/ Close the library:\n media_type = magic_mime_type;\n ::magic_close(cookie);\n\n \/\/ 4. If the libmagic could not determine the document's MIME type, test for XML:\n if (media_type.empty() and document.size() > 5)\n return std::strncmp(document.c_str(), \"<?xml\", 5) == 0 ? \"text\/xml\" : \"\";\n\n if (auto_simplify)\n SimplifyMediaType(&media_type);\n\n return media_type;\n}\n\n\nstd::string GetFileMediaType(const std::string &filename, const bool auto_simplify) {\n const magic_t cookie(::magic_open(MAGIC_MIME | MAGIC_SYMLINK));\n if (unlikely(cookie == nullptr))\n throw std::runtime_error(\"in MediaTypeUtil::GetMediaType: could not open libmagic!\");\n\n \/\/ Load the default \"magic\" definitions file:\n if (unlikely(::magic_load(cookie, nullptr \/* use default magic file *\/) != 0)) {\n ::magic_close(cookie);\n throw std::runtime_error(\"in MediaTypeUtil::GetMediaType: could not load libmagic (\"\n + std::string(::magic_error(cookie)) + \").\");\n }\n\n \/\/ Use magic to get the mime type of the buffer:\n const char *magic_mime_type(::magic_file(cookie, filename.c_str()));\n if (unlikely(magic_mime_type == nullptr)) {\n ::magic_close(cookie);\n throw std::runtime_error(\"in MediaTypeUtil::GetFileMediaType: error in libmagic (\"\n + std::string(::magic_error(cookie)) + \").\");\n }\n\n \/\/ Attempt to remove possible leading junk (no idea why libmagic behaves in this manner every now and then):\n if (std::strncmp(magic_mime_type, \"\\\\012- \", 6) == 0)\n magic_mime_type += 6;\n\n \/\/ Close the library:\n std::string media_type(magic_mime_type);\n ::magic_close(cookie);\n\n if (auto_simplify)\n SimplifyMediaType(&media_type);\n\n if (StringUtil::StartsWith(media_type, \"application\/octet-stream\")) {\n File input(filename, \"r\");\n if (unlikely(input.anErrorOccurred()))\n logger->error(\"in MediaTypeUtil::GetFileMediaType: failed to open \\\"\" + filename + \"\\\" for reading!\");\n char * const buf(reinterpret_cast<char *>(::alloca(LZ4_MAGIC.size())));\n if ((input.read(buf, sizeof(buf)) == sizeof(buf)) and std::strncmp(LZ4_MAGIC.c_str(), buf, LZ4_MAGIC.size()) == 0)\n return \"application\/lz4\";\n }\n\n return media_type;\n}\n\n\n\/\/ GetMediaType -- get the media type of a Web page.\n\/\/\nstd::string GetMediaType(const std::string &page_header, const std::string &page_body, const bool auto_simplify) {\n \/\/ First, attempt to find the media type in the header:\n HttpHeader http_header(page_header);\n if (http_header.isValid()) {\n std::string media_type(http_header.getMediaType());\n if (not media_type.empty()) {\n StringUtil::ToLower(&media_type);\n if (auto_simplify)\n SimplifyMediaType(&media_type);\n return media_type;\n }\n }\n\n \/\/ Otherwise, check the content:\n return GetMediaType(page_body, auto_simplify);\n}\n\n\n\/\/ GetMediaType -- Get the MediaType of the page. Returns true if \"media_type\" is known and set.\n\/\/\nbool GetMediaType(const Url &url, const HttpHeader &http_header, const std::string &page_content,\n std::string * const media_type, const bool auto_simplify)\n{\n \/\/ First, attempt to find the media type in the header:\n if (http_header.isValid()) {\n *media_type = http_header.getMediaType();\n if (not media_type->empty()) {\n if (auto_simplify)\n SimplifyMediaType(media_type);\n return true;\n }\n }\n\n \/\/ Second, attempt to use the \"magic\" library (libmagic) to analyse the page:\n *media_type = MediaTypeUtil::GetMediaType(page_content);\n if (not media_type->empty()) {\n if (auto_simplify)\n SimplifyMediaType(media_type);\n return true;\n }\n\n \/\/ Third, guess based on URL:\n *media_type = WebUtil::GuessMediaType(url);\n if (not media_type->empty() and auto_simplify)\n SimplifyMediaType(media_type);\n return not media_type->empty();\n}\n\n\nstd::string GetMediaType(const HttpHeader &http_header, const std::string &page_body, const bool auto_simplify) {\n std::string media_type;\n\n \/\/ First, attempt to find the media type in the header:\n if (http_header.isValid()) {\n media_type = http_header.getMediaType();\n if (not media_type.empty()) {\n StringUtil::ToLower(&media_type);\n if (auto_simplify)\n SimplifyMediaType(&media_type);\n return media_type;\n }\n }\n\n \/\/ Second, attempt to use the \"magic\" library (libmagic) to analyse the page:\n media_type = MediaTypeUtil::GetMediaType(page_body, auto_simplify);\n\n return media_type;\n}\n\n\nbool GetMediaType(const std::string &url, const HttpHeader &http_header, const std::string &page_content,\n std::string * const media_type, const bool auto_simplify)\n{\n return GetMediaType(Url(url), http_header, page_content, media_type, auto_simplify);\n}\n\n\nbool SimplifyMediaType(std::string * const media_type) {\n if (media_type->empty())\n return false;\n\n \/\/ This is the format of the Content-Type field for Web pages:\n \/\/ media-type = type \"\/\" subtype *( \";\" parameter )\n \/\/ type = token\n \/\/ subtype = token\n \/\/ See: http:\/\/www.w3.org\/Protocols\/rfc2616\/rfc2616-sec3.html#sec3.7\n\n const std::string initial_media_type(*media_type);\n\n \/\/ Search for a semicolon and delete any 'parameter' parts:\n const std::string::size_type semicolon_pos(media_type->find(';'));\n if (semicolon_pos != std::string::npos)\n media_type->resize(semicolon_pos);\n else { \/\/ Try a space instead of a semicolon.\n const std::string::size_type space_pos(media_type->find(' '));\n if (space_pos != std::string::npos)\n media_type->resize(space_pos);\n }\n\n StringUtil::TrimWhite(media_type);\n\n \/\/ Return if \"media_type\" has changed:\n return initial_media_type != *media_type;\n}\n\n\n} \/\/ namespace MediaTypeUtil\n<|endoftext|>"} {"text":"<commit_before>\/** \\file rss_subset_aggregator.cc\n * \\brief Aggregates RSS feeds.\n * \\author Dr. Johannes Ruscheinski (johannes.ruscheinski@uni-tuebingen.de)\n *\n * \\copyright 2021 Universitätsbibliothek Tübingen. All rights reserved.\n *\n * This program is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License as\n * published by the Free Software Foundation, either version 3 of the\n * License, or (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Affero General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public License\n * along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n#include <algorithm>\n#include <map>\n#include <unordered_map>\n#include <unordered_set>\n#include <cinttypes>\n#include <cstring>\n#include \"Compiler.h\"\n#include \"DbConnection.h\"\n#include \"DbResultSet.h\"\n#include \"EmailSender.h\"\n#include \"FileUtil.h\"\n#include \"HtmlUtil.h\"\n#include \"SqlUtil.h\"\n#include \"StringUtil.h\"\n#include \"SyndicationFormat.h\"\n#include \"Template.h\"\n#include \"UBTools.h\"\n#include \"util.h\"\n#include \"VuFind.h\"\n#include \"XmlWriter.h\"\n\n\nnamespace {\n\n\n[[noreturn]] void Usage() {\n ::Usage(\"--mode=(email|rss_xml) (user_id|error_email_address) subsystem_type]\\n\"\n \"If the mode is \\\"rss_xml\\\" a VuFind user_id needs to be specified, o\/w an error email address should be provided.\");\n}\n\n\nstruct HarvestedRSSItem {\n SyndicationFormat::Item item_;\n std::string feed_title_;\n std::string feed_url_;\n\n HarvestedRSSItem(const SyndicationFormat::Item item, const std::string feed_title, const std::string feed_url)\n : item_(item), feed_title_(feed_title), feed_url_(feed_url) {}\n};\n\n\nstruct ChannelDesc {\n std::string title_;\n std::string link_;\npublic:\n ChannelDesc(const std::string &title, const std::string &link)\n : title_(title), link_(link) { }\n};\n\n\nconst std::map<std::string, ChannelDesc> subsystem_type_to_channel_desc_map = {\n { \"relbib\", ChannelDesc(\"RelBib RSS Aggregator\", \"https:\/\/relbib.de\/\") },\n { \"ixtheo\", ChannelDesc(\"IxTheo RSS Aggregator\", \"https:\/\/itheo.de\/\") },\n { \"krimdok\", ChannelDesc(\"KrimDok RSS Aggregator\", \"https:\/\/krimdok.uni-tuebingen.de\/\") },\n};\n\n\nstd::string GetChannelDescEntry(const std::string &subsystem_type, const std::string &entry) {\n const auto subsystem_type_and_channel_desc(subsystem_type_to_channel_desc_map.find(subsystem_type));\n if (subsystem_type_and_channel_desc == subsystem_type_to_channel_desc_map.cend())\n LOG_ERROR(\"unknown subsystem type \\\"\" + subsystem_type + \"\\\"!\");\n\n if (entry == \"title\")\n return subsystem_type_and_channel_desc->second.title_;\n if (entry == \"link\")\n return subsystem_type_and_channel_desc->second.link_;\n LOG_ERROR(\"unknown entry name \\\"\" + entry + \"\\\"!\");\n}\n\n\nvoid WriteRSSFeedXMLOutput(const std::string &subsystem_type, const std::vector<HarvestedRSSItem> &harvested_items,\n XmlWriter * const xml_writer)\n{\n xml_writer->openTag(\"rss\", { { \"version\", \"2.0\" } });\n xml_writer->openTag(\"channel\");\n xml_writer->writeTagsWithData(\"title\", GetChannelDescEntry(subsystem_type, \"title\"));\n xml_writer->writeTagsWithData(\"link\", GetChannelDescEntry(subsystem_type, \"link\"));\n xml_writer->writeTagsWithData(\"description\", \"RSS Aggregator\");\n\n for (const auto &harvested_item : harvested_items) {\n xml_writer->openTag(\"item\");\n\n const auto title(harvested_item.item_.getTitle());\n if (not title.empty())\n xml_writer->writeTagsWithData(\"title\", harvested_item.item_.getTitle());\n\n xml_writer->writeTagsWithData(\"link\", harvested_item.item_.getLink());\n\n const auto description(HtmlUtil::ShortenText(harvested_item.item_.getDescription(), \/*max_length = *\/500));\n if (not description.empty())\n xml_writer->writeTagsWithData(\"description\", description);\n\n xml_writer->writeTagsWithData(\"pubDate\",\n TimeUtil::TimeTToString(harvested_item.item_.getPubDate(), TimeUtil::RFC822_FORMAT,\n TimeUtil::UTC));\n xml_writer->writeTagsWithData(\"guid\", harvested_item.item_.getId());\n xml_writer->closeTag(\"item\", \/* suppress_indent *\/ false);\n }\n\n xml_writer->closeTag(\"channel\");\n xml_writer->closeTag(\"rss\");\n}\n\n\nstruct FeedNameAndURL {\n std::string name_;\n std::string url_;\npublic:\n FeedNameAndURL() = default;\n FeedNameAndURL(const FeedNameAndURL &other) = default;\n FeedNameAndURL(const std::string &name, const std::string &url)\n : name_(name), url_(url) { }\n};\n\n\n\/\/ \\return True if a notification email was sent successfully, o\/w false.\nbool SendEmail(const std::string &subsystem_type, const std::string &email_sender, const std::string &user_email,\n const std::string &user_address, const std::string &language,\n const std::vector<HarvestedRSSItem> &harvested_items)\n{\n const auto template_filename_prefix(UBTools::GetTuelibPath() + \"rss_email.template\");\n std::string template_filename(template_filename_prefix + \".\" + language);\n if (not FileUtil::Exists(template_filename))\n template_filename = template_filename_prefix + \".en\";\n static const std::string email_template(FileUtil::ReadStringOrDie(template_filename));\n\n Template::Map names_to_values_map;\n names_to_values_map.insertScalar(\"user_email\", user_email);\n names_to_values_map.insertScalar(\"user_address\", user_address);\n\n std::vector<std::string> titles, links, descriptions;\n for (const auto &harvested_item : harvested_items) {\n titles.emplace_back(HtmlUtil::HtmlEscape(harvested_item.item_.getTitle()));\n links.emplace_back(harvested_item.item_.getLink());\n descriptions.emplace_back(HtmlUtil::HtmlEscape(harvested_item.item_.getDescription()));\n }\n names_to_values_map.insertArray(\"titles\", titles);\n names_to_values_map.insertArray(\"links\", links);\n names_to_values_map.insertArray(\"descriptions\", descriptions);\n\n const auto email_body(Template::ExpandTemplate(email_template, names_to_values_map));\n const auto retcode(EmailSender::SimplerSendEmail(email_sender, { user_email }, GetChannelDescEntry(subsystem_type, \"title\"),\n email_body, EmailSender::DO_NOT_SET_PRIORITY, EmailSender::HTML));\n if (retcode <= 299)\n return true;\n\n LOG_WARNING(\"EmailSender::SimplerSendEmail returned \" + std::to_string(retcode) + \" while trying to send to \\\"\"\n + user_email + \"\\\"!\");\n return false;\n}\n\n\nconst unsigned DEFAULT_XML_INDENT_AMOUNT(2);\n\n\nvoid GenerateFeed(const std::string &subsystem_type, const std::vector<HarvestedRSSItem> &harvested_items) {\n XmlWriter xml_writer(FileUtil::OpenOutputFileOrDie(\"\/dev\/stdout\").release(),\n XmlWriter::WriteTheXmlDeclaration, DEFAULT_XML_INDENT_AMOUNT);\n WriteRSSFeedXMLOutput(subsystem_type, harvested_items, &xml_writer);\n}\n\n\nbool ProcessFeeds(const std::string &user_id, const std::string &rss_feed_last_notification, const std::string &email_sender,\n const std::string &user_email, const std::string &user_address, const std::string &language,\n const bool send_email, const std::string &subsystem_type,\n DbConnection * const db_connection)\n{\n db_connection->queryOrDie(\"SELECT rss_feeds_id FROM tuefind_rss_subscriptions WHERE user_id=\" + user_id);\n auto rss_subscriptions_result_set(db_connection->getLastResultSet());\n std::vector<std::string> feed_ids;\n while (const auto row = rss_subscriptions_result_set.getNextRow())\\\n feed_ids.emplace_back(row[\"rss_feeds_id\"]);\n if (feed_ids.empty())\n return false;\n\n std::vector<HarvestedRSSItem> harvested_items;\n std::string max_insertion_time;\n for (const auto &feed_id : feed_ids) {\n db_connection->queryOrDie(\"SELECT feed_name,feed_url FROM tuefind_rss_feeds WHERE id=\" + feed_id);\n auto feed_result_set(db_connection->getLastResultSet());\n const auto feed_row(feed_result_set.getNextRow());\n const auto feed_name(feed_row[\"feed_name\"]);\n const auto feed_url(feed_row[\"feed_url\"]);\n feed_result_set.~DbResultSet();\n\n db_connection->queryOrDie(\"SELECT item_title,item_description,item_url,item_id,pub_date,insertion_time FROM \"\n \"tuefind_rss_items WHERE rss_feeds_id=\" + feed_id + \" AND insertion_time > '\"\n + rss_feed_last_notification + \"'\");\n auto items_result_set(db_connection->getLastResultSet());\n while (const auto item_row = items_result_set.getNextRow()) {\n harvested_items.emplace_back(SyndicationFormat::Item(item_row[\"item_title\"], item_row[\"item_description\"],\n item_row[\"item_url\"], item_row[\"item_id\"],\n SqlUtil::DatetimeToTimeT(item_row[\"pub_date\"])),\n feed_name, feed_url);\n const auto insertion_time(item_row[\"insertion_time\"]);\n if (insertion_time > max_insertion_time)\n max_insertion_time = insertion_time;\n }\n }\n if (harvested_items.empty())\n return false;\n\n if (send_email) {\n if (not SendEmail(subsystem_type, email_sender, user_email, user_address, language, harvested_items))\n return true;\n db_connection->queryOrDie(\"INSERT INTO user SET tuefind_rss_feed_last_notification='\" + max_insertion_time\n + \"' WHERE id=\" + user_id);\n } else\n GenerateFeed(subsystem_type, harvested_items);\n return true;\n}\n\n\n\/\/ Yes, this function has a confusing name but I could not think of a better one. :-(\n\/\/ What is meant is how to address a user!\nstd::string GenerateUserAddress(const std::string &first_name, const std::string &last_name) {\n if (last_name.empty())\n return first_name;\n\n return first_name + \" \" + last_name;\n}\n\n\n} \/\/ unnamed namespace\n\n\nstruct UserInfo {\n std::string user_id_;\n std::string first_name_;\n std::string last_name_;\n std::string email_;\n std::string rss_feed_last_notification_;\npublic:\n UserInfo() = default;\n UserInfo(const UserInfo &other) = default;\n UserInfo(const std::string &user_id, const std::string &first_name, const std::string &last_name,\n const std::string &email, const std::string &rss_feed_last_notification)\n : user_id_(user_id), first_name_(first_name), last_name_(last_name), email_(email),\n rss_feed_last_notification_(rss_feed_last_notification) { }\n};\n\n\nint Main(int argc, char *argv[]) {\n if (argc != 4)\n Usage();\n\n std::string error_email_address, vufind_user_id;\n if (std::strcmp(argv[1], \"--mode=email\") == 0)\n vufind_user_id = argv[2];\n else if (std::strcmp(argv[1], \"--mode=rss_xml\") == 0)\n vufind_user_id = argv[2];\n else\n Usage();\n const std::string subsystem_type(argv[3]);\n if (subsystem_type != \"ixtheo\" and subsystem_type != \"relbib\" and subsystem_type != \"krimdok\")\n LOG_ERROR(\"subsystem_type must be one of {ixtheo,relbib,krimdok}!\");\n\n const auto db_connection(VuFind::GetDbConnection());\n\n std::string sql_query(\"SELECT id,firstname,lastname,email,tuefind_rss_feed_send_emails\"\n \",tuefind_rss_feed_last_notification FROM user\");\n if (vufind_user_id.empty())\n sql_query += \" WHERE tuefind_rss_feed_send_emails IS TRUE\";\n else\n sql_query += \" WHERE id=\" + db_connection->escapeAndQuoteString(vufind_user_id);\n db_connection->queryOrDie(sql_query);\n\n auto user_result_set(db_connection->getLastResultSet());\n std::unordered_map<std::string, UserInfo> ids_to_user_infos_map;\n while (const auto user_row = user_result_set.getNextRow())\n ids_to_user_infos_map[user_row[\"id\"]] =\n UserInfo(user_row[\"id\"], user_row[\"firstname\"], user_row[\"lastname\"], user_row[\"email\"],\n user_row[\"tuefind_rss_feed_last_notification\"]);\n\n unsigned feed_generation_count(0), email_sent_count(0);\n for (const auto &[user_id, user_info] : ids_to_user_infos_map) {\n if (vufind_user_id.empty() and not EmailSender::IsValidEmailAddress(user_info.email_)) {\n LOG_WARNING(\"no valid email address for vufind.user.id \" + user_id + \"!\");\n continue;\n }\n\n const std::string language(\"en\");\n if (ProcessFeeds(user_id, user_info.rss_feed_last_notification_, error_email_address, user_info.email_,\n GenerateUserAddress(user_info.first_name_, user_info.last_name_),\n language, vufind_user_id.empty(), subsystem_type, db_connection.get()))\n {\n if (vufind_user_id.empty())\n ++email_sent_count;\n ++feed_generation_count;\n }\n }\n LOG_INFO(\"Generated \" + std::to_string(feed_generation_count) + \" RSS feed(s) and sent \"\n + std::to_string(email_sent_count) + \" email(s).\");\n\n return EXIT_SUCCESS;\n}\n<commit_msg>Fixed an obvious bug.<commit_after>\/** \\file rss_subset_aggregator.cc\n * \\brief Aggregates RSS feeds.\n * \\author Dr. Johannes Ruscheinski (johannes.ruscheinski@uni-tuebingen.de)\n *\n * \\copyright 2021 Universitätsbibliothek Tübingen. All rights reserved.\n *\n * This program is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License as\n * published by the Free Software Foundation, either version 3 of the\n * License, or (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Affero General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public License\n * along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n#include <algorithm>\n#include <map>\n#include <unordered_map>\n#include <unordered_set>\n#include <cinttypes>\n#include <cstring>\n#include \"Compiler.h\"\n#include \"DbConnection.h\"\n#include \"DbResultSet.h\"\n#include \"EmailSender.h\"\n#include \"FileUtil.h\"\n#include \"HtmlUtil.h\"\n#include \"SqlUtil.h\"\n#include \"StringUtil.h\"\n#include \"SyndicationFormat.h\"\n#include \"Template.h\"\n#include \"UBTools.h\"\n#include \"util.h\"\n#include \"VuFind.h\"\n#include \"XmlWriter.h\"\n\n\nnamespace {\n\n\n[[noreturn]] void Usage() {\n ::Usage(\"--mode=(email|rss_xml) (user_id|error_email_address) subsystem_type]\\n\"\n \"If the mode is \\\"rss_xml\\\" a VuFind user_id needs to be specified, o\/w an error email address should be provided.\");\n}\n\n\nstruct HarvestedRSSItem {\n SyndicationFormat::Item item_;\n std::string feed_title_;\n std::string feed_url_;\n\n HarvestedRSSItem(const SyndicationFormat::Item item, const std::string feed_title, const std::string feed_url)\n : item_(item), feed_title_(feed_title), feed_url_(feed_url) {}\n};\n\n\nstruct ChannelDesc {\n std::string title_;\n std::string link_;\npublic:\n ChannelDesc(const std::string &title, const std::string &link)\n : title_(title), link_(link) { }\n};\n\n\nconst std::map<std::string, ChannelDesc> subsystem_type_to_channel_desc_map = {\n { \"relbib\", ChannelDesc(\"RelBib RSS Aggregator\", \"https:\/\/relbib.de\/\") },\n { \"ixtheo\", ChannelDesc(\"IxTheo RSS Aggregator\", \"https:\/\/itheo.de\/\") },\n { \"krimdok\", ChannelDesc(\"KrimDok RSS Aggregator\", \"https:\/\/krimdok.uni-tuebingen.de\/\") },\n};\n\n\nstd::string GetChannelDescEntry(const std::string &subsystem_type, const std::string &entry) {\n const auto subsystem_type_and_channel_desc(subsystem_type_to_channel_desc_map.find(subsystem_type));\n if (subsystem_type_and_channel_desc == subsystem_type_to_channel_desc_map.cend())\n LOG_ERROR(\"unknown subsystem type \\\"\" + subsystem_type + \"\\\"!\");\n\n if (entry == \"title\")\n return subsystem_type_and_channel_desc->second.title_;\n if (entry == \"link\")\n return subsystem_type_and_channel_desc->second.link_;\n LOG_ERROR(\"unknown entry name \\\"\" + entry + \"\\\"!\");\n}\n\n\nvoid WriteRSSFeedXMLOutput(const std::string &subsystem_type, const std::vector<HarvestedRSSItem> &harvested_items,\n XmlWriter * const xml_writer)\n{\n xml_writer->openTag(\"rss\", { { \"version\", \"2.0\" } });\n xml_writer->openTag(\"channel\");\n xml_writer->writeTagsWithData(\"title\", GetChannelDescEntry(subsystem_type, \"title\"));\n xml_writer->writeTagsWithData(\"link\", GetChannelDescEntry(subsystem_type, \"link\"));\n xml_writer->writeTagsWithData(\"description\", \"RSS Aggregator\");\n\n for (const auto &harvested_item : harvested_items) {\n xml_writer->openTag(\"item\");\n\n const auto title(harvested_item.item_.getTitle());\n if (not title.empty())\n xml_writer->writeTagsWithData(\"title\", harvested_item.item_.getTitle());\n\n xml_writer->writeTagsWithData(\"link\", harvested_item.item_.getLink());\n\n const auto description(HtmlUtil::ShortenText(harvested_item.item_.getDescription(), \/*max_length = *\/500));\n if (not description.empty())\n xml_writer->writeTagsWithData(\"description\", description);\n\n xml_writer->writeTagsWithData(\"pubDate\",\n TimeUtil::TimeTToString(harvested_item.item_.getPubDate(), TimeUtil::RFC822_FORMAT,\n TimeUtil::UTC));\n xml_writer->writeTagsWithData(\"guid\", harvested_item.item_.getId());\n xml_writer->closeTag(\"item\", \/* suppress_indent *\/ false);\n }\n\n xml_writer->closeTag(\"channel\");\n xml_writer->closeTag(\"rss\");\n}\n\n\nstruct FeedNameAndURL {\n std::string name_;\n std::string url_;\npublic:\n FeedNameAndURL() = default;\n FeedNameAndURL(const FeedNameAndURL &other) = default;\n FeedNameAndURL(const std::string &name, const std::string &url)\n : name_(name), url_(url) { }\n};\n\n\n\/\/ \\return True if a notification email was sent successfully, o\/w false.\nbool SendEmail(const std::string &subsystem_type, const std::string &email_sender, const std::string &user_email,\n const std::string &user_address, const std::string &language,\n const std::vector<HarvestedRSSItem> &harvested_items)\n{\n const auto template_filename_prefix(UBTools::GetTuelibPath() + \"rss_email.template\");\n std::string template_filename(template_filename_prefix + \".\" + language);\n if (not FileUtil::Exists(template_filename))\n template_filename = template_filename_prefix + \".en\";\n static const std::string email_template(FileUtil::ReadStringOrDie(template_filename));\n\n Template::Map names_to_values_map;\n names_to_values_map.insertScalar(\"user_email\", user_email);\n names_to_values_map.insertScalar(\"user_address\", user_address);\n\n std::vector<std::string> titles, links, descriptions;\n for (const auto &harvested_item : harvested_items) {\n titles.emplace_back(HtmlUtil::HtmlEscape(harvested_item.item_.getTitle()));\n links.emplace_back(harvested_item.item_.getLink());\n descriptions.emplace_back(HtmlUtil::HtmlEscape(harvested_item.item_.getDescription()));\n }\n names_to_values_map.insertArray(\"titles\", titles);\n names_to_values_map.insertArray(\"links\", links);\n names_to_values_map.insertArray(\"descriptions\", descriptions);\n\n const auto email_body(Template::ExpandTemplate(email_template, names_to_values_map));\n const auto retcode(EmailSender::SimplerSendEmail(email_sender, { user_email }, GetChannelDescEntry(subsystem_type, \"title\"),\n email_body, EmailSender::DO_NOT_SET_PRIORITY, EmailSender::HTML));\n if (retcode <= 299)\n return true;\n\n LOG_WARNING(\"EmailSender::SimplerSendEmail returned \" + std::to_string(retcode) + \" while trying to send to \\\"\"\n + user_email + \"\\\"!\");\n return false;\n}\n\n\nconst unsigned DEFAULT_XML_INDENT_AMOUNT(2);\n\n\nvoid GenerateFeed(const std::string &subsystem_type, const std::vector<HarvestedRSSItem> &harvested_items) {\n XmlWriter xml_writer(FileUtil::OpenOutputFileOrDie(\"\/dev\/stdout\").release(),\n XmlWriter::WriteTheXmlDeclaration, DEFAULT_XML_INDENT_AMOUNT);\n WriteRSSFeedXMLOutput(subsystem_type, harvested_items, &xml_writer);\n}\n\n\nbool ProcessFeeds(const std::string &user_id, const std::string &rss_feed_last_notification, const std::string &email_sender,\n const std::string &user_email, const std::string &user_address, const std::string &language,\n const bool send_email, const std::string &subsystem_type,\n DbConnection * const db_connection)\n{\n db_connection->queryOrDie(\"SELECT rss_feeds_id FROM tuefind_rss_subscriptions WHERE user_id=\" + user_id);\n auto rss_subscriptions_result_set(db_connection->getLastResultSet());\n std::vector<std::string> feed_ids;\n while (const auto row = rss_subscriptions_result_set.getNextRow())\\\n feed_ids.emplace_back(row[\"rss_feeds_id\"]);\n if (feed_ids.empty())\n return false;\n\n std::vector<HarvestedRSSItem> harvested_items;\n std::string max_insertion_time;\n for (const auto &feed_id : feed_ids) {\n db_connection->queryOrDie(\"SELECT feed_name,feed_url FROM tuefind_rss_feeds WHERE id=\" + feed_id);\n auto feed_result_set(db_connection->getLastResultSet());\n const auto feed_row(feed_result_set.getNextRow());\n const auto feed_name(feed_row[\"feed_name\"]);\n const auto feed_url(feed_row[\"feed_url\"]);\n feed_result_set.~DbResultSet();\n\n db_connection->queryOrDie(\"SELECT item_title,item_description,item_url,item_id,pub_date,insertion_time FROM \"\n \"tuefind_rss_items WHERE rss_feeds_id=\" + feed_id + \" AND insertion_time > '\"\n + rss_feed_last_notification + \"'\");\n auto items_result_set(db_connection->getLastResultSet());\n while (const auto item_row = items_result_set.getNextRow()) {\n harvested_items.emplace_back(SyndicationFormat::Item(item_row[\"item_title\"], item_row[\"item_description\"],\n item_row[\"item_url\"], item_row[\"item_id\"],\n SqlUtil::DatetimeToTimeT(item_row[\"pub_date\"])),\n feed_name, feed_url);\n const auto insertion_time(item_row[\"insertion_time\"]);\n if (insertion_time > max_insertion_time)\n max_insertion_time = insertion_time;\n }\n }\n if (harvested_items.empty())\n return false;\n\n if (send_email) {\n if (not SendEmail(subsystem_type, email_sender, user_email, user_address, language, harvested_items))\n return true;\n db_connection->queryOrDie(\"UPDATE user SET tuefind_rss_feed_last_notification='\" + max_insertion_time\n + \"' WHERE id=\" + user_id);\n } else\n GenerateFeed(subsystem_type, harvested_items);\n return true;\n}\n\n\n\/\/ Yes, this function has a confusing name but I could not think of a better one. :-(\n\/\/ What is meant is how to address a user!\nstd::string GenerateUserAddress(const std::string &first_name, const std::string &last_name) {\n if (last_name.empty())\n return first_name;\n\n return first_name + \" \" + last_name;\n}\n\n\n} \/\/ unnamed namespace\n\n\nstruct UserInfo {\n std::string user_id_;\n std::string first_name_;\n std::string last_name_;\n std::string email_;\n std::string rss_feed_last_notification_;\npublic:\n UserInfo() = default;\n UserInfo(const UserInfo &other) = default;\n UserInfo(const std::string &user_id, const std::string &first_name, const std::string &last_name,\n const std::string &email, const std::string &rss_feed_last_notification)\n : user_id_(user_id), first_name_(first_name), last_name_(last_name), email_(email),\n rss_feed_last_notification_(rss_feed_last_notification) { }\n};\n\n\nint Main(int argc, char *argv[]) {\n if (argc != 4)\n Usage();\n\n std::string error_email_address, vufind_user_id;\n if (std::strcmp(argv[1], \"--mode=email\") == 0)\n vufind_user_id = argv[2];\n else if (std::strcmp(argv[1], \"--mode=rss_xml\") == 0)\n vufind_user_id = argv[2];\n else\n Usage();\n const std::string subsystem_type(argv[3]);\n if (subsystem_type != \"ixtheo\" and subsystem_type != \"relbib\" and subsystem_type != \"krimdok\")\n LOG_ERROR(\"subsystem_type must be one of {ixtheo,relbib,krimdok}!\");\n\n const auto db_connection(VuFind::GetDbConnection());\n\n std::string sql_query(\"SELECT id,firstname,lastname,email,tuefind_rss_feed_send_emails\"\n \",tuefind_rss_feed_last_notification FROM user\");\n if (vufind_user_id.empty())\n sql_query += \" WHERE tuefind_rss_feed_send_emails IS TRUE\";\n else\n sql_query += \" WHERE id=\" + db_connection->escapeAndQuoteString(vufind_user_id);\n db_connection->queryOrDie(sql_query);\n\n auto user_result_set(db_connection->getLastResultSet());\n std::unordered_map<std::string, UserInfo> ids_to_user_infos_map;\n while (const auto user_row = user_result_set.getNextRow())\n ids_to_user_infos_map[user_row[\"id\"]] =\n UserInfo(user_row[\"id\"], user_row[\"firstname\"], user_row[\"lastname\"], user_row[\"email\"],\n user_row[\"tuefind_rss_feed_last_notification\"]);\n\n unsigned feed_generation_count(0), email_sent_count(0);\n for (const auto &[user_id, user_info] : ids_to_user_infos_map) {\n if (vufind_user_id.empty() and not EmailSender::IsValidEmailAddress(user_info.email_)) {\n LOG_WARNING(\"no valid email address for vufind.user.id \" + user_id + \"!\");\n continue;\n }\n\n const std::string language(\"en\");\n if (ProcessFeeds(user_id, user_info.rss_feed_last_notification_, error_email_address, user_info.email_,\n GenerateUserAddress(user_info.first_name_, user_info.last_name_),\n language, vufind_user_id.empty(), subsystem_type, db_connection.get()))\n {\n if (vufind_user_id.empty())\n ++email_sent_count;\n ++feed_generation_count;\n }\n }\n LOG_INFO(\"Generated \" + std::to_string(feed_generation_count) + \" RSS feed(s) and sent \"\n + std::to_string(email_sent_count) + \" email(s).\");\n\n return EXIT_SUCCESS;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2015 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"flutter\/shell\/common\/vsync_waiter.h\"\n\n#include \"flutter\/fml\/task_runner.h\"\n#include \"flutter\/fml\/trace_event.h\"\n\nnamespace shell {\n\nVsyncWaiter::VsyncWaiter(blink::TaskRunners task_runners)\n : task_runners_(std::move(task_runners)) {}\n\nVsyncWaiter::~VsyncWaiter() = default;\n\nvoid VsyncWaiter::AsyncWaitForVsync(Callback callback) {\n {\n std::lock_guard<std::mutex> lock(callback_mutex_);\n callback_ = std::move(callback);\n }\n AwaitVSync();\n}\n\nvoid VsyncWaiter::FireCallback(fml::TimePoint frame_start_time,\n fml::TimePoint frame_target_time) {\n Callback callback;\n\n {\n std::lock_guard<std::mutex> lock(callback_mutex_);\n callback = std::move(callback_);\n }\n\n if (!callback) {\n return;\n }\n\n task_runners_.GetUITaskRunner()->PostTask(\n [callback, frame_start_time, frame_target_time]() {\n \/\/ Note: The tag name must be \"VSYNC\" (it is special) so that the\n \/\/ \"Highlight\n \/\/ Vsync\" checkbox in the timeline can be enabled.\n TRACE_EVENT0(\"flutter\", \"VSYNC\");\n callback(frame_start_time, frame_target_time);\n });\n}\n\n} \/\/ namespace shell\n<commit_msg>Remove the \"VSYNC\" trace event on Fuchsia (#5907)<commit_after>\/\/ Copyright 2015 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"flutter\/shell\/common\/vsync_waiter.h\"\n\n#include \"flutter\/fml\/task_runner.h\"\n#include \"flutter\/fml\/trace_event.h\"\n\nnamespace shell {\n\nVsyncWaiter::VsyncWaiter(blink::TaskRunners task_runners)\n : task_runners_(std::move(task_runners)) {}\n\nVsyncWaiter::~VsyncWaiter() = default;\n\nvoid VsyncWaiter::AsyncWaitForVsync(Callback callback) {\n {\n std::lock_guard<std::mutex> lock(callback_mutex_);\n callback_ = std::move(callback);\n }\n AwaitVSync();\n}\n\nvoid VsyncWaiter::FireCallback(fml::TimePoint frame_start_time,\n fml::TimePoint frame_target_time) {\n Callback callback;\n\n {\n std::lock_guard<std::mutex> lock(callback_mutex_);\n callback = std::move(callback_);\n }\n\n if (!callback) {\n return;\n }\n\n task_runners_.GetUITaskRunner()->PostTask(\n [callback, frame_start_time, frame_target_time]() {\n#if defined(OS_FUCHSIA)\n \/\/ In general, traces on Fuchsia are recorded across the whole system.\n \/\/ Because of this, emitting a \"VSYNC\" event per flutter process is\n \/\/ undesirable, as the events will collide with each other. We\n \/\/ instead let another area of the system emit them.\n TRACE_EVENT0(\"flutter\", \"vsync callback\");\n#else\n \/\/ Note: The tag name must be \"VSYNC\" (it is special) so that the\n \/\/ \"Highlight Vsync\" checkbox in the timeline can be enabled.\n TRACE_EVENT0(\"flutter\", \"VSYNC\");\n#endif\n callback(frame_start_time, frame_target_time);\n });\n}\n\n} \/\/ namespace shell\n<|endoftext|>"} {"text":"<commit_before>#include \"video.h\"\n\n#include \"SDL_render.h\"\n\n#include \"debug.h\"\n\nvoid capture_application_target() {\n SDL_GL_BindTexture ( shim.target, nullptr, nullptr );\n libshimmer->capture_application_texture();\n}\n\nvoid set_application_render_target() {\n if ( shim.target ) {\n SDL_DestroyTexture ( shim.target );\n }\n\n int w, h;\n\n SDL_GetWindowSize ( shim.window, &w, &h );\n\n shim.target = SDL_CreateTexture ( shim.renderer,\n SDL_PIXELFORMAT_BGRA32,\n SDL_TEXTUREACCESS_TARGET,\n w, h );\n\n if ( SDL_SetRenderTarget ( shim.renderer, shim.target ) != 0 ) {\n std::cout << \"Could not set render target: \"\n << SDL_GetError() << std::endl;\n\n std::cout << glpp::gl_framebuffer_status_to_string (\n glpp::framebuffer::check_status() ) << \"\\n\";\n }\n\n capture_application_target();\n}\n\nvoid init_shimmer() {\n if ( !shim.opengl_initiliased ) {\n glewExperimental = GL_TRUE;\n\n GLenum glew_err = glewInit();\n\n if ( glew_err ) {\n std::cerr << \"Error) Unable to initialise GLEW: \"\n << glewGetErrorString ( glew_err ) << std::endl;\n }\n\n shim.opengl_initiliased = true;\n }\n\n libshimmer->init_renderer();\n}\n\nSDL_Window* SDL_CreateWindow ( const char* title,\n int x,\n int y,\n int w,\n int h,\n Uint32 flags ) {\n SHIM_LOG ( 2 );\n\n std::string wtitle = title;\n glpp::coords_2i coords ( x, y );\n glpp::dims_2u dims ( w, h );\n libshimmer->create_window ( wtitle, coords, dims );\n\n \/\/ if ( libshimmer->scaling_enabled() )\n\n flags |= SDL_WINDOW_RESIZABLE | SDL_WINDOW_OPENGL;\n\n shim.window = sym::SDL_CreateWindow ( wtitle.c_str(),\n coords.x,\n coords.y,\n dims.width,\n dims.height,\n flags );\n\n return shim.window;\n}\n\nSDL_Renderer* SDL_CreateRenderer ( SDL_Window* window,\n int index,\n Uint32 flags ) {\n SHIM_LOG ( 10 );\n\n shim.renderer = sym::SDL_CreateRenderer ( window, -1,\n SDL_RENDERER_ACCELERATED |\n SDL_RENDERER_TARGETTEXTURE );\n\n init_shimmer();\n\n set_application_render_target();\n\n return shim.renderer;\n}\n\nint SDL_CreateWindowAndRenderer ( int width,\n int height,\n Uint32 window_flags,\n SDL_Window** window,\n SDL_Renderer** renderer ) {\n SHIM_LOG ( 10 );\n\n shim.window = SDL_CreateWindow ( \"SDL2 Application\",\n 0,\n 0,\n width,\n height,\n window_flags );\n\n if ( !shim.window ) {\n return -1;\n }\n\n shim.renderer = SDL_CreateRenderer ( shim.window,\n -1,\n SDL_RENDERER_ACCELERATED |\n SDL_RENDERER_TARGETTEXTURE );\n\n init_shimmer();\n\n set_application_render_target();\n\n return shim.renderer ? 0 : -1;\n}\n\nvoid SDL_RenderPresent ( SDL_Renderer* renderer ) {\n SHIM_LOG ( 10 );\n\n if ( shim.renderer == renderer ) {\n SDL_SetRenderTarget ( shim.renderer, nullptr );\n\n libshimmer->refresh_display();\n sym::SDL_RenderPresent ( renderer );\n\n SDL_SetRenderTarget ( shim.renderer, shim.target );\n }\n else {\n sym::SDL_RenderPresent ( renderer );\n }\n}\n\nvoid SDL_GL_SwapWindow ( SDL_Window* window ) {\n SHIM_LOG ( 1 );\n sym::SDL_GL_SwapWindow ( window );\n}\n\nvoid SDL_SetWindowTitle ( SDL_Window* window,\n const char* title ) {\n std::string wtitle = title;\n libshimmer->set_window_title ( wtitle );\n sym::SDL_SetWindowTitle ( window, wtitle.c_str() );\n}\n\nint SDL_SetWindowDisplayMode ( SDL_Window* window,\n const SDL_DisplayMode* mode ) {\n SHIM_LOG ( 10 );\n\n return sym::SDL_SetWindowDisplayMode ( window, mode );\n}\n\nvoid SDL_DestroyWindow ( SDL_Window* window ) {\n SHIM_LOG ( 10 );\n\n \/\/ if ( shim.window != window ) {\n sym::SDL_DestroyWindow ( window );\n\n \/\/ }\n}\n\nvoid SDL_DestroyRenderer ( SDL_Renderer* renderer ) {\n SHIM_LOG ( 10 );\n\n \/\/ if ( shim.renderer != renderer ) {\n sym::SDL_DestroyRenderer ( renderer );\n\n \/\/ }\n}\n\nvoid SDL_GetWindowSize ( SDL_Window* window,\n int* w,\n int* h ) {\n auto dims = libshimmer->app_surface_dims();\n\n *w = dims.width;\n *h = dims.height;\n}\n<commit_msg>[sdl2] Reuse shimmer window and renderer when application request changes.<commit_after>#include \"video.h\"\n\n#include \"SDL_render.h\"\n\n#include \"debug.h\"\n\nvoid capture_application_target() {\n SDL_GL_BindTexture ( shim.target, nullptr, nullptr );\n libshimmer->capture_application_texture();\n}\n\nvoid set_application_render_target() {\n if ( shim.target ) {\n SDL_DestroyTexture ( shim.target );\n }\n\n int w, h;\n\n SDL_GetWindowSize ( shim.window, &w, &h );\n\n shim.target = SDL_CreateTexture ( shim.renderer,\n SDL_PIXELFORMAT_BGRA32,\n SDL_TEXTUREACCESS_TARGET,\n w, h );\n\n if ( SDL_SetRenderTarget ( shim.renderer, shim.target ) != 0 ) {\n std::cout << \"Could not set render target: \"\n << SDL_GetError() << std::endl;\n\n std::cout << glpp::gl_framebuffer_status_to_string (\n glpp::framebuffer::check_status() ) << \"\\n\";\n }\n\n capture_application_target();\n}\n\nvoid init_shimmer() {\n if ( !shim.opengl_initiliased ) {\n glewExperimental = GL_TRUE;\n\n GLenum glew_err = glewInit();\n\n if ( glew_err ) {\n std::cerr << \"Error) Unable to initialise GLEW: \"\n << glewGetErrorString ( glew_err ) << std::endl;\n }\n\n shim.opengl_initiliased = true;\n }\n\n libshimmer->init_renderer();\n}\n\nSDL_Window* SDL_CreateWindow ( const char* title,\n int x,\n int y,\n int w,\n int h,\n Uint32 flags ) {\n SHIM_LOG ( 2 );\n\n std::string wtitle = title;\n glpp::coords_2i coords ( x, y );\n glpp::dims_2u dims ( w, h );\n libshimmer->create_window ( wtitle, coords, dims );\n\n if ( !shim.window ) {\n \/\/ if ( libshimmer->scaling_enabled() )\n\n flags |= SDL_WINDOW_RESIZABLE | SDL_WINDOW_OPENGL;\n\n shim.window = sym::SDL_CreateWindow ( wtitle.c_str(),\n coords.x,\n coords.y,\n dims.width,\n dims.height,\n flags );\n }\n else {\n set_application_render_target();\n }\n\n return shim.window;\n}\n\nSDL_Renderer* SDL_CreateRenderer ( SDL_Window* window,\n int index,\n Uint32 flags ) {\n SHIM_LOG ( 10 );\n\n if ( shim.window == window ) {\n if ( !shim.renderer ) {\n shim.renderer = sym::SDL_CreateRenderer ( window, -1,\n SDL_RENDERER_ACCELERATED |\n SDL_RENDERER_TARGETTEXTURE );\n\n init_shimmer();\n\n set_application_render_target();\n }\n\n return shim.renderer;\n }\n\n return sym::SDL_CreateRenderer ( window, index, flags );\n}\n\nint SDL_CreateWindowAndRenderer ( int width,\n int height,\n Uint32 window_flags,\n SDL_Window** window,\n SDL_Renderer** renderer ) {\n SHIM_LOG ( 10 );\n\n SDL_CreateWindow ( \"SDL2 Application\", 0, 0, width, height, window_flags );\n\n if ( !shim.window ) return -1;\n\n SDL_CreateRenderer ( shim.window, 0, 0 );\n\n return shim.renderer ? 0 : -1;\n}\n\nvoid SDL_RenderPresent ( SDL_Renderer* renderer ) {\n SHIM_LOG ( 10 );\n\n if ( shim.renderer == renderer ) {\n SDL_SetRenderTarget ( shim.renderer, nullptr );\n\n libshimmer->refresh_display();\n sym::SDL_RenderPresent ( renderer );\n\n SDL_SetRenderTarget ( shim.renderer, shim.target );\n }\n else {\n sym::SDL_RenderPresent ( renderer );\n }\n}\n\nvoid SDL_GL_SwapWindow ( SDL_Window* window ) {\n SHIM_LOG ( 1 );\n sym::SDL_GL_SwapWindow ( window );\n}\n\nvoid SDL_SetWindowTitle ( SDL_Window* window,\n const char* title ) {\n std::string wtitle = title;\n libshimmer->set_window_title ( wtitle );\n sym::SDL_SetWindowTitle ( window, wtitle.c_str() );\n}\n\nint SDL_SetWindowDisplayMode ( SDL_Window* window,\n const SDL_DisplayMode* mode ) {\n SHIM_LOG ( 10 );\n\n return sym::SDL_SetWindowDisplayMode ( window, mode );\n}\n\nvoid SDL_DestroyWindow ( SDL_Window* window ) {\n SHIM_LOG ( 10 );\n\n if ( shim.window != window ) {\n sym::SDL_DestroyWindow ( window );\n }\n}\n\nvoid SDL_DestroyRenderer ( SDL_Renderer* renderer ) {\n SHIM_LOG ( 10 );\n\n if ( shim.renderer != renderer ) {\n sym::SDL_DestroyRenderer ( renderer );\n }\n}\n\nvoid SDL_GetWindowSize ( SDL_Window* window,\n int* w,\n int* h ) {\n auto dims = libshimmer->app_surface_dims();\n\n *w = dims.width;\n *h = dims.height;\n}\n<|endoftext|>"} {"text":"<commit_before>#ifdef BARRELFISH\nextern \"C\" {\n#include <lua\/lua.h>\n#include <lua\/lualib.h>\n#include <lua\/lauxlib.h>\n}\n#else\nextern \"C\" {\n#include \"lua.h\"\n#include \"lualib.h\"\n#include \"lauxlib.h\"\n}\n#endif\n\n#include <cstdio>\n#include <cassert>\n#include <cstring>\n\n#include \"shl_internal.h\"\n#include \"shl_timer.hpp\"\n\n\/**\n *\n *\/\nconst char* shl__arr_feature_table[] = {\n \"partitioning\",\n \"replication\",\n \"distribution\",\n \"hugepage\"\n};\n\n#ifdef BARRELFISH\n\/\/static const char* SETTINGS_FILE = \"\/nfs\/array_settings.lua\";\n#else\nstatic const char* SETTINGS_FILE = \"settings.lua\";\n#endif\n\n\/\/\/<\nstatic lua_State *L = NULL;\n\n\/\/\/<\nstatic Timer lua_timer;\n\n#if 0\n\/\/ http:\/\/windrealm.org\/tutorials\/reading-a-lua-configuration-file-from-c.php\nstatic const char* shl__lua_stringexpr(lua_State* lua, const char* expr, const char* def)\n{\n\n const char* r = def;\n char buf[256] = \"\";\n\n \/* Assign the Lua expression to a Lua global variable. *\/\n sprintf(buf, \"evalExpr=%s\", expr);\n if (!luaL_dostring(lua, buf)) {\n\n \/* Get the value of the global varibable *\/\n lua_getglobal(lua, \"evalExpr\");\n if (lua_isstring(lua, -1)) {\n r = lua_tostring(lua, -1);\n }\n\n \/* remove lua_getglobal value *\/\n lua_pop(lua, 1);\n }\n\n return r;\n}\n#endif\n\n\/**\n *\n * @param lua\n * @param expr\n * @param def_val\n * @return\n *\/\nstatic int shl__lua_boolexpr(lua_State* lua, const char* expr, bool def_val)\n{\n int ok = def_val;\n char buf[256] = \"\";\n\n \/* Assign the Lua expression to a Lua global variable. *\/\n\n printf(\"Querying [%s] ..\", expr);\n\n sprintf(buf, \"evalExpr=%s\", expr);\n\n if (!luaL_dostring(lua, buf)) {\n\n \/* Get the value of the global varibable *\/\n\n lua_getglobal(lua, \"evalExpr\");\n\n if (lua_isboolean(lua, -1)) {\n ok = lua_toboolean(lua, -1);\n printf(\" .. found %d\", ok);\n }\n\n \/* remove lua_getglobal value *\/\n\n lua_pop(lua, 1);\n\n }\n\n printf(\" .. result %d\\n\", ok);\n\n return ok;\n\n}\n\n\/**\n * \\brief Return array feature configuration for given array\n *\/\nbool shl__get_array_conf(const char *array_name, int feature, bool def)\n{\n lua_timer.start();\n assert(strlen(array_name) < SHL__ARRAY_NAME_LEN_MAX);\n assert(strncmp(array_name, \"shl__\", 5) == 0);\n\n array_name = array_name + strlen(\"shl__\");\n\n char tmp[256 + SHL__ARRAY_NAME_LEN_MAX];\n\n sprintf(tmp, \"settings.arrays[\\\"%s\\\"].%s\", array_name,\n shl__arr_feature_table[feature]);\n\n bool res = shl__lua_boolexpr(L, tmp, def);\n lua_timer.stop();\n\n return res;\n}\n\n\/**\n *\n *\/\nvoid shl__lua_init(void)\n{\n lua_timer.start();\n#ifndef BARRELFISH\n L = luaL_newstate();\n if (L) {\n luaL_openlibs(L);\n } else {\n printf(\"ERROR: opening LUA\\n\");\n }\n\n \/\/ Load settings file\n if ( luaL_dofile( L, SETTINGS_FILE ) == 1) {\n printf(\"Error loading %s\\n\", SETTINGS_FILE);\n assert(!\"Error loading settings-file. Check it's syntax.\");\n }\n\n \/\/ luaL_loadbuffer(L, program, strlen(program), \"line\")\n#endif\n lua_timer.stop();\n}\n\n\/**\n *\n *\/\nvoid shl__lua_deinit(void)\n{\n lua_close(L);\n L = NULL;\n printf(\"LUA done (time spent: %f)\\n\", lua_timer.get());\n}\n<commit_msg>reverted ifdef of lua init<commit_after>#ifdef BARRELFISH\nextern \"C\" {\n#include <lua\/lua.h>\n#include <lua\/lualib.h>\n#include <lua\/lauxlib.h>\n}\n#else\nextern \"C\" {\n#include \"lua.h\"\n#include \"lualib.h\"\n#include \"lauxlib.h\"\n}\n#endif\n\n#include <cstdio>\n#include <cassert>\n#include <cstring>\n\n#include \"shl_internal.h\"\n#include \"shl_timer.hpp\"\n\n\/**\n *\n *\/\nconst char* shl__arr_feature_table[] = {\n \"partitioning\",\n \"replication\",\n \"distribution\",\n \"hugepage\"\n};\n\n#ifdef BARRELFISH\nstatic const char* SETTINGS_FILE = \"\/nfs\/array_settings.lua\";\n#else\nstatic const char* SETTINGS_FILE = \"settings.lua\";\n#endif\n\n\/\/\/<\nstatic lua_State *L = NULL;\n\n\/\/\/<\nstatic Timer lua_timer;\n\n#if 0\n\/\/ http:\/\/windrealm.org\/tutorials\/reading-a-lua-configuration-file-from-c.php\nstatic const char* shl__lua_stringexpr(lua_State* lua, const char* expr, const char* def)\n{\n\n const char* r = def;\n char buf[256] = \"\";\n\n \/* Assign the Lua expression to a Lua global variable. *\/\n sprintf(buf, \"evalExpr=%s\", expr);\n if (!luaL_dostring(lua, buf)) {\n\n \/* Get the value of the global varibable *\/\n lua_getglobal(lua, \"evalExpr\");\n if (lua_isstring(lua, -1)) {\n r = lua_tostring(lua, -1);\n }\n\n \/* remove lua_getglobal value *\/\n lua_pop(lua, 1);\n }\n\n return r;\n}\n#endif\n\n\/**\n *\n * @param lua\n * @param expr\n * @param def_val\n * @return\n *\/\nstatic int shl__lua_boolexpr(lua_State* lua, const char* expr, bool def_val)\n{\n int ok = def_val;\n char buf[256] = \"\";\n\n \/* Assign the Lua expression to a Lua global variable. *\/\n\n printf(\"Querying [%s] ..\", expr);\n\n sprintf(buf, \"evalExpr=%s\", expr);\n\n if (!luaL_dostring(lua, buf)) {\n\n \/* Get the value of the global varibable *\/\n\n lua_getglobal(lua, \"evalExpr\");\n\n if (lua_isboolean(lua, -1)) {\n ok = lua_toboolean(lua, -1);\n printf(\" .. found %d\", ok);\n }\n\n \/* remove lua_getglobal value *\/\n\n lua_pop(lua, 1);\n\n }\n\n printf(\" .. result %d\\n\", ok);\n\n return ok;\n\n}\n\n\/**\n * \\brief Return array feature configuration for given array\n *\/\nbool shl__get_array_conf(const char *array_name, int feature, bool def)\n{\n lua_timer.start();\n assert(strlen(array_name) < SHL__ARRAY_NAME_LEN_MAX);\n assert(strncmp(array_name, \"shl__\", 5) == 0);\n\n array_name = array_name + strlen(\"shl__\");\n\n char tmp[256 + SHL__ARRAY_NAME_LEN_MAX];\n\n sprintf(tmp, \"settings.arrays[\\\"%s\\\"].%s\", array_name,\n shl__arr_feature_table[feature]);\n\n bool res = shl__lua_boolexpr(L, tmp, def);\n lua_timer.stop();\n\n return res;\n}\n\n\/**\n *\n *\/\nvoid shl__lua_init(void)\n{\n lua_timer.start();\n L = luaL_newstate();\n if (L) {\n luaL_openlibs(L);\n } else {\n printf(\"ERROR: opening LUA\\n\");\n }\n\n \/\/ Load settings file\n if ( luaL_dofile( L, SETTINGS_FILE ) == 1) {\n printf(\"Error loading %s\\n\", SETTINGS_FILE);\n assert(!\"Error loading settings-file. Check it's syntax.\");\n }\n\n \/\/ luaL_loadbuffer(L, program, strlen(program), \"line\")\n lua_timer.stop();\n}\n\n\/**\n *\n *\/\nvoid shl__lua_deinit(void)\n{\n lua_close(L);\n L = NULL;\n printf(\"LUA done (time spent: %f)\\n\", lua_timer.get());\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n*soundplayer.cpp: Many helpful sound functions.\nBy 2MB Solutions: https\/\/2mb.solutions\nReleased under the MIT license. See license.txt for details.\nBilly: https:\/\/stormdragon.tk\/\nMichael: https:\/\/michaeltaboada.me\n*\/\n#include <allegro5\/allegro.h>\n#include \"dynamic_menu.h\"\n#include <keyboard.h>\n#include <sound.h>\n#include <string>\n#include <misc.h>\n#include <menu_helper.h>\n#include \"soundplayer.h\"\n\n\n\nint power_bar(string soundstring, int p, int min, int max, float wait)\n{\nsound s;\nif(!s.load(soundstring)) {\nlog(\"Could not load power bar sound.\\n\");\nreturn -100;\n}\ns.set_pitch(min);\ns.set_loop(true);\nif(!s.play()) {\nlog(\"Could not play power bar sound.\\n\");\nreturn -100;\n}\nif(p > min-1) {\nfor(int x = min; x <= p; x++) {\nal_rest(wait);\ns.set_pitch(s.get_pitch()+1);\n}\n}\nelse {\nkeyboard kb;\nint dir = 1;\nwhile(!kb.key_pressed(ALLEGRO_KEY_SPACE)) {\nif(kb.key_pressed(ALLEGRO_KEY_ESCAPE) || ((kb.key_down(ALLEGRO_KEY_ALT) || kb.key_down(ALLEGRO_KEY_ALTGR)) && kb.key_pressed(ALLEGRO_KEY_F4))) {\nreturn -100;\n}\nif (kb.key_pressed(ALLEGRO_KEY_BACKSPACE)) {\nreturn -101;\n}\nal_rest(wait);\ns.set_pitch(s.get_pitch()+dir);\nif(s.get_pitch() >= max) {\ndir = -1;\n}\nelse if(s.get_pitch() <= min) {\ndir = 1;\n}\n}\n}\ns.stop();\nreturn s.get_pitch();\n}\n\nint direction_bar(string soundstring, int d, int min, int max, float wait)\n{\nsound s;\nif(!s.load(soundstring)) {\nlog(\"Could not load direction bar sound.\\n\");\nreturn -100;\n}\ns.set_pan(min);\ns.set_loop(true);\nif(!s.play()) {\nlog(\"Could not play direction bar sound.\\n\");\nreturn -100;\n}\nif(d >= min && d <= max) {\nfor (int x = min; x <= d; x++) {\nal_rest(wait);\ns.set_pan(x);\n}\n}\nelse {\nkeyboard kb;\nint dir = 1;\nwhile(!kb.key_pressed(ALLEGRO_KEY_SPACE)) {\nif(kb.key_pressed(ALLEGRO_KEY_ESCAPE) || ((kb.key_down(ALLEGRO_KEY_ALT) || kb.key_down(ALLEGRO_KEY_ALTGR)) && kb.key_pressed(ALLEGRO_KEY_F4))) {\nreturn -100;\n}\nif(kb.key_pressed(ALLEGRO_KEY_BACKSPACE)) {\nreturn -101;\n}\nal_rest(wait);\ns.set_pan(s.get_pan()+dir);\nif(s.get_pan() >= max) {\ndir = -1;\n}\nelse if(s.get_pan() <= min) {\ndir = 1;\n}\n}\n}\ns.stop();\nreturn s.get_pan();\n}\n\nvoid fade(sound* s, int start, int end, float time) {\nif(!s) {\nreturn;\n}\ns->set_gain(start);\nfor(int x = 0; x < time\/0.005; x++) {\nal_rest(0.005);\ns->set_gain(s->get_gain()+((end-start)\/(time\/0.005)+start));\n}\ns->stop();\n}\n\nbool play_sound_wait(sound* s) {\nif(!s->play()) {\nlog(\"Could not play sound file.\\n\");\nreturn false;\n}\nwhile(s->is_playing()) {\nal_rest(0.005);\n}\nreturn true;\n}\n\nbool play_sound_wait(string s) {\nsound so;\nif(!so.load(s)) {\nlog(((string)(\"Could not load sound \")+s+\".\\n\").c_str());\nreturn false;\n}\nelse {\nreturn play_sound_wait(&so);\n}\n}\n\nvoid learn_sounds() {\nvector<string>* vec = get_dir_children(\"sounds\", 1);\nvector<string> real_items;\nfor (int x = 0; x < vec->size(); x++) {\nif((*vec)[x].find(\"-music\") == string::npos) {\nstring temp = (*vec)[x];\nint pos = temp.find(\"-\");\nwhile(pos != string::npos) {\ntemp.replace(pos, 1, \" \");\npos = temp.find(\"-\", pos+1);\n}\ntemp.replace(temp.find(\".\"), string::npos, \"\");\nreal_items.push_back(temp);\n}\nelse {\nvec->erase(vec->begin()+x);\nx--;\n}\n}\nreal_items.push_back(\"back to main menu\");\ndynamic_menu* menu = create_menu(real_items, vector<string>());\nint ran = menu->run_extended(\"\", \"Use your arrow keys to navigate the menu, and enter to play the sound. Pressing space while the sound is playing will stop it.\", 1, true);\nkeyboard kb;\nwhile(ran != -1 && ran != 0 && ran != real_items.size()) {\nsound s;\ns.load((string)(\"sounds\/\")+(*vec)[ran-1]);\ns.play();\nwhile(s.is_playing()) {\nif(kb.key_pressed(ALLEGRO_KEY_SPACE)) {\nbreak;\n}\n}\ns.stop();\nran = menu->run_extended(\"\", \"\", ran, false);\n}\ndelete vec;\ndelete menu;\n}\n\n<commit_msg>Hopefully fixed crashes.<commit_after>\/*\n*soundplayer.cpp: Many helpful sound functions.\nBy 2MB Solutions: https\/\/2mb.solutions\nReleased under the MIT license. See license.txt for details.\nBilly: https:\/\/stormdragon.tk\/\nMichael: https:\/\/michaeltaboada.me\n*\/\n#include <allegro5\/allegro.h>\n#include \"dynamic_menu.h\"\n#include <keyboard.h>\n#include <sound.h>\n#include <string>\n#include <misc.h>\n#include <menu_helper.h>\n#include \"soundplayer.h\"\n\n\n\nint power_bar(string soundstring, int p, int min, int max, float wait)\n{\nsound s;\nif(!s.load(soundstring)) {\nlog(\"Could not load power bar sound.\\n\");\nreturn -100;\n}\ns.set_pitch(min);\ns.set_loop(true);\nif(!s.play()) {\nlog(\"Could not play power bar sound.\\n\");\nreturn -100;\n}\nif(p > min-1) {\nfor(int x = min; x <= p; x++) {\nal_rest(wait);\ns.set_pitch(s.get_pitch()+1);\n}\n}\nelse {\nkeyboard kb;\nint dir = 1;\nwhile(!kb.key_pressed(ALLEGRO_KEY_SPACE)) {\nif(kb.key_pressed(ALLEGRO_KEY_ESCAPE) || ((kb.key_down(ALLEGRO_KEY_ALT) || kb.key_down(ALLEGRO_KEY_ALTGR)) && kb.key_pressed(ALLEGRO_KEY_F4))) {\nreturn -100;\n}\nif (kb.key_pressed(ALLEGRO_KEY_BACKSPACE)) {\nreturn -101;\n}\nal_rest(wait);\ns.set_pitch(s.get_pitch()+dir);\nif(s.get_pitch() >= max) {\ndir = -1;\n}\nelse if(s.get_pitch() <= min) {\ndir = 1;\n}\n}\n}\ns.stop();\nreturn s.get_pitch();\n}\n\nint direction_bar(string soundstring, int d, int min, int max, float wait)\n{\nsound s;\nif(!s.load(soundstring)) {\nlog(\"Could not load direction bar sound.\\n\");\nreturn -100;\n}\ns.set_pan(min);\ns.set_loop(true);\nif(!s.play()) {\nlog(\"Could not play direction bar sound.\\n\");\nreturn -100;\n}\nif(d >= min && d <= max) {\nfor (int x = min; x <= d; x++) {\nal_rest(wait);\ns.set_pan(x);\n}\n}\nelse {\nkeyboard kb;\nint dir = 1;\nwhile(!kb.key_pressed(ALLEGRO_KEY_SPACE)) {\nif(kb.key_pressed(ALLEGRO_KEY_ESCAPE) || ((kb.key_down(ALLEGRO_KEY_ALT) || kb.key_down(ALLEGRO_KEY_ALTGR)) && kb.key_pressed(ALLEGRO_KEY_F4))) {\nreturn -100;\n}\nif(kb.key_pressed(ALLEGRO_KEY_BACKSPACE)) {\nreturn -101;\n}\nal_rest(wait);\ns.set_pan(s.get_pan()+dir);\nif(s.get_pan() >= max) {\ndir = -1;\n}\nelse if(s.get_pan() <= min) {\ndir = 1;\n}\n}\n}\ns.stop();\nreturn s.get_pan();\n}\n\nvoid fade(sound* s, int start, int end, float time) {\nif(!s) {\nreturn;\n}\ns->set_gain(start);\nfor(int x = 0; x < time\/0.005; x++) {\nal_rest(0.005);\ns->set_gain(s->get_gain()+((end-start)\/(time\/0.005)+start));\n}\ns->stop();\n}\n\nbool play_sound_wait(sound* s) {\nif(!s->play()) {\nlog(\"Could not play sound file.\\n\");\nreturn false;\n}\nwhile(s->is_playing()) {\nal_rest(0.005);\n}\nreturn true;\n}\n\nbool play_sound_wait(string s) {\nsound so;\nif(!so.load(s)) {\nlog(((string)(\"Could not load sound \")+s+\".\\n\").c_str());\nreturn false;\n}\nelse {\nreturn play_sound_wait(&so);\n}\n}\n\nvoid learn_sounds() {\nvector<string>* vec = get_dir_children(\"sounds\", 1);\nvector<string> real_items;\nif (vec) {\nfor (int x = 0; x < vec->size(); x++) {\nif((*vec)[x].find(\"-music\") == string::npos) {\nstring temp = (*vec)[x];\nint pos = temp.find(\"-\");\nwhile(pos != string::npos) {\ntemp.replace(pos, 1, \" \");\npos = temp.find(\"-\", pos+1);\n}\ntemp.replace(temp.find(\".\"), string::npos, \"\");\nreal_items.push_back(temp);\n}\nelse {\nvec->erase(vec->begin()+x);\nx--;\n}\n}\nreal_items.push_back(\"back to main menu\");\ndynamic_menu* menu = create_menu(real_items, vector<string>());\nint ran = menu->run_extended(\"\", \"Use your arrow keys to navigate the menu, and enter to play the sound. Pressing space while the sound is playing will stop it.\", 1, true);\nkeyboard kb;\nwhile(ran != -1 && ran != 0 && ran != real_items.size()) {\nsound s;\ns.load((string)(\"sounds\/\")+(*vec)[ran-1]);\ns.play();\nwhile(s.is_playing()) {\nif(kb.key_pressed(ALLEGRO_KEY_SPACE)) {\nbreak;\n}\n}\ns.stop();\nran = menu->run_extended(\"\", \"\", ran, false);\n}\ndelete vec;\ndelete menu;\n}\nelse {\nlog(\"Learn game sounds: the vector returned was NULL!\\n\");\n}\n}\n\n<|endoftext|>"} {"text":"<commit_before>#ifndef CAMERA_H\n#define CAMERA_H\n\n#include <string>\n#include <opencv2\/opencv.hpp>\n#include <opencv2\/videoio.hpp>\n\n#pragma comment(lib,\"opencv_world320.lib\")\n\nstatic const int devid = 0;\n\nclass Camera\n{\nprivate:\n void operator=(const Camera&){};\n Camera(const Camera&){};\n int makeTimePath();\n cv::Mat rmNoize(cv::Mat src);\n cv::VideoCapture capture(int devid);\n std::string timePath;\n cv::Mat input;\/\/入力画像\n cv::Mat output;\/\/出力画像\npublic:\n Camera();\n ~Camera();\n int takePhoto();\n int binarize();\n double countArea();\n double getCenter();\n};\n\n#endif\n<commit_msg>dbeug<commit_after>#ifndef CAMERA_H\n#define CAMERA_H\n\n#include <string>\n#include <opencv2\/opencv.hpp>\n#include <opencv2\/videoio.hpp>\n\n#pragma comment(lib,\"opencv_world320.lib\")\n\nclass Camera\n{\nprivate:\n void operator=(const Camera&){};\n Camera(const Camera&){};\n int makeTimePath();\n cv::Mat rmNoize(cv::Mat src);\n cv::VideoCapture capture(0);\n std::string timePath;\n cv::Mat input;\/\/入力画像\n cv::Mat output;\/\/出力画像\npublic:\n Camera();\n ~Camera();\n int takePhoto();\n int binarize();\n double countArea();\n double getCenter();\n};\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n#include \"mnist.hpp\"\n#include \"timing.hpp\"\n#include \"network.hpp\"\n\nint main()\n{\n\t\/\/ RELU - tops at ~84%, eta = 0.05, batch_size = 30, 100 (seems to not matter much)\n\t\/\/ Sigmoid - tops at ~98%, eta = 2.0, 1.0, 0.5 (<0.96,<0.97,<1.0), batch_size = 10\n\t{\n\t\tusing namespace nn;\n\t\tnetwork net;\n\t\tconstexpr ActivationType type = ActivationType::kSigmoid;\n\n\t\tnet.addInputLayer<type>(28 * 28);\n\t\tnet.addRegularLayer<type, WeightInitializationType::kWeightedGaussian>(50);\n\t\tnet.addRegularLayer<type, WeightInitializationType::kWeightedGaussian>(10);\n\t\t\n\t\tstd::vector<MatrixType> training_set, validation_set;\n\t\tstd::vector<uint8_t> training_labels, validation_labels;\n\t\tconst size_t dataset_size = 60000;\n\t\t{\n\t\t\tconst auto images = loadMNISTImages(\"externals\/mnist\/train-images.idx3-ubyte\", dataset_size);\n\t\t\tconst auto labels = loadMNISTLabels(\"externals\/mnist\/train-labels.idx1-ubyte\", dataset_size);\n\t\t\ttraining_set = std::vector<MatrixType>(images.cbegin(), images.cbegin() + 50000);\n\t\t\tvalidation_set = std::vector<MatrixType>(images.cbegin() + 50000, images.cend());\n\t\t\ttraining_labels = std::vector<uint8_t>(labels.cbegin(), labels.cbegin() + 50000);\n\t\t\tvalidation_labels = std::vector<uint8_t>(labels.cbegin() + 50000, labels.cend());\n\t\t}\n\t\tconst size_t epochs = 30;\n\t\tconst size_t batch_size = 10;\n\t\treal eta = 2.0f;\n\t\t\/\/ SGD\n\t\ttiming timer;\n\t\tfor (size_t epoch = 0u; epoch < epochs; ++epoch)\n\t\t{\n\t\t\tconst size_t batches = training_set.size() \/ batch_size;\n\t\t\tMatrixType image_batch = MatrixType::Zero(28 * 28, batch_size);\n\t\t\tstd::vector<uint8_t> label_batch(batch_size);\n\t\t\tfor (size_t k = 0u; k < batches; k++)\n\t\t\t{\n\t\t\t\tconst size_t batch_start = k * batch_size;\n\t\t\t\tconst size_t batch_end = (k + 1) * batch_size;\n\n\t\t\t\tfor (size_t i = batch_start; i < batch_end; ++i)\n\t\t\t\t{\n\t\t\t\t\timage_batch.col(i - batch_start) = training_set[i];\n\t\t\t\t\tlabel_batch[i - batch_start] = training_labels[i];\n\t\t\t\t}\n\t\t\t\tnet.feedforward(image_batch);\n\t\t\t\tnet.backprop(label_batch);\n\t\t\t\tnet.update_weights(eta, batch_size);\n\t\t\t}\n\t\t\treal correct = net.evaluate(validation_set, validation_labels);\n\t\t\t\/\/ learning rate slow down at peak accuracy\n\t\t\tif (correct > 0.96) eta = 1.0f;\n\t\t\tif (correct > 0.97) eta = 0.5f;\n\t\t\tstd::cout << \"Epoch \" << epoch << \", acc: \" << correct * 100.0f << \"% (\" << timer.seconds() << \" seconds passed)\" << std::endl;\n\t\t}\n\t}\n\tint x;\n\tstd::cin >> x;\n\treturn 0;\n}<commit_msg>do not allocate memory inside the epoch loop<commit_after>#include <iostream>\n#include \"mnist.hpp\"\n#include \"timing.hpp\"\n#include \"network.hpp\"\n\nint main()\n{\n\t\/\/ RELU - tops at ~84%, eta = 0.05, batch_size = 30, 100 (seems to not matter much)\n\t\/\/ Sigmoid - tops at ~98%, eta = 2.0, 1.0, 0.5 (<0.96,<0.97,<1.0), batch_size = 10\n\t{\n\t\tusing namespace nn;\n\t\tnetwork net;\n\t\tconstexpr ActivationType type = ActivationType::kSigmoid;\n\n\t\tnet.addInputLayer<type>(28 * 28);\n\t\tnet.addRegularLayer<type, WeightInitializationType::kWeightedGaussian>(50);\n\t\tnet.addRegularLayer<type, WeightInitializationType::kWeightedGaussian>(10);\n\t\t\n\t\tstd::vector<MatrixType> training_set, validation_set;\n\t\tstd::vector<uint8_t> training_labels, validation_labels;\n\t\tconst size_t dataset_size = 60000;\n\t\t{\n\t\t\tconst auto images = loadMNISTImages(\"externals\/mnist\/train-images.idx3-ubyte\", dataset_size);\n\t\t\tconst auto labels = loadMNISTLabels(\"externals\/mnist\/train-labels.idx1-ubyte\", dataset_size);\n\t\t\ttraining_set = std::vector<MatrixType>(images.cbegin(), images.cbegin() + 50000);\n\t\t\tvalidation_set = std::vector<MatrixType>(images.cbegin() + 50000, images.cend());\n\t\t\ttraining_labels = std::vector<uint8_t>(labels.cbegin(), labels.cbegin() + 50000);\n\t\t\tvalidation_labels = std::vector<uint8_t>(labels.cbegin() + 50000, labels.cend());\n\t\t}\n\t\tconst size_t epochs = 30;\n\t\tconst size_t batch_size = 10;\n\t\treal eta = 2.0f;\n\t\t\/\/ SGD\n\t\ttiming timer;\n\t\tconst size_t batches = training_set.size() \/ batch_size;\n\t\tMatrixType image_batch = MatrixType::Zero(28 * 28, batch_size);\n\t\tstd::vector<uint8_t> label_batch(batch_size);\n\t\tfor (size_t epoch = 0u; epoch < epochs; ++epoch)\n\t\t{\n\t\t\tfor (size_t k = 0u; k < batches; k++)\n\t\t\t{\n\t\t\t\tconst size_t batch_start = k * batch_size;\n\t\t\t\tconst size_t batch_end = (k + 1) * batch_size;\n\n\t\t\t\tfor (size_t i = batch_start; i < batch_end; ++i)\n\t\t\t\t{\n\t\t\t\t\timage_batch.col(i - batch_start) = training_set[i];\n\t\t\t\t\tlabel_batch[i - batch_start] = training_labels[i];\n\t\t\t\t}\n\t\t\t\tnet.feedforward(image_batch);\n\t\t\t\tnet.backprop(label_batch);\n\t\t\t\tnet.update_weights(eta, batch_size);\n\t\t\t}\n\t\t\treal correct = net.evaluate(validation_set, validation_labels);\n\t\t\t\/\/ learning rate slow down at peak accuracy\n\t\t\tif (correct > 0.96) eta = 1.0f;\n\t\t\tif (correct > 0.97) eta = 0.5f;\n\t\t\tstd::cout << \"Epoch \" << epoch << \", acc: \" << correct * 100.0f << \"% (\" << timer.seconds() << \" seconds passed)\" << std::endl;\n\t\t}\n\t}\n\tint x;\n\tstd::cin >> x;\n\treturn 0;\n}<|endoftext|>"} {"text":"<commit_before>#include <opencv2\/objdetect.hpp>\n#include <opencv2\/highgui.hpp>\n#include <opencv2\/imgproc.hpp>\n#include <opencv2\/core\/utility.hpp>\n#include <opencv2\/imgcodecs.hpp>\n\n#include <opencv2\/videoio\/videoio_c.h>\n#include <opencv2\/highgui\/highgui_c.h>\n\n#include <cctype>\n#include <iostream>\n#include <fstream>\n#include <iterator>\n\n#include <stdio.h>\n#include \"svg_image.h\"\n\n\nusing namespace std;\n\/\/using namespace cv;\n\n\nconst char * help_string = \"\\\n## Swap faces from a picture with a set of faces from choice ##\nThis program assumes hardcoded paths: \\n\\\n- source -- must be current dir \\n\\\n - faceswap -- executable \\n\\\n - file-template.xml \\n\\\n - img-template.xml \\n\\\n - [source code] \\n\\\n- photo_result -- will cointain the svg's \\n\\\n - *.svg -- refers to images with relative paths \\n\\\n- haarcascades -- image recongnition data \\n\\\n - haarcascade_frontalface_alt.xml \\n\\\n - haarcascade_frontalface_alt2.xml \\n\\\n - haarcascade_frontalface_alt_tree.xml \\n\\\n - haarcascade_frontalface_default.xml \\n\\\n - ... \\n\\\n- photo_heads -- contains the photos's of heads you want to set_rect \\n\\\n - *.png \\n\\\n- photos -- for the sake of path's in the SVG file it's advised to place your pictures here \\n\\\n \\n\\\nThe outputted SVG is viewed best with a browser. \\n\\\n\";\n\nstd::vector<cv::Rect> detectAndDraw( cv::Mat& image, cv::CascadeClassifier& cascade,\n double scale, bool tryflip );\n\nconst char* cascadeNames[] = {\n \"..\/haarcascades\/haarcascade_frontalface_alt.xml\",\n \"..\/haarcascades\/haarcascade_frontalface_alt2.xml\",\n \"..\/haarcascades\/haarcascade_frontalface_alt_tree.xml\",\n \"..\/haarcascades\/haarcascade_frontalface_default.xml\"\n};\n\nstd::string file_original = \"..\/photos\/pic_example.jpg\";\nstd::string file_target_svg = \"..\/photo_result\/default_path.svg\";\n\n\nstd::string MakeTargetSvgPath(std::string original)\n{\n std::size_t pos = original.find_last_of(\"\/\"); \/\/ position of \"live\" in str\n auto str_tmp = original.substr (pos, original.length()-pos-3); \/\/ get from \"live\" to the end\n return std::string(\"..\/photo_result\") + str_tmp + \"svg\";\n}\n\n\nint main( int argc, const char** argv )\n{\n const string scaleOpt = \"--scale=\";\n size_t scaleOptLen = scaleOpt.length();\n\n const string photoOpt = \"--photo=\";\n size_t photoOptLen = photoOpt.length();\n\n const string cascadeOpt = \"--cascade=\";\n size_t cascadeOptLen = cascadeOpt.length();\n\n const string helpOpt = \"--help\";\n size_t helpOptLen = helpOpt.length();\n\n const string tryFlipOpt = \"--try-flip\";\n size_t tryFlipOptLen = tryFlipOpt.length();\n\n bool tryflip = false;\n double scale = 1;\n\n for( int i = 1; i < argc; i++ )\n {\n cout << \"Argument \" << i << \": \" << argv[i] << endl;\n if( cascadeOpt.compare( 0, cascadeOptLen, argv[i], cascadeOptLen ) == 0 )\n {\n cascadeNames[0] = argv[i];\n cout << \" from which we have cascade1Name= \" << cascadeNames[0] << endl;\n }\n else if( photoOpt.compare( 0, photoOptLen, argv[i], photoOptLen ) == 0 )\n {\n if( !sscanf( argv[i] + photoOpt.length(), \"%lf\", &scale ) || scale < 1 )\n file_original = string(argv[i]);\n cout << \" from which we read scale = \" << file_original << endl;\n }\n else if( scaleOpt.compare( 0, scaleOptLen, argv[i], scaleOptLen ) == 0 )\n {\n if( !sscanf( argv[i] + scaleOpt.length(), \"%lf\", &scale ) || scale < 1 )\n scale = 1;\n cout << \" from which we read scale = \" << scale << endl;\n }\n else if( tryFlipOpt.compare( 0, tryFlipOptLen, argv[i], tryFlipOptLen ) == 0 )\n {\n tryflip = true;\n cout << \" will try to flip image horizontally to detect assymetric objects\\n\";\n }\n else if( helpOpt.compare( 0, helpOptLen, argv[i], helpOptLen ) == 0 )\n {\n cout << help_string;\n cout << \"Using OpenCV version \" << CV_VERSION << \"\\n\" << endl;\n return 0;\n }\n else if( argv[i][0] == '-' )\n {\n cerr << \"WARNING: Unknown option \" << argv[i] << endl;\n }\n else\n file_original.assign( argv[i] );\n }\n\n file_target_svg = MakeTargetSvgPath(file_original);\n cout << \"Output ile: \" << file_target_svg << endl;\n \/\/ End of freacking input stuff \/\/\n\n\n vector<cv::CascadeClassifier> cascades;\n for( unsigned int i = 0; i<4; ++i){\n cascades.push_back(cv::CascadeClassifier());\n if( !cascades[i].load( cascadeNames[i] ) )\n {\n cerr << \"ERROR: Could not load cascade \" << cascadeNames[i] << endl;\n return -1;\n }\n }\n\n\n\n\n cv::Mat image = cv::imread(file_original); \/\/ Read the file\n if(!image.data )\n {\n cout << \"Could not open or find the image\" << std::endl ;\n return -1;\n }\n\n std::vector<cv::Rect> faces_all, faces;\n\n faces = detectAndDraw( image, cascades[1], scale, tryflip );\n faces_all.insert(faces_all.end(), faces.begin(), faces.end());\n\n \/\/faces = detectAndDraw( image, cascade, scale, tryflip );\n \/\/faces_all.insert(faces_all.end(), faces.begin(), faces.end());\n\n\n\n std::stringstream ss(\"\", ios_base::app | ios_base::out);\n\n for(auto r : faces_all)\n {\n \/\/ messy object, I know, I know\n auto svgimage = svg_image();\n svgimage.refresh();\n svgimage.set_rect(r);\n ss << svgimage.get_resulting_svg();\n }\n\n\n auto file_content = file_to_string(\"file-template.xml\");\n replace_var(file_content, \"$original_picture_here\", file_original);\n replace_var(file_content, \"$img_attributes_here\", ss.str());\n replace_var(file_content, \"$image_width\", std::to_string(image.cols));\n replace_var(file_content, \"$image_height\", std::to_string(image.rows));\n\n ofstream myfile;\n myfile.open (file_target_svg, ios::out);\n myfile << file_content;\n myfile.close();\n\n\n return 0;\n}\n\n\nstd::vector<cv::Rect> detectAndDraw( cv::Mat& image, cv::CascadeClassifier& cascade,\n double scale, bool tryflip)\n{\n cv::Mat imgCopy( cvRound(image.rows\/scale), cvRound(image.cols\/scale), CV_8UC1 );\n \/\/cv::Mat imgCopy( 732*0.8, 1100*0.8, CV_8UC1 );\n \/\/Size( std::min (image.rows, 100), std::min(image.cols, 100) )\n cv::Mat imgGray;\n cv::cvtColor( image, imgGray, cv::COLOR_BGR2GRAY );\n cv::resize( imgGray, imgCopy, imgCopy.size() , 0, 0, cv::INTER_LINEAR );\n cv::equalizeHist( imgCopy, imgCopy );\n\n vector<cv::Rect> faces;\n cascade.detectMultiScale( imgCopy, faces,\n 1.1, 2, 0\n \/\/|cv::CASCADE_FIND_BIGGEST_OBJECT\n \/\/|cv::CASCADE_DO_ROUGH_SEARCH\n |cv::CASCADE_SCALE_IMAGE\n ,\n cv::Size(11, 11) );\n if( tryflip )\n {\n vector<cv::Rect> faces_fliped;\n cv::flip(imgCopy, imgCopy, 1);\n cascade.detectMultiScale( imgCopy, faces_fliped,\n 1.1, 2, 0\n \/\/|cv::CASCADE_FIND_BIGGEST_OBJECT\n \/\/|cv::CASCADE_DO_ROUGH_SEARCH\n |cv::CASCADE_SCALE_IMAGE\n ,\n cv::Size(17, 17) );\n\n faces.insert(faces.end(), faces_fliped.begin(), faces_fliped.end());\n }\n\n cout << \"Number of faces: \" << faces.size() << endl;\n\n\n return faces;\n}\n<commit_msg>fixed help_string<commit_after>#include <opencv2\/objdetect.hpp>\n#include <opencv2\/highgui.hpp>\n#include <opencv2\/imgproc.hpp>\n#include <opencv2\/core\/utility.hpp>\n#include <opencv2\/imgcodecs.hpp>\n\n#include <opencv2\/videoio\/videoio_c.h>\n#include <opencv2\/highgui\/highgui_c.h>\n\n#include <cctype>\n#include <iostream>\n#include <fstream>\n#include <iterator>\n\n#include <stdio.h>\n#include \"svg_image.h\"\n\n\nusing namespace std;\n\/\/using namespace cv;\n\n\nconst char * help_string = \"\\\n## Swap faces from a picture with a set of faces from choice ## \\n\\\nThis program assumes hardcoded paths: \\n\\\n- source -- must be current dir \\n\\\n - faceswap -- executable \\n\\\n - file-template.xml \\n\\\n - img-template.xml \\n\\\n - [source code] \\n\\\n- photo_result -- will cointain the svg's \\n\\\n - *.svg -- refers to images with relative paths \\n\\\n- haarcascades -- image recongnition data \\n\\\n - haarcascade_frontalface_alt.xml \\n\\\n - haarcascade_frontalface_alt2.xml \\n\\\n - haarcascade_frontalface_alt_tree.xml \\n\\\n - haarcascade_frontalface_default.xml \\n\\\n - ... \\n\\\n- photo_heads -- contains the photos's of heads you want to set_rect \\n\\\n - *.png \\n\\\n- photos -- for the sake of path's in the SVG file it's advised to place your pictures here \\n\\\n \\n\\\nThe outputted SVG is viewed best with a browser. \\n\\\n\";\n\nstd::vector<cv::Rect> detectAndDraw( cv::Mat& image, cv::CascadeClassifier& cascade,\n double scale, bool tryflip );\n\nconst char* cascadeNames[] = {\n \"..\/haarcascades\/haarcascade_frontalface_alt.xml\",\n \"..\/haarcascades\/haarcascade_frontalface_alt2.xml\",\n \"..\/haarcascades\/haarcascade_frontalface_alt_tree.xml\",\n \"..\/haarcascades\/haarcascade_frontalface_default.xml\"\n};\n\nstd::string file_original = \"..\/photos\/pic_example.jpg\";\nstd::string file_target_svg = \"..\/photo_result\/default_path.svg\";\n\n\nstd::string MakeTargetSvgPath(std::string original)\n{\n std::size_t pos = original.find_last_of(\"\/\"); \/\/ position of \"live\" in str\n auto str_tmp = original.substr (pos, original.length()-pos-3); \/\/ get from \"live\" to the end\n return std::string(\"..\/photo_result\") + str_tmp + \"svg\";\n}\n\n\nint main( int argc, const char** argv )\n{\n const string scaleOpt = \"--scale=\";\n size_t scaleOptLen = scaleOpt.length();\n\n const string photoOpt = \"--photo=\";\n size_t photoOptLen = photoOpt.length();\n\n const string cascadeOpt = \"--cascade=\";\n size_t cascadeOptLen = cascadeOpt.length();\n\n const string helpOpt = \"--help\";\n size_t helpOptLen = helpOpt.length();\n\n const string tryFlipOpt = \"--try-flip\";\n size_t tryFlipOptLen = tryFlipOpt.length();\n\n bool tryflip = false;\n double scale = 1;\n\n for( int i = 1; i < argc; i++ )\n {\n cout << \"Argument \" << i << \": \" << argv[i] << endl;\n if( cascadeOpt.compare( 0, cascadeOptLen, argv[i], cascadeOptLen ) == 0 )\n {\n cascadeNames[0] = argv[i];\n cout << \" from which we have cascade1Name= \" << cascadeNames[0] << endl;\n }\n else if( photoOpt.compare( 0, photoOptLen, argv[i], photoOptLen ) == 0 )\n {\n if( !sscanf( argv[i] + photoOpt.length(), \"%lf\", &scale ) || scale < 1 )\n file_original = string(argv[i]);\n cout << \" from which we read scale = \" << file_original << endl;\n }\n else if( scaleOpt.compare( 0, scaleOptLen, argv[i], scaleOptLen ) == 0 )\n {\n if( !sscanf( argv[i] + scaleOpt.length(), \"%lf\", &scale ) || scale < 1 )\n scale = 1;\n cout << \" from which we read scale = \" << scale << endl;\n }\n else if( tryFlipOpt.compare( 0, tryFlipOptLen, argv[i], tryFlipOptLen ) == 0 )\n {\n tryflip = true;\n cout << \" will try to flip image horizontally to detect assymetric objects\\n\";\n }\n else if( helpOpt.compare( 0, helpOptLen, argv[i], helpOptLen ) == 0 )\n {\n cout << help_string;\n cout << \"Using OpenCV version \" << CV_VERSION << \"\\n\" << endl;\n return 0;\n }\n else if( argv[i][0] == '-' )\n {\n cerr << \"WARNING: Unknown option \" << argv[i] << endl;\n }\n else\n file_original.assign( argv[i] );\n }\n\n file_target_svg = MakeTargetSvgPath(file_original);\n cout << \"Output ile: \" << file_target_svg << endl;\n \/\/ End of freacking input stuff \/\/\n\n\n vector<cv::CascadeClassifier> cascades;\n for( unsigned int i = 0; i<4; ++i){\n cascades.push_back(cv::CascadeClassifier());\n if( !cascades[i].load( cascadeNames[i] ) )\n {\n cerr << \"ERROR: Could not load cascade \" << cascadeNames[i] << endl;\n return -1;\n }\n }\n\n\n\n\n cv::Mat image = cv::imread(file_original); \/\/ Read the file\n if(!image.data )\n {\n cout << \"Could not open or find the image\" << std::endl ;\n return -1;\n }\n\n std::vector<cv::Rect> faces_all, faces;\n\n faces = detectAndDraw( image, cascades[1], scale, tryflip );\n faces_all.insert(faces_all.end(), faces.begin(), faces.end());\n\n \/\/faces = detectAndDraw( image, cascade, scale, tryflip );\n \/\/faces_all.insert(faces_all.end(), faces.begin(), faces.end());\n\n\n\n std::stringstream ss(\"\", ios_base::app | ios_base::out);\n\n for(auto r : faces_all)\n {\n \/\/ messy object, I know, I know\n auto svgimage = svg_image();\n svgimage.refresh();\n svgimage.set_rect(r);\n ss << svgimage.get_resulting_svg();\n }\n\n\n auto file_content = file_to_string(\"file-template.xml\");\n replace_var(file_content, \"$original_picture_here\", file_original);\n replace_var(file_content, \"$img_attributes_here\", ss.str());\n replace_var(file_content, \"$image_width\", std::to_string(image.cols));\n replace_var(file_content, \"$image_height\", std::to_string(image.rows));\n\n ofstream myfile;\n myfile.open (file_target_svg, ios::out);\n myfile << file_content;\n myfile.close();\n\n\n return 0;\n}\n\n\nstd::vector<cv::Rect> detectAndDraw( cv::Mat& image, cv::CascadeClassifier& cascade,\n double scale, bool tryflip)\n{\n cv::Mat imgCopy( cvRound(image.rows\/scale), cvRound(image.cols\/scale), CV_8UC1 );\n \/\/cv::Mat imgCopy( 732*0.8, 1100*0.8, CV_8UC1 );\n \/\/Size( std::min (image.rows, 100), std::min(image.cols, 100) )\n cv::Mat imgGray;\n cv::cvtColor( image, imgGray, cv::COLOR_BGR2GRAY );\n cv::resize( imgGray, imgCopy, imgCopy.size() , 0, 0, cv::INTER_LINEAR );\n cv::equalizeHist( imgCopy, imgCopy );\n\n vector<cv::Rect> faces;\n cascade.detectMultiScale( imgCopy, faces,\n 1.1, 2, 0\n \/\/|cv::CASCADE_FIND_BIGGEST_OBJECT\n \/\/|cv::CASCADE_DO_ROUGH_SEARCH\n |cv::CASCADE_SCALE_IMAGE\n ,\n cv::Size(11, 11) );\n if( tryflip )\n {\n vector<cv::Rect> faces_fliped;\n cv::flip(imgCopy, imgCopy, 1);\n cascade.detectMultiScale( imgCopy, faces_fliped,\n 1.1, 2, 0\n \/\/|cv::CASCADE_FIND_BIGGEST_OBJECT\n \/\/|cv::CASCADE_DO_ROUGH_SEARCH\n |cv::CASCADE_SCALE_IMAGE\n ,\n cv::Size(17, 17) );\n\n faces.insert(faces.end(), faces_fliped.begin(), faces_fliped.end());\n }\n\n cout << \"Number of faces: \" << faces.size() << endl;\n\n\n return faces;\n}\n<|endoftext|>"} {"text":"<commit_before>\/* mbed Microcontroller Library\n * Copyright (c) 2006-2013 ARM Limited\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"mbed-drivers\/mbed.h\"\n#include \"ble\/BLE.h\"\n#include \"EddystoneService.h\"\n\n#include \"PersistentStorageHelper\/ConfigParamsPersistence.h\"\n\/\/ #include \"stdio.h\"\n\n\/\/ Instantiation of the main event loop for this program\n\n#ifdef YOTTA_CFG_MBED_OS \/\/ use minar on mbed OS\n#include \"EventQueue\/EventQueueMinar.h\"\ntypedef eq::EventQueueMinar event_queue_t;\n\n#else \/\/ otherwise use the event classic queue\n#include \"EventQueue\/EventQueueClassic.h\"\ntypedef eq::EventQueueClassic<\n \/* event count *\/ 10\n> event_queue_t;\n\n#endif\n\nstatic event_queue_t eventQueue;\n\nEddystoneService *eddyServicePtr;\n\n\/* Duration after power-on that config service is available. *\/\nstatic const int CONFIG_ADVERTISEMENT_TIMEOUT_SECONDS = YOTTA_CFG_EDDYSTONE_DEFAULT_CONFIG_ADVERTISEMENT_TIMEOUT_SECONDS;\n\n\/* Values for ADV packets related to firmware levels, calibrated based on measured values at 1m *\/\nstatic const PowerLevels_t advTxPowerLevels = YOTTA_CFG_EDDYSTONE_DEFAULT_ADV_TX_POWER_LEVELS;\n\/* Values for radio power levels, provided by manufacturer. *\/\nstatic const PowerLevels_t radioTxPowerLevels = YOTTA_CFG_EDDYSTONE_DEFAULT_RADIO_TX_POWER_LEVELS;\n\n\/\/ This allows a quick switch between targets without changing the 'platform'\n\/\/ settings in config.json each time. If you do change target to nrf51dk-gcc,\n\/\/ note you will still need to change 'softdevice' to 's130'\n\/\/\n #define QUICK_SWITCH_TO_NRF51DK 1\n#ifdef QUICK_SWITCH_TO_NRF51DK\n #define LED_OFF 1\n #define CONFIG_LED LED3\n #define SHUTDOWN_LED LED1\n #define RESET_BUTTON BUTTON1\n#else\n #define LED_OFF YOTTA_CFG_PLATFORM_LED_OFF\n #define CONFIG_LED YOTTA_CFG_PLATFORM_CONFIG_LED\n #define SHUTDOWN_LED YOTTA_CFG_PLATFORM_SHUTDOWN_LED\n #define RESET_BUTTON YOTTA_CFG_PLATFORM_RESET_BUTTON\n#endif\n\n\nDigitalOut configLED(CONFIG_LED, LED_OFF);\nDigitalOut shutdownLED(SHUTDOWN_LED, LED_OFF);\nInterruptIn button(RESET_BUTTON);\n\nstatic int buttonBusy; \/\/ semaphore to make prevent switch bounce problems\n\nstatic const int BLINKY_MSEC = 500; \/\/ How long to cycle config LED on\/off\nstatic int beaconIsOn = 1; \/\/ Button handler boolean to switch on or off\nstatic event_queue_t::event_handle_t handle = 0; \/\/ For the config mode timeout\nstatic event_queue_t::event_handle_t BlinkyHandle = 0; \/\/ For the blinking LED when in config mode\n\nstatic void blinky(void) { configLED = !configLED; }\nstatic void shutdownLED_on(void) { shutdownLED = !LED_OFF; }\nstatic void shutdownLED_off(void) { shutdownLED = LED_OFF; }\nstatic void freeButtonBusy(void) { buttonBusy = false; }\n\nstatic void configLED_on(void) {\n configLED = !LED_OFF;\n BlinkyHandle = eventQueue.post_every(blinky, BLINKY_MSEC);\n}\nstatic void configLED_off(void) {\n configLED = LED_OFF;\n if (BlinkyHandle) {\n eventQueue.cancel(BlinkyHandle);\n BlinkyHandle = NULL;\n }\n}\n\n\/**\n * Callback triggered some time after application started to switch to beacon mode.\n *\/\nstatic void timeoutToStartEddystoneBeaconAdvertisements(void)\n{\n Gap::GapState_t state;\n state = BLE::Instance().gap().getState();\n if (!state.connected) { \/* don't switch if we're in a connected state. *\/\n eddyServicePtr->startEddystoneBeaconAdvertisements();\n configLED_off();\n }\n}\n\n\/**\n * Callback triggered for a connection event.\n *\/\nstatic void connectionCallback(const Gap::ConnectionCallbackParams_t *cbParams)\n{\n (void) cbParams;\n \/\/ Stop advertising whatever the current mode\n eddyServicePtr->stopEddystoneBeaconAdvertisements();\n}\n\n\/**\n * Callback triggered for a disconnection event.\n *\/\nstatic void disconnectionCallback(const Gap::DisconnectionCallbackParams_t *cbParams)\n{\n (void) cbParams;\n BLE::Instance().gap().startAdvertising();\n \/\/ Save params in persistent storage\n EddystoneService::EddystoneParams_t params;\n eddyServicePtr->getEddystoneParams(params);\n saveEddystoneServiceConfigParams(¶ms);\n \/\/ Ensure LED is off at the end of Config Mode or during a connection\n configLED_off();\n \/\/ 0.5 Second callback to rapidly re-establish Beaconing Service\n \/\/ (because it needs to be executed outside of disconnect callback)\n eventQueue.post_in(timeoutToStartEddystoneBeaconAdvertisements, 500 \/* ms *\/);\n}\n\n\n\/\/ Callback used to handle button presses from thread mode (not IRQ)\nstatic void button_task(void) {\n eventQueue.cancel(handle); \/\/ kill any pending callback tasks\n\n if (beaconIsOn) {\n beaconIsOn = 0;\n eddyServicePtr->stopEddystoneBeaconAdvertisements();\n configLED_off(); \/\/ just in case it's still running...\n shutdownLED_on(); \/\/ Flash shutdownLED to let user know we're turning off\n eventQueue.post_in(shutdownLED_off, 1000);\n } else {\n\n beaconIsOn = 1;\n eddyServicePtr->startEddystoneConfigAdvertisements();\n configLED_on();\n handle = eventQueue.post_in(\n timeoutToStartEddystoneBeaconAdvertisements,\n CONFIG_ADVERTISEMENT_TIMEOUT_SECONDS * 1000 \/* ms *\/\n );\n }\n eventQueue.post_in(freeButtonBusy, 750 \/* ms *\/);\n}\n\n\/**\n * Raw IRQ handler for the reset button. We don't want to actually do any work here.\n * Instead, we queue work to happen later using an event queue, by posting a callback.\n * This has the added avantage of serialising actions, so if the button press happens\n * during the config->beacon mode transition timeout, the button_task won't happen\n * until the previous task has finished.\n *\n * If your buttons aren't debounced, you should do this in software, or button_task\n * might get queued multiple times.\n *\/\nstatic void reset_rise(void)\n{\n if (!buttonBusy) {\n buttonBusy = true;\n eventQueue.post(button_task);\n }\n}\n\nstatic void onBleInitError(BLE::InitializationCompleteCallbackContext* initContext)\n{\n \/* Initialization error handling goes here... *\/\n (void) initContext;\n}\n\n\nstatic void bleInitComplete(BLE::InitializationCompleteCallbackContext* initContext)\n{\n BLE &ble = initContext->ble;\n ble_error_t error = initContext->error;\n\n if (error != BLE_ERROR_NONE) {\n onBleInitError(initContext);\n return;\n }\n\n ble.gap().onDisconnection(disconnectionCallback);\n\n ble.gap().onConnection(connectionCallback);\n\n EddystoneService::EddystoneParams_t params;\n\n \/\/ Determine if booting directly after re-Flash or not\n if (loadEddystoneServiceConfigParams(¶ms)) {\n \/\/ 2+ Boot after reflash, so get parms from Persistent Storage\n eddyServicePtr = new EddystoneService(ble, params, radioTxPowerLevels, eventQueue);\n } else {\n \/\/ 1st Boot after reflash, so reset everything to defaults\n \/* NOTE: slots are initialized in the constructor from the config.json file *\/\n eddyServicePtr = new EddystoneService(ble, advTxPowerLevels, radioTxPowerLevels, eventQueue);\n }\n\n \/\/ Save Default params in persistent storage ready for next boot event\n eddyServicePtr->getEddystoneParams(params);\n saveEddystoneServiceConfigParams(¶ms);\n\n \/\/ Start the Eddystone Config service - This will never stop (only connectability will change)\n eddyServicePtr->startEddystoneConfigService();\n\n \/* Start Eddystone config Advertizements (to initialize everything properly) *\/\n configLED_on();\n eddyServicePtr->startEddystoneConfigAdvertisements();\n handle = eventQueue.post_in(\n timeoutToStartEddystoneBeaconAdvertisements,\n CONFIG_ADVERTISEMENT_TIMEOUT_SECONDS * 1000 \/* ms *\/\n );\n\n \/\/ now shut everything off (used for final beacon that ships w\/ battery)\n eventQueue.post_in(button_task, 2000 \/* ms *\/);\n}\n\nvoid app_start(int, char *[])\n{\n \/* Tell standard C library to not allocate large buffers for these streams *\/\n setbuf(stdout, NULL);\n setbuf(stderr, NULL);\n setbuf(stdin, NULL);\n\n beaconIsOn = 1; \/\/ Booting up, initialize for button handler\n buttonBusy = false; \/\/ software debouncing of the reset button\n button.rise(&reset_rise); \/\/ setup reset button\n\n BLE &ble = BLE::Instance();\n ble.init(bleInitComplete);\n}\n\n#if !defined(YOTTA_CFG_MBED_OS)\n\nint main() {\n\n app_start(0, NULL);\n\n while (true) {\n eventQueue.dispatch();\n ble.waitForEvent();\n }\n\n return 0;\n}\n\n#endif\n<commit_msg>Fix reference to BLE instance.<commit_after>\/* mbed Microcontroller Library\n * Copyright (c) 2006-2013 ARM Limited\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"mbed-drivers\/mbed.h\"\n#include \"ble\/BLE.h\"\n#include \"EddystoneService.h\"\n\n#include \"PersistentStorageHelper\/ConfigParamsPersistence.h\"\n\/\/ #include \"stdio.h\"\n\n\/\/ Instantiation of the main event loop for this program\n\n#ifdef YOTTA_CFG_MBED_OS \/\/ use minar on mbed OS\n#include \"EventQueue\/EventQueueMinar.h\"\ntypedef eq::EventQueueMinar event_queue_t;\n\n#else \/\/ otherwise use the event classic queue\n#include \"EventQueue\/EventQueueClassic.h\"\ntypedef eq::EventQueueClassic<\n \/* event count *\/ 10\n> event_queue_t;\n\n#endif\n\nstatic event_queue_t eventQueue;\n\nEddystoneService *eddyServicePtr;\n\n\/* Duration after power-on that config service is available. *\/\nstatic const int CONFIG_ADVERTISEMENT_TIMEOUT_SECONDS = YOTTA_CFG_EDDYSTONE_DEFAULT_CONFIG_ADVERTISEMENT_TIMEOUT_SECONDS;\n\n\/* Values for ADV packets related to firmware levels, calibrated based on measured values at 1m *\/\nstatic const PowerLevels_t advTxPowerLevels = YOTTA_CFG_EDDYSTONE_DEFAULT_ADV_TX_POWER_LEVELS;\n\/* Values for radio power levels, provided by manufacturer. *\/\nstatic const PowerLevels_t radioTxPowerLevels = YOTTA_CFG_EDDYSTONE_DEFAULT_RADIO_TX_POWER_LEVELS;\n\n\/\/ This allows a quick switch between targets without changing the 'platform'\n\/\/ settings in config.json each time. If you do change target to nrf51dk-gcc,\n\/\/ note you will still need to change 'softdevice' to 's130'\n\/\/\n #define QUICK_SWITCH_TO_NRF51DK 1\n#ifdef QUICK_SWITCH_TO_NRF51DK\n #define LED_OFF 1\n #define CONFIG_LED LED3\n #define SHUTDOWN_LED LED1\n #define RESET_BUTTON BUTTON1\n#else\n #define LED_OFF YOTTA_CFG_PLATFORM_LED_OFF\n #define CONFIG_LED YOTTA_CFG_PLATFORM_CONFIG_LED\n #define SHUTDOWN_LED YOTTA_CFG_PLATFORM_SHUTDOWN_LED\n #define RESET_BUTTON YOTTA_CFG_PLATFORM_RESET_BUTTON\n#endif\n\n\nDigitalOut configLED(CONFIG_LED, LED_OFF);\nDigitalOut shutdownLED(SHUTDOWN_LED, LED_OFF);\nInterruptIn button(RESET_BUTTON);\n\nstatic int buttonBusy; \/\/ semaphore to make prevent switch bounce problems\n\nstatic const int BLINKY_MSEC = 500; \/\/ How long to cycle config LED on\/off\nstatic int beaconIsOn = 1; \/\/ Button handler boolean to switch on or off\nstatic event_queue_t::event_handle_t handle = 0; \/\/ For the config mode timeout\nstatic event_queue_t::event_handle_t BlinkyHandle = 0; \/\/ For the blinking LED when in config mode\n\nstatic void blinky(void) { configLED = !configLED; }\nstatic void shutdownLED_on(void) { shutdownLED = !LED_OFF; }\nstatic void shutdownLED_off(void) { shutdownLED = LED_OFF; }\nstatic void freeButtonBusy(void) { buttonBusy = false; }\n\nstatic void configLED_on(void) {\n configLED = !LED_OFF;\n BlinkyHandle = eventQueue.post_every(blinky, BLINKY_MSEC);\n}\nstatic void configLED_off(void) {\n configLED = LED_OFF;\n if (BlinkyHandle) {\n eventQueue.cancel(BlinkyHandle);\n BlinkyHandle = NULL;\n }\n}\n\n\/**\n * Callback triggered some time after application started to switch to beacon mode.\n *\/\nstatic void timeoutToStartEddystoneBeaconAdvertisements(void)\n{\n Gap::GapState_t state;\n state = BLE::Instance().gap().getState();\n if (!state.connected) { \/* don't switch if we're in a connected state. *\/\n eddyServicePtr->startEddystoneBeaconAdvertisements();\n configLED_off();\n }\n}\n\n\/**\n * Callback triggered for a connection event.\n *\/\nstatic void connectionCallback(const Gap::ConnectionCallbackParams_t *cbParams)\n{\n (void) cbParams;\n \/\/ Stop advertising whatever the current mode\n eddyServicePtr->stopEddystoneBeaconAdvertisements();\n}\n\n\/**\n * Callback triggered for a disconnection event.\n *\/\nstatic void disconnectionCallback(const Gap::DisconnectionCallbackParams_t *cbParams)\n{\n (void) cbParams;\n BLE::Instance().gap().startAdvertising();\n \/\/ Save params in persistent storage\n EddystoneService::EddystoneParams_t params;\n eddyServicePtr->getEddystoneParams(params);\n saveEddystoneServiceConfigParams(¶ms);\n \/\/ Ensure LED is off at the end of Config Mode or during a connection\n configLED_off();\n \/\/ 0.5 Second callback to rapidly re-establish Beaconing Service\n \/\/ (because it needs to be executed outside of disconnect callback)\n eventQueue.post_in(timeoutToStartEddystoneBeaconAdvertisements, 500 \/* ms *\/);\n}\n\n\n\/\/ Callback used to handle button presses from thread mode (not IRQ)\nstatic void button_task(void) {\n eventQueue.cancel(handle); \/\/ kill any pending callback tasks\n\n if (beaconIsOn) {\n beaconIsOn = 0;\n eddyServicePtr->stopEddystoneBeaconAdvertisements();\n configLED_off(); \/\/ just in case it's still running...\n shutdownLED_on(); \/\/ Flash shutdownLED to let user know we're turning off\n eventQueue.post_in(shutdownLED_off, 1000);\n } else {\n\n beaconIsOn = 1;\n eddyServicePtr->startEddystoneConfigAdvertisements();\n configLED_on();\n handle = eventQueue.post_in(\n timeoutToStartEddystoneBeaconAdvertisements,\n CONFIG_ADVERTISEMENT_TIMEOUT_SECONDS * 1000 \/* ms *\/\n );\n }\n eventQueue.post_in(freeButtonBusy, 750 \/* ms *\/);\n}\n\n\/**\n * Raw IRQ handler for the reset button. We don't want to actually do any work here.\n * Instead, we queue work to happen later using an event queue, by posting a callback.\n * This has the added avantage of serialising actions, so if the button press happens\n * during the config->beacon mode transition timeout, the button_task won't happen\n * until the previous task has finished.\n *\n * If your buttons aren't debounced, you should do this in software, or button_task\n * might get queued multiple times.\n *\/\nstatic void reset_rise(void)\n{\n if (!buttonBusy) {\n buttonBusy = true;\n eventQueue.post(button_task);\n }\n}\n\nstatic void onBleInitError(BLE::InitializationCompleteCallbackContext* initContext)\n{\n \/* Initialization error handling goes here... *\/\n (void) initContext;\n}\n\n\nstatic void bleInitComplete(BLE::InitializationCompleteCallbackContext* initContext)\n{\n BLE &ble = initContext->ble;\n ble_error_t error = initContext->error;\n\n if (error != BLE_ERROR_NONE) {\n onBleInitError(initContext);\n return;\n }\n\n ble.gap().onDisconnection(disconnectionCallback);\n\n ble.gap().onConnection(connectionCallback);\n\n EddystoneService::EddystoneParams_t params;\n\n \/\/ Determine if booting directly after re-Flash or not\n if (loadEddystoneServiceConfigParams(¶ms)) {\n \/\/ 2+ Boot after reflash, so get parms from Persistent Storage\n eddyServicePtr = new EddystoneService(ble, params, radioTxPowerLevels, eventQueue);\n } else {\n \/\/ 1st Boot after reflash, so reset everything to defaults\n \/* NOTE: slots are initialized in the constructor from the config.json file *\/\n eddyServicePtr = new EddystoneService(ble, advTxPowerLevels, radioTxPowerLevels, eventQueue);\n }\n\n \/\/ Save Default params in persistent storage ready for next boot event\n eddyServicePtr->getEddystoneParams(params);\n saveEddystoneServiceConfigParams(¶ms);\n\n \/\/ Start the Eddystone Config service - This will never stop (only connectability will change)\n eddyServicePtr->startEddystoneConfigService();\n\n \/* Start Eddystone config Advertizements (to initialize everything properly) *\/\n configLED_on();\n eddyServicePtr->startEddystoneConfigAdvertisements();\n handle = eventQueue.post_in(\n timeoutToStartEddystoneBeaconAdvertisements,\n CONFIG_ADVERTISEMENT_TIMEOUT_SECONDS * 1000 \/* ms *\/\n );\n\n \/\/ now shut everything off (used for final beacon that ships w\/ battery)\n eventQueue.post_in(button_task, 2000 \/* ms *\/);\n}\n\nvoid app_start(int, char *[])\n{\n \/* Tell standard C library to not allocate large buffers for these streams *\/\n setbuf(stdout, NULL);\n setbuf(stderr, NULL);\n setbuf(stdin, NULL);\n\n beaconIsOn = 1; \/\/ Booting up, initialize for button handler\n buttonBusy = false; \/\/ software debouncing of the reset button\n button.rise(&reset_rise); \/\/ setup reset button\n\n BLE &ble = BLE::Instance();\n ble.init(bleInitComplete);\n}\n\n#if !defined(YOTTA_CFG_MBED_OS)\n\nint main() {\n\n app_start(0, NULL);\n\n while (true) {\n eventQueue.dispatch();\n BLE::Instance().waitForEvent();\n }\n\n return 0;\n}\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/\/ See unity.cpp for build instructions\n\n#include <cstdio>\n#include <cstdlib>\n#include <cstring>\n\n#include \"env.hpp\"\n#include \"gl.hpp\"\n\nnamespace qm {\nstruct Shader {\n\tGLuint vs;\n\tGLuint fs;\n\tGLuint prog;\n\tGLuint phaseLoc;\n\tGLuint colorLoc;\n};\n\nconst GLchar* g_vs= \"\\\n#version 120\\n\\\nvarying vec3 v_pos; \\\nvarying vec3 v_normal; \\\nvoid main() \\\n{ \\\n gl_Position= vec4(gl_Vertex.xy, 0.0, 1.0); \\\n\tv_pos= (gl_ModelViewMatrix*gl_Vertex).xyz; \\\n\tv_normal= mat3(gl_ModelViewMatrix)*vec3(gl_Vertex.xy, -1.0); \\\n} \\\n\\n\";\n\nconst GLchar* g_fs= \"\\\n#version 120\\n\\\nuniform float u_phase; \\\nuniform vec3 u_color; \\\nvarying vec3 v_pos; \\\nvarying vec3 v_normal; \\\n\/* x emission, y absorption *\/ \\\nvec2 sample(vec3 p) \\\n{ \\\n\tp.z += 0.2; \\\n\tfloat beam_e= \\\n\t\tabs(cos(p.z*10.0 - sign(p.z)*u_phase)*0.5 + 1.0)* \\\n\t\t\t0.001\/(p.x*p.x + p.y*p.y + 0.001); \\\n\tfloat disc_e= \\\n\t\t0.01\/((p.z*p.z + 0.01)*(p.x*p.x + p.y*p.y)*100.0 + 0.1); \\\n\tfloat hole_a= pow(min(1.0, 0.1\/(dot(p, p))), 10.0); \\\n\tfloat a= clamp(hole_a, 0.0, 1.0); \\\n return vec2((disc_e + beam_e)*(1 - a), a + disc_e*7.0)*25.0; \\\n} \\\nvoid main() \\\n{ \\\n\tvec3 n= normalize(v_normal); \\\n\tvec3 color= u_color; \\\n\tfloat intensity= 0.0; \\\n\tconst int steps= 45; \\\n\tconst float dl= 2.0\/steps; \\\n\tfor (int i= 0; i < steps; ++i) { \\\n\t\tvec2 s= sample(v_pos + n*2.0*float(steps - i - 1)\/steps); \\\n\t\tintensity= max(0, intensity + (s.x - s.y*intensity)*dl); \\\n\t} \\\n\tgl_FragColor= vec4(color*intensity, 1.0); \\\n} \\\n\\n\";\n\nvoid init(Env& env, Shader& shd)\n{\n\tenv= envInit();\n\tqueryGlFuncs();\n\n\t{ \/\/ Create shaders\n\t\t{ \/\/ Vertex\n\t\t\tshd.vs= glCreateShader(GL_VERTEX_SHADER);\n\t\t\tglShaderSource(shd.vs, 1, &g_vs, NULL);\n\t\t\tglCompileShader(shd.vs);\n\t\t\tcheckShaderStatus(shd.vs);\n\t\t}\n\t\t{ \/\/ Fragment\n\t\t\tshd.fs= glCreateShader(GL_FRAGMENT_SHADER);\n\t\t\tglShaderSource(shd.fs, 1, &g_fs, NULL);\n\t\t\tglCompileShader(shd.fs);\n\t\t\tcheckShaderStatus(shd.fs);\n\t\t}\n\t\t{ \/\/ Shader program\n\t\t\tshd.prog= glCreateProgram();\n\t\t\tglAttachShader(shd.prog, shd.vs);\n\t\t\tglAttachShader(shd.prog, shd.fs);\n\t\t\tglLinkProgram(shd.prog);\n\t\t\tcheckProgramStatus(shd.prog);\n\n\t\t\tshd.phaseLoc= glGetUniformLocation(shd.prog, \"u_phase\");\n\t\t\tshd.colorLoc= glGetUniformLocation(shd.prog, \"u_color\");\n\t\t}\n\t}\n\n\t{ \/\/ Setup initial GL state\n\t\tglClearColor(0.0, 0.0, 0.0, 0.0);\n\t\tglEnable(GL_BLEND);\n\t\tglBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);\n\t}\n}\n\nvoid quit(Env& env, const Shader& shd)\n{\n\tglDetachShader(shd.prog, shd.vs);\n\tglDeleteShader(shd.vs);\n\n\tglDetachShader(shd.prog, shd.fs);\n\tglDeleteShader(shd.fs);\n\n\tglDeleteProgram(shd.prog);\n\n\tenvQuit(env);\n}\n\nvoid frame(const Env& env, const Shader& shd)\n{\n\tstatic float setting_r= 0.3;\n\tstatic float setting_g= 0.8;\n\tstatic float setting_b= 1.0;\n\n\tstruct Slider {\n\t\tconst char* title;\n\t\tfloat min;\n\t\tfloat max;\n\t\tfloat& value;\n\t\tint decimals;\n\t\tbool hover;\n\n\t\tstatic float height() { return 0.05; }\n\t\tstatic float width() { return 0.4; }\n\t\tstatic float top(std::size_t i) { return 1.0 - i*height(); }\n\t\tstatic float bottom(std::size_t i) { return top(i + 1); }\n\t\tbool pointInside(std::size_t i, Vec2f p) const\n\t\t{\n\t\t\treturn\tp.x >= -1.0\t&& p.x < width() - 1.0 &&\n\t\t\t\t\tp.y > bottom(i)\t&& p.y < top(i);\n\t\t}\n\t\tfloat fraction() const\n\t\t{ return (value - min)\/(max - min); }\n\t\tfloat coordToValue(float x) const\n\t\t{\n\t\t\treturn clamp((1.0 + x)\/width()*(max - min) + min, min, max);\n\t\t}\n\t};\n\n\tstatic Slider sliders[]= {\n\t\t{ \"r\",\t\t0.0,\t2.0, setting_r,\t2,\tfalse },\n\t\t{ \"g\",\t\t0.0,\t2.0, setting_g,\t2,\tfalse },\n\t\t{ \"b\",\t\t0.0,\t2.0, setting_b,\t2,\tfalse },\n\t};\n\tconst std::size_t slider_count= sizeof(sliders)\/sizeof(*sliders);\n\t\n\tstatic Vec2f prev_delta;\n\tstatic Vec2f rot;\n\t\n\t{ \/\/ User interaction\n\t\tbool slider_activity= false;\n\t\tfor (std::size_t i= 0; i < slider_count; ++i) {\n\t\t\tSlider& s= sliders[i];\n\t\t\tif (s.pointInside(i, env.anchorPos)) {\n\t\t\t\tif (env.lmbDown)\n\t\t\t\t\ts.value= s.coordToValue(env.cursorPos.x);\n\t\t\t\ts.hover= true;\n\t\t\t\tslider_activity= true;\n\t\t\t} else {\n\t\t\t\ts.hover= false;\n\t\t\t}\n\t\t}\n\t\t\n\t\tif (env.lmbDown && !slider_activity) {\n\t\t\tVec2f smooth_delta= prev_delta*0.5 + (env.cursorDelta)*0.5;\n\t\t\tprev_delta= smooth_delta;\n\t\t\t\n\t\t\trot += smooth_delta*2;\n\t\t\trot.y= clamp(rot.y, -tau\/4, tau\/4);\n\t\t}\n\t}\n\t\n\tglClear(GL_COLOR_BUFFER_BIT);\n\tglViewport(0, 0, env.winSize.x, env.winSize.y);\n\n\t{ \/\/ Draw volume\n\t\tstatic float phase;\n\n\t\t\/\/\/ @todo *dt\n\t\tphase += 0.3;\n\n\t\tglMatrixMode(GL_PROJECTION);\n\t\tglLoadIdentity();\n\n\t\tglMatrixMode(GL_MODELVIEW);\n\t\t\/\/ Trackball-style rotation\n\t\tglRotatef(rot.y*radToDeg, cos(rot.x), 0.0, sin(rot.x));\n\t\tglRotatef(rot.x*radToDeg, 0.0, -1.0, 0.0);\n\n\t\tglUseProgram(shd.prog);\n\t\tglUniform1f(shd.phaseLoc, phase);\n\t\tglUniform3f(shd.colorLoc, setting_r, setting_g, setting_b);\n\n\t\tglBegin(GL_QUADS);\n\t\t\tglVertex3f(-1, -1, 1);\n\t\t\tglVertex3f(1, -1, 1);\n\t\t\tglVertex3f(1, 1, 1);\n\t\t\tglVertex3f(-1, 1, 1);\n\t\tglEnd();\n\t}\n\n\t{ \/\/ Draw gui\n\t\tglMatrixMode(GL_MODELVIEW);\n\t\tglLoadIdentity();\n\t\tglUseProgram(0);\n\n\t\tglBegin(GL_QUADS);\n\t\t\t\/\/ Background\n\t\t\tglColor4f(0.0, 0.0, 0.0, 0.3);\n\t\t\tglVertex2f(-1.0, 1.0);\n\t\t\tglVertex2f(-1.0, 1.0 - slider_count*Slider::height());\n\t\t\tglVertex2f(Slider::width() - 1.0, 1.0 - slider_count*Slider::height());\n\t\t\tglVertex2f(Slider::width() - 1.0, 1.0);\n\n\t\t\tfor (std::size_t i= 0; i < slider_count; ++i) {\n\t\t\t\tSlider& s= sliders[i];\n\t\t\t\tfloat top= s.top(i);\n\t\t\t\tfloat bottom= s.bottom(i);\n\t\t\t\tfloat width= s.width()*s.fraction();\n\n\t\t\t\tif (!s.hover)\n\t\t\t\t\tglColor4f(0.3, 0.3, 0.3, 0.6);\n\t\t\t\telse\n\t\t\t\t\tglColor4f(1.0, 1.0, 1.0, 0.8);\n\n\t\t\t\tglVertex2f(-1.0, top);\n\t\t\t\tglVertex2f(-1.0, bottom);\n\t\t\t\tglVertex2f(-1.0 + width, bottom);\n\t\t\t\tglVertex2f(-1.0 + width, top);\n\t\t\t}\n\t\tglEnd();\n\t}\n} \n\n} \/\/ qm\n\nint main()\n{\n\tqm::Env env;\n\tqm::Shader shd;\n\tqm::init(env, shd);\n\n\twhile (!env.quitRequested) {\n\t\tqm::envUpdate(env);\n\t\tqm::frame(env, shd);\n\t}\n\n\tqm::quit(env, shd);\n}\n\n<commit_msg>Added noise<commit_after>\/\/ See unity.cpp for build instructions\n\n#include <cstdio>\n#include <cstdlib>\n#include <cstring>\n\n#include \"env.hpp\"\n#include \"gl.hpp\"\n\nnamespace qm {\nstruct Shader {\n\tGLuint vs;\n\tGLuint fs;\n\tGLuint prog;\n\tGLuint phaseLoc;\n\tGLuint colorLoc;\n};\n\nconst GLchar* g_vs= \"\\\n#version 120\\n\\\nvarying vec3 v_pos; \\\nvarying vec3 v_normal; \\\nvoid main() \\\n{ \\\n gl_Position= vec4(gl_Vertex.xy, 0.0, 1.0); \\\n\tv_pos= (gl_ModelViewMatrix*gl_Vertex).xyz; \\\n\tv_normal= mat3(gl_ModelViewMatrix)*vec3(gl_Vertex.xy, -1.0); \\\n} \\\n\\n\";\n\nconst GLchar* g_fs= \"\\\n#version 120\\n\\\nuniform float u_phase; \\\nuniform vec3 u_color; \\\nvarying vec3 v_pos; \\\nvarying vec3 v_normal; \\\nfloat rand(vec2 co){ \\\n return fract(sin(dot(co.xy ,vec2(12.9898,78.233))) * 43758.5453); \\\n} \\\n\/* x emission, y absorption *\/ \\\nvec2 sample(vec3 p) \\\n{ \\\n\tp.z += 0.2; \\\n\tfloat beam_e= \\\n\t\tabs(cos(p.z*10.0 - sign(p.z)*u_phase)*0.5 + 1.0)* \\\n\t\t\t0.001\/(p.x*p.x + p.y*p.y + 0.001); \\\n\tfloat disc_e= \\\n\t\t0.01\/((p.z*p.z + 0.01)*(p.x*p.x + p.y*p.y)*100.0 + 0.1); \\\n\tfloat hole_a= pow(min(1.0, 0.1\/(dot(p, p))), 10.0); \\\n\tfloat a= clamp(hole_a, 0.0, 1.0); \\\n return vec2((disc_e + beam_e)*(1 - a), a + disc_e*7.0)*25.0; \\\n} \\\nvoid main() \\\n{ \\\n\tvec3 n= normalize(v_normal); \\\n\tvec3 color= u_color; \\\n\tfloat intensity= 0.0; \\\n\tconst int steps= 45; \\\n\tconst float dl= 2.0\/steps; \\\n\tfor (int i= 0; i < steps; ++i) { \\\n\t\tvec2 s= sample(v_pos + n*2.0*float(steps - i - 1)\/steps); \\\n\t\tintensity= max(0, intensity + (s.x - s.y*intensity)*dl); \\\n\t} \\\n\tintensity += rand(v_pos.xy + vec2(u_phase, 0))*0.02; \\\n\tgl_FragColor= vec4(color*intensity, 1.0); \\\n} \\\n\\n\";\n\nvoid init(Env& env, Shader& shd)\n{\n\tenv= envInit();\n\tqueryGlFuncs();\n\n\t{ \/\/ Create shaders\n\t\t{ \/\/ Vertex\n\t\t\tshd.vs= glCreateShader(GL_VERTEX_SHADER);\n\t\t\tglShaderSource(shd.vs, 1, &g_vs, NULL);\n\t\t\tglCompileShader(shd.vs);\n\t\t\tcheckShaderStatus(shd.vs);\n\t\t}\n\t\t{ \/\/ Fragment\n\t\t\tshd.fs= glCreateShader(GL_FRAGMENT_SHADER);\n\t\t\tglShaderSource(shd.fs, 1, &g_fs, NULL);\n\t\t\tglCompileShader(shd.fs);\n\t\t\tcheckShaderStatus(shd.fs);\n\t\t}\n\t\t{ \/\/ Shader program\n\t\t\tshd.prog= glCreateProgram();\n\t\t\tglAttachShader(shd.prog, shd.vs);\n\t\t\tglAttachShader(shd.prog, shd.fs);\n\t\t\tglLinkProgram(shd.prog);\n\t\t\tcheckProgramStatus(shd.prog);\n\n\t\t\tshd.phaseLoc= glGetUniformLocation(shd.prog, \"u_phase\");\n\t\t\tshd.colorLoc= glGetUniformLocation(shd.prog, \"u_color\");\n\t\t}\n\t}\n\n\t{ \/\/ Setup initial GL state\n\t\tglClearColor(0.0, 0.0, 0.0, 0.0);\n\t\tglEnable(GL_BLEND);\n\t\tglBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);\n\t}\n}\n\nvoid quit(Env& env, const Shader& shd)\n{\n\tglDetachShader(shd.prog, shd.vs);\n\tglDeleteShader(shd.vs);\n\n\tglDetachShader(shd.prog, shd.fs);\n\tglDeleteShader(shd.fs);\n\n\tglDeleteProgram(shd.prog);\n\n\tenvQuit(env);\n}\n\nvoid frame(const Env& env, const Shader& shd)\n{\n\tstatic float setting_r= 0.3;\n\tstatic float setting_g= 0.8;\n\tstatic float setting_b= 1.0;\n\n\tstruct Slider {\n\t\tconst char* title;\n\t\tfloat min;\n\t\tfloat max;\n\t\tfloat& value;\n\t\tint decimals;\n\t\tbool hover;\n\n\t\tstatic float height() { return 0.05; }\n\t\tstatic float width() { return 0.4; }\n\t\tstatic float top(std::size_t i) { return 1.0 - i*height(); }\n\t\tstatic float bottom(std::size_t i) { return top(i + 1); }\n\t\tbool pointInside(std::size_t i, Vec2f p) const\n\t\t{\n\t\t\treturn\tp.x >= -1.0\t&& p.x < width() - 1.0 &&\n\t\t\t\t\tp.y > bottom(i)\t&& p.y < top(i);\n\t\t}\n\t\tfloat fraction() const\n\t\t{ return (value - min)\/(max - min); }\n\t\tfloat coordToValue(float x) const\n\t\t{\n\t\t\treturn clamp((1.0 + x)\/width()*(max - min) + min, min, max);\n\t\t}\n\t};\n\n\tstatic Slider sliders[]= {\n\t\t{ \"r\",\t\t0.0,\t2.0, setting_r,\t2,\tfalse },\n\t\t{ \"g\",\t\t0.0,\t2.0, setting_g,\t2,\tfalse },\n\t\t{ \"b\",\t\t0.0,\t2.0, setting_b,\t2,\tfalse },\n\t};\n\tconst std::size_t slider_count= sizeof(sliders)\/sizeof(*sliders);\n\t\n\tstatic Vec2f prev_delta;\n\tstatic Vec2f rot;\n\t\n\t{ \/\/ User interaction\n\t\tbool slider_activity= false;\n\t\tfor (std::size_t i= 0; i < slider_count; ++i) {\n\t\t\tSlider& s= sliders[i];\n\t\t\tif (s.pointInside(i, env.anchorPos)) {\n\t\t\t\tif (env.lmbDown)\n\t\t\t\t\ts.value= s.coordToValue(env.cursorPos.x);\n\t\t\t\ts.hover= true;\n\t\t\t\tslider_activity= true;\n\t\t\t} else {\n\t\t\t\ts.hover= false;\n\t\t\t}\n\t\t}\n\t\t\n\t\tif (env.lmbDown && !slider_activity) {\n\t\t\tVec2f smooth_delta= prev_delta*0.5 + (env.cursorDelta)*0.5;\n\t\t\tprev_delta= smooth_delta;\n\t\t\t\n\t\t\trot += smooth_delta*2;\n\t\t\trot.y= clamp(rot.y, -tau\/4, tau\/4);\n\t\t}\n\t}\n\t\n\tglClear(GL_COLOR_BUFFER_BIT);\n\tglViewport(0, 0, env.winSize.x, env.winSize.y);\n\n\t{ \/\/ Draw volume\n\t\tstatic float phase;\n\n\t\t\/\/\/ @todo *dt\n\t\tphase += 0.3;\n\n\t\tglMatrixMode(GL_PROJECTION);\n\t\tglLoadIdentity();\n\n\t\tglMatrixMode(GL_MODELVIEW);\n\t\t\/\/ Trackball-style rotation\n\t\tglRotatef(rot.y*radToDeg, cos(rot.x), 0.0, sin(rot.x));\n\t\tglRotatef(rot.x*radToDeg, 0.0, -1.0, 0.0);\n\n\t\tglUseProgram(shd.prog);\n\t\tglUniform1f(shd.phaseLoc, phase);\n\t\tglUniform3f(shd.colorLoc, setting_r, setting_g, setting_b);\n\n\t\tglBegin(GL_QUADS);\n\t\t\tglVertex3f(-1, -1, 1);\n\t\t\tglVertex3f(1, -1, 1);\n\t\t\tglVertex3f(1, 1, 1);\n\t\t\tglVertex3f(-1, 1, 1);\n\t\tglEnd();\n\t}\n\n\t{ \/\/ Draw gui\n\t\tglMatrixMode(GL_MODELVIEW);\n\t\tglLoadIdentity();\n\t\tglUseProgram(0);\n\n\t\tglBegin(GL_QUADS);\n\t\t\t\/\/ Background\n\t\t\tglColor4f(0.0, 0.0, 0.0, 0.3);\n\t\t\tglVertex2f(-1.0, 1.0);\n\t\t\tglVertex2f(-1.0, 1.0 - slider_count*Slider::height());\n\t\t\tglVertex2f(Slider::width() - 1.0, 1.0 - slider_count*Slider::height());\n\t\t\tglVertex2f(Slider::width() - 1.0, 1.0);\n\n\t\t\tfor (std::size_t i= 0; i < slider_count; ++i) {\n\t\t\t\tSlider& s= sliders[i];\n\t\t\t\tfloat top= s.top(i);\n\t\t\t\tfloat bottom= s.bottom(i);\n\t\t\t\tfloat width= s.width()*s.fraction();\n\n\t\t\t\tif (!s.hover)\n\t\t\t\t\tglColor4f(0.3, 0.3, 0.3, 0.6);\n\t\t\t\telse\n\t\t\t\t\tglColor4f(1.0, 1.0, 1.0, 0.8);\n\n\t\t\t\tglVertex2f(-1.0, top);\n\t\t\t\tglVertex2f(-1.0, bottom);\n\t\t\t\tglVertex2f(-1.0 + width, bottom);\n\t\t\t\tglVertex2f(-1.0 + width, top);\n\t\t\t}\n\t\tglEnd();\n\t}\n} \n\n} \/\/ qm\n\nint main()\n{\n\tqm::Env env;\n\tqm::Shader shd;\n\tqm::init(env, shd);\n\n\twhile (!env.quitRequested) {\n\t\tqm::envUpdate(env);\n\t\tqm::frame(env, shd);\n\t}\n\n\tqm::quit(env, shd);\n}\n\n<|endoftext|>"} {"text":"<commit_before>#include <QGLWidget>\n#include \"Mesh.h\"\n#include \"Matrix44.h\"\n#include \"Common.h\"\n\nMesh::Mesh() : triangleColouring(MESH_COLOUR_SAME), geomType(MESH_GEOM_TRIANGLES),\n\tsurfaceTexture(NULL), useSurfaceNormals(false)\n{\n}\n\nMesh::~Mesh()\n{\n}\n\nconst VertexList& Mesh::vertices() const\n{\n\treturn verts;\n}\n\nvoid Mesh::setVertices(const VertexList& newVerts)\n{\n\tverts = newVerts;\n}\n\nconst TriangleList& Mesh::triangles() const\n{\n\treturn tris;\n}\n\nvoid Mesh::setTriangles(const TriangleList& newTris)\n{\n\ttris = newTris;\n}\n\nMesh::Colouring Mesh::colouring() const\n{\n\treturn triangleColouring;\n}\n\nvoid Mesh::setColouring(Mesh::Colouring newColouring)\n{\n\ttriangleColouring = newColouring;\n}\n\nMesh::GeometryType Mesh::geometryType() const\n{\n\treturn geomType;\n}\n\nvoid Mesh::setGeometryType(Mesh::GeometryType newGeomType)\n{\n\tgeomType = newGeomType;\n}\n\nbool Mesh::showingNormals() const\n{\n\treturn drawNormals;\n}\n\nvoid Mesh::showNormals(bool willShow)\n{\n\tdrawNormals = willShow;\n}\n\nTexture* Mesh::texture() const\n{\n\treturn surfaceTexture;\n}\n\nvoid Mesh::setTexture(Texture* newTexture)\n{\n\tsurfaceTexture = newTexture;\n}\n\n\nbool Mesh::usingPerFaceNormals() const\n{\n\treturn useSurfaceNormals;\n}\n\nvoid Mesh::setPerFaceNormals(bool usePerFace)\n{\n\tuseSurfaceNormals = usePerFace;\n}\n\nvoid Mesh::renderVertex(const Vertex& v)\n{\n\tglTexCoord2f(v.texCoord.s, v.texCoord.t);\n\tglNormal3f(v.normal.x, v.normal.y, v.normal.z);\n\tglVertex3f(v.position.x, v.position.y, v.position.y);\n}\n\nvoid Mesh::renderTriangle(const VertexList& verticesToUse, const Triangle& tri)\n{\n\trenderVertex( verticesToUse[tri.v1] );\n\trenderVertex( verticesToUse[tri.v2] );\n\trenderVertex( verticesToUse[tri.v3] );\n}\n\nvoid Mesh::renderPoints(const VertexList& vertices)\n{\n\tglColor3f(1.0f, 1.0f, 1.0f);\n\tglBegin(GL_POINTS);\n\t\tfor (VertexList::const_iterator it = vertices.begin(); (it != vertices.end()); it++)\n\t\t\tglVertex3f(it->position.x, it->position.y, it->position.x);\n\tglEnd();\n}\n\nvoid Mesh::renderLines(const VertexList& vertices, const TriangleList& triangles)\n{\n\tglColor3f(1.0f, 1.0f, 1.0f);\n\tglBegin(GL_LINES);\n\t\tfor (TriangleList::const_iterator it = triangles.begin(); (it != triangles.end()); it++)\n\t\t{\n\t\t\tconst Vertex& v1 = vertices[it->v1];\n\t\t\tconst Vertex& v2 = vertices[it->v2];\n\t\t\tconst Vertex& v3 = vertices[it->v3];\n\t\t\tglVertex3f(v1.position.x, v1.position.y, v1.position.x);\n\t\t\tglVertex3f(v2.position.x, v2.position.y, v2.position.x);\n\t\t\tglVertex3f(v2.position.x, v2.position.y, v2.position.x);\n\t\t\tglVertex3f(v3.position.x, v3.position.y, v3.position.x);\n\t\t\tglVertex3f(v3.position.x, v3.position.y, v3.position.x);\n\t\t\tglVertex3f(v1.position.x, v1.position.y, v1.position.x);\n\t\t}\n\tglEnd();\n}\n\nvoid Mesh::renderTriangles(const VertexList& vertices, const TriangleList& triangles)\n{\n\tglBegin(GL_TRIANGLES);\n\tif (triangleColouring == MESH_ALTERNATING_TRIANGLES)\n\t{\n\t\t\/\/ Whole for-loop put it if-statement so there isn't a branch every iteration (costly operation\n\t\tfor (unsigned int i = 0; (i < triangles.size()); i++)\n\t\t{\n\t\t\tconst Vector3& col = ALTERNATING_TRIANGLE_COLOURS[i % NUM_ALTERNATING_COLOURS];\n\t\t\tglColor3f(col.x, col.y, col.y);\n\t\t\trenderTriangle(vertices, tris[i]);\n\t\t}\n\t}\n\telse\n\t{\n\t\tfor (TriangleList::const_iterator it = triangles.begin(); (it != triangles.end()); it++)\t\n\t\t\trenderTriangle(vertices, *it);\n\t}\n\tglEnd();\n}\n\nvoid Mesh::renderNormals(const VertexList& vertices)\n{\n\tglColor3f(1.0f, 1.0f, 1.0f);\n\tglBegin(GL_LINES);\n\t\tfor (VertexList::const_iterator it = vertices.begin(); (it != vertices.end()); it++)\n\t\t{\n\t\t\tconst Vector3& position = it->position;\n\t\t\tconst Vector3& normal = it->normal;\n\t\t\tVector3 end = position + (normal * NORMAL_SCALING_FACTOR);\n\t\t\tglVertex3f(it->position.x, it->position.y, it->position.z);\n\t\t\tglVertex3f(end.x, end.y, end.y);\t\n\t\t}\n\tglEnd();\n}\n\nvoid Mesh::render()\n{\n\t\/\/ If texturing has been enabled, ensure we set the correct OpenGL state\n\tif (triangleColouring == MESH_TEXTURE)\n\t{\n\t\t\/\/ If texture hasn't been loaded yet - load it now!\n\t\t\/\/ This is lazy initialisation\n\t\tif (!surfaceTexture)\n\t\t\tsurfaceTexture = new Texture(\"resources\/world_texture.jpg\");\n\t\tglEnable(GL_TEXTURE_2D);\n\t\tsurfaceTexture->bind();\n\t}\n\n\tglMatrixMode(GL_MODELVIEW);\n\tglPushMatrix();\n\tglLoadIdentity();\n\n\t\/\/ Perform local model transformations on mesh\n\tMatrix44 transformation = Matrix44::translation(pos.x, pos.y, pos.z);\n\ttransformation = transformation * Matrix44::xyzRotation(rot);\n\t\/\/ Transform vertices using position and orientation of drawable\n\tVertexList transformedVerts = verts;\n\t\/\/ If using per-face normals and not per-vertex normals, compute surface normals now\n\tif (useSurfaceNormals)\n\t{\n\t\tVector3List surfaceNormals = computeSurfaceNormals(transformedVerts, tris);\n\t\tfor (int i = 0; (i < surfaceNormals.size()); i++)\n\t\t{\n\t\t\ttransformedVerts[i].normal = surfaceNormals[i];\n\t\t}\n\t}\n\tfor (VertexList::iterator it = transformedVerts.begin(); (it != transformedVerts.end()); it++)\n\t{\n\t\tit->position = transformation * it->position;\n\t\tit->normal = (transformation * it->normal).normalise();\n\t}\n\n\t\/\/ How mesh is drawn depends on geometry type chosen\n\tswitch (geomType)\n\t{\n\tcase MESH_GEOM_POINTS:\n\t\trenderPoints(transformedVerts);\n\t\tbreak;\n\tcase MESH_GEOM_LINES:\n\t\trenderLines(transformedVerts, tris);\n\t\tbreak;\n\tcase MESH_GEOM_TRIANGLES:\n\t\trenderTriangles(transformedVerts, tris);\n\t\tbreak;\n\t}\n\t\/\/ Also draw lines reprensenting vertex normals\n\tif (drawNormals)\n\t{\n\t\trenderNormals(transformedVerts);\n\t}\n\n\tglPopMatrix();\n\n\t\/\/ Make sure the mesh's texture is unbinded after rendering\n\tif (triangleColouring == MESH_TEXTURE)\n\t{\n\t\tif (surfaceTexture)\n\t\t\tsurfaceTexture->unbind();\n\t\tglDisable(GL_TEXTURE_2D);\n\t}\n}\n\nVector3List Mesh::computeSurfaceNormals(const VertexList& vertices, const TriangleList& triangles)\n{\n\tVector3List normals;\n\tnormals.resize(vertices.size());\n\n\tfor (TriangleList::const_iterator it = triangles.begin();\n\t\t(it != triangles.end()); it++)\n\t{\n\t\t\/\/ Get two points of the triangle and create two vectors from them (sides of triangle)\n\t\tVector3 s1 = vertices[it->v2].position - vertices[it->v1].position;\n\t\tVector3 s2 = vertices[it->v3].position - vertices[it->v1].position;\n\t\t\/\/ Compute cross product of sides to get surface normal\n\t\tVector3 surfaceNormal = s1.cross(s2).normalise();\n\t\t\/\/ Assign this surface normal to all v\n\t\tnormals[it->v1] = surfaceNormal;\n\t\tnormals[it->v2] = surfaceNormal;\n\t\tnormals[it->v3] = surfaceNormal;\n\t}\n\n\treturn normals;\n}\n<commit_msg>Guarantee white being uswed as colour for \"same triangle colouring\"<commit_after>#include <QGLWidget>\n#include \"Mesh.h\"\n#include \"Matrix44.h\"\n#include \"Common.h\"\n\nMesh::Mesh() : triangleColouring(MESH_COLOUR_SAME), geomType(MESH_GEOM_TRIANGLES),\n\tsurfaceTexture(NULL), useSurfaceNormals(false)\n{\n}\n\nMesh::~Mesh()\n{\n}\n\nconst VertexList& Mesh::vertices() const\n{\n\treturn verts;\n}\n\nvoid Mesh::setVertices(const VertexList& newVerts)\n{\n\tverts = newVerts;\n}\n\nconst TriangleList& Mesh::triangles() const\n{\n\treturn tris;\n}\n\nvoid Mesh::setTriangles(const TriangleList& newTris)\n{\n\ttris = newTris;\n}\n\nMesh::Colouring Mesh::colouring() const\n{\n\treturn triangleColouring;\n}\n\nvoid Mesh::setColouring(Mesh::Colouring newColouring)\n{\n\ttriangleColouring = newColouring;\n}\n\nMesh::GeometryType Mesh::geometryType() const\n{\n\treturn geomType;\n}\n\nvoid Mesh::setGeometryType(Mesh::GeometryType newGeomType)\n{\n\tgeomType = newGeomType;\n}\n\nbool Mesh::showingNormals() const\n{\n\treturn drawNormals;\n}\n\nvoid Mesh::showNormals(bool willShow)\n{\n\tdrawNormals = willShow;\n}\n\nTexture* Mesh::texture() const\n{\n\treturn surfaceTexture;\n}\n\nvoid Mesh::setTexture(Texture* newTexture)\n{\n\tsurfaceTexture = newTexture;\n}\n\n\nbool Mesh::usingPerFaceNormals() const\n{\n\treturn useSurfaceNormals;\n}\n\nvoid Mesh::setPerFaceNormals(bool usePerFace)\n{\n\tuseSurfaceNormals = usePerFace;\n}\n\nvoid Mesh::renderVertex(const Vertex& v)\n{\n\tglTexCoord2f(v.texCoord.s, v.texCoord.t);\n\tglNormal3f(v.normal.x, v.normal.y, v.normal.z);\n\tglVertex3f(v.position.x, v.position.y, v.position.y);\n}\n\nvoid Mesh::renderTriangle(const VertexList& verticesToUse, const Triangle& tri)\n{\n\trenderVertex( verticesToUse[tri.v1] );\n\trenderVertex( verticesToUse[tri.v2] );\n\trenderVertex( verticesToUse[tri.v3] );\n}\n\nvoid Mesh::renderPoints(const VertexList& vertices)\n{\n\tglColor3f(1.0f, 1.0f, 1.0f);\n\tglBegin(GL_POINTS);\n\t\tfor (VertexList::const_iterator it = vertices.begin(); (it != vertices.end()); it++)\n\t\t\tglVertex3f(it->position.x, it->position.y, it->position.x);\n\tglEnd();\n}\n\nvoid Mesh::renderLines(const VertexList& vertices, const TriangleList& triangles)\n{\n\tglColor3f(1.0f, 1.0f, 1.0f);\n\tglBegin(GL_LINES);\n\t\tfor (TriangleList::const_iterator it = triangles.begin(); (it != triangles.end()); it++)\n\t\t{\n\t\t\tconst Vertex& v1 = vertices[it->v1];\n\t\t\tconst Vertex& v2 = vertices[it->v2];\n\t\t\tconst Vertex& v3 = vertices[it->v3];\n\t\t\tglVertex3f(v1.position.x, v1.position.y, v1.position.x);\n\t\t\tglVertex3f(v2.position.x, v2.position.y, v2.position.x);\n\t\t\tglVertex3f(v2.position.x, v2.position.y, v2.position.x);\n\t\t\tglVertex3f(v3.position.x, v3.position.y, v3.position.x);\n\t\t\tglVertex3f(v3.position.x, v3.position.y, v3.position.x);\n\t\t\tglVertex3f(v1.position.x, v1.position.y, v1.position.x);\n\t\t}\n\tglEnd();\n}\n\nvoid Mesh::renderTriangles(const VertexList& vertices, const TriangleList& triangles)\n{\n\tglBegin(GL_TRIANGLES);\n\tif (triangleColouring == MESH_ALTERNATING_TRIANGLES)\n\t{\n\t\t\/\/ Whole for-loop put it if-statement so there isn't a branch every iteration (costly operation\n\t\tfor (unsigned int i = 0; (i < triangles.size()); i++)\n\t\t{\n\t\t\tconst Vector3& col = ALTERNATING_TRIANGLE_COLOURS[i % NUM_ALTERNATING_COLOURS];\n\t\t\tglColor3f(col.x, col.y, col.y);\n\t\t\trenderTriangle(vertices, tris[i]);\n\t\t}\n\t}\n\telse\n\t{\n\t\tif (triangleColouring == MESH_COLOUR_SAME)\n\t\t\tglColor3f(1.0f, 1.0f, 1.0f);\n\t\tfor (TriangleList::const_iterator it = triangles.begin(); (it != triangles.end()); it++)\t\n\t\t\trenderTriangle(vertices, *it);\n\t}\n\tglEnd();\n}\n\nvoid Mesh::renderNormals(const VertexList& vertices)\n{\n\tglColor3f(1.0f, 1.0f, 1.0f);\n\tglBegin(GL_LINES);\n\t\tfor (VertexList::const_iterator it = vertices.begin(); (it != vertices.end()); it++)\n\t\t{\n\t\t\tconst Vector3& position = it->position;\n\t\t\tconst Vector3& normal = it->normal;\n\t\t\tVector3 end = position + (normal * NORMAL_SCALING_FACTOR);\n\t\t\tglVertex3f(it->position.x, it->position.y, it->position.z);\n\t\t\tglVertex3f(end.x, end.y, end.y);\t\n\t\t}\n\tglEnd();\n}\n\nvoid Mesh::render()\n{\n\t\/\/ If texturing has been enabled, ensure we set the correct OpenGL state\n\tif (triangleColouring == MESH_TEXTURE)\n\t{\n\t\t\/\/ If texture hasn't been loaded yet - load it now!\n\t\t\/\/ This is lazy initialisation\n\t\tif (!surfaceTexture)\n\t\t\tsurfaceTexture = new Texture(\"resources\/world_texture.jpg\");\n\t\tglEnable(GL_TEXTURE_2D);\n\t\tsurfaceTexture->bind();\n\t}\n\n\tglMatrixMode(GL_MODELVIEW);\n\tglPushMatrix();\n\tglLoadIdentity();\n\n\t\/\/ Perform local model transformations on mesh\n\tMatrix44 transformation = Matrix44::translation(pos.x, pos.y, pos.z);\n\ttransformation = transformation * Matrix44::xyzRotation(rot);\n\t\/\/ Transform vertices using position and orientation of drawable\n\tVertexList transformedVerts = verts;\n\t\/\/ If using per-face normals and not per-vertex normals, compute surface normals now\n\tif (useSurfaceNormals)\n\t{\n\t\tVector3List surfaceNormals = computeSurfaceNormals(transformedVerts, tris);\n\t\tfor (int i = 0; (i < surfaceNormals.size()); i++)\n\t\t{\n\t\t\ttransformedVerts[i].normal = surfaceNormals[i];\n\t\t}\n\t}\n\tfor (VertexList::iterator it = transformedVerts.begin(); (it != transformedVerts.end()); it++)\n\t{\n\t\tit->position = transformation * it->position;\n\t\tit->normal = (transformation * it->normal).normalise();\n\t}\n\n\t\/\/ How mesh is drawn depends on geometry type chosen\n\tswitch (geomType)\n\t{\n\tcase MESH_GEOM_POINTS:\n\t\trenderPoints(transformedVerts);\n\t\tbreak;\n\tcase MESH_GEOM_LINES:\n\t\trenderLines(transformedVerts, tris);\n\t\tbreak;\n\tcase MESH_GEOM_TRIANGLES:\n\t\trenderTriangles(transformedVerts, tris);\n\t\tbreak;\n\t}\n\t\/\/ Also draw lines reprensenting vertex normals\n\tif (drawNormals)\n\t{\n\t\trenderNormals(transformedVerts);\n\t}\n\n\tglPopMatrix();\n\n\t\/\/ Make sure the mesh's texture is unbinded after rendering\n\tif (triangleColouring == MESH_TEXTURE)\n\t{\n\t\tif (surfaceTexture)\n\t\t\tsurfaceTexture->unbind();\n\t\tglDisable(GL_TEXTURE_2D);\n\t}\n}\n\nVector3List Mesh::computeSurfaceNormals(const VertexList& vertices, const TriangleList& triangles)\n{\n\tVector3List normals;\n\tnormals.resize(vertices.size());\n\n\tfor (TriangleList::const_iterator it = triangles.begin();\n\t\t(it != triangles.end()); it++)\n\t{\n\t\t\/\/ Get two points of the triangle and create two vectors from them (sides of triangle)\n\t\tVector3 s1 = vertices[it->v2].position - vertices[it->v1].position;\n\t\tVector3 s2 = vertices[it->v3].position - vertices[it->v1].position;\n\t\t\/\/ Compute cross product of sides to get surface normal\n\t\tVector3 surfaceNormal = s1.cross(s2).normalise();\n\t\t\/\/ Assign this surface normal to all v\n\t\tnormals[it->v1] = surfaceNormal;\n\t\tnormals[it->v2] = surfaceNormal;\n\t\tnormals[it->v3] = surfaceNormal;\n\t}\n\n\treturn normals;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\r\n * Copyright (c) 2007-2008 Digital Bazaar, Inc. All rights reserved.\r\n *\/\r\n#include \"db\/modest\/OperationDispatcher.h\"\r\n#include \"db\/modest\/Engine.h\"\r\n\r\nusing namespace std;\r\nusing namespace db::modest;\r\nusing namespace db::rt;\r\n\r\nOperationDispatcher::OperationDispatcher(Engine* e) :\r\n ThreadPool(200),\r\n JobDispatcher(this, false)\r\n{\r\n mEngine = e;\r\n mDispatch = false;\r\n \r\n \/\/ set thread expire time to 2 minutes (120000 milliseconds) by default\r\n getThreadPool()->setThreadExpireTime(120000);\r\n}\r\n\r\nOperationDispatcher::~OperationDispatcher()\r\n{\r\n \/\/ stop dispatching\r\n stopDispatching();\r\n \r\n \/\/ terminate all running operations\r\n terminateRunningOperations();\r\n \r\n \/\/ clear all queued operations\r\n clearQueuedOperations();\r\n}\r\n\r\nbool OperationDispatcher::canDispatch()\r\n{\r\n return mDispatch;\r\n}\r\n\r\nvoid OperationDispatcher::dispatchJobs()\r\n{\r\n OperationImpl* impl = NULL;\r\n \r\n \/\/ get engine state\r\n ImmutableState* state = mEngine->getState();\r\n \r\n lock();\r\n {\r\n \/\/ turn off dispatching until an Operation executes or is canceled\r\n mDispatch = false;\r\n \r\n \/\/ execute all Operations that can be executed\r\n int guardCheck;\r\n for(list<Runnable*>::iterator i = mJobQueue.begin();\r\n impl == NULL && i != mJobQueue.end();)\r\n {\r\n impl = (OperationImpl*)*i;\r\n \r\n \/\/ lock engine state\r\n state->lock();\r\n {\r\n \/\/ check the Operation's guard restrictions\r\n guardCheck = 0;\r\n if(impl->getGuard() != NULL)\r\n {\r\n Operation& op = mOpMap[impl];\r\n if(!impl->getGuard()->canExecuteOperation(state, op))\r\n {\r\n if(!impl->isInterrupted() &&\r\n !impl->getGuard()->mustCancelOperation(state, op))\r\n {\r\n \/\/ operation can wait\r\n guardCheck = 1;\r\n }\r\n else\r\n {\r\n \/\/ operation must be canceled\r\n guardCheck = 2;\r\n }\r\n }\r\n }\r\n \r\n switch(guardCheck)\r\n {\r\n case 0:\r\n \/\/ Operation is executable, enable dispatching and unqueue\r\n mDispatch = true;\r\n i = mJobQueue.erase(i);\r\n \r\n \/\/ do pre-execution state mutation\r\n if(impl->getStateMutator() != NULL)\r\n {\r\n impl->getStateMutator()->mutatePreExecutionState(\r\n (State*)state, mOpMap[impl]);\r\n }\r\n \r\n \/\/ try to run the operation\r\n if(getThreadPool()->tryRunJob(*impl))\r\n {\r\n \/\/ Operation executed, no need to run it outside of loop\r\n impl = NULL;\r\n }\r\n break;\r\n case 1:\r\n \/\/ move to next Operation\r\n impl = NULL;\r\n i++;\r\n break;\r\n case 2:\r\n \/\/ Operation is canceled, stop, unmap and unqueue\r\n impl->stop();\r\n mOpMap.erase(impl);\r\n i = mJobQueue.erase(i);\r\n impl = NULL;\r\n break;\r\n }\r\n }\r\n \/\/ unlock engine state\r\n state->unlock();\r\n }\r\n }\r\n unlock();\r\n \r\n if(impl != NULL)\r\n {\r\n \/\/ execute Operation, allow thread blocking\r\n getThreadPool()->runJob(*impl);\r\n }\r\n}\r\n\r\nvoid OperationDispatcher::queueOperation(Operation& op)\r\n{\r\n lock();\r\n {\r\n \/\/ ensure to enable dispatching, then add operation to queue and map\r\n mDispatch = true;\r\n mJobQueue.push_back(&(*op));\r\n mOpMap.insert(make_pair(&(*op), op));\r\n }\r\n unlock();\r\n \r\n \/\/ wake up dispatcher\r\n wakeup();\r\n}\r\n\r\nvoid OperationDispatcher::clearQueuedOperations()\r\n{\r\n lock();\r\n {\r\n \/\/ remove all job queue entries from the map\r\n for(list<Runnable*>::iterator i = mJobQueue.begin();\r\n i != mJobQueue.end(); i++)\r\n {\r\n mOpMap.erase((OperationImpl*)*i);\r\n }\r\n \r\n \/\/ clear queue\r\n mJobQueue.clear();\r\n }\r\n unlock();\r\n \r\n \/\/ wake up dispatcher\r\n wakeup();\r\n}\r\n\r\nvoid OperationDispatcher::terminateRunningOperations()\r\n{\r\n JobDispatcher::terminateAllRunningJobs();\r\n \r\n \/\/ wake up dispatcher\r\n wakeup();\r\n}\r\n\r\nvoid OperationDispatcher::jobCompleted(PooledThread* t)\r\n{\r\n lock();\r\n {\r\n \/\/ Note: this method is executed by a PooledThread, external to an\r\n \/\/ Operation, so that the Operation can be safely garbage-collected\r\n \/\/ here if the map happens to hold the last reference to it \r\n \r\n \/\/ get operation reference\r\n OperationImpl* impl = (OperationImpl*)t->getJob();\r\n Operation& op = mOpMap[impl];\r\n \r\n \/\/ do post-execution state mutation\r\n if(op->getStateMutator() != NULL)\r\n {\r\n mEngine->getState()->lock();\r\n {\r\n op->getStateMutator()->mutatePostExecutionState(\r\n (State*)mEngine->getState(), op);\r\n }\r\n mEngine->getState()->unlock();\r\n }\r\n \r\n \/\/ stop operation\r\n op->stop();\r\n \r\n \/\/ wake up dispatcher\r\n mDispatch = true;\r\n wakeup();\r\n \r\n \/\/ remove operation reference from map\r\n mOpMap.erase(impl);\r\n }\r\n unlock();\r\n \r\n \/\/ call parent method to release thread back into pool\r\n ThreadPool::jobCompleted(t);\r\n}\r\n\r\nOperation OperationDispatcher::getCurrentOperation()\r\n{\r\n \/\/ get the current thread's OperationImpl\r\n Thread* thread = Thread::currentThread();\r\n OperationImpl* impl = (OperationImpl*)thread->getUserData();\r\n Operation op = mOpMap[impl];\r\n return op;\r\n}\r\n\r\nThreadPool* OperationDispatcher::getThreadPool()\r\n{\r\n return JobDispatcher::getThreadPool();\r\n}\r\n\r\nunsigned int OperationDispatcher::getQueuedOperationCount()\r\n{\r\n return JobDispatcher::getQueuedJobCount();\r\n}\r\n\r\nunsigned int OperationDispatcher::getTotalOperationCount()\r\n{\r\n return JobDispatcher::getTotalJobCount();\r\n}\r\n<commit_msg>Made job cleanup code faster.<commit_after>\/*\r\n * Copyright (c) 2007-2008 Digital Bazaar, Inc. All rights reserved.\r\n *\/\r\n#include \"db\/modest\/OperationDispatcher.h\"\r\n#include \"db\/modest\/Engine.h\"\r\n\r\nusing namespace std;\r\nusing namespace db::modest;\r\nusing namespace db::rt;\r\n\r\nOperationDispatcher::OperationDispatcher(Engine* e) :\r\n ThreadPool(200),\r\n JobDispatcher(this, false)\r\n{\r\n mEngine = e;\r\n mDispatch = false;\r\n \r\n \/\/ set thread expire time to 2 minutes (120000 milliseconds) by default\r\n getThreadPool()->setThreadExpireTime(120000);\r\n}\r\n\r\nOperationDispatcher::~OperationDispatcher()\r\n{\r\n \/\/ stop dispatching\r\n stopDispatching();\r\n \r\n \/\/ terminate all running operations\r\n terminateRunningOperations();\r\n \r\n \/\/ clear all queued operations\r\n clearQueuedOperations();\r\n}\r\n\r\nbool OperationDispatcher::canDispatch()\r\n{\r\n return mDispatch;\r\n}\r\n\r\nvoid OperationDispatcher::dispatchJobs()\r\n{\r\n OperationImpl* impl = NULL;\r\n \r\n \/\/ get engine state\r\n ImmutableState* state = mEngine->getState();\r\n \r\n lock();\r\n {\r\n \/\/ turn off dispatching until an Operation executes or is canceled\r\n mDispatch = false;\r\n \r\n \/\/ execute all Operations that can be executed\r\n int guardCheck;\r\n for(list<Runnable*>::iterator i = mJobQueue.begin();\r\n impl == NULL && i != mJobQueue.end();)\r\n {\r\n impl = (OperationImpl*)*i;\r\n \r\n \/\/ lock engine state\r\n state->lock();\r\n {\r\n \/\/ check the Operation's guard restrictions\r\n guardCheck = 0;\r\n if(impl->getGuard() != NULL)\r\n {\r\n Operation& op = mOpMap[impl];\r\n if(!impl->getGuard()->canExecuteOperation(state, op))\r\n {\r\n if(!impl->isInterrupted() &&\r\n !impl->getGuard()->mustCancelOperation(state, op))\r\n {\r\n \/\/ operation can wait\r\n guardCheck = 1;\r\n }\r\n else\r\n {\r\n \/\/ operation must be canceled\r\n guardCheck = 2;\r\n }\r\n }\r\n }\r\n \r\n switch(guardCheck)\r\n {\r\n case 0:\r\n \/\/ Operation is executable, enable dispatching and unqueue\r\n mDispatch = true;\r\n i = mJobQueue.erase(i);\r\n \r\n \/\/ do pre-execution state mutation\r\n if(impl->getStateMutator() != NULL)\r\n {\r\n impl->getStateMutator()->mutatePreExecutionState(\r\n (State*)state, mOpMap[impl]);\r\n }\r\n \r\n \/\/ try to run the operation\r\n if(getThreadPool()->tryRunJob(*impl))\r\n {\r\n \/\/ Operation executed, no need to run it outside of loop\r\n impl = NULL;\r\n }\r\n break;\r\n case 1:\r\n \/\/ move to next Operation\r\n impl = NULL;\r\n i++;\r\n break;\r\n case 2:\r\n \/\/ Operation is canceled, stop, unmap and unqueue\r\n impl->stop();\r\n mOpMap.erase(impl);\r\n i = mJobQueue.erase(i);\r\n impl = NULL;\r\n break;\r\n }\r\n }\r\n \/\/ unlock engine state\r\n state->unlock();\r\n }\r\n }\r\n unlock();\r\n \r\n if(impl != NULL)\r\n {\r\n \/\/ execute Operation, allow thread blocking\r\n getThreadPool()->runJob(*impl);\r\n }\r\n}\r\n\r\nvoid OperationDispatcher::queueOperation(Operation& op)\r\n{\r\n lock();\r\n {\r\n \/\/ ensure to enable dispatching, then add operation to queue and map\r\n mDispatch = true;\r\n mJobQueue.push_back(&(*op));\r\n mOpMap.insert(make_pair(&(*op), op));\r\n }\r\n unlock();\r\n \r\n \/\/ wake up dispatcher\r\n wakeup();\r\n}\r\n\r\nvoid OperationDispatcher::clearQueuedOperations()\r\n{\r\n lock();\r\n {\r\n \/\/ remove all job queue entries from the map\r\n for(list<Runnable*>::iterator i = mJobQueue.begin();\r\n i != mJobQueue.end(); i++)\r\n {\r\n mOpMap.erase((OperationImpl*)*i);\r\n }\r\n \r\n \/\/ clear queue\r\n mJobQueue.clear();\r\n }\r\n unlock();\r\n \r\n \/\/ wake up dispatcher\r\n wakeup();\r\n}\r\n\r\nvoid OperationDispatcher::terminateRunningOperations()\r\n{\r\n JobDispatcher::terminateAllRunningJobs();\r\n \r\n \/\/ wake up dispatcher\r\n wakeup();\r\n}\r\n\r\nvoid OperationDispatcher::jobCompleted(PooledThread* t)\r\n{\r\n lock();\r\n {\r\n \/\/ Note: this method is executed by a PooledThread, external to an\r\n \/\/ Operation, so that the Operation can be safely garbage-collected\r\n \/\/ here if the map happens to hold the last reference to it \r\n \r\n \/\/ get operation reference\r\n OperationImpl* impl = (OperationImpl*)t->getJob();\r\n OperationMap::iterator i = mOpMap.find(impl);\r\n Operation& op = i->second;\r\n \r\n \/\/ do post-execution state mutation\r\n if(op->getStateMutator() != NULL)\r\n {\r\n mEngine->getState()->lock();\r\n {\r\n op->getStateMutator()->mutatePostExecutionState(\r\n (State*)mEngine->getState(), op);\r\n }\r\n mEngine->getState()->unlock();\r\n }\r\n \r\n \/\/ stop operation\r\n op->stop();\r\n \r\n \/\/ wake up dispatcher\r\n mDispatch = true;\r\n wakeup();\r\n \r\n \/\/ remove operation reference from map\r\n mOpMap.erase(i);\r\n }\r\n unlock();\r\n \r\n \/\/ call parent method to release thread back into pool\r\n ThreadPool::jobCompleted(t);\r\n}\r\n\r\nOperation OperationDispatcher::getCurrentOperation()\r\n{\r\n \/\/ get the current thread's OperationImpl\r\n Thread* thread = Thread::currentThread();\r\n OperationImpl* impl = (OperationImpl*)thread->getUserData();\r\n Operation op = mOpMap[impl];\r\n return op;\r\n}\r\n\r\nThreadPool* OperationDispatcher::getThreadPool()\r\n{\r\n return JobDispatcher::getThreadPool();\r\n}\r\n\r\nunsigned int OperationDispatcher::getQueuedOperationCount()\r\n{\r\n return JobDispatcher::getQueuedJobCount();\r\n}\r\n\r\nunsigned int OperationDispatcher::getTotalOperationCount()\r\n{\r\n return JobDispatcher::getTotalJobCount();\r\n}\r\n<|endoftext|>"} {"text":"<commit_before>#include \"luaSemanticAnalyzerTest.h\"\n\n#include \"qrtext\/lua\/ast\/assignment.h\"\n#include \"qrtext\/lua\/ast\/block.h\"\n#include \"qrtext\/lua\/ast\/functionCall.h\"\n#include \"qrtext\/lua\/ast\/unaryMinus.h\"\n\n#include \"qrtext\/lua\/types\/integer.h\"\n#include \"qrtext\/lua\/types\/float.h\"\n#include \"qrtext\/lua\/types\/string.h\"\n\n#include \"gtest\/gtest.h\"\n\nusing namespace qrTest;\nusing namespace qrtext;\nusing namespace qrtext::lua;\nusing namespace qrtext::lua::details;\nusing namespace qrtext::lua::types;\n\nvoid LuaSemanticAnalyzerTest::SetUp()\n{\n\tmAnalyzer.reset(new LuaSemanticAnalyzer(mErrors));\n\tmParser.reset(new LuaParser(mErrors));\n\tmLexer.reset(new LuaLexer(mErrors));\n}\n\nQSharedPointer<qrtext::core::ast::Node> LuaSemanticAnalyzerTest::parse(QString const &code)\n{\n\treturn mParser->parse(mLexer->tokenize(code));\n}\n\nTEST_F(LuaSemanticAnalyzerTest, sanityCheck)\n{\n\tauto tree = parse(\"123\");\n\tmAnalyzer->analyze(tree);\n\tEXPECT_TRUE(mErrors.empty());\n\tEXPECT_TRUE(mAnalyzer->type(tree)->is<Integer>());\n\tEXPECT_TRUE(mAnalyzer->type(tree)->is<Number>());\n}\n\nTEST_F(LuaSemanticAnalyzerTest, assignment)\n{\n\tauto tree = parse(\"a = 123\");\n\n\tauto variable = as<ast::Assignment>(tree)->variable();\n\tauto value = as<ast::Assignment>(tree)->value();\n\n\tmAnalyzer->analyze(tree);\n\n\tEXPECT_TRUE(mErrors.empty());\n\tEXPECT_TRUE(mAnalyzer->type(variable)->is<types::Integer>());\n\tEXPECT_TRUE(mAnalyzer->type(value)->is<types::Integer>());\n}\n\nTEST_F(LuaSemanticAnalyzerTest, unaryOperator)\n{\n\tauto tree = parse(\"-123\");\n\n\tmAnalyzer->analyze(tree);\n\n\tEXPECT_TRUE(mErrors.empty());\n\tEXPECT_TRUE(mAnalyzer->type(as<ast::UnaryMinus>(tree))->is<types::Integer>());\n}\n\nTEST_F(LuaSemanticAnalyzerTest, propagation)\n{\n\tauto tree = parse(\"a = -123; b = a\");\n\n\tmAnalyzer->analyze(tree);\n\n\tEXPECT_TRUE(mErrors.empty());\n\n\tauto block = as<ast::Block>(tree);\n\tauto firstAssignment = as<ast::Assignment>(block->children()[0]);\n\tauto secondAssignment = as<ast::Assignment>(block->children()[1]);\n\n\tauto firstVariable = firstAssignment->variable();\n\tauto firstValue = firstAssignment->value();\n\n\tEXPECT_TRUE(mAnalyzer->type(firstVariable)->is<types::Integer>());\n\tEXPECT_TRUE(mAnalyzer->type(firstValue)->is<types::Integer>());\n\n\tauto secondVariable = secondAssignment->variable();\n\tauto secondValue = secondAssignment->value();\n\n\tEXPECT_TRUE(mAnalyzer->type(secondVariable)->is<types::Integer>());\n\tEXPECT_TRUE(mAnalyzer->type(secondValue)->is<types::Integer>());\n}\n\nTEST_F(LuaSemanticAnalyzerTest, integerFloatCoercion)\n{\n\tauto tree = parse(\"a = -123; a = 1.0\");\n\n\tmAnalyzer->analyze(tree);\n\n\tEXPECT_TRUE(mErrors.isEmpty());\n\n\tauto block = as<ast::Block>(tree);\n\tauto firstAssignment = as<ast::Assignment>(block->children()[0]);\n\tauto secondAssignment = as<ast::Assignment>(block->children()[1]);\n\n\tauto firstVariable = firstAssignment->variable();\n\tauto firstValue = firstAssignment->value();\n\n\tEXPECT_TRUE(mAnalyzer->type(firstVariable)->is<types::Float>());\n\tEXPECT_TRUE(mAnalyzer->type(firstValue)->is<types::Integer>());\n\n\tauto secondVariable = secondAssignment->variable();\n\tauto secondValue = secondAssignment->value();\n\n\tEXPECT_TRUE(mAnalyzer->type(secondVariable)->is<types::Float>());\n\tEXPECT_TRUE(mAnalyzer->type(secondValue)->is<types::Float>());\n}\n\nTEST_F(LuaSemanticAnalyzerTest, functionReturnType)\n{\n\tauto tree = parse(\"a = f(1)\");\n\n\tmAnalyzer->addIntrinsicFunction(\"f\", QSharedPointer<types::Function>(new types::Function(\n\t\t\tQSharedPointer<core::types::TypeExpression>(new types::Float()),\n\t\t\t{QSharedPointer<core::types::TypeExpression>(new types::Integer())}\n\t\t\t)));\n\n\tmAnalyzer->analyze(tree);\n\n\tEXPECT_TRUE(mErrors.isEmpty());\n\n\tauto assignment = as<ast::Assignment>(tree);\n\n\tauto a = assignment->variable();\n\tauto f = assignment->value();\n\n\tEXPECT_TRUE(mAnalyzer->type(a)->is<types::Float>());\n\tEXPECT_TRUE(mAnalyzer->type(f)->is<types::Float>());\n}\n\nTEST_F(LuaSemanticAnalyzerTest, functionParameters)\n{\n\tauto tree = parse(\"a = f(b, c)\");\n\n\tmAnalyzer->addIntrinsicFunction(\"f\", QSharedPointer<types::Function>(new types::Function(\n\t\t\tQSharedPointer<core::types::TypeExpression>(new types::Float()),\n\t\t\t{QSharedPointer<core::types::TypeExpression>(new types::Integer())\n\t\t\t\t\t, QSharedPointer<core::types::TypeExpression>(new types::String())}\n\t\t\t)));\n\n\tmAnalyzer->analyze(tree);\n\n\tEXPECT_TRUE(mErrors.isEmpty());\n\n\tauto assignment = as<ast::Assignment>(tree);\n\n\tauto f = as<ast::FunctionCall>(assignment->value());\n\n\tauto b = f->arguments()[0];\n\tauto c = f->arguments()[1];\n\n\tEXPECT_TRUE(mAnalyzer->type(b)->is<types::Integer>());\n\tEXPECT_TRUE(mAnalyzer->type(c)->is<types::String>());\n}\n\nTEST_F(LuaSemanticAnalyzerTest, invalidFunctionParameters)\n{\n\tauto tree = parse(\"a = f(0.5, 'a')\");\n\n\tmAnalyzer->addIntrinsicFunction(\"f\", QSharedPointer<types::Function>(new types::Function(\n\t\t\tQSharedPointer<core::types::TypeExpression>(new types::Float()),\n\t\t\t{QSharedPointer<core::types::TypeExpression>(new types::Integer())\n\t\t\t\t\t, QSharedPointer<core::types::TypeExpression>(new types::String())}\n\t\t\t)));\n\n\tmAnalyzer->analyze(tree);\n\n\tASSERT_FALSE(mErrors.isEmpty());\n}\n<commit_msg>added test for invalid use of integer-float coercion where it breaks existing type constraints<commit_after>#include \"luaSemanticAnalyzerTest.h\"\n\n#include \"qrtext\/core\/types\/any.h\"\n\n#include \"qrtext\/lua\/ast\/assignment.h\"\n#include \"qrtext\/lua\/ast\/block.h\"\n#include \"qrtext\/lua\/ast\/functionCall.h\"\n#include \"qrtext\/lua\/ast\/unaryMinus.h\"\n\n#include \"qrtext\/lua\/types\/integer.h\"\n#include \"qrtext\/lua\/types\/float.h\"\n#include \"qrtext\/lua\/types\/string.h\"\n\n#include \"gtest\/gtest.h\"\n\nusing namespace qrTest;\nusing namespace qrtext;\nusing namespace qrtext::lua;\nusing namespace qrtext::lua::details;\nusing namespace qrtext::lua::types;\n\nvoid LuaSemanticAnalyzerTest::SetUp()\n{\n\tmAnalyzer.reset(new LuaSemanticAnalyzer(mErrors));\n\tmParser.reset(new LuaParser(mErrors));\n\tmLexer.reset(new LuaLexer(mErrors));\n}\n\nQSharedPointer<qrtext::core::ast::Node> LuaSemanticAnalyzerTest::parse(QString const &code)\n{\n\treturn mParser->parse(mLexer->tokenize(code));\n}\n\nTEST_F(LuaSemanticAnalyzerTest, sanityCheck)\n{\n\tauto tree = parse(\"123\");\n\tmAnalyzer->analyze(tree);\n\tEXPECT_TRUE(mErrors.empty());\n\tEXPECT_TRUE(mAnalyzer->type(tree)->is<Integer>());\n\tEXPECT_TRUE(mAnalyzer->type(tree)->is<Number>());\n}\n\nTEST_F(LuaSemanticAnalyzerTest, assignment)\n{\n\tauto tree = parse(\"a = 123\");\n\n\tauto variable = as<ast::Assignment>(tree)->variable();\n\tauto value = as<ast::Assignment>(tree)->value();\n\n\tmAnalyzer->analyze(tree);\n\n\tEXPECT_TRUE(mErrors.empty());\n\tEXPECT_TRUE(mAnalyzer->type(variable)->is<types::Integer>());\n\tEXPECT_TRUE(mAnalyzer->type(value)->is<types::Integer>());\n}\n\nTEST_F(LuaSemanticAnalyzerTest, unaryOperator)\n{\n\tauto tree = parse(\"-123\");\n\n\tmAnalyzer->analyze(tree);\n\n\tEXPECT_TRUE(mErrors.empty());\n\tEXPECT_TRUE(mAnalyzer->type(as<ast::UnaryMinus>(tree))->is<types::Integer>());\n}\n\nTEST_F(LuaSemanticAnalyzerTest, propagation)\n{\n\tauto tree = parse(\"a = -123; b = a\");\n\n\tmAnalyzer->analyze(tree);\n\n\tEXPECT_TRUE(mErrors.empty());\n\n\tauto block = as<ast::Block>(tree);\n\tauto firstAssignment = as<ast::Assignment>(block->children()[0]);\n\tauto secondAssignment = as<ast::Assignment>(block->children()[1]);\n\n\tauto firstVariable = firstAssignment->variable();\n\tauto firstValue = firstAssignment->value();\n\n\tEXPECT_TRUE(mAnalyzer->type(firstVariable)->is<types::Integer>());\n\tEXPECT_TRUE(mAnalyzer->type(firstValue)->is<types::Integer>());\n\n\tauto secondVariable = secondAssignment->variable();\n\tauto secondValue = secondAssignment->value();\n\n\tEXPECT_TRUE(mAnalyzer->type(secondVariable)->is<types::Integer>());\n\tEXPECT_TRUE(mAnalyzer->type(secondValue)->is<types::Integer>());\n}\n\nTEST_F(LuaSemanticAnalyzerTest, integerFloatCoercion)\n{\n\tauto tree = parse(\"a = -123; a = 1.0\");\n\n\tmAnalyzer->analyze(tree);\n\n\tEXPECT_TRUE(mErrors.isEmpty());\n\n\tauto block = as<ast::Block>(tree);\n\tauto firstAssignment = as<ast::Assignment>(block->children()[0]);\n\tauto secondAssignment = as<ast::Assignment>(block->children()[1]);\n\n\tauto firstVariable = firstAssignment->variable();\n\tauto firstValue = firstAssignment->value();\n\n\tEXPECT_TRUE(mAnalyzer->type(firstVariable)->is<types::Float>());\n\tEXPECT_TRUE(mAnalyzer->type(firstValue)->is<types::Integer>());\n\n\tauto secondVariable = secondAssignment->variable();\n\tauto secondValue = secondAssignment->value();\n\n\tEXPECT_TRUE(mAnalyzer->type(secondVariable)->is<types::Float>());\n\tEXPECT_TRUE(mAnalyzer->type(secondValue)->is<types::Float>());\n}\n\nTEST_F(LuaSemanticAnalyzerTest, functionReturnType)\n{\n\tauto tree = parse(\"a = f(1)\");\n\n\tmAnalyzer->addIntrinsicFunction(\"f\", QSharedPointer<types::Function>(new types::Function(\n\t\t\tQSharedPointer<core::types::TypeExpression>(new types::Float()),\n\t\t\t{QSharedPointer<core::types::TypeExpression>(new types::Integer())}\n\t\t\t)));\n\n\tmAnalyzer->analyze(tree);\n\n\tEXPECT_TRUE(mErrors.isEmpty());\n\n\tauto assignment = as<ast::Assignment>(tree);\n\n\tauto a = assignment->variable();\n\tauto f = assignment->value();\n\n\tEXPECT_TRUE(mAnalyzer->type(a)->is<types::Float>());\n\tEXPECT_TRUE(mAnalyzer->type(f)->is<types::Float>());\n}\n\nTEST_F(LuaSemanticAnalyzerTest, functionParameters)\n{\n\tauto tree = parse(\"a = f(b, c)\");\n\n\tmAnalyzer->addIntrinsicFunction(\"f\", QSharedPointer<types::Function>(new types::Function(\n\t\t\tQSharedPointer<core::types::TypeExpression>(new types::Float()),\n\t\t\t{QSharedPointer<core::types::TypeExpression>(new types::Integer())\n\t\t\t\t\t, QSharedPointer<core::types::TypeExpression>(new types::String())}\n\t\t\t)));\n\n\tmAnalyzer->analyze(tree);\n\n\tEXPECT_TRUE(mErrors.isEmpty());\n\n\tauto assignment = as<ast::Assignment>(tree);\n\n\tauto f = as<ast::FunctionCall>(assignment->value());\n\n\tauto b = f->arguments()[0];\n\tauto c = f->arguments()[1];\n\n\tEXPECT_TRUE(mAnalyzer->type(b)->is<types::Integer>());\n\tEXPECT_TRUE(mAnalyzer->type(c)->is<types::String>());\n}\n\nTEST_F(LuaSemanticAnalyzerTest, invalidFunctionParameters)\n{\n\tauto tree = parse(\"a = f(0.5, 'a')\");\n\n\tmAnalyzer->addIntrinsicFunction(\"f\", QSharedPointer<types::Function>(new types::Function(\n\t\t\tQSharedPointer<core::types::TypeExpression>(new types::Float()),\n\t\t\t{QSharedPointer<core::types::TypeExpression>(new types::Integer())\n\t\t\t\t\t, QSharedPointer<core::types::TypeExpression>(new types::String())}\n\t\t\t)));\n\n\tmAnalyzer->analyze(tree);\n\n\tASSERT_FALSE(mErrors.isEmpty());\n}\n\nTEST_F(LuaSemanticAnalyzerTest, invalidCoercion)\n{\n\tauto tree = parse(\"a = f(b, c); b = 0.5\");\n\n\tmAnalyzer->addIntrinsicFunction(\"f\", QSharedPointer<types::Function>(new types::Function(\n\t\t\tQSharedPointer<core::types::TypeExpression>(new types::Float()),\n\t\t\t{QSharedPointer<core::types::TypeExpression>(new types::Integer())\n\t\t\t\t\t, QSharedPointer<core::types::TypeExpression>(new types::String())}\n\t\t\t)));\n\n\tmAnalyzer->analyze(tree);\n\n\tEXPECT_FALSE(mErrors.isEmpty());\n\n\tauto block = as<ast::Block>(tree);\n\tauto firstAssignment = as<ast::Assignment>(block->children()[0]);\n\n\tauto a = firstAssignment->variable();\n\tauto f = as<ast::FunctionCall>(firstAssignment->value());\n\n\tEXPECT_TRUE(mAnalyzer->type(a)->is<types::Float>());\n\n\tauto b = f->arguments()[0];\n\tauto c = f->arguments()[1];\n\n\tEXPECT_TRUE(mAnalyzer->type(b)->is<qrtext::core::types::Any>());\n\tEXPECT_TRUE(mAnalyzer->type(c)->is<types::String>());\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * opencog\/atoms\/core\/PutLink.cc\n *\n * Copyright (C) 2015 Linas Vepstas\n * All Rights Reserved\n *\n * This program is free software; you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License v3 as\n * published by the Free Software Foundation and including the exceptions\n * at http:\/\/opencog.org\/wiki\/Licenses\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public License\n * along with this program; if not, write to:\n * Free Software Foundation, Inc.,\n * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.\n *\/\n\n#include <opencog\/atoms\/base\/atom_types.h>\n#include <opencog\/atoms\/base\/ClassServer.h>\n#include \"DefineLink.h\"\n#include \"FreeLink.h\"\n#include \"LambdaLink.h\"\n#include \"PutLink.h\"\n\nusing namespace opencog;\n\nPutLink::PutLink(const HandleSeq& oset, Type t)\n : RewriteLink(oset, t)\n{\n\tinit();\n}\n\nPutLink::PutLink(const Link& l)\n : RewriteLink(l)\n{\n\tinit();\n}\n\n\/* ================================================================= *\/\n\n\/\/\/ PutLink expects a very strict format: an arity-2 link, with\n\/\/\/ the first part being a pattern, and the second a list or set\n\/\/\/ of values. If the pattern has N variables, then the seccond\n\/\/\/ part must have N values. Furthermore, any type restrictions on\n\/\/\/ the variables must be satisfied by the values.\n\/\/\/\n\/\/\/ The following formats are understood:\n\/\/\/\n\/\/\/ PutLink\n\/\/\/ <pattern with 1 variable>\n\/\/\/ <any single atom>\n\/\/\/\n\/\/\/ PutLink\n\/\/\/ <pattern with N variables>\n\/\/\/ ListLink ;; must have arity N\n\/\/\/ <atom 1>\n\/\/\/ ...\n\/\/\/ <atom N>\n\/\/\/\n\/\/\/ The below is a handy-dandy easy-to-use form. When it is reduced,\n\/\/\/ it will result in the creation of a set of reduced forms, not\n\/\/\/ just one (the two sets haveing the same arity). Unfortunately,\n\/\/\/ this trick cannot work for N=1 unless the variable is cosntrained\n\/\/\/ to not be a set.\n\/\/\/\n\/\/\/ PutLink\n\/\/\/ <pattern with N variables>\n\/\/\/ SetLink ;; Must hold a set of ListLinks\n\/\/\/ ListLink ;; must have arity N\n\/\/\/ <atom 1>\n\/\/\/ ...\n\/\/\/ <atom N>\n\/\/\/\nvoid PutLink::init(void)\n{\n\tif (not classserver().isA(get_type(), PUT_LINK))\n\t\tthrow InvalidParamException(TRACE_INFO, \"Expecting a PutLink\");\n\n\tsize_t sz = _outgoing.size();\n\tif (2 != sz and 3 != sz)\n\t\tthrow InvalidParamException(TRACE_INFO,\n\t\t\t\"Expecting an outgoing set size of two or three, got %d; %s\",\n\t\t\tsz, to_string().c_str());\n\n\tScopeLink::extract_variables(_outgoing);\n\n\tif (2 == sz)\n\t{\n\t\t\/\/ If the body is just a single variable, and there are no\n\t\t\/\/ type declarations for it, then ScopeLink gets confused.\n\t\t_vardecl = Handle::UNDEFINED;\n\t\t_body = _outgoing[0];\n\t\t_values = _outgoing[1];\n\t}\n\telse\n\t\t_values = _outgoing[2];\n\n\tstatic_typecheck_values();\n}\n\n\n\/\/\/ Check that the values in the PutLink obey the type constraints.\n\/\/\/ This only performs \"static\" typechecking, at construction-time;\n\/\/\/ since the values may be dynamically obtained at run-time, we cannot\n\/\/\/ check these here.\nvoid PutLink::static_typecheck_values(void)\n{\n\t\/\/ Cannot typecheck at this pont in time, because the schema\n\t\/\/ might not be defined yet...\n\tType btype = _body->get_type();\n\tif (DEFINED_SCHEMA_NODE == btype)\n\t\treturn;\n\tif (DEFINED_PREDICATE_NODE == btype)\n\t\treturn;\n\n\t\/\/ If its part of a signature, there is nothing to do.\n\tif (classserver().isA(btype, TYPE_NODE) or TYPE_CHOICE == btype)\n\t\treturn;\n\n\tsize_t sz = _varlist.varseq.size();\n\tType vtype = _values->get_type();\n\n\tif (1 == sz)\n\t{\n\t\tif (not _varlist.is_type(_values)\n\t\t and SET_LINK != vtype\n\t\t and PUT_LINK != vtype\n\t\t and not (classserver().isA(vtype, SATISFYING_LINK)))\n\t\t{\n\t\t\t\tthrow InvalidParamException(TRACE_INFO,\n\t\t\t\t\t\"PutLink mismatched type!\");\n\t\t}\n\t\treturn;\n\t}\n\n\t\/\/ Cannot typecheck naked FunctionLinks. For example:\n\t\/\/ (cog-execute! (Put (Plus) (List (Number 2) (Number 2))))\n\tif (0 == sz and classserver().isA(btype, FUNCTION_LINK))\n\t\treturn;\n\n\t\/\/ The standard, default case is to get a ListLink as an argument.\n\tif (LIST_LINK == vtype)\n\t{\n\t\tif (not _varlist.is_type(_values->getOutgoingSet()))\n\t\t{\n\t\t\tif (_vardecl)\n\t\t\t\tthrow SyntaxException(TRACE_INFO,\n\t\t\t\t\t\"PutLink has mismatched value list! vardecl=%s\\nvals=%s\",\n\t\t\t\t\t_vardecl->to_string().c_str(),\n\t\t\t\t\t_values->to_string().c_str());\n\t\t\telse\n\t\t\t\tthrow SyntaxException(TRACE_INFO,\n\t\t\t\t\t\"PutLink has mismatched value list! body=%s\\nvals=%s\",\n\t\t\t\t\t_body->to_string().c_str(),\n\t\t\t\t\t_values->to_string().c_str());\n\t\t}\n\t\treturn;\n\t}\n\n\t\/\/ GetLinks (and the like) are evaluated dynamically, later.\n\tif (classserver().isA(vtype, SATISFYING_LINK))\n\t\treturn;\n\n\t\/\/ If its part of a signature, there is nothing to do.\n\tif (TYPE_NODE == vtype or TYPE_CHOICE == vtype)\n\t\treturn;\n\n\t\/\/ The only remaining possibility is that there is set of ListLinks.\n\tif (SET_LINK != vtype)\n\t\tthrow InvalidParamException(TRACE_INFO,\n\t\t\t\"PutLink was expecting a ListLink, SetLink or GetLink!\");\n\n\tif (1 < sz)\n\t{\n\t\tfor (const Handle& h : _values->getOutgoingSet())\n\t\t{\n\t\t\t\/\/ If the arity is greater than one, then the values must be in a list.\n\t\t if (h->get_type() != LIST_LINK)\n\t\t\t\tthrow InvalidParamException(TRACE_INFO,\n\t\t\t\t\t\"PutLink expected value list!\");\n\n\t\t\tif (not _varlist.is_type(h->getOutgoingSet()))\n\t\t\t\tthrow InvalidParamException(TRACE_INFO,\n\t\t\t\t\t\"PutLink bad value list!\");\n\t\t}\n\t\treturn;\n\t}\n\n\t\/\/ If the arity is one, the values must obey type constraint.\n\tfor (const Handle& h : _values->getOutgoingSet())\n\t{\n\t\tif (not _varlist.is_type(h))\n\t\t\tthrow InvalidParamException(TRACE_INFO,\n\t\t\t\t\t\"PutLink bad type!\");\n\t}\n}\n\n\/* ================================================================= *\/\n\nstatic inline Handle reddy(RewriteLinkPtr subs, const HandleSeq& oset)\n{\n\tsubs->make_silent(true);\n\treturn subs->beta_reduce(oset);\n}\n\n\/**\n * Perform the actual beta reduction --\n *\n * Substitute values for the variables in the pattern tree.\n * This is a lot like applying the function fun to the argument list\n * args, except that no actual evaluation is performed; only\n * substitution. The resulting tree is NOT placed into any atomspace,\n * either. If you want that, you must do it youself. If you want\n * evaluation or execution to happen during or after sustitution, use\n * either the EvaluationLink, the ExecutionOutputLink, or the Instantiator.\n *\n * So, for example, if this PutLink looks like this:\n *\n * PutLink\n * EvaluationLink\n * PredicateNode \"is a kind of\"\n * ListLink\n * VariableNode $a\n * ConceptNode \"hot patootie\"\n * ConceptNode \"cowpie\"\n *\n * then the reduced value will be\n *\n * EvaluationLink\n * PredicateNode \"is a kind of\"\n * ListLink\n * ConceptNode \"cowpie\"\n * ConceptNode \"hot patootie\"\n *\n * Type checking is performed during substitution; if the values fail to\n * have the desired types, no substitution is performed. In this case,\n * an undefined handle is returned. For set substitutions, this acts as\n * a filter, removing (filtering out) the mismatched types.\n *\n * Again, only a substitution is performed, there is no execution or\n * evaluation. Note also that the resulting tree is NOT placed into\n * any atomspace!\n *\/\nHandle PutLink::do_reduce(void) const\n{\n\tHandle bods(_body);\n\tVariables vars(_varlist);\n\tRewriteLinkPtr subs(RewriteLinkCast(get_handle()));\n\n\t\/\/ Resolve the body, if needed. That is, if the body is\n\t\/\/ given in a defintion, get that defintion.\n\tType btype = _body->get_type();\n\tif (DEFINED_SCHEMA_NODE == btype or\n\t DEFINED_PREDICATE_NODE == btype)\n\t{\n\t\tbods = DefineLink::get_definition(bods);\n\t\tbtype = bods->get_type();\n\t\t\/\/ XXX TODO we should perform a type-check on the function.\n\t\tif (not classserver().isA(btype, LAMBDA_LINK))\n\t\t\tthrow InvalidParamException(TRACE_INFO,\n\t\t\t\t\t\"Expecting a LambdaLink, got %s\",\n\t\t\t bods->to_string().c_str());\n\t}\n\n\t\/\/ If the body is a lambda, work with that.\n\tif (classserver().isA(btype, LAMBDA_LINK))\n\t{\n\t\tLambdaLinkPtr lam(LambdaLinkCast(bods));\n\t\tbods = lam->get_body();\n\t\tvars = lam->get_variables();\n\t\tbtype = bods->get_type();\n\t\tsubs = lam;\n\t}\n\n\t\/\/ Now get the values that we will plug into the body.\n\tType vtype = _values->get_type();\n\n\tsize_t nvars = vars.varseq.size();\n\n\t\/\/ FunctionLinks behave like combinators; that is, one can create\n\t\/\/ valid beta-redexes with them. We handle that here.\n\t\/\/\n\t\/\/ XXX At this time, we don't know the number of arguments any\n\t\/\/ given FunctionLink might take. Atomese does have the mechanisms\n\t\/\/ to declare these, including arbitrary-arity functions, its\n\t\/\/ just that its currently not declared anywhere for any of the\n\t\/\/ FunctionLinks. So we just punt. Example usage:\n\t\/\/ (cog-execute! (Put (Plus) (List (Number 2) (Number 2))))\n\t\/\/ (cog-execute! (Put (Plus (Number 9)) (List (Number 2) (Number 2))))\n\tif (0 == nvars and classserver().isA(btype, FUNCTION_LINK))\n\t{\n\t\tif (LIST_LINK == vtype)\n\t\t{\n\t\t\tHandleSeq oset(bods->getOutgoingSet());\n\t\t\tconst HandleSeq& rest = _values->getOutgoingSet();\n\t\t\toset.insert(oset.end(), rest.begin(), rest.end());\n\t\t\treturn createLink(oset, btype);\n\t\t}\n\n\t\tif (SET_LINK != vtype)\n\t\t{\n\t\t\tHandleSeq oset(bods->getOutgoingSet());\n\t\t\toset.emplace_back(_values);\n\t\t\treturn createLink(oset, btype);\n\t\t}\n\n\t\t\/\/ If the values are given in a set, then iterate over the set...\n\t\tHandleSeq bset;\n\t\tfor (const Handle& h : _values->getOutgoingSet())\n\t\t{\n\t\t\tif (LIST_LINK == h->get_type())\n\t\t\t{\n\t\t\t\tHandleSeq oset(bods->getOutgoingSet());\n\t\t\t\tconst HandleSeq& rest = h->getOutgoingSet();\n\t\t\t\toset.insert(oset.end(), rest.begin(), rest.end());\n\t\t\t\tbset.emplace_back(createLink(oset, btype));\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tHandleSeq oset(bods->getOutgoingSet());\n\t\t\t\toset.emplace_back(h);\n\t\t\t\tbset.emplace_back(createLink(oset, btype));\n\t\t\t}\n\t\t}\n\t\treturn createLink(bset, SET_LINK);\n\t}\n\n\t\/\/ If there is only one variable in the PutLink body...\n\tif (1 == nvars)\n\t{\n\t\tif (SET_LINK != vtype)\n\t\t{\n\t\t\tHandleSeq oset;\n\t\t\toset.emplace_back(_values);\n\t\t\ttry\n\t\t\t{\n\t\t\t\t\/\/ return vars.substitute(bods, oset, \/* silent *\/ true);\n\t\t\t\treturn reddy(subs, oset);\n\t\t\t}\n\t\t\tcatch (const TypeCheckException& ex)\n\t\t\t{\n\t\t\t\treturn Handle::UNDEFINED;\n\t\t\t}\n\t\t}\n\n\t\t\/\/ If the values are given in a set, then iterate over the set...\n\t\tHandleSeq bset;\n\t\tfor (const Handle& h : _values->getOutgoingSet())\n\t\t{\n\t\t\tHandleSeq oset;\n\t\t\toset.emplace_back(h);\n\t\t\ttry\n\t\t\t{\n\t\t\t\t\/\/ bset.emplace_back(vars.substitute(bods, oset, \/* silent *\/ true));\n\t\t\t\tbset.emplace_back(reddy(subs, oset));\n\t\t\t}\n\t\t\tcatch (const TypeCheckException& ex) {}\n\t\t}\n\t\treturn createLink(bset, SET_LINK);\n\t}\n\n\t\/\/ If we are here, then there are multiple variables in the body.\n\t\/\/ See how many values there are. If the values are a ListLink,\n\t\/\/ then assume that there is only a single set of values to plug in.\n\tif (LIST_LINK == vtype)\n\t{\n\t\tconst HandleSeq& oset = _values->getOutgoingSet();\n\t\ttry\n\t\t{\n\t\t\t\/\/ return vars.substitute(bods, oset, \/* silent *\/ true);\n\t\t\treturn reddy(subs, oset);\n\t\t}\n\t\tcatch (const TypeCheckException& ex)\n\t\t{\n\t\t\treturn Handle::UNDEFINED;\n\t\t}\n\t}\n\n\t\/\/ If we are here, then there are multiple values.\n\t\/\/ These MUST be given to us as a SetLink.\n\tOC_ASSERT(SET_LINK == vtype,\n\t\t\"Should have caught this earlier, in the ctor\");\n\n\tHandleSeq bset;\n\tfor (const Handle& h : _values->getOutgoingSet())\n\t{\n\t\tconst HandleSeq& oset = h->getOutgoingSet();\n\t\ttry\n\t\t{\n\t\t\t\/\/ bset.emplace_back(vars.substitute(bods, oset, \/* silent *\/ true));\n\t\t\tbset.emplace_back(reddy(subs, oset));\n\t\t}\n\t\tcatch (const TypeCheckException& ex) {}\n\t}\n\treturn createLink(bset, SET_LINK);\n}\n\nHandle PutLink::reduce(void)\n{\n\treturn do_reduce();\n}\n\nDEFINE_LINK_FACTORY(PutLink, PUT_LINK)\n\n\/* ===================== END OF FILE ===================== *\/\n<commit_msg>support eta conversion<commit_after>\/*\n * opencog\/atoms\/core\/PutLink.cc\n *\n * Copyright (C) 2015 Linas Vepstas\n * All Rights Reserved\n *\n * This program is free software; you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License v3 as\n * published by the Free Software Foundation and including the exceptions\n * at http:\/\/opencog.org\/wiki\/Licenses\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public License\n * along with this program; if not, write to:\n * Free Software Foundation, Inc.,\n * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.\n *\/\n\n#include <opencog\/atoms\/base\/atom_types.h>\n#include <opencog\/atoms\/base\/ClassServer.h>\n#include \"DefineLink.h\"\n#include \"FreeLink.h\"\n#include \"LambdaLink.h\"\n#include \"PutLink.h\"\n\nusing namespace opencog;\n\nPutLink::PutLink(const HandleSeq& oset, Type t)\n : RewriteLink(oset, t)\n{\n\tinit();\n}\n\nPutLink::PutLink(const Link& l)\n : RewriteLink(l)\n{\n\tinit();\n}\n\n\/* ================================================================= *\/\n\n\/\/\/ PutLink expects a very strict format: an arity-2 link, with\n\/\/\/ the first part being a pattern, and the second a list or set\n\/\/\/ of values. If the pattern has N variables, then the seccond\n\/\/\/ part must have N values. Furthermore, any type restrictions on\n\/\/\/ the variables must be satisfied by the values.\n\/\/\/\n\/\/\/ The following formats are understood:\n\/\/\/\n\/\/\/ PutLink\n\/\/\/ <pattern with 1 variable>\n\/\/\/ <any single atom>\n\/\/\/\n\/\/\/ PutLink\n\/\/\/ <pattern with N variables>\n\/\/\/ ListLink ;; must have arity N\n\/\/\/ <atom 1>\n\/\/\/ ...\n\/\/\/ <atom N>\n\/\/\/\n\/\/\/ The below is a handy-dandy easy-to-use form. When it is reduced,\n\/\/\/ it will result in the creation of a set of reduced forms, not\n\/\/\/ just one (the two sets haveing the same arity). Unfortunately,\n\/\/\/ this trick cannot work for N=1 unless the variable is cosntrained\n\/\/\/ to not be a set.\n\/\/\/\n\/\/\/ PutLink\n\/\/\/ <pattern with N variables>\n\/\/\/ SetLink ;; Must hold a set of ListLinks\n\/\/\/ ListLink ;; must have arity N\n\/\/\/ <atom 1>\n\/\/\/ ...\n\/\/\/ <atom N>\n\/\/\/\nvoid PutLink::init(void)\n{\n\tif (not classserver().isA(get_type(), PUT_LINK))\n\t\tthrow InvalidParamException(TRACE_INFO, \"Expecting a PutLink\");\n\n\tsize_t sz = _outgoing.size();\n\tif (2 != sz and 3 != sz)\n\t\tthrow InvalidParamException(TRACE_INFO,\n\t\t\t\"Expecting an outgoing set size of two or three, got %d; %s\",\n\t\t\tsz, to_string().c_str());\n\n\tScopeLink::extract_variables(_outgoing);\n\n\tif (2 == sz)\n\t{\n\t\t\/\/ If the body is just a single variable, and there are no\n\t\t\/\/ type declarations for it, then ScopeLink gets confused.\n\t\t_vardecl = Handle::UNDEFINED;\n\t\t_body = _outgoing[0];\n\t\t_values = _outgoing[1];\n\t}\n\telse\n\t\t_values = _outgoing[2];\n\n\tstatic_typecheck_values();\n}\n\n\n\/\/\/ Check that the values in the PutLink obey the type constraints.\n\/\/\/ This only performs \"static\" typechecking, at construction-time;\n\/\/\/ since the values may be dynamically obtained at run-time, we cannot\n\/\/\/ check these here.\nvoid PutLink::static_typecheck_values(void)\n{\n\t\/\/ Cannot typecheck at this pont in time, because the schema\n\t\/\/ might not be defined yet...\n\tType btype = _body->get_type();\n\tif (DEFINED_SCHEMA_NODE == btype)\n\t\treturn;\n\tif (DEFINED_PREDICATE_NODE == btype)\n\t\treturn;\n\n\t\/\/ If its part of a signature, there is nothing to do.\n\tif (classserver().isA(btype, TYPE_NODE) or TYPE_CHOICE == btype)\n\t\treturn;\n\n\tsize_t sz = _varlist.varseq.size();\n\n\tHandle valley = _values;\n\tType vtype = valley->get_type();\n\n\t\/\/ If its a LambdaLink, try to see if its eta-reducible. If\n\t\/\/ so, then eta-reduce it immediately. A LambdaLink is\n\t\/\/ eta-reducible when it's body is a ListLink.\n\tif (LAMBDA_LINK == vtype)\n\t{\n\t\tLambdaLinkPtr lam(LambdaLinkCast(_values));\n\t\tHandle body = lam->get_body();\n\t\tType bt = body->get_type();\n\t\tif (LIST_LINK == bt)\n\t\t{\n\t\t\tvalley = body;\n\t\t\tvtype = bt;\n\t\t}\n\t}\n\n\tif (1 == sz)\n\t{\n\t\tif (not _varlist.is_type(valley)\n\t\t and SET_LINK != vtype\n\t\t and PUT_LINK != vtype\n\t\t and not (classserver().isA(vtype, SATISFYING_LINK)))\n\t\t{\n\t\t\t\tthrow InvalidParamException(TRACE_INFO,\n\t\t\t\t\t\"PutLink mismatched type!\");\n\t\t}\n\t\treturn;\n\t}\n\n\t\/\/ Cannot typecheck naked FunctionLinks. For example:\n\t\/\/ (cog-execute! (Put (Plus) (List (Number 2) (Number 2))))\n\tif (0 == sz and classserver().isA(btype, FUNCTION_LINK))\n\t\treturn;\n\n\t\/\/ The standard, default case is to get a ListLink as an argument.\n\tif (LIST_LINK == vtype)\n\t{\n\t\tif (not _varlist.is_type(valley->getOutgoingSet()))\n\t\t{\n\t\t\tif (_vardecl)\n\t\t\t\tthrow SyntaxException(TRACE_INFO,\n\t\t\t\t\t\"PutLink has mismatched value list! vardecl=%s\\nvals=%s\",\n\t\t\t\t\t_vardecl->to_string().c_str(),\n\t\t\t\t\t_values->to_string().c_str());\n\t\t\telse\n\t\t\t\tthrow SyntaxException(TRACE_INFO,\n\t\t\t\t\t\"PutLink has mismatched value list! body=%s\\nvals=%s\",\n\t\t\t\t\t_body->to_string().c_str(),\n\t\t\t\t\t_values->to_string().c_str());\n\t\t}\n\t\treturn;\n\t}\n\n\t\/\/ GetLinks (and the like) are evaluated dynamically, later.\n\tif (classserver().isA(vtype, SATISFYING_LINK))\n\t\treturn;\n\n\t\/\/ If its part of a signature, there is nothing to do.\n\tif (TYPE_NODE == vtype or TYPE_CHOICE == vtype)\n\t\treturn;\n\n\t\/\/ The only remaining possibility is that there is set of ListLinks.\n\tif (SET_LINK != vtype)\n\t\tthrow InvalidParamException(TRACE_INFO,\n\t\t\t\"PutLink was expecting a ListLink, SetLink or GetLink!\");\n\n\tif (1 < sz)\n\t{\n\t\tfor (const Handle& h : valley->getOutgoingSet())\n\t\t{\n\t\t\t\/\/ If the arity is greater than one, then the values must be in a list.\n\t\t if (h->get_type() != LIST_LINK)\n\t\t\t\tthrow InvalidParamException(TRACE_INFO,\n\t\t\t\t\t\"PutLink expected value list!\");\n\n\t\t\tif (not _varlist.is_type(h->getOutgoingSet()))\n\t\t\t\tthrow InvalidParamException(TRACE_INFO,\n\t\t\t\t\t\"PutLink bad value list!\");\n\t\t}\n\t\treturn;\n\t}\n\n\t\/\/ If the arity is one, the values must obey type constraint.\n\tfor (const Handle& h : valley->getOutgoingSet())\n\t{\n\t\tif (not _varlist.is_type(h))\n\t\t\tthrow InvalidParamException(TRACE_INFO,\n\t\t\t\t\t\"PutLink bad type!\");\n\t}\n}\n\n\/* ================================================================= *\/\n\nstatic inline Handle reddy(RewriteLinkPtr subs, const HandleSeq& oset)\n{\n\tsubs->make_silent(true);\n\treturn subs->beta_reduce(oset);\n}\n\n\/**\n * Perform the actual beta reduction --\n *\n * Substitute values for the variables in the pattern tree.\n * This is a lot like applying the function fun to the argument list\n * args, except that no actual evaluation is performed; only\n * substitution. The resulting tree is NOT placed into any atomspace,\n * either. If you want that, you must do it youself. If you want\n * evaluation or execution to happen during or after sustitution, use\n * either the EvaluationLink, the ExecutionOutputLink, or the Instantiator.\n *\n * So, for example, if this PutLink looks like this:\n *\n * PutLink\n * EvaluationLink\n * PredicateNode \"is a kind of\"\n * ListLink\n * VariableNode $a\n * ConceptNode \"hot patootie\"\n * ConceptNode \"cowpie\"\n *\n * then the reduced value will be\n *\n * EvaluationLink\n * PredicateNode \"is a kind of\"\n * ListLink\n * ConceptNode \"cowpie\"\n * ConceptNode \"hot patootie\"\n *\n * Type checking is performed during substitution; if the values fail to\n * have the desired types, no substitution is performed. In this case,\n * an undefined handle is returned. For set substitutions, this acts as\n * a filter, removing (filtering out) the mismatched types.\n *\n * Again, only a substitution is performed, there is no execution or\n * evaluation. Note also that the resulting tree is NOT placed into\n * any atomspace!\n *\/\nHandle PutLink::do_reduce(void) const\n{\n\tHandle bods(_body);\n\tVariables vars(_varlist);\n\tRewriteLinkPtr subs(RewriteLinkCast(get_handle()));\n\n\t\/\/ Resolve the body, if needed. That is, if the body is\n\t\/\/ given in a defintion, get that defintion.\n\tType btype = _body->get_type();\n\tif (DEFINED_SCHEMA_NODE == btype or\n\t DEFINED_PREDICATE_NODE == btype)\n\t{\n\t\tbods = DefineLink::get_definition(bods);\n\t\tbtype = bods->get_type();\n\t\t\/\/ XXX TODO we should perform a type-check on the function.\n\t\tif (not classserver().isA(btype, LAMBDA_LINK))\n\t\t\tthrow InvalidParamException(TRACE_INFO,\n\t\t\t\t\t\"Expecting a LambdaLink, got %s\",\n\t\t\t bods->to_string().c_str());\n\t}\n\n\t\/\/ If the body is a lambda, work with that.\n\tif (classserver().isA(btype, LAMBDA_LINK))\n\t{\n\t\tLambdaLinkPtr lam(LambdaLinkCast(bods));\n\t\tbods = lam->get_body();\n\t\tvars = lam->get_variables();\n\t\tbtype = bods->get_type();\n\t\tsubs = lam;\n\t}\n\n\t\/\/ Now get the values that we will plug into the body.\n\tHandle valley = _values;\n\tType vtype = valley->get_type();\n\n\t\/\/ If the value is a LambdaLink, try to see if its eta-reducible.\n\t\/\/ If so, then eta-reduce it immediately. A LambdaLink is\n\t\/\/ eta-reducible when it's body is a ListLink.\n\tif (LAMBDA_LINK == vtype)\n\t{\n\t\tLambdaLinkPtr lam(LambdaLinkCast(_values));\n\t\tHandle eta = lam->get_body();\n\t\tType bt = eta->get_type();\n\t\tif (LIST_LINK == bt)\n\t\t{\n\t\t\tvalley = eta;\n\t\t\tvtype = bt;\n\t\t}\n\t}\n\n\tsize_t nvars = vars.varseq.size();\n\n\t\/\/ FunctionLinks behave like combinators; that is, one can create\n\t\/\/ valid beta-redexes with them. We handle that here.\n\t\/\/\n\t\/\/ XXX At this time, we don't know the number of arguments any\n\t\/\/ given FunctionLink might take. Atomese does have the mechanisms\n\t\/\/ to declare these, including arbitrary-arity functions, its\n\t\/\/ just that its currently not declared anywhere for any of the\n\t\/\/ FunctionLinks. So we just punt. Example usage:\n\t\/\/ (cog-execute! (Put (Plus) (List (Number 2) (Number 2))))\n\t\/\/ (cog-execute! (Put (Plus (Number 9)) (List (Number 2) (Number 2))))\n\tif (0 == nvars and classserver().isA(btype, FUNCTION_LINK))\n\t{\n\t\tif (LIST_LINK == vtype)\n\t\t{\n\t\t\tHandleSeq oset(bods->getOutgoingSet());\n\t\t\tconst HandleSeq& rest = valley->getOutgoingSet();\n\t\t\toset.insert(oset.end(), rest.begin(), rest.end());\n\t\t\treturn createLink(oset, btype);\n\t\t}\n\n\t\tif (SET_LINK != vtype)\n\t\t{\n\t\t\tHandleSeq oset(bods->getOutgoingSet());\n\t\t\toset.emplace_back(valley);\n\t\t\treturn createLink(oset, btype);\n\t\t}\n\n\t\t\/\/ If the values are given in a set, then iterate over the set...\n\t\tHandleSeq bset;\n\t\tfor (const Handle& h : valley->getOutgoingSet())\n\t\t{\n\t\t\tif (LIST_LINK == h->get_type())\n\t\t\t{\n\t\t\t\tHandleSeq oset(bods->getOutgoingSet());\n\t\t\t\tconst HandleSeq& rest = h->getOutgoingSet();\n\t\t\t\toset.insert(oset.end(), rest.begin(), rest.end());\n\t\t\t\tbset.emplace_back(createLink(oset, btype));\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tHandleSeq oset(bods->getOutgoingSet());\n\t\t\t\toset.emplace_back(h);\n\t\t\t\tbset.emplace_back(createLink(oset, btype));\n\t\t\t}\n\t\t}\n\t\treturn createLink(bset, SET_LINK);\n\t}\n\n\t\/\/ If there is only one variable in the PutLink body...\n\tif (1 == nvars)\n\t{\n\t\tif (SET_LINK != vtype)\n\t\t{\n\t\t\tHandleSeq oset;\n\t\t\toset.emplace_back(valley);\n\t\t\ttry\n\t\t\t{\n\t\t\t\t\/\/ return vars.substitute(bods, oset, \/* silent *\/ true);\n\t\t\t\treturn reddy(subs, oset);\n\t\t\t}\n\t\t\tcatch (const TypeCheckException& ex)\n\t\t\t{\n\t\t\t\treturn Handle::UNDEFINED;\n\t\t\t}\n\t\t}\n\n\t\t\/\/ If the values are given in a set, then iterate over the set...\n\t\tHandleSeq bset;\n\t\tfor (const Handle& h : valley->getOutgoingSet())\n\t\t{\n\t\t\tHandleSeq oset;\n\t\t\toset.emplace_back(h);\n\t\t\ttry\n\t\t\t{\n\t\t\t\t\/\/ bset.emplace_back(vars.substitute(bods, oset, \/* silent *\/ true));\n\t\t\t\tbset.emplace_back(reddy(subs, oset));\n\t\t\t}\n\t\t\tcatch (const TypeCheckException& ex) {}\n\t\t}\n\t\treturn createLink(bset, SET_LINK);\n\t}\n\n\t\/\/ If we are here, then there are multiple variables in the body.\n\t\/\/ See how many values there are. If the values are a ListLink,\n\t\/\/ then assume that there is only a single set of values to plug in.\n\tif (LIST_LINK == vtype)\n\t{\n\t\tconst HandleSeq& oset = valley->getOutgoingSet();\n\t\ttry\n\t\t{\n\t\t\t\/\/ return vars.substitute(bods, oset, \/* silent *\/ true);\n\t\t\treturn reddy(subs, oset);\n\t\t}\n\t\tcatch (const TypeCheckException& ex)\n\t\t{\n\t\t\treturn Handle::UNDEFINED;\n\t\t}\n\t}\n\n\t\/\/ If we are here, then there are multiple values.\n\t\/\/ These MUST be given to us as a SetLink.\n\tOC_ASSERT(SET_LINK == vtype,\n\t\t\"Should have caught this earlier, in the ctor\");\n\n\tHandleSeq bset;\n\tfor (const Handle& h : valley->getOutgoingSet())\n\t{\n\t\tconst HandleSeq& oset = h->getOutgoingSet();\n\t\ttry\n\t\t{\n\t\t\t\/\/ bset.emplace_back(vars.substitute(bods, oset, \/* silent *\/ true));\n\t\t\tbset.emplace_back(reddy(subs, oset));\n\t\t}\n\t\tcatch (const TypeCheckException& ex) {}\n\t}\n\treturn createLink(bset, SET_LINK);\n}\n\nHandle PutLink::reduce(void)\n{\n\treturn do_reduce();\n}\n\nDEFINE_LINK_FACTORY(PutLink, PUT_LINK)\n\n\/* ===================== END OF FILE ===================== *\/\n<|endoftext|>"} {"text":"<commit_before>\/******************************************************************************\n* SOFA, Simulation Open-Framework Architecture, version 1.0 beta 4 *\n* (c) 2006-2009 MGH, INRIA, USTL, UJF, CNRS *\n* *\n* This library is free software; you can redistribute it and\/or modify it *\n* under the terms of the GNU Lesser General Public License as published by *\n* the Free Software Foundation; either version 2.1 of the License, or (at *\n* your option) any later version. *\n* *\n* This library is distributed in the hope that it will be useful, but WITHOUT *\n* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or *\n* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License *\n* for more details. *\n* *\n* You should have received a copy of the GNU Lesser General Public License *\n* along with this library; if not, write to the Free Software Foundation, *\n* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. *\n*******************************************************************************\n* SOFA :: Modules *\n* *\n* Authors: The SOFA Team and external contributors (see Authors.txt) *\n* *\n* Contact information: contact@sofa-framework.org *\n******************************************************************************\/\n#include <sofa\/helper\/system\/config.h>\n#include <sofa\/component\/initComponentMisc.h>\n\n\nnamespace sofa\n{\n\nnamespace component\n{\n\n\nvoid initComponentMisc()\n{\n static bool first = true;\n if (first)\n {\n first = false;\n }\n}\n\n\/\/SOFA_LINK_CLASS(ParallelCollisionPipeline)\n\/\/SOFA_LINK_CLASS(TriangleModelInRegularGrid)\n\/\/SOFA_LINK_CLASS(ContinuousTriangleIntersection)\n\/\/SOFA_LINK_CLASS(RigidContactMapper)\n\/\/SOFA_LINK_CLASS(RuleBasedContactMapper)\nSOFA_LINK_CLASS(DiscreteBeamBsplineMapping)\nSOFA_LINK_CLASS(TreeCollisionGroupManager)\nSOFA_LINK_CLASS(MatrixMass)\nSOFA_LINK_CLASS(MeshMatrixMass)\nSOFA_LINK_CLASS(FastTetrahedralCorotationalForceField)\nSOFA_LINK_CLASS(LennardJonesForceField)\nSOFA_LINK_CLASS(TetrahedralTensorMassForceField)\nSOFA_LINK_CLASS(WashingMachineForceField)\nSOFA_LINK_CLASS(BeamLinearMapping)\nSOFA_LINK_CLASS(CenterPointMechanicalMapping)\nSOFA_LINK_CLASS(CenterOfMassMapping)\nSOFA_LINK_CLASS(CenterOfMassMultiMapping)\nSOFA_LINK_CLASS(CenterOfMassMulti2Mapping)\nSOFA_LINK_CLASS(CurveMapping)\nSOFA_LINK_CLASS(ExternalInterpolationMapping)\nSOFA_LINK_CLASS(SubsetMultiMapping)\nSOFA_LINK_CLASS(TubularMapping)\nSOFA_LINK_CLASS(VoidMapping)\nSOFA_LINK_CLASS(Distances)\nSOFA_LINK_CLASS(ManifoldEdgeSetGeometryAlgorithms)\nSOFA_LINK_CLASS(ManifoldEdgeSetTopologyAlgorithms)\nSOFA_LINK_CLASS(ManifoldEdgeSetTopologyContainer)\nSOFA_LINK_CLASS(ManifoldEdgeSetTopologyModifier)\nSOFA_LINK_CLASS(ManifoldTriangleSetTopologyContainer)\nSOFA_LINK_CLASS(ManifoldTriangleSetTopologyModifier)\nSOFA_LINK_CLASS(ManifoldTriangleSetTopologyAlgorithms)\n\/\/SOFA_LINK_CLASS(ManifoldTetrahedronSetTopologyContainer)\n\/\/SOFA_LINK_CLASS(IndexedMapTopology)\nSOFA_LINK_CLASS(MeshTetraStuffing)\nSOFA_LINK_CLASS(TopologicalChangeProcessor)\n\/\/SOFA_LINK_CLASS(Triplet)\n\/\/SOFA_LINK_CLASS(SubdivisionCell)\n\/\/SOFA_LINK_CLASS(TopologyChangeTest)\n\/\/SOFA_LINK_CLASS(BoundingBox)\n\/\/SOFA_LINK_CLASS(TagRule)\n\/\/SOFA_LINK_CLASS(ParallelCGLinearSolver)\n\/\/SOFA_LINK_CLASS(DampVelocitySolver)\nSOFA_LINK_CLASS(NewmarkImplicitSolver)\n\n#ifdef SOFA_DEV\nSOFA_LINK_CLASS(ContinuousIntersection)\nSOFA_LINK_CLASS(TestDetection)\nSOFA_LINK_CLASS(BarycentricStickContact)\nSOFA_LINK_CLASS(BglCollisionGroupManager)\nSOFA_LINK_CLASS(ArborisDescription)\nSOFA_LINK_CLASS(ShapeMatchingForceField)\nSOFA_LINK_CLASS(VectorField)\nSOFA_LINK_CLASS(ArborisMapping)\nSOFA_LINK_CLASS(CircumcenterMapping)\nSOFA_LINK_CLASS(DeformableOnRigidFrameMapping)\nSOFA_LINK_CLASS(PCAOnRigidFrameMapping)\nSOFA_LINK_CLASS(Triangle2DFEMForceField)\nSOFA_LINK_CLASS(TriangleBendingFEMForceField)\nSOFA_LINK_CLASS(FluidSolidInteractionForceField)\nSOFA_LINK_CLASS(DistanceOnGrid)\nSOFA_LINK_CLASS(Edge2TetraTopologicalMapping)\nSOFA_LINK_CLASS(TriangleSubdivisionTopologicalMapping)\nSOFA_LINK_CLASS(SpringIt)\nSOFA_LINK_CLASS(GraphScenePartionner)\nSOFA_LINK_CLASS(MappedBeamToTetraForceField)\nSOFA_LINK_CLASS(FlowVisualModel)\nSOFA_LINK_CLASS(NewtonEulerImplicit)\n#endif\n\n} \/\/ namespace component\n\n} \/\/ namespace sofa\n<commit_msg>r11157\/sofa-dev : CHANGE: desactive components: FluidSolidInteractionForceField, FlowVisualModel and VectorField for the moment as manifold topologies are going to be moved in a plugin.<commit_after>\/******************************************************************************\n* SOFA, Simulation Open-Framework Architecture, version 1.0 beta 4 *\n* (c) 2006-2009 MGH, INRIA, USTL, UJF, CNRS *\n* *\n* This library is free software; you can redistribute it and\/or modify it *\n* under the terms of the GNU Lesser General Public License as published by *\n* the Free Software Foundation; either version 2.1 of the License, or (at *\n* your option) any later version. *\n* *\n* This library is distributed in the hope that it will be useful, but WITHOUT *\n* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or *\n* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License *\n* for more details. *\n* *\n* You should have received a copy of the GNU Lesser General Public License *\n* along with this library; if not, write to the Free Software Foundation, *\n* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. *\n*******************************************************************************\n* SOFA :: Modules *\n* *\n* Authors: The SOFA Team and external contributors (see Authors.txt) *\n* *\n* Contact information: contact@sofa-framework.org *\n******************************************************************************\/\n#include <sofa\/helper\/system\/config.h>\n#include <sofa\/component\/initComponentMisc.h>\n\n\nnamespace sofa\n{\n\nnamespace component\n{\n\n\nvoid initComponentMisc()\n{\n static bool first = true;\n if (first)\n {\n first = false;\n }\n}\n\n\/\/SOFA_LINK_CLASS(ParallelCollisionPipeline)\n\/\/SOFA_LINK_CLASS(TriangleModelInRegularGrid)\n\/\/SOFA_LINK_CLASS(ContinuousTriangleIntersection)\n\/\/SOFA_LINK_CLASS(RigidContactMapper)\n\/\/SOFA_LINK_CLASS(RuleBasedContactMapper)\nSOFA_LINK_CLASS(DiscreteBeamBsplineMapping)\nSOFA_LINK_CLASS(TreeCollisionGroupManager)\nSOFA_LINK_CLASS(MatrixMass)\nSOFA_LINK_CLASS(MeshMatrixMass)\nSOFA_LINK_CLASS(FastTetrahedralCorotationalForceField)\nSOFA_LINK_CLASS(LennardJonesForceField)\nSOFA_LINK_CLASS(TetrahedralTensorMassForceField)\nSOFA_LINK_CLASS(WashingMachineForceField)\nSOFA_LINK_CLASS(BeamLinearMapping)\nSOFA_LINK_CLASS(CenterPointMechanicalMapping)\nSOFA_LINK_CLASS(CenterOfMassMapping)\nSOFA_LINK_CLASS(CenterOfMassMultiMapping)\nSOFA_LINK_CLASS(CenterOfMassMulti2Mapping)\nSOFA_LINK_CLASS(CurveMapping)\nSOFA_LINK_CLASS(ExternalInterpolationMapping)\nSOFA_LINK_CLASS(SubsetMultiMapping)\nSOFA_LINK_CLASS(TubularMapping)\nSOFA_LINK_CLASS(VoidMapping)\nSOFA_LINK_CLASS(Distances)\n\/\/SOFA_LINK_CLASS(IndexedMapTopology)\nSOFA_LINK_CLASS(MeshTetraStuffing)\nSOFA_LINK_CLASS(TopologicalChangeProcessor)\n\/\/SOFA_LINK_CLASS(Triplet)\n\/\/SOFA_LINK_CLASS(SubdivisionCell)\n\/\/SOFA_LINK_CLASS(TopologyChangeTest)\n\/\/SOFA_LINK_CLASS(BoundingBox)\n\/\/SOFA_LINK_CLASS(TagRule)\n\/\/SOFA_LINK_CLASS(ParallelCGLinearSolver)\n\/\/SOFA_LINK_CLASS(DampVelocitySolver)\nSOFA_LINK_CLASS(NewmarkImplicitSolver)\n\n#ifdef SOFA_DEV\nSOFA_LINK_CLASS(ContinuousIntersection)\nSOFA_LINK_CLASS(TestDetection)\nSOFA_LINK_CLASS(BarycentricStickContact)\nSOFA_LINK_CLASS(BglCollisionGroupManager)\nSOFA_LINK_CLASS(ArborisDescription)\nSOFA_LINK_CLASS(ShapeMatchingForceField)\n\/\/SOFA_LINK_CLASS(VectorField)\nSOFA_LINK_CLASS(ArborisMapping)\nSOFA_LINK_CLASS(CircumcenterMapping)\nSOFA_LINK_CLASS(DeformableOnRigidFrameMapping)\nSOFA_LINK_CLASS(PCAOnRigidFrameMapping)\nSOFA_LINK_CLASS(Triangle2DFEMForceField)\nSOFA_LINK_CLASS(TriangleBendingFEMForceField)\n\/\/SOFA_LINK_CLASS(FluidSolidInteractionForceField)\nSOFA_LINK_CLASS(DistanceOnGrid)\nSOFA_LINK_CLASS(Edge2TetraTopologicalMapping)\nSOFA_LINK_CLASS(TriangleSubdivisionTopologicalMapping)\nSOFA_LINK_CLASS(SpringIt)\nSOFA_LINK_CLASS(GraphScenePartionner)\nSOFA_LINK_CLASS(MappedBeamToTetraForceField)\n\/\/SOFA_LINK_CLASS(FlowVisualModel)\nSOFA_LINK_CLASS(NewtonEulerImplicit)\n#endif\n\n} \/\/ namespace component\n\n} \/\/ namespace sofa\n<|endoftext|>"} {"text":"<commit_before>\/* Bucky Frost\n * Paul Gentemann\n * CS 381\n * File Name : splinepatch.cpp\n * Last Modified : Sat 09 Nov 2013 11:46:15 PM AKST\n * Description : A pair of spline plains, patched together, that will\n * ripple upon user input.\n *\/\n\n\/\/ OpenGL\/GLUT includes - DO THESE FIRST\n#include <cstdlib> \/\/ Do this before GL\/GLUT includes\nusing std::exit;\n#ifndef __APPLE__\n# include <GL\/glew.h>\n# include <GL\/glut.h> \/\/ Includes OpenGL headers as well\n#else\n# include <GLEW\/glew.h>\n# include <GLUT\/glut.h> \/\/ Apple puts glut.h in a different place\n#endif\n#ifdef _MSC_VER \/\/ Tell MS-Visual Studio about GLEW lib\n# pragma comment(lib, \"glew32.lib\")\n#endif\n#include \"lib381\/bitmapprinter.h\"\n#include \"lib381\/glslprog.h\" \/\/ For GLSL code-handling functions\n#include <string>\nusing std::string;\n#include <iostream>\nusing std::cout; using std::cerr; using std::endl;\n#include <vector>\nusing std::vector;\n#include <sstream>\nusing std::ostringstream;\n#include <iomanip>\nusing std::setprecision;\nusing std::fixed;\n#include <cmath>\nusing std::sin;\n#include \"mouse.h\"\nMouse mousy = Mouse();\n\n\/\/ Function prototypes\nvoid documentation();\nvoid waveFun(int);\nvoid drawBezierPatch(int, double, GLdouble *);\nvoid myDisplay();\nvoid myIdle();\nvoid reset(GLdouble);\nvoid myKeyboard(unsigned char, int, int);\nvoid myPassiveMotion(int, int);\nvoid init();\nvoid myReshape(int, int);\nvoid set(GLdouble, GLdouble, GLdouble, GLdouble,\n GLdouble, GLdouble, GLdouble, GLdouble);\n\n\/\/ Global variables\nconst int ESCKEY = 27; \/\/ ASCII value of Escape\nconst int startwinsize = 600; \/\/ Start window width & height (pixels)\nint winw = 1, winh = 1; \/\/ Window width, height (pixels)\nbool help = false;\n\n\/\/ Shaders\nstring vshader1fname; \/\/ Filename for vertex shader source\nstring fshader1fname; \/\/ Filename for fragment shader source\nGLhandleARB prog1; \/\/ GLSL Program Object\nbool shaderbool1 = false;\nGLfloat shaderfloat1 = .5;\n\n\/\/ Camera\nGLdouble viewmatrix[16],\n viewang = 5.; \/\/ Degrees\n\n\/\/ Wave\/Spline Patches\nint numsubdivs; \/\/ Number of subdivisions for object\nconst int minsubdivs = 1; \/\/ Minumum of above\nconst int maxsubdivs = 50; \/\/ Maximum of above\nconst int PTS = 4; \/\/ Number of control points in a patch\nconst int EDGES = 4; \/\/ Sides in a patch\nconst int SIZE = PTS*EDGES*3; \/\/ Size of Patch Arrays\nbool wave; \/\/ Starts the wave propagation.\ndouble modd; \/\/ Value for the waves in the Bezier patches\n\nGLdouble b1[SIZE] = {\n 1.5,-1.5, 0.0, 1.5,-0.5,-3.0, 1.5, 0.5,-2.0, 1.5, 1.5, 1.0,\n 0.5,-1.5, 0.0, 0.5,-0.5, 0.0, 0.5, 0.5, 0.0, 0.5, 1.5, 0.0,\n -0.5,-1.5, 0.0, -0.5,-0.5, 1.0, -0.5, 0.5,-3.0, -0.5, 1.5, 1.0,\n -1.5,-1.5, 1.0, -1.5,-0.5,-2.0, -1.5, 0.5, 1.0, -1.5, 1.5, 0.0};\n\nGLdouble b2[SIZE] = {\n 1.5, 1.5, 1.0, 1.5, 0.5,-2.0, 2.5, 0.5,-2.0, 1.5, 1.5, 1.0,\n 0.5, 1.5, 0.0, 0.5, 0.5, 0.0, 1.5, 0.5, 0.0, 0.5, 1.5, 0.0,\n -0.5, 1.5, 1.0, -0.5, 0.5,-3.0, -1.5, 0.5,-3.0, -0.5, 1.5, 1.0,\n -1.5, 1.5, 0.0, -1.5, 0.5, 1.0, -2.5, 0.5, 1.0, -1.5, 1.5, 0.0};\n\n\/\/ waveFun\n\/\/ Propogates a wave through one of the axes of a spline patch. \nvoid waveFun(GLdouble *arr, int column, int axis)\n{\n for (int i = 0; i < PTS; ++i)\n {\n arr[(column * 3 + axis) * i] *= sin(modd);\n cout << (column + axis) * 3 + i << endl;\n }\n}\n\n\/\/ drawBezierPatch\n\/\/ Draws a number of control points for a bezier patch\n\/\/ The z coordinates of all the points are translated\n\/\/ by the sine of the mod parameter.\nvoid drawBezierPatch(int subdivs, double mod, GLdouble *cpts)\n{\n glColor3d(0.,0.,0.5);\n glMap2d(GL_MAP2_VERTEX_3, 0., 1., 3, 4, 0., 1., 3*4, 4, cpts);\n glEnable(GL_MAP2_VERTEX_3);\n\n glMapGrid2d(subdivs, 0., 1., subdivs, 0., 1.);\n glEnable(GL_AUTO_NORMAL);\n\n glFrontFace(GL_CW); \/\/ Normals are evidently backwards here :-(\n glEvalMesh2(GL_FILL, 0, subdivs, 0, subdivs);\n glFrontFace(GL_CCW);\n}\n\n\/\/ myDisplay\n\/\/ The GLUT display function\nvoid myDisplay()\n{\n glClearColor(0.5f, 0.5f, 0.5f, 1.0f);\n glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);\n\n GLhandleARB theprog; \/\/ CURRENTLY-used program object or 0 if none\n\n \/\/ Activating the shaders\n glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);\n theprog = prog1;\n\n glEnable(GL_DEPTH_TEST); \/\/ Set up 3D\n\n \/\/ Setting up the camera view\n glLoadIdentity();\n glMultMatrixd(viewmatrix);\n\n\n\n \/\/ Position light source 0 & draw ball there\n glPushMatrix();\n\/\/ glRotated(lightrotang, 1.,0.,0.);\n glTranslated(-1., 1., 2.);\n GLfloat origin4[] = { 0.f, 0.f, 0.f, 1.f };\n glLightfv(GL_LIGHT0, GL_POSITION, origin4);\n GLfloat spotdir3[] = { 1.f, -1.f, -1.f };\n glLightfv(GL_LIGHT0, GL_SPOT_DIRECTION, spotdir3);\n glUseProgramObjectARB(0);\n glColor3d(1., 1., 1.);\n glutSolidSphere(0.1, 20, 15); \/\/ obj for light source\n glPopMatrix();\n\n glUseProgramObjectARB(theprog);\n\n \/\/Send info to shader\n if (theprog)\n {\n GLint loc; \/\/ Location for shader vars\n\n loc = glGetUniformLocationARB(theprog, \"myb1\");\n if (loc != -1)\n {\n glUniform1i(loc, shaderbool1);\n }\n\n loc = glGetUniformLocationARB(theprog, \"myf1\");\n if (loc != -1)\n {\n glUniform1f(loc, shaderfloat1);\n }\n }\n\n \/\/ Draw objects\n glTranslated(0,0,-4);\n if(wave)\n {\n drawBezierPatch(numsubdivs, modd, b1);\n drawBezierPatch(numsubdivs, modd, b2);\n }\n else\n {\n drawBezierPatch(numsubdivs, 0, b1);\n drawBezierPatch(numsubdivs, 0, b2);\n }\n\n documentation();\n glutSwapBuffers();\n}\n\n\/\/ myIdle\n\/\/ The GLUT idle function\nvoid myIdle()\n{\n modd += 0.1;\n waveFun(b1, 3, 2);\n waveFun(b2, 0, 2);\n glutPostRedisplay();\n \/\/ Print OpenGL errors, if there are any (for debugging)\n static int error_count = 0;\n if (GLenum err = glGetError())\n {\n ++error_count;\n cerr << \"OpenGL ERROR \" << error_count << \": \"\n << gluErrorString(err) << endl;\n }\n}\n\n\/\/ set()\n\/\/ Sets given matrix to given translation\/rotation.\nvoid set(GLdouble *arr, GLdouble tx, GLdouble ty, GLdouble tz,\n GLdouble rang=0., GLdouble rx=0., GLdouble ry=0., GLdouble rz=0.)\n{\n glLoadIdentity();\n glTranslated(tx, ty, tz);\n glRotated(rang, rx, ry, rz);\n glMultMatrixd(arr);\n glGetDoublev(GL_MODELVIEW_MATRIX, arr);\n}\n\n\/\/ reset()\n\/\/ Resets the given matrix to the identity\nvoid reset(GLdouble *arr)\n{\n glLoadIdentity();\n glGetDoublev(GL_MODELVIEW_MATRIX, arr);\n}\n\n\n\/\/ myKeyboard\n\/\/ The GLUT keyboard function\nvoid myKeyboard(unsigned char key, int x, int y)\n{\n switch (key)\n {\n case ESCKEY: \/\/ Esc: quit\n exit(0);\n break;\n case '+':\n set(viewmatrix, 0., 0., 1.);\n break;\n case '-':\n set(viewmatrix, 0., 0., -1.);\n break;\n case '<':\n set(viewmatrix, 0., -1., 0., 10,1,0,0);\n break;\n case '>':\n set(viewmatrix, 0., 1., 0., -10,1,0,0);\n break;\n case ',':\n set(viewmatrix, 0., -1., 0., 10,0,1,0);\n break;\n case '.':\n set(viewmatrix, 0., 1., 0., -10,0,1,0);\n break;\n case 'R':\n case 'r':\n reset(viewmatrix);\n break;\n case ' ':\n wave = !wave;\n break;\n case '(':\n if(numsubdivs > minsubdivs)\n --numsubdivs;\n break;\n case ')':\n if(numsubdivs < maxsubdivs)\n ++numsubdivs;\n break;\n case 'h':\n case 'H':\n help = !help;\n break;\n case 'f': \/\/ Space: toggle shader bool\n shaderbool1 = !shaderbool1;\n break;\n case '[': \/\/ [: Decrease shader float\n shaderfloat1 -= 0.02;\n if (shaderfloat1 < 0.)\n shaderfloat1 = 0.;\n break;\n case ']': \/\/ ]: Increase shader float\n shaderfloat1 += 0.02;\n if (shaderfloat1 > 1.)\n shaderfloat1 = 1.;\n break;\n }\n glutPostRedisplay();\n}\n\n\/\/ mySpecial\n\/\/ The GLUT special function\nvoid mySpecial(int key, int x, int y)\n{\n switch (key)\n {\n case GLUT_KEY_LEFT:\n set(viewmatrix, 0.,0.,0., -viewang, 0.,1.,0.);\n break;\n case GLUT_KEY_RIGHT:\n set(viewmatrix, 0.,0.,0., viewang, 0.,1.,0.);\n break;\n case GLUT_KEY_UP:\n set(viewmatrix, 0.,0.,0., -viewang,0.,.0,1.);\n break;\n case GLUT_KEY_DOWN:\n set(viewmatrix, 0.,0.,0., viewang,0.,.0,1.);\n break;\n }\n glutPostRedisplay();\n}\n\n\/\/ myReshape\n\/\/ The GLUT reshape function\nvoid myReshape(int w, int h)\n{\n \/\/ Set viewport & save window dimensions in globals\n glViewport(0, 0, w, h);\n winw = w;\n winh = h;\n \/\/ Set up projection\n \/\/ Perspective projection with near quite near & far pretty far\n glMatrixMode(GL_PROJECTION);\n glLoadIdentity();\n gluPerspective(60., double(w)\/h, 0.01, 100.);\n glMatrixMode(GL_MODELVIEW); \/\/ Always go back to model\/view mode\n}\n\n\/\/ init\n\/\/ Initialize GL states & global data\nvoid init()\n{\n reset(viewmatrix); \/\/ Reset camera position\n glMatrixMode(GL_MODELVIEW);\n modd = 0.0;\n wave = false;\n numsubdivs = 10;\n\n \/\/ Shaders\n prog1 = makeProgramObjectFromFiles(vshader1fname, fshader1fname);\n}\n\n\/\/ myPassiveMotion\n\/\/ The GLUT passiveMotion function\nvoid myPassiveMotion(int x, int y)\n{\n \/\/ Save mouse position in class (haha)\n mousy.saveMouse(x, y);\n}\n\n\/\/ The main\nint main(int argc, char ** argv)\n{\n \/\/ Initilization of OpenGL\/GLUT\n glutInit(&argc, argv);\n \/\/ Set shader source filenames. Done here, as opposed to in\n getShaderFilenames(vshader1fname, fshader1fname, argc, argv);\n \/\/ function init, so that we can use command-line arguments.\n glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);\n\n \/\/ Creating the view window\n glutInitWindowSize(startwinsize, startwinsize);\n glutInitWindowPosition(50, 50);\n glutCreateWindow(\"CS 381 - Shaders, Normals, Lighting, and Splines Oh My!\");\n\n \/\/ Init GLEW & check status - exit on failure\n if (glewInit() != GLEW_OK)\n {\n cerr << \"glewInit failed\" << endl;\n exit(1);\n }\n\n init();\n glutDisplayFunc(myDisplay);\n glutIdleFunc(myIdle);\n glutReshapeFunc(myReshape);\n\/\/ glutMouseFunc(myMouse);\n glutKeyboardFunc(myKeyboard);\n glutSpecialFunc(mySpecial);\n glutPassiveMotionFunc(myPassiveMotion);\n\n \/\/ Start GLUT event handling loop\n glutMainLoop();\n\n return 0;\n}\n\nvoid documentation()\n{\n \/\/ Draw documentation\n glDisable(GL_DEPTH_TEST);\n glLoadIdentity();\n glMatrixMode(GL_PROJECTION); \/\/ Set up simple ortho projection\n glPushMatrix();\n glLoadIdentity();\n gluOrtho2D(0., double(winw), 0., double(winh));\n glColor3d(0., 0., 0.); \/\/ Black text\n BitmapPrinter p(20., winh-20., 20.);\n if(help)\n {\n ostringstream os2;\n os2 << fixed << setprecision(2) << numsubdivs;\n p.print(\"Arrows Rotate Scene\");\n p.print(\"( ) Change Subdivisions (\" + os2.str() + \")\");\n p.print(\"+\/- Zoom in\/out\");\n p.print(\"r Reset Camera\");\n p.print(string(\"space Start wave (\" )+ (wave ? \"true\" : \"false\") + \")\");\n }\n else\n {\n p.print(\"h help\");\n }\n p.print(\"Esc Quit\");\n glPopMatrix(); \/\/ Restore prev projection\n glMatrixMode(GL_MODELVIEW);\n}\n<commit_msg>rotate works, but zoom is screwy<commit_after>\/* Bucky Frost\n * Paul Gentemann\n * CS 381\n * File Name : splinepatch.cpp\n * Last Modified : Sun 10 Nov 2013 05:16:20 AM AKST\n * Description : A pair of spline plains, patched together, that will\n * ripple upon user input.\n *\/\n\n\/\/ OpenGL\/GLUT includes - DO THESE FIRST\n#include <cstdlib> \/\/ Do this before GL\/GLUT includes\nusing std::exit;\n#ifndef __APPLE__\n# include <GL\/glew.h>\n# include <GL\/glut.h> \/\/ Includes OpenGL headers as well\n#else\n# include <GLEW\/glew.h>\n# include <GLUT\/glut.h> \/\/ Apple puts glut.h in a different place\n#endif\n#ifdef _MSC_VER \/\/ Tell MS-Visual Studio about GLEW lib\n# pragma comment(lib, \"glew32.lib\")\n#endif\n#include \"lib381\/bitmapprinter.h\"\n#include \"lib381\/glslprog.h\" \/\/ For GLSL code-handling functions\n#include <string>\nusing std::string;\n#include <iostream>\nusing std::cout; using std::cerr; using std::endl;\n#include <vector>\nusing std::vector;\n#include <sstream>\nusing std::ostringstream;\n#include <iomanip>\nusing std::setprecision;\nusing std::fixed;\n#include <cmath>\nusing std::sin;\n#include \"mouse.h\"\nMouse mousy = Mouse();\n\n\/\/ Function prototypes\nvoid documentation();\nvoid waveFun(int);\nvoid drawBezierPatch(int, GLdouble *);\nvoid myDisplay();\nvoid myIdle();\nvoid reset(GLdouble);\nvoid myKeyboard(unsigned char, int, int);\nvoid myPassiveMotion(int, int);\nvoid init();\nvoid myReshape(int, int);\nvoid set(GLdouble, GLdouble, GLdouble, GLdouble,\n GLdouble, GLdouble, GLdouble, GLdouble);\n\n\/\/ Global variables\nconst int ESCKEY = 27; \/\/ ASCII value of Escape\nconst int startwinsize = 600; \/\/ Start window width & height (pixels)\nint winw = 1, winh = 1; \/\/ Window width, height (pixels)\nbool help = false;\nint zoom = -4;\n\n\/\/ Shaders\nbool shaderbool1 = true;\nstring vshader1fname; \/\/ Filename for vertex shader source\nstring fshader1fname; \/\/ Filename for fragment shader source\nGLhandleARB prog1; \/\/ GLSL Program Object\nGLfloat shaderfloat1 = .5;\n\n\/\/ Camera\nGLdouble viewmatrix[16],\n viewang = 5.; \/\/ Degrees\n\n\/\/ Wave\/Spline Patches\nint numsubdivs; \/\/ Number of subdivisions for object\nconst int minsubdivs = 1; \/\/ Minumum of above\nconst int maxsubdivs = 50; \/\/ Maximum of above\nconst int PTS = 4; \/\/ Number of control points in a patch\nconst int EDGES = 4; \/\/ Sides in a patch\nconst int SIZE = PTS*EDGES*3; \/\/ Size of Patch Arrays\nbool wave; \/\/ Starts the wave propagation.\ndouble modd; \/\/ Value for the waves in the Bezier patches\n\nGLdouble b1[SIZE] = {\n 1.5,-1.5, 0.0, 1.5,-0.5,-0.0, 1.5, 0.5,-0.0, 1.5, 1.5, 0.0,\n 0.5,-1.5, 0.0, 0.5,-0.5, 0.0, 0.5, 0.5, 0.0, 0.5, 1.5, 0.0,\n -0.5,-1.5, 0.0, -0.5,-0.5, 0.0, -0.5, 0.5,-0.0, -0.5, 1.5, 0.0,\n -1.5,-1.5, 0.0, -1.5,-0.5,-0.0, -1.5, 0.5, 0.0, -1.5, 1.5, 0.0};\n\nGLdouble b2[SIZE] = {\n 1.5, 0.5, 0.0, 1.5, 1.5,-0.0, 2.5, 1.8,-0.0, 3.0, 3.5,-0.0,\n 0.5, 0.5, 0.0, 0.5, 1.5, 0.0, 1.5, 2.0, 0.0, 0.0, 3.5, 0.0,\n -0.5, 0.5, 0.0, -0.5, 1.5,-0.0, -1.5, 2.3,-0.0, -0.0, 3.5,-0.0,\n -1.5, 0.5, 0.0, -1.5, 1.5, 0.0, -2.5, 2.8, 0.0, -3.0, 3.5, 0.0};\n\n\/\/ waveFun\n\/\/ Propogates a wave through one of the axes of a spline patch. \nvoid waveFun(GLdouble *arr, int column, int axis, int mult)\n{\n for (int i = 0; i < PTS; ++i)\n {\n arr[PTS * 3 * i + (3 * column + axis)] = mult * sin(modd);\n }\n}\n\n\/\/ drawBezierPatch\n\/\/ Draws a number of control points for a bezier patch. The z coordinates \n\/\/ of all the points are translated by the sine of the mod parameter.\nvoid drawBezierPatch(int subdivs, GLdouble *cpts)\n{\n glColor3d(0.,0.,0.5);\n glMap2d(GL_MAP2_VERTEX_3, 0., 1., 3, 4, 0., 1., 3*4, 4, cpts);\n glEnable(GL_MAP2_VERTEX_3);\n\n glMapGrid2d(subdivs, 0., 1., subdivs, 0., 1.);\n glEnable(GL_AUTO_NORMAL);\n\n glFrontFace(GL_CW); \/\/ Normals are evidently backwards here :-(\n glEvalMesh2(GL_FILL, 0, subdivs, 0, subdivs);\n glFrontFace(GL_CCW);\n}\n\n\/\/ myDisplay\n\/\/ The GLUT display function\nvoid myDisplay()\n{\n glClearColor(0.5f, 0.5f, 0.5f, 1.0f);\n glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);\n\n GLhandleARB theprog; \/\/ CURRENTLY-used program object or 0 if none\n\n \/\/ Activating the shaders\n glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);\n theprog = prog1;\n\n glEnable(GL_DEPTH_TEST); \/\/ Set up 3D\n\n \/\/ Setting up the camera view\n glLoadIdentity();\n glMultMatrixd(viewmatrix);\n\n \/\/ Position light source 0 & draw ball there\n glPushMatrix();\n glTranslated(-1., 1., 2.);\n GLfloat origin4[] = { 0.f, 0.f, 0.f, 1.f };\n glLightfv(GL_LIGHT0, GL_POSITION, origin4);\n GLfloat spotdir3[] = { 1.f, -1.f, -1.f };\n glLightfv(GL_LIGHT0, GL_SPOT_DIRECTION, spotdir3);\n glUseProgramObjectARB(0);\n glColor3d(1., 1., 1.);\n glutSolidSphere(0.1, 20, 15); \/\/ obj for light source\n glPopMatrix();\n\n glUseProgramObjectARB(theprog);\n\n \/\/Send info to shader\n if (theprog)\n {\n GLint loc; \/\/ Location for shader vars\n loc = glGetUniformLocationARB(theprog, \"myb1\");\n if (loc != -1)\n {\n glUniform1i(loc, shaderbool1);\n }\n loc = glGetUniformLocationARB(theprog, \"myf1\");\n if (loc != -1)\n {\n glUniform1f(loc, shaderfloat1);\n }\n }\n\n \/\/ Draw objects\n glTranslated(0,0,zoom);\n if(wave)\n {\n modd += 0.1;\n waveFun(b1, 2, 2, 1);\n waveFun(b2, 2, 2, -1);\n drawBezierPatch(numsubdivs, b1);\n drawBezierPatch(numsubdivs, b2);\n }\n else\n {\n drawBezierPatch(numsubdivs, b1);\n drawBezierPatch(numsubdivs, b2);\n }\n\n documentation();\n glutSwapBuffers();\n}\n\n\/\/ myIdle\n\/\/ The GLUT idle function\nvoid myIdle()\n{\n glutPostRedisplay();\n \/\/ Print OpenGL errors, if there are any (for debugging)\n static int error_count = 0;\n if (GLenum err = glGetError())\n {\n ++error_count;\n cerr << \"OpenGL ERROR \" << error_count << \": \"\n << gluErrorString(err) << endl;\n }\n}\n\n\/\/ set()\n\/\/ Sets given matrix to given translation\/rotation.\nvoid set(GLdouble *arr, GLdouble tx, GLdouble ty, GLdouble tz,\n GLdouble rang=0., GLdouble rx=0., GLdouble ry=0., GLdouble rz=0.)\n{\n glLoadIdentity();\n glTranslated(tx, ty, tz);\n glRotated(rang, rx, ry, rz);\n glMultMatrixd(arr);\n glGetDoublev(GL_MODELVIEW_MATRIX, arr);\n}\n\n\/\/ reset()\n\/\/ Resets the given matrix to the identity\nvoid reset(GLdouble *arr)\n{\n glLoadIdentity();\n glGetDoublev(GL_MODELVIEW_MATRIX, arr);\n}\n\n\/\/ myKeyboard\n\/\/ The GLUT keyboard function\nvoid myKeyboard(unsigned char key, int x, int y)\n{\n switch (key)\n {\n case ESCKEY: \/\/ Esc: quit\n exit(0);\n break;\n case '+':\n ++zoom;\n set(viewmatrix, 0., 0., 1.);\n break;\n case '-':\n --zoom;\n set(viewmatrix, 0., 0.,-1.);\n break;\n case '<':\n set(viewmatrix, 0., -1., 0., 10,1,0,0);\n break;\n case '>':\n set(viewmatrix, 0., 1., 0., -10,1,0,0);\n break;\n case ',':\n set(viewmatrix, 0., -1., 0., 10,0,1,0);\n break;\n case '.':\n set(viewmatrix, 0., 1., 0., -10,0,1,0);\n break;\n case 'R':\n case 'r':\n zoom = -4;\n reset(viewmatrix);\n break;\n case ' ':\n wave = !wave;\n break;\n case '(':\n if(numsubdivs > minsubdivs)\n --numsubdivs;\n break;\n case ')':\n if(numsubdivs < maxsubdivs)\n ++numsubdivs;\n break;\n case 'h':\n case 'H':\n help = !help;\n break;\n case 'f': \/\/ Space: toggle shader bool\n shaderbool1 = !shaderbool1;\n break;\n case '[': \/\/ [: Decrease shader float\n shaderfloat1 -= 0.02;\n if (shaderfloat1 < 0.)\n shaderfloat1 = 0.;\n break;\n case ']': \/\/ ]: Increase shader float\n shaderfloat1 += 0.02;\n if (shaderfloat1 > 1.)\n shaderfloat1 = 1.;\n break;\n }\n glutPostRedisplay();\n}\n\n\/\/ mySpecial\n\/\/ The GLUT special function\nvoid mySpecial(int key, int x, int y)\n{\n glLoadMatrixd(viewmatrix);\n glTranslated(0., 0., zoom);\n switch (key)\n {\n case GLUT_KEY_LEFT:\n glRotated(-5, 0., 1., 0.);\n break;\n case GLUT_KEY_RIGHT:\n glRotated(5, 0., 1., 0.);\n break;\n case GLUT_KEY_UP:\n glRotated(-5, 0., 0., 1.);\n break;\n case GLUT_KEY_DOWN:\n glRotated(5, 0., 0., 1.);\n break;\n }\n glTranslated(0., 0., -zoom);\n glGetDoublev(GL_MODELVIEW_MATRIX, viewmatrix);\n glutPostRedisplay();\n}\n\n\/\/ myReshape\n\/\/ The GLUT reshape function\nvoid myReshape(int w, int h)\n{\n \/\/ Set viewport & save window dimensions in globals\n glViewport(0, 0, w, h);\n winw = w;\n winh = h;\n \/\/ Set up projection\n \/\/ Perspective projection with near quite near & far pretty far\n glMatrixMode(GL_PROJECTION);\n glLoadIdentity();\n gluPerspective(60., double(w)\/h, 0.01, 100.);\n glMatrixMode(GL_MODELVIEW); \/\/ Always go back to model\/view mode\n}\n\n\/\/ init\n\/\/ Initialize GL states & global data\nvoid init()\n{\n reset(viewmatrix); \/\/ Reset camera position\n glMatrixMode(GL_MODELVIEW);\n modd = 0.0;\n wave = false;\n numsubdivs = 10;\n\n \/\/ Shaders\n prog1 = makeProgramObjectFromFiles(vshader1fname, fshader1fname);\n}\n\n\/\/ myPassiveMotion\n\/\/ The GLUT passiveMotion function\nvoid myPassiveMotion(int x, int y)\n{\n \/\/ Save mouse position in class (haha)\n mousy.saveMouse(x, y);\n}\n\n\/\/ The main\nint main(int argc, char ** argv)\n{\n \/\/ Initilization of OpenGL\/GLUT\n glutInit(&argc, argv);\n \/\/ Set shader source filenames. Done here, as opposed to in\n getShaderFilenames(vshader1fname, fshader1fname, argc, argv);\n \/\/ function init, so that we can use command-line arguments.\n glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);\n\n \/\/ Creating the view window\n glutInitWindowSize(startwinsize, startwinsize);\n glutInitWindowPosition(50, 50);\n glutCreateWindow(\"CS 381 - Shaders, Normals, Lighting, and Splines Oh My!\");\n\n \/\/ Init GLEW & check status - exit on failure\n if (glewInit() != GLEW_OK)\n {\n cerr << \"glewInit failed\" << endl;\n exit(1);\n }\n\n init();\n glutDisplayFunc(myDisplay);\n glutIdleFunc(myIdle);\n glutReshapeFunc(myReshape);\n\/\/ glutMouseFunc(myMouse);\n glutKeyboardFunc(myKeyboard);\n glutSpecialFunc(mySpecial);\n glutPassiveMotionFunc(myPassiveMotion);\n\n \/\/ Start GLUT event handling loop\n glutMainLoop();\n\n return 0;\n}\n\nvoid documentation()\n{\n \/\/ Draw documentation\n glDisable(GL_DEPTH_TEST);\n glLoadIdentity();\n glMatrixMode(GL_PROJECTION); \/\/ Set up simple ortho projection\n glPushMatrix();\n glLoadIdentity();\n gluOrtho2D(0., double(winw), 0., double(winh));\n glColor3d(0., 0., 0.); \/\/ Black text\n BitmapPrinter p(20., winh-20., 20.);\n if(help)\n {\n ostringstream os2;\n os2 << fixed << setprecision(2) << numsubdivs;\n p.print(\"Arrows Rotate Scene\");\n p.print(\"( ) Change Subdivisions (\" + os2.str() + \")\");\n p.print(\"+\/- Zoom in\/out\");\n p.print(\"r Reset Camera\");\n p.print(string(\"space Start wave (\" )+ (wave ? \"true\" : \"false\") + \")\");\n }\n else\n {\n p.print(\"h help\");\n }\n p.print(\"Esc Quit\");\n glPopMatrix(); \/\/ Restore prev projection\n glMatrixMode(GL_MODELVIEW);\n}\n<|endoftext|>"} {"text":"<commit_before>\/****************************************************************************\n *\n * Copyright (c) 2013 PX4 Development Team. All rights reserved.\n * Author: \t@author Thomas Gubler <thomasgubler@gmail.com>\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in\n * the documentation and\/or other materials provided with the\n * distribution.\n * 3. Neither the name PX4 nor the names of its contributors may be\n * used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS\n * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED\n * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n ****************************************************************************\/\n\n\n\/**\n * @file mTecs.cpp\n *\n * @author Thomas Gubler <thomasgubler@gmail.com>\n *\/\n\n#include \"mTecs.h\"\n\n#include <lib\/geo\/geo.h>\n#include <stdio.h>\n\nnamespace fwPosctrl {\n\nmTecs::mTecs() :\n\tSuperBlock(NULL, \"MT\"),\n\t\/* Parameters *\/\n\t_mTecsEnabled(this, \"ENABLED\"),\n\t_airspeedMin(this, \"FW_AIRSPD_MIN\", false),\n\t\/* Publications *\/\n\t_status(&getPublications(), ORB_ID(tecs_status)),\n\t\/* control blocks *\/\n\t_controlTotalEnergy(this, \"THR\"),\n\t_controlEnergyDistribution(this, \"PIT\", true),\n\t_controlAltitude(this, \"FPA\", true),\n\t_controlAirSpeed(this, \"ACC\"),\n\t_airspeedDerivative(this, \"AD\"),\n\t_throttleSp(0.0f),\n\t_pitchSp(0.0f),\n\t_BlockOutputLimiterTakeoffThrottle(this, \"TKF_THR\"),\n\t_BlockOutputLimiterTakeoffPitch(this, \"TKF_PIT\", true),\n\t_BlockOutputLimiterUnderspeedThrottle(this, \"USP_THR\"),\n\t_BlockOutputLimiterUnderspeedPitch(this, \"USP_PIT\", true),\n\t_BlockOutputLimiterLandThrottle(this, \"LND_THR\"),\n\t_BlockOutputLimiterLandPitch(this, \"LND_PIT\", true),\n\ttimestampLastIteration(hrt_absolute_time()),\n\t_firstIterationAfterReset(true),\n\t_dtCalculated(false),\n\t_counter(0),\n\t_debug(false)\n{\n}\n\nmTecs::~mTecs()\n{\n}\n\nint mTecs::updateAltitudeSpeed(float flightPathAngle, float altitude, float altitudeSp, float airspeed,\n\t\tfloat airspeedSp, tecs_mode mode, LimitOverride limitOverride)\n{\n\t\/* check if all input arguments are numbers and abort if not so *\/\n\tif (!isfinite(flightPathAngle) || !isfinite(altitude) ||\n\t\t\t!isfinite(altitudeSp) || !isfinite(airspeed) || !isfinite(airspeedSp) || !isfinite(mode)) {\n\t\treturn -1;\n\t}\n\n\t\/* time measurement *\/\n\tupdateTimeMeasurement();\n\n\t\/* calculate flight path angle setpoint from altitude setpoint *\/\n\tfloat flightPathAngleSp = _controlAltitude.update(altitudeSp - altitude);\n\n\t\/* Debug output *\/\n\tif (_counter % 10 == 0) {\n\t\tdebug(\"***\");\n\t\tdebug(\"updateAltitudeSpeed: altitudeSp %.4f, altitude %.4f, flightPathAngleSp %.4f\", (double)altitudeSp, (double)altitude, (double)flightPathAngleSp);\n\t}\n\n\t\/* Write part of the status message *\/\n\t_status.altitudeSp = altitudeSp;\n\t_status.altitude = altitude;\n\n\n\t\/* use flightpath angle setpoint for total energy control *\/\n\treturn updateFlightPathAngleSpeed(flightPathAngle, flightPathAngleSp, airspeed,\n\t\t\tairspeedSp, mode, limitOverride);\n}\n\nint mTecs::updateFlightPathAngleSpeed(float flightPathAngle, float flightPathAngleSp, float airspeed,\n\t\tfloat airspeedSp, tecs_mode mode, LimitOverride limitOverride)\n{\n\t\/* check if all input arguments are numbers and abort if not so *\/\n\tif (!isfinite(flightPathAngle) || !isfinite(flightPathAngleSp) ||\n\t\t\t!isfinite(airspeed) || !isfinite(airspeedSp) || !isfinite(mode)) {\n\t\treturn -1;\n\t}\n\n\t\/* time measurement *\/\n\tupdateTimeMeasurement();\n\n\t\/* calculate longitudinal acceleration setpoint from airspeed setpoint*\/\n\tfloat accelerationLongitudinalSp = _controlAirSpeed.update(airspeedSp - airspeed);\n\n\t\/* Debug output *\/\n\tif (_counter % 10 == 0) {\n\t\tdebug(\"updateFlightPathAngleSpeed airspeedSp %.4f, airspeed %.4f, accelerationLongitudinalSp%.4f\", (double)airspeedSp, (double)airspeed, (double)accelerationLongitudinalSp);\n\t}\n\n\t\/* Write part of the status message *\/\n\t_status.flightPathAngleSp = flightPathAngleSp;\n\t_status.flightPathAngle = flightPathAngle;\n\t_status.airspeedSp = airspeedSp;\n\t_status.airspeed = airspeed;\n\n\n\t\/* use longitudinal acceleration setpoint for total energy control *\/\n\treturn updateFlightPathAngleAcceleration(flightPathAngle, flightPathAngleSp, airspeed,\n\t\t\taccelerationLongitudinalSp, mode, limitOverride);\n}\n\nint mTecs::updateFlightPathAngleAcceleration(float flightPathAngle, float flightPathAngleSp, float airspeed,\n\t\tfloat accelerationLongitudinalSp, tecs_mode mode, LimitOverride limitOverride)\n{\n\t\/* check if all input arguments are numbers and abort if not so *\/\n\tif (!isfinite(flightPathAngle) || !isfinite(flightPathAngleSp) ||\n\t\t\t!isfinite(airspeed) || !isfinite(accelerationLongitudinalSp) || !isfinite(mode)) {\n\t\treturn -1;\n\t}\n\t\/* time measurement *\/\n\tupdateTimeMeasurement();\n\n\t\/* update parameters first *\/\n\tupdateParams();\n\n\t\/* calculate values (energies) *\/\n\tfloat flightPathAngleError = flightPathAngleSp - flightPathAngle;\n\tfloat airspeedDerivative = 0.0f;\n\tif(_airspeedDerivative.getDt() > 0.0f) {\n\t\tairspeedDerivative = _airspeedDerivative.update(airspeed);\n\t}\n\tfloat airspeedDerivativeNorm = airspeedDerivative \/ CONSTANTS_ONE_G;\n\tfloat airspeedDerivativeSp = accelerationLongitudinalSp;\n\tfloat airspeedDerivativeNormSp = airspeedDerivativeSp \/ CONSTANTS_ONE_G;\n\tfloat airspeedDerivativeNormError = airspeedDerivativeNormSp - airspeedDerivativeNorm;\n\n\tfloat totalEnergyRate = flightPathAngle + airspeedDerivativeNorm;\n\tfloat totalEnergyRateError = flightPathAngleError + airspeedDerivativeNormError;\n\tfloat totalEnergyRateSp = flightPathAngleSp + airspeedDerivativeNormSp;\n\tfloat totalEnergyRateError2 = totalEnergyRateSp - totalEnergyRate;\n\n\tfloat energyDistributionRate = flightPathAngle - airspeedDerivativeNorm;\n\tfloat energyDistributionRateError = flightPathAngleError - airspeedDerivativeNormError;\n\tfloat energyDistributionRateSp = flightPathAngleSp - airspeedDerivativeNormSp;\n\tfloat energyDistributionRateError2 = energyDistributionRateSp - energyDistributionRate;\n\n\t\/* Debug output *\/\n\tif (_counter % 10 == 0) {\n\t\tdebug(\"totalEnergyRateSp %.2f, totalEnergyRate %.2f, totalEnergyRateError %.2f totalEnergyRateError2 %.2f airspeedDerivativeNorm %.4f\",\n\t\t\t\t(double)totalEnergyRateSp, (double)totalEnergyRate, (double)totalEnergyRateError, (double)totalEnergyRateError2, (double)airspeedDerivativeNorm);\n\t\tdebug(\"energyDistributionRateSp %.2f, energyDistributionRate %.2f, energyDistributionRateError %.2f energyDistributionRateError2 %.2f\",\n\t\t\t\t(double)energyDistributionRateSp, (double)energyDistributionRate, (double)energyDistributionRateError, (double)energyDistributionRateError2);\n\t}\n\n\t\/* Check airspeed: if below safe value switch to underspeed mode (if not in takeoff mode) *\/\n\tif (!TECS_MODE_LAND && airspeed < _airspeedMin.get()) {\n\t\tmode = TECS_MODE_UNDERSPEED;\n\t}\n\n\t\/* Set special ouput limiters if we are not in TECS_MODE_NORMAL *\/\n\tBlockOutputLimiter *outputLimiterThrottle = NULL; \/\/ NULL --> use standard inflight limits\n\tBlockOutputLimiter *outputLimiterPitch = NULL; \/\/ NULL --> use standard inflight limits\n\tif (mode == TECS_MODE_TAKEOFF) {\n\t\toutputLimiterThrottle = &_BlockOutputLimiterTakeoffThrottle; \/\/XXX: accept prelaunch values from launchdetector\n\t\toutputLimiterPitch = &_BlockOutputLimiterTakeoffPitch;\n\t} else if (mode == TECS_MODE_LAND) {\n\t\t\/\/ only limit pitch but do not limit throttle\n\t\toutputLimiterPitch = &_BlockOutputLimiterLandPitch;\n\t} else if (mode == TECS_MODE_LAND_THROTTLELIM) {\n\t\toutputLimiterThrottle = &_BlockOutputLimiterLandThrottle;\n\t\toutputLimiterPitch = &_BlockOutputLimiterLandPitch;\n\t} else if (mode == TECS_MODE_UNDERSPEED) {\n\t\toutputLimiterThrottle = &_BlockOutputLimiterUnderspeedThrottle;\n\t\toutputLimiterPitch = &_BlockOutputLimiterUnderspeedPitch;\n\t}\n\n\t\/* Apply overrride given by the limitOverride argument (this is used for limits which are not given by\n\t * parameters such as pitch limits with takeoff waypoints or throttle limits when the launchdetector\n\t * is running) *\/\n\tbool limitApplied = limitOverride.applyOverride(outputLimiterThrottle == NULL ?\n\t\t\t_controlTotalEnergy.getOutputLimiter() :\n\t\t\t*outputLimiterThrottle,\n\t\t\toutputLimiterPitch == NULL ?\n\t\t\t_controlEnergyDistribution.getOutputLimiter() :\n\t\t\t*outputLimiterPitch);\n\n\t\/* Write part of the status message *\/\n\t_status.airspeedDerivativeSp = airspeedDerivativeSp;\n\t_status.airspeedDerivative = airspeedDerivative;\n\t_status.totalEnergyRateSp = totalEnergyRateSp;\n\t_status.totalEnergyRate = totalEnergyRate;\n\t_status.energyDistributionRateSp = energyDistributionRateSp;\n\t_status.energyDistributionRate = energyDistributionRate;\n\t_status.mode = mode;\n\n\t\/** update control blocks **\/\n\t\/* update total energy rate control block *\/\n\t_throttleSp = _controlTotalEnergy.update(totalEnergyRateSp, totalEnergyRateError, outputLimiterThrottle);\n\n\t\/* update energy distribution rate control block *\/\n\t_pitchSp = _controlEnergyDistribution.update(energyDistributionRateSp, energyDistributionRateError, outputLimiterPitch);\n\n\n\tif (_counter % 10 == 0) {\n\t\tdebug(\"_throttleSp %.1f, _pitchSp %.1f, flightPathAngleSp %.1f, flightPathAngle %.1f accelerationLongitudinalSp %.1f, airspeedDerivative %.1f\",\n\t\t\t\t(double)_throttleSp, (double)_pitchSp,\n\t\t\t\t(double)flightPathAngleSp, (double)flightPathAngle,\n\t\t\t\t(double)accelerationLongitudinalSp, (double)airspeedDerivative);\n\t}\n\n\t\/* publish status messge *\/\n\t_status.update();\n\n\t\/* clean up *\/\n\t_firstIterationAfterReset = false;\n\t_dtCalculated = false;\n\n\t_counter++;\n\n\treturn 0;\n}\n\nvoid mTecs::resetIntegrators()\n{\n\t_controlTotalEnergy.getIntegral().setY(0.0f);\n\t_controlEnergyDistribution.getIntegral().setY(0.0f);\n\ttimestampLastIteration = hrt_absolute_time();\n\t_firstIterationAfterReset = true;\n}\n\nvoid mTecs::resetDerivatives(float airspeed)\n{\n\t_airspeedDerivative.setU(airspeed);\n}\n\n\nvoid mTecs::updateTimeMeasurement()\n{\n\tif (!_dtCalculated) {\n\t\tfloat deltaTSeconds = 0.0f;\n\t\tif (!_firstIterationAfterReset) {\n\t\t\thrt_abstime timestampNow = hrt_absolute_time();\n\t\t\tdeltaTSeconds = (float)(timestampNow - timestampLastIteration) * 1e-6f;\n\t\t\ttimestampLastIteration = timestampNow;\n\t\t}\n\t\tsetDt(deltaTSeconds);\n\n\t\t_dtCalculated = true;\n\t}\n}\n\nvoid mTecs::debug_print(const char *fmt, va_list args)\n{\n\tfprintf(stderr, \"%s: \", \"[mtecs]\");\n\tvfprintf(stderr, fmt, args);\n\n\tfprintf(stderr, \"\\n\");\n}\n\nvoid mTecs::debug(const char *fmt, ...) {\n\n\tif (!_debug) {\n\t\treturn;\n\t}\n\n\tva_list args;\n\n\tva_start(args, fmt);\n\tdebug_print(fmt, args);\n}\n\nbool mTecs::LimitOverride::applyOverride(BlockOutputLimiter &outputLimiterThrottle,\n\t\tBlockOutputLimiter &outputLimiterPitch)\n{\n\tbool ret = false;\n\n\tif (overrideThrottleMinEnabled)\t{\n\t\toutputLimiterThrottle.setMin(overrideThrottleMin);\n\t\tret = true;\n\t}\n\tif (overrideThrottleMaxEnabled)\t{\n\t\toutputLimiterThrottle.setMax(overrideThrottleMax);\n\t\tret = true;\n\t}\n\tif (overridePitchMinEnabled)\t{\n\t\toutputLimiterPitch.setMin(overridePitchMin);\n\t\tret = true;\n\t}\n\tif (overridePitchMaxEnabled)\t{\n\t\toutputLimiterPitch.setMax(overridePitchMax);\n\t\tret = true;\n\t}\n\n\treturn ret;\n}\n\n} \/* namespace fwPosctrl *\/\n<commit_msg>fix stupid error in underspeed detection<commit_after>\/****************************************************************************\n *\n * Copyright (c) 2013 PX4 Development Team. All rights reserved.\n * Author: \t@author Thomas Gubler <thomasgubler@gmail.com>\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in\n * the documentation and\/or other materials provided with the\n * distribution.\n * 3. Neither the name PX4 nor the names of its contributors may be\n * used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS\n * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED\n * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n ****************************************************************************\/\n\n\n\/**\n * @file mTecs.cpp\n *\n * @author Thomas Gubler <thomasgubler@gmail.com>\n *\/\n\n#include \"mTecs.h\"\n\n#include <lib\/geo\/geo.h>\n#include <stdio.h>\n\nnamespace fwPosctrl {\n\nmTecs::mTecs() :\n\tSuperBlock(NULL, \"MT\"),\n\t\/* Parameters *\/\n\t_mTecsEnabled(this, \"ENABLED\"),\n\t_airspeedMin(this, \"FW_AIRSPD_MIN\", false),\n\t\/* Publications *\/\n\t_status(&getPublications(), ORB_ID(tecs_status)),\n\t\/* control blocks *\/\n\t_controlTotalEnergy(this, \"THR\"),\n\t_controlEnergyDistribution(this, \"PIT\", true),\n\t_controlAltitude(this, \"FPA\", true),\n\t_controlAirSpeed(this, \"ACC\"),\n\t_airspeedDerivative(this, \"AD\"),\n\t_throttleSp(0.0f),\n\t_pitchSp(0.0f),\n\t_BlockOutputLimiterTakeoffThrottle(this, \"TKF_THR\"),\n\t_BlockOutputLimiterTakeoffPitch(this, \"TKF_PIT\", true),\n\t_BlockOutputLimiterUnderspeedThrottle(this, \"USP_THR\"),\n\t_BlockOutputLimiterUnderspeedPitch(this, \"USP_PIT\", true),\n\t_BlockOutputLimiterLandThrottle(this, \"LND_THR\"),\n\t_BlockOutputLimiterLandPitch(this, \"LND_PIT\", true),\n\ttimestampLastIteration(hrt_absolute_time()),\n\t_firstIterationAfterReset(true),\n\t_dtCalculated(false),\n\t_counter(0),\n\t_debug(false)\n{\n}\n\nmTecs::~mTecs()\n{\n}\n\nint mTecs::updateAltitudeSpeed(float flightPathAngle, float altitude, float altitudeSp, float airspeed,\n\t\tfloat airspeedSp, tecs_mode mode, LimitOverride limitOverride)\n{\n\t\/* check if all input arguments are numbers and abort if not so *\/\n\tif (!isfinite(flightPathAngle) || !isfinite(altitude) ||\n\t\t\t!isfinite(altitudeSp) || !isfinite(airspeed) || !isfinite(airspeedSp) || !isfinite(mode)) {\n\t\treturn -1;\n\t}\n\n\t\/* time measurement *\/\n\tupdateTimeMeasurement();\n\n\t\/* calculate flight path angle setpoint from altitude setpoint *\/\n\tfloat flightPathAngleSp = _controlAltitude.update(altitudeSp - altitude);\n\n\t\/* Debug output *\/\n\tif (_counter % 10 == 0) {\n\t\tdebug(\"***\");\n\t\tdebug(\"updateAltitudeSpeed: altitudeSp %.4f, altitude %.4f, flightPathAngleSp %.4f\", (double)altitudeSp, (double)altitude, (double)flightPathAngleSp);\n\t}\n\n\t\/* Write part of the status message *\/\n\t_status.altitudeSp = altitudeSp;\n\t_status.altitude = altitude;\n\n\n\t\/* use flightpath angle setpoint for total energy control *\/\n\treturn updateFlightPathAngleSpeed(flightPathAngle, flightPathAngleSp, airspeed,\n\t\t\tairspeedSp, mode, limitOverride);\n}\n\nint mTecs::updateFlightPathAngleSpeed(float flightPathAngle, float flightPathAngleSp, float airspeed,\n\t\tfloat airspeedSp, tecs_mode mode, LimitOverride limitOverride)\n{\n\t\/* check if all input arguments are numbers and abort if not so *\/\n\tif (!isfinite(flightPathAngle) || !isfinite(flightPathAngleSp) ||\n\t\t\t!isfinite(airspeed) || !isfinite(airspeedSp) || !isfinite(mode)) {\n\t\treturn -1;\n\t}\n\n\t\/* time measurement *\/\n\tupdateTimeMeasurement();\n\n\t\/* calculate longitudinal acceleration setpoint from airspeed setpoint*\/\n\tfloat accelerationLongitudinalSp = _controlAirSpeed.update(airspeedSp - airspeed);\n\n\t\/* Debug output *\/\n\tif (_counter % 10 == 0) {\n\t\tdebug(\"updateFlightPathAngleSpeed airspeedSp %.4f, airspeed %.4f, accelerationLongitudinalSp%.4f\", (double)airspeedSp, (double)airspeed, (double)accelerationLongitudinalSp);\n\t}\n\n\t\/* Write part of the status message *\/\n\t_status.flightPathAngleSp = flightPathAngleSp;\n\t_status.flightPathAngle = flightPathAngle;\n\t_status.airspeedSp = airspeedSp;\n\t_status.airspeed = airspeed;\n\n\n\t\/* use longitudinal acceleration setpoint for total energy control *\/\n\treturn updateFlightPathAngleAcceleration(flightPathAngle, flightPathAngleSp, airspeed,\n\t\t\taccelerationLongitudinalSp, mode, limitOverride);\n}\n\nint mTecs::updateFlightPathAngleAcceleration(float flightPathAngle, float flightPathAngleSp, float airspeed,\n\t\tfloat accelerationLongitudinalSp, tecs_mode mode, LimitOverride limitOverride)\n{\n\t\/* check if all input arguments are numbers and abort if not so *\/\n\tif (!isfinite(flightPathAngle) || !isfinite(flightPathAngleSp) ||\n\t\t\t!isfinite(airspeed) || !isfinite(accelerationLongitudinalSp) || !isfinite(mode)) {\n\t\treturn -1;\n\t}\n\t\/* time measurement *\/\n\tupdateTimeMeasurement();\n\n\t\/* update parameters first *\/\n\tupdateParams();\n\n\t\/* calculate values (energies) *\/\n\tfloat flightPathAngleError = flightPathAngleSp - flightPathAngle;\n\tfloat airspeedDerivative = 0.0f;\n\tif(_airspeedDerivative.getDt() > 0.0f) {\n\t\tairspeedDerivative = _airspeedDerivative.update(airspeed);\n\t}\n\tfloat airspeedDerivativeNorm = airspeedDerivative \/ CONSTANTS_ONE_G;\n\tfloat airspeedDerivativeSp = accelerationLongitudinalSp;\n\tfloat airspeedDerivativeNormSp = airspeedDerivativeSp \/ CONSTANTS_ONE_G;\n\tfloat airspeedDerivativeNormError = airspeedDerivativeNormSp - airspeedDerivativeNorm;\n\n\tfloat totalEnergyRate = flightPathAngle + airspeedDerivativeNorm;\n\tfloat totalEnergyRateError = flightPathAngleError + airspeedDerivativeNormError;\n\tfloat totalEnergyRateSp = flightPathAngleSp + airspeedDerivativeNormSp;\n\tfloat totalEnergyRateError2 = totalEnergyRateSp - totalEnergyRate;\n\n\tfloat energyDistributionRate = flightPathAngle - airspeedDerivativeNorm;\n\tfloat energyDistributionRateError = flightPathAngleError - airspeedDerivativeNormError;\n\tfloat energyDistributionRateSp = flightPathAngleSp - airspeedDerivativeNormSp;\n\tfloat energyDistributionRateError2 = energyDistributionRateSp - energyDistributionRate;\n\n\t\/* Debug output *\/\n\tif (_counter % 10 == 0) {\n\t\tdebug(\"totalEnergyRateSp %.2f, totalEnergyRate %.2f, totalEnergyRateError %.2f totalEnergyRateError2 %.2f airspeedDerivativeNorm %.4f\",\n\t\t\t\t(double)totalEnergyRateSp, (double)totalEnergyRate, (double)totalEnergyRateError, (double)totalEnergyRateError2, (double)airspeedDerivativeNorm);\n\t\tdebug(\"energyDistributionRateSp %.2f, energyDistributionRate %.2f, energyDistributionRateError %.2f energyDistributionRateError2 %.2f\",\n\t\t\t\t(double)energyDistributionRateSp, (double)energyDistributionRate, (double)energyDistributionRateError, (double)energyDistributionRateError2);\n\t}\n\n\t\/* Check airspeed: if below safe value switch to underspeed mode (if not in takeoff mode) *\/\n\tif (mode != TECS_MODE_LAND && airspeed < _airspeedMin.get()) {\n\t\tmode = TECS_MODE_UNDERSPEED;\n\t}\n\n\t\/* Set special ouput limiters if we are not in TECS_MODE_NORMAL *\/\n\tBlockOutputLimiter *outputLimiterThrottle = NULL; \/\/ NULL --> use standard inflight limits\n\tBlockOutputLimiter *outputLimiterPitch = NULL; \/\/ NULL --> use standard inflight limits\n\tif (mode == TECS_MODE_TAKEOFF) {\n\t\toutputLimiterThrottle = &_BlockOutputLimiterTakeoffThrottle; \/\/XXX: accept prelaunch values from launchdetector\n\t\toutputLimiterPitch = &_BlockOutputLimiterTakeoffPitch;\n\t} else if (mode == TECS_MODE_LAND) {\n\t\t\/\/ only limit pitch but do not limit throttle\n\t\toutputLimiterPitch = &_BlockOutputLimiterLandPitch;\n\t} else if (mode == TECS_MODE_LAND_THROTTLELIM) {\n\t\toutputLimiterThrottle = &_BlockOutputLimiterLandThrottle;\n\t\toutputLimiterPitch = &_BlockOutputLimiterLandPitch;\n\t} else if (mode == TECS_MODE_UNDERSPEED) {\n\t\toutputLimiterThrottle = &_BlockOutputLimiterUnderspeedThrottle;\n\t\toutputLimiterPitch = &_BlockOutputLimiterUnderspeedPitch;\n\t}\n\n\t\/* Apply overrride given by the limitOverride argument (this is used for limits which are not given by\n\t * parameters such as pitch limits with takeoff waypoints or throttle limits when the launchdetector\n\t * is running) *\/\n\tbool limitApplied = limitOverride.applyOverride(outputLimiterThrottle == NULL ?\n\t\t\t_controlTotalEnergy.getOutputLimiter() :\n\t\t\t*outputLimiterThrottle,\n\t\t\toutputLimiterPitch == NULL ?\n\t\t\t_controlEnergyDistribution.getOutputLimiter() :\n\t\t\t*outputLimiterPitch);\n\n\t\/* Write part of the status message *\/\n\t_status.airspeedDerivativeSp = airspeedDerivativeSp;\n\t_status.airspeedDerivative = airspeedDerivative;\n\t_status.totalEnergyRateSp = totalEnergyRateSp;\n\t_status.totalEnergyRate = totalEnergyRate;\n\t_status.energyDistributionRateSp = energyDistributionRateSp;\n\t_status.energyDistributionRate = energyDistributionRate;\n\t_status.mode = mode;\n\n\t\/** update control blocks **\/\n\t\/* update total energy rate control block *\/\n\t_throttleSp = _controlTotalEnergy.update(totalEnergyRateSp, totalEnergyRateError, outputLimiterThrottle);\n\n\t\/* update energy distribution rate control block *\/\n\t_pitchSp = _controlEnergyDistribution.update(energyDistributionRateSp, energyDistributionRateError, outputLimiterPitch);\n\n\n\tif (_counter % 10 == 0) {\n\t\tdebug(\"_throttleSp %.1f, _pitchSp %.1f, flightPathAngleSp %.1f, flightPathAngle %.1f accelerationLongitudinalSp %.1f, airspeedDerivative %.1f\",\n\t\t\t\t(double)_throttleSp, (double)_pitchSp,\n\t\t\t\t(double)flightPathAngleSp, (double)flightPathAngle,\n\t\t\t\t(double)accelerationLongitudinalSp, (double)airspeedDerivative);\n\t}\n\n\t\/* publish status messge *\/\n\t_status.update();\n\n\t\/* clean up *\/\n\t_firstIterationAfterReset = false;\n\t_dtCalculated = false;\n\n\t_counter++;\n\n\treturn 0;\n}\n\nvoid mTecs::resetIntegrators()\n{\n\t_controlTotalEnergy.getIntegral().setY(0.0f);\n\t_controlEnergyDistribution.getIntegral().setY(0.0f);\n\ttimestampLastIteration = hrt_absolute_time();\n\t_firstIterationAfterReset = true;\n}\n\nvoid mTecs::resetDerivatives(float airspeed)\n{\n\t_airspeedDerivative.setU(airspeed);\n}\n\n\nvoid mTecs::updateTimeMeasurement()\n{\n\tif (!_dtCalculated) {\n\t\tfloat deltaTSeconds = 0.0f;\n\t\tif (!_firstIterationAfterReset) {\n\t\t\thrt_abstime timestampNow = hrt_absolute_time();\n\t\t\tdeltaTSeconds = (float)(timestampNow - timestampLastIteration) * 1e-6f;\n\t\t\ttimestampLastIteration = timestampNow;\n\t\t}\n\t\tsetDt(deltaTSeconds);\n\n\t\t_dtCalculated = true;\n\t}\n}\n\nvoid mTecs::debug_print(const char *fmt, va_list args)\n{\n\tfprintf(stderr, \"%s: \", \"[mtecs]\");\n\tvfprintf(stderr, fmt, args);\n\n\tfprintf(stderr, \"\\n\");\n}\n\nvoid mTecs::debug(const char *fmt, ...) {\n\n\tif (!_debug) {\n\t\treturn;\n\t}\n\n\tva_list args;\n\n\tva_start(args, fmt);\n\tdebug_print(fmt, args);\n}\n\nbool mTecs::LimitOverride::applyOverride(BlockOutputLimiter &outputLimiterThrottle,\n\t\tBlockOutputLimiter &outputLimiterPitch)\n{\n\tbool ret = false;\n\n\tif (overrideThrottleMinEnabled)\t{\n\t\toutputLimiterThrottle.setMin(overrideThrottleMin);\n\t\tret = true;\n\t}\n\tif (overrideThrottleMaxEnabled)\t{\n\t\toutputLimiterThrottle.setMax(overrideThrottleMax);\n\t\tret = true;\n\t}\n\tif (overridePitchMinEnabled)\t{\n\t\toutputLimiterPitch.setMin(overridePitchMin);\n\t\tret = true;\n\t}\n\tif (overridePitchMaxEnabled)\t{\n\t\toutputLimiterPitch.setMax(overridePitchMax);\n\t\tret = true;\n\t}\n\n\treturn ret;\n}\n\n} \/* namespace fwPosctrl *\/\n<|endoftext|>"} {"text":"<commit_before>\/*\n Copyright 2012 Frederik Gladhorn <gladhorn@kde.org>\n\n This library is free software; you can redistribute it and\/or\n modify it under the terms of the GNU Lesser General Public\n License as published by the Free Software Foundation; either\n version 2.1 of the License, or (at your option) version 3, or any\n later version accepted by the membership of KDE e.V. (or its\n successor approved by the membership of KDE e.V.), which shall\n act as a proxy defined in Section 6 of version 3 of the license.\n\n This library is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n Lesser General Public License for more details.\n\n You should have received a copy of the GNU Lesser General Public\n License along with this library. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n*\/\n\n#include \"accessibleobject.h\"\n\n#include <qstring.h>\n#include <qdebug.h>\n\n#include \"accessibleobject_p.h\"\n#include \"registry_p.h\"\n\n#include <atspi\/atspi-constants.h>\n\nusing namespace QAccessibleClient;\n\nAccessibleObject::AccessibleObject()\n :d(0)\n{\n}\n\nAccessibleObject::AccessibleObject(RegistryPrivate *registryPrivate, const QString &service, const QString &path)\n :d(0)\n{\n Q_ASSERT(registryPrivate);\n Q_ASSERT(!service.isEmpty());\n Q_ASSERT(!path.isEmpty());\n if (registryPrivate->m_cacheStrategy) {\n const QString id = path + service;\n d = registryPrivate->m_cacheStrategy->get(id);\n if (!d) {\n d = QSharedPointer<AccessibleObjectPrivate>(new AccessibleObjectPrivate(registryPrivate, service, path));\n registryPrivate->m_cacheStrategy->add(id, d);\n }\n } else {\n d = QSharedPointer<AccessibleObjectPrivate>(new AccessibleObjectPrivate(registryPrivate, service, path));\n }\n}\n\nAccessibleObject::AccessibleObject(const QSharedPointer<AccessibleObjectPrivate> &dd)\n :d(dd)\n{\n}\n\nAccessibleObject::AccessibleObject(const AccessibleObject &other)\n : d(other.d)\n{\n}\n\nAccessibleObject::~AccessibleObject()\n{\n}\n\nQString AccessibleObject::id() const\n{\n if (!d || !d->registryPrivate)\n return QString();\n return d->path + d->service;\n}\n\nQUrl AccessibleObject::url() const\n{\n return d && d->registryPrivate ? d->registryPrivate->url(*this) : QUrl();\n}\n\nbool AccessibleObject::isValid() const\n{\n return d && d->registryPrivate\n && (!d->service.isEmpty())\n && (!d->path.isEmpty())\n && (d->path != QLatin1String(\"\/org\/a11y\/atspi\/null\"));\n}\n\nAccessibleObject &AccessibleObject::operator=(const AccessibleObject &other)\n{\n d = other.d;\n return *this;\n}\n\nbool AccessibleObject::operator==(const AccessibleObject &other) const\n{\n return (d == other.d) || (d && other.d && *d == *other.d);\n}\n\nRegistryPrivate* AccessibleObject::registryPrivate() const\n{\n return d ? d->registryPrivate : 0;\n}\n\nQSharedPointer<AccessibleObjectPrivate> AccessibleObject::objectPrivate() const\n{\n return d;\n}\n\nAccessibleObject AccessibleObject::parent() const\n{\n return d->registryPrivate->parentAccessible(*this);\n}\n\nQList<AccessibleObject> AccessibleObject::children() const\n{\n return d->registryPrivate->children(*this);\n}\n\nint AccessibleObject::childCount() const\n{\n return d->registryPrivate->childCount(*this);\n}\n\nAccessibleObject AccessibleObject::child(int index) const\n{\n return d->registryPrivate->child(*this, index);\n}\n\nint AccessibleObject::indexInParent() const\n{\n return d->registryPrivate->indexInParent(*this);\n}\n\nQString AccessibleObject::name() const\n{\n return d->registryPrivate->name(*this);\n}\n\nQString AccessibleObject::description() const\n{\n return d->registryPrivate->description(*this);\n}\n\nAccessibleObject::Role AccessibleObject::role() const\n{\n return d->registryPrivate->role(*this);\n}\n\nQString AccessibleObject::roleName() const\n{\n return d->registryPrivate->roleName(*this);\n}\n\nQString AccessibleObject::localizedRoleName() const\n{\n return d->registryPrivate->localizedRoleName(*this);\n}\n\nint AccessibleObject::layer() const\n{\n return d->registryPrivate->layer(*this);\n}\n\nint AccessibleObject::mdiZOrder() const\n{\n return d->registryPrivate->mdiZOrder(*this);\n}\n\ndouble AccessibleObject::alpha() const\n{\n return d->registryPrivate->alpha(*this);\n}\n\nQRect AccessibleObject::boundingRect() const\n{\n if( supportedInterfaces() & AccessibleObject::ComponentInterface ){\n return d->registryPrivate->boundingRect(*this);\n } else {\n qWarning() << \"boundingRect called on accessible that does not implement component\";\n return QRect();\n }\n}\n\nQRect AccessibleObject::characterRect(int offset) const\n{\n if( supportedInterfaces() & AccessibleObject::TextInterface ){\n return d->registryPrivate->characterRect(*this, offset);\n } else {\n qWarning() << \"characterRect called on accessible that does not implement text\";\n return QRect();\n }\n}\n\nAccessibleObject::Interfaces AccessibleObject::supportedInterfaces() const\n{\n return d->registryPrivate->supportedInterfaces(*this);\n}\n\nint AccessibleObject::caretOffset() const\n{\n if( supportedInterfaces() & AccessibleObject::TextInterface ){\n return d->registryPrivate->caretOffset(*this);\n } else {\n qWarning() << \"caretOffset called on accessible that does not implement text\";\n return 0;\n }\n}\n\nQPoint AccessibleObject::focusPoint() const\n{\n Interfaces ifaces = supportedInterfaces();\n if (ifaces & TextInterface) {\n int offset = caretOffset();\n QRect r = characterRect(offset);\n if (!r.isNull())\n return r.center();\n }\n if (ifaces & ComponentInterface) {\n QRect r = boundingRect();\n if (!r.isNull())\n return r.center();\n }\n AccessibleObject p = parent();\n if (p.isValid())\n return p.focusPoint(); \/\/ recursive\n return QPoint();\n}\n\nAccessibleObject AccessibleObject::application() const\n{\n return d->registryPrivate->application(*this);\n}\n\nQString AccessibleObject::appToolkitName() const\n{\n return d->registryPrivate->appToolkitName(*this);\n}\n\nQString AccessibleObject::appVersion() const\n{\n return d->registryPrivate->appVersion(*this);\n}\n\nint AccessibleObject::appId() const\n{\n return d->registryPrivate->appId(*this);\n}\n\nQString AccessibleObject::appLocale(LocaleType lctype) const\n{\n return d->registryPrivate->appLocale(*this, lctype);\n}\n\nQString AccessibleObject::appBusAddress() const\n{\n return d->registryPrivate->appBusAddress(*this);\n}\n\ndouble AccessibleObject::minimumValue() const\n{\n return d->registryPrivate->minimumValue(*this);\n}\n\ndouble AccessibleObject::maximumValue() const\n{\n return d->registryPrivate->maximumValue(*this);\n}\n\ndouble AccessibleObject::minimumValueIncrement() const\n{\n return d->registryPrivate->minimumValueIncrement(*this);\n}\n\ndouble AccessibleObject::currentValue() const\n{\n return d->registryPrivate->currentValue(*this);\n}\n\nQList<AccessibleObject> AccessibleObject::selection() const\n{\n return d->registryPrivate->selection(*this);\n}\n\nQString AccessibleObject::imageDescription() const\n{\n return d->registryPrivate->imageDescription(*this);\n}\n\nQString AccessibleObject::imageLocale() const\n{\n return d->registryPrivate->imageLocale(*this);\n}\n\nQRect AccessibleObject::imageRect() const\n{\n return d->registryPrivate->imageRect(*this);\n}\n\nQVector< QSharedPointer<QAction> > AccessibleObject::actions() const\n{\n \/\/ Actions in atspi are supposed to be static what means they cannot change in\n \/\/ between (e.g. actions removed or added or edited) so we can safely just\n \/\/ fetch them only once and store the result for the life-time of the object,\n if (!d->actionsFetched) {\n d->actionsFetched = true;\n d->actions = d->registryPrivate->actions(*this);\n }\n return d->actions;\n}\n\nbool AccessibleObject::hasSelectableText() const\n{\n return d->registryPrivate->state(*this) & (quint64(1) << ATSPI_STATE_SELECTABLE_TEXT);\n}\n\nbool AccessibleObject::hasToolTip() const\n{\n return d->registryPrivate->state(*this) & (quint64(1) << ATSPI_STATE_HAS_TOOLTIP);\n}\n\nbool AccessibleObject::isActive() const\n{\n return d->registryPrivate->state(*this) & (quint64(1) << ATSPI_STATE_ACTIVE);\n}\n\nbool AccessibleObject::isCheckable() const\n{\n \/\/FIXME: Find better AccessibleObject::isCheckable\n \/\/return d->registryPrivate->state(*this) & (quint64(1) << ATSPI_STATE_);\n\n Role role = d->registryPrivate->role(*this);\n if (role == AccessibleObject::CheckBox ||\n role == AccessibleObject::CheckableMenuItem ||\n role == AccessibleObject::RadioButton ||\n role == AccessibleObject::RadioMenuItem ||\n role == AccessibleObject::ToggleButton)\n return true;\n return false;\n}\n\nbool AccessibleObject::isChecked() const\n{\n return d->registryPrivate->state(*this) & (quint64(1) << ATSPI_STATE_CHECKED);\n}\n\nbool AccessibleObject::isDefunct() const\n{\n return d->defunct;\n}\n\nbool AccessibleObject::isDefault() const\n{\n return d->registryPrivate->state(*this) & (quint64(1) << ATSPI_STATE_IS_DEFAULT);\n}\n\nbool AccessibleObject::isEditable() const\n{\n return d->registryPrivate->state(*this) & (quint64(1) << ATSPI_STATE_EDITABLE);\n}\n\nbool AccessibleObject::isEnabled() const\n{\n return d->registryPrivate->state(*this) & (quint64(1) << ATSPI_STATE_ENABLED);\n}\n\nbool AccessibleObject::isExpandable() const\n{\n return d->registryPrivate->state(*this) & (quint64(1) << ATSPI_STATE_EXPANDABLE);\n}\n\nbool AccessibleObject::isExpanded() const\n{\n return d->registryPrivate->state(*this) & (quint64(1) << ATSPI_STATE_EXPANDED);\n}\n\nbool AccessibleObject::isFocusable() const\n{\n return d->registryPrivate->state(*this) & (quint64(1) << ATSPI_STATE_FOCUSABLE);\n}\n\nbool AccessibleObject::isFocused() const\n{\n return d->registryPrivate->state(*this) & (quint64(1) << ATSPI_STATE_FOCUSED);\n}\n\nbool AccessibleObject::isMultiLine() const\n{\n return d->registryPrivate->state(*this) & (quint64(1) << ATSPI_STATE_MULTI_LINE);\n}\n\nbool AccessibleObject::isSelectable() const\n{\n return d->registryPrivate->state(*this) & (quint64(1) << ATSPI_STATE_SELECTABLE);\n}\n\nbool AccessibleObject::isSelected() const\n{\n return d->registryPrivate->state(*this) & (quint64(1) << ATSPI_STATE_SELECTED);\n}\n\nbool AccessibleObject::isSensitive() const\n{\n return d->registryPrivate->state(*this) & (quint64(1) << ATSPI_STATE_SENSITIVE);\n}\n\nbool AccessibleObject::isSingleLine() const\n{\n return d->registryPrivate->state(*this) & (quint64(1) << ATSPI_STATE_SINGLE_LINE);\n}\n\nbool AccessibleObject::isVisible() const\n{\n return d->registryPrivate->state(*this) & (quint64(1) << ATSPI_STATE_VISIBLE);\n}\n\nbool AccessibleObject::supportsAutocompletion() const\n{\n return d->registryPrivate->state(*this) & (quint64(1) << ATSPI_STATE_SUPPORTS_AUTOCOMPLETION);\n}\n\n#ifndef QT_NO_DEBUG_STREAM\nQACCESSIBILITYCLIENT_EXPORT QDebug QAccessibleClient::operator<<(QDebug d, const AccessibleObject &object)\n{\n d.nospace();\n d << \"AccessibleObject(\"; \/\/d:\" << hex << (void *) object.d << dec;\n d << \"service=\" << object.d->service;\n d << \" path=\" << object.d->path;\n d << \")\";\n return d.space();\n}\n#endif\n\nuint qHash(const QAccessibleClient::AccessibleObject& object) {\n return qHash(object.d);\n}\n<commit_msg>For the focus it's ok if width is zero.<commit_after>\/*\n Copyright 2012 Frederik Gladhorn <gladhorn@kde.org>\n\n This library is free software; you can redistribute it and\/or\n modify it under the terms of the GNU Lesser General Public\n License as published by the Free Software Foundation; either\n version 2.1 of the License, or (at your option) version 3, or any\n later version accepted by the membership of KDE e.V. (or its\n successor approved by the membership of KDE e.V.), which shall\n act as a proxy defined in Section 6 of version 3 of the license.\n\n This library is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n Lesser General Public License for more details.\n\n You should have received a copy of the GNU Lesser General Public\n License along with this library. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n*\/\n\n#include \"accessibleobject.h\"\n\n#include <qstring.h>\n#include <qdebug.h>\n\n#include \"accessibleobject_p.h\"\n#include \"registry_p.h\"\n\n#include <atspi\/atspi-constants.h>\n\nusing namespace QAccessibleClient;\n\nAccessibleObject::AccessibleObject()\n :d(0)\n{\n}\n\nAccessibleObject::AccessibleObject(RegistryPrivate *registryPrivate, const QString &service, const QString &path)\n :d(0)\n{\n Q_ASSERT(registryPrivate);\n Q_ASSERT(!service.isEmpty());\n Q_ASSERT(!path.isEmpty());\n if (registryPrivate->m_cacheStrategy) {\n const QString id = path + service;\n d = registryPrivate->m_cacheStrategy->get(id);\n if (!d) {\n d = QSharedPointer<AccessibleObjectPrivate>(new AccessibleObjectPrivate(registryPrivate, service, path));\n registryPrivate->m_cacheStrategy->add(id, d);\n }\n } else {\n d = QSharedPointer<AccessibleObjectPrivate>(new AccessibleObjectPrivate(registryPrivate, service, path));\n }\n}\n\nAccessibleObject::AccessibleObject(const QSharedPointer<AccessibleObjectPrivate> &dd)\n :d(dd)\n{\n}\n\nAccessibleObject::AccessibleObject(const AccessibleObject &other)\n : d(other.d)\n{\n}\n\nAccessibleObject::~AccessibleObject()\n{\n}\n\nQString AccessibleObject::id() const\n{\n if (!d || !d->registryPrivate)\n return QString();\n return d->path + d->service;\n}\n\nQUrl AccessibleObject::url() const\n{\n return d && d->registryPrivate ? d->registryPrivate->url(*this) : QUrl();\n}\n\nbool AccessibleObject::isValid() const\n{\n return d && d->registryPrivate\n && (!d->service.isEmpty())\n && (!d->path.isEmpty())\n && (d->path != QLatin1String(\"\/org\/a11y\/atspi\/null\"));\n}\n\nAccessibleObject &AccessibleObject::operator=(const AccessibleObject &other)\n{\n d = other.d;\n return *this;\n}\n\nbool AccessibleObject::operator==(const AccessibleObject &other) const\n{\n return (d == other.d) || (d && other.d && *d == *other.d);\n}\n\nRegistryPrivate* AccessibleObject::registryPrivate() const\n{\n return d ? d->registryPrivate : 0;\n}\n\nQSharedPointer<AccessibleObjectPrivate> AccessibleObject::objectPrivate() const\n{\n return d;\n}\n\nAccessibleObject AccessibleObject::parent() const\n{\n return d->registryPrivate->parentAccessible(*this);\n}\n\nQList<AccessibleObject> AccessibleObject::children() const\n{\n return d->registryPrivate->children(*this);\n}\n\nint AccessibleObject::childCount() const\n{\n return d->registryPrivate->childCount(*this);\n}\n\nAccessibleObject AccessibleObject::child(int index) const\n{\n return d->registryPrivate->child(*this, index);\n}\n\nint AccessibleObject::indexInParent() const\n{\n return d->registryPrivate->indexInParent(*this);\n}\n\nQString AccessibleObject::name() const\n{\n return d->registryPrivate->name(*this);\n}\n\nQString AccessibleObject::description() const\n{\n return d->registryPrivate->description(*this);\n}\n\nAccessibleObject::Role AccessibleObject::role() const\n{\n return d->registryPrivate->role(*this);\n}\n\nQString AccessibleObject::roleName() const\n{\n return d->registryPrivate->roleName(*this);\n}\n\nQString AccessibleObject::localizedRoleName() const\n{\n return d->registryPrivate->localizedRoleName(*this);\n}\n\nint AccessibleObject::layer() const\n{\n return d->registryPrivate->layer(*this);\n}\n\nint AccessibleObject::mdiZOrder() const\n{\n return d->registryPrivate->mdiZOrder(*this);\n}\n\ndouble AccessibleObject::alpha() const\n{\n return d->registryPrivate->alpha(*this);\n}\n\nQRect AccessibleObject::boundingRect() const\n{\n if( supportedInterfaces() & AccessibleObject::ComponentInterface ){\n return d->registryPrivate->boundingRect(*this);\n } else {\n qWarning() << \"boundingRect called on accessible that does not implement component\";\n return QRect();\n }\n}\n\nQRect AccessibleObject::characterRect(int offset) const\n{\n if( supportedInterfaces() & AccessibleObject::TextInterface ){\n return d->registryPrivate->characterRect(*this, offset);\n } else {\n qWarning() << \"characterRect called on accessible that does not implement text\";\n return QRect();\n }\n}\n\nAccessibleObject::Interfaces AccessibleObject::supportedInterfaces() const\n{\n return d->registryPrivate->supportedInterfaces(*this);\n}\n\nint AccessibleObject::caretOffset() const\n{\n if( supportedInterfaces() & AccessibleObject::TextInterface ){\n return d->registryPrivate->caretOffset(*this);\n } else {\n qWarning() << \"caretOffset called on accessible that does not implement text\";\n return 0;\n }\n}\n\nQPoint AccessibleObject::focusPoint() const\n{\n Interfaces ifaces = supportedInterfaces();\n if (ifaces & TextInterface) {\n int offset = caretOffset();\n QRect r = characterRect(offset);\n if (r.x() != 0 || r.y() != 0)\n return r.center();\n }\n if (ifaces & ComponentInterface) {\n QRect r = boundingRect();\n if (!r.isNull())\n return r.center();\n }\n AccessibleObject p = parent();\n if (p.isValid())\n return p.focusPoint(); \/\/ recursive\n return QPoint();\n}\n\nAccessibleObject AccessibleObject::application() const\n{\n return d->registryPrivate->application(*this);\n}\n\nQString AccessibleObject::appToolkitName() const\n{\n return d->registryPrivate->appToolkitName(*this);\n}\n\nQString AccessibleObject::appVersion() const\n{\n return d->registryPrivate->appVersion(*this);\n}\n\nint AccessibleObject::appId() const\n{\n return d->registryPrivate->appId(*this);\n}\n\nQString AccessibleObject::appLocale(LocaleType lctype) const\n{\n return d->registryPrivate->appLocale(*this, lctype);\n}\n\nQString AccessibleObject::appBusAddress() const\n{\n return d->registryPrivate->appBusAddress(*this);\n}\n\ndouble AccessibleObject::minimumValue() const\n{\n return d->registryPrivate->minimumValue(*this);\n}\n\ndouble AccessibleObject::maximumValue() const\n{\n return d->registryPrivate->maximumValue(*this);\n}\n\ndouble AccessibleObject::minimumValueIncrement() const\n{\n return d->registryPrivate->minimumValueIncrement(*this);\n}\n\ndouble AccessibleObject::currentValue() const\n{\n return d->registryPrivate->currentValue(*this);\n}\n\nQList<AccessibleObject> AccessibleObject::selection() const\n{\n return d->registryPrivate->selection(*this);\n}\n\nQString AccessibleObject::imageDescription() const\n{\n return d->registryPrivate->imageDescription(*this);\n}\n\nQString AccessibleObject::imageLocale() const\n{\n return d->registryPrivate->imageLocale(*this);\n}\n\nQRect AccessibleObject::imageRect() const\n{\n return d->registryPrivate->imageRect(*this);\n}\n\nQVector< QSharedPointer<QAction> > AccessibleObject::actions() const\n{\n \/\/ Actions in atspi are supposed to be static what means they cannot change in\n \/\/ between (e.g. actions removed or added or edited) so we can safely just\n \/\/ fetch them only once and store the result for the life-time of the object,\n if (!d->actionsFetched) {\n d->actionsFetched = true;\n d->actions = d->registryPrivate->actions(*this);\n }\n return d->actions;\n}\n\nbool AccessibleObject::hasSelectableText() const\n{\n return d->registryPrivate->state(*this) & (quint64(1) << ATSPI_STATE_SELECTABLE_TEXT);\n}\n\nbool AccessibleObject::hasToolTip() const\n{\n return d->registryPrivate->state(*this) & (quint64(1) << ATSPI_STATE_HAS_TOOLTIP);\n}\n\nbool AccessibleObject::isActive() const\n{\n return d->registryPrivate->state(*this) & (quint64(1) << ATSPI_STATE_ACTIVE);\n}\n\nbool AccessibleObject::isCheckable() const\n{\n \/\/FIXME: Find better AccessibleObject::isCheckable\n \/\/return d->registryPrivate->state(*this) & (quint64(1) << ATSPI_STATE_);\n\n Role role = d->registryPrivate->role(*this);\n if (role == AccessibleObject::CheckBox ||\n role == AccessibleObject::CheckableMenuItem ||\n role == AccessibleObject::RadioButton ||\n role == AccessibleObject::RadioMenuItem ||\n role == AccessibleObject::ToggleButton)\n return true;\n return false;\n}\n\nbool AccessibleObject::isChecked() const\n{\n return d->registryPrivate->state(*this) & (quint64(1) << ATSPI_STATE_CHECKED);\n}\n\nbool AccessibleObject::isDefunct() const\n{\n return d->defunct;\n}\n\nbool AccessibleObject::isDefault() const\n{\n return d->registryPrivate->state(*this) & (quint64(1) << ATSPI_STATE_IS_DEFAULT);\n}\n\nbool AccessibleObject::isEditable() const\n{\n return d->registryPrivate->state(*this) & (quint64(1) << ATSPI_STATE_EDITABLE);\n}\n\nbool AccessibleObject::isEnabled() const\n{\n return d->registryPrivate->state(*this) & (quint64(1) << ATSPI_STATE_ENABLED);\n}\n\nbool AccessibleObject::isExpandable() const\n{\n return d->registryPrivate->state(*this) & (quint64(1) << ATSPI_STATE_EXPANDABLE);\n}\n\nbool AccessibleObject::isExpanded() const\n{\n return d->registryPrivate->state(*this) & (quint64(1) << ATSPI_STATE_EXPANDED);\n}\n\nbool AccessibleObject::isFocusable() const\n{\n return d->registryPrivate->state(*this) & (quint64(1) << ATSPI_STATE_FOCUSABLE);\n}\n\nbool AccessibleObject::isFocused() const\n{\n return d->registryPrivate->state(*this) & (quint64(1) << ATSPI_STATE_FOCUSED);\n}\n\nbool AccessibleObject::isMultiLine() const\n{\n return d->registryPrivate->state(*this) & (quint64(1) << ATSPI_STATE_MULTI_LINE);\n}\n\nbool AccessibleObject::isSelectable() const\n{\n return d->registryPrivate->state(*this) & (quint64(1) << ATSPI_STATE_SELECTABLE);\n}\n\nbool AccessibleObject::isSelected() const\n{\n return d->registryPrivate->state(*this) & (quint64(1) << ATSPI_STATE_SELECTED);\n}\n\nbool AccessibleObject::isSensitive() const\n{\n return d->registryPrivate->state(*this) & (quint64(1) << ATSPI_STATE_SENSITIVE);\n}\n\nbool AccessibleObject::isSingleLine() const\n{\n return d->registryPrivate->state(*this) & (quint64(1) << ATSPI_STATE_SINGLE_LINE);\n}\n\nbool AccessibleObject::isVisible() const\n{\n return d->registryPrivate->state(*this) & (quint64(1) << ATSPI_STATE_VISIBLE);\n}\n\nbool AccessibleObject::supportsAutocompletion() const\n{\n return d->registryPrivate->state(*this) & (quint64(1) << ATSPI_STATE_SUPPORTS_AUTOCOMPLETION);\n}\n\n#ifndef QT_NO_DEBUG_STREAM\nQACCESSIBILITYCLIENT_EXPORT QDebug QAccessibleClient::operator<<(QDebug d, const AccessibleObject &object)\n{\n d.nospace();\n d << \"AccessibleObject(\"; \/\/d:\" << hex << (void *) object.d << dec;\n d << \"service=\" << object.d->service;\n d << \" path=\" << object.d->path;\n d << \")\";\n return d.space();\n}\n#endif\n\nuint qHash(const QAccessibleClient::AccessibleObject& object) {\n return qHash(object.d);\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/=======================================================================\n\/\/ Copyright 2014-2015 David Simmons-Duffin.\n\/\/ Distributed under the MIT License.\n\/\/ (See accompanying file LICENSE or copy at\n\/\/ http:\/\/opensource.org\/licenses\/MIT)\n\/\/=======================================================================\n\n\/\/ See the manual for a description of the correct XML input format.\n\n#include \"parse_append_many.hxx\"\n\n#include \"..\/Polynomial.hxx\"\n#include \"..\/SDP.hxx\"\n\n#include <boost\/filesystem.hpp>\n#include <boost\/property_tree\/xml_parser.hpp>\n\nstd::vector<Real> parse_vector(const boost::property_tree::ptree &tree);\n\nPolynomial_Vector_Matrix\nparse_polynomial_vector_matrix(const boost::property_tree::ptree &tree);\n\nSDP read_bootstrap_sdp(const std::vector<boost::filesystem::path> sdp_files)\n{\n Vector objective;\n std::vector<Polynomial_Vector_Matrix> polynomialVectorMatrices;\n for(auto &sdp_file : sdp_files)\n {\n {\n boost::property_tree::ptree tree;\n boost::property_tree::read_xml(sdp_file.string(), tree);\n\n const auto sdp = tree.get_child(\"sdp\");\n auto objective_iterator(sdp.find(\"objective\"));\n \/\/\/ boost::property_tree uses not_found() instead of end() :(\n if(objective_iterator != sdp.not_found())\n { objective = parse_vector(objective_iterator->second); }\n\n auto polynomialVectorMatrices_iterator(\n sdp.find(\"polynomialVectorMatrices\"));\n if(polynomialVectorMatrices_iterator != sdp.not_found())\n {\n parse_append_many(\"polynomialVectorMatrix\",\n parse_polynomial_vector_matrix,\n polynomialVectorMatrices_iterator->second,\n polynomialVectorMatrices);\n }\n }\n }\n return bootstrapSDP(objective, polynomialVectorMatrices);\n}\n<commit_msg>Reindent<commit_after>\/\/=======================================================================\n\/\/ Copyright 2014-2015 David Simmons-Duffin.\n\/\/ Distributed under the MIT License.\n\/\/ (See accompanying file LICENSE or copy at\n\/\/ http:\/\/opensource.org\/licenses\/MIT)\n\/\/=======================================================================\n\n\/\/ See the manual for a description of the correct XML input format.\n\n#include \"parse_append_many.hxx\"\n\n#include \"..\/Polynomial.hxx\"\n#include \"..\/SDP.hxx\"\n\n#include <boost\/filesystem.hpp>\n#include <boost\/property_tree\/xml_parser.hpp>\n\nstd::vector<Real> parse_vector(const boost::property_tree::ptree &tree);\n\nPolynomial_Vector_Matrix\nparse_polynomial_vector_matrix(const boost::property_tree::ptree &tree);\n\nSDP read_bootstrap_sdp(const std::vector<boost::filesystem::path> sdp_files)\n{\n Vector objective;\n std::vector<Polynomial_Vector_Matrix> polynomialVectorMatrices;\n for(auto &sdp_file : sdp_files)\n {\n boost::property_tree::ptree tree;\n boost::property_tree::read_xml(sdp_file.string(), tree);\n\n const auto sdp = tree.get_child(\"sdp\");\n auto objective_iterator(sdp.find(\"objective\"));\n \/\/\/ boost::property_tree uses not_found() instead of end() :(\n if(objective_iterator != sdp.not_found())\n {\n objective = parse_vector(objective_iterator->second);\n }\n\n auto polynomialVectorMatrices_iterator(\n sdp.find(\"polynomialVectorMatrices\"));\n if(polynomialVectorMatrices_iterator != sdp.not_found())\n {\n parse_append_many(\n \"polynomialVectorMatrix\", parse_polynomial_vector_matrix,\n polynomialVectorMatrices_iterator->second, polynomialVectorMatrices);\n }\n }\n return bootstrapSDP(objective, polynomialVectorMatrices);\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ time_t_decoder.cpp --- pretty print time_t values\n\/\/ Author: Dan Harms <enniomore@icloud.com>\n\/\/ Created: Thursday, July 2, 2015\n\/\/ Modified Time-stamp: <2022-07-21 14:33:39 dharms>\n\/\/ Modified by: Dan Harms\n\n#include <iostream>\n#include <iomanip>\n#include <ctime>\n\nint main(int argc, char* argv[])\n{\n if (argc < 1)\n {\n return EXIT_FAILURE;\n }\n time_t when;\n if (argc == 1)\n {\n when = std::time(nullptr);\n }\n else\n {\n long long val = std::atoll(argv[1]);\n static const long long secs = 10000000000;\n static const long long nanos = 1000000000;\n if (val > secs)\n {\n val \/= nanos;\n }\n when = val;\n }\n\n std::cout << std::put_time(std::gmtime(&when), \"%c %Z\")\n << \" \/ \"\n << std::put_time(std::localtime(&when), \"%c %Z\")\n << std::endl;\n\n return EXIT_SUCCESS;;\n}\n\n\/\/ code ends here\n<commit_msg>fix small typo in src file<commit_after>\/\/ time_t_decoder.cpp --- pretty print time_t values\n\/\/ Author: Dan Harms <enniomore@icloud.com>\n\/\/ Created: Thursday, July 2, 2015\n\/\/ Modified Time-stamp: <2022-10-12 21:56:53 dharms>\n\/\/ Modified by: Dan Harms\n\n#include <iostream>\n#include <iomanip>\n#include <ctime>\n\nint main(int argc, char* argv[])\n{\n if (argc < 1)\n {\n return EXIT_FAILURE;\n }\n time_t when;\n if (argc == 1)\n {\n when = std::time(nullptr);\n }\n else\n {\n long long val = std::atoll(argv[1]);\n static const long long secs = 10000000000;\n static const long long nanos = 1000000000;\n if (val > secs)\n {\n val \/= nanos;\n }\n when = val;\n }\n\n std::cout << std::put_time(std::gmtime(&when), \"%c %Z\")\n << \" \/ \"\n << std::put_time(std::localtime(&when), \"%c %Z\")\n << std::endl;\n\n return EXIT_SUCCESS;\n}\n\n\/\/ code ends here\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (C) 2008-2011, Gostai S.A.S.\n *\n * This software is provided \"as is\" without warranty of any kind,\n * either expressed or implied, including but not limited to the\n * implied warranties of fitness for a particular purpose.\n *\n * See the LICENSE file for more information.\n *\/\n\n#include <iostream>\n\n#include <boost\/thread\/tss.hpp>\n\n#include <libport\/cassert>\n#include <libport\/containers.hh>\n#include <libport\/cstdio>\n#include <libport\/debug.hh>\n#include <libport\/escape.hh>\n#include <libport\/fnmatch.h>\n#include <libport\/foreach.hh>\n#include <libport\/format.hh>\n#include <libport\/ip-semaphore.hh>\n#include <libport\/lockable.hh>\n#include <libport\/pthread.h>\n#include <libport\/thread-data.hh>\n#include <libport\/tokenizer.hh>\n#include <libport\/unistd.h>\n#include <libport\/utime.hh>\n#include <libport\/windows.hh>\n#include <sched\/coroutine-data.hh>\n\n#ifndef WIN32\n# include <syslog.h>\n#endif\n\n#ifndef LIBPORT_DEBUG_DISABLE\n\nGD_CATEGORY(Libport.Debug);\n\nnamespace libport\n{\n LIBPORT_API boost::function0<local_data&> debugger_data;\n LIBPORT_API Debug* debugger = 0;\n LIBPORT_API Debug::levels::Level Debug::filter_(levels::log);\n\n local_data&\n debugger_data_thread_local()\n {\n static boost::thread_specific_ptr<local_data> storage;\n if (!storage.get())\n storage.reset(new local_data);\n return *storage;\n }\n\n\n local_data::local_data()\n : indent(0)\n {}\n\n\n namespace debug\n {\n \/\/ Wether categories are enabled by default.\n static bool default_category_state = true;\n\n LIBPORT_API void\n uninitialized_msg(const std::string& msg)\n {\n static bool warned = false;\n if (!warned)\n {\n std::cerr << \"[Libport.Debug] Uninitialized debug, fallback to stderr.\" << std::endl;\n warned = true;\n }\n std::cerr << \"[Libport.Debug] \" << msg << std::endl;\n }\n\n \/\/ Categories added so far.\n categories_type&\n categories()\n {\n static categories_type categories;\n return categories;\n }\n\n static unsigned\n current_pattern()\n {\n static unsigned current = 0;\n return current++;\n }\n\n \/\/ Patterns added so far.\n patterns_type&\n patterns()\n {\n static patterns_type patterns;\n return patterns;\n }\n\n \/\/ Maximum category width.\n size_t&\n categories_largest()\n {\n static size_t res = 0;\n return res;\n }\n\n \/\/ Add a new category, look if it matches a pattern.\n Symbol\n add_category(Symbol name)\n {\n int order = -1;\n bool value = default_category_state;\n foreach (patterns_type::value_type& s, patterns())\n {\n if (fnmatch(s.first.name_get(), name.name_get()) == 0)\n {\n if (int(s.second.second) > order)\n {\n value = s.second.first;\n order = s.second.second;\n }\n }\n }\n\n categories()[name] = value;\n\n size_t size = name.name_get().size();\n if (categories_largest() < size)\n categories_largest() = size;\n\n return name;\n }\n\n \/\/ Add a new category pattern.\n int\n enable_category(Symbol pattern)\n {\n patterns()[pattern] = std::make_pair(true, current_pattern());\n foreach (categories_type::value_type& s, categories())\n {\n if (fnmatch(pattern.name_get(), s.first.name_get()) == 0)\n s.second = true;\n }\n\n return 42;\n }\n\n \/\/ Disable a new category pattern.\n int\n disable_category(Symbol pattern)\n {\n patterns()[pattern] = std::make_pair(false, current_pattern());\n foreach (categories_type::value_type& s, categories())\n {\n if (fnmatch(pattern.name_get(), s.first.name_get()) == 0)\n s.second = false;\n }\n\n return 42;\n }\n\n \/\/ Enable\/Disable a new category pattern with modifier.\n int\n auto_category(Symbol pattern)\n {\n std::string p = pattern.name_get();\n char modifier = p[0];\n if (modifier == '+' || modifier == '-')\n p = p.substr(1);\n else\n modifier = '+';\n bool value = modifier == '+';\n\n patterns()[Symbol(p)] = std::make_pair(value, current_pattern());\n foreach (categories_type::value_type& s, categories())\n {\n if (fnmatch(p, s.first.name_get()) == 0)\n s.second = value;\n }\n\n return 42;\n }\n\n bool test_category(Symbol name)\n {\n return categories()[name];\n }\n\n typedef enum\n {\n ENABLE,\n DISABLE,\n AUTO,\n } category_modifier_type;\n\n static void set_category_state(const char* list,\n const category_modifier_type state)\n {\n if (state == ENABLE)\n debug::default_category_state = false;\n else\n debug::default_category_state = true;\n\n \/\/ Also set existing to default_category_state.\n foreach(categories_type::value_type& v, categories())\n v.second = debug::default_category_state;\n\n std::string s(list); \/\/ Do not pass temporary to make_tokenizer.\n tokenizer_type t = make_tokenizer(s, \",\");\n foreach(const std::string& elem, t)\n {\n Symbol pattern(elem);\n switch(state)\n {\n case ENABLE:\n enable_category(pattern);\n break;\n case DISABLE:\n disable_category(pattern);\n break;\n case AUTO:\n auto_category(pattern);\n break;\n }\n }\n }\n }\n\n Debug::Debug()\n : locations_(getenv(\"GD_LOC\"))\n , timestamps_(getenv(\"GD_TIME\") || getenv(\"GD_TIMESTAMP_US\"))\n {\n \/\/ Process enabled\/disabled\/auto categories in environment.\n if (const char* autolist = getenv(\"GD_CATEGORY\"))\n debug::set_category_state(autolist, debug::AUTO);\n else\n {\n if (const char* enablelist = getenv(\"GD_ENABLE_CATEGORY\"))\n debug::set_category_state(enablelist, debug::ENABLE);\n if (const char* disablelist = getenv(\"GD_DISABLE_CATEGORY\"))\n debug::set_category_state(disablelist, debug::DISABLE);\n }\n\n if (const char* lvl_c = getenv(\"GD_LEVEL\"))\n filter(lvl_c);\n }\n\n Debug::~Debug()\n {}\n\n void\n Debug::filter(levels::Level lvl)\n {\n filter_ = lvl;\n }\n\n void\n Debug::filter(const std::string& lvl)\n {\n if (lvl == \"NONE\" || lvl == \"0\")\n filter(Debug::levels::none);\n else if (lvl == \"LOG\" || lvl == \"1\")\n filter(Debug::levels::log);\n else if (lvl == \"TRACE\" || lvl == \"2\")\n filter(Debug::levels::trace);\n else if (lvl == \"DEBUG\" || lvl == \"3\")\n filter(Debug::levels::debug);\n else if (lvl == \"DUMP\" || lvl == \"4\")\n filter(Debug::levels::dump);\n else\n \/\/ Don't use GD_ABORT here, we can be in the debugger constructor!\n pabort(\"invalid debug level (NONE, LOG, TRACE, DEBUG, DUMP or [0-4])\");\n }\n\n unsigned\n Debug::indentation() const\n {\n return debugger_data().indent;\n }\n\n Debug::levels::Level\n Debug::level()\n {\n return filter_;\n }\n\n# ifdef LIBPORT_HAVE_IP_SEMAPHORE\n static IPSemaphore& sem()\n {\n static IPSemaphore res(1);\n return res;\n }\n# endif\n\n void\n Debug::debug(const std::string& msg,\n types::Type type,\n debug::category_type category,\n const std::string& fun,\n const std::string& file,\n unsigned line)\n {\n# ifdef LIBPORT_HAVE_IP_SEMAPHORE\n static bool useLock = getenv(\"GD_USE_LOCK\") || getenv(\"GD_PID\");\n libport::Finally f;\n if (useLock)\n {\n --sem();\n f << boost::bind(&IPSemaphore::operator++, boost::ref(sem()));\n }\n# endif\n message(category, msg, type, fun, file, line);\n }\n\n Debug*\n Debug::push(debug::category_type category,\n const std::string& msg,\n const std::string& fun,\n const std::string& file,\n unsigned line)\n {\n message_push(category, msg, fun, file, line);\n return this;\n }\n\n std::string\n Debug::category_format(debug::category_type cat) const\n {\n std::string res = cat;\n size_t size = res.size();\n size_t largest = debug::categories_largest();\n if (size < largest)\n {\n size_t diff = largest - size;\n res = std::string(diff \/ 2, ' ')\n + res\n + std::string(diff \/ 2 + diff % 2, ' ');\n }\n\n return res;\n }\n\n namespace opts\n {\n\n void cb_debug_fun(const std::string& lvl)\n {\n GD_DEBUGGER->filter(lvl);\n }\n\n OptionValued::callback_type cb_debug(cb_debug_fun);\n\n OptionValue\n debug(\"set the debug level in NONE, LOG (default), TRACE, DEBUG, DUMP\",\n \"debug\", 'd', \"LEVEL\", cb_debug);\n\n }\n\n ConsoleDebug::ConsoleDebug()\n {}\n\n namespace\n {\n inline\n std::string\n time()\n {\n static bool us = getenv(\"GD_TIMESTAMP_US\");\n if (us)\n return string_cast(utime());\n time_t now = std::time(0);\n struct tm* ts = std::localtime(&now);\n char buf[80];\n strftime(buf, sizeof buf, \"%a %Y-%m-%d %H:%M:%S %Z\", ts);\n return buf;\n }\n\n inline\n std::string\n color(int color, bool bold = true)\n {\n static bool tty = isatty(STDERR_FILENO);\n static bool force = getenv(\"GD_COLOR\");\n static bool force_disable = getenv(\"GD_NO_COLOR\");\n return (((tty || force) && !force_disable)\n ? format(\"\u001b[33;0%s;%sm\", bold ? 1 : 0, color)\n : \"\");\n }\n }\n\n static Debug::colors::Color\n msg_color(Debug::types::Type type)\n {\n switch (type)\n {\n case Debug::types::info:\n return Debug::colors::white;\n case Debug::types::warn:\n return Debug::colors::yellow;\n case Debug::types::error:\n return Debug::colors::red;\n };\n GD_UNREACHABLE();\n }\n\n void\n ConsoleDebug::message(debug::category_type category,\n const std::string& msg,\n types::Type type,\n const std::string& fun,\n const std::string& file,\n unsigned line)\n {\n std::ostringstream ostr;\n Debug::colors::Color c = msg_color(type);\n if (timestamps())\n ostr << color(c) << time() << \" \";\n ostr << color(colors::purple)\n << \"[\" << category_format(category) << \"] \";\n {\n static bool pid = getenv(\"GD_PID\");\n if (pid)\n ostr << \"[\" << getpid() << \"] \";\n }\n#ifndef WIN32\n {\n static bool thread = getenv(\"GD_THREAD\");\n if (thread)\n ostr << \"[\" << pthread_self() << \"] \";\n }\n#endif\n ostr << color(c);\n for (unsigned i = 0; i < debugger_data().indent; ++i)\n ostr << \" \";\n \/\/ As syslog would do, don't issue the users' \\n.\n if (!msg.empty() && msg[msg.size() - 1] == '\\n')\n ostr.write(msg.c_str(), msg.size() - 1);\n else\n ostr << msg;\n if (locations())\n ostr << color(colors::blue)\n << \" (\" << fun << \", \" << file << \":\" << line << \")\";\n ostr << color(colors::white);\n std::cerr << ostr.str() << std::endl;\n }\n\n void\n ConsoleDebug::message_push(debug::category_type category,\n const std::string& msg,\n const std::string& fun,\n const std::string& file,\n unsigned line)\n {\n debug(msg, types::info, category, fun, file, line);\n GD_INDENTATION_INC();\n }\n\n void\n ConsoleDebug::pop()\n {\n assert_gt(debugger_data().indent, 0u);\n GD_INDENTATION_DEC();\n }\n\n std::string gd_ihexdump(const unsigned char* data, unsigned size)\n {\n std::string res =\n format(\"\\\"%s\\\"\",\n libport::escape(std::string((const char*)data, (size_t)(size))));\n\n bool first = true;\n for (unsigned i = 0; i < size; ++i)\n {\n if (first)\n first = false;\n else\n res += \" \";\n \/\/ Cast to int, or boost::format will print the character.\n res += format(\"0x%x\", static_cast<unsigned int>(data[i]));\n }\n return res;\n }\n\n#ifndef WIN32\n \/*-------------.\n | Syslog debug |\n `-------------*\/\n\n SyslogDebug::SyslogDebug(const std::string& program)\n {\n openlog(strdup(program.c_str()), LOG_PID, LOG_DAEMON);\n syslog(LOG_INFO | LOG_DAEMON, \"%s\",\n format(\"Opening syslog session for '%s'\", program).c_str());\n }\n\n SyslogDebug::~SyslogDebug()\n {\n syslog(LOG_INFO | LOG_DAEMON, \"Closing syslog session.\");\n closelog();\n }\n\n static\n int type_to_prio(Debug::types::Type t)\n {\n switch (t)\n {\n#define CASE(In, Out) \\\n case Debug::types::In: return Out; break\n CASE(info, LOG_INFO);\n CASE(warn, LOG_WARNING);\n CASE(error, LOG_ERR);\n#undef CASE\n }\n \/\/ Pacify Gcc.\n libport::abort();\n }\n\n void\n SyslogDebug::message(debug::category_type category,\n const std::string& msg,\n types::Type type,\n const std::string& fun,\n const std::string& file,\n unsigned line)\n {\n std::stringstream s;\n s << \"[\" << category_format(category) << \"] \";\n for (unsigned i = 0; i < debugger_data().indent; ++i)\n s << \" \";\n \/\/ As syslog would do, don't issue the users' \\n.\n if (!msg.empty() && msg[msg.size() - 1] == '\\n')\n s.write(msg.c_str(), msg.size() - 1);\n else\n s << msg;\n if (locations())\n s << \" (\" << fun << \", \" << file << \":\" << line << \")\";\n int prio = type_to_prio(type) | LOG_DAEMON;\n syslog(prio, \"%s\", s.str().c_str());\n }\n\n void\n SyslogDebug::message_push(debug::category_type category,\n const std::string& msg,\n const std::string& fun,\n const std::string& file,\n unsigned line)\n {\n debug(msg, types::info, category, fun, file, line);\n GD_INDENTATION_INC();\n }\n\n void\n SyslogDebug::pop()\n {\n assert_gt(debugger_data().indent, 0u);\n GD_INDENTATION_DEC();\n }\n#endif\n\n boost::function0<Debug*> make_debugger;\n\n namespace debug\n {\n void clear()\n {\n#if FIXME\n delete debugger();\n#endif\n }\n }\n}\n\n#endif\n<commit_msg>Libport.Debug: avoid extraneous \\n.<commit_after>\/*\n * Copyright (C) 2008-2011, Gostai S.A.S.\n *\n * This software is provided \"as is\" without warranty of any kind,\n * either expressed or implied, including but not limited to the\n * implied warranties of fitness for a particular purpose.\n *\n * See the LICENSE file for more information.\n *\/\n\n#include <iostream>\n\n#include <boost\/thread\/tss.hpp>\n\n#include <libport\/cassert>\n#include <libport\/containers.hh>\n#include <libport\/cstdio>\n#include <libport\/debug.hh>\n#include <libport\/escape.hh>\n#include <libport\/fnmatch.h>\n#include <libport\/foreach.hh>\n#include <libport\/format.hh>\n#include <libport\/ip-semaphore.hh>\n#include <libport\/lockable.hh>\n#include <libport\/pthread.h>\n#include <libport\/thread-data.hh>\n#include <libport\/tokenizer.hh>\n#include <libport\/unistd.h>\n#include <libport\/utime.hh>\n#include <libport\/windows.hh>\n#include <sched\/coroutine-data.hh>\n\n#ifndef WIN32\n# include <syslog.h>\n#endif\n\n#ifndef LIBPORT_DEBUG_DISABLE\n\nGD_CATEGORY(Libport.Debug);\n\nnamespace libport\n{\n LIBPORT_API boost::function0<local_data&> debugger_data;\n LIBPORT_API Debug* debugger = 0;\n LIBPORT_API Debug::levels::Level Debug::filter_(levels::log);\n\n local_data&\n debugger_data_thread_local()\n {\n static boost::thread_specific_ptr<local_data> storage;\n if (!storage.get())\n storage.reset(new local_data);\n return *storage;\n }\n\n\n local_data::local_data()\n : indent(0)\n {}\n\n\n namespace debug\n {\n \/\/ Wether categories are enabled by default.\n static bool default_category_state = true;\n\n LIBPORT_API void\n uninitialized_msg(const std::string& msg)\n {\n static bool tail = false;\n if (!tail++)\n std::cerr << \"[Libport.Debug] \"\n << \"Uninitialized debug, fallback to stderr.\" << std::endl;\n std::cerr << \"[Libport.Debug] \" << msg;\n if (msg.empty() || msg[msg.size() - 1] != '\\n')\n std::cerr << std::endl;\n }\n\n \/\/ Categories added so far.\n categories_type&\n categories()\n {\n static categories_type categories;\n return categories;\n }\n\n static unsigned\n current_pattern()\n {\n static unsigned current = 0;\n return current++;\n }\n\n \/\/ Patterns added so far.\n patterns_type&\n patterns()\n {\n static patterns_type patterns;\n return patterns;\n }\n\n \/\/ Maximum category width.\n size_t&\n categories_largest()\n {\n static size_t res = 0;\n return res;\n }\n\n \/\/ Add a new category, look if it matches a pattern.\n Symbol\n add_category(Symbol name)\n {\n int order = -1;\n bool value = default_category_state;\n foreach (patterns_type::value_type& s, patterns())\n {\n if (fnmatch(s.first.name_get(), name.name_get()) == 0)\n {\n if (int(s.second.second) > order)\n {\n value = s.second.first;\n order = s.second.second;\n }\n }\n }\n\n categories()[name] = value;\n\n size_t size = name.name_get().size();\n if (categories_largest() < size)\n categories_largest() = size;\n\n return name;\n }\n\n \/\/ Add a new category pattern.\n int\n enable_category(Symbol pattern)\n {\n patterns()[pattern] = std::make_pair(true, current_pattern());\n foreach (categories_type::value_type& s, categories())\n {\n if (fnmatch(pattern.name_get(), s.first.name_get()) == 0)\n s.second = true;\n }\n\n return 42;\n }\n\n \/\/ Disable a new category pattern.\n int\n disable_category(Symbol pattern)\n {\n patterns()[pattern] = std::make_pair(false, current_pattern());\n foreach (categories_type::value_type& s, categories())\n {\n if (fnmatch(pattern.name_get(), s.first.name_get()) == 0)\n s.second = false;\n }\n\n return 42;\n }\n\n \/\/ Enable\/Disable a new category pattern with modifier.\n int\n auto_category(Symbol pattern)\n {\n std::string p = pattern.name_get();\n char modifier = p[0];\n if (modifier == '+' || modifier == '-')\n p = p.substr(1);\n else\n modifier = '+';\n bool value = modifier == '+';\n\n patterns()[Symbol(p)] = std::make_pair(value, current_pattern());\n foreach (categories_type::value_type& s, categories())\n {\n if (fnmatch(p, s.first.name_get()) == 0)\n s.second = value;\n }\n\n return 42;\n }\n\n bool test_category(Symbol name)\n {\n return categories()[name];\n }\n\n typedef enum\n {\n ENABLE,\n DISABLE,\n AUTO,\n } category_modifier_type;\n\n static void set_category_state(const char* list,\n const category_modifier_type state)\n {\n if (state == ENABLE)\n debug::default_category_state = false;\n else\n debug::default_category_state = true;\n\n \/\/ Also set existing to default_category_state.\n foreach(categories_type::value_type& v, categories())\n v.second = debug::default_category_state;\n\n std::string s(list); \/\/ Do not pass temporary to make_tokenizer.\n tokenizer_type t = make_tokenizer(s, \",\");\n foreach(const std::string& elem, t)\n {\n Symbol pattern(elem);\n switch(state)\n {\n case ENABLE:\n enable_category(pattern);\n break;\n case DISABLE:\n disable_category(pattern);\n break;\n case AUTO:\n auto_category(pattern);\n break;\n }\n }\n }\n }\n\n Debug::Debug()\n : locations_(getenv(\"GD_LOC\"))\n , timestamps_(getenv(\"GD_TIME\") || getenv(\"GD_TIMESTAMP_US\"))\n {\n \/\/ Process enabled\/disabled\/auto categories in environment.\n if (const char* autolist = getenv(\"GD_CATEGORY\"))\n debug::set_category_state(autolist, debug::AUTO);\n else\n {\n if (const char* enablelist = getenv(\"GD_ENABLE_CATEGORY\"))\n debug::set_category_state(enablelist, debug::ENABLE);\n if (const char* disablelist = getenv(\"GD_DISABLE_CATEGORY\"))\n debug::set_category_state(disablelist, debug::DISABLE);\n }\n\n if (const char* lvl_c = getenv(\"GD_LEVEL\"))\n filter(lvl_c);\n }\n\n Debug::~Debug()\n {}\n\n void\n Debug::filter(levels::Level lvl)\n {\n filter_ = lvl;\n }\n\n void\n Debug::filter(const std::string& lvl)\n {\n if (lvl == \"NONE\" || lvl == \"0\")\n filter(Debug::levels::none);\n else if (lvl == \"LOG\" || lvl == \"1\")\n filter(Debug::levels::log);\n else if (lvl == \"TRACE\" || lvl == \"2\")\n filter(Debug::levels::trace);\n else if (lvl == \"DEBUG\" || lvl == \"3\")\n filter(Debug::levels::debug);\n else if (lvl == \"DUMP\" || lvl == \"4\")\n filter(Debug::levels::dump);\n else\n \/\/ Don't use GD_ABORT here, we can be in the debugger constructor!\n pabort(\"invalid debug level (NONE, LOG, TRACE, DEBUG, DUMP or [0-4])\");\n }\n\n unsigned\n Debug::indentation() const\n {\n return debugger_data().indent;\n }\n\n Debug::levels::Level\n Debug::level()\n {\n return filter_;\n }\n\n# ifdef LIBPORT_HAVE_IP_SEMAPHORE\n static IPSemaphore& sem()\n {\n static IPSemaphore res(1);\n return res;\n }\n# endif\n\n void\n Debug::debug(const std::string& msg,\n types::Type type,\n debug::category_type category,\n const std::string& fun,\n const std::string& file,\n unsigned line)\n {\n# ifdef LIBPORT_HAVE_IP_SEMAPHORE\n static bool useLock = getenv(\"GD_USE_LOCK\") || getenv(\"GD_PID\");\n libport::Finally f;\n if (useLock)\n {\n --sem();\n f << boost::bind(&IPSemaphore::operator++, boost::ref(sem()));\n }\n# endif\n message(category, msg, type, fun, file, line);\n }\n\n Debug*\n Debug::push(debug::category_type category,\n const std::string& msg,\n const std::string& fun,\n const std::string& file,\n unsigned line)\n {\n message_push(category, msg, fun, file, line);\n return this;\n }\n\n std::string\n Debug::category_format(debug::category_type cat) const\n {\n std::string res = cat;\n size_t size = res.size();\n size_t largest = debug::categories_largest();\n if (size < largest)\n {\n size_t diff = largest - size;\n res = std::string(diff \/ 2, ' ')\n + res\n + std::string(diff \/ 2 + diff % 2, ' ');\n }\n\n return res;\n }\n\n namespace opts\n {\n\n void cb_debug_fun(const std::string& lvl)\n {\n GD_DEBUGGER->filter(lvl);\n }\n\n OptionValued::callback_type cb_debug(cb_debug_fun);\n\n OptionValue\n debug(\"set the debug level in NONE, LOG (default), TRACE, DEBUG, DUMP\",\n \"debug\", 'd', \"LEVEL\", cb_debug);\n\n }\n\n ConsoleDebug::ConsoleDebug()\n {}\n\n namespace\n {\n inline\n std::string\n time()\n {\n static bool us = getenv(\"GD_TIMESTAMP_US\");\n if (us)\n return string_cast(utime());\n time_t now = std::time(0);\n struct tm* ts = std::localtime(&now);\n char buf[80];\n strftime(buf, sizeof buf, \"%a %Y-%m-%d %H:%M:%S %Z\", ts);\n return buf;\n }\n\n inline\n std::string\n color(int color, bool bold = true)\n {\n static bool tty = isatty(STDERR_FILENO);\n static bool force = getenv(\"GD_COLOR\");\n static bool force_disable = getenv(\"GD_NO_COLOR\");\n return (((tty || force) && !force_disable)\n ? format(\"\u001b[33;0%s;%sm\", bold ? 1 : 0, color)\n : \"\");\n }\n }\n\n static Debug::colors::Color\n msg_color(Debug::types::Type type)\n {\n switch (type)\n {\n case Debug::types::info:\n return Debug::colors::white;\n case Debug::types::warn:\n return Debug::colors::yellow;\n case Debug::types::error:\n return Debug::colors::red;\n };\n GD_UNREACHABLE();\n }\n\n void\n ConsoleDebug::message(debug::category_type category,\n const std::string& msg,\n types::Type type,\n const std::string& fun,\n const std::string& file,\n unsigned line)\n {\n std::ostringstream ostr;\n Debug::colors::Color c = msg_color(type);\n if (timestamps())\n ostr << color(c) << time() << \" \";\n ostr << color(colors::purple)\n << \"[\" << category_format(category) << \"] \";\n {\n static bool pid = getenv(\"GD_PID\");\n if (pid)\n ostr << \"[\" << getpid() << \"] \";\n }\n#ifndef WIN32\n {\n static bool thread = getenv(\"GD_THREAD\");\n if (thread)\n ostr << \"[\" << pthread_self() << \"] \";\n }\n#endif\n ostr << color(c);\n for (unsigned i = 0; i < debugger_data().indent; ++i)\n ostr << \" \";\n \/\/ As syslog would do, don't issue the users' \\n.\n if (!msg.empty() && msg[msg.size() - 1] == '\\n')\n ostr.write(msg.c_str(), msg.size() - 1);\n else\n ostr << msg;\n if (locations())\n ostr << color(colors::blue)\n << \" (\" << fun << \", \" << file << \":\" << line << \")\";\n ostr << color(colors::white);\n std::cerr << ostr.str() << std::endl;\n }\n\n void\n ConsoleDebug::message_push(debug::category_type category,\n const std::string& msg,\n const std::string& fun,\n const std::string& file,\n unsigned line)\n {\n debug(msg, types::info, category, fun, file, line);\n GD_INDENTATION_INC();\n }\n\n void\n ConsoleDebug::pop()\n {\n assert_gt(debugger_data().indent, 0u);\n GD_INDENTATION_DEC();\n }\n\n std::string gd_ihexdump(const unsigned char* data, unsigned size)\n {\n std::string res =\n format(\"\\\"%s\\\"\",\n libport::escape(std::string((const char*)data, (size_t)(size))));\n\n bool first = true;\n for (unsigned i = 0; i < size; ++i)\n {\n if (first)\n first = false;\n else\n res += \" \";\n \/\/ Cast to int, or boost::format will print the character.\n res += format(\"0x%x\", static_cast<unsigned int>(data[i]));\n }\n return res;\n }\n\n#ifndef WIN32\n \/*-------------.\n | Syslog debug |\n `-------------*\/\n\n SyslogDebug::SyslogDebug(const std::string& program)\n {\n openlog(strdup(program.c_str()), LOG_PID, LOG_DAEMON);\n syslog(LOG_INFO | LOG_DAEMON, \"%s\",\n format(\"Opening syslog session for '%s'\", program).c_str());\n }\n\n SyslogDebug::~SyslogDebug()\n {\n syslog(LOG_INFO | LOG_DAEMON, \"Closing syslog session.\");\n closelog();\n }\n\n static\n int type_to_prio(Debug::types::Type t)\n {\n switch (t)\n {\n#define CASE(In, Out) \\\n case Debug::types::In: return Out; break\n CASE(info, LOG_INFO);\n CASE(warn, LOG_WARNING);\n CASE(error, LOG_ERR);\n#undef CASE\n }\n \/\/ Pacify Gcc.\n libport::abort();\n }\n\n void\n SyslogDebug::message(debug::category_type category,\n const std::string& msg,\n types::Type type,\n const std::string& fun,\n const std::string& file,\n unsigned line)\n {\n std::stringstream s;\n s << \"[\" << category_format(category) << \"] \";\n for (unsigned i = 0; i < debugger_data().indent; ++i)\n s << \" \";\n \/\/ As syslog would do, don't issue the users' \\n.\n if (!msg.empty() && msg[msg.size() - 1] == '\\n')\n s.write(msg.c_str(), msg.size() - 1);\n else\n s << msg;\n if (locations())\n s << \" (\" << fun << \", \" << file << \":\" << line << \")\";\n int prio = type_to_prio(type) | LOG_DAEMON;\n syslog(prio, \"%s\", s.str().c_str());\n }\n\n void\n SyslogDebug::message_push(debug::category_type category,\n const std::string& msg,\n const std::string& fun,\n const std::string& file,\n unsigned line)\n {\n debug(msg, types::info, category, fun, file, line);\n GD_INDENTATION_INC();\n }\n\n void\n SyslogDebug::pop()\n {\n assert_gt(debugger_data().indent, 0u);\n GD_INDENTATION_DEC();\n }\n#endif\n\n boost::function0<Debug*> make_debugger;\n\n namespace debug\n {\n void clear()\n {\n#if FIXME\n delete debugger();\n#endif\n }\n }\n}\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/\/ Licensed to the Apache Software Foundation (ASF) under one\n\/\/ or more contributor license agreements. See the NOTICE file\n\/\/ distributed with this work for additional information\n\/\/ regarding copyright ownership. The ASF licenses this file\n\/\/ to you under the Apache License, Version 2.0 (the\n\/\/ \"License\"); you may not use this file except in compliance\n\/\/ with the License. You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include <unistd.h>\n\n#include <map>\n#include <string>\n\n#include <mesos\/mesos.hpp>\n\n#include <mesos\/module\/container_logger.hpp>\n\n#include <mesos\/slave\/container_logger.hpp>\n#include <mesos\/slave\/containerizer.hpp>\n\n#include <process\/dispatch.hpp>\n#include <process\/future.hpp>\n#include <process\/process.hpp>\n#include <process\/subprocess.hpp>\n\n#include <stout\/bytes.hpp>\n#include <stout\/error.hpp>\n#include <stout\/try.hpp>\n#include <stout\/none.hpp>\n#include <stout\/nothing.hpp>\n#include <stout\/path.hpp>\n#include <stout\/strings.hpp>\n\n#include <stout\/os\/constants.hpp>\n#include <stout\/os\/environment.hpp>\n#include <stout\/os\/fcntl.hpp>\n#include <stout\/os\/killtree.hpp>\n\n#ifdef __linux__\n#include \"linux\/systemd.hpp\"\n#endif \/\/ __linux__\n\n#include \"slave\/container_loggers\/logrotate.hpp\"\n#include \"slave\/container_loggers\/lib_logrotate.hpp\"\n\n\nusing namespace mesos;\nusing namespace process;\n\nusing std::map;\nusing std::string;\n\nusing mesos::slave::ContainerConfig;\nusing mesos::slave::ContainerLogger;\nusing mesos::slave::ContainerIO;\n\nnamespace mesos {\nnamespace internal {\nnamespace logger {\n\nclass LogrotateContainerLoggerProcess :\n public Process<LogrotateContainerLoggerProcess>\n{\npublic:\n LogrotateContainerLoggerProcess(const Flags& _flags) : flags(_flags) {}\n\n \/\/ Spawns two subprocesses that read from their stdin and write to\n \/\/ \"stdout\" and \"stderr\" files in the sandbox. The subprocesses will rotate\n \/\/ the files according to the configured maximum size and number of files.\n Future<ContainerIO> prepare(\n const ContainerID& containerId,\n const ContainerConfig& containerConfig)\n {\n \/\/ Prepare the environment for the container logger subprocess.\n \/\/ We inherit agent environment variables except for those\n \/\/ LIBPROCESS or MESOS prefixed environment variables. See MESOS-6747.\n map<string, string> environment;\n\n foreachpair (\n const string& key, const string& value, os::environment()) {\n if (!strings::startsWith(key, \"LIBPROCESS_\") &&\n !strings::startsWith(key, \"MESOS_\")) {\n environment.emplace(key, value);\n }\n }\n\n \/\/ Make sure the libprocess of the subprocess can properly\n \/\/ initialize and find the IP. Since we don't need to use the TCP\n \/\/ socket for communication, it's OK to use a local address.\n environment.emplace(\"LIBPROCESS_IP\", \"127.0.0.1\");\n\n \/\/ Use the number of worker threads for libprocess that was passed\n \/\/ in through the flags.\n CHECK_GT(flags.libprocess_num_worker_threads, 0u);\n environment[\"LIBPROCESS_NUM_WORKER_THREADS\"] =\n stringify(flags.libprocess_num_worker_threads);\n\n \/\/ Copy the global rotation flags.\n \/\/ These will act as the defaults in case the container's environment\n \/\/ overrides a subset of them.\n LoggerFlags overriddenFlags;\n overriddenFlags.max_stdout_size = flags.max_stdout_size;\n overriddenFlags.logrotate_stdout_options = flags.logrotate_stdout_options;\n overriddenFlags.max_stderr_size = flags.max_stderr_size;\n overriddenFlags.logrotate_stderr_options = flags.logrotate_stderr_options;\n\n \/\/ Check for overrides of the rotation settings in the\n \/\/ `CommandInfo`s environment variables.\n if (containerConfig.command_info().has_environment()) {\n \/\/ Search the environment for prefixed environment variables.\n \/\/ We un-prefix those variables before parsing the flag values.\n map<string, string> containerEnvironment;\n foreach (const Environment::Variable variable,\n containerConfig.command_info().environment().variables()) {\n if (strings::startsWith(\n variable.name(), flags.environment_variable_prefix)) {\n string unprefixed = strings::lower(strings::remove(\n variable.name(),\n flags.environment_variable_prefix,\n strings::PREFIX));\n containerEnvironment[unprefixed] = variable.value();\n }\n }\n\n \/\/ We will error out if there are unknown flags with the same prefix.\n Try<flags::Warnings> load = overriddenFlags.load(containerEnvironment);\n\n if (load.isError()) {\n return Failure(\n \"Failed to load container logger settings: \" + load.error());\n }\n\n \/\/ Log any flag warnings.\n foreach (const flags::Warning& warning, load->warnings) {\n LOG(WARNING) << warning.message;\n }\n }\n\n \/\/ NOTE: We manually construct a pipe here instead of using\n \/\/ `Subprocess::PIPE` so that the ownership of the FDs is properly\n \/\/ represented. The `Subprocess` spawned below owns the read-end\n \/\/ of the pipe and will be solely responsible for closing that end.\n \/\/ The ownership of the write-end will be passed to the caller\n \/\/ of this function.\n int pipefd[2];\n if (::pipe(pipefd) == -1) {\n return Failure(ErrnoError(\"Failed to create pipe\").message);\n }\n\n Subprocess::IO::InputFileDescriptors outfds;\n outfds.read = pipefd[0];\n outfds.write = pipefd[1];\n\n \/\/ NOTE: We need to `cloexec` this FD so that it will be closed when\n \/\/ the child subprocess is spawned and so that the FD will not be\n \/\/ inherited by the second child for stderr.\n Try<Nothing> cloexec = os::cloexec(outfds.write.get());\n if (cloexec.isError()) {\n os::close(outfds.read);\n os::close(outfds.write.get());\n return Failure(\"Failed to cloexec: \" + cloexec.error());\n }\n\n \/\/ Spawn a process to handle stdout.\n mesos::internal::logger::rotate::Flags outFlags;\n outFlags.max_size = overriddenFlags.max_stdout_size;\n outFlags.logrotate_options = overriddenFlags.logrotate_stdout_options;\n outFlags.log_filename = path::join(containerConfig.directory(), \"stdout\");\n outFlags.logrotate_path = flags.logrotate_path;\n outFlags.user = containerConfig.has_user()\n ? Option<string>(containerConfig.user())\n : Option<string>::none();\n\n \/\/ If we are on systemd, then extend the life of the process as we\n \/\/ do with the executor. Any grandchildren's lives will also be\n \/\/ extended.\n std::vector<Subprocess::ParentHook> parentHooks;\n#ifdef __linux__\n if (systemd::enabled()) {\n parentHooks.emplace_back(Subprocess::ParentHook(\n &systemd::mesos::extendLifetime));\n }\n#endif \/\/ __linux__\n\n Try<Subprocess> outProcess = subprocess(\n path::join(flags.launcher_dir, mesos::internal::logger::rotate::NAME),\n {mesos::internal::logger::rotate::NAME},\n Subprocess::FD(outfds.read, Subprocess::IO::OWNED),\n Subprocess::PATH(os::DEV_NULL),\n Subprocess::FD(STDERR_FILENO),\n &outFlags,\n environment,\n None(),\n parentHooks);\n\n if (outProcess.isError()) {\n os::close(outfds.write.get());\n return Failure(\"Failed to create logger process: \" + outProcess.error());\n }\n\n \/\/ NOTE: We manually construct a pipe here to properly express\n \/\/ ownership of the FDs. See the NOTE above.\n if (::pipe(pipefd) == -1) {\n os::close(outfds.write.get());\n os::killtree(outProcess->pid(), SIGKILL);\n return Failure(ErrnoError(\"Failed to create pipe\").message);\n }\n\n Subprocess::IO::InputFileDescriptors errfds;\n errfds.read = pipefd[0];\n errfds.write = pipefd[1];\n\n \/\/ NOTE: We need to `cloexec` this FD so that it will be closed when\n \/\/ the child subprocess is spawned.\n cloexec = os::cloexec(errfds.write.get());\n if (cloexec.isError()) {\n os::close(outfds.write.get());\n os::close(errfds.read);\n os::close(errfds.write.get());\n os::killtree(outProcess->pid(), SIGKILL);\n return Failure(\"Failed to cloexec: \" + cloexec.error());\n }\n\n \/\/ Spawn a process to handle stderr.\n mesos::internal::logger::rotate::Flags errFlags;\n errFlags.max_size = overriddenFlags.max_stderr_size;\n errFlags.logrotate_options = overriddenFlags.logrotate_stderr_options;\n errFlags.log_filename = path::join(containerConfig.directory(), \"stderr\");\n errFlags.logrotate_path = flags.logrotate_path;\n errFlags.user = containerConfig.has_user()\n ? Option<string>(containerConfig.user())\n : Option<string>::none();\n\n Try<Subprocess> errProcess = subprocess(\n path::join(flags.launcher_dir, mesos::internal::logger::rotate::NAME),\n {mesos::internal::logger::rotate::NAME},\n Subprocess::FD(errfds.read, Subprocess::IO::OWNED),\n Subprocess::PATH(os::DEV_NULL),\n Subprocess::FD(STDERR_FILENO),\n &errFlags,\n environment,\n None(),\n parentHooks);\n\n if (errProcess.isError()) {\n os::close(outfds.write.get());\n os::close(errfds.write.get());\n os::killtree(outProcess->pid(), SIGKILL);\n return Failure(\"Failed to create logger process: \" + errProcess.error());\n }\n\n \/\/ NOTE: The ownership of these FDs is given to the caller of this function.\n ContainerIO io;\n io.out = ContainerIO::IO::FD(outfds.write.get());\n io.err = ContainerIO::IO::FD(errfds.write.get());\n return io;\n }\n\nprotected:\n Flags flags;\n};\n\n\nLogrotateContainerLogger::LogrotateContainerLogger(const Flags& _flags)\n : flags(_flags),\n process(new LogrotateContainerLoggerProcess(flags))\n{\n \/\/ Spawn and pass validated parameters to the process.\n spawn(process.get());\n}\n\n\nLogrotateContainerLogger::~LogrotateContainerLogger()\n{\n terminate(process.get());\n wait(process.get());\n}\n\n\nTry<Nothing> LogrotateContainerLogger::initialize()\n{\n return Nothing();\n}\n\n\nFuture<ContainerIO> LogrotateContainerLogger::prepare(\n const ContainerID& containerId,\n const ContainerConfig& containerConfig)\n{\n return dispatch(\n process.get(),\n &LogrotateContainerLoggerProcess::prepare,\n containerId,\n containerConfig);\n}\n\n} \/\/ namespace logger {\n} \/\/ namespace internal {\n} \/\/ namespace mesos {\n\n\nmesos::modules::Module<ContainerLogger>\norg_apache_mesos_LogrotateContainerLogger(\n MESOS_MODULE_API_VERSION,\n MESOS_VERSION,\n \"Apache Mesos\",\n \"modules@mesos.apache.org\",\n \"Logrotate Container Logger module.\",\n nullptr,\n [](const Parameters& parameters) -> ContainerLogger* {\n \/\/ Convert `parameters` into a map.\n map<string, string> values;\n foreach (const Parameter& parameter, parameters.parameter()) {\n values[parameter.key()] = parameter.value();\n }\n\n \/\/ Load and validate flags from the map.\n mesos::internal::logger::Flags flags;\n Try<flags::Warnings> load = flags.load(values);\n\n if (load.isError()) {\n LOG(ERROR) << \"Failed to parse parameters: \" << load.error();\n return nullptr;\n }\n\n \/\/ Log any flag warnings.\n foreach (const flags::Warning& warning, load->warnings) {\n LOG(WARNING) << warning.message;\n }\n\n return new mesos::internal::logger::LogrotateContainerLogger(flags);\n });\n<commit_msg>Updated the ::pipe() system calls to pipe2 in lib_logrotate.<commit_after>\/\/ Licensed to the Apache Software Foundation (ASF) under one\n\/\/ or more contributor license agreements. See the NOTICE file\n\/\/ distributed with this work for additional information\n\/\/ regarding copyright ownership. The ASF licenses this file\n\/\/ to you under the Apache License, Version 2.0 (the\n\/\/ \"License\"); you may not use this file except in compliance\n\/\/ with the License. You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include <unistd.h>\n\n#include <map>\n#include <string>\n\n#include <mesos\/mesos.hpp>\n\n#include <mesos\/module\/container_logger.hpp>\n\n#include <mesos\/slave\/container_logger.hpp>\n#include <mesos\/slave\/containerizer.hpp>\n\n#include <process\/dispatch.hpp>\n#include <process\/future.hpp>\n#include <process\/process.hpp>\n#include <process\/subprocess.hpp>\n\n#include <stout\/bytes.hpp>\n#include <stout\/error.hpp>\n#include <stout\/try.hpp>\n#include <stout\/none.hpp>\n#include <stout\/nothing.hpp>\n#include <stout\/path.hpp>\n#include <stout\/strings.hpp>\n\n#include <stout\/os\/constants.hpp>\n#include <stout\/os\/environment.hpp>\n#include <stout\/os\/fcntl.hpp>\n#include <stout\/os\/killtree.hpp>\n#include <stout\/os\/pipe.hpp>\n\n#ifdef __linux__\n#include \"linux\/systemd.hpp\"\n#endif \/\/ __linux__\n\n#include \"slave\/container_loggers\/logrotate.hpp\"\n#include \"slave\/container_loggers\/lib_logrotate.hpp\"\n\n\nusing namespace mesos;\nusing namespace process;\n\nusing std::array;\nusing std::map;\nusing std::string;\n\nusing mesos::slave::ContainerConfig;\nusing mesos::slave::ContainerLogger;\nusing mesos::slave::ContainerIO;\n\nnamespace mesos {\nnamespace internal {\nnamespace logger {\n\nclass LogrotateContainerLoggerProcess :\n public Process<LogrotateContainerLoggerProcess>\n{\npublic:\n LogrotateContainerLoggerProcess(const Flags& _flags) : flags(_flags) {}\n\n \/\/ Spawns two subprocesses that read from their stdin and write to\n \/\/ \"stdout\" and \"stderr\" files in the sandbox. The subprocesses will rotate\n \/\/ the files according to the configured maximum size and number of files.\n Future<ContainerIO> prepare(\n const ContainerID& containerId,\n const ContainerConfig& containerConfig)\n {\n \/\/ Prepare the environment for the container logger subprocess.\n \/\/ We inherit agent environment variables except for those\n \/\/ LIBPROCESS or MESOS prefixed environment variables. See MESOS-6747.\n map<string, string> environment;\n\n foreachpair (\n const string& key, const string& value, os::environment()) {\n if (!strings::startsWith(key, \"LIBPROCESS_\") &&\n !strings::startsWith(key, \"MESOS_\")) {\n environment.emplace(key, value);\n }\n }\n\n \/\/ Make sure the libprocess of the subprocess can properly\n \/\/ initialize and find the IP. Since we don't need to use the TCP\n \/\/ socket for communication, it's OK to use a local address.\n environment.emplace(\"LIBPROCESS_IP\", \"127.0.0.1\");\n\n \/\/ Use the number of worker threads for libprocess that was passed\n \/\/ in through the flags.\n CHECK_GT(flags.libprocess_num_worker_threads, 0u);\n environment[\"LIBPROCESS_NUM_WORKER_THREADS\"] =\n stringify(flags.libprocess_num_worker_threads);\n\n \/\/ Copy the global rotation flags.\n \/\/ These will act as the defaults in case the container's environment\n \/\/ overrides a subset of them.\n LoggerFlags overriddenFlags;\n overriddenFlags.max_stdout_size = flags.max_stdout_size;\n overriddenFlags.logrotate_stdout_options = flags.logrotate_stdout_options;\n overriddenFlags.max_stderr_size = flags.max_stderr_size;\n overriddenFlags.logrotate_stderr_options = flags.logrotate_stderr_options;\n\n \/\/ Check for overrides of the rotation settings in the\n \/\/ `CommandInfo`s environment variables.\n if (containerConfig.command_info().has_environment()) {\n \/\/ Search the environment for prefixed environment variables.\n \/\/ We un-prefix those variables before parsing the flag values.\n map<string, string> containerEnvironment;\n foreach (const Environment::Variable variable,\n containerConfig.command_info().environment().variables()) {\n if (strings::startsWith(\n variable.name(), flags.environment_variable_prefix)) {\n string unprefixed = strings::lower(strings::remove(\n variable.name(),\n flags.environment_variable_prefix,\n strings::PREFIX));\n containerEnvironment[unprefixed] = variable.value();\n }\n }\n\n \/\/ We will error out if there are unknown flags with the same prefix.\n Try<flags::Warnings> load = overriddenFlags.load(containerEnvironment);\n\n if (load.isError()) {\n return Failure(\n \"Failed to load container logger settings: \" + load.error());\n }\n\n \/\/ Log any flag warnings.\n foreach (const flags::Warning& warning, load->warnings) {\n LOG(WARNING) << warning.message;\n }\n }\n\n \/\/ NOTE: We manually construct a pipe here instead of using\n \/\/ `Subprocess::PIPE` so that the ownership of the FDs is properly\n \/\/ represented. The `Subprocess` spawned below owns the read-end\n \/\/ of the pipe and will be solely responsible for closing that end.\n \/\/ The ownership of the write-end will be passed to the caller\n \/\/ of this function.\n Try<array<int, 2>> pipefd = os::pipe();\n if (pipefd.isError()) {\n return Failure(\"Failed to create pipe: \" + pipefd.error());\n }\n\n Subprocess::IO::InputFileDescriptors outfds;\n outfds.read = pipefd->at(0);\n outfds.write = pipefd->at(1);\n\n const std::vector<int_fd> whitelistOutFds{pipefd->at(0), pipefd->at(1)};\n\n \/\/ Spawn a process to handle stdout.\n mesos::internal::logger::rotate::Flags outFlags;\n outFlags.max_size = overriddenFlags.max_stdout_size;\n outFlags.logrotate_options = overriddenFlags.logrotate_stdout_options;\n outFlags.log_filename = path::join(containerConfig.directory(), \"stdout\");\n outFlags.logrotate_path = flags.logrotate_path;\n outFlags.user = containerConfig.has_user()\n ? Option<string>(containerConfig.user())\n : Option<string>::none();\n\n \/\/ If we are on systemd, then extend the life of the process as we\n \/\/ do with the executor. Any grandchildren's lives will also be\n \/\/ extended.\n std::vector<Subprocess::ParentHook> parentHooks;\n#ifdef __linux__\n if (systemd::enabled()) {\n parentHooks.emplace_back(Subprocess::ParentHook(\n &systemd::mesos::extendLifetime));\n }\n#endif \/\/ __linux__\n\n \/\/ TODO(gilbert): libprocess should take care of this, see MESOS-9164.\n std::vector<Subprocess::ChildHook> childHooks;\n foreach (int_fd fd, whitelistOutFds) {\n childHooks.push_back(Subprocess::ChildHook::UNSET_CLOEXEC(fd));\n }\n\n Try<Subprocess> outProcess = subprocess(\n path::join(flags.launcher_dir, mesos::internal::logger::rotate::NAME),\n {mesos::internal::logger::rotate::NAME},\n Subprocess::FD(outfds.read, Subprocess::IO::OWNED),\n Subprocess::PATH(os::DEV_NULL),\n Subprocess::FD(STDERR_FILENO),\n &outFlags,\n environment,\n None(),\n parentHooks,\n childHooks,\n whitelistOutFds);\n\n if (outProcess.isError()) {\n os::close(outfds.write.get());\n return Failure(\"Failed to create logger process: \" + outProcess.error());\n }\n\n \/\/ NOTE: We manually construct a pipe here to properly express\n \/\/ ownership of the FDs. See the NOTE above.\n pipefd = os::pipe();\n if (pipefd.isError()) {\n os::close(outfds.write.get());\n os::killtree(outProcess->pid(), SIGKILL);\n return Failure(\"Failed to create pipe: \" + pipefd.error());\n }\n\n Subprocess::IO::InputFileDescriptors errfds;\n errfds.read = pipefd->at(0);\n errfds.write = pipefd->at(1);\n\n const std::vector<int_fd> whitelistErrFds{pipefd->at(0), pipefd->at(1)};\n\n \/\/ Spawn a process to handle stderr.\n mesos::internal::logger::rotate::Flags errFlags;\n errFlags.max_size = overriddenFlags.max_stderr_size;\n errFlags.logrotate_options = overriddenFlags.logrotate_stderr_options;\n errFlags.log_filename = path::join(containerConfig.directory(), \"stderr\");\n errFlags.logrotate_path = flags.logrotate_path;\n errFlags.user = containerConfig.has_user()\n ? Option<string>(containerConfig.user())\n : Option<string>::none();\n\n \/\/ TODO(gilbert): libprocess should take care of this, see MESOS-9164.\n childHooks.clear();\n foreach (int_fd fd, whitelistErrFds) {\n childHooks.push_back(Subprocess::ChildHook::UNSET_CLOEXEC(fd));\n }\n\n Try<Subprocess> errProcess = subprocess(\n path::join(flags.launcher_dir, mesos::internal::logger::rotate::NAME),\n {mesos::internal::logger::rotate::NAME},\n Subprocess::FD(errfds.read, Subprocess::IO::OWNED),\n Subprocess::PATH(os::DEV_NULL),\n Subprocess::FD(STDERR_FILENO),\n &errFlags,\n environment,\n None(),\n parentHooks,\n childHooks,\n whitelistErrFds);\n\n if (errProcess.isError()) {\n os::close(outfds.write.get());\n os::close(errfds.write.get());\n os::killtree(outProcess->pid(), SIGKILL);\n return Failure(\"Failed to create logger process: \" + errProcess.error());\n }\n\n \/\/ NOTE: The ownership of these FDs is given to the caller of this function.\n ContainerIO io;\n io.out = ContainerIO::IO::FD(outfds.write.get());\n io.err = ContainerIO::IO::FD(errfds.write.get());\n return io;\n }\n\nprotected:\n Flags flags;\n};\n\n\nLogrotateContainerLogger::LogrotateContainerLogger(const Flags& _flags)\n : flags(_flags),\n process(new LogrotateContainerLoggerProcess(flags))\n{\n \/\/ Spawn and pass validated parameters to the process.\n spawn(process.get());\n}\n\n\nLogrotateContainerLogger::~LogrotateContainerLogger()\n{\n terminate(process.get());\n wait(process.get());\n}\n\n\nTry<Nothing> LogrotateContainerLogger::initialize()\n{\n return Nothing();\n}\n\n\nFuture<ContainerIO> LogrotateContainerLogger::prepare(\n const ContainerID& containerId,\n const ContainerConfig& containerConfig)\n{\n return dispatch(\n process.get(),\n &LogrotateContainerLoggerProcess::prepare,\n containerId,\n containerConfig);\n}\n\n} \/\/ namespace logger {\n} \/\/ namespace internal {\n} \/\/ namespace mesos {\n\n\nmesos::modules::Module<ContainerLogger>\norg_apache_mesos_LogrotateContainerLogger(\n MESOS_MODULE_API_VERSION,\n MESOS_VERSION,\n \"Apache Mesos\",\n \"modules@mesos.apache.org\",\n \"Logrotate Container Logger module.\",\n nullptr,\n [](const Parameters& parameters) -> ContainerLogger* {\n \/\/ Convert `parameters` into a map.\n map<string, string> values;\n foreach (const Parameter& parameter, parameters.parameter()) {\n values[parameter.key()] = parameter.value();\n }\n\n \/\/ Load and validate flags from the map.\n mesos::internal::logger::Flags flags;\n Try<flags::Warnings> load = flags.load(values);\n\n if (load.isError()) {\n LOG(ERROR) << \"Failed to parse parameters: \" << load.error();\n return nullptr;\n }\n\n \/\/ Log any flag warnings.\n foreach (const flags::Warning& warning, load->warnings) {\n LOG(WARNING) << warning.message;\n }\n\n return new mesos::internal::logger::LogrotateContainerLogger(flags);\n });\n<|endoftext|>"} {"text":"<commit_before>#ifndef __STAN__GM__ARGUMENTS__STEPSIZE__JITTER__HPP__\n#define __STAN__GM__ARGUMENTS__STEPSIZE__JITTER__HPP__\n\n#include <stan\/gm\/arguments\/singleton_argument.hpp>\n\nnamespace stan {\n \n namespace gm {\n \n class arg_stepsize_jitter: public real_argument {\n \n public:\n \n arg_stepsize_jitter(): real_argument() {\n _name = \"stepsize_jitter\";\n _description = \"Uniformly random jitter of the stepsize, in percent\";\n _validity = \"0 < stepsize_jitter < 1\";\n _default = \"0\";\n _default_value = 0.0;\n _constrained = true;\n _good_value = 0.5;\n _bad_value = -1.0;\n _value = _default_value;\n };\n \n bool is_valid(double value) { return 0 < value && value < 1; }\n \n };\n \n } \/\/ gm\n \n} \/\/ stan\n\n#endif<commit_msg>Use inclusive range of validity<commit_after>#ifndef __STAN__GM__ARGUMENTS__STEPSIZE__JITTER__HPP__\n#define __STAN__GM__ARGUMENTS__STEPSIZE__JITTER__HPP__\n\n#include <stan\/gm\/arguments\/singleton_argument.hpp>\n\nnamespace stan {\n \n namespace gm {\n \n class arg_stepsize_jitter: public real_argument {\n \n public:\n \n arg_stepsize_jitter(): real_argument() {\n _name = \"stepsize_jitter\";\n _description = \"Uniformly random jitter of the stepsize, in percent\";\n _validity = \"0 <= stepsize_jitter <= 1\";\n _default = \"0\";\n _default_value = 0.0;\n _constrained = true;\n _good_value = 0.5;\n _bad_value = -1.0;\n _value = _default_value;\n };\n \n bool is_valid(double value) { return 0 <= value && value <= 1; }\n \n };\n \n } \/\/ gm\n \n} \/\/ stan\n\n#endif<|endoftext|>"} {"text":"<commit_before>\/* Luwra\n * Minimal-overhead Lua wrapper for C++\n *\n * Copyright (C) 2015, Ole Krüger <ole@vprsm.de>\n *\/\n\n#ifndef LUWRA_VALUES_H_\n#define LUWRA_VALUES_H_\n\n#include \"common.hpp\"\n#include \"internal\/indexsequence.hpp\"\n\n#include <utility>\n#include <string>\n\nLUWRA_NS_BEGIN\n\ntemplate <typename UserType>\nstruct Value;\n\n\/\/\/ Alias for @ref Value<Type>\ntemplate <typename Type>\nstruct Value<const Type>: Value<Type> {};\n\n\/\/\/ Alias for @ref Value<Type>\ntemplate <typename Type>\nstruct Value<volatile Type>: Value<Type> {};\n\n\/\/\/ Alias for @ref Value<Type>\ntemplate <typename Type>\nstruct Value<const volatile Type>: Value<Type> {};\n\n\/\/\/ Alias for @ref Value<Type>\ntemplate <typename Type>\nstruct Value<Type&>: Value<Type> {};\n\n\/\/\/ Alias for @ref Value<Type>\ntemplate <typename Type>\nstruct Value<Type&&>: Value<Type> {};\n\nnamespace internal {\n\tstruct InferValueType {\n\t\tState* state;\n\t\tint index;\n\n\t\ttemplate <typename Type>\n\t\toperator Type() const && {\n\t\t\treturn Value<Type>::read(state, index);\n\t\t}\n\n\t\ttemplate <typename Type>\n\t\toperator Type&() const & {\n\t\t\treturn Value<Type&>::read(state, index);\n\t\t}\n\t};\n}\n\n\/\/\/ Enables reading of type-infered values\ntemplate <>\nstruct Value<internal::InferValueType> {\n\tstatic inline\n\tconst internal::InferValueType read(State* state, int index) {\n\t\treturn {state, index};\n\t}\n};\n\n\/\/\/ Enables reading\/pushing `nil`\ntemplate <>\nstruct Value<std::nullptr_t> {\n\tstatic inline\n\tstd::nullptr_t read(State* state, int n) {\n\t\tluaL_checktype(state, n, LUA_TNIL);\n\t\treturn nullptr;\n\t}\n\n\tstatic inline\n\tvoid push(State* state, std::nullptr_t) {\n\t\tlua_pushnil(state);\n\t}\n};\n\n\/\/\/ Enables reading Lua threads\ntemplate <>\nstruct Value<State*> {\n\tstatic inline\n\tState* read(State* state, int n) {\n\t\tluaL_checktype(state, n, LUA_TTHREAD);\n\t\treturn lua_tothread(state, n);\n\t}\n};\n\n\/\/\/ Enables reading\/pushing light data\ntemplate <>\nstruct Value<void*> {\n\tstatic inline\n\tvoid* read(State* state, int n) {\n\t\tluaL_checktype(state, n, LUA_TLIGHTUSERDATA);\n\t\treturn lua_touserdata(state, n);\n\t}\n\n\tstatic inline\n\tvoid push(State* state, void* data) {\n\t\tlua_pushlightuserdata(state, data);\n\t}\n};\n\n\/\/\/ Enables reading constant light data\ntemplate <>\nstruct Value<const void*> {\n\tstatic inline\n\tconst void* read(State* state, int n) {\n\t\tluaL_checktype(state, n, LUA_TLIGHTUSERDATA);\n\t\treturn lua_touserdata(state, n);\n\t}\n};\n\nnamespace internal {\n\ttemplate <typename Type>\n\tstruct NumericTransportValue {\n\t\tstatic_assert(\n\t\t\tsizeof(Type) == -1,\n\t\t\t\"Parameter to NumericTransportValue is not a numeric base type\"\n\t\t);\n\t};\n\n\t\/\/ Transport unit `Integer`\n\ttemplate <>\n\tstruct NumericTransportValue<Integer> {\n\t\tstatic inline\n\t\tInteger read(State* state, int index) {\n\t\t\treturn luaL_checkinteger(state, index);\n\t\t}\n\n\t\tstatic inline\n\t\tvoid push(State* state, Integer value) {\n\t\t\tlua_pushinteger(state, value);\n\t\t}\n\t};\n\n\t\/\/ Transport unit `Number`\n\ttemplate <>\n\tstruct NumericTransportValue<Number> {\n\t\tstatic inline\n\t\tNumber read(State* state, int index) {\n\t\t\treturn luaL_checknumber(state, index);\n\t\t}\n\n\t\tstatic inline\n\t\tvoid push(State* state, Number value) {\n\t\t\tlua_pushnumber(state, value);\n\t\t}\n\t};\n\n\t\/\/ Base for `Value<Type>` specializations which uses `Transport` as transport unit\n\ttemplate <typename Type, typename Transport>\n\tstruct NumericValueBase {\n\t\tstatic inline\n\t\tType read(State* state, int index) {\n\t\t\treturn static_cast<Type>(NumericTransportValue<Transport>::read(state, index));\n\t\t}\n\n\t\tstatic inline\n\t\tvoid push(State* state, Type value) {\n\t\t\tNumericTransportValue<Transport>::push(state, static_cast<Transport>(value));\n\t\t}\n\t};\n}\n\n\/\/ Define an integral type which will be transported via `base`.\n#define LUWRA_DEF_NUMERIC(base, type) \\\n\ttemplate <> \\\n\tstruct Value<type>: internal::NumericValueBase<type, base> {};\n\n\/\/ Lua-dependent types\nLUWRA_DEF_NUMERIC(Number, float)\nLUWRA_DEF_NUMERIC(Number, double)\nLUWRA_DEF_NUMERIC(Number, long double)\n\n\/\/ Integral types\nLUWRA_DEF_NUMERIC(Integer, signed char)\nLUWRA_DEF_NUMERIC(Integer, unsigned char)\nLUWRA_DEF_NUMERIC(Integer, signed short)\nLUWRA_DEF_NUMERIC(Integer, unsigned short)\nLUWRA_DEF_NUMERIC(Integer, signed int)\nLUWRA_DEF_NUMERIC(Integer, unsigned int)\nLUWRA_DEF_NUMERIC(Integer, signed long int)\nLUWRA_DEF_NUMERIC(Integer, unsigned long int)\nLUWRA_DEF_NUMERIC(Integer, signed long long int)\nLUWRA_DEF_NUMERIC(Integer, unsigned long long int)\n\n\/\/ Do not export this macros\n#undef LUWRA_DEF_NUMERIC\n\n\/\/\/ Enables reading\/pushing strings as C strings\ntemplate <>\nstruct Value<const char*> {\n\tstatic inline\n\tconst char* read(State* state, int n) {\n\t\treturn luaL_checkstring(state, n);\n\t}\n\n\tstatic inline\n\tvoid push(State* state, const char* value) {\n\t\tlua_pushstring(state, value);\n\t}\n};\n\n\/\/\/ Enables reading\/pushing string as `std::string`.\ntemplate <>\nstruct Value<std::string> {\n\tstatic inline\n\tstd::string read(State* state, int n) {\n\t\tsize_t length;\n\t\tconst char* value = luaL_checklstring(state, n, &length);\n\t\treturn {value, length};\n\t}\n\n\tstatic inline\n\tvoid push(State* state, const std::string& value) {\n\t\tlua_pushstring(state, value.c_str());\n\t}\n};\n\n\/\/\/ Enables reading\/pushing booleans\ntemplate <>\nstruct Value<bool> {\n\tstatic inline\n\tbool read(State* state, int n) {\n\t\tluaL_checktype(state, n, LUA_TBOOLEAN);\n\t\treturn lua_toboolean(state, n) == 1;\n\t}\n\n\tstatic inline\n\tvoid push(State* state, bool value) {\n\t\tlua_pushboolean(state, static_cast<int>(value));\n\t}\n};\n\n\/\/\/ Alias for @ref Value<const char*>\ntemplate <>\nstruct Value<char*>: Value<const char*> {};\n\n\/\/\/ Alias for @ref Value<const char*>\ntemplate <size_t N>\nstruct Value<char[N]>: Value<const char*> {};\n\n\/\/\/ Alias for @ref Value<const char*>\ntemplate <size_t N>\nstruct Value<const char[N]>: Value<const char*> {};\n\n\/\/\/ A version of @ref Value for pushing return values onto the stack. @ref ReturnValue inherits\n\/\/\/ `push` implementations from @ref Value.\ntemplate <typename Type>\nstruct ReturnValue {\n\ttemplate <typename... Args> static inline\n\tsize_t push(State* state, Args&&... args) {\n\t\tValue<Type>::push(state, std::forward<Args>(args)...);\n\t\treturn 1;\n\t}\n};\n\n\/\/\/ Alias for `ReturnValue<Type>`\ntemplate <typename Type>\nstruct ReturnValue<const Type>: ReturnValue<Type> {};\n\n\/\/\/ Alias for `ReturnValue<Type>`\ntemplate <typename Type>\nstruct ReturnValue<volatile Type>: ReturnValue<Type> {};\n\n\/\/\/ Alias for `ReturnValue<Type>`\ntemplate <typename Type>\nstruct ReturnValue<const volatile Type>: ReturnValue<Type> {};\n\n\/\/\/ Alias for `ReturnValue<Type>`\ntemplate <typename Type>\nstruct ReturnValue<Type&>: ReturnValue<Type> {};\n\n\/\/\/ Alias for `ReturnValue<Type>`\ntemplate <typename Type>\nstruct ReturnValue<Type&&>: ReturnValue<Type> {};\n\nLUWRA_NS_END\n\n#endif\n<commit_msg>Make 'InferValueType' conversion operators as inline<commit_after>\/* Luwra\n * Minimal-overhead Lua wrapper for C++\n *\n * Copyright (C) 2015, Ole Krüger <ole@vprsm.de>\n *\/\n\n#ifndef LUWRA_VALUES_H_\n#define LUWRA_VALUES_H_\n\n#include \"common.hpp\"\n#include \"internal\/indexsequence.hpp\"\n\n#include <utility>\n#include <string>\n\nLUWRA_NS_BEGIN\n\ntemplate <typename UserType>\nstruct Value;\n\n\/\/\/ Alias for @ref Value<Type>\ntemplate <typename Type>\nstruct Value<const Type>: Value<Type> {};\n\n\/\/\/ Alias for @ref Value<Type>\ntemplate <typename Type>\nstruct Value<volatile Type>: Value<Type> {};\n\n\/\/\/ Alias for @ref Value<Type>\ntemplate <typename Type>\nstruct Value<const volatile Type>: Value<Type> {};\n\n\/\/\/ Alias for @ref Value<Type>\ntemplate <typename Type>\nstruct Value<Type&>: Value<Type> {};\n\n\/\/\/ Alias for @ref Value<Type>\ntemplate <typename Type>\nstruct Value<Type&&>: Value<Type> {};\n\nnamespace internal {\n\tstruct InferValueType {\n\t\tState* state;\n\t\tint index;\n\n\t\ttemplate <typename Type> inline\n\t\toperator Type() const && {\n\t\t\treturn Value<Type>::read(state, index);\n\t\t}\n\n\t\ttemplate <typename Type> inline\n\t\toperator Type&() const & {\n\t\t\treturn Value<Type&>::read(state, index);\n\t\t}\n\t};\n}\n\n\/\/\/ Enables reading of type-infered values\ntemplate <>\nstruct Value<internal::InferValueType> {\n\tstatic inline\n\tconst internal::InferValueType read(State* state, int index) {\n\t\treturn {state, index};\n\t}\n};\n\n\/\/\/ Enables reading\/pushing `nil`\ntemplate <>\nstruct Value<std::nullptr_t> {\n\tstatic inline\n\tstd::nullptr_t read(State* state, int n) {\n\t\tluaL_checktype(state, n, LUA_TNIL);\n\t\treturn nullptr;\n\t}\n\n\tstatic inline\n\tvoid push(State* state, std::nullptr_t) {\n\t\tlua_pushnil(state);\n\t}\n};\n\n\/\/\/ Enables reading Lua threads\ntemplate <>\nstruct Value<State*> {\n\tstatic inline\n\tState* read(State* state, int n) {\n\t\tluaL_checktype(state, n, LUA_TTHREAD);\n\t\treturn lua_tothread(state, n);\n\t}\n};\n\n\/\/\/ Enables reading\/pushing light data\ntemplate <>\nstruct Value<void*> {\n\tstatic inline\n\tvoid* read(State* state, int n) {\n\t\tluaL_checktype(state, n, LUA_TLIGHTUSERDATA);\n\t\treturn lua_touserdata(state, n);\n\t}\n\n\tstatic inline\n\tvoid push(State* state, void* data) {\n\t\tlua_pushlightuserdata(state, data);\n\t}\n};\n\n\/\/\/ Enables reading constant light data\ntemplate <>\nstruct Value<const void*> {\n\tstatic inline\n\tconst void* read(State* state, int n) {\n\t\tluaL_checktype(state, n, LUA_TLIGHTUSERDATA);\n\t\treturn lua_touserdata(state, n);\n\t}\n};\n\nnamespace internal {\n\ttemplate <typename Type>\n\tstruct NumericTransportValue {\n\t\tstatic_assert(\n\t\t\tsizeof(Type) == -1,\n\t\t\t\"Parameter to NumericTransportValue is not a numeric base type\"\n\t\t);\n\t};\n\n\t\/\/ Transport unit `Integer`\n\ttemplate <>\n\tstruct NumericTransportValue<Integer> {\n\t\tstatic inline\n\t\tInteger read(State* state, int index) {\n\t\t\treturn luaL_checkinteger(state, index);\n\t\t}\n\n\t\tstatic inline\n\t\tvoid push(State* state, Integer value) {\n\t\t\tlua_pushinteger(state, value);\n\t\t}\n\t};\n\n\t\/\/ Transport unit `Number`\n\ttemplate <>\n\tstruct NumericTransportValue<Number> {\n\t\tstatic inline\n\t\tNumber read(State* state, int index) {\n\t\t\treturn luaL_checknumber(state, index);\n\t\t}\n\n\t\tstatic inline\n\t\tvoid push(State* state, Number value) {\n\t\t\tlua_pushnumber(state, value);\n\t\t}\n\t};\n\n\t\/\/ Base for `Value<Type>` specializations which uses `Transport` as transport unit\n\ttemplate <typename Type, typename Transport>\n\tstruct NumericValueBase {\n\t\tstatic inline\n\t\tType read(State* state, int index) {\n\t\t\treturn static_cast<Type>(NumericTransportValue<Transport>::read(state, index));\n\t\t}\n\n\t\tstatic inline\n\t\tvoid push(State* state, Type value) {\n\t\t\tNumericTransportValue<Transport>::push(state, static_cast<Transport>(value));\n\t\t}\n\t};\n}\n\n\/\/ Define an integral type which will be transported via `base`.\n#define LUWRA_DEF_NUMERIC(base, type) \\\n\ttemplate <> \\\n\tstruct Value<type>: internal::NumericValueBase<type, base> {};\n\n\/\/ Lua-dependent types\nLUWRA_DEF_NUMERIC(Number, float)\nLUWRA_DEF_NUMERIC(Number, double)\nLUWRA_DEF_NUMERIC(Number, long double)\n\n\/\/ Integral types\nLUWRA_DEF_NUMERIC(Integer, signed char)\nLUWRA_DEF_NUMERIC(Integer, unsigned char)\nLUWRA_DEF_NUMERIC(Integer, signed short)\nLUWRA_DEF_NUMERIC(Integer, unsigned short)\nLUWRA_DEF_NUMERIC(Integer, signed int)\nLUWRA_DEF_NUMERIC(Integer, unsigned int)\nLUWRA_DEF_NUMERIC(Integer, signed long int)\nLUWRA_DEF_NUMERIC(Integer, unsigned long int)\nLUWRA_DEF_NUMERIC(Integer, signed long long int)\nLUWRA_DEF_NUMERIC(Integer, unsigned long long int)\n\n\/\/ Do not export this macros\n#undef LUWRA_DEF_NUMERIC\n\n\/\/\/ Enables reading\/pushing strings as C strings\ntemplate <>\nstruct Value<const char*> {\n\tstatic inline\n\tconst char* read(State* state, int n) {\n\t\treturn luaL_checkstring(state, n);\n\t}\n\n\tstatic inline\n\tvoid push(State* state, const char* value) {\n\t\tlua_pushstring(state, value);\n\t}\n};\n\n\/\/\/ Enables reading\/pushing string as `std::string`.\ntemplate <>\nstruct Value<std::string> {\n\tstatic inline\n\tstd::string read(State* state, int n) {\n\t\tsize_t length;\n\t\tconst char* value = luaL_checklstring(state, n, &length);\n\t\treturn {value, length};\n\t}\n\n\tstatic inline\n\tvoid push(State* state, const std::string& value) {\n\t\tlua_pushstring(state, value.c_str());\n\t}\n};\n\n\/\/\/ Enables reading\/pushing booleans\ntemplate <>\nstruct Value<bool> {\n\tstatic inline\n\tbool read(State* state, int n) {\n\t\tluaL_checktype(state, n, LUA_TBOOLEAN);\n\t\treturn lua_toboolean(state, n) == 1;\n\t}\n\n\tstatic inline\n\tvoid push(State* state, bool value) {\n\t\tlua_pushboolean(state, static_cast<int>(value));\n\t}\n};\n\n\/\/\/ Alias for @ref Value<const char*>\ntemplate <>\nstruct Value<char*>: Value<const char*> {};\n\n\/\/\/ Alias for @ref Value<const char*>\ntemplate <size_t N>\nstruct Value<char[N]>: Value<const char*> {};\n\n\/\/\/ Alias for @ref Value<const char*>\ntemplate <size_t N>\nstruct Value<const char[N]>: Value<const char*> {};\n\n\/\/\/ A version of @ref Value for pushing return values onto the stack. @ref ReturnValue inherits\n\/\/\/ `push` implementations from @ref Value.\ntemplate <typename Type>\nstruct ReturnValue {\n\ttemplate <typename... Args> static inline\n\tsize_t push(State* state, Args&&... args) {\n\t\tValue<Type>::push(state, std::forward<Args>(args)...);\n\t\treturn 1;\n\t}\n};\n\n\/\/\/ Alias for `ReturnValue<Type>`\ntemplate <typename Type>\nstruct ReturnValue<const Type>: ReturnValue<Type> {};\n\n\/\/\/ Alias for `ReturnValue<Type>`\ntemplate <typename Type>\nstruct ReturnValue<volatile Type>: ReturnValue<Type> {};\n\n\/\/\/ Alias for `ReturnValue<Type>`\ntemplate <typename Type>\nstruct ReturnValue<const volatile Type>: ReturnValue<Type> {};\n\n\/\/\/ Alias for `ReturnValue<Type>`\ntemplate <typename Type>\nstruct ReturnValue<Type&>: ReturnValue<Type> {};\n\n\/\/\/ Alias for `ReturnValue<Type>`\ntemplate <typename Type>\nstruct ReturnValue<Type&&>: ReturnValue<Type> {};\n\nLUWRA_NS_END\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>#include \"Memory.h\"\n\n#include <vector>\n#include <iostream>\n#include <iomanip>\n#include <cstdint>\n#include <cassert>\n\n#include <llvm\/IR\/GlobalVariable.h>\n#include <llvm\/IR\/Function.h>\n\n#include <libdevcore\/Common.h>\n\n#include \"Type.h\"\n#include \"Runtime.h\"\n#include \"GasMeter.h\"\n#include \"Endianness.h\"\n#include \"Runtime.h\"\n\nnamespace dev\n{\nnamespace eth\n{\nnamespace jit\n{\n\nMemory::Memory(RuntimeManager& _runtimeManager, GasMeter& _gasMeter):\n\tRuntimeHelper(_runtimeManager)\n{\n\tauto module = getModule();\n\tauto i64Ty = m_builder.getInt64Ty();\n\tllvm::Type* argTypes[] = {i64Ty, i64Ty};\n\tauto dumpTy = llvm::FunctionType::get(m_builder.getVoidTy(), llvm::ArrayRef<llvm::Type*>(argTypes), false);\n\tm_memDump = llvm::Function::Create(dumpTy, llvm::GlobalValue::LinkageTypes::ExternalLinkage,\n\t\t\t\t\t\t\t\t\t \"evmccrt_memory_dump\", module);\n\n\tm_data = new llvm::GlobalVariable(*module, Type::BytePtr, false, llvm::GlobalVariable::PrivateLinkage, llvm::UndefValue::get(Type::BytePtr), \"mem.data\");\n\tm_data->setUnnamedAddr(true); \/\/ Address is not important\n\n\tm_size = new llvm::GlobalVariable(*module, Type::i256, false, llvm::GlobalVariable::PrivateLinkage, Constant::get(0), \"mem.size\");\n\tm_size->setUnnamedAddr(true); \/\/ Address is not important\n\n\tllvm::Type* resizeArgs[] = {Type::RuntimePtr, Type::WordPtr};\n\tm_resize = llvm::Function::Create(llvm::FunctionType::get(Type::BytePtr, resizeArgs, false), llvm::Function::ExternalLinkage, \"mem_resize\", module);\n\tllvm::AttrBuilder attrBuilder;\n\tattrBuilder.addAttribute(llvm::Attribute::NoAlias).addAttribute(llvm::Attribute::NoCapture).addAttribute(llvm::Attribute::NonNull).addAttribute(llvm::Attribute::ReadOnly);\n\tm_resize->setAttributes(llvm::AttributeSet::get(m_resize->getContext(), 1, attrBuilder));\n\n\tm_require = createRequireFunc(_gasMeter, _runtimeManager);\n\tm_loadWord = createFunc(false, Type::i256, _gasMeter);\n\tm_storeWord = createFunc(true, Type::i256, _gasMeter);\n\tm_storeByte = createFunc(true, Type::Byte, _gasMeter);\n}\n\nllvm::Function* Memory::createRequireFunc(GasMeter& _gasMeter, RuntimeManager& _runtimeManager)\n{\n\tauto func = llvm::Function::Create(llvm::FunctionType::get(Type::Void, Type::i256, false), llvm::Function::PrivateLinkage, \"mem.require\", getModule());\n\n\tauto checkBB = llvm::BasicBlock::Create(func->getContext(), \"check\", func);\n\tauto resizeBB = llvm::BasicBlock::Create(func->getContext(), \"resize\", func);\n\tauto returnBB = llvm::BasicBlock::Create(func->getContext(), \"return\", func);\n\n\tInsertPointGuard guard(m_builder); \/\/ Restores insert point at function exit\n\n\t\/\/ BB \"check\"\n\tm_builder.SetInsertPoint(checkBB);\n\tllvm::Value* sizeRequired = func->arg_begin();\n\tsizeRequired->setName(\"sizeRequired\");\n\tauto size = m_builder.CreateLoad(m_size, \"size\");\n\tauto resizeNeeded = m_builder.CreateICmpULE(size, sizeRequired, \"resizeNeeded\");\n\tm_builder.CreateCondBr(resizeNeeded, resizeBB, returnBB); \/\/ OPT branch weights?\n\n\t\/\/ BB \"resize\"\n\tm_builder.SetInsertPoint(resizeBB);\n\t\/\/ Check gas first\n\tauto wordsRequired = m_builder.CreateUDiv(m_builder.CreateAdd(sizeRequired, Constant::get(31)), Constant::get(32), \"wordsRequired\");\n\tauto words = m_builder.CreateUDiv(m_builder.CreateAdd(size, Constant::get(31)), Constant::get(32), \"words\");\n\tauto newWords = m_builder.CreateSub(wordsRequired, words, \"addtionalWords\");\n\t_gasMeter.checkMemory(newWords, m_builder);\n\t\/\/ Resize\n\tm_builder.CreateStore(sizeRequired, m_size);\n\tauto newData = m_builder.CreateCall2(m_resize, _runtimeManager.getRuntimePtr(), m_size, \"newData\");\n\tm_builder.CreateStore(newData, m_data);\n\tm_builder.CreateBr(returnBB);\n\n\t\/\/ BB \"return\"\n\tm_builder.SetInsertPoint(returnBB);\n\tm_builder.CreateRetVoid();\n\treturn func;\n}\n\nllvm::Function* Memory::createFunc(bool _isStore, llvm::Type* _valueType, GasMeter&)\n{\n\tauto isWord = _valueType == Type::i256;\n\n\tllvm::Type* storeArgs[] = {Type::i256, _valueType};\n\tauto name = _isStore ? isWord ? \"mstore\" : \"mstore8\" : \"mload\";\n\tauto funcType = _isStore ? llvm::FunctionType::get(Type::Void, storeArgs, false) : llvm::FunctionType::get(Type::i256, Type::i256, false);\n\tauto func = llvm::Function::Create(funcType, llvm::Function::PrivateLinkage, name, getModule());\n\n\tInsertPointGuard guard(m_builder); \/\/ Restores insert point at function exit\n\n\tm_builder.SetInsertPoint(llvm::BasicBlock::Create(func->getContext(), {}, func));\n\tllvm::Value* index = func->arg_begin();\n\tindex->setName(\"index\");\n\n\tauto valueSize = _valueType->getPrimitiveSizeInBits() \/ 8;\n\tthis->require(index, Constant::get(valueSize));\n\tauto data = m_builder.CreateLoad(m_data, \"data\");\n\tauto ptr = m_builder.CreateGEP(data, index, \"ptr\");\n\tif (isWord)\n\t\tptr = m_builder.CreateBitCast(ptr, Type::WordPtr, \"wordPtr\");\n\tif (_isStore)\n\t{\n\t\tllvm::Value* value = ++func->arg_begin();\n\t\tvalue->setName(\"value\");\n\t\tif (isWord)\n\t\t\tvalue = Endianness::toBE(m_builder, value);\n\t\tm_builder.CreateStore(value, ptr);\n\t\tm_builder.CreateRetVoid();\n\t}\n\telse\n\t{\n\t\tllvm::Value* ret = m_builder.CreateLoad(ptr);\n\t\tret = Endianness::toNative(m_builder, ret);\n\t\tm_builder.CreateRet(ret);\n\t}\n\n\treturn func;\n}\n\n\nllvm::Value* Memory::loadWord(llvm::Value* _addr)\n{\n\tauto value = m_builder.CreateCall(m_loadWord, _addr);\n\n\tdump(0);\n\treturn value;\n}\n\nvoid Memory::storeWord(llvm::Value* _addr, llvm::Value* _word)\n{\n\tm_builder.CreateCall2(m_storeWord, _addr, _word);\n\n\tdump(0);\n}\n\nvoid Memory::storeByte(llvm::Value* _addr, llvm::Value* _word)\n{\n\tauto byte = m_builder.CreateTrunc(_word, Type::Byte, \"byte\");\n\tm_builder.CreateCall2(m_storeByte, _addr, byte);\n\n\tdump(0);\n}\n\nllvm::Value* Memory::getData()\n{\n\treturn m_builder.CreateLoad(m_data);\n}\n\nllvm::Value* Memory::getSize()\n{\n\treturn m_builder.CreateLoad(m_size);\n}\n\nvoid Memory::require(llvm::Value* _size)\n{\n\tm_builder.CreateCall(m_require, _size);\n}\n\nvoid Memory::require(llvm::Value* _offset, llvm::Value* _size)\n{\n\tauto sizeRequired = m_builder.CreateAdd(_offset, _size, \"sizeRequired\");\n\trequire(sizeRequired);\n}\n\nvoid Memory::copyBytes(llvm::Value* _srcPtr, llvm::Value* _srcSize, llvm::Value* _srcIdx,\n\t\t\t\t\t llvm::Value* _destMemIdx, llvm::Value* _reqBytes)\n{\n\tauto zero256 = llvm::ConstantInt::get(Type::i256, 0);\n\n\tauto reqMemSize = m_builder.CreateAdd(_destMemIdx, _reqBytes, \"req_mem_size\");\n\trequire(reqMemSize);\n\n\tauto srcPtr = m_builder.CreateGEP(_srcPtr, _srcIdx, \"src_idx\");\n\n\tauto memPtr = getData();\n\tauto destPtr = m_builder.CreateGEP(memPtr, _destMemIdx, \"dest_mem_ptr\");\n\n\t\/\/ remaining source bytes:\n\tauto remSrcSize = m_builder.CreateSub(_srcSize, _srcIdx);\n\tauto remSizeNegative = m_builder.CreateICmpSLT(remSrcSize, zero256);\n\tauto remSrcBytes = m_builder.CreateSelect(remSizeNegative, zero256, remSrcSize, \"rem_src_bytes\");\n\n\tauto tooFewSrcBytes = m_builder.CreateICmpULT(remSrcBytes, _reqBytes);\n\tauto bytesToCopy = m_builder.CreateSelect(tooFewSrcBytes, remSrcBytes, _reqBytes, \"bytes_to_copy\");\n\n\tm_builder.CreateMemCpy(destPtr, srcPtr, bytesToCopy, 0);\n}\n\nvoid Memory::dump(uint64_t _begin, uint64_t _end)\n{\n\tif (getenv(\"EVMCC_DEBUG_MEMORY\") == nullptr)\n\t\treturn;\n\n\tauto beginVal = llvm::ConstantInt::get(m_builder.getInt64Ty(), _begin);\n\tauto endVal = llvm::ConstantInt::get(m_builder.getInt64Ty(), _end);\n\n\tstd::vector<llvm::Value*> args = {beginVal, endVal};\n\tm_builder.CreateCall(m_memDump, llvm::ArrayRef<llvm::Value*>(args));\n}\n\n}\n}\n}\n\n\nextern \"C\"\n{\n\n\tusing namespace dev::eth::jit;\n\n\tEXPORT uint8_t* mem_resize(Runtime* _rt, i256* _size)\n\t{\n\t\tauto size = _size->a; \/\/ Trunc to 64-bit\n\t\tauto& memory = _rt->getMemory();\n\t\tmemory.resize(size);\n\t\treturn memory.data();\n\t}\n\n} \/\/ extern \"C\"\n<commit_msg>Fix MSIZE and memory resize step [Delivers #81777708]<commit_after>#include \"Memory.h\"\n\n#include <vector>\n#include <iostream>\n#include <iomanip>\n#include <cstdint>\n#include <cassert>\n\n#include <llvm\/IR\/GlobalVariable.h>\n#include <llvm\/IR\/Function.h>\n\n#include <libdevcore\/Common.h>\n\n#include \"Type.h\"\n#include \"Runtime.h\"\n#include \"GasMeter.h\"\n#include \"Endianness.h\"\n#include \"Runtime.h\"\n\nnamespace dev\n{\nnamespace eth\n{\nnamespace jit\n{\n\nMemory::Memory(RuntimeManager& _runtimeManager, GasMeter& _gasMeter):\n\tRuntimeHelper(_runtimeManager)\n{\n\tauto module = getModule();\n\tauto i64Ty = m_builder.getInt64Ty();\n\tllvm::Type* argTypes[] = {i64Ty, i64Ty};\n\tauto dumpTy = llvm::FunctionType::get(m_builder.getVoidTy(), llvm::ArrayRef<llvm::Type*>(argTypes), false);\n\tm_memDump = llvm::Function::Create(dumpTy, llvm::GlobalValue::LinkageTypes::ExternalLinkage,\n\t\t\t\t\t\t\t\t\t \"evmccrt_memory_dump\", module);\n\n\tm_data = new llvm::GlobalVariable(*module, Type::BytePtr, false, llvm::GlobalVariable::PrivateLinkage, llvm::UndefValue::get(Type::BytePtr), \"mem.data\");\n\tm_data->setUnnamedAddr(true); \/\/ Address is not important\n\n\tm_size = new llvm::GlobalVariable(*module, Type::i256, false, llvm::GlobalVariable::PrivateLinkage, Constant::get(0), \"mem.size\");\n\tm_size->setUnnamedAddr(true); \/\/ Address is not important\n\n\tllvm::Type* resizeArgs[] = {Type::RuntimePtr, Type::WordPtr};\n\tm_resize = llvm::Function::Create(llvm::FunctionType::get(Type::BytePtr, resizeArgs, false), llvm::Function::ExternalLinkage, \"mem_resize\", module);\n\tllvm::AttrBuilder attrBuilder;\n\tattrBuilder.addAttribute(llvm::Attribute::NoAlias).addAttribute(llvm::Attribute::NoCapture).addAttribute(llvm::Attribute::NonNull).addAttribute(llvm::Attribute::ReadOnly);\n\tm_resize->setAttributes(llvm::AttributeSet::get(m_resize->getContext(), 1, attrBuilder));\n\n\tm_require = createRequireFunc(_gasMeter, _runtimeManager);\n\tm_loadWord = createFunc(false, Type::i256, _gasMeter);\n\tm_storeWord = createFunc(true, Type::i256, _gasMeter);\n\tm_storeByte = createFunc(true, Type::Byte, _gasMeter);\n}\n\nllvm::Function* Memory::createRequireFunc(GasMeter& _gasMeter, RuntimeManager& _runtimeManager)\n{\n\tauto func = llvm::Function::Create(llvm::FunctionType::get(Type::Void, Type::i256, false), llvm::Function::PrivateLinkage, \"mem.require\", getModule());\n\n\tauto checkBB = llvm::BasicBlock::Create(func->getContext(), \"check\", func);\n\tauto resizeBB = llvm::BasicBlock::Create(func->getContext(), \"resize\", func);\n\tauto returnBB = llvm::BasicBlock::Create(func->getContext(), \"return\", func);\n\n\tInsertPointGuard guard(m_builder); \/\/ Restores insert point at function exit\n\n\t\/\/ BB \"check\"\n\tm_builder.SetInsertPoint(checkBB);\n\tllvm::Value* sizeRequired = func->arg_begin();\n\tsizeRequired->setName(\"sizeRequired\");\n\tauto size = m_builder.CreateLoad(m_size, \"size\");\n\tauto resizeNeeded = m_builder.CreateICmpULE(size, sizeRequired, \"resizeNeeded\");\n\tm_builder.CreateCondBr(resizeNeeded, resizeBB, returnBB); \/\/ OPT branch weights?\n\n\t\/\/ BB \"resize\"\n\tm_builder.SetInsertPoint(resizeBB);\n\t\/\/ Check gas first\n\tauto wordsRequired = m_builder.CreateUDiv(m_builder.CreateAdd(sizeRequired, Constant::get(31)), Constant::get(32), \"wordsRequired\");\n\tsizeRequired = m_builder.CreateMul(wordsRequired, Constant::get(32), \"roundedSizeRequired\");\n\tauto words = m_builder.CreateUDiv(size, Constant::get(32), \"words\");\t\/\/ size is always 32*k\n\tauto newWords = m_builder.CreateSub(wordsRequired, words, \"addtionalWords\");\n\t_gasMeter.checkMemory(newWords, m_builder);\n\t\/\/ Resize\n\tm_builder.CreateStore(sizeRequired, m_size);\n\tauto newData = m_builder.CreateCall2(m_resize, _runtimeManager.getRuntimePtr(), m_size, \"newData\");\n\tm_builder.CreateStore(newData, m_data);\n\tm_builder.CreateBr(returnBB);\n\n\t\/\/ BB \"return\"\n\tm_builder.SetInsertPoint(returnBB);\n\tm_builder.CreateRetVoid();\n\treturn func;\n}\n\nllvm::Function* Memory::createFunc(bool _isStore, llvm::Type* _valueType, GasMeter&)\n{\n\tauto isWord = _valueType == Type::i256;\n\n\tllvm::Type* storeArgs[] = {Type::i256, _valueType};\n\tauto name = _isStore ? isWord ? \"mstore\" : \"mstore8\" : \"mload\";\n\tauto funcType = _isStore ? llvm::FunctionType::get(Type::Void, storeArgs, false) : llvm::FunctionType::get(Type::i256, Type::i256, false);\n\tauto func = llvm::Function::Create(funcType, llvm::Function::PrivateLinkage, name, getModule());\n\n\tInsertPointGuard guard(m_builder); \/\/ Restores insert point at function exit\n\n\tm_builder.SetInsertPoint(llvm::BasicBlock::Create(func->getContext(), {}, func));\n\tllvm::Value* index = func->arg_begin();\n\tindex->setName(\"index\");\n\n\tauto valueSize = _valueType->getPrimitiveSizeInBits() \/ 8;\n\tthis->require(index, Constant::get(valueSize));\n\tauto data = m_builder.CreateLoad(m_data, \"data\");\n\tauto ptr = m_builder.CreateGEP(data, index, \"ptr\");\n\tif (isWord)\n\t\tptr = m_builder.CreateBitCast(ptr, Type::WordPtr, \"wordPtr\");\n\tif (_isStore)\n\t{\n\t\tllvm::Value* value = ++func->arg_begin();\n\t\tvalue->setName(\"value\");\n\t\tif (isWord)\n\t\t\tvalue = Endianness::toBE(m_builder, value);\n\t\tm_builder.CreateStore(value, ptr);\n\t\tm_builder.CreateRetVoid();\n\t}\n\telse\n\t{\n\t\tllvm::Value* ret = m_builder.CreateLoad(ptr);\n\t\tret = Endianness::toNative(m_builder, ret);\n\t\tm_builder.CreateRet(ret);\n\t}\n\n\treturn func;\n}\n\n\nllvm::Value* Memory::loadWord(llvm::Value* _addr)\n{\n\tauto value = m_builder.CreateCall(m_loadWord, _addr);\n\n\tdump(0);\n\treturn value;\n}\n\nvoid Memory::storeWord(llvm::Value* _addr, llvm::Value* _word)\n{\n\tm_builder.CreateCall2(m_storeWord, _addr, _word);\n\n\tdump(0);\n}\n\nvoid Memory::storeByte(llvm::Value* _addr, llvm::Value* _word)\n{\n\tauto byte = m_builder.CreateTrunc(_word, Type::Byte, \"byte\");\n\tm_builder.CreateCall2(m_storeByte, _addr, byte);\n\n\tdump(0);\n}\n\nllvm::Value* Memory::getData()\n{\n\treturn m_builder.CreateLoad(m_data);\n}\n\nllvm::Value* Memory::getSize()\n{\n\treturn m_builder.CreateLoad(m_size);\n}\n\nvoid Memory::require(llvm::Value* _size)\n{\n\tm_builder.CreateCall(m_require, _size);\n}\n\nvoid Memory::require(llvm::Value* _offset, llvm::Value* _size)\n{\n\tauto sizeRequired = m_builder.CreateAdd(_offset, _size, \"sizeRequired\");\n\trequire(sizeRequired);\n}\n\nvoid Memory::copyBytes(llvm::Value* _srcPtr, llvm::Value* _srcSize, llvm::Value* _srcIdx,\n\t\t\t\t\t llvm::Value* _destMemIdx, llvm::Value* _reqBytes)\n{\n\tauto zero256 = llvm::ConstantInt::get(Type::i256, 0);\n\n\tauto reqMemSize = m_builder.CreateAdd(_destMemIdx, _reqBytes, \"req_mem_size\");\n\trequire(reqMemSize);\n\n\tauto srcPtr = m_builder.CreateGEP(_srcPtr, _srcIdx, \"src_idx\");\n\n\tauto memPtr = getData();\n\tauto destPtr = m_builder.CreateGEP(memPtr, _destMemIdx, \"dest_mem_ptr\");\n\n\t\/\/ remaining source bytes:\n\tauto remSrcSize = m_builder.CreateSub(_srcSize, _srcIdx);\n\tauto remSizeNegative = m_builder.CreateICmpSLT(remSrcSize, zero256);\n\tauto remSrcBytes = m_builder.CreateSelect(remSizeNegative, zero256, remSrcSize, \"rem_src_bytes\");\n\n\tauto tooFewSrcBytes = m_builder.CreateICmpULT(remSrcBytes, _reqBytes);\n\tauto bytesToCopy = m_builder.CreateSelect(tooFewSrcBytes, remSrcBytes, _reqBytes, \"bytes_to_copy\");\n\n\tm_builder.CreateMemCpy(destPtr, srcPtr, bytesToCopy, 0);\n}\n\nvoid Memory::dump(uint64_t _begin, uint64_t _end)\n{\n\tif (getenv(\"EVMCC_DEBUG_MEMORY\") == nullptr)\n\t\treturn;\n\n\tauto beginVal = llvm::ConstantInt::get(m_builder.getInt64Ty(), _begin);\n\tauto endVal = llvm::ConstantInt::get(m_builder.getInt64Ty(), _end);\n\n\tstd::vector<llvm::Value*> args = {beginVal, endVal};\n\tm_builder.CreateCall(m_memDump, llvm::ArrayRef<llvm::Value*>(args));\n}\n\n}\n}\n}\n\n\nextern \"C\"\n{\n\n\tusing namespace dev::eth::jit;\n\n\tEXPORT uint8_t* mem_resize(Runtime* _rt, i256* _size)\n\t{\n\t\tauto size = _size->a; \/\/ Trunc to 64-bit\n\t\tauto& memory = _rt->getMemory();\n\t\tmemory.resize(size);\n\t\treturn memory.data();\n\t}\n\n} \/\/ extern \"C\"\n<|endoftext|>"} {"text":"<commit_before>#include \"stdafx.h\"\n#include \"ProcessInfoProvider.h\"\n\nclass Handle;\n\nProcessInfoProvider::ProcessInfoProvider()\n{\n}\n\n\nProcessInfoProvider::~ProcessInfoProvider()\n{\n}\n\ntypedef BOOL(WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);\nbool ProcessInfoProvider::IsWow64() const\n{\t\n\tint bIsWow64 = false;\n\tLPFN_ISWOW64PROCESS fnIsWow64Process;\n\tfnIsWow64Process = reinterpret_cast<LPFN_ISWOW64PROCESS>(GetProcAddress(GetModuleHandle(TEXT(\"kernel32\")), \"IsWow64Process\"));\n\tif (NULL != fnIsWow64Process)\n\t{\n\t\tif (!fnIsWow64Process(GetCurrentProcess(), &bIsWow64))\n\t\t{\n\t\t\treturn false;\n\t\t}\n\t}\n\n\treturn bIsWow64 != 0;\n}\n\nbool ProcessInfoProvider::IsSuitableOS() const\n{\n#if defined(_M_X64) || defined(x86_64)\t\n#else\n\tif (Is64OS())\n\t{\n\t\treturn false;\n\t}\n#endif\n\t\n\treturn true;\n}\n<commit_msg>Fix build<commit_after>#include \"stdafx.h\"\n#include \"ProcessInfoProvider.h\"\n\nclass Handle;\n\nProcessInfoProvider::ProcessInfoProvider()\n{\n}\n\n\nProcessInfoProvider::~ProcessInfoProvider()\n{\n}\n\ntypedef BOOL(WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);\nbool ProcessInfoProvider::IsWow64() const\n{\t\n\tint bIsWow64 = false;\n\tLPFN_ISWOW64PROCESS fnIsWow64Process;\n\tfnIsWow64Process = reinterpret_cast<LPFN_ISWOW64PROCESS>(GetProcAddress(GetModuleHandle(TEXT(\"kernel32\")), \"IsWow64Process\"));\n\tif (NULL != fnIsWow64Process)\n\t{\n\t\tif (!fnIsWow64Process(GetCurrentProcess(), &bIsWow64))\n\t\t{\n\t\t\treturn false;\n\t\t}\n\t}\n\n\treturn bIsWow64 != 0;\n}\n\nbool ProcessInfoProvider::IsSuitableOS() const\n{\n#if defined(_M_X64) || defined(x86_64)\t\n#else\n\tif (Is64OS())\n\t{\n\t\treturn false;\n\t}\n#endif\n\t\n\treturn true;\n}\n\nbool ProcessInfoProvider::Is64OS() const\n{\n#if defined(_M_X64) || defined(x86_64)\n\treturn true;\n#else\n\treturn IsWow64() == true;\n#endif\n}<|endoftext|>"} {"text":"<commit_before>\/\/--------------------------------------------------------------\n\/\/-- Oscillator.pde\n\/\/-- Generate sinusoidal oscillations in the servos\n\/\/--------------------------------------------------------------\n\/\/-- (c) Juan Gonzalez-Gomez (Obijuan), Dec 2011\n\/\/-- GPL license\n\/\/--------------------------------------------------------------\n#if defined(ARDUINO) && ARDUINO >= 100\n #include \"Arduino.h\"\n#else\n #include \"WProgram.h\"\n #include <pins_arduino.h>\n#endif\n#include \"Oscillator.h\"\n#include <Servo.h>\n\n\/\/-- This function returns true if another sample\n\/\/-- should be taken (i.e. the TS time has passed since\n\/\/-- the last sample was taken\nbool Oscillator::next_sample()\n{\n \n \/\/-- Read current time\n _currentMillis = millis();\n \n \/\/-- Check if the timeout has passed\n if(_currentMillis - _previousMillis > _TS) {\n _previousMillis = _currentMillis; \n\n return true;\n }\n \n return false;\n}\n\n\/\/-- Attach an oscillator to a servo\n\/\/-- Input: pin is the arduino pin were the servo\n\/\/-- is connected\nvoid Oscillator::attach(int pin, bool rev)\n{\n \/\/-- If the oscillator is detached, attach it.\n if(!_servo.attached()){\n\n \/\/-- Attach the servo and move it to the home position\n _servo.attach(pin);\n _servo.write(90);\n\n \/\/-- Initialization of oscilaltor parameters\n _TS=30;\n _T=2000;\n _N = _T\/_TS;\n _inc = 2*M_PI\/_N;\n\n _previousMillis=0;\n\n \/\/-- Default parameters\n _A=45;\n _phase=0;\n _phase0=0;\n _O=0;\n _stop=false;\n\n \/\/-- Reverse mode\n _rev = rev;\n }\n \n}\n\n\/\/-- Detach an oscillator from his servo\nvoid Oscillator::detach()\n{\n \/\/-- If the oscillator is attached, detach it.\n if(_servo.attached())\n _servo.detach();\n\n}\n\n\/*************************************\/\n\/* Set the oscillator period, in ms *\/\n\/*************************************\/\nvoid Oscillator::SetT(unsigned int T)\n{\n \/\/-- Assign the new period\n _T=T;\n \n \/\/-- Recalculate the parameters\n _N = _T\/_TS;\n _inc = 2*M_PI\/_N;\n};\n\n\/*******************************\/\n\/* Manual set of the position *\/\n\/******************************\/\n\nvoid Oscillator::SetPosition(int position)\n{\n _servo.write(position+_trim);\n};\n\n\n\/*******************************************************************\/\n\/* This function should be periodically called *\/\n\/* in order to maintain the oscillations. It calculates *\/\n\/* if another sample should be taken and position the servo if so *\/\n\/*******************************************************************\/\nvoid Oscillator::refresh()\n{\n \n \/\/-- Only When TS milliseconds have passed, the new sample is obtained\n if (next_sample()) {\n \n \/\/-- If the oscillator is not stopped, calculate the servo position\n if (!_stop) {\n \/\/-- Sample the sine function and set the servo pos\n _pos = round(_A * sin(_phase + _phase0) + _O);\n\t if (_rev) _pos=-_pos;\n _servo.write(_pos+90+_trim);\n }\n\n \/\/-- Increment the phase\n \/\/-- It is always increased, even when the oscillator is stop\n \/\/-- so that the coordination is always kept\n _phase = _phase + _inc;\n\n }\n}\n<commit_msg>Delete Oscillator.cpp<commit_after><|endoftext|>"} {"text":"<commit_before>#include \"oglWidget.h\"\n#include <iostream>\n\/\/\n\/\/ CONSTRUCTORS \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ \n\n\/**\n * @brief Default constructor for OGLWidget.\n *\/\nOGLWidget::OGLWidget()\n{\n \/\/ Update the widget after a frameswap\n connect( this, SIGNAL( frameSwapped() ),\n this, SLOT( update() ) );\n\n \/\/ Allows keyboard input to fall through\n setFocusPolicy( Qt::ClickFocus );\n\n camera.rotate( -90.0f, 1.0f, 0.0f, 0.0f );\n camera.translate( 30.0f, 75.0f, 30.0f );\n\n renderables[\"Labyrinth\"] = new Labyrinth( Environment::Ice, 10, 30, 30 );\n renderables[\"Ball\"] = new Ball();\n}\n\n\/**\n * @brief Destructor class to unallocate OpenGL information.\n *\/\nOGLWidget::~OGLWidget()\n{\n makeCurrent();\n teardownGL();\n teardownBullet();\n}\n\n\/\/\n\/\/ OPENGL FUNCTIONS \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ \n\n\/**\n * @brief Initializes any OpenGL operations.\n *\/\nvoid OGLWidget::initializeGL()\n{\n \/\/ Init OpenGL Backend\n initializeOpenGLFunctions();\n printContextInfo();\n initializeBullet();\n\n for( QMap<QString, Renderable*>::iterator iter = renderables.begin(); \n iter != renderables.end(); iter++ )\n {\n (*iter)->initializeGL();\n }\n\n ((Labyrinth*)renderables[\"Labyrinth\"])->addRigidBodys( m_dynamicsWorld );\n m_dynamicsWorld->addRigidBody(\n ((Ball*)renderables[\"Ball\"])->RigidBody\n );\n}\n\n\/**\n * @brief Sets the prespective whenever the window is resized.\n *\n * @param[in] width The width of the new window.\n * @param[in] height The height of the new window.\n *\/\nvoid OGLWidget::resizeGL( int width, int height )\n{\n projection.setToIdentity();\n projection.perspective( 55.0f, \/\/ Field of view angle\n float( width ) \/ float( height ), \/\/ Aspect Ratio\n 0.001f, \/\/ Near Plane (MUST BE GREATER THAN 0)\n 1500.0f ); \/\/ Far Plane\n}\n\n\/**\n * @brief OpenGL function to draw elements to the surface.\n *\/\nvoid OGLWidget::paintGL()\n{\n \/\/ Set the default OpenGL states\n glEnable( GL_DEPTH_TEST );\n glDepthFunc( GL_LEQUAL );\n glDepthMask( GL_TRUE );\n glEnable( GL_CULL_FACE );\n glClearColor( 0.0f, 0.0f, 0.2f, 1.0f );\n\n \/\/ Clear the screen\n glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );\n\n for( QMap<QString, Renderable*>::iterator iter = renderables.begin(); \n iter != renderables.end(); iter++ )\n {\n (*iter)->paintGL( camera, projection );\n }\n}\n\n\/**\n * @brief Destroys any OpenGL data.\n *\/\nvoid OGLWidget::teardownGL()\n{\n for( QMap<QString, Renderable*>::iterator iter = renderables.begin(); \n iter != renderables.end(); iter++ )\n {\n (*iter)->teardownGL();\n }\n}\n\n\/\/\n\/\/ SLOTS \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ \n\n\/**\n * @brief Updates any user interactions and model transformations.\n *\/\nvoid OGLWidget::update()\n{\n float dt = updateTimer.deltaTime();\n Input::update();\n flyThroughCamera();\n\n \/\/ not sure what to call this method\n controlBoard();\n\n for( QMap<QString, Renderable*>::iterator iter = renderables.begin(); \n iter != renderables.end(); iter++ )\n {\n (*iter)->update();\n }\n\n m_dynamicsWorld->stepSimulation( dt, 10 );\n QOpenGLWidget::update();\n}\n\n\/\/\n\/\/ INPUT EVENTS \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ \n\n\/**\n * @brief Default slot for handling key press events.\n *\n * @param event The key event information.\n *\/\nvoid OGLWidget::keyPressEvent( QKeyEvent* event )\n{\n if( event->isAutoRepeat() )\n event->ignore();\n else\n Input::registerKeyPress( event->key() );\n}\n\n\/**\n * @brief Default slot for handling key release events.\n *\n * @param event The key event information.\n *\/\nvoid OGLWidget::keyReleaseEvent( QKeyEvent* event )\n{\n if( event->isAutoRepeat() )\n event->ignore();\n else\n Input::registerKeyRelease( event->key() );\n}\n\n\/**\n * @brief Default slot for handling mouse press events.\n *\n * @param event The mouse event information.\n *\/\nvoid OGLWidget::mousePressEvent( QMouseEvent* event )\n{\n Input::registerMousePress( event->button() );\n}\n\n\/**\n * @brief Default slot for handling mouse release events.\n *\n * @param event The mouse event information.\n *\/\nvoid OGLWidget::mouseReleaseEvent( QMouseEvent* event )\n{\n Input::registerMouseRelease( event->button() );\n}\n\n\/\/\n\/\/ PRIVATE HELPER FUNCTIONS \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\n\/**\n * @brief Helper function to initialize bullet data.\n *\/\nvoid OGLWidget::initializeBullet()\n{\n m_broadphase = new btDbvtBroadphase();\n m_collisionConfig = new btDefaultCollisionConfiguration();\n m_dispatcher = new btCollisionDispatcher( m_collisionConfig );\n m_solver = new btSequentialImpulseConstraintSolver();\n m_dynamicsWorld = new btDiscreteDynamicsWorld( m_dispatcher, m_broadphase,\n m_solver, m_collisionConfig );\n m_dynamicsWorld->setGravity( btVector3( 0, -9.8, 0 ) );\n}\n\n\/**\n * @brief Helper function to delete bullet allocations.\n *\/\nvoid OGLWidget::teardownBullet()\n{\n delete m_dynamicsWorld;\n delete m_solver;\n delete m_dispatcher;\n delete m_collisionConfig;\n delete m_broadphase;\n}\n\n\n\/**\n * @brief Updates the main camera to behave like a Fly-Through Camera.\n *\/\nvoid OGLWidget::flyThroughCamera()\n{\n static const float cameraTranslationSpeed = 0.02f;\n static const float cameraRotationSpeed = 0.1f;\n\n if( Input::buttonPressed( Qt::RightButton ) )\n {\n \/\/ Rotate the camera based on mouse movement\n camera.rotate( -cameraRotationSpeed * Input::mouseDelta().x(), \n Camera3D::LocalUp );\n camera.rotate( -cameraRotationSpeed * Input::mouseDelta().y(),\n camera.right() );\n }\n\n \/\/ Translate the camera based on keyboard input\n QVector3D cameraTranslations;\n if( Input::keyPressed( Qt::Key_W ) )\n cameraTranslations += camera.forward();\n if( Input::keyPressed( Qt::Key_S ) )\n cameraTranslations -= camera.forward();\n if( Input::keyPressed( Qt::Key_A ) )\n cameraTranslations -= camera.right();\n if( Input::keyPressed( Qt::Key_D ) )\n cameraTranslations += camera.right();\n if( Input::keyPressed( Qt::Key_Q ) )\n cameraTranslations -= camera.up();\n if( Input::keyPressed( Qt::Key_E ) )\n cameraTranslations += camera.up();\n camera.translate( cameraTranslationSpeed * cameraTranslations );\n} \n\n\/**\n * @brief Updates board based on user input.\n *\/\nvoid OGLWidget::controlBoard()\n{\n const float rotationSpeed = 0.5f;\n const float rollingSpeed = 1.0f;\n btVector3 gravity = m_dynamicsWorld->getGravity();\n\n \/* I suppose gravity being relative to camera would be best, here is some code incase you want\n to figure out a good way to do it.\n\n float cameraAngle;\n QVector3D cameraAxis;\n camera.rotation().getAxisAndAngle( &cameraAxis, &cameraAngle );\n \/\/std::cout << cameraAngle << std::endl;\n \/\/std::cout << cameraAxis.x() << std::endl;\n *\/\n\n if( Input::keyPressed( Qt::Key_Z ) )\n {\n \/\/ Update horizontal rotation\n if( Input::keyPressed( Qt::Key_Left ) )\n {\n camera.rotate( -rotationSpeed, QVector3D(0, 0, 1) );\n gravity -= btVector3( rollingSpeed, 0, 0 );\n }\n\n else if( Input::keyPressed( Qt::Key_Right ) )\n {\n camera.rotate( rotationSpeed, QVector3D(0, 0, 1) ); \n gravity += btVector3( rollingSpeed, 0, 0 );\n }\n\n\n \/\/ Update vertical rotation\n if( Input::keyPressed( Qt::Key_Up ) )\n {\n camera.rotate( rotationSpeed, QVector3D(1, 0, 0) ); \n gravity -= btVector3( 0, 0, rollingSpeed );\n }\n\n else if( Input::keyPressed( Qt::Key_Down ) )\n {\n camera.rotate( -rotationSpeed, QVector3D(1, 0, 0) ); \n gravity += btVector3( 0, 0, rollingSpeed );\n }\n }\n\n else\n {\n \/\/ Update horizontal rotation\n if( Input::keyPressed( Qt::Key_Left ) )\n {\n camera.rotate( rotationSpeed, QVector3D(0, 0, 1) );\n gravity -= btVector3( rollingSpeed, 0, 0 );\n }\n\n else if( Input::keyPressed( Qt::Key_Right ) )\n {\n camera.rotate( -rotationSpeed, QVector3D(0, 0, 1) ); \n gravity += btVector3( rollingSpeed, 0, 0 );\n }\n\n\n \/\/ Update vertical rotation\n if( Input::keyPressed( Qt::Key_Up ) )\n {\n camera.rotate( -rotationSpeed, QVector3D(1, 0, 0) ); \n gravity -= btVector3( 0, 0, rollingSpeed );\n }\n\n else if( Input::keyPressed( Qt::Key_Down ) )\n {\n camera.rotate( rotationSpeed, QVector3D(1, 0, 0) ); \n gravity += btVector3( 0, 0, rollingSpeed );\n }\n }\n\n \/\/ Update gravity\n m_dynamicsWorld->setGravity( gravity );\n\n}\n\/**\n * @brief Helper function to print OpenGL Context information to the debug.\n *\/\nvoid OGLWidget::printContextInfo()\n{\n QString glType;\n QString glVersion;\n QString glProfile;\n\n \/\/ Get Version Information\n glType = ( context()->isOpenGLES() ) ? \"OpenGL ES\" : \"OpenGL\";\n glVersion = reinterpret_cast<const char*>( glGetString( GL_VERSION ) );\n\n \/\/ Get Profile Information\n switch( format().profile() )\n {\n case QSurfaceFormat::NoProfile:\n glProfile = \"No Profile\";\n break;\n case QSurfaceFormat::CoreProfile:\n glProfile = \"Core Profile\";\n break;\n case QSurfaceFormat::CompatibilityProfile:\n glProfile = \"Compatibility Profile\";\n break;\n }\n\n qDebug() << qPrintable( glType ) << qPrintable( glVersion ) << \n \"(\" << qPrintable( glProfile ) << \")\";\n}<commit_msg>Camera now moves with rotation, removed inverted option<commit_after>#include \"oglWidget.h\"\n#include <iostream>\n\/\/\n\/\/ CONSTRUCTORS \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ \n\n\/**\n * @brief Default constructor for OGLWidget.\n *\/\nOGLWidget::OGLWidget()\n{\n \/\/ Update the widget after a frameswap\n connect( this, SIGNAL( frameSwapped() ),\n this, SLOT( update() ) );\n\n \/\/ Allows keyboard input to fall through\n setFocusPolicy( Qt::ClickFocus );\n\n camera.rotate( -90.0f, 1.0f, 0.0f, 0.0f );\n camera.translate( 30.0f, 75.0f, 30.0f );\n\n renderables[\"Labyrinth\"] = new Labyrinth( Environment::Ice, 10, 30, 30 );\n renderables[\"Ball\"] = new Ball();\n}\n\n\/**\n * @brief Destructor class to unallocate OpenGL information.\n *\/\nOGLWidget::~OGLWidget()\n{\n makeCurrent();\n teardownGL();\n teardownBullet();\n}\n\n\/\/\n\/\/ OPENGL FUNCTIONS \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ \n\n\/**\n * @brief Initializes any OpenGL operations.\n *\/\nvoid OGLWidget::initializeGL()\n{\n \/\/ Init OpenGL Backend\n initializeOpenGLFunctions();\n printContextInfo();\n initializeBullet();\n\n for( QMap<QString, Renderable*>::iterator iter = renderables.begin(); \n iter != renderables.end(); iter++ )\n {\n (*iter)->initializeGL();\n }\n\n ((Labyrinth*)renderables[\"Labyrinth\"])->addRigidBodys( m_dynamicsWorld );\n m_dynamicsWorld->addRigidBody(\n ((Ball*)renderables[\"Ball\"])->RigidBody\n );\n}\n\n\/**\n * @brief Sets the prespective whenever the window is resized.\n *\n * @param[in] width The width of the new window.\n * @param[in] height The height of the new window.\n *\/\nvoid OGLWidget::resizeGL( int width, int height )\n{\n projection.setToIdentity();\n projection.perspective( 55.0f, \/\/ Field of view angle\n float( width ) \/ float( height ), \/\/ Aspect Ratio\n 0.001f, \/\/ Near Plane (MUST BE GREATER THAN 0)\n 1500.0f ); \/\/ Far Plane\n}\n\n\/**\n * @brief OpenGL function to draw elements to the surface.\n *\/\nvoid OGLWidget::paintGL()\n{\n \/\/ Set the default OpenGL states\n glEnable( GL_DEPTH_TEST );\n glDepthFunc( GL_LEQUAL );\n glDepthMask( GL_TRUE );\n glEnable( GL_CULL_FACE );\n glClearColor( 0.0f, 0.0f, 0.2f, 1.0f );\n\n \/\/ Clear the screen\n glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );\n\n for( QMap<QString, Renderable*>::iterator iter = renderables.begin(); \n iter != renderables.end(); iter++ )\n {\n (*iter)->paintGL( camera, projection );\n }\n}\n\n\/**\n * @brief Destroys any OpenGL data.\n *\/\nvoid OGLWidget::teardownGL()\n{\n for( QMap<QString, Renderable*>::iterator iter = renderables.begin(); \n iter != renderables.end(); iter++ )\n {\n (*iter)->teardownGL();\n }\n}\n\n\/\/\n\/\/ SLOTS \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ \n\n\/**\n * @brief Updates any user interactions and model transformations.\n *\/\nvoid OGLWidget::update()\n{\n float dt = updateTimer.deltaTime();\n Input::update();\n flyThroughCamera();\n\n \/\/ not sure what to call this method\n controlBoard();\n\n for( QMap<QString, Renderable*>::iterator iter = renderables.begin(); \n iter != renderables.end(); iter++ )\n {\n (*iter)->update();\n }\n\n m_dynamicsWorld->stepSimulation( dt, 10 );\n QOpenGLWidget::update();\n}\n\n\/\/\n\/\/ INPUT EVENTS \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ \n\n\/**\n * @brief Default slot for handling key press events.\n *\n * @param event The key event information.\n *\/\nvoid OGLWidget::keyPressEvent( QKeyEvent* event )\n{\n if( event->isAutoRepeat() )\n event->ignore();\n else\n Input::registerKeyPress( event->key() );\n}\n\n\/**\n * @brief Default slot for handling key release events.\n *\n * @param event The key event information.\n *\/\nvoid OGLWidget::keyReleaseEvent( QKeyEvent* event )\n{\n if( event->isAutoRepeat() )\n event->ignore();\n else\n Input::registerKeyRelease( event->key() );\n}\n\n\/**\n * @brief Default slot for handling mouse press events.\n *\n * @param event The mouse event information.\n *\/\nvoid OGLWidget::mousePressEvent( QMouseEvent* event )\n{\n Input::registerMousePress( event->button() );\n}\n\n\/**\n * @brief Default slot for handling mouse release events.\n *\n * @param event The mouse event information.\n *\/\nvoid OGLWidget::mouseReleaseEvent( QMouseEvent* event )\n{\n Input::registerMouseRelease( event->button() );\n}\n\n\/\/\n\/\/ PRIVATE HELPER FUNCTIONS \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\n\/**\n * @brief Helper function to initialize bullet data.\n *\/\nvoid OGLWidget::initializeBullet()\n{\n m_broadphase = new btDbvtBroadphase();\n m_collisionConfig = new btDefaultCollisionConfiguration();\n m_dispatcher = new btCollisionDispatcher( m_collisionConfig );\n m_solver = new btSequentialImpulseConstraintSolver();\n m_dynamicsWorld = new btDiscreteDynamicsWorld( m_dispatcher, m_broadphase,\n m_solver, m_collisionConfig );\n m_dynamicsWorld->setGravity( btVector3( 0, -9.8, 0 ) );\n}\n\n\/**\n * @brief Helper function to delete bullet allocations.\n *\/\nvoid OGLWidget::teardownBullet()\n{\n delete m_dynamicsWorld;\n delete m_solver;\n delete m_dispatcher;\n delete m_collisionConfig;\n delete m_broadphase;\n}\n\n\n\/**\n * @brief Updates the main camera to behave like a Fly-Through Camera.\n *\/\nvoid OGLWidget::flyThroughCamera()\n{\n static const float cameraTranslationSpeed = 0.02f;\n static const float cameraRotationSpeed = 0.1f;\n\n if( Input::buttonPressed( Qt::RightButton ) )\n {\n \/\/ Rotate the camera based on mouse movement\n camera.rotate( -cameraRotationSpeed * Input::mouseDelta().x(), \n Camera3D::LocalUp );\n camera.rotate( -cameraRotationSpeed * Input::mouseDelta().y(),\n camera.right() );\n }\n\n \/\/ Translate the camera based on keyboard input\n QVector3D cameraTranslations;\n if( Input::keyPressed( Qt::Key_W ) )\n cameraTranslations += camera.forward();\n if( Input::keyPressed( Qt::Key_S ) )\n cameraTranslations -= camera.forward();\n if( Input::keyPressed( Qt::Key_A ) )\n cameraTranslations -= camera.right();\n if( Input::keyPressed( Qt::Key_D ) )\n cameraTranslations += camera.right();\n if( Input::keyPressed( Qt::Key_Q ) )\n cameraTranslations -= camera.up();\n if( Input::keyPressed( Qt::Key_E ) )\n cameraTranslations += camera.up();\n camera.translate( cameraTranslationSpeed * cameraTranslations );\n} \n\n\/**\n * @brief Updates board based on user input.\n *\/\nvoid OGLWidget::controlBoard()\n{\n const float rotationSpeed = 0.5f;\n const float rollingSpeed = 1.0f;\n btVector3 gravity = m_dynamicsWorld->getGravity();\n\n \/* I suppose gravity being relative to camera would be best, here is some code incase you want\n to figure out a good way to do it.\n\n float cameraAngle;\n QVector3D cameraAxis;\n camera.rotation().getAxisAndAngle( &cameraAxis, &cameraAngle );\n \/\/std::cout << cameraAngle << std::endl;\n \/\/std::cout << cameraAxis.x() << std::endl;\n *\/\n\n\n \/\/ Update horizontal rotation\n if( Input::keyPressed( Qt::Key_Left ) )\n {\n camera.rotate( -rotationSpeed, QVector3D(0, 0, 1) ); \n camera.translate( 0.5f, 0, 0);\n gravity -= btVector3( rollingSpeed, 0, 0 );\n }\n\n else if( Input::keyPressed( Qt::Key_Right ) )\n {\n camera.rotate( rotationSpeed, QVector3D(0, 0, 1) ); \n camera.translate( -0.5f, 0, 0); \n gravity += btVector3( rollingSpeed, 0, 0 );\n }\n\n\n \/\/ Update vertical rotation\n if( Input::keyPressed( Qt::Key_Up ) )\n {\n camera.rotate( rotationSpeed, QVector3D(1, 0, 0) );\n camera.translate( 0, 0, 0.75f ); \n gravity -= btVector3( 0, 0, rollingSpeed );\n }\n\n else if( Input::keyPressed( Qt::Key_Down ) )\n {\n camera.rotate( -rotationSpeed, QVector3D(1, 0, 0) );\n camera.translate( 0, 0, -0.75f ); \n gravity += btVector3( 0, 0, rollingSpeed );\n }\n\n \/\/ Update gravity\n m_dynamicsWorld->setGravity( gravity );\n\n}\n\/**\n * @brief Helper function to print OpenGL Context information to the debug.\n *\/\nvoid OGLWidget::printContextInfo()\n{\n QString glType;\n QString glVersion;\n QString glProfile;\n\n \/\/ Get Version Information\n glType = ( context()->isOpenGLES() ) ? \"OpenGL ES\" : \"OpenGL\";\n glVersion = reinterpret_cast<const char*>( glGetString( GL_VERSION ) );\n\n \/\/ Get Profile Information\n switch( format().profile() )\n {\n case QSurfaceFormat::NoProfile:\n glProfile = \"No Profile\";\n break;\n case QSurfaceFormat::CoreProfile:\n glProfile = \"Core Profile\";\n break;\n case QSurfaceFormat::CompatibilityProfile:\n glProfile = \"Compatibility Profile\";\n break;\n }\n\n qDebug() << qPrintable( glType ) << qPrintable( glVersion ) << \n \"(\" << qPrintable( glProfile ) << \")\";\n}<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ EigenJS.cpp\n\/\/ ~~~~~~~~~~~\n\/\/\n\/\/ Copyright (c) 2014 Rick Yang (rick68 at gmail dot com)\n\/\/\n\/\/ This Source Code Form is subject to the terms of the Mozilla\n\/\/ Public License v. 2.0. If a copy of the MPL was not distributed\n\/\/ with this file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n\/\/\n\n#ifndef EIGENJS_COMPLEX_HPP\n#define EIGENJS_COMPLEX_HPP\n\n#include <node.h>\n#include <v8.h>\n\n#include <nan.h>\n\n#include <complex>\n#include <sstream>\n\n#define EIGENJS_COMPLEX_CLASS_METHOD( NAME ) \\\n static NAN_METHOD( NAME ) { \\\n NanScope(); \\\n \\\n if ( args.Length() == 1 && HasInstance(args[0]) ) { \\\n const Complex* obj = \\\n node::ObjectWrap::Unwrap<Complex>( args[0]->ToObject() ); \\\n \\\n const complex_type& NAME = std::NAME( obj->complex_ ); \\\n const element_type& real = NAME.real(); \\\n const element_type& imag = NAME.imag(); \\\n \\\n v8::Local<v8::Function> ctor = NanNew( constructor ); \\\n v8::Local<v8::Value> argv[] = { \\\n NanNew<v8::Number>( real ) \\\n , NanNew<v8::Number>( imag ) \\\n }; \\\n \\\n v8::Local<v8::Object> new_complex = ctor->NewInstance( \\\n sizeof( argv ) \/ sizeof( v8::Local<v8::Value> ) \\\n , argv \\\n ); \\\n \\\n NanReturnValue( new_complex ); \\\n } \\\n \\\n NanReturnUndefined(); \\\n } \\\n\/**\/\n\nnamespace EigenJS {\n\ntemplate <typename ValueType>\nclass Complex : public node::ObjectWrap {\n typedef ValueType element_type;\n typedef std::complex<element_type> complex_type;\n\n public:\n static void Init(v8::Handle<v8::Object> exports) {\n NanScope();\n\n v8::Local<v8::FunctionTemplate> tpl = NanNew<v8::FunctionTemplate>(New);\n tpl->SetClassName(NanNew(\"Complex\"));\n tpl->InstanceTemplate()->SetInternalFieldCount(1);\n\n NODE_SET_PROTOTYPE_METHOD(tpl, \"abs\", abs);\n NODE_SET_PROTOTYPE_METHOD(tpl, \"arg\", arg);\n NODE_SET_PROTOTYPE_METHOD(tpl, \"norm\", norm);\n NODE_SET_PROTOTYPE_METHOD(tpl, \"conj\", conj);\n\n NODE_SET_METHOD(tpl, \"polar\", polar);\n NODE_SET_METHOD(tpl, \"proj\", proj);\n\n NODE_SET_METHOD(tpl, \"cos\", cos);\n NODE_SET_METHOD(tpl, \"cosh\", cosh);\n NODE_SET_METHOD(tpl, \"exp\", exp);\n NODE_SET_METHOD(tpl, \"log\", log);\n NODE_SET_METHOD(tpl, \"log10\", log10);\n NODE_SET_METHOD(tpl, \"pow\", pow);\n NODE_SET_METHOD(tpl, \"sin\", sin);\n NODE_SET_METHOD(tpl, \"sinh\", sinh);\n NODE_SET_METHOD(tpl, \"sqrt\", sqrt);\n NODE_SET_METHOD(tpl, \"tan\", tan);\n NODE_SET_METHOD(tpl, \"tanh\", tanh);\n NODE_SET_METHOD(tpl, \"acos\", acos);\n NODE_SET_METHOD(tpl, \"acosh\", acosh);\n\n NODE_SET_PROTOTYPE_METHOD(tpl, \"toString\", toString);\n\n v8::Local<v8::ObjectTemplate> proto = tpl->PrototypeTemplate();\n proto->SetAccessor(NanNew(\"real\"), get_real, set_real);\n proto->SetAccessor(NanNew(\"imag\"), get_imag, set_imag);\n\n NanAssignPersistent(constructor, tpl->GetFunction());\n exports->Set(NanNew(\"Complex\"), tpl->GetFunction());\n\n NanAssignPersistent(function_template, tpl);\n }\n\n static NAN_METHOD(abs) {\n const Complex* obj = node::ObjectWrap::Unwrap<Complex>(args.This());\n NanScope();\n\n NanReturnValue(NanNew(std::abs(obj->complex_)));\n }\n\n static NAN_METHOD(arg) {\n const Complex* obj = node::ObjectWrap::Unwrap<Complex>(args.This());\n NanScope();\n\n NanReturnValue(NanNew(std::arg(obj->complex_)));\n }\n\n static NAN_METHOD(norm) {\n const Complex* obj = node::ObjectWrap::Unwrap<Complex>(args.This());\n NanScope();\n\n NanReturnValue(NanNew(std::norm(obj->complex_)));\n }\n\n static NAN_METHOD(conj) {\n const Complex* obj = node::ObjectWrap::Unwrap<Complex>(args.This());\n const complex_type& c = std::conj(obj->complex_);\n const element_type& real = c.real();\n const element_type& imag = c.imag();\n NanScope();\n\n v8::Local<v8::Function> ctor = NanNew(constructor);\n v8::Local<v8::Value> argv[] = {\n NanNew<v8::Number>(real)\n , NanNew<v8::Number>(imag)\n };\n\n v8::Local<v8::Object> new_complex = ctor->NewInstance(\n sizeof(argv) \/ sizeof(v8::Local<v8::Value>)\n , argv\n );\n\n NanReturnValue(new_complex);\n }\n\n static NAN_METHOD(polar) {\n NanScope();\n\n if (args.Length() == 2 &&\n args[0]->IsNumber() &&\n args[1]->IsNumber()) {\n const element_type& rho = args[0]->NumberValue();\n const element_type& theta = args[1]->NumberValue();\n\n v8::Local<v8::Function> ctor = NanNew(constructor);\n v8::Local<v8::Value> argv[] = {\n NanNew<v8::Number>(rho)\n , NanNew<v8::Number>(theta)\n };\n\n v8::Local<v8::Object> new_complex = ctor->NewInstance(\n sizeof(argv) \/ sizeof(v8::Local<v8::Value>)\n , argv\n );\n\n NanReturnValue(new_complex);\n }\n\n NanReturnUndefined();\n }\n\n EIGENJS_COMPLEX_CLASS_METHOD(proj)\n EIGENJS_COMPLEX_CLASS_METHOD(cos)\n EIGENJS_COMPLEX_CLASS_METHOD(cosh)\n EIGENJS_COMPLEX_CLASS_METHOD(exp)\n EIGENJS_COMPLEX_CLASS_METHOD(log)\n EIGENJS_COMPLEX_CLASS_METHOD(log10)\n EIGENJS_COMPLEX_CLASS_METHOD(sin)\n EIGENJS_COMPLEX_CLASS_METHOD(sinh)\n EIGENJS_COMPLEX_CLASS_METHOD(sqrt)\n EIGENJS_COMPLEX_CLASS_METHOD(tan)\n EIGENJS_COMPLEX_CLASS_METHOD(tanh)\n EIGENJS_COMPLEX_CLASS_METHOD(acos)\n EIGENJS_COMPLEX_CLASS_METHOD(acosh)\n\n static NAN_METHOD(pow) {\n NanScope();\n\n if (args.Length() == 2 &&\n is_complex_or_saclar(args[0]) &&\n is_complex_or_saclar(args[1])) {\n const bool& arg0_is_complex = is_complex(args[0]);\n const bool& arg1_is_complex = is_complex(args[1]);\n const bool& arg0_is_scalar = is_saclar(args[0]);\n const bool& arg1_is_scalar = is_saclar(args[1]);\n complex_type c;\n\n if (arg0_is_complex && arg1_is_complex) {\n const Complex* obj0 =\n node::ObjectWrap::Unwrap<Complex>(args[0]->ToObject());\n const Complex* obj1 =\n node::ObjectWrap::Unwrap<Complex>(args[1]->ToObject());\n c = std::pow(obj0->complex_, obj1->complex_);\n } else if (arg0_is_complex && arg1_is_scalar) {\n const Complex* obj0 =\n node::ObjectWrap::Unwrap<Complex>(args[0]->ToObject());\n const element_type& scalar1 = args[1]->NumberValue();\n c = std::pow(obj0->complex_, scalar1);\n } else if (arg0_is_scalar && arg1_is_complex) {\n const element_type& scalar0 = args[0]->NumberValue();\n const Complex* obj1 =\n node::ObjectWrap::Unwrap<Complex>(args[1]->ToObject());\n c = std::pow(scalar0, obj1->complex_);\n } else if (arg0_is_scalar && arg1_is_scalar) {\n const element_type& scalar0 = args[0]->NumberValue();\n const element_type& scalar1 = args[1]->NumberValue();\n c = std::pow(scalar0, scalar1);\n }\n\n v8::Local<v8::Function> ctor = NanNew(constructor);\n v8::Local<v8::Value> argv[] = {\n NanNew<v8::Number>(c.real())\n , NanNew<v8::Number>(c.imag())\n };\n\n v8::Local<v8::Object> new_complex = ctor->NewInstance(\n sizeof(argv) \/ sizeof(v8::Local<v8::Value>)\n , argv\n );\n\n NanReturnValue(new_complex);\n }\n\n NanReturnUndefined();\n }\n\n static NAN_METHOD(toString) {\n const Complex* obj = node::ObjectWrap::Unwrap<Complex>(args.This());\n NanScope();\n\n std::ostringstream result;\n result << obj->complex_;\n\n NanReturnValue(NanNew(result.str().c_str()));\n\n NanReturnUndefined();\n }\n\n static NAN_GETTER(get_real) {\n NanScope();\n\n if (!NanGetInternalFieldPointer(args.This(), 0))\n NanReturnValue(args.This());\n\n const Complex* obj = node::ObjectWrap::Unwrap<Complex>(args.This());\n\n NanReturnValue(NanNew(obj->complex_.real()));\n }\n\n static NAN_SETTER(set_real) {\n if (value->IsNumber()) {\n Complex* obj = node::ObjectWrap::Unwrap<Complex>(args.This());\n obj->complex_ = complex_type(\n value->NumberValue()\n , obj->complex_.imag()\n );\n }\n }\n\n static NAN_GETTER(get_imag) {\n NanScope();\n\n if (!NanGetInternalFieldPointer(args.This(), 0))\n NanReturnValue(args.This());\n\n const Complex* obj = node::ObjectWrap::Unwrap<Complex>(args.This());\n\n NanReturnValue(NanNew(obj->complex_.imag()));\n }\n\n static NAN_SETTER(set_imag) {\n if (value->IsNumber()) {\n Complex* obj = node::ObjectWrap::Unwrap<Complex>(args.This());\n obj->complex_ = complex_type(\n obj->complex_.real()\n , value->NumberValue()\n );\n }\n }\n\n private:\n Complex(const element_type& real, const element_type& imag)\n : complex_(real, imag)\n {}\n ~Complex() {}\n\n static NAN_METHOD(New) {\n NanScope();\n\n if (args.Length() < 2) {\n NanThrowError(\"Tried creating complex without real and imag arguments\");\n NanReturnUndefined();\n }\n\n if (args.IsConstructCall()) {\n const element_type& real = args[0]->NumberValue();\n const element_type& imag = args[1]->NumberValue();\n Complex* obj = new Complex(real, imag);\n obj->Wrap(args.This());\n NanReturnValue(args.This());\n } else {\n v8::Local<v8::Function> ctr = NanNew(constructor);\n v8::Local<v8::Value> argv[] = {args[0], args[1]};\n NanReturnValue(\n ctr->NewInstance(\n sizeof(argv) \/ sizeof(v8::Local<v8::Value>)\n , argv\n )\n );\n }\n }\n\n static bool HasInstance(const v8::Handle<v8::Value>& value) {\n NanScope();\n v8::Local<v8::FunctionTemplate> tpl = NanNew(function_template);\n return tpl->HasInstance(value);\n }\n\n private:\n static v8::Persistent<v8::FunctionTemplate> function_template;\n static v8::Persistent<v8::Function> constructor;\n\n private:\n static bool is_complex(const v8::Handle<v8::Value>& arg) {\n return HasInstance(arg) ? true : false;\n }\n\n static bool is_saclar(const v8::Handle<v8::Value>& arg) {\n return arg->IsNumber() ? true : false;\n }\n\n static bool is_complex_or_saclar(const v8::Handle<v8::Value>& arg) {\n return HasInstance(arg) || arg->IsNumber()\n ? true : false;\n }\n\n private:\n complex_type complex_;\n};\n\ntemplate<typename ValueType>\nv8::Persistent<v8::FunctionTemplate> Complex<ValueType>::function_template;\n\ntemplate<typename ValueType>\nv8::Persistent<v8::Function> Complex<ValueType>::constructor;\n\n} \/\/ namespace EigenJS\n\n#undef EIGENJS_COMPLEX_CLASS_METHOD\n\n#endif \/\/ EIGENJS_COMPLEX_HPP\n<commit_msg>src: added class method 'Complex.asin()'<commit_after>\/\/\n\/\/ EigenJS.cpp\n\/\/ ~~~~~~~~~~~\n\/\/\n\/\/ Copyright (c) 2014 Rick Yang (rick68 at gmail dot com)\n\/\/\n\/\/ This Source Code Form is subject to the terms of the Mozilla\n\/\/ Public License v. 2.0. If a copy of the MPL was not distributed\n\/\/ with this file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n\/\/\n\n#ifndef EIGENJS_COMPLEX_HPP\n#define EIGENJS_COMPLEX_HPP\n\n#include <node.h>\n#include <v8.h>\n\n#include <nan.h>\n\n#include <complex>\n#include <sstream>\n\n#define EIGENJS_COMPLEX_CLASS_METHOD( NAME ) \\\n static NAN_METHOD( NAME ) { \\\n NanScope(); \\\n \\\n if ( args.Length() == 1 && HasInstance(args[0]) ) { \\\n const Complex* obj = \\\n node::ObjectWrap::Unwrap<Complex>( args[0]->ToObject() ); \\\n \\\n const complex_type& NAME = std::NAME( obj->complex_ ); \\\n const element_type& real = NAME.real(); \\\n const element_type& imag = NAME.imag(); \\\n \\\n v8::Local<v8::Function> ctor = NanNew( constructor ); \\\n v8::Local<v8::Value> argv[] = { \\\n NanNew<v8::Number>( real ) \\\n , NanNew<v8::Number>( imag ) \\\n }; \\\n \\\n v8::Local<v8::Object> new_complex = ctor->NewInstance( \\\n sizeof( argv ) \/ sizeof( v8::Local<v8::Value> ) \\\n , argv \\\n ); \\\n \\\n NanReturnValue( new_complex ); \\\n } \\\n \\\n NanReturnUndefined(); \\\n } \\\n\/**\/\n\nnamespace EigenJS {\n\ntemplate <typename ValueType>\nclass Complex : public node::ObjectWrap {\n typedef ValueType element_type;\n typedef std::complex<element_type> complex_type;\n\n public:\n static void Init(v8::Handle<v8::Object> exports) {\n NanScope();\n\n v8::Local<v8::FunctionTemplate> tpl = NanNew<v8::FunctionTemplate>(New);\n tpl->SetClassName(NanNew(\"Complex\"));\n tpl->InstanceTemplate()->SetInternalFieldCount(1);\n\n NODE_SET_PROTOTYPE_METHOD(tpl, \"abs\", abs);\n NODE_SET_PROTOTYPE_METHOD(tpl, \"arg\", arg);\n NODE_SET_PROTOTYPE_METHOD(tpl, \"norm\", norm);\n NODE_SET_PROTOTYPE_METHOD(tpl, \"conj\", conj);\n\n NODE_SET_METHOD(tpl, \"polar\", polar);\n NODE_SET_METHOD(tpl, \"proj\", proj);\n\n NODE_SET_METHOD(tpl, \"cos\", cos);\n NODE_SET_METHOD(tpl, \"cosh\", cosh);\n NODE_SET_METHOD(tpl, \"exp\", exp);\n NODE_SET_METHOD(tpl, \"log\", log);\n NODE_SET_METHOD(tpl, \"log10\", log10);\n NODE_SET_METHOD(tpl, \"pow\", pow);\n NODE_SET_METHOD(tpl, \"sin\", sin);\n NODE_SET_METHOD(tpl, \"sinh\", sinh);\n NODE_SET_METHOD(tpl, \"sqrt\", sqrt);\n NODE_SET_METHOD(tpl, \"tan\", tan);\n NODE_SET_METHOD(tpl, \"tanh\", tanh);\n NODE_SET_METHOD(tpl, \"acos\", acos);\n NODE_SET_METHOD(tpl, \"acosh\", acosh);\n NODE_SET_METHOD(tpl, \"asin\", asin);\n\n NODE_SET_PROTOTYPE_METHOD(tpl, \"toString\", toString);\n\n v8::Local<v8::ObjectTemplate> proto = tpl->PrototypeTemplate();\n proto->SetAccessor(NanNew(\"real\"), get_real, set_real);\n proto->SetAccessor(NanNew(\"imag\"), get_imag, set_imag);\n\n NanAssignPersistent(constructor, tpl->GetFunction());\n exports->Set(NanNew(\"Complex\"), tpl->GetFunction());\n\n NanAssignPersistent(function_template, tpl);\n }\n\n static NAN_METHOD(abs) {\n const Complex* obj = node::ObjectWrap::Unwrap<Complex>(args.This());\n NanScope();\n\n NanReturnValue(NanNew(std::abs(obj->complex_)));\n }\n\n static NAN_METHOD(arg) {\n const Complex* obj = node::ObjectWrap::Unwrap<Complex>(args.This());\n NanScope();\n\n NanReturnValue(NanNew(std::arg(obj->complex_)));\n }\n\n static NAN_METHOD(norm) {\n const Complex* obj = node::ObjectWrap::Unwrap<Complex>(args.This());\n NanScope();\n\n NanReturnValue(NanNew(std::norm(obj->complex_)));\n }\n\n static NAN_METHOD(conj) {\n const Complex* obj = node::ObjectWrap::Unwrap<Complex>(args.This());\n const complex_type& c = std::conj(obj->complex_);\n const element_type& real = c.real();\n const element_type& imag = c.imag();\n NanScope();\n\n v8::Local<v8::Function> ctor = NanNew(constructor);\n v8::Local<v8::Value> argv[] = {\n NanNew<v8::Number>(real)\n , NanNew<v8::Number>(imag)\n };\n\n v8::Local<v8::Object> new_complex = ctor->NewInstance(\n sizeof(argv) \/ sizeof(v8::Local<v8::Value>)\n , argv\n );\n\n NanReturnValue(new_complex);\n }\n\n static NAN_METHOD(polar) {\n NanScope();\n\n if (args.Length() == 2 &&\n args[0]->IsNumber() &&\n args[1]->IsNumber()) {\n const element_type& rho = args[0]->NumberValue();\n const element_type& theta = args[1]->NumberValue();\n\n v8::Local<v8::Function> ctor = NanNew(constructor);\n v8::Local<v8::Value> argv[] = {\n NanNew<v8::Number>(rho)\n , NanNew<v8::Number>(theta)\n };\n\n v8::Local<v8::Object> new_complex = ctor->NewInstance(\n sizeof(argv) \/ sizeof(v8::Local<v8::Value>)\n , argv\n );\n\n NanReturnValue(new_complex);\n }\n\n NanReturnUndefined();\n }\n\n EIGENJS_COMPLEX_CLASS_METHOD(proj)\n EIGENJS_COMPLEX_CLASS_METHOD(cos)\n EIGENJS_COMPLEX_CLASS_METHOD(cosh)\n EIGENJS_COMPLEX_CLASS_METHOD(exp)\n EIGENJS_COMPLEX_CLASS_METHOD(log)\n EIGENJS_COMPLEX_CLASS_METHOD(log10)\n EIGENJS_COMPLEX_CLASS_METHOD(sin)\n EIGENJS_COMPLEX_CLASS_METHOD(sinh)\n EIGENJS_COMPLEX_CLASS_METHOD(sqrt)\n EIGENJS_COMPLEX_CLASS_METHOD(tan)\n EIGENJS_COMPLEX_CLASS_METHOD(tanh)\n EIGENJS_COMPLEX_CLASS_METHOD(acos)\n EIGENJS_COMPLEX_CLASS_METHOD(acosh)\n EIGENJS_COMPLEX_CLASS_METHOD(asin)\n\n static NAN_METHOD(pow) {\n NanScope();\n\n if (args.Length() == 2 &&\n is_complex_or_saclar(args[0]) &&\n is_complex_or_saclar(args[1])) {\n const bool& arg0_is_complex = is_complex(args[0]);\n const bool& arg1_is_complex = is_complex(args[1]);\n const bool& arg0_is_scalar = is_saclar(args[0]);\n const bool& arg1_is_scalar = is_saclar(args[1]);\n complex_type c;\n\n if (arg0_is_complex && arg1_is_complex) {\n const Complex* obj0 =\n node::ObjectWrap::Unwrap<Complex>(args[0]->ToObject());\n const Complex* obj1 =\n node::ObjectWrap::Unwrap<Complex>(args[1]->ToObject());\n c = std::pow(obj0->complex_, obj1->complex_);\n } else if (arg0_is_complex && arg1_is_scalar) {\n const Complex* obj0 =\n node::ObjectWrap::Unwrap<Complex>(args[0]->ToObject());\n const element_type& scalar1 = args[1]->NumberValue();\n c = std::pow(obj0->complex_, scalar1);\n } else if (arg0_is_scalar && arg1_is_complex) {\n const element_type& scalar0 = args[0]->NumberValue();\n const Complex* obj1 =\n node::ObjectWrap::Unwrap<Complex>(args[1]->ToObject());\n c = std::pow(scalar0, obj1->complex_);\n } else if (arg0_is_scalar && arg1_is_scalar) {\n const element_type& scalar0 = args[0]->NumberValue();\n const element_type& scalar1 = args[1]->NumberValue();\n c = std::pow(scalar0, scalar1);\n }\n\n v8::Local<v8::Function> ctor = NanNew(constructor);\n v8::Local<v8::Value> argv[] = {\n NanNew<v8::Number>(c.real())\n , NanNew<v8::Number>(c.imag())\n };\n\n v8::Local<v8::Object> new_complex = ctor->NewInstance(\n sizeof(argv) \/ sizeof(v8::Local<v8::Value>)\n , argv\n );\n\n NanReturnValue(new_complex);\n }\n\n NanReturnUndefined();\n }\n\n static NAN_METHOD(toString) {\n const Complex* obj = node::ObjectWrap::Unwrap<Complex>(args.This());\n NanScope();\n\n std::ostringstream result;\n result << obj->complex_;\n\n NanReturnValue(NanNew(result.str().c_str()));\n\n NanReturnUndefined();\n }\n\n static NAN_GETTER(get_real) {\n NanScope();\n\n if (!NanGetInternalFieldPointer(args.This(), 0))\n NanReturnValue(args.This());\n\n const Complex* obj = node::ObjectWrap::Unwrap<Complex>(args.This());\n\n NanReturnValue(NanNew(obj->complex_.real()));\n }\n\n static NAN_SETTER(set_real) {\n if (value->IsNumber()) {\n Complex* obj = node::ObjectWrap::Unwrap<Complex>(args.This());\n obj->complex_ = complex_type(\n value->NumberValue()\n , obj->complex_.imag()\n );\n }\n }\n\n static NAN_GETTER(get_imag) {\n NanScope();\n\n if (!NanGetInternalFieldPointer(args.This(), 0))\n NanReturnValue(args.This());\n\n const Complex* obj = node::ObjectWrap::Unwrap<Complex>(args.This());\n\n NanReturnValue(NanNew(obj->complex_.imag()));\n }\n\n static NAN_SETTER(set_imag) {\n if (value->IsNumber()) {\n Complex* obj = node::ObjectWrap::Unwrap<Complex>(args.This());\n obj->complex_ = complex_type(\n obj->complex_.real()\n , value->NumberValue()\n );\n }\n }\n\n private:\n Complex(const element_type& real, const element_type& imag)\n : complex_(real, imag)\n {}\n ~Complex() {}\n\n static NAN_METHOD(New) {\n NanScope();\n\n if (args.Length() < 2) {\n NanThrowError(\"Tried creating complex without real and imag arguments\");\n NanReturnUndefined();\n }\n\n if (args.IsConstructCall()) {\n const element_type& real = args[0]->NumberValue();\n const element_type& imag = args[1]->NumberValue();\n Complex* obj = new Complex(real, imag);\n obj->Wrap(args.This());\n NanReturnValue(args.This());\n } else {\n v8::Local<v8::Function> ctr = NanNew(constructor);\n v8::Local<v8::Value> argv[] = {args[0], args[1]};\n NanReturnValue(\n ctr->NewInstance(\n sizeof(argv) \/ sizeof(v8::Local<v8::Value>)\n , argv\n )\n );\n }\n }\n\n static bool HasInstance(const v8::Handle<v8::Value>& value) {\n NanScope();\n v8::Local<v8::FunctionTemplate> tpl = NanNew(function_template);\n return tpl->HasInstance(value);\n }\n\n private:\n static v8::Persistent<v8::FunctionTemplate> function_template;\n static v8::Persistent<v8::Function> constructor;\n\n private:\n static bool is_complex(const v8::Handle<v8::Value>& arg) {\n return HasInstance(arg) ? true : false;\n }\n\n static bool is_saclar(const v8::Handle<v8::Value>& arg) {\n return arg->IsNumber() ? true : false;\n }\n\n static bool is_complex_or_saclar(const v8::Handle<v8::Value>& arg) {\n return HasInstance(arg) || arg->IsNumber()\n ? true : false;\n }\n\n private:\n complex_type complex_;\n};\n\ntemplate<typename ValueType>\nv8::Persistent<v8::FunctionTemplate> Complex<ValueType>::function_template;\n\ntemplate<typename ValueType>\nv8::Persistent<v8::Function> Complex<ValueType>::constructor;\n\n} \/\/ namespace EigenJS\n\n#undef EIGENJS_COMPLEX_CLASS_METHOD\n\n#endif \/\/ EIGENJS_COMPLEX_HPP\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (C) 2017-2019 CS Systemes d'Information (CS SI)\n *\n * This file is part of Orfeo Toolbox\n *\n * https:\/\/www.orfeo-toolbox.org\/\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#ifndef otbMultiImageFileWriter_hxx\n#define otbMultiImageFileWriter_hxx\n\n#include \"otbMultiImageFileWriter.h\"\n#include \"otbImageIOFactory.h\"\n#include \"otbMacro.h\"\n\nnamespace otb\n{\n\ntemplate <class TImage>\nMultiImageFileWriter::Sink<TImage>::Sink(typename TImage::ConstPointer inputImage, const std::string& fileName)\n : SinkBase(dynamic_cast<const ImageBaseType*>(inputImage.GetPointer())), m_Writer(otb::ImageFileWriter<TImage>::New()), m_ImageIO(NULL)\n{\n m_Writer->SetFileName(fileName);\n m_Writer->SetInput(inputImage);\n}\n\ntemplate <class TImage>\nMultiImageFileWriter::Sink<TImage>::Sink(typename otb::ImageFileWriter<TImage>::Pointer writer)\n : SinkBase(dynamic_cast<const ImageBaseType*>(writer->GetInput())), m_Writer(writer), m_ImageIO(NULL)\n{\n}\n\ntemplate <class TImage>\nbool MultiImageFileWriter::Sink<TImage>::CanStreamWrite() const\n{\n if (m_ImageIO.IsNull())\n return false;\n return m_ImageIO->CanStreamWrite();\n}\n\ntemplate <class TImage>\nvoid MultiImageFileWriter::Sink<TImage>::WriteImageInformation()\n{\n m_Writer->UpdateOutputInformation();\n m_ImageIO = m_Writer->GetImageIO();\n}\n\ntemplate <class TImage>\nvoid MultiImageFileWriter::Sink<TImage>::Write(const RegionType& streamRegion)\n{\n \/\/ Write the image stream\n itk::ImageIORegion ioRegion(TImage::ImageDimension);\n for (unsigned int i = 0; i < TImage::ImageDimension; ++i)\n {\n ioRegion.SetSize(i, streamRegion.GetSize(i));\n ioRegion.SetIndex(i, streamRegion.GetIndex(i));\n }\n m_ImageIO->SetIORegion(ioRegion);\n m_Writer->UpdateOutputData(nullptr);\n}\n\ntemplate <class TImage>\nitk::ImageRegion<2>\nMultiImageFileWriter::Sink<TImage>::GetRegionToWrite() const\n{\n auto fnameHelper = m_Writer->GetFilenameHelper();\n if (fnameHelper->BoxIsSet())\n {\n std::vector<unsigned int> boxVector;\n Utils::ConvertStringToVector(fnameHelper->GetBox(), boxVector, \"ExtendedFileName:box\", \":\");\n\n if (boxVector.size() != 4)\n {\n itk::ImageFileWriterException e(__FILE__, __LINE__);\n std::ostringstream msg;\n msg << \"Invalid box option \" << fnameHelper->GetBox() << \". The box should contains four elements: startx:starty:sizex:sizey\";\n e.SetDescription(msg.str());\n e.SetLocation(ITK_LOCATION);\n throw e;\n }\n \n typename itk::ImageRegion<2>::IndexType start {boxVector[0], boxVector[1]};\n typename itk::ImageRegion<2>::SizeType size {boxVector[2], boxVector[3]};\n itk::ImageRegion<2> regionToWrite {start , size};\n regionToWrite.Crop(m_InputImage->GetLargestPossibleRegion());\n return regionToWrite;\n }\n else\n {\n return m_InputImage->GetLargestPossibleRegion();\n }\n}\n\ntemplate <class TWriter>\nvoid MultiImageFileWriter::AddInputWriter(typename TWriter::Pointer writer)\n{\n Sink<typename TWriter::InputImageType>* sink = new Sink<typename TWriter::InputImageType>(writer);\n m_SinkList.push_back(SinkBase::Pointer(sink));\n unsigned int size = m_SinkList.size();\n this->SetNthInput(size - 1, const_cast<itk::DataObject*>(dynamic_cast<const itk::DataObject*>(writer->GetInput())));\n \/** Parse streaming modes *\/\n \n auto filenameHelper = writer->GetFilenameHelper();\n if (filenameHelper->StreamingTypeIsSet())\n {\n otbLogMacro(\n Warning,\n << \"Streaming configuration through extended filename is used. Any previous streaming configuration (ram value, streaming mode ...) will be ignored.\");\n\n std::string type = filenameHelper->GetStreamingType();\n\n std::string sizemode = \"auto\";\n\n if (filenameHelper->StreamingSizeModeIsSet())\n {\n sizemode = filenameHelper->GetStreamingSizeMode();\n }\n \n unsigned int sizevalue = 0;\n \/\/ Save the DefaultRAM value for later\n unsigned int oldDefaultRAM = m_StreamingManager->GetDefaultRAM();\n if (sizemode == \"auto\")\n {\n sizevalue = oldDefaultRAM;\n }\n\n if (filenameHelper->StreamingSizeValueIsSet())\n {\n sizevalue = static_cast<unsigned int>(filenameHelper->GetStreamingSizeValue());\n }\n\n if (type == \"auto\")\n {\n if (sizemode != \"auto\")\n {\n otbLogMacro(Warning, << \"In auto streaming type, the sizemode option will be ignored.\");\n }\n if (sizevalue == 0)\n {\n otbLogMacro(Warning, << \"sizemode is auto but sizevalue is 0. Value will be fetched from the OTB_MAX_RAM_HINT environment variable if set, or else use \"\n \"the default value\");\n }\n this->SetAutomaticAdaptativeStreaming(sizevalue);\n }\n else if (type == \"tiled\")\n {\n if (sizemode == \"auto\")\n {\n if (sizevalue == 0)\n {\n otbLogMacro(Warning, << \"sizemode is auto but sizevalue is 0. Value will be fetched from the OTB_MAX_RAM_HINT environment variable if set, or else \"\n \"use the default value\");\n }\n this->SetAutomaticTiledStreaming(sizevalue);\n }\n else if (sizemode == \"nbsplits\")\n {\n if (sizevalue == 0)\n {\n otbLogMacro(Warning, << \"Streaming sizemode is set to nbsplits but sizevalue is 0. This will result in undefined behaviour. Please consider setting \"\n \"the sizevalue by using &streaming:sizevalue=x.\");\n }\n this->SetNumberOfDivisionsTiledStreaming(sizevalue);\n }\n else if (sizemode == \"height\")\n {\n if (sizevalue == 0)\n {\n otbLogMacro(Warning, << \"Streaming sizemode is set to height but sizevalue is 0. This will result in undefined behaviour. Please consider setting \"\n \"the sizevalue by using &streaming:sizevalue=x.\");\n }\n\n this->SetTileDimensionTiledStreaming(sizevalue);\n }\n }\n else if (type == \"stripped\")\n {\n if (sizemode == \"auto\")\n {\n if (sizevalue == 0)\n {\n otbLogMacro(\n Warning, << \"sizemode is auto but sizevalue is 0. Value will be fetched from configuration file if any, or from cmake configuration otherwise.\");\n }\n\n this->SetAutomaticStrippedStreaming(sizevalue);\n }\n else if (sizemode == \"nbsplits\")\n {\n if (sizevalue == 0)\n {\n otbLogMacro(Warning, << \"Streaming sizemode is set to nbsplits but sizevalue is 0. This will result in undefined behaviour. Please consider setting \"\n \"the sizevalue by using &streaming:sizevalue=x.\");\n }\n this->SetNumberOfDivisionsStrippedStreaming(sizevalue);\n }\n else if (sizemode == \"height\")\n {\n if (sizevalue == 0)\n {\n otbLogMacro(Warning, << \"Streaming sizemode is set to height but sizevalue is 0. This will result in undefined behaviour. Please consider setting \"\n \"the sizevalue by using &streaming:sizevalue=x.\");\n }\n this->SetNumberOfLinesStrippedStreaming(sizevalue);\n }\n }\n else if (type == \"none\")\n {\n if (sizemode != \"\" || sizevalue != 0)\n {\n otbLogMacro(Warning, << \"Streaming is explicitly disabled, sizemode and sizevalue will be ignored.\");\n }\n this->SetNumberOfDivisionsTiledStreaming(0);\n }\n m_StreamingManager->SetDefaultRAM(oldDefaultRAM);\n }\n else\n {\n if (filenameHelper->StreamingSizeValueIsSet() || filenameHelper->StreamingSizeModeIsSet())\n {\n otbLogMacro(Warning, << \"No streaming type is set, streaming sizemode and sizevalue will be ignored.\");\n }\n }\n}\n\ntemplate <class TImage>\nvoid MultiImageFileWriter::AddInputImage(const TImage* inputPtr, const std::string& fileName)\n{\n Sink<TImage>* sink = new Sink<TImage>(inputPtr, fileName);\n m_SinkList.push_back(SinkBase::Pointer(sink));\n unsigned int size = m_SinkList.size();\n this->SetNthInput(size - 1, const_cast<itk::DataObject*>(dynamic_cast<const itk::DataObject*>(inputPtr)));\n}\n\n} \/\/ end of namespace otb\n\n#endif \/\/ otbMultiImageFileWriter_hxx\n<commit_msg>WRG: fix clang warning<commit_after>\/*\n * Copyright (C) 2017-2019 CS Systemes d'Information (CS SI)\n *\n * This file is part of Orfeo Toolbox\n *\n * https:\/\/www.orfeo-toolbox.org\/\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#ifndef otbMultiImageFileWriter_hxx\n#define otbMultiImageFileWriter_hxx\n\n#include \"otbMultiImageFileWriter.h\"\n#include \"otbImageIOFactory.h\"\n#include \"otbMacro.h\"\n\nnamespace otb\n{\n\ntemplate <class TImage>\nMultiImageFileWriter::Sink<TImage>::Sink(typename TImage::ConstPointer inputImage, const std::string& fileName)\n : SinkBase(dynamic_cast<const ImageBaseType*>(inputImage.GetPointer())), m_Writer(otb::ImageFileWriter<TImage>::New()), m_ImageIO(NULL)\n{\n m_Writer->SetFileName(fileName);\n m_Writer->SetInput(inputImage);\n}\n\ntemplate <class TImage>\nMultiImageFileWriter::Sink<TImage>::Sink(typename otb::ImageFileWriter<TImage>::Pointer writer)\n : SinkBase(dynamic_cast<const ImageBaseType*>(writer->GetInput())), m_Writer(writer), m_ImageIO(NULL)\n{\n}\n\ntemplate <class TImage>\nbool MultiImageFileWriter::Sink<TImage>::CanStreamWrite() const\n{\n if (m_ImageIO.IsNull())\n return false;\n return m_ImageIO->CanStreamWrite();\n}\n\ntemplate <class TImage>\nvoid MultiImageFileWriter::Sink<TImage>::WriteImageInformation()\n{\n m_Writer->UpdateOutputInformation();\n m_ImageIO = m_Writer->GetImageIO();\n}\n\ntemplate <class TImage>\nvoid MultiImageFileWriter::Sink<TImage>::Write(const RegionType& streamRegion)\n{\n \/\/ Write the image stream\n itk::ImageIORegion ioRegion(TImage::ImageDimension);\n for (unsigned int i = 0; i < TImage::ImageDimension; ++i)\n {\n ioRegion.SetSize(i, streamRegion.GetSize(i));\n ioRegion.SetIndex(i, streamRegion.GetIndex(i));\n }\n m_ImageIO->SetIORegion(ioRegion);\n m_Writer->UpdateOutputData(nullptr);\n}\n\ntemplate <class TImage>\nitk::ImageRegion<2>\nMultiImageFileWriter::Sink<TImage>::GetRegionToWrite() const\n{\n auto fnameHelper = m_Writer->GetFilenameHelper();\n if (fnameHelper->BoxIsSet())\n {\n std::vector<unsigned int> boxVector;\n Utils::ConvertStringToVector(fnameHelper->GetBox(), boxVector, \"ExtendedFileName:box\", \":\");\n\n if (boxVector.size() != 4)\n {\n itk::ImageFileWriterException e(__FILE__, __LINE__);\n std::ostringstream msg;\n msg << \"Invalid box option \" << fnameHelper->GetBox() << \". The box should contains four elements: startx:starty:sizex:sizey\";\n e.SetDescription(msg.str());\n e.SetLocation(ITK_LOCATION);\n throw e;\n }\n \n typename itk::ImageRegion<2>::IndexType start {{boxVector[0], boxVector[1]}};\n typename itk::ImageRegion<2>::SizeType size {{boxVector[2], boxVector[3]}};\n itk::ImageRegion<2> regionToWrite {start , size};\n regionToWrite.Crop(m_InputImage->GetLargestPossibleRegion());\n return regionToWrite;\n }\n else\n {\n return m_InputImage->GetLargestPossibleRegion();\n }\n}\n\ntemplate <class TWriter>\nvoid MultiImageFileWriter::AddInputWriter(typename TWriter::Pointer writer)\n{\n Sink<typename TWriter::InputImageType>* sink = new Sink<typename TWriter::InputImageType>(writer);\n m_SinkList.push_back(SinkBase::Pointer(sink));\n unsigned int size = m_SinkList.size();\n this->SetNthInput(size - 1, const_cast<itk::DataObject*>(dynamic_cast<const itk::DataObject*>(writer->GetInput())));\n \/** Parse streaming modes *\/\n \n auto filenameHelper = writer->GetFilenameHelper();\n if (filenameHelper->StreamingTypeIsSet())\n {\n otbLogMacro(\n Warning,\n << \"Streaming configuration through extended filename is used. Any previous streaming configuration (ram value, streaming mode ...) will be ignored.\");\n\n std::string type = filenameHelper->GetStreamingType();\n\n std::string sizemode = \"auto\";\n\n if (filenameHelper->StreamingSizeModeIsSet())\n {\n sizemode = filenameHelper->GetStreamingSizeMode();\n }\n \n unsigned int sizevalue = 0;\n \/\/ Save the DefaultRAM value for later\n unsigned int oldDefaultRAM = m_StreamingManager->GetDefaultRAM();\n if (sizemode == \"auto\")\n {\n sizevalue = oldDefaultRAM;\n }\n\n if (filenameHelper->StreamingSizeValueIsSet())\n {\n sizevalue = static_cast<unsigned int>(filenameHelper->GetStreamingSizeValue());\n }\n\n if (type == \"auto\")\n {\n if (sizemode != \"auto\")\n {\n otbLogMacro(Warning, << \"In auto streaming type, the sizemode option will be ignored.\");\n }\n if (sizevalue == 0)\n {\n otbLogMacro(Warning, << \"sizemode is auto but sizevalue is 0. Value will be fetched from the OTB_MAX_RAM_HINT environment variable if set, or else use \"\n \"the default value\");\n }\n this->SetAutomaticAdaptativeStreaming(sizevalue);\n }\n else if (type == \"tiled\")\n {\n if (sizemode == \"auto\")\n {\n if (sizevalue == 0)\n {\n otbLogMacro(Warning, << \"sizemode is auto but sizevalue is 0. Value will be fetched from the OTB_MAX_RAM_HINT environment variable if set, or else \"\n \"use the default value\");\n }\n this->SetAutomaticTiledStreaming(sizevalue);\n }\n else if (sizemode == \"nbsplits\")\n {\n if (sizevalue == 0)\n {\n otbLogMacro(Warning, << \"Streaming sizemode is set to nbsplits but sizevalue is 0. This will result in undefined behaviour. Please consider setting \"\n \"the sizevalue by using &streaming:sizevalue=x.\");\n }\n this->SetNumberOfDivisionsTiledStreaming(sizevalue);\n }\n else if (sizemode == \"height\")\n {\n if (sizevalue == 0)\n {\n otbLogMacro(Warning, << \"Streaming sizemode is set to height but sizevalue is 0. This will result in undefined behaviour. Please consider setting \"\n \"the sizevalue by using &streaming:sizevalue=x.\");\n }\n\n this->SetTileDimensionTiledStreaming(sizevalue);\n }\n }\n else if (type == \"stripped\")\n {\n if (sizemode == \"auto\")\n {\n if (sizevalue == 0)\n {\n otbLogMacro(\n Warning, << \"sizemode is auto but sizevalue is 0. Value will be fetched from configuration file if any, or from cmake configuration otherwise.\");\n }\n\n this->SetAutomaticStrippedStreaming(sizevalue);\n }\n else if (sizemode == \"nbsplits\")\n {\n if (sizevalue == 0)\n {\n otbLogMacro(Warning, << \"Streaming sizemode is set to nbsplits but sizevalue is 0. This will result in undefined behaviour. Please consider setting \"\n \"the sizevalue by using &streaming:sizevalue=x.\");\n }\n this->SetNumberOfDivisionsStrippedStreaming(sizevalue);\n }\n else if (sizemode == \"height\")\n {\n if (sizevalue == 0)\n {\n otbLogMacro(Warning, << \"Streaming sizemode is set to height but sizevalue is 0. This will result in undefined behaviour. Please consider setting \"\n \"the sizevalue by using &streaming:sizevalue=x.\");\n }\n this->SetNumberOfLinesStrippedStreaming(sizevalue);\n }\n }\n else if (type == \"none\")\n {\n if (sizemode != \"\" || sizevalue != 0)\n {\n otbLogMacro(Warning, << \"Streaming is explicitly disabled, sizemode and sizevalue will be ignored.\");\n }\n this->SetNumberOfDivisionsTiledStreaming(0);\n }\n m_StreamingManager->SetDefaultRAM(oldDefaultRAM);\n }\n else\n {\n if (filenameHelper->StreamingSizeValueIsSet() || filenameHelper->StreamingSizeModeIsSet())\n {\n otbLogMacro(Warning, << \"No streaming type is set, streaming sizemode and sizevalue will be ignored.\");\n }\n }\n}\n\ntemplate <class TImage>\nvoid MultiImageFileWriter::AddInputImage(const TImage* inputPtr, const std::string& fileName)\n{\n Sink<TImage>* sink = new Sink<TImage>(inputPtr, fileName);\n m_SinkList.push_back(SinkBase::Pointer(sink));\n unsigned int size = m_SinkList.size();\n this->SetNthInput(size - 1, const_cast<itk::DataObject*>(dynamic_cast<const itk::DataObject*>(inputPtr)));\n}\n\n} \/\/ end of namespace otb\n\n#endif \/\/ otbMultiImageFileWriter_hxx\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: MasterPageDescriptor.cxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: obo $ $Date: 2006-09-16 19:19:16 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_sd.hxx\"\n\n#include \"MasterPageDescriptor.hxx\"\n\n#include \"DocumentHelper.hxx\"\n#include \"sdpage.hxx\"\n\n#ifndef _URLOBJ_HXX\n#include <tools\/urlobj.hxx>\n#endif\n\nnamespace sd { namespace toolpanel { namespace controls {\n\n\n\/\/===== MasterPageDescriptor ==================================================\n\nMasterPageDescriptor::MasterPageDescriptor (\n MasterPageContainer::Origin eOrigin,\n const sal_Int32 nTemplateIndex,\n const String& rsURL,\n const String& rsPageName,\n const String& rsStyleName,\n const ::boost::shared_ptr<PageObjectProvider>& rpPageObjectProvider,\n const ::boost::shared_ptr<PreviewProvider>& rpPreviewProvider)\n : maToken(MasterPageContainer::NIL_TOKEN),\n meOrigin(eOrigin),\n msURL(INetURLObject(rsURL).GetMainURL(INetURLObject::DECODE_UNAMBIGUOUS)),\n msPageName(rsPageName),\n msStyleName(rsStyleName),\n mpMasterPage(NULL),\n mpSlide(NULL),\n maSmallPreview(),\n maLargePreview(),\n mpPreviewProvider(rpPreviewProvider),\n mpPageObjectProvider(rpPageObjectProvider),\n mnTemplateIndex(nTemplateIndex),\n meURLClassification(URLCLASS_UNDETERMINED),\n mnUseCount(0)\n{\n}\n\n\n\n\nMasterPageDescriptor::MasterPageDescriptor (const MasterPageDescriptor& rDescriptor)\n : maToken(rDescriptor.maToken),\n meOrigin(rDescriptor.meOrigin),\n msURL(rDescriptor.msURL),\n msPageName(rDescriptor.msPageName),\n msStyleName(rDescriptor.msStyleName),\n mpMasterPage(rDescriptor.mpMasterPage),\n mpSlide(rDescriptor.mpSlide),\n maSmallPreview(rDescriptor.maSmallPreview),\n maLargePreview(rDescriptor.maLargePreview),\n mpPreviewProvider(rDescriptor.mpPreviewProvider),\n mpPageObjectProvider(rDescriptor.mpPageObjectProvider),\n mnTemplateIndex(rDescriptor.mnTemplateIndex),\n meURLClassification(rDescriptor.meURLClassification),\n mnUseCount(rDescriptor.mnUseCount)\n{\n}\n\n\n\n\nMasterPageDescriptor::~MasterPageDescriptor (void)\n{\n}\n\n\n\n\nvoid MasterPageDescriptor::SetToken (MasterPageContainer::Token aToken)\n{\n maToken = aToken;\n}\n\n\n\n\nImage MasterPageDescriptor::GetPreview (MasterPageContainer::PreviewSize eSize)\n{\n if (eSize == MasterPageContainer::SMALL)\n return maSmallPreview;\n else\n return maLargePreview;\n}\n\n\n\n\n::std::auto_ptr<std::vector<MasterPageContainerChangeEvent::EventType> >\n MasterPageDescriptor::Update (\n const MasterPageDescriptor& rDescriptor)\n{\n bool bDataChanged (false);\n bool bIndexChanged (false);\n bool bPreviewChanged (false);\n\n if (meOrigin==MasterPageContainer::UNKNOWN\n && rDescriptor.meOrigin!=MasterPageContainer::UNKNOWN)\n {\n meOrigin = rDescriptor.meOrigin;\n bIndexChanged = true;\n }\n\n if (msURL.getLength()==0 && rDescriptor.msURL.getLength()!=0)\n {\n msURL = rDescriptor.msURL;\n bDataChanged = true;\n }\n\n if (msPageName.getLength()==0 && rDescriptor.msPageName.getLength()!=0)\n {\n msPageName = rDescriptor.msPageName;\n bDataChanged = true;\n }\n\n if (msStyleName.getLength()==0 && rDescriptor.msStyleName.getLength()!=0)\n {\n msStyleName = rDescriptor.msStyleName;\n bDataChanged = true;\n }\n\n if (mpPageObjectProvider.get()==NULL && rDescriptor.mpPageObjectProvider.get()!=NULL)\n {\n mpPageObjectProvider = rDescriptor.mpPageObjectProvider;\n bDataChanged = true;\n }\n\n if (mpPreviewProvider.get()==NULL && rDescriptor.mpPreviewProvider.get()!=NULL)\n {\n mpPreviewProvider = rDescriptor.mpPreviewProvider;\n bPreviewChanged = true;\n }\n\n if (mnTemplateIndex<0 && rDescriptor.mnTemplateIndex>=0)\n {\n mnTemplateIndex = rDescriptor.mnTemplateIndex;\n bIndexChanged = true;\n }\n\n \/\/ Prepare the list of event types that will be returned.\n ::std::auto_ptr<std::vector<MasterPageContainerChangeEvent::EventType> > pResult;\n if (bDataChanged || bIndexChanged || bPreviewChanged)\n {\n pResult.reset(new std::vector<MasterPageContainerChangeEvent::EventType>());\n if (bDataChanged)\n pResult->push_back(MasterPageContainerChangeEvent::DATA_CHANGED);\n if (bIndexChanged)\n pResult->push_back(MasterPageContainerChangeEvent::INDEX_CHANGED);\n if (bPreviewChanged)\n pResult->push_back(MasterPageContainerChangeEvent::PREVIEW_CHANGED);\n }\n\n return pResult;\n}\n\n\n\n\nbool MasterPageDescriptor::UpdatePageObject (\n sal_Int32 nCostThreshold,\n SdDrawDocument* pDocument)\n{\n bool bModified (false);\n\n \/\/ Update the page object when that is not yet known.\n if (mpMasterPage == NULL\n && mpPageObjectProvider.get()!=NULL\n && (nCostThreshold<0 || mpPageObjectProvider->GetCostIndex()<=nCostThreshold))\n {\n \/\/ Note that pDocument may be NULL.\n\n SdPage* pPage = (*mpPageObjectProvider)(pDocument);\n if (meOrigin == MasterPageContainer::MASTERPAGE)\n {\n mpMasterPage = pPage;\n }\n else\n {\n \/\/ Master pages from templates are copied into the local document.\n if (pDocument != NULL)\n mpMasterPage = DocumentHelper::CopyMasterPageToLocalDocument(*pDocument,pPage);\n mpSlide = DocumentHelper::GetSlideForMasterPage(mpMasterPage);\n }\n\n if (mpMasterPage != NULL)\n {\n \/\/ Update page name and style name.\n if (msPageName.getLength() == 0)\n msPageName = mpMasterPage->GetName();\n msStyleName = mpMasterPage->GetName();\n\n \/\/ Delete an existing substitution. The next request for a preview\n \/\/ will create the real one.\n maSmallPreview = Image();\n maLargePreview = Image();\n mpPreviewProvider = ::boost::shared_ptr<PreviewProvider>(new PagePreviewProvider());\n }\n else\n {\n DBG_ASSERT(false, \"UpdatePageObject: master page is NULL\");\n }\n\n bModified = true;\n }\n\n return bModified;\n}\n\n\n\n\nbool MasterPageDescriptor::UpdatePreview (\n sal_Int32 nCostThreshold,\n const Size& rSmallSize,\n const Size& rLargeSize,\n ::sd::PreviewRenderer& rRenderer)\n{\n bool bModified (false);\n\n \/\/ Update the preview when that is not yet known.\n if (maLargePreview.GetSizePixel().Width()==0\n && mpPreviewProvider.get()!=NULL\n && (nCostThreshold<0 || mpPreviewProvider->GetCostIndex()<=nCostThreshold))\n {\n SdPage* pPage = mpSlide;\n if (pPage == NULL)\n {\n pPage = mpMasterPage;\n }\n maLargePreview = (*mpPreviewProvider)(\n rLargeSize.Width(),\n pPage,\n rRenderer);\n if (maLargePreview.GetSizePixel().Width() > 0)\n {\n \/\/ Create the small preview by scaling the large one down.\n maSmallPreview = rRenderer.ScaleBitmap(\n maLargePreview.GetBitmapEx(),\n rSmallSize.Width());\n \/\/ The large preview may not have the desired width. Scale it\n \/\/ accrodingly.\n if (maLargePreview.GetSizePixel().Width() != rLargeSize.Width())\n maLargePreview = rRenderer.ScaleBitmap(\n maLargePreview.GetBitmapEx(),\n rLargeSize.Width());\n bModified = true;\n }\n }\n\n return bModified;\n}\n\n\n\n\nMasterPageDescriptor::URLClassification MasterPageDescriptor::GetURLClassification (void)\n{\n if (meURLClassification == URLCLASS_UNDETERMINED)\n {\n if (msURL.getLength() == 0)\n meURLClassification = URLCLASS_UNKNOWN;\n else if (msURL.indexOf(::rtl::OUString::createFromAscii(\"presnt\"))>=0)\n {\n meURLClassification = URLCLASS_PRESENTATION;\n }\n else if (msURL.indexOf(::rtl::OUString::createFromAscii(\"layout\"))>=0)\n {\n meURLClassification = URLCLASS_LAYOUT;\n }\n else if (msURL.indexOf(::rtl::OUString::createFromAscii(\"educate\"))>=0)\n {\n meURLClassification = URLCLASS_OTHER;\n }\n else\n {\n meURLClassification = URLCLASS_USER;\n }\n }\n\n return meURLClassification;\n}\n\n\n\n\/\/===== URLComparator =========================================================\n\nMasterPageDescriptor::URLComparator::URLComparator (const ::rtl::OUString& sURL)\n : msURL(sURL)\n{\n}\n\n\n\n\nbool MasterPageDescriptor::URLComparator::operator() (\n const SharedMasterPageDescriptor& rDescriptor)\n{\n if (rDescriptor.get() == NULL)\n return false;\n else\n return rDescriptor->msURL.equals(msURL);\n}\n\n\n\n\n\/\/===== PageNameComparator ====================================================\n\nMasterPageDescriptor::PageNameComparator::PageNameComparator (const ::rtl::OUString& sPageName)\n : msPageName(sPageName)\n{\n}\n\n\n\n\nbool MasterPageDescriptor::PageNameComparator::operator() (\n const SharedMasterPageDescriptor& rDescriptor)\n{\n if (rDescriptor.get() == NULL)\n return false;\n else\n return rDescriptor->msPageName.equals(msPageName);\n}\n\n\n\n\n\/\/ ===== StyleNameComparator ==================================================\n\nMasterPageDescriptor::StyleNameComparator::StyleNameComparator (const ::rtl::OUString& sStyleName)\n : msStyleName(sStyleName)\n{\n}\n\n\n\n\nbool MasterPageDescriptor::StyleNameComparator::operator() (\n const SharedMasterPageDescriptor& rDescriptor)\n{\n if (rDescriptor.get() == NULL)\n return false;\n else\n return rDescriptor->msStyleName.equals(msStyleName);\n}\n\n\n\n\n\/\/===== PageObjectComparator ==================================================\n\nMasterPageDescriptor::PageObjectComparator::PageObjectComparator (const SdPage* pPageObject)\n : mpMasterPage(pPageObject)\n{\n}\n\n\n\n\nbool MasterPageDescriptor::PageObjectComparator::operator() (\n const SharedMasterPageDescriptor& rDescriptor)\n{\n if (rDescriptor.get() == NULL)\n return false;\n else\n return rDescriptor->mpMasterPage==mpMasterPage;\n}\n\n\n\n\n\/\/===== AllComparator =========================================================\n\nMasterPageDescriptor::AllComparator::AllComparator(const SharedMasterPageDescriptor& rDescriptor)\n : mpDescriptor(rDescriptor)\n{\n}\n\n\n\n\nbool MasterPageDescriptor::AllComparator::operator() (const SharedMasterPageDescriptor&rDescriptor)\n{\n if (rDescriptor.get() == NULL)\n return false;\n else\n {\n \/\/ Take URL, page name, style name, and page object into account\n \/\/ when comparing two descriptors. When two descriptors are\n \/\/ identical in any of these values then their are thought of as\n \/\/ equivalent. Only the Origin has to be the same in both\n \/\/ descriptors.\n return\n mpDescriptor->meOrigin == rDescriptor->meOrigin\n && (\n (mpDescriptor->msURL.getLength()>0\n && mpDescriptor->msURL.equals(rDescriptor->msURL))\n || (mpDescriptor->msPageName.getLength()>0\n && mpDescriptor->msPageName.equals(rDescriptor->msPageName))\n || (mpDescriptor->msStyleName.getLength()>0\n && mpDescriptor->msStyleName.equals(rDescriptor->msStyleName))\n || (mpDescriptor->mpMasterPage!=NULL\n && mpDescriptor->mpMasterPage==rDescriptor->mpMasterPage)\n || (mpDescriptor->mpPageObjectProvider.get()!=NULL\n && rDescriptor->mpPageObjectProvider.get()!=NULL\n && mpDescriptor->mpPageObjectProvider==rDescriptor->mpPageObjectProvider));\n }\n}\n\n\n} } } \/\/ end of namespace ::sd::toolpanel::controls\n<commit_msg>INTEGRATION: CWS changefileheader (1.3.358); FILE MERGED 2008\/04\/01 15:36:08 thb 1.3.358.2: #i85898# Stripping all external header guards 2008\/03\/31 13:59:02 rt 1.3.358.1: #i87441# Change license header to LPGL v3.<commit_after>\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2008 by Sun Microsystems, Inc.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: MasterPageDescriptor.cxx,v $\n * $Revision: 1.4 $\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * <http:\/\/www.openoffice.org\/license.html>\n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_sd.hxx\"\n\n#include \"MasterPageDescriptor.hxx\"\n\n#include \"DocumentHelper.hxx\"\n#include \"sdpage.hxx\"\n#include <tools\/urlobj.hxx>\n\nnamespace sd { namespace toolpanel { namespace controls {\n\n\n\/\/===== MasterPageDescriptor ==================================================\n\nMasterPageDescriptor::MasterPageDescriptor (\n MasterPageContainer::Origin eOrigin,\n const sal_Int32 nTemplateIndex,\n const String& rsURL,\n const String& rsPageName,\n const String& rsStyleName,\n const ::boost::shared_ptr<PageObjectProvider>& rpPageObjectProvider,\n const ::boost::shared_ptr<PreviewProvider>& rpPreviewProvider)\n : maToken(MasterPageContainer::NIL_TOKEN),\n meOrigin(eOrigin),\n msURL(INetURLObject(rsURL).GetMainURL(INetURLObject::DECODE_UNAMBIGUOUS)),\n msPageName(rsPageName),\n msStyleName(rsStyleName),\n mpMasterPage(NULL),\n mpSlide(NULL),\n maSmallPreview(),\n maLargePreview(),\n mpPreviewProvider(rpPreviewProvider),\n mpPageObjectProvider(rpPageObjectProvider),\n mnTemplateIndex(nTemplateIndex),\n meURLClassification(URLCLASS_UNDETERMINED),\n mnUseCount(0)\n{\n}\n\n\n\n\nMasterPageDescriptor::MasterPageDescriptor (const MasterPageDescriptor& rDescriptor)\n : maToken(rDescriptor.maToken),\n meOrigin(rDescriptor.meOrigin),\n msURL(rDescriptor.msURL),\n msPageName(rDescriptor.msPageName),\n msStyleName(rDescriptor.msStyleName),\n mpMasterPage(rDescriptor.mpMasterPage),\n mpSlide(rDescriptor.mpSlide),\n maSmallPreview(rDescriptor.maSmallPreview),\n maLargePreview(rDescriptor.maLargePreview),\n mpPreviewProvider(rDescriptor.mpPreviewProvider),\n mpPageObjectProvider(rDescriptor.mpPageObjectProvider),\n mnTemplateIndex(rDescriptor.mnTemplateIndex),\n meURLClassification(rDescriptor.meURLClassification),\n mnUseCount(rDescriptor.mnUseCount)\n{\n}\n\n\n\n\nMasterPageDescriptor::~MasterPageDescriptor (void)\n{\n}\n\n\n\n\nvoid MasterPageDescriptor::SetToken (MasterPageContainer::Token aToken)\n{\n maToken = aToken;\n}\n\n\n\n\nImage MasterPageDescriptor::GetPreview (MasterPageContainer::PreviewSize eSize)\n{\n if (eSize == MasterPageContainer::SMALL)\n return maSmallPreview;\n else\n return maLargePreview;\n}\n\n\n\n\n::std::auto_ptr<std::vector<MasterPageContainerChangeEvent::EventType> >\n MasterPageDescriptor::Update (\n const MasterPageDescriptor& rDescriptor)\n{\n bool bDataChanged (false);\n bool bIndexChanged (false);\n bool bPreviewChanged (false);\n\n if (meOrigin==MasterPageContainer::UNKNOWN\n && rDescriptor.meOrigin!=MasterPageContainer::UNKNOWN)\n {\n meOrigin = rDescriptor.meOrigin;\n bIndexChanged = true;\n }\n\n if (msURL.getLength()==0 && rDescriptor.msURL.getLength()!=0)\n {\n msURL = rDescriptor.msURL;\n bDataChanged = true;\n }\n\n if (msPageName.getLength()==0 && rDescriptor.msPageName.getLength()!=0)\n {\n msPageName = rDescriptor.msPageName;\n bDataChanged = true;\n }\n\n if (msStyleName.getLength()==0 && rDescriptor.msStyleName.getLength()!=0)\n {\n msStyleName = rDescriptor.msStyleName;\n bDataChanged = true;\n }\n\n if (mpPageObjectProvider.get()==NULL && rDescriptor.mpPageObjectProvider.get()!=NULL)\n {\n mpPageObjectProvider = rDescriptor.mpPageObjectProvider;\n bDataChanged = true;\n }\n\n if (mpPreviewProvider.get()==NULL && rDescriptor.mpPreviewProvider.get()!=NULL)\n {\n mpPreviewProvider = rDescriptor.mpPreviewProvider;\n bPreviewChanged = true;\n }\n\n if (mnTemplateIndex<0 && rDescriptor.mnTemplateIndex>=0)\n {\n mnTemplateIndex = rDescriptor.mnTemplateIndex;\n bIndexChanged = true;\n }\n\n \/\/ Prepare the list of event types that will be returned.\n ::std::auto_ptr<std::vector<MasterPageContainerChangeEvent::EventType> > pResult;\n if (bDataChanged || bIndexChanged || bPreviewChanged)\n {\n pResult.reset(new std::vector<MasterPageContainerChangeEvent::EventType>());\n if (bDataChanged)\n pResult->push_back(MasterPageContainerChangeEvent::DATA_CHANGED);\n if (bIndexChanged)\n pResult->push_back(MasterPageContainerChangeEvent::INDEX_CHANGED);\n if (bPreviewChanged)\n pResult->push_back(MasterPageContainerChangeEvent::PREVIEW_CHANGED);\n }\n\n return pResult;\n}\n\n\n\n\nbool MasterPageDescriptor::UpdatePageObject (\n sal_Int32 nCostThreshold,\n SdDrawDocument* pDocument)\n{\n bool bModified (false);\n\n \/\/ Update the page object when that is not yet known.\n if (mpMasterPage == NULL\n && mpPageObjectProvider.get()!=NULL\n && (nCostThreshold<0 || mpPageObjectProvider->GetCostIndex()<=nCostThreshold))\n {\n \/\/ Note that pDocument may be NULL.\n\n SdPage* pPage = (*mpPageObjectProvider)(pDocument);\n if (meOrigin == MasterPageContainer::MASTERPAGE)\n {\n mpMasterPage = pPage;\n }\n else\n {\n \/\/ Master pages from templates are copied into the local document.\n if (pDocument != NULL)\n mpMasterPage = DocumentHelper::CopyMasterPageToLocalDocument(*pDocument,pPage);\n mpSlide = DocumentHelper::GetSlideForMasterPage(mpMasterPage);\n }\n\n if (mpMasterPage != NULL)\n {\n \/\/ Update page name and style name.\n if (msPageName.getLength() == 0)\n msPageName = mpMasterPage->GetName();\n msStyleName = mpMasterPage->GetName();\n\n \/\/ Delete an existing substitution. The next request for a preview\n \/\/ will create the real one.\n maSmallPreview = Image();\n maLargePreview = Image();\n mpPreviewProvider = ::boost::shared_ptr<PreviewProvider>(new PagePreviewProvider());\n }\n else\n {\n DBG_ASSERT(false, \"UpdatePageObject: master page is NULL\");\n }\n\n bModified = true;\n }\n\n return bModified;\n}\n\n\n\n\nbool MasterPageDescriptor::UpdatePreview (\n sal_Int32 nCostThreshold,\n const Size& rSmallSize,\n const Size& rLargeSize,\n ::sd::PreviewRenderer& rRenderer)\n{\n bool bModified (false);\n\n \/\/ Update the preview when that is not yet known.\n if (maLargePreview.GetSizePixel().Width()==0\n && mpPreviewProvider.get()!=NULL\n && (nCostThreshold<0 || mpPreviewProvider->GetCostIndex()<=nCostThreshold))\n {\n SdPage* pPage = mpSlide;\n if (pPage == NULL)\n {\n pPage = mpMasterPage;\n }\n maLargePreview = (*mpPreviewProvider)(\n rLargeSize.Width(),\n pPage,\n rRenderer);\n if (maLargePreview.GetSizePixel().Width() > 0)\n {\n \/\/ Create the small preview by scaling the large one down.\n maSmallPreview = rRenderer.ScaleBitmap(\n maLargePreview.GetBitmapEx(),\n rSmallSize.Width());\n \/\/ The large preview may not have the desired width. Scale it\n \/\/ accrodingly.\n if (maLargePreview.GetSizePixel().Width() != rLargeSize.Width())\n maLargePreview = rRenderer.ScaleBitmap(\n maLargePreview.GetBitmapEx(),\n rLargeSize.Width());\n bModified = true;\n }\n }\n\n return bModified;\n}\n\n\n\n\nMasterPageDescriptor::URLClassification MasterPageDescriptor::GetURLClassification (void)\n{\n if (meURLClassification == URLCLASS_UNDETERMINED)\n {\n if (msURL.getLength() == 0)\n meURLClassification = URLCLASS_UNKNOWN;\n else if (msURL.indexOf(::rtl::OUString::createFromAscii(\"presnt\"))>=0)\n {\n meURLClassification = URLCLASS_PRESENTATION;\n }\n else if (msURL.indexOf(::rtl::OUString::createFromAscii(\"layout\"))>=0)\n {\n meURLClassification = URLCLASS_LAYOUT;\n }\n else if (msURL.indexOf(::rtl::OUString::createFromAscii(\"educate\"))>=0)\n {\n meURLClassification = URLCLASS_OTHER;\n }\n else\n {\n meURLClassification = URLCLASS_USER;\n }\n }\n\n return meURLClassification;\n}\n\n\n\n\/\/===== URLComparator =========================================================\n\nMasterPageDescriptor::URLComparator::URLComparator (const ::rtl::OUString& sURL)\n : msURL(sURL)\n{\n}\n\n\n\n\nbool MasterPageDescriptor::URLComparator::operator() (\n const SharedMasterPageDescriptor& rDescriptor)\n{\n if (rDescriptor.get() == NULL)\n return false;\n else\n return rDescriptor->msURL.equals(msURL);\n}\n\n\n\n\n\/\/===== PageNameComparator ====================================================\n\nMasterPageDescriptor::PageNameComparator::PageNameComparator (const ::rtl::OUString& sPageName)\n : msPageName(sPageName)\n{\n}\n\n\n\n\nbool MasterPageDescriptor::PageNameComparator::operator() (\n const SharedMasterPageDescriptor& rDescriptor)\n{\n if (rDescriptor.get() == NULL)\n return false;\n else\n return rDescriptor->msPageName.equals(msPageName);\n}\n\n\n\n\n\/\/ ===== StyleNameComparator ==================================================\n\nMasterPageDescriptor::StyleNameComparator::StyleNameComparator (const ::rtl::OUString& sStyleName)\n : msStyleName(sStyleName)\n{\n}\n\n\n\n\nbool MasterPageDescriptor::StyleNameComparator::operator() (\n const SharedMasterPageDescriptor& rDescriptor)\n{\n if (rDescriptor.get() == NULL)\n return false;\n else\n return rDescriptor->msStyleName.equals(msStyleName);\n}\n\n\n\n\n\/\/===== PageObjectComparator ==================================================\n\nMasterPageDescriptor::PageObjectComparator::PageObjectComparator (const SdPage* pPageObject)\n : mpMasterPage(pPageObject)\n{\n}\n\n\n\n\nbool MasterPageDescriptor::PageObjectComparator::operator() (\n const SharedMasterPageDescriptor& rDescriptor)\n{\n if (rDescriptor.get() == NULL)\n return false;\n else\n return rDescriptor->mpMasterPage==mpMasterPage;\n}\n\n\n\n\n\/\/===== AllComparator =========================================================\n\nMasterPageDescriptor::AllComparator::AllComparator(const SharedMasterPageDescriptor& rDescriptor)\n : mpDescriptor(rDescriptor)\n{\n}\n\n\n\n\nbool MasterPageDescriptor::AllComparator::operator() (const SharedMasterPageDescriptor&rDescriptor)\n{\n if (rDescriptor.get() == NULL)\n return false;\n else\n {\n \/\/ Take URL, page name, style name, and page object into account\n \/\/ when comparing two descriptors. When two descriptors are\n \/\/ identical in any of these values then their are thought of as\n \/\/ equivalent. Only the Origin has to be the same in both\n \/\/ descriptors.\n return\n mpDescriptor->meOrigin == rDescriptor->meOrigin\n && (\n (mpDescriptor->msURL.getLength()>0\n && mpDescriptor->msURL.equals(rDescriptor->msURL))\n || (mpDescriptor->msPageName.getLength()>0\n && mpDescriptor->msPageName.equals(rDescriptor->msPageName))\n || (mpDescriptor->msStyleName.getLength()>0\n && mpDescriptor->msStyleName.equals(rDescriptor->msStyleName))\n || (mpDescriptor->mpMasterPage!=NULL\n && mpDescriptor->mpMasterPage==rDescriptor->mpMasterPage)\n || (mpDescriptor->mpPageObjectProvider.get()!=NULL\n && rDescriptor->mpPageObjectProvider.get()!=NULL\n && mpDescriptor->mpPageObjectProvider==rDescriptor->mpPageObjectProvider));\n }\n}\n\n\n} } } \/\/ end of namespace ::sd::toolpanel::controls\n<|endoftext|>"} {"text":"<commit_before>#include \"CryFuse.h\"\n\n#include <sys\/types.h>\n#include <sys\/time.h>\n#include <dirent.h>\n#include <cassert>\n\n#include \"cryfs_lib\/CryNode.h\"\n#include \"cryfs_lib\/CryErrnoException.h\"\n\n#define UNUSED(expr) (void)(expr)\n\nusing fusepp::path;\n\nnamespace cryfs {\n\nnamespace {\n int errcode_map(int exit_status) {\n if (exit_status < 0) {\n return -errno;\n }\n return exit_status;\n }\n}\n\nCryFuse::CryFuse(CryDevice *device)\n :_device(device) {\n}\n\nint CryFuse::getattr(const path &path, struct stat *stbuf) {\n try {\n _device->lstat(path, stbuf);\n return 0;\n } catch(cryfs::CryErrnoException &e) {\n return -e.getErrno();\n }\n}\n\nint CryFuse::fgetattr(const path &path, struct stat *stbuf, fuse_file_info *fileinfo) {\n \/\/printf(\"fgetattr(%s, _, _)\\n\", path.c_str());\n\n \/\/ On FreeBSD, trying to do anything with the mountpoint ends up\n \/\/ opening it, and then using the FD for an fgetattr. So in the\n \/\/ special case of a path of \"\/\", I need to do a getattr on the\n \/\/ underlying root directory instead of doing the fgetattr().\n \/\/ TODO Check if necessary\n if (path.native() == \"\/\") {\n return getattr(path, stbuf);\n }\n\n try {\n\t_device->fstat(fileinfo->fh, stbuf);\n\treturn 0;\n } catch(cryfs::CryErrnoException &e) {\n\t return -e.getErrno();\n }\n}\n\n\/\/TODO\nint CryFuse::readlink(const path &path, char *buf, size_t size) {\n \/\/printf(\"readlink(%s, _, %zu)\\n\", path.c_str(), size);\n auto real_path = _device->RootDir() \/ path;\n \/\/size-1, because the fuse readlink() function includes the null terminating byte in the buffer size,\n \/\/but the posix version does not and also doesn't append one.\n int real_size = ::readlink(real_path.c_str(), buf, size-1);\n if (real_size < 0) {\n return -errno;\n }\n \/\/Terminate the string\n buf[real_size] = '\\0';\n\n return 0;\n}\n\nint CryFuse::mknod(const path &path, mode_t mode, dev_t rdev) {\n UNUSED(rdev);\n UNUSED(mode);\n UNUSED(path);\n printf(\"Called non-implemented mknod(%s, %d, _)\\n\", path.c_str(), mode);\n return 0;\n}\n\nint CryFuse::mkdir(const path &path, mode_t mode) {\n \/\/printf(\"mkdir(%s, %d)\\n\", path.c_str(), mode);\n try {\n _device->mkdir(path, mode);\n return 0;\n } catch(cryfs::CryErrnoException &e) {\n return -e.getErrno();\n }\n}\n\nint CryFuse::unlink(const path &path) {\n \/\/printf(\"unlink(%s)\\n\", path.c_str());\n try {\n _device->unlink(path);\n return 0;\n } catch(cryfs::CryErrnoException &e) {\n return -e.getErrno();\n }\n}\n\nint CryFuse::rmdir(const path &path) {\n try {\n _device->rmdir(path);\n return 0;\n } catch(cryfs::CryErrnoException &e) {\n return -e.getErrno();\n }\n}\n\n\/\/TODO\nint CryFuse::symlink(const path &from, const path &to) {\n printf(\"NOT IMPLEMENTED: symlink(%s, %s)\\n\", from.c_str(), to.c_str());\n \/\/auto real_from = _device->RootDir() \/ from;\n \/\/auto real_to = _device->RootDir() \/ to;\n \/\/int retstat = ::symlink(real_from.c_str(), real_to.c_str());\n \/\/return errcode_map(retstat);\n return ENOSYS;\n}\n\nint CryFuse::rename(const path &from, const path &to) {\n \/\/printf(\"rename(%s, %s)\\n\", from.c_str(), to.c_str());\n try {\n _device->rename(from, to);\n return 0;\n } catch(cryfs::CryErrnoException &e) {\n return -e.getErrno();\n }\n}\n\n\/\/TODO\nint CryFuse::link(const path &from, const path &to) {\n printf(\"NOT IMPLEMENTED: link(%s, %s)\\n\", from.c_str(), to.c_str());\n \/\/auto real_from = _device->RootDir() \/ from;\n \/\/auto real_to = _device->RootDir() \/ to;\n \/\/int retstat = ::link(real_from.c_str(), real_to.c_str());\n \/\/return errcode_map(retstat);\n return ENOSYS;\n}\n\n\/\/TODO\nint CryFuse::chmod(const path &path, mode_t mode) {\n printf(\"NOT IMPLEMENTED: chmod(%s, %d)\\n\", path.c_str(), mode);\n \/\/auto real_path = _device->RootDir() \/ path;\n \/\/int retstat = ::chmod(real_path.c_str(), mode);\n \/\/return errcode_map(retstat);\n return ENOSYS;\n}\n\n\/\/TODO\nint CryFuse::chown(const path &path, uid_t uid, gid_t gid) {\n printf(\"NOT IMPLEMENTED: chown(%s, %d, %d)\\n\", path.c_str(), uid, gid);\n \/\/auto real_path = _device->RootDir() \/ path;\n \/\/int retstat = ::chown(real_path.c_str(), uid, gid);\n \/\/return errcode_map(retstat);\n return ENOSYS;\n}\n\nint CryFuse::truncate(const path &path, off_t size) {\n \/\/printf(\"truncate(%s, %zu)\\n\", path.c_str(), size);\n try {\n _device->truncate(path, size);\n return 0;\n } catch (CryErrnoException &e) {\n return -e.getErrno();\n }\n}\n\nint CryFuse::ftruncate(const path &path, off_t size, fuse_file_info *fileinfo) {\n \/\/printf(\"ftruncate(%s, %zu, _)\\n\", path.c_str(), size);\n\tUNUSED(path);\n try {\n _device->ftruncate(fileinfo->fh, size);\n return 0;\n } catch (CryErrnoException &e) {\n return -e.getErrno();\n }\n}\n\n\/\/TODO\nint CryFuse::utimens(const path &path, const timespec times[2]) {\n UNUSED(times);\n printf(\"NOT IMPLEMENTED: utimens(%s, _)\\n\", path.c_str());\n \/\/auto real_path = _device->RootDir() \/ path;\n \/\/struct timeval tv[2];\n \/\/tv[0].tv_sec = times[0].tv_sec;\n \/\/tv[0].tv_usec = times[0].tv_nsec \/ 1000;\n \/\/tv[1].tv_sec = times[1].tv_sec;\n \/\/tv[1].tv_usec = times[1].tv_nsec \/ 1000;\n \/\/int retstat = ::lutimes(real_path.c_str(), tv);\n \/\/return errcode_map(retstat);\n return ENOSYS;\n}\n\nint CryFuse::open(const path &path, fuse_file_info *fileinfo) {\n \/\/printf(\"open(%s, _)\\n\", path.c_str());\n try {\n\t fileinfo->fh = _device->openFile(path, fileinfo->flags);\n\t return 0;\n } catch (CryErrnoException &e) {\n\t return -e.getErrno();\n }\n}\n\nint CryFuse::release(const path &path, fuse_file_info *fileinfo) {\n \/\/printf(\"release(%s, _)\\n\", path.c_str());\n UNUSED(path);\n try {\n\t _device->closeFile(fileinfo->fh);\n\t return 0;\n } catch (CryErrnoException &e) {\n return -e.getErrno();\n }\n}\n\nint CryFuse::read(const path &path, char *buf, size_t size, off_t offset, fuse_file_info *fileinfo) {\n \/\/printf(\"read(%s, _, %zu, %zu, _)\\n\", path.c_str(), size, offset);\n UNUSED(path);\n try {\n \/\/printf(\"Reading from file %d\\n\", fileinfo->fh);\n \/\/fflush(stdout);\n return _device->read(fileinfo->fh, buf, size, offset);\n } catch (CryErrnoException &e) {\n return -e.getErrno();\n }\n}\n\nint CryFuse::write(const path &path, const char *buf, size_t size, off_t offset, fuse_file_info *fileinfo) {\n \/\/printf(\"write(%s, _, %zu, %zu, _)\\n\", path.c_str(), size, offset);\n UNUSED(path);\n try {\n _device->write(fileinfo->fh, buf, size, offset);\n return size;\n } catch (CryErrnoException &e) {\n return -e.getErrno();\n }\n}\n\n\/\/TODO\nint CryFuse::statfs(const path &path, struct statvfs *fsstat) {\n printf(\"HALF-IMPLEMENTED: statfs(%s, _)\\n\", path.c_str());\n auto real_path = _device->RootDir() \/ path;\n int retstat = ::statvfs(real_path.c_str(), fsstat);\n return errcode_map(retstat);\n}\n\n\/\/TODO\nint CryFuse::flush(const path &path, fuse_file_info *fileinfo) {\n \/\/printf(\"Called non-implemented flush(%s, _)\\n\", path.c_str());\n UNUSED(path);\n UNUSED(fileinfo);\n return 0;\n}\n\nint CryFuse::fsync(const path &path, int datasync, fuse_file_info *fileinfo) {\n \/\/printf(\"fsync(%s, %d, _)\\n\", path.c_str(), datasync);\n UNUSED(path);\n try {\n if (datasync) {\n _device->fdatasync(fileinfo->fh);\n } else {\n _device->fsync(fileinfo->fh);\n }\n return 0;\n } catch (CryErrnoException &e) {\n return -e.getErrno();\n }\n}\n\nint CryFuse::opendir(const path &path, fuse_file_info *fileinfo) {\n \/\/printf(\"opendir(%s, _)\\n\", path.c_str());\n try {\n fileinfo->fh = _device->openDir(path);\n return 0;\n } catch(CryErrnoException &e) {\n return -e.getErrno();\n }\n}\n\nint CryFuse::readdir(const path &path, void *buf, fuse_fill_dir_t filler, off_t offset, fuse_file_info *fileinfo) {\n UNUSED(path);\n \/\/printf(\"readdir(%s, _, _, %zu, _)\\n\", path.c_str(), offset);\n UNUSED(offset);\n try {\n auto entries = _device->readDir(fileinfo->fh);\n for (const auto &entry : *entries) {\n \/\/TODO Also give file attributes (third param of filler)\n if (filler(buf, entry.c_str(), nullptr, 0) != 0) {\n return -ENOMEM;\n }\n }\n return 0;\n } catch (CryErrnoException &e) {\n return -e.getErrno();\n }\n}\n\nint CryFuse::releasedir(const path &path, fuse_file_info *fileinfo) {\n \/\/printf(\"releasedir(%s, _)\\n\", path.c_str());\n UNUSED(path);\n try {\n _device->closeDir(fileinfo->fh);\n return 0;\n } catch (CryErrnoException &e) {\n return -e.getErrno();\n }\n}\n\n\/\/TODO\nint CryFuse::fsyncdir(const path &path, int datasync, fuse_file_info *fileinfo) {\n UNUSED(fileinfo);\n UNUSED(datasync);\n UNUSED(path);\n \/\/printf(\"Called non-implemented fsyncdir(%s, %d, _)\\n\", path.c_str(), datasync);\n return 0;\n}\n\nvoid CryFuse::init(fuse_conn_info *conn) {\n UNUSED(conn);\n \/\/printf(\"init()\\n\");\n}\n\nvoid CryFuse::destroy() {\n \/\/printf(\"destroy()\\n\");\n}\n\nint CryFuse::access(const path &path, int mask) {\n \/\/printf(\"access(%s, %d)\\n\", path.c_str(), mask);\n try {\n _device->access(path, mask);\n return 0;\n } catch (CryErrnoException &e) {\n return -e.getErrno();\n }\n}\n\nint CryFuse::create(const path &path, mode_t mode, fuse_file_info *fileinfo) {\n \/\/printf(\"create(%s, %d, _)\\n\", path.c_str(), mode);\n try {\n fileinfo->fh = _device->createAndOpenFile(path, mode);\n return 0;\n } catch (CryErrnoException &e) {\n return -e.getErrno();\n }\n}\n\n} \/* namespace cryfs *\/\n<commit_msg>Fix unimplemented utimens<commit_after>#include \"CryFuse.h\"\n\n#include <sys\/types.h>\n#include <sys\/time.h>\n#include <dirent.h>\n#include <cassert>\n\n#include \"cryfs_lib\/CryNode.h\"\n#include \"cryfs_lib\/CryErrnoException.h\"\n\n#define UNUSED(expr) (void)(expr)\n\nusing fusepp::path;\n\nnamespace cryfs {\n\nnamespace {\n int errcode_map(int exit_status) {\n if (exit_status < 0) {\n return -errno;\n }\n return exit_status;\n }\n}\n\nCryFuse::CryFuse(CryDevice *device)\n :_device(device) {\n}\n\nint CryFuse::getattr(const path &path, struct stat *stbuf) {\n try {\n _device->lstat(path, stbuf);\n return 0;\n } catch(cryfs::CryErrnoException &e) {\n return -e.getErrno();\n }\n}\n\nint CryFuse::fgetattr(const path &path, struct stat *stbuf, fuse_file_info *fileinfo) {\n \/\/printf(\"fgetattr(%s, _, _)\\n\", path.c_str());\n\n \/\/ On FreeBSD, trying to do anything with the mountpoint ends up\n \/\/ opening it, and then using the FD for an fgetattr. So in the\n \/\/ special case of a path of \"\/\", I need to do a getattr on the\n \/\/ underlying root directory instead of doing the fgetattr().\n \/\/ TODO Check if necessary\n if (path.native() == \"\/\") {\n return getattr(path, stbuf);\n }\n\n try {\n\t_device->fstat(fileinfo->fh, stbuf);\n\treturn 0;\n } catch(cryfs::CryErrnoException &e) {\n\t return -e.getErrno();\n }\n}\n\n\/\/TODO\nint CryFuse::readlink(const path &path, char *buf, size_t size) {\n \/\/printf(\"readlink(%s, _, %zu)\\n\", path.c_str(), size);\n auto real_path = _device->RootDir() \/ path;\n \/\/size-1, because the fuse readlink() function includes the null terminating byte in the buffer size,\n \/\/but the posix version does not and also doesn't append one.\n int real_size = ::readlink(real_path.c_str(), buf, size-1);\n if (real_size < 0) {\n return -errno;\n }\n \/\/Terminate the string\n buf[real_size] = '\\0';\n\n return 0;\n}\n\nint CryFuse::mknod(const path &path, mode_t mode, dev_t rdev) {\n UNUSED(rdev);\n UNUSED(mode);\n UNUSED(path);\n printf(\"Called non-implemented mknod(%s, %d, _)\\n\", path.c_str(), mode);\n return 0;\n}\n\nint CryFuse::mkdir(const path &path, mode_t mode) {\n \/\/printf(\"mkdir(%s, %d)\\n\", path.c_str(), mode);\n try {\n _device->mkdir(path, mode);\n return 0;\n } catch(cryfs::CryErrnoException &e) {\n return -e.getErrno();\n }\n}\n\nint CryFuse::unlink(const path &path) {\n \/\/printf(\"unlink(%s)\\n\", path.c_str());\n try {\n _device->unlink(path);\n return 0;\n } catch(cryfs::CryErrnoException &e) {\n return -e.getErrno();\n }\n}\n\nint CryFuse::rmdir(const path &path) {\n try {\n _device->rmdir(path);\n return 0;\n } catch(cryfs::CryErrnoException &e) {\n return -e.getErrno();\n }\n}\n\n\/\/TODO\nint CryFuse::symlink(const path &from, const path &to) {\n printf(\"NOT IMPLEMENTED: symlink(%s, %s)\\n\", from.c_str(), to.c_str());\n \/\/auto real_from = _device->RootDir() \/ from;\n \/\/auto real_to = _device->RootDir() \/ to;\n \/\/int retstat = ::symlink(real_from.c_str(), real_to.c_str());\n \/\/return errcode_map(retstat);\n return ENOSYS;\n}\n\nint CryFuse::rename(const path &from, const path &to) {\n \/\/printf(\"rename(%s, %s)\\n\", from.c_str(), to.c_str());\n try {\n _device->rename(from, to);\n return 0;\n } catch(cryfs::CryErrnoException &e) {\n return -e.getErrno();\n }\n}\n\n\/\/TODO\nint CryFuse::link(const path &from, const path &to) {\n printf(\"NOT IMPLEMENTED: link(%s, %s)\\n\", from.c_str(), to.c_str());\n \/\/auto real_from = _device->RootDir() \/ from;\n \/\/auto real_to = _device->RootDir() \/ to;\n \/\/int retstat = ::link(real_from.c_str(), real_to.c_str());\n \/\/return errcode_map(retstat);\n return ENOSYS;\n}\n\n\/\/TODO\nint CryFuse::chmod(const path &path, mode_t mode) {\n printf(\"NOT IMPLEMENTED: chmod(%s, %d)\\n\", path.c_str(), mode);\n \/\/auto real_path = _device->RootDir() \/ path;\n \/\/int retstat = ::chmod(real_path.c_str(), mode);\n \/\/return errcode_map(retstat);\n return ENOSYS;\n}\n\n\/\/TODO\nint CryFuse::chown(const path &path, uid_t uid, gid_t gid) {\n printf(\"NOT IMPLEMENTED: chown(%s, %d, %d)\\n\", path.c_str(), uid, gid);\n \/\/auto real_path = _device->RootDir() \/ path;\n \/\/int retstat = ::chown(real_path.c_str(), uid, gid);\n \/\/return errcode_map(retstat);\n return ENOSYS;\n}\n\nint CryFuse::truncate(const path &path, off_t size) {\n \/\/printf(\"truncate(%s, %zu)\\n\", path.c_str(), size);\n try {\n _device->truncate(path, size);\n return 0;\n } catch (CryErrnoException &e) {\n return -e.getErrno();\n }\n}\n\nint CryFuse::ftruncate(const path &path, off_t size, fuse_file_info *fileinfo) {\n \/\/printf(\"ftruncate(%s, %zu, _)\\n\", path.c_str(), size);\n\tUNUSED(path);\n try {\n _device->ftruncate(fileinfo->fh, size);\n return 0;\n } catch (CryErrnoException &e) {\n return -e.getErrno();\n }\n}\n\n\/\/TODO\nint CryFuse::utimens(const path &path, const timespec times[2]) {\n UNUSED(times);\n printf(\"NOT IMPLEMENTED: utimens(%s, _)\\n\", path.c_str());\n \/\/auto real_path = _device->RootDir() \/ path;\n \/\/struct timeval tv[2];\n \/\/tv[0].tv_sec = times[0].tv_sec;\n \/\/tv[0].tv_usec = times[0].tv_nsec \/ 1000;\n \/\/tv[1].tv_sec = times[1].tv_sec;\n \/\/tv[1].tv_usec = times[1].tv_nsec \/ 1000;\n \/\/int retstat = ::lutimes(real_path.c_str(), tv);\n \/\/return errcode_map(retstat);\n return 0;\n}\n\nint CryFuse::open(const path &path, fuse_file_info *fileinfo) {\n \/\/printf(\"open(%s, _)\\n\", path.c_str());\n try {\n\t fileinfo->fh = _device->openFile(path, fileinfo->flags);\n\t return 0;\n } catch (CryErrnoException &e) {\n\t return -e.getErrno();\n }\n}\n\nint CryFuse::release(const path &path, fuse_file_info *fileinfo) {\n \/\/printf(\"release(%s, _)\\n\", path.c_str());\n UNUSED(path);\n try {\n\t _device->closeFile(fileinfo->fh);\n\t return 0;\n } catch (CryErrnoException &e) {\n return -e.getErrno();\n }\n}\n\nint CryFuse::read(const path &path, char *buf, size_t size, off_t offset, fuse_file_info *fileinfo) {\n \/\/printf(\"read(%s, _, %zu, %zu, _)\\n\", path.c_str(), size, offset);\n UNUSED(path);\n try {\n \/\/printf(\"Reading from file %d\\n\", fileinfo->fh);\n \/\/fflush(stdout);\n return _device->read(fileinfo->fh, buf, size, offset);\n } catch (CryErrnoException &e) {\n return -e.getErrno();\n }\n}\n\nint CryFuse::write(const path &path, const char *buf, size_t size, off_t offset, fuse_file_info *fileinfo) {\n \/\/printf(\"write(%s, _, %zu, %zu, _)\\n\", path.c_str(), size, offset);\n UNUSED(path);\n try {\n _device->write(fileinfo->fh, buf, size, offset);\n return size;\n } catch (CryErrnoException &e) {\n return -e.getErrno();\n }\n}\n\n\/\/TODO\nint CryFuse::statfs(const path &path, struct statvfs *fsstat) {\n printf(\"HALF-IMPLEMENTED: statfs(%s, _)\\n\", path.c_str());\n auto real_path = _device->RootDir() \/ path;\n int retstat = ::statvfs(real_path.c_str(), fsstat);\n return errcode_map(retstat);\n}\n\n\/\/TODO\nint CryFuse::flush(const path &path, fuse_file_info *fileinfo) {\n \/\/printf(\"Called non-implemented flush(%s, _)\\n\", path.c_str());\n UNUSED(path);\n UNUSED(fileinfo);\n return 0;\n}\n\nint CryFuse::fsync(const path &path, int datasync, fuse_file_info *fileinfo) {\n \/\/printf(\"fsync(%s, %d, _)\\n\", path.c_str(), datasync);\n UNUSED(path);\n try {\n if (datasync) {\n _device->fdatasync(fileinfo->fh);\n } else {\n _device->fsync(fileinfo->fh);\n }\n return 0;\n } catch (CryErrnoException &e) {\n return -e.getErrno();\n }\n}\n\nint CryFuse::opendir(const path &path, fuse_file_info *fileinfo) {\n \/\/printf(\"opendir(%s, _)\\n\", path.c_str());\n try {\n fileinfo->fh = _device->openDir(path);\n return 0;\n } catch(CryErrnoException &e) {\n return -e.getErrno();\n }\n}\n\nint CryFuse::readdir(const path &path, void *buf, fuse_fill_dir_t filler, off_t offset, fuse_file_info *fileinfo) {\n UNUSED(path);\n \/\/printf(\"readdir(%s, _, _, %zu, _)\\n\", path.c_str(), offset);\n UNUSED(offset);\n try {\n auto entries = _device->readDir(fileinfo->fh);\n for (const auto &entry : *entries) {\n \/\/TODO Also give file attributes (third param of filler)\n if (filler(buf, entry.c_str(), nullptr, 0) != 0) {\n return -ENOMEM;\n }\n }\n return 0;\n } catch (CryErrnoException &e) {\n return -e.getErrno();\n }\n}\n\nint CryFuse::releasedir(const path &path, fuse_file_info *fileinfo) {\n \/\/printf(\"releasedir(%s, _)\\n\", path.c_str());\n UNUSED(path);\n try {\n _device->closeDir(fileinfo->fh);\n return 0;\n } catch (CryErrnoException &e) {\n return -e.getErrno();\n }\n}\n\n\/\/TODO\nint CryFuse::fsyncdir(const path &path, int datasync, fuse_file_info *fileinfo) {\n UNUSED(fileinfo);\n UNUSED(datasync);\n UNUSED(path);\n \/\/printf(\"Called non-implemented fsyncdir(%s, %d, _)\\n\", path.c_str(), datasync);\n return 0;\n}\n\nvoid CryFuse::init(fuse_conn_info *conn) {\n UNUSED(conn);\n \/\/printf(\"init()\\n\");\n}\n\nvoid CryFuse::destroy() {\n \/\/printf(\"destroy()\\n\");\n}\n\nint CryFuse::access(const path &path, int mask) {\n \/\/printf(\"access(%s, %d)\\n\", path.c_str(), mask);\n try {\n _device->access(path, mask);\n return 0;\n } catch (CryErrnoException &e) {\n return -e.getErrno();\n }\n}\n\nint CryFuse::create(const path &path, mode_t mode, fuse_file_info *fileinfo) {\n \/\/printf(\"create(%s, %d, _)\\n\", path.c_str(), mode);\n try {\n fileinfo->fh = _device->createAndOpenFile(path, mode);\n return 0;\n } catch (CryErrnoException &e) {\n return -e.getErrno();\n }\n}\n\n} \/* namespace cryfs *\/\n<|endoftext|>"} {"text":"<commit_before>\/* $Id: CreateCuts.C,v 1.5 2008\/01\/11 08:28:52 jgrosseo Exp $ *\/\n\n\/\/ this macro creates the track and event cuts used in this analysis\n\nAliESDtrackCuts* CreateTrackCuts(AliPWG0Helper::AnalysisMode analysisMode, Bool_t hists = kTRUE)\n{\n AliESDtrackCuts* esdTrackCuts = new AliESDtrackCuts(\"AliESDtrackCuts\");\n\n if (hists)\n esdTrackCuts->DefineHistograms(1);\n\n \/\/ default cuts for ITS+TPC\n Double_t cov1 = 2;\n Double_t cov2 = 2;\n Double_t cov3 = 0.5;\n Double_t cov4 = 0.5;\n Double_t cov5 = 2;\n Double_t nSigma = 4;\n\n Bool_t tpcRefit = kTRUE;\n Bool_t sigmaToVertex = kTRUE;\n\n TString tag(\"Global tracking\");\n\n \/\/ TPC-only cuts\n if (analysisMode & AliPWG0Helper::kTPC)\n {\n cov1 = 1e10;\n cov2 = 1e10;\n cov3 = 1e10;\n cov4 = 1e10;\n cov5 = 1e10;\n \n tpcRefit = kFALSE;\n sigmaToVertex = kFALSE;\n \n tag = \"TPC-only tracking\";\n }\n \n \/\/ cuts for data without field\n if (!(analysisMode & AliPWG0Helper::kFieldOn))\n {\n cov5 = 1e10;\n tag += \" without field\";\n }\n\n esdTrackCuts->SetMaxCovDiagonalElements(cov1, cov2, cov3, cov4, cov5);\n\n esdTrackCuts->SetRequireSigmaToVertex(sigmaToVertex);\n\n if (sigmaToVertex) {\n esdTrackCuts->SetMaxNsigmaToVertex(nSigma);\n }\n else\n {\n esdTrackCuts->SetMaxDCAToVertexZ(3.2);\n esdTrackCuts->SetMaxDCAToVertexXY(2.4);\n esdTrackCuts->SetDCAToVertex2D(kTRUE);\n }\n\n esdTrackCuts->SetRequireTPCRefit(tpcRefit);\n esdTrackCuts->SetAcceptKinkDaughters(kFALSE);\n\n esdTrackCuts->SetMinNClustersTPC(50);\n esdTrackCuts->SetMaxChi2PerClusterTPC(4);\n\n Printf(\"Created track cuts for: %s\", tag.Data());\n\n return esdTrackCuts;\n}\n\n<commit_msg>updated TPC cuts<commit_after>\/* $Id: CreateCuts.C,v 1.5 2008\/01\/11 08:28:52 jgrosseo Exp $ *\/\n\n\/\/ this macro creates the track cuts used in this analysis\n\nAliESDtrackCuts* CreateTrackCuts(AliPWG0Helper::AnalysisMode analysisMode, Bool_t hists = kTRUE)\n{\n AliESDtrackCuts* esdTrackCuts = 0;\n \n \/\/ see https:\/\/twiki.cern.ch\/twiki\/bin\/view\/ALICE\/SelectionOfPrimaryTracksForPp2009DataAnalysis\n \n if (analysisMode & AliPWG0Helper::kTPC)\n {\n esdTrackCuts = new AliESDtrackCuts(\"AliESDtrackCuts\");\n\n TString tag(\"TPC-only tracking\");\n\n esdTrackCuts->SetMaxDCAToVertexZ(3.2);\n esdTrackCuts->SetMaxDCAToVertexXY(2.4);\n esdTrackCuts->SetDCAToVertex2D(kTRUE);\n \n esdTrackCuts->SetRequireTPCRefit(kTRUE);\n esdTrackCuts->SetAcceptKinkDaughters(kFALSE);\n esdTrackCuts->SetMinNClustersTPC(70);\n esdTrackCuts->SetMaxChi2PerClusterTPC(4);\n }\n\n if (analysisMode & AliPWG0Helper::kTPCITS)\n {\n esdTrackCuts = AliESDtrackCuts::GetStandardITSTPCTrackCuts2009(kTRUE);\n \n TString tag(\"Global tracking\");\n }\n\n if (hists)\n esdTrackCuts->DefineHistograms(1);\n\n \/\/ cuts for data without field\n if (!(analysisMode & AliPWG0Helper::kFieldOn))\n {\n tag += \" without field\";\n }\n\n Printf(\"Created track cuts for: %s\", tag.Data());\n\n return esdTrackCuts;\n}\n\n<|endoftext|>"} {"text":"<commit_before>#pragma once\n\n\/* Voxel test with procedural data. *\/\n\n#include \"material.hpp\"\n\n#include \"math\/vector3.hpp\"\n#include <cmath>\n\n#include <cstdint>\n\n#include <cstddef>\n\n#include <algorithm>\n\n#include \"contact.hpp\"\n\n#include \"geometry\/voxel_types.hpp\"\n\n#include \"geometry\/fast_stack.hpp\"\n\n#include \"geometry\/aabb.hpp\"\n\n\/\/ the encoding currently used for voxels imposes a maximum of 2 billion nodes\n\/\/ but it may make sense to use uint64_t and use the extra 32 bits in the leaf\n\/\/ nodes for fast-changing material properties (or other)\n\/\/ (we'd need to know how many voxels constitute a typical world with LOD, and\n\/\/ see if double the memory usage is worth a richer & faster material system)\n\nstruct Node\n{\n uint32_t child[8];\n};\n\nuint32_t encode_leaf(const uint16_t &normal, const uint16_t &material)\n{\n return (((material & 0x7FFF) << 16) | normal) | 0x80000000;\n}\n\n\/\/ assumes the high bit marker has already been removed\nvoid decode_leaf(const uint32_t &leaf, uint16_t &normal, uint16_t &material)\n{\n material = leaf >> 16;\n normal = leaf & 0xFFFF;\n}\n\n#define svo_depth 9 \/\/ TEMPORARY (will not be hardcoded later)\n\n#define STACK_SIZE (4 * svo_depth) \/\/ can probably bring this down with some mathematical analysis of worst-case SVO traversal\n \/\/ (until we figure out how stackless traversal works, anyway)\n \/\/ (it doesn't really matter on the CPU due to how the stack works, but will be a killer on\n \/\/ the GPU as it will increase register pressure and kill parallelism ---> need stackless)\n\nstatic distance3 light_pos = distance3(0.2f, -0.35f, 0.3f);\n\nclass VoxelTest\n{\npublic:\n distance3 light() const\n {\n return light_pos;\n }\n \n bool intersects(const distance3 &origin, const distance3 &direction,\n\t\t distance &dist, Contact &contact) const\n\t{\n return traverse(origin, direction,\n std::numeric_limits<distance>::infinity(), dist, contact, false);\n\t}\n\n bool occludes(const distance3 &origin, const distance3 &direction,\n distance &dist, distance target_dist) const\n {\n Contact contact;\n \n return traverse(origin, direction,\n target_dist, dist, contact, true);\n }\n\n bool occludes(const distance3 &origin, const distance3 &direction,\n distance target_dist) const\n {\n distance dist;\n Contact contact;\n\n return traverse(origin, direction,\n target_dist, dist, contact, true);\n }\n \n bool occludes(const distance3 &origin, const distance3 &direction) const\n {\n return occludes(origin, direction, std::numeric_limits<distance>::infinity());\n }\n\t\n\tVoxelTest()\n\t{\n\t printf(\"Building SVO (this is done only once).\\n\");\n\t init_mem();\n\t root = build_SVO(svo_depth, world);\n\t printf(\"SVO built (%zu nodes, depth = %d).\\n\",\n\t node_offset, svo_depth);\n\t}\n\t\nprivate:\n const aabb world = aabb{distance3(-1, -1, -1), distance3(1, 1, 1)};\n\n \/\/ looks up a voxel through its memory address (this could be an offset later on\n \/\/ for virtualization) and fills in an appropriate Contact structure to indicate\n \/\/ the material and surface normal, when applicable\n \n \/\/ this function has some pretty strong invariants to maintain, pay attention.\n \/\/ (read: if the invariants are not maintained, traversal will FAIL horribly)\n \n \/\/ (procedural data generation can happen here as well)\n inline\n bool lookup(const distance3 &origin, const distance3 &direction,\n const stack_item &leaf, distance &nearest,\n Contact &contact) const\n {\n \/\/ default implementation, voxels are cubic and solid\n \n (void)origin;\n (void)direction;\n \n decode_leaf(leaf.offset, contact.normal, contact.material);\n \n nearest = leaf.hit; \/\/ IMPORTANT: you must set \"nearest\" to the\n \/\/ nearest intersection within the voxel's bounding box, IF AND\n \/\/ ONLY IF this intersection is closer than the currently recorded\n \/\/ \"nearest\" value (and if this is the case, populate \"contact\",\n \/\/ else LEAVE IT ALONE).\n\n return true; \/\/ return if and only if \"nearest\" was modified\n } __attribute__ ((hot))\n\n \/\/ this is the heart of the voxel renderer, the SVO traversal code\n \/\/ this is where optimization efforts should be focused\n \/\/ current optimizations and todo's:\n \/\/ DONE: convert to iteration and use a stack\n \/\/ TODO: implement and benchmark stackless traversal algorithms\n \/\/ DONE: uses early rejection by sorting children\n \/\/ DONE: fix remaining bugs\n\n \/\/ CURRENT REASONS FOR BEING SLOW:\n \/\/ 1. no SSE vector instructions [WIP]\n \/\/ 2. unnecessary ray_aabb call in leaf [fixed]\n \/\/ 3. recursion [fixed]\n \/\/ 4. \"intersections\" buffer not optimized [fixed]\n \/\/ 5. tree nodes allocated via malloc(), poor locality [fixed]\n \/\/ 6. ray_aabb is not optimized at all [fixed]\n \/\/ 7. possible algorithmic improvements?\n\n \/\/ QUESTIONS TO RESOLVE:\n \/\/ 1. do we need \"far\" in the \"intersections\" buffer? [NO]\n \/\/ 2. are there any bugs? need a known voxel data set to test against\n \/\/ (do that once we have interactivity, to better locate glitches)\n\n \/\/ ADDITIONAL INFO:\n \/\/ - final tree will potentially be very deep, with up to 64 levels\n \/\/ (32 levels --> 64km^3 with 0.015 mm resolution)\n \/\/ - procedural data generation can be done outside the tree, once\n \/\/ a voxel is intersected, by generating procedural data *inside*\n \/\/ the intersected voxel, depending on its material\n \/\/ (this is actually a REALLY GOOD idea as it completely gets rid\n \/\/ of any cubic artifacts and improves subpixel performance)\n \/\/ - 64 levels --> 1800 AU^3 with 0.015 mm resolution\n \/\/ (that's 274 billion km^3, I trust this will be enough)\n \/\/ - possibly use a hybrid approach, with two trees, one handling large\n \/\/ 64km^3 \"chunks\", optimized for ultra fast traversal, and another\n \/\/ which focuses on culling chunks to improve performance\n bool traverse(const distance3 &origin, const distance3 &direction,\n const distance &range, distance &nearest,\n Contact &contact, const bool occlusion) const\n {\n traversal_stack<STACK_SIZE> stack(root, world);\n const distance3 &invdir = 1 \/ direction;\n\n bool hit = false;\n nearest = range;\n\n while (!stack.empty())\n {\n auto s = stack.pop();\n if (s.hit < nearest)\n {\n if (s.offset & 0x80000000)\n {\n s.offset ^= 0x80000000; \/* Decode this leaf offset. *\/\n hit |= lookup(origin, direction, s, nearest, contact);\n if (occlusion && hit) return true; \/* Voxel is hit. *\/\n }\n else\n {\n size_t last = stack.position();\n auto current = nodes[s.offset];\n for (size_t t = 0; t < 8; ++t)\n {\n uint32_t child = current.child[t];\n if (child == 0x00000000) continue;\n auto node = s.subdivide(child, t);\n \n if (intersect(origin, invdir, node.cube, node.hit))\n if (node.hit < nearest) stack.push(node);\n }\n \n \/* Push back to front. *\/\n stack.special_sort(last);\n }\n }\n }\n\n return hit;\n\t} __attribute__ ((hot))\n\n \/\/ this will be done in a separate program later on (SVO's will be\n \/\/ loaded on the fly, no time to build them while streaming voxels)\n uint32_t build_SVO(int depth, const aabb &cube)\n {\n if (depth == 0)\n {\n \/\/ this is a leaf - add voxel\n \n uint16_t normal, material;\n get_voxel_data(cube, normal, material);\n \n \/\/ encode leaf data into 32-bit offset\n return encode_leaf(normal, material);\n }\n \n Node *node = alloc_node();\n \n \/\/ build children here\n for (int t = 0; t < 8; ++t)\n {\n aabb child = split_node(cube, t);\n \n if (!contains_voxels(child)) node->child[t] = 0;\n else node->child[t] = build_SVO(depth - 1, child);\n }\n \n return (uint32_t)(node - nodes);\n }\n \n float heightmap(distance x, distance z) const \/\/ TEMPORARY\n {\n \/\/return 0.05f * (sin(x) + cos(z)) - 0.7f;\n \n if ((x <= -0.525f) || (x >= 0.6f)) return std::numeric_limits<distance>::infinity();\n if ((z <= 0.2f)) return std::numeric_limits<distance>::infinity();\n \n \n return -0.7f + 0.03f * (sin(15 * z) + sin(10 * x + 1));\n \n \/\/return -2.0f\/3.0f + 0.2f * x * x;\n }\n \n math::float3 get_normal(distance x, distance z) const \/\/ TEMPORARY\n {\n distance dx = 0.2 * cos(10 * x + 1);\n distance dz = 0.3 * cos(15 * z);\n\n \/\/distance dx = 0.4f * x;\n \/\/distance dz = 0;\n \n return normalize(distance3(dx, 1, dz));\n }\n \n bool contains_voxels(const aabb &node) const \/\/ TEMPORARY\n {\n int r = 10;\n \n for (int px = 0; px < r; ++px)\n for (int pz = 0; pz < r; ++pz)\n {\n distance x = node.min.x + (node.max.x - node.min.x) * (distance)px \/ r;\n distance z = node.min.z + (node.max.z - node.min.z) * (distance)pz \/ r;\n \n distance height = heightmap(x, z);\n \n if ((node.min.y <= height) && (height <= node.max.y)) return true;\n }\n \n return false;\n }\n \n void get_voxel_data(const aabb &node, uint16_t &normal, uint16_t &material) const\n \/\/ TEMPORARY\n {\n int r = 10;\n \n for (int px = 0; px < r; ++px)\n for (int pz = 0; pz < r; ++pz)\n {\n distance x = node.min.x + (node.max.x - node.min.x) * (distance)px \/ r;\n distance z = node.min.z + (node.max.z - node.min.z) * (distance)pz \/ r;\n \n distance height = heightmap(x, z);\n \n if ((node.min.y <= height) && (height <= node.max.y))\n {\n normal = encode_normal(get_normal(x, z));\n material = 0;\n \n return;\n }\n }\n }\n \n \/\/ pray your libc overcommits :)\n #define NODE_MEMORY (1024 * 1024 * 1024)\n \n Node *nodes;\n size_t node_offset;\n \n void init_mem()\n {\n nodes = (Node*)malloc(NODE_MEMORY);\n node_offset = 0;\n }\n \n Node *alloc_node()\n {\n Node *ptr = nodes + node_offset;\n node_offset++;\n return ptr;\n }\n \n uint32_t root;\n};\n<commit_msg>Added 3D array -> SVO construction code (ugly and slow).<commit_after>#pragma once\n\n\/* Voxel test with procedural data. *\/\n\n#include \"material.hpp\"\n\n#include \"math\/vector3.hpp\"\n#include <cmath>\n\n#include <cstdint>\n\n#include <cstddef>\n\n#include <algorithm>\n\n#include \"contact.hpp\"\n\n#include \"geometry\/voxel_types.hpp\"\n\n#include \"geometry\/fast_stack.hpp\"\n\n#include \"geometry\/aabb.hpp\"\n\n\/\/ the encoding currently used for voxels imposes a maximum of 2 billion nodes\n\/\/ but it may make sense to use uint64_t and use the extra 32 bits in the leaf\n\/\/ nodes for fast-changing material properties (or other)\n\/\/ (we'd need to know how many voxels constitute a typical world with LOD, and\n\/\/ see if double the memory usage is worth a richer & faster material system)\n\nstatic const math::basic_vector3<int> offset_int[8] =\n {\n math::basic_vector3<int>(0, 0, 0),\n math::basic_vector3<int>(0, 0, 1),\n math::basic_vector3<int>(0, 1, 0),\n math::basic_vector3<int>(0, 1, 1),\n math::basic_vector3<int>(1, 0, 0),\n math::basic_vector3<int>(1, 0, 1),\n math::basic_vector3<int>(1, 1, 0),\n math::basic_vector3<int>(1, 1, 1),\n };\n\nstruct Voxel \/\/ for building only\n{\n uint16_t material;\n uint16_t normal;\n};\n\nstruct Node\n{\n uint32_t child[8];\n};\n\nuint32_t encode_leaf(const uint16_t &normal, const uint16_t &material)\n{\n return (((material & 0x7FFF) << 16) | normal) | 0x80000000;\n}\n\n\/\/ assumes the high bit marker has already been removed\nvoid decode_leaf(const uint32_t &leaf, uint16_t &normal, uint16_t &material)\n{\n material = leaf >> 16;\n normal = leaf & 0xFFFF;\n}\n\n#define RESOLUTION 256\n\n#define svo_depth 7 \/\/ TEMPORARY (will not be hardcoded later)\n\n#define STACK_SIZE (4 * svo_depth) \/\/ can probably bring this down with some mathematical analysis of worst-case SVO traversal\n \/\/ (until we figure out how stackless traversal works, anyway)\n \/\/ (it doesn't really matter on the CPU due to how the stack works, but will be a killer on\n \/\/ the GPU as it will increase register pressure and kill parallelism ---> need stackless)\n\nstatic distance3 light_pos = distance3(0.2f, -0.35f, 0.3f);\n\nclass VoxelTest\n{\npublic:\n distance3 light() const\n {\n return light_pos;\n }\n \n bool intersects(const distance3 &origin, const distance3 &direction,\n\t\t distance &dist, Contact &contact) const\n\t{\n return traverse(origin, direction,\n std::numeric_limits<distance>::infinity(), dist, contact, false);\n\t}\n\n bool occludes(const distance3 &origin, const distance3 &direction,\n distance &dist, distance target_dist) const\n {\n Contact contact;\n \n return traverse(origin, direction,\n target_dist, dist, contact, true);\n }\n\n bool occludes(const distance3 &origin, const distance3 &direction,\n distance target_dist) const\n {\n distance dist;\n Contact contact;\n\n return traverse(origin, direction,\n target_dist, dist, contact, true);\n }\n \n bool occludes(const distance3 &origin, const distance3 &direction) const\n {\n return occludes(origin, direction, std::numeric_limits<distance>::infinity());\n }\n\t\n\tVoxelTest()\n\t{\n\t printf(\"Building SVO (this is done only once).\\n\");\n\t init_mem();\n\t root = build_SVO(svo_depth, world, math::basic_vector3<int>(0, 0, 0), math::basic_vector3<int>(RESOLUTION - 1, RESOLUTION - 1, RESOLUTION - 1));\n\t printf(\"SVO built (%zu nodes, depth = %d).\\n\",\n\t node_offset, svo_depth);\n\t free_mem();\n\t}\n\t\nprivate:\n const aabb world = aabb{distance3(-1, -1, -1), distance3(1, 1, 1)};\n\n \/\/ looks up a voxel through its memory address (this could be an offset later on\n \/\/ for virtualization) and fills in an appropriate Contact structure to indicate\n \/\/ the material and surface normal, when applicable\n \n \/\/ this function has some pretty strong invariants to maintain, pay attention.\n \/\/ (read: if the invariants are not maintained, traversal will FAIL horribly)\n \n \/\/ (procedural data generation can happen here as well)\n inline\n bool lookup(const distance3 &origin, const distance3 &direction,\n const stack_item &leaf, distance &nearest,\n Contact &contact) const\n {\n \/\/ default implementation, voxels are cubic and solid\n \n (void)origin;\n (void)direction;\n \n decode_leaf(leaf.offset, contact.normal, contact.material);\n \n nearest = leaf.hit; \/\/ IMPORTANT: you must set \"nearest\" to the\n \/\/ nearest intersection within the voxel's bounding box, IF AND\n \/\/ ONLY IF this intersection is closer than the currently recorded\n \/\/ \"nearest\" value (and if this is the case, populate \"contact\",\n \/\/ else LEAVE IT ALONE).\n\n return true; \/\/ return if and only if \"nearest\" was modified\n } __attribute__ ((hot))\n\n \/\/ this is the heart of the voxel renderer, the SVO traversal code\n \/\/ this is where optimization efforts should be focused\n \/\/ current optimizations and todo's:\n \/\/ DONE: convert to iteration and use a stack\n \/\/ TODO: implement and benchmark stackless traversal algorithms\n \/\/ DONE: uses early rejection by sorting children\n \/\/ DONE: fix remaining bugs\n\n \/\/ CURRENT REASONS FOR BEING SLOW:\n \/\/ 1. no SSE vector instructions [WIP]\n \/\/ 2. unnecessary ray_aabb call in leaf [fixed]\n \/\/ 3. recursion [fixed]\n \/\/ 4. \"intersections\" buffer not optimized [fixed]\n \/\/ 5. tree nodes allocated via malloc(), poor locality [fixed]\n \/\/ 6. ray_aabb is not optimized at all [fixed]\n \/\/ 7. possible algorithmic improvements?\n\n \/\/ QUESTIONS TO RESOLVE:\n \/\/ 1. do we need \"far\" in the \"intersections\" buffer? [NO]\n \/\/ 2. are there any bugs? need a known voxel data set to test against\n \/\/ (do that once we have interactivity, to better locate glitches)\n\n \/\/ ADDITIONAL INFO:\n \/\/ - final tree will potentially be very deep, with up to 64 levels\n \/\/ (32 levels --> 64km^3 with 0.015 mm resolution)\n \/\/ - procedural data generation can be done outside the tree, once\n \/\/ a voxel is intersected, by generating procedural data *inside*\n \/\/ the intersected voxel, depending on its material\n \/\/ (this is actually a REALLY GOOD idea as it completely gets rid\n \/\/ of any cubic artifacts and improves subpixel performance)\n \/\/ - 64 levels --> 1800 AU^3 with 0.015 mm resolution\n \/\/ (that's 274 billion km^3, I trust this will be enough)\n \/\/ - possibly use a hybrid approach, with two trees, one handling large\n \/\/ 64km^3 \"chunks\", optimized for ultra fast traversal, and another\n \/\/ which focuses on culling chunks to improve performance\n bool traverse(const distance3 &origin, const distance3 &direction,\n const distance &range, distance &nearest,\n Contact &contact, const bool occlusion) const\n {\n traversal_stack<STACK_SIZE> stack(root, world);\n const distance3 &invdir = 1 \/ direction;\n\n bool hit = false;\n nearest = range;\n\n while (!stack.empty())\n {\n auto s = stack.pop();\n if (s.hit < nearest)\n {\n if (s.offset & 0x80000000)\n {\n s.offset ^= 0x80000000; \/* Decode this leaf offset. *\/\n hit |= lookup(origin, direction, s, nearest, contact);\n if (occlusion && hit) return true; \/* Voxel is hit. *\/\n }\n else\n {\n size_t last = stack.position();\n auto current = nodes[s.offset];\n for (size_t t = 0; t < 8; ++t)\n {\n uint32_t child = current.child[t];\n if (child == 0x00000000) continue;\n auto node = s.subdivide(child, t);\n \n if (intersect(origin, invdir, node.cube, node.hit))\n if (node.hit < nearest) stack.push(node);\n }\n \n \/* Push back to front. *\/\n stack.special_sort(last);\n }\n }\n }\n\n return hit;\n\t} __attribute__ ((hot))\n\t\n\tvoid split_int(const math::basic_vector3<int> &min, const math::basic_vector3<int> &max, int t,\n\t math::basic_vector3<int> &child_min, math::basic_vector3<int> &child_max)\n\t{\n\t math::basic_vector3<int> extent = (max - min) \/ 2;\n math::basic_vector3<int> p = min + extent * offset_int[t];\n child_min = p;\n child_max = p + extent;\n\t}\n\n \/\/ this will be done in a separate program later on (SVO's will be\n \/\/ loaded on the fly, no time to build them while streaming voxels)\n uint32_t build_SVO(int depth, const aabb &cube, const math::basic_vector3<int> &min, const math::basic_vector3<int> &max)\n {\n if (depth == 0)\n {\n \/\/ this is a leaf - add voxel\n \n uint16_t normal, material;\n get_voxel_data(min, max, normal, material);\n \n \/\/ encode leaf data into 32-bit offset\n return encode_leaf(normal, material);\n }\n \n Node *node = alloc_node();\n \n \/\/ build children here\n for (int t = 0; t < 8; ++t)\n {\n aabb child = split_node(cube, t);\n \n math::basic_vector3<int> child_min, child_max;\n split_int(min, max, t, child_min, child_max);\n \n if (!contains_voxels(child_min, child_max)) node->child[t] = 0;\n else node->child[t] = build_SVO(depth - 1, child, child_min, child_max);\n }\n \n return (uint32_t)(node - nodes);\n }\n \n float heightmap(distance x, distance z) const \/\/ TEMPORARY\n {\n \/\/return 0.05f * (sin(x) + cos(z)) - 0.7f;\n \n \/\/if ((x <= -0.525f) || (x >= 0.6f)) return std::numeric_limits<distance>::infinity();\n \/\/if ((z <= 0.2f)) return std::numeric_limits<distance>::infinity();\n \n \n return -0.7f + 0.03f * (sin(15 * z) + sin(10 * x + 1));\n \n \/\/return -2.0f\/3.0f + 0.2f * x * x;\n }\n \n math::float3 get_normal(distance x, distance z) const \/\/ TEMPORARY\n {\n distance dx = 0.2 * cos(10 * x + 1);\n distance dz = 0.3 * cos(15 * z);\n\n \/\/distance dx = 0.4f * x;\n \/\/distance dz = 0;\n \n return normalize(distance3(dx, 1, dz));\n }\n \n bool contains_voxels(const math::basic_vector3<int> &min, const math::basic_vector3<int> &max) const \/\/ TEMPORARY\n {\n \/*int r = 10;\n \n for (int px = 0; px < r; ++px)\n for (int pz = 0; pz < r; ++pz)\n {\n distance x = node.min.x + (node.max.x - node.min.x) * (distance)px \/ r;\n distance z = node.min.z + (node.max.z - node.min.z) * (distance)pz \/ r;\n \n distance height = heightmap(x, z);\n \n if ((node.min.y <= height) && (height <= node.max.y)) return true;\n }\n \n return false;*\/\n \n for (int x = min.x; x < max.x; ++x)\n for (int y = min.y; y < max.y; ++y)\n for (int z = min.z; z < max.z; ++z)\n if (data[x][y][z].material != 0xFFFF) return true;\n \n return false;\n }\n \n void get_voxel_data(const math::basic_vector3<int> &min, const math::basic_vector3<int> &max, uint16_t &normal, uint16_t &material) const\n \/\/ TEMPORARY\n {\n \/*int r = 10;\n \n for (int px = 0; px < r; ++px)\n for (int pz = 0; pz < r; ++pz)\n {\n distance x = node.min.x + (node.max.x - node.min.x) * (distance)px \/ r;\n distance z = node.min.z + (node.max.z - node.min.z) * (distance)pz \/ r;\n \n distance height = heightmap(x, z);\n \n if ((node.min.y <= height) && (height <= node.max.y))\n {\n normal = encode_normal(get_normal(x, z));\n material = 0;\n \n return;\n }\n }*\/\n \n int x = min.x;\n int y = min.y;\n int z = min.z;\n \n normal = data[x][y][z].normal;\n material = data[x][y][z].material;\n }\n \n Voxel ***data;\n \n void alloc_data()\n {\n data = new Voxel**[RESOLUTION];\n \n for (int x = 0; x < RESOLUTION; ++x)\n {\n data[x] = new Voxel*[RESOLUTION];\n \n for (int y = 0; y < RESOLUTION; ++y)\n {\n data[x][y] = new Voxel[RESOLUTION];\n }\n }\n }\n \n void free_mem()\n {\n for (int x = 0; x < RESOLUTION; ++x)\n for (int y = 0; y < RESOLUTION; ++y)\n delete[] data[x][y];\n \n for (int x = 0; x < RESOLUTION; ++x)\n delete[] data[x];\n \n delete[] data;\n }\n \n void clear_data()\n {\n for (int x = 0; x < RESOLUTION; ++x)\n for (int y = 0; y < RESOLUTION; ++y)\n for (int z = 0; z < RESOLUTION; ++z)\n data[x][y][z].material = 0xFFFF;\n }\n \n void filter_data()\n {\n for (int x = 1; x < RESOLUTION - 1; ++x)\n for (int y = 1; y < RESOLUTION - 1; ++y)\n for (int z = 1; z < RESOLUTION - 1; ++z)\n {\n if ((data[x - 1][y][z].material != 0xFFFF)\n && (data[x + 1][y][z].material != 0xFFFF)\n && (data[x][y - 1][z].material != 0xFFFF)\n && (data[x][y + 1][z].material != 0xFFFF)\n && (data[x][y][z - 1].material != 0xFFFF)\n && (data[x][y][z + 1].material != 0xFFFF))\n {\n data[x][y][z].material = 0xFFFF;\n }\n }\n }\n \n void gen_data()\n {\n for (int x = 0; x < RESOLUTION; ++x)\n for (int y = 0; y < RESOLUTION; ++y)\n for (int z = 0; z < RESOLUTION; ++z)\n {\n float px = ((float)x \/ RESOLUTION - 0.5f) * 2;\n float py = ((float)y \/ RESOLUTION - 0.5f) * 2;\n float pz = ((float)z \/ RESOLUTION - 0.5f) * 2;\n \n if (py <= heightmap(px, pz))\n {\n data[x][y][z].material = 0;\n \n data[x][y][z].normal = encode_normal(get_normal(px, pz));\n }\n }\n }\n \n void load_model()\n {\n alloc_data();\n \n clear_data();\n \n gen_data();\n \n filter_data();\n }\n \n \/\/ pray your libc overcommits :)\n #define NODE_MEMORY (1024 * 1024 * 1024)\n \n Node *nodes;\n size_t node_offset;\n \n void init_mem()\n {\n nodes = (Node*)malloc(NODE_MEMORY);\n node_offset = 0;\n load_model();\n }\n \n Node *alloc_node()\n {\n Node *ptr = nodes + node_offset;\n node_offset++;\n return ptr;\n }\n \n uint32_t root;\n};\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ Copyright (C) Pixar. All rights reserved.\n\/\/\n\/\/ This license governs use of the accompanying software. If you\n\/\/ use the software, you accept this license. If you do not accept\n\/\/ the license, do not use the software.\n\/\/\n\/\/ 1. Definitions\n\/\/ The terms \"reproduce,\" \"reproduction,\" \"derivative works,\" and\n\/\/ \"distribution\" have the same meaning here as under U.S.\n\/\/ copyright law. A \"contribution\" is the original software, or\n\/\/ any additions or changes to the software.\n\/\/ A \"contributor\" is any person or entity that distributes its\n\/\/ contribution under this license.\n\/\/ \"Licensed patents\" are a contributor's patent claims that read\n\/\/ directly on its contribution.\n\/\/\n\/\/ 2. Grant of Rights\n\/\/ (A) Copyright Grant- Subject to the terms of this license,\n\/\/ including the license conditions and limitations in section 3,\n\/\/ each contributor grants you a non-exclusive, worldwide,\n\/\/ royalty-free copyright license to reproduce its contribution,\n\/\/ prepare derivative works of its contribution, and distribute\n\/\/ its contribution or any derivative works that you create.\n\/\/ (B) Patent Grant- Subject to the terms of this license,\n\/\/ including the license conditions and limitations in section 3,\n\/\/ each contributor grants you a non-exclusive, worldwide,\n\/\/ royalty-free license under its licensed patents to make, have\n\/\/ made, use, sell, offer for sale, import, and\/or otherwise\n\/\/ dispose of its contribution in the software or derivative works\n\/\/ of the contribution in the software.\n\/\/\n\/\/ 3. Conditions and Limitations\n\/\/ (A) No Trademark License- This license does not grant you\n\/\/ rights to use any contributor's name, logo, or trademarks.\n\/\/ (B) If you bring a patent claim against any contributor over\n\/\/ patents that you claim are infringed by the software, your\n\/\/ patent license from such contributor to the software ends\n\/\/ automatically.\n\/\/ (C) If you distribute any portion of the software, you must\n\/\/ retain all copyright, patent, trademark, and attribution\n\/\/ notices that are present in the software.\n\/\/ (D) If you distribute any portion of the software in source\n\/\/ code form, you may do so only under this license by including a\n\/\/ complete copy of this license with your distribution. If you\n\/\/ distribute any portion of the software in compiled or object\n\/\/ code form, you may only do so under a license that complies\n\/\/ with this license.\n\/\/ (E) The software is licensed \"as-is.\" You bear the risk of\n\/\/ using it. The contributors give no express warranties,\n\/\/ guarantees or conditions. You may have additional consumer\n\/\/ rights under your local laws which this license cannot change.\n\/\/ To the extent permitted under your local laws, the contributors\n\/\/ exclude the implied warranties of merchantability, fitness for\n\/\/ a particular purpose and non-infringement.\n\/\/\n\n#include \"..\/osd\/gcdKernel.h\"\n#include \"..\/osd\/cpuKernel.h\"\n#include \"..\/osd\/vertexDescriptor.h\"\n\n#include <math.h>\n\nnamespace OpenSubdiv {\nnamespace OPENSUBDIV_VERSION {\n\nconst int GCD_WORK_STRIDE = 32;\n\n\nvoid OsdGcdComputeFace(\n const OsdVertexDescriptor *vdesc, float * vertex, float * varying,\n const int *F_IT, const int *F_ITa, int offset, int start, int end,\n dispatch_queue_t gcdq) {\n\n dispatch_apply(end-start, gcdq, ^(size_t blockIdx){\n int i = start+blockIdx;\n int h = F_ITa[2*i];\n int n = F_ITa[2*i+1];\n\n float weight = 1.0f\/n;\n\n \/\/ XXX: should use local vertex struct variable instead of\n \/\/ accumulating directly into global memory.\n int dstIndex = offset + i;\n vdesc->Clear(vertex, varying, dstIndex);\n\n for (int j = 0; j < n; ++j) {\n int index = F_IT[h+j];\n vdesc->AddWithWeight(vertex, dstIndex, index, weight);\n vdesc->AddVaryingWithWeight(varying, dstIndex, index, weight);\n }\n });\n}\n\nvoid OsdGcdComputeEdge(\n const OsdVertexDescriptor *vdesc, float *vertex, float *varying,\n const int *E_IT, const float *E_W, int offset, int start, int end,\n dispatch_queue_t gcdq) {\n\n const int workSize = end-start;\n dispatch_apply(workSize\/GCD_WORK_STRIDE, gcdq, ^(size_t blockIdx){\n const int start_i = start + blockIdx*GCD_WORK_STRIDE;\n const int end_i = start_i + GCD_WORK_STRIDE;\n OsdCpuComputeEdge(vdesc, vertex, varying, E_IT, E_W, offset,\n start_i, end_i);\n });\n const int start_e = end - workSize%GCD_WORK_STRIDE;\n const int end_e = end;\n if (start_e < end_e)\n OsdCpuComputeEdge(vdesc, vertex, varying, E_IT, E_W, offset,\n start_e, end_e);\n}\n\nvoid OsdGcdComputeVertexA(\n const OsdVertexDescriptor *vdesc, float *vertex, float *varying,\n const int *V_ITa, const float *V_W,\n int offset, int start, int end, int pass,\n dispatch_queue_t gcdq) {\n\n const int workSize = end-start;\n dispatch_apply(workSize\/GCD_WORK_STRIDE, gcdq, ^(size_t blockIdx){\n const int start_i = start + blockIdx*GCD_WORK_STRIDE;\n const int end_i = start_i + GCD_WORK_STRIDE;\n OsdCpuComputeVertexA(vdesc, vertex, varying, V_ITa, V_W, offset,\n start_i, end_i, pass);\n });\n const int start_e = end - workSize%GCD_WORK_STRIDE;\n const int end_e = end;\n if (start_e < end_e)\n OsdCpuComputeVertexA(vdesc, vertex, varying, V_ITa, V_W, offset,\n start_e, end_e, pass);\n}\n\nvoid OsdGcdComputeVertexB(\n const OsdVertexDescriptor *vdesc, float *vertex, float *varying,\n const int *V_ITa, const int *V_IT, const float *V_W,\n int offset, int start, int end,\n dispatch_queue_t gcdq) {\n\n const int workSize = end-start;\n dispatch_apply(workSize\/GCD_WORK_STRIDE, gcdq, ^(size_t blockIdx){\n const int start_i = start + blockIdx*GCD_WORK_STRIDE;\n const int end_i = start_i + GCD_WORK_STRIDE;\n OsdCpuComputeVertexB(vdesc, vertex, varying, V_ITa, V_IT, V_W, offset,\n start_i, end_i);\n });\n const int start_e = end - workSize%GCD_WORK_STRIDE;\n const int end_e = end;\n if (start_e < end_e)\n OsdCpuComputeVertexB(vdesc, vertex, varying, V_ITa, V_IT, V_W, offset,\n start_e, end_e);\n}\n\nvoid OsdGcdComputeLoopVertexB(\n const OsdVertexDescriptor *vdesc, float *vertex, float *varying,\n const int *V_ITa, const int *V_IT, const float *V_W,\n int offset, int start, int end,\n dispatch_queue_t gcdq) {\n\n dispatch_apply(end-start, gcdq, ^(size_t blockIdx){\n int i = start+blockIdx;\n int h = V_ITa[5*i];\n int n = V_ITa[5*i+1];\n int p = V_ITa[5*i+2];\n\n float weight = V_W[i];\n float wp = 1.0f\/static_cast<float>(n);\n float beta = 0.25f * cosf(static_cast<float>(M_PI) * 2.0f * wp) + 0.375f;\n beta = beta * beta;\n beta = (0.625f - beta) * wp;\n\n int dstIndex = offset + i;\n vdesc->Clear(vertex, varying, dstIndex);\n\n vdesc->AddWithWeight(vertex, dstIndex, p, weight * (1.0f - (beta * n)));\n\n for (int j = 0; j < n; ++j)\n vdesc->AddWithWeight(vertex, dstIndex, V_IT[h+j], weight * beta);\n\n vdesc->AddVaryingWithWeight(varying, dstIndex, p, 1.0f);\n });\n}\n\nvoid OsdGcdComputeBilinearEdge(\n const OsdVertexDescriptor *vdesc, float *vertex, float *varying,\n const int *E_IT, int offset, int start, int end,\n dispatch_queue_t gcdq) {\n\n dispatch_apply(end-start, gcdq, ^(size_t blockIdx){\n int i = start+blockIdx;\n int eidx0 = E_IT[2*i+0];\n int eidx1 = E_IT[2*i+1];\n\n int dstIndex = offset + i;\n vdesc->Clear(vertex, varying, dstIndex);\n\n vdesc->AddWithWeight(vertex, dstIndex, eidx0, 0.5f);\n vdesc->AddWithWeight(vertex, dstIndex, eidx1, 0.5f);\n\n vdesc->AddVaryingWithWeight(varying, dstIndex, eidx0, 0.5f);\n vdesc->AddVaryingWithWeight(varying, dstIndex, eidx1, 0.5f);\n });\n}\n\nvoid OsdGcdComputeBilinearVertex(\n const OsdVertexDescriptor *vdesc, float *vertex, float *varying,\n const int *V_ITa, int offset, int start, int end,\n dispatch_queue_t gcdq) {\n\n dispatch_apply(end-start, gcdq, ^(size_t blockIdx){\n int i = start+blockIdx;\n int p = V_ITa[i];\n\n int dstIndex = offset + i;\n vdesc->Clear(vertex, varying, dstIndex);\n\n vdesc->AddWithWeight(vertex, dstIndex, p, 1.0f);\n vdesc->AddVaryingWithWeight(varying, dstIndex, p, 1.0f);\n });\n}\n\nvoid OsdGcdEditVertexAdd(\n const OsdVertexDescriptor *vdesc, float *vertex,\n int primVarOffset, int primVarWidth, int vertexCount,\n const int *editIndices, const float *editValues,\n dispatch_queue_t gcdq) {\n\n dispatch_apply(vertexCount, gcdq, ^(size_t blockIdx){\n int i = blockIdx;\n vdesc->ApplyVertexEditAdd(vertex, primVarOffset, primVarWidth,\n editIndices[i], &editValues[i*primVarWidth]);\n });\n}\n\nvoid OsdGcdEditVertexSet(\n const OsdVertexDescriptor *vdesc, float *vertex,\n int primVarOffset, int primVarWidth, int vertexCount,\n const int *editIndices, const float *editValues,\n dispatch_queue_t gcdq) {\n\n dispatch_apply(vertexCount, gcdq, ^(size_t blockIdx){\n int i = blockIdx;\n vdesc->ApplyVertexEditSet(vertex, primVarOffset, primVarWidth,\n editIndices[i], &editValues[i*primVarWidth]);\n });\n}\n\n\n} \/\/ end namespace OPENSUBDIV_VERSION\n} \/\/ end namespace OpenSubdiv\n<commit_msg>gcd: convert face loop to work in 32 item size batches. MBP6,2 (2 core 4 thread), catmark_car Lv4: 31.2ms CPU, 15.8ms GCD (was 22ms)<commit_after>\/\/\n\/\/ Copyright (C) Pixar. All rights reserved.\n\/\/\n\/\/ This license governs use of the accompanying software. If you\n\/\/ use the software, you accept this license. If you do not accept\n\/\/ the license, do not use the software.\n\/\/\n\/\/ 1. Definitions\n\/\/ The terms \"reproduce,\" \"reproduction,\" \"derivative works,\" and\n\/\/ \"distribution\" have the same meaning here as under U.S.\n\/\/ copyright law. A \"contribution\" is the original software, or\n\/\/ any additions or changes to the software.\n\/\/ A \"contributor\" is any person or entity that distributes its\n\/\/ contribution under this license.\n\/\/ \"Licensed patents\" are a contributor's patent claims that read\n\/\/ directly on its contribution.\n\/\/\n\/\/ 2. Grant of Rights\n\/\/ (A) Copyright Grant- Subject to the terms of this license,\n\/\/ including the license conditions and limitations in section 3,\n\/\/ each contributor grants you a non-exclusive, worldwide,\n\/\/ royalty-free copyright license to reproduce its contribution,\n\/\/ prepare derivative works of its contribution, and distribute\n\/\/ its contribution or any derivative works that you create.\n\/\/ (B) Patent Grant- Subject to the terms of this license,\n\/\/ including the license conditions and limitations in section 3,\n\/\/ each contributor grants you a non-exclusive, worldwide,\n\/\/ royalty-free license under its licensed patents to make, have\n\/\/ made, use, sell, offer for sale, import, and\/or otherwise\n\/\/ dispose of its contribution in the software or derivative works\n\/\/ of the contribution in the software.\n\/\/\n\/\/ 3. Conditions and Limitations\n\/\/ (A) No Trademark License- This license does not grant you\n\/\/ rights to use any contributor's name, logo, or trademarks.\n\/\/ (B) If you bring a patent claim against any contributor over\n\/\/ patents that you claim are infringed by the software, your\n\/\/ patent license from such contributor to the software ends\n\/\/ automatically.\n\/\/ (C) If you distribute any portion of the software, you must\n\/\/ retain all copyright, patent, trademark, and attribution\n\/\/ notices that are present in the software.\n\/\/ (D) If you distribute any portion of the software in source\n\/\/ code form, you may do so only under this license by including a\n\/\/ complete copy of this license with your distribution. If you\n\/\/ distribute any portion of the software in compiled or object\n\/\/ code form, you may only do so under a license that complies\n\/\/ with this license.\n\/\/ (E) The software is licensed \"as-is.\" You bear the risk of\n\/\/ using it. The contributors give no express warranties,\n\/\/ guarantees or conditions. You may have additional consumer\n\/\/ rights under your local laws which this license cannot change.\n\/\/ To the extent permitted under your local laws, the contributors\n\/\/ exclude the implied warranties of merchantability, fitness for\n\/\/ a particular purpose and non-infringement.\n\/\/\n\n#include \"..\/osd\/gcdKernel.h\"\n#include \"..\/osd\/cpuKernel.h\"\n#include \"..\/osd\/vertexDescriptor.h\"\n\n#include <math.h>\n\nnamespace OpenSubdiv {\nnamespace OPENSUBDIV_VERSION {\n\nconst int GCD_WORK_STRIDE = 32;\n\n\nvoid OsdGcdComputeFace(\n const OsdVertexDescriptor *vdesc, float * vertex, float * varying,\n const int *F_IT, const int *F_ITa, int offset, int start, int end,\n dispatch_queue_t gcdq) {\n\n const int workSize = end-start;\n dispatch_apply(workSize\/GCD_WORK_STRIDE, gcdq, ^(size_t blockIdx){\n const int start_i = start + blockIdx*GCD_WORK_STRIDE;\n const int end_i = start_i + GCD_WORK_STRIDE;\n OsdCpuComputeFace(vdesc, vertex, varying, F_IT, F_ITa, offset,\n start_i, end_i);\n });\n const int start_e = end - workSize%GCD_WORK_STRIDE;\n const int end_e = end;\n if (start_e < end_e)\n OsdCpuComputeFace(vdesc, vertex, varying, F_IT, F_ITa, offset,\n start_e, end_e);\n}\n\nvoid OsdGcdComputeEdge(\n const OsdVertexDescriptor *vdesc, float *vertex, float *varying,\n const int *E_IT, const float *E_W, int offset, int start, int end,\n dispatch_queue_t gcdq) {\n\n const int workSize = end-start;\n dispatch_apply(workSize\/GCD_WORK_STRIDE, gcdq, ^(size_t blockIdx){\n const int start_i = start + blockIdx*GCD_WORK_STRIDE;\n const int end_i = start_i + GCD_WORK_STRIDE;\n OsdCpuComputeEdge(vdesc, vertex, varying, E_IT, E_W, offset,\n start_i, end_i);\n });\n const int start_e = end - workSize%GCD_WORK_STRIDE;\n const int end_e = end;\n if (start_e < end_e)\n OsdCpuComputeEdge(vdesc, vertex, varying, E_IT, E_W, offset,\n start_e, end_e);\n}\n\nvoid OsdGcdComputeVertexA(\n const OsdVertexDescriptor *vdesc, float *vertex, float *varying,\n const int *V_ITa, const float *V_W,\n int offset, int start, int end, int pass,\n dispatch_queue_t gcdq) {\n\n const int workSize = end-start;\n dispatch_apply(workSize\/GCD_WORK_STRIDE, gcdq, ^(size_t blockIdx){\n const int start_i = start + blockIdx*GCD_WORK_STRIDE;\n const int end_i = start_i + GCD_WORK_STRIDE;\n OsdCpuComputeVertexA(vdesc, vertex, varying, V_ITa, V_W, offset,\n start_i, end_i, pass);\n });\n const int start_e = end - workSize%GCD_WORK_STRIDE;\n const int end_e = end;\n if (start_e < end_e)\n OsdCpuComputeVertexA(vdesc, vertex, varying, V_ITa, V_W, offset,\n start_e, end_e, pass);\n}\n\nvoid OsdGcdComputeVertexB(\n const OsdVertexDescriptor *vdesc, float *vertex, float *varying,\n const int *V_ITa, const int *V_IT, const float *V_W,\n int offset, int start, int end,\n dispatch_queue_t gcdq) {\n\n const int workSize = end-start;\n dispatch_apply(workSize\/GCD_WORK_STRIDE, gcdq, ^(size_t blockIdx){\n const int start_i = start + blockIdx*GCD_WORK_STRIDE;\n const int end_i = start_i + GCD_WORK_STRIDE;\n OsdCpuComputeVertexB(vdesc, vertex, varying, V_ITa, V_IT, V_W, offset,\n start_i, end_i);\n });\n const int start_e = end - workSize%GCD_WORK_STRIDE;\n const int end_e = end;\n if (start_e < end_e)\n OsdCpuComputeVertexB(vdesc, vertex, varying, V_ITa, V_IT, V_W, offset,\n start_e, end_e);\n}\n\nvoid OsdGcdComputeLoopVertexB(\n const OsdVertexDescriptor *vdesc, float *vertex, float *varying,\n const int *V_ITa, const int *V_IT, const float *V_W,\n int offset, int start, int end,\n dispatch_queue_t gcdq) {\n\n dispatch_apply(end-start, gcdq, ^(size_t blockIdx){\n int i = start+blockIdx;\n int h = V_ITa[5*i];\n int n = V_ITa[5*i+1];\n int p = V_ITa[5*i+2];\n\n float weight = V_W[i];\n float wp = 1.0f\/static_cast<float>(n);\n float beta = 0.25f * cosf(static_cast<float>(M_PI) * 2.0f * wp) + 0.375f;\n beta = beta * beta;\n beta = (0.625f - beta) * wp;\n\n int dstIndex = offset + i;\n vdesc->Clear(vertex, varying, dstIndex);\n\n vdesc->AddWithWeight(vertex, dstIndex, p, weight * (1.0f - (beta * n)));\n\n for (int j = 0; j < n; ++j)\n vdesc->AddWithWeight(vertex, dstIndex, V_IT[h+j], weight * beta);\n\n vdesc->AddVaryingWithWeight(varying, dstIndex, p, 1.0f);\n });\n}\n\nvoid OsdGcdComputeBilinearEdge(\n const OsdVertexDescriptor *vdesc, float *vertex, float *varying,\n const int *E_IT, int offset, int start, int end,\n dispatch_queue_t gcdq) {\n\n dispatch_apply(end-start, gcdq, ^(size_t blockIdx){\n int i = start+blockIdx;\n int eidx0 = E_IT[2*i+0];\n int eidx1 = E_IT[2*i+1];\n\n int dstIndex = offset + i;\n vdesc->Clear(vertex, varying, dstIndex);\n\n vdesc->AddWithWeight(vertex, dstIndex, eidx0, 0.5f);\n vdesc->AddWithWeight(vertex, dstIndex, eidx1, 0.5f);\n\n vdesc->AddVaryingWithWeight(varying, dstIndex, eidx0, 0.5f);\n vdesc->AddVaryingWithWeight(varying, dstIndex, eidx1, 0.5f);\n });\n}\n\nvoid OsdGcdComputeBilinearVertex(\n const OsdVertexDescriptor *vdesc, float *vertex, float *varying,\n const int *V_ITa, int offset, int start, int end,\n dispatch_queue_t gcdq) {\n\n dispatch_apply(end-start, gcdq, ^(size_t blockIdx){\n int i = start+blockIdx;\n int p = V_ITa[i];\n\n int dstIndex = offset + i;\n vdesc->Clear(vertex, varying, dstIndex);\n\n vdesc->AddWithWeight(vertex, dstIndex, p, 1.0f);\n vdesc->AddVaryingWithWeight(varying, dstIndex, p, 1.0f);\n });\n}\n\nvoid OsdGcdEditVertexAdd(\n const OsdVertexDescriptor *vdesc, float *vertex,\n int primVarOffset, int primVarWidth, int vertexCount,\n const int *editIndices, const float *editValues,\n dispatch_queue_t gcdq) {\n\n dispatch_apply(vertexCount, gcdq, ^(size_t blockIdx){\n int i = blockIdx;\n vdesc->ApplyVertexEditAdd(vertex, primVarOffset, primVarWidth,\n editIndices[i], &editValues[i*primVarWidth]);\n });\n}\n\nvoid OsdGcdEditVertexSet(\n const OsdVertexDescriptor *vdesc, float *vertex,\n int primVarOffset, int primVarWidth, int vertexCount,\n const int *editIndices, const float *editValues,\n dispatch_queue_t gcdq) {\n\n dispatch_apply(vertexCount, gcdq, ^(size_t blockIdx){\n int i = blockIdx;\n vdesc->ApplyVertexEditSet(vertex, primVarOffset, primVarWidth,\n editIndices[i], &editValues[i*primVarWidth]);\n });\n}\n\n\n} \/\/ end namespace OPENSUBDIV_VERSION\n} \/\/ end namespace OpenSubdiv\n<|endoftext|>"} {"text":"<commit_before>#include <DS18B20.h>\n\nDS18B20::DS18B20(uint8_t pin) : oneWire(OneWire(pin)) {\n resetSearch();\n sendCommand(SKIP_ROM, READ_POWER_SUPPLY);\n globalPowerMode = oneWire.read_bit();\n\n while (selectNext()) {\n uint8_t resolution = getResolution();\n\n if (resolution > globalResolution) {\n globalResolution = resolution;\n }\n\n numberOfDevices++;\n }\n}\n\nuint8_t DS18B20::select(uint8_t address[]) {\n if (isConnected(address)) {\n memcpy(selectedAddress, address, 8);\n\n if (readScratchpad()) {\n selectedResolution = getResolution();\n\n sendCommand(MATCH_ROM, READ_POWER_SUPPLY);\n selectedPowerMode = oneWire.read_bit();\n\n return 1;\n }\n }\n\n return 0;\n}\n\nuint8_t DS18B20::selectNext() {\n if (oneWireSearch(SEARCH_ROM)) {\n return select(searchAddress);\n }\n\n return 0;\n}\n\nuint8_t DS18B20::selectNextAlarm() {\n if (oneWireSearch(ALARM_SEARCH)) {\n return select(searchAddress);\n }\n\n return 0;\n}\n\nvoid DS18B20::resetSearch() {\n lastDiscrepancy = 0;\n lastDevice = 0;\n}\n\nfloat DS18B20::getTempC() {\n sendCommand(MATCH_ROM, CONVERT_T, !selectedPowerMode);\n delayForConversion(selectedResolution, selectedPowerMode);\n readScratchpad();\n uint8_t lsb = selectedScratchpad[TEMP_LSB];\n uint8_t msb = selectedScratchpad[TEMP_MSB];\n\n switch (selectedResolution) {\n case 9:\n lsb &= 0xF8;\n break;\n case 10:\n lsb &= 0xFC;\n break;\n case 11:\n lsb &= 0xFE;\n break;\n }\n\n uint8_t sign = msb & 0x80;\n int16_t temp = (msb << 8) + lsb;\n\n if (sign) {\n temp = ((temp ^ 0xffff) + 1) * -1;\n }\n\n return temp \/ 16.0;\n}\n\nfloat DS18B20::getTempF() {\n return getTempC() * 1.8 + 32;\n}\n\nuint8_t DS18B20::getResolution() {\n switch (selectedScratchpad[CONFIGURATION]) {\n case RES_9_BIT:\n return 9;\n case RES_10_BIT:\n return 10;\n case RES_11_BIT:\n return 11;\n case RES_12_BIT:\n return 12;\n }\n}\n\nvoid DS18B20::setResolution(uint8_t resolution) {\n resolution = constrain(resolution, 9, 12);\n\n switch (resolution) {\n case 9:\n selectedScratchpad[CONFIGURATION] = RES_9_BIT;\n break;\n case 10:\n selectedScratchpad[CONFIGURATION] = RES_10_BIT;\n break;\n case 11:\n selectedScratchpad[CONFIGURATION] = RES_11_BIT;\n break;\n case 12:\n selectedScratchpad[CONFIGURATION] = RES_12_BIT;\n break;\n }\n\n if (resolution > globalResolution) {\n globalResolution = resolution;\n }\n\n writeScratchpad();\n}\n\nuint8_t DS18B20::getPowerMode() {\n return selectedPowerMode;\n}\n\nuint8_t DS18B20::getFamilyCode() {\n return selectedAddress[0];\n}\n\nvoid DS18B20::getAddress(uint8_t address[]) {\n memcpy(address, selectedAddress, 8);\n}\n\nvoid DS18B20::doConversion() {\n sendCommand(SKIP_ROM, CONVERT_T, !globalPowerMode);\n delayForConversion(globalResolution, globalPowerMode);\n}\n\nuint8_t DS18B20::getNumberOfDevices() {\n return numberOfDevices;\n}\n\nuint8_t DS18B20::hasAlarm() {\n uint8_t oldResolution = selectedResolution;\n setResolution(9);\n float temp = getTempC();\n setResolution(oldResolution);\n return ((temp <= selectedScratchpad[ALARM_LOW]) || (temp >= selectedScratchpad[ALARM_HIGH]));\n}\n\nvoid DS18B20::setAlarms(int8_t alarmLow, int8_t alarmHigh) {\n setAlarmLow(alarmLow);\n setAlarmHigh(alarmHigh);\n writeScratchpad();\n}\n\nint8_t DS18B20::getAlarmLow() {\n return selectedScratchpad[ALARM_LOW];\n}\n\nvoid DS18B20::setAlarmLow(int8_t alarmLow) {\n alarmLow = constrain(alarmLow, -55, 125);\n selectedScratchpad[ALARM_LOW] = alarmLow;\n writeScratchpad();\n}\n\nint8_t DS18B20::getAlarmHigh() {\n return selectedScratchpad[ALARM_HIGH];\n}\n\nvoid DS18B20::setAlarmHigh(int8_t alarmHigh) {\n alarmHigh = constrain(alarmHigh, -55, 125);\n selectedScratchpad[ALARM_HIGH] = alarmHigh;\n writeScratchpad();\n}\n\nvoid DS18B20::setRegisters(int8_t lowRegister, int8_t highRegister) {\n setAlarms(lowRegister, highRegister);\n}\n\nint8_t DS18B20::getLowRegister() {\n return getAlarmLow();\n}\n\nvoid DS18B20::setLowRegister(int8_t lowRegister) {\n setAlarmLow(lowRegister);\n}\n\nint8_t DS18B20::getHighRegister() {\n return getAlarmHigh();\n}\n\nvoid DS18B20::setHighRegister(int8_t highRegister) {\n setAlarmHigh(highRegister);\n}\n\nuint8_t DS18B20::readScratchpad() {\n sendCommand(MATCH_ROM, READ_SCRATCHPAD);\n\n for (uint8_t i = 0; i < SIZE_SCRATCHPAD; i++) {\n selectedScratchpad[i] = oneWire.read();\n }\n\n return OneWire::crc8(selectedScratchpad, 8) == selectedScratchpad[CRC8];\n}\n\nvoid DS18B20::writeScratchpad() {\n sendCommand(MATCH_ROM, WRITE_SCRATCHPAD);\n oneWire.write(selectedScratchpad[ALARM_HIGH]);\n oneWire.write(selectedScratchpad[ALARM_LOW]);\n oneWire.write(selectedScratchpad[CONFIGURATION]);\n sendCommand(MATCH_ROM, COPY_SCRATCHPAD, !selectedPowerMode);\n\n if (!selectedPowerMode) {\n delay(10);\n }\n}\n\nuint8_t DS18B20::sendCommand(uint8_t romCommand) {\n if (!oneWire.reset()) {\n return 0;\n }\n\n switch (romCommand) {\n case SEARCH_ROM:\n case SKIP_ROM:\n case ALARM_SEARCH:\n oneWire.write(romCommand);\n break;\n case MATCH_ROM:\n oneWire.select(selectedAddress);\n break;\n default:\n return 0;\n }\n\n return 1;\n}\n\nuint8_t DS18B20::sendCommand(uint8_t romCommand, uint8_t functionCommand, uint8_t power) {\n if (!sendCommand(romCommand)) {\n return 0;\n }\n\n switch (functionCommand) {\n case CONVERT_T:\n case COPY_SCRATCHPAD:\n oneWire.write(functionCommand, power);\n break;\n case WRITE_SCRATCHPAD:\n case READ_SCRATCHPAD:\n case READ_POWER_SUPPLY:\n oneWire.write(functionCommand);\n break;\n default:\n return 0;\n }\n\n return 1;\n}\n\nuint8_t DS18B20::oneWireSearch(uint8_t romCommand) {\n if (lastDevice || !sendCommand(romCommand)) {\n resetSearch();\n return 0;\n }\n\n uint8_t lastZero = 0;\n uint8_t direction, byteNumber, bitNumber, currentBit, currentBitComp;\n\n for (uint8_t bitPosition = 0; bitPosition < 64; bitPosition++) {\n currentBit = oneWire.read_bit();\n currentBitComp = oneWire.read_bit();\n\n if (currentBit && currentBitComp) {\n lastDiscrepancy = 0;\n return 0;\n }\n\n byteNumber = bitPosition \/ 8;\n bitNumber = bitPosition % 8;\n\n if (!currentBit && !currentBitComp) {\n if (bitPosition == lastDiscrepancy) {\n direction = 1;\n } else if (bitPosition > lastDiscrepancy) {\n direction = 0;\n lastZero = bitPosition;\n } else {\n direction = bitRead(searchAddress[byteNumber], bitNumber);\n\n if (!direction) {\n lastZero = bitPosition;\n }\n }\n } else {\n direction = currentBit;\n }\n\n bitWrite(searchAddress[byteNumber], bitNumber, direction);\n oneWire.write_bit(direction);\n }\n\n lastDiscrepancy = lastZero;\n\n if (!lastDiscrepancy) {\n lastDevice = 1;\n }\n\n return 1;\n}\n\nuint8_t DS18B20::isConnected(uint8_t address[]) {\n if (!sendCommand(SEARCH_ROM)) {\n return 0;\n }\n\n uint8_t currentBit, currentBitComp, byteNumber, bitNumber;\n\n for (uint8_t bitPosition = 0; bitPosition < 64; bitPosition++) {\n currentBit = oneWire.read_bit();\n currentBitComp = oneWire.read_bit();\n\n if (currentBit && currentBitComp) {\n return 0;\n }\n\n byteNumber = bitPosition \/ 8;\n bitNumber = bitPosition % 8;\n oneWire.write_bit(bitRead(address[byteNumber], bitNumber));\n }\n\n return 1;\n}\n\nvoid DS18B20::delayForConversion(uint8_t resolution, uint8_t powerMode) {\n if (powerMode) {\n while (!oneWire.read_bit());\n } else {\n switch (resolution) {\n case 9:\n delay(CONV_TIME_9_BIT);\n break;\n case 10:\n delay(CONV_TIME_10_BIT);\n break;\n case 11:\n delay(CONV_TIME_11_BIT);\n break;\n case 12:\n delay(CONV_TIME_12_BIT);\n break;\n }\n }\n}\n<commit_msg>Initialize class members in the constructor<commit_after>#include <DS18B20.h>\n\nDS18B20::DS18B20(uint8_t pin) :\n oneWire(OneWire(pin)),\n numberOfDevices(0),\n globalResolution(0),\n selectedResolution(0),\n selectedPowerMode(0)\n{\n resetSearch();\n sendCommand(SKIP_ROM, READ_POWER_SUPPLY);\n globalPowerMode = oneWire.read_bit();\n\n while (selectNext()) {\n uint8_t resolution = getResolution();\n\n if (resolution > globalResolution) {\n globalResolution = resolution;\n }\n\n numberOfDevices++;\n }\n}\n\nuint8_t DS18B20::select(uint8_t address[]) {\n if (isConnected(address)) {\n memcpy(selectedAddress, address, 8);\n\n if (readScratchpad()) {\n selectedResolution = getResolution();\n\n sendCommand(MATCH_ROM, READ_POWER_SUPPLY);\n selectedPowerMode = oneWire.read_bit();\n\n return 1;\n }\n }\n\n return 0;\n}\n\nuint8_t DS18B20::selectNext() {\n if (oneWireSearch(SEARCH_ROM)) {\n return select(searchAddress);\n }\n\n return 0;\n}\n\nuint8_t DS18B20::selectNextAlarm() {\n if (oneWireSearch(ALARM_SEARCH)) {\n return select(searchAddress);\n }\n\n return 0;\n}\n\nvoid DS18B20::resetSearch() {\n lastDiscrepancy = 0;\n lastDevice = 0;\n}\n\nfloat DS18B20::getTempC() {\n sendCommand(MATCH_ROM, CONVERT_T, !selectedPowerMode);\n delayForConversion(selectedResolution, selectedPowerMode);\n readScratchpad();\n uint8_t lsb = selectedScratchpad[TEMP_LSB];\n uint8_t msb = selectedScratchpad[TEMP_MSB];\n\n switch (selectedResolution) {\n case 9:\n lsb &= 0xF8;\n break;\n case 10:\n lsb &= 0xFC;\n break;\n case 11:\n lsb &= 0xFE;\n break;\n }\n\n uint8_t sign = msb & 0x80;\n int16_t temp = (msb << 8) + lsb;\n\n if (sign) {\n temp = ((temp ^ 0xffff) + 1) * -1;\n }\n\n return temp \/ 16.0;\n}\n\nfloat DS18B20::getTempF() {\n return getTempC() * 1.8 + 32;\n}\n\nuint8_t DS18B20::getResolution() {\n switch (selectedScratchpad[CONFIGURATION]) {\n case RES_9_BIT:\n return 9;\n case RES_10_BIT:\n return 10;\n case RES_11_BIT:\n return 11;\n case RES_12_BIT:\n return 12;\n }\n}\n\nvoid DS18B20::setResolution(uint8_t resolution) {\n resolution = constrain(resolution, 9, 12);\n\n switch (resolution) {\n case 9:\n selectedScratchpad[CONFIGURATION] = RES_9_BIT;\n break;\n case 10:\n selectedScratchpad[CONFIGURATION] = RES_10_BIT;\n break;\n case 11:\n selectedScratchpad[CONFIGURATION] = RES_11_BIT;\n break;\n case 12:\n selectedScratchpad[CONFIGURATION] = RES_12_BIT;\n break;\n }\n\n if (resolution > globalResolution) {\n globalResolution = resolution;\n }\n\n writeScratchpad();\n}\n\nuint8_t DS18B20::getPowerMode() {\n return selectedPowerMode;\n}\n\nuint8_t DS18B20::getFamilyCode() {\n return selectedAddress[0];\n}\n\nvoid DS18B20::getAddress(uint8_t address[]) {\n memcpy(address, selectedAddress, 8);\n}\n\nvoid DS18B20::doConversion() {\n sendCommand(SKIP_ROM, CONVERT_T, !globalPowerMode);\n delayForConversion(globalResolution, globalPowerMode);\n}\n\nuint8_t DS18B20::getNumberOfDevices() {\n return numberOfDevices;\n}\n\nuint8_t DS18B20::hasAlarm() {\n uint8_t oldResolution = selectedResolution;\n setResolution(9);\n float temp = getTempC();\n setResolution(oldResolution);\n return ((temp <= selectedScratchpad[ALARM_LOW]) || (temp >= selectedScratchpad[ALARM_HIGH]));\n}\n\nvoid DS18B20::setAlarms(int8_t alarmLow, int8_t alarmHigh) {\n setAlarmLow(alarmLow);\n setAlarmHigh(alarmHigh);\n writeScratchpad();\n}\n\nint8_t DS18B20::getAlarmLow() {\n return selectedScratchpad[ALARM_LOW];\n}\n\nvoid DS18B20::setAlarmLow(int8_t alarmLow) {\n alarmLow = constrain(alarmLow, -55, 125);\n selectedScratchpad[ALARM_LOW] = alarmLow;\n writeScratchpad();\n}\n\nint8_t DS18B20::getAlarmHigh() {\n return selectedScratchpad[ALARM_HIGH];\n}\n\nvoid DS18B20::setAlarmHigh(int8_t alarmHigh) {\n alarmHigh = constrain(alarmHigh, -55, 125);\n selectedScratchpad[ALARM_HIGH] = alarmHigh;\n writeScratchpad();\n}\n\nvoid DS18B20::setRegisters(int8_t lowRegister, int8_t highRegister) {\n setAlarms(lowRegister, highRegister);\n}\n\nint8_t DS18B20::getLowRegister() {\n return getAlarmLow();\n}\n\nvoid DS18B20::setLowRegister(int8_t lowRegister) {\n setAlarmLow(lowRegister);\n}\n\nint8_t DS18B20::getHighRegister() {\n return getAlarmHigh();\n}\n\nvoid DS18B20::setHighRegister(int8_t highRegister) {\n setAlarmHigh(highRegister);\n}\n\nuint8_t DS18B20::readScratchpad() {\n sendCommand(MATCH_ROM, READ_SCRATCHPAD);\n\n for (uint8_t i = 0; i < SIZE_SCRATCHPAD; i++) {\n selectedScratchpad[i] = oneWire.read();\n }\n\n return OneWire::crc8(selectedScratchpad, 8) == selectedScratchpad[CRC8];\n}\n\nvoid DS18B20::writeScratchpad() {\n sendCommand(MATCH_ROM, WRITE_SCRATCHPAD);\n oneWire.write(selectedScratchpad[ALARM_HIGH]);\n oneWire.write(selectedScratchpad[ALARM_LOW]);\n oneWire.write(selectedScratchpad[CONFIGURATION]);\n sendCommand(MATCH_ROM, COPY_SCRATCHPAD, !selectedPowerMode);\n\n if (!selectedPowerMode) {\n delay(10);\n }\n}\n\nuint8_t DS18B20::sendCommand(uint8_t romCommand) {\n if (!oneWire.reset()) {\n return 0;\n }\n\n switch (romCommand) {\n case SEARCH_ROM:\n case SKIP_ROM:\n case ALARM_SEARCH:\n oneWire.write(romCommand);\n break;\n case MATCH_ROM:\n oneWire.select(selectedAddress);\n break;\n default:\n return 0;\n }\n\n return 1;\n}\n\nuint8_t DS18B20::sendCommand(uint8_t romCommand, uint8_t functionCommand, uint8_t power) {\n if (!sendCommand(romCommand)) {\n return 0;\n }\n\n switch (functionCommand) {\n case CONVERT_T:\n case COPY_SCRATCHPAD:\n oneWire.write(functionCommand, power);\n break;\n case WRITE_SCRATCHPAD:\n case READ_SCRATCHPAD:\n case READ_POWER_SUPPLY:\n oneWire.write(functionCommand);\n break;\n default:\n return 0;\n }\n\n return 1;\n}\n\nuint8_t DS18B20::oneWireSearch(uint8_t romCommand) {\n if (lastDevice || !sendCommand(romCommand)) {\n resetSearch();\n return 0;\n }\n\n uint8_t lastZero = 0;\n uint8_t direction, byteNumber, bitNumber, currentBit, currentBitComp;\n\n for (uint8_t bitPosition = 0; bitPosition < 64; bitPosition++) {\n currentBit = oneWire.read_bit();\n currentBitComp = oneWire.read_bit();\n\n if (currentBit && currentBitComp) {\n lastDiscrepancy = 0;\n return 0;\n }\n\n byteNumber = bitPosition \/ 8;\n bitNumber = bitPosition % 8;\n\n if (!currentBit && !currentBitComp) {\n if (bitPosition == lastDiscrepancy) {\n direction = 1;\n } else if (bitPosition > lastDiscrepancy) {\n direction = 0;\n lastZero = bitPosition;\n } else {\n direction = bitRead(searchAddress[byteNumber], bitNumber);\n\n if (!direction) {\n lastZero = bitPosition;\n }\n }\n } else {\n direction = currentBit;\n }\n\n bitWrite(searchAddress[byteNumber], bitNumber, direction);\n oneWire.write_bit(direction);\n }\n\n lastDiscrepancy = lastZero;\n\n if (!lastDiscrepancy) {\n lastDevice = 1;\n }\n\n return 1;\n}\n\nuint8_t DS18B20::isConnected(uint8_t address[]) {\n if (!sendCommand(SEARCH_ROM)) {\n return 0;\n }\n\n uint8_t currentBit, currentBitComp, byteNumber, bitNumber;\n\n for (uint8_t bitPosition = 0; bitPosition < 64; bitPosition++) {\n currentBit = oneWire.read_bit();\n currentBitComp = oneWire.read_bit();\n\n if (currentBit && currentBitComp) {\n return 0;\n }\n\n byteNumber = bitPosition \/ 8;\n bitNumber = bitPosition % 8;\n oneWire.write_bit(bitRead(address[byteNumber], bitNumber));\n }\n\n return 1;\n}\n\nvoid DS18B20::delayForConversion(uint8_t resolution, uint8_t powerMode) {\n if (powerMode) {\n while (!oneWire.read_bit());\n } else {\n switch (resolution) {\n case 9:\n delay(CONV_TIME_9_BIT);\n break;\n case 10:\n delay(CONV_TIME_10_BIT);\n break;\n case 11:\n delay(CONV_TIME_11_BIT);\n break;\n case 12:\n delay(CONV_TIME_12_BIT);\n break;\n }\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * IP address for the multicast group 224.0.0.224\n * Port for multicast group 45454\n *\n *\n * broadcasts are of the format\n * [type][channel][nick][contents]\n * type is a 4 byte string, currently \"edct\" for normal edicts, \"mdct\" for medicts, \"ntfy\" for notifies.\n * channel is a 64 byte string which contains the destination channel for the message terminated with zero characters.\n * nick is the same size and idea as channel, except it contains the nick of the sender.\n * contents is a max 256 byte string of whatever the text being sent is. If the contents are shorter, the broadcast is shorter to match.\n *\n * a periodic broadcast of type \"here\" is sent out every minute; it's format is\n * [type][nick]\n * type is the standard 4 byte string, and nick is a max 64 byte\n *\n * To Do:\n * make sure the nick\/channel\/message length being broadcast is short enough\n * toss a notify to the UI if ^ fails\n *\n * add the timed \"still here\" messages\n *\/\n\n\n#include <thread>\n#include <iostream>\n#include <QByteArray>\n#include <QString>\n#include <QSettings>\n#include <QtNetwork>\n#include <unordered_set>\n#include <ctime>\n\n#include \"lirch_constants.h\"\n#include \"blocker_messages.h\"\n#include \"edict_messages.h\"\n#include \"received_messages.h\"\n#include \"lirch_plugin.h\"\n#include \"lirch_constants.h\"\n#include \"grinder_messages.h\"\n#include \"notify_messages.h\"\n\nusing namespace std;\n\n\n\/\/this nonsense is needed in order to have our blocklist be searchable\nnamespace std\n{\n\ttemplate <>\n\tstruct hash<QHostAddress>\n\t{\n\t\tsize_t operator()(const QHostAddress& v) const\n\t\t{\n\t\t\treturn std::hash<std::string>()(v.toString().toStdString());\n\t\t}\n\t};\n}\n\nmessage sendBlock(QString str, QString)\n{\n\tif (str.startsWith(\"\/block \"))\n\t\treturn block_message::create(block_message_subtype::ADD,QHostAddress(str.section(' ',1)));\n\treturn empty_message::create();\n}\n\nmessage sendUnblock(QString str, QString)\n{\n\tif (str.startsWith(\"\/unblock \"))\n\t\treturn block_message::create(block_message_subtype::REMOVE,QHostAddress(str.section(' ',1)));\n\treturn empty_message::create();\n}\n\nQByteArray formatMessage(QString type, QString channel, QString nick, QString contents);\n\nvoid run(plugin_pipe p, string name)\n{\n\tunordered_set<QHostAddress> blocklist;\n\n\ttime_t lastSent=time(NULL);\n\n\t\/\/register for the message types the antenna can handle\n\tp.write(registration_message::create(0, name, \"block\"));\n\tp.write(registration_message::create(0, name, \"edict\"));\n\tp.write(registration_message::create(0, name, \"handler_ready\"));\n\n\tp.write(register_handler::create(\"\/block\", sendBlock));\n\tp.write(register_handler::create(\"\/unblock\", sendUnblock));\n\n\t\/\/connect to multicast group\n\tQUdpSocket udpSocket;\n\tQHostAddress groupAddress(LIRCH_DEFAULT_ADDR);\n\tquint16 port = LIRCH_DEFAULT_PORT;\n\n\n\t\/\/TODO: Explicitly set QAbstractSocket::MulticastLoopbackOption to 1\n\tif (!udpSocket.bind(groupAddress,port,QUdpSocket::ShareAddress))\n\t{\n\t\tp.write(notify_message::create(\"default\",\"Failed to bind.\"));\n\t\treturn;\n\t}\n\tif(!udpSocket.joinMulticastGroup(groupAddress))\n\t{\n\t\tp.write(notify_message::create(\"default\",\"Failed to join Multicast Group.\"));\n\t\treturn;\n\t}\n\n\t\/\/needed to send nick with your messages\n\tQSettings settings(QSettings::IniFormat, QSettings::UserScope, LIRCH_COMPANY_NAME, \"Lirch\");\n\tsettings.beginGroup(\"UserData\");\n\n\twhile(true)\n\t{\n\t\twhile (p.has_message())\n\t\t{\n\t\t\tmessage m = p.read();\n\n\t\t\tif (m.type==\"shutdown\")\n\t\t\t{\n\t\t\t\tudpSocket.leaveMulticastGroup(groupAddress);\n\t\t\t\tudpSocket.close();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\telse if (m.type==\"registration_status\")\n\t\t\t{\n\t\t\t\tauto s=dynamic_cast<registration_status *>(m.getdata());\n\t\t\t\tif (!s)\n\t\t\t\t\tcontinue;\n\t\t\t\t\/\/Retry 2000 times until we succeed\n\t\t\t\tif (!s->status)\n\t\t\t\t{\n\t\t\t\t\tif (s->priority<2000)\n\t\t\t\t\t\tp.write(registration_message::create(s->priority+1, name, s->type));\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if(m.type==\"handler_ready\")\n\t\t\t{\n\t\t\t\tp.write(register_handler::create(\"\/block\", sendBlock));\n\t\t\t\tp.write(register_handler::create(\"\/unblock\", sendUnblock));\n\t\t\t\tp.write(m.decrement_priority());\n\t\t\t}\n\t\t\telse if(m.type==\"block\")\n\t\t\t{\n\t\t\t\tauto castMessage=dynamic_cast<block_message *>(m.getdata());\n\n\t\t\t\t\/\/if it's not actually a block message, ignore it and move on\n\t\t\t\tif (!castMessage)\n\t\t\t\t\tcontinue;\n\n\t\t\t\t\/\/this contains the IP that \/block or \/unblock was called on\n\t\t\t\tauto toModify=castMessage->ip;\n\n\t\t\t\tif(castMessage->subtype==block_message_subtype::ADD)\n\t\t\t\t{\n\t\t\t\t\tblocklist.insert(toModify);\n\t\t\t\t\tp.write(notify_message::create(\"default\",toModify.toString()+\" is now blocked.\"));\n\t\t\t\t}\n\t\t\t\tif(castMessage->subtype==block_message_subtype::REMOVE)\n\t\t\t\t{\n\t\t\t\t\tblocklist.erase(toModify);\n\t\t\t\t\tp.write(notify_message::create(\"default\",toModify.toString()+\" is now unblocked.\"));\n\t\t\t\t}\n\t\t\t}\t\t\t\n\t\t\telse if(m.type==\"edict\")\n\t\t\t{\n\t\t\t\tauto castMessage=dynamic_cast<edict_message *>(m.getdata());\n\n\t\t\t\t\/\/if it's not actually an edict message, ignore it and move on\n\t\t\t\tif (!castMessage)\n\t\t\t\t\tcontinue;\n\n\n\t\t\t\tQString nick=settings.value(\"nick\",\"spartacus\").value<QString>();\n\t\t\t\tQString channel=castMessage->channel;\n\t\t\t\tQString contents=castMessage->contents;\n\t\t\t\tQString type;\n\t\t\t\tif(castMessage->subtype==edict_message_subtype::NORMAL)\n\t\t\t\t\ttype=\"edct\";\n\t\t\t\telse if(castMessage->subtype==edict_message_subtype::ME)\n\t\t\t\t\ttype=\"mdct\";\n\t\t\t\tQByteArray message = formatMessage(type,channel,nick,contents);\n\n\t\t\t\t\/\/change to use write() function when we have time\n\t\t\t\tif(message.length()>0)\n\t\t\t\t{\n\t\t\t\t\tudpSocket.writeDatagram(message,groupAddress,port);\n\t\t\t\t\tlastSent=time(NULL);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if(m.type==\"sendable_notify\")\n\t\t\t{\n\t\t\t\tauto castMessage=dynamic_cast<sendable_notify_message *>(m.getdata());\n\n\t\t\t\t\/\/if it's not actually an edict message, ignore it and move on\n\t\t\t\tif (!castMessage)\n\t\t\t\t\tcontinue;\n\n\t\t\t\tQString nick=settings.value(\"nick\",\"spartacus\").value<QString>();\n\t\t\t\tQString channel=castMessage->channel;\n\t\t\t\tQString contents=castMessage->contents;\n\t\t\t\tQString type=\"ntfy\";\n\n\t\t\t\tQByteArray message = formatMessage(type,channel,nick,contents);\n\n\t\t\t\t\/\/change to use write() function when we have time\n\t\t\t\tif(message.length()>0)\n\t\t\t\t{\n\t\t\t\t\tudpSocket.writeDatagram(message,groupAddress,port);\n\t\t\t\t\tlastSent=time(NULL);\n\t\t\t\t}\n\t\t\t}\n\t\t\t\/\/if somehow a message is recieved that is not of these types, send it back.\n\t\t\telse\n\t\t\t{\n\t\t\t\tp.write(m.decrement_priority());\n\t\t\t}\n\t\t}\n\n\t\twhile (udpSocket.hasPendingDatagrams())\n\t\t{\n\t\t\tchar broadcast[512];\n\t\t\tQHostAddress senderIP;\n\t\t\tquint16 senderPort;\n\t\t\tqint64 size = udpSocket.readDatagram(broadcast,512,&senderIP,&senderPort);\n\t\t\tbroadcast[size]='\\0';\n\t\t\tif(blocklist.end()!=blocklist.find(senderIP))\n\t\t\t\tcontinue;\n\n\t\t\tstring type(broadcast,4);\n\n\t\t\tif (type==\"here\")\n\t\t\t{\n\t\t\t\tp.write(received_message::create(received_message_subtype::HERE,\"\",QString::fromUtf8(broadcast+4),\"\",senderIP));\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tQString destinationChannel=QString::fromUtf8(broadcast+4);\n\t\t\tQString senderNick=QString::fromUtf8(broadcast+68);\n\t\t\tQString sentContents=QString::fromUtf8(broadcast+132);\n\n\t\t\tif (type==\"edct\")\n\t\t\t{\n\t\t\t\tp.write(received_message::create(received_message_subtype::NORMAL,destinationChannel,senderNick,sentContents,senderIP));\n\t\t\t}\n\t\t\telse if (type==\"mdct\")\n\t\t\t{\n\t\t\t\tp.write(received_message::create(received_message_subtype::ME,destinationChannel,senderNick,sentContents,senderIP));\n\t\t\t}\n\t\t\telse if (type==\"ntfy\")\n\t\t\t{\n\t\t\t\tp.write(received_message::create(received_message_subtype::NOTIFY,destinationChannel,senderNick,sentContents,senderIP));\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t}\n\n\n\t\t\/\/sends out a \"still here\" message every minute\n\t\tif(time(NULL)-lastSent>60)\n\t\t{\n\t\t\tQString nick=settings.value(\"nick\",\"spartacus\").value<QString>();\n\t\t\tQString type=\"here\";\n\n\t\t\tQByteArray message = type.toUtf8()+nick.toUtf8();\n\t\t\tmessage.truncate(68);\n\n\t\t\tudpSocket.writeDatagram(message,groupAddress,port);\n\t\t\tlastSent=time(NULL);\n\t\t}\n\n\t\tthis_thread::sleep_for(chrono::milliseconds(50));\n\n\n\t}\n\n\n\n};\n\n\/\/if components are too long, the cropped version might not have a \\0 to terminate it. might need fixing later.\nQByteArray formatMessage(QString type, QString channel, QString nick, QString contents)\n{\n\tQByteArray output;\n\toutput += type.toUtf8();\n\toutput += channel.toUtf8().leftJustified(64,'\\0',true);\n\toutput += nick.toUtf8().leftJustified(64,'\\0',true);\n\tQByteArray holder =contents.toUtf8();\n\tif (holder.length()>256)\n\t{\n\t\treturn QByteArray();\n\t}\n\toutput += holder;\n\toutput += '\\0';\n\treturn output;\n};\n<commit_msg>made broadcast fields not spill into one another<commit_after>\/*\n * IP address for the multicast group 224.0.0.224\n * Port for multicast group 45454\n *\n *\n * broadcasts are of the format\n * [type][channel][nick][contents]\n * type is a 4 byte string, currently \"edct\" for normal edicts, \"mdct\" for medicts, \"ntfy\" for notifies.\n * channel is a 64 byte string which contains the destination channel for the message terminated with zero characters.\n * nick is the same size and idea as channel, except it contains the nick of the sender.\n * contents is a max 256 byte string of whatever the text being sent is. If the contents are shorter, the broadcast is shorter to match.\n *\n * a periodic broadcast of type \"here\" is sent out every minute; it's format is\n * [type][nick]\n * type is the standard 4 byte string, and nick is a max 64 byte\n *\n * To Do:\n * make sure the nick\/channel\/message length being broadcast is short enough\n * toss a notify to the UI if ^ fails\n *\n * add the timed \"still here\" messages\n *\/\n\n\n#include <thread>\n#include <iostream>\n#include <QByteArray>\n#include <QString>\n#include <QSettings>\n#include <QtNetwork>\n#include <unordered_set>\n#include <ctime>\n\n#include \"lirch_constants.h\"\n#include \"blocker_messages.h\"\n#include \"edict_messages.h\"\n#include \"received_messages.h\"\n#include \"lirch_plugin.h\"\n#include \"lirch_constants.h\"\n#include \"grinder_messages.h\"\n#include \"notify_messages.h\"\n\nusing namespace std;\n\n\n\/\/this nonsense is needed in order to have our blocklist be searchable\nnamespace std\n{\n\ttemplate <>\n\tstruct hash<QHostAddress>\n\t{\n\t\tsize_t operator()(const QHostAddress& v) const\n\t\t{\n\t\t\treturn std::hash<std::string>()(v.toString().toStdString());\n\t\t}\n\t};\n}\n\nmessage sendBlock(QString str, QString)\n{\n\tif (str.startsWith(\"\/block \"))\n\t\treturn block_message::create(block_message_subtype::ADD,QHostAddress(str.section(' ',1)));\n\treturn empty_message::create();\n}\n\nmessage sendUnblock(QString str, QString)\n{\n\tif (str.startsWith(\"\/unblock \"))\n\t\treturn block_message::create(block_message_subtype::REMOVE,QHostAddress(str.section(' ',1)));\n\treturn empty_message::create();\n}\n\nQByteArray formatMessage(QString type, QString channel, QString nick, QString contents);\n\nvoid run(plugin_pipe p, string name)\n{\n\tunordered_set<QHostAddress> blocklist;\n\n\ttime_t lastSent=time(NULL);\n\n\t\/\/register for the message types the antenna can handle\n\tp.write(registration_message::create(0, name, \"block\"));\n\tp.write(registration_message::create(0, name, \"edict\"));\n\tp.write(registration_message::create(0, name, \"handler_ready\"));\n\n\tp.write(register_handler::create(\"\/block\", sendBlock));\n\tp.write(register_handler::create(\"\/unblock\", sendUnblock));\n\n\t\/\/connect to multicast group\n\tQUdpSocket udpSocket;\n\tQHostAddress groupAddress(LIRCH_DEFAULT_ADDR);\n\tquint16 port = LIRCH_DEFAULT_PORT;\n\n\n\t\/\/TODO: Explicitly set QAbstractSocket::MulticastLoopbackOption to 1\n\tif (!udpSocket.bind(groupAddress,port,QUdpSocket::ShareAddress))\n\t{\n\t\tp.write(notify_message::create(\"default\",\"Failed to bind.\"));\n\t\treturn;\n\t}\n\tif(!udpSocket.joinMulticastGroup(groupAddress))\n\t{\n\t\tp.write(notify_message::create(\"default\",\"Failed to join Multicast Group.\"));\n\t\treturn;\n\t}\n\n\t\/\/needed to send nick with your messages\n\tQSettings settings(QSettings::IniFormat, QSettings::UserScope, LIRCH_COMPANY_NAME, \"Lirch\");\n\tsettings.beginGroup(\"UserData\");\n\n\twhile(true)\n\t{\n\t\twhile (p.has_message())\n\t\t{\n\t\t\tmessage m = p.read();\n\n\t\t\tif (m.type==\"shutdown\")\n\t\t\t{\n\t\t\t\tudpSocket.leaveMulticastGroup(groupAddress);\n\t\t\t\tudpSocket.close();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\telse if (m.type==\"registration_status\")\n\t\t\t{\n\t\t\t\tauto s=dynamic_cast<registration_status *>(m.getdata());\n\t\t\t\tif (!s)\n\t\t\t\t\tcontinue;\n\t\t\t\t\/\/Retry 2000 times until we succeed\n\t\t\t\tif (!s->status)\n\t\t\t\t{\n\t\t\t\t\tif (s->priority<2000)\n\t\t\t\t\t\tp.write(registration_message::create(s->priority+1, name, s->type));\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if(m.type==\"handler_ready\")\n\t\t\t{\n\t\t\t\tp.write(register_handler::create(\"\/block\", sendBlock));\n\t\t\t\tp.write(register_handler::create(\"\/unblock\", sendUnblock));\n\t\t\t\tp.write(m.decrement_priority());\n\t\t\t}\n\t\t\telse if(m.type==\"block\")\n\t\t\t{\n\t\t\t\tauto castMessage=dynamic_cast<block_message *>(m.getdata());\n\n\t\t\t\t\/\/if it's not actually a block message, ignore it and move on\n\t\t\t\tif (!castMessage)\n\t\t\t\t\tcontinue;\n\n\t\t\t\t\/\/this contains the IP that \/block or \/unblock was called on\n\t\t\t\tauto toModify=castMessage->ip;\n\n\t\t\t\tif(castMessage->subtype==block_message_subtype::ADD)\n\t\t\t\t{\n\t\t\t\t\tblocklist.insert(toModify);\n\t\t\t\t\tp.write(notify_message::create(\"default\",toModify.toString()+\" is now blocked.\"));\n\t\t\t\t}\n\t\t\t\tif(castMessage->subtype==block_message_subtype::REMOVE)\n\t\t\t\t{\n\t\t\t\t\tblocklist.erase(toModify);\n\t\t\t\t\tp.write(notify_message::create(\"default\",toModify.toString()+\" is now unblocked.\"));\n\t\t\t\t}\n\t\t\t}\t\t\t\n\t\t\telse if(m.type==\"edict\")\n\t\t\t{\n\t\t\t\tauto castMessage=dynamic_cast<edict_message *>(m.getdata());\n\n\t\t\t\t\/\/if it's not actually an edict message, ignore it and move on\n\t\t\t\tif (!castMessage)\n\t\t\t\t\tcontinue;\n\n\n\t\t\t\tQString nick=settings.value(\"nick\",\"spartacus\").value<QString>();\n\t\t\t\tQString channel=castMessage->channel;\n\t\t\t\tQString contents=castMessage->contents;\n\t\t\t\tQString type;\n\t\t\t\tif(castMessage->subtype==edict_message_subtype::NORMAL)\n\t\t\t\t\ttype=\"edct\";\n\t\t\t\telse if(castMessage->subtype==edict_message_subtype::ME)\n\t\t\t\t\ttype=\"mdct\";\n\t\t\t\tQByteArray message = formatMessage(type,channel,nick,contents);\n\n\t\t\t\t\/\/change to use write() function when we have time\n\t\t\t\tif(message.length()>0)\n\t\t\t\t{\n\t\t\t\t\tudpSocket.writeDatagram(message,groupAddress,port);\n\t\t\t\t\tlastSent=time(NULL);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if(m.type==\"sendable_notify\")\n\t\t\t{\n\t\t\t\tauto castMessage=dynamic_cast<sendable_notify_message *>(m.getdata());\n\n\t\t\t\t\/\/if it's not actually an edict message, ignore it and move on\n\t\t\t\tif (!castMessage)\n\t\t\t\t\tcontinue;\n\n\t\t\t\tQString nick=settings.value(\"nick\",\"spartacus\").value<QString>();\n\t\t\t\tQString channel=castMessage->channel;\n\t\t\t\tQString contents=castMessage->contents;\n\t\t\t\tQString type=\"ntfy\";\n\n\t\t\t\tQByteArray message = formatMessage(type,channel,nick,contents);\n\n\t\t\t\t\/\/change to use write() function when we have time\n\t\t\t\tif(message.length()>0)\n\t\t\t\t{\n\t\t\t\t\tudpSocket.writeDatagram(message,groupAddress,port);\n\t\t\t\t\tlastSent=time(NULL);\n\t\t\t\t}\n\t\t\t}\n\t\t\t\/\/if somehow a message is recieved that is not of these types, send it back.\n\t\t\telse\n\t\t\t{\n\t\t\t\tp.write(m.decrement_priority());\n\t\t\t}\n\t\t}\n\n\t\twhile (udpSocket.hasPendingDatagrams())\n\t\t{\n\t\t\tchar broadcast[512];\n\t\t\tQHostAddress senderIP;\n\t\t\tquint16 senderPort;\n\t\t\tqint64 size = udpSocket.readDatagram(broadcast,512,&senderIP,&senderPort);\n\t\t\tbroadcast[size]='\\0';\n\t\t\tif(blocklist.end()!=blocklist.find(senderIP))\n\t\t\t\tcontinue;\n\n\t\t\tstring type(broadcast,4);\n\n\t\t\tif (type==\"here\")\n\t\t\t{\n\t\t\t\tp.write(received_message::create(received_message_subtype::HERE,\"\",QString::fromUtf8(broadcast+4),\"\",senderIP));\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t\/\/takes the components out of the broadcast and crops them apropriately, just in case\n\t\t\tQString destinationChannel=QString::fromUtf8(broadcast+4);\n\t\t\tdestinationChannel.truncate(64);\n\t\t\tQString senderNick=QString::fromUtf8(broadcast+68);\n\t\t\tsenderNick.truncate(64);\n\t\t\tQString sentContents=QString::fromUtf8(broadcast+132);\n\t\t\tsentContents.truncate(256);\n\n\t\t\tif (type==\"edct\")\n\t\t\t{\n\t\t\t\tp.write(received_message::create(received_message_subtype::NORMAL,destinationChannel,senderNick,sentContents,senderIP));\n\t\t\t}\n\t\t\telse if (type==\"mdct\")\n\t\t\t{\n\t\t\t\tp.write(received_message::create(received_message_subtype::ME,destinationChannel,senderNick,sentContents,senderIP));\n\t\t\t}\n\t\t\telse if (type==\"ntfy\")\n\t\t\t{\n\t\t\t\tp.write(received_message::create(received_message_subtype::NOTIFY,destinationChannel,senderNick,sentContents,senderIP));\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\n\n\t\t\/\/sends out a \"still here\" message every minute\n\t\tif(time(NULL)-lastSent>60)\n\t\t{\n\t\t\tQString nick=settings.value(\"nick\",\"spartacus\").value<QString>();\n\t\t\tQString type=\"here\";\n\n\t\t\tQByteArray message = type.toUtf8()+nick.toUtf8();\n\t\t\tmessage.truncate(68);\n\n\t\t\tudpSocket.writeDatagram(message,groupAddress,port);\n\t\t\tlastSent=time(NULL);\n\t\t}\n\t\tthis_thread::sleep_for(chrono::milliseconds(50));\n\t}\n};\n\n\/\/stores type in he first 4 bytes, channel in the 64 after that, then 64 for nick, and up to 256 for the contents of the message\nQByteArray formatMessage(QString type, QString channel, QString nick, QString contents)\n{\n\tQByteArray output;\n\toutput += type.toUtf8();\n\toutput += channel.toUtf8().leftJustified(64,'\\0',true);\n\toutput += nick.toUtf8().leftJustified(64,'\\0',true);\n\tQByteArray holder =contents.toUtf8();\n\tif (holder.length()>256)\n\t{\n\t\treturn QByteArray();\n\t}\n\toutput += holder;\n\toutput += '\\0';\n\treturn output;\n};\n<|endoftext|>"} {"text":"<commit_before>\n#include <silicon\/server.hh>\n\niod_define_symbol(module, _Module);\n\nnamespace iod\n{\n std::string javascript_call_procedure();\n\n template <typename S, typename... T>\n std::string generate_javascript_client(const S& s, T... _options)\n {\n auto desc = server_api_description(s);\n\n\n auto opts = D(_options...);\n\n std::ostringstream calls;\n\n auto handlers = s.get_handlers();\n for (int i = 0; i < desc.size(); i++)\n {\n \/\/visit(h)\n calls << \" \/\/ \";\n print_procedure_desc(calls, desc[i]);\n calls << std::endl;\n calls << \" this.\" << desc[i].name << \" = function(params) { return this.call_procedure(\" << i << \", params); }\" << std::endl;\n calls << std::endl;\n }\n\n std::string module = opts.get(_Module, \"sl\");\n\n std::ostringstream src;\n\n src << \"function \" << module << \"() {\" << std::endl;\n src << javascript_call_procedure();\n src << calls.str();\n src << \"}\" << std::endl;\n\n return src.str();\n }\n \n std::string javascript_call_procedure()\n {\n return R\"javascript(\n var server_url = \"\/\";\n this.set_server = function(url) { server_url = url; }\n this.call_procedure = function(id, params)\n {\n \/\/ Return a new promise.\n var _this = this;\n return new Promise(function(resolve, reject) {\n \/\/ Do the usual XHR stuff\n var req = new XMLHttpRequest();\n req.open('POST', _this.server_url);\n\n req.onload = function() {\n \/\/ This is called even on 404 etc\n \/\/ so check the status\n if (req.status == 200) {\n \/\/ Resolve the promise with the response text\n resolve(req.response);\n }\n else {\n \/\/ Otherwise reject with the status text\n \/\/ which will hopefully be a meaningful error\n reject(Error(req.statusText));\n }\n };\n\n \/\/ Handle network errors\n req.onerror = function() {\n reject(Error(\"Network Error\"));\n };\n\n \/\/ Make the request\n body = JSON.stringify({ handler_id: id}) + JSON.stringify(params);\n req.send(body);\n });\n }\n\n\n)javascript\";\n \n }\n}\n<commit_msg>Handle return types of procedures in javascript client.<commit_after>\n#include <silicon\/server.hh>\n\nnamespace iod\n{\n std::string javascript_api_base();\n\n template <typename S, typename... T>\n std::string generate_javascript_client(const S& s, T... _options)\n {\n auto opts = D(_options...);\n std::string module = opts.get(_Module, \"sl\");\n\n auto desc = server_api_description(s);\n\n\n std::ostringstream calls;\n\n auto handlers = s.get_handlers();\n for (int i = 0; i < desc.size(); i++)\n {\n std::string ret = desc[i].return_type;\n if (ret[0] == '{') ret = \"json\";\n\n calls << \" \/\/ \";\n print_procedure_desc(calls, desc[i]);\n calls << std::endl;\n calls << \" \" << module << \".prototype.\" << desc[i].name << \" = function(params) { return this.call_procedure(\" << i << \", params, '\" << ret << \"'); }\" << std::endl;\n calls << std::endl;\n }\n\n\n std::ostringstream src;\n\n src << javascript_api_base();\n src << \"var \" << module << \" = new silicon_api_base();\" << std::endl;\n src << calls.str();\n src << \"}\" << std::endl;\n\n return src.str();\n }\n \n std::string javascript_api_base()\n {\n return R\"javascript(\n\nfunction silicon_api_base()\n{\n this.server_url = \"\/\";\n this.set_server = function(url) { this.server_url = url; }\n this.call_procedure = function(id, params, return_type)\n {\n \/\/ Return a new promise.\n var _this = this;\n return new Promise(function(resolve, reject) {\n \/\/ Do the usual XHR stuff\n var req = new XMLHttpRequest();\n req.open('POST', _this.server_url);\n\n req.onload = function() {\n \/\/ This is called even on 404 etc\n \/\/ so check the status\n if (req.status == 200) {\n \/\/ Resolve the promise with the response text\n switch (return_type) {\n case \"int\": resolve(parseInt(req.response)); break;\n case \"float\": resolve(parseFloat(req.response)); break;\n case \"json\": resolve(JSON.parse(req.response)); break;\n default: resolve(req.response); break;\n }\n else {\n \/\/ Otherwise reject with the request object.\n reject(req);\n }\n };\n\n \/\/ Handle network errors\n req.onerror = function() {\n reject(Error(\"Network Error\"));\n };\n\n \/\/ Make the request\n body = JSON.stringify({ handler_id: id}) + JSON.stringify(params);\n req.send(body);\n });\n }\n\n\n}\n\n)javascript\";\n \n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ __BEGIN_LICENSE__\n\/\/ Copyright (C) 2006-2010 United States Government as represented by\n\/\/ the Administrator of the National Aeronautics and Space Administration.\n\/\/ All Rights Reserved.\n\/\/ __END_LICENSE__\n\n\n#include <vw\/BundleAdjustment\/BundleAdjustReport.h>\nnamespace fs = boost::filesystem;\n\nnamespace vw {\nnamespace ba {\n\n void write_kml_styles( KMLFile& kml ) {\n \/\/ GCP Placemark Style\n kml.append_style( \"gcp_circle\", \"\", 1.2,\n \"http:\/\/maps.google.com\/mapfiles\/kml\/shapes\/placemark_circle.png\" );\n kml.append_style( \"gcp_circle_highlight\", \"\", 1.4,\n \"http:\/\/maps.google.com\/mapfiles\/kml\/shapes\/placemark_circle_highlight.png\" );\n kml.append_stylemap( \"gcp_placemark\", \"gcp_circle\",\n \"gcp_circle_highlight\" );\n\n \/\/ Est Circle Lvl 1 (Green) Placemark\n kml.append_style( \"est_circle_1\", \"ff00ff00\", 0.8,\n \"http:\/\/maps.google.com\/mapfiles\/kml\/shapes\/shaded_dot.png\" );\n kml.append_style( \"est_circle_1_highlight\", \"ff00ff00\", 0.9,\n \"http:\/\/maps.google.com\/mapfiles\/kml\/shapes\/shaded_dot.png\" );\n kml.append_stylemap( \"est_placemark_1\", \"est_circle_1\",\n \"est_circle_1_highlight\" );\n\n \/\/ Est Circle Lvl 2 (Green-Yellow) Placemark\n kml.append_style( \"est_circle_2\", \"ff00ff80\", 0.8,\n \"http:\/\/maps.google.com\/mapfiles\/kml\/shapes\/shaded_dot.png\" );\n kml.append_style( \"est_circle_2_highlight\", \"ff00ff80\", 0.9,\n \"http:\/\/maps.google.com\/mapfiles\/kml\/shapes\/shaded_dot.png\" );\n kml.append_stylemap( \"est_placemark_2\", \"est_circle_2\",\n \"est_circle_2_highlight\" );\n\n \/\/ Est Circle Lvl 3 (Yellow) Placemark\n kml.append_style( \"est_circle_3\", \"ff00ffff\", 0.8,\n \"http:\/\/maps.google.com\/mapfiles\/kml\/shapes\/shaded_dot.png\" );\n kml.append_style( \"est_circle_3_highlight\", \"ff00ffff\", 0.9,\n \"http:\/\/maps.google.com\/mapfiles\/kml\/shapes\/shaded_dot.png\" );\n kml.append_stylemap( \"est_placemark_3\", \"est_circle_3\",\n \"est_circle_3_highlight\" );\n\n \/\/ Est Circle Lvl 4 (Red-Yellow) Placemark\n kml.append_style( \"est_circle_4\", \"ff0080ff\", 0.8,\n \"http:\/\/maps.google.com\/mapfiles\/kml\/shapes\/shaded_dot.png\" );\n kml.append_style( \"est_circle_4_highlight\", \"ff0080ff\", 0.9,\n \"http:\/\/maps.google.com\/mapfiles\/kml\/shapes\/shaded_dot.png\" );\n kml.append_stylemap( \"est_placemark_4\", \"est_circle_4\",\n \"est_circle_4_highlight\" );\n\n \/\/ Est Circle Lvl 5 (Red) Placemark\n kml.append_style( \"est_circle_5\", \"ff0000ff\", 0.8,\n \"http:\/\/maps.google.com\/mapfiles\/kml\/shapes\/shaded_dot.png\" );\n kml.append_style( \"est_circle_5_highlight\", \"ff0000ff\", 0.9,\n \"http:\/\/maps.google.com\/mapfiles\/kml\/shapes\/shaded_dot.png\" );\n kml.append_stylemap( \"est_placemark_5\", \"est_circle_5\",\n \"est_circle_5_highlight\" );\n }\n\n void write_gcps_kml( KMLFile& kml,\n ControlNetwork const& cnet ) {\n kml.enter_folder( \"Ground Control Points\",\n \"Used for Bundle Adjustment in VW\" );\n\n unsigned count = 0;\n for ( ControlNetwork::const_iterator iter = cnet.begin();\n iter != cnet.end(); ++iter ) {\n if ( (*iter).type() == ControlPoint::GroundControlPoint ) {\n count++;\n Vector3 llr = cartography::xyz_to_lon_lat_radius( (*iter).position() );\n\n std::ostringstream desc;\n \/\/ GCP data\n desc << \"<h2>Ground Control Point<\/h2>\";\n desc << \"<b>Lon:<\/b> \" << llr.x() << \" deg<br>\";\n desc << \"<b>Lat:<\/b> \" << llr.y() << \" deg<br>\";\n desc << \"<b>Rad:<\/b> \" << llr.z() << \" m<br>\";\n\n \/\/ Images viewing\n desc << \"<h3>Viewed by:<\/h3><ol>\";\n for ( ControlPoint::const_iterator measure = (*iter).begin();\n measure != (*iter).end(); ++measure ) {\n desc << \"<li>\" << \"[\" << (*measure).image_id() << \"] \"\n << (*measure).serial() << \"<\/li>\";\n }\n desc << \"<\/ol>\";\n\n if ( (*iter).id() != \"Null\" ) {\n kml.append_placemark( llr.x(), llr.y(),\n (*iter).id(), desc.str(),\n \"gcp_placemark\" );\n } else {\n std::ostringstream gcp_name;\n gcp_name << \"GCP \" << count;\n kml.append_placemark( llr.x(), llr.y(),\n gcp_name.str(), desc.str(),\n \"gcp_placemark\" );\n }\n }\n }\n\n kml.exit_folder();\n }\n\n void write_3d_est_kml( KMLFile& kml,\n ControlNetwork const& cnet,\n std::vector<double>& image_errors ) {\n kml.enter_folder( \"3D Point estimates\",\n \"Used for Bundle Adjustment in VW\" );\n\n std::list<Vector3> points; \/\/ Lon, Lat, Interest\n\n unsigned index = 0;\n for ( ControlNetwork::const_iterator iter = cnet.begin();\n iter != cnet.end(); ++iter ) {\n Vector3 llr = cartography::xyz_to_lon_lat_radius( (*iter).position() );\n double mean_image_error = 0;\n int count_measures = 0;\n for ( ControlPoint::const_iterator m_iter = (*iter).begin();\n m_iter != (*iter).end(); ++m_iter ) {\n mean_image_error += image_errors[index];\n index++;\n count_measures++;\n }\n mean_image_error \/= count_measures;\n if ( (*iter).type() == ControlPoint::TiePoint )\n points.push_back( Vector3(llr.x(),llr.y(), mean_image_error) );\n }\n\n \/\/ Grow a bounding box\n BBox2 total;\n for ( std::list<Vector3>::iterator it = points.begin();\n it != points.end(); ++it )\n total.grow( Vector2((*it).x(),(*it).y()) );\n\n \/\/ Building tiles of smaller bounding boxes\n Vector2f lower_corner = total.min();\n Vector2f upper_corner = total.max();\n lower_corner.x() = floor( lower_corner.x() );\n lower_corner.y() = floor( lower_corner.y() );\n upper_corner.x() = ceil( upper_corner.x() );\n upper_corner.y() = ceil( upper_corner.y() );\n\n \/\/ Finding the maximium and minimium error\n double min = 1e20, max = -1;\n for ( std::list<Vector3>::iterator it = points.begin();\n it != points.end(); ++it ) {\n if ( (*it).z() < min )\n min = (*it).z();\n if ( (*it).z() > max )\n max = (*it).z();\n }\n\n recursive_kml_placemark( kml, points, kml.name(), min, max,\n upper_corner.y(), lower_corner.y(),\n upper_corner.x(), lower_corner.x(), 0 );\n\n kml.exit_folder();\n }\n\n void recursive_kml_placemark( KMLFile& kml,\n std::list<Vector3>& list,\n std::string const& name,\n double& min, double& max,\n float& north, float& south,\n float& east, float& west,\n int recursive_lvl) {\n \/\/ Sub divides\n std::vector<float> north_dv;\n north_dv.push_back(north); north_dv.push_back(north);\n north_dv.push_back(south+(north-south)\/2);\n north_dv.push_back( north_dv[2] );\n std::vector<float> south_dv;\n south_dv.push_back( north_dv[3] ); south_dv.push_back( north_dv[3] );\n south_dv.push_back( south ); south_dv.push_back( south );\n std::vector<float> east_dv;\n east_dv.push_back( east ); east_dv.push_back( west + (east-west)\/2 );\n east_dv.push_back( east_dv[0] ); east_dv.push_back( east_dv[1] );\n std::vector<float> west_dv;\n west_dv.push_back( east_dv[1] ); west_dv.push_back( west );\n west_dv.push_back( west_dv[0] ); west_dv.push_back( west_dv[1] );\n double diff = max - min;\n\n \/\/ Checking list\n int count = 0;\n for ( std::list<Vector3>::iterator it = list.begin();\n it != list.end(); ++it )\n count++;\n if ( count <= 500 ) {\n \/\/ Write a termination file\n kml.enter_folder(\"\",\"\");\n\n \/\/ Regioning\n kml.open_bracket(\"Region\");\n kml.append_latlonaltbox( north, south, east, west );\n kml.append_lod( 512, -1 );\n kml.close_bracket();\n\n \/\/ Placemarks\n for ( std::list<Vector3>::iterator it = list.begin();\n it != list.end(); ++it ) {\n std::ostringstream desc;\n desc << \"Image error: \" << (*it).z();\n if ( (*it).z() > 4*diff\/5 + min )\n kml.append_placemark( (*it).x(), (*it).y(),\n \"\", desc.str(),\n \"est_placemark_5\" );\n else if ( (*it).z() > 3*diff\/5 + min )\n kml.append_placemark( (*it).x(), (*it).y(),\n \"\", desc.str(),\n \"est_placemark_4\" );\n else if ( (*it).z() > 2*diff\/5 + min )\n kml.append_placemark( (*it).x(), (*it).y(),\n \"\", desc.str(),\n \"est_placemark_3\" );\n else if ( (*it).z() > 1*diff\/5 + min )\n kml.append_placemark( (*it).x(), (*it).y(),\n \"\", desc.str(),\n \"est_placemark_2\" );\n else\n kml.append_placemark( (*it).x(), (*it).y(),\n \"\", desc.str(),\n \"est_placemark_1\" );\n }\n\n kml.exit_folder();\n return;\n } else {\n \/\/ Write a branching file\n list.sort( vector_sorting );\n\n kml.enter_folder(\"\",\"\");\n\n for ( char i = 0; i < 4; i++ ) {\n std::ostringstream link;\n if ( recursive_lvl == 0 )\n link << \"data\/\";\n link << name << int(i) << \".kml\";\n kml.append_network( link.str(),\n north_dv[i], south_dv[i],\n east_dv[i], west_dv[i] );\n }\n\n kml.enter_folder(\"\",\"\");\n\n \/\/ Regioning\n kml.open_bracket(\"Region\");\n kml.append_latlonaltbox( north, south, east, west );\n kml.append_lod( 512, -1 );\n kml.close_bracket();\n\n \/\/ Placemarks\n count = 500;\n std::list<Vector3>::iterator it = list.begin();\n while ( count > 0 ) {\n std::ostringstream desc;\n desc << \"Image error: \" << (*it).z();\n if ( (*it).z() > 4*diff\/5 + min )\n kml.append_placemark( (*it).x(), (*it).y(),\n \"\", desc.str(),\n \"est_placemark_5\" );\n else if ( (*it).z() > 3*diff\/5 + min )\n kml.append_placemark( (*it).x(), (*it).y(),\n \"\", desc.str(),\n \"est_placemark_4\" );\n else if ( (*it).z() > 2*diff\/5 + min )\n kml.append_placemark( (*it).x(), (*it).y(),\n \"\", desc.str(),\n \"est_placemark_3\" );\n else if ( (*it).z() > 1*diff\/5 + min )\n kml.append_placemark( (*it).x(), (*it).y(),\n \"\", desc.str(),\n \"est_placemark_2\" );\n else\n kml.append_placemark( (*it).x(), (*it).y(),\n \"\", desc.str(),\n \"est_placemark_1\" );\n it = list.erase( it );\n count--;\n }\n\n kml.exit_folder();\n kml.exit_folder();\n }\n\n \/\/ Making calls to make lower levels\n for ( char i = 0; i < 4; i++ ) {\n std::list<Vector3> temp;\n for ( std::list<Vector3>::iterator it = list.begin();\n it != list.end(); ++it )\n if ( (*it).y() < north_dv[i] && (*it).y() > south_dv[i] &&\n (*it).x() < east_dv[i] && (*it).x() > west_dv[i] ) {\n temp.push_back( *it );\n it = list.erase( it );\n it--;\n }\n if ( !temp.empty() ) {\n std::ostringstream new_name;\n new_name << name << int(i);\n std::ostringstream dir;\n if ( kml.directory() != \"\" )\n dir << kml.directory() << \"\/\";\n if ( recursive_lvl == 0 )\n dir << \"data\/\";\n KMLFile subsection( new_name.str() + \".kml\",\n new_name.str(), dir.str() );\n write_kml_styles( subsection );\n recursive_kml_placemark( subsection,\n temp, new_name.str(),\n min, max,\n north_dv[i], south_dv[i],\n east_dv[i], west_dv[i],\n recursive_lvl+1 );\n }\n }\n\n if ( !list.empty() )\n std::cout << \"Error! Vector not empty!\\n\";\n\n }\n\n bool vector_sorting( Vector3 i, Vector3 j) {\n return (i.z() > j.z());\n }\n\n}}\n<commit_msg>Increased precision in BA report KML.<commit_after>\/\/ __BEGIN_LICENSE__\n\/\/ Copyright (C) 2006-2010 United States Government as represented by\n\/\/ the Administrator of the National Aeronautics and Space Administration.\n\/\/ All Rights Reserved.\n\/\/ __END_LICENSE__\n\n\n#include <vw\/BundleAdjustment\/BundleAdjustReport.h>\nnamespace fs = boost::filesystem;\n\nnamespace vw {\nnamespace ba {\n\n void write_kml_styles( KMLFile& kml ) {\n \/\/ GCP Placemark Style\n kml.append_style( \"gcp_circle\", \"\", 1.2,\n \"http:\/\/maps.google.com\/mapfiles\/kml\/shapes\/placemark_circle.png\" );\n kml.append_style( \"gcp_circle_highlight\", \"\", 1.4,\n \"http:\/\/maps.google.com\/mapfiles\/kml\/shapes\/placemark_circle_highlight.png\" );\n kml.append_stylemap( \"gcp_placemark\", \"gcp_circle\",\n \"gcp_circle_highlight\" );\n\n \/\/ Est Circle Lvl 1 (Green) Placemark\n kml.append_style( \"est_circle_1\", \"ff00ff00\", 0.8,\n \"http:\/\/maps.google.com\/mapfiles\/kml\/shapes\/shaded_dot.png\" );\n kml.append_style( \"est_circle_1_highlight\", \"ff00ff00\", 0.9,\n \"http:\/\/maps.google.com\/mapfiles\/kml\/shapes\/shaded_dot.png\" );\n kml.append_stylemap( \"est_placemark_1\", \"est_circle_1\",\n \"est_circle_1_highlight\" );\n\n \/\/ Est Circle Lvl 2 (Green-Yellow) Placemark\n kml.append_style( \"est_circle_2\", \"ff00ff80\", 0.8,\n \"http:\/\/maps.google.com\/mapfiles\/kml\/shapes\/shaded_dot.png\" );\n kml.append_style( \"est_circle_2_highlight\", \"ff00ff80\", 0.9,\n \"http:\/\/maps.google.com\/mapfiles\/kml\/shapes\/shaded_dot.png\" );\n kml.append_stylemap( \"est_placemark_2\", \"est_circle_2\",\n \"est_circle_2_highlight\" );\n\n \/\/ Est Circle Lvl 3 (Yellow) Placemark\n kml.append_style( \"est_circle_3\", \"ff00ffff\", 0.8,\n \"http:\/\/maps.google.com\/mapfiles\/kml\/shapes\/shaded_dot.png\" );\n kml.append_style( \"est_circle_3_highlight\", \"ff00ffff\", 0.9,\n \"http:\/\/maps.google.com\/mapfiles\/kml\/shapes\/shaded_dot.png\" );\n kml.append_stylemap( \"est_placemark_3\", \"est_circle_3\",\n \"est_circle_3_highlight\" );\n\n \/\/ Est Circle Lvl 4 (Red-Yellow) Placemark\n kml.append_style( \"est_circle_4\", \"ff0080ff\", 0.8,\n \"http:\/\/maps.google.com\/mapfiles\/kml\/shapes\/shaded_dot.png\" );\n kml.append_style( \"est_circle_4_highlight\", \"ff0080ff\", 0.9,\n \"http:\/\/maps.google.com\/mapfiles\/kml\/shapes\/shaded_dot.png\" );\n kml.append_stylemap( \"est_placemark_4\", \"est_circle_4\",\n \"est_circle_4_highlight\" );\n\n \/\/ Est Circle Lvl 5 (Red) Placemark\n kml.append_style( \"est_circle_5\", \"ff0000ff\", 0.8,\n \"http:\/\/maps.google.com\/mapfiles\/kml\/shapes\/shaded_dot.png\" );\n kml.append_style( \"est_circle_5_highlight\", \"ff0000ff\", 0.9,\n \"http:\/\/maps.google.com\/mapfiles\/kml\/shapes\/shaded_dot.png\" );\n kml.append_stylemap( \"est_placemark_5\", \"est_circle_5\",\n \"est_circle_5_highlight\" );\n }\n\n void write_gcps_kml( KMLFile& kml,\n ControlNetwork const& cnet ) {\n kml.enter_folder( \"Ground Control Points\",\n \"Used for Bundle Adjustment in VW\" );\n\n unsigned count = 0;\n for ( ControlNetwork::const_iterator iter = cnet.begin();\n iter != cnet.end(); ++iter ) {\n if ( (*iter).type() == ControlPoint::GroundControlPoint ) {\n count++;\n Vector3 llr = cartography::xyz_to_lon_lat_radius( (*iter).position() );\n\n std::ostringstream desc;\n \/\/ GCP data\n desc << \"<h2>Ground Control Point<\/h2>\";\n desc << \"<b>Lon:<\/b> \" << llr.x() << \" deg<br>\";\n desc << \"<b>Lat:<\/b> \" << llr.y() << \" deg<br>\";\n desc << \"<b>Rad:<\/b> \" << std::setprecision(12)\n << llr.z() << \" m<br>\";\n\n \/\/ Images viewing\n desc << \"<h3>Viewed by:<\/h3><ol>\";\n for ( ControlPoint::const_iterator measure = (*iter).begin();\n measure != (*iter).end(); ++measure ) {\n desc << \"<li>\" << \"[\" << (*measure).image_id() << \"] \"\n << (*measure).serial() << \" ( \" << measure->position()[0] << \", \"\n << measure->position()[1] << \" ) \" << \"<\/li>\";\n }\n desc << \"<\/ol>\";\n\n if ( (*iter).id() != \"Null\" ) {\n kml.append_placemark( llr.x(), llr.y(),\n (*iter).id(), desc.str(),\n \"gcp_placemark\" );\n } else {\n std::ostringstream gcp_name;\n gcp_name << \"GCP \" << count;\n kml.append_placemark( llr.x(), llr.y(),\n gcp_name.str(), desc.str(),\n \"gcp_placemark\" );\n }\n }\n }\n\n kml.exit_folder();\n }\n\n void write_3d_est_kml( KMLFile& kml,\n ControlNetwork const& cnet,\n std::vector<double>& image_errors ) {\n kml.enter_folder( \"3D Point estimates\",\n \"Used for Bundle Adjustment in VW\" );\n\n std::list<Vector3> points; \/\/ Lon, Lat, Interest\n\n unsigned index = 0;\n for ( ControlNetwork::const_iterator iter = cnet.begin();\n iter != cnet.end(); ++iter ) {\n Vector3 llr = cartography::xyz_to_lon_lat_radius( (*iter).position() );\n double mean_image_error = 0;\n int count_measures = 0;\n for ( ControlPoint::const_iterator m_iter = (*iter).begin();\n m_iter != (*iter).end(); ++m_iter ) {\n mean_image_error += image_errors[index];\n index++;\n count_measures++;\n }\n mean_image_error \/= count_measures;\n if ( (*iter).type() == ControlPoint::TiePoint )\n points.push_back( Vector3(llr.x(),llr.y(), mean_image_error) );\n }\n\n \/\/ Grow a bounding box\n BBox2 total;\n for ( std::list<Vector3>::iterator it = points.begin();\n it != points.end(); ++it )\n total.grow( Vector2((*it).x(),(*it).y()) );\n\n \/\/ Building tiles of smaller bounding boxes\n Vector2f lower_corner = total.min();\n Vector2f upper_corner = total.max();\n lower_corner.x() = floor( lower_corner.x() );\n lower_corner.y() = floor( lower_corner.y() );\n upper_corner.x() = ceil( upper_corner.x() );\n upper_corner.y() = ceil( upper_corner.y() );\n\n \/\/ Finding the maximium and minimium error\n double min = 1e20, max = -1;\n for ( std::list<Vector3>::iterator it = points.begin();\n it != points.end(); ++it ) {\n if ( (*it).z() < min )\n min = (*it).z();\n if ( (*it).z() > max )\n max = (*it).z();\n }\n\n recursive_kml_placemark( kml, points, kml.name(), min, max,\n upper_corner.y(), lower_corner.y(),\n upper_corner.x(), lower_corner.x(), 0 );\n\n kml.exit_folder();\n }\n\n void recursive_kml_placemark( KMLFile& kml,\n std::list<Vector3>& list,\n std::string const& name,\n double& min, double& max,\n float& north, float& south,\n float& east, float& west,\n int recursive_lvl) {\n \/\/ Sub divides\n std::vector<float> north_dv;\n north_dv.push_back(north); north_dv.push_back(north);\n north_dv.push_back(south+(north-south)\/2);\n north_dv.push_back( north_dv[2] );\n std::vector<float> south_dv;\n south_dv.push_back( north_dv[3] ); south_dv.push_back( north_dv[3] );\n south_dv.push_back( south ); south_dv.push_back( south );\n std::vector<float> east_dv;\n east_dv.push_back( east ); east_dv.push_back( west + (east-west)\/2 );\n east_dv.push_back( east_dv[0] ); east_dv.push_back( east_dv[1] );\n std::vector<float> west_dv;\n west_dv.push_back( east_dv[1] ); west_dv.push_back( west );\n west_dv.push_back( west_dv[0] ); west_dv.push_back( west_dv[1] );\n double diff = max - min;\n\n \/\/ Checking list\n int count = 0;\n for ( std::list<Vector3>::iterator it = list.begin();\n it != list.end(); ++it )\n count++;\n if ( count <= 500 ) {\n \/\/ Write a termination file\n kml.enter_folder(\"\",\"\");\n\n \/\/ Regioning\n kml.open_bracket(\"Region\");\n kml.append_latlonaltbox( north, south, east, west );\n kml.append_lod( 512, -1 );\n kml.close_bracket();\n\n \/\/ Placemarks\n for ( std::list<Vector3>::iterator it = list.begin();\n it != list.end(); ++it ) {\n std::ostringstream desc;\n desc << \"Image error: \" << (*it).z();\n if ( (*it).z() > 4*diff\/5 + min )\n kml.append_placemark( (*it).x(), (*it).y(),\n \"\", desc.str(),\n \"est_placemark_5\" );\n else if ( (*it).z() > 3*diff\/5 + min )\n kml.append_placemark( (*it).x(), (*it).y(),\n \"\", desc.str(),\n \"est_placemark_4\" );\n else if ( (*it).z() > 2*diff\/5 + min )\n kml.append_placemark( (*it).x(), (*it).y(),\n \"\", desc.str(),\n \"est_placemark_3\" );\n else if ( (*it).z() > 1*diff\/5 + min )\n kml.append_placemark( (*it).x(), (*it).y(),\n \"\", desc.str(),\n \"est_placemark_2\" );\n else\n kml.append_placemark( (*it).x(), (*it).y(),\n \"\", desc.str(),\n \"est_placemark_1\" );\n }\n\n kml.exit_folder();\n return;\n } else {\n \/\/ Write a branching file\n list.sort( vector_sorting );\n\n kml.enter_folder(\"\",\"\");\n\n for ( char i = 0; i < 4; i++ ) {\n std::ostringstream link;\n if ( recursive_lvl == 0 )\n link << \"data\/\";\n link << name << int(i) << \".kml\";\n kml.append_network( link.str(),\n north_dv[i], south_dv[i],\n east_dv[i], west_dv[i] );\n }\n\n kml.enter_folder(\"\",\"\");\n\n \/\/ Regioning\n kml.open_bracket(\"Region\");\n kml.append_latlonaltbox( north, south, east, west );\n kml.append_lod( 512, -1 );\n kml.close_bracket();\n\n \/\/ Placemarks\n count = 500;\n std::list<Vector3>::iterator it = list.begin();\n while ( count > 0 ) {\n std::ostringstream desc;\n desc << \"Image error: \" << (*it).z();\n if ( (*it).z() > 4*diff\/5 + min )\n kml.append_placemark( (*it).x(), (*it).y(),\n \"\", desc.str(),\n \"est_placemark_5\" );\n else if ( (*it).z() > 3*diff\/5 + min )\n kml.append_placemark( (*it).x(), (*it).y(),\n \"\", desc.str(),\n \"est_placemark_4\" );\n else if ( (*it).z() > 2*diff\/5 + min )\n kml.append_placemark( (*it).x(), (*it).y(),\n \"\", desc.str(),\n \"est_placemark_3\" );\n else if ( (*it).z() > 1*diff\/5 + min )\n kml.append_placemark( (*it).x(), (*it).y(),\n \"\", desc.str(),\n \"est_placemark_2\" );\n else\n kml.append_placemark( (*it).x(), (*it).y(),\n \"\", desc.str(),\n \"est_placemark_1\" );\n it = list.erase( it );\n count--;\n }\n\n kml.exit_folder();\n kml.exit_folder();\n }\n\n \/\/ Making calls to make lower levels\n for ( char i = 0; i < 4; i++ ) {\n std::list<Vector3> temp;\n for ( std::list<Vector3>::iterator it = list.begin();\n it != list.end(); ++it )\n if ( (*it).y() < north_dv[i] && (*it).y() > south_dv[i] &&\n (*it).x() < east_dv[i] && (*it).x() > west_dv[i] ) {\n temp.push_back( *it );\n it = list.erase( it );\n it--;\n }\n if ( !temp.empty() ) {\n std::ostringstream new_name;\n new_name << name << int(i);\n std::ostringstream dir;\n if ( kml.directory() != \"\" )\n dir << kml.directory() << \"\/\";\n if ( recursive_lvl == 0 )\n dir << \"data\/\";\n KMLFile subsection( new_name.str() + \".kml\",\n new_name.str(), dir.str() );\n write_kml_styles( subsection );\n recursive_kml_placemark( subsection,\n temp, new_name.str(),\n min, max,\n north_dv[i], south_dv[i],\n east_dv[i], west_dv[i],\n recursive_lvl+1 );\n }\n }\n\n if ( !list.empty() )\n std::cout << \"Error! Vector not empty!\\n\";\n\n }\n\n bool vector_sorting( Vector3 i, Vector3 j) {\n return (i.z() > j.z());\n }\n\n}}\n<|endoftext|>"} {"text":"<commit_before>\/*******************************************************************************\n\nLicensed to the OpenCOR team under one or more contributor license agreements.\nSee the NOTICE.txt file distributed with this work for additional information\nregarding copyright ownership. The OpenCOR team licenses this file to you under\nthe Apache License, Version 2.0 (the \"License\"); you may not use this file\nexcept in compliance with the License. You may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software distributed\nunder the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR\nCONDITIONS OF ANY KIND, either express or implied. See the License for the\nspecific language governing permissions and limitations under the License.\n\n*******************************************************************************\/\n\n\/\/==============================================================================\n\/\/ User message widget\n\/\/==============================================================================\n\n#include \"guiutils.h\"\n#include \"usermessagewidget.h\"\n\n\/\/==============================================================================\n\n#include <Qt>\n\n\/\/==============================================================================\n\n#include <QBuffer>\n#include <QFont>\n#include <QIcon>\n#include <QSizePolicy>\n#include <QWidget>\n\n\/\/==============================================================================\n\nnamespace OpenCOR {\nnamespace Core {\n\n\/\/==============================================================================\n\nvoid UserMessageWidget::constructor(const QString &pIcon,\n const QString &pMessage,\n const QString &pExtraMessage)\n{\n \/\/ Some initialisations\n\n mIcon = QString();\n mMessage = QString();\n mExtraMessage = QString();\n\n \/\/ Customise our background\n\n setAutoFillBackground(true);\n setBackgroundRole(QPalette::Base);\n\n \/\/ Increase the size of our font\n\n QFont newFont = font();\n\n newFont.setPointSizeF(1.35*newFont.pointSize());\n\n setFont(newFont);\n\n \/\/ Some other customisations\n\n setContextMenuPolicy(Qt::NoContextMenu);\n setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);\n setWordWrap(true);\n\n \/\/ 'Initialise' our message\n\n setIconMessage(pIcon, pMessage, pExtraMessage);\n}\n\n\/\/==============================================================================\n\nUserMessageWidget::UserMessageWidget(const QString &pIcon,\n const QString &pMessage,\n const QString &pExtraMessage,\n QWidget *pParent) :\n QLabel(pParent)\n{\n \/\/ Construct our object\n\n constructor(pIcon, pMessage, pExtraMessage);\n}\n\n\/\/==============================================================================\n\nUserMessageWidget::UserMessageWidget(const QString &pIcon,\n const QString &pMessage,\n QWidget *pParent) :\n QLabel(pParent)\n{\n \/\/ Construct our object\n\n constructor(pIcon, pMessage);\n}\n\n\/\/==============================================================================\n\nUserMessageWidget::UserMessageWidget(const QString &pIcon, QWidget *pParent) :\n QLabel(pParent)\n{\n \/\/ Construct our object\n\n constructor(pIcon);\n}\n\n\/\/==============================================================================\n\nUserMessageWidget::UserMessageWidget(QWidget *pParent) :\n QLabel(pParent)\n{\n \/\/ Construct our object\n\n constructor();\n}\n\n\/\/==============================================================================\n\nvoid UserMessageWidget::setIconMessage(const QString &pIcon,\n const QString &pMessage,\n const QString &pExtraMessage)\n{\n \/\/ Set our message, if needed\n\n if ( pIcon.compare(mIcon)\n || pMessage.compare(mMessage)\n || pExtraMessage.compare(mExtraMessage)) {\n \/\/ Keep track of the new values for our icon, message and extra message\n\n mIcon = pIcon;\n mMessage = pMessage;\n mExtraMessage = pExtraMessage;\n\n \/\/ Set our text as HTML\n \/\/ Note: we want our icon to have a final size of 32px by 32px. However,\n \/\/ it may be that it has a different size to begin with. Normally,\n \/\/ we would rely on QLabel's HTML support (and in particular on\n \/\/ the width and height attributes of the img element) to have our\n \/\/ icon resized for us, but this results in a pixelated and\n \/\/ therefore ugly image. So, instead, we retrieve a data URI for\n \/\/ our resized icon...\n\n if (mExtraMessage.isEmpty())\n setText(QString(\"<table align=center>\"\n \" <tbody>\"\n \" <tr valign=middle>\"\n \" <td>\"\n \" <img src=\\\"%1\\\"\/>\"\n \" <\/td>\"\n \" <td align=center>\"\n \" <p style=\\\"margin: 0px;\\\">\"\n \" %2\"\n \" <\/p>\"\n \" <\/td>\"\n \" <\/tr>\"\n \" <\/tbody>\"\n \"<\/table>\").arg(iconDataUri(mIcon, 32, 32), mMessage));\n else\n setText(QString(\"<table align=center>\"\n \" <tbody>\"\n \" <tr valign=middle>\"\n \" <td>\"\n \" <img src=\\\"%1\\\"\/>\"\n \" <\/td>\"\n \" <td align=center>\"\n \" <p style=\\\"margin: 0px;\\\">\"\n \" %2\"\n \" <\/p>\"\n \" <p style=\\\"margin: 0px;\\\">\"\n \" <small><em>(%3)<\/em><\/small>\"\n \" <\/p>\"\n \" <\/td>\"\n \" <\/tr>\"\n \" <\/tbody>\"\n \"<\/table>\").arg(iconDataUri(mIcon, 32, 32), mMessage, mExtraMessage));\n }\n}\n\n\/\/==============================================================================\n\nvoid UserMessageWidget::setMessage(const QString &pMessage,\n const QString &pExtraMessage)\n{\n \/\/ Set our message\n\n setIconMessage(mIcon, pMessage, pExtraMessage);\n}\n\n\/\/==============================================================================\n\n} \/\/ namespace Core\n} \/\/ namespace OpenCOR\n\n\/\/==============================================================================\n\/\/ End of file\n\/\/==============================================================================\n<commit_msg>Slight improvement to Core::UserMessageWidget.<commit_after>\/*******************************************************************************\n\nLicensed to the OpenCOR team under one or more contributor license agreements.\nSee the NOTICE.txt file distributed with this work for additional information\nregarding copyright ownership. The OpenCOR team licenses this file to you under\nthe Apache License, Version 2.0 (the \"License\"); you may not use this file\nexcept in compliance with the License. You may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software distributed\nunder the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR\nCONDITIONS OF ANY KIND, either express or implied. See the License for the\nspecific language governing permissions and limitations under the License.\n\n*******************************************************************************\/\n\n\/\/==============================================================================\n\/\/ User message widget\n\/\/==============================================================================\n\n#include \"guiutils.h\"\n#include \"usermessagewidget.h\"\n\n\/\/==============================================================================\n\n#include <Qt>\n\n\/\/==============================================================================\n\n#include <QBuffer>\n#include <QFont>\n#include <QIcon>\n#include <QSizePolicy>\n#include <QWidget>\n\n\/\/==============================================================================\n\nnamespace OpenCOR {\nnamespace Core {\n\n\/\/==============================================================================\n\nvoid UserMessageWidget::constructor(const QString &pIcon,\n const QString &pMessage,\n const QString &pExtraMessage)\n{\n \/\/ Some initialisations\n\n mIcon = QString();\n mMessage = QString();\n mExtraMessage = QString();\n\n \/\/ Customise our background\n\n setAutoFillBackground(true);\n setBackgroundRole(QPalette::Base);\n\n \/\/ Increase the size of our font\n\n QFont newFont = font();\n\n newFont.setPointSizeF(1.35*newFont.pointSize());\n\n setFont(newFont);\n\n \/\/ Some other customisations\n\n setContextMenuPolicy(Qt::NoContextMenu);\n setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);\n setWordWrap(true);\n\n \/\/ 'Initialise' our message\n\n setIconMessage(pIcon, pMessage, pExtraMessage);\n}\n\n\/\/==============================================================================\n\nUserMessageWidget::UserMessageWidget(const QString &pIcon,\n const QString &pMessage,\n const QString &pExtraMessage,\n QWidget *pParent) :\n QLabel(pParent)\n{\n \/\/ Construct our object\n\n constructor(pIcon, pMessage, pExtraMessage);\n}\n\n\/\/==============================================================================\n\nUserMessageWidget::UserMessageWidget(const QString &pIcon,\n const QString &pMessage,\n QWidget *pParent) :\n QLabel(pParent)\n{\n \/\/ Construct our object\n\n constructor(pIcon, pMessage);\n}\n\n\/\/==============================================================================\n\nUserMessageWidget::UserMessageWidget(const QString &pIcon, QWidget *pParent) :\n QLabel(pParent)\n{\n \/\/ Construct our object\n\n constructor(pIcon);\n}\n\n\/\/==============================================================================\n\nUserMessageWidget::UserMessageWidget(QWidget *pParent) :\n QLabel(pParent)\n{\n \/\/ Construct our object\n\n constructor();\n}\n\n\/\/==============================================================================\n\nvoid UserMessageWidget::setIconMessage(const QString &pIcon,\n const QString &pMessage,\n const QString &pExtraMessage)\n{\n \/\/ Set our message, if needed\n\n if ( pIcon.compare(mIcon)\n || pMessage.compare(mMessage)\n || pExtraMessage.compare(mExtraMessage)) {\n \/\/ Keep track of the new values for our icon, message and extra message\n\n mIcon = pIcon;\n mMessage = pMessage;\n mExtraMessage = pExtraMessage;\n\n \/\/ Set our text as HTML\n \/\/ Note: we want our icon to have a final size of 32px by 32px. However,\n \/\/ it may be that it has a different size to begin with. Normally,\n \/\/ we would rely on QLabel's HTML support (and in particular on\n \/\/ the width and height attributes of the img element) to have our\n \/\/ icon resized for us, but this results in a pixelated and\n \/\/ therefore ugly image. So, instead, we retrieve a data URI for\n \/\/ our resized icon...\n\n if (mExtraMessage.isEmpty())\n setText(QString(\"<table align=center>\"\n \" <tbody>\"\n \" <tr valign=middle>\"\n \" <td>\"\n \" <img src=\\\"%1\\\"\/>\"\n \" <\/td>\"\n \" <td>\"\n \" <p style=\\\"margin: 0px;\\\">\"\n \" %2\"\n \" <\/p>\"\n \" <\/td>\"\n \" <\/tr>\"\n \" <\/tbody>\"\n \"<\/table>\").arg(iconDataUri(mIcon, 32, 32), mMessage));\n else\n setText(QString(\"<table align=center>\"\n \" <tbody>\"\n \" <tr valign=middle>\"\n \" <td>\"\n \" <img src=\\\"%1\\\"\/>\"\n \" <\/td>\"\n \" <td>\"\n \" <p style=\\\"margin: 0px;\\\">\"\n \" %2\"\n \" <\/p>\"\n \" <p style=\\\"margin: 0px;\\\">\"\n \" <small><em>(%3)<\/em><\/small>\"\n \" <\/p>\"\n \" <\/td>\"\n \" <\/tr>\"\n \" <\/tbody>\"\n \"<\/table>\").arg(iconDataUri(mIcon, 32, 32), mMessage, mExtraMessage));\n }\n}\n\n\/\/==============================================================================\n\nvoid UserMessageWidget::setMessage(const QString &pMessage,\n const QString &pExtraMessage)\n{\n \/\/ Set our message\n\n setIconMessage(mIcon, pMessage, pExtraMessage);\n}\n\n\/\/==============================================================================\n\n} \/\/ namespace Core\n} \/\/ namespace OpenCOR\n\n\/\/==============================================================================\n\/\/ End of file\n\/\/==============================================================================\n<|endoftext|>"} {"text":"<commit_before>#include <b9\/interpreter.hpp>\n#include <b9\/jit.hpp>\n#include <b9\/loader.hpp>\n#include <cstdio>\n#include <cstdlib>\n#include <cstring>\n#include <iostream>\n\n\/\/\/ B9run's usage string. Printed when run with -help.\nstatic const char* usage =\n \"Usage: b9run [<option>...] [--] <module> [<main>]\\n\"\n \" Or: b9run -help\\n\"\n \"Jit Options:\\n\"\n \" -jit: Enable the jit\\n\"\n \" -directcall: make direct jit to jit calls\\n\"\n \" -passparam: Pass arguments in CPU registers\\n\"\n \" -lazyvmstate: Only update the VM state as needed\\n\"\n \"Run Options:\\n\"\n \" -loop <n>: Run the program <n> times\\n\"\n \" -inline <n>: Enable inlining\\n\"\n \" -debug: Enable debug code\\n\"\n \" -verbose: Run with verbose printing\\n\"\n \" -help: Print this help message\";\n\n\/\/\/ The b9run program's global configuration.\nstruct RunConfig {\n b9::Config b9;\n const char* moduleName = \"\";\n const char* mainFunction = \"b9main\";\n std::size_t loopCount = 1;\n bool verbose = false;\n std::vector<b9::StackElement> usrArgs;\n};\n\nstd::ostream& operator<<(std::ostream& out, const RunConfig& cfg) {\n out << \"Module: \" << cfg.moduleName << std::endl\n << \"Function: \" << cfg.mainFunction << std::endl\n << \"Looping: \" << cfg.loopCount << std::endl;\n\n out << \"Arguments: [ \";\n for (const auto& arg : cfg.usrArgs) {\n out << arg << \" \";\n }\n out << \"]\" << std::endl;\n\n out << cfg.b9;\n return out;\n}\n\n\/\/\/ Parse CLI arguments and set up the config.\nstatic bool parseArguments(RunConfig& cfg, const int argc, char* argv[]) {\n std::size_t i = 1;\n\n for (; i < argc; i++) {\n const char* arg = argv[i];\n\n if (strcmp(arg, \"-help\") == 0) {\n std::cout << usage << std::endl;\n exit(EXIT_SUCCESS);\n } else if (strcmp(arg, \"-loop\") == 0) {\n cfg.loopCount = atoi(argv[++i]);\n } else if (strcmp(arg, \"-inline\") == 0) {\n cfg.b9.maxInlineDepth = atoi(argv[++i]);\n } else if (strcmp(arg, \"-verbose\") == 0) {\n cfg.verbose = true;\n cfg.b9.verbose = true;\n } else if (strcmp(arg, \"-debug\") == 0) {\n cfg.b9.debug = true;\n } else if (strcmp(arg, \"-function\") == 0) {\n cfg.mainFunction = argv[++i];\n } else if (strcmp(arg, \"-jit\") == 0) {\n cfg.b9.jit = true;\n } else if (strcmp(arg, \"-directcall\") == 0) {\n cfg.b9.directCall = true;\n } else if (strcmp(arg, \"-passparam\") == 0) {\n cfg.b9.passParam = true;\n } else if (strcmp(arg, \"-lazyvmstate\") == 0) {\n cfg.b9.lazyVmState = true;\n } else if (strcmp(arg, \"--\") == 0) {\n i++;\n break;\n } else if (strcmp(arg, \"-\") == 0) {\n std::cerr << \"Unrecognized option: \" << arg << std::endl;\n return false;\n } else {\n break;\n }\n }\n\n \/\/ check for user defined module\n if (i < argc) {\n cfg.moduleName = argv[i++];\n } else {\n std::cerr << \"No module name given to b9run\" << std::endl;\n return false;\n }\n\n \/\/ check for user defined arguments\n for (; i < argc; i++) {\n cfg.usrArgs.push_back(std::atoi(argv[i]));\n }\n\n return true;\n}\n\nstatic void run(const RunConfig& cfg) {\n b9::VirtualMachine vm{cfg.b9};\n b9::DlLoader loader{true};\n\n auto module = loader.loadModule(cfg.moduleName);\n vm.load(module);\n\n if (cfg.b9.jit) {\n vm.generateAllCode();\n }\n\n size_t functionIndex = module->findFunction(cfg.mainFunction);\n if (cfg.loopCount == 1) {\n b9::StackElement returnVal = vm.run(functionIndex, cfg.usrArgs);\n std::cout << std::endl\n << cfg.mainFunction << \" returned: \" << returnVal << std::endl;\n } else {\n b9::StackElement returnVal;\n std::cout << \"\\nRunning \" << cfg.mainFunction << \" \" << cfg.loopCount\n << \" times:\" << std::endl;\n for (std::size_t i = 1; i <= cfg.loopCount; i++) {\n returnVal = vm.run(functionIndex, cfg.usrArgs);\n std::cout << \"Return value of iteration \" << i << \": \" << returnVal\n << std::endl;\n }\n }\n}\n\nint main(int argc, char* argv[]) {\n RunConfig cfg;\n\n if (!parseArguments(cfg, argc, argv)) {\n std::cerr << usage << std::endl;\n exit(EXIT_FAILURE);\n }\n\n if (cfg.verbose) {\n std::cout << cfg << std::endl << std::endl;\n }\n\n try {\n run(cfg);\n } catch (const b9::DlException& e) {\n std::cerr << \"Failed to load module: \" << e.what() << std::endl;\n exit(EXIT_FAILURE);\n } catch (const b9::FunctionNotFoundException& e) {\n std::cerr << \"Failed to find function: \" << e.what() << std::endl;\n exit(EXIT_FAILURE);\n } catch (const b9::BadFunctionCallException& e) {\n std::cerr << \"Failed to call function \" << e.what() << std::endl;\n exit(EXIT_FAILURE);\n } catch (const b9::CompilationException& e) {\n std::cerr << \"Failed to compile function: \" << e.what() << std::endl;\n exit(EXIT_FAILURE);\n }\n\n exit(EXIT_SUCCESS);\n}\n<commit_msg>Simplify the result printing<commit_after>#include <b9\/interpreter.hpp>\n#include <b9\/jit.hpp>\n#include <b9\/loader.hpp>\n#include <cstdio>\n#include <cstdlib>\n#include <cstring>\n#include <iostream>\n\n\/\/\/ B9run's usage string. Printed when run with -help.\nstatic const char* usage =\n \"Usage: b9run [<option>...] [--] <module> [<main>]\\n\"\n \" Or: b9run -help\\n\"\n \"Jit Options:\\n\"\n \" -jit: Enable the jit\\n\"\n \" -directcall: make direct jit to jit calls\\n\"\n \" -passparam: Pass arguments in CPU registers\\n\"\n \" -lazyvmstate: Only update the VM state as needed\\n\"\n \"Run Options:\\n\"\n \" -loop <n>: Run the program <n> times\\n\"\n \" -inline <n>: Enable inlining\\n\"\n \" -debug: Enable debug code\\n\"\n \" -verbose: Run with verbose printing\\n\"\n \" -help: Print this help message\";\n\n\/\/\/ The b9run program's global configuration.\nstruct RunConfig {\n b9::Config b9;\n const char* moduleName = \"\";\n const char* mainFunction = \"b9main\";\n std::size_t loopCount = 1;\n bool verbose = false;\n std::vector<b9::StackElement> usrArgs;\n};\n\nstd::ostream& operator<<(std::ostream& out, const RunConfig& cfg) {\n out << \"Module: \" << cfg.moduleName << std::endl\n << \"Function: \" << cfg.mainFunction << std::endl\n << \"Looping: \" << cfg.loopCount << std::endl;\n\n out << \"Arguments: [ \";\n for (const auto& arg : cfg.usrArgs) {\n out << arg << \" \";\n }\n out << \"]\" << std::endl;\n\n out << cfg.b9;\n return out;\n}\n\n\/\/\/ Parse CLI arguments and set up the config.\nstatic bool parseArguments(RunConfig& cfg, const int argc, char* argv[]) {\n std::size_t i = 1;\n\n for (; i < argc; i++) {\n const char* arg = argv[i];\n\n if (strcmp(arg, \"-help\") == 0) {\n std::cout << usage << std::endl;\n exit(EXIT_SUCCESS);\n } else if (strcmp(arg, \"-loop\") == 0) {\n cfg.loopCount = atoi(argv[++i]);\n } else if (strcmp(arg, \"-inline\") == 0) {\n cfg.b9.maxInlineDepth = atoi(argv[++i]);\n } else if (strcmp(arg, \"-verbose\") == 0) {\n cfg.verbose = true;\n cfg.b9.verbose = true;\n } else if (strcmp(arg, \"-debug\") == 0) {\n cfg.b9.debug = true;\n } else if (strcmp(arg, \"-function\") == 0) {\n cfg.mainFunction = argv[++i];\n } else if (strcmp(arg, \"-jit\") == 0) {\n cfg.b9.jit = true;\n } else if (strcmp(arg, \"-directcall\") == 0) {\n cfg.b9.directCall = true;\n } else if (strcmp(arg, \"-passparam\") == 0) {\n cfg.b9.passParam = true;\n } else if (strcmp(arg, \"-lazyvmstate\") == 0) {\n cfg.b9.lazyVmState = true;\n } else if (strcmp(arg, \"--\") == 0) {\n i++;\n break;\n } else if (strcmp(arg, \"-\") == 0) {\n std::cerr << \"Unrecognized option: \" << arg << std::endl;\n return false;\n } else {\n break;\n }\n }\n\n \/\/ check for user defined module\n if (i < argc) {\n cfg.moduleName = argv[i++];\n } else {\n std::cerr << \"No module name given to b9run\" << std::endl;\n return false;\n }\n\n \/\/ check for user defined arguments\n for (; i < argc; i++) {\n cfg.usrArgs.push_back(std::atoi(argv[i]));\n }\n\n return true;\n}\n\nstatic void run(const RunConfig& cfg) {\n b9::VirtualMachine vm{cfg.b9};\n b9::DlLoader loader{true};\n\n auto module = loader.loadModule(cfg.moduleName);\n vm.load(module);\n\n if (cfg.b9.jit) {\n vm.generateAllCode();\n }\n\n size_t functionIndex = module->findFunction(cfg.mainFunction);\n for (std::size_t i = 0; i < cfg.loopCount; i += 1) {\n auto result = vm.run(functionIndex, cfg.usrArgs);\n std::cout << std::endl << \"=> \" << result << std::endl;\n }\n}\n\nint main(int argc, char* argv[]) {\n RunConfig cfg;\n\n if (!parseArguments(cfg, argc, argv)) {\n std::cerr << usage << std::endl;\n exit(EXIT_FAILURE);\n }\n\n if (cfg.verbose) {\n std::cout << cfg << std::endl << std::endl;\n }\n\n try {\n run(cfg);\n } catch (const b9::DlException& e) {\n std::cerr << \"Failed to load module: \" << e.what() << std::endl;\n exit(EXIT_FAILURE);\n } catch (const b9::FunctionNotFoundException& e) {\n std::cerr << \"Failed to find function: \" << e.what() << std::endl;\n exit(EXIT_FAILURE);\n } catch (const b9::BadFunctionCallException& e) {\n std::cerr << \"Failed to call function \" << e.what() << std::endl;\n exit(EXIT_FAILURE);\n } catch (const b9::CompilationException& e) {\n std::cerr << \"Failed to compile function: \" << e.what() << std::endl;\n exit(EXIT_FAILURE);\n }\n\n exit(EXIT_SUCCESS);\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ Created by qife on 16\/1\/11.\n\/\/\n\n#include <string>\n#include <locale>\n#include <stack>\n#include <queue>\n#include <functional>\n\nusing NodeDeque = std::deque<Expr::ExprNode>;\n\nstatic bool GetRePolishExpression(const char *str, NodeDeque &nodes)\n{\n using namespace Expr;\n\n int paren = 0;\n std::queue<ExprNode> exprNodes; \/\/ 表达式节点\n auto tmp = SkipWhiteSpace(str);\n tmp = TestSignDigit(tmp, exprNodes);\n\n while (true) {\n tmp = SkipWhiteSpace(tmp);\n if (*tmp == '(') {\n ExprNode node(ExprType::Operator);\n node.data.op = '(';\n exprNodes.push(std::move(node));\n\n tmp = SkipWhiteSpace(tmp, 1);\n tmp = TestSignDigit(tmp, exprNodes);\n ++paren;\n }\n\n if (!ReadNumOrProp(&tmp, exprNodes)) {\n return false;\n }\n\n tmp = SkipWhiteSpace(tmp);\n if (*tmp == ')') {\n if (--paren < 0) {\n return false;\n }\n\n ExprNode node(ExprType::Operator);\n node.data.op = ')';\n exprNodes.push(std::move(node));\n\n tmp = SkipWhiteSpace(tmp, 1);\n }\n\n if (*tmp) {\n if (!ReadOperator(&tmp, exprNodes)) {\n return false;\n }\n } else {\n break;\n }\n }\n if (paren != 0) {\n return false;\n }\n\n std::stack<ExprNode> opStack; \/\/ 运算符暂存堆栈\n while (!exprNodes.empty()) {\n ExprNode &node = exprNodes.front();\n\n if (node.type == ExprType::Operator) {\n char op = node.data.op;\n if (opStack.empty() || op == '(') {\n opStack.push(std::move(node));\n exprNodes.pop();\n continue;\n }\n if (op == ')') {\n while (!opStack.empty()) {\n ExprNode &tmpOpNode = opStack.top();\n if (tmpOpNode.data.op != '(') {\n nodes.push_back(std::move(tmpOpNode));\n opStack.pop();\n } else {\n opStack.pop();\n break;\n }\n }\n\n exprNodes.pop();\n continue;\n }\n\n ExprNode &opNode = opStack.top();\n if (opNode.data.op == '(') {\n opStack.push(std::move(node));\n exprNodes.pop();\n continue;\n }\n if (OpLessOrEqual(op, opNode.data.op)) {\n nodes.push_back(std::move(opNode));\n opStack.pop();\n while (!opStack.empty()) {\n ExprNode &tmpOpNode = opStack.top();\n if (OpLessOrEqual(op, tmpOpNode.data.op)) {\n nodes.push_back(std::move(tmpOpNode));\n opStack.pop();\n } else {\n break;\n }\n }\n\n opStack.push(std::move(node));\n exprNodes.pop();\n } else {\n opStack.push(std::move(node));\n exprNodes.pop();\n }\n } else {\n nodes.push_back(std::move(node));\n exprNodes.pop();\n }\n }\n while (!opStack.empty()) {\n nodes.push_back(std::move(opStack.top()));\n opStack.pop();\n }\n\n return true;\n}\n\nstatic bool ComputeRePolish(const NodeDeque &nodes, const std::function<bool(const std::string &, double *)> &get, double *result)\n{\n std::stack<double> computeStack;\n\n for (const auto &item : nodes) {\n switch (item.type) {\n case Expr::Numeric: {\n computeStack.push(item.data.num);\n continue;\n }\n\n case Expr::Property: {\n double value = 0.0;\n if (get(*item.data.prop, &value)) {\n computeStack.push(value);\n continue;\n } else {\n return false;\n }\n }\n\n case Expr::Operator: {\n if (computeStack.size() < 2) {\n return false;\n }\n\n double num2 = computeStack.top();\n computeStack.pop();\n double num1 = computeStack.top();\n computeStack.pop();\n\n switch (item.data.op) {\n case '+':\n computeStack.push(num1 + num2);\n continue;\n\n case '-':\n computeStack.push(num1 - num2);\n continue;\n\n case '*':\n computeStack.push(num1 * num2);\n continue;\n\n case '\/':\n computeStack.push(num1 \/ num2);\n continue;\n\n case '%':\n computeStack.push((int)num1 % (int)num2); \/\/ TODO: test int value\n continue;\n\n default:\n return false;\n }\n }\n\n case Expr::Boolean:\n return false;\n }\n }\n\n if (computeStack.size() == 1) {\n *result = computeStack.top();\n return true;\n }\n\n return false;\n}\n\nstatic int GetOperatorPriority(char op)\n{\n switch (op) {\n case '+':\n case '-':\n return 1;\n\n case '*':\n case '\/':\n case '%':\n return 3;\n\n default:\n return 0;\n }\n}\n\nstatic bool OpLessOrEqual(char op1, char op2)\n{\n int p1 = GetOperatorPriority(op1);\n int p2 = GetOperatorPriority(op2);\n\n return p1 <= p2;\n}\n\nstatic const char *TestSignDigit(const char *str, std::queue<Expr::ExprNode> &nodes)\n{\n using namespace Expr;\n\n if (*str == '-') {\n ExprNode node(ExprType::Numeric);\n node.data.num = 0;\n nodes.push(std::move(node));\n\n node.type = ExprType::Operator;\n node.data.op = '-';\n nodes.push(std::move(node));\n\n return str + 1;\n }\n if (*str == '+') {\n return str + 1;\n }\n\n return str;\n}\n\nstatic bool ReadNumOrProp(const char **str, std::queue<Expr::ExprNode> &nodes)\n{\n using namespace Expr;\n\n auto tmp = *str;\n tmp = SkipWhiteSpace(tmp);\n\n if (*tmp == '@') {\n if (*(tmp + 1) != '.') {\n return false;\n }\n tmp += 2;\n\n unsigned int len = 0;\n auto start = tmp;\n while (true) {\n switch (*start) {\n case '+':\n case '-':\n case '*':\n case '\/':\n case '%':\n case ')':\n case ' ':\n break;\n\n case '(':\n return false;\n\n default:\n ++len;\n ++start;\n continue;\n }\n\n if (len == 0) {\n return false;\n }\n\n ExprNode node(ExprType::Property);\n node.data.prop = new std::string(tmp, len);\n nodes.push(std::move(node));\n break;\n }\n\n *str = start;\n return true;\n } else {\n if (!std::isdigit(*tmp)) {\n return false;\n }\n\n char *end = nullptr;\n auto num = std::strtod(tmp, &end);\n if (nullptr == end) {\n return false;\n }\n\n ExprNode node(ExprType::Numeric);\n node.data.num = num;\n nodes.push(std::move(node));\n\n *str = end;\n return true;\n }\n}\n\nstatic bool ReadOperator(const char **str, std::queue<Expr::ExprNode> &nodes)\n{\n using namespace Expr;\n\n auto tmp = *str;\n\n switch (*tmp) {\n case '+':\n case '-':\n case '*':\n case '\/':\n case '%': {\n ExprNode node(ExprType::Operator);\n node.data.op = *tmp;\n nodes.push(std::move(node));\n\n *str = tmp + 1;\n return true;\n }\n\n default:\n return false;\n }\n}\n<commit_msg>remove unused file.<commit_after><|endoftext|>"} {"text":"<commit_before>\/**\n * \\file\n * \\brief Definitions of low-level SPI master drivers for SPIv2 in STM32\n *\n * \\author Copyright (C) 2016-2017 Kamil Szczygiel http:\/\/www.distortec.com http:\/\/www.freddiechopin.info\n *\n * \\par License\n * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not\n * distributed with this file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\/\n\n#include \"distortos\/chip\/spis.hpp\"\n\n#include \"distortos\/chip\/ChipSpiMasterLowLevel.hpp\"\n\nnamespace distortos\n{\n\nnamespace chip\n{\n\n\/*---------------------------------------------------------------------------------------------------------------------+\n| SPI1 global objects and functions\n+---------------------------------------------------------------------------------------------------------------------*\/\n\n#ifdef CONFIG_CHIP_STM32_SPIV2_SPI1_ENABLE\n\nChipSpiMasterLowLevel spi1 {ChipSpiMasterLowLevel::spi1Parameters};\n\n\/**\n * \\brief SPI1 interrupt handler\n *\/\n\nextern \"C\" void SPI1_IRQHandler()\n{\n\tspi1.interruptHandler();\n}\n\n#endif\t\/\/ def CONFIG_CHIP_STM32_SPIV2_SPI1_ENABLE\n\n\/*---------------------------------------------------------------------------------------------------------------------+\n| SPI2 global objects and functions\n+---------------------------------------------------------------------------------------------------------------------*\/\n\n#ifdef CONFIG_CHIP_STM32_SPIV2_SPI2_ENABLE\n\nChipSpiMasterLowLevel spi2 {ChipSpiMasterLowLevel::spi2Parameters};\n\n\/**\n * \\brief SPI2 interrupt handler\n *\/\n\nextern \"C\" void SPI2_IRQHandler()\n{\n\tspi2.interruptHandler();\n}\n\n#endif\t\/\/ def CONFIG_CHIP_STM32_SPIV2_SPI2_ENABLE\n\n\/*---------------------------------------------------------------------------------------------------------------------+\n| SPI3 global objects and functions\n+---------------------------------------------------------------------------------------------------------------------*\/\n\n#ifdef CONFIG_CHIP_STM32_SPIV2_SPI3_ENABLE\n\nChipSpiMasterLowLevel spi3 {ChipSpiMasterLowLevel::spi3Parameters};\n\n\/**\n * \\brief SPI3 interrupt handler\n *\/\n\nextern \"C\" void SPI3_IRQHandler()\n{\n\tspi3.interruptHandler();\n}\n\n#endif\t\/\/ def CONFIG_CHIP_STM32_SPIV2_SPI3_ENABLE\n\n\/*---------------------------------------------------------------------------------------------------------------------+\n| SPI4 global objects and functions\n+---------------------------------------------------------------------------------------------------------------------*\/\n\n#ifdef CONFIG_CHIP_STM32_SPIV2_SPI4_ENABLE\n\nChipSpiMasterLowLevel spi4 {ChipSpiMasterLowLevel::spi4Parameters};\n\n\/**\n * \\brief SPI4 interrupt handler\n *\/\n\nextern \"C\" void SPI4_IRQHandler()\n{\n\tspi4.interruptHandler();\n}\n\n#endif\t\/\/ def CONFIG_CHIP_STM32_SPIV2_SPI4_ENABLE\n\n\/*---------------------------------------------------------------------------------------------------------------------+\n| SPI5 global objects and functions\n+---------------------------------------------------------------------------------------------------------------------*\/\n\n#ifdef CONFIG_CHIP_STM32_SPIV2_SPI5_ENABLE\n\nChipSpiMasterLowLevel spi5 {ChipSpiMasterLowLevel::spi5Parameters};\n\n\/**\n * \\brief SPI5 interrupt handler\n *\/\n\nextern \"C\" void SPI5_IRQHandler()\n{\n\tspi5.interruptHandler();\n}\n\n#endif\t\/\/ def CONFIG_CHIP_STM32_SPIV2_SPI5_ENABLE\n\n\/*---------------------------------------------------------------------------------------------------------------------+\n| SPI6 global objects and functions\n+---------------------------------------------------------------------------------------------------------------------*\/\n\n#ifdef CONFIG_CHIP_STM32_SPIV2_SPI6_ENABLE\n\nChipSpiMasterLowLevel spi6 {ChipSpiMasterLowLevel::spi6Parameters};\n\n\/**\n * \\brief SPI6 interrupt handler\n *\/\n\nextern \"C\" void SPI6_IRQHandler()\n{\n\tspi6.interruptHandler();\n}\n\n#endif\t\/\/ def CONFIG_CHIP_STM32_SPIV2_SPI6_ENABLE\n\n}\t\/\/ namespace chip\n\n}\t\/\/ namespace distortos\n<commit_msg>Rearrange things in STM32-SPIv2-spis.cpp<commit_after>\/**\n * \\file\n * \\brief Definitions of low-level SPI master drivers for SPIv2 in STM32\n *\n * \\author Copyright (C) 2016-2017 Kamil Szczygiel http:\/\/www.distortec.com http:\/\/www.freddiechopin.info\n *\n * \\par License\n * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not\n * distributed with this file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\/\n\n#include \"distortos\/chip\/spis.hpp\"\n\n#include \"distortos\/chip\/ChipSpiMasterLowLevel.hpp\"\n\nnamespace distortos\n{\n\nnamespace chip\n{\n\n\/*---------------------------------------------------------------------------------------------------------------------+\n| global objects\n+---------------------------------------------------------------------------------------------------------------------*\/\n\n#ifdef CONFIG_CHIP_STM32_SPIV2_SPI1_ENABLE\n\nChipSpiMasterLowLevel spi1 {ChipSpiMasterLowLevel::spi1Parameters};\n\n#endif\t\/\/ def CONFIG_CHIP_STM32_SPIV2_SPI1_ENABLE\n\n#ifdef CONFIG_CHIP_STM32_SPIV2_SPI2_ENABLE\n\nChipSpiMasterLowLevel spi2 {ChipSpiMasterLowLevel::spi2Parameters};\n\n#endif\t\/\/ def CONFIG_CHIP_STM32_SPIV2_SPI2_ENABLE\n\n#ifdef CONFIG_CHIP_STM32_SPIV2_SPI3_ENABLE\n\nChipSpiMasterLowLevel spi3 {ChipSpiMasterLowLevel::spi3Parameters};\n\n#endif\t\/\/ def CONFIG_CHIP_STM32_SPIV2_SPI3_ENABLE\n\n#ifdef CONFIG_CHIP_STM32_SPIV2_SPI4_ENABLE\n\nChipSpiMasterLowLevel spi4 {ChipSpiMasterLowLevel::spi4Parameters};\n\n#endif\t\/\/ def CONFIG_CHIP_STM32_SPIV2_SPI4_ENABLE\n\n#ifdef CONFIG_CHIP_STM32_SPIV2_SPI5_ENABLE\n\nChipSpiMasterLowLevel spi5 {ChipSpiMasterLowLevel::spi5Parameters};\n\n#endif\t\/\/ def CONFIG_CHIP_STM32_SPIV2_SPI5_ENABLE\n\n#ifdef CONFIG_CHIP_STM32_SPIV2_SPI6_ENABLE\n\nChipSpiMasterLowLevel spi6 {ChipSpiMasterLowLevel::spi6Parameters};\n\n#endif\t\/\/ def CONFIG_CHIP_STM32_SPIV2_SPI6_ENABLE\n\n\/*---------------------------------------------------------------------------------------------------------------------+\n| global functions\n+---------------------------------------------------------------------------------------------------------------------*\/\n\n#ifdef CONFIG_CHIP_STM32_SPIV2_SPI1_ENABLE\n\n\/**\n * \\brief SPI1 interrupt handler\n *\/\n\nextern \"C\" void SPI1_IRQHandler()\n{\n\tspi1.interruptHandler();\n}\n\n#endif\t\/\/ def CONFIG_CHIP_STM32_SPIV2_SPI1_ENABLE\n\n#ifdef CONFIG_CHIP_STM32_SPIV2_SPI2_ENABLE\n\n\/**\n * \\brief SPI2 interrupt handler\n *\/\n\nextern \"C\" void SPI2_IRQHandler()\n{\n\tspi2.interruptHandler();\n}\n\n#endif\t\/\/ def CONFIG_CHIP_STM32_SPIV2_SPI2_ENABLE\n\n#ifdef CONFIG_CHIP_STM32_SPIV2_SPI3_ENABLE\n\n\/**\n * \\brief SPI3 interrupt handler\n *\/\n\nextern \"C\" void SPI3_IRQHandler()\n{\n\tspi3.interruptHandler();\n}\n\n#endif\t\/\/ def CONFIG_CHIP_STM32_SPIV2_SPI3_ENABLE\n\n#ifdef CONFIG_CHIP_STM32_SPIV2_SPI4_ENABLE\n\n\/**\n * \\brief SPI4 interrupt handler\n *\/\n\nextern \"C\" void SPI4_IRQHandler()\n{\n\tspi4.interruptHandler();\n}\n\n#endif\t\/\/ def CONFIG_CHIP_STM32_SPIV2_SPI4_ENABLE\n\n#ifdef CONFIG_CHIP_STM32_SPIV2_SPI5_ENABLE\n\n\/**\n * \\brief SPI5 interrupt handler\n *\/\n\nextern \"C\" void SPI5_IRQHandler()\n{\n\tspi5.interruptHandler();\n}\n\n#endif\t\/\/ def CONFIG_CHIP_STM32_SPIV2_SPI5_ENABLE\n\n#ifdef CONFIG_CHIP_STM32_SPIV2_SPI6_ENABLE\n\n\/**\n * \\brief SPI6 interrupt handler\n *\/\n\nextern \"C\" void SPI6_IRQHandler()\n{\n\tspi6.interruptHandler();\n}\n\n#endif\t\/\/ def CONFIG_CHIP_STM32_SPIV2_SPI6_ENABLE\n\n}\t\/\/ namespace chip\n\n}\t\/\/ namespace distortos\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 2010, Willow Garage, Inc.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution.\n * * Neither the name of the Willow Garage, Inc. nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \"triangle_list_marker.h\"\n\n#include \"marker_selection_handler.h\"\n#include \"rviz\/default_plugin\/marker_display.h\"\n#include \"rviz\/selection\/selection_manager.h\"\n#include \"rviz\/uniform_string_stream.h\"\n\n#include \"rviz\/display_context.h\"\n#include \"rviz\/mesh_loader.h\"\n#include \"marker_display.h\"\n\n#include <OGRE\/OgreSceneNode.h>\n#include <OGRE\/OgreSceneManager.h>\n#include <OGRE\/OgreManualObject.h>\n#include <OGRE\/OgreMaterialManager.h>\n#include <OGRE\/OgreTextureManager.h>\n#include <OGRE\/OgreTechnique.h>\n\nnamespace rviz\n{\n\nTriangleListMarker::TriangleListMarker(MarkerDisplay* owner, DisplayContext* context, Ogre::SceneNode* parent_node)\n: MarkerBase(owner, context, parent_node)\n, manual_object_(0)\n{\n}\n\nTriangleListMarker::~TriangleListMarker()\n{\n context_->getSceneManager()->destroyManualObject(manual_object_);\n\n for (size_t i = 0; i < material_->getNumTechniques(); ++i)\n {\n Ogre::Technique* t = material_->getTechnique(i);\n \/\/ hack hack hack, really need to do a shader-based way of picking, rather than\n \/\/ creating a texture for each object\n if (t->getSchemeName() == \"Pick\")\n {\n Ogre::TextureManager::getSingleton().remove(t->getPass(0)->getTextureUnitState(0)->getTextureName());\n }\n }\n\n material_->unload();\n Ogre::MaterialManager::getSingleton().remove(material_->getName());\n}\n\nvoid TriangleListMarker::onNewMessage(const MarkerConstPtr& old_message, const MarkerConstPtr& new_message)\n{\n ROS_ASSERT(new_message->type == visualization_msgs::Marker::TRIANGLE_LIST);\n\n size_t num_points = new_message->points.size();\n if( (num_points % 3) != 0 || num_points == 0 )\n {\n std::stringstream ss;\n if( num_points == 0 )\n {\n ss << \"TriMesh marker [\" << getStringID() << \"] has no points.\";\n }\n else\n {\n ss << \"TriMesh marker [\" << getStringID() << \"] has a point count which is not divisible by 3 [\" << num_points <<\"]\";\n }\n if ( owner_ )\n {\n owner_->setMarkerStatus(getID(), StatusProperty::Error, ss.str());\n }\n ROS_DEBUG(\"%s\", ss.str().c_str());\n\n scene_node_->setVisible( false );\n return;\n }\n else\n {\n scene_node_->setVisible( true );\n }\n\n if (!manual_object_)\n {\n static uint32_t count = 0;\n UniformStringStream ss;\n ss << \"Triangle List Marker\" << count++;\n manual_object_ = context_->getSceneManager()->createManualObject(ss.str());\n scene_node_->attachObject(manual_object_);\n\n ss << \"Material\";\n material_name_ = ss.str();\n material_ = Ogre::MaterialManager::getSingleton().create( material_name_, ROS_PACKAGE_NAME );\n material_->setReceiveShadows(false);\n material_->getTechnique(0)->setLightingEnabled(true);\n material_->setCullingMode(Ogre::CULL_NONE);\n\n context_->getSelectionManager()->removeObject(coll_);\n\n SelectionManager* sel_man = context_->getSelectionManager();\n coll_ = sel_man->createHandle();\n sel_man->addPickTechnique(coll_, material_);\n sel_man->addObject( coll_, SelectionHandlerPtr(new MarkerSelectionHandler(this, MarkerID(new_message->ns, new_message->id))) );\n }\n\n Ogre::Vector3 pos, scale;\n Ogre::Quaternion orient;\n transform(new_message, pos, orient, scale);\n\n if ( owner_ && (new_message->scale.x * new_message->scale.y * new_message->scale.z == 0.0f) )\n {\n owner_->setMarkerStatus(getID(), StatusProperty::Warn, \"Scale of 0 in one of x\/y\/z\");\n }\n\n setPosition(pos);\n setOrientation(orient);\n scene_node_->setScale(scale);\n\n \/\/ If we have the same number of tris as previously, just update the object\n if (old_message && num_points == old_message->points.size())\n {\n manual_object_->beginUpdate(0);\n }\n else \/\/ Otherwise clear it and begin anew\n {\n manual_object_->clear();\n manual_object_->estimateVertexCount(num_points);\n manual_object_->begin(material_name_, Ogre::RenderOperation::OT_TRIANGLE_LIST);\n }\n\n bool has_vertex_colors = new_message->colors.size() == num_points;\n bool any_vertex_has_alpha = false;\n\n if (has_vertex_colors)\n {\n for (size_t i = 0; i < num_points; ++i)\n {\n manual_object_->position(new_message->points[i].x, new_message->points[i].y, new_message->points[i].z);\n any_vertex_has_alpha = any_vertex_has_alpha || (new_message->colors[i].a < 0.9998);\n manual_object_->colour(new_message->colors[i].r, new_message->colors[i].g, new_message->colors[i].b, new_message->color.a * new_message->colors[i].a);\n }\n }\n else\n {\n for (size_t i = 0; i < num_points; ++i)\n {\n manual_object_->position(new_message->points[i].x, new_message->points[i].y, new_message->points[i].z);\n }\n }\n\n manual_object_->end();\n\n if (has_vertex_colors)\n {\n material_->getTechnique(0)->setLightingEnabled(false);\n }\n else\n {\n material_->getTechnique(0)->setLightingEnabled(true);\n float r,g,b,a;\n r = new_message->color.r;\n g = new_message->color.g;\n b = new_message->color.b;\n a = new_message->color.a;\n material_->getTechnique(0)->setAmbient( r,g,b );\n material_->getTechnique(0)->setDiffuse( 0,0,0,a );\n }\n\n if( (!has_vertex_colors && new_message->color.a < 0.9998) || (has_vertex_colors && any_vertex_has_alpha))\n {\n material_->getTechnique(0)->setSceneBlending( Ogre::SBT_TRANSPARENT_ALPHA );\n material_->getTechnique(0)->setDepthWriteEnabled( false );\n }\n else\n {\n material_->getTechnique(0)->setSceneBlending( Ogre::SBT_REPLACE );\n material_->getTechnique(0)->setDepthWriteEnabled( true );\n }\n}\n\nS_MaterialPtr TriangleListMarker::getMaterials()\n{\n S_MaterialPtr materials;\n materials.insert( material_ );\n return materials;\n}\n\n\n}\n\n<commit_msg>discard marker if transform() fails. Otherwise uninitialized Ogre vectors are passed in and segfaults happen<commit_after>\/*\n * Copyright (c) 2010, Willow Garage, Inc.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution.\n * * Neither the name of the Willow Garage, Inc. nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \"triangle_list_marker.h\"\n\n#include \"marker_selection_handler.h\"\n#include \"rviz\/default_plugin\/marker_display.h\"\n#include \"rviz\/selection\/selection_manager.h\"\n#include \"rviz\/uniform_string_stream.h\"\n\n#include \"rviz\/display_context.h\"\n#include \"rviz\/mesh_loader.h\"\n#include \"marker_display.h\"\n\n#include <OGRE\/OgreSceneNode.h>\n#include <OGRE\/OgreSceneManager.h>\n#include <OGRE\/OgreManualObject.h>\n#include <OGRE\/OgreMaterialManager.h>\n#include <OGRE\/OgreTextureManager.h>\n#include <OGRE\/OgreTechnique.h>\n\nnamespace rviz\n{\n\nTriangleListMarker::TriangleListMarker(MarkerDisplay* owner, DisplayContext* context, Ogre::SceneNode* parent_node)\n: MarkerBase(owner, context, parent_node)\n, manual_object_(0)\n{\n}\n\nTriangleListMarker::~TriangleListMarker()\n{\n context_->getSceneManager()->destroyManualObject(manual_object_);\n\n for (size_t i = 0; i < material_->getNumTechniques(); ++i)\n {\n Ogre::Technique* t = material_->getTechnique(i);\n \/\/ hack hack hack, really need to do a shader-based way of picking, rather than\n \/\/ creating a texture for each object\n if (t->getSchemeName() == \"Pick\")\n {\n Ogre::TextureManager::getSingleton().remove(t->getPass(0)->getTextureUnitState(0)->getTextureName());\n }\n }\n\n material_->unload();\n Ogre::MaterialManager::getSingleton().remove(material_->getName());\n}\n\nvoid TriangleListMarker::onNewMessage(const MarkerConstPtr& old_message, const MarkerConstPtr& new_message)\n{\n ROS_ASSERT(new_message->type == visualization_msgs::Marker::TRIANGLE_LIST);\n\n size_t num_points = new_message->points.size();\n if( (num_points % 3) != 0 || num_points == 0 )\n {\n std::stringstream ss;\n if( num_points == 0 )\n {\n ss << \"TriMesh marker [\" << getStringID() << \"] has no points.\";\n }\n else\n {\n ss << \"TriMesh marker [\" << getStringID() << \"] has a point count which is not divisible by 3 [\" << num_points <<\"]\";\n }\n if ( owner_ )\n {\n owner_->setMarkerStatus(getID(), StatusProperty::Error, ss.str());\n }\n ROS_DEBUG(\"%s\", ss.str().c_str());\n\n scene_node_->setVisible( false );\n return;\n }\n else\n {\n scene_node_->setVisible( true );\n }\n\n if (!manual_object_)\n {\n static uint32_t count = 0;\n UniformStringStream ss;\n ss << \"Triangle List Marker\" << count++;\n manual_object_ = context_->getSceneManager()->createManualObject(ss.str());\n scene_node_->attachObject(manual_object_);\n\n ss << \"Material\";\n material_name_ = ss.str();\n material_ = Ogre::MaterialManager::getSingleton().create( material_name_, ROS_PACKAGE_NAME );\n material_->setReceiveShadows(false);\n material_->getTechnique(0)->setLightingEnabled(true);\n material_->setCullingMode(Ogre::CULL_NONE);\n\n context_->getSelectionManager()->removeObject(coll_);\n\n SelectionManager* sel_man = context_->getSelectionManager();\n coll_ = sel_man->createHandle();\n sel_man->addPickTechnique(coll_, material_);\n sel_man->addObject( coll_, SelectionHandlerPtr(new MarkerSelectionHandler(this, MarkerID(new_message->ns, new_message->id))) );\n }\n\n Ogre::Vector3 pos, scale;\n Ogre::Quaternion orient;\n if (!transform(new_message, pos, orient, scale))\n { \n ROS_DEBUG(\"Unable to transform marker message\");\n scene_node_->setVisible( false );\n return;\n }\n \n if ( owner_ && (new_message->scale.x * new_message->scale.y * new_message->scale.z == 0.0f) )\n {\n owner_->setMarkerStatus(getID(), StatusProperty::Warn, \"Scale of 0 in one of x\/y\/z\");\n }\n\n setPosition(pos);\n setOrientation(orient);\n scene_node_->setScale(scale);\n\n \/\/ If we have the same number of tris as previously, just update the object\n if (old_message && num_points == old_message->points.size())\n {\n manual_object_->beginUpdate(0);\n }\n else \/\/ Otherwise clear it and begin anew\n {\n manual_object_->clear();\n manual_object_->estimateVertexCount(num_points);\n manual_object_->begin(material_name_, Ogre::RenderOperation::OT_TRIANGLE_LIST);\n }\n\n bool has_vertex_colors = new_message->colors.size() == num_points;\n bool any_vertex_has_alpha = false;\n\n if (has_vertex_colors)\n {\n for (size_t i = 0; i < num_points; ++i)\n {\n manual_object_->position(new_message->points[i].x, new_message->points[i].y, new_message->points[i].z);\n any_vertex_has_alpha = any_vertex_has_alpha || (new_message->colors[i].a < 0.9998);\n manual_object_->colour(new_message->colors[i].r, new_message->colors[i].g, new_message->colors[i].b, new_message->color.a * new_message->colors[i].a);\n }\n }\n else\n {\n for (size_t i = 0; i < num_points; ++i)\n {\n manual_object_->position(new_message->points[i].x, new_message->points[i].y, new_message->points[i].z);\n }\n }\n\n manual_object_->end();\n\n if (has_vertex_colors)\n {\n material_->getTechnique(0)->setLightingEnabled(false);\n }\n else\n {\n material_->getTechnique(0)->setLightingEnabled(true);\n float r,g,b,a;\n r = new_message->color.r;\n g = new_message->color.g;\n b = new_message->color.b;\n a = new_message->color.a;\n material_->getTechnique(0)->setAmbient( r,g,b );\n material_->getTechnique(0)->setDiffuse( 0,0,0,a );\n }\n\n if( (!has_vertex_colors && new_message->color.a < 0.9998) || (has_vertex_colors && any_vertex_has_alpha))\n {\n material_->getTechnique(0)->setSceneBlending( Ogre::SBT_TRANSPARENT_ALPHA );\n material_->getTechnique(0)->setDepthWriteEnabled( false );\n }\n else\n {\n material_->getTechnique(0)->setSceneBlending( Ogre::SBT_REPLACE );\n material_->getTechnique(0)->setDepthWriteEnabled( true );\n }\n}\n\nS_MaterialPtr TriangleListMarker::getMaterials()\n{\n S_MaterialPtr materials;\n materials.insert( material_ );\n return materials;\n}\n\n\n}\n\n<|endoftext|>"} {"text":"<commit_before>#include <vector>\n#include <iostream>\n\n#include <opengm\/learning\/loss\/generalized-hammingloss.hxx>\n#include <opengm\/graphicalmodel\/graphicalmodel.hxx>\n#include <opengm\/graphicalmodel\/graphicalmodel_factor.hxx>\n\n\/\/*************************************\ntypedef double ValueType;\ntypedef size_t IndexType;\ntypedef size_t LabelType;\ntypedef opengm::meta::TypeListGenerator<opengm::ExplicitFunction<ValueType,IndexType,LabelType> >::type FunctionListType;\ntypedef opengm::GraphicalModel<ValueType,opengm::Adder, FunctionListType, opengm::DiscreteSpace<IndexType,LabelType> > GM;\n\n\/\/*************************************\n\n\nint main() {\n\n std::vector<double> label_loss_multipliers;\n label_loss_multipliers.push_back(2.0);\n label_loss_multipliers.push_back(1.0);\n label_loss_multipliers.push_back(0.5);\n\n std::vector<double> node_loss_multipliers;\n node_loss_multipliers.push_back(5.0);\n node_loss_multipliers.push_back(6.0);\n node_loss_multipliers.push_back(7.0);\n node_loss_multipliers.push_back(8.0);\n\n \/\/ create loss\n opengm::learning::GeneralizedHammingLoss loss(node_loss_multipliers.begin(),\n node_loss_multipliers.end(),\n label_loss_multipliers.begin(),\n label_loss_multipliers.end());\n\n \/\/ evaluate for a test point\n std::vector<size_t> labels;\n labels.push_back(0);\n labels.push_back(1);\n labels.push_back(2);\n labels.push_back(2);\n\n std::vector<size_t> ground_truth;\n ground_truth.push_back(1);\n ground_truth.push_back(1);\n ground_truth.push_back(1);\n ground_truth.push_back(1);\n\n OPENGM_ASSERT_OP(loss.loss(labels.begin(), labels.end(), ground_truth.begin(), ground_truth.end()), ==, 17.5);\n\n \/\/ add loss to a model and evaluate for a given labeling\n GM gm;\n size_t numberOfLabels = 3;\n gm.addVariable(numberOfLabels);\n gm.addVariable(numberOfLabels);\n gm.addVariable(numberOfLabels);\n gm.addVariable(numberOfLabels);\n\n \/\/ add a unary to node 2 (if indexed from 1)\n opengm::ExplicitFunction<typename GM::ValueType,typename GM::IndexType, typename GM::LabelType> f(&numberOfLabels, &(numberOfLabels)+1, 2.0);\n size_t variableIndex = 1;\n gm.addFactor(gm.addFunction(f), &variableIndex, &variableIndex+1);\n OPENGM_ASSERT_OP(gm.evaluate(labels.begin()), ==, 2.0);\n\n \/\/ loss augmented model:\n loss.addLoss(gm, ground_truth.begin());\n OPENGM_ASSERT_OP(gm.evaluate(labels.begin()), ==, 19.5);\n}\n<commit_msg>make it compileable<commit_after>#include <vector>\n#include <iostream>\n\n#include <opengm\/learning\/loss\/generalized-hammingloss.hxx>\n#include <opengm\/graphicalmodel\/graphicalmodel.hxx>\n#include <opengm\/graphicalmodel\/graphicalmodel_factor.hxx>\n\n\/\/*************************************\ntypedef double ValueType;\ntypedef size_t IndexType;\ntypedef size_t LabelType;\ntypedef opengm::meta::TypeListGenerator<opengm::ExplicitFunction<ValueType,IndexType,LabelType> >::type FunctionListType;\ntypedef opengm::GraphicalModel<ValueType,opengm::Adder, FunctionListType, opengm::DiscreteSpace<IndexType,LabelType> > GM;\n\n\/\/*************************************\n\n\nint main() {\n\n std::vector<double> label_loss_multipliers;\n label_loss_multipliers.push_back(2.0);\n label_loss_multipliers.push_back(1.0);\n label_loss_multipliers.push_back(0.5);\n\n std::vector<double> node_loss_multipliers;\n node_loss_multipliers.push_back(5.0);\n node_loss_multipliers.push_back(6.0);\n node_loss_multipliers.push_back(7.0);\n node_loss_multipliers.push_back(8.0);\n\n \/\/ create loss\n opengm::learning::GeneralizedHammingLoss loss(node_loss_multipliers.begin(),\n node_loss_multipliers.end(),\n label_loss_multipliers.begin(),\n label_loss_multipliers.end());\n\n \/\/ evaluate for a test point\n std::vector<size_t> labels;\n labels.push_back(0);\n labels.push_back(1);\n labels.push_back(2);\n labels.push_back(2);\n\n std::vector<size_t> ground_truth;\n ground_truth.push_back(1);\n ground_truth.push_back(1);\n ground_truth.push_back(1);\n ground_truth.push_back(1);\n\n OPENGM_ASSERT_OP(loss.loss(labels.begin(), labels.end(), ground_truth.begin(), ground_truth.end()), ==, 17.5);\n\n \/\/ add loss to a model and evaluate for a given labeling\n GM gm;\n size_t numberOfLabels = 3;\n gm.addVariable(numberOfLabels);\n gm.addVariable(numberOfLabels);\n gm.addVariable(numberOfLabels);\n gm.addVariable(numberOfLabels);\n\n \/\/ add a unary to node 2 (if indexed from 1)\n opengm::ExplicitFunction<GM::ValueType,GM::IndexType,GM::LabelType> f(&numberOfLabels, &(numberOfLabels)+1, 2.0);\n size_t variableIndex = 1;\n gm.addFactor(gm.addFunction(f), &variableIndex, &variableIndex+1);\n OPENGM_ASSERT_OP(gm.evaluate(labels.begin()), ==, 2.0);\n\n \/\/ loss augmented model:\n loss.addLoss(gm, ground_truth.begin());\n OPENGM_ASSERT_OP(gm.evaluate(labels.begin()), ==, 19.5);\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"Common.h\"\n#include \"Logging.h\"\n\n#include <stdarg.h>\n#include <time.h>\n\nVINYL_NS_BEGIN;\n\nnamespace Log\n{\n\tFormatVar::FormatVar(int i)\n\t{\n\t\tm_type = FVT_Integer;\n\t\tm_data = (void*)i;\n\t}\n\n\tFormatVar::FormatVar(const char* str)\n\t{\n\t\tm_type = FVT_String;\n\t\tm_data = (void*)str;\n\t}\n\n\tFormatVar::FormatVar(char c)\n\t{\n\t\tm_type = FVT_Char;\n\t\tm_data = (void*)c;\n\t}\n\n\tFormatVar::~FormatVar()\n\t{\n\t\tif (m_cache != nullptr) {\n\t\t\tfree(m_cache);\n\t\t}\n\t}\n\n\tconst char* FormatVar::GetString()\n\t{\n\t\tif (m_type == FVT_Integer) {\n\t\t\tif (m_cache == nullptr) {\n\t\t\t\tm_cache = (char*)malloc(14);\n\t\t\t}\n\t\t\tint num = (int)m_data;\n\t\t\tsnprintf(m_cache, 14, \"%d\", num);\n\t\t\treturn m_cache;\n\n\t\t} else if (m_type == FVT_String) {\n\t\t\treturn (const char*)m_data;\n\n\t\t} else if (m_type == FVT_Char) {\n\t\t\tif (m_cache == nullptr) {\n\t\t\t\tm_cache = (char*)malloc(2);\n\t\t\t\tm_cache[1] = '\\0';\n\t\t\t}\n\t\t\tm_cache[0] = (char)(int)m_data;\n\t\t\treturn m_cache;\n\t\t}\n\n\t\treturn \"\";\n\t}\n\n\ts::String Format(const char* format, va_list vl)\n\t{\n\t\ts::StackArray<FormatVar> vars;\n\t\tvars.sa_bOnlyPop = true;\n\n\t\tint numHighest = 0;\n\n\t\tint bufferLen = 128;\n\t\ts::String ret;\n\n\t\tint len = strlen(format);\n\t\tfor (int i = 0; i < len; i++) {\n\t\t\tchar c = format[i];\n\t\t\tif (c == '%') {\n\t\t\t\tchar cn = format[++i];\n\t\t\t\tchar str[5];\n\t\t\t\tint strc = 0;\n\t\t\t\twhile (cn >= '0' && cn <= '9' && strc < 4 && i < len) {\n\t\t\t\t\tstr[strc] = cn;\n\t\t\t\t\tstrc++;\n\t\t\t\t\tcn = format[++i];\n\t\t\t\t}\n\t\t\t\ti--;\n\t\t\t\tstr[strc] = '\\0';\n\t\t\t\tint num = atoi(str);\n\t\t\t\tif (num == 0) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif (num > numHighest) {\n\t\t\t\t\tfor (int j = numHighest; j < num; j++) {\n\t\t\t\t\t\tFormatVar &newvar = va_arg(vl, FormatVar);\n\t\t\t\t\t\tvars.Push(&newvar);\n\t\t\t\t\t}\n\t\t\t\t\tnumHighest = num;\n\t\t\t\t}\n\t\t\t\tFormatVar &var = vars[num - 1];\n\t\t\t\tret += var.GetString();\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tret += c;\n\t\t}\n\n\t\treturn ret;\n\t}\n\n\tLogLevel Level = LogLevel_Info;\n\n\tstatic s::Mutex _mutex;\n\n\tstatic void LogLine(const char* keyword, const s::String &str, int16_t color_windows, const char* color_linux)\n\t{\n\t\t_mutex.Lock();\n\n#define LOG_FORMAT_BEGIN \"%7s | %02d:%02d:%02d | \"\n\n\t\ttime_t t = time(nullptr);\n\t\ttm tms;\n#if WINDOWS\n\t\tlocaltime_s(&tms, &t);\n#else\n\t\tlocaltime_r(&t, &tms);\n#endif\n\n\t\ts::String lineBegin = s::strPrintF(LOG_FORMAT_BEGIN, keyword, tms.tm_hour, tms.tm_min, tms.tm_sec);\n\n#if WINDOWS\n\t\tHANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);\n\t\tSetConsoleTextAttribute(hConsole, color_windows);\n\t\tprintf(\"%s%s\\n\", (const char*)lineBegin, (const char*)str);\n\t\tSetConsoleTextAttribute(hConsole, 7);\n#else\n\t\tprintf(\"\\x1B[%sm%s%s\\x1B[0m\\n\", color_linux, (const char*)lineBegin, (const char*)str);\n#endif\n\n\t\t_mutex.Unlock();\n\t}\n\n\tvoid Trace(const char* format, ...)\n\t{\n\t\tif (Level > LogLevel_Trace) {\n\t\t\treturn;\n\t\t}\n\n\t\tva_list vl;\n\t\tva_start(vl, format);\n\t\ts::String str = Format(format, vl);\n\t\tva_end(vl);\n\n\t\tLogLine(\"TRACE\", str, 8, \"02\");\n\t}\n\n\tvoid Debug(const char* format, ...)\n\t{\n\t\tif (Level > LogLevel_Debug) {\n\t\t\treturn;\n\t\t}\n\n\t\tva_list vl;\n\t\tva_start(vl, format);\n\t\ts::String str = Format(format, vl);\n\t\tva_end(vl);\n\n\t\tLogLine(\"DEBUG\", str, 7, \"38\");\n\t}\n\n\tvoid Info(const char* format, ...)\n\t{\n\t\tif (Level > LogLevel_Info) {\n\t\t\treturn;\n\t\t}\n\n\t\tva_list vl;\n\t\tva_start(vl, format);\n\t\ts::String str = Format(format, vl);\n\t\tva_end(vl);\n\n\t\tLogLine(\"INFO\", str, 15, \"37\");\n\t}\n\n\tvoid Warning(const char* format, ...)\n\t{\n\t\tif (Level > LogLevel_Warning) {\n\t\t\treturn;\n\t\t}\n\n\t\tva_list vl;\n\t\tva_start(vl, format);\n\t\ts::String str = Format(format, vl);\n\t\tva_end(vl);\n\n\t\tLogLine(\"WARNING\", str, 13, \"35\");\n\t}\n\n\tvoid Error(const char* format, ...)\n\t{\n\t\tif (Level > LogLevel_Error) {\n\t\t\treturn;\n\t\t}\n\n\t\tva_list vl;\n\t\tva_start(vl, format);\n\t\ts::String str = Format(format, vl);\n\t\tva_end(vl);\n\n\t\tLogLine(\"ERROR\", str, 14, \"33\");\n\t}\n\n\tvoid Fatal(const char* format, ...)\n\t{\n\t\tif (Level > LogLevel_Fatal) {\n\t\t\treturn;\n\t\t}\n\n\t\tva_list vl;\n\t\tva_start(vl, format);\n\t\ts::String str = Format(format, vl);\n\t\tva_end(vl);\n\n\t\tLogLine(\"FATAL\", str, 12, \"31\");\n\t}\n}\n\nVINYL_NS_END;\n<commit_msg>Fix linux build<commit_after>#include \"Common.h\"\n#include \"Logging.h\"\n\n#include <stdarg.h>\n#include <time.h>\n\nVINYL_NS_BEGIN;\n\nnamespace Log\n{\n\tFormatVar::FormatVar(int i)\n\t{\n\t\tm_type = FVT_Integer;\n\t\tm_data = (void*)i;\n\t}\n\n\tFormatVar::FormatVar(const char* str)\n\t{\n\t\tm_type = FVT_String;\n\t\tm_data = (void*)str;\n\t}\n\n\tFormatVar::FormatVar(char c)\n\t{\n\t\tm_type = FVT_Char;\n\t\tm_data = (void*)c;\n\t}\n\n\tFormatVar::~FormatVar()\n\t{\n\t\tif (m_cache != nullptr) {\n\t\t\tfree(m_cache);\n\t\t}\n\t}\n\n\tconst char* FormatVar::GetString()\n\t{\n\t\tif (m_type == FVT_Integer) {\n\t\t\tif (m_cache == nullptr) {\n\t\t\t\tm_cache = (char*)malloc(14);\n\t\t\t}\n#ifdef _LP64\n\t\t\tint num = (int)(long int)m_data;\n#else\n\t\t\tint num = (int)m_data;\n#endif\n\t\t\tsnprintf(m_cache, 14, \"%d\", num);\n\t\t\treturn m_cache;\n\n\t\t} else if (m_type == FVT_String) {\n\t\t\treturn (const char*)m_data;\n\n\t\t} else if (m_type == FVT_Char) {\n\t\t\tif (m_cache == nullptr) {\n\t\t\t\tm_cache = (char*)malloc(2);\n\t\t\t\tm_cache[1] = '\\0';\n\t\t\t}\n#ifdef _LP64\n\t\t\tm_cache[0] = (char)(long int)m_data;\n#else\n\t\t\tm_cache[0] = (char)(int)m_data;\n#endif\n\t\t\treturn m_cache;\n\t\t}\n\n\t\treturn \"\";\n\t}\n\n\ts::String Format(const char* format, va_list vl)\n\t{\n\t\ts::StackArray<FormatVar> vars;\n\t\tvars.sa_bOnlyPop = true;\n\n\t\tint numHighest = 0;\n\n\t\tint bufferLen = 128;\n\t\ts::String ret;\n\n\t\tint len = strlen(format);\n\t\tfor (int i = 0; i < len; i++) {\n\t\t\tchar c = format[i];\n\t\t\tif (c == '%') {\n\t\t\t\tchar cn = format[++i];\n\t\t\t\tchar str[5];\n\t\t\t\tint strc = 0;\n\t\t\t\twhile (cn >= '0' && cn <= '9' && strc < 4 && i < len) {\n\t\t\t\t\tstr[strc] = cn;\n\t\t\t\t\tstrc++;\n\t\t\t\t\tcn = format[++i];\n\t\t\t\t}\n\t\t\t\ti--;\n\t\t\t\tstr[strc] = '\\0';\n\t\t\t\tint num = atoi(str);\n\t\t\t\tif (num == 0) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif (num > numHighest) {\n\t\t\t\t\tfor (int j = numHighest; j < num; j++) {\n\t\t\t\t\t\tFormatVar &newvar = va_arg(vl, FormatVar);\n\t\t\t\t\t\tvars.Push(&newvar);\n\t\t\t\t\t}\n\t\t\t\t\tnumHighest = num;\n\t\t\t\t}\n\t\t\t\tFormatVar &var = vars[num - 1];\n\t\t\t\tret += var.GetString();\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tret += c;\n\t\t}\n\n\t\treturn ret;\n\t}\n\n\tLogLevel Level = LogLevel_Info;\n\n\tstatic s::Mutex _mutex;\n\n\tstatic void LogLine(const char* keyword, const s::String &str, int16_t color_windows, const char* color_linux)\n\t{\n\t\t_mutex.Lock();\n\n#define LOG_FORMAT_BEGIN \"%7s | %02d:%02d:%02d | \"\n\n\t\ttime_t t = time(nullptr);\n\t\ttm tms;\n#if WINDOWS\n\t\tlocaltime_s(&tms, &t);\n#else\n\t\tlocaltime_r(&t, &tms);\n#endif\n\n\t\ts::String lineBegin = s::strPrintF(LOG_FORMAT_BEGIN, keyword, tms.tm_hour, tms.tm_min, tms.tm_sec);\n\n#if WINDOWS\n\t\tHANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);\n\t\tSetConsoleTextAttribute(hConsole, color_windows);\n\t\tprintf(\"%s%s\\n\", (const char*)lineBegin, (const char*)str);\n\t\tSetConsoleTextAttribute(hConsole, 7);\n#else\n\t\tprintf(\"\\x1B[%sm%s%s\\x1B[0m\\n\", color_linux, (const char*)lineBegin, (const char*)str);\n#endif\n\n\t\t_mutex.Unlock();\n\t}\n\n\tvoid Trace(const char* format, ...)\n\t{\n\t\tif (Level > LogLevel_Trace) {\n\t\t\treturn;\n\t\t}\n\n\t\tva_list vl;\n\t\tva_start(vl, format);\n\t\ts::String str = Format(format, vl);\n\t\tva_end(vl);\n\n\t\tLogLine(\"TRACE\", str, 8, \"02\");\n\t}\n\n\tvoid Debug(const char* format, ...)\n\t{\n\t\tif (Level > LogLevel_Debug) {\n\t\t\treturn;\n\t\t}\n\n\t\tva_list vl;\n\t\tva_start(vl, format);\n\t\ts::String str = Format(format, vl);\n\t\tva_end(vl);\n\n\t\tLogLine(\"DEBUG\", str, 7, \"38\");\n\t}\n\n\tvoid Info(const char* format, ...)\n\t{\n\t\tif (Level > LogLevel_Info) {\n\t\t\treturn;\n\t\t}\n\n\t\tva_list vl;\n\t\tva_start(vl, format);\n\t\ts::String str = Format(format, vl);\n\t\tva_end(vl);\n\n\t\tLogLine(\"INFO\", str, 15, \"37\");\n\t}\n\n\tvoid Warning(const char* format, ...)\n\t{\n\t\tif (Level > LogLevel_Warning) {\n\t\t\treturn;\n\t\t}\n\n\t\tva_list vl;\n\t\tva_start(vl, format);\n\t\ts::String str = Format(format, vl);\n\t\tva_end(vl);\n\n\t\tLogLine(\"WARNING\", str, 13, \"35\");\n\t}\n\n\tvoid Error(const char* format, ...)\n\t{\n\t\tif (Level > LogLevel_Error) {\n\t\t\treturn;\n\t\t}\n\n\t\tva_list vl;\n\t\tva_start(vl, format);\n\t\ts::String str = Format(format, vl);\n\t\tva_end(vl);\n\n\t\tLogLine(\"ERROR\", str, 14, \"33\");\n\t}\n\n\tvoid Fatal(const char* format, ...)\n\t{\n\t\tif (Level > LogLevel_Fatal) {\n\t\t\treturn;\n\t\t}\n\n\t\tva_list vl;\n\t\tva_start(vl, format);\n\t\ts::String str = Format(format, vl);\n\t\tva_end(vl);\n\n\t\tLogLine(\"FATAL\", str, 12, \"31\");\n\t}\n}\n\nVINYL_NS_END;\n<|endoftext|>"} {"text":"<commit_before>#include \"Manager.h\"\n\n#include \"BeginRequestRecord.h\"\n#include \"EnumHelpers.h\"\n#include \"ParametersRecord.h\"\n#include \"RecordHeader.h\"\n#include \"StandardInputRecord.h\"\n\n#include \"fastcgi.h\"\n\n#include <QDebug>\n#include <QFile>\n#include <QHostAddress>\n#include <QLocalSocket>\n#include <QSignalMapper>\n\n#include <errno.h>\n#include <sys\/file.h>\n#include <sys\/socket.h>\n#include <sys\/un.h>\n\nnamespace FastCgiQt\n{\n\tManager::Manager(ResponderGenerator responderGenerator, QObject* parent)\n\t\t:\n\t\t\tQObject(parent),\n\t\t\tm_responderGenerator(responderGenerator),\n\t\t\tm_socket(new QLocalSocket(this)),\n\t\t\tm_socketMapper(new QSignalMapper(this))\n\t{\n\t\tconnect(\n\t\t\tm_socketMapper,\n\t\t\tSIGNAL(mapped(int)),\n\t\t\tthis,\n\t\t\tSLOT(processSocketData(int))\n\t\t);\n\n\t\t\/\/ Initialise socket address structure\n\t\tsockaddr_un sa;\n\t\tsocklen_t len = sizeof(sa);\n\t\tmemset(&sa, 0, len);\n\n\t\t\/\/ The recommended way of telling if we're running as fastcgi or not.\n\t\tint error = ::getpeername(FCGI_LISTENSOCK_FILENO, reinterpret_cast<sockaddr*>(&sa), &len);\n\t\tif(error == -1 && errno != ENOTCONN)\n\t\t{\n\t\t\tqDebug() << tr(\"CGI not supported.\");\n\t\t\treturn;\n\t\t}\n\n\t\t\/\/ Listen on the socket\n\t\tqDebug() << \"Accepting socket\";\n\t\tlockSocket(FCGI_LISTENSOCK_FILENO);\n\t\tint newSocket = ::accept(FCGI_LISTENSOCK_FILENO, reinterpret_cast<sockaddr*>(&sa), &len);\n\t\treleaseSocket(FCGI_LISTENSOCK_FILENO);\n\t\t::close(FCGI_LISTENSOCK_FILENO);\n\n\t\t\/\/ We're connected, setup a QAbstractSocket\n\t\tqDebug() << \"New socket:\" << newSocket;\n\t\tm_socket->setSocketDescriptor(newSocket, QLocalSocket::ConnectedState, QIODevice::ReadWrite);\n\t\t\/\/ Map readyReady to processSocketData(newSocket)\n\t\tconnect(\n\t\t\tm_socket,\n\t\t\tSIGNAL(readyRead()),\n\t\t\tm_socketMapper,\n\t\t\tSLOT(map())\n\t\t);\n\t\tm_socketMapper->setMapping(m_socket, newSocket);\n\t}\n\n\tvoid Manager::lockSocket(int socket)\n\t{\n\t\t::flock(socket, LOCK_EX);\n\t}\n\n\tvoid Manager::releaseSocket(int socket)\n\t{\n\t\t::flock(socket, LOCK_UN);\n\t}\n\n\tvoid Manager::processSocketData(int socket)\n\t{\n\t\tbool success;\n\t\tdo\n\t\t{\n\t\t\tif(!m_socketHeaders.contains(socket))\n\t\t\t{\n\t\t\t\tsuccess = processNewRecord(socket);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tsuccess = processRecordData(socket);\n\t\t\t}\n\t\t}\n\t\twhile(success && m_socket->bytesAvailable() > 0);\n\t}\n\n\tbool Manager::processRecordData(int socket)\n\t{\n\t\tqDebug() << \"Payload on socket\" << socket;\n\t\tconst RecordHeader header(m_socketHeaders.value(socket));\n\t\tif(m_socket->bytesAvailable() < header.payloadLength())\n\t\t{\n\t\t\treturn false;\n\t\t}\n\n\t\tQByteArray data = m_socket->read(header.payloadLength());\n\t\tqint64 bytesRead = data.length();\n\n\t\tif(bytesRead != header.payloadLength())\n\t\t{\n\t\t\tqFatal(\"Couldn't read payload - tried to read %d bytes, got %d\", header.payloadLength(), bytesRead);\n\t\t}\n\t\tswitch(header.type())\n\t\t{\n\t\t\tcase RecordHeader::BeginRequestRecord:\n\t\t\t\tbeginRequest(header, data);\n\t\t\t\tbreak;\n\t\t\tcase RecordHeader::ParametersRecord:\n\t\t\t\tloadParameters(header, data);\n\t\t\t\tbreak;\n\t\t\tcase RecordHeader::StandardInputRecord:\n\t\t\t\treadStandardInput(header, data);\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tqDebug() << \"Got query string data\" << m_requests[header.requestId()].getData();\n\t\t\t\tqFatal(\"Don't know how to deal with payload for type %s\", ENUM_DEBUG_STRING(RecordHeader,RecordType,header.type()));\n\t\t}\n\t\tm_socketHeaders.remove(socket);\n\t\treturn true;\n\t}\n\n\tvoid Manager::loadParameters(const RecordHeader& header, const QByteArray& data)\n\t{\n\t\tQ_ASSERT(header.type() == RecordHeader::ParametersRecord);\n\t\tQ_ASSERT(m_requests.value(header.requestId()).isValid());\n\t\tParametersRecord record(header, data);\n\t\tm_requests[header.requestId()].addServerData(record.parameters());\n\t}\n\n\tvoid Manager::readStandardInput(const RecordHeader& header, const QByteArray& data)\n\t{\n\t\tQ_ASSERT(header.type() == RecordHeader::StandardInputRecord);\n\t\tQ_ASSERT(m_requests.value(header.requestId()).isValid());\n\t\tStandardInputRecord record(header, data);\n\t\tm_requests[header.requestId()].appendContent(record.streamData());\n\t\tif(m_requests[header.requestId()].haveContent())\n\t\t{\n\t\t\trespond(header.requestId());\n\t\t}\n\t\tqDebug() << \"Read standard input - done?\" << m_requests.value(header.requestId()).haveContent();\n\t}\n\n\tvoid Manager::beginRequest(const RecordHeader& header, const QByteArray& data)\n\t{\n\t\tQ_ASSERT(header.type() == RecordHeader::BeginRequestRecord);\n\t\tQ_ASSERT(!m_requests.value(header.requestId()).isValid());\n\t\tBeginRequestRecord record(header, *reinterpret_cast<const FCGI_BeginRequestBody*>(data.constData()));\n\t\tqDebug() << \"Got new begin request with id\" << record.requestId() << \"role\" << record.role() << \"flags\" << record.flags();\n\t\tQ_ASSERT(record.role() == BeginRequestRecord::ResponderRole);\n\n\t\tif(m_requests.size() -1 < record.requestId())\n\t\t{\n\t\t\tm_requests.resize((record.requestId() + 1) + 2);\n\t\t\tm_requests[record.requestId()] = Request(record.requestId());\n\t\t}\n\t}\n\n\tvoid Manager::respond(quint16 requestId)\n\t{\n\t\tResponder* responder = (*m_responderGenerator)(\n\t\t\tm_requests.at(requestId),\n\t\t\tm_socket,\n\t\t\tthis\n\t\t);\n\t\tresponder->respond();\n\t\tqDebug() << \"responded\";\n\t\t\/\/\/@todo send end request\n\t\tdelete responder;\n\t}\n\n\tbool Manager::processNewRecord(int socket)\n\t{\n\t\tqDebug() << \"New record on socket\" << socket;\n\t\tif(m_socket->bytesAvailable() < FCGI_HEADER_LEN)\n\t\t{\n\t\t\treturn false;\n\t\t}\n\n\t\tFCGI_Header fcgiHeader;\n\t\tqint64 bytesRead = m_socket->read(reinterpret_cast<char*>(&fcgiHeader), FCGI_HEADER_LEN);\n\t\tif(bytesRead != FCGI_HEADER_LEN)\n\t\t{\n\t\t\tqFatal(\"Couldn't read FCGI header - tried to read %d bytes, got %d\", FCGI_HEADER_LEN, bytesRead);\n\t\t}\n\t\tRecordHeader header(fcgiHeader);\n\t\tqDebug() << \"Got header with record type\" << header.type() << \"id\" << header.requestId() << \"payload size\" << header.payloadLength() << \"content size\" << header.contentLength();\n\t\tm_socketHeaders.insert(socket, header);\n\t\tif(m_socket->bytesAvailable() >= header.payloadLength())\n\t\t{\n\t\t\tprocessRecordData(socket);\n\t\t}\n\t\treturn true;\n\t}\n}\n<commit_msg>send EndRequestRecords<commit_after>#include \"Manager.h\"\n\n#include \"BeginRequestRecord.h\"\n#include \"EndRequestRecord.h\"\n#include \"EnumHelpers.h\"\n#include \"ParametersRecord.h\"\n#include \"RecordHeader.h\"\n#include \"StandardInputRecord.h\"\n\n#include \"fastcgi.h\"\n\n#include <QDebug>\n#include <QFile>\n#include <QHostAddress>\n#include <QLocalSocket>\n#include <QSignalMapper>\n\n#include <errno.h>\n#include <sys\/file.h>\n#include <sys\/socket.h>\n#include <sys\/un.h>\n\nnamespace FastCgiQt\n{\n\tManager::Manager(ResponderGenerator responderGenerator, QObject* parent)\n\t\t:\n\t\t\tQObject(parent),\n\t\t\tm_responderGenerator(responderGenerator),\n\t\t\tm_socket(new QLocalSocket(this)),\n\t\t\tm_socketMapper(new QSignalMapper(this))\n\t{\n\t\tconnect(\n\t\t\tm_socketMapper,\n\t\t\tSIGNAL(mapped(int)),\n\t\t\tthis,\n\t\t\tSLOT(processSocketData(int))\n\t\t);\n\n\t\t\/\/ Initialise socket address structure\n\t\tsockaddr_un sa;\n\t\tsocklen_t len = sizeof(sa);\n\t\tmemset(&sa, 0, len);\n\n\t\t\/\/ The recommended way of telling if we're running as fastcgi or not.\n\t\tint error = ::getpeername(FCGI_LISTENSOCK_FILENO, reinterpret_cast<sockaddr*>(&sa), &len);\n\t\tif(error == -1 && errno != ENOTCONN)\n\t\t{\n\t\t\tqDebug() << tr(\"CGI not supported.\");\n\t\t\treturn;\n\t\t}\n\n\t\t\/\/ Listen on the socket\n\t\tqDebug() << \"Accepting socket\";\n\t\tlockSocket(FCGI_LISTENSOCK_FILENO);\n\t\tint newSocket = ::accept(FCGI_LISTENSOCK_FILENO, reinterpret_cast<sockaddr*>(&sa), &len);\n\t\treleaseSocket(FCGI_LISTENSOCK_FILENO);\n\t\t::close(FCGI_LISTENSOCK_FILENO);\n\n\t\t\/\/ We're connected, setup a QAbstractSocket\n\t\tqDebug() << \"New socket:\" << newSocket;\n\t\tm_socket->setSocketDescriptor(newSocket, QLocalSocket::ConnectedState, QIODevice::ReadWrite);\n\t\t\/\/ Map readyReady to processSocketData(newSocket)\n\t\tconnect(\n\t\t\tm_socket,\n\t\t\tSIGNAL(readyRead()),\n\t\t\tm_socketMapper,\n\t\t\tSLOT(map())\n\t\t);\n\t\tm_socketMapper->setMapping(m_socket, newSocket);\n\t}\n\n\tvoid Manager::lockSocket(int socket)\n\t{\n\t\t::flock(socket, LOCK_EX);\n\t}\n\n\tvoid Manager::releaseSocket(int socket)\n\t{\n\t\t::flock(socket, LOCK_UN);\n\t}\n\n\tvoid Manager::processSocketData(int socket)\n\t{\n\t\tbool success;\n\t\tdo\n\t\t{\n\t\t\tif(!m_socketHeaders.contains(socket))\n\t\t\t{\n\t\t\t\tsuccess = processNewRecord(socket);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tsuccess = processRecordData(socket);\n\t\t\t}\n\t\t}\n\t\twhile(success && m_socket->bytesAvailable() > 0);\n\t}\n\n\tbool Manager::processRecordData(int socket)\n\t{\n\t\tqDebug() << \"Payload on socket\" << socket;\n\t\tconst RecordHeader header(m_socketHeaders.value(socket));\n\t\tif(m_socket->bytesAvailable() < header.payloadLength())\n\t\t{\n\t\t\treturn false;\n\t\t}\n\n\t\tQByteArray data = m_socket->read(header.payloadLength());\n\t\tqint64 bytesRead = data.length();\n\n\t\tif(bytesRead != header.payloadLength())\n\t\t{\n\t\t\tqFatal(\"Couldn't read payload - tried to read %d bytes, got %d\", header.payloadLength(), bytesRead);\n\t\t}\n\t\tswitch(header.type())\n\t\t{\n\t\t\tcase RecordHeader::BeginRequestRecord:\n\t\t\t\tbeginRequest(header, data);\n\t\t\t\tbreak;\n\t\t\tcase RecordHeader::ParametersRecord:\n\t\t\t\tloadParameters(header, data);\n\t\t\t\tbreak;\n\t\t\tcase RecordHeader::StandardInputRecord:\n\t\t\t\treadStandardInput(header, data);\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tqDebug() << \"Got query string data\" << m_requests[header.requestId()].getData();\n\t\t\t\tqFatal(\"Don't know how to deal with payload for type %s\", ENUM_DEBUG_STRING(RecordHeader,RecordType,header.type()));\n\t\t}\n\t\tm_socketHeaders.remove(socket);\n\t\treturn true;\n\t}\n\n\tvoid Manager::loadParameters(const RecordHeader& header, const QByteArray& data)\n\t{\n\t\tQ_ASSERT(header.type() == RecordHeader::ParametersRecord);\n\t\tQ_ASSERT(m_requests.value(header.requestId()).isValid());\n\t\tParametersRecord record(header, data);\n\t\tm_requests[header.requestId()].addServerData(record.parameters());\n\t}\n\n\tvoid Manager::readStandardInput(const RecordHeader& header, const QByteArray& data)\n\t{\n\t\tQ_ASSERT(header.type() == RecordHeader::StandardInputRecord);\n\t\tQ_ASSERT(m_requests.value(header.requestId()).isValid());\n\t\tStandardInputRecord record(header, data);\n\t\tm_requests[header.requestId()].appendContent(record.streamData());\n\t\tif(m_requests[header.requestId()].haveContent())\n\t\t{\n\t\t\trespond(header.requestId());\n\t\t}\n\t}\n\n\tvoid Manager::beginRequest(const RecordHeader& header, const QByteArray& data)\n\t{\n\t\tQ_ASSERT(header.type() == RecordHeader::BeginRequestRecord);\n\t\tQ_ASSERT(!m_requests.value(header.requestId()).isValid());\n\t\tBeginRequestRecord record(header, *reinterpret_cast<const FCGI_BeginRequestBody*>(data.constData()));\n\t\tqDebug() << \"Got new begin request with id\" << record.requestId() << \"role\" << record.role() << \"flags\" << record.flags();\n\t\tQ_ASSERT(record.role() == BeginRequestRecord::ResponderRole);\n\n\t\tif(m_requests.size() -1 < record.requestId())\n\t\t{\n\t\t\tm_requests.resize((record.requestId() + 1) + 2);\n\t\t\tm_requests[record.requestId()] = Request(record.requestId());\n\t\t}\n\t}\n\n\tvoid Manager::respond(quint16 requestId)\n\t{\n\t\tResponder* responder = (*m_responderGenerator)(\n\t\t\tm_requests.at(requestId),\n\t\t\tm_socket,\n\t\t\tthis\n\t\t);\n\t\tresponder->respond();\n\t\tm_socket->write(EndRequestRecord::create(requestId));\n\t\tqDebug() << \"responded\";\n\t\tdelete responder;\n\t}\n\n\tbool Manager::processNewRecord(int socket)\n\t{\n\t\tqDebug() << \"New record on socket\" << socket;\n\t\tif(m_socket->bytesAvailable() < FCGI_HEADER_LEN)\n\t\t{\n\t\t\treturn false;\n\t\t}\n\n\t\tFCGI_Header fcgiHeader;\n\t\tqint64 bytesRead = m_socket->read(reinterpret_cast<char*>(&fcgiHeader), FCGI_HEADER_LEN);\n\t\tif(bytesRead != FCGI_HEADER_LEN)\n\t\t{\n\t\t\tqFatal(\"Couldn't read FCGI header - tried to read %d bytes, got %d\", FCGI_HEADER_LEN, bytesRead);\n\t\t}\n\t\tRecordHeader header(fcgiHeader);\n\t\tqDebug() << \"Got header with record type\" << header.type() << \"id\" << header.requestId() << \"payload size\" << header.payloadLength() << \"content size\" << header.contentLength();\n\t\tm_socketHeaders.insert(socket, header);\n\t\tif(m_socket->bytesAvailable() >= header.payloadLength())\n\t\t{\n\t\t\tprocessRecordData(socket);\n\t\t}\n\t\treturn true;\n\t}\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ $Id$\n\n\/\/ The libMesh Finite Element Library.\n\/\/ Copyright (C) 2002-2007 Benjamin S. Kirk, John W. Peterson\n \n\/\/ This library is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU Lesser General Public\n\/\/ License as published by the Free Software Foundation; either\n\/\/ version 2.1 of the License, or (at your option) any later version.\n \n\/\/ This library is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ Lesser General Public License for more details.\n \n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License along with this library; if not, write to the Free Software\n\/\/ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n\n\n\/\/ System Includes\n#include <algorithm>\n#include <iostream>\n\n\/\/ Local Includes\n#include \"libmesh_common.h\"\n#include \"parallel.h\"\n#include \"parallel_sort.h\"\n#include \"parallel_bin_sorter.h\"\n#ifdef HAVE_LIBHILBERT\n# include \"hilbert.h\"\n#endif\n\n\nnamespace Parallel {\n \n\/\/ The Constructor sorts the local data using\n\/\/ std::sort(). Therefore, the construction of\n\/\/ a Parallel::Sort object takes O(nlogn) time,\n\/\/ where n is the length of _data.\ntemplate <typename KeyType>\nSort<KeyType>::Sort(std::vector<KeyType>& d,\n\t\t const unsigned int n_procs,\n\t\t const unsigned int proc_id) :\t \n _n_procs(n_procs),\n _proc_id(proc_id),\n _bin_is_sorted(false),\n _data(d)\n{\n std::sort(_data.begin(), _data.end());\n\n \/\/ Allocate storage\n _local_bin_sizes.resize(_n_procs);\n}\n\n\n\ntemplate <typename KeyType>\nvoid Sort<KeyType>::sort()\n{\n this->binsort();\n this->communicate_bins();\n this->sort_local_bin();\n\n \/\/ Set sorted flag to true\n _bin_is_sorted = true;\n}\n\n\n\ntemplate <typename KeyType>\nvoid Sort<KeyType>::binsort()\n{\n \/\/ Find the global min and max from all the\n \/\/ processors.\n std::vector<KeyType> global_min_max(2);\n\n \/\/ Insert the local min and max for this processor\n global_min_max[0] = -_data.front();\n global_min_max[1] = _data.back();\n\n \/\/ Communicate to determine the global\n \/\/ min and max for all processors.\n Parallel::max(global_min_max);\n\n \/\/ Multiply the min by -1 to obtain the true min\n global_min_max[0] *= -1;\n\n \/\/ Bin-Sort based on the global min and max\n Parallel::BinSorter<KeyType> bs(_data);\n bs.binsort(_n_procs, global_min_max[1], global_min_max[0]);\n\n \/\/ Now save the local bin sizes in a vector so\n \/\/ we don't have to keep around the BinSorter.\n for (unsigned int i=0; i<_n_procs; ++i)\n _local_bin_sizes[i] = bs.sizeof_bin(i);\n}\n\n\n\n#if defined(HAVE_LIBHILBERT) && defined(HAVE_MPI)\n\/\/ Full specialization for HilbertIndices, there is a fair amount of\n\/\/ code duplication here that could potentially be consolidated with the \n\/\/ above method\ntemplate <>\nvoid Sort<Hilbert::HilbertIndices>::binsort()\n{\n \/\/ Find the global min and max from all the\n \/\/ processors. Do this using MPI_Allreduce.\n Hilbert::HilbertIndices \n local_min, local_max,\n global_min, global_max;\n\n if (_data.empty())\n {\n local_min.rack0 = local_min.rack1 = local_min.rack2 = static_cast<Hilbert::inttype>(-1);\n local_max.rack0 = local_max.rack1 = local_max.rack2 = 0;\n }\n else\n {\n local_min = _data.front();\n local_max = _data.back();\n }\n \n MPI_Op hilbert_max, hilbert_min;\n MPI_Datatype hilbert_type;\n\n MPI_Type_contiguous (3, MPI_UNSIGNED, &hilbert_type);\n MPI_Type_commit (&hilbert_type);\n MPI_Op_create ((MPI_User_function*)__hilbert_max_op, true, &hilbert_max);\n MPI_Op_create ((MPI_User_function*)__hilbert_min_op, true, &hilbert_min);\n\n \/\/ Communicate to determine the global\n \/\/ min and max for all processors.\n MPI_Allreduce(&local_min,\n\t\t&global_min,\n\t\t1,\n\t\thilbert_type,\n\t\thilbert_min,\n\t\tlibMesh::COMM_WORLD);\n\n MPI_Allreduce(&local_max,\n\t\t&global_max,\n\t\t1,\n\t\thilbert_type,\n\t\thilbert_max,\n\t\tlibMesh::COMM_WORLD);\n\n MPI_Type_free (&hilbert_type);\n MPI_Op_free (&hilbert_max);\n MPI_Op_free (&hilbert_min);\n\n \/\/ Bin-Sort based on the global min and max\n Parallel::BinSorter<Hilbert::HilbertIndices> bs(_data);\n bs.binsort(_n_procs, global_max, global_min);\n\n \/\/ Now save the local bin sizes in a vector so\n \/\/ we don't have to keep around the BinSorter.\n for (unsigned int i=0; i<_n_procs; ++i)\n _local_bin_sizes[i] = bs.sizeof_bin(i);\n}\n\n#endif \/\/ #ifdef HAVE_LIBHILBERT\n\n\ntemplate <typename KeyType>\nvoid Sort<KeyType>::communicate_bins()\n{\n#ifdef HAVE_MPI\n \/\/ Create storage for the global bin sizes. This\n \/\/ is the number of keys which will be held in\n \/\/ each bin over all processors.\n std::vector<unsigned int> global_bin_sizes = _local_bin_sizes;\n \n \/\/ Sum to find the total number of entries in each bin.\n Parallel::sum(global_bin_sizes);\n\n \/\/ Create a vector to temporarily hold the results of MPI_Gatherv\n \/\/ calls. The vector dest may be saved away to _my_bin depending on which\n \/\/ processor is being MPI_Gatherv'd.\n std::vector<KeyType> dest;\n\n unsigned int local_offset = 0;\n \n for (unsigned int i=0; i<_n_procs; ++i)\n {\n \/\/ Vector to receive the total bin size for each\n \/\/ processor. Processor i's bin size will be\n \/\/ held in proc_bin_size[i]\n std::vector<unsigned int> proc_bin_size;\n\n \/\/ Find the number of contributions coming from each\n \/\/ processor for this bin. Note: allgather combines\n \/\/ the MPI_Gather and MPI_Bcast operations into one.\n Parallel::allgather(_local_bin_sizes[i], proc_bin_size);\n\n \/\/ Compute the offsets into my_bin for each processor's\n \/\/ portion of the bin. These are basically partial sums\n \/\/ of the proc_bin_size vector.\n std::vector<unsigned int> displacements(_n_procs);\n for (unsigned int j=1; j<_n_procs; ++j)\n\tdisplacements[j] = proc_bin_size[j-1] + displacements[j-1];\n\n \/\/ Resize the destination buffer\n dest.resize (global_bin_sizes[i]);\n\t \n MPI_Gatherv((_data.size() > local_offset) ?\n\t\t &_data[local_offset] :\n\t\t NULL, \/\/ Points to the beginning of the bin to be sent\n\t\t _local_bin_sizes[i], \/\/ How much data is in the bin being sent.\n\t\t Parallel::datatype<KeyType>(), \/\/ The data type we are sorting\n\t\t (dest.empty()) ?\n\t\t NULL :\n\t\t &dest[0], \/\/ Enough storage to hold all bin contributions\n\t\t (int*) &proc_bin_size[0], \/\/ How much is to be received from each processor\n\t (int*) &displacements[0], \/\/ Offsets into the receive buffer\n\t\t Parallel::datatype<KeyType>(), \/\/ The data type we are sorting\n\t\t i, \/\/ The root process (we do this once for each proc)\n\t\t libMesh::COMM_WORLD);\n\n \/\/ Copy the destination buffer if it\n \/\/ corresponds to the bin for this processor\n if (i == _proc_id)\n\t_my_bin = dest;\n\t \n \/\/ Increment the local offset counter\n local_offset += _local_bin_sizes[i];\n } \n#endif \/\/ HAVE_MPI\n}\n\n\n\n#if defined(HAVE_LIBHILBERT) && defined(HAVE_MPI)\n\/\/ Full specialization for HilbertIndices, there is a fair amount of\n\/\/ code duplication here that could potentially be consolidated with the \n\/\/ above method\ntemplate <>\nvoid Sort<Hilbert::HilbertIndices>::communicate_bins()\n{\n \/\/ Create storage for the global bin sizes. This\n \/\/ is the number of keys which will be held in\n \/\/ each bin over all processors.\n std::vector<unsigned int> global_bin_sizes(_n_procs);\n \n assert (_local_bin_sizes.size() == global_bin_sizes.size());\n\n \/\/ Sum to find the total number of entries in each bin.\n \/\/ This is stored in global_bin_sizes. Note, we\n \/\/ explicitly know that we are communicating MPI_UNSIGNED's here.\n MPI_Allreduce(&_local_bin_sizes[0],\n\t\t&global_bin_sizes[0],\n\t\t_n_procs,\n\t\tMPI_UNSIGNED,\n\t\tMPI_SUM,\n\t\tlibMesh::COMM_WORLD);\n\n MPI_Datatype hilbert_type;\n\n MPI_Type_contiguous (3, MPI_UNSIGNED, &hilbert_type);\n MPI_Type_commit (&hilbert_type);\n\n \/\/ Create a vector to temporarily hold the results of MPI_Gatherv\n \/\/ calls. The vector dest may be saved away to _my_bin depending on which\n \/\/ processor is being MPI_Gatherv'd.\n std::vector<Hilbert::HilbertIndices> sendbuf, dest;\n\n unsigned int local_offset = 0;\n \n for (unsigned int i=0; i<_n_procs; ++i)\n {\n \/\/ Vector to receive the total bin size for each\n \/\/ processor. Processor i's bin size will be\n \/\/ held in proc_bin_size[i]\n std::vector<unsigned int> proc_bin_size(_n_procs);\n\n \/\/ Find the number of contributions coming from each\n \/\/ processor for this bin. Note: Allgather combines\n \/\/ the MPI_Gather and MPI_Bcast operations into one.\n \/\/ Note: Here again we know that we are communicating\n \/\/ MPI_UNSIGNED's so there is no need to check the MPI_traits.\n MPI_Allgather(&_local_bin_sizes[i], \/\/ Source: # of entries on this proc in bin i\n\t\t 1, \/\/ Number of items to gather \n\t\t MPI_UNSIGNED, \n\t\t &proc_bin_size[0], \/\/ Destination: Total # of entries in bin i\n\t\t 1,\n\t\t MPI_UNSIGNED,\n\t\t libMesh::COMM_WORLD);\n \n \/\/ Compute the offsets into my_bin for each processor's\n \/\/ portion of the bin. These are basically partial sums\n \/\/ of the proc_bin_size vector.\n std::vector<unsigned int> displacements(_n_procs);\n for (unsigned int j=1; j<_n_procs; ++j)\n\tdisplacements[j] = proc_bin_size[j-1] + displacements[j-1];\n\n \/\/ Resize the destination buffer\n dest.resize (global_bin_sizes[i]);\n \n MPI_Gatherv((_data.size() > local_offset) ?\n\t\t &_data[local_offset] :\n\t\t NULL, \/\/ Points to the beginning of the bin to be sent\n\t\t _local_bin_sizes[i], \/\/ How much data is in the bin being sent.\n\t\t hilbert_type, \/\/ The data type we are sorting\n\t\t (dest.empty()) ?\n\t\t NULL :\n\t\t &dest[0], \/\/ Enough storage to hold all bin contributions\n\t\t (int*) &proc_bin_size[0], \/\/ How much is to be received from each processor\n\t\t (int*) &displacements[0], \/\/ Offsets into the receive buffer\n\t\t hilbert_type, \/\/ The data type we are sorting\n\t\t i, \/\/ The root process (we do this once for each proc)\n\t\t libMesh::COMM_WORLD);\n\n \/\/ Copy the destination buffer if it\n \/\/ corresponds to the bin for this processor\n if (i == _proc_id)\n\t_my_bin = dest;\n\n \/\/ Increment the local offset counter\n local_offset += _local_bin_sizes[i];\n }\n\n MPI_Type_free (&hilbert_type); \n}\n\n#endif \/\/ #if defined(HAVE_LIBHILBERT) && defined(HAVE_MPI)\n\n\n\ntemplate <typename KeyType>\nvoid Sort<KeyType>::sort_local_bin()\n{\n std::sort(_my_bin.begin(), _my_bin.end());\n}\n\n\n\ntemplate <typename KeyType>\nconst std::vector<KeyType>& Sort<KeyType>::bin()\n{\n if (!_bin_is_sorted)\n {\n std::cout << \"Warning! Bin is not yet sorted!\" << std::endl; \n }\n\n return _my_bin;\n}\n\n}\n\n\n\n\/\/ Explicitly instantiate for int, double\ntemplate class Parallel::Sort<int>;\ntemplate class Parallel::Sort<double>;\n#if defined(HAVE_LIBHILBERT) && defined(HAVE_MPI)\ntemplate class Parallel::Sort<Hilbert::HilbertIndices>;\n#endif\n<commit_msg>handle the degenerate case where for some reason we try to sort a single item in parallel<commit_after>\/\/ $Id$\n\n\/\/ The libMesh Finite Element Library.\n\/\/ Copyright (C) 2002-2007 Benjamin S. Kirk, John W. Peterson\n \n\/\/ This library is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU Lesser General Public\n\/\/ License as published by the Free Software Foundation; either\n\/\/ version 2.1 of the License, or (at your option) any later version.\n \n\/\/ This library is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ Lesser General Public License for more details.\n \n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License along with this library; if not, write to the Free Software\n\/\/ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n\n\n\/\/ System Includes\n#include <algorithm>\n#include <iostream>\n\n\/\/ Local Includes\n#include \"libmesh_common.h\"\n#include \"parallel.h\"\n#include \"parallel_sort.h\"\n#include \"parallel_bin_sorter.h\"\n#ifdef HAVE_LIBHILBERT\n# include \"hilbert.h\"\n#endif\n\n\nnamespace Parallel {\n \n\/\/ The Constructor sorts the local data using\n\/\/ std::sort(). Therefore, the construction of\n\/\/ a Parallel::Sort object takes O(nlogn) time,\n\/\/ where n is the length of _data.\ntemplate <typename KeyType>\nSort<KeyType>::Sort(std::vector<KeyType>& d,\n\t\t const unsigned int n_procs,\n\t\t const unsigned int proc_id) :\t \n _n_procs(n_procs),\n _proc_id(proc_id),\n _bin_is_sorted(false),\n _data(d)\n{\n std::sort(_data.begin(), _data.end());\n\n \/\/ Allocate storage\n _local_bin_sizes.resize(_n_procs);\n}\n\n\n\ntemplate <typename KeyType>\nvoid Sort<KeyType>::sort()\n{\n \/\/ Find the global data size. The sorting\n \/\/ algorithms assume they have a range to\n \/\/ work with, so catch the degenerate cases here\n unsigned int global_data_size = _data.size();\n\n Parallel::sum (global_data_size);\n\n if (global_data_size < 2)\n {\n \/\/ the entire global range is either empty\n \/\/ or contains only one element\n _my_bin = _data;\n\n Parallel::allgather (static_cast<unsigned int>(_my_bin.size()),\n\t\t\t _local_bin_sizes);\n }\n else\n {\n this->binsort();\n this->communicate_bins();\n this->sort_local_bin();\n }\n \n \/\/ Set sorted flag to true\n _bin_is_sorted = true;\n}\n\n\n\ntemplate <typename KeyType>\nvoid Sort<KeyType>::binsort()\n{ \n \/\/ Find the global min and max from all the\n \/\/ processors.\n std::vector<KeyType> global_min_max(2);\n\n \/\/ Insert the local min and max for this processor\n global_min_max[0] = -_data.front();\n global_min_max[1] = _data.back();\n\n \/\/ Communicate to determine the global\n \/\/ min and max for all processors.\n Parallel::max(global_min_max);\n\n \/\/ Multiply the min by -1 to obtain the true min\n global_min_max[0] *= -1;\n\n \/\/ Bin-Sort based on the global min and max\n Parallel::BinSorter<KeyType> bs(_data);\n bs.binsort(_n_procs, global_min_max[1], global_min_max[0]);\n\n \/\/ Now save the local bin sizes in a vector so\n \/\/ we don't have to keep around the BinSorter.\n for (unsigned int i=0; i<_n_procs; ++i)\n _local_bin_sizes[i] = bs.sizeof_bin(i);\n}\n\n\n\n#if defined(HAVE_LIBHILBERT) && defined(HAVE_MPI)\n\/\/ Full specialization for HilbertIndices, there is a fair amount of\n\/\/ code duplication here that could potentially be consolidated with the \n\/\/ above method\ntemplate <>\nvoid Sort<Hilbert::HilbertIndices>::binsort()\n{\n \/\/ Find the global min and max from all the\n \/\/ processors. Do this using MPI_Allreduce.\n Hilbert::HilbertIndices \n local_min, local_max,\n global_min, global_max;\n\n if (_data.empty())\n {\n local_min.rack0 = local_min.rack1 = local_min.rack2 = static_cast<Hilbert::inttype>(-1);\n local_max.rack0 = local_max.rack1 = local_max.rack2 = 0;\n }\n else\n {\n local_min = _data.front();\n local_max = _data.back();\n }\n \n MPI_Op hilbert_max, hilbert_min;\n MPI_Datatype hilbert_type;\n\n MPI_Type_contiguous (3, MPI_UNSIGNED, &hilbert_type);\n MPI_Type_commit (&hilbert_type);\n MPI_Op_create ((MPI_User_function*)__hilbert_max_op, true, &hilbert_max);\n MPI_Op_create ((MPI_User_function*)__hilbert_min_op, true, &hilbert_min);\n\n \/\/ Communicate to determine the global\n \/\/ min and max for all processors.\n MPI_Allreduce(&local_min,\n\t\t&global_min,\n\t\t1,\n\t\thilbert_type,\n\t\thilbert_min,\n\t\tlibMesh::COMM_WORLD);\n\n MPI_Allreduce(&local_max,\n\t\t&global_max,\n\t\t1,\n\t\thilbert_type,\n\t\thilbert_max,\n\t\tlibMesh::COMM_WORLD);\n\n MPI_Type_free (&hilbert_type);\n MPI_Op_free (&hilbert_max);\n MPI_Op_free (&hilbert_min);\n\n \/\/ Bin-Sort based on the global min and max\n Parallel::BinSorter<Hilbert::HilbertIndices> bs(_data);\n bs.binsort(_n_procs, global_max, global_min);\n\n \/\/ Now save the local bin sizes in a vector so\n \/\/ we don't have to keep around the BinSorter.\n for (unsigned int i=0; i<_n_procs; ++i)\n _local_bin_sizes[i] = bs.sizeof_bin(i);\n}\n\n#endif \/\/ #ifdef HAVE_LIBHILBERT\n\n\ntemplate <typename KeyType>\nvoid Sort<KeyType>::communicate_bins()\n{\n#ifdef HAVE_MPI\n \/\/ Create storage for the global bin sizes. This\n \/\/ is the number of keys which will be held in\n \/\/ each bin over all processors.\n std::vector<unsigned int> global_bin_sizes = _local_bin_sizes;\n \n \/\/ Sum to find the total number of entries in each bin.\n Parallel::sum(global_bin_sizes);\n\n \/\/ Create a vector to temporarily hold the results of MPI_Gatherv\n \/\/ calls. The vector dest may be saved away to _my_bin depending on which\n \/\/ processor is being MPI_Gatherv'd.\n std::vector<KeyType> dest;\n\n unsigned int local_offset = 0;\n \n for (unsigned int i=0; i<_n_procs; ++i)\n {\n \/\/ Vector to receive the total bin size for each\n \/\/ processor. Processor i's bin size will be\n \/\/ held in proc_bin_size[i]\n std::vector<unsigned int> proc_bin_size;\n\n \/\/ Find the number of contributions coming from each\n \/\/ processor for this bin. Note: allgather combines\n \/\/ the MPI_Gather and MPI_Bcast operations into one.\n Parallel::allgather(_local_bin_sizes[i], proc_bin_size);\n\n \/\/ Compute the offsets into my_bin for each processor's\n \/\/ portion of the bin. These are basically partial sums\n \/\/ of the proc_bin_size vector.\n std::vector<unsigned int> displacements(_n_procs);\n for (unsigned int j=1; j<_n_procs; ++j)\n\tdisplacements[j] = proc_bin_size[j-1] + displacements[j-1];\n\n \/\/ Resize the destination buffer\n dest.resize (global_bin_sizes[i]);\n\t \n MPI_Gatherv((_data.size() > local_offset) ?\n\t\t &_data[local_offset] :\n\t\t NULL, \/\/ Points to the beginning of the bin to be sent\n\t\t _local_bin_sizes[i], \/\/ How much data is in the bin being sent.\n\t\t Parallel::datatype<KeyType>(), \/\/ The data type we are sorting\n\t\t (dest.empty()) ?\n\t\t NULL :\n\t\t &dest[0], \/\/ Enough storage to hold all bin contributions\n\t\t (int*) &proc_bin_size[0], \/\/ How much is to be received from each processor\n\t (int*) &displacements[0], \/\/ Offsets into the receive buffer\n\t\t Parallel::datatype<KeyType>(), \/\/ The data type we are sorting\n\t\t i, \/\/ The root process (we do this once for each proc)\n\t\t libMesh::COMM_WORLD);\n\n \/\/ Copy the destination buffer if it\n \/\/ corresponds to the bin for this processor\n if (i == _proc_id)\n\t_my_bin = dest;\n\t \n \/\/ Increment the local offset counter\n local_offset += _local_bin_sizes[i];\n } \n#endif \/\/ HAVE_MPI\n}\n\n\n\n#if defined(HAVE_LIBHILBERT) && defined(HAVE_MPI)\n\/\/ Full specialization for HilbertIndices, there is a fair amount of\n\/\/ code duplication here that could potentially be consolidated with the \n\/\/ above method\ntemplate <>\nvoid Sort<Hilbert::HilbertIndices>::communicate_bins()\n{\n \/\/ Create storage for the global bin sizes. This\n \/\/ is the number of keys which will be held in\n \/\/ each bin over all processors.\n std::vector<unsigned int> global_bin_sizes(_n_procs);\n \n assert (_local_bin_sizes.size() == global_bin_sizes.size());\n\n \/\/ Sum to find the total number of entries in each bin.\n \/\/ This is stored in global_bin_sizes. Note, we\n \/\/ explicitly know that we are communicating MPI_UNSIGNED's here.\n MPI_Allreduce(&_local_bin_sizes[0],\n\t\t&global_bin_sizes[0],\n\t\t_n_procs,\n\t\tMPI_UNSIGNED,\n\t\tMPI_SUM,\n\t\tlibMesh::COMM_WORLD);\n\n MPI_Datatype hilbert_type;\n\n MPI_Type_contiguous (3, MPI_UNSIGNED, &hilbert_type);\n MPI_Type_commit (&hilbert_type);\n\n \/\/ Create a vector to temporarily hold the results of MPI_Gatherv\n \/\/ calls. The vector dest may be saved away to _my_bin depending on which\n \/\/ processor is being MPI_Gatherv'd.\n std::vector<Hilbert::HilbertIndices> sendbuf, dest;\n\n unsigned int local_offset = 0;\n \n for (unsigned int i=0; i<_n_procs; ++i)\n {\n \/\/ Vector to receive the total bin size for each\n \/\/ processor. Processor i's bin size will be\n \/\/ held in proc_bin_size[i]\n std::vector<unsigned int> proc_bin_size(_n_procs);\n\n \/\/ Find the number of contributions coming from each\n \/\/ processor for this bin. Note: Allgather combines\n \/\/ the MPI_Gather and MPI_Bcast operations into one.\n \/\/ Note: Here again we know that we are communicating\n \/\/ MPI_UNSIGNED's so there is no need to check the MPI_traits.\n MPI_Allgather(&_local_bin_sizes[i], \/\/ Source: # of entries on this proc in bin i\n\t\t 1, \/\/ Number of items to gather \n\t\t MPI_UNSIGNED, \n\t\t &proc_bin_size[0], \/\/ Destination: Total # of entries in bin i\n\t\t 1,\n\t\t MPI_UNSIGNED,\n\t\t libMesh::COMM_WORLD);\n \n \/\/ Compute the offsets into my_bin for each processor's\n \/\/ portion of the bin. These are basically partial sums\n \/\/ of the proc_bin_size vector.\n std::vector<unsigned int> displacements(_n_procs);\n for (unsigned int j=1; j<_n_procs; ++j)\n\tdisplacements[j] = proc_bin_size[j-1] + displacements[j-1];\n\n \/\/ Resize the destination buffer\n dest.resize (global_bin_sizes[i]);\n \n MPI_Gatherv((_data.size() > local_offset) ?\n\t\t &_data[local_offset] :\n\t\t NULL, \/\/ Points to the beginning of the bin to be sent\n\t\t _local_bin_sizes[i], \/\/ How much data is in the bin being sent.\n\t\t hilbert_type, \/\/ The data type we are sorting\n\t\t (dest.empty()) ?\n\t\t NULL :\n\t\t &dest[0], \/\/ Enough storage to hold all bin contributions\n\t\t (int*) &proc_bin_size[0], \/\/ How much is to be received from each processor\n\t\t (int*) &displacements[0], \/\/ Offsets into the receive buffer\n\t\t hilbert_type, \/\/ The data type we are sorting\n\t\t i, \/\/ The root process (we do this once for each proc)\n\t\t libMesh::COMM_WORLD);\n\n \/\/ Copy the destination buffer if it\n \/\/ corresponds to the bin for this processor\n if (i == _proc_id)\n\t_my_bin = dest;\n\n \/\/ Increment the local offset counter\n local_offset += _local_bin_sizes[i];\n }\n\n MPI_Type_free (&hilbert_type); \n}\n\n#endif \/\/ #if defined(HAVE_LIBHILBERT) && defined(HAVE_MPI)\n\n\n\ntemplate <typename KeyType>\nvoid Sort<KeyType>::sort_local_bin()\n{\n std::sort(_my_bin.begin(), _my_bin.end());\n}\n\n\n\ntemplate <typename KeyType>\nconst std::vector<KeyType>& Sort<KeyType>::bin()\n{\n if (!_bin_is_sorted)\n {\n std::cout << \"Warning! Bin is not yet sorted!\" << std::endl; \n }\n\n return _my_bin;\n}\n\n}\n\n\n\n\/\/ Explicitly instantiate for int, double\ntemplate class Parallel::Sort<int>;\ntemplate class Parallel::Sort<double>;\n#if defined(HAVE_LIBHILBERT) && defined(HAVE_MPI)\ntemplate class Parallel::Sort<Hilbert::HilbertIndices>;\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (C) 2014 Open Source Robotics Foundation\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n*\/\n\n#ifdef _WIN32\n #include <Winsock2.h>\n#else\n #include <arpa\/inet.h>\n #include <netdb.h>\n #include <unistd.h>\n#endif\n\n#include <stdlib.h>\n#include <cstring>\n#include <iostream>\n#include <string>\n#include \"ignition\/transport\/config.hh\"\n#include \"ignition\/transport\/NetUtils.hh\"\n\n#ifdef HAVE_IFADDRS\n# include <ifaddrs.h>\n#endif\n\nusing namespace ignition;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nbool transport::isPrivateIP(const char *_ip)\n{\n bool b = !strncmp(\"192.168\", _ip, 7) || !strncmp(\"10.\", _ip, 3) ||\n !strncmp(\"169.254\", _ip, 7);\n return b;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nint transport::hostnameToIp(char *_hostname, std::string &_ip)\n{\n struct hostent *he;\n struct in_addr **addr_list;\n int i;\n\n if ((he = gethostbyname(_hostname)) == nullptr)\n {\n \/\/ get the host info\n std::cerr << \"Error in gethostbyname when using hostname = \" << hostname;\n return 1;\n }\n\n addr_list = (struct in_addr **) he->h_addr_list;\n\n for (i = 0; addr_list[i] != nullptr; ++i)\n {\n \/\/ Return the first one;\n _ip = std::string(inet_ntoa(*addr_list[i]));\n return 0;\n }\n\n return 1;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nstd::string transport::determineHost()\n{\n char *ip_env;\n \/\/ First, did the user set DZMQ_IP?\n ip_env = std::getenv(\"DZMQ_IP\");\n\n if (ip_env)\n {\n if (strlen(ip_env) != 0)\n return ip_env;\n else\n std::cerr << \"invalid DZMQ_IP (an empty string)\" << std::endl;\n }\n\n \/\/ Second, try the hostname\n char host[1024];\n memset(host, 0, sizeof(host));\n if (gethostname(host, sizeof(host) - 1) != 0)\n std::cerr << \"determineIP: gethostname failed\" << std::endl;\n\n \/\/ We don't want localhost to be our ip\n else if (strlen(host) && strcmp(\"localhost\", host))\n {\n std::string hostIP;\n strcat(host, \".local\");\n if (hostnameToIp(host, hostIP) == 0)\n {\n return std::string(hostIP);\n }\n }\n\n \/\/ Third, fall back on interface search, which will yield an IP address\n#ifdef HAVE_IFADDRS\n struct ifaddrs *ifa = nullptr, *ifp = NULL;\n int rc;\n if ((rc = getifaddrs(&ifp)) < 0)\n {\n std::cerr << \"error in getifaddrs: \" << strerror(rc) << std::endl;\n exit(-1);\n }\n char preferred_ip[200] = {0};\n for (ifa = ifp; ifa; ifa = ifa->ifa_next)\n {\n char ip_[200];\n socklen_t salen;\n if (!ifa->ifa_addr)\n continue; \/\/ evidently this interface has no ip address\n if (ifa->ifa_addr->sa_family == AF_INET)\n salen = sizeof(struct sockaddr_in);\n else if (ifa->ifa_addr->sa_family == AF_INET6)\n salen = sizeof(struct sockaddr_in6);\n else\n continue;\n if (getnameinfo(ifa->ifa_addr, salen, ip_, sizeof(ip_), nullptr, 0,\n NI_NUMERICHOST) < 0)\n {\n std::cout << \"getnameinfo couldn't get the ip of interface \" <<\n ifa->ifa_name << std::endl;\n continue;\n }\n \/\/ prefer non-private IPs over private IPs\n if (!strcmp(\"127.0.0.1\", ip_) || strchr(ip_, ':'))\n continue; \/\/ ignore loopback unless we have no other choice\n if (ifa->ifa_addr->sa_family == AF_INET6 && !preferred_ip[0])\n strcpy(preferred_ip, ip_);\n else if (isPrivateIP(ip_) && !preferred_ip[0])\n strcpy(preferred_ip, ip_);\n else if (!isPrivateIP(ip_) &&\n (isPrivateIP(preferred_ip) || !preferred_ip[0]))\n strcpy(preferred_ip, ip_);\n }\n freeifaddrs(ifp);\n if (!preferred_ip[0])\n {\n std::cerr <<\n \"Couldn't find a preferred IP via the getifaddrs() call; \"\n \"I'm assuming that your IP \"\n \"address is 127.0.0.1. This should work for local processes, \"\n \"but will almost certainly not work if you have remote processes.\"\n \"Report to the disc-zmq development team to seek a fix.\" << std::endl;\n return std::string(\"127.0.0.1\");\n }\n return std::string(preferred_ip);\n#else\n \/\/ @todo Fix IP determination in the case where getifaddrs() isn't\n \/\/ available.\n std::cerr <<\n \"You don't have the getifaddrs() call; I'm assuming that your IP \"\n \"address is 127.0.0.1. This should work for local processes, \"\n \"but will almost certainly not work if you have remote processes.\"\n \"Report to the disc-zmq development team to seek a fix.\" << std::endl;\n return std::string(\"127.0.0.1\");\n#endif\n}\n<commit_msg>Fix variable name<commit_after>\/*\n * Copyright (C) 2014 Open Source Robotics Foundation\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n*\/\n\n#ifdef _WIN32\n #include <Winsock2.h>\n#else\n #include <arpa\/inet.h>\n #include <netdb.h>\n #include <unistd.h>\n#endif\n\n#include <stdlib.h>\n#include <cstring>\n#include <iostream>\n#include <string>\n#include \"ignition\/transport\/config.hh\"\n#include \"ignition\/transport\/NetUtils.hh\"\n\n#ifdef HAVE_IFADDRS\n# include <ifaddrs.h>\n#endif\n\nusing namespace ignition;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nbool transport::isPrivateIP(const char *_ip)\n{\n bool b = !strncmp(\"192.168\", _ip, 7) || !strncmp(\"10.\", _ip, 3) ||\n !strncmp(\"169.254\", _ip, 7);\n return b;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nint transport::hostnameToIp(char *_hostname, std::string &_ip)\n{\n struct hostent *he;\n struct in_addr **addr_list;\n int i;\n\n if ((he = gethostbyname(_hostname)) == nullptr)\n {\n \/\/ get the host info\n std::cerr << \"Error in gethostbyname when using hostname = \" << _hostname;\n return 1;\n }\n\n addr_list = (struct in_addr **) he->h_addr_list;\n\n for (i = 0; addr_list[i] != nullptr; ++i)\n {\n \/\/ Return the first one;\n _ip = std::string(inet_ntoa(*addr_list[i]));\n return 0;\n }\n\n return 1;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nstd::string transport::determineHost()\n{\n char *ip_env;\n \/\/ First, did the user set DZMQ_IP?\n ip_env = std::getenv(\"DZMQ_IP\");\n\n if (ip_env)\n {\n if (strlen(ip_env) != 0)\n return ip_env;\n else\n std::cerr << \"invalid DZMQ_IP (an empty string)\" << std::endl;\n }\n\n \/\/ Second, try the hostname\n char host[1024];\n memset(host, 0, sizeof(host));\n if (gethostname(host, sizeof(host) - 1) != 0)\n std::cerr << \"determineIP: gethostname failed\" << std::endl;\n\n \/\/ We don't want localhost to be our ip\n else if (strlen(host) && strcmp(\"localhost\", host))\n {\n std::string hostIP;\n strcat(host, \".local\");\n if (hostnameToIp(host, hostIP) == 0)\n {\n return std::string(hostIP);\n }\n }\n\n \/\/ Third, fall back on interface search, which will yield an IP address\n#ifdef HAVE_IFADDRS\n struct ifaddrs *ifa = nullptr, *ifp = NULL;\n int rc;\n if ((rc = getifaddrs(&ifp)) < 0)\n {\n std::cerr << \"error in getifaddrs: \" << strerror(rc) << std::endl;\n exit(-1);\n }\n char preferred_ip[200] = {0};\n for (ifa = ifp; ifa; ifa = ifa->ifa_next)\n {\n char ip_[200];\n socklen_t salen;\n if (!ifa->ifa_addr)\n continue; \/\/ evidently this interface has no ip address\n if (ifa->ifa_addr->sa_family == AF_INET)\n salen = sizeof(struct sockaddr_in);\n else if (ifa->ifa_addr->sa_family == AF_INET6)\n salen = sizeof(struct sockaddr_in6);\n else\n continue;\n if (getnameinfo(ifa->ifa_addr, salen, ip_, sizeof(ip_), nullptr, 0,\n NI_NUMERICHOST) < 0)\n {\n std::cout << \"getnameinfo couldn't get the ip of interface \" <<\n ifa->ifa_name << std::endl;\n continue;\n }\n \/\/ prefer non-private IPs over private IPs\n if (!strcmp(\"127.0.0.1\", ip_) || strchr(ip_, ':'))\n continue; \/\/ ignore loopback unless we have no other choice\n if (ifa->ifa_addr->sa_family == AF_INET6 && !preferred_ip[0])\n strcpy(preferred_ip, ip_);\n else if (isPrivateIP(ip_) && !preferred_ip[0])\n strcpy(preferred_ip, ip_);\n else if (!isPrivateIP(ip_) &&\n (isPrivateIP(preferred_ip) || !preferred_ip[0]))\n strcpy(preferred_ip, ip_);\n }\n freeifaddrs(ifp);\n if (!preferred_ip[0])\n {\n std::cerr <<\n \"Couldn't find a preferred IP via the getifaddrs() call; \"\n \"I'm assuming that your IP \"\n \"address is 127.0.0.1. This should work for local processes, \"\n \"but will almost certainly not work if you have remote processes.\"\n \"Report to the disc-zmq development team to seek a fix.\" << std::endl;\n return std::string(\"127.0.0.1\");\n }\n return std::string(preferred_ip);\n#else\n \/\/ @todo Fix IP determination in the case where getifaddrs() isn't\n \/\/ available.\n std::cerr <<\n \"You don't have the getifaddrs() call; I'm assuming that your IP \"\n \"address is 127.0.0.1. This should work for local processes, \"\n \"but will almost certainly not work if you have remote processes.\"\n \"Report to the disc-zmq development team to seek a fix.\" << std::endl;\n return std::string(\"127.0.0.1\");\n#endif\n}\n<|endoftext|>"} {"text":"<commit_before>\/*****************************************************************************\n\n Licensed to Accellera Systems Initiative Inc. (Accellera) under one or\n more contributor license agreements. See the NOTICE file distributed\n with this work for additional information regarding copyright ownership.\n Accellera licenses this file to you under the Apache License, Version 2.0\n (the \"License\"); you may not use this file except in compliance with the\n License. You may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n implied. See the License for the specific language governing\n permissions and limitations under the License.\n\n *****************************************************************************\/\n\n#ifndef __SYSTEMC_EXT_TLM_CORE_1_REQ_RSP_PORTS_EVENT_FINDER_HH__\n#define __SYSTEMC_EXT_TLM_CORE_1_REQ_RSP_PORTS_EVENT_FINDER_HH__\n\n#include <sstream>\n\n#include \"..\/interfaces\/tag.hh\"\n\nnamespace tlm\n{\n\ntemplate <class IF, class T>\nclass tlm_event_finder_t : public sc_core::sc_event_finder\n{\n public:\n tlm_event_finder_t(const sc_core::sc_port_base &port_,\n const sc_core::sc_event &(IF::*event_method_)(\n tlm_tag<T> *) const) :\n sc_core::sc_event_finder(port_), m_event_method(event_method_)\n {}\n\n virtual ~tlm_event_finder_t() {}\n\n virtual const sc_core::sc_event &\n find_event(sc_core::sc_interface *if_p=nullptr) const;\n\n private:\n const sc_core::sc_event &(IF::*m_event_method)(tlm_tag<T> *) const;\n\n private:\n \/\/ disabled\n tlm_event_finder_t();\n tlm_event_finder_t(const tlm_event_finder_t<IF, T> &);\n tlm_event_finder_t<IF, T> &operator = (const tlm_event_finder_t<IF, T> &);\n};\n\ntemplate <class IF, class T>\ninline const sc_core::sc_event &\ntlm_event_finder_t<IF, T>::find_event(sc_core::sc_interface *if_p) const\n{\n const IF *iface = if_p ? dynamic_cast<const IF *>(if_p) :\n dynamic_cast<const IF *>(port()->_gem5Interface(0));\n if (iface == nullptr) {\n std::ostringstream out;\n out << \"port is not bound: port '\" << port()->name() <<\n \"' (\" << port()->kind() << \")\";\n SC_REPORT_ERROR(sc_core::SC_ID_FIND_EVENT_, out.str().c_str());\n static sc_core::sc_event none;\n return none;\n }\n return (const_cast<IF *>(iface)->*m_event_method)(nullptr);\n}\n\n} \/\/ namespace tlm\n\n#endif \/* __SYSTEMC_EXT_TLM_CORE_1_REQ_RSP_PORTS_EVENT_FINDER_HH__ *\/\n<commit_msg>systemc: Fix up some lingering Accellera specific code in TLM v1.<commit_after>\/*****************************************************************************\n\n Licensed to Accellera Systems Initiative Inc. (Accellera) under one or\n more contributor license agreements. See the NOTICE file distributed\n with this work for additional information regarding copyright ownership.\n Accellera licenses this file to you under the Apache License, Version 2.0\n (the \"License\"); you may not use this file except in compliance with the\n License. You may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n implied. See the License for the specific language governing\n permissions and limitations under the License.\n\n *****************************************************************************\/\n\n#ifndef __SYSTEMC_EXT_TLM_CORE_1_REQ_RSP_PORTS_EVENT_FINDER_HH__\n#define __SYSTEMC_EXT_TLM_CORE_1_REQ_RSP_PORTS_EVENT_FINDER_HH__\n\n#include <sstream>\n\n#include \"..\/interfaces\/tag.hh\"\n\nnamespace tlm\n{\n\ntemplate <class IF, class T>\nclass tlm_event_finder_t : public sc_core::sc_event_finder_t<IF>\n{\n public:\n tlm_event_finder_t(const sc_core::sc_port_base &port_,\n const sc_core::sc_event &(IF::*event_method_)(\n tlm_tag<T> *) const) :\n sc_core::sc_event_finder_t<IF>(port_), m_event_method(event_method_)\n {}\n\n virtual ~tlm_event_finder_t() {}\n\n virtual const sc_core::sc_event &\n find_event(sc_core::sc_interface *if_p=nullptr) const;\n\n private:\n const sc_core::sc_event &(IF::*m_event_method)(tlm_tag<T> *) const;\n\n private:\n \/\/ disabled\n tlm_event_finder_t();\n tlm_event_finder_t(const tlm_event_finder_t<IF, T> &);\n tlm_event_finder_t<IF, T> &operator = (const tlm_event_finder_t<IF, T> &);\n};\n\ntemplate <class IF, class T>\ninline const sc_core::sc_event &\ntlm_event_finder_t<IF, T>::find_event(sc_core::sc_interface *if_p) const\n{\n const IF *iface = if_p ? dynamic_cast<const IF *>(if_p) :\n dynamic_cast<const IF *>(this->port()->_gem5Interface(0));\n if (iface == nullptr) {\n std::ostringstream out;\n out << \"port is not bound: port '\" << this->port()->name() <<\n \"' (\" << this->port()->kind() << \")\";\n SC_REPORT_ERROR(sc_core::SC_ID_FIND_EVENT_, out.str().c_str());\n static sc_core::sc_event none;\n return none;\n }\n return (const_cast<IF *>(iface)->*m_event_method)(nullptr);\n}\n\n} \/\/ namespace tlm\n\n#endif \/* __SYSTEMC_EXT_TLM_CORE_1_REQ_RSP_PORTS_EVENT_FINDER_HH__ *\/\n<|endoftext|>"} {"text":"<commit_before>#include \"qnetstring.h\"\n\n\/**********************************************************************************************************************\/\n\/* Public API *\/\n\/**********************************************************************************************************************\/\n\nQNetString::QNetString(QObject *parent) :\n QObject(parent)\n{\n \/\/ Connect to our internal signals\n connect(this, SIGNAL(tryParse()), this, SLOT(onTryParse()));\n} \/\/ end QNetString\n\nQByteArray QNetString::encode(QByteArray data)\n{\n return QString(\"%1:%2,\").arg(data.length()).arg(data.constData()).toUtf8();\n} \/\/ end encode\n\n\/**********************************************************************************************************************\/\n\/* Public Slots *\/\n\/**********************************************************************************************************************\/\n\nvoid QNetString::addData(QByteArray data)\n{\n this->buffer.append(data);\n emit tryParse();\n} \/\/ end addData\n\n\/**********************************************************************************************************************\/\n\/* Private Slots *\/\n\/**********************************************************************************************************************\/\n\nvoid QNetString::onTryParse()\n{\n int netstringLength = -1;\n\n while(true)\n {\n \/\/ If the buffer's empty or we don't have a colon, we can't parse.\n if(this->buffer.length() == 0 || !buffer.contains(':'))\n {\n \/\/ We don't have enough data to read\n return;\n } \/\/ end if\n\n int idx = buffer.indexOf(':');\n\n \/\/ Determine our length\n netstringLength = buffer.left(idx).toInt();\n\n if(buffer.length() < idx + netstringLength + 2)\n {\n return;\n } \/\/ end if\n\n if(buffer[netstringLength + idx + 1] != ',')\n {\n qCritical() << \"Invalid netstring: \" << QString(buffer);\n } \/\/ end if\n\n \/\/ Pull out our data\n QByteArray data = buffer.mid(idx + 1, netstringLength);\n\n \/\/qDebug() << \"Data: \" << data;\n\n \/\/ Trim our buffer, and reset our lengh\n buffer = buffer.mid(idx + netstringLength + 2);\n\n \/\/qDebug() << \"Buffer: \" << buffer;\n\n \/\/ Emit the data\n emit dataReady(data);\n } \/\/ end while\n} \/\/ end onTryParse\n<commit_msg>fixed a bug where we would not properly encode a netstring the moment we left the range of ASCII values. Now, we do it all with QByteArray, which should be faster, and much much much more robust. This solves an issue that prevented AES encrypted data from being sent.<commit_after>#include \"qnetstring.h\"\n\n\/**********************************************************************************************************************\/\n\/* Public API *\/\n\/**********************************************************************************************************************\/\n\nQNetString::QNetString(QObject *parent) :\n QObject(parent)\n{\n \/\/ Connect to our internal signals\n connect(this, SIGNAL(tryParse()), this, SLOT(onTryParse()));\n} \/\/ end QNetString\n\nQByteArray QNetString::encode(QByteArray data)\n{\n\treturn QByteArray::number(data.length(), 10).append(':').append(data).append(',');\n} \/\/ end encode\n\n\/**********************************************************************************************************************\/\n\/* Public Slots *\/\n\/**********************************************************************************************************************\/\n\nvoid QNetString::addData(QByteArray data)\n{\n this->buffer.append(data);\n emit tryParse();\n} \/\/ end addData\n\n\/**********************************************************************************************************************\/\n\/* Private Slots *\/\n\/**********************************************************************************************************************\/\n\nvoid QNetString::onTryParse()\n{\n int netstringLength = -1;\n\n while(true)\n {\n \/\/ If the buffer's empty or we don't have a colon, we can't parse.\n if(this->buffer.length() == 0 || !buffer.contains(':'))\n {\n \/\/ We don't have enough data to read\n return;\n } \/\/ end if\n\n int idx = buffer.indexOf(':');\n\n \/\/ Determine our length\n netstringLength = buffer.left(idx).toInt();\n\n if(buffer.length() < idx + netstringLength + 2)\n {\n return;\n } \/\/ end if\n\n if(buffer[netstringLength + idx + 1] != ',')\n {\n qCritical() << \"Invalid netstring: \" << QString(buffer);\n } \/\/ end if\n\n \/\/ Pull out our data\n QByteArray data = buffer.mid(idx + 1, netstringLength);\n\n \/\/qDebug() << \"Data: \" << data;\n\n \/\/ Trim our buffer, and reset our lengh\n buffer = buffer.mid(idx + netstringLength + 2);\n\n \/\/qDebug() << \"Buffer: \" << buffer;\n\n \/\/ Emit the data\n emit dataReady(data);\n } \/\/ end while\n} \/\/ end onTryParse\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2020 Google LLC\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n\/\/ This is a test file for our protobuf specifications of bmv2 json.\n\/\/ It reads an input bmv2 json string (usually the output of p4c) via stdin,\n\/\/ it parses the string using protobuf, and then dumps the parsed protobuf\n\/\/ objects using protobuf text format and json.\n\/\/ The dumps are written to output files whose paths are provided as command\n\/\/ line arguments.\n\n\/\/ The implementation of our PDPI interface.\n\n#include \"p4_symbolic\/ir\/pdpi_driver.h\"\n\n#include <memory>\n\n#include \"p4_pdpi\/util.h\"\n\nnamespace p4_symbolic {\nnamespace ir {\n\n\/\/ Parse into standard p4 protobuf and then into PDPI.\n\/\/ If either of these steps fail, their failure status is returned.\npdpi::StatusOr<pdpi::ir::IrP4Info> ParsePdpi(std::string p4info_path) {\n \/\/ Verify link and compile versions are the same.\n GOOGLE_PROTOBUF_VERIFY_VERSION;\n\n \/\/ Parse the p4info file into the standard p4 protobuf.\n p4::config::v1::P4Info p4info;\n RETURN_IF_ERROR(pdpi::ReadProtoFromFile(p4info_path, &p4info));\n\n \/\/ Transform the p4 protobuf to a pdpi protobuf using a pdpi::P4InfoManager.\n pdpi::StatusOr<std::unique_ptr<pdpi::P4InfoManager>> status_or_info =\n pdpi::P4InfoManager::Create(p4info);\n RETURN_IF_ERROR(status_or_info.status());\n\n return pdpi::StatusOr<pdpi::ir::IrP4Info>(\n status_or_info.value()->GetIrP4Info());\n}\n\n} \/\/ namespace ir\n} \/\/ namespace p4_symbolic\n<commit_msg>remove google protobuf verify version from pdpi_driver<commit_after>\/\/ Copyright 2020 Google LLC\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n\/\/ This is a test file for our protobuf specifications of bmv2 json.\n\/\/ It reads an input bmv2 json string (usually the output of p4c) via stdin,\n\/\/ it parses the string using protobuf, and then dumps the parsed protobuf\n\/\/ objects using protobuf text format and json.\n\/\/ The dumps are written to output files whose paths are provided as command\n\/\/ line arguments.\n\n\/\/ The implementation of our PDPI interface.\n\n#include \"p4_symbolic\/ir\/pdpi_driver.h\"\n\n#include <memory>\n\n#include \"p4_pdpi\/util.h\"\n\nnamespace p4_symbolic {\nnamespace ir {\n\n\/\/ Parse into standard p4 protobuf and then into PDPI.\n\/\/ If either of these steps fail, their failure status is returned.\npdpi::StatusOr<pdpi::ir::IrP4Info> ParsePdpi(std::string p4info_path) {\n \/\/ Parse the p4info file into the standard p4 protobuf.\n p4::config::v1::P4Info p4info;\n RETURN_IF_ERROR(pdpi::ReadProtoFromFile(p4info_path, &p4info));\n\n \/\/ Transform the p4 protobuf to a pdpi protobuf using a pdpi::P4InfoManager.\n pdpi::StatusOr<std::unique_ptr<pdpi::P4InfoManager>> status_or_info =\n pdpi::P4InfoManager::Create(p4info);\n RETURN_IF_ERROR(status_or_info.status());\n\n return pdpi::StatusOr<pdpi::ir::IrP4Info>(\n status_or_info.value()->GetIrP4Info());\n}\n\n} \/\/ namespace ir\n} \/\/ namespace p4_symbolic\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2014, German Neuroinformatics Node (G-Node)\n\/\/\n\/\/ All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted under the terms of the BSD License. See\n\/\/ LICENSE file in the root of the Project.\n\n#include <boost\/python.hpp>\n#include <boost\/optional.hpp>\n\n#include <nix.hpp>\n#include <accessors.hpp>\n#include <transmorgify.hpp>\n\n#include <PyEntity.hpp>\n#include <PyValue.hpp>\n\nusing namespace nix;\nusing namespace boost::python;\n\nnamespace nixpy {\n\nvoid PyValue::do_export() {\n\n class_<Value>(\"Value\")\n .def_readwrite(\"reference\", &Value::reference)\n .def_readwrite(\"filename\", &Value::filename)\n .def_readwrite(\"encoder\", &Value::encoder)\n .def_readwrite(\"checksum\", &Value::checksum)\n ;\n\n to_python_converter<std::vector<Value>, vector_transmogrify<Value>>();\n vector_transmogrify<Value>::register_from_python();\n to_python_converter<boost::optional<Value>, option_transmogrify<Value>>();\n\n}\n\n}\n<commit_msg>PyValue: constructors and setter and setter<commit_after>\/\/ Copyright (c) 2014, German Neuroinformatics Node (G-Node)\n\/\/\n\/\/ All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted under the terms of the BSD License. See\n\/\/ LICENSE file in the root of the Project.\n\n#include <boost\/python.hpp>\n#include <boost\/optional.hpp>\n\n#include <nix.hpp>\n#include <accessors.hpp>\n#include <transmorgify.hpp>\n\n#include <PyEntity.hpp>\n#include <PyValue.hpp>\n\nusing namespace nix;\nusing namespace boost::python;\n\nnamespace nixpy {\n\n\nstd::shared_ptr<Value> create(PyObject* value) {\n\n std::shared_ptr<Value> created = std::make_shared<Value>(new Value());\n\n if (PyBool_Check(value)) {\n bool conv = extract<bool>(value);\n created->set(conv);\n } else if (PyInt_Check(value)) {\n int64_t conv = extract<int64_t>(value);\n created->set(conv);\n } else if (PyFloat_Check(value)) {\n double conv = extract<double>(value);\n created->set(conv);\n } else if (PyString_Check(value)) {\n std::string conv = extract<std::string>(value);\n created->set(conv);\n } else {\n throw std::runtime_error(\"Wrong type\");\n }\n\n return created;\n}\n\nvoid set(Value& ref, PyObject* value) {\n\n if (PyBool_Check(value)) {\n bool conv = extract<bool>(value);\n ref.set(conv);\n } else if (PyInt_Check(value)) {\n int64_t conv = extract<int64_t>(value);\n ref.set(conv);\n } else if (PyFloat_Check(value)) {\n double conv = extract<double>(value);\n ref.set(conv);\n } else if (PyString_Check(value)) {\n std::string conv = extract<std::string>(value);\n ref.set(conv);\n } else {\n throw std::runtime_error(\"Wrong type\");\n }\n\n}\n\nPyObject* get(const Value& ref) {\n\n DataType type = ref.type();\n switch(type) {\n case DataType::Bool:\n return incref(object(ref.get<bool>()).ptr());\n case DataType::Float:\n case DataType::Double:\n return incref(object(ref.get<double>()).ptr());\n case DataType::Char:\n case DataType::Int8:\n case DataType::Int16:\n case DataType::Int32:\n case DataType::Int64:\n return incref(object(ref.get<int64_t>()).ptr());\n case DataType::UInt8:\n case DataType::UInt16:\n case DataType::UInt32:\n case DataType::UInt64:\n return incref(object(ref.get<u_int64_t>()).ptr());\n case DataType::String:\n return incref(object(ref.get<std::string>()).ptr());\n case DataType::Date:\n case DataType::DateTime:\n \/\/ TODO support for date\n case DataType::Nothing:\n default:\n Py_RETURN_NONE;\n }\n}\n\nvoid PyValue::do_export() {\n\n class_<Value>(\"Value\")\n .def(\"__init__\", make_constructor(create))\n .def_readwrite(\"reference\", &Value::reference)\n .def_readwrite(\"filename\", &Value::filename)\n .def_readwrite(\"encoder\", &Value::encoder)\n .def_readwrite(\"checksum\", &Value::checksum)\n .def(\"set\", set)\n .def(\"get\", get)\n \/\/ Other\n .def(\"__str__\", &toStr<Value>)\n .def(\"__repr__\", &toStr<Value>)\n ;\n\n to_python_converter<std::vector<Value>, vector_transmogrify<Value>>();\n vector_transmogrify<Value>::register_from_python();\n to_python_converter<boost::optional<Value>, option_transmogrify<Value>>();\n\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before>#ifndef SAPLIST_HPP\n#define SAPLIST_HPP 1\n\n#include <functional>\n#include <map>\n#include <typeinfo>\n#include <climits>\n#include \"CollisionManager.hpp\"\n\nclass Collisionable {\nprotected: int x, y, w, h;\npublic: Collisionable(int x=0, int y=0, int w=0, int h=0) :\n x(x), y(y), w(w), h(h) {}\n};\n\nclass SAPList : public CollisionManager<Collisionable> {\n\n class EndPoint;\n\n class AABB {\n public:\n \/** min\/max\n * - first is x axis\n * - second is y axis *\/\n EndPoint * min[2];\n EndPoint * max[2];\n\n size_t typeId; \/* Need to use std::type_info::hash_code() *\/\n void * owner;\n };\n\n \/**\n * TODO:\n * - Optimize merging isMin boolean into another member\n * (as a flag)\n * - Using doubly-linked list could waste memory but is easier to implement\n * than arrays.\n * - Implement pair manager\n *\/\n class EndPoint {\n public:\n AABB * owner;\n int value;\n bool isMin;\n\n EndPoint * prev;\n EndPoint * next;\n\n EndPoint (AABB* o,int v,bool m,EndPoint* p,EndPoint* n) : \n owner(o), value(v), isMin(m), prev(p), next(n) {}\n\n \/** When and EndPoint is destroyed, it updates prev and next *\/\n ~EndPoint () {\n if (this->prev != NULL) {\n this->prev->next = this->next;\n }\n if (this->next != NULL)\n this->next->prev = this->prev;\n }\n };\n\n\n \/**\n * Action manager stores actions to perform on collision or separation\n * of two objects depending on their type\n * It also stores default actions to execute if no specific action is\n * defined for two types.\n *\/\n class ActionManager {\n public:\n std::map < std::pair < size_t,size_t >,\n std::pair < std::function < void (void *, void *) >,\n std::function < void (void *, void *) > > > \n actions;\n \n std::function < void (void *, void *) >\n onCollision(size_t t1, size_t t2) {\n return this\n ->actions[std::pair<size_t, size_t>(t1,t2)].first;\n }\n \n std::function < void (void *, void *) >\n onSeparation(size_t t1, size_t t2) {\n return this\n ->actions[std::pair<size_t, size_t>(t1,t2)].second;\n }\n };\n\n\nprivate:\n\n EndPoint * xAxis;\n EndPoint * yAxis;\n ActionManager actions;\n\n void swap(EndPoint * p1, EndPoint * p2) {\n p2->next->prev = p1;\n p1->next = p2->next;\n p1->prev->next = p2;\n p1->prev = p2;\n p2->next = p1;\n }\n\n \/* check on one axis *\/\n inline bool partialCollisionCheck(const AABB & b1,\n const AABB & b2,\n int dim) {\n return (b1.max[dim] <= b2.max[dim] && b1.max[dim] >= b2.min[dim])\n || (b1.min[dim] >= b2.min[dim] && b1.max[dim] <= b2.max[dim]);\n }\n\n bool collisionCheck(const AABB & b1, const AABB & b2) {\n return partialCollisionCheck (b1, b2, 0)\n && partialCollisionCheck (b1, b2, 1);\n }\n\n void updateEndPoint(EndPoint * pt) {\n \n auto aux =\n [&pt, this]\n (std::function<EndPoint*(EndPoint*)>succ,\n std::function<bool(int,int)>loop_cond,\n std::function<bool(EndPoint*,EndPoint*)>mustAdd,\n std::function<bool(EndPoint*,EndPoint*)>mustRm) {\n \n EndPoint * tmp = succ(pt);\n \n while (loop_cond(tmp->value, pt->value)) {\n this->swap(tmp, pt);\n if (mustAdd(pt, tmp)) {\n if (this->collisionCheck(*(pt->owner), *(tmp->owner))) {\n this->actions.onCollision\n (pt->owner->typeId, tmp->owner->typeId)\n (pt->owner->owner, tmp->owner->owner);\n }\n } else if (mustRm(pt, tmp)) {\n this->actions.onSeparation\n (pt->owner->typeId,tmp->owner->typeId)\n (pt->owner->owner, tmp->owner->owner);\n }\n }\n };\n\n \/** TODO: use aux to update on x and y axis *\/\n\n }\n \npublic:\n\n SAPList () {\n \/* not sure about the true\/false values *\/\n xAxis = new EndPoint(NULL, INT_MIN, true, NULL, NULL);\n xAxis->next = new EndPoint(NULL, INT_MAX, false, xAxis, NULL);\n yAxis = new EndPoint(NULL, INT_MIN, true, NULL, NULL);\n yAxis->next = new EndPoint(NULL, INT_MAX, false, yAxis, NULL);\n }\n\n ~SAPList () {\n\n while (xAxis->next != NULL) {\n delete xAxis->next;\n } delete xAxis;\n\n while (yAxis->next != NULL) {\n delete yAxis->next;\n } delete yAxis;\n }\n\n void addObject(const Collisionable &) {}\n void updateObject(const Collisionable &) {}\n void removeObject(const Collisionable &) {}\n};\n\n#endif\n<commit_msg>Doc++, used public field in Collisionable objects, new functions: - AABB constructor - mk_AABB<commit_after>#ifndef SAPLIST_HPP\n#define SAPLIST_HPP 1\n\n#include <functional>\n#include <map>\n#include <typeinfo>\n#include <climits>\n#include \"CollisionManager.hpp\"\n\nclass Collisionable {\n \/* FIXME: use getters instead of public fields *\/\npublic:\n int x, y, w, h;\n Collisionable(int x=0, int y=0, int w=0, int h=0) :\n x(x), y(y), w(w), h(h) {}\n};\n\nclass SAPList : public CollisionManager<Collisionable> {\n\n class EndPoint;\n\n class AABB {\n public:\n \/** min\/max\n * - first is x axis\n * - second is y axis *\/\n EndPoint * min[2];\n EndPoint * max[2];\n\n size_t typeId; \/* Need to use std::type_info::hash_code() *\/\n void * owner;\n\n AABB (int * minX, int minY, int maxX, int maxY, size_t t, void * o) :\n typeId(t), owner(o) {\n min[0] = minX;\n min[1] = minY;\n max[0] = maxX;\n max[1] = maxY;\n }\n\n };\n\n \/**\n * TODO:\n * - Optimize merging isMin boolean into another member\n * (as a flag)\n * - Using doubly-linked list could waste memory but is easier to implement\n * than arrays.\n * - Implement pair manager\n *\/\n class EndPoint {\n public:\n AABB * owner;\n int value;\n bool isMin;\n\n EndPoint * prev;\n EndPoint * next;\n\n EndPoint (AABB* o,int v,bool m,EndPoint* p,EndPoint* n) : \n owner(o), value(v), isMin(m), prev(p), next(n) {}\n\n \/** When and EndPoint is destroyed, it updates prev and next *\/\n ~EndPoint () {\n if (this->prev != NULL) {\n this->prev->next = this->next;\n }\n if (this->next != NULL)\n this->next->prev = this->prev;\n }\n };\n\n\n \/**\n * Action manager stores actions to perform on collision or separation\n * of two objects depending on their type\n * It also stores default actions to execute if no specific action is\n * defined for two types.\n *\/\n class ActionManager {\n public:\n \/**\n * action table stores 2 actions per types couple:\n * - first is onCollision\n * - second is onSeparation\n *\/\n std::map < std::pair < size_t,size_t >,\n std::pair < std::function < void (void *, void *) >,\n std::function < void (void *, void *) > > > \n actions;\n \n \/**\n * @param t1 type id of first object\n * @param t2 type id of second object\n * @return function to call on t1\/t2 collision\n *\/\n std::function < void (void *, void *) >\n onCollision(size_t t1, size_t t2) {\n return this\n ->actions[std::pair<size_t, size_t>(t1,t2)].first;\n }\n\n \/**\n * @param t1 type id of first object\n * @param t2 type id of second object\n * @return function to call on t1\/t2 separation\n *\/ \n std::function < void (void *, void *) >\n onSeparation(size_t t1, size_t t2) {\n return this\n ->actions[std::pair<size_t, size_t>(t1,t2)].second;\n }\n };\n\n\nprivate:\n\n EndPoint * xAxis;\n EndPoint * yAxis;\n ActionManager actions;\n\n \/** Swap two EndPoint * *\/\n void swap(EndPoint * p1, EndPoint * p2) {\n p2->next->prev = p1;\n p1->next = p2->next;\n p1->prev->next = p2;\n p1->prev = p2;\n p2->next = p1;\n }\n\n \/** A collision between two AABB on one axis *\/\n inline bool partialCollisionCheck(const AABB & b1,\n const AABB & b2,\n int dim) {\n return (b1.max[dim] <= b2.max[dim] && b1.max[dim] >= b2.min[dim])\n || (b1.min[dim] >= b2.min[dim] && b1.max[dim] <= b2.max[dim]);\n }\n\n \/**\n * Check if two AABB collide using 2 axises\n * @see partialCollisionCheck\n *\/\n bool collisionCheck(const AABB & b1, const AABB & b2) {\n return partialCollisionCheck (b1, b2, 0)\n && partialCollisionCheck (b1, b2, 1);\n }\n\n\n \/** Create the AABB corresponding to a collisionable object\n * @param c the object used to create the corresponding AABB\n * @return a pointer to freshly heap-allocated AABB \n *\/\n AABB * mk_AABB(const Collisionable & c) {\n EndPoint * miX, * miY, * maX, * maY;\n\n \/* TODO: create EndPoints *\/\n\n return new AABB(miX, miY, maX, maY, typeid(c).hash_code, (void *) c);\n }\n\n\n \/** Update EndPoint place and call the appropriate function in case \n * of collision\/separation\n * @param pt the EndPoint to update\n *\/\n void updateEndPoint(EndPoint * pt) {\n \n auto aux =\n [&pt, this]\n (std::function<EndPoint*(EndPoint*)>succ,\n std::function<bool(int,int)>loop_cond,\n std::function<bool(EndPoint*,EndPoint*)>mustAdd,\n std::function<bool(EndPoint*,EndPoint*)>mustRm) {\n \n EndPoint * tmp = succ(pt);\n \n while (loop_cond(tmp->value, pt->value)) {\n this->swap(tmp, pt);\n if (mustAdd(pt, tmp)) {\n if (this->collisionCheck(*(pt->owner), *(tmp->owner))) {\n this->actions.onCollision\n (pt->owner->typeId, tmp->owner->typeId)\n (pt->owner->owner, tmp->owner->owner);\n }\n } else if (mustRm(pt, tmp)) {\n this->actions.onSeparation\n (pt->owner->typeId,tmp->owner->typeId)\n (pt->owner->owner, tmp->owner->owner);\n }\n }\n };\n\n \/** TODO: use aux to update on x and y axis *\/\n\n }\n \npublic:\n\n SAPList () {\n \/* not sure about the true\/false values *\/\n xAxis = new EndPoint(NULL, INT_MIN, true, NULL, NULL);\n xAxis->next = new EndPoint(NULL, INT_MAX, false, xAxis, NULL);\n yAxis = new EndPoint(NULL, INT_MIN, true, NULL, NULL);\n yAxis->next = new EndPoint(NULL, INT_MAX, false, yAxis, NULL);\n }\n\n ~SAPList () {\n\n while (xAxis->next != NULL) {\n delete xAxis->next;\n } delete xAxis;\n\n while (yAxis->next != NULL) {\n delete yAxis->next;\n } delete yAxis;\n }\n\n void addObject(const Collisionable &) {}\n void updateObject(const Collisionable &) {}\n void removeObject(const Collisionable &) {}\n};\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>#include \"Testing.h\"\n\n#ifdef DEBUG\n#include <cstdlib>\n#include <fstream>\n#include <iostream>\n#include <cmath>\n#include <thread>\n#include <iomanip>\n\n#include \"Game\/Board.h\"\n#include \"Moves\/Complete_Move.h\"\n#include \"Players\/Genetic_AI.h\"\n#include \"Game\/Clock.h\"\n\n#include \"Utility.h\"\n\n#include \"Exceptions\/Illegal_Move_Exception.h\"\n\n\/\/ Declaration to silence warnings\nbool files_are_identical(const std::string& file_name1, const std::string& file_name2);\n\nbool files_are_identical(const std::string& file_name1, const std::string& file_name2)\n{\n std::ifstream file1(file_name1);\n std::ifstream file2(file_name2);\n int line_count = 0;\n\n while(true)\n {\n std::string line1, line2;\n std::getline(file1, line1);\n std::getline(file2, line2);\n ++line_count;\n\n if(line1 != line2)\n {\n std::cerr << \"Mismatch at line \" << line_count << \":\\n\";\n std::cerr << line1 << \" != \" << line2 << \"\\n\";\n return false;\n }\n\n if( ! file1 && ! file2)\n {\n break;\n }\n }\n\n return true;\n}\n\nvoid run_tests()\n{\n bool tests_passed = true;\n\n \/\/ Castling with attacking piece\n for(auto castle_side : std::string(\"KQ\"))\n {\n for(int rook_left_space = 0; rook_left_space < 8; ++rook_left_space)\n {\n auto rook_left = (rook_left_space > 0 ? std::to_string(rook_left_space) : std::string());\n auto rook_right = (rook_left_space < 7 ? std::to_string(7 - rook_left_space) : std::string());\n Board board(\"1k6\/\" + rook_left + \"r\" + rook_right + \"\/8\/8\/8\/8\/8\/R3K2R w KQ - 0 1\");\n\n char final_file = (castle_side == 'K' ? 'g' : 'c');\n\n try\n {\n board.get_complete_move('e', 1, final_file, 1);\n }\n catch(const Illegal_Move_Exception&)\n {\n if(castle_side == 'K')\n {\n if(rook_left_space >= 4 && rook_left_space <= 6)\n {\n continue;\n }\n }\n else\n {\n if(rook_left_space >= 2 && rook_left_space <= 4)\n {\n continue;\n }\n }\n\n board.ascii_draw(WHITE);\n std::cout << std::string(1, castle_side) + \"-castle should be legal here.\" << std::endl;\n tests_passed = false;\n }\n\n if(castle_side == 'K')\n {\n if(rook_left_space < 4 || rook_left_space > 6)\n {\n continue;\n }\n }\n else\n {\n if(rook_left_space < 2 || rook_left_space > 4)\n {\n continue;\n }\n }\n\n board.ascii_draw(WHITE);\n std::cout << std::string(1, castle_side) + \"-castle should be illegal here.\" << std::endl;\n tests_passed = false;\n }\n }\n\n\n \/\/ Test Genetic_AI file loading\n auto pool_file_name = \"test_gene_pool.txt\";\n auto write_file_name = \"test_genome_write.txt\";\n auto rewrite_file_name = \"test_genome_rewrite.txt\";\n remove(pool_file_name);\n remove(write_file_name);\n remove(rewrite_file_name);\n\n std::vector<Genetic_AI> test_pool(100);\n for(auto& ai : test_pool)\n {\n for(int i = 0; i < 1000; ++i)\n {\n ai.mutate();\n }\n ai.print_genome(pool_file_name);\n }\n\n auto index = Random::random_integer(0, test_pool.size() - 1);\n test_pool[index].print_genome(write_file_name);\n auto read_ai = Genetic_AI(pool_file_name, index);\n read_ai.print_genome(rewrite_file_name);\n\n if( ! files_are_identical(write_file_name, rewrite_file_name))\n {\n std::cerr << \"Genome loaded from gene pool file not preserved.\" << std::endl;\n tests_passed = false;\n }\n else\n {\n remove(pool_file_name);\n remove(write_file_name);\n remove(rewrite_file_name);\n }\n\n\n \/\/ String utilities\n std::string original = \" a # b\";\n std::string expected = \"a\";\n std::string result = String::strip_comments(original, '#');\n if(expected != result)\n {\n std::cerr << \"\\\"\" << original << \"\\\" --> \\\"\" << result << \"\\\"\" << std::endl;\n std::cerr << \"Expected result: \\\"\" << expected << \"\\\"\" << std::endl;\n tests_passed = false;\n }\n\n original = \" a { b } c { d } \";\n expected = \"a c\";\n result = String::strip_block_comment(original, '{', '}');\n if(expected != result)\n {\n std::cerr << \"\\\"\" << original << \"\\\" --> \\\"\" << result << \"\\\"\" << std::endl;\n std::cerr << \"Expected result: \\\"\" << expected << \"\\\"\" << std::endl;\n tests_passed = false;\n }\n\n std::string search_string = \"abcdefg\";\n std::string target = \"abc\";\n if( ! String::starts_with(search_string, target))\n {\n std::cerr << \"\\\"\" << target << \"\\\" not found at beginning of \" << search_string << std::endl;\n tests_passed = false;\n }\n\n std::string wrong_target = \"abd\";\n if(String::starts_with(search_string, wrong_target))\n {\n std::cerr << \"\\\"\" << wrong_target << \"\\\" erroneously found at beginning of \" << search_string << std::endl;\n tests_passed = false;\n }\n\n\n \/\/ Log-Norm distribution check\n const double mean_moves = 26.0;\n const double width = .5;\n const size_t moves_so_far = 22;\n auto moves_left = Math::average_moves_left(mean_moves, width, moves_so_far);\n auto expected_moves_left = 15.2629;\n if(std::abs(moves_left - expected_moves_left) > 1e-4)\n {\n std::cout << \"Log-Norm failed: Expected: \" << expected_moves_left\n << \" --- Got: \" << moves_left << std::endl;\n tests_passed = false;\n }\n\n\n \/\/ Clock time reset test\n auto time = 30;\n auto moves_to_reset = 40;\n auto clock = Clock(time, moves_to_reset);\n clock.start();\n for(int i = 0; i < 2*moves_to_reset; ++i)\n {\n std::this_thread::sleep_for(std::chrono::milliseconds(5));\n clock.punch();\n }\n clock.stop();\n if(clock.time_left(BLACK) != time)\n {\n std::cerr << \"Clock incorrect: time left for black is \" << clock.time_left(BLACK) << \" sec. Should be \" << time << \"sec.\" << std::endl;\n tests_passed = false;\n }\n\n \/\/ Clock time increment test\n auto increment = 5;\n auto clock2 = Clock(time, 0, increment);\n clock2.start();\n double expected_time = time;\n for(int i = 0; i < 2*moves_to_reset; ++i)\n {\n std::this_thread::sleep_for(std::chrono::milliseconds(5));\n clock2.punch();\n if(i % 2 == 1) \/\/ only on black moves\n {\n expected_time += increment - 0.005;\n }\n }\n clock2.stop();\n if(std::abs(clock2.time_left(BLACK) - expected_time) > 0.01)\n {\n std::cerr << \"Clock incorrect: time left for black is \" << clock2.time_left(BLACK) << \" sec. Should be \" << expected_time << \"sec.\" << std::endl;\n tests_passed = false;\n }\n\n Game_Tree_Node_Result r1 = {Complete_Move(),\n 10,\n WHITE,\n 2,\n {}};\n Game_Tree_Node_Result r2 = {Complete_Move(),\n 10,\n BLACK,\n 2,\n {}};\n\n if(better_than(r2, r1, WHITE))\n {\n std::cerr << \"1. Error in comparing Game Tree Node Results.\" << std::endl;\n tests_passed = false;\n }\n\n if(better_than(r1, r2, BLACK))\n {\n std::cerr << \"2. Error in comparing Game Tree Node Results.\" << std::endl;\n tests_passed = false;\n }\n\n Game_Tree_Node_Result alpha_start = {Complete_Move(),\n -Math::infinity,\n WHITE,\n 0,\n {}};\n\n Game_Tree_Node_Result beta_start = {Complete_Move(),\n Math::infinity,\n WHITE,\n 0,\n {}};\n if(better_than(alpha_start, beta_start, WHITE))\n {\n std::cerr << \"3. Error in comparing Game Tree Node Results.\" << std::endl;\n tests_passed = false;\n }\n\n if( ! better_than(alpha_start, beta_start, BLACK))\n {\n std::cerr << \"4. Error in comparing Game Tree Node Results.\" << std::endl;\n tests_passed = false;\n }\n\n\n Game_Tree_Node_Result white_win4 = {Complete_Move(),\n Math::win_score,\n WHITE,\n 4,\n {}};\n Game_Tree_Node_Result white_win6 = {Complete_Move(),\n Math::win_score,\n WHITE,\n 6,\n {}};\n if(better_than(white_win6, white_win4, WHITE))\n {\n std::cerr << \"Later win preferred over earlier win.\" << std::endl;\n tests_passed = false;\n }\n\n if(better_than(white_win4, white_win6, BLACK))\n {\n std::cerr << \"Earlier loss preferred over later win.\" << std::endl;\n tests_passed = false;\n }\n\n Game_Tree_Node_Result black_loss6 = {Complete_Move(),\n -Math::win_score,\n BLACK,\n 6,\n {}};\n if( ! (white_win6 == black_loss6))\n {\n std::cerr << \"White win in 6 not equal to black loss in 6.\" << std::endl;\n tests_passed = false;\n }\n\n\n \/\/ Move ambiguity check\n Board board;\n bool ambiguous_move_caught = false;\n try\n {\n for(auto move : {\"Nc3\", \"a1\",\n \"Nf3\", \"b1\",\n \"Ne4\", \"c1\",\n \"Ng5\"})\n {\n board.submit_move(board.get_complete_move(move));\n }\n }\n catch(const Illegal_Move_Exception&)\n {\n ambiguous_move_caught = true;\n }\n\n if( ! ambiguous_move_caught)\n {\n std::cerr << \"Last move should have been an error:\" << std::endl;\n board.print_game_record(nullptr, nullptr,\n \"\", Game_Result(NONE, \"\", false), 0, 0, 0, Clock());\n\n tests_passed = false;\n }\n\n Board().ascii_draw(WHITE);\n\n int int_width = 10;\n int real_width = 15;\n int norm_width = 15;\n std::cout << std::setw(int_width) << \"Integers\"\n << std::setw(real_width) << \"Reals\"\n << std::setw(norm_width) << \"Normals\" << '\\n';\n std::cout << std::setw(int_width) << \"+\/-1000\"\n << std::setw(real_width) << \"[0-2]\"\n << std::setw(norm_width) << \"sig = 3\" << '\\n';\n for(int i = 0; i < 10; ++i)\n {\n std::cout << std::setw(int_width) << Random::random_integer(-1000, 1000)\n << std::setw(real_width) << Random::random_real(0, 2)\n << std::setw(norm_width) << Random::random_normal(3) << '\\n';\n }\n\n \/\/ FEN input\/output\n for(std::string test : {\"rnbqkbnr\/pppppppp\/8\/8\/8\/8\/PPPPPPPP\/RNBQKBNR w KQkq - 0 1\",\n \"rnbqkbnr\/pppppppp\/8\/8\/4P3\/8\/PPPP1PPP\/RNBQKBNR b KQkq e3 0 1\",\n \"rnbqkbnr\/pp1ppppp\/8\/2p5\/4P3\/8\/PPPP1PPP\/RNBQKBNR w KQkq c6 0 2\",\n \"rnbqkbnr\/pp1ppppp\/8\/2p5\/4P3\/5N2\/PPPP1PPP\/RNBQKB1R b KQkq - 1 2\"})\n {\n if(Board(test).fen_status() != test)\n {\n std::cerr << test << \" -->\\n\" << Board(test).fen_status() << \"\\n\\n\";\n tests_passed = false;\n }\n }\n\n if(tests_passed)\n {\n std::cout << \"All tests passed.\" << std::endl;\n }\n else\n {\n std::cout << \"Tests failed.\" << std::endl;\n }\n}\n#else\nvoid run_tests() {}\n#endif\n<commit_msg>Add basic rules check in tests<commit_after>#include \"Testing.h\"\n\n#ifdef DEBUG\n#include <cstdlib>\n#include <fstream>\n#include <iostream>\n#include <cmath>\n#include <thread>\n#include <iomanip>\n\n#include \"Game\/Board.h\"\n#include \"Moves\/Complete_Move.h\"\n#include \"Players\/Genetic_AI.h\"\n#include \"Game\/Clock.h\"\n\n#include \"Utility.h\"\n\n#include \"Exceptions\/Illegal_Move_Exception.h\"\n\n\/\/ Declaration to silence warnings\nbool files_are_identical(const std::string& file_name1, const std::string& file_name2);\n\nbool files_are_identical(const std::string& file_name1, const std::string& file_name2)\n{\n std::ifstream file1(file_name1);\n std::ifstream file2(file_name2);\n int line_count = 0;\n\n while(true)\n {\n std::string line1, line2;\n std::getline(file1, line1);\n std::getline(file2, line2);\n ++line_count;\n\n if(line1 != line2)\n {\n std::cerr << \"Mismatch at line \" << line_count << \":\\n\";\n std::cerr << line1 << \" != \" << line2 << \"\\n\";\n return false;\n }\n\n if( ! file1 && ! file2)\n {\n break;\n }\n }\n\n return true;\n}\n\nvoid run_tests()\n{\n bool tests_passed = true;\n\n \/\/ Basic chess rules check\n Board starting_board;\n auto starting_move_count = starting_board.legal_moves().size();\n auto correct_move_count = 20;\n if(starting_move_count != correct_move_count)\n {\n std::cerr << \"Wrong number of legal moves at beginning of game. Got \" << starting_move_count\n << \", should be \" << correct_move_count << std::endl;\n std::cerr << \"Legal moves found:\" << std::endl;\n auto move_count = 0;\n for(const auto& move : starting_board.legal_moves())\n {\n std::cerr << ++move_count << \". \" << move.game_record_item(starting_board) << std::endl;\n }\n\n tests_passed = false;\n }\n\n \/\/ Castling with attacking piece\n for(auto castle_side : std::string(\"KQ\"))\n {\n for(int rook_left_space = 0; rook_left_space < 8; ++rook_left_space)\n {\n auto rook_left = (rook_left_space > 0 ? std::to_string(rook_left_space) : std::string());\n auto rook_right = (rook_left_space < 7 ? std::to_string(7 - rook_left_space) : std::string());\n Board board(\"1k6\/\" + rook_left + \"r\" + rook_right + \"\/8\/8\/8\/8\/8\/R3K2R w KQ - 0 1\");\n\n char final_file = (castle_side == 'K' ? 'g' : 'c');\n\n try\n {\n board.get_complete_move('e', 1, final_file, 1);\n }\n catch(const Illegal_Move_Exception&)\n {\n if(castle_side == 'K')\n {\n if(rook_left_space >= 4 && rook_left_space <= 6)\n {\n continue;\n }\n }\n else\n {\n if(rook_left_space >= 2 && rook_left_space <= 4)\n {\n continue;\n }\n }\n\n board.ascii_draw(WHITE);\n std::cout << std::string(1, castle_side) + \"-castle should be legal here.\" << std::endl;\n tests_passed = false;\n }\n\n if(castle_side == 'K')\n {\n if(rook_left_space < 4 || rook_left_space > 6)\n {\n continue;\n }\n }\n else\n {\n if(rook_left_space < 2 || rook_left_space > 4)\n {\n continue;\n }\n }\n\n board.ascii_draw(WHITE);\n std::cout << std::string(1, castle_side) + \"-castle should be illegal here.\" << std::endl;\n tests_passed = false;\n }\n }\n\n\n \/\/ Test Genetic_AI file loading\n auto pool_file_name = \"test_gene_pool.txt\";\n auto write_file_name = \"test_genome_write.txt\";\n auto rewrite_file_name = \"test_genome_rewrite.txt\";\n remove(pool_file_name);\n remove(write_file_name);\n remove(rewrite_file_name);\n\n std::vector<Genetic_AI> test_pool(100);\n for(auto& ai : test_pool)\n {\n for(int i = 0; i < 1000; ++i)\n {\n ai.mutate();\n }\n ai.print_genome(pool_file_name);\n }\n\n auto index = Random::random_integer(0, test_pool.size() - 1);\n test_pool[index].print_genome(write_file_name);\n auto read_ai = Genetic_AI(pool_file_name, index);\n read_ai.print_genome(rewrite_file_name);\n\n if( ! files_are_identical(write_file_name, rewrite_file_name))\n {\n std::cerr << \"Genome loaded from gene pool file not preserved.\" << std::endl;\n tests_passed = false;\n }\n else\n {\n remove(pool_file_name);\n remove(write_file_name);\n remove(rewrite_file_name);\n }\n\n\n \/\/ String utilities\n std::string original = \" a # b\";\n std::string expected = \"a\";\n std::string result = String::strip_comments(original, '#');\n if(expected != result)\n {\n std::cerr << \"\\\"\" << original << \"\\\" --> \\\"\" << result << \"\\\"\" << std::endl;\n std::cerr << \"Expected result: \\\"\" << expected << \"\\\"\" << std::endl;\n tests_passed = false;\n }\n\n original = \" a { b } c { d } \";\n expected = \"a c\";\n result = String::strip_block_comment(original, '{', '}');\n if(expected != result)\n {\n std::cerr << \"\\\"\" << original << \"\\\" --> \\\"\" << result << \"\\\"\" << std::endl;\n std::cerr << \"Expected result: \\\"\" << expected << \"\\\"\" << std::endl;\n tests_passed = false;\n }\n\n std::string search_string = \"abcdefg\";\n std::string target = \"abc\";\n if( ! String::starts_with(search_string, target))\n {\n std::cerr << \"\\\"\" << target << \"\\\" not found at beginning of \" << search_string << std::endl;\n tests_passed = false;\n }\n\n std::string wrong_target = \"abd\";\n if(String::starts_with(search_string, wrong_target))\n {\n std::cerr << \"\\\"\" << wrong_target << \"\\\" erroneously found at beginning of \" << search_string << std::endl;\n tests_passed = false;\n }\n\n\n \/\/ Log-Norm distribution check\n const double mean_moves = 26.0;\n const double width = .5;\n const size_t moves_so_far = 22;\n auto moves_left = Math::average_moves_left(mean_moves, width, moves_so_far);\n auto expected_moves_left = 15.2629;\n if(std::abs(moves_left - expected_moves_left) > 1e-4)\n {\n std::cout << \"Log-Norm failed: Expected: \" << expected_moves_left\n << \" --- Got: \" << moves_left << std::endl;\n tests_passed = false;\n }\n\n\n \/\/ Clock time reset test\n auto time = 30;\n auto moves_to_reset = 40;\n auto clock = Clock(time, moves_to_reset);\n clock.start();\n for(int i = 0; i < 2*moves_to_reset; ++i)\n {\n std::this_thread::sleep_for(std::chrono::milliseconds(5));\n clock.punch();\n }\n clock.stop();\n if(clock.time_left(BLACK) != time)\n {\n std::cerr << \"Clock incorrect: time left for black is \" << clock.time_left(BLACK) << \" sec. Should be \" << time << \"sec.\" << std::endl;\n tests_passed = false;\n }\n\n \/\/ Clock time increment test\n auto increment = 5;\n auto clock2 = Clock(time, 0, increment);\n clock2.start();\n double expected_time = time;\n for(int i = 0; i < 2*moves_to_reset; ++i)\n {\n std::this_thread::sleep_for(std::chrono::milliseconds(5));\n clock2.punch();\n if(i % 2 == 1) \/\/ only on black moves\n {\n expected_time += increment - 0.005;\n }\n }\n clock2.stop();\n if(std::abs(clock2.time_left(BLACK) - expected_time) > 0.01)\n {\n std::cerr << \"Clock incorrect: time left for black is \" << clock2.time_left(BLACK) << \" sec. Should be \" << expected_time << \"sec.\" << std::endl;\n tests_passed = false;\n }\n\n Game_Tree_Node_Result r1 = {Complete_Move(),\n 10,\n WHITE,\n 2,\n {}};\n Game_Tree_Node_Result r2 = {Complete_Move(),\n 10,\n BLACK,\n 2,\n {}};\n\n if(better_than(r2, r1, WHITE))\n {\n std::cerr << \"1. Error in comparing Game Tree Node Results.\" << std::endl;\n tests_passed = false;\n }\n\n if(better_than(r1, r2, BLACK))\n {\n std::cerr << \"2. Error in comparing Game Tree Node Results.\" << std::endl;\n tests_passed = false;\n }\n\n Game_Tree_Node_Result alpha_start = {Complete_Move(),\n -Math::infinity,\n WHITE,\n 0,\n {}};\n\n Game_Tree_Node_Result beta_start = {Complete_Move(),\n Math::infinity,\n WHITE,\n 0,\n {}};\n if(better_than(alpha_start, beta_start, WHITE))\n {\n std::cerr << \"3. Error in comparing Game Tree Node Results.\" << std::endl;\n tests_passed = false;\n }\n\n if( ! better_than(alpha_start, beta_start, BLACK))\n {\n std::cerr << \"4. Error in comparing Game Tree Node Results.\" << std::endl;\n tests_passed = false;\n }\n\n\n Game_Tree_Node_Result white_win4 = {Complete_Move(),\n Math::win_score,\n WHITE,\n 4,\n {}};\n Game_Tree_Node_Result white_win6 = {Complete_Move(),\n Math::win_score,\n WHITE,\n 6,\n {}};\n if(better_than(white_win6, white_win4, WHITE))\n {\n std::cerr << \"Later win preferred over earlier win.\" << std::endl;\n tests_passed = false;\n }\n\n if(better_than(white_win4, white_win6, BLACK))\n {\n std::cerr << \"Earlier loss preferred over later win.\" << std::endl;\n tests_passed = false;\n }\n\n Game_Tree_Node_Result black_loss6 = {Complete_Move(),\n -Math::win_score,\n BLACK,\n 6,\n {}};\n if( ! (white_win6 == black_loss6))\n {\n std::cerr << \"White win in 6 not equal to black loss in 6.\" << std::endl;\n tests_passed = false;\n }\n\n\n \/\/ Move ambiguity check\n Board board;\n bool ambiguous_move_caught = false;\n try\n {\n for(auto move : {\"Nc3\", \"a1\",\n \"Nf3\", \"b1\",\n \"Ne4\", \"c1\",\n \"Ng5\"})\n {\n board.submit_move(board.get_complete_move(move));\n }\n }\n catch(const Illegal_Move_Exception&)\n {\n ambiguous_move_caught = true;\n }\n\n if( ! ambiguous_move_caught)\n {\n std::cerr << \"Last move should have been an error:\" << std::endl;\n board.print_game_record(nullptr, nullptr,\n \"\", Game_Result(NONE, \"\", false), 0, 0, 0, Clock());\n\n tests_passed = false;\n }\n\n Board().ascii_draw(WHITE);\n\n int int_width = 10;\n int real_width = 15;\n int norm_width = 15;\n std::cout << std::setw(int_width) << \"Integers\"\n << std::setw(real_width) << \"Reals\"\n << std::setw(norm_width) << \"Normals\" << '\\n';\n std::cout << std::setw(int_width) << \"+\/-1000\"\n << std::setw(real_width) << \"[0-2]\"\n << std::setw(norm_width) << \"sig = 3\" << '\\n';\n for(int i = 0; i < 10; ++i)\n {\n std::cout << std::setw(int_width) << Random::random_integer(-1000, 1000)\n << std::setw(real_width) << Random::random_real(0, 2)\n << std::setw(norm_width) << Random::random_normal(3) << '\\n';\n }\n\n \/\/ FEN input\/output\n for(std::string test : {\"rnbqkbnr\/pppppppp\/8\/8\/8\/8\/PPPPPPPP\/RNBQKBNR w KQkq - 0 1\",\n \"rnbqkbnr\/pppppppp\/8\/8\/4P3\/8\/PPPP1PPP\/RNBQKBNR b KQkq e3 0 1\",\n \"rnbqkbnr\/pp1ppppp\/8\/2p5\/4P3\/8\/PPPP1PPP\/RNBQKBNR w KQkq c6 0 2\",\n \"rnbqkbnr\/pp1ppppp\/8\/2p5\/4P3\/5N2\/PPPP1PPP\/RNBQKB1R b KQkq - 1 2\"})\n {\n if(Board(test).fen_status() != test)\n {\n std::cerr << test << \" -->\\n\" << Board(test).fen_status() << \"\\n\\n\";\n tests_passed = false;\n }\n }\n\n if(tests_passed)\n {\n std::cout << \"All tests passed.\" << std::endl;\n }\n else\n {\n std::cout << \"Tests failed.\" << std::endl;\n }\n}\n#else\nvoid run_tests() {}\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/*\n * goal_orientation_constraint.cpp\n *\n * Created on: Apr 21, 2016\n * Author: Jorge Nicho\n *\/\n\n#include <ros\/console.h>\n#include <Eigen\/Geometry>\n#include <eigen_conversions\/eigen_msg.h>\n#include <moveit\/robot_state\/robot_state.h>\n#include <moveit\/robot_state\/conversions.h>\n#include <pluginlib\/class_list_macros.h>\n#include <stomp_moveit\/noisy_filters\/underconstrained_goal.h>\n#include <XmlRpcException.h>\n\nPLUGINLIB_EXPORT_CLASS(stomp_moveit::noisy_filters::UnderconstrainedGoal,stomp_moveit::noisy_filters::StompNoisyFilter);\n\n\nconst static unsigned int DOF_SIZE = 6;\nconst static double EPSILON = 0.1;\nconst static double LAMBDA = 0.01;\n\nstatic void reduceJacobian(const Eigen::MatrixXd& jacb,\n const std::vector<int>& indices,Eigen::MatrixXd& jacb_reduced)\n{\n jacb_reduced.resize(indices.size(),jacb.cols());\n for(auto i = 0u; i < indices.size(); i++)\n {\n jacb_reduced.row(i) = jacb.row(indices[i]);\n }\n}\n\nstatic void calculateMoorePenrosePseudoInverse(const Eigen::MatrixXd& jacb,Eigen::MatrixXd& jacb_pseudo_inv)\n{\n Eigen::MatrixXd jacb_transpose = jacb.transpose();\n jacb_pseudo_inv = (jacb_transpose) * ((jacb * jacb_transpose).inverse());\n}\n\nstatic void calculateDampedPseudoInverse(const Eigen::MatrixXd &jacb, Eigen::MatrixXd &jacb_pseudo_inv,\n double eps = 0.011, double lambda = 0.01)\n{\n using namespace Eigen;\n\n\n \/\/Calculate A+ (pseudoinverse of A) = V S+ U*, where U* is Hermition of U (just transpose if all values of U are real)\n \/\/in order to solve Ax=b -> x*=A+ b\n Eigen::JacobiSVD<MatrixXd> svd(jacb, Eigen::ComputeThinU | Eigen::ComputeThinV);\n const MatrixXd &U = svd.matrixU();\n const VectorXd &Sv = svd.singularValues();\n const MatrixXd &V = svd.matrixV();\n\n \/\/ calculate the reciprocal of Singular-Values\n \/\/ damp inverse with lambda so that inverse doesn't oscillate near solution\n size_t nSv = Sv.size();\n VectorXd inv_Sv(nSv);\n for(size_t i=0; i< nSv; ++i)\n {\n if (fabs(Sv(i)) > eps)\n {\n inv_Sv(i) = 1\/Sv(i);\n }\n else\n {\n inv_Sv(i) = Sv(i) \/ (Sv(i)*Sv(i) + lambda*lambda);\n }\n }\n\n jacb_pseudo_inv = V * inv_Sv.asDiagonal() * U.transpose();\n}\n\nstatic void computeTwist(const Eigen::Affine3d& p0,\n const Eigen::Affine3d& pf,\n const Eigen::ArrayXi& nullity,Eigen::VectorXd& twist)\n{\n twist.resize(nullity.size());\n twist.setConstant(0);\n Eigen::Vector3d twist_pos = pf.translation() - p0.translation();\n\n \/\/ relative rotation -> R = inverse(R0) * Rf\n Eigen::AngleAxisd relative_rot(p0.rotation().transpose() * pf.rotation());\n double angle = relative_rot.angle();\n Eigen::Vector3d axis = relative_rot.axis();\n\n \/\/ forcing angle to range [-pi , pi]\n while( (angle > M_PI) || (angle < -M_PI))\n {\n angle = (angle > M_PI) ? (angle - 2*M_PI) : angle;\n angle = (angle < -M_PI )? (angle + 2*M_PI) : angle;\n }\n\n \/\/ creating twist rotation relative to tool\n Eigen::Vector3d twist_rot = axis * angle;\n\n \/\/ assigning into full 6dof twist vector\n twist.head(3) = twist_pos;\n twist.tail(3) = twist_rot;\n\n \/\/ zeroing all underconstrained cartesian dofs\n twist = (nullity == 0).select(0,twist);\n}\n\nnamespace stomp_moveit\n{\nnamespace noisy_filters\n{\n\nUnderconstrainedGoal::UnderconstrainedGoal():\n name_(\"UnderconstrainedGoal\")\n{\n\n}\n\nUnderconstrainedGoal::~UnderconstrainedGoal()\n{\n \/\/ TODO Auto-generated destructor stub\n}\n\nbool UnderconstrainedGoal::initialize(moveit::core::RobotModelConstPtr robot_model_ptr,\n const std::string& group_name,const XmlRpc::XmlRpcValue& config)\n{\n group_name_ = group_name;\n robot_model_ = robot_model_ptr;\n\n return configure(config);\n}\n\nbool UnderconstrainedGoal::configure(const XmlRpc::XmlRpcValue& config)\n{\n using namespace XmlRpc;\n\n try\n {\n XmlRpcValue params = config;\n\n XmlRpcValue dof_nullity_param = params[\"constrained_dofs\"];\n XmlRpcValue dof_thresholds_param = params[\"cartesian_convergence\"];\n XmlRpcValue joint_updates_param = params[\"joint_update_rates\"];\n if((dof_nullity_param.getType() != XmlRpcValue::TypeArray) ||\n dof_nullity_param.size() < DOF_SIZE ||\n dof_thresholds_param.getType() != XmlRpcValue::TypeArray ||\n dof_thresholds_param.size() < DOF_SIZE ||\n joint_updates_param.getType() != XmlRpcValue::TypeArray ||\n joint_updates_param.size() == 0)\n {\n ROS_ERROR(\"UnderconstrainedGoal received invalid array parameters\");\n return false;\n }\n\n dof_nullity_.resize(DOF_SIZE);\n for(auto i = 0u; i < dof_nullity_param.size(); i++)\n {\n dof_nullity_(i) = static_cast<int>(dof_nullity_param[i]);\n }\n\n cartesian_convergence_thresholds_.resize(DOF_SIZE);\n for(auto i = 0u; i < dof_thresholds_param.size(); i++)\n {\n cartesian_convergence_thresholds_(i) = static_cast<double>(dof_thresholds_param[i]);\n }\n\n joint_update_rates_.resize(joint_updates_param.size());\n for(auto i = 0u; i < joint_updates_param.size(); i++)\n {\n joint_update_rates_(i) = static_cast<double>(joint_updates_param[i]);\n }\n\n \/\/update_weight_ = static_cast<double>(params[\"update_weight\"]);\n max_iterations_ = static_cast<int>(params[\"max_ik_iterations\"]);\n }\n catch(XmlRpc::XmlRpcException& e)\n {\n ROS_ERROR(\"UnderconstrainedGoal failed to load parameters, %s\",e.getMessage().c_str());\n return false;\n }\n\n return true;\n}\n\nbool UnderconstrainedGoal::setMotionPlanRequest(const planning_scene::PlanningSceneConstPtr& planning_scene,\n const moveit_msgs::MotionPlanRequest &req,\n const stomp_core::StompConfiguration &config,\n moveit_msgs::MoveItErrorCodes& error_code)\n{\n using namespace Eigen;\n using namespace moveit::core;\n\n const JointModelGroup* joint_group = robot_model_->getJointModelGroup(group_name_);\n tool_link_ = joint_group->getLinkModelNames().back();\n state_.reset(new RobotState(robot_model_));\n robotStateMsgToRobotState(req.start_state,*state_);\n\n const std::vector<moveit_msgs::Constraints>& goals = req.goal_constraints;\n if(goals.empty())\n {\n ROS_ERROR(\"A goal constraint was not provided\");\n error_code.val = error_code.INVALID_GOAL_CONSTRAINTS;\n return false;\n }\n\n \/\/ storing tool goal pose\n if(goals.front().position_constraints.empty() ||\n goals.front().orientation_constraints.empty())\n {\n ROS_WARN(\"A goal constraint for the tool link was not provided, using forward kinematics\");\n\n \/\/ check joint constraints\n if(goals.front().joint_constraints.empty())\n {\n ROS_ERROR_STREAM(\"No joint values for the goal were found\");\n error_code.val = error_code.INVALID_GOAL_CONSTRAINTS;\n return false;\n }\n\n \/\/ compute FK to obtain tool pose\n const std::vector<moveit_msgs::JointConstraint>& joint_constraints = goals.front().joint_constraints;\n\n \/\/ copying goal values into state\n for(auto& jc: joint_constraints)\n {\n state_->setVariablePosition(jc.joint_name,jc.position);\n }\n\n state_->update(true);\n state_->enforceBounds(joint_group);\n tool_goal_pose_ = state_->getGlobalLinkTransform(tool_link_);\n }\n else\n {\n \/\/ tool goal\n const moveit_msgs::PositionConstraint& pos_constraint = goals.front().position_constraints.front();\n const moveit_msgs::OrientationConstraint& orient_constraint = goals.front().orientation_constraints.front();\n\n geometry_msgs::Pose pose;\n pose.position = pos_constraint.constraint_region.primitive_poses[0].position;\n pose.orientation = orient_constraint.orientation;\n tf::poseMsgToEigen(pose,tool_goal_pose_);\n }\n\n error_code.val = error_code.SUCCESS;\n return true;\n}\n\n\nbool UnderconstrainedGoal::filter(std::size_t start_timestep,\n std::size_t num_timesteps,\n int iteration_number,\n int rollout_number,\n Eigen::MatrixXd& parameters,\n bool& filtered)\n{\n using namespace Eigen;\n using namespace moveit::core;\n\n VectorXd init_joint_pose = parameters.rightCols(1);\n VectorXd joint_pose;\n\n if(!runIK(tool_goal_pose_,init_joint_pose,joint_pose))\n {\n ROS_ERROR(\"UnderconstrainedGoal failed to find valid ik close to reference pose\");\n filtered = false;\n return false;\n }\n\n filtered = true;\n ROS_DEBUG_STREAM(\"Last joint pose changes \"<<(parameters.rightCols(1) - joint_pose).transpose());\n parameters.rightCols(1) = joint_pose;\n\n return true;\n}\n\nbool UnderconstrainedGoal::runIK(const Eigen::Affine3d& tool_goal_pose,const Eigen::VectorXd& init_joint_pose,\n Eigen::VectorXd& joint_pose)\n{\n using namespace Eigen;\n using namespace moveit::core;\n\n \/\/ joint variables\n VectorXd delta_j = VectorXd::Zero(init_joint_pose.size());\n joint_pose = init_joint_pose;\n const JointModelGroup* joint_group = robot_model_->getJointModelGroup(group_name_);\n state_->setJointGroupPositions(joint_group,joint_pose);\n Affine3d tool_current_pose = state_->getGlobalLinkTransform(tool_link_);\n\n \/\/ tool twist variables\n VectorXd tool_twist, tool_twist_reduced;\n std::vector<int> indices;\n for(auto i = 0u; i < dof_nullity_.size(); i++)\n {\n if(dof_nullity_(i) != 0)\n {\n indices.push_back(i);\n }\n }\n tool_twist_reduced = VectorXd::Zero(indices.size());\n\n \/\/ jacobian calculation variables\n MatrixXd identity = MatrixXd::Identity(init_joint_pose.size(),init_joint_pose.size());\n MatrixXd jacb, jacb_reduced, jacb_pseudo_inv;\n\n unsigned int iteration_count = 0;\n bool converged = false;\n while(iteration_count < max_iterations_)\n {\n\n \/\/ computing twist vector\n computeTwist(tool_current_pose,tool_goal_pose,dof_nullity_,tool_twist);\n\n \/\/ check convergence\n if((tool_twist.cwiseAbs().array() < cartesian_convergence_thresholds_).all())\n {\n \/\/ converged\n converged = true;\n ROS_DEBUG(\"Found numeric ik solution after %i iterations\",iteration_count);\n break;\n }\n\n \/\/ updating reduced tool twist\n for(auto i = 0u; i < indices.size(); i++)\n {\n tool_twist_reduced(i) = tool_twist(indices[i]);\n }\n\n \/\/ computing jacobian\n if(!state_->getJacobian(joint_group,state_->getLinkModel(tool_link_),Vector3d::Zero(),jacb))\n {\n ROS_ERROR(\"Failed to get Jacobian for link %s\",tool_link_.c_str());\n return false;\n }\n\n \/\/ transform jacobian rotational part to tool coordinates\n jacb.bottomRows(3) = tool_current_pose.rotation().transpose()*jacb.bottomRows(3);\n\n \/\/ reduce jacobian and compute its pseudo inverse\n reduceJacobian(jacb,indices,jacb_reduced);\n calculateDampedPseudoInverse(jacb_reduced,jacb_pseudo_inv,EPSILON,LAMBDA);\n\n \/\/ computing joint change\n delta_j = (jacb_pseudo_inv*tool_twist_reduced);\n\n \/\/ updating joint values\n joint_pose += (joint_update_rates_* delta_j.array()).matrix();\n\n \/\/ updating tool pose\n state_->setJointGroupPositions(joint_group,joint_pose);\n tool_current_pose = state_->getGlobalLinkTransform(tool_link_);\n\n iteration_count++;\n }\n\n ROS_DEBUG_STREAM(\"Final tool twist \"<<tool_twist.transpose());\n\n return converged;\n}\n\n\n\n} \/* namespace filters *\/\n} \/* namespace stomp_moveit *\/\n<commit_msg>Remove print statement<commit_after>\/*\n * goal_orientation_constraint.cpp\n *\n * Created on: Apr 21, 2016\n * Author: Jorge Nicho\n *\/\n\n#include <ros\/console.h>\n#include <Eigen\/Geometry>\n#include <eigen_conversions\/eigen_msg.h>\n#include <moveit\/robot_state\/robot_state.h>\n#include <moveit\/robot_state\/conversions.h>\n#include <pluginlib\/class_list_macros.h>\n#include <stomp_moveit\/noisy_filters\/underconstrained_goal.h>\n#include <XmlRpcException.h>\n\nPLUGINLIB_EXPORT_CLASS(stomp_moveit::noisy_filters::UnderconstrainedGoal,stomp_moveit::noisy_filters::StompNoisyFilter);\n\n\nconst static unsigned int DOF_SIZE = 6;\nconst static double EPSILON = 0.1;\nconst static double LAMBDA = 0.01;\n\nstatic void reduceJacobian(const Eigen::MatrixXd& jacb,\n const std::vector<int>& indices,Eigen::MatrixXd& jacb_reduced)\n{\n jacb_reduced.resize(indices.size(),jacb.cols());\n for(auto i = 0u; i < indices.size(); i++)\n {\n jacb_reduced.row(i) = jacb.row(indices[i]);\n }\n}\n\nstatic void calculateMoorePenrosePseudoInverse(const Eigen::MatrixXd& jacb,Eigen::MatrixXd& jacb_pseudo_inv)\n{\n Eigen::MatrixXd jacb_transpose = jacb.transpose();\n jacb_pseudo_inv = (jacb_transpose) * ((jacb * jacb_transpose).inverse());\n}\n\nstatic void calculateDampedPseudoInverse(const Eigen::MatrixXd &jacb, Eigen::MatrixXd &jacb_pseudo_inv,\n double eps = 0.011, double lambda = 0.01)\n{\n using namespace Eigen;\n\n\n \/\/Calculate A+ (pseudoinverse of A) = V S+ U*, where U* is Hermition of U (just transpose if all values of U are real)\n \/\/in order to solve Ax=b -> x*=A+ b\n Eigen::JacobiSVD<MatrixXd> svd(jacb, Eigen::ComputeThinU | Eigen::ComputeThinV);\n const MatrixXd &U = svd.matrixU();\n const VectorXd &Sv = svd.singularValues();\n const MatrixXd &V = svd.matrixV();\n\n \/\/ calculate the reciprocal of Singular-Values\n \/\/ damp inverse with lambda so that inverse doesn't oscillate near solution\n size_t nSv = Sv.size();\n VectorXd inv_Sv(nSv);\n for(size_t i=0; i< nSv; ++i)\n {\n if (fabs(Sv(i)) > eps)\n {\n inv_Sv(i) = 1\/Sv(i);\n }\n else\n {\n inv_Sv(i) = Sv(i) \/ (Sv(i)*Sv(i) + lambda*lambda);\n }\n }\n\n jacb_pseudo_inv = V * inv_Sv.asDiagonal() * U.transpose();\n}\n\nstatic void computeTwist(const Eigen::Affine3d& p0,\n const Eigen::Affine3d& pf,\n const Eigen::ArrayXi& nullity,Eigen::VectorXd& twist)\n{\n twist.resize(nullity.size());\n twist.setConstant(0);\n Eigen::Vector3d twist_pos = pf.translation() - p0.translation();\n\n \/\/ relative rotation -> R = inverse(R0) * Rf\n Eigen::AngleAxisd relative_rot(p0.rotation().transpose() * pf.rotation());\n double angle = relative_rot.angle();\n Eigen::Vector3d axis = relative_rot.axis();\n\n \/\/ forcing angle to range [-pi , pi]\n while( (angle > M_PI) || (angle < -M_PI))\n {\n angle = (angle > M_PI) ? (angle - 2*M_PI) : angle;\n angle = (angle < -M_PI )? (angle + 2*M_PI) : angle;\n }\n\n \/\/ creating twist rotation relative to tool\n Eigen::Vector3d twist_rot = axis * angle;\n\n \/\/ assigning into full 6dof twist vector\n twist.head(3) = twist_pos;\n twist.tail(3) = twist_rot;\n\n \/\/ zeroing all underconstrained cartesian dofs\n twist = (nullity == 0).select(0,twist);\n}\n\nnamespace stomp_moveit\n{\nnamespace noisy_filters\n{\n\nUnderconstrainedGoal::UnderconstrainedGoal():\n name_(\"UnderconstrainedGoal\")\n{\n\n}\n\nUnderconstrainedGoal::~UnderconstrainedGoal()\n{\n \/\/ TODO Auto-generated destructor stub\n}\n\nbool UnderconstrainedGoal::initialize(moveit::core::RobotModelConstPtr robot_model_ptr,\n const std::string& group_name,const XmlRpc::XmlRpcValue& config)\n{\n group_name_ = group_name;\n robot_model_ = robot_model_ptr;\n\n return configure(config);\n}\n\nbool UnderconstrainedGoal::configure(const XmlRpc::XmlRpcValue& config)\n{\n using namespace XmlRpc;\n\n try\n {\n XmlRpcValue params = config;\n\n XmlRpcValue dof_nullity_param = params[\"constrained_dofs\"];\n XmlRpcValue dof_thresholds_param = params[\"cartesian_convergence\"];\n XmlRpcValue joint_updates_param = params[\"joint_update_rates\"];\n if((dof_nullity_param.getType() != XmlRpcValue::TypeArray) ||\n dof_nullity_param.size() < DOF_SIZE ||\n dof_thresholds_param.getType() != XmlRpcValue::TypeArray ||\n dof_thresholds_param.size() < DOF_SIZE ||\n joint_updates_param.getType() != XmlRpcValue::TypeArray ||\n joint_updates_param.size() == 0)\n {\n ROS_ERROR(\"UnderconstrainedGoal received invalid array parameters\");\n return false;\n }\n\n dof_nullity_.resize(DOF_SIZE);\n for(auto i = 0u; i < dof_nullity_param.size(); i++)\n {\n dof_nullity_(i) = static_cast<int>(dof_nullity_param[i]);\n }\n\n cartesian_convergence_thresholds_.resize(DOF_SIZE);\n for(auto i = 0u; i < dof_thresholds_param.size(); i++)\n {\n cartesian_convergence_thresholds_(i) = static_cast<double>(dof_thresholds_param[i]);\n }\n\n joint_update_rates_.resize(joint_updates_param.size());\n for(auto i = 0u; i < joint_updates_param.size(); i++)\n {\n joint_update_rates_(i) = static_cast<double>(joint_updates_param[i]);\n }\n\n \/\/update_weight_ = static_cast<double>(params[\"update_weight\"]);\n max_iterations_ = static_cast<int>(params[\"max_ik_iterations\"]);\n }\n catch(XmlRpc::XmlRpcException& e)\n {\n ROS_ERROR(\"UnderconstrainedGoal failed to load parameters, %s\",e.getMessage().c_str());\n return false;\n }\n\n return true;\n}\n\nbool UnderconstrainedGoal::setMotionPlanRequest(const planning_scene::PlanningSceneConstPtr& planning_scene,\n const moveit_msgs::MotionPlanRequest &req,\n const stomp_core::StompConfiguration &config,\n moveit_msgs::MoveItErrorCodes& error_code)\n{\n using namespace Eigen;\n using namespace moveit::core;\n\n const JointModelGroup* joint_group = robot_model_->getJointModelGroup(group_name_);\n tool_link_ = joint_group->getLinkModelNames().back();\n state_.reset(new RobotState(robot_model_));\n robotStateMsgToRobotState(req.start_state,*state_);\n\n const std::vector<moveit_msgs::Constraints>& goals = req.goal_constraints;\n if(goals.empty())\n {\n ROS_ERROR(\"A goal constraint was not provided\");\n error_code.val = error_code.INVALID_GOAL_CONSTRAINTS;\n return false;\n }\n\n \/\/ storing tool goal pose\n if(goals.front().position_constraints.empty() ||\n goals.front().orientation_constraints.empty())\n {\n ROS_WARN(\"A goal constraint for the tool link was not provided, using forward kinematics\");\n\n \/\/ check joint constraints\n if(goals.front().joint_constraints.empty())\n {\n ROS_ERROR_STREAM(\"No joint values for the goal were found\");\n error_code.val = error_code.INVALID_GOAL_CONSTRAINTS;\n return false;\n }\n\n \/\/ compute FK to obtain tool pose\n const std::vector<moveit_msgs::JointConstraint>& joint_constraints = goals.front().joint_constraints;\n\n \/\/ copying goal values into state\n for(auto& jc: joint_constraints)\n {\n state_->setVariablePosition(jc.joint_name,jc.position);\n }\n\n state_->update(true);\n state_->enforceBounds(joint_group);\n tool_goal_pose_ = state_->getGlobalLinkTransform(tool_link_);\n }\n else\n {\n \/\/ tool goal\n const moveit_msgs::PositionConstraint& pos_constraint = goals.front().position_constraints.front();\n const moveit_msgs::OrientationConstraint& orient_constraint = goals.front().orientation_constraints.front();\n\n geometry_msgs::Pose pose;\n pose.position = pos_constraint.constraint_region.primitive_poses[0].position;\n pose.orientation = orient_constraint.orientation;\n tf::poseMsgToEigen(pose,tool_goal_pose_);\n }\n\n error_code.val = error_code.SUCCESS;\n return true;\n}\n\n\nbool UnderconstrainedGoal::filter(std::size_t start_timestep,\n std::size_t num_timesteps,\n int iteration_number,\n int rollout_number,\n Eigen::MatrixXd& parameters,\n bool& filtered)\n{\n using namespace Eigen;\n using namespace moveit::core;\n\n VectorXd init_joint_pose = parameters.rightCols(1);\n VectorXd joint_pose;\n\n if(!runIK(tool_goal_pose_,init_joint_pose,joint_pose))\n {\n ROS_ERROR(\"UnderconstrainedGoal failed to find valid ik close to reference pose\");\n filtered = false;\n return false;\n }\n\n filtered = true;\n parameters.rightCols(1) = joint_pose;\n\n return true;\n}\n\nbool UnderconstrainedGoal::runIK(const Eigen::Affine3d& tool_goal_pose,const Eigen::VectorXd& init_joint_pose,\n Eigen::VectorXd& joint_pose)\n{\n using namespace Eigen;\n using namespace moveit::core;\n\n \/\/ joint variables\n VectorXd delta_j = VectorXd::Zero(init_joint_pose.size());\n joint_pose = init_joint_pose;\n const JointModelGroup* joint_group = robot_model_->getJointModelGroup(group_name_);\n state_->setJointGroupPositions(joint_group,joint_pose);\n Affine3d tool_current_pose = state_->getGlobalLinkTransform(tool_link_);\n\n \/\/ tool twist variables\n VectorXd tool_twist, tool_twist_reduced;\n std::vector<int> indices;\n for(auto i = 0u; i < dof_nullity_.size(); i++)\n {\n if(dof_nullity_(i) != 0)\n {\n indices.push_back(i);\n }\n }\n tool_twist_reduced = VectorXd::Zero(indices.size());\n\n \/\/ jacobian calculation variables\n MatrixXd identity = MatrixXd::Identity(init_joint_pose.size(),init_joint_pose.size());\n MatrixXd jacb, jacb_reduced, jacb_pseudo_inv;\n\n unsigned int iteration_count = 0;\n bool converged = false;\n while(iteration_count < max_iterations_)\n {\n\n \/\/ computing twist vector\n computeTwist(tool_current_pose,tool_goal_pose,dof_nullity_,tool_twist);\n\n \/\/ check convergence\n if((tool_twist.cwiseAbs().array() < cartesian_convergence_thresholds_).all())\n {\n \/\/ converged\n converged = true;\n ROS_DEBUG(\"Found numeric ik solution after %i iterations\",iteration_count);\n break;\n }\n\n \/\/ updating reduced tool twist\n for(auto i = 0u; i < indices.size(); i++)\n {\n tool_twist_reduced(i) = tool_twist(indices[i]);\n }\n\n \/\/ computing jacobian\n if(!state_->getJacobian(joint_group,state_->getLinkModel(tool_link_),Vector3d::Zero(),jacb))\n {\n ROS_ERROR(\"Failed to get Jacobian for link %s\",tool_link_.c_str());\n return false;\n }\n\n \/\/ transform jacobian rotational part to tool coordinates\n jacb.bottomRows(3) = tool_current_pose.rotation().transpose()*jacb.bottomRows(3);\n\n \/\/ reduce jacobian and compute its pseudo inverse\n reduceJacobian(jacb,indices,jacb_reduced);\n calculateDampedPseudoInverse(jacb_reduced,jacb_pseudo_inv,EPSILON,LAMBDA);\n\n \/\/ computing joint change\n delta_j = (jacb_pseudo_inv*tool_twist_reduced);\n\n \/\/ updating joint values\n joint_pose += (joint_update_rates_* delta_j.array()).matrix();\n\n \/\/ updating tool pose\n state_->setJointGroupPositions(joint_group,joint_pose);\n tool_current_pose = state_->getGlobalLinkTransform(tool_link_);\n\n iteration_count++;\n }\n\n ROS_DEBUG_STREAM(\"Final tool twist \"<<tool_twist.transpose());\n\n return converged;\n}\n\n\n\n} \/* namespace filters *\/\n} \/* namespace stomp_moveit *\/\n<|endoftext|>"} {"text":"<commit_before>#include \"Tracing.h\"\n#include \"IRMutator.h\"\n#include \"IROperator.h\"\n#include \"runtime\/HalideRuntime.h\"\n\nnamespace Halide {\nnamespace Internal {\n\nint tracing_level() {\n char *trace = getenv(\"HL_TRACE\");\n return trace ? atoi(trace) : 0;\n}\n\nusing std::vector;\nusing std::map;\nusing std::string;\n\nclass InjectTracing : public IRMutator {\npublic:\n const map<string, Function> &env;\n int global_level;\n InjectTracing(const map<string, Function> &e)\n : env(e),\n global_level(tracing_level()) {}\n\nprivate:\n using IRMutator::visit;\n\n void visit(const Call *op) {\n\n \/\/ Calls inside of an address_of don't count, but we want to\n \/\/ visit the args of the inner call.\n if (op->call_type == Call::Intrinsic && op->name == Call::address_of) {\n internal_assert(op->args.size() == 1);\n const Call *c = op->args[0].as<Call>();\n const Load *l = op->args[0].as<Load>();\n\n internal_assert(c || l);\n\n std::vector<Expr> args;\n if (c) {\n args = c->args;\n } else {\n args.push_back(l->index);\n }\n\n bool unchanged = true;\n vector<Expr> new_args(args.size());\n for (size_t i = 0; i < args.size(); i++) {\n new_args[i] = mutate(args[i]);\n unchanged = unchanged && (new_args[i].same_as(args[i]));\n }\n\n if (unchanged) {\n expr = op;\n return;\n } else {\n Expr inner;\n if (c) {\n inner = Call::make(c->type, c->name, new_args, c->call_type,\n c->func, c->value_index, c->image, c->param);\n } else {\n Expr inner = Load::make(l->type, l->name, new_args[0], l->image, l->param);\n }\n expr = Call::make(Handle(), Call::address_of, {inner}, Call::Intrinsic);\n return;\n }\n }\n\n\n\n IRMutator::visit(op);\n op = expr.as<Call>();\n internal_assert(op);\n\n bool trace_it = false;\n Expr trace_parent;\n if (op->call_type == Call::Halide) {\n Function f = op->func;\n bool inlined = f.schedule().compute_level().is_inline();\n trace_it = f.is_tracing_loads() || (global_level > 2 && !inlined);\n trace_parent = Variable::make(Int(32), op->name + \".trace_id\");\n } else if (op->call_type == Call::Image) {\n trace_it = global_level > 2;\n trace_parent = -1;\n }\n\n if (trace_it) {\n \/\/ Wrap the load in a call to trace_load\n vector<Expr> args;\n args.push_back(op->name);\n args.push_back(halide_trace_load);\n args.push_back(trace_parent);\n args.push_back(op->value_index);\n args.push_back(op);\n args.insert(args.end(), op->args.begin(), op->args.end());\n\n expr = Call::make(op->type, Call::trace_expr, args, Call::Intrinsic);\n }\n\n }\n\n void visit(const Provide *op) {\n IRMutator::visit(op);\n op = stmt.as<Provide>();\n internal_assert(op);\n\n map<string, Function>::const_iterator iter = env.find(op->name);\n if (iter == env.end()) return;\n Function f = iter->second;\n bool inlined = f.schedule().compute_level().is_inline();\n\n if (f.is_tracing_stores() || (global_level > 1 && !inlined)) {\n \/\/ Wrap each expr in a tracing call\n\n const vector<Expr> &values = op->values;\n vector<Expr> traces(op->values.size());\n\n for (size_t i = 0; i < values.size(); i++) {\n vector<Expr> args;\n args.push_back(f.name());\n args.push_back(halide_trace_store);\n args.push_back(Variable::make(Int(32), op->name + \".trace_id\"));\n args.push_back((int)i);\n args.push_back(values[i]);\n args.insert(args.end(), op->args.begin(), op->args.end());\n traces[i] = Call::make(values[i].type(), Call::trace_expr, args, Call::Intrinsic);\n }\n\n stmt = Provide::make(op->name, traces, op->args);\n }\n }\n\n void visit(const Realize *op) {\n IRMutator::visit(op);\n op = stmt.as<Realize>();\n internal_assert(op);\n\n map<string, Function>::const_iterator iter = env.find(op->name);\n if (iter == env.end()) return;\n Function f = iter->second;\n if (f.is_tracing_realizations() || global_level > 0) {\n\n \/\/ Throw a tracing call before and after the realize body\n vector<Expr> args;\n args.push_back(op->name);\n args.push_back(halide_trace_begin_realization); \/\/ event type for begin realization\n args.push_back(0); \/\/ realization id\n args.push_back(0); \/\/ value index\n args.push_back(0); \/\/ value\n\n for (size_t i = 0; i < op->bounds.size(); i++) {\n args.push_back(op->bounds[i].min);\n args.push_back(op->bounds[i].extent);\n }\n\n \/\/ Begin realization returns a unique token to pass to further trace calls affecting this buffer.\n\n Expr call_before = Call::make(Int(32), Call::trace, args, Call::Intrinsic);\n args[1] = halide_trace_end_realization;\n args[2] = Variable::make(Int(32), op->name + \".trace_id\");\n Expr call_after = Call::make(Int(32), Call::trace, args, Call::Intrinsic);\n Stmt new_body = op->body;\n new_body = Block::make(new_body, Evaluate::make(call_after));\n new_body = LetStmt::make(op->name + \".trace_id\", call_before, new_body);\n stmt = Realize::make(op->name, op->types, op->bounds, op->condition, new_body);\n } else if (f.is_tracing_stores() || f.is_tracing_loads()) {\n \/\/ We need a trace id defined to pass to the loads and stores\n Stmt new_body = op->body;\n new_body = LetStmt::make(op->name + \".trace_id\", 0, new_body);\n stmt = Realize::make(op->name, op->types, op->bounds, op->condition, new_body);\n }\n\n\n }\n\n void visit(const ProducerConsumer *op) {\n IRMutator::visit(op);\n op = stmt.as<ProducerConsumer>();\n internal_assert(op);\n map<string, Function>::const_iterator iter = env.find(op->name);\n if (iter == env.end()) return;\n Function f = iter->second;\n if (f.is_tracing_realizations() || global_level > 0) {\n \/\/ Throw a tracing call around each pipeline event\n vector<Expr> args;\n args.push_back(op->name);\n args.push_back(0);\n args.push_back(Variable::make(Int(32), op->name + \".trace_id\"));\n args.push_back(0); \/\/ value index\n args.push_back(0); \/\/ value\n\n \/\/ Use the size of the pure step\n\n for (int i = 0; i < f.dimensions(); i++) {\n Expr min = Variable::make(Int(32), f.name() + \".s0.\" + f.args()[i] + \".min\");\n Expr max = Variable::make(Int(32), f.name() + \".s0.\" + f.args()[i] + \".max\");\n Expr extent = (max + 1) - min;\n args.push_back(min);\n args.push_back(extent);\n }\n\n Expr call;\n Stmt new_update;\n if (op->update.defined()) {\n args[1] = halide_trace_update;\n call = Call::make(Int(32), Call::trace, args, Call::Intrinsic);\n new_update = Block::make(Evaluate::make(call), op->update);\n }\n\n args[1] = halide_trace_consume;\n call = Call::make(Int(32), Call::trace, args, Call::Intrinsic);\n Stmt new_consume = Block::make(Evaluate::make(call), op->consume);\n\n args[1] = halide_trace_end_consume;\n call = Call::make(Int(32), Call::trace, args, Call::Intrinsic);\n new_consume = Block::make(new_consume, Evaluate::make(call));\n\n stmt = ProducerConsumer::make(op->name, op->produce, new_update, new_consume);\n\n args[1] = halide_trace_produce;\n call = Call::make(Int(32), Call::trace, args, Call::Intrinsic);\n stmt = LetStmt::make(f.name() + \".trace_id\", call, stmt);\n }\n\n }\n};\n\nclass RemoveRealizeOverOutput : public IRMutator {\n using IRMutator::visit;\n const vector<Function> &outputs;\n\n void visit(const Realize *op) {\n for (Function f : outputs) {\n if (op->name == f.name()) {\n stmt = mutate(op->body);\n return;\n }\n }\n IRMutator::visit(op);\n }\n\npublic:\n RemoveRealizeOverOutput(const vector<Function> &o) : outputs(o) {}\n};\n\nStmt inject_tracing(Stmt s, const map<string, Function> &env, const vector<Function> &outputs) {\n Stmt original = s;\n InjectTracing tracing(env);\n\n \/\/ Add a dummy realize block for the output buffers\n for (Function output : outputs) {\n Region output_region;\n Parameter output_buf = output.output_buffers()[0];\n internal_assert(output_buf.is_buffer());\n for (int i = 0; i < output.dimensions(); i++) {\n string d = std::to_string(i);\n Expr min = Variable::make(Int(32), output_buf.name() + \".min.\" + d);\n Expr extent = Variable::make(Int(32), output_buf.name() + \".extent.\" + d);\n output_region.push_back(Range(min, extent));\n }\n s = Realize::make(output.name(), output.output_types(), output_region, const_true(), s);\n }\n\n \/\/ Inject tracing calls\n s = tracing.mutate(s);\n\n \/\/ Strip off the dummy realize blocks\n s = RemoveRealizeOverOutput(outputs).mutate(s);\n\n \/\/ Unless tracing was a no-op, add a call to shut down the trace\n \/\/ (which flushes the output stream)\n if (!s.same_as(original)) {\n Expr flush = Call::make(Int(32), \"halide_shutdown_trace\", vector<Expr>(), Call::Extern);\n s = Block::make(s, Evaluate::make(flush));\n }\n return s;\n}\n\n}\n}\n<commit_msg>Trace inlined reductions too<commit_after>#include \"Tracing.h\"\n#include \"IRMutator.h\"\n#include \"IROperator.h\"\n#include \"runtime\/HalideRuntime.h\"\n\nnamespace Halide {\nnamespace Internal {\n\nint tracing_level() {\n char *trace = getenv(\"HL_TRACE\");\n return trace ? atoi(trace) : 0;\n}\n\nusing std::vector;\nusing std::map;\nusing std::string;\n\nclass InjectTracing : public IRMutator {\npublic:\n const map<string, Function> &env;\n int global_level;\n InjectTracing(const map<string, Function> &e)\n : env(e),\n global_level(tracing_level()) {}\n\nprivate:\n using IRMutator::visit;\n\n void visit(const Call *op) {\n\n \/\/ Calls inside of an address_of don't count, but we want to\n \/\/ visit the args of the inner call.\n if (op->call_type == Call::Intrinsic && op->name == Call::address_of) {\n internal_assert(op->args.size() == 1);\n const Call *c = op->args[0].as<Call>();\n const Load *l = op->args[0].as<Load>();\n\n internal_assert(c || l);\n\n std::vector<Expr> args;\n if (c) {\n args = c->args;\n } else {\n args.push_back(l->index);\n }\n\n bool unchanged = true;\n vector<Expr> new_args(args.size());\n for (size_t i = 0; i < args.size(); i++) {\n new_args[i] = mutate(args[i]);\n unchanged = unchanged && (new_args[i].same_as(args[i]));\n }\n\n if (unchanged) {\n expr = op;\n return;\n } else {\n Expr inner;\n if (c) {\n inner = Call::make(c->type, c->name, new_args, c->call_type,\n c->func, c->value_index, c->image, c->param);\n } else {\n Expr inner = Load::make(l->type, l->name, new_args[0], l->image, l->param);\n }\n expr = Call::make(Handle(), Call::address_of, {inner}, Call::Intrinsic);\n return;\n }\n }\n\n\n\n IRMutator::visit(op);\n op = expr.as<Call>();\n internal_assert(op);\n\n bool trace_it = false;\n Expr trace_parent;\n if (op->call_type == Call::Halide) {\n Function f = op->func;\n bool inlined = f.schedule().compute_level().is_inline();\n if (f.has_update_definition()) inlined = false;\n trace_it = f.is_tracing_loads() || (global_level > 2 && !inlined);\n trace_parent = Variable::make(Int(32), op->name + \".trace_id\");\n } else if (op->call_type == Call::Image) {\n trace_it = global_level > 2;\n trace_parent = -1;\n }\n\n if (trace_it) {\n \/\/ Wrap the load in a call to trace_load\n vector<Expr> args;\n args.push_back(op->name);\n args.push_back(halide_trace_load);\n args.push_back(trace_parent);\n args.push_back(op->value_index);\n args.push_back(op);\n args.insert(args.end(), op->args.begin(), op->args.end());\n\n expr = Call::make(op->type, Call::trace_expr, args, Call::Intrinsic);\n }\n\n }\n\n void visit(const Provide *op) {\n IRMutator::visit(op);\n op = stmt.as<Provide>();\n internal_assert(op);\n\n map<string, Function>::const_iterator iter = env.find(op->name);\n if (iter == env.end()) return;\n Function f = iter->second;\n bool inlined = f.schedule().compute_level().is_inline();\n if (f.has_update_definition()) inlined = false;\n\n if (f.is_tracing_stores() || (global_level > 1 && !inlined)) {\n \/\/ Wrap each expr in a tracing call\n\n const vector<Expr> &values = op->values;\n vector<Expr> traces(op->values.size());\n\n for (size_t i = 0; i < values.size(); i++) {\n vector<Expr> args;\n args.push_back(f.name());\n args.push_back(halide_trace_store);\n args.push_back(Variable::make(Int(32), op->name + \".trace_id\"));\n args.push_back((int)i);\n args.push_back(values[i]);\n args.insert(args.end(), op->args.begin(), op->args.end());\n traces[i] = Call::make(values[i].type(), Call::trace_expr, args, Call::Intrinsic);\n }\n\n stmt = Provide::make(op->name, traces, op->args);\n }\n }\n\n void visit(const Realize *op) {\n IRMutator::visit(op);\n op = stmt.as<Realize>();\n internal_assert(op);\n\n map<string, Function>::const_iterator iter = env.find(op->name);\n if (iter == env.end()) return;\n Function f = iter->second;\n if (f.is_tracing_realizations() || global_level > 0) {\n\n \/\/ Throw a tracing call before and after the realize body\n vector<Expr> args;\n args.push_back(op->name);\n args.push_back(halide_trace_begin_realization); \/\/ event type for begin realization\n args.push_back(0); \/\/ realization id\n args.push_back(0); \/\/ value index\n args.push_back(0); \/\/ value\n\n for (size_t i = 0; i < op->bounds.size(); i++) {\n args.push_back(op->bounds[i].min);\n args.push_back(op->bounds[i].extent);\n }\n\n \/\/ Begin realization returns a unique token to pass to further trace calls affecting this buffer.\n\n Expr call_before = Call::make(Int(32), Call::trace, args, Call::Intrinsic);\n args[1] = halide_trace_end_realization;\n args[2] = Variable::make(Int(32), op->name + \".trace_id\");\n Expr call_after = Call::make(Int(32), Call::trace, args, Call::Intrinsic);\n Stmt new_body = op->body;\n new_body = Block::make(new_body, Evaluate::make(call_after));\n new_body = LetStmt::make(op->name + \".trace_id\", call_before, new_body);\n stmt = Realize::make(op->name, op->types, op->bounds, op->condition, new_body);\n } else if (f.is_tracing_stores() || f.is_tracing_loads()) {\n \/\/ We need a trace id defined to pass to the loads and stores\n Stmt new_body = op->body;\n new_body = LetStmt::make(op->name + \".trace_id\", 0, new_body);\n stmt = Realize::make(op->name, op->types, op->bounds, op->condition, new_body);\n }\n\n\n }\n\n void visit(const ProducerConsumer *op) {\n IRMutator::visit(op);\n op = stmt.as<ProducerConsumer>();\n internal_assert(op);\n map<string, Function>::const_iterator iter = env.find(op->name);\n if (iter == env.end()) return;\n Function f = iter->second;\n if (f.is_tracing_realizations() || global_level > 0) {\n \/\/ Throw a tracing call around each pipeline event\n vector<Expr> args;\n args.push_back(op->name);\n args.push_back(0);\n args.push_back(Variable::make(Int(32), op->name + \".trace_id\"));\n args.push_back(0); \/\/ value index\n args.push_back(0); \/\/ value\n\n \/\/ Use the size of the pure step\n\n for (int i = 0; i < f.dimensions(); i++) {\n Expr min = Variable::make(Int(32), f.name() + \".s0.\" + f.args()[i] + \".min\");\n Expr max = Variable::make(Int(32), f.name() + \".s0.\" + f.args()[i] + \".max\");\n Expr extent = (max + 1) - min;\n args.push_back(min);\n args.push_back(extent);\n }\n\n Expr call;\n Stmt new_update;\n if (op->update.defined()) {\n args[1] = halide_trace_update;\n call = Call::make(Int(32), Call::trace, args, Call::Intrinsic);\n new_update = Block::make(Evaluate::make(call), op->update);\n }\n\n args[1] = halide_trace_consume;\n call = Call::make(Int(32), Call::trace, args, Call::Intrinsic);\n Stmt new_consume = Block::make(Evaluate::make(call), op->consume);\n\n args[1] = halide_trace_end_consume;\n call = Call::make(Int(32), Call::trace, args, Call::Intrinsic);\n new_consume = Block::make(new_consume, Evaluate::make(call));\n\n stmt = ProducerConsumer::make(op->name, op->produce, new_update, new_consume);\n\n args[1] = halide_trace_produce;\n call = Call::make(Int(32), Call::trace, args, Call::Intrinsic);\n stmt = LetStmt::make(f.name() + \".trace_id\", call, stmt);\n }\n\n }\n};\n\nclass RemoveRealizeOverOutput : public IRMutator {\n using IRMutator::visit;\n const vector<Function> &outputs;\n\n void visit(const Realize *op) {\n for (Function f : outputs) {\n if (op->name == f.name()) {\n stmt = mutate(op->body);\n return;\n }\n }\n IRMutator::visit(op);\n }\n\npublic:\n RemoveRealizeOverOutput(const vector<Function> &o) : outputs(o) {}\n};\n\nStmt inject_tracing(Stmt s, const map<string, Function> &env, const vector<Function> &outputs) {\n Stmt original = s;\n InjectTracing tracing(env);\n\n \/\/ Add a dummy realize block for the output buffers\n for (Function output : outputs) {\n Region output_region;\n Parameter output_buf = output.output_buffers()[0];\n internal_assert(output_buf.is_buffer());\n for (int i = 0; i < output.dimensions(); i++) {\n string d = std::to_string(i);\n Expr min = Variable::make(Int(32), output_buf.name() + \".min.\" + d);\n Expr extent = Variable::make(Int(32), output_buf.name() + \".extent.\" + d);\n output_region.push_back(Range(min, extent));\n }\n s = Realize::make(output.name(), output.output_types(), output_region, const_true(), s);\n }\n\n \/\/ Inject tracing calls\n s = tracing.mutate(s);\n\n \/\/ Strip off the dummy realize blocks\n s = RemoveRealizeOverOutput(outputs).mutate(s);\n\n \/\/ Unless tracing was a no-op, add a call to shut down the trace\n \/\/ (which flushes the output stream)\n if (!s.same_as(original)) {\n Expr flush = Call::make(Int(32), \"halide_shutdown_trace\", vector<Expr>(), Call::Extern);\n s = Block::make(s, Evaluate::make(flush));\n }\n return s;\n}\n\n}\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"Version.h\"\n\n#include \"Hash.h\"\n\n#include <ostream>\n#include <sstream>\n#include <iostream>\n#include <string>\n#include <regex>\n\nusing namespace Arbiter;\n\nsize_t std::hash<ArbiterSemanticVersion>::operator() (const ArbiterSemanticVersion &version) const\n{\n return hashOf(version._major)\n ^ hashOf(version._minor)\n ^ hashOf(version._patch)\n ^ hashOf(version._prereleaseVersion)\n ^ hashOf(version._buildMetadata);\n}\n\nsize_t std::hash<ArbiterSelectedVersion>::operator() (const ArbiterSelectedVersion &version) const\n{\n return hashOf(version._semanticVersion);\n}\n\nOptional<ArbiterSemanticVersion> ArbiterSemanticVersion::fromString (const std::string &versionString)\n{\n \/\/ Versions and identifiers cannot have a leading zero.\n #define VERSION \"(0|[1-9][0-9]*)\"\n #define IDENTIFIER \"(?:0|[1-9A-Za-z-][0-9A-Za-z-]*)\"\n #define DOT_SEPARATED_IDENTIFIER \"(\" IDENTIFIER \"(?:\\\\.\" IDENTIFIER \")*)\"\n\n std::regex pattern {\n VERSION \"\\\\.\" VERSION \"\\\\.\" VERSION\n \/\/ prerelease begins with a hyphen followed by a dot separated identifier\n \"(?:\" \"-\" DOT_SEPARATED_IDENTIFIER \")?\"\n \/\/ metadata begins with a plus sign followed by a dot separated identifier\n \"(?:\" \"\\\\+\" DOT_SEPARATED_IDENTIFIER \")?\"\n };\n\n #undef DOT_SEPARATED_IDENTIFIER\n #undef IDENTIFIER\n #undef VERSION\n\n std::smatch match;\n if (!std::regex_match(versionString, match, pattern)) {\n return Optional<ArbiterSemanticVersion>();\n }\n\n unsigned major = stoi(match.str(1));\n unsigned minor = stoi(match.str(2));\n unsigned patch = stoi(match.str(3));\n\n Optional<std::string> prereleaseVersion;\n Optional<std::string> buildMetadata;\n\n if (match.length(4) > 0) {\n prereleaseVersion = Optional<std::string>(match.str(4));\n }\n if (match.length(5) > 0) {\n buildMetadata = Optional<std::string>(match.str(5));\n }\n\n return ArbiterSemanticVersion(major, minor, patch, prereleaseVersion, buildMetadata);\n}\n\nbool ArbiterSemanticVersion::operator< (const ArbiterSemanticVersion &other) const noexcept\n{\n if (_major < other._major) {\n return true;\n } else if (_major > other._major) {\n return false;\n }\n\n if (_minor < other._minor) {\n return true;\n } else if (_minor > other._minor) {\n return false;\n }\n\n if (_patch < other._patch) {\n return true;\n } else if (_patch > other._patch) {\n return false;\n }\n\n if (_prereleaseVersion) {\n if (!other._prereleaseVersion) {\n return true;\n }\n\n \/\/ FIXME: This should compare numbers naturally, not lexically\n return _prereleaseVersion.value() < other._prereleaseVersion.value();\n }\n\n \/\/ Build metadata does not participate in precedence.\n return false;\n}\n\nstd::ostream &operator<< (std::ostream &os, const ArbiterSemanticVersion &version)\n{\n os << version._major << '.' << version._minor << '.' << version._patch;\n\n if (version._prereleaseVersion) {\n os << '-' << version._prereleaseVersion.value();\n }\n\n if (version._buildMetadata) {\n os << '+' << version._buildMetadata.value();\n }\n\n return os;\n}\n\nstd::ostream &operator<< (std::ostream &os, const ArbiterSelectedVersion &version)\n{\n return os << version._semanticVersion << \" (\" << version._metadata << \")\";\n}\n\nstd::ostream &operator<< (std::ostream &os, const ArbiterSelectedVersionList &versionList)\n{\n os << \"Version list:\";\n\n for (const auto &version : versionList._versions) {\n os << \"\\n\" << version;\n }\n\n return os;\n}\n\nArbiterSemanticVersion *ArbiterCreateSemanticVersion (unsigned major, unsigned minor, unsigned patch, const char *prereleaseVersion, const char *buildMetadata)\n{\n return new ArbiterSemanticVersion(\n major,\n minor,\n patch,\n (prereleaseVersion ? Optional<std::string>(prereleaseVersion) : Optional<std::string>()),\n (buildMetadata ? Optional<std::string>(buildMetadata) : Optional<std::string>())\n );\n}\n\nArbiterSemanticVersion *ArbiterCreateSemanticVersionFromString (const char *string)\n{\n auto version = ArbiterSemanticVersion::fromString(string);\n if (version) {\n return new ArbiterSemanticVersion(std::move(version.value()));\n } else {\n return nullptr;\n }\n}\n\nvoid ArbiterFreeSemanticVersion (ArbiterSemanticVersion *version)\n{\n delete version;\n}\n\nunsigned ArbiterGetMajorVersion (const ArbiterSemanticVersion *version)\n{\n return version->_major;\n}\n\nunsigned ArbiterGetMinorVersion (const ArbiterSemanticVersion *version)\n{\n return version->_minor;\n}\n\nunsigned ArbiterGetPatchVersion (const ArbiterSemanticVersion *version)\n{\n return version->_patch;\n}\n\nconst char *ArbiterGetPrereleaseVersion (const ArbiterSemanticVersion *version)\n{\n if (version->_prereleaseVersion) {\n return version->_prereleaseVersion->c_str();\n } else {\n return nullptr;\n }\n}\n\nconst char *ArbiterGetBuildMetadata (const ArbiterSemanticVersion *version)\n{\n if (version->_buildMetadata) {\n return version->_buildMetadata->c_str();\n } else {\n return nullptr;\n }\n}\n\nbool ArbiterEqualVersions (const ArbiterSemanticVersion *lhs, const ArbiterSemanticVersion *rhs)\n{\n return *lhs == *rhs;\n}\n\nint ArbiterCompareVersionOrdering (const ArbiterSemanticVersion *lhs, const ArbiterSemanticVersion *rhs)\n{\n if (*lhs < *rhs) {\n return -1;\n } else if (*lhs > *rhs) {\n return 1;\n } else {\n return 0;\n }\n}\n\nArbiterSelectedVersion *ArbiterCreateSelectedVersion (const ArbiterSemanticVersion *semanticVersion, ArbiterUserValue metadata)\n{\n return new ArbiterSelectedVersion(*semanticVersion, ArbiterSelectedVersion::Metadata(metadata));\n}\n\nconst ArbiterSemanticVersion *ArbiterSelectedVersionSemanticVersion (const ArbiterSelectedVersion *version)\n{\n return &version->_semanticVersion;\n}\n\nconst void *ArbiterSelectedVersionMetadata (const ArbiterSelectedVersion *version)\n{\n return version->_metadata.data();\n}\n\nbool ArbiterEqualSelectedVersions (const ArbiterSelectedVersion *lhs, const ArbiterSelectedVersion *rhs)\n{\n return *lhs == *rhs;\n}\n\nvoid ArbiterFreeSelectedVersion (ArbiterSelectedVersion *version)\n{\n delete version;\n}\n<commit_msg>Less verbose pattern name<commit_after>#include \"Version.h\"\n\n#include \"Hash.h\"\n\n#include <ostream>\n#include <sstream>\n#include <iostream>\n#include <string>\n#include <regex>\n\nusing namespace Arbiter;\n\nsize_t std::hash<ArbiterSemanticVersion>::operator() (const ArbiterSemanticVersion &version) const\n{\n return hashOf(version._major)\n ^ hashOf(version._minor)\n ^ hashOf(version._patch)\n ^ hashOf(version._prereleaseVersion)\n ^ hashOf(version._buildMetadata);\n}\n\nsize_t std::hash<ArbiterSelectedVersion>::operator() (const ArbiterSelectedVersion &version) const\n{\n return hashOf(version._semanticVersion);\n}\n\nOptional<ArbiterSemanticVersion> ArbiterSemanticVersion::fromString (const std::string &versionString)\n{\n \/\/ Versions and identifiers cannot have a leading zero.\n #define VERSION \"(0|[1-9][0-9]*)\"\n #define IDENTIFIER \"(?:0|[1-9A-Za-z-][0-9A-Za-z-]*)\"\n #define DOTTED_IDENTIFIER \"(\" IDENTIFIER \"(?:\\\\.\" IDENTIFIER \")*)\"\n\n std::regex pattern {\n VERSION \"\\\\.\" VERSION \"\\\\.\" VERSION\n \/\/ prerelease begins with a hyphen followed by a dot separated identifier\n \"(?:\" \"-\" DOTTED_IDENTIFIER \")?\"\n \/\/ metadata begins with a plus sign followed by a dot separated identifier\n \"(?:\" \"\\\\+\" DOTTED_IDENTIFIER \")?\"\n };\n\n #undef DOTTED_IDENTIFIER\n #undef IDENTIFIER\n #undef VERSION\n\n std::smatch match;\n if (!std::regex_match(versionString, match, pattern)) {\n return Optional<ArbiterSemanticVersion>();\n }\n\n unsigned major = stoi(match.str(1));\n unsigned minor = stoi(match.str(2));\n unsigned patch = stoi(match.str(3));\n\n Optional<std::string> prereleaseVersion;\n Optional<std::string> buildMetadata;\n\n if (match.length(4) > 0) {\n prereleaseVersion = Optional<std::string>(match.str(4));\n }\n if (match.length(5) > 0) {\n buildMetadata = Optional<std::string>(match.str(5));\n }\n\n return ArbiterSemanticVersion(major, minor, patch, prereleaseVersion, buildMetadata);\n}\n\nbool ArbiterSemanticVersion::operator< (const ArbiterSemanticVersion &other) const noexcept\n{\n if (_major < other._major) {\n return true;\n } else if (_major > other._major) {\n return false;\n }\n\n if (_minor < other._minor) {\n return true;\n } else if (_minor > other._minor) {\n return false;\n }\n\n if (_patch < other._patch) {\n return true;\n } else if (_patch > other._patch) {\n return false;\n }\n\n if (_prereleaseVersion) {\n if (!other._prereleaseVersion) {\n return true;\n }\n\n \/\/ FIXME: This should compare numbers naturally, not lexically\n return _prereleaseVersion.value() < other._prereleaseVersion.value();\n }\n\n \/\/ Build metadata does not participate in precedence.\n return false;\n}\n\nstd::ostream &operator<< (std::ostream &os, const ArbiterSemanticVersion &version)\n{\n os << version._major << '.' << version._minor << '.' << version._patch;\n\n if (version._prereleaseVersion) {\n os << '-' << version._prereleaseVersion.value();\n }\n\n if (version._buildMetadata) {\n os << '+' << version._buildMetadata.value();\n }\n\n return os;\n}\n\nstd::ostream &operator<< (std::ostream &os, const ArbiterSelectedVersion &version)\n{\n return os << version._semanticVersion << \" (\" << version._metadata << \")\";\n}\n\nstd::ostream &operator<< (std::ostream &os, const ArbiterSelectedVersionList &versionList)\n{\n os << \"Version list:\";\n\n for (const auto &version : versionList._versions) {\n os << \"\\n\" << version;\n }\n\n return os;\n}\n\nArbiterSemanticVersion *ArbiterCreateSemanticVersion (unsigned major, unsigned minor, unsigned patch, const char *prereleaseVersion, const char *buildMetadata)\n{\n return new ArbiterSemanticVersion(\n major,\n minor,\n patch,\n (prereleaseVersion ? Optional<std::string>(prereleaseVersion) : Optional<std::string>()),\n (buildMetadata ? Optional<std::string>(buildMetadata) : Optional<std::string>())\n );\n}\n\nArbiterSemanticVersion *ArbiterCreateSemanticVersionFromString (const char *string)\n{\n auto version = ArbiterSemanticVersion::fromString(string);\n if (version) {\n return new ArbiterSemanticVersion(std::move(version.value()));\n } else {\n return nullptr;\n }\n}\n\nvoid ArbiterFreeSemanticVersion (ArbiterSemanticVersion *version)\n{\n delete version;\n}\n\nunsigned ArbiterGetMajorVersion (const ArbiterSemanticVersion *version)\n{\n return version->_major;\n}\n\nunsigned ArbiterGetMinorVersion (const ArbiterSemanticVersion *version)\n{\n return version->_minor;\n}\n\nunsigned ArbiterGetPatchVersion (const ArbiterSemanticVersion *version)\n{\n return version->_patch;\n}\n\nconst char *ArbiterGetPrereleaseVersion (const ArbiterSemanticVersion *version)\n{\n if (version->_prereleaseVersion) {\n return version->_prereleaseVersion->c_str();\n } else {\n return nullptr;\n }\n}\n\nconst char *ArbiterGetBuildMetadata (const ArbiterSemanticVersion *version)\n{\n if (version->_buildMetadata) {\n return version->_buildMetadata->c_str();\n } else {\n return nullptr;\n }\n}\n\nbool ArbiterEqualVersions (const ArbiterSemanticVersion *lhs, const ArbiterSemanticVersion *rhs)\n{\n return *lhs == *rhs;\n}\n\nint ArbiterCompareVersionOrdering (const ArbiterSemanticVersion *lhs, const ArbiterSemanticVersion *rhs)\n{\n if (*lhs < *rhs) {\n return -1;\n } else if (*lhs > *rhs) {\n return 1;\n } else {\n return 0;\n }\n}\n\nArbiterSelectedVersion *ArbiterCreateSelectedVersion (const ArbiterSemanticVersion *semanticVersion, ArbiterUserValue metadata)\n{\n return new ArbiterSelectedVersion(*semanticVersion, ArbiterSelectedVersion::Metadata(metadata));\n}\n\nconst ArbiterSemanticVersion *ArbiterSelectedVersionSemanticVersion (const ArbiterSelectedVersion *version)\n{\n return &version->_semanticVersion;\n}\n\nconst void *ArbiterSelectedVersionMetadata (const ArbiterSelectedVersion *version)\n{\n return version->_metadata.data();\n}\n\nbool ArbiterEqualSelectedVersions (const ArbiterSelectedVersion *lhs, const ArbiterSelectedVersion *rhs)\n{\n return *lhs == *rhs;\n}\n\nvoid ArbiterFreeSelectedVersion (ArbiterSelectedVersion *version)\n{\n delete version;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"ascii_in.h\"\n\n#include <iostream>\n\nnamespace redsea {\n\nAsciiBits::AsciiBits() : is_eof_(false) {\n\n}\n\nAsciiBits::~AsciiBits() {\n\n}\n\nint AsciiBits::getNextBit() {\n int result = 0;\n while (result != '0' && result != '1' && result != EOF)\n result = getchar();\n\n if (result == EOF) {\n is_eof_ = true;\n return 0;\n }\n\n return (result == '1');\n\n}\n\nbool AsciiBits::isEOF() const {\n return is_eof_;\n}\n\nstd::vector<uint16_t> getNextGroupRSpy() {\n std::vector<uint16_t> result;\n\n bool finished = false;\n\n while (! (finished || std::cin.eof())) {\n std::string line;\n std::getline(std::cin, line);\n if (line.length() < 16)\n continue;\n\n for (int nblok=0; nblok<4; nblok++) {\n uint16_t bval=0;\n int nyb=0;\n\n while (nyb < 4) {\n\n if (line.length() < 1) {\n finished = true;\n break;\n }\n\n std::string single = line.substr(0,1);\n\n if (single.compare(\" \") != 0) {\n try {\n int nval = std::stoi(std::string(single), nullptr, 16);\n bval = (bval << 4) + nval;\n nyb++;\n } catch (std::invalid_argument) {\n finished = true;\n break;\n }\n }\n line = line.substr(1);\n }\n\n if (finished)\n break;\n\n result.push_back(bval);\n\n if (nblok==3)\n finished = true;\n }\n }\n\n return result;\n\n}\n\n\n} \/\/ namespace redsea\n<commit_msg>fix compile error on RasPi<commit_after>#include \"ascii_in.h\"\n\n#include <iostream>\n#include <stdexcept>\n\nnamespace redsea {\n\nAsciiBits::AsciiBits() : is_eof_(false) {\n\n}\n\nAsciiBits::~AsciiBits() {\n\n}\n\nint AsciiBits::getNextBit() {\n int result = 0;\n while (result != '0' && result != '1' && result != EOF)\n result = getchar();\n\n if (result == EOF) {\n is_eof_ = true;\n return 0;\n }\n\n return (result == '1');\n\n}\n\nbool AsciiBits::isEOF() const {\n return is_eof_;\n}\n\nstd::vector<uint16_t> getNextGroupRSpy() {\n std::vector<uint16_t> result;\n\n bool finished = false;\n\n while (! (finished || std::cin.eof())) {\n std::string line;\n std::getline(std::cin, line);\n if (line.length() < 16)\n continue;\n\n for (int nblok=0; nblok<4; nblok++) {\n uint16_t bval=0;\n int nyb=0;\n\n while (nyb < 4) {\n\n if (line.length() < 1) {\n finished = true;\n break;\n }\n\n std::string single = line.substr(0,1);\n\n if (single.compare(\" \") != 0) {\n try {\n int nval = std::stoi(std::string(single), nullptr, 16);\n bval = (bval << 4) + nval;\n nyb++;\n } catch (std::invalid_argument) {\n finished = true;\n break;\n }\n }\n line = line.substr(1);\n }\n\n if (finished)\n break;\n\n result.push_back(bval);\n\n if (nblok==3)\n finished = true;\n }\n }\n\n return result;\n\n}\n\n\n} \/\/ namespace redsea\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2010, Camilo Aguilar. Cloudescape, LLC.\n#include \"bindings.h\"\n\n\/* size of the event structure, not counting name *\/\n#define EVENT_SIZE (sizeof (struct inotify_event))\n\n\/* reasonable guess as to size of 1024 events *\/\n#define BUF_LEN (1024 * (EVENT_SIZE + 16))\n\nnamespace NodeInotify {\n static Persistent<String> path_sym;\n static Persistent<String> watch_for_sym;\n static Persistent<String> callback_sym;\n static Persistent<String> persistent_sym;\n static Persistent<String> watch_sym;\n static Persistent<String> mask_sym;\n static Persistent<String> cookie_sym;\n static Persistent<String> name_sym;\n\n void Inotify::Initialize(Handle<Object> target) {\n Local<FunctionTemplate> t = FunctionTemplate::New(Inotify::New);\n\n t->Inherit(EventEmitter::constructor_template);\n t->InstanceTemplate()->SetInternalFieldCount(1);\n\n NODE_SET_PROTOTYPE_METHOD(t, \"addWatch\",\n Inotify::AddWatch);\n NODE_SET_PROTOTYPE_METHOD(t, \"removeWatch\",\n Inotify::RemoveWatch);\n NODE_SET_PROTOTYPE_METHOD(t, \"close\",\n Inotify::Close);\n\n \/\/Constants initialization\n NODE_DEFINE_CONSTANT(t, IN_ACCESS); \/\/File was accessed (read)\n NODE_DEFINE_CONSTANT(t, IN_ATTRIB); \/\/Metadata changed, e.g., permissions, timestamps,\n \/\/extended attributes, link count (since Linux 2.6.25),\n \/\/UID, GID, etc.\n NODE_DEFINE_CONSTANT(t, IN_CLOSE_WRITE); \/\/File opened for writing was closed\n NODE_DEFINE_CONSTANT(t, IN_CLOSE_NOWRITE); \/\/File not opened for writing was closed\n NODE_DEFINE_CONSTANT(t, IN_CREATE); \/\/File\/directory created in watched directory\n NODE_DEFINE_CONSTANT(t, IN_DELETE); \/\/File\/directory deleted from watched directory\n NODE_DEFINE_CONSTANT(t, IN_DELETE_SELF); \/\/Watched file\/directory was itself deleted\n NODE_DEFINE_CONSTANT(t, IN_MODIFY); \/\/File was modified\n NODE_DEFINE_CONSTANT(t, IN_MOVE_SELF); \/\/Watched file\/directory was itself moved\n NODE_DEFINE_CONSTANT(t, IN_MOVED_FROM); \/\/File moved out of watched directory\n NODE_DEFINE_CONSTANT(t, IN_MOVED_TO); \/\/File moved into watched directory\n NODE_DEFINE_CONSTANT(t, IN_OPEN); \/\/File was opened\n NODE_DEFINE_CONSTANT(t, IN_IGNORED); \/\/ Watch was removed explicitly (inotify.watch.rm) or\n \/\/automatically (file was deleted, or file system was\n \/\/unmounted)\n NODE_DEFINE_CONSTANT(t, IN_ISDIR); \/\/Subject of this event is a directory\n NODE_DEFINE_CONSTANT(t, IN_Q_OVERFLOW); \/\/Event queue overflowed (wd is -1 for this event)\n NODE_DEFINE_CONSTANT(t, IN_UNMOUNT); \/\/File system containing watched object was unmounted\n NODE_DEFINE_CONSTANT(t, IN_ALL_EVENTS);\n\n NODE_DEFINE_CONSTANT(t, IN_ONLYDIR); \/\/ Only watch the path if it is a directory.\n NODE_DEFINE_CONSTANT(t, IN_DONT_FOLLOW); \/\/ Do not follow a sym link\n NODE_DEFINE_CONSTANT(t, IN_ONESHOT); \/\/ Only send event once\n NODE_DEFINE_CONSTANT(t, IN_MASK_ADD); \/\/Add (OR) events to watch mask for this pathname if it\n \/\/already exists (instead of replacing mask).\n\n NODE_DEFINE_CONSTANT(t, IN_CLOSE); \/\/ (IN_CLOSE_WRITE | IN_CLOSE_NOWRITE) Close\n NODE_DEFINE_CONSTANT(t, IN_MOVE); \/\/ (IN_MOVED_FROM | IN_MOVED_TO) Moves\n\n path_sym = NODE_PSYMBOL(\"path\");\n watch_for_sym = NODE_PSYMBOL(\"watch_for\");\n callback_sym = NODE_PSYMBOL(\"callback\");\n persistent_sym = NODE_PSYMBOL(\"persistent\");\n\n watch_sym = NODE_PSYMBOL(\"watch\");\n mask_sym = NODE_PSYMBOL(\"mask\");\n cookie_sym = NODE_PSYMBOL(\"cookie\");\n name_sym = NODE_PSYMBOL(\"name\");\n\n Local<ObjectTemplate> object_tmpl = t->InstanceTemplate();\n object_tmpl->SetAccessor(persistent_sym, Inotify::GetPersistent);\n\n t->SetClassName(String::NewSymbol(\"Inotify\"));\n target->Set(String::NewSymbol(\"Inotify\"), t->GetFunction());\n }\n\n Inotify::Inotify() : EventEmitter() {\n ev_init(&read_watcher, Inotify::Callback);\n read_watcher.data = this; \/\/preserving my reference to use it inside Inotify::Callback\n persistent = true;\n }\n\n Inotify::Inotify(bool nonpersistent) : EventEmitter() {\n ev_init(&read_watcher, Inotify::Callback);\n read_watcher.data = this; \/\/preserving my reference to use it inside Inotify::Callback\n persistent = nonpersistent;\n }\n\n Inotify::~Inotify() {\n if(!persistent) {\n ev_ref(EV_DEFAULT_UC);\n }\n ev_io_stop(EV_DEFAULT_UC_ &read_watcher);\n assert(!ev_is_active(&read_watcher));\n assert(!ev_is_pending(&read_watcher));\n }\n\n Handle<Value> Inotify::New(const Arguments& args) {\n HandleScope scope;\n\n Inotify *inotify = NULL;\n if(args.Length() == 1 && args[0]->IsBoolean()) {\n inotify = new Inotify(args[0]->IsTrue());\n } else {\n inotify = new Inotify();\n }\n\n \tinotify->fd = inotify_init();\n\n if(inotify->fd == -1) {\n ThrowException(String::New(strerror(errno)));\n return Null();\n }\n\t\n\tint flags = fcntl(inotify->fd, F_GETFL);\n\tif(flags == -1) {\n\t flags = 0;\n\t}\n\n\tfcntl(inotify->fd, F_SETFL, flags | O_NONBLOCK);\n\n ev_io_set(&inotify->read_watcher, inotify->fd, EV_READ);\n ev_io_start(EV_DEFAULT_UC_ &inotify->read_watcher);\n\n Local<Object> obj = args.This();\n inotify->Wrap(obj);\n\n if(!inotify->persistent) {\n ev_unref(EV_DEFAULT_UC);\n }\n \/*Increment object references to avoid be GCed while\n I'm waiting for inotify events in th ev_pool.\n Also, the object is not weak anymore *\/\n inotify->Ref();\n\n return scope.Close(obj);\n }\n\n Handle<Value> Inotify::AddWatch(const Arguments& args) {\n HandleScope scope;\n uint32_t mask = 0;\n int watch_descriptor = 0;\n\n if(args.Length() < 1 || !args[0]->IsObject()) {\n return ThrowException(Exception::TypeError(\n String::New(\"You must specify an object as first argument\")));\n }\n\n Local<Object> args_ = args[0]->ToObject();\n\n if(!args_->Has(path_sym)) {\n return ThrowException(Exception::TypeError(\n String::New(\"You must specify a path to watch for events\")));\n }\n\n if(!args_->Has(callback_sym) ||\n !args_->Get(callback_sym)->IsFunction()) {\n return ThrowException(Exception::TypeError(\n String::New(\"You must specify a callback function\")));\n }\n\n if(!args_->Has(watch_for_sym)) {\n mask |= IN_ALL_EVENTS;\n } else {\n if(!args_->Get(watch_for_sym)->IsInt32()) {\n return ThrowException(Exception::TypeError(\n String::New(\"You must specify OR'ed set of events\")));\n }\n mask |= args_->Get(watch_for_sym)->Int32Value();\n if(mask == 0) {\n return ThrowException(Exception::TypeError(\n String::New(\"You must specify OR'ed set of events\")));\n }\n }\n\n String::Utf8Value path(args_->Get(path_sym));\n\n Inotify *inotify = ObjectWrap::Unwrap<Inotify>(args.This());\n\n \/* add watch *\/\n watch_descriptor = inotify_add_watch(inotify->fd, (const char *) *path, mask);\n\n Local<Integer> descriptor = Integer::New(watch_descriptor);\n\n \/\/Local<Function> callback = Local<Function>::Cast(args_->Get(callback_sym));\n inotify->handle_->Set(descriptor, args_->Get(callback_sym));\n\n return scope.Close(descriptor);\n }\n\n Handle<Value> Inotify::RemoveWatch(const Arguments& args) {\n HandleScope scope;\n uint32_t watch = 0;\n int ret = -1;\n\n if(args.Length() == 0 || !args[0]->IsInt32()) {\n return ThrowException(Exception::TypeError(\n String::New(\"You must specify a valid watcher descriptor as argument\")));\n }\n watch = args[0]->Int32Value();\n\n Inotify *inotify = ObjectWrap::Unwrap<Inotify>(args.This());\n\n ret = inotify_rm_watch(inotify->fd, watch);\n if(ret == -1) {\n ThrowException(String::New(strerror(errno)));\n return False();\n }\n\n return True();\n }\n\n Handle<Value> Inotify::Close(const Arguments& args) {\n HandleScope scope;\n int ret = -1;\n\n Inotify *inotify = ObjectWrap::Unwrap<Inotify>(args.This());\n ret = close(inotify->fd);\n\n if(ret == -1) {\n ThrowException(String::New(strerror(errno)));\n return False();\n }\n\n if(!inotify->persistent) {\n ev_ref(EV_DEFAULT_UC);\n }\n\n ev_io_stop(EV_DEFAULT_UC_ &inotify->read_watcher);\n\n \/*Eliminating reference created inside of Inotify::New.\n The object is also weak again.\n Now v8 can do its stuff and GC the object.\n *\/\n inotify->Unref();\n\n return True();\n }\n\n void Inotify::Callback(EV_P_ ev_io *watcher, int revents) {\n HandleScope scope;\n\n Inotify *inotify = static_cast<Inotify*>(watcher->data);\n assert(watcher == &inotify->read_watcher);\n\n char buffer[BUF_LEN];\n\n \/\/int length = read(inotify->fd, buffer, BUF_LEN);\n\n Local<Value> argv[1];\n TryCatch try_catch;\n\n int i = 0;\n while (i < read(inotify->fd, buffer, BUF_LEN)) {\n struct inotify_event *event;\n event = (struct inotify_event *) &buffer[i];\n\n Local<Object> obj = Object::New();\n obj->Set(watch_sym, Integer::New(event->wd));\n obj->Set(mask_sym, Integer::New(event->mask));\n obj->Set(cookie_sym, Integer::New(event->cookie));\n\n if(event->len) {\n obj->Set(name_sym, String::New(event->name));\n }\n argv[0] = obj;\n\n inotify->Ref();\n Local<Value> callback_ = inotify->handle_->Get(Integer::New(event->wd));\n Local<Function> callback = Local<Function>::Cast(callback_);\n\n callback->Call(inotify->handle_, 1, argv);\n inotify->Unref();\n\n if(event->mask & IN_IGNORED) {\n \/\/deleting callback because the watch was removed\n Local<Value> wd = Integer::New(event->wd);\n inotify->handle_->Delete(wd->ToString());\n }\n\n if (try_catch.HasCaught()) {\n FatalException(try_catch);\n }\n\n i += EVENT_SIZE + event->len;\n }\n }\n\n Handle<Value> Inotify::GetPersistent(Local<String> property,\n const AccessorInfo& info) {\n Inotify *inotify = ObjectWrap::Unwrap<Inotify>(info.This());\n\n return inotify->persistent ? True() : False();\n }\n}\/\/namespace NodeInotify\n\n<commit_msg>fix read loop to pick up all events instead of just one per buffer<commit_after>\/\/ Copyright 2010, Camilo Aguilar. Cloudescape, LLC.\n#include \"bindings.h\"\n\n\/* size of the event structure, not counting name *\/\n#define EVENT_SIZE (sizeof (struct inotify_event))\n\n\/* reasonable guess as to size of 1024 events *\/\n#define BUF_LEN (1024 * (EVENT_SIZE + 16))\n\nnamespace NodeInotify {\n static Persistent<String> path_sym;\n static Persistent<String> watch_for_sym;\n static Persistent<String> callback_sym;\n static Persistent<String> persistent_sym;\n static Persistent<String> watch_sym;\n static Persistent<String> mask_sym;\n static Persistent<String> cookie_sym;\n static Persistent<String> name_sym;\n\n void Inotify::Initialize(Handle<Object> target) {\n Local<FunctionTemplate> t = FunctionTemplate::New(Inotify::New);\n\n t->Inherit(EventEmitter::constructor_template);\n t->InstanceTemplate()->SetInternalFieldCount(1);\n\n NODE_SET_PROTOTYPE_METHOD(t, \"addWatch\",\n Inotify::AddWatch);\n NODE_SET_PROTOTYPE_METHOD(t, \"removeWatch\",\n Inotify::RemoveWatch);\n NODE_SET_PROTOTYPE_METHOD(t, \"close\",\n Inotify::Close);\n\n \/\/Constants initialization\n NODE_DEFINE_CONSTANT(t, IN_ACCESS); \/\/File was accessed (read)\n NODE_DEFINE_CONSTANT(t, IN_ATTRIB); \/\/Metadata changed, e.g., permissions, timestamps,\n \/\/extended attributes, link count (since Linux 2.6.25),\n \/\/UID, GID, etc.\n NODE_DEFINE_CONSTANT(t, IN_CLOSE_WRITE); \/\/File opened for writing was closed\n NODE_DEFINE_CONSTANT(t, IN_CLOSE_NOWRITE); \/\/File not opened for writing was closed\n NODE_DEFINE_CONSTANT(t, IN_CREATE); \/\/File\/directory created in watched directory\n NODE_DEFINE_CONSTANT(t, IN_DELETE); \/\/File\/directory deleted from watched directory\n NODE_DEFINE_CONSTANT(t, IN_DELETE_SELF); \/\/Watched file\/directory was itself deleted\n NODE_DEFINE_CONSTANT(t, IN_MODIFY); \/\/File was modified\n NODE_DEFINE_CONSTANT(t, IN_MOVE_SELF); \/\/Watched file\/directory was itself moved\n NODE_DEFINE_CONSTANT(t, IN_MOVED_FROM); \/\/File moved out of watched directory\n NODE_DEFINE_CONSTANT(t, IN_MOVED_TO); \/\/File moved into watched directory\n NODE_DEFINE_CONSTANT(t, IN_OPEN); \/\/File was opened\n NODE_DEFINE_CONSTANT(t, IN_IGNORED); \/\/ Watch was removed explicitly (inotify.watch.rm) or\n \/\/automatically (file was deleted, or file system was\n \/\/unmounted)\n NODE_DEFINE_CONSTANT(t, IN_ISDIR); \/\/Subject of this event is a directory\n NODE_DEFINE_CONSTANT(t, IN_Q_OVERFLOW); \/\/Event queue overflowed (wd is -1 for this event)\n NODE_DEFINE_CONSTANT(t, IN_UNMOUNT); \/\/File system containing watched object was unmounted\n NODE_DEFINE_CONSTANT(t, IN_ALL_EVENTS);\n\n NODE_DEFINE_CONSTANT(t, IN_ONLYDIR); \/\/ Only watch the path if it is a directory.\n NODE_DEFINE_CONSTANT(t, IN_DONT_FOLLOW); \/\/ Do not follow a sym link\n NODE_DEFINE_CONSTANT(t, IN_ONESHOT); \/\/ Only send event once\n NODE_DEFINE_CONSTANT(t, IN_MASK_ADD); \/\/Add (OR) events to watch mask for this pathname if it\n \/\/already exists (instead of replacing mask).\n\n NODE_DEFINE_CONSTANT(t, IN_CLOSE); \/\/ (IN_CLOSE_WRITE | IN_CLOSE_NOWRITE) Close\n NODE_DEFINE_CONSTANT(t, IN_MOVE); \/\/ (IN_MOVED_FROM | IN_MOVED_TO) Moves\n\n path_sym = NODE_PSYMBOL(\"path\");\n watch_for_sym = NODE_PSYMBOL(\"watch_for\");\n callback_sym = NODE_PSYMBOL(\"callback\");\n persistent_sym = NODE_PSYMBOL(\"persistent\");\n\n watch_sym = NODE_PSYMBOL(\"watch\");\n mask_sym = NODE_PSYMBOL(\"mask\");\n cookie_sym = NODE_PSYMBOL(\"cookie\");\n name_sym = NODE_PSYMBOL(\"name\");\n\n Local<ObjectTemplate> object_tmpl = t->InstanceTemplate();\n object_tmpl->SetAccessor(persistent_sym, Inotify::GetPersistent);\n\n t->SetClassName(String::NewSymbol(\"Inotify\"));\n target->Set(String::NewSymbol(\"Inotify\"), t->GetFunction());\n }\n\n Inotify::Inotify() : EventEmitter() {\n ev_init(&read_watcher, Inotify::Callback);\n read_watcher.data = this; \/\/preserving my reference to use it inside Inotify::Callback\n persistent = true;\n }\n\n Inotify::Inotify(bool nonpersistent) : EventEmitter() {\n ev_init(&read_watcher, Inotify::Callback);\n read_watcher.data = this; \/\/preserving my reference to use it inside Inotify::Callback\n persistent = nonpersistent;\n }\n\n Inotify::~Inotify() {\n if(!persistent) {\n ev_ref(EV_DEFAULT_UC);\n }\n ev_io_stop(EV_DEFAULT_UC_ &read_watcher);\n assert(!ev_is_active(&read_watcher));\n assert(!ev_is_pending(&read_watcher));\n }\n\n Handle<Value> Inotify::New(const Arguments& args) {\n HandleScope scope;\n\n Inotify *inotify = NULL;\n if(args.Length() == 1 && args[0]->IsBoolean()) {\n inotify = new Inotify(args[0]->IsTrue());\n } else {\n inotify = new Inotify();\n }\n\n \tinotify->fd = inotify_init();\n\n if(inotify->fd == -1) {\n ThrowException(String::New(strerror(errno)));\n return Null();\n }\n\t\n\tint flags = fcntl(inotify->fd, F_GETFL);\n\tif(flags == -1) {\n\t flags = 0;\n\t}\n\n\tfcntl(inotify->fd, F_SETFL, flags | O_NONBLOCK);\n\n ev_io_set(&inotify->read_watcher, inotify->fd, EV_READ);\n ev_io_start(EV_DEFAULT_UC_ &inotify->read_watcher);\n\n Local<Object> obj = args.This();\n inotify->Wrap(obj);\n\n if(!inotify->persistent) {\n ev_unref(EV_DEFAULT_UC);\n }\n \/*Increment object references to avoid be GCed while\n I'm waiting for inotify events in th ev_pool.\n Also, the object is not weak anymore *\/\n inotify->Ref();\n\n return scope.Close(obj);\n }\n\n Handle<Value> Inotify::AddWatch(const Arguments& args) {\n HandleScope scope;\n uint32_t mask = 0;\n int watch_descriptor = 0;\n\n if(args.Length() < 1 || !args[0]->IsObject()) {\n return ThrowException(Exception::TypeError(\n String::New(\"You must specify an object as first argument\")));\n }\n\n Local<Object> args_ = args[0]->ToObject();\n\n if(!args_->Has(path_sym)) {\n return ThrowException(Exception::TypeError(\n String::New(\"You must specify a path to watch for events\")));\n }\n\n if(!args_->Has(callback_sym) ||\n !args_->Get(callback_sym)->IsFunction()) {\n return ThrowException(Exception::TypeError(\n String::New(\"You must specify a callback function\")));\n }\n\n if(!args_->Has(watch_for_sym)) {\n mask |= IN_ALL_EVENTS;\n } else {\n if(!args_->Get(watch_for_sym)->IsInt32()) {\n return ThrowException(Exception::TypeError(\n String::New(\"You must specify OR'ed set of events\")));\n }\n mask |= args_->Get(watch_for_sym)->Int32Value();\n if(mask == 0) {\n return ThrowException(Exception::TypeError(\n String::New(\"You must specify OR'ed set of events\")));\n }\n }\n\n String::Utf8Value path(args_->Get(path_sym));\n\n Inotify *inotify = ObjectWrap::Unwrap<Inotify>(args.This());\n\n \/* add watch *\/\n watch_descriptor = inotify_add_watch(inotify->fd, (const char *) *path, mask);\n\n Local<Integer> descriptor = Integer::New(watch_descriptor);\n\n \/\/Local<Function> callback = Local<Function>::Cast(args_->Get(callback_sym));\n inotify->handle_->Set(descriptor, args_->Get(callback_sym));\n\n return scope.Close(descriptor);\n }\n\n Handle<Value> Inotify::RemoveWatch(const Arguments& args) {\n HandleScope scope;\n uint32_t watch = 0;\n int ret = -1;\n\n if(args.Length() == 0 || !args[0]->IsInt32()) {\n return ThrowException(Exception::TypeError(\n String::New(\"You must specify a valid watcher descriptor as argument\")));\n }\n watch = args[0]->Int32Value();\n\n Inotify *inotify = ObjectWrap::Unwrap<Inotify>(args.This());\n\n ret = inotify_rm_watch(inotify->fd, watch);\n if(ret == -1) {\n ThrowException(String::New(strerror(errno)));\n return False();\n }\n\n return True();\n }\n\n Handle<Value> Inotify::Close(const Arguments& args) {\n HandleScope scope;\n int ret = -1;\n\n Inotify *inotify = ObjectWrap::Unwrap<Inotify>(args.This());\n ret = close(inotify->fd);\n\n if(ret == -1) {\n ThrowException(String::New(strerror(errno)));\n return False();\n }\n\n if(!inotify->persistent) {\n ev_ref(EV_DEFAULT_UC);\n }\n\n ev_io_stop(EV_DEFAULT_UC_ &inotify->read_watcher);\n\n \/*Eliminating reference created inside of Inotify::New.\n The object is also weak again.\n Now v8 can do its stuff and GC the object.\n *\/\n inotify->Unref();\n\n return True();\n }\n\n void Inotify::Callback(EV_P_ ev_io *watcher, int revents) {\n HandleScope scope;\n\n Inotify *inotify = static_cast<Inotify*>(watcher->data);\n assert(watcher == &inotify->read_watcher);\n\n char buffer[BUF_LEN];\n\n \/\/int length = read(inotify->fd, buffer, BUF_LEN);\n\n Local<Value> argv[1];\n TryCatch try_catch;\n\n int i = 0;\n\tint sz = 0;\n while ((sz = read(inotify->fd, buffer, BUF_LEN)) > 0) {\n\t struct inotify_event *event;\n\t for (i = 0; i <= (sz-EVENT_SIZE); i += (EVENT_SIZE + event->len)) {\n event = (struct inotify_event *) &buffer[i];\n\n Local<Object> obj = Object::New();\n obj->Set(watch_sym, Integer::New(event->wd));\n obj->Set(mask_sym, Integer::New(event->mask));\n obj->Set(cookie_sym, Integer::New(event->cookie));\n\n if(event->len) {\n obj->Set(name_sym, String::New(event->name));\n }\n argv[0] = obj;\n\n inotify->Ref();\n Local<Value> callback_ = inotify->handle_->Get(Integer::New(event->wd));\n Local<Function> callback = Local<Function>::Cast(callback_);\n\n callback->Call(inotify->handle_, 1, argv);\n inotify->Unref();\n\n if(event->mask & IN_IGNORED) {\n \/\/deleting callback because the watch was removed\n Local<Value> wd = Integer::New(event->wd);\n inotify->handle_->Delete(wd->ToString());\n }\n\n if (try_catch.HasCaught()) {\n FatalException(try_catch);\n }\n\t }\n\t}\n }\n\n Handle<Value> Inotify::GetPersistent(Local<String> property,\n const AccessorInfo& info) {\n Inotify *inotify = ObjectWrap::Unwrap<Inotify>(info.This());\n\n return inotify->persistent ? True() : False();\n }\n}\/\/namespace NodeInotify\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright 2015 Cloudius Systems\n *\/\n\n#ifndef DB_SERIALIZER_HH_\n#define DB_SERIALIZER_HH_\n\n#include \"utils\/data_input.hh\"\n#include \"utils\/data_output.hh\"\n#include \"bytes.hh\"\n#include \"mutation.hh\"\n#include \"keys.hh\"\n#include \"database_fwd.hh\"\n\nnamespace db {\n\/**\n * Serialization objects for various types and using \"internal\" format. (Not CQL, origin whatnot).\n * The design rationale is that a \"serializer\" can be instantiated for an object, and will contain\n * the obj + size, and is usable as a functor.\n *\n * Serialization can also be done \"explicitly\" through the static method \"write\"\n * (Not using \"serialize\", because writing \"serializer<apa>::serialize\" all the time is tiring and redundant)\n * though care should be takes than data will fit of course.\n *\/\ntemplate<typename T>\nclass serializer {\npublic:\n typedef T type;\n typedef data_output output;\n typedef data_input input;\n typedef serializer<T> _MyType;\n\n serializer(const type&);\n\n \/\/ apply to memory, must be at least size() large.\n const _MyType& operator()(output& out) const {\n write(out, _item);\n return *this;\n }\n\n static void write(output&, const T&);\n static void read(T&, input&);\n static T read(input&);\n static void skip(input& in);\n\n size_t size() const {\n return _size;\n }\nprivate:\n const T& _item;\n size_t _size;\n};\n\ntemplate<> serializer<utils::UUID>::serializer(const utils::UUID &);\ntemplate<> void serializer<utils::UUID>::write(output&, const type&);\ntemplate<> void serializer<utils::UUID>::read(utils::UUID&, input&);\ntemplate<> void serializer<utils::UUID>::skip(input&);\ntemplate<> utils::UUID serializer<utils::UUID>::read(input&);\n\ntemplate<> serializer<bytes>::serializer(const bytes &);\ntemplate<> void serializer<bytes>::write(output&, const type&);\ntemplate<> void serializer<bytes>::read(bytes&, input&);\n\ntemplate<> serializer<bytes_view>::serializer(const bytes_view&);\ntemplate<> void serializer<bytes_view>::write(output&, const type&);\ntemplate<> void serializer<bytes_view>::read(bytes_view&, input&);\ntemplate<> bytes_view serializer<bytes_view>::read(input&);\n\ntemplate<> serializer<sstring>::serializer(const sstring&);\ntemplate<> void serializer<sstring>::write(output&, const type&);\ntemplate<> void serializer<sstring>::read(sstring&, input&);\n\ntemplate<> serializer<tombstone>::serializer(const tombstone &);\ntemplate<> void serializer<tombstone>::write(output&, const type&);\ntemplate<> void serializer<tombstone>::read(tombstone&, input&);\n\ntemplate<> serializer<atomic_cell_view>::serializer(const atomic_cell_view &);\ntemplate<> void serializer<atomic_cell_view>::write(output&, const type&);\ntemplate<> void serializer<atomic_cell_view>::read(atomic_cell_view&, input&);\ntemplate<> atomic_cell_view serializer<atomic_cell_view>::read(input&);\n\ntemplate<> serializer<collection_mutation::view>::serializer(const collection_mutation::view &);\ntemplate<> void serializer<collection_mutation::view>::write(output&, const type&);\ntemplate<> void serializer<collection_mutation::view>::read(collection_mutation::view&, input&);\n\ntemplate<> serializer<row>::serializer(const row &);\ntemplate<> void serializer<row>::write(output&, const type&);\ntemplate<> void serializer<row>::read(row&, input&);\n\ntemplate<> serializer<mutation_partition>::serializer(const mutation_partition &);\ntemplate<> void serializer<mutation_partition>::write(output&, const type&);\ntemplate<> void serializer<mutation_partition>::read(mutation_partition&, input&);\ntemplate<> mutation_partition serializer<mutation_partition>::read(input&) = delete;\n\ntemplate<> serializer<mutation>::serializer(const mutation &);\ntemplate<> void serializer<mutation>::write(output&, const type&);\ntemplate<> void serializer<mutation>::read(mutation&, input&) = delete;\ntemplate<> mutation serializer<mutation>::read(input&);\n\ntemplate<> serializer<partition_key_view>::serializer(const partition_key_view &);\ntemplate<> void serializer<partition_key_view>::write(output&, const partition_key_view&);\ntemplate<> void serializer<partition_key_view>::read(partition_key_view&, input&);\ntemplate<> partition_key_view serializer<partition_key_view>::read(input&);\ntemplate<> void serializer<partition_key_view>::skip(input&);\n\ntemplate<> serializer<clustering_key_view>::serializer(const clustering_key_view &);\ntemplate<> void serializer<clustering_key_view>::write(output&, const clustering_key_view&);\ntemplate<> void serializer<clustering_key_view>::read(clustering_key_view&, input&);\ntemplate<> clustering_key_view serializer<clustering_key_view>::read(input&);\n\ntemplate<> serializer<clustering_key_prefix_view>::serializer(const clustering_key_prefix_view &);\ntemplate<> void serializer<clustering_key_prefix_view>::write(output&, const clustering_key_prefix_view&);\ntemplate<> void serializer<clustering_key_prefix_view>::read(clustering_key_prefix_view&, input&);\ntemplate<> clustering_key_prefix_view serializer<clustering_key_prefix_view>::read(input&);\n\ntemplate<typename T>\nT serializer<T>::read(input& in) {\n type t;\n read(t, in);\n return t;\n}\n\nextern template class serializer<tombstone>;\nextern template class serializer<bytes>;\nextern template class serializer<bytes_view>;\nextern template class serializer<sstring>;\nextern template class serializer<utils::UUID>;\nextern template class serializer<partition_key_view>;\nextern template class serializer<clustering_key_view>;\nextern template class serializer<clustering_key_prefix_view>;\n\ntypedef serializer<tombstone> tombstone_serializer;\ntypedef serializer<bytes> bytes_serializer; \/\/ Compatible with bytes_view_serializer\ntypedef serializer<bytes_view> bytes_view_serializer; \/\/ Compatible with bytes_serializer\ntypedef serializer<sstring> sstring_serializer;\ntypedef serializer<atomic_cell_view> atomic_cell_view_serializer;\ntypedef serializer<collection_mutation::view> collection_mutation_view_serializer;\ntypedef serializer<utils::UUID> uuid_serializer;\ntypedef serializer<partition_key_view> partition_key_view_serializer;\ntypedef serializer<clustering_key_view> clustering_key_view_serializer;\ntypedef serializer<clustering_key_prefix_view> clustering_key_prefix_view_serializer;\n\n}\n\n#endif \/* DB_SERIALIZER_HH_ *\/\n<commit_msg>remove leftovers from db\/serializer.hh<commit_after>\/*\n * Copyright 2015 Cloudius Systems\n *\/\n\n#ifndef DB_SERIALIZER_HH_\n#define DB_SERIALIZER_HH_\n\n#include \"utils\/data_input.hh\"\n#include \"utils\/data_output.hh\"\n#include \"bytes.hh\"\n#include \"mutation.hh\"\n#include \"keys.hh\"\n#include \"database_fwd.hh\"\n\nnamespace db {\n\/**\n * Serialization objects for various types and using \"internal\" format. (Not CQL, origin whatnot).\n * The design rationale is that a \"serializer\" can be instantiated for an object, and will contain\n * the obj + size, and is usable as a functor.\n *\n * Serialization can also be done \"explicitly\" through the static method \"write\"\n * (Not using \"serialize\", because writing \"serializer<apa>::serialize\" all the time is tiring and redundant)\n * though care should be takes than data will fit of course.\n *\/\ntemplate<typename T>\nclass serializer {\npublic:\n typedef T type;\n typedef data_output output;\n typedef data_input input;\n typedef serializer<T> _MyType;\n\n serializer(const type&);\n\n \/\/ apply to memory, must be at least size() large.\n const _MyType& operator()(output& out) const {\n write(out, _item);\n return *this;\n }\n\n static void write(output&, const T&);\n static void read(T&, input&);\n static T read(input&);\n static void skip(input& in);\n\n size_t size() const {\n return _size;\n }\nprivate:\n const T& _item;\n size_t _size;\n};\n\ntemplate<> serializer<utils::UUID>::serializer(const utils::UUID &);\ntemplate<> void serializer<utils::UUID>::write(output&, const type&);\ntemplate<> void serializer<utils::UUID>::read(utils::UUID&, input&);\ntemplate<> void serializer<utils::UUID>::skip(input&);\ntemplate<> utils::UUID serializer<utils::UUID>::read(input&);\n\ntemplate<> serializer<bytes>::serializer(const bytes &);\ntemplate<> void serializer<bytes>::write(output&, const type&);\ntemplate<> void serializer<bytes>::read(bytes&, input&);\n\ntemplate<> serializer<bytes_view>::serializer(const bytes_view&);\ntemplate<> void serializer<bytes_view>::write(output&, const type&);\ntemplate<> void serializer<bytes_view>::read(bytes_view&, input&);\ntemplate<> bytes_view serializer<bytes_view>::read(input&);\n\ntemplate<> serializer<sstring>::serializer(const sstring&);\ntemplate<> void serializer<sstring>::write(output&, const type&);\ntemplate<> void serializer<sstring>::read(sstring&, input&);\n\ntemplate<> serializer<tombstone>::serializer(const tombstone &);\ntemplate<> void serializer<tombstone>::write(output&, const type&);\ntemplate<> void serializer<tombstone>::read(tombstone&, input&);\n\ntemplate<> serializer<atomic_cell_view>::serializer(const atomic_cell_view &);\ntemplate<> void serializer<atomic_cell_view>::write(output&, const type&);\ntemplate<> void serializer<atomic_cell_view>::read(atomic_cell_view&, input&);\ntemplate<> atomic_cell_view serializer<atomic_cell_view>::read(input&);\n\ntemplate<> serializer<collection_mutation::view>::serializer(const collection_mutation::view &);\ntemplate<> void serializer<collection_mutation::view>::write(output&, const type&);\ntemplate<> void serializer<collection_mutation::view>::read(collection_mutation::view&, input&);\n\ntemplate<> serializer<partition_key_view>::serializer(const partition_key_view &);\ntemplate<> void serializer<partition_key_view>::write(output&, const partition_key_view&);\ntemplate<> void serializer<partition_key_view>::read(partition_key_view&, input&);\ntemplate<> partition_key_view serializer<partition_key_view>::read(input&);\ntemplate<> void serializer<partition_key_view>::skip(input&);\n\ntemplate<> serializer<clustering_key_view>::serializer(const clustering_key_view &);\ntemplate<> void serializer<clustering_key_view>::write(output&, const clustering_key_view&);\ntemplate<> void serializer<clustering_key_view>::read(clustering_key_view&, input&);\ntemplate<> clustering_key_view serializer<clustering_key_view>::read(input&);\n\ntemplate<> serializer<clustering_key_prefix_view>::serializer(const clustering_key_prefix_view &);\ntemplate<> void serializer<clustering_key_prefix_view>::write(output&, const clustering_key_prefix_view&);\ntemplate<> void serializer<clustering_key_prefix_view>::read(clustering_key_prefix_view&, input&);\ntemplate<> clustering_key_prefix_view serializer<clustering_key_prefix_view>::read(input&);\n\ntemplate<typename T>\nT serializer<T>::read(input& in) {\n type t;\n read(t, in);\n return t;\n}\n\nextern template class serializer<tombstone>;\nextern template class serializer<bytes>;\nextern template class serializer<bytes_view>;\nextern template class serializer<sstring>;\nextern template class serializer<utils::UUID>;\nextern template class serializer<partition_key_view>;\nextern template class serializer<clustering_key_view>;\nextern template class serializer<clustering_key_prefix_view>;\n\ntypedef serializer<tombstone> tombstone_serializer;\ntypedef serializer<bytes> bytes_serializer; \/\/ Compatible with bytes_view_serializer\ntypedef serializer<bytes_view> bytes_view_serializer; \/\/ Compatible with bytes_serializer\ntypedef serializer<sstring> sstring_serializer;\ntypedef serializer<atomic_cell_view> atomic_cell_view_serializer;\ntypedef serializer<collection_mutation::view> collection_mutation_view_serializer;\ntypedef serializer<utils::UUID> uuid_serializer;\ntypedef serializer<partition_key_view> partition_key_view_serializer;\ntypedef serializer<clustering_key_view> clustering_key_view_serializer;\ntypedef serializer<clustering_key_prefix_view> clustering_key_prefix_view_serializer;\n\n}\n\n#endif \/* DB_SERIALIZER_HH_ *\/\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ file : assert.hpp\n\/\/ in : file:\/\/\/home\/tim\/projects\/nsched\/nsched\/tools\/debug\/assert.hpp\n\/\/\n\/\/ created by : Timothée Feuillet on linux.site\n\/\/ date: 03\/08\/2014 16:18:37\n\/\/\n\/\/\n\/\/ Copyright (c) 2014-2016 Timothée Feuillet\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in all\n\/\/ copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n\/\/ SOFTWARE.\n\/\/\n\n#ifndef __N_1744658631925022054_1134258981__ASSERT_HPP__\n# define __N_1744658631925022054_1134258981__ASSERT_HPP__\n\n#include \"..\/exception.hpp\"\n\n#ifndef N_DEBUG_USE_CERR\n# include \"..\/logger\/logger.hpp\"\n#endif\n\n#include <string>\n#include <string.h>\n\n#include <sstream>\n#include <fstream>\n#include <iostream>\n#include <iomanip>\n\n#include <stdexcept>\n\n\/\/\n\/\/ (yet another) nice assert\/function check tool\n\/\/ NOTE: you could define N_DISABLE_CHECKS to completly disable every checks.\n\/\/ you could define N_DISABLE_ASSERTS to disable asserts.\n\/\/ you could define N_DISABLE_FNC_CHECKS to disable function checks.\n\/\/ you could define N_DEBUG_USE_CERR to output only (and directly) to std::cerr\n\/\/\n\/\/ there's the macro N_COLUMN_WIDTH that you can define (either to a hardcoded value or a variable)\n\/\/ to control the width of a column. Default is 200.\n\/\/ there's the macro N_ALLOW_DEBUG that you can define (either to a hardcoded value or a variable)\n\/\/ to allow *debug* information (like logging success and co). Default is false.\n\n#ifndef N_COLUMN_WIDTH\n#define N_COLUMN_WIDTH 100\n#endif\n#ifndef N_ALLOW_DEBUG\n#define N_ALLOW_DEBUG false\n#endif\n\nnamespace neam\n{\n namespace debug\n {\n class assert {};\n class function_check {};\n\n template<template<typename ErrorType> class ErrorClass, template<typename> class ExceptionClass = typed_exception>\n class on_error\n {\n private:\n on_error() = delete;\n on_error(const on_error &) = delete;\n\n public:\n template<typename ReturnType>\n static ReturnType &&_throw_exception(const char *file, size_t line, const std::string &func_call, ReturnType &&ret)\n {\n const bool is_error = ErrorClass<ReturnType>::is_error(ret);\n if (N_ALLOW_DEBUG || is_error)\n {\n std::string message = get_message(func_call, ret);\n#ifdef N_DEBUG_USE_CERR\n std::cerr << ((is_error) ? \" ** \" : \" -- \") << message << std::endl;\n#else\n if (is_error)\n neam::cr::out.error() << LOGGER_INFO_TPL(get_filename(file), line) << message << std::endl;\n else\n neam::cr::out.debug() << LOGGER_INFO_TPL(get_filename(file), line) << message << std::endl;\n#endif\n if (is_error)\n throw ExceptionClass<ErrorClass<ReturnType>>(message);\n }\n return std::move(ret);\n }\n\n \/\/ return true in case of error\n template<typename ReturnType>\n static bool _log_and_check(const char *file, size_t line, const std::string &func_call, ReturnType &&ret)\n {\n const bool is_error = ErrorClass<ReturnType>::is_error(ret);\n if (N_ALLOW_DEBUG || is_error)\n {\n std::string message = get_message(func_call, ret);\n#ifdef N_DEBUG_USE_CERR\n std::cerr << ((is_error) ? \" ** \" : \" -- \") << message << std::endl;\n#else\n if (is_error)\n neam::cr::out.error() << LOGGER_INFO_TPL(get_filename(file), line) << message << std::endl;\n else\n neam::cr::out.debug() << LOGGER_INFO_TPL(get_filename(file), line) << message << std::endl;\n#endif\n\n if (is_error)\n return false;\n return true;\n }\n return false;\n }\n\n \/\/ simply log the error and return the value 'as-is'\n template<typename ReturnType>\n static ReturnType &&_log_and_return(const char *file, size_t line, const std::string &func_call, ReturnType &&ret)\n {\n const bool is_error = ErrorClass<ReturnType>::is_error(ret);\n if (N_ALLOW_DEBUG || is_error)\n {\n std::string message = get_message(func_call, ret);\n#ifdef N_DEBUG_USE_CERR\n std::cerr << ((is_error) ? \" ** \" : \" -- \") << message << std::endl;\n#else\n if (is_error)\n neam::cr::out.error() << LOGGER_INFO_TPL(get_filename(file), line) << message << std::endl;\n else\n neam::cr::out.debug() << LOGGER_INFO_TPL(get_filename(file), line) << message << std::endl;\n#endif\n }\n return std::move(ret);\n }\n\n static void _assert(const char *file, size_t line, const std::string &test, bool status, const std::string message)\n {\n if (N_ALLOW_DEBUG || !status)\n {\n#ifdef N_DEBUG_USE_CERR\n std::cerr << ((!status) ? \" ** \" : \" -- \") << std::left << std::setw(N_COLUMN_WIDTH) << std::setfill('.') << (neam::demangle<assert>() + \": \" + test + \" \") << (!status ? \" [FAILED]: \" + message : \" [SUCCESS]\") << std::endl;\n#else\n if (!status)\n neam::cr::out.error() << LOGGER_INFO_TPL(get_filename(file), line) << std::left << std::setw(N_COLUMN_WIDTH) << std::setfill('.') << (neam::demangle<_assert>() + \": \" + test + \" \") << \"[FAILED]: \" + message << std::endl;\n else\n neam::cr::out.debug() << LOGGER_INFO_TPL(get_filename(file), line) << std::left << std::setw(N_COLUMN_WIDTH) << std::setfill('.') << (neam::demangle<_assert>() + \": \" + test + \" \") << \" [SUCCESS]\" << std::endl;\n#endif\n if (!status)\n throw ExceptionClass<on_error>(test + \": assert failed: \" + message);\n }\n }\n\n static bool _assert_and_return(const char *file, size_t line, const std::string &test, bool status, const std::string message)\n {\n if (N_ALLOW_DEBUG || !status)\n {\n#ifdef N_DEBUG_USE_CERR\n std::cerr << ((!status) ? \" ** \" : \" -- \") << std::left << std::setw(N_COLUMN_WIDTH) << std::setfill('.') << (neam::demangle<assert>() + \": \" + test + \" \") << (!status ? \" [FAILED]: \" + message : \" [SUCCESS]\") << std::endl;\n#else\n if (!status)\n neam::cr::out.error() << LOGGER_INFO_TPL(get_filename(file), line) << std::left << std::setw(N_COLUMN_WIDTH) << std::setfill('.') << (neam::demangle<_assert_and_return>() + \": \" + test + \" \") << \"[FAILED]: \" + message << std::endl;\n else\n neam::cr::out.debug() << LOGGER_INFO_TPL(get_filename(file), line) << std::left << std::setw(N_COLUMN_WIDTH) << std::setfill('.') << (neam::demangle<_assert_and_return>() + \": \" + test + \" \") << \" [SUCCESS]\" << std::endl;\n#endif\n }\n return !status;\n }\n\n template<typename ReturnType>\n static ReturnType &&_dummy(ReturnType &&ret)\n {\n return std::move(ret);\n }\n\n#if not defined N_DISABLE_ASSERTS and not defined N_DISABLE_CHECKS\n#define n_assert(test, message) _assert(__FILE__, __LINE__, #test, test, message)\n#define n_assert_exp(test, message) assert(test, message)\n#define n_assert_and_return(test, message) _assert_and_return(__FILE__, __LINE__, #test, test, message)\n#define n_assert_and_return_exp(test, message) assert_and_return(test, message)\n#else\n#define n_assert(test, message) _dummy(((test), true))\n#define n_assert_exp(test, message) assert(test, message)\n#define n_assert_and_return(test, message) _dummy(((test), true))\n#define n_assert_and_return_exp(test, message) assert_and_return(test, message)\n#endif\n\n#if not defined N_DISABLE_FNC_CHECKS and not defined N_DISABLE_CHECKS\n# define n_throw_exception(fnc) _throw_exception(__FILE__, __LINE__, #fnc, fnc)\n# define n_throw_exception_exp(fnc) throw_exception(fnc)\n# define n_log_and_check(fnc) _log_and_check(__FILE__, __LINE__, #fnc, fnc)\n# define n_log_and_check_exp(fnc) log_and_check(fnc)\n# define n_log_and_return(fnc) _log_and_return(__FILE__, __LINE__, #fnc, fnc)\n# define n_log_and_return_exp(fnc) log_and_return(fnc)\n#else\n# define n_throw_exception(fnc) _dummy(fnc)\n# define n_throw_exception_exp(fnc) _dummy(fnc)\n# define n_log_and_return(fnc) _dummy(fnc)\n# define n_log_and_return_exp(fnc) _dummy(fnc)\n# define n_log_and_check(fnc) _dummy(fnc)\n# define n_log_and_check_exp(fnc) _dummy(fnc)\n#endif\n\n private:\n static const char *get_filename(const char *file)\n {\n return (strrchr((file), '\/') ? strrchr((file), '\/') + 1 : file);\n }\n\n template<typename ReturnType>\n static std::string get_message(const std::string &func_call, const ReturnType &code)\n {\n std::ostringstream is;\n\n if (ErrorClass<ReturnType>::exists(code))\n {\n const std::string code_name = ErrorClass<ReturnType>::get_code_name(code);\n const std::string description = ErrorClass<ReturnType>::get_description(code);\n\n is << std::left << std::setw(N_COLUMN_WIDTH) << std::setfill('.') << (func_call + \" \") << \" [\" << code_name << \"]: \" << description;\n }\n else\n is << std::left << std::setw(N_COLUMN_WIDTH) << std::setfill('.') << (func_call + \" \") << \" [code: \" << code << \"]: [UNKNOW ERROR CODE]\";\n return is.str();\n }\n };\n } \/\/ namespace debug\n} \/\/ namespace neam\n\n#endif \/*__N_1744658631925022054_1134258981__ASSERT_HPP__*\/\n\n\/\/ kate: indent-mode cstyle; indent-width 2; replace-tabs on; \n\n<commit_msg>[DEBUG]: Update the debug tool to account changes in the logger<commit_after>\/\/\n\/\/ file : assert.hpp\n\/\/ in : file:\/\/\/home\/tim\/projects\/nsched\/nsched\/tools\/debug\/assert.hpp\n\/\/\n\/\/ created by : Timothée Feuillet on linux.site\n\/\/ date: 03\/08\/2014 16:18:37\n\/\/\n\/\/\n\/\/ Copyright (c) 2014-2016 Timothée Feuillet\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in all\n\/\/ copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n\/\/ SOFTWARE.\n\/\/\n\n#ifndef __N_1744658631925022054_1134258981__ASSERT_HPP__\n# define __N_1744658631925022054_1134258981__ASSERT_HPP__\n\n#include \"..\/exception.hpp\"\n\n#ifndef N_DEBUG_USE_CERR\n# include \"..\/logger\/logger.hpp\"\n#endif\n\n#include <string>\n#include <string.h>\n\n#include <sstream>\n#include <fstream>\n#include <iostream>\n#include <iomanip>\n\n#include <stdexcept>\n\n\/\/\n\/\/ (yet another) nice assert\/function check tool\n\/\/ NOTE: you could define N_DISABLE_CHECKS to completly disable every checks.\n\/\/ you could define N_DISABLE_ASSERTS to disable asserts.\n\/\/ you could define N_DISABLE_FNC_CHECKS to disable function checks.\n\/\/ you could define N_DEBUG_USE_CERR to output only (and directly) to std::cerr\n\/\/\n\/\/ there's the macro N_COLUMN_WIDTH that you can define (either to a hardcoded value or a variable)\n\/\/ to control the width of a column. Default is 200.\n\/\/ there's the macro N_ALLOW_DEBUG that you can define (either to a hardcoded value or a variable)\n\/\/ to allow *debug* information (like logging success and co). Default is false.\n\n#ifndef N_COLUMN_WIDTH\n#define N_COLUMN_WIDTH 100\n#endif\n#ifndef N_ALLOW_DEBUG\n#define N_ALLOW_DEBUG false\n#endif\n\nnamespace neam\n{\n namespace debug\n {\n template<template<typename ErrorType> class ErrorClass, template<typename> class ExceptionClass = typed_exception>\n class on_error\n {\n private:\n on_error() = delete;\n on_error(const on_error &) = delete;\n\n public:\n template<typename ReturnType>\n static ReturnType &&_throw_exception(const char *file, size_t line, const std::string &func_call, ReturnType &&ret)\n {\n const bool is_error = ErrorClass<ReturnType>::is_error(ret);\n if (N_ALLOW_DEBUG || is_error)\n {\n std::string message = get_message(func_call, ret);\n#ifdef N_DEBUG_USE_CERR\n std::cerr << ((is_error) ? \" ** \" : \" -- \") << message << std::endl;\n#else\n if (is_error)\n neam::cr::out.error() << LOGGER_INFO_TPL(get_filename(file), line) << message << std::endl;\n else\n neam::cr::out.debug() << LOGGER_INFO_TPL(get_filename(file), line) << message << std::endl;\n#endif\n if (is_error)\n throw ExceptionClass<ErrorClass<ReturnType>>(message);\n }\n return std::move(ret);\n }\n\n \/\/ return true in case of error\n template<typename ReturnType>\n static bool _log_and_check(const char *file, size_t line, const std::string &func_call, ReturnType &&ret)\n {\n const bool is_error = ErrorClass<ReturnType>::is_error(ret);\n if (N_ALLOW_DEBUG || is_error)\n {\n std::string message = get_message(func_call, ret);\n#ifdef N_DEBUG_USE_CERR\n std::cerr << ((is_error) ? \" ** \" : \" -- \") << message << std::endl;\n#else\n if (is_error)\n neam::cr::out.error() << LOGGER_INFO_TPL(get_filename(file), line) << message << std::endl;\n else\n neam::cr::out.debug() << LOGGER_INFO_TPL(get_filename(file), line) << message << std::endl;\n#endif\n\n if (is_error)\n return false;\n return true;\n }\n return false;\n }\n\n \/\/ simply log the error and return the value 'as-is'\n template<typename ReturnType>\n static ReturnType &&_log_and_return(const char *file, size_t line, const std::string &func_call, ReturnType &&ret)\n {\n const bool is_error = ErrorClass<ReturnType>::is_error(ret);\n if (N_ALLOW_DEBUG || is_error)\n {\n std::string message = get_message(func_call, ret);\n#ifdef N_DEBUG_USE_CERR\n std::cerr << ((is_error) ? \" ** \" : \" -- \") << message << std::endl;\n#else\n if (is_error)\n neam::cr::out.error() << LOGGER_INFO_TPL(get_filename(file), line) << message << std::endl;\n else\n neam::cr::out.debug() << LOGGER_INFO_TPL(get_filename(file), line) << message << std::endl;\n#endif\n }\n return std::move(ret);\n }\n\n static void _assert(const char *file, size_t line, const std::string &test, bool status, const std::string message)\n {\n if (N_ALLOW_DEBUG || !status)\n {\n#ifdef N_DEBUG_USE_CERR\n std::cerr << ((!status) ? \" ** \" : \" -- \") << std::left << std::setw(N_COLUMN_WIDTH) << std::setfill('.') << (test + \" \") << (!status ? \" [FAILED]: \" + message : \" [SUCCESS]\") << std::endl;\n#else\n if (!status)\n neam::cr::out.error() << LOGGER_INFO_TPL(get_filename(file), line) << std::left << std::setw(N_COLUMN_WIDTH) << std::setfill('.') << (test + \" \") << \"[FAILED]: \" + message << std::endl;\n else\n neam::cr::out.debug() << LOGGER_INFO_TPL(get_filename(file), line) << std::left << std::setw(N_COLUMN_WIDTH) << std::setfill('.') << (test + \" \") << \" [SUCCESS]\" << std::endl;\n#endif\n if (!status)\n throw ExceptionClass<on_error>(test + \": assert failed: \" + message);\n }\n }\n\n static bool _assert_and_return(const char *file, size_t line, const std::string &test, bool status, const std::string message)\n {\n if (N_ALLOW_DEBUG || !status)\n {\n#ifdef N_DEBUG_USE_CERR\n std::cerr << ((!status) ? \" ** \" : \" -- \") << std::left << std::setw(N_COLUMN_WIDTH) << std::setfill('.') << (test + \" \") << (!status ? \" [FAILED]: \" + message : \" [SUCCESS]\") << std::endl;\n#else\n if (!status)\n neam::cr::out.error() << LOGGER_INFO_TPL(get_filename(file), line) << std::left << std::setw(N_COLUMN_WIDTH) << std::setfill('.') << (test + \" \") << \"[FAILED]: \" + message << std::endl;\n else\n neam::cr::out.debug() << LOGGER_INFO_TPL(get_filename(file), line) << std::left << std::setw(N_COLUMN_WIDTH) << std::setfill('.') << (test + \" \") << \" [SUCCESS]\" << std::endl;\n#endif\n }\n return !status;\n }\n\n template<typename ReturnType>\n static ReturnType &&_dummy(ReturnType &&ret)\n {\n return std::move(ret);\n }\n\n#if not defined N_DISABLE_ASSERTS and not defined N_DISABLE_CHECKS\n#define n_assert(test, message) _assert(__FILE__, __LINE__, #test, test, message)\n#define n_assert_exp(test, message) assert(test, message)\n#define n_assert_and_return(test, message) _assert_and_return(__FILE__, __LINE__, #test, test, message)\n#define n_assert_and_return_exp(test, message) assert_and_return(test, message)\n#else\n#define n_assert(test, message) _dummy(((test), true))\n#define n_assert_exp(test, message) assert(test, message)\n#define n_assert_and_return(test, message) _dummy(((test), true))\n#define n_assert_and_return_exp(test, message) assert_and_return(test, message)\n#endif\n\n#if not defined N_DISABLE_FNC_CHECKS and not defined N_DISABLE_CHECKS\n# define n_throw_exception(fnc) _throw_exception(__FILE__, __LINE__, #fnc, fnc)\n# define n_throw_exception_exp(fnc) throw_exception(fnc)\n# define n_log_and_check(fnc) _log_and_check(__FILE__, __LINE__, #fnc, fnc)\n# define n_log_and_check_exp(fnc) log_and_check(fnc)\n# define n_log_and_return(fnc) _log_and_return(__FILE__, __LINE__, #fnc, fnc)\n# define n_log_and_return_exp(fnc) log_and_return(fnc)\n#else\n# define n_throw_exception(fnc) _dummy(fnc)\n# define n_throw_exception_exp(fnc) _dummy(fnc)\n# define n_log_and_return(fnc) _dummy(fnc)\n# define n_log_and_return_exp(fnc) _dummy(fnc)\n# define n_log_and_check(fnc) _dummy(fnc)\n# define n_log_and_check_exp(fnc) _dummy(fnc)\n#endif\n\n private:\n static const char *get_filename(const char *file)\n {\n return (strrchr((file), '\/') ? strrchr((file), '\/') + 1 : file);\n }\n\n template<typename ReturnType>\n static std::string get_message(const std::string &func_call, const ReturnType &code)\n {\n std::ostringstream is;\n\n if (ErrorClass<ReturnType>::exists(code))\n {\n const std::string code_name = ErrorClass<ReturnType>::get_code_name(code);\n const std::string description = ErrorClass<ReturnType>::get_description(code);\n\n is << std::left << std::setw(N_COLUMN_WIDTH) << std::setfill('.') << (func_call + \" \") << \" [\" << code_name << \"]: \" << description;\n }\n else\n is << std::left << std::setw(N_COLUMN_WIDTH) << std::setfill('.') << (func_call + \" \") << \" [code: \" << code << \"]: [UNKNOW ERROR CODE]\";\n return is.str();\n }\n };\n } \/\/ namespace debug\n} \/\/ namespace neam\n\n#endif \/*__N_1744658631925022054_1134258981__ASSERT_HPP__*\/\n\n\/\/ kate: indent-mode cstyle; indent-width 2; replace-tabs on; \n\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ Copyright (c) 2018 Rokas Kupstys\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n\/\/ THE SOFTWARE.\n\/\/\n\n#include <Urho3D\/Urho3DAll.h>\n#include <CLI11\/CLI11.hpp>\n#include <Toolbox\/SystemUI\/Gizmo.h>\n#include <ctime>\n#include <cstdio>\n\nusing namespace std::placeholders;\n\nnamespace Urho3D\n{\n\nclass AssetViewer\n : public Application\n{\n URHO3D_OBJECT(AssetViewer, Application);\npublic:\n SharedPtr<Scene> scene_;\n SharedPtr<Viewport> viewport_;\n SharedPtr<Light> light_;\n WeakPtr<Camera> camera_;\n WeakPtr<Node> node_;\n WeakPtr<Node> parentNode_;\n WeakPtr<AnimatedModel> model_;\n WeakPtr<AnimationController> animator_;\n float lookSensitivity_ = 1.0f;\n Gizmo gizmo_;\n bool showHelp_ = false;\n std::string assetFile_;\n\n explicit AssetViewer(Context* context)\n : Application(context), gizmo_(context)\n {\n }\n\n void Setup() override\n {\n engineParameters_[EP_WINDOW_TITLE] = GetTypeName();\n engineParameters_[EP_WINDOW_WIDTH] = 1024;\n engineParameters_[EP_WINDOW_HEIGHT] = 768;\n engineParameters_[EP_FULL_SCREEN] = false;\n engineParameters_[EP_HEADLESS] = false;\n engineParameters_[EP_SOUND] = false;\n engineParameters_[EP_RESOURCE_PATHS] = \"CoreData\";\n engineParameters_[EP_RESOURCE_PREFIX_PATHS] = \";..;..\/..\";\n engineParameters_[EP_WINDOW_RESIZABLE] = true;\n\n GetCommandLineParser().add_option(\"asset\", assetFile_, \"Asset file to be opened on application startup.\");\n }\n\n void Start() override\n {\n ui::GetIO().IniFilename = nullptr; \/\/ Disable saving of settings.\n\n GetInput()->SetMouseVisible(true);\n GetInput()->SetMouseMode(MM_ABSOLUTE);\n\n scene_ = new Scene(context_);\n scene_->CreateComponent<Octree>();\n auto zone = scene_->CreateComponent<Zone>();\n zone->SetFogColor(Color(0.5f, 0.5f, 0.7f));\n camera_ = scene_->CreateChild(\"Camera\")->CreateComponent<Camera>();\n light_ = camera_->GetNode()->CreateComponent<Light>();\n light_->SetColor(Color::WHITE);\n light_->SetLightType(LIGHT_DIRECTIONAL);\n\n viewport_ = new Viewport(context_, scene_, camera_);\n GetSubsystem<Renderer>()->SetViewport(0, viewport_);\n\n \/\/ Parent node used to rotate model around it's center (not origin).\n parentNode_ = scene_->CreateChild();\n\n GetSystemUI()->ApplyStyleDefault(true, 1);\n ui::GetStyle().WindowRounding = 0;\n\n SubscribeToEvent(E_UPDATE, std::bind(&AssetViewer::OnUpdate, this, _2));\n SubscribeToEvent(E_DROPFILE, std::bind(&AssetViewer::OnFileDrop, this, _2));\n\n if (!assetFile_.empty())\n LoadFile(assetFile_.c_str());\n }\n\n void OnUpdate(VariantMap& args)\n {\n if (node_.Null())\n return;\n\n if (!GetSystemUI()->IsAnyItemActive() && !GetSystemUI()->IsAnyItemHovered())\n {\n auto input = GetSubsystem<Input>();\n\n if (!input->GetKeyDown(KEY_SHIFT))\n {\n if (input->GetMouseButtonDown(MOUSEB_RIGHT))\n {\n if (input->IsMouseVisible())\n input->SetMouseVisible(false);\n\n if (input->GetMouseMove() != IntVector2::ZERO)\n {\n camera_->GetNode()->RotateAround(Vector3::ZERO,\n Quaternion(input->GetMouseMoveX() * 0.1f * lookSensitivity_, camera_->GetNode()->GetUp()) *\n Quaternion(input->GetMouseMoveY() * 0.1f * lookSensitivity_, camera_->GetNode()->GetRight()), TS_WORLD);\n }\n }\n else if (input->GetMouseButtonDown(MOUSEB_MIDDLE))\n {\n if (input->IsMouseVisible())\n input->SetMouseVisible(false);\n\n node_->Translate2D(Vector2(input->GetMouseMoveX(), -input->GetMouseMoveY()) \/ 300.f, TS_WORLD);\n }\n else if (!input->IsMouseVisible())\n input->SetMouseVisible(true);\n\n camera_->GetNode()->Translate(Vector3::FORWARD * input->GetMouseMoveWheel() * 0.2f);\n }\n else if (!input->IsMouseVisible())\n input->SetMouseVisible(true);\n }\n\n if (GetInput()->GetKeyPress(KEY_F1))\n showHelp_ = true;\n\n\n ui::SetNextWindowPos({0, 0}, ImGuiCond_Always);\n if (ui::Begin(\"Settings\", nullptr,\n ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoTitleBar |\n ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoSavedSettings))\n {\n gizmo_.RenderUI();\n\n if (ui::Button(\"Reset\"))\n ResetNode();\n\n \/\/ Window has to contain controls already in order for it's size to be set to match contents.\n ui::SetWindowSize({0, 0}, ImGuiCond_Always);\n }\n ui::End();\n\n if (showHelp_)\n {\n if (ui::Begin(\"Help\", &showHelp_, ImGuiWindowFlags_NoSavedSettings))\n {\n ui::TextUnformatted(\"RMB: hold it rotates model around its center.\");\n ui::TextUnformatted(\"Shift: holding it provides manipulation gizmo at model origin.\");\n }\n ui::End();\n }\n\n if (node_ && GetInput()->GetKeyDown(KEY_SHIFT))\n gizmo_.Manipulate(camera_, parentNode_);\n }\n\n void OnFileDrop(VariantMap& args)\n {\n LoadFile(args[DropFile::P_FILENAME].GetString());\n }\n\n void LoadFile(const String& file_path)\n {\n if (file_path.EndsWith(\".mdl\"))\n LoadModel(file_path);\n else if (file_path.EndsWith(\".ani\"))\n LoadAnimation(file_path);\n else if (file_path.EndsWith(\".fbx\"))\n LoadFbx(file_path);\n }\n\n void LoadModel(const String& file_path, const Vector<String>& materials = { })\n {\n if (node_.NotNull())\n node_->Remove();\n\n node_ = parentNode_->CreateChild(\"Node\");\n model_ = node_->CreateComponent<AnimatedModel>();\n animator_ = node_->CreateComponent<AnimationController>();\n\n auto cache = GetSubsystem<ResourceCache>();\n model_->SetModel(cache->GetTempResource<Model>(file_path));\n\n ResetNode();\n\n for (auto i = 0; i < materials.Size(); i++)\n model_->SetMaterial(i, cache->GetTempResource<Material>(materials[i]));\n }\n\n void ResetNode()\n {\n if (node_.NotNull())\n {\n parentNode_->SetScale(1.f);\n parentNode_->SetPosition(Vector3::ZERO);\n parentNode_->SetRotation(Quaternion::IDENTITY);\n \/\/ Scale model to size of 1 unit\n auto size = model_->GetBoundingBox().Size();\n node_->SetScale(1.f \/ Max(size.x_, Max(size.y_, size.z_)));\n \/\/ Snap center of the model to {0,0,0}\n node_->SetWorldPosition(node_->GetWorldPosition() - model_->GetWorldBoundingBox().Center());\n node_->SetRotation(Quaternion::IDENTITY);\n\n camera_->GetNode()->LookAt(Vector3::ZERO);\n camera_->GetNode()->SetRotation(Quaternion::IDENTITY);\n camera_->GetNode()->SetPosition(Vector3::BACK * 1.5f);\n }\n }\n\n void LoadAnimation(const String& file_path)\n {\n if (animator_)\n animator_->PlayExclusive(file_path, 0, true);\n }\n\n void LoadFbx(const String& file_path)\n {\n auto fs = GetSubsystem<FileSystem>();\n String temp = fs->GetTemporaryDir();\n temp += \"AssetViewer\/\";\n if (!fs->DirExists(temp))\n {\n fs->CreateDir(temp);\n fs->CreateDir(temp + \"\/mdl\");\n fs->CreateDir(temp + \"\/ani\");\n }\n auto animation_path = temp + \"\/ani\";\n auto model_file = temp + \"\/mdl\/out.mdl\";\n auto material_list_file = temp + \"\/mdl\/out.txt\";\n fs->Delete(model_file);\n\n Process proc(fs->GetProgramDir() + \"AssetImporter\", {\"model\", file_path, model_file.CString(), \"-na\", \"-l\"});\n if (proc.Run() == 0)\n {\n if (fs->FileExists(model_file))\n {\n Vector<String> materials;\n File fp(context_, material_list_file);\n if (fp.IsOpen())\n {\n while (!fp.IsEof())\n materials.Push(temp + \"\/mdl\/\" + fp.ReadLine());\n }\n LoadModel(model_file, materials);\n }\n\n Vector<String> animations;\n fs->ScanDir(animations, animation_path, \"*.ani\", SCAN_FILES, false);\n for (const auto& filename : animations)\n fs->Delete(animation_path + \"\/\" + filename);\n\n proc = Process(fs->GetProgramDir() + \"AssetImporter\",\n {\"anim\", file_path, animation_path + \"\/out_\" + ToString(\"%ld\", time(nullptr))});\n if (proc.Run() == 0)\n {\n fs->ScanDir(animations, animation_path, \"*.ani\", SCAN_FILES, false);\n\n if (animations.Size())\n LoadAnimation(animation_path + \"\/\" + animations[0]);\n }\n else\n URHO3D_LOGERROR(\"Importing animations failed.\");\n }\n else\n URHO3D_LOGERROR(\"Importing model failed.\");\n }\n};\n\n}\n\nURHO3D_DEFINE_APPLICATION_MAIN(Urho3D::AssetViewer);\n<commit_msg>Tools: Get rid of Urho3DAll.h usage in AssetViewer.<commit_after>\/\/\n\/\/ Copyright (c) 2018 Rokas Kupstys\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n\/\/ THE SOFTWARE.\n\/\/\n\n#include <CLI11\/CLI11.hpp>\n#include <Urho3D\/Core\/CoreEvents.h>\n#include <Urho3D\/Engine\/Application.h>\n#include <Urho3D\/Engine\/EngineDefs.h>\n#include <Urho3D\/Graphics\/AnimatedModel.h>\n#include <Urho3D\/Graphics\/AnimationController.h>\n#include <Urho3D\/Graphics\/Camera.h>\n#include <Urho3D\/Graphics\/Light.h>\n#include <Urho3D\/Graphics\/Octree.h>\n#include <Urho3D\/Graphics\/Renderer.h>\n#include <Urho3D\/Graphics\/Viewport.h>\n#include <Urho3D\/Graphics\/Zone.h>\n#include <Urho3D\/Input\/Input.h>\n#include <Urho3D\/IO\/FileSystem.h>\n#include <Urho3D\/Resource\/ResourceCache.h>\n#include <Urho3D\/Scene\/Scene.h>\n#include <Urho3D\/SystemUI\/SystemUI.h>\n#include <Toolbox\/SystemUI\/Gizmo.h>\n#include <ctime>\n#include <cstdio>\n#include <Urho3D\/IO\/Log.h>\n\n\nusing namespace std::placeholders;\n\nnamespace Urho3D\n{\n\nclass AssetViewer\n : public Application\n{\n URHO3D_OBJECT(AssetViewer, Application);\npublic:\n SharedPtr<Scene> scene_;\n SharedPtr<Viewport> viewport_;\n SharedPtr<Light> light_;\n WeakPtr<Camera> camera_;\n WeakPtr<Node> node_;\n WeakPtr<Node> parentNode_;\n WeakPtr<AnimatedModel> model_;\n WeakPtr<AnimationController> animator_;\n float lookSensitivity_ = 1.0f;\n Gizmo gizmo_;\n bool showHelp_ = false;\n std::string assetFile_;\n\n explicit AssetViewer(Context* context)\n : Application(context), gizmo_(context)\n {\n }\n\n void Setup() override\n {\n engineParameters_[EP_WINDOW_TITLE] = GetTypeName();\n engineParameters_[EP_WINDOW_WIDTH] = 1024;\n engineParameters_[EP_WINDOW_HEIGHT] = 768;\n engineParameters_[EP_FULL_SCREEN] = false;\n engineParameters_[EP_HEADLESS] = false;\n engineParameters_[EP_SOUND] = false;\n engineParameters_[EP_RESOURCE_PATHS] = \"CoreData\";\n engineParameters_[EP_RESOURCE_PREFIX_PATHS] = \";..;..\/..\";\n engineParameters_[EP_WINDOW_RESIZABLE] = true;\n\n GetCommandLineParser().add_option(\"asset\", assetFile_, \"Asset file to be opened on application startup.\");\n }\n\n void Start() override\n {\n ui::GetIO().IniFilename = nullptr; \/\/ Disable saving of settings.\n\n GetInput()->SetMouseVisible(true);\n GetInput()->SetMouseMode(MM_ABSOLUTE);\n\n scene_ = new Scene(context_);\n scene_->CreateComponent<Octree>();\n auto zone = scene_->CreateComponent<Zone>();\n zone->SetFogColor(Color(0.5f, 0.5f, 0.7f));\n camera_ = scene_->CreateChild(\"Camera\")->CreateComponent<Camera>();\n light_ = camera_->GetNode()->CreateComponent<Light>();\n light_->SetColor(Color::WHITE);\n light_->SetLightType(LIGHT_DIRECTIONAL);\n\n viewport_ = new Viewport(context_, scene_, camera_);\n GetSubsystem<Renderer>()->SetViewport(0, viewport_);\n\n \/\/ Parent node used to rotate model around it's center (not origin).\n parentNode_ = scene_->CreateChild();\n\n GetSystemUI()->ApplyStyleDefault(true, 1);\n ui::GetStyle().WindowRounding = 0;\n\n SubscribeToEvent(E_UPDATE, std::bind(&AssetViewer::OnUpdate, this, _2));\n SubscribeToEvent(E_DROPFILE, std::bind(&AssetViewer::OnFileDrop, this, _2));\n\n if (!assetFile_.empty())\n LoadFile(assetFile_.c_str());\n }\n\n void OnUpdate(VariantMap& args)\n {\n if (node_.Null())\n return;\n\n if (!GetSystemUI()->IsAnyItemActive() && !GetSystemUI()->IsAnyItemHovered())\n {\n auto input = GetSubsystem<Input>();\n\n if (!input->GetKeyDown(KEY_SHIFT))\n {\n if (input->GetMouseButtonDown(MOUSEB_RIGHT))\n {\n if (input->IsMouseVisible())\n input->SetMouseVisible(false);\n\n if (input->GetMouseMove() != IntVector2::ZERO)\n {\n camera_->GetNode()->RotateAround(Vector3::ZERO,\n Quaternion(input->GetMouseMoveX() * 0.1f * lookSensitivity_, camera_->GetNode()->GetUp()) *\n Quaternion(input->GetMouseMoveY() * 0.1f * lookSensitivity_, camera_->GetNode()->GetRight()), TS_WORLD);\n }\n }\n else if (input->GetMouseButtonDown(MOUSEB_MIDDLE))\n {\n if (input->IsMouseVisible())\n input->SetMouseVisible(false);\n\n node_->Translate2D(Vector2(input->GetMouseMoveX(), -input->GetMouseMoveY()) \/ 300.f, TS_WORLD);\n }\n else if (!input->IsMouseVisible())\n input->SetMouseVisible(true);\n\n camera_->GetNode()->Translate(Vector3::FORWARD * input->GetMouseMoveWheel() * 0.2f);\n }\n else if (!input->IsMouseVisible())\n input->SetMouseVisible(true);\n }\n\n if (GetInput()->GetKeyPress(KEY_F1))\n showHelp_ = true;\n\n\n ui::SetNextWindowPos({0, 0}, ImGuiCond_Always);\n if (ui::Begin(\"Settings\", nullptr,\n ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoTitleBar |\n ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoSavedSettings))\n {\n gizmo_.RenderUI();\n\n if (ui::Button(\"Reset\"))\n ResetNode();\n\n \/\/ Window has to contain controls already in order for it's size to be set to match contents.\n ui::SetWindowSize({0, 0}, ImGuiCond_Always);\n }\n ui::End();\n\n if (showHelp_)\n {\n if (ui::Begin(\"Help\", &showHelp_, ImGuiWindowFlags_NoSavedSettings))\n {\n ui::TextUnformatted(\"RMB: hold it rotates model around its center.\");\n ui::TextUnformatted(\"Shift: holding it provides manipulation gizmo at model origin.\");\n }\n ui::End();\n }\n\n if (node_ && GetInput()->GetKeyDown(KEY_SHIFT))\n gizmo_.Manipulate(camera_, parentNode_);\n }\n\n void OnFileDrop(VariantMap& args)\n {\n LoadFile(args[DropFile::P_FILENAME].GetString());\n }\n\n void LoadFile(const String& file_path)\n {\n if (file_path.EndsWith(\".mdl\"))\n LoadModel(file_path);\n else if (file_path.EndsWith(\".ani\"))\n LoadAnimation(file_path);\n else if (file_path.EndsWith(\".fbx\"))\n LoadFbx(file_path);\n }\n\n void LoadModel(const String& file_path, const Vector<String>& materials = { })\n {\n if (node_.NotNull())\n node_->Remove();\n\n node_ = parentNode_->CreateChild(\"Node\");\n model_ = node_->CreateComponent<AnimatedModel>();\n animator_ = node_->CreateComponent<AnimationController>();\n\n auto cache = GetSubsystem<ResourceCache>();\n model_->SetModel(cache->GetTempResource<Model>(file_path));\n\n ResetNode();\n\n for (auto i = 0; i < materials.Size(); i++)\n model_->SetMaterial(i, cache->GetTempResource<Material>(materials[i]));\n }\n\n void ResetNode()\n {\n if (node_.NotNull())\n {\n parentNode_->SetScale(1.f);\n parentNode_->SetPosition(Vector3::ZERO);\n parentNode_->SetRotation(Quaternion::IDENTITY);\n \/\/ Scale model to size of 1 unit\n auto size = model_->GetBoundingBox().Size();\n node_->SetScale(1.f \/ Max(size.x_, Max(size.y_, size.z_)));\n \/\/ Snap center of the model to {0,0,0}\n node_->SetWorldPosition(node_->GetWorldPosition() - model_->GetWorldBoundingBox().Center());\n node_->SetRotation(Quaternion::IDENTITY);\n\n camera_->GetNode()->LookAt(Vector3::ZERO);\n camera_->GetNode()->SetRotation(Quaternion::IDENTITY);\n camera_->GetNode()->SetPosition(Vector3::BACK * 1.5f);\n }\n }\n\n void LoadAnimation(const String& file_path)\n {\n if (animator_)\n animator_->PlayExclusive(file_path, 0, true);\n }\n\n void LoadFbx(const String& file_path)\n {\n auto fs = GetSubsystem<FileSystem>();\n String temp = fs->GetTemporaryDir();\n temp += \"AssetViewer\/\";\n if (!fs->DirExists(temp))\n {\n fs->CreateDir(temp);\n fs->CreateDir(temp + \"\/mdl\");\n fs->CreateDir(temp + \"\/ani\");\n }\n auto animation_path = temp + \"\/ani\";\n auto model_file = temp + \"\/mdl\/out.mdl\";\n auto material_list_file = temp + \"\/mdl\/out.txt\";\n fs->Delete(model_file);\n\n Process proc(fs->GetProgramDir() + \"AssetImporter\", {\"model\", file_path, model_file.CString(), \"-na\", \"-l\"});\n if (proc.Run() == 0)\n {\n if (fs->FileExists(model_file))\n {\n Vector<String> materials;\n File fp(context_, material_list_file);\n if (fp.IsOpen())\n {\n while (!fp.IsEof())\n materials.Push(temp + \"\/mdl\/\" + fp.ReadLine());\n }\n LoadModel(model_file, materials);\n }\n\n Vector<String> animations;\n fs->ScanDir(animations, animation_path, \"*.ani\", SCAN_FILES, false);\n for (const auto& filename : animations)\n fs->Delete(animation_path + \"\/\" + filename);\n\n proc = Process(fs->GetProgramDir() + \"AssetImporter\",\n {\"anim\", file_path, animation_path + \"\/out_\" + ToString(\"%ld\", time(nullptr))});\n if (proc.Run() == 0)\n {\n fs->ScanDir(animations, animation_path, \"*.ani\", SCAN_FILES, false);\n\n if (animations.Size())\n LoadAnimation(animation_path + \"\/\" + animations[0]);\n }\n else\n URHO3D_LOGERROR(\"Importing animations failed.\");\n }\n else\n URHO3D_LOGERROR(\"Importing model failed.\");\n }\n};\n\n}\n\nURHO3D_DEFINE_APPLICATION_MAIN(Urho3D::AssetViewer);\n<|endoftext|>"} {"text":"<commit_before>#include <clw\/clw.h>\n#include <iostream>\n#include <string>\n\nstd::string deviceTypeName(clw::EDeviceType type)\n{\n switch(type)\n {\n case clw::Cpu: return std::string(\"Cpu\");\n case clw::Gpu: return std::string(\"Gpu\");\n case clw::Accelerator: return std::string(\"Accelerator\"); \n case clw::Custom: return std::string(\"Custom\");\n default: return std::string(\"Undefined\");\n }\n}\n\nstd::string boolName(bool v)\n{\n return v ? std::string(\"yes\") : std::string(\"no\");\n}\n\nstd::string cacheTypeName(clw::ECacheType type)\n{\n switch(type)\n {\n case clw::Cache_NoChache: return \"No chache\";\n case clw::Cache_ReadOnlyCache: return \"Read-only cache\";\n case clw::Cache_ReadWriteCache: return \"Read-write cache\";\n default: return std::string(\"Undefined\");\n }\n}\n\nstd::string floatCapabilitiesName(clw::EFloatCapabilities caps)\n{\n std::string accum;\n if(caps & clw::Capability_Denorm)\n accum += \"Denorm \";\n if(caps & clw::Capability_InfinityAndNaN)\n accum += \"InfinityAndNaN \";\n if(caps & clw::Capability_RoundToNearest)\n accum += \"RoundToNearest \";\n if(caps & clw::Capability_RoundToZero)\n accum += \"RoundToZero \";\n if(caps & clw::Capability_RoundToInf)\n accum += \"RoundToInf \";\n if(caps & clw::Capability_FusedMultiplyAdd)\n accum += \"FusedMultiplyAdd \";\n if(caps & clw::Capability_CorrectlyRoundedDivideSqrt)\n accum += \"CorrectlyRoundedDivideSqrt \";\n if(caps & clw::Capability_SoftwareFloat)\n accum += \"SoftwareFloat \";\n\n if(accum.empty())\n accum += \"Not supported\";\n return accum;\n}\n\nstd::string memorySizeName(uint64_t memSize)\n{\n#if defined(_MSC_VER)\n# define snprintf _snprintf\n#endif\n char buf[64];\n if(memSize >= 1024 * 1024)\n snprintf(buf, sizeof(buf)\/sizeof(char), \"%d MB\", int(memSize \/ (1024 * 1024)));\n else\n snprintf(buf, sizeof(buf)\/sizeof(char), \"%d kB\", int(memSize \/ 1024));\n return std::string(buf);\n}\n\nint main()\n{\n auto platforms = clw::availablePlatforms();\n for(const clw::Platform& platform : platforms)\n {\n std::cout << \"OpenCL Platform:\\n\";\n std::cout << \" Profile : \" << platform.profile() << std::endl;\n std::cout << \" Version : \" << platform.versionString() << std::endl;\n std::cout << \" Name : \" << platform.name() << std::endl;\n std::cout << \" Vendor : \" << platform.vendor() << std::endl;\n std::cout << \" Extension suffix : \" << platform.extensionSuffix() << std::endl;\n\n auto exts = platform.extensions();\n std::cout << \" Extensions : (\" << exts.size() << \")\\n\";\n for(const std::string& extension : exts)\n std::cout << \" \" << extension << std::endl;\n std::cout << \"\\n\";\n\n auto devices = clw::devices(clw::All, platform);\n for(const clw::Device& device : devices)\n {\n std::cout << \"OpenCL Device: (available: \" << boolName(device.isAvailable()) << \")\\n\";\n std::cout << \" Name : \" << device.name() << std::endl;\n std::cout << \" Version : \" << device.version() << std::endl;\n std::cout << \" Vendor : \" << device.vendor() << std::endl;\n std::cout << \" Device type : \" << deviceTypeName(device.deviceType()) << std::endl;\t\t\t\t\t\t\t\t\t\t\t \n std::cout << \" Driver version : \" << device.driverVersion() << std::endl;\n std::cout << \" Language version : \" << device.languageVersion() << std::endl;\n std::cout << \" Is compiler available : \" << boolName(device.isCompilerAvailable()) << std::endl;\n std::cout << \" Supports double : \" << boolName(device.supportsDouble()) << std::endl;\n std::cout << \" Supports half float : \" << boolName(device.supportsHalf()) << std::endl;\n std::cout << \" Supports error correction : \" << boolName(device.supportsErrorCorrection()) << std::endl;\n std::cout << \" Supports native kernel : \" << boolName(device.supportsNativeKernel()) << std::endl;\n std::cout << \" Supports out of order exec. : \" << boolName(device.supportsOutOfOrderExecution()) << std::endl;\n std::cout << \" Supports images : \" << boolName(device.supportsImages()) << std::endl;\n std::cout << \" Is unified memory : \" << boolName(device.isUnifiedMemory()) << std::endl;\n std::cout << \" Separate local memory : \" << boolName(device.isLocalMemorySeparate()) << std::endl;\n std::cout << \" Address bitness : \" << device.addressBitness() << std::endl;\n std::cout << \" Endianess : \" << (device.isLittleEndian() ? \"little\" : \"big\") << std::endl;\n std::cout << \" Clock frequency : \" << device.clockFrequency() << \" MHz\" << std::endl;\n std::cout << \" Compute units : \" << device.computeUnits() << std::endl;\n std::cout << \" Default alignment : \" << device.defaultAlignment() << \" bits\" << std::endl;\n std::cout << \" Minimum alignment : \" << device.minimumAlignment() << \" bytes\" << std::endl;\n\t\t\tstd::cout << \" Float capabilities : \" << floatCapabilitiesName(device.floatCapabilities()) << std::endl;\n std::cout << \" Double capabilities : \" << floatCapabilitiesName(device.doubleCapabilities()) << std::endl;\n std::cout << \" Half capabilities : \" << floatCapabilitiesName(device.halfCapabilities()) << std::endl;\n std::cout << \" GMEM cache size : \" << memorySizeName(device.globalMemoryCacheSize()) << std::endl;\n std::cout << \" GMEM cache line size : \" << device.globalMemoryCacheLineSize() << \" bytes\" << std::endl;\n std::cout << \" GMEM cache type : \" << cacheTypeName(device.globalMemoryCacheType()) << std::endl;\n std::cout << \" GMEM size : \" << memorySizeName(device.globalMemorySize()) << std::endl;\n std::cout << \" LMEM size : \" << memorySizeName(device.localMemorySize()) << std::endl;\n std::cout << \" Max. single allocation size : \" << memorySizeName(device.maximumAllocationSize()) << std::endl;\n std::cout << \" Max. image 2D size : \" << device.maximumImage2DSize() << std::endl;\n std::cout << \" Max. image 3D size : \" << device.maximumImage3DSize() << std::endl;\n std::cout << \" Max. images (read) : \" << device.maximumReadImages() << std::endl;\n std::cout << \" Max. images (write) : \" << device.maximumWriteImages() << std::endl;\n std::cout << \" Max. samplers : \" << device.maximumSamplers() << std::endl;\n std::cout << \" Max. const arguments : \" << device.maximumConstantArguments() << std::endl;\n std::cout << \" Max. constant buffer size : \" << memorySizeName(device.maximumConstantBufferSize()) << std::endl;\n std::cout << \" Max. parameter size : \" << device.maximumParameterBytes() << \" bytes\" << std::endl;\n std::cout << \" Max. work items : \" << device.maximumWorkItemSize() << std::endl;\n std::cout << \" Max. work items per group : \" << device.maximumWorkItemsPerGroup() << std::endl;\n std::cout << \" Timer resolution : \" << device.profilingTimerResolution() << \" nsec\" << std::endl;\n std::cout << \" Native vectors width : char\" << device.nativeCharVectorWidth()\n << \" short\" << device.nativeShortVectorWidth() \n << \" int\" << device.nativeIntVectorWidth() \n << \" long\" << device.nativeLongVectorWidth() \n << \" float\" << device.nativeFloatVectorWidth() \n << \" double\" << device.nativeDoubleVectorWidth() \n << \" half\" << device.nativeHalfVectorWidth()\n << std::endl;\n std::cout << \" Preferred vectors width : char\" << device.preferredCharVectorWidth()\n << \" short\" << device.preferredShortVectorWidth() \n << \" int\" << device.preferredIntVectorWidth() \n << \" long\" << device.preferredLongVectorWidth() \n << \" float\" << device.preferredFloatVectorWidth() \n << \" double\" << device.preferredDoubleVectorWidth() \n << \" half\" << device.preferredHalfVectorWidth()\n << std::endl;\n\n \/\/ Radeons specific device attributes\n if(device.vendor() == std::string(\"Advanced Micro Devices, Inc.\") &&\n device.deviceType() == clw::Gpu)\n {\n auto gmemFree = device.globalFreeMemory();\n std::cout << \" AMD specific : \" << std::endl;\n std::cout << \" Board name : \" << device.boardName() << std::endl;\n if(gmemFree.size() == 2)\n std::cout << \" Free GMEM : \" << memorySizeName(gmemFree[1] * 1024) \n << \"\/\" << memorySizeName(gmemFree[0] * 1024) << std::endl;\n std::cout << \" SIMD per Compute Unit : \" << device.simdPerComputeUnit() << std::endl;\n std::cout << \" SIMD width : \" << device.simdWidth() << std::endl;\n std::cout << \" SIMD Instruction width : \" << device.simdInstructionWidth() << std::endl;\n std::cout << \" Wavefront width : \" << device.wavefrontWidth() << std::endl;\n std::cout << \" GMEM channels : \" << device.globalMemoryChannels() << std::endl;\n std::cout << \" GMEM channel banks : \" << device.globalMemoryChannelBanks() << std::endl;\n std::cout << \" GMEM channel bank width : \" << device.globalMemoryChannelBankWidth() << std::endl;\t\t\t\t\t\t\t\t\t\t\t \n std::cout << \" LMEM size per CU : \" << device.localMemorySizePerComputeUnit() << std::endl;\t\t\t\t\t\t\t\t\t\t\t \n std::cout << \" LMEM memory banks : \" << device.localMemoryBanks() << std::endl;\t\t\t\t\n }\n else if(device.vendor() == std::string(\"NVIDIA\") &&\n device.deviceType() == clw::Gpu)\n {\n std::cout << \" NVIDIA specific : \" << std::endl;\n std::cout << \" Compute Capability : \" << device.computeCapabilityMajor() << \".\" << device.computeCapabilityMinor() << std::endl;\n std::cout << \" Registers per Block : \" << device.registersPerBlock() << std::endl;\n std::cout << \" Warp size : \" << device.warpSize() << std::endl;\n std::cout << \" GPU overlap : \" << device.gpuOverlap() << std::endl;\n std::cout << \" Kernel execution timeout : \" << device.kernelExecutionTimeout() << std::endl;\n std::cout << \" Integrated memory : \" << device.integratedMemory() << std::endl;\n }\n\n auto exts = device.extensions();\n std::cout << \" Extensions : (\" << exts.size() << \")\\n\";\n for(const std::string& extension : exts)\n std::cout << \" \" << extension << std::endl;\n std::cout << \"\\n\";\n }\n std::cout << \"\\n\";\n }\n\n return 0;\n}<commit_msg>fixed tabs<commit_after>#include <clw\/clw.h>\n#include <iostream>\n#include <string>\n\nstd::string deviceTypeName(clw::EDeviceType type)\n{\n switch(type)\n {\n case clw::Cpu: return std::string(\"Cpu\");\n case clw::Gpu: return std::string(\"Gpu\");\n case clw::Accelerator: return std::string(\"Accelerator\"); \n case clw::Custom: return std::string(\"Custom\");\n default: return std::string(\"Undefined\");\n }\n}\n\nstd::string boolName(bool v)\n{\n return v ? std::string(\"yes\") : std::string(\"no\");\n}\n\nstd::string cacheTypeName(clw::ECacheType type)\n{\n switch(type)\n {\n case clw::Cache_NoChache: return \"No chache\";\n case clw::Cache_ReadOnlyCache: return \"Read-only cache\";\n case clw::Cache_ReadWriteCache: return \"Read-write cache\";\n default: return std::string(\"Undefined\");\n }\n}\n\nstd::string floatCapabilitiesName(clw::EFloatCapabilities caps)\n{\n std::string accum;\n if(caps & clw::Capability_Denorm)\n accum += \"Denorm \";\n if(caps & clw::Capability_InfinityAndNaN)\n accum += \"InfinityAndNaN \";\n if(caps & clw::Capability_RoundToNearest)\n accum += \"RoundToNearest \";\n if(caps & clw::Capability_RoundToZero)\n accum += \"RoundToZero \";\n if(caps & clw::Capability_RoundToInf)\n accum += \"RoundToInf \";\n if(caps & clw::Capability_FusedMultiplyAdd)\n accum += \"FusedMultiplyAdd \";\n if(caps & clw::Capability_CorrectlyRoundedDivideSqrt)\n accum += \"CorrectlyRoundedDivideSqrt \";\n if(caps & clw::Capability_SoftwareFloat)\n accum += \"SoftwareFloat \";\n\n if(accum.empty())\n accum += \"Not supported\";\n return accum;\n}\n\nstd::string memorySizeName(uint64_t memSize)\n{\n#if defined(_MSC_VER)\n# define snprintf _snprintf\n#endif\n char buf[64];\n if(memSize >= 1024 * 1024)\n snprintf(buf, sizeof(buf)\/sizeof(char), \"%d MB\", int(memSize \/ (1024 * 1024)));\n else\n snprintf(buf, sizeof(buf)\/sizeof(char), \"%d kB\", int(memSize \/ 1024));\n return std::string(buf);\n}\n\nint main()\n{\n auto platforms = clw::availablePlatforms();\n for(const clw::Platform& platform : platforms)\n {\n std::cout << \"OpenCL Platform:\\n\";\n std::cout << \" Profile : \" << platform.profile() << std::endl;\n std::cout << \" Version : \" << platform.versionString() << std::endl;\n std::cout << \" Name : \" << platform.name() << std::endl;\n std::cout << \" Vendor : \" << platform.vendor() << std::endl;\n std::cout << \" Extension suffix : \" << platform.extensionSuffix() << std::endl;\n\n auto exts = platform.extensions();\n std::cout << \" Extensions : (\" << exts.size() << \")\\n\";\n for(const std::string& extension : exts)\n std::cout << \" \" << extension << std::endl;\n std::cout << \"\\n\";\n\n auto devices = clw::devices(clw::All, platform);\n for(const clw::Device& device : devices)\n {\n std::cout << \"OpenCL Device: (available: \" << boolName(device.isAvailable()) << \")\\n\";\n std::cout << \" Name : \" << device.name() << std::endl;\n std::cout << \" Version : \" << device.version() << std::endl;\n std::cout << \" Vendor : \" << device.vendor() << std::endl;\n std::cout << \" Device type : \" << deviceTypeName(device.deviceType()) << std::endl;\t\t\t\t\t\t\t\t\t\t\t \n std::cout << \" Driver version : \" << device.driverVersion() << std::endl;\n std::cout << \" Language version : \" << device.languageVersion() << std::endl;\n std::cout << \" Is compiler available : \" << boolName(device.isCompilerAvailable()) << std::endl;\n std::cout << \" Supports double : \" << boolName(device.supportsDouble()) << std::endl;\n std::cout << \" Supports half float : \" << boolName(device.supportsHalf()) << std::endl;\n std::cout << \" Supports error correction : \" << boolName(device.supportsErrorCorrection()) << std::endl;\n std::cout << \" Supports native kernel : \" << boolName(device.supportsNativeKernel()) << std::endl;\n std::cout << \" Supports out of order exec. : \" << boolName(device.supportsOutOfOrderExecution()) << std::endl;\n std::cout << \" Supports images : \" << boolName(device.supportsImages()) << std::endl;\n std::cout << \" Is unified memory : \" << boolName(device.isUnifiedMemory()) << std::endl;\n std::cout << \" Separate local memory : \" << boolName(device.isLocalMemorySeparate()) << std::endl;\n std::cout << \" Address bitness : \" << device.addressBitness() << std::endl;\n std::cout << \" Endianess : \" << (device.isLittleEndian() ? \"little\" : \"big\") << std::endl;\n std::cout << \" Clock frequency : \" << device.clockFrequency() << \" MHz\" << std::endl;\n std::cout << \" Compute units : \" << device.computeUnits() << std::endl;\n std::cout << \" Default alignment : \" << device.defaultAlignment() << \" bits\" << std::endl;\n std::cout << \" Minimum alignment : \" << device.minimumAlignment() << \" bytes\" << std::endl;\n std::cout << \" Float capabilities : \" << floatCapabilitiesName(device.floatCapabilities()) << std::endl;\n std::cout << \" Double capabilities : \" << floatCapabilitiesName(device.doubleCapabilities()) << std::endl;\n std::cout << \" Half capabilities : \" << floatCapabilitiesName(device.halfCapabilities()) << std::endl;\n std::cout << \" GMEM cache size : \" << memorySizeName(device.globalMemoryCacheSize()) << std::endl;\n std::cout << \" GMEM cache line size : \" << device.globalMemoryCacheLineSize() << \" bytes\" << std::endl;\n std::cout << \" GMEM cache type : \" << cacheTypeName(device.globalMemoryCacheType()) << std::endl;\n std::cout << \" GMEM size : \" << memorySizeName(device.globalMemorySize()) << std::endl;\n std::cout << \" LMEM size : \" << memorySizeName(device.localMemorySize()) << std::endl;\n std::cout << \" Max. single allocation size : \" << memorySizeName(device.maximumAllocationSize()) << std::endl;\n std::cout << \" Max. image 2D size : \" << device.maximumImage2DSize() << std::endl;\n std::cout << \" Max. image 3D size : \" << device.maximumImage3DSize() << std::endl;\n std::cout << \" Max. images (read) : \" << device.maximumReadImages() << std::endl;\n std::cout << \" Max. images (write) : \" << device.maximumWriteImages() << std::endl;\n std::cout << \" Max. samplers : \" << device.maximumSamplers() << std::endl;\n std::cout << \" Max. const arguments : \" << device.maximumConstantArguments() << std::endl;\n std::cout << \" Max. constant buffer size : \" << memorySizeName(device.maximumConstantBufferSize()) << std::endl;\n std::cout << \" Max. parameter size : \" << device.maximumParameterBytes() << \" bytes\" << std::endl;\n std::cout << \" Max. work items : \" << device.maximumWorkItemSize() << std::endl;\n std::cout << \" Max. work items per group : \" << device.maximumWorkItemsPerGroup() << std::endl;\n std::cout << \" Timer resolution : \" << device.profilingTimerResolution() << \" nsec\" << std::endl;\n std::cout << \" Native vectors width : char\" << device.nativeCharVectorWidth()\n << \" short\" << device.nativeShortVectorWidth() \n << \" int\" << device.nativeIntVectorWidth() \n << \" long\" << device.nativeLongVectorWidth() \n << \" float\" << device.nativeFloatVectorWidth() \n << \" double\" << device.nativeDoubleVectorWidth() \n << \" half\" << device.nativeHalfVectorWidth()\n << std::endl;\n std::cout << \" Preferred vectors width : char\" << device.preferredCharVectorWidth()\n << \" short\" << device.preferredShortVectorWidth() \n << \" int\" << device.preferredIntVectorWidth() \n << \" long\" << device.preferredLongVectorWidth() \n << \" float\" << device.preferredFloatVectorWidth() \n << \" double\" << device.preferredDoubleVectorWidth() \n << \" half\" << device.preferredHalfVectorWidth()\n << std::endl;\n\n \/\/ Radeons specific device attributes\n if(device.vendor() == std::string(\"Advanced Micro Devices, Inc.\") &&\n device.deviceType() == clw::Gpu)\n {\n auto gmemFree = device.globalFreeMemory();\n std::cout << \" AMD specific : \" << std::endl;\n std::cout << \" Board name : \" << device.boardName() << std::endl;\n if(gmemFree.size() == 2)\n std::cout << \" Free GMEM : \" << memorySizeName(gmemFree[1] * 1024) \n << \"\/\" << memorySizeName(gmemFree[0] * 1024) << std::endl;\n std::cout << \" SIMD per Compute Unit : \" << device.simdPerComputeUnit() << std::endl;\n std::cout << \" SIMD width : \" << device.simdWidth() << std::endl;\n std::cout << \" SIMD Instruction width : \" << device.simdInstructionWidth() << std::endl;\n std::cout << \" Wavefront width : \" << device.wavefrontWidth() << std::endl;\n std::cout << \" GMEM channels : \" << device.globalMemoryChannels() << std::endl;\n std::cout << \" GMEM channel banks : \" << device.globalMemoryChannelBanks() << std::endl;\n std::cout << \" GMEM channel bank width : \" << device.globalMemoryChannelBankWidth() << std::endl;\t\t\t\t\t\t\t\t\t\t\t \n std::cout << \" LMEM size per CU : \" << device.localMemorySizePerComputeUnit() << std::endl;\t\t\t\t\t\t\t\t\t\t\t \n std::cout << \" LMEM memory banks : \" << device.localMemoryBanks() << std::endl;\t\t\t\t\n }\n else if(device.vendor() == std::string(\"NVIDIA\") &&\n device.deviceType() == clw::Gpu)\n {\n std::cout << \" NVIDIA specific : \" << std::endl;\n std::cout << \" Compute Capability : \" << device.computeCapabilityMajor() << \".\" << device.computeCapabilityMinor() << std::endl;\n std::cout << \" Registers per Block : \" << device.registersPerBlock() << std::endl;\n std::cout << \" Warp size : \" << device.warpSize() << std::endl;\n std::cout << \" GPU overlap : \" << device.gpuOverlap() << std::endl;\n std::cout << \" Kernel execution timeout : \" << device.kernelExecutionTimeout() << std::endl;\n std::cout << \" Integrated memory : \" << device.integratedMemory() << std::endl;\n }\n\n auto exts = device.extensions();\n std::cout << \" Extensions : (\" << exts.size() << \")\\n\";\n for(const std::string& extension : exts)\n std::cout << \" \" << extension << std::endl;\n std::cout << \"\\n\";\n }\n std::cout << \"\\n\";\n }\n\n return 0;\n}<|endoftext|>"} {"text":"<commit_before>\/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying\n file Copyright.txt or https:\/\/opensource.org\/licenses\/BSD-3-Clause for\n details. *\/\n\n#include <algorithm>\n#include <cctype>\n#include <fstream>\n#include <functional>\n#include <iostream>\n#include <memory>\n#include <regex>\n#include <string>\n#include <utility>\n#include <vector>\n\n#include \"parser.h\"\n\nusing namespace std::placeholders;\n\nvoid replace_all_in_string(std::string &main_string, const std::string &from,\n const std::string &to) {\n\tsize_t pos = 0;\n\twhile ((pos = main_string.find(from, pos)) != std::string::npos) {\n\t\tmain_string.replace(pos, from.size(), to);\n\t}\n}\n\nstd::string lowerstring(const std::string &val) {\n\tstd::string newval = val;\n\tstd::transform(newval.begin(), newval.end(), newval.begin(),\n\t [](char c) { return std::tolower(c); });\n\treturn newval;\n}\n\nstd::string repeat_string(const std::string &val, size_t n) {\n\tstd::string newval;\n\tfor (size_t i = 0; i < n; i++) {\n\t\tnewval += val;\n\t}\n\treturn newval;\n}\n\nusing FormatterFunction = std::function<void(const std::vector<Command> &, std::vector<Span> &)>;\n\nclass Formatter {\n public:\n\tvirtual ~Formatter() = default;\n\tvirtual std::vector<std::pair<std::string, std::string>> describeCommandLine() = 0;\n\tvirtual bool handleCommandLine(const std::string &arg,\n\t std::vector<FormatterFunction> &formatter_functions) = 0;\n};\n\nclass FormatterIndent : public Formatter {\n\tstd::vector<std::pair<std::string, std::string>> describeCommandLine() override {\n\t\treturn {{\"-indent=STRING\", \"Use STRING for indentation.\"}};\n\t}\n\n\tbool handleCommandLine(const std::string &arg,\n\t std::vector<FormatterFunction> &formatter_functions) override {\n\t\tif (arg.find(\"-indent=\") != 0) {\n\t\t\treturn false;\n\t\t}\n\n\t\tstd::string indent_string = arg.substr(std::string{\"-indent=\"}.size());\n\t\treplace_all_in_string(indent_string, \"\\\\t\", \"\\t\");\n\t\tformatter_functions.emplace_back(std::bind(run, _1, _2, indent_string));\n\n\t\treturn true;\n\t};\n\n\tstatic void run(const std::vector<Command> &commands, std::vector<Span> &spans,\n\t const std::string &indent_string) {\n\t\tint global_indentation_level = 0;\n\t\tfor (auto c : commands) {\n\t\t\tconst std::string ident = lowerstring(spans[c.identifier].data);\n\n\t\t\tif (ident == \"endif\" || ident == \"endforeach\" || ident == \"endwhile\" ||\n\t\t\t ident == \"endmacro\" || ident == \"endfunction\") {\n\t\t\t\tglobal_indentation_level--;\n\t\t\t}\n\n\t\t\tauto indentation_level = global_indentation_level;\n\t\t\tif (ident == \"else\" || ident == \"elseif\") {\n\t\t\t\tindentation_level--;\n\t\t\t}\n\n\t\t\tconst std::string old_indentation = spans[c.identifier - 1].data;\n\n\t\t\t\/\/ Re-indent the command invocation\n\t\t\tspans[c.identifier - 1].data = repeat_string(indent_string, indentation_level);\n\n\t\t\t\/\/ Walk forwards to fix arguments and the closing paren.\n\t\t\tsize_t next_token = c.identifier + 1;\n\t\t\twhile (true) {\n\t\t\t\tif (spans[next_token].type == SpanType::Newline) {\n\t\t\t\t\tsize_t old_indentation_pos = spans[next_token + 1].data.find(old_indentation);\n\t\t\t\t\tif (old_indentation_pos != 0) {\n\t\t\t\t\t} else {\n\t\t\t\t\t\tspans[next_token + 1].data =\n\t\t\t\t\t\t (repeat_string(indent_string, indentation_level) +\n\t\t\t\t\t\t spans[next_token + 1].data.substr(old_indentation.size()));\n\t\t\t\t\t}\n\t\t\t\t\tnext_token++;\n\t\t\t\t} else if (spans[next_token].type == SpanType::Lparen) {\n\t\t\t\t\tbreak;\n\t\t\t\t} else {\n\t\t\t\t\tnext_token++;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t\/\/ Walk backwards to fix comments at the same prior indentation\n\t\t\t\/\/ level.\n\t\t\tsize_t last_token_on_previous_line = c.identifier - 3;\n\t\t\twhile (true) {\n\t\t\t\tif (spans[last_token_on_previous_line].type == SpanType::Comment &&\n\t\t\t\t spans[last_token_on_previous_line - 1].type == SpanType::Space &&\n\t\t\t\t spans[last_token_on_previous_line - 2].type == SpanType::Newline) {\n\t\t\t\t\tspans[last_token_on_previous_line - 1].data =\n\t\t\t\t\t repeat_string(indent_string, indentation_level);\n\t\t\t\t\tlast_token_on_previous_line -= 3;\n\t\t\t\t} else if (spans[last_token_on_previous_line].type == SpanType::Space &&\n\t\t\t\t spans[last_token_on_previous_line - 1].type == SpanType::Newline) {\n\t\t\t\t\tlast_token_on_previous_line -= 2;\n\t\t\t\t} else if (spans[last_token_on_previous_line].type == SpanType::Newline) {\n\t\t\t\t\tlast_token_on_previous_line -= 1;\n\t\t\t\t} else {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (ident == \"if\" || ident == \"foreach\" || ident == \"while\" || ident == \"macro\" ||\n\t\t\t ident == \"function\") {\n\t\t\t\tglobal_indentation_level++;\n\t\t\t}\n\t\t}\n\t}\n};\n\nclass FormatterIndentArgument : public Formatter {\n\tstd::vector<std::pair<std::string, std::string>> describeCommandLine() override {\n\t\treturn {\n\t\t {\"-indent-arguments=align-paren\",\n\t\t \"Align arguments on continuing lines with the command's left parenthesis.\"},\n\t\t {\"-indent-arguments=STRING\", \"Use STRING for indenting arguments on continuing lines.\"},\n\t\t};\n\t}\n\n\tbool handleCommandLine(const std::string &arg,\n\t std::vector<FormatterFunction> &formatter_functions) override {\n\n\t\tif (arg == \"-indent-arguments=align-paren\") {\n\t\t\tformatter_functions.emplace_back(std::bind(run, _1, _2, true, \"\"));\n\t\t\treturn true;\n\t\t}\n\t\tif (arg.find(\"-indent-arguments=\") == 0) {\n\t\t\tstd::string argument_indent_string =\n\t\t\t arg.substr(std::string{\"-indent-arguments=\"}.size());\n\t\t\treplace_all_in_string(argument_indent_string, \"\\\\t\", \"\\t\");\n\t\t\tformatter_functions.emplace_back(std::bind(run, _1, _2, false, argument_indent_string));\n\t\t\treturn true;\n\t\t}\n\n\t\treturn false;\n\t}\n\n\tstatic void run(const std::vector<Command> &commands, std::vector<Span> &spans,\n\t bool argument_indent_after_lparen, std::string argument_indent_string) {\n\n\t\t(void)argument_indent_after_lparen;\n\n\t\tfor (auto c : commands) {\n\t\t\tconst std::string ident = lowerstring(spans[c.identifier].data);\n\n\t\t\tstd::string command_indentation;\n\t\t\tif (spans[c.identifier - 1].type == SpanType::Newline) {\n\t\t\t\tcommand_indentation = \"\";\n\t\t\t} else {\n\t\t\t\tcommand_indentation = spans[c.identifier - 1].data;\n\t\t\t}\n\n\t\t\tif (argument_indent_after_lparen) {\n\t\t\t\targument_indent_string = repeat_string(\" \", ident.size() + 1);\n\t\t\t}\n\n\t\t\t\/\/ Walk forwards to fix argument indents.\n\t\t\tsize_t next_token = c.identifier + 1;\n\t\t\twhile (true) {\n\t\t\t\tif (spans[next_token].type == SpanType::Newline) {\n\t\t\t\t\tif (spans[next_token + 2].type != SpanType::Rparen) {\n\t\t\t\t\t\tspans[next_token + 1].data = command_indentation + argument_indent_string;\n\t\t\t\t\t}\n\t\t\t\t\tnext_token++;\n\t\t\t\t} else if (spans[next_token].type == SpanType::Rparen) {\n\t\t\t\t\tbreak;\n\t\t\t\t} else {\n\t\t\t\t\tnext_token++;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n};\n\nclass FormatterIndentRparen : public Formatter {\n\tstd::vector<std::pair<std::string, std::string>> describeCommandLine() override {\n\t\treturn {{\"-indent-rparen=STRING\", \"Use STRING for indenting hanging right-parens.\"}};\n\t}\n\n\tbool handleCommandLine(const std::string &arg,\n\t std::vector<FormatterFunction> &formatter_functions) override {\n\t\tif (arg.find(\"-indent-rparen=\") != 0) {\n\t\t\treturn false;\n\t\t}\n\n\t\tstd::string rparen_indent_string = arg.substr(std::string{\"-indent-rparen=\"}.size());\n\t\treplace_all_in_string(rparen_indent_string, \"\\\\t\", \"\\t\");\n\n\t\tformatter_functions.emplace_back(std::bind(run, _1, _2, rparen_indent_string));\n\n\t\treturn true;\n\t}\n\n\tstatic void run(const std::vector<Command> &commands, std::vector<Span> &spans,\n\t const std::string &rparen_indent_string) {\n\t\tfor (auto c : commands) {\n\t\t\tconst std::string ident = lowerstring(spans[c.identifier].data);\n\n\t\t\tstd::string command_indentation;\n\t\t\tif (spans[c.identifier - 1].type == SpanType::Newline) {\n\t\t\t\tcommand_indentation = \"\";\n\t\t\t} else {\n\t\t\t\tcommand_indentation = spans[c.identifier - 1].data;\n\t\t\t}\n\n\t\t\t\/\/ Walk forwards to fix continuation indents.\n\t\t\tsize_t next_token = c.identifier + 1;\n\t\t\twhile (true) {\n\t\t\t\tif (spans[next_token].type == SpanType::Rparen) {\n\t\t\t\t\tif (spans[next_token - 2].type == SpanType::Newline) {\n\t\t\t\t\t\tspans[next_token - 1].data = (command_indentation + rparen_indent_string);\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\t} else {\n\t\t\t\t\tnext_token++;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n};\n\nclass FormatterLowercaseCommands : public Formatter {\n\tstd::vector<std::pair<std::string, std::string>> describeCommandLine() override {\n\t\treturn {{\"-lowercase-commands\", \"Lowercase command names in command invocations.\"}};\n\t}\n\n\tbool handleCommandLine(const std::string &arg,\n\t std::vector<FormatterFunction> &formatting_functions) override {\n\t\tif (arg != \"-lowercase-commands\")\n\t\t\treturn false;\n\t\tformatting_functions.emplace_back(formatLowercaseCommands);\n\t\treturn true;\n\t}\n\n\tstatic void formatLowercaseCommands(const std::vector<Command> &commands,\n\t std::vector<Span> &spans) {\n\t\tfor (auto c : commands) {\n\t\t\tspans[c.identifier].data = lowerstring(spans[c.identifier].data);\n\t\t}\n\t}\n};\n\nint main(int argc, char **argv) {\n\n\tstd::vector<std::unique_ptr<Formatter>> formatters;\n\tformatters.emplace_back(new FormatterLowercaseCommands());\n\tformatters.emplace_back(new FormatterIndent());\n\tformatters.emplace_back(new FormatterIndentArgument());\n\tformatters.emplace_back(new FormatterIndentRparen());\n\n\tbool format_in_place = false;\n\tstd::vector<FormatterFunction> formatting_functions;\n\n\tstd::vector<std::string> filenames;\n\tfor (int i = 1; i < argc; i++) {\n\t\tconst std::string arg{argv[i]};\n\t\tif (arg[0] == '-') {\n\t\t\tstd::smatch reindent_match;\n\n\t\t\tif (\"-help\" == arg || \"-h\" == arg || \"--help\" == arg) {\n\t\t\t\tfprintf(stderr,\n\t\t\t\t \"usage: %s [options] [file ...]\\n\"\n\t\t\t\t \"\\n\"\n\t\t\t\t \"Re-formats specified files. If -i is specified, formats files\\n\"\n\t\t\t\t \"in-place; otherwise, writes results to standard output.\\n\"\n\t\t\t\t \"\\n\",\n\t\t\t\t argv[0]);\n\t\t\t\tfprintf(stderr, \"options:\\n\");\n\n\t\t\t\tsize_t max_option_size = 0;\n\t\t\t\tfor (auto const &f : formatters) {\n\t\t\t\t\tfor (auto const p : f->describeCommandLine()) {\n\t\t\t\t\t\tmax_option_size = std::max(max_option_size, p.first.size());\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tfor (auto const &f : formatters) {\n\t\t\t\t\tfor (auto const p : f->describeCommandLine()) {\n\t\t\t\t\t\tstd::string opt;\n\t\t\t\t\t\tstd::string description;\n\t\t\t\t\t\tstd::tie(opt, description) = p;\n\t\t\t\t\t\tfprintf(stderr, \" %s%s %s\\n\", opt.c_str(),\n\t\t\t\t\t\t repeat_string(\" \", max_option_size - opt.size()).c_str(),\n\t\t\t\t\t\t description.c_str());\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tfprintf(stderr, \" %s%s %s\\n\", \"-i\",\n\t\t\t\t repeat_string(\" \", max_option_size - 2).c_str(),\n\t\t\t\t \"Re-format files in-place.\");\n\t\t\t\texit(1);\n\t\t\t} else if (arg == \"-i\") {\n\t\t\t\tformat_in_place = true;\n\t\t\t} else {\n\t\t\t\tbool handled_arg = false;\n\t\t\t\tfor (const auto &f : formatters) {\n\t\t\t\t\tif ((handled_arg = f->handleCommandLine(arg, formatting_functions))) {\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (!handled_arg) {\n\t\t\t\t\tfprintf(stderr, \"%s: unrecognized option '%s'. Try: %s -help\\n\", argv[0],\n\t\t\t\t\t arg.c_str(), argv[0]);\n\t\t\t\t\texit(1);\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tfilenames.emplace_back(arg);\n\t\t}\n\t}\n\n\tif (filenames.size() == 0) {\n\t\tfprintf(stderr, \"%s: no filenames specified. Try: %s -help\\n\", argv[0], argv[0]);\n\t\texit(1);\n\t}\n\n\tif (formatting_functions.size() == 0) {\n\t\tfprintf(stderr, \"%s: no formatting options specified. Try: %s -help\\n\", argv[0], argv[0]);\n\t\texit(1);\n\t}\n\n\tfor (auto filename : filenames) {\n\t\tstd::string content;\n\t\t{\n\t\t\tstd::ifstream file{filename};\n\t\t\tcontent = {std::istreambuf_iterator<char>(file), std::istreambuf_iterator<char>()};\n\t\t}\n\n\t\tstd::vector<Span> spans;\n\t\tstd::vector<Command> commands;\n\t\tstd::tie(spans, commands) = parse(content);\n\n\t\tfor (auto f : formatting_functions) {\n\t\t\tf(commands, spans);\n\t\t}\n\n\t\tif (format_in_place) {\n\t\t\tstd::ofstream file{filename};\n\t\t\tfor (auto s : spans) {\n\t\t\t\tfile << s.data;\n\t\t\t}\n\t\t} else {\n\t\t\tfor (auto s : spans) {\n\t\t\t\tstd::cout << s.data;\n\t\t\t}\n\t\t}\n\t}\n}\n<commit_msg>cmake-format: replace size_t with ssize_t in FormatterIndent::run<commit_after>\/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying\n file Copyright.txt or https:\/\/opensource.org\/licenses\/BSD-3-Clause for\n details. *\/\n\n#include <algorithm>\n#include <cctype>\n#include <fstream>\n#include <functional>\n#include <iostream>\n#include <memory>\n#include <regex>\n#include <string>\n#include <utility>\n#include <vector>\n\n#include \"parser.h\"\n\nusing namespace std::placeholders;\n\nvoid replace_all_in_string(std::string &main_string, const std::string &from,\n const std::string &to) {\n\tsize_t pos = 0;\n\twhile ((pos = main_string.find(from, pos)) != std::string::npos) {\n\t\tmain_string.replace(pos, from.size(), to);\n\t}\n}\n\nstd::string lowerstring(const std::string &val) {\n\tstd::string newval = val;\n\tstd::transform(newval.begin(), newval.end(), newval.begin(),\n\t [](char c) { return std::tolower(c); });\n\treturn newval;\n}\n\nstd::string repeat_string(const std::string &val, size_t n) {\n\tstd::string newval;\n\tfor (size_t i = 0; i < n; i++) {\n\t\tnewval += val;\n\t}\n\treturn newval;\n}\n\nusing FormatterFunction = std::function<void(const std::vector<Command> &, std::vector<Span> &)>;\n\nclass Formatter {\n public:\n\tvirtual ~Formatter() = default;\n\tvirtual std::vector<std::pair<std::string, std::string>> describeCommandLine() = 0;\n\tvirtual bool handleCommandLine(const std::string &arg,\n\t std::vector<FormatterFunction> &formatter_functions) = 0;\n};\n\nclass FormatterIndent : public Formatter {\n\tstd::vector<std::pair<std::string, std::string>> describeCommandLine() override {\n\t\treturn {{\"-indent=STRING\", \"Use STRING for indentation.\"}};\n\t}\n\n\tbool handleCommandLine(const std::string &arg,\n\t std::vector<FormatterFunction> &formatter_functions) override {\n\t\tif (arg.find(\"-indent=\") != 0) {\n\t\t\treturn false;\n\t\t}\n\n\t\tstd::string indent_string = arg.substr(std::string{\"-indent=\"}.size());\n\t\treplace_all_in_string(indent_string, \"\\\\t\", \"\\t\");\n\t\tformatter_functions.emplace_back(std::bind(run, _1, _2, indent_string));\n\n\t\treturn true;\n\t};\n\n\tstatic void run(const std::vector<Command> &commands, std::vector<Span> &spans,\n\t const std::string &indent_string) {\n\t\tint global_indentation_level = 0;\n\t\tfor (auto c : commands) {\n\t\t\tconst std::string ident = lowerstring(spans[c.identifier].data);\n\n\t\t\tif (ident == \"endif\" || ident == \"endforeach\" || ident == \"endwhile\" ||\n\t\t\t ident == \"endmacro\" || ident == \"endfunction\") {\n\t\t\t\tglobal_indentation_level--;\n\t\t\t}\n\n\t\t\tauto indentation_level = global_indentation_level;\n\t\t\tif (ident == \"else\" || ident == \"elseif\") {\n\t\t\t\tindentation_level--;\n\t\t\t}\n\n\t\t\tconst std::string old_indentation = spans[c.identifier - 1].data;\n\n\t\t\t\/\/ Re-indent the command invocation\n\t\t\tspans[c.identifier - 1].data = repeat_string(indent_string, indentation_level);\n\n\t\t\t\/\/ Walk forwards to fix arguments and the closing paren.\n\t\t\tsize_t next_token = c.identifier + 1;\n\t\t\twhile (true) {\n\t\t\t\tif (spans[next_token].type == SpanType::Newline) {\n\t\t\t\t\tsize_t old_indentation_pos = spans[next_token + 1].data.find(old_indentation);\n\t\t\t\t\tif (old_indentation_pos != 0) {\n\t\t\t\t\t} else {\n\t\t\t\t\t\tspans[next_token + 1].data =\n\t\t\t\t\t\t (repeat_string(indent_string, indentation_level) +\n\t\t\t\t\t\t spans[next_token + 1].data.substr(old_indentation.size()));\n\t\t\t\t\t}\n\t\t\t\t\tnext_token++;\n\t\t\t\t} else if (spans[next_token].type == SpanType::Lparen) {\n\t\t\t\t\tbreak;\n\t\t\t\t} else {\n\t\t\t\t\tnext_token++;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t\/\/ Walk backwards to fix comments at the same prior indentation\n\t\t\t\/\/ level.\n\t\t\tssize_t last_token_on_previous_line = c.identifier - 3;\n\t\t\twhile (last_token_on_previous_line >= 0) {\n\t\t\t\tif (spans[last_token_on_previous_line].type == SpanType::Comment &&\n\t\t\t\t spans[last_token_on_previous_line - 1].type == SpanType::Space &&\n\t\t\t\t spans[last_token_on_previous_line - 2].type == SpanType::Newline) {\n\t\t\t\t\tspans[last_token_on_previous_line - 1].data =\n\t\t\t\t\t repeat_string(indent_string, indentation_level);\n\t\t\t\t\tlast_token_on_previous_line -= 3;\n\t\t\t\t} else if (spans[last_token_on_previous_line].type == SpanType::Space &&\n\t\t\t\t spans[last_token_on_previous_line - 1].type == SpanType::Newline) {\n\t\t\t\t\tlast_token_on_previous_line -= 2;\n\t\t\t\t} else if (spans[last_token_on_previous_line].type == SpanType::Newline) {\n\t\t\t\t\tlast_token_on_previous_line -= 1;\n\t\t\t\t} else {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (ident == \"if\" || ident == \"foreach\" || ident == \"while\" || ident == \"macro\" ||\n\t\t\t ident == \"function\") {\n\t\t\t\tglobal_indentation_level++;\n\t\t\t}\n\t\t}\n\t}\n};\n\nclass FormatterIndentArgument : public Formatter {\n\tstd::vector<std::pair<std::string, std::string>> describeCommandLine() override {\n\t\treturn {\n\t\t {\"-indent-arguments=align-paren\",\n\t\t \"Align arguments on continuing lines with the command's left parenthesis.\"},\n\t\t {\"-indent-arguments=STRING\", \"Use STRING for indenting arguments on continuing lines.\"},\n\t\t};\n\t}\n\n\tbool handleCommandLine(const std::string &arg,\n\t std::vector<FormatterFunction> &formatter_functions) override {\n\n\t\tif (arg == \"-indent-arguments=align-paren\") {\n\t\t\tformatter_functions.emplace_back(std::bind(run, _1, _2, true, \"\"));\n\t\t\treturn true;\n\t\t}\n\t\tif (arg.find(\"-indent-arguments=\") == 0) {\n\t\t\tstd::string argument_indent_string =\n\t\t\t arg.substr(std::string{\"-indent-arguments=\"}.size());\n\t\t\treplace_all_in_string(argument_indent_string, \"\\\\t\", \"\\t\");\n\t\t\tformatter_functions.emplace_back(std::bind(run, _1, _2, false, argument_indent_string));\n\t\t\treturn true;\n\t\t}\n\n\t\treturn false;\n\t}\n\n\tstatic void run(const std::vector<Command> &commands, std::vector<Span> &spans,\n\t bool argument_indent_after_lparen, std::string argument_indent_string) {\n\n\t\t(void)argument_indent_after_lparen;\n\n\t\tfor (auto c : commands) {\n\t\t\tconst std::string ident = lowerstring(spans[c.identifier].data);\n\n\t\t\tstd::string command_indentation;\n\t\t\tif (spans[c.identifier - 1].type == SpanType::Newline) {\n\t\t\t\tcommand_indentation = \"\";\n\t\t\t} else {\n\t\t\t\tcommand_indentation = spans[c.identifier - 1].data;\n\t\t\t}\n\n\t\t\tif (argument_indent_after_lparen) {\n\t\t\t\targument_indent_string = repeat_string(\" \", ident.size() + 1);\n\t\t\t}\n\n\t\t\t\/\/ Walk forwards to fix argument indents.\n\t\t\tsize_t next_token = c.identifier + 1;\n\t\t\twhile (true) {\n\t\t\t\tif (spans[next_token].type == SpanType::Newline) {\n\t\t\t\t\tif (spans[next_token + 2].type != SpanType::Rparen) {\n\t\t\t\t\t\tspans[next_token + 1].data = command_indentation + argument_indent_string;\n\t\t\t\t\t}\n\t\t\t\t\tnext_token++;\n\t\t\t\t} else if (spans[next_token].type == SpanType::Rparen) {\n\t\t\t\t\tbreak;\n\t\t\t\t} else {\n\t\t\t\t\tnext_token++;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n};\n\nclass FormatterIndentRparen : public Formatter {\n\tstd::vector<std::pair<std::string, std::string>> describeCommandLine() override {\n\t\treturn {{\"-indent-rparen=STRING\", \"Use STRING for indenting hanging right-parens.\"}};\n\t}\n\n\tbool handleCommandLine(const std::string &arg,\n\t std::vector<FormatterFunction> &formatter_functions) override {\n\t\tif (arg.find(\"-indent-rparen=\") != 0) {\n\t\t\treturn false;\n\t\t}\n\n\t\tstd::string rparen_indent_string = arg.substr(std::string{\"-indent-rparen=\"}.size());\n\t\treplace_all_in_string(rparen_indent_string, \"\\\\t\", \"\\t\");\n\n\t\tformatter_functions.emplace_back(std::bind(run, _1, _2, rparen_indent_string));\n\n\t\treturn true;\n\t}\n\n\tstatic void run(const std::vector<Command> &commands, std::vector<Span> &spans,\n\t const std::string &rparen_indent_string) {\n\t\tfor (auto c : commands) {\n\t\t\tconst std::string ident = lowerstring(spans[c.identifier].data);\n\n\t\t\tstd::string command_indentation;\n\t\t\tif (spans[c.identifier - 1].type == SpanType::Newline) {\n\t\t\t\tcommand_indentation = \"\";\n\t\t\t} else {\n\t\t\t\tcommand_indentation = spans[c.identifier - 1].data;\n\t\t\t}\n\n\t\t\t\/\/ Walk forwards to fix continuation indents.\n\t\t\tsize_t next_token = c.identifier + 1;\n\t\t\twhile (true) {\n\t\t\t\tif (spans[next_token].type == SpanType::Rparen) {\n\t\t\t\t\tif (spans[next_token - 2].type == SpanType::Newline) {\n\t\t\t\t\t\tspans[next_token - 1].data = (command_indentation + rparen_indent_string);\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\t} else {\n\t\t\t\t\tnext_token++;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n};\n\nclass FormatterLowercaseCommands : public Formatter {\n\tstd::vector<std::pair<std::string, std::string>> describeCommandLine() override {\n\t\treturn {{\"-lowercase-commands\", \"Lowercase command names in command invocations.\"}};\n\t}\n\n\tbool handleCommandLine(const std::string &arg,\n\t std::vector<FormatterFunction> &formatting_functions) override {\n\t\tif (arg != \"-lowercase-commands\")\n\t\t\treturn false;\n\t\tformatting_functions.emplace_back(formatLowercaseCommands);\n\t\treturn true;\n\t}\n\n\tstatic void formatLowercaseCommands(const std::vector<Command> &commands,\n\t std::vector<Span> &spans) {\n\t\tfor (auto c : commands) {\n\t\t\tspans[c.identifier].data = lowerstring(spans[c.identifier].data);\n\t\t}\n\t}\n};\n\nint main(int argc, char **argv) {\n\n\tstd::vector<std::unique_ptr<Formatter>> formatters;\n\tformatters.emplace_back(new FormatterLowercaseCommands());\n\tformatters.emplace_back(new FormatterIndent());\n\tformatters.emplace_back(new FormatterIndentArgument());\n\tformatters.emplace_back(new FormatterIndentRparen());\n\n\tbool format_in_place = false;\n\tstd::vector<FormatterFunction> formatting_functions;\n\n\tstd::vector<std::string> filenames;\n\tfor (int i = 1; i < argc; i++) {\n\t\tconst std::string arg{argv[i]};\n\t\tif (arg[0] == '-') {\n\t\t\tstd::smatch reindent_match;\n\n\t\t\tif (\"-help\" == arg || \"-h\" == arg || \"--help\" == arg) {\n\t\t\t\tfprintf(stderr,\n\t\t\t\t \"usage: %s [options] [file ...]\\n\"\n\t\t\t\t \"\\n\"\n\t\t\t\t \"Re-formats specified files. If -i is specified, formats files\\n\"\n\t\t\t\t \"in-place; otherwise, writes results to standard output.\\n\"\n\t\t\t\t \"\\n\",\n\t\t\t\t argv[0]);\n\t\t\t\tfprintf(stderr, \"options:\\n\");\n\n\t\t\t\tsize_t max_option_size = 0;\n\t\t\t\tfor (auto const &f : formatters) {\n\t\t\t\t\tfor (auto const p : f->describeCommandLine()) {\n\t\t\t\t\t\tmax_option_size = std::max(max_option_size, p.first.size());\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tfor (auto const &f : formatters) {\n\t\t\t\t\tfor (auto const p : f->describeCommandLine()) {\n\t\t\t\t\t\tstd::string opt;\n\t\t\t\t\t\tstd::string description;\n\t\t\t\t\t\tstd::tie(opt, description) = p;\n\t\t\t\t\t\tfprintf(stderr, \" %s%s %s\\n\", opt.c_str(),\n\t\t\t\t\t\t repeat_string(\" \", max_option_size - opt.size()).c_str(),\n\t\t\t\t\t\t description.c_str());\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tfprintf(stderr, \" %s%s %s\\n\", \"-i\",\n\t\t\t\t repeat_string(\" \", max_option_size - 2).c_str(),\n\t\t\t\t \"Re-format files in-place.\");\n\t\t\t\texit(1);\n\t\t\t} else if (arg == \"-i\") {\n\t\t\t\tformat_in_place = true;\n\t\t\t} else {\n\t\t\t\tbool handled_arg = false;\n\t\t\t\tfor (const auto &f : formatters) {\n\t\t\t\t\tif ((handled_arg = f->handleCommandLine(arg, formatting_functions))) {\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (!handled_arg) {\n\t\t\t\t\tfprintf(stderr, \"%s: unrecognized option '%s'. Try: %s -help\\n\", argv[0],\n\t\t\t\t\t arg.c_str(), argv[0]);\n\t\t\t\t\texit(1);\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tfilenames.emplace_back(arg);\n\t\t}\n\t}\n\n\tif (filenames.size() == 0) {\n\t\tfprintf(stderr, \"%s: no filenames specified. Try: %s -help\\n\", argv[0], argv[0]);\n\t\texit(1);\n\t}\n\n\tif (formatting_functions.size() == 0) {\n\t\tfprintf(stderr, \"%s: no formatting options specified. Try: %s -help\\n\", argv[0], argv[0]);\n\t\texit(1);\n\t}\n\n\tfor (auto filename : filenames) {\n\t\tstd::string content;\n\t\t{\n\t\t\tstd::ifstream file{filename};\n\t\t\tcontent = {std::istreambuf_iterator<char>(file), std::istreambuf_iterator<char>()};\n\t\t}\n\n\t\tstd::vector<Span> spans;\n\t\tstd::vector<Command> commands;\n\t\tstd::tie(spans, commands) = parse(content);\n\n\t\tfor (auto f : formatting_functions) {\n\t\t\tf(commands, spans);\n\t\t}\n\n\t\tif (format_in_place) {\n\t\t\tstd::ofstream file{filename};\n\t\t\tfor (auto s : spans) {\n\t\t\t\tfile << s.data;\n\t\t\t}\n\t\t} else {\n\t\t\tfor (auto s : spans) {\n\t\t\t\tstd::cout << s.data;\n\t\t\t}\n\t\t}\n\t}\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"Test.h\"\n\nvoid Test::conIntList() {\n bool compStatus = compileChecker(\"con\/conIntList.sppl\");\n CPPUNIT_ASSERT_MESSAGE(compMsgFail, compStatus);\n bool execStatus = executeChecker(\"[1, 2, 3, 4]\");\n CPPUNIT_ASSERT_MESSAGE(execMsg, execStatus);\n}\n\nvoid Test::conFloatList() {\n bool compStatus = compileChecker(\"con\/conFloatList.sppl\");\n CPPUNIT_ASSERT_MESSAGE(compMsgFail, compStatus);\n bool execStatus = executeChecker(\"[1.000000, 2.000000, 3.000000, 4.000000]\");\n CPPUNIT_ASSERT_MESSAGE(execMsg, execStatus);\n}\n\nvoid Test::conBoolList() {\n bool compStatus = compileChecker(\"con\/conBoolList.sppl\");\n CPPUNIT_ASSERT_MESSAGE(compMsgFail, compStatus);\n bool execStatus = executeChecker(\"[True, True, False, False]\");\n CPPUNIT_ASSERT_MESSAGE(execMsg, execStatus);\n}\n\nvoid Test::conCharList() {\n bool compStatus = compileChecker(\"con\/conCharList.sppl\");\n CPPUNIT_ASSERT_MESSAGE(compMsgFail, compStatus);\n bool execStatus = executeChecker(\"['c', 'h', 'a', 'r']\");\n CPPUNIT_ASSERT_MESSAGE(execMsg, execStatus);\n}\n\nvoid Test::conStringList() {\n bool compStatus = compileChecker(\"con\/conStringList.sppl\");\n CPPUNIT_ASSERT_MESSAGE(compMsgFail, compStatus);\n bool execStatus = executeChecker(\"[\\\"string\\\", \\\"string\\\", \\\"string\\\", \\\"string\\\"]\");\n CPPUNIT_ASSERT_MESSAGE(execMsg, execStatus);\n}\n\nvoid Test::conNestedList() {\n bool compStatus = compileChecker(\"con\/conNestedList.sppl\");\n CPPUNIT_ASSERT_MESSAGE(compMsgFail, compStatus);\n bool execStatus = executeChecker(\"[[1, 2], [3, 4], [5, 6], [7, 8]]\");\n CPPUNIT_ASSERT_MESSAGE(execMsg, execStatus);\n}\n\nvoid Test::conTupleList() {\n bool compStatus = compileChecker(\"con\/conTupleList.sppl\");\n CPPUNIT_ASSERT_MESSAGE(compMsgFail, compStatus);\n bool execStatus = executeChecker(\"[(1, True), (2, False), (3, True), (4, False)]\");\n CPPUNIT_ASSERT_MESSAGE(execMsg, execStatus);\n}\n\nvoid Test::conTuple() {\n bool compStatus = compileChecker(\"con\/conTuple.sppl\");\n CPPUNIT_ASSERT_MESSAGE(compMsgSucc, !compStatus);\n}\n\nvoid Test::conInt() {\n bool compStatus = compileChecker(\"con\/conInt.sppl\");\n CPPUNIT_ASSERT_MESSAGE(compMsgSucc, !compStatus);\n\n}\n\nvoid Test::conFloat() {\n bool compStatus = compileChecker(\"con\/conFloat.sppl\");\n CPPUNIT_ASSERT_MESSAGE(compMsgSucc, !compStatus);\n}\n\nvoid Test::conBool() {\n bool compStatus = compileChecker(\"con\/conBool.sppl\");\n CPPUNIT_ASSERT_MESSAGE(compMsgSucc, !compStatus);\n}\n\nvoid Test::conChar() {\n bool compStatus = compileChecker(\"con\/conChar.sppl\");\n CPPUNIT_ASSERT_MESSAGE(compMsgSucc, !compStatus);\n}\n\nvoid Test::conString() {\n bool compStatus = compileChecker(\"con\/conString.sppl\");\n CPPUNIT_ASSERT_MESSAGE(compMsgFail, compStatus);\n bool execStatus = executeChecker(\"\\\"concatstring\\\"\");\n CPPUNIT_ASSERT_MESSAGE(execMsg, execStatus);\n}\n\nvoid Test::conMix() {\n bool compStatus = compileChecker(\"con\/conMix.sppl\");\n CPPUNIT_ASSERT_MESSAGE(compMsgSucc, !compStatus);\n}\n\nvoid Test::conFuncResOne() {\n bool compStatus = compileChecker(\"con\/conFunResOne.sppl\");\n CPPUNIT_ASSERT_MESSAGE(compMsgFail, compStatus);\n bool execStatus = executeChecker(\"[1, 2, 3, 4]\");\n CPPUNIT_ASSERT_MESSAGE(execMsg, execStatus);\n}\n\nvoid Test::conFuncResTwo() {\n bool compStatus = compileChecker(\"con\/conFunResTwo.sppl\");\n CPPUNIT_ASSERT_MESSAGE(compMsgFail, compStatus);\n bool execStatus = executeChecker(\"[1, 2, 3, 4]\");\n CPPUNIT_ASSERT_MESSAGE(execMsg, execStatus);\n}\n\nvoid Test::conEmpty() {\n bool compStatus = compileChecker(\"con\/conEmpty.sppl\");\n CPPUNIT_ASSERT_MESSAGE(compMsgSucc, !compStatus);\n}<commit_msg>unittests: fixed concat tests<commit_after>#include \"Test.h\"\n\nvoid Test::conIntList() {\n bool compStatus = compileChecker(\"con\/conIntList.sppl\");\n CPPUNIT_ASSERT_MESSAGE(compMsgFail, compStatus);\n bool execStatus = executeChecker(\"[1, 2, 3, 4]\");\n CPPUNIT_ASSERT_MESSAGE(execMsg, execStatus);\n}\n\nvoid Test::conFloatList() {\n bool compStatus = compileChecker(\"con\/conFloatList.sppl\");\n CPPUNIT_ASSERT_MESSAGE(compMsgFail, compStatus);\n bool execStatus = executeChecker(\"[1.000000, 2.000000, 3.000000, 4.000000]\");\n CPPUNIT_ASSERT_MESSAGE(execMsg, execStatus);\n}\n\nvoid Test::conBoolList() {\n bool compStatus = compileChecker(\"con\/conBoolList.sppl\");\n CPPUNIT_ASSERT_MESSAGE(compMsgFail, compStatus);\n bool execStatus = executeChecker(\"[True, True, False, False]\");\n CPPUNIT_ASSERT_MESSAGE(execMsg, execStatus);\n}\n\nvoid Test::conCharList() {\n bool compStatus = compileChecker(\"con\/conCharList.sppl\");\n CPPUNIT_ASSERT_MESSAGE(compMsgFail, compStatus);\n bool execStatus = executeChecker(\"['c', 'h', 'a', 'r']\");\n CPPUNIT_ASSERT_MESSAGE(execMsg, execStatus);\n}\n\nvoid Test::conStringList() {\n bool compStatus = compileChecker(\"con\/conStringList.sppl\");\n CPPUNIT_ASSERT_MESSAGE(compMsgFail, compStatus);\n bool execStatus = executeChecker(\"[\\\"string\\\", \\\"string\\\", \\\"string\\\", \\\"string\\\"]\");\n CPPUNIT_ASSERT_MESSAGE(execMsg, execStatus);\n}\n\nvoid Test::conNestedList() {\n bool compStatus = compileChecker(\"con\/conNestedList.sppl\");\n CPPUNIT_ASSERT_MESSAGE(compMsgFail, compStatus);\n bool execStatus = executeChecker(\"[[1, 2], [3, 4], [5, 6], [7, 8]]\");\n CPPUNIT_ASSERT_MESSAGE(execMsg, execStatus);\n}\n\nvoid Test::conTupleList() {\n bool compStatus = compileChecker(\"con\/conTupleList.sppl\");\n CPPUNIT_ASSERT_MESSAGE(compMsgFail, compStatus);\n bool execStatus = executeChecker(\"[(1, True), (2, False), (3, True), (4, False)]\");\n CPPUNIT_ASSERT_MESSAGE(execMsg, execStatus);\n}\n\nvoid Test::conTuple() {\n bool compStatus = compileChecker(\"con\/conTuple.sppl\");\n CPPUNIT_ASSERT_MESSAGE(compMsgSucc, !compStatus);\n}\n\nvoid Test::conInt() {\n bool compStatus = compileChecker(\"con\/conInt.sppl\");\n CPPUNIT_ASSERT_MESSAGE(compMsgSucc, !compStatus);\n\n}\n\nvoid Test::conFloat() {\n bool compStatus = compileChecker(\"con\/conFloat.sppl\");\n CPPUNIT_ASSERT_MESSAGE(compMsgSucc, !compStatus);\n}\n\nvoid Test::conBool() {\n bool compStatus = compileChecker(\"con\/conBool.sppl\");\n CPPUNIT_ASSERT_MESSAGE(compMsgSucc, !compStatus);\n}\n\nvoid Test::conChar() {\n bool compStatus = compileChecker(\"con\/conChar.sppl\");\n CPPUNIT_ASSERT_MESSAGE(compMsgSucc, !compStatus);\n}\n\nvoid Test::conString() {\n bool compStatus = compileChecker(\"con\/conString.sppl\");\n CPPUNIT_ASSERT_MESSAGE(compMsgFail, compStatus);\n bool execStatus = executeChecker(\"\\\"concatstring\\\"\");\n CPPUNIT_ASSERT_MESSAGE(execMsg, execStatus);\n}\n\nvoid Test::conMix() {\n bool compStatus = compileChecker(\"con\/conMix.sppl\");\n CPPUNIT_ASSERT_MESSAGE(compMsgSucc, !compStatus);\n}\n\nvoid Test::conFuncResOne() {\n bool compStatus = compileChecker(\"con\/conFuncResOne.sppl\");\n CPPUNIT_ASSERT_MESSAGE(compMsgFail, compStatus);\n bool execStatus = executeChecker(\"[1, 2, 3, 4]\");\n CPPUNIT_ASSERT_MESSAGE(execMsg, execStatus);\n}\n\nvoid Test::conFuncResTwo() {\n bool compStatus = compileChecker(\"con\/conFuncResTwo.sppl\");\n CPPUNIT_ASSERT_MESSAGE(compMsgFail, compStatus);\n bool execStatus = executeChecker(\"[1, 2, 3, 4]\");\n CPPUNIT_ASSERT_MESSAGE(execMsg, execStatus);\n}\n\nvoid Test::conEmpty() {\n bool compStatus = compileChecker(\"con\/conEmpty.sppl\");\n CPPUNIT_ASSERT_MESSAGE(compMsgSucc, !compStatus);\n}<|endoftext|>"} {"text":"<commit_before>\/***********************************************************************\n * filename: Element.cpp\n * created: 28\/10\/2011\n * author: Martin Preisler\n *************************************************************************\/\n\/***************************************************************************\n * Copyright (C) 2004 - 2011 Paul D Turner & The CEGUI Development Team\n *\n * Permission is hereby granted, free of charge, to any person obtaining\n * a copy of this software and associated documentation files (the\n * \"Software\"), to deal in the Software without restriction, including\n * without limitation the rights to use, copy, modify, merge, publish,\n * distribute, sublicense, and\/or sell copies of the Software, and to\n * permit persons to whom the Software is furnished to do so, subject to\n * the following conditions:\n *\n * The above copyright notice and this permission notice shall be\n * included in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\n * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR\n * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,\n * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\n * OTHER DEALINGS IN THE SOFTWARE.\n ***************************************************************************\/\n\n#include \"CEGUI\/Element.h\"\n\n#include <boost\/test\/unit_test.hpp>\n#include <boost\/timer.hpp>\n\nBOOST_AUTO_TEST_SUITE(Element)\n\nBOOST_AUTO_TEST_CASE(RelativeSizing)\n{\n \/\/ in this test, everything is top left aligned\n \n CEGUI::Element* root = new CEGUI::Element();\n root->setSize(CEGUI::USize(100.0f * CEGUI::UDim::px(), 100 * CEGUI::UDim::px()));\n CEGUI::Element* child = new CEGUI::Element();\n child->setSize(CEGUI::USize(50.0f * CEGUI::UDim::percent(), 25.0f * CEGUI::UDim::percent()));\n root->addChild(child);\n \n BOOST_CHECK_EQUAL(root->getPixelSize(), CEGUI::Sizef(100.0f, 100.0f));\n BOOST_CHECK_EQUAL(child->getPixelSize(), CEGUI::Sizef(50.0f, 25.0f));\n \n CEGUI::Element* innerChild = new CEGUI::Element();\n child->addChild(innerChild);\n innerChild->setSize(CEGUI::USize(200.0f * CEGUI::UDim::percent(), 100.0f * CEGUI::UDim::percent()));\n BOOST_CHECK_EQUAL(innerChild->getPixelSize(), CEGUI::Sizef(100.0f, 25.0f));\n \n delete innerChild;\n delete child;\n delete root;\n}\n\nBOOST_AUTO_TEST_CASE(TopLeftAlignment)\n{\n \/\/ in this test, everything is top left aligned\n \n CEGUI::Element* root = new CEGUI::Element();\n root->setSize(CEGUI::USize(100.0f * CEGUI::UDim::px(), 100 * CEGUI::UDim::px()));\n CEGUI::Element* child = new CEGUI::Element();\n child->setSize(CEGUI::USize(50.0f * CEGUI::UDim::px(), 25.0f * CEGUI::UDim::px()));\n root->addChild(child);\n \n \/\/ even though it is the default at the point of writing the test, we have to make sure this fact doesn't change!\n BOOST_CHECK_EQUAL(root->getHorizontalAlignment(), CEGUI::HA_LEFT);\n BOOST_CHECK_EQUAL(root->getVerticalAlignment(), CEGUI::VA_TOP);\n BOOST_CHECK_EQUAL(child->getHorizontalAlignment(), CEGUI::HA_LEFT);\n BOOST_CHECK_EQUAL(child->getVerticalAlignment(), CEGUI::VA_TOP);\n \n BOOST_CHECK_EQUAL(root->getUnclippedOuterRect().get(), CEGUI::Rectf(0, 0, 100, 100));\n BOOST_CHECK_EQUAL(child->getUnclippedOuterRect().get(), CEGUI::Rectf(0, 0, 50, 25));\n \n child->setPosition(CEGUI::UVector2(10.0f * CEGUI::UDim::px(), 5.0f * CEGUI::UDim::px()));\n \n BOOST_CHECK_EQUAL(child->getUnclippedOuterRect().get(), CEGUI::Rectf(10, 5, 60, 30));\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n<commit_msg>Split Element top left alignment test case into 2<commit_after>\/***********************************************************************\n * filename: Element.cpp\n * created: 28\/10\/2011\n * author: Martin Preisler\n *************************************************************************\/\n\/***************************************************************************\n * Copyright (C) 2004 - 2011 Paul D Turner & The CEGUI Development Team\n *\n * Permission is hereby granted, free of charge, to any person obtaining\n * a copy of this software and associated documentation files (the\n * \"Software\"), to deal in the Software without restriction, including\n * without limitation the rights to use, copy, modify, merge, publish,\n * distribute, sublicense, and\/or sell copies of the Software, and to\n * permit persons to whom the Software is furnished to do so, subject to\n * the following conditions:\n *\n * The above copyright notice and this permission notice shall be\n * included in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\n * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR\n * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,\n * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\n * OTHER DEALINGS IN THE SOFTWARE.\n ***************************************************************************\/\n\n#include \"CEGUI\/Element.h\"\n\n#include <boost\/test\/unit_test.hpp>\n#include <boost\/timer.hpp>\n\nBOOST_AUTO_TEST_SUITE(Element)\n\nBOOST_AUTO_TEST_CASE(RelativeSizing)\n{\n \/\/ in this test, everything is top left aligned\n \n CEGUI::Element* root = new CEGUI::Element();\n root->setSize(CEGUI::USize(100.0f * CEGUI::UDim::px(), 100 * CEGUI::UDim::px()));\n CEGUI::Element* child = new CEGUI::Element();\n child->setSize(CEGUI::USize(50.0f * CEGUI::UDim::percent(), 25.0f * CEGUI::UDim::percent()));\n root->addChild(child);\n \n BOOST_CHECK_EQUAL(root->getPixelSize(), CEGUI::Sizef(100.0f, 100.0f));\n BOOST_CHECK_EQUAL(child->getPixelSize(), CEGUI::Sizef(50.0f, 25.0f));\n \n CEGUI::Element* innerChild = new CEGUI::Element();\n child->addChild(innerChild);\n innerChild->setSize(CEGUI::USize(200.0f * CEGUI::UDim::percent(), 100.0f * CEGUI::UDim::percent()));\n BOOST_CHECK_EQUAL(innerChild->getPixelSize(), CEGUI::Sizef(100.0f, 25.0f));\n \n delete innerChild;\n delete child;\n delete root;\n}\n\nBOOST_AUTO_TEST_CASE(LeftAlignment)\n{\n \/\/ in this test, everything is top left aligned\n \n CEGUI::Element* root = new CEGUI::Element();\n root->setSize(CEGUI::USize(100.0f * CEGUI::UDim::px(), 0.0f * CEGUI::UDim::px()));\n CEGUI::Element* child = new CEGUI::Element();\n child->setSize(CEGUI::USize(50.0f * CEGUI::UDim::px(), 0.0f * CEGUI::UDim::px()));\n root->addChild(child);\n \n \/\/ even though it is the default at the point of writing the test, we have to make sure this fact doesn't change!\n BOOST_CHECK_EQUAL(root->getHorizontalAlignment(), CEGUI::HA_LEFT);\n BOOST_CHECK_EQUAL(child->getHorizontalAlignment(), CEGUI::HA_LEFT);\n \n BOOST_CHECK_EQUAL(root->getUnclippedOuterRect().get(), CEGUI::Rectf(0, 0, 100, 0));\n BOOST_CHECK_EQUAL(child->getUnclippedOuterRect().get(), CEGUI::Rectf(0, 0, 50, 0));\n \n child->setPosition(CEGUI::UVector2(10.0f * CEGUI::UDim::px(), 0.0f * CEGUI::UDim::px()));\n \n BOOST_CHECK_EQUAL(child->getUnclippedOuterRect().get(), CEGUI::Rectf(10, 0, 60, 0));\n}\n\nBOOST_AUTO_TEST_CASE(TopAlignment)\n{\n \/\/ in this test, everything is top left aligned\n \n CEGUI::Element* root = new CEGUI::Element();\n root->setSize(CEGUI::USize(0.0f * CEGUI::UDim::px(), 100 * CEGUI::UDim::px()));\n CEGUI::Element* child = new CEGUI::Element();\n child->setSize(CEGUI::USize(0.0f * CEGUI::UDim::px(), 25.0f * CEGUI::UDim::px()));\n root->addChild(child);\n \n \/\/ even though it is the default at the point of writing the test, we have to make sure this fact doesn't change!\n BOOST_CHECK_EQUAL(root->getVerticalAlignment(), CEGUI::VA_TOP);\n BOOST_CHECK_EQUAL(child->getVerticalAlignment(), CEGUI::VA_TOP);\n \n BOOST_CHECK_EQUAL(root->getUnclippedOuterRect().get(), CEGUI::Rectf(0, 0, 0, 100));\n BOOST_CHECK_EQUAL(child->getUnclippedOuterRect().get(), CEGUI::Rectf(0, 0, 0, 25));\n \n child->setPosition(CEGUI::UVector2(0.0f * CEGUI::UDim::px(), 5.0f * CEGUI::UDim::px()));\n \n BOOST_CHECK_EQUAL(child->getUnclippedOuterRect().get(), CEGUI::Rectf(0, 5, 0, 30));\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n<|endoftext|>"} {"text":"<commit_before>\/\/===-- LibCxxList.cpp ------------------------------------------*- C++ -*-===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n\/\/ C Includes\n\/\/ C++ Includes\n\/\/ Other libraries and framework includes\n\/\/ Project includes\n#include \"LibCxx.h\"\n\n#include \"lldb\/Core\/DataBufferHeap.h\"\n#include \"lldb\/Core\/Error.h\"\n#include \"lldb\/Core\/Stream.h\"\n#include \"lldb\/Core\/ValueObject.h\"\n#include \"lldb\/Core\/ValueObjectConstResult.h\"\n#include \"lldb\/DataFormatters\/FormattersHelpers.h\"\n#include \"lldb\/Host\/Endian.h\"\n#include \"lldb\/Symbol\/ClangASTContext.h\"\n#include \"lldb\/Target\/Target.h\"\n\nusing namespace lldb;\nusing namespace lldb_private;\nusing namespace lldb_private::formatters;\n\nnamespace {\n\n class ListEntry\n {\n public:\n ListEntry() = default;\n ListEntry (ValueObjectSP entry_sp) : m_entry_sp(entry_sp) {}\n ListEntry(const ListEntry& rhs) = default;\n ListEntry (ValueObject* entry) : m_entry_sp(entry ? entry->GetSP() : ValueObjectSP()) {}\n\n ListEntry\n next ()\n {\n if (!m_entry_sp)\n return ListEntry();\n return ListEntry(m_entry_sp->GetChildAtIndexPath({0,1}));\n }\n\n ListEntry\n prev ()\n {\n if (!m_entry_sp)\n return ListEntry();\n return ListEntry(m_entry_sp->GetChildAtIndexPath({0,0}));\n }\n\n uint64_t\n value () const\n {\n if (!m_entry_sp)\n return 0;\n return m_entry_sp->GetValueAsUnsigned(0);\n }\n\n bool\n null()\n {\n return (value() == 0);\n }\n\n explicit operator bool ()\n {\n return GetEntry() && !null();\n }\n\n ValueObjectSP\n GetEntry ()\n {\n return m_entry_sp;\n }\n\n void\n SetEntry (ValueObjectSP entry)\n {\n m_entry_sp = entry;\n }\n\n bool\n operator == (const ListEntry& rhs) const\n {\n return value() == rhs.value();\n }\n\n bool\n operator != (const ListEntry& rhs) const\n {\n return !(*this == rhs);\n }\n\n private:\n ValueObjectSP m_entry_sp;\n };\n \n class ListIterator\n {\n public:\n ListIterator() = default;\n ListIterator (ListEntry entry) : m_entry(entry) {}\n ListIterator (ValueObjectSP entry) : m_entry(entry) {}\n ListIterator(const ListIterator& rhs) = default;\n ListIterator (ValueObject* entry) : m_entry(entry) {}\n \n ValueObjectSP\n value ()\n {\n return m_entry.GetEntry();\n }\n \n ValueObjectSP\n advance (size_t count)\n {\n if (count == 0)\n return m_entry.GetEntry();\n if (count == 1)\n {\n next ();\n return m_entry.GetEntry();\n }\n while (count > 0)\n {\n next ();\n count--;\n if (m_entry.null())\n return lldb::ValueObjectSP();\n }\n return m_entry.GetEntry();\n }\n \n bool\n operator == (const ListIterator& rhs) const\n {\n return (rhs.m_entry == m_entry);\n }\n \n protected:\n void\n next ()\n {\n m_entry = m_entry.next();\n }\n \n void\n prev ()\n {\n m_entry = m_entry.prev();\n }\n \n private:\n ListEntry m_entry;\n };\n\n} \/\/ end anonymous namespace\n\nnamespace lldb_private {\n namespace formatters {\n class LibcxxStdListSyntheticFrontEnd : public SyntheticChildrenFrontEnd\n {\n public:\n LibcxxStdListSyntheticFrontEnd (lldb::ValueObjectSP valobj_sp);\n\n ~LibcxxStdListSyntheticFrontEnd() override = default;\n\n size_t\n CalculateNumChildren() override;\n \n lldb::ValueObjectSP\n GetChildAtIndex(size_t idx) override;\n \n bool\n Update() override;\n \n bool\n MightHaveChildren() override;\n \n size_t\n GetIndexOfChildWithName(const ConstString &name) override;\n \n private:\n bool\n HasLoop(size_t count);\n \n size_t m_list_capping_size;\n static const bool g_use_loop_detect = true;\n\n size_t m_loop_detected; \/\/ The number of elements that have had loop detection run over them.\n ListEntry m_slow_runner; \/\/ Used for loop detection\n ListEntry m_fast_runner; \/\/ Used for loop detection\n\n lldb::addr_t m_node_address;\n ValueObject* m_head;\n ValueObject* m_tail;\n CompilerType m_element_type;\n size_t m_count;\n std::map<size_t, ListIterator> m_iterators;\n };\n } \/\/ namespace formatters\n} \/\/ namespace lldb_private\n\nlldb_private::formatters::LibcxxStdListSyntheticFrontEnd::LibcxxStdListSyntheticFrontEnd (lldb::ValueObjectSP valobj_sp) :\n SyntheticChildrenFrontEnd(*valobj_sp),\n m_list_capping_size(0),\n m_loop_detected(0),\n m_node_address(),\n m_head(nullptr),\n m_tail(nullptr),\n m_element_type(),\n m_count(UINT32_MAX),\n m_iterators()\n{\n if (valobj_sp)\n Update();\n}\n\nbool\nlldb_private::formatters::LibcxxStdListSyntheticFrontEnd::HasLoop(size_t count)\n{\n if (!g_use_loop_detect)\n return false;\n \/\/ don't bother checking for a loop if we won't actually need to jump nodes\n if (m_count < 2)\n return false;\n\n if (m_loop_detected == 0)\n {\n \/\/ This is the first time we are being run (after the last update). Set up the loop\n \/\/ invariant for the first element.\n m_slow_runner = ListEntry(m_head).next();\n m_fast_runner = m_slow_runner.next();\n m_loop_detected = 1;\n }\n\n \/\/ Loop invariant:\n \/\/ Loop detection has been run over the first m_loop_detected elements. If m_slow_runner ==\n \/\/ m_fast_runner then the loop has been detected after m_loop_detected elements.\n const size_t steps_to_run = std::min(count,m_count);\n while (m_loop_detected < steps_to_run\n && m_slow_runner\n && m_fast_runner\n && m_slow_runner != m_fast_runner) {\n\n m_slow_runner = m_slow_runner.next();\n m_fast_runner = m_fast_runner.next().next();\n m_loop_detected++;\n }\n if (count <= m_loop_detected)\n return false; \/\/ No loop in the first m_loop_detected elements.\n if (!m_slow_runner || !m_fast_runner)\n return false; \/\/ Reached the end of the list. Definitely no loops.\n return m_slow_runner == m_fast_runner;\n}\n\nsize_t\nlldb_private::formatters::LibcxxStdListSyntheticFrontEnd::CalculateNumChildren ()\n{\n if (m_count != UINT32_MAX)\n return m_count;\n if (!m_head || !m_tail || m_node_address == 0)\n return 0;\n ValueObjectSP size_alloc(m_backend.GetChildMemberWithName(ConstString(\"__size_alloc_\"), true));\n if (size_alloc)\n {\n ValueObjectSP first(size_alloc->GetChildMemberWithName(ConstString(\"__first_\"), true));\n if (first)\n {\n m_count = first->GetValueAsUnsigned(UINT32_MAX);\n }\n }\n if (m_count != UINT32_MAX)\n {\n return m_count;\n }\n else\n {\n uint64_t next_val = m_head->GetValueAsUnsigned(0);\n uint64_t prev_val = m_tail->GetValueAsUnsigned(0);\n if (next_val == 0 || prev_val == 0)\n return 0;\n if (next_val == m_node_address)\n return 0;\n if (next_val == prev_val)\n return 1;\n uint64_t size = 2;\n ListEntry current(m_head);\n while (current.next() && current.next().value() != m_node_address)\n {\n size++;\n current = current.next();\n if (size > m_list_capping_size)\n break;\n }\n return m_count = (size-1);\n }\n}\n\nlldb::ValueObjectSP\nlldb_private::formatters::LibcxxStdListSyntheticFrontEnd::GetChildAtIndex (size_t idx)\n{\n if (idx >= CalculateNumChildren())\n return lldb::ValueObjectSP();\n \n if (!m_head || !m_tail || m_node_address == 0)\n return lldb::ValueObjectSP();\n \n if (HasLoop(idx+1))\n return lldb::ValueObjectSP();\n \n size_t actual_advance = idx;\n \n ListIterator current(m_head);\n if (idx > 0)\n {\n auto cached_iterator = m_iterators.find(idx-1);\n if (cached_iterator != m_iterators.end())\n {\n current = cached_iterator->second;\n actual_advance = 1;\n }\n }\n \n ValueObjectSP current_sp(current.advance(actual_advance));\n if (!current_sp)\n return lldb::ValueObjectSP();\n \n m_iterators[idx] = current;\n \n current_sp = current_sp->GetChildAtIndex(1, true); \/\/ get the __value_ child\n if (!current_sp)\n return lldb::ValueObjectSP();\n \/\/ we need to copy current_sp into a new object otherwise we will end up with all items named __value_\n DataExtractor data;\n Error error;\n current_sp->GetData(data, error);\n if (error.Fail())\n return lldb::ValueObjectSP();\n \n StreamString name;\n name.Printf(\"[%\" PRIu64 \"]\", (uint64_t)idx);\n return CreateValueObjectFromData(name.GetData(),\n data,\n m_backend.GetExecutionContextRef(),\n m_element_type);\n}\n\nbool\nlldb_private::formatters::LibcxxStdListSyntheticFrontEnd::Update()\n{\n m_iterators.clear();\n m_head = m_tail = nullptr;\n m_node_address = 0;\n m_count = UINT32_MAX;\n m_loop_detected = 0;\n m_slow_runner.SetEntry(nullptr);\n m_fast_runner.SetEntry(nullptr);\n\n Error err;\n ValueObjectSP backend_addr(m_backend.AddressOf(err));\n m_list_capping_size = 0;\n if (m_backend.GetTargetSP())\n m_list_capping_size = m_backend.GetTargetSP()->GetMaximumNumberOfChildrenToDisplay();\n if (m_list_capping_size == 0)\n m_list_capping_size = 255;\n if (err.Fail() || !backend_addr)\n return false;\n m_node_address = backend_addr->GetValueAsUnsigned(0);\n if (!m_node_address || m_node_address == LLDB_INVALID_ADDRESS)\n return false;\n ValueObjectSP impl_sp(m_backend.GetChildMemberWithName(ConstString(\"__end_\"),true));\n if (!impl_sp)\n return false;\n CompilerType list_type = m_backend.GetCompilerType();\n if (list_type.IsReferenceType())\n list_type = list_type.GetNonReferenceType();\n\n if (list_type.GetNumTemplateArguments() == 0)\n return false;\n lldb::TemplateArgumentKind kind;\n m_element_type = list_type.GetTemplateArgument(0, kind);\n m_head = impl_sp->GetChildMemberWithName(ConstString(\"__next_\"), true).get();\n m_tail = impl_sp->GetChildMemberWithName(ConstString(\"__prev_\"), true).get();\n return false;\n}\n\nbool\nlldb_private::formatters::LibcxxStdListSyntheticFrontEnd::MightHaveChildren ()\n{\n return true;\n}\n\nsize_t\nlldb_private::formatters::LibcxxStdListSyntheticFrontEnd::GetIndexOfChildWithName (const ConstString &name)\n{\n return ExtractIndexFromString(name.GetCString());\n}\n\nSyntheticChildrenFrontEnd*\nlldb_private::formatters::LibcxxStdListSyntheticFrontEndCreator (CXXSyntheticChildren*, lldb::ValueObjectSP valobj_sp)\n{\n return (valobj_sp ? new LibcxxStdListSyntheticFrontEnd(valobj_sp) : nullptr);\n}\n<commit_msg>Fix an issue where the libc++ std::list formatter wasn't recognizing the new memory layout correctly<commit_after>\/\/===-- LibCxxList.cpp ------------------------------------------*- C++ -*-===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n\/\/ C Includes\n\/\/ C++ Includes\n\/\/ Other libraries and framework includes\n\/\/ Project includes\n#include \"LibCxx.h\"\n\n#include \"lldb\/Core\/DataBufferHeap.h\"\n#include \"lldb\/Core\/Error.h\"\n#include \"lldb\/Core\/Stream.h\"\n#include \"lldb\/Core\/ValueObject.h\"\n#include \"lldb\/Core\/ValueObjectConstResult.h\"\n#include \"lldb\/DataFormatters\/FormattersHelpers.h\"\n#include \"lldb\/Host\/Endian.h\"\n#include \"lldb\/Symbol\/ClangASTContext.h\"\n#include \"lldb\/Target\/Target.h\"\n\nusing namespace lldb;\nusing namespace lldb_private;\nusing namespace lldb_private::formatters;\n\nnamespace {\n\n class ListEntry\n {\n public:\n ListEntry() = default;\n ListEntry (ValueObjectSP entry_sp) : m_entry_sp(entry_sp) {}\n ListEntry(const ListEntry& rhs) = default;\n ListEntry (ValueObject* entry) : m_entry_sp(entry ? entry->GetSP() : ValueObjectSP()) {}\n\n ListEntry\n next ()\n {\n static ConstString g_next(\"__next_\");\n \n if (!m_entry_sp)\n return ListEntry();\n return ListEntry(m_entry_sp->GetChildMemberWithName(g_next, true));\n }\n\n ListEntry\n prev ()\n {\n static ConstString g_prev(\"__prev_\");\n\n if (!m_entry_sp)\n return ListEntry();\n return ListEntry(m_entry_sp->GetChildMemberWithName(g_prev, true));\n }\n\n uint64_t\n value () const\n {\n if (!m_entry_sp)\n return 0;\n return m_entry_sp->GetValueAsUnsigned(0);\n }\n\n bool\n null()\n {\n return (value() == 0);\n }\n\n explicit operator bool ()\n {\n return GetEntry() && !null();\n }\n\n ValueObjectSP\n GetEntry ()\n {\n return m_entry_sp;\n }\n\n void\n SetEntry (ValueObjectSP entry)\n {\n m_entry_sp = entry;\n }\n\n bool\n operator == (const ListEntry& rhs) const\n {\n return value() == rhs.value();\n }\n\n bool\n operator != (const ListEntry& rhs) const\n {\n return !(*this == rhs);\n }\n\n private:\n ValueObjectSP m_entry_sp;\n };\n \n class ListIterator\n {\n public:\n ListIterator() = default;\n ListIterator (ListEntry entry) : m_entry(entry) {}\n ListIterator (ValueObjectSP entry) : m_entry(entry) {}\n ListIterator(const ListIterator& rhs) = default;\n ListIterator (ValueObject* entry) : m_entry(entry) {}\n \n ValueObjectSP\n value ()\n {\n return m_entry.GetEntry();\n }\n \n ValueObjectSP\n advance (size_t count)\n {\n if (count == 0)\n return m_entry.GetEntry();\n if (count == 1)\n {\n next ();\n return m_entry.GetEntry();\n }\n while (count > 0)\n {\n next ();\n count--;\n if (m_entry.null())\n return lldb::ValueObjectSP();\n }\n return m_entry.GetEntry();\n }\n \n bool\n operator == (const ListIterator& rhs) const\n {\n return (rhs.m_entry == m_entry);\n }\n \n protected:\n void\n next ()\n {\n m_entry = m_entry.next();\n }\n \n void\n prev ()\n {\n m_entry = m_entry.prev();\n }\n \n private:\n ListEntry m_entry;\n };\n\n} \/\/ end anonymous namespace\n\nnamespace lldb_private {\n namespace formatters {\n class LibcxxStdListSyntheticFrontEnd : public SyntheticChildrenFrontEnd\n {\n public:\n LibcxxStdListSyntheticFrontEnd (lldb::ValueObjectSP valobj_sp);\n\n ~LibcxxStdListSyntheticFrontEnd() override = default;\n\n size_t\n CalculateNumChildren() override;\n \n lldb::ValueObjectSP\n GetChildAtIndex(size_t idx) override;\n \n bool\n Update() override;\n \n bool\n MightHaveChildren() override;\n \n size_t\n GetIndexOfChildWithName(const ConstString &name) override;\n \n private:\n bool\n HasLoop(size_t count);\n \n size_t m_list_capping_size;\n static const bool g_use_loop_detect = true;\n\n size_t m_loop_detected; \/\/ The number of elements that have had loop detection run over them.\n ListEntry m_slow_runner; \/\/ Used for loop detection\n ListEntry m_fast_runner; \/\/ Used for loop detection\n\n lldb::addr_t m_node_address;\n ValueObject* m_head;\n ValueObject* m_tail;\n CompilerType m_element_type;\n size_t m_count;\n std::map<size_t, ListIterator> m_iterators;\n };\n } \/\/ namespace formatters\n} \/\/ namespace lldb_private\n\nlldb_private::formatters::LibcxxStdListSyntheticFrontEnd::LibcxxStdListSyntheticFrontEnd (lldb::ValueObjectSP valobj_sp) :\n SyntheticChildrenFrontEnd(*valobj_sp),\n m_list_capping_size(0),\n m_loop_detected(0),\n m_node_address(),\n m_head(nullptr),\n m_tail(nullptr),\n m_element_type(),\n m_count(UINT32_MAX),\n m_iterators()\n{\n if (valobj_sp)\n Update();\n}\n\nbool\nlldb_private::formatters::LibcxxStdListSyntheticFrontEnd::HasLoop(size_t count)\n{\n if (!g_use_loop_detect)\n return false;\n \/\/ don't bother checking for a loop if we won't actually need to jump nodes\n if (m_count < 2)\n return false;\n\n if (m_loop_detected == 0)\n {\n \/\/ This is the first time we are being run (after the last update). Set up the loop\n \/\/ invariant for the first element.\n m_slow_runner = ListEntry(m_head).next();\n m_fast_runner = m_slow_runner.next();\n m_loop_detected = 1;\n }\n\n \/\/ Loop invariant:\n \/\/ Loop detection has been run over the first m_loop_detected elements. If m_slow_runner ==\n \/\/ m_fast_runner then the loop has been detected after m_loop_detected elements.\n const size_t steps_to_run = std::min(count,m_count);\n while (m_loop_detected < steps_to_run\n && m_slow_runner\n && m_fast_runner\n && m_slow_runner != m_fast_runner) {\n\n m_slow_runner = m_slow_runner.next();\n m_fast_runner = m_fast_runner.next().next();\n m_loop_detected++;\n }\n if (count <= m_loop_detected)\n return false; \/\/ No loop in the first m_loop_detected elements.\n if (!m_slow_runner || !m_fast_runner)\n return false; \/\/ Reached the end of the list. Definitely no loops.\n return m_slow_runner == m_fast_runner;\n}\n\nsize_t\nlldb_private::formatters::LibcxxStdListSyntheticFrontEnd::CalculateNumChildren ()\n{\n if (m_count != UINT32_MAX)\n return m_count;\n if (!m_head || !m_tail || m_node_address == 0)\n return 0;\n ValueObjectSP size_alloc(m_backend.GetChildMemberWithName(ConstString(\"__size_alloc_\"), true));\n if (size_alloc)\n {\n ValueObjectSP first(size_alloc->GetChildMemberWithName(ConstString(\"__first_\"), true));\n if (first)\n {\n m_count = first->GetValueAsUnsigned(UINT32_MAX);\n }\n }\n if (m_count != UINT32_MAX)\n {\n return m_count;\n }\n else\n {\n uint64_t next_val = m_head->GetValueAsUnsigned(0);\n uint64_t prev_val = m_tail->GetValueAsUnsigned(0);\n if (next_val == 0 || prev_val == 0)\n return 0;\n if (next_val == m_node_address)\n return 0;\n if (next_val == prev_val)\n return 1;\n uint64_t size = 2;\n ListEntry current(m_head);\n while (current.next() && current.next().value() != m_node_address)\n {\n size++;\n current = current.next();\n if (size > m_list_capping_size)\n break;\n }\n return m_count = (size-1);\n }\n}\n\nlldb::ValueObjectSP\nlldb_private::formatters::LibcxxStdListSyntheticFrontEnd::GetChildAtIndex (size_t idx)\n{\n static ConstString g_value(\"__value_\");\n static ConstString g_next(\"__next_\");\n\n if (idx >= CalculateNumChildren())\n return lldb::ValueObjectSP();\n \n if (!m_head || !m_tail || m_node_address == 0)\n return lldb::ValueObjectSP();\n \n if (HasLoop(idx+1))\n return lldb::ValueObjectSP();\n \n size_t actual_advance = idx;\n \n ListIterator current(m_head);\n if (idx > 0)\n {\n auto cached_iterator = m_iterators.find(idx-1);\n if (cached_iterator != m_iterators.end())\n {\n current = cached_iterator->second;\n actual_advance = 1;\n }\n }\n \n ValueObjectSP current_sp(current.advance(actual_advance));\n if (!current_sp)\n return lldb::ValueObjectSP();\n \n m_iterators[idx] = current;\n \n current_sp = current_sp->GetChildAtIndex(1, true); \/\/ get the __value_ child\n if (!current_sp)\n return lldb::ValueObjectSP();\n \n if (current_sp->GetName() == g_next)\n {\n ProcessSP process_sp(current_sp->GetProcessSP());\n if (!process_sp)\n return nullptr;\n\n \/\/ if we grabbed the __next_ pointer, then the child is one pointer deep-er\n lldb::addr_t addr = current_sp->GetParent()->GetPointerValue();\n addr = addr + 2*process_sp->GetAddressByteSize();\n ExecutionContext exe_ctx(process_sp);\n current_sp = CreateValueObjectFromAddress(\"__value_\",\n addr,\n exe_ctx,\n m_element_type);\n }\n \n \/\/ we need to copy current_sp into a new object otherwise we will end up with all items named __value_\n DataExtractor data;\n Error error;\n current_sp->GetData(data, error);\n if (error.Fail())\n return lldb::ValueObjectSP();\n \n StreamString name;\n name.Printf(\"[%\" PRIu64 \"]\", (uint64_t)idx);\n return CreateValueObjectFromData(name.GetData(),\n data,\n m_backend.GetExecutionContextRef(),\n m_element_type);\n}\n\nbool\nlldb_private::formatters::LibcxxStdListSyntheticFrontEnd::Update()\n{\n m_iterators.clear();\n m_head = m_tail = nullptr;\n m_node_address = 0;\n m_count = UINT32_MAX;\n m_loop_detected = 0;\n m_slow_runner.SetEntry(nullptr);\n m_fast_runner.SetEntry(nullptr);\n\n Error err;\n ValueObjectSP backend_addr(m_backend.AddressOf(err));\n m_list_capping_size = 0;\n if (m_backend.GetTargetSP())\n m_list_capping_size = m_backend.GetTargetSP()->GetMaximumNumberOfChildrenToDisplay();\n if (m_list_capping_size == 0)\n m_list_capping_size = 255;\n if (err.Fail() || !backend_addr)\n return false;\n m_node_address = backend_addr->GetValueAsUnsigned(0);\n if (!m_node_address || m_node_address == LLDB_INVALID_ADDRESS)\n return false;\n ValueObjectSP impl_sp(m_backend.GetChildMemberWithName(ConstString(\"__end_\"),true));\n if (!impl_sp)\n return false;\n CompilerType list_type = m_backend.GetCompilerType();\n if (list_type.IsReferenceType())\n list_type = list_type.GetNonReferenceType();\n\n if (list_type.GetNumTemplateArguments() == 0)\n return false;\n lldb::TemplateArgumentKind kind;\n m_element_type = list_type.GetTemplateArgument(0, kind);\n m_head = impl_sp->GetChildMemberWithName(ConstString(\"__next_\"), true).get();\n m_tail = impl_sp->GetChildMemberWithName(ConstString(\"__prev_\"), true).get();\n return false;\n}\n\nbool\nlldb_private::formatters::LibcxxStdListSyntheticFrontEnd::MightHaveChildren ()\n{\n return true;\n}\n\nsize_t\nlldb_private::formatters::LibcxxStdListSyntheticFrontEnd::GetIndexOfChildWithName (const ConstString &name)\n{\n return ExtractIndexFromString(name.GetCString());\n}\n\nSyntheticChildrenFrontEnd*\nlldb_private::formatters::LibcxxStdListSyntheticFrontEndCreator (CXXSyntheticChildren*, lldb::ValueObjectSP valobj_sp)\n{\n return (valobj_sp ? new LibcxxStdListSyntheticFrontEnd(valobj_sp) : nullptr);\n}\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: dlgexpor.hxx,v $\n *\n * $Revision: 1.5 $\n *\n * last change: $Author: rt $ $Date: 2005-09-08 15:36:53 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\n#ifndef _DLGEXPOR_HXX_\n#define _DLGEXPOR_HXX_\n\n#include \"fltcall.hxx\"\n#include <vcl\/dialog.hxx>\n#include <vcl\/button.hxx>\n#include <vcl\/fixed.hxx>\n#include <vcl\/field.hxx>\n#include <vcl\/lstbox.hxx>\n\n\/*************************************************************************\n|*\n|* Dialog zum Einstellen von Filteroptionen bei Pixelformaten\n|*\n\\************************************************************************\/\n\nclass FilterConfigItem;\nclass DlgExportPix : public ModalDialog\n{\nprivate:\n\n FltCallDialogParameter& rFltCallPara;\n\n OKButton aBtnOK;\n CancelButton aBtnCancel;\n HelpButton aBtnHelp;\n\n ListBox aLbColors;\n CheckBox aCbxRLE;\n FixedLine aGrpColors;\n\n RadioButton aRbOriginal;\n RadioButton aRbRes;\n RadioButton aRbSize;\n FixedText aFtSizeX;\n MetricField aMtfSizeX;\n FixedText aFtSizeY;\n MetricField aMtfSizeY;\n FixedLine aGrpMode;\n ComboBox aCbbRes;\n\n FilterConfigItem* pConfigItem;\n ResMgr* pMgr;\n\n String aExt;\n\n DECL_LINK( OK, void* p );\n DECL_LINK( ClickRbOriginal,void* p );\n DECL_LINK( ClickRbRes,void* p );\n DECL_LINK( ClickRbSize,void* p );\n DECL_LINK( SelectLbColors, void* p );\n\npublic:\n DlgExportPix( FltCallDialogParameter& rPara );\n ~DlgExportPix();\n};\n\n\n\/*************************************************************************\n|*\n|* Dialog zum Einstellen von Filteroptionen bei Vektorformaten\n|*\n\\************************************************************************\/\nclass DlgExportVec : public ModalDialog\n{\nprivate:\n\n FltCallDialogParameter& rFltCallPara;\n\n OKButton aBtnOK;\n CancelButton aBtnCancel;\n HelpButton aBtnHelp;\n\n RadioButton aRbOriginal;\n RadioButton aRbSize;\n FixedLine aGrpMode;\n\n FixedText aFtSizeX;\n MetricField aMtfSizeX;\n FixedText aFtSizeY;\n MetricField aMtfSizeY;\n FixedLine aGrpSize;\n\n FilterConfigItem* pConfigItem;\n ResMgr* pMgr;\n\n String aExt;\n\n DECL_LINK( OK, void* p );\n DECL_LINK( ClickRbOriginal,void* p );\n DECL_LINK( ClickRbSize,void* p );\n\npublic:\n DlgExportVec( FltCallDialogParameter& rPara );\n ~DlgExportVec();\n};\n\n#endif \/\/ _DLGEXPOR_HXX_\n\n<commit_msg>INTEGRATION: CWS vgbugs07 (1.5.526); FILE MERGED 2007\/06\/04 13:31:37 vg 1.5.526.1: #i76605# Remove -I ...\/inc\/module hack introduced by hedaburemove01<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: dlgexpor.hxx,v $\n *\n * $Revision: 1.6 $\n *\n * last change: $Author: hr $ $Date: 2007-06-27 21:35:09 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\n#ifndef _DLGEXPOR_HXX_\n#define _DLGEXPOR_HXX_\n\n#include <svtools\/fltcall.hxx>\n#include <vcl\/dialog.hxx>\n#include <vcl\/button.hxx>\n#include <vcl\/fixed.hxx>\n#include <vcl\/field.hxx>\n#include <vcl\/lstbox.hxx>\n\n\/*************************************************************************\n|*\n|* Dialog zum Einstellen von Filteroptionen bei Pixelformaten\n|*\n\\************************************************************************\/\n\nclass FilterConfigItem;\nclass DlgExportPix : public ModalDialog\n{\nprivate:\n\n FltCallDialogParameter& rFltCallPara;\n\n OKButton aBtnOK;\n CancelButton aBtnCancel;\n HelpButton aBtnHelp;\n\n ListBox aLbColors;\n CheckBox aCbxRLE;\n FixedLine aGrpColors;\n\n RadioButton aRbOriginal;\n RadioButton aRbRes;\n RadioButton aRbSize;\n FixedText aFtSizeX;\n MetricField aMtfSizeX;\n FixedText aFtSizeY;\n MetricField aMtfSizeY;\n FixedLine aGrpMode;\n ComboBox aCbbRes;\n\n FilterConfigItem* pConfigItem;\n ResMgr* pMgr;\n\n String aExt;\n\n DECL_LINK( OK, void* p );\n DECL_LINK( ClickRbOriginal,void* p );\n DECL_LINK( ClickRbRes,void* p );\n DECL_LINK( ClickRbSize,void* p );\n DECL_LINK( SelectLbColors, void* p );\n\npublic:\n DlgExportPix( FltCallDialogParameter& rPara );\n ~DlgExportPix();\n};\n\n\n\/*************************************************************************\n|*\n|* Dialog zum Einstellen von Filteroptionen bei Vektorformaten\n|*\n\\************************************************************************\/\nclass DlgExportVec : public ModalDialog\n{\nprivate:\n\n FltCallDialogParameter& rFltCallPara;\n\n OKButton aBtnOK;\n CancelButton aBtnCancel;\n HelpButton aBtnHelp;\n\n RadioButton aRbOriginal;\n RadioButton aRbSize;\n FixedLine aGrpMode;\n\n FixedText aFtSizeX;\n MetricField aMtfSizeX;\n FixedText aFtSizeY;\n MetricField aMtfSizeY;\n FixedLine aGrpSize;\n\n FilterConfigItem* pConfigItem;\n ResMgr* pMgr;\n\n String aExt;\n\n DECL_LINK( OK, void* p );\n DECL_LINK( ClickRbOriginal,void* p );\n DECL_LINK( ClickRbSize,void* p );\n\npublic:\n DlgExportVec( FltCallDialogParameter& rPara );\n ~DlgExportVec();\n};\n\n#endif \/\/ _DLGEXPOR_HXX_\n\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: viewobjectcontact.hxx,v $\n *\n * $Revision: 1.7 $\n *\n * last change: $Author: hr $ $Date: 2007-06-26 12:02:19 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef _SDR_CONTACT_VIEWOBJECTCONTACT_HXX\n#define _SDR_CONTACT_VIEWOBJECTCONTACT_HXX\n\n#ifndef _SAL_TYPES_H_\n#include <sal\/types.h>\n#endif\n\n#include <vector>\n\n#ifndef _TOOLS_DEBUG_HXX\n#include <tools\/debug.hxx>\n#endif\n\n#ifndef _SDR_CONTACT_VIEWOBJECTCONTACTLIST_HXX\n#include <svx\/sdr\/contact\/viewobjectcontactlist.hxx>\n#endif\n\n#ifndef _SV_GEN_HXX\n#include <tools\/gen.hxx>\n#endif\n\n#ifndef INCLUDED_SVXDLLAPI_H\n#include \"svx\/svxdllapi.h\"\n#endif\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ predeclarations\n\nclass Region;\n\nnamespace sdr\n{\n namespace contact\n {\n class ObjectContact;\n class ViewContact;\n class ViewObjectContactRedirector;\n } \/\/ end of namespace contact\n namespace animation\n {\n class AnimationState;\n class AnimationInfo;\n } \/\/ end of namespace animation\n} \/\/ end of namespace sdr\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nnamespace sdr\n{\n namespace contact\n {\n class SVX_DLLPUBLIC ViewObjectContact\n {\n \/\/ must-exist and constant contacts\n ObjectContact& mrObjectContact;\n ViewContact& mrViewContact;\n\n \/\/ for building up a mirror of the draw object hierarchy. One\n \/\/ parent pointer and a list of sub objects.\n ViewObjectContact* mpParent;\n ViewObjectContactList maVOCList;\n\n \/\/ The AnimationState if the object supports animation.\n sdr::animation::AnimationState* mpAnimationState;\n\n protected:\n \/\/ This rectangle remembers the last positive paint output rectangle.\n \/\/ It is then used for invalidating. It needs to be set together with\n \/\/ the mbIsPainted flag.\n Rectangle maPaintedRectangle;\n\n \/\/ bitfield\n \/\/ This flag describes if the object corresponding to this VOC\n \/\/ was painted and thus would need to be invalidated if changes\n \/\/ happen. Init with sal_False.\n unsigned mbIsPainted : 1;\n\n \/\/ This flag remembers if the DrawHierarchy below this entry is\n \/\/ valid or not. Init with sal_False.\n unsigned mbdrawHierarchyValid : 1;\n\n \/\/ method to get the AnimationState. Needs to give a result. It will\n \/\/ return a existing one or create a new one using CreateAnimationState()\n \/\/ at the AnimationInfo.\n sdr::animation::AnimationState* GetAnimationState(sdr::animation::AnimationInfo& rInfo) const;\n\n public:\n \/\/ basic constructor.\n ViewObjectContact(ObjectContact& rObjectContact, ViewContact& rViewContact);\n\n \/\/ The destructor. When PrepareDelete() was not called before (see there)\n \/\/ warnings will be generated in debug version if there are still contacts\n \/\/ existing.\n virtual ~ViewObjectContact();\n\n \/\/ Prepare deletion of this object. This needs to be called always\n \/\/ before really deleting this objects. This is necessary since in a c++\n \/\/ destructor no virtual function calls are allowed. To avoid this problem,\n \/\/ it is required to first call PrepareDelete().\n virtual void PrepareDelete();\n\n \/\/ access to ObjectContact\n ObjectContact& GetObjectContact() const { return mrObjectContact; }\n\n \/\/ access to ViewContact\n ViewContact& GetViewContact() const { return mrViewContact; }\n\n \/\/ access to parent\n void SetParent(ViewObjectContact* pNew) { mpParent = pNew; }\n ViewObjectContact* GetParent() const { return mpParent; }\n\n \/\/ A ViewObjectContact was deleted and shall be forgotten.\n void RemoveViewObjectContact(ViewObjectContact& rVOContact);\n\n \/\/ This method recursively rebuilds the draw hierarchy structure in parallel\n \/\/ to the SdrObject structure.\n void BuildDrawHierarchy(ObjectContact& rObjectContact, ViewContact& rSourceNode);\n\n \/\/ This method recursively checks the draw hierarchy structure in parallel\n \/\/ to the SdrObject structure and rebuilds the invalid parts.\n void CheckDrawHierarchy(ObjectContact& rObjectContact);\n\n \/\/ This method only recursively clears the draw hierarchy structure between the\n \/\/ DrawObjectContacts, it does not delete any to make them reusable.\n void ClearDrawHierarchy();\n\n \/\/ Paint this object. This is before evtl. SubObjects get painted. This method\n \/\/ needs to set the flag mbIsPainted and to set the\n \/\/ maPaintedRectangle member. This information is later used for invalidates\n \/\/ and repaints.\n virtual void PaintObject(DisplayInfo& rDisplayInfo);\n\n \/\/ Pre- and Post-Paint this object. Is used e.g. for page background\/foreground painting.\n virtual void PrePaintObject(DisplayInfo& rDisplayInfo);\n virtual void PostPaintObject(DisplayInfo& rDisplayInfo);\n\n \/\/ Paint this objects DrawHierarchy\n virtual void PaintDrawHierarchy(DisplayInfo& rDisplayInfo);\n\n \/\/ This method recursively paints the draw hierarchy. It is also the\n \/\/ start point for the mechanism seen from the ObjectContact.\n void PaintObjectHierarchy(DisplayInfo& rDisplayInfo);\n\n \/\/ Get info if this is the active group of the view\n sal_Bool IsActiveGroup() const;\n\n \/\/ React on changes of the object of this ViewContact\n virtual void ActionChanged();\n\n \/\/ Get info if it's painted\n sal_Bool IsPainted() const;\n\n \/\/ Get info about the painted rectangle\n const Rectangle& GetPaintedRectangle() const;\n\n \/\/ Take some action when new objects are inserted\n virtual void ActionChildInserted(const Rectangle& rInitialRectangle);\n\n \/\/ Get info about validity of DrawHierarchy,\n \/\/ set to invalid\n sal_Bool IsDrawHierarchyValid() const;\n void InvalidateDrawHierarchy();\n\n \/\/ If DrawHierarchy is handled by a object itself, the sub-objects are set\n \/\/ to be equally painted to that object\n void CopyPaintFlagsFromParent(const ViewObjectContact& rParent);\n\n \/\/ take care for clean shutdown of an existing AnimationState\n void DeleteAnimationState();\n\n \/\/ Check for AnimationFeatures. Take necessary actions to evtl. create\n \/\/ an AnimationState and register at the ObjectContact's animator\n void CheckForAnimationFeatures(sdr::animation::AnimationInfo& rInfo);\n\n \/\/ Test if this VOC has an animation state and thus is animated\n sal_Bool HasAnimationState() const;\n\n \/\/ get the correct redirector\n ViewObjectContactRedirector* GetRedirector() const;\n };\n\n \/\/ typedefs for a list of ViewObjectContact\n typedef ::std::vector< ViewObjectContact* > ViewObjectContactVector;\n\n } \/\/ end of namespace contact\n} \/\/ end of namespace sdr\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#endif \/\/_SDR_CONTACT_VIEWOBJECTCONTACT_HXX\n\n\/\/ eof\n<commit_msg>INTEGRATION: CWS changefileheader (1.7.366); FILE MERGED 2008\/04\/01 15:50:02 thb 1.7.366.3: #i85898# Stripping all external header guards 2008\/04\/01 12:47:51 thb 1.7.366.2: #i85898# Stripping all external header guards 2008\/03\/31 14:18:59 rt 1.7.366.1: #i87441# Change license header to LPGL v3.<commit_after>\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2008 by Sun Microsystems, Inc.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: viewobjectcontact.hxx,v $\n * $Revision: 1.8 $\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * <http:\/\/www.openoffice.org\/license.html>\n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n#ifndef _SDR_CONTACT_VIEWOBJECTCONTACT_HXX\n#define _SDR_CONTACT_VIEWOBJECTCONTACT_HXX\n\n#include <sal\/types.h>\n\n#include <vector>\n#include <tools\/debug.hxx>\n#include <svx\/sdr\/contact\/viewobjectcontactlist.hxx>\n#include <tools\/gen.hxx>\n#include \"svx\/svxdllapi.h\"\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ predeclarations\n\nclass Region;\n\nnamespace sdr\n{\n namespace contact\n {\n class ObjectContact;\n class ViewContact;\n class ViewObjectContactRedirector;\n } \/\/ end of namespace contact\n namespace animation\n {\n class AnimationState;\n class AnimationInfo;\n } \/\/ end of namespace animation\n} \/\/ end of namespace sdr\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nnamespace sdr\n{\n namespace contact\n {\n class SVX_DLLPUBLIC ViewObjectContact\n {\n \/\/ must-exist and constant contacts\n ObjectContact& mrObjectContact;\n ViewContact& mrViewContact;\n\n \/\/ for building up a mirror of the draw object hierarchy. One\n \/\/ parent pointer and a list of sub objects.\n ViewObjectContact* mpParent;\n ViewObjectContactList maVOCList;\n\n \/\/ The AnimationState if the object supports animation.\n sdr::animation::AnimationState* mpAnimationState;\n\n protected:\n \/\/ This rectangle remembers the last positive paint output rectangle.\n \/\/ It is then used for invalidating. It needs to be set together with\n \/\/ the mbIsPainted flag.\n Rectangle maPaintedRectangle;\n\n \/\/ bitfield\n \/\/ This flag describes if the object corresponding to this VOC\n \/\/ was painted and thus would need to be invalidated if changes\n \/\/ happen. Init with sal_False.\n unsigned mbIsPainted : 1;\n\n \/\/ This flag remembers if the DrawHierarchy below this entry is\n \/\/ valid or not. Init with sal_False.\n unsigned mbdrawHierarchyValid : 1;\n\n \/\/ method to get the AnimationState. Needs to give a result. It will\n \/\/ return a existing one or create a new one using CreateAnimationState()\n \/\/ at the AnimationInfo.\n sdr::animation::AnimationState* GetAnimationState(sdr::animation::AnimationInfo& rInfo) const;\n\n public:\n \/\/ basic constructor.\n ViewObjectContact(ObjectContact& rObjectContact, ViewContact& rViewContact);\n\n \/\/ The destructor. When PrepareDelete() was not called before (see there)\n \/\/ warnings will be generated in debug version if there are still contacts\n \/\/ existing.\n virtual ~ViewObjectContact();\n\n \/\/ Prepare deletion of this object. This needs to be called always\n \/\/ before really deleting this objects. This is necessary since in a c++\n \/\/ destructor no virtual function calls are allowed. To avoid this problem,\n \/\/ it is required to first call PrepareDelete().\n virtual void PrepareDelete();\n\n \/\/ access to ObjectContact\n ObjectContact& GetObjectContact() const { return mrObjectContact; }\n\n \/\/ access to ViewContact\n ViewContact& GetViewContact() const { return mrViewContact; }\n\n \/\/ access to parent\n void SetParent(ViewObjectContact* pNew) { mpParent = pNew; }\n ViewObjectContact* GetParent() const { return mpParent; }\n\n \/\/ A ViewObjectContact was deleted and shall be forgotten.\n void RemoveViewObjectContact(ViewObjectContact& rVOContact);\n\n \/\/ This method recursively rebuilds the draw hierarchy structure in parallel\n \/\/ to the SdrObject structure.\n void BuildDrawHierarchy(ObjectContact& rObjectContact, ViewContact& rSourceNode);\n\n \/\/ This method recursively checks the draw hierarchy structure in parallel\n \/\/ to the SdrObject structure and rebuilds the invalid parts.\n void CheckDrawHierarchy(ObjectContact& rObjectContact);\n\n \/\/ This method only recursively clears the draw hierarchy structure between the\n \/\/ DrawObjectContacts, it does not delete any to make them reusable.\n void ClearDrawHierarchy();\n\n \/\/ Paint this object. This is before evtl. SubObjects get painted. This method\n \/\/ needs to set the flag mbIsPainted and to set the\n \/\/ maPaintedRectangle member. This information is later used for invalidates\n \/\/ and repaints.\n virtual void PaintObject(DisplayInfo& rDisplayInfo);\n\n \/\/ Pre- and Post-Paint this object. Is used e.g. for page background\/foreground painting.\n virtual void PrePaintObject(DisplayInfo& rDisplayInfo);\n virtual void PostPaintObject(DisplayInfo& rDisplayInfo);\n\n \/\/ Paint this objects DrawHierarchy\n virtual void PaintDrawHierarchy(DisplayInfo& rDisplayInfo);\n\n \/\/ This method recursively paints the draw hierarchy. It is also the\n \/\/ start point for the mechanism seen from the ObjectContact.\n void PaintObjectHierarchy(DisplayInfo& rDisplayInfo);\n\n \/\/ Get info if this is the active group of the view\n sal_Bool IsActiveGroup() const;\n\n \/\/ React on changes of the object of this ViewContact\n virtual void ActionChanged();\n\n \/\/ Get info if it's painted\n sal_Bool IsPainted() const;\n\n \/\/ Get info about the painted rectangle\n const Rectangle& GetPaintedRectangle() const;\n\n \/\/ Take some action when new objects are inserted\n virtual void ActionChildInserted(const Rectangle& rInitialRectangle);\n\n \/\/ Get info about validity of DrawHierarchy,\n \/\/ set to invalid\n sal_Bool IsDrawHierarchyValid() const;\n void InvalidateDrawHierarchy();\n\n \/\/ If DrawHierarchy is handled by a object itself, the sub-objects are set\n \/\/ to be equally painted to that object\n void CopyPaintFlagsFromParent(const ViewObjectContact& rParent);\n\n \/\/ take care for clean shutdown of an existing AnimationState\n void DeleteAnimationState();\n\n \/\/ Check for AnimationFeatures. Take necessary actions to evtl. create\n \/\/ an AnimationState and register at the ObjectContact's animator\n void CheckForAnimationFeatures(sdr::animation::AnimationInfo& rInfo);\n\n \/\/ Test if this VOC has an animation state and thus is animated\n sal_Bool HasAnimationState() const;\n\n \/\/ get the correct redirector\n ViewObjectContactRedirector* GetRedirector() const;\n };\n\n \/\/ typedefs for a list of ViewObjectContact\n typedef ::std::vector< ViewObjectContact* > ViewObjectContactVector;\n\n } \/\/ end of namespace contact\n} \/\/ end of namespace sdr\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#endif \/\/_SDR_CONTACT_VIEWOBJECTCONTACT_HXX\n\n\/\/ eof\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: viewcontactofgroup.cxx,v $\n *\n * $Revision: 1.5 $\n *\n * last change: $Author: obo $ $Date: 2006-09-17 05:35:43 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_svx.hxx\"\n\n#ifndef _SDR_CONTACT_VIEWCONTACTOFGROUP_HXX\n#include <svx\/sdr\/contact\/viewcontactofgroup.hxx>\n#endif\n\n#ifndef _SVDOGRP_HXX\n#include <svdogrp.hxx>\n#endif\n\n#ifndef _SVDPAGE_HXX\n#include <svdpage.hxx>\n#endif\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nnamespace sdr\n{\n namespace contact\n {\n \/\/ method to recalculate the PaintRectangle if the validity flag shows that\n \/\/ it is invalid. The flag is set from GetPaintRectangle, thus the implementation\n \/\/ only needs to refresh maPaintRectangle itself.\n void ViewContactOfGroup::CalcPaintRectangle()\n {\n maPaintRectangle = GetSdrObjGroup().GetCurrentBoundRect();\n }\n\n ViewContactOfGroup::ViewContactOfGroup(SdrObjGroup& rGroup)\n : ViewContactOfSdrObj(rGroup)\n {\n }\n\n ViewContactOfGroup::~ViewContactOfGroup()\n {\n }\n\n \/\/ When ShouldPaintObject() returns sal_True, the object itself is painted and\n \/\/ PaintObject() is called.\n sal_Bool ViewContactOfGroup::ShouldPaintObject(DisplayInfo& \/*rDisplayInfo*\/, const ViewObjectContact& \/*rAssociatedVOC*\/)\n {\n \/\/ Do not paint groups themthelves only when they are empty\n if(!GetSdrObjGroup().GetSubList() || !GetSdrObjGroup().GetSubList()->GetObjCount())\n {\n \/\/ Paint empty group to get a replacement visualisation\n return sal_True;\n }\n\n return sal_False;\n }\n\n \/\/ Paint this object. This is before evtl. SubObjects get painted. It needs to return\n \/\/ sal_True when something was pained and the paint output rectangle in rPaintRectangle.\n sal_Bool ViewContactOfGroup::PaintObject(DisplayInfo& rDisplayInfo, Rectangle& rPaintRectangle, const ViewObjectContact& \/*rAssociatedVOC*\/)\n {\n \/\/ Paint the object. If this is called, the group is empty.\n \/\/ Paint a replacement object.\n return PaintReplacementObject(rDisplayInfo, rPaintRectangle);\n }\n } \/\/ end of namespace contact\n} \/\/ end of namespace sdr\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ eof\n<commit_msg>INTEGRATION: CWS vgbugs07 (1.5.350); FILE MERGED 2007\/06\/04 13:27:15 vg 1.5.350.1: #i76605# Remove -I ...\/inc\/module hack introduced by hedaburemove01<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: viewcontactofgroup.cxx,v $\n *\n * $Revision: 1.6 $\n *\n * last change: $Author: hr $ $Date: 2007-06-27 18:45:09 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_svx.hxx\"\n\n#ifndef _SDR_CONTACT_VIEWCONTACTOFGROUP_HXX\n#include <svx\/sdr\/contact\/viewcontactofgroup.hxx>\n#endif\n\n#ifndef _SVDOGRP_HXX\n#include <svx\/svdogrp.hxx>\n#endif\n\n#ifndef _SVDPAGE_HXX\n#include <svx\/svdpage.hxx>\n#endif\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nnamespace sdr\n{\n namespace contact\n {\n \/\/ method to recalculate the PaintRectangle if the validity flag shows that\n \/\/ it is invalid. The flag is set from GetPaintRectangle, thus the implementation\n \/\/ only needs to refresh maPaintRectangle itself.\n void ViewContactOfGroup::CalcPaintRectangle()\n {\n maPaintRectangle = GetSdrObjGroup().GetCurrentBoundRect();\n }\n\n ViewContactOfGroup::ViewContactOfGroup(SdrObjGroup& rGroup)\n : ViewContactOfSdrObj(rGroup)\n {\n }\n\n ViewContactOfGroup::~ViewContactOfGroup()\n {\n }\n\n \/\/ When ShouldPaintObject() returns sal_True, the object itself is painted and\n \/\/ PaintObject() is called.\n sal_Bool ViewContactOfGroup::ShouldPaintObject(DisplayInfo& \/*rDisplayInfo*\/, const ViewObjectContact& \/*rAssociatedVOC*\/)\n {\n \/\/ Do not paint groups themthelves only when they are empty\n if(!GetSdrObjGroup().GetSubList() || !GetSdrObjGroup().GetSubList()->GetObjCount())\n {\n \/\/ Paint empty group to get a replacement visualisation\n return sal_True;\n }\n\n return sal_False;\n }\n\n \/\/ Paint this object. This is before evtl. SubObjects get painted. It needs to return\n \/\/ sal_True when something was pained and the paint output rectangle in rPaintRectangle.\n sal_Bool ViewContactOfGroup::PaintObject(DisplayInfo& rDisplayInfo, Rectangle& rPaintRectangle, const ViewObjectContact& \/*rAssociatedVOC*\/)\n {\n \/\/ Paint the object. If this is called, the group is empty.\n \/\/ Paint a replacement object.\n return PaintReplacementObject(rDisplayInfo, rPaintRectangle);\n }\n } \/\/ end of namespace contact\n} \/\/ end of namespace sdr\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ eof\n<|endoftext|>"} {"text":"<commit_before>#include \"directinput\/Manager.h\"\r\n#include \"directinput\/Keyboard.h\"\r\n#include \"directinput\/Joystick.h\"\r\n#include <stdexcept>\r\n\r\nusing namespace Framework::DirectInput;\r\n\r\nCManager::CManager()\r\n: m_updateThreadHandle(NULL)\r\n, m_updateThreadOver(false)\r\n, m_nextInputEventHandlerId(1)\r\n{\r\n\tif(FAILED(DirectInput8Create(GetModuleHandle(NULL), DIRECTINPUT_VERSION, IID_IDirectInput8, reinterpret_cast<void**>(&m_directInput), NULL)))\r\n\t{\r\n\t\tthrow std::runtime_error(\"Couldn't create DirectInput8\");\r\n\t}\r\n\tm_directInput->EnumDevices(DI8DEVCLASS_GAMECTRL, &CManager::EnumDevicesCallback, this, DIEDFL_ATTACHEDONLY);\r\n\t{\r\n\t\tDWORD threadId = 0;\r\n\t\tInitializeCriticalSection(&m_updateMutex);\r\n\t\tm_updateThreadHandle = CreateThread(NULL, NULL, &CManager::UpdateThreadProcStub, this, NULL, &threadId);\r\n\t}\r\n}\r\n\r\nCManager::~CManager()\r\n{\r\n\tm_updateThreadOver = true;\r\n\tWaitForSingleObject(m_updateThreadHandle, INFINITE);\r\n\tDeleteCriticalSection(&m_updateMutex);\r\n}\r\n\r\nuint32 CManager::RegisterInputEventHandler(const InputEventHandler& inputEventHandler)\r\n{\r\n\tuint32 eventHandlerId = m_nextInputEventHandlerId++;\r\n\tEnterCriticalSection(&m_updateMutex);\r\n\t{\r\n\t\tm_inputEventHandlers[eventHandlerId] = inputEventHandler;\r\n\t}\r\n\tLeaveCriticalSection(&m_updateMutex);\r\n\treturn eventHandlerId;\r\n}\r\n\r\nvoid CManager::UnregisterInputEventHandler(uint32 eventHandlerId)\r\n{\r\n\tEnterCriticalSection(&m_updateMutex);\r\n\t{\r\n\t\tauto inputEventHandlerIterator = m_inputEventHandlers.find(eventHandlerId);\r\n\t\tassert(inputEventHandlerIterator != std::end(m_inputEventHandlers));\r\n\t\tm_inputEventHandlers.erase(inputEventHandlerIterator);\r\n\t}\r\n\tLeaveCriticalSection(&m_updateMutex);\r\n}\r\n\r\nvoid CManager::CreateKeyboard(HWND window)\r\n{\r\n\tCDevice::DirectInputDevicePtr device;\r\n\tif(FAILED(m_directInput->CreateDevice(GUID_SysKeyboard, &device, NULL)))\r\n\t{\r\n\t\tthrow std::runtime_error(\"Couldn't create device.\");\r\n\t}\r\n\tEnterCriticalSection(&m_updateMutex);\r\n\t{\r\n\t\tm_devices[GUID_SysKeyboard] = std::make_shared<CKeyboard>(device, window);\r\n\t}\r\n\tLeaveCriticalSection(&m_updateMutex);\r\n}\r\n\r\nvoid CManager::CreateJoysticks(HWND window)\r\n{\r\n\tfor(auto joystickIterator(std::begin(m_joystickInstances));\r\n\t\tstd::end(m_joystickInstances) != joystickIterator; joystickIterator++)\r\n\t{\r\n\t\tCDevice::DirectInputDevicePtr device;\r\n\t\tconst auto& deviceGuid(*joystickIterator);\r\n\t\tif(FAILED(m_directInput->CreateDevice(deviceGuid, &device, NULL)))\r\n\t\t{\r\n\t\t\tcontinue;\r\n\t\t}\r\n\t\tEnterCriticalSection(&m_updateMutex);\r\n\t\t{\r\n\t\t\tm_devices[deviceGuid] = std::make_shared<CJoystick>(device, window);\r\n\t\t}\r\n\t\tLeaveCriticalSection(&m_updateMutex);\r\n\t}\r\n}\r\n\r\nbool CManager::GetDeviceInfo(const GUID& deviceId, DIDEVICEINSTANCE* deviceInfo)\r\n{\r\n\tif(!deviceInfo) return false;\r\n\tauto deviceIterator(m_devices.find(deviceId));\r\n\tif(deviceIterator == std::end(m_devices)) return false;\r\n\tauto& device = deviceIterator->second;\r\n\treturn device->GetInfo(deviceInfo);\r\n}\r\n\r\nbool CManager::GetDeviceObjectInfo(const GUID& deviceId, uint32 id, DIDEVICEOBJECTINSTANCE* objectInfo)\r\n{\r\n\tif(!objectInfo) return false;\r\n\tauto deviceIterator(m_devices.find(deviceId));\r\n\tif(deviceIterator == std::end(m_devices)) return false;\r\n\tauto& device = deviceIterator->second;\r\n\treturn device->GetObjectInfo(id, objectInfo);\r\n}\r\n\r\nBOOL CALLBACK CManager::EnumDevicesCallback(LPCDIDEVICEINSTANCE lpddi, LPVOID pvRef)\r\n{\r\n\treturn static_cast<CManager*>(pvRef)->EnumDevicesCallbackImpl(lpddi);\r\n}\r\n\r\nBOOL CManager::EnumDevicesCallbackImpl(LPCDIDEVICEINSTANCE lpddi)\r\n{\r\n\tm_joystickInstances.push_back(lpddi->guidInstance);\r\n\treturn DIENUM_CONTINUE;\r\n}\r\n\r\nvoid CManager::CallInputEventHandlers(const GUID& device, uint32 id, uint32 value)\r\n{\r\n\tfor(auto inputEventHandlerIterator(std::begin(m_inputEventHandlers));\r\n\t\tinputEventHandlerIterator != std::end(m_inputEventHandlers); inputEventHandlerIterator++)\r\n\t{\r\n\t\tinputEventHandlerIterator->second(device, id, value);\r\n\t}\r\n}\r\n\r\nDWORD CManager::UpdateThreadProc()\r\n{\r\n\tauto inputEventHandler = std::bind(&CManager::CallInputEventHandlers, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3);\r\n\twhile(!m_updateThreadOver)\r\n\t{\r\n\t\tEnterCriticalSection(&m_updateMutex);\r\n\t\t{\r\n\t\t\tfor(auto deviceIterator(std::begin(m_devices));\r\n\t\t\t\tdeviceIterator != std::end(m_devices); deviceIterator++)\r\n\t\t\t{\r\n\t\t\t\tauto& device = deviceIterator->second;\r\n\t\t\t\tdevice->ProcessEvents(inputEventHandler);\r\n\t\t\t}\r\n\t\t}\r\n\t\tLeaveCriticalSection(&m_updateMutex);\r\n\t\tSleep(16);\r\n\t}\r\n\treturn 0;\r\n}\r\n\r\nDWORD WINAPI CManager::UpdateThreadProcStub(void* param)\r\n{\r\n\treturn reinterpret_cast<CManager*>(param)->UpdateThreadProc();\r\n}\r\n<commit_msg>More cleanup.<commit_after>#include \"directinput\/Manager.h\"\r\n#include \"directinput\/Keyboard.h\"\r\n#include \"directinput\/Joystick.h\"\r\n#include <stdexcept>\r\n\r\nusing namespace Framework::DirectInput;\r\n\r\nCManager::CManager()\r\n: m_updateThreadHandle(NULL)\r\n, m_updateThreadOver(false)\r\n, m_nextInputEventHandlerId(1)\r\n{\r\n\tif(FAILED(DirectInput8Create(GetModuleHandle(NULL), DIRECTINPUT_VERSION, IID_IDirectInput8, reinterpret_cast<void**>(&m_directInput), NULL)))\r\n\t{\r\n\t\tthrow std::runtime_error(\"Couldn't create DirectInput8\");\r\n\t}\r\n\tm_directInput->EnumDevices(DI8DEVCLASS_GAMECTRL, &CManager::EnumDevicesCallback, this, DIEDFL_ATTACHEDONLY);\r\n\t{\r\n\t\tDWORD threadId = 0;\r\n\t\tInitializeCriticalSection(&m_updateMutex);\r\n\t\tm_updateThreadHandle = CreateThread(NULL, NULL, &CManager::UpdateThreadProcStub, this, NULL, &threadId);\r\n\t}\r\n}\r\n\r\nCManager::~CManager()\r\n{\r\n\tm_updateThreadOver = true;\r\n\tWaitForSingleObject(m_updateThreadHandle, INFINITE);\r\n\tDeleteCriticalSection(&m_updateMutex);\r\n}\r\n\r\nuint32 CManager::RegisterInputEventHandler(const InputEventHandler& inputEventHandler)\r\n{\r\n\tuint32 eventHandlerId = m_nextInputEventHandlerId++;\r\n\tEnterCriticalSection(&m_updateMutex);\r\n\t{\r\n\t\tm_inputEventHandlers[eventHandlerId] = inputEventHandler;\r\n\t}\r\n\tLeaveCriticalSection(&m_updateMutex);\r\n\treturn eventHandlerId;\r\n}\r\n\r\nvoid CManager::UnregisterInputEventHandler(uint32 eventHandlerId)\r\n{\r\n\tEnterCriticalSection(&m_updateMutex);\r\n\t{\r\n\t\tauto inputEventHandlerIterator = m_inputEventHandlers.find(eventHandlerId);\r\n\t\tassert(inputEventHandlerIterator != std::end(m_inputEventHandlers));\r\n\t\tm_inputEventHandlers.erase(inputEventHandlerIterator);\r\n\t}\r\n\tLeaveCriticalSection(&m_updateMutex);\r\n}\r\n\r\nvoid CManager::CreateKeyboard(HWND window)\r\n{\r\n\tCDevice::DirectInputDevicePtr device;\r\n\tif(FAILED(m_directInput->CreateDevice(GUID_SysKeyboard, &device, NULL)))\r\n\t{\r\n\t\tthrow std::runtime_error(\"Couldn't create device.\");\r\n\t}\r\n\tEnterCriticalSection(&m_updateMutex);\r\n\t{\r\n\t\tm_devices[GUID_SysKeyboard] = std::make_shared<CKeyboard>(device, window);\r\n\t}\r\n\tLeaveCriticalSection(&m_updateMutex);\r\n}\r\n\r\nvoid CManager::CreateJoysticks(HWND window)\r\n{\r\n\tfor(const auto& joystickInstance : m_joystickInstances)\r\n\t{\r\n\t\tCDevice::DirectInputDevicePtr device;\r\n\t\tif(FAILED(m_directInput->CreateDevice(joystickInstance, &device, NULL)))\r\n\t\t{\r\n\t\t\tcontinue;\r\n\t\t}\r\n\t\tEnterCriticalSection(&m_updateMutex);\r\n\t\t{\r\n\t\t\tm_devices[joystickInstance] = std::make_shared<CJoystick>(device, window);\r\n\t\t}\r\n\t\tLeaveCriticalSection(&m_updateMutex);\r\n\t}\r\n}\r\n\r\nbool CManager::GetDeviceInfo(const GUID& deviceId, DIDEVICEINSTANCE* deviceInfo)\r\n{\r\n\tif(!deviceInfo) return false;\r\n\tauto deviceIterator(m_devices.find(deviceId));\r\n\tif(deviceIterator == std::end(m_devices)) return false;\r\n\tauto& device = deviceIterator->second;\r\n\treturn device->GetInfo(deviceInfo);\r\n}\r\n\r\nbool CManager::GetDeviceObjectInfo(const GUID& deviceId, uint32 id, DIDEVICEOBJECTINSTANCE* objectInfo)\r\n{\r\n\tif(!objectInfo) return false;\r\n\tauto deviceIterator(m_devices.find(deviceId));\r\n\tif(deviceIterator == std::end(m_devices)) return false;\r\n\tauto& device = deviceIterator->second;\r\n\treturn device->GetObjectInfo(id, objectInfo);\r\n}\r\n\r\nBOOL CALLBACK CManager::EnumDevicesCallback(LPCDIDEVICEINSTANCE lpddi, LPVOID pvRef)\r\n{\r\n\treturn static_cast<CManager*>(pvRef)->EnumDevicesCallbackImpl(lpddi);\r\n}\r\n\r\nBOOL CManager::EnumDevicesCallbackImpl(LPCDIDEVICEINSTANCE lpddi)\r\n{\r\n\tm_joystickInstances.push_back(lpddi->guidInstance);\r\n\treturn DIENUM_CONTINUE;\r\n}\r\n\r\nvoid CManager::CallInputEventHandlers(const GUID& device, uint32 id, uint32 value)\r\n{\r\n\tfor(const auto& inputEventHandler : m_inputEventHandlers)\r\n\t{\r\n\t\tinputEventHandler.second(device, id, value);\r\n\t}\r\n}\r\n\r\nDWORD CManager::UpdateThreadProc()\r\n{\r\n\tauto inputEventHandler = std::bind(&CManager::CallInputEventHandlers, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3);\r\n\twhile(!m_updateThreadOver)\r\n\t{\r\n\t\tEnterCriticalSection(&m_updateMutex);\r\n\t\t{\r\n\t\t\tfor(auto deviceIterator(std::begin(m_devices));\r\n\t\t\t\tdeviceIterator != std::end(m_devices); deviceIterator++)\r\n\t\t\t{\r\n\t\t\t\tauto& device = deviceIterator->second;\r\n\t\t\t\tdevice->ProcessEvents(inputEventHandler);\r\n\t\t\t}\r\n\t\t}\r\n\t\tLeaveCriticalSection(&m_updateMutex);\r\n\t\tSleep(16);\r\n\t}\r\n\treturn 0;\r\n}\r\n\r\nDWORD WINAPI CManager::UpdateThreadProcStub(void* param)\r\n{\r\n\treturn reinterpret_cast<CManager*>(param)->UpdateThreadProc();\r\n}\r\n<|endoftext|>"} {"text":"<commit_before>\/****************************************************************************\n**\n** Copyright (C) 2014 Digia Plc and\/or its subsidiary(-ies).\n** Contact: http:\/\/www.qt-project.org\/legal\n**\n** This file is part of Qt Creator.\n**\n** Commercial License Usage\n** Licensees holding valid commercial Qt licenses may use this file in\n** accordance with the commercial license agreement provided with the\n** Software or, alternatively, in accordance with the terms contained in\n** a written agreement between you and Digia. For licensing terms and\n** conditions see http:\/\/qt.digia.com\/licensing. For further information\n** use the contact form at http:\/\/qt.digia.com\/contact-us.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Digia gives you certain additional\n** rights. These rights are described in the Digia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n****************************************************************************\/\n\n#include \"iosprobe.h\"\n\n#include <utils\/logging.h>\n\n#include <QFileInfo>\n#include <QProcess>\n#include <QDir>\n#include <QFileInfoList>\n\nnamespace {\nQ_LOGGING_CATEGORY(probeLog, \"qtc.ios.probe\")\n}\nnamespace Ios {\n\nstatic QString qsystem(const QString &exe, const QStringList &args = QStringList())\n{\n QProcess p;\n p.setProcessChannelMode(QProcess::MergedChannels);\n p.start(exe, args);\n p.waitForFinished();\n return QString::fromLocal8Bit(p.readAll());\n}\n\nQMap<QString, Platform> IosProbe::detectPlatforms(const QString &devPath)\n{\n IosProbe probe;\n probe.addDeveloperPath(devPath);\n probe.detectFirst();\n return probe.detectedPlatforms();\n}\n\nstatic int compareVersions(const QString &v1, const QString &v2)\n{\n QStringList v1L = v1.split(QLatin1Char('.'));\n QStringList v2L = v2.split(QLatin1Char('.'));\n int i = 0;\n while (v1.length() > i && v1.length() > i) {\n bool n1Ok, n2Ok;\n int n1 = v1L.value(i).toInt(&n1Ok);\n int n2 = v2L.value(i).toInt(&n2Ok);\n if (!(n1Ok && n2Ok)) {\n qCWarning(probeLog) << QString::fromLatin1(\"Failed to compare version %1 and %2\").arg(v1, v2);\n return 0;\n }\n if (n1 > n2)\n return -1;\n else if (n1 < n2)\n return 1;\n ++i;\n }\n if (v1.length() > v2.length())\n return -1;\n if (v1.length() < v2.length())\n return 1;\n return 0;\n}\n\nvoid IosProbe::addDeveloperPath(const QString &path)\n{\n if (path.isEmpty())\n return;\n QFileInfo pInfo(path);\n if (!pInfo.exists() || !pInfo.isDir())\n return;\n if (m_developerPaths.contains(path))\n return;\n m_developerPaths.append(path);\n qCDebug(probeLog) << QString::fromLatin1(\"Added developer path %1\").arg(path);\n}\n\nvoid IosProbe::detectDeveloperPaths()\n{\n QProcess selectedXcode;\n QString program = QLatin1String(\"\/usr\/bin\/xcode-select\");\n QStringList arguments(QLatin1String(\"--print-path\"));\n selectedXcode.start(program, arguments, QProcess::ReadOnly);\n if (!selectedXcode.waitForFinished() || selectedXcode.exitCode()) {\n qCWarning(probeLog) << QString::fromLatin1(\"Could not detect selected xcode with \/usr\/bin\/xcode-select\");\n } else {\n QString path = QString::fromLocal8Bit(selectedXcode.readAllStandardOutput());\n path.chop(1);\n addDeveloperPath(path);\n }\n addDeveloperPath(QLatin1String(\"\/Applications\/Xcode.app\/Contents\/Developer\"));\n}\n\nvoid IosProbe::setupDefaultToolchains(const QString &devPath, const QString &xcodeName)\n{\n qCDebug(probeLog) << QString::fromLatin1(\"Setting up platform \\\"%1\\\".\").arg(xcodeName);\n QString indent = QLatin1String(\" \");\n\n \/\/ detect clang (default toolchain)\n QFileInfo clangFileInfo(devPath\n + QLatin1String(\"\/Toolchains\/XcodeDefault.xctoolchain\/usr\/bin\")\n + QLatin1String(\"\/clang++\"));\n bool hasClang = clangFileInfo.exists();\n if (!hasClang)\n qCWarning(probeLog) << indent << QString::fromLatin1(\"Default toolchain %1 not found.\")\n .arg(clangFileInfo.canonicalFilePath());\n \/\/ Platforms\n QDir platformsDir(devPath + QLatin1String(\"\/Platforms\"));\n QFileInfoList platforms = platformsDir.entryInfoList(QDir::Dirs | QDir::NoDotAndDotDot);\n foreach (const QFileInfo &fInfo, platforms) {\n if (fInfo.isDir() && fInfo.suffix() == QLatin1String(\"platform\")) {\n qCDebug(probeLog) << indent << QString::fromLatin1(\"Setting up %1\").arg(fInfo.fileName());\n QSettingsPtr infoSettings(new QSettings(\n fInfo.absoluteFilePath() + QLatin1String(\"\/Info.plist\"),\n QSettings::NativeFormat));\n if (!infoSettings->contains(QLatin1String(\"Name\"))) {\n qCWarning(probeLog) << indent << QString::fromLatin1(\"Missing platform name in Info.plist of %1\")\n .arg(fInfo.absoluteFilePath());\n continue;\n }\n QString name = infoSettings->value(QLatin1String(\"Name\")).toString();\n if (name != QLatin1String(\"macosx\") && name != QLatin1String(\"iphoneos\")\n && name != QLatin1String(\"iphonesimulator\"))\n {\n qCWarning(probeLog) << indent << QString::fromLatin1(\"Skipping unknown platform %1\").arg(name);\n continue;\n }\n\n \/\/ prepare default platform properties\n QVariantMap defaultProp = infoSettings->value(QLatin1String(\"DefaultProperties\"))\n .toMap();\n QVariantMap overrideProp = infoSettings->value(QLatin1String(\"OverrideProperties\"))\n .toMap();\n QMapIterator<QString, QVariant> i(overrideProp);\n while (i.hasNext()) {\n i.next();\n \/\/ use unite? might lead to double insertions...\n defaultProp[i.key()] = i.value();\n }\n\n QString clangFullName = name + QLatin1String(\"-clang\") + xcodeName;\n QString clang11FullName = name + QLatin1String(\"-clang11\") + xcodeName;\n \/\/ detect gcc\n QFileInfo gccFileInfo(fInfo.absoluteFilePath() + QLatin1String(\"\/Developer\/usr\/bin\/g++\"));\n QString gccFullName = name + QLatin1String(\"-gcc\") + xcodeName;\n if (!gccFileInfo.exists())\n gccFileInfo = QFileInfo(devPath + QLatin1String(\"\/usr\/bin\/g++\"));\n bool hasGcc = gccFileInfo.exists();\n\n QStringList extraFlags;\n if (defaultProp.contains(QLatin1String(\"NATIVE_ARCH\"))) {\n QString arch = defaultProp.value(QLatin1String(\"NATIVE_ARCH\")).toString();\n if (!arch.startsWith(QLatin1String(\"arm\")))\n qCWarning(probeLog) << indent << QString::fromLatin1(\"Expected arm architecture, not %1\").arg(arch);\n extraFlags << QLatin1String(\"-arch\") << arch;\n } else if (name == QLatin1String(\"iphonesimulator\")) {\n \/\/ don't generate a toolchain for 64 bit (to fix when we support that)\n extraFlags << QLatin1String(\"-arch\") << QLatin1String(\"i386\");\n }\n if (hasClang) {\n Platform clangProfile;\n clangProfile.developerPath = Utils::FileName::fromString(devPath);\n clangProfile.platformKind = 0;\n clangProfile.name = clangFullName;\n clangProfile.platformPath = Utils::FileName(fInfo);\n clangProfile.platformInfo = infoSettings;\n clangProfile.compilerPath = Utils::FileName(clangFileInfo);\n QStringList flags = extraFlags;\n flags << QLatin1String(\"-dumpmachine\");\n QString compilerTriplet = qsystem(clangFileInfo.canonicalFilePath(), flags)\n .simplified();\n QStringList compilerTripletl = compilerTriplet.split(QLatin1Char('-'));\n clangProfile.architecture = compilerTripletl.value(0);\n clangProfile.backendFlags = extraFlags;\n qCDebug(probeLog) << indent << QString::fromLatin1(\"* adding profile %1\").arg(clangProfile.name);\n m_platforms[clangProfile.name] = clangProfile;\n clangProfile.platformKind |= Platform::Cxx11Support;\n clangProfile.backendFlags.append(QLatin1String(\"-std=c++11\"));\n clangProfile.backendFlags.append(QLatin1String(\"-stdlib=libc++\"));\n clangProfile.name = clang11FullName;\n m_platforms[clangProfile.name] = clangProfile;\n }\n if (hasGcc) {\n Platform gccProfile;\n gccProfile.developerPath = Utils::FileName::fromString(devPath);\n gccProfile.name = gccFullName;\n gccProfile.platformKind = 0;\n \/\/ use the arm-apple-darwin10-llvm-* variant and avoid the extraFlags if available???\n gccProfile.platformPath = Utils::FileName(fInfo);\n gccProfile.platformInfo = infoSettings;\n gccProfile.compilerPath = Utils::FileName(gccFileInfo);\n QStringList flags = extraFlags;\n flags << QLatin1String(\"-dumpmachine\");\n QString compilerTriplet = qsystem(gccFileInfo.canonicalFilePath(), flags)\n .simplified();\n QStringList compilerTripletl = compilerTriplet.split(QLatin1Char('-'));\n gccProfile.architecture = compilerTripletl.value(0);\n gccProfile.backendFlags = extraFlags;\n qCDebug(probeLog) << indent << QString::fromLatin1(\"* adding profile %1\").arg(gccProfile.name);\n m_platforms[gccProfile.name] = gccProfile;\n }\n\n \/\/ set SDKs\/sysroot\n QString sysRoot;\n QSettingsPtr sdkSettings;\n {\n QString sdkName;\n if (defaultProp.contains(QLatin1String(\"SDKROOT\")))\n sdkName = defaultProp.value(QLatin1String(\"SDKROOT\")).toString();\n QString sdkPath;\n QDir sdks(fInfo.absoluteFilePath() + QLatin1String(\"\/Developer\/SDKs\"));\n QString maxVersion;\n foreach (const QFileInfo &sdkDirInfo, sdks.entryInfoList(QDir::Dirs\n | QDir::NoDotAndDotDot)) {\n indent = QLatin1String(\" \");\n QSettingsPtr sdkInfo(new QSettings(sdkDirInfo.absoluteFilePath()\n + QLatin1String(\"\/SDKSettings.plist\"),\n QSettings::NativeFormat));\n QString versionStr = sdkInfo->value(QLatin1String(\"Version\")).toString();\n QVariant currentSdkName = sdkInfo->value(QLatin1String(\"CanonicalName\"));\n bool isBaseSdk = sdkInfo->value((QLatin1String(\"isBaseSDK\"))).toString()\n .toLower() != QLatin1String(\"no\");\n if (!isBaseSdk) {\n qCDebug(probeLog) << indent << QString::fromLatin1(\"Skipping non base Sdk %1\")\n .arg(currentSdkName.toString());\n continue;\n }\n if (sdkName.isEmpty()) {\n if (compareVersions(maxVersion, versionStr) > 0) {\n maxVersion = versionStr;\n sdkPath = sdkDirInfo.canonicalFilePath();\n sdkSettings = sdkInfo;\n }\n } else if (currentSdkName == sdkName) {\n sdkPath = sdkDirInfo.canonicalFilePath();\n sdkSettings = sdkInfo;\n }\n }\n if (!sdkPath.isEmpty())\n sysRoot = sdkPath;\n else if (!sdkName.isEmpty())\n qCDebug(probeLog) << indent << QString::fromLatin1(\"Failed to find sysroot %1\").arg(sdkName);\n }\n if (hasClang && !sysRoot.isEmpty()) {\n m_platforms[clangFullName].platformKind |= Platform::BasePlatform;\n m_platforms[clangFullName].sdkPath = Utils::FileName::fromString(sysRoot);\n m_platforms[clangFullName].sdkSettings = sdkSettings;\n m_platforms[clang11FullName].platformKind |= Platform::BasePlatform;\n m_platforms[clang11FullName].sdkPath = Utils::FileName::fromString(sysRoot);\n m_platforms[clang11FullName].sdkSettings = sdkSettings;\n }\n if (hasGcc && !sysRoot.isEmpty()) {\n m_platforms[gccFullName].platformKind |= Platform::BasePlatform;\n m_platforms[gccFullName].sdkPath = Utils::FileName::fromString(sysRoot);\n m_platforms[gccFullName].sdkSettings = sdkSettings;\n }\n }\n indent = QLatin1String(\" \");\n }\n}\n\nvoid IosProbe::detectFirst()\n{\n detectDeveloperPaths();\n if (!m_developerPaths.isEmpty())\n setupDefaultToolchains(m_developerPaths.value(0),QLatin1String(\"\"));\n}\n\nQMap<QString, Platform> IosProbe::detectedPlatforms()\n{\n return m_platforms;\n}\n\n}\n<commit_msg>Ios: Fix version comparison<commit_after>\/****************************************************************************\n**\n** Copyright (C) 2014 Digia Plc and\/or its subsidiary(-ies).\n** Contact: http:\/\/www.qt-project.org\/legal\n**\n** This file is part of Qt Creator.\n**\n** Commercial License Usage\n** Licensees holding valid commercial Qt licenses may use this file in\n** accordance with the commercial license agreement provided with the\n** Software or, alternatively, in accordance with the terms contained in\n** a written agreement between you and Digia. For licensing terms and\n** conditions see http:\/\/qt.digia.com\/licensing. For further information\n** use the contact form at http:\/\/qt.digia.com\/contact-us.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Digia gives you certain additional\n** rights. These rights are described in the Digia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n****************************************************************************\/\n\n#include \"iosprobe.h\"\n\n#include <utils\/logging.h>\n\n#include <QFileInfo>\n#include <QProcess>\n#include <QDir>\n#include <QFileInfoList>\n\nnamespace {\nQ_LOGGING_CATEGORY(probeLog, \"qtc.ios.probe\")\n}\nnamespace Ios {\n\nstatic QString qsystem(const QString &exe, const QStringList &args = QStringList())\n{\n QProcess p;\n p.setProcessChannelMode(QProcess::MergedChannels);\n p.start(exe, args);\n p.waitForFinished();\n return QString::fromLocal8Bit(p.readAll());\n}\n\nQMap<QString, Platform> IosProbe::detectPlatforms(const QString &devPath)\n{\n IosProbe probe;\n probe.addDeveloperPath(devPath);\n probe.detectFirst();\n return probe.detectedPlatforms();\n}\n\nstatic int compareVersions(const QString &v1, const QString &v2)\n{\n QStringList v1L = v1.split(QLatin1Char('.'));\n QStringList v2L = v2.split(QLatin1Char('.'));\n int i = 0;\n while (v1L.length() > i && v2L.length() > i) {\n bool n1Ok, n2Ok;\n int n1 = v1L.value(i).toInt(&n1Ok);\n int n2 = v2L.value(i).toInt(&n2Ok);\n if (!(n1Ok && n2Ok)) {\n qCWarning(probeLog) << QString::fromLatin1(\"Failed to compare version %1 and %2\").arg(v1, v2);\n return 0;\n }\n if (n1 > n2)\n return -1;\n else if (n1 < n2)\n return 1;\n ++i;\n }\n if (v1L.length() > v2L.length())\n return -1;\n if (v1L.length() < v2L.length())\n return 1;\n return 0;\n}\n\nvoid IosProbe::addDeveloperPath(const QString &path)\n{\n if (path.isEmpty())\n return;\n QFileInfo pInfo(path);\n if (!pInfo.exists() || !pInfo.isDir())\n return;\n if (m_developerPaths.contains(path))\n return;\n m_developerPaths.append(path);\n qCDebug(probeLog) << QString::fromLatin1(\"Added developer path %1\").arg(path);\n}\n\nvoid IosProbe::detectDeveloperPaths()\n{\n QProcess selectedXcode;\n QString program = QLatin1String(\"\/usr\/bin\/xcode-select\");\n QStringList arguments(QLatin1String(\"--print-path\"));\n selectedXcode.start(program, arguments, QProcess::ReadOnly);\n if (!selectedXcode.waitForFinished() || selectedXcode.exitCode()) {\n qCWarning(probeLog) << QString::fromLatin1(\"Could not detect selected xcode with \/usr\/bin\/xcode-select\");\n } else {\n QString path = QString::fromLocal8Bit(selectedXcode.readAllStandardOutput());\n path.chop(1);\n addDeveloperPath(path);\n }\n addDeveloperPath(QLatin1String(\"\/Applications\/Xcode.app\/Contents\/Developer\"));\n}\n\nvoid IosProbe::setupDefaultToolchains(const QString &devPath, const QString &xcodeName)\n{\n qCDebug(probeLog) << QString::fromLatin1(\"Setting up platform \\\"%1\\\".\").arg(xcodeName);\n QString indent = QLatin1String(\" \");\n\n \/\/ detect clang (default toolchain)\n QFileInfo clangFileInfo(devPath\n + QLatin1String(\"\/Toolchains\/XcodeDefault.xctoolchain\/usr\/bin\")\n + QLatin1String(\"\/clang++\"));\n bool hasClang = clangFileInfo.exists();\n if (!hasClang)\n qCWarning(probeLog) << indent << QString::fromLatin1(\"Default toolchain %1 not found.\")\n .arg(clangFileInfo.canonicalFilePath());\n \/\/ Platforms\n QDir platformsDir(devPath + QLatin1String(\"\/Platforms\"));\n QFileInfoList platforms = platformsDir.entryInfoList(QDir::Dirs | QDir::NoDotAndDotDot);\n foreach (const QFileInfo &fInfo, platforms) {\n if (fInfo.isDir() && fInfo.suffix() == QLatin1String(\"platform\")) {\n qCDebug(probeLog) << indent << QString::fromLatin1(\"Setting up %1\").arg(fInfo.fileName());\n QSettingsPtr infoSettings(new QSettings(\n fInfo.absoluteFilePath() + QLatin1String(\"\/Info.plist\"),\n QSettings::NativeFormat));\n if (!infoSettings->contains(QLatin1String(\"Name\"))) {\n qCWarning(probeLog) << indent << QString::fromLatin1(\"Missing platform name in Info.plist of %1\")\n .arg(fInfo.absoluteFilePath());\n continue;\n }\n QString name = infoSettings->value(QLatin1String(\"Name\")).toString();\n if (name != QLatin1String(\"macosx\") && name != QLatin1String(\"iphoneos\")\n && name != QLatin1String(\"iphonesimulator\"))\n {\n qCWarning(probeLog) << indent << QString::fromLatin1(\"Skipping unknown platform %1\").arg(name);\n continue;\n }\n\n \/\/ prepare default platform properties\n QVariantMap defaultProp = infoSettings->value(QLatin1String(\"DefaultProperties\"))\n .toMap();\n QVariantMap overrideProp = infoSettings->value(QLatin1String(\"OverrideProperties\"))\n .toMap();\n QMapIterator<QString, QVariant> i(overrideProp);\n while (i.hasNext()) {\n i.next();\n \/\/ use unite? might lead to double insertions...\n defaultProp[i.key()] = i.value();\n }\n\n QString clangFullName = name + QLatin1String(\"-clang\") + xcodeName;\n QString clang11FullName = name + QLatin1String(\"-clang11\") + xcodeName;\n \/\/ detect gcc\n QFileInfo gccFileInfo(fInfo.absoluteFilePath() + QLatin1String(\"\/Developer\/usr\/bin\/g++\"));\n QString gccFullName = name + QLatin1String(\"-gcc\") + xcodeName;\n if (!gccFileInfo.exists())\n gccFileInfo = QFileInfo(devPath + QLatin1String(\"\/usr\/bin\/g++\"));\n bool hasGcc = gccFileInfo.exists();\n\n QStringList extraFlags;\n if (defaultProp.contains(QLatin1String(\"NATIVE_ARCH\"))) {\n QString arch = defaultProp.value(QLatin1String(\"NATIVE_ARCH\")).toString();\n if (!arch.startsWith(QLatin1String(\"arm\")))\n qCWarning(probeLog) << indent << QString::fromLatin1(\"Expected arm architecture, not %1\").arg(arch);\n extraFlags << QLatin1String(\"-arch\") << arch;\n } else if (name == QLatin1String(\"iphonesimulator\")) {\n \/\/ don't generate a toolchain for 64 bit (to fix when we support that)\n extraFlags << QLatin1String(\"-arch\") << QLatin1String(\"i386\");\n }\n if (hasClang) {\n Platform clangProfile;\n clangProfile.developerPath = Utils::FileName::fromString(devPath);\n clangProfile.platformKind = 0;\n clangProfile.name = clangFullName;\n clangProfile.platformPath = Utils::FileName(fInfo);\n clangProfile.platformInfo = infoSettings;\n clangProfile.compilerPath = Utils::FileName(clangFileInfo);\n QStringList flags = extraFlags;\n flags << QLatin1String(\"-dumpmachine\");\n QString compilerTriplet = qsystem(clangFileInfo.canonicalFilePath(), flags)\n .simplified();\n QStringList compilerTripletl = compilerTriplet.split(QLatin1Char('-'));\n clangProfile.architecture = compilerTripletl.value(0);\n clangProfile.backendFlags = extraFlags;\n qCDebug(probeLog) << indent << QString::fromLatin1(\"* adding profile %1\").arg(clangProfile.name);\n m_platforms[clangProfile.name] = clangProfile;\n clangProfile.platformKind |= Platform::Cxx11Support;\n clangProfile.backendFlags.append(QLatin1String(\"-std=c++11\"));\n clangProfile.backendFlags.append(QLatin1String(\"-stdlib=libc++\"));\n clangProfile.name = clang11FullName;\n m_platforms[clangProfile.name] = clangProfile;\n }\n if (hasGcc) {\n Platform gccProfile;\n gccProfile.developerPath = Utils::FileName::fromString(devPath);\n gccProfile.name = gccFullName;\n gccProfile.platformKind = 0;\n \/\/ use the arm-apple-darwin10-llvm-* variant and avoid the extraFlags if available???\n gccProfile.platformPath = Utils::FileName(fInfo);\n gccProfile.platformInfo = infoSettings;\n gccProfile.compilerPath = Utils::FileName(gccFileInfo);\n QStringList flags = extraFlags;\n flags << QLatin1String(\"-dumpmachine\");\n QString compilerTriplet = qsystem(gccFileInfo.canonicalFilePath(), flags)\n .simplified();\n QStringList compilerTripletl = compilerTriplet.split(QLatin1Char('-'));\n gccProfile.architecture = compilerTripletl.value(0);\n gccProfile.backendFlags = extraFlags;\n qCDebug(probeLog) << indent << QString::fromLatin1(\"* adding profile %1\").arg(gccProfile.name);\n m_platforms[gccProfile.name] = gccProfile;\n }\n\n \/\/ set SDKs\/sysroot\n QString sysRoot;\n QSettingsPtr sdkSettings;\n {\n QString sdkName;\n if (defaultProp.contains(QLatin1String(\"SDKROOT\")))\n sdkName = defaultProp.value(QLatin1String(\"SDKROOT\")).toString();\n QString sdkPath;\n QDir sdks(fInfo.absoluteFilePath() + QLatin1String(\"\/Developer\/SDKs\"));\n QString maxVersion;\n foreach (const QFileInfo &sdkDirInfo, sdks.entryInfoList(QDir::Dirs\n | QDir::NoDotAndDotDot)) {\n indent = QLatin1String(\" \");\n QSettingsPtr sdkInfo(new QSettings(sdkDirInfo.absoluteFilePath()\n + QLatin1String(\"\/SDKSettings.plist\"),\n QSettings::NativeFormat));\n QString versionStr = sdkInfo->value(QLatin1String(\"Version\")).toString();\n QVariant currentSdkName = sdkInfo->value(QLatin1String(\"CanonicalName\"));\n bool isBaseSdk = sdkInfo->value((QLatin1String(\"isBaseSDK\"))).toString()\n .toLower() != QLatin1String(\"no\");\n if (!isBaseSdk) {\n qCDebug(probeLog) << indent << QString::fromLatin1(\"Skipping non base Sdk %1\")\n .arg(currentSdkName.toString());\n continue;\n }\n if (sdkName.isEmpty()) {\n if (compareVersions(maxVersion, versionStr) > 0) {\n maxVersion = versionStr;\n sdkPath = sdkDirInfo.canonicalFilePath();\n sdkSettings = sdkInfo;\n }\n } else if (currentSdkName == sdkName) {\n sdkPath = sdkDirInfo.canonicalFilePath();\n sdkSettings = sdkInfo;\n }\n }\n if (!sdkPath.isEmpty())\n sysRoot = sdkPath;\n else if (!sdkName.isEmpty())\n qCDebug(probeLog) << indent << QString::fromLatin1(\"Failed to find sysroot %1\").arg(sdkName);\n }\n if (hasClang && !sysRoot.isEmpty()) {\n m_platforms[clangFullName].platformKind |= Platform::BasePlatform;\n m_platforms[clangFullName].sdkPath = Utils::FileName::fromString(sysRoot);\n m_platforms[clangFullName].sdkSettings = sdkSettings;\n m_platforms[clang11FullName].platformKind |= Platform::BasePlatform;\n m_platforms[clang11FullName].sdkPath = Utils::FileName::fromString(sysRoot);\n m_platforms[clang11FullName].sdkSettings = sdkSettings;\n }\n if (hasGcc && !sysRoot.isEmpty()) {\n m_platforms[gccFullName].platformKind |= Platform::BasePlatform;\n m_platforms[gccFullName].sdkPath = Utils::FileName::fromString(sysRoot);\n m_platforms[gccFullName].sdkSettings = sdkSettings;\n }\n }\n indent = QLatin1String(\" \");\n }\n}\n\nvoid IosProbe::detectFirst()\n{\n detectDeveloperPaths();\n if (!m_developerPaths.isEmpty())\n setupDefaultToolchains(m_developerPaths.value(0),QLatin1String(\"\"));\n}\n\nQMap<QString, Platform> IosProbe::detectedPlatforms()\n{\n return m_platforms;\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/**\n * @file\n *\n * @brief Read key sets using yaml-cpp\n *\n * @copyright BSD License (see LICENSE.md or https:\/\/www.libelektra.org)\n *\/\n\n#include \"read.hpp\"\n#include \"yaml-cpp\/yaml.h\"\n\n#include <kdb.hpp>\n#include <kdbease.h>\n#include <kdblogger.h>\n#include <kdbplugin.h>\n\n#include <sstream>\n\nusing namespace std;\nusing namespace kdb;\n\nnamespace\n{\n\/**\n * @brief This function creates a new key from the given parameters.\n *\n * @param name This string specifies the postfix of the name of the key produced by this function.\n * @param parent This key specifies the prefix of the name of the key produced by this function.\n *\n * @returns The function returns a new key that combines the name of the parent key and `name`.\n *\/\nKey newKey (string const & name, Key const & parent)\n{\n\tKey key{ parent.getFullName (), KEY_END };\n\tkey.addBaseName (name);\n\n\treturn key;\n}\n\n\/**\n * @brief This function creates a new array key from the given parameters.\n *\n * @param mappings This argument specifies the key set of the new key this function creates.\n * @param arrayKey This argument specifies the key that represents the root of the array.\n *\n * @returns The function returns a new key that is part of the array represented by `arrayKey`.\n *\/\nKey newArrayKey (KeySet const & mappings, Key & arrayKey)\n{\n\tKeySet arrayEntries{ elektraArrayGet (arrayKey.getKey (), mappings.getKeySet ()) };\n\n\tif (arrayEntries.size () <= 0)\n\t{\n\t\tKey first = arrayKey.dup ();\n\t\tfirst.addBaseName (\"#\");\n\t\tarrayEntries.append (first);\n\t}\n\n\tKey newKey{ elektraArrayGetNextKey (arrayEntries.getKeySet ()) };\n\tarrayKey.setMeta (\"array\", newKey.getBaseName ());\n\n\treturn newKey;\n}\n\n\/**\n * @brief Add metadata saved in a YAML map to the specified key\n *\n * @param key This parameter saves the key to which this function should add the metadata stored in `node`.\n * @param node This YAML node stores a map containing metadata.\n *\/\nvoid addMetadata (Key & key, YAML::Node const & node)\n{\n\tfor (auto & element : node)\n\t{\n\t\tauto metakey = element.first.as<string> ();\n\t\tauto metavalue = element.second.IsNull () ? \"\" : element.second.as<string> ();\n\t\tELEKTRA_LOG_DEBUG (\"Add metakey “%s: %s”\", metakey.c_str (), metavalue.c_str ());\n\t\tkey.setMeta (metakey, metavalue);\n\t}\n}\n\n\/**\n * @brief Convert a YAML node to a key set\n *\n * @param node This YAML node stores the data that should be added to the keyset `mappings`\n * @param mappings The key set where the YAML data will be stored\n * @param parent This key stores the prefix for the key name\n *\/\nvoid convertNodeToKeySet (YAML::Node const & node, KeySet & mappings, Key & parent)\n{\n\tif (node.Tag () == \"!elektra\/meta\")\n\t{\n\t\tKey key (parent.getFullName (), KEY_VALUE, node[0].as<string> ().c_str (), KEY_END);\n\t\tELEKTRA_LOG_DEBUG (\"Add key “%s: %s”\", key.getName ().c_str (), key.get<string> ().c_str ());\n\t\tmappings.append (key);\n\t\taddMetadata (key, node[1]);\n\t}\n\telse if (node.IsScalar () || node.IsNull ())\n\t{\n\t\tKey key (parent.getFullName (), KEY_END);\n\t\tif (node.IsNull ())\n\t\t{\n\t\t\tkey.setMeta (\"binary\", \"\");\n\t\t}\n\t\telse\n\t\t{\n\t\t\tkey.setString (node.as<string> ());\n\t\t}\n\t\tELEKTRA_LOG_DEBUG (\"Add key “%s: %s”\", key.getName ().c_str (),\n\t\t\t\t key.getBinarySize () == 0 ? \"NULL\" : key.get<string> ().c_str ());\n\t\tif (node.Tag () == \"tag:yaml.org,2002:binary\")\n\t\t{\n\t\t\tELEKTRA_LOG_DEBUG (\"Set metadata type of key to binary\");\n\t\t\tkey.setMeta (\"type\", \"binary\");\n\t\t}\n\t\tmappings.append (key);\n\t}\n\telse if (node.IsMap () || node.IsSequence ())\n\t{\n\t\tfor (auto element : node)\n\t\t{\n\t\t\tKey key = node.IsMap () ? newKey (element.first.as<string> (), parent) : newArrayKey (mappings, parent);\n\t\t\tELEKTRA_LOG_DEBUG (\"Add intermediate key “%s”\", key.getName ().c_str ());\n\t\t\tmappings.append (key);\n\t\t\tconvertNodeToKeySet (node.IsMap () ? element.second : element, mappings, key);\n\t\t}\n\t}\n}\n} \/\/ end namespace\n\n\/**\n * @brief Read a YAML file and add the resulting data to a given key set\n *\n * @param mappings The key set where the YAML data will be stored\n * @param parent This key stores the path to the YAML data file that should be read\n *\/\nvoid yamlcpp::yamlRead (KeySet & mappings, Key & parent)\n{\n\tYAML::Node config = YAML::LoadFile (parent.getString ());\n\n#ifdef HAVE_LOGGER\n\tostringstream data;\n\tdata << config;\n\tELEKTRA_LOG_DEBUG (\"Read data “%s”\", data.str ().c_str ());\n#endif\n\n\tconvertNodeToKeySet (config, mappings, parent);\n\tELEKTRA_LOG_DEBUG (\"Added %zd key%s\", mappings.size (), mappings.size () == 1 ? \"\" : \"s\");\n}\n<commit_msg>YAML CPP: Add separate function to create Key<commit_after>\/**\n * @file\n *\n * @brief Read key sets using yaml-cpp\n *\n * @copyright BSD License (see LICENSE.md or https:\/\/www.libelektra.org)\n *\/\n\n#include \"read.hpp\"\n#include \"yaml-cpp\/yaml.h\"\n\n#include <kdb.hpp>\n#include <kdbease.h>\n#include <kdblogger.h>\n#include <kdbplugin.h>\n\n#include <sstream>\n\nusing namespace std;\nusing namespace kdb;\n\nnamespace\n{\n\/**\n * @brief This function creates a new key from the given parameters.\n *\n * @param name This string specifies the postfix of the name of the key produced by this function.\n * @param parent This key specifies the prefix of the name of the key produced by this function.\n *\n * @returns The function returns a new key that combines the name of the parent key and `name`.\n *\/\nKey newKey (string const & name, Key const & parent)\n{\n\tKey key{ parent.getFullName (), KEY_END };\n\tkey.addBaseName (name);\n\n\treturn key;\n}\n\n\/**\n * @brief This function creates a new array key from the given parameters.\n *\n * @param mappings This argument specifies the key set of the new key this function creates.\n * @param arrayKey This argument specifies the key that represents the root of the array.\n *\n * @returns The function returns a new key that is part of the array represented by `arrayKey`.\n *\/\nKey newArrayKey (KeySet const & mappings, Key & arrayKey)\n{\n\tKeySet arrayEntries{ elektraArrayGet (arrayKey.getKey (), mappings.getKeySet ()) };\n\n\tif (arrayEntries.size () <= 0)\n\t{\n\t\tKey first = arrayKey.dup ();\n\t\tfirst.addBaseName (\"#\");\n\t\tarrayEntries.append (first);\n\t}\n\n\tKey newKey{ elektraArrayGetNextKey (arrayEntries.getKeySet ()) };\n\tarrayKey.setMeta (\"array\", newKey.getBaseName ());\n\n\treturn newKey;\n}\n\n\/**\n * @brief Add metadata saved in a YAML map to the specified key\n *\n * @param key This parameter saves the key to which this function should add the metadata stored in `node`.\n * @param node This YAML node stores a map containing metadata.\n *\/\nvoid addMetadata (Key & key, YAML::Node const & node)\n{\n\tfor (auto & element : node)\n\t{\n\t\tauto metakey = element.first.as<string> ();\n\t\tauto metavalue = element.second.IsNull () ? \"\" : element.second.as<string> ();\n\t\tELEKTRA_LOG_DEBUG (\"Add metakey “%s: %s”\", metakey.c_str (), metavalue.c_str ());\n\t\tkey.setMeta (metakey, metavalue);\n\t}\n}\n\n\/**\n * @brief Create a key containing a (possibly empty) value.\n *\n * @param node This YAML node stores the data that should be converted to a new `Key`.\n * @param name This text specifies the name of the key this function creates.\n *\n * @return A new key containing the data specified in `node`\n *\/\nKey createLeafKey (YAML::Node const & node, string const & name)\n{\n\tKey key (name, KEY_END);\n\tif (node.IsNull ())\n\t{\n\t\tkey.setMeta (\"binary\", \"\");\n\t}\n\telse\n\t{\n\t\tkey.setString (node.as<string> ());\n\t}\n\tELEKTRA_LOG_DEBUG (\"Add key “%s: %s”\", key.getName ().c_str (), key.getBinarySize () == 0 ? \"NULL\" : key.get<string> ().c_str ());\n\tif (node.Tag () == \"tag:yaml.org,2002:binary\")\n\t{\n\t\tELEKTRA_LOG_DEBUG (\"Set metadata type of key to binary\");\n\t\tkey.setMeta (\"type\", \"binary\");\n\t}\n\treturn key;\n}\n\n\/**\n * @brief Convert a YAML node to a key set\n *\n * @param node This YAML node stores the data that should be added to the keyset `mappings`\n * @param mappings The key set where the YAML data will be stored\n * @param parent This key stores the prefix for the key name\n *\/\nvoid convertNodeToKeySet (YAML::Node const & node, KeySet & mappings, Key & parent)\n{\n\tif (node.Tag () == \"!elektra\/meta\")\n\t{\n\t\tKey key (parent.getFullName (), KEY_VALUE, node[0].as<string> ().c_str (), KEY_END);\n\t\tELEKTRA_LOG_DEBUG (\"Add key “%s: %s”\", key.getName ().c_str (), key.get<string> ().c_str ());\n\t\tmappings.append (key);\n\t\taddMetadata (key, node[1]);\n\t}\n\telse if (node.IsScalar () || node.IsNull ())\n\t{\n\t\tauto key = createLeafKey (node, parent.getFullName ());\n\t\tmappings.append (key);\n\t}\n\telse if (node.IsMap () || node.IsSequence ())\n\t{\n\t\tfor (auto element : node)\n\t\t{\n\t\t\tKey key = node.IsMap () ? newKey (element.first.as<string> (), parent) : newArrayKey (mappings, parent);\n\t\t\tELEKTRA_LOG_DEBUG (\"Add intermediate key “%s”\", key.getName ().c_str ());\n\t\t\tmappings.append (key);\n\t\t\tconvertNodeToKeySet (node.IsMap () ? element.second : element, mappings, key);\n\t\t}\n\t}\n}\n} \/\/ end namespace\n\n\/**\n * @brief Read a YAML file and add the resulting data to a given key set\n *\n * @param mappings The key set where the YAML data will be stored\n * @param parent This key stores the path to the YAML data file that should be read\n *\/\nvoid yamlcpp::yamlRead (KeySet & mappings, Key & parent)\n{\n\tYAML::Node config = YAML::LoadFile (parent.getString ());\n\n#ifdef HAVE_LOGGER\n\tostringstream data;\n\tdata << config;\n\tELEKTRA_LOG_DEBUG (\"Read data “%s”\", data.str ().c_str ());\n#endif\n\n\tconvertNodeToKeySet (config, mappings, parent);\n\tELEKTRA_LOG_DEBUG (\"Added %zd key%s\", mappings.size (), mappings.size () == 1 ? \"\" : \"s\");\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/=============================================================================================================\n\/**\n* @file test_fiff_anonymize.cpp\n* @author Lorenz Esch <lorenzesch@hotmail.com>;\n* @version 1.0\n* @date September, 2019\n*\n* @section LICENSE\n*\n* Copyright (C) 2019, Lorenz Esch. All rights reserved.\n*\n* Redistribution and use in source and binary forms, with or without modification, are permitted provided that\n* the following conditions are met:\n* * Redistributions of source code must retain the above copyright notice, this list of conditions and the\n* following disclaimer.\n* * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and\n* the following disclaimer in the documentation and\/or other materials provided with the distribution.\n* * Neither the name of MNE-CPP authors nor the names of its contributors may be used\n* to endorse or promote products derived from this software without specific prior written permission.\n*\n* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED\n* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A\n* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n* POSSIBILITY OF SUCH DAMAGE.\n*\n*\n* @brief Test for anonymizing a fiff raw file\n*\n*\/\n\n\n\/\/*************************************************************************************************************\n\/\/=============================================================================================================\n\/\/ INCLUDES\n\/\/=============================================================================================================\n\n#include <fiff\/fiff.h>\n\n#include <iostream>\n\n\n\/\/*************************************************************************************************************\n\/\/=============================================================================================================\n\/\/ QT INCLUDES\n\/\/=============================================================================================================\n\n#include <QtTest>\n#include <QProcess>\n#include <QScopedPointer>\n\n\n\/\/*************************************************************************************************************\n\/\/=============================================================================================================\n\/\/ USED NAMESPACES\n\/\/=============================================================================================================\n\nusing namespace FIFFLIB;\n\n\/\/=============================================================================================================\n\/**\n* DECLARE CLASS TestFiffAnonymize\n*\n* @brief The TestFiffAnonymize class provides fiff anonymizing verification tests\n*\n*\/\nclass TestFiffAnonymize: public QObject\n{\n Q_OBJECT\n\npublic:\n TestFiffAnonymize();\n\nprivate slots:\n void initTestCase();\n void compareData();\n void cleanupTestCase();\n\nprivate:\n double epsilon;\n};\n\n\n\/\/*************************************************************************************************************\n\nTestFiffAnonymize::TestFiffAnonymize()\n: epsilon(0.000001)\n{\n}\n\n\n\n\/\/*************************************************************************************************************\n\nvoid TestFiffAnonymize::initTestCase()\n{\n qInfo() << \"TestFiffAnonymize::initTestCase - Epsilon\" << epsilon;\n\n \/\/ Init testing arguments\n QString sFileIn(\".\/mne-cpp-test-data\/MEG\/sample\/sample_audvis_raw_short.fif\");\n QString sFileOut(\".\/mne-cpp-test-data\/MEG\/sample\/sample_audvis_raw_short_anonymized.fif\");\n\n qInfo() << \"TestFiffAnonymize::initTestCase - sFileIn\" << sFileIn;\n qInfo() << \"TestFiffAnonymize::initTestCase - sFileOut\" << sFileOut;\n\n QString program = \".\/mne_anonymize\";\n QStringList arguments;\n arguments << \"--in\" << sFileIn;\n arguments << \"--out\" << sFileOut;\n\n \/\/ Pass arguments to application and anaonyimze the fiff file\n QScopedPointer<QProcess> myProcess (new QProcess);\n myProcess->start(program, arguments);\n myProcess->waitForFinished();\n}\n\n\n\/\/*************************************************************************************************************\n\nvoid TestFiffAnonymize::compareData()\n{\n \/\/ Open .\/mne-cpp-test-data\/MEG\/sample\/sample_audvis_raw_anonymized.fif\n\n \/\/ ToDo: Implement function which reads sensitive tags and checks if they were anaonymized. Use Q_VERIFY().\n}\n\n\/\/*************************************************************************************************************\n\nvoid TestFiffAnonymize::cleanupTestCase()\n{\n}\n\n\n\/\/*************************************************************************************************************\n\/\/=============================================================================================================\n\/\/ MAIN\n\/\/=============================================================================================================\n\nQTEST_APPLESS_MAIN(TestFiffAnonymize)\n#include \"test_fiff_anonymize.moc\"\n<commit_msg>[ci skip] add file crc code for comparison<commit_after>\/\/=============================================================================================================\n\/**\n* @file test_fiff_anonymize.cpp\n* @author Lorenz Esch <lorenzesch@hotmail.com>;\n* @version 1.0\n* @date September, 2019\n*\n* @section LICENSE\n*\n* Copyright (C) 2019, Lorenz Esch. All rights reserved.\n*\n* Redistribution and use in source and binary forms, with or without modification, are permitted provided that\n* the following conditions are met:\n* * Redistributions of source code must retain the above copyright notice, this list of conditions and the\n* following disclaimer.\n* * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and\n* the following disclaimer in the documentation and\/or other materials provided with the distribution.\n* * Neither the name of MNE-CPP authors nor the names of its contributors may be used\n* to endorse or promote products derived from this software without specific prior written permission.\n*\n* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED\n* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A\n* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n* POSSIBILITY OF SUCH DAMAGE.\n*\n*\n* @brief Test for anonymizing a fiff raw file\n*\n*\/\n\n\n\/\/*************************************************************************************************************\n\/\/=============================================================================================================\n\/\/ INCLUDES\n\/\/=============================================================================================================\n\n#include <fiff\/fiff.h>\n\n#include <iostream>\n\n\n\/\/*************************************************************************************************************\n\/\/=============================================================================================================\n\/\/ QT INCLUDES\n\/\/=============================================================================================================\n\n#include <QtTest>\n#include <QProcess>\n#include <QScopedPointer>\n\n\n\/\/*************************************************************************************************************\n\/\/=============================================================================================================\n\/\/ USED NAMESPACES\n\/\/=============================================================================================================\n\nusing namespace FIFFLIB;\n\n\/\/=============================================================================================================\n\/**\n* DECLARE CLASS TestFiffAnonymize\n*\n* @brief The TestFiffAnonymize class provides fiff anonymizing verification tests\n*\n*\/\nclass TestFiffAnonymize: public QObject\n{\n Q_OBJECT\n\npublic:\n TestFiffAnonymize();\n\nprivate slots:\n void initTestCase();\n void compareData();\n void cleanupTestCase();\n\nprivate:\n double epsilon;\n};\n\n\n\/\/*************************************************************************************************************\n\nTestFiffAnonymize::TestFiffAnonymize()\n: epsilon(0.000001)\n{\n}\n\n\n\n\/\/*************************************************************************************************************\n\nvoid TestFiffAnonymize::initTestCase()\n{\n qInfo() << \"TestFiffAnonymize::initTestCase - Epsilon\" << epsilon;\n\n \/\/ Init testing arguments\n QString sFileIn(\".\/mne-cpp-test-data\/MEG\/sample\/sample_audvis_raw_short.fif\");\n QString sFileOut(\".\/mne-cpp-test-data\/MEG\/sample\/sample_audvis_raw_short_anonymized.fif\");\n\n qInfo() << \"TestFiffAnonymize::initTestCase - sFileIn\" << sFileIn;\n qInfo() << \"TestFiffAnonymize::initTestCase - sFileOut\" << sFileOut;\n\n QString program = \".\/mne_anonymize\";\n QStringList arguments;\n arguments << \"--in\" << sFileIn;\n arguments << \"--out\" << sFileOut;\n\n \/\/ Pass arguments to application and anaonyimze the fiff file\n QScopedPointer<QProcess> myProcess (new QProcess);\n myProcess->start(program, arguments);\n myProcess->waitForFinished();\n}\n\n\n\/\/*************************************************************************************************************\n\nvoid TestFiffAnonymize::compareData()\n{\n \/\/ Open .\/mne-cpp-test-data\/MEG\/sample\/sample_audvis_raw_anonymized.fif\n QString inFileName(\".\/mne-cpp-test-data\/MEG\/sample\/sample_audvis_raw_anonymized.fif\");\n QFile inFile(inFileName);\n QByteArray inData(inFile.readAll());\n quint16 crc = qChecksum(inData.data(),static_cast<uint>(inData.size()));\n qDebug() << crc;\n\n \/\/ ToDo: Implement function which reads sensitive tags and checks if they were anaonymized. Use Q_VERIFY().\n}\n\n\/\/*************************************************************************************************************\n\nvoid TestFiffAnonymize::cleanupTestCase()\n{\n}\n\n\n\/\/*************************************************************************************************************\n\/\/=============================================================================================================\n\/\/ MAIN\n\/\/=============================================================================================================\n\nQTEST_APPLESS_MAIN(TestFiffAnonymize)\n#include \"test_fiff_anonymize.moc\"\n<|endoftext|>"} {"text":"<commit_before>#ifndef ITER_COMBINATIONS_HPP_\n#define ITER_COMBINATIONS_HPP_\n\n#include \"internal\/iterbase.hpp\"\n#include \"internal\/iteratoriterator.hpp\"\n\n#include <vector>\n#include <type_traits>\n#include <iterator>\n#include <initializer_list>\n\nnamespace iter {\n namespace impl {\n template <typename Container>\n class Combinator;\n }\n\n template <typename Container>\n impl::Combinator<Container> combinations(Container&&, std::size_t);\n\n template <typename T>\n impl::Combinator<std::initializer_list<T>> combinations(\n std::initializer_list<T>, std::size_t);\n}\n\ntemplate <typename Container>\nclass iter::impl::Combinator {\n private:\n Container container;\n std::size_t length;\n\n friend Combinator iter::combinations<Container>(Container&&, std::size_t);\n template <typename T>\n friend Combinator<std::initializer_list<T>> iter::combinations(\n std::initializer_list<T>, std::size_t);\n\n Combinator(Container&& in_container, std::size_t in_length)\n : container(std::forward<Container>(in_container)), length{in_length} {}\n\n using IndexVector = std::vector<iterator_type<Container>>;\n using CombIteratorDeref = IterIterWrapper<IndexVector>;\n\n public:\n class Iterator\n : public std::iterator<std::input_iterator_tag, CombIteratorDeref> {\n private:\n constexpr static const int COMPLETE = -1;\n typename std::remove_reference<Container>::type* container_p;\n CombIteratorDeref indices;\n int steps{};\n\n public:\n Iterator(Container& in_container, std::size_t n)\n : container_p{&in_container}, indices{n} {\n if (n == 0) {\n this->steps = COMPLETE;\n return;\n }\n size_t inc = 0;\n for (auto& iter : this->indices.get()) {\n auto it = std::begin(*this->container_p);\n dumb_advance(it, std::end(*this->container_p), inc);\n if (it != std::end(*this->container_p)) {\n iter = it;\n ++inc;\n } else {\n this->steps = COMPLETE;\n break;\n }\n }\n }\n\n CombIteratorDeref& operator*() {\n return this->indices;\n }\n\n CombIteratorDeref* operator->() {\n return &this->indices;\n }\n\n Iterator& operator++() {\n for (auto iter = indices.get().rbegin(); iter != indices.get().rend();\n ++iter) {\n ++(*iter);\n\n \/\/ what we have to check here is if the distance between\n \/\/ the index and the end of indices is >= the distance\n \/\/ between the item and end of item\n auto dist = std::distance(this->indices.get().rbegin(), iter);\n\n if (!(dumb_next(*iter, dist) != std::end(*this->container_p))) {\n if ((iter + 1) != indices.get().rend()) {\n size_t inc = 1;\n for (auto down = iter; down != indices.get().rbegin() - 1; --down) {\n (*down) = dumb_next(*(iter + 1), 1 + inc);\n ++inc;\n }\n } else {\n this->steps = COMPLETE;\n break;\n }\n } else {\n break;\n }\n \/\/ we break because none of the rest of the items need\n \/\/ to be incremented\n }\n if (this->steps != COMPLETE) {\n ++this->steps;\n }\n return *this;\n }\n\n Iterator operator++(int) {\n auto ret = *this;\n ++*this;\n return ret;\n }\n\n bool operator!=(const Iterator& other) const {\n return !(*this == other);\n }\n\n bool operator==(const Iterator& other) const {\n return this->steps == other.steps;\n }\n };\n\n Iterator begin() {\n return {this->container, this->length};\n }\n\n Iterator end() {\n return {this->container, 0};\n }\n};\n\ntemplate <typename Container>\niter::impl::Combinator<Container> iter::combinations(\n Container&& container, std::size_t length) {\n return {std::forward<Container>(container), length};\n}\n\ntemplate <typename T>\niter::impl::Combinator<std::initializer_list<T>> iter::combinations(\n std::initializer_list<T> il, std::size_t length) {\n return {std::move(il), length};\n}\n\n#endif\n<commit_msg>makes combinations impl class move-only<commit_after>#ifndef ITER_COMBINATIONS_HPP_\n#define ITER_COMBINATIONS_HPP_\n\n#include \"internal\/iterbase.hpp\"\n#include \"internal\/iteratoriterator.hpp\"\n\n#include <vector>\n#include <type_traits>\n#include <iterator>\n#include <initializer_list>\n\nnamespace iter {\n namespace impl {\n template <typename Container>\n class Combinator;\n }\n\n template <typename Container>\n impl::Combinator<Container> combinations(Container&&, std::size_t);\n\n template <typename T>\n impl::Combinator<std::initializer_list<T>> combinations(\n std::initializer_list<T>, std::size_t);\n}\n\ntemplate <typename Container>\nclass iter::impl::Combinator {\n private:\n Container container;\n std::size_t length;\n\n friend Combinator iter::combinations<Container>(Container&&, std::size_t);\n template <typename T>\n friend Combinator<std::initializer_list<T>> iter::combinations(\n std::initializer_list<T>, std::size_t);\n\n Combinator(Container&& in_container, std::size_t in_length)\n : container(std::forward<Container>(in_container)), length{in_length} {}\n\n using IndexVector = std::vector<iterator_type<Container>>;\n using CombIteratorDeref = IterIterWrapper<IndexVector>;\n\n public:\n Combinator(Combinator&&) = default;\n class Iterator\n : public std::iterator<std::input_iterator_tag, CombIteratorDeref> {\n private:\n constexpr static const int COMPLETE = -1;\n typename std::remove_reference<Container>::type* container_p;\n CombIteratorDeref indices;\n int steps{};\n\n public:\n Iterator(Container& in_container, std::size_t n)\n : container_p{&in_container}, indices{n} {\n if (n == 0) {\n this->steps = COMPLETE;\n return;\n }\n size_t inc = 0;\n for (auto& iter : this->indices.get()) {\n auto it = std::begin(*this->container_p);\n dumb_advance(it, std::end(*this->container_p), inc);\n if (it != std::end(*this->container_p)) {\n iter = it;\n ++inc;\n } else {\n this->steps = COMPLETE;\n break;\n }\n }\n }\n\n CombIteratorDeref& operator*() {\n return this->indices;\n }\n\n CombIteratorDeref* operator->() {\n return &this->indices;\n }\n\n Iterator& operator++() {\n for (auto iter = indices.get().rbegin(); iter != indices.get().rend();\n ++iter) {\n ++(*iter);\n\n \/\/ what we have to check here is if the distance between\n \/\/ the index and the end of indices is >= the distance\n \/\/ between the item and end of item\n auto dist = std::distance(this->indices.get().rbegin(), iter);\n\n if (!(dumb_next(*iter, dist) != std::end(*this->container_p))) {\n if ((iter + 1) != indices.get().rend()) {\n size_t inc = 1;\n for (auto down = iter; down != indices.get().rbegin() - 1; --down) {\n (*down) = dumb_next(*(iter + 1), 1 + inc);\n ++inc;\n }\n } else {\n this->steps = COMPLETE;\n break;\n }\n } else {\n break;\n }\n \/\/ we break because none of the rest of the items need\n \/\/ to be incremented\n }\n if (this->steps != COMPLETE) {\n ++this->steps;\n }\n return *this;\n }\n\n Iterator operator++(int) {\n auto ret = *this;\n ++*this;\n return ret;\n }\n\n bool operator!=(const Iterator& other) const {\n return !(*this == other);\n }\n\n bool operator==(const Iterator& other) const {\n return this->steps == other.steps;\n }\n };\n\n Iterator begin() {\n return {this->container, this->length};\n }\n\n Iterator end() {\n return {this->container, 0};\n }\n};\n\ntemplate <typename Container>\niter::impl::Combinator<Container> iter::combinations(\n Container&& container, std::size_t length) {\n return {std::forward<Container>(container), length};\n}\n\ntemplate <typename T>\niter::impl::Combinator<std::initializer_list<T>> iter::combinations(\n std::initializer_list<T> il, std::size_t length) {\n return {std::move(il), length};\n}\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Main.cpp\n *\n * Created on: 06.04.2017\n * Author: aca619\n *\/\n#include <iostream>\n#include <chrono>\n#include <sys\/neutrino.h>\n#include \"ITimer.h\"\n#include \"TimerService.h\"\n\n#define PM_CODE 4\n#define PM_VALUE 123456\n\nint main(void){\n\tstd::cout << \"Geht los hier\" << std::endl;\n\n\tint chid = ChannelCreate_r(0);\n\tif(chid < 0){\n\t\tstd::cout << \"Channel Create failed\" << std::endl;\n\t}\n\n\tstd::chrono::time_point<std::chrono::system_clock> start, end;\n\n\tstruct _pulse pulse;\n\n\tITimer* timer = new TimerService(chid, PM_CODE, PM_VALUE);\n\n\tstart = std::chrono::system_clock::now();\n\n\ttimer->setAlarm(500);\n\n\tint err = MsgReceive_r(chid, &pulse, sizeof(_pulse),NULL);\n\t\tif(err) {\n\t\t\t\t\/\/ TODO error handling\n\t\t\t\tstd::cout << \"client MsgReceive_r failed\" << std::endl;\n\t\t}\n\tend = std::chrono::system_clock::now();\n\n\tint elapsed_seconds = std::chrono::duration_cast<std::chrono::milliseconds> (end-start).count();\n\n\tstd::cout << \"Message received: \" << pulse.value.sival_int << \" after: \" << elapsed_seconds << std::endl;\n\n\tstd::cout << \"Zuende hier\" << std::endl;\n}\n\n\n\n\n<commit_msg>Enhanced the timer example<commit_after>\/*\n * Main.cpp\n *\n * Created on: 06.04.2017\n * Author: aca619\n *\/\n#include <iostream>\n#include <chrono>\n#include <sys\/neutrino.h>\n#include \"ITimer.h\"\n#include \"TimerService.h\"\n\n#define PM_CODE 4\n#define PM_VALUE 123456\n\nint main(void){\n\tstd::cout << \"Geht los hier\" << std::endl;\n\n\tint chid = ChannelCreate_r(0);\n\tif(chid < 0){\n\t\tstd::cout << \"Channel Create failed\" << std::endl;\n\t}\n\n\tstd::chrono::time_point<std::chrono::system_clock> start, end;\n\n\tstruct _pulse pulse;\n\n\tITimer* timer = new TimerService(chid, PM_CODE);\n\n\tstart = std::chrono::system_clock::now();\n\n\ttimer->setAlarm(500, PM_VALUE);\n\n\tstd::this_thread::sleep_for(std::chrono::milliseconds(200));\n\n\ttimer->stopAlarm();\n\n\tstd::this_thread::sleep_for(std::chrono::seconds(1));\n\n\ttimer->resumeAlarm();\n\n\tint err = MsgReceive_r(chid, &pulse, sizeof(_pulse),NULL);\n\t\tif(err) {\n\t\t\t\t\/\/ TODO error handling\n\t\t\t\tstd::cout << \"client MsgReceive_r failed\" << std::endl;\n\t\t}\n\tend = std::chrono::system_clock::now();\n\n\tint elapsed_seconds = std::chrono::duration_cast<std::chrono::milliseconds> (end-start).count();\n\n\tstd::cout << \"Message received: \" << pulse.value.sival_int << \" after: \" << elapsed_seconds << std::endl;\n\n\tstd::cout << \"Zuende hier\" << std::endl;\n\n\tstart = std::chrono::system_clock::now();\n\n\ttimer->setAlarm(500, PM_VALUE);\n\n\terr = MsgReceive_r(chid, &pulse, sizeof(_pulse),NULL);\n\t\tif(err) {\n\t\t\t\t\/\/ TODO error handling\n\t\t\t\tstd::cout << \"client MsgReceive_r failed\" << std::endl;\n\t\t}\n\tend = std::chrono::system_clock::now();\n\n\telapsed_seconds = std::chrono::duration_cast<std::chrono::milliseconds> (end-start).count();\n\n\tstd::cout << \"Message received: \" << pulse.value.sival_int << \" after: \" << elapsed_seconds << std::endl;\n\n\tstd::cout << \"Zuende hier\" << std::endl;\n}\n\n\n\n\n<|endoftext|>"} {"text":"<commit_before>\/* Rapicorn Tests\n * Copyright (C) 2008 Tim Janik\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * A copy of the GNU Lesser General Public License should ship along\n * with this library; if not, see http:\/\/www.gnu.org\/copyleft\/.\n *\/\n#include <rapicorn.hh>\n#include <sys\/types.h>\n#include <dirent.h>\n#include <errno.h>\n#include <string.h>\n\nnamespace {\nusing namespace Rapicorn;\n\nstatic void\nfill_store (Store1 &s1,\n const String &dirname)\n{\n DIR *d = opendir (dirname.c_str());\n s1.clear();\n if (!d)\n {\n critical (\"failed to access directory: %s: %s\", dirname.c_str(), strerror (errno));\n return;\n }\n struct dirent *e = readdir (d);\n while (e)\n {\n Array row;\n uint n = 0;\n row[n++] = e->d_ino;\n row[n++] = \" | \";\n row[n++] = e->d_type;\n row[n++] = \" | \";\n row[n++] = e->d_name;\n s1.insert (-1, row);\n e = readdir (d);\n }\n closedir (d);\n}\n\nstatic Store1*\ncreate_store ()\n{\n Store1 *s1 = Store1::create_memory_store (\"models\/files\",\n Type::lookup (\"string\"), SELECTION_BROWSE);\n fill_store (*s1, \".\");\n return s1;\n}\n\nextern \"C\" int\nmain (int argc,\n char *argv[])\n{\n \/* initialize Rapicorn for X11 *\/\n Application_SmartHandle smApp = init_app (\"FileView\", &argc, argv); \/\/ acquires Rapicorn mutex\n ApplicationImpl &app = ApplicationImpl::the(); \/\/ FIXME: use Application_SmartHandle once C++ bindings are ready\n\n \/* load GUI definition file, relative to argv[0] *\/\n app.auto_load (\"RapicornTest\", \"fileview.xml\", argv[0]);\n\n \/* create root item *\/\n Store1 *s1 = create_store();\n Wind0wIface &wind0w = *app.create_wind0w (\"main-dialog\",\n Args (\"\"),\n Args (\"ListModel=\" + s1->model().plor_name()));\n wind0w.show();\n\n app.execute_loops();\n\n return 0;\n}\n\n} \/\/ anon\n<commit_msg>TESTS: fixed fileview to use IDL API, model\/store support still missing<commit_after>\/\/ Licensed GNU LGPL v3 or later: http:\/\/www.gnu.org\/licenses\/lgpl.html\n#include <rapicorn.hh>\n#include <sys\/types.h>\n#include <dirent.h>\n#include <errno.h>\n#include <string.h>\n\nnamespace {\nusing namespace Rapicorn;\n\nstatic void\nfill_store (Store1 &s1,\n const String &dirname)\n{\n DIR *d = opendir (dirname.c_str());\n s1.clear();\n if (!d)\n {\n critical (\"failed to access directory: %s: %s\", dirname.c_str(), strerror (errno));\n return;\n }\n struct dirent *e = readdir (d);\n while (e)\n {\n Array row;\n uint n = 0;\n row[n++] = e->d_ino;\n row[n++] = \" | \";\n row[n++] = e->d_type;\n row[n++] = \" | \";\n row[n++] = e->d_name;\n s1.insert (-1, row);\n e = readdir (d);\n }\n closedir (d);\n}\n\nstatic Store1*\ncreate_store ()\n{\n Store1 *s1 = Store1::create_memory_store (\"models\/files\",\n Type::lookup (\"string\"), SELECTION_BROWSE);\n fill_store (*s1, \".\");\n return s1;\n}\n\nextern \"C\" int\nmain (int argc,\n char *argv[])\n{\n \/\/ initialize Rapicorn\n Application app = init_app (\"RapicornFileView\", &argc, argv);\n\n \/\/ find and load GUI definitions relative to argv[0]\n app.auto_load (\"RapicornFileView\", \"fileview.xml\", argv[0]);\n\n \/\/ create main wind0w\n \/\/ FIXME: Store1 *s1 = create_store();\n Wind0w wind0w = app.create_wind0w (\"main-dialog\"); \/\/ FIXME: Args (\"\"), Args (\"ListModel=\" + s1->model().plor_name()));\n wind0w.show();\n\n \/\/ run event loops while wind0ws are on screen\n return app.run_and_exit();\n}\n\n} \/\/ anon\n<|endoftext|>"} {"text":"<commit_before>\/*\n * This file is open source software, licensed to you under the terms\n * of the Apache License, Version 2.0 (the \"License\"). See the NOTICE file\n * distributed with this work for additional information regarding copyright\n * ownership. You may not use this file except in compliance with the License.\n *\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied. See the License for the\n * specific language governing permissions and limitations\n * under the License.\n *\/\n\/*\n * Copyright (C) 2016 ScyllaDB\n *\/\n\n\n#include \"loopback_socket.hh\"\n#include \"rpc\/rpc.hh\"\n#include \"rpc\/lz4_compressor.hh\"\n#include \"rpc\/multi_algo_compressor_factory.hh\"\n#include \"test-utils.hh\"\n#include \"core\/thread.hh\"\n#include \"core\/sleep.hh\"\n\nusing namespace seastar;\n\nstruct serializer {\n};\n\ntemplate <typename T, typename Output>\ninline\nvoid write_arithmetic_type(Output& out, T v) {\n static_assert(std::is_arithmetic<T>::value, \"must be arithmetic type\");\n return out.write(reinterpret_cast<const char*>(&v), sizeof(T));\n}\n\ntemplate <typename T, typename Input>\ninline\nT read_arithmetic_type(Input& in) {\n static_assert(std::is_arithmetic<T>::value, \"must be arithmetic type\");\n T v;\n in.read(reinterpret_cast<char*>(&v), sizeof(T));\n return v;\n}\n\ntemplate <typename Output>\ninline void write(serializer, Output& output, int32_t v) { return write_arithmetic_type(output, v); }\ntemplate <typename Output>\ninline void write(serializer, Output& output, uint32_t v) { return write_arithmetic_type(output, v); }\ntemplate <typename Output>\ninline void write(serializer, Output& output, int64_t v) { return write_arithmetic_type(output, v); }\ntemplate <typename Output>\ninline void write(serializer, Output& output, uint64_t v) { return write_arithmetic_type(output, v); }\ntemplate <typename Output>\ninline void write(serializer, Output& output, double v) { return write_arithmetic_type(output, v); }\ntemplate <typename Input>\ninline int32_t read(serializer, Input& input, rpc::type<int32_t>) { return read_arithmetic_type<int32_t>(input); }\ntemplate <typename Input>\ninline uint32_t read(serializer, Input& input, rpc::type<uint32_t>) { return read_arithmetic_type<uint32_t>(input); }\ntemplate <typename Input>\ninline uint64_t read(serializer, Input& input, rpc::type<uint64_t>) { return read_arithmetic_type<uint64_t>(input); }\ntemplate <typename Input>\ninline uint64_t read(serializer, Input& input, rpc::type<int64_t>) { return read_arithmetic_type<int64_t>(input); }\ntemplate <typename Input>\ninline double read(serializer, Input& input, rpc::type<double>) { return read_arithmetic_type<double>(input); }\n\ntemplate <typename Output>\ninline void write(serializer, Output& out, const sstring& v) {\n write_arithmetic_type(out, uint32_t(v.size()));\n out.write(v.c_str(), v.size());\n}\n\ntemplate <typename Input>\ninline sstring read(serializer, Input& in, rpc::type<sstring>) {\n auto size = read_arithmetic_type<uint32_t>(in);\n sstring ret(sstring::initialized_later(), size);\n in.read(ret.begin(), size);\n return ret;\n}\n\nusing test_rpc_proto = rpc::protocol<serializer>;\nusing connect_fn = std::function<test_rpc_proto::client (ipv4_addr addr)>;\n\nclass rpc_socket_impl : public ::net::socket_impl {\n promise<connected_socket> _p;\n bool _connect;\n loopback_socket_impl _socket;\npublic:\n rpc_socket_impl(loopback_connection_factory& factory, bool connect)\n : _connect(connect), _socket(factory) {\n }\n virtual future<connected_socket> connect(socket_address sa, socket_address local, transport proto = transport::TCP) override {\n return _connect ? _socket.connect(sa, local, proto) : _p.get_future();\n }\n virtual void shutdown() override {\n if (_connect) {\n _socket.shutdown();\n } else {\n _p.set_exception(std::make_exception_ptr(std::system_error(ECONNABORTED, std::system_category())));\n }\n }\n};\n\nfuture<>\nwith_rpc_env(rpc::resource_limits resource_limits, rpc::client_options co, rpc::server_options so, bool connect,\n std::function<future<> (test_rpc_proto& proto, test_rpc_proto::server& server, connect_fn connect)> test_fn) {\n struct state {\n test_rpc_proto proto{serializer()};\n loopback_connection_factory lcf;\n std::unique_ptr<test_rpc_proto::server> server;\n };\n return do_with(state(), [=] (state& s) {\n s.server = std::make_unique<test_rpc_proto::server>(s.proto, so, s.lcf.get_server_socket(), resource_limits);\n auto make_client = [&s, connect, co] (ipv4_addr addr) {\n auto socket = seastar::socket(std::make_unique<rpc_socket_impl>(s.lcf, connect));\n return test_rpc_proto::client(s.proto, co, std::move(socket), addr);\n };\n return test_fn(s.proto, *s.server, make_client).finally([&] {\n return s.server->stop();\n });\n });\n}\n\nstruct cfactory : rpc::compressor::factory {\n mutable int use_compression = 0;\n const sstring name;\n cfactory(sstring name_ = \"LZ4\") : name(std::move(name_)) {}\n const sstring& supported() const override {\n return name;\n }\n std::unique_ptr<rpc::compressor> negotiate(sstring feature, bool is_server) const override {\n if (feature == name) {\n use_compression++;\n return std::make_unique<rpc::lz4_compressor>();\n } else {\n return nullptr;\n }\n }\n};\n\nSEASTAR_TEST_CASE(test_rpc_connect) {\n std::vector<future<>> fs;\n\n for (auto i = 0; i < 2; i++) {\n for (auto j = 0; j < 4; j++) {\n auto factory = std::make_unique<cfactory>();\n rpc::server_options so;\n rpc::client_options co;\n if (i == 1) {\n so.compressor_factory = factory.get();\n }\n if (j & 1) {\n co.compressor_factory = factory.get();\n }\n co.send_timeout_data = j & 2;\n auto f = with_rpc_env({}, co, so, true, [] (test_rpc_proto& proto, test_rpc_proto::server& s, connect_fn connect) {\n return seastar::async([&proto, connect] {\n auto c1 = connect(ipv4_addr());\n auto sum = proto.register_handler(1, [](int a, int b) {\n return make_ready_future<int>(a+b);\n });\n auto result = sum(c1, 2, 3).get0();\n BOOST_REQUIRE_EQUAL(result, 2 + 3);\n c1.stop().get();\n });\n }).handle_exception([] (auto ep) {\n BOOST_FAIL(\"No exception expected\");\n }).finally([factory = std::move(factory), i, j = j & 1] {\n if (i == 1 && j == 1) {\n BOOST_REQUIRE_EQUAL(factory->use_compression, 2);\n } else {\n BOOST_REQUIRE_EQUAL(factory->use_compression, 0);\n }\n });\n fs.emplace_back(std::move(f));\n }\n }\n return when_all(fs.begin(), fs.end()).discard_result();\n}\n\nSEASTAR_TEST_CASE(test_rpc_connect_multi_compression_algo) {\n auto factory1 = std::make_unique<cfactory>();\n auto factory2 = std::make_unique<cfactory>(\"LZ4NEW\");\n rpc::server_options so;\n rpc::client_options co;\n static rpc::multi_algo_compressor_factory server({factory1.get(), factory2.get()});\n static rpc::multi_algo_compressor_factory client({factory2.get(), factory1.get()});\n so.compressor_factory = &server;\n co.compressor_factory = &client;\n return with_rpc_env({}, co, so, true, [] (test_rpc_proto& proto, test_rpc_proto::server& s, connect_fn connect) {\n return seastar::async([&proto, connect] {\n auto c1 = connect(ipv4_addr());\n auto sum = proto.register_handler(1, [](int a, int b) {\n return make_ready_future<int>(a+b);\n });\n auto result = sum(c1, 2, 3).get0();\n BOOST_REQUIRE_EQUAL(result, 2 + 3);\n c1.stop().get();\n });\n }).finally([factory1 = std::move(factory1), factory2 = std::move(factory2)] {\n BOOST_REQUIRE_EQUAL(factory1->use_compression, 0);\n BOOST_REQUIRE_EQUAL(factory2->use_compression, 2);\n });\n}\n\nSEASTAR_TEST_CASE(test_rpc_connect_abort) {\n return with_rpc_env({}, {}, {}, false, [] (test_rpc_proto& proto, test_rpc_proto::server& s, connect_fn connect) {\n return seastar::async([&proto, connect] {\n auto c1 = connect(ipv4_addr());\n auto f = proto.register_handler(1, []() { return make_ready_future<>(); });\n c1.stop().get0();\n try {\n f(c1).get0();\n BOOST_REQUIRE(false);\n } catch (...) {}\n });\n });\n}\n\nSEASTAR_TEST_CASE(test_rpc_cancel) {\n using namespace std::chrono_literals;\n return with_rpc_env({}, {}, {}, true, [] (test_rpc_proto& proto, test_rpc_proto::server& s, connect_fn connect) {\n return seastar::async([&proto, connect] {\n auto c1 = connect(ipv4_addr());\n bool rpc_executed = false;\n int good = 0;\n promise<> handler_called;\n future<> f_handler_called = handler_called.get_future();\n auto call = proto.register_handler(1, [&rpc_executed, handler_called = std::move(handler_called)] () mutable {\n handler_called.set_value(); rpc_executed = true; return sleep(1ms);\n });\n rpc::cancellable cancel;\n auto f = call(c1, cancel);\n \/\/ cancel send side\n cancel.cancel();\n try {\n f.get();\n } catch(rpc::canceled_error&) {\n good += !rpc_executed;\n };\n f = call(c1, cancel);\n \/\/ cancel wait side\n f_handler_called.then([&cancel] {\n cancel.cancel();\n }).get();\n try {\n f.get();\n } catch(rpc::canceled_error&) {\n good += 10*rpc_executed;\n };\n c1.stop().get();\n BOOST_REQUIRE_EQUAL(good, 11);\n });\n });\n}\n\nSEASTAR_TEST_CASE(test_message_to_big) {\n return with_rpc_env({0, 1, 100}, {}, {}, true, [] (test_rpc_proto& proto, test_rpc_proto::server& s, connect_fn connect) {\n return seastar::async([&proto, connect] {\n auto c = connect(ipv4_addr());\n bool good = true;\n auto call = proto.register_handler(1, [&] (sstring payload) mutable {\n good = false;\n });\n try {\n call(c, sstring(sstring::initialized_later(), 101)).get();\n good = false;\n } catch(std::runtime_error& err) {\n } catch(...) {\n good = false;\n }\n c.stop().get();\n BOOST_REQUIRE_EQUAL(good, true);\n });\n });\n}\n<commit_msg>tests: rpc: add streaming tests<commit_after>\/*\n * This file is open source software, licensed to you under the terms\n * of the Apache License, Version 2.0 (the \"License\"). See the NOTICE file\n * distributed with this work for additional information regarding copyright\n * ownership. You may not use this file except in compliance with the License.\n *\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied. See the License for the\n * specific language governing permissions and limitations\n * under the License.\n *\/\n\/*\n * Copyright (C) 2016 ScyllaDB\n *\/\n\n\n#include \"loopback_socket.hh\"\n#include \"rpc\/rpc.hh\"\n#include \"rpc\/rpc_types.hh\"\n#include \"rpc\/lz4_compressor.hh\"\n#include \"rpc\/multi_algo_compressor_factory.hh\"\n#include \"test-utils.hh\"\n#include \"core\/thread.hh\"\n#include \"core\/sleep.hh\"\n\nusing namespace seastar;\n\nstruct serializer {\n};\n\ntemplate <typename T, typename Output>\ninline\nvoid write_arithmetic_type(Output& out, T v) {\n static_assert(std::is_arithmetic<T>::value, \"must be arithmetic type\");\n return out.write(reinterpret_cast<const char*>(&v), sizeof(T));\n}\n\ntemplate <typename T, typename Input>\ninline\nT read_arithmetic_type(Input& in) {\n static_assert(std::is_arithmetic<T>::value, \"must be arithmetic type\");\n T v;\n in.read(reinterpret_cast<char*>(&v), sizeof(T));\n return v;\n}\n\ntemplate <typename Output>\ninline void write(serializer, Output& output, int32_t v) { return write_arithmetic_type(output, v); }\ntemplate <typename Output>\ninline void write(serializer, Output& output, uint32_t v) { return write_arithmetic_type(output, v); }\ntemplate <typename Output>\ninline void write(serializer, Output& output, int64_t v) { return write_arithmetic_type(output, v); }\ntemplate <typename Output>\ninline void write(serializer, Output& output, uint64_t v) { return write_arithmetic_type(output, v); }\ntemplate <typename Output>\ninline void write(serializer, Output& output, double v) { return write_arithmetic_type(output, v); }\ntemplate <typename Input>\ninline int32_t read(serializer, Input& input, rpc::type<int32_t>) { return read_arithmetic_type<int32_t>(input); }\ntemplate <typename Input>\ninline uint32_t read(serializer, Input& input, rpc::type<uint32_t>) { return read_arithmetic_type<uint32_t>(input); }\ntemplate <typename Input>\ninline uint64_t read(serializer, Input& input, rpc::type<uint64_t>) { return read_arithmetic_type<uint64_t>(input); }\ntemplate <typename Input>\ninline uint64_t read(serializer, Input& input, rpc::type<int64_t>) { return read_arithmetic_type<int64_t>(input); }\ntemplate <typename Input>\ninline double read(serializer, Input& input, rpc::type<double>) { return read_arithmetic_type<double>(input); }\n\ntemplate <typename Output>\ninline void write(serializer, Output& out, const sstring& v) {\n write_arithmetic_type(out, uint32_t(v.size()));\n out.write(v.c_str(), v.size());\n}\n\ntemplate <typename Input>\ninline sstring read(serializer, Input& in, rpc::type<sstring>) {\n auto size = read_arithmetic_type<uint32_t>(in);\n sstring ret(sstring::initialized_later(), size);\n in.read(ret.begin(), size);\n return ret;\n}\n\nusing test_rpc_proto = rpc::protocol<serializer>;\nusing make_socket_fn = std::function<seastar::socket ()>;\n\nstruct rpc_loopback_error_injector : public loopback_error_injector {\n int _x = 0;\n bool server_rcv_error() override {\n return _x++ >= 50;\n }\n};\n\nclass rpc_socket_impl : public ::net::socket_impl {\n promise<connected_socket> _p;\n bool _connect;\n loopback_socket_impl _socket;\n rpc_loopback_error_injector _error_injector;\npublic:\n rpc_socket_impl(loopback_connection_factory& factory, bool connect, bool inject_error)\n : _connect(connect),\n _socket(factory, inject_error ? &_error_injector : nullptr) {\n }\n virtual future<connected_socket> connect(socket_address sa, socket_address local, transport proto = transport::TCP) override {\n return _connect ? _socket.connect(sa, local, proto) : _p.get_future();\n }\n virtual void shutdown() override {\n if (_connect) {\n _socket.shutdown();\n } else {\n _p.set_exception(std::make_exception_ptr(std::system_error(ECONNABORTED, std::system_category())));\n }\n }\n};\n\nfuture<>\nwith_rpc_env(rpc::resource_limits resource_limits, rpc::server_options so, bool connect, bool inject_error,\n std::function<future<> (test_rpc_proto& proto, test_rpc_proto::server& server, make_socket_fn make_socket)> test_fn) {\n struct state {\n test_rpc_proto proto{serializer()};\n loopback_connection_factory lcf;\n std::unique_ptr<test_rpc_proto::server> server;\n };\n return do_with(state(), [=] (state& s) {\n s.server = std::make_unique<test_rpc_proto::server>(s.proto, so, s.lcf.get_server_socket(), resource_limits);\n auto make_socket = [&s, connect, inject_error] () {\n return seastar::socket(std::make_unique<rpc_socket_impl>(s.lcf, connect, inject_error));\n };\n return test_fn(s.proto, *s.server, make_socket).finally([&] {\n return s.server->stop();\n });\n });\n}\n\nstruct cfactory : rpc::compressor::factory {\n mutable int use_compression = 0;\n const sstring name;\n cfactory(sstring name_ = \"LZ4\") : name(std::move(name_)) {}\n const sstring& supported() const override {\n return name;\n }\n std::unique_ptr<rpc::compressor> negotiate(sstring feature, bool is_server) const override {\n if (feature == name) {\n use_compression++;\n return std::make_unique<rpc::lz4_compressor>();\n } else {\n return nullptr;\n }\n }\n};\n#if 1\nSEASTAR_TEST_CASE(test_rpc_connect) {\n std::vector<future<>> fs;\n\n for (auto i = 0; i < 2; i++) {\n for (auto j = 0; j < 4; j++) {\n auto factory = std::make_unique<cfactory>();\n rpc::server_options so;\n rpc::client_options co;\n if (i == 1) {\n so.compressor_factory = factory.get();\n }\n if (j & 1) {\n co.compressor_factory = factory.get();\n }\n co.send_timeout_data = j & 2;\n auto f = with_rpc_env({}, so, true, false, [co] (test_rpc_proto& proto, test_rpc_proto::server& s, make_socket_fn make_socket) {\n return seastar::async([&proto, make_socket, co] {\n auto c1 = test_rpc_proto::client(proto, co, make_socket(), ipv4_addr());\n auto sum = proto.register_handler(1, [](int a, int b) {\n return make_ready_future<int>(a+b);\n });\n auto result = sum(c1, 2, 3).get0();\n BOOST_REQUIRE_EQUAL(result, 2 + 3);\n c1.stop().get();\n });\n }).handle_exception([] (auto ep) {\n BOOST_FAIL(\"No exception expected\");\n }).finally([factory = std::move(factory), i, j = j & 1] {\n if (i == 1 && j == 1) {\n BOOST_REQUIRE_EQUAL(factory->use_compression, 2);\n } else {\n BOOST_REQUIRE_EQUAL(factory->use_compression, 0);\n }\n });\n fs.emplace_back(std::move(f));\n }\n }\n return when_all(fs.begin(), fs.end()).discard_result();\n}\n\nSEASTAR_TEST_CASE(test_rpc_connect_multi_compression_algo) {\n auto factory1 = std::make_unique<cfactory>();\n auto factory2 = std::make_unique<cfactory>(\"LZ4NEW\");\n rpc::server_options so;\n rpc::client_options co;\n static rpc::multi_algo_compressor_factory server({factory1.get(), factory2.get()});\n static rpc::multi_algo_compressor_factory client({factory2.get(), factory1.get()});\n so.compressor_factory = &server;\n co.compressor_factory = &client;\n return with_rpc_env({}, so, true, false, [co] (test_rpc_proto& proto, test_rpc_proto::server& s, make_socket_fn make_socket) {\n return seastar::async([&proto, make_socket, co] {\n auto c1 = test_rpc_proto::client(proto, co, make_socket(), ipv4_addr());\n auto sum = proto.register_handler(1, [](int a, int b) {\n return make_ready_future<int>(a+b);\n });\n auto result = sum(c1, 2, 3).get0();\n BOOST_REQUIRE_EQUAL(result, 2 + 3);\n c1.stop().get();\n });\n }).finally([factory1 = std::move(factory1), factory2 = std::move(factory2)] {\n BOOST_REQUIRE_EQUAL(factory1->use_compression, 0);\n BOOST_REQUIRE_EQUAL(factory2->use_compression, 2);\n });\n}\n\nSEASTAR_TEST_CASE(test_rpc_connect_abort) {\n return with_rpc_env({}, {}, false, false, [] (test_rpc_proto& proto, test_rpc_proto::server& s, make_socket_fn make_socket) {\n return seastar::async([&proto, make_socket] {\n auto c1 = test_rpc_proto::client(proto, {}, make_socket(), ipv4_addr());\n auto f = proto.register_handler(1, []() { return make_ready_future<>(); });\n c1.stop().get0();\n try {\n f(c1).get0();\n BOOST_REQUIRE(false);\n } catch (...) {}\n });\n });\n}\n\nSEASTAR_TEST_CASE(test_rpc_cancel) {\n using namespace std::chrono_literals;\n return with_rpc_env({}, {}, true, false, [] (test_rpc_proto& proto, test_rpc_proto::server& s, make_socket_fn make_socket) {\n return seastar::async([&proto, make_socket] {\n auto c1 = test_rpc_proto::client(proto, {}, make_socket(), ipv4_addr());\n bool rpc_executed = false;\n int good = 0;\n promise<> handler_called;\n future<> f_handler_called = handler_called.get_future();\n auto call = proto.register_handler(1, [&rpc_executed, handler_called = std::move(handler_called)] () mutable {\n handler_called.set_value(); rpc_executed = true; return sleep(1ms);\n });\n rpc::cancellable cancel;\n auto f = call(c1, cancel);\n \/\/ cancel send side\n cancel.cancel();\n try {\n f.get();\n } catch(rpc::canceled_error&) {\n good += !rpc_executed;\n };\n f = call(c1, cancel);\n \/\/ cancel wait side\n f_handler_called.then([&cancel] {\n cancel.cancel();\n }).get();\n try {\n f.get();\n } catch(rpc::canceled_error&) {\n good += 10*rpc_executed;\n };\n c1.stop().get();\n BOOST_REQUIRE_EQUAL(good, 11);\n });\n });\n}\n\nSEASTAR_TEST_CASE(test_message_to_big) {\n return with_rpc_env({0, 1, 100}, {}, true, false, [] (test_rpc_proto& proto, test_rpc_proto::server& s, make_socket_fn make_socket) {\n return seastar::async([&proto, make_socket] {\n auto c = test_rpc_proto::client(proto, {}, make_socket(), ipv4_addr());\n bool good = true;\n auto call = proto.register_handler(1, [&] (sstring payload) mutable {\n good = false;\n });\n try {\n call(c, sstring(sstring::initialized_later(), 101)).get();\n good = false;\n } catch(std::runtime_error& err) {\n } catch(...) {\n good = false;\n }\n c.stop().get();\n BOOST_REQUIRE_EQUAL(good, true);\n });\n });\n}\n#endif\n\nstruct stream_test_result {\n bool client_source_closed = false;\n bool server_source_closed = false;\n bool sink_exception = false;\n bool sink_close_exception = false;\n bool source_done_exception = false;\n bool server_done_exception = false;\n bool client_stop_exception = false;\n int server_sum = 0;\n};\n\nfuture<stream_test_result> stream_test_func(test_rpc_proto& proto, make_socket_fn make_socket, bool stop_client) {\n return seastar::async([&proto, make_socket, stop_client] {\n stream_test_result r;\n auto c = test_rpc_proto::client(proto, {}, make_socket(), ipv4_addr());\n future<> server_done = make_ready_future();\n proto.register_handler(1, [&](int i, rpc::source<int> source) {\n BOOST_REQUIRE_EQUAL(i, 666);\n auto sink = source.make_sink<serializer, sstring>();\n auto sink_loop = seastar::async([sink] () mutable {\n for (auto i = 0; i < 100; i++) {\n sink(\"seastar\").get();\n sleep(std::chrono::milliseconds(1)).get();\n }\n sink.close().get();\n });\n auto source_loop = seastar::async([source, &r] () mutable {\n while (!r.server_source_closed) {\n auto data = source().get0();\n if (data) {\n r.server_sum += std::get<0>(*data);\n } else {\n r.server_source_closed = true;\n }\n }\n });\n server_done = when_all_succeed(std::move(sink_loop), std::move(source_loop)).discard_result();\n return sink;\n });\n auto call = proto.make_client<rpc::source<sstring> (int, rpc::sink<int>)>(1);\n auto x = [&] {\n try {\n return c.make_stream_sink<serializer, int>(make_socket()).get0();\n } catch (...) {\n c.stop().get();\n throw;\n }\n };\n auto sink = x();\n auto source = call(c, 666, sink).get0();\n auto source_done = seastar::async([&] {\n while (!r.client_source_closed) {\n auto data = source().get0();\n if (data) {\n BOOST_REQUIRE_EQUAL(std::get<0>(*data), \"seastar\");\n } else {\n r.client_source_closed = true;\n }\n }\n });\n auto check_exception = [] (auto f) {\n try {\n f.get();\n } catch (...) {\n return true;\n }\n return false;\n };\n future<> stop_client_future = make_ready_future();\n for (int i = 1; i < 101; i++) {\n if (stop_client && i == 50) {\n \/\/ stop client while stream is in use\n stop_client_future = c.stop();\n }\n sleep(std::chrono::milliseconds(1)).get();\n r.sink_exception = check_exception(sink(i));\n if (r.sink_exception) {\n break;\n }\n }\n r.sink_close_exception = check_exception(sink.close());\n r.source_done_exception = check_exception(std::move(source_done));\n r.server_done_exception = check_exception(std::move(server_done));\n r.client_stop_exception = check_exception(!stop_client ? c.stop() : std::move(stop_client_future));\n return r;\n });\n}\n\nSEASTAR_TEST_CASE(test_stream_simple) {\n rpc::server_options so;\n so.streaming_domain = rpc::streaming_domain_type(1);\n return with_rpc_env({}, so, true, false, [] (test_rpc_proto& proto, test_rpc_proto::server& s, make_socket_fn make_socket) {\n return stream_test_func(proto, make_socket, false).then([] (stream_test_result r) {\n BOOST_REQUIRE(r.client_source_closed &&\n r.server_source_closed &&\n r.server_sum == 5050 &&\n !r.sink_exception &&\n !r.sink_close_exception &&\n !r.source_done_exception &&\n !r.server_done_exception &&\n !r.client_stop_exception);\n });\n });\n}\n\nSEASTAR_TEST_CASE(test_stream_stop_client) {\n rpc::server_options so;\n so.streaming_domain = rpc::streaming_domain_type(1);\n return with_rpc_env({}, so, true, false, [] (test_rpc_proto& proto, test_rpc_proto::server& s, make_socket_fn make_socket) {\n return stream_test_func(proto, make_socket, true).then([] (stream_test_result r) {\n BOOST_REQUIRE(!r.client_source_closed &&\n !r.server_source_closed &&\n r.sink_exception &&\n r.sink_close_exception &&\n r.source_done_exception &&\n r.server_done_exception &&\n !r.client_stop_exception);\n });\n });\n}\n\n\nSEASTAR_TEST_CASE(test_stream_connection_error) {\n rpc::server_options so;\n so.streaming_domain = rpc::streaming_domain_type(1);\n return with_rpc_env({}, so, true, true, [] (test_rpc_proto& proto, test_rpc_proto::server& s, make_socket_fn make_socket) {\n return stream_test_func(proto, make_socket, false).then([] (stream_test_result r) {\n BOOST_REQUIRE(!r.client_source_closed &&\n !r.server_source_closed &&\n r.sink_exception &&\n r.sink_close_exception &&\n r.source_done_exception &&\n r.server_done_exception &&\n !r.client_stop_exception);\n });\n });\n}\n<|endoftext|>"} {"text":"<commit_before>\/**\n * File : D2.cpp\n * Author : Kazune Takahashi\n * Created : 2018-7-15 16:51:34\n * Powered by Visual Studio Code\n *\/\n\n#include <iostream>\n#include <iomanip> \/\/ << fixed << setprecision(xxx)\n#include <algorithm> \/\/ do { } while ( next_permutation(A, A+xxx) ) ;\n#include <vector>\n#include <string> \/\/ to_string(nnn) \/\/ substr(m, n) \/\/ stoi(nnn)\n#include <complex>\n#include <tuple>\n#include <queue>\n#include <stack>\n#include <map> \/\/ if (M.find(key) != M.end()) { }\n#include <set>\n#include <functional>\n#include <random> \/\/ auto rd = bind(uniform_int_distribution<int>(0, 9), mt19937(19920725));\n#include <chrono> \/\/ std::chrono::system_clock::time_point start_time, end_time;\n\/\/ start = std::chrono::system_clock::now();\n\/\/ double elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(end_time-start_time).count();\n#include <cctype>\n#include <cassert>\n#include <cmath>\n#include <cstdio>\n#include <cstdlib>\nusing namespace std;\n\n#define DEBUG 0 \/\/ change 0 -> 1 if we need debug.\n\ntypedef long long ll;\n\n\/\/ const int dx[4] = {1, 0, -1, 0};\n\/\/ const int dy[4] = {0, 1, 0, -1};\n\n\/\/ const int C = 1e6+10;\nconst ll infty = 1000000007;\nconst ll MOD = 1000000007;\n\ntypedef tuple<ll, ll> P;\n\nint N;\nll H[110];\n\nlong long power(long long x, long long n)\n{\n if (n == 0)\n {\n return 1;\n }\n else if (n % 2 == 1)\n {\n return (x * power(x, n - 1)) % MOD;\n }\n else\n {\n long long half = power(x, n \/ 2);\n return (half * half) % MOD;\n }\n}\n\nint h_ind(int l, int r)\n{\n int ind = -1;\n ll mini = infty;\n for (auto i = l; i < r; i++)\n {\n if (H[i] < mini)\n {\n ind = i;\n mini = H[i];\n }\n }\n return ind;\n}\n\nP func(int l, int r, ll h)\n{\n if (l == r)\n {\n return P(1, 1);\n }\n int ind = h_ind(l, r);\n ll height = H[ind] - h;\n if (l + 1 == r && height == 1)\n {\n return P(2, 1);\n }\n if (height == 1)\n {\n auto it1 = func(l, ind, h);\n auto it2 = func(ind + 1, r, h);\n ll f1 = get<0>(it1);\n ll g1 = get<1>(it1);\n ll f2 = get<0>(it2);\n ll g2 = get<1>(it2);\n ll f = (((2 * f1) % MOD) * f2) % MOD;\n ll g = (g1 * g2) % MOD;\n return P(f, g);\n }\n auto it1 = func(l, ind, h + height - 1);\n ll f1 = get<0>(it1);\n ll g1 = get<1>(it1);\n ll f = f1;\n f += 2 * (MOD - g1);\n f %= MOD;\n f += (power(2, height) * g1) % MOD;\n f %= MOD;\n ll g = (power(2, height - 1) * g1) % MOD;\n return P(f, g);\n}\n\nint main()\n{\n cin >> N;\n for (auto i = 0; i < N; i++)\n {\n cin >> H[i];\n }\n cout << get<0>(func(0, N, 0)) << endl;\n}<commit_msg>tried D2.cpp to 'D'<commit_after>\/**\n * File : D2.cpp\n * Author : Kazune Takahashi\n * Created : 2018-7-15 16:51:34\n * Powered by Visual Studio Code\n *\/\n\n#include <iostream>\n#include <iomanip> \/\/ << fixed << setprecision(xxx)\n#include <algorithm> \/\/ do { } while ( next_permutation(A, A+xxx) ) ;\n#include <vector>\n#include <string> \/\/ to_string(nnn) \/\/ substr(m, n) \/\/ stoi(nnn)\n#include <complex>\n#include <tuple>\n#include <queue>\n#include <stack>\n#include <map> \/\/ if (M.find(key) != M.end()) { }\n#include <set>\n#include <functional>\n#include <random> \/\/ auto rd = bind(uniform_int_distribution<int>(0, 9), mt19937(19920725));\n#include <chrono> \/\/ std::chrono::system_clock::time_point start_time, end_time;\n\/\/ start = std::chrono::system_clock::now();\n\/\/ double elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(end_time-start_time).count();\n#include <cctype>\n#include <cassert>\n#include <cmath>\n#include <cstdio>\n#include <cstdlib>\nusing namespace std;\n\n#define DEBUG 0 \/\/ change 0 -> 1 if we need debug.\n\ntypedef long long ll;\n\n\/\/ const int dx[4] = {1, 0, -1, 0};\n\/\/ const int dy[4] = {0, 1, 0, -1};\n\n\/\/ const int C = 1e6+10;\nconst ll infty = 1000000007;\nconst ll MOD = 1000000007;\n\ntypedef tuple<ll, ll> P;\n\nint N;\nll H[110];\n\nlong long power(long long x, long long n)\n{\n if (n == 0)\n {\n return 1;\n }\n else if (n % 2 == 1)\n {\n return (x * power(x, n - 1)) % MOD;\n }\n else\n {\n long long half = power(x, n \/ 2);\n return (half * half) % MOD;\n }\n}\n\nint h_ind(int l, int r)\n{\n int ind = -1;\n ll mini = infty;\n for (auto i = l; i < r; i++)\n {\n if (H[i] < mini)\n {\n ind = i;\n mini = H[i];\n }\n }\n return ind;\n}\n\nP func(int l, int r, ll h)\n{\n if (l == r)\n {\n cerr << \"func(\" << l << \", \" << r << \", \" << h << \") = \";\n cerr << \"1, 1\" << endl;\n return P(1, 1);\n }\n int ind = h_ind(l, r);\n ll height = H[ind] - h;\n if (l + 1 == r && height == 1)\n {\n cerr << \"func(\" << l << \", \" << r << \", \" << h << \") = \";\n cerr << \"2, 1\" << endl;\n return P(2, 1);\n }\n if (height == 1)\n {\n auto it1 = func(l, ind, h);\n auto it2 = func(ind + 1, r, h);\n ll f1 = get<0>(it1);\n ll g1 = get<1>(it1);\n ll f2 = get<0>(it2);\n ll g2 = get<1>(it2);\n ll f = (((2 * f1) % MOD) * f2) % MOD;\n ll g = (g1 * g2) % MOD;\n cerr << \"func(\" << l << \", \" << r << \", \" << h << \") = \";\n cerr << f << \", \" << g << endl;\n return P(f, g);\n }\n auto it1 = func(l, ind, h + height - 1);\n ll f1 = get<0>(it1);\n ll g1 = get<1>(it1);\n ll f = f1;\n f += 2 * (MOD - g1);\n f %= MOD;\n f += (power(2, height) * g1) % MOD;\n f %= MOD;\n ll g = (power(2, height - 1) * g1) % MOD;\n cerr << \"func(\" << l << \", \" << r << \", \" << h << \") = \";\n cerr << f << \", \" << g << endl;\n return P(f, g);\n}\n\nint main()\n{\n cin >> N;\n for (auto i = 0; i < N; i++)\n {\n cin >> H[i];\n }\n cout << get<0>(func(0, N, 0)) << endl;\n}<|endoftext|>"} {"text":"<commit_before>\/\/ This file is a part of the OpenSurgSim project.\n\/\/ Copyright 2012-2013, SimQuest Solutions Inc.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n\/\/\/ \\file\n\/\/\/ Tests for the View class.\n\n#include \"SurgSim\/Graphics\/UnitTests\/MockObjects.h\"\n\n#include \"gtest\/gtest.h\"\n\n#include <random>\n\nusing SurgSim::Graphics::Camera;\nusing SurgSim::Graphics::View;\n\nTEST(ViewTests, InitTest)\n{\n\tASSERT_NO_THROW({std::shared_ptr<View> view = std::make_shared<MockView>(\"test name\");});\n}\n\nTEST(ViewTests, NameTest)\n{\n\tstd::shared_ptr<View> view = std::make_shared<MockView>(\"test name\");\n\n\tEXPECT_EQ(\"test name\", view->getName());\n}\n\nTEST(ViewTests, PositionAndDimensionsTest)\n{\n\tstd::shared_ptr<View> view = std::make_shared<MockView>(\"test name\");\n\n\tstd::default_random_engine generator;\n\tstd::uniform_int_distribution<int> distribution(0, 1000);\n\n\tint x = distribution(generator);\n\tint y = distribution(generator);\n\tint width = distribution(generator);\n\tint height = distribution(generator);\n\n\t\/\/\/ Set position and check that it set correctly\n\tEXPECT_TRUE(view->setPosition(x, y));\n\n\tint testX, testY;\n\tview->getPosition(&testX, &testY);\n\n\tEXPECT_EQ(x, testX);\n\tEXPECT_EQ(y, testY);\n\n\t\/\/\/ Set dimensions and check that it set correctly\n\tEXPECT_TRUE(view->setDimensions(width, height));\n\n\tint testWidth, testHeight;\n\tview->getDimensions(&testWidth, &testHeight);\n\n\tEXPECT_EQ(width, testWidth);\n\tEXPECT_EQ(height, testHeight);\n}\n\nTEST(ViewTests, CameraTest)\n{\n\tstd::shared_ptr<View> view = std::make_shared<MockView>(\"test name\");\n\n\tstd::shared_ptr<Camera> camera = std::make_shared<MockCamera>(\"test camera\");\n\n\t\/\/\/ Set the camera and check that it set correctly\n\tview->setCamera(camera);\n\n\tEXPECT_EQ(camera, view->getCamera());\n}\n\nTEST(ViewTests, UpdateTest)\n{\n\tstd::shared_ptr<MockView> mockView = std::make_shared<MockView>(\"test name\");\n\tstd::shared_ptr<View> view = mockView;\n\n\tEXPECT_EQ(0, mockView->getNumUpdates());\n\tEXPECT_EQ(0.0, mockView->getSumDt());\n\n\tdouble sumDt = 0.0;\n\tstd::default_random_engine generator;\n\tstd::uniform_real_distribution<double> distribution(0.0, 1.0);\n\n\t\/\/\/ Do 10 updates with random dt and check each time that the number of updates and sum of dt are correct.\n\tfor (int i = 1; i <= 10; ++i)\n\t{\n\t\tdouble dt = distribution(generator);\n\t\tsumDt += dt;\n\n\t\tview->update(dt);\n\t\tEXPECT_EQ(i, mockView->getNumUpdates());\n\t\tEXPECT_LT(fabs(sumDt - mockView->getSumDt()), Eigen::NumTraits<double>::dummy_precision());\n\t}\n}\n<commit_msg>Check that setCamera() returns true in Graphics ViewTests.<commit_after>\/\/ This file is a part of the OpenSurgSim project.\n\/\/ Copyright 2012-2013, SimQuest Solutions Inc.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n\/\/\/ \\file\n\/\/\/ Tests for the View class.\n\n#include \"SurgSim\/Graphics\/UnitTests\/MockObjects.h\"\n\n#include \"gtest\/gtest.h\"\n\n#include <random>\n\nusing SurgSim::Graphics::Camera;\nusing SurgSim::Graphics::View;\n\nTEST(ViewTests, InitTest)\n{\n\tASSERT_NO_THROW({std::shared_ptr<View> view = std::make_shared<MockView>(\"test name\");});\n}\n\nTEST(ViewTests, NameTest)\n{\n\tstd::shared_ptr<View> view = std::make_shared<MockView>(\"test name\");\n\n\tEXPECT_EQ(\"test name\", view->getName());\n}\n\nTEST(ViewTests, PositionAndDimensionsTest)\n{\n\tstd::shared_ptr<View> view = std::make_shared<MockView>(\"test name\");\n\n\tstd::default_random_engine generator;\n\tstd::uniform_int_distribution<int> distribution(0, 1000);\n\n\tint x = distribution(generator);\n\tint y = distribution(generator);\n\tint width = distribution(generator);\n\tint height = distribution(generator);\n\n\t\/\/\/ Set position and check that it set correctly\n\tEXPECT_TRUE(view->setPosition(x, y));\n\n\tint testX, testY;\n\tview->getPosition(&testX, &testY);\n\n\tEXPECT_EQ(x, testX);\n\tEXPECT_EQ(y, testY);\n\n\t\/\/\/ Set dimensions and check that it set correctly\n\tEXPECT_TRUE(view->setDimensions(width, height));\n\n\tint testWidth, testHeight;\n\tview->getDimensions(&testWidth, &testHeight);\n\n\tEXPECT_EQ(width, testWidth);\n\tEXPECT_EQ(height, testHeight);\n}\n\nTEST(ViewTests, CameraTest)\n{\n\tstd::shared_ptr<View> view = std::make_shared<MockView>(\"test name\");\n\n\tstd::shared_ptr<Camera> camera = std::make_shared<MockCamera>(\"test camera\");\n\n\t\/\/\/ Set the camera and check that it set correctly\n\tEXPECT_TRUE(view->setCamera(camera));\n\n\tEXPECT_EQ(camera, view->getCamera());\n}\n\nTEST(ViewTests, UpdateTest)\n{\n\tstd::shared_ptr<MockView> mockView = std::make_shared<MockView>(\"test name\");\n\tstd::shared_ptr<View> view = mockView;\n\n\tEXPECT_EQ(0, mockView->getNumUpdates());\n\tEXPECT_EQ(0.0, mockView->getSumDt());\n\n\tdouble sumDt = 0.0;\n\tstd::default_random_engine generator;\n\tstd::uniform_real_distribution<double> distribution(0.0, 1.0);\n\n\t\/\/\/ Do 10 updates with random dt and check each time that the number of updates and sum of dt are correct.\n\tfor (int i = 1; i <= 10; ++i)\n\t{\n\t\tdouble dt = distribution(generator);\n\t\tsumDt += dt;\n\n\t\tview->update(dt);\n\t\tEXPECT_EQ(i, mockView->getNumUpdates());\n\t\tEXPECT_LT(fabs(sumDt - mockView->getSumDt()), Eigen::NumTraits<double>::dummy_precision());\n\t}\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"Menu_button.h\"\n#include \"Input_handler.h\"\n\nMenu_button::Menu_button(const Loader_params* params, void(*callback)()) : SDL_Game_object(params), m_callback(callback) {\n\tm_current_frame = MOUSE_OUT;\n}\n\nvoid Menu_button::draw() {\n\tSDL_Game_object::draw();\n}\n\nvoid Menu_button::update() {\n\tVec2D* mouse_pos = The_Input_handler->get_mouse_position();\n\tdouble mx = mouse_pos->get_x();\n\tdouble my = mouse_pos->get_y();\n\tdouble x = m_position.get_x();\n\tdouble y = m_position.get_y();\n\n\tm_current_frame = MOUSE_OUT;\n\n\tif (mx < (x + m_width) && mx >= x && my < (y + m_height) && my >= y) {\n\t\tm_current_frame = MOUSE_OVER;\n\t\tif (The_Input_handler->get_mouse_button_state(LEFT)) {\n\t\t\tm_current_frame = CLICKED;\n\t\t}\n\t}\n}\n\nvoid Menu_button::clean() {\n\tSDL_Game_object::clean();\n}<commit_msg>working button callback functionality<commit_after>#include \"Menu_button.h\"\n#include \"Input_handler.h\"\n\nMenu_button::Menu_button(const Loader_params* params, void(*callback)()) : SDL_Game_object(params), m_callback(callback) {\n\tm_current_frame = MOUSE_OUT;\n}\n\nvoid Menu_button::draw() {\n\tSDL_Game_object::draw();\n}\n\nvoid Menu_button::update() {\n\tVec2D* mouse_pos = The_Input_handler->get_mouse_position();\n\tdouble mx = mouse_pos->get_x();\n\tdouble my = mouse_pos->get_y();\n\tdouble x = m_position.get_x();\n\tdouble y = m_position.get_y();\n\n\tif (mx < (x + m_width) && mx >= x && my < (y + m_height) && my >= y) {\n\t\tif (The_Input_handler->get_mouse_button_state(LEFT) && m_released) {\n\t\t\tm_current_frame = CLICKED;\n\t\t\tm_callback();\n\t\t\tm_released = false;\n\t\t} else if (!The_Input_handler->get_mouse_button_state(LEFT)) {\n\t\t\tm_released = true;\n\t\t\tm_current_frame = MOUSE_OVER;\n\t\t}\n\t} else {\n\t\tm_current_frame = MOUSE_OUT;\n\t}\n}\n\nvoid Menu_button::clean() {\n\tSDL_Game_object::clean();\n}<|endoftext|>"} {"text":"<commit_before>#pragma once\n\n#include \"..\/utils\/type_traits.hpp\"\n\nnamespace autocxxpy\n{\n template <class T, class T2>\n auto append_as_tuple(T&& v1, T2&& v2)\n {\n return std::make_tuple<T, remove_cvref_t<T2>>(std::move(v1), std::move(v2));\n }\n\n template <class ... Ts, class T2, size_t ... idx>\n auto append_as_tuple_impl(std::tuple<Ts...> tv, T2&& v2, std::index_sequence<idx...>)\n {\n return std::make_tuple<Ts ..., T2>(std::move(std::get<idx>(tv)) ..., std::move(v2));\n }\n\n template <class ... Ts, class T2>\n auto append_as_tuple(std::tuple<Ts ...>&& tv, T2&& v2)\n {\n return append_as_tuple_impl(std::move(tv), std::move(v2), std::index_sequence_for<Ts...>{});\n }\n}\n<commit_msg>Delete utils.hpp<commit_after><|endoftext|>"} {"text":"<commit_before>#include <string.h>\n#include <thin3d\/thin3d.h>\n\n#include \"base\/logging.h\"\n#include \"image\/zim_load.h\"\n#include \"image\/png_load.h\"\n#include \"file\/vfs.h\"\n#include \"ext\/jpge\/jpgd.h\"\n\nstatic const char * const glsl_fsTexCol =\n\"varying vec4 oColor0;\\n\"\n\"varying vec2 oTexCoord0;\\n\"\n\"uniform sampler2D Sampler0;\\n\"\n\"void main() { gl_FragColor = oColor0 * texture2D(Sampler0, oTexCoord0); }\\n\";\n\nstatic const char * const hlslFsTexCol =\n\"struct PS_INPUT { float4 color : COLOR0; float2 uv : TEXCOORD0; };\\n\"\n\"sampler2D Sampler0 : register(s0);\\n\"\n\"float4 main(PS_INPUT input) : COLOR0 {\\n\"\n\" return input.color * tex2D(Sampler0, input.uv);\\n\"\n\"}\\n\";\n\nstatic const char * const glsl_fsCol =\n\"varying vec4 oColor0;\\n\"\n\"void main() { gl_FragColor = oColor0; }\\n\";\n\nstatic const char * const hlslFsCol =\n\"struct PS_INPUT { float4 color : COLOR0; };\\n\"\n\"float4 main(PS_INPUT input) : COLOR0 {\\n\"\n\" return input.color;\\n\"\n\"}\\n\";\n\nstatic const char * const glsl_vsCol =\n\"attribute vec3 Position;\\n\"\n\"attribute vec4 Color0;\\n\"\n\"varying vec4 oColor0;\\n\"\n\"uniform mat4 WorldViewProj;\\n\"\n\"void main() {\\n\"\n\" gl_Position = WorldViewProj * vec4(Position, 1.0);\\n\"\n\" oColor0 = Color0;\\n\"\n\"}\";\n\nstatic const char * const hlslVsCol =\n\"struct VS_INPUT { float3 Position : POSITION; float4 Color0 : COLOR0; };\\n\"\n\"struct VS_OUTPUT { float4 Position : POSITION; float4 Color0 : COLOR0; };\\n\"\n\"float4x4 WorldViewProj;\\n\"\n\"VS_OUTPUT main(VS_INPUT input) {\\n\"\n\" VS_OUTPUT output;\\n\"\n\" output.Position = mul(float4(input.Position, 1.0), WorldViewProj);\\n\"\n\" output.Color0 = input.Color0;\\n\"\n\" return output;\\n\"\n\"}\\n\";\n\nstatic const char * const glsl_vsTexCol =\n\"attribute vec3 Position;\\n\"\n\"attribute vec4 Color0;\\n\"\n\"attribute vec2 TexCoord0;\\n\"\n\"varying vec4 oColor0;\\n\"\n\"varying vec2 oTexCoord0;\\n\"\n\"uniform mat4 WorldViewProj;\\n\"\n\"void main() {\\n\"\n\" gl_Position = WorldViewProj * vec4(Position, 1.0);\\n\"\n\" oColor0 = Color0;\\n\"\n\" oTexCoord0 = TexCoord0;\\n\"\n\"}\\n\";\n\nstatic const char * const hlslVsTexCol =\n\"struct VS_INPUT { float3 Position : POSITION; float2 Texcoord0 : TEXCOORD0; float4 Color0 : COLOR0; };\\n\"\n\"struct VS_OUTPUT { float4 Position : POSITION; float2 Texcoord0 : TEXCOORD0; float4 Color0 : COLOR0; };\\n\"\n\"float4x4 WorldViewProj;\\n\"\n\"VS_OUTPUT main(VS_INPUT input) {\\n\"\n\" VS_OUTPUT output;\\n\"\n\" output.Position = mul(float4(input.Position, 1.0), WorldViewProj);\\n\"\n\" output.Texcoord0 = input.Texcoord0;\\n\"\n\" output.Color0 = input.Color0;\\n\"\n\" return output;\\n\"\n\"}\\n\";\n\nvoid Thin3DContext::CreatePresets() {\n\t\/\/ Build prebuilt objects\n\tT3DBlendStateDesc off = { false };\n\tT3DBlendStateDesc additive = { true, T3DBlendEquation::ADD, T3DBlendFactor::ONE, T3DBlendFactor::ONE, T3DBlendEquation::ADD, T3DBlendFactor::ONE, T3DBlendFactor::ZERO };\n\tT3DBlendStateDesc standard_alpha = { true, T3DBlendEquation::ADD, T3DBlendFactor::SRC_ALPHA, T3DBlendFactor::ONE_MINUS_SRC_ALPHA, T3DBlendEquation::ADD, T3DBlendFactor::ONE, T3DBlendFactor::ZERO };\n\tT3DBlendStateDesc premul_alpha = { true, T3DBlendEquation::ADD, T3DBlendFactor::ONE, T3DBlendFactor::ONE_MINUS_SRC_ALPHA, T3DBlendEquation::ADD, T3DBlendFactor::ONE, T3DBlendFactor::ZERO };\n\n\tbsPresets_[BS_OFF] = CreateBlendState(off);\n\tbsPresets_[BS_ADDITIVE] = CreateBlendState(additive);\n\tbsPresets_[BS_STANDARD_ALPHA] = CreateBlendState(standard_alpha);\n\tbsPresets_[BS_PREMUL_ALPHA] = CreateBlendState(premul_alpha);\n\n\tvsPresets_[VS_TEXTURE_COLOR_2D] = CreateVertexShader(glsl_vsTexCol, hlslVsTexCol);\n\tvsPresets_[VS_COLOR_2D] = CreateVertexShader(glsl_vsCol, hlslVsCol);\n\n\tfsPresets_[FS_TEXTURE_COLOR_2D] = CreateFragmentShader(glsl_fsTexCol, hlslFsTexCol);\n\tfsPresets_[FS_COLOR_2D] = CreateFragmentShader(glsl_fsCol, hlslFsCol);\n\n\tssPresets_[SS_TEXTURE_COLOR_2D] = CreateShaderSet(vsPresets_[VS_TEXTURE_COLOR_2D], fsPresets_[FS_TEXTURE_COLOR_2D]);\n\tssPresets_[SS_COLOR_2D] = CreateShaderSet(vsPresets_[VS_COLOR_2D], fsPresets_[FS_COLOR_2D]);\n}\n\nThin3DContext::~Thin3DContext() {\n\tfor (int i = 0; i < VS_MAX_PRESET; i++) {\n\t\tif (vsPresets_[i]) {\n\t\t\tvsPresets_[i]->Release();\n\t\t}\n\t}\n\tfor (int i = 0; i < FS_MAX_PRESET; i++) {\n\t\tif (fsPresets_[i]) {\n\t\t\tfsPresets_[i]->Release();\n\t\t}\n\t}\n\tfor (int i = 0; i < BS_MAX_PRESET; i++) {\n\t\tif (bsPresets_[i]) {\n\t\t\tbsPresets_[i]->Release();\n\t\t}\n\t}\n\tfor (int i = 0; i < SS_MAX_PRESET; i++) {\n\t\tif (ssPresets_[i]) {\n\t\t\tssPresets_[i]->Release();\n\t\t}\n\t}\n}\n\nstatic T3DImageFormat ZimToT3DFormat(int zim) {\n\tswitch (zim) {\n\tcase ZIM_ETC1: return T3DImageFormat::ETC1;\n\tcase ZIM_RGBA8888: return T3DImageFormat::RGBA8888;\n\tcase ZIM_LUMINANCE: return T3DImageFormat::LUMINANCE;\n\tdefault: return T3DImageFormat::RGBA8888;\n\t}\n}\n\nstatic T3DImageType DetectImageFileType(const uint8_t *data, size_t size) {\n\tif (!memcmp(data, \"ZIMG\", 4)) {\n\t\treturn ZIM;\n\t} else if (!memcmp(data, \"\\x89\\x50\\x4E\\x47\", 4)) {\n\t\treturn PNG;\n\t} else if (!memcmp(data, \"\\xff\\xd8\\xff\\xe0\", 4)) {\n\t\treturn JPEG;\n\t} else {\n\t\treturn TYPE_UNKNOWN;\n\t}\n}\n\nstatic bool LoadTextureLevels(const uint8_t *data, size_t size, T3DImageType type, int width[16], int height[16], int *num_levels, T3DImageFormat *fmt, uint8_t *image[16], int *zim_flags) {\n\tif (type == DETECT) {\n\t\ttype = DetectImageFileType(data, size);\n\t}\n\tif (type == TYPE_UNKNOWN) {\n\t\tELOG(\"File has unknown format\");\n\t\treturn false;\n\t}\n\n\t*num_levels = 0;\n\t*zim_flags = 0;\n\n\tswitch (type) {\n\tcase ZIM:\n\t{\n\t\t*num_levels = LoadZIMPtr((const uint8_t *)data, size, width, height, zim_flags, image);\n\t\t*fmt = ZimToT3DFormat(*zim_flags & ZIM_FORMAT_MASK);\n\t}\n\t\tbreak;\n\n\tcase PNG:\n\t\tif (1 == pngLoadPtr((const unsigned char *)data, size, &width[0], &height[0], &image[0], false)) {\n\t\t\t*num_levels = 1;\n\t\t\t*fmt = RGBA8888;\n\t\t}\n\t\tbreak;\n\n\tcase JPEG:\n\t\t{\n\t\t\tint actual_components = 0;\n\t\t\tunsigned char *jpegBuf = jpgd::decompress_jpeg_image_from_memory(data, (int)size, &width[0], &height[0], &actual_components, 4);\n\t\t\tif (jpegBuf) {\n\t\t\t\t*num_levels = 1;\n\t\t\t\t*fmt = RGBA8888;\n\t\t\t\timage[0] = (uint8_t *)jpegBuf;\n\t\t\t}\n\t\t}\n\t\tbreak;\n\n\tdefault:\n\t\tELOG(\"Unknown image format\");\n\t\treturn false;\n\t}\n\n\treturn *num_levels > 0;\n}\n\nbool Thin3DTexture::LoadFromFileData(const uint8_t *data, size_t dataSize, T3DImageType type) {\n\tint width[16], height[16];\n\tuint8_t *image[16] = { nullptr };\n\n\tint num_levels;\n\tint zim_flags;\n\tT3DImageFormat fmt;\n\n\tif (!LoadTextureLevels(data, dataSize, type, width, height, &num_levels, &fmt, image, &zim_flags)) {\n\t\treturn false;\n\t}\n\n\tCreate(LINEAR2D, fmt, width[0], height[0], 1, num_levels);\n\tfor (int i = 0; i < num_levels; i++) {\n\t\tif (image[i]) {\n\t\t\tSetImageData(0, 0, 0, width[i], height[i], 1, i, width[i] * 4, image[i]);\n\t\t\tfree(image[i]);\n\t\t} else {\n\t\t\tELOG(\"Missing image level %i\", i);\n\t\t}\n\t}\n\n\tFinalize(zim_flags);\n\treturn true;\n}\n\nbool Thin3DTexture::LoadFromFile(const std::string &filename, T3DImageType type) {\n\tfilename_ = \"\";\n\tsize_t fileSize;\n\tuint8_t *buffer = VFSReadFile(filename.c_str(), &fileSize);\n\tif (!buffer) {\n\t\treturn false;\n\t}\n\tbool retval = LoadFromFileData(buffer, fileSize, type);\n\tif (retval) {\n\t\tfilename_ = filename;\n\t} else {\n\t\tELOG(\"%s: Failed to load texture %s\", __FUNCTION__, filename.c_str());\n\t}\n\tdelete[] buffer;\n\treturn retval;\n}\n\nThin3DTexture *Thin3DContext::CreateTextureFromFile(const char *filename, T3DImageType type) {\n\tThin3DTexture *tex = CreateTexture();\n\tif (!tex->LoadFromFile(filename, type)) {\n\t\ttex->Release();\n\t\treturn NULL;\n\t}\n\treturn tex;\n}\n\n\/\/ TODO: Remove the code duplication between this and LoadFromFileData\nThin3DTexture *Thin3DContext::CreateTextureFromFileData(const uint8_t *data, int size, T3DImageType type) {\n\tint width[16], height[16];\n\tint num_levels = 0;\n\tint zim_flags = 0;\n\tT3DImageFormat fmt;\n\tuint8_t *image[16] = { nullptr };\n\n\tif (!LoadTextureLevels(data, size, type, width, height, &num_levels, &fmt, image, &zim_flags)) {\n\t\treturn NULL;\n\t}\n\n\tThin3DTexture *tex = CreateTexture(LINEAR2D, fmt, width[0], height[0], 1, num_levels);\n\tfor (int i = 0; i < num_levels; i++) {\n\t\ttex->SetImageData(0, 0, 0, width[i], height[i], 1, i, width[i] * 4, image[i]);\n\t\tfree(image[i]);\n\t}\n\n\ttex->Finalize(zim_flags);\n\treturn tex;\n}\n<commit_msg>Thin3d preset GLSL shaders: Make them identical to the old GL-only shaders by adding precision qualifiers<commit_after>#include <string.h>\n#include <thin3d\/thin3d.h>\n\n#include \"base\/logging.h\"\n#include \"image\/zim_load.h\"\n#include \"image\/png_load.h\"\n#include \"file\/vfs.h\"\n#include \"ext\/jpge\/jpgd.h\"\n\nstatic const char * const glsl_fsTexCol =\n\"#ifdef GL_ES\\n\"\n\"precision lowp float;\\n\"\n\"#endif\\n\"\n\"varying vec4 oColor0;\\n\"\n\"varying vec2 oTexCoord0;\\n\"\n\"uniform sampler2D Sampler0;\\n\"\n\"void main() { gl_FragColor = texture2D(Sampler0, oTexCoord0) * oColor0; }\\n\";\n\nstatic const char * const hlslFsTexCol =\n\"struct PS_INPUT { float4 color : COLOR0; float2 uv : TEXCOORD0; };\\n\"\n\"sampler2D Sampler0 : register(s0);\\n\"\n\"float4 main(PS_INPUT input) : COLOR0 {\\n\"\n\" return input.color * tex2D(Sampler0, input.uv);\\n\"\n\"}\\n\";\n\nstatic const char * const glsl_fsCol =\n\"#ifdef GL_ES\\n\"\n\"precision lowp float;\\n\"\n\"#endif\\n\"\n\"varying vec4 oColor0;\\n\"\n\"void main() { gl_FragColor = oColor0; }\\n\";\n\nstatic const char * const hlslFsCol =\n\"struct PS_INPUT { float4 color : COLOR0; };\\n\"\n\"float4 main(PS_INPUT input) : COLOR0 {\\n\"\n\" return input.color;\\n\"\n\"}\\n\";\n\nstatic const char * const glsl_vsCol =\n\"attribute vec3 Position;\\n\"\n\"attribute vec4 Color0;\\n\"\n\"varying vec4 oColor0;\\n\"\n\"uniform mat4 WorldViewProj;\\n\"\n\"void main() {\\n\"\n\" gl_Position = WorldViewProj * vec4(Position, 1.0);\\n\"\n\" oColor0 = Color0;\\n\"\n\"}\";\n\nstatic const char * const hlslVsCol =\n\"struct VS_INPUT { float3 Position : POSITION; float4 Color0 : COLOR0; };\\n\"\n\"struct VS_OUTPUT { float4 Position : POSITION; float4 Color0 : COLOR0; };\\n\"\n\"float4x4 WorldViewProj;\\n\"\n\"VS_OUTPUT main(VS_INPUT input) {\\n\"\n\" VS_OUTPUT output;\\n\"\n\" output.Position = mul(float4(input.Position, 1.0), WorldViewProj);\\n\"\n\" output.Color0 = input.Color0;\\n\"\n\" return output;\\n\"\n\"}\\n\";\n\nstatic const char * const glsl_vsTexCol =\n\"attribute vec3 Position;\\n\"\n\"attribute vec4 Color0;\\n\"\n\"attribute vec2 TexCoord0;\\n\"\n\"varying vec4 oColor0;\\n\"\n\"varying vec2 oTexCoord0;\\n\"\n\"uniform mat4 WorldViewProj;\\n\"\n\"void main() {\\n\"\n\" gl_Position = WorldViewProj * vec4(Position, 1.0);\\n\"\n\" oColor0 = Color0;\\n\"\n\" oTexCoord0 = TexCoord0;\\n\"\n\"}\\n\";\n\nstatic const char * const hlslVsTexCol =\n\"struct VS_INPUT { float3 Position : POSITION; float2 Texcoord0 : TEXCOORD0; float4 Color0 : COLOR0; };\\n\"\n\"struct VS_OUTPUT { float4 Position : POSITION; float2 Texcoord0 : TEXCOORD0; float4 Color0 : COLOR0; };\\n\"\n\"float4x4 WorldViewProj;\\n\"\n\"VS_OUTPUT main(VS_INPUT input) {\\n\"\n\" VS_OUTPUT output;\\n\"\n\" output.Position = mul(float4(input.Position, 1.0), WorldViewProj);\\n\"\n\" output.Texcoord0 = input.Texcoord0;\\n\"\n\" output.Color0 = input.Color0;\\n\"\n\" return output;\\n\"\n\"}\\n\";\n\nvoid Thin3DContext::CreatePresets() {\n\t\/\/ Build prebuilt objects\n\tT3DBlendStateDesc off = { false };\n\tT3DBlendStateDesc additive = { true, T3DBlendEquation::ADD, T3DBlendFactor::ONE, T3DBlendFactor::ONE, T3DBlendEquation::ADD, T3DBlendFactor::ONE, T3DBlendFactor::ZERO };\n\tT3DBlendStateDesc standard_alpha = { true, T3DBlendEquation::ADD, T3DBlendFactor::SRC_ALPHA, T3DBlendFactor::ONE_MINUS_SRC_ALPHA, T3DBlendEquation::ADD, T3DBlendFactor::ONE, T3DBlendFactor::ZERO };\n\tT3DBlendStateDesc premul_alpha = { true, T3DBlendEquation::ADD, T3DBlendFactor::ONE, T3DBlendFactor::ONE_MINUS_SRC_ALPHA, T3DBlendEquation::ADD, T3DBlendFactor::ONE, T3DBlendFactor::ZERO };\n\n\tbsPresets_[BS_OFF] = CreateBlendState(off);\n\tbsPresets_[BS_ADDITIVE] = CreateBlendState(additive);\n\tbsPresets_[BS_STANDARD_ALPHA] = CreateBlendState(standard_alpha);\n\tbsPresets_[BS_PREMUL_ALPHA] = CreateBlendState(premul_alpha);\n\n\tvsPresets_[VS_TEXTURE_COLOR_2D] = CreateVertexShader(glsl_vsTexCol, hlslVsTexCol);\n\tvsPresets_[VS_COLOR_2D] = CreateVertexShader(glsl_vsCol, hlslVsCol);\n\n\tfsPresets_[FS_TEXTURE_COLOR_2D] = CreateFragmentShader(glsl_fsTexCol, hlslFsTexCol);\n\tfsPresets_[FS_COLOR_2D] = CreateFragmentShader(glsl_fsCol, hlslFsCol);\n\n\tssPresets_[SS_TEXTURE_COLOR_2D] = CreateShaderSet(vsPresets_[VS_TEXTURE_COLOR_2D], fsPresets_[FS_TEXTURE_COLOR_2D]);\n\tssPresets_[SS_COLOR_2D] = CreateShaderSet(vsPresets_[VS_COLOR_2D], fsPresets_[FS_COLOR_2D]);\n}\n\nThin3DContext::~Thin3DContext() {\n\tfor (int i = 0; i < VS_MAX_PRESET; i++) {\n\t\tif (vsPresets_[i]) {\n\t\t\tvsPresets_[i]->Release();\n\t\t}\n\t}\n\tfor (int i = 0; i < FS_MAX_PRESET; i++) {\n\t\tif (fsPresets_[i]) {\n\t\t\tfsPresets_[i]->Release();\n\t\t}\n\t}\n\tfor (int i = 0; i < BS_MAX_PRESET; i++) {\n\t\tif (bsPresets_[i]) {\n\t\t\tbsPresets_[i]->Release();\n\t\t}\n\t}\n\tfor (int i = 0; i < SS_MAX_PRESET; i++) {\n\t\tif (ssPresets_[i]) {\n\t\t\tssPresets_[i]->Release();\n\t\t}\n\t}\n}\n\nstatic T3DImageFormat ZimToT3DFormat(int zim) {\n\tswitch (zim) {\n\tcase ZIM_ETC1: return T3DImageFormat::ETC1;\n\tcase ZIM_RGBA8888: return T3DImageFormat::RGBA8888;\n\tcase ZIM_LUMINANCE: return T3DImageFormat::LUMINANCE;\n\tdefault: return T3DImageFormat::RGBA8888;\n\t}\n}\n\nstatic T3DImageType DetectImageFileType(const uint8_t *data, size_t size) {\n\tif (!memcmp(data, \"ZIMG\", 4)) {\n\t\treturn ZIM;\n\t} else if (!memcmp(data, \"\\x89\\x50\\x4E\\x47\", 4)) {\n\t\treturn PNG;\n\t} else if (!memcmp(data, \"\\xff\\xd8\\xff\\xe0\", 4)) {\n\t\treturn JPEG;\n\t} else {\n\t\treturn TYPE_UNKNOWN;\n\t}\n}\n\nstatic bool LoadTextureLevels(const uint8_t *data, size_t size, T3DImageType type, int width[16], int height[16], int *num_levels, T3DImageFormat *fmt, uint8_t *image[16], int *zim_flags) {\n\tif (type == DETECT) {\n\t\ttype = DetectImageFileType(data, size);\n\t}\n\tif (type == TYPE_UNKNOWN) {\n\t\tELOG(\"File has unknown format\");\n\t\treturn false;\n\t}\n\n\t*num_levels = 0;\n\t*zim_flags = 0;\n\n\tswitch (type) {\n\tcase ZIM:\n\t{\n\t\t*num_levels = LoadZIMPtr((const uint8_t *)data, size, width, height, zim_flags, image);\n\t\t*fmt = ZimToT3DFormat(*zim_flags & ZIM_FORMAT_MASK);\n\t}\n\t\tbreak;\n\n\tcase PNG:\n\t\tif (1 == pngLoadPtr((const unsigned char *)data, size, &width[0], &height[0], &image[0], false)) {\n\t\t\t*num_levels = 1;\n\t\t\t*fmt = RGBA8888;\n\t\t}\n\t\tbreak;\n\n\tcase JPEG:\n\t\t{\n\t\t\tint actual_components = 0;\n\t\t\tunsigned char *jpegBuf = jpgd::decompress_jpeg_image_from_memory(data, (int)size, &width[0], &height[0], &actual_components, 4);\n\t\t\tif (jpegBuf) {\n\t\t\t\t*num_levels = 1;\n\t\t\t\t*fmt = RGBA8888;\n\t\t\t\timage[0] = (uint8_t *)jpegBuf;\n\t\t\t}\n\t\t}\n\t\tbreak;\n\n\tdefault:\n\t\tELOG(\"Unknown image format\");\n\t\treturn false;\n\t}\n\n\treturn *num_levels > 0;\n}\n\nbool Thin3DTexture::LoadFromFileData(const uint8_t *data, size_t dataSize, T3DImageType type) {\n\tint width[16], height[16];\n\tuint8_t *image[16] = { nullptr };\n\n\tint num_levels;\n\tint zim_flags;\n\tT3DImageFormat fmt;\n\n\tif (!LoadTextureLevels(data, dataSize, type, width, height, &num_levels, &fmt, image, &zim_flags)) {\n\t\treturn false;\n\t}\n\n\tCreate(LINEAR2D, fmt, width[0], height[0], 1, num_levels);\n\tfor (int i = 0; i < num_levels; i++) {\n\t\tif (image[i]) {\n\t\t\tSetImageData(0, 0, 0, width[i], height[i], 1, i, width[i] * 4, image[i]);\n\t\t\tfree(image[i]);\n\t\t} else {\n\t\t\tELOG(\"Missing image level %i\", i);\n\t\t}\n\t}\n\n\tFinalize(zim_flags);\n\treturn true;\n}\n\nbool Thin3DTexture::LoadFromFile(const std::string &filename, T3DImageType type) {\n\tfilename_ = \"\";\n\tsize_t fileSize;\n\tuint8_t *buffer = VFSReadFile(filename.c_str(), &fileSize);\n\tif (!buffer) {\n\t\treturn false;\n\t}\n\tbool retval = LoadFromFileData(buffer, fileSize, type);\n\tif (retval) {\n\t\tfilename_ = filename;\n\t} else {\n\t\tELOG(\"%s: Failed to load texture %s\", __FUNCTION__, filename.c_str());\n\t}\n\tdelete[] buffer;\n\treturn retval;\n}\n\nThin3DTexture *Thin3DContext::CreateTextureFromFile(const char *filename, T3DImageType type) {\n\tThin3DTexture *tex = CreateTexture();\n\tif (!tex->LoadFromFile(filename, type)) {\n\t\ttex->Release();\n\t\treturn NULL;\n\t}\n\treturn tex;\n}\n\n\/\/ TODO: Remove the code duplication between this and LoadFromFileData\nThin3DTexture *Thin3DContext::CreateTextureFromFileData(const uint8_t *data, int size, T3DImageType type) {\n\tint width[16], height[16];\n\tint num_levels = 0;\n\tint zim_flags = 0;\n\tT3DImageFormat fmt;\n\tuint8_t *image[16] = { nullptr };\n\n\tif (!LoadTextureLevels(data, size, type, width, height, &num_levels, &fmt, image, &zim_flags)) {\n\t\treturn NULL;\n\t}\n\n\tThin3DTexture *tex = CreateTexture(LINEAR2D, fmt, width[0], height[0], 1, num_levels);\n\tfor (int i = 0; i < num_levels; i++) {\n\t\ttex->SetImageData(0, 0, 0, width[i], height[i], 1, i, width[i] * 4, image[i]);\n\t\tfree(image[i]);\n\t}\n\n\ttex->Finalize(zim_flags);\n\treturn tex;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ @(#)root\/pyroot:$Id$\n\/\/ Author: Wim Lavrijsen, Apr 2004\n\n\/\/ Bindings\n#include \"PyROOT.h\"\n#include \"ConstructorHolder.h\"\n#include \"Executors.h\"\n#include \"ObjectProxy.h\"\n#include \"MemoryRegulator.h\"\n#include \"Adapters.h\"\n\n\/\/ ROOT\n#include \"TClass.h\"\n#include \"TMethod.h\"\n\n\/\/ Standard\n#include <string>\n\n\n\/\/- protected members --------------------------------------------------------\ntemplate< class T, class M >\nBool_t PyROOT::TConstructorHolder< T, M >::InitExecutor_( TExecutor*& executor )\n{\n\/\/ pick up special case new object executor\n executor = (gExecFactories[ \"__init__\" ])();\n return kTRUE;\n}\n\n\/\/- constructors -------------------------------------------------------------\ntemplate< class T, class M >\nPyROOT::TConstructorHolder< T, M >::TConstructorHolder( const T& klass, const M& method ) :\n TMethodHolder< T, M >( klass, method )\n{\n}\n\n\/\/____________________________________________________________________________\nnamespace PyROOT {\n\ntemplate<>\nTConstructorHolder< TScopeAdapter, TMemberAdapter >::TConstructorHolder( const TScopeAdapter& klass ) :\n TMethodHolder< TScopeAdapter, TMemberAdapter >( klass, (TFunction*)0 )\n{\n}\n\n} \/\/ namespace PyROOT\n\n\/\/- public members -----------------------------------------------------------\ntemplate< class T, class M >\nPyObject* PyROOT::TConstructorHolder< T, M >::GetDocString()\n{\n\/\/ GetMethod() may return an empty function if this is just a special case place holder\n std::string clName = this->GetClass().Name();\n return PyROOT_PyUnicode_FromFormat( \"%s::%s%s\",\n clName.c_str(), clName.c_str(), this->GetMethod() ? this->GetSignatureString().c_str() : \"()\" );\n}\n\n\/\/____________________________________________________________________________\ntemplate< class T, class M >\nPyObject* PyROOT::TConstructorHolder< T, M >::operator()(\n ObjectProxy* self, PyObject* args, PyObject* kwds, Long_t user )\n{\n\/\/ preliminary check in case keywords are accidently used (they are ignored otherwise)\n if ( kwds != 0 && PyDict_Size( kwds ) ) {\n PyErr_SetString( PyExc_TypeError, \"keyword arguments are not yet supported\" );\n return 0;\n }\n\n\/\/ do not allow instantiation of abstract classes\n if ( this->GetClass().IsAbstract() ) {\n PyErr_Format( PyExc_TypeError,\n \"%s is abstract and can not be instantiated\", this->GetClass().Name().c_str() );\n return 0;\n }\n\n\/\/ setup as necessary\n if ( ! this->Initialize() )\n return 0; \/\/ important: 0, not Py_None\n\n\/\/ fetch self, verify, and put the arguments in usable order\n if ( ! ( args = this->FilterArgs( self, args, kwds ) ) )\n return 0;\n\n\/\/ translate the arguments\n if ( ! this->SetMethodArgs( args, user ) ) {\n Py_DECREF( args );\n return 0;\n }\n\n TClass* klass = (TClass*)this->GetClass().Id();\n\n\/\/ perform the call (fails for loaded macro's)\n Long_t address = (Long_t)this->Execute( klass );\n\n\/\/ done with filtered args\n Py_DECREF( args );\n\n\/\/ return object if successful, lament if not\n if ( address != 0 ) {\n Py_INCREF( self );\n\n \/\/ note: constructors are no longer set to take ownership by default; instead that is\n \/\/ decided by the method proxy (which carries a creator flag) upon return\n self->Set( (void*)address );\n\n \/\/ allow lookup upon destruction on the ROOT\/CINT side for TObjects\n TObject* object = (TObject*) klass->DynamicCast( TObject::Class(), (void*)address );\n if ( object )\n TMemoryRegulator::RegisterObject( self, object );\n\n \/\/ done with self\n Py_DECREF( self );\n\n Py_INCREF( Py_None );\n return Py_None; \/\/ by definition\n }\n\n if ( ! PyErr_Occurred() ) \/\/ should be set, otherwise write a generic error msg\n PyErr_SetString( PyExc_TypeError, const_cast< char* >(\n ( std::string( klass->GetName() ) + \" constructor failed\" ).c_str() ) );\n\n\/\/ do not throw an exception, '0' might trigger the overload handler to choose a\n\/\/ different constructor, which if all fails will throw an exception\n return 0;\n}\n\n\/\/____________________________________________________________________________\ntemplate class PyROOT::TConstructorHolder< PyROOT::TScopeAdapter, PyROOT::TMemberAdapter >;\n<commit_msg>change in who allocates memory for newly constructed objects<commit_after>\/\/ @(#)root\/pyroot:$Id$\n\/\/ Author: Wim Lavrijsen, Apr 2004\n\n\/\/ Bindings\n#include \"PyROOT.h\"\n#include \"ConstructorHolder.h\"\n#include \"Executors.h\"\n#include \"ObjectProxy.h\"\n#include \"MemoryRegulator.h\"\n#include \"Adapters.h\"\n\n\/\/ ROOT\n#include \"TClass.h\"\n#include \"TMethod.h\"\n\n\/\/ Standard\n#include <string>\n\n\n\/\/- protected members --------------------------------------------------------\ntemplate< class T, class M >\nBool_t PyROOT::TConstructorHolder< T, M >::InitExecutor_( TExecutor*& executor )\n{\n\/\/ pick up special case new object executor\n executor = (gExecFactories[ \"__init__\" ])();\n return kTRUE;\n}\n\n\/\/- constructors -------------------------------------------------------------\ntemplate< class T, class M >\nPyROOT::TConstructorHolder< T, M >::TConstructorHolder( const T& klass, const M& method ) :\n TMethodHolder< T, M >( klass, method )\n{\n}\n\n\/\/____________________________________________________________________________\nnamespace PyROOT {\n\ntemplate<>\nTConstructorHolder< TScopeAdapter, TMemberAdapter >::TConstructorHolder( const TScopeAdapter& klass ) :\n TMethodHolder< TScopeAdapter, TMemberAdapter >( klass, (TFunction*)0 )\n{\n}\n\n} \/\/ namespace PyROOT\n\n\/\/- public members -----------------------------------------------------------\ntemplate< class T, class M >\nPyObject* PyROOT::TConstructorHolder< T, M >::GetDocString()\n{\n\/\/ GetMethod() may return an empty function if this is just a special case place holder\n std::string clName = this->GetClass().Name();\n return PyROOT_PyUnicode_FromFormat( \"%s::%s%s\",\n clName.c_str(), clName.c_str(), this->GetMethod() ? this->GetSignatureString().c_str() : \"()\" );\n}\n\n\/\/____________________________________________________________________________\ntemplate< class T, class M >\nPyObject* PyROOT::TConstructorHolder< T, M >::operator()(\n ObjectProxy* self, PyObject* args, PyObject* kwds, Long_t user )\n{\n\/\/ preliminary check in case keywords are accidently used (they are ignored otherwise)\n if ( kwds != 0 && PyDict_Size( kwds ) ) {\n PyErr_SetString( PyExc_TypeError, \"keyword arguments are not yet supported\" );\n return 0;\n }\n\n\/\/ do not allow instantiation of abstract classes\n if ( this->GetClass().IsAbstract() ) {\n PyErr_Format( PyExc_TypeError,\n \"%s is abstract and can not be instantiated\", this->GetClass().Name().c_str() );\n return 0;\n }\n\n\/\/ setup as necessary\n if ( ! this->Initialize() )\n return 0; \/\/ important: 0, not Py_None\n\n\/\/ fetch self, verify, and put the arguments in usable order\n if ( ! ( args = this->FilterArgs( self, args, kwds ) ) )\n return 0;\n\n\/\/ translate the arguments\n if ( ! this->SetMethodArgs( args, user ) ) {\n Py_DECREF( args );\n return 0;\n }\n\n TClass* klass = (TClass*)this->GetClass().Id();\n\n\/\/ perform the call, 0 makes the other side allocate the memory\n Long_t address = (Long_t)this->Execute( 0 );\n\n\/\/ done with filtered args\n Py_DECREF( args );\n\n\/\/ return object if successful, lament if not\n if ( address != 0 ) {\n Py_INCREF( self );\n\n \/\/ note: constructors are no longer set to take ownership by default; instead that is\n \/\/ decided by the method proxy (which carries a creator flag) upon return\n self->Set( (void*)address );\n\n \/\/ allow lookup upon destruction on the ROOT\/CINT side for TObjects\n TObject* object = (TObject*) klass->DynamicCast( TObject::Class(), (void*)address );\n if ( object )\n TMemoryRegulator::RegisterObject( self, object );\n\n \/\/ done with self\n Py_DECREF( self );\n\n Py_INCREF( Py_None );\n return Py_None; \/\/ by definition\n }\n\n if ( ! PyErr_Occurred() ) \/\/ should be set, otherwise write a generic error msg\n PyErr_SetString( PyExc_TypeError, const_cast< char* >(\n ( std::string( klass->GetName() ) + \" constructor failed\" ).c_str() ) );\n\n\/\/ do not throw an exception, '0' might trigger the overload handler to choose a\n\/\/ different constructor, which if all fails will throw an exception\n return 0;\n}\n\n\/\/____________________________________________________________________________\ntemplate class PyROOT::TConstructorHolder< PyROOT::TScopeAdapter, PyROOT::TMemberAdapter >;\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ Copyright (c) 2009, Zbigniew Zagorski\n\/\/ This software licensed under terms described in LICENSE.txt\n\/\/\n\n#include \"option.h\"\n\n#include \"tinfra\/tstring.h\"\n#include \"tinfra\/trace.h\"\n\n#include <ostream>\n#include <cstdlib>\n\nnamespace tinfra {\n\n\/\/\n\/\/ option_base\n\/\/\n\nconst char option_base::NO_SWITCH = 0;\n \noption_base::option_base()\n{\n option_registry::get().add(this);\n}\n\noption_base::option_base(option_list& ol)\n{\n ol.add(this);\n}\n\noption_base::~option_base()\n{\n}\n\n\/\/\n\/\/ option_impl\n\/\/\n\noption_impl::option_impl(option_list& ol,char switch_letter, std::string const& name, std::string const& synopsis):\n option_base(ol),\n switch_letter(switch_letter),\n name(name),\n synopsis(synopsis)\n{\n}\n\noption_impl::option_impl(option_list& ol,std::string const& name, std::string const& synopsis):\n option_base(ol),\n switch_letter(NO_SWITCH),\n name(name),\n synopsis(synopsis)\n{\n}\n\noption_impl::option_impl(char switch_letter, std::string const& name, std::string const& synopsis):\n switch_letter(switch_letter),\n name(name),\n synopsis(synopsis)\n{\n}\n\noption_impl::option_impl(std::string const& name, std::string const& synopsis):\n switch_letter(NO_SWITCH),\n name(name),\n synopsis(synopsis)\n{\n}\n\nchar option_impl::get_switch_letter() const\n{\n return switch_letter;\n}\nstd::string option_impl::get_name() const\n{\n return name;\n}\n\nstd::string option_impl::get_synopsis() const\n{\n return synopsis;\n}\n\n\/\/\n\/\/ option_switch\n\/\/\n\nvoid option_switch::accept(tstring const& input)\n{\n if( input.size() == 0 ) {\n this->value_ = !default_value();\n } else if( input == \"yes\" ||\n input == \"y\" ||\n input == \"1\") {\n this->value_ = true;\n } else {\n this->value_ = false;\n }\n accepted_ = true;\n}\n\/\/\n\/\/ option_list\n\/\/\n\nvoid option_list::add(option_base* opt)\n{\n options.push_back(opt);\n}\n\nvoid remove_params(std::vector<tstring>& from_where, unsigned pos, unsigned how_many = 1)\n{\n assert(pos + how_many <= from_where.size());\n \n std::vector<tstring>::iterator remove_begin = from_where.begin()+pos;\n std::vector<tstring>::iterator remove_end = from_where.begin()+pos + how_many;\n from_where.erase(remove_begin, remove_end); \n}\n\nvoid option_list::parse(std::vector<tstring>& params)\n{\n unsigned i = 0;\n while( i < params.size()) {\n tstring current = params[i];\n if( current.size() < 2 ) {\n i+=1;\n continue;\n }\n\n tstring option_name;\n tstring option_value;\n bool argument_present;\n option_base* opt;\n if( std::strncmp(current.data(), \"--\", 2) == 0 ) {\n if( current.size() == 2 ) {\n remove_params(params,i,1);\n \/\/ -- is an end of parameters\n break;\n }\n \n \/\/ parse only long style, gnu-like options (--foo-bar, --foo-bar=AAA, --foo-bar AAA)\n current = current.substr(2);\n \n size_t eq_pos = current.find_first_of('=');\n argument_present = (eq_pos != tstring::npos);\n if( argument_present ) {\n \/\/ and option=argument pair\n option_name = current.substr(0,eq_pos);\n option_value = current.substr(eq_pos+1);\n } else {\n \/\/ only option, no argument\n option_name = current;\n }\n opt = find_by_name(option_name);\n } else if( current[0] == '-' ) {\n \/\/ parse short options:\n \/\/ -I\n \/\/ -Iparam\n \/\/ -I param\n const char shortcut = current[1];\n \n option_value = current.substr(2);\n argument_present = (option_value.size() != 0);\n opt = find_by_shortcut(shortcut);\n\t} else {\n i+=1;\n continue;\n }\n \n int arguments_eaten = 1;\n \n if( opt == 0 ) {\n \/\/ ignore unknown option\n \/\/ TODO, invent other strategy for unknown options\n i+=1;\n continue;\n }\n \n if( opt->needs_argument() ) {\n if( !argument_present ) {\n if( i == params.size() - 1 ) {\n \/\/ we need argument but are at last element, so \n \/\/ throw!\n assert(false);\n throw;\n }\n option_value = params[i+1];\n arguments_eaten += 1;\n }\n \n opt->accept(option_value);\n } else {\n if( argument_present ) \n opt->accept(option_value);\n else\n opt->accept(\"\");\n }\n remove_params(params, i, arguments_eaten);\n }\n}\n\nvoid option_list::print_help(tinfra::output_stream& out)\n{\n std::ostringstream tmp;\n for(option_list_t::const_iterator i = options.begin(); i != options.end(); ++i) \n {\n const option_base* opt = *i;\n tmp << \" \";\n \n \n \/\/ TODO:\n \/\/ switch_letter is not yet supported so don't show it to user\n \/*\n const char switch_letter = opt->get_switch_letter();\n if( switch_letter != option_base::NO_SWITCH )\n out << \"-\" << switch_letter << \", \";\n *\/\n \n tmp << \"--\" << opt->get_name();\n if( opt->needs_argument() ) {\n tmp << \" ARG\";\n }\n \n tmp << \"\\t\" << opt->get_synopsis() << \"\\n\";\n }\n out.write(tmp.str());\n}\noption_base* option_list::find_by_name(tstring const& name)\n{\n for(option_list_t::const_iterator i = options.begin(); i != options.end(); ++i) \n {\n option_base* opt = *i;\n \n if( name == opt->get_name() ) \n return opt;\n \n \/\/ TODO: add - and _ insensitive search\n }\n return 0;\n}\n\noption_base* option_list::find_by_shortcut(char shortcut)\n{\n for(option_list_t::const_iterator i = options.begin(); i != options.end(); ++i) \n {\n option_base* opt = *i;\n \n if( shortcut == opt->get_switch_letter() ) \n return opt;\n }\n return 0;\n}\n\noption_list::option_list_t option_list::get_options()\n{\n return options;\n}\n\n\/\/\n\/\/ option_registry\n\/\/\nstatic option_list* default_option_list = 0;\nstatic void delete_default_option_list()\n{\n delete default_option_list;\n}\n\noption_list& option_registry::get()\n{\n if( default_option_list == 0 ) {\n default_option_list = new option_list();\n std::atexit(delete_default_option_list);\n }\n return *default_option_list;\n}\n\n} \/\/ end namespace tinfra\n\n\/\/ jedit: :tabSize=8:indentSize=4:noTabs=true:mode=c++:\n\n<commit_msg>option_list::print_help(): show also short versions of options<commit_after>\/\/\n\/\/ Copyright (c) 2009, Zbigniew Zagorski\n\/\/ This software licensed under terms described in LICENSE.txt\n\/\/\n\n#include \"option.h\"\n\n#include \"tinfra\/tstring.h\"\n#include \"tinfra\/trace.h\"\n\n#include <cstdlib>\n\nnamespace tinfra {\n\n\/\/\n\/\/ option_base\n\/\/\n\nconst char option_base::NO_SWITCH = 0;\n \noption_base::option_base()\n{\n option_registry::get().add(this);\n}\n\noption_base::option_base(option_list& ol)\n{\n ol.add(this);\n}\n\noption_base::~option_base()\n{\n}\n\n\/\/\n\/\/ option_impl\n\/\/\n\noption_impl::option_impl(option_list& ol,char switch_letter, std::string const& name, std::string const& synopsis):\n option_base(ol),\n switch_letter(switch_letter),\n name(name),\n synopsis(synopsis)\n{\n}\n\noption_impl::option_impl(option_list& ol,std::string const& name, std::string const& synopsis):\n option_base(ol),\n switch_letter(NO_SWITCH),\n name(name),\n synopsis(synopsis)\n{\n}\n\noption_impl::option_impl(char switch_letter, std::string const& name, std::string const& synopsis):\n switch_letter(switch_letter),\n name(name),\n synopsis(synopsis)\n{\n}\n\noption_impl::option_impl(std::string const& name, std::string const& synopsis):\n switch_letter(NO_SWITCH),\n name(name),\n synopsis(synopsis)\n{\n}\n\nchar option_impl::get_switch_letter() const\n{\n return switch_letter;\n}\nstd::string option_impl::get_name() const\n{\n return name;\n}\n\nstd::string option_impl::get_synopsis() const\n{\n return synopsis;\n}\n\n\/\/\n\/\/ option_switch\n\/\/\n\nvoid option_switch::accept(tstring const& input)\n{\n if( input.size() == 0 ) {\n this->value_ = !default_value();\n } else if( input == \"yes\" ||\n input == \"y\" ||\n input == \"1\") {\n this->value_ = true;\n } else {\n this->value_ = false;\n }\n accepted_ = true;\n}\n\/\/\n\/\/ option_list\n\/\/\n\nvoid option_list::add(option_base* opt)\n{\n options.push_back(opt);\n}\n\nvoid remove_params(std::vector<tstring>& from_where, unsigned pos, unsigned how_many = 1)\n{\n assert(pos + how_many <= from_where.size());\n \n std::vector<tstring>::iterator remove_begin = from_where.begin()+pos;\n std::vector<tstring>::iterator remove_end = from_where.begin()+pos + how_many;\n from_where.erase(remove_begin, remove_end); \n}\n\nvoid option_list::parse(std::vector<tstring>& params)\n{\n unsigned i = 0;\n while( i < params.size()) {\n tstring current = params[i];\n if( current.size() < 2 ) {\n i+=1;\n continue;\n }\n\n tstring option_name;\n tstring option_value;\n bool argument_present;\n option_base* opt;\n if( std::strncmp(current.data(), \"--\", 2) == 0 ) {\n if( current.size() == 2 ) {\n remove_params(params,i,1);\n \/\/ -- is an end of parameters\n break;\n }\n \n \/\/ parse only long style, gnu-like options (--foo-bar, --foo-bar=AAA, --foo-bar AAA)\n current = current.substr(2);\n \n size_t eq_pos = current.find_first_of('=');\n argument_present = (eq_pos != tstring::npos);\n if( argument_present ) {\n \/\/ and option=argument pair\n option_name = current.substr(0,eq_pos);\n option_value = current.substr(eq_pos+1);\n } else {\n \/\/ only option, no argument\n option_name = current;\n }\n opt = find_by_name(option_name);\n } else if( current[0] == '-' ) {\n \/\/ parse short options:\n \/\/ -I\n \/\/ -Iparam\n \/\/ -I param\n const char shortcut = current[1];\n \n option_value = current.substr(2);\n argument_present = (option_value.size() != 0);\n opt = find_by_shortcut(shortcut);\n\t} else {\n i+=1;\n continue;\n }\n \n int arguments_eaten = 1;\n \n if( opt == 0 ) {\n \/\/ ignore unknown option\n \/\/ TODO, invent other strategy for unknown options\n i+=1;\n continue;\n }\n \n if( opt->needs_argument() ) {\n if( !argument_present ) {\n if( i == params.size() - 1 ) {\n \/\/ we need argument but are at last element, so \n \/\/ throw!\n assert(false);\n throw;\n }\n option_value = params[i+1];\n arguments_eaten += 1;\n }\n \n opt->accept(option_value);\n } else {\n if( argument_present ) \n opt->accept(option_value);\n else\n opt->accept(\"\");\n }\n remove_params(params, i, arguments_eaten);\n }\n}\n\nvoid option_list::print_help(tinfra::output_stream& out)\n{\n std::ostringstream tmp;\n for(option_list_t::const_iterator i = options.begin(); i != options.end(); ++i) \n {\n const option_base* opt = *i;\n tmp << \" \";\n \n const char switch_letter = opt->get_switch_letter();\n if( switch_letter != option_base::NO_SWITCH )\n tmp << \"-\" << switch_letter << \", \";\n \n \n tmp << \"--\" << opt->get_name();\n if( opt->needs_argument() ) {\n tmp << \" ARG\";\n }\n \n tmp << \"\\t\" << opt->get_synopsis() << \"\\n\";\n }\n out.write(tmp.str());\n}\noption_base* option_list::find_by_name(tstring const& name)\n{\n for(option_list_t::const_iterator i = options.begin(); i != options.end(); ++i) \n {\n option_base* opt = *i;\n \n if( name == opt->get_name() ) \n return opt;\n \n \/\/ TODO: add - and _ insensitive search\n }\n return 0;\n}\n\noption_base* option_list::find_by_shortcut(char shortcut)\n{\n for(option_list_t::const_iterator i = options.begin(); i != options.end(); ++i) \n {\n option_base* opt = *i;\n \n if( shortcut == opt->get_switch_letter() ) \n return opt;\n }\n return 0;\n}\n\noption_list::option_list_t option_list::get_options()\n{\n return options;\n}\n\n\/\/\n\/\/ option_registry\n\/\/\nstatic option_list* default_option_list = 0;\nstatic void delete_default_option_list()\n{\n delete default_option_list;\n}\n\noption_list& option_registry::get()\n{\n if( default_option_list == 0 ) {\n default_option_list = new option_list();\n std::atexit(delete_default_option_list);\n }\n return *default_option_list;\n}\n\n} \/\/ end namespace tinfra\n\n\/\/ jedit: :tabSize=8:indentSize=4:noTabs=true:mode=c++:\n\n<|endoftext|>"} {"text":"<commit_before>\/*=========================================================================\n\n Program: Insight Segmentation & Registration Toolkit\n Module: itkDecoratorTest.cxx\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n Copyright (c) Insight Software Consortium. All rights reserved.\n See ITKCopyright.txt or http:\/\/www.itk.org\/HTML\/Copyright.htm for details.\n\n This software is distributed WITHOUT ANY WARRANTY; without even \n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR \n PURPOSE. See the above copyright notices for more information.\n\n=========================================================================*\/\n#if defined(_MSC_VER)\n#pragma warning ( disable : 4786 )\n#endif\n\n#include <iostream>\n#include \"itkVector.h\"\n#include \"itkAffineTransform.h\"\n#include \"itkSimpleDataObjectDecorator.h\"\n#include \"itkDataObjectDecorator.h\"\n#include \"itkAutoPointerDataObjectDecorator.h\"\n\n\/\/ Problems with gcc 2.95. Temporary workaround\n#if !(defined(__GNUC__) && __GNUC__ <= 2)\n#define OK\n#endif\n\n#ifdef OK\nnamespace {\ntemplate <class charT, class traits, class T, class A>\nstd::basic_ostream<charT, traits>&\noperator<<(std::basic_ostream<charT, traits>&os, const std::vector<T,A> &p) \n{\n os << \"vector<\" << typeid(T).name() << \"> with \" << p.size() << \" elements \" << std::endl;\n return os;\n}\n}\n#endif\n\nint itkDecoratorTest(int, char* [] )\n{\n int status = 0;\n\n std::cout << \"----------------------------------------------------\"\n << std::endl;\n \n typedef itk::SimpleDataObjectDecorator<float> FloatObjectType;\n\n FloatObjectType::Pointer f = FloatObjectType::New();\n f->Set(5.0);\n\n std::cout << \"Value of f: \" << f->Get() << std::endl;\n std::cout << \"FloatDataObject: \" << f << std::endl;\n\n std::cout << \"----------------------------------------------------\"\n << std::endl;\n\n typedef itk::AffineTransform<double, 3> TransformType;\n typedef itk::DataObjectDecorator<TransformType> TransformObjectType;\n\n TransformObjectType::Pointer decoratedTransform = TransformObjectType::New();\n TransformType * transformObject = TransformType::New();\n const TransformType * constTransformObject = transformObject;\n\n transformObject->Scale( 5.0 );\n\n decoratedTransform->Set( constTransformObject );\n \n std::cout << \"Value of decoratedTransform: \";\n decoratedTransform->Get()->Print(std::cout);\n std::cout << \"TransformDataObject: \" << decoratedTransform;\n\n std::cout << \"----------------------------------------------------\"\n << std::endl;\n\n typedef std::vector<float> VectorType;\n typedef VectorType* VectorPointer;\n typedef itk::SimpleDataObjectDecorator<VectorType> VectorObjectType;\n typedef itk::AutoPointerDataObjectDecorator<VectorType> VectorPointerObjectType;\n\n VectorType v;\n v.resize(5);\n#ifdef OK\n std::cout << v << std::endl;\n#endif \n VectorObjectType::Pointer vo = VectorObjectType::New();\n vo->Set(v);\n#ifdef OK\n std::cout << vo;\n#endif\n std::cout << \"----------------------------------------------------\"\n << std::endl;\n\n \/\/ The following code block will NOT cause a memory leak because the\n \/\/ ownership of the dynamically allocated memory is passed to the\n \/\/ AutoPointerDataObjectDecorator \n {\n VectorPointer vp;\n vp = new VectorType;\n vp->resize(3);\n#ifdef OK\n std::cout << *vp << std::endl;\n#endif\n\n VectorPointerObjectType::Pointer vop = VectorPointerObjectType::New();\n vop->Set(vp);\n\n#ifdef OK\n std::cout << vop;\n#endif\n }\n\n std::cout << \"----------------------------------------------------\"\n << std::endl;\n\n \/\/ The following code block will cause a memory leak because the\n \/\/ decorator does not deallocate the memory that was passed in on a\n \/\/ pointer. The AutoPointerDataObjectDecorator does delete the memory.\n \/\/typedef itk::SimpleDataObjectDecorator<VectorPointer> VectorPointerObjectType2;\n \/\/{\n \/\/VectorPointer vp2;\n \/\/vp2 = new VectorType;\n \/\/vp2->resize(4);\n \/\/std::cout << *vp2 << std::endl;\n \n \/\/VectorPointerObjectType2::Pointer vop2 = VectorPointerObjectType2::New();\n \/\/vop2->Set(vp2);\n\n \/\/std::cout << vop2;\n \/\/}\n\n return status;\n}\n<commit_msg>BUG: Transform object was not being assigned to a SmartPointer after its construction from a New() operator call.<commit_after>\/*=========================================================================\n\n Program: Insight Segmentation & Registration Toolkit\n Module: itkDecoratorTest.cxx\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n Copyright (c) Insight Software Consortium. All rights reserved.\n See ITKCopyright.txt or http:\/\/www.itk.org\/HTML\/Copyright.htm for details.\n\n This software is distributed WITHOUT ANY WARRANTY; without even \n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR \n PURPOSE. See the above copyright notices for more information.\n\n=========================================================================*\/\n#if defined(_MSC_VER)\n#pragma warning ( disable : 4786 )\n#endif\n\n#include <iostream>\n#include \"itkVector.h\"\n#include \"itkAffineTransform.h\"\n#include \"itkSimpleDataObjectDecorator.h\"\n#include \"itkDataObjectDecorator.h\"\n#include \"itkAutoPointerDataObjectDecorator.h\"\n\n\/\/ Problems with gcc 2.95. Temporary workaround\n#if !(defined(__GNUC__) && __GNUC__ <= 2)\n#define OK\n#endif\n\n#ifdef OK\nnamespace {\ntemplate <class charT, class traits, class T, class A>\nstd::basic_ostream<charT, traits>&\noperator<<(std::basic_ostream<charT, traits>&os, const std::vector<T,A> &p) \n{\n os << \"vector<\" << typeid(T).name() << \"> with \" << p.size() << \" elements \" << std::endl;\n return os;\n}\n}\n#endif\n\nint itkDecoratorTest(int, char* [] )\n{\n int status = 0;\n\n std::cout << \"----------------------------------------------------\"\n << std::endl;\n \n typedef itk::SimpleDataObjectDecorator<float> FloatObjectType;\n\n FloatObjectType::Pointer f = FloatObjectType::New();\n f->Set(5.0);\n\n std::cout << \"Value of f: \" << f->Get() << std::endl;\n std::cout << \"FloatDataObject: \" << f << std::endl;\n\n std::cout << \"----------------------------------------------------\"\n << std::endl;\n\n typedef itk::AffineTransform<double, 3> TransformType;\n typedef itk::DataObjectDecorator<TransformType> TransformObjectType;\n\n TransformObjectType::Pointer decoratedTransform = TransformObjectType::New();\n TransformType::Pointer transformObject = TransformType::New();\n const TransformType * constTransformObject = transformObject;\n\n transformObject->Scale( 5.0 );\n\n decoratedTransform->Set( constTransformObject );\n \n std::cout << \"Value of decoratedTransform: \";\n decoratedTransform->Get()->Print(std::cout);\n std::cout << \"TransformDataObject: \" << decoratedTransform;\n\n std::cout << \"----------------------------------------------------\"\n << std::endl;\n\n typedef std::vector<float> VectorType;\n typedef VectorType* VectorPointer;\n typedef itk::SimpleDataObjectDecorator<VectorType> VectorObjectType;\n typedef itk::AutoPointerDataObjectDecorator<VectorType> VectorPointerObjectType;\n\n VectorType v;\n v.resize(5);\n#ifdef OK\n std::cout << v << std::endl;\n#endif \n VectorObjectType::Pointer vo = VectorObjectType::New();\n vo->Set(v);\n#ifdef OK\n std::cout << vo;\n#endif\n std::cout << \"----------------------------------------------------\"\n << std::endl;\n\n \/\/ The following code block will NOT cause a memory leak because the\n \/\/ ownership of the dynamically allocated memory is passed to the\n \/\/ AutoPointerDataObjectDecorator \n {\n VectorPointer vp;\n vp = new VectorType;\n vp->resize(3);\n#ifdef OK\n std::cout << *vp << std::endl;\n#endif\n\n VectorPointerObjectType::Pointer vop = VectorPointerObjectType::New();\n vop->Set(vp);\n\n#ifdef OK\n std::cout << vop;\n#endif\n }\n\n std::cout << \"----------------------------------------------------\"\n << std::endl;\n\n \/\/ The following code block will cause a memory leak because the\n \/\/ decorator does not deallocate the memory that was passed in on a\n \/\/ pointer. The AutoPointerDataObjectDecorator does delete the memory.\n \/\/typedef itk::SimpleDataObjectDecorator<VectorPointer> VectorPointerObjectType2;\n \/\/{\n \/\/VectorPointer vp2;\n \/\/vp2 = new VectorType;\n \/\/vp2->resize(4);\n \/\/std::cout << *vp2 << std::endl;\n \n \/\/VectorPointerObjectType2::Pointer vop2 = VectorPointerObjectType2::New();\n \/\/vop2->Set(vp2);\n\n \/\/std::cout << vop2;\n \/\/}\n\n return status;\n}\n<|endoftext|>"} {"text":"<commit_before>\/***********************************************************************\n created: 20th February 2010\n author: Lukas E Meindl\n \n purpose: Implementation of the class used to provide conversions\n between the ColourPicker colour types\n*************************************************************************\/\n\/***************************************************************************\n* Copyright (C) 2004 - 2010 Paul D Turner & The CEGUI Development Team\n*\n* Permission is hereby granted, free of charge, to any person obtaining\n* a copy of this software and associated documentation files (the\n* \"Software\"), to deal in the Software without restriction, including\n* without limitation the rights to use, copy, modify, merge, publish,\n* distribute, sublicense, and\/or sell copies of the Software, and to\n* permit persons to whom the Software is furnished to do so, subject to\n* the following conditions:\n*\n* The above copyright notice and this permission notice shall be\n* included in all copies or substantial portions of the Software.\n*\n* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\n* IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR\n* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,\n* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\n* OTHER DEALINGS IN THE SOFTWARE.\n***************************************************************************\/\n#include \"CEGUI\/CommonDialogs\/ColourPicker\/Conversions.h\"\n#include <math.h>\n#include <algorithm>\n\nnamespace CEGUI\n{\n\n\/\/----------------------------------------------------------------------------\/\/\nconst float ColourPickerConversions::Xn(0.95047f);\nconst float ColourPickerConversions::Yn(1.00000f);\nconst float ColourPickerConversions::Zn(1.08883f);\n\nconst float ColourPickerConversions::LAB_COMPARE_VALUE_CONST(0.00885645167903563081717167575546f);\n\n\/\/----------------------------------------------------------------------------\/\/\nvoid ColourPickerConversions::clamp(float& value, float min_val, float max_val)\n{\n value = value < min_val ? min_val : (value > max_val ? max_val : value);\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nfloat ColourPickerConversions::toX(unsigned char R, unsigned char G, unsigned char B)\n{\n return toX(R \/ 255.0f, G \/ 255.0f, B \/ 255.0f);\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nfloat ColourPickerConversions::toY(unsigned char R, unsigned char G, unsigned char B)\n{\n return toY(R \/ 255.0f, G \/ 255.0f, B \/ 255.0f);\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nfloat ColourPickerConversions::toZ(unsigned char R, unsigned char G, unsigned char B)\n{\n return toZ(R \/ 255.0f, G \/ 255.0f, B \/ 255.0f);\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nfloat ColourPickerConversions::toX(float R, float G, float B)\n{\n return (0.4124564f * R + 0.3575761f * G + 0.1804375f * B);\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nfloat ColourPickerConversions::toY(float R, float G, float B)\n{\n return (0.2126729f * R + 0.7151522f * G + 0.0721750f * B);\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nfloat ColourPickerConversions::toZ(float R, float G, float B)\n{\n return (0.0193339f * R + 0.1191920f * G + 0.9503041f * B);\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nfloat ColourPickerConversions::toL(float Y)\n{\n return (116.0f * YNormCalc(Y) - 16.0f);\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nfloat ColourPickerConversions::toA(float X, float Y)\n{\n return (500.0f * (XNormCalc(X) - YNormCalc(Y)));\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nfloat ColourPickerConversions::toB(float Y, float Z)\n{\n return (200.0f * (YNormCalc(Y) - ZNormCalc(Z)));\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nfloat ColourPickerConversions::XNormCalc(float X)\n{\n float div = (X \/ Xn);\n return normCalc(div);\n\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nfloat ColourPickerConversions::YNormCalc(float Y)\n{\n float div = (Y \/ Yn);\n return normCalc(div);\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nfloat ColourPickerConversions::ZNormCalc(float Z)\n{\n float div = (Z \/ Zn);\n return normCalc(div);\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nfloat ColourPickerConversions::normCalc(float div)\n{\n if (div < LAB_COMPARE_VALUE_CONST)\n return ((24389.0f \/ 27.0f * div + 16.0f) \/ 116.0f);\n else\n return pow(div, 1.0f \/ 3.0f);\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nRGB_Colour ColourPickerConversions::toRGB(const Lab_Colour& colour)\n{\n return toRGB(colour.L, colour.a, colour.b);\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nRGB_Colour ColourPickerConversions::toRGB(float L, float a, float b)\n{\n float vy = (L + 16.0f) \/ 116.0f;\n float vx = a \/ 500.0f + vy;\n float vz = vy - b \/ 200.0f;\n\n {\n float vx3 = pow(vx, 3);\n float vy3 = pow(vy, 3);\n float vz3 = pow(vz, 3);\n\n if (vy3 > LAB_COMPARE_VALUE_CONST)\n vy = vy3;\n else\n vy = (vy - 16.0f \/ 116.0f) \/ 7.787f;\n\n if (vx3 > LAB_COMPARE_VALUE_CONST)\n vx = vx3;\n else\n vx = (vx - 16.0f \/ 116.0f) \/ 7.787f;\n\n if (vz3 > LAB_COMPARE_VALUE_CONST)\n vz = vz3;\n else\n vz = (vz - 16.0f \/ 116.0f) \/ 7.787f;\n }\n\n vx *= Xn;\n vz *= Zn;\n\n float vr = vx * 3.2406f + vy * -1.5372f + vz * -0.4986f;\n float vg = vx * -0.9689f + vy * 1.8758f + vz * 0.0415f;\n float vb = vx * 0.0557f + vy * -0.2040f + vz * 1.0570f;\n\n clamp(vr, 0.0f, 1.0f);\n clamp(vg, 0.0f, 1.0f);\n clamp(vb, 0.0f, 1.0f);\n\n return RGB_Colour(static_cast<unsigned char>(255.0f * vr),\n static_cast<unsigned char>(255.0f * vg),\n static_cast<unsigned char>(255.0f * vb));\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nRGB_Colour ColourPickerConversions::toRGB(const CEGUI::Colour& colour)\n{\n return RGB_Colour(static_cast<unsigned char>(colour.getRed() * 255.0f),\n static_cast<unsigned char>(colour.getGreen() * 255.0f),\n static_cast<unsigned char>(colour.getBlue() * 255.0f));\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nCEGUI::Colour ColourPickerConversions::toCeguiColour(const RGB_Colour& colourRGB)\n{\n return CEGUI::Colour(colourRGB.r \/ 255.0f,\n colourRGB.g \/ 255.0f,\n colourRGB.b \/ 255.0f);\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nRGB_Colour ColourPickerConversions::linearInterpolationRGB(float interPolBalance,\n const RGB_Colour& start,\n const RGB_Colour& end)\n{\n RGB_Colour colour;\n\n clampInterpolationValue(interPolBalance);\n\n colour.r = static_cast<unsigned char>(\n (1 - interPolBalance) * start.r + (interPolBalance * end.r));\n colour.g = static_cast<unsigned char>(\n (1 - interPolBalance) * start.g + (interPolBalance * end.g));\n colour.b = static_cast<unsigned char>(\n (1 - interPolBalance) * start.b + (interPolBalance * end.b));\n\n return colour;\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nLab_Colour ColourPickerConversions::linearInterpolationLab(float interPolBalance,\n const Lab_Colour& start,\n const Lab_Colour& end)\n{\n Lab_Colour colour;\n\n clampInterpolationValue(interPolBalance);\n\n colour.L = (1 - interPolBalance) * start.L + (interPolBalance * end.L);\n colour.a = (1 - interPolBalance) * start.a + (interPolBalance * end.a);\n colour.b = (1 - interPolBalance) * start.b + (interPolBalance * end.b);\n\n return colour;\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nHSV_Colour ColourPickerConversions::linearInterpolationHSV(float interPolBalance,\n const HSV_Colour& start,\n const HSV_Colour& end)\n{\n HSV_Colour colour;\n\n clampInterpolationValue(interPolBalance);\n\n colour.H = (1 - interPolBalance) * start.H + (interPolBalance * end.H);\n colour.S = (1 - interPolBalance) * start.S + (interPolBalance * end.S);\n colour.V = (1 - interPolBalance) * start.V + (interPolBalance * end.V);\n\n return colour;\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nunsigned char ColourPickerConversions::linearInterpolationAlpha(float interPolBalance,\n unsigned char startAlpha,\n unsigned char endAlpha)\n{\n clampInterpolationValue(interPolBalance);\n\n return static_cast<unsigned char>(\n (1 - interPolBalance) * startAlpha + (interPolBalance * endAlpha));\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nvoid ColourPickerConversions::clampInterpolationValue(float& interPolBalance)\n{\n interPolBalance = std::max(0.0f, interPolBalance);\n interPolBalance = std::min(1.0f, interPolBalance);\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nRGB_Colour ColourPickerConversions::toRGB(const HSV_Colour& colour)\n{\n float r = 0.0f;\n float g = 0.0f;\n float b = 0.0f;\n\n int i = (int)(colour.H * 6.0f);\n float f = colour.H * 6 - i;\n float p = colour.V * (1 - colour.S);\n float q = colour.V * (1 - f * colour.S);\n float t = colour.V * (1 - (1 - f) * colour.S);\n\n switch (i % 6)\n {\n case 0:\n r = colour.V;\n g = t;\n b = p;\n break;\n\n case 1:\n r = q;\n g = colour.V;\n b = p;\n break;\n\n case 2:\n r = p;\n g = colour.V;\n b = t;\n break;\n\n case 3:\n r = p;\n g = q;\n b = colour.V;\n break;\n\n case 4:\n r = t;\n g = p;\n b = colour.V;\n break;\n\n case 5:\n r = colour.V;\n g = p;\n b = q;\n break;\n }\n\n return RGB_Colour(static_cast<unsigned char>(r * 255),\n static_cast<unsigned char>(g * 255),\n static_cast<unsigned char>(b * 255));\n}\n\/\/----------------------------------------------------------------------------\/\/\n\nLab_Colour ColourPickerConversions::toLab(RGB_Colour colour)\n{\n float X = toX(colour.r, colour.g, colour.b);\n float Y = toY(colour.r, colour.g, colour.b);\n float Z = toZ(colour.r, colour.g, colour.b);\n\n float L = toL(Y);\n float a = toA(X, Y);\n float b = toB(Y, Z);\n\n return Lab_Colour(L, a, b);\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nHSV_Colour ColourPickerConversions::toHSV(RGB_Colour colour)\n{\n float r = colour.r \/ 255.0f;\n float g = colour.g \/ 255.0f;\n float b = colour.b \/ 255.0f;\n\n bool maxCompRed = false;\n bool maxCompGreen = false;\n float max_comp = b;\n\n if(r > g && r > b)\n {\n maxCompRed = true;\n max_comp = r;\n }\n else if(g > b)\n {\n maxCompGreen = true;\n max_comp = g;\n }\n\n float min_comp = ceguimin(ceguimin(r, g), b);\n float h;\n float s;\n float v = max_comp;\n\n float diff = max_comp - min_comp;\n s = (max_comp == 0.0f ? 0.0f : diff \/ max_comp);\n\n if (max_comp == min_comp)\n {\n h = 0; \/\/ achromatic\n }\n else\n {\n if (maxCompRed)\n h = (g - b) \/ diff + (g < b ? 6.0f : 0.0f);\n\n if (maxCompGreen)\n h = (b - r) \/ diff + 2.0f;\n\n else\n h = (r - g) \/ diff + 4.0f;\n\n h \/= 6.0f;\n }\n\n return HSV_Colour(h, s, v);\n}\n\n\/\/----------------------------------------------------------------------------\/\/\n\n}\n\n<commit_msg>MOD: Fixed a small HSV conversion bug<commit_after>\/***********************************************************************\n created: 20th February 2010\n author: Lukas E Meindl\n \n purpose: Implementation of the class used to provide conversions\n between the ColourPicker colour types\n*************************************************************************\/\n\/***************************************************************************\n* Copyright (C) 2004 - 2010 Paul D Turner & The CEGUI Development Team\n*\n* Permission is hereby granted, free of charge, to any person obtaining\n* a copy of this software and associated documentation files (the\n* \"Software\"), to deal in the Software without restriction, including\n* without limitation the rights to use, copy, modify, merge, publish,\n* distribute, sublicense, and\/or sell copies of the Software, and to\n* permit persons to whom the Software is furnished to do so, subject to\n* the following conditions:\n*\n* The above copyright notice and this permission notice shall be\n* included in all copies or substantial portions of the Software.\n*\n* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\n* IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR\n* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,\n* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\n* OTHER DEALINGS IN THE SOFTWARE.\n***************************************************************************\/\n#include \"CEGUI\/CommonDialogs\/ColourPicker\/Conversions.h\"\n#include <math.h>\n#include <algorithm>\n\nnamespace CEGUI\n{\n\n\/\/----------------------------------------------------------------------------\/\/\nconst float ColourPickerConversions::Xn(0.95047f);\nconst float ColourPickerConversions::Yn(1.00000f);\nconst float ColourPickerConversions::Zn(1.08883f);\n\nconst float ColourPickerConversions::LAB_COMPARE_VALUE_CONST(0.00885645167903563081717167575546f);\n\n\/\/----------------------------------------------------------------------------\/\/\nvoid ColourPickerConversions::clamp(float& value, float min_val, float max_val)\n{\n value = value < min_val ? min_val : (value > max_val ? max_val : value);\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nfloat ColourPickerConversions::toX(unsigned char R, unsigned char G, unsigned char B)\n{\n return toX(R \/ 255.0f, G \/ 255.0f, B \/ 255.0f);\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nfloat ColourPickerConversions::toY(unsigned char R, unsigned char G, unsigned char B)\n{\n return toY(R \/ 255.0f, G \/ 255.0f, B \/ 255.0f);\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nfloat ColourPickerConversions::toZ(unsigned char R, unsigned char G, unsigned char B)\n{\n return toZ(R \/ 255.0f, G \/ 255.0f, B \/ 255.0f);\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nfloat ColourPickerConversions::toX(float R, float G, float B)\n{\n return (0.4124564f * R + 0.3575761f * G + 0.1804375f * B);\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nfloat ColourPickerConversions::toY(float R, float G, float B)\n{\n return (0.2126729f * R + 0.7151522f * G + 0.0721750f * B);\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nfloat ColourPickerConversions::toZ(float R, float G, float B)\n{\n return (0.0193339f * R + 0.1191920f * G + 0.9503041f * B);\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nfloat ColourPickerConversions::toL(float Y)\n{\n return (116.0f * YNormCalc(Y) - 16.0f);\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nfloat ColourPickerConversions::toA(float X, float Y)\n{\n return (500.0f * (XNormCalc(X) - YNormCalc(Y)));\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nfloat ColourPickerConversions::toB(float Y, float Z)\n{\n return (200.0f * (YNormCalc(Y) - ZNormCalc(Z)));\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nfloat ColourPickerConversions::XNormCalc(float X)\n{\n float div = (X \/ Xn);\n return normCalc(div);\n\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nfloat ColourPickerConversions::YNormCalc(float Y)\n{\n float div = (Y \/ Yn);\n return normCalc(div);\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nfloat ColourPickerConversions::ZNormCalc(float Z)\n{\n float div = (Z \/ Zn);\n return normCalc(div);\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nfloat ColourPickerConversions::normCalc(float div)\n{\n if (div < LAB_COMPARE_VALUE_CONST)\n return ((24389.0f \/ 27.0f * div + 16.0f) \/ 116.0f);\n else\n return pow(div, 1.0f \/ 3.0f);\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nRGB_Colour ColourPickerConversions::toRGB(const Lab_Colour& colour)\n{\n return toRGB(colour.L, colour.a, colour.b);\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nRGB_Colour ColourPickerConversions::toRGB(float L, float a, float b)\n{\n float vy = (L + 16.0f) \/ 116.0f;\n float vx = a \/ 500.0f + vy;\n float vz = vy - b \/ 200.0f;\n\n {\n float vx3 = pow(vx, 3);\n float vy3 = pow(vy, 3);\n float vz3 = pow(vz, 3);\n\n if (vy3 > LAB_COMPARE_VALUE_CONST)\n vy = vy3;\n else\n vy = (vy - 16.0f \/ 116.0f) \/ 7.787f;\n\n if (vx3 > LAB_COMPARE_VALUE_CONST)\n vx = vx3;\n else\n vx = (vx - 16.0f \/ 116.0f) \/ 7.787f;\n\n if (vz3 > LAB_COMPARE_VALUE_CONST)\n vz = vz3;\n else\n vz = (vz - 16.0f \/ 116.0f) \/ 7.787f;\n }\n\n vx *= Xn;\n vz *= Zn;\n\n float vr = vx * 3.2406f + vy * -1.5372f + vz * -0.4986f;\n float vg = vx * -0.9689f + vy * 1.8758f + vz * 0.0415f;\n float vb = vx * 0.0557f + vy * -0.2040f + vz * 1.0570f;\n\n clamp(vr, 0.0f, 1.0f);\n clamp(vg, 0.0f, 1.0f);\n clamp(vb, 0.0f, 1.0f);\n\n return RGB_Colour(static_cast<unsigned char>(255.0f * vr),\n static_cast<unsigned char>(255.0f * vg),\n static_cast<unsigned char>(255.0f * vb));\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nRGB_Colour ColourPickerConversions::toRGB(const CEGUI::Colour& colour)\n{\n return RGB_Colour(static_cast<unsigned char>(colour.getRed() * 255.0f),\n static_cast<unsigned char>(colour.getGreen() * 255.0f),\n static_cast<unsigned char>(colour.getBlue() * 255.0f));\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nCEGUI::Colour ColourPickerConversions::toCeguiColour(const RGB_Colour& colourRGB)\n{\n return CEGUI::Colour(colourRGB.r \/ 255.0f,\n colourRGB.g \/ 255.0f,\n colourRGB.b \/ 255.0f);\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nRGB_Colour ColourPickerConversions::linearInterpolationRGB(float interPolBalance,\n const RGB_Colour& start,\n const RGB_Colour& end)\n{\n RGB_Colour colour;\n\n clampInterpolationValue(interPolBalance);\n\n colour.r = static_cast<unsigned char>(\n (1 - interPolBalance) * start.r + (interPolBalance * end.r));\n colour.g = static_cast<unsigned char>(\n (1 - interPolBalance) * start.g + (interPolBalance * end.g));\n colour.b = static_cast<unsigned char>(\n (1 - interPolBalance) * start.b + (interPolBalance * end.b));\n\n return colour;\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nLab_Colour ColourPickerConversions::linearInterpolationLab(float interPolBalance,\n const Lab_Colour& start,\n const Lab_Colour& end)\n{\n Lab_Colour colour;\n\n clampInterpolationValue(interPolBalance);\n\n colour.L = (1 - interPolBalance) * start.L + (interPolBalance * end.L);\n colour.a = (1 - interPolBalance) * start.a + (interPolBalance * end.a);\n colour.b = (1 - interPolBalance) * start.b + (interPolBalance * end.b);\n\n return colour;\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nHSV_Colour ColourPickerConversions::linearInterpolationHSV(float interPolBalance,\n const HSV_Colour& start,\n const HSV_Colour& end)\n{\n HSV_Colour colour;\n\n clampInterpolationValue(interPolBalance);\n\n colour.H = (1 - interPolBalance) * start.H + (interPolBalance * end.H);\n colour.S = (1 - interPolBalance) * start.S + (interPolBalance * end.S);\n colour.V = (1 - interPolBalance) * start.V + (interPolBalance * end.V);\n\n return colour;\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nunsigned char ColourPickerConversions::linearInterpolationAlpha(float interPolBalance,\n unsigned char startAlpha,\n unsigned char endAlpha)\n{\n clampInterpolationValue(interPolBalance);\n\n return static_cast<unsigned char>(\n (1 - interPolBalance) * startAlpha + (interPolBalance * endAlpha));\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nvoid ColourPickerConversions::clampInterpolationValue(float& interPolBalance)\n{\n interPolBalance = std::max(0.0f, interPolBalance);\n interPolBalance = std::min(1.0f, interPolBalance);\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nRGB_Colour ColourPickerConversions::toRGB(const HSV_Colour& colour)\n{\n float r = 0.0f;\n float g = 0.0f;\n float b = 0.0f;\n\n int i = (int)(colour.H * 6.0f);\n float f = colour.H * 6 - i;\n float p = colour.V * (1 - colour.S);\n float q = colour.V * (1 - f * colour.S);\n float t = colour.V * (1 - (1 - f) * colour.S);\n\n switch (i % 6)\n {\n case 0:\n r = colour.V;\n g = t;\n b = p;\n break;\n\n case 1:\n r = q;\n g = colour.V;\n b = p;\n break;\n\n case 2:\n r = p;\n g = colour.V;\n b = t;\n break;\n\n case 3:\n r = p;\n g = q;\n b = colour.V;\n break;\n\n case 4:\n r = t;\n g = p;\n b = colour.V;\n break;\n\n case 5:\n r = colour.V;\n g = p;\n b = q;\n break;\n }\n\n return RGB_Colour(static_cast<unsigned char>(r * 255),\n static_cast<unsigned char>(g * 255),\n static_cast<unsigned char>(b * 255));\n}\n\/\/----------------------------------------------------------------------------\/\/\n\nLab_Colour ColourPickerConversions::toLab(RGB_Colour colour)\n{\n float X = toX(colour.r, colour.g, colour.b);\n float Y = toY(colour.r, colour.g, colour.b);\n float Z = toZ(colour.r, colour.g, colour.b);\n\n float L = toL(Y);\n float a = toA(X, Y);\n float b = toB(Y, Z);\n\n return Lab_Colour(L, a, b);\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nHSV_Colour ColourPickerConversions::toHSV(RGB_Colour colour)\n{\n float r = colour.r \/ 255.0f;\n float g = colour.g \/ 255.0f;\n float b = colour.b \/ 255.0f;\n\n bool maxCompRed = false;\n bool maxCompGreen = false;\n float max_comp = b;\n\n if(r > g && r > b)\n {\n maxCompRed = true;\n max_comp = r;\n }\n else if(g > b)\n {\n maxCompGreen = true;\n max_comp = g;\n }\n\n float min_comp = ceguimin(ceguimin(r, g), b);\n float h;\n float s;\n float v = max_comp;\n\n float diff = max_comp - min_comp;\n s = (max_comp == 0.0f ? 0.0f : diff \/ max_comp);\n\n if (max_comp == min_comp)\n {\n h = 0; \/\/ achromatic\n }\n else\n {\n if (maxCompRed)\n {\n h = (g - b) \/ diff + (g < b ? 6.0f : 0.0f);\n }\n else if (maxCompGreen)\n {\n h = (b - r) \/ diff + 2.0f;\n }\n else\n {\n h = (r - g) \/ diff + 4.0f;\n }\n\n h \/= 6.0f;\n }\n\n return HSV_Colour(h, s, v);\n}\n\n\/\/----------------------------------------------------------------------------\/\/\n\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/*=========================================================================\n\n Program: ORFEO Toolbox\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n\n Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.\n See OTBCopyright.txt for details.\n\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notices for more information.\n\n=========================================================================*\/\n\n#include \"otbWrapperApplicationRegistry.h\"\n\nint main(int argc,char* argv[])\n{\n using otb::Wrapper::ApplicationRegistry;\n using otb::Wrapper::Application;\n \n if (argc != 5)\n {\n std::cout << \"Usage: 0000478-UncaughtException app_module_path stereo_ref stereo_sec output_file\" << std::endl;\n return 1;\n }\n \n ApplicationRegistry::SetApplicationPath(argv[1]);\n Application::Pointer myApp = ApplicationRegistry::CreateApplication(\"StereoSensorModelToElevationMap\");\n \n if (myApp.IsNull())\n {\n std::cout << \"Application not created\" << std::endl;\n return 1;\n }\n \n myApp->Init();\n \n myApp->SetParameterString(\"ref\", argv[2]);\n myApp->SetParameterString(\"sec\", argv[3]);\n myApp->SetParameterString(\"out\", argv[4]);\n myApp->SetParameterString(\"elev\",\"dem\");\n myApp->SetParameterString(\"elev.dem.path\", \"FAKE_DEM_PATH\");\n myApp->SetParameterString(\"elev.dem.geoid\", \"FAKE_GEOID_PATH\");\n \n std::cout << \"Try-catch section\" << std::endl;\n try\n {\n myApp->ExecuteAndWriteOutput();\n }\n catch(...)\n {\n std::cerr << \"An unknown exception has been caught !\" << std::endl;\n }\n \n return 0;\n}\n<commit_msg>TEST: Fixing test code following elevation management refactoring<commit_after>\/*=========================================================================\n\n Program: ORFEO Toolbox\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n\n Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.\n See OTBCopyright.txt for details.\n\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notices for more information.\n\n=========================================================================*\/\n\n#include \"otbWrapperApplicationRegistry.h\"\n\nint main(int argc,char* argv[])\n{\n using otb::Wrapper::ApplicationRegistry;\n using otb::Wrapper::Application;\n \n if (argc != 5)\n {\n std::cout << \"Usage: 0000478-UncaughtException app_module_path stereo_ref stereo_sec output_file\" << std::endl;\n return 1;\n }\n \n ApplicationRegistry::SetApplicationPath(argv[1]);\n Application::Pointer myApp = ApplicationRegistry::CreateApplication(\"StereoSensorModelToElevationMap\");\n \n if (myApp.IsNull())\n {\n std::cout << \"Application not created\" << std::endl;\n return 1;\n }\n \n myApp->Init();\n \n myApp->SetParameterString(\"ref\", argv[2]);\n myApp->SetParameterString(\"sec\", argv[3]);\n myApp->SetParameterString(\"out\", argv[4]);\n myApp->SetParameterString(\"elev.dem\", \"FAKE_DEM_PATH\");\n myApp->SetParameterString(\"elev.geoid\", \"FAKE_GEOID_PATH\");\n \n std::cout << \"Try-catch section\" << std::endl;\n try\n {\n myApp->ExecuteAndWriteOutput();\n }\n catch(...)\n {\n std::cerr << \"An unknown exception has been caught !\" << std::endl;\n }\n \n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: urp_marshal.cxx,v $\n *\n * $Revision: 1.5 $\n *\n * last change: $Author: rt $ $Date: 2005-09-07 22:47:17 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n#include <string.h>\n#include <osl\/diagnose.h>\n#include <rtl\/alloc.h>\n\n#include <uno\/any2.h>\n#include <uno\/sequence2.h>\n\n#include \"urp_marshal.hxx\"\n\nusing namespace ::rtl;\n\nusing namespace ::com::sun::star::uno;\n\nnamespace bridges_urp {\n\nstatic int g_nDetectLittleEndian = 1;\nchar g_bMarshalSystemIsLittleEndian = ((char*)&g_nDetectLittleEndian)[0];\n\nMarshal::Marshal( urp_BridgeImpl *pBridgeImpl,\n sal_Int32 nBufferSize,\n urp_extractOidCallback callback) :\n m_nBufferSize( nBufferSize ),\n m_base( (sal_Int8*)rtl_allocateMemory( nBufferSize ) ),\n m_pos( m_base + 2*sizeof( sal_Int32 ) ),\n m_pBridgeImpl( pBridgeImpl ),\n m_callback( callback )\n{}\n\nMarshal::~Marshal( )\n{\n rtl_freeMemory( m_base );\n}\n\nvoid Marshal::packOid( const ::rtl::OUString & oid )\n{\n sal_uInt16 nIndex;\n if( oid.getLength() )\n {\n nIndex = m_pBridgeImpl->m_oidCacheOut.seek( oid );\n if( 0xffff == nIndex )\n {\n nIndex = m_pBridgeImpl->m_oidCacheOut.put( oid );\n packString( (void*)(&oid.pData) );\n }\n else\n {\n OUString dummy;\n packString( &dummy );\n }\n }\n else\n {\n \/\/ null reference\n nIndex = 0xffff;\n OUString dummy;\n packString( &dummy );\n }\n packInt16( &nIndex );\n}\n\nvoid Marshal::packTid( const ByteSequence & threadId, sal_Bool bIgnoreCache )\n{\n\n sal_uInt16 nIndex = 0xffff;\n if( ! bIgnoreCache )\n {\n nIndex = m_pBridgeImpl->m_tidCacheOut.seek( threadId );\n }\n\n if( 0xffff == nIndex )\n {\n if( ! bIgnoreCache )\n {\n nIndex = m_pBridgeImpl->m_tidCacheOut.put( threadId );\n }\n packByteSequence( (sal_Int8*) threadId.getConstArray() ,threadId.getLength());\n }\n else\n {\n packByteSequence( 0 , 0 );\n }\n packInt16( &nIndex );\n}\n\n\nvoid Marshal::packType( void *pSource )\n{\n typelib_TypeDescriptionReference *pRef =\n *(typelib_TypeDescriptionReference ** ) pSource;\n\n OSL_ASSERT( pRef );\n\n sal_uInt8 nTypeClass = ( sal_uInt8 ) pRef->eTypeClass;\n\n if( nTypeClass <= \/* any*\/ 14 )\n {\n packInt8( (sal_Int8*)&nTypeClass );\n }\n else\n {\n OUString sTypeName;\n sal_uInt16 nIndex = 0xffff;\n\n nIndex = m_pBridgeImpl->m_typeCacheOut.seek( *(Type*)&pRef );\n if( 0xffff == nIndex )\n {\n \/\/ put it into the cache\n nIndex = m_pBridgeImpl->m_typeCacheOut.put( *(Type*)&pRef );\n sTypeName = pRef->pTypeName;\n nTypeClass = nTypeClass | 0x80;\n }\n packInt8( &nTypeClass );\n packInt16( &nIndex );\n if( 0x80 & nTypeClass )\n {\n packString( &sTypeName );\n }\n }\n}\n\nsal_Bool Marshal::packRecursive( void *pSource , typelib_TypeDescription *pType )\n{\n sal_Bool bSuccess = sal_True;\n switch( pType->eTypeClass )\n {\n case typelib_TypeClass_EXCEPTION:\n case typelib_TypeClass_STRUCT:\n {\n typelib_CompoundTypeDescription * pCompType = (typelib_CompoundTypeDescription*)pType;\n\n if (pCompType->pBaseTypeDescription)\n {\n bSuccess = pack( pSource , (typelib_TypeDescription*) pCompType->pBaseTypeDescription );\n }\n\n \/\/ then construct members\n typelib_TypeDescriptionReference ** ppTypeRefs = pCompType->ppTypeRefs;\n sal_Int32 * pMemberOffsets = pCompType->pMemberOffsets;\n sal_Int32 nDescr = pCompType->nMembers;\n\n for ( sal_Int32 nPos = 0; nPos < nDescr; ++nPos )\n {\n typelib_TypeDescription * pMemberType = 0;\n TYPELIB_DANGER_GET( &pMemberType, ppTypeRefs[nPos] );\n if( pMemberType )\n {\n bSuccess = bSuccess && pack( (char*)pSource + pMemberOffsets[nPos] , pMemberType );\n TYPELIB_DANGER_RELEASE( pMemberType );\n }\n else\n {\n OUStringBuffer buf( 64 );\n buf.appendAscii( RTL_CONSTASCII_STRINGPARAM(\"Couldn't get typedescription for type \"));\n buf.append( ppTypeRefs[nPos]->pTypeName );\n m_pBridgeImpl->addError( buf.makeStringAndClear() );\n bSuccess = sal_False;\n }\n }\n break;\n }\n case typelib_TypeClass_SEQUENCE:\n {\n typelib_IndirectTypeDescription *pIndirectType =\n ( typelib_IndirectTypeDescription* ) pType;\n\n const sal_Int32 nElements = (*(uno_Sequence **)pSource)->nElements;\n char * pSourceElements = (char *)(*(uno_Sequence **)pSource)->elements;\n\n if( typelib_TypeClass_BYTE == pIndirectType->pType->eTypeClass )\n {\n \/\/ Byte sequences are optimized\n packByteSequence( (sal_Int8*)pSourceElements , nElements );\n }\n else\n {\n typelib_TypeDescription *pElementType = 0;\n TYPELIB_DANGER_GET( &pElementType, pIndirectType->pType );\n if( pElementType )\n {\n const sal_Int32 nElementSize = pElementType->nSize;\n\n packCompressedSize( nElements );\n for ( sal_Int32 i = 0 ; i < nElements; i++ )\n {\n bSuccess = bSuccess && pack( pSourceElements + (nElementSize*i) , pElementType );\n }\n TYPELIB_DANGER_RELEASE( pElementType );\n }\n else\n {\n bSuccess = sal_False;\n OUStringBuffer buf( 64 );\n buf.appendAscii( RTL_CONSTASCII_STRINGPARAM(\"Couldn't get typedescription for type \"));\n buf.append( pIndirectType->pType->pTypeName );\n m_pBridgeImpl->addError( buf.makeStringAndClear() );\n }\n }\n break;\n }\n default:\n OSL_ASSERT( 0 );\n }\n return bSuccess;\n}\n\n} \/\/ end namespace bridges\n<commit_msg>INTEGRATION: CWS pchfix02 (1.5.70); FILE MERGED 2006\/09\/01 17:17:42 kaib 1.5.70.1: #i68856# Added header markers and pch files<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: urp_marshal.cxx,v $\n *\n * $Revision: 1.6 $\n *\n * last change: $Author: obo $ $Date: 2006-09-16 16:01:41 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_bridges.hxx\"\n#include <string.h>\n#include <osl\/diagnose.h>\n#include <rtl\/alloc.h>\n\n#include <uno\/any2.h>\n#include <uno\/sequence2.h>\n\n#include \"urp_marshal.hxx\"\n\nusing namespace ::rtl;\n\nusing namespace ::com::sun::star::uno;\n\nnamespace bridges_urp {\n\nstatic int g_nDetectLittleEndian = 1;\nchar g_bMarshalSystemIsLittleEndian = ((char*)&g_nDetectLittleEndian)[0];\n\nMarshal::Marshal( urp_BridgeImpl *pBridgeImpl,\n sal_Int32 nBufferSize,\n urp_extractOidCallback callback) :\n m_nBufferSize( nBufferSize ),\n m_base( (sal_Int8*)rtl_allocateMemory( nBufferSize ) ),\n m_pos( m_base + 2*sizeof( sal_Int32 ) ),\n m_pBridgeImpl( pBridgeImpl ),\n m_callback( callback )\n{}\n\nMarshal::~Marshal( )\n{\n rtl_freeMemory( m_base );\n}\n\nvoid Marshal::packOid( const ::rtl::OUString & oid )\n{\n sal_uInt16 nIndex;\n if( oid.getLength() )\n {\n nIndex = m_pBridgeImpl->m_oidCacheOut.seek( oid );\n if( 0xffff == nIndex )\n {\n nIndex = m_pBridgeImpl->m_oidCacheOut.put( oid );\n packString( (void*)(&oid.pData) );\n }\n else\n {\n OUString dummy;\n packString( &dummy );\n }\n }\n else\n {\n \/\/ null reference\n nIndex = 0xffff;\n OUString dummy;\n packString( &dummy );\n }\n packInt16( &nIndex );\n}\n\nvoid Marshal::packTid( const ByteSequence & threadId, sal_Bool bIgnoreCache )\n{\n\n sal_uInt16 nIndex = 0xffff;\n if( ! bIgnoreCache )\n {\n nIndex = m_pBridgeImpl->m_tidCacheOut.seek( threadId );\n }\n\n if( 0xffff == nIndex )\n {\n if( ! bIgnoreCache )\n {\n nIndex = m_pBridgeImpl->m_tidCacheOut.put( threadId );\n }\n packByteSequence( (sal_Int8*) threadId.getConstArray() ,threadId.getLength());\n }\n else\n {\n packByteSequence( 0 , 0 );\n }\n packInt16( &nIndex );\n}\n\n\nvoid Marshal::packType( void *pSource )\n{\n typelib_TypeDescriptionReference *pRef =\n *(typelib_TypeDescriptionReference ** ) pSource;\n\n OSL_ASSERT( pRef );\n\n sal_uInt8 nTypeClass = ( sal_uInt8 ) pRef->eTypeClass;\n\n if( nTypeClass <= \/* any*\/ 14 )\n {\n packInt8( (sal_Int8*)&nTypeClass );\n }\n else\n {\n OUString sTypeName;\n sal_uInt16 nIndex = 0xffff;\n\n nIndex = m_pBridgeImpl->m_typeCacheOut.seek( *(Type*)&pRef );\n if( 0xffff == nIndex )\n {\n \/\/ put it into the cache\n nIndex = m_pBridgeImpl->m_typeCacheOut.put( *(Type*)&pRef );\n sTypeName = pRef->pTypeName;\n nTypeClass = nTypeClass | 0x80;\n }\n packInt8( &nTypeClass );\n packInt16( &nIndex );\n if( 0x80 & nTypeClass )\n {\n packString( &sTypeName );\n }\n }\n}\n\nsal_Bool Marshal::packRecursive( void *pSource , typelib_TypeDescription *pType )\n{\n sal_Bool bSuccess = sal_True;\n switch( pType->eTypeClass )\n {\n case typelib_TypeClass_EXCEPTION:\n case typelib_TypeClass_STRUCT:\n {\n typelib_CompoundTypeDescription * pCompType = (typelib_CompoundTypeDescription*)pType;\n\n if (pCompType->pBaseTypeDescription)\n {\n bSuccess = pack( pSource , (typelib_TypeDescription*) pCompType->pBaseTypeDescription );\n }\n\n \/\/ then construct members\n typelib_TypeDescriptionReference ** ppTypeRefs = pCompType->ppTypeRefs;\n sal_Int32 * pMemberOffsets = pCompType->pMemberOffsets;\n sal_Int32 nDescr = pCompType->nMembers;\n\n for ( sal_Int32 nPos = 0; nPos < nDescr; ++nPos )\n {\n typelib_TypeDescription * pMemberType = 0;\n TYPELIB_DANGER_GET( &pMemberType, ppTypeRefs[nPos] );\n if( pMemberType )\n {\n bSuccess = bSuccess && pack( (char*)pSource + pMemberOffsets[nPos] , pMemberType );\n TYPELIB_DANGER_RELEASE( pMemberType );\n }\n else\n {\n OUStringBuffer buf( 64 );\n buf.appendAscii( RTL_CONSTASCII_STRINGPARAM(\"Couldn't get typedescription for type \"));\n buf.append( ppTypeRefs[nPos]->pTypeName );\n m_pBridgeImpl->addError( buf.makeStringAndClear() );\n bSuccess = sal_False;\n }\n }\n break;\n }\n case typelib_TypeClass_SEQUENCE:\n {\n typelib_IndirectTypeDescription *pIndirectType =\n ( typelib_IndirectTypeDescription* ) pType;\n\n const sal_Int32 nElements = (*(uno_Sequence **)pSource)->nElements;\n char * pSourceElements = (char *)(*(uno_Sequence **)pSource)->elements;\n\n if( typelib_TypeClass_BYTE == pIndirectType->pType->eTypeClass )\n {\n \/\/ Byte sequences are optimized\n packByteSequence( (sal_Int8*)pSourceElements , nElements );\n }\n else\n {\n typelib_TypeDescription *pElementType = 0;\n TYPELIB_DANGER_GET( &pElementType, pIndirectType->pType );\n if( pElementType )\n {\n const sal_Int32 nElementSize = pElementType->nSize;\n\n packCompressedSize( nElements );\n for ( sal_Int32 i = 0 ; i < nElements; i++ )\n {\n bSuccess = bSuccess && pack( pSourceElements + (nElementSize*i) , pElementType );\n }\n TYPELIB_DANGER_RELEASE( pElementType );\n }\n else\n {\n bSuccess = sal_False;\n OUStringBuffer buf( 64 );\n buf.appendAscii( RTL_CONSTASCII_STRINGPARAM(\"Couldn't get typedescription for type \"));\n buf.append( pIndirectType->pType->pTypeName );\n m_pBridgeImpl->addError( buf.makeStringAndClear() );\n }\n }\n break;\n }\n default:\n OSL_ASSERT( 0 );\n }\n return bSuccess;\n}\n\n} \/\/ end namespace bridges\n<|endoftext|>"} {"text":"<commit_before>\/*\n-----------------------------------------------------------------------------\nThis source file is part of OGRE\n(Object-oriented Graphics Rendering Engine)\nFor the latest info, see http:\/\/www.ogre3d.org\/\n\nCopyright (c) 2000-2014 Torus Knot Software Ltd\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n-----------------------------------------------------------------------------\n*\/\n#include \"Ogre.h\"\n#include \"RootWithoutRenderSystemFixture.h\"\n#include \"OgreShaderGenerator.h\"\n#include \"OgreShaderProgramManager.h\"\n\n#include \"OgreShaderFFPTransform.h\"\n#include \"OgreShaderFFPColour.h\"\n\nusing namespace Ogre;\n\nstruct RTShaderSystem : public RootWithoutRenderSystemFixture\n{\n std::unique_ptr<GpuProgramManager> gpuProgMgr;\n\n void SetUp()\n {\n RootWithoutRenderSystemFixture::SetUp();\n gpuProgMgr.reset(new GpuProgramManager());\n\n RTShader::ShaderGenerator::initialize();\n RTShader::ShaderGenerator::getSingleton().setTargetLanguage(\"glsl\");\n }\n void TearDown()\n {\n RTShader::ShaderGenerator::destroy();\n gpuProgMgr.reset();\n RootWithoutRenderSystemFixture::TearDown();\n }\n};\n\nTEST_F(RTShaderSystem, createShaderBasedTechnique)\n{\n auto& shaderGen = RTShader::ShaderGenerator::getSingleton();\n auto mat = MaterialManager::getSingleton().create(\"TestMat\", RGN_DEFAULT);\n\n EXPECT_TRUE(shaderGen.createShaderBasedTechnique(mat->getTechniques()[0], \"MyScheme\"));\n\n EXPECT_EQ(mat->getTechniques().size(), size_t(1));\n shaderGen.validateMaterial(\"MyScheme\", mat->getName(), mat->getGroup());\n EXPECT_EQ(mat->getTechniques().size(), size_t(2));\n\n auto newTech = mat->getTechniques()[1];\n\n EXPECT_EQ(newTech->getSchemeName(), \"MyScheme\");\n EXPECT_TRUE(newTech->getPasses()[0]->hasGpuProgram(GPT_VERTEX_PROGRAM));\n EXPECT_TRUE(newTech->getPasses()[0]->hasGpuProgram(GPT_FRAGMENT_PROGRAM));\n\n EXPECT_TRUE(shaderGen.removeShaderBasedTechnique(mat->getTechniques()[0], \"MyScheme\"));\n}\n\nTEST_F(RTShaderSystem, TargetRenderState)\n{\n auto mat = MaterialManager::getSingleton().create(\"TestMat\", RGN_DEFAULT);\n auto pass = mat->getTechniques()[0]->getPasses()[0];\n\n using namespace RTShader;\n auto& shaderGen = ShaderGenerator::getSingleton();\n\n TargetRenderState targetRenderState;\n targetRenderState.addSubRenderStateInstance(shaderGen.createSubRenderState<FFPTransform>());\n targetRenderState.addSubRenderStateInstance(shaderGen.createSubRenderState<FFPColour>());\n\n targetRenderState.acquirePrograms(pass);\n\n EXPECT_TRUE(pass->hasGpuProgram(GPT_VERTEX_PROGRAM));\n EXPECT_TRUE(pass->hasGpuProgram(GPT_FRAGMENT_PROGRAM));\n}\n<commit_msg>RTSS: add material serializer test<commit_after>\/*\n-----------------------------------------------------------------------------\nThis source file is part of OGRE\n(Object-oriented Graphics Rendering Engine)\nFor the latest info, see http:\/\/www.ogre3d.org\/\n\nCopyright (c) 2000-2014 Torus Knot Software Ltd\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n-----------------------------------------------------------------------------\n*\/\n#include \"Ogre.h\"\n#include \"RootWithoutRenderSystemFixture.h\"\n#include \"OgreShaderGenerator.h\"\n#include \"OgreShaderProgramManager.h\"\n#include \"OgreShaderMaterialSerializerListener.h\"\n\n#include \"OgreShaderFFPTransform.h\"\n#include \"OgreShaderFFPColour.h\"\n\nusing namespace Ogre;\n\nstruct RTShaderSystem : public RootWithoutRenderSystemFixture\n{\n std::unique_ptr<GpuProgramManager> gpuProgMgr;\n\n void SetUp()\n {\n RootWithoutRenderSystemFixture::SetUp();\n gpuProgMgr.reset(new GpuProgramManager());\n\n RTShader::ShaderGenerator::initialize();\n RTShader::ShaderGenerator::getSingleton().setTargetLanguage(\"glsl\");\n }\n void TearDown()\n {\n RTShader::ShaderGenerator::destroy();\n gpuProgMgr.reset();\n RootWithoutRenderSystemFixture::TearDown();\n }\n};\n\nTEST_F(RTShaderSystem, createShaderBasedTechnique)\n{\n auto& shaderGen = RTShader::ShaderGenerator::getSingleton();\n auto mat = MaterialManager::getSingleton().create(\"TestMat\", RGN_DEFAULT);\n\n EXPECT_TRUE(shaderGen.createShaderBasedTechnique(mat->getTechniques()[0], \"MyScheme\"));\n\n EXPECT_EQ(mat->getTechniques().size(), size_t(1));\n shaderGen.validateMaterial(\"MyScheme\", mat->getName(), mat->getGroup());\n EXPECT_EQ(mat->getTechniques().size(), size_t(2));\n\n auto newTech = mat->getTechniques()[1];\n\n EXPECT_EQ(newTech->getSchemeName(), \"MyScheme\");\n EXPECT_TRUE(newTech->getPasses()[0]->hasGpuProgram(GPT_VERTEX_PROGRAM));\n EXPECT_TRUE(newTech->getPasses()[0]->hasGpuProgram(GPT_FRAGMENT_PROGRAM));\n\n EXPECT_TRUE(shaderGen.removeShaderBasedTechnique(mat->getTechniques()[0], \"MyScheme\"));\n}\n\nTEST_F(RTShaderSystem, MaterialSerializer)\n{\n auto& shaderGen = RTShader::ShaderGenerator::getSingleton();\n auto mat = MaterialManager::getSingleton().create(\"TestMat\", RGN_DEFAULT);\n\n shaderGen.createShaderBasedTechnique(mat->getTechniques()[0], \"MyScheme\");\n\n auto rstate = shaderGen.getRenderState(\"MyScheme\", \"TestMat\", RGN_DEFAULT, 0);\n rstate->addTemplateSubRenderState(shaderGen.createSubRenderState<RTShader::FFPColour>());\n\n shaderGen.validateMaterial(\"MyScheme\", mat->getName(), mat->getGroup());\n\n MaterialSerializer ser;\n ser.addListener(shaderGen.getMaterialSerializerListener());\n ser.queueForExport(mat);\n EXPECT_TRUE(ser.getQueuedAsString().find(\"colour_stage\") != String::npos);\n}\n\nTEST_F(RTShaderSystem, TargetRenderState)\n{\n auto mat = MaterialManager::getSingleton().create(\"TestMat\", RGN_DEFAULT);\n auto pass = mat->getTechniques()[0]->getPasses()[0];\n\n using namespace RTShader;\n auto& shaderGen = ShaderGenerator::getSingleton();\n\n TargetRenderState targetRenderState;\n targetRenderState.addSubRenderStateInstance(shaderGen.createSubRenderState<FFPTransform>());\n targetRenderState.addSubRenderStateInstance(shaderGen.createSubRenderState<FFPColour>());\n\n targetRenderState.acquirePrograms(pass);\n\n EXPECT_TRUE(pass->hasGpuProgram(GPT_VERTEX_PROGRAM));\n EXPECT_TRUE(pass->hasGpuProgram(GPT_FRAGMENT_PROGRAM));\n}\n<|endoftext|>"} {"text":"<commit_before>#include <glow\/FrameBufferObject.h>\n#include <glow\/Log.h>\n\n#include <sstream>\n\nusing namespace glow;\n\nColorAttachment::ColorAttachment(GLenum attachment)\n: _attachment(attachment)\n{\n}\n\nGLenum ColorAttachment::attachment() const\n{\n\treturn _attachment;\n}\n\nTextureAttachment::TextureAttachment(Texture* texture, GLenum attachment)\n: ColorAttachment(attachment)\n, _texture(texture)\n{\n}\n\nRenderBufferAttachment::RenderBufferAttachment(RenderBufferObject* renderBuffer, GLenum attachment)\n: ColorAttachment(attachment)\n, _renderBuffer(renderBuffer)\n{\n}\n\n\nFrameBufferObject::FrameBufferObject()\n: Object(genFrameBuffer())\n, _target(GL_FRAMEBUFFER)\n{\n}\n\nFrameBufferObject::~FrameBufferObject()\n{\n\tif (_id) glDeleteFramebuffers(1, &_id);\n}\n\nGLuint FrameBufferObject::genFrameBuffer()\n{\n\tGLuint id = 0;\n\tglGenFramebuffers(1, &id);\n\treturn id;\n}\n\nvoid FrameBufferObject::bind()\n{\n\tglBindFramebuffer(_target, _id);\n}\n\nvoid FrameBufferObject::bind(GLenum target)\n{\n\t_target = target;\n\tglBindFramebuffer(target, _id);\n}\n\nvoid FrameBufferObject::unbind()\n{\n\tglBindFramebuffer(_target, 0);\n}\n\nvoid FrameBufferObject::setParameter(GLenum pname, GLint param)\n{\n\tbind();\n\tglFramebufferParameteri(_target, pname, param);\n}\n\nvoid FrameBufferObject::attachTexture(GLenum attachment, Texture* texture, GLint level)\n{\n\tbind();\n\tglFramebufferTexture(_target, attachment, texture->id(), level);\n\tattach(new TextureAttachment(texture, attachment));\n}\n\nvoid FrameBufferObject::attachTexture1D(GLenum attachment, Texture* texture, GLint level)\n{\n\tbind();\n\tglFramebufferTexture1D(_target, attachment, texture->target(), texture->id(), level);\n\tattach(new TextureAttachment(texture, attachment));\n}\n\nvoid FrameBufferObject::attachTexture2D(GLenum attachment, Texture* texture, GLint level)\n{\n\tbind();\n\tglFramebufferTexture2D(_target, attachment, texture->target(), texture->id(), level);\n\tattach(new TextureAttachment(texture, attachment));\n}\n\nvoid FrameBufferObject::attachTextureLayer(GLenum attachment, Texture* texture, GLint level, GLint layer)\n{\n\tbind();\n\tglFramebufferTextureLayer(_target, attachment, texture->id(), level, layer);\n\tattach(new TextureAttachment(texture, attachment));\n}\n\nvoid FrameBufferObject::attachRenderBuffer(GLenum attachment, RenderBufferObject* renderBuffer)\n{\n\tbind();\n\tglFramebufferRenderbuffer(_target, attachment, GL_RENDERBUFFER, renderBuffer->id());\n\tattach(new RenderBufferAttachment(renderBuffer, attachment));\n}\n\nvoid FrameBufferObject::attach(ColorAttachment* attachment)\n{\n\t_attachments[attachment->attachment()] = attachment;\n}\n\nvoid FrameBufferObject::blit(GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1, GLint destX0, GLint destY0, GLint destX1, GLint destY1, GLbitfield mask, GLenum filter)\n{\n\tglBlitFramebuffer(srcX0, srcY0, srcX1, srcY1, destX0, destY0, destX1, destY1, mask, filter);\n}\n\nGLenum FrameBufferObject::checkStatus()\n{\n\tbind();\n\treturn glCheckFramebufferStatus(_target);\n}\n\nstd::string FrameBufferObject::statusString()\n{\n\treturn statusString(checkStatus());\n}\n\nstd::string FrameBufferObject::statusString(GLenum status)\n{\n\tswitch (status)\n\t{\n\t\tcase GL_FRAMEBUFFER_COMPLETE:\n\t\t\treturn \"GL_FRAMEBUFFER_COMPLETE​\";\n\t\tcase GL_FRAMEBUFFER_UNDEFINED:\n\t\t\treturn \"GL_FRAMEBUFFER_UNDEFINED\";\n\t\tcase GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT:\n\t\t\treturn \"GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT\";\n\t\tcase GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:\n\t\t\treturn \"GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT\";\n\t\tcase GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER:\n\t\t\treturn \"GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER\";\n\t\tcase GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER:\n\t\t\treturn \"GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER\";\n\t\tcase GL_FRAMEBUFFER_UNSUPPORTED:\n\t\t\treturn \"GL_FRAMEBUFFER_UNSUPPORTED\";\n\t\tcase GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE:\n\t\t\treturn \"GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE\";\n\t\tcase GL_FRAMEBUFFER_INCOMPLETE_LAYER_TARGETS:\n\t\t\treturn \"GL_FRAMEBUFFER_INCOMPLETE_LAYER_TARGETS\";\n\t\tdefault:\n\t\t\treturn \"unknown framebuffer error\";\n\t}\n}\n\nvoid FrameBufferObject::printStatus(bool onlyErrors)\n{\n\tGLenum status = checkStatus();\n\n\tif (onlyErrors && status == GL_FRAMEBUFFER_COMPLETE) return;\n\n\tif (status == GL_FRAMEBUFFER_COMPLETE)\n\t{\n\t\tlog() << statusString(GL_FRAMEBUFFER_COMPLETE);\n\t}\n\telse\n\t{\n\t\tstd::stringstream ss;\n\t\tss.flags(std::ios::hex | std::ios::showbase);\n\t\tss << status;\n\n\t\terror() << statusString(status) << \" (\" << ss.str() << \")\";\n\t}\n}\n<commit_msg>bind render buffer when attached to framebufferobject<commit_after>#include <glow\/FrameBufferObject.h>\n#include <glow\/Log.h>\n\n#include <sstream>\n\nusing namespace glow;\n\nColorAttachment::ColorAttachment(GLenum attachment)\n: _attachment(attachment)\n{\n}\n\nGLenum ColorAttachment::attachment() const\n{\n\treturn _attachment;\n}\n\nTextureAttachment::TextureAttachment(Texture* texture, GLenum attachment)\n: ColorAttachment(attachment)\n, _texture(texture)\n{\n}\n\nRenderBufferAttachment::RenderBufferAttachment(RenderBufferObject* renderBuffer, GLenum attachment)\n: ColorAttachment(attachment)\n, _renderBuffer(renderBuffer)\n{\n}\n\n\nFrameBufferObject::FrameBufferObject()\n: Object(genFrameBuffer())\n, _target(GL_FRAMEBUFFER)\n{\n}\n\nFrameBufferObject::~FrameBufferObject()\n{\n\tif (_id) glDeleteFramebuffers(1, &_id);\n}\n\nGLuint FrameBufferObject::genFrameBuffer()\n{\n\tGLuint id = 0;\n\tglGenFramebuffers(1, &id);\n\treturn id;\n}\n\nvoid FrameBufferObject::bind()\n{\n\tglBindFramebuffer(_target, _id);\n}\n\nvoid FrameBufferObject::bind(GLenum target)\n{\n\t_target = target;\n\tglBindFramebuffer(target, _id);\n}\n\nvoid FrameBufferObject::unbind()\n{\n\tglBindFramebuffer(_target, 0);\n}\n\nvoid FrameBufferObject::setParameter(GLenum pname, GLint param)\n{\n\tbind();\n\tglFramebufferParameteri(_target, pname, param);\n}\n\nvoid FrameBufferObject::attachTexture(GLenum attachment, Texture* texture, GLint level)\n{\n\tbind();\n\tglFramebufferTexture(_target, attachment, texture->id(), level);\n\tattach(new TextureAttachment(texture, attachment));\n}\n\nvoid FrameBufferObject::attachTexture1D(GLenum attachment, Texture* texture, GLint level)\n{\n\tbind();\n\tglFramebufferTexture1D(_target, attachment, texture->target(), texture->id(), level);\n\tattach(new TextureAttachment(texture, attachment));\n}\n\nvoid FrameBufferObject::attachTexture2D(GLenum attachment, Texture* texture, GLint level)\n{\n\tbind();\n\tglFramebufferTexture2D(_target, attachment, texture->target(), texture->id(), level);\n\tattach(new TextureAttachment(texture, attachment));\n}\n\nvoid FrameBufferObject::attachTextureLayer(GLenum attachment, Texture* texture, GLint level, GLint layer)\n{\n\tbind();\n\tglFramebufferTextureLayer(_target, attachment, texture->id(), level, layer);\n\tattach(new TextureAttachment(texture, attachment));\n}\n\nvoid FrameBufferObject::attachRenderBuffer(GLenum attachment, RenderBufferObject* renderBuffer)\n{\n\tbind();\n\trenderBuffer->bind();\n\tglFramebufferRenderbuffer(_target, attachment, GL_RENDERBUFFER, renderBuffer->id());\n\tattach(new RenderBufferAttachment(renderBuffer, attachment));\n}\n\nvoid FrameBufferObject::attach(ColorAttachment* attachment)\n{\n\t_attachments[attachment->attachment()] = attachment;\n}\n\nvoid FrameBufferObject::blit(GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1, GLint destX0, GLint destY0, GLint destX1, GLint destY1, GLbitfield mask, GLenum filter)\n{\n\tglBlitFramebuffer(srcX0, srcY0, srcX1, srcY1, destX0, destY0, destX1, destY1, mask, filter);\n}\n\nGLenum FrameBufferObject::checkStatus()\n{\n\tbind();\n\treturn glCheckFramebufferStatus(_target);\n}\n\nstd::string FrameBufferObject::statusString()\n{\n\treturn statusString(checkStatus());\n}\n\nstd::string FrameBufferObject::statusString(GLenum status)\n{\n\tswitch (status)\n\t{\n\t\tcase GL_FRAMEBUFFER_COMPLETE:\n\t\t\treturn \"GL_FRAMEBUFFER_COMPLETE​\";\n\t\tcase GL_FRAMEBUFFER_UNDEFINED:\n\t\t\treturn \"GL_FRAMEBUFFER_UNDEFINED\";\n\t\tcase GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT:\n\t\t\treturn \"GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT\";\n\t\tcase GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:\n\t\t\treturn \"GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT\";\n\t\tcase GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER:\n\t\t\treturn \"GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER\";\n\t\tcase GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER:\n\t\t\treturn \"GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER\";\n\t\tcase GL_FRAMEBUFFER_UNSUPPORTED:\n\t\t\treturn \"GL_FRAMEBUFFER_UNSUPPORTED\";\n\t\tcase GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE:\n\t\t\treturn \"GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE\";\n\t\tcase GL_FRAMEBUFFER_INCOMPLETE_LAYER_TARGETS:\n\t\t\treturn \"GL_FRAMEBUFFER_INCOMPLETE_LAYER_TARGETS\";\n\t\tdefault:\n\t\t\treturn \"unknown framebuffer error\";\n\t}\n}\n\nvoid FrameBufferObject::printStatus(bool onlyErrors)\n{\n\tGLenum status = checkStatus();\n\n\tif (onlyErrors && status == GL_FRAMEBUFFER_COMPLETE) return;\n\n\tif (status == GL_FRAMEBUFFER_COMPLETE)\n\t{\n\t\tlog() << statusString(GL_FRAMEBUFFER_COMPLETE);\n\t}\n\telse\n\t{\n\t\tstd::stringstream ss;\n\t\tss.flags(std::ios::hex | std::ios::showbase);\n\t\tss << status;\n\n\t\terror() << statusString(status) << \" (\" << ss.str() << \")\";\n\t}\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2009 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/tab_contents\/web_contents_view_gtk.h\"\n\n#include <gdk\/gdk.h>\n#include <gtk\/gtk.h>\n\n#include \"base\/gfx\/point.h\"\n#include \"base\/gfx\/rect.h\"\n#include \"chrome\/browser\/gtk\/browser_window_gtk.h\"\n#include \"chrome\/browser\/renderer_host\/render_view_host.h\"\n#include \"chrome\/browser\/renderer_host\/render_widget_host_view_gtk.h\"\n#include \"chrome\/browser\/tab_contents\/render_view_context_menu_gtk.h\"\n#include \"chrome\/browser\/tab_contents\/tab_contents_delegate.h\"\n#include \"chrome\/browser\/tab_contents\/web_contents.h\"\n\n#include \"webkit\/glue\/webinputevent.h\"\n\nnamespace {\n\n\/\/ Called when the content view gtk widget is tabbed to. We always return true\n\/\/ and grab focus if we don't have it. The call to SetInitialFocus(bool)\n\/\/ forwards the tab to webkit. We leave focus via TakeFocus().\n\/\/ We cast the WebContents to a TabContents because SetInitialFocus is public\n\/\/ in TabContents and protected in WebContents.\ngboolean OnFocus(GtkWidget* widget, GtkDirectionType focus,\n TabContents* tab_contents) {\n if (GTK_WIDGET_HAS_FOCUS(widget))\n return TRUE;\n\n gtk_widget_grab_focus(widget);\n bool reverse = focus == GTK_DIR_TAB_BACKWARD;\n tab_contents->SetInitialFocus(reverse);\n return TRUE;\n}\n\n\/\/ Called when the mouse leaves the widget. We notify our delegate.\ngboolean OnLeaveNotify(GtkWidget* widget, GdkEventCrossing* event,\n WebContents* web_contents) {\n if (web_contents->delegate())\n web_contents->delegate()->ContentsMouseEvent(web_contents, false);\n return FALSE;\n}\n\n\/\/ Called when the mouse moves within the widget. We notify our delegate.\ngboolean OnMouseMove(GtkWidget* widget, GdkEventMotion* event,\n WebContents* web_contents) {\n if (web_contents->delegate())\n web_contents->delegate()->ContentsMouseEvent(web_contents, true);\n return FALSE;\n}\n\n\/\/ Callback used in WebContentsViewGtk::CreateViewForWidget().\nvoid RemoveWidget(GtkWidget* widget, gpointer container) {\n gtk_container_remove(GTK_CONTAINER(container), widget);\n}\n\n} \/\/ namespace\n\n\/\/ static\nWebContentsView* WebContentsView::Create(WebContents* web_contents) {\n return new WebContentsViewGtk(web_contents);\n}\n\nWebContentsViewGtk::WebContentsViewGtk(WebContents* web_contents)\n : WebContentsView(web_contents),\n vbox_(gtk_vbox_new(FALSE, 0)) {\n}\n\nWebContentsViewGtk::~WebContentsViewGtk() {\n vbox_.Destroy();\n}\n\nvoid WebContentsViewGtk::CreateView() {\n NOTIMPLEMENTED();\n}\n\nRenderWidgetHostView* WebContentsViewGtk::CreateViewForWidget(\n RenderWidgetHost* render_widget_host) {\n DCHECK(!render_widget_host->view());\n RenderWidgetHostViewGtk* view =\n new RenderWidgetHostViewGtk(render_widget_host);\n view->InitAsChild();\n content_view_ = view->native_view();\n g_signal_connect(content_view_, \"focus\",\n G_CALLBACK(OnFocus), web_contents());\n g_signal_connect(view->native_view(), \"leave-notify-event\",\n G_CALLBACK(OnLeaveNotify), web_contents());\n g_signal_connect(view->native_view(), \"motion-notify-event\",\n G_CALLBACK(OnMouseMove), web_contents());\n gtk_widget_add_events(view->native_view(), GDK_LEAVE_NOTIFY_MASK |\n GDK_POINTER_MOTION_MASK);\n gtk_container_foreach(GTK_CONTAINER(vbox_.get()), RemoveWidget, vbox_.get());\n gtk_box_pack_start(GTK_BOX(vbox_.get()), content_view_, TRUE, TRUE, 0);\n return view;\n}\n\ngfx::NativeView WebContentsViewGtk::GetNativeView() const {\n return vbox_.get();\n}\n\ngfx::NativeView WebContentsViewGtk::GetContentNativeView() const {\n return content_view_;\n}\n\ngfx::NativeWindow WebContentsViewGtk::GetTopLevelNativeWindow() const {\n return GTK_WINDOW(gtk_widget_get_toplevel(vbox_.get()));\n}\n\nvoid WebContentsViewGtk::GetContainerBounds(gfx::Rect* out) const {\n \/\/ This is used for positioning the download shelf arrow animation,\n \/\/ as well as sizing some other widgets in Windows. In GTK the size is\n \/\/ managed for us, so it appears to be only used for the download shelf\n \/\/ animation.\n out->SetRect(vbox_.get()->allocation.x, vbox_.get()->allocation.y,\n vbox_.get()->allocation.width, vbox_.get()->allocation.height);\n}\n\nvoid WebContentsViewGtk::OnContentsDestroy() {\n \/\/ TODO(estade): Windows uses this function cancel pending drag-n-drop drags.\n \/\/ We don't have drags yet, so do nothing for now.\n}\n\nvoid WebContentsViewGtk::SetPageTitle(const std::wstring& title) {\n \/\/ Set the window name to include the page title so it's easier to spot\n \/\/ when debugging (e.g. via xwininfo -tree).\n if (content_view_ && content_view_->window)\n gdk_window_set_title(content_view_->window, WideToUTF8(title).c_str());\n}\n\nvoid WebContentsViewGtk::Invalidate() {\n NOTIMPLEMENTED();\n}\n\nvoid WebContentsViewGtk::SizeContents(const gfx::Size& size) {\n NOTIMPLEMENTED();\n}\n\nvoid WebContentsViewGtk::FindInPage(const Browser& browser,\n bool find_next, bool forward_direction) {\n NOTIMPLEMENTED();\n}\n\nvoid WebContentsViewGtk::HideFindBar(bool end_session) {\n NOTIMPLEMENTED();\n}\n\nvoid WebContentsViewGtk::ReparentFindWindow(Browser* new_browser) const {\n NOTIMPLEMENTED();\n}\n\nbool WebContentsViewGtk::GetFindBarWindowInfo(gfx::Point* position,\n bool* fully_visible) const {\n NOTIMPLEMENTED();\n return false;\n}\n\nvoid WebContentsViewGtk::SetInitialFocus() {\n if (web_contents()->FocusLocationBarByDefault())\n web_contents()->delegate()->SetFocusToLocationBar();\n else\n gtk_widget_grab_focus(content_view_);\n}\n\nvoid WebContentsViewGtk::StoreFocus() {\n NOTIMPLEMENTED();\n}\n\nvoid WebContentsViewGtk::RestoreFocus() {\n \/\/ TODO(estade): implement this function.\n \/\/ For now just assume we are viewing the tab for the first time.\n SetInitialFocus();\n NOTIMPLEMENTED() << \" -- need to restore the focus position on this page.\";\n}\n\nvoid WebContentsViewGtk::UpdateDragCursor(bool is_drop_target) {\n NOTIMPLEMENTED();\n}\n\n\/\/ This is called when we the renderer asks us to take focus back (i.e., it has\n\/\/ iterated past the last focusable element on the page).\nvoid WebContentsViewGtk::TakeFocus(bool reverse) {\n web_contents()->delegate()->SetFocusToLocationBar();\n}\n\nvoid WebContentsViewGtk::HandleKeyboardEvent(\n const NativeWebKeyboardEvent& event) {\n \/\/ This may be an accelerator. Pass it on to our browser window to handle.\n GtkWindow* window = GetTopLevelNativeWindow();\n BrowserWindowGtk* browser_window = static_cast<BrowserWindowGtk*>(\n g_object_get_data(G_OBJECT(window), \"browser_window_gtk\"));\n browser_window->HandleAccelerator(event.os_event->keyval,\n static_cast<GdkModifierType>(event.os_event->state));\n}\n\nvoid WebContentsViewGtk::OnFindReply(int request_id,\n int number_of_matches,\n const gfx::Rect& selection_rect,\n int active_match_ordinal,\n bool final_update) {\n NOTIMPLEMENTED();\n}\n\nvoid WebContentsViewGtk::ShowContextMenu(const ContextMenuParams& params) {\n context_menu_.reset(new RenderViewContextMenuGtk(web_contents(), params));\n context_menu_->Popup();\n}\n\nvoid WebContentsViewGtk::StartDragging(const WebDropData& drop_data) {\n NOTIMPLEMENTED();\n\n \/\/ Until we have d'n'd implemented, just immediately pretend we're\n \/\/ already done with the drag and drop so we don't get stuck\n \/\/ thinking we're in mid-drag.\n \/\/ TODO(port): remove me when the above NOTIMPLEMENTED is fixed.\n if (web_contents()->render_view_host())\n web_contents()->render_view_host()->DragSourceSystemDragEnded();\n}\n\nWebContents* WebContentsViewGtk::CreateNewWindowInternal(\n int route_id,\n base::WaitableEvent* modal_dialog_event) {\n NOTIMPLEMENTED();\n return NULL;\n}\n\nvoid WebContentsViewGtk::ShowCreatedWindowInternal(\n WebContents* new_web_contents,\n WindowOpenDisposition disposition,\n const gfx::Rect& initial_pos,\n bool user_gesture) {\n NOTIMPLEMENTED();\n}\n<commit_msg>Fix crash when trying to handle keyboard accelerators while the current tab contents is no longer in the view hierarchy (ie., it got switched out).<commit_after>\/\/ Copyright (c) 2009 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/tab_contents\/web_contents_view_gtk.h\"\n\n#include <gdk\/gdk.h>\n#include <gtk\/gtk.h>\n\n#include \"base\/gfx\/point.h\"\n#include \"base\/gfx\/rect.h\"\n#include \"chrome\/browser\/gtk\/browser_window_gtk.h\"\n#include \"chrome\/browser\/renderer_host\/render_view_host.h\"\n#include \"chrome\/browser\/renderer_host\/render_widget_host_view_gtk.h\"\n#include \"chrome\/browser\/tab_contents\/render_view_context_menu_gtk.h\"\n#include \"chrome\/browser\/tab_contents\/tab_contents_delegate.h\"\n#include \"chrome\/browser\/tab_contents\/web_contents.h\"\n\n#include \"webkit\/glue\/webinputevent.h\"\n\nnamespace {\n\n\/\/ Called when the content view gtk widget is tabbed to. We always return true\n\/\/ and grab focus if we don't have it. The call to SetInitialFocus(bool)\n\/\/ forwards the tab to webkit. We leave focus via TakeFocus().\n\/\/ We cast the WebContents to a TabContents because SetInitialFocus is public\n\/\/ in TabContents and protected in WebContents.\ngboolean OnFocus(GtkWidget* widget, GtkDirectionType focus,\n TabContents* tab_contents) {\n if (GTK_WIDGET_HAS_FOCUS(widget))\n return TRUE;\n\n gtk_widget_grab_focus(widget);\n bool reverse = focus == GTK_DIR_TAB_BACKWARD;\n tab_contents->SetInitialFocus(reverse);\n return TRUE;\n}\n\n\/\/ Called when the mouse leaves the widget. We notify our delegate.\ngboolean OnLeaveNotify(GtkWidget* widget, GdkEventCrossing* event,\n WebContents* web_contents) {\n if (web_contents->delegate())\n web_contents->delegate()->ContentsMouseEvent(web_contents, false);\n return FALSE;\n}\n\n\/\/ Called when the mouse moves within the widget. We notify our delegate.\ngboolean OnMouseMove(GtkWidget* widget, GdkEventMotion* event,\n WebContents* web_contents) {\n if (web_contents->delegate())\n web_contents->delegate()->ContentsMouseEvent(web_contents, true);\n return FALSE;\n}\n\n\/\/ Callback used in WebContentsViewGtk::CreateViewForWidget().\nvoid RemoveWidget(GtkWidget* widget, gpointer container) {\n gtk_container_remove(GTK_CONTAINER(container), widget);\n}\n\n} \/\/ namespace\n\n\/\/ static\nWebContentsView* WebContentsView::Create(WebContents* web_contents) {\n return new WebContentsViewGtk(web_contents);\n}\n\nWebContentsViewGtk::WebContentsViewGtk(WebContents* web_contents)\n : WebContentsView(web_contents),\n vbox_(gtk_vbox_new(FALSE, 0)) {\n}\n\nWebContentsViewGtk::~WebContentsViewGtk() {\n vbox_.Destroy();\n}\n\nvoid WebContentsViewGtk::CreateView() {\n NOTIMPLEMENTED();\n}\n\nRenderWidgetHostView* WebContentsViewGtk::CreateViewForWidget(\n RenderWidgetHost* render_widget_host) {\n DCHECK(!render_widget_host->view());\n RenderWidgetHostViewGtk* view =\n new RenderWidgetHostViewGtk(render_widget_host);\n view->InitAsChild();\n content_view_ = view->native_view();\n g_signal_connect(content_view_, \"focus\",\n G_CALLBACK(OnFocus), web_contents());\n g_signal_connect(view->native_view(), \"leave-notify-event\",\n G_CALLBACK(OnLeaveNotify), web_contents());\n g_signal_connect(view->native_view(), \"motion-notify-event\",\n G_CALLBACK(OnMouseMove), web_contents());\n gtk_widget_add_events(view->native_view(), GDK_LEAVE_NOTIFY_MASK |\n GDK_POINTER_MOTION_MASK);\n gtk_container_foreach(GTK_CONTAINER(vbox_.get()), RemoveWidget, vbox_.get());\n gtk_box_pack_start(GTK_BOX(vbox_.get()), content_view_, TRUE, TRUE, 0);\n return view;\n}\n\ngfx::NativeView WebContentsViewGtk::GetNativeView() const {\n return vbox_.get();\n}\n\ngfx::NativeView WebContentsViewGtk::GetContentNativeView() const {\n return content_view_;\n}\n\ngfx::NativeWindow WebContentsViewGtk::GetTopLevelNativeWindow() const {\n GtkWidget* window = gtk_widget_get_ancestor(GetNativeView(), GTK_TYPE_WINDOW);\n return window ? GTK_WINDOW(window) : NULL;\n}\n\nvoid WebContentsViewGtk::GetContainerBounds(gfx::Rect* out) const {\n \/\/ This is used for positioning the download shelf arrow animation,\n \/\/ as well as sizing some other widgets in Windows. In GTK the size is\n \/\/ managed for us, so it appears to be only used for the download shelf\n \/\/ animation.\n out->SetRect(vbox_.get()->allocation.x, vbox_.get()->allocation.y,\n vbox_.get()->allocation.width, vbox_.get()->allocation.height);\n}\n\nvoid WebContentsViewGtk::OnContentsDestroy() {\n \/\/ TODO(estade): Windows uses this function cancel pending drag-n-drop drags.\n \/\/ We don't have drags yet, so do nothing for now.\n}\n\nvoid WebContentsViewGtk::SetPageTitle(const std::wstring& title) {\n \/\/ Set the window name to include the page title so it's easier to spot\n \/\/ when debugging (e.g. via xwininfo -tree).\n if (content_view_ && content_view_->window)\n gdk_window_set_title(content_view_->window, WideToUTF8(title).c_str());\n}\n\nvoid WebContentsViewGtk::Invalidate() {\n NOTIMPLEMENTED();\n}\n\nvoid WebContentsViewGtk::SizeContents(const gfx::Size& size) {\n NOTIMPLEMENTED();\n}\n\nvoid WebContentsViewGtk::FindInPage(const Browser& browser,\n bool find_next, bool forward_direction) {\n NOTIMPLEMENTED();\n}\n\nvoid WebContentsViewGtk::HideFindBar(bool end_session) {\n NOTIMPLEMENTED();\n}\n\nvoid WebContentsViewGtk::ReparentFindWindow(Browser* new_browser) const {\n NOTIMPLEMENTED();\n}\n\nbool WebContentsViewGtk::GetFindBarWindowInfo(gfx::Point* position,\n bool* fully_visible) const {\n NOTIMPLEMENTED();\n return false;\n}\n\nvoid WebContentsViewGtk::SetInitialFocus() {\n if (web_contents()->FocusLocationBarByDefault())\n web_contents()->delegate()->SetFocusToLocationBar();\n else\n gtk_widget_grab_focus(content_view_);\n}\n\nvoid WebContentsViewGtk::StoreFocus() {\n NOTIMPLEMENTED();\n}\n\nvoid WebContentsViewGtk::RestoreFocus() {\n \/\/ TODO(estade): implement this function.\n \/\/ For now just assume we are viewing the tab for the first time.\n SetInitialFocus();\n NOTIMPLEMENTED() << \" -- need to restore the focus position on this page.\";\n}\n\nvoid WebContentsViewGtk::UpdateDragCursor(bool is_drop_target) {\n NOTIMPLEMENTED();\n}\n\n\/\/ This is called when we the renderer asks us to take focus back (i.e., it has\n\/\/ iterated past the last focusable element on the page).\nvoid WebContentsViewGtk::TakeFocus(bool reverse) {\n web_contents()->delegate()->SetFocusToLocationBar();\n}\n\nvoid WebContentsViewGtk::HandleKeyboardEvent(\n const NativeWebKeyboardEvent& event) {\n \/\/ This may be an accelerator. Try to pass it on to our browser window\n \/\/ to handle.\n GtkWindow* window = GetTopLevelNativeWindow();\n \/\/ It's possible to not be associated with a window at the time when we're\n \/\/ handling the keyboard event (e.g., the user opened a new tab in the time).\n \/\/ What we really want to do is get whatever currently has focus and have\n \/\/ that handle the accelerator. TODO(tc): Consider walking\n \/\/ gtk_window_list_toplevels to find what has focus and if that's a browser\n \/\/ window, forward the event.\n if (!window)\n return;\n\n BrowserWindowGtk* browser_window = static_cast<BrowserWindowGtk*>(\n g_object_get_data(G_OBJECT(window), \"browser_window_gtk\"));\n DCHECK(browser_window);\n browser_window->HandleAccelerator(event.os_event->keyval,\n static_cast<GdkModifierType>(event.os_event->state));\n}\n\nvoid WebContentsViewGtk::OnFindReply(int request_id,\n int number_of_matches,\n const gfx::Rect& selection_rect,\n int active_match_ordinal,\n bool final_update) {\n NOTIMPLEMENTED();\n}\n\nvoid WebContentsViewGtk::ShowContextMenu(const ContextMenuParams& params) {\n context_menu_.reset(new RenderViewContextMenuGtk(web_contents(), params));\n context_menu_->Popup();\n}\n\nvoid WebContentsViewGtk::StartDragging(const WebDropData& drop_data) {\n NOTIMPLEMENTED();\n\n \/\/ Until we have d'n'd implemented, just immediately pretend we're\n \/\/ already done with the drag and drop so we don't get stuck\n \/\/ thinking we're in mid-drag.\n \/\/ TODO(port): remove me when the above NOTIMPLEMENTED is fixed.\n if (web_contents()->render_view_host())\n web_contents()->render_view_host()->DragSourceSystemDragEnded();\n}\n\nWebContents* WebContentsViewGtk::CreateNewWindowInternal(\n int route_id,\n base::WaitableEvent* modal_dialog_event) {\n NOTIMPLEMENTED();\n return NULL;\n}\n\nvoid WebContentsViewGtk::ShowCreatedWindowInternal(\n WebContents* new_web_contents,\n WindowOpenDisposition disposition,\n const gfx::Rect& initial_pos,\n bool user_gesture) {\n NOTIMPLEMENTED();\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/===-- llc.cpp - Implement the LLVM Native Code Generator ----------------===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file was developed by the LLVM research group and is distributed under\n\/\/ the University of Illinois Open Source License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This is the llc code generator driver. It provides a convenient\n\/\/ command-line interface for generating native assembly-language code\n\/\/ or C code, given LLVM bytecode.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/Bytecode\/Reader.h\"\n#include \"llvm\/Target\/SubtargetFeature.h\"\n#include \"llvm\/Target\/TargetMachine.h\"\n#include \"llvm\/Target\/TargetMachineRegistry.h\"\n#include \"llvm\/Transforms\/Scalar.h\"\n#include \"llvm\/Module.h\"\n#include \"llvm\/PassManager.h\"\n#include \"llvm\/Pass.h\"\n#include \"llvm\/Support\/CommandLine.h\"\n#include \"llvm\/Support\/PluginLoader.h\"\n#include \"llvm\/Support\/PassNameParser.h\"\n#include \"llvm\/Analysis\/Verifier.h\"\n#include \"llvm\/System\/Signals.h\"\n#include \"llvm\/Config\/config.h\"\n#include <fstream>\n#include <iostream>\n#include <memory>\n\nusing namespace llvm;\n\n\/\/ General options for llc. Other pass-specific options are specified\n\/\/ within the corresponding llc passes, and target-specific options\n\/\/ and back-end code generation options are specified with the target machine.\n\/\/\nstatic cl::opt<std::string>\nInputFilename(cl::Positional, cl::desc(\"<input bytecode>\"), cl::init(\"-\"));\n\nstatic cl::opt<std::string>\nOutputFilename(\"o\", cl::desc(\"Output filename\"), cl::value_desc(\"filename\"));\n\nstatic cl::opt<bool> Force(\"f\", cl::desc(\"Overwrite output files\"));\n\nstatic cl::opt<bool> Fast(\"fast\", \n cl::desc(\"Generate code quickly, potentially sacrificing code quality\"));\n\n\nstatic cl::opt<const TargetMachineRegistry::Entry*, false, TargetNameParser>\nMArch(\"march\", cl::desc(\"Architecture to generate code for:\"));\n\nstatic cl::opt<std::string>\nMCPU(\"mcpu\", \n cl::desc(\"Target a specific cpu type (-mcpu=help for details)\"),\n cl::value_desc(\"cpu-name\"),\n cl::init(\"\"));\n\nstatic cl::list<std::string>\nMAttrs(\"mattr\", \n cl::CommaSeparated,\n cl::desc(\"Target specific attributes (-mattr=help for details)\"),\n cl::value_desc(\"a1,+a2,-a3,...\"));\n\ncl::opt<TargetMachine::CodeGenFileType>\nFileType(\"filetype\", cl::init(TargetMachine::AssemblyFile),\n cl::desc(\"Choose a file type (not all types are supported by all targets):\"),\n cl::values(\n clEnumValN(TargetMachine::AssemblyFile, \"asm\",\n \" Emit an assembly ('.s') file\"),\n clEnumValN(TargetMachine::ObjectFile, \"obj\",\n \" Emit a native object ('.o') file [experimental]\"),\n clEnumValN(TargetMachine::DynamicLibrary, \"dynlib\",\n \" Emit a native dynamic library ('.so') file\"),\n clEnumValEnd));\n\n\/\/ The LLCPassList is populated with passes that were registered using\n\/\/ PassInfo::LLC by the FilteredPassNameParser:\ncl::list<const PassInfo*, bool, FilteredPassNameParser<PassInfo::LLC> >\nLLCPassList(cl::desc(\"Passes Available\"));\n\ncl::opt<bool> NoVerify(\"disable-verify\", cl::Hidden,\n cl::desc(\"Do not verify input module\"));\n\n\n\/\/ GetFileNameRoot - Helper function to get the basename of a filename.\nstatic inline std::string\nGetFileNameRoot(const std::string &InputFilename) {\n std::string IFN = InputFilename;\n std::string outputFilename;\n int Len = IFN.length();\n if ((Len > 2) &&\n IFN[Len-3] == '.' && IFN[Len-2] == 'b' && IFN[Len-1] == 'c') {\n outputFilename = std::string(IFN.begin(), IFN.end()-3); \/\/ s\/.bc\/.s\/\n } else {\n outputFilename = IFN;\n }\n return outputFilename;\n}\n\n\n\/\/ main - Entry point for the llc compiler.\n\/\/\nint main(int argc, char **argv) {\n try {\n cl::ParseCommandLineOptions(argc, argv, \" llvm system compiler\\n\");\n sys::PrintStackTraceOnErrorSignal();\n\n \/\/ Load the module to be compiled...\n std::auto_ptr<Module> M(ParseBytecodeFile(InputFilename));\n if (M.get() == 0) {\n std::cerr << argv[0] << \": bytecode didn't read correctly.\\n\";\n return 1;\n }\n Module &mod = *M.get();\n\n \/\/ Allocate target machine. First, check whether the user has\n \/\/ explicitly specified an architecture to compile for.\n TargetMachine* (*TargetMachineAllocator)(const Module&,\n IntrinsicLowering *) = 0;\n if (MArch == 0) {\n std::string Err;\n MArch = TargetMachineRegistry::getClosestStaticTargetForModule(mod, Err);\n if (MArch == 0) {\n std::cerr << argv[0] << \": error auto-selecting target for module '\"\n << Err << \"'. Please use the -march option to explicitly \"\n << \"pick a target.\\n\";\n return 1;\n }\n }\n\n \/\/ Package up features to be passed to target\/subtarget\n std::string FeaturesStr;\n if (MCPU.size() || MAttrs.size()) {\n SubtargetFeatures Features;\n Features.setCPU(MCPU);\n for (unsigned i = 0; i != MAttrs.size(); ++i)\n Features.AddFeature(MAttrs[i]);\n FeaturesStr = Features.getString();\n }\n\n std::auto_ptr<TargetMachine> target(MArch->CtorFn(mod, 0, FeaturesStr));\n assert(target.get() && \"Could not allocate target machine!\");\n TargetMachine &Target = *target.get();\n const TargetData &TD = Target.getTargetData();\n\n \/\/ Build up all of the passes that we want to do to the module...\n PassManager Passes;\n Passes.add(new TargetData(TD));\n\n \/\/ Create a new pass for each one specified on the command line\n for (unsigned i = 0; i < LLCPassList.size(); ++i) {\n const PassInfo *aPass = LLCPassList[i];\n\n if (aPass->getNormalCtor()) {\n Pass *P = aPass->getNormalCtor()();\n Passes.add(P);\n } else {\n std::cerr << argv[0] << \": cannot create pass: \"\n << aPass->getPassName() << \"\\n\";\n }\n }\n\n#ifndef NDEBUG\n if(!NoVerify)\n Passes.add(createVerifierPass());\n#endif\n\n \/\/ Figure out where we are going to send the output...\n std::ostream *Out = 0;\n if (OutputFilename != \"\") {\n if (OutputFilename != \"-\") {\n \/\/ Specified an output filename?\n if (!Force && std::ifstream(OutputFilename.c_str())) {\n \/\/ If force is not specified, make sure not to overwrite a file!\n std::cerr << argv[0] << \": error opening '\" << OutputFilename\n << \"': file exists!\\n\"\n << \"Use -f command line argument to force output\\n\";\n return 1;\n }\n Out = new std::ofstream(OutputFilename.c_str());\n\n \/\/ Make sure that the Out file gets unlinked from the disk if we get a\n \/\/ SIGINT\n sys::RemoveFileOnSignal(sys::Path(OutputFilename));\n } else {\n Out = &std::cout;\n }\n } else {\n if (InputFilename == \"-\") {\n OutputFilename = \"-\";\n Out = &std::cout;\n } else {\n OutputFilename = GetFileNameRoot(InputFilename);\n\n switch (FileType) {\n case TargetMachine::AssemblyFile:\n if (MArch->Name[0] != 'c' || MArch->Name[1] != 0) \/\/ not CBE\n OutputFilename += \".s\";\n else\n OutputFilename += \".cbe.c\";\n break;\n case TargetMachine::ObjectFile:\n OutputFilename += \".o\";\n break;\n case TargetMachine::DynamicLibrary:\n OutputFilename += LTDL_SHLIB_EXT;\n break;\n }\n\n if (!Force && std::ifstream(OutputFilename.c_str())) {\n \/\/ If force is not specified, make sure not to overwrite a file!\n std::cerr << argv[0] << \": error opening '\" << OutputFilename\n << \"': file exists!\\n\"\n << \"Use -f command line argument to force output\\n\";\n return 1;\n }\n\n Out = new std::ofstream(OutputFilename.c_str());\n if (!Out->good()) {\n std::cerr << argv[0] << \": error opening \" << OutputFilename << \"!\\n\";\n delete Out;\n return 1;\n }\n\n \/\/ Make sure that the Out file gets unlinked from the disk if we get a\n \/\/ SIGINT\n sys::RemoveFileOnSignal(sys::Path(OutputFilename));\n }\n }\n\n \/\/ Ask the target to add backend passes as necessary.\n if (Target.addPassesToEmitFile(Passes, *Out, FileType, Fast)) {\n std::cerr << argv[0] << \": target '\" << Target.getName()\n << \"' does not support generation of this file type!\\n\";\n if (Out != &std::cout) delete Out;\n \/\/ And the Out file is empty and useless, so remove it now.\n std::remove(OutputFilename.c_str());\n return 1;\n } else {\n \/\/ Run our queue of passes all at once now, efficiently.\n Passes.run(*M.get());\n }\n\n \/\/ Delete the ostream if it's not a stdout stream\n if (Out != &std::cout) delete Out;\n\n return 0;\n } catch (const std::string& msg) {\n std::cerr << argv[0] << \": \" << msg << \"\\n\";\n } catch (...) {\n std::cerr << argv[0] << \": Unexpected unknown exception occurred.\\n\";\n }\n return 1;\n}\n<commit_msg>provide an option to override the target triple in a module from the command line.<commit_after>\/\/===-- llc.cpp - Implement the LLVM Native Code Generator ----------------===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file was developed by the LLVM research group and is distributed under\n\/\/ the University of Illinois Open Source License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This is the llc code generator driver. It provides a convenient\n\/\/ command-line interface for generating native assembly-language code\n\/\/ or C code, given LLVM bytecode.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/Bytecode\/Reader.h\"\n#include \"llvm\/Target\/SubtargetFeature.h\"\n#include \"llvm\/Target\/TargetMachine.h\"\n#include \"llvm\/Target\/TargetMachineRegistry.h\"\n#include \"llvm\/Transforms\/Scalar.h\"\n#include \"llvm\/Module.h\"\n#include \"llvm\/PassManager.h\"\n#include \"llvm\/Pass.h\"\n#include \"llvm\/Support\/CommandLine.h\"\n#include \"llvm\/Support\/PluginLoader.h\"\n#include \"llvm\/Support\/PassNameParser.h\"\n#include \"llvm\/Analysis\/Verifier.h\"\n#include \"llvm\/System\/Signals.h\"\n#include \"llvm\/Config\/config.h\"\n#include <fstream>\n#include <iostream>\n#include <memory>\n\nusing namespace llvm;\n\n\/\/ General options for llc. Other pass-specific options are specified\n\/\/ within the corresponding llc passes, and target-specific options\n\/\/ and back-end code generation options are specified with the target machine.\n\/\/\nstatic cl::opt<std::string>\nInputFilename(cl::Positional, cl::desc(\"<input bytecode>\"), cl::init(\"-\"));\n\nstatic cl::opt<std::string>\nOutputFilename(\"o\", cl::desc(\"Output filename\"), cl::value_desc(\"filename\"));\n\nstatic cl::opt<bool> Force(\"f\", cl::desc(\"Overwrite output files\"));\n\nstatic cl::opt<bool> Fast(\"fast\", \n cl::desc(\"Generate code quickly, potentially sacrificing code quality\"));\n\nstatic cl::opt<std::string>\nTargetTriple(\"triple\", cl::desc(\"Override target triple for module\"));\n\nstatic cl::opt<const TargetMachineRegistry::Entry*, false, TargetNameParser>\nMArch(\"march\", cl::desc(\"Architecture to generate code for:\"));\n\nstatic cl::opt<std::string>\nMCPU(\"mcpu\", \n cl::desc(\"Target a specific cpu type (-mcpu=help for details)\"),\n cl::value_desc(\"cpu-name\"),\n cl::init(\"\"));\n\nstatic cl::list<std::string>\nMAttrs(\"mattr\", \n cl::CommaSeparated,\n cl::desc(\"Target specific attributes (-mattr=help for details)\"),\n cl::value_desc(\"a1,+a2,-a3,...\"));\n\ncl::opt<TargetMachine::CodeGenFileType>\nFileType(\"filetype\", cl::init(TargetMachine::AssemblyFile),\n cl::desc(\"Choose a file type (not all types are supported by all targets):\"),\n cl::values(\n clEnumValN(TargetMachine::AssemblyFile, \"asm\",\n \" Emit an assembly ('.s') file\"),\n clEnumValN(TargetMachine::ObjectFile, \"obj\",\n \" Emit a native object ('.o') file [experimental]\"),\n clEnumValN(TargetMachine::DynamicLibrary, \"dynlib\",\n \" Emit a native dynamic library ('.so') file\"),\n clEnumValEnd));\n\n\/\/ The LLCPassList is populated with passes that were registered using\n\/\/ PassInfo::LLC by the FilteredPassNameParser:\ncl::list<const PassInfo*, bool, FilteredPassNameParser<PassInfo::LLC> >\nLLCPassList(cl::desc(\"Passes Available\"));\n\ncl::opt<bool> NoVerify(\"disable-verify\", cl::Hidden,\n cl::desc(\"Do not verify input module\"));\n\n\n\/\/ GetFileNameRoot - Helper function to get the basename of a filename.\nstatic inline std::string\nGetFileNameRoot(const std::string &InputFilename) {\n std::string IFN = InputFilename;\n std::string outputFilename;\n int Len = IFN.length();\n if ((Len > 2) &&\n IFN[Len-3] == '.' && IFN[Len-2] == 'b' && IFN[Len-1] == 'c') {\n outputFilename = std::string(IFN.begin(), IFN.end()-3); \/\/ s\/.bc\/.s\/\n } else {\n outputFilename = IFN;\n }\n return outputFilename;\n}\n\n\n\/\/ main - Entry point for the llc compiler.\n\/\/\nint main(int argc, char **argv) {\n try {\n cl::ParseCommandLineOptions(argc, argv, \" llvm system compiler\\n\");\n sys::PrintStackTraceOnErrorSignal();\n\n \/\/ Load the module to be compiled...\n std::auto_ptr<Module> M(ParseBytecodeFile(InputFilename));\n if (M.get() == 0) {\n std::cerr << argv[0] << \": bytecode didn't read correctly.\\n\";\n return 1;\n }\n Module &mod = *M.get();\n\n \/\/ If we are supposed to override the target triple, do so now.\n if (!TargetTriple.empty())\n mod.setTargetTriple(TargetTriple);\n \n \/\/ Allocate target machine. First, check whether the user has\n \/\/ explicitly specified an architecture to compile for.\n TargetMachine* (*TargetMachineAllocator)(const Module&,\n IntrinsicLowering *) = 0;\n if (MArch == 0) {\n std::string Err;\n MArch = TargetMachineRegistry::getClosestStaticTargetForModule(mod, Err);\n if (MArch == 0) {\n std::cerr << argv[0] << \": error auto-selecting target for module '\"\n << Err << \"'. Please use the -march option to explicitly \"\n << \"pick a target.\\n\";\n return 1;\n }\n }\n\n \/\/ Package up features to be passed to target\/subtarget\n std::string FeaturesStr;\n if (MCPU.size() || MAttrs.size()) {\n SubtargetFeatures Features;\n Features.setCPU(MCPU);\n for (unsigned i = 0; i != MAttrs.size(); ++i)\n Features.AddFeature(MAttrs[i]);\n FeaturesStr = Features.getString();\n }\n\n std::auto_ptr<TargetMachine> target(MArch->CtorFn(mod, 0, FeaturesStr));\n assert(target.get() && \"Could not allocate target machine!\");\n TargetMachine &Target = *target.get();\n const TargetData &TD = Target.getTargetData();\n\n \/\/ Build up all of the passes that we want to do to the module...\n PassManager Passes;\n Passes.add(new TargetData(TD));\n\n \/\/ Create a new pass for each one specified on the command line\n for (unsigned i = 0; i < LLCPassList.size(); ++i) {\n const PassInfo *aPass = LLCPassList[i];\n\n if (aPass->getNormalCtor()) {\n Pass *P = aPass->getNormalCtor()();\n Passes.add(P);\n } else {\n std::cerr << argv[0] << \": cannot create pass: \"\n << aPass->getPassName() << \"\\n\";\n }\n }\n\n#ifndef NDEBUG\n if(!NoVerify)\n Passes.add(createVerifierPass());\n#endif\n\n \/\/ Figure out where we are going to send the output...\n std::ostream *Out = 0;\n if (OutputFilename != \"\") {\n if (OutputFilename != \"-\") {\n \/\/ Specified an output filename?\n if (!Force && std::ifstream(OutputFilename.c_str())) {\n \/\/ If force is not specified, make sure not to overwrite a file!\n std::cerr << argv[0] << \": error opening '\" << OutputFilename\n << \"': file exists!\\n\"\n << \"Use -f command line argument to force output\\n\";\n return 1;\n }\n Out = new std::ofstream(OutputFilename.c_str());\n\n \/\/ Make sure that the Out file gets unlinked from the disk if we get a\n \/\/ SIGINT\n sys::RemoveFileOnSignal(sys::Path(OutputFilename));\n } else {\n Out = &std::cout;\n }\n } else {\n if (InputFilename == \"-\") {\n OutputFilename = \"-\";\n Out = &std::cout;\n } else {\n OutputFilename = GetFileNameRoot(InputFilename);\n\n switch (FileType) {\n case TargetMachine::AssemblyFile:\n if (MArch->Name[0] != 'c' || MArch->Name[1] != 0) \/\/ not CBE\n OutputFilename += \".s\";\n else\n OutputFilename += \".cbe.c\";\n break;\n case TargetMachine::ObjectFile:\n OutputFilename += \".o\";\n break;\n case TargetMachine::DynamicLibrary:\n OutputFilename += LTDL_SHLIB_EXT;\n break;\n }\n\n if (!Force && std::ifstream(OutputFilename.c_str())) {\n \/\/ If force is not specified, make sure not to overwrite a file!\n std::cerr << argv[0] << \": error opening '\" << OutputFilename\n << \"': file exists!\\n\"\n << \"Use -f command line argument to force output\\n\";\n return 1;\n }\n\n Out = new std::ofstream(OutputFilename.c_str());\n if (!Out->good()) {\n std::cerr << argv[0] << \": error opening \" << OutputFilename << \"!\\n\";\n delete Out;\n return 1;\n }\n\n \/\/ Make sure that the Out file gets unlinked from the disk if we get a\n \/\/ SIGINT\n sys::RemoveFileOnSignal(sys::Path(OutputFilename));\n }\n }\n\n \/\/ Ask the target to add backend passes as necessary.\n if (Target.addPassesToEmitFile(Passes, *Out, FileType, Fast)) {\n std::cerr << argv[0] << \": target '\" << Target.getName()\n << \"' does not support generation of this file type!\\n\";\n if (Out != &std::cout) delete Out;\n \/\/ And the Out file is empty and useless, so remove it now.\n std::remove(OutputFilename.c_str());\n return 1;\n } else {\n \/\/ Run our queue of passes all at once now, efficiently.\n Passes.run(*M.get());\n }\n\n \/\/ Delete the ostream if it's not a stdout stream\n if (Out != &std::cout) delete Out;\n\n return 0;\n } catch (const std::string& msg) {\n std::cerr << argv[0] << \": \" << msg << \"\\n\";\n } catch (...) {\n std::cerr << argv[0] << \": Unexpected unknown exception occurred.\\n\";\n }\n return 1;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/===-- llc.cpp - Implement the LLVM Native Code Generator ----------------===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This is the llc code generator driver. It provides a convenient\n\/\/ command-line interface for generating native assembly-language code\n\/\/ or C code, given LLVM bitcode.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/LLVMContext.h\"\n#include \"llvm\/DataLayout.h\"\n#include \"llvm\/Module.h\"\n#include \"llvm\/PassManager.h\"\n#include \"llvm\/Pass.h\"\n#include \"llvm\/ADT\/Triple.h\"\n#include \"llvm\/Assembly\/PrintModulePass.h\"\n#include \"llvm\/Support\/IRReader.h\"\n#include \"llvm\/CodeGen\/CommandFlags.h\"\n#include \"llvm\/CodeGen\/LinkAllAsmWriterComponents.h\"\n#include \"llvm\/CodeGen\/LinkAllCodegenComponents.h\"\n#include \"llvm\/MC\/SubtargetFeature.h\"\n#include \"llvm\/Support\/CommandLine.h\"\n#include \"llvm\/Support\/Debug.h\"\n#include \"llvm\/Support\/FormattedStream.h\"\n#include \"llvm\/Support\/ManagedStatic.h\"\n#include \"llvm\/Support\/PluginLoader.h\"\n#include \"llvm\/Support\/PrettyStackTrace.h\"\n#include \"llvm\/Support\/ToolOutputFile.h\"\n#include \"llvm\/Support\/Host.h\"\n#include \"llvm\/Support\/Signals.h\"\n#include \"llvm\/Support\/TargetRegistry.h\"\n#include \"llvm\/Support\/TargetSelect.h\"\n#include \"llvm\/Target\/TargetLibraryInfo.h\"\n#include \"llvm\/Target\/TargetMachine.h\"\n#include <memory>\nusing namespace llvm;\n\n\/\/ General options for llc. Other pass-specific options are specified\n\/\/ within the corresponding llc passes, and target-specific options\n\/\/ and back-end code generation options are specified with the target machine.\n\/\/\nstatic cl::opt<std::string>\nInputFilename(cl::Positional, cl::desc(\"<input bitcode>\"), cl::init(\"-\"));\n\nstatic cl::opt<std::string>\nOutputFilename(\"o\", cl::desc(\"Output filename\"), cl::value_desc(\"filename\"));\n\n\/\/ Determine optimization level.\nstatic cl::opt<char>\nOptLevel(\"O\",\n cl::desc(\"Optimization level. [-O0, -O1, -O2, or -O3] \"\n \"(default = '-O2')\"),\n cl::Prefix,\n cl::ZeroOrMore,\n cl::init(' '));\n\nstatic cl::opt<std::string>\nTargetTriple(\"mtriple\", cl::desc(\"Override target triple for module\"));\n\ncl::opt<bool> NoVerify(\"disable-verify\", cl::Hidden,\n cl::desc(\"Do not verify input module\"));\n\ncl::opt<bool>\nDisableSimplifyLibCalls(\"disable-simplify-libcalls\",\n cl::desc(\"Disable simplify-libcalls\"),\n cl::init(false));\n\n\/\/ GetFileNameRoot - Helper function to get the basename of a filename.\nstatic inline std::string\nGetFileNameRoot(const std::string &InputFilename) {\n std::string IFN = InputFilename;\n std::string outputFilename;\n int Len = IFN.length();\n if ((Len > 2) &&\n IFN[Len-3] == '.' &&\n ((IFN[Len-2] == 'b' && IFN[Len-1] == 'c') ||\n (IFN[Len-2] == 'l' && IFN[Len-1] == 'l'))) {\n outputFilename = std::string(IFN.begin(), IFN.end()-3); \/\/ s\/.bc\/.s\/\n } else {\n outputFilename = IFN;\n }\n return outputFilename;\n}\n\nstatic tool_output_file *GetOutputStream(const char *TargetName,\n Triple::OSType OS,\n const char *ProgName) {\n \/\/ If we don't yet have an output filename, make one.\n if (OutputFilename.empty()) {\n if (InputFilename == \"-\")\n OutputFilename = \"-\";\n else {\n OutputFilename = GetFileNameRoot(InputFilename);\n\n switch (FileType) {\n case TargetMachine::CGFT_AssemblyFile:\n if (TargetName[0] == 'c') {\n if (TargetName[1] == 0)\n OutputFilename += \".cbe.c\";\n else if (TargetName[1] == 'p' && TargetName[2] == 'p')\n OutputFilename += \".cpp\";\n else\n OutputFilename += \".s\";\n } else\n OutputFilename += \".s\";\n break;\n case TargetMachine::CGFT_ObjectFile:\n if (OS == Triple::Win32)\n OutputFilename += \".obj\";\n else\n OutputFilename += \".o\";\n break;\n case TargetMachine::CGFT_Null:\n OutputFilename += \".null\";\n break;\n }\n }\n }\n\n \/\/ Decide if we need \"binary\" output.\n bool Binary = false;\n switch (FileType) {\n case TargetMachine::CGFT_AssemblyFile:\n break;\n case TargetMachine::CGFT_ObjectFile:\n case TargetMachine::CGFT_Null:\n Binary = true;\n break;\n }\n\n \/\/ Open the file.\n std::string error;\n unsigned OpenFlags = 0;\n if (Binary) OpenFlags |= raw_fd_ostream::F_Binary;\n tool_output_file *FDOut = new tool_output_file(OutputFilename.c_str(), error,\n OpenFlags);\n if (!error.empty()) {\n errs() << error << '\\n';\n delete FDOut;\n return 0;\n }\n\n return FDOut;\n}\n\n\/\/ main - Entry point for the llc compiler.\n\/\/\nint main(int argc, char **argv) {\n sys::PrintStackTraceOnErrorSignal();\n PrettyStackTraceProgram X(argc, argv);\n\n \/\/ Enable debug stream buffering.\n EnableDebugBuffering = true;\n\n LLVMContext &Context = getGlobalContext();\n llvm_shutdown_obj Y; \/\/ Call llvm_shutdown() on exit.\n\n \/\/ Initialize targets first, so that --version shows registered targets.\n InitializeAllTargets();\n InitializeAllTargetMCs();\n InitializeAllAsmPrinters();\n InitializeAllAsmParsers();\n\n \/\/ Initialize codegen and IR passes used by llc so that the -print-after,\n \/\/ -print-before, and -stop-after options work.\n PassRegistry *Registry = PassRegistry::getPassRegistry();\n initializeCore(*Registry);\n initializeCodeGen(*Registry);\n initializeLoopStrengthReducePass(*Registry);\n initializeLowerIntrinsicsPass(*Registry);\n initializeUnreachableBlockElimPass(*Registry);\n\n \/\/ Register the target printer for --version.\n cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);\n\n cl::ParseCommandLineOptions(argc, argv, \"llvm system compiler\\n\");\n\n \/\/ Load the module to be compiled...\n SMDiagnostic Err;\n std::auto_ptr<Module> M;\n Module *mod = 0;\n Triple TheTriple;\n\n bool SkipModule = MCPU == \"help\" ||\n (!MAttrs.empty() && MAttrs.front() == \"help\");\n\n \/\/ If user just wants to list available options, skip module loading\n if (!SkipModule) {\n M.reset(ParseIRFile(InputFilename, Err, Context));\n mod = M.get();\n if (mod == 0) {\n Err.print(argv[0], errs());\n return 1;\n }\n\n \/\/ If we are supposed to override the target triple, do so now.\n if (!TargetTriple.empty())\n mod->setTargetTriple(Triple::normalize(TargetTriple));\n TheTriple = Triple(mod->getTargetTriple());\n } else {\n TheTriple = Triple(Triple::normalize(TargetTriple));\n }\n\n if (TheTriple.getTriple().empty())\n TheTriple.setTriple(sys::getDefaultTargetTriple());\n\n \/\/ Get the target specific parser.\n std::string Error;\n const Target *TheTarget = TargetRegistry::lookupTarget(MArch, TheTriple,\n Error);\n if (!TheTarget) {\n errs() << argv[0] << \": \" << Error;\n return 1;\n }\n\n \/\/ Package up features to be passed to target\/subtarget\n std::string FeaturesStr;\n if (MAttrs.size()) {\n SubtargetFeatures Features;\n for (unsigned i = 0; i != MAttrs.size(); ++i)\n Features.AddFeature(MAttrs[i]);\n FeaturesStr = Features.getString();\n }\n\n CodeGenOpt::Level OLvl = CodeGenOpt::Default;\n switch (OptLevel) {\n default:\n errs() << argv[0] << \": invalid optimization level.\\n\";\n return 1;\n case ' ': break;\n case '0': OLvl = CodeGenOpt::None; break;\n case '1': OLvl = CodeGenOpt::Less; break;\n case '2': OLvl = CodeGenOpt::Default; break;\n case '3': OLvl = CodeGenOpt::Aggressive; break;\n }\n\n TargetOptions Options;\n Options.LessPreciseFPMADOption = EnableFPMAD;\n Options.NoFramePointerElim = DisableFPElim;\n Options.NoFramePointerElimNonLeaf = DisableFPElimNonLeaf;\n Options.AllowFPOpFusion = FuseFPOps;\n Options.UnsafeFPMath = EnableUnsafeFPMath;\n Options.NoInfsFPMath = EnableNoInfsFPMath;\n Options.NoNaNsFPMath = EnableNoNaNsFPMath;\n Options.HonorSignDependentRoundingFPMathOption =\n EnableHonorSignDependentRoundingFPMath;\n Options.UseSoftFloat = GenerateSoftFloatCalls;\n if (FloatABIForCalls != FloatABI::Default)\n Options.FloatABIType = FloatABIForCalls;\n Options.NoZerosInBSS = DontPlaceZerosInBSS;\n Options.GuaranteedTailCallOpt = EnableGuaranteedTailCallOpt;\n Options.DisableTailCalls = DisableTailCalls;\n Options.StackAlignmentOverride = OverrideStackAlignment;\n Options.RealignStack = EnableRealignStack;\n Options.TrapFuncName = TrapFuncName;\n Options.PositionIndependentExecutable = EnablePIE;\n Options.EnableSegmentedStacks = SegmentedStacks;\n Options.UseInitArray = UseInitArray;\n Options.SSPBufferSize = SSPBufferSize;\n\n std::auto_ptr<TargetMachine>\n target(TheTarget->createTargetMachine(TheTriple.getTriple(),\n MCPU, FeaturesStr, Options,\n RelocModel, CMModel, OLvl));\n assert(target.get() && \"Could not allocate target machine!\");\n assert(mod && \"Should have exited after outputting help!\");\n TargetMachine &Target = *target.get();\n\n if (DisableDotLoc)\n Target.setMCUseLoc(false);\n\n if (DisableCFI)\n Target.setMCUseCFI(false);\n\n if (EnableDwarfDirectory)\n Target.setMCUseDwarfDirectory(true);\n\n if (GenerateSoftFloatCalls)\n FloatABIForCalls = FloatABI::Soft;\n\n \/\/ Disable .loc support for older OS X versions.\n if (TheTriple.isMacOSX() &&\n TheTriple.isMacOSXVersionLT(10, 6))\n Target.setMCUseLoc(false);\n\n \/\/ Figure out where we are going to send the output.\n OwningPtr<tool_output_file> Out\n (GetOutputStream(TheTarget->getName(), TheTriple.getOS(), argv[0]));\n if (!Out) return 1;\n\n \/\/ Build up all of the passes that we want to do to the module.\n PassManager PM;\n\n \/\/ Add an appropriate TargetLibraryInfo pass for the module's triple.\n TargetLibraryInfo *TLI = new TargetLibraryInfo(TheTriple);\n if (DisableSimplifyLibCalls)\n TLI->disableAllFunctions();\n PM.add(TLI);\n\n if (target.get()) {\n PM.add(new TargetTransformInfo(target->getScalarTargetTransformInfo(),\n target->getVectorTargetTransformInfo()));\n }\n\n \/\/ Add the target data from the target machine, if it exists, or the module.\n if (const DataLayout *TD = Target.getDataLayout())\n PM.add(new DataLayout(*TD));\n else\n PM.add(new DataLayout(mod));\n\n \/\/ Override default to generate verbose assembly.\n Target.setAsmVerbosityDefault(true);\n\n if (RelaxAll) {\n if (FileType != TargetMachine::CGFT_ObjectFile)\n errs() << argv[0]\n << \": warning: ignoring -mc-relax-all because filetype != obj\";\n else\n Target.setMCRelaxAll(true);\n }\n\n {\n formatted_raw_ostream FOS(Out->os());\n\n AnalysisID StartAfterID = 0;\n AnalysisID StopAfterID = 0;\n const PassRegistry *PR = PassRegistry::getPassRegistry();\n if (!StartAfter.empty()) {\n const PassInfo *PI = PR->getPassInfo(StartAfter);\n if (!PI) {\n errs() << argv[0] << \": start-after pass is not registered.\\n\";\n return 1;\n }\n StartAfterID = PI->getTypeInfo();\n }\n if (!StopAfter.empty()) {\n const PassInfo *PI = PR->getPassInfo(StopAfter);\n if (!PI) {\n errs() << argv[0] << \": stop-after pass is not registered.\\n\";\n return 1;\n }\n StopAfterID = PI->getTypeInfo();\n }\n\n \/\/ Ask the target to add backend passes as necessary.\n if (Target.addPassesToEmitFile(PM, FOS, FileType, NoVerify,\n StartAfterID, StopAfterID)) {\n errs() << argv[0] << \": target does not support generation of this\"\n << \" file type!\\n\";\n return 1;\n }\n\n \/\/ Before executing passes, print the final values of the LLVM options.\n cl::PrintOptionValues();\n\n PM.run(*mod);\n }\n\n \/\/ Declare success.\n Out->keep();\n\n return 0;\n}\n<commit_msg>Add a -time-compilations=<N> option to llc.<commit_after>\/\/===-- llc.cpp - Implement the LLVM Native Code Generator ----------------===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This is the llc code generator driver. It provides a convenient\n\/\/ command-line interface for generating native assembly-language code\n\/\/ or C code, given LLVM bitcode.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/LLVMContext.h\"\n#include \"llvm\/DataLayout.h\"\n#include \"llvm\/Module.h\"\n#include \"llvm\/PassManager.h\"\n#include \"llvm\/Pass.h\"\n#include \"llvm\/ADT\/Triple.h\"\n#include \"llvm\/Assembly\/PrintModulePass.h\"\n#include \"llvm\/Support\/IRReader.h\"\n#include \"llvm\/CodeGen\/CommandFlags.h\"\n#include \"llvm\/CodeGen\/LinkAllAsmWriterComponents.h\"\n#include \"llvm\/CodeGen\/LinkAllCodegenComponents.h\"\n#include \"llvm\/MC\/SubtargetFeature.h\"\n#include \"llvm\/Support\/CommandLine.h\"\n#include \"llvm\/Support\/Debug.h\"\n#include \"llvm\/Support\/FormattedStream.h\"\n#include \"llvm\/Support\/ManagedStatic.h\"\n#include \"llvm\/Support\/PluginLoader.h\"\n#include \"llvm\/Support\/PrettyStackTrace.h\"\n#include \"llvm\/Support\/ToolOutputFile.h\"\n#include \"llvm\/Support\/Host.h\"\n#include \"llvm\/Support\/Signals.h\"\n#include \"llvm\/Support\/TargetRegistry.h\"\n#include \"llvm\/Support\/TargetSelect.h\"\n#include \"llvm\/Target\/TargetLibraryInfo.h\"\n#include \"llvm\/Target\/TargetMachine.h\"\n#include <memory>\nusing namespace llvm;\n\n\/\/ General options for llc. Other pass-specific options are specified\n\/\/ within the corresponding llc passes, and target-specific options\n\/\/ and back-end code generation options are specified with the target machine.\n\/\/\nstatic cl::opt<std::string>\nInputFilename(cl::Positional, cl::desc(\"<input bitcode>\"), cl::init(\"-\"));\n\nstatic cl::opt<std::string>\nOutputFilename(\"o\", cl::desc(\"Output filename\"), cl::value_desc(\"filename\"));\n\nstatic cl::opt<unsigned>\nTimeCompilations(\"time-compilations\", cl::Hidden, cl::init(1u),\n cl::value_desc(\"N\"),\n cl::desc(\"Repeat compilation N times for timing\"));\n\n\/\/ Determine optimization level.\nstatic cl::opt<char>\nOptLevel(\"O\",\n cl::desc(\"Optimization level. [-O0, -O1, -O2, or -O3] \"\n \"(default = '-O2')\"),\n cl::Prefix,\n cl::ZeroOrMore,\n cl::init(' '));\n\nstatic cl::opt<std::string>\nTargetTriple(\"mtriple\", cl::desc(\"Override target triple for module\"));\n\ncl::opt<bool> NoVerify(\"disable-verify\", cl::Hidden,\n cl::desc(\"Do not verify input module\"));\n\ncl::opt<bool>\nDisableSimplifyLibCalls(\"disable-simplify-libcalls\",\n cl::desc(\"Disable simplify-libcalls\"),\n cl::init(false));\n\nstatic int compileModule(char**, LLVMContext&);\n\n\/\/ GetFileNameRoot - Helper function to get the basename of a filename.\nstatic inline std::string\nGetFileNameRoot(const std::string &InputFilename) {\n std::string IFN = InputFilename;\n std::string outputFilename;\n int Len = IFN.length();\n if ((Len > 2) &&\n IFN[Len-3] == '.' &&\n ((IFN[Len-2] == 'b' && IFN[Len-1] == 'c') ||\n (IFN[Len-2] == 'l' && IFN[Len-1] == 'l'))) {\n outputFilename = std::string(IFN.begin(), IFN.end()-3); \/\/ s\/.bc\/.s\/\n } else {\n outputFilename = IFN;\n }\n return outputFilename;\n}\n\nstatic tool_output_file *GetOutputStream(const char *TargetName,\n Triple::OSType OS,\n const char *ProgName) {\n \/\/ If we don't yet have an output filename, make one.\n if (OutputFilename.empty()) {\n if (InputFilename == \"-\")\n OutputFilename = \"-\";\n else {\n OutputFilename = GetFileNameRoot(InputFilename);\n\n switch (FileType) {\n case TargetMachine::CGFT_AssemblyFile:\n if (TargetName[0] == 'c') {\n if (TargetName[1] == 0)\n OutputFilename += \".cbe.c\";\n else if (TargetName[1] == 'p' && TargetName[2] == 'p')\n OutputFilename += \".cpp\";\n else\n OutputFilename += \".s\";\n } else\n OutputFilename += \".s\";\n break;\n case TargetMachine::CGFT_ObjectFile:\n if (OS == Triple::Win32)\n OutputFilename += \".obj\";\n else\n OutputFilename += \".o\";\n break;\n case TargetMachine::CGFT_Null:\n OutputFilename += \".null\";\n break;\n }\n }\n }\n\n \/\/ Decide if we need \"binary\" output.\n bool Binary = false;\n switch (FileType) {\n case TargetMachine::CGFT_AssemblyFile:\n break;\n case TargetMachine::CGFT_ObjectFile:\n case TargetMachine::CGFT_Null:\n Binary = true;\n break;\n }\n\n \/\/ Open the file.\n std::string error;\n unsigned OpenFlags = 0;\n if (Binary) OpenFlags |= raw_fd_ostream::F_Binary;\n tool_output_file *FDOut = new tool_output_file(OutputFilename.c_str(), error,\n OpenFlags);\n if (!error.empty()) {\n errs() << error << '\\n';\n delete FDOut;\n return 0;\n }\n\n return FDOut;\n}\n\n\/\/ main - Entry point for the llc compiler.\n\/\/\nint main(int argc, char **argv) {\n sys::PrintStackTraceOnErrorSignal();\n PrettyStackTraceProgram X(argc, argv);\n\n \/\/ Enable debug stream buffering.\n EnableDebugBuffering = true;\n\n LLVMContext &Context = getGlobalContext();\n llvm_shutdown_obj Y; \/\/ Call llvm_shutdown() on exit.\n\n \/\/ Initialize targets first, so that --version shows registered targets.\n InitializeAllTargets();\n InitializeAllTargetMCs();\n InitializeAllAsmPrinters();\n InitializeAllAsmParsers();\n\n \/\/ Initialize codegen and IR passes used by llc so that the -print-after,\n \/\/ -print-before, and -stop-after options work.\n PassRegistry *Registry = PassRegistry::getPassRegistry();\n initializeCore(*Registry);\n initializeCodeGen(*Registry);\n initializeLoopStrengthReducePass(*Registry);\n initializeLowerIntrinsicsPass(*Registry);\n initializeUnreachableBlockElimPass(*Registry);\n\n \/\/ Register the target printer for --version.\n cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);\n\n cl::ParseCommandLineOptions(argc, argv, \"llvm system compiler\\n\");\n\n \/\/ Compile the module TimeCompilations times to give better compile time\n \/\/ metrics.\n for (unsigned I = TimeCompilations; I; --I)\n if (int RetVal = compileModule(argv, Context))\n return RetVal;\n return 0;\n}\n\nstatic int compileModule(char **argv, LLVMContext &Context) {\n \/\/ Load the module to be compiled...\n SMDiagnostic Err;\n std::auto_ptr<Module> M;\n Module *mod = 0;\n Triple TheTriple;\n\n bool SkipModule = MCPU == \"help\" ||\n (!MAttrs.empty() && MAttrs.front() == \"help\");\n\n \/\/ If user just wants to list available options, skip module loading\n if (!SkipModule) {\n M.reset(ParseIRFile(InputFilename, Err, Context));\n mod = M.get();\n if (mod == 0) {\n Err.print(argv[0], errs());\n return 1;\n }\n\n \/\/ If we are supposed to override the target triple, do so now.\n if (!TargetTriple.empty())\n mod->setTargetTriple(Triple::normalize(TargetTriple));\n TheTriple = Triple(mod->getTargetTriple());\n } else {\n TheTriple = Triple(Triple::normalize(TargetTriple));\n }\n\n if (TheTriple.getTriple().empty())\n TheTriple.setTriple(sys::getDefaultTargetTriple());\n\n \/\/ Get the target specific parser.\n std::string Error;\n const Target *TheTarget = TargetRegistry::lookupTarget(MArch, TheTriple,\n Error);\n if (!TheTarget) {\n errs() << argv[0] << \": \" << Error;\n return 1;\n }\n\n \/\/ Package up features to be passed to target\/subtarget\n std::string FeaturesStr;\n if (MAttrs.size()) {\n SubtargetFeatures Features;\n for (unsigned i = 0; i != MAttrs.size(); ++i)\n Features.AddFeature(MAttrs[i]);\n FeaturesStr = Features.getString();\n }\n\n CodeGenOpt::Level OLvl = CodeGenOpt::Default;\n switch (OptLevel) {\n default:\n errs() << argv[0] << \": invalid optimization level.\\n\";\n return 1;\n case ' ': break;\n case '0': OLvl = CodeGenOpt::None; break;\n case '1': OLvl = CodeGenOpt::Less; break;\n case '2': OLvl = CodeGenOpt::Default; break;\n case '3': OLvl = CodeGenOpt::Aggressive; break;\n }\n\n TargetOptions Options;\n Options.LessPreciseFPMADOption = EnableFPMAD;\n Options.NoFramePointerElim = DisableFPElim;\n Options.NoFramePointerElimNonLeaf = DisableFPElimNonLeaf;\n Options.AllowFPOpFusion = FuseFPOps;\n Options.UnsafeFPMath = EnableUnsafeFPMath;\n Options.NoInfsFPMath = EnableNoInfsFPMath;\n Options.NoNaNsFPMath = EnableNoNaNsFPMath;\n Options.HonorSignDependentRoundingFPMathOption =\n EnableHonorSignDependentRoundingFPMath;\n Options.UseSoftFloat = GenerateSoftFloatCalls;\n if (FloatABIForCalls != FloatABI::Default)\n Options.FloatABIType = FloatABIForCalls;\n Options.NoZerosInBSS = DontPlaceZerosInBSS;\n Options.GuaranteedTailCallOpt = EnableGuaranteedTailCallOpt;\n Options.DisableTailCalls = DisableTailCalls;\n Options.StackAlignmentOverride = OverrideStackAlignment;\n Options.RealignStack = EnableRealignStack;\n Options.TrapFuncName = TrapFuncName;\n Options.PositionIndependentExecutable = EnablePIE;\n Options.EnableSegmentedStacks = SegmentedStacks;\n Options.UseInitArray = UseInitArray;\n Options.SSPBufferSize = SSPBufferSize;\n\n std::auto_ptr<TargetMachine>\n target(TheTarget->createTargetMachine(TheTriple.getTriple(),\n MCPU, FeaturesStr, Options,\n RelocModel, CMModel, OLvl));\n assert(target.get() && \"Could not allocate target machine!\");\n assert(mod && \"Should have exited after outputting help!\");\n TargetMachine &Target = *target.get();\n\n if (DisableDotLoc)\n Target.setMCUseLoc(false);\n\n if (DisableCFI)\n Target.setMCUseCFI(false);\n\n if (EnableDwarfDirectory)\n Target.setMCUseDwarfDirectory(true);\n\n if (GenerateSoftFloatCalls)\n FloatABIForCalls = FloatABI::Soft;\n\n \/\/ Disable .loc support for older OS X versions.\n if (TheTriple.isMacOSX() &&\n TheTriple.isMacOSXVersionLT(10, 6))\n Target.setMCUseLoc(false);\n\n \/\/ Figure out where we are going to send the output.\n OwningPtr<tool_output_file> Out\n (GetOutputStream(TheTarget->getName(), TheTriple.getOS(), argv[0]));\n if (!Out) return 1;\n\n \/\/ Build up all of the passes that we want to do to the module.\n PassManager PM;\n\n \/\/ Add an appropriate TargetLibraryInfo pass for the module's triple.\n TargetLibraryInfo *TLI = new TargetLibraryInfo(TheTriple);\n if (DisableSimplifyLibCalls)\n TLI->disableAllFunctions();\n PM.add(TLI);\n\n if (target.get()) {\n PM.add(new TargetTransformInfo(target->getScalarTargetTransformInfo(),\n target->getVectorTargetTransformInfo()));\n }\n\n \/\/ Add the target data from the target machine, if it exists, or the module.\n if (const DataLayout *TD = Target.getDataLayout())\n PM.add(new DataLayout(*TD));\n else\n PM.add(new DataLayout(mod));\n\n \/\/ Override default to generate verbose assembly.\n Target.setAsmVerbosityDefault(true);\n\n if (RelaxAll) {\n if (FileType != TargetMachine::CGFT_ObjectFile)\n errs() << argv[0]\n << \": warning: ignoring -mc-relax-all because filetype != obj\";\n else\n Target.setMCRelaxAll(true);\n }\n\n {\n formatted_raw_ostream FOS(Out->os());\n\n AnalysisID StartAfterID = 0;\n AnalysisID StopAfterID = 0;\n const PassRegistry *PR = PassRegistry::getPassRegistry();\n if (!StartAfter.empty()) {\n const PassInfo *PI = PR->getPassInfo(StartAfter);\n if (!PI) {\n errs() << argv[0] << \": start-after pass is not registered.\\n\";\n return 1;\n }\n StartAfterID = PI->getTypeInfo();\n }\n if (!StopAfter.empty()) {\n const PassInfo *PI = PR->getPassInfo(StopAfter);\n if (!PI) {\n errs() << argv[0] << \": stop-after pass is not registered.\\n\";\n return 1;\n }\n StopAfterID = PI->getTypeInfo();\n }\n\n \/\/ Ask the target to add backend passes as necessary.\n if (Target.addPassesToEmitFile(PM, FOS, FileType, NoVerify,\n StartAfterID, StopAfterID)) {\n errs() << argv[0] << \": target does not support generation of this\"\n << \" file type!\\n\";\n return 1;\n }\n\n \/\/ Before executing passes, print the final values of the LLVM options.\n cl::PrintOptionValues();\n\n PM.run(*mod);\n }\n\n \/\/ Declare success.\n Out->keep();\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/===- lli.cpp - LLVM Interpreter \/ Dynamic compiler ----------------------===\/\/\n\/\/\n\/\/ This utility provides a way to execute LLVM bytecode without static\n\/\/ compilation. This consists of a very simple and slow (but portable)\n\/\/ interpreter, along with capability for system specific dynamic compilers. At\n\/\/ runtime, the fastest (stable) execution engine is selected to run the\n\/\/ program. This means the JIT compiler for the current platform if it's\n\/\/ available.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"ExecutionEngine.h\"\n#include \"Support\/CommandLine.h\"\n#include \"llvm\/Bytecode\/Reader.h\"\n#include \"llvm\/Module.h\"\n#include \"llvm\/Target\/TargetMachineImpls.h\"\n\nnamespace {\n cl::opt<std::string>\n InputFile(cl::desc(\"<input bytecode>\"), cl::Positional, cl::init(\"-\"));\n\n cl::list<std::string>\n InputArgv(cl::ConsumeAfter, cl::desc(\"<program arguments>...\"));\n\n cl::opt<std::string>\n MainFunction (\"f\", cl::desc(\"Function to execute\"), cl::init(\"main\"),\n\t\tcl::value_desc(\"function name\"));\n\n cl::opt<bool> DebugMode(\"d\", cl::desc(\"Start program in debugger\"));\n\n cl::opt<bool> TraceMode(\"trace\", cl::desc(\"Enable Tracing\"));\n\n cl::opt<bool> ForceInterpreter(\"force-interpreter\",\n\t\t\t\t cl::desc(\"Force interpretation: disable JIT\"),\n\t\t\t\t cl::init(true));\n}\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ ExecutionEngine Class Implementation\n\/\/\n\nExecutionEngine::~ExecutionEngine() {\n delete &CurMod;\n}\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ main Driver function\n\/\/\nint main(int argc, char** argv) {\n cl::ParseCommandLineOptions(argc, argv,\n\t\t\t \" llvm interpreter & dynamic compiler\\n\");\n\n \/\/ Load the bytecode...\n std::string ErrorMsg;\n Module *M = ParseBytecodeFile(InputFile, &ErrorMsg);\n if (M == 0) {\n std::cout << \"Error parsing '\" << InputFile << \"': \"\n << ErrorMsg << \"\\n\";\n exit(1);\n }\n\n#if 0\n \/\/ Link in the runtime library for LLI...\n std::string RuntimeLib = getCurrentExecutablePath();\n if (!RuntimeLib.empty()) RuntimeLib += \"\/\";\n RuntimeLib += \"RuntimeLib.bc\";\n\n if (Module *SupportLib = ParseBytecodeFile(RuntimeLib, &ErrorMsg)) {\n if (LinkModules(M, SupportLib, &ErrorMsg))\n std::cerr << \"Error Linking runtime library into current module: \"\n << ErrorMsg << \"\\n\";\n } else {\n std::cerr << \"Error loading runtime library '\"+RuntimeLib+\"': \"\n << ErrorMsg << \"\\n\";\n }\n#endif\n\n unsigned Config = (M->isLittleEndian() ? TM::LittleEndian : TM::BigEndian) |\n (M->has32BitPointers() ? TM::PtrSize32 : TM::PtrSize64);\n ExecutionEngine *EE = 0;\n\n \/\/ If there is nothing that is forcing us to use the interpreter, make a JIT.\n if (!ForceInterpreter && !DebugMode && !TraceMode)\n EE = ExecutionEngine::createJIT(M, Config);\n\n \/\/ If we can't make a JIT, make an interpreter instead.\n if (EE == 0)\n EE = ExecutionEngine::createInterpreter(M, Config, DebugMode, TraceMode);\n\n \/\/ Add the module name to the start of the argv vector...\n InputArgv.insert(InputArgv.begin(), InputFile);\n\n \/\/ Run the main function!\n int ExitCode = EE->run(MainFunction, InputArgv);\n\n \/\/ Now that we are done executing the program, shut down the execution engine\n delete EE;\n return ExitCode;\n}\n<commit_msg>The JIT is the default mode for LLI now<commit_after>\/\/===- lli.cpp - LLVM Interpreter \/ Dynamic compiler ----------------------===\/\/\n\/\/\n\/\/ This utility provides a way to execute LLVM bytecode without static\n\/\/ compilation. This consists of a very simple and slow (but portable)\n\/\/ interpreter, along with capability for system specific dynamic compilers. At\n\/\/ runtime, the fastest (stable) execution engine is selected to run the\n\/\/ program. This means the JIT compiler for the current platform if it's\n\/\/ available.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"ExecutionEngine.h\"\n#include \"Support\/CommandLine.h\"\n#include \"llvm\/Bytecode\/Reader.h\"\n#include \"llvm\/Module.h\"\n#include \"llvm\/Target\/TargetMachineImpls.h\"\n\nnamespace {\n cl::opt<std::string>\n InputFile(cl::desc(\"<input bytecode>\"), cl::Positional, cl::init(\"-\"));\n\n cl::list<std::string>\n InputArgv(cl::ConsumeAfter, cl::desc(\"<program arguments>...\"));\n\n cl::opt<std::string>\n MainFunction (\"f\", cl::desc(\"Function to execute\"), cl::init(\"main\"),\n\t\tcl::value_desc(\"function name\"));\n\n cl::opt<bool> DebugMode(\"d\", cl::desc(\"Start program in debugger\"));\n\n cl::opt<bool> TraceMode(\"trace\", cl::desc(\"Enable Tracing\"));\n\n cl::opt<bool> ForceInterpreter(\"force-interpreter\",\n\t\t\t\t cl::desc(\"Force interpretation: disable JIT\"),\n\t\t\t\t cl::init(false));\n}\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ ExecutionEngine Class Implementation\n\/\/\n\nExecutionEngine::~ExecutionEngine() {\n delete &CurMod;\n}\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ main Driver function\n\/\/\nint main(int argc, char** argv) {\n cl::ParseCommandLineOptions(argc, argv,\n\t\t\t \" llvm interpreter & dynamic compiler\\n\");\n\n \/\/ Load the bytecode...\n std::string ErrorMsg;\n Module *M = ParseBytecodeFile(InputFile, &ErrorMsg);\n if (M == 0) {\n std::cout << \"Error parsing '\" << InputFile << \"': \"\n << ErrorMsg << \"\\n\";\n exit(1);\n }\n\n#if 0\n \/\/ Link in the runtime library for LLI...\n std::string RuntimeLib = getCurrentExecutablePath();\n if (!RuntimeLib.empty()) RuntimeLib += \"\/\";\n RuntimeLib += \"RuntimeLib.bc\";\n\n if (Module *SupportLib = ParseBytecodeFile(RuntimeLib, &ErrorMsg)) {\n if (LinkModules(M, SupportLib, &ErrorMsg))\n std::cerr << \"Error Linking runtime library into current module: \"\n << ErrorMsg << \"\\n\";\n } else {\n std::cerr << \"Error loading runtime library '\"+RuntimeLib+\"': \"\n << ErrorMsg << \"\\n\";\n }\n#endif\n\n unsigned Config = (M->isLittleEndian() ? TM::LittleEndian : TM::BigEndian) |\n (M->has32BitPointers() ? TM::PtrSize32 : TM::PtrSize64);\n ExecutionEngine *EE = 0;\n\n \/\/ If there is nothing that is forcing us to use the interpreter, make a JIT.\n if (!ForceInterpreter && !DebugMode && !TraceMode)\n EE = ExecutionEngine::createJIT(M, Config);\n\n \/\/ If we can't make a JIT, make an interpreter instead.\n if (EE == 0)\n EE = ExecutionEngine::createInterpreter(M, Config, DebugMode, TraceMode);\n\n \/\/ Add the module name to the start of the argv vector...\n InputArgv.insert(InputArgv.begin(), InputFile);\n\n \/\/ Run the main function!\n int ExitCode = EE->run(MainFunction, InputArgv);\n\n \/\/ Now that we are done executing the program, shut down the execution engine\n delete EE;\n return ExitCode;\n}\n<|endoftext|>"} {"text":"<commit_before>#include <chord.h>\n#include <location.h>\n#include <locationtable.h>\n#include <dhash_common.h>\n#include <dhash.h>\n#include <misc_utils.h>\n#include \"dhblock.h\"\n#include \"download.h\"\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ dhash_download -- downloads a block of a specific chord node. That node\n\/\/ should already be in the location table.\n\ndhash_download::dhash_download (ptr<vnode> clntnode, chord_node source,\n\t\t\t\tblockID blockID, char *data, u_int len,\n\t\t\t\tu_int totsz, int cookie, cbretrieve_t cb,\n\t\t\t\tcbtmo_t cb_tmo)\n : clntnode (clntnode), npending (0), error (false), source (source), \n\t\t\t\t blckID (blockID), cb (cb), cb_tmo (cb_tmo),\n\t\t\t\t nextchunk (0), numchunks (0), \n\t\t\t\t didrexmit (false)\n{\n start = getusec ();\n \/\/ the first chunk of data may be passed in\n if (data) {\n process_first_chunk (data, len, totsz, cookie);\n check_finish ();\n } else {\n unsigned mtu = (clntnode->my_location ()->id () == source.x)\n ? 8192 : dhblock::dhash_mtu ();\n getchunk (0, mtu, 0, wrap (this, &dhash_download::first_chunk_cb));\n }\n}\n\ndhash_download::~dhash_download ()\n{\n if (buffer) {\n free (buffer);\n buffer = NULL;\n }\n}\n\nvoid\ndhash_download::getchunk (u_int start, u_int len, int cookie, gotchunkcb_t cb)\n{\n ptr<s_dhash_fetch_arg> arg = New refcounted<s_dhash_fetch_arg>;\n arg->key = blckID.ID;\n arg->ctype = blckID.ctype;\n arg->start = start;\n arg->len = len;\n arg->cookie = cookie;\n\n npending++;\n ptr<dhash_fetchiter_res> res = New refcounted<dhash_fetchiter_res> ();\n\n long seqno = clntnode->doRPC \n (source, dhash_program_1, DHASHPROC_FETCHITER, arg, res, \n wrap (this, &dhash_download::gotchunk, cb, res, numchunks++),\n cb_tmo);\n\n seqnos.push_back (seqno);\n}\n \nvoid\ndhash_download::gotchunk (gotchunkcb_t cb, ptr<dhash_fetchiter_res> res,\n\t\t\t int chunknum, clnt_stat err)\n{\n (*cb) (res, chunknum, err);\n}\n\nvoid\ndhash_download::first_chunk_cb (ptr<dhash_fetchiter_res> res, int chunknum,\n\t\t\t\t clnt_stat err)\n{\n npending--;\n\n if (err || (res && res->status != DHASH_COMPLETE))\n fail (dhasherr2str (res->status));\n else {\n int cookie = res->compl_res->cookie;\n size_t totsz = res->compl_res->attr.size;\n size_t datalen = res->compl_res->res.size ();\n char *data = res->compl_res->res.base ();\n process_first_chunk (data, datalen, totsz, cookie);\n }\n check_finish ();\n}\n\nvoid\ndhash_download::process_first_chunk (char *data, size_t datalen, size_t totsz,\n\t\t\t\t int cookie)\n{\n buf_len = totsz;\n buffer = (char *)malloc (buf_len);\n\n nextchunk++;\n add_data (data, datalen, 0);\n\n \/\/issue the RPCs to get the other chunks\n size_t nread = datalen;\n while (nread < totsz) {\n unsigned mtu = (clntnode->my_location ()->id () == source.x)\n ? 8192 : dhblock::dhash_mtu ();\n int length = MIN (mtu, totsz - nread);\n getchunk (nread, length, cookie,\n\t wrap (this, &dhash_download::later_chunk_cb));\n nread += length;\n }\n}\n\nvoid\ndhash_download::later_chunk_cb (ptr<dhash_fetchiter_res> res, int chunknum,\n\t\t\t\tclnt_stat err)\n{\n npending--;\n \n if (err || (res && res->status != DHASH_COMPLETE))\n fail (dhasherr2str (res->status));\n else {\n\n if (!didrexmit && (chunknum > nextchunk)) {\n warn << \"FAST retransmit: \" << blckID << \" chunk \"\n\t << nextchunk << \" being retransmitted.\\n\";\n clntnode->resendRPC (seqnos[nextchunk]);\n didrexmit = true; \/\/ be conservative: only fast rexmit once per block\n }\n\n nextchunk++;\n add_data (res->compl_res->res.base (), res->compl_res->res.size (), \n\t res->compl_res->offset);\n }\n check_finish ();\n}\n\nvoid\ndhash_download::add_data (char *data, int len, int off)\n{\n if ((unsigned)(off + len) > (u_int)buf_len)\n fail (strbuf (\"bad chunk: off %d, len %d, block %d\", \n\t\t off, len, buf_len));\n else\n memcpy (buffer + off, data, len);\n}\n\nvoid\ndhash_download::check_finish ()\n{\n if (npending == 0) {\n ptr<dhash_block> block = NULL;\n \/* got all chunks *\/\n if (!error) {\n block = New refcounted<dhash_block> (buffer, buf_len, blckID.ctype);\n block->source = source.x;\n block->hops = 0;\n block->errors = 0;\n }\n (*cb) (block);\n delete this;\n }\n}\n\nvoid\ndhash_download::fail (str errstr)\n{\n warn << \"dhash_download failed: \" << blckID << \": \"\n << errstr << \" at \" << source.x << \"\\n\";\n error = true;\n}\n\n<commit_msg>Initialize memory.<commit_after>#include <chord.h>\n#include <location.h>\n#include <locationtable.h>\n#include <dhash_common.h>\n#include <dhash.h>\n#include <misc_utils.h>\n#include \"dhblock.h\"\n#include \"download.h\"\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ dhash_download -- downloads a block of a specific chord node. That node\n\/\/ should already be in the location table.\n\ndhash_download::dhash_download (ptr<vnode> clntnode, chord_node source,\n\t\t\t\tblockID blockID, char *data, u_int len,\n\t\t\t\tu_int totsz, int cookie, cbretrieve_t cb,\n\t\t\t\tcbtmo_t cb_tmo) :\n clntnode (clntnode),\n npending (0),\n error (false),\n source (source),\n blckID (blockID),\n cb (cb),\n cb_tmo (cb_tmo),\n buffer (NULL),\n buf_len (0),\n nextchunk (0),\n numchunks (0),\n didrexmit (false),\n start (getusec ())\n{\n \/\/ the first chunk of data may be passed in\n if (data) {\n process_first_chunk (data, len, totsz, cookie);\n check_finish ();\n } else {\n unsigned mtu = (clntnode->my_location ()->id () == source.x)\n ? 8192 : dhblock::dhash_mtu ();\n getchunk (0, mtu, 0, wrap (this, &dhash_download::first_chunk_cb));\n }\n}\n\ndhash_download::~dhash_download ()\n{\n if (buffer) {\n free (buffer);\n buffer = NULL;\n }\n}\n\nvoid\ndhash_download::getchunk (u_int start, u_int len, int cookie, gotchunkcb_t cb)\n{\n ptr<s_dhash_fetch_arg> arg = New refcounted<s_dhash_fetch_arg>;\n arg->key = blckID.ID;\n arg->ctype = blckID.ctype;\n arg->start = start;\n arg->len = len;\n arg->cookie = cookie;\n\n npending++;\n ptr<dhash_fetchiter_res> res = New refcounted<dhash_fetchiter_res> ();\n\n long seqno = clntnode->doRPC \n (source, dhash_program_1, DHASHPROC_FETCHITER, arg, res, \n wrap (this, &dhash_download::gotchunk, cb, res, numchunks++),\n cb_tmo);\n\n seqnos.push_back (seqno);\n}\n \nvoid\ndhash_download::gotchunk (gotchunkcb_t cb, ptr<dhash_fetchiter_res> res,\n\t\t\t int chunknum, clnt_stat err)\n{\n (*cb) (res, chunknum, err);\n}\n\nvoid\ndhash_download::first_chunk_cb (ptr<dhash_fetchiter_res> res, int chunknum,\n\t\t\t\t clnt_stat err)\n{\n npending--;\n\n if (err || (res && res->status != DHASH_COMPLETE))\n fail (dhasherr2str (res->status));\n else {\n int cookie = res->compl_res->cookie;\n size_t totsz = res->compl_res->attr.size;\n size_t datalen = res->compl_res->res.size ();\n char *data = res->compl_res->res.base ();\n process_first_chunk (data, datalen, totsz, cookie);\n }\n check_finish ();\n}\n\nvoid\ndhash_download::process_first_chunk (char *data, size_t datalen, size_t totsz,\n\t\t\t\t int cookie)\n{\n buf_len = totsz;\n buffer = (char *)malloc (buf_len);\n\n nextchunk++;\n add_data (data, datalen, 0);\n\n \/\/issue the RPCs to get the other chunks\n size_t nread = datalen;\n while (nread < totsz) {\n unsigned mtu = (clntnode->my_location ()->id () == source.x)\n ? 8192 : dhblock::dhash_mtu ();\n int length = MIN (mtu, totsz - nread);\n getchunk (nread, length, cookie,\n\t wrap (this, &dhash_download::later_chunk_cb));\n nread += length;\n }\n}\n\nvoid\ndhash_download::later_chunk_cb (ptr<dhash_fetchiter_res> res, int chunknum,\n\t\t\t\tclnt_stat err)\n{\n npending--;\n \n if (err || (res && res->status != DHASH_COMPLETE))\n fail (dhasherr2str (res->status));\n else {\n\n if (!didrexmit && (chunknum > nextchunk)) {\n warn << \"FAST retransmit: \" << blckID << \" chunk \"\n\t << nextchunk << \" being retransmitted.\\n\";\n clntnode->resendRPC (seqnos[nextchunk]);\n didrexmit = true; \/\/ be conservative: only fast rexmit once per block\n }\n\n nextchunk++;\n add_data (res->compl_res->res.base (), res->compl_res->res.size (), \n\t res->compl_res->offset);\n }\n check_finish ();\n}\n\nvoid\ndhash_download::add_data (char *data, int len, int off)\n{\n if ((unsigned)(off + len) > (u_int)buf_len)\n fail (strbuf (\"bad chunk: off %d, len %d, block %d\", \n\t\t off, len, buf_len));\n else\n memcpy (buffer + off, data, len);\n}\n\nvoid\ndhash_download::check_finish ()\n{\n if (npending == 0) {\n ptr<dhash_block> block = NULL;\n \/* got all chunks *\/\n if (!error) {\n block = New refcounted<dhash_block> (buffer, buf_len, blckID.ctype);\n block->source = source.x;\n block->hops = 0;\n block->errors = 0;\n }\n (*cb) (block);\n delete this;\n }\n}\n\nvoid\ndhash_download::fail (str errstr)\n{\n warn << \"dhash_download failed: \" << blckID << \": \"\n << errstr << \" at \" << source.x << \"\\n\";\n error = true;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\n\n#include \"RemoteReasoner.h\"\n\n#include \"actasp\/reasoners\/Clingo.h\"\n#include \"actasp\/executors\/ReplanningActionExecutor.h\"\n#include \"actasp\/ActionExecutor.h\"\n#include \"actasp\/AspFluent.h\"\n#include \"actasp\/planners\/AnyPlan.h\"\n\n#include \"actions\/ActionFactory.h\"\n#include \"actions\/LogicalNavigation.h\"\n\n#include <ros\/ros.h>\n#include <ros\/console.h>\n\n#include <boost\/filesystem.hpp>\n\n#include <string>\n\n\nusing namespace std;\nusing namespace bwi_krexec;\nusing namespace actasp;\n\nint main(int argc, char**argv) {\n ros::init(argc, argv, \"bwi_action_execution\");\n ros::NodeHandle n;\n\n if (ros::console::set_logger_level(ROSCONSOLE_DEFAULT_NAME, ros::console::levels::Debug)) {\n ros::console::notifyLoggerLevelsChanged();\n }\n\n\/\/ create initial state\n LogicalNavigation setInitialState(\"noop\");\n setInitialState.run();\n\n ActionFactory::setSimulation(true); \/\/parametrize this\n\n AspKR *reasoner = new RemoteReasoner();\n Planner *planner = new AnyPlan(reasoner);\n ActionExecutor *executor = new ReplanningActionExecutor(reasoner,planner,ActionFactory::actions());\n \n vector<AspRule> goalRules;\n \n goalRules.push_back(AspRule() << AspFluent(\"not visited(l3_418,n)\"));\n goalRules.push_back(AspRule() << AspFluent(\"not visited(l3_414a,n)\"));\n \n executor->setGoal(goalRules);\n \n ros::Rate loop(10);\n \n while (ros::ok() && !executor->goalReached() && !executor->failed()) {\n \n executor->executeActionStep();\n\n ros::spinOnce();\n\n loop.sleep();\n }\n \n delete executor;\n delete reasoner;\n\n return 0;\n}<commit_msg>minor changes in the action executor<commit_after>\n\n#include \"RemoteReasoner.h\"\n\n#include \"actasp\/reasoners\/Clingo.h\"\n#include \"actasp\/executors\/ReplanningActionExecutor.h\"\n#include \"actasp\/ActionExecutor.h\"\n#include \"actasp\/AspFluent.h\"\n#include \"actasp\/planners\/AnyPlan.h\"\n\n#include \"actions\/ActionFactory.h\"\n#include \"actions\/LogicalNavigation.h\"\n\n#include <ros\/ros.h>\n#include <ros\/console.h>\n\n#include <boost\/filesystem.hpp>\n\n#include <string>\n\n\nusing namespace std;\nusing namespace bwi_krexec;\nusing namespace actasp;\n\nint main(int argc, char**argv) {\n ros::init(argc, argv, \"bwi_action_execution\");\n ros::NodeHandle n;\n\n if (ros::console::set_logger_level(ROSCONSOLE_DEFAULT_NAME, ros::console::levels::Debug)) {\n ros::console::notifyLoggerLevelsChanged();\n }\n\n\/\/ create initial state\n LogicalNavigation setInitialState(\"noop\");\n setInitialState.run();\n\n ActionFactory::setSimulation(true); \/\/parametrize this\n\n AspKR *reasoner = new RemoteReasoner();\n ActionExecutor *executor = new ReplanningActionExecutor(reasoner,reasoner,ActionFactory::actions());\n \n vector<AspRule> goalRules(1);\n \n goalRules[0].body.push_back(AspFluent(\"not at(l3_516,I)\"));\n \n executor->setGoal(goalRules);\n \n ros::Rate loop(10);\n \n while (ros::ok() && !executor->goalReached() && !executor->failed()) {\n \n executor->executeActionStep();\n\n ros::spinOnce();\n\n loop.sleep();\n }\n \n if(executor->failed()) {\n ROS_INFO(\"Execution failed\");\n }\n if(executor->goalReached()) {\n ROS_INFO(\"Execution succeded\");\n }\n \n delete executor;\n delete reasoner;\n\n return 0;\n}<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ diana_client.cpp\n\/\/ diana\n\/\/\n\/\/ Created by Raphael Bost on 20\/07\/2016.\n\/\/ Copyright © 2016 Raphael Bost. All rights reserved.\n\/\/\n\n#include \"diana\/client_runner.hpp\"\n#include \"utils\/logger.hpp\"\n#include \"aux\/db_generator.hpp\"\n\n#include <sse\/crypto\/utils.hpp>\n\n\n#include <list>\n#include <mutex>\n#include <iostream>\n\n#include <unistd.h>\n#include <stdio.h>\n\n__thread std::list<std::pair<std::string, uint64_t>> *buffer_list__ = NULL;\n\nint main(int argc, char** argv) {\n sse::logger::set_severity(sse::logger::INFO);\n sse::logger::set_benchmark_file(\"benchmark_diana_client.out\");\n \n sse::crypto::init_crypto_lib();\n \n opterr = 0;\n int c;\n\n std::list<std::string> input_files;\n std::list<std::string> keywords;\n std::string json_file;\n std::string client_db;\n std::string output_path;\n bool print_stats = false;\n uint32_t bench_count = 0;\n uint32_t rnd_entries_count = 0;\n \n bool print_results = true;\n \n while ((c = getopt (argc, argv, \"l:b:o:i:t:dpr:q\")) != -1)\n switch (c)\n {\n case 'l':\n input_files.push_back(std::string(optarg));\n break;\n case 'b':\n client_db = std::string(optarg);\n break;\n case 'o':\n output_path = std::string(optarg);\n break;\n case 'i':\n json_file = std::string(optarg);\n break;\n case 't':\n bench_count = atoi(optarg);\n break;\n case 'd': \/\/ load a default file, only for debugging\n\/\/ input_files.push_back(\"\/Volumes\/Storage\/WP_Inverted\/inverted_index_all_sizes\/inverted_index_10000.json\");\n input_files.push_back(\"\/Users\/raphaelbost\/Documents\/inverted_index_1000.json\");\n break;\n case 'p':\n print_stats = true;\n break;\n case 'q':\n print_results = false;\n break;\n case 'r':\n rnd_entries_count = (uint32_t)std::stod(std::string(optarg),nullptr);\n \/\/atol(optarg);\n break;\n case '?':\n if (optopt == 'l' || optopt == 'b' || optopt == 'o' || optopt == 'i' || optopt == 't' || optopt == 'r')\n fprintf (stderr, \"Option -%c requires an argument.\\n\", optopt);\n else if (isprint (optopt))\n fprintf (stderr, \"Unknown option `-%c'.\\n\", optopt);\n else\n fprintf (stderr,\n \"Unknown option character `\\\\x%x'.\\n\",\n optopt);\n return 1;\n default:\n exit(-1);\n }\n \n \n for (int index = optind; index < argc; index++)\n {\n keywords.push_back(std::string(argv[index]));\n }\n\n if (client_db.size()==0) {\n sse::logger::log(sse::logger::WARNING) << \"Client database not specified\" << std::endl;\n sse::logger::log(sse::logger::WARNING) << \"Using \\'test.dcdb\\' by default\" << std::endl;\n client_db = \"test.dcdb\";\n }else{\n sse::logger::log(sse::logger::INFO) << \"Running client with database \" << client_db << std::endl;\n }\n \n std::unique_ptr<sse::diana::DianaClientRunner> client_runner;\n \n if (json_file.size() > 0) {\n sse::logger::log(sse::logger::CRITICAL) << \"JSON import is not supported in Diana!\" << std::endl;\n\/\/ client_runner.reset( new sse::diana::DianaClientRunner(\"localhost:4241\", client_db, json_file) );\n }else{\n size_t setup_size = 1e5;\n uint32_t n_keywords = 1e4;\n \n if( rnd_entries_count > 0)\n {\n setup_size = 11*rnd_entries_count;\n n_keywords = 1.4*rnd_entries_count\/(10*std::thread::hardware_concurrency());\n }\n \n client_runner.reset( new sse::diana::DianaClientRunner(\"localhost:4241\", client_db, setup_size, n_keywords) );\n }\n\n for (std::string &path : input_files) {\n sse::logger::log(sse::logger::INFO) << \"Load file \" << path << std::endl;\n client_runner->load_inverted_index(path);\n sse::logger::log(sse::logger::INFO) << \"Done loading file \" << path << std::endl;\n }\n \n if (rnd_entries_count > 0) {\n sse::logger::log(sse::logger::INFO) << \"Randomly generating database with \" << rnd_entries_count << \" docs\" << std::endl;\n\n std::mutex buffer_mtx;\n\n auto gen_callback = [&client_runner](const std::string &s, size_t i)\n {\n if (buffer_list__ == NULL) {\n buffer_list__ = new std::list<std::pair<std::string, uint64_t>>();\n }\n buffer_list__->push_back(std::make_pair(s, i));\n \n if (buffer_list__->size() >= 50) {\n client_runner->async_update(*buffer_list__);\n \n buffer_list__->clear();\n }\n\/\/ client_runner->async_update(s, i);\n };\n \n client_runner->start_update_session();\n sse::sophos::gen_db(rnd_entries_count, gen_callback);\n client_runner->end_update_session();\n }\n \n for (std::string &kw : keywords) {\n std::cout << \"-------------- Search --------------\" << std::endl;\n \n std::mutex logger_mtx;\n std::ostream& log_stream = sse::logger::log(sse::logger::INFO);\n bool first = true;\n \n auto print_callback = [&logger_mtx, &log_stream, &first, print_results](uint64_t res)\n {\n if (print_results) {\n logger_mtx.lock();\n\n if (!first) {\n log_stream << \", \";\n }\n first = false;\n log_stream << res;\n \n logger_mtx.unlock();\n }\n };\n \n log_stream << \"Search results: \\n{\";\n\n auto res = client_runner->search(kw, print_callback);\n \n log_stream << \"}\" << std::endl;\n }\n \n \n if (output_path.size()>0) {\n sse::logger::log(sse::logger::CRITICAL) << \"JSON export is not supported in Diana!\" << std::endl;\n\n\/\/ client_runner->output_db(output_path);\n }\n \n if (print_stats)\n {\n client_runner->print_stats(sse::logger::log(sse::logger::INFO));\n }\n \n client_runner.reset();\n \n sse::crypto::cleanup_crypto_lib();\n\n \n return 0;\n}\n<commit_msg>Removed useless CLI options for Diana's client<commit_after>\/\/\n\/\/ diana_client.cpp\n\/\/ diana\n\/\/\n\/\/ Created by Raphael Bost on 20\/07\/2016.\n\/\/ Copyright © 2016 Raphael Bost. All rights reserved.\n\/\/\n\n#include \"diana\/client_runner.hpp\"\n#include \"utils\/logger.hpp\"\n#include \"aux\/db_generator.hpp\"\n\n#include <sse\/crypto\/utils.hpp>\n\n\n#include <list>\n#include <mutex>\n#include <iostream>\n\n#include <unistd.h>\n#include <stdio.h>\n\n__thread std::list<std::pair<std::string, uint64_t>> *buffer_list__ = NULL;\n\nint main(int argc, char** argv) {\n sse::logger::set_severity(sse::logger::INFO);\n sse::logger::set_benchmark_file(\"benchmark_diana_client.out\");\n \n sse::crypto::init_crypto_lib();\n \n opterr = 0;\n int c;\n\n std::list<std::string> input_files;\n std::list<std::string> keywords;\n std::string client_db;\n bool print_stats = false;\n uint32_t rnd_entries_count = 0;\n \n bool print_results = true;\n \n while ((c = getopt (argc, argv, \"l:b:dpr:q\")) != -1)\n switch (c)\n {\n case 'l':\n input_files.push_back(std::string(optarg));\n break;\n case 'b':\n client_db = std::string(optarg);\n break;\n case 'd': \/\/ load a default file, only for debugging\n\/\/ input_files.push_back(\"\/Volumes\/Storage\/WP_Inverted\/inverted_index_all_sizes\/inverted_index_10000.json\");\n input_files.push_back(\"\/Users\/raphaelbost\/Documents\/inverted_index_1000.json\");\n break;\n case 'p':\n print_stats = true;\n break;\n case 'q':\n print_results = false;\n break;\n case 'r':\n rnd_entries_count = (uint32_t)std::stod(std::string(optarg),nullptr);\n \/\/atol(optarg);\n break;\n case '?':\n if (optopt == 'l' || optopt == 'b' || optopt == 'o' || optopt == 'i' || optopt == 't' || optopt == 'r')\n fprintf (stderr, \"Option -%c requires an argument.\\n\", optopt);\n else if (isprint (optopt))\n fprintf (stderr, \"Unknown option `-%c'.\\n\", optopt);\n else\n fprintf (stderr,\n \"Unknown option character `\\\\x%x'.\\n\",\n optopt);\n return 1;\n default:\n exit(-1);\n }\n \n \n for (int index = optind; index < argc; index++)\n {\n keywords.push_back(std::string(argv[index]));\n }\n\n if (client_db.size()==0) {\n sse::logger::log(sse::logger::WARNING) << \"Client database not specified\" << std::endl;\n sse::logger::log(sse::logger::WARNING) << \"Using \\'test.dcdb\\' by default\" << std::endl;\n client_db = \"test.dcdb\";\n }else{\n sse::logger::log(sse::logger::INFO) << \"Running client with database \" << client_db << std::endl;\n }\n \n std::unique_ptr<sse::diana::DianaClientRunner> client_runner;\n \n size_t setup_size = 1e5;\n uint32_t n_keywords = 1e4;\n \n if( rnd_entries_count > 0)\n {\n setup_size = 11*rnd_entries_count;\n n_keywords = 1.4*rnd_entries_count\/(10*std::thread::hardware_concurrency());\n }\n \n client_runner.reset( new sse::diana::DianaClientRunner(\"localhost:4241\", client_db, setup_size, n_keywords) );\n \n for (std::string &path : input_files) {\n sse::logger::log(sse::logger::INFO) << \"Load file \" << path << std::endl;\n client_runner->load_inverted_index(path);\n sse::logger::log(sse::logger::INFO) << \"Done loading file \" << path << std::endl;\n }\n \n if (rnd_entries_count > 0) {\n sse::logger::log(sse::logger::INFO) << \"Randomly generating database with \" << rnd_entries_count << \" docs\" << std::endl;\n\n std::mutex buffer_mtx;\n\n auto gen_callback = [&client_runner](const std::string &s, size_t i)\n {\n if (buffer_list__ == NULL) {\n buffer_list__ = new std::list<std::pair<std::string, uint64_t>>();\n }\n buffer_list__->push_back(std::make_pair(s, i));\n \n if (buffer_list__->size() >= 50) {\n client_runner->async_update(*buffer_list__);\n \n buffer_list__->clear();\n }\n\/\/ client_runner->async_update(s, i);\n };\n \n client_runner->start_update_session();\n sse::sophos::gen_db(rnd_entries_count, gen_callback);\n client_runner->end_update_session();\n }\n \n for (std::string &kw : keywords) {\n std::cout << \"-------------- Search --------------\" << std::endl;\n \n std::mutex logger_mtx;\n std::ostream& log_stream = sse::logger::log(sse::logger::INFO);\n bool first = true;\n \n auto print_callback = [&logger_mtx, &log_stream, &first, print_results](uint64_t res)\n {\n if (print_results) {\n logger_mtx.lock();\n\n if (!first) {\n log_stream << \", \";\n }\n first = false;\n log_stream << res;\n \n logger_mtx.unlock();\n }\n };\n \n log_stream << \"Search results: \\n{\";\n\n auto res = client_runner->search(kw, print_callback);\n \n log_stream << \"}\" << std::endl;\n }\n \n \n if (print_stats)\n {\n client_runner->print_stats(sse::logger::log(sse::logger::INFO));\n }\n \n client_runner.reset();\n \n sse::crypto::cleanup_crypto_lib();\n\n \n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>#ifndef DISPLACEMENT_H\n#define DISPLACEMENT_H\n\n#include <fftw3.h>\n#include <stdint.h>\n#include \"part_data.hpp\"\n\nclass PowerSpec;\n\nclass DisplacementFields\n{\n public:\n DisplacementFields(size_t Nmesh, int Seed, double Box, bool twolpt=true);\n lpt_data displacement_fields(const int type, part_grid& Pgrid, PowerSpec * PSpec, bool RayleighScatter=true);\n ~DisplacementFields();\n private:\n \/\/Takes the computed Fourier displacement field and reads them into lpt_data outdata, using a grid specified in Pgrid.\n double displacement_read_out(const int order, lpt_data& outdata, part_grid& Pgrid, const int axes, const int type);\n \/\/Size of the Fourier grid\n const size_t Nmesh;\n \/\/Do we need a twolpt term?\n const bool twolpt;\n \/\/Seed for the random number generator.\n \/\/Constant for all particle types, so they are coherent.\n const int Seed;\n \/\/Box size\n const double Box;\n \/\/FFT variables for Zeldovich\n fftw_plan Inverse_plan;\n double *Disp;\n \/\/This will always be a cast of Disp\n fftw_complex *Cdata;\n \/\/Pointers for 2LPT term\n fftwf_plan Forward_plan2;\n fftwf_plan Inverse_plan_grad[3];\n float *twosrc;\n fftwf_complex *ctwosrc;\n fftwf_complex *(cdigrad[3]);\n float *(digrad[3]);\n};\n\n#endif\n<commit_msg>Fix compiler warning<commit_after>#ifndef DISPLACEMENT_H\n#define DISPLACEMENT_H\n\n#include <fftw3.h>\n#include <stdint.h>\n#include \"part_data.hpp\"\n\nclass PowerSpec;\n\nclass DisplacementFields\n{\n public:\n DisplacementFields(size_t Nmesh, int Seed, double Box, bool twolpt=true);\n lpt_data displacement_fields(const int type, part_grid& Pgrid, PowerSpec * PSpec, bool RayleighScatter=true);\n ~DisplacementFields();\n private:\n \/\/Takes the computed Fourier displacement field and reads them into lpt_data outdata, using a grid specified in Pgrid.\n double displacement_read_out(const int order, lpt_data& outdata, part_grid& Pgrid, const int axes, const int type);\n \/\/Size of the Fourier grid\n const size_t Nmesh;\n \/\/Do we need a twolpt term?\n const bool twolpt;\n \/\/Seed for the random number generator.\n \/\/Constant for all particle types, so they are coherent.\n const int Seed;\n \/\/Box size\n const double Box;\n \/\/FFT variables for Zeldovich\n fftw_plan Inverse_plan;\n double *Disp;\n \/\/This will always be a cast of Disp\n fftw_complex *Cdata;\n \/\/Pointers for 2LPT term\n fftwf_plan Forward_plan2;\n fftwf_plan Inverse_plan_grad[3];\n float *twosrc;\n fftwf_complex *ctwosrc;\n fftwf_complex *cdigrad[3];\n float *digrad[3];\n};\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/*\nC++ implementation of the PCA fitter\n\nL.Storchi, A.Modak, S.R.Chowdhury : 2016\n*\/\n#include \"..\/interface\/PCATrackFitter.h\"\n#include \"..\/interface\/pcaconst.hpp\"\n\nnamespace \n{\n \/* quick and very dirty *\/\n void dump_element (const pca::matrixpcaconst<double> & in, std::ostream & out)\n {\n out.precision(6);\n for (unsigned int i = 0; i<in.n_rows(); ++i)\n {\n for (unsigned int j = 0; j<in.n_cols(); ++j)\n out << std::scientific << in(i, j) << \" \";\n out << std::endl;\n }\n }\n\n bool import_pca_const (const std::string & cfname, \n pca::matrixpcaconst<double> & cmtx_rz, \n pca::matrixpcaconst<double> & qvec_rz, \n pca::matrixpcaconst<double> & amtx_rz, \n pca::matrixpcaconst<double> & kvec_rz, \n pca::matrixpcaconst<double> & cmtx_rphi, \n pca::matrixpcaconst<double> & qvec_rphi, \n pca::matrixpcaconst<double> & amtx_rphi, \n pca::matrixpcaconst<double> & kvec_rphi, \n double eta, double pt, \n int chargesignin)\n {\n std::vector<pca::matrixpcaconst<double> > vct;\n if (pca::read_pcacosnt_from_file (vct, cfname.c_str()))\n {\n int hwmanygot = 0;\n std::vector<pca::matrixpcaconst<double> >::const_iterator it = \n vct.begin();\n for (; it != vct.end(); ++it)\n {\n double ptmin, ptmax, etamin, etamax;\n int chargesign;\n \n it->get_ptrange(ptmin, ptmax);\n it->get_etarange(etamin, etamax);\n chargesign = it->get_chargesign();\n \n if (it->get_plane_type() == pca::matrixpcaconst<double>::RZ)\n {\n if ((eta >= etamin) && (eta <= etamax)) \n {\n switch(it->get_const_type())\n {\n case pca::matrixpcaconst<double>::QVEC :\n qvec_rz = *it;\n hwmanygot++;\n break;\n case pca::matrixpcaconst<double>::KVEC :\n kvec_rz = *it;\n hwmanygot++;\n break;\n case pca::matrixpcaconst<double>::CMTX :\n cmtx_rz = *it;\n hwmanygot++;\n break;\n case pca::matrixpcaconst<double>::AMTX :\n amtx_rz = *it;\n hwmanygot++;\n break;\n default:\n break;\n }\n } \n }\n else if (it->get_plane_type() == pca::matrixpcaconst<double>::RPHI)\n {\n if (chargesignin == chargesign)\n {\n if ((pt >= ptmin) && (pt <= ptmax))\n {\n switch(it->get_const_type())\n {\n case pca::matrixpcaconst<double>::QVEC : \n qvec_rphi = *it;\n hwmanygot++;\n break;\n case pca::matrixpcaconst<double>::KVEC :\n kvec_rphi = *it;\n hwmanygot++;\n break;\n case pca::matrixpcaconst<double>::CMTX :\n cmtx_rphi = *it;\n hwmanygot++;\n break;\n case pca::matrixpcaconst<double>::AMTX :\n amtx_rphi = *it;\n hwmanygot++;\n break;\n default:\n break;\n }\n }\n } \n }\n }\n \n if (hwmanygot == 8)\n return true;\n else\n {\n std::cerr << \"Found \" << hwmanygot << \" const instead of 8\" << std::endl;\n return false;\n }\n }\n \n \/\/ TODO add consistency check for dims\n \n return false;\n }\n}\n\nPCATrackFitter::PCATrackFitter():TrackFitter(0)\n{\n}\n\nPCATrackFitter::PCATrackFitter(int nb):TrackFitter(nb)\n{\n}\n\nPCATrackFitter::~PCATrackFitter()\n{\n}\n\nvoid PCATrackFitter::initialize()\n{\n}\n\nvoid PCATrackFitter::mergePatterns()\n{\n}\n\n\/\/ Tentative duplicate removal\n\/\/ Not used for the moment\n\nvoid PCATrackFitter::mergeTracks()\n{\n unsigned int index = 0;\n vector<Track*>::iterator it = tracks.begin();\n \n while(it!=tracks.end())\n {\n Track* newTrack = *it;\n bool found = false;\n for(unsigned int i=0;i<index;i++)\n {\n Track* ref = tracks[i];\n float dpt,dphi,dz,deta;\n dpt = fabs(newTrack->getCurve()-ref->getCurve());\n dphi = fabs(newTrack->getPhi0()-ref->getPhi0());\n dz = fabs(newTrack->getZ0()-ref->getZ0());\n deta = fabs(newTrack->getEta0()-ref->getEta0());\n found = (deta<0.02) &&\n\t(dphi<0.005) &&\n\t(dpt<0.1) &&\n\t(dz<0.3);\n \n if(found)\n\tbreak;\n }\n\n if(found)\n tracks.erase(it);\n else\n {\n index++;\n it++;\n }\n }\n}\n\nvoid PCATrackFitter::setTracks(const std::vector<Track*> & intc)\n{\n tracks_ = intc;\n}\n\nvoid PCATrackFitter::fit(vector<Hit*> hits)\n{\n int tow = sector_id; \/\/ The tower ID, necessary to get the phi shift\n\n std::cout << \"In PCA::fit tow: \" << tow << std::endl;\n\n double sec_phi = 0;\n switch (tow%8)\n {\n case 0:\n sec_phi = 0.4;\n break;\n case 1:\n sec_phi = 1.2;\n break;\n case 3:\n sec_phi = 2.0;\n break;\n case 4:\n sec_phi = 2.7;\n break;\n case 5:\n sec_phi = -2.0;\n break;\n case 6:\n sec_phi = -1.2;\n break;\n case 7:\n sec_phi = -0.4;\n break;\n }\n \n double ci = cos(sec_phi);\n double si = sin(sec_phi);\n\n \/\/std::cout << \"tracks_.size() : \" << tracks_.size() << std::endl;\n \n \/*\n std::ofstream xyzfile;\n xyzfile.open (\"PCAxyzfile.txt\");\n\n std::ofstream rpzfile;\n rpzfile.open (\"PCArphizfile.txt\");\n *\/\n\n for(unsigned int tt=0; tt<tracks_.size(); ++tt)\n {\n \/\/vector<int> stubids = tracks_[tt]->getStubs(); \/\/ TODO are they the hits idx ? \n\n \/\/std::cout << \"hits.size() : \" << hits.size() << std::endl;\n\n if (hits.size() == 6)\n {\n pca::matrixpcaconst<double> zrv(1, 12), phirv(1, 12);\n unsigned int coordidx = 0;\n\n for(unsigned int idx = 0; idx < hits.size(); ++idx)\n {\n double xi = hits[idx]->getX()*ci+ hits[idx]->getY()*si;\n double yi = -hits[idx]->getX()*si+ hits[idx]->getY()*ci;\n\n double zi = hits[idx]->getZ();\n double ri = sqrt(xi*xi+yi*yi);\n double pi = atan2(yi,xi);\n\n std::cout << \"PCAxyz \" << xi << \" \" << yi << \" \" << zi << \" \" << \n (int) hits[idx]->getLayer() << std::endl;\n\n std::cout << \"PCArpz \" << xi << \" \" << yi << \" \" << zi << \" \" << \n (int) hits[idx]->getLayer() << std::endl;\n\n \/*\n xyzfile << xi << \" \" << yi << \" \" << zi << \" \" << \n (int) hits[idx]->getLayer() << std::endl;\n\n rpzfile << ri << \" \" << pi << zi << \" \" << \n (int) hits[idx]->getLayer() << std::endl;\n *\/\n\n zrv(0, coordidx) = zi;\n phirv(0, coordidx) = pi;\n\n ++coordidx;\n\n zrv(0, coordidx) = ri;\n phirv(0, coordidx) = ri;\n\n ++coordidx;\n }\n\n int charge;\n double pt_est, eta_est, z0_est, phi_est;\n charge = tracks_[tt]->getCharge(); \n pt_est = tracks_[tt]->getCurve();\n eta_est = tracks_[tt]->getEta0();\n z0_est = tracks_[tt]->getZ0();\n phi_est = tracks_[tt]->getPhi0();\n\n \/* TEST \n zrv(0, 0) = -16.1314; zrv(0, 1) = 23.3135;\n zrv(0, 2) = -22.7054; zrv(0, 3) = 34.8367;\n zrv(0, 4) = -32.6362; zrv(0, 5) = 51.9131;\n eta_est = -0.580448;\n z0_est = -2.65203;\n\n phirv(0, 0) = 2.74588; phirv(0, 1) = 23.2105;\n phirv(0, 2) = 2.76857; phirv(0, 3) = 37.0286;\n phirv(0, 4) = 2.79267; phirv(0, 5) = 51.2692;\n phirv(0, 6) = 2.82109; phirv(0, 7) = 67.7289;\n phirv(0, 8) = 2.85643; phirv(0, 9) = 87.8179;\n phirv(0, 10) = 2.89452; phirv(0, 11) = 109.012;\n pt_est = 1.0\/0.315806;\n phi_est = 2.70006;\n charge = +1;\n *\/\n\n std::string cfname = \".\/barrel_tow18_pca_const.txt\";\n\n pca::matrixpcaconst<double> cmtx_rz(0, 0);\n pca::matrixpcaconst<double> qvec_rz(0, 0); \n pca::matrixpcaconst<double> amtx_rz(0, 0); \n pca::matrixpcaconst<double> kvec_rz(0, 0); \n pca::matrixpcaconst<double> cmtx_rphi(0, 0); \n pca::matrixpcaconst<double> qvec_rphi(0, 0); \n pca::matrixpcaconst<double> amtx_rphi(0, 0); \n pca::matrixpcaconst<double> kvec_rphi(0, 0); \n\n if (import_pca_const (cfname, \n cmtx_rz, \n qvec_rz, \n amtx_rz, \n kvec_rz, \n cmtx_rphi, \n qvec_rphi, \n amtx_rphi, \n kvec_rphi, \n eta_est, \n pt_est, \n charge))\n {\n \/*\n std::cout << \"CMTX RZ: \" << std::endl;\n dump_element(cmtx_rz, std::cout);\n\n std::cout << \"QVEC RZ: \" << std::endl;\n dump_element(qvec_rz, std::cout);\n\n std::cout << \"CMTX RPHI: \" << std::endl;\n dump_element(cmtx_rphi, std::cout);\n\n std::cout << \"QVEC RPHI: \" << std::endl;\n dump_element(qvec_rphi, std::cout);\n *\/\n\n double cottheta = 0.0; \/\/ eta\n double z0 = 0.0;\n \n cottheta = qvec_rz(0,0);\n z0 = qvec_rz(0,1);\n for (int i=0; i<(int)cmtx_rz.n_cols(); ++i)\n {\n cottheta += cmtx_rz(0, i) * zrv(0, i);\n z0 += cmtx_rz(1, i) * zrv(0, i);\n }\n \n double coverpt = 0.0; \/\/ pt\n double phi = 0.0;\n \n coverpt = qvec_rphi(0,0);\n phi = qvec_rphi(0,1);\n for (int i=0; i<(int)cmtx_rphi.n_cols(); ++i)\n {\n coverpt += cmtx_rphi(0, i) * phirv(0, i);\n phi += cmtx_rphi(1, i) * phirv(0, i);\n }\n \n double pt = (double)(charge)\/coverpt;\n \n \/\/ TODO: checkit theta to eta \n double eta = 0.0e0;\n double theta = atan(1.0e0 \/ cottheta); \n double tantheta2 = tan (theta\/2.0e0); \n if (tantheta2 < 0.0)\n eta = 1.0e0 * log (-1.0e0 * tantheta2);\n else\n eta = -1.0e0 * log (tantheta2);\n \n Track* fit_track = new Track();\n\n std::cout.precision(8);\n std::cout << std::scientific << \" pt : \" << pt << \" ==> \" << pt_est << std::endl;\n std::cout << std::scientific << \" phi: \" << phi << \" ==> \" << phi_est << std::endl; \n std::cout << std::scientific << \" eta: \" << eta << \" ==> \" << eta_est << std::endl;\n std::cout << std::scientific << \" z0 : \" << z0 << \" ==> \" << z0_est << std::endl;\n \n fit_track->setCurve(pt);\n fit_track->setPhi0(phi);\n fit_track->setEta0(eta);\n fit_track->setZ0(z0);\n \n for(unsigned int idx = 0; idx < hits.size(); ++idx)\n fit_track->addStubIndex(idx);\n \n tracks.push_back(fit_track);\n }\n else \n {\n std::cerr << \"error while reading PCA const\" << std::endl;\n std::cout << \"error while reading PCA const\" << std::endl;\n }\n\n }\n else\n {\n \/\/ TODO non 6 layers \n }\n }\n\n \/*\n xyzfile.close();\n rpzfile.close();\n\n std::cout << \"Close files\" << std::endl;\n *\/\n}\n\nvoid PCATrackFitter::fit()\n{\n\n vector<Hit*> activatedHits;\n\n \/\/\/\/\/\/\/\/ Get the list of unique stubs from the tracks \/\/\/\/\/\/\/\/\/\/\/\n\n \/\/ TODO not sure will work as it is now need to deal with given \n \/\/ tracks\n \n set<int> ids;\n int total=0;\n for (unsigned int i=0; i<patterns.size(); ++i)\n {\n vector<Hit*> allHits = patterns[i]->getHits();\n total+=allHits.size();\n for(unsigned int j=0; j<allHits.size(); ++j)\n {\n pair<set<int>::iterator,bool> result = ids.insert(allHits[j]->getID());\n if (result.second == true )\n activatedHits.push_back(allHits[j]); \n }\n }\n \n fit(activatedHits);\n}\n\nTrackFitter* PCATrackFitter::clone()\n{\n PCATrackFitter* fit = new PCATrackFitter(nb_layers);\n\n \/\/ TODO\n\n return fit;\n}\n\n<commit_msg>backup<commit_after>\/*\nC++ implementation of the PCA fitter\n\nL.Storchi, A.Modak, S.R.Chowdhury : 2016\n*\/\n#include \"..\/interface\/PCATrackFitter.h\"\n#include \"..\/interface\/pcaconst.hpp\"\n\nnamespace \n{\n \/* quick and very dirty *\/\n void dump_element (const pca::matrixpcaconst<double> & in, std::ostream & out)\n {\n out.precision(6);\n for (unsigned int i = 0; i<in.n_rows(); ++i)\n {\n for (unsigned int j = 0; j<in.n_cols(); ++j)\n out << std::scientific << in(i, j) << \" \";\n out << std::endl;\n }\n }\n\n bool import_pca_const (const std::string & cfname, \n pca::matrixpcaconst<double> & cmtx_rz, \n pca::matrixpcaconst<double> & qvec_rz, \n pca::matrixpcaconst<double> & amtx_rz, \n pca::matrixpcaconst<double> & kvec_rz, \n pca::matrixpcaconst<double> & cmtx_rphi, \n pca::matrixpcaconst<double> & qvec_rphi, \n pca::matrixpcaconst<double> & amtx_rphi, \n pca::matrixpcaconst<double> & kvec_rphi, \n double eta, double pt, \n int chargesignin)\n {\n std::vector<pca::matrixpcaconst<double> > vct;\n if (pca::read_pcacosnt_from_file (vct, cfname.c_str()))\n {\n int hwmanygot = 0;\n std::vector<pca::matrixpcaconst<double> >::const_iterator it = \n vct.begin();\n for (; it != vct.end(); ++it)\n {\n double ptmin, ptmax, etamin, etamax;\n int chargesign;\n \n it->get_ptrange(ptmin, ptmax);\n it->get_etarange(etamin, etamax);\n chargesign = it->get_chargesign();\n \n if (it->get_plane_type() == pca::matrixpcaconst<double>::RZ)\n {\n if ((eta >= etamin) && (eta <= etamax)) \n {\n switch(it->get_const_type())\n {\n case pca::matrixpcaconst<double>::QVEC :\n qvec_rz = *it;\n hwmanygot++;\n break;\n case pca::matrixpcaconst<double>::KVEC :\n kvec_rz = *it;\n hwmanygot++;\n break;\n case pca::matrixpcaconst<double>::CMTX :\n cmtx_rz = *it;\n hwmanygot++;\n break;\n case pca::matrixpcaconst<double>::AMTX :\n amtx_rz = *it;\n hwmanygot++;\n break;\n default:\n break;\n }\n } \n }\n else if (it->get_plane_type() == pca::matrixpcaconst<double>::RPHI)\n {\n if (chargesignin == chargesign)\n {\n if ((pt >= ptmin) && (pt <= ptmax))\n {\n switch(it->get_const_type())\n {\n case pca::matrixpcaconst<double>::QVEC : \n qvec_rphi = *it;\n hwmanygot++;\n break;\n case pca::matrixpcaconst<double>::KVEC :\n kvec_rphi = *it;\n hwmanygot++;\n break;\n case pca::matrixpcaconst<double>::CMTX :\n cmtx_rphi = *it;\n hwmanygot++;\n break;\n case pca::matrixpcaconst<double>::AMTX :\n amtx_rphi = *it;\n hwmanygot++;\n break;\n default:\n break;\n }\n }\n } \n }\n }\n \n if (hwmanygot == 8)\n return true;\n else\n {\n std::cerr << \"Found \" << hwmanygot << \" const instead of 8\" << std::endl;\n return false;\n }\n }\n \n \/\/ TODO add consistency check for dims\n \n return false;\n }\n}\n\nPCATrackFitter::PCATrackFitter():TrackFitter(0)\n{\n}\n\nPCATrackFitter::PCATrackFitter(int nb):TrackFitter(nb)\n{\n}\n\nPCATrackFitter::~PCATrackFitter()\n{\n}\n\nvoid PCATrackFitter::initialize()\n{\n}\n\nvoid PCATrackFitter::mergePatterns()\n{\n}\n\n\/\/ Tentative duplicate removal\n\/\/ Not used for the moment\n\nvoid PCATrackFitter::mergeTracks()\n{\n unsigned int index = 0;\n vector<Track*>::iterator it = tracks.begin();\n \n while(it!=tracks.end())\n {\n Track* newTrack = *it;\n bool found = false;\n for(unsigned int i=0;i<index;i++)\n {\n Track* ref = tracks[i];\n float dpt,dphi,dz,deta;\n dpt = fabs(newTrack->getCurve()-ref->getCurve());\n dphi = fabs(newTrack->getPhi0()-ref->getPhi0());\n dz = fabs(newTrack->getZ0()-ref->getZ0());\n deta = fabs(newTrack->getEta0()-ref->getEta0());\n found = (deta<0.02) &&\n\t(dphi<0.005) &&\n\t(dpt<0.1) &&\n\t(dz<0.3);\n \n if(found)\n\tbreak;\n }\n\n if(found)\n tracks.erase(it);\n else\n {\n index++;\n it++;\n }\n }\n}\n\nvoid PCATrackFitter::setTracks(const std::vector<Track*> & intc)\n{\n tracks_ = intc;\n}\n\nvoid PCATrackFitter::fit(vector<Hit*> hits)\n{\n int tow = sector_id; \/\/ The tower ID, necessary to get the phi shift\n\n std::cout << \"In PCA::fit tow: \" << tow << std::endl;\n\n double sec_phi = 0;\n switch (tow%8)\n {\n case 0:\n sec_phi = 0.4;\n break;\n case 1:\n sec_phi = 1.2;\n break;\n case 3:\n sec_phi = 2.0;\n break;\n case 4:\n sec_phi = 2.7;\n break;\n case 5:\n sec_phi = -2.0;\n break;\n case 6:\n sec_phi = -1.2;\n break;\n case 7:\n sec_phi = -0.4;\n break;\n }\n \n double ci = cos(sec_phi);\n double si = sin(sec_phi);\n\n \/\/std::cout << \"tracks_.size() : \" << tracks_.size() << std::endl;\n \n \/*\n std::ofstream xyzfile;\n xyzfile.open (\"PCAxyzfile.txt\");\n\n std::ofstream rpzfile;\n rpzfile.open (\"PCArphizfile.txt\");\n *\/\n\n for(unsigned int tt=0; tt<tracks_.size(); ++tt)\n {\n \/\/vector<int> stubids = tracks_[tt]->getStubs(); \/\/ TODO are they the hits idx ? \n\n \/\/std::cout << \"hits.size() : \" << hits.size() << std::endl;\n\n if (hits.size() == 6)\n {\n pca::matrixpcaconst<double> zrv(1, 12), phirv(1, 12);\n unsigned int coordidx = 0;\n\n for(unsigned int idx = 0; idx < hits.size(); ++idx)\n {\n double xi = hits[idx]->getX()*ci+ hits[idx]->getY()*si;\n double yi = -hits[idx]->getX()*si+ hits[idx]->getY()*ci;\n\n double zi = hits[idx]->getZ();\n double ri = sqrt(xi*xi+yi*yi);\n double pi = atan2(yi,xi);\n\n std::cout << \"PCAxyz \" << xi << \" \" << yi << \" \" << zi << \" \" << \n (int) hits[idx]->getLayer() << std::endl;\n\n std::cout << \"PCArpz \" << ri << \" \" << pi << \" \" << zi << \" \" << \n (int) hits[idx]->getLayer() << std::endl;\n\n \/*\n xyzfile << xi << \" \" << yi << \" \" << zi << \" \" << \n (int) hits[idx]->getLayer() << std::endl;\n\n rpzfile << ri << \" \" << pi << zi << \" \" << \n (int) hits[idx]->getLayer() << std::endl;\n *\/\n\n zrv(0, coordidx) = zi;\n phirv(0, coordidx) = pi;\n\n ++coordidx;\n\n zrv(0, coordidx) = ri;\n phirv(0, coordidx) = ri;\n\n ++coordidx;\n }\n\n int charge;\n double pt_est, eta_est, z0_est, phi_est;\n charge = tracks_[tt]->getCharge(); \n pt_est = tracks_[tt]->getCurve();\n eta_est = tracks_[tt]->getEta0();\n z0_est = tracks_[tt]->getZ0();\n phi_est = tracks_[tt]->getPhi0();\n\n \/* TEST \n zrv(0, 0) = -16.1314; zrv(0, 1) = 23.3135;\n zrv(0, 2) = -22.7054; zrv(0, 3) = 34.8367;\n zrv(0, 4) = -32.6362; zrv(0, 5) = 51.9131;\n eta_est = -0.580448;\n z0_est = -2.65203;\n\n phirv(0, 0) = 2.74588; phirv(0, 1) = 23.2105;\n phirv(0, 2) = 2.76857; phirv(0, 3) = 37.0286;\n phirv(0, 4) = 2.79267; phirv(0, 5) = 51.2692;\n phirv(0, 6) = 2.82109; phirv(0, 7) = 67.7289;\n phirv(0, 8) = 2.85643; phirv(0, 9) = 87.8179;\n phirv(0, 10) = 2.89452; phirv(0, 11) = 109.012;\n pt_est = 1.0\/0.315806;\n phi_est = 2.70006;\n charge = +1;\n *\/\n\n std::string cfname = \".\/barrel_tow18_pca_const.txt\";\n\n pca::matrixpcaconst<double> cmtx_rz(0, 0);\n pca::matrixpcaconst<double> qvec_rz(0, 0); \n pca::matrixpcaconst<double> amtx_rz(0, 0); \n pca::matrixpcaconst<double> kvec_rz(0, 0); \n pca::matrixpcaconst<double> cmtx_rphi(0, 0); \n pca::matrixpcaconst<double> qvec_rphi(0, 0); \n pca::matrixpcaconst<double> amtx_rphi(0, 0); \n pca::matrixpcaconst<double> kvec_rphi(0, 0); \n\n if (import_pca_const (cfname, \n cmtx_rz, \n qvec_rz, \n amtx_rz, \n kvec_rz, \n cmtx_rphi, \n qvec_rphi, \n amtx_rphi, \n kvec_rphi, \n eta_est, \n pt_est, \n charge))\n {\n \/*\n std::cout << \"CMTX RZ: \" << std::endl;\n dump_element(cmtx_rz, std::cout);\n\n std::cout << \"QVEC RZ: \" << std::endl;\n dump_element(qvec_rz, std::cout);\n\n std::cout << \"CMTX RPHI: \" << std::endl;\n dump_element(cmtx_rphi, std::cout);\n\n std::cout << \"QVEC RPHI: \" << std::endl;\n dump_element(qvec_rphi, std::cout);\n *\/\n\n double cottheta = 0.0; \/\/ eta\n double z0 = 0.0;\n \n cottheta = qvec_rz(0,0);\n z0 = qvec_rz(0,1);\n for (int i=0; i<(int)cmtx_rz.n_cols(); ++i)\n {\n cottheta += cmtx_rz(0, i) * zrv(0, i);\n z0 += cmtx_rz(1, i) * zrv(0, i);\n }\n \n double coverpt = 0.0; \/\/ pt\n double phi = 0.0;\n \n coverpt = qvec_rphi(0,0);\n phi = qvec_rphi(0,1);\n for (int i=0; i<(int)cmtx_rphi.n_cols(); ++i)\n {\n coverpt += cmtx_rphi(0, i) * phirv(0, i);\n phi += cmtx_rphi(1, i) * phirv(0, i);\n }\n \n double pt = (double)(charge)\/coverpt;\n \n \/\/ TODO: checkit theta to eta \n double eta = 0.0e0;\n double theta = atan(1.0e0 \/ cottheta); \n double tantheta2 = tan (theta\/2.0e0); \n if (tantheta2 < 0.0)\n eta = 1.0e0 * log (-1.0e0 * tantheta2);\n else\n eta = -1.0e0 * log (tantheta2);\n \n Track* fit_track = new Track();\n\n std::cout << \" pt : \" << pt << \" ==> \" << pt_est << std::endl;\n std::cout << \" phi: \" << phi << \" ==> \" << phi_est << std::endl; \n std::cout << \" eta: \" << eta << \" ==> \" << eta_est << std::endl;\n std::cout << \" z0 : \" << z0 << \" ==> \" << z0_est << std::endl;\n \n fit_track->setCurve(pt);\n fit_track->setPhi0(phi);\n fit_track->setEta0(eta);\n fit_track->setZ0(z0);\n \n for(unsigned int idx = 0; idx < hits.size(); ++idx)\n fit_track->addStubIndex(idx);\n \n tracks.push_back(fit_track);\n }\n else \n {\n std::cerr << \"error while reading PCA const\" << std::endl;\n std::cout << \"error while reading PCA const\" << std::endl;\n }\n\n }\n else\n {\n \/\/ TODO non 6 layers \n }\n }\n\n \/*\n xyzfile.close();\n rpzfile.close();\n\n std::cout << \"Close files\" << std::endl;\n *\/\n}\n\nvoid PCATrackFitter::fit()\n{\n\n vector<Hit*> activatedHits;\n\n \/\/\/\/\/\/\/\/ Get the list of unique stubs from the tracks \/\/\/\/\/\/\/\/\/\/\/\n\n \/\/ TODO not sure will work as it is now need to deal with given \n \/\/ tracks\n \n set<int> ids;\n int total=0;\n for (unsigned int i=0; i<patterns.size(); ++i)\n {\n vector<Hit*> allHits = patterns[i]->getHits();\n total+=allHits.size();\n for(unsigned int j=0; j<allHits.size(); ++j)\n {\n pair<set<int>::iterator,bool> result = ids.insert(allHits[j]->getID());\n if (result.second == true )\n activatedHits.push_back(allHits[j]); \n }\n }\n \n fit(activatedHits);\n}\n\nTrackFitter* PCATrackFitter::clone()\n{\n PCATrackFitter* fit = new PCATrackFitter(nb_layers);\n\n \/\/ TODO\n\n return fit;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/******************************************************************************\n\n This source file is part of the MongoModel project.\n\n Copyright 2011 Kitware, Inc.\n\n This source code is released under the New BSD License, (the \"License\").\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n\n******************************************************************************\/\n\n#include \"MongoModel.h\"\n\n#include <mongo\/client\/dbclient.h>\n#include <mongo\/client\/gridfs.h>\n#include <QtCore\/QString>\n#include <QtCore\/QStringList>\n#include <QtCore\/QFileInfo>\n#include <QtCore\/QFile>\n#include <QtCore\/QSize>\n#include <QtCore\/QDebug>\n#include <QtGui\/QColor>\n#include <QtGui\/QPixmap>\n\n#include <vtkNew.h>\n#include <vtkTable.h>\n#include <vtkFloatArray.h>\n#include <vtkStringArray.h>\n\nusing namespace mongo;\n\nnamespace ChemData {\n\nclass MongoModel::Private\n{\npublic:\n Private(const QString &host) : m_namespace(\"chem.import\"), m_rows(0)\n {\n this->connect(host);\n }\n\n ~Private()\n {\n }\n\n bool connect(const QString &host)\n {\n try {\n m_db.connect(host.toStdString());\n cout << \"connected OK\" << endl;\n return query();\n }\n catch (DBException &e) {\n cout << \"caught \" << e.what() << endl;\n return false;\n }\n }\n\n bool query()\n {\n if (m_db.isFailed())\n return false;\n m_rowObjects.resize(0);\n m_rows = m_db.count(m_namespace.toStdString());\n m_rowObjects.reserve(m_rows);\n BSONObj empty;\n m_cursor = m_db.query(m_namespace.toStdString(), Query().sort(\"Observed\"));\n \/\/, QUERY(\"ago\" << 33));\n return true;\n }\n\n BSONObj * getRecord(unsigned int index)\n {\n if (index < m_rowObjects.size()) {\n return &m_rowObjects[index];\n }\n else {\n while (index >= m_rowObjects.size() && m_cursor->more())\n m_rowObjects.push_back(m_cursor->next().getOwned());\n \/\/ If there are enough objects, return the one requested\n if (index < m_rowObjects.size())\n return &m_rowObjects[index];\n else\n return 0;\n }\n }\n\n DBClientConnection m_db;\n auto_ptr<DBClientCursor> m_cursor;\n QString m_namespace;\n std::vector<BSONObj> m_rowObjects;\n int m_rows;\n\n QStringList m_fields;\n QMap<QString, QString> m_titles;\n};\n\nMongoModel::MongoModel(QObject *parent)\n : QAbstractItemModel(parent)\n{\n d = new MongoModel::Private(\"localhost\");\n\/\/ d = new MongoModel::Private(\"londinium.kitwarein.com\");\n\n d->m_fields << \"CAS\" << \"Set\"\n << \"Molecular Weight\"\n << \"Observed\"\n << \"Predicted log Sw (MLR)\"\n << \"Predicted log Sw (RF)\";\n d->m_titles[\"Observed\"] = \"Observed log(Sw)\";\n d->m_titles[\"Predicted log Sw (MLR)\"] = \"log(Sw) (MLR)\";\n d->m_titles[\"Predicted log Sw (RF)\"] = \"log(Sw) (RF)\";\n}\n\nMongoModel::~MongoModel()\n{\n delete d;\n}\n\nQModelIndex MongoModel::parent(const QModelIndex &) const\n{\n return QModelIndex();\n}\n\nint MongoModel::rowCount(const QModelIndex &parent) const\n{\n return d->m_rows;\n}\n\nint MongoModel::columnCount(const QModelIndex &parent) const\n{\n return d->m_fields.size();\n}\n\nQVariant MongoModel::headerData(int section, Qt::Orientation orientation,\n int role) const\n{\n if (orientation == Qt::Horizontal && role == Qt::DisplayRole) {\n if (d->m_titles.contains(d->m_fields[section]))\n return d->m_titles[d->m_fields[section]];\n else\n return d->m_fields[section];\n }\n else if (orientation == Qt::Vertical && role == Qt::DisplayRole) {\n return QVariant(section);\n }\n return QVariant();\n}\n\nQVariant MongoModel::data(const QModelIndex &index, int role) const\n{\n if (index.internalPointer()) {\n BSONObj *obj = static_cast<BSONObj *>(index.internalPointer());\n if (obj) {\n if (role == Qt::DisplayRole) {\n BSONElement e = obj->getField(d->m_fields[index.column()].toStdString());\n if (e.isNumber())\n return QVariant(e.number());\n else if (e.isNull())\n return QVariant();\n else\n return e.str().c_str();\n }\n else if (role == Qt::SizeHintRole) {\n if (d->m_fields[index.column()] == \"Molecular Weight\" &&\n !obj->getField(\"2D PNG\").eoo()) {\n return QVariant(QSize(250, 250));\n }\n else {\n return QVariant(QSize(120, 20));\n }\n }\n else if (role == Qt::DecorationRole) {\n if (d->m_fields[index.column()] == \"CAS\") {\n if (obj->getField(\"InChIKey\").eoo())\n return Qt::red;\n else\n return Qt::green;\n }\n else if (d->m_fields[index.column()] == \"Molecular Weight\") {\n BSONElement image = obj->getField(\"2D PNG\");\n if (!image.eoo()) {\n int length;\n const char *data = image.binData(length);\n QByteArray inData(data, length);\n QImage in = QImage::fromData(inData, \"PNG\");\n QPixmap pix = QPixmap::fromImage(in);\n return QVariant(pix);\n }\n }\n }\n else if (role == Qt::ToolTipRole) {\n if (d->m_fields[index.column()] == \"CAS\") {\n BSONElement iupac = obj->getField(\"IUPAC\");\n if (iupac.eoo())\n return \"<b>Unknown<\/b>\";\n else\n return iupac.str().c_str();\n }\n else if (d->m_fields[index.column()] == \"Molecular Weight\") {\n BSONElement e = obj->getField(\"Formula\");\n if (!e.eoo()) {\n QStringList parts = QString(e.str().c_str()).split(\" \",\n QString::SkipEmptyParts);\n QString formula;\n for (int i = 0; i < parts.size(); i += 2) {\n formula += parts[i];\n if (parts[i+1].toInt() > 1)\n formula += \"<sub>\" + parts[i+1] + \"<\/sub>\";\n }\n return formula;\n }\n }\n }\n }\n\n }\n return QVariant();\n}\n\nbool MongoModel::setData(const QModelIndex &index, const QVariant &value,\n int role)\n{\n return false;\n}\n\nQt::ItemFlags MongoModel::flags(const QModelIndex &index) const\n{\n if (index.column() == 0)\n return Qt::ItemIsSelectable | Qt::ItemIsEnabled | Qt::ItemIsUserCheckable;\n else\n return Qt::ItemIsSelectable | Qt::ItemIsEnabled;\n}\n\nQModelIndex MongoModel::index(int row, int column,\n const QModelIndex &parent) const\n{\n if (row >= 0 && row < d->m_rows) {\n BSONObj *obj = d->getRecord(row);\n return createIndex(row, column, obj);\n }\n return QModelIndex();\n}\n\nvoid MongoModel::clear()\n{\n}\n\nbool MongoModel::addIdentifiers(int row, const QString &identifiers)\n{\n BSONObj *obj = d->getRecord(row);\n BSONObjBuilder b;\n QStringList lines = identifiers.split(\"\\n\", QString::SkipEmptyParts);\n for (int i = 0; i < lines.size(); ++i) {\n if (lines[i].trimmed() == \"[Formula]\")\n b << \"Formula\" << lines[++i].trimmed().toStdString();\n else if (lines[i].trimmed() == \"[Molecular weight]\")\n b << \"Molecular Weight\" << lines[++i].trimmed().toDouble();\n else if (lines[i].trimmed() == \"[smiles]\")\n b << \"SMILES\" << lines[++i].trimmed().toStdString();\n else if (lines[i].trimmed() == \"[canonical smiles]\")\n b << \"Canonical SMILES\" << lines[++i].trimmed().toStdString();\n else if (lines[i].trimmed() == \"[inchi]\")\n b << \"InChI\" << lines[++i].trimmed().toStdString();\n else if (lines[i].trimmed() == \"[inchikey]\")\n b << \"InChIKey\" << lines[++i].trimmed().toStdString();\n else if (lines[i].trimmed() == \"[XYZ]\") {\n \/\/ Read in all of the XYZ file\n QString file = lines[++i] + \"\\n\";\n while (lines[++i].trimmed() != \"[end]\")\n file += lines[i] + \"\\n\";\n b << \"XYZ File\" << file.toStdString();\n }\n else if (lines[i].trimmed() == \"[CML]\") {\n \/\/ Read in all of the CML file\n QString file = lines[++i] + \"\\n\";\n while (lines[++i].trimmed() != \"[end]\")\n file += lines[i] + \"\\n\";\n b << \"CML File\" << file.toStdString();\n }\n }\n BSONObjBuilder updateSet;\n updateSet << \"$set\" << b.obj();\n d->m_db.update(d->m_namespace.toStdString(), *obj, updateSet.obj());\n d->query();\n}\n\nbool MongoModel::setIUPACName(int row, const QString &name)\n{\n BSONObj *obj = d->getRecord(row);\n BSONObjBuilder b;\n b << \"IUPAC\" << name.toStdString();\n BSONObjBuilder updateSet;\n updateSet << \"$set\" << b.obj();\n d->m_db.update(d->m_namespace.toStdString(), *obj, updateSet.obj());\n d->query();\n}\n\nbool MongoModel::setImage2D(int row, const QByteArray &image)\n{\n BSONObj *obj = d->getRecord(row);\n BSONObjBuilder b;\n qDebug() << \"Image data:\" << image.length() << image;\n b.appendBinData(\"2D PNG\", image.length(), mongo::BinDataGeneral, image.data());\n BSONObjBuilder updateSet;\n updateSet << \"$set\" << b.obj();\n d->m_db.update(d->m_namespace.toStdString(), *obj, updateSet.obj());\n d->query();\n}\n\nbool MongoModel::addOutputFile(const QString &outputFile,\n const QString &inputFile)\n{\n qDebug() << \"output\" << outputFile << \"input\" << inputFile;\n BSONObjBuilder b;\n b.genOID();\n QFile output(outputFile);\n if (output.open(QIODevice::ReadOnly)) {\n QByteArray out = output.readAll();\n qDebug() << \"GAMESS log file\" << out;\n b.append(\"gamout\", out.data());\n output.close();\n }\n else {\n qDebug() << \"Failed to open output file:\" << outputFile;\n return false;\n }\n if (!inputFile.isEmpty()) {\n QFile input(inputFile);\n if (input.open(QIODevice::ReadOnly)) {\n QByteArray in = input.readAll();\n b.append(\"gaminp\", in.data());\n input.close();\n }\n }\n d->m_db.insert(\"chem.gamess\", b.obj());\n return true;\n}\n\nbool MongoModel::results(vtkTable *table)\n{\n vtkNew<vtkStringArray> CAS;\n CAS->SetName(\"CAS\");\n CAS->SetNumberOfTuples(d->m_rows);\n vtkNew<vtkStringArray> set;\n set->SetName(\"Set\");\n set->SetNumberOfTuples(d->m_rows);\n vtkNew<vtkFloatArray> observed;\n observed->SetName(\"Observed\");\n observed->SetNumberOfTuples(d->m_rows);\n vtkNew<vtkFloatArray> mlr;\n mlr->SetName(\"log(Sw) (MLR)\");\n mlr->SetNumberOfTuples(d->m_rows);\n vtkNew<vtkFloatArray> rf;\n rf->SetName(\"log(Sw) (RF)\");\n rf->SetNumberOfTuples(d->m_rows);\n for (int i = 0; i < d->m_rows; ++i) {\n BSONObj *obj = d->getRecord(i);\n CAS->SetValue(i, obj->getField(\"CAS\").str().c_str());\n set->SetValue(i, obj->getField(\"Set\").str().c_str());\n observed->SetValue(i, obj->getField(\"Observed\").number());\n mlr->SetValue(i, obj->getField(\"Predicted log Sw (MLR)\").number());\n rf->SetValue(i, obj->getField(\"Predicted log Sw (RF)\").number());\n }\n table->AddColumn(CAS.GetPointer());\n table->AddColumn(set.GetPointer());\n table->AddColumn(observed.GetPointer());\n table->AddColumn(mlr.GetPointer());\n table->AddColumn(rf.GetPointer());\n return true;\n}\n\n} \/\/ End of namespace\n<commit_msg>Place molecule diagram in its own column<commit_after>\/******************************************************************************\n\n This source file is part of the MongoModel project.\n\n Copyright 2011 Kitware, Inc.\n\n This source code is released under the New BSD License, (the \"License\").\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n\n******************************************************************************\/\n\n#include \"MongoModel.h\"\n\n#include <mongo\/client\/dbclient.h>\n#include <mongo\/client\/gridfs.h>\n#include <QtCore\/QString>\n#include <QtCore\/QStringList>\n#include <QtCore\/QFileInfo>\n#include <QtCore\/QFile>\n#include <QtCore\/QSize>\n#include <QtCore\/QDebug>\n#include <QtGui\/QColor>\n#include <QtGui\/QPixmap>\n\n#include <vtkNew.h>\n#include <vtkTable.h>\n#include <vtkFloatArray.h>\n#include <vtkStringArray.h>\n\nusing namespace mongo;\n\nnamespace ChemData {\n\nclass MongoModel::Private\n{\npublic:\n Private(const QString &host) : m_namespace(\"chem.import\"), m_rows(0)\n {\n this->connect(host);\n }\n\n ~Private()\n {\n }\n\n bool connect(const QString &host)\n {\n try {\n m_db.connect(host.toStdString());\n cout << \"connected OK\" << endl;\n return query();\n }\n catch (DBException &e) {\n cout << \"caught \" << e.what() << endl;\n return false;\n }\n }\n\n bool query()\n {\n if (m_db.isFailed())\n return false;\n m_rowObjects.resize(0);\n m_rows = m_db.count(m_namespace.toStdString());\n m_rowObjects.reserve(m_rows);\n BSONObj empty;\n m_cursor = m_db.query(m_namespace.toStdString(), Query().sort(\"Observed\"));\n \/\/, QUERY(\"ago\" << 33));\n return true;\n }\n\n BSONObj * getRecord(unsigned int index)\n {\n if (index < m_rowObjects.size()) {\n return &m_rowObjects[index];\n }\n else {\n while (index >= m_rowObjects.size() && m_cursor->more())\n m_rowObjects.push_back(m_cursor->next().getOwned());\n \/\/ If there are enough objects, return the one requested\n if (index < m_rowObjects.size())\n return &m_rowObjects[index];\n else\n return 0;\n }\n }\n\n DBClientConnection m_db;\n auto_ptr<DBClientCursor> m_cursor;\n QString m_namespace;\n std::vector<BSONObj> m_rowObjects;\n int m_rows;\n\n QStringList m_fields;\n QMap<QString, QString> m_titles;\n};\n\nMongoModel::MongoModel(QObject *parent)\n : QAbstractItemModel(parent)\n{\n d = new MongoModel::Private(\"localhost\");\n\/\/ d = new MongoModel::Private(\"londinium.kitwarein.com\");\n\n d->m_fields << \"CAS\"\n << \"Set\"\n << \"2D PNG\"\n << \"Molecular Weight\"\n << \"Observed\"\n << \"Predicted log Sw (MLR)\"\n << \"Predicted log Sw (RF)\";\n d->m_titles[\"2D PNG\"] = \"Diagram\";\n d->m_titles[\"Observed\"] = \"Observed log(Sw)\";\n d->m_titles[\"Predicted log Sw (MLR)\"] = \"log(Sw) (MLR)\";\n d->m_titles[\"Predicted log Sw (RF)\"] = \"log(Sw) (RF)\";\n}\n\nMongoModel::~MongoModel()\n{\n delete d;\n}\n\nQModelIndex MongoModel::parent(const QModelIndex &) const\n{\n return QModelIndex();\n}\n\nint MongoModel::rowCount(const QModelIndex &parent) const\n{\n return d->m_rows;\n}\n\nint MongoModel::columnCount(const QModelIndex &parent) const\n{\n return d->m_fields.size();\n}\n\nQVariant MongoModel::headerData(int section, Qt::Orientation orientation,\n int role) const\n{\n if (orientation == Qt::Horizontal && role == Qt::DisplayRole) {\n if (d->m_titles.contains(d->m_fields[section]))\n return d->m_titles[d->m_fields[section]];\n else\n return d->m_fields[section];\n }\n else if (orientation == Qt::Vertical && role == Qt::DisplayRole) {\n return QVariant(section);\n }\n return QVariant();\n}\n\nQVariant MongoModel::data(const QModelIndex &index, int role) const\n{\n if (index.internalPointer()) {\n BSONObj *obj = static_cast<BSONObj *>(index.internalPointer());\n if (obj) {\n if (role == Qt::DisplayRole) {\n BSONElement e = obj->getField(d->m_fields[index.column()].toStdString());\n if (e.isNumber())\n return QVariant(e.number());\n else if (e.isNull())\n return QVariant();\n else\n return e.str().c_str();\n }\n else if (role == Qt::SizeHintRole) {\n if (d->m_fields[index.column()] == \"Molecular Weight\" &&\n !obj->getField(\"2D PNG\").eoo()) {\n return QVariant(QSize(250, 250));\n }\n else {\n return QVariant(QSize(120, 20));\n }\n }\n else if (role == Qt::DecorationRole) {\n if (d->m_fields[index.column()] == \"CAS\") {\n if (obj->getField(\"InChIKey\").eoo())\n return Qt::red;\n else\n return Qt::green;\n }\n else if (d->m_fields[index.column()] == \"2D PNG\") {\n BSONElement image = obj->getField(\"2D PNG\");\n if (!image.eoo()) {\n int length;\n const char *data = image.binData(length);\n QByteArray inData(data, length);\n QImage in = QImage::fromData(inData, \"PNG\");\n QPixmap pix = QPixmap::fromImage(in);\n return QVariant(pix);\n }\n }\n }\n else if (role == Qt::ToolTipRole) {\n if (d->m_fields[index.column()] == \"CAS\") {\n BSONElement iupac = obj->getField(\"IUPAC\");\n if (iupac.eoo())\n return \"<b>Unknown<\/b>\";\n else\n return iupac.str().c_str();\n }\n else if (d->m_fields[index.column()] == \"Molecular Weight\") {\n BSONElement e = obj->getField(\"Formula\");\n if (!e.eoo()) {\n QStringList parts = QString(e.str().c_str()).split(\" \",\n QString::SkipEmptyParts);\n QString formula;\n for (int i = 0; i < parts.size(); i += 2) {\n formula += parts[i];\n if (parts[i+1].toInt() > 1)\n formula += \"<sub>\" + parts[i+1] + \"<\/sub>\";\n }\n return formula;\n }\n }\n }\n }\n\n }\n return QVariant();\n}\n\nbool MongoModel::setData(const QModelIndex &index, const QVariant &value,\n int role)\n{\n return false;\n}\n\nQt::ItemFlags MongoModel::flags(const QModelIndex &index) const\n{\n if (index.column() == 0)\n return Qt::ItemIsSelectable | Qt::ItemIsEnabled | Qt::ItemIsUserCheckable;\n else\n return Qt::ItemIsSelectable | Qt::ItemIsEnabled;\n}\n\nQModelIndex MongoModel::index(int row, int column,\n const QModelIndex &parent) const\n{\n if (row >= 0 && row < d->m_rows) {\n BSONObj *obj = d->getRecord(row);\n return createIndex(row, column, obj);\n }\n return QModelIndex();\n}\n\nvoid MongoModel::clear()\n{\n}\n\nbool MongoModel::addIdentifiers(int row, const QString &identifiers)\n{\n BSONObj *obj = d->getRecord(row);\n BSONObjBuilder b;\n QStringList lines = identifiers.split(\"\\n\", QString::SkipEmptyParts);\n for (int i = 0; i < lines.size(); ++i) {\n if (lines[i].trimmed() == \"[Formula]\")\n b << \"Formula\" << lines[++i].trimmed().toStdString();\n else if (lines[i].trimmed() == \"[Molecular weight]\")\n b << \"Molecular Weight\" << lines[++i].trimmed().toDouble();\n else if (lines[i].trimmed() == \"[smiles]\")\n b << \"SMILES\" << lines[++i].trimmed().toStdString();\n else if (lines[i].trimmed() == \"[canonical smiles]\")\n b << \"Canonical SMILES\" << lines[++i].trimmed().toStdString();\n else if (lines[i].trimmed() == \"[inchi]\")\n b << \"InChI\" << lines[++i].trimmed().toStdString();\n else if (lines[i].trimmed() == \"[inchikey]\")\n b << \"InChIKey\" << lines[++i].trimmed().toStdString();\n else if (lines[i].trimmed() == \"[XYZ]\") {\n \/\/ Read in all of the XYZ file\n QString file = lines[++i] + \"\\n\";\n while (lines[++i].trimmed() != \"[end]\")\n file += lines[i] + \"\\n\";\n b << \"XYZ File\" << file.toStdString();\n }\n else if (lines[i].trimmed() == \"[CML]\") {\n \/\/ Read in all of the CML file\n QString file = lines[++i] + \"\\n\";\n while (lines[++i].trimmed() != \"[end]\")\n file += lines[i] + \"\\n\";\n b << \"CML File\" << file.toStdString();\n }\n }\n BSONObjBuilder updateSet;\n updateSet << \"$set\" << b.obj();\n d->m_db.update(d->m_namespace.toStdString(), *obj, updateSet.obj());\n d->query();\n}\n\nbool MongoModel::setIUPACName(int row, const QString &name)\n{\n BSONObj *obj = d->getRecord(row);\n BSONObjBuilder b;\n b << \"IUPAC\" << name.toStdString();\n BSONObjBuilder updateSet;\n updateSet << \"$set\" << b.obj();\n d->m_db.update(d->m_namespace.toStdString(), *obj, updateSet.obj());\n d->query();\n}\n\nbool MongoModel::setImage2D(int row, const QByteArray &image)\n{\n BSONObj *obj = d->getRecord(row);\n BSONObjBuilder b;\n qDebug() << \"Image data:\" << image.length() << image;\n b.appendBinData(\"2D PNG\", image.length(), mongo::BinDataGeneral, image.data());\n BSONObjBuilder updateSet;\n updateSet << \"$set\" << b.obj();\n d->m_db.update(d->m_namespace.toStdString(), *obj, updateSet.obj());\n d->query();\n}\n\nbool MongoModel::addOutputFile(const QString &outputFile,\n const QString &inputFile)\n{\n qDebug() << \"output\" << outputFile << \"input\" << inputFile;\n BSONObjBuilder b;\n b.genOID();\n QFile output(outputFile);\n if (output.open(QIODevice::ReadOnly)) {\n QByteArray out = output.readAll();\n qDebug() << \"GAMESS log file\" << out;\n b.append(\"gamout\", out.data());\n output.close();\n }\n else {\n qDebug() << \"Failed to open output file:\" << outputFile;\n return false;\n }\n if (!inputFile.isEmpty()) {\n QFile input(inputFile);\n if (input.open(QIODevice::ReadOnly)) {\n QByteArray in = input.readAll();\n b.append(\"gaminp\", in.data());\n input.close();\n }\n }\n d->m_db.insert(\"chem.gamess\", b.obj());\n return true;\n}\n\nbool MongoModel::results(vtkTable *table)\n{\n vtkNew<vtkStringArray> CAS;\n CAS->SetName(\"CAS\");\n CAS->SetNumberOfTuples(d->m_rows);\n vtkNew<vtkStringArray> set;\n set->SetName(\"Set\");\n set->SetNumberOfTuples(d->m_rows);\n vtkNew<vtkFloatArray> observed;\n observed->SetName(\"Observed\");\n observed->SetNumberOfTuples(d->m_rows);\n vtkNew<vtkFloatArray> mlr;\n mlr->SetName(\"log(Sw) (MLR)\");\n mlr->SetNumberOfTuples(d->m_rows);\n vtkNew<vtkFloatArray> rf;\n rf->SetName(\"log(Sw) (RF)\");\n rf->SetNumberOfTuples(d->m_rows);\n for (int i = 0; i < d->m_rows; ++i) {\n BSONObj *obj = d->getRecord(i);\n CAS->SetValue(i, obj->getField(\"CAS\").str().c_str());\n set->SetValue(i, obj->getField(\"Set\").str().c_str());\n observed->SetValue(i, obj->getField(\"Observed\").number());\n mlr->SetValue(i, obj->getField(\"Predicted log Sw (MLR)\").number());\n rf->SetValue(i, obj->getField(\"Predicted log Sw (RF)\").number());\n }\n table->AddColumn(CAS.GetPointer());\n table->AddColumn(set.GetPointer());\n table->AddColumn(observed.GetPointer());\n table->AddColumn(mlr.GetPointer());\n table->AddColumn(rf.GetPointer());\n return true;\n}\n\n} \/\/ End of namespace\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright 2014 Jules Cléro\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *\/\n\n#include <string>\n\nnamespace ghost\n{\nnamespace core\n{\nnamespace carryingSystem\n{\n\n\/** Factory of At Command used to communicate with the Arduino *\/\nclass CarryingSystemAtCommandFactory\n{\n\npublic:\n\n \/** Ackable Commands *\/\n enum AtCommandReceivable {\n LIFTED = 666,\n DROPED,\n ACK\n };\n\n \/** Generate the AT Command allowing the carrying system to lift the packet *\/\n static const std::string liftCommand();\n\n \/** Generate the AT Command allowing the carrying system to drop the packet *\/\n static const std::string dropCommand();\n\n \/** Test if a received AT Commands try to ack an other one *\/\n static bool isAckCommandOf(const std::string& atCmd, const std::string& commandType);\n\nprivate:\n\n \/** At Command parts *\/\n static const std::string mAtCommandPrefix;\n static const std::string mAtCommandAssignement;\n static const std::string mAtCommandSuffix;\n\n \/** Available At Commands *\/\n static const std::string mAtCommandDropHeader;\n static const std::string mAtCommandLiftHeader;\n static const std::string mAtCommandAckHeader;\n\n \/** General method which allows to create an AT Command without arguments. *\/\n static const std::string commandFactory(const std::string& atCmdHeader);\n\n \/** General method which allows to create an AT Command with one argument. *\/\n \/\/ const std::string commandFactory(const std::string& atCmdHeader, const std::string& atCmdParameter);\n\n static const std::string determineParameter(const std::string& atCmd);\n static const std::string determineHeader(const std::string& atCmd);\n\n};\n\n} \/* carryingSystem namespace *\/\n} \/* core namespace *\/\n} \/* ghost namespace *\/\n<commit_msg>[Core] Add missing comments in CarryingSystemAtCommandFactory header<commit_after>\/*\n * Copyright 2014 Jules Cléro\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *\/\n\n#pragma once\n\n#include <string>\n\nnamespace ghost\n{\nnamespace core\n{\nnamespace carryingSystem\n{\n\n\/** Factory of At Command used to communicate with the Arduino *\/\nclass CarryingSystemAtCommandFactory\n{\n\npublic:\n\n \/** Generate the AT Command allowing the carrying system to lift the packet *\/\n static const std::string liftCommand();\n\n \/** Generate the AT Command allowing the carrying system to drop the packet *\/\n static const std::string dropCommand();\n\n \/** Test if a received AT Commands try to ack an other one *\/\n static bool isAckCommandOf(const std::string& atCmd, const std::string& commandType);\n\nprivate:\n\n \/** At Command parts *\/\n static const std::string mAtCommandPrefix;\n static const std::string mAtCommandAssignement;\n static const std::string mAtCommandSuffix;\n\n \/** Available At Commands *\/\n static const std::string mAtCommandDropHeader;\n static const std::string mAtCommandLiftHeader;\n static const std::string mAtCommandAckHeader;\n\n \/** General method which allows to create an AT Command without arguments. *\/\n static const std::string commandFactory(const std::string& atCmdHeader);\n\n static const std::string determineParameter(const std::string& atCmd);\n static const std::string determineHeader(const std::string& atCmd);\n\n};\n\n} \/* carryingSystem namespace *\/\n} \/* core namespace *\/\n} \/* ghost namespace *\/\n<|endoftext|>"} {"text":"<commit_before>\/***************************************************************************\/\/**\n * rendergl.hpp\n * OpenGL rendering calls\n *\/\n\/* ***** BEGIN LICENSE BLOCK *****\n * Version: MPL 1.1\/GPL 2.0\/LGPL 2.1\n *\n * The contents of this file are subject to the Mozilla Public License Version\n * 1.1 (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n * http:\/\/www.mozilla.org\/MPL\/\n *\n * Software distributed under the License is distributed on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License\n * for the specific language governing rights and limitations under the\n * License.\n *\n * The Original Code is cmgui.\n *\n * The Initial Developer of the Original Code is\n * Auckland Uniservices Ltd, Auckland, New Zealand.\n * Portions created by the Initial Developer are Copyright (C) 2005\n * the Initial Developer. All Rights Reserved.\n *\n * Contributor(s):\n * Shane Blackett <shane@blackett.co.nz>\n * \n * Alternatively, the contents of this file may be used under the terms of\n * either the GNU General Public License Version 2 or later (the \"GPL\"), or\n * the GNU Lesser General Public License Version 2.1 or later (the \"LGPL\"),\n * in which case the provisions of the GPL or the LGPL are applicable instead\n * of those above. If you wish to allow use of your version of this file only\n * under the terms of either the GPL or the LGPL, and not to allow others to\n * use your version of this file under the terms of the MPL, indicate your\n * decision by deleting the provisions above and replace them with the notice\n * and other provisions required by the GPL or the LGPL. If you do not delete\n * the provisions above, a recipient may use your version of this file under\n * the terms of any one of the MPL, the GPL or the LGPL.\n *\n * ***** END LICENSE BLOCK ***** *\/\n#if !defined (RENDERGL_HPP)\n#define RENDERGL_HPP\n\n#include \"graphics\/graphics_object.h\"\n#include \"graphics\/render.hpp\"\n\n\/***************************************************************************\/\/**\n * Common code for all OpenGL based implementations.\n *\/\nclass Render_graphics_opengl : public Render_graphics_compile_members\n{\npublic:\n\t\/** Specifies that we should be rendering only objects marked as fast\n\t * changing.\n\t *\/\n\tint fast_changing;\n\t\/** Indicates that we are rendering specifically to pick objects.\n\t * Requires the ndc transformation to be different as the viewport is the picking window.\n\t *\/\n\tint picking;\n\tGraphics_buffer *graphics_buffer;\n\t\n\tint allow_texture_tiling; \/** Flag controls whether when compiling a large texture\n\t it can be split into multiple texture tiles *\/\n\tTexture_tiling *texture_tiling; \/** If a given texture is compiled into tiles\n\t\t\t\t\t\t\t\t\t\t\t\t\t then this field is filled in and expected to\n\t\t\t\t\t\t\t\t\t\t\t\t\t be used when compiling graphics that use that material. *\/\n\t\npublic:\n\tRender_graphics_opengl(Graphics_buffer *graphics_buffer) :\n\t\tgraphics_buffer(graphics_buffer)\n\t{\n\t\tfast_changing = 0;\n\t\tpicking = 0;\n\t\ttexture_tiling = NULL;\t\t\n\t}\n\n\t\/***************************************************************************\/\/**\n\t * @see Render_graphics::Scene_compile\n\t *\/\n\tvirtual int Scene_compile(Scene *scene);\n\n\t\/***************************************************************************\/\/**\n\t * @see Render_graphics::Graphics_object_compile\n\t *\/\n\tvirtual int Graphics_object_compile(GT_object *graphics_object);\n\n\t\/***************************************************************************\/\/**\n\t * @see Render_graphics::Material_compile\n\t *\/\n\tvirtual int Material_compile(Graphical_material *material);\n\n\t\/**************************************************************************\/\/**\n\t * Temporarily override the viewing coordinates so that the current opengl\n\t * display is in normalised device coordinates (aligned with the viewport).\n\t *\/\n\tvirtual int Start_ndc_coordinates() = 0;\n\n\t\/**************************************************************************\/\/**\n\t * Reverse the changes made by Start_ndc_coordinates and resume normal \n\t * 3D rendering.\n\t *\/\n\tvirtual int End_ndc_coordinates() = 0;\n\n}; \/* class Render_graphics_opengl *\/\n\n\n\/***************************************************************************\/\/**\n * Factory function to create a renderer that uses immediate mode \n * glBegin\/glEnd calls to render primitives.\n *\/\nRender_graphics_opengl *Render_graphics_opengl_create_glbeginend_renderer(\n\tGraphics_buffer *graphics_buffer);\n\n\/***************************************************************************\/\/**\n * Factory function to create a renderer that compiles objects into display lists\n * for rendering and uses glBegin\/glEnd calls when compiling primitives.\n *\/\nRender_graphics_opengl *Render_graphics_opengl_create_glbeginend_display_list_renderer(\n\tGraphics_buffer *graphics_buffer);\n\n\/***************************************************************************\/\/**\n * Factory function to create a renderer that uses immediate mode \n * client vertex arrays to render primitives.\n *\/\nRender_graphics_opengl *Render_graphics_opengl_create_client_vertex_arrays_renderer(\n\tGraphics_buffer *graphics_buffer);\n\n\/***************************************************************************\/\/**\n * Factory function to create a renderer that compiles objects into display lists\n * for rendering and uses client vertex arrays when compiling primitives.\n *\/\nRender_graphics_opengl *Render_graphics_opengl_create_client_vertex_arrays_display_list_renderer(\n\tGraphics_buffer *graphics_buffer);\n\n\/***************************************************************************\/\/**\n * Factory function to create a renderer that uses immediate mode \n * vertex buffer objects to render primitives.\n *\/\nRender_graphics_opengl *Render_graphics_opengl_create_vertex_buffer_object_renderer(\n\tGraphics_buffer *graphics_buffer);\n\n\/***************************************************************************\/\/**\n * Factory function to create a renderer that compiles objects into display lists\n * for rendering and uses vertex buffer objects when compiling primitives.\n *\/\nRender_graphics_opengl *Render_graphics_opengl_create_vertex_buffer_object_display_list_renderer(\n\tGraphics_buffer *graphics_buffer);\n\n#endif \/* !defined (RENDERGL_HPP) *\/\n<commit_msg>allow_texture_tiling field should be initialised. ASSIGNED - bug 1401: Use vertex arrays with OpenGL https:\/\/tracker.physiomeproject.org\/show_bug.cgi?id=1401<commit_after>\/***************************************************************************\/\/**\n * rendergl.hpp\n * OpenGL rendering calls\n *\/\n\/* ***** BEGIN LICENSE BLOCK *****\n * Version: MPL 1.1\/GPL 2.0\/LGPL 2.1\n *\n * The contents of this file are subject to the Mozilla Public License Version\n * 1.1 (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n * http:\/\/www.mozilla.org\/MPL\/\n *\n * Software distributed under the License is distributed on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License\n * for the specific language governing rights and limitations under the\n * License.\n *\n * The Original Code is cmgui.\n *\n * The Initial Developer of the Original Code is\n * Auckland Uniservices Ltd, Auckland, New Zealand.\n * Portions created by the Initial Developer are Copyright (C) 2005\n * the Initial Developer. All Rights Reserved.\n *\n * Contributor(s):\n * Shane Blackett <shane@blackett.co.nz>\n * \n * Alternatively, the contents of this file may be used under the terms of\n * either the GNU General Public License Version 2 or later (the \"GPL\"), or\n * the GNU Lesser General Public License Version 2.1 or later (the \"LGPL\"),\n * in which case the provisions of the GPL or the LGPL are applicable instead\n * of those above. If you wish to allow use of your version of this file only\n * under the terms of either the GPL or the LGPL, and not to allow others to\n * use your version of this file under the terms of the MPL, indicate your\n * decision by deleting the provisions above and replace them with the notice\n * and other provisions required by the GPL or the LGPL. If you do not delete\n * the provisions above, a recipient may use your version of this file under\n * the terms of any one of the MPL, the GPL or the LGPL.\n *\n * ***** END LICENSE BLOCK ***** *\/\n#if !defined (RENDERGL_HPP)\n#define RENDERGL_HPP\n\n#include \"graphics\/graphics_object.h\"\n#include \"graphics\/render.hpp\"\n\n\/***************************************************************************\/\/**\n * Common code for all OpenGL based implementations.\n *\/\nclass Render_graphics_opengl : public Render_graphics_compile_members\n{\npublic:\n\t\/** Specifies that we should be rendering only objects marked as fast\n\t * changing.\n\t *\/\n\tint fast_changing;\n\t\/** Indicates that we are rendering specifically to pick objects.\n\t * Requires the ndc transformation to be different as the viewport is the picking window.\n\t *\/\n\tint picking;\n\tGraphics_buffer *graphics_buffer;\n\t\n\tint allow_texture_tiling; \/** Flag controls whether when compiling a large texture\n\t it can be split into multiple texture tiles *\/\n\tTexture_tiling *texture_tiling; \/** If a given texture is compiled into tiles\n\t\t\t\t\t\t\t\t\t\t\t\t\t then this field is filled in and expected to\n\t\t\t\t\t\t\t\t\t\t\t\t\t be used when compiling graphics that use that material. *\/\n\t\npublic:\n\tRender_graphics_opengl(Graphics_buffer *graphics_buffer) :\n\t\tgraphics_buffer(graphics_buffer)\n\t{\n\t\tfast_changing = 0;\n\t\tpicking = 0;\n\t\tallow_texture_tiling = 0;\n\t\ttexture_tiling = NULL;\n\t}\n\n\t\/***************************************************************************\/\/**\n\t * @see Render_graphics::Scene_compile\n\t *\/\n\tvirtual int Scene_compile(Scene *scene);\n\n\t\/***************************************************************************\/\/**\n\t * @see Render_graphics::Graphics_object_compile\n\t *\/\n\tvirtual int Graphics_object_compile(GT_object *graphics_object);\n\n\t\/***************************************************************************\/\/**\n\t * @see Render_graphics::Material_compile\n\t *\/\n\tvirtual int Material_compile(Graphical_material *material);\n\n\t\/**************************************************************************\/\/**\n\t * Temporarily override the viewing coordinates so that the current opengl\n\t * display is in normalised device coordinates (aligned with the viewport).\n\t *\/\n\tvirtual int Start_ndc_coordinates() = 0;\n\n\t\/**************************************************************************\/\/**\n\t * Reverse the changes made by Start_ndc_coordinates and resume normal \n\t * 3D rendering.\n\t *\/\n\tvirtual int End_ndc_coordinates() = 0;\n\n}; \/* class Render_graphics_opengl *\/\n\n\n\/***************************************************************************\/\/**\n * Factory function to create a renderer that uses immediate mode \n * glBegin\/glEnd calls to render primitives.\n *\/\nRender_graphics_opengl *Render_graphics_opengl_create_glbeginend_renderer(\n\tGraphics_buffer *graphics_buffer);\n\n\/***************************************************************************\/\/**\n * Factory function to create a renderer that compiles objects into display lists\n * for rendering and uses glBegin\/glEnd calls when compiling primitives.\n *\/\nRender_graphics_opengl *Render_graphics_opengl_create_glbeginend_display_list_renderer(\n\tGraphics_buffer *graphics_buffer);\n\n\/***************************************************************************\/\/**\n * Factory function to create a renderer that uses immediate mode \n * client vertex arrays to render primitives.\n *\/\nRender_graphics_opengl *Render_graphics_opengl_create_client_vertex_arrays_renderer(\n\tGraphics_buffer *graphics_buffer);\n\n\/***************************************************************************\/\/**\n * Factory function to create a renderer that compiles objects into display lists\n * for rendering and uses client vertex arrays when compiling primitives.\n *\/\nRender_graphics_opengl *Render_graphics_opengl_create_client_vertex_arrays_display_list_renderer(\n\tGraphics_buffer *graphics_buffer);\n\n\/***************************************************************************\/\/**\n * Factory function to create a renderer that uses immediate mode \n * vertex buffer objects to render primitives.\n *\/\nRender_graphics_opengl *Render_graphics_opengl_create_vertex_buffer_object_renderer(\n\tGraphics_buffer *graphics_buffer);\n\n\/***************************************************************************\/\/**\n * Factory function to create a renderer that compiles objects into display lists\n * for rendering and uses vertex buffer objects when compiling primitives.\n *\/\nRender_graphics_opengl *Render_graphics_opengl_create_vertex_buffer_object_display_list_renderer(\n\tGraphics_buffer *graphics_buffer);\n\n#endif \/* !defined (RENDERGL_HPP) *\/\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ Aspia Project\n\/\/ Copyright (C) 2018 Dmitry Chapyshev <dmitry@aspia.ru>\n\/\/\n\/\/ This program is free software: you can redistribute it and\/or modify\n\/\/ it under the terms of the GNU General Public License as published by\n\/\/ the Free Software Foundation, either version 3 of the License, or\n\/\/ (at your option) any later version.\n\/\/\n\/\/ This program is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n\/\/ GNU General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU General Public License\n\/\/ along with this program. If not, see <https:\/\/www.gnu.org\/licenses\/>.\n\/\/\n\n#include \"host\/host_settings.h\"\n\n#include \"base\/logging.h\"\n#include \"base\/xml_settings.h\"\n#include \"build\/build_config.h\"\n#include \"crypto\/random.h\"\n#include \"network\/srp_user.h\"\n\nnamespace aspia {\n\nHostSettings::HostSettings()\n : settings_(XmlSettings::registerFormat(),\n QSettings::SystemScope,\n QLatin1String(\"aspia\"),\n QLatin1String(\"host\"))\n{\n \/\/ Nothing\n}\n\nHostSettings::~HostSettings() = default;\n\nQString HostSettings::filePath() const\n{\n return settings_.fileName();\n}\n\nbool HostSettings::isWritable() const\n{\n return settings_.isWritable();\n}\n\nQString HostSettings::locale() const\n{\n return settings_.value(QLatin1String(\"Locale\"), DEFAULT_LOCALE).toString();\n}\n\nvoid HostSettings::setLocale(const QString& locale)\n{\n settings_.setValue(QLatin1String(\"Locale\"), locale);\n}\n\nuint16_t HostSettings::tcpPort() const\n{\n return settings_.value(QLatin1String(\"TcpPort\"), DEFAULT_HOST_TCP_PORT).toUInt();\n}\n\nvoid HostSettings::setTcpPort(uint16_t port)\n{\n settings_.setValue(QLatin1String(\"TcpPort\"), port);\n}\n\nbool HostSettings::addFirewallRule() const\n{\n return settings_.value(QLatin1String(\"AddFirewallRule\"), true).toBool();\n}\n\nvoid HostSettings::setAddFirewallRule(bool value)\n{\n settings_.setValue(QLatin1String(\"AddFirewallRule\"), value);\n}\n\nSrpUserList HostSettings::userList() const\n{\n SrpUserList users;\n\n users.seed_key = settings_.value(QLatin1String(\"SeedKey\")).toByteArray();\n if (users.seed_key.isEmpty())\n users.seed_key = Random::generateBuffer(64);\n\n int size = settings_.beginReadArray(QLatin1String(\"Users\"));\n for (int i = 0; i < size; ++i)\n {\n settings_.setArrayIndex(i);\n\n SrpUser user;\n user.name = settings_.value(QLatin1String(\"Name\")).toString();\n user.salt = QByteArray::fromBase64(settings_.value(QLatin1String(\"Salt\")).toByteArray());\n user.verifier = QByteArray::fromBase64(settings_.value(QLatin1String(\"Verifier\")).toByteArray());\n user.number = QByteArray::fromBase64(settings_.value(QLatin1String(\"Number\")).toByteArray());\n user.generator = QByteArray::fromBase64(settings_.value(QLatin1String(\"Generator\")).toByteArray());\n user.sessions = settings_.value(QLatin1String(\"Sessions\")).toUInt();\n user.flags = settings_.value(QLatin1String(\"Flags\")).toUInt();\n\n CHECK(!user.name.isEmpty());\n CHECK(!user.salt.isEmpty());\n CHECK(!user.verifier.isEmpty());\n CHECK(!user.number.isEmpty());\n CHECK(!user.generator.isEmpty());\n\n users.list.append(user);\n }\n settings_.endArray();\n\n return users;\n}\n\nvoid HostSettings::setUserList(const SrpUserList& users)\n{\n \/\/ Clear the old list of users.\n settings_.remove(QLatin1String(\"Users\"));\n\n settings_.setValue(QLatin1String(\"SeedKey\"), users.seed_key.toBase64());\n\n settings_.beginWriteArray(QLatin1String(\"Users\"));\n for (int i = 0; i < users.list.size(); ++i)\n {\n settings_.setArrayIndex(i);\n\n const SrpUser& user = users.list.at(i);\n\n settings_.setValue(QLatin1String(\"Name\"), user.name);\n settings_.setValue(QLatin1String(\"Salt\"), user.salt.toBase64());\n settings_.setValue(QLatin1String(\"Verifier\"), user.verifier.toBase64());\n settings_.setValue(QLatin1String(\"Number\"), user.number.toBase64());\n settings_.setValue(QLatin1String(\"Generator\"), user.generator.toBase64());\n settings_.setValue(QLatin1String(\"Sessions\"), user.sessions);\n settings_.setValue(QLatin1String(\"Flags\"), user.flags);\n }\n settings_.endArray();\n}\n\nQString HostSettings::updateServer() const\n{\n return settings_.value(QLatin1String(\"UpdateServer\"), DEFAULT_UPDATE_SERVER).toString();\n}\n\nvoid HostSettings::setUpdateServer(const QString& server)\n{\n settings_.setValue(QLatin1String(\"UpdateServer\"), server);\n}\n\nbool HostSettings::remoteUpdate() const\n{\n return settings_.value(QLatin1String(\"RemoteUpdate\"), true).toBool();\n}\n\nvoid HostSettings::setRemoteUpdate(bool allow)\n{\n settings_.setValue(QLatin1String(\"RemoteUpdate\"), allow);\n}\n\n} \/\/ namespace aspia\n<commit_msg>- Converting to base64 is no longer necessary.<commit_after>\/\/\n\/\/ Aspia Project\n\/\/ Copyright (C) 2018 Dmitry Chapyshev <dmitry@aspia.ru>\n\/\/\n\/\/ This program is free software: you can redistribute it and\/or modify\n\/\/ it under the terms of the GNU General Public License as published by\n\/\/ the Free Software Foundation, either version 3 of the License, or\n\/\/ (at your option) any later version.\n\/\/\n\/\/ This program is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n\/\/ GNU General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU General Public License\n\/\/ along with this program. If not, see <https:\/\/www.gnu.org\/licenses\/>.\n\/\/\n\n#include \"host\/host_settings.h\"\n\n#include \"base\/logging.h\"\n#include \"base\/xml_settings.h\"\n#include \"build\/build_config.h\"\n#include \"crypto\/random.h\"\n#include \"network\/srp_user.h\"\n\nnamespace aspia {\n\nHostSettings::HostSettings()\n : settings_(XmlSettings::registerFormat(),\n QSettings::SystemScope,\n QLatin1String(\"aspia\"),\n QLatin1String(\"host\"))\n{\n \/\/ Nothing\n}\n\nHostSettings::~HostSettings() = default;\n\nQString HostSettings::filePath() const\n{\n return settings_.fileName();\n}\n\nbool HostSettings::isWritable() const\n{\n return settings_.isWritable();\n}\n\nQString HostSettings::locale() const\n{\n return settings_.value(QLatin1String(\"Locale\"), DEFAULT_LOCALE).toString();\n}\n\nvoid HostSettings::setLocale(const QString& locale)\n{\n settings_.setValue(QLatin1String(\"Locale\"), locale);\n}\n\nuint16_t HostSettings::tcpPort() const\n{\n return settings_.value(QLatin1String(\"TcpPort\"), DEFAULT_HOST_TCP_PORT).toUInt();\n}\n\nvoid HostSettings::setTcpPort(uint16_t port)\n{\n settings_.setValue(QLatin1String(\"TcpPort\"), port);\n}\n\nbool HostSettings::addFirewallRule() const\n{\n return settings_.value(QLatin1String(\"AddFirewallRule\"), true).toBool();\n}\n\nvoid HostSettings::setAddFirewallRule(bool value)\n{\n settings_.setValue(QLatin1String(\"AddFirewallRule\"), value);\n}\n\nSrpUserList HostSettings::userList() const\n{\n SrpUserList users;\n\n users.seed_key = settings_.value(QLatin1String(\"SeedKey\")).toByteArray();\n if (users.seed_key.isEmpty())\n users.seed_key = Random::generateBuffer(64);\n\n int size = settings_.beginReadArray(QLatin1String(\"Users\"));\n for (int i = 0; i < size; ++i)\n {\n settings_.setArrayIndex(i);\n\n SrpUser user;\n user.name = settings_.value(QLatin1String(\"Name\")).toString();\n user.salt = settings_.value(QLatin1String(\"Salt\")).toByteArray();\n user.verifier = settings_.value(QLatin1String(\"Verifier\")).toByteArray();\n user.number = settings_.value(QLatin1String(\"Number\")).toByteArray();\n user.generator = settings_.value(QLatin1String(\"Generator\")).toByteArray();\n user.sessions = settings_.value(QLatin1String(\"Sessions\")).toUInt();\n user.flags = settings_.value(QLatin1String(\"Flags\")).toUInt();\n\n CHECK(!user.name.isEmpty());\n CHECK(!user.salt.isEmpty());\n CHECK(!user.verifier.isEmpty());\n CHECK(!user.number.isEmpty());\n CHECK(!user.generator.isEmpty());\n\n users.list.append(user);\n }\n settings_.endArray();\n\n return users;\n}\n\nvoid HostSettings::setUserList(const SrpUserList& users)\n{\n \/\/ Clear the old list of users.\n settings_.remove(QLatin1String(\"Users\"));\n\n settings_.setValue(QLatin1String(\"SeedKey\"), users.seed_key);\n\n settings_.beginWriteArray(QLatin1String(\"Users\"));\n for (int i = 0; i < users.list.size(); ++i)\n {\n settings_.setArrayIndex(i);\n\n const SrpUser& user = users.list.at(i);\n\n settings_.setValue(QLatin1String(\"Name\"), user.name);\n settings_.setValue(QLatin1String(\"Salt\"), user.salt);\n settings_.setValue(QLatin1String(\"Verifier\"), user.verifier);\n settings_.setValue(QLatin1String(\"Number\"), user.number);\n settings_.setValue(QLatin1String(\"Generator\"), user.generator);\n settings_.setValue(QLatin1String(\"Sessions\"), user.sessions);\n settings_.setValue(QLatin1String(\"Flags\"), user.flags);\n }\n settings_.endArray();\n}\n\nQString HostSettings::updateServer() const\n{\n return settings_.value(QLatin1String(\"UpdateServer\"), DEFAULT_UPDATE_SERVER).toString();\n}\n\nvoid HostSettings::setUpdateServer(const QString& server)\n{\n settings_.setValue(QLatin1String(\"UpdateServer\"), server);\n}\n\nbool HostSettings::remoteUpdate() const\n{\n return settings_.value(QLatin1String(\"RemoteUpdate\"), true).toBool();\n}\n\nvoid HostSettings::setRemoteUpdate(bool allow)\n{\n settings_.setValue(QLatin1String(\"RemoteUpdate\"), allow);\n}\n\n} \/\/ namespace aspia\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2013 Mirus Project\n\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n\/\/\n\/\/ paging.cpp - interface for paging and related structures\n\/\/\n\n#include <mem\/paging.hpp>\n#include <mem\/kheap.hpp>\n\nnamespace mirus\n{\n namespace mem\n {\n page_directory_t* kernel_directory = 0;\n page_directory_t* current_directory = 0;\n\n uint32_t* frames;\n uint32_t nframes;\n\n extern uint32_t placement_address;\n\n #define INDEX_FROM_BIT(a) (a \/ 0x20)\n #define OFFSET_FROM_BIT(a) (a % 0x20)\n\n static void set_frame(uint32_t frame_addr)\n {\n uint32_t frame = frame_addr \/ 0x1000;\n uint32_t index = INDEX_FROM_BIT(frame);\n uint32_t offset = OFFSET_FROM_BIT(frame);\n \n frames[index] |= (0x1 << offset);\n }\n\n static void clear_frame(uint32_t frame_addr)\n {\n uint32_t frame = frame_addr \/ 0x1000;\n uint32_t index = INDEX_FROM_BIT(frame);\n uint32_t offset = OFFSET_FROM_BIT(frame);\n \n frames[index] &= ~(0x1 << offset);\n }\n\n static uint32_t test_frame(uint32_t frame_addr)\n {\n uint32_t frame = frame_addr \/ 0x1000;\n uint32_t index = INDEX_FROM_BIT(frame);\n uint32_t offset = OFFSET_FROM_BIT(frame);\n\n return (frames[index] & (0x1 << offset));\n }\n\n static uint32_t first_frame()\n {\n for (uint32_t i = 0; i < INDEX_FROM_BIT(nframes); i++)\n {\n if (frames[i] != 0xFFFFFFFF)\n {\n for (uint32_t j = 0; j < 32; j++)\n {\n uint32_t test = 0x1 << j;\n\n if (!(frames[i]&test))\n return i * 0x20 +j;\n }\n }\n }\n }\n\n void alloc_frame(page_t* page, uint32_t is_kernel, int is_writeable)\n {\n if (page->frame != 0)\n {\n page->present = 1;\n page->rw = (is_writeable == 1) ? 1:0;\n page->user = (is_kernel == 1) ? 0:1;\n return;\n }\n else\n {\n uint32_t index = first_frame();\n set_frame(index * 0x1000);\n page->present = 1;\n page->rw = (is_writeable == 1) ? 1 : 0;\n page->user = (is_kernel == 1) ? 0 : 1;\n page->frame = index;\n }\n }\n\n void free_frame(page_t* page)\n {\n uint32_t frame;\n\n if (!(frame = page->frame))\n return;\n else\n {\n clear_frame(frame * 0x1000);\n page->frame = 0x0;\n }\n }\n\n void paging::init(uint32_t memsize)\n {\n nframes = memsize \/ 4;\n frames = (uint32_t*)kmalloc(INDEX_FROM_BIT(nframes * 8));\n memset(frames, 0, INDEX_FROM_BIT(nframes));\n\n kernel_directory = (page_directory_t*)kmalloc_a(sizeof(page_directory_t));\n current_directory = kernel_directory;\n\n for (uintptr_t i = 0; i < placement_address + 0x3000; i += 0x1000) \n alloc_frame(paging::get_page(i, 1, kernel_directory), 1, 0);\n\n cpu::irq::install_handler(14, paging::page_fault);\n kernel_directory->physical_address = (uintptr_t)kernel_directory->tables_physical;\n paging::switch_page_directory(kernel_directory);\n }\n\n void paging::switch_page_directory(page_directory_t* dir)\n {\n current_directory = dir;\n\n asm volatile(\"mov %0, %%cr3\":: \"r\"(current_directory->physical_address));\n uint32_t cr0;\n asm volatile(\"mov %%cr0, %0\": \"=r\"(cr0));\n cr0 |= 0x80000000;\n asm volatile(\"mov %0, %%cr0\":: \"r\"(cr0));\n }\n\n page_t* paging::get_page(uint32_t address, int make, page_directory_t* dir)\n {\n address \/= 0x1000;\n uint32_t table_index = address \/ 1024;\n\n if (dir->tables[table_index])\n return &dir->tables[table_index]->pages[address % 1024];\n else if (make)\n {\n uint32_t temp;\n \n dir->tables[table_index] = \n (page_table_t*)kmalloc_ap(sizeof(page_table_t), &temp);\n dir->tables_physical[table_index] = temp | 0x7;\n return &dir->tables[table_index]->pages[address % 1024];\n }\n else\n return 0;\n }\n\n void paging::page_fault(cpu::regs* regs)\n {\n \/\/ A page fault has occurred.\n \/\/ The faulting address is stored in the CR2 register.\n uint32_t faulting_address;\n asm volatile(\"mov %%cr2, %0\" : \"=r\" (faulting_address));\n \n \/\/ The error code gives us details of what happened.\n int present = !(regs->err_code & 0x1); \/\/ Page not present\n int rw = regs->err_code & 0x2; \/\/ Write operation?\n int us = regs->err_code & 0x4; \/\/ Processor was in user-mode?\n int reserved = regs->err_code & 0x8; \/\/ Overwritten CPU-reserved bits of page entry?\n int id = regs->err_code & 0x10; \/\/ Caused by an instruction fetch?\n\n \/\/ Output an error message.\n kprintf(\"Page fault! ( \");\n if (present) {kprintf(\"present \");}\n if (rw) {kprintf(\"read-only \");}\n if (us) {kprintf(\"user-mode \");}\n if (reserved) {kprintf(\"reserved \");}\n kprintf(\") at %x\\n\", faulting_address);\n }\n } \/\/ !namespace\n} \/\/ !namespace<commit_msg>It still dies<commit_after>\/\/ Copyright 2013 Mirus Project\n\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n\/\/\n\/\/ paging.cpp - interface for paging and related structures\n\/\/\n\n#include <mem\/paging.hpp>\n#include <mem\/kheap.hpp>\n\nnamespace mirus\n{\n namespace mem\n {\n page_directory_t* kernel_directory = 0;\n page_directory_t* current_directory = 0;\n\n uint32_t* frames;\n uint32_t nframes;\n\n extern uint32_t placement_address;\n\n #define INDEX_FROM_BIT(a) (a \/ 0x20)\n #define OFFSET_FROM_BIT(a) (a % 0x20)\n\n static void set_frame(uint32_t frame_addr)\n {\n uint32_t frame = frame_addr \/ 0x1000;\n uint32_t index = INDEX_FROM_BIT(frame);\n uint32_t offset = OFFSET_FROM_BIT(frame);\n \n frames[index] |= (0x1 << offset);\n }\n\n static void clear_frame(uint32_t frame_addr)\n {\n uint32_t frame = frame_addr \/ 0x1000;\n uint32_t index = INDEX_FROM_BIT(frame);\n uint32_t offset = OFFSET_FROM_BIT(frame);\n \n frames[index] &= ~(0x1 << offset);\n }\n\n static uint32_t test_frame(uint32_t frame_addr)\n {\n uint32_t frame = frame_addr \/ 0x1000;\n uint32_t index = INDEX_FROM_BIT(frame);\n uint32_t offset = OFFSET_FROM_BIT(frame);\n\n return (frames[index] & (0x1 << offset));\n }\n\n static uint32_t first_frame()\n {\n for (uint32_t i = 0; i < INDEX_FROM_BIT(nframes); i++)\n {\n if (frames[i] != 0xFFFFFFFF)\n {\n for (uint32_t j = 0; j < 32; j++)\n {\n uint32_t test = 0x1 << j;\n\n if (!(frames[i]&test))\n return i * 0x20 +j;\n }\n }\n }\n }\n\n void alloc_frame(page_t* page, uint32_t is_kernel, int is_writeable)\n {\n if (page->frame)\n return;\n else\n {\n uint32_t index = first_frame();\n set_frame(index * 0x1000);\n page->present = 1;\n page->rw = (is_writeable == 1) ? 1 : 0;\n page->user = (is_kernel == 1) ? 0 : 1;\n page->frame = index;\n }\n }\n\n void free_frame(page_t* page)\n {\n uint32_t frame;\n\n if (!(frame = page->frame))\n return;\n else\n {\n clear_frame(frame);\n page->frame = 0x0;\n }\n }\n\n void paging::init(uint32_t memsize)\n {\n uint32_t mem_end_page = memsize;\n nframes = mem_end_page \/ 0x1000;\n frames = (uint32_t*)kmalloc(INDEX_FROM_BIT(nframes));\n memset(frames, 0, INDEX_FROM_BIT(nframes));\n\n kernel_directory = (page_directory_t*)kmalloc_a(sizeof(page_directory_t));\n memset((uint8_t*)kernel_directory, 0, sizeof(page_directory_t));\n kernel_directory->physical_address = (uint32_t)kernel_directory->tables_physical;\n\n current_directory = kernel_directory;\n\n for (uintptr_t i = 0; i < placement_address + 0x3000; i += 0x1000) \n alloc_frame(paging::get_page(i, 1, kernel_directory), 0, 0);\n\n paging::switch_page_directory(kernel_directory);\n\n cpu::irq::install_handler(14, paging::page_fault);\n kernel_directory->physical_address = (uintptr_t)kernel_directory->tables_physical;\n paging::switch_page_directory(current_directory);\n }\n\n void paging::switch_page_directory(page_directory_t* dir)\n {\n current_directory = dir;\n\n asm volatile(\"mov %0, %%cr3\":: \"r\"(current_directory->physical_address));\n uint32_t cr0;\n asm volatile(\"mov %%cr0, %0\": \"=r\"(cr0));\n cr0 |= 0x80000000;\n asm volatile(\"mov %0, %%cr0\":: \"r\"(cr0));\n }\n\n page_t* paging::get_page(uint32_t address, int make, page_directory_t* dir)\n {\n address \/= 0x1000;\n uint32_t table_index = address \/ 1024;\n\n if (dir->tables[table_index])\n return &dir->tables[table_index]->pages[address % 1024];\n else if (make)\n {\n uint32_t temp;\n \n dir->tables[table_index] = \n (page_table_t*)kmalloc_ap(sizeof(page_table_t), &temp);\n dir->tables_physical[table_index] = temp | 0x7;\n return &dir->tables[table_index]->pages[address % 1024];\n }\n else\n return 0;\n }\n\n void paging::page_fault(cpu::regs* regs)\n {\n \/\/ A page fault has occurred.\n \/\/ The faulting address is stored in the CR2 register.\n uint32_t faulting_address;\n asm volatile(\"mov %%cr2, %0\" : \"=r\" (faulting_address));\n \n \/\/ The error code gives us details of what happened.\n int present = !(regs->err_code & 0x1); \/\/ Page not present\n int rw = regs->err_code & 0x2; \/\/ Write operation?\n int us = regs->err_code & 0x4; \/\/ Processor was in user-mode?\n int reserved = regs->err_code & 0x8; \/\/ Overwritten CPU-reserved bits of page entry?\n int id = regs->err_code & 0x10; \/\/ Caused by an instruction fetch?\n\n \/\/ Output an error message.\n kprintf(\"Page fault! ( \");\n if (present) {kprintf(\"present \");}\n if (rw) {kprintf(\"read-only \");}\n if (us) {kprintf(\"user-mode \");}\n if (reserved) {kprintf(\"reserved \");}\n kprintf(\") at %x\\n\", faulting_address);\n }\n } \/\/ !namespace\n} \/\/ !namespace<|endoftext|>"} {"text":"<commit_before>\/* Copyright © 2001-2014, Canal TP and\/or its affiliates. All rights reserved.\n\nThis file is part of Navitia,\n the software to build cool stuff with public transport.\n\nHope you'll enjoy and contribute to this project,\n powered by Canal TP (www.canaltp.fr).\nHelp us simplify mobility and open public transport:\n a non ending quest to the responsive locomotion way of traveling!\n\nLICENCE: This program is free software; you can redistribute it and\/or modify\nit under the terms of the GNU Affero General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU Affero General Public License for more details.\n\nYou should have received a copy of the GNU Affero General Public License\nalong with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n\nStay tuned using\ntwitter @navitia\nIRC #navitia on freenode\nhttps:\/\/groups.google.com\/d\/forum\/navitia\nwww.navitia.io\n*\/\n\n#include \"conf.h\"\n#include \"type\/type.pb.h\"\n#include <google\/protobuf\/descriptor.h>\n\n#include <boost\/thread.hpp>\n#include <functional>\n#include <string>\n#include <iostream>\n#include \"utils\/init.h\"\n#include \"kraken_zmq.h\"\n#include \"utils\/zmq.h\"\n#include \"utils\/functions.h\" \/\/navitia::absolute_path function\n\nstatic void show_usage(const std::string& name)\n{\n std::cerr << \"Usage:\\n\"\n << \"\\t\" << name << \" --help\\t\\tShow this message.\\n\"\n << \"\\t\" << name << \" [config_file]\\tSpecify the path of the configuration file \"\n << \"(default: kraken.ini in the current path)\"\n << std::endl;\n}\n\nint main(int argn, char** argv){\n navitia::init_app();\n navitia::kraken::Configuration conf;\n\n std::string::size_type posSlash = std::string(argv[0]).find_last_of( \"\\\\\/\" );\n std::string application = std::string(argv[0]).substr(posSlash+1);\n std::string path = navitia::absolute_path();\n if (path.empty()) {\n return 1;\n }\n std::string conf_file;\n if(argn > 1){\n std::string arg = argv[1];\n if(arg == \"-h\" || arg == \"--help\"){\n show_usage(argv[0]);\n return 0;\n }else{\n \/\/ The first argument is the path to the configuration file\n conf_file = arg;\n }\n }else{\n conf_file = path + application + \".ini\";\n }\n conf.load(conf_file);\n auto log_level = conf.log_level();\n auto log_format = conf.log_format();\n if(log_level && log_format){\n init_logger(*log_level, *log_format);\n }else{\n init_logger(conf_file);\n }\n\n DataManager<navitia::type::Data> data_manager;\n\n auto logger = log4cplus::Logger::getInstance(\"startup\");\n LOG4CPLUS_INFO(logger, \"starting kraken: \" << navitia::config::project_version);\n boost::thread_group threads;\n \/\/ Prepare our context and sockets\n zmq::context_t context(1);\n \/\/ Catch startup exceptions; without this, startup errors are on stdout\n std::string zmq_socket = conf.zmq_socket_path();\n \/\/TODO: try\/catch\n LoadBalancer lb(context);\n\n const navitia::Metrics metrics(conf.metrics_binding(), conf.instance_name());\n\n threads.create_thread(navitia::MaintenanceWorker(data_manager, conf));\n\n int nb_threads = conf.nb_threads();\n \/\/ Launch pool of worker threads\n LOG4CPLUS_INFO(logger, \"starting workers threads\");\n for(int thread_nbr = 0; thread_nbr < nb_threads; ++thread_nbr) {\n threads.create_thread(std::bind(&doWork,\n std::ref(context),\n std::ref(data_manager),\n conf,\n std::ref(metrics)));\n }\n\n \/\/Data have been loaded, we can now accept connections\n try{\n lb.bind(zmq_socket, \"inproc:\/\/workers\");\n }catch(zmq::error_t& e){\n LOG4CPLUS_ERROR(logger, \"zmq::socket_t::bind() failure: \" << e.what());\n return 1;\n }\n\n \/\/ Connect worker threads to client threads via a queue\n do{\n try{\n lb.run();\n }catch(const zmq::error_t&){}\/\/lors d'un SIGHUP on restore la queue\n }while(true);\n}\n\n<commit_msg>Fix crash artemis<commit_after>\/* Copyright © 2001-2014, Canal TP and\/or its affiliates. All rights reserved.\n\nThis file is part of Navitia,\n the software to build cool stuff with public transport.\n\nHope you'll enjoy and contribute to this project,\n powered by Canal TP (www.canaltp.fr).\nHelp us simplify mobility and open public transport:\n a non ending quest to the responsive locomotion way of traveling!\n\nLICENCE: This program is free software; you can redistribute it and\/or modify\nit under the terms of the GNU Affero General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU Affero General Public License for more details.\n\nYou should have received a copy of the GNU Affero General Public License\nalong with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n\nStay tuned using\ntwitter @navitia\nIRC #navitia on freenode\nhttps:\/\/groups.google.com\/d\/forum\/navitia\nwww.navitia.io\n*\/\n\n#include \"conf.h\"\n#include \"type\/type.pb.h\"\n#include <google\/protobuf\/descriptor.h>\n\n#include <boost\/thread.hpp>\n#include <functional>\n#include <string>\n#include <iostream>\n#include \"utils\/init.h\"\n#include \"kraken_zmq.h\"\n#include \"utils\/zmq.h\"\n#include \"utils\/functions.h\" \/\/navitia::absolute_path function\n\nstatic void show_usage(const std::string& name)\n{\n std::cerr << \"Usage:\\n\"\n << \"\\t\" << name << \" --help\\t\\tShow this message.\\n\"\n << \"\\t\" << name << \" [config_file]\\tSpecify the path of the configuration file \"\n << \"(default: kraken.ini in the current path)\"\n << std::endl;\n}\n\nint main(int argn, char** argv){\n navitia::init_app();\n navitia::kraken::Configuration conf;\n\n std::string::size_type posSlash = std::string(argv[0]).find_last_of( \"\\\\\/\" );\n std::string application = std::string(argv[0]).substr(posSlash+1);\n std::string path = navitia::absolute_path();\n if (path.empty()) {\n return 1;\n }\n std::string conf_file;\n if(argn > 1){\n std::string arg = argv[1];\n if(arg == \"-h\" || arg == \"--help\"){\n show_usage(argv[0]);\n return 0;\n }else{\n \/\/ The first argument is the path to the configuration file\n conf_file = arg;\n }\n }else{\n conf_file = path + application + \".ini\";\n }\n conf.load(conf_file);\n auto log_level = conf.log_level();\n auto log_format = conf.log_format();\n if(log_level && log_format){\n init_logger(*log_level, *log_format);\n }else{\n init_logger(conf_file);\n }\n\n DataManager<navitia::type::Data> data_manager;\n\n auto logger = log4cplus::Logger::getInstance(\"startup\");\n LOG4CPLUS_INFO(logger, \"starting kraken: \" << navitia::config::project_version);\n boost::thread_group threads;\n \/\/ Prepare our context and sockets\n zmq::context_t context(1);\n \/\/ Catch startup exceptions; without this, startup errors are on stdout\n std::string zmq_socket = conf.zmq_socket_path();\n \/\/TODO: try\/catch\n LoadBalancer lb(context);\n\n const navitia::Metrics metrics(conf.metrics_binding(), conf.instance_name());\n\n threads.create_thread(navitia::MaintenanceWorker(data_manager, conf));\n \/\/\n \/\/Data have been loaded, we can now accept connections\n try{\n lb.bind(zmq_socket, \"inproc:\/\/workers\");\n }catch(zmq::error_t& e){\n LOG4CPLUS_ERROR(logger, \"zmq::socket_t::bind() failure: \" << e.what());\n return 1;\n }\n\n int nb_threads = conf.nb_threads();\n \/\/ Launch pool of worker threads\n LOG4CPLUS_INFO(logger, \"starting workers threads\");\n for(int thread_nbr = 0; thread_nbr < nb_threads; ++thread_nbr) {\n threads.create_thread(std::bind(&doWork,\n std::ref(context),\n std::ref(data_manager),\n conf,\n std::ref(metrics)));\n }\n\n \/\/ Connect worker threads to client threads via a queue\n do{\n try{\n lb.run();\n }catch(const zmq::error_t&){}\/\/lors d'un SIGHUP on restore la queue\n }while(true);\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 1999-2007 Stephen Williams (steve@icarus.com)\n *\n * This source code is free software; you can redistribute it\n * and\/or modify it in source code form under the terms of the GNU\n * General Public License as published by the Free Software\n * Foundation; either version 2 of the License, or (at your option)\n * any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA\n *\/\n#ifdef HAVE_CVS_IDENT\n#ident \"$Id: PWire.cc,v 1.14 2007\/05\/24 04:07:11 steve Exp $\"\n#endif\n\n# include \"config.h\"\n# include \"PWire.h\"\n# include \"PExpr.h\"\n# include <assert.h>\n\nPWire::PWire(const pform_name_t&n,\n\t NetNet::Type t,\n\t NetNet::PortType pt,\n\t ivl_variable_type_t dt)\n: hname_(n), type_(t), port_type_(pt), data_type_(dt),\n signed_(false), isint_(false), port_set_(false), net_set_(false),\n port_msb_(0), port_lsb_(0), net_msb_(0), net_lsb_(0), error_cnt_(0),\n lidx_(0), ridx_(0)\n{\n if (t == NetNet::INTEGER) {\n\t type_ = NetNet::REG;\n\t signed_ = true;\n\t isint_ = true;\n }\n}\n\nNetNet::Type PWire::get_wire_type() const\n{\n return type_;\n}\n\nconst pform_name_t& PWire::path() const\n{\n return hname_;\n}\n\nbool PWire::set_wire_type(NetNet::Type t)\n{\n assert(t != NetNet::IMPLICIT);\n\n switch (type_) {\n\t case NetNet::IMPLICIT:\n\t type_ = t;\n\t return true;\n\t case NetNet::IMPLICIT_REG:\n\t if (t == NetNet::REG) { type_ = t; return true; }\n\t return false;\n\t case NetNet::REG:\n\t if (t == NetNet::INTEGER) {\n\t\t isint_ = true;\n\t\t return true;\n\t }\n\t if (t == NetNet::REG) return true;\n\t return false;\n\t default:\n\t if (type_ != t)\n\t\t return false;\n\t else\n\t\t return true;\n }\n}\n\nNetNet::PortType PWire::get_port_type() const\n{\n return port_type_;\n}\n\nbool PWire::set_port_type(NetNet::PortType pt)\n{\n assert(pt != NetNet::NOT_A_PORT);\n assert(pt != NetNet::PIMPLICIT);\n\n switch (port_type_) {\n\t case NetNet::PIMPLICIT:\n\t port_type_ = pt;\n\t return true;\n\n\t case NetNet::NOT_A_PORT:\n\t return false;\n\n\t default:\n\t if (port_type_ != pt)\n\t\t return false;\n\t else\n\t\t return true;\n }\n}\n\nbool PWire::set_data_type(ivl_variable_type_t dt)\n{\n if (data_type_ != IVL_VT_NO_TYPE)\n\t if (data_type_ != dt)\n\t\t return false;\n\t else\n\t\t return true;\n\n assert(data_type_ == IVL_VT_NO_TYPE);\n data_type_ = dt;\n return true;\n}\n\nvoid PWire::set_signed(bool flag)\n{\n signed_ = flag;\n}\n\nbool PWire::get_signed() const\n{\n return signed_;\n}\n\nbool PWire::get_isint() const\n{\n return isint_;\n}\n\n\/*\n * Since implicitly defined list of port declarations are no longer\n * considered fully defined we no longer need this routine to force\n * them to be fully defined.\n *\nvoid PWire::set_net_range()\n{\n net_msb_ = port_msb_;\n net_lsb_ = port_lsb_;\n net_set_ = true;\n}\n*\/\n\nvoid PWire::set_range(PExpr*m, PExpr*l, PWSRType type)\n{\n switch (type) {\n\t case SR_PORT:\n\t if (port_set_) {\n\t\t cerr << get_line() << \": error: Port ``\" << hname_\n\t\t << \"'' has already been declared a port.\" << endl;\n\t\t error_cnt_ += 1;\n\t } else {\n\t\t port_msb_ = m;\n\t\t port_lsb_ = l;\n\t\t port_set_ = true;\n\t }\n\t return;\n\n\t case SR_NET:\n\t if (net_set_) {\n\t\t cerr << get_line() << \": error: Net ``\" << hname_\n\t\t << \"'' has already been declared.\" << endl;\n\t\t error_cnt_ += 1;\n\t } else {\n\t\t net_msb_ = m;\n\t\t net_lsb_ = l;\n\t\t net_set_ = true;\n\t }\n\t return;\n\n\t case SR_BOTH:\n\t if (port_set_ || net_set_) {\n\t\t if (port_set_) {\n\t\t cerr << get_line() << \": error: Port ``\" << hname_\n\t\t << \"'' has already been declared a port.\" << endl;\n\t\t error_cnt_ += 1;\n\t\t }\n\t\t if (net_set_) {\n\t\t cerr << get_line() << \": error: Net ``\" << hname_\n\t\t << \"'' has already been declared.\" << endl;\n\t\t error_cnt_ += 1;\n\t\t }\n\t } else {\n\t\t port_msb_ = m;\n\t\t port_lsb_ = l;\n\t\t port_set_ = true;\n\t\t net_msb_ = m;\n\t\t net_lsb_ = l;\n\t\t net_set_ = true;\n\t }\n\t return;\n }\n}\n\nvoid PWire::set_memory_idx(PExpr*ldx, PExpr*rdx)\n{\n assert(lidx_ == 0);\n assert(ridx_ == 0);\n lidx_ = ldx;\n ridx_ = rdx;\n}\n\n<commit_msg>Error message for duplicate declare of arrays.<commit_after>\/*\n * Copyright (c) 1999-2007 Stephen Williams (steve@icarus.com)\n *\n * This source code is free software; you can redistribute it\n * and\/or modify it in source code form under the terms of the GNU\n * General Public License as published by the Free Software\n * Foundation; either version 2 of the License, or (at your option)\n * any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA\n *\/\n#ifdef HAVE_CVS_IDENT\n#ident \"$Id: PWire.cc,v 1.14 2007\/05\/24 04:07:11 steve Exp $\"\n#endif\n\n# include \"config.h\"\n# include \"PWire.h\"\n# include \"PExpr.h\"\n# include <assert.h>\n\nPWire::PWire(const pform_name_t&n,\n\t NetNet::Type t,\n\t NetNet::PortType pt,\n\t ivl_variable_type_t dt)\n: hname_(n), type_(t), port_type_(pt), data_type_(dt),\n signed_(false), isint_(false), port_set_(false), net_set_(false),\n port_msb_(0), port_lsb_(0), net_msb_(0), net_lsb_(0), error_cnt_(0),\n lidx_(0), ridx_(0)\n{\n if (t == NetNet::INTEGER) {\n\t type_ = NetNet::REG;\n\t signed_ = true;\n\t isint_ = true;\n }\n}\n\nNetNet::Type PWire::get_wire_type() const\n{\n return type_;\n}\n\nconst pform_name_t& PWire::path() const\n{\n return hname_;\n}\n\nbool PWire::set_wire_type(NetNet::Type t)\n{\n assert(t != NetNet::IMPLICIT);\n\n switch (type_) {\n\t case NetNet::IMPLICIT:\n\t type_ = t;\n\t return true;\n\t case NetNet::IMPLICIT_REG:\n\t if (t == NetNet::REG) { type_ = t; return true; }\n\t return false;\n\t case NetNet::REG:\n\t if (t == NetNet::INTEGER) {\n\t\t isint_ = true;\n\t\t return true;\n\t }\n\t if (t == NetNet::REG) return true;\n\t return false;\n\t default:\n\t if (type_ != t)\n\t\t return false;\n\t else\n\t\t return true;\n }\n}\n\nNetNet::PortType PWire::get_port_type() const\n{\n return port_type_;\n}\n\nbool PWire::set_port_type(NetNet::PortType pt)\n{\n assert(pt != NetNet::NOT_A_PORT);\n assert(pt != NetNet::PIMPLICIT);\n\n switch (port_type_) {\n\t case NetNet::PIMPLICIT:\n\t port_type_ = pt;\n\t return true;\n\n\t case NetNet::NOT_A_PORT:\n\t return false;\n\n\t default:\n\t if (port_type_ != pt)\n\t\t return false;\n\t else\n\t\t return true;\n }\n}\n\nbool PWire::set_data_type(ivl_variable_type_t dt)\n{\n if (data_type_ != IVL_VT_NO_TYPE)\n\t if (data_type_ != dt)\n\t\t return false;\n\t else\n\t\t return true;\n\n assert(data_type_ == IVL_VT_NO_TYPE);\n data_type_ = dt;\n return true;\n}\n\nvoid PWire::set_signed(bool flag)\n{\n signed_ = flag;\n}\n\nbool PWire::get_signed() const\n{\n return signed_;\n}\n\nbool PWire::get_isint() const\n{\n return isint_;\n}\n\n\/*\n * Since implicitly defined list of port declarations are no longer\n * considered fully defined we no longer need this routine to force\n * them to be fully defined.\n *\nvoid PWire::set_net_range()\n{\n net_msb_ = port_msb_;\n net_lsb_ = port_lsb_;\n net_set_ = true;\n}\n*\/\n\nvoid PWire::set_range(PExpr*m, PExpr*l, PWSRType type)\n{\n switch (type) {\n\t case SR_PORT:\n\t if (port_set_) {\n\t\t cerr << get_line() << \": error: Port ``\" << hname_\n\t\t << \"'' has already been declared a port.\" << endl;\n\t\t error_cnt_ += 1;\n\t } else {\n\t\t port_msb_ = m;\n\t\t port_lsb_ = l;\n\t\t port_set_ = true;\n\t }\n\t return;\n\n\t case SR_NET:\n\t if (net_set_) {\n\t\t cerr << get_line() << \": error: Net ``\" << hname_\n\t\t << \"'' has already been declared.\" << endl;\n\t\t error_cnt_ += 1;\n\t } else {\n\t\t net_msb_ = m;\n\t\t net_lsb_ = l;\n\t\t net_set_ = true;\n\t }\n\t return;\n\n\t case SR_BOTH:\n\t if (port_set_ || net_set_) {\n\t\t if (port_set_) {\n\t\t cerr << get_line() << \": error: Port ``\" << hname_\n\t\t << \"'' has already been declared a port.\" << endl;\n\t\t error_cnt_ += 1;\n\t\t }\n\t\t if (net_set_) {\n\t\t cerr << get_line() << \": error: Net ``\" << hname_\n\t\t << \"'' has already been declared.\" << endl;\n\t\t error_cnt_ += 1;\n\t\t }\n\t } else {\n\t\t port_msb_ = m;\n\t\t port_lsb_ = l;\n\t\t port_set_ = true;\n\t\t net_msb_ = m;\n\t\t net_lsb_ = l;\n\t\t net_set_ = true;\n\t }\n\t return;\n }\n}\n\nvoid PWire::set_memory_idx(PExpr*ldx, PExpr*rdx)\n{\n if (lidx_ != 0 || ridx_ != 0) {\n\t cerr << get_line() << \": error: Array ``\" << hname_\n\t << \"'' has already been declared.\" << endl;\n\t error_cnt_ += 1;\n } else {\n lidx_ = ldx;\n ridx_ = rdx;\n }\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/* Copyright © 2001-2014, Canal TP and\/or its affiliates. All rights reserved.\n \nThis file is part of Navitia,\n the software to build cool stuff with public transport.\n \nHope you'll enjoy and contribute to this project,\n powered by Canal TP (www.canaltp.fr).\nHelp us simplify mobility and open public transport:\n a non ending quest to the responsive locomotion way of traveling!\n \nLICENCE: This program is free software; you can redistribute it and\/or modify\nit under the terms of the GNU Affero General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n \nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU Affero General Public License for more details.\n \nYou should have received a copy of the GNU Affero General Public License\nalong with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n \nStay tuned using\ntwitter @navitia \nIRC #navitia on freenode\nhttps:\/\/groups.google.com\/d\/forum\/navitia\nwww.navitia.io\n*\/\n\n#include \"raptor.h\"\n#include \"type\/data.h\"\n#include \"utils\/timer.h\"\n#include <boost\/program_options.hpp>\n#include <boost\/progress.hpp>\n#include <random>\n#include <fstream>\n#include \"utils\/init.h\"\n\nusing namespace navitia;\nusing namespace routing;\nnamespace po = boost::program_options;\n\nstruct PathDemand {\n type::idx_t start;\n type::idx_t target;\n unsigned int date;\n unsigned int hour;\n};\n\nstruct Result {\n int duration;\n int time;\n int arrival;\n int nb_changes;\n\n Result(Path path) : duration(path.duration.total_seconds()), time(-1), arrival(-1), nb_changes(path.nb_changes) {\n if(!path.items.empty())\n arrival = path.items.back().arrival.time_of_day().total_seconds();\n }\n};\n\nint main(int argc, char** argv){\n navitia::init_app();\n po::options_description desc(\"Options de l'outil de benchmark\");\n std::string file, output;\n int iterations, start, target, date, hour;\n\n desc.add_options()\n (\"help\", \"Show this message\")\n (\"interations,i\", po::value<int>(&iterations)->default_value(100),\n \"Number of iterations (10 calcuations par iteration)\")\n (\"file,f\", po::value<std::string>(&file)->default_value(\"data.nav.lz4\"),\n \"Path to data.nav.lz4\")\n (\"start,s\", po::value<int>(&start)->default_value(-1),\n \"Start of a particular journey\")\n (\"target,t\", po::value<int>(&target)->default_value(-1),\n \"Target of a particular journey\")\n (\"date,d\", po::value<int>(&date)->default_value(-1),\n \"Begginning date of a particular journey\")\n (\"hour,h\", po::value<int>(&hour)->default_value(-1),\n \"Begginning hour of a particular journey\")\n (\"verbose,v\", \"Verbose debugging output\")\n (\"output,o\", po::value<std::string>(&output)->default_value(\"benchmark.csv\"),\n \"Output file\");\n po::variables_map vm;\n po::store(po::parse_command_line(argc, argv, desc), vm);\n po::notify(vm);\n bool verbose = vm.count(\"verbose\");\n\n if (vm.count(\"help\")) {\n std::cout << \"This is used to benchmark journey computation\" << std::endl;\n std::cout << desc << std::endl;\n return 1;\n }\n\n type::Data data;\n {\n Timer t(\"Chargement des données : \" + file);\n data.load(file);\n }\n std::vector<PathDemand> demands;\n\n if(start != -1 && target != -1 && date != -1 && hour != -1) {\n PathDemand demand;\n demand.start = start;\n demand.target = target;\n demand.hour = hour;\n demand.date = date;\n demands.push_back(demand);\n } else {\n \/\/ Génération des instances\n std::random_device rd;\n std::mt19937 rng(31442);\n std::uniform_int_distribution<> gen(0,data.pt_data->stop_areas.size()-1);\n std::vector<unsigned int> hours{0, 28800, 36000, 72000, 86000};\n std::vector<unsigned int> days({7});\n if(data.pt_data->validity_patterns.front()->beginning_date.day_of_week().as_number() == 6)\n days.push_back(8);\n else\n days.push_back(13);\n\n for(int i = 0; i < iterations; ++i) {\n PathDemand demand;\n demand.start = gen(rng);\n demand.target = gen(rng);\n while(demand.start == demand.target) {\n demand.target = gen(rng);\n demand.start = gen(rng);\n }\n for(auto day : days) {\n for(auto hour : hours) {\n demand.date = day;\n demand.hour = hour;\n demands.push_back(demand);\n }\n }\n }\n }\n\n \/\/ Calculs des itinéraires\n std::vector<Result> results;\n data.build_raptor();\n RAPTOR router(data);\n\n std::cout << \"On lance le benchmark de l'algo \" << std::endl;\n boost::progress_display show_progress(demands.size());\n Timer t(\"Calcul avec l'algorithme \");\n \/\/ProfilerStart(\"bench.prof\");\n int nb_reponses = 0;\n for(auto demand : demands){\n ++show_progress;\n Timer t2;\n if (verbose){\n std::cout << data.pt_data->stop_areas[demand.start]->uri\n << \", \" << demand.start\n << \", \" << data.pt_data->stop_areas[demand.target]->uri\n << \", \" << demand.target\n << \", \" << demand.date\n << \", \" << demand.hour\n << \"\\n\";\n }\n auto res = router.compute(data.pt_data->stop_areas[demand.start], data.pt_data->stop_areas[demand.target], demand.hour, demand.date, navitia::DateTimeUtils::inf,false, true);\n\n Path path;\n if(res.size() > 0) {\n path = res[0];\n ++ nb_reponses;\n }\n\n Result result(path);\n result.time = t2.ms();\n results.push_back(result);\n }\n \/\/ProfilerStop();\n\n\n Timer ecriture(\"Writing results\");\n std::fstream out_file(output, std::ios::out);\n out_file << \"Start, Start id, Target, Target id, Day, Hour\";\n out_file << \", \"\n << \"arrival, \"\n << \"duration, \"\n << \"nb_change, \"\n << \"visited, \"\n << \"time\";\n out_file << \"\\n\";\n\n for(size_t i = 0; i < demands.size(); ++i){\n PathDemand demand = demands[i];\n out_file << data.pt_data->stop_areas[demand.start]->uri\n << \", \" << demand.start\n << \", \" << data.pt_data->stop_areas[demand.target]->uri\n << \", \" << demand.target\n << \", \" << demand.date\n << \", \" << demand.hour;\n\n out_file << \", \"\n << results[i].arrival << \", \"\n << results[i].duration << \", \"\n << results[i].nb_changes << \", \"\n << results[i].time;\n\n out_file << \"\\n\";\n }\n out_file.close();\n\n std::cout << \"Number of requests :\" << demands.size() << std::endl;\n std::cout << \"Number of results with solution\" << nb_reponses << std::endl;\n}\n<commit_msg>Benchmark: add possibility to run again the same tests<commit_after>\/* Copyright © 2001-2014, Canal TP and\/or its affiliates. All rights reserved.\n \nThis file is part of Navitia,\n the software to build cool stuff with public transport.\n \nHope you'll enjoy and contribute to this project,\n powered by Canal TP (www.canaltp.fr).\nHelp us simplify mobility and open public transport:\n a non ending quest to the responsive locomotion way of traveling!\n \nLICENCE: This program is free software; you can redistribute it and\/or modify\nit under the terms of the GNU Affero General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n \nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU Affero General Public License for more details.\n \nYou should have received a copy of the GNU Affero General Public License\nalong with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n \nStay tuned using\ntwitter @navitia \nIRC #navitia on freenode\nhttps:\/\/groups.google.com\/d\/forum\/navitia\nwww.navitia.io\n*\/\n\n#include \"raptor.h\"\n#include \"type\/data.h\"\n#include \"utils\/timer.h\"\n#include <boost\/program_options.hpp>\n#include <boost\/progress.hpp>\n#include <random>\n#include <fstream>\n#include \"utils\/init.h\"\n#include \"utils\/csv.h\"\n\nusing namespace navitia;\nusing namespace routing;\nnamespace po = boost::program_options;\n\nstruct PathDemand {\n type::idx_t start;\n type::idx_t target;\n unsigned int date;\n unsigned int hour;\n};\n\nstruct Result {\n int duration;\n int time;\n int arrival;\n int nb_changes;\n\n Result(Path path) : duration(path.duration.total_seconds()), time(-1), arrival(-1), nb_changes(path.nb_changes) {\n if(!path.items.empty())\n arrival = path.items.back().arrival.time_of_day().total_seconds();\n }\n};\n\nint main(int argc, char** argv){\n navitia::init_app();\n po::options_description desc(\"Options de l'outil de benchmark\");\n std::string file, output, stop_input_file;\n int iterations, start, target, date, hour;\n\n desc.add_options()\n (\"help\", \"Show this message\")\n (\"interations,i\", po::value<int>(&iterations)->default_value(100),\n \"Number of iterations (10 calcuations par iteration)\")\n (\"file,f\", po::value<std::string>(&file)->default_value(\"data.nav.lz4\"),\n \"Path to data.nav.lz4\")\n (\"start,s\", po::value<int>(&start)->default_value(-1),\n \"Start of a particular journey\")\n (\"target,t\", po::value<int>(&target)->default_value(-1),\n \"Target of a particular journey\")\n (\"date,d\", po::value<int>(&date)->default_value(-1),\n \"Begginning date of a particular journey\")\n (\"hour,h\", po::value<int>(&hour)->default_value(-1),\n \"Begginning hour of a particular journey\")\n (\"verbose,v\", \"Verbose debugging output\")\n (\"stop_files\", po::value<std::string>(&stop_input_file), \"File with list of start and target\")\n (\"output,o\", po::value<std::string>(&output)->default_value(\"benchmark.csv\"),\n \"Output file\");\n po::variables_map vm;\n po::store(po::parse_command_line(argc, argv, desc), vm);\n po::notify(vm);\n bool verbose = vm.count(\"verbose\");\n\n if (vm.count(\"help\")) {\n std::cout << \"This is used to benchmark journey computation\" << std::endl;\n std::cout << desc << std::endl;\n return 1;\n }\n\n type::Data data;\n {\n Timer t(\"Chargement des données : \" + file);\n data.load(file);\n }\n std::vector<PathDemand> demands;\n\n if (! stop_input_file.empty()) {\n \/\/csv file should be the same as the output one\n CsvReader csv(stop_input_file, ',');\n csv.next();\n size_t cpt_not_found = 0;\n for (auto it = csv.next(); ! csv.eof(); it = csv.next()) {\n const auto it_start = data.pt_data->stop_areas_map.find(it[0]);\n if (it_start == data.pt_data->stop_areas_map.end()) {\n std::cout << \"impossible to find \" << it[0] << std::endl;\n cpt_not_found++;\n continue;\n }\n const auto start = it_start->second;\n\n const auto it_end = data.pt_data->stop_areas_map.find(it[2]);\n if (it_end == data.pt_data->stop_areas_map.end()) {\n std::cout << \"impossible to find \" << it[2] << std::endl;\n cpt_not_found++;\n continue;\n }\n const auto end = it_end->second;\n\n PathDemand demand;\n demand.start = start->idx;\n demand.target = end->idx;\n demand.hour = boost::lexical_cast<unsigned int>(it[5]);\n demand.date = boost::lexical_cast<unsigned int>(it[4]);\n demands.push_back(demand);\n }\n std::cout << \"nb start not found \" << cpt_not_found << std::endl;\n }\n else if(start != -1 && target != -1 && date != -1 && hour != -1) {\n PathDemand demand;\n demand.start = start;\n demand.target = target;\n demand.hour = hour;\n demand.date = date;\n demands.push_back(demand);\n } else {\n \/\/ Génération des instances\n std::random_device rd;\n std::mt19937 rng(31442);\n std::uniform_int_distribution<> gen(0,data.pt_data->stop_areas.size()-1);\n std::vector<unsigned int> hours{0, 28800, 36000, 72000, 86000};\n std::vector<unsigned int> days({7});\n if(data.pt_data->validity_patterns.front()->beginning_date.day_of_week().as_number() == 6)\n days.push_back(8);\n else\n days.push_back(13);\n\n for(int i = 0; i < iterations; ++i) {\n PathDemand demand;\n demand.start = gen(rng);\n demand.target = gen(rng);\n while(demand.start == demand.target) {\n demand.target = gen(rng);\n demand.start = gen(rng);\n }\n for(auto day : days) {\n for(auto hour : hours) {\n demand.date = day;\n demand.hour = hour;\n demands.push_back(demand);\n }\n }\n }\n }\n\n \/\/ Calculs des itinéraires\n std::vector<Result> results;\n data.build_raptor();\n RAPTOR router(data);\n\n std::cout << \"On lance le benchmark de l'algo \" << std::endl;\n boost::progress_display show_progress(demands.size());\n Timer t(\"Calcul avec l'algorithme \");\n \/\/ProfilerStart(\"bench.prof\");\n int nb_reponses = 0;\n for(auto demand : demands){\n ++show_progress;\n Timer t2;\n if (verbose){\n std::cout << data.pt_data->stop_areas[demand.start]->uri\n << \", \" << demand.start\n << \", \" << data.pt_data->stop_areas[demand.target]->uri\n << \", \" << demand.target\n << \", \" << demand.date\n << \", \" << demand.hour\n << \"\\n\";\n }\n auto res = router.compute(data.pt_data->stop_areas[demand.start], data.pt_data->stop_areas[demand.target], demand.hour, demand.date, navitia::DateTimeUtils::inf,false, true);\n\n Path path;\n if(res.size() > 0) {\n path = res[0];\n ++ nb_reponses;\n }\n\n Result result(path);\n result.time = t2.ms();\n results.push_back(result);\n }\n \/\/ProfilerStop();\n\n\n Timer ecriture(\"Writing results\");\n std::fstream out_file(output, std::ios::out);\n out_file << \"Start, Start id, Target, Target id, Day, Hour\";\n out_file << \", \"\n << \"arrival, \"\n << \"duration, \"\n << \"nb_change, \"\n << \"visited, \"\n << \"time\";\n out_file << \"\\n\";\n\n for(size_t i = 0; i < demands.size(); ++i){\n PathDemand demand = demands[i];\n out_file << data.pt_data->stop_areas[demand.start]->uri\n << \", \" << demand.start\n << \", \" << data.pt_data->stop_areas[demand.target]->uri\n << \", \" << demand.target\n << \", \" << demand.date\n << \", \" << demand.hour;\n\n out_file << \", \"\n << results[i].arrival << \", \"\n << results[i].duration << \", \"\n << results[i].nb_changes << \", \"\n << results[i].time;\n\n out_file << \"\\n\";\n }\n out_file.close();\n\n std::cout << \"Number of requests :\" << demands.size() << std::endl;\n std::cout << \"Number of results with solution\" << nb_reponses << std::endl;\n}\n<|endoftext|>"} {"text":"<commit_before>#include <ctime>\r\n#include <iostream>\r\n#include <cmath>\r\n\r\nusing namespace std;\r\n\r\nint main() {\r\n\r\n\tint side{ 0 };\r\n\tint roll{ 0 };\r\n\tcout << \"Enter ctrl + z in place of a number to exit at any time.\" << endl << endl;\r\n\twhile (!cin.fail()) {\r\n\t\tsrand(time(0));\r\n\t\tcout << \"Enter the amount of sides your dice needs: \";\r\n\t\tcin >> side;\r\n\t\tcout << \"Enter how many times you need to roll this die: \";\r\n\t\tcin >> roll;\r\n\t\twhile (cin.fail())\r\n\t\t{\r\n\t\t\tsystem(\"pause\");\r\n\t\t\treturn 0;\r\n\t\t}\r\n\t\tcout << endl << \"Your rolls are below.\" << endl;\r\n\t\tfor (int i = 0; i < roll; i++)\r\n\t\t\tcout << 1 + rand() % side << endl;\r\n\t}\r\n\r\n\tsystem(\"pause\");\r\n\treturn 0;\r\n\r\n}<commit_msg>Update Roll.cpp<commit_after>#include <ctime>\r\n#include <iostream>\r\n#include <cmath>\r\n\r\nusing namespace std;\r\n\r\nint main() {\r\n\r\n\tint side{ 0 };\r\n\tint roll{ 0 };\r\n\t\/\/User exit method prompt\r\n\tcout << \"Enter ctrl + z in place of a number to exit at any time.\" << endl << endl;\r\n\twhile (!cin.fail()) { \/\/While ctrl+z is not entered\r\n\t\tsrand(time(0));\/\/seed random numbers for rolling die\r\n\t\t\/\/prompt for die size (d20, d6, d8, etc) and get user input\r\n\t\tcout << \"Enter the amount of sides your dice needs: \"; \r\n\t\tcin >> side;\r\n\t\t\/\/prompt for roll amount and get user input\r\n\t\tcout << \"Enter how many times you need to roll this die: \";\r\n\t\tcin >> roll;\r\n\t\twhile (cin.fail()) \/\/check for user exit method\r\n\t\t{\r\n\t\t\tsystem(\"pause\");\r\n\t\t\treturn 0;\r\n\t\t}\r\n\t\t\/\/output roll results\r\n\t\tcout << endl << \"Your rolls are below.\" << endl;\r\n\t\t\/\/repeat as many times as user requested\r\n\t\tfor (int i = 0; i < roll; i++)\r\n\t\t\t\/\/calculate roll range and output each roll on its own line\r\n\t\t\tcout << 1 + rand() % side << endl;\r\n\t}\r\n\/\/end program statements because it's a habit\r\n\tsystem(\"pause\");\r\n\treturn 0;\r\n\r\n}\r\n<|endoftext|>"} {"text":"<commit_before>\/\/ For conditions of distribution and use, see copyright notice in license.txt\n\n#include \"StableHeaders.h\"\n#include \"DebugOperatorNew.h\"\n\n#include \"EC_3DCanvasSource.h\"\n\n#include \"EC_3DCanvas.h\"\n#include \"EC_Mesh.h\"\n#include \"EC_OgreCustomObject.h\"\n#include \"IModule.h\"\n#include \"ModuleManager.h\"\n#include \"Entity.h\"\n#include \"UiProxyWidget.h\"\n#include \"UiServiceInterface.h\"\n#include \"LoggingFunctions.h\"\n\nDEFINE_POCO_LOGGING_FUNCTIONS(\"EC_3DCanvasSource\")\n\n#include <QWebView>\n#include <QLineEdit>\n#include <QApplication>\n#include <QPushButton>\n#include <QUiLoader>\n#include <QVBoxLayout>\n#include <QGraphicsScene>\n#include <QPushButton>\n#include <QProgressBar>\n#include <QSize>\n\n#include \"MemoryLeakCheck.h\"\n\nEC_3DCanvasSource::EC_3DCanvasSource(IModule *module) :\n IComponent(module->GetFramework()),\n source(this, \"Source\", \"\"),\n submesh(this, \"Submesh\", 0),\n refreshRate(this, \"Refresh per sec\", 0),\n show2d(this, \"Show 2D on click\", true),\n sync2dbrowsing(this, \"Sync 2D browsing\", false),\n pageWidth(this, \"Page width\", 800),\n pageHeight(this, \"Page height\", 600),\n widget_(0),\n content_widget_(0),\n placeholder_widget_(0),\n button_refreshstop_(0),\n progress_bar_(0),\n proxy_(0),\n source_edit_(0),\n canvas_started_(false)\n{\n static AttributeMetadata size_metadata(\"\", \"100\", \"2000\", \"50\");\n pageWidth.SetMetadata(&size_metadata);\n pageHeight.SetMetadata(&size_metadata);\n\n connect(this, SIGNAL(OnAttributeChanged(IAttribute*, AttributeChange::Type)), this, SLOT(UpdateWidgetAndCanvas(IAttribute*, AttributeChange::Type)));\n connect(this, SIGNAL(ParentEntitySet()), this, SLOT(RegisterActions()));\n CreateWidget();\n}\n\nEC_3DCanvasSource::~EC_3DCanvasSource()\n{\n \/\/ Note: content widget is inside widget_s layout,\n \/\/ no need to do a separate deleteLater for it. This would cause problems on rundown.\n SAFE_DELETE_LATER(widget_);\n}\n\nvoid EC_3DCanvasSource::OnClick()\n{\n if ((getshow2d() == true) && (widget_) && (proxy_))\n {\n if (!proxy_->scene())\n return;\n if (!proxy_->scene()->isActive())\n return;\n if (proxy_->isVisible())\n proxy_->AnimatedHide();\n else\n proxy_->show();\n }\n}\n\nvoid EC_3DCanvasSource::SourceEdited()\n{\n if (!source_edit_)\n return;\n \n QString new_source = source_edit_->text();\n if (new_source != getsource())\n {\n if (getsync2dbrowsing())\n setsource(new_source);\n else\n UpdateWidget(new_source);\n }\n}\n\nvoid EC_3DCanvasSource::RefreshStopPressed()\n{\n QWebView *webview = GetWebView();\n if (!webview || !progress_bar_)\n return;\n if (progress_bar_->isVisible())\n webview->stop();\n else\n webview->reload();\n}\n\nvoid EC_3DCanvasSource::BackPressed()\n{\n QWebView *webview = GetWebView();\n if (!webview)\n return;\n webview->back();\n}\n\nvoid EC_3DCanvasSource::ForwardPressed()\n{\n QWebView *webview = GetWebView();\n if (!webview)\n return;\n webview->forward();\n}\n\nvoid EC_3DCanvasSource::HomePressed()\n{\n QWebView *webview = GetWebView();\n if (!webview || home_url_.isEmpty())\n return;\n webview->load(QUrl(home_url_));\n}\n\nvoid EC_3DCanvasSource::UpdateWidgetAndCanvas(IAttribute *attribute, AttributeChange::Type type)\n{\n EC_3DCanvas *canvas = Get3DCanvas();\n bool update = false;\n if (attribute == &submesh)\n {\n if (canvas)\n {\n int my_submesh = getsubmesh();\n if (my_submesh < 0)\n my_submesh = 0;\n if (!canvas->GetSubMeshes().contains(my_submesh))\n {\n canvas->SetSubmesh(my_submesh);\n update = true;\n }\n }\n else\n UpdateWidget();\n }\n else if (attribute == &source)\n {\n if (last_source_ != getsource())\n {\n UpdateWidget();\n if (!canvas_started_)\n UpdateCanvas();\n else\n update = true;\n\n if (home_url_.isEmpty())\n home_url_ = getsource();\n }\n }\n else if (attribute == &refreshRate)\n {\n if (canvas)\n {\n int ref_rate_sec = getrefreshRate();\n if (ref_rate_sec > 0)\n {\n int ref_rate_msec = 1000 \/ ref_rate_sec;\n if (canvas->GetRefreshRate() != ref_rate_msec)\n {\n canvas->SetRefreshRate(ref_rate_sec);\n canvas_started_ = false;\n UpdateCanvas();\n }\n }\n else\n canvas->SetRefreshRate(0);\n }\n }\n else if (attribute == &pageHeight || attribute == &pageWidth)\n {\n QWebView *webview = GetWebView();\n if (webview)\n {\n QSize new_size(getpageWidth(), getpageHeight());\n if (webview->size() != new_size)\n {\n webview->resize(new_size);\n update = true;\n }\n }\n }\n \n if (update && canvas)\n UpdateCanvas();\n}\n\nvoid EC_3DCanvasSource::WebViewLinkClicked(const QUrl& url)\n{\n \/\/! \\todo: check here if the link is something we want to open differently (external program etc.)\n \n \/\/ If url is different than the source, update the lineedit & browser & replicate to network\n QString url_str = url.toString();\n if (url_str != getsource())\n {\n QWebView* webwidget = dynamic_cast<QWebView*>(content_widget_);\n if (!webwidget)\n return;\n webwidget->setUrl(url);\n \n if (source_edit_)\n source_edit_->setText(url_str);\n \n if (getsync2dbrowsing())\n {\n \/\/ Set last_source now so that we won't trigger reload of the page again when the source comes back from network\n last_source_ = url_str;\n setsource(url_str);\n }\n }\n}\n\nvoid EC_3DCanvasSource::WebViewLoadStarted()\n{\n if (progress_bar_)\n progress_bar_->show();\n if (button_refreshstop_)\n button_refreshstop_->setStyleSheet(\"QPushButton#button_refreshstop { background-image: url('.\/data\/ui\/images\/browser\/stop.png'); }\");\n}\n\nvoid EC_3DCanvasSource::WebViewLoadProgress(int progress)\n{\n if (progress_bar_)\n progress_bar_->setValue(progress);\n}\n\nvoid EC_3DCanvasSource::WebViewLoadCompleted()\n{\n \/\/ Setup ui\n if (progress_bar_)\n progress_bar_->hide();\n if (button_refreshstop_)\n button_refreshstop_->setStyleSheet(\"QPushButton#button_refreshstop { background-image: url('.\/data\/ui\/images\/browser\/refresh.png'); }\");\n \n \/\/ Update the 2d ui line edit\n QWebView *webview = GetWebView();\n if (webview && source_edit_)\n source_edit_->setText(webview->url().toString());\n\n \/\/ Invoke a delayed repaint of the inworld texture\n QTimer::singleShot(50, this, SLOT(RepaintCanvas()));\n}\n\nvoid EC_3DCanvasSource::RepaintCanvas()\n{\n EC_3DCanvas *canvas = Get3DCanvas();\n if (canvas)\n canvas->Update();\n}\n\nEC_3DCanvas *EC_3DCanvasSource::Get3DCanvas()\n{\n Scene::Entity* entity = GetParentEntity();\n if (!entity)\n return 0;\n ComponentPtr comp = entity->GetComponent(EC_3DCanvas::TypeNameStatic());\n if (!comp)\n return 0;\n EC_3DCanvas* canvas = checked_static_cast<EC_3DCanvas*>(comp.get());\n return canvas;\n}\n\nQWebView *EC_3DCanvasSource::GetWebView()\n{\n if (!content_widget_)\n return 0;\n return dynamic_cast<QWebView*>(content_widget_);\n}\n\nvoid EC_3DCanvasSource::UpdateWidget(QString url)\n{\n \/\/ Prefer inparam over the attribute (if sync 2d browsing is disabled)\n QString source;\n if (url.isEmpty())\n source = getsource();\n else\n source = url;\n\n if (source.isEmpty())\n {\n QTimer::singleShot(1000, this, SLOT(FetchWebViewUrl()));\n return;\n }\n\n if (source != last_source_)\n {\n if (source_edit_)\n source_edit_->setText(source);\n last_source_ = source;\n\n if (!placeholder_widget_)\n {\n LogError(\"No placeholder widget, cannot create content widget\");\n return;\n }\n \n \/\/ See if source looks like an url, and instantiate a QWebView then if it doesn't already exist\n if (source.indexOf(\"http:\/\/\") != -1)\n {\n QWebView* webwidget = GetWebView();\n if (!webwidget)\n {\n \/\/ If widget exists, but is wrong type, delete and recreate\n if (content_widget_)\n {\n content_widget_->deleteLater();\n content_widget_ = 0;\n }\n \n webwidget = new QWebView(placeholder_widget_);\n QVBoxLayout *layout = placeholder_widget_->findChild<QVBoxLayout*>(\"widget_placeholder_layout\");\n if (layout)\n layout->addWidget(webwidget);\n\n \/\/ Load current source and resize to attribute set size\n webwidget->load(QUrl(source));\n webwidget->page()->setLinkDelegationPolicy(QWebPage::DelegateAllLinks);\n webwidget->resize(getpageWidth(), getpageHeight());\n \n \/\/ Connect webview signals\n connect(webwidget, SIGNAL(loadStarted()), this, SLOT(WebViewLoadStarted()), Qt::UniqueConnection);\n connect(webwidget, SIGNAL(loadProgress(int)), this, SLOT(WebViewLoadProgress(int)), Qt::UniqueConnection);\n connect(webwidget, SIGNAL(loadFinished(bool)), this, SLOT(WebViewLoadCompleted()), Qt::UniqueConnection);\n connect(webwidget, SIGNAL(linkClicked(const QUrl&)), this, SLOT(WebViewLinkClicked(const QUrl &)), Qt::UniqueConnection);\n connect(webwidget->page(), SIGNAL(scrollRequested(int, int, const QRect&)), this, SLOT(RepaintCanvas()), Qt::UniqueConnection);\n\n \/\/ This webview is our new content_widget_\n content_widget_ = webwidget;\n }\n else\n {\n \/\/ If source changed, update the webview URL\n webwidget->load(QUrl(source));\n }\n }\n }\n}\n\nvoid EC_3DCanvasSource::UpdateCanvas()\n{\n if (!content_widget_)\n return;\n \n Scene::Entity* entity = GetParentEntity();\n if (!entity)\n {\n LogError(\"No parent entity, cannot create\/update 3DCanvas\");\n return;\n }\n \n ComponentPtr comp = entity->GetOrCreateComponent(EC_3DCanvas::TypeNameStatic());\n if (!comp)\n {\n LogError(\"Could not create\/get 3DCanvas component\");\n return;\n }\n \n \/\/ If entity has no valid mesh or prim yet, start a retry timer and try to set the canvas later\n if ((!entity->GetComponent(EC_Mesh::TypeNameStatic())) && \n (!entity->GetComponent(EC_OgreCustomObject::TypeNameStatic())))\n {\n \/\/LogInfo(\"Mesh or prim did not exist yet, retrying\");\n QTimer::singleShot(1000, this, SLOT(UpdateCanvas()));\n return;\n }\n \n \/\/ Set widget if different\n EC_3DCanvas* canvas = checked_static_cast<EC_3DCanvas*>(comp.get());\n if (canvas->GetWidget() != content_widget_)\n {\n canvas->SetWidget(content_widget_);\n }\n\n \/\/ Set submesh if different\n int my_submesh = getsubmesh();\n if (my_submesh < 0)\n my_submesh = 0;\n if (!canvas->GetSubMeshes().contains(my_submesh))\n canvas->SetSubmesh(my_submesh);\n\n \/\/ Refresh rate\n int ref_rate_sec = getrefreshRate();\n if (ref_rate_sec > 0)\n {\n int ref_rate_msec = 1000 \/ ref_rate_sec;\n if (canvas->GetRefreshRate() != ref_rate_msec)\n {\n canvas->SetRefreshRate(ref_rate_sec);\n canvas_started_ = false;\n }\n }\n else\n canvas->SetRefreshRate(0);\n\n \/\/ Start if first run\n if (!canvas_started_)\n {\n canvas->Start();\n canvas_started_ = true;\n }\n \/\/ Update otherwise\n else\n {\n canvas->Update();\n }\n}\n\nvoid EC_3DCanvasSource::FetchWebViewUrl()\n{ \n \/\/ Workaround on the bug that ec_3canvas->webview()->url() is not valid when this component is created\/updated.\n \/\/ Somehow its doesent have time to set it before we already come here. So this polls untill the url is valid.\n\n Scene::Entity* entity = GetParentEntity();\n if (!entity)\n {\n LogError(\"No parent entity, cannot create\/update 3DCanvas\");\n return;\n }\n \n ComponentPtr comp = entity->GetOrCreateComponent(EC_3DCanvas::TypeNameStatic());\n if (!comp)\n {\n LogError(\"Could not create\/get 3DCanvas component\");\n return;\n }\n\n EC_3DCanvas* canvas = checked_static_cast<EC_3DCanvas*>(comp.get());\n QWidget *canvas_widget = canvas->GetWidget();\n if (!canvas_widget)\n return;\n QWebView *canvas_webview = dynamic_cast<QWebView*>(canvas_widget);\n if (!canvas_webview)\n return;\n QString url = canvas_webview->url().toString();\n if (!url.isEmpty())\n {\n setsource(url);\n if (home_url_.isEmpty())\n home_url_ = url;\n }\n else\n QTimer::singleShot(1000, this, SLOT(FetchWebViewUrl()));\n}\n\nvoid EC_3DCanvasSource::ChangeLanguage()\n{\n if (widget_)\n {\n QString title = tr(\"3DCanvas Controls\");\n widget_->setWindowTitle(title);\n }\n}\n\nvoid EC_3DCanvasSource::CreateWidget()\n{\n UiServiceInterface *ui = framework_->GetService<UiServiceInterface>();\n if (!ui)\n {\n LogError(\"Failed to acquire UI service\");\n return;\n }\n\n QUiLoader loader;\n loader.setLanguageChangeEnabled(true);\n QFile file(\".\/data\/ui\/3dcanvassource.ui\");\n file.open(QFile::ReadOnly);\n widget_ = loader.load(&file);\n file.close();\n \n if (!widget_)\n {\n LogError(\"Failed to create 3D canvas controls widget\");\n return;\n }\n\n widget_->setWindowTitle(tr(\"Naali Web Browser\"));\n proxy_ = ui->AddWidgetToScene(widget_);\n connect(qApp, SIGNAL(LanguageChanged()), this, SLOT(ChangeLanguage()));\n\n source_edit_ = widget_->findChild<QLineEdit*>(\"line_source\");\n if (source_edit_)\n connect(source_edit_, SIGNAL(returnPressed()), SLOT(SourceEdited()));\n\n placeholder_widget_ = widget_->findChild<QWidget*>(\"widget_placeholder\");\n\n button_refreshstop_ = widget_->findChild<QPushButton*>(\"button_refreshstop\");\n if (button_refreshstop_) \n connect(button_refreshstop_, SIGNAL(clicked()), SLOT(RefreshStopPressed()));\n\n QPushButton* button = widget_->findChild<QPushButton*>(\"button_back\");\n if (button) \n connect(button, SIGNAL(clicked()), SLOT(BackPressed()));\n\n button = widget_->findChild<QPushButton*>(\"button_forward\");\n if (button) \n connect(button, SIGNAL(clicked()), SLOT(ForwardPressed()));\n\n button = widget_->findChild<QPushButton*>(\"button_home\");\n if (button) \n connect(button, SIGNAL(clicked()), SLOT(HomePressed()));\n\n progress_bar_ = widget_->findChild<QProgressBar*>(\"progress_bar\");\n if (progress_bar_)\n progress_bar_->hide();\n}\n\nvoid EC_3DCanvasSource::RegisterActions()\n{\n Scene::Entity *entity = GetParentEntity();\n assert(entity);\n if (entity)\n entity->ConnectAction(\"MousePress\", this, SLOT(OnClick()));\n}\n\n<commit_msg>3DCanvasSource: Was trying to oad widgets and webviews into memory on a headless server, no more.<commit_after>\/\/ For conditions of distribution and use, see copyright notice in license.txt\n\n#include \"StableHeaders.h\"\n#include \"DebugOperatorNew.h\"\n\n#include \"EC_3DCanvasSource.h\"\n\n#include \"EC_3DCanvas.h\"\n#include \"EC_Mesh.h\"\n#include \"EC_OgreCustomObject.h\"\n#include \"IModule.h\"\n#include \"ModuleManager.h\"\n#include \"Entity.h\"\n#include \"UiProxyWidget.h\"\n#include \"UiServiceInterface.h\"\n#include \"LoggingFunctions.h\"\n\nDEFINE_POCO_LOGGING_FUNCTIONS(\"EC_3DCanvasSource\")\n\n#include <QWebView>\n#include <QLineEdit>\n#include <QApplication>\n#include <QPushButton>\n#include <QUiLoader>\n#include <QVBoxLayout>\n#include <QGraphicsScene>\n#include <QPushButton>\n#include <QProgressBar>\n#include <QSize>\n\n#include \"MemoryLeakCheck.h\"\n\nEC_3DCanvasSource::EC_3DCanvasSource(IModule *module) :\n IComponent(module->GetFramework()),\n source(this, \"Source\", \"\"),\n submesh(this, \"Submesh\", 0),\n refreshRate(this, \"Refresh per sec\", 0),\n show2d(this, \"Show 2D on click\", true),\n sync2dbrowsing(this, \"Sync 2D browsing\", false),\n pageWidth(this, \"Page width\", 800),\n pageHeight(this, \"Page height\", 600),\n widget_(0),\n content_widget_(0),\n placeholder_widget_(0),\n button_refreshstop_(0),\n progress_bar_(0),\n proxy_(0),\n source_edit_(0),\n canvas_started_(false)\n{\n static AttributeMetadata size_metadata(\"\", \"100\", \"2000\", \"50\");\n pageWidth.SetMetadata(&size_metadata);\n pageHeight.SetMetadata(&size_metadata);\n\n connect(this, SIGNAL(OnAttributeChanged(IAttribute*, AttributeChange::Type)), this, SLOT(UpdateWidgetAndCanvas(IAttribute*, AttributeChange::Type)));\n connect(this, SIGNAL(ParentEntitySet()), this, SLOT(RegisterActions()));\n CreateWidget();\n}\n\nEC_3DCanvasSource::~EC_3DCanvasSource()\n{\n \/\/ Note: content widget is inside widget_s layout,\n \/\/ no need to do a separate deleteLater for it. This would cause problems on rundown.\n SAFE_DELETE_LATER(widget_);\n}\n\nvoid EC_3DCanvasSource::OnClick()\n{\n if ((getshow2d() == true) && (widget_) && (proxy_))\n {\n if (!proxy_->scene())\n return;\n if (!proxy_->scene()->isActive())\n return;\n if (proxy_->isVisible())\n proxy_->AnimatedHide();\n else\n proxy_->show();\n }\n}\n\nvoid EC_3DCanvasSource::SourceEdited()\n{\n if (!source_edit_)\n return;\n \n QString new_source = source_edit_->text();\n if (new_source != getsource())\n {\n if (getsync2dbrowsing())\n setsource(new_source);\n else\n UpdateWidget(new_source);\n }\n}\n\nvoid EC_3DCanvasSource::RefreshStopPressed()\n{\n QWebView *webview = GetWebView();\n if (!webview || !progress_bar_)\n return;\n if (progress_bar_->isVisible())\n webview->stop();\n else\n webview->reload();\n}\n\nvoid EC_3DCanvasSource::BackPressed()\n{\n QWebView *webview = GetWebView();\n if (!webview)\n return;\n webview->back();\n}\n\nvoid EC_3DCanvasSource::ForwardPressed()\n{\n QWebView *webview = GetWebView();\n if (!webview)\n return;\n webview->forward();\n}\n\nvoid EC_3DCanvasSource::HomePressed()\n{\n QWebView *webview = GetWebView();\n if (!webview || home_url_.isEmpty())\n return;\n webview->load(QUrl(home_url_));\n}\n\nvoid EC_3DCanvasSource::UpdateWidgetAndCanvas(IAttribute *attribute, AttributeChange::Type type)\n{\n EC_3DCanvas *canvas = Get3DCanvas();\n bool update = false;\n if (attribute == &submesh)\n {\n if (canvas)\n {\n int my_submesh = getsubmesh();\n if (my_submesh < 0)\n my_submesh = 0;\n if (!canvas->GetSubMeshes().contains(my_submesh))\n {\n canvas->SetSubmesh(my_submesh);\n update = true;\n }\n }\n else\n UpdateWidget();\n }\n else if (attribute == &source)\n {\n if (last_source_ != getsource())\n {\n UpdateWidget();\n if (!canvas_started_)\n UpdateCanvas();\n else\n update = true;\n\n if (home_url_.isEmpty())\n home_url_ = getsource();\n }\n }\n else if (attribute == &refreshRate)\n {\n if (canvas)\n {\n int ref_rate_sec = getrefreshRate();\n if (ref_rate_sec > 0)\n {\n int ref_rate_msec = 1000 \/ ref_rate_sec;\n if (canvas->GetRefreshRate() != ref_rate_msec)\n {\n canvas->SetRefreshRate(ref_rate_sec);\n canvas_started_ = false;\n UpdateCanvas();\n }\n }\n else\n canvas->SetRefreshRate(0);\n }\n }\n else if (attribute == &pageHeight || attribute == &pageWidth)\n {\n QWebView *webview = GetWebView();\n if (webview)\n {\n QSize new_size(getpageWidth(), getpageHeight());\n if (webview->size() != new_size)\n {\n webview->resize(new_size);\n update = true;\n }\n }\n }\n \n if (update && canvas)\n UpdateCanvas();\n}\n\nvoid EC_3DCanvasSource::WebViewLinkClicked(const QUrl& url)\n{\n \/\/! \\todo: check here if the link is something we want to open differently (external program etc.)\n \n \/\/ If url is different than the source, update the lineedit & browser & replicate to network\n QString url_str = url.toString();\n if (url_str != getsource())\n {\n QWebView* webwidget = dynamic_cast<QWebView*>(content_widget_);\n if (!webwidget)\n return;\n webwidget->setUrl(url);\n \n if (source_edit_)\n source_edit_->setText(url_str);\n \n if (getsync2dbrowsing())\n {\n \/\/ Set last_source now so that we won't trigger reload of the page again when the source comes back from network\n last_source_ = url_str;\n setsource(url_str);\n }\n }\n}\n\nvoid EC_3DCanvasSource::WebViewLoadStarted()\n{\n if (progress_bar_)\n progress_bar_->show();\n if (button_refreshstop_)\n button_refreshstop_->setStyleSheet(\"QPushButton#button_refreshstop { background-image: url('.\/data\/ui\/images\/browser\/stop.png'); }\");\n}\n\nvoid EC_3DCanvasSource::WebViewLoadProgress(int progress)\n{\n if (progress_bar_)\n progress_bar_->setValue(progress);\n}\n\nvoid EC_3DCanvasSource::WebViewLoadCompleted()\n{\n \/\/ Setup ui\n if (progress_bar_)\n progress_bar_->hide();\n if (button_refreshstop_)\n button_refreshstop_->setStyleSheet(\"QPushButton#button_refreshstop { background-image: url('.\/data\/ui\/images\/browser\/refresh.png'); }\");\n \n \/\/ Update the 2d ui line edit\n QWebView *webview = GetWebView();\n if (webview && source_edit_)\n source_edit_->setText(webview->url().toString());\n\n \/\/ Invoke a delayed repaint of the inworld texture\n QTimer::singleShot(50, this, SLOT(RepaintCanvas()));\n}\n\nvoid EC_3DCanvasSource::RepaintCanvas()\n{\n EC_3DCanvas *canvas = Get3DCanvas();\n if (canvas)\n canvas->Update();\n}\n\nEC_3DCanvas *EC_3DCanvasSource::Get3DCanvas()\n{\n Scene::Entity* entity = GetParentEntity();\n if (!entity)\n return 0;\n ComponentPtr comp = entity->GetComponent(EC_3DCanvas::TypeNameStatic());\n if (!comp)\n return 0;\n EC_3DCanvas* canvas = checked_static_cast<EC_3DCanvas*>(comp.get());\n return canvas;\n}\n\nQWebView *EC_3DCanvasSource::GetWebView()\n{\n if (!content_widget_)\n return 0;\n return dynamic_cast<QWebView*>(content_widget_);\n}\n\nvoid EC_3DCanvasSource::UpdateWidget(QString url)\n{\n \/\/ Don't load QWebViews into memory if headless\n if (GetFramework()->IsHeadless())\n return;\n\n \/\/ Prefer inparam over the attribute (if sync 2d browsing is disabled)\n QString source;\n if (url.isEmpty())\n source = getsource();\n else\n source = url;\n\n if (source.isEmpty())\n {\n QTimer::singleShot(1000, this, SLOT(FetchWebViewUrl()));\n return;\n }\n\n if (source != last_source_)\n {\n if (source_edit_)\n source_edit_->setText(source);\n last_source_ = source;\n\n if (!placeholder_widget_)\n {\n LogError(\"No placeholder widget, cannot create content widget\");\n return;\n }\n \n \/\/ See if source looks like an url, and instantiate a QWebView then if it doesn't already exist\n if (source.indexOf(\"http:\/\/\") != -1)\n {\n QWebView* webwidget = GetWebView();\n if (!webwidget)\n {\n \/\/ If widget exists, but is wrong type, delete and recreate\n if (content_widget_)\n {\n content_widget_->deleteLater();\n content_widget_ = 0;\n }\n \n webwidget = new QWebView(placeholder_widget_);\n QVBoxLayout *layout = placeholder_widget_->findChild<QVBoxLayout*>(\"widget_placeholder_layout\");\n if (layout)\n layout->addWidget(webwidget);\n\n \/\/ Load current source and resize to attribute set size\n webwidget->load(QUrl(source));\n webwidget->page()->setLinkDelegationPolicy(QWebPage::DelegateAllLinks);\n webwidget->resize(getpageWidth(), getpageHeight());\n \n \/\/ Connect webview signals\n connect(webwidget, SIGNAL(loadStarted()), this, SLOT(WebViewLoadStarted()), Qt::UniqueConnection);\n connect(webwidget, SIGNAL(loadProgress(int)), this, SLOT(WebViewLoadProgress(int)), Qt::UniqueConnection);\n connect(webwidget, SIGNAL(loadFinished(bool)), this, SLOT(WebViewLoadCompleted()), Qt::UniqueConnection);\n connect(webwidget, SIGNAL(linkClicked(const QUrl&)), this, SLOT(WebViewLinkClicked(const QUrl &)), Qt::UniqueConnection);\n connect(webwidget->page(), SIGNAL(scrollRequested(int, int, const QRect&)), this, SLOT(RepaintCanvas()), Qt::UniqueConnection);\n\n \/\/ This webview is our new content_widget_\n content_widget_ = webwidget;\n }\n else\n {\n \/\/ If source changed, update the webview URL\n webwidget->load(QUrl(source));\n }\n }\n }\n}\n\nvoid EC_3DCanvasSource::UpdateCanvas()\n{\n if (!content_widget_)\n return;\n \n Scene::Entity* entity = GetParentEntity();\n if (!entity)\n {\n LogError(\"No parent entity, cannot create\/update 3DCanvas\");\n return;\n }\n \n ComponentPtr comp = entity->GetOrCreateComponent(EC_3DCanvas::TypeNameStatic());\n if (!comp)\n {\n LogError(\"Could not create\/get 3DCanvas component\");\n return;\n }\n \n \/\/ If entity has no valid mesh or prim yet, start a retry timer and try to set the canvas later\n if ((!entity->GetComponent(EC_Mesh::TypeNameStatic())) && \n (!entity->GetComponent(EC_OgreCustomObject::TypeNameStatic())))\n {\n \/\/LogInfo(\"Mesh or prim did not exist yet, retrying\");\n QTimer::singleShot(1000, this, SLOT(UpdateCanvas()));\n return;\n }\n \n \/\/ Set widget if different\n EC_3DCanvas* canvas = checked_static_cast<EC_3DCanvas*>(comp.get());\n if (canvas->GetWidget() != content_widget_)\n {\n canvas->SetWidget(content_widget_);\n }\n\n \/\/ Set submesh if different\n int my_submesh = getsubmesh();\n if (my_submesh < 0)\n my_submesh = 0;\n if (!canvas->GetSubMeshes().contains(my_submesh))\n canvas->SetSubmesh(my_submesh);\n\n \/\/ Refresh rate\n int ref_rate_sec = getrefreshRate();\n if (ref_rate_sec > 0)\n {\n int ref_rate_msec = 1000 \/ ref_rate_sec;\n if (canvas->GetRefreshRate() != ref_rate_msec)\n {\n canvas->SetRefreshRate(ref_rate_sec);\n canvas_started_ = false;\n }\n }\n else\n canvas->SetRefreshRate(0);\n\n \/\/ Start if first run\n if (!canvas_started_)\n {\n canvas->Start();\n canvas_started_ = true;\n }\n \/\/ Update otherwise\n else\n {\n canvas->Update();\n }\n}\n\nvoid EC_3DCanvasSource::FetchWebViewUrl()\n{ \n \/\/ Workaround on the bug that ec_3canvas->webview()->url() is not valid when this component is created\/updated.\n \/\/ Somehow its doesent have time to set it before we already come here. So this polls untill the url is valid.\n\n Scene::Entity* entity = GetParentEntity();\n if (!entity)\n {\n LogError(\"No parent entity, cannot create\/update 3DCanvas\");\n return;\n }\n \n ComponentPtr comp = entity->GetOrCreateComponent(EC_3DCanvas::TypeNameStatic());\n if (!comp)\n {\n LogError(\"Could not create\/get 3DCanvas component\");\n return;\n }\n\n EC_3DCanvas* canvas = checked_static_cast<EC_3DCanvas*>(comp.get());\n QWidget *canvas_widget = canvas->GetWidget();\n if (!canvas_widget)\n return;\n QWebView *canvas_webview = dynamic_cast<QWebView*>(canvas_widget);\n if (!canvas_webview)\n return;\n QString url = canvas_webview->url().toString();\n if (!url.isEmpty())\n {\n setsource(url);\n if (home_url_.isEmpty())\n home_url_ = url;\n }\n else\n QTimer::singleShot(1000, this, SLOT(FetchWebViewUrl()));\n}\n\nvoid EC_3DCanvasSource::ChangeLanguage()\n{\n if (widget_)\n {\n QString title = tr(\"3DCanvas Controls\");\n widget_->setWindowTitle(title);\n }\n}\n\nvoid EC_3DCanvasSource::CreateWidget()\n{\n if (GetFramework()->IsHeadless())\n return;\n\n UiServiceInterface *ui = framework_->GetService<UiServiceInterface>();\n if (!ui)\n {\n LogError(\"Failed to acquire UI service\");\n return;\n }\n\n QUiLoader loader;\n loader.setLanguageChangeEnabled(true);\n QFile file(\".\/data\/ui\/3dcanvassource.ui\");\n file.open(QFile::ReadOnly);\n widget_ = loader.load(&file);\n file.close();\n \n if (!widget_)\n {\n LogError(\"Failed to create 3D canvas controls widget\");\n return;\n }\n\n widget_->setWindowTitle(tr(\"Naali Web Browser\"));\n proxy_ = ui->AddWidgetToScene(widget_);\n connect(qApp, SIGNAL(LanguageChanged()), this, SLOT(ChangeLanguage()));\n\n source_edit_ = widget_->findChild<QLineEdit*>(\"line_source\");\n if (source_edit_)\n connect(source_edit_, SIGNAL(returnPressed()), SLOT(SourceEdited()));\n\n placeholder_widget_ = widget_->findChild<QWidget*>(\"widget_placeholder\");\n\n button_refreshstop_ = widget_->findChild<QPushButton*>(\"button_refreshstop\");\n if (button_refreshstop_) \n connect(button_refreshstop_, SIGNAL(clicked()), SLOT(RefreshStopPressed()));\n\n QPushButton* button = widget_->findChild<QPushButton*>(\"button_back\");\n if (button) \n connect(button, SIGNAL(clicked()), SLOT(BackPressed()));\n\n button = widget_->findChild<QPushButton*>(\"button_forward\");\n if (button) \n connect(button, SIGNAL(clicked()), SLOT(ForwardPressed()));\n\n button = widget_->findChild<QPushButton*>(\"button_home\");\n if (button) \n connect(button, SIGNAL(clicked()), SLOT(HomePressed()));\n\n progress_bar_ = widget_->findChild<QProgressBar*>(\"progress_bar\");\n if (progress_bar_)\n progress_bar_->hide();\n}\n\nvoid EC_3DCanvasSource::RegisterActions()\n{\n Scene::Entity *entity = GetParentEntity();\n assert(entity);\n if (entity)\n entity->ConnectAction(\"MousePress\", this, SLOT(OnClick()));\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ CsScripts.cpp : Defines the exported functions for the DLL application.\n\/\/\n\n#include \"stdafx.h\"\n#include \"CsScripts.h\"\n#include \"SafeArray.h\"\n#include <iostream>\n#include <sstream>\n#include <vector>\n\n\n\/\/ CLR headers\n#include <metahost.h>\n#include <CorError.h>\n\n#pragma comment(lib, \"mscoree.lib\")\n\n\/\/ Import mscorlib.tlb (Microsoft Common Language Runtime Class Library).\n#import \"mscorlib.tlb\" raw_interfaces_only\t\t\t\t\\\n high_property_prefixes(\"_get\",\"_put\",\"_putref\")\t\t\\\n rename(\"ReportEvent\", \"InteropServices_ReportEvent\")\n\n\n#import \"CsScriptManaged.tlb\" raw_interfaces_only\n\n\/\/ Debugging engine headers\n#define KDEXT_64BIT \n#include <wdbgexts.h>\n#include <Dbgeng.h>\n\nusing namespace std;\nusing namespace mscorlib;\n\n\/\/ Checks HRESULT expression and throws ComException if fails.\n\/\/\n#define CHECKCOM(expr) \\\n { \\\n HRESULT _temp_hr = (expr); \\\n if (FAILED(_temp_hr)) \\\n { \\\n WriteComException(_temp_hr, #expr); \\\n return _temp_hr; \\\n } \\\n }\n\nvoid WriteComException(HRESULT hr, const char* expression)\n{\n CAutoComPtr<IErrorInfo> errorInfo;\n\n cout << \"COM Exception!!!\" << endl;\n cout << \"HRESULT: \" << hex << showbase << hr << noshowbase << dec << endl;\n cout << \"Expression: \" << expression << endl;\n if (SUCCEEDED(GetErrorInfo(0, &errorInfo)) && errorInfo != nullptr)\n {\n BSTR description = nullptr;\n\n errorInfo->GetDescription(&description);\n if (description != nullptr)\n {\n wcout << \"Description: \" << description << endl;\n }\n\n CAutoComPtr<_Exception> exception;\n\n if (SUCCEEDED(errorInfo->QueryInterface(IID_PPV_ARGS(&exception))))\n {\n \tBSTR toString = nullptr, stackTrace = nullptr;\n\n \texception->get_ToString(&toString);\n \tif (toString != nullptr)\n \t{\n \t\twcout << \"Exception.ToString(): \" << toString << endl;\n \t}\n }\n }\n}\n\nclass HostControl : public IHostControl\n{\npublic:\n\tHostControl()\n\t\t: counter(1)\n\t{\n\t}\n\n\tvirtual HRESULT STDMETHODCALLTYPE QueryInterface(\n\t\tREFIID riid,\n\t\tvoid ** ppvObject)\n\t{\n\t\tif (riid == __uuidof(IHostControl))\n\t\t{\n\t\t\tAddRef();\n\t\t\t*ppvObject = this;\n\t\t\treturn S_OK;\n\t\t}\n\n\t\treturn E_NOINTERFACE;\n\t}\n\n\tvirtual ULONG STDMETHODCALLTYPE AddRef()\n\t{\n\t\treturn ++counter;\n\t}\n\n\tvirtual ULONG STDMETHODCALLTYPE Release()\n\t{\n\t\tULONG result = --counter;\n\n\t\tif (result == 0)\n\t\t\tdelete this;\n\t\treturn result;\n\t}\n\n\tHRESULT STDMETHODCALLTYPE GetHostManager(\n\t\t_In_ REFIID riid,\n\t\t_Outptr_result_maybenull_ void **ppv)\n\t{\n\t\treturn E_NOINTERFACE;\n\t}\n\n\tHRESULT STDMETHODCALLTYPE SetAppDomainManager(\n\t\t_In_ DWORD dwAppDomainID,\n\t\t_In_ IUnknown *pUnkAppDomainManager)\n\t{\n\t\treturn pUnkAppDomainManager->QueryInterface(__uuidof(CsScriptManaged::IExecutor), (PVOID*)&m_appDomainManager);\n\t}\n\n\tCsScriptManaged::IExecutor* GetAppDomainManager() const\n\t{\n\t\treturn m_appDomainManager;\n\t}\n\nprivate:\n\tCAutoComPtr<CsScriptManaged::IExecutor> m_appDomainManager;\n\tULONG counter;\n};\n\n\nwstring GetCurrentDllDirectory()\n{\n wchar_t dllpath[8000];\n HMODULE hm = NULL;\n\n if (!GetModuleHandleExA(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS |\n GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,\n (LPCSTR)&GetCurrentDllDirectory,\n &hm))\n {\n int ret = GetLastError();\n fprintf(stderr, \"GetModuleHandle returned %d\\n\", ret);\n }\n\n GetModuleFileNameW(hm, dllpath, ARRAYSIZE(dllpath));\n\n wstring path = dllpath;\n size_t pos = path.find_last_of('\\\\');\n\n if (pos != wstring::npos)\n path.resize(pos + 1);\n return path;\n}\n\nwstring GetWorkingDirectory()\n{\n\twchar_t dllpath[8000];\n\n\tGetCurrentDirectoryW(ARRAYSIZE(dllpath), dllpath);\n\treturn dllpath;\n}\n\nclass ClrInitializator\n{\npublic:\n\tHRESULT Initialize(const wchar_t* csScriptsManaged, IDebugClient* client)\n\t{\n\t\t\/\/ We should figure out needed runtime version\n\t\t\/\/\n\t\tCAutoComPtr<ICLRMetaHostPolicy> pClrHostPolicy;\n\n\t\tCHECKCOM(CLRCreateInstance(\n\t\t\tCLSID_CLRMetaHostPolicy,\n\t\t\tIID_ICLRMetaHostPolicy,\n\t\t\t(LPVOID*)&pClrHostPolicy));\n\n\t\twstring runtimeVersion;\n\t\twchar_t queriedRuntimeVersion[100] = { 0 };\n\t\tDWORD length = sizeof(queriedRuntimeVersion) \/ sizeof(wchar_t);\n\n\t\tCHECKCOM(pClrHostPolicy->GetRequestedRuntime(\n\t\t\tMETAHOST_POLICY_HIGHCOMPAT,\n\t\t\tcsScriptsManaged,\n\t\t\tnullptr,\n\t\t\tqueriedRuntimeVersion,\n\t\t\t&length,\n\t\t\tnullptr,\n\t\t\tnullptr,\n\t\t\tnullptr,\n\t\t\tIID_PPV_ARGS(&runtimeInfo)));\n\t\truntimeVersion = queriedRuntimeVersion;\n\n\t\t\/\/ Set custom memory manager and start CLR\n\t\t\/\/\n\t\thostControl = new HostControl();\n\t\tCHECKCOM(runtimeInfo->BindAsLegacyV2Runtime());\n\t\t\/\/CHECKCOM(runtimeInfo->SetDefaultStartupFlags(clrStartupFlags, nullptr));\n\t\tCHECKCOM(runtimeInfo->GetInterface(CLSID_CLRRuntimeHost, IID_PPV_ARGS(&clrRuntimeHost)));\n\t\tCHECKCOM(clrRuntimeHost->GetCLRControl(&clrControl));\n\t\t\/\/CHECKCOM(clrControl->SetAppDomainManagerType(L\"CsScriptManaged\", L\"CsScriptManaged.CustomAppDomainManager\"));\n\t\tCHECKCOM(clrRuntimeHost->SetHostControl(hostControl));\n\t\tCHECKCOM(clrRuntimeHost->Start());\n\n\t\t\/\/ Create a new AppDomain that will contain application configuration.\n\t\t\/\/\n\t\tCAutoComPtr<IUnknown> appDomainSetupThunk;\n\t\tCAutoComPtr<IAppDomainSetup> appDomainSetup;\n\t\tCAutoComPtr<IUnknown> appDomainThunk;\n\t\tCAutoComPtr<_AppDomain> appDomain;\n\n\t\tCHECKCOM(runtimeInfo->GetInterface(CLSID_CorRuntimeHost, IID_PPV_ARGS(&corRuntimeHost)));\n\t\tCHECKCOM(corRuntimeHost->CreateDomainSetup(&appDomainSetupThunk));\n\t\tCHECKCOM(appDomainSetupThunk->QueryInterface(IID_PPV_ARGS(&appDomainSetup)));\n\t\tCHECKCOM(corRuntimeHost->CreateDomainEx(L\"MyDomain\", appDomainSetup, nullptr, &appDomainThunk));\n\t\tCHECKCOM(appDomainThunk->QueryInterface(IID_PPV_ARGS(&appDomain)));\n\n\t\t\/\/ Load our assembly\n\t\t\/\/\n\t\tCAutoComPtr<_Assembly> mscorlibAssembly;\n\t\tCAutoComPtr<_Type> reflectionAssemblyType;\n\t\tSafeArray loadFromArguments;\n\t\tvariant_t loadFromResult;\n\t\tvariant_t arg1(csScriptsManaged);\n\n\t\tloadFromArguments.CreateVector(VT_VARIANT, 0, 1);\n\t\tloadFromArguments.PutElement(0, &arg1);\n\n\t\tCHECKCOM(GetAssemblyFromAppDomain(appDomain, L\"mscorlib\", &mscorlibAssembly));\n\t\tCHECKCOM(mscorlibAssembly->GetType_2(bstr_t(L\"System.Reflection.Assembly\"), &reflectionAssemblyType));\n\t\tCHECKCOM(reflectionAssemblyType->InvokeMember_3(bstr_t(L\"LoadFrom\"), (BindingFlags)(BindingFlags_InvokeMethod | BindingFlags_Public | BindingFlags_Static), nullptr, variant_t(), loadFromArguments, &loadFromResult));\n\n\t\t\/\/ Create our extension CLR instance\n\t\t\/\/\n\t\tCAutoComPtr<_Assembly> assembly = (_Assembly*)(IDispatch*)loadFromResult;\n\t\tvariant_t variant;\n\n\t\tCHECKCOM(assembly->CreateInstance_2(bstr_t(L\"CsScriptManaged.Executor\"), true, &variant));\n\t\tCHECKCOM(variant.punkVal->QueryInterface(&instance));\n\n\t\tCHECKCOM(InitializeContext(client));\n\t\treturn S_OK;\n\t}\n\n\tHRESULT InitializeContext(IDebugClient* client)\n\t{\n\t\tCHECKCOM(instance->InitializeContext(client));\n\t\treturn S_OK;\n\t}\n\n\tHRESULT ExecuteScript(const wchar_t* scriptPath, const vector<wstring>& arguments)\n\t{\n\t\t\/\/ Transfer all arguments to CLR\n\t\t\/\/\n\t\tSafeArray safeArray;\n\t\tbstr_t bstrScriptPath = scriptPath;\n\n\t\tsafeArray.CreateVector(VT_BSTR, 0, (ULONG)arguments.size());\n\t\tfor (size_t i = 0; i < arguments.size(); i++)\n\t\t{\n\t\t\t\/\/ Intentionally allocating string because SafeArray will automatically dispose of it.\n\t\t\t\/\/\n\t\t\tsafeArray.PutElement((LONG)i, SysAllocString(arguments[i].c_str()));\n\t\t}\n\n\t\t\/\/ Execute script function\n\t\t\/\/\n\t\tCHECKCOM(instance->ExecuteScript(bstrScriptPath, safeArray));\n\t\treturn S_OK;\n\t}\n\n\tHRESULT ExecuteScript(const wchar_t* arguments)\n\t{\n\t\t\/\/ Execute script function\n\t\t\/\/\n\t\tbstr_t bstrArguments = arguments;\n\n\t\tCHECKCOM(instance->ExecuteScript_2(bstrArguments));\n\t\treturn S_OK;\n\t}\n\n\tvoid Uninitialize()\n\t{\n\t\tclrRuntimeHost->Stop();\n\t\tcorRuntimeHost = nullptr;\n\t\tclrControl = nullptr;\n\t\tclrRuntimeHost = nullptr;\n\t\truntimeInfo = nullptr;\n\t\thostControl = nullptr;\n\t\tinstance = nullptr;\n\t}\n\nprivate:\n\tHRESULT GetAssemblyFromAppDomain(_AppDomain* appDomain, const wchar_t* assemblyName, _Assembly **assembly)\n\t{\n\t\tSAFEARRAY* safearray;\n\t\tCComSafeArray<IUnknown*> assemblies;\n\n\t\tCHECKCOM(appDomain->GetAssemblies(&safearray));\n\t\tassemblies.Attach(safearray);\n\t\tfor (int i = 0, n = assemblies.GetCount(); i < n; i++)\n\t\t{\n\t\t\tCComPtr<_Assembly> a;\n\n\t\t\ta = assemblies[i];\n\t\t\tif (a == nullptr)\n\t\t\t\tcontinue;\n\t\t\tCComBSTR assemblyFullName;\n\t\t\tCHECKCOM(a->get_FullName(&assemblyFullName));\n\t\t\tif (assemblyFullName != nullptr && _wcsnicmp(assemblyFullName, assemblyName, wcslen(assemblyName)) == 0)\n\t\t\t{\n\t\t\t\t*assembly = a.Detach();\n\t\t\t\treturn S_OK;\n\t\t\t}\n\t\t}\n\n\t\treturn E_FAIL;\n\t}\n\n\tCAutoComPtr<ICLRRuntimeInfo> runtimeInfo;\n\tCAutoComPtr<ICLRRuntimeHost> clrRuntimeHost;\n\tCAutoComPtr<ICLRControl> clrControl;\n\tCAutoComPtr<HostControl> hostControl;\n\tCAutoComPtr<ICorRuntimeHost> corRuntimeHost;\n\tCAutoComPtr<CsScriptManaged::IExecutor> instance;\n} clr;\n\nCSSCRIPTS_API HRESULT DebugExtensionInitialize(\n _Out_ PULONG Version,\n _Out_ PULONG Flags)\n{\n wstring currentDirectory = GetCurrentDllDirectory();\n wstring csScriptsManaged = currentDirectory + L\"CsScriptManaged.dll\";\n\n \/\/ Return parameters\n if (Version != nullptr)\n *Version = DEBUG_EXTENSION_VERSION(0, 1);\n if (Flags != nullptr)\n *Flags = 0;\n\n\t\/\/ Initialize CRL and CsScriptManaged library\n\tCAutoComPtr<IDebugClient> debugClient;\n\n\tCHECKCOM(DebugCreate(IID_PPV_ARGS(&debugClient)));\n\n\tHRESULT hr = clr.Initialize(csScriptsManaged.c_str(), debugClient);\n\n\treturn hr;\n}\n\nCSSCRIPTS_API void CALLBACK DebugExtensionUninitialize()\n{\n\tclr.Uninitialize();\n}\n\nHRESULT CALLBACK execute(\n\t_In_ IDebugClient* Client,\n\t_In_opt_ PCSTR Args)\n{\n\twstringstream ss;\n\n\tss << Args;\n\tclr.InitializeContext(Client);\n\treturn clr.ExecuteScript(ss.str().c_str());\n}\n<commit_msg>Removing unused code from CsScripts native code...<commit_after>\/\/ CsScripts.cpp : Defines the exported functions for the DLL application.\n\/\/\n\n#include \"stdafx.h\"\n#include \"CsScripts.h\"\n#include \"SafeArray.h\"\n#include <iostream>\n#include <sstream>\n#include <vector>\n\n\n\/\/ CLR headers\n#include <metahost.h>\n#include <CorError.h>\n\n#pragma comment(lib, \"mscoree.lib\")\n\n\/\/ Import mscorlib.tlb (Microsoft Common Language Runtime Class Library).\n#import \"mscorlib.tlb\" raw_interfaces_only\t\t\t\t\\\n high_property_prefixes(\"_get\",\"_put\",\"_putref\")\t\t\\\n rename(\"ReportEvent\", \"InteropServices_ReportEvent\")\n\n\n#import \"CsScriptManaged.tlb\" raw_interfaces_only\n\n\/\/ Debugging engine headers\n#define KDEXT_64BIT \n#include <wdbgexts.h>\n#include <Dbgeng.h>\n\nusing namespace std;\nusing namespace mscorlib;\n\n\/\/ Checks HRESULT expression and throws ComException if fails.\n\/\/\n#define CHECKCOM(expr) \\\n { \\\n HRESULT _temp_hr = (expr); \\\n if (FAILED(_temp_hr)) \\\n { \\\n WriteComException(_temp_hr, #expr); \\\n return _temp_hr; \\\n } \\\n }\n\nvoid WriteComException(HRESULT hr, const char* expression)\n{\n CAutoComPtr<IErrorInfo> errorInfo;\n\n cout << \"COM Exception!!!\" << endl;\n cout << \"HRESULT: \" << hex << showbase << hr << noshowbase << dec << endl;\n cout << \"Expression: \" << expression << endl;\n if (SUCCEEDED(GetErrorInfo(0, &errorInfo)) && errorInfo != nullptr)\n {\n BSTR description = nullptr;\n\n errorInfo->GetDescription(&description);\n if (description != nullptr)\n {\n wcout << \"Description: \" << description << endl;\n }\n\n CAutoComPtr<_Exception> exception;\n\n if (SUCCEEDED(errorInfo->QueryInterface(IID_PPV_ARGS(&exception))))\n {\n \tBSTR toString = nullptr, stackTrace = nullptr;\n\n \texception->get_ToString(&toString);\n \tif (toString != nullptr)\n \t{\n \t\twcout << \"Exception.ToString(): \" << toString << endl;\n \t}\n }\n }\n}\n\n\nwstring GetCurrentDllDirectory()\n{\n wchar_t dllpath[8000];\n HMODULE hm = NULL;\n\n if (!GetModuleHandleExA(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS |\n GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,\n (LPCSTR)&GetCurrentDllDirectory,\n &hm))\n {\n int ret = GetLastError();\n fprintf(stderr, \"GetModuleHandle returned %d\\n\", ret);\n }\n\n GetModuleFileNameW(hm, dllpath, ARRAYSIZE(dllpath));\n\n wstring path = dllpath;\n size_t pos = path.find_last_of('\\\\');\n\n if (pos != wstring::npos)\n path.resize(pos + 1);\n return path;\n}\n\nwstring GetWorkingDirectory()\n{\n\twchar_t dllpath[8000];\n\n\tGetCurrentDirectoryW(ARRAYSIZE(dllpath), dllpath);\n\treturn dllpath;\n}\n\nclass ClrInitializator\n{\npublic:\n\tHRESULT Initialize(const wchar_t* csScriptsManaged, IDebugClient* client)\n\t{\n\t\t\/\/ We should figure out needed runtime version\n\t\t\/\/\n\t\tCAutoComPtr<ICLRMetaHostPolicy> pClrHostPolicy;\n\n\t\tCHECKCOM(CLRCreateInstance(\n\t\t\tCLSID_CLRMetaHostPolicy,\n\t\t\tIID_ICLRMetaHostPolicy,\n\t\t\t(LPVOID*)&pClrHostPolicy));\n\n\t\twstring runtimeVersion;\n\t\twchar_t queriedRuntimeVersion[100] = { 0 };\n\t\tDWORD length = sizeof(queriedRuntimeVersion) \/ sizeof(wchar_t);\n\n\t\tCHECKCOM(pClrHostPolicy->GetRequestedRuntime(\n\t\t\tMETAHOST_POLICY_HIGHCOMPAT,\n\t\t\tcsScriptsManaged,\n\t\t\tnullptr,\n\t\t\tqueriedRuntimeVersion,\n\t\t\t&length,\n\t\t\tnullptr,\n\t\t\tnullptr,\n\t\t\tnullptr,\n\t\t\tIID_PPV_ARGS(&runtimeInfo)));\n\t\truntimeVersion = queriedRuntimeVersion;\n\n\t\t\/\/ Set custom memory manager and start CLR\n\t\t\/\/\n\t\tCHECKCOM(runtimeInfo->BindAsLegacyV2Runtime());\n\t\t\/\/CHECKCOM(runtimeInfo->SetDefaultStartupFlags(clrStartupFlags, nullptr));\n\t\tCHECKCOM(runtimeInfo->GetInterface(CLSID_CLRRuntimeHost, IID_PPV_ARGS(&clrRuntimeHost)));\n\t\tCHECKCOM(clrRuntimeHost->GetCLRControl(&clrControl));\n\t\tCHECKCOM(clrRuntimeHost->Start());\n\n\t\t\/\/ Create a new AppDomain that will contain application configuration.\n\t\t\/\/\n\t\tCAutoComPtr<IUnknown> appDomainSetupThunk;\n\t\tCAutoComPtr<IAppDomainSetup> appDomainSetup;\n\t\tCAutoComPtr<IUnknown> appDomainThunk;\n\t\tCAutoComPtr<_AppDomain> appDomain;\n\n\t\tCHECKCOM(runtimeInfo->GetInterface(CLSID_CorRuntimeHost, IID_PPV_ARGS(&corRuntimeHost)));\n\t\tCHECKCOM(corRuntimeHost->CreateDomainSetup(&appDomainSetupThunk));\n\t\tCHECKCOM(appDomainSetupThunk->QueryInterface(IID_PPV_ARGS(&appDomainSetup)));\n\t\tCHECKCOM(corRuntimeHost->CreateDomainEx(L\"MyDomain\", appDomainSetup, nullptr, &appDomainThunk));\n\t\tCHECKCOM(appDomainThunk->QueryInterface(IID_PPV_ARGS(&appDomain)));\n\n\t\t\/\/ Load our assembly\n\t\t\/\/\n\t\tCAutoComPtr<_Assembly> mscorlibAssembly;\n\t\tCAutoComPtr<_Type> reflectionAssemblyType;\n\t\tSafeArray loadFromArguments;\n\t\tvariant_t loadFromResult;\n\t\tvariant_t arg1(csScriptsManaged);\n\n\t\tloadFromArguments.CreateVector(VT_VARIANT, 0, 1);\n\t\tloadFromArguments.PutElement(0, &arg1);\n\n\t\tCHECKCOM(GetAssemblyFromAppDomain(appDomain, L\"mscorlib\", &mscorlibAssembly));\n\t\tCHECKCOM(mscorlibAssembly->GetType_2(bstr_t(L\"System.Reflection.Assembly\"), &reflectionAssemblyType));\n\t\tCHECKCOM(reflectionAssemblyType->InvokeMember_3(bstr_t(L\"LoadFrom\"), (BindingFlags)(BindingFlags_InvokeMethod | BindingFlags_Public | BindingFlags_Static), nullptr, variant_t(), loadFromArguments, &loadFromResult));\n\n\t\t\/\/ Create our extension CLR instance\n\t\t\/\/\n\t\tCAutoComPtr<_Assembly> assembly = (_Assembly*)(IDispatch*)loadFromResult;\n\t\tvariant_t variant;\n\n\t\tCHECKCOM(assembly->CreateInstance_2(bstr_t(L\"CsScriptManaged.Executor\"), true, &variant));\n\t\tCHECKCOM(variant.punkVal->QueryInterface(&instance));\n\n\t\tCHECKCOM(InitializeContext(client));\n\t\treturn S_OK;\n\t}\n\n\tHRESULT InitializeContext(IDebugClient* client)\n\t{\n\t\tCHECKCOM(instance->InitializeContext(client));\n\t\treturn S_OK;\n\t}\n\n\tHRESULT ExecuteScript(const wchar_t* scriptPath, const vector<wstring>& arguments)\n\t{\n\t\t\/\/ Transfer all arguments to CLR\n\t\t\/\/\n\t\tSafeArray safeArray;\n\t\tbstr_t bstrScriptPath = scriptPath;\n\n\t\tsafeArray.CreateVector(VT_BSTR, 0, (ULONG)arguments.size());\n\t\tfor (size_t i = 0; i < arguments.size(); i++)\n\t\t{\n\t\t\t\/\/ Intentionally allocating string because SafeArray will automatically dispose of it.\n\t\t\t\/\/\n\t\t\tsafeArray.PutElement((LONG)i, SysAllocString(arguments[i].c_str()));\n\t\t}\n\n\t\t\/\/ Execute script function\n\t\t\/\/\n\t\tCHECKCOM(instance->ExecuteScript(bstrScriptPath, safeArray));\n\t\treturn S_OK;\n\t}\n\n\tHRESULT ExecuteScript(const wchar_t* arguments)\n\t{\n\t\t\/\/ Execute script function\n\t\t\/\/\n\t\tbstr_t bstrArguments = arguments;\n\n\t\tCHECKCOM(instance->ExecuteScript_2(bstrArguments));\n\t\treturn S_OK;\n\t}\n\n\tvoid Uninitialize()\n\t{\n\t\tclrRuntimeHost->Stop();\n\t\tcorRuntimeHost = nullptr;\n\t\tclrControl = nullptr;\n\t\tclrRuntimeHost = nullptr;\n\t\truntimeInfo = nullptr;\n\t\tinstance = nullptr;\n\t}\n\nprivate:\n\tHRESULT GetAssemblyFromAppDomain(_AppDomain* appDomain, const wchar_t* assemblyName, _Assembly **assembly)\n\t{\n\t\tSAFEARRAY* safearray;\n\t\tCComSafeArray<IUnknown*> assemblies;\n\n\t\tCHECKCOM(appDomain->GetAssemblies(&safearray));\n\t\tassemblies.Attach(safearray);\n\t\tfor (int i = 0, n = assemblies.GetCount(); i < n; i++)\n\t\t{\n\t\t\tCComPtr<_Assembly> a;\n\n\t\t\ta = assemblies[i];\n\t\t\tif (a == nullptr)\n\t\t\t\tcontinue;\n\t\t\tCComBSTR assemblyFullName;\n\t\t\tCHECKCOM(a->get_FullName(&assemblyFullName));\n\t\t\tif (assemblyFullName != nullptr && _wcsnicmp(assemblyFullName, assemblyName, wcslen(assemblyName)) == 0)\n\t\t\t{\n\t\t\t\t*assembly = a.Detach();\n\t\t\t\treturn S_OK;\n\t\t\t}\n\t\t}\n\n\t\treturn E_FAIL;\n\t}\n\n\tCAutoComPtr<ICLRRuntimeInfo> runtimeInfo;\n\tCAutoComPtr<ICLRRuntimeHost> clrRuntimeHost;\n\tCAutoComPtr<ICLRControl> clrControl;\n\tCAutoComPtr<ICorRuntimeHost> corRuntimeHost;\n\tCAutoComPtr<CsScriptManaged::IExecutor> instance;\n} clr;\n\nCSSCRIPTS_API HRESULT DebugExtensionInitialize(\n _Out_ PULONG Version,\n _Out_ PULONG Flags)\n{\n wstring currentDirectory = GetCurrentDllDirectory();\n wstring csScriptsManaged = currentDirectory + L\"CsScriptManaged.dll\";\n\n \/\/ Return parameters\n if (Version != nullptr)\n *Version = DEBUG_EXTENSION_VERSION(0, 1);\n if (Flags != nullptr)\n *Flags = 0;\n\n\t\/\/ Initialize CRL and CsScriptManaged library\n\tCAutoComPtr<IDebugClient> debugClient;\n\n\tCHECKCOM(DebugCreate(IID_PPV_ARGS(&debugClient)));\n\n\tHRESULT hr = clr.Initialize(csScriptsManaged.c_str(), debugClient);\n\n\treturn hr;\n}\n\nCSSCRIPTS_API void CALLBACK DebugExtensionUninitialize()\n{\n\tclr.Uninitialize();\n}\n\nHRESULT CALLBACK execute(\n\t_In_ IDebugClient* Client,\n\t_In_opt_ PCSTR Args)\n{\n\twstringstream ss;\n\n\tss << Args;\n\tclr.InitializeContext(Client);\n\treturn clr.ExecuteScript(ss.str().c_str());\n}\n<|endoftext|>"} {"text":"<commit_before>\/*=========================================================================\n\n Program: Visualization Toolkit\n Module: vtkHyperTreeGridToUnstructuredGrid.cxx\n\n Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen\n All rights reserved.\n See Copyright.txt or http:\/\/www.kitware.com\/Copyright.htm for details.\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notice for more information.\n\n=========================================================================*\/\n#include \"vtkHyperTreeGridToUnstructuredGrid.h\"\n\n#include \"vtkBitArray.h\"\n#include \"vtkCellArray.h\"\n#include \"vtkCellData.h\"\n#include \"vtkHyperTreeGrid.h\"\n#include \"vtkInformation.h\"\n#include \"vtkInformationVector.h\"\n#include \"vtkObjectFactory.h\"\n#include \"vtkUnstructuredGrid.h\"\n\nvtkStandardNewMacro(vtkHyperTreeGridToUnstructuredGrid);\n\n\/\/-----------------------------------------------------------------------------\nvtkHyperTreeGridToUnstructuredGrid::vtkHyperTreeGridToUnstructuredGrid()\n{\n this->Points = 0;\n this->Cells = 0;\n this->Input = 0;\n this->Output = 0;\n\n this->Dimension = 0;\n this->CellSize = 0;\n this->Coefficients = 0;\n}\n\n\/\/-----------------------------------------------------------------------------\nvtkHyperTreeGridToUnstructuredGrid::~vtkHyperTreeGridToUnstructuredGrid()\n{\n if ( this->Points )\n {\n this->Points->Delete();\n this->Points = 0;\n }\n if ( this->Cells )\n {\n this->Cells->Delete();\n this->Cells = 0;\n }\n if ( this->Coefficients )\n {\n delete [] this->Coefficients;\n this->Coefficients = 0;\n }\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkHyperTreeGridToUnstructuredGrid::PrintSelf( ostream& os, vtkIndent indent )\n{\n this->Superclass::PrintSelf( os, indent );\n\n if( this->Input )\n {\n os << indent << \"Input:\\n\";\n this->Input->PrintSelf( os, indent.GetNextIndent() );\n }\n else\n {\n os << indent << \"Input: ( none )\\n\";\n }\n if( this->Output )\n {\n os << indent << \"Output:\\n\";\n this->Output->PrintSelf( os, indent.GetNextIndent() );\n }\n else\n {\n os << indent << \"Output: ( none )\\n\";\n }\n if( this->Points )\n {\n os << indent << \"Points:\\n\";\n this->Points->PrintSelf( os, indent.GetNextIndent() );\n }\n else\n {\n os << indent << \"Points: ( none )\\n\";\n }\n if( this->Cells )\n {\n os << indent << \"Cells:\\n\";\n this->Cells->PrintSelf( os, indent.GetNextIndent() );\n }\n else\n {\n os << indent << \"Cells: ( none )\\n\";\n }\n\n os << indent << \"Dimension : \" << this->Dimension << endl;\n os << indent << \"CellSize : \" << this->CellSize << endl;\n os << indent << \"Coefficients : \" << endl;\n for ( unsigned int i = 0; i < this->CellSize; ++ i )\n {\n os << indent;\n for ( unsigned int j = 0; j < this->Dimension; ++ j )\n {\n os << \" \" << this->Coefficients[i * this->Dimension + j];\n }\n os << endl;\n }\n}\n\n\/\/-----------------------------------------------------------------------------\nint vtkHyperTreeGridToUnstructuredGrid::FillInputPortInformation( int, vtkInformation *info )\n{\n info->Set( vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE(), \"vtkHyperTreeGrid\" );\n return 1;\n}\n\n\/\/----------------------------------------------------------------------------\nint vtkHyperTreeGridToUnstructuredGrid::RequestData( vtkInformation*,\n vtkInformationVector** inputVector,\n vtkInformationVector* outputVector )\n{\n \/\/ Get the info objects\n vtkInformation *inInfo = inputVector[0]->GetInformationObject( 0 );\n vtkInformation *outInfo = outputVector->GetInformationObject( 0 );\n\n \/\/ Retrieve input and output\n this->Input = vtkHyperTreeGrid::SafeDownCast( inInfo->Get( vtkDataObject::DATA_OBJECT() ) );\n this->Output= vtkUnstructuredGrid::SafeDownCast( outInfo->Get( vtkDataObject::DATA_OBJECT() ) );\n\n \/\/ Set instance variables needed for this conversion\n this->Dimension = this->Input->GetDimension();\n switch ( this->Dimension )\n {\n case 1:\n this->CellSize = 2;\n this->Coefficients = new unsigned int[2];\n for ( unsigned int i = 0; i < 2; ++ i )\n {\n this->Coefficients[i] = i;\n }\n break;\n case 2 :\n this->CellSize = 4;\n this->Coefficients = new unsigned int[8];\n for ( unsigned int i = 0; i < 4; ++ i )\n {\n div_t r = div( i, 2 );\n this->Coefficients[2 * i] = r.rem;\n this->Coefficients[2 * i + 1] = r.quot;\n }\n break;\n case 3 :\n this->CellSize = 8;\n this->Coefficients = new unsigned int[24];\n for ( unsigned int i = 0; i < 8; ++ i )\n {\n div_t r1 = div( i, 2 );\n div_t r2 = div( r1.quot, 2 );\n this->Coefficients[3 * i] = r1.rem;\n this->Coefficients[3 * i + 1] = r2.quot;\n this->Coefficients[3 * i + 2] = r2.rem;\n }\n break;\n default:\n vtkErrorMacro( \"Incorrect tree dimension: \"\n << this->Dimension\n << \".\" );\n return 0;\n }\n \n\n \/\/ Ensure that primal grid API is used for hyper trees\n int inputDualFlagIsOn = this->Input->GetUseDualGrid();\n if ( inputDualFlagIsOn )\n {\n this->Input->SetUseDualGrid( 0 );\n }\n\n \/\/ Initialize output cell data\n vtkCellData *outCD = this->Output->GetCellData();\n vtkCellData *inCD = this->Input->GetCellData();\n outCD->CopyAllocate( inCD );\n\n \/\/ Cut through hyper tree grid\n this->ProcessTrees();\n\n \/\/ Return duality flag of input to its original state\n if ( inputDualFlagIsOn )\n {\n this->Input->SetUseDualGrid( 1 );\n }\n\n \/\/ Clean up\n this->Input = 0;\n this->Output = 0;\n\n this->UpdateProgress ( 1. );\n\n return 1;\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid vtkHyperTreeGridToUnstructuredGrid::ProcessTrees()\n{\n \/\/ TODO: MTime on generation of this table.\n this->Input->GenerateSuperCursorTraversalTable();\n\n \/\/ Primal corner points\n this->Points = vtkPoints::New();\n this->Cells = vtkCellArray::New();\n\n \/\/ Iterate over all hyper trees\n unsigned int* gridSize = this->Input->GetGridSize();\n for ( unsigned int k = 0; k < gridSize[2]; ++ k )\n {\n for ( unsigned int j = 0; j < gridSize[1]; ++ j )\n {\n for ( unsigned int i = 0; i < gridSize[0]; ++ i )\n {\n \/\/ Storage for super cursors\n vtkHyperTreeGridSuperCursor superCursor;\n\n \/\/ Initialize center cursor\n this->Input->InitializeSuperCursor(&superCursor, i, j, k );\n\n \/\/ Traverse and populate dual recursively\n this->RecursiveProcessTree( &superCursor );\n } \/\/ i\n } \/\/ j\n } \/\/ k\n\n \/\/ Set output geometry and topology\n this->Output->SetPoints( this->Points );\n switch ( this->Dimension )\n {\n case 1:\n this->Output->SetCells( VTK_LINE, this->Cells );\n break;\n case 2:\n this->Output->SetCells( VTK_QUAD, this->Cells );\n break;\n case 3:\n this->Output->SetCells( VTK_VOXEL, this->Cells );\n break;\n }\n}\n\n\n\/\/----------------------------------------------------------------------------\nvoid vtkHyperTreeGridToUnstructuredGrid::AddCell( vtkIdType inId, \n double* origin, \n double* size )\n{\n \/\/ Storage for cell IDs\n vtkIdType ids[8];\n\n \/\/ Generate 2^d points\n double pt[3];\n pt[0] = origin[0];\n pt[1] = origin[1];\n pt[2] = origin[2];\n ids[0] = this->Points->InsertNextPoint( pt );\n for ( unsigned int i = 1; i < this->CellSize; ++ i )\n {\n for ( unsigned int j = 0; j < this->Dimension; ++ j )\n {\n pt[j] = origin[j] + this->Coefficients[i * this->Dimension + j] * size[j];\n }\n ids[i] = this->Points->InsertNextPoint( pt );\n }\n\n vtkIdType outId = this->Cells->InsertNextCell( this->CellSize, ids );\n this->Output->GetCellData()->CopyData( this->Input->GetCellData(), inId, outId );\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkHyperTreeGridToUnstructuredGrid::RecursiveProcessTree( vtkHyperTreeGridSuperCursor* superCursor )\n{\n \/\/ Get cursor at super cursor center\n vtkHyperTreeGridCursor* cursor = superCursor->GetCursor( 0 );\n\n \/\/ If cursor is not at leaf, recurse to all children\n if ( ! cursor->IsLeaf() )\n {\n int numChildren = this->Input->GetNumberOfChildren();\n for ( int child = 0; child < numChildren; ++ child )\n {\n vtkHyperTreeGridSuperCursor newSuperCursor;\n this->Input->InitializeSuperCursorChild( superCursor,&newSuperCursor, child );\n this->RecursiveProcessTree( &newSuperCursor );\n }\n return;\n }\n\n \/\/ Cursor is a leaf, retrieve its global index\n vtkIdType inId = cursor->GetGlobalLeafIndex();\n\n \/\/ If leaf is masked, skip it\n if ( ! this->Input->GetMaskedLeafIds()->GetTuple1( inId ) )\n {\n return;\n }\n\n \/\/ Create cell\n this->AddCell( inId, superCursor->Origin, superCursor->Size );\n}\n<commit_msg>whitespace cleanup<commit_after>\/*=========================================================================\n\n Program: Visualization Toolkit\n Module: vtkHyperTreeGridToUnstructuredGrid.cxx\n\n Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen\n All rights reserved.\n See Copyright.txt or http:\/\/www.kitware.com\/Copyright.htm for details.\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notice for more information.\n\n=========================================================================*\/\n#include \"vtkHyperTreeGridToUnstructuredGrid.h\"\n\n#include \"vtkBitArray.h\"\n#include \"vtkCellArray.h\"\n#include \"vtkCellData.h\"\n#include \"vtkHyperTreeGrid.h\"\n#include \"vtkInformation.h\"\n#include \"vtkInformationVector.h\"\n#include \"vtkObjectFactory.h\"\n#include \"vtkUnstructuredGrid.h\"\n\nvtkStandardNewMacro(vtkHyperTreeGridToUnstructuredGrid);\n\n\/\/-----------------------------------------------------------------------------\nvtkHyperTreeGridToUnstructuredGrid::vtkHyperTreeGridToUnstructuredGrid()\n{\n this->Points = 0;\n this->Cells = 0;\n this->Input = 0;\n this->Output = 0;\n\n this->Dimension = 0;\n this->CellSize = 0;\n this->Coefficients = 0;\n}\n\n\/\/-----------------------------------------------------------------------------\nvtkHyperTreeGridToUnstructuredGrid::~vtkHyperTreeGridToUnstructuredGrid()\n{\n if ( this->Points )\n {\n this->Points->Delete();\n this->Points = 0;\n }\n if ( this->Cells )\n {\n this->Cells->Delete();\n this->Cells = 0;\n }\n if ( this->Coefficients )\n {\n delete [] this->Coefficients;\n this->Coefficients = 0;\n }\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkHyperTreeGridToUnstructuredGrid::PrintSelf( ostream& os, vtkIndent indent )\n{\n this->Superclass::PrintSelf( os, indent );\n\n if( this->Input )\n {\n os << indent << \"Input:\\n\";\n this->Input->PrintSelf( os, indent.GetNextIndent() );\n }\n else\n {\n os << indent << \"Input: ( none )\\n\";\n }\n if( this->Output )\n {\n os << indent << \"Output:\\n\";\n this->Output->PrintSelf( os, indent.GetNextIndent() );\n }\n else\n {\n os << indent << \"Output: ( none )\\n\";\n }\n if( this->Points )\n {\n os << indent << \"Points:\\n\";\n this->Points->PrintSelf( os, indent.GetNextIndent() );\n }\n else\n {\n os << indent << \"Points: ( none )\\n\";\n }\n if( this->Cells )\n {\n os << indent << \"Cells:\\n\";\n this->Cells->PrintSelf( os, indent.GetNextIndent() );\n }\n else\n {\n os << indent << \"Cells: ( none )\\n\";\n }\n\n os << indent << \"Dimension : \" << this->Dimension << endl;\n os << indent << \"CellSize : \" << this->CellSize << endl;\n os << indent << \"Coefficients : \" << endl;\n for ( unsigned int i = 0; i < this->CellSize; ++ i )\n {\n os << indent;\n for ( unsigned int j = 0; j < this->Dimension; ++ j )\n {\n os << \" \" << this->Coefficients[i * this->Dimension + j];\n }\n os << endl;\n }\n}\n\n\/\/-----------------------------------------------------------------------------\nint vtkHyperTreeGridToUnstructuredGrid::FillInputPortInformation( int, vtkInformation *info )\n{\n info->Set( vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE(), \"vtkHyperTreeGrid\" );\n return 1;\n}\n\n\/\/----------------------------------------------------------------------------\nint vtkHyperTreeGridToUnstructuredGrid::RequestData( vtkInformation*,\n vtkInformationVector** inputVector,\n vtkInformationVector* outputVector )\n{\n \/\/ Get the info objects\n vtkInformation *inInfo = inputVector[0]->GetInformationObject( 0 );\n vtkInformation *outInfo = outputVector->GetInformationObject( 0 );\n\n \/\/ Retrieve input and output\n this->Input = vtkHyperTreeGrid::SafeDownCast( inInfo->Get( vtkDataObject::DATA_OBJECT() ) );\n this->Output= vtkUnstructuredGrid::SafeDownCast( outInfo->Get( vtkDataObject::DATA_OBJECT() ) );\n\n \/\/ Set instance variables needed for this conversion\n this->Dimension = this->Input->GetDimension();\n switch ( this->Dimension )\n {\n case 1:\n this->CellSize = 2;\n this->Coefficients = new unsigned int[2];\n for ( unsigned int i = 0; i < 2; ++ i )\n {\n this->Coefficients[i] = i;\n }\n break;\n case 2 :\n this->CellSize = 4;\n this->Coefficients = new unsigned int[8];\n for ( unsigned int i = 0; i < 4; ++ i )\n {\n div_t r = div( i, 2 );\n this->Coefficients[2 * i] = r.rem;\n this->Coefficients[2 * i + 1] = r.quot;\n }\n break;\n case 3 :\n this->CellSize = 8;\n this->Coefficients = new unsigned int[24];\n for ( unsigned int i = 0; i < 8; ++ i )\n {\n div_t r1 = div( i, 2 );\n div_t r2 = div( r1.quot, 2 );\n this->Coefficients[3 * i] = r1.rem;\n this->Coefficients[3 * i + 1] = r2.quot;\n this->Coefficients[3 * i + 2] = r2.rem;\n }\n break;\n default:\n vtkErrorMacro( \"Incorrect tree dimension: \"\n << this->Dimension\n << \".\" );\n return 0;\n }\n\n\n \/\/ Ensure that primal grid API is used for hyper trees\n int inputDualFlagIsOn = this->Input->GetUseDualGrid();\n if ( inputDualFlagIsOn )\n {\n this->Input->SetUseDualGrid( 0 );\n }\n\n \/\/ Initialize output cell data\n vtkCellData *outCD = this->Output->GetCellData();\n vtkCellData *inCD = this->Input->GetCellData();\n outCD->CopyAllocate( inCD );\n\n \/\/ Cut through hyper tree grid\n this->ProcessTrees();\n\n \/\/ Return duality flag of input to its original state\n if ( inputDualFlagIsOn )\n {\n this->Input->SetUseDualGrid( 1 );\n }\n\n \/\/ Clean up\n this->Input = 0;\n this->Output = 0;\n\n this->UpdateProgress ( 1. );\n\n return 1;\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid vtkHyperTreeGridToUnstructuredGrid::ProcessTrees()\n{\n \/\/ TODO: MTime on generation of this table.\n this->Input->GenerateSuperCursorTraversalTable();\n\n \/\/ Primal corner points\n this->Points = vtkPoints::New();\n this->Cells = vtkCellArray::New();\n\n \/\/ Iterate over all hyper trees\n unsigned int* gridSize = this->Input->GetGridSize();\n for ( unsigned int k = 0; k < gridSize[2]; ++ k )\n {\n for ( unsigned int j = 0; j < gridSize[1]; ++ j )\n {\n for ( unsigned int i = 0; i < gridSize[0]; ++ i )\n {\n \/\/ Storage for super cursors\n vtkHyperTreeGridSuperCursor superCursor;\n\n \/\/ Initialize center cursor\n this->Input->InitializeSuperCursor(&superCursor, i, j, k );\n\n \/\/ Traverse and populate dual recursively\n this->RecursiveProcessTree( &superCursor );\n } \/\/ i\n } \/\/ j\n } \/\/ k\n\n \/\/ Set output geometry and topology\n this->Output->SetPoints( this->Points );\n switch ( this->Dimension )\n {\n case 1:\n this->Output->SetCells( VTK_LINE, this->Cells );\n break;\n case 2:\n this->Output->SetCells( VTK_QUAD, this->Cells );\n break;\n case 3:\n this->Output->SetCells( VTK_VOXEL, this->Cells );\n break;\n }\n}\n\n\n\/\/----------------------------------------------------------------------------\nvoid vtkHyperTreeGridToUnstructuredGrid::AddCell( vtkIdType inId,\n double* origin,\n double* size )\n{\n \/\/ Storage for cell IDs\n vtkIdType ids[8];\n\n \/\/ Generate 2^d points\n double pt[3];\n pt[0] = origin[0];\n pt[1] = origin[1];\n pt[2] = origin[2];\n ids[0] = this->Points->InsertNextPoint( pt );\n for ( unsigned int i = 1; i < this->CellSize; ++ i )\n {\n for ( unsigned int j = 0; j < this->Dimension; ++ j )\n {\n pt[j] = origin[j] + this->Coefficients[i * this->Dimension + j] * size[j];\n }\n ids[i] = this->Points->InsertNextPoint( pt );\n }\n\n vtkIdType outId = this->Cells->InsertNextCell( this->CellSize, ids );\n this->Output->GetCellData()->CopyData( this->Input->GetCellData(), inId, outId );\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkHyperTreeGridToUnstructuredGrid::RecursiveProcessTree( vtkHyperTreeGridSuperCursor* superCursor )\n{\n \/\/ Get cursor at super cursor center\n vtkHyperTreeGridCursor* cursor = superCursor->GetCursor( 0 );\n\n \/\/ If cursor is not at leaf, recurse to all children\n if ( ! cursor->IsLeaf() )\n {\n int numChildren = this->Input->GetNumberOfChildren();\n for ( int child = 0; child < numChildren; ++ child )\n {\n vtkHyperTreeGridSuperCursor newSuperCursor;\n this->Input->InitializeSuperCursorChild( superCursor,&newSuperCursor, child );\n this->RecursiveProcessTree( &newSuperCursor );\n }\n return;\n }\n\n \/\/ Cursor is a leaf, retrieve its global index\n vtkIdType inId = cursor->GetGlobalLeafIndex();\n\n \/\/ If leaf is masked, skip it\n if ( ! this->Input->GetMaskedLeafIds()->GetTuple1( inId ) )\n {\n return;\n }\n\n \/\/ Create cell\n this->AddCell( inId, superCursor->Origin, superCursor->Size );\n}\n<|endoftext|>"} {"text":"<commit_before>\/**************************************************************************\n * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *\n * *\n * Author: The ALICE Off-line Project. *\n * Contributors are mentioned in the code where appropriate. *\n * *\n * Permission to use, copy, modify and distribute this software and its *\n * documentation strictly for non-commercial purposes is hereby granted *\n * without fee, provided that the above copyright notice appears in all *\n * copies and that both the copyright notice and this permission notice *\n * appear in the supporting documentation. The authors make no claims *\n * about the suitability of this software for any purpose. It is *\n * provided \"as is\" without express or implied warranty. *\n **************************************************************************\/\n\n\/* $Id$ *\/\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ \/\/\n\/\/ START raw data conversion class \/\/\n\/\/ \/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include <Riostream.h>\n#include <TTree.h>\n\n#include \"AliSTART.h\"\n#include \"AliSTARTRawData.h\"\n#include \"AliSTARTdigit.h\"\n#include \"AliBitPacking.h\"\n#include \"AliRawDataHeader.h\"\n#include \"AliBitPacking.h\"\n\nClassImp(AliSTARTRawData)\n\n\/\/_____________________________________________________________________________\nAliSTARTRawData::AliSTARTRawData():TObject()\n{\n \/*\n- 48 channels (2 words each as in TOF DDL) for :\nword 1 :0-5bit number of PMT; word 2: 0-7 error sign, 8-31 TDC\nand the same but for amplified signal. Now I wrote the same time because\nCDF are not ready and differences didn't measured yet.\n\n- 48 channel for amplitude: very preliminary, QTC features are not\nknown now, preliminary i put as T1 time signal for this PMT in first\nchannel and T1+A in second, where A=Log(Amplitude);\nand the same for amplified but A=Log(10*Amplitude).\n\n- T0-A and T0-C 2 channels\n- T0A-T0C vertex information\n- Time Meaner where T0C TOF increase to the T0A TOF distance\n- 6 multiplicity signals the same way as amplitude and with the same\nuncertances\n *\/\n\n fIndex=-1;\n fDigits = NULL;\n\n fTimeCFD = new TArrayI(24);\n fADC = new TArrayI(24);\n fTimeLED = new TArrayI(24);\n fADC0 = new TArrayI(24);\n \/\/ this->Dump();\n \n}\n\n\/\/_____________________________________________________________________________\nAliSTARTRawData::AliSTARTRawData(const AliSTARTRawData &r):TObject()\n{\n \/\/\n \/\/ AliSTARTrawData copy constructor\n \/\/\n\n ((AliSTARTRawData &) r).Copy(*this);\n\n}\n\n\/\/_____________________________________________________________________________\nAliSTARTRawData::~AliSTARTRawData()\n{\n \/\/\n \/\/ Destructor\n \/\/\n if (fDigits) {\n delete fDigits;\n fDigits = NULL;\n }\n delete fTimeCFD;\n delete fADC;\n delete fTimeLED;\n delete fADC0;\n}\n\n\/\/_____________________________________________________________________________\nAliSTARTRawData &AliSTARTRawData::operator=(const AliSTARTRawData &r)\n{\n \/\/\n \/\/ Assignment operator\n \/\/\n\n if (this != &r) ((AliSTARTRawData &) r).Copy(*this);\n return *this;\n\n}\n\n\/\/_____________________________________________________________________________\nvoid AliSTARTRawData::GetDigits(AliSTARTdigit *fDigits, UInt_t *buf)\n{\n \n \/\/This method packs the START digits in a proper 32 bits structure\n\n \/\/read START digits and fill TDC and ADC arrays\n\n\n UInt_t word;\n UInt_t baseWord=0;\n Int_t error=0;\n\n \/\/ Get the digits array\n\n fDigits->GetTime(*fTimeCFD);\n fDigits->GetADC(*fADC);\n fDigits->GetTimeAmp(*fTimeLED);\n fDigits->GetADCAmp(*fADC0);\n \n \/\/ Loop through all PMT\n \n for (Int_t det = 0; det < 24; det++) {\n Int_t timeLED=fTimeLED->At(det);\n \/\/ if( timeLED > 0){\n \/\/ DDL 1 0-5 -#PMT, 6-31 - empty\n \/\/LED\n word=det;;\n PackWord(baseWord,word, 0, 8); \n fIndex++;\n buf[fIndex]=baseWord;\n \n word=0;\n baseWord=0;\n word=error;\n PackWord(baseWord,word,0, 7); \/\/ Error flag\n word=timeLED;\n PackWord(baseWord,word,8,31); \/\/ time-of-flight\n fIndex++;\n buf[fIndex]=baseWord;\n word=0;\n baseWord=0;\n \/\/ }\n }\n for (Int_t det = 0; det < 24; det++) {\n \/\/CDF\n Int_t timeCFD=fTimeCFD->At(det);\n \/\/ if ( timeCFD >0 ) {\n \/\/ DDL2 2 0-5 -#PMT, 6-31 - empty\n word=0;\n baseWord=0;\n word=det+24;\n PackWord(baseWord,word, 0, 8); \/\/ number of PMT on the right side\n fIndex++;\n buf[fIndex]=baseWord;\n word=0;\n baseWord=0;\n word=error;\n PackWord(baseWord,word,0, 7); \/\/ Error flag\n word=timeCFD;\n PackWord(baseWord,word,8,31); \/\/ time-of-flight\n fIndex++;\n buf[fIndex]=baseWord;\n word=0;\n baseWord=0;\n \/\/ }\n }\n for (Int_t det = 0; det < 24; det++) {\n \/\/conver ADC to time (preliminary algorithm)\n Int_t qtc=fADC->At(det);\n \/\/ if ( qtc > 0 )\n \/\/ {\n\tword=det+48;\n\tPackWord(baseWord,word, 0, 8); \/\/ number of PMT on the right side\n\tfIndex++;\n\tbuf[fIndex]=baseWord;\n\tbaseWord=0;\n\tword=error;\n\tPackWord(baseWord,word,0, 7); \/\/ Error flag\n\tword=qtc;\n\tPackWord(baseWord,word,8,31); \/\/ Q->Time\n\tfIndex++;\n\tbuf[fIndex]=baseWord;\n \tword=0;\n\tbaseWord=0;\n\t\/\/ }\n }\n \n for (Int_t det = 0; det < 24; det++) {\n Int_t qtcAmp=fADC0->At(det);\n \n \/\/ DDL 4 amplified QTC charge * 10\n \n \/\/Amplified ADC -> TDC \n \n word=det+72;\n PackWord(baseWord,word, 0, 8); \/\/ number of PMT on the right side\n fIndex++;\n buf[fIndex]=baseWord;\n baseWord=0;\n word=error;\n PackWord(baseWord,word,0, 7); \/\/ Error flag\n word=qtcAmp;\n PackWord(baseWord,word,8,31); \/\/ Q->T amplified\n fIndex++;\n buf[fIndex]=baseWord;\n \n word=0;\n baseWord=0;\n }\n\n\n word=0;\n baseWord=0;\n fIndex++;\n word=97;\n PackWord(baseWord,word, 0, 8); \/\/ ?????????????????\n buf[fIndex]=baseWord;\n baseWord=0;\n word=error;\n PackWord(baseWord,word,0, 7); \/\/ Error flag\n word=fDigits->MeanTime();\n PackWord(baseWord,word,8,31); \/\/ MEANER\n \n fIndex++;\n buf[fIndex]=baseWord;\n\n\n\n \/\/ besttime right & left\n word=98;\n PackWord(baseWord,word, 0, 8); \/\/ T0-A sign\n fIndex++;\n buf[fIndex]=baseWord;\n\n baseWord=0;\n word=error;\n PackWord(baseWord,word,0, 7); \/\/ Error flag\n word=fDigits->BestTimeRight();\n PackWord(baseWord,word,8,31); \/\/ time-of-flight T0-A\n fIndex++;\n buf[fIndex]=baseWord;\n\n word=99;\n PackWord(baseWord,word, 0, 8); \/\/ T0-C sign\n fIndex++;\n buf[fIndex]=baseWord;\n\n baseWord=0;\n word=error;\n PackWord(baseWord,word,0, 7); \/\/ Error flag\n word=fDigits->BestTimeLeft();\n PackWord(baseWord,word,8,31); \/\/ time-of-flight T0-C \n fIndex++;\n buf[fIndex]=baseWord;\n \n \/\/ time difference\n word=100;\n PackWord(baseWord,word, 0, 8); \/\/ TVDS sign\n fIndex++;\n buf[fIndex]=baseWord;\n\n baseWord=0;\n\n word=error;\n PackWord(baseWord,word,0, 7); \/\/ Error flag\n word=fDigits->TimeDiff();\n PackWord(baseWord,word,8,31); \/\/ T0verex\n fIndex++;\n buf[fIndex]=baseWord;\n\n\n \/\/ multiplicity \n \n Int_t mult=fDigits->SumMult();\n word=101;\n PackWord(baseWord,word, 0, 8); \n fIndex++;\n buf[fIndex]=baseWord;\n \n baseWord=0;\n word=error;\n PackWord(baseWord,word,0, 7); \/\/ Error flag\n word=mult;\n PackWord(baseWord,word,8,31); \/\/ time amplitude\n fIndex++;\n buf[fIndex]=baseWord;\n \n\n\n \/\/ trigger channels\n \/\/ besttime right & left\n word=102;\n PackWord(baseWord,word, 0, 8); \/\/ T0-A sign\n fIndex++;\n buf[fIndex]=baseWord;\n\n baseWord=0;\n word=error;\n PackWord(baseWord,word,0, 7); \/\/ Error flag\n word=fDigits->BestTimeRight();\n PackWord(baseWord,word,8,31); \/\/ time-of-flight T0-A\n fIndex++;\n buf[fIndex]=baseWord;\n \n word=103;\n PackWord(baseWord,word, 0, 8); \/\/ T0-C sign\n fIndex++;\n buf[fIndex]=baseWord;\n\n baseWord=0;\n\n word=error;\n PackWord(baseWord,word,0, 7); \/\/ Error flag\n word=fDigits->BestTimeLeft();\n PackWord(baseWord,word,8,31); \/\/ time-of-flight T0-C \n fIndex++;\n buf[fIndex]=baseWord;\n\n \/\/ time difference\n word=104;\n PackWord(baseWord,word, 0, 8); \/\/ TVDS sign\n word=fDigits->TimeDiff();\n PackWord(baseWord,word, 6, 31); \/\/ T0 vertex \n fIndex++;\n buf[fIndex]=baseWord;\n\n baseWord=0;\n\n word=error;\n PackWord(baseWord,word,0, 7); \/\/ Error flag\n word=fDigits->TimeDiff();\n PackWord(baseWord,word,8,31); \/\/ T0verex\n fIndex++;\n buf[fIndex]=baseWord;\n\n \/\/ multiplicity \n \n mult=fDigits->SumMult();\n word=105;\n PackWord(baseWord,word, 0, 8); \n word=mult;\n PackWord(baseWord,word, 6, 31); \/\/ sum amplitude\n fIndex++;\n buf[fIndex]=baseWord;\n \n baseWord=0;\n word=error;\n PackWord(baseWord,word,0, 7); \/\/ Error flag\n word=mult;\n PackWord(baseWord,word,8,31); \/\/ time amplitude\n fIndex++;\n buf[fIndex]=baseWord;\n \n \/\/ multiplicity \n \n mult=fDigits->SumMult();\n word=106;\n PackWord(baseWord,word, 0, 8); \n fIndex++;\n buf[fIndex]=baseWord;\n \n baseWord=0;\n word=error;\n PackWord(baseWord,word,0, 7); \/\/ Error flag\n word=mult;\n PackWord(baseWord,word,8,31); \/\/ time amplitude\n fIndex++;\n buf[fIndex]=baseWord;\n cout<<endl;\n}\n\n\/\/-----------------------------------------------------------------------------------\n\nvoid AliSTARTRawData::PackWord(UInt_t &BaseWord, UInt_t Word, Int_t StartBit, Int_t StopBit)\n{\n \/\/This method packs a word into the Baseword buffer starting form the \"StartBit\"\n \/\/and tacking StopBit-StartBit+1 bits\n UInt_t dummyWord,offSet;\n Int_t length;\n UInt_t sum;\n \/\/The BaseWord is being filled with 1 from StartBit to StopBit\n length=StopBit-StartBit+1;\n sum=(UInt_t)TMath::Power(2,length)-1;\n\n if(Word > sum){\n Error(\"PackWord\", \"Word to be filled is not within desired length\\n\"\n \"Word:%d Start bit:%d Stop Bit:%d\",Word,StartBit,StopBit);\n return;\n }\n offSet=sum;\n offSet<<=StartBit;\n BaseWord=BaseWord|offSet;\n\n \/\/The Word to be filled is shifted to the position StartBit\n \/\/and the remaining Left and Right bits are filled with 1\n sum=(UInt_t)TMath::Power(2,StartBit)-1;\n dummyWord=0xFFFFFFFF<<length;\n dummyWord +=Word;\n dummyWord<<=StartBit;\n dummyWord+=sum;\n BaseWord=BaseWord&dummyWord;\n return;\n}\n\n\/\/---------------------------------------------------------------------------------------\n\nInt_t AliSTARTRawData::RawDataSTART(AliSTARTdigit *fDigits)\n{\n \/\/This method creates the Raw data files for START detector\n\n\n const Int_t kSize=512; \/\/2*AliTOFGeometry::NpadXSector() \n \/\/max number of digits per DDL file times 2\n UInt_t buf[kSize];\n UInt_t baseWord;\n UInt_t word;\n\n fIndex=-1;\n\n char fileName[15];\n ofstream outfile; \/\/ logical name of the output file \n AliRawDataHeader header;\n AliBitPacking *pack ;\n \/\/loop over TOF DDL files\n sprintf(fileName,\"START_%d.ddl\", 0xd00);\n \/\/ sprintf(fileName,\"START_0xd00.ddl\"); \/\/The name of the output file\n#ifndef __DECCXX\n outfile.open(fileName,ios::binary);\n#else\n outfile.open(fileName);\n#endif\n \/\/write Dummy DATA HEADER\n UInt_t dataHeaderPosition=outfile.tellp();\n outfile.write((char*)(&header),sizeof(header));\n\n baseWord=0;\n word=0;\n pack-> PackWord(baseWord,word,0, 31); \/\/ Number of DDL file\n\n fIndex++;\n buf[fIndex]=baseWord;\n GetDigits(fDigits,buf);\n\n outfile.write((char *)buf,((fIndex+1)*sizeof(UInt_t)));\n for(Int_t ii=0;ii<(fIndex+1);ii++) buf[ii]=0;\n fIndex=-1;\n \n \/\/Write REAL DATA HEADER\n UInt_t currentFilePosition=outfile.tellp();\n outfile.seekp(dataHeaderPosition);\n header.fSize=currentFilePosition-dataHeaderPosition;\n header.SetAttribute(0); \/\/ valid data\n outfile.write((char*)(&header),sizeof(header));\n outfile.close();\n\n \/\/end for\n \n return 0; \n \n}\n<commit_msg>Bug fixes (Alla)<commit_after>\/**************************************************************************\n * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *\n * *\n * Author: The ALICE Off-line Project. *\n * Contributors are mentioned in the code where appropriate. *\n * *\n * Permission to use, copy, modify and distribute this software and its *\n * documentation strictly for non-commercial purposes is hereby granted *\n * without fee, provided that the above copyright notice appears in all *\n * copies and that both the copyright notice and this permission notice *\n * appear in the supporting documentation. The authors make no claims *\n * about the suitability of this software for any purpose. It is *\n * provided \"as is\" without express or implied warranty. *\n **************************************************************************\/\n\n\/* $Id$ *\/\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ \/\/\n\/\/ START raw data conversion class \/\/\n\/\/ \/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include <Riostream.h>\n#include <TTree.h>\n\n#include \"AliSTART.h\"\n#include \"AliSTARTRawData.h\"\n#include \"AliSTARTdigit.h\"\n#include \"AliBitPacking.h\"\n#include \"AliRawDataHeader.h\"\n#include \"AliBitPacking.h\"\n\nClassImp(AliSTARTRawData)\n\n\/\/_____________________________________________________________________________\nAliSTARTRawData::AliSTARTRawData():TObject()\n{\n \/*\n- 48 channels (2 words each as in TOF DDL) for :\nword 1 :0-5bit number of PMT; word 2: 0-7 error sign, 8-31 TDC\nand the same but for amplified signal. Now I wrote the same time because\nCDF are not ready and differences didn't measured yet.\n\n- 48 channel for amplitude: very preliminary, QTC features are not\nknown now, preliminary i put as T1 time signal for this PMT in first\nchannel and T1+A in second, where A=Log(Amplitude);\nand the same for amplified but A=Log(10*Amplitude).\n\n- T0-A and T0-C 2 channels\n- T0A-T0C vertex information\n- Time Meaner where T0C TOF increase to the T0A TOF distance\n- 6 multiplicity signals the same way as amplitude and with the same\nuncertances\n *\/\n\n fIndex=-1;\n fDigits = NULL;\n\n fTimeCFD = new TArrayI(24);\n fADC = new TArrayI(24);\n fTimeLED = new TArrayI(24);\n fADC0 = new TArrayI(24);\n \/\/ this->Dump();\n \n}\n\n\/\/_____________________________________________________________________________\nAliSTARTRawData::AliSTARTRawData(const AliSTARTRawData &r):TObject()\n{\n \/\/\n \/\/ AliSTARTrawData copy constructor\n \/\/\n\n ((AliSTARTRawData &) r).Copy(*this);\n\n}\n\n\/\/_____________________________________________________________________________\nAliSTARTRawData::~AliSTARTRawData()\n{\n \/\/\n \/\/ Destructor\n \/\/\n if (fDigits) {\n delete fDigits;\n fDigits = NULL;\n }\n delete fTimeCFD;\n delete fADC;\n delete fTimeLED;\n delete fADC0;\n}\n\n\/\/_____________________________________________________________________________\nAliSTARTRawData &AliSTARTRawData::operator=(const AliSTARTRawData &r)\n{\n \/\/\n \/\/ Assignment operator\n \/\/\n\n if (this != &r) ((AliSTARTRawData &) r).Copy(*this);\n return *this;\n\n}\n\n\/\/_____________________________________________________________________________\nvoid AliSTARTRawData::GetDigits(AliSTARTdigit *fDigits, UInt_t *buf)\n{\n \n \/\/This method packs the START digits in a proper 32 bits structure\n\n \/\/read START digits and fill TDC and ADC arrays\n\n\n UInt_t word;\n UInt_t baseWord=0;\n Int_t error=0;\n\n \/\/ Get the digits array\n\n fDigits->GetTime(*fTimeCFD);\n fDigits->GetADC(*fADC);\n fDigits->GetTimeAmp(*fTimeLED);\n fDigits->GetADCAmp(*fADC0);\n \n \/\/ Loop through all PMT\n \n for (Int_t det = 0; det < 24; det++) {\n Int_t timeLED=fTimeLED->At(det);\n \/\/ if( timeLED > 0){\n \/\/ DDL 1 0-5 -#PMT, 6-31 - empty\n \/\/LED\n word=det;;\n PackWord(baseWord,word, 0, 8); \n fIndex++;\n buf[fIndex]=baseWord;\n \n word=0;\n baseWord=0;\n word=error;\n PackWord(baseWord,word,0, 7); \/\/ Error flag\n word=timeLED;\n PackWord(baseWord,word,8,31); \/\/ time-of-flight\n fIndex++;\n buf[fIndex]=baseWord;\n word=0;\n baseWord=0;\n \/\/ }\n }\n for (Int_t det = 0; det < 24; det++) {\n \/\/CDF\n Int_t timeCFD=fTimeCFD->At(det);\n \/\/ if ( timeCFD >0 ) {\n \/\/ DDL2 2 0-5 -#PMT, 6-31 - empty\n word=0;\n baseWord=0;\n word=det+24;\n PackWord(baseWord,word, 0, 8); \/\/ number of PMT on the right side\n fIndex++;\n buf[fIndex]=baseWord;\n word=0;\n baseWord=0;\n word=error;\n PackWord(baseWord,word,0, 7); \/\/ Error flag\n word=timeCFD;\n PackWord(baseWord,word,8,31); \/\/ time-of-flight\n fIndex++;\n buf[fIndex]=baseWord;\n word=0;\n baseWord=0;\n \/\/ }\n }\n for (Int_t det = 0; det < 24; det++) {\n \/\/conver ADC to time (preliminary algorithm)\n Int_t qtc=fADC->At(det);\n \/\/ if ( qtc > 0 )\n \/\/ {\n\tword=det+48;\n\tPackWord(baseWord,word, 0, 8); \/\/ number of PMT on the right side\n\tfIndex++;\n\tbuf[fIndex]=baseWord;\n\tbaseWord=0;\n\tword=error;\n\tPackWord(baseWord,word,0, 7); \/\/ Error flag\n\tword=qtc;\n\tPackWord(baseWord,word,8,31); \/\/ Q->Time\n\tfIndex++;\n\tbuf[fIndex]=baseWord;\n \tword=0;\n\tbaseWord=0;\n\t\/\/ }\n }\n \n for (Int_t det = 0; det < 24; det++) {\n Int_t qtcAmp=fADC0->At(det);\n \n \/\/ DDL 4 amplified QTC charge * 10\n \n \/\/Amplified ADC -> TDC \n \n word=det+72;\n PackWord(baseWord,word, 0, 8); \/\/ number of PMT on the right side\n fIndex++;\n buf[fIndex]=baseWord;\n baseWord=0;\n word=error;\n PackWord(baseWord,word,0, 7); \/\/ Error flag\n word=qtcAmp;\n PackWord(baseWord,word,8,31); \/\/ Q->T amplified\n fIndex++;\n buf[fIndex]=baseWord;\n \n word=0;\n baseWord=0;\n }\n\n\n word=0;\n baseWord=0;\n fIndex++;\n word=97;\n PackWord(baseWord,word, 0, 8); \/\/ ?????????????????\n buf[fIndex]=baseWord;\n baseWord=0;\n word=error;\n PackWord(baseWord,word,0, 7); \/\/ Error flag\n word=fDigits->MeanTime();\n PackWord(baseWord,word,8,31); \/\/ MEANER\n \n fIndex++;\n buf[fIndex]=baseWord;\n\n\n\n \/\/ besttime right & left\n word=98;\n PackWord(baseWord,word, 0, 8); \/\/ T0-A sign\n fIndex++;\n buf[fIndex]=baseWord;\n\n baseWord=0;\n word=error;\n PackWord(baseWord,word,0, 7); \/\/ Error flag\n word=fDigits->BestTimeRight();\n PackWord(baseWord,word,8,31); \/\/ time-of-flight T0-A\n fIndex++;\n buf[fIndex]=baseWord;\n\n word=99;\n PackWord(baseWord,word, 0, 8); \/\/ T0-C sign\n fIndex++;\n buf[fIndex]=baseWord;\n\n baseWord=0;\n word=error;\n PackWord(baseWord,word,0, 7); \/\/ Error flag\n word=fDigits->BestTimeLeft();\n PackWord(baseWord,word,8,31); \/\/ time-of-flight T0-C \n fIndex++;\n buf[fIndex]=baseWord;\n \n \/\/ time difference\n word=100;\n PackWord(baseWord,word, 0, 8); \/\/ TVDS sign\n fIndex++;\n buf[fIndex]=baseWord;\n\n baseWord=0;\n\n word=error;\n PackWord(baseWord,word,0, 7); \/\/ Error flag\n word=fDigits->TimeDiff();\n PackWord(baseWord,word,8,31); \/\/ T0verex\n fIndex++;\n buf[fIndex]=baseWord;\n\n\n \/\/ multiplicity \n \n Int_t mult=fDigits->SumMult();\n word=101;\n PackWord(baseWord,word, 0, 8); \n fIndex++;\n buf[fIndex]=baseWord;\n \n baseWord=0;\n word=error;\n PackWord(baseWord,word,0, 7); \/\/ Error flag\n word=mult;\n PackWord(baseWord,word,8,31); \/\/ time amplitude\n fIndex++;\n buf[fIndex]=baseWord;\n \n\n\n \/\/ trigger channels\n \/\/ besttime right & left\n word=102;\n PackWord(baseWord,word, 0, 8); \/\/ T0-A sign\n fIndex++;\n buf[fIndex]=baseWord;\n\n baseWord=0;\n word=error;\n PackWord(baseWord,word,0, 7); \/\/ Error flag\n word=fDigits->BestTimeRight();\n PackWord(baseWord,word,8,31); \/\/ time-of-flight T0-A\n fIndex++;\n buf[fIndex]=baseWord;\n \n word=103;\n PackWord(baseWord,word, 0, 8); \/\/ T0-C sign\n fIndex++;\n buf[fIndex]=baseWord;\n\n baseWord=0;\n\n word=error;\n PackWord(baseWord,word,0, 7); \/\/ Error flag\n word=fDigits->BestTimeLeft();\n PackWord(baseWord,word,8,31); \/\/ time-of-flight T0-C \n fIndex++;\n buf[fIndex]=baseWord;\n\n \/\/ time difference\n word=104;\n PackWord(baseWord,word, 0, 8); \/\/ TVDS sign\n fIndex++;\n buf[fIndex]=baseWord;\n\n baseWord=0;\n\n word=error;\n PackWord(baseWord,word,0, 7); \/\/ Error flag\n word=fDigits->TimeDiff();\n PackWord(baseWord,word,8,31); \/\/ T0verex\n fIndex++;\n buf[fIndex]=baseWord;\n\n \/\/ multiplicity \n \n mult=fDigits->SumMult();\n word=105;\n PackWord(baseWord,word, 0, 8); \n fIndex++;\n buf[fIndex]=baseWord;\n \n baseWord=0;\n word=error;\n PackWord(baseWord,word,0, 7); \/\/ Error flag\n word=mult;\n PackWord(baseWord,word,8,31); \/\/ time amplitude\n fIndex++;\n buf[fIndex]=baseWord;\n \n \/\/ multiplicity \n \n mult=fDigits->SumMult();\n word=106;\n PackWord(baseWord,word, 0, 8); \n fIndex++;\n buf[fIndex]=baseWord;\n \n baseWord=0;\n word=error;\n PackWord(baseWord,word,0, 7); \/\/ Error flag\n word=mult;\n PackWord(baseWord,word,8,31); \/\/ time amplitude\n fIndex++;\n buf[fIndex]=baseWord;\n cout<<endl;\n}\n\n\/\/-----------------------------------------------------------------------------------\n\nvoid AliSTARTRawData::PackWord(UInt_t &BaseWord, UInt_t Word, Int_t StartBit, Int_t StopBit)\n{\n \/\/This method packs a word into the Baseword buffer starting form the \"StartBit\"\n \/\/and tacking StopBit-StartBit+1 bits\n UInt_t dummyWord,offSet;\n Int_t length;\n UInt_t sum;\n \/\/The BaseWord is being filled with 1 from StartBit to StopBit\n length=StopBit-StartBit+1;\n sum=(UInt_t)TMath::Power(2,length)-1;\n\n if(Word > sum){\n Error(\"PackWord\", \"Word to be filled is not within desired length\\n\"\n \"Word:%d Start bit:%d Stop Bit:%d\",Word,StartBit,StopBit);\n return;\n }\n offSet=sum;\n offSet<<=StartBit;\n BaseWord=BaseWord|offSet;\n\n \/\/The Word to be filled is shifted to the position StartBit\n \/\/and the remaining Left and Right bits are filled with 1\n sum=(UInt_t)TMath::Power(2,StartBit)-1;\n dummyWord=0xFFFFFFFF<<length;\n dummyWord +=Word;\n dummyWord<<=StartBit;\n dummyWord+=sum;\n BaseWord=BaseWord&dummyWord;\n return;\n}\n\n\/\/---------------------------------------------------------------------------------------\n\nInt_t AliSTARTRawData::RawDataSTART(AliSTARTdigit *fDigits)\n{\n \/\/This method creates the Raw data files for START detector\n\n\n const Int_t kSize=512; \/\/2*AliTOFGeometry::NpadXSector() \n \/\/max number of digits per DDL file times 2\n UInt_t buf[kSize];\n UInt_t baseWord;\n UInt_t word;\n\n fIndex=-1;\n\n char fileName[15];\n ofstream outfile; \/\/ logical name of the output file \n AliRawDataHeader header;\n \/\/loop over TOF DDL files\n sprintf(fileName,\"START_%d.ddl\", 0xd00);\n \/\/ sprintf(fileName,\"START_0xd00.ddl\"); \/\/The name of the output file\n#ifndef __DECCXX\n outfile.open(fileName,ios::binary);\n#else\n outfile.open(fileName);\n#endif\n \/\/write Dummy DATA HEADER\n UInt_t dataHeaderPosition=outfile.tellp();\n outfile.write((char*)(&header),sizeof(header));\n\n baseWord=0;\n word=0;\n PackWord(baseWord,word,0, 31); \/\/ Number of DDL file\n\n fIndex++;\n buf[fIndex]=baseWord;\n GetDigits(fDigits,buf);\n\n outfile.write((char *)buf,((fIndex+1)*sizeof(UInt_t)));\n for(Int_t ii=0;ii<(fIndex+1);ii++) buf[ii]=0;\n fIndex=-1;\n \n \/\/Write REAL DATA HEADER\n UInt_t currentFilePosition=outfile.tellp();\n outfile.seekp(dataHeaderPosition);\n header.fSize=currentFilePosition-dataHeaderPosition;\n header.SetAttribute(0); \/\/ valid data\n outfile.write((char*)(&header),sizeof(header));\n outfile.close();\n\n \/\/end for\n \n return 0; \n \n}\n<|endoftext|>"} {"text":"<commit_before><commit_msg>Change a DCHECK to a DCHECK_LT so we can see the failing values.<commit_after><|endoftext|>"} {"text":"<commit_before>\/\/ @(#)root\/test:$name: $:$id: filter.cxx,v 1.0 exp $\n\/\/ Author: O.Couet\n\n\/\/\n\/\/ filters doc files.\n\/\/\n\n\n#include <stdlib.h>\n#include <Riostream.h>\n#include <time.h>\n#include <TString.h>\n#include <TROOT.h>\n#include <TError.h>\n#include <TRandom.h>\n#include <TBenchmark.h>\n#include <TSystem.h>\n#include <TApplication.h>\n#include <TDatime.h>\n#include <TFile.h>\n#include <TF1.h>\n#include \"TF2.h\"\n#include <TF3.h>\n#include <TH2.h>\n#include <TNtuple.h>\n#include <TProfile.h>\n#include \"TString.h\"\n\n#include <TStyle.h>\n#include <TCanvas.h>\n#include <TColor.h>\n#include <TFrame.h>\n#include <TPostScript.h>\n#include <TPDF.h>\n#include <TLine.h>\n#include <TMarker.h>\n#include <TPolyLine.h>\n#include <TLatex.h>\n#include <TMathText.h>\n#include <TLegend.h>\n#include <TEllipse.h>\n#include <TCurlyArc.h>\n#include <TArc.h>\n#include <TPaveText.h>\n#include <TPaveStats.h>\n#include <TPaveLabel.h>\n#include <TGaxis.h>\n#include <TGraph.h>\n#include <TGraphErrors.h>\n#include <TGraphAsymmErrors.h>\n#include <TGraphBentErrors.h>\n#include <TMultiGraph.h>\n#include <TGraph2D.h>\n#include <TParallelCoord.h>\n#include <TImage.h>\n#include <TMath.h>\n#include <TSystem.h>\n\n\n\/\/ Auxiliary functions\nvoid GetClassName();\nvoid StandardizeKeywords();\nvoid ExecuteMacro();\nvoid ExecuteCommand(TString);\n\n\n\/\/ Global variables.\nchar gLine[255];\nTString gFileName;\nTString gLineString;\nTString gClassName;\nTString gImageName;\nBool_t gHeader;\nBool_t gSource;\nBool_t gInClassDef;\nBool_t gClass;\nInt_t gInMacro;\nInt_t gImageID;\n\n\n\/\/______________________________________________________________________________\nint main(int argc, char *argv[])\n{\n \/\/ Filter ROOT files for Doxygen.\n\n \/\/ Initialisation\n\n gFileName = argv[1];\n gHeader = kFALSE;\n gSource = kFALSE;\n gInClassDef = kFALSE;\n gClass = kFALSE;\n gInMacro = 0;\n gImageID = 0;\n if (gFileName.EndsWith(\".cxx\")) gSource = kTRUE;\n if (gFileName.EndsWith(\".h\")) gHeader = kTRUE;\n GetClassName();\n\n \/\/ Loop on file.\n FILE *f = fopen(gFileName.Data(),\"r\");\n\n \/\/ File header.\n if (gHeader) {\n while (fgets(gLine,255,f)) {\n gLineString = gLine;\n\n if (gLineString.BeginsWith(\"class\")) gInClassDef = kTRUE;\n if (gLineString.Index(\"ClassDef\") >= 0) gInClassDef = kFALSE;\n\n if (gInClassDef && gLineString.Index(\"\/\/\") >= 0) {\n gLineString.ReplaceAll(\"\/\/\",\"\/\/\/<\");\n }\n\n printf(\"%s\",gLineString.Data());\n }\n }\n\n \/\/ Source file.\n if (gSource) {\n while (fgets(gLine,255,f)) {\n gLineString = gLine;\n StandardizeKeywords();\n\n if (gLineString.Index(\"begin_html\") >= 0) {\n if (!gClass) {\n gLineString = TString::Format(\"\/*! \\\\class %s\\n\",gClassName.Data());\n gClass = kTRUE;\n } else {\n gLineString.ReplaceAll(\"begin_html\",\"\");\n }\n }\n\n if (gLineString.Index(\"end_html\") >= 0) {\n gLineString.ReplaceAll(\"end_html\",\"\");\n }\n\n if (gInMacro) {\n if (gInMacro == 1) {\n if (gLineString.EndsWith(\".C\\n\")) ExecuteMacro();\n }\n gInMacro++;\n }\n\n if (gLineString.Index(\"Begin_Macro\") >= 0) {\n gLineString = \"<pre lang=\\\"cpp\\\">\\n\";\n gInMacro++;\n }\n\n if (gLineString.Index(\"End_Macro\") >= 0) {\n gLineString.ReplaceAll(\"End_Macro\",\"<\/pre>\\n\");\n gInMacro = 0;\n }\n\n printf(\"%s\",gLineString.Data());\n }\n }\n\n return 1;\n}\n\n\n\/\/______________________________________________________________________________\nvoid GetClassName()\n{\n \/\/ Retrieve the class name.\n\n Int_t i1 = 0;\n Int_t i2 = 0;\n\n FILE *f = fopen(gFileName.Data(),\"r\");\n\n \/\/ File header.\n if (gHeader) {\n while (fgets(gLine,255,f)) {\n gLineString = gLine;\n if (gLineString.Index(\"ClassDef\") >= 0) {\n i1 = gLineString.Index(\"(\")+1;\n i2 = gLineString.Index(\",\")-1;\n gClassName = gLineString(i1,i2-i1+1);\n fclose(f);\n return;\n }\n }\n }\n\n \/\/ Source file.\n if (gSource) {\n while (fgets(gLine,255,f)) {\n gLineString = gLine;\n if (gLineString.Index(\"ClassImp\") >= 0) {\n i1 = gLineString.Index(\"(\")+1;\n i2 = gLineString.Index(\")\")-1;\n gClassName = gLineString(i1,i2-i1+1);\n fclose(f);\n return;\n }\n }\n }\n\n fclose(f);\n return;\n}\n\n\n\/\/______________________________________________________________________________\nvoid StandardizeKeywords()\n{\n \/\/ Standardize the THTML keywords to ease the parsing.\n\n gLineString.ReplaceAll(\"End_Html\",\"end_html\");\n gLineString.ReplaceAll(\"End_html\",\"end_html\");\n gLineString.ReplaceAll(\"end_html \",\"end_html\");\n gLineString.ReplaceAll(\"Begin_Html\",\"begin_html\");\n gLineString.ReplaceAll(\"Begin_html\",\"begin_html\");\n gLineString.ReplaceAll(\"<big>\",\"\");\n gLineString.ReplaceAll(\"<\/big>\",\"\");\n}\n\n\n\/\/______________________________________________________________________________\nvoid ExecuteMacro()\n{\n \/\/ Execute the macro in gLineString and produce the corresponding picture\n\n \/\/ Name of the next Image to be generated\n gImageName = TString::Format(\"%s_%3.3d.png\", gClassName.Data()\n , gImageID++);\n\n \/\/ Build the ROOT command to be executed.\n gLineString.ReplaceAll(\"..\/..\/..\",\"root -l -b -q \\\"makeimage.C(\\\\\\\"..\/..\");\n Int_t l = gLineString.Length();\n gLineString.Replace(l-2,1,TString::Format(\"C\\\\\\\",\\\\\\\"%s\/html\/%s\\\\\\\")\\\"\", gSystem->Getenv(\"OUTPUT_DIRECTORY\")\n , gImageName.Data()));\n\n ExecuteCommand(gLineString);\n\n gLineString = TString::Format(\"\\\\image html %s\\n\",gImageName.Data());\n}\n\n\n\/\/______________________________________________________________________________\nvoid ExecuteCommand(TString command)\n{\n \/\/ Execute a command making sure stdout will not go in the doxygen file.\n\n int o = dup(fileno(stdout));\n freopen(\"stdout.dat\",\"a\",stdout);\n gSystem->Exec(command.Data());\n dup2(o,fileno(stdout));\n close(o);\n}<commit_msg>Generate pictures for macros in ..\/doc\/macros<commit_after>\/\/ @(#)root\/test:$name: $:$id: filter.cxx,v 1.0 exp $\n\/\/ Author: O.Couet\n\n\/\/\n\/\/ filters doc files.\n\/\/\n\n\n#include <stdlib.h>\n#include <Riostream.h>\n#include <time.h>\n#include <TString.h>\n#include <TROOT.h>\n#include <TError.h>\n#include <TRandom.h>\n#include <TBenchmark.h>\n#include <TSystem.h>\n#include <TApplication.h>\n#include <TDatime.h>\n#include <TFile.h>\n#include <TF1.h>\n#include \"TF2.h\"\n#include <TF3.h>\n#include <TH2.h>\n#include <TNtuple.h>\n#include <TProfile.h>\n#include \"TString.h\"\n\n#include <TStyle.h>\n#include <TCanvas.h>\n#include <TColor.h>\n#include <TFrame.h>\n#include <TPostScript.h>\n#include <TPDF.h>\n#include <TLine.h>\n#include <TMarker.h>\n#include <TPolyLine.h>\n#include <TLatex.h>\n#include <TMathText.h>\n#include <TLegend.h>\n#include <TEllipse.h>\n#include <TCurlyArc.h>\n#include <TArc.h>\n#include <TPaveText.h>\n#include <TPaveStats.h>\n#include <TPaveLabel.h>\n#include <TGaxis.h>\n#include <TGraph.h>\n#include <TGraphErrors.h>\n#include <TGraphAsymmErrors.h>\n#include <TGraphBentErrors.h>\n#include <TMultiGraph.h>\n#include <TGraph2D.h>\n#include <TParallelCoord.h>\n#include <TImage.h>\n#include <TMath.h>\n#include <TSystem.h>\n\n\n\/\/ Auxiliary functions\nvoid GetClassName();\nvoid StandardizeKeywords();\nvoid ExecuteMacro();\nvoid ExecuteCommand(TString);\n\n\n\/\/ Global variables.\nchar gLine[255];\nTString gFileName;\nTString gLineString;\nTString gClassName;\nTString gImageName;\nTString gCwd;\nBool_t gHeader;\nBool_t gSource;\nBool_t gInClassDef;\nBool_t gClass;\nInt_t gInMacro;\nInt_t gImageID;\n\n\n\/\/______________________________________________________________________________\nint main(int argc, char *argv[])\n{\n \/\/ Filter ROOT files for Doxygen.\n\n \/\/ Initialisation\n\n gFileName = argv[1];\n gHeader = kFALSE;\n gSource = kFALSE;\n gInClassDef = kFALSE;\n gClass = kFALSE;\n gInMacro = 0;\n gImageID = 0;\n if (gFileName.EndsWith(\".cxx\")) gSource = kTRUE;\n if (gFileName.EndsWith(\".h\")) gHeader = kTRUE;\n GetClassName();\n gCwd = gFileName(0, gFileName.Last('\/'));\n\n \/\/ Loop on file.\n FILE *f = fopen(gFileName.Data(),\"r\");\n\n \/\/ File header.\n if (gHeader) {\n while (fgets(gLine,255,f)) {\n gLineString = gLine;\n\n if (gLineString.BeginsWith(\"class\")) gInClassDef = kTRUE;\n if (gLineString.Index(\"ClassDef\") >= 0) gInClassDef = kFALSE;\n\n if (gInClassDef && gLineString.Index(\"\/\/\") >= 0) {\n gLineString.ReplaceAll(\"\/\/\",\"\/\/\/<\");\n }\n\n printf(\"%s\",gLineString.Data());\n }\n }\n\n \/\/ Source file.\n if (gSource) {\n while (fgets(gLine,255,f)) {\n gLineString = gLine;\n StandardizeKeywords();\n\n if (gLineString.Index(\"begin_html\") >= 0) {\n if (!gClass) {\n gLineString = TString::Format(\"\/*! \\\\class %s\\n\",gClassName.Data());\n gClass = kTRUE;\n } else {\n gLineString.ReplaceAll(\"begin_html\",\"\");\n }\n }\n\n if (gLineString.Index(\"end_html\") >= 0) {\n gLineString.ReplaceAll(\"end_html\",\"\");\n }\n\n if (gInMacro) {\n if (gInMacro == 1) {\n if (gLineString.EndsWith(\".C\\n\")) {\n ExecuteMacro();\n gInMacro++;\n } else {\n }\n } else {\n }\n }\n\n if (gLineString.Index(\"Begin_Macro\") >= 0) {\n gLineString = \"<pre lang=\\\"cpp\\\">\\n\";\n gInMacro++;\n }\n\n if (gLineString.Index(\"End_Macro\") >= 0) {\n gLineString.ReplaceAll(\"End_Macro\",\"<\/pre>\\n\");\n gInMacro = 0;\n }\n\n printf(\"%s\",gLineString.Data());\n }\n }\n\n return 1;\n}\n\n\n\/\/______________________________________________________________________________\nvoid GetClassName()\n{\n \/\/ Retrieve the class name.\n\n Int_t i1 = 0;\n Int_t i2 = 0;\n\n FILE *f = fopen(gFileName.Data(),\"r\");\n\n \/\/ File header.\n if (gHeader) {\n while (fgets(gLine,255,f)) {\n gLineString = gLine;\n if (gLineString.Index(\"ClassDef\") >= 0) {\n i1 = gLineString.Index(\"(\")+1;\n i2 = gLineString.Index(\",\")-1;\n gClassName = gLineString(i1,i2-i1+1);\n fclose(f);\n return;\n }\n }\n }\n\n \/\/ Source file.\n if (gSource) {\n while (fgets(gLine,255,f)) {\n gLineString = gLine;\n if (gLineString.Index(\"ClassImp\") >= 0) {\n i1 = gLineString.Index(\"(\")+1;\n i2 = gLineString.Index(\")\")-1;\n gClassName = gLineString(i1,i2-i1+1);\n fclose(f);\n return;\n }\n }\n }\n\n fclose(f);\n\n return;\n}\n\n\n\/\/______________________________________________________________________________\nvoid StandardizeKeywords()\n{\n \/\/ Standardize the THTML keywords to ease the parsing.\n\n gLineString.ReplaceAll(\"End_Html\",\"end_html\");\n gLineString.ReplaceAll(\"End_html\",\"end_html\");\n gLineString.ReplaceAll(\"end_html \",\"end_html\");\n gLineString.ReplaceAll(\"Begin_Html\",\"begin_html\");\n gLineString.ReplaceAll(\"Begin_html\",\"begin_html\");\n gLineString.ReplaceAll(\"<big>\",\"\");\n gLineString.ReplaceAll(\"<\/big>\",\"\");\n}\n\n\n\/\/______________________________________________________________________________\nvoid ExecuteMacro()\n{\n \/\/ Execute the macro in gLineString and produce the corresponding picture\n\n \/\/ Name of the next Image to be generated\n gImageName = TString::Format(\"%s_%3.3d.png\", gClassName.Data()\n , gImageID++);\n\n \/\/ Build the ROOT command to be executed.\n if (gLineString.Index(\"..\/..\/..\") >= 0) {\n gLineString.ReplaceAll(\"..\/..\/..\",\"root -l -b -q \\\"makeimage.C(\\\\\\\"..\/..\");\n } else {\n gLineString.Prepend(TString::Format(\"root -l -b -q \\\"makeimage.C(\\\\\\\"%s\/..\/doc\/macros\/\",gCwd.Data()));\n }\n Int_t l = gLineString.Length();\n TString OutDir = gSystem->Getenv(\"OUTPUT_DIRECTORY\");\n OutDir.ReplaceAll(\"\\\"\",\"\");\n gLineString.Replace(l-2,1,TString::Format(\"C\\\\\\\",\\\\\\\"%s\/html\/%s\\\\\\\")\\\"\",\n OutDir.Data(),\n gImageName.Data()));\n\n ExecuteCommand(gLineString);\n\n gLineString = TString::Format(\"\\\\image html %s\\n\",gImageName.Data());\n}\n\n\n\/\/______________________________________________________________________________\nvoid ExecuteCommand(TString command)\n{\n \/\/ Execute a command making sure stdout will not go in the doxygen file.\n\n int o = dup(fileno(stdout));\n freopen(\"stdout.dat\",\"a\",stdout);\n gSystem->Exec(command.Data());\n dup2(o,fileno(stdout));\n close(o);\n}<|endoftext|>"} {"text":"<commit_before>#include \"drape_frontend\/visual_params.hpp\"\n\n#include \"base\/macros.hpp\"\n#include \"base\/math.hpp\"\n#include \"base\/assert.hpp\"\n\n#include \"indexer\/mercator.hpp\"\n\n#include \"std\/limits.hpp\"\n#include \"std\/algorithm.hpp\"\n\nnamespace df\n{\n\nuint32_t const YotaDevice = 0x1;\n\nnamespace\n{\n\nstatic VisualParams g_VizParams;\n\ntypedef pair<string, double> visual_scale_t;\n\nstruct VisualScaleFinder\n{\n VisualScaleFinder(double vs)\n : m_vs(vs)\n {\n }\n\n bool operator()(visual_scale_t const & node)\n {\n return my::AlmostEqualULPs(node.second, m_vs);\n }\n\n double m_vs;\n};\n\n} \/\/ namespace\n\n#ifdef DEBUG\nstatic bool g_isInited = false;\n#define RISE_INITED g_isInited = true\n#define ASSERT_INITED ASSERT(g_isInited, ())\n#else\n#define RISE_INITED\n#define ASSERT_INITED\n#endif\n\n\nvoid VisualParams::Init(double vs, uint32_t tileSize, vector<uint32_t> const & additionalOptions)\n{\n g_VizParams.m_tileSize = tileSize;\n g_VizParams.m_visualScale = vs;\n if (find(additionalOptions.begin(), additionalOptions.end(), YotaDevice) != additionalOptions.end())\n g_VizParams.m_isYotaDevice = true;\n RISE_INITED;\n}\n\nVisualParams & VisualParams::Instance()\n{\n ASSERT_INITED;\n return g_VizParams;\n}\n\nstring const & VisualParams::GetResourcePostfix(double visualScale, bool isYotaDevice)\n{\n static visual_scale_t postfixes[] =\n {\n make_pair(\"ldpi\", 0.75),\n make_pair(\"mdpi\", 1.0),\n make_pair(\"hdpi\", 1.5),\n make_pair(\"xhdpi\", 2.0),\n make_pair(\"xxhdpi\", 3.0),\n make_pair(\"6plus\", 2.4),\n };\n\n static string specifixPostfixes[] =\n {\n \"yota\"\n };\n\n if (isYotaDevice)\n return specifixPostfixes[0];\n\n visual_scale_t * finded = find_if(postfixes, postfixes + ARRAY_SIZE(postfixes), VisualScaleFinder(visualScale));\n ASSERT(finded < postfixes + ARRAY_SIZE(postfixes), ());\n return finded->first;\n}\n\nstring const & VisualParams::GetResourcePostfix() const\n{\n return VisualParams::GetResourcePostfix(m_visualScale, m_isYotaDevice);\n}\n\ndouble VisualParams::GetVisualScale() const\n{\n return m_visualScale;\n}\n\nuint32_t VisualParams::GetTileSize() const\n{\n return m_tileSize;\n}\n\nuint32_t VisualParams::GetTouchRectRadius() const\n{\n return 20 * GetVisualScale();\n}\n\ndouble VisualParams::GetDragThreshold() const\n{\n return 10.0 * GetVisualScale();\n}\n\nVisualParams::VisualParams()\n : m_tileSize(0)\n , m_visualScale(0.0)\n{\n}\n\nm2::RectD const & GetWorldRect()\n{\n static m2::RectD const worldRect = MercatorBounds::FullRect();\n return worldRect;\n}\n\nint GetTileScaleBase(ScreenBase const & s, uint32_t tileSize)\n{\n ScreenBase tmpS = s;\n tmpS.Rotate(-tmpS.GetAngle());\n\n \/\/ slightly smaller than original to produce \"antialiasing\" effect using bilinear filtration.\n int const halfSize = static_cast<int>(tileSize \/ 1.05 \/ 2.0);\n\n m2::RectD glbRect;\n m2::PointD const pxCenter = tmpS.PixelRect().Center();\n tmpS.PtoG(m2::RectD(pxCenter - m2::PointD(halfSize, halfSize),\n pxCenter + m2::PointD(halfSize, halfSize)),\n glbRect);\n\n return GetTileScaleBase(glbRect);\n}\n\nint GetTileScaleBase(ScreenBase const & s)\n{\n return GetTileScaleBase(s, VisualParams::Instance().GetTileSize());\n}\n\nint GetTileScaleBase(m2::RectD const & r)\n{\n double const sz = max(r.SizeX(), r.SizeY());\n return max(1, my::rounds(log((MercatorBounds::maxX - MercatorBounds::minX) \/ sz) \/ log(2.0)));\n}\n\nint GetTileScaleIncrement(uint32_t tileSize, double visualScale)\n{\n return log(tileSize \/ 256.0 \/ visualScale) \/ log(2.0);\n}\n\nint GetTileScaleIncrement()\n{\n VisualParams const & p = VisualParams::Instance();\n return GetTileScaleIncrement(p.GetTileSize(), p.GetVisualScale());\n}\n\nm2::RectD GetRectForDrawScale(int drawScale, m2::PointD const & center, uint32_t tileSize, double visualScale)\n{\n \/\/ +1 - we will calculate half length for each side\n double const factor = 1 << (max(1, drawScale - GetTileScaleIncrement(tileSize, visualScale)) + 1);\n\n double const len = (MercatorBounds::maxX - MercatorBounds::minX) \/ factor;\n\n return m2::RectD(MercatorBounds::ClampX(center.x - len),\n MercatorBounds::ClampY(center.y - len),\n MercatorBounds::ClampX(center.x + len),\n MercatorBounds::ClampY(center.y + len));\n}\n\nm2::RectD GetRectForDrawScale(int drawScale, m2::PointD const & center)\n{\n VisualParams const & p = VisualParams::Instance();\n return GetRectForDrawScale(drawScale, center, p.GetTileSize(), p.GetVisualScale());\n}\n\nm2::RectD GetRectForDrawScale(double drawScale, m2::PointD const & center, uint32_t tileSize, double visualScale)\n{\n return GetRectForDrawScale(my::rounds(drawScale), center, tileSize, visualScale);\n}\n\nm2::RectD GetRectForDrawScale(double drawScale, m2::PointD const & center)\n{\n return GetRectForDrawScale(my::rounds(drawScale), center);\n}\n\nint CalculateTileSize(int screenWidth, int screenHeight)\n{\n int const maxSz = max(screenWidth, screenHeight);\n\n \/\/ we're calculating the tileSize based on (maxSz > 1024 ? rounded : ceiled)\n \/\/ to the nearest power of two value of the maxSz\n\n int const ceiledSz = 1 << static_cast<int>(ceil(log(double(maxSz + 1)) \/ log(2.0)));\n int res = 0;\n\n if (maxSz < 1024)\n res = ceiledSz;\n else\n {\n int const flooredSz = ceiledSz \/ 2;\n \/\/ rounding to the nearest power of two.\n if (ceiledSz - maxSz < maxSz - flooredSz)\n res = ceiledSz;\n else\n res = flooredSz;\n }\n\n#ifndef OMIM_OS_DESKTOP\n return my::clamp(res \/ 2, 256, 1024);\n#else\n return my::clamp(res \/ 2, 512, 1024);\n#endif\n}\n\nint GetDrawTileScale(int baseScale, uint32_t tileSize, double visualScale)\n{\n return max(1, baseScale + GetTileScaleIncrement(tileSize, visualScale));\n}\n\nint GetDrawTileScale(ScreenBase const & s, uint32_t tileSize, double visualScale)\n{\n return GetDrawTileScale(GetTileScaleBase(s, tileSize), tileSize, visualScale);\n}\n\nint GetDrawTileScale(m2::RectD const & r, uint32_t tileSize, double visualScale)\n{\n return GetDrawTileScale(GetTileScaleBase(r), tileSize, visualScale);\n}\n\nint GetDrawTileScale(int baseScale)\n{\n VisualParams const & p = VisualParams::Instance();\n return GetDrawTileScale(baseScale, p.GetTileSize(), p.GetVisualScale());\n}\n\nint GetDrawTileScale(ScreenBase const & s)\n{\n VisualParams const & p = VisualParams::Instance();\n return GetDrawTileScale(s, p.GetTileSize(), p.GetVisualScale());\n}\n\nint GetDrawTileScale(m2::RectD const & r)\n{\n VisualParams const & p = VisualParams::Instance();\n return GetDrawTileScale(r, p.GetTileSize(), p.GetVisualScale());\n}\n\n} \/\/ namespace df\n<commit_msg>Fixed algorithm to choose resource postfix to more stable<commit_after>#include \"drape_frontend\/visual_params.hpp\"\n\n#include \"base\/macros.hpp\"\n#include \"base\/math.hpp\"\n#include \"base\/assert.hpp\"\n\n#include \"indexer\/mercator.hpp\"\n\n#include \"std\/limits.hpp\"\n#include \"std\/algorithm.hpp\"\n\nnamespace df\n{\n\nuint32_t const YotaDevice = 0x1;\n\nnamespace\n{\n\nstatic VisualParams g_VizParams;\n\ntypedef pair<string, double> visual_scale_t;\n\n} \/\/ namespace\n\n#ifdef DEBUG\nstatic bool g_isInited = false;\n#define RISE_INITED g_isInited = true\n#define ASSERT_INITED ASSERT(g_isInited, ())\n#else\n#define RISE_INITED\n#define ASSERT_INITED\n#endif\n\n\nvoid VisualParams::Init(double vs, uint32_t tileSize, vector<uint32_t> const & additionalOptions)\n{\n g_VizParams.m_tileSize = tileSize;\n g_VizParams.m_visualScale = vs;\n if (find(additionalOptions.begin(), additionalOptions.end(), YotaDevice) != additionalOptions.end())\n g_VizParams.m_isYotaDevice = true;\n RISE_INITED;\n}\n\nVisualParams & VisualParams::Instance()\n{\n ASSERT_INITED;\n return g_VizParams;\n}\n\nstring const & VisualParams::GetResourcePostfix(double visualScale, bool isYotaDevice)\n{\n static visual_scale_t postfixes[] =\n {\n make_pair(\"ldpi\", 0.75),\n make_pair(\"mdpi\", 1.0),\n make_pair(\"hdpi\", 1.5),\n make_pair(\"xhdpi\", 2.0),\n make_pair(\"xxhdpi\", 3.0),\n make_pair(\"6plus\", 2.4),\n };\n\n static string specifixPostfixes[] =\n {\n \"yota\"\n };\n\n if (isYotaDevice)\n return specifixPostfixes[0];\n\n \/\/ Looking for the nearest available scale.\n int postfixIndex = -1;\n double minValue = numeric_limits<float>::max();\n for (int i = 0; i < ARRAY_SIZE(postfixes); i++)\n {\n double val = fabs(postfixes[i].second - visualScale);\n if (val < minValue)\n {\n minValue = val;\n postfixIndex = i;\n }\n }\n\n ASSERT_GREATER_OR_EQUAL(postfixIndex, 0, ());\n return postfixes[postfixIndex].first;\n}\n\nstring const & VisualParams::GetResourcePostfix() const\n{\n return VisualParams::GetResourcePostfix(m_visualScale, m_isYotaDevice);\n}\n\ndouble VisualParams::GetVisualScale() const\n{\n return m_visualScale;\n}\n\nuint32_t VisualParams::GetTileSize() const\n{\n return m_tileSize;\n}\n\nuint32_t VisualParams::GetTouchRectRadius() const\n{\n return 20 * GetVisualScale();\n}\n\ndouble VisualParams::GetDragThreshold() const\n{\n return 10.0 * GetVisualScale();\n}\n\nVisualParams::VisualParams()\n : m_tileSize(0)\n , m_visualScale(0.0)\n{\n}\n\nm2::RectD const & GetWorldRect()\n{\n static m2::RectD const worldRect = MercatorBounds::FullRect();\n return worldRect;\n}\n\nint GetTileScaleBase(ScreenBase const & s, uint32_t tileSize)\n{\n ScreenBase tmpS = s;\n tmpS.Rotate(-tmpS.GetAngle());\n\n \/\/ slightly smaller than original to produce \"antialiasing\" effect using bilinear filtration.\n int const halfSize = static_cast<int>(tileSize \/ 1.05 \/ 2.0);\n\n m2::RectD glbRect;\n m2::PointD const pxCenter = tmpS.PixelRect().Center();\n tmpS.PtoG(m2::RectD(pxCenter - m2::PointD(halfSize, halfSize),\n pxCenter + m2::PointD(halfSize, halfSize)),\n glbRect);\n\n return GetTileScaleBase(glbRect);\n}\n\nint GetTileScaleBase(ScreenBase const & s)\n{\n return GetTileScaleBase(s, VisualParams::Instance().GetTileSize());\n}\n\nint GetTileScaleBase(m2::RectD const & r)\n{\n double const sz = max(r.SizeX(), r.SizeY());\n return max(1, my::rounds(log((MercatorBounds::maxX - MercatorBounds::minX) \/ sz) \/ log(2.0)));\n}\n\nint GetTileScaleIncrement(uint32_t tileSize, double visualScale)\n{\n return log(tileSize \/ 256.0 \/ visualScale) \/ log(2.0);\n}\n\nint GetTileScaleIncrement()\n{\n VisualParams const & p = VisualParams::Instance();\n return GetTileScaleIncrement(p.GetTileSize(), p.GetVisualScale());\n}\n\nm2::RectD GetRectForDrawScale(int drawScale, m2::PointD const & center, uint32_t tileSize, double visualScale)\n{\n \/\/ +1 - we will calculate half length for each side\n double const factor = 1 << (max(1, drawScale - GetTileScaleIncrement(tileSize, visualScale)) + 1);\n\n double const len = (MercatorBounds::maxX - MercatorBounds::minX) \/ factor;\n\n return m2::RectD(MercatorBounds::ClampX(center.x - len),\n MercatorBounds::ClampY(center.y - len),\n MercatorBounds::ClampX(center.x + len),\n MercatorBounds::ClampY(center.y + len));\n}\n\nm2::RectD GetRectForDrawScale(int drawScale, m2::PointD const & center)\n{\n VisualParams const & p = VisualParams::Instance();\n return GetRectForDrawScale(drawScale, center, p.GetTileSize(), p.GetVisualScale());\n}\n\nm2::RectD GetRectForDrawScale(double drawScale, m2::PointD const & center, uint32_t tileSize, double visualScale)\n{\n return GetRectForDrawScale(my::rounds(drawScale), center, tileSize, visualScale);\n}\n\nm2::RectD GetRectForDrawScale(double drawScale, m2::PointD const & center)\n{\n return GetRectForDrawScale(my::rounds(drawScale), center);\n}\n\nint CalculateTileSize(int screenWidth, int screenHeight)\n{\n int const maxSz = max(screenWidth, screenHeight);\n\n \/\/ we're calculating the tileSize based on (maxSz > 1024 ? rounded : ceiled)\n \/\/ to the nearest power of two value of the maxSz\n\n int const ceiledSz = 1 << static_cast<int>(ceil(log(double(maxSz + 1)) \/ log(2.0)));\n int res = 0;\n\n if (maxSz < 1024)\n res = ceiledSz;\n else\n {\n int const flooredSz = ceiledSz \/ 2;\n \/\/ rounding to the nearest power of two.\n if (ceiledSz - maxSz < maxSz - flooredSz)\n res = ceiledSz;\n else\n res = flooredSz;\n }\n\n#ifndef OMIM_OS_DESKTOP\n return my::clamp(res \/ 2, 256, 1024);\n#else\n return my::clamp(res \/ 2, 512, 1024);\n#endif\n}\n\nint GetDrawTileScale(int baseScale, uint32_t tileSize, double visualScale)\n{\n return max(1, baseScale + GetTileScaleIncrement(tileSize, visualScale));\n}\n\nint GetDrawTileScale(ScreenBase const & s, uint32_t tileSize, double visualScale)\n{\n return GetDrawTileScale(GetTileScaleBase(s, tileSize), tileSize, visualScale);\n}\n\nint GetDrawTileScale(m2::RectD const & r, uint32_t tileSize, double visualScale)\n{\n return GetDrawTileScale(GetTileScaleBase(r), tileSize, visualScale);\n}\n\nint GetDrawTileScale(int baseScale)\n{\n VisualParams const & p = VisualParams::Instance();\n return GetDrawTileScale(baseScale, p.GetTileSize(), p.GetVisualScale());\n}\n\nint GetDrawTileScale(ScreenBase const & s)\n{\n VisualParams const & p = VisualParams::Instance();\n return GetDrawTileScale(s, p.GetTileSize(), p.GetVisualScale());\n}\n\nint GetDrawTileScale(m2::RectD const & r)\n{\n VisualParams const & p = VisualParams::Instance();\n return GetDrawTileScale(r, p.GetTileSize(), p.GetVisualScale());\n}\n\n} \/\/ namespace df\n<|endoftext|>"} {"text":"<commit_before>#ifndef DUNE_STUFF_GRID_PROVIDER_GMSH_HH\n#define DUNE_STUFF_GRID_PROVIDER_GMSH_HH\n\n#ifdef HAVE_CMAKE_CONFIG\n #include \"cmake_config.h\"\n#else\n #include \"config.h\"\n#endif \/\/ ifdef HAVE_CMAKE_CONFIG\n\n#if HAVE_DUNE_GRID\n#if HAVE_ALUGRID || HAVE_ALBERTA || HAVE_UG\n#if defined ALUGRID_CONFORM || defined ALUGRID_CUBE || defined ALUGRID_SIMPLEX || defined ALBERTAGRID || defined UGGRID\n\n#include <memory>\n#include <sstream>\n#include <type_traits>\n\n#include <boost\/assign\/list_of.hpp>\n\n#include <dune\/common\/parametertree.hh>\n#include <dune\/common\/shared_ptr.hh>\n#include <dune\/common\/exceptions.hh>\n#include <dune\/common\/fvector.hh>\n\n#include <dune\/grid\/utility\/structuredgridfactory.hh>\n#include <dune\/grid\/sgrid.hh>\n#include <dune\/grid\/io\/file\/gmshreader.hh>\n\n#include <dune\/stuff\/common\/parameter\/tree.hh>\n\n#include \"interface.hh\"\n\nnamespace Dune {\nnamespace Stuff {\n\n\n\/**\n * \\brief Gmsh grid provider\n *\/\n#if defined HAVE_CONFIG_H || defined HAVE_CMAKE_CONFIG\ntemplate< class GridImp = Dune::GridSelector::GridType >\n#else\ntemplate< class GridImp = Dune::SGrid< 2, 2 > >\n#endif\nclass GridProviderGmsh\n : public GridProviderInterface< GridImp >\n{\npublic:\n \/\/! Type of the provided grid.\n typedef GridImp GridType;\n\n typedef GridProviderInterface< GridType > BaseType;\n\n typedef GridProviderGmsh< GridType > ThisType;\n\n \/\/! Dimension of the provided grid.\n static const unsigned int dim = BaseType::dim;\n\n \/\/! Type of the grids coordinates.\n typedef typename BaseType::CoordinateType CoordinateType;\n\n \/\/! Unique identifier: \\c stuff.grid.provider.gmsh\n static const std::string id()\n {\n return BaseType::id() + \".gmsh\";\n }\n\n GridProviderGmsh(const std::string filename)\n {\n dune_static_assert(!(Dune::is_same< GridType, Dune::YaspGrid< dim > >::value), \"GmshReader does not work with YaspGrid!\");\n dune_static_assert(!(Dune::is_same< GridType, Dune::SGrid< 2, 2 > >::value), \"GmshReader does not work with SGrid!\");\n grid_ = std::shared_ptr< GridType >(GmshReader< GridType >::read(filename));\n }\n\n GridProviderGmsh(ThisType& other)\n : grid_(other.grid_)\n {}\n\n GridProviderGmsh(const ThisType& other)\n : grid_(other.grid_)\n {}\n\n static Dune::ParameterTree defaultSettings(const std::string subName = \"\")\n {\n Dune::ParameterTree description;\n description[\"filename\"] = \"path_to_g.msh\";\n if (subName.empty())\n return description;\n else {\n Dune::Stuff::Common::ExtendedParameterTree extendedDescription;\n extendedDescription.add(description, subName);\n return extendedDescription;\n }\n } \/\/ ... createDefaultSettings(...)\n\n static ThisType* create(const Dune::ParameterTree& _settings, const std::string subName = id())\n {\n \/\/ get correct _settings\n Dune::Stuff::Common::ExtendedParameterTree settings;\n if (_settings.hasSub(subName))\n settings = _settings.sub(subName);\n else\n settings = _settings;\n \/\/ create and return\n if (!settings.hasKey(\"filename\"))\n DUNE_THROW(Dune::RangeError,\n \"\\nMissing key 'filename' in the following Dune::ParameterTree:\\n\" << settings.reportString(\" \"));\n const std::string filename = settings.get(\"filename\", \"meaningless_default_value\");\n return new ThisType(filename);\n }\n\n ThisType& operator=(ThisType& other)\n {\n if (this != &other) {\n grid_ = other.grid();\n }\n return this;\n }\n\n \/\/! access to shared ptr\n virtual std::shared_ptr<GridType> grid()\n {\n return grid_;\n }\n\n \/\/! const access to shared ptr\n virtual const std::shared_ptr< const GridType > grid() const\n {\n return grid_;\n }\n\nprivate:\n std::shared_ptr< GridType > grid_;\n}; \/\/ class GridProviderGmsh\n\n\n} \/\/ namespace Stuff\n} \/\/ namespace Dune\n\n#endif \/\/ HAVE_DUNE_GRID\n#endif \/\/ defined ALUGRID_CONFORM || defined ALUGRID_CUBE || defined ALUGRID_SIMPLEX || defined ALBERTAGRID || defined UGGRID\n#endif \/\/ HAVE_ALUGRID || HAVE_ALBERTA || HAVE_UG\n\n#endif \/\/ DUNE_STUFF_GRID_PROVIDER_GMSH_HH\n<commit_msg>[grid.provider.gmsh] removed SGrid default and some #ifdefs<commit_after>#ifndef DUNE_STUFF_GRID_PROVIDER_GMSH_HH\n#define DUNE_STUFF_GRID_PROVIDER_GMSH_HH\n\n#if HAVE_DUNE_GRID\n\n#include <memory>\n#include <sstream>\n#include <type_traits>\n\n#include <dune\/common\/exceptions.hh>\n#include <dune\/common\/fvector.hh>\n\n#include <dune\/grid\/utility\/structuredgridfactory.hh>\n#include <dune\/grid\/sgrid.hh>\n#include <dune\/grid\/io\/file\/gmshreader.hh>\n\n#include <dune\/stuff\/common\/parameter\/tree.hh>\n\n#include \"interface.hh\"\n\nnamespace Dune {\nnamespace Stuff {\n\n\n\/**\n * \\brief Gmsh grid provider\n *\/\n#if defined HAVE_CONFIG_H || defined HAVE_CMAKE_CONFIG\ntemplate< class GridImp = Dune::GridSelector::GridType >\n#else\ntemplate< class GridImp >\n#endif\nclass GridProviderGmsh\n : public GridProviderInterface< GridImp >\n{\npublic:\n \/\/! Type of the provided grid.\n typedef GridImp GridType;\n\n typedef GridProviderInterface< GridType > BaseType;\n\n typedef GridProviderGmsh< GridType > ThisType;\n\n \/\/! Dimension of the provided grid.\n static const unsigned int dim = BaseType::dim;\n\n \/\/! Type of the grids coordinates.\n typedef typename BaseType::CoordinateType CoordinateType;\n\n \/\/! Unique identifier: \\c stuff.grid.provider.gmsh\n static const std::string id()\n {\n return BaseType::id() + \".gmsh\";\n }\n\n GridProviderGmsh(const std::string filename)\n {\n dune_static_assert(!(Dune::is_same< GridType, Dune::YaspGrid< dim > >::value),\n \"GmshReader does not work with YaspGrid!\");\n dune_static_assert(!(Dune::is_same< GridType, Dune::SGrid< 2, 2 > >::value),\n \"GmshReader does not work with SGrid!\");\n grid_ = std::shared_ptr< GridType >(GmshReader< GridType >::read(filename));\n }\n\n GridProviderGmsh(ThisType& other)\n : grid_(other.grid_)\n {}\n\n GridProviderGmsh(const ThisType& other)\n : grid_(other.grid_)\n {}\n\n static Dune::ParameterTree defaultSettings(const std::string subName = \"\")\n {\n Dune::ParameterTree description;\n description[\"filename\"] = \"path_to_g.msh\";\n if (subName.empty())\n return description;\n else {\n Dune::Stuff::Common::ExtendedParameterTree extendedDescription;\n extendedDescription.add(description, subName);\n return extendedDescription;\n }\n } \/\/ ... createDefaultSettings(...)\n\n static ThisType* create(const Dune::ParameterTree& _settings, const std::string subName = id())\n {\n \/\/ get correct _settings\n Dune::Stuff::Common::ExtendedParameterTree settings;\n if (_settings.hasSub(subName))\n settings = _settings.sub(subName);\n else\n settings = _settings;\n \/\/ create and return\n if (!settings.hasKey(\"filename\"))\n DUNE_THROW(Dune::RangeError,\n \"\\nMissing key 'filename' in the following Dune::ParameterTree:\\n\" << settings.reportString(\" \"));\n const std::string filename = settings.get(\"filename\", \"meaningless_default_value\");\n return new ThisType(filename);\n }\n\n ThisType& operator=(ThisType& other)\n {\n if (this != &other) {\n grid_ = other.grid();\n }\n return this;\n }\n\n \/\/! access to shared ptr\n virtual std::shared_ptr<GridType> grid()\n {\n return grid_;\n }\n\n \/\/! const access to shared ptr\n virtual const std::shared_ptr< const GridType > grid() const\n {\n return grid_;\n }\n\nprivate:\n std::shared_ptr< GridType > grid_;\n}; \/\/ class GridProviderGmsh\n\n\n} \/\/ namespace Stuff\n} \/\/ namespace Dune\n\n#endif \/\/ HAVE_DUNE_GRID\n\n#endif \/\/ DUNE_STUFF_GRID_PROVIDER_GMSH_HH\n<|endoftext|>"} {"text":"<commit_before>#include <map>\n#include <iostream>\n#include <stdlib.h>\nusing namespace std;\n\nfloat* def_variables(int ecozone, int forestmodel_data, int ifl, int climate, int plant_data, int lossyr)\n{\n\n\tint model_years; \/\/ How many loss years are in the model\n model_years = 15;\n\n\tint tropical; \/\/ The ecozone code for the tropics\n tropical = 1;\n int temperate; \/\/ The ecozone code for the temperate zone\n temperate = 3;\n int boreal; \/\/ The ecozone code for the boreal zone\n boreal = 2;\n\n\t\/\/ returns Cf, CO2, CH4, N2O, peatburn, peat_drain_total\n\tfloat Cf;\n\tfloat CO2;\n\tfloat CH4;\n\tfloat N2O;\n\tfloat peatburn;\n\tfloat peat_drain_annual;\n\tfloat peat_drain_total;\n\n\tif ((forestmodel_data == 1) || (forestmodel_data == 2) || (forestmodel_data == 5)) \/\/ Commodities, shifting ag., or urbanization\n\t{\n\t\tif (ecozone == boreal) \/\/ Commodities\/shifting ag\/urbanization, boreal\n\t\t{\n\t\t\tCf = 0.59;\n\t\t\tCO2 = 1569;\n\t\t\tCH4 = 4.7;\n\t\t\tN2O = 0.26;\n\t\t\tpeatburn = 41;\n\t\t\tpeat_drain_total = (model_years - lossyr) * 36;\n\t\t}\n\t\telse if (ecozone == temperate)\/\/ Commodities\/shifting ag\/urbanization, temperate\n\t\t{\n\t\t\tCf = 0.51;\n\t\t\tCO2 = 1569;\n\t\t\tCH4 = 4.7;\n\t\t\tN2O = 0.26;\n\t\t\tpeatburn = 41;\n\t\t\tpeat_drain_total = (model_years - lossyr) * 31;\n\t\t}\n\t\telse if (ecozone == tropical) \/\/ Commodities\/shifting ag\/urbanization, tropics\n\t\t{\n\t\t\tCO2 = 1580;\n\t\t\tCH4 = 6.8;\n\t\t\tN2O = 0.2;\n\t\t\tpeatburn = 163;\n\n if (plant_data == 1) \/\/ Commodities\/shifting ag\/urbanization, tropics, oil palm\n {\n peat_drain_annual = 47;\n }\n else if (plant_data == 2) \/\/ Commodities\/shifting ag\/urbanization, tropics, wood fiber\n {\n peat_drain_annual = 80;\n }\n else \/\/ Commodities\/shifting ag\/urbanization, tropics, other plantation or no plantation\n {\n peat_drain_annual = 62;\n }\n peat_drain_total = (model_years - lossyr) * peat_drain_annual;\n\n\t\t\tif (ifl > 0) \/\/ Commodities\/shifting ag\/urbanization, tropics, in IFL\n\t\t\t{\n\t\t\t\tCf = 0.36;\n\t\t\t}\n\t\t\telse \/\/ Commodities\/shifting ag\/urbanization, tropics, outside IFL\n\t\t\t{\n\t\t\t\tCf = 0.55;\n\t\t\t}\n\t\t}\n\/\/ cout << \"ecozone: \" << ecozone << endl;\n\/\/ cout << \"forestmodel_data: \" << forestmodel_data << endl;\n\/\/ cout << \"ifl: \" << ifl << endl;\n\/\/ cout << \"climate: \" << climate << endl;\n\/\/ cout << \"plant_data: \" << plant_data << endl;\n\/\/ cout << \"model_years: \" << model_years << endl;\n\/\/ cout << \"loss_yr: \" << lossyr << endl;\n\/\/ cout << \"peat_drain_annual: \" << peat_drain_annual << endl;\n\/\/ cout << \"peat_drain_total: \" << peat_drain_total << endl;\n\t}\n\n\telse if (forestmodel_data == 3) \/\/ Forestry\n\t{\n\n\t\tif (ecozone == boreal) \/\/ Forestry, boreal\n\t\t{\n\t\t\tCf = 0.33;\n\t\t\tCO2 = 1569;\n\t\t\tCH4 = 4.7;\n\t\t\tN2O = 0.26;\n\t\t\tpeatburn = 41;\n\t\t\tpeat_drain_total = (model_years - lossyr) * 3;\n\t\t}\n\t\telse if (ecozone == temperate)\/\/ Forestry, temperate\n\t\t{\n\t\t\tCf = 0.62;\n\t\t\tCO2 = 1569;\n\t\t\tCH4 = 4.7;\n\t\t\tN2O = 0.26;\n\t\t\tpeatburn = 41;\n\t\t\tpeat_drain_total = (model_years - lossyr) * 12;\n\t\t}\n\t\telse if (ecozone == tropical) \/\/ Forestry, tropics\n\t\t{\n\t\t\tCO2 = 1580;\n\t\t\tCH4 = 6.8;\n\t\t\tN2O = 0.2;\n\t\t\tpeatburn = 163;\n\n\t\t\tif (plant_data == 1) \/\/ Forestry, tropics, oil palm\n {\n peat_drain_annual = 45;\n }\n else if (plant_data == 2) \/\/ Forestry, tropics, wood fiber\n {\n peat_drain_annual = 79;\n }\n else \/\/ Forestry, tropics, other plantation or no plantation\n {\n peat_drain_annual = 60;\n }\n peat_drain_total = (model_years - lossyr) * peat_drain_annual;\n\n\t\t\tif (ifl > 0)\n\t\t\t{\n\t\t\t\tCf = 0.36; \/\/ Forestry, tropics, in IFL\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tCf = 0.55; \/\/ Forestry, tropics, outside IFL\n\t\t\t}\n\t\t}\n\/\/ cout << \"ecozone: \" << ecozone << endl;\n\/\/ cout << \"forestmodel_data: \" << forestmodel_data << endl;\n\/\/ cout << \"ifl: \" << ifl << endl;\n\/\/ cout << \"climate: \" << climate << endl;\n\/\/ cout << \"plant_data: \" << plant_data << endl;\n\/\/ cout << \"model_years: \" << model_years << endl;\n\/\/ cout << \"loss_yr: \" << lossyr << endl;\n\/\/ cout << \"peat_drain_annual: \" << peat_drain_annual << endl;\n\/\/ cout << \"peat_drain_total: \" << peat_drain_total << endl;\n\t}\n\n\telse if (forestmodel_data == 4) \/\/ Wildfire\n\t{\n\n\t\tif (ecozone == boreal) \/\/ Wildfire, boreal\n\t\t{\n\t\t\tCf = 0.59;\n\t\t\tCO2 = 1569;\n\t\t\tCH4 = 4.7;\n\t\t\tN2O = 0.26;\n\t\t\tpeatburn = 41;\n\t\t\tpeat_drain_total = (model_years - lossyr) * 3;\n\t\t}\n\t\telse if (ecozone == temperate)\/\/ Wildfire, temperate\n\t\t{\n\t\t\tCf = 0.51;\n\t\t\tCO2 = 1569;\n\t\t\tCH4 = 4.7;\n\t\t\tN2O = 0.26;\n\t\t\tpeatburn = 41;\n\t\t\tpeat_drain_total = (model_years - lossyr) * 12;\n\t\t}\n\t\telse if (ecozone == tropical) \/\/ Wildfire, tropics\n\t\t{\n\t\t\tCO2 = 1580;\n\t\t\tCH4 = 6.8;\n\t\t\tN2O = 0.2;\n\t\t\tpeatburn = 371;\n\n\t\t if (plant_data == 1) \/\/ Wildfire, tropics, oil palm\n {\n peat_drain_annual = 45;\n }\n else if (plant_data == 2) \/\/ Wildfire, tropics, wood fiber\n {\n peat_drain_annual = 79;\n }\n else \/\/ Wildfire, tropics, other plantation or no plantation\n {\n peat_drain_annual = 60;\n }\n peat_drain_total = (model_years - lossyr) * peat_drain_annual;\n\n\t\t\tif (ifl > 0) \/\/ Wildfire, tropics, in IFL\n\t\t\t{\n\t\t\t\tCf = 0.36;\n\t\t\t}\n\t\t\telse \/\/ Wildfire, tropics, outside IFL\n\t\t\t{\n\t\t\t\tCf = 0.55;\n\t\t\t}\n\t\t}\n\/\/ cout << \"ecozone: \" << ecozone << endl;\n\/\/ cout << \"forestmodel_data: \" << forestmodel_data << endl;\n\/\/ cout << \"ifl: \" << ifl << endl;\n\/\/ cout << \"climate: \" << climate << endl;\n\/\/ cout << \"plant_data: \" << plant_data << endl;\n\/\/ cout << \"model_years: \" << model_years << endl;\n\/\/ cout << \"loss_yr: \" << lossyr << endl;\n\/\/ cout << \"peat_drain_annual: \" << peat_drain_annual << endl;\n\/\/ cout << \"peat_drain_total: \" << peat_drain_total << endl;\n\t}\n\n\telse \/\/ No driver-- same as forestry\n\t{\n\t\tif (ecozone == boreal) \/\/ No driver, boreal\n\t\t{\n\t\t\tCf = 0.33;\n\t\t\tCO2 = 1569;\n\t\t\tCH4 = 4.7;\n\t\t\tN2O = 0.26;\n\t\t\tpeatburn = 41;\n\t\t\tpeat_drain_total = (model_years - lossyr) * 3;\n\t\t}\n\t\telse if (ecozone == temperate)\/\/ No driver, temperate\n\t\t{\n\t\t\tCf = 0.62;\n\t\t\tCO2 = 1569;\n\t\t\tCH4 = 4.7;\n\t\t\tN2O = 0.26;\n\t\t\tpeatburn = 41;\n\t\t\tpeat_drain_total = (model_years - lossyr) * 12;\n\t\t}\n\t\telse if (ecozone == tropical) \/\/ No driver, tropics\n\t\t{\n\t\t\tCO2 = 1580;\n\t\t\tCH4 = 6.8;\n\t\t\tN2O = 0.2;\n\t\t\tpeatburn = 163;\n\n\t\t\tif (plant_data == 1) \/\/ No driver, tropics, oil palm\n {\n peat_drain_annual = 45;\n }\n else if (plant_data == 2) \/\/ No driver, tropics, wood fiber\n {\n peat_drain_annual = 79;\n }\n else \/\/ No driver, tropics, other plantation or no plantation\n {\n peat_drain_annual = 60;\n }\n peat_drain_total = (model_years - lossyr) * peat_drain_annual;\n\n\t\t\tif (ifl > 0)\n\t\t\t{\n\t\t\t\tCf = 0.36; \/\/ No driver, tropics, in IFL\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tCf = 0.55; \/\/ No driver, tropics, outside IFL\n\t\t\t}\n\t\t}\n\/\/ cout << \"ecozone: \" << ecozone << endl;\n\/\/ cout << \"forestmodel_data: \" << forestmodel_data << endl;\n\/\/ cout << \"ifl: \" << ifl << endl;\n\/\/ cout << \"climate: \" << climate << endl;\n\/\/ cout << \"plant_data: \" << plant_data << endl;\n\/\/ cout << \"model_years: \" << model_years << endl;\n\/\/ cout << \"loss_yr: \" << lossyr << endl;\n\/\/ cout << \"peat_drain_annual: \" << peat_drain_annual << endl;\n\/\/ cout << \"peat_drain_total: \" << peat_drain_total << endl;\n\t}\n\n\/\/ cout << \"ecozone end of fx: \" << ecozone << endl;\n\/\/ cout << \"forestmodel_data end of fx: \" << forestmodel_data << endl;\n\/\/ cout << \"ifl end of fx: \" << ifl << endl;\n\/\/ cout << \"climate end of fx: \" << climate << endl;\n\/\/ cout << \"plant_data end of fx: \" << plant_data << endl;\n\/\/ cout << \"model_years end of fx: \" << model_years << endl;\n\/\/ cout << \"loss_yr end of fx: \" << lossyr << endl;\n\n float test;\n test = srand(time(0));\n\n cout << \"cf end of fx: \" << Cf << endl;\n cout << \"gef_co2 end of fx: \" << CO2 << endl;\n cout << \"gef_Ch4 end of fx: \" << CH4 << endl;\n cout << \"gef_n2o end of fx: \" << N2O << endl;\n cout << \"peatburn end of fx: \" << peatburn << endl;\n cout << \"peat_drain_annual end of fx: \" << peat_drain_annual << endl;\n cout << \"peat_drain_total end of fx: \" << peat_drain_total << endl;\n cout << \"random_number end of fx: \" << test << endl;\n cout << endl;\n\n\tstatic float def_variables[6] = {Cf, CO2, CH4, N2O, peatburn, test};\n\n\treturn def_variables;\n\n}<commit_msg>Peat drain values aren't being added to emissions. Trying to figure out why.<commit_after>#include <map>\n#include <iostream>\n#include <stdlib.h>\nusing namespace std;\n\nfloat* def_variables(int ecozone, int forestmodel_data, int ifl, int climate, int plant_data, int lossyr)\n{\n\n\tint model_years; \/\/ How many loss years are in the model\n model_years = 15;\n\n\tint tropical; \/\/ The ecozone code for the tropics\n tropical = 1;\n int temperate; \/\/ The ecozone code for the temperate zone\n temperate = 3;\n int boreal; \/\/ The ecozone code for the boreal zone\n boreal = 2;\n\n\t\/\/ returns Cf, CO2, CH4, N2O, peatburn, peat_drain_total\n\tfloat Cf;\n\tfloat CO2;\n\tfloat CH4;\n\tfloat N2O;\n\tfloat peatburn;\n\tfloat peat_drain_annual;\n\tfloat peat_drain_total;\n\n\tif ((forestmodel_data == 1) || (forestmodel_data == 2) || (forestmodel_data == 5)) \/\/ Commodities, shifting ag., or urbanization\n\t{\n\t\tif (ecozone == boreal) \/\/ Commodities\/shifting ag\/urbanization, boreal\n\t\t{\n\t\t\tCf = 0.59;\n\t\t\tCO2 = 1569;\n\t\t\tCH4 = 4.7;\n\t\t\tN2O = 0.26;\n\t\t\tpeatburn = 41;\n\t\t\tpeat_drain_total = (model_years - lossyr) * 36;\n\t\t}\n\t\telse if (ecozone == temperate)\/\/ Commodities\/shifting ag\/urbanization, temperate\n\t\t{\n\t\t\tCf = 0.51;\n\t\t\tCO2 = 1569;\n\t\t\tCH4 = 4.7;\n\t\t\tN2O = 0.26;\n\t\t\tpeatburn = 41;\n\t\t\tpeat_drain_total = (model_years - lossyr) * 31;\n\t\t}\n\t\telse if (ecozone == tropical) \/\/ Commodities\/shifting ag\/urbanization, tropics\n\t\t{\n\t\t\tCO2 = 1580;\n\t\t\tCH4 = 6.8;\n\t\t\tN2O = 0.2;\n\t\t\tpeatburn = 163;\n\n if (plant_data == 1) \/\/ Commodities\/shifting ag\/urbanization, tropics, oil palm\n {\n peat_drain_annual = 47;\n }\n else if (plant_data == 2) \/\/ Commodities\/shifting ag\/urbanization, tropics, wood fiber\n {\n peat_drain_annual = 80;\n }\n else \/\/ Commodities\/shifting ag\/urbanization, tropics, other plantation or no plantation\n {\n peat_drain_annual = 62;\n }\n peat_drain_total = (model_years - lossyr) * peat_drain_annual;\n\n\t\t\tif (ifl > 0) \/\/ Commodities\/shifting ag\/urbanization, tropics, in IFL\n\t\t\t{\n\t\t\t\tCf = 0.36;\n\t\t\t}\n\t\t\telse \/\/ Commodities\/shifting ag\/urbanization, tropics, outside IFL\n\t\t\t{\n\t\t\t\tCf = 0.55;\n\t\t\t}\n\t\t}\n\/\/ cout << \"ecozone: \" << ecozone << endl;\n\/\/ cout << \"forestmodel_data: \" << forestmodel_data << endl;\n\/\/ cout << \"ifl: \" << ifl << endl;\n\/\/ cout << \"climate: \" << climate << endl;\n\/\/ cout << \"plant_data: \" << plant_data << endl;\n\/\/ cout << \"model_years: \" << model_years << endl;\n\/\/ cout << \"loss_yr: \" << lossyr << endl;\n\/\/ cout << \"peat_drain_annual: \" << peat_drain_annual << endl;\n\/\/ cout << \"peat_drain_total: \" << peat_drain_total << endl;\n\t}\n\n\telse if (forestmodel_data == 3) \/\/ Forestry\n\t{\n\n\t\tif (ecozone == boreal) \/\/ Forestry, boreal\n\t\t{\n\t\t\tCf = 0.33;\n\t\t\tCO2 = 1569;\n\t\t\tCH4 = 4.7;\n\t\t\tN2O = 0.26;\n\t\t\tpeatburn = 41;\n\t\t\tpeat_drain_total = (model_years - lossyr) * 3;\n\t\t}\n\t\telse if (ecozone == temperate)\/\/ Forestry, temperate\n\t\t{\n\t\t\tCf = 0.62;\n\t\t\tCO2 = 1569;\n\t\t\tCH4 = 4.7;\n\t\t\tN2O = 0.26;\n\t\t\tpeatburn = 41;\n\t\t\tpeat_drain_total = (model_years - lossyr) * 12;\n\t\t}\n\t\telse if (ecozone == tropical) \/\/ Forestry, tropics\n\t\t{\n\t\t\tCO2 = 1580;\n\t\t\tCH4 = 6.8;\n\t\t\tN2O = 0.2;\n\t\t\tpeatburn = 163;\n\n\t\t\tif (plant_data == 1) \/\/ Forestry, tropics, oil palm\n {\n peat_drain_annual = 45;\n }\n else if (plant_data == 2) \/\/ Forestry, tropics, wood fiber\n {\n peat_drain_annual = 79;\n }\n else \/\/ Forestry, tropics, other plantation or no plantation\n {\n peat_drain_annual = 60;\n }\n peat_drain_total = (model_years - lossyr) * peat_drain_annual;\n\n\t\t\tif (ifl > 0)\n\t\t\t{\n\t\t\t\tCf = 0.36; \/\/ Forestry, tropics, in IFL\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tCf = 0.55; \/\/ Forestry, tropics, outside IFL\n\t\t\t}\n\t\t}\n\/\/ cout << \"ecozone: \" << ecozone << endl;\n\/\/ cout << \"forestmodel_data: \" << forestmodel_data << endl;\n\/\/ cout << \"ifl: \" << ifl << endl;\n\/\/ cout << \"climate: \" << climate << endl;\n\/\/ cout << \"plant_data: \" << plant_data << endl;\n\/\/ cout << \"model_years: \" << model_years << endl;\n\/\/ cout << \"loss_yr: \" << lossyr << endl;\n\/\/ cout << \"peat_drain_annual: \" << peat_drain_annual << endl;\n\/\/ cout << \"peat_drain_total: \" << peat_drain_total << endl;\n\t}\n\n\telse if (forestmodel_data == 4) \/\/ Wildfire\n\t{\n\n\t\tif (ecozone == boreal) \/\/ Wildfire, boreal\n\t\t{\n\t\t\tCf = 0.59;\n\t\t\tCO2 = 1569;\n\t\t\tCH4 = 4.7;\n\t\t\tN2O = 0.26;\n\t\t\tpeatburn = 41;\n\t\t\tpeat_drain_total = (model_years - lossyr) * 3;\n\t\t}\n\t\telse if (ecozone == temperate)\/\/ Wildfire, temperate\n\t\t{\n\t\t\tCf = 0.51;\n\t\t\tCO2 = 1569;\n\t\t\tCH4 = 4.7;\n\t\t\tN2O = 0.26;\n\t\t\tpeatburn = 41;\n\t\t\tpeat_drain_total = (model_years - lossyr) * 12;\n\t\t}\n\t\telse if (ecozone == tropical) \/\/ Wildfire, tropics\n\t\t{\n\t\t\tCO2 = 1580;\n\t\t\tCH4 = 6.8;\n\t\t\tN2O = 0.2;\n\t\t\tpeatburn = 371;\n\n\t\t if (plant_data == 1) \/\/ Wildfire, tropics, oil palm\n {\n peat_drain_annual = 45;\n }\n else if (plant_data == 2) \/\/ Wildfire, tropics, wood fiber\n {\n peat_drain_annual = 79;\n }\n else \/\/ Wildfire, tropics, other plantation or no plantation\n {\n peat_drain_annual = 60;\n }\n peat_drain_total = (model_years - lossyr) * peat_drain_annual;\n\n\t\t\tif (ifl > 0) \/\/ Wildfire, tropics, in IFL\n\t\t\t{\n\t\t\t\tCf = 0.36;\n\t\t\t}\n\t\t\telse \/\/ Wildfire, tropics, outside IFL\n\t\t\t{\n\t\t\t\tCf = 0.55;\n\t\t\t}\n\t\t}\n\/\/ cout << \"ecozone: \" << ecozone << endl;\n\/\/ cout << \"forestmodel_data: \" << forestmodel_data << endl;\n\/\/ cout << \"ifl: \" << ifl << endl;\n\/\/ cout << \"climate: \" << climate << endl;\n\/\/ cout << \"plant_data: \" << plant_data << endl;\n\/\/ cout << \"model_years: \" << model_years << endl;\n\/\/ cout << \"loss_yr: \" << lossyr << endl;\n\/\/ cout << \"peat_drain_annual: \" << peat_drain_annual << endl;\n\/\/ cout << \"peat_drain_total: \" << peat_drain_total << endl;\n\t}\n\n\telse \/\/ No driver-- same as forestry\n\t{\n\t\tif (ecozone == boreal) \/\/ No driver, boreal\n\t\t{\n\t\t\tCf = 0.33;\n\t\t\tCO2 = 1569;\n\t\t\tCH4 = 4.7;\n\t\t\tN2O = 0.26;\n\t\t\tpeatburn = 41;\n\t\t\tpeat_drain_total = (model_years - lossyr) * 3;\n\t\t}\n\t\telse if (ecozone == temperate)\/\/ No driver, temperate\n\t\t{\n\t\t\tCf = 0.62;\n\t\t\tCO2 = 1569;\n\t\t\tCH4 = 4.7;\n\t\t\tN2O = 0.26;\n\t\t\tpeatburn = 41;\n\t\t\tpeat_drain_total = (model_years - lossyr) * 12;\n\t\t}\n\t\telse if (ecozone == tropical) \/\/ No driver, tropics\n\t\t{\n\t\t\tCO2 = 1580;\n\t\t\tCH4 = 6.8;\n\t\t\tN2O = 0.2;\n\t\t\tpeatburn = 163;\n\n\t\t\tif (plant_data == 1) \/\/ No driver, tropics, oil palm\n {\n peat_drain_annual = 45;\n }\n else if (plant_data == 2) \/\/ No driver, tropics, wood fiber\n {\n peat_drain_annual = 79;\n }\n else \/\/ No driver, tropics, other plantation or no plantation\n {\n peat_drain_annual = 60;\n }\n peat_drain_total = (model_years - lossyr) * peat_drain_annual;\n\n\t\t\tif (ifl > 0)\n\t\t\t{\n\t\t\t\tCf = 0.36; \/\/ No driver, tropics, in IFL\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tCf = 0.55; \/\/ No driver, tropics, outside IFL\n\t\t\t}\n\t\t}\n\/\/ cout << \"ecozone: \" << ecozone << endl;\n\/\/ cout << \"forestmodel_data: \" << forestmodel_data << endl;\n\/\/ cout << \"ifl: \" << ifl << endl;\n\/\/ cout << \"climate: \" << climate << endl;\n\/\/ cout << \"plant_data: \" << plant_data << endl;\n\/\/ cout << \"model_years: \" << model_years << endl;\n\/\/ cout << \"loss_yr: \" << lossyr << endl;\n\/\/ cout << \"peat_drain_annual: \" << peat_drain_annual << endl;\n\/\/ cout << \"peat_drain_total: \" << peat_drain_total << endl;\n\t}\n\n\/\/ cout << \"ecozone end of fx: \" << ecozone << endl;\n\/\/ cout << \"forestmodel_data end of fx: \" << forestmodel_data << endl;\n\/\/ cout << \"ifl end of fx: \" << ifl << endl;\n\/\/ cout << \"climate end of fx: \" << climate << endl;\n\/\/ cout << \"plant_data end of fx: \" << plant_data << endl;\n\/\/ cout << \"model_years end of fx: \" << model_years << endl;\n\/\/ cout << \"loss_yr end of fx: \" << lossyr << endl;\n\n float test;\n srand(time(0));\n test = rand();\n\n cout << \"cf end of fx: \" << Cf << endl;\n cout << \"gef_co2 end of fx: \" << CO2 << endl;\n cout << \"gef_Ch4 end of fx: \" << CH4 << endl;\n cout << \"gef_n2o end of fx: \" << N2O << endl;\n cout << \"peatburn end of fx: \" << peatburn << endl;\n cout << \"peat_drain_annual end of fx: \" << peat_drain_annual << endl;\n cout << \"peat_drain_total end of fx: \" << peat_drain_total << endl;\n cout << \"random_number end of fx: \" << test << endl;\n cout << endl;\n\n\tstatic float def_variables[6] = {Cf, CO2, CH4, N2O, peatburn, test};\n\n\treturn def_variables;\n\n}<|endoftext|>"} {"text":"<commit_before>\/***************************************************************************\n * Copyright (C) 2005-2008 by the FIFE team *\n * http:\/\/www.fifengine.de *\n * This file is part of FIFE. *\n * *\n * FIFE is free software; you can redistribute it and\/or *\n * modify it under the terms of the GNU Lesser General Public *\n * License as published by the Free Software Foundation; either *\n * version 2.1 of the License, or (at your option) any later version. *\n * *\n * This library is distributed in the hope that it will be useful, *\n * but WITHOUT ANY WARRANTY; without even the implied warranty of *\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *\n * Lesser General Public License for more details. *\n * *\n * You should have received a copy of the GNU Lesser General Public *\n * License along with this library; if not, write to the *\n * Free Software Foundation, Inc., *\n * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA *\n ***************************************************************************\/\n\n\/\/ Standard C++ library includes\n#include <fstream>\n\n\/\/ 3rd party library includes\n#include <boost\/filesystem\/operations.hpp>\n#include <boost\/filesystem\/path.hpp>\n#include <boost\/version.hpp>\n\n\/\/ FIFE includes\n\/\/ These includes are split up in two parts, separated by one empty line\n\/\/ First block: files included from the FIFE root src directory\n\/\/ Second block: files included from the same folder\n#include \"vfs\/raw\/rawdata.h\"\n#include \"vfs\/raw\/rawdatafile.h\"\n#include \"util\/log\/logger.h\"\n#include \"util\/base\/exception.h\"\n#include \"vfsdirectory.h\"\n\nnamespace \n{\n \/\/ grab the major and minor version of boost, taken from boost\/version.hpp\n#define BOOST_MAJOR_VERSION BOOST_VERSION \/ 100000\n#define BOOST_MINOR_VERSION BOOST_VERSION \/ 100 % 1000\n\n#if (BOOST_MAJOR_VERSION >= 1 && BOOST_MINOR_VERSION >= 36)\n #define USE_NEW_BOOST_FILESYSTEM\n#endif\n}\n\nnamespace bfs = boost::filesystem;\nnamespace FIFE {\n\tstatic Logger _log(LM_VFS);\n\n\tVFSDirectory::VFSDirectory(VFS* vfs, const std::string& root) : VFSSource(vfs), m_root(root) {\n\t\tFL_DBG(_log, LMsg(\"VFSDirectory created with root path \") << m_root);\n\t\tif(!m_root.empty() && *(m_root.end() - 1) != '\/')\n\t\t\tm_root.append(1,'\/');\n\t}\n\n\n\tVFSDirectory::~VFSDirectory() {\n\t}\n\n\n\tbool VFSDirectory::fileExists(const std::string& name) const {\n\t\tstd::string fullpath = m_root + name;\n\t\tstd::ifstream file(fullpath.c_str());\n\t\tif (file)\n\t\t\treturn true;\n\n\t\treturn false;\n\t}\n\n\tRawData* VFSDirectory::open(const std::string& file) const {\n\t\treturn new RawData(new RawDataFile(m_root + file));\n\t}\n\n\tstd::set<std::string> VFSDirectory::listFiles(const std::string& path) const {\n\t\treturn list(path, false);\n\t}\n\n\tstd::set<std::string> VFSDirectory::listDirectories(const std::string& path) const {\n\t\treturn list(path, true);\n\t}\n\n\tstd::set<std::string> VFSDirectory::list(const std::string& path, bool directorys) const {\n\t\tstd::set<std::string> list;\n\t\tstd::string dir = m_root;\n\n\t\t\/\/ Avoid double slashes\n\t\tif(path[0] == '\/' && m_root[m_root.size()-1] == '\/') {\n\t\t\tdir.append(path.substr(1));\n\t\t}\n\t\telse {\n\t\t\tdir.append(path);\n\t\t}\n\n\t\ttry {\n\t\t\tbfs::path boost_path(dir);\n\t\t\tif (!bfs::exists(boost_path) || !bfs::is_directory(boost_path))\n\t\t\t\treturn list;\n\n\t\t\tbfs::directory_iterator end;\n\t\t\tfor\t(bfs::directory_iterator i(boost_path); i != end; ++i) {\n\t\t\t\tif (bfs::is_directory(*i) != directorys)\n\t\t\t\t\tcontinue;\n\n#if defined(USE_NEW_BOOST_FILESYSTEM)\n \/\/ the new way to get a filename using 1.36 and above\n list.insert(i->path().filename());\n#else\n \/\/ the old way to get a filename in version 1.35 and below\n list.insert(i->leaf());\n#endif\n\t\t\t}\n\t\t}\n\t\tcatch (const bfs::filesystem_error& ex) {\n\t\t\tthrow Exception(ex.what());\n\t\t}\n\n\t\treturn list;\n\t}\n}\n<commit_msg>Fixed the VFSDirectory so that it is compatible with the different versions of boost::filesystem. It chooses the correct functions based on the boost version being used. This is the same fix that was applied to the trunk. closes[t:529]<commit_after>\/***************************************************************************\n * Copyright (C) 2005-2008 by the FIFE team *\n * http:\/\/www.fifengine.de *\n * This file is part of FIFE. *\n * *\n * FIFE is free software; you can redistribute it and\/or *\n * modify it under the terms of the GNU Lesser General Public *\n * License as published by the Free Software Foundation; either *\n * version 2.1 of the License, or (at your option) any later version. *\n * *\n * This library is distributed in the hope that it will be useful, *\n * but WITHOUT ANY WARRANTY; without even the implied warranty of *\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *\n * Lesser General Public License for more details. *\n * *\n * You should have received a copy of the GNU Lesser General Public *\n * License along with this library; if not, write to the *\n * Free Software Foundation, Inc., *\n * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA *\n ***************************************************************************\/\n\n\/\/ Standard C++ library includes\n#include <fstream>\n\n\/\/ 3rd party library includes\n#include <boost\/filesystem\/operations.hpp>\n#include <boost\/filesystem\/path.hpp>\n#include <boost\/version.hpp>\n\n\/\/ FIFE includes\n\/\/ These includes are split up in two parts, separated by one empty line\n\/\/ First block: files included from the FIFE root src directory\n\/\/ Second block: files included from the same folder\n#include \"vfs\/raw\/rawdata.h\"\n#include \"vfs\/raw\/rawdatafile.h\"\n#include \"util\/log\/logger.h\"\n#include \"util\/base\/exception.h\"\n#include \"vfsdirectory.h\"\n\nnamespace bfs = boost::filesystem;\n\nnamespace \n{\n \/\/ grab the major and minor version of boost, \n \/\/ calculations taken from boost\/version.hpp\n #define BOOST_MAJOR_VERSION BOOST_VERSION \/ 100000\n #define BOOST_MINOR_VERSION BOOST_VERSION \/ 100 % 1000\n\n#if (BOOST_MAJOR_VERSION >= 1 && BOOST_MINOR_VERSION >= 46)\n \/\/ this define will tell us to use boost filesystem\n \/\/ version 3 since this is the default version of the library\n \/\/ starting in boost version 1.46 and above\n #define USE_BOOST_FILESYSTEM_V3\n#elif (BOOST_MAJOR_VERSION >= 1 && BOOST_MINOR_VERSION >= 36)\n \/\/ this define will tell us not to use the deprecated functions\n \/\/ in boost filesystem version 2 library which were introduced\n \/\/ in boost version 1.36 and above\n #define USE_NON_DEPRECATED_BOOST_FILESYSTEM_V2\n#endif\n}\n\nnamespace FIFE {\n\tstatic Logger _log(LM_VFS);\n\n\tVFSDirectory::VFSDirectory(VFS* vfs, const std::string& root) : VFSSource(vfs), m_root(root) {\n\t\tFL_DBG(_log, LMsg(\"VFSDirectory created with root path \") << m_root);\n\t\tif(!m_root.empty() && *(m_root.end() - 1) != '\/')\n\t\t\tm_root.append(1,'\/');\n\t}\n\n\n\tVFSDirectory::~VFSDirectory() {\n\t}\n\n\n\tbool VFSDirectory::fileExists(const std::string& name) const {\n\t\tstd::string fullpath = m_root + name;\n\t\tstd::ifstream file(fullpath.c_str());\n\t\tif (file)\n\t\t\treturn true;\n\n\t\treturn false;\n\t}\n\n\tRawData* VFSDirectory::open(const std::string& file) const {\n\t\treturn new RawData(new RawDataFile(m_root + file));\n\t}\n\n\tstd::set<std::string> VFSDirectory::listFiles(const std::string& path) const {\n\t\treturn list(path, false);\n\t}\n\n\tstd::set<std::string> VFSDirectory::listDirectories(const std::string& path) const {\n\t\treturn list(path, true);\n\t}\n\n\tstd::set<std::string> VFSDirectory::list(const std::string& path, bool directorys) const {\n\t\tstd::set<std::string> list;\n\t\tstd::string dir = m_root;\n\n\t\t\/\/ Avoid double slashes\n\t\tif(path[0] == '\/' && m_root[m_root.size()-1] == '\/') {\n\t\t\tdir.append(path.substr(1));\n\t\t}\n\t\telse {\n\t\t\tdir.append(path);\n\t\t}\n\n\t\ttry {\n\t\t\tbfs::path boost_path(dir);\n\t\t\tif (!bfs::exists(boost_path) || !bfs::is_directory(boost_path))\n\t\t\t\treturn list;\n\n\t\t\tbfs::directory_iterator end;\n\t\t\tfor\t(bfs::directory_iterator i(boost_path); i != end; ++i) {\n\t\t\t\tif (bfs::is_directory(*i) != directorys)\n\t\t\t\t\tcontinue;\n\n#if defined(USE_BOOST_FILESYSTEM_V3)\n \/\/ boost version 1.46 and above uses\n \/\/ boost filesystem version 3 as the default\n \/\/ which has yet a different way of getting\n \/\/ a filename string\n bfs::path filenamePath = i->path().filename();\n list.insert(filenamePath.string());\n#elif defined(USE_NON_DEPRECATED_BOOST_FILESYSTEM_V2)\n \/\/ the new way in boost filesystem version 2\n \/\/ to get a filename string\n \/\/(this is for boost version 1.36 and above)\n list.insert(i->path().filename());\n#else\n \/\/ the old way in boost filesystem version 2\n \/\/ to get a filename string \n \/\/(this is for boost version 1.35 and below)\n list.insert(i->leaf());\n#endif\n\t\t\t}\n\t\t}\n\t\tcatch (const bfs::filesystem_error& ex) {\n\t\t\tthrow Exception(ex.what());\n\t\t}\n\n\t\treturn list;\n\t}\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * #%L\n * %%\n * Copyright (C) 2011 - 2017 BMW Car IT GmbH\n * %%\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * \n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * #L%\n *\/\n#include <memory>\n#include <string>\n#include <cstdint>\n\n#include <gtest\/gtest.h>\n#include <gmock\/gmock.h>\n\n#include \"joynr\/JoynrClusterControllerRuntime.h\"\n#include \"tests\/utils\/MockObjects.h\"\n#include \"joynr\/tests\/testProvider.h\"\n#include \"joynr\/tests\/testProxy.h\"\n#include \"joynr\/vehicle\/GpsProxy.h\"\n#include \"joynr\/types\/ProviderQos.h\"\n#include \"joynr\/Future.h\"\n#include \"joynr\/OnChangeWithKeepAliveSubscriptionQos.h\"\n#include \"joynr\/LibjoynrSettings.h\"\n#include \"joynr\/PrivateCopyAssign.h\"\n#include \"tests\/JoynrTest.h\"\n\nusing namespace ::testing;\n\n\nusing namespace joynr;\n\nclass End2EndRPCTest : public TestWithParam< std::string >{\npublic:\n std::string domain;\n std::shared_ptr<JoynrClusterControllerRuntime> runtime;\n std::shared_ptr<vehicle::GpsProvider> gpsProvider;\n\n End2EndRPCTest() :\n domain(),\n runtime()\n {\n runtime = std::make_shared<JoynrClusterControllerRuntime>(\n std::make_unique<Settings>(GetParam())\n );\n runtime->init();\n domain = \"cppEnd2EndRPCTest_Domain_\" + util::createUuid();\n\n discoveryQos.setArbitrationStrategy(DiscoveryQos::ArbitrationStrategy::HIGHEST_PRIORITY);\n discoveryQos.setDiscoveryTimeoutMs(3000);\n }\n \/\/ Sets up the test fixture.\n void SetUp(){\n runtime->start();\n }\n\n \/\/ Tears down the test fixture.\n void TearDown(){\n bool deleteChannel = true;\n runtime->stop(deleteChannel);\n\n \/\/ Delete persisted files\n std::remove(ClusterControllerSettings::DEFAULT_LOCAL_CAPABILITIES_DIRECTORY_PERSISTENCE_FILENAME().c_str());\n std::remove(LibjoynrSettings::DEFAULT_MESSAGE_ROUTER_PERSISTENCE_FILENAME().c_str());\n std::remove(LibjoynrSettings::DEFAULT_SUBSCRIPTIONREQUEST_PERSISTENCE_FILENAME().c_str());\n std::remove(LibjoynrSettings::DEFAULT_PARTICIPANT_IDS_PERSISTENCE_FILENAME().c_str());\n\n std::this_thread::sleep_for(std::chrono::milliseconds(550));\n }\n\n ~End2EndRPCTest() = default;\nprotected:\n\n joynr::DiscoveryQos discoveryQos;\n\nprivate:\n DISALLOW_COPY_AND_ASSIGN(End2EndRPCTest);\n};\n\n\/\/ leadsm to assert failure in GpsInProcessConnector line 185: not yet implemented in connector\nTEST_P(End2EndRPCTest, call_rpc_method_and_get_expected_result)\n{\n\n auto mockProvider = std::make_shared<MockGpsProvider>();\n\n types::ProviderQos providerQos;\n std::chrono::milliseconds millisSinceEpoch =\n std::chrono::duration_cast<std::chrono::milliseconds>(\n std::chrono::system_clock::now().time_since_epoch());\n providerQos.setPriority(millisSinceEpoch.count());\n providerQos.setScope(joynr::types::ProviderScope::GLOBAL);\n providerQos.setSupportsOnChangeSubscriptions(true);\n std::string participantId = runtime->registerProvider<vehicle::GpsProvider>(domain, mockProvider, providerQos);\n std::this_thread::sleep_for(std::chrono::milliseconds(550));\n\n std::shared_ptr<ProxyBuilder<vehicle::GpsProxy>> gpsProxyBuilder =\n runtime->createProxyBuilder<vehicle::GpsProxy>(domain);\n\n std::int64_t qosRoundTripTTL = 40000;\n std::shared_ptr<vehicle::GpsProxy> gpsProxy = gpsProxyBuilder\n ->setMessagingQos(MessagingQos(qosRoundTripTTL))\n ->setDiscoveryQos(discoveryQos)\n ->build();\n std::shared_ptr<Future<int> >gpsFuture (gpsProxy->calculateAvailableSatellitesAsync());\n gpsFuture->wait();\n int expectedValue = 42; \/\/as defined in MockGpsProvider\n int actualValue;\n gpsFuture->get(actualValue);\n EXPECT_EQ(expectedValue, actualValue);\n \/\/ This is not yet implemented in CapabilitiesClient\n \/\/ runtime->unregisterProvider(\"Fake_ParticipantId_vehicle\/gpsDummyProvider\");\n runtime->unregisterProvider(participantId);\n}\n\nTEST_P(End2EndRPCTest, call_void_operation)\n{\n auto mockProvider = std::make_shared<MockTestProvider>();\n\n types::ProviderQos providerQos;\n std::chrono::milliseconds millisSinceEpoch =\n std::chrono::duration_cast<std::chrono::milliseconds>(\n std::chrono::system_clock::now().time_since_epoch());\n providerQos.setPriority(millisSinceEpoch.count());\n providerQos.setScope(joynr::types::ProviderScope::GLOBAL);\n providerQos.setSupportsOnChangeSubscriptions(true);\n std::string participantId = runtime->registerProvider<tests::testProvider>(domain, mockProvider, providerQos);\n std::this_thread::sleep_for(std::chrono::milliseconds(550));\n\n std::shared_ptr<ProxyBuilder<tests::testProxy>> testProxyBuilder =\n runtime->createProxyBuilder<tests::testProxy>(domain);\n\n std::int64_t qosRoundTripTTL = 40000;\n std::shared_ptr<tests::testProxy> testProxy = testProxyBuilder\n ->setMessagingQos(MessagingQos(qosRoundTripTTL))\n ->setDiscoveryQos(discoveryQos)\n ->build();\n testProxy->voidOperation();\n\/\/ EXPECT_EQ(expectedValue, gpsFuture->getValue());\n \/\/ This is not yet implemented in CapabilitiesClient\n \/\/ runtime->unregisterProvider(\"Fake_ParticipantId_vehicle\/gpsDummyProvider\");\n runtime->unregisterProvider(participantId);\n}\n\n\/\/ tests in process subscription\nTEST_P(End2EndRPCTest, _call_subscribeTo_and_get_expected_result)\n{\n auto mockProvider = std::make_shared<MockTestProvider>();\n types::ProviderQos providerQos;\n std::chrono::milliseconds millisSinceEpoch =\n std::chrono::duration_cast<std::chrono::milliseconds>(\n std::chrono::system_clock::now().time_since_epoch());\n providerQos.setPriority(millisSinceEpoch.count());\n providerQos.setScope(joynr::types::ProviderScope::GLOBAL);\n providerQos.setSupportsOnChangeSubscriptions(true);\n std::string participantId = runtime->registerProvider<tests::testProvider>(domain, mockProvider, providerQos);\n\n std::this_thread::sleep_for(std::chrono::milliseconds(550));\n\n std::shared_ptr<ProxyBuilder<tests::testProxy>> testProxyBuilder =\n runtime->createProxyBuilder<tests::testProxy>(domain);\n\n std::int64_t qosRoundTripTTL = 40000;\n std::shared_ptr<tests::testProxy> testProxy = testProxyBuilder\n ->setMessagingQos(MessagingQos(qosRoundTripTTL))\n ->setDiscoveryQos(discoveryQos)\n ->build();\n\n MockGpsSubscriptionListener* mockListener = new MockGpsSubscriptionListener();\n std::shared_ptr<ISubscriptionListener<types::Localisation::GpsLocation> > subscriptionListener(\n mockListener);\n\n EXPECT_CALL(*mockListener, onReceive(A<const types::Localisation::GpsLocation&>()))\n .Times(AtLeast(2));\n\n auto subscriptionQos = std::make_shared<OnChangeWithKeepAliveSubscriptionQos>(\n 800, \/\/ validity_ms\n 1000, \/\/ publication ttl\n 100, \/\/ minInterval_ms\n 200, \/\/ maxInterval_ms\n 1000 \/\/ alertInterval_ms\n );\n std::shared_ptr<Future<std::string>> subscriptionIdFuture = testProxy->subscribeToLocation(subscriptionListener, subscriptionQos);\n std::this_thread::sleep_for(std::chrono::milliseconds(1500));\n \/\/ This is not yet implemented in CapabilitiesClient\n \/\/ runtime->unregisterProvider(\"Fake_ParticipantId_vehicle\/gpsDummyProvider\");\n std::string subscriptionId;\n JOYNR_ASSERT_NO_THROW(subscriptionIdFuture->get(5000, subscriptionId));\n JOYNR_ASSERT_NO_THROW(testProxy->unsubscribeFromLocation(subscriptionId));\n runtime->unregisterProvider(participantId);\n}\n\nINSTANTIATE_TEST_CASE_P(Http,\n End2EndRPCTest,\n testing::Values(\n \"test-resources\/HttpSystemIntegrationTest1.settings\"\n )\n);\n\nINSTANTIATE_TEST_CASE_P(Mqtt,\n End2EndRPCTest,\n testing::Values(\n \"test-resources\/MqttSystemIntegrationTest1.settings\"\n )\n);\n<commit_msg>[C++] Fixed End2EndRPCTest<commit_after>\/*\n * #%L\n * %%\n * Copyright (C) 2011 - 2017 BMW Car IT GmbH\n * %%\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * \n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * #L%\n *\/\n#include <memory>\n#include <string>\n#include <cstdint>\n\n#include <gtest\/gtest.h>\n#include <gmock\/gmock.h>\n\n#include \"joynr\/JoynrClusterControllerRuntime.h\"\n#include \"tests\/utils\/MockObjects.h\"\n#include \"joynr\/tests\/testProvider.h\"\n#include \"joynr\/tests\/testProxy.h\"\n#include \"joynr\/vehicle\/GpsProxy.h\"\n#include \"joynr\/types\/ProviderQos.h\"\n#include \"joynr\/Future.h\"\n#include \"joynr\/OnChangeWithKeepAliveSubscriptionQos.h\"\n#include \"joynr\/LibjoynrSettings.h\"\n#include \"joynr\/PrivateCopyAssign.h\"\n#include \"tests\/JoynrTest.h\"\n\nusing namespace ::testing;\n\n\nusing namespace joynr;\n\nclass End2EndRPCTest : public TestWithParam< std::string >{\npublic:\n std::string domain;\n std::shared_ptr<JoynrClusterControllerRuntime> runtime;\n std::shared_ptr<vehicle::GpsProvider> gpsProvider;\n\n End2EndRPCTest() :\n domain(),\n runtime()\n {\n runtime = std::make_shared<JoynrClusterControllerRuntime>(\n std::make_unique<Settings>(GetParam())\n );\n runtime->init();\n domain = \"cppEnd2EndRPCTest_Domain_\" + util::createUuid();\n\n discoveryQos.setArbitrationStrategy(DiscoveryQos::ArbitrationStrategy::HIGHEST_PRIORITY);\n discoveryQos.setDiscoveryTimeoutMs(3000);\n }\n \/\/ Sets up the test fixture.\n void SetUp(){\n runtime->start();\n }\n\n \/\/ Tears down the test fixture.\n void TearDown(){\n bool deleteChannel = true;\n runtime->stop(deleteChannel);\n runtime.reset();\n\n \/\/ Delete persisted files\n std::remove(ClusterControllerSettings::DEFAULT_LOCAL_CAPABILITIES_DIRECTORY_PERSISTENCE_FILENAME().c_str());\n std::remove(LibjoynrSettings::DEFAULT_MESSAGE_ROUTER_PERSISTENCE_FILENAME().c_str());\n std::remove(LibjoynrSettings::DEFAULT_SUBSCRIPTIONREQUEST_PERSISTENCE_FILENAME().c_str());\n std::remove(LibjoynrSettings::DEFAULT_PARTICIPANT_IDS_PERSISTENCE_FILENAME().c_str());\n\n std::this_thread::sleep_for(std::chrono::milliseconds(550));\n }\n\n ~End2EndRPCTest() = default;\nprotected:\n\n joynr::DiscoveryQos discoveryQos;\n\nprivate:\n DISALLOW_COPY_AND_ASSIGN(End2EndRPCTest);\n};\n\n\/\/ leadsm to assert failure in GpsInProcessConnector line 185: not yet implemented in connector\nTEST_P(End2EndRPCTest, call_rpc_method_and_get_expected_result)\n{\n\n auto mockProvider = std::make_shared<MockGpsProvider>();\n\n types::ProviderQos providerQos;\n std::chrono::milliseconds millisSinceEpoch =\n std::chrono::duration_cast<std::chrono::milliseconds>(\n std::chrono::system_clock::now().time_since_epoch());\n providerQos.setPriority(millisSinceEpoch.count());\n providerQos.setScope(joynr::types::ProviderScope::GLOBAL);\n providerQos.setSupportsOnChangeSubscriptions(true);\n std::string participantId = runtime->registerProvider<vehicle::GpsProvider>(domain, mockProvider, providerQos);\n std::this_thread::sleep_for(std::chrono::milliseconds(550));\n\n std::shared_ptr<ProxyBuilder<vehicle::GpsProxy>> gpsProxyBuilder =\n runtime->createProxyBuilder<vehicle::GpsProxy>(domain);\n\n std::int64_t qosRoundTripTTL = 40000;\n std::shared_ptr<vehicle::GpsProxy> gpsProxy = gpsProxyBuilder\n ->setMessagingQos(MessagingQos(qosRoundTripTTL))\n ->setDiscoveryQos(discoveryQos)\n ->build();\n std::shared_ptr<Future<int> >gpsFuture (gpsProxy->calculateAvailableSatellitesAsync());\n gpsFuture->wait();\n int expectedValue = 42; \/\/as defined in MockGpsProvider\n int actualValue;\n gpsFuture->get(actualValue);\n EXPECT_EQ(expectedValue, actualValue);\n \/\/ This is not yet implemented in CapabilitiesClient\n \/\/ runtime->unregisterProvider(\"Fake_ParticipantId_vehicle\/gpsDummyProvider\");\n runtime->unregisterProvider(participantId);\n}\n\nTEST_P(End2EndRPCTest, call_void_operation)\n{\n auto mockProvider = std::make_shared<MockTestProvider>();\n\n types::ProviderQos providerQos;\n std::chrono::milliseconds millisSinceEpoch =\n std::chrono::duration_cast<std::chrono::milliseconds>(\n std::chrono::system_clock::now().time_since_epoch());\n providerQos.setPriority(millisSinceEpoch.count());\n providerQos.setScope(joynr::types::ProviderScope::GLOBAL);\n providerQos.setSupportsOnChangeSubscriptions(true);\n std::string participantId = runtime->registerProvider<tests::testProvider>(domain, mockProvider, providerQos);\n std::this_thread::sleep_for(std::chrono::milliseconds(550));\n\n std::shared_ptr<ProxyBuilder<tests::testProxy>> testProxyBuilder =\n runtime->createProxyBuilder<tests::testProxy>(domain);\n\n std::int64_t qosRoundTripTTL = 40000;\n std::shared_ptr<tests::testProxy> testProxy = testProxyBuilder\n ->setMessagingQos(MessagingQos(qosRoundTripTTL))\n ->setDiscoveryQos(discoveryQos)\n ->build();\n testProxy->voidOperation();\n\/\/ EXPECT_EQ(expectedValue, gpsFuture->getValue());\n \/\/ This is not yet implemented in CapabilitiesClient\n \/\/ runtime->unregisterProvider(\"Fake_ParticipantId_vehicle\/gpsDummyProvider\");\n runtime->unregisterProvider(participantId);\n}\n\n\/\/ tests in process subscription\nTEST_P(End2EndRPCTest, _call_subscribeTo_and_get_expected_result)\n{\n auto mockProvider = std::make_shared<MockTestProvider>();\n types::ProviderQos providerQos;\n std::chrono::milliseconds millisSinceEpoch =\n std::chrono::duration_cast<std::chrono::milliseconds>(\n std::chrono::system_clock::now().time_since_epoch());\n providerQos.setPriority(millisSinceEpoch.count());\n providerQos.setScope(joynr::types::ProviderScope::GLOBAL);\n providerQos.setSupportsOnChangeSubscriptions(true);\n std::string participantId = runtime->registerProvider<tests::testProvider>(domain, mockProvider, providerQos);\n\n std::this_thread::sleep_for(std::chrono::milliseconds(550));\n\n std::shared_ptr<ProxyBuilder<tests::testProxy>> testProxyBuilder =\n runtime->createProxyBuilder<tests::testProxy>(domain);\n\n std::int64_t qosRoundTripTTL = 40000;\n std::shared_ptr<tests::testProxy> testProxy = testProxyBuilder\n ->setMessagingQos(MessagingQos(qosRoundTripTTL))\n ->setDiscoveryQos(discoveryQos)\n ->build();\n\n MockGpsSubscriptionListener* mockListener = new MockGpsSubscriptionListener();\n std::shared_ptr<ISubscriptionListener<types::Localisation::GpsLocation> > subscriptionListener(\n mockListener);\n\n EXPECT_CALL(*mockListener, onReceive(A<const types::Localisation::GpsLocation&>()))\n .Times(AtLeast(2));\n\n auto subscriptionQos = std::make_shared<OnChangeWithKeepAliveSubscriptionQos>(\n 800, \/\/ validity_ms\n 1000, \/\/ publication ttl\n 100, \/\/ minInterval_ms\n 200, \/\/ maxInterval_ms\n 1000 \/\/ alertInterval_ms\n );\n std::shared_ptr<Future<std::string>> subscriptionIdFuture = testProxy->subscribeToLocation(subscriptionListener, subscriptionQos);\n std::this_thread::sleep_for(std::chrono::milliseconds(1500));\n \/\/ This is not yet implemented in CapabilitiesClient\n \/\/ runtime->unregisterProvider(\"Fake_ParticipantId_vehicle\/gpsDummyProvider\");\n std::string subscriptionId;\n JOYNR_ASSERT_NO_THROW(subscriptionIdFuture->get(5000, subscriptionId));\n JOYNR_ASSERT_NO_THROW(testProxy->unsubscribeFromLocation(subscriptionId));\n runtime->unregisterProvider(participantId);\n}\n\nINSTANTIATE_TEST_CASE_P(Http,\n End2EndRPCTest,\n testing::Values(\n \"test-resources\/HttpSystemIntegrationTest1.settings\"\n )\n);\n\nINSTANTIATE_TEST_CASE_P(Mqtt,\n End2EndRPCTest,\n testing::Values(\n \"test-resources\/MqttSystemIntegrationTest1.settings\"\n )\n);\n<|endoftext|>"} {"text":"<commit_before>#define BOOST_TEST_MODULE test_function\n\n#include <stdexcept>\n#include <boost\/test\/included\/unit_test.hpp>\n\n#include \"variable.hxx\"\n#include \"coreutils.hxx\"\n\n\ndouble sum(std::vector<double> & args)\n{\n double res(0.);\n for (unsigned i = 0; i < args.size(); ++i) {\n res += double(args[i]);\n }\n return res;\n}\n\nstruct fnsetup {\n fnsetup() : myfunc(NULL)\n {\n double array[3] = {1, 2, 3};\n myfunc = &make_function(sum, 3, array);\n }\n ~fnsetup() {}\n function * myfunc;\n};\n\nBOOST_AUTO_TEST_SUITE(test)\n\nBOOST_FIXTURE_TEST_CASE(automatic_conversion, fnsetup)\n{\n BOOST_CHECK_EQUAL(6.0, *myfunc); \/\/ 1+2+3\n}\n\nBOOST_FIXTURE_TEST_CASE(direct_access, fnsetup)\n{\n auto& vars = myfunc->components();\n vars[1] = fnbase_ptr(new variable(3));\n vars[2] = fnbase_ptr(new variable(5));\n BOOST_CHECK_EQUAL(9, *myfunc); \/\/ 1+3+5\n}\n\nBOOST_FIXTURE_TEST_CASE(setter_access, fnsetup)\n{\n for (unsigned i = 0; i < 3; ++i) {\n myfunc->replace(i, new variable((i+1) * 2));\n }\n BOOST_CHECK_EQUAL(12, *myfunc); \/\/ 2+4+6\n}\n\nBOOST_AUTO_TEST_CASE(functional)\n{\n double array[3] = {1, 2, 3};\n function myfunc1 = make_function(sum, 3, array); \/\/ 1+2+3\n function myfunc2 = make_function(sum, 3, array); \/\/ 1+2+3\n fnbase_vec vars {fnbase_ptr(&myfunc1), fnbase_ptr(&myfunc2)};\n function * grandsum = new function(sum, vars); \/\/ 6+6\n BOOST_CHECK_EQUAL(12, *grandsum);\n}\n\nBOOST_FIXTURE_TEST_CASE(assignment_operator, fnsetup)\n{\n function newfn = *myfunc;\n BOOST_CHECK_EQUAL(*myfunc, newfn);\n}\n\nBOOST_FIXTURE_TEST_CASE(index_out_of_range_exception, fnsetup)\n{\n BOOST_REQUIRE_THROW(myfunc->replace(3, new variable(2)),\n\t\t std::out_of_range);\n \/\/ BOOST_REQUIRE_EXCEPTION(myfunc->replace(3, new variable(2)),\n \/\/ \t\t\t std::out_of_range, predicate);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n<commit_msg>Add test for memory problem in case of funcitonals<commit_after>#define BOOST_TEST_MODULE test_function\n\n#include <stdexcept>\n#include <boost\/test\/included\/unit_test.hpp>\n\n#include \"variable.hxx\"\n#include \"coreutils.hxx\"\n\n\ndouble sum(std::vector<double> & args)\n{\n double res(0.);\n for (unsigned i = 0; i < args.size(); ++i) {\n res += double(args[i]);\n }\n return res;\n}\n\nstruct fnsetup {\n fnsetup() : myfunc(NULL)\n {\n double array[3] = {1, 2, 3};\n myfunc = &make_function(sum, 3, array);\n }\n ~fnsetup() {}\n function * myfunc;\n};\n\nBOOST_AUTO_TEST_SUITE(test)\n\nBOOST_AUTO_TEST_CASE(base_class)\n{\n double array[3] = {1, 2, 3};\n function myfunc1 = make_function(sum, 3, array); \/\/ 1+2+3\n function myfunc2 = make_function(sum, 3, array); \/\/ 1+2+3\n fnbase_vec vars {fnbase_ptr(&myfunc1), fnbase_ptr(&myfunc2)};\n function grandsum(sum, vars); \/\/ 6+6\n BOOST_CHECK_EQUAL(12, grandsum);\n \/\/ function * grandsum = new function(sum, vars); \/\/ 6+6\n \/\/ BOOST_CHECK_EQUAL(12, *grandsum);\n}\n\nBOOST_FIXTURE_TEST_CASE(automatic_conversion, fnsetup)\n{\n BOOST_CHECK_EQUAL(6.0, *myfunc); \/\/ 1+2+3\n}\n\nBOOST_FIXTURE_TEST_CASE(direct_access, fnsetup)\n{\n auto& vars = myfunc->components();\n vars[1] = fnbase_ptr(new variable(3));\n vars[2] = fnbase_ptr(new variable(5));\n BOOST_CHECK_EQUAL(9, *myfunc); \/\/ 1+3+5\n}\n\nBOOST_FIXTURE_TEST_CASE(setter_access, fnsetup)\n{\n for (unsigned i = 0; i < 3; ++i) {\n myfunc->replace(i, new variable((i+1) * 2));\n }\n BOOST_CHECK_EQUAL(12, *myfunc); \/\/ 2+4+6\n}\n\nBOOST_AUTO_TEST_CASE(functional)\n{\n double array[3] = {1, 2, 3};\n function myfunc1 = make_function(sum, 3, array); \/\/ 1+2+3\n function myfunc2 = make_function(sum, 3, array); \/\/ 1+2+3\n fnbase_vec vars {fnbase_ptr(&myfunc1), fnbase_ptr(&myfunc2)};\n function * grandsum = new function(sum, vars); \/\/ 6+6\n BOOST_CHECK_EQUAL(12, *grandsum);\n}\n\nBOOST_FIXTURE_TEST_CASE(assignment_operator, fnsetup)\n{\n function newfn = *myfunc;\n BOOST_CHECK_EQUAL(*myfunc, newfn);\n}\n\nBOOST_FIXTURE_TEST_CASE(index_out_of_range_exception, fnsetup)\n{\n BOOST_REQUIRE_THROW(myfunc->replace(3, new variable(2)),\n\t\t std::out_of_range);\n \/\/ BOOST_REQUIRE_EXCEPTION(myfunc->replace(3, new variable(2)),\n \/\/ \t\t\t std::out_of_range, predicate);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n<|endoftext|>"} {"text":"<commit_before>\/*\n * MIT License\n *\n * Copyright (c) 2016 xiongziliang <771730766@qq.com>\n *\n * This file is part of ZLMediaKit(https:\/\/github.com\/xiongziliang\/ZLMediaKit).\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n *\/\n\n#include <map>\n#include <signal.h>\n#include <iostream>\n#include \"Common\/config.h\"\n\n#ifdef ENABLE_OPENSSL\n#include \"Util\/SSLBox.h\"\n#include \"Http\/HttpsSession.h\"\n#endif\/\/ENABLE_OPENSSL\n\n#include \"Util\/File.h\"\n#include \"Util\/logger.h\"\n#include \"Util\/onceToken.h\"\n#include \"Network\/TcpServer.h\"\n#include \"Poller\/EventPoller.h\"\n#include \"Thread\/WorkThreadPool.h\"\n#include \"Util\/NoticeCenter.h\"\n\nusing namespace std;\nusing namespace ZL::Util;\nusing namespace ZL::Http;\nusing namespace ZL::Thread;\nusing namespace ZL::Network;\n\nstatic onceToken s_token([](){\n NoticeCenter::Instance().addListener(nullptr,Config::Broadcast::kBroadcastHttpRequest,[](BroadcastHttpRequestArgs){\n \/\/const Parser &parser,HttpSession::HttpResponseInvoker &invoker,bool &consumed\n if(strstr(parser.Url().data(),\"\/api\/\") != parser.Url().data()){\n return;\n }\n \/\/url以\"\/api\/起始,说明是http api\"\n consumed = true;\/\/该http请求已被消费\n\n _StrPrinter printer;\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/method\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n printer << \"\\r\\nmethod:\\r\\n\\t\" << parser.Method();\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/url\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n printer << \"\\r\\nurl:\\r\\n\\t\" << parser.Url();\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/protocol\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n printer << \"\\r\\nprotocol:\\r\\n\\t\" << parser.Tail();\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/args\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n printer << \"\\r\\nargs:\\r\\n\";\n for(auto &pr : parser.getUrlArgs()){\n printer << \"\\t\" << pr.first << \" : \" << pr.second << \"\\r\\n\";\n }\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/header\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n printer << \"\\r\\nheader:\\r\\n\";\n for(auto &pr : parser.getValues()){\n printer << \"\\t\" << pr.first << \" : \" << pr.second << \"\\r\\n\";\n }\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/content\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n printer << \"\\r\\ncontent:\\r\\n\" << parser.Content();\n auto contentOut = printer << endl;\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/我们测算异步回复,当然你也可以同步回复\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n EventPoller::Instance().sync([invoker,contentOut](){\n HttpSession::KeyValue headerOut;\n\t\t\t\/\/你可以自定义header,如果跟默认header重名,则会覆盖之\n\t\t\t\/\/默认header有:Server,Connection,Date,Content-Type,Content-Length\n\t\t\t\/\/请勿覆盖Connection、Content-Length键\n\t\t\t\/\/键名覆盖时不区分大小写\n headerOut[\"TestHeader\"] = \"HeaderValue\";\n invoker(\"200 OK\",headerOut,contentOut);\n });\n });\n}, nullptr);\n\nint main(int argc,char *argv[]){\n\t\/\/设置退出信号处理函数\n\tsignal(SIGINT, [](int){EventPoller::Instance().shutdown();});\n\t\/\/设置日志\n\tLogger::Instance().add(std::make_shared<ConsoleChannel>(\"stdout\", LTrace));\n Logger::Instance().setWriter(std::make_shared<AsyncLogWriter>());\n\t\/\/加载配置文件,如果配置文件不存在就创建一个\n\tConfig::loadIniConfig();\n\n#ifdef ENABLE_OPENSSL\n\t\/\/请把证书\"test_httpApi.pem\"放置在本程序可执行程序同目录下\n\ttry{\n\t\t\/\/加载证书,证书包含公钥和私钥\n\t\tSSL_Initor::Instance().loadServerPem((exePath() + \".pem\").data());\n\t}catch(...){\n\t\tFatalL << \"请把证书:\" << (exeName() + \".pem\") << \"放置在本程序可执行程序同目录下:\" << exeDir() << endl;\n\t\treturn 0;\n\t}\n#endif \/\/ENABLE_OPENSSL\n\n\t\/\/开启http服务器\n\tTcpServer<HttpSession>::Ptr httpSrv(new TcpServer<HttpSession>());\n\thttpSrv->start(mINI::Instance()[Config::Http::kPort]);\/\/默认80\n\n#ifdef ENABLE_OPENSSL\n \/\/如果支持ssl,还可以开启https服务器\n\tTcpServer<HttpsSession>::Ptr httpsSrv(new TcpServer<HttpsSession>());\n\thttpsSrv->start(mINI::Instance()[Config::Http::kSSLPort]);\/\/默认443\n#endif \/\/ENABLE_OPENSSL\n\n\tInfoL << \"你可以在浏览器输入:http:\/\/127.0.0.1\/api\/my_api?key0=val0&key1=参数1\" << endl;\n\n\tEventPoller::Instance().runLoop();\n\n\tstatic onceToken s_token(nullptr,[]() {\n\t\t\/\/TcpServer用到了WorkThreadPool\n\t\tWorkThreadPool::Destory();\n\t\tEventPoller::Destory();\n\t\tLogger::Destory();\n\t});\n\treturn 0;\n}\n\n<commit_msg>修复编译不过的bug<commit_after>\/*\n * MIT License\n *\n * Copyright (c) 2016 xiongziliang <771730766@qq.com>\n *\n * This file is part of ZLMediaKit(https:\/\/github.com\/xiongziliang\/ZLMediaKit).\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n *\/\n\n#include <map>\n#include <signal.h>\n#include <iostream>\n#include \"Common\/config.h\"\n#include \"Http\/HttpSession.h\"\n#ifdef ENABLE_OPENSSL\n#include \"Util\/SSLBox.h\"\n#include \"Http\/HttpsSession.h\"\n#endif\/\/ENABLE_OPENSSL\n\n#include \"Util\/File.h\"\n#include \"Util\/logger.h\"\n#include \"Util\/onceToken.h\"\n#include \"Network\/TcpServer.h\"\n#include \"Poller\/EventPoller.h\"\n#include \"Thread\/WorkThreadPool.h\"\n#include \"Util\/NoticeCenter.h\"\n\nusing namespace std;\nusing namespace ZL::Util;\nusing namespace ZL::Http;\nusing namespace ZL::Thread;\nusing namespace ZL::Network;\n\nstatic onceToken s_token([](){\n NoticeCenter::Instance().addListener(nullptr,Config::Broadcast::kBroadcastHttpRequest,[](BroadcastHttpRequestArgs){\n \/\/const Parser &parser,HttpSession::HttpResponseInvoker &invoker,bool &consumed\n if(strstr(parser.Url().data(),\"\/api\/\") != parser.Url().data()){\n return;\n }\n \/\/url以\"\/api\/起始,说明是http api\"\n consumed = true;\/\/该http请求已被消费\n\n _StrPrinter printer;\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/method\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n printer << \"\\r\\nmethod:\\r\\n\\t\" << parser.Method();\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/url\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n printer << \"\\r\\nurl:\\r\\n\\t\" << parser.Url();\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/protocol\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n printer << \"\\r\\nprotocol:\\r\\n\\t\" << parser.Tail();\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/args\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n printer << \"\\r\\nargs:\\r\\n\";\n for(auto &pr : parser.getUrlArgs()){\n printer << \"\\t\" << pr.first << \" : \" << pr.second << \"\\r\\n\";\n }\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/header\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n printer << \"\\r\\nheader:\\r\\n\";\n for(auto &pr : parser.getValues()){\n printer << \"\\t\" << pr.first << \" : \" << pr.second << \"\\r\\n\";\n }\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/content\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n printer << \"\\r\\ncontent:\\r\\n\" << parser.Content();\n auto contentOut = printer << endl;\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/我们测算异步回复,当然你也可以同步回复\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n EventPoller::Instance().sync([invoker,contentOut](){\n HttpSession::KeyValue headerOut;\n\t\t\t\/\/你可以自定义header,如果跟默认header重名,则会覆盖之\n\t\t\t\/\/默认header有:Server,Connection,Date,Content-Type,Content-Length\n\t\t\t\/\/请勿覆盖Connection、Content-Length键\n\t\t\t\/\/键名覆盖时不区分大小写\n headerOut[\"TestHeader\"] = \"HeaderValue\";\n invoker(\"200 OK\",headerOut,contentOut);\n });\n });\n}, nullptr);\n\nint main(int argc,char *argv[]){\n\t\/\/设置退出信号处理函数\n\tsignal(SIGINT, [](int){EventPoller::Instance().shutdown();});\n\t\/\/设置日志\n\tLogger::Instance().add(std::make_shared<ConsoleChannel>(\"stdout\", LTrace));\n Logger::Instance().setWriter(std::make_shared<AsyncLogWriter>());\n\t\/\/加载配置文件,如果配置文件不存在就创建一个\n\tConfig::loadIniConfig();\n\n#ifdef ENABLE_OPENSSL\n\t\/\/请把证书\"test_httpApi.pem\"放置在本程序可执行程序同目录下\n\ttry{\n\t\t\/\/加载证书,证书包含公钥和私钥\n\t\tSSL_Initor::Instance().loadServerPem((exePath() + \".pem\").data());\n\t}catch(...){\n\t\tFatalL << \"请把证书:\" << (exeName() + \".pem\") << \"放置在本程序可执行程序同目录下:\" << exeDir() << endl;\n\t\treturn 0;\n\t}\n#endif \/\/ENABLE_OPENSSL\n\n\t\/\/开启http服务器\n\tTcpServer<HttpSession>::Ptr httpSrv(new TcpServer<HttpSession>());\n\thttpSrv->start(mINI::Instance()[Config::Http::kPort]);\/\/默认80\n\n#ifdef ENABLE_OPENSSL\n \/\/如果支持ssl,还可以开启https服务器\n\tTcpServer<HttpsSession>::Ptr httpsSrv(new TcpServer<HttpsSession>());\n\thttpsSrv->start(mINI::Instance()[Config::Http::kSSLPort]);\/\/默认443\n#endif \/\/ENABLE_OPENSSL\n\n\tInfoL << \"你可以在浏览器输入:http:\/\/127.0.0.1\/api\/my_api?key0=val0&key1=参数1\" << endl;\n\n\tEventPoller::Instance().runLoop();\n\n\tstatic onceToken s_token(nullptr,[]() {\n\t\t\/\/TcpServer用到了WorkThreadPool\n\t\tWorkThreadPool::Destory();\n\t\tEventPoller::Destory();\n\t\tLogger::Destory();\n\t});\n\treturn 0;\n}\n\n<|endoftext|>"} {"text":"<commit_before>#define BOOST_TEST_MODULE \"test_acceptor\"\n#ifdef UNITTEST_FRAMEWORK_LIBRARY_EXIST\n#include <boost\/test\/unit_test.hpp>\n#else\n#define BOOST_TEST_NO_LIB\n#include <boost\/test\/included\/unit_test.hpp>\n#endif\n#include <toml\/utility.hpp>\n#include <vector>\n#include <array>\n\nBOOST_AUTO_TEST_CASE(test_resize)\n{\n {\n typedef std::vector<int> resizable_type;\n typedef std::array<int,1> non_resizable_type;\n BOOST_CHECK(toml::detail::has_resize_method<resizable_type>::value);\n BOOST_CHECK(!toml::detail::has_resize_method<non_resizable_type>::value);\n }\n\n {\n bool thrown = false;\n std::vector<int> v;\n try\n {\n toml::resize(v, 10);\n }\n catch(std::exception& ex)\n {\n thrown = true;\n }\n BOOST_CHECK(!thrown);\n BOOST_CHECK_EQUAL(v.size(), 10);\n }\n\n {\n bool thrown = false;\n std::array<int, 15> a;\n try\n {\n toml::resize(a, 10);\n }\n catch(std::exception& ex)\n {\n thrown = true;\n }\n BOOST_CHECK(!thrown);\n BOOST_CHECK_EQUAL(a.size(), 15);\n }\n\n {\n bool thrown = false;\n std::array<int, 15> a;\n try\n {\n toml::resize(a, 20);\n }\n catch(std::exception& ex)\n {\n thrown = true;\n }\n BOOST_CHECK(thrown);\n }\n}\n<commit_msg>add test for concat_string<commit_after>#define BOOST_TEST_MODULE \"test_acceptor\"\n#ifdef UNITTEST_FRAMEWORK_LIBRARY_EXIST\n#include <boost\/test\/unit_test.hpp>\n#else\n#define BOOST_TEST_NO_LIB\n#include <boost\/test\/included\/unit_test.hpp>\n#endif\n#include <toml\/utility.hpp>\n#include <vector>\n#include <array>\n\nBOOST_AUTO_TEST_CASE(test_resize)\n{\n {\n typedef std::vector<int> resizable_type;\n typedef std::array<int,1> non_resizable_type;\n BOOST_CHECK(toml::detail::has_resize_method<resizable_type>::value);\n BOOST_CHECK(!toml::detail::has_resize_method<non_resizable_type>::value);\n }\n\n {\n bool thrown = false;\n std::vector<int> v;\n try\n {\n toml::resize(v, 10);\n }\n catch(std::exception& ex)\n {\n thrown = true;\n }\n BOOST_CHECK(!thrown);\n BOOST_CHECK_EQUAL(v.size(), 10u);\n }\n\n {\n bool thrown = false;\n std::array<int, 15> a;\n try\n {\n toml::resize(a, 10);\n }\n catch(std::exception& ex)\n {\n thrown = true;\n }\n BOOST_CHECK(!thrown);\n BOOST_CHECK_EQUAL(a.size(), 15u);\n }\n\n {\n bool thrown = false;\n std::array<int, 15> a;\n try\n {\n toml::resize(a, 20);\n }\n catch(std::exception& ex)\n {\n thrown = true;\n }\n BOOST_CHECK(thrown);\n }\n}\n\nBOOST_AUTO_TEST_CASE(test_concat_to_string)\n{\n const std::string cat = toml::concat_to_string(\"foo\", \"bar\", 42);\n BOOST_CHECK(cat == \"foobar42\");\n}\n<|endoftext|>"} {"text":"<commit_before>#include <gtest\/gtest.h>\n\n#include <putl\/state_ptr.hpp>\n\n#include <vector>\n#include <iostream>\n\nnamespace {\n\nusing namespace putl;\n\nstruct Foo{\n\tint a;\n};\n\nTEST(ConstexprLog2, Zero) {\n\tEXPECT_EQ(detail::log2(0), 0);\n}\n\nTEST(ConstexprLog2, One) {\n\tEXPECT_EQ(detail::log2(1), 0);\n}\n\nTEST(ConstexprLog2, PowersOfTwo) {\n\tEXPECT_EQ(detail::log2( 2), 1);\n\tEXPECT_EQ(detail::log2( 4), 2);\n\tEXPECT_EQ(detail::log2( 8), 3);\n\tEXPECT_EQ(detail::log2( 16), 4);\n\tEXPECT_EQ(detail::log2( 32), 5);\n\tEXPECT_EQ(detail::log2( 64), 6);\n\tEXPECT_EQ(detail::log2( 128), 7);\n\tEXPECT_EQ(detail::log2( 256), 8);\n\tEXPECT_EQ(detail::log2( 512), 9);\n\tEXPECT_EQ(detail::log2(1024), 10);\n}\n\nTEST(ConstexprLog2, Odd) {\n\tEXPECT_EQ(detail::log2(13), 3);\n\tEXPECT_EQ(detail::log2(17), 4);\n\tEXPECT_EQ(detail::log2(35), 5);\n}\n\nTEST(StatePointer, InitializedAsNull) {\n\tstate_ptr<Foo> foo{nullptr, 0};\n\tstate_ptr<Foo> bar{nullptr, 0};\n\tASSERT_EQ(foo, bar);\n\tASSERT_EQ(foo, nullptr);\n}\n\nTEST(StatePointer, GetStateNull) {\n\tFoo* foo = new Foo;\n\tstate_ptr<Foo> p{foo, 0};\n\tASSERT_EQ(p.get_ptr(), foo);\n\tASSERT_EQ(p.get_state(), 0ul);\n\tfree(foo);\n}\n\nTEST(StatePointer, SetState) {\n\tFoo foo;\n\tstate_ptr<Foo> p{&foo, 1};\n\tASSERT_EQ(p.get_ptr(), &foo);\n\tASSERT_EQ(p.get_state(), 1ul);\n\tp.set_state(2);\n\tASSERT_EQ(p.get_ptr(), &foo);\n\tASSERT_EQ(p.get_state(), 2ul);\n}\n\n} \/\/ namspace\n<commit_msg>added a new test for custom state type<commit_after>#include <gtest\/gtest.h>\n\n#include <putl\/state_ptr.hpp>\n\n#include <vector>\n#include <iostream>\n\nnamespace {\n\nusing namespace putl;\n\nstruct Foo{\n\tint a;\n};\n\nenum Bar {\n\tA = 0,\n\tB = 1,\n\tC = 2,\n\tD = 1337 \/\/ probably too large !\n};\n\nTEST(ConstexprLog2, Zero) {\n\tEXPECT_EQ(detail::log2(0), 0);\n}\n\nTEST(ConstexprLog2, One) {\n\tEXPECT_EQ(detail::log2(1), 0);\n}\n\nTEST(ConstexprLog2, PowersOfTwo) {\n\tEXPECT_EQ(detail::log2( 2), 1);\n\tEXPECT_EQ(detail::log2( 4), 2);\n\tEXPECT_EQ(detail::log2( 8), 3);\n\tEXPECT_EQ(detail::log2( 16), 4);\n\tEXPECT_EQ(detail::log2( 32), 5);\n\tEXPECT_EQ(detail::log2( 64), 6);\n\tEXPECT_EQ(detail::log2( 128), 7);\n\tEXPECT_EQ(detail::log2( 256), 8);\n\tEXPECT_EQ(detail::log2( 512), 9);\n\tEXPECT_EQ(detail::log2(1024), 10);\n}\n\nTEST(ConstexprLog2, Odd) {\n\tEXPECT_EQ(detail::log2(13), 3);\n\tEXPECT_EQ(detail::log2(17), 4);\n\tEXPECT_EQ(detail::log2(35), 5);\n}\n\nTEST(StatePointer, InitializedAsNull) {\n\tstate_ptr<Foo> foo{nullptr, 0};\n\tstate_ptr<Foo> bar{nullptr, 0};\n\tASSERT_EQ(foo, bar);\n\tASSERT_EQ(foo, nullptr);\n}\n\nTEST(StatePointer, GetStateNull) {\n\tFoo foo;\n\tstate_ptr<Foo> p{&foo, 0};\n\tASSERT_EQ(p.get_ptr(), &foo);\n\tASSERT_EQ(p.get_state(), 0ul);\n}\n\nTEST(StatePointer, SetState) {\n\tFoo foo;\n\tstate_ptr<Foo> p{&foo, 1};\n\tASSERT_EQ(p.get_ptr(), &foo);\n\tASSERT_EQ(p.get_state(), 1ul);\n\tp.set_state(2);\n\tASSERT_EQ(p.get_ptr(), &foo);\n\tASSERT_EQ(p.get_state(), 2ul);\n}\n\nTEST(StatePointer, EnumState) {\n\tFoo foo;\n\tstate_ptr<Foo, Bar> p{&foo, Bar::A};\n\tASSERT_EQ(p.get_ptr(), &foo);\n\tASSERT_EQ(p.get_state(), Bar::A);\n\tp.set_state(Bar::B);\n\tASSERT_EQ(p.get_ptr(), &foo);\n\tASSERT_EQ(p.get_state(), Bar::B);\n}\n\n} \/\/ namspace\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/\tTime.hpp\n\/\/\tA class around std::chrono that can be used for high precision timers for gameloops\n\/\/\n\n#pragma once\n\n#include <chrono>\n#include <cstdint> \/\/std::uint64_t\n\nusing namespace std;\nusing namespace chrono;\n\nclass Time\n{\npublic:\n\tinline uint64_t nanoTime()\n\t{\n\t\treturn duration_cast<nanoseconds>(high_resolution_clock::now().time_since_epoch()).count();\n\t}\n\n\tinline uint64_t sysTime()\n\t{\n\t\treturn duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();\n\t}\n};<commit_msg>Final Commit<commit_after>\/\/\n\/\/\tTime.hpp\n\/\/\tA wrapper around std::chrono that can be used for high precision timers for gameloops\n\/\/\n\n#pragma once\n\n#include <chrono>\n#include <cstdint> \/\/std::uint64_t\n\nusing namespace std;\nusing namespace chrono;\n\nstruct Time\n{\n\tinline uint64_t nanoTime()\n\t{\n\t\treturn duration_cast<nanoseconds>(high_resolution_clock::now().time_since_epoch()).count();\n\t}\n\n\tinline uint64_t sysTime()\n\t{\n\t\treturn duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();\n\t}\n} Time;<|endoftext|>"} {"text":"<commit_before>#include \"View.h\"\n\nusing namespace std;\n\nstatic View NullView = View(0,0);\nstatic Cluster<double> NullCluster = Cluster<double>(0);\n\nView::View(int NUM_COLS, double CRP_ALPHA) {\n num_cols = NUM_COLS;\n crp_alpha = CRP_ALPHA;\n num_vectors = 0;\n}\n\nvoid View::print() {\n std::set<Cluster<double>*>::iterator it = clusters.begin();\n for(; it!=clusters.end(); it++) {\n std::cout << **it << std::endl;\n }\n}\n\ndouble View::get_score() const {\n return score;\n}\n\ndouble View::get_num_vectors() const {\n return num_vectors;\n}\n\ndouble View::get_num_cols() const {\n return num_cols;\n}\n\nCluster<double>& View::get_new_cluster() {\n Cluster<double> *p_new_cluster = new Cluster<double>(num_cols);\n clusters.insert(p_new_cluster);\n return *p_new_cluster;\n}\n\nCluster<double>& View::get_cluster(int cluster_idx) {\n assert(cluster_idx <= clusters.size());\n bool not_new = cluster_idx < clusters.size();\n if(not_new) {\n std::set<Cluster<double>*>::iterator it = clusters.begin();\n std::advance(it, cluster_idx);\n return **it;\n } else {\n return get_new_cluster();\n }\n}\n\ndouble View::calc_cluster_vector_logp(std::vector<double> vd, Cluster<double> which_cluster) const {\n int cluster_count = which_cluster.get_count();\n double crp_logp_delta, data_logp_delta, score_delta;\n \/\/ NOTE: non-mutating, so presume vector is not in state\n \/\/ so use num_vectors, not num_vectors - 1\n \/\/ should try to cache counts in some way\n crp_logp_delta = numerics::calc_cluster_crp_logp(cluster_count,\n\t\t\t\t\t\t num_vectors,\n\t\t\t\t\t\t crp_alpha);\n data_logp_delta = which_cluster.calc_data_logp(vd);\n score_delta = crp_logp_delta + data_logp_delta;\n return score_delta;\n}\n\nstd::vector<double> View::calc_cluster_vector_logps(std::vector<double> vd) const {\n std::vector<double> logps;\n std::set<Cluster<double>*>::iterator it = clusters.begin();\n for(; it!=clusters.end(); it++) {\n logps.push_back(calc_cluster_vector_logp(vd, **it));\n }\n Cluster<double> empty_cluster(num_cols);\n logps.push_back(calc_cluster_vector_logp(vd, empty_cluster));\n return logps;\n}\n\ndouble View::draw_rand_u() {\n rng.next();\n}\n\nint View::draw_rand_i(int max) {\n return rng.nexti(max);\n}\n\nvoid View::transition_z(std::vector<double> vd, int row_idx) {\n std::vector<double> unorm_logps = calc_cluster_vector_logps(vd);\n double rand_u = draw_rand_u();\n int draw = numerics::draw_sample_unnormalized(unorm_logps, rand_u);\n Cluster<double> &which_cluster = get_cluster(draw);\n insert_row(vd, which_cluster, row_idx);\n}\n\nstd::vector<int> View::shuffle_row_indices() {\n std::vector<int> original_order;\n map<int, Cluster<double>*>::iterator it = cluster_lookup.begin();\n for(; it!=cluster_lookup.end(); it++) {\n original_order.push_back(it->first);\n }\n std::vector<int> shuffled_order;\n while(original_order.size()!=0) {\n int draw = draw_rand_i(original_order.size());\n int row_idx = original_order[draw];\n shuffled_order.push_back(row_idx);\n original_order.erase(original_order.begin() + draw);\n }\n return shuffled_order;\n}\n\nvoid View::transition_zs(map<int, vector<double> > row_data_map) {\n vector<int> shuffled_row_indices = shuffle_row_indices();\n std::cout << \"shuffled_row_indices: \" << shuffled_row_indices << endl;\n vector<int>::iterator it = shuffled_row_indices.begin();\n for(; it!=shuffled_row_indices.end(); it++) {\n int row_idx = *it;\n vector<double> vd = row_data_map[row_idx];\n cout << \"shuffling row: \" << row_idx << \" :: \" << vd << endl;\n remove_row(vd, row_idx);\n transition_z(vd, row_idx);\n }\n}\n\ndouble View::insert_row(std::vector<double> vd, Cluster<double>& which_cluster, int row_idx) {\n double score_delta = calc_cluster_vector_logp(vd, which_cluster);\n which_cluster.insert_row(vd, row_idx);\n cluster_lookup[row_idx] = &which_cluster;\n score += score_delta;\n num_vectors += 1;\n return score_delta;\n}\n\nvoid View::remove_if_empty(Cluster<double>& which_cluster) {\n if(which_cluster.get_count()==0) {\n clusters.erase(clusters.find(&which_cluster));\n delete &which_cluster;\n }\n}\n\ndouble View::remove_row(std::vector<double> vd, int row_idx) {\n Cluster<double> &which_cluster = *(cluster_lookup[row_idx]);\n cluster_lookup.erase(cluster_lookup.find(row_idx));\n which_cluster.remove_row(vd, row_idx);\n num_vectors -= 1;\n double score_delta = calc_cluster_vector_logp(vd, which_cluster);\n remove_if_empty(which_cluster);\n score -= score_delta;\n return score_delta;\n}\n\nstd::vector<int> View::get_cluster_counts() const {\n std::vector<int> counts;\n std::set<Cluster<double>*>::const_iterator it = clusters.begin();\n for(; it!=clusters.end(); it++) {\n int count = (**it).get_count();\n counts.push_back(count);\n }\n return counts;\n}\n\ndouble View::get_crp_score() const {\n std::vector<int> cluster_counts = get_cluster_counts();\n return numerics::calc_crp_alpha_conditional(cluster_counts, crp_alpha, -1, true);\n}\n<commit_msg>move remove_row operation to transition_z from transition_zs \"transition\" suggests its still in the model<commit_after>#include \"View.h\"\n\nusing namespace std;\n\nstatic View NullView = View(0,0);\nstatic Cluster<double> NullCluster = Cluster<double>(0);\n\nView::View(int NUM_COLS, double CRP_ALPHA) {\n num_cols = NUM_COLS;\n crp_alpha = CRP_ALPHA;\n num_vectors = 0;\n}\n\nvoid View::print() {\n std::set<Cluster<double>*>::iterator it = clusters.begin();\n for(; it!=clusters.end(); it++) {\n std::cout << **it << std::endl;\n }\n}\n\ndouble View::get_score() const {\n return score;\n}\n\ndouble View::get_num_vectors() const {\n return num_vectors;\n}\n\ndouble View::get_num_cols() const {\n return num_cols;\n}\n\nCluster<double>& View::get_new_cluster() {\n Cluster<double> *p_new_cluster = new Cluster<double>(num_cols);\n clusters.insert(p_new_cluster);\n return *p_new_cluster;\n}\n\nCluster<double>& View::get_cluster(int cluster_idx) {\n assert(cluster_idx <= clusters.size());\n bool not_new = cluster_idx < clusters.size();\n if(not_new) {\n std::set<Cluster<double>*>::iterator it = clusters.begin();\n std::advance(it, cluster_idx);\n return **it;\n } else {\n return get_new_cluster();\n }\n}\n\ndouble View::calc_cluster_vector_logp(std::vector<double> vd, Cluster<double> which_cluster) const {\n int cluster_count = which_cluster.get_count();\n double crp_logp_delta, data_logp_delta, score_delta;\n \/\/ NOTE: non-mutating, so presume vector is not in state\n \/\/ so use num_vectors, not num_vectors - 1\n \/\/ should try to cache counts in some way\n crp_logp_delta = numerics::calc_cluster_crp_logp(cluster_count,\n\t\t\t\t\t\t num_vectors,\n\t\t\t\t\t\t crp_alpha);\n data_logp_delta = which_cluster.calc_data_logp(vd);\n score_delta = crp_logp_delta + data_logp_delta;\n return score_delta;\n}\n\nstd::vector<double> View::calc_cluster_vector_logps(std::vector<double> vd) const {\n std::vector<double> logps;\n std::set<Cluster<double>*>::iterator it = clusters.begin();\n for(; it!=clusters.end(); it++) {\n logps.push_back(calc_cluster_vector_logp(vd, **it));\n }\n Cluster<double> empty_cluster(num_cols);\n logps.push_back(calc_cluster_vector_logp(vd, empty_cluster));\n return logps;\n}\n\ndouble View::draw_rand_u() {\n rng.next();\n}\n\nint View::draw_rand_i(int max) {\n return rng.nexti(max);\n}\n\nvoid View::transition_z(std::vector<double> vd, int row_idx) {\n remove_row(vd, row_idx);\n std::vector<double> unorm_logps = calc_cluster_vector_logps(vd);\n double rand_u = draw_rand_u();\n int draw = numerics::draw_sample_unnormalized(unorm_logps, rand_u);\n Cluster<double> &which_cluster = get_cluster(draw);\n insert_row(vd, which_cluster, row_idx);\n}\n\nstd::vector<int> View::shuffle_row_indices() {\n std::vector<int> original_order;\n map<int, Cluster<double>*>::iterator it = cluster_lookup.begin();\n for(; it!=cluster_lookup.end(); it++) {\n original_order.push_back(it->first);\n }\n std::vector<int> shuffled_order;\n while(original_order.size()!=0) {\n int draw = draw_rand_i(original_order.size());\n int row_idx = original_order[draw];\n shuffled_order.push_back(row_idx);\n original_order.erase(original_order.begin() + draw);\n }\n return shuffled_order;\n}\n\nvoid View::transition_zs(map<int, vector<double> > row_data_map) {\n vector<int> shuffled_row_indices = shuffle_row_indices();\n std::cout << \"shuffled_row_indices: \" << shuffled_row_indices << endl;\n vector<int>::iterator it = shuffled_row_indices.begin();\n for(; it!=shuffled_row_indices.end(); it++) {\n int row_idx = *it;\n vector<double> vd = row_data_map[row_idx];\n cout << \"shuffling row: \" << row_idx << \" :: \" << vd << endl;\n transition_z(vd, row_idx);\n }\n}\n\ndouble View::insert_row(std::vector<double> vd, Cluster<double>& which_cluster, int row_idx) {\n double score_delta = calc_cluster_vector_logp(vd, which_cluster);\n which_cluster.insert_row(vd, row_idx);\n cluster_lookup[row_idx] = &which_cluster;\n score += score_delta;\n num_vectors += 1;\n return score_delta;\n}\n\nvoid View::remove_if_empty(Cluster<double>& which_cluster) {\n if(which_cluster.get_count()==0) {\n clusters.erase(clusters.find(&which_cluster));\n delete &which_cluster;\n }\n}\n\ndouble View::remove_row(std::vector<double> vd, int row_idx) {\n Cluster<double> &which_cluster = *(cluster_lookup[row_idx]);\n cluster_lookup.erase(cluster_lookup.find(row_idx));\n which_cluster.remove_row(vd, row_idx);\n num_vectors -= 1;\n double score_delta = calc_cluster_vector_logp(vd, which_cluster);\n remove_if_empty(which_cluster);\n score -= score_delta;\n return score_delta;\n}\n\nstd::vector<int> View::get_cluster_counts() const {\n std::vector<int> counts;\n std::set<Cluster<double>*>::const_iterator it = clusters.begin();\n for(; it!=clusters.end(); it++) {\n int count = (**it).get_count();\n counts.push_back(count);\n }\n return counts;\n}\n\ndouble View::get_crp_score() const {\n std::vector<int> cluster_counts = get_cluster_counts();\n return numerics::calc_crp_alpha_conditional(cluster_counts, crp_alpha, -1, true);\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n Copyright (c) 2013, Randolph Voorhies, Shane Grant\n All rights reserved.\n\n Redistribution and use in source and binary forms, with or without\n modification, are permitted provided that the following conditions are met:\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in the\n documentation and\/or other materials provided with the distribution.\n * Neither the name of cereal nor the\n names of its contributors may be used to endorse or promote products\n derived from this software without specific prior written permission.\n\n THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n DISCLAIMED. IN NO EVENT SHALL RANDOLPH VOORHIES AND SHANE GRANT BE LIABLE FOR ANY\n DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*\/\n\n#include <cereal\/cereal.hpp>\n#include <cereal\/archives\/binary.hpp>\n#include <cereal\/archives\/json.hpp>\n\n#include <cereal\/types\/string.hpp>\n#include <cereal\/types\/utility.hpp>\n#include <cereal\/types\/memory.hpp>\n#include <cereal\/types\/complex.hpp>\n#include <cereal\/types\/base_class.hpp>\n#include <cereal\/types\/array.hpp>\n#include <cereal\/types\/vector.hpp>\n#include <cereal\/types\/map.hpp>\n\n#include <cereal\/external\/rapidjson\/filestream.h>\n\n#include <sstream>\n#include <fstream>\n#include <cassert>\n#include <complex>\n#include <iostream>\n#include <iomanip>\n#include <string>\n\n\/\/ ###################################\nstruct Test1\n{\n int a;\n\n private:\n friend class cereal::access;\n template<class Archive>\n void serialize(Archive & ar)\n {\n ar(CEREAL_NVP(a));\n }\n};\n\n\/\/ ###################################\nclass Test2\n{\n public:\n Test2() {}\n Test2( int x ) : a( x ) {}\n int a;\n\n private:\n friend class cereal::access;\n\n template<class Archive>\n void save(Archive & ar) const\n {\n ar(a);\n }\n\n template<class Archive>\n void load(Archive & ar)\n {\n ar(a);\n }\n};\n\n\/\/ ###################################\nstruct Test3\n{\n int a;\n};\n\ntemplate<class Archive>\nvoid serialize(Archive & ar, Test3 & t)\n{\n ar(CEREAL_NVP(t.a));\n}\n\nnamespace test4\n{\n \/\/ ###################################\n struct Test4\n {\n int a;\n };\n\n template<class Archive>\n void save(Archive & ar, Test4 const & t)\n {\n ar(CEREAL_NVP(t.a));\n }\n\n template<class Archive>\n void load(Archive & ar, Test4 & t)\n {\n ar(CEREAL_NVP(t.a));\n }\n}\n\nclass Private\n{\n public:\n Private() : a('z') {}\n\n private:\n char a;\n\n friend class cereal::access;\n\n template<class Archive>\n void serialize(Archive & ar)\n {\n ar(a);\n }\n};\n\nstruct Everything\n{\n int x;\n int y;\n Test1 t1;\n Test2 t2;\n Test3 t3;\n test4::Test4 t4;\n std::string s;\n\n template<class Archive>\n void serialize(Archive & ar)\n {\n ar(CEREAL_NVP(x));\n ar(CEREAL_NVP(y));\n ar(CEREAL_NVP(t1));\n ar(CEREAL_NVP(t2));\n ar(CEREAL_NVP(t3));\n ar(CEREAL_NVP(t4));\n ar(CEREAL_NVP(s));\n }\n\n bool operator==(Everything const & o)\n {\n return\n x == o.x &&\n y == o.y &&\n t1.a == o.t1.a &&\n t2.a == o.t2.a &&\n t3.a == o.t3.a &&\n t4.a == o.t4.a &&\n s == o.s;\n }\n};\n\n\nstruct SubFixture\n{\n SubFixture() : a( 3 ),\n b( 9999 ),\n c( 100.1f ),\n d( 2000.9 ),\n s( \"hello, world!\" )\n {}\n\n int a;\n uint64_t b;\n float c;\n double d;\n std::string s;\n\n template<class Archive>\n void serialize(Archive & ar)\n {\n ar( CEREAL_NVP(a),\n b,\n c,\n CEREAL_NVP(d),\n CEREAL_NVP(s) );\n }\n void change()\n {\n a = 4;\n b = 4;\n c = 4;\n d = 4;\n s = \"4\";\n }\n};\n\nstruct Fixture\n{\n SubFixture f1, f2, f3;\n int array[4];\n\n Fixture()\n {\n array[0] = 1;\n array[1] = 2;\n array[2] = 3;\n array[3] = 4;\n }\n\n template<class Archive>\n void save(Archive & ar) const\n {\n ar( f1,\n CEREAL_NVP(f2),\n f3 );\n ar.saveBinaryValue( array, sizeof(int)*4, \"cool array man\" );\n }\n\n template<class Archive>\n void load(Archive & ar)\n {\n ar( f1,\n CEREAL_NVP(f2),\n f3 );\n ar.loadBinaryValue( array, sizeof(int)*4 );\n }\n\n void change()\n {\n f1.change();\n f2.change();\n f3.change();\n }\n};\n\nstruct AAA\n{\n AAA() : one( 1 ), two( 2 ), three( { {1, 2, 3}, { 4, 5, 6 }, {} } ) {}\n int one, two;\n\n std::vector<std::vector<int>> three;\n\n template<class Archive>\n void serialize(Archive & ar)\n {\n ar( CEREAL_NVP(one), CEREAL_NVP(two) );\n \/\/ar( CEREAL_NVP(three) );\n }\n};\n\nclass Stuff\n{\n public:\n Stuff() {}\n\n void fillData()\n {\n std::vector<std::complex<float>> t1{ {0, -1.0f},\n { 0, -2.9932f },\n { 0, -3.5f } };\n std::vector<std::complex<float>> t2{ {1.0f, 0},\n { 2.2f, 0 },\n { 3.3f, 0 } };\n data[\"imaginary\"] = t1;\n data[\"real\"] = t2;\n }\n\n private:\n std::map<std::string, std::vector<std::complex<float>>> data;\n\n friend class cereal::access;\n\n template <class Archive>\n void serialize( Archive & ar )\n {\n ar( CEREAL_NVP(data) );\n }\n};\n\nstruct OOJson\n{\n OOJson() = default;\n OOJson( int aa, int bb, bool cc, double dd ) :\n a( aa ), b( bb ), c{ cc, dd }\n {\n d[0] = 0; d[1] = 1; d[2] = 2;\n }\n\n int a;\n int b;\n std::pair<bool, double> c;\n float d[3];\n\n template <class Archive>\n void serialize( Archive & ar )\n {\n ar( CEREAL_NVP(c) );\n ar( CEREAL_NVP(a) );\n ar( b );\n ar( CEREAL_NVP(d) );\n }\n};\n\n\/\/ ######################################################################\nint main()\n{\n std::cout << std::boolalpha << std::endl;\n\n {\n std::ofstream os(\"file.json\");\n cereal::JSONOutputArchive oar( os, 5 );\n\n \/\/auto f = std::make_shared<Fixture>();\n \/\/auto f2 = f;\n \/\/oar( f );\n \/\/oar( f2 );\n Stuff s; s.fillData();\n oar( cereal::make_nvp(\"best data ever\", s) );\n }\n\n {\n std::ifstream is(\"file.json\");\n std::string str((std::istreambuf_iterator<char>(is)), std::istreambuf_iterator<char>());\n std::cout << \"---------------------\" << std::endl << str << std::endl << \"---------------------\" << std::endl;\n }\n\n {\n cereal::JSONOutputArchive archive( std::cout );\n bool arr[] = {true, false};\n std::vector<int> vec = {1, 2, 3, 4, 5};\n archive( CEREAL_NVP(vec),\n arr );\n auto f = std::make_shared<Fixture>();\n auto f2 = f;\n archive( f );\n archive( f2 );\n\n enum Bla\n {\n x,\n y\n };\n\n archive( Bla::x );\n }\n\n \/\/ test out of order\n std::stringstream oos;\n {\n cereal::JSONOutputArchive ar(oos);\n cereal::JSONOutputArchive ar2(std::cout);\n\n ar( cereal::make_nvp( \"1\", 1 ),\n cereal::make_nvp( \"2\", 2 ),\n 3,\n 0, \/\/ unused\n cereal::make_nvp( \"4\", 4 ),\n cereal::make_nvp( \"5\", 5 ) );\n\n int x = 33;\n ar.saveBinaryValue( &x, sizeof(int), \"bla\" );\n\n ar2( cereal::make_nvp( \"1\", 1 ),\n cereal::make_nvp( \"2\", 2 ),\n 3,\n 0, \/\/ unused\n cereal::make_nvp( \"4\", 4 ),\n cereal::make_nvp( \"5\", 5 ) );\n ar2.saveBinaryValue( &x, sizeof(int), \"bla\" );\n\n OOJson oo( 1, 2, 3, 4 );\n ar( CEREAL_NVP(oo) );\n ar2( CEREAL_NVP(oo) );\n\n \/\/ boost stuff\n ar & cereal::make_nvp(\"usingop&\", oo ) & 5;\n ar << 5 << 4 << 3;\n\n ar2 & cereal::make_nvp(\"usingop&\", oo ) & 5;\n ar2 << 5 << 4 << 3;\n }\n\n {\n cereal::JSONInputArchive ar(oos);\n int i1, i2, i3, i4, i5, x;\n\n ar( i1 );\n ar( cereal::make_nvp( \"2\", i2 ), i3 );\n\n ar( cereal::make_nvp( \"4\", i4 ),\n i5 );\n\n ar.loadBinaryValue( &x, sizeof(int) );\n\n OOJson ii;\n ar( cereal::make_nvp(\"oo\", ii) );\n ar( cereal::make_nvp( \"2\", i2 ) );\n\n std::cout << i1 << \" \" << i2 << \" \" << i3 << \" \" << i4 << \" \" << i5 << std::endl;\n std::cout << x << std::endl;\n std::cout << ii.a << \" \" << ii.b << \" \" << ii.c.first << \" \" << ii.c.second << \" \";\n for( auto z : ii.d )\n std::cout << z << \" \";\n std::cout << std::endl;\n\n }\n\n\n\n\n \/\/{\n \/\/ std::ifstream is(\"file.json\");\n \/\/ cereal::JSONInputArchive iar( is );\n\n \/\/ std::shared_ptr<Fixture> f, f2;\n \/\/ iar( f, f2 );\n \/\/ assert( f->array[0] == 1 );\n \/\/ assert( f->array[1] == 2 );\n \/\/ assert( f->array[2] == 3 );\n \/\/ assert( f->array[3] == 4 );\n \/\/}\n\n return 0;\n}\n<commit_msg>testing boost ops<commit_after>\/*\n Copyright (c) 2013, Randolph Voorhies, Shane Grant\n All rights reserved.\n\n Redistribution and use in source and binary forms, with or without\n modification, are permitted provided that the following conditions are met:\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in the\n documentation and\/or other materials provided with the distribution.\n * Neither the name of cereal nor the\n names of its contributors may be used to endorse or promote products\n derived from this software without specific prior written permission.\n\n THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n DISCLAIMED. IN NO EVENT SHALL RANDOLPH VOORHIES AND SHANE GRANT BE LIABLE FOR ANY\n DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*\/\n\n#include <cereal\/cereal.hpp>\n#include <cereal\/archives\/binary.hpp>\n#include <cereal\/archives\/json.hpp>\n\n#include <cereal\/types\/string.hpp>\n#include <cereal\/types\/utility.hpp>\n#include <cereal\/types\/memory.hpp>\n#include <cereal\/types\/complex.hpp>\n#include <cereal\/types\/base_class.hpp>\n#include <cereal\/types\/array.hpp>\n#include <cereal\/types\/vector.hpp>\n#include <cereal\/types\/map.hpp>\n\n#include <cereal\/external\/rapidjson\/filestream.h>\n\n#include <sstream>\n#include <fstream>\n#include <cassert>\n#include <complex>\n#include <iostream>\n#include <iomanip>\n#include <string>\n\n\/\/ ###################################\nstruct Test1\n{\n int a;\n\n private:\n friend class cereal::access;\n template<class Archive>\n void serialize(Archive & ar)\n {\n ar(CEREAL_NVP(a));\n }\n};\n\n\/\/ ###################################\nclass Test2\n{\n public:\n Test2() {}\n Test2( int x ) : a( x ) {}\n int a;\n\n private:\n friend class cereal::access;\n\n template<class Archive>\n void save(Archive & ar) const\n {\n ar(a);\n }\n\n template<class Archive>\n void load(Archive & ar)\n {\n ar(a);\n }\n};\n\n\/\/ ###################################\nstruct Test3\n{\n int a;\n};\n\ntemplate<class Archive>\nvoid serialize(Archive & ar, Test3 & t)\n{\n ar(CEREAL_NVP(t.a));\n}\n\nnamespace test4\n{\n \/\/ ###################################\n struct Test4\n {\n int a;\n };\n\n template<class Archive>\n void save(Archive & ar, Test4 const & t)\n {\n ar(CEREAL_NVP(t.a));\n }\n\n template<class Archive>\n void load(Archive & ar, Test4 & t)\n {\n ar(CEREAL_NVP(t.a));\n }\n}\n\nclass Private\n{\n public:\n Private() : a('z') {}\n\n private:\n char a;\n\n friend class cereal::access;\n\n template<class Archive>\n void serialize(Archive & ar)\n {\n ar(a);\n }\n};\n\nstruct Everything\n{\n int x;\n int y;\n Test1 t1;\n Test2 t2;\n Test3 t3;\n test4::Test4 t4;\n std::string s;\n\n template<class Archive>\n void serialize(Archive & ar)\n {\n ar(CEREAL_NVP(x));\n ar(CEREAL_NVP(y));\n ar(CEREAL_NVP(t1));\n ar(CEREAL_NVP(t2));\n ar(CEREAL_NVP(t3));\n ar(CEREAL_NVP(t4));\n ar(CEREAL_NVP(s));\n }\n\n bool operator==(Everything const & o)\n {\n return\n x == o.x &&\n y == o.y &&\n t1.a == o.t1.a &&\n t2.a == o.t2.a &&\n t3.a == o.t3.a &&\n t4.a == o.t4.a &&\n s == o.s;\n }\n};\n\n\nstruct SubFixture\n{\n SubFixture() : a( 3 ),\n b( 9999 ),\n c( 100.1f ),\n d( 2000.9 ),\n s( \"hello, world!\" )\n {}\n\n int a;\n uint64_t b;\n float c;\n double d;\n std::string s;\n\n template<class Archive>\n void serialize(Archive & ar)\n {\n ar( CEREAL_NVP(a),\n b,\n c,\n CEREAL_NVP(d),\n CEREAL_NVP(s) );\n }\n void change()\n {\n a = 4;\n b = 4;\n c = 4;\n d = 4;\n s = \"4\";\n }\n};\n\nstruct Fixture\n{\n SubFixture f1, f2, f3;\n int array[4];\n\n Fixture()\n {\n array[0] = 1;\n array[1] = 2;\n array[2] = 3;\n array[3] = 4;\n }\n\n template<class Archive>\n void save(Archive & ar) const\n {\n ar( f1,\n CEREAL_NVP(f2),\n f3 );\n ar.saveBinaryValue( array, sizeof(int)*4, \"cool array man\" );\n }\n\n template<class Archive>\n void load(Archive & ar)\n {\n ar( f1,\n CEREAL_NVP(f2),\n f3 );\n ar.loadBinaryValue( array, sizeof(int)*4 );\n }\n\n void change()\n {\n f1.change();\n f2.change();\n f3.change();\n }\n};\n\nstruct AAA\n{\n AAA() : one( 1 ), two( 2 ), three( { {1, 2, 3}, { 4, 5, 6 }, {} } ) {}\n int one, two;\n\n std::vector<std::vector<int>> three;\n\n template<class Archive>\n void serialize(Archive & ar)\n {\n ar( CEREAL_NVP(one), CEREAL_NVP(two) );\n \/\/ar( CEREAL_NVP(three) );\n }\n};\n\nclass Stuff\n{\n public:\n Stuff() {}\n\n void fillData()\n {\n std::vector<std::complex<float>> t1{ {0, -1.0f},\n { 0, -2.9932f },\n { 0, -3.5f } };\n std::vector<std::complex<float>> t2{ {1.0f, 0},\n { 2.2f, 0 },\n { 3.3f, 0 } };\n data[\"imaginary\"] = t1;\n data[\"real\"] = t2;\n }\n\n private:\n std::map<std::string, std::vector<std::complex<float>>> data;\n\n friend class cereal::access;\n\n template <class Archive>\n void serialize( Archive & ar )\n {\n ar( CEREAL_NVP(data) );\n }\n};\n\nstruct OOJson\n{\n OOJson() = default;\n OOJson( int aa, int bb, bool cc, double dd ) :\n a( aa ), b( bb ), c{ cc, dd }\n {\n d[0] = 0; d[1] = 1; d[2] = 2;\n }\n\n int a;\n int b;\n std::pair<bool, double> c;\n float d[3];\n\n template <class Archive>\n void serialize( Archive & ar )\n {\n ar( CEREAL_NVP(c) );\n ar( CEREAL_NVP(a) );\n ar( b );\n ar( CEREAL_NVP(d) );\n }\n};\n\n\/\/ ######################################################################\nint main()\n{\n std::cout << std::boolalpha << std::endl;\n\n {\n std::ofstream os(\"file.json\");\n cereal::JSONOutputArchive oar( os, 5 );\n\n \/\/auto f = std::make_shared<Fixture>();\n \/\/auto f2 = f;\n \/\/oar( f );\n \/\/oar( f2 );\n Stuff s; s.fillData();\n oar( cereal::make_nvp(\"best data ever\", s) );\n }\n\n {\n std::ifstream is(\"file.json\");\n std::string str((std::istreambuf_iterator<char>(is)), std::istreambuf_iterator<char>());\n std::cout << \"---------------------\" << std::endl << str << std::endl << \"---------------------\" << std::endl;\n }\n\n {\n cereal::JSONOutputArchive archive( std::cout );\n bool arr[] = {true, false};\n std::vector<int> vec = {1, 2, 3, 4, 5};\n archive( CEREAL_NVP(vec),\n arr );\n auto f = std::make_shared<Fixture>();\n auto f2 = f;\n archive( f );\n archive( f2 );\n\n enum Bla\n {\n x,\n y\n };\n\n archive( Bla::x );\n }\n\n \/\/ test out of order\n std::stringstream oos;\n {\n cereal::JSONOutputArchive ar(oos);\n cereal::JSONOutputArchive ar2(std::cout);\n\n ar( cereal::make_nvp( \"1\", 1 ),\n cereal::make_nvp( \"2\", 2 ),\n 3,\n 0, \/\/ unused\n cereal::make_nvp( \"4\", 4 ),\n cereal::make_nvp( \"5\", 5 ) );\n\n int x = 33;\n ar.saveBinaryValue( &x, sizeof(int), \"bla\" );\n\n ar2( cereal::make_nvp( \"1\", 1 ),\n cereal::make_nvp( \"2\", 2 ),\n 3,\n 0, \/\/ unused\n cereal::make_nvp( \"4\", 4 ),\n cereal::make_nvp( \"5\", 5 ) );\n ar2.saveBinaryValue( &x, sizeof(int), \"bla\" );\n\n OOJson oo( 1, 2, 3, 4 );\n ar( CEREAL_NVP(oo) );\n ar2( CEREAL_NVP(oo) );\n\n \/\/ boost stuff\n ar & cereal::make_nvp(\"usingop&\", oo ) & 6;\n ar << 5 << 4 << 3;\n\n ar2 & cereal::make_nvp(\"usingop&\", oo ) & 6;\n ar2 << 5 << 4 << 3;\n }\n\n {\n cereal::JSONInputArchive ar(oos);\n int i1, i2, i3, i4, i5, x;\n\n ar( i1 );\n ar( cereal::make_nvp( \"2\", i2 ), i3 );\n\n ar( cereal::make_nvp( \"4\", i4 ),\n i5 );\n\n ar.loadBinaryValue( &x, sizeof(int) );\n\n OOJson ii;\n ar( cereal::make_nvp(\"oo\", ii) );\n ar( cereal::make_nvp( \"2\", i2 ) );\n\n std::cout << i1 << \" \" << i2 << \" \" << i3 << \" \" << i4 << \" \" << i5 << std::endl;\n std::cout << x << std::endl;\n std::cout << ii.a << \" \" << ii.b << \" \" << ii.c.first << \" \" << ii.c.second << \" \";\n for( auto z : ii.d )\n std::cout << z << \" \";\n std::cout << std::endl;\n\n OOJson oo;\n ar >> cereal::make_nvp(\"usingop&\", oo );\n std::cout << oo.a << \" \" << oo.b << \" \" << oo.c.first << \" \" << oo.c.second << \" \";\n for( auto z : oo.d )\n std::cout << z << \" \";\n\n int aa, a, b, c;\n ar & aa & a & b & c;\n std::cout << aa << \" \" << a << \" \" << b << \" \" << c << std::endl;\n\n }\n\n\n\n\n \/\/{\n \/\/ std::ifstream is(\"file.json\");\n \/\/ cereal::JSONInputArchive iar( is );\n\n \/\/ std::shared_ptr<Fixture> f, f2;\n \/\/ iar( f, f2 );\n \/\/ assert( f->array[0] == 1 );\n \/\/ assert( f->array[1] == 2 );\n \/\/ assert( f->array[2] == 3 );\n \/\/ assert( f->array[3] == 4 );\n \/\/}\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>#include <opencv2\/highgui\/highgui.hpp>\n#include <opencv2\/imgproc\/imgproc.hpp>\n\n#include <iostream>\n#include <cstring>\n\nusing namespace cv;\nusing namespace std;\n\nMat calculate_energy(Mat I){\n Mat Ix,Iy;\n\n Sobel(I,Ix,CV_32F,1,0);\n convertScaleAbs(Ix,Ix);\n\n Sobel(I,Iy,CV_32F,0,1);\n convertScaleAbs(Iy,Iy);\n\n Mat energy;\n addWeighted(Ix, 0.5, Iy, 0.5, 0, energy, CV_8U);\n\n return energy;\n}\n\nMat calculate_energy2(Mat I){\n int Y = I.rows,X = I.cols;\n Mat energy = Mat(Y, X, CV_32S);\n\n for(int x = 0;x < X;++x){\n for(int y = 0;y < Y;++y){\n int val = 0;\n\n if(x > 0 && x + 1 < X)\n val += abs((int)I.at<uchar>(y,x + 1) - (int)I.at<uchar>(y,x - 1));\n else if(x > 0)\n val += 2 * abs((int)I.at<uchar>(y,x) - (int)I.at<uchar>(y,x - 1));\n else\n val += 2 * abs((int)I.at<uchar>(y,x + 1) - (int)I.at<uchar>(y,x));\n\n if(y > 0 && y + 1 < Y)\n val += abs((int)I.at<uchar>(y + 1,x) - (int)I.at<uchar>(y - 1,x));\n else if(y > 0)\n val += 2 * abs((int)I.at<uchar>(y,x) - (int)I.at<uchar>(y - 1,x));\n else\n val += 2 * abs((int)I.at<uchar>(y + 1,x) - (int)I.at<uchar>(y,x));\n\n energy.at<int>(y,x) = val;\n }\n }\n\n return energy;\n}\n\nint query(int bit[], int idx){\n int ret = 0;\n\n for(int x = idx;x > 0;x -= x & -x)\n ret += bit[x];\n\n return ret;\n}\n\nvoid update(int bit[], int maxX, int idx){\n for(int x = idx;x < maxX;x += x & -x)\n ++bit[x];\n}\n\nint main(){\n Mat_<Vec3b> I = imread(\"..\/bench.jpg\");\n\n imshow(\"seam-carving\",I);\n waitKey(0);\n\n int Y = I.rows,X = I.cols;\n int Y0 = Y,X0 = X;\n\n Mat gray,energy;\n \n \/\/cvtColor(I,gray,CV_BGR2GRAY);\n \/\/energy = calculate_energy(gray);\n \/\/imshow(\"seam-carving\",energy);\n \/\/waitKey(0);\n\n unsigned int dpH[X][Y],dpV[X][Y];\n int dirH[X][Y],dirV[X][Y];\n vector<int> posH[X],posV[Y];\n int bitH[Y + 1],bitV[X + 1];\n\n Mat seams = I.clone();\n\n \/\/ Horizontal seams\n\n for(int it = 0;it < 50;++it){\n cvtColor(I,gray,CV_BGR2GRAY);\n energy = calculate_energy2(gray);\n\n for(int y = 0;y < Y;++y)\n dpH[0][y] = energy.at<uchar>(y,0);\n\n for(int x = 1;x < X;++x){\n for(int y = 0;y < Y;++y){\n uint val = energy.at<uchar>(y,x);\n dpH[x][y] = -1;\n\n if(y > 0 && (dpH[x][y] == -1 || val + dpH[x - 1][y - 1] < dpH[x][y])){\n dpH[x][y] = val + dpH[x - 1][y - 1];\n dirH[x][y] = -1;\n }\n\n if(dpH[x][y] == -1 || val + dpH[x - 1][y] < dpH[x][y]){\n dpH[x][y] = val + dpH[x - 1][y];\n dirH[x][y] = 0;\n }\n\n if(y + 1 < Y && (dpH[x][y] == -1 || val + dpH[x - 1][y + 1] < dpH[x][y])){\n dpH[x][y] = val + dpH[x - 1][y + 1];\n dirH[x][y] = 1;\n }\n }\n }\n\n unsigned int bestH = dpH[X - 1][0];\n int cury = 0;\n\n for(int y = 0;y < Y;++y){\n if(dpH[X - 1][y] < bestH){\n bestH = dpH[X - 1][y];\n cury = y;\n }\n }\n\n \/\/cout << \"cury = \" << cury << endl;\n \/\/cout << \"bestH = \" << bestH << endl;\n\n Mat_<Vec3b> tmp(Y - 1,X);\n\n for(int x = X - 1,cont = 0;x >= 0;--x,++cont){\n posH[x].push_back(cury);\n\n for(int i = 0;i < Y;++i){\n if(i < cury) tmp.at<Vec3b>(i,x) = I.at<Vec3b>(i,x);\n else if(i > cury) tmp.at<Vec3b>(i - 1,x) = I.at<Vec3b>(i,x);\n }\n\n if(x > 0)\n cury = cury + dirH[x][cury];\n }\n\n I = tmp;\n --Y;\n }\n\n \/\/imwrite(\"seam_horizontal2.jpg\", I);\n\n for(int x = 0;x < X;++x){\n memset(bitH,0,sizeof bitH);\n\n for(int i = 0;i < posH[x].size();++i){\n int y = posH[x][i];\n update(bitH,Y0 + 1,y + 1);\n y += query(bitH,y + 1) - 1;\n\n seams.at<Vec3b>(y,x) = Vec3b(0,0,255);\n }\n }\n\n \/\/ Vertical seams\n\n for(int it = 0;it < 100;++it){\n cvtColor(I,gray,CV_BGR2GRAY);\n energy = calculate_energy2(gray);\n\n for(int x = 0;x < X;++x)\n dpV[x][0] = energy.at<uint>(0,x);\n\n for(int y = 1;y < Y;++y){\n for(int x = 0;x < X;++x){\n uint val = energy.at<uint>(y,x);\n dpV[x][y] = -1;\n\n if(x > 0 && (dpV[x][y] == -1 || val + dpV[x - 1][y - 1] < dpV[x][y])){\n dpV[x][y] = val + dpV[x - 1][y - 1];\n dirV[x][y] = -1;\n }\n\n if(dpV[x][y] == -1 || val + dpV[x][y - 1] < dpV[x][y]){\n dpV[x][y] = val + dpV[x][y - 1];\n dirV[x][y] = 0;\n }\n\n if(x + 1 < X && (dpV[x][y] == -1 || val + dpV[x + 1][y - 1] < dpV[x][y])){\n dpV[x][y] = val + dpV[x + 1][y - 1];\n dirV[x][y] = 1;\n }\n }\n }\n\n unsigned int bestV = dpV[0][Y - 1];\n int curx = 0;\n\n for(int x = 0;x < X;++x){\n if(dpV[x][Y - 1] < bestV){\n bestV = dpV[x][Y - 1];\n curx = x;\n }\n }\n\n Mat_<Vec3b> tmp(Y,X - 1);\n\n for(int y = Y - 1;y >= 0;--y){\n posV[y].push_back(curx);\n\n for(int i = 0;i < X;++i){\n if(i < curx) tmp.at<Vec3b>(y,i) = I.at<Vec3b>(y,i);\n else if(i > curx) tmp.at<Vec3b>(y,i - 1) = I.at<Vec3b>(y,i);\n }\n\n if(y > 0)\n curx = curx + dirV[curx][y];\n }\n\n I = tmp;\n --X;\n }\n\n imshow(\"seams\",seams);\n imshow(\"seam-carving-out\",I);\n waitKey(0);\n\n return 0;\n}<commit_msg>show horizontal and vertical seams<commit_after>#include <opencv2\/highgui\/highgui.hpp>\n#include <opencv2\/imgproc\/imgproc.hpp>\n\n#include <iostream>\n#include <cstring>\n\nusing namespace cv;\nusing namespace std;\n\n\/*Mat calculate_energy(Mat I){\n Mat Ix,Iy;\n\n Sobel(I,Ix,CV_32F,1,0);\n convertScaleAbs(Ix,Ix);\n\n Sobel(I,Iy,CV_32F,0,1);\n convertScaleAbs(Iy,Iy);\n\n Mat energy;\n addWeighted(Ix, 0.5, Iy, 0.5, 0, energy, CV_8U);\n\n return energy;\n}*\/\n\nMat calculate_energy(Mat I){\n int Y = I.rows,X = I.cols;\n Mat energy = Mat(Y, X, CV_32S);\n\n for(int x = 0;x < X;++x){\n for(int y = 0;y < Y;++y){\n int val = 0;\n\n if(x > 0 && x + 1 < X)\n val += abs((int)I.at<uchar>(y,x + 1) - (int)I.at<uchar>(y,x - 1));\n else if(x > 0)\n val += 2 * abs((int)I.at<uchar>(y,x) - (int)I.at<uchar>(y,x - 1));\n else\n val += 2 * abs((int)I.at<uchar>(y,x + 1) - (int)I.at<uchar>(y,x));\n\n if(y > 0 && y + 1 < Y)\n val += abs((int)I.at<uchar>(y + 1,x) - (int)I.at<uchar>(y - 1,x));\n else if(y > 0)\n val += 2 * abs((int)I.at<uchar>(y,x) - (int)I.at<uchar>(y - 1,x));\n else\n val += 2 * abs((int)I.at<uchar>(y + 1,x) - (int)I.at<uchar>(y,x));\n\n energy.at<int>(y,x) = val;\n }\n }\n\n return energy;\n}\n\nint main(){\n Mat_<Vec3b> I = imread(\"..\/bench.jpg\");\n\n imshow(\"seam-carving\",I);\n waitKey(0);\n\n int Y = I.rows,X = I.cols;\n int Y0 = Y,X0 = X;\n\n Mat gray,energy;\n \n \/\/cvtColor(I,gray,CV_BGR2GRAY);\n \/\/energy = calculate_energy(gray);\n \/\/imshow(\"seam-carving\",energy);\n \/\/waitKey(0);\n\n unsigned int dpH[X][Y],dpV[X][Y];\n int dirH[X][Y],dirV[X][Y];\n vector<int> posH[X],posV[Y];\n pair<int, int> pos[X][Y];\n\n for(int i = 0;i < X;++i)\n for(int j = 0;j < Y;++j)\n pos[i][j] = make_pair(i,j);\n\n Mat seams = I.clone();\n\n \/\/ Horizontal seams\n\n for(int it = 0;it < 50;++it){\n cvtColor(I,gray,CV_BGR2GRAY);\n energy = calculate_energy(gray);\n\n for(int y = 0;y < Y;++y)\n dpH[0][y] = energy.at<int>(y,0);\n\n for(int x = 1;x < X;++x){\n for(int y = 0;y < Y;++y){\n uint val = energy.at<int>(y,x);\n dpH[x][y] = -1;\n\n if(y > 0 && (dpH[x][y] == -1 || val + dpH[x - 1][y - 1] < dpH[x][y])){\n dpH[x][y] = val + dpH[x - 1][y - 1];\n dirH[x][y] = -1;\n }\n\n if(dpH[x][y] == -1 || val + dpH[x - 1][y] < dpH[x][y]){\n dpH[x][y] = val + dpH[x - 1][y];\n dirH[x][y] = 0;\n }\n\n if(y + 1 < Y && (dpH[x][y] == -1 || val + dpH[x - 1][y + 1] < dpH[x][y])){\n dpH[x][y] = val + dpH[x - 1][y + 1];\n dirH[x][y] = 1;\n }\n }\n }\n\n unsigned int bestH = dpH[X - 1][0];\n int cury = 0;\n\n for(int y = 0;y < Y;++y){\n if(dpH[X - 1][y] < bestH){\n bestH = dpH[X - 1][y];\n cury = y;\n }\n }\n\n Mat_<Vec3b> tmp(Y - 1,X);\n\n for(int x = X - 1,cont = 0;x >= 0;--x,++cont){\n posH[x].push_back(cury);\n\n for(int i = 0;i < Y;++i){\n if(i < cury){\n tmp.at<Vec3b>(i,x) = I.at<Vec3b>(i,x);\n }else if(i > cury){\n tmp.at<Vec3b>(i - 1,x) = I.at<Vec3b>(i,x);\n pos[x][i - 1] = pos[x][i];\n }else{\n seams.at<Vec3b>(pos[x][i].second, pos[x][i].first) = Vec3b(0,0,255);\n }\n }\n\n if(x > 0)\n cury = cury + dirH[x][cury];\n }\n\n I = tmp;\n --Y;\n }\n\n \/\/ Vertical seams\n\n for(int it = 0;it < 100;++it){\n cvtColor(I,gray,CV_BGR2GRAY);\n energy = calculate_energy(gray);\n\n for(int x = 0;x < X;++x)\n dpV[x][0] = energy.at<int>(0,x);\n\n for(int y = 1;y < Y;++y){\n for(int x = 0;x < X;++x){\n int val = energy.at<int>(y,x);\n dpV[x][y] = -1;\n\n if(x > 0 && (dpV[x][y] == -1 || val + dpV[x - 1][y - 1] < dpV[x][y])){\n dpV[x][y] = val + dpV[x - 1][y - 1];\n dirV[x][y] = -1;\n }\n\n if(dpV[x][y] == -1 || val + dpV[x][y - 1] < dpV[x][y]){\n dpV[x][y] = val + dpV[x][y - 1];\n dirV[x][y] = 0;\n }\n\n if(x + 1 < X && (dpV[x][y] == -1 || val + dpV[x + 1][y - 1] < dpV[x][y])){\n dpV[x][y] = val + dpV[x + 1][y - 1];\n dirV[x][y] = 1;\n }\n }\n }\n\n unsigned int bestV = dpV[0][Y - 1];\n int curx = 0;\n\n for(int x = 0;x < X;++x){\n if(dpV[x][Y - 1] < bestV){\n bestV = dpV[x][Y - 1];\n curx = x;\n }\n }\n\n Mat_<Vec3b> tmp(Y,X - 1);\n\n for(int y = Y - 1;y >= 0;--y){\n posV[y].push_back(curx);\n\n for(int i = 0;i < X;++i){\n if(i < curx){\n tmp.at<Vec3b>(y,i) = I.at<Vec3b>(y,i);\n }else if(i > curx){\n tmp.at<Vec3b>(y,i - 1) = I.at<Vec3b>(y,i);\n pos[i - 1][y] = pos[i][y];\n }else{\n seams.at<Vec3b>(pos[i][y].second, pos[i][y].first) = Vec3b(0,0,255);\n }\n }\n\n if(y > 0)\n curx = curx + dirV[curx][y];\n }\n\n I = tmp;\n --X;\n }\n\n imshow(\"seams\",seams);\n \/\/imwrite(\"seams.jpg\", seams);\n imshow(\"seam-carving-out\",I);\n \/\/imwrite(\"seam-carving-out-2.jpg\",I);\n waitKey(0);\n\n return 0;\n}<|endoftext|>"} {"text":"<commit_before>\/*===================================================================\n\nThe Medical Imaging Interaction Toolkit (MITK)\n\nCopyright (c) German Cancer Research Center,\nDivision of Medical and Biological Informatics.\nAll rights reserved.\n\nThis software is distributed WITHOUT ANY WARRANTY; without\neven the implied warranty of MERCHANTABILITY or FITNESS FOR\nA PARTICULAR PURPOSE.\n\nSee LICENSE.txt or http:\/\/www.mitk.org for details.\n\n===================================================================*\/\n#ifndef _mitkExtendedLabelStatisticsImageFilter_hxx\n#define _mitkExtendedLabelStatisticsImageFilter_hxx\n\n#include \"mitkExtendedLabelStatisticsImageFilter.h\"\n\n#include \"itkImageRegionIterator.h\"\n#include \"itkImageRegionConstIteratorWithIndex.h\"\n#include \"itkProgressReporter.h\"\n\n#include \"itkImageFileWriter.h\"\n\nnamespace itk\n{\n template< class TInputImage , class TLabelImage>\n ExtendedLabelStatisticsImageFilter< TInputImage, TLabelImage >\n ::ExtendedLabelStatisticsImageFilter()\n : LabelStatisticsImageFilter()\n {\n m_LabelStatisticsCoefficients;\n }\n\n\n template< class TInputImage, class TLabelImage >\n typename ExtendedLabelStatisticsImageFilter< TInputImage, TLabelImage >::RealType\n ExtendedLabelStatisticsImageFilter< TInputImage, TLabelImage >\n ::GetKurtosis(LabelPixelType label) const\n {\n CoefficientsMapConstIterator mapIt;\n\n mapIt = m_LabelStatisticsCoefficients.find(label);\n if ( mapIt == m_LabelStatisticsCoefficients.end() )\n {\n \/\/ label does not exist, return a default value\n return NumericTraits< PixelType >::Zero;\n }\n else\n {\n return ( *mapIt ).second.m_Kurtosis;\n }\n }\n\n\n template< class TInputImage, class TLabelImage >\n typename ExtendedLabelStatisticsImageFilter< TInputImage, TLabelImage >::RealType\n ExtendedLabelStatisticsImageFilter< TInputImage, TLabelImage >\n ::GetSkewness(LabelPixelType label) const\n {\n CoefficientsMapConstIterator mapIt;\n\n mapIt = m_LabelStatisticsCoefficients.find(label);\n if ( mapIt == m_LabelStatisticsCoefficients.end() )\n {\n \/\/ label does not exist, return a default value\n return NumericTraits< PixelType >::Zero;\n }\n else\n {\n return ( *mapIt ).second.m_Skewness;\n }\n }\n\n\n template< class TInputImage, class TLabelImage >\n void\n ExtendedLabelStatisticsImageFilter< TInputImage, TLabelImage >::\n ComputeTheSkewnessAndCurtosis()\n {\n MapIterator mapIt;\n TLabelImage::RegionType Subregion;\n\n double baseOfSkewnessAndCurtosis;\n double Kurtosis = 0.0;\n double Skewness = 0.0;\n\n std::list< LabelPixelType> relevantLabels;\n bool maskNonEmpty = false;\n LabelPixelType i;\n for ( i = 1; i < 100; ++i )\n {\n if ( this->HasLabel( i ) )\n {\n relevantLabels.push_back( i );\n maskNonEmpty = true;\n m_LabelStatisticsCoefficients.insert( std::make_pair(i, CoefficientsClass()) );\n }\n }\n\n if ( maskNonEmpty )\n {\n std::list< LabelPixelType >::iterator it;\n for ( it = relevantLabels.begin(), i = 0;\n it != relevantLabels.end();\n ++it, ++i )\n {\n double Sigma = GetSigma( *it );\n double Mean = GetMean( *it );\n Subregion = Superclass::GetRegion(*it);\n\n ImageRegionConstIteratorWithIndex< TInputImage > it1 (this->GetInput(),\n Subregion);\n ImageRegionConstIterator< TLabelImage > labelIt (this->GetLabelInput(),\n Subregion);\n\n for (it1.GoToBegin(); !it1.IsAtEnd(); ++it1, ++labelIt)\n {\n if (labelIt.Get() == *it)\n {\n baseOfSkewnessAndCurtosis = ( it1.Get() -Mean ) \/ Sigma ;\n Kurtosis += baseOfSkewnessAndCurtosis*baseOfSkewnessAndCurtosis*baseOfSkewnessAndCurtosis*baseOfSkewnessAndCurtosis;\n Skewness += baseOfSkewnessAndCurtosis*baseOfSkewnessAndCurtosis*baseOfSkewnessAndCurtosis;\n }\n }\n\n m_LabelStatisticsCoefficients[*it].m_Skewness = double(Skewness\/GetCount(*it));\n m_LabelStatisticsCoefficients[*it].m_Kurtosis = double(Kurtosis\/GetCount(*it));\n }\n }\n }\n\n\n template< class TInputImage, class TLabelImage >\n void ExtendedLabelStatisticsImageFilter< TInputImage, TLabelImage >::\n AfterThreadedGenerateData()\n {\n Superclass::AfterThreadedGenerateData();\n\n ComputeTheSkewnessAndCurtosis();\n }\n\n} \/\/ end namespace itk\n\n#endif<commit_msg>removed unused includes<commit_after>\/*===================================================================\n\nThe Medical Imaging Interaction Toolkit (MITK)\n\nCopyright (c) German Cancer Research Center,\nDivision of Medical and Biological Informatics.\nAll rights reserved.\n\nThis software is distributed WITHOUT ANY WARRANTY; without\neven the implied warranty of MERCHANTABILITY or FITNESS FOR\nA PARTICULAR PURPOSE.\n\nSee LICENSE.txt or http:\/\/www.mitk.org for details.\n\n===================================================================*\/\n#ifndef _mitkExtendedLabelStatisticsImageFilter_hxx\n#define _mitkExtendedLabelStatisticsImageFilter_hxx\n\n#include \"mitkExtendedLabelStatisticsImageFilter.h\"\n\n#include \"itkImageRegionConstIteratorWithIndex.h\"\n\nnamespace itk\n{\n template< class TInputImage , class TLabelImage>\n ExtendedLabelStatisticsImageFilter< TInputImage, TLabelImage >\n ::ExtendedLabelStatisticsImageFilter()\n : LabelStatisticsImageFilter()\n {\n m_LabelStatisticsCoefficients;\n }\n\n\n template< class TInputImage, class TLabelImage >\n typename ExtendedLabelStatisticsImageFilter< TInputImage, TLabelImage >::RealType\n ExtendedLabelStatisticsImageFilter< TInputImage, TLabelImage >\n ::GetKurtosis(LabelPixelType label) const\n {\n CoefficientsMapConstIterator mapIt;\n\n mapIt = m_LabelStatisticsCoefficients.find(label);\n if ( mapIt == m_LabelStatisticsCoefficients.end() )\n {\n \/\/ label does not exist, return a default value\n return NumericTraits< PixelType >::Zero;\n }\n else\n {\n return ( *mapIt ).second.m_Kurtosis;\n }\n }\n\n\n template< class TInputImage, class TLabelImage >\n typename ExtendedLabelStatisticsImageFilter< TInputImage, TLabelImage >::RealType\n ExtendedLabelStatisticsImageFilter< TInputImage, TLabelImage >\n ::GetSkewness(LabelPixelType label) const\n {\n CoefficientsMapConstIterator mapIt;\n\n mapIt = m_LabelStatisticsCoefficients.find(label);\n if ( mapIt == m_LabelStatisticsCoefficients.end() )\n {\n \/\/ label does not exist, return a default value\n return NumericTraits< PixelType >::Zero;\n }\n else\n {\n return ( *mapIt ).second.m_Skewness;\n }\n }\n\n\n template< class TInputImage, class TLabelImage >\n void\n ExtendedLabelStatisticsImageFilter< TInputImage, TLabelImage >::\n ComputeTheSkewnessAndCurtosis()\n {\n MapIterator mapIt;\n TLabelImage::RegionType Subregion;\n\n double baseOfSkewnessAndCurtosis;\n double Kurtosis = 0.0;\n double Skewness = 0.0;\n\n std::list< LabelPixelType> relevantLabels;\n bool maskNonEmpty = false;\n LabelPixelType i;\n for ( i = 1; i < 100; ++i )\n {\n if ( this->HasLabel( i ) )\n {\n relevantLabels.push_back( i );\n maskNonEmpty = true;\n m_LabelStatisticsCoefficients.insert( std::make_pair(i, CoefficientsClass()) );\n }\n }\n\n if ( maskNonEmpty )\n {\n std::list< LabelPixelType >::iterator it;\n for ( it = relevantLabels.begin(), i = 0;\n it != relevantLabels.end();\n ++it, ++i )\n {\n double Sigma = GetSigma( *it );\n double Mean = GetMean( *it );\n Subregion = Superclass::GetRegion(*it);\n\n ImageRegionConstIteratorWithIndex< TInputImage > it1 (this->GetInput(),\n Subregion);\n ImageRegionConstIterator< TLabelImage > labelIt (this->GetLabelInput(),\n Subregion);\n\n for (it1.GoToBegin(); !it1.IsAtEnd(); ++it1, ++labelIt)\n {\n if (labelIt.Get() == *it)\n {\n baseOfSkewnessAndCurtosis = ( it1.Get() -Mean ) \/ Sigma ;\n Kurtosis += baseOfSkewnessAndCurtosis*baseOfSkewnessAndCurtosis*baseOfSkewnessAndCurtosis*baseOfSkewnessAndCurtosis;\n Skewness += baseOfSkewnessAndCurtosis*baseOfSkewnessAndCurtosis*baseOfSkewnessAndCurtosis;\n }\n }\n\n m_LabelStatisticsCoefficients[*it].m_Skewness = double(Skewness\/GetCount(*it));\n m_LabelStatisticsCoefficients[*it].m_Kurtosis = double(Kurtosis\/GetCount(*it));\n }\n }\n }\n\n\n template< class TInputImage, class TLabelImage >\n void ExtendedLabelStatisticsImageFilter< TInputImage, TLabelImage >::\n AfterThreadedGenerateData()\n {\n Superclass::AfterThreadedGenerateData();\n\n ComputeTheSkewnessAndCurtosis();\n }\n\n} \/\/ end namespace itk\n\n#endif<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2017, WNProject Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE.txt file.\n\n#include \"WNWindow\/inc\/WNXCBWindow.h\"\n#include \"WNApplicationData\/inc\/WNApplicationData.h\"\n#include \"WNExecutable\/inc\/WNEntryData.h\"\n#include \"WNMultiTasking\/inc\/WNJobPool.h\"\n#include \"WNMultiTasking\/inc\/WNJobSignal.h\"\n\nnamespace wn {\nnamespace runtime {\nnamespace window {\n\nwindow_error xcb_window::initialize() {\n m_job_pool->add_job(\n &m_destroy_signal, &xcb_window::dispatch_loop, this, nullptr);\n return window_error::ok;\n}\n\nvoid xcb_window::dispatch_loop(void*) {\n m_job_pool->call_blocking_function([&]() {\n m_data.connection = xcb_connect(NULL, NULL);\n if (m_data.connection == nullptr) {\n return;\n }\n\n const xcb_setup_t* setup = xcb_get_setup(m_data.connection);\n m_screen = xcb_setup_roots_iterator(setup).data;\n\n if (m_screen == nullptr) {\n xcb_disconnect(m_data.connection);\n m_data.connection = nullptr;\n m_creation_signal->increment(1);\n m_create_signal.increment(1);\n return;\n }\n\n m_data.window = xcb_generate_id(m_data.connection);\n\n uint32_t values[1] = {XCB_EVENT_MASK_STRUCTURE_NOTIFY};\n\n xcb_create_window(m_data.connection, XCB_COPY_FROM_PARENT, m_data.window,\n m_screen->root, m_x, m_y, m_width, m_height, 10,\n XCB_WINDOW_CLASS_INPUT_OUTPUT, m_screen->root_visual, XCB_CW_EVENT_MASK,\n values);\n\n if (m_creation_signal) {\n m_creation_signal->increment(1);\n }\n\n const char* protocol = \"WM_PROTOCOLS\";\n xcb_intern_atom_cookie_t cookie =\n xcb_intern_atom(m_data.connection, true, strlen(protocol), protocol);\n xcb_intern_atom_reply_t* reply =\n xcb_intern_atom_reply(m_data.connection, cookie, NULL);\n\n const char* delete_window = \"WM_DELETE_WINDOW\";\n cookie = xcb_intern_atom(\n m_data.connection, true, strlen(delete_window), delete_window);\n m_delete_window = xcb_intern_atom_reply(m_data.connection, cookie, NULL);\n\n xcb_change_property(m_data.connection, XCB_PROP_MODE_REPLACE, m_data.window,\n reply->atom, 4, 32, 1, &m_delete_window->atom);\n\n free(reply);\n\n xcb_map_window(m_data.connection, m_data.window);\n\n xcb_flush(m_data.connection);\n\n m_create_signal.increment(1);\n\n xcb_generic_event_t* event;\n while ((event = xcb_wait_for_event(m_data.connection))) {\n switch (event->response_type & 0x7F) {\n case XCB_CLIENT_MESSAGE:\n if ((*(xcb_client_message_event_t*)event).data.data32[0] ==\n m_delete_window->atom) {\n free(event);\n return;\n }\n case XCB_DESTROY_NOTIFY:\n free(event);\n return;\n default:\n break;\n }\n free(event);\n }\n });\n}\n\n} \/\/ namespace window\n} \/\/ namespace runtime\n} \/\/ namespace wn\n<commit_msg>Fix bug in XCB swapchain.<commit_after>\/\/ Copyright (c) 2017, WNProject Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE.txt file.\n\n#include \"WNWindow\/inc\/WNXCBWindow.h\"\n#include \"WNApplicationData\/inc\/WNApplicationData.h\"\n#include \"WNExecutable\/inc\/WNEntryData.h\"\n#include \"WNMultiTasking\/inc\/WNJobPool.h\"\n#include \"WNMultiTasking\/inc\/WNJobSignal.h\"\n\nnamespace wn {\nnamespace runtime {\nnamespace window {\n\nwindow_error xcb_window::initialize() {\n m_job_pool->add_job(\n &m_destroy_signal, &xcb_window::dispatch_loop, this, nullptr);\n return window_error::ok;\n}\n\nvoid xcb_window::dispatch_loop(void*) {\n m_job_pool->call_blocking_function([&]() {\n m_data.connection = xcb_connect(NULL, NULL);\n if (m_data.connection == nullptr) {\n return;\n }\n\n const xcb_setup_t* setup = xcb_get_setup(m_data.connection);\n m_screen = xcb_setup_roots_iterator(setup).data;\n\n if (m_screen == nullptr) {\n xcb_disconnect(m_data.connection);\n m_data.connection = nullptr;\n m_creation_signal->increment(1);\n m_create_signal.increment(1);\n return;\n }\n\n m_data.window = xcb_generate_id(m_data.connection);\n\n uint32_t values[1] = {XCB_EVENT_MASK_STRUCTURE_NOTIFY};\n\n xcb_create_window(m_data.connection, XCB_COPY_FROM_PARENT, m_data.window,\n m_screen->root, m_x, m_y, m_width, m_height, 10,\n XCB_WINDOW_CLASS_INPUT_OUTPUT, m_screen->root_visual, XCB_CW_EVENT_MASK,\n values);\n\n const char* protocol = \"WM_PROTOCOLS\";\n xcb_intern_atom_cookie_t cookie =\n xcb_intern_atom(m_data.connection, true, strlen(protocol), protocol);\n xcb_intern_atom_reply_t* reply =\n xcb_intern_atom_reply(m_data.connection, cookie, NULL);\n\n const char* delete_window = \"WM_DELETE_WINDOW\";\n cookie = xcb_intern_atom(\n m_data.connection, true, strlen(delete_window), delete_window);\n m_delete_window = xcb_intern_atom_reply(m_data.connection, cookie, NULL);\n\n xcb_change_property(m_data.connection, XCB_PROP_MODE_REPLACE, m_data.window,\n reply->atom, 4, 32, 1, &m_delete_window->atom);\n\n free(reply);\n\n xcb_map_window(m_data.connection, m_data.window);\n\n xcb_flush(m_data.connection);\n\n if (m_creation_signal) {\n m_creation_signal->increment(1);\n }\n\n m_create_signal.increment(1);\n\n xcb_generic_event_t* event;\n while ((event = xcb_wait_for_event(m_data.connection))) {\n switch (event->response_type & 0x7F) {\n case XCB_CLIENT_MESSAGE:\n if ((*(xcb_client_message_event_t*)event).data.data32[0] ==\n m_delete_window->atom) {\n free(event);\n return;\n }\n case XCB_DESTROY_NOTIFY:\n free(event);\n return;\n default:\n break;\n }\n free(event);\n }\n });\n}\n\n} \/\/ namespace window\n} \/\/ namespace runtime\n} \/\/ namespace wn\n<|endoftext|>"} {"text":"<commit_before>\/\/ RUN: %clang_cc1 -std=c++11 -S -emit-llvm -o - %s | FileCheck %s\n\nnamespace std {\n typedef decltype(sizeof(int)) size_t;\n\n \/\/ libc++'s implementation\n template <class _E>\n class initializer_list\n {\n const _E* __begin_;\n size_t __size_;\n\n initializer_list(const _E* __b, size_t __s)\n : __begin_(__b),\n __size_(__s)\n {}\n\n public:\n typedef _E value_type;\n typedef const _E& reference;\n typedef const _E& const_reference;\n typedef size_t size_type;\n\n typedef const _E* iterator;\n typedef const _E* const_iterator;\n\n initializer_list() : __begin_(nullptr), __size_(0) {}\n\n size_t size() const {return __size_;}\n const _E* begin() const {return __begin_;}\n const _E* end() const {return __begin_ + __size_;}\n };\n}\n\nvoid fn1(int i) {\n \/\/ CHECK: define void @_Z3fn1i\n \/\/ temporary array\n \/\/ CHECK: [[array:%[^ ]+]] = alloca [3 x i32]\n \/\/ CHECK: getelementptr inbounds [3 x i32]* [[array]], i{{32|64}} 0\n \/\/ CHECK-NEXT: store i32 1, i32*\n \/\/ CHECK-NEXT: getelementptr\n \/\/ CHECK-NEXT: store\n \/\/ CHECK-NEXT: getelementptr\n \/\/ CHECK-NEXT: load\n \/\/ CHECK-NEXT: store\n \/\/ init the list\n \/\/ CHECK-NEXT: getelementptr\n \/\/ CHECK-NEXT: getelementptr inbounds [3 x i32]*\n \/\/ CHECK-NEXT: store i32*\n \/\/ CHECK-NEXT: getelementptr\n \/\/ CHECK-NEXT: store i{{32|64}} 3\n std::initializer_list<int> intlist{1, 2, i};\n}\n\nstruct destroyme1 {\n ~destroyme1();\n};\nstruct destroyme2 {\n ~destroyme2();\n};\n\n\nvoid fn2() {\n \/\/ CHECK: define void @_Z3fn2v\n void target(std::initializer_list<destroyme1>);\n \/\/ objects should be destroyed before dm2, after call returns\n target({ destroyme1(), destroyme1() });\n \/\/ CHECK: call void @_ZN10destroyme1D1Ev\n destroyme2 dm2;\n \/\/ CHECK: call void @_ZN10destroyme2D1Ev\n}\n\nvoid fn3() {\n \/\/ CHECK: define void @_Z3fn3v\n \/\/ objects should be destroyed after dm2\n auto list = { destroyme1(), destroyme1() };\n destroyme2 dm2;\n \/\/ CHECK: call void @_ZN10destroyme2D1Ev\n \/\/ CHECK: call void @_ZN10destroyme1D1Ev\n}\n<commit_msg>Add a testcase to show that temporaries from the initializer list are destroyed correctly.<commit_after>\/\/ RUN: %clang_cc1 -std=c++11 -S -emit-llvm -o - %s | FileCheck %s\n\nnamespace std {\n typedef decltype(sizeof(int)) size_t;\n\n \/\/ libc++'s implementation\n template <class _E>\n class initializer_list\n {\n const _E* __begin_;\n size_t __size_;\n\n initializer_list(const _E* __b, size_t __s)\n : __begin_(__b),\n __size_(__s)\n {}\n\n public:\n typedef _E value_type;\n typedef const _E& reference;\n typedef const _E& const_reference;\n typedef size_t size_type;\n\n typedef const _E* iterator;\n typedef const _E* const_iterator;\n\n initializer_list() : __begin_(nullptr), __size_(0) {}\n\n size_t size() const {return __size_;}\n const _E* begin() const {return __begin_;}\n const _E* end() const {return __begin_ + __size_;}\n };\n}\n\nvoid fn1(int i) {\n \/\/ CHECK: define void @_Z3fn1i\n \/\/ temporary array\n \/\/ CHECK: [[array:%[^ ]+]] = alloca [3 x i32]\n \/\/ CHECK: getelementptr inbounds [3 x i32]* [[array]], i{{32|64}} 0\n \/\/ CHECK-NEXT: store i32 1, i32*\n \/\/ CHECK-NEXT: getelementptr\n \/\/ CHECK-NEXT: store\n \/\/ CHECK-NEXT: getelementptr\n \/\/ CHECK-NEXT: load\n \/\/ CHECK-NEXT: store\n \/\/ init the list\n \/\/ CHECK-NEXT: getelementptr\n \/\/ CHECK-NEXT: getelementptr inbounds [3 x i32]*\n \/\/ CHECK-NEXT: store i32*\n \/\/ CHECK-NEXT: getelementptr\n \/\/ CHECK-NEXT: store i{{32|64}} 3\n std::initializer_list<int> intlist{1, 2, i};\n}\n\nstruct destroyme1 {\n ~destroyme1();\n};\nstruct destroyme2 {\n ~destroyme2();\n};\nstruct witharg1 {\n witharg1(const destroyme1&);\n ~witharg1();\n};\n\n\nvoid fn2() {\n \/\/ CHECK: define void @_Z3fn2v\n void target(std::initializer_list<destroyme1>);\n \/\/ objects should be destroyed before dm2, after call returns\n \/\/ CHECK: call void @_Z6targetSt16initializer_listI10destroyme1E\n target({ destroyme1(), destroyme1() });\n \/\/ CHECK: call void @_ZN10destroyme1D1Ev\n destroyme2 dm2;\n \/\/ CHECK: call void @_ZN10destroyme2D1Ev\n}\n\nvoid fn3() {\n \/\/ CHECK: define void @_Z3fn3v\n \/\/ objects should be destroyed after dm2\n auto list = { destroyme1(), destroyme1() };\n destroyme2 dm2;\n \/\/ CHECK: call void @_ZN10destroyme2D1Ev\n \/\/ CHECK: call void @_ZN10destroyme1D1Ev\n}\n\nvoid fn4() {\n \/\/ CHECK: define void @_Z3fn4v\n void target(std::initializer_list<witharg1>);\n \/\/ objects should be destroyed before dm2, after call returns\n \/\/ CHECK: call void @_ZN8witharg1C1ERK10destroyme1\n \/\/ CHECK: call void @_Z6targetSt16initializer_listI8witharg1E\n target({ witharg1(destroyme1()), witharg1(destroyme1()) });\n \/\/ CHECK: call void @_ZN8witharg1D1Ev\n \/\/ CHECK: call void @_ZN10destroyme1D1Ev\n destroyme2 dm2;\n \/\/ CHECK: call void @_ZN10destroyme2D1Ev\n}\n\nvoid fn5() {\n \/\/ CHECK: define void @_Z3fn5v\n \/\/ temps should be destroyed before dm2\n \/\/ objects should be destroyed after dm2\n \/\/ CHECK: call void @_ZN8witharg1C1ERK10destroyme1\n auto list = { witharg1(destroyme1()), witharg1(destroyme1()) };\n \/\/ CHECK: call void @_ZN10destroyme1D1Ev\n destroyme2 dm2;\n \/\/ CHECK: call void @_ZN10destroyme2D1Ev\n \/\/ CHECK: call void @_ZN8witharg1D1Ev\n}\n<|endoftext|>"} {"text":"<commit_before>;\n#include \"..\/Flare.h\"\n#include \"FlareSpacecraft.h\"\n#include \"Subsystems\/FlareSpacecraftDamageSystem.h\"\n#include \"..\/Game\/FlarePlanetarium.h\"\n#include \"FlareSpacecraftSpinningComponent.h\"\n\n\n\/*----------------------------------------------------\n\tConstructor\n----------------------------------------------------*\/\n\nUFlareSpacecraftSpinningComponent::UFlareSpacecraftSpinningComponent(const class FObjectInitializer& PCIP)\n\t: Super(PCIP)\n\t, RotationAxisRoll(true)\n\t, RotationAxisYaw(false)\n\t, RotationSpeed(20)\n{\n}\n\n\n\/*----------------------------------------------------\n\tGameplay\n----------------------------------------------------*\/\n\nvoid UFlareSpacecraftSpinningComponent::BeginPlay()\n{\n\tSuper::BeginPlay();\n\tSetCollisionProfileName(\"BlockAllDynamic\");\n}\n\nvoid UFlareSpacecraftSpinningComponent::TickComponent(float DeltaSeconds, enum ELevelTick TickType, FActorComponentTickFunction *ThisTickFunction)\n{\n\tSuper::TickComponent(DeltaSeconds, TickType, ThisTickFunction);\n\tAFlareSpacecraft* Ship = GetSpacecraft();\n\tif (!Ship)\n\t{\n\t\treturn;\n\t}\n\n\t\/\/ Update\n\tif (!Ship->IsPresentationMode() && Ship->GetDamageSystem()->IsAlive())\n\t{\n\t\t\/\/ Rotation axis\n\t\tFRotator Axis;\n\t\tif (RotationAxisRoll)\n\t\t{\n\t\t\tAxis = FRotator(0, 0, 1);\n\t\t}\n\t\telse if (RotationAxisYaw)\n\t\t{\n\t\t\tAxis = FRotator(0, 1, 0);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tAxis = FRotator(1, 0, 0);\n\t\t}\n\n\t\t\/\/ Sun-looker\n\t\tif (LookForSun)\n\t\t{\n\t\t\tAFlarePlanetarium* Planetarium = Ship->GetGame()->GetPlanetarium();\n\t\t\tif (Planetarium)\n\t\t\t{\n\t\t\t\tFRotator SunRotator = Planetarium->GetSunDirection().Rotation();\n\t\t\t\tFRotator SpinnerRotator = GetComponentRotation();\n\t\t\t\tFRotator Delta = SunRotator - SpinnerRotator;\n\n\t\t\t\t\/\/ Does not work, because Roll axis if zero when extracted from a direction... :) \n\n\t\t\t\tif (RotationAxisRoll)\n\t\t\t\t{\n\t\t\t\t\tDelta = FRotator(0, 0, Delta.Roll);\n\t\t\t\t}\n\t\t\t\telse if (RotationAxisYaw)\n\t\t\t\t{\n\t\t\t\t\tDelta = FRotator(0, Delta.Yaw, 0);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tDelta = FRotator(Delta.Pitch, 0, 0);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tAddLocalRotation(RotationSpeed * DeltaSeconds * Delta);\n\t\t\t}\n\t\t}\n\n\t\t\/\/ Simple spinner\n\t\telse\n\t\t{\n\t\t\tAddLocalRotation(RotationSpeed * DeltaSeconds * Axis);\n\t\t}\n\t}\n}\n\n\n<commit_msg>Fixed sun-searching components, mostly (#114)<commit_after>;\n#include \"..\/Flare.h\"\n#include \"FlareSpacecraft.h\"\n#include \"Subsystems\/FlareSpacecraftDamageSystem.h\"\n#include \"..\/Game\/FlarePlanetarium.h\"\n#include \"FlareSpacecraftSpinningComponent.h\"\n\n\n\/*----------------------------------------------------\n\tConstructor\n----------------------------------------------------*\/\n\nUFlareSpacecraftSpinningComponent::UFlareSpacecraftSpinningComponent(const class FObjectInitializer& PCIP)\n\t: Super(PCIP)\n\t, RotationAxisRoll(true)\n\t, RotationAxisYaw(false)\n\t, RotationSpeed(20)\n{\n}\n\n\n\/*----------------------------------------------------\n\tGameplay\n----------------------------------------------------*\/\n\nvoid UFlareSpacecraftSpinningComponent::BeginPlay()\n{\n\tSuper::BeginPlay();\n\tSetCollisionProfileName(\"BlockAllDynamic\");\n}\n\nvoid UFlareSpacecraftSpinningComponent::TickComponent(float DeltaSeconds, enum ELevelTick TickType, FActorComponentTickFunction *ThisTickFunction)\n{\n\tSuper::TickComponent(DeltaSeconds, TickType, ThisTickFunction);\n\tAFlareSpacecraft* Ship = GetSpacecraft();\n\tif (!Ship)\n\t{\n\t\treturn;\n\t}\n\n\t\/\/ Update\n\tif (!Ship->IsPresentationMode() && Ship->GetDamageSystem()->IsAlive())\n\t{\n\t\t\/\/ Rotation axis\n\t\tFRotator Axis;\n\t\tif (RotationAxisRoll)\n\t\t{\n\t\t\tAxis = FRotator(0, 0, 1);\n\t\t}\n\t\telse if (RotationAxisYaw)\n\t\t{\n\t\t\tAxis = FRotator(0, 1, 0);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tAxis = FRotator(1, 0, 0);\n\t\t}\n\n\t\t\/\/ Sun-looker\n\t\tif (LookForSun)\n\t\t{\n\t\t\tAFlarePlanetarium* Planetarium = Ship->GetGame()->GetPlanetarium();\n\t\t\tif (Planetarium)\n\t\t\t{\n\t\t\t\tFVector X(1, 0, 0);\n\t\t\t\tFVector Y(0, 1, 0);\n\t\t\t\tFVector Z(0, 0, 1);\n\n\t\t\t\tFRotator SunRotator = Planetarium->GetSunDirection().Rotation();\n\t\t\t\tFRotator SpinnerRotator = GetComponentRotation();\n\t\t\t\tFRotator Delta;\n\n\t\t\t\t\/\/ Compute the angle difference\n\t\t\t\tSunRotator.Normalize();\n\t\t\t\tSpinnerRotator.Normalize();\n\t\t\t\tfloat Angle = FMath::Acos(FVector::DotProduct(SunRotator.RotateVector(X), SpinnerRotator.RotateVector(Z)));\n\t\t\t\t\/\/ TODO : angle has a 50% chance of being the wrong way depending on orientation...\n\n\t\t\t\t\/\/ Use the correct axis\n\t\t\t\tif (RotationAxisRoll)\n\t\t\t\t{\n\t\t\t\t\tDelta = FQuat(X, Angle).Rotator();\n\t\t\t\t}\n\t\t\t\telse if (RotationAxisYaw)\n\t\t\t\t{\n\t\t\t\t\tDelta = FQuat(Z, Angle).Rotator();\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tDelta = FQuat(Y, Angle).Rotator();\n\t\t\t\t}\n\n\t\t\t\t\/\/ Update\n\t\t\t\tfloat DegreesAngle = FMath::RadiansToDegrees(Angle);\n\t\t\t\tif (DegreesAngle > 1)\n\t\t\t\t{\n\t\t\t\t\tAddLocalRotation(RotationSpeed * DeltaSeconds * Delta);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t\/\/ Simple spinner\n\t\telse\n\t\t{\n\t\t\tAddLocalRotation(RotationSpeed * DeltaSeconds * Axis);\n\t\t}\n\t}\n}\n\n\n<|endoftext|>"} {"text":"<commit_before>#undef BOOST_SPIRIT_NO_PREDEFINED_TERMINALS\n#define BOOST_TEST_MODULE path_element_tests\n\n\/\/ boost.test\n#include <boost\/test\/included\/unit_test.hpp>\n\n\/\/ boost.filesystem\n#include <boost\/filesystem.hpp>\n\n\/\/ mapnik\n#include <mapnik\/map.hpp>\n#include <mapnik\/rule.hpp>\n#include <mapnik\/feature_type_style.hpp>\n#include <mapnik\/svg\/output\/svg_renderer.hpp>\n#include <mapnik\/text\/placements\/dummy.hpp>\n#include <mapnik\/datasource_cache.hpp>\n#include <mapnik\/expression.hpp>\n#include <mapnik\/color_factory.hpp>\n#include <mapnik\/image_util.hpp>\n#include <mapnik\/graphics.hpp>\n#include <mapnik\/agg_renderer.hpp>\n\n\n\/\/ stl\n#include <fstream>\n#include <iterator>\n\nnamespace fs = boost::filesystem;\nusing namespace mapnik;\n\nconst std::string srs_lcc=\"+proj=lcc +ellps=GRS80 +lat_0=49 +lon_0=-95 +lat+1=49 +lat_2=77 \\\n +datum=NAD83 +units=m +no_defs\";\nconst std::string srs_merc=\"+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 \\\n +y_0=0.0 +k=1.0 +units=m +nadgrids=@null +wktext +no_defs +over\";\n\nvoid prepare_map(Map & m)\n{\n \/\/ Provinces (polygon)\n feature_type_style provpoly_style;\n {\n rule r;\n r.set_filter(parse_expression(\"[NAME_EN] = 'Ontario'\"));\n {\n polygon_symbolizer poly_sym;\n put(poly_sym, keys::fill, color(250, 190, 183));\n r.append(std::move(poly_sym));\n }\n provpoly_style.add_rule(std::move(r));\n }\n {\n rule r;\n r.set_filter(parse_expression(\"[NOM_FR] = 'Québec'\"));\n {\n polygon_symbolizer poly_sym;\n put(poly_sym, keys::fill, color(217, 235, 203));\n r.append(std::move(poly_sym));\n }\n provpoly_style.add_rule(std::move(r));\n }\n m.insert_style(\"provinces\",provpoly_style);\n\n \/\/ Provinces (polyline)\n feature_type_style provlines_style;\n {\n rule r;\n {\n line_symbolizer line_sym;\n put(line_sym,keys::stroke,color(0,0,0));\n put(line_sym,keys::stroke_width,1.0);\n dash_array dash;\n dash.emplace_back(8,4);\n dash.emplace_back(2,2);\n dash.emplace_back(2,2);\n put(line_sym,keys::stroke_dasharray,dash);\n r.append(std::move(line_sym));\n }\n provlines_style.add_rule(std::move(r));\n }\n m.insert_style(\"provlines\",provlines_style);\n\n \/\/ Drainage\n feature_type_style qcdrain_style;\n {\n rule r;\n r.set_filter(parse_expression(\"[HYC] = 8\"));\n {\n polygon_symbolizer poly_sym;\n put(poly_sym, keys::fill, color(153, 204, 255));\n r.append(std::move(poly_sym));\n }\n qcdrain_style.add_rule(std::move(r));\n }\n m.insert_style(\"drainage\",qcdrain_style);\n\n \/\/ Roads 3 and 4 (The \"grey\" roads)\n feature_type_style roads34_style;\n {\n rule r;\n r.set_filter(parse_expression(\"[CLASS] = 3 or [CLASS] = 4\"));\n {\n line_symbolizer line_sym;\n put(line_sym,keys::stroke,color(171,158,137));\n put(line_sym,keys::stroke_width,2.0);\n put(line_sym,keys::stroke_linecap,ROUND_CAP);\n put(line_sym,keys::stroke_linejoin,ROUND_JOIN);\n r.append(std::move(line_sym));\n }\n roads34_style.add_rule(std::move(r));\n }\n m.insert_style(\"smallroads\",roads34_style);\n\n \/\/ Roads 2 (The thin yellow ones)\n feature_type_style roads2_style_1;\n {\n rule r;\n r.set_filter(parse_expression(\"[CLASS] = 2\"));\n {\n line_symbolizer line_sym;\n put(line_sym,keys::stroke,color(171,158,137));\n put(line_sym,keys::stroke_width,4.0);\n put(line_sym,keys::stroke_linecap,ROUND_CAP);\n put(line_sym,keys::stroke_linejoin,ROUND_JOIN);\n r.append(std::move(line_sym));\n }\n roads2_style_1.add_rule(std::move(r));\n }\n m.insert_style(\"road-border\", roads2_style_1);\n\n feature_type_style roads2_style_2;\n {\n rule r;\n r.set_filter(parse_expression(\"[CLASS] = 2\"));\n {\n line_symbolizer line_sym;\n put(line_sym,keys::stroke,color(255,250,115));\n put(line_sym,keys::stroke_width,2.0);\n put(line_sym,keys::stroke_linecap,ROUND_CAP);\n put(line_sym,keys::stroke_linejoin,ROUND_JOIN);\n r.append(std::move(line_sym));\n }\n roads2_style_2.add_rule(std::move(r));\n }\n m.insert_style(\"road-fill\", roads2_style_2);\n\n \/\/ Roads 1 (The big orange ones, the highways)\n feature_type_style roads1_style_1;\n {\n rule r;\n r.set_filter(parse_expression(\"[CLASS] = 1\"));\n {\n line_symbolizer line_sym;\n put(line_sym,keys::stroke,color(188,149,28));\n put(line_sym,keys::stroke_width,7.0);\n put(line_sym,keys::stroke_linecap,ROUND_CAP);\n put(line_sym,keys::stroke_linejoin,ROUND_JOIN);\n r.append(std::move(line_sym));\n }\n roads1_style_1.add_rule(std::move(r));\n }\n m.insert_style(\"highway-border\", roads1_style_1);\n\n feature_type_style roads1_style_2;\n {\n rule r;\n r.set_filter(parse_expression(\"[CLASS] = 1\"));\n {\n line_symbolizer line_sym;\n put(line_sym,keys::stroke,color(242,191,36));\n put(line_sym,keys::stroke_width,5.0);\n put(line_sym,keys::stroke_linecap,ROUND_CAP);\n put(line_sym,keys::stroke_linejoin,ROUND_JOIN);\n r.append(std::move(line_sym));\n }\n roads1_style_2.add_rule(std::move(r));\n }\n m.insert_style(\"highway-fill\", roads1_style_2);\n\n \/\/ Populated Places\n feature_type_style popplaces_style;\n {\n rule r;\n {\n text_symbolizer text_sym;\n text_placements_ptr placement_finder = std::make_shared<text_placements_dummy>();\n placement_finder->defaults.format->face_name = \"DejaVu Sans Book\";\n placement_finder->defaults.format->text_size = 10;\n placement_finder->defaults.format->fill = color(0,0,0);\n placement_finder->defaults.format->halo_fill = color(255,255,200);\n placement_finder->defaults.format->halo_radius = 1;\n placement_finder->defaults.set_old_style_expression(parse_expression(\"[GEONAME]\"));\n put<text_placements_ptr>(text_sym, keys::text_placements_, placement_finder);\n r.append(std::move(text_sym));\n }\n popplaces_style.add_rule(std::move(r));\n }\n\n m.insert_style(\"popplaces\",popplaces_style );\n\n \/\/ layers\n \/\/ Provincial polygons\n {\n parameters p;\n p[\"type\"]=\"shape\";\n p[\"file\"]=\"demo\/data\/boundaries\";\n p[\"encoding\"]=\"latin1\";\n layer lyr(\"Provinces\");\n lyr.set_datasource(datasource_cache::instance().create(p));\n lyr.set_srs(srs_lcc);\n lyr.add_style(\"provinces\");\n m.add_layer(lyr);\n }\n\n \/\/ Drainage\n {\n parameters p;\n p[\"type\"]=\"shape\";\n p[\"file\"]=\"demo\/data\/qcdrainage\";\n layer lyr(\"Quebec Hydrography\");\n lyr.set_datasource(datasource_cache::instance().create(p));\n lyr.set_srs(srs_lcc);\n lyr.add_style(\"drainage\");\n m.add_layer(lyr);\n }\n\n {\n parameters p;\n p[\"type\"]=\"shape\";\n p[\"file\"]=\"demo\/data\/ontdrainage\";\n layer lyr(\"Ontario Hydrography\");\n lyr.set_datasource(datasource_cache::instance().create(p));\n lyr.set_srs(srs_lcc);\n lyr.add_style(\"drainage\");\n m.add_layer(lyr);\n }\n\n \/\/ Provincial boundaries\n {\n parameters p;\n p[\"type\"]=\"shape\";\n p[\"file\"]=\"demo\/data\/boundaries_l\";\n layer lyr(\"Provincial borders\");\n lyr.set_srs(srs_lcc);\n lyr.set_datasource(datasource_cache::instance().create(p));\n lyr.add_style(\"provlines\");\n m.add_layer(lyr);\n }\n\n \/\/ Roads\n {\n parameters p;\n p[\"type\"]=\"shape\";\n p[\"file\"]=\"demo\/data\/roads\";\n layer lyr(\"Roads\");\n lyr.set_srs(srs_lcc);\n lyr.set_datasource(datasource_cache::instance().create(p));\n lyr.add_style(\"smallroads\");\n lyr.add_style(\"road-border\");\n lyr.add_style(\"road-fill\");\n lyr.add_style(\"highway-border\");\n lyr.add_style(\"highway-fill\");\n\n m.add_layer(lyr);\n }\n\n \/\/ popplaces\n {\n parameters p;\n p[\"type\"]=\"shape\";\n p[\"file\"]=\"demo\/data\/popplaces\";\n p[\"encoding\"] = \"latin1\";\n layer lyr(\"Populated Places\");\n lyr.set_srs(srs_lcc);\n lyr.set_datasource(datasource_cache::instance().create(p));\n lyr.add_style(\"popplaces\");\n m.add_layer(lyr);\n }\n}\n\nvoid render_to_file(Map const& m, const std::string output_filename)\n{\n std::ofstream output_stream(output_filename.c_str());\n\n if(output_stream)\n {\n using svg_ren = svg_renderer<std::ostream_iterator<char> >;\n std::ostream_iterator<char> output_stream_iterator(output_stream);\n svg_ren renderer(m, output_stream_iterator);\n renderer.apply();\n output_stream.close();\n fs::path output_filename_path =\n fs::system_complete(fs::path(\".\")) \/ fs::path(output_filename);\n BOOST_CHECK_MESSAGE(fs::exists(output_filename_path),\n \"File '\"+output_filename_path.string()+\"' was created.\");\n }\n else\n {\n BOOST_FAIL(\"Could not create create\/open file '\"+output_filename+\"'.\");\n }\n}\n\nBOOST_AUTO_TEST_CASE(path_element_test_case_1)\n{\n std::cout << \" looking for 'shape.input' plugin in .\/plugins\/input\/\" << \"\\n\";\n datasource_cache::instance().register_datasources(\"plugins\/input\/\");\n Map m(800,600);\n m.set_background(parse_color(\"white\"));\n m.set_srs(srs_merc);\n prepare_map(m);\n m.zoom_to_box(box2d<double>(-8024477.28459,5445190.38849,-7381388.20071,5662941.44855));\n render_to_file(m, \"path_element_test_case_1.svg\");\n mapnik::image_32 buf(m.width(),m.height());\n mapnik::agg_renderer<mapnik::image_32> ren(m,buf);\n ren.apply();\n mapnik::save_to_file(buf,\"path_element_test_case_1.png\");\n}\n<commit_msg>fix compile of svg renderer tests<commit_after>#undef BOOST_SPIRIT_NO_PREDEFINED_TERMINALS\n#define BOOST_TEST_MODULE path_element_tests\n\n\/\/ boost\n#include <boost\/test\/included\/unit_test.hpp>\n#include <boost\/filesystem.hpp>\n\n\/\/ mapnik\n#include <mapnik\/map.hpp>\n#include <mapnik\/layer.hpp>\n#include <mapnik\/rule.hpp>\n#include <mapnik\/feature_type_style.hpp>\n#include <mapnik\/svg\/output\/svg_renderer.hpp>\n#include <mapnik\/text\/placements\/dummy.hpp>\n#include <mapnik\/datasource_cache.hpp>\n#include <mapnik\/expression.hpp>\n#include <mapnik\/color_factory.hpp>\n#include <mapnik\/image_util.hpp>\n#include <mapnik\/graphics.hpp>\n#include <mapnik\/agg_renderer.hpp>\n\n\/\/ stl\n#include <fstream>\n#include <iterator>\n\nnamespace fs = boost::filesystem;\nusing namespace mapnik;\n\nconst std::string srs_lcc=\"+proj=lcc +ellps=GRS80 +lat_0=49 +lon_0=-95 +lat+1=49 +lat_2=77 \\\n +datum=NAD83 +units=m +no_defs\";\nconst std::string srs_merc=\"+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 \\\n +y_0=0.0 +k=1.0 +units=m +nadgrids=@null +wktext +no_defs +over\";\n\nvoid prepare_map(Map & m)\n{\n \/\/ Provinces (polygon)\n feature_type_style provpoly_style;\n {\n rule r;\n r.set_filter(parse_expression(\"[NAME_EN] = 'Ontario'\"));\n {\n polygon_symbolizer poly_sym;\n put(poly_sym, keys::fill, color(250, 190, 183));\n r.append(std::move(poly_sym));\n }\n provpoly_style.add_rule(std::move(r));\n }\n {\n rule r;\n r.set_filter(parse_expression(\"[NOM_FR] = 'Québec'\"));\n {\n polygon_symbolizer poly_sym;\n put(poly_sym, keys::fill, color(217, 235, 203));\n r.append(std::move(poly_sym));\n }\n provpoly_style.add_rule(std::move(r));\n }\n m.insert_style(\"provinces\",provpoly_style);\n\n \/\/ Provinces (polyline)\n feature_type_style provlines_style;\n {\n rule r;\n {\n line_symbolizer line_sym;\n put(line_sym,keys::stroke,color(0,0,0));\n put(line_sym,keys::stroke_width,1.0);\n dash_array dash;\n dash.emplace_back(8,4);\n dash.emplace_back(2,2);\n dash.emplace_back(2,2);\n put(line_sym,keys::stroke_dasharray,dash);\n r.append(std::move(line_sym));\n }\n provlines_style.add_rule(std::move(r));\n }\n m.insert_style(\"provlines\",provlines_style);\n\n \/\/ Drainage\n feature_type_style qcdrain_style;\n {\n rule r;\n r.set_filter(parse_expression(\"[HYC] = 8\"));\n {\n polygon_symbolizer poly_sym;\n put(poly_sym, keys::fill, color(153, 204, 255));\n r.append(std::move(poly_sym));\n }\n qcdrain_style.add_rule(std::move(r));\n }\n m.insert_style(\"drainage\",qcdrain_style);\n\n \/\/ Roads 3 and 4 (The \"grey\" roads)\n feature_type_style roads34_style;\n {\n rule r;\n r.set_filter(parse_expression(\"[CLASS] = 3 or [CLASS] = 4\"));\n {\n line_symbolizer line_sym;\n put(line_sym,keys::stroke,color(171,158,137));\n put(line_sym,keys::stroke_width,2.0);\n put(line_sym,keys::stroke_linecap,ROUND_CAP);\n put(line_sym,keys::stroke_linejoin,ROUND_JOIN);\n r.append(std::move(line_sym));\n }\n roads34_style.add_rule(std::move(r));\n }\n m.insert_style(\"smallroads\",roads34_style);\n\n \/\/ Roads 2 (The thin yellow ones)\n feature_type_style roads2_style_1;\n {\n rule r;\n r.set_filter(parse_expression(\"[CLASS] = 2\"));\n {\n line_symbolizer line_sym;\n put(line_sym,keys::stroke,color(171,158,137));\n put(line_sym,keys::stroke_width,4.0);\n put(line_sym,keys::stroke_linecap,ROUND_CAP);\n put(line_sym,keys::stroke_linejoin,ROUND_JOIN);\n r.append(std::move(line_sym));\n }\n roads2_style_1.add_rule(std::move(r));\n }\n m.insert_style(\"road-border\", roads2_style_1);\n\n feature_type_style roads2_style_2;\n {\n rule r;\n r.set_filter(parse_expression(\"[CLASS] = 2\"));\n {\n line_symbolizer line_sym;\n put(line_sym,keys::stroke,color(255,250,115));\n put(line_sym,keys::stroke_width,2.0);\n put(line_sym,keys::stroke_linecap,ROUND_CAP);\n put(line_sym,keys::stroke_linejoin,ROUND_JOIN);\n r.append(std::move(line_sym));\n }\n roads2_style_2.add_rule(std::move(r));\n }\n m.insert_style(\"road-fill\", roads2_style_2);\n\n \/\/ Roads 1 (The big orange ones, the highways)\n feature_type_style roads1_style_1;\n {\n rule r;\n r.set_filter(parse_expression(\"[CLASS] = 1\"));\n {\n line_symbolizer line_sym;\n put(line_sym,keys::stroke,color(188,149,28));\n put(line_sym,keys::stroke_width,7.0);\n put(line_sym,keys::stroke_linecap,ROUND_CAP);\n put(line_sym,keys::stroke_linejoin,ROUND_JOIN);\n r.append(std::move(line_sym));\n }\n roads1_style_1.add_rule(std::move(r));\n }\n m.insert_style(\"highway-border\", roads1_style_1);\n\n feature_type_style roads1_style_2;\n {\n rule r;\n r.set_filter(parse_expression(\"[CLASS] = 1\"));\n {\n line_symbolizer line_sym;\n put(line_sym,keys::stroke,color(242,191,36));\n put(line_sym,keys::stroke_width,5.0);\n put(line_sym,keys::stroke_linecap,ROUND_CAP);\n put(line_sym,keys::stroke_linejoin,ROUND_JOIN);\n r.append(std::move(line_sym));\n }\n roads1_style_2.add_rule(std::move(r));\n }\n m.insert_style(\"highway-fill\", roads1_style_2);\n\n \/\/ Populated Places\n feature_type_style popplaces_style;\n {\n rule r;\n {\n text_symbolizer text_sym;\n text_placements_ptr placement_finder = std::make_shared<text_placements_dummy>();\n placement_finder->defaults.format_defaults.face_name = \"DejaVu Sans Book\";\n placement_finder->defaults.format_defaults.text_size = mapnik::value_integer(10);\n placement_finder->defaults.format_defaults.fill = color(0,0,0);\n placement_finder->defaults.format_defaults.halo_fill = color(255,255,200);\n placement_finder->defaults.format_defaults.halo_radius = mapnik::value_integer(1);\n placement_finder->defaults.set_old_style_expression(parse_expression(\"[GEONAME]\"));\n put<text_placements_ptr>(text_sym, keys::text_placements_, placement_finder);\n r.append(std::move(text_sym));\n }\n popplaces_style.add_rule(std::move(r));\n }\n\n m.insert_style(\"popplaces\",popplaces_style );\n\n \/\/ layers\n \/\/ Provincial polygons\n {\n parameters p;\n p[\"type\"]=\"shape\";\n p[\"file\"]=\"demo\/data\/boundaries\";\n p[\"encoding\"]=\"latin1\";\n layer lyr(\"Provinces\");\n lyr.set_datasource(datasource_cache::instance().create(p));\n lyr.set_srs(srs_lcc);\n lyr.add_style(\"provinces\");\n m.add_layer(lyr);\n }\n\n \/\/ Drainage\n {\n parameters p;\n p[\"type\"]=\"shape\";\n p[\"file\"]=\"demo\/data\/qcdrainage\";\n layer lyr(\"Quebec Hydrography\");\n lyr.set_datasource(datasource_cache::instance().create(p));\n lyr.set_srs(srs_lcc);\n lyr.add_style(\"drainage\");\n m.add_layer(lyr);\n }\n\n {\n parameters p;\n p[\"type\"]=\"shape\";\n p[\"file\"]=\"demo\/data\/ontdrainage\";\n layer lyr(\"Ontario Hydrography\");\n lyr.set_datasource(datasource_cache::instance().create(p));\n lyr.set_srs(srs_lcc);\n lyr.add_style(\"drainage\");\n m.add_layer(lyr);\n }\n\n \/\/ Provincial boundaries\n {\n parameters p;\n p[\"type\"]=\"shape\";\n p[\"file\"]=\"demo\/data\/boundaries_l\";\n layer lyr(\"Provincial borders\");\n lyr.set_srs(srs_lcc);\n lyr.set_datasource(datasource_cache::instance().create(p));\n lyr.add_style(\"provlines\");\n m.add_layer(lyr);\n }\n\n \/\/ Roads\n {\n parameters p;\n p[\"type\"]=\"shape\";\n p[\"file\"]=\"demo\/data\/roads\";\n layer lyr(\"Roads\");\n lyr.set_srs(srs_lcc);\n lyr.set_datasource(datasource_cache::instance().create(p));\n lyr.add_style(\"smallroads\");\n lyr.add_style(\"road-border\");\n lyr.add_style(\"road-fill\");\n lyr.add_style(\"highway-border\");\n lyr.add_style(\"highway-fill\");\n\n m.add_layer(lyr);\n }\n\n \/\/ popplaces\n {\n parameters p;\n p[\"type\"]=\"shape\";\n p[\"file\"]=\"demo\/data\/popplaces\";\n p[\"encoding\"] = \"latin1\";\n layer lyr(\"Populated Places\");\n lyr.set_srs(srs_lcc);\n lyr.set_datasource(datasource_cache::instance().create(p));\n lyr.add_style(\"popplaces\");\n m.add_layer(lyr);\n }\n}\n\nvoid render_to_file(Map const& m, const std::string output_filename)\n{\n std::ofstream output_stream(output_filename.c_str());\n\n if(output_stream)\n {\n using svg_ren = svg_renderer<std::ostream_iterator<char> >;\n std::ostream_iterator<char> output_stream_iterator(output_stream);\n svg_ren renderer(m, output_stream_iterator);\n renderer.apply();\n output_stream.close();\n fs::path output_filename_path =\n fs::system_complete(fs::path(\".\")) \/ fs::path(output_filename);\n BOOST_CHECK_MESSAGE(fs::exists(output_filename_path),\n \"File '\"+output_filename_path.string()+\"' was created.\");\n }\n else\n {\n BOOST_FAIL(\"Could not create create\/open file '\"+output_filename+\"'.\");\n }\n}\n\nBOOST_AUTO_TEST_CASE(path_element_test_case_1)\n{\n std::cout << \" looking for 'shape.input' plugin in .\/plugins\/input\/\" << \"\\n\";\n datasource_cache::instance().register_datasources(\"plugins\/input\/\");\n Map m(800,600);\n m.set_background(parse_color(\"white\"));\n m.set_srs(srs_merc);\n prepare_map(m);\n m.zoom_to_box(box2d<double>(-8024477.28459,5445190.38849,-7381388.20071,5662941.44855));\n render_to_file(m, \"path_element_test_case_1.svg\");\n mapnik::image_32 buf(m.width(),m.height());\n mapnik::agg_renderer<mapnik::image_32> ren(m,buf);\n ren.apply();\n mapnik::save_to_file(buf,\"path_element_test_case_1.png\");\n}\n<|endoftext|>"} {"text":"<commit_before>#ifndef SILICIUM_REACTIVE_LINUX_INOTIFY_HPP\n#define SILICIUM_REACTIVE_LINUX_INOTIFY_HPP\n\n#include <silicium\/observable.hpp>\n#include <silicium\/override.hpp>\n#include <boost\/filesystem\/path.hpp>\n#include <boost\/asio\/posix\/stream_descriptor.hpp>\n#include <boost\/swap.hpp>\n#include <boost\/optional.hpp>\n#include <sys\/inotify.h>\n#include <dirent.h>\n\nnamespace Si\n{\n\tnamespace linux\n\t{\n\t\tstruct file_notification\n\t\t{\n\t\t\tboost::uint32_t mask;\n\t\t\tboost::filesystem::path name;\n\t\t};\n\n\t\tstruct watch_descriptor\n\t\t{\n\t\t\twatch_descriptor() BOOST_NOEXCEPT\n\t\t\t{\n\t\t\t}\n\n\t\t\twatch_descriptor(int notifier, int watch) BOOST_NOEXCEPT\n\t\t\t\t: notifier(notifier)\n\t\t\t\t, watch(watch)\n\t\t\t{\n\t\t\t}\n\n\t\t\twatch_descriptor(watch_descriptor &&other) BOOST_NOEXCEPT\n\t\t\t\t: notifier(other.notifier)\n\t\t\t\t, watch(other.watch)\n\t\t\t{\n\t\t\t\tother.notifier = -1;\n\t\t\t}\n\n\t\t\t~watch_descriptor() BOOST_NOEXCEPT\n\t\t\t{\n\t\t\t\tif (notifier == -1)\n\t\t\t\t{\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tinotify_rm_watch(notifier, watch);\n\t\t\t}\n\n\t\t\twatch_descriptor &operator = (watch_descriptor &&other) BOOST_NOEXCEPT\n\t\t\t{\n\t\t\t\tboost::swap(notifier, other.notifier);\n\t\t\t\tboost::swap(watch, other.watch);\n\t\t\t\treturn *this;\n\t\t\t}\n\n\t\tprivate:\n\n\t\t\tint notifier = -1;\n\t\t\tint watch = -1;\n\t\t};\n\n\t\tstruct inotify_observable : observable<std::vector<file_notification>>, boost::noncopyable\n\t\t{\n\t\t\ttypedef std::vector<file_notification> element_type;\n\n\t\t\tinotify_observable();\n\t\t\texplicit inotify_observable(boost::asio::io_service &io);\n\t\t\twatch_descriptor watch(boost::filesystem::path const &target, boost::uint32_t mask);\n\t\t\twatch_descriptor watch(boost::filesystem::path const &target, boost::uint32_t mask, boost::system::error_code &ec);\n\t\t\tvirtual void async_get_one(observer<element_type> &receiver) SILICIUM_OVERRIDE;\n\t\t\tvirtual void cancel() SILICIUM_OVERRIDE;\n\n\t\tprivate:\n\n\t\t\tboost::optional<boost::asio::posix::stream_descriptor> notifier;\n\t\t\tstd::vector<char> read_buffer;\n\t\t\tobserver<element_type> *receiver_ = nullptr;\n\t\t};\n\t}\n}\n\n#endif\n<commit_msg>devirtualize inotify_observable<commit_after>#ifndef SILICIUM_REACTIVE_LINUX_INOTIFY_HPP\n#define SILICIUM_REACTIVE_LINUX_INOTIFY_HPP\n\n#include <silicium\/observer.hpp>\n#include <silicium\/override.hpp>\n#include <boost\/filesystem\/path.hpp>\n#include <boost\/asio\/posix\/stream_descriptor.hpp>\n#include <boost\/swap.hpp>\n#include <boost\/optional.hpp>\n#include <sys\/inotify.h>\n#include <dirent.h>\n\nnamespace Si\n{\n\tnamespace linux\n\t{\n\t\tstruct file_notification\n\t\t{\n\t\t\tboost::uint32_t mask;\n\t\t\tboost::filesystem::path name;\n\t\t};\n\n\t\tstruct watch_descriptor\n\t\t{\n\t\t\twatch_descriptor() BOOST_NOEXCEPT\n\t\t\t{\n\t\t\t}\n\n\t\t\twatch_descriptor(int notifier, int watch) BOOST_NOEXCEPT\n\t\t\t\t: notifier(notifier)\n\t\t\t\t, watch(watch)\n\t\t\t{\n\t\t\t}\n\n\t\t\twatch_descriptor(watch_descriptor &&other) BOOST_NOEXCEPT\n\t\t\t\t: notifier(other.notifier)\n\t\t\t\t, watch(other.watch)\n\t\t\t{\n\t\t\t\tother.notifier = -1;\n\t\t\t}\n\n\t\t\t~watch_descriptor() BOOST_NOEXCEPT\n\t\t\t{\n\t\t\t\tif (notifier == -1)\n\t\t\t\t{\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tinotify_rm_watch(notifier, watch);\n\t\t\t}\n\n\t\t\twatch_descriptor &operator = (watch_descriptor &&other) BOOST_NOEXCEPT\n\t\t\t{\n\t\t\t\tboost::swap(notifier, other.notifier);\n\t\t\t\tboost::swap(watch, other.watch);\n\t\t\t\treturn *this;\n\t\t\t}\n\n\t\tprivate:\n\n\t\t\tint notifier = -1;\n\t\t\tint watch = -1;\n\t\t};\n\n\t\tstruct inotify_observable : private boost::noncopyable\n\t\t{\n\t\t\ttypedef std::vector<file_notification> element_type;\n\n\t\t\tinotify_observable();\n\t\t\texplicit inotify_observable(boost::asio::io_service &io);\n\t\t\twatch_descriptor watch(boost::filesystem::path const &target, boost::uint32_t mask);\n\t\t\twatch_descriptor watch(boost::filesystem::path const &target, boost::uint32_t mask, boost::system::error_code &ec);\n\t\t\tvoid async_get_one(observer<element_type> &receiver);\n\t\t\tvoid cancel();\n\n\t\tprivate:\n\n\t\t\tboost::optional<boost::asio::posix::stream_descriptor> notifier;\n\t\t\tstd::vector<char> read_buffer;\n\t\t\tobserver<element_type> *receiver_ = nullptr;\n\t\t};\n\t}\n}\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/\/ FindDlg.cpp : implementation file\n\/\/\n\n#include \"stdafx.h\"\n#include \"passwordsafe.h\"\n\n#if defined(POCKET_PC)\n #include \"pocketpc\/resource.h\"\n#else\n #include \"resource.h\"\n#endif\n#include \"FindDlg.h\"\n#include \"DboxMain.h\"\n\n#ifdef _DEBUG\n#define new DEBUG_NEW\n#undef THIS_FILE\nstatic char THIS_FILE[] = __FILE__;\n#endif\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ CFindDlg dialog\n\nCFindDlg *CFindDlg::self = NULL; \/\/ for Singleton pattern\n\nvoid CFindDlg::Doit(CWnd *pParent)\n{\n if (self == NULL) {\n self = new CFindDlg(pParent);\n if (self != NULL)\n if (self->Create(CFindDlg::IDD))\n\tself->ShowWindow(SW_SHOW);\n } else {\n self->BringWindowToTop();\n }\n}\n\nCFindDlg::CFindDlg(CWnd* pParent \/*=NULL*\/)\n : super(CFindDlg::IDD, pParent), m_indices(NULL),\n m_lastshown(-1), m_numFound(0),\n m_last_search_text(_T(\"\")), m_last_cs_search(FALSE)\n{\n \/\/{{AFX_DATA_INIT(CFindDlg)\n m_cs_search = FALSE;\n m_search_text = _T(\"\");\n m_status = _T(\"\");\n\t\/\/}}AFX_DATA_INIT\n}\n\nCFindDlg::~CFindDlg()\n{\n delete[] m_indices;\n self = NULL;\n}\n\nvoid CFindDlg::DoDataExchange(CDataExchange* pDX)\n{\n\tsuper::DoDataExchange(pDX);\n\t\/\/{{AFX_DATA_MAP(CFindDlg)\n\tDDX_Check(pDX, IDC_FIND_CS, m_cs_search);\n\tDDX_Text(pDX, IDC_FIND_TEXT, m_search_text);\n#if !defined(POCKET_PC)\n\tDDX_Text(pDX, IDC_STATUS, m_status);\n#endif\n\t\/\/}}AFX_DATA_MAP\n}\n\n\nBEGIN_MESSAGE_MAP(CFindDlg, super)\n\t\/\/{{AFX_MSG_MAP(CFindDlg)\n\tON_BN_CLICKED(IDOK, OnFind)\n#if defined(POCKET_PC)\n\tON_BN_CLICKED(IDCANCEL, OnCancel)\n#else\n\tON_BN_CLICKED(IDCANCEL, OnClose)\n#endif\n\t\/\/}}AFX_MSG_MAP\nEND_MESSAGE_MAP()\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ CFindDlg message handlers\n\nvoid CFindDlg::OnFind() \n{\n\n DboxMain* pParent = (DboxMain*) GetParent();\n ASSERT(pParent != NULL);\n\n const int numEntries = pParent->GetNumEntries();\n\n if (numEntries == 0) {\n \/\/ Right Thing would be to disable find menu item if list is empty\n m_status = _T(\"Password list is empty.\");\n UpdateData(FALSE);\n return;\n }\n\n UpdateData(TRUE);\n\n if (m_search_text.IsEmpty()) {\n m_status = _T(\"Please enter a search string\");\n UpdateData(FALSE);\n return;\n }\n\n \/\/ If the user changes the search text or cs, then this is a new search:\n if (m_search_text != m_last_search_text ||\n m_cs_search != m_last_cs_search) {\n m_last_search_text = m_search_text;\n m_last_cs_search = m_cs_search;\n m_lastshown = -1;\n }\n\n if (m_lastshown == -1) {\n\n if (m_indices != NULL) {\n \/\/ take care of the pathological case where someone added or deleted\n \/\/ an entry while this dialog box is open\n delete[] m_indices;\n }\n m_indices = new int[numEntries];\n\n m_numFound = pParent->FindAll(m_search_text, m_cs_search, m_indices);\n\n switch (m_numFound) {\n case 0:\n m_status = _T(\"No matches found.\");\n break;\n case 1:\n m_status = _T(\"Found 1 match.\");\n break;\n default:\n \/\/ {kjp} this kludge is needed because the declaration of CString in <afx.h> defines\n \/\/ {kjp} FormatMessage as implemented, but if you take a look at the source for \n \/\/ {kjp} CString in strex.cpp you'll see that it's only actully implemented if the\n \/\/ {kjp} platform is not WinCE. Methinks this is a bug in afx.h\n#if defined(POCKET_PC)\n m_status.Format( _T(\"Found %d matches.\"), m_numFound );\n#else\n m_status.FormatMessage(_T(\"Found %1!d! matches.\"), m_numFound);\n#endif\n break;\n }\n UpdateData(FALSE);\n } \/\/ m_lastshown == -1\n\n \/\/ OK, so now we have a (possibly empty) list of items to select.\n\n if (m_numFound > 0) {\n m_lastshown = (m_lastshown + 1) % m_numFound; \/\/from -1 to 0, cycle afterwards\n pParent->SelectEntry(m_indices[m_lastshown], TRUE);\n }\n if (m_numFound > 1) {\n SetDlgItemText(IDOK, _T(\"Find Next\"));\n }\n \/\/ don't call super::OnOK - user will Cancel() to close dbox\n}\n\n#if defined(POCKET_PC)\nvoid CFindDlg::OnCancel()\n{\n\tself = NULL;\n\tsuper::DestroyWindow();\n}\n#else\nvoid CFindDlg::OnClose() \n{\n self = NULL;\n super::OnCancel();\n}\n#endif\n<commit_msg>[1082510] - Find dialog no longer obscures parent.<commit_after>\/\/ FindDlg.cpp : implementation file\n\/\/\n\n#include \"stdafx.h\"\n#include \"passwordsafe.h\"\n\n#if defined(POCKET_PC)\n #include \"pocketpc\/resource.h\"\n#else\n #include \"resource.h\"\n#endif\n#include \"FindDlg.h\"\n#include \"DboxMain.h\"\n\n#ifdef _DEBUG\n#define new DEBUG_NEW\n#undef THIS_FILE\nstatic char THIS_FILE[] = __FILE__;\n#endif\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ CFindDlg dialog\n\nCFindDlg *CFindDlg::self = NULL; \/\/ for Singleton pattern\n\nvoid CFindDlg::Doit(CWnd *pParent)\n{\n if (self == NULL) {\n self = new CFindDlg(pParent);\n if (self != NULL)\n if (self->Create(CFindDlg::IDD)) {\n\tRECT myRect, parentRect; \n\t\/\/ move find dialog so that it doesn't overlap its parent\n\tpParent->GetWindowRect(&parentRect);\n\tself->GetWindowRect(&myRect);\n\t\/\/ Move the dialog to the right if parent is on left side\n\t\/\/ of screen,and vice versa\n\tint screenCenter = GetSystemMetrics(SM_CXSCREEN)\/2;\n\tint parentCenter = (parentRect.right + parentRect.left)\/2;\n\n\tif (parentCenter < screenCenter) {\n\t \/\/ move right\n\t myRect.right = parentRect.right + myRect.right - myRect.left;\n\t myRect.left = parentRect.right;\n\t} else { \/\/ move left\n\t myRect.left = parentRect.left - (myRect.right - myRect.left);\n\t myRect.right = parentRect.left;\n\t}\n\tself-> MoveWindow(&myRect);\n\tself->ShowWindow(SW_SHOW);\n }\n } else {\n self->BringWindowToTop();\n }\n}\n\nCFindDlg::CFindDlg(CWnd* pParent \/*=NULL*\/)\n : super(CFindDlg::IDD, pParent), m_indices(NULL),\n m_lastshown(-1), m_numFound(0),\n m_last_search_text(_T(\"\")), m_last_cs_search(FALSE)\n{\n \/\/{{AFX_DATA_INIT(CFindDlg)\n m_cs_search = FALSE;\n m_search_text = _T(\"\");\n m_status = _T(\"\");\n\t\/\/}}AFX_DATA_INIT\n}\n\nCFindDlg::~CFindDlg()\n{\n delete[] m_indices;\n self = NULL;\n}\n\nvoid CFindDlg::DoDataExchange(CDataExchange* pDX)\n{\n\tsuper::DoDataExchange(pDX);\n\t\/\/{{AFX_DATA_MAP(CFindDlg)\n\tDDX_Check(pDX, IDC_FIND_CS, m_cs_search);\n\tDDX_Text(pDX, IDC_FIND_TEXT, m_search_text);\n#if !defined(POCKET_PC)\n\tDDX_Text(pDX, IDC_STATUS, m_status);\n#endif\n\t\/\/}}AFX_DATA_MAP\n}\n\n\nBEGIN_MESSAGE_MAP(CFindDlg, super)\n\t\/\/{{AFX_MSG_MAP(CFindDlg)\n\tON_BN_CLICKED(IDOK, OnFind)\n#if defined(POCKET_PC)\n\tON_BN_CLICKED(IDCANCEL, OnCancel)\n#else\n\tON_BN_CLICKED(IDCANCEL, OnClose)\n#endif\n\t\/\/}}AFX_MSG_MAP\nEND_MESSAGE_MAP()\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ CFindDlg message handlers\n\nvoid CFindDlg::OnFind() \n{\n\n DboxMain* pParent = (DboxMain*) GetParent();\n ASSERT(pParent != NULL);\n\n const int numEntries = pParent->GetNumEntries();\n\n if (numEntries == 0) {\n \/\/ Right Thing would be to disable find menu item if list is empty\n m_status = _T(\"Password list is empty.\");\n UpdateData(FALSE);\n return;\n }\n\n UpdateData(TRUE);\n\n if (m_search_text.IsEmpty()) {\n m_status = _T(\"Please enter a search string\");\n UpdateData(FALSE);\n return;\n }\n\n \/\/ If the user changes the search text or cs, then this is a new search:\n if (m_search_text != m_last_search_text ||\n m_cs_search != m_last_cs_search) {\n m_last_search_text = m_search_text;\n m_last_cs_search = m_cs_search;\n m_lastshown = -1;\n }\n\n if (m_lastshown == -1) {\n\n if (m_indices != NULL) {\n \/\/ take care of the pathological case where someone added or deleted\n \/\/ an entry while this dialog box is open\n delete[] m_indices;\n }\n m_indices = new int[numEntries];\n\n m_numFound = pParent->FindAll(m_search_text, m_cs_search, m_indices);\n\n switch (m_numFound) {\n case 0:\n m_status = _T(\"No matches found.\");\n break;\n case 1:\n m_status = _T(\"Found 1 match.\");\n break;\n default:\n \/\/ {kjp} this kludge is needed because the declaration of CString in <afx.h> defines\n \/\/ {kjp} FormatMessage as implemented, but if you take a look at the source for \n \/\/ {kjp} CString in strex.cpp you'll see that it's only actully implemented if the\n \/\/ {kjp} platform is not WinCE. Methinks this is a bug in afx.h\n#if defined(POCKET_PC)\n m_status.Format( _T(\"Found %d matches.\"), m_numFound );\n#else\n m_status.FormatMessage(_T(\"Found %1!d! matches.\"), m_numFound);\n#endif\n break;\n }\n UpdateData(FALSE);\n } \/\/ m_lastshown == -1\n\n \/\/ OK, so now we have a (possibly empty) list of items to select.\n\n if (m_numFound > 0) {\n m_lastshown = (m_lastshown + 1) % m_numFound; \/\/from -1 to 0, cycle afterwards\n pParent->SelectEntry(m_indices[m_lastshown], TRUE);\n }\n if (m_numFound > 1) {\n SetDlgItemText(IDOK, _T(\"Find Next\"));\n }\n \/\/ don't call super::OnOK - user will Cancel() to close dbox\n}\n\n#if defined(POCKET_PC)\nvoid CFindDlg::OnCancel()\n{\n\tself = NULL;\n\tsuper::DestroyWindow();\n}\n#else\nvoid CFindDlg::OnClose() \n{\n self = NULL;\n super::OnCancel();\n}\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/*=========================================================================\n\n Program: ORFEO Toolbox\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n\n Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.\n See OTBCopyright.txt for details.\n\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notices for more information.\n\n=========================================================================*\/\n\n#if defined(_MSC_VER)\n#pragma warning ( disable : 4786 )\n#endif\n\n#include \"otbImageIOFactory.h\"\n#include \"itkExceptionObject.h\"\n#include <iostream>\n\nint otbImageIOFactoryNew(int argc, char* argv [])\n{\n otb::ImageIOFactory * lImageIOFactory;\n\n return EXIT_SUCCESS;\n}\n<commit_msg>WRG: otbImageIOFactoryNew.cxx:29: warning: unused variable lImageIOFactory<commit_after>\/*=========================================================================\n\n Program: ORFEO Toolbox\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n\n Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.\n See OTBCopyright.txt for details.\n\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notices for more information.\n\n=========================================================================*\/\n\n#if defined(_MSC_VER)\n#pragma warning ( disable : 4786 )\n#endif\n\n#include \"otbImageIOFactory.h\"\n#include \"itkExceptionObject.h\"\n#include <iostream>\n\nint otbImageIOFactoryNew(int argc, char* argv [])\n{\n otb::ImageIOFactory * lImageIOFactory;\n lImageIOFactory = NULL;\n return EXIT_SUCCESS;\n}\n<|endoftext|>"} {"text":"<commit_before>\/** This file is part of Contacts daemon\n **\n ** Copyright (c) 2010-2011 Nokia Corporation and\/or its subsidiary(-ies).\n **\n ** Contact: Nokia Corporation (info@qt.nokia.com)\n **\n ** GNU Lesser General Public License Usage\n ** This file may be used under the terms of the GNU Lesser General Public License\n ** version 2.1 as published by the Free Software Foundation and appearing in the\n ** file LICENSE.LGPL included in the packaging of this file. Please review the\n ** following information to ensure the GNU Lesser General Public License version\n ** 2.1 requirements will be met:\n ** http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n **\n ** In addition, as a special exception, Nokia gives you certain additional rights.\n ** These rights are described in the Nokia Qt LGPL Exception version 1.1, included\n ** in the file LGPL_EXCEPTION.txt in this package.\n **\n ** Other Usage\n ** Alternatively, this file may be used in accordance with the terms and\n ** conditions contained in a signed written agreement between you and Nokia.\n **\/\n\n#include \"cdbirthdaycontroller.h\"\n#include \"cdbirthdaycalendar.h\"\n#include \"cdbirthdayplugin.h\"\n#include \"debug.h\"\n\n#include <QDir>\n#include <QFile>\n\n#include <cubi.h>\n#include <ontologies.h>\n\n#include <QContactBirthday>\n#include <QContactDetailFilter>\n#include <QContactDisplayLabel>\n#include <QContactFetchRequest>\n#include <QContactLocalIdFilter>\n\n\nQTM_USE_NAMESPACE\n\nCUBI_USE_NAMESPACE\nCUBI_USE_NAMESPACE_RESOURCES\n\nusing namespace Contactsd;\n\n\/\/ The logic behind this class was strongly influenced by QctTrackerChangeListener in\n\/\/ qtcontacts-tracker.\nCDBirthdayController::CDBirthdayController(QSparqlConnection &connection,\n QObject *parent)\n : QObject(parent)\n , mSparqlConnection(connection)\n , mCalendar(0)\n , mManager(0)\n{\n const QLatin1String trackerManagerName = QLatin1String(\"tracker\");\n\n mManager = new QContactManager(trackerManagerName, QMap<QString, QString>(), this);\n\n if (mManager->managerName() != trackerManagerName) {\n debug() << Q_FUNC_INFO << \"Tracker plugin not found\";\n return;\n }\n\n fetchTrackerIds();\n\n if (not stampFileExists()) {\n \/\/ Delete the calendar database.\n mCalendar = new CDBirthdayCalendar(CDBirthdayCalendar::FullSync, this);\n\n updateAllBirthdays();\n } else {\n \/\/ Use the existing calendar database.\n mCalendar = new CDBirthdayCalendar(CDBirthdayCalendar::Incremental, this);\n }\n}\n\nCDBirthdayController::~CDBirthdayController()\n{\n}\n\nvoid\nCDBirthdayController::fetchTrackerIds()\n{\n \/\/ keep in sync with the enum in the header and NTrackerIds\n const QList<ResourceValue> resources = QList<ResourceValue>()\n << nco::birthDate::resource()\n << rdf::type::resource()\n << nco::PersonContact::resource()\n << nco::ContactGroup::resource();\n\n Select select;\n\n foreach (const ResourceValue &value, resources) {\n select.addProjection(Functions::trackerId.apply(value));\n }\n\n if (not mSparqlConnection.isValid()) {\n debug() << Q_FUNC_INFO << \"SPARQL connection is not valid\";\n return;\n }\n\n QScopedPointer<QSparqlResult> result(mSparqlConnection.exec(QSparqlQuery(select.sparql())));\n\n if (result->hasError()) {\n debug() << Q_FUNC_INFO << \"Could not fetch Tracker IDs:\" << result->lastError().message();\n return;\n }\n\n connect(result.take(), SIGNAL(finished()), this, SLOT(onTrackerIdsFetched()));\n}\n\nbool CDBirthdayController::stampFileExists()\n{\n const QFile cacheFile(stampFilePath(), this);\n\n return cacheFile.exists();\n}\n\nvoid CDBirthdayController::createStampFile()\n{\n QFile cacheFile(stampFilePath(), this);\n\n if (not cacheFile.exists()) {\n if (not cacheFile.open(QIODevice::WriteOnly)) {\n warning() << Q_FUNC_INFO << \"Unable to create birthday plugin stamp file \"\n << cacheFile.fileName() << \" with error \" << cacheFile.errorString();\n } else {\n cacheFile.close();\n }\n }\n}\n\nQString CDBirthdayController::stampFilePath() const\n{\n return BasePlugin::cacheFileName(QLatin1String(\"calendar.stamp\"));\n}\n\nvoid\nCDBirthdayController::updateAllBirthdays()\n{\n QContactFetchHint fetchHint;\n static const QStringList detailDefinitions = QStringList() << QContactBirthday::DefinitionName\n << QContactDisplayLabel::DefinitionName;\n fetchHint.setDetailDefinitionsHint(detailDefinitions);\n\n \/\/ Filter on any contact with a birthday.\n QContactDetailFilter fetchFilter;\n fetchFilter.setDetailDefinitionName(QContactBirthday::DefinitionName);\n\n QContactFetchRequest * const fetchRequest = new QContactFetchRequest(this);\n fetchRequest->setManager(mManager);\n fetchRequest->setFetchHint(fetchHint);\n fetchRequest->setFilter(fetchFilter);\n\n connect(fetchRequest,\n SIGNAL(stateChanged(QContactAbstractRequest::State)),\n SLOT(onFullSyncRequestStateChanged(QContactAbstractRequest::State)));\n\n if (not fetchRequest->start()) {\n warning() << Q_FUNC_INFO << \"Unable to start contact birthdays fetch request\";\n delete fetchRequest;\n return;\n }\n\n debug() << \"Contact birthdays fetch request started\";\n}\n\nvoid\nCDBirthdayController::onTrackerIdsFetched()\n{\n QSparqlResult *result = qobject_cast<QSparqlResult*>(sender());\n\n if (result == 0) {\n debug() << Q_FUNC_INFO << \"Invalid result\";\n return;\n }\n\n if (result->hasError()) {\n debug() << Q_FUNC_INFO << \"Could not fetch Tracker IDs:\" << result->lastError().message();\n } else if (not result->next()) {\n debug() << Q_FUNC_INFO << \"No results returned\";\n return;\n } else {\n const QSparqlResultRow row = result->current();\n\n for (int i = 0; i < NTrackerIds; ++i) {\n mTrackerIds[i] = row.value(i).toInt();\n }\n }\n\n \/\/ Provide hint we are done with this result.\n result->deleteLater();\n\n debug() << Q_FUNC_INFO << \"Tracker IDs fetched, connecting the change notifier\";\n\n connectChangeNotifier();\n}\n\nvoid\nCDBirthdayController::connectChangeNotifier()\n{\n const QStringList contactClassIris = QStringList()\n << nco::PersonContact::iri()\n << nco::ContactGroup::iri();\n\n foreach (const QString &iri, contactClassIris) {\n connect(new TrackerChangeNotifier(iri, this),\n SIGNAL(changed(QList<TrackerChangeNotifier::Quad>,\n QList<TrackerChangeNotifier::Quad>)),\n SLOT(onGraphChanged(QList<TrackerChangeNotifier::Quad>,\n QList<TrackerChangeNotifier::Quad>)));\n }\n}\n\nvoid CDBirthdayController::onGraphChanged(const QList<TrackerChangeNotifier::Quad>& deletions,\n const QList<TrackerChangeNotifier::Quad>& insertions)\n{\n mDeleteNotifications += deletions;\n mInsertNotifications += insertions;\n\n if (isDebugEnabled()) {\n TrackerChangeNotifier const * const notifier = qobject_cast<TrackerChangeNotifier *>(sender());\n\n if (notifier == 0) {\n warning() << Q_FUNC_INFO << \"Error casting birthday change notifier\";\n return;\n }\n\n debug() << notifier->watchedClass() << \"birthday: deletions:\" << deletions;\n debug() << notifier->watchedClass() << \"birthday: insertions:\" << insertions;\n }\n\n processNotificationQueues();\n}\n\nvoid\nCDBirthdayController::onFullSyncRequestStateChanged(QContactAbstractRequest::State newState)\n{\n QContactFetchRequest * const fetchRequest = qobject_cast<QContactFetchRequest*>(sender());\n\n if (not processFetchRequest(fetchRequest, newState)) {\n return;\n }\n\n updateBirthdays(fetchRequest->contacts());\n\n \/\/ Create the stamp file only after a successful full sync.\n createStampFile();\n}\n\nvoid\nCDBirthdayController::onFetchRequestStateChanged(QContactAbstractRequest::State newState)\n{\n QContactFetchRequest * const fetchRequest = qobject_cast<QContactFetchRequest*>(sender());\n\n if (not processFetchRequest(fetchRequest, newState)) {\n return;\n }\n\n updateBirthdays(fetchRequest->contacts());\n}\n\nbool\nCDBirthdayController::processFetchRequest(QContactFetchRequest * const fetchRequest,\n QContactAbstractRequest::State newState)\n{\n if (fetchRequest == 0) {\n warning() << Q_FUNC_INFO << \"Invalid fetch request\";\n return false;\n }\n\n bool success = false;\n\n switch (newState) {\n case QContactAbstractRequest::FinishedState:\n debug() << \"Birthday contacts fetch request finished\";\n\n if (fetchRequest->error() != QContactManager::NoError) {\n warning() << Q_FUNC_INFO << \"Error during birthday contact fetch request, code: \"\n << fetchRequest->error();\n } else {\n success = true;\n }\n\n break;\n\n case QContactAbstractRequest::CanceledState:\n break;\n\n default:\n return false;\n }\n\n \/\/ Provide hint we are done with this request.\n fetchRequest->deleteLater();\n\n return success;\n}\n\nvoid\nCDBirthdayController::processNotificationQueues()\n{\n QSet<QContactLocalId> insertedContacts;\n QSet<QContactLocalId> deletedContacts;\n QSet<QContactLocalId> birthdayChangedIds;\n\n \/\/ Process notification queues to determine contacts with changed birthdays.\n processNotifications(mDeleteNotifications, birthdayChangedIds, deletedContacts);\n processNotifications(mInsertNotifications, birthdayChangedIds, insertedContacts);\n\n if (isDebugEnabled()) {\n debug() << \"changed birthdates: \" << birthdayChangedIds.count() << birthdayChangedIds;\n }\n\n \/\/ Remove the birthdays for contacts that are not there anymore\n foreach (QContactLocalId id, deletedContacts) {\n mCalendar->deleteBirthday(id);\n }\n\n \/\/ Update the calendar with the birthday changes.\n if (not birthdayChangedIds.isEmpty()) {\n fetchContacts(birthdayChangedIds.toList());\n }\n}\n\nvoid\nCDBirthdayController::processNotifications(QList<TrackerChangeNotifier::Quad> ¬ifications,\n QSet<QContactLocalId> &propertyChanges,\n QSet<QContactLocalId> &resourceChanges)\n{\n foreach (const TrackerChangeNotifier::Quad &quad, notifications) {\n if (quad.predicate == mTrackerIds[NcoBirthDate]) {\n propertyChanges += quad.subject;\n continue;\n }\n\n if (quad.predicate == mTrackerIds[RdfType]) {\n if (quad.object == mTrackerIds[NcoPersonContact]\n || quad.object == mTrackerIds[NcoContactGroup]) {\n resourceChanges += quad.subject;\n }\n }\n }\n\n \/\/ Remove the processed notifications.\n notifications.clear();\n}\n\nvoid\nCDBirthdayController::fetchContacts(const QList<QContactLocalId> &contactIds)\n{\n QContactFetchHint fetchHint;\n static const QStringList detailDefinitions = QStringList() << QContactBirthday::DefinitionName\n << QContactDisplayLabel::DefinitionName;\n fetchHint.setDetailDefinitionsHint(detailDefinitions);\n\n QContactLocalIdFilter fetchFilter;\n fetchFilter.setIds(contactIds);\n\n QContactFetchRequest * const fetchRequest = new QContactFetchRequest(this);\n fetchRequest->setManager(mManager);\n fetchRequest->setFetchHint(fetchHint);\n fetchRequest->setFilter(fetchFilter);\n\n connect(fetchRequest,\n SIGNAL(stateChanged(QContactAbstractRequest::State)),\n SLOT(onFetchRequestStateChanged(QContactAbstractRequest::State)));\n\n if (not fetchRequest->start()) {\n warning() << Q_FUNC_INFO << \"Unable to start birthday contact fetch request\";\n delete fetchRequest;\n return;\n }\n\n debug() << \"Birthday contacts fetch request started\";\n}\n\nvoid\nCDBirthdayController::updateBirthdays(const QList<QContact> &changedBirthdays)\n{\n foreach (const QContact &contact, changedBirthdays) {\n const QContactBirthday contactBirthday = contact.detail<QContactBirthday>();\n const QContactDisplayLabel contactDisplayLabel = contact.detail<QContactDisplayLabel>();\n const QDate calendarBirthday = mCalendar->birthdayDate(contact.localId());\n const QString calendarSummary = mCalendar->summary(contact.localId());\n\n \/\/ Display label or birthdate was removed from the contact, so delete it from the calendar.\n if (contactDisplayLabel.label().isNull() || contactBirthday.date().isNull()) {\n if (isDebugEnabled()) {\n debug() << \"Contact: \" << contact << \" removed birthday or displayLabel, so delete the calendar event\";\n }\n\n mCalendar->deleteBirthday(contact.localId());\n \/\/ Display label or birthdate was changed on the contact, so update the calendar.\n } else if ((contactDisplayLabel.label() != calendarSummary) ||\n (contactBirthday.date() != calendarBirthday)) {\n if (isDebugEnabled()) {\n debug() << \"Contact with calendar birthday: \" << contactBirthday.date()\n << \" and calendar displayLabel: \" << calendarSummary\n << \" changed details to: \" << contact << \", so update the calendar event\";\n }\n\n mCalendar->updateBirthday(contact);\n }\n }\n}\n<commit_msg>Fixes: Reorder birthday controller methods to have a chance understanding it<commit_after>\/** This file is part of Contacts daemon\n **\n ** Copyright (c) 2010-2011 Nokia Corporation and\/or its subsidiary(-ies).\n **\n ** Contact: Nokia Corporation (info@qt.nokia.com)\n **\n ** GNU Lesser General Public License Usage\n ** This file may be used under the terms of the GNU Lesser General Public License\n ** version 2.1 as published by the Free Software Foundation and appearing in the\n ** file LICENSE.LGPL included in the packaging of this file. Please review the\n ** following information to ensure the GNU Lesser General Public License version\n ** 2.1 requirements will be met:\n ** http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n **\n ** In addition, as a special exception, Nokia gives you certain additional rights.\n ** These rights are described in the Nokia Qt LGPL Exception version 1.1, included\n ** in the file LGPL_EXCEPTION.txt in this package.\n **\n ** Other Usage\n ** Alternatively, this file may be used in accordance with the terms and\n ** conditions contained in a signed written agreement between you and Nokia.\n **\/\n\n#include \"cdbirthdaycontroller.h\"\n#include \"cdbirthdaycalendar.h\"\n#include \"cdbirthdayplugin.h\"\n#include \"debug.h\"\n\n#include <QDir>\n#include <QFile>\n\n#include <cubi.h>\n#include <ontologies.h>\n\n#include <QContactBirthday>\n#include <QContactDetailFilter>\n#include <QContactDisplayLabel>\n#include <QContactFetchRequest>\n#include <QContactLocalIdFilter>\n\n\nQTM_USE_NAMESPACE\n\nCUBI_USE_NAMESPACE\nCUBI_USE_NAMESPACE_RESOURCES\n\nusing namespace Contactsd;\n\n\/\/ The logic behind this class was strongly influenced by QctTrackerChangeListener in\n\/\/ qtcontacts-tracker.\nCDBirthdayController::CDBirthdayController(QSparqlConnection &connection,\n QObject *parent)\n : QObject(parent)\n , mSparqlConnection(connection)\n , mCalendar(0)\n , mManager(0)\n{\n const QLatin1String trackerManagerName = QLatin1String(\"tracker\");\n\n mManager = new QContactManager(trackerManagerName, QMap<QString, QString>(), this);\n\n if (mManager->managerName() != trackerManagerName) {\n debug() << Q_FUNC_INFO << \"Tracker plugin not found\";\n return;\n }\n\n fetchTrackerIds();\n\n if (not stampFileExists()) {\n \/\/ Delete the calendar database.\n mCalendar = new CDBirthdayCalendar(CDBirthdayCalendar::FullSync, this);\n\n updateAllBirthdays();\n } else {\n \/\/ Use the existing calendar database.\n mCalendar = new CDBirthdayCalendar(CDBirthdayCalendar::Incremental, this);\n }\n}\n\nCDBirthdayController::~CDBirthdayController()\n{\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Tracker ID fetching\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid\nCDBirthdayController::fetchTrackerIds()\n{\n \/\/ keep in sync with the enum in the header and NTrackerIds\n const QList<ResourceValue> resources = QList<ResourceValue>()\n << nco::birthDate::resource()\n << rdf::type::resource()\n << nco::PersonContact::resource()\n << nco::ContactGroup::resource();\n\n Select select;\n\n foreach (const ResourceValue &value, resources) {\n select.addProjection(Functions::trackerId.apply(value));\n }\n\n if (not mSparqlConnection.isValid()) {\n debug() << Q_FUNC_INFO << \"SPARQL connection is not valid\";\n return;\n }\n\n QScopedPointer<QSparqlResult> result(mSparqlConnection.exec(QSparqlQuery(select.sparql())));\n\n if (result->hasError()) {\n debug() << Q_FUNC_INFO << \"Could not fetch Tracker IDs:\" << result->lastError().message();\n return;\n }\n\n connect(result.take(), SIGNAL(finished()), this, SLOT(onTrackerIdsFetched()));\n}\n\nvoid\nCDBirthdayController::onTrackerIdsFetched()\n{\n QSparqlResult *result = qobject_cast<QSparqlResult*>(sender());\n\n if (result == 0) {\n debug() << Q_FUNC_INFO << \"Invalid result\";\n return;\n }\n\n if (result->hasError()) {\n debug() << Q_FUNC_INFO << \"Could not fetch Tracker IDs:\" << result->lastError().message();\n } else if (not result->next()) {\n debug() << Q_FUNC_INFO << \"No results returned\";\n return;\n } else {\n const QSparqlResultRow row = result->current();\n\n for (int i = 0; i < NTrackerIds; ++i) {\n mTrackerIds[i] = row.value(i).toInt();\n }\n }\n\n \/\/ Provide hint we are done with this result.\n result->deleteLater();\n\n debug() << Q_FUNC_INFO << \"Tracker IDs fetched, connecting the change notifier\";\n\n connectChangeNotifier();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Contact monitor\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid\nCDBirthdayController::connectChangeNotifier()\n{\n const QStringList contactClassIris = QStringList()\n << nco::PersonContact::iri()\n << nco::ContactGroup::iri();\n\n foreach (const QString &iri, contactClassIris) {\n connect(new TrackerChangeNotifier(iri, this),\n SIGNAL(changed(QList<TrackerChangeNotifier::Quad>,\n QList<TrackerChangeNotifier::Quad>)),\n SLOT(onGraphChanged(QList<TrackerChangeNotifier::Quad>,\n QList<TrackerChangeNotifier::Quad>)));\n }\n}\n\nvoid\nCDBirthdayController::onGraphChanged(const QList<TrackerChangeNotifier::Quad>& deletions,\n const QList<TrackerChangeNotifier::Quad>& insertions)\n{\n mDeleteNotifications += deletions;\n mInsertNotifications += insertions;\n\n if (isDebugEnabled()) {\n TrackerChangeNotifier const * const notifier = qobject_cast<TrackerChangeNotifier *>(sender());\n\n if (notifier == 0) {\n warning() << Q_FUNC_INFO << \"Error casting birthday change notifier\";\n return;\n }\n\n debug() << notifier->watchedClass() << \"birthday: deletions:\" << deletions;\n debug() << notifier->watchedClass() << \"birthday: insertions:\" << insertions;\n }\n\n processNotificationQueues();\n}\n\nvoid\nCDBirthdayController::processNotifications(QList<TrackerChangeNotifier::Quad> ¬ifications,\n QSet<QContactLocalId> &propertyChanges,\n QSet<QContactLocalId> &resourceChanges)\n{\n foreach (const TrackerChangeNotifier::Quad &quad, notifications) {\n if (quad.predicate == mTrackerIds[NcoBirthDate]) {\n propertyChanges += quad.subject;\n continue;\n }\n\n if (quad.predicate == mTrackerIds[RdfType]) {\n if (quad.object == mTrackerIds[NcoPersonContact]\n || quad.object == mTrackerIds[NcoContactGroup]) {\n resourceChanges += quad.subject;\n }\n }\n }\n\n \/\/ Remove the processed notifications.\n notifications.clear();\n}\n\nvoid\nCDBirthdayController::processNotificationQueues()\n{\n QSet<QContactLocalId> insertedContacts;\n QSet<QContactLocalId> deletedContacts;\n QSet<QContactLocalId> birthdayChangedIds;\n\n \/\/ Process notification queues to determine contacts with changed birthdays.\n processNotifications(mDeleteNotifications, birthdayChangedIds, deletedContacts);\n processNotifications(mInsertNotifications, birthdayChangedIds, insertedContacts);\n\n if (isDebugEnabled()) {\n debug() << \"changed birthdates: \" << birthdayChangedIds.count() << birthdayChangedIds;\n }\n\n \/\/ Remove the birthdays for contacts that are not there anymore\n foreach (QContactLocalId id, deletedContacts) {\n mCalendar->deleteBirthday(id);\n }\n\n \/\/ Update the calendar with the birthday changes.\n if (not birthdayChangedIds.isEmpty()) {\n fetchContacts(birthdayChangedIds.toList());\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Full sync logic\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nbool\nCDBirthdayController::stampFileExists()\n{\n const QFile cacheFile(stampFilePath(), this);\n\n return cacheFile.exists();\n}\n\nvoid\nCDBirthdayController::createStampFile()\n{\n QFile cacheFile(stampFilePath(), this);\n\n if (not cacheFile.exists()) {\n if (not cacheFile.open(QIODevice::WriteOnly)) {\n warning() << Q_FUNC_INFO << \"Unable to create birthday plugin stamp file \"\n << cacheFile.fileName() << \" with error \" << cacheFile.errorString();\n } else {\n cacheFile.close();\n }\n }\n}\n\nQString\nCDBirthdayController::stampFilePath() const\n{\n return BasePlugin::cacheFileName(QLatin1String(\"calendar.stamp\"));\n}\n\nvoid\nCDBirthdayController::updateAllBirthdays()\n{\n QContactFetchHint fetchHint;\n static const QStringList detailDefinitions = QStringList() << QContactBirthday::DefinitionName\n << QContactDisplayLabel::DefinitionName;\n fetchHint.setDetailDefinitionsHint(detailDefinitions);\n\n \/\/ Filter on any contact with a birthday.\n QContactDetailFilter fetchFilter;\n fetchFilter.setDetailDefinitionName(QContactBirthday::DefinitionName);\n\n QContactFetchRequest * const fetchRequest = new QContactFetchRequest(this);\n fetchRequest->setManager(mManager);\n fetchRequest->setFetchHint(fetchHint);\n fetchRequest->setFilter(fetchFilter);\n\n connect(fetchRequest,\n SIGNAL(stateChanged(QContactAbstractRequest::State)),\n SLOT(onFullSyncRequestStateChanged(QContactAbstractRequest::State)));\n\n if (not fetchRequest->start()) {\n warning() << Q_FUNC_INFO << \"Unable to start contact birthdays fetch request\";\n delete fetchRequest;\n return;\n }\n\n debug() << \"Contact birthdays fetch request started\";\n}\n\nvoid\nCDBirthdayController::onFullSyncRequestStateChanged(QContactAbstractRequest::State newState)\n{\n QContactFetchRequest * const fetchRequest = qobject_cast<QContactFetchRequest*>(sender());\n\n if (not processFetchRequest(fetchRequest, newState)) {\n return;\n }\n\n updateBirthdays(fetchRequest->contacts());\n\n \/\/ Create the stamp file only after a successful full sync.\n createStampFile();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Incremental sync logic\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid\nCDBirthdayController::fetchContacts(const QList<QContactLocalId> &contactIds)\n{\n QContactFetchHint fetchHint;\n static const QStringList detailDefinitions = QStringList() << QContactBirthday::DefinitionName\n << QContactDisplayLabel::DefinitionName;\n fetchHint.setDetailDefinitionsHint(detailDefinitions);\n\n QContactLocalIdFilter fetchFilter;\n fetchFilter.setIds(contactIds);\n\n QContactFetchRequest * const fetchRequest = new QContactFetchRequest(this);\n fetchRequest->setManager(mManager);\n fetchRequest->setFetchHint(fetchHint);\n fetchRequest->setFilter(fetchFilter);\n\n connect(fetchRequest,\n SIGNAL(stateChanged(QContactAbstractRequest::State)),\n SLOT(onFetchRequestStateChanged(QContactAbstractRequest::State)));\n\n if (not fetchRequest->start()) {\n warning() << Q_FUNC_INFO << \"Unable to start birthday contact fetch request\";\n delete fetchRequest;\n return;\n }\n\n debug() << \"Birthday contacts fetch request started\";\n}\n\nvoid\nCDBirthdayController::onFetchRequestStateChanged(QContactAbstractRequest::State newState)\n{\n QContactFetchRequest * const fetchRequest = qobject_cast<QContactFetchRequest*>(sender());\n\n if (not processFetchRequest(fetchRequest, newState)) {\n return;\n }\n\n updateBirthdays(fetchRequest->contacts());\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Common sync logic\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nbool\nCDBirthdayController::processFetchRequest(QContactFetchRequest * const fetchRequest,\n QContactAbstractRequest::State newState)\n{\n if (fetchRequest == 0) {\n warning() << Q_FUNC_INFO << \"Invalid fetch request\";\n return false;\n }\n\n bool success = false;\n\n switch (newState) {\n case QContactAbstractRequest::FinishedState:\n debug() << \"Birthday contacts fetch request finished\";\n\n if (fetchRequest->error() != QContactManager::NoError) {\n warning() << Q_FUNC_INFO << \"Error during birthday contact fetch request, code: \"\n << fetchRequest->error();\n } else {\n success = true;\n }\n\n break;\n\n case QContactAbstractRequest::CanceledState:\n break;\n\n default:\n return false;\n }\n\n \/\/ Provide hint we are done with this request.\n fetchRequest->deleteLater();\n\n return success;\n}\n\nvoid\nCDBirthdayController::updateBirthdays(const QList<QContact> &changedBirthdays)\n{\n foreach (const QContact &contact, changedBirthdays) {\n const QContactBirthday contactBirthday = contact.detail<QContactBirthday>();\n const QContactDisplayLabel contactDisplayLabel = contact.detail<QContactDisplayLabel>();\n const QDate calendarBirthday = mCalendar->birthdayDate(contact.localId());\n const QString calendarSummary = mCalendar->summary(contact.localId());\n\n \/\/ Display label or birthdate was removed from the contact, so delete it from the calendar.\n if (contactDisplayLabel.label().isNull() || contactBirthday.date().isNull()) {\n if (isDebugEnabled()) {\n debug() << \"Contact: \" << contact << \" removed birthday or displayLabel, so delete the calendar event\";\n }\n\n mCalendar->deleteBirthday(contact.localId());\n \/\/ Display label or birthdate was changed on the contact, so update the calendar.\n } else if ((contactDisplayLabel.label() != calendarSummary) ||\n (contactBirthday.date() != calendarBirthday)) {\n if (isDebugEnabled()) {\n debug() << \"Contact with calendar birthday: \" << contactBirthday.date()\n << \" and calendar displayLabel: \" << calendarSummary\n << \" changed details to: \" << contact << \", so update the calendar event\";\n }\n\n mCalendar->updateBirthday(contact);\n }\n }\n}\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n\nstruct node\n{\n int data;\n node* left;\n node* right;\n};\n\nvoid preOrder(node *root) {\n if (root == NULL) return;\n std::cout<<root->data<<\" \";\n preOrder(root->left);\n preOrder(root->right);\n}\n\nvoid inOrder(node *root) {\n\tif (root == NULL) return;\n\tinOrder(root->left);\n\tstd::cout<<root->data<<\" \";\n\tinOrder(root->right);\n}\n\nvoid postOrder(node *root) {\n if (root == NULL) return;\n postOrder(root->left);\n postOrder(root->right);\n std::cout<<root->data<<\" \";\n}<commit_msg>added height in tree.cpp<commit_after>#include <iostream>\n\nstruct node\n{\n int data;\n node* left;\n node* right;\n};\n\nvoid preOrder(node *root) {\n if (root == NULL) return;\n std::cout<<root->data<<\" \";\n preOrder(root->left);\n preOrder(root->right);\n}\n\nvoid inOrder(node *root) {\n\tif (root == NULL) return;\n\tinOrder(root->left);\n\tstd::cout<<root->data<<\" \";\n\tinOrder(root->right);\n}\n\nvoid postOrder(node *root) {\n if (root == NULL) return;\n postOrder(root->left);\n postOrder(root->right);\n std::cout<<root->data<<\" \";\n}\n\nint height(Node* root) {\n if (root == NULL) return 0;\n return max(height(root->left), height(root->right)) + 1;\n }<|endoftext|>"} {"text":"<commit_before>#ifndef RAPIDXML_PRINT_HPP_INCLUDED\n#define RAPIDXML_PRINT_HPP_INCLUDED\n\n\/\/ Copyright (C) 2006, 2009 Marcin Kalicinski\n\/\/ Version 1.13\n\/\/ Revision $DateTime: 2009\/05\/13 01:46:17 $\n\/\/! \\file rapidxml_print.hpp This file contains rapidxml printer implementation\n\n#include \"rapidxml.hpp\"\n\n\/\/ Only include streams if not disabled\n#ifndef RAPIDXML_NO_STREAMS\n #include <ostream>\n #include <iterator>\n#endif\n\nnamespace rapidxml\n{\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ Printing flags\n\n const int print_no_indenting = 0x1; \/\/!< Printer flag instructing the printer to suppress indenting of XML. See print() function.\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ Internal\n\n \/\/! \\cond internal\n namespace internal\n {\n \n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ Internal character operations\n \n \/\/ Copy characters from given range to given output iterator\n template<class OutIt, class Ch>\n inline OutIt copy_chars(const Ch *begin, const Ch *end, OutIt out)\n {\n while (begin != end)\n *out++ = *begin++;\n return out;\n }\n \n \/\/ Copy characters from given range to given output iterator and expand\n \/\/ characters into references (< > ' " &)\n template<class OutIt, class Ch>\n inline OutIt copy_and_expand_chars(const Ch *begin, const Ch *end, Ch noexpand, OutIt out)\n {\n while (begin != end)\n {\n if (*begin == noexpand)\n {\n *out++ = *begin; \/\/ No expansion, copy character\n }\n else\n {\n switch (*begin)\n {\n case Ch('<'):\n *out++ = Ch('&'); *out++ = Ch('l'); *out++ = Ch('t'); *out++ = Ch(';');\n break;\n case Ch('>'): \n *out++ = Ch('&'); *out++ = Ch('g'); *out++ = Ch('t'); *out++ = Ch(';');\n break;\n case Ch('\\''): \n *out++ = Ch('&'); *out++ = Ch('a'); *out++ = Ch('p'); *out++ = Ch('o'); *out++ = Ch('s'); *out++ = Ch(';');\n break;\n case Ch('\"'): \n *out++ = Ch('&'); *out++ = Ch('q'); *out++ = Ch('u'); *out++ = Ch('o'); *out++ = Ch('t'); *out++ = Ch(';');\n break;\n case Ch('&'): \n *out++ = Ch('&'); *out++ = Ch('a'); *out++ = Ch('m'); *out++ = Ch('p'); *out++ = Ch(';'); \n break;\n default:\n *out++ = *begin; \/\/ No expansion, copy character\n }\n }\n ++begin; \/\/ Step to next character\n }\n return out;\n }\n\n \/\/ Fill given output iterator with repetitions of the same character\n template<class OutIt, class Ch>\n inline OutIt fill_chars(OutIt out, int n, Ch ch)\n {\n for (int i = 0; i < n; ++i)\n *out++ = ch;\n return out;\n }\n\n \/\/ Find character\n template<class Ch, Ch ch>\n inline bool find_char(const Ch *begin, const Ch *end)\n {\n while (begin != end)\n if (*begin++ == ch)\n return true;\n return false;\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ Internal printing operations\n \n \/\/ Print node\n template<class OutIt, class Ch>\n inline OutIt print_node(OutIt out, const xml_node<Ch> *node, int flags, int indent)\n {\n \/\/ Print proper node type\n switch (node->type())\n {\n\n \/\/ Document\n case node_document:\n out = print_children(out, node, flags, indent);\n break;\n\n \/\/ Element\n case node_element:\n out = print_element_node(out, node, flags, indent);\n break;\n \n \/\/ Data\n case node_data:\n out = print_data_node(out, node, flags, indent);\n break;\n \n \/\/ CDATA\n case node_cdata:\n out = print_cdata_node(out, node, flags, indent);\n break;\n\n \/\/ Declaration\n case node_declaration:\n out = print_declaration_node(out, node, flags, indent);\n break;\n\n \/\/ Comment\n case node_comment:\n out = print_comment_node(out, node, flags, indent);\n break;\n \n \/\/ Doctype\n case node_doctype:\n out = print_doctype_node(out, node, flags, indent);\n break;\n\n \/\/ Pi\n case node_pi:\n out = print_pi_node(out, node, flags, indent);\n break;\n\n \/\/ Unknown\n default:\n assert(0);\n break;\n }\n \n \/\/ If indenting not disabled, add line break after node\n if (!(flags & print_no_indenting))\n *out = Ch('\\n'), ++out;\n\n \/\/ Return modified iterator\n return out;\n }\n \n \/\/ Print children of the node \n template<class OutIt, class Ch>\n inline OutIt print_children(OutIt out, const xml_node<Ch> *node, int flags, int indent)\n {\n for (xml_node<Ch> *child = node->first_node(); child; child = child->next_sibling())\n out = print_node(out, child, flags, indent);\n return out;\n }\n\n \/\/ Print attributes of the node\n template<class OutIt, class Ch>\n inline OutIt print_attributes(OutIt out, const xml_node<Ch> *node, int flags)\n {\n for (xml_attribute<Ch> *attribute = node->first_attribute(); attribute; attribute = attribute->next_attribute())\n {\n if (attribute->name() && attribute->value())\n {\n \/\/ Print attribute name\n *out = Ch(' '), ++out;\n out = copy_chars(attribute->name(), attribute->name() + attribute->name_size(), out);\n *out = Ch('='), ++out;\n \/\/ Print attribute value using appropriate quote type\n if (find_char<Ch, Ch('\"')>(attribute->value(), attribute->value() + attribute->value_size()))\n {\n *out = Ch('\\''), ++out;\n out = copy_and_expand_chars(attribute->value(), attribute->value() + attribute->value_size(), Ch('\"'), out);\n *out = Ch('\\''), ++out;\n }\n else\n {\n *out = Ch('\"'), ++out;\n out = copy_and_expand_chars(attribute->value(), attribute->value() + attribute->value_size(), Ch('\\''), out);\n *out = Ch('\"'), ++out;\n }\n }\n }\n return out;\n }\n\n \/\/ Print data node\n template<class OutIt, class Ch>\n inline OutIt print_data_node(OutIt out, const xml_node<Ch> *node, int flags, int indent)\n {\n assert(node->type() == node_data);\n if (!(flags & print_no_indenting))\n out = fill_chars(out, indent, Ch('\\t'));\n out = copy_and_expand_chars(node->value(), node->value() + node->value_size(), Ch(0), out);\n return out;\n }\n\n \/\/ Print data node\n template<class OutIt, class Ch>\n inline OutIt print_cdata_node(OutIt out, const xml_node<Ch> *node, int flags, int indent)\n {\n assert(node->type() == node_cdata);\n if (!(flags & print_no_indenting))\n out = fill_chars(out, indent, Ch('\\t'));\n *out = Ch('<'); ++out;\n *out = Ch('!'); ++out;\n *out = Ch('['); ++out;\n *out = Ch('C'); ++out;\n *out = Ch('D'); ++out;\n *out = Ch('A'); ++out;\n *out = Ch('T'); ++out;\n *out = Ch('A'); ++out;\n *out = Ch('['); ++out;\n out = copy_chars(node->value(), node->value() + node->value_size(), out);\n *out = Ch(']'); ++out;\n *out = Ch(']'); ++out;\n *out = Ch('>'); ++out;\n return out;\n }\n\n \/\/ Print element node\n template<class OutIt, class Ch>\n inline OutIt print_element_node(OutIt out, const xml_node<Ch> *node, int flags, int indent)\n {\n assert(node->type() == node_element);\n\n \/\/ Print element name and attributes, if any\n if (!(flags & print_no_indenting))\n out = fill_chars(out, indent, Ch('\\t'));\n *out = Ch('<'), ++out;\n out = copy_chars(node->name(), node->name() + node->name_size(), out);\n out = print_attributes(out, node, flags);\n \n \/\/ If node is childless\n if (node->value_size() == 0 && !node->first_node())\n {\n \/\/ Print childless node tag ending\n *out = Ch('\/'), ++out;\n *out = Ch('>'), ++out;\n }\n else\n {\n \/\/ Print normal node tag ending\n *out = Ch('>'), ++out;\n\n \/\/ Test if node contains a single data node only (and no other nodes)\n xml_node<Ch> *child = node->first_node();\n if (!child)\n {\n \/\/ If node has no children, only print its value without indenting\n out = copy_and_expand_chars(node->value(), node->value() + node->value_size(), Ch(0), out);\n }\n else if (child->next_sibling() == 0 && child->type() == node_data)\n {\n \/\/ If node has a sole data child, only print its value without indenting\n out = copy_and_expand_chars(child->value(), child->value() + child->value_size(), Ch(0), out);\n }\n else\n {\n \/\/ Print all children with full indenting\n if (!(flags & print_no_indenting))\n *out = Ch('\\n'), ++out;\n out = print_children(out, node, flags, indent + 1);\n if (!(flags & print_no_indenting))\n out = fill_chars(out, indent, Ch('\\t'));\n }\n\n \/\/ Print node end\n *out = Ch('<'), ++out;\n *out = Ch('\/'), ++out;\n out = copy_chars(node->name(), node->name() + node->name_size(), out);\n *out = Ch('>'), ++out;\n }\n return out;\n }\n\n \/\/ Print declaration node\n template<class OutIt, class Ch>\n inline OutIt print_declaration_node(OutIt out, const xml_node<Ch> *node, int flags, int indent)\n {\n \/\/ Print declaration start\n if (!(flags & print_no_indenting))\n out = fill_chars(out, indent, Ch('\\t'));\n *out = Ch('<'), ++out;\n *out = Ch('?'), ++out;\n *out = Ch('x'), ++out;\n *out = Ch('m'), ++out;\n *out = Ch('l'), ++out;\n\n \/\/ Print attributes\n out = print_attributes(out, node, flags);\n \n \/\/ Print declaration end\n *out = Ch('?'), ++out;\n *out = Ch('>'), ++out;\n \n return out;\n }\n\n \/\/ Print comment node\n template<class OutIt, class Ch>\n inline OutIt print_comment_node(OutIt out, const xml_node<Ch> *node, int flags, int indent)\n {\n assert(node->type() == node_comment);\n if (!(flags & print_no_indenting))\n out = fill_chars(out, indent, Ch('\\t'));\n *out = Ch('<'), ++out;\n *out = Ch('!'), ++out;\n *out = Ch('-'), ++out;\n *out = Ch('-'), ++out;\n out = copy_chars(node->value(), node->value() + node->value_size(), out);\n *out = Ch('-'), ++out;\n *out = Ch('-'), ++out;\n *out = Ch('>'), ++out;\n return out;\n }\n\n \/\/ Print doctype node\n template<class OutIt, class Ch>\n inline OutIt print_doctype_node(OutIt out, const xml_node<Ch> *node, int flags, int indent)\n {\n assert(node->type() == node_doctype);\n if (!(flags & print_no_indenting))\n out = fill_chars(out, indent, Ch('\\t'));\n *out = Ch('<'), ++out;\n *out = Ch('!'), ++out;\n *out = Ch('D'), ++out;\n *out = Ch('O'), ++out;\n *out = Ch('C'), ++out;\n *out = Ch('T'), ++out;\n *out = Ch('Y'), ++out;\n *out = Ch('P'), ++out;\n *out = Ch('E'), ++out;\n *out = Ch(' '), ++out;\n out = copy_chars(node->value(), node->value() + node->value_size(), out);\n *out = Ch('>'), ++out;\n return out;\n }\n\n \/\/ Print pi node\n template<class OutIt, class Ch>\n inline OutIt print_pi_node(OutIt out, const xml_node<Ch> *node, int flags, int indent)\n {\n assert(node->type() == node_pi);\n if (!(flags & print_no_indenting))\n out = fill_chars(out, indent, Ch('\\t'));\n *out = Ch('<'), ++out;\n *out = Ch('?'), ++out;\n out = copy_chars(node->name(), node->name() + node->name_size(), out);\n *out = Ch(' '), ++out;\n out = copy_chars(node->value(), node->value() + node->value_size(), out);\n *out = Ch('?'), ++out;\n *out = Ch('>'), ++out;\n return out;\n }\n\n }\n \/\/! \\endcond\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ Printing\n\n \/\/! Prints XML to given output iterator.\n \/\/! \\param out Output iterator to print to.\n \/\/! \\param node Node to be printed. Pass xml_document to print entire document.\n \/\/! \\param flags Flags controlling how XML is printed.\n \/\/! \\return Output iterator pointing to position immediately after last character of printed text.\n template<class OutIt, class Ch> \n inline OutIt print(OutIt out, const xml_node<Ch> &node, int flags = 0)\n {\n return internal::print_node(out, &node, flags, 0);\n }\n\n#ifndef RAPIDXML_NO_STREAMS\n\n \/\/! Prints XML to given output stream.\n \/\/! \\param out Output stream to print to.\n \/\/! \\param node Node to be printed. Pass xml_document to print entire document.\n \/\/! \\param flags Flags controlling how XML is printed.\n \/\/! \\return Output stream.\n template<class Ch> \n inline std::basic_ostream<Ch> &print(std::basic_ostream<Ch> &out, const xml_node<Ch> &node, int flags = 0)\n {\n print(std::ostream_iterator<Ch>(out), node, flags);\n return out;\n }\n\n \/\/! Prints formatted XML to given output stream. Uses default printing flags. Use print() function to customize printing process.\n \/\/! \\param out Output stream to print to.\n \/\/! \\param node Node to be printed.\n \/\/! \\return Output stream.\n template<class Ch> \n inline std::basic_ostream<Ch> &operator <<(std::basic_ostream<Ch> &out, const xml_node<Ch> &node)\n {\n return print(out, node);\n }\n\n#endif\n\n}\n\n#endif\n<commit_msg>Fixed compilation error with GCC >= 4.7<commit_after>#ifndef RAPIDXML_PRINT_HPP_INCLUDED\n#define RAPIDXML_PRINT_HPP_INCLUDED\n\n\/\/ Copyright (C) 2006, 2009 Marcin Kalicinski\n\/\/ Version 1.13\n\/\/ Revision $DateTime: 2009\/05\/13 01:46:17 $\n\/\/! \\file rapidxml_print.hpp This file contains rapidxml printer implementation\n\n#include \"rapidxml.hpp\"\n\n\/\/ Only include streams if not disabled\n#ifndef RAPIDXML_NO_STREAMS\n #include <ostream>\n #include <iterator>\n#endif\n\nnamespace rapidxml\n{\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ Printing flags\n\n const int print_no_indenting = 0x1; \/\/!< Printer flag instructing the printer to suppress indenting of XML. See print() function.\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ Internal\n\n \/\/! \\cond internal\n namespace internal\n {\n \n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ Internal character operations\n \n \/\/ Copy characters from given range to given output iterator\n template<class OutIt, class Ch>\n inline OutIt copy_chars(const Ch *begin, const Ch *end, OutIt out)\n {\n while (begin != end)\n *out++ = *begin++;\n return out;\n }\n \n \/\/ Copy characters from given range to given output iterator and expand\n \/\/ characters into references (< > ' " &)\n template<class OutIt, class Ch>\n inline OutIt copy_and_expand_chars(const Ch *begin, const Ch *end, Ch noexpand, OutIt out)\n {\n while (begin != end)\n {\n if (*begin == noexpand)\n {\n *out++ = *begin; \/\/ No expansion, copy character\n }\n else\n {\n switch (*begin)\n {\n case Ch('<'):\n *out++ = Ch('&'); *out++ = Ch('l'); *out++ = Ch('t'); *out++ = Ch(';');\n break;\n case Ch('>'): \n *out++ = Ch('&'); *out++ = Ch('g'); *out++ = Ch('t'); *out++ = Ch(';');\n break;\n case Ch('\\''): \n *out++ = Ch('&'); *out++ = Ch('a'); *out++ = Ch('p'); *out++ = Ch('o'); *out++ = Ch('s'); *out++ = Ch(';');\n break;\n case Ch('\"'): \n *out++ = Ch('&'); *out++ = Ch('q'); *out++ = Ch('u'); *out++ = Ch('o'); *out++ = Ch('t'); *out++ = Ch(';');\n break;\n case Ch('&'): \n *out++ = Ch('&'); *out++ = Ch('a'); *out++ = Ch('m'); *out++ = Ch('p'); *out++ = Ch(';'); \n break;\n default:\n *out++ = *begin; \/\/ No expansion, copy character\n }\n }\n ++begin; \/\/ Step to next character\n }\n return out;\n }\n\n \/\/ Fill given output iterator with repetitions of the same character\n template<class OutIt, class Ch>\n inline OutIt fill_chars(OutIt out, int n, Ch ch)\n {\n for (int i = 0; i < n; ++i)\n *out++ = ch;\n return out;\n }\n\n \/\/ Find character\n template<class Ch, Ch ch>\n inline bool find_char(const Ch *begin, const Ch *end)\n {\n while (begin != end)\n if (*begin++ == ch)\n return true;\n return false;\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ Internal printing operations\n \n template<class OutIt, class Ch>\n inline OutIt print_children(OutIt out, const xml_node<Ch> *node, int flags, int indent);\n\n template<class OutIt, class Ch>\n inline OutIt print_attributes(OutIt out, const xml_node<Ch> *node, int flags);\n\n template<class OutIt, class Ch>\n inline OutIt print_data_node(OutIt out, const xml_node<Ch> *node, int flags, int indent);\n\n template<class OutIt, class Ch>\n inline OutIt print_cdata_node(OutIt out, const xml_node<Ch> *node, int flags, int indent);\n\n template<class OutIt, class Ch>\n inline OutIt print_element_node(OutIt out, const xml_node<Ch> *node, int flags, int indent);\n\n template<class OutIt, class Ch>\n inline OutIt print_declaration_node(OutIt out, const xml_node<Ch> *node, int flags, int indent);\n\n template<class OutIt, class Ch>\n inline OutIt print_comment_node(OutIt out, const xml_node<Ch> *node, int flags, int indent);\n\n template<class OutIt, class Ch>\n inline OutIt print_doctype_node(OutIt out, const xml_node<Ch> *node, int flags, int indent);\n\n template<class OutIt, class Ch>\n inline OutIt print_pi_node(OutIt out, const xml_node<Ch> *node, int flags, int indent);\n\n \/\/ Print node\n template<class OutIt, class Ch>\n inline OutIt print_node(OutIt out, const xml_node<Ch> *node, int flags, int indent)\n {\n \/\/ Print proper node type\n switch (node->type())\n {\n\n \/\/ Document\n case node_document:\n out = print_children(out, node, flags, indent);\n break;\n\n \/\/ Element\n case node_element:\n out = print_element_node(out, node, flags, indent);\n break;\n \n \/\/ Data\n case node_data:\n out = print_data_node(out, node, flags, indent);\n break;\n \n \/\/ CDATA\n case node_cdata:\n out = print_cdata_node(out, node, flags, indent);\n break;\n\n \/\/ Declaration\n case node_declaration:\n out = print_declaration_node(out, node, flags, indent);\n break;\n\n \/\/ Comment\n case node_comment:\n out = print_comment_node(out, node, flags, indent);\n break;\n \n \/\/ Doctype\n case node_doctype:\n out = print_doctype_node(out, node, flags, indent);\n break;\n\n \/\/ Pi\n case node_pi:\n out = print_pi_node(out, node, flags, indent);\n break;\n\n \/\/ Unknown\n default:\n assert(0);\n break;\n }\n \n \/\/ If indenting not disabled, add line break after node\n if (!(flags & print_no_indenting))\n *out = Ch('\\n'), ++out;\n\n \/\/ Return modified iterator\n return out;\n }\n \n \/\/ Print children of the node \n template<class OutIt, class Ch>\n inline OutIt print_children(OutIt out, const xml_node<Ch> *node, int flags, int indent)\n {\n for (xml_node<Ch> *child = node->first_node(); child; child = child->next_sibling())\n out = print_node(out, child, flags, indent);\n return out;\n }\n\n \/\/ Print attributes of the node\n template<class OutIt, class Ch>\n inline OutIt print_attributes(OutIt out, const xml_node<Ch> *node, int flags)\n {\n for (xml_attribute<Ch> *attribute = node->first_attribute(); attribute; attribute = attribute->next_attribute())\n {\n if (attribute->name() && attribute->value())\n {\n \/\/ Print attribute name\n *out = Ch(' '), ++out;\n out = copy_chars(attribute->name(), attribute->name() + attribute->name_size(), out);\n *out = Ch('='), ++out;\n \/\/ Print attribute value using appropriate quote type\n if (find_char<Ch, Ch('\"')>(attribute->value(), attribute->value() + attribute->value_size()))\n {\n *out = Ch('\\''), ++out;\n out = copy_and_expand_chars(attribute->value(), attribute->value() + attribute->value_size(), Ch('\"'), out);\n *out = Ch('\\''), ++out;\n }\n else\n {\n *out = Ch('\"'), ++out;\n out = copy_and_expand_chars(attribute->value(), attribute->value() + attribute->value_size(), Ch('\\''), out);\n *out = Ch('\"'), ++out;\n }\n }\n }\n return out;\n }\n\n \/\/ Print data node\n template<class OutIt, class Ch>\n inline OutIt print_data_node(OutIt out, const xml_node<Ch> *node, int flags, int indent)\n {\n assert(node->type() == node_data);\n if (!(flags & print_no_indenting))\n out = fill_chars(out, indent, Ch('\\t'));\n out = copy_and_expand_chars(node->value(), node->value() + node->value_size(), Ch(0), out);\n return out;\n }\n\n \/\/ Print data node\n template<class OutIt, class Ch>\n inline OutIt print_cdata_node(OutIt out, const xml_node<Ch> *node, int flags, int indent)\n {\n assert(node->type() == node_cdata);\n if (!(flags & print_no_indenting))\n out = fill_chars(out, indent, Ch('\\t'));\n *out = Ch('<'); ++out;\n *out = Ch('!'); ++out;\n *out = Ch('['); ++out;\n *out = Ch('C'); ++out;\n *out = Ch('D'); ++out;\n *out = Ch('A'); ++out;\n *out = Ch('T'); ++out;\n *out = Ch('A'); ++out;\n *out = Ch('['); ++out;\n out = copy_chars(node->value(), node->value() + node->value_size(), out);\n *out = Ch(']'); ++out;\n *out = Ch(']'); ++out;\n *out = Ch('>'); ++out;\n return out;\n }\n\n \/\/ Print element node\n template<class OutIt, class Ch>\n inline OutIt print_element_node(OutIt out, const xml_node<Ch> *node, int flags, int indent)\n {\n assert(node->type() == node_element);\n\n \/\/ Print element name and attributes, if any\n if (!(flags & print_no_indenting))\n out = fill_chars(out, indent, Ch('\\t'));\n *out = Ch('<'), ++out;\n out = copy_chars(node->name(), node->name() + node->name_size(), out);\n out = print_attributes(out, node, flags);\n \n \/\/ If node is childless\n if (node->value_size() == 0 && !node->first_node())\n {\n \/\/ Print childless node tag ending\n *out = Ch('\/'), ++out;\n *out = Ch('>'), ++out;\n }\n else\n {\n \/\/ Print normal node tag ending\n *out = Ch('>'), ++out;\n\n \/\/ Test if node contains a single data node only (and no other nodes)\n xml_node<Ch> *child = node->first_node();\n if (!child)\n {\n \/\/ If node has no children, only print its value without indenting\n out = copy_and_expand_chars(node->value(), node->value() + node->value_size(), Ch(0), out);\n }\n else if (child->next_sibling() == 0 && child->type() == node_data)\n {\n \/\/ If node has a sole data child, only print its value without indenting\n out = copy_and_expand_chars(child->value(), child->value() + child->value_size(), Ch(0), out);\n }\n else\n {\n \/\/ Print all children with full indenting\n if (!(flags & print_no_indenting))\n *out = Ch('\\n'), ++out;\n out = print_children(out, node, flags, indent + 1);\n if (!(flags & print_no_indenting))\n out = fill_chars(out, indent, Ch('\\t'));\n }\n\n \/\/ Print node end\n *out = Ch('<'), ++out;\n *out = Ch('\/'), ++out;\n out = copy_chars(node->name(), node->name() + node->name_size(), out);\n *out = Ch('>'), ++out;\n }\n return out;\n }\n\n \/\/ Print declaration node\n template<class OutIt, class Ch>\n inline OutIt print_declaration_node(OutIt out, const xml_node<Ch> *node, int flags, int indent)\n {\n \/\/ Print declaration start\n if (!(flags & print_no_indenting))\n out = fill_chars(out, indent, Ch('\\t'));\n *out = Ch('<'), ++out;\n *out = Ch('?'), ++out;\n *out = Ch('x'), ++out;\n *out = Ch('m'), ++out;\n *out = Ch('l'), ++out;\n\n \/\/ Print attributes\n out = print_attributes(out, node, flags);\n \n \/\/ Print declaration end\n *out = Ch('?'), ++out;\n *out = Ch('>'), ++out;\n \n return out;\n }\n\n \/\/ Print comment node\n template<class OutIt, class Ch>\n inline OutIt print_comment_node(OutIt out, const xml_node<Ch> *node, int flags, int indent)\n {\n assert(node->type() == node_comment);\n if (!(flags & print_no_indenting))\n out = fill_chars(out, indent, Ch('\\t'));\n *out = Ch('<'), ++out;\n *out = Ch('!'), ++out;\n *out = Ch('-'), ++out;\n *out = Ch('-'), ++out;\n out = copy_chars(node->value(), node->value() + node->value_size(), out);\n *out = Ch('-'), ++out;\n *out = Ch('-'), ++out;\n *out = Ch('>'), ++out;\n return out;\n }\n\n \/\/ Print doctype node\n template<class OutIt, class Ch>\n inline OutIt print_doctype_node(OutIt out, const xml_node<Ch> *node, int flags, int indent)\n {\n assert(node->type() == node_doctype);\n if (!(flags & print_no_indenting))\n out = fill_chars(out, indent, Ch('\\t'));\n *out = Ch('<'), ++out;\n *out = Ch('!'), ++out;\n *out = Ch('D'), ++out;\n *out = Ch('O'), ++out;\n *out = Ch('C'), ++out;\n *out = Ch('T'), ++out;\n *out = Ch('Y'), ++out;\n *out = Ch('P'), ++out;\n *out = Ch('E'), ++out;\n *out = Ch(' '), ++out;\n out = copy_chars(node->value(), node->value() + node->value_size(), out);\n *out = Ch('>'), ++out;\n return out;\n }\n\n \/\/ Print pi node\n template<class OutIt, class Ch>\n inline OutIt print_pi_node(OutIt out, const xml_node<Ch> *node, int flags, int indent)\n {\n assert(node->type() == node_pi);\n if (!(flags & print_no_indenting))\n out = fill_chars(out, indent, Ch('\\t'));\n *out = Ch('<'), ++out;\n *out = Ch('?'), ++out;\n out = copy_chars(node->name(), node->name() + node->name_size(), out);\n *out = Ch(' '), ++out;\n out = copy_chars(node->value(), node->value() + node->value_size(), out);\n *out = Ch('?'), ++out;\n *out = Ch('>'), ++out;\n return out;\n }\n\n }\n \/\/! \\endcond\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ Printing\n\n \/\/! Prints XML to given output iterator.\n \/\/! \\param out Output iterator to print to.\n \/\/! \\param node Node to be printed. Pass xml_document to print entire document.\n \/\/! \\param flags Flags controlling how XML is printed.\n \/\/! \\return Output iterator pointing to position immediately after last character of printed text.\n template<class OutIt, class Ch> \n inline OutIt print(OutIt out, const xml_node<Ch> &node, int flags = 0)\n {\n return internal::print_node(out, &node, flags, 0);\n }\n\n#ifndef RAPIDXML_NO_STREAMS\n\n \/\/! Prints XML to given output stream.\n \/\/! \\param out Output stream to print to.\n \/\/! \\param node Node to be printed. Pass xml_document to print entire document.\n \/\/! \\param flags Flags controlling how XML is printed.\n \/\/! \\return Output stream.\n template<class Ch> \n inline std::basic_ostream<Ch> &print(std::basic_ostream<Ch> &out, const xml_node<Ch> &node, int flags = 0)\n {\n print(std::ostream_iterator<Ch>(out), node, flags);\n return out;\n }\n\n \/\/! Prints formatted XML to given output stream. Uses default printing flags. Use print() function to customize printing process.\n \/\/! \\param out Output stream to print to.\n \/\/! \\param node Node to be printed.\n \/\/! \\return Output stream.\n template<class Ch> \n inline std::basic_ostream<Ch> &operator <<(std::basic_ostream<Ch> &out, const xml_node<Ch> &node)\n {\n return print(out, node);\n }\n\n#endif\n\n}\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/*\n For more information, please see: http:\/\/software.sci.utah.edu\n\n The MIT License\n\n Copyright (c) 2015 Scientific Computing and Imaging Institute,\n University of Utah.\n\n License for the specific language governing rights and limitations under\n Permission is hereby granted, free of charge, to any person obtaining a\n copy of this software and associated documentation files (the \"Software\"),\n to deal in the Software without restriction, including without limitation\n the rights to use, copy, modify, merge, publish, distribute, sublicense,\n and\/or sell copies of the Software, and to permit persons to whom the\n Software is furnished to do so, subject to the following conditions:\n\n The above copyright notice and this permission notice shall be included\n in all copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n DEALINGS IN THE SOFTWARE.\n*\/\n\n#include <Interface\/Modules\/Base\/WidgetSlotManagers.h>\n#include <Interface\/Modules\/Base\/ModuleDialogGeneric.h>\n\nusing namespace SCIRun::Gui;\nusing namespace SCIRun::Core::Algorithms;\n\nWidgetSlotManager::WidgetSlotManager(SCIRun::Dataflow::Networks::ModuleStateHandle state, ModuleDialogGeneric& dialog, QWidget* widget, const AlgorithmParameterName& name)\n : state_(state), dialog_(dialog)\n{\n if (widget)\n widget->setToolTip(QString::fromStdString(name.name_));\n}\n\nWidgetSlotManager::~WidgetSlotManager() \n{\n}\n\nvoid WidgetSlotManager::push()\n{\n \/\/TODO: idea: tell state_ directly, i'm in a scoped region of pushing\/editing, don't signal while i edit. signal when done editing!\n if (!dialog_.isPulling())\n pushImpl();\n}<commit_msg>Closes #1255<commit_after>\/*\n For more information, please see: http:\/\/software.sci.utah.edu\n\n The MIT License\n\n Copyright (c) 2015 Scientific Computing and Imaging Institute,\n University of Utah.\n\n License for the specific language governing rights and limitations under\n Permission is hereby granted, free of charge, to any person obtaining a\n copy of this software and associated documentation files (the \"Software\"),\n to deal in the Software without restriction, including without limitation\n the rights to use, copy, modify, merge, publish, distribute, sublicense,\n and\/or sell copies of the Software, and to permit persons to whom the\n Software is furnished to do so, subject to the following conditions:\n\n The above copyright notice and this permission notice shall be included\n in all copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n DEALINGS IN THE SOFTWARE.\n*\/\n\n#include <Interface\/Modules\/Base\/WidgetSlotManagers.h>\n#include <Interface\/Modules\/Base\/ModuleDialogGeneric.h>\n\nusing namespace SCIRun::Gui;\nusing namespace SCIRun::Core::Algorithms;\n\nWidgetSlotManager::WidgetSlotManager(SCIRun::Dataflow::Networks::ModuleStateHandle state, ModuleDialogGeneric& dialog, QWidget* widget, const AlgorithmParameterName& name)\n : state_(state), dialog_(dialog)\n{\n if (widget)\n {\n widget->setToolTip(\"State key: \" + QString::fromStdString(name.name_));\n widget->setStyleSheet(widget->styleSheet() + \" QToolTip { color: #ffffff; background - color: #2a82da; border: 1px solid white; }\");\n }\n}\n\nWidgetSlotManager::~WidgetSlotManager() \n{\n}\n\nvoid WidgetSlotManager::push()\n{\n \/\/TODO: idea: tell state_ directly, i'm in a scoped region of pushing\/editing, don't signal while i edit. signal when done editing!\n if (!dialog_.isPulling())\n pushImpl();\n}<|endoftext|>"} {"text":"<commit_before>#include \"HelloWorld5Module.h\"\n#include \"NFComm\/NFCore\/NFTimer.h\"\n#include <thread>\n#include \"NFComm\/NFCore\/NFIComponent.h\"\n#include \"NFCTestComponent.h\"\n\n\n\nbool HelloWorld5Module::Init()\n{\n \/\/ʼ\n std::cout << \"Hello, world5, Init\" << std::endl;\n\n return true;\n}\n\nbool HelloWorld5Module::AfterInit()\n{\n \/\/ʼ\n std::cout << \"Hello, world5, AfterInit, ThreadID: \" << std::this_thread::get_id() << std::endl;\n\n m_pKernelModule = dynamic_cast<NFIKernelModule*>(pPluginManager->FindModule(\"NFCKernelModule\"));\n m_pEventProcessModule = dynamic_cast<NFIEventProcessModule*>(pPluginManager->FindModule(\"NFCEventProcessModule\"));\n m_pElementInfoModule = dynamic_cast<NFIElementInfoModule*>(pPluginManager->FindModule(\"NFCElementInfoModule\"));\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\t\/\/int nActorID = m_pEventProcessModule->AddActorEventCallBack<NFCTestComponent, HelloWorld5Module>(this, &HelloWorld5Module::OnSyncEvent);\n\tint nActorID = m_pEventProcessModule->AddActorEventCallBack<NFCTestComponent>(this, &HelloWorld5Module::OnSyncEvent);\n\n m_pEventProcessModule->SendActorMsg(nActorID, 555, NFIDENTID(), \"Event Param\");\n\n\n std::cout << \"End Test Actor, ThreadID: \" << std::this_thread::get_id() << std::endl;\n\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \n\n return true;\n}\n\nint HelloWorld5Module::OnSyncEvent(const NFIDENTID& self, const int event, const std::string& arg)\n{\n \/\/¼ص\n std::cout << \"End OnEvent EventID: \" << event << \" self: \" << self.nData64 << \" argList: \" << arg << \" ThreadID: \" << std::this_thread::get_id() << std::endl;\n\n return 0;\n}\n\nbool HelloWorld5Module::Execute( const float fLasFrametime, const float fStartedTime )\n{\n \/\/ÿִ֡\n \/\/std::cout << \"Hello, world5, Execute\" << std::endl;\n\n return true;\n}\n\nbool HelloWorld5Module::BeforeShut()\n{\n \/\/ʼ֮ǰ\n std::cout << \"Hello, world5, BeforeShut\" << std::endl;\n\n m_pKernelModule->DestroyAll();\n\n return true;\n}\n\nbool HelloWorld5Module::Shut()\n{\n \/\/ʼ\n std::cout << \"Hello, world5, Shut\" << std::endl;\n\n return true;\n}\n<commit_msg>Tutorial<commit_after>#include \"HelloWorld5Module.h\"\n#include \"NFComm\/NFCore\/NFTimer.h\"\n#include <thread>\n#include \"NFComm\/NFCore\/NFIComponent.h\"\n#include \"NFCTestComponent.h\"\n\n\n\nbool HelloWorld5Module::Init()\n{\n \/\/ʼ\n std::cout << \"Hello, world5, Init\" << std::endl;\n\n return true;\n}\n\nbool HelloWorld5Module::AfterInit()\n{\n \/\/ʼ\n std::cout << \"Hello, world5, AfterInit, ThreadID: \" << std::this_thread::get_id() << std::endl;\n\n m_pKernelModule = dynamic_cast<NFIKernelModule*>(pPluginManager->FindModule(\"NFCKernelModule\"));\n m_pEventProcessModule = dynamic_cast<NFIEventProcessModule*>(pPluginManager->FindModule(\"NFCEventProcessModule\"));\n m_pElementInfoModule = dynamic_cast<NFIElementInfoModule*>(pPluginManager->FindModule(\"NFCElementInfoModule\"));\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\t\/\/int nActorID = m_pEventProcessModule->AddActorEventCallBack<NFCTestComponent, HelloWorld5Module>(this, &HelloWorld5Module::OnSyncEvent);\n\tint nActorID = m_pEventProcessModule->AddActorEventCallBack<NFCTestComponent>(this, &HelloWorld5Module::OnSyncEvent);\n\n\tfor (int i = 0; i < 20; ++i)\n\t{\n\t\tm_pEventProcessModule->SendActorMsg(nActorID, 555, NFIDENTID(), boost::lexical_cast<std::string>(i));\n\t}\n\n\n std::cout << \"End Test Actor, ThreadID: \" << std::this_thread::get_id() << std::endl;\n\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \n\n return true;\n}\n\nint HelloWorld5Module::OnSyncEvent(const NFIDENTID& self, const int event, const std::string& arg)\n{\n \/\/¼ص\n std::cout << \"End OnEvent EventID: \" << event << \" self: \" << self.nData64 << \" argList: \" << arg << \" ThreadID: \" << std::this_thread::get_id() << std::endl;\n\n return 0;\n}\n\nbool HelloWorld5Module::Execute( const float fLasFrametime, const float fStartedTime )\n{\n \/\/ÿִ֡\n \/\/std::cout << \"Hello, world5, Execute\" << std::endl;\n\n return true;\n}\n\nbool HelloWorld5Module::BeforeShut()\n{\n \/\/ʼ֮ǰ\n std::cout << \"Hello, world5, BeforeShut\" << std::endl;\n\n m_pKernelModule->DestroyAll();\n\n return true;\n}\n\nbool HelloWorld5Module::Shut()\n{\n \/\/ʼ\n std::cout << \"Hello, world5, Shut\" << std::endl;\n\n return true;\n}\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n#include <vector>\n#include <utility>\n#include <fstream>\n#include <sstream>\n#include \"TGraph.h\"\n#include \"TCanvas.h\"\n#include \"TF1.h\"\n#include \"TStyle.h\"\n#include \"TGraphErrors.h\"\n\nstd::vector< std::pair<int,double> > takeData(const std::string file, const char thresholdLabel);\nstd::pair<double,double> plotVelocity(std::vector<double> positions, std::vector<double> means, int strip, std::vector<double> errors, char thresholdLabel);\n\nstruct positionData{\n\tdouble positionValue;\n\tdouble deltaT;\n\tdouble deltaTError;\n};\n\nstruct thresholdData{\n\tchar thresholdLabel;\n\tstd::vector<positionData> positions;\n};\n\nstruct scintData{\n\tint ID;\n\tstd::vector<thresholdData> thrData;\n};\n\nstd::vector<scintData> takeData(const std::string file);\nvoid velocityCalc(std::vector<scintData>& data, const char thrLabel, const std::string& outPath);\nvoid parserTest(std::vector<scintData>& data, const char thrLabel);\n\nint main(int argc, char** argv)\n{\n\tgStyle->SetOptFit(1);\n\t\n\tstd::vector<scintData> data;\n\tstd::string outPath = \"\";\n\tif(argc == 1)\n\t{\n\t data = takeData(\"results.txt\");\n\t}\n\telse if (argc == 2)\n\t{\n\t data = takeData(std::string(argv[1]));\n\t}\n\telse if (argc == 3)\n\t{\n\t data = takeData(std::string(argv[1]));\n\t outPath = argv[2];\n\t}\n\t\n\tif(data.size() == 0 )\n\t{\n\t std::cout<<\"Error while opening input file\"<<std::endl;\n\t return 1;\n\t}\n\t\n\tvelocityCalc( data , 'a', outPath);\n\tvelocityCalc( data , 'b', outPath);\n\tvelocityCalc( data , 'c', outPath);\n\tvelocityCalc( data , 'd', outPath);\n\n\treturn 0;\n}\n\nvoid parserTest(std::vector<scintData>& data, const char thrLabel)\n{\n\tfor(auto scintillator : data)\n\t{\t\n\t\tstd::cout << scintillator.ID;\n\t\tfor(auto threshold : scintillator.thrData)\n\t\t{\n\t\t\tif( thrLabel == threshold.thresholdLabel )\n\t\t\t{\n\t\t\t\tstd::cout << \"\\t\" << threshold.thresholdLabel;\n\t\t\t\tfor( auto position : threshold.positions )\n\t\t\t\t{\n\t\t\t\t\tstd::cout << \"\\t\" << position.positionValue << \"\\t\" << position.deltaT << \"\\t\" << position.deltaTError <<std::endl;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n}\n\n\nvoid velocityCalc(std::vector<scintData>& data, const char thrLabel, const std::string& outPath)\n{\n\n\tstd::ofstream results;\n\tstd::string title = outPath+\"resultsForThreshold\";\n\ttitle+= thrLabel;\n\ttitle+= \".txt\";\n\tresults.open( title.c_str() );\n\tfor(auto scintillator : data)\n\t{\t\n\t\tstd::vector<double> positionsForFit;\n\t\tstd::vector<double> timesForFit;\t\n\t\tstd::vector<double> errorsForFit;\n\t\tfor(auto threshold : scintillator.thrData)\n\t\t{\n\t\t\t\n\t\t\tif( thrLabel == threshold.thresholdLabel )\n\t\t\t{\t\t\t\n\t\t\t\tfor( auto position : threshold.positions )\n\t\t\t\t{\n\t\t\t\t\tstd::cout << \"\\t\" << position.positionValue << \"\\t\" << position.deltaT << \"\\t\" << position.deltaTError <<std::endl;\n\t\t\t\t\tpositionsForFit.push_back( position.positionValue );\n\t\t\t\t\ttimesForFit.push_back( position.deltaT );\n\t\t\t\t\terrorsForFit.push_back( position.deltaTError);\n\t\t\t\t\tstd::cout << positionsForFit.size() << std::endl;\n\t\t\t\t\tstd::cout << timesForFit.size() << std::endl;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tstd::pair<double,double> velocity = plotVelocity( positionsForFit, timesForFit, scintillator.ID, errorsForFit, thrLabel);\n\t\tresults << scintillator.ID << \"\\t\" << velocity.first << \"\\t\" << velocity.second << std::endl;\n\t}\n\n\tresults.close();\n}\n\nstd::pair<double,double> plotVelocity(std::vector<double> positions, std::vector<double> means, int strip, std::vector<double> errors, char thresholdLabel)\n{\n\tTCanvas* c = new TCanvas();\n\tTGraphErrors* vGraph = new TGraphErrors(positions.size(), &means[0], &positions[0], 0, &errors[0] );\n\tvGraph->SetMarkerStyle(20);\n\tvGraph->SetMarkerSize(1);\n\tvGraph->Draw(\"AP\");\n\tvGraph->Fit(\"pol1\");\n\tTF1* fit = vGraph->GetFunction(\"pol1\");\n\tstd::stringstream buf;\n\tbuf << strip << \"_\" << thresholdLabel;\n\tc->SaveAs( (buf.str() + \".png\").c_str() );\n\tstd::pair<double,double> resultOfFit = std::make_pair<double,double> ( (fit->GetParameter(1))*-0.2, (fit->GetParError(1))*-0.2 );\n\treturn resultOfFit;\n}\n\nbool ifScintillatorIsIn( std::vector<scintData>& data, int ID)\n{\n\tfor( auto scintillator : data )\n\t{\n\t\tif( ID == scintillator.ID )\n\t\t\treturn true;\n\t}\n\treturn false;\n}\n\nint findScintillatorIn( std::vector<scintData>& data, int ID)\n{\n\tfor( unsigned int i = 0; i < data.size(); i++ )\n\t{\n\t\tif( ID == data[i].ID )\n\t\t\treturn i;\n\t}\n\treturn -1;\n}\n\nstd::vector<scintData> takeData(const std::string file){\n\tstd::ifstream dataFile;\n\tdataFile.open(file.c_str());\n\n\tif( !dataFile.good() )\n\t{\n\t\tstd::exit(1);\n\t}\n\n\tstd::vector< scintData > allData;\n\t\n\tdouble position = 999;\n\tchar thrLabel = 'z';\n\tdouble chi2 = 99;\n\tint degrees = 0;\n\tint ID = 0;\n\tdouble mean = 999;\n\tdouble meanError = 0;\n\t\twhile( dataFile >> ID >> position >> thrLabel >> mean >> meanError >> chi2 >> degrees )\n\t\t{\t\n\t\t\t\/\/IF ID IS IN ALLDATA\n\t\t\tif ( ifScintillatorIsIn(allData, ID) )\n\t\t\t{\n\t\t\t\t\/\/FILL THIS SCINTILLATOR WITH ADDITIONAL INFO\n\t\t\t\tint scintIndex = findScintillatorIn(allData, ID);\n\t\t\t\t\n\t\t\t\tpositionData pos;\n\t\t\t\tpos.positionValue = position;\n\t\t\t\tpos.deltaT = mean;\n\t\t\t\tpos.deltaTError = meanError;\n\t\t\t\t\n\t\t\t\tthresholdData thr;\n\t\t\t\tthr.thresholdLabel = thrLabel;\n\t\t\t\tthr.positions.push_back(pos);\n\t\t\t\t\n\t\t\t\tallData[ scintIndex ].thrData.push_back(thr);\n\t\t\t}\n\t\t\telse{\n\t\t\t\t\/\/ELSE MAKE NEW SCINTILLATOR AND FILL\n\t\t\t\tpositionData pos;\n\t\t\t\tpos.positionValue = position;\n\t\t\t\tpos.deltaT = mean;\n\t\t\t\tpos.deltaTError = meanError;\n\t\t\t\t\n\t\t\t\tthresholdData thr;\n\t\t\t\tthr.thresholdLabel = thrLabel;\n\t\t\t\tthr.positions.push_back(pos);\n\t\t\t\t\n\t\t\t\tscintData scintillator;\n\t\t\t\tscintillator.ID = ID;\n\t\t\t\tscintillator.thrData.push_back(thr);\n\t\t\t\t\n\t\t\t\t\/\/ FILL THRESHOLD AND POSITION\n\t\t\t\tallData.push_back(scintillator);\n\t\t\t}\n\t\t}\n\t\n\treturn allData;\t\n}\n\n<commit_msg>Make universal format output from velocity calib<commit_after>#include <iostream>\n#include <vector>\n#include <utility>\n#include <fstream>\n#include <sstream>\n#include \"TGraph.h\"\n#include \"TCanvas.h\"\n#include \"TF1.h\"\n#include \"TStyle.h\"\n#include \"TGraphErrors.h\"\n#include <map>\n\nstd::vector< std::pair<int,double> > takeData(const std::string file, const char thresholdLabel);\nstd::pair<double,double> plotVelocity(std::vector<double> positions, std::vector<double> means, int strip, std::vector<double> errors, char thresholdLabel);\n\n\n\nstruct positionData{\n\tdouble positionValue;\n\tdouble deltaT;\n\tdouble deltaTError;\n};\n\nstruct thresholdData{\n\tchar thresholdLabel;\n\tstd::vector<positionData> positions;\n};\n\nstruct scintData{\n\tint ID;\n\tstd::vector<thresholdData> thrData;\n};\n\nstd::vector<scintData> takeData(const std::string file);\nvoid velocityCalc(std::vector<scintData>& data, const std::string& outPath);\nvoid parserTest(std::vector<scintData>& data, const char thrLabel);\n\nint main(int argc, char** argv)\n{\n\tgStyle->SetOptFit(1);\n\t\n\tstd::vector<scintData> data;\n\tstd::string outPath = \"\";\n\tif(argc == 1)\n\t{\n\t data = takeData(\"results.txt\");\n\t}\n\telse if (argc == 2)\n\t{\n\t data = takeData(std::string(argv[1]));\n\t}\n\telse if (argc == 3)\n\t{\n\t data = takeData(std::string(argv[1]));\n\t outPath = argv[2];\n\t}\n\t\n\tif(data.size() == 0 )\n\t{\n\t std::cout<<\"Error while opening input file\"<<std::endl;\n\t return 1;\n\t}\n\t\n\tvelocityCalc( data , outPath);\n\t\n\treturn 0;\n}\n\nvoid parserTest(std::vector<scintData>& data, const char thrLabel)\n{\n\tfor(auto scintillator : data)\n\t{\t\n\t\tstd::cout << scintillator.ID;\n\t\tfor(auto threshold : scintillator.thrData)\n\t\t{\n\t\t\tif( thrLabel == threshold.thresholdLabel )\n\t\t\t{\n\t\t\t\tstd::cout << \"\\t\" << threshold.thresholdLabel;\n\t\t\t\tfor( auto position : threshold.positions )\n\t\t\t\t{\n\t\t\t\t\tstd::cout << \"\\t\" << position.positionValue << \"\\t\" << position.deltaT << \"\\t\" << position.deltaTError <<std::endl;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n}\n\n\nvoid velocityCalc(std::vector<scintData>& data, const std::string& outPath)\n{\n\tstd::map<char, int> thresholdLabelToInt = {{'a', 1}, {'b',2}, {'c',3}, {'d',4}};\n\tstd::ofstream results;\n\tstd::string title = outPath+\"EffVelocities\";\n\ttitle+= \".txt\";\n\tresults.open( title.c_str() );\n\tfor(auto scintillator : data)\n\t{\t\n\t\tstd::cout << scintillator.ID;\n\t\tfor(auto threshold : scintillator.thrData)\n\t\t{\n\t\t\tstd::cout << \"\\t\" << threshold.thresholdLabel;\n\t\t\tstd::vector<double> positionsForFit;\n\t\t\tstd::vector<double> timesForFit;\t\n\t\t\tstd::vector<double> errorsForFit;\n\t\t\tfor( auto position : threshold.positions )\n\t\t\t{\n\t\t\t\tstd::cout << \"\\t\" << position.positionValue << \"\\t\" << position.deltaT << \"\\t\" << position.deltaTError <<std::endl;\n\t\t\t\tpositionsForFit.push_back( position.positionValue );\n\t\t\t\ttimesForFit.push_back( position.deltaT );\n\t\t\t\terrorsForFit.push_back( position.deltaTError);\n\t\t\t}\n\t\t\tstd::pair<double,double> velocity = plotVelocity( positionsForFit, timesForFit, scintillator.ID, errorsForFit, threshold.thresholdLabel);\n\t\t\tint layer = 0, layerReset = 0;\n\t\t\tif( scintillator.ID < 49 )\n\t\t\t{\n\t\t\t layer = 1;\n\t\t\t}\n\t\t\telse if( scintillator.ID > 48 && scintillator.ID < 97 )\n\t\t\t{\n\t\t\t layer = 2; \n\t\t\t layerReset = 48;\n\t\t\t}\n\t\t\telse \n\t\t\t{\n\t\t\t layer = 3;\n\t\t\t layerReset = 96;\n\t\t\t}\n\t\t\t\n\t\t\tresults << layer << \"\\t\" << scintillator.ID - layerReset << \"\\tA\\t\" << thresholdLabelToInt[threshold.thresholdLabel];\n\t\t\tresults << \"\\t\" << velocity.first << \"\\t\" << velocity.second;\n\t\t\tresults << \"\\t0\\t0\\t0\\t0\\t0\\t0\" << std::endl;\n\t\t\tresults << layer << \"\\t\" << scintillator.ID - layerReset << \"\\tB\\t\" << thresholdLabelToInt[threshold.thresholdLabel];\n\t\t\tresults << \"\\t\" << velocity.first << \"\\t\" << velocity.second;\n\t\t\tresults << \"\\t0\\t0\\t0\\t0\\t0\\t0\" << std::endl;\n\t\t}\n\t}\n\n\tresults.close();\n}\n\nstd::pair<double,double> plotVelocity(std::vector<double> positions, std::vector<double> means, int strip, std::vector<double> errors, char thresholdLabel)\n{\n\tTCanvas* c = new TCanvas();\n\tTGraphErrors* vGraph = new TGraphErrors(positions.size(), &means[0], &positions[0], 0, &errors[0] );\n\tvGraph->SetMarkerStyle(20);\n\tvGraph->SetMarkerSize(1);\n\tvGraph->Draw(\"AP\");\n\tvGraph->Fit(\"pol1\");\n\tTF1* fit = vGraph->GetFunction(\"pol1\");\n\tstd::stringstream buf;\n\tbuf << strip << \"_\" << thresholdLabel;\n\tc->SaveAs( (buf.str() + \".png\").c_str() );\n\tstd::pair<double,double> resultOfFit = std::make_pair<double,double> ( (fit->GetParameter(1))*-0.2, (fit->GetParError(1))*-0.2 );\n\treturn resultOfFit;\n}\n\nbool ifScintillatorIsIn( std::vector<scintData>& data, int ID)\n{\n\tfor( auto scintillator : data )\n\t{\n\t\tif( ID == scintillator.ID )\n\t\t\treturn true;\n\t}\n\treturn false;\n}\n\nint findScintillatorIn( std::vector<scintData>& data, int ID)\n{\n\tfor( unsigned int i = 0; i < data.size(); i++ )\n\t{\n\t\tif( ID == data[i].ID )\n\t\t\treturn i;\n\t}\n\treturn -1;\n}\n\nbool ifThresholdIsIn( scintData& data, char label)\n{\n\tfor( auto threshold : data.thrData )\n\t{\n\t\tif( label == threshold.thresholdLabel)\n\t\t\treturn true;\n\t}\n\treturn false;\n}\n\nint findThresholdIn( scintData& data, char label)\n{\n\tfor( unsigned int i = 0; i < data.thrData.size(); i++ )\n\t{\n\t\tif( label == data.thrData[i].thresholdLabel )\n\t\t\treturn i;\n\t}\n\treturn -1;\n}\n\n\nstd::vector<scintData> takeData(const std::string file){\n\tstd::ifstream dataFile;\n\tdataFile.open(file.c_str());\n\n\tif( !dataFile.good() )\n\t{\n\t\tstd::exit(1);\n\t}\n\n\tstd::vector< scintData > allData;\n\t\n\tdouble position = 999;\n\tchar thrLabel = 'z';\n\tdouble chi2 = 99;\n\tint degrees = 0;\n\tint ID = 0;\n\tdouble mean = 999;\n\tdouble meanError = 0;\n\t\twhile( dataFile >> ID >> position >> thrLabel >> mean >> meanError >> chi2 >> degrees )\n\t\t{\t\n\t\t\t\/\/IF ID IS IN ALLDATA\n\t\t\tif ( ifScintillatorIsIn(allData, ID) )\n\t\t\t{\n\t\t\t\t\/\/FILL THIS SCINTILLATOR WITH ADDITIONAL INFO\n\t\t\t\tint scintIndex = findScintillatorIn(allData, ID);\n\t\t\t\t\n\t\t\t\tpositionData pos;\n\t\t\t\tpos.positionValue = position;\n\t\t\t\tpos.deltaT = mean;\n\t\t\t\tpos.deltaTError = meanError;\n\t\t\t\t\n\t\t\t\t\/\/IF THR IS IN SCINTILLATOR\n\t\t\t\tif( ifThresholdIsIn( allData[scintIndex], thrLabel ) )\n\t\t\t\t{\n\t\t\t\t int thrIndex = findThresholdIn( allData[scintIndex], thrLabel );\n\t\t\t\t allData[ scintIndex ].thrData[thrIndex].positions.push_back(pos);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\/\/ELSE MAKE A NEW THRESHOLD AND FILL\n\t\t\t\tthresholdData thr;\n\t\t\t\tthr.thresholdLabel = thrLabel;\n\t\t\t\tthr.positions.push_back(pos);\n\t\t\t\t\n\t\t\t\tallData[ scintIndex ].thrData.push_back(thr);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse{\n\t\t\t\t\/\/ELSE MAKE NEW SCINTILLATOR AND FILL\n\t\t\t\tpositionData pos;\n\t\t\t\tpos.positionValue = position;\n\t\t\t\tpos.deltaT = mean;\n\t\t\t\tpos.deltaTError = meanError;\n\t\t\t\t\n\t\t\t\tthresholdData thr;\n\t\t\t\tthr.thresholdLabel = thrLabel;\n\t\t\t\tthr.positions.push_back(pos);\n\t\t\t\t\n\t\t\t\tscintData scintillator;\n\t\t\t\tscintillator.ID = ID;\n\t\t\t\tscintillator.thrData.push_back(thr);\n\t\t\t\t\n\t\t\t\t\/\/ FILL THRESHOLD AND POSITION\n\t\t\t\tallData.push_back(scintillator);\n\t\t\t}\n\t\t}\n\t\n\treturn allData;\t\n}\n\n<|endoftext|>"} {"text":"<commit_before>#include \"cinder\/app\/AppNative.h\"\n#include \"cinder\/gl\/gl.h\"\n#include \"cinder\/MayaCamUI.h\"\n#include \"cinder\/Perlin.h\"\n#include \"cinder\/gl\/Fbo.h\"\n\n#include \"VibrissaElement.h\"\n\nusing namespace ci;\nusing namespace ci::app;\nusing namespace std;\n\n\nclass VibrissaSketchApp : public AppNative {\n public:\n\tvoid setup();\n\tvoid update();\n\tvoid draw();\n void prepareSettings(Settings *settings);\n\n void mouseDown(MouseEvent event);\n void mouseDrag(MouseEvent event);\n void resize();\n \nprotected:\n MayaCamUI mMayaCam;\n VibrissaElement mElement;\n Perlin mPerlin;\n\n gl::Fbo mFboScene;\n gl::Fbo mFboBlur1;\n gl::Fbo mFboBlur2;\n gl::GlslProg mBlurShader;\n gl::GlslProg mPostShader;\n \n void drawScene();\n void drawElements();\n void drawGrid(float size=100.0f, float step=5.0f);\n void drawVibrissa(Vec3f origin);\n};\n\n\nvoid VibrissaSketchApp::setup()\n{\n setFullScreen(true);\n hideCursor();\t\t\n \n gl::Fbo::Format fmt;\n fmt.setColorInternalFormat(GL_RGB32F_ARB);\n \n mFboScene = gl::Fbo(getWindowWidth() * 2, getWindowHeight() * 2, fmt);\n mFboBlur1 = gl::Fbo(getWindowWidth() \/ 4, getWindowHeight() \/ 4, fmt);\n mFboBlur2 = gl::Fbo(getWindowWidth() \/ 4, getWindowHeight() \/ 4, fmt);\n\n mBlurShader = gl::GlslProg(loadResource(\"blur.glslv\"), loadResource(\"blur.glslf\"));\n mPostShader = gl::GlslProg(loadResource(\"post.glslv\"), loadResource(\"post.glslf\"));\n \n mElement.setup(*this);\n \n CameraPersp cam;\n cam.setEyePoint( Vec3f(5.0f, 1.5f, -5.0f) );\n cam.setCenterOfInterestPoint( Vec3f(20.f, 5.f, 4.f) );\n cam.setPerspective( 60.0f, getWindowAspectRatio(), 1.0f, 1000.0f );\n mMayaCam.setCurrentCam( cam );\n}\n\nvoid VibrissaSketchApp::prepareSettings( Settings *settings )\n{\n settings->setWindowSize( 1920, 1080 );\n settings->setFrameRate( 60.0f );\n}\n\nvoid VibrissaSketchApp::mouseDown( MouseEvent event )\n{\n mMayaCam.mouseDown( event.getPos() );\n}\n\nvoid VibrissaSketchApp::mouseDrag( MouseEvent event )\n{\n mMayaCam.mouseDrag(event.getPos(),\n event.isLeftDown() && !event.isShiftDown(),\n event.isMiddleDown() || event.isShiftDown(),\n event.isRightDown() );\n}\n\nvoid VibrissaSketchApp::resize()\n{\n CameraPersp cam = mMayaCam.getCamera();\n cam.setAspectRatio( getWindowAspectRatio() );\n mMayaCam.setCurrentCam( cam );\n}\n\nvoid VibrissaSketchApp::update()\n{\n mElement.update();\n}\n\nvoid VibrissaSketchApp::drawGrid(float size, float step)\n{\n float gray = 0.12f;\n gl::color( Colorf(gray, gray, gray) );\n\n for (float i=-size;i<=size;i+=step) {\n gl::drawLine( Vec3f(i, 0.0f, -size), Vec3f(i, 0.0f, size) );\n gl::drawLine( Vec3f(-size, 0.0f, i), Vec3f(size, 0.0f, i) );\n }\n}\n\nvoid VibrissaSketchApp::draw()\n{\n mFboScene.bindFramebuffer();\n gl::setViewport(mFboScene.getBounds());\n gl::enableDepthRead();\n gl::enableDepthWrite();\n\n drawScene();\n\n mFboScene.unbindFramebuffer();\n gl::disableDepthRead();\n gl::disableDepthWrite();\n gl::color(1.f, 1.f, 1.f);\n \n const float atten = 2.5f;\n for (unsigned step = 0; step < 10; step++) {\n \n \/\/ Horizontal blur\n mFboBlur1.bindFramebuffer();\n gl::setViewport(mFboBlur1.getBounds());\n gl::setMatricesWindow(mFboBlur1.getSize());\n mBlurShader.bind();\n mBlurShader.uniform(\"tex0\", 0);\n mBlurShader.uniform(\"sample_offset\", Vec2f(1.f \/ mFboBlur1.getWidth(), 0.f));\n mBlurShader.uniform(\"attenuation\", step ? 1.f : atten);\n gl::draw(step ? mFboBlur2.getTexture() : mFboScene.getTexture(),\n Rectf(Vec2f(0,0), mFboBlur1.getSize()));\n mBlurShader.unbind();\n mFboBlur1.unbindFramebuffer();\n\n \/\/ Vertical blur\n mFboBlur2.bindFramebuffer();\n gl::setViewport(mFboBlur2.getBounds());\n gl::setMatricesWindow(mFboBlur2.getSize());\n mBlurShader.bind();\n mBlurShader.uniform(\"tex0\", 0);\n mBlurShader.uniform(\"sample_offset\", Vec2f(0.f, 1.f \/ mFboBlur2.getWidth()));\n mBlurShader.uniform(\"attenuation\", 1.f);\n gl::draw(mFboBlur1.getTexture(), Rectf(Vec2f(0,0), mFboBlur2.getSize()));\n mBlurShader.unbind();\n mFboBlur2.unbindFramebuffer();\n }\n \n \/\/ Final scene, combine blurred and unblurred\n gl::setViewport(getWindowBounds());\n gl::setMatricesWindow(getWindowSize(), false);\n mPostShader.bind();\n mPostShader.uniform(\"scene\", 0);\n mPostShader.uniform(\"blurred\", 1);\n mFboBlur2.getTexture().bind(1);\n gl::draw(mFboScene.getTexture(), Rectf(Vec2f(0,0), getWindowSize()));\n mPostShader.unbind();\n}\n\nvoid VibrissaSketchApp::drawScene()\n{\n float gray = 0.02f;\n gl::clear(Colorf(gray, gray, gray));\n\n gl::setMatrices(mMayaCam.getCamera());\n drawGrid();\n drawElements();\n}\n \nvoid VibrissaSketchApp::drawElements()\n{\n const float kMetersPerInch = 0.0254f;\n const float kMetersPerFoot = kMetersPerInch * 12;\n\n float extent = 540 * kMetersPerFoot;\n float spacing = 20 * kMetersPerFoot;\n \n \/\/ Line of elements along the front\n for (float t = 0.f; t <= 1.f; t += spacing \/ extent) {\n mElement.draw(Vec3f((t - 0.5f) * extent, 0.f, 0.f), t);\n }\n \n float loop_center = (225 + 150) * kMetersPerFoot \/ 2;\n float loop_r = 80 * kMetersPerFoot \/ 2;\n float path_r = 6 * kMetersPerFoot;\n \n \/\/ Loops along path\n for (int side = -1; side <= 1; side += 2) {\n \n for (float t = 0.f; t < 1.f; t += 0.1f) {\n float a = t * M_PI * 2.f;\n float r = loop_r * (0.5f + 6.f * mPerlin.noise(sin(a) * 0.4f));\n\n for (int pair = 0; pair < 2; pair++) {\n mElement.draw(Vec3f(cos(a) * r * 2.f + loop_center * side, 0.f,\n sin(a) * r + loop_r * 1.5f), t);\n r += path_r;\n }\n }\n }\n}\n\nCINDER_APP_NATIVE( VibrissaSketchApp, RendererGl )\n<commit_msg>Fullscreen on \"f\" key<commit_after>#include \"cinder\/app\/AppNative.h\"\n#include \"cinder\/gl\/gl.h\"\n#include \"cinder\/MayaCamUI.h\"\n#include \"cinder\/Perlin.h\"\n#include \"cinder\/gl\/Fbo.h\"\n\n#include \"VibrissaElement.h\"\n\nusing namespace ci;\nusing namespace ci::app;\nusing namespace std;\n\n\nclass VibrissaSketchApp : public AppNative {\n public:\n\tvoid setup();\n\tvoid update();\n\tvoid draw();\n void prepareSettings(Settings *settings);\n\n void mouseDown(MouseEvent event);\n void mouseDrag(MouseEvent event);\n void resize();\n void keyDown(KeyEvent event);\n \nprotected:\n MayaCamUI mMayaCam;\n VibrissaElement mElement;\n Perlin mPerlin;\n\n gl::Fbo mFboScene;\n gl::Fbo mFboBlur1;\n gl::Fbo mFboBlur2;\n gl::GlslProg mBlurShader;\n gl::GlslProg mPostShader;\n \n void drawScene();\n void drawElements();\n void drawGrid(float size=100.0f, float step=5.0f);\n void drawVibrissa(Vec3f origin);\n};\n\n\nvoid VibrissaSketchApp::keyDown(KeyEvent event)\n{\n if (event.getCode() == KeyEvent::KEY_f) {\n bool fs = !isFullScreen();\n setFullScreen(fs);\n if (fs) {\n hideCursor();\n } else {\n showCursor();\n }\n }\n}\n\n\nvoid VibrissaSketchApp::setup()\n{\n gl::Fbo::Format fmt;\n fmt.setColorInternalFormat(GL_RGB32F_ARB);\n \n mFboScene = gl::Fbo(getWindowWidth() * 2, getWindowHeight() * 2, fmt);\n mFboBlur1 = gl::Fbo(getWindowWidth() \/ 4, getWindowHeight() \/ 4, fmt);\n mFboBlur2 = gl::Fbo(getWindowWidth() \/ 4, getWindowHeight() \/ 4, fmt);\n\n mBlurShader = gl::GlslProg(loadResource(\"blur.glslv\"), loadResource(\"blur.glslf\"));\n mPostShader = gl::GlslProg(loadResource(\"post.glslv\"), loadResource(\"post.glslf\"));\n \n mElement.setup(*this);\n \n CameraPersp cam;\n cam.setEyePoint( Vec3f(5.0f, 1.5f, -5.0f) );\n cam.setCenterOfInterestPoint( Vec3f(20.f, 5.f, 4.f) );\n cam.setPerspective( 60.0f, getWindowAspectRatio(), 1.0f, 1000.0f );\n mMayaCam.setCurrentCam( cam );\n}\n\nvoid VibrissaSketchApp::prepareSettings( Settings *settings )\n{\n settings->setWindowSize( 1920, 1080 );\n settings->setFrameRate( 60.0f );\n}\n\nvoid VibrissaSketchApp::mouseDown( MouseEvent event )\n{\n mMayaCam.mouseDown( event.getPos() );\n}\n\nvoid VibrissaSketchApp::mouseDrag( MouseEvent event )\n{\n mMayaCam.mouseDrag(event.getPos(),\n event.isLeftDown() && !event.isShiftDown(),\n event.isMiddleDown() || event.isShiftDown(),\n event.isRightDown() );\n}\n\nvoid VibrissaSketchApp::resize()\n{\n CameraPersp cam = mMayaCam.getCamera();\n cam.setAspectRatio( getWindowAspectRatio() );\n mMayaCam.setCurrentCam( cam );\n}\n\nvoid VibrissaSketchApp::update()\n{\n mElement.update();\n}\n\nvoid VibrissaSketchApp::drawGrid(float size, float step)\n{\n float gray = 0.12f;\n gl::color( Colorf(gray, gray, gray) );\n\n for (float i=-size;i<=size;i+=step) {\n gl::drawLine( Vec3f(i, 0.0f, -size), Vec3f(i, 0.0f, size) );\n gl::drawLine( Vec3f(-size, 0.0f, i), Vec3f(size, 0.0f, i) );\n }\n}\n\nvoid VibrissaSketchApp::draw()\n{\n mFboScene.bindFramebuffer();\n gl::setViewport(mFboScene.getBounds());\n gl::enableDepthRead();\n gl::enableDepthWrite();\n\n drawScene();\n\n mFboScene.unbindFramebuffer();\n gl::disableDepthRead();\n gl::disableDepthWrite();\n gl::color(1.f, 1.f, 1.f);\n \n const float atten = 2.5f;\n for (unsigned step = 0; step < 10; step++) {\n \n \/\/ Horizontal blur\n mFboBlur1.bindFramebuffer();\n gl::setViewport(mFboBlur1.getBounds());\n gl::setMatricesWindow(mFboBlur1.getSize());\n mBlurShader.bind();\n mBlurShader.uniform(\"tex0\", 0);\n mBlurShader.uniform(\"sample_offset\", Vec2f(1.f \/ mFboBlur1.getWidth(), 0.f));\n mBlurShader.uniform(\"attenuation\", step ? 1.f : atten);\n gl::draw(step ? mFboBlur2.getTexture() : mFboScene.getTexture(),\n Rectf(Vec2f(0,0), mFboBlur1.getSize()));\n mBlurShader.unbind();\n mFboBlur1.unbindFramebuffer();\n\n \/\/ Vertical blur\n mFboBlur2.bindFramebuffer();\n gl::setViewport(mFboBlur2.getBounds());\n gl::setMatricesWindow(mFboBlur2.getSize());\n mBlurShader.bind();\n mBlurShader.uniform(\"tex0\", 0);\n mBlurShader.uniform(\"sample_offset\", Vec2f(0.f, 1.f \/ mFboBlur2.getWidth()));\n mBlurShader.uniform(\"attenuation\", 1.f);\n gl::draw(mFboBlur1.getTexture(), Rectf(Vec2f(0,0), mFboBlur2.getSize()));\n mBlurShader.unbind();\n mFboBlur2.unbindFramebuffer();\n }\n \n \/\/ Final scene, combine blurred and unblurred\n gl::setViewport(getWindowBounds());\n gl::setMatricesWindow(getWindowSize(), false);\n mPostShader.bind();\n mPostShader.uniform(\"scene\", 0);\n mPostShader.uniform(\"blurred\", 1);\n mFboBlur2.getTexture().bind(1);\n gl::draw(mFboScene.getTexture(), Rectf(Vec2f(0,0), getWindowSize()));\n mPostShader.unbind();\n}\n\nvoid VibrissaSketchApp::drawScene()\n{\n float gray = 0.02f;\n gl::clear(Colorf(gray, gray, gray));\n\n gl::setMatrices(mMayaCam.getCamera());\n drawGrid();\n drawElements();\n}\n \nvoid VibrissaSketchApp::drawElements()\n{\n const float kMetersPerInch = 0.0254f;\n const float kMetersPerFoot = kMetersPerInch * 12;\n\n float extent = 540 * kMetersPerFoot;\n float spacing = 20 * kMetersPerFoot;\n \n \/\/ Line of elements along the front\n for (float t = 0.f; t <= 1.f; t += spacing \/ extent) {\n mElement.draw(Vec3f((t - 0.5f) * extent, 0.f, 0.f), t);\n }\n \n float loop_center = (225 + 150) * kMetersPerFoot \/ 2;\n float loop_r = 80 * kMetersPerFoot \/ 2;\n float path_r = 6 * kMetersPerFoot;\n \n \/\/ Loops along path\n for (int side = -1; side <= 1; side += 2) {\n \n for (float t = 0.f; t < 1.f; t += 0.1f) {\n float a = t * M_PI * 2.f;\n float r = loop_r * (0.5f + 6.f * mPerlin.noise(sin(a) * 0.4f));\n\n for (int pair = 0; pair < 2; pair++) {\n mElement.draw(Vec3f(cos(a) * r * 2.f + loop_center * side, 0.f,\n sin(a) * r + loop_r * 1.5f), t);\n r += path_r;\n }\n }\n }\n}\n\nCINDER_APP_NATIVE( VibrissaSketchApp, RendererGl )\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ This class is the task for connecting together \n\/\/ MC information and the RC information \n\/\/\n\/\/ The task is a wrapper over two components\n\/\/ AliGenInfoMaker\n\/\/ AliESDRecInfoMaker.h\n\n\/\/ ROOT includes\n#include <TChain.h>\n#include <TMath.h>\n\n\/\/ ALIROOT includes\n#include <TTreeStream.h>\n#include <AliAnalysisManager.h>\n#include <AliESDInputHandler.h>\n#include \"AliStack.h\"\n#include \"AliMCEvent.h\"\n#include \"AliMCEventHandler.h\"\n\n#include <AliESD.h>\n#include \"AliGenInfoTask.h\"\n#include \"AliGenInfoMaker.h\"\n#include \"AliHelix.h\"\n\n\/\/\n#include \"AliMCInfo.h\"\n#include \"AliComparisonObject.h\"\n#include \"AliESDRecInfo.h\"\n#include \"AliTPCParamSR.h\"\n#include \"TSystem.h\"\n#include \"TTimeStamp.h\"\n#include \"TFile.h\"\n#include \"AliTPCseed.h\"\n\n\/\/ STL includes\n#include <iostream>\n\nusing namespace std;\n\nClassImp(AliGenInfoTask)\n\n\/\/________________________________________________________________________\nAliGenInfoTask::AliGenInfoTask() : \n AliAnalysisTask(), \n fMCinfo(0), \/\/! MC event handler\n fESD(0),\n fCompList(0), \/\/array of comparison objects\n fGenTracksArray(0), \/\/clones array with filtered particles\n fGenKinkArray(0), \/\/clones array with filtered Kinks\n fGenV0Array(0), \/\/clones array with filtered V0s\n fRecTracksArray(0), \/\/clones array with filtered particles\n fDebugStreamer(0),\n fStreamLevel(0),\n fDebugLevel(0),\n fDebugOutputPath()\n{\n \/\/\n \/\/ Default constructor (should not be used)\n \/\/\n}\n\nAliGenInfoTask::AliGenInfoTask(const AliGenInfoTask& \/*info*\/) : \n AliAnalysisTask(), \n fMCinfo(0), \/\/! MC event handler\n fESD(0),\n fCompList(0),\n fGenTracksArray(0), \/\/clones array with filtered particles\n fGenKinkArray(0), \/\/clones array with filtered Kinks\n fGenV0Array(0), \/\/clones array with filtered V0s\n fRecTracksArray(0), \/\/clones array with filtered particles\n \/\/\n fDebugStreamer(0),\n fStreamLevel(0),\n fDebugLevel(),\n fDebugOutputPath()\n{\n \/\/\n \/\/ Default constructor \n \/\/\n}\n\n\n\n\/\/________________________________________________________________________\nAliGenInfoTask::AliGenInfoTask(const char *name) : \n AliAnalysisTask(name, \"AliGenInfoTask\"), \n fMCinfo(0), \/\/! MC event handler\n fESD(0),\n fCompList(0),\n fGenTracksArray(0), \/\/clones array with filtered particles\n fGenKinkArray(0), \/\/clones array with filtered Kinks\n fGenV0Array(0), \/\/clones array with filtered V0s\n fRecTracksArray(0), \/\/clones array with filtered particles\n fDebugStreamer(0),\n fStreamLevel(0),\n fDebugLevel(0),\n fDebugOutputPath()\n{\n \/\/\n \/\/ Normal constructor\n \/\/\n \/\/ Input slot #0 works with a TChain\n DefineInput(0, TChain::Class());\n \/\/ Output slot #0 writes into a TList\n DefineOutput(0, TObjArray::Class());\n \/\/\n \/\/\n fCompList = new TObjArray;\n}\n\nAliGenInfoTask::~AliGenInfoTask(){\n \/\/\n \/\/\n \/\/\n if (fDebugLevel>0) printf(\"AliGenInfoTask::~AliGenInfoTask\\n\");\n if (fDebugStreamer) delete fDebugStreamer;\n fDebugStreamer=0;\n if(fCompList) delete fCompList; \n fCompList =0; \n}\n\n\n\/\/________________________________________________________________________\nvoid AliGenInfoTask::ConnectInputData(Option_t *) \n{\n \/\/\n \/\/ Connect the input data\n \/\/\n if(fDebugLevel>3)\n cout << \"AnalysisTaskTPCCluster::ConnectInputData()\" << endl;\n\n TTree* tree=dynamic_cast<TTree*>(GetInputData(0));\n if (!tree) {\n \/\/Printf(\"ERROR: Could not read chain from input slot 0\");\n }\n else {\n AliESDInputHandler *esdH = dynamic_cast<AliESDInputHandler*> (AliAnalysisManager::GetAnalysisManager()->GetInputEventHandler());\n if (!esdH) {\n \/\/Printf(\"ERROR: Could not get ESDInputHandler\");\n }\n else {\n fESD = esdH->GetEvent();\n fESDfriend=static_cast<AliESDfriend*>(fESD->FindListObject(\"AliESDfriend\"));\n fESD->SetESDfriend(fESDfriend);\n \/\/Printf(\"*** CONNECTED NEW EVENT ****\");\n } \n }\n AliMCEventHandler* mcinfo = (AliMCEventHandler*) (AliAnalysisManager::GetAnalysisManager()->GetMCtruthEventHandler()); \n mcinfo->SetReadTR(kTRUE);\n \n fMCinfo = mcinfo->MCEvent();\n\n\n}\n\n\n\/\/_____________________________________________________________________________\nBool_t AliGenInfoTask::AddComparisonObject(AliComparisonObject *pObj) \n{\n \/\/ add comparison object to the list\n if(pObj == 0) {\n Printf(\"ERROR: Could not add comparison object\");\n\t return kFALSE;\n }\n \/\/ add object to the list\n fCompList->AddLast(pObj); \n return kTRUE;\n}\n\n\n\n\n\/\/________________________________________________________________________\nvoid AliGenInfoTask::CreateOutputObjects() \n{\n \/\/\n \/\/ Connect the output objects\n \/\/\n if(fDebugLevel>3)\n cout << \"AnalysisTaskTPCCluster::CreateOutputObjects()\" << endl;\n \n}\n\n\n\/\/________________________________________________________________________\nvoid AliGenInfoTask::Exec(Option_t *) {\n \/\/\n \/\/ Execute analysis for current event \n \/\/\n\n if(fDebugLevel>3)\n cout << \"AliGenInfoTask::Exec()\" << endl;\n \n\n \/\/ If MC has been connected \n if (fGenTracksArray) fGenTracksArray->Delete();\n if (fRecTracksArray) fRecTracksArray->Delete();\n\n if (!fMCinfo){\n cout << \"Not MC info\\n\" << endl;\n }else{\n \/\/mcinfo->Print();\n ProcessMCInfo();\n ProcessESDInfo();\n DumpInfo();\n ProcessComparison();\n }\n \/\/\n} \n\n\n\n\n\/\/________________________________________________________________________\nvoid AliGenInfoTask::Terminate(Option_t *) {\n \/\/\n \/\/ Terminate loop\n \/\/\n if(fDebugLevel>3)\n printf(\"AliGenInfoTask: Terminate() \\n\"); \n \/\/\n if (fDebugLevel>0) printf(\"AliTPCcalibBase::Terminate\\n\");\n if (fDebugStreamer) delete fDebugStreamer;\n fDebugStreamer = 0;\n return;\n}\n\n\n\n\n\nTTreeSRedirector *AliGenInfoTask::GetDebugStreamer(){\n \/\/\n \/\/ Get Debug streamer\n \/\/ In case debug streamer not yet initialized and StreamLevel>0 create new one\n \/\/\n if (fStreamLevel==0) return 0;\n if (fDebugStreamer) return fDebugStreamer;\n TString dsName;\n dsName=GetName();\n dsName+=\"Debug.root\";\n dsName.ReplaceAll(\" \",\"\");\n fDebugStreamer = new TTreeSRedirector(dsName.Data());\n return fDebugStreamer;\n}\n\n\n\nAliMCInfo* AliGenInfoTask::GetTrack(Int_t index, Bool_t force){\n \/\/\n \/\/ Get the MC info for given track\n \/\/\n if (!fGenTracksArray) fGenTracksArray = new TClonesArray(\"AliMCInfo\",1000);\n if (index>fGenTracksArray->GetEntriesFast()) fGenTracksArray->Expand(index*2+10);\n AliMCInfo * info = (AliMCInfo*)fGenTracksArray->At(index);\n if (!force) return info;\n if (!info){\n info = new ((*fGenTracksArray)[index]) AliMCInfo;\n }\n return info;\n}\n\nAliESDRecInfo* AliGenInfoTask::GetRecTrack(Int_t index, Bool_t force){\n \/\/\n \/\/ Get the MC info for given track\n \/\/\n if (!fRecTracksArray) fRecTracksArray = new TClonesArray(\"AliESDRecInfo\",1000);\n if (index>fRecTracksArray->GetEntriesFast()) fRecTracksArray->Expand(index*2+10);\n AliESDRecInfo * info = (AliESDRecInfo*)fRecTracksArray->At(index);\n if (!force) return info;\n if (!info){\n info = new ((*fRecTracksArray)[index]) AliESDRecInfo;\n }\n return info;\n}\n\n\n\n\nvoid AliGenInfoTask::ProcessMCInfo(){\n \/\/\n \/\/ Dump information from MC to the array\n \/\/\n \/\/\n TParticle * particle= new TParticle;\n TClonesArray * trefs = new TClonesArray(\"AliTrackReference\");\n \/\/\n \/\/\n \/\/ Process tracks\n \/\/\n Int_t npart = fMCinfo->GetNumberOfTracks();\n if (npart==0) return;\n Double_t vertex[4]={0,0,0,0};\n fMCinfo->GetParticleAndTR(0, particle, trefs);\n if (particle){\n vertex[0]=particle->Vx();\n vertex[1]=particle->Vy();\n vertex[2]=particle->Vz();\n vertex[3]=particle->R();\n }\n\n for (Int_t ipart=0;ipart<npart;ipart++){\n Int_t status = fMCinfo->GetParticleAndTR(ipart, particle, trefs);\n if (status<0) continue;\n if (!particle) continue;\n if (!trefs) continue;\n if (!AcceptParticle(particle)) continue;\n \/\/if (trefs->GetEntries()<1) continue;\n AliMCInfo * mcinfo = GetTrack(ipart,kTRUE);\n mcinfo->Update(particle,trefs,vertex,ipart);\n \/\/\n TTreeSRedirector *pcstream = GetDebugStreamer();\n if (pcstream){\n (*pcstream)<<\"MC\"<<\n\t\"p.=\"<<particle<<\n\t\"MC.=\"<<mcinfo<<\n\t\"\\n\";\n }\n }\n}\n\nvoid AliGenInfoTask::ProcessESDInfo(){\n \/\/\n \/\/\n \/\/\n static AliTPCParamSR param;\n fESDfriend=static_cast<AliESDfriend*>(fESD->FindListObject(\"AliESDfriend\"));\n if (!fESDfriend) {\n \/\/Printf(\"ERROR: fESDfriend not available\");\n return;\n }\n fESD->SetESDfriend(fESDfriend);\n \/\/\n \/\/\n if (!fESD) return;\n Int_t ntracks = fESD->GetNumberOfTracks();\n for (Int_t itrack=0; itrack<ntracks; itrack++){\n AliESDtrack *track = fESD->GetTrack(itrack);\n Int_t label = TMath::Abs(track->GetLabel());\n AliMCInfo * mcinfo = GetTrack(label,kFALSE);\n if (!mcinfo) continue;\n AliESDRecInfo *recInfo= GetRecTrack(label,kTRUE);\n recInfo->AddESDtrack(track,mcinfo);\n recInfo->Update(mcinfo,¶m,kTRUE);\n }\n \/\/\n\n\n} \n\n\nvoid AliGenInfoTask::ProcessComparison(){\n \/\/\n \/\/\n \/\/\n static AliESDRecInfo dummy;\n Int_t npart = fMCinfo->GetNumberOfTracks();\n for (Int_t ipart=0;ipart<npart;ipart++){\n AliMCInfo * mcinfo = GetTrack(ipart,kFALSE);\n if (!mcinfo) continue;\n AliESDRecInfo *recInfo= GetRecTrack(ipart,kFALSE);\n if (!recInfo) recInfo=&dummy; \n \/\/\n for (Int_t icomp = 0; icomp<fCompList->GetEntries(); icomp++){\n AliComparisonObject *pObj= (AliComparisonObject *)fCompList->At(icomp);\n if (pObj){\n\tpObj->Exec(mcinfo,recInfo);\n }\n } \n }\n PostData(0, fCompList);\n}\n\nvoid AliGenInfoTask::DumpInfo(){\n \/\/\n \/\/\n \/\/\n\n static AliESDRecInfo dummy;\n Int_t npart = fMCinfo->GetNumberOfTracks();\n for (Int_t ipart=0;ipart<npart;ipart++){\n AliMCInfo * mcinfo = GetTrack(ipart,kFALSE);\n if (!mcinfo) continue;\n AliESDRecInfo *recInfo= GetRecTrack(ipart,kFALSE);\n \/\/\n \/\/ AliTPCseed *tpctrack=0;\n\/\/ if (recInfo) {\n\/\/ AliESDfriendTrack *friendTrack=fESDfriend->GetTrack(recInfo->GetESDtrack()->GetID());\n\/\/ if (friendTrack) {\n\/\/ \tTObject *calibObject=0;\n\/\/ \tAliTPCseed *seed=0;\n\/\/ \tfor (Int_t j=0;(calibObject=friendTrack->GetCalibObject(j));++j)\n\/\/ \t if ((seed=dynamic_cast<AliTPCseed*>(calibObject)))\n\/\/ \t break;\n\/\/ \ttpctrack=seed;\n\/\/ }\n\/\/ }\n\/\/ if (!tpctrack) continue;\n if (!recInfo) recInfo=&dummy; \n TTreeSRedirector *pcstream = GetDebugStreamer();\n if (pcstream){\n (*pcstream)<<\"RC\"<<\t\n\t\"MC.=\"<<mcinfo<<\n\t\"RC.=\"<<recInfo<<\n\t\/\/\t\"tr.=\"<<tpctrack<<\n\t\"\\n\";\n } \n }\n}\n\n\n\nBool_t AliGenInfoTask::AcceptParticle(TParticle *part){\n \/\/\n \/*\n MC cuts\n TCut cutPt(\"p.Pt()>0.1\");\n TCut cutZ(\"abs(p.Vz())<250\");\n TCut cutR(\"abs(p.R())<250\");\n \/\/\n *\/\n \/\/\n \/\/\n if (part->Pt()<0.1) return kFALSE;\n if (TMath::Abs(part->Vz())>250) return kFALSE;\n if (part->R()>360) return kFALSE;\n if (part->GetPDG()){\n if (part->GetPDG()->Charge()==0) return kFALSE;\n }\n return kTRUE;\n}\n\n\n\nvoid AliGenInfoTask::FinishTaskOutput()\n{\n \/\/\n \/\/ According description in AliAnalisysTask this method is call\n \/\/ on the slaves before sending data\n \/\/\n Terminate(\"slave\");\n RegisterDebugOutput(fDebugOutputPath.Data());\n\n}\n\n\n\nvoid AliGenInfoTask::RegisterDebugOutput(const char *path){\n \/\/\n \/\/ store - copy debug output to the destination position\n \/\/ currently ONLY for local copy\n TString dsName;\n dsName=GetName();\n dsName+=\"Debug.root\";\n dsName.ReplaceAll(\" \",\"\");\n TString dsName2=fDebugOutputPath.Data();\n gSystem->MakeDirectory(dsName2.Data());\n dsName2+=\"\/\";;\n dsName2+=gSystem->HostName();\n gSystem->MakeDirectory(dsName2.Data());\n dsName2+=\"\/\";\n dsName2+=gSystem->BaseName(gSystem->pwd());\n dsName2+=\"\/\";\n gSystem->MakeDirectory(dsName2.Data());\n dsName2+=dsName;\n AliInfo(Form(\"copy %s\\t%s\\n\",dsName.Data(),dsName2.Data()));\n printf(\"copy %s\\t%s\\n\",dsName.Data(),dsName2.Data());\n TFile::Cp(dsName.Data(),dsName2.Data());\n}\n<commit_msg>Fix warning<commit_after>\/\/\n\/\/ This class is the task for connecting together \n\/\/ MC information and the RC information \n\/\/\n\/\/ The task is a wrapper over two components\n\/\/ AliGenInfoMaker\n\/\/ AliESDRecInfoMaker.h\n\n\/\/ ROOT includes\n#include <TChain.h>\n#include <TMath.h>\n\n\/\/ ALIROOT includes\n#include <TTreeStream.h>\n#include <AliAnalysisManager.h>\n#include <AliESDInputHandler.h>\n#include \"AliStack.h\"\n#include \"AliMCEvent.h\"\n#include \"AliMCEventHandler.h\"\n\n#include <AliESD.h>\n#include \"AliGenInfoTask.h\"\n#include \"AliGenInfoMaker.h\"\n#include \"AliHelix.h\"\n\n\/\/\n#include \"AliMCInfo.h\"\n#include \"AliComparisonObject.h\"\n#include \"AliESDRecInfo.h\"\n#include \"AliTPCParamSR.h\"\n#include \"TSystem.h\"\n#include \"TTimeStamp.h\"\n#include \"TFile.h\"\n#include \"AliTPCseed.h\"\n\n\/\/ STL includes\n#include <iostream>\n\nusing namespace std;\n\nClassImp(AliGenInfoTask)\n\n\/\/________________________________________________________________________\nAliGenInfoTask::AliGenInfoTask() : \n AliAnalysisTask(), \n fMCinfo(0), \/\/! MC event handler\n fESD(0),\n fESDfriend(0),\n fCompList(0), \/\/array of comparison objects\n fGenTracksArray(0), \/\/clones array with filtered particles\n fGenKinkArray(0), \/\/clones array with filtered Kinks\n fGenV0Array(0), \/\/clones array with filtered V0s\n fRecTracksArray(0), \/\/clones array with filtered particles\n fDebugStreamer(0),\n fStreamLevel(0),\n fDebugLevel(0),\n fDebugOutputPath()\n{\n \/\/\n \/\/ Default constructor (should not be used)\n \/\/\n}\n\nAliGenInfoTask::AliGenInfoTask(const AliGenInfoTask& \/*info*\/) : \n AliAnalysisTask(), \n fMCinfo(0), \/\/! MC event handler\n fESD(0),\n fESDfriend(0),\n fCompList(0),\n fGenTracksArray(0), \/\/clones array with filtered particles\n fGenKinkArray(0), \/\/clones array with filtered Kinks\n fGenV0Array(0), \/\/clones array with filtered V0s\n fRecTracksArray(0), \/\/clones array with filtered particles\n \/\/\n fDebugStreamer(0),\n fStreamLevel(0),\n fDebugLevel(),\n fDebugOutputPath()\n{\n \/\/\n \/\/ Default constructor \n \/\/\n}\n\n\n\n\/\/________________________________________________________________________\nAliGenInfoTask::AliGenInfoTask(const char *name) : \n AliAnalysisTask(name, \"AliGenInfoTask\"), \n fMCinfo(0), \/\/! MC event handler\n fESD(0),\n fESDfriend(0),\n fCompList(0),\n fGenTracksArray(0), \/\/clones array with filtered particles\n fGenKinkArray(0), \/\/clones array with filtered Kinks\n fGenV0Array(0), \/\/clones array with filtered V0s\n fRecTracksArray(0), \/\/clones array with filtered particles\n fDebugStreamer(0),\n fStreamLevel(0),\n fDebugLevel(0),\n fDebugOutputPath()\n{\n \/\/\n \/\/ Normal constructor\n \/\/\n \/\/ Input slot #0 works with a TChain\n DefineInput(0, TChain::Class());\n \/\/ Output slot #0 writes into a TList\n DefineOutput(0, TObjArray::Class());\n \/\/\n \/\/\n fCompList = new TObjArray;\n}\n\nAliGenInfoTask::~AliGenInfoTask(){\n \/\/\n \/\/\n \/\/\n if (fDebugLevel>0) printf(\"AliGenInfoTask::~AliGenInfoTask\\n\");\n if (fDebugStreamer) delete fDebugStreamer;\n fDebugStreamer=0;\n if(fCompList) delete fCompList; \n fCompList =0; \n}\n\n\n\/\/________________________________________________________________________\nvoid AliGenInfoTask::ConnectInputData(Option_t *) \n{\n \/\/\n \/\/ Connect the input data\n \/\/\n if(fDebugLevel>3)\n cout << \"AnalysisTaskTPCCluster::ConnectInputData()\" << endl;\n\n TTree* tree=dynamic_cast<TTree*>(GetInputData(0));\n if (!tree) {\n \/\/Printf(\"ERROR: Could not read chain from input slot 0\");\n }\n else {\n AliESDInputHandler *esdH = dynamic_cast<AliESDInputHandler*> (AliAnalysisManager::GetAnalysisManager()->GetInputEventHandler());\n if (!esdH) {\n \/\/Printf(\"ERROR: Could not get ESDInputHandler\");\n }\n else {\n fESD = esdH->GetEvent();\n fESDfriend=static_cast<AliESDfriend*>(fESD->FindListObject(\"AliESDfriend\"));\n fESD->SetESDfriend(fESDfriend);\n \/\/Printf(\"*** CONNECTED NEW EVENT ****\");\n } \n }\n AliMCEventHandler* mcinfo = (AliMCEventHandler*) (AliAnalysisManager::GetAnalysisManager()->GetMCtruthEventHandler()); \n mcinfo->SetReadTR(kTRUE);\n \n fMCinfo = mcinfo->MCEvent();\n\n\n}\n\n\n\/\/_____________________________________________________________________________\nBool_t AliGenInfoTask::AddComparisonObject(AliComparisonObject *pObj) \n{\n \/\/ add comparison object to the list\n if(pObj == 0) {\n Printf(\"ERROR: Could not add comparison object\");\n\t return kFALSE;\n }\n \/\/ add object to the list\n fCompList->AddLast(pObj); \n return kTRUE;\n}\n\n\n\n\n\/\/________________________________________________________________________\nvoid AliGenInfoTask::CreateOutputObjects() \n{\n \/\/\n \/\/ Connect the output objects\n \/\/\n if(fDebugLevel>3)\n cout << \"AnalysisTaskTPCCluster::CreateOutputObjects()\" << endl;\n \n}\n\n\n\/\/________________________________________________________________________\nvoid AliGenInfoTask::Exec(Option_t *) {\n \/\/\n \/\/ Execute analysis for current event \n \/\/\n\n if(fDebugLevel>3)\n cout << \"AliGenInfoTask::Exec()\" << endl;\n \n\n \/\/ If MC has been connected \n if (fGenTracksArray) fGenTracksArray->Delete();\n if (fRecTracksArray) fRecTracksArray->Delete();\n\n if (!fMCinfo){\n cout << \"Not MC info\\n\" << endl;\n }else{\n \/\/mcinfo->Print();\n ProcessMCInfo();\n ProcessESDInfo();\n DumpInfo();\n ProcessComparison();\n }\n \/\/\n} \n\n\n\n\n\/\/________________________________________________________________________\nvoid AliGenInfoTask::Terminate(Option_t *) {\n \/\/\n \/\/ Terminate loop\n \/\/\n if(fDebugLevel>3)\n printf(\"AliGenInfoTask: Terminate() \\n\"); \n \/\/\n if (fDebugLevel>0) printf(\"AliTPCcalibBase::Terminate\\n\");\n if (fDebugStreamer) delete fDebugStreamer;\n fDebugStreamer = 0;\n return;\n}\n\n\n\n\n\nTTreeSRedirector *AliGenInfoTask::GetDebugStreamer(){\n \/\/\n \/\/ Get Debug streamer\n \/\/ In case debug streamer not yet initialized and StreamLevel>0 create new one\n \/\/\n if (fStreamLevel==0) return 0;\n if (fDebugStreamer) return fDebugStreamer;\n TString dsName;\n dsName=GetName();\n dsName+=\"Debug.root\";\n dsName.ReplaceAll(\" \",\"\");\n fDebugStreamer = new TTreeSRedirector(dsName.Data());\n return fDebugStreamer;\n}\n\n\n\nAliMCInfo* AliGenInfoTask::GetTrack(Int_t index, Bool_t force){\n \/\/\n \/\/ Get the MC info for given track\n \/\/\n if (!fGenTracksArray) fGenTracksArray = new TClonesArray(\"AliMCInfo\",1000);\n if (index>fGenTracksArray->GetEntriesFast()) fGenTracksArray->Expand(index*2+10);\n AliMCInfo * info = (AliMCInfo*)fGenTracksArray->At(index);\n if (!force) return info;\n if (!info){\n info = new ((*fGenTracksArray)[index]) AliMCInfo;\n }\n return info;\n}\n\nAliESDRecInfo* AliGenInfoTask::GetRecTrack(Int_t index, Bool_t force){\n \/\/\n \/\/ Get the MC info for given track\n \/\/\n if (!fRecTracksArray) fRecTracksArray = new TClonesArray(\"AliESDRecInfo\",1000);\n if (index>fRecTracksArray->GetEntriesFast()) fRecTracksArray->Expand(index*2+10);\n AliESDRecInfo * info = (AliESDRecInfo*)fRecTracksArray->At(index);\n if (!force) return info;\n if (!info){\n info = new ((*fRecTracksArray)[index]) AliESDRecInfo;\n }\n return info;\n}\n\n\n\n\nvoid AliGenInfoTask::ProcessMCInfo(){\n \/\/\n \/\/ Dump information from MC to the array\n \/\/\n \/\/\n TParticle * particle= new TParticle;\n TClonesArray * trefs = new TClonesArray(\"AliTrackReference\");\n \/\/\n \/\/\n \/\/ Process tracks\n \/\/\n Int_t npart = fMCinfo->GetNumberOfTracks();\n if (npart==0) return;\n Double_t vertex[4]={0,0,0,0};\n fMCinfo->GetParticleAndTR(0, particle, trefs);\n if (particle){\n vertex[0]=particle->Vx();\n vertex[1]=particle->Vy();\n vertex[2]=particle->Vz();\n vertex[3]=particle->R();\n }\n\n for (Int_t ipart=0;ipart<npart;ipart++){\n Int_t status = fMCinfo->GetParticleAndTR(ipart, particle, trefs);\n if (status<0) continue;\n if (!particle) continue;\n if (!trefs) continue;\n if (!AcceptParticle(particle)) continue;\n \/\/if (trefs->GetEntries()<1) continue;\n AliMCInfo * mcinfo = GetTrack(ipart,kTRUE);\n mcinfo->Update(particle,trefs,vertex,ipart);\n \/\/\n TTreeSRedirector *pcstream = GetDebugStreamer();\n if (pcstream){\n (*pcstream)<<\"MC\"<<\n\t\"p.=\"<<particle<<\n\t\"MC.=\"<<mcinfo<<\n\t\"\\n\";\n }\n }\n}\n\nvoid AliGenInfoTask::ProcessESDInfo(){\n \/\/\n \/\/\n \/\/\n static AliTPCParamSR param;\n fESDfriend=static_cast<AliESDfriend*>(fESD->FindListObject(\"AliESDfriend\"));\n if (!fESDfriend) {\n \/\/Printf(\"ERROR: fESDfriend not available\");\n return;\n }\n fESD->SetESDfriend(fESDfriend);\n \/\/\n \/\/\n if (!fESD) return;\n Int_t ntracks = fESD->GetNumberOfTracks();\n for (Int_t itrack=0; itrack<ntracks; itrack++){\n AliESDtrack *track = fESD->GetTrack(itrack);\n Int_t label = TMath::Abs(track->GetLabel());\n AliMCInfo * mcinfo = GetTrack(label,kFALSE);\n if (!mcinfo) continue;\n AliESDRecInfo *recInfo= GetRecTrack(label,kTRUE);\n recInfo->AddESDtrack(track,mcinfo);\n recInfo->Update(mcinfo,¶m,kTRUE);\n }\n \/\/\n\n\n} \n\n\nvoid AliGenInfoTask::ProcessComparison(){\n \/\/\n \/\/\n \/\/\n static AliESDRecInfo dummy;\n Int_t npart = fMCinfo->GetNumberOfTracks();\n for (Int_t ipart=0;ipart<npart;ipart++){\n AliMCInfo * mcinfo = GetTrack(ipart,kFALSE);\n if (!mcinfo) continue;\n AliESDRecInfo *recInfo= GetRecTrack(ipart,kFALSE);\n if (!recInfo) recInfo=&dummy; \n \/\/\n for (Int_t icomp = 0; icomp<fCompList->GetEntries(); icomp++){\n AliComparisonObject *pObj= (AliComparisonObject *)fCompList->At(icomp);\n if (pObj){\n\tpObj->Exec(mcinfo,recInfo);\n }\n } \n }\n PostData(0, fCompList);\n}\n\nvoid AliGenInfoTask::DumpInfo(){\n \/\/\n \/\/\n \/\/\n\n static AliESDRecInfo dummy;\n Int_t npart = fMCinfo->GetNumberOfTracks();\n for (Int_t ipart=0;ipart<npart;ipart++){\n AliMCInfo * mcinfo = GetTrack(ipart,kFALSE);\n if (!mcinfo) continue;\n AliESDRecInfo *recInfo= GetRecTrack(ipart,kFALSE);\n \/\/\n \/\/ AliTPCseed *tpctrack=0;\n\/\/ if (recInfo) {\n\/\/ AliESDfriendTrack *friendTrack=fESDfriend->GetTrack(recInfo->GetESDtrack()->GetID());\n\/\/ if (friendTrack) {\n\/\/ \tTObject *calibObject=0;\n\/\/ \tAliTPCseed *seed=0;\n\/\/ \tfor (Int_t j=0;(calibObject=friendTrack->GetCalibObject(j));++j)\n\/\/ \t if ((seed=dynamic_cast<AliTPCseed*>(calibObject)))\n\/\/ \t break;\n\/\/ \ttpctrack=seed;\n\/\/ }\n\/\/ }\n\/\/ if (!tpctrack) continue;\n if (!recInfo) recInfo=&dummy; \n TTreeSRedirector *pcstream = GetDebugStreamer();\n if (pcstream){\n (*pcstream)<<\"RC\"<<\t\n\t\"MC.=\"<<mcinfo<<\n\t\"RC.=\"<<recInfo<<\n\t\/\/\t\"tr.=\"<<tpctrack<<\n\t\"\\n\";\n } \n }\n}\n\n\n\nBool_t AliGenInfoTask::AcceptParticle(TParticle *part){\n \/\/\n \/*\n MC cuts\n TCut cutPt(\"p.Pt()>0.1\");\n TCut cutZ(\"abs(p.Vz())<250\");\n TCut cutR(\"abs(p.R())<250\");\n \/\/\n *\/\n \/\/\n \/\/\n if (part->Pt()<0.1) return kFALSE;\n if (TMath::Abs(part->Vz())>250) return kFALSE;\n if (part->R()>360) return kFALSE;\n if (part->GetPDG()){\n if (part->GetPDG()->Charge()==0) return kFALSE;\n }\n return kTRUE;\n}\n\n\n\nvoid AliGenInfoTask::FinishTaskOutput()\n{\n \/\/\n \/\/ According description in AliAnalisysTask this method is call\n \/\/ on the slaves before sending data\n \/\/\n Terminate(\"slave\");\n RegisterDebugOutput(fDebugOutputPath.Data());\n\n}\n\n\n\nvoid AliGenInfoTask::RegisterDebugOutput(const char *\/*path*\/){\n \/\/\n \/\/ store - copy debug output to the destination position\n \/\/ currently ONLY for local copy\n TString dsName;\n dsName=GetName();\n dsName+=\"Debug.root\";\n dsName.ReplaceAll(\" \",\"\");\n TString dsName2=fDebugOutputPath.Data();\n gSystem->MakeDirectory(dsName2.Data());\n dsName2+=\"\/\";;\n dsName2+=gSystem->HostName();\n gSystem->MakeDirectory(dsName2.Data());\n dsName2+=\"\/\";\n dsName2+=gSystem->BaseName(gSystem->pwd());\n dsName2+=\"\/\";\n gSystem->MakeDirectory(dsName2.Data());\n dsName2+=dsName;\n AliInfo(Form(\"copy %s\\t%s\\n\",dsName.Data(),dsName2.Data()));\n printf(\"copy %s\\t%s\\n\",dsName.Data(),dsName2.Data());\n TFile::Cp(dsName.Data(),dsName2.Data());\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2009 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include <gdk\/gdkkeysyms.h>\n#include <X11\/XF86keysym.h>\n\n#include \"chrome\/browser\/accelerator_table_linux.h\"\n\n#include \"base\/basictypes.h\"\n#include \"chrome\/app\/chrome_dll_resource.h\"\n\nnamespace browser {\n\n\/\/ Keep this in sync with various context menus which display the accelerators.\nconst AcceleratorMapping kAcceleratorMap[] = {\n \/\/ Focus.\n { GDK_k, IDC_FOCUS_SEARCH, GDK_CONTROL_MASK },\n { GDK_e, IDC_FOCUS_SEARCH, GDK_CONTROL_MASK },\n { XF86XK_Search, IDC_FOCUS_SEARCH, GdkModifierType(0) },\n { GDK_l, IDC_FOCUS_LOCATION, GDK_CONTROL_MASK },\n { GDK_d, IDC_FOCUS_LOCATION, GDK_MOD1_MASK },\n { GDK_F6, IDC_FOCUS_LOCATION, GdkModifierType(0) },\n { XF86XK_OpenURL, IDC_FOCUS_LOCATION, GdkModifierType(0) },\n { XF86XK_Go, IDC_FOCUS_LOCATION, GdkModifierType(0) },\n\n \/\/ Tab\/window controls.\n { GDK_Page_Down, IDC_SELECT_NEXT_TAB, GDK_CONTROL_MASK },\n { GDK_Page_Up, IDC_SELECT_PREVIOUS_TAB, GDK_CONTROL_MASK },\n { GDK_w, IDC_CLOSE_TAB, GDK_CONTROL_MASK },\n { GDK_t, IDC_RESTORE_TAB,\n GdkModifierType(GDK_CONTROL_MASK | GDK_SHIFT_MASK) },\n\n { GDK_1, IDC_SELECT_TAB_0, GDK_CONTROL_MASK },\n { GDK_2, IDC_SELECT_TAB_1, GDK_CONTROL_MASK },\n { GDK_3, IDC_SELECT_TAB_2, GDK_CONTROL_MASK },\n { GDK_4, IDC_SELECT_TAB_3, GDK_CONTROL_MASK },\n { GDK_5, IDC_SELECT_TAB_4, GDK_CONTROL_MASK },\n { GDK_6, IDC_SELECT_TAB_5, GDK_CONTROL_MASK },\n { GDK_7, IDC_SELECT_TAB_6, GDK_CONTROL_MASK },\n { GDK_8, IDC_SELECT_TAB_7, GDK_CONTROL_MASK },\n { GDK_9, IDC_SELECT_LAST_TAB, GDK_CONTROL_MASK },\n\n { GDK_1, IDC_SELECT_TAB_0, GDK_MOD1_MASK },\n { GDK_2, IDC_SELECT_TAB_1, GDK_MOD1_MASK },\n { GDK_3, IDC_SELECT_TAB_2, GDK_MOD1_MASK },\n { GDK_4, IDC_SELECT_TAB_3, GDK_MOD1_MASK },\n { GDK_5, IDC_SELECT_TAB_4, GDK_MOD1_MASK },\n { GDK_6, IDC_SELECT_TAB_5, GDK_MOD1_MASK },\n { GDK_7, IDC_SELECT_TAB_6, GDK_MOD1_MASK },\n { GDK_8, IDC_SELECT_TAB_7, GDK_MOD1_MASK },\n { GDK_9, IDC_SELECT_LAST_TAB, GDK_MOD1_MASK },\n\n { GDK_F4, IDC_CLOSE_TAB, GDK_CONTROL_MASK },\n { GDK_F4, IDC_CLOSE_WINDOW, GDK_MOD1_MASK },\n\n \/\/ Zoom level.\n { GDK_plus, IDC_ZOOM_PLUS,\n GdkModifierType(GDK_CONTROL_MASK | GDK_SHIFT_MASK) },\n { GDK_equal, IDC_ZOOM_PLUS, GDK_CONTROL_MASK },\n { XF86XK_ZoomIn, IDC_ZOOM_PLUS, GdkModifierType(0) },\n { GDK_0, IDC_ZOOM_NORMAL, GDK_CONTROL_MASK },\n { GDK_minus, IDC_ZOOM_MINUS, GDK_CONTROL_MASK },\n { GDK_underscore, IDC_ZOOM_MINUS,\n GdkModifierType(GDK_CONTROL_MASK | GDK_SHIFT_MASK) },\n { XF86XK_ZoomOut, IDC_ZOOM_MINUS, GdkModifierType(0) },\n\n \/\/ Find in page.\n { GDK_g, IDC_FIND_NEXT, GDK_CONTROL_MASK },\n { GDK_F3, IDC_FIND_NEXT, GdkModifierType(0) },\n { GDK_g, IDC_FIND_PREVIOUS,\n GdkModifierType(GDK_CONTROL_MASK | GDK_SHIFT_MASK) },\n { GDK_F3, IDC_FIND_PREVIOUS, GDK_SHIFT_MASK },\n\n \/\/ Navigation \/ toolbar buttons.\n { GDK_Home, IDC_HOME, GDK_MOD1_MASK },\n { XF86XK_HomePage, IDC_HOME, GdkModifierType(0) },\n { GDK_Escape, IDC_STOP, GdkModifierType(0) },\n { XF86XK_Stop, IDC_STOP, GdkModifierType(0) },\n { GDK_Left, IDC_BACK, GDK_MOD1_MASK },\n { GDK_BackSpace, IDC_BACK, GdkModifierType(0) },\n { XF86XK_Back, IDC_BACK, GdkModifierType(0) },\n { GDK_Right, IDC_FORWARD, GDK_MOD1_MASK },\n { GDK_BackSpace, IDC_FORWARD, GDK_SHIFT_MASK },\n { XF86XK_Forward, IDC_FORWARD, GdkModifierType(0) },\n { GDK_r, IDC_RELOAD, GDK_CONTROL_MASK },\n { GDK_F5, IDC_RELOAD, GdkModifierType(0) },\n { GDK_F5, IDC_RELOAD, GDK_CONTROL_MASK },\n { GDK_F5, IDC_RELOAD, GDK_SHIFT_MASK },\n { XF86XK_Reload, IDC_RELOAD, GdkModifierType(0) },\n { XF86XK_Refresh, IDC_RELOAD, GdkModifierType(0) },\n\n \/\/ Miscellany.\n { GDK_d, IDC_STAR, GDK_CONTROL_MASK },\n { XF86XK_AddFavorite, IDC_STAR, GdkModifierType(0) },\n { XF86XK_Favorites, IDC_SHOW_BOOKMARK_BAR, GdkModifierType(0) },\n { XF86XK_History, IDC_SHOW_HISTORY, GdkModifierType(0) },\n { GDK_o, IDC_OPEN_FILE, GDK_CONTROL_MASK },\n { GDK_F11, IDC_FULLSCREEN, GdkModifierType(0) },\n { GDK_u, IDC_VIEW_SOURCE, GDK_CONTROL_MASK },\n { GDK_p, IDC_PRINT, GDK_CONTROL_MASK },\n { GDK_Escape, IDC_TASK_MANAGER, GDK_SHIFT_MASK },\n\n#if defined(OS_CHROMEOS)\n { GDK_f, IDC_FULLSCREEN,\n GdkModifierType(GDK_CONTROL_MASK | GDK_MOD1_MASK) },\n { GDK_Delete, IDC_TASK_MANAGER,\n GdkModifierType(GDK_CONTROL_MASK | GDK_MOD1_MASK) },\n { GDK_comma, IDC_CONTROL_PANEL, GdkModifierType(GDK_CONTROL_MASK) },\n#endif\n};\n\nconst size_t kAcceleratorMapLength = arraysize(kAcceleratorMap);\n\n} \/\/ namespace browser\n<commit_msg>GTK: Allow keypad to be used for all tab selection accelerators.<commit_after>\/\/ Copyright (c) 2009 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include <gdk\/gdkkeysyms.h>\n#include <X11\/XF86keysym.h>\n\n#include \"chrome\/browser\/accelerator_table_linux.h\"\n\n#include \"base\/basictypes.h\"\n#include \"chrome\/app\/chrome_dll_resource.h\"\n\nnamespace browser {\n\n\/\/ Keep this in sync with various context menus which display the accelerators.\nconst AcceleratorMapping kAcceleratorMap[] = {\n \/\/ Focus.\n { GDK_k, IDC_FOCUS_SEARCH, GDK_CONTROL_MASK },\n { GDK_e, IDC_FOCUS_SEARCH, GDK_CONTROL_MASK },\n { XF86XK_Search, IDC_FOCUS_SEARCH, GdkModifierType(0) },\n { GDK_l, IDC_FOCUS_LOCATION, GDK_CONTROL_MASK },\n { GDK_d, IDC_FOCUS_LOCATION, GDK_MOD1_MASK },\n { GDK_F6, IDC_FOCUS_LOCATION, GdkModifierType(0) },\n { XF86XK_OpenURL, IDC_FOCUS_LOCATION, GdkModifierType(0) },\n { XF86XK_Go, IDC_FOCUS_LOCATION, GdkModifierType(0) },\n\n \/\/ Tab\/window controls.\n { GDK_Page_Down, IDC_SELECT_NEXT_TAB, GDK_CONTROL_MASK },\n { GDK_Page_Up, IDC_SELECT_PREVIOUS_TAB, GDK_CONTROL_MASK },\n { GDK_w, IDC_CLOSE_TAB, GDK_CONTROL_MASK },\n { GDK_t, IDC_RESTORE_TAB,\n GdkModifierType(GDK_CONTROL_MASK | GDK_SHIFT_MASK) },\n\n { GDK_1, IDC_SELECT_TAB_0, GDK_CONTROL_MASK },\n { GDK_2, IDC_SELECT_TAB_1, GDK_CONTROL_MASK },\n { GDK_3, IDC_SELECT_TAB_2, GDK_CONTROL_MASK },\n { GDK_4, IDC_SELECT_TAB_3, GDK_CONTROL_MASK },\n { GDK_5, IDC_SELECT_TAB_4, GDK_CONTROL_MASK },\n { GDK_6, IDC_SELECT_TAB_5, GDK_CONTROL_MASK },\n { GDK_7, IDC_SELECT_TAB_6, GDK_CONTROL_MASK },\n { GDK_8, IDC_SELECT_TAB_7, GDK_CONTROL_MASK },\n { GDK_9, IDC_SELECT_LAST_TAB, GDK_CONTROL_MASK },\n\n { GDK_1, IDC_SELECT_TAB_0, GDK_MOD1_MASK },\n { GDK_2, IDC_SELECT_TAB_1, GDK_MOD1_MASK },\n { GDK_3, IDC_SELECT_TAB_2, GDK_MOD1_MASK },\n { GDK_4, IDC_SELECT_TAB_3, GDK_MOD1_MASK },\n { GDK_5, IDC_SELECT_TAB_4, GDK_MOD1_MASK },\n { GDK_6, IDC_SELECT_TAB_5, GDK_MOD1_MASK },\n { GDK_7, IDC_SELECT_TAB_6, GDK_MOD1_MASK },\n { GDK_8, IDC_SELECT_TAB_7, GDK_MOD1_MASK },\n { GDK_9, IDC_SELECT_LAST_TAB, GDK_MOD1_MASK },\n\n { GDK_KP_1, IDC_SELECT_TAB_0, GDK_CONTROL_MASK },\n { GDK_KP_2, IDC_SELECT_TAB_1, GDK_CONTROL_MASK },\n { GDK_KP_3, IDC_SELECT_TAB_2, GDK_CONTROL_MASK },\n { GDK_KP_4, IDC_SELECT_TAB_3, GDK_CONTROL_MASK },\n { GDK_KP_5, IDC_SELECT_TAB_4, GDK_CONTROL_MASK },\n { GDK_KP_6, IDC_SELECT_TAB_5, GDK_CONTROL_MASK },\n { GDK_KP_7, IDC_SELECT_TAB_6, GDK_CONTROL_MASK },\n { GDK_KP_8, IDC_SELECT_TAB_7, GDK_CONTROL_MASK },\n { GDK_KP_9, IDC_SELECT_LAST_TAB, GDK_CONTROL_MASK },\n\n { GDK_KP_1, IDC_SELECT_TAB_0, GDK_MOD1_MASK },\n { GDK_KP_2, IDC_SELECT_TAB_1, GDK_MOD1_MASK },\n { GDK_KP_3, IDC_SELECT_TAB_2, GDK_MOD1_MASK },\n { GDK_KP_4, IDC_SELECT_TAB_3, GDK_MOD1_MASK },\n { GDK_KP_5, IDC_SELECT_TAB_4, GDK_MOD1_MASK },\n { GDK_KP_6, IDC_SELECT_TAB_5, GDK_MOD1_MASK },\n { GDK_KP_7, IDC_SELECT_TAB_6, GDK_MOD1_MASK },\n { GDK_KP_8, IDC_SELECT_TAB_7, GDK_MOD1_MASK },\n { GDK_KP_9, IDC_SELECT_LAST_TAB, GDK_MOD1_MASK },\n\n { GDK_F4, IDC_CLOSE_TAB, GDK_CONTROL_MASK },\n { GDK_F4, IDC_CLOSE_WINDOW, GDK_MOD1_MASK },\n\n \/\/ Zoom level.\n { GDK_plus, IDC_ZOOM_PLUS,\n GdkModifierType(GDK_CONTROL_MASK | GDK_SHIFT_MASK) },\n { GDK_equal, IDC_ZOOM_PLUS, GDK_CONTROL_MASK },\n { XF86XK_ZoomIn, IDC_ZOOM_PLUS, GdkModifierType(0) },\n { GDK_0, IDC_ZOOM_NORMAL, GDK_CONTROL_MASK },\n { GDK_minus, IDC_ZOOM_MINUS, GDK_CONTROL_MASK },\n { GDK_underscore, IDC_ZOOM_MINUS,\n GdkModifierType(GDK_CONTROL_MASK | GDK_SHIFT_MASK) },\n { XF86XK_ZoomOut, IDC_ZOOM_MINUS, GdkModifierType(0) },\n\n \/\/ Find in page.\n { GDK_g, IDC_FIND_NEXT, GDK_CONTROL_MASK },\n { GDK_F3, IDC_FIND_NEXT, GdkModifierType(0) },\n { GDK_g, IDC_FIND_PREVIOUS,\n GdkModifierType(GDK_CONTROL_MASK | GDK_SHIFT_MASK) },\n { GDK_F3, IDC_FIND_PREVIOUS, GDK_SHIFT_MASK },\n\n \/\/ Navigation \/ toolbar buttons.\n { GDK_Home, IDC_HOME, GDK_MOD1_MASK },\n { XF86XK_HomePage, IDC_HOME, GdkModifierType(0) },\n { GDK_Escape, IDC_STOP, GdkModifierType(0) },\n { XF86XK_Stop, IDC_STOP, GdkModifierType(0) },\n { GDK_Left, IDC_BACK, GDK_MOD1_MASK },\n { GDK_BackSpace, IDC_BACK, GdkModifierType(0) },\n { XF86XK_Back, IDC_BACK, GdkModifierType(0) },\n { GDK_Right, IDC_FORWARD, GDK_MOD1_MASK },\n { GDK_BackSpace, IDC_FORWARD, GDK_SHIFT_MASK },\n { XF86XK_Forward, IDC_FORWARD, GdkModifierType(0) },\n { GDK_r, IDC_RELOAD, GDK_CONTROL_MASK },\n { GDK_F5, IDC_RELOAD, GdkModifierType(0) },\n { GDK_F5, IDC_RELOAD, GDK_CONTROL_MASK },\n { GDK_F5, IDC_RELOAD, GDK_SHIFT_MASK },\n { XF86XK_Reload, IDC_RELOAD, GdkModifierType(0) },\n { XF86XK_Refresh, IDC_RELOAD, GdkModifierType(0) },\n\n \/\/ Miscellany.\n { GDK_d, IDC_STAR, GDK_CONTROL_MASK },\n { XF86XK_AddFavorite, IDC_STAR, GdkModifierType(0) },\n { XF86XK_Favorites, IDC_SHOW_BOOKMARK_BAR, GdkModifierType(0) },\n { XF86XK_History, IDC_SHOW_HISTORY, GdkModifierType(0) },\n { GDK_o, IDC_OPEN_FILE, GDK_CONTROL_MASK },\n { GDK_F11, IDC_FULLSCREEN, GdkModifierType(0) },\n { GDK_u, IDC_VIEW_SOURCE, GDK_CONTROL_MASK },\n { GDK_p, IDC_PRINT, GDK_CONTROL_MASK },\n { GDK_Escape, IDC_TASK_MANAGER, GDK_SHIFT_MASK },\n\n#if defined(OS_CHROMEOS)\n { GDK_f, IDC_FULLSCREEN,\n GdkModifierType(GDK_CONTROL_MASK | GDK_MOD1_MASK) },\n { GDK_Delete, IDC_TASK_MANAGER,\n GdkModifierType(GDK_CONTROL_MASK | GDK_MOD1_MASK) },\n { GDK_comma, IDC_CONTROL_PANEL, GdkModifierType(GDK_CONTROL_MASK) },\n#endif\n};\n\nconst size_t kAcceleratorMapLength = arraysize(kAcceleratorMap);\n\n} \/\/ namespace browser\n<|endoftext|>"} {"text":"<commit_before>\/\/ Ouzel by Elviss Strazdins\n\n#ifndef OUZEL_AUDIO_MIXER_STREAM_HPP\n#define OUZEL_AUDIO_MIXER_STREAM_HPP\n\n#include \"Object.hpp\"\n#include \"Bus.hpp\"\n#include \"Data.hpp\"\n\nnamespace ouzel::audio::mixer\n{\n class Bus;\n class Data;\n\n class Stream: public Object\n {\n friend Bus;\n public:\n explicit Stream(Data& initData) noexcept:\n data{initData}\n {\n }\n\n ~Stream() override\n {\n if (output) output->removeInput(this);\n }\n\n Stream(const Stream&) = delete;\n Stream& operator=(const Object&) = delete;\n\n Stream(Stream&&) = delete;\n Stream& operator=(Stream&&) = delete;\n\n auto& getData() const noexcept { return data; }\n\n void setOutput(Bus* newOutput)\n {\n if (output) output->removeInput(this);\n output = newOutput;\n if (output) output->addInput(this);\n }\n\n auto isPlaying() const noexcept { return playing; }\n void play() { playing = true; }\n\n void stop(bool shouldReset)\n {\n playing = false;\n if (shouldReset) reset();\n }\n\n virtual void reset() = 0;\n\n virtual void generateSamples(std::uint32_t frames, std::vector<float>& samples) = 0;\n\n protected:\n Data& data;\n Bus* output = nullptr;\n bool playing = false;\n };\n}\n\n#endif \/\/ OUZEL_AUDIO_MIXER_STREAM_HPP\n<commit_msg>Make play noexcept<commit_after>\/\/ Ouzel by Elviss Strazdins\n\n#ifndef OUZEL_AUDIO_MIXER_STREAM_HPP\n#define OUZEL_AUDIO_MIXER_STREAM_HPP\n\n#include \"Object.hpp\"\n#include \"Bus.hpp\"\n#include \"Data.hpp\"\n\nnamespace ouzel::audio::mixer\n{\n class Bus;\n class Data;\n\n class Stream: public Object\n {\n friend Bus;\n public:\n explicit Stream(Data& initData) noexcept:\n data{initData}\n {\n }\n\n ~Stream() override\n {\n if (output) output->removeInput(this);\n }\n\n Stream(const Stream&) = delete;\n Stream& operator=(const Object&) = delete;\n\n Stream(Stream&&) = delete;\n Stream& operator=(Stream&&) = delete;\n\n auto& getData() const noexcept { return data; }\n\n void setOutput(Bus* newOutput)\n {\n if (output) output->removeInput(this);\n output = newOutput;\n if (output) output->addInput(this);\n }\n\n auto isPlaying() const noexcept { return playing; }\n void play() noexcept { playing = true; }\n\n void stop(bool shouldReset)\n {\n playing = false;\n if (shouldReset) reset();\n }\n\n virtual void reset() = 0;\n\n virtual void generateSamples(std::uint32_t frames, std::vector<float>& samples) = 0;\n\n protected:\n Data& data;\n Bus* output = nullptr;\n bool playing = false;\n };\n}\n\n#endif \/\/ OUZEL_AUDIO_MIXER_STREAM_HPP\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/cookie_modal_dialog.h\"\n\n#include \"app\/l10n_util.h\"\n#include \"base\/logging.h\"\n#include \"chrome\/browser\/gtk\/gtk_chrome_link_button.h\"\n#include \"chrome\/browser\/views\/cookie_prompt_view.h\"\n#include \"chrome\/browser\/tab_contents\/tab_contents.h\"\n#include \"chrome\/common\/gtk_util.h\"\n#include \"grit\/generated_resources.h\"\n#include \"grit\/locale_settings.h\"\n\nvoid CookiePromptModalDialog::CreateAndShowDialog() {\n dialog_ = CreateNativeDialog();\n gtk_widget_show_all(GTK_WIDGET(GTK_DIALOG(dialog_)));\n\n \/\/ Suggest a minimum size.\n gint width;\n GtkRequisition req;\n gtk_widget_size_request(dialog_, &req);\n gtk_util::GetWidgetSizeFromResources(dialog_, IDS_ALERT_DIALOG_WIDTH_CHARS, 0,\n &width, NULL);\n if (width > req.width)\n gtk_widget_set_size_request(dialog_, width, -1);\n}\n\nint CookiePromptModalDialog::GetDialogButtons() {\n return 0;\n}\n\nvoid CookiePromptModalDialog::AcceptWindow() {\n HandleDialogResponse(GTK_DIALOG(dialog_), GTK_RESPONSE_ACCEPT);\n}\n\nvoid CookiePromptModalDialog::CancelWindow() {\n HandleDialogResponse(GTK_DIALOG(dialog_), GTK_RESPONSE_REJECT);\n}\n\nNativeDialog CookiePromptModalDialog::CreateNativeDialog() {\n gfx::NativeWindow window = tab_contents_->GetMessageBoxRootWindow();\n CookiePromptModalDialog::DialogType type = dialog_type();\n NativeDialog dialog = gtk_dialog_new_with_buttons(\n l10n_util::GetStringFUTF8(\n type == CookiePromptModalDialog::DIALOG_TYPE_COOKIE ?\n IDS_COOKIE_ALERT_TITLE : IDS_DATA_ALERT_TITLE,\n UTF8ToUTF16(origin().host())).c_str(),\n window,\n GTK_DIALOG_MODAL,\n l10n_util::GetStringUTF8(IDS_COOKIE_ALERT_BLOCK_BUTTON).c_str(),\n GTK_RESPONSE_REJECT,\n l10n_util::GetStringUTF8(IDS_COOKIE_ALERT_ALLOW_BUTTON).c_str(),\n GTK_RESPONSE_ACCEPT,\n NULL);\n\n GtkWidget* content_area = GTK_DIALOG(dialog)->vbox;\n gtk_box_set_spacing(GTK_BOX(content_area), gtk_util::kContentAreaSpacing);\n\n string16 display_host = UTF8ToUTF16(origin().host());\n GtkWidget* label = gtk_label_new(\n l10n_util::GetStringFUTF8(\n type == CookiePromptModalDialog::DIALOG_TYPE_COOKIE ?\n IDS_COOKIE_ALERT_LABEL : IDS_DATA_ALERT_LABEL,\n display_host).c_str());\n\n gtk_box_pack_start(GTK_BOX(content_area), label, FALSE, FALSE, 0);\n\n \/\/ Create a vbox for all the radio buttons so they aren't too far away from\n \/\/ each other.\n GtkWidget* radio_box = gtk_vbox_new(FALSE, gtk_util::kControlSpacing);\n remember_radio_ = gtk_radio_button_new_with_label(NULL,\n l10n_util::GetStringFUTF8(IDS_COOKIE_ALERT_REMEMBER_RADIO,\n display_host).c_str());\n gtk_box_pack_start(GTK_BOX(radio_box), remember_radio_, FALSE, FALSE, 0);\n\n GtkWidget* ask_radio = gtk_radio_button_new_with_label_from_widget(\n GTK_RADIO_BUTTON(remember_radio_),\n l10n_util::GetStringUTF8(IDS_COOKIE_ALERT_ASK_RADIO).c_str());\n gtk_box_pack_start(GTK_BOX(radio_box), ask_radio, FALSE, FALSE, 0);\n\n gtk_box_pack_start(GTK_BOX(content_area), radio_box, FALSE, FALSE, 0);\n\n \/\/ Now we create the details link and align it left in the button box.\n GtkWidget* details_button = gtk_chrome_link_button_new(\n l10n_util::GetStringUTF8(IDS_COOKIE_SHOW_DETAILS_LABEL).c_str());\n gtk_box_pack_start(GTK_BOX(GTK_DIALOG(dialog)->action_area),\n details_button, FALSE, FALSE, 0);\n gtk_widget_set_sensitive(details_button, FALSE);\n gtk_button_box_set_child_secondary(\n GTK_BUTTON_BOX(GTK_DIALOG(dialog)->action_area),\n details_button,\n TRUE);\n\n \/\/ TODO(erg): http:\/\/crbug.com\/35178 : Needs to implement the cookie details\n \/\/ box here.\n\n gtk_dialog_set_default_response(GTK_DIALOG(dialog), GTK_RESPONSE_ACCEPT);\n g_signal_connect(dialog, \"response\",\n G_CALLBACK(AppModalDialog::OnDialogResponse),\n reinterpret_cast<AppModalDialog*>(this));\n\n gtk_util::MakeAppModalWindowGroup();\n\n return dialog;\n}\n\nvoid CookiePromptModalDialog::HandleDialogResponse(GtkDialog* dialog,\n gint response_id) {\n bool remember_radio = gtk_toggle_button_get_active(\n GTK_TOGGLE_BUTTON(remember_radio_));\n if (response_id == GTK_RESPONSE_REJECT) {\n BlockSiteData(remember_radio);\n } else if (response_id == GTK_RESPONSE_ACCEPT) {\n \/\/ TODO(erg): Needs to use |session_expire_| instead of true.\n AllowSiteData(remember_radio, true);\n } else {\n BlockSiteData(false);\n }\n gtk_widget_destroy(GTK_WIDGET(dialog));\n\n CompleteDialog();\n\n gtk_util::AppModalDismissedUngroupWindows();\n delete this;\n}\n<commit_msg>linux: touchups on the cookie prompt dialog<commit_after>\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/cookie_modal_dialog.h\"\n\n#include \"app\/l10n_util.h\"\n#include \"base\/logging.h\"\n#include \"chrome\/browser\/gtk\/gtk_chrome_link_button.h\"\n#include \"chrome\/browser\/views\/cookie_prompt_view.h\"\n#include \"chrome\/browser\/tab_contents\/tab_contents.h\"\n#include \"chrome\/common\/gtk_util.h\"\n#include \"grit\/generated_resources.h\"\n#include \"grit\/locale_settings.h\"\n\nvoid CookiePromptModalDialog::CreateAndShowDialog() {\n dialog_ = CreateNativeDialog();\n gtk_widget_show_all(GTK_WIDGET(GTK_DIALOG(dialog_)));\n\n \/\/ Suggest a minimum size.\n gint width;\n GtkRequisition req;\n gtk_widget_size_request(dialog_, &req);\n gtk_util::GetWidgetSizeFromResources(dialog_, IDS_ALERT_DIALOG_WIDTH_CHARS, 0,\n &width, NULL);\n if (width > req.width)\n gtk_widget_set_size_request(dialog_, width, -1);\n}\n\nint CookiePromptModalDialog::GetDialogButtons() {\n return 0;\n}\n\nvoid CookiePromptModalDialog::AcceptWindow() {\n HandleDialogResponse(GTK_DIALOG(dialog_), GTK_RESPONSE_ACCEPT);\n}\n\nvoid CookiePromptModalDialog::CancelWindow() {\n HandleDialogResponse(GTK_DIALOG(dialog_), GTK_RESPONSE_REJECT);\n}\n\nNativeDialog CookiePromptModalDialog::CreateNativeDialog() {\n gfx::NativeWindow window = tab_contents_->GetMessageBoxRootWindow();\n CookiePromptModalDialog::DialogType type = dialog_type();\n NativeDialog dialog = gtk_dialog_new_with_buttons(\n l10n_util::GetStringFUTF8(\n type == CookiePromptModalDialog::DIALOG_TYPE_COOKIE ?\n IDS_COOKIE_ALERT_TITLE : IDS_DATA_ALERT_TITLE,\n UTF8ToUTF16(origin().host())).c_str(),\n window,\n static_cast<GtkDialogFlags>(GTK_DIALOG_MODAL | GTK_DIALOG_NO_SEPARATOR),\n l10n_util::GetStringUTF8(IDS_COOKIE_ALERT_BLOCK_BUTTON).c_str(),\n GTK_RESPONSE_REJECT,\n l10n_util::GetStringUTF8(IDS_COOKIE_ALERT_ALLOW_BUTTON).c_str(),\n GTK_RESPONSE_ACCEPT,\n NULL);\n gtk_window_set_resizable(GTK_WINDOW(dialog), FALSE);\n\n GtkWidget* content_area = GTK_DIALOG(dialog)->vbox;\n gtk_box_set_spacing(GTK_BOX(content_area), gtk_util::kContentAreaSpacing);\n\n string16 display_host = UTF8ToUTF16(origin().host());\n GtkWidget* label = gtk_util::LeftAlignMisc(gtk_label_new(\n l10n_util::GetStringFUTF8(\n type == CookiePromptModalDialog::DIALOG_TYPE_COOKIE ?\n IDS_COOKIE_ALERT_LABEL : IDS_DATA_ALERT_LABEL,\n display_host).c_str()));\n gtk_box_pack_start(GTK_BOX(content_area), label, FALSE, FALSE, 0);\n\n \/\/ Create a vbox for all the radio buttons so they aren't too far away from\n \/\/ each other.\n GtkWidget* radio_box = gtk_vbox_new(FALSE, gtk_util::kControlSpacing);\n remember_radio_ = gtk_radio_button_new_with_label(NULL,\n l10n_util::GetStringFUTF8(IDS_COOKIE_ALERT_REMEMBER_RADIO,\n display_host).c_str());\n gtk_box_pack_start(GTK_BOX(radio_box), remember_radio_, FALSE, FALSE, 0);\n\n GtkWidget* ask_radio = gtk_radio_button_new_with_label_from_widget(\n GTK_RADIO_BUTTON(remember_radio_),\n l10n_util::GetStringUTF8(IDS_COOKIE_ALERT_ASK_RADIO).c_str());\n gtk_box_pack_start(GTK_BOX(radio_box), ask_radio, FALSE, FALSE, 0);\n\n gtk_box_pack_start(GTK_BOX(content_area), radio_box, FALSE, FALSE, 0);\n\n \/\/ Now we create the details link and align it left in the button box.\n GtkWidget* details_button = gtk_chrome_link_button_new(\n l10n_util::GetStringUTF8(IDS_COOKIE_SHOW_DETAILS_LABEL).c_str());\n gtk_box_pack_start(GTK_BOX(GTK_DIALOG(dialog)->action_area),\n details_button, FALSE, FALSE, 0);\n gtk_widget_set_sensitive(details_button, FALSE);\n gtk_button_box_set_child_secondary(\n GTK_BUTTON_BOX(GTK_DIALOG(dialog)->action_area),\n details_button,\n TRUE);\n\n \/\/ TODO(erg): http:\/\/crbug.com\/35178 : Needs to implement the cookie details\n \/\/ box here.\n\n gtk_dialog_set_default_response(GTK_DIALOG(dialog), GTK_RESPONSE_ACCEPT);\n g_signal_connect(dialog, \"response\",\n G_CALLBACK(AppModalDialog::OnDialogResponse),\n reinterpret_cast<AppModalDialog*>(this));\n\n gtk_util::MakeAppModalWindowGroup();\n\n return dialog;\n}\n\nvoid CookiePromptModalDialog::HandleDialogResponse(GtkDialog* dialog,\n gint response_id) {\n bool remember_radio = gtk_toggle_button_get_active(\n GTK_TOGGLE_BUTTON(remember_radio_));\n if (response_id == GTK_RESPONSE_REJECT) {\n BlockSiteData(remember_radio);\n } else if (response_id == GTK_RESPONSE_ACCEPT) {\n \/\/ TODO(erg): Needs to use |session_expire_| instead of true.\n AllowSiteData(remember_radio, true);\n } else {\n BlockSiteData(false);\n }\n gtk_widget_destroy(GTK_WIDGET(dialog));\n\n CompleteDialog();\n\n gtk_util::AppModalDismissedUngroupWindows();\n delete this;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n\/\/ Navigates the browser to server and client redirect pages and makes sure\n\/\/ that the correct redirects are reflected in the history database. Errors\n\/\/ here might indicate that WebKit changed the calls our glue layer gets in\n\/\/ the case of redirects. It may also mean problems with the history system.\n\n#include \"base\/file_util.h\"\n#include \"base\/platform_thread.h\"\n#include \"base\/scoped_ptr.h\"\n#include \"base\/string_util.h\"\n#include \"base\/string16.h\"\n#include \"base\/utf_string_conversions.h\"\n#include \"chrome\/browser\/view_ids.h\"\n#include \"chrome\/test\/automation\/browser_proxy.h\"\n#include \"chrome\/test\/automation\/tab_proxy.h\"\n#include \"chrome\/test\/automation\/window_proxy.h\"\n#include \"chrome\/test\/ui\/ui_test.h\"\n#include \"net\/base\/net_util.h\"\n#include \"net\/test\/test_server.h\"\n#include \"views\/event.h\"\n\nnamespace {\n\nclass RedirectTest : public UITest {\n public:\n RedirectTest()\n : test_server_(net::TestServer::TYPE_HTTP,\n FilePath(FILE_PATH_LITERAL(\"chrome\/test\/data\"))) {\n }\n\n protected:\n net::TestServer test_server_;\n};\n\n\/\/ Tests a single server redirect\nTEST_F(RedirectTest, Server) {\n ASSERT_TRUE(test_server_.Start());\n\n GURL final_url = test_server_.GetURL(std::string());\n GURL first_url = test_server_.GetURL(\n \"server-redirect?\" + final_url.spec());\n\n NavigateToURL(first_url);\n\n scoped_refptr<TabProxy> tab_proxy(GetActiveTab());\n ASSERT_TRUE(tab_proxy.get());\n\n std::vector<GURL> redirects;\n ASSERT_TRUE(tab_proxy->GetRedirectsFrom(first_url, &redirects));\n\n ASSERT_EQ(1U, redirects.size());\n EXPECT_EQ(final_url.spec(), redirects[0].spec());\n}\n\n\/\/ Tests a single client redirect.\nTEST_F(RedirectTest, Client) {\n ASSERT_TRUE(test_server_.Start());\n\n GURL final_url = test_server_.GetURL(std::string());\n GURL first_url = test_server_.GetURL(\n \"client-redirect?\" + final_url.spec());\n\n \/\/ The client redirect appears as two page visits in the browser.\n NavigateToURLBlockUntilNavigationsComplete(first_url, 2);\n\n scoped_refptr<TabProxy> tab_proxy(GetActiveTab());\n ASSERT_TRUE(tab_proxy.get());\n\n std::vector<GURL> redirects;\n ASSERT_TRUE(tab_proxy->GetRedirectsFrom(first_url, &redirects));\n\n ASSERT_EQ(1U, redirects.size());\n EXPECT_EQ(final_url.spec(), redirects[0].spec());\n\n \/\/ The address bar should display the final URL.\n GURL tab_url;\n EXPECT_TRUE(tab_proxy->GetCurrentURL(&tab_url));\n EXPECT_TRUE(final_url == tab_url);\n\n \/\/ Navigate one more time.\n NavigateToURLBlockUntilNavigationsComplete(first_url, 2);\n\n \/\/ The address bar should still display the final URL.\n EXPECT_TRUE(tab_proxy->GetCurrentURL(&tab_url));\n EXPECT_TRUE(final_url == tab_url);\n}\n\nTEST_F(RedirectTest, ClientEmptyReferer) {\n ASSERT_TRUE(test_server_.Start());\n\n GURL final_url = test_server_.GetURL(std::string());\n FilePath test_file(test_data_directory_);\n test_file = test_file.AppendASCII(\"file_client_redirect.html\");\n GURL first_url = net::FilePathToFileURL(test_file);\n\n \/\/ The client redirect appears as two page visits in the browser.\n NavigateToURLBlockUntilNavigationsComplete(first_url, 2);\n\n std::vector<GURL> redirects;\n scoped_refptr<TabProxy> tab_proxy(GetActiveTab());\n ASSERT_TRUE(tab_proxy.get());\n ASSERT_TRUE(tab_proxy->GetRedirectsFrom(first_url, &redirects));\n ASSERT_EQ(1U, redirects.size());\n EXPECT_EQ(final_url.spec(), redirects[0].spec());\n}\n\n\/\/ Tests to make sure a location change when a pending redirect exists isn't\n\/\/ flagged as a redirect.\n#if defined(OS_MACOSX)\n\/\/ SimulateOSClick is broken on the Mac: http:\/\/crbug.com\/45162\n#define MAYBE_ClientCancelled DISABLED_ClientCancelled\n#elif defined(OS_WIN)\n\/\/ http:\/\/crbug.com\/53091\n#define MAYBE_ClientCancelled FAILS_ClientCancelled\n#else\n#define MAYBE_ClientCancelled ClientCancelled\n#endif\n\nTEST_F(RedirectTest, MAYBE_ClientCancelled) {\n FilePath first_path(test_data_directory_);\n first_path = first_path.AppendASCII(\"cancelled_redirect_test.html\");\n ASSERT_TRUE(file_util::AbsolutePath(&first_path));\n GURL first_url = net::FilePathToFileURL(first_path);\n\n NavigateToURLBlockUntilNavigationsComplete(first_url, 1);\n\n scoped_refptr<BrowserProxy> browser = automation()->GetBrowserWindow(0);\n ASSERT_TRUE(browser.get());\n scoped_refptr<WindowProxy> window = browser->GetWindow();\n ASSERT_TRUE(window.get());\n scoped_refptr<TabProxy> tab_proxy(GetActiveTab());\n ASSERT_TRUE(tab_proxy.get());\n int64 last_nav_time = 0;\n EXPECT_TRUE(tab_proxy->GetLastNavigationTime(&last_nav_time));\n \/\/ Simulate a click to force to make a user-initiated location change;\n \/\/ otherwise, a non user-initiated in-page location change will be treated\n \/\/ as client redirect and the redirect will be recoreded, which can cause\n \/\/ this test failed.\n gfx::Rect tab_view_bounds;\n ASSERT_TRUE(browser->BringToFront());\n ASSERT_TRUE(window->GetViewBounds(VIEW_ID_TAB_CONTAINER, &tab_view_bounds,\n true));\n ASSERT_TRUE(\n window->SimulateOSClick(tab_view_bounds.CenterPoint(),\n views::Event::EF_LEFT_BUTTON_DOWN));\n EXPECT_TRUE(tab_proxy->WaitForNavigation(last_nav_time));\n\n std::vector<GURL> redirects;\n ASSERT_TRUE(tab_proxy->GetRedirectsFrom(first_url, &redirects));\n\n \/\/ There should be no redirects from first_url, because the anchor location\n \/\/ change that occurs should not be flagged as a redirect and the meta-refresh\n \/\/ won't have fired yet.\n ASSERT_EQ(0U, redirects.size());\n GURL current_url;\n ASSERT_TRUE(tab_proxy->GetCurrentURL(¤t_url));\n\n \/\/ Need to test final path and ref separately since constructing a file url\n \/\/ containing an anchor using FilePathToFileURL will escape the anchor as\n \/\/ %23, but in current_url the anchor will be '#'.\n std::string final_ref = \"myanchor\";\n FilePath current_path;\n ASSERT_TRUE(net::FileURLToFilePath(current_url, ¤t_path));\n ASSERT_TRUE(file_util::AbsolutePath(¤t_path));\n \/\/ Path should remain unchanged.\n EXPECT_EQ(StringToLowerASCII(first_path.value()),\n StringToLowerASCII(current_path.value()));\n EXPECT_EQ(final_ref, current_url.ref());\n}\n\n\/\/ Tests a client->server->server redirect\nTEST_F(RedirectTest, ClientServerServer) {\n ASSERT_TRUE(test_server_.Start());\n\n GURL final_url = test_server_.GetURL(std::string());\n GURL next_to_last = test_server_.GetURL(\n \"server-redirect?\" + final_url.spec());\n GURL second_url = test_server_.GetURL(\n \"server-redirect?\" + next_to_last.spec());\n GURL first_url = test_server_.GetURL(\n \"client-redirect?\" + second_url.spec());\n std::vector<GURL> redirects;\n\n \/\/ We need the sleep for the client redirects, because it appears as two\n \/\/ page visits in the browser.\n NavigateToURL(first_url);\n\n for (int i = 0; i < 10; ++i) {\n PlatformThread::Sleep(sleep_timeout_ms());\n scoped_refptr<TabProxy> tab_proxy(GetActiveTab());\n ASSERT_TRUE(tab_proxy.get());\n ASSERT_TRUE(tab_proxy->GetRedirectsFrom(first_url, &redirects));\n if (!redirects.empty())\n break;\n }\n\n ASSERT_EQ(3U, redirects.size());\n EXPECT_EQ(second_url.spec(), redirects[0].spec());\n EXPECT_EQ(next_to_last.spec(), redirects[1].spec());\n EXPECT_EQ(final_url.spec(), redirects[2].spec());\n}\n\n\/\/ Tests that the \"#reference\" gets preserved across server redirects.\nTEST_F(RedirectTest, ServerReference) {\n ASSERT_TRUE(test_server_.Start());\n\n const std::string ref(\"reference\");\n\n GURL final_url = test_server_.GetURL(std::string());\n GURL initial_url = test_server_.GetURL(\n \"server-redirect?\" + final_url.spec() + \"#\" + ref);\n\n NavigateToURL(initial_url);\n\n GURL url = GetActiveTabURL();\n EXPECT_EQ(ref, url.ref());\n}\n\n\/\/ Test that redirect from http:\/\/ to file:\/\/ :\n\/\/ A) does not crash the browser or confuse the redirect chain, see bug 1080873\n\/\/ B) does not take place.\nTEST_F(RedirectTest, NoHttpToFile) {\n ASSERT_TRUE(test_server_.Start());\n FilePath test_file(test_data_directory_);\n test_file = test_file.AppendASCII(\"http_to_file.html\");\n GURL file_url = net::FilePathToFileURL(test_file);\n\n GURL initial_url = test_server_.GetURL(\n \"client-redirect?\" + file_url.spec());\n\n NavigateToURL(initial_url);\n \/\/ UITest will check for crashes. We make sure the title doesn't match the\n \/\/ title from the file, because the nav should not have taken place.\n scoped_refptr<TabProxy> tab_proxy(GetActiveTab());\n ASSERT_TRUE(tab_proxy.get());\n std::wstring actual_title;\n ASSERT_TRUE(tab_proxy->GetTabTitle(&actual_title));\n EXPECT_NE(\"File!\", WideToUTF8(actual_title));\n}\n\n\/\/ Ensures that non-user initiated location changes (within page) are\n\/\/ flagged as client redirects. See bug 1139823.\nTEST_F(RedirectTest, ClientFragments) {\n ASSERT_TRUE(test_server_.Start());\n\n FilePath test_file(test_data_directory_);\n test_file = test_file.AppendASCII(\"ref_redirect.html\");\n GURL first_url = net::FilePathToFileURL(test_file);\n std::vector<GURL> redirects;\n\n NavigateToURL(first_url);\n\n scoped_refptr<TabProxy> tab_proxy(GetActiveTab());\n ASSERT_TRUE(tab_proxy.get());\n ASSERT_TRUE(tab_proxy->GetRedirectsFrom(first_url, &redirects));\n EXPECT_EQ(1U, redirects.size());\n EXPECT_EQ(first_url.spec() + \"#myanchor\", redirects[0].spec());\n}\n\n\/\/ TODO(timsteele): This is disabled because our current testserver can't\n\/\/ handle multiple requests in parallel, making it hang on the first request\n\/\/ to \/slow?60. It's unable to serve our second request for files\/title2.html\n\/\/ until \/slow? completes, which doesn't give the desired behavior. We could\n\/\/ alternatively load the second page from disk, but we would need to start\n\/\/ the browser for this testcase with --process-per-tab, and I don't think\n\/\/ we can do this at test-case-level granularity at the moment.\n\/\/ http:\/\/crbug.com\/45056\nTEST_F(RedirectTest,\n DISABLED_ClientCancelledByNewNavigationAfterProvisionalLoad) {\n \/\/ We want to initiate a second navigation after the provisional load for\n \/\/ the client redirect destination has started, but before this load is\n \/\/ committed. To achieve this, we tell the browser to load a slow page,\n \/\/ which causes it to start a provisional load, and while it is waiting\n \/\/ for the response (which means it hasn't committed the load for the client\n \/\/ redirect destination page yet), we issue a new navigation request.\n ASSERT_TRUE(test_server_.Start());\n\n GURL final_url = test_server_.GetURL(\"files\/title2.html\");\n GURL slow = test_server_.GetURL(\"slow?60\");\n GURL first_url = test_server_.GetURL(\n \"client-redirect?\" + slow.spec());\n std::vector<GURL> redirects;\n\n NavigateToURL(first_url);\n \/\/ We don't sleep here - the first navigation won't have been committed yet\n \/\/ because we told the server to wait a minute. This means the browser has\n \/\/ started it's provisional load for the client redirect destination page but\n \/\/ hasn't completed. Our time is now!\n NavigateToURL(final_url);\n\n std::wstring tab_title;\n std::wstring final_url_title = UTF8ToWide(\"Title Of Awesomeness\");\n \/\/ Wait till the final page has been loaded.\n for (int i = 0; i < 10; ++i) {\n PlatformThread::Sleep(sleep_timeout_ms());\n scoped_refptr<TabProxy> tab_proxy(GetActiveTab());\n ASSERT_TRUE(tab_proxy.get());\n ASSERT_TRUE(tab_proxy->GetTabTitle(&tab_title));\n if (tab_title == final_url_title) {\n ASSERT_TRUE(tab_proxy->GetRedirectsFrom(first_url, &redirects));\n break;\n }\n }\n\n \/\/ Check to make sure the navigation did in fact take place and we are\n \/\/ at the expected page.\n EXPECT_EQ(final_url_title, tab_title);\n\n bool final_navigation_not_redirect = true;\n \/\/ Check to make sure our request for files\/title2.html doesn't get flagged\n \/\/ as a client redirect from the first (\/client-redirect?) page.\n for (std::vector<GURL>::iterator it = redirects.begin();\n it != redirects.end(); ++it) {\n if (final_url.spec() == it->spec()) {\n final_navigation_not_redirect = false;\n break;\n }\n }\n EXPECT_TRUE(final_navigation_not_redirect);\n}\n\n} \/\/ namespace\n<commit_msg>Marking RedirectTest.Client as FLAKY<commit_after>\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n\/\/ Navigates the browser to server and client redirect pages and makes sure\n\/\/ that the correct redirects are reflected in the history database. Errors\n\/\/ here might indicate that WebKit changed the calls our glue layer gets in\n\/\/ the case of redirects. It may also mean problems with the history system.\n\n#include \"base\/file_util.h\"\n#include \"base\/platform_thread.h\"\n#include \"base\/scoped_ptr.h\"\n#include \"base\/string_util.h\"\n#include \"base\/string16.h\"\n#include \"base\/utf_string_conversions.h\"\n#include \"chrome\/browser\/view_ids.h\"\n#include \"chrome\/test\/automation\/browser_proxy.h\"\n#include \"chrome\/test\/automation\/tab_proxy.h\"\n#include \"chrome\/test\/automation\/window_proxy.h\"\n#include \"chrome\/test\/ui\/ui_test.h\"\n#include \"net\/base\/net_util.h\"\n#include \"net\/test\/test_server.h\"\n#include \"views\/event.h\"\n\nnamespace {\n\nclass RedirectTest : public UITest {\n public:\n RedirectTest()\n : test_server_(net::TestServer::TYPE_HTTP,\n FilePath(FILE_PATH_LITERAL(\"chrome\/test\/data\"))) {\n }\n\n protected:\n net::TestServer test_server_;\n};\n\n\/\/ Tests a single server redirect\nTEST_F(RedirectTest, Server) {\n ASSERT_TRUE(test_server_.Start());\n\n GURL final_url = test_server_.GetURL(std::string());\n GURL first_url = test_server_.GetURL(\n \"server-redirect?\" + final_url.spec());\n\n NavigateToURL(first_url);\n\n scoped_refptr<TabProxy> tab_proxy(GetActiveTab());\n ASSERT_TRUE(tab_proxy.get());\n\n std::vector<GURL> redirects;\n ASSERT_TRUE(tab_proxy->GetRedirectsFrom(first_url, &redirects));\n\n ASSERT_EQ(1U, redirects.size());\n EXPECT_EQ(final_url.spec(), redirects[0].spec());\n}\n\n\/\/ Tests a single client redirect.\n\/\/ Flaky: see crbug.com\/55380\nTEST_F(RedirectTest, FLAKY_Client) {\n ASSERT_TRUE(test_server_.Start());\n\n GURL final_url = test_server_.GetURL(std::string());\n GURL first_url = test_server_.GetURL(\n \"client-redirect?\" + final_url.spec());\n\n \/\/ The client redirect appears as two page visits in the browser.\n NavigateToURLBlockUntilNavigationsComplete(first_url, 2);\n\n scoped_refptr<TabProxy> tab_proxy(GetActiveTab());\n ASSERT_TRUE(tab_proxy.get());\n\n std::vector<GURL> redirects;\n ASSERT_TRUE(tab_proxy->GetRedirectsFrom(first_url, &redirects));\n\n ASSERT_EQ(1U, redirects.size());\n EXPECT_EQ(final_url.spec(), redirects[0].spec());\n\n \/\/ The address bar should display the final URL.\n GURL tab_url;\n EXPECT_TRUE(tab_proxy->GetCurrentURL(&tab_url));\n EXPECT_TRUE(final_url == tab_url);\n\n \/\/ Navigate one more time.\n NavigateToURLBlockUntilNavigationsComplete(first_url, 2);\n\n \/\/ The address bar should still display the final URL.\n EXPECT_TRUE(tab_proxy->GetCurrentURL(&tab_url));\n EXPECT_TRUE(final_url == tab_url);\n}\n\nTEST_F(RedirectTest, ClientEmptyReferer) {\n ASSERT_TRUE(test_server_.Start());\n\n GURL final_url = test_server_.GetURL(std::string());\n FilePath test_file(test_data_directory_);\n test_file = test_file.AppendASCII(\"file_client_redirect.html\");\n GURL first_url = net::FilePathToFileURL(test_file);\n\n \/\/ The client redirect appears as two page visits in the browser.\n NavigateToURLBlockUntilNavigationsComplete(first_url, 2);\n\n std::vector<GURL> redirects;\n scoped_refptr<TabProxy> tab_proxy(GetActiveTab());\n ASSERT_TRUE(tab_proxy.get());\n ASSERT_TRUE(tab_proxy->GetRedirectsFrom(first_url, &redirects));\n ASSERT_EQ(1U, redirects.size());\n EXPECT_EQ(final_url.spec(), redirects[0].spec());\n}\n\n\/\/ Tests to make sure a location change when a pending redirect exists isn't\n\/\/ flagged as a redirect.\n#if defined(OS_MACOSX)\n\/\/ SimulateOSClick is broken on the Mac: http:\/\/crbug.com\/45162\n#define MAYBE_ClientCancelled DISABLED_ClientCancelled\n#elif defined(OS_WIN)\n\/\/ http:\/\/crbug.com\/53091\n#define MAYBE_ClientCancelled FAILS_ClientCancelled\n#else\n#define MAYBE_ClientCancelled ClientCancelled\n#endif\n\nTEST_F(RedirectTest, MAYBE_ClientCancelled) {\n FilePath first_path(test_data_directory_);\n first_path = first_path.AppendASCII(\"cancelled_redirect_test.html\");\n ASSERT_TRUE(file_util::AbsolutePath(&first_path));\n GURL first_url = net::FilePathToFileURL(first_path);\n\n NavigateToURLBlockUntilNavigationsComplete(first_url, 1);\n\n scoped_refptr<BrowserProxy> browser = automation()->GetBrowserWindow(0);\n ASSERT_TRUE(browser.get());\n scoped_refptr<WindowProxy> window = browser->GetWindow();\n ASSERT_TRUE(window.get());\n scoped_refptr<TabProxy> tab_proxy(GetActiveTab());\n ASSERT_TRUE(tab_proxy.get());\n int64 last_nav_time = 0;\n EXPECT_TRUE(tab_proxy->GetLastNavigationTime(&last_nav_time));\n \/\/ Simulate a click to force to make a user-initiated location change;\n \/\/ otherwise, a non user-initiated in-page location change will be treated\n \/\/ as client redirect and the redirect will be recoreded, which can cause\n \/\/ this test failed.\n gfx::Rect tab_view_bounds;\n ASSERT_TRUE(browser->BringToFront());\n ASSERT_TRUE(window->GetViewBounds(VIEW_ID_TAB_CONTAINER, &tab_view_bounds,\n true));\n ASSERT_TRUE(\n window->SimulateOSClick(tab_view_bounds.CenterPoint(),\n views::Event::EF_LEFT_BUTTON_DOWN));\n EXPECT_TRUE(tab_proxy->WaitForNavigation(last_nav_time));\n\n std::vector<GURL> redirects;\n ASSERT_TRUE(tab_proxy->GetRedirectsFrom(first_url, &redirects));\n\n \/\/ There should be no redirects from first_url, because the anchor location\n \/\/ change that occurs should not be flagged as a redirect and the meta-refresh\n \/\/ won't have fired yet.\n ASSERT_EQ(0U, redirects.size());\n GURL current_url;\n ASSERT_TRUE(tab_proxy->GetCurrentURL(¤t_url));\n\n \/\/ Need to test final path and ref separately since constructing a file url\n \/\/ containing an anchor using FilePathToFileURL will escape the anchor as\n \/\/ %23, but in current_url the anchor will be '#'.\n std::string final_ref = \"myanchor\";\n FilePath current_path;\n ASSERT_TRUE(net::FileURLToFilePath(current_url, ¤t_path));\n ASSERT_TRUE(file_util::AbsolutePath(¤t_path));\n \/\/ Path should remain unchanged.\n EXPECT_EQ(StringToLowerASCII(first_path.value()),\n StringToLowerASCII(current_path.value()));\n EXPECT_EQ(final_ref, current_url.ref());\n}\n\n\/\/ Tests a client->server->server redirect\nTEST_F(RedirectTest, ClientServerServer) {\n ASSERT_TRUE(test_server_.Start());\n\n GURL final_url = test_server_.GetURL(std::string());\n GURL next_to_last = test_server_.GetURL(\n \"server-redirect?\" + final_url.spec());\n GURL second_url = test_server_.GetURL(\n \"server-redirect?\" + next_to_last.spec());\n GURL first_url = test_server_.GetURL(\n \"client-redirect?\" + second_url.spec());\n std::vector<GURL> redirects;\n\n \/\/ We need the sleep for the client redirects, because it appears as two\n \/\/ page visits in the browser.\n NavigateToURL(first_url);\n\n for (int i = 0; i < 10; ++i) {\n PlatformThread::Sleep(sleep_timeout_ms());\n scoped_refptr<TabProxy> tab_proxy(GetActiveTab());\n ASSERT_TRUE(tab_proxy.get());\n ASSERT_TRUE(tab_proxy->GetRedirectsFrom(first_url, &redirects));\n if (!redirects.empty())\n break;\n }\n\n ASSERT_EQ(3U, redirects.size());\n EXPECT_EQ(second_url.spec(), redirects[0].spec());\n EXPECT_EQ(next_to_last.spec(), redirects[1].spec());\n EXPECT_EQ(final_url.spec(), redirects[2].spec());\n}\n\n\/\/ Tests that the \"#reference\" gets preserved across server redirects.\nTEST_F(RedirectTest, ServerReference) {\n ASSERT_TRUE(test_server_.Start());\n\n const std::string ref(\"reference\");\n\n GURL final_url = test_server_.GetURL(std::string());\n GURL initial_url = test_server_.GetURL(\n \"server-redirect?\" + final_url.spec() + \"#\" + ref);\n\n NavigateToURL(initial_url);\n\n GURL url = GetActiveTabURL();\n EXPECT_EQ(ref, url.ref());\n}\n\n\/\/ Test that redirect from http:\/\/ to file:\/\/ :\n\/\/ A) does not crash the browser or confuse the redirect chain, see bug 1080873\n\/\/ B) does not take place.\nTEST_F(RedirectTest, NoHttpToFile) {\n ASSERT_TRUE(test_server_.Start());\n FilePath test_file(test_data_directory_);\n test_file = test_file.AppendASCII(\"http_to_file.html\");\n GURL file_url = net::FilePathToFileURL(test_file);\n\n GURL initial_url = test_server_.GetURL(\n \"client-redirect?\" + file_url.spec());\n\n NavigateToURL(initial_url);\n \/\/ UITest will check for crashes. We make sure the title doesn't match the\n \/\/ title from the file, because the nav should not have taken place.\n scoped_refptr<TabProxy> tab_proxy(GetActiveTab());\n ASSERT_TRUE(tab_proxy.get());\n std::wstring actual_title;\n ASSERT_TRUE(tab_proxy->GetTabTitle(&actual_title));\n EXPECT_NE(\"File!\", WideToUTF8(actual_title));\n}\n\n\/\/ Ensures that non-user initiated location changes (within page) are\n\/\/ flagged as client redirects. See bug 1139823.\nTEST_F(RedirectTest, ClientFragments) {\n ASSERT_TRUE(test_server_.Start());\n\n FilePath test_file(test_data_directory_);\n test_file = test_file.AppendASCII(\"ref_redirect.html\");\n GURL first_url = net::FilePathToFileURL(test_file);\n std::vector<GURL> redirects;\n\n NavigateToURL(first_url);\n\n scoped_refptr<TabProxy> tab_proxy(GetActiveTab());\n ASSERT_TRUE(tab_proxy.get());\n ASSERT_TRUE(tab_proxy->GetRedirectsFrom(first_url, &redirects));\n EXPECT_EQ(1U, redirects.size());\n EXPECT_EQ(first_url.spec() + \"#myanchor\", redirects[0].spec());\n}\n\n\/\/ TODO(timsteele): This is disabled because our current testserver can't\n\/\/ handle multiple requests in parallel, making it hang on the first request\n\/\/ to \/slow?60. It's unable to serve our second request for files\/title2.html\n\/\/ until \/slow? completes, which doesn't give the desired behavior. We could\n\/\/ alternatively load the second page from disk, but we would need to start\n\/\/ the browser for this testcase with --process-per-tab, and I don't think\n\/\/ we can do this at test-case-level granularity at the moment.\n\/\/ http:\/\/crbug.com\/45056\nTEST_F(RedirectTest,\n DISABLED_ClientCancelledByNewNavigationAfterProvisionalLoad) {\n \/\/ We want to initiate a second navigation after the provisional load for\n \/\/ the client redirect destination has started, but before this load is\n \/\/ committed. To achieve this, we tell the browser to load a slow page,\n \/\/ which causes it to start a provisional load, and while it is waiting\n \/\/ for the response (which means it hasn't committed the load for the client\n \/\/ redirect destination page yet), we issue a new navigation request.\n ASSERT_TRUE(test_server_.Start());\n\n GURL final_url = test_server_.GetURL(\"files\/title2.html\");\n GURL slow = test_server_.GetURL(\"slow?60\");\n GURL first_url = test_server_.GetURL(\n \"client-redirect?\" + slow.spec());\n std::vector<GURL> redirects;\n\n NavigateToURL(first_url);\n \/\/ We don't sleep here - the first navigation won't have been committed yet\n \/\/ because we told the server to wait a minute. This means the browser has\n \/\/ started it's provisional load for the client redirect destination page but\n \/\/ hasn't completed. Our time is now!\n NavigateToURL(final_url);\n\n std::wstring tab_title;\n std::wstring final_url_title = UTF8ToWide(\"Title Of Awesomeness\");\n \/\/ Wait till the final page has been loaded.\n for (int i = 0; i < 10; ++i) {\n PlatformThread::Sleep(sleep_timeout_ms());\n scoped_refptr<TabProxy> tab_proxy(GetActiveTab());\n ASSERT_TRUE(tab_proxy.get());\n ASSERT_TRUE(tab_proxy->GetTabTitle(&tab_title));\n if (tab_title == final_url_title) {\n ASSERT_TRUE(tab_proxy->GetRedirectsFrom(first_url, &redirects));\n break;\n }\n }\n\n \/\/ Check to make sure the navigation did in fact take place and we are\n \/\/ at the expected page.\n EXPECT_EQ(final_url_title, tab_title);\n\n bool final_navigation_not_redirect = true;\n \/\/ Check to make sure our request for files\/title2.html doesn't get flagged\n \/\/ as a client redirect from the first (\/client-redirect?) page.\n for (std::vector<GURL>::iterator it = redirects.begin();\n it != redirects.end(); ++it) {\n if (final_url.spec() == it->spec()) {\n final_navigation_not_redirect = false;\n break;\n }\n }\n EXPECT_TRUE(final_navigation_not_redirect);\n}\n\n} \/\/ namespace\n<|endoftext|>"} {"text":"<commit_before>\/* IBM_PROLOG_BEGIN_TAG *\/\n\/* This is an automatically generated prolog. *\/\n\/* *\/\n\/* $Source: src\/import\/chips\/p9\/procedures\/hwp\/sbe\/p9_sbe_ext_defs.H $ *\/\n\/* *\/\n\/* OpenPOWER HostBoot Project *\/\n\/* *\/\n\/* Contributors Listed Below - COPYRIGHT 2016,2019 *\/\n\/* [+] International Business Machines Corp. *\/\n\/* *\/\n\/* *\/\n\/* Licensed under the Apache License, Version 2.0 (the \"License\"); *\/\n\/* you may not use this file except in compliance with the License. *\/\n\/* You may obtain a copy of the License at *\/\n\/* *\/\n\/* http:\/\/www.apache.org\/licenses\/LICENSE-2.0 *\/\n\/* *\/\n\/* Unless required by applicable law or agreed to in writing, software *\/\n\/* distributed under the License is distributed on an \"AS IS\" BASIS, *\/\n\/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or *\/\n\/* implied. See the License for the specific language governing *\/\n\/* permissions and limitations under the License. *\/\n\/* *\/\n\/* IBM_PROLOG_END_TAG *\/\n\/\/\/ @file p9_sbe_ext_defs.H\n\/\/\/ @brief This file will has structures and constants that can be treated as\n\/\/ the external interfaces of the SBE.\n\n#ifndef _P9_SBE_EXT_DEFS_H_\n#define _P9_SBE_EXT_DEFS_H_\n\n\/\/\/ @brief A structure (bitfield) representing the SBE messaging register\ntypedef union sbeMsgReg\n{\n struct\n {\n#ifdef _BIG_ENDIAN\n uint32_t sbeBooted : 1; \/\/\/< SBE control loop initialized\n uint32_t reserved1 : 3; \/\/\/< Reserved\n uint32_t prevState : 4; \/\/\/< Previous SBE state\n uint32_t currState : 4; \/\/\/< Current SBE state\n uint32_t majorStep : 8; \/\/\/< Last major istep executed by the SBE\n uint32_t minorStep : 6; \/\/\/< Last minor istep executed by the SBE\n uint32_t reserved2 : 6; \/\/\/< Reserved\n#else\n uint32_t reserved2 : 6; \/\/\/< Reserved\n uint32_t minorStep : 6; \/\/\/< Last minor istep executed by the SBE\n uint32_t majorStep : 8; \/\/\/< Last major istep executed by the SBE\n uint32_t currState : 4; \/\/\/< Current SBE state\n uint32_t prevState : 4; \/\/\/< Previous SBE state\n uint32_t reserved1 : 3; \/\/\/< Reserved\n uint32_t sbeBooted : 1; \/\/\/< SBE control loop initialized\n#endif\n };\n uint32_t reg; \/\/\/< The complete SBE messaging register as a uint32\n} sbeMsgReg_t;\n\n\/**\n * @brief Enumeration of SBE states\n*\/\ntypedef enum sbeState\n{\n SBE_STATE_UNKNOWN = 0x0, \/\/ Unkown, initial state\n SBE_STATE_IPLING = 0x1, \/\/ IPL'ing - autonomous mode (transient)\n SBE_STATE_ISTEP = 0x2, \/\/ ISTEP - Running IPL by steps (transient)\n SBE_STATE_MPIPL = 0x3, \/\/ MPIPL\n SBE_STATE_RUNTIME = 0x4, \/\/ SBE Runtime\n SBE_STATE_DMT = 0x5, \/\/ Dead Man Timer State (transient)\n SBE_STATE_DUMP = 0x6, \/\/ Dumping\n SBE_STATE_FAILURE = 0x7, \/\/ Internal SBE failure\n SBE_STATE_QUIESCE = 0x8, \/\/ Final state - needs SBE reset to get out\n\n \/\/ Max States, Always keep it at the last of the enum and sequential\n SBE_MAX_STATE = 0x9,\n \/\/ Don't count this in the state, just to intialize the state variables\n SBE_INVALID_STATE = 0xF,\n} sbeState_t;\n\n#endif \/\/_P9_SBE_EXT_DEFS_H_\n<commit_msg>Support for async bit<commit_after>\/* IBM_PROLOG_BEGIN_TAG *\/\n\/* This is an automatically generated prolog. *\/\n\/* *\/\n\/* $Source: src\/import\/chips\/p9\/procedures\/hwp\/sbe\/p9_sbe_ext_defs.H $ *\/\n\/* *\/\n\/* OpenPOWER HostBoot Project *\/\n\/* *\/\n\/* Contributors Listed Below - COPYRIGHT 2016,2019 *\/\n\/* [+] International Business Machines Corp. *\/\n\/* *\/\n\/* *\/\n\/* Licensed under the Apache License, Version 2.0 (the \"License\"); *\/\n\/* you may not use this file except in compliance with the License. *\/\n\/* You may obtain a copy of the License at *\/\n\/* *\/\n\/* http:\/\/www.apache.org\/licenses\/LICENSE-2.0 *\/\n\/* *\/\n\/* Unless required by applicable law or agreed to in writing, software *\/\n\/* distributed under the License is distributed on an \"AS IS\" BASIS, *\/\n\/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or *\/\n\/* implied. See the License for the specific language governing *\/\n\/* permissions and limitations under the License. *\/\n\/* *\/\n\/* IBM_PROLOG_END_TAG *\/\n\/\/\/ @file p9_sbe_ext_defs.H\n\/\/\/ @brief This file will has structures and constants that can be treated as\n\/\/ the external interfaces of the SBE.\n\n#ifndef _P9_SBE_EXT_DEFS_H_\n#define _P9_SBE_EXT_DEFS_H_\n\n\/\/\/ @brief A structure (bitfield) representing the SBE messaging register\ntypedef union sbeMsgReg\n{\n struct\n {\n#ifdef _BIG_ENDIAN\n uint32_t sbeBooted : 1; \/\/\/< SBE control loop initialized\n uint32_t asyncFFDC : 1; \/\/ < async ffdc present on sbe\n uint32_t reserved1 : 2; \/\/\/< Reserved\n uint32_t prevState : 4; \/\/\/< Previous SBE state\n uint32_t currState : 4; \/\/\/< Current SBE state\n uint32_t majorStep : 8; \/\/\/< Last major istep executed by the SBE\n uint32_t minorStep : 6; \/\/\/< Last minor istep executed by the SBE\n uint32_t reserved2 : 6; \/\/\/< Reserved\n#else\n uint32_t reserved2 : 6; \/\/\/< Reserved\n uint32_t minorStep : 6; \/\/\/< Last minor istep executed by the SBE\n uint32_t majorStep : 8; \/\/\/< Last major istep executed by the SBE\n uint32_t currState : 4; \/\/\/< Current SBE state\n uint32_t prevState : 4; \/\/\/< Previous SBE state\n uint32_t reserved1 : 2; \/\/\/< Reserved\n uint32_t asyncFFDC : 1; \/\/ < async ffdc present on sbe\n uint32_t sbeBooted : 1; \/\/\/< SBE control loop initialized\n#endif\n };\n uint32_t reg; \/\/\/< The complete SBE messaging register as a uint32\n} sbeMsgReg_t;\n\n\/**\n * @brief Enumeration of SBE states\n*\/\ntypedef enum sbeState\n{\n SBE_STATE_UNKNOWN = 0x0, \/\/ Unkown, initial state\n SBE_STATE_IPLING = 0x1, \/\/ IPL'ing - autonomous mode (transient)\n SBE_STATE_ISTEP = 0x2, \/\/ ISTEP - Running IPL by steps (transient)\n SBE_STATE_MPIPL = 0x3, \/\/ MPIPL\n SBE_STATE_RUNTIME = 0x4, \/\/ SBE Runtime\n SBE_STATE_DMT = 0x5, \/\/ Dead Man Timer State (transient)\n SBE_STATE_DUMP = 0x6, \/\/ Dumping\n SBE_STATE_FAILURE = 0x7, \/\/ Internal SBE failure\n SBE_STATE_QUIESCE = 0x8, \/\/ Final state - needs SBE reset to get out\n\n \/\/ Max States, Always keep it at the last of the enum and sequential\n SBE_MAX_STATE = 0x9,\n \/\/ Don't count this in the state, just to intialize the state variables\n SBE_INVALID_STATE = 0xF,\n} sbeState_t;\n\n#endif \/\/_P9_SBE_EXT_DEFS_H_\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome_frame\/test\/test_mock_with_web_server.h\"\n\n#include \"base\/scoped_variant_win.h\"\n#include \"base\/utf_string_conversions.h\"\n#include \"chrome_frame\/test\/simulate_input.h\"\n#include \"chrome_frame\/test\/test_with_web_server.h\"\n\nusing chrome_frame_test::CloseIeAtEndOfScope;\nusing chrome_frame_test::ComStackObjectWithUninitialize;\nusing chrome_frame_test::kChromeFrameLongNavigationTimeoutInSeconds;\nusing testing::_;\n\nnamespace {\n\n\/\/ The same as MockWebBrowserEventSink, except OnDocumentComplete is added.\n\/\/ This class can be merged with its base class, but it would require some\n\/\/ modification to most of the test cases.\nclass MockWebBrowserEventSink\n : public chrome_frame_test::MockWebBrowserEventSink {\n public:\n \/\/ This method is called for each OnDocumentComplete event in which the\n \/\/ document is rendered by IE and not CF.\n MOCK_METHOD1(OnIELoad, void (const wchar_t* url)); \/\/ NOLINT\n\n \/\/ The OnDocumentComplete event is received for every document load,\n \/\/ regardless of whether IE or CF is hosting. This method will call\n \/\/ OnIELoad iff the document was loaded in an IE renderer.\n STDMETHOD_(void, OnDocumentComplete)(IDispatch* dispatch,\n VARIANT* url_variant) {\n ScopedVariant url;\n if (url_variant)\n url.Reset(*url_variant);\n \/\/ To determine if the document is loaded in IE or CF, check if\n \/\/ IHTMLDocument2 can be retrieved. If so, call OnIELoad.\n ScopedComPtr<IWebBrowser2> web_browser2;\n web_browser2.QueryFrom(dispatch);\n EXPECT_TRUE(web_browser2);\n if (web_browser2) {\n ScopedComPtr<IDispatch> doc_dispatch;\n HRESULT hr = web_browser2->get_Document(doc_dispatch.Receive());\n EXPECT_HRESULT_SUCCEEDED(hr);\n EXPECT_TRUE(doc_dispatch);\n if (doc_dispatch) {\n ScopedComPtr<IHTMLDocument2> doc;\n doc.QueryFrom(doc_dispatch);\n if (doc) {\n OnIELoad(V_BSTR(&url));\n }\n }\n }\n }\n};\n\n\/\/ Fixture for tests which ensure that Chrome Frame does not interfere with\n\/\/ normal IE operation.\n\/\/ TODO(kkania): Move this fixture to test_mock_with_web_server.h and change\n\/\/ those tests to use this too.\nclass NoInterferenceTest : public ChromeFrameTestWithWebServer {\n protected:\n \/\/ Launches IE and navigates to |url|, then waits until receiving a quit\n \/\/ message or the timeout is exceeded.\n void LaunchIEAndNavigate(const std::wstring& url) {\n EXPECT_CALL(mock_, OnQuit())\n .Times(testing::AtMost(1))\n .WillOnce(QUIT_LOOP(loop_));\n HRESULT hr = mock_.LaunchIEAndNavigate(url);\n ASSERT_HRESULT_SUCCEEDED(hr);\n if (hr == S_FALSE)\n return;\n\n ASSERT_TRUE(mock_.web_browser2() != NULL);\n loop_.RunFor(kChromeFrameLongNavigationTimeoutInSeconds);\n mock_.Uninitialize();\n }\n\n const std::wstring GetTestUrl(const wchar_t* relative_path) {\n std::wstring path = std::wstring(L\"files\/no_interference\/\") +\n relative_path;\n return UTF8ToWide(server_.Resolve(path.c_str()).spec());\n }\n\n const std::wstring empty_page_url() {\n return GetTestUrl(L\"empty.html\");\n }\n\n \/\/ Returns the url for a page with a single link, which points to the\n \/\/ empty page.\n const std::wstring link_page_url() {\n return GetTestUrl(L\"link.html\");\n }\n\n CloseIeAtEndOfScope last_resort_close_ie;\n chrome_frame_test::TimedMsgLoop loop_;\n CComObjectStackEx<testing::StrictMock<MockWebBrowserEventSink> > mock_;\n};\n\nACTION_P(ExpectIERendererWindowHasFocus, mock) {\n mock->ExpectIERendererWindowHasFocus();\n}\n\nACTION_P6(DelaySendMouseClickToIE, mock, loop, delay, x, y, button) {\n loop->PostDelayedTask(FROM_HERE, NewRunnableMethod(mock,\n &MockWebBrowserEventSink::SendMouseClickToIE, x, y, button), delay);\n}\n\nACTION_P2(OpenContextMenu, loop, delay) {\n loop->PostDelayedTask(FROM_HERE, NewRunnableFunction(\n simulate_input::SendScanCode, VK_F10, simulate_input::SHIFT), delay);\n}\n\nACTION_P3(SelectItem, loop, delay, index) {\n chrome_frame_test::DelaySendExtendedKeysEnter(loop, delay, VK_DOWN, index + 1,\n simulate_input::NONE);\n}\n\n\/\/ A new IE renderer window should have focus.\nTEST_F(NoInterferenceTest, FLAKY_SimpleFocus) {\n mock_.ExpectNavigationInIE(empty_page_url());\n EXPECT_CALL(mock_, OnIELoad(testing::StrCaseEq(empty_page_url())))\n .WillOnce(testing::DoAll(\n ExpectIERendererWindowHasFocus(&mock_),\n VerifyAddressBarUrl(&mock_),\n CloseBrowserMock(&mock_)));\n\n LaunchIEAndNavigate(empty_page_url());\n}\n\n\/\/ Javascript window.open should open a new window with an IE renderer.\nTEST_F(NoInterferenceTest, FLAKY_JavascriptWindowOpen) {\n const std::wstring kWindowOpenUrl = GetTestUrl(L\"window_open.html\");\n ComStackObjectWithUninitialize<\n testing::StrictMock<MockWebBrowserEventSink> > new_window_mock;\n\n mock_.ExpectNavigationInIE(kWindowOpenUrl);\n EXPECT_CALL(mock_, OnIELoad(testing::StrCaseEq(kWindowOpenUrl)))\n .WillOnce(testing::DoAll(\n DelaySendMouseClickToIE(&mock_, &loop_, 0, 100, 100,\n simulate_input::LEFT),\n DelaySendMouseClickToIE(&mock_, &loop_, 0, 100, 100,\n simulate_input::LEFT)));\n\n EXPECT_CALL(mock_, OnNewWindow3(_, _, _, _, _));\n\n EXPECT_CALL(mock_, OnNewBrowserWindow(_, _))\n .WillOnce(testing::WithArgs<0>(testing::Invoke(CreateFunctor(\n &new_window_mock, &MockWebBrowserEventSink::Attach))));\n\n EXPECT_CALL(new_window_mock, OnBeforeNavigate2(_,\n testing::Field(&VARIANT::bstrVal,\n testing::StrCaseEq(empty_page_url())),\n _, _, _, _, _));\n\n EXPECT_CALL(new_window_mock, OnFileDownload(VARIANT_TRUE, _))\n .Times(testing::AnyNumber());\n\n EXPECT_CALL(new_window_mock, OnNavigateComplete2(_,\n testing::Field(&VARIANT::bstrVal,\n testing::StrCaseEq(empty_page_url()))))\n .WillOnce(testing::DoAll(\n testing::InvokeWithoutArgs(CreateFunctor(&new_window_mock,\n &chrome_frame_test::MockWebBrowserEventSink::ExpectAddressBarUrl,\n empty_page_url())),\n DelayCloseBrowserMock(&loop_, 2000, &new_window_mock)));\n\n \/\/ The DocumentComplete at times fires twice for new windows. Hack to account\n \/\/ for that.\n EXPECT_CALL(new_window_mock,\n OnIELoad(testing::StrCaseEq(empty_page_url())))\n .Times(testing::AtMost(2));\n\n EXPECT_CALL(new_window_mock, OnQuit())\n .WillOnce(DelayCloseBrowserMock(&loop_, 2000, &mock_));\n\n LaunchIEAndNavigate(kWindowOpenUrl);\n}\n\n\/\/ Redirecting with window.location in Javascript should work.\nTEST_F(NoInterferenceTest, JavascriptRedirect) {\n const std::wstring kRedirectUrl = GetTestUrl(L\"javascript_redirect.html\");\n mock_.ExpectNavigationInIE(kRedirectUrl);\n EXPECT_CALL(mock_, OnIELoad(testing::StrCaseEq(kRedirectUrl)))\n .WillOnce(VerifyAddressBarUrl(&mock_));\n\n mock_.ExpectNavigationInIE(empty_page_url());\n EXPECT_CALL(mock_, OnIELoad(testing::StrCaseEq(empty_page_url())))\n .WillOnce(testing::DoAll(\n VerifyAddressBarUrl(&mock_),\n CloseBrowserMock(&mock_)));\n\n LaunchIEAndNavigate(kRedirectUrl);\n}\n\nTEST_F(NoInterferenceTest, FLAKY_FollowLink) {\n mock_.ExpectNavigationInIE(link_page_url());\n EXPECT_CALL(mock_, OnIELoad(testing::StrCaseEq(link_page_url())))\n .WillOnce(testing::DoAll(\n DelaySendMouseClickToIE(&mock_, &loop_, 0, 1, 1,\n simulate_input::LEFT),\n DelaySendScanCode(&loop_, 500, VK_TAB, simulate_input::NONE),\n DelaySendScanCode(&loop_, 1000, VK_RETURN, simulate_input::NONE)));\n\n mock_.ExpectNavigationInIE(empty_page_url());\n EXPECT_CALL(mock_, OnIELoad(testing::StrCaseEq(empty_page_url())))\n .WillOnce(testing::DoAll(\n VerifyAddressBarUrl(&mock_),\n CloseBrowserMock(&mock_)));\n\n LaunchIEAndNavigate(link_page_url());\n}\n\nTEST_F(NoInterferenceTest, FLAKY_SelectContextMenuOpen) {\n mock_.ExpectNavigationInIE(link_page_url());\n \/\/ Focus the renderer window by clicking and then tab once to highlight the\n \/\/ link.\n EXPECT_CALL(mock_, OnIELoad(testing::StrCaseEq(link_page_url())))\n .WillOnce(testing::DoAll(\n DelaySendMouseClickToIE(&mock_, &loop_, 0, 1, 1,\n simulate_input::LEFT),\n DelaySendScanCode(&loop_, 500, VK_TAB, simulate_input::NONE),\n OpenContextMenu(&loop_, 1000),\n SelectItem(&loop_, 1500, 0)));\n\n mock_.ExpectNavigationInIE(empty_page_url());\n EXPECT_CALL(mock_, OnIELoad(testing::StrCaseEq(empty_page_url())))\n .WillOnce(testing::DoAll(\n VerifyAddressBarUrl(&mock_),\n CloseBrowserMock(&mock_)));\n\n LaunchIEAndNavigate(link_page_url());\n}\n\nTEST_F(NoInterferenceTest, FLAKY_SelectContextMenuOpenInNewWindow) {\n ComStackObjectWithUninitialize<\n testing::StrictMock<MockWebBrowserEventSink> > new_window_mock;\n int open_new_window_index = 2;\n if (chrome_frame_test::GetInstalledIEVersion() == IE_6)\n open_new_window_index = 1;\n\n \/\/ Focus the renderer window by clicking and then tab once to highlight the\n \/\/ link.\n mock_.ExpectNavigationInIE(link_page_url());\n EXPECT_CALL(mock_, OnIELoad(testing::StrCaseEq(link_page_url())))\n .WillOnce(testing::DoAll(\n DelaySendMouseClickToIE(&mock_, &loop_, 0, 1, 1,\n simulate_input::LEFT),\n DelaySendScanCode(&loop_, 500, VK_TAB, simulate_input::NONE),\n OpenContextMenu(&loop_, 1000),\n SelectItem(&loop_, 1500, open_new_window_index)));\n\n mock_.ExpectNewWindowWithIE(empty_page_url(), &new_window_mock);\n \/\/ The DocumentComplete at times fires twice for new windows. Hack to account\n \/\/ for that.\n \/\/ TODO(kkania): Verifying the address bar is flaky with this, at least\n \/\/ on XP ie6. Fix.\n EXPECT_CALL(new_window_mock,\n OnIELoad(testing::StrCaseEq(empty_page_url())))\n .Times(testing::AtMost(2))\n .WillOnce(DelayCloseBrowserMock(&loop_, 2000, &new_window_mock));\n\n EXPECT_CALL(new_window_mock, OnQuit()).WillOnce(CloseBrowserMock(&mock_));\n\n LaunchIEAndNavigate(link_page_url());\n}\n\n} \/\/ namespace<commit_msg>Disable a crashing test: NoInterferenceTest.JavascriptWindowOpen<commit_after>\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome_frame\/test\/test_mock_with_web_server.h\"\n\n#include \"base\/scoped_variant_win.h\"\n#include \"base\/utf_string_conversions.h\"\n#include \"chrome_frame\/test\/simulate_input.h\"\n#include \"chrome_frame\/test\/test_with_web_server.h\"\n\nusing chrome_frame_test::CloseIeAtEndOfScope;\nusing chrome_frame_test::ComStackObjectWithUninitialize;\nusing chrome_frame_test::kChromeFrameLongNavigationTimeoutInSeconds;\nusing testing::_;\n\nnamespace {\n\n\/\/ The same as MockWebBrowserEventSink, except OnDocumentComplete is added.\n\/\/ This class can be merged with its base class, but it would require some\n\/\/ modification to most of the test cases.\nclass MockWebBrowserEventSink\n : public chrome_frame_test::MockWebBrowserEventSink {\n public:\n \/\/ This method is called for each OnDocumentComplete event in which the\n \/\/ document is rendered by IE and not CF.\n MOCK_METHOD1(OnIELoad, void (const wchar_t* url)); \/\/ NOLINT\n\n \/\/ The OnDocumentComplete event is received for every document load,\n \/\/ regardless of whether IE or CF is hosting. This method will call\n \/\/ OnIELoad iff the document was loaded in an IE renderer.\n STDMETHOD_(void, OnDocumentComplete)(IDispatch* dispatch,\n VARIANT* url_variant) {\n ScopedVariant url;\n if (url_variant)\n url.Reset(*url_variant);\n \/\/ To determine if the document is loaded in IE or CF, check if\n \/\/ IHTMLDocument2 can be retrieved. If so, call OnIELoad.\n ScopedComPtr<IWebBrowser2> web_browser2;\n web_browser2.QueryFrom(dispatch);\n EXPECT_TRUE(web_browser2);\n if (web_browser2) {\n ScopedComPtr<IDispatch> doc_dispatch;\n HRESULT hr = web_browser2->get_Document(doc_dispatch.Receive());\n EXPECT_HRESULT_SUCCEEDED(hr);\n EXPECT_TRUE(doc_dispatch);\n if (doc_dispatch) {\n ScopedComPtr<IHTMLDocument2> doc;\n doc.QueryFrom(doc_dispatch);\n if (doc) {\n OnIELoad(V_BSTR(&url));\n }\n }\n }\n }\n};\n\n\/\/ Fixture for tests which ensure that Chrome Frame does not interfere with\n\/\/ normal IE operation.\n\/\/ TODO(kkania): Move this fixture to test_mock_with_web_server.h and change\n\/\/ those tests to use this too.\nclass NoInterferenceTest : public ChromeFrameTestWithWebServer {\n protected:\n \/\/ Launches IE and navigates to |url|, then waits until receiving a quit\n \/\/ message or the timeout is exceeded.\n void LaunchIEAndNavigate(const std::wstring& url) {\n EXPECT_CALL(mock_, OnQuit())\n .Times(testing::AtMost(1))\n .WillOnce(QUIT_LOOP(loop_));\n HRESULT hr = mock_.LaunchIEAndNavigate(url);\n ASSERT_HRESULT_SUCCEEDED(hr);\n if (hr == S_FALSE)\n return;\n\n ASSERT_TRUE(mock_.web_browser2() != NULL);\n loop_.RunFor(kChromeFrameLongNavigationTimeoutInSeconds);\n mock_.Uninitialize();\n }\n\n const std::wstring GetTestUrl(const wchar_t* relative_path) {\n std::wstring path = std::wstring(L\"files\/no_interference\/\") +\n relative_path;\n return UTF8ToWide(server_.Resolve(path.c_str()).spec());\n }\n\n const std::wstring empty_page_url() {\n return GetTestUrl(L\"empty.html\");\n }\n\n \/\/ Returns the url for a page with a single link, which points to the\n \/\/ empty page.\n const std::wstring link_page_url() {\n return GetTestUrl(L\"link.html\");\n }\n\n CloseIeAtEndOfScope last_resort_close_ie;\n chrome_frame_test::TimedMsgLoop loop_;\n CComObjectStackEx<testing::StrictMock<MockWebBrowserEventSink> > mock_;\n};\n\nACTION_P(ExpectIERendererWindowHasFocus, mock) {\n mock->ExpectIERendererWindowHasFocus();\n}\n\nACTION_P6(DelaySendMouseClickToIE, mock, loop, delay, x, y, button) {\n loop->PostDelayedTask(FROM_HERE, NewRunnableMethod(mock,\n &MockWebBrowserEventSink::SendMouseClickToIE, x, y, button), delay);\n}\n\nACTION_P2(OpenContextMenu, loop, delay) {\n loop->PostDelayedTask(FROM_HERE, NewRunnableFunction(\n simulate_input::SendScanCode, VK_F10, simulate_input::SHIFT), delay);\n}\n\nACTION_P3(SelectItem, loop, delay, index) {\n chrome_frame_test::DelaySendExtendedKeysEnter(loop, delay, VK_DOWN, index + 1,\n simulate_input::NONE);\n}\n\n\/\/ A new IE renderer window should have focus.\nTEST_F(NoInterferenceTest, FLAKY_SimpleFocus) {\n mock_.ExpectNavigationInIE(empty_page_url());\n EXPECT_CALL(mock_, OnIELoad(testing::StrCaseEq(empty_page_url())))\n .WillOnce(testing::DoAll(\n ExpectIERendererWindowHasFocus(&mock_),\n VerifyAddressBarUrl(&mock_),\n CloseBrowserMock(&mock_)));\n\n LaunchIEAndNavigate(empty_page_url());\n}\n\n\/\/ Javascript window.open should open a new window with an IE renderer.\n\/\/ Disabled because of crashes.\n\/\/ http:\/\/code.google.com\/p\/chromium\/issues\/detail?id=48175\nTEST_F(NoInterferenceTest, DISABLED_JavascriptWindowOpen) {\n const std::wstring kWindowOpenUrl = GetTestUrl(L\"window_open.html\");\n ComStackObjectWithUninitialize<\n testing::StrictMock<MockWebBrowserEventSink> > new_window_mock;\n\n mock_.ExpectNavigationInIE(kWindowOpenUrl);\n EXPECT_CALL(mock_, OnIELoad(testing::StrCaseEq(kWindowOpenUrl)))\n .WillOnce(testing::DoAll(\n DelaySendMouseClickToIE(&mock_, &loop_, 0, 100, 100,\n simulate_input::LEFT),\n DelaySendMouseClickToIE(&mock_, &loop_, 0, 100, 100,\n simulate_input::LEFT)));\n\n EXPECT_CALL(mock_, OnNewWindow3(_, _, _, _, _));\n\n EXPECT_CALL(mock_, OnNewBrowserWindow(_, _))\n .WillOnce(testing::WithArgs<0>(testing::Invoke(CreateFunctor(\n &new_window_mock, &MockWebBrowserEventSink::Attach))));\n\n EXPECT_CALL(new_window_mock, OnBeforeNavigate2(_,\n testing::Field(&VARIANT::bstrVal,\n testing::StrCaseEq(empty_page_url())),\n _, _, _, _, _));\n\n EXPECT_CALL(new_window_mock, OnFileDownload(VARIANT_TRUE, _))\n .Times(testing::AnyNumber());\n\n EXPECT_CALL(new_window_mock, OnNavigateComplete2(_,\n testing::Field(&VARIANT::bstrVal,\n testing::StrCaseEq(empty_page_url()))))\n .WillOnce(testing::DoAll(\n testing::InvokeWithoutArgs(CreateFunctor(&new_window_mock,\n &chrome_frame_test::MockWebBrowserEventSink::ExpectAddressBarUrl,\n empty_page_url())),\n DelayCloseBrowserMock(&loop_, 2000, &new_window_mock)));\n\n \/\/ The DocumentComplete at times fires twice for new windows. Hack to account\n \/\/ for that.\n EXPECT_CALL(new_window_mock,\n OnIELoad(testing::StrCaseEq(empty_page_url())))\n .Times(testing::AtMost(2));\n\n EXPECT_CALL(new_window_mock, OnQuit())\n .WillOnce(DelayCloseBrowserMock(&loop_, 2000, &mock_));\n\n LaunchIEAndNavigate(kWindowOpenUrl);\n}\n\n\/\/ Redirecting with window.location in Javascript should work.\nTEST_F(NoInterferenceTest, JavascriptRedirect) {\n const std::wstring kRedirectUrl = GetTestUrl(L\"javascript_redirect.html\");\n mock_.ExpectNavigationInIE(kRedirectUrl);\n EXPECT_CALL(mock_, OnIELoad(testing::StrCaseEq(kRedirectUrl)))\n .WillOnce(VerifyAddressBarUrl(&mock_));\n\n mock_.ExpectNavigationInIE(empty_page_url());\n EXPECT_CALL(mock_, OnIELoad(testing::StrCaseEq(empty_page_url())))\n .WillOnce(testing::DoAll(\n VerifyAddressBarUrl(&mock_),\n CloseBrowserMock(&mock_)));\n\n LaunchIEAndNavigate(kRedirectUrl);\n}\n\nTEST_F(NoInterferenceTest, FLAKY_FollowLink) {\n mock_.ExpectNavigationInIE(link_page_url());\n EXPECT_CALL(mock_, OnIELoad(testing::StrCaseEq(link_page_url())))\n .WillOnce(testing::DoAll(\n DelaySendMouseClickToIE(&mock_, &loop_, 0, 1, 1,\n simulate_input::LEFT),\n DelaySendScanCode(&loop_, 500, VK_TAB, simulate_input::NONE),\n DelaySendScanCode(&loop_, 1000, VK_RETURN, simulate_input::NONE)));\n\n mock_.ExpectNavigationInIE(empty_page_url());\n EXPECT_CALL(mock_, OnIELoad(testing::StrCaseEq(empty_page_url())))\n .WillOnce(testing::DoAll(\n VerifyAddressBarUrl(&mock_),\n CloseBrowserMock(&mock_)));\n\n LaunchIEAndNavigate(link_page_url());\n}\n\nTEST_F(NoInterferenceTest, FLAKY_SelectContextMenuOpen) {\n mock_.ExpectNavigationInIE(link_page_url());\n \/\/ Focus the renderer window by clicking and then tab once to highlight the\n \/\/ link.\n EXPECT_CALL(mock_, OnIELoad(testing::StrCaseEq(link_page_url())))\n .WillOnce(testing::DoAll(\n DelaySendMouseClickToIE(&mock_, &loop_, 0, 1, 1,\n simulate_input::LEFT),\n DelaySendScanCode(&loop_, 500, VK_TAB, simulate_input::NONE),\n OpenContextMenu(&loop_, 1000),\n SelectItem(&loop_, 1500, 0)));\n\n mock_.ExpectNavigationInIE(empty_page_url());\n EXPECT_CALL(mock_, OnIELoad(testing::StrCaseEq(empty_page_url())))\n .WillOnce(testing::DoAll(\n VerifyAddressBarUrl(&mock_),\n CloseBrowserMock(&mock_)));\n\n LaunchIEAndNavigate(link_page_url());\n}\n\nTEST_F(NoInterferenceTest, FLAKY_SelectContextMenuOpenInNewWindow) {\n ComStackObjectWithUninitialize<\n testing::StrictMock<MockWebBrowserEventSink> > new_window_mock;\n int open_new_window_index = 2;\n if (chrome_frame_test::GetInstalledIEVersion() == IE_6)\n open_new_window_index = 1;\n\n \/\/ Focus the renderer window by clicking and then tab once to highlight the\n \/\/ link.\n mock_.ExpectNavigationInIE(link_page_url());\n EXPECT_CALL(mock_, OnIELoad(testing::StrCaseEq(link_page_url())))\n .WillOnce(testing::DoAll(\n DelaySendMouseClickToIE(&mock_, &loop_, 0, 1, 1,\n simulate_input::LEFT),\n DelaySendScanCode(&loop_, 500, VK_TAB, simulate_input::NONE),\n OpenContextMenu(&loop_, 1000),\n SelectItem(&loop_, 1500, open_new_window_index)));\n\n mock_.ExpectNewWindowWithIE(empty_page_url(), &new_window_mock);\n \/\/ The DocumentComplete at times fires twice for new windows. Hack to account\n \/\/ for that.\n \/\/ TODO(kkania): Verifying the address bar is flaky with this, at least\n \/\/ on XP ie6. Fix.\n EXPECT_CALL(new_window_mock,\n OnIELoad(testing::StrCaseEq(empty_page_url())))\n .Times(testing::AtMost(2))\n .WillOnce(DelayCloseBrowserMock(&loop_, 2000, &new_window_mock));\n\n EXPECT_CALL(new_window_mock, OnQuit()).WillOnce(CloseBrowserMock(&mock_));\n\n LaunchIEAndNavigate(link_page_url());\n}\n\n} \/\/ namespace\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2011 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\/\/\n\/\/ NOTE: These tests are run as part of \"unit_tests\" (in chrome\/test\/unit)\n\/\/ rather than as part of test_shell_tests because they rely on being able\n\/\/ to instantiate a MessageLoop of type TYPE_IO. test_shell_tests uses\n\/\/ TYPE_UI, which URLRequest doesn't allow.\n\/\/\n\n#include \"webkit\/fileapi\/file_system_operation.h\"\n\n#include \"base\/message_loop.h\"\n#include \"base\/memory\/scoped_ptr.h\"\n#include \"base\/memory\/scoped_temp_dir.h\"\n#include \"base\/message_loop.h\"\n#include \"googleurl\/src\/gurl.h\"\n#include \"net\/url_request\/url_request.h\"\n#include \"net\/url_request\/url_request_context.h\"\n#include \"net\/url_request\/url_request_job.h\"\n#include \"testing\/gtest\/include\/gtest\/gtest.h\"\n#include \"webkit\/blob\/blob_data.h\"\n#include \"webkit\/blob\/blob_storage_controller.h\"\n#include \"webkit\/blob\/blob_url_request_job.h\"\n#include \"webkit\/fileapi\/file_system_callback_dispatcher.h\"\n#include \"webkit\/fileapi\/file_system_file_util.h\"\n\nnamespace fileapi {\nnamespace {\nclass MockDispatcher;\n} \/\/ namespace (anonymous)\n\nclass FileSystemOperationWriteTest : public testing::Test {\n public:\n FileSystemOperationWriteTest()\n : loop_(MessageLoop::TYPE_IO),\n status_(base::PLATFORM_FILE_OK),\n bytes_written_(0),\n complete_(false) {}\n\n FileSystemOperation* operation();\n\n void set_failure_status(base::PlatformFileError status) {\n EXPECT_FALSE(complete_);\n EXPECT_EQ(status_, base::PLATFORM_FILE_OK);\n EXPECT_NE(status, base::PLATFORM_FILE_OK);\n complete_ = true;\n status_ = status;\n }\n base::PlatformFileError status() const { return status_; }\n void add_bytes_written(int64 bytes, bool complete) {\n bytes_written_ += bytes;\n EXPECT_FALSE(complete_);\n complete_ = complete;\n }\n int64 bytes_written() const { return bytes_written_; }\n bool complete() const { return complete_; }\n\n virtual void SetUp();\n virtual void TearDown();\n\n protected:\n GURL URLForRelativePath(const std::string& path) const {\n \/\/ Only the path will actually get used.\n return GURL(\"file:\/\/\").Resolve(file_.value()).Resolve(path);\n }\n\n GURL URLForPath(const FilePath& path) const {\n \/\/ Only the path will actually get used.\n return GURL(\"file:\/\/\").Resolve(path.value());\n }\n\n MessageLoop loop_;\n\n ScopedTempDir dir_;\n FilePath file_;\n\n \/\/ For post-operation status.\n base::PlatformFileError status_;\n int64 bytes_written_;\n bool complete_;\n\n DISALLOW_COPY_AND_ASSIGN(FileSystemOperationWriteTest);\n};\n\nnamespace {\n\nclass TestURLRequestContext : public net::URLRequestContext {\n public:\n webkit_blob::BlobStorageController* blob_storage_controller() {\n return &blob_storage_controller_;\n }\n\n private:\n webkit_blob::BlobStorageController blob_storage_controller_;\n};\n\nstatic net::URLRequestJob* BlobURLRequestJobFactory(net::URLRequest* request,\n const std::string& scheme) {\n webkit_blob::BlobStorageController* blob_storage_controller =\n static_cast<TestURLRequestContext*>(request->context())->\n blob_storage_controller();\n return new webkit_blob::BlobURLRequestJob(\n request,\n blob_storage_controller->GetBlobDataFromUrl(request->url()),\n base::MessageLoopProxy::CreateForCurrentThread());\n}\n\nclass MockDispatcher : public FileSystemCallbackDispatcher {\n public:\n MockDispatcher(FileSystemOperationWriteTest* test) : test_(test) { }\n\n virtual void DidFail(base::PlatformFileError status) {\n test_->set_failure_status(status);\n MessageLoop::current()->Quit();\n }\n\n virtual void DidSucceed() {\n ADD_FAILURE();\n }\n\n virtual void DidReadMetadata(\n const base::PlatformFileInfo& info,\n const FilePath& platform_path) {\n ADD_FAILURE();\n }\n\n virtual void DidReadDirectory(\n const std::vector<base::FileUtilProxy::Entry>& entries,\n bool \/* has_more *\/) {\n ADD_FAILURE();\n }\n\n virtual void DidOpenFileSystem(const std::string&, const GURL&) {\n ADD_FAILURE();\n }\n\n virtual void DidWrite(int64 bytes, bool complete) {\n test_->add_bytes_written(bytes, complete);\n MessageLoop::current()->Quit();\n }\n\n private:\n FileSystemOperationWriteTest* test_;\n};\n\n} \/\/ namespace (anonymous)\n\nvoid FileSystemOperationWriteTest::SetUp() {\n ASSERT_TRUE(dir_.CreateUniqueTempDir());\n file_util::CreateTemporaryFileInDir(dir_.path(), &file_);\n net::URLRequest::RegisterProtocolFactory(\"blob\", &BlobURLRequestJobFactory);\n}\n\nvoid FileSystemOperationWriteTest::TearDown() {\n net::URLRequest::RegisterProtocolFactory(\"blob\", NULL);\n}\n\nFileSystemOperation* FileSystemOperationWriteTest::operation() {\n FileSystemOperation* operation = new FileSystemOperation(\n new MockDispatcher(this),\n base::MessageLoopProxy::CreateForCurrentThread(),\n NULL,\n FileSystemFileUtil::GetInstance());\n operation->file_system_operation_context()->set_src_type(\n kFileSystemTypeTemporary);\n operation->file_system_operation_context()->set_dest_type(\n kFileSystemTypeTemporary);\n return operation;\n}\n\nTEST_F(FileSystemOperationWriteTest, TestWriteSuccess) {\n GURL blob_url(\"blob:success\");\n scoped_refptr<webkit_blob::BlobData> blob_data(new webkit_blob::BlobData());\n blob_data->AppendData(\"Hello, world!\\n\");\n\n scoped_refptr<TestURLRequestContext> url_request_context(\n new TestURLRequestContext());\n url_request_context->blob_storage_controller()->\n RegisterBlobUrl(blob_url, blob_data);\n\n operation()->Write(url_request_context, URLForPath(file_), blob_url, 0);\n MessageLoop::current()->Run();\n\n url_request_context->blob_storage_controller()->UnregisterBlobUrl(blob_url);\n\n EXPECT_EQ(14, bytes_written());\n EXPECT_EQ(base::PLATFORM_FILE_OK, status());\n EXPECT_TRUE(complete());\n}\n\nTEST_F(FileSystemOperationWriteTest, TestWriteZero) {\n GURL blob_url(\"blob:zero\");\n scoped_refptr<webkit_blob::BlobData> blob_data(new webkit_blob::BlobData());\n blob_data->AppendData(\"\");\n\n scoped_refptr<TestURLRequestContext> url_request_context(\n new TestURLRequestContext());\n url_request_context->blob_storage_controller()->\n RegisterBlobUrl(blob_url, blob_data);\n\n operation()->Write(url_request_context, URLForPath(file_), blob_url, 0);\n MessageLoop::current()->Run();\n\n url_request_context->blob_storage_controller()->UnregisterBlobUrl(blob_url);\n\n EXPECT_EQ(0, bytes_written());\n EXPECT_EQ(base::PLATFORM_FILE_OK, status());\n EXPECT_TRUE(complete());\n}\n\nTEST_F(FileSystemOperationWriteTest, TestWriteInvalidBlobUrl) {\n scoped_refptr<TestURLRequestContext> url_request_context(\n new TestURLRequestContext());\n\n operation()->Write(url_request_context, URLForPath(file_),\n GURL(\"blob:invalid\"), 0);\n MessageLoop::current()->Run();\n\n EXPECT_EQ(0, bytes_written());\n EXPECT_EQ(base::PLATFORM_FILE_OK, status());\n EXPECT_TRUE(complete());\n}\n\nTEST_F(FileSystemOperationWriteTest, TestWriteInvalidFile) {\n GURL blob_url(\"blob:writeinvalidfile\");\n scoped_refptr<webkit_blob::BlobData> blob_data(new webkit_blob::BlobData());\n blob_data->AppendData(\"It\\'ll not be written.\");\n\n scoped_refptr<TestURLRequestContext> url_request_context(\n new TestURLRequestContext());\n url_request_context->blob_storage_controller()->\n RegisterBlobUrl(blob_url, blob_data);\n\n operation()->Write(url_request_context,\n URLForRelativePath(\"nonexist\"), blob_url, 0);\n MessageLoop::current()->Run();\n\n url_request_context->blob_storage_controller()->UnregisterBlobUrl(blob_url);\n\n EXPECT_EQ(0, bytes_written());\n EXPECT_EQ(base::PLATFORM_FILE_ERROR_NOT_FOUND, status());\n EXPECT_TRUE(complete());\n}\n\nTEST_F(FileSystemOperationWriteTest, TestWriteDir) {\n GURL blob_url(\"blob:writedir\");\n scoped_refptr<webkit_blob::BlobData> blob_data(new webkit_blob::BlobData());\n blob_data->AppendData(\"It\\'ll not be written, too.\");\n\n scoped_refptr<TestURLRequestContext> url_request_context(\n new TestURLRequestContext());\n url_request_context->blob_storage_controller()->\n RegisterBlobUrl(blob_url, blob_data);\n\n operation()->Write(url_request_context, URLForPath(dir_.path()), blob_url, 0);\n MessageLoop::current()->Run();\n\n url_request_context->blob_storage_controller()->UnregisterBlobUrl(blob_url);\n\n EXPECT_EQ(0, bytes_written());\n EXPECT_EQ(base::PLATFORM_FILE_ERROR_ACCESS_DENIED, status());\n EXPECT_TRUE(complete());\n}\n\n\/\/ TODO(ericu,dmikurube): Add tests for Cancel.\n\n} \/\/ namespace fileapi\n<commit_msg>Nit fix FileSystemOperationWriteTest about when exiting the thread and remove unnecessary lines.<commit_after>\/\/ Copyright (c) 2011 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\/\/\n\/\/ NOTE: These tests are run as part of \"unit_tests\" (in chrome\/test\/unit)\n\/\/ rather than as part of test_shell_tests because they rely on being able\n\/\/ to instantiate a MessageLoop of type TYPE_IO. test_shell_tests uses\n\/\/ TYPE_UI, which URLRequest doesn't allow.\n\/\/\n\n#include \"base\/message_loop.h\"\n#include \"base\/memory\/scoped_ptr.h\"\n#include \"base\/memory\/scoped_temp_dir.h\"\n#include \"base\/message_loop.h\"\n#include \"googleurl\/src\/gurl.h\"\n#include \"net\/url_request\/url_request.h\"\n#include \"net\/url_request\/url_request_context.h\"\n#include \"net\/url_request\/url_request_job.h\"\n#include \"testing\/gtest\/include\/gtest\/gtest.h\"\n#include \"webkit\/blob\/blob_data.h\"\n#include \"webkit\/blob\/blob_storage_controller.h\"\n#include \"webkit\/blob\/blob_url_request_job.h\"\n#include \"webkit\/fileapi\/file_system_callback_dispatcher.h\"\n#include \"webkit\/fileapi\/file_system_file_util.h\"\n#include \"webkit\/fileapi\/file_system_operation.h\"\n\nnamespace fileapi {\n\nclass FileSystemOperationWriteTest : public testing::Test {\n public:\n FileSystemOperationWriteTest()\n : loop_(MessageLoop::TYPE_IO),\n status_(base::PLATFORM_FILE_OK),\n bytes_written_(0),\n complete_(false) {}\n\n FileSystemOperation* operation();\n\n void set_failure_status(base::PlatformFileError status) {\n EXPECT_FALSE(complete_);\n EXPECT_EQ(status_, base::PLATFORM_FILE_OK);\n EXPECT_NE(status, base::PLATFORM_FILE_OK);\n complete_ = true;\n status_ = status;\n }\n base::PlatformFileError status() const { return status_; }\n void add_bytes_written(int64 bytes, bool complete) {\n bytes_written_ += bytes;\n EXPECT_FALSE(complete_);\n complete_ = complete;\n }\n int64 bytes_written() const { return bytes_written_; }\n bool complete() const { return complete_; }\n\n virtual void SetUp();\n virtual void TearDown();\n\n protected:\n GURL URLForRelativePath(const std::string& path) const {\n \/\/ Only the path will actually get used.\n return GURL(\"file:\/\/\").Resolve(file_.value()).Resolve(path);\n }\n\n GURL URLForPath(const FilePath& path) const {\n \/\/ Only the path will actually get used.\n return GURL(\"file:\/\/\").Resolve(path.value());\n }\n\n MessageLoop loop_;\n\n ScopedTempDir dir_;\n FilePath file_;\n\n \/\/ For post-operation status.\n base::PlatformFileError status_;\n int64 bytes_written_;\n bool complete_;\n\n DISALLOW_COPY_AND_ASSIGN(FileSystemOperationWriteTest);\n};\n\nnamespace {\n\nclass TestURLRequestContext : public net::URLRequestContext {\n public:\n webkit_blob::BlobStorageController* blob_storage_controller() {\n return &blob_storage_controller_;\n }\n\n private:\n webkit_blob::BlobStorageController blob_storage_controller_;\n};\n\nstatic net::URLRequestJob* BlobURLRequestJobFactory(net::URLRequest* request,\n const std::string& scheme) {\n webkit_blob::BlobStorageController* blob_storage_controller =\n static_cast<TestURLRequestContext*>(request->context())->\n blob_storage_controller();\n return new webkit_blob::BlobURLRequestJob(\n request,\n blob_storage_controller->GetBlobDataFromUrl(request->url()),\n base::MessageLoopProxy::CreateForCurrentThread());\n}\n\nclass MockDispatcher : public FileSystemCallbackDispatcher {\n public:\n MockDispatcher(FileSystemOperationWriteTest* test) : test_(test) { }\n\n virtual void DidFail(base::PlatformFileError status) {\n test_->set_failure_status(status);\n MessageLoop::current()->Quit();\n }\n\n virtual void DidSucceed() {\n ADD_FAILURE();\n }\n\n virtual void DidReadMetadata(\n const base::PlatformFileInfo& info,\n const FilePath& platform_path) {\n ADD_FAILURE();\n }\n\n virtual void DidReadDirectory(\n const std::vector<base::FileUtilProxy::Entry>& entries,\n bool \/* has_more *\/) {\n ADD_FAILURE();\n }\n\n virtual void DidOpenFileSystem(const std::string&, const GURL&) {\n ADD_FAILURE();\n }\n\n virtual void DidWrite(int64 bytes, bool complete) {\n test_->add_bytes_written(bytes, complete);\n if (complete)\n MessageLoop::current()->Quit();\n }\n\n private:\n FileSystemOperationWriteTest* test_;\n};\n\n} \/\/ namespace (anonymous)\n\nvoid FileSystemOperationWriteTest::SetUp() {\n ASSERT_TRUE(dir_.CreateUniqueTempDir());\n file_util::CreateTemporaryFileInDir(dir_.path(), &file_);\n net::URLRequest::RegisterProtocolFactory(\"blob\", &BlobURLRequestJobFactory);\n}\n\nvoid FileSystemOperationWriteTest::TearDown() {\n net::URLRequest::RegisterProtocolFactory(\"blob\", NULL);\n}\n\nFileSystemOperation* FileSystemOperationWriteTest::operation() {\n FileSystemOperation* operation = new FileSystemOperation(\n new MockDispatcher(this),\n base::MessageLoopProxy::CreateForCurrentThread(),\n NULL,\n FileSystemFileUtil::GetInstance());\n operation->file_system_operation_context()->set_src_type(\n kFileSystemTypeTemporary);\n operation->file_system_operation_context()->set_dest_type(\n kFileSystemTypeTemporary);\n return operation;\n}\n\nTEST_F(FileSystemOperationWriteTest, TestWriteSuccess) {\n GURL blob_url(\"blob:success\");\n scoped_refptr<webkit_blob::BlobData> blob_data(new webkit_blob::BlobData());\n blob_data->AppendData(\"Hello, world!\\n\");\n\n scoped_refptr<TestURLRequestContext> url_request_context(\n new TestURLRequestContext());\n url_request_context->blob_storage_controller()->\n RegisterBlobUrl(blob_url, blob_data);\n\n operation()->Write(url_request_context, URLForPath(file_), blob_url, 0);\n MessageLoop::current()->Run();\n\n url_request_context->blob_storage_controller()->UnregisterBlobUrl(blob_url);\n\n EXPECT_EQ(14, bytes_written());\n EXPECT_EQ(base::PLATFORM_FILE_OK, status());\n EXPECT_TRUE(complete());\n}\n\nTEST_F(FileSystemOperationWriteTest, TestWriteZero) {\n GURL blob_url(\"blob:zero\");\n scoped_refptr<webkit_blob::BlobData> blob_data(new webkit_blob::BlobData());\n blob_data->AppendData(\"\");\n\n scoped_refptr<TestURLRequestContext> url_request_context(\n new TestURLRequestContext());\n url_request_context->blob_storage_controller()->\n RegisterBlobUrl(blob_url, blob_data);\n\n operation()->Write(url_request_context, URLForPath(file_), blob_url, 0);\n MessageLoop::current()->Run();\n\n url_request_context->blob_storage_controller()->UnregisterBlobUrl(blob_url);\n\n EXPECT_EQ(0, bytes_written());\n EXPECT_EQ(base::PLATFORM_FILE_OK, status());\n EXPECT_TRUE(complete());\n}\n\nTEST_F(FileSystemOperationWriteTest, TestWriteInvalidBlobUrl) {\n scoped_refptr<TestURLRequestContext> url_request_context(\n new TestURLRequestContext());\n\n operation()->Write(url_request_context, URLForPath(file_),\n GURL(\"blob:invalid\"), 0);\n MessageLoop::current()->Run();\n\n EXPECT_EQ(0, bytes_written());\n EXPECT_EQ(base::PLATFORM_FILE_OK, status());\n EXPECT_TRUE(complete());\n}\n\nTEST_F(FileSystemOperationWriteTest, TestWriteInvalidFile) {\n GURL blob_url(\"blob:writeinvalidfile\");\n scoped_refptr<webkit_blob::BlobData> blob_data(new webkit_blob::BlobData());\n blob_data->AppendData(\"It\\'ll not be written.\");\n\n scoped_refptr<TestURLRequestContext> url_request_context(\n new TestURLRequestContext());\n url_request_context->blob_storage_controller()->\n RegisterBlobUrl(blob_url, blob_data);\n\n operation()->Write(url_request_context,\n URLForRelativePath(\"nonexist\"), blob_url, 0);\n MessageLoop::current()->Run();\n\n url_request_context->blob_storage_controller()->UnregisterBlobUrl(blob_url);\n\n EXPECT_EQ(0, bytes_written());\n EXPECT_EQ(base::PLATFORM_FILE_ERROR_NOT_FOUND, status());\n EXPECT_TRUE(complete());\n}\n\nTEST_F(FileSystemOperationWriteTest, TestWriteDir) {\n GURL blob_url(\"blob:writedir\");\n scoped_refptr<webkit_blob::BlobData> blob_data(new webkit_blob::BlobData());\n blob_data->AppendData(\"It\\'ll not be written, too.\");\n\n scoped_refptr<TestURLRequestContext> url_request_context(\n new TestURLRequestContext());\n url_request_context->blob_storage_controller()->\n RegisterBlobUrl(blob_url, blob_data);\n\n operation()->Write(url_request_context, URLForPath(dir_.path()), blob_url, 0);\n MessageLoop::current()->Run();\n\n url_request_context->blob_storage_controller()->UnregisterBlobUrl(blob_url);\n\n EXPECT_EQ(0, bytes_written());\n EXPECT_EQ(base::PLATFORM_FILE_ERROR_ACCESS_DENIED, status());\n EXPECT_TRUE(complete());\n}\n\n\/\/ TODO(ericu,dmikurube): Add tests for Cancel.\n\n} \/\/ namespace fileapi\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (C) 2007-2014 Frank Mertens.\n *\n * Use of this source is governed by a BSD-style license that can be\n * found in the LICENSE file.\n *\n *\/\n\n#include <flux\/Singleton>\n#ifndef NDEBUG\n#include <flux\/SyntaxDebugger>\n#endif\n#include <flux\/syntax>\n#include <flux\/Format>\n#include <flux\/Pattern>\n#include <flux\/PatternSyntax>\n\nnamespace flux {\n\ntypedef syntax::NODE NODE;\n\nPatternSyntax::PatternSyntax()\n{\n SYNTAX(\"pattern\");\n\n any_ = DEFINE(\"Any\", CHAR('#'));\n gap_ = DEFINE(\"Gap\", CHAR('*'));\n boi_ = DEFINE(\"Boi\", GLUE(BOI(), CHAR('^')));\n eoi_ = DEFINE(\"Eoi\", GLUE(CHAR('^'), EOI()));\n\n char_ =\n DEFINE(\"Char\",\n CHOICE(\n EXCEPT(\"#*\\\\[](){}|^:\"),\n GLUE(\n CHAR('\\\\'),\n EXPECT(\"Invalid escape sequence\",\n CHOICE(\n RANGE(\n \"#*\\\\[](){}|^:\"\n \"nstrf\"\n ),\n GLUE(\n CHAR('x'),\n REPEAT(2, 2,\n CHOICE(\n RANGE('0', '9'),\n RANGE('a', 'f'),\n RANGE('A', 'F')\n )\n )\n )\n )\n )\n )\n )\n );\n\n string_ =\n DEFINE(\"String\",\n REPEAT(2,\n REF(\"Char\")\n )\n );\n\n rangeMinMax_ =\n DEFINE(\"RangeMinMax\",\n GLUE(\n CHAR('['),\n CHOICE(\n GLUE(\n REPEAT(0, 1, CHAR('^')),\n CHOICE(\n GLUE(\n STRING(\"..\"),\n REF(\"Char\")\n ),\n GLUE(\n REF(\"Char\"),\n STRING(\"..\"),\n REF(\"Char\")\n ),\n GLUE(\n REF(\"Char\"),\n STRING(\"..\")\n )\n )\n ),\n STRING(\"..\")\n ),\n EXPECT(\"Expected closing ']'\",\n CHAR(']')\n )\n )\n );\n\n rangeExplicit_ =\n DEFINE(\"RangeExplicit\",\n GLUE(\n CHAR('['),\n REPEAT(0, 1, CHAR('^')),\n REPEAT(1, REF(\"Char\")),\n EXPECT(\"Expected closing ']'\",\n CHAR(']')\n )\n )\n );\n\n DEFINE(\"Range\",\n GLUE(\n AHEAD(CHAR('[')),\n EXPECT(\"Expected range definition\",\n CHOICE(\n REF(\"RangeMinMax\"),\n REF(\"RangeExplicit\")\n )\n )\n )\n );\n\n DEFINE(\"Number\",\n REPEAT(1, 20,\n RANGE('0', '9')\n )\n );\n\n minRepeat_ = DEFINE(\"MinRepeat\", INLINE(\"Number\"));\n maxRepeat_ = DEFINE(\"MaxRepeat\", INLINE(\"Number\"));\n\n repeat_ =\n DEFINE(\"Repeat\",\n GLUE(\n CHAR('{'),\n REPEAT(0, 1, RANGE(\"<~>\")),\n REPEAT(0, 1,\n GLUE(\n REPEAT(0, 1, REF(\"MinRepeat\")),\n STRING(\"..\"),\n REPEAT(0, 1, REF(\"MaxRepeat\")),\n EXPECT(\"Expected ':' after repeat counts\",\n CHAR(':')\n )\n )\n ),\n EXPECT(\"Expected repeat expression\",\n REF(\"Choice\")\n ),\n EXPECT(\"Expected closing '}'\",\n CHAR('}')\n )\n )\n );\n\n sequence_ =\n DEFINE(\"Sequence\",\n REPEAT(\n CHOICE(\n REF(\"Repeat\"),\n REF(\"String\"),\n REF(\"Char\"),\n REF(\"Any\"),\n REF(\"Gap\"),\n INLINE(\"Range\"),\n REF(\"Boi\"),\n REF(\"Eoi\"),\n REF(\"Group\"),\n REF(\"Behind\"),\n REF(\"Ahead\"),\n REF(\"Capture\"),\n REF(\"Replay\")\n )\n )\n );\n\n group_ =\n DEFINE(\"Group\",\n GLUE(\n CHAR('('),\n NOT(AHEAD(CHAR('?'))),\n REF(\"Choice\"),\n EXPECT(\"Expected closing ')'\",\n CHAR(')')\n )\n )\n );\n\n ahead_ =\n DEFINE(\"Ahead\",\n GLUE(\n STRING(\"(?>\"),\n REPEAT(0, 1, CHAR('!')),\n REPEAT(0, 1, CHAR(':')),\n EXPECT(\"Expected ahead expression\",\n REF(\"Choice\")\n ),\n EXPECT(\"Expected closing ')'\",\n CHAR(')')\n )\n )\n );\n\n behind_ =\n DEFINE(\"Behind\",\n GLUE(\n STRING(\"(?<\"),\n REPEAT(0, 1, CHAR('!')),\n REPEAT(0, 1, CHAR(':')),\n EXPECT(\"Expected behind expression\",\n REF(\"Choice\")\n ),\n EXPECT(\"Expected closing ')'\",\n CHAR(')')\n )\n )\n );\n\n identifier_ =\n DEFINE(\"CaptureIdentifier\",\n REPEAT(\n CHOICE(\n RANGE('a', 'z'),\n RANGE('A', 'Z'),\n RANGE('0', '9'),\n CHAR('_')\n )\n )\n );\n\n capture_ =\n DEFINE(\"Capture\",\n GLUE(\n STRING(\"(?@\"),\n REF(\"CaptureIdentifier\"),\n REPEAT(0, 1, CHAR(':')),\n EXPECT(\"Expected capture expression\",\n REF(\"Choice\")\n ),\n EXPECT(\"Expected closing ')'\",\n CHAR(')')\n )\n )\n );\n\n replay_ =\n DEFINE(\"Replay\",\n GLUE(\n STRING(\"(?=\"),\n REF(\"CaptureIdentifier\"),\n EXPECT(\"Expected closing ')'\",\n CHAR(')')\n )\n )\n );\n\n choice_ =\n DEFINE(\"Choice\",\n GLUE(\n REF(\"Sequence\"),\n REPEAT(\n GLUE(\n CHAR('|'),\n REF(\"Sequence\")\n )\n )\n )\n );\n\n pattern_ =\n DEFINE(\"Pattern\",\n GLUE(\n REF(\"Choice\"),\n EOI()\n )\n );\n\n ENTRY(\"Pattern\");\n LINK();\n}\n\nvoid PatternSyntax::compile(const ByteArray *text, SyntaxDefinition *definition) const\n{\n Ref<SyntaxState> state = match(text);\n if (!state->valid()) throw SyntaxError(text, state);\n NODE entry;\n if (text->count() == 0) entry = definition->PASS();\n else entry = compileChoice(text, state->rootToken()->firstChild(), definition);\n definition->DEFINE(\"Expression\", entry);\n definition->ENTRY(\"Expression\");\n definition->LINK();\n}\n\nNODE PatternSyntax::compileChoice(const ByteArray *text, Token *token, SyntaxDefinition *definition) const\n{\n if (token->countChildren() == 1)\n return compileSequence(text, token->firstChild(), definition);\n NODE node = new syntax::LazyChoiceNode;\n for (Token *child = token->firstChild(); child; child = child->nextSibling())\n node->appendChild(compileSequence(text, child, definition));\n return definition->debug(node, \"Choice\");\n}\n\nNODE PatternSyntax::compileSequence(const ByteArray *text, Token *token, SyntaxDefinition *definition) const\n{\n NODE node = new syntax::GlueNode;\n for (Token *child = token->firstChild(); child; child = child->nextSibling()) {\n if (child->rule() == string_) node->appendChild(definition->STRING(readString(text, child)));\n else if (child->rule() == char_) node->appendChild(definition->CHAR(readChar(text, child)));\n else if (child->rule() == any_) node->appendChild(definition->ANY());\n else if (child->rule() == gap_) node->appendChild(definition->GREEDY_REPEAT(definition->ANY()));\n else if (child->rule() == rangeMinMax_) node->appendChild(compileRangeMinMax(text, child, definition));\n else if (child->rule() == rangeExplicit_) node->appendChild(compileRangeExplicit(text, child, definition));\n else if (child->rule() == repeat_) { node->appendChild(compileRepeat(text, child, definition)); }\n else if (child->rule() == boi_) node->appendChild(definition->BOI());\n else if (child->rule() == eoi_) node->appendChild(definition->EOI());\n else if (child->rule() == group_) node->appendChild(compileChoice(text, child->firstChild(), definition));\n else if (child->rule() == ahead_) node->appendChild(compileAhead(text, child, definition));\n else if (child->rule() == behind_) node->appendChild(compileBehind(text, child, definition));\n else if (child->rule() == capture_) node->appendChild(compileCapture(text, child, definition));\n else if (child->rule() == replay_) node->appendChild(compileReference(text, child, definition));\n }\n if (node->firstChild() == node->lastChild()) {\n NODE child = node->firstChild();\n child->unlink();\n return child;\n }\n return definition->debug(node, \"Glue\");\n}\n\nNODE PatternSyntax::compileAhead(const ByteArray *text, Token *token, SyntaxDefinition *definition) const\n{\n return (text->at(token->i0() + 3) != '!') ?\n definition->AHEAD(compileChoice(text, token->firstChild(), definition)) :\n definition->NOT(compileChoice(text, token->firstChild(), definition));\n}\n\nNODE PatternSyntax::compileBehind(const ByteArray *text, Token *token, SyntaxDefinition *definition) const\n{\n return (text->at(token->i0() + 3) != '!') ?\n definition->BEHIND(compileChoice(text, token->firstChild(), definition)) :\n definition->NOT_BEHIND(compileChoice(text, token->firstChild(), definition));\n}\n\nNODE PatternSyntax::compileCapture(const ByteArray *text, Token *token, SyntaxDefinition *definition) const\n{\n String name = text->copy(token->firstChild());\n return definition->CAPTURE(name, compileChoice(text, token->lastChild(), definition));\n}\n\nNODE PatternSyntax::compileReference(const ByteArray *text, Token *token, SyntaxDefinition *definition) const\n{\n String name = text->copy(token->firstChild());\n return definition->REPLAY(name);\n}\n\nchar PatternSyntax::readChar(const ByteArray *text, Token *token) const\n{\n return (token->i1() - token->i0() > 1) ?\n text->copy(token)->unescapeInsitu()->at(0) :\n text->at(token->i0());\n}\n\nString PatternSyntax::readString(const ByteArray *text, Token *token) const\n{\n String s(token->countChildren());\n int i = 0;\n for (Token *child = token->firstChild(); child; child = child->nextSibling())\n s->at(i++) = readChar(text, child);\n return s;\n}\n\nNODE PatternSyntax::compileRangeMinMax(const ByteArray *text, Token *token, SyntaxDefinition *definition) const\n{\n int n = token->countChildren();\n bool invert = (text->at(token->i0() + 1) == '^');\n if (n == 2) {\n Token *min = token->firstChild();\n Token *max = min->nextSibling();\n char a = readChar(text, min);\n char b = readChar(text, max);\n return invert ? definition->EXCEPT(a, b) : definition->RANGE(a, b);\n }\n else if (n == 1) {\n Token *child = token->firstChild();\n char ch = readChar(text, child);\n return invert ?\n ( (child->i0() - token->i0() <= 2) ? definition->BELOW(ch) : definition->GREATER(ch) ) :\n ( (child->i0() - token->i0() <= 2) ? definition->GREATER_OR_EQUAL(ch) : definition->BELOW_OR_EQUAL(ch) );\n }\n return definition->ANY();\n}\n\nNODE PatternSyntax::compileRangeExplicit(const ByteArray *text, Token *token, SyntaxDefinition *definition) const\n{\n Token *child = token->firstChild();\n bool invert = (text->at(token->i0() + 1) == '^');\n int n = token->countChildren();\n String s(n);\n for (int i = 0; i < n; ++i) {\n s->at(i) = readChar(text, child);\n child = child->nextSibling();\n }\n return invert ? definition->EXCEPT(s) : definition->RANGE(s);\n}\n\nNODE PatternSyntax::compileRepeat(const ByteArray *text, Token *token, SyntaxDefinition *definition) const\n{\n Token *child = token->firstChild(), *min = 0, *max = 0;\n while (child) {\n if (child->rule() == minRepeat_) min = child;\n else if (child->rule() == maxRepeat_) max = child;\n child = child->nextSibling();\n }\n int minRepeat = min ? text->copy(min)->toInt() : 0;\n int maxRepeat = max ? text->copy(max)->toInt() : intMax;\n char modifier = text->at(token->i0() + 1);\n NODE node = compileChoice(text, token->lastChild(), definition);\n if (modifier == '<')\n return definition->LAZY_REPEAT(minRepeat, node);\n else if (modifier == '~')\n return definition->REPEAT(minRepeat, maxRepeat, node);\n \/\/ else if (modifier == '>');\n return definition->GREEDY_REPEAT(minRepeat, maxRepeat, node);\n}\n\nconst PatternSyntax *patternSyntax() { return Singleton<PatternSyntax>::instance(); }\n\n} \/\/ namespace flux\n<commit_msg>Fix: Pattern: compilation of empty name captures<commit_after>\/*\n * Copyright (C) 2007-2014 Frank Mertens.\n *\n * Use of this source is governed by a BSD-style license that can be\n * found in the LICENSE file.\n *\n *\/\n\n#include <flux\/Singleton>\n#ifndef NDEBUG\n#include <flux\/SyntaxDebugger>\n#endif\n#include <flux\/syntax>\n#include <flux\/Format>\n#include <flux\/Pattern>\n#include <flux\/PatternSyntax>\n\nnamespace flux {\n\ntypedef syntax::NODE NODE;\n\nPatternSyntax::PatternSyntax()\n{\n SYNTAX(\"pattern\");\n\n any_ = DEFINE(\"Any\", CHAR('#'));\n gap_ = DEFINE(\"Gap\", CHAR('*'));\n boi_ = DEFINE(\"Boi\", GLUE(BOI(), CHAR('^')));\n eoi_ = DEFINE(\"Eoi\", GLUE(CHAR('^'), EOI()));\n\n char_ =\n DEFINE(\"Char\",\n CHOICE(\n EXCEPT(\"#*\\\\[](){}|^:\"),\n GLUE(\n CHAR('\\\\'),\n EXPECT(\"Invalid escape sequence\",\n CHOICE(\n RANGE(\n \"#*\\\\[](){}|^:\"\n \"nstrf\"\n ),\n GLUE(\n CHAR('x'),\n REPEAT(2, 2,\n CHOICE(\n RANGE('0', '9'),\n RANGE('a', 'f'),\n RANGE('A', 'F')\n )\n )\n )\n )\n )\n )\n )\n );\n\n string_ =\n DEFINE(\"String\",\n REPEAT(2,\n REF(\"Char\")\n )\n );\n\n rangeMinMax_ =\n DEFINE(\"RangeMinMax\",\n GLUE(\n CHAR('['),\n CHOICE(\n GLUE(\n REPEAT(0, 1, CHAR('^')),\n CHOICE(\n GLUE(\n STRING(\"..\"),\n REF(\"Char\")\n ),\n GLUE(\n REF(\"Char\"),\n STRING(\"..\"),\n REF(\"Char\")\n ),\n GLUE(\n REF(\"Char\"),\n STRING(\"..\")\n )\n )\n ),\n STRING(\"..\")\n ),\n EXPECT(\"Expected closing ']'\",\n CHAR(']')\n )\n )\n );\n\n rangeExplicit_ =\n DEFINE(\"RangeExplicit\",\n GLUE(\n CHAR('['),\n REPEAT(0, 1, CHAR('^')),\n REPEAT(1, REF(\"Char\")),\n EXPECT(\"Expected closing ']'\",\n CHAR(']')\n )\n )\n );\n\n DEFINE(\"Range\",\n GLUE(\n AHEAD(CHAR('[')),\n EXPECT(\"Expected range definition\",\n CHOICE(\n REF(\"RangeMinMax\"),\n REF(\"RangeExplicit\")\n )\n )\n )\n );\n\n DEFINE(\"Number\",\n REPEAT(1, 20,\n RANGE('0', '9')\n )\n );\n\n minRepeat_ = DEFINE(\"MinRepeat\", INLINE(\"Number\"));\n maxRepeat_ = DEFINE(\"MaxRepeat\", INLINE(\"Number\"));\n\n repeat_ =\n DEFINE(\"Repeat\",\n GLUE(\n CHAR('{'),\n REPEAT(0, 1, RANGE(\"<~>\")),\n REPEAT(0, 1,\n GLUE(\n REPEAT(0, 1, REF(\"MinRepeat\")),\n STRING(\"..\"),\n REPEAT(0, 1, REF(\"MaxRepeat\")),\n EXPECT(\"Expected ':' after repeat counts\",\n CHAR(':')\n )\n )\n ),\n EXPECT(\"Expected repeat expression\",\n REF(\"Choice\")\n ),\n EXPECT(\"Expected closing '}'\",\n CHAR('}')\n )\n )\n );\n\n sequence_ =\n DEFINE(\"Sequence\",\n REPEAT(\n CHOICE(\n REF(\"Repeat\"),\n REF(\"String\"),\n REF(\"Char\"),\n REF(\"Any\"),\n REF(\"Gap\"),\n INLINE(\"Range\"),\n REF(\"Boi\"),\n REF(\"Eoi\"),\n REF(\"Group\"),\n REF(\"Behind\"),\n REF(\"Ahead\"),\n REF(\"Capture\"),\n REF(\"Replay\")\n )\n )\n );\n\n group_ =\n DEFINE(\"Group\",\n GLUE(\n CHAR('('),\n NOT(CHAR('?')),\n REF(\"Choice\"),\n EXPECT(\"Expected closing ')'\",\n CHAR(')')\n )\n )\n );\n\n ahead_ =\n DEFINE(\"Ahead\",\n GLUE(\n STRING(\"(?>\"),\n REPEAT(0, 1, CHAR('!')),\n REPEAT(0, 1, CHAR(':')),\n EXPECT(\"Expected ahead expression\",\n REF(\"Choice\")\n ),\n EXPECT(\"Expected closing ')'\",\n CHAR(')')\n )\n )\n );\n\n behind_ =\n DEFINE(\"Behind\",\n GLUE(\n STRING(\"(?<\"),\n REPEAT(0, 1, CHAR('!')),\n REPEAT(0, 1, CHAR(':')),\n EXPECT(\"Expected behind expression\",\n REF(\"Choice\")\n ),\n EXPECT(\"Expected closing ')'\",\n CHAR(')')\n )\n )\n );\n\n identifier_ =\n DEFINE(\"CaptureIdentifier\",\n REPEAT(\n CHOICE(\n RANGE('a', 'z'),\n RANGE('A', 'Z'),\n RANGE('0', '9'),\n CHAR('_')\n )\n )\n );\n\n capture_ =\n DEFINE(\"Capture\",\n GLUE(\n STRING(\"(?@\"),\n REPEAT(0, 1,\n GLUE(\n REF(\"CaptureIdentifier\"),\n CHAR(':')\n )\n ),\n EXPECT(\"Expected capture expression\",\n LENGTH(1,\n REF(\"Choice\")\n )\n ),\n EXPECT(\"Expected closing ')'\",\n CHAR(')')\n )\n )\n );\n\n replay_ =\n DEFINE(\"Replay\",\n GLUE(\n STRING(\"(?=\"),\n REF(\"CaptureIdentifier\"),\n EXPECT(\"Expected closing ')'\",\n CHAR(')')\n )\n )\n );\n\n choice_ =\n DEFINE(\"Choice\",\n GLUE(\n REF(\"Sequence\"),\n REPEAT(\n GLUE(\n CHAR('|'),\n REF(\"Sequence\")\n )\n )\n )\n );\n\n pattern_ =\n DEFINE(\"Pattern\",\n GLUE(\n REF(\"Choice\"),\n EOI()\n )\n );\n\n ENTRY(\"Pattern\");\n LINK();\n}\n\nvoid PatternSyntax::compile(const ByteArray *text, SyntaxDefinition *definition) const\n{\n Ref<SyntaxState> state = match(text);\n if (!state->valid()) throw SyntaxError(text, state);\n NODE entry;\n if (text->count() == 0) entry = definition->PASS();\n else entry = compileChoice(text, state->rootToken()->firstChild(), definition);\n definition->DEFINE(\"Expression\", entry);\n definition->ENTRY(\"Expression\");\n definition->LINK();\n}\n\nNODE PatternSyntax::compileChoice(const ByteArray *text, Token *token, SyntaxDefinition *definition) const\n{\n if (token->countChildren() == 1)\n return compileSequence(text, token->firstChild(), definition);\n NODE node = new syntax::LazyChoiceNode;\n for (Token *child = token->firstChild(); child; child = child->nextSibling())\n node->appendChild(compileSequence(text, child, definition));\n return definition->debug(node, \"Choice\");\n}\n\nNODE PatternSyntax::compileSequence(const ByteArray *text, Token *token, SyntaxDefinition *definition) const\n{\n NODE node = new syntax::GlueNode;\n for (Token *child = token->firstChild(); child; child = child->nextSibling()) {\n if (child->rule() == string_) node->appendChild(definition->STRING(readString(text, child)));\n else if (child->rule() == char_) node->appendChild(definition->CHAR(readChar(text, child)));\n else if (child->rule() == any_) node->appendChild(definition->ANY());\n else if (child->rule() == gap_) node->appendChild(definition->GREEDY_REPEAT(definition->ANY()));\n else if (child->rule() == rangeMinMax_) node->appendChild(compileRangeMinMax(text, child, definition));\n else if (child->rule() == rangeExplicit_) node->appendChild(compileRangeExplicit(text, child, definition));\n else if (child->rule() == repeat_) { node->appendChild(compileRepeat(text, child, definition)); }\n else if (child->rule() == boi_) node->appendChild(definition->BOI());\n else if (child->rule() == eoi_) node->appendChild(definition->EOI());\n else if (child->rule() == group_) node->appendChild(compileChoice(text, child->firstChild(), definition));\n else if (child->rule() == ahead_) node->appendChild(compileAhead(text, child, definition));\n else if (child->rule() == behind_) node->appendChild(compileBehind(text, child, definition));\n else if (child->rule() == capture_) node->appendChild(compileCapture(text, child, definition));\n else if (child->rule() == replay_) node->appendChild(compileReference(text, child, definition));\n }\n if (node->firstChild() == node->lastChild()) {\n NODE child = node->firstChild();\n child->unlink();\n return child;\n }\n return definition->debug(node, \"Glue\");\n}\n\nNODE PatternSyntax::compileAhead(const ByteArray *text, Token *token, SyntaxDefinition *definition) const\n{\n return (text->at(token->i0() + 3) != '!') ?\n definition->AHEAD(compileChoice(text, token->firstChild(), definition)) :\n definition->NOT(compileChoice(text, token->firstChild(), definition));\n}\n\nNODE PatternSyntax::compileBehind(const ByteArray *text, Token *token, SyntaxDefinition *definition) const\n{\n return (text->at(token->i0() + 3) != '!') ?\n definition->BEHIND(compileChoice(text, token->firstChild(), definition)) :\n definition->NOT_BEHIND(compileChoice(text, token->firstChild(), definition));\n}\n\nNODE PatternSyntax::compileCapture(const ByteArray *text, Token *token, SyntaxDefinition *definition) const\n{\n String name;\n if (token->firstChild() != token->lastChild())\n name = text->copy(token->firstChild());\n return definition->CAPTURE(name, compileChoice(text, token->lastChild(), definition));\n}\n\nNODE PatternSyntax::compileReference(const ByteArray *text, Token *token, SyntaxDefinition *definition) const\n{\n String name = text->copy(token->firstChild());\n return definition->REPLAY(name);\n}\n\nchar PatternSyntax::readChar(const ByteArray *text, Token *token) const\n{\n return (token->i1() - token->i0() > 1) ?\n text->copy(token)->unescapeInsitu()->at(0) :\n text->at(token->i0());\n}\n\nString PatternSyntax::readString(const ByteArray *text, Token *token) const\n{\n String s(token->countChildren());\n int i = 0;\n for (Token *child = token->firstChild(); child; child = child->nextSibling())\n s->at(i++) = readChar(text, child);\n return s;\n}\n\nNODE PatternSyntax::compileRangeMinMax(const ByteArray *text, Token *token, SyntaxDefinition *definition) const\n{\n int n = token->countChildren();\n bool invert = (text->at(token->i0() + 1) == '^');\n if (n == 2) {\n Token *min = token->firstChild();\n Token *max = min->nextSibling();\n char a = readChar(text, min);\n char b = readChar(text, max);\n return invert ? definition->EXCEPT(a, b) : definition->RANGE(a, b);\n }\n else if (n == 1) {\n Token *child = token->firstChild();\n char ch = readChar(text, child);\n return invert ?\n ( (child->i0() - token->i0() <= 2) ? definition->BELOW(ch) : definition->GREATER(ch) ) :\n ( (child->i0() - token->i0() <= 2) ? definition->GREATER_OR_EQUAL(ch) : definition->BELOW_OR_EQUAL(ch) );\n }\n return definition->ANY();\n}\n\nNODE PatternSyntax::compileRangeExplicit(const ByteArray *text, Token *token, SyntaxDefinition *definition) const\n{\n Token *child = token->firstChild();\n bool invert = (text->at(token->i0() + 1) == '^');\n int n = token->countChildren();\n String s(n);\n for (int i = 0; i < n; ++i) {\n s->at(i) = readChar(text, child);\n child = child->nextSibling();\n }\n return invert ? definition->EXCEPT(s) : definition->RANGE(s);\n}\n\nNODE PatternSyntax::compileRepeat(const ByteArray *text, Token *token, SyntaxDefinition *definition) const\n{\n Token *child = token->firstChild(), *min = 0, *max = 0;\n while (child) {\n if (child->rule() == minRepeat_) min = child;\n else if (child->rule() == maxRepeat_) max = child;\n child = child->nextSibling();\n }\n int minRepeat = min ? text->copy(min)->toInt() : 0;\n int maxRepeat = max ? text->copy(max)->toInt() : intMax;\n char modifier = text->at(token->i0() + 1);\n NODE node = compileChoice(text, token->lastChild(), definition);\n if (modifier == '<')\n return definition->LAZY_REPEAT(minRepeat, node);\n else if (modifier == '~')\n return definition->REPEAT(minRepeat, maxRepeat, node);\n \/\/ else if (modifier == '>');\n return definition->GREEDY_REPEAT(minRepeat, maxRepeat, node);\n}\n\nconst PatternSyntax *patternSyntax() { return Singleton<PatternSyntax>::instance(); }\n\n} \/\/ namespace flux\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright(c) Sophist Solutions, Inc. 1990-2011. All rights reserved\n *\/\n#include\t\"..\/..\/StroikaPreComp.h\"\n\n#if\t\tqPlatform_Windows\n\t#include\t<io.h>\n#elif\tqPlatform_POSIX\n\t#include\t<unistd.h>\n#endif\n#include\t<cstdlib>\n\n#include\t\"Socket.h\"\n\n\n\n\nusing\tnamespace\tStroika::Foundation;\nusing\tnamespace\tStroika::Foundation::IO;\nusing\tnamespace\tStroika::Foundation::IO::Network;\n\n\n\nclass\tSocket::Rep_ {\n\tpublic:\n\t\tNativeSocket\tfSD_;\n\tpublic:\n\t\tRep_ ()\n\t\t\t{\n\t\t\t}\n\t\tRep_ (NativeSocket sd)\n\t\t\t: fSD_ (sd)\n\t\t\t{\n\t\t\t}\n\n\tpublic:\n\t\tvoid\tClose ()\n\t\t\t{\n\t\t\t\t#if\t\tqPlatform_Windows\n\t\t\t\t\t::_close (fSD_);\n\t\t\t\t#elif\tqPlatform_POSIX\n\t\t\t\t\t::close (fSD_);\n\t\t\t\t#else\n\t\t\t\t\tAssertNotImplemented ();\n\t\t\t\t#endif\n\t\t\t}\n\tpublic:\n\t\tsize_t\tRead (Byte* buffer, size_t bufSize) override\n\t\t\t{\n\t\t\t\t\/\/ Must do erorr checking and throw exceptions!!!\n\t\t\t\t#if\t\tqPlatform_Windows\n\t\t\t\t\treturn ::_read (fSD_, buffer, bufSize);\n\t\t\t\t#elif\tqPlatform_POSIX\n\t\t\t\t\treturn ::read (fSD_, buffer, bufSize);\n\t\t\t\t#else\n\t\t\t\t\tAssertNotImplemented ();\n\t\t\t\t#endif\n\t\t\t}\n\tpublic:\n\t\tvoid\tWrite (const Byte* buffer, size_t bufSize) override\n\t\t\t{\n\t\t\t\t\/\/ Must do erorr checking and throw exceptions!!!\n\t\t\t\t#if\t\tqPlatform_Windows\n\t\t\t\t\tint\t\tn\t=\t::_write (fSD_, buffer, bufSize);\n\t\t\t\t#elif\tqPlatform_POSIX\n\t\t\t\t\tint\t\tn\t=\t::write (fSD_, buffer, bufSize);\n\t\t\t\t#else\n\t\t\t\t\tAssertNotImplemented ();\n\t\t\t\t#endif\n\t\t\t}\n\tpublic:\n\t\tvoid\tBind (const Socket::BindProperties& bindProperties)\n\t\t\t{\n\t\t\t\/\/\n\t\t\t}\n\n\tpublic:\n\t\tSocket\tAccept ()\n\t\t\t{\n\t\t\t\treturn Socket ();\n\t\t\t}\n\n};\n\n\n\n\n\nSocket::Socket ()\n{\n}\n\nSocket::Socket (const Socket& s)\n{\n}\n\nSocket::Socket (NativeSocket sd)\n{\n}\n\nSocket::~Socket ()\n{\n}\n\nconst Socket& Socket::operator= (const Socket& s)\n{\n\treturn *this;\n}\n\nvoid\tSocket::Bind (const BindProperties& bindProperties)\n{\n\tfRep_->Bind (bindProperties);\n}\n\nSocket\tSocket::Accept ()\n{\n\treturn fRep_->Accept ();\n}\n\nsize_t\tSocket::Read (Byte* buffer, size_t bufSize)\n{\n\treturn fRep_->Read (buffer, bufSize);\n}\n\nvoid\tSocket::Write (const Byte* buffer, size_t bufSize)\n{\n\tfRep_->Write (buffer, bufSize);\n}\n\nvoid\tSocket::Close ()\n{\n\tfRep_->Close ();\n}\n<commit_msg>a little more progress on Socket implementatioatn (bind\/accept first draft)<commit_after>\/*\n * Copyright(c) Sophist Solutions, Inc. 1990-2011. All rights reserved\n *\/\n#include\t\"..\/..\/StroikaPreComp.h\"\n\n#include\t<sys\/types.h>\n\n#if\t\tqPlatform_Windows\n\t#include\t<winsock2.h>\n\t#include\t<ws2tcpip.h>\n\t#include\t<io.h>\n#elif\tqPlatform_POSIX\n\t#include\t<unistd.h>\n\t#include\t<sys\/socket.h>\n#endif\n\n\n\n#include\t<cstdlib>\n\n#include\t\"Socket.h\"\n\n\n\n\nusing\tnamespace\tStroika::Foundation;\nusing\tnamespace\tStroika::Foundation::IO;\nusing\tnamespace\tStroika::Foundation::IO::Network;\n\n\n\nclass\tSocket::Rep_ {\n\tpublic:\n\t\tNativeSocket\tfSD_;\n\tpublic:\n\t\tRep_ ()\n\t\t\t{\n\t\t\t}\n\t\tRep_ (NativeSocket sd)\n\t\t\t: fSD_ (sd)\n\t\t\t{\n\t\t\t}\n\n\tpublic:\n\t\tvoid\tClose ()\n\t\t\t{\n\t\t\t\t#if\t\tqPlatform_Windows\n\t\t\t\t\t::_close (fSD_);\n\t\t\t\t#elif\tqPlatform_POSIX\n\t\t\t\t\t::close (fSD_);\n\t\t\t\t#else\n\t\t\t\t\tAssertNotImplemented ();\n\t\t\t\t#endif\n\t\t\t}\n\tpublic:\n\t\tsize_t\tRead (Byte* buffer, size_t bufSize) override\n\t\t\t{\n\t\t\t\t\/\/ Must do erorr checking and throw exceptions!!!\n\t\t\t\t#if\t\tqPlatform_Windows\n\t\t\t\t\treturn ::_read (fSD_, buffer, bufSize);\n\t\t\t\t#elif\tqPlatform_POSIX\n\t\t\t\t\treturn ::read (fSD_, buffer, bufSize);\n\t\t\t\t#else\n\t\t\t\t\tAssertNotImplemented ();\n\t\t\t\t#endif\n\t\t\t}\n\tpublic:\n\t\tvoid\tWrite (const Byte* buffer, size_t bufSize) override\n\t\t\t{\n\t\t\t\t\/\/ Must do erorr checking and throw exceptions!!!\n\t\t\t\t#if\t\tqPlatform_Windows\n\t\t\t\t\tint\t\tn\t=\t::_write (fSD_, buffer, bufSize);\n\t\t\t\t#elif\tqPlatform_POSIX\n\t\t\t\t\tint\t\tn\t=\t::write (fSD_, buffer, bufSize);\n\t\t\t\t#else\n\t\t\t\t\tAssertNotImplemented ();\n\t\t\t\t#endif\n\t\t\t}\n\tpublic:\n\t\tvoid\tBind (const Socket::BindProperties& bindProperties)\n\t\t\t{\n\t\t\t\taddrinfo hints;\n\t\t\t\taddrinfo* res = nullptr;\n\t\t\t\tmemset ((void*)&hints, 0, sizeof(hints));\n\t\t\t\thints.ai_family = AF_UNSPEC;\n\t\t\t hints.ai_socktype = SOCK_STREAM;\n\t\t\t\thints.ai_flags = AI_PASSIVE;\n\t\t\t\tstring\ttmp\t=\tbindProperties.fHostName.AsUTF8<string> ();\t\/\/ BAD - SB tstring - or??? not sure what...\n\t\t\t\tif (getaddrinfo (tmp.c_str (), nullptr, &hints, &res) < 0) {\n\t\t\t\t\t\/\/ throw\n\t\t\t\t}\n\t\t\t\tfSD_ = socket(AF_INET, SOCK_STREAM, 0);\n\n\t\t\t\tif (::bind (fSD_, res->ai_addr, res->ai_addrlen) < 0) {\n\t\t\t\t\t\/\/ throw\n\t\t\t\t}\n\t\t\t}\n\n\tpublic:\n\t\tSocket\tAccept ()\n\t\t\t{\n\t\t\t\tsockaddr\tpeer;\n\t\t\t\tmemset (&peer, 0, sizeof (peer));\n\n\t\t\t\tint\tsz\t=\tsizeof (peer);\n\t\t\t\tint r = accept(fSD_, &peer, &sz);\n\/\/ must update Socket object so CTOR also takes (optional) sockaddr (for the peer - mostly to answer other quesiutona later)\n\t\t\t\tif (r < 0) {\n\t\t\t\t\t\/\/ throw...\n\t\t\t\t}\n\t\t\t\treturn Socket (r);\n\t\t\t}\n\n};\n\n\n\n\n\nSocket::Socket ()\n{\n}\n\nSocket::Socket (const Socket& s)\n{\n}\n\nSocket::Socket (NativeSocket sd)\n{\n}\n\nSocket::~Socket ()\n{\n}\n\nconst Socket& Socket::operator= (const Socket& s)\n{\n\treturn *this;\n}\n\nvoid\tSocket::Bind (const BindProperties& bindProperties)\n{\n\tfRep_->Bind (bindProperties);\n}\n\nSocket\tSocket::Accept ()\n{\n\treturn fRep_->Accept ();\n}\n\nsize_t\tSocket::Read (Byte* buffer, size_t bufSize)\n{\n\treturn fRep_->Read (buffer, bufSize);\n}\n\nvoid\tSocket::Write (const Byte* buffer, size_t bufSize)\n{\n\tfRep_->Write (buffer, bufSize);\n}\n\nvoid\tSocket::Close ()\n{\n\tfRep_->Close ();\n}\n<|endoftext|>"} {"text":"<commit_before>\/*===================================================================\n\nThe Medical Imaging Interaction Toolkit (MITK)\n\nCopyright (c) German Cancer Research Center,\nDivision of Medical and Biological Informatics.\nAll rights reserved.\n\nThis software is distributed WITHOUT ANY WARRANTY; without\neven the implied warranty of MERCHANTABILITY or FITNESS FOR\nA PARTICULAR PURPOSE.\n\nSee LICENSE.txt or http:\/\/www.mitk.org for details.\n\n===================================================================*\/\n\n#include \"mitkTestingMacros.h\"\n#include <mitkTestingConfig.h>\n#include <mitkTestFixture.h>\n\n#include <mitkIOUtil.h>\n#include <mitkInteractionTestHelper.h>\n#include <mitkStandaloneDataStorage.h>\n#include <mitkToolManager.h>\n#include <mitkGlobalInteraction.h>\n#include <mitkDataNode.h>\n\n\nclass mitkToolInteractionTestSuite : public mitk::TestFixture\n{\n\n CPPUNIT_TEST_SUITE(mitkToolInteractionTestSuite);\n MITK_TEST(AddToolInteractionTest);\n MITK_TEST(AddToolInteraction_4D_Test);\n CPPUNIT_TEST_SUITE_END();\n\n\nprivate:\n\/\/ mitk::DataNode::Pointer testPointSetNode;\n mitk::InteractionTestHelper::Pointer m_InteractionTestHelper;\n mitk::DataStorage* m_DataStorage;\n mitk::ToolManager::Pointer m_ToolManager;\n\npublic:\n\n int GetToolIDFromToolName (const std::string& toolName)\n {\n \/\/find tool from toolname\n int numberOfTools = m_ToolManager->GetTools().size();\n int toolId = 0;\n for(; toolId < numberOfTools; ++toolId)\n {\n mitk::Tool* currentTool = m_ToolManager->GetToolById(toolId);\n if(toolName.compare( currentTool->GetNameOfClass() ) == 0)\n {\n return toolId;\n }\n }\n return -1;\n }\n\n void RunTestWithParameters(const std::string& patientImagePath,\n const std::string& referenceSegmentationImage,\n const std::string& toolName,\n const std::string& interactionPattern)\n {\n \/\/Create test helper to initialize all necessary objects for interaction\n m_InteractionTestHelper = mitk::InteractionTestHelper::New(GetTestDataFilePath(interactionPattern));\n\n \/\/Use data storage of test helper\n m_DataStorage = m_InteractionTestHelper->GetDataStorage().GetPointer();\n\n \/\/create ToolManager\n m_ToolManager = mitk::ToolManager::New(m_DataStorage);\n m_ToolManager->InitializeTools();\n m_ToolManager->RegisterClient();\/\/This is needed because there must be at least one registered. Otherwise tools can't be activated.\n\n \/\/Load patient image\n mitk::Image::Pointer patientImage = mitk::IOUtil::LoadImage(GetTestDataFilePath(patientImagePath));\n CPPUNIT_ASSERT(patientImage.IsNotNull());\n mitk::DataNode::Pointer patientImageNode = mitk::DataNode::New();\n patientImageNode->SetData(patientImage);\n\n \/\/Activate tool to work with\n int toolID = GetToolIDFromToolName(toolName);\n mitk::Tool* tool = m_ToolManager->GetToolById(toolID);\n\n CPPUNIT_ASSERT(tool != NULL);\n\n \/\/Create empty segmentation working image\n mitk::DataNode::Pointer workingImageNode = mitk::DataNode::New();\n const std::string organName = \"test\";\n mitk::Color color;\/\/actually it dosn't matter which color we are using\n color.SetRed(1); \/\/but CreateEmptySegmentationNode expects a color parameter\n color.SetGreen(0);\n color.SetBlue(0);\n workingImageNode = tool->CreateEmptySegmentationNode(patientImage, organName, color);\n\n CPPUNIT_ASSERT(workingImageNode.IsNotNull());\n CPPUNIT_ASSERT(workingImageNode->GetData() != NULL);\n\n \/\/add images to datastorage\n m_InteractionTestHelper->AddNodeToStorage(patientImageNode);\n m_InteractionTestHelper->AddNodeToStorage(workingImageNode);\n\n \/\/set reference and working image\n m_ToolManager->SetWorkingData(workingImageNode);\n m_ToolManager->SetReferenceData(patientImageNode);\n\n \/\/load interaction events\n m_ToolManager->ActivateTool(toolID);\n\n CPPUNIT_ASSERT(m_ToolManager->GetActiveTool() != NULL);\n\n \/\/Start Interaction\n m_InteractionTestHelper->PlaybackInteraction();\n\n \/\/load reference segmentation image\n mitk::Image::Pointer segmentationReferenceImage = mitk::IOUtil::LoadImage(GetTestDataFilePath(referenceSegmentationImage));\n mitk::Image* currentSegmentationImage = dynamic_cast<mitk::Image*>(workingImageNode->GetData());\n\n CPPUNIT_ASSERT(currentSegmentationImage != NULL);\n\n \/\/compare reference with interaction result\n MITK_ASSERT_EQUAL(segmentationReferenceImage.GetPointer(), currentSegmentationImage, \"Reference equals interaction result.\" );\n }\n\n void setUp()\n {\n }\n\n void tearDown()\n {\n m_ToolManager->ActivateTool(-1);\n m_ToolManager = NULL;\n m_InteractionTestHelper = NULL;\n }\n\n void AddToolInteractionTest()\n {\n RunTestWithParameters(\"Pic3D.nrrd\", \"Segmentation\/ReferenceSegmentations\/AddTool.nrrd\", \"AddContourTool\", \"Segmentation\/InteractionPatterns\/AddTool.xml\");\n }\n\n void AddToolInteraction_4D_Test()\n {\n m_InteractionTestHelper->SetTimeStep(1);\n RunTestWithParameters(\"US4DCyl.nrrd\", \"Segmentation\/ReferenceSegmentations\/AddTool_4D.nrrd\", \"AddContourTool\", \"Segmentation\/InteractionPatterns\/AddTool_4D.xml\");\n }\n\n};\n\nMITK_TEST_SUITE_REGISTRATION(mitkToolInteraction)\n<commit_msg>Changed test helper.<commit_after>\/*===================================================================\n\nThe Medical Imaging Interaction Toolkit (MITK)\n\nCopyright (c) German Cancer Research Center,\nDivision of Medical and Biological Informatics.\nAll rights reserved.\n\nThis software is distributed WITHOUT ANY WARRANTY; without\neven the implied warranty of MERCHANTABILITY or FITNESS FOR\nA PARTICULAR PURPOSE.\n\nSee LICENSE.txt or http:\/\/www.mitk.org for details.\n\n===================================================================*\/\n\n#include \"mitkTestingMacros.h\"\n#include <mitkTestingConfig.h>\n#include <mitkTestFixture.h>\n\n#include <mitkIOUtil.h>\n#include <mitkInteractionTestHelper.h>\n#include <mitkStandaloneDataStorage.h>\n#include <mitkToolManager.h>\n#include <mitkGlobalInteraction.h>\n#include <mitkDataNode.h>\n\n\nclass mitkToolInteractionTestSuite : public mitk::TestFixture\n{\n\n CPPUNIT_TEST_SUITE(mitkToolInteractionTestSuite);\n MITK_TEST(AddToolInteractionTest);\n MITK_TEST(AddToolInteraction_4D_Test);\n CPPUNIT_TEST_SUITE_END();\n\n\nprivate:\n\n mitk::DataStorage* m_DataStorage;\n mitk::ToolManager::Pointer m_ToolManager;\n\npublic:\n\n int GetToolIDFromToolName (const std::string& toolName)\n {\n \/\/find tool from toolname\n int numberOfTools = m_ToolManager->GetTools().size();\n int toolId = 0;\n for(; toolId < numberOfTools; ++toolId)\n {\n mitk::Tool* currentTool = m_ToolManager->GetToolById(toolId);\n if(toolName.compare( currentTool->GetNameOfClass() ) == 0)\n {\n return toolId;\n }\n }\n return -1;\n }\n\n void RunTestWithParameters(const std::string& patientImagePath,\n const std::string& referenceSegmentationImage,\n const std::string& toolName,\n const std::string& interactionPattern)\n {\n \/\/Create test helper to initialize all necessary objects for interaction\n mitk::InteractionTestHelper m_InteractionTestHelper(GetTestDataFilePath(interactionPattern));\n\n \/\/Use data storage of test helper\n m_DataStorage = m_InteractionTestHelper.GetDataStorage().GetPointer();\n\n \/\/create ToolManager\n m_ToolManager = mitk::ToolManager::New(m_DataStorage);\n m_ToolManager->InitializeTools();\n m_ToolManager->RegisterClient();\/\/This is needed because there must be at least one registered. Otherwise tools can't be activated.\n\n \/\/Load patient image\n mitk::Image::Pointer patientImage = mitk::IOUtil::LoadImage(GetTestDataFilePath(patientImagePath));\n CPPUNIT_ASSERT(patientImage.IsNotNull());\n mitk::DataNode::Pointer patientImageNode = mitk::DataNode::New();\n patientImageNode->SetData(patientImage);\n\n \/\/Activate tool to work with\n int toolID = GetToolIDFromToolName(toolName);\n mitk::Tool* tool = m_ToolManager->GetToolById(toolID);\n\n CPPUNIT_ASSERT(tool != NULL);\n\n \/\/Create empty segmentation working image\n mitk::DataNode::Pointer workingImageNode = mitk::DataNode::New();\n const std::string organName = \"test\";\n mitk::Color color;\/\/actually it dosn't matter which color we are using\n color.SetRed(1); \/\/but CreateEmptySegmentationNode expects a color parameter\n color.SetGreen(0);\n color.SetBlue(0);\n workingImageNode = tool->CreateEmptySegmentationNode(patientImage, organName, color);\n\n CPPUNIT_ASSERT(workingImageNode.IsNotNull());\n CPPUNIT_ASSERT(workingImageNode->GetData() != NULL);\n\n \/\/add images to datastorage\n m_InteractionTestHelper.AddNodeToStorage(patientImageNode);\n m_InteractionTestHelper.AddNodeToStorage(workingImageNode);\n\n \/\/set reference and working image\n m_ToolManager->SetWorkingData(workingImageNode);\n m_ToolManager->SetReferenceData(patientImageNode);\n\n \/\/load interaction events\n m_ToolManager->ActivateTool(toolID);\n\n CPPUNIT_ASSERT(m_ToolManager->GetActiveTool() != NULL);\n\n \/\/Start Interaction\n m_InteractionTestHelper.PlaybackInteraction();\n\n \/\/load reference segmentation image\n mitk::Image::Pointer segmentationReferenceImage = mitk::IOUtil::LoadImage(GetTestDataFilePath(referenceSegmentationImage));\n mitk::Image* currentSegmentationImage = dynamic_cast<mitk::Image*>(workingImageNode->GetData());\n\n CPPUNIT_ASSERT(currentSegmentationImage != NULL);\n\n \/\/compare reference with interaction result\n MITK_ASSERT_EQUAL(segmentationReferenceImage.GetPointer(), currentSegmentationImage, \"Reference equals interaction result.\" );\n }\n\n void setUp()\n {\n }\n\n void tearDown()\n {\n m_ToolManager->ActivateTool(-1);\n m_ToolManager = NULL;\n }\n\n void AddToolInteractionTest()\n {\n RunTestWithParameters(\"Pic3D.nrrd\", \"Segmentation\/ReferenceSegmentations\/AddTool.nrrd\", \"AddContourTool\", \"Segmentation\/InteractionPatterns\/AddTool.xml\");\n }\n\n void AddToolInteraction_4D_Test()\n {\n m_InteractionTestHelper->SetTimeStep(1);\n RunTestWithParameters(\"US4DCyl.nrrd\", \"Segmentation\/ReferenceSegmentations\/AddTool_4D.nrrd\", \"AddContourTool\", \"Segmentation\/InteractionPatterns\/AddTool_4D.xml\");\n }\n\n};\n\nMITK_TEST_SUITE_REGISTRATION(mitkToolInteraction)\n<|endoftext|>"} {"text":"<commit_before>\/**\n * @file Cosa\/Keypad.cpp\n * @version 1.0\n *\n * @section License\n * Copyright (C) 2013-2015, Mikael Patel\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * This file is part of the Arduino Che Cosa project.\n *\/\n\n#include \"Cosa\/Keypad.hh\"\n\nvoid\nKeypad::Key::on_change(uint16_t value)\n{\n uint8_t nr = 0;\n while (value < (uint16_t) pgm_read_word(&m_map[nr])) nr++;\n if (UNLIKELY(nr == m_latest)) return;\n if (nr != 0)\n m_keypad->on_key_down(nr);\n else\n m_keypad->on_key_up(m_latest);\n m_latest = nr;\n}\n\nvoid\nKeypad::run()\n{\n m_key.sample_request(Event::SAMPLE_COMPLETED_TYPE);\n}\n<commit_msg>Fixed power management.<commit_after>\/**\n * @file Cosa\/Keypad.cpp\n * @version 1.0\n *\n * @section License\n * Copyright (C) 2013-2015, Mikael Patel\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * This file is part of the Arduino Che Cosa project.\n *\/\n\n#include \"Cosa\/Keypad.hh\"\n\nvoid\nKeypad::Key::on_change(uint16_t value)\n{\n uint8_t nr = 0;\n while (value < (uint16_t) pgm_read_word(&m_map[nr])) nr++;\n if (UNLIKELY(nr == m_latest)) return;\n if (nr != 0)\n m_keypad->on_key_down(nr);\n else\n m_keypad->on_key_up(m_latest);\n m_latest = nr;\n}\n\nvoid\nKeypad::run()\n{\n m_key.powerup();\n m_key.sample_request(Event::SAMPLE_COMPLETED_TYPE);\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2011, Cornell University\n\/\/ All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright notice,\n\/\/ this list of conditions and the following disclaimer.\n\/\/ * Redistributions in binary form must reproduce the above copyright\n\/\/ notice, this list of conditions and the following disclaimer in the\n\/\/ documentation and\/or other materials provided with the distribution.\n\/\/ * Neither the name of HyperDex nor the names of its contributors may be\n\/\/ used to endorse or promote products derived from this software without\n\/\/ specific prior written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n\/\/ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\/\/ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\/\/ ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\n\/\/ LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n\/\/ CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n\/\/ SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n\/\/ INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n\/\/ CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n\/\/ ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n\/\/ POSSIBILITY OF SUCH DAMAGE.\n\n\/\/ STL\n#include <memory>\n#include <string>\n\n\/\/ po6\n#include <po6\/net\/ipaddr.h>\n#include <po6\/net\/location.h>\n\n\/\/ e\n#include <e\/convert.h>\n#include <e\/timer.h>\n\n\/\/ HyperDex\n#include \"hyperclient\/hyperclient.h\"\n\nconst char* colnames[] = {\"1\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\", \"10\",\n \"11\", \"12\", \"13\", \"14\", \"15\", \"16\", \"17\", \"18\", \"19\",\n \"20\", \"21\", \"22\", \"23\", \"24\", \"25\", \"26\", \"27\", \"28\",\n \"29\", \"30\", \"31\", \"32\"};\n\nstatic int\nusage();\n\nstatic void\nvalidate_search(hyperclient* cl,\n uint32_t num,\n const char* space,\n const struct hyperclient_attribute* eq,\n size_t eq_sz,\n const struct hyperclient_range_query* rn,\n size_t rn_sz,\n const char* type);\n\nint\nmain(int argc, char* argv[])\n{\n if (argc != 5)\n {\n return usage();\n }\n\n const char* ip;\n uint16_t port;\n const char* space = argv[3];\n uint32_t numbers;\n\n try\n {\n ip = argv[1];\n }\n catch (std::invalid_argument& e)\n {\n std::cerr << \"The IP address must be an IPv4 or IPv6 address.\" << std::endl;\n return EXIT_FAILURE;\n }\n\n try\n {\n port = e::convert::to_uint16_t(argv[2]);\n }\n catch (std::domain_error& e)\n {\n std::cerr << \"The port number must be an integer.\" << std::endl;\n return EXIT_FAILURE;\n }\n catch (std::out_of_range& e)\n {\n std::cerr << \"The port number must be suitably small.\" << std::endl;\n return EXIT_FAILURE;\n }\n\n try\n {\n numbers = e::convert::to_uint32_t(argv[4]);\n }\n catch (std::domain_error& e)\n {\n std::cerr << \"The number must be an integer.\" << std::endl;\n return EXIT_FAILURE;\n }\n catch (std::out_of_range& e)\n {\n std::cerr << \"The number must be suitably small.\" << std::endl;\n return EXIT_FAILURE;\n }\n\n try\n {\n hyperclient cl(ip, port);\n\n for (uint32_t num = 0; num < numbers; ++num)\n {\n hyperclient_attribute attrs[32];\n\n for (size_t i = 0; i < 32; ++i)\n {\n attrs[i].attr = colnames[i];\n attrs[i].datatype = HYPERDATATYPE_STRING;\n\n if ((num & (1 << i)))\n {\n attrs[i].value = \"ONE\";\n attrs[i].value_sz = 3;\n }\n else\n {\n attrs[i].value = \"ZERO\";\n attrs[i].value_sz = 4;\n }\n }\n\n uint64_t numle = htole64(num);\n hyperclient_returncode pstatus;\n int64_t pid = cl.put(space, reinterpret_cast<const char*>(&numle),\n sizeof(uint32_t), attrs, 32, &pstatus);\n\n if (pid < 0)\n {\n std::cerr << \"put error \" << pstatus << \" \" << (-1 - pid) << std::endl;\n return EXIT_FAILURE;\n }\n\n hyperclient_returncode lstatus;\n int64_t lid = cl.loop(-1, &lstatus);\n\n if (pid != lid)\n {\n std::cerr << \"loop error \" << pstatus << std::endl;\n return EXIT_FAILURE;\n }\n }\n\n std::cerr << \"Starting searches.\" << std::endl;\n e::stopwatch stopw;\n stopw.start();\n\n for (uint32_t num = 0; num < numbers; ++num)\n {\n hyperclient_attribute attrs[32];\n\n for (size_t i = 0; i < 32; ++i)\n {\n attrs[i].attr = colnames[i];\n attrs[i].datatype = HYPERDATATYPE_STRING;\n\n if ((num & (1 << i)))\n {\n attrs[i].value = \"ONE\";\n attrs[i].value_sz = 3;\n }\n else\n {\n attrs[i].value = \"ZERO\";\n attrs[i].value_sz = 4;\n }\n }\n\n validate_search(&cl, num, space, attrs, 32, NULL, 0, \"equality\");\n\n hyperclient_range_query rn;\n rn.attr = \"num\";\n rn.lower = num;\n rn.upper = num + 1;\n\n validate_search(&cl, num, space, NULL, 0, &rn, 1, \"range\");\n }\n\n std::cerr << \"test took \" << stopw.peek() << \" nanoseconds for \" << numbers << \" searches\" << std::endl;\n }\n catch (po6::error& e)\n {\n std::cerr << \"There was a system error: \" << e.what() << std::endl;\n return EXIT_FAILURE;\n }\n catch (std::runtime_error& e)\n {\n std::cerr << \"There was a runtime error: \" << e.what() << std::endl;\n return EXIT_FAILURE;\n }\n catch (std::bad_alloc& e)\n {\n std::cerr << \"There was a memory allocation error: \" << e.what() << std::endl;\n return EXIT_FAILURE;\n }\n catch (std::exception& e)\n {\n std::cerr << \"There was a generic error: \" << e.what() << std::endl;\n return EXIT_FAILURE;\n }\n\n return EXIT_SUCCESS;\n}\n\nint\nusage()\n{\n std::cerr << \"Usage: binary <coordinator ip> <coordinator port> <space name> <numbers>\\n\"\n << \"This will create <numbers> points whose key is a number [0, <numbers>) and \"\n << \"then perform searches over the bits of the number. The space should have 32 \"\n << \"secondary dimensions so that all bits of a number may be stored.\"\n << std::endl;\n return EXIT_FAILURE;\n}\n\nvoid\nvalidate_search(hyperclient* cl,\n uint32_t num,\n const char* space,\n const struct hyperclient_attribute* eq,\n size_t eq_sz,\n const struct hyperclient_range_query* rn,\n size_t rn_sz,\n const char* type)\n{\n hyperclient_returncode sstatus;\n hyperclient_attribute* attrs;\n size_t attrs_sz;\n int64_t sid = cl->search(space, eq, eq_sz, rn, rn_sz, &sstatus, &attrs, &attrs_sz);\n\n if (sid < 0)\n {\n std::cerr << \"invalid \" << type << \" search returns(\" << sid << \", \" << sstatus << \")\" << std::endl;\n abort();\n }\n\n hyperclient_returncode lstatus;\n int64_t lid = cl->loop(-1, &lstatus);\n\n if (lid < 0)\n {\n std::cerr << type << \" search's loop returns(\" << lid << \", \" << lstatus << \")\" << std::endl;\n abort();\n }\n\n if (lid != sid)\n {\n std::cerr << \"for the \" << type << \" search, the ids do not match \" << sid << \" \" << lid << std::endl;\n abort();\n }\n\n if (sstatus != HYPERCLIENT_SUCCESS)\n {\n std::cerr << \"for the \" << type << \" search, the first loop did not return a result.\" << std::endl;\n abort();\n }\n\n if (attrs_sz != 33)\n {\n std::cerr << \"for the \" << type << \" search, there are not 1+32 attributes\" << std::endl;\n abort();\n }\n\n if (strcmp(attrs[0].attr, \"num\") != 0)\n {\n std::cerr << \"for the \" << type << \" search, attribute 0 (the key) is not named num\" << std::endl;\n abort();\n }\n\n if (attrs[0].value_sz != sizeof(num)\n || memcmp(&num, attrs[0].value, sizeof(num)))\n {\n std::cerr << \"for the \" << type << \" search, attribute 0 (the key) != \" << num << std::endl;\n abort();\n }\n\n if (memcmp(&num, attrs[0].value, std::min(sizeof(num), attrs[0].value_sz)) != 0)\n {\n std::cerr << \"for the \" << type << \" search, the result's key does not match\" << std::endl;\n abort();\n }\n\n for (size_t i = 0; i < 32; ++i)\n {\n if (strcmp(attrs[i + 1].attr, colnames[i]) != 0)\n {\n std::cerr << \"for the \" << type << \" search, secondary attribute \" << i << \" is not named \" << colnames[i] << std::endl;\n abort();\n }\n\n if ((num & (1 << i))\n && !(attrs[i + 1].value_sz == 3 && memcmp(attrs[i + 1].value, \"ONE\", 3) == 0))\n {\n std::cerr << \"for the \" << type << \" search, secondary attribute \" << i << \" != ONE\" << std::endl;\n abort();\n }\n else if (!(num & (1 << i))\n && !(attrs[i + 1].value_sz == 4 && memcmp(attrs[i + 1].value, \"ZERO\", 4) == 0))\n {\n std::cerr << \"for the \" << type << \" search, secondary attribute \" << i << \" != ZERO\" << std::endl;\n abort();\n }\n }\n\n hyperclient_destroy_attrs(attrs, attrs_sz);\n\n lid = cl->loop(-1, &lstatus);\n\n if (lid < 0)\n {\n std::cerr << type << \" search's 2nd loop returns(\" << lid << \", \" << lstatus << \")\" << std::endl;\n abort();\n }\n\n if (lid != sid)\n {\n std::cerr << \"for the \" << type << \" search's 2nd loop, the ids do not match \" << sid << \" \" << lid << std::endl;\n abort();\n }\n\n if (sstatus != HYPERCLIENT_SEARCHDONE)\n {\n std::cerr << type << \" search's 2nd loop is not a SEARCHDONE message\";\n abort();\n }\n}\n<commit_msg>Don't use non-portable endianness in binary-test.cc<commit_after>\/\/ Copyright (c) 2011, Cornell University\n\/\/ All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright notice,\n\/\/ this list of conditions and the following disclaimer.\n\/\/ * Redistributions in binary form must reproduce the above copyright\n\/\/ notice, this list of conditions and the following disclaimer in the\n\/\/ documentation and\/or other materials provided with the distribution.\n\/\/ * Neither the name of HyperDex nor the names of its contributors may be\n\/\/ used to endorse or promote products derived from this software without\n\/\/ specific prior written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n\/\/ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\/\/ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\/\/ ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\n\/\/ LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n\/\/ CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n\/\/ SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n\/\/ INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n\/\/ CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n\/\/ ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n\/\/ POSSIBILITY OF SUCH DAMAGE.\n\n\/\/ STL\n#include <memory>\n#include <string>\n\n\/\/ po6\n#include <po6\/net\/ipaddr.h>\n#include <po6\/net\/location.h>\n\n\/\/ e\n#include <e\/convert.h>\n#include <e\/endian.h>\n#include <e\/timer.h>\n\n\/\/ HyperDex\n#include \"hyperclient\/hyperclient.h\"\n\nconst char* colnames[] = {\"1\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\", \"10\",\n \"11\", \"12\", \"13\", \"14\", \"15\", \"16\", \"17\", \"18\", \"19\",\n \"20\", \"21\", \"22\", \"23\", \"24\", \"25\", \"26\", \"27\", \"28\",\n \"29\", \"30\", \"31\", \"32\"};\n\nstatic int\nusage();\n\nstatic void\nvalidate_search(hyperclient* cl,\n uint32_t num,\n const char* space,\n const struct hyperclient_attribute* eq,\n size_t eq_sz,\n const struct hyperclient_range_query* rn,\n size_t rn_sz,\n const char* type);\n\nint\nmain(int argc, char* argv[])\n{\n if (argc != 5)\n {\n return usage();\n }\n\n const char* ip;\n uint16_t port;\n const char* space = argv[3];\n uint32_t numbers;\n\n try\n {\n ip = argv[1];\n }\n catch (std::invalid_argument& e)\n {\n std::cerr << \"The IP address must be an IPv4 or IPv6 address.\" << std::endl;\n return EXIT_FAILURE;\n }\n\n try\n {\n port = e::convert::to_uint16_t(argv[2]);\n }\n catch (std::domain_error& e)\n {\n std::cerr << \"The port number must be an integer.\" << std::endl;\n return EXIT_FAILURE;\n }\n catch (std::out_of_range& e)\n {\n std::cerr << \"The port number must be suitably small.\" << std::endl;\n return EXIT_FAILURE;\n }\n\n try\n {\n numbers = e::convert::to_uint32_t(argv[4]);\n }\n catch (std::domain_error& e)\n {\n std::cerr << \"The number must be an integer.\" << std::endl;\n return EXIT_FAILURE;\n }\n catch (std::out_of_range& e)\n {\n std::cerr << \"The number must be suitably small.\" << std::endl;\n return EXIT_FAILURE;\n }\n\n try\n {\n hyperclient cl(ip, port);\n\n for (uint32_t num = 0; num < numbers; ++num)\n {\n hyperclient_attribute attrs[32];\n\n for (size_t i = 0; i < 32; ++i)\n {\n attrs[i].attr = colnames[i];\n attrs[i].datatype = HYPERDATATYPE_STRING;\n\n if ((num & (1 << i)))\n {\n attrs[i].value = \"ONE\";\n attrs[i].value_sz = 3;\n }\n else\n {\n attrs[i].value = \"ZERO\";\n attrs[i].value_sz = 4;\n }\n }\n\n uint8_t bufle[sizeof(uint64_t)];\n e::pack64le(num, bufle);\n hyperclient_returncode pstatus;\n int64_t pid = cl.put(space, reinterpret_cast<const char*>(bufle), sizeof(uint32_t), attrs, 32, &pstatus);\n\n if (pid < 0)\n {\n std::cerr << \"put error \" << pstatus << \" \" << (-1 - pid) << std::endl;\n return EXIT_FAILURE;\n }\n\n hyperclient_returncode lstatus;\n int64_t lid = cl.loop(-1, &lstatus);\n\n if (pid != lid)\n {\n std::cerr << \"loop error \" << pstatus << std::endl;\n return EXIT_FAILURE;\n }\n }\n\n std::cerr << \"Starting searches.\" << std::endl;\n e::stopwatch stopw;\n stopw.start();\n\n for (uint32_t num = 0; num < numbers; ++num)\n {\n hyperclient_attribute attrs[32];\n\n for (size_t i = 0; i < 32; ++i)\n {\n attrs[i].attr = colnames[i];\n attrs[i].datatype = HYPERDATATYPE_STRING;\n\n if ((num & (1 << i)))\n {\n attrs[i].value = \"ONE\";\n attrs[i].value_sz = 3;\n }\n else\n {\n attrs[i].value = \"ZERO\";\n attrs[i].value_sz = 4;\n }\n }\n\n validate_search(&cl, num, space, attrs, 32, NULL, 0, \"equality\");\n\n hyperclient_range_query rn;\n rn.attr = \"num\";\n rn.lower = num;\n rn.upper = num + 1;\n\n validate_search(&cl, num, space, NULL, 0, &rn, 1, \"range\");\n }\n\n std::cerr << \"test took \" << stopw.peek() << \" nanoseconds for \" << numbers << \" searches\" << std::endl;\n }\n catch (po6::error& e)\n {\n std::cerr << \"There was a system error: \" << e.what() << std::endl;\n return EXIT_FAILURE;\n }\n catch (std::runtime_error& e)\n {\n std::cerr << \"There was a runtime error: \" << e.what() << std::endl;\n return EXIT_FAILURE;\n }\n catch (std::bad_alloc& e)\n {\n std::cerr << \"There was a memory allocation error: \" << e.what() << std::endl;\n return EXIT_FAILURE;\n }\n catch (std::exception& e)\n {\n std::cerr << \"There was a generic error: \" << e.what() << std::endl;\n return EXIT_FAILURE;\n }\n\n return EXIT_SUCCESS;\n}\n\nint\nusage()\n{\n std::cerr << \"Usage: binary <coordinator ip> <coordinator port> <space name> <numbers>\\n\"\n << \"This will create <numbers> points whose key is a number [0, <numbers>) and \"\n << \"then perform searches over the bits of the number. The space should have 32 \"\n << \"secondary dimensions so that all bits of a number may be stored.\"\n << std::endl;\n return EXIT_FAILURE;\n}\n\nvoid\nvalidate_search(hyperclient* cl,\n uint32_t num,\n const char* space,\n const struct hyperclient_attribute* eq,\n size_t eq_sz,\n const struct hyperclient_range_query* rn,\n size_t rn_sz,\n const char* type)\n{\n hyperclient_returncode sstatus;\n hyperclient_attribute* attrs;\n size_t attrs_sz;\n int64_t sid = cl->search(space, eq, eq_sz, rn, rn_sz, &sstatus, &attrs, &attrs_sz);\n\n if (sid < 0)\n {\n std::cerr << \"invalid \" << type << \" search returns(\" << sid << \", \" << sstatus << \")\" << std::endl;\n abort();\n }\n\n hyperclient_returncode lstatus;\n int64_t lid = cl->loop(-1, &lstatus);\n\n if (lid < 0)\n {\n std::cerr << type << \" search's loop returns(\" << lid << \", \" << lstatus << \")\" << std::endl;\n abort();\n }\n\n if (lid != sid)\n {\n std::cerr << \"for the \" << type << \" search, the ids do not match \" << sid << \" \" << lid << std::endl;\n abort();\n }\n\n if (sstatus != HYPERCLIENT_SUCCESS)\n {\n std::cerr << \"for the \" << type << \" search, the first loop did not return a result.\" << std::endl;\n abort();\n }\n\n if (attrs_sz != 33)\n {\n std::cerr << \"for the \" << type << \" search, there are not 1+32 attributes\" << std::endl;\n abort();\n }\n\n if (strcmp(attrs[0].attr, \"num\") != 0)\n {\n std::cerr << \"for the \" << type << \" search, attribute 0 (the key) is not named num\" << std::endl;\n abort();\n }\n\n if (attrs[0].value_sz != sizeof(num)\n || memcmp(&num, attrs[0].value, sizeof(num)))\n {\n std::cerr << \"for the \" << type << \" search, attribute 0 (the key) != \" << num << std::endl;\n abort();\n }\n\n if (memcmp(&num, attrs[0].value, std::min(sizeof(num), attrs[0].value_sz)) != 0)\n {\n std::cerr << \"for the \" << type << \" search, the result's key does not match\" << std::endl;\n abort();\n }\n\n for (size_t i = 0; i < 32; ++i)\n {\n if (strcmp(attrs[i + 1].attr, colnames[i]) != 0)\n {\n std::cerr << \"for the \" << type << \" search, secondary attribute \" << i << \" is not named \" << colnames[i] << std::endl;\n abort();\n }\n\n if ((num & (1 << i))\n && !(attrs[i + 1].value_sz == 3 && memcmp(attrs[i + 1].value, \"ONE\", 3) == 0))\n {\n std::cerr << \"for the \" << type << \" search, secondary attribute \" << i << \" != ONE\" << std::endl;\n abort();\n }\n else if (!(num & (1 << i))\n && !(attrs[i + 1].value_sz == 4 && memcmp(attrs[i + 1].value, \"ZERO\", 4) == 0))\n {\n std::cerr << \"for the \" << type << \" search, secondary attribute \" << i << \" != ZERO\" << std::endl;\n abort();\n }\n }\n\n hyperclient_destroy_attrs(attrs, attrs_sz);\n\n lid = cl->loop(-1, &lstatus);\n\n if (lid < 0)\n {\n std::cerr << type << \" search's 2nd loop returns(\" << lid << \", \" << lstatus << \")\" << std::endl;\n abort();\n }\n\n if (lid != sid)\n {\n std::cerr << \"for the \" << type << \" search's 2nd loop, the ids do not match \" << sid << \" \" << lid << std::endl;\n abort();\n }\n\n if (sstatus != HYPERCLIENT_SEARCHDONE)\n {\n std::cerr << type << \" search's 2nd loop is not a SEARCHDONE message\";\n abort();\n }\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"location.h\"\n#include \"world.h\"\n#include \"state.h\"\n#include \"a_star.h\"\n\n#include <iostream>\n\nusing namespace std;\n\nint main(){\n\t\/* Test location class *\/\n\tLocation loc(1, 3);\n\tloc.print();\n\n\t\/* Test world class *\/\n\tint i,j;\n\tMatrix map;\n\tvector<int> tmp;\n\tfor (i = 0; i < 10; i++){\n\t\ttmp.clear();\n\n\t\tfor (j = 0; j < 10; j++) {\n\t\t\ttmp.push_back(EMPTY);\n\t\t}\n\n\t\tmap.push_back(tmp);\n\t}\n\n\tvector<Location> boxes;\n\tvector<Location> targets;\n\tfor (i = 1; i < 5; i++) {\n\t\tboxes.push_back(Location(i,i));\n\t\ttargets.push_back(Location(i+1,i));\n\t\tmap.at(i).at(i) = BOX;\n\t\tmap.at(i+1).at(i) = TARGET;\n\t}\n\n\tmap.at(1).at(5) = ROBOT;\n\n\tWorld world(&map, new Location(1,1), &boxes, &targets);\n\tworld.printWorld();\n\t\/\/world.printConfig();\n\n\tState state(world);\n\tstate.printState(\"Starting\");\n\n\t\/\/AStar astar(state);\n\t\/\/cout << \"Output of AStar::printClosed()\" << endl;\n\t\/\/astar.printClosed();\n\n\t\/\/astar.solve();\n\t\/\/vector<State> solution = astar.solve();\n\t\/\/astar.printSolution();\n\n \tcout << \"Hello World!\" << endl;\n return 1;\n}\n<commit_msg>updated helloworld file<commit_after>#include \"location.h\"\n#include \"world.h\"\n#include \"state.h\"\n#include \"a_star.h\"\n\n#include <iostream>\n\nusing namespace std;\n\nint main(){\n\t\/* Test location class *\/\n\tLocation loc(1, 3);\n\tloc.print();\n\n\t\/* Test world class *\/\n\tint i,j;\n\tMatrix map;\n\tvector<int> tmp;\n\tfor (i = 0; i < 10; i++){\n\t\ttmp.clear();\n\n\t\tfor (j = 0; j < 10; j++) {\n\t\t\ttmp.push_back(EMPTY);\n\t\t}\n\n\t\tmap.push_back(tmp);\n\t}\n\n\tvector<Location> boxes;\n\tvector<Location> targets;\n\tfor (i = 1; i < 5; i++) {\n\t\tboxes.push_back(Location(i,i));\n\t\ttargets.push_back(Location(i+1,i));\n\t\tmap.at(i).at(i) = BOX;\n\t\tmap.at(i+1).at(i) = TARGET;\n\t}\n\n\tmap.at(1).at(5) = ROBOT;\n\n\tWorld world(&map, new Location(1,8), &boxes, &targets);\n\tworld.printWorld();\n\t\/\/world.printConfig();\n\n\tState state(world);\n\tstate.printState(\"Starting\");\n\n\tAStar astar(state);\n\tcout << \"Output of AStar::printClosed()\" << endl;\n\tastar.printClosed();\n\n\tastar.solve();\n\t\/\/vector<State> solution = astar.solve();\n\t\/\/astar.printSolution();\n\n \tcout << \"Hello World!\" << endl;\n return 1;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"darkfeed\/util\/hashing.hpp\"\n#include <gtest\/gtest.h>\n\nusing namespace darkfeed;\n\n\nTEST(CRC32C, SliceBy8Empty)\n{\n const char *empty = \"\";\n unsigned char expected_arr[] = {0x00, 0x00, 0x00, 0x00};\n std::uint32_t crc = CRC32C_FINISH(crc32cSlicingBy8(CRC32C_INIT, empty, 0));\n ASSERT_EQ(*(std::uint32_t *) expected_arr, crc);\n}\n\n\nTEST(CRC32C, SliceBy8Alphabet)\n{\n const char alphabet[] = \"abcdefghijklmnopqrstuvwxyz\";\n unsigned char expected_arr[] = {0x25, 0xef, 0xe6, 0x9e};\n std::uint32_t crc = CRC32C_FINISH(crc32cSlicingBy8(CRC32C_INIT, alphabet, 26));\n ASSERT_EQ(*(std::uint32_t *) expected_arr, crc);\n}\n\n#ifdef HAS_SSE_4_2\n\n\nTEST(CRC32C, IntelEmpty)\n{\n const char *empty = \"\";\n unsigned char expected_arr[] = {0x00, 0x00, 0x00, 0x00};\n std::uint32_t crc = CRC32C_FINISH(crc32cIntelC(CRC32C_INIT, empty, 0));\n ASSERT_EQ(*(std::uint32_t *) expected_arr, crc);\n}\n\n\nTEST(CRC32C, IntelAlphabet)\n{\n const char alphabet[] = \"abcdefghijklmnopqrstuvwxyz\";\n unsigned char expected_arr[] = {0x25, 0xef, 0xe6, 0x9e};\n std::uint32_t crc = CRC32C_FINISH(crc32cIntelC(CRC32C_INIT, alphabet, 26));\n ASSERT_EQ(*(std::uint32_t *) expected_arr, crc);\n}\n#endif\n\n\nTEST(CRC32CCStrHasher, Alphabet)\n{\n const char alphabet[] = \"abcdefghijklmnopqrstuvwxyz\";\n unsigned char expected_arr[] = {0x25, 0xef, 0xe6, 0x9e};\n CRC32CCStrHasher hasher;\n std::uint32_t crc = hasher(alphabet);\n ASSERT_EQ(*(std::uint32_t *) expected_arr, crc);\n}\n\n\nTEST(CRC32CStrHasher, Alphabet)\n{\n std::string alphabet = \"abcdefghijklmnopqrstuvwxyz\";\n unsigned char expected_arr[] = {0x25, 0xef, 0xe6, 0x9e};\n CRC32CStrHasher hasher;\n std::uint32_t crc = hasher(alphabet);\n ASSERT_EQ(*(std::uint32_t *) expected_arr, crc);\n}\n<commit_msg>[cpp] Add test for hardware accelerated (SSE4.3) CRC32C symbol hasher<commit_after>#include \"darkfeed\/util\/hashing.hpp\"\n#include <gtest\/gtest.h>\n\nusing namespace darkfeed;\n\n\nTEST(CRC32C, SliceBy8Empty)\n{\n const char *empty = \"\";\n unsigned char expected_arr[] = {0x00, 0x00, 0x00, 0x00};\n std::uint32_t crc = CRC32C_FINISH(crc32cSlicingBy8(CRC32C_INIT, empty, 0));\n ASSERT_EQ(*(std::uint32_t *) expected_arr, crc);\n}\n\n\nTEST(CRC32C, SliceBy8Alphabet)\n{\n const char alphabet[] = \"abcdefghijklmnopqrstuvwxyz\";\n unsigned char expected_arr[] = {0x25, 0xef, 0xe6, 0x9e};\n std::uint32_t crc = CRC32C_FINISH(crc32cSlicingBy8(CRC32C_INIT, alphabet, 26));\n ASSERT_EQ(*(std::uint32_t *) expected_arr, crc);\n}\n\n#ifdef HAS_SSE_4_2\n\n\nTEST(CRC32C, IntelEmpty)\n{\n const char *empty = \"\";\n unsigned char expected_arr[] = {0x00, 0x00, 0x00, 0x00};\n std::uint32_t crc = CRC32C_FINISH(crc32cIntelC(CRC32C_INIT, empty, 0));\n ASSERT_EQ(*(std::uint32_t *) expected_arr, crc);\n}\n\n\nTEST(CRC32C, IntelAlphabet)\n{\n const char alphabet[] = \"abcdefghijklmnopqrstuvwxyz\";\n unsigned char expected_arr[] = {0x25, 0xef, 0xe6, 0x9e};\n std::uint32_t crc = CRC32C_FINISH(crc32cIntelC(CRC32C_INIT, alphabet, 26));\n ASSERT_EQ(*(std::uint32_t *) expected_arr, crc);\n}\n#endif\n\n\nTEST(CRC32CCStrHasher, Alphabet)\n{\n const char alphabet[] = \"abcdefghijklmnopqrstuvwxyz\";\n unsigned char expected_arr[] = {0x25, 0xef, 0xe6, 0x9e};\n CRC32CCStrHasher hasher;\n std::uint32_t crc = hasher(alphabet);\n ASSERT_EQ(*(std::uint32_t *) expected_arr, crc);\n}\n\n\nTEST(CRC32CStrHasher, Alphabet)\n{\n std::string alphabet = \"abcdefghijklmnopqrstuvwxyz\";\n unsigned char expected_arr[] = {0x25, 0xef, 0xe6, 0x9e};\n CRC32CStrHasher hasher;\n std::uint32_t crc = hasher(alphabet);\n ASSERT_EQ(*(std::uint32_t *) expected_arr, crc);\n}\n\n\nTEST(CRC32CSymHasher, BaseCase)\n{\n Symbol s(MIC::XNYS, \"BRK.PR.A\");\n ASSERT_STREQ(\"BRK\", s.root);\n ASSERT_EQ(IssueType::preferred, s.issue_type);\n ASSERT_EQ('A', s.series);\n CRC32CSymHasher h;\n auto h1 = h(s);\n auto sc = s;\n auto h2 = h(sc);\n ASSERT_EQ(h1, h2);\n Symbol s2(MIC::XNYS, \"BRK.A\");\n ASSERT_STREQ(\"BRK\", s2.root);\n ASSERT_EQ(IssueType::normal, s2.issue_type);\n ASSERT_EQ('A', s2.series);\n auto h3 = h(s2);\n ASSERT_NE(h1, h3);\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\r\n * $Id$\r\n *\r\n * Copyright(C) 1998-2005 Satoshi Nakamura\r\n * All rights reserved.\r\n *\r\n *\/\r\n\r\n#include <qs.h>\r\n#include <qsassert.h>\r\n#include <qsconv.h>\r\n#include <qsstring.h>\r\n#include <qsthread.h>\r\n\r\n#ifndef _WIN32_WCE\r\n#\tinclude <process.h>\r\n#endif\r\n#include <tchar.h>\r\n\r\n#include \"thread.h\"\r\n\r\n#ifdef _WIN32_WCE\r\n#\tdefine UNVOLATILE(type) const_cast<type>\r\n#else\r\n#\tdefine UNVOLATILE(type)\r\n#endif\r\n\r\nusing namespace qs;\r\n\r\n\r\n\/****************************************************************************\r\n *\r\n * Runnable\r\n *\r\n *\/\r\n\r\nqs::Runnable::~Runnable()\r\n{\r\n}\r\n\r\n\r\n\/****************************************************************************\r\n *\r\n * ThreadImpl\r\n *\r\n *\/\r\n\r\nstruct qs::ThreadImpl\r\n{\r\n\tHANDLE hThread_;\r\n\tRunnable* pRunnable_;\r\n};\r\n\r\n\r\n\/****************************************************************************\r\n *\r\n * Thread\r\n *\r\n *\/\r\n\r\nnamespace qs {\r\n#ifdef _WIN32_WCE\r\nDWORD WINAPI threadProc(LPVOID pParam);\r\n#else\r\nunsigned int __stdcall threadProc(void* pParam);\r\n#endif\r\n}\r\n\r\n#ifdef _WIN32_WCE\r\nDWORD WINAPI qs::threadProc(LPVOID pParam)\r\n#else\r\nunsigned int __stdcall qs::threadProc(void* pParam)\r\n#endif\r\n{\r\n\tassert(pParam);\r\n\tRunnable* pRunnable = static_cast<Runnable*>(pParam);\r\n\tpRunnable->run();\r\n\treturn 0;\r\n}\r\n\r\nqs::Thread::Thread() :\r\n\tpImpl_(0)\r\n{\r\n\tinit(this);\r\n}\r\n\r\nqs::Thread::Thread(Runnable* pRunnable) :\r\n\tpImpl_(0)\r\n{\r\n\tinit(pRunnable);\r\n}\r\n\r\nqs::Thread::~Thread()\r\n{\r\n\tif (pImpl_->hThread_)\r\n\t\t::CloseHandle(pImpl_->hThread_);\r\n\tdelete pImpl_;\r\n\tpImpl_ = 0;\r\n}\r\n\r\nbool qs::Thread::start()\r\n{\r\n\tassert(pImpl_);\r\n\t\r\n#ifdef _WIN32_WCE\r\n\tDWORD dwId = 0;\r\n\tpImpl_->hThread_ = ::CreateThread(0, 0, threadProc,\r\n\t\tpImpl_->pRunnable_, 0, &dwId);\r\n#else\r\n\tunsigned int nId = 0;\r\n\tpImpl_->hThread_ = reinterpret_cast<HANDLE>(_beginthreadex(\r\n\t\t0, 0, threadProc, pImpl_->pRunnable_, 0, &nId));\r\n#endif\r\n\treturn pImpl_->hThread_ != 0;\r\n}\r\n\r\nbool qs::Thread::join()\r\n{\r\n\treturn join(0);\r\n}\r\n\r\nbool qs::Thread::join(DWORD dwWait)\r\n{\r\n\tassert(pImpl_);\r\n\t\r\n\tif (!pImpl_->hThread_)\r\n\t\treturn false;\r\n\t\r\n\tif (dwWait == 0)\r\n\t\tdwWait = INFINITE;\r\n\treturn ::WaitForSingleObject(pImpl_->hThread_, dwWait) != WAIT_FAILED;\r\n}\r\n\r\nHANDLE qs::Thread::getHandle() const\r\n{\r\n\tassert(pImpl_);\r\n\treturn pImpl_->hThread_;\r\n}\r\n\r\nvoid qs::Thread::run()\r\n{\r\n\tif (pImpl_->pRunnable_)\r\n\t\tpImpl_->pRunnable_->run();\r\n}\r\n\r\nvoid qs::Thread::init(Runnable* pRunnable)\r\n{\r\n\tassert(!pImpl_);\r\n\t\r\n\tpImpl_ = new ThreadImpl();\r\n\tpImpl_->hThread_ = 0;\r\n\tpImpl_->pRunnable_ = pRunnable;\r\n}\r\n\r\n\r\n\/****************************************************************************\r\n *\r\n * ThreadLocal\r\n *\r\n *\/\r\n\r\nqs::ThreadLocal::ThreadLocal() :\r\n\tdwTls_(0xffffffff)\r\n{\r\n\tdwTls_ = ::TlsAlloc();\r\n}\r\n\r\nqs::ThreadLocal::~ThreadLocal()\r\n{\r\n\t::TlsFree(dwTls_);\r\n}\r\n\r\nvoid* qs::ThreadLocal::get() const\r\n{\r\n\treturn ::TlsGetValue(dwTls_);\r\n}\r\n\r\nvoid qs::ThreadLocal::set(void* pValue)\r\n{\r\n\t::TlsSetValue(dwTls_, pValue);\r\n}\r\n\r\n\r\n\/****************************************************************************\r\n *\r\n * SpinLock\r\n *\r\n *\/\r\n\r\nunsigned int qs::SpinLock::nMax__ = LOW_MAX;\r\nunsigned int qs::SpinLock::nLast__ = 0;\r\n\r\nvoid qs::SpinLock::lock() const\r\n{\r\n\tif (::InterlockedExchange(UNVOLATILE(LONG*)(&nLock_), 1) != 0) {\r\n\t\tunsigned int nSpinMax = nMax__;\r\n\t\tunsigned int nSpinLast = nLast__;\r\n\t\tunsigned int nJunk = 17;\r\n\t\tunsigned int n = 0;\r\n\t\tfor (n = 0; n < nSpinMax; ++n) {\r\n\t\t\tif (n < nSpinLast\/2 || nLock_) {\r\n\t\t\t\tnJunk *= nJunk;\r\n\t\t\t\tnJunk *= nJunk;\r\n\t\t\t\tnJunk *= nJunk;\r\n\t\t\t\tnJunk *= nJunk;\r\n\t\t\t}\r\n\t\t\telse {\r\n\t\t\t\tif (::InterlockedExchange(UNVOLATILE(LONG*)(&nLock_), 1) == 0) {\r\n\t\t\t\t\tnLast__ = n;\r\n\t\t\t\t\tnMax__ = HIGH_MAX;\r\n\t\t\t\t\treturn;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\t\r\n\t\tfor (n = 0; ; ++n) {\r\n\t\t\tint nSec = n + 6;\r\n\t\t\tif (nSec > 27)\r\n\t\t\t\tnSec = 27;\r\n\t\t\tif (::InterlockedExchange(UNVOLATILE(LONG*)(&nLock_), 1) == 0)\r\n\t\t\t\tbreak;\r\n\t\t\t::Sleep(nSec);\r\n\t\t}\r\n\t}\r\n}\r\n\r\n\r\n\/****************************************************************************\r\n *\r\n * ReadWriteLock\r\n *\r\n *\/\r\n\r\nqs::ReadWriteLock::ReadWriteLock() :\r\n\thMutexWrite_(0),\r\n\thEventRead_(0),\r\n\tnReader_(0)\r\n{\r\n\thMutexWrite_ = ::CreateMutex(0, FALSE, 0);\r\n\thEventRead_ = ::CreateEvent(0, TRUE, FALSE, 0);\r\n}\r\n\r\nqs::ReadWriteLock::~ReadWriteLock()\r\n{\r\n\t::CloseHandle(hMutexWrite_);\r\n\t::CloseHandle(hEventRead_);\r\n}\r\n\r\nvoid qs::ReadWriteLock::readLock() const\r\n{\r\n\t::WaitForSingleObject(hMutexWrite_, INFINITE);\r\n\t::InterlockedIncrement(UNVOLATILE(LONG*)(&nReader_));\r\n\t::ResetEvent(hEventRead_);\r\n\t::ReleaseMutex(hMutexWrite_);\r\n}\r\n\r\nvoid qs::ReadWriteLock::writeLock() const\r\n{\r\n\t::WaitForSingleObject(hMutexWrite_, INFINITE);\r\n\tif (::InterlockedCompareExchange(UNVOLATILE(LONG*)(&nReader_), 0, 0) != 0)\r\n\t\t::WaitForSingleObject(hEventRead_, INFINITE);\r\n}\r\n\r\nvoid qs::ReadWriteLock::unlock() const\r\n{\r\n\tif (!::ReleaseMutex(hMutexWrite_) && ::GetLastError() == ERROR_NOT_OWNER) {\r\n\t\tif (::InterlockedDecrement(UNVOLATILE(LONG*)(&nReader_)) == 0)\r\n\t\t\t::SetEvent(hEventRead_);\r\n\t}\r\n}\r\n\r\n\r\n\/****************************************************************************\r\n *\r\n * Event\r\n *\r\n *\/\r\n\r\nqs::Event::Event() :\r\n\thEvent_(0)\r\n{\r\n\thEvent_ = ::CreateEvent(0, FALSE, FALSE, 0);\r\n}\r\n\r\nqs::Event::Event(bool bManual, bool bInitial)\r\n{\r\n\thEvent_ = ::CreateEvent(0, bManual, bInitial, 0);\r\n}\r\n\r\nqs::Event::Event(bool bManual,\r\n\t\t\t\t bool bInitial,\r\n\t\t\t\t const WCHAR* pwszName)\r\n{\r\n\ttstring_ptr tstrName(wcs2tcs(pwszName));\r\n\thEvent_ = ::CreateEvent(0, bManual, bInitial, tstrName.get());\r\n}\r\n\r\nqs::Event::~Event()\r\n{\r\n\tif (hEvent_)\r\n\t\t::CloseHandle(hEvent_);\r\n}\r\n\r\nbool qs::Event::set()\r\n{\r\n\treturn ::SetEvent(hEvent_) != 0;\r\n}\r\n\r\nbool qs::Event::reset()\r\n{\r\n\treturn ::ResetEvent(hEvent_) != 0;\r\n}\r\n\r\nbool qs::Event::pulse()\r\n{\r\n\treturn ::PulseEvent(hEvent_) != 0;\r\n}\r\n\r\nbool qs::Event::wait()\r\n{\r\n\treturn wait(INFINITE);\r\n}\r\n\r\nbool qs::Event::wait(unsigned int nMillisecond)\r\n{\r\n\treturn ::WaitForSingleObject(hEvent_, nMillisecond) != WAIT_FAILED;\r\n}\r\n\r\nHANDLE qs::Event::getHandle() const\r\n{\r\n\treturn hEvent_;\r\n}\r\n\r\n\r\n\/****************************************************************************\r\n *\r\n * Mutex\r\n *\r\n *\/\r\n\r\nqs::Mutex::Mutex() :\r\n\thMutex_(0)\r\n{\r\n\tinit(false, 0);\r\n}\r\n\r\nqs::Mutex::Mutex(bool bOwner) :\r\n\thMutex_(0)\r\n{\r\n\tinit(bOwner, 0);\r\n}\r\n\r\nqs::Mutex::Mutex(bool bOwner,\r\n\t\t\t\t const WCHAR* pwszName) :\r\n\thMutex_(0)\r\n{\r\n\tinit(bOwner, pwszName);\r\n}\r\n\r\nqs::Mutex::~Mutex()\r\n{\r\n\tif (hMutex_)\r\n\t\t::CloseHandle(hMutex_);\r\n}\r\n\r\nbool qs::Mutex::acquire()\r\n{\r\n\tassert(hMutex_);\r\n\treturn ::WaitForSingleObject(hMutex_, INFINITE) != WAIT_FAILED;\r\n}\r\n\r\nbool qs::Mutex::release()\r\n{\r\n\tassert(hMutex_);\r\n\treturn ::ReleaseMutex(hMutex_) != 0;\r\n}\r\n\r\nvoid qs::Mutex::init(bool bOwner,\r\n\t\t\t\t\t const WCHAR* pwszName)\r\n{\r\n\tif (pwszName) {\r\n\t\tW2T(pwszName, ptszName);\r\n\t\thMutex_ = ::CreateMutex(0, bOwner, ptszName);\r\n\t}\r\n\telse {\r\n\t\thMutex_ = ::CreateMutex(0, bOwner, 0);\r\n\t}\r\n}\r\n\r\n\r\n\/****************************************************************************\r\n *\r\n * Synchronizer\r\n *\r\n *\/\r\n\r\nqs::Synchronizer::Synchronizer() :\r\n\tpWindow_(0)\r\n{\r\n\tstd::auto_ptr<SynchronizerWindow> pWindow(new SynchronizerWindow());\r\n\tif (!pWindow->create(L\"QsSynchronizerWindow\", 0, WS_POPUP,\r\n\t\t0, 0, 0, 0, 0, 0, 0, 0, 0))\r\n\t\treturn;\r\n\tpWindow_ = pWindow.release();\r\n}\r\n\r\nqs::Synchronizer::~Synchronizer()\r\n{\r\n\tpWindow_->destroyWindow();\r\n}\r\n\r\nvoid qs::Synchronizer::syncExec(Runnable* pRunnable)\r\n{\r\n\tpWindow_->sendMessage(SynchronizerWindow::WM_SYNCEXEC,\r\n\t\t0, reinterpret_cast<LPARAM>(pRunnable));\r\n}\r\n\r\n\r\n\/****************************************************************************\r\n *\r\n * SynchronizerWindow\r\n *\r\n *\/\r\n\r\nqs::SynchronizerWindow::SynchronizerWindow() :\r\n\tWindowBase(true)\r\n{\r\n\tsetWindowHandler(this, false);\r\n}\r\n\r\nqs::SynchronizerWindow::~SynchronizerWindow()\r\n{\r\n}\r\n\r\nLRESULT qs::SynchronizerWindow::windowProc(UINT uMsg,\r\n\t\t\t\t\t\t\t\t\t\t WPARAM wParam,\r\n\t\t\t\t\t\t\t\t\t\t LPARAM lParam)\r\n{\r\n\tBEGIN_MESSAGE_HANDLER()\r\n\t\tHANDLE_MESSAGE(WM_SYNCEXEC, onSyncExec)\r\n\tEND_MESSAGE_HANDLER()\r\n\treturn DefaultWindowHandler::windowProc(uMsg, wParam, lParam);\r\n}\r\n\r\nLRESULT qs::SynchronizerWindow::onSyncExec(WPARAM wParam,\r\n\t\t\t\t\t\t\t\t\t\t LPARAM lParam)\r\n{\r\n\tRunnable* pRunnable = reinterpret_cast<Runnable*>(lParam);\r\n\tQTRY {\r\n\t\tpRunnable->run();\r\n\t}\r\n\tQCATCH_ALL() {\r\n\t\t;\r\n\t}\r\n\treturn 0;\r\n}\r\n<commit_msg>Fix it cannot compile for Windows CE 3.0 or earlier, because InterlockedCompareExchange is a macro to call via a function pointer on these platforms.<commit_after>\/*\r\n * $Id$\r\n *\r\n * Copyright(C) 1998-2005 Satoshi Nakamura\r\n * All rights reserved.\r\n *\r\n *\/\r\n\r\n#include <qs.h>\r\n#include <qsassert.h>\r\n#include <qsconv.h>\r\n#include <qsstring.h>\r\n#include <qsthread.h>\r\n\r\n#ifndef _WIN32_WCE\r\n#\tinclude <process.h>\r\n#endif\r\n#include <tchar.h>\r\n\r\n#include \"thread.h\"\r\n\r\n#ifdef _WIN32_WCE\r\n#\tdefine UNVOLATILE(type) const_cast<type>\r\n#else\r\n#\tdefine UNVOLATILE(type)\r\n#endif\r\n\r\nusing namespace qs;\r\n\r\n\r\n\/****************************************************************************\r\n *\r\n * Runnable\r\n *\r\n *\/\r\n\r\nqs::Runnable::~Runnable()\r\n{\r\n}\r\n\r\n\r\n\/****************************************************************************\r\n *\r\n * ThreadImpl\r\n *\r\n *\/\r\n\r\nstruct qs::ThreadImpl\r\n{\r\n\tHANDLE hThread_;\r\n\tRunnable* pRunnable_;\r\n};\r\n\r\n\r\n\/****************************************************************************\r\n *\r\n * Thread\r\n *\r\n *\/\r\n\r\nnamespace qs {\r\n#ifdef _WIN32_WCE\r\nDWORD WINAPI threadProc(LPVOID pParam);\r\n#else\r\nunsigned int __stdcall threadProc(void* pParam);\r\n#endif\r\n}\r\n\r\n#ifdef _WIN32_WCE\r\nDWORD WINAPI qs::threadProc(LPVOID pParam)\r\n#else\r\nunsigned int __stdcall qs::threadProc(void* pParam)\r\n#endif\r\n{\r\n\tassert(pParam);\r\n\tRunnable* pRunnable = static_cast<Runnable*>(pParam);\r\n\tpRunnable->run();\r\n\treturn 0;\r\n}\r\n\r\nqs::Thread::Thread() :\r\n\tpImpl_(0)\r\n{\r\n\tinit(this);\r\n}\r\n\r\nqs::Thread::Thread(Runnable* pRunnable) :\r\n\tpImpl_(0)\r\n{\r\n\tinit(pRunnable);\r\n}\r\n\r\nqs::Thread::~Thread()\r\n{\r\n\tif (pImpl_->hThread_)\r\n\t\t::CloseHandle(pImpl_->hThread_);\r\n\tdelete pImpl_;\r\n\tpImpl_ = 0;\r\n}\r\n\r\nbool qs::Thread::start()\r\n{\r\n\tassert(pImpl_);\r\n\t\r\n#ifdef _WIN32_WCE\r\n\tDWORD dwId = 0;\r\n\tpImpl_->hThread_ = ::CreateThread(0, 0, threadProc,\r\n\t\tpImpl_->pRunnable_, 0, &dwId);\r\n#else\r\n\tunsigned int nId = 0;\r\n\tpImpl_->hThread_ = reinterpret_cast<HANDLE>(_beginthreadex(\r\n\t\t0, 0, threadProc, pImpl_->pRunnable_, 0, &nId));\r\n#endif\r\n\treturn pImpl_->hThread_ != 0;\r\n}\r\n\r\nbool qs::Thread::join()\r\n{\r\n\treturn join(0);\r\n}\r\n\r\nbool qs::Thread::join(DWORD dwWait)\r\n{\r\n\tassert(pImpl_);\r\n\t\r\n\tif (!pImpl_->hThread_)\r\n\t\treturn false;\r\n\t\r\n\tif (dwWait == 0)\r\n\t\tdwWait = INFINITE;\r\n\treturn ::WaitForSingleObject(pImpl_->hThread_, dwWait) != WAIT_FAILED;\r\n}\r\n\r\nHANDLE qs::Thread::getHandle() const\r\n{\r\n\tassert(pImpl_);\r\n\treturn pImpl_->hThread_;\r\n}\r\n\r\nvoid qs::Thread::run()\r\n{\r\n\tif (pImpl_->pRunnable_)\r\n\t\tpImpl_->pRunnable_->run();\r\n}\r\n\r\nvoid qs::Thread::init(Runnable* pRunnable)\r\n{\r\n\tassert(!pImpl_);\r\n\t\r\n\tpImpl_ = new ThreadImpl();\r\n\tpImpl_->hThread_ = 0;\r\n\tpImpl_->pRunnable_ = pRunnable;\r\n}\r\n\r\n\r\n\/****************************************************************************\r\n *\r\n * ThreadLocal\r\n *\r\n *\/\r\n\r\nqs::ThreadLocal::ThreadLocal() :\r\n\tdwTls_(0xffffffff)\r\n{\r\n\tdwTls_ = ::TlsAlloc();\r\n}\r\n\r\nqs::ThreadLocal::~ThreadLocal()\r\n{\r\n\t::TlsFree(dwTls_);\r\n}\r\n\r\nvoid* qs::ThreadLocal::get() const\r\n{\r\n\treturn ::TlsGetValue(dwTls_);\r\n}\r\n\r\nvoid qs::ThreadLocal::set(void* pValue)\r\n{\r\n\t::TlsSetValue(dwTls_, pValue);\r\n}\r\n\r\n\r\n\/****************************************************************************\r\n *\r\n * SpinLock\r\n *\r\n *\/\r\n\r\nunsigned int qs::SpinLock::nMax__ = LOW_MAX;\r\nunsigned int qs::SpinLock::nLast__ = 0;\r\n\r\nvoid qs::SpinLock::lock() const\r\n{\r\n\tif (::InterlockedExchange(UNVOLATILE(LONG*)(&nLock_), 1) != 0) {\r\n\t\tunsigned int nSpinMax = nMax__;\r\n\t\tunsigned int nSpinLast = nLast__;\r\n\t\tunsigned int nJunk = 17;\r\n\t\tunsigned int n = 0;\r\n\t\tfor (n = 0; n < nSpinMax; ++n) {\r\n\t\t\tif (n < nSpinLast\/2 || nLock_) {\r\n\t\t\t\tnJunk *= nJunk;\r\n\t\t\t\tnJunk *= nJunk;\r\n\t\t\t\tnJunk *= nJunk;\r\n\t\t\t\tnJunk *= nJunk;\r\n\t\t\t}\r\n\t\t\telse {\r\n\t\t\t\tif (::InterlockedExchange(UNVOLATILE(LONG*)(&nLock_), 1) == 0) {\r\n\t\t\t\t\tnLast__ = n;\r\n\t\t\t\t\tnMax__ = HIGH_MAX;\r\n\t\t\t\t\treturn;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\t\r\n\t\tfor (n = 0; ; ++n) {\r\n\t\t\tint nSec = n + 6;\r\n\t\t\tif (nSec > 27)\r\n\t\t\t\tnSec = 27;\r\n\t\t\tif (::InterlockedExchange(UNVOLATILE(LONG*)(&nLock_), 1) == 0)\r\n\t\t\t\tbreak;\r\n\t\t\t::Sleep(nSec);\r\n\t\t}\r\n\t}\r\n}\r\n\r\n\r\n\/****************************************************************************\r\n *\r\n * ReadWriteLock\r\n *\r\n *\/\r\n\r\nqs::ReadWriteLock::ReadWriteLock() :\r\n\thMutexWrite_(0),\r\n\thEventRead_(0),\r\n\tnReader_(0)\r\n{\r\n\thMutexWrite_ = ::CreateMutex(0, FALSE, 0);\r\n\thEventRead_ = ::CreateEvent(0, TRUE, FALSE, 0);\r\n}\r\n\r\nqs::ReadWriteLock::~ReadWriteLock()\r\n{\r\n\t::CloseHandle(hMutexWrite_);\r\n\t::CloseHandle(hEventRead_);\r\n}\r\n\r\nvoid qs::ReadWriteLock::readLock() const\r\n{\r\n\t::WaitForSingleObject(hMutexWrite_, INFINITE);\r\n\t::InterlockedIncrement(UNVOLATILE(LONG*)(&nReader_));\r\n\t::ResetEvent(hEventRead_);\r\n\t::ReleaseMutex(hMutexWrite_);\r\n}\r\n\r\nvoid qs::ReadWriteLock::writeLock() const\r\n{\r\n\t::WaitForSingleObject(hMutexWrite_, INFINITE);\r\n\tif (InterlockedCompareExchange(UNVOLATILE(LONG*)(&nReader_), 0, 0) != 0)\r\n\t\t::WaitForSingleObject(hEventRead_, INFINITE);\r\n}\r\n\r\nvoid qs::ReadWriteLock::unlock() const\r\n{\r\n\tif (!::ReleaseMutex(hMutexWrite_) && ::GetLastError() == ERROR_NOT_OWNER) {\r\n\t\tif (::InterlockedDecrement(UNVOLATILE(LONG*)(&nReader_)) == 0)\r\n\t\t\t::SetEvent(hEventRead_);\r\n\t}\r\n}\r\n\r\n\r\n\/****************************************************************************\r\n *\r\n * Event\r\n *\r\n *\/\r\n\r\nqs::Event::Event() :\r\n\thEvent_(0)\r\n{\r\n\thEvent_ = ::CreateEvent(0, FALSE, FALSE, 0);\r\n}\r\n\r\nqs::Event::Event(bool bManual, bool bInitial)\r\n{\r\n\thEvent_ = ::CreateEvent(0, bManual, bInitial, 0);\r\n}\r\n\r\nqs::Event::Event(bool bManual,\r\n\t\t\t\t bool bInitial,\r\n\t\t\t\t const WCHAR* pwszName)\r\n{\r\n\ttstring_ptr tstrName(wcs2tcs(pwszName));\r\n\thEvent_ = ::CreateEvent(0, bManual, bInitial, tstrName.get());\r\n}\r\n\r\nqs::Event::~Event()\r\n{\r\n\tif (hEvent_)\r\n\t\t::CloseHandle(hEvent_);\r\n}\r\n\r\nbool qs::Event::set()\r\n{\r\n\treturn ::SetEvent(hEvent_) != 0;\r\n}\r\n\r\nbool qs::Event::reset()\r\n{\r\n\treturn ::ResetEvent(hEvent_) != 0;\r\n}\r\n\r\nbool qs::Event::pulse()\r\n{\r\n\treturn ::PulseEvent(hEvent_) != 0;\r\n}\r\n\r\nbool qs::Event::wait()\r\n{\r\n\treturn wait(INFINITE);\r\n}\r\n\r\nbool qs::Event::wait(unsigned int nMillisecond)\r\n{\r\n\treturn ::WaitForSingleObject(hEvent_, nMillisecond) != WAIT_FAILED;\r\n}\r\n\r\nHANDLE qs::Event::getHandle() const\r\n{\r\n\treturn hEvent_;\r\n}\r\n\r\n\r\n\/****************************************************************************\r\n *\r\n * Mutex\r\n *\r\n *\/\r\n\r\nqs::Mutex::Mutex() :\r\n\thMutex_(0)\r\n{\r\n\tinit(false, 0);\r\n}\r\n\r\nqs::Mutex::Mutex(bool bOwner) :\r\n\thMutex_(0)\r\n{\r\n\tinit(bOwner, 0);\r\n}\r\n\r\nqs::Mutex::Mutex(bool bOwner,\r\n\t\t\t\t const WCHAR* pwszName) :\r\n\thMutex_(0)\r\n{\r\n\tinit(bOwner, pwszName);\r\n}\r\n\r\nqs::Mutex::~Mutex()\r\n{\r\n\tif (hMutex_)\r\n\t\t::CloseHandle(hMutex_);\r\n}\r\n\r\nbool qs::Mutex::acquire()\r\n{\r\n\tassert(hMutex_);\r\n\treturn ::WaitForSingleObject(hMutex_, INFINITE) != WAIT_FAILED;\r\n}\r\n\r\nbool qs::Mutex::release()\r\n{\r\n\tassert(hMutex_);\r\n\treturn ::ReleaseMutex(hMutex_) != 0;\r\n}\r\n\r\nvoid qs::Mutex::init(bool bOwner,\r\n\t\t\t\t\t const WCHAR* pwszName)\r\n{\r\n\tif (pwszName) {\r\n\t\tW2T(pwszName, ptszName);\r\n\t\thMutex_ = ::CreateMutex(0, bOwner, ptszName);\r\n\t}\r\n\telse {\r\n\t\thMutex_ = ::CreateMutex(0, bOwner, 0);\r\n\t}\r\n}\r\n\r\n\r\n\/****************************************************************************\r\n *\r\n * Synchronizer\r\n *\r\n *\/\r\n\r\nqs::Synchronizer::Synchronizer() :\r\n\tpWindow_(0)\r\n{\r\n\tstd::auto_ptr<SynchronizerWindow> pWindow(new SynchronizerWindow());\r\n\tif (!pWindow->create(L\"QsSynchronizerWindow\", 0, WS_POPUP,\r\n\t\t0, 0, 0, 0, 0, 0, 0, 0, 0))\r\n\t\treturn;\r\n\tpWindow_ = pWindow.release();\r\n}\r\n\r\nqs::Synchronizer::~Synchronizer()\r\n{\r\n\tpWindow_->destroyWindow();\r\n}\r\n\r\nvoid qs::Synchronizer::syncExec(Runnable* pRunnable)\r\n{\r\n\tpWindow_->sendMessage(SynchronizerWindow::WM_SYNCEXEC,\r\n\t\t0, reinterpret_cast<LPARAM>(pRunnable));\r\n}\r\n\r\n\r\n\/****************************************************************************\r\n *\r\n * SynchronizerWindow\r\n *\r\n *\/\r\n\r\nqs::SynchronizerWindow::SynchronizerWindow() :\r\n\tWindowBase(true)\r\n{\r\n\tsetWindowHandler(this, false);\r\n}\r\n\r\nqs::SynchronizerWindow::~SynchronizerWindow()\r\n{\r\n}\r\n\r\nLRESULT qs::SynchronizerWindow::windowProc(UINT uMsg,\r\n\t\t\t\t\t\t\t\t\t\t WPARAM wParam,\r\n\t\t\t\t\t\t\t\t\t\t LPARAM lParam)\r\n{\r\n\tBEGIN_MESSAGE_HANDLER()\r\n\t\tHANDLE_MESSAGE(WM_SYNCEXEC, onSyncExec)\r\n\tEND_MESSAGE_HANDLER()\r\n\treturn DefaultWindowHandler::windowProc(uMsg, wParam, lParam);\r\n}\r\n\r\nLRESULT qs::SynchronizerWindow::onSyncExec(WPARAM wParam,\r\n\t\t\t\t\t\t\t\t\t\t LPARAM lParam)\r\n{\r\n\tRunnable* pRunnable = reinterpret_cast<Runnable*>(lParam);\r\n\tQTRY {\r\n\t\tpRunnable->run();\r\n\t}\r\n\tQCATCH_ALL() {\r\n\t\t;\r\n\t}\r\n\treturn 0;\r\n}\r\n<|endoftext|>"} {"text":"<commit_before>\/*\nThe MIT License (MIT)\n\nCopyright (c) 2016 shawnw\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n*\/\n\n#ifndef USEFUL_SORT_HPP\n#define USEFUL_SORT_HPP\n\n#include <algorithm>\n#include <iterator>\n#include <utility>\n#include <functional>\n\n\/* Additional sorting algorithms that work on iterator ranges. Of note is that\n * insertion and selection sort only need forward iterators, so they'll sort\n * linked list classes without having to use a sort member function. Useful for\n * container agnostic code.\n *\/\n\nnamespace useful {\n\ttemplate<class RandomAccessIterator>\n\tvoid heap_sort(RandomAccessIterator first, RandomAccessIterator last) {\n\t\tstd::make_heap(first, last);\n\t\tstd::sort_heap(first, last);\n\t}\n\t\n\ttemplate<class RandomAccessIterator, class Compare>\n\tvoid heap_sort(RandomAccessIterator first, RandomAccessIterator last, Compare comp) {\n\t\tstd::make_heap(first, last, comp);\n\t\tstd::sort_heap(first, last, comp);\n\t}\n\t\n\ttemplate<class ForwardIterator>\n\tvoid insertion_sort(ForwardIterator first, ForwardIterator last) {\n\t\tfor (auto i = first; i != last; ++i)\n\t\t\tstd::rotate(std::upper_bound(first, i, *i), i, std::next(i));\n\t}\n\t\t\n\ttemplate<class ForwardIterator, class Compare>\n\tvoid insertion_sort(ForwardIterator first, ForwardIterator last, Compare comp) {\n\t\tfor (auto i = first; i != last; ++i) \n\t\t\tstd::rotate(std::upper_bound(first, i, *i, comp), i, std::next(i));\n\t}\n\t\n\ttemplate<class ForwardIterator>\n\tvoid selection_sort(ForwardIterator first, ForwardIterator last) {\n\t\tfor (; first != last; ++first)\n\t\t\tstd::iter_swap(first, std::min_element(first, last));\n\t}\n\t\t\n\ttemplate<class ForwardIterator, class Compare>\n\tvoid selection_sort(ForwardIterator first, ForwardIterator last, Compare comp) {\n\t\tfor (; first != last; ++first)\n\t\t\tstd::iter_swap(first, std::min_element(first, last, comp));\n\t}\n\n\ttemplate<class BidirectionalIterator, class Compare>\n\tvoid merge_sort(BidirectionalIterator first, BidirectionalIterator last, Compare comp) {\n\t\tauto length = std::distance(first, last);\n\t\tbool isodd = length % 2;\n\t\tBidirectionalIterator mlast = last;\n\t\tif (isodd) {\n\t\t\tlength -= 1;\n\t\t\t--mlast;\n\t\t}\n\t\tfor (int s = 1; s <= length \/ 2; s += s) {\n\t\t\tBidirectionalIterator s1s = first;\n\t\t\tBidirectionalIterator s1e = s1s, s2e = s1s;\n\t\t\twhile (std::distance(first, s1s) + s + s <= length) {\n\t\t\t\tstd::advance(s1e, s);\n\t\t\t\tstd::advance(s2e, s + s);\n\t\t\t\tstd::inplace_merge(s1s, s1e, s2e, comp);\n\t\t\t\ts1s = s1e = s2e;\n\t\t\t}\n\t\t\tif (std::distance(first, s1s) + s <= length) \n\t\t\t\tstd::inplace_merge(first, s1s, mlast);\n\t\t}\n\t\tif (isodd)\n\t\t\tstd::inplace_merge(first, mlast, last, comp);\n\t}\n\t\n\ttemplate<class BidirectionalIterator>\n\tvoid merge_sort(BidirectionalIterator first, BidirectionalIterator last) {\n\t\tusing value_type = typename std::iterator_traits<BidirectionalIterator>::value_type;\n\t\tmerge_sort(first, last, std::less<value_type>());\n\t}\n\t\n\t\/* Useful functions for comparing pairs of values. Unlike the standard < for\n\t * pairs, only look at the first or second element. cmp1st and cmp2nd are\n\t * functors that work with std::not2 and a user-specific comparison operator,\n\t * comp1st and comp2nd are functions that use <. Use whichever works better\n\t * for the need.\n\t *\/\n\n\ttemplate<class T1, class T2, class Comp = std::less<T1>>\n\tstruct cmp1st {\n\t\tusing result_type = bool;\n\t\tusing first_argument_type = std::pair<T1, T2>;\n\t\tusing second_argument_type = std::pair<T1, T2>;\n\t\tComp c;\n\t\texplicit cmp1st(Comp c_ = Comp()) : c(c_) {}\n\t\tresult_type operator()(const first_argument_type &a, const second_argument_type &b) const {\n\t\t\treturn c(a.first, b.first);\n\t\t}\n\t};\n\t\n\ttemplate<class T1, class T2>\n\tbool comp1st(const std::pair<T1, T2> &a, const std::pair<T1, T2> &b) {\n\t\treturn cmp1st<T1, T2>()(a, b);\n\t}\n\t\n\ttemplate<class T1, class T2, class Comp = std::less<T2>>\n\tstruct cmp2nd {\n\t\tusing result_type = bool;\n\t\tusing first_argument_type = std::pair<T1, T2>;\n\t\tusing second_argument_type = std::pair<T1, T2>;\n\t\tComp c;\n\t\texplicit cmp2nd(Comp c_ = Comp()) : c(c_) {}\n\t\tresult_type operator()(const first_argument_type &a, const second_argument_type &b) const {\n\t\t\treturn c(a.second, b.second);\n\t\t}\t\n\t};\n\n\ttemplate<class T1, class T2>\n\tbool comp2nd(const std::pair<T1, T2> &a, const std::pair<T1, T2> &b) {\n\t\treturn cmp2nd<T1, T2>()(a, b);\n\t}\n};\n\n#endif\n<commit_msg>Add quick_sort implementation.<commit_after>\/*\nThe MIT License (MIT)\n\nCopyright (c) 2017 shawnw\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n*\/\n\n#ifndef USEFUL_SORT_HPP\n#define USEFUL_SORT_HPP\n\n#include <algorithm>\n#include <iterator>\n#include <utility>\n#include <functional>\n\n\/* Additional sorting algorithms that work on iterator ranges. Of note\n * is that insertion and selection sort only need forward iterators,\n * and quick sort a bidirectional one, so they'll sort linked list\n * classes without having to use a sort member function.\n *\n * Useful for container agnostic code.\n *\/\n\nnamespace useful {\n template<class RandomAccessIterator>\n void heap_sort(RandomAccessIterator first, RandomAccessIterator last) {\n std::make_heap(first, last);\n std::sort_heap(first, last);\n }\n\t\n template<class RandomAccessIterator, class Compare>\n void heap_sort(RandomAccessIterator first, RandomAccessIterator last, Compare comp) {\n std::make_heap(first, last, comp);\n std::sort_heap(first, last, comp);\n }\n\t\n template<class ForwardIterator>\n void insertion_sort(ForwardIterator first, ForwardIterator last) {\n for (auto i = first; i != last; ++i)\n std::rotate(std::upper_bound(first, i, *i), i, std::next(i));\n }\n \n template<class ForwardIterator, class Compare>\n void insertion_sort(ForwardIterator first, ForwardIterator last, Compare comp) {\n for (auto i = first; i != last; ++i) \n std::rotate(std::upper_bound(first, i, *i, comp), i, std::next(i));\n }\n\t\n template<class ForwardIterator>\n void selection_sort(ForwardIterator first, ForwardIterator last) {\n for (; first != last; ++first)\n std::iter_swap(first, std::min_element(first, last));\n }\n\t\t\n template<class ForwardIterator, class Compare>\n void selection_sort(ForwardIterator first, ForwardIterator last, Compare comp) {\n for (; first != last; ++first)\n std::iter_swap(first, std::min_element(first, last, comp));\n }\n\n template<class BidirectionalIterator, class Compare>\n void merge_sort(BidirectionalIterator first, BidirectionalIterator last, Compare comp) {\n auto length = std::distance(first, last);\n bool isodd = length % 2;\n auto mlast = last;\n if (isodd) {\n length -= 1;\n --mlast;\n }\n for (int s = 1; s <= length \/ 2; s += s) {\n auto s1s = first;\n auto s1e = s1s, s2e = s1s;\n while (std::distance(first, s1s) + s + s <= length) {\n std::advance(s1e, s);\n std::advance(s2e, s + s);\n std::inplace_merge(s1s, s1e, s2e, comp);\n s1s = s1e = s2e;\n }\n if (std::distance(first, s1s) + s <= length) \n std::inplace_merge(first, s1s, mlast);\n }\n if (isodd)\n std::inplace_merge(first, mlast, last, comp);\n }\n\t\n template<class BidirectionalIterator>\n void merge_sort(BidirectionalIterator first, BidirectionalIterator last) {\n using value_type = typename std::iterator_traits<BidirectionalIterator>::value_type;\n merge_sort(first, last, std::less<value_type>());\n }\n \n template<typename BiDirectionalIterator, typename Comp>\n void quick_sort(BiDirectionalIterator start, BiDirectionalIterator end, Comp cmp) {\n if (start == end)\n return;\n \n auto pivot = std::next(start, std::distance(start, end) \/ 2);\n std::iter_swap(start, pivot);\n auto mid = std::partition(std::next(start), end,\n [&](const auto &a){ return cmp(a, *start); }); \n auto mid2 = std::prev(mid);\n std::iter_swap(start, mid2);\n\n quick_sort(start, mid2, cmp);\n quick_sort(mid, end, cmp);\n }\n\n template<typename BiDirectionalIterator>\n void quick_sort(BiDirectionalIterator start, BiDirectionalIterator end) {\n using value_type = typename std::iterator_traits<BiDirectionalIterator>::value_type;\n quick_sort(start, end, std::less<value_type>());\n }\n\n \/* Useful functions for comparing pairs of values. Unlike the\n * standard < for pairs, only look at the first or second\n * element. cmp1st and cmp2nd are functors that work with a\n * user-specific comparison operator, comp1st and comp2nd are\n * functions that use <. Use whichever works better for the need.\n *\/\n\n template<class T1, class T2, class Comp = std::less<T1>>\n struct cmp1st {\n using result_type = bool;\n using argument_type = std::pair<T1, T2>;\n Comp c;\n explicit cmp1st(Comp c_ = Comp()) : c(c_) {}\n result_type operator()(const argument_type &a, const argument_type &b) const {\n return c(a.first, b.first);\n }\n };\n\t\n template<class T1, class T2>\n bool comp1st(const std::pair<T1, T2> &a, const std::pair<T1, T2> &b) {\n return cmp1st<T1, T2>()(a, b);\n }\n \n template<class T1, class T2, class Comp = std::less<T2>>\n struct cmp2nd {\n using result_type = bool;\n using argument_type = std::pair<T1, T2>;\n Comp c;\n explicit cmp2nd(Comp c_ = Comp()) : c(c_) {}\n result_type operator()(const argument_type &a, const argument_type &b) const {\n return c(a.second, b.second);\n }\t\n };\n \n template<class T1, class T2>\n bool comp2nd(const std::pair<T1, T2> &a, const std::pair<T1, T2> &b) {\n return cmp2nd<T1, T2>()(a, b);\n }\n};\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>#pragma once\n\/*\n** Copyright (C) 2013 Aldebaran Robotics\n** See COPYING for the license\n*\/\n\n#ifndef _QITYPE_DETAILS_SIGNAL_HXX_\n#define _QITYPE_DETAILS_SIGNAL_HXX_\n\n#include <qi\/trackable.hpp>\n#include <qi\/type\/detail\/manageable.hpp>\n#include <boost\/bind.hpp>\n#include <qi\/type\/detail\/functionsignature.hxx>\n\nnamespace qi\n{\n #define genConnect(n, ATYPEDECL, ATYPES, ADECL, AUSE, comma) \\\n template<typename T> \\\n template<typename F, typename P comma ATYPEDECL> \\\n SignalSubscriber& SignalF<T>::connect(F func, P p comma ADECL) \\\n { \\\n int curId; \\\n SignalLink* trackLink; \\\n createNewTrackLink(curId, trackLink); \\\n SignalSubscriber& s = connect(::qi::bindWithFallback<T>( \\\n boost::bind(&SignalF<T>::disconnectTrackLink, this, curId), \\\n func, p comma AUSE)); \\\n *trackLink = s; \\\n return s; \\\n }\n QI_GEN(genConnect)\n #undef genConnect\n\n template<typename T>\n SignalSubscriber& SignalF<T>::connect(AnyFunction f)\n {\n return SignalBase::connect(SignalSubscriber(f));\n }\n template<typename T>\n SignalSubscriber& SignalF<T>::connect(const SignalSubscriber& sub)\n {\n return SignalBase::connect(sub);\n }\n template<typename T>\n template<typename U>\n SignalSubscriber& SignalF<T>::connect(SignalF<U>& signal)\n {\n int curId;\n SignalLink* trackLink;\n createNewTrackLink(curId, trackLink);\n SignalSubscriber& s = connect(qi::trackWithFallback(\n boost::bind(&SignalF<T>::disconnectTrackLink, this, curId),\n (boost::function<U>&)signal,\n boost::weak_ptr<SignalBasePrivate>(signal._p)));\n *trackLink = s;\n return s;\n }\n\n template<typename T>\n template<QI_SIGNAL_TEMPLATE_DECL>\n SignalSubscriber& SignalF<T>::connect(Signal<QI_SIGNAL_TEMPLATE>& signal)\n {\n typedef typename detail::VoidFunctionType<QI_SIGNAL_TEMPLATE>::type ftype;\n int curId;\n SignalLink* trackLink;\n createNewTrackLink(curId, trackLink);\n SignalSubscriber& s = connect(qi::trackWithFallback(\n boost::bind(&SignalF<T>::disconnectTrackLink, this, curId),\n (boost::function<ftype>&)signal,\n boost::weak_ptr<SignalBasePrivate>(signal._p)));\n *trackLink = s;\n return s;\n }\n\n template<typename T>\n SignalSubscriber& SignalF<T>::connect(const boost::function<T>& fun)\n {\n return connect(AnyFunction::from(fun));\n }\n template<typename F>\n SignalSubscriber& SignalBase::connect(const boost::function<F>& fun)\n {\n return connect(AnyFunction::from(fun));\n }\n template<typename T>\n template<typename CALLABLE>\n SignalSubscriber& SignalF<T>::connect(CALLABLE c)\n {\n return connect((boost::function<T>)c);\n }\n template<typename T>\n SignalSubscriber& SignalF<T>::connect(const AnyObject& obj, const std::string& slot)\n {\n return SignalBase::connect(obj, slot);\n }\n\n template<typename T>\n SignalSubscriber& SignalF<T>::connect(const AnyObject& obj, unsigned int slot)\n {\n return connect(SignalSubscriber(obj, slot));\n }\n\n namespace detail\n {\n\n template<typename T> class BounceToSignalBase\n {\n \/\/ This default should not be instanciated\n BOOST_STATIC_ASSERT(sizeof(T) < 0);\n public:\n BounceToSignalBase(SignalBase& sb)\n {\n }\n };\n #define pushArg(z, n, _) \\\n args.push_back(AutoAnyReference(p ##n));\n #define makeBounce(n, argstypedecl, argstype, argsdecl, argsues, comma) \\\n template<typename R comma argstypedecl> \\\n class BounceToSignalBase<R(argstype)> { \\\n public: \\\n BounceToSignalBase(SignalBase& signalBase) : signalBase(signalBase) {} \\\n R operator()(argsdecl) { \\\n AnyReferenceVector args; \\\n BOOST_PP_REPEAT(n, pushArg, _); \\\n signalBase.trigger(args); \\\n } \\\n private: \\\n SignalBase& signalBase; \\\n };\n QI_GEN(makeBounce)\n #undef makeBounce\n #undef pushArg\n\n } \/\/ detail\n\n template<typename T>\n SignalF<T>::SignalF(OnSubscribers onSubscribers)\n : SignalBase(onSubscribers)\n {\n * (boost::function<T>*)this = detail::BounceToSignalBase<T>(*this);\n _setSignature(detail::functionArgumentsSignature<T>());\n }\n\n\n template<typename T>\n qi::Signature SignalF<T>::signature() const\n {\n return detail::functionArgumentsSignature<T>();\n }\n\n inline\n SignalSubscriber& SignalSubscriber::setCallType(MetaCallType ct)\n {\n threadingModel = ct;\n return *this;\n }\n} \/\/ qi\n#endif \/\/ _QITYPE_DETAILS_SIGNAL_HXX_\n<commit_msg>Signal: fix race on signal destruction<commit_after>#pragma once\n\/*\n** Copyright (C) 2013 Aldebaran Robotics\n** See COPYING for the license\n*\/\n\n#ifndef _QITYPE_DETAILS_SIGNAL_HXX_\n#define _QITYPE_DETAILS_SIGNAL_HXX_\n\n#include <qi\/trackable.hpp>\n#include <qi\/type\/detail\/manageable.hpp>\n#include <boost\/bind.hpp>\n#include <qi\/type\/detail\/functionsignature.hxx>\n\nnamespace qi\n{\n#define genConnect(n, ATYPEDECL, ATYPES, ADECL, AUSE, comma) \\\n template <typename T> \\\n template <typename F, typename P comma ATYPEDECL> \\\n SignalSubscriber& SignalF<T>::connect(F func, P p comma ADECL) \\\n { \\\n int curId; \\\n SignalLink* trackLink; \\\n createNewTrackLink(curId, trackLink); \\\n SignalSubscriber& s = connect(::qi::bindWithFallback<T>( \\\n qi::track(boost::function<void()>(boost::bind( \\\n &SignalF<T>::disconnectTrackLink, this, curId)), \\\n boost::weak_ptr<SignalBasePrivate>(_p)), \\\n func, p comma AUSE)); \\\n *trackLink = s; \\\n return s; \\\n }\n QI_GEN(genConnect)\n#undef genConnect\n\n template<typename T>\n SignalSubscriber& SignalF<T>::connect(AnyFunction f)\n {\n return SignalBase::connect(SignalSubscriber(f));\n }\n template<typename T>\n SignalSubscriber& SignalF<T>::connect(const SignalSubscriber& sub)\n {\n return SignalBase::connect(sub);\n }\n template<typename T>\n template<typename U>\n SignalSubscriber& SignalF<T>::connect(SignalF<U>& signal)\n {\n int curId;\n SignalLink* trackLink;\n createNewTrackLink(curId, trackLink);\n SignalSubscriber& s = connect(qi::trackWithFallback(\n boost::bind(&SignalF<T>::disconnectTrackLink, this, curId),\n (boost::function<U>&)signal,\n boost::weak_ptr<SignalBasePrivate>(signal._p)));\n *trackLink = s;\n return s;\n }\n\n template<typename T>\n template<QI_SIGNAL_TEMPLATE_DECL>\n SignalSubscriber& SignalF<T>::connect(Signal<QI_SIGNAL_TEMPLATE>& signal)\n {\n typedef typename detail::VoidFunctionType<QI_SIGNAL_TEMPLATE>::type ftype;\n int curId;\n SignalLink* trackLink;\n createNewTrackLink(curId, trackLink);\n SignalSubscriber& s = connect(qi::trackWithFallback(\n boost::bind(&SignalF<T>::disconnectTrackLink, this, curId),\n (boost::function<ftype>&)signal,\n boost::weak_ptr<SignalBasePrivate>(signal._p)));\n *trackLink = s;\n return s;\n }\n\n template<typename T>\n SignalSubscriber& SignalF<T>::connect(const boost::function<T>& fun)\n {\n return connect(AnyFunction::from(fun));\n }\n template<typename F>\n SignalSubscriber& SignalBase::connect(const boost::function<F>& fun)\n {\n return connect(AnyFunction::from(fun));\n }\n template<typename T>\n template<typename CALLABLE>\n SignalSubscriber& SignalF<T>::connect(CALLABLE c)\n {\n return connect((boost::function<T>)c);\n }\n template<typename T>\n SignalSubscriber& SignalF<T>::connect(const AnyObject& obj, const std::string& slot)\n {\n return SignalBase::connect(obj, slot);\n }\n\n template<typename T>\n SignalSubscriber& SignalF<T>::connect(const AnyObject& obj, unsigned int slot)\n {\n return connect(SignalSubscriber(obj, slot));\n }\n\n namespace detail\n {\n\n template<typename T> class BounceToSignalBase\n {\n \/\/ This default should not be instanciated\n BOOST_STATIC_ASSERT(sizeof(T) < 0);\n public:\n BounceToSignalBase(SignalBase& sb)\n {\n }\n };\n #define pushArg(z, n, _) \\\n args.push_back(AutoAnyReference(p ##n));\n #define makeBounce(n, argstypedecl, argstype, argsdecl, argsues, comma) \\\n template<typename R comma argstypedecl> \\\n class BounceToSignalBase<R(argstype)> { \\\n public: \\\n BounceToSignalBase(SignalBase& signalBase) : signalBase(signalBase) {} \\\n R operator()(argsdecl) { \\\n AnyReferenceVector args; \\\n BOOST_PP_REPEAT(n, pushArg, _); \\\n signalBase.trigger(args); \\\n } \\\n private: \\\n SignalBase& signalBase; \\\n };\n QI_GEN(makeBounce)\n #undef makeBounce\n #undef pushArg\n\n } \/\/ detail\n\n template<typename T>\n SignalF<T>::SignalF(OnSubscribers onSubscribers)\n : SignalBase(onSubscribers)\n {\n * (boost::function<T>*)this = detail::BounceToSignalBase<T>(*this);\n _setSignature(detail::functionArgumentsSignature<T>());\n }\n\n\n template<typename T>\n qi::Signature SignalF<T>::signature() const\n {\n return detail::functionArgumentsSignature<T>();\n }\n\n inline\n SignalSubscriber& SignalSubscriber::setCallType(MetaCallType ct)\n {\n threadingModel = ct;\n return *this;\n }\n} \/\/ qi\n#endif \/\/ _QITYPE_DETAILS_SIGNAL_HXX_\n<|endoftext|>"} {"text":"<commit_before>\/*\n webpresenceplugin.cpp\n\n Kopete Web Presence plugin\n\n Copyright (c) 2002 by Will Stephenson <will@stevello.free-online.co.uk>\n\n Kopete (c) 2002 by the Kopete developers <kopete-devel@kde.org>\n\n *************************************************************************\n * \t*\n * This program is free software; you can redistribute it and\/or modify *\n * it under the terms of the GNU General Public License as published by *\n * the Free Software Foundation; either version 2 of the License, or *\n * (at your option) any later version. *\n * *\n *************************************************************************\n *\/\n\n#include \"config.h\"\n\n#include <qtimer.h>\n#include <qfile.h>\n\n#include <kdebug.h>\n#include <kgenericfactory.h>\n#include <ktempfile.h>\n#include <kstandarddirs.h>\n\n#ifdef HAVE_XSLT\n#include <libxml\/xmlmemory.h>\n#include <libxml\/debugXML.h>\n#include <libxml\/HTMLtree.h>\n#include <libxml\/xmlIO.h>\n#include <libxml\/DOCBparser.h>\n#include <libxml\/xinclude.h>\n#include <libxml\/catalog.h>\n#include <libxslt\/xsltconfig.h>\n#include <libxslt\/xslt.h>\n#include <libxslt\/xsltInternals.h>\n#include <libxslt\/transform.h>\n#include <libxslt\/xsltutils.h>\n#endif\n\n#include \"pluginloader.h\"\n#include \"kopeteprotocol.h\"\n#include \"kopeteaccountmanager.h\"\n#include \"kopeteaccount.h\"\n\n#include \"webpresenceplugin.h\"\n#include \"webpresencepreferences.h\"\n\nK_EXPORT_COMPONENT_FACTORY( kopete_webpresence, KGenericFactory<WebPresencePlugin> );\n\nWebPresencePlugin::WebPresencePlugin( QObject *parent, const char *name, const QStringList& \/*args*\/ )\n: KopetePlugin( parent, name )\n{\n\tm_writeScheduler = new QTimer( this );\n\tconnect ( m_writeScheduler, SIGNAL( timeout() ), this, SLOT( slotWriteFile() ) );\n\tm_prefs = new WebPresencePreferences( \"\", this );\n\tconnect( KopeteAccountManager::manager(), SIGNAL(accountReady(KopeteAccount*)),\n\t\t\t\tthis, SLOT( listenToAllAccounts() ) );\n\tconnect( KopeteAccountManager::manager(), SIGNAL(accountUnregistered(KopeteAccount*)),\n\t\t\t\tthis, SLOT( listenToAllAccounts() ) );\n\n}\n\nWebPresencePlugin::~WebPresencePlugin()\n{\n}\n\nvoid WebPresencePlugin::listenToAllAccounts()\n{\n\t\/\/ connect to signals notifying of all accounts' status changes\n\tQPtrList<KopeteProtocol> protocols = allProtocols();\n\tfor ( KopeteProtocol *p = protocols.first();\n\t\t\tp; p = protocols.next() )\n\t{\n\t\tQDict<KopeteAccount> dict=KopeteAccountManager::manager()->accounts( p );\n\t\tQDictIterator<KopeteAccount> it( dict );\n\t\tfor( ; KopeteAccount *account=it.current(); ++it )\n\t\t{\n\t\t\t listenToAccount( account );\n\t\t}\n \t}\n\tslotWaitMoreStatusChanges();\n}\n\nvoid WebPresencePlugin::listenToAccount( KopeteAccount* account )\n{\n\tif(account->myself())\n\t{\n\t\t\/\/ Connect to the account's status changed signal\n\t\t\/\/ because we can't know if the account has already connected\n\t\tQObject::disconnect( account->myself(),\n\t\t\t\t\t\tSIGNAL(onlineStatusChanged( KopeteContact *,\n\t\t\t\t\t\t\t\tconst KopeteOnlineStatus &,\n\t\t\t\t\t\t\t\tconst KopeteOnlineStatus & ) ),\n\t\t\t\t\t\tthis,\n\t\t\t\t\t\tSLOT( slotWaitMoreStatusChanges() ) ) ;\n\t\tQObject::connect( account->myself(),\n\t\t\t\t\t\tSIGNAL(onlineStatusChanged( KopeteContact *,\n\t\t\t\t\t\t\t\tconst KopeteOnlineStatus &,\n\t\t\t\t\t\t\t\tconst KopeteOnlineStatus & ) ),\n\t\t\t\t\t\tthis,\n\t\t\t\t\t\tSLOT( slotWaitMoreStatusChanges() ) );\n\t}\n}\n\nvoid WebPresencePlugin::slotWaitMoreStatusChanges()\n{\n\tif ( !m_writeScheduler->isActive() )\n\t\t m_writeScheduler->start( m_prefs->frequency() * 1000);\n\n}\n\nvoid WebPresencePlugin::slotWriteFile()\n{\n\tbool error = false;\n\t\/\/ generate the (temporary) XML file representing the current contactlist\n\tKTempFile* xml = generateFile();\n\txml->setAutoDelete( true );\n\n\tkdDebug(14309) << k_funcinfo << \" \" << xml->name() << endl;\n\n\tif ( m_prefs->justXml() )\n\t{\n\t\tm_output = xml;\n\t\txml = 0L;\n\t}\n\telse\n\t{\n\t\t\/\/ transform XML to the final format\n\t\tm_output = new KTempFile();\n\t\tm_output->setAutoDelete( true );\n\t\tif ( !transform( xml, m_output ) )\n\t\t{\n\t\t\terror = true;\n\t\t\tdelete m_output;\n\t\t}\n\t\tdelete xml; \/\/ might make debugging harder!\n\t}\n\tif ( !error )\n\t{\n\t\t\/\/ upload it to the specified URL\n\t\tKURL src( m_output->name() );\n\t\tKURL dest( m_prefs->url() );\n\t\tKIO::FileCopyJob *job = KIO::file_copy( src, dest, -1, true, false, false );\n\t\tconnect( job, SIGNAL( result( KIO::Job * ) ),\n\t\t\t\tSLOT( slotUploadJobResult( KIO::Job * ) ) );\n\t}\n\tm_writeScheduler->stop();\n}\n\nvoid WebPresencePlugin::slotUploadJobResult( KIO::Job *job )\n{\n\tif ( job->error() ) {\n\t\tkdDebug(14309) << \"Error uploading presence info.\" << endl;\n\t\tjob->showErrorDialog( 0 );\n\t}\n\tdelete m_output;\n\treturn;\n}\n\nKTempFile* WebPresencePlugin::generateFile()\n{\n\t\/\/ generate the (temporary) file representing the current contactlist\n\tkdDebug( 14309 ) << k_funcinfo << endl;\n\n\tKTempFile* theFile = new KTempFile();\n\tQTextStream* qout = theFile->textStream() ;\n\tQString output;\n\tQString notKnown = i18n( \"Not yet known\" );\n\tQPtrList<KopeteProtocol> protocols = allProtocols();\n\n\tXMLHelper h;\n\toutput += h.content( \"<?xml version=\\\"1.0\\\"?>\" );\n\toutput += h.openTag( \"contacts\" );\n\n\t\/\/ insert the current date\/time\n\toutput += h.oneLineTag( \"listdate\",\n\t\t\tKGlobal::locale()->formatDateTime( QDateTime::currentDateTime() ) );\n\n\toutput += h.openTag( \"contact\", \"type=\\\"self\\\"\" );\n\n\t\/\/ insert the user's name\n\tif ( !m_prefs->useImName() && !m_prefs->userName().isEmpty() )\n\t\toutput += h.oneLineTag( \"name\", m_prefs->userName() );\n\telse\n\t\toutput += h.oneLineTag( \"name\", notKnown );\n\n\t\/\/ insert the list of the contact's protocols\n\toutput += h.openTag( \"protocols\" );\n\n\tfor ( KopeteProtocol *p = protocols.first();\n\t\t\tp; p = protocols.next() )\n\t{\n\t\t\/\/ get all the accounts per protocol\n\t\tQDict<KopeteAccount> dict = KopeteAccountManager::manager()->accounts( p );\n\t\t\/\/ If no accounts, stop here\n\t\tif ( dict.isEmpty() )\n\t\t\tcontinue;\n\n\t\toutput += h.openTag( \"protocol\" );\n\t\toutput += h.oneLineTag( \"protoname\", p->pluginId() );\n\n\t\tfor( QDictIterator<KopeteAccount> it( dict );\n\t\t\t KopeteAccount *account=it.current();\n\t\t\t ++it )\n\t\t{\n\t\t\toutput += h.openTag( \"account\" );\n\n\t\t\tKopeteContact* me = account->myself();\n\t\t\toutput += h.oneLineTag( \"accountname\",\n\t\t\t\t\t( me )\n\t\t\t\t\t? me->displayName().latin1()\n\t\t\t\t\t: notKnown.latin1() );\n\t\t\toutput += h.oneLineTag( \"accountstatus\",\n\t\t\t\t\t( me )\n\t\t\t\t\t? statusAsString( me->onlineStatus() )\n\t\t\t\t\t: notKnown );\n\n\t\t\tif ( m_prefs->showAddresses() )\n\t\t\t\toutput += h.oneLineTag( \"accountaddress\",\n\t\t\t\t\t\t( me )\n\t\t\t\t\t\t? me->contactId().latin1()\n\t\t\t\t\t\t: notKnown.latin1() );\n\n\t\t\toutput += h.closeTag();\n\t\t}\n\t\toutput += h.closeTag();\n\t}\n\n\t\/\/ finish off neatly\n\toutput += h.closeTag();\n\toutput += h.closeTag();\n\toutput += h.closeTag();\n\n\t\/\/ write our XML\n\t*qout << output;\n\t\n\ttheFile->close();\n\treturn theFile;\n}\n\nbool WebPresencePlugin::transform( KTempFile * src, KTempFile * dest )\n{\n#ifdef HAVE_XSLT\n\tQString error = \"\";\n\txmlSubstituteEntitiesDefault( 1 );\n\txmlLoadExtDtdDefaultValue = 1;\n\t\/\/ test if the stylesheet exists\n\tQFile sheet;\n\tif ( m_prefs->useDefaultStyleSheet() )\n\t\tsheet.setName( locate( \"appdata\", \"webpresence\/webpresencedefault.xsl\" ) );\n\telse\n\t\tsheet.setName( m_prefs->userStyleSheet() );\n\t\n\tif ( sheet.exists() )\n\t{\n\t\t\/\/ and if it is a valid stylesheet\n\t\txsltStylesheetPtr cur = NULL;\n\t\tif ( ( cur = xsltParseStylesheetFile(\n\t\t\t\t\t( const xmlChar *) sheet.name().latin1() ) ) )\n\t\t{\n\t\t\t\/\/ and if we can parse the input XML\n\t\t\txmlDocPtr doc = NULL;\n\t\t\tif ( ( doc = xmlParseFile( src->name() ) ) )\n\t\t\t{\n\t\t\t\t\/\/ and if we can apply the stylesheet\n\t\t\t\txmlDocPtr res = NULL;\n\t\t\t\tif ( ( res = xsltApplyStylesheet( cur, doc, 0 ) ) )\n\t\t\t\t{\n\t\t\t\t\t\/\/ and if we can save the result\n\t\t\t\t\tif ( xsltSaveResultToFile(dest->fstream() , res, cur)\n\t\t\t\t\t\t\t!= -1 )\n\t\t\t\t\t{\n\t\t\t\t\t\t\/\/ then it all worked!\n\t\t\t\t\t\tdest->close();\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t\terror = \"write result!\";\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\terror = \"apply stylesheet!\";\n\t\t\t\t\terror += \" Check the stylesheet works using xsltproc\";\n\t\t\t\t}\n\t\t\t\txmlFreeDoc(res);\n\t\t\t}\n\t\t\telse\n\t\t\t\terror = \"parse input XML!\";\n\t\t\txmlFreeDoc(doc);\n\t\t}\n\t\telse\n\t\t\terror = \"parse stylesheet!\";\n\t\txsltFreeStylesheet(cur);\n\t}\n\telse\n\t\terror = \"find stylesheet\" + sheet.name() + \"!\";\n\n\txsltCleanupGlobals();\n\txmlCleanupParser();\n\t\n\tif ( error.isEmpty() )\n\t\treturn true;\n\telse\n\t{\n\t\tkdDebug(14309) << k_funcinfo << \" - couldn't \"\n\t\t\t<< error << endl;\n\t\treturn false;\n\t}\n#else\n\tQ_UNUSED( src );\n\tQ_UNUSED( dest );\n\n\treturn false;\n#endif\n}\n\nQPtrList<KopeteProtocol> WebPresencePlugin::allProtocols()\n{\n\tkdDebug(14309) << k_funcinfo << endl;\n\tQPtrList<KopeteProtocol> protos;\n\tQPtrList<KopetePlugin> plugins = LibraryLoader::pluginLoader()->plugins();\n\n\tfor( KopetePlugin *p = plugins.first(); p; p = plugins.next() )\n\t{\n\t\tKopeteProtocol *proto = dynamic_cast<KopeteProtocol*>( p );\n\t\tif( !proto )\n\t\t\tcontinue;\n\t\tprotos.append( proto );\n\t}\n\treturn protos;\n}\n\nQString WebPresencePlugin::statusAsString( const KopeteOnlineStatus &newStatus )\n{\n\tQString status;\n\tswitch ( newStatus.status() )\n\t{\n\tcase KopeteOnlineStatus::Online:\n\t\tstatus = \"ONLINE\";\n\t\tbreak;\n\tcase KopeteOnlineStatus::Away:\n\t\tstatus = \"AWAY\";\n\t\tbreak;\n\tcase KopeteOnlineStatus::Offline:\n\t\tstatus = \"OFFLINE\";\n\t\tbreak;\n\tdefault:\n\t\tstatus = \"UNKNOWN\";\n\t}\n\n\treturn status;\n}\n\nWebPresencePlugin::XMLHelper::XMLHelper()\n{\n\tdepth = 0;\n\tstack = new QValueStack<QString>();\n}\n\nWebPresencePlugin::XMLHelper::~XMLHelper()\n{\n\tdelete stack;\n}\n\nQString WebPresencePlugin::XMLHelper::oneLineTag( QString name, QString content, QString attrs )\n{\n\tQString out;\n\tout.fill( '\\t', depth );\n\tout += \"<\" + name;\n\tif ( !attrs.isEmpty() )\n\t\tout += \" \" + attrs;\n\tif ( !content.isEmpty() )\n\t\tout += \">\" + content + \"<\/\" + name + \">\\n\";\n\telse\n\t\tout += \"\/>\\n\";\n\treturn out;\n}\n\nQString WebPresencePlugin::XMLHelper::openTag( QString name, QString attrs )\n{\n\tQString out;\n\tout.fill( '\\t', depth++ );\n\tout += \"<\" + name;\n\tif ( !attrs.isEmpty() )\n\t\tout += \" \" + attrs;\n\tout += \">\\n\";\n\n\tstack->push( name );\n\n\treturn out;\n}\n\nQString WebPresencePlugin::XMLHelper::content( QString content )\n{\n\tQString out;\n\tout.fill( '\\t', depth );\n\tout += content + \"\\n\";\n\n\treturn out;\n}\n\nQString WebPresencePlugin::XMLHelper::closeTag()\n{\n\tQString out;\n\tout.fill( '\\t', --depth );\n\tout += \"<\/\" + stack->pop () + \">\\n\";\n\n\treturn out;\n}\n\nQString WebPresencePlugin::XMLHelper::closeAll()\n{\n\tQString out;\n\twhile ( !stack->isEmpty() )\n\t{\n\t\tout.fill( '\\t', --depth );\n\t\tout += \"<\/\" + stack->pop () + \">\\n\";\n\t}\n\n\treturn out;\n}\n\n\/\/ vim: set noet ts=4 sts=4 sw=4:\n#include \"webpresenceplugin.moc\"\n<commit_msg>More icons.<commit_after>\/*\n webpresenceplugin.cpp\n\n Kopete Web Presence plugin\n\n Copyright (c) 2002 by Will Stephenson <will@stevello.free-online.co.uk>\n\n Kopete (c) 2002 by the Kopete developers <kopete-devel@kde.org>\n\n *************************************************************************\n * \t*\n * This program is free software; you can redistribute it and\/or modify *\n * it under the terms of the GNU General Public License as published by *\n * the Free Software Foundation; either version 2 of the License, or *\n * (at your option) any later version. *\n * *\n *************************************************************************\n *\/\n\n#include \"config.h\"\n\n#include <qtimer.h>\n#include <qfile.h>\n\n#include <kdebug.h>\n#include <kgenericfactory.h>\n#include <ktempfile.h>\n#include <kstandarddirs.h>\n\n#ifdef HAVE_XSLT\n#include <libxml\/xmlmemory.h>\n#include <libxml\/debugXML.h>\n#include <libxml\/HTMLtree.h>\n#include <libxml\/xmlIO.h>\n#include <libxml\/DOCBparser.h>\n#include <libxml\/xinclude.h>\n#include <libxml\/catalog.h>\n#include <libxslt\/xsltconfig.h>\n#include <libxslt\/xslt.h>\n#include <libxslt\/xsltInternals.h>\n#include <libxslt\/transform.h>\n#include <libxslt\/xsltutils.h>\n#endif\n\n#include \"pluginloader.h\"\n#include \"kopeteprotocol.h\"\n#include \"kopeteaccountmanager.h\"\n#include \"kopeteaccount.h\"\n\n#include \"webpresenceplugin.h\"\n#include \"webpresencepreferences.h\"\n\nK_EXPORT_COMPONENT_FACTORY( kopete_webpresence, KGenericFactory<WebPresencePlugin> );\n\nWebPresencePlugin::WebPresencePlugin( QObject *parent, const char *name, const QStringList& \/*args*\/ )\n: KopetePlugin( parent, name )\n{\n\tm_writeScheduler = new QTimer( this );\n\tconnect ( m_writeScheduler, SIGNAL( timeout() ), this, SLOT( slotWriteFile() ) );\n\tm_prefs = new WebPresencePreferences( \"html\", this );\n\tconnect( KopeteAccountManager::manager(), SIGNAL(accountReady(KopeteAccount*)),\n\t\t\t\tthis, SLOT( listenToAllAccounts() ) );\n\tconnect( KopeteAccountManager::manager(), SIGNAL(accountUnregistered(KopeteAccount*)),\n\t\t\t\tthis, SLOT( listenToAllAccounts() ) );\n\n}\n\nWebPresencePlugin::~WebPresencePlugin()\n{\n}\n\nvoid WebPresencePlugin::listenToAllAccounts()\n{\n\t\/\/ connect to signals notifying of all accounts' status changes\n\tQPtrList<KopeteProtocol> protocols = allProtocols();\n\tfor ( KopeteProtocol *p = protocols.first();\n\t\t\tp; p = protocols.next() )\n\t{\n\t\tQDict<KopeteAccount> dict=KopeteAccountManager::manager()->accounts( p );\n\t\tQDictIterator<KopeteAccount> it( dict );\n\t\tfor( ; KopeteAccount *account=it.current(); ++it )\n\t\t{\n\t\t\t listenToAccount( account );\n\t\t}\n \t}\n\tslotWaitMoreStatusChanges();\n}\n\nvoid WebPresencePlugin::listenToAccount( KopeteAccount* account )\n{\n\tif(account->myself())\n\t{\n\t\t\/\/ Connect to the account's status changed signal\n\t\t\/\/ because we can't know if the account has already connected\n\t\tQObject::disconnect( account->myself(),\n\t\t\t\t\t\tSIGNAL(onlineStatusChanged( KopeteContact *,\n\t\t\t\t\t\t\t\tconst KopeteOnlineStatus &,\n\t\t\t\t\t\t\t\tconst KopeteOnlineStatus & ) ),\n\t\t\t\t\t\tthis,\n\t\t\t\t\t\tSLOT( slotWaitMoreStatusChanges() ) ) ;\n\t\tQObject::connect( account->myself(),\n\t\t\t\t\t\tSIGNAL(onlineStatusChanged( KopeteContact *,\n\t\t\t\t\t\t\t\tconst KopeteOnlineStatus &,\n\t\t\t\t\t\t\t\tconst KopeteOnlineStatus & ) ),\n\t\t\t\t\t\tthis,\n\t\t\t\t\t\tSLOT( slotWaitMoreStatusChanges() ) );\n\t}\n}\n\nvoid WebPresencePlugin::slotWaitMoreStatusChanges()\n{\n\tif ( !m_writeScheduler->isActive() )\n\t\t m_writeScheduler->start( m_prefs->frequency() * 1000);\n\n}\n\nvoid WebPresencePlugin::slotWriteFile()\n{\n\tbool error = false;\n\t\/\/ generate the (temporary) XML file representing the current contactlist\n\tKTempFile* xml = generateFile();\n\txml->setAutoDelete( true );\n\n\tkdDebug(14309) << k_funcinfo << \" \" << xml->name() << endl;\n\n\tif ( m_prefs->justXml() )\n\t{\n\t\tm_output = xml;\n\t\txml = 0L;\n\t}\n\telse\n\t{\n\t\t\/\/ transform XML to the final format\n\t\tm_output = new KTempFile();\n\t\tm_output->setAutoDelete( true );\n\t\tif ( !transform( xml, m_output ) )\n\t\t{\n\t\t\terror = true;\n\t\t\tdelete m_output;\n\t\t}\n\t\tdelete xml; \/\/ might make debugging harder!\n\t}\n\tif ( !error )\n\t{\n\t\t\/\/ upload it to the specified URL\n\t\tKURL src( m_output->name() );\n\t\tKURL dest( m_prefs->url() );\n\t\tKIO::FileCopyJob *job = KIO::file_copy( src, dest, -1, true, false, false );\n\t\tconnect( job, SIGNAL( result( KIO::Job * ) ),\n\t\t\t\tSLOT( slotUploadJobResult( KIO::Job * ) ) );\n\t}\n\tm_writeScheduler->stop();\n}\n\nvoid WebPresencePlugin::slotUploadJobResult( KIO::Job *job )\n{\n\tif ( job->error() ) {\n\t\tkdDebug(14309) << \"Error uploading presence info.\" << endl;\n\t\tjob->showErrorDialog( 0 );\n\t}\n\tdelete m_output;\n\treturn;\n}\n\nKTempFile* WebPresencePlugin::generateFile()\n{\n\t\/\/ generate the (temporary) file representing the current contactlist\n\tkdDebug( 14309 ) << k_funcinfo << endl;\n\n\tKTempFile* theFile = new KTempFile();\n\tQTextStream* qout = theFile->textStream() ;\n\tQString output;\n\tQString notKnown = i18n( \"Not yet known\" );\n\tQPtrList<KopeteProtocol> protocols = allProtocols();\n\n\tXMLHelper h;\n\toutput += h.content( \"<?xml version=\\\"1.0\\\"?>\" );\n\toutput += h.openTag( \"contacts\" );\n\n\t\/\/ insert the current date\/time\n\toutput += h.oneLineTag( \"listdate\",\n\t\t\tKGlobal::locale()->formatDateTime( QDateTime::currentDateTime() ) );\n\n\toutput += h.openTag( \"contact\", \"type=\\\"self\\\"\" );\n\n\t\/\/ insert the user's name\n\tif ( !m_prefs->useImName() && !m_prefs->userName().isEmpty() )\n\t\toutput += h.oneLineTag( \"name\", m_prefs->userName() );\n\telse\n\t\toutput += h.oneLineTag( \"name\", notKnown );\n\n\t\/\/ insert the list of the contact's protocols\n\toutput += h.openTag( \"protocols\" );\n\n\tfor ( KopeteProtocol *p = protocols.first();\n\t\t\tp; p = protocols.next() )\n\t{\n\t\t\/\/ get all the accounts per protocol\n\t\tQDict<KopeteAccount> dict = KopeteAccountManager::manager()->accounts( p );\n\t\t\/\/ If no accounts, stop here\n\t\tif ( dict.isEmpty() )\n\t\t\tcontinue;\n\n\t\toutput += h.openTag( \"protocol\" );\n\t\toutput += h.oneLineTag( \"protoname\", p->pluginId() );\n\n\t\tfor( QDictIterator<KopeteAccount> it( dict );\n\t\t\t KopeteAccount *account=it.current();\n\t\t\t ++it )\n\t\t{\n\t\t\toutput += h.openTag( \"account\" );\n\n\t\t\tKopeteContact* me = account->myself();\n\t\t\toutput += h.oneLineTag( \"accountname\",\n\t\t\t\t\t( me )\n\t\t\t\t\t? me->displayName().latin1()\n\t\t\t\t\t: notKnown.latin1() );\n\t\t\toutput += h.oneLineTag( \"accountstatus\",\n\t\t\t\t\t( me )\n\t\t\t\t\t? statusAsString( me->onlineStatus() )\n\t\t\t\t\t: notKnown );\n\n\t\t\tif ( m_prefs->showAddresses() )\n\t\t\t\toutput += h.oneLineTag( \"accountaddress\",\n\t\t\t\t\t\t( me )\n\t\t\t\t\t\t? me->contactId().latin1()\n\t\t\t\t\t\t: notKnown.latin1() );\n\n\t\t\toutput += h.closeTag();\n\t\t}\n\t\toutput += h.closeTag();\n\t}\n\n\t\/\/ finish off neatly\n\toutput += h.closeTag();\n\toutput += h.closeTag();\n\toutput += h.closeTag();\n\n\t\/\/ write our XML\n\t*qout << output;\n\t\n\ttheFile->close();\n\treturn theFile;\n}\n\nbool WebPresencePlugin::transform( KTempFile * src, KTempFile * dest )\n{\n#ifdef HAVE_XSLT\n\tQString error = \"\";\n\txmlSubstituteEntitiesDefault( 1 );\n\txmlLoadExtDtdDefaultValue = 1;\n\t\/\/ test if the stylesheet exists\n\tQFile sheet;\n\tif ( m_prefs->useDefaultStyleSheet() )\n\t\tsheet.setName( locate( \"appdata\", \"webpresence\/webpresencedefault.xsl\" ) );\n\telse\n\t\tsheet.setName( m_prefs->userStyleSheet() );\n\t\n\tif ( sheet.exists() )\n\t{\n\t\t\/\/ and if it is a valid stylesheet\n\t\txsltStylesheetPtr cur = NULL;\n\t\tif ( ( cur = xsltParseStylesheetFile(\n\t\t\t\t\t( const xmlChar *) sheet.name().latin1() ) ) )\n\t\t{\n\t\t\t\/\/ and if we can parse the input XML\n\t\t\txmlDocPtr doc = NULL;\n\t\t\tif ( ( doc = xmlParseFile( src->name() ) ) )\n\t\t\t{\n\t\t\t\t\/\/ and if we can apply the stylesheet\n\t\t\t\txmlDocPtr res = NULL;\n\t\t\t\tif ( ( res = xsltApplyStylesheet( cur, doc, 0 ) ) )\n\t\t\t\t{\n\t\t\t\t\t\/\/ and if we can save the result\n\t\t\t\t\tif ( xsltSaveResultToFile(dest->fstream() , res, cur)\n\t\t\t\t\t\t\t!= -1 )\n\t\t\t\t\t{\n\t\t\t\t\t\t\/\/ then it all worked!\n\t\t\t\t\t\tdest->close();\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t\terror = \"write result!\";\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\terror = \"apply stylesheet!\";\n\t\t\t\t\terror += \" Check the stylesheet works using xsltproc\";\n\t\t\t\t}\n\t\t\t\txmlFreeDoc(res);\n\t\t\t}\n\t\t\telse\n\t\t\t\terror = \"parse input XML!\";\n\t\t\txmlFreeDoc(doc);\n\t\t}\n\t\telse\n\t\t\terror = \"parse stylesheet!\";\n\t\txsltFreeStylesheet(cur);\n\t}\n\telse\n\t\terror = \"find stylesheet\" + sheet.name() + \"!\";\n\n\txsltCleanupGlobals();\n\txmlCleanupParser();\n\t\n\tif ( error.isEmpty() )\n\t\treturn true;\n\telse\n\t{\n\t\tkdDebug(14309) << k_funcinfo << \" - couldn't \"\n\t\t\t<< error << endl;\n\t\treturn false;\n\t}\n#else\n\tQ_UNUSED( src );\n\tQ_UNUSED( dest );\n\n\treturn false;\n#endif\n}\n\nQPtrList<KopeteProtocol> WebPresencePlugin::allProtocols()\n{\n\tkdDebug(14309) << k_funcinfo << endl;\n\tQPtrList<KopeteProtocol> protos;\n\tQPtrList<KopetePlugin> plugins = LibraryLoader::pluginLoader()->plugins();\n\n\tfor( KopetePlugin *p = plugins.first(); p; p = plugins.next() )\n\t{\n\t\tKopeteProtocol *proto = dynamic_cast<KopeteProtocol*>( p );\n\t\tif( !proto )\n\t\t\tcontinue;\n\t\tprotos.append( proto );\n\t}\n\treturn protos;\n}\n\nQString WebPresencePlugin::statusAsString( const KopeteOnlineStatus &newStatus )\n{\n\tQString status;\n\tswitch ( newStatus.status() )\n\t{\n\tcase KopeteOnlineStatus::Online:\n\t\tstatus = \"ONLINE\";\n\t\tbreak;\n\tcase KopeteOnlineStatus::Away:\n\t\tstatus = \"AWAY\";\n\t\tbreak;\n\tcase KopeteOnlineStatus::Offline:\n\t\tstatus = \"OFFLINE\";\n\t\tbreak;\n\tdefault:\n\t\tstatus = \"UNKNOWN\";\n\t}\n\n\treturn status;\n}\n\nWebPresencePlugin::XMLHelper::XMLHelper()\n{\n\tdepth = 0;\n\tstack = new QValueStack<QString>();\n}\n\nWebPresencePlugin::XMLHelper::~XMLHelper()\n{\n\tdelete stack;\n}\n\nQString WebPresencePlugin::XMLHelper::oneLineTag( QString name, QString content, QString attrs )\n{\n\tQString out;\n\tout.fill( '\\t', depth );\n\tout += \"<\" + name;\n\tif ( !attrs.isEmpty() )\n\t\tout += \" \" + attrs;\n\tif ( !content.isEmpty() )\n\t\tout += \">\" + content + \"<\/\" + name + \">\\n\";\n\telse\n\t\tout += \"\/>\\n\";\n\treturn out;\n}\n\nQString WebPresencePlugin::XMLHelper::openTag( QString name, QString attrs )\n{\n\tQString out;\n\tout.fill( '\\t', depth++ );\n\tout += \"<\" + name;\n\tif ( !attrs.isEmpty() )\n\t\tout += \" \" + attrs;\n\tout += \">\\n\";\n\n\tstack->push( name );\n\n\treturn out;\n}\n\nQString WebPresencePlugin::XMLHelper::content( QString content )\n{\n\tQString out;\n\tout.fill( '\\t', depth );\n\tout += content + \"\\n\";\n\n\treturn out;\n}\n\nQString WebPresencePlugin::XMLHelper::closeTag()\n{\n\tQString out;\n\tout.fill( '\\t', --depth );\n\tout += \"<\/\" + stack->pop () + \">\\n\";\n\n\treturn out;\n}\n\nQString WebPresencePlugin::XMLHelper::closeAll()\n{\n\tQString out;\n\twhile ( !stack->isEmpty() )\n\t{\n\t\tout.fill( '\\t', --depth );\n\t\tout += \"<\/\" + stack->pop () + \">\\n\";\n\t}\n\n\treturn out;\n}\n\n\/\/ vim: set noet ts=4 sts=4 sw=4:\n#include \"webpresenceplugin.moc\"\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) Meta Platforms, Inc. and affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n *\/\n\n#include \"LeakChecker.h\"\n\n#include <glog\/logging.h>\n#include <jsi\/instrumentation.h>\n\n#include <utility>\n\nnamespace facebook::react {\n\nLeakChecker::LeakChecker(RuntimeExecutor runtimeExecutor)\n : runtimeExecutor_(std::move(runtimeExecutor)) {}\n\nvoid LeakChecker::uiManagerDidCreateShadowNodeFamily(\n ShadowNodeFamily::Shared const &shadowNodeFamily) const {\n registry_.add(shadowNodeFamily);\n}\n\nvoid LeakChecker::stopSurface(SurfaceId surfaceId) {\n if (previouslyStoppedSurface_ > 0) {\n \/\/ Dispatch the check onto JavaScript thread to make sure all other\n \/\/ cleanup code has had chance to run.\n runtimeExecutor_([previouslySoppedSurface = previouslyStoppedSurface_,\n this](jsi::Runtime &runtime) {\n runtime.instrumentation().collectGarbage(\"LeakChecker\");\n \/\/ For now check the previous surface because React uses double\n \/\/ buffering which keeps the surface that was just stopped in\n \/\/ memory. This is a documented problem in the last point of\n \/\/ https:\/\/github.com\/facebook\/react\/issues\/16087\n checkSurfaceForLeaks(previouslySoppedSurface);\n });\n }\n\n previouslyStoppedSurface_ = surfaceId;\n}\n\nvoid LeakChecker::checkSurfaceForLeaks(SurfaceId surfaceId) const {\n auto weakFamilies = registry_.weakFamiliesForSurfaceId(surfaceId);\n unsigned int numberOfLeaks = 0;\n for (auto const &weakFamily : weakFamilies) {\n auto strong = weakFamily.lock();\n if (strong) {\n ++numberOfLeaks;\n }\n }\n if (numberOfLeaks > 0) {\n LOG(ERROR) << \"[LeakChecker] Surface with id: \" << surfaceId\n << \" has leaked \" << numberOfLeaks << \" components out of \"\n << weakFamilies.size();\n }\n registry_.removeFamiliesWithSurfaceId(surfaceId);\n}\n\n} \/\/ namespace facebook::react\n<commit_msg>fix typo in LeakChecker<commit_after>\/*\n * Copyright (c) Meta Platforms, Inc. and affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n *\/\n\n#include \"LeakChecker.h\"\n\n#include <glog\/logging.h>\n#include <jsi\/instrumentation.h>\n\n#include <utility>\n\nnamespace facebook::react {\n\nLeakChecker::LeakChecker(RuntimeExecutor runtimeExecutor)\n : runtimeExecutor_(std::move(runtimeExecutor)) {}\n\nvoid LeakChecker::uiManagerDidCreateShadowNodeFamily(\n ShadowNodeFamily::Shared const &shadowNodeFamily) const {\n registry_.add(shadowNodeFamily);\n}\n\nvoid LeakChecker::stopSurface(SurfaceId surfaceId) {\n if (previouslyStoppedSurface_ > 0) {\n \/\/ Dispatch the check onto JavaScript thread to make sure all other\n \/\/ cleanup code has had chance to run.\n runtimeExecutor_([previouslyStoppedSurface = previouslyStoppedSurface_,\n this](jsi::Runtime &runtime) {\n runtime.instrumentation().collectGarbage(\"LeakChecker\");\n \/\/ For now check the previous surface because React uses double\n \/\/ buffering which keeps the surface that was just stopped in\n \/\/ memory. This is a documented problem in the last point of\n \/\/ https:\/\/github.com\/facebook\/react\/issues\/16087\n checkSurfaceForLeaks(previouslyStoppedSurface);\n });\n }\n\n previouslyStoppedSurface_ = surfaceId;\n}\n\nvoid LeakChecker::checkSurfaceForLeaks(SurfaceId surfaceId) const {\n auto weakFamilies = registry_.weakFamiliesForSurfaceId(surfaceId);\n unsigned int numberOfLeaks = 0;\n for (auto const &weakFamily : weakFamilies) {\n auto strong = weakFamily.lock();\n if (strong) {\n ++numberOfLeaks;\n }\n }\n if (numberOfLeaks > 0) {\n LOG(ERROR) << \"[LeakChecker] Surface with id: \" << surfaceId\n << \" has leaked \" << numberOfLeaks << \" components out of \"\n << weakFamilies.size();\n }\n registry_.removeFamiliesWithSurfaceId(surfaceId);\n}\n\n} \/\/ namespace facebook::react\n<|endoftext|>"} {"text":"<commit_before>#include <common\/list.h>\n#include <common\/log.h>\n#include <user_cmd\/pertypes.h>\n#include <user_cmd\/per.lex.h>\n#include <user_cmd\/per.tab.h>\n#include <sys\/types.h>\n#include <sys\/stat.h>\n#include <fcntl.h>\n#include <unistd.h>\n#include <string.h>\n#include <stdio.h>\n\n\n\/* macros *\/\n\/**\n * \\brief\tremove leading and trailing spaces\n *\n * \\param\ts\tstring to be updated\n * \\param\to\tindex of the first non-blank\n *\/\n#define skip_blank(s, o) { \\\n\tunsigned int i; \\\n\t\\\n\t\\\n\to = 0; \\\n\twhile(s[o] != 0 && s[o] == ' ') o++; \\\n\ti = strlen(s) - 1; \\\n\twhile(i > 0 && s[i] == ' ') i--; \\\n\ts[i + 1] = 0; \\\n}\n\n\n\/* global functions *\/\nint main(int argc, char** argv){\n\tint retval = 1;\n\tunsigned int sec_off,\n\t\t\t\t reg_off,\n\t\t\t\t bit_off;\n\tFILE *per,\n\t\t *header;\n\tper_section_t *sec;\n\tper_range_t *rlst, *range;\n\tper_register_t* reg;\n\tper_bits_t* bits;\n\n\n\t\/* init *\/\n\tif(argc < 3){\n\t\tprintf(\"usage: %s <per-file> <header-file>\\n\", argv[0]);\n\t\tgoto e0;\n\t}\n\n\tif(log::init(\"\/proc\/self\/fd\/1\", LOG_LEVEL) != 0)\n\t\tgoto e0;\n\n\tper = fopen(argv[1], \"r\");\n\n\tif(per == 0){\n\t\tUSER(\"error: unable to open file \\\"%s\\\" - %s\\n\", argv[1], strerror(errno));\n\t\tgoto e1;\n\t}\n\n\theader = fopen(argv[2], \"w\");\n\n\tif(header == 0){\n\t\tUSER(\"error: unable to open file \\\"%s\\\" - %s\\n\", argv[2], strerror(errno));\n\t\tgoto e2;\n\t}\n\n\t\/* parse peripheral file *\/\n\tif(perparse(per, &rlst) != 0){\n\t\tUSER(\"error: parsing peripheral file failed\\n\");\n\t\tgoto e3;\n\t}\n\n\t\/* generate header *\/\n\tlist_for_each(rlst, range){\n\t\tlist_for_each(range->sections, sec){\n\t\t\tif(!sec->name)\n\t\t\t\tcontinue;\n\n\t\t\tskip_blank(sec->name, sec_off);\n\t\t\tfprintf(header, \"\/* %s *\/\\n\", sec->name + sec_off);\n\n\t\t\tlist_for_each(sec->regs, reg){\n\t\t\t\tif(reg->nbytes == 0)\n\t\t\t\t\tcontinue;\n\n\t\t\t\tskip_blank(reg->name, reg_off);\n\n\t\t\t\tfprintf(header,\n\t\t\t\t\t\"\/* %s *\/\\n\"\n\t\t\t\t\t\"\/\/ register\\n\"\n\t\t\t\t\t\"#define %s\\t\\t\\t0x%lx\\n\\n\"\n\t\t\t\t\t, reg->name + reg_off\n\t\t\t\t\t, reg->name + reg_off\n\t\t\t\t\t, (unsigned long int)range->base + reg->offset\n\t\t\t\t);\n\n\t\t\t\tif(!list_empty(reg->bits))\n\t\t\t\t\tfprintf(header, \"\/\/ bits\\n\");\n\n\t\t\t\tlist_for_each(reg->bits, bits){\n\t\t\t\t\tskip_blank(bits->name, bit_off);\n\t\t\t\t\tfprintf(header, \"#define %s_%s\\t\\t%d\\n\", reg->name + reg_off, bits->name + bit_off, bits->idx);\n\t\t\t\t}\n\n\t\t\t\tif(!list_empty(reg->bits))\n\t\t\t\t\tfprintf(header, \"\\n\/\/ masks\\n\");\n\n\t\t\t\tlist_for_each(reg->bits, bits)\n\t\t\t\t\tfprintf(header, \"#define %s_%s_MASK\\t0x%x\\n\", reg->name + reg_off, bits->name + bit_off, bits->mask);\n\n\t\t\t\t\n\t\t\t\tif(!list_empty(reg->bits))\n\t\t\t\t\tfprintf(header, \"\\n\");\n\t\t\t}\n\t\t}\n\t}\n\n\tretval = 0;\n\n\t\/* cleanup *\/\ne3:\n\tperlex_destroy();\n\ne2:\n\tfclose(per);\n\ne1:\n\tlog::cleanup();\n\ne0:\n\treturn retval;\n}\n<commit_msg>[tools: per2h]<commit_after>#include <common\/list.h>\n#include <common\/log.h>\n#include <user_cmd\/pertypes.h>\n#include <user_cmd\/per.lex.h>\n#include <user_cmd\/per.tab.h>\n#include <sys\/types.h>\n#include <sys\/stat.h>\n#include <fcntl.h>\n#include <unistd.h>\n#include <string.h>\n#include <stdio.h>\n\n\n\/* macros *\/\n\/**\n * \\brief\tremove leading and trailing spaces\n *\n * \\param\ts\tstring to be updated\n * \\param\to\tindex of the first non-blank\n *\/\n#define skip_blank(s, o) { \\\n\tunsigned int i; \\\n\t\\\n\t\\\n\to = 0; \\\n\twhile(s[o] != 0 && s[o] == ' ') o++; \\\n\ti = strlen(s) - 1; \\\n\twhile(i > 0 && s[i] == ' ') i--; \\\n\ts[i + 1] = 0; \\\n}\n\n\n\/* global functions *\/\nint main(int argc, char** argv){\n\tint retval = 1;\n\tunsigned int sec_off,\n\t\t\t\t reg_off,\n\t\t\t\t bit_off;\n\tFILE *per,\n\t\t *header;\n\tper_section_t *sec;\n\tper_range_t *rlst, *range;\n\tper_register_t* reg;\n\tper_bits_t* bits;\n\n\n\t\/* init *\/\n\tif(argc < 3){\n\t\tprintf(\"usage: %s <per-file> <header-file>\\n\", argv[0]);\n\t\tgoto e0;\n\t}\n\n\tif(log::init(\"\/proc\/self\/fd\/1\", LOG_LEVEL) != 0)\n\t\tgoto e0;\n\n\tper = fopen(argv[1], \"r\");\n\n\tif(per == 0){\n\t\tUSER(\"error: unable to open file \\\"%s\\\" - %s\\n\", argv[1], strerror(errno));\n\t\tgoto e1;\n\t}\n\n\theader = fopen(argv[2], \"w\");\n\n\tif(header == 0){\n\t\tUSER(\"error: unable to open file \\\"%s\\\" - %s\\n\", argv[2], strerror(errno));\n\t\tgoto e2;\n\t}\n\n\t\/* parse peripheral file *\/\n\tif(perparse(per, &rlst) != 0){\n\t\tUSER(\"error: parsing peripheral file failed\\n\");\n\t\tgoto e3;\n\t}\n\n\t\/* generate header *\/\n\tlist_for_each(rlst, range){\n\t\tlist_for_each(range->sections, sec){\n\t\t\tif(!sec->name)\n\t\t\t\tcontinue;\n\n\t\t\tskip_blank(sec->name, sec_off);\n\t\t\tfprintf(header, \"\/**\\n *\\t%s\\n *\/\\n\", sec->name + sec_off);\n\n\t\t\tlist_for_each(sec->regs, reg){\n\t\t\t\tif(reg->nbytes == 0)\n\t\t\t\t\tcontinue;\n\n\t\t\t\tskip_blank(reg->name, reg_off);\n\n\t\t\t\tfprintf(header,\n\t\t\t\t\t\"\/* %s *\/\\n\"\n\t\t\t\t\t\"\/\/ register\\n\"\n\t\t\t\t\t\"#define %s\\t\\t\\t0x%lx\\n\\n\"\n\t\t\t\t\t, reg->name + reg_off\n\t\t\t\t\t, reg->name + reg_off\n\t\t\t\t\t, (unsigned long int)range->base + reg->offset\n\t\t\t\t);\n\n\t\t\t\tif(!list_empty(reg->bits))\n\t\t\t\t\tfprintf(header, \"\/\/ bits\\n\");\n\n\t\t\t\tlist_for_each(reg->bits, bits){\n\t\t\t\t\tskip_blank(bits->name, bit_off);\n\t\t\t\t\tfprintf(header, \"#define %s_%s\\t\\t%d\\n\", reg->name + reg_off, bits->name + bit_off, bits->idx);\n\t\t\t\t}\n\n\t\t\t\tif(!list_empty(reg->bits))\n\t\t\t\t\tfprintf(header, \"\\n\/\/ masks\\n\");\n\n\t\t\t\tlist_for_each(reg->bits, bits)\n\t\t\t\t\tfprintf(header, \"#define %s_%s_MASK\\t0x%x\\n\", reg->name + reg_off, bits->name + bit_off, bits->mask);\n\n\t\t\t\t\n\t\t\t\tif(!list_empty(reg->bits))\n\t\t\t\t\tfprintf(header, \"\\n\");\n\t\t\t}\n\t\t}\n\t}\n\n\tretval = 0;\n\n\t\/* cleanup *\/\ne3:\n\tperlex_destroy();\n\ne2:\n\tfclose(per);\n\ne1:\n\tlog::cleanup();\n\ne0:\n\treturn retval;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"GasMeter.h\"\n\n#include \"preprocessor\/llvm_includes_start.h\"\n#include <llvm\/IR\/IntrinsicInst.h>\n#include \"preprocessor\/llvm_includes_end.h\"\n\n#include \"Ext.h\"\n#include \"RuntimeManager.h\"\n\nnamespace dev\n{\nnamespace eth\n{\nnamespace jit\n{\n\nnamespace \/\/ Helper functions\n{\n\nint64_t const c_stepGas[] = {0, 2, 3, 5, 8, 10, 20};\nint64_t const c_expByteGas = 10;\nint64_t const c_sha3Gas = 30;\nint64_t const c_sha3WordGas = 6;\nint64_t const c_sloadGas = 50;\nint64_t const c_sstoreSetGas = 20000;\nint64_t const c_sstoreResetGas = 5000;\nint64_t const c_sstoreClearGas = 5000;\nint64_t const c_jumpdestGas = 1;\nint64_t const c_logGas = 375;\nint64_t const c_logTopicGas = 375;\nint64_t const c_logDataGas = 8;\nint64_t const c_callGas = 40;\nint64_t const c_createGas = 32000;\nint64_t const c_memoryGas = 3;\nint64_t const c_copyGas = 3;\n\nint64_t getStepCost(Instruction inst)\n{\n\tswitch (inst)\n\t{\n\t\/\/ Tier 0\n\tcase Instruction::STOP:\n\tcase Instruction::RETURN:\n\tcase Instruction::SUICIDE:\n\tcase Instruction::SSTORE: \/\/ Handle cost of SSTORE separately in GasMeter::countSStore()\n\t\treturn c_stepGas[0];\n\n\t\/\/ Tier 1\n\tcase Instruction::ADDRESS:\n\tcase Instruction::ORIGIN:\n\tcase Instruction::CALLER:\n\tcase Instruction::CALLVALUE:\n\tcase Instruction::CALLDATASIZE:\n\tcase Instruction::CODESIZE:\n\tcase Instruction::GASPRICE:\n\tcase Instruction::COINBASE:\n\tcase Instruction::TIMESTAMP:\n\tcase Instruction::NUMBER:\n\tcase Instruction::DIFFICULTY:\n\tcase Instruction::GASLIMIT:\n\tcase Instruction::POP:\n\tcase Instruction::PC:\n\tcase Instruction::MSIZE:\n\tcase Instruction::GAS:\n\t\treturn c_stepGas[1];\n\n\t\/\/ Tier 2\n\tcase Instruction::ADD:\n\tcase Instruction::SUB:\n\tcase Instruction::LT:\n\tcase Instruction::GT:\n\tcase Instruction::SLT:\n\tcase Instruction::SGT:\n\tcase Instruction::EQ:\n\tcase Instruction::ISZERO:\n\tcase Instruction::AND:\n\tcase Instruction::OR:\n\tcase Instruction::XOR:\n\tcase Instruction::NOT:\n\tcase Instruction::BYTE:\n\tcase Instruction::CALLDATALOAD:\n\tcase Instruction::CALLDATACOPY:\n\tcase Instruction::CODECOPY:\n\tcase Instruction::MLOAD:\n\tcase Instruction::MSTORE:\n\tcase Instruction::MSTORE8:\n\tcase Instruction::ANY_PUSH:\n\tcase Instruction::ANY_DUP:\n\tcase Instruction::ANY_SWAP:\n\t\treturn c_stepGas[2];\n\n\t\/\/ Tier 3\n\tcase Instruction::MUL:\n\tcase Instruction::DIV:\n\tcase Instruction::SDIV:\n\tcase Instruction::MOD:\n\tcase Instruction::SMOD:\n\tcase Instruction::SIGNEXTEND:\n\t\treturn c_stepGas[3];\n\n\t\/\/ Tier 4\n\tcase Instruction::ADDMOD:\n\tcase Instruction::MULMOD:\n\tcase Instruction::JUMP:\n\t\treturn c_stepGas[4];\n\n\t\/\/ Tier 5\n\tcase Instruction::EXP:\n\tcase Instruction::JUMPI:\n\t\treturn c_stepGas[5];\n\n\t\/\/ Tier 6\n\tcase Instruction::BALANCE:\n\tcase Instruction::EXTCODESIZE:\n\tcase Instruction::EXTCODECOPY:\n\tcase Instruction::BLOCKHASH:\n\t\treturn c_stepGas[6];\n\n\tcase Instruction::SHA3:\n\t\treturn c_sha3Gas;\n\n\tcase Instruction::SLOAD:\n\t\treturn c_sloadGas;\n\n\tcase Instruction::JUMPDEST:\n\t\treturn c_jumpdestGas;\n\n\tcase Instruction::LOG0:\n\tcase Instruction::LOG1:\n\tcase Instruction::LOG2:\n\tcase Instruction::LOG3:\n\tcase Instruction::LOG4:\n\t{\n\t\tauto numTopics = static_cast<int64_t>(inst) - static_cast<int64_t>(Instruction::LOG0);\n\t\treturn c_logGas + numTopics * c_logTopicGas;\n\t}\n\n\tcase Instruction::CALL:\n\tcase Instruction::CALLCODE:\n\t\treturn c_callGas;\n\n\tcase Instruction::CREATE:\n\t\treturn c_createGas;\n\t}\n\n\treturn 0; \/\/ TODO: Add UNREACHABLE macro\n}\n\n}\n\nGasMeter::GasMeter(llvm::IRBuilder<>& _builder, RuntimeManager& _runtimeManager) :\n\tCompilerHelper(_builder),\n\tm_runtimeManager(_runtimeManager)\n{\n\tllvm::Type* gasCheckArgs[] = {Type::Gas->getPointerTo(), Type::Gas, Type::BytePtr};\n\tm_gasCheckFunc = llvm::Function::Create(llvm::FunctionType::get(Type::Void, gasCheckArgs, false), llvm::Function::PrivateLinkage, \"gas.check\", getModule());\n\tm_gasCheckFunc->setDoesNotThrow();\n\tm_gasCheckFunc->setDoesNotCapture(1);\n\n\tauto checkBB = llvm::BasicBlock::Create(_builder.getContext(), \"Check\", m_gasCheckFunc);\n\tauto updateBB = llvm::BasicBlock::Create(_builder.getContext(), \"Update\", m_gasCheckFunc);\n\tauto outOfGasBB = llvm::BasicBlock::Create(_builder.getContext(), \"OutOfGas\", m_gasCheckFunc);\n\n\tauto gasPtr = &m_gasCheckFunc->getArgumentList().front();\n\tgasPtr->setName(\"gasPtr\");\n\tauto cost = gasPtr->getNextNode();\n\tcost->setName(\"cost\");\n\tauto jmpBuf = cost->getNextNode();\n\tjmpBuf->setName(\"jmpBuf\");\n\n\tInsertPointGuard guard(m_builder);\n\tm_builder.SetInsertPoint(checkBB);\n\tauto gas = m_builder.CreateLoad(gasPtr, \"gas\");\n\tauto gasUpdated = m_builder.CreateNSWSub(gas, cost, \"gasUpdated\");\n\tauto gasOk = m_builder.CreateICmpSGE(gasUpdated, m_builder.getInt64(0), \"gasOk\"); \/\/ gas >= 0, with gas == 0 we can still do 0 cost instructions\n\tm_builder.CreateCondBr(gasOk, updateBB, outOfGasBB, Type::expectTrue);\n\n\tm_builder.SetInsertPoint(updateBB);\n\tm_builder.CreateStore(gasUpdated, gasPtr);\n\tm_builder.CreateRetVoid();\n\n\tm_builder.SetInsertPoint(outOfGasBB);\n\tm_runtimeManager.abort(jmpBuf);\n\tm_builder.CreateUnreachable();\n}\n\nvoid GasMeter::count(Instruction _inst)\n{\n\tif (!m_checkCall)\n\t{\n\t\t\/\/ Create gas check call with mocked block cost at begining of current cost-block\n\t\tm_checkCall = createCall(m_gasCheckFunc, {m_runtimeManager.getGasPtr(), llvm::UndefValue::get(Type::Gas), m_runtimeManager.getJmpBuf()});\n\t}\n\n\tm_blockCost += getStepCost(_inst);\n}\n\nvoid GasMeter::count(llvm::Value* _cost, llvm::Value* _jmpBuf, llvm::Value* _gasPtr)\n{\n\tif (_cost->getType() == Type::Word)\n\t{\n\t\tauto gasMax256 = m_builder.CreateZExt(Constant::gasMax, Type::Word);\n\t\tauto tooHigh = m_builder.CreateICmpUGT(_cost, gasMax256, \"costTooHigh\");\n\t\tauto cost64 = m_builder.CreateTrunc(_cost, Type::Gas);\n\t\t_cost = m_builder.CreateSelect(tooHigh, Constant::gasMax, cost64, \"cost\");\n\t}\n\n\tassert(_cost->getType() == Type::Gas);\n\tcreateCall(m_gasCheckFunc, {_gasPtr ? _gasPtr : m_runtimeManager.getGasPtr(), _cost, _jmpBuf ? _jmpBuf : m_runtimeManager.getJmpBuf()});\n}\n\nvoid GasMeter::countExp(llvm::Value* _exponent)\n{\n\t\/\/ Additional cost is 1 per significant byte of exponent\n\t\/\/ lz - leading zeros\n\t\/\/ cost = ((256 - lz) + 7) \/ 8\n\n\t\/\/ OPT: Can gas update be done in exp algorithm?\n\n\tauto ctlz = llvm::Intrinsic::getDeclaration(getModule(), llvm::Intrinsic::ctlz, Type::Word);\n\tauto lz256 = m_builder.CreateCall2(ctlz, _exponent, m_builder.getInt1(false));\n\tauto lz = m_builder.CreateTrunc(lz256, Type::Gas, \"lz\");\n\tauto sigBits = m_builder.CreateSub(m_builder.getInt64(256), lz, \"sigBits\");\n\tauto sigBytes = m_builder.CreateUDiv(m_builder.CreateAdd(sigBits, m_builder.getInt64(7)), m_builder.getInt64(8));\n\tcount(m_builder.CreateNUWMul(sigBytes, m_builder.getInt64(c_expByteGas)));\n}\n\nvoid GasMeter::countSStore(Ext& _ext, llvm::Value* _index, llvm::Value* _newValue)\n{\n\tauto oldValue = _ext.sload(_index);\n\tauto oldValueIsZero = m_builder.CreateICmpEQ(oldValue, Constant::get(0), \"oldValueIsZero\");\n\tauto newValueIsntZero = m_builder.CreateICmpNE(_newValue, Constant::get(0), \"newValueIsntZero\");\n\tauto isInsert = m_builder.CreateAnd(oldValueIsZero, newValueIsntZero, \"isInsert\");\n\tstatic_assert(c_sstoreResetGas == c_sstoreClearGas, \"Update SSTORE gas cost\");\n\tauto cost = m_builder.CreateSelect(isInsert, m_builder.getInt64(c_sstoreSetGas), m_builder.getInt64(c_sstoreResetGas), \"cost\");\n\tcount(cost);\n}\n\nvoid GasMeter::countLogData(llvm::Value* _dataLength)\n{\n\tassert(m_checkCall);\n\tassert(m_blockCost > 0); \/\/ LOGn instruction is already counted\n\tstatic_assert(c_logDataGas != 1, \"Log data gas cost has changed. Update GasMeter.\");\n\tcount(m_builder.CreateNUWMul(_dataLength, Constant::get(c_logDataGas))); \/\/ TODO: Use i64\n}\n\nvoid GasMeter::countSha3Data(llvm::Value* _dataLength)\n{\n\tassert(m_checkCall);\n\tassert(m_blockCost > 0); \/\/ SHA3 instruction is already counted\n\n\t\/\/ TODO: This round ups to 32 happens in many places\n\tstatic_assert(c_sha3WordGas != 1, \"SHA3 data cost has changed. Update GasMeter\");\n\tauto dataLength64 = getBuilder().CreateTrunc(_dataLength, Type::Gas);\n\tauto words64 = m_builder.CreateUDiv(m_builder.CreateNUWAdd(dataLength64, getBuilder().getInt64(31)), getBuilder().getInt64(32));\n\tauto cost64 = m_builder.CreateNUWMul(getBuilder().getInt64(c_sha3WordGas), words64);\n\tcount(cost64);\n}\n\nvoid GasMeter::giveBack(llvm::Value* _gas)\n{\n\tassert(_gas->getType() == Type::Gas);\n\tm_runtimeManager.setGas(m_builder.CreateAdd(m_runtimeManager.getGas(), _gas));\n}\n\nvoid GasMeter::commitCostBlock()\n{\n\t\/\/ If any uncommited block\n\tif (m_checkCall)\n\t{\n\t\tif (m_blockCost == 0) \/\/ Do not check 0\n\t\t{\n\t\t\tm_checkCall->eraseFromParent(); \/\/ Remove the gas check call\n\t\t\tm_checkCall = nullptr;\n\t\t\treturn;\n\t\t}\n\n\t\tm_checkCall->setArgOperand(1, m_builder.getInt64(m_blockCost)); \/\/ Update block cost in gas check call\n\t\tm_checkCall = nullptr; \/\/ End cost-block\n\t\tm_blockCost = 0;\n\t}\n\tassert(m_blockCost == 0);\n}\n\nvoid GasMeter::countMemory(llvm::Value* _additionalMemoryInWords, llvm::Value* _jmpBuf, llvm::Value* _gasPtr)\n{\n\tstatic_assert(c_memoryGas != 1, \"Memory gas cost has changed. Update GasMeter.\");\n\tcount(_additionalMemoryInWords, _jmpBuf, _gasPtr);\n}\n\nvoid GasMeter::countCopy(llvm::Value* _copyWords)\n{\n\tstatic_assert(c_copyGas != 1, \"Copy gas cost has changed. Update GasMeter.\");\n\tcount(m_builder.CreateNUWMul(_copyWords, m_builder.getInt64(c_copyGas)));\n}\n\n}\n}\n}\n\n<commit_msg>Workaround for buggy LLVM ctlz used in counting EXP cost<commit_after>#include \"GasMeter.h\"\n\n#include \"preprocessor\/llvm_includes_start.h\"\n#include <llvm\/IR\/IntrinsicInst.h>\n#include \"preprocessor\/llvm_includes_end.h\"\n\n#include \"Ext.h\"\n#include \"RuntimeManager.h\"\n\nnamespace dev\n{\nnamespace eth\n{\nnamespace jit\n{\n\nnamespace \/\/ Helper functions\n{\n\nint64_t const c_stepGas[] = {0, 2, 3, 5, 8, 10, 20};\nint64_t const c_expByteGas = 10;\nint64_t const c_sha3Gas = 30;\nint64_t const c_sha3WordGas = 6;\nint64_t const c_sloadGas = 50;\nint64_t const c_sstoreSetGas = 20000;\nint64_t const c_sstoreResetGas = 5000;\nint64_t const c_sstoreClearGas = 5000;\nint64_t const c_jumpdestGas = 1;\nint64_t const c_logGas = 375;\nint64_t const c_logTopicGas = 375;\nint64_t const c_logDataGas = 8;\nint64_t const c_callGas = 40;\nint64_t const c_createGas = 32000;\nint64_t const c_memoryGas = 3;\nint64_t const c_copyGas = 3;\n\nint64_t getStepCost(Instruction inst)\n{\n\tswitch (inst)\n\t{\n\t\/\/ Tier 0\n\tcase Instruction::STOP:\n\tcase Instruction::RETURN:\n\tcase Instruction::SUICIDE:\n\tcase Instruction::SSTORE: \/\/ Handle cost of SSTORE separately in GasMeter::countSStore()\n\t\treturn c_stepGas[0];\n\n\t\/\/ Tier 1\n\tcase Instruction::ADDRESS:\n\tcase Instruction::ORIGIN:\n\tcase Instruction::CALLER:\n\tcase Instruction::CALLVALUE:\n\tcase Instruction::CALLDATASIZE:\n\tcase Instruction::CODESIZE:\n\tcase Instruction::GASPRICE:\n\tcase Instruction::COINBASE:\n\tcase Instruction::TIMESTAMP:\n\tcase Instruction::NUMBER:\n\tcase Instruction::DIFFICULTY:\n\tcase Instruction::GASLIMIT:\n\tcase Instruction::POP:\n\tcase Instruction::PC:\n\tcase Instruction::MSIZE:\n\tcase Instruction::GAS:\n\t\treturn c_stepGas[1];\n\n\t\/\/ Tier 2\n\tcase Instruction::ADD:\n\tcase Instruction::SUB:\n\tcase Instruction::LT:\n\tcase Instruction::GT:\n\tcase Instruction::SLT:\n\tcase Instruction::SGT:\n\tcase Instruction::EQ:\n\tcase Instruction::ISZERO:\n\tcase Instruction::AND:\n\tcase Instruction::OR:\n\tcase Instruction::XOR:\n\tcase Instruction::NOT:\n\tcase Instruction::BYTE:\n\tcase Instruction::CALLDATALOAD:\n\tcase Instruction::CALLDATACOPY:\n\tcase Instruction::CODECOPY:\n\tcase Instruction::MLOAD:\n\tcase Instruction::MSTORE:\n\tcase Instruction::MSTORE8:\n\tcase Instruction::ANY_PUSH:\n\tcase Instruction::ANY_DUP:\n\tcase Instruction::ANY_SWAP:\n\t\treturn c_stepGas[2];\n\n\t\/\/ Tier 3\n\tcase Instruction::MUL:\n\tcase Instruction::DIV:\n\tcase Instruction::SDIV:\n\tcase Instruction::MOD:\n\tcase Instruction::SMOD:\n\tcase Instruction::SIGNEXTEND:\n\t\treturn c_stepGas[3];\n\n\t\/\/ Tier 4\n\tcase Instruction::ADDMOD:\n\tcase Instruction::MULMOD:\n\tcase Instruction::JUMP:\n\t\treturn c_stepGas[4];\n\n\t\/\/ Tier 5\n\tcase Instruction::EXP:\n\tcase Instruction::JUMPI:\n\t\treturn c_stepGas[5];\n\n\t\/\/ Tier 6\n\tcase Instruction::BALANCE:\n\tcase Instruction::EXTCODESIZE:\n\tcase Instruction::EXTCODECOPY:\n\tcase Instruction::BLOCKHASH:\n\t\treturn c_stepGas[6];\n\n\tcase Instruction::SHA3:\n\t\treturn c_sha3Gas;\n\n\tcase Instruction::SLOAD:\n\t\treturn c_sloadGas;\n\n\tcase Instruction::JUMPDEST:\n\t\treturn c_jumpdestGas;\n\n\tcase Instruction::LOG0:\n\tcase Instruction::LOG1:\n\tcase Instruction::LOG2:\n\tcase Instruction::LOG3:\n\tcase Instruction::LOG4:\n\t{\n\t\tauto numTopics = static_cast<int64_t>(inst) - static_cast<int64_t>(Instruction::LOG0);\n\t\treturn c_logGas + numTopics * c_logTopicGas;\n\t}\n\n\tcase Instruction::CALL:\n\tcase Instruction::CALLCODE:\n\t\treturn c_callGas;\n\n\tcase Instruction::CREATE:\n\t\treturn c_createGas;\n\t}\n\n\treturn 0; \/\/ TODO: Add UNREACHABLE macro\n}\n\n}\n\nGasMeter::GasMeter(llvm::IRBuilder<>& _builder, RuntimeManager& _runtimeManager) :\n\tCompilerHelper(_builder),\n\tm_runtimeManager(_runtimeManager)\n{\n\tllvm::Type* gasCheckArgs[] = {Type::Gas->getPointerTo(), Type::Gas, Type::BytePtr};\n\tm_gasCheckFunc = llvm::Function::Create(llvm::FunctionType::get(Type::Void, gasCheckArgs, false), llvm::Function::PrivateLinkage, \"gas.check\", getModule());\n\tm_gasCheckFunc->setDoesNotThrow();\n\tm_gasCheckFunc->setDoesNotCapture(1);\n\n\tauto checkBB = llvm::BasicBlock::Create(_builder.getContext(), \"Check\", m_gasCheckFunc);\n\tauto updateBB = llvm::BasicBlock::Create(_builder.getContext(), \"Update\", m_gasCheckFunc);\n\tauto outOfGasBB = llvm::BasicBlock::Create(_builder.getContext(), \"OutOfGas\", m_gasCheckFunc);\n\n\tauto gasPtr = &m_gasCheckFunc->getArgumentList().front();\n\tgasPtr->setName(\"gasPtr\");\n\tauto cost = gasPtr->getNextNode();\n\tcost->setName(\"cost\");\n\tauto jmpBuf = cost->getNextNode();\n\tjmpBuf->setName(\"jmpBuf\");\n\n\tInsertPointGuard guard(m_builder);\n\tm_builder.SetInsertPoint(checkBB);\n\tauto gas = m_builder.CreateLoad(gasPtr, \"gas\");\n\tauto gasUpdated = m_builder.CreateNSWSub(gas, cost, \"gasUpdated\");\n\tauto gasOk = m_builder.CreateICmpSGE(gasUpdated, m_builder.getInt64(0), \"gasOk\"); \/\/ gas >= 0, with gas == 0 we can still do 0 cost instructions\n\tm_builder.CreateCondBr(gasOk, updateBB, outOfGasBB, Type::expectTrue);\n\n\tm_builder.SetInsertPoint(updateBB);\n\tm_builder.CreateStore(gasUpdated, gasPtr);\n\tm_builder.CreateRetVoid();\n\n\tm_builder.SetInsertPoint(outOfGasBB);\n\tm_runtimeManager.abort(jmpBuf);\n\tm_builder.CreateUnreachable();\n}\n\nvoid GasMeter::count(Instruction _inst)\n{\n\tif (!m_checkCall)\n\t{\n\t\t\/\/ Create gas check call with mocked block cost at begining of current cost-block\n\t\tm_checkCall = createCall(m_gasCheckFunc, {m_runtimeManager.getGasPtr(), llvm::UndefValue::get(Type::Gas), m_runtimeManager.getJmpBuf()});\n\t}\n\n\tm_blockCost += getStepCost(_inst);\n}\n\nvoid GasMeter::count(llvm::Value* _cost, llvm::Value* _jmpBuf, llvm::Value* _gasPtr)\n{\n\tif (_cost->getType() == Type::Word)\n\t{\n\t\tauto gasMax256 = m_builder.CreateZExt(Constant::gasMax, Type::Word);\n\t\tauto tooHigh = m_builder.CreateICmpUGT(_cost, gasMax256, \"costTooHigh\");\n\t\tauto cost64 = m_builder.CreateTrunc(_cost, Type::Gas);\n\t\t_cost = m_builder.CreateSelect(tooHigh, Constant::gasMax, cost64, \"cost\");\n\t}\n\n\tassert(_cost->getType() == Type::Gas);\n\tcreateCall(m_gasCheckFunc, {_gasPtr ? _gasPtr : m_runtimeManager.getGasPtr(), _cost, _jmpBuf ? _jmpBuf : m_runtimeManager.getJmpBuf()});\n}\n\nvoid GasMeter::countExp(llvm::Value* _exponent)\n{\n\t\/\/ Additional cost is 1 per significant byte of exponent\n\t\/\/ lz - leading zeros\n\t\/\/ cost = ((256 - lz) + 7) \/ 8\n\n\t\/\/ OPT: Can gas update be done in exp algorithm?\n\n\tauto t = llvm::APInt{256, 1};\n\tauto c = m_builder.CreateSelect(m_builder.CreateICmpUGE(_exponent, Constant::get(t)), m_builder.getInt64(1), m_builder.getInt64(0));\n\tfor (auto i = 2; i <= 32; ++i)\n\t{\n\t\tt <<= 8;\n\t\tc = m_builder.CreateSelect(m_builder.CreateICmpUGE(_exponent, Constant::get(t)), m_builder.getInt64(i), c);\n\t}\n\n\t\/\/ FIXME: Does not work because of LLVM bug: https:\/\/llvm.org\/bugs\/show_bug.cgi?id=22304\n\/\/\tauto ctlz = llvm::Intrinsic::getDeclaration(getModule(), llvm::Intrinsic::ctlz, Type::Word);\n\/\/\tauto lz256 = m_builder.CreateCall2(ctlz, _exponent, m_builder.getInt1(false));\n\/\/\tauto lz = m_builder.CreateTrunc(lz256, Type::Gas, \"lz\");\n\/\/\tauto sigBits = m_builder.CreateSub(m_builder.getInt64(256), lz, \"sigBits\");\n\/\/\tauto sigBytes = m_builder.CreateUDiv(m_builder.CreateAdd(sigBits, m_builder.getInt64(7)), m_builder.getInt64(8));\n\tcount(m_builder.CreateNUWMul(c, m_builder.getInt64(c_expByteGas)));\n}\n\nvoid GasMeter::countSStore(Ext& _ext, llvm::Value* _index, llvm::Value* _newValue)\n{\n\tauto oldValue = _ext.sload(_index);\n\tauto oldValueIsZero = m_builder.CreateICmpEQ(oldValue, Constant::get(0), \"oldValueIsZero\");\n\tauto newValueIsntZero = m_builder.CreateICmpNE(_newValue, Constant::get(0), \"newValueIsntZero\");\n\tauto isInsert = m_builder.CreateAnd(oldValueIsZero, newValueIsntZero, \"isInsert\");\n\tstatic_assert(c_sstoreResetGas == c_sstoreClearGas, \"Update SSTORE gas cost\");\n\tauto cost = m_builder.CreateSelect(isInsert, m_builder.getInt64(c_sstoreSetGas), m_builder.getInt64(c_sstoreResetGas), \"cost\");\n\tcount(cost);\n}\n\nvoid GasMeter::countLogData(llvm::Value* _dataLength)\n{\n\tassert(m_checkCall);\n\tassert(m_blockCost > 0); \/\/ LOGn instruction is already counted\n\tstatic_assert(c_logDataGas != 1, \"Log data gas cost has changed. Update GasMeter.\");\n\tcount(m_builder.CreateNUWMul(_dataLength, Constant::get(c_logDataGas))); \/\/ TODO: Use i64\n}\n\nvoid GasMeter::countSha3Data(llvm::Value* _dataLength)\n{\n\tassert(m_checkCall);\n\tassert(m_blockCost > 0); \/\/ SHA3 instruction is already counted\n\n\t\/\/ TODO: This round ups to 32 happens in many places\n\tstatic_assert(c_sha3WordGas != 1, \"SHA3 data cost has changed. Update GasMeter\");\n\tauto dataLength64 = getBuilder().CreateTrunc(_dataLength, Type::Gas);\n\tauto words64 = m_builder.CreateUDiv(m_builder.CreateNUWAdd(dataLength64, getBuilder().getInt64(31)), getBuilder().getInt64(32));\n\tauto cost64 = m_builder.CreateNUWMul(getBuilder().getInt64(c_sha3WordGas), words64);\n\tcount(cost64);\n}\n\nvoid GasMeter::giveBack(llvm::Value* _gas)\n{\n\tassert(_gas->getType() == Type::Gas);\n\tm_runtimeManager.setGas(m_builder.CreateAdd(m_runtimeManager.getGas(), _gas));\n}\n\nvoid GasMeter::commitCostBlock()\n{\n\t\/\/ If any uncommited block\n\tif (m_checkCall)\n\t{\n\t\tif (m_blockCost == 0) \/\/ Do not check 0\n\t\t{\n\t\t\tm_checkCall->eraseFromParent(); \/\/ Remove the gas check call\n\t\t\tm_checkCall = nullptr;\n\t\t\treturn;\n\t\t}\n\n\t\tm_checkCall->setArgOperand(1, m_builder.getInt64(m_blockCost)); \/\/ Update block cost in gas check call\n\t\tm_checkCall = nullptr; \/\/ End cost-block\n\t\tm_blockCost = 0;\n\t}\n\tassert(m_blockCost == 0);\n}\n\nvoid GasMeter::countMemory(llvm::Value* _additionalMemoryInWords, llvm::Value* _jmpBuf, llvm::Value* _gasPtr)\n{\n\tstatic_assert(c_memoryGas != 1, \"Memory gas cost has changed. Update GasMeter.\");\n\tcount(_additionalMemoryInWords, _jmpBuf, _gasPtr);\n}\n\nvoid GasMeter::countCopy(llvm::Value* _copyWords)\n{\n\tstatic_assert(c_copyGas != 1, \"Copy gas cost has changed. Update GasMeter.\");\n\tcount(m_builder.CreateNUWMul(_copyWords, m_builder.getInt64(c_copyGas)));\n}\n\n}\n}\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include <ocidl.h>\n#include <commdlg.h>\n\n#include <string>\n\n#include \"base\/scoped_ptr.h\"\n#include \"printing\/printing_test.h\"\n#include \"printing\/printing_context.h\"\n#include \"printing\/printing_context_win.h\"\n#include \"printing\/print_settings.h\"\n#include \"testing\/gtest\/include\/gtest\/gtest.h\"\n\n\/\/ This test is automatically disabled if no printer is available.\nclass PrintingContextTest : public PrintingTest<testing::Test> {\n public:\n void PrintSettingsCallback(printing::PrintingContext::Result result) {\n result_ = result;\n }\n\n protected:\n printing::PrintingContext::Result result() const { return result_; }\n\n private:\n printing::PrintingContext::Result result_;\n};\n\n\/\/ This is a fake PrintDlgEx implementation that sets the right fields in\n\/\/ |lppd| to trigger a bug in older revisions of PrintingContext.\nHRESULT WINAPI PrintDlgExMock(LPPRINTDLGEX lppd) {\n \/\/ The interesting bits:\n \/\/ Pretend the user hit print\n lppd->dwResultAction = PD_RESULT_PRINT;\n\n \/\/ Pretend the page range is 1-5, but since lppd->Flags does not have\n \/\/ PD_SELECTION set, this really shouldn't matter.\n lppd->nPageRanges = 1;\n lppd->lpPageRanges = new PRINTPAGERANGE[1];\n lppd->lpPageRanges[0].nFromPage = 1;\n lppd->lpPageRanges[0].nToPage = 5;\n\n \/\/ Painful paperwork.\n std::wstring printer_name = PrintingContextTest::GetDefaultPrinter();\n HANDLE printer;\n if (!OpenPrinter(const_cast<wchar_t*>(printer_name.c_str()), &printer, NULL))\n return E_FAIL;\n\n scoped_array<uint8> buffer;\n DEVMODE* dev_mode = NULL;\n PRINTER_INFO_2* info_2 = NULL;\n\n printing::PrintingContextWin::GetPrinterHelper(printer, 2, &buffer);\n if (buffer.get()) {\n info_2 = reinterpret_cast<PRINTER_INFO_2*>(buffer.get());\n if (info_2->pDevMode != NULL)\n dev_mode = info_2->pDevMode;\n }\n if (!dev_mode)\n return E_FAIL;\n\n if (!printing::PrintingContextWin::AllocateContext(printer_name, dev_mode,\n &lppd->hDC)) {\n return E_FAIL;\n }\n\n size_t dev_mode_size = dev_mode->dmSize + dev_mode->dmDriverExtra;\n lppd->hDevMode = GlobalAlloc(GMEM_MOVEABLE, dev_mode_size);\n if (!lppd->hDevMode)\n return E_FAIL;\n void* dev_mode_ptr = GlobalLock(lppd->hDevMode);\n if (!dev_mode_ptr)\n return E_FAIL;\n memcpy(dev_mode_ptr, dev_mode, dev_mode_size);\n GlobalUnlock(lppd->hDevMode);\n\n size_t driver_size = 2 + sizeof(wchar_t) * lstrlen(info_2->pDriverName);\n size_t printer_size = 2 + sizeof(wchar_t) * lstrlen(info_2->pPrinterName);\n size_t port_size = 2 + sizeof(wchar_t) * lstrlen(info_2->pPortName);\n size_t dev_names_size = sizeof(DEVNAMES) + driver_size + printer_size +\n port_size;\n lppd->hDevNames = GlobalAlloc(GHND, dev_names_size);\n if (!lppd->hDevNames)\n return E_FAIL;\n void* dev_names_ptr = GlobalLock(lppd->hDevNames);\n if (!dev_names_ptr)\n return E_FAIL;\n DEVNAMES* dev_names = reinterpret_cast<DEVNAMES*>(dev_names_ptr);\n dev_names->wDefault = 1;\n dev_names->wDriverOffset = sizeof(DEVNAMES);\n memcpy(reinterpret_cast<uint8*>(dev_names_ptr) + dev_names->wDriverOffset,\n info_2->pDriverName, driver_size);\n dev_names->wDeviceOffset = dev_names->wDriverOffset + driver_size;\n memcpy(reinterpret_cast<uint8*>(dev_names_ptr) + dev_names->wDeviceOffset,\n info_2->pPrinterName, printer_size);\n dev_names->wOutputOffset = dev_names->wDeviceOffset + printer_size;\n memcpy(reinterpret_cast<uint8*>(dev_names_ptr) + dev_names->wOutputOffset,\n info_2->pPortName, port_size);\n GlobalUnlock(lppd->hDevNames);\n\n return S_OK;\n}\n\nTEST_F(PrintingContextTest, Base) {\n printing::PrintSettings settings;\n\n settings.set_device_name(GetDefaultPrinter());\n \/\/ Initialize it.\n scoped_ptr<printing::PrintingContext> context(\n printing::PrintingContext::Create());\n EXPECT_EQ(printing::PrintingContext::OK, context->InitWithSettings(settings));\n\n \/\/ The print may lie to use and may not support world transformation.\n \/\/ Verify right now.\n XFORM random_matrix = { 1, 0.1f, 0, 1.5f, 0, 1 };\n EXPECT_TRUE(SetWorldTransform(context->context(), &random_matrix));\n EXPECT_TRUE(ModifyWorldTransform(context->context(), NULL, MWT_IDENTITY));\n}\n\nTEST_F(PrintingContextTest, PrintAll) {\n printing::PrintingContextWin context;\n context.SetPrintDialog(&PrintDlgExMock);\n context.AskUserForSettings(\n NULL,\n 123,\n false,\n NewCallback(static_cast<PrintingContextTest*>(this),\n &PrintingContextTest::PrintSettingsCallback));\n ASSERT_EQ(printing::PrintingContext::OK, result());\n printing::PrintSettings settings = context.settings();\n EXPECT_EQ(settings.ranges.size(), 0);\n}\n<commit_msg>Mark PrintingContextTest.PrintAll as flaky as it fails on Win builder.<commit_after>\/\/ Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include <ocidl.h>\n#include <commdlg.h>\n\n#include <string>\n\n#include \"base\/scoped_ptr.h\"\n#include \"printing\/printing_test.h\"\n#include \"printing\/printing_context.h\"\n#include \"printing\/printing_context_win.h\"\n#include \"printing\/print_settings.h\"\n#include \"testing\/gtest\/include\/gtest\/gtest.h\"\n\n\/\/ This test is automatically disabled if no printer is available.\nclass PrintingContextTest : public PrintingTest<testing::Test> {\n public:\n void PrintSettingsCallback(printing::PrintingContext::Result result) {\n result_ = result;\n }\n\n protected:\n printing::PrintingContext::Result result() const { return result_; }\n\n private:\n printing::PrintingContext::Result result_;\n};\n\n\/\/ This is a fake PrintDlgEx implementation that sets the right fields in\n\/\/ |lppd| to trigger a bug in older revisions of PrintingContext.\nHRESULT WINAPI PrintDlgExMock(LPPRINTDLGEX lppd) {\n \/\/ The interesting bits:\n \/\/ Pretend the user hit print\n lppd->dwResultAction = PD_RESULT_PRINT;\n\n \/\/ Pretend the page range is 1-5, but since lppd->Flags does not have\n \/\/ PD_SELECTION set, this really shouldn't matter.\n lppd->nPageRanges = 1;\n lppd->lpPageRanges = new PRINTPAGERANGE[1];\n lppd->lpPageRanges[0].nFromPage = 1;\n lppd->lpPageRanges[0].nToPage = 5;\n\n \/\/ Painful paperwork.\n std::wstring printer_name = PrintingContextTest::GetDefaultPrinter();\n HANDLE printer;\n if (!OpenPrinter(const_cast<wchar_t*>(printer_name.c_str()), &printer, NULL))\n return E_FAIL;\n\n scoped_array<uint8> buffer;\n DEVMODE* dev_mode = NULL;\n PRINTER_INFO_2* info_2 = NULL;\n\n printing::PrintingContextWin::GetPrinterHelper(printer, 2, &buffer);\n if (buffer.get()) {\n info_2 = reinterpret_cast<PRINTER_INFO_2*>(buffer.get());\n if (info_2->pDevMode != NULL)\n dev_mode = info_2->pDevMode;\n }\n if (!dev_mode)\n return E_FAIL;\n\n if (!printing::PrintingContextWin::AllocateContext(printer_name, dev_mode,\n &lppd->hDC)) {\n return E_FAIL;\n }\n\n size_t dev_mode_size = dev_mode->dmSize + dev_mode->dmDriverExtra;\n lppd->hDevMode = GlobalAlloc(GMEM_MOVEABLE, dev_mode_size);\n if (!lppd->hDevMode)\n return E_FAIL;\n void* dev_mode_ptr = GlobalLock(lppd->hDevMode);\n if (!dev_mode_ptr)\n return E_FAIL;\n memcpy(dev_mode_ptr, dev_mode, dev_mode_size);\n GlobalUnlock(lppd->hDevMode);\n\n size_t driver_size = 2 + sizeof(wchar_t) * lstrlen(info_2->pDriverName);\n size_t printer_size = 2 + sizeof(wchar_t) * lstrlen(info_2->pPrinterName);\n size_t port_size = 2 + sizeof(wchar_t) * lstrlen(info_2->pPortName);\n size_t dev_names_size = sizeof(DEVNAMES) + driver_size + printer_size +\n port_size;\n lppd->hDevNames = GlobalAlloc(GHND, dev_names_size);\n if (!lppd->hDevNames)\n return E_FAIL;\n void* dev_names_ptr = GlobalLock(lppd->hDevNames);\n if (!dev_names_ptr)\n return E_FAIL;\n DEVNAMES* dev_names = reinterpret_cast<DEVNAMES*>(dev_names_ptr);\n dev_names->wDefault = 1;\n dev_names->wDriverOffset = sizeof(DEVNAMES);\n memcpy(reinterpret_cast<uint8*>(dev_names_ptr) + dev_names->wDriverOffset,\n info_2->pDriverName, driver_size);\n dev_names->wDeviceOffset = dev_names->wDriverOffset + driver_size;\n memcpy(reinterpret_cast<uint8*>(dev_names_ptr) + dev_names->wDeviceOffset,\n info_2->pPrinterName, printer_size);\n dev_names->wOutputOffset = dev_names->wDeviceOffset + printer_size;\n memcpy(reinterpret_cast<uint8*>(dev_names_ptr) + dev_names->wOutputOffset,\n info_2->pPortName, port_size);\n GlobalUnlock(lppd->hDevNames);\n\n return S_OK;\n}\n\nTEST_F(PrintingContextTest, Base) {\n printing::PrintSettings settings;\n\n settings.set_device_name(GetDefaultPrinter());\n \/\/ Initialize it.\n scoped_ptr<printing::PrintingContext> context(\n printing::PrintingContext::Create());\n EXPECT_EQ(printing::PrintingContext::OK, context->InitWithSettings(settings));\n\n \/\/ The print may lie to use and may not support world transformation.\n \/\/ Verify right now.\n XFORM random_matrix = { 1, 0.1f, 0, 1.5f, 0, 1 };\n EXPECT_TRUE(SetWorldTransform(context->context(), &random_matrix));\n EXPECT_TRUE(ModifyWorldTransform(context->context(), NULL, MWT_IDENTITY));\n}\n\n\/\/ http:\/\/crbug.com\/61499\nTEST_F(PrintingContextTest, FLAKY_PrintAll) {\n printing::PrintingContextWin context;\n context.SetPrintDialog(&PrintDlgExMock);\n context.AskUserForSettings(\n NULL,\n 123,\n false,\n NewCallback(static_cast<PrintingContextTest*>(this),\n &PrintingContextTest::PrintSettingsCallback));\n ASSERT_EQ(printing::PrintingContext::OK, result());\n printing::PrintSettings settings = context.settings();\n EXPECT_EQ(settings.ranges.size(), 0);\n}\n<|endoftext|>"} {"text":"<commit_before>#include <opencv2\/features2d.hpp>\n#include <opencv2\/videoio.hpp>\n#include <opencv2\/opencv.hpp>\n#include <vector>\n#include <iostream>\n#include <iomanip>\n\n#include \"stats.h\" \/\/ Stats structure definition\n#include \"utils.h\" \/\/ Drawing and printing functions\n\nusing namespace std;\nusing namespace cv;\n\nconst double akaze_thresh = 3e-4; \/\/ AKAZE detection threshold set to locate about 1000 keypoints\nconst double ransac_thresh = 2.5f; \/\/ RANSAC inlier threshold\nconst double nn_match_ratio = 0.8f; \/\/ Nearest-neighbour matching ratio\nconst int bb_min_inliers = 100; \/\/ Minimal number of inliers to draw bounding box\nconst int stats_update_period = 10; \/\/ On-screen statistics are updated every 10 frames\n\nclass Tracker\n{\npublic:\n Tracker(Ptr<Feature2D> _detector, Ptr<DescriptorMatcher> _matcher) :\n detector(_detector),\n matcher(_matcher)\n {}\n\n void setFirstFrame(const Mat frame, vector<Point2f> bb, string title, Stats& stats);\n Mat process(const Mat frame, Stats& stats);\n Ptr<Feature2D> getDetector() {\n return detector;\n }\nprotected:\n Ptr<Feature2D> detector;\n Ptr<DescriptorMatcher> matcher;\n Mat first_frame, first_desc;\n vector<KeyPoint> first_kp;\n vector<Point2f> object_bb;\n};\n\nvoid Tracker::setFirstFrame(const Mat frame, vector<Point2f> bb, string title, Stats& stats)\n{\n first_frame = frame.clone();\n detector->detectAndCompute(first_frame, noArray(), first_kp, first_desc);\n stats.keypoints = (int)first_kp.size();\n drawBoundingBox(first_frame, bb);\n putText(first_frame, title, Point(0, 60), FONT_HERSHEY_PLAIN, 5, Scalar::all(0), 4);\n object_bb = bb;\n}\n\nMat Tracker::process(const Mat frame, Stats& stats)\n{\n vector<KeyPoint> kp;\n Mat desc;\n detector->detectAndCompute(frame, noArray(), kp, desc);\n stats.keypoints = (int)kp.size();\n\n vector< vector<DMatch> > matches;\n vector<KeyPoint> matched1, matched2;\n matcher->knnMatch(first_desc, desc, matches, 2);\n for(unsigned i = 0; i < matches.size(); i++) {\n if(matches[i][0].distance < nn_match_ratio * matches[i][1].distance) {\n matched1.push_back(first_kp[matches[i][0].queryIdx]);\n matched2.push_back( kp[matches[i][0].trainIdx]);\n }\n }\n stats.matches = (int)matched1.size();\n\n Mat inlier_mask, homography;\n vector<KeyPoint> inliers1, inliers2;\n vector<DMatch> inlier_matches;\n if(matched1.size() >= 4) {\n homography = findHomography(Points(matched1), Points(matched2),\n RANSAC, ransac_thresh, inlier_mask);\n }\n\n if(matched1.size() < 4 || homography.empty()) {\n Mat res;\n hconcat(first_frame, frame, res);\n stats.inliers = 0;\n stats.ratio = 0;\n return res;\n }\n for(unsigned i = 0; i < matched1.size(); i++) {\n if(inlier_mask.at<uchar>(i)) {\n int new_i = static_cast<int>(inliers1.size());\n inliers1.push_back(matched1[i]);\n inliers2.push_back(matched2[i]);\n inlier_matches.push_back(DMatch(new_i, new_i, 0));\n }\n }\n stats.inliers = (int)inliers1.size();\n stats.ratio = stats.inliers * 1.0 \/ stats.matches;\n\n vector<Point2f> new_bb;\n perspectiveTransform(object_bb, new_bb, homography);\n Mat frame_with_bb = frame.clone();\n if(stats.inliers >= bb_min_inliers) {\n drawBoundingBox(frame_with_bb, new_bb);\n }\n Mat res;\n drawMatches(first_frame, inliers1, frame_with_bb, inliers2,\n inlier_matches, res,\n Scalar(255, 0, 0), Scalar(255, 0, 0));\n return res;\n}\n\nint main(int argc, char **argv)\n{\n if(argc < 4) {\n cerr << \"Usage: \" << endl <<\n \"akaze_track input_path output_path bounding_box\" << endl;\n return 1;\n }\n VideoCapture video_in(argv[1]);\n VideoWriter video_out(argv[2],\n (int)video_in.get(CAP_PROP_FOURCC),\n (int)video_in.get(CAP_PROP_FPS),\n Size(2 * (int)video_in.get(CAP_PROP_FRAME_WIDTH),\n 2 * (int)video_in.get(CAP_PROP_FRAME_HEIGHT)));\n\n if(!video_in.isOpened()) {\n cerr << \"Couldn't open \" << argv[1] << endl;\n return 1;\n }\n if(!video_out.isOpened()) {\n cerr << \"Couldn't open \" << argv[2] << endl;\n return 1;\n }\n\n vector<Point2f> bb;\n FileStorage fs(argv[3], FileStorage::READ);\n if(fs[\"bounding_box\"].empty()) {\n cerr << \"Couldn't read bounding_box from \" << argv[3] << endl;\n return 1;\n }\n fs[\"bounding_box\"] >> bb;\n\n Stats stats, akaze_stats, orb_stats;\n Ptr<AKAZE> akaze = AKAZE::create();\n akaze->setThreshold(akaze_thresh);\n Ptr<ORB> orb = ORB::create();\n orb->setMaxFeatures(stats.keypoints);\n Ptr<DescriptorMatcher> matcher = DescriptorMatcher::create(\"BruteForce-Hamming\");\n Tracker akaze_tracker(akaze, matcher);\n Tracker orb_tracker(orb, matcher);\n\n Mat frame;\n video_in >> frame;\n akaze_tracker.setFirstFrame(frame, bb, \"AKAZE\", stats);\n orb_tracker.setFirstFrame(frame, bb, \"ORB\", stats);\n\n Stats akaze_draw_stats, orb_draw_stats;\n int frame_count = (int)video_in.get(CAP_PROP_FRAME_COUNT);\n Mat akaze_res, orb_res, res_frame;\n for(int i = 1; i < frame_count; i++) {\n bool update_stats = (i % stats_update_period == 0);\n video_in >> frame;\n\n akaze_res = akaze_tracker.process(frame, stats);\n akaze_stats += stats;\n if(update_stats) {\n akaze_draw_stats = stats;\n }\n\n orb->setMaxFeatures(stats.keypoints);\n orb_res = orb_tracker.process(frame, stats);\n orb_stats += stats;\n if(update_stats) {\n orb_draw_stats = stats;\n }\n\n drawStatistics(akaze_res, akaze_draw_stats);\n drawStatistics(orb_res, orb_draw_stats);\n vconcat(akaze_res, orb_res, res_frame);\n video_out << res_frame;\n cout << i << \"\/\" << frame_count - 1 << endl;\n }\n akaze_stats \/= frame_count - 1;\n orb_stats \/= frame_count - 1;\n printStatistics(\"AKAZE\", akaze_stats);\n printStatistics(\"ORB\", orb_stats);\n return 0;\n}\n<commit_msg>- remove zero threshold that prevents ORB from finding any local features<commit_after>#include <opencv2\/features2d.hpp>\n#include <opencv2\/videoio.hpp>\n#include <opencv2\/opencv.hpp>\n#include <vector>\n#include <iostream>\n#include <iomanip>\n\n#include \"stats.h\" \/\/ Stats structure definition\n#include \"utils.h\" \/\/ Drawing and printing functions\n\nusing namespace std;\nusing namespace cv;\n\nconst double akaze_thresh = 3e-4; \/\/ AKAZE detection threshold set to locate about 1000 keypoints\nconst double ransac_thresh = 2.5f; \/\/ RANSAC inlier threshold\nconst double nn_match_ratio = 0.8f; \/\/ Nearest-neighbour matching ratio\nconst int bb_min_inliers = 100; \/\/ Minimal number of inliers to draw bounding box\nconst int stats_update_period = 10; \/\/ On-screen statistics are updated every 10 frames\n\nclass Tracker\n{\npublic:\n Tracker(Ptr<Feature2D> _detector, Ptr<DescriptorMatcher> _matcher) :\n detector(_detector),\n matcher(_matcher)\n {}\n\n void setFirstFrame(const Mat frame, vector<Point2f> bb, string title, Stats& stats);\n Mat process(const Mat frame, Stats& stats);\n Ptr<Feature2D> getDetector() {\n return detector;\n }\nprotected:\n Ptr<Feature2D> detector;\n Ptr<DescriptorMatcher> matcher;\n Mat first_frame, first_desc;\n vector<KeyPoint> first_kp;\n vector<Point2f> object_bb;\n};\n\nvoid Tracker::setFirstFrame(const Mat frame, vector<Point2f> bb, string title, Stats& stats)\n{\n first_frame = frame.clone();\n detector->detectAndCompute(first_frame, noArray(), first_kp, first_desc);\n stats.keypoints = (int)first_kp.size();\n drawBoundingBox(first_frame, bb);\n putText(first_frame, title, Point(0, 60), FONT_HERSHEY_PLAIN, 5, Scalar::all(0), 4);\n object_bb = bb;\n}\n\nMat Tracker::process(const Mat frame, Stats& stats)\n{\n vector<KeyPoint> kp;\n Mat desc;\n detector->detectAndCompute(frame, noArray(), kp, desc);\n stats.keypoints = (int)kp.size();\n\n vector< vector<DMatch> > matches;\n vector<KeyPoint> matched1, matched2;\n matcher->knnMatch(first_desc, desc, matches, 2);\n for(unsigned i = 0; i < matches.size(); i++) {\n if(matches[i][0].distance < nn_match_ratio * matches[i][1].distance) {\n matched1.push_back(first_kp[matches[i][0].queryIdx]);\n matched2.push_back( kp[matches[i][0].trainIdx]);\n }\n }\n stats.matches = (int)matched1.size();\n\n Mat inlier_mask, homography;\n vector<KeyPoint> inliers1, inliers2;\n vector<DMatch> inlier_matches;\n if(matched1.size() >= 4) {\n homography = findHomography(Points(matched1), Points(matched2),\n RANSAC, ransac_thresh, inlier_mask);\n }\n\n if(matched1.size() < 4 || homography.empty()) {\n Mat res;\n hconcat(first_frame, frame, res);\n stats.inliers = 0;\n stats.ratio = 0;\n return res;\n }\n for(unsigned i = 0; i < matched1.size(); i++) {\n if(inlier_mask.at<uchar>(i)) {\n int new_i = static_cast<int>(inliers1.size());\n inliers1.push_back(matched1[i]);\n inliers2.push_back(matched2[i]);\n inlier_matches.push_back(DMatch(new_i, new_i, 0));\n }\n }\n stats.inliers = (int)inliers1.size();\n stats.ratio = stats.inliers * 1.0 \/ stats.matches;\n\n vector<Point2f> new_bb;\n perspectiveTransform(object_bb, new_bb, homography);\n Mat frame_with_bb = frame.clone();\n if(stats.inliers >= bb_min_inliers) {\n drawBoundingBox(frame_with_bb, new_bb);\n }\n Mat res;\n drawMatches(first_frame, inliers1, frame_with_bb, inliers2,\n inlier_matches, res,\n Scalar(255, 0, 0), Scalar(255, 0, 0));\n return res;\n}\n\nint main(int argc, char **argv)\n{\n if(argc < 4) {\n cerr << \"Usage: \" << endl <<\n \"akaze_track input_path output_path bounding_box\" << endl;\n return 1;\n }\n VideoCapture video_in(argv[1]);\n VideoWriter video_out(argv[2],\n (int)video_in.get(CAP_PROP_FOURCC),\n (int)video_in.get(CAP_PROP_FPS),\n Size(2 * (int)video_in.get(CAP_PROP_FRAME_WIDTH),\n 2 * (int)video_in.get(CAP_PROP_FRAME_HEIGHT)));\n\n if(!video_in.isOpened()) {\n cerr << \"Couldn't open \" << argv[1] << endl;\n return 1;\n }\n if(!video_out.isOpened()) {\n cerr << \"Couldn't open \" << argv[2] << endl;\n return 1;\n }\n\n vector<Point2f> bb;\n FileStorage fs(argv[3], FileStorage::READ);\n if(fs[\"bounding_box\"].empty()) {\n cerr << \"Couldn't read bounding_box from \" << argv[3] << endl;\n return 1;\n }\n fs[\"bounding_box\"] >> bb;\n\n Stats stats, akaze_stats, orb_stats;\n Ptr<AKAZE> akaze = AKAZE::create();\n akaze->setThreshold(akaze_thresh);\n Ptr<ORB> orb = ORB::create();\n Ptr<DescriptorMatcher> matcher = DescriptorMatcher::create(\"BruteForce-Hamming\");\n Tracker akaze_tracker(akaze, matcher);\n Tracker orb_tracker(orb, matcher);\n\n Mat frame;\n video_in >> frame;\n akaze_tracker.setFirstFrame(frame, bb, \"AKAZE\", stats);\n orb_tracker.setFirstFrame(frame, bb, \"ORB\", stats);\n\n Stats akaze_draw_stats, orb_draw_stats;\n int frame_count = (int)video_in.get(CAP_PROP_FRAME_COUNT);\n Mat akaze_res, orb_res, res_frame;\n for(int i = 1; i < frame_count; i++) {\n bool update_stats = (i % stats_update_period == 0);\n video_in >> frame;\n\n akaze_res = akaze_tracker.process(frame, stats);\n akaze_stats += stats;\n if(update_stats) {\n akaze_draw_stats = stats;\n }\n\n orb->setMaxFeatures(stats.keypoints);\n orb_res = orb_tracker.process(frame, stats);\n orb_stats += stats;\n if(update_stats) {\n orb_draw_stats = stats;\n }\n\n drawStatistics(akaze_res, akaze_draw_stats);\n drawStatistics(orb_res, orb_draw_stats);\n vconcat(akaze_res, orb_res, res_frame);\n video_out << res_frame;\n cout << i << \"\/\" << frame_count - 1 << endl;\n }\n akaze_stats \/= frame_count - 1;\n orb_stats \/= frame_count - 1;\n printStatistics(\"AKAZE\", akaze_stats);\n printStatistics(\"ORB\", orb_stats);\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"axisstepper.h\"\n\nnamespace drv {\n\nEvent AxisStepper::getEvent() const {\n\treturn Event::StepperEvent(this->time, this->index(), this->direction);\n}\n\nvoid AxisStepper::_nextStep() {\n\t\/\/should be implemented in derivatives.\n}\n\n}\n<commit_msg>Attempt to detect a lack of overriding of AxisStepper::_nextStep()<commit_after>#include \"axisstepper.h\"\n\nnamespace drv {\n\nEvent AxisStepper::getEvent() const {\n\treturn Event::StepperEvent(this->time, this->index(), this->direction);\n}\n\nvoid AxisStepper::_nextStep() {\n\t\/\/should be implemented in derivatives.\n\tthrow std::runtime_error(\"AxisStepper::_nextStep() must be overriden in any child classes\");\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before>#include <cstdarg>\n#include <cstdio>\n#include <ctime>\n#include <cerrno>\n#include <cstring>\n#include <sys\/utsname.h>\n#include <unistd.h>\n#include <sys\/stat.h>\n#include \"..\/utils\/utils.hpp\"\n\nenum { Bufsz = 256 };\n\nstatic const char *start4 = \"#start data file format 4\\n\";\nstatic const char *end4 = \"#end data file format 4\\n\";\n\nstatic void machineid(FILE*);\nstatic void tryprocstatus(FILE*);\n\nvoid dfpair(FILE *f, const char *key, const char *fmt, ...) {\n\tchar buf[Bufsz];\n\n\tint n = snprintf(buf, Bufsz, \"#pair \\\"%s\\\"\\t\\\"\", key);\n\n\tva_list ap;\n\tva_start(ap, fmt);\n\tn += vsnprintf(buf+n, Bufsz-n, fmt, ap);\n\tva_end(ap);\n\n\tfprintf(f, \"%s\\\"\\n\", buf);\n}\n\nvoid dfrowhdr(FILE *f, const char *name, int ncols, ...) {\n\tchar buf[Bufsz];\n\tint n = snprintf(buf, Bufsz, \"#altcols \\\"%s\\\"\", name);\n\n\tva_list ap;\n\tva_start(ap, ncols);\n\tfor (int i = 0; i < ncols; i++) {\n\t\tchar *col = va_arg(ap, char*);\n\t\tn += snprintf(buf+n, Bufsz-n, \"\\t\\\"%s\\\"\", col);\n\t}\n\tva_end(ap);\n\n\tfprintf(f, \"%s\\n\", buf);\n}\n\nvoid dfrow(FILE *f, const char *name, const char *colfmt, ...) {\n\tchar buf[Bufsz];\n\tint n = snprintf(buf, Bufsz, \"#altrow \\\"%s\\\"\", name);\n\n\tva_list ap;\n\tva_start(ap, colfmt);\n\tfor (unsigned int i = 0; i < strlen(colfmt); i++) {\n\t\tdouble g = 0;\n\t\tlong d = 0;\n\t\tunsigned long u = 0;\n\t\tswitch (colfmt[i]) {\n\t\tcase 'g':\n\t\t\tg = va_arg(ap, double);\n\t\t\tn += snprintf(buf+n, Bufsz-n, \"\\t%g\", g);\n\t\t\tbreak;\n\t\tcase 'f':\n\t\t\tg = va_arg(ap, double);\n\t\t\tn += snprintf(buf+n, Bufsz-n, \"\\t%lf\", g);\n\t\t\tbreak;\n\t\tcase 'd':\n\t\t\td = va_arg(ap, long);\n\t\t\tn += snprintf(buf+n, Bufsz-n, \"\\t%ld\", d);\n\t\t\tbreak;\n\t\tcase 'u':\n\t\t\tu = va_arg(ap, unsigned long);\n\t\t\tn += snprintf(buf+n, Bufsz-n, \"\\t%lu\", u);\n\t\t\tbreak;\n\t\t}\n\t}\n\tva_end(ap);\n\n\tfprintf(f, \"%s\\n\", buf);\n}\n\nvoid dfheader(FILE *f) {\n\tfputs(start4, f);\n\n\ttime_t tm;\n\ttime(&tm);\n\tchar *tstr = ctime(&tm);\n\ttstr[strlen(tstr)-1] = '\\0';\n\tdfpair(f, \"wall start date\", \"%s\", tstr);\n\n\tdfpair(f, \"wall start time\", \"%g\", walltime());\n\tmachineid(f);\n}\n\nvoid dffooter(FILE *f) {\n\tdfpair(f, \"wall finish time\", \"%g\", walltime());\n\n\ttime_t tm;\n\ttime(&tm);\n\tchar *tstr = ctime(&tm);\n\ttstr[strlen(tstr)-1] = '\\0';\n\tdfpair(f, \"wall finish date\", \"%s\", tstr);\n\ttryprocstatus(f);\n\tfputs(end4, f);\n}\n\nvoid dfprocstatus(FILE *f) {\n\ttryprocstatus(f);\n}\n\nstatic void machineid(FILE *f) {\n\tchar hname[Bufsz];\n\tmemset(hname, '\\0', Bufsz);\n\tif (gethostname(hname, Bufsz) == -1) {\n\t\twarnx(errno, \"gethostname failed, unable to print machine id\\n\");\n\t\treturn;\n\t}\n\n\tstruct utsname u;\n\tif (uname(&u) == -1) {\n\t\twarnx(errno, \"uname failed\\n\");\n\t\tdfpair(f, \"machine id\", \"%s\", hname);\n\t}\n\n\tdfpair(f, \"machine id\", \"%s-%s-%s-%s\", hname, u.sysname, u.release, u.machine);\n}\n\nstatic void tryprocstatus(FILE *out)\n{\n\tstatic const char *field = \"VmPeak:\";\n\tstatic const char *key = \"max virtual kilobytes\";\n\tchar buf[Bufsz];\n\n\tint n = snprintf(buf, Bufsz, \"\/proc\/%d\/status\", getpid());\n\tif (n <= 0 || n > Bufsz)\n\t\treturn;\n\n\tstruct stat sb;\n\tif (stat(buf, &sb) < 0)\n\t\treturn;\n\n\tFILE *in = fopen(buf, \"r\");\n\n\tfor (;;) {\n\t\tif (!fgets(buf, Bufsz, in))\n\t\t\tbreak;\n\t\tif (!strstr(buf, field))\n\t\t\tcontinue;\n\t\tsize_t skip = strspn(buf + strlen(field), \" \\t\");\n\t\tchar *strt = buf + strlen(field) + skip;\n\t\tchar *end = strchr(strt, ' ');\n\t\t*end = '\\0';\n\t\tdfpair(out, key, \"%s\", strt);\n\t\tbreak;\n\t}\n\n\tfclose(in);\n}\n<commit_msg>Fatal when datafile functions overflow the buffer. dfpair has a dynamic buffer.<commit_after>#include <cstdarg>\n#include <cstdio>\n#include <ctime>\n#include <cstdlib>\n#include <cerrno>\n#include <cstring>\n#include <cassert>\n#include <sys\/utsname.h>\n#include <unistd.h>\n#include <sys\/stat.h>\n#include \"..\/utils\/utils.hpp\"\n\nenum { Bufsz = 256 };\n\nstatic const char *start4 = \"#start data file format 4\\n\";\nstatic const char *end4 = \"#end data file format 4\\n\";\n\nstatic void dfpair_sz(FILE*, unsigned int, const char*, const char*, va_list);\nstatic void machineid(FILE*);\nstatic void tryprocstatus(FILE*);\n\nvoid dfpair(FILE *f, const char *key, const char *fmt, ...) {\n\tchar buf[Bufsz];\n\tint n = snprintf(buf, Bufsz, \"#pair \\\"%s\\\"\\t\\\"\", key);\n\tif (n > Bufsz)\n\t\tfatal(\"dfrowhdr: buffer is too small\\n\");\n\n\tva_list ap;\n\tva_start(ap, fmt);\n\tunsigned int m = vsnprintf(buf+n, Bufsz-n, fmt, ap);\n\tva_end(ap);\n\n\tif (m > (unsigned int) Bufsz-n) {\t\/\/ Err, overflow\n\t\tva_start(ap, fmt);\n\t\tdfpair_sz(f, m + n + 1, key, fmt, ap);\n\t\tva_end(ap);\n\t\treturn;\n\t}\n\n\tfprintf(f, \"%s\\\"\\n\", buf);\n}\n\nstatic void dfpair_sz(FILE *f, unsigned int sz, const char *key, const char *fmt, va_list ap) {\n\tchar *buf = (char*) malloc(sz * sizeof(*buf));\n\n\tunsigned int n = snprintf(buf, sz, \"#pair \\\"%s\\\"\\t\\\"\", key);\n\tassert (n <= sz);\n\tvsnprintf(buf+n, sz-n, fmt, ap);\n\n\tfprintf(f, \"%s\\\"\\n\", buf);\n\tfree(buf);\n}\n\nvoid dfrowhdr(FILE *f, const char *name, int ncols, ...) {\n\tchar buf[Bufsz];\n\tint n = snprintf(buf, Bufsz, \"#altcols \\\"%s\\\"\", name);\n\tif (n > Bufsz)\n\t\tfatal(\"dfrowhdr: buffer is too small\\n\");\n\n\tva_list ap;\n\tva_start(ap, ncols);\n\tfor (int i = 0; i < ncols; i++) {\n\t\tchar *col = va_arg(ap, char*);\n\t\tunsigned int m = snprintf(buf+n, Bufsz-n, \"\\t\\\"%s\\\"\", col);\n\t\tif (m > (unsigned int) Bufsz - n)\n\t\t\tfatal(\"dfrowhdr: buffer is too small\\n\");\n\t\tn += m;\n\t}\n\tva_end(ap);\n\n\tfprintf(f, \"%s\\n\", buf);\n}\n\nvoid dfrow(FILE *f, const char *name, const char *colfmt, ...) {\n\tchar buf[Bufsz];\n\tint n = snprintf(buf, Bufsz, \"#altrow \\\"%s\\\"\", name);\n\tif (n > Bufsz)\n\t\tfatal(\"dfrowhdr: buffer is too small\\n\");\n\n\tva_list ap;\n\tva_start(ap, colfmt);\n\tfor (unsigned int i = 0; i < strlen(colfmt); i++) {\n\t\tdouble g = 0;\n\t\tlong d = 0;\n\t\tunsigned long u = 0;\n\t\tunsigned int m = 0;\n\t\tswitch (colfmt[i]) {\n\t\tcase 'g':\n\t\t\tg = va_arg(ap, double);\n\t\t\tm = snprintf(buf+n, Bufsz-n, \"\\t%g\", g);\n\t\t\tbreak;\n\t\tcase 'f':\n\t\t\tg = va_arg(ap, double);\n\t\t\tm = snprintf(buf+n, Bufsz-n, \"\\t%lf\", g);\n\t\t\tbreak;\n\t\tcase 'd':\n\t\t\td = va_arg(ap, long);\n\t\t\tm = snprintf(buf+n, Bufsz-n, \"\\t%ld\", d);\n\t\t\tbreak;\n\t\tcase 'u':\n\t\t\tu = va_arg(ap, unsigned long);\n\t\t\tm = snprintf(buf+n, Bufsz-n, \"\\t%lu\", u);\n\t\t\tbreak;\n\t\t}\n\t\tif (m > (unsigned int) Bufsz-n)\n\t\t\tfatal(\"dfrow: buffer is too small\\n\");\n\t\tn += m;\n\t}\n\tva_end(ap);\n\n\tfprintf(f, \"%s\\n\", buf);\n}\n\nvoid dfheader(FILE *f) {\n\tfputs(start4, f);\n\n\ttime_t tm;\n\ttime(&tm);\n\tchar *tstr = ctime(&tm);\n\ttstr[strlen(tstr)-1] = '\\0';\n\tdfpair(f, \"wall start date\", \"%s\", tstr);\n\n\tdfpair(f, \"wall start time\", \"%g\", walltime());\n\tmachineid(f);\n}\n\nvoid dffooter(FILE *f) {\n\tdfpair(f, \"wall finish time\", \"%g\", walltime());\n\n\ttime_t tm;\n\ttime(&tm);\n\tchar *tstr = ctime(&tm);\n\ttstr[strlen(tstr)-1] = '\\0';\n\tdfpair(f, \"wall finish date\", \"%s\", tstr);\n\ttryprocstatus(f);\n\tfputs(end4, f);\n}\n\nvoid dfprocstatus(FILE *f) {\n\ttryprocstatus(f);\n}\n\nstatic void machineid(FILE *f) {\n\tchar hname[Bufsz];\n\tmemset(hname, '\\0', Bufsz);\n\tif (gethostname(hname, Bufsz) == -1) {\n\t\twarnx(errno, \"gethostname failed, unable to print machine id\\n\");\n\t\treturn;\n\t}\n\n\tstruct utsname u;\n\tif (uname(&u) == -1) {\n\t\twarnx(errno, \"uname failed\\n\");\n\t\tdfpair(f, \"machine id\", \"%s\", hname);\n\t}\n\n\tdfpair(f, \"machine id\", \"%s-%s-%s-%s\", hname, u.sysname, u.release, u.machine);\n}\n\nstatic void tryprocstatus(FILE *out)\n{\n\tstatic const char *field = \"VmPeak:\";\n\tstatic const char *key = \"max virtual kilobytes\";\n\tchar buf[Bufsz];\n\n\tint n = snprintf(buf, Bufsz, \"\/proc\/%d\/status\", getpid());\n\tif (n <= 0 || n > Bufsz)\n\t\treturn;\n\n\tstruct stat sb;\n\tif (stat(buf, &sb) < 0)\n\t\treturn;\n\n\tFILE *in = fopen(buf, \"r\");\n\n\tfor (;;) {\n\t\tif (!fgets(buf, Bufsz, in))\n\t\t\tbreak;\n\t\tif (!strstr(buf, field))\n\t\t\tcontinue;\n\t\tsize_t skip = strspn(buf + strlen(field), \" \\t\");\n\t\tchar *strt = buf + strlen(field) + skip;\n\t\tchar *end = strchr(strt, ' ');\n\t\t*end = '\\0';\n\t\tdfpair(out, key, \"%s\", strt);\n\t\tbreak;\n\t}\n\n\tfclose(in);\n}\n<|endoftext|>"} {"text":"<commit_before>\/*=========================================================================\n\n Program: ORFEO Toolbox\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n\n Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.\n See OTBCopyright.txt for details.\n\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notices for more information.\n\n =========================================================================*\/\n\n#include \"otbWrapperApplication.h\"\n#include \"otbWrapperApplicationFactory.h\"\n\n#include \"otbVectorImage.h\"\n#include \"otbImage.h\"\n#include \"itkEuclideanDistance.h\"\n#include \"itkImageRegionSplitter.h\"\n#include \"otbStreamingTraits.h\"\n#include \"otbKMeansImageClassificationFilter.h\"\n#include \"itkImageRegionConstIterator.h\"\n#include \"itkListSample.h\"\n#include \"itkWeightedCentroidKdTreeGenerator.h\"\n#include \"itkKdTreeBasedKmeansEstimator.h\"\n#include \"itkMersenneTwisterRandomVariateGenerator.h\"\n\nnamespace otb\n{\nnamespace Wrapper\n{\n\ntypedef FloatImageType::PixelType PixelType;\n\ntypedef itk::FixedArray<PixelType, 108> SampleType;\ntypedef itk::Statistics::ListSample<SampleType> ListSampleType;\ntypedef itk::Statistics::WeightedCentroidKdTreeGenerator<ListSampleType> TreeGeneratorType;\ntypedef TreeGeneratorType::KdTreeType TreeType;\ntypedef itk::Statistics::KdTreeBasedKmeansEstimator<TreeType> EstimatorType;\n\ntypedef otb::StreamingTraits<FloatVectorImageType> StreamingTraitsType;\ntypedef itk::ImageRegionSplitter<2> SplitterType;\ntypedef FloatImageType::RegionType RegionType;\n\ntypedef itk::ImageRegionConstIterator<FloatVectorImageType> IteratorType;\ntypedef itk::ImageRegionConstIterator<UInt8ImageType> LabeledIteratorType;\n\ntypedef otb::KMeansImageClassificationFilter<FloatVectorImageType, UInt8ImageType, 108> ClassificationFilterType;\n\nclass KMeansClassification: public Application\n{\npublic:\n \/** Standard class typedefs. *\/\n typedef KMeansClassification Self;\n typedef Application Superclass;\n typedef itk::SmartPointer<Self> Pointer;\n typedef itk::SmartPointer<const Self> ConstPointer;\n\n \/** Standard macro *\/\n itkNewMacro(Self);\n\n itkTypeMacro(KMeansClassification, otb::Application);\n\nprivate:\n KMeansClassification()\n {\n SetName(\"KMeansClassification\");\n SetDescription(\"Unsupervised KMeans image classification.\");\n }\n\n virtual ~KMeansClassification()\n {\n }\n\n void DoCreateParameters()\n {\n\n AddParameter(ParameterType_InputImage, \"in\", \"Input Image\");\n AddParameter(ParameterType_OutputImage, \"out\", \"Output Image\");\n AddParameter(ParameterType_InputImage, \"vm\", \"Validity Mask\");\n AddParameter(ParameterType_Int, \"ts\", \"Size of the training set\");\n SetParameterInt(\"ts\", 100);\n AddParameter(ParameterType_Float, \"tp\", \"Probability for a sample to be selected in the training set\");\n SetParameterFloat(\"tp\", 0.5);\n AddParameter(ParameterType_Int, \"nc\", \"Number of classes\");\n SetParameterInt(\"nc\", 3);\n AddParameter(ParameterType_Float, \"cp\", \"Probability for a pixel to be selected as an initial class centroid\");\n SetParameterFloat(\"cp\", 0.8);\n AddParameter(ParameterType_Int, \"sl\", \"Number of lines for each streaming block\");\n SetParameterInt(\"sl\", 1000);\n }\n\n void DoUpdateParameters()\n {\n \/\/ Nothing to do here : all parameters are independent\n }\n\n void DoExecute()\n {\n GetLogger()->Debug(\"Entering DoExecute\\n\");\n\n \/\/ initiating random number generation\n itk::Statistics::MersenneTwisterRandomVariateGenerator::Pointer\n randomGen = itk::Statistics::MersenneTwisterRandomVariateGenerator::New();\n m_InImage = GetParameterImage(\"in\");\n std::cout<<\"mask in progress\"<<std::endl;\n\n UInt8ImageType::Pointer maskImage = GetParameterUInt8Image(\"vm\");\n\n std::cout<<\"mask in progress done\"<<std::endl;\n std::ostringstream message(\"\");\n\n const unsigned int nbsamples = GetParameterInt(\"ts\");\n const double trainingProb = GetParameterFloat(\"tp\");\n const double initProb = GetParameterFloat(\"cp\");\n const unsigned int nb_classes = GetParameterInt(\"nc\");\n const unsigned int nbLinesForStreaming = GetParameterInt(\"sl\");\n\n \/*******************************************\/\n \/* Sampling data *\/\n \/*******************************************\/\n GetLogger()->Info(\"-- SAMPLING DATA --\");\n\n \/\/ Update input images information\n m_InImage->UpdateOutputInformation();\n maskImage->UpdateOutputInformation();\n\n if (m_InImage->GetLargestPossibleRegion() != maskImage->GetLargestPossibleRegion())\n {\n GetLogger()->Error(\"Mask image and input image have different sizes.\");\n }\n\n RegionType largestRegion = m_InImage->GetLargestPossibleRegion();\n\n \/\/ Setting up local streaming capabilities\n SplitterType::Pointer splitter = SplitterType::New();\n unsigned int\n numberOfStreamDivisions = StreamingTraitsType::CalculateNumberOfStreamDivisions(\n m_InImage,\n largestRegion,\n splitter,\n otb::SET_BUFFER_NUMBER_OF_LINES,\n 0, 0, nbLinesForStreaming);\n\n message.clear();\n message << \"The images will be streamed into \" << numberOfStreamDivisions << \" parts.\";\n GetLogger()->Info(message.str());\n\n \/\/ Training sample lists\n ListSampleType::Pointer sampleList = ListSampleType::New();\n EstimatorType::ParametersType initialMeans(108 * nb_classes);\n initialMeans.Fill(0);\n unsigned int init_means_index = 0;\n\n \/\/ Sample dimension and max dimension\n unsigned int maxDimension = SampleType::Dimension;\n unsigned int sampleSize = std::min(m_InImage->GetNumberOfComponentsPerPixel(), maxDimension);\n unsigned int totalSamples = 0;\n\n message.clear();\n message << \"Sample max possible dimension: \" << maxDimension << std::endl;\n GetLogger()->Info(message.str());\n message.clear();\n message << \"The following sample size will be used: \" << sampleSize << std::endl;\n GetLogger()->Info(message.str());\n \/\/ local streaming variables\n unsigned int piece = 0;\n RegionType streamingRegion;\n\n while ((totalSamples < nbsamples) && (init_means_index < 108 * nb_classes))\n {\n double random = randomGen->GetVariateWithClosedRange();\n piece = static_cast<unsigned int> (random * numberOfStreamDivisions);\n\n streamingRegion = splitter->GetSplit(piece, numberOfStreamDivisions, largestRegion);\n\n message.clear();\n message << \"Processing region: \" << streamingRegion << std::endl;\n GetLogger()->Info(message.str());\n\n m_InImage->SetRequestedRegion(streamingRegion);\n m_InImage->PropagateRequestedRegion();\n m_InImage->UpdateOutputData();\n\n maskImage->SetRequestedRegion(streamingRegion);\n maskImage->PropagateRequestedRegion();\n maskImage->UpdateOutputData();\n\n IteratorType it(m_InImage, streamingRegion);\n LabeledIteratorType m_MaskIt(maskImage, streamingRegion);\n\n it.GoToBegin();\n m_MaskIt.GoToBegin();\n\n unsigned int localNbSamples = 0;\n\n \/\/ Loop on the image\n while (!it.IsAtEnd() && !m_MaskIt.IsAtEnd() && (totalSamples < nbsamples)\n && (init_means_index < (108 * nb_classes)))\n {\n \/\/ If the current pixel is labeled\n if (m_MaskIt.Get() > 0)\n {\n if ((rand() < trainingProb * RAND_MAX))\n {\n SampleType newSample;\n\n \/\/ build the sample\n newSample.Fill(0);\n for (unsigned int i = 0; i < sampleSize; ++i)\n {\n newSample[i] = it.Get()[i];\n }\n \/\/ Update the the sample lists\n sampleList->PushBack(newSample);\n ++totalSamples;\n ++localNbSamples;\n }\n else\n if ((init_means_index < 108 * nb_classes) && (rand() < initProb * RAND_MAX))\n {\n for (unsigned int i = 0; i < sampleSize; ++i)\n {\n initialMeans[init_means_index + i] = it.Get()[i];\n }\n init_means_index += 108;\n }\n }\n ++it;\n ++m_MaskIt;\n }\n\n message.clear();\n message << localNbSamples << \" samples added to the training set.\" << std::endl;\n GetLogger()->Info(message.str());\n\n }\n\n message.clear();\n message << \"The final training set contains \" << totalSamples << \" samples.\" << std::endl;\n GetLogger()->Info(message.str());\n\n message.clear();\n message << \"Data sampling completed.\" << std::endl;\n GetLogger()->Info(message.str());\n\n \/*******************************************\/\n \/* Learning *\/\n \/*******************************************\/\n message.clear();\n message << \"-- LEARNING --\" << std::endl;\n message << \"Initial centroids are: \" << std::endl;\n GetLogger()->Info(message.str());\n message.clear();\n for (unsigned int i = 0; i < nb_classes; ++i)\n {\n message << \"Class \" << i << \": \";\n for (unsigned int j = 0; j < sampleSize; ++j)\n {\n message << initialMeans[i * 108 + j] << \"\\t\";\n }\n message << std::endl;\n }\n message << std::endl;\n\n message.clear();\n message << \"Starting optimization.\" << std::endl;\n message << std::endl;\n GetLogger()->Info(message.str());\n\n EstimatorType::Pointer estimator = EstimatorType::New();\n\n TreeGeneratorType::Pointer treeGenerator = TreeGeneratorType::New();\n treeGenerator->SetSample(sampleList);\n treeGenerator->SetBucketSize(100);\n treeGenerator->Update();\n\n estimator->SetParameters(initialMeans);\n estimator->SetKdTree(treeGenerator->GetOutput());\n estimator->SetMaximumIteration(100000000);\n estimator->SetCentroidPositionChangesThreshold(0.001);\n estimator->StartOptimization();\n\n EstimatorType::ParametersType estimatedMeans = estimator->GetParameters();\n message.clear();\n message << \"Optimization completed.\" << std::endl;\n message << std::endl;\n message << \"Estimated centroids are: \" << std::endl;\n\n for (unsigned int i = 0; i < nb_classes; ++i)\n {\n message << \"Class \" << i << \": \";\n for (unsigned int j = 0; j < sampleSize; ++j)\n {\n message << estimatedMeans[i * 108 + j] << \"\\t\";\n }\n message << std::endl;\n }\n\n message << std::endl;\n message << \"Learning completed.\" << std::endl;\n message << std::endl;\n GetLogger()->Info(message.str());\n\n \/*******************************************\/\n \/* Classification *\/\n \/*******************************************\/\n message.clear();\n message << \"-- CLASSIFICATION --\" << std::endl;\n message << std::endl;\n GetLogger()->Info(message.str());\n\n m_Classifier = ClassificationFilterType::New();\n\n m_Classifier->SetInput(m_InImage);\n m_Classifier->SetInputMask(maskImage);\n\n m_Classifier->SetCentroids(estimator->GetParameters());\n\n SetParameterOutputImage<UInt8ImageType> (\"out\", m_Classifier->GetOutput());\n\n }\n\n ClassificationFilterType::Pointer m_Classifier;\n FloatVectorImageType::Pointer m_InImage;\n\n\n};\n\n}\n}\n\nOTB_APPLICATION_EXPORT(otb::Wrapper::KMeansClassification)\n\n\n\n<commit_msg>DOC : KMeans Classification Qt application doc update.<commit_after>\/*=========================================================================\n\n Program: ORFEO Toolbox\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n\n Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.\n See OTBCopyright.txt for details.\n\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notices for more information.\n\n =========================================================================*\/\n\n#include \"otbWrapperApplication.h\"\n#include \"otbWrapperApplicationFactory.h\"\n\n#include \"otbVectorImage.h\"\n#include \"otbImage.h\"\n#include \"itkEuclideanDistance.h\"\n#include \"itkImageRegionSplitter.h\"\n#include \"otbStreamingTraits.h\"\n#include \"otbKMeansImageClassificationFilter.h\"\n#include \"itkImageRegionConstIterator.h\"\n#include \"itkListSample.h\"\n#include \"itkWeightedCentroidKdTreeGenerator.h\"\n#include \"itkKdTreeBasedKmeansEstimator.h\"\n#include \"itkMersenneTwisterRandomVariateGenerator.h\"\n\nnamespace otb\n{\nnamespace Wrapper\n{\n\ntypedef FloatImageType::PixelType PixelType;\n\ntypedef itk::FixedArray<PixelType, 108> SampleType;\ntypedef itk::Statistics::ListSample<SampleType> ListSampleType;\ntypedef itk::Statistics::WeightedCentroidKdTreeGenerator<ListSampleType> TreeGeneratorType;\ntypedef TreeGeneratorType::KdTreeType TreeType;\ntypedef itk::Statistics::KdTreeBasedKmeansEstimator<TreeType> EstimatorType;\n\ntypedef otb::StreamingTraits<FloatVectorImageType> StreamingTraitsType;\ntypedef itk::ImageRegionSplitter<2> SplitterType;\ntypedef FloatImageType::RegionType RegionType;\n\ntypedef itk::ImageRegionConstIterator<FloatVectorImageType> IteratorType;\ntypedef itk::ImageRegionConstIterator<UInt8ImageType> LabeledIteratorType;\n\ntypedef otb::KMeansImageClassificationFilter<FloatVectorImageType, UInt8ImageType, 108> ClassificationFilterType;\n\nclass KMeansClassification: public Application\n{\npublic:\n \/** Standard class typedefs. *\/\n typedef KMeansClassification Self;\n typedef Application Superclass;\n typedef itk::SmartPointer<Self> Pointer;\n typedef itk::SmartPointer<const Self> ConstPointer;\n\n \/** Standard macro *\/\n itkNewMacro(Self);\n\n itkTypeMacro(KMeansClassification, otb::Application);\n\nprivate:\n KMeansClassification()\n {\n SetName(\"KMeansClassification\");\n SetDescription(\"Unsupervised KMeans image classification\");\n\n SetDocName(\"Unsupervised KMeans image classification Application\");\n SetDocLongDescription(\"Performs Unsupervised KMeans image classification.\");\n SetDocLimitations(\"None\");\n SetDocAuthors(\"OTB-Team\");\n SetDocSeeAlso(\" \");\n SetDocCLExample(\"otbApplicationLauncherCommandLine KMeansClassification \"\n \"--in ${OTB-Data}\/Input\/poupees_sub.png --vm ${OTB-Data}\/Input\/mask_KMeans.png \"\n \"--ts 100 --tp 0.6 --nc 5 --cp 0.9 --sl 100 --out ClassificationFilterOuptut.tif \");\n AddDocTag(\"Classification\");\n\n }\n\n virtual ~KMeansClassification()\n {\n }\n\n void DoCreateParameters()\n {\n\n AddParameter(ParameterType_InputImage, \"in\", \"Input Image\");\n SetParameterDescription(\"in\",\"Input image filename.\");\n AddParameter(ParameterType_OutputImage, \"out\", \"Output Image\");\n SetParameterDescription(\"out\",\"Output image filename.\");\n AddParameter(ParameterType_InputImage, \"vm\", \"Validity Mask\");\n SetParameterDescription(\"vm\",\"Validity mask. Only non-zero pixels will be used to estimate KMeans modes.\");\n AddParameter(ParameterType_Int, \"ts\", \"Training set size\");\n SetParameterDescription(\"ts\", \"Size of the training set.\");\n SetParameterInt(\"ts\", 100);\n AddParameter(ParameterType_Float, \"tp\", \"Training set sample selection probability\");\n SetParameterDescription(\"tp\", \"Probability for a sample to be selected in the training set.\");\n SetParameterFloat(\"tp\", 0.5);\n AddParameter(ParameterType_Int, \"nc\", \"Number of classes\");\n SetParameterDescription(\"nc\",\"number of modes, which will be used to generate class membership.\");\n SetParameterInt(\"nc\", 3);\n AddParameter(ParameterType_Float, \"cp\", \"Initial class centroid probability\");\n SetParameterDescription(\"cp\", \"Probability for a pixel to be selected as an initial class centroid\");\n SetParameterFloat(\"cp\", 0.8);\n AddParameter(ParameterType_Int, \"sl\", \"Number of lines for each streaming block\");\n SetParameterDescription(\"sl\",\"input image will be divided into sl lines.\");\n SetParameterInt(\"sl\", 1000);\n }\n\n void DoUpdateParameters()\n {\n \/\/ Nothing to do here : all parameters are independent\n }\n\n void DoExecute()\n {\n GetLogger()->Debug(\"Entering DoExecute\\n\");\n\n \/\/ initiating random number generation\n itk::Statistics::MersenneTwisterRandomVariateGenerator::Pointer\n randomGen = itk::Statistics::MersenneTwisterRandomVariateGenerator::New();\n m_InImage = GetParameterImage(\"in\");\n std::cout<<\"mask in progress\"<<std::endl;\n\n UInt8ImageType::Pointer maskImage = GetParameterUInt8Image(\"vm\");\n\n std::cout<<\"mask in progress done\"<<std::endl;\n std::ostringstream message(\"\");\n\n const unsigned int nbsamples = GetParameterInt(\"ts\");\n const double trainingProb = GetParameterFloat(\"tp\");\n const double initProb = GetParameterFloat(\"cp\");\n const unsigned int nb_classes = GetParameterInt(\"nc\");\n const unsigned int nbLinesForStreaming = GetParameterInt(\"sl\");\n\n \/*******************************************\/\n \/* Sampling data *\/\n \/*******************************************\/\n GetLogger()->Info(\"-- SAMPLING DATA --\");\n\n \/\/ Update input images information\n m_InImage->UpdateOutputInformation();\n maskImage->UpdateOutputInformation();\n\n if (m_InImage->GetLargestPossibleRegion() != maskImage->GetLargestPossibleRegion())\n {\n GetLogger()->Error(\"Mask image and input image have different sizes.\");\n }\n\n RegionType largestRegion = m_InImage->GetLargestPossibleRegion();\n\n \/\/ Setting up local streaming capabilities\n SplitterType::Pointer splitter = SplitterType::New();\n unsigned int\n numberOfStreamDivisions = StreamingTraitsType::CalculateNumberOfStreamDivisions(\n m_InImage,\n largestRegion,\n splitter,\n otb::SET_BUFFER_NUMBER_OF_LINES,\n 0, 0, nbLinesForStreaming);\n\n message.clear();\n message << \"The images will be streamed into \" << numberOfStreamDivisions << \" parts.\";\n GetLogger()->Info(message.str());\n\n \/\/ Training sample lists\n ListSampleType::Pointer sampleList = ListSampleType::New();\n EstimatorType::ParametersType initialMeans(108 * nb_classes);\n initialMeans.Fill(0);\n unsigned int init_means_index = 0;\n\n \/\/ Sample dimension and max dimension\n unsigned int maxDimension = SampleType::Dimension;\n unsigned int sampleSize = std::min(m_InImage->GetNumberOfComponentsPerPixel(), maxDimension);\n unsigned int totalSamples = 0;\n\n message.clear();\n message << \"Sample max possible dimension: \" << maxDimension << std::endl;\n GetLogger()->Info(message.str());\n message.clear();\n message << \"The following sample size will be used: \" << sampleSize << std::endl;\n GetLogger()->Info(message.str());\n \/\/ local streaming variables\n unsigned int piece = 0;\n RegionType streamingRegion;\n\n while ((totalSamples < nbsamples) && (init_means_index < 108 * nb_classes))\n {\n double random = randomGen->GetVariateWithClosedRange();\n piece = static_cast<unsigned int> (random * numberOfStreamDivisions);\n\n streamingRegion = splitter->GetSplit(piece, numberOfStreamDivisions, largestRegion);\n\n message.clear();\n message << \"Processing region: \" << streamingRegion << std::endl;\n GetLogger()->Info(message.str());\n\n m_InImage->SetRequestedRegion(streamingRegion);\n m_InImage->PropagateRequestedRegion();\n m_InImage->UpdateOutputData();\n\n maskImage->SetRequestedRegion(streamingRegion);\n maskImage->PropagateRequestedRegion();\n maskImage->UpdateOutputData();\n\n IteratorType it(m_InImage, streamingRegion);\n LabeledIteratorType m_MaskIt(maskImage, streamingRegion);\n\n it.GoToBegin();\n m_MaskIt.GoToBegin();\n\n unsigned int localNbSamples = 0;\n\n \/\/ Loop on the image\n while (!it.IsAtEnd() && !m_MaskIt.IsAtEnd() && (totalSamples < nbsamples)\n && (init_means_index < (108 * nb_classes)))\n {\n \/\/ If the current pixel is labeled\n if (m_MaskIt.Get() > 0)\n {\n if ((rand() < trainingProb * RAND_MAX))\n {\n SampleType newSample;\n\n \/\/ build the sample\n newSample.Fill(0);\n for (unsigned int i = 0; i < sampleSize; ++i)\n {\n newSample[i] = it.Get()[i];\n }\n \/\/ Update the the sample lists\n sampleList->PushBack(newSample);\n ++totalSamples;\n ++localNbSamples;\n }\n else\n if ((init_means_index < 108 * nb_classes) && (rand() < initProb * RAND_MAX))\n {\n for (unsigned int i = 0; i < sampleSize; ++i)\n {\n initialMeans[init_means_index + i] = it.Get()[i];\n }\n init_means_index += 108;\n }\n }\n ++it;\n ++m_MaskIt;\n }\n\n message.clear();\n message << localNbSamples << \" samples added to the training set.\" << std::endl;\n GetLogger()->Info(message.str());\n\n }\n\n message.clear();\n message << \"The final training set contains \" << totalSamples << \" samples.\" << std::endl;\n GetLogger()->Info(message.str());\n\n message.clear();\n message << \"Data sampling completed.\" << std::endl;\n GetLogger()->Info(message.str());\n\n \/*******************************************\/\n \/* Learning *\/\n \/*******************************************\/\n message.clear();\n message << \"-- LEARNING --\" << std::endl;\n message << \"Initial centroids are: \" << std::endl;\n GetLogger()->Info(message.str());\n message.clear();\n for (unsigned int i = 0; i < nb_classes; ++i)\n {\n message << \"Class \" << i << \": \";\n for (unsigned int j = 0; j < sampleSize; ++j)\n {\n message << initialMeans[i * 108 + j] << \"\\t\";\n }\n message << std::endl;\n }\n message << std::endl;\n\n message.clear();\n message << \"Starting optimization.\" << std::endl;\n message << std::endl;\n GetLogger()->Info(message.str());\n\n EstimatorType::Pointer estimator = EstimatorType::New();\n\n TreeGeneratorType::Pointer treeGenerator = TreeGeneratorType::New();\n treeGenerator->SetSample(sampleList);\n treeGenerator->SetBucketSize(100);\n treeGenerator->Update();\n\n estimator->SetParameters(initialMeans);\n estimator->SetKdTree(treeGenerator->GetOutput());\n estimator->SetMaximumIteration(100000000);\n estimator->SetCentroidPositionChangesThreshold(0.001);\n estimator->StartOptimization();\n\n EstimatorType::ParametersType estimatedMeans = estimator->GetParameters();\n message.clear();\n message << \"Optimization completed.\" << std::endl;\n message << std::endl;\n message << \"Estimated centroids are: \" << std::endl;\n\n for (unsigned int i = 0; i < nb_classes; ++i)\n {\n message << \"Class \" << i << \": \";\n for (unsigned int j = 0; j < sampleSize; ++j)\n {\n message << estimatedMeans[i * 108 + j] << \"\\t\";\n }\n message << std::endl;\n }\n\n message << std::endl;\n message << \"Learning completed.\" << std::endl;\n message << std::endl;\n GetLogger()->Info(message.str());\n\n \/*******************************************\/\n \/* Classification *\/\n \/*******************************************\/\n message.clear();\n message << \"-- CLASSIFICATION --\" << std::endl;\n message << std::endl;\n GetLogger()->Info(message.str());\n\n m_Classifier = ClassificationFilterType::New();\n\n m_Classifier->SetInput(m_InImage);\n m_Classifier->SetInputMask(maskImage);\n\n m_Classifier->SetCentroids(estimator->GetParameters());\n\n SetParameterOutputImage<UInt8ImageType> (\"out\", m_Classifier->GetOutput());\n\n }\n\n ClassificationFilterType::Pointer m_Classifier;\n FloatVectorImageType::Pointer m_InImage;\n\n\n};\n\n}\n}\n\nOTB_APPLICATION_EXPORT(otb::Wrapper::KMeansClassification)\n\n\n\n<|endoftext|>"} {"text":"<commit_before>\/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2003 Robert Osfield \n *\n * This application is open source and may be redistributed and\/or modified \n * freely and without restriction, both in commericial and non commericial applications,\n * as long as this copyright notice is maintained.\n * \n * This application is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n*\/\n\n#include <osgDB\/ReadFile>\n#include <osgUtil\/Optimizer>\n#include <osgProducer\/Viewer>\n#include <osg\/CoordinateSystemNode>\n\nint main( int argc, char **argv )\n{\n\n \/\/ use an ArgumentParser object to manage the program arguments.\n osg::ArgumentParser arguments(&argc,argv);\n \n \/\/ set up the usage document, in case we need to print out how to use this program.\n arguments.getApplicationUsage()->setApplicationName(arguments.getApplicationName());\n arguments.getApplicationUsage()->setDescription(arguments.getApplicationName()+\" is the standard OpenSceneGraph example which loads and visualises 3d models.\");\n arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+\" [options] filename ...\");\n arguments.getApplicationUsage()->addCommandLineOption(\"-h or --help\",\"Display this information\");\n \n\n \/\/ construct the viewer.\n osgProducer::Viewer viewer(arguments);\n\n \/\/ set up the value with sensible default event handlers.\n viewer.setUpViewer(osgProducer::Viewer::STANDARD_SETTINGS);\n\n \/\/ get details on keyboard and mouse bindings used by the viewer.\n viewer.getUsage(*arguments.getApplicationUsage());\n\n \/\/ if user request help write it out to cout.\n if (arguments.read(\"-h\") || arguments.read(\"--help\"))\n {\n arguments.getApplicationUsage()->write(std::cout);\n return 1;\n }\n\n \/\/ report any errors if they have occured when parsing the program aguments.\n if (arguments.errors())\n {\n arguments.writeErrorMessages(std::cout);\n return 1;\n }\n \n if (arguments.argc()<=1)\n {\n arguments.getApplicationUsage()->write(std::cout,osg::ApplicationUsage::COMMAND_LINE_OPTION);\n return 1;\n }\n\n osg::Timer_t start_tick = osg::Timer::instance()->tick();\n\n \/\/ read the scene from the list of file specified commandline args.\n osg::ref_ptr<osg::Node> loadedModel = osgDB::readNodeFiles(arguments);\n\n \/\/ if no model has been successfully loaded report failure.\n if (!loadedModel) \n {\n std::cout << arguments.getApplicationName() <<\": No data loaded\" << std::endl;\n return 1;\n }\n\n \/\/ any option left unread are converted into errors to write out later.\n arguments.reportRemainingOptionsAsUnrecognized();\n\n \/\/ report any errors if they have occured when parsing the program aguments.\n if (arguments.errors())\n {\n arguments.writeErrorMessages(std::cout);\n }\n\n osg::Timer_t end_tick = osg::Timer::instance()->tick();\n\n std::cout << \"Time to load = \"<<osg::Timer::instance()->delta_s(start_tick,end_tick)<<std::endl;\n\n \/\/ optimize the scene graph, remove rendundent nodes and state etc.\n osgUtil::Optimizer optimizer;\n optimizer.optimize(loadedModel.get());\n\n \/\/ pass the loaded scene graph to the viewer.\n viewer.setSceneData(loadedModel.get());\n\n \/\/ create the windows and run the threads.\n viewer.realize();\n\n while( !viewer.done() )\n {\n \/\/ wait for all cull and draw threads to complete.\n viewer.sync();\n\n \/\/ update the scene by traversing it with the the update visitor which will\n \/\/ call all node update callbacks and animations.\n viewer.update();\n \n \/\/ fire off the cull and draw traversals of the scene.\n viewer.frame();\n \n }\n \n \/\/ wait for all cull and draw threads to complete before exit.\n viewer.sync();\n\n return 0;\n}\n\n<commit_msg>Added --image and --dem documentation to command line parameters<commit_after>\/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2003 Robert Osfield \n *\n * This application is open source and may be redistributed and\/or modified \n * freely and without restriction, both in commericial and non commericial applications,\n * as long as this copyright notice is maintained.\n * \n * This application is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n*\/\n\n#include <osgDB\/ReadFile>\n#include <osgUtil\/Optimizer>\n#include <osgProducer\/Viewer>\n#include <osg\/CoordinateSystemNode>\n\nint main( int argc, char **argv )\n{\n\n \/\/ use an ArgumentParser object to manage the program arguments.\n osg::ArgumentParser arguments(&argc,argv);\n \n \/\/ set up the usage document, in case we need to print out how to use this program.\n arguments.getApplicationUsage()->setApplicationName(arguments.getApplicationName());\n arguments.getApplicationUsage()->setDescription(arguments.getApplicationName()+\" is the standard OpenSceneGraph example which loads and visualises 3d models.\");\n arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+\" [options] filename ...\");\n arguments.getApplicationUsage()->addCommandLineOption(\"--image <filename>\",\"Load an image and render it on a quad\");\n arguments.getApplicationUsage()->addCommandLineOption(\"--dem <filename>\",\"Load an image\/DEM and render it on a HeightField\");\n arguments.getApplicationUsage()->addCommandLineOption(\"-h or --help\",\"Display this information\");\n \n\n \/\/ construct the viewer.\n osgProducer::Viewer viewer(arguments);\n\n \/\/ set up the value with sensible default event handlers.\n viewer.setUpViewer(osgProducer::Viewer::STANDARD_SETTINGS);\n\n \/\/ get details on keyboard and mouse bindings used by the viewer.\n viewer.getUsage(*arguments.getApplicationUsage());\n\n \/\/ if user request help write it out to cout.\n if (arguments.read(\"-h\") || arguments.read(\"--help\"))\n {\n arguments.getApplicationUsage()->write(std::cout);\n return 1;\n }\n\n \/\/ report any errors if they have occured when parsing the program aguments.\n if (arguments.errors())\n {\n arguments.writeErrorMessages(std::cout);\n return 1;\n }\n \n if (arguments.argc()<=1)\n {\n arguments.getApplicationUsage()->write(std::cout,osg::ApplicationUsage::COMMAND_LINE_OPTION);\n return 1;\n }\n\n osg::Timer_t start_tick = osg::Timer::instance()->tick();\n\n \/\/ read the scene from the list of file specified commandline args.\n osg::ref_ptr<osg::Node> loadedModel = osgDB::readNodeFiles(arguments);\n\n \/\/ if no model has been successfully loaded report failure.\n if (!loadedModel) \n {\n std::cout << arguments.getApplicationName() <<\": No data loaded\" << std::endl;\n return 1;\n }\n\n \/\/ any option left unread are converted into errors to write out later.\n arguments.reportRemainingOptionsAsUnrecognized();\n\n \/\/ report any errors if they have occured when parsing the program aguments.\n if (arguments.errors())\n {\n arguments.writeErrorMessages(std::cout);\n }\n\n osg::Timer_t end_tick = osg::Timer::instance()->tick();\n\n std::cout << \"Time to load = \"<<osg::Timer::instance()->delta_s(start_tick,end_tick)<<std::endl;\n\n \/\/ optimize the scene graph, remove rendundent nodes and state etc.\n osgUtil::Optimizer optimizer;\n optimizer.optimize(loadedModel.get());\n\n \/\/ pass the loaded scene graph to the viewer.\n viewer.setSceneData(loadedModel.get());\n\n \/\/ create the windows and run the threads.\n viewer.realize();\n\n while( !viewer.done() )\n {\n \/\/ wait for all cull and draw threads to complete.\n viewer.sync();\n\n \/\/ update the scene by traversing it with the the update visitor which will\n \/\/ call all node update callbacks and animations.\n viewer.update();\n \n \/\/ fire off the cull and draw traversals of the scene.\n viewer.frame();\n \n }\n \n \/\/ wait for all cull and draw threads to complete before exit.\n viewer.sync();\n\n return 0;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.\n#include <vespa\/document\/base\/documentid.h>\n#include <vespa\/document\/datatype\/documenttype.h>\n#include <vespa\/document\/fieldvalue\/document.h>\n#include <vespa\/document\/fieldvalue\/bytefieldvalue.h>\n#include <vespa\/document\/fieldvalue\/doublefieldvalue.h>\n#include <vespa\/document\/fieldvalue\/floatfieldvalue.h>\n#include <vespa\/document\/fieldvalue\/intfieldvalue.h>\n#include <vespa\/document\/fieldvalue\/longfieldvalue.h>\n#include <vespa\/document\/fieldvalue\/rawfieldvalue.h>\n#include <vespa\/document\/fieldvalue\/shortfieldvalue.h>\n#include <vespa\/document\/fieldvalue\/stringfieldvalue.h>\n#include <vespa\/vespalib\/testkit\/test_kit.h>\n#include <vespa\/searchlib\/common\/matching_elements.h>\n#include <vespa\/searchsummary\/docsummary\/docsumwriter.h>\n#include <vespa\/searchsummary\/docsummary\/docsumstate.h>\n#include <vespa\/searchsummary\/docsummary\/keywordextractor.h>\n#include <vespa\/searchsummary\/docsummary\/docsum_store_document.h>\n#include <vespa\/vespalib\/data\/slime\/slime.h>\n#include <vespa\/vespalib\/data\/smart_buffer.h>\n#include <vespa\/vespalib\/util\/size_literals.h>\n\nusing namespace vespalib::slime::convenience;\nusing namespace search::docsummary;\nusing vespalib::slime::BinaryFormat;\nusing search::MatchingElements;\nusing document::ByteFieldValue;\nusing document::DataType;\nusing document::Document;\nusing document::DocumentId;\nusing document::DocumentType;\nusing document::DoubleFieldValue;\nusing document::Field;\nusing document::FloatFieldValue;\nusing document::IntFieldValue;\nusing document::LongFieldValue;\nusing document::RawFieldValue;\nusing document::ShortFieldValue;\nusing document::StringFieldValue;\nusing document::StructDataType;\nusing document::StructFieldValue;\n\nnamespace {\n\nstruct DocsumFixture : IDocsumStore, GetDocsumsStateCallback {\n std::unique_ptr<DynamicDocsumWriter> writer;\n StructDataType int_pair_type;\n DocumentType doc_type;\n GetDocsumsState state;\n DocsumFixture();\n ~DocsumFixture() override;\n void getDocsum(Slime &slime) {\n Slime slimeOut;\n SlimeInserter inserter(slimeOut);\n writer->WriteDocsum(1u, &state, this, inserter);\n vespalib::SmartBuffer buf(4_Ki);\n BinaryFormat::encode(slimeOut, buf);\n EXPECT_GREATER(BinaryFormat::decode(buf.obtain(), slime), 0u);\n }\n uint32_t getNumDocs() const override { return 2; }\n std::unique_ptr<const IDocsumStoreDocument> getMappedDocsum(uint32_t docid) override {\n EXPECT_EQUAL(1u, docid);\n auto doc = std::make_unique<Document>(doc_type, DocumentId(\"id:test:test::0\"));\n doc->setValue(\"int_field\", IntFieldValue(4));\n doc->setValue(\"short_field\", ShortFieldValue(2));\n doc->setValue(\"byte_field\", ByteFieldValue(1));\n doc->setValue(\"float_field\", FloatFieldValue(4.5));\n doc->setValue(\"double_field\", DoubleFieldValue(8.75));\n doc->setValue(\"int64_field\", LongFieldValue(8));\n doc->setValue(\"string_field\", StringFieldValue(\"string\"));\n doc->setValue(\"data_field\", RawFieldValue(\"data\"));\n doc->setValue(\"longstring_field\", StringFieldValue(\"long_string\"));\n doc->setValue(\"longdata_field\", RawFieldValue(\"long_data\"));\n {\n StructFieldValue int_pair(int_pair_type);\n int_pair.setValue(\"foo\", IntFieldValue(1));\n int_pair.setValue(\"bar\", IntFieldValue(2));\n doc->setValue(\"int_pair_field\", int_pair);\n }\n return std::make_unique<DocsumStoreDocument>(std::move(doc));\n }\n void FillSummaryFeatures(GetDocsumsState&) override { }\n void FillRankFeatures(GetDocsumsState&) override { }\n std::unique_ptr<MatchingElements> fill_matching_elements(const search::MatchingElementsFields &) override { abort(); }\n};\n\n\nDocsumFixture::DocsumFixture()\n : writer(),\n int_pair_type(\"int_pair\"),\n doc_type(\"test\"),\n state(*this)\n{\n auto config = std::make_unique<ResultConfig>();\n ResultClass *cfg = config->AddResultClass(\"default\", 0);\n EXPECT_TRUE(cfg != nullptr);\n EXPECT_TRUE(cfg->AddConfigEntry(\"int_field\", RES_INT));\n EXPECT_TRUE(cfg->AddConfigEntry(\"short_field\", RES_SHORT));\n EXPECT_TRUE(cfg->AddConfigEntry(\"byte_field\", RES_BYTE));\n EXPECT_TRUE(cfg->AddConfigEntry(\"float_field\", RES_FLOAT));\n EXPECT_TRUE(cfg->AddConfigEntry(\"double_field\", RES_DOUBLE));\n EXPECT_TRUE(cfg->AddConfigEntry(\"int64_field\", RES_INT64));\n EXPECT_TRUE(cfg->AddConfigEntry(\"string_field\", RES_STRING));\n EXPECT_TRUE(cfg->AddConfigEntry(\"data_field\", RES_DATA));\n EXPECT_TRUE(cfg->AddConfigEntry(\"longstring_field\", RES_LONG_STRING));\n EXPECT_TRUE(cfg->AddConfigEntry(\"longdata_field\", RES_LONG_DATA));\n EXPECT_TRUE(cfg->AddConfigEntry(\"int_pair_field\", RES_JSONSTRING));\n config->set_default_result_class_id(0);\n config->CreateEnumMaps();\n writer = std::make_unique<DynamicDocsumWriter>(std::move(config), std::unique_ptr<KeywordExtractor>());\n int_pair_type.addField(Field(\"foo\", *DataType::INT));\n int_pair_type.addField(Field(\"bar\", *DataType::INT));\n doc_type.addField(Field(\"int_field\", *DataType::INT));\n doc_type.addField(Field(\"short_field\", *DataType::SHORT));\n doc_type.addField(Field(\"byte_field\", *DataType::BYTE));\n doc_type.addField(Field(\"float_field\", *DataType::FLOAT));\n doc_type.addField(Field(\"double_field\", *DataType::DOUBLE));\n doc_type.addField(Field(\"int64_field\", *DataType::LONG));\n doc_type.addField(Field(\"string_field\", *DataType::STRING));\n doc_type.addField(Field(\"data_field\", *DataType::RAW));\n doc_type.addField(Field(\"longstring_field\", *DataType::STRING));\n doc_type.addField(Field(\"longdata_field\", *DataType::RAW));\n doc_type.addField(Field(\"int_pair_field\", int_pair_type));\n}\nDocsumFixture::~DocsumFixture() = default;\n\n} \/\/ namespace <unnamed>\n\nTEST_FF(\"require that docsum can be written as slime\", DocsumFixture(), Slime()) {\n f1.getDocsum(f2);\n EXPECT_EQUAL(f2.get()[\"int_field\"].asLong(), 4u);\n EXPECT_EQUAL(f2.get()[\"short_field\"].asLong(), 2u);\n EXPECT_EQUAL(f2.get()[\"byte_field\"].asLong(), 1u);\n EXPECT_EQUAL(f2.get()[\"float_field\"].asDouble(), 4.5);\n EXPECT_EQUAL(f2.get()[\"double_field\"].asDouble(), 8.75);\n EXPECT_EQUAL(f2.get()[\"int64_field\"].asLong(), 8u);\n EXPECT_EQUAL(f2.get()[\"string_field\"].asString().make_string(), std::string(\"string\"));\n EXPECT_EQUAL(f2.get()[\"data_field\"].asData().make_string(), std::string(\"data\"));\n EXPECT_EQUAL(f2.get()[\"longstring_field\"].asString().make_string(), std::string(\"long_string\"));\n EXPECT_EQUAL(f2.get()[\"longdata_field\"].asData().make_string(), std::string(\"long_data\"));\n EXPECT_EQUAL(f2.get()[\"int_pair_field\"][\"foo\"].asLong(), 1u);\n EXPECT_EQUAL(f2.get()[\"int_pair_field\"][\"bar\"].asLong(), 2u);\n}\n\nTEST_MAIN() { TEST_RUN_ALL(); }\n<commit_msg>Test failure to get backing document and failure to find summary class when generating summary.<commit_after>\/\/ Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.\n#include <vespa\/document\/base\/documentid.h>\n#include <vespa\/document\/datatype\/documenttype.h>\n#include <vespa\/document\/fieldvalue\/document.h>\n#include <vespa\/document\/fieldvalue\/bytefieldvalue.h>\n#include <vespa\/document\/fieldvalue\/doublefieldvalue.h>\n#include <vespa\/document\/fieldvalue\/floatfieldvalue.h>\n#include <vespa\/document\/fieldvalue\/intfieldvalue.h>\n#include <vespa\/document\/fieldvalue\/longfieldvalue.h>\n#include <vespa\/document\/fieldvalue\/rawfieldvalue.h>\n#include <vespa\/document\/fieldvalue\/shortfieldvalue.h>\n#include <vespa\/document\/fieldvalue\/stringfieldvalue.h>\n#include <vespa\/vespalib\/testkit\/test_kit.h>\n#include <vespa\/searchlib\/common\/matching_elements.h>\n#include <vespa\/searchsummary\/docsummary\/docsumwriter.h>\n#include <vespa\/searchsummary\/docsummary\/docsumstate.h>\n#include <vespa\/searchsummary\/docsummary\/keywordextractor.h>\n#include <vespa\/searchsummary\/docsummary\/docsum_store_document.h>\n#include <vespa\/vespalib\/data\/slime\/slime.h>\n#include <vespa\/vespalib\/data\/smart_buffer.h>\n#include <vespa\/vespalib\/util\/size_literals.h>\n\nusing namespace vespalib::slime::convenience;\nusing namespace search::docsummary;\nusing vespalib::slime::BinaryFormat;\nusing search::MatchingElements;\nusing document::ByteFieldValue;\nusing document::DataType;\nusing document::Document;\nusing document::DocumentId;\nusing document::DocumentType;\nusing document::DoubleFieldValue;\nusing document::Field;\nusing document::FloatFieldValue;\nusing document::IntFieldValue;\nusing document::LongFieldValue;\nusing document::RawFieldValue;\nusing document::ShortFieldValue;\nusing document::StringFieldValue;\nusing document::StructDataType;\nusing document::StructFieldValue;\n\nnamespace {\n\nstruct DocsumFixture : IDocsumStore, GetDocsumsStateCallback {\n std::unique_ptr<DynamicDocsumWriter> writer;\n StructDataType int_pair_type;\n DocumentType doc_type;\n GetDocsumsState state;\n bool fail_get_mapped_docsum;\n bool empty_get_mapped_docsum;\n DocsumFixture();\n ~DocsumFixture() override;\n void getDocsum(Slime &slime) {\n Slime slimeOut;\n SlimeInserter inserter(slimeOut);\n writer->WriteDocsum(1u, &state, this, inserter);\n vespalib::SmartBuffer buf(4_Ki);\n BinaryFormat::encode(slimeOut, buf);\n EXPECT_GREATER(BinaryFormat::decode(buf.obtain(), slime), 0u);\n }\n uint32_t getNumDocs() const override { return 2; }\n std::unique_ptr<const IDocsumStoreDocument> getMappedDocsum(uint32_t docid) override {\n EXPECT_EQUAL(1u, docid);\n if (fail_get_mapped_docsum) {\n return {};\n }\n if (empty_get_mapped_docsum) {\n return std::make_unique<DocsumStoreDocument>(std::unique_ptr<Document>());\n }\n auto doc = std::make_unique<Document>(doc_type, DocumentId(\"id:test:test::0\"));\n doc->setValue(\"int_field\", IntFieldValue(4));\n doc->setValue(\"short_field\", ShortFieldValue(2));\n doc->setValue(\"byte_field\", ByteFieldValue(1));\n doc->setValue(\"float_field\", FloatFieldValue(4.5));\n doc->setValue(\"double_field\", DoubleFieldValue(8.75));\n doc->setValue(\"int64_field\", LongFieldValue(8));\n doc->setValue(\"string_field\", StringFieldValue(\"string\"));\n doc->setValue(\"data_field\", RawFieldValue(\"data\"));\n doc->setValue(\"longstring_field\", StringFieldValue(\"long_string\"));\n doc->setValue(\"longdata_field\", RawFieldValue(\"long_data\"));\n {\n StructFieldValue int_pair(int_pair_type);\n int_pair.setValue(\"foo\", IntFieldValue(1));\n int_pair.setValue(\"bar\", IntFieldValue(2));\n doc->setValue(\"int_pair_field\", int_pair);\n }\n return std::make_unique<DocsumStoreDocument>(std::move(doc));\n }\n void FillSummaryFeatures(GetDocsumsState&) override { }\n void FillRankFeatures(GetDocsumsState&) override { }\n std::unique_ptr<MatchingElements> fill_matching_elements(const search::MatchingElementsFields &) override { abort(); }\n};\n\n\nDocsumFixture::DocsumFixture()\n : writer(),\n int_pair_type(\"int_pair\"),\n doc_type(\"test\"),\n state(*this),\n fail_get_mapped_docsum(false),\n empty_get_mapped_docsum(false)\n{\n auto config = std::make_unique<ResultConfig>();\n ResultClass *cfg = config->AddResultClass(\"default\", 0);\n EXPECT_TRUE(cfg != nullptr);\n EXPECT_TRUE(cfg->AddConfigEntry(\"int_field\", RES_INT));\n EXPECT_TRUE(cfg->AddConfigEntry(\"short_field\", RES_SHORT));\n EXPECT_TRUE(cfg->AddConfigEntry(\"byte_field\", RES_BYTE));\n EXPECT_TRUE(cfg->AddConfigEntry(\"float_field\", RES_FLOAT));\n EXPECT_TRUE(cfg->AddConfigEntry(\"double_field\", RES_DOUBLE));\n EXPECT_TRUE(cfg->AddConfigEntry(\"int64_field\", RES_INT64));\n EXPECT_TRUE(cfg->AddConfigEntry(\"string_field\", RES_STRING));\n EXPECT_TRUE(cfg->AddConfigEntry(\"data_field\", RES_DATA));\n EXPECT_TRUE(cfg->AddConfigEntry(\"longstring_field\", RES_LONG_STRING));\n EXPECT_TRUE(cfg->AddConfigEntry(\"longdata_field\", RES_LONG_DATA));\n EXPECT_TRUE(cfg->AddConfigEntry(\"int_pair_field\", RES_JSONSTRING));\n config->set_default_result_class_id(0);\n config->CreateEnumMaps();\n writer = std::make_unique<DynamicDocsumWriter>(std::move(config), std::unique_ptr<KeywordExtractor>());\n int_pair_type.addField(Field(\"foo\", *DataType::INT));\n int_pair_type.addField(Field(\"bar\", *DataType::INT));\n doc_type.addField(Field(\"int_field\", *DataType::INT));\n doc_type.addField(Field(\"short_field\", *DataType::SHORT));\n doc_type.addField(Field(\"byte_field\", *DataType::BYTE));\n doc_type.addField(Field(\"float_field\", *DataType::FLOAT));\n doc_type.addField(Field(\"double_field\", *DataType::DOUBLE));\n doc_type.addField(Field(\"int64_field\", *DataType::LONG));\n doc_type.addField(Field(\"string_field\", *DataType::STRING));\n doc_type.addField(Field(\"data_field\", *DataType::RAW));\n doc_type.addField(Field(\"longstring_field\", *DataType::STRING));\n doc_type.addField(Field(\"longdata_field\", *DataType::RAW));\n doc_type.addField(Field(\"int_pair_field\", int_pair_type));\n}\nDocsumFixture::~DocsumFixture() = default;\n\n} \/\/ namespace <unnamed>\n\nTEST_FF(\"require that docsum can be written as slime\", DocsumFixture(), Slime()) {\n f1.getDocsum(f2);\n EXPECT_EQUAL(f2.get()[\"int_field\"].asLong(), 4u);\n EXPECT_EQUAL(f2.get()[\"short_field\"].asLong(), 2u);\n EXPECT_EQUAL(f2.get()[\"byte_field\"].asLong(), 1u);\n EXPECT_EQUAL(f2.get()[\"float_field\"].asDouble(), 4.5);\n EXPECT_EQUAL(f2.get()[\"double_field\"].asDouble(), 8.75);\n EXPECT_EQUAL(f2.get()[\"int64_field\"].asLong(), 8u);\n EXPECT_EQUAL(f2.get()[\"string_field\"].asString().make_string(), std::string(\"string\"));\n EXPECT_EQUAL(f2.get()[\"data_field\"].asData().make_string(), std::string(\"data\"));\n EXPECT_EQUAL(f2.get()[\"longstring_field\"].asString().make_string(), std::string(\"long_string\"));\n EXPECT_EQUAL(f2.get()[\"longdata_field\"].asData().make_string(), std::string(\"long_data\"));\n EXPECT_EQUAL(f2.get()[\"int_pair_field\"][\"foo\"].asLong(), 1u);\n EXPECT_EQUAL(f2.get()[\"int_pair_field\"][\"bar\"].asLong(), 2u);\n}\n\nTEST_FF(\"require that unknown summary class gives empty slime\", DocsumFixture(), Slime())\n{\n f1.state._args.setResultClassName(\"unknown\");\n f1.getDocsum(f2);\n EXPECT_TRUE(f2.get().valid());\n EXPECT_EQUAL(vespalib::slime::NIX::ID, f2.get().type().getId());\n}\n\nTEST_FF(\"require that failure to retrieve docsum store document gives empty slime\", DocsumFixture(), Slime())\n{\n f1.fail_get_mapped_docsum = true;\n f1.getDocsum(f2);\n EXPECT_TRUE(f2.get().valid());\n EXPECT_EQUAL(vespalib::slime::NIX::ID, f2.get().type().getId());\n}\n\nTEST_FF(\"require that empty docsum store document gives empty object\", DocsumFixture(), Slime())\n{\n f1.empty_get_mapped_docsum = true;\n f1.getDocsum(f2);\n EXPECT_TRUE(f2.get().valid());\n EXPECT_EQUAL(vespalib::slime::OBJECT::ID, f2.get().type().getId());\n EXPECT_EQUAL(0u, f2.get().fields());\n}\n\nTEST_MAIN() { TEST_RUN_ALL(); }\n<|endoftext|>"} {"text":"<commit_before>\/* -*- coding: utf-8; mode: c++; tab-width: 3; indent-tabs-mode: nil -*-\n\nCopyright 2010, 2011, 2012, 2013, 2014\nRaffaello D. Di Napoli\n\nThis file is part of Abaclade.\n\nAbaclade is free software: you can redistribute it and\/or modify it under the terms of the GNU\nGeneral Public License as published by the Free Software Foundation, either version 3 of the\nLicense, or (at your option) any later version.\n\nAbaclade is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even\nthe implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General\nPublic License for more details.\n\nYou should have received a copy of the GNU General Public License along with Abaclade. If not, see\n<http:\/\/www.gnu.org\/licenses\/>.\n--------------------------------------------------------------------------------------------------*\/\n\n\/\/ #include <abaclade.hxx> already done in exception-os.cxx.\n\n#include <cstdlib> \/\/ std::abort()\n#include <signal.h> \/\/ sigaction sig*()\n#include <ucontext.h> \/\/ ucontext_t\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ abc::exception\n\nnamespace {\n\n\/\/! Signals that we can translate into C++ exceptions.\nint const g_aiHandledSignals[] = {\n\/\/ Signal (Default action) Description (standard).\n\/\/ SIGABRT, \/\/ (Core) Abort signal from abort(3) (POSIX.1-1990).\n\/\/ SIGALRM, \/\/ (Term) Timer signal from alarm(2) (POSIX.1-1990).\n SIGBUS, \/\/ (Core) Bus error (bad memory access) (POSIX.1-2001).\n\/\/ SIGCHLD, \/\/ (Ign ) Child stopped or terminated (POSIX.1-1990).\n\/\/ SIGCONT, \/\/ (Cont) Continue if stopped (POSIX.1-1990).\n SIGFPE, \/\/ (Core) Floating point exception (POSIX.1-1990).\n\/\/ SIGHUP, \/\/ (Term) Hangup on controlling terminal or death of controlling process (POSIX.1-1990).\n\/\/ SIGILL, \/\/ (Core) Illegal Instruction (POSIX.1-1990).\n\/\/ SIGINT, \/\/ (Term) Interrupt from keyboard (POSIX.1-1990).\n\/\/ SIGPIPE, \/\/ (Term) Broken pipe: write to pipe with no readers (POSIX.1-1990).\n\/\/ SIGPROF, \/\/ (Term) Profiling timer expired (POSIX.1-2001).\n\/\/ SIGQUIT, \/\/ (Core) Quit from keyboard (POSIX.1-1990).\n SIGSEGV \/\/ (Core) Invalid memory reference (POSIX.1-1990).\n\/\/ SIGTERM \/\/ (Term) Termination signal (POSIX.1-1990).\n\/\/ SIGTRAP \/\/ (Core) Trace\/breakpoint trap (POSIX.1-2001).\n\/\/ SIGTSTP \/\/ (Stop) Stop typed at terminal (POSIX.1-1990).\n\/\/ SIGTTIN \/\/ (Stop) Terminal input for background process (POSIX.1-1990).\n\/\/ SIGTTOU \/\/ (Stop) Terminal output for background process (POSIX.1-1990).\n\/\/ SIGUSR1 \/\/ (Term) User-defined signal 1 (POSIX.1-1990).\n\/\/ SIGUSR2 \/\/ (Term) User-defined signal 2 (POSIX.1-1990).\n};\n\/\/! Default handler for each of the signals above.\nstruct ::sigaction g_asaDefault[ABC_COUNTOF(g_aiHandledSignals)];\n\n\/\/! Possible exception types thrown by throw_after_fault().\nABC_ENUM_AUTO_VALUES(fault_exception_types,\n arithmetic_error,\n division_by_zero_error,\n floating_point_error,\n memory_access_error,\n memory_address_error,\n null_pointer_error,\n overflow_error\n);\n\n\/*! Throws an exception of the specified type.\n\n@param fxt\n Type of exception to be throw.\n@param iArg0\n Exception type-specific argument 0.\n@param iArg1\n Exception type-specific argument 1.\n*\/\nvoid throw_after_fault(\n fault_exception_types::enum_type fxt, std::intptr_t iArg0, std::intptr_t iArg1\n) {\n\/\/printf(\"throw_after_fault: %d %p %p\\n\", fxt, iArg0, iArg1);\n ABC_UNUSED_ARG(iArg1);\n switch (fxt) {\n case fault_exception_types::arithmetic_error:\n ABC_THROW(abc::arithmetic_error, ());\n case fault_exception_types::division_by_zero_error:\n ABC_THROW(abc::division_by_zero_error, ());\n case fault_exception_types::floating_point_error:\n ABC_THROW(abc::floating_point_error, ());\n case fault_exception_types::memory_access_error:\n ABC_THROW(abc::memory_access_error, (reinterpret_cast<void const *>(iArg0)));\n case fault_exception_types::memory_address_error:\n ABC_THROW(abc::memory_address_error, (reinterpret_cast<void const *>(iArg0)));\n case fault_exception_types::null_pointer_error:\n ABC_THROW(abc::null_pointer_error, ());\n case fault_exception_types::overflow_error:\n ABC_THROW(abc::overflow_error, ());\n default:\n \/\/ Unexpected exception type. Should never happen.\n std::abort();\n }\n}\n\n\/*! Translates POSIX signals into C++ exceptions, whenever possible. This works by injecting the\nstack frame of a call to throw_after_fault(), and then returning, ending processing of the signal.\nExecution will resume from throw_after_fault(), which creates the appearance of a C++ exception\nbeing thrown at the location of the offending instruction, without calling any of the (many)\nfunctions that are forbidden in a signal handler.\n\n@param iSignal\n Signal number for which the function is being called.\n@param psi\n Additional information on the signal.\n@param pctx\n Thread context. This is used to manipulate the stack of the thread to inject a call frame.\n*\/\nvoid fault_signal_handler(int iSignal, ::siginfo_t * psi, void * pctx) {\n \/* Don’t let external programs mess with us: if the source is not the kernel, ignore the error.\n POSIX.1-2008 states that:\n “Historically, an si_code value of less than or equal to zero indicated that the signal was\n generated by a process via the kill() function, and values of si_code that provided additional\n information for implementation-generated signals, such as SIGFPE or SIGSEGV, were all\n positive. […] if si_code is less than or equal to zero, the signal was generated by a process.\n However, since POSIX.1b did not specify that SI_USER (or SI_QUEUE) had a value less than or\n equal to zero, it is not true that when the signal is generated by a process, the value of\n si_code will always be less than or equal to zero. XSI applications should check whether\n si_code is SI_USER or SI_QUEUE in addition to checking whether it is less than or equal to\n zero.”\n So we do exactly that – except we skip checking for SI_USER and SI_QUEUE at this point because\n they don’t apply to many signals this handler takes care of. *\/\n if (psi->si_code <= 0) {\n return;\n }\n\n fault_exception_types::enum_type fxt;\n std::intptr_t iArg0 = 0, iArg1 = 0;\n switch (iSignal) {\n case SIGBUS:\n \/* There aren’t many codes here that are safe to handle; most of them indicate that there\n is some major memory corruption going on, and in that case we really don’t want to keep on\n going – even the code to throw an exception could be compromised. *\/\n switch (psi->si_code) {\n case BUS_ADRALN: \/\/ Invalid address alignment.\n fxt = fault_exception_types::memory_access_error;\n iArg0 = reinterpret_cast<std::intptr_t>(psi->si_addr);\n break;\n default:\n std::abort();\n }\n break;\n\n case SIGFPE:\n switch (psi->si_code) {\n case FPE_INTDIV: \/\/ Integer divide by zero.\n fxt = fault_exception_types::division_by_zero_error;\n break;\n case FPE_INTOVF: \/\/ Integer overflow.\n fxt = fault_exception_types::overflow_error;\n break;\n case FPE_FLTDIV: \/\/ Floating-point divide by zero.\n case FPE_FLTOVF: \/\/ Floating-point overflow.\n case FPE_FLTUND: \/\/ Floating-point underflow.\n case FPE_FLTRES: \/\/ Floating-point inexact result.\n case FPE_FLTINV: \/\/ Floating-point invalid operation.\n case FPE_FLTSUB: \/\/ Subscript out of range.\n fxt = fault_exception_types::floating_point_error;\n break;\n default:\n \/* At the time of writing, the above case labels don’t leave out any values, but\n that’s not necessarily going to be true in 5 years, so… *\/\n fxt = fault_exception_types::arithmetic_error;\n break;\n }\n break;\n\n case SIGSEGV:\n if (psi->si_addr == nullptr) {\n fxt = fault_exception_types::null_pointer_error;\n } else {\n fxt = fault_exception_types::memory_address_error;\n iArg0 = reinterpret_cast<std::intptr_t>(psi->si_addr);\n }\n break;\n\n default:\n \/* Handle all unrecognized cases here. Since here we only handle signals for which the\n default actions is a core dump, calling abort (which sends SIGABRT, also causing a core\n dump) is the same as invoking the default action. *\/\n std::abort();\n }\n\n \/* Change the address at which the thread will resume execution: manipulate the thread context\n to emulate a function call to throw_after_fault(). *\/\n\n ::ucontext_t * puctx = static_cast< ::ucontext_t *>(pctx);\n #if ABC_HOST_ARCH_I386\n #if ABC_HOST_API_LINUX\n typedef std::int32_t reg_t;\n reg_t & eip = puctx->uc_mcontext.gregs[REG_EIP];\n reg_t & esp = puctx->uc_mcontext.gregs[REG_ESP];\n #elif ABC_HOST_API_FREEBSD\n typedef std::int32_t reg_t;\n reg_t & eip = puctx->uc_mcontext.mc_eip;\n reg_t & esp = puctx->uc_mcontext.mc_esp;\n #else\n #error \"TODO: HOST_API\"\n #endif\n \/* Push the arguments to throw_after_fault() onto the stack, push the address of the current\n (failing) instruction, then set eip to the start of throw_after_fault(). These steps emulate a\n 3-argument subroutine call. *\/\n reinterpret_cast<reg_t *>(esp -= 4) = static_cast<reg_t>(iArg1);\n reinterpret_cast<reg_t *>(esp -= 4) = static_cast<reg_t>(iArg0);\n reinterpret_cast<reg_t *>(esp -= 4) = static_cast<reg_t>(fxt);\n reinterpret_cast<reg_t *>(esp -= 4) = eip;\n eip = reinterpret_cast<reg_t>(&throw_after_fault);\n #elif ABC_HOST_ARCH_X86_64\n #if ABC_HOST_API_LINUX\n typedef std::int64_t reg_t;\n reg_t & rip = puctx->uc_mcontext.gregs[REG_RIP];\n reg_t & rsp = puctx->uc_mcontext.gregs[REG_RSP];\n reg_t & rdi = puctx->uc_mcontext.gregs[REG_RDI];\n reg_t & rsi = puctx->uc_mcontext.gregs[REG_RSI];\n reg_t & rdx = puctx->uc_mcontext.gregs[REG_RDX];\n #elif ABC_HOST_API_FREEBSD\n typedef std::int64_t reg_t;\n reg_t & rip = puctx->uc_mcontext.mc_rip;\n reg_t & rsp = puctx->uc_mcontext.mc_rsp;\n reg_t & rdi = puctx->uc_mcontext.mc_rdi;\n reg_t & rsi = puctx->uc_mcontext.mc_rsi;\n reg_t & rdx = puctx->uc_mcontext.mc_rdx;\n #else\n #error \"TODO: HOST_API\"\n #endif\n \/* Load the arguments to throw_after_fault() in rdi\/rsi\/rdx, push the address of the current\n (failing) instruction, then set rip to the start of throw_after_fault(). These steps emulate a\n 3-argument subroutine call. *\/\n rdi = static_cast<reg_t>(fxt);\n rsi = static_cast<reg_t>(iArg0);\n rdx = static_cast<reg_t>(iArg1);\n \/\/ TODO: validate that stack alignment to 16 bytes is done by the callee with push rbp.\n *reinterpret_cast<reg_t *>(rsp -= 8) = rip;\n rip = reinterpret_cast<reg_t>(&throw_after_fault);\n #else\n #error \"TODO: HOST_ARCH\"\n #endif\n}\n\n} \/\/namespace\n\nnamespace abc {\n\nexception::fault_converter::fault_converter() {\n \/\/ Setup handlers for the signals in g_aiHandledSignals.\n struct ::sigaction saNew;\n saNew.sa_sigaction = &fault_signal_handler;\n sigemptyset(&saNew.sa_mask);\n \/* SA_SIGINFO (POSIX.1-2001) provides the handler with more information about the signal, which\n we use to generate more precise exceptions. *\/\n saNew.sa_flags = SA_SIGINFO;\n for (std::size_t i = ABC_COUNTOF(g_aiHandledSignals); i-- > 0; ) {\n ::sigaction(g_aiHandledSignals[i], &saNew, &g_asaDefault[i]);\n }\n}\n\nexception::fault_converter::~fault_converter() {\n \/\/ Restore the saved signal handlers.\n for (std::size_t i = ABC_COUNTOF(g_aiHandledSignals); i-- > 0; ) {\n ::sigaction(g_aiHandledSignals[i], &g_asaDefault[i], nullptr);\n }\n}\n\n} \/\/namespace abc\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n<commit_msg>Simplify register manipulation<commit_after>\/* -*- coding: utf-8; mode: c++; tab-width: 3; indent-tabs-mode: nil -*-\n\nCopyright 2010, 2011, 2012, 2013, 2014\nRaffaello D. Di Napoli\n\nThis file is part of Abaclade.\n\nAbaclade is free software: you can redistribute it and\/or modify it under the terms of the GNU\nGeneral Public License as published by the Free Software Foundation, either version 3 of the\nLicense, or (at your option) any later version.\n\nAbaclade is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even\nthe implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General\nPublic License for more details.\n\nYou should have received a copy of the GNU General Public License along with Abaclade. If not, see\n<http:\/\/www.gnu.org\/licenses\/>.\n--------------------------------------------------------------------------------------------------*\/\n\n\/\/ #include <abaclade.hxx> already done in exception-os.cxx.\n\n#include <cstdlib> \/\/ std::abort()\n#include <signal.h> \/\/ sigaction sig*()\n#include <ucontext.h> \/\/ ucontext_t\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ abc::exception\n\nnamespace {\n\n\/\/! Signals that we can translate into C++ exceptions.\nint const g_aiHandledSignals[] = {\n\/\/ Signal (Default action) Description (standard).\n\/\/ SIGABRT, \/\/ (Core) Abort signal from abort(3) (POSIX.1-1990).\n\/\/ SIGALRM, \/\/ (Term) Timer signal from alarm(2) (POSIX.1-1990).\n SIGBUS, \/\/ (Core) Bus error (bad memory access) (POSIX.1-2001).\n\/\/ SIGCHLD, \/\/ (Ign ) Child stopped or terminated (POSIX.1-1990).\n\/\/ SIGCONT, \/\/ (Cont) Continue if stopped (POSIX.1-1990).\n SIGFPE, \/\/ (Core) Floating point exception (POSIX.1-1990).\n\/\/ SIGHUP, \/\/ (Term) Hangup on controlling terminal or death of controlling process (POSIX.1-1990).\n\/\/ SIGILL, \/\/ (Core) Illegal Instruction (POSIX.1-1990).\n\/\/ SIGINT, \/\/ (Term) Interrupt from keyboard (POSIX.1-1990).\n\/\/ SIGPIPE, \/\/ (Term) Broken pipe: write to pipe with no readers (POSIX.1-1990).\n\/\/ SIGPROF, \/\/ (Term) Profiling timer expired (POSIX.1-2001).\n\/\/ SIGQUIT, \/\/ (Core) Quit from keyboard (POSIX.1-1990).\n SIGSEGV \/\/ (Core) Invalid memory reference (POSIX.1-1990).\n\/\/ SIGTERM \/\/ (Term) Termination signal (POSIX.1-1990).\n\/\/ SIGTRAP \/\/ (Core) Trace\/breakpoint trap (POSIX.1-2001).\n\/\/ SIGTSTP \/\/ (Stop) Stop typed at terminal (POSIX.1-1990).\n\/\/ SIGTTIN \/\/ (Stop) Terminal input for background process (POSIX.1-1990).\n\/\/ SIGTTOU \/\/ (Stop) Terminal output for background process (POSIX.1-1990).\n\/\/ SIGUSR1 \/\/ (Term) User-defined signal 1 (POSIX.1-1990).\n\/\/ SIGUSR2 \/\/ (Term) User-defined signal 2 (POSIX.1-1990).\n};\n\/\/! Default handler for each of the signals above.\nstruct ::sigaction g_asaDefault[ABC_COUNTOF(g_aiHandledSignals)];\n\n\/\/! Possible exception types thrown by throw_after_fault().\nABC_ENUM_AUTO_VALUES(fault_exception_types,\n arithmetic_error,\n division_by_zero_error,\n floating_point_error,\n memory_access_error,\n memory_address_error,\n null_pointer_error,\n overflow_error\n);\n\n\/*! Throws an exception of the specified type.\n\n@param fxt\n Type of exception to be throw.\n@param iArg0\n Exception type-specific argument 0.\n@param iArg1\n Exception type-specific argument 1.\n*\/\nvoid throw_after_fault(\n fault_exception_types::enum_type fxt, std::intptr_t iArg0, std::intptr_t iArg1\n) {\n\/\/printf(\"throw_after_fault: %d %p %p\\n\", fxt, iArg0, iArg1);\n ABC_UNUSED_ARG(iArg1);\n switch (fxt) {\n case fault_exception_types::arithmetic_error:\n ABC_THROW(abc::arithmetic_error, ());\n case fault_exception_types::division_by_zero_error:\n ABC_THROW(abc::division_by_zero_error, ());\n case fault_exception_types::floating_point_error:\n ABC_THROW(abc::floating_point_error, ());\n case fault_exception_types::memory_access_error:\n ABC_THROW(abc::memory_access_error, (reinterpret_cast<void const *>(iArg0)));\n case fault_exception_types::memory_address_error:\n ABC_THROW(abc::memory_address_error, (reinterpret_cast<void const *>(iArg0)));\n case fault_exception_types::null_pointer_error:\n ABC_THROW(abc::null_pointer_error, ());\n case fault_exception_types::overflow_error:\n ABC_THROW(abc::overflow_error, ());\n default:\n \/\/ Unexpected exception type. Should never happen.\n std::abort();\n }\n}\n\n\/*! Translates POSIX signals into C++ exceptions, whenever possible. This works by injecting the\nstack frame of a call to throw_after_fault(), and then returning, ending processing of the signal.\nExecution will resume from throw_after_fault(), which creates the appearance of a C++ exception\nbeing thrown at the location of the offending instruction, without calling any of the (many)\nfunctions that are forbidden in a signal handler.\n\n@param iSignal\n Signal number for which the function is being called.\n@param psi\n Additional information on the signal.\n@param pctx\n Thread context. This is used to manipulate the stack of the thread to inject a call frame.\n*\/\nvoid fault_signal_handler(int iSignal, ::siginfo_t * psi, void * pctx) {\n \/* Don’t let external programs mess with us: if the source is not the kernel, ignore the error.\n POSIX.1-2008 states that:\n “Historically, an si_code value of less than or equal to zero indicated that the signal was\n generated by a process via the kill() function, and values of si_code that provided additional\n information for implementation-generated signals, such as SIGFPE or SIGSEGV, were all\n positive. […] if si_code is less than or equal to zero, the signal was generated by a process.\n However, since POSIX.1b did not specify that SI_USER (or SI_QUEUE) had a value less than or\n equal to zero, it is not true that when the signal is generated by a process, the value of\n si_code will always be less than or equal to zero. XSI applications should check whether\n si_code is SI_USER or SI_QUEUE in addition to checking whether it is less than or equal to\n zero.”\n So we do exactly that – except we skip checking for SI_USER and SI_QUEUE at this point because\n they don’t apply to many signals this handler takes care of. *\/\n if (psi->si_code <= 0) {\n return;\n }\n\n fault_exception_types::enum_type fxt;\n std::intptr_t iArg0 = 0, iArg1 = 0;\n switch (iSignal) {\n case SIGBUS:\n \/* There aren’t many codes here that are safe to handle; most of them indicate that there\n is some major memory corruption going on, and in that case we really don’t want to keep on\n going – even the code to throw an exception could be compromised. *\/\n switch (psi->si_code) {\n case BUS_ADRALN: \/\/ Invalid address alignment.\n fxt = fault_exception_types::memory_access_error;\n iArg0 = reinterpret_cast<std::intptr_t>(psi->si_addr);\n break;\n default:\n std::abort();\n }\n break;\n\n case SIGFPE:\n switch (psi->si_code) {\n case FPE_INTDIV: \/\/ Integer divide by zero.\n fxt = fault_exception_types::division_by_zero_error;\n break;\n case FPE_INTOVF: \/\/ Integer overflow.\n fxt = fault_exception_types::overflow_error;\n break;\n case FPE_FLTDIV: \/\/ Floating-point divide by zero.\n case FPE_FLTOVF: \/\/ Floating-point overflow.\n case FPE_FLTUND: \/\/ Floating-point underflow.\n case FPE_FLTRES: \/\/ Floating-point inexact result.\n case FPE_FLTINV: \/\/ Floating-point invalid operation.\n case FPE_FLTSUB: \/\/ Subscript out of range.\n fxt = fault_exception_types::floating_point_error;\n break;\n default:\n \/* At the time of writing, the above case labels don’t leave out any values, but\n that’s not necessarily going to be true in 5 years, so… *\/\n fxt = fault_exception_types::arithmetic_error;\n break;\n }\n break;\n\n case SIGSEGV:\n if (psi->si_addr == nullptr) {\n fxt = fault_exception_types::null_pointer_error;\n } else {\n fxt = fault_exception_types::memory_address_error;\n iArg0 = reinterpret_cast<std::intptr_t>(psi->si_addr);\n }\n break;\n\n default:\n \/* Handle all unrecognized cases here. Since here we only handle signals for which the\n default actions is a core dump, calling abort (which sends SIGABRT, also causing a core\n dump) is the same as invoking the default action. *\/\n std::abort();\n }\n\n \/* Change the address at which the thread will resume execution: manipulate the thread context to\n emulate a function call to throw_after_fault(). *\/\n\n ::ucontext_t * puctx = static_cast< ::ucontext_t *>(pctx);\n #if ABC_HOST_ARCH_I386\n #if ABC_HOST_API_LINUX\n typedef std::int32_t reg_t;\n reg_t & eip = puctx->uc_mcontext.gregs[REG_EIP];\n reg_t *& esp = reinterpret_cast<reg_t *&>(puctx->uc_mcontext.gregs[REG_ESP]);\n #elif ABC_HOST_API_FREEBSD\n typedef std::int32_t reg_t;\n reg_t & eip = puctx->uc_mcontext.mc_eip;\n reg_t *& esp = reinterpret_cast<reg_t *&>(puctx->uc_mcontext.mc_esp);\n #else\n #error \"TODO: HOST_API\"\n #endif\n \/* Push the arguments to throw_after_fault() onto the stack, push the address of the current\n (failing) instruction, then set eip to the start of throw_after_fault(). These steps emulate a\n 3-argument subroutine call. *\/\n *--esp = static_cast<reg_t>(iArg1);\n *--esp = static_cast<reg_t>(iArg0);\n *--esp = static_cast<reg_t>(fxt);\n *--esp = eip;\n eip = reinterpret_cast<reg_t>(&throw_after_fault);\n #elif ABC_HOST_ARCH_X86_64\n #if ABC_HOST_API_LINUX\n typedef std::int64_t reg_t;\n reg_t & rip = puctx->uc_mcontext.gregs[REG_RIP];\n reg_t *& rsp = reinterpret_cast<reg_t *&>(puctx->uc_mcontext.gregs[REG_RSP]);\n reg_t & rdi = puctx->uc_mcontext.gregs[REG_RDI];\n reg_t & rsi = puctx->uc_mcontext.gregs[REG_RSI];\n reg_t & rdx = puctx->uc_mcontext.gregs[REG_RDX];\n #elif ABC_HOST_API_FREEBSD\n typedef std::int64_t reg_t;\n reg_t & rip = puctx->uc_mcontext.mc_rip;\n reg_t *& rsp = reinterpret_cast<reg_t *&>(puctx->uc_mcontext.mc_rsp);\n reg_t & rdi = puctx->uc_mcontext.mc_rdi;\n reg_t & rsi = puctx->uc_mcontext.mc_rsi;\n reg_t & rdx = puctx->uc_mcontext.mc_rdx;\n #else\n #error \"TODO: HOST_API\"\n #endif\n \/* Load the arguments to throw_after_fault() in rdi\/rsi\/rdx, push the address of the current\n (failing) instruction, then set rip to the start of throw_after_fault(). These steps emulate a\n 3-argument subroutine call. *\/\n rdi = static_cast<reg_t>(fxt);\n rsi = static_cast<reg_t>(iArg0);\n rdx = static_cast<reg_t>(iArg1);\n \/\/ TODO: validate that stack alignment to 16 bytes is done by the callee with push rbp.\n *--rsp = rip;\n rip = reinterpret_cast<reg_t>(&throw_after_fault);\n #else\n #error \"TODO: HOST_ARCH\"\n #endif\n}\n\n} \/\/namespace\n\nnamespace abc {\n\nexception::fault_converter::fault_converter() {\n \/\/ Setup handlers for the signals in g_aiHandledSignals.\n struct ::sigaction saNew;\n saNew.sa_sigaction = &fault_signal_handler;\n sigemptyset(&saNew.sa_mask);\n \/* SA_SIGINFO (POSIX.1-2001) provides the handler with more information about the signal, which\n we use to generate more precise exceptions. *\/\n saNew.sa_flags = SA_SIGINFO;\n for (std::size_t i = ABC_COUNTOF(g_aiHandledSignals); i-- > 0; ) {\n ::sigaction(g_aiHandledSignals[i], &saNew, &g_asaDefault[i]);\n }\n}\n\nexception::fault_converter::~fault_converter() {\n \/\/ Restore the saved signal handlers.\n for (std::size_t i = ABC_COUNTOF(g_aiHandledSignals); i-- > 0; ) {\n ::sigaction(g_aiHandledSignals[i], &g_asaDefault[i], nullptr);\n }\n}\n\n} \/\/namespace abc\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2016-2018 Chris Conway (Koderz). All Rights Reserved.\n\n#include \"RuntimeMeshActor.h\"\n#include \"RuntimeMeshComponent.h\"\n#include \"RuntimeMeshComponentPlugin.h\"\n\n\nARuntimeMeshActor::ARuntimeMeshActor(const FObjectInitializer& ObjectInitializer)\n\t: Super(ObjectInitializer)\n\t, bRunGenerateMeshesOnConstruction(true)\n\t, bRunGenerateMeshesOnBeginPlay(false)\n{\n\tbCanBeDamaged = false;\n\n\tRuntimeMeshComponent = CreateDefaultSubobject<URuntimeMeshComponent>(TEXT(\"RuntimeMeshComponent0\"));\n\tRuntimeMeshComponent->SetCollisionProfileName(UCollisionProfile::BlockAll_ProfileName);\n\tRuntimeMeshComponent->Mobility = EComponentMobility::Static;\n\n#if ENGINE_MAJOR_VERSION >= 4 && ENGINE_MINOR_VERSION >= 20\n\tRuntimeMeshComponent->SetGenerateOverlapEvents(false);\n#else\n\tRuntimeMeshComponent->bGenerateOverlapEvents = false;\n#endif\n\tRootComponent = RuntimeMeshComponent;\n}\n\nERuntimeMeshMobility ARuntimeMeshActor::GetRuntimeMeshMobility()\n{\n\tif (RuntimeMeshComponent)\n\t{\n\t\treturn RuntimeMeshComponent->GetRuntimeMeshMobility();\n\t}\n\treturn ERuntimeMeshMobility::Static;\n}\n\nvoid ARuntimeMeshActor::SetRuntimeMeshMobility(ERuntimeMeshMobility NewMobility)\n{\n\tif (RuntimeMeshComponent)\n\t{\n\t\tRuntimeMeshComponent->SetRuntimeMeshMobility(NewMobility);\n\t}\n}\n\nvoid ARuntimeMeshActor::SetMobility(EComponentMobility::Type InMobility)\n{\n\tif (RuntimeMeshComponent)\n\t{\n\t\tRuntimeMeshComponent->SetMobility(InMobility);\n\t}\n}\n\nEComponentMobility::Type ARuntimeMeshActor::GetMobility()\n{\n\tif (RuntimeMeshComponent)\n\t{\n\t\treturn RuntimeMeshComponent->Mobility;\n\t}\n\treturn EComponentMobility::Static;\n}\n\nvoid ARuntimeMeshActor::OnConstruction(const FTransform& Transform)\n{\n\tSuper::OnConstruction();\n\t\n\tif (bRunGenerateMeshesOnConstruction)\n\t{\n\t\tGenerateMeshes();\n\t}\n}\n\nvoid ARuntimeMeshActor::BeginPlay()\n{\n\tSuper::BeginPlay();\n\t\n\tbool bIsGameWorld = GetWorld() && GetWorld()->IsGameWorld() && !GetWorld()->IsPreviewWorld() && !GetWorld()->IsEditorWorld();\n\n\tbool bHadSerializedMeshData = false;\n\tif (RuntimeMeshComponent)\n\t{\n\t\tURuntimeMesh* Mesh = RuntimeMeshComponent->GetRuntimeMesh();\n\t\tif (Mesh)\n\t\t{\n\t\t\tbHadSerializedMeshData = Mesh->HasSerializedMeshData();\n\t\t}\n\t}\n\n\tif ((bIsGameWorld && !bHadSerializedMeshData) || bRunGenerateMeshesOnBeginPlay)\n\t{\n\t\tGenerateMeshes();\n\t}\n}\n\nvoid ARuntimeMeshActor::GenerateMeshes_Implementation()\n{\n\n}\n\n<commit_msg>Update RuntimeMeshActor.cpp<commit_after>\/\/ Copyright 2016-2018 Chris Conway (Koderz). All Rights Reserved.\n\n#include \"RuntimeMeshActor.h\"\n#include \"RuntimeMeshComponent.h\"\n#include \"RuntimeMeshComponentPlugin.h\"\n\n\nARuntimeMeshActor::ARuntimeMeshActor(const FObjectInitializer& ObjectInitializer)\n\t: Super(ObjectInitializer)\n\t, bRunGenerateMeshesOnConstruction(true)\n\t, bRunGenerateMeshesOnBeginPlay(false)\n{\n\tbCanBeDamaged = false;\n\n\tRuntimeMeshComponent = CreateDefaultSubobject<URuntimeMeshComponent>(TEXT(\"RuntimeMeshComponent0\"));\n\tRuntimeMeshComponent->SetCollisionProfileName(UCollisionProfile::BlockAll_ProfileName);\n\tRuntimeMeshComponent->Mobility = EComponentMobility::Static;\n\n#if ENGINE_MAJOR_VERSION >= 4 && ENGINE_MINOR_VERSION >= 20\n\tRuntimeMeshComponent->SetGenerateOverlapEvents(false);\n#else\n\tRuntimeMeshComponent->bGenerateOverlapEvents = false;\n#endif\n\tRootComponent = RuntimeMeshComponent;\n}\n\nERuntimeMeshMobility ARuntimeMeshActor::GetRuntimeMeshMobility()\n{\n\tif (RuntimeMeshComponent)\n\t{\n\t\treturn RuntimeMeshComponent->GetRuntimeMeshMobility();\n\t}\n\treturn ERuntimeMeshMobility::Static;\n}\n\nvoid ARuntimeMeshActor::SetRuntimeMeshMobility(ERuntimeMeshMobility NewMobility)\n{\n\tif (RuntimeMeshComponent)\n\t{\n\t\tRuntimeMeshComponent->SetRuntimeMeshMobility(NewMobility);\n\t}\n}\n\nvoid ARuntimeMeshActor::SetMobility(EComponentMobility::Type InMobility)\n{\n\tif (RuntimeMeshComponent)\n\t{\n\t\tRuntimeMeshComponent->SetMobility(InMobility);\n\t}\n}\n\nEComponentMobility::Type ARuntimeMeshActor::GetMobility()\n{\n\tif (RuntimeMeshComponent)\n\t{\n\t\treturn RuntimeMeshComponent->Mobility;\n\t}\n\treturn EComponentMobility::Static;\n}\n\nvoid ARuntimeMeshActor::OnConstruction(const FTransform& Transform)\n{\n\tSuper::OnConstruction(Transform);\n\t\n\tif (bRunGenerateMeshesOnConstruction)\n\t{\n\t\tGenerateMeshes();\n\t}\n}\n\nvoid ARuntimeMeshActor::BeginPlay()\n{\n\tSuper::BeginPlay();\n\t\n\tbool bIsGameWorld = GetWorld() && GetWorld()->IsGameWorld() && !GetWorld()->IsPreviewWorld() && !GetWorld()->IsEditorWorld();\n\n\tbool bHadSerializedMeshData = false;\n\tif (RuntimeMeshComponent)\n\t{\n\t\tURuntimeMesh* Mesh = RuntimeMeshComponent->GetRuntimeMesh();\n\t\tif (Mesh)\n\t\t{\n\t\t\tbHadSerializedMeshData = Mesh->HasSerializedMeshData();\n\t\t}\n\t}\n\n\tif ((bIsGameWorld && !bHadSerializedMeshData) || bRunGenerateMeshesOnBeginPlay)\n\t{\n\t\tGenerateMeshes();\n\t}\n}\n\nvoid ARuntimeMeshActor::GenerateMeshes_Implementation()\n{\n\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/**\n * Title: CoreMIDI4J\n * Description: Core MIDI Device Provider for Java on OS X\n * Copyright: Copyright (c) 2015-2016\n * Company: x.factory Librarians\n *\n * @author Derek Cook\n *\n * CoreMIDI4J is an open source Service Provider Interface for supporting external MIDI devices on MAC OS X\n *\n * This file is part of the XCODE project that provides the native implementation of CoreMIDI4J\n *\n * CREDITS - This library uses principles established by OSXMIDI4J, but converted so it operates at the JNI level with no additional libraries required\n *\n *\/\n\n#include \"CoreMidiDeviceProvider.h\"\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Native functions for CoreMidiDeviceProvider\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/*\n * Gets the number of MIDI sources provided by the Core MIDI system\n *\n * Class: com_coremidi4j_CoreMidiDeviceProvider\n * Method: getNumberOfSources\n * Signature: ()I\n *\n * @param env\t\tThe JNI environment\n * @param obj The reference to the java object instance that called this native method\n *\n * @return The number of MIDI sources provided by the Core MIDI system\n *\n *\/\n\nJNIEXPORT jint JNICALL Java_uk_co_xfactorylibrarians_coremidi4j_CoreMidiDeviceProvider_getNumberOfSources(JNIEnv *env, jobject obj) {\n\n return (jint) MIDIGetNumberOfSources();\n\n}\n\n\/*\n * Gets the number of MIDI destinations provided by the Core MIDI system\n *\n * Class: com_coremidi4j_CoreMidiDeviceProvider\n * Method: getNumberOfDestinations\n * Signature: ()I\n *\n * @param env The JNI environment\n * @param obj The reference to the java object instance that called this native method\n *\n * @return The number of MIDI destinations provided by the Core MIDI system\n *\n *\/\n\nJNIEXPORT jint JNICALL Java_uk_co_xfactorylibrarians_coremidi4j_CoreMidiDeviceProvider_getNumberOfDestinations(JNIEnv *env, jobject obj) {\n\n return (jint) MIDIGetNumberOfDestinations();\n\n}\n\n\/*\n * Gets the specified Core MIDI Source\n *\n * Class: com_coremidi4j_CoreMidiDeviceProvider\n * Method: getSource\n * Signature: (I)I\n *\n * @param env The JNI environment\n * @param obj The reference to the java object instance that called this native method\n * @param sourceIndex The index of the MIDI source to get\n *\n * @return The specified Core MIDI Source\n *\n * @throws CoreMidiEXception if the source index is not valid\n *\n *\/\n\nJNIEXPORT jint JNICALL Java_uk_co_xfactorylibrarians_coremidi4j_CoreMidiDeviceProvider_getSource(JNIEnv *env, jobject obj, jint sourceIndex) {\n\n if ( sourceIndex >= MIDIGetNumberOfSources() ) {\n\n ThrowException(env,CFSTR(\"MIDIGetSource\"),sourceIndex);\n\n }\n\n return MIDIGetSource(sourceIndex);\n\n}\n\n\/*\n * Gets the specified Core MIDI Destination\n *\n * Class: com_coremidi4j_CoreMidiDeviceProvider\n * Method: getDestination\n * Signature: (I)I\n *\n * @param env The JNI environment\n * @param obj The reference to the java object instance that called this native method\n * @param destinationIndex The index of the MIDI destination to get\n *\n * @return The specified Core MIDI Destination\n *\n * @throws CoreMidiEXception if the destination index is not valid\n *\n *\/\n\nJNIEXPORT jint JNICALL Java_uk_co_xfactorylibrarians_coremidi4j_CoreMidiDeviceProvider_getDestination(JNIEnv *env, jobject obj, jint destinationIndex) {\n\n if ( destinationIndex >= MIDIGetNumberOfDestinations() ) {\n\n ThrowException(env,CFSTR(\"MIDIGetDestination\"), destinationIndex);\n\n }\n\n return MIDIGetDestination(destinationIndex);\n\n}\n\n\/*\n * Gets the unique ID (UID) of the specified end point\n *\n * Class: com_coremidi4j_CoreMidiDeviceProvider\n * Method: getUniqueID\n * Signature: (I)I\n *\n * @param env The JNI environment\n * @param obj The reference to the java object instance that called this native method\n * @param endPointReference The end point reference\n *\n * @return The unique ID (UID) of the specified end point\n *\n *\/\n\nJNIEXPORT jint JNICALL Java_uk_co_xfactorylibrarians_coremidi4j_CoreMidiDeviceProvider_getUniqueID(JNIEnv *env, jobject obj, jint endPointReference) {\n\n SInt32 uid = 0;\n\n MIDIObjectGetIntegerProperty(endPointReference, kMIDIPropertyUniqueID, &uid);\n\n return uid;\n\n}\n\n\/*\n * Safely obtains a C string pointer from a CFStringRef. We must do it this way, because CFStringGetCStringPtr\n * is free to return NULL for a variety of reasons, including simply not having an efficient way to respond.\n * However, this means that it is the responsibility of the caller to free() the returned pointer when it is\n * no longer needed, unless we returned NULL.\n *\n * @param aString The CFStringRef\n *\n * @return A newly allocated C string holding the contents of str, or NULL\n *\n *\/\nchar * safeCFStringCopyUTF8String(CFStringRef aString) {\n if (aString == NULL) {\n return NULL;\n }\n\n CFIndex length = CFStringGetLength(aString);\n CFIndex maxSize = CFStringGetMaximumSizeForEncoding(length, kCFStringEncodingUTF8) + 1;\n char *buffer = (char *)malloc(maxSize);\n if (CFStringGetCString(aString, buffer, maxSize, kCFStringEncodingUTF8)) {\n return buffer;\n }\n free(buffer); \/\/ We failed\n return NULL;\n}\n\n\/*\n * Safely prints a line describing a retrieved string for debugging purposes.\n * If the string is null, also reports that.\n *\n * @param label Describes the string being printed\n * @param aString The CFStringRef to be printed\n *\n *\/\n\/\/ Uncomment this if you want to perform the (also commented out) debug printing in the function below.\n\/\/void debugPrintCFString(std::string label, CFStringRef aString) {\n\/\/ char *cString = safeCFStringCopyUTF8String(aString);\n\/\/ std::cout << label << ((cString != NULL)? cString : \"<NULL pointer>\") << std::endl;\n\/\/ free(cString);\n\/\/}\n\n\/*\n * Creates and gets a MidiDevice.Info object for the specified end point reference\n *\n * Class: com_coremidi4j_CoreMidiDeviceProvider\n * Method: getMidiDeviceInfo\n * Signature: (I)Ljavax\/sound\/midi\/MidiDevice\/Info;\n *\n * @param env The JNI environment\n * @param obj The reference to the java object instance that called this native method\n * @param endPointReference The end point reference\n *\n * @return A MidiDevice.Info object for the specified end point reference\n *\n *\/\n\nJNIEXPORT jobject JNICALL Java_uk_co_xfactorylibrarians_coremidi4j_CoreMidiDeviceProvider_getMidiDeviceInfo(JNIEnv *env, jobject obj, jint endPointReference) {\n\n MIDIDeviceRef deviceReference = NULL;\n CFStringRef deviceName = NULL;\n CFStringRef deviceManufacturer = NULL;\n CFStringRef deviceModel = NULL;\n SInt32 deviceOffline = NULL;\n SInt32 deviceUniqueID = 0;\n SInt32 deviceDriverVersion = 0;\n\n MIDIEntityRef entityReference = NULL;\n CFStringRef entityName = NULL;\n CFStringRef entityManufacturer = NULL;\n CFStringRef entityModel = NULL;\n SInt32 entityOffline = NULL;\n SInt32 entityUniqueID = 0;\n SInt32 entityDriverVersion = 0;\n\n \/\/ End point reference is in method parameters\n CFStringRef endpointName = NULL;\n CFStringRef endpointManufacturer = NULL;\n CFStringRef endpointModel = NULL;\n SInt32 endpointOffline = NULL;\n SInt32 endpointUniqueID = 0;\n SInt32 endpointDriverVersion = 0;\n\n \/\/ Find the Java CoreMIDIDeviceInfo class and its constructor\n jclass javaClass = env->FindClass(\"uk\/co\/xfactorylibrarians\/coremidi4j\/CoreMidiDeviceInfo\");\n jmethodID constructor = env->GetMethodID(javaClass, \"<init>\", \"(Ljava\/lang\/String;Ljava\/lang\/String;Ljava\/lang\/String;Ljava\/lang\/String;Ljava\/lang\/String;IILjava\/lang\/String;IILjava\/lang\/String;II)V\");\n\n \/\/ Get the endpoint properties\n MIDIObjectGetStringProperty (endPointReference, kMIDIPropertyName, &endpointName);\n MIDIObjectGetStringProperty (endPointReference, kMIDIPropertyModel, &endpointModel);\n MIDIObjectGetStringProperty (endPointReference, kMIDIPropertyManufacturer, &endpointManufacturer);\n MIDIObjectGetIntegerProperty(endPointReference, kMIDIPropertyOffline, &endpointOffline);\n MIDIObjectGetIntegerProperty(endPointReference, kMIDIPropertyUniqueID, &endpointUniqueID);\n MIDIObjectGetIntegerProperty(endPointReference, kMIDIPropertyDriverVersion, &endpointDriverVersion);\n\n \/\/ Get the entity properties\n MIDIEndpointGetEntity(endPointReference, &entityReference);\n\n MIDIObjectGetStringProperty (entityReference, kMIDIPropertyName, &entityName);\n MIDIObjectGetStringProperty (entityReference, kMIDIPropertyModel, &entityModel);\n MIDIObjectGetStringProperty (entityReference, kMIDIPropertyManufacturer, &entityManufacturer);\n MIDIObjectGetIntegerProperty(entityReference, kMIDIPropertyOffline, &entityOffline);\n MIDIObjectGetIntegerProperty(entityReference, kMIDIPropertyUniqueID, &entityUniqueID);\n MIDIObjectGetIntegerProperty(entityReference, kMIDIPropertyDriverVersion, &entityDriverVersion);\n\n \/\/ Get the device properties\n MIDIEntityGetDevice(entityReference, &deviceReference);\n\n MIDIObjectGetStringProperty (deviceReference, kMIDIPropertyName, &deviceName); \/\/ Get this again in case our string build fails\n MIDIObjectGetStringProperty (deviceReference, kMIDIPropertyModel, &deviceModel);\n MIDIObjectGetStringProperty (deviceReference, kMIDIPropertyManufacturer, &deviceManufacturer);\n MIDIObjectGetIntegerProperty(deviceReference, kMIDIPropertyOffline, &deviceOffline);\n MIDIObjectGetIntegerProperty(deviceReference, kMIDIPropertyUniqueID, &deviceUniqueID);\n MIDIObjectGetIntegerProperty(deviceReference, kMIDIPropertyDriverVersion, &deviceDriverVersion);\n\n long numberOfEntities = MIDIDeviceGetNumberOfEntities(deviceReference);\n\n\/\/ Uncomment these lines and debugPrintCFString (above) if you wish to view information as received on the native side during debugging.\n\/\/ std::cout << \"End Point \" << std::endl;\n\/\/ std::cout << \" End Point Reference \" << endPointReference << std::endl;\n\/\/ debugPrintCFString(\" End Point kMIDIPropertyName \", endpointName);\n\/\/ debugPrintCFString(\" End Point kMIDIPropertyModel \", endpointModel);\n\/\/ debugPrintCFString(\" End Point kMIDIPropertyManufacturer \", endpointManufacturer);\n\/\/ std::cout << \" End Point kMIDIPropertyOffline \" << endpointOffline << std::endl;\n\/\/ std::cout << \" End Point kMIDIPropertyUniqueID \" << endpointUniqueID << std::endl;\n\/\/ std::cout << \" End Point kMIDIPropertyDriverVersion \" << endpointDriverVersion << std::endl;\n\/\/ std::cout << std::endl;\n\/\/ std::cout << \" Entity Reference \" << entityReference << std::endl;\n\/\/ debugPrintCFString(\" Entity kMIDIPropertyName \", entityName);\n\/\/ debugPrintCFString(\" Entity kMIDIPropertyModel \", entityModel);\n\/\/ debugPrintCFString(\" Entity kMIDIPropertyManufacturer \", entityManufacturer);\n\/\/ std::cout << \" Entity kMIDIPropertyOffline \" << entityOffline << std::endl;\n\/\/ std::cout << \" Entity kMIDIPropertyUniqueID \" << entityUniqueID << std::endl;\n\/\/ std::cout << \" Entity kMIDIPropertyDriverVersion \" << entityDriverVersion << std::endl;\n\/\/ std::cout << std::endl;\n\/\/ std::cout << \" Device Reference \" << deviceReference << std::endl;\n\/\/ debugPrintCFString(\" Device kMIDIPropertyName \", deviceName);\n\/\/ debugPrintCFString(\" Device kMIDIPropertyModel \", deviceModel);\n\/\/ debugPrintCFString(\" Device kMIDIPropertyManufacturer \", deviceManufacturer);\n\/\/ std::cout << \" Device kMIDIPropertyOffline \" << deviceOffline << std::endl;\n\/\/ std::cout << \" Device kMIDIPropertyUniqueID \" << deviceUniqueID << std::endl;\n\/\/ std::cout << \" Device kMIDIPropertyDriverVersion \" << deviceDriverVersion << std::endl;\n\/\/ std::cout << std::endl;\n\/\/ std::cout << \" Number of entities \" << numberOfEntities << std::endl;\n\/\/ std::cout << std::endl;\n\n \/\/ Build the Device Info name. Add \"CoreMIDI4J - \" to the start of our device name if we can\n \/\/ And if the device has more than one entity then add the entity name\n CFMutableStringRef buildName = CFStringCreateMutable(NULL, 0);\n CFStringRef deviceInfoName;\n\n if ( buildName != NULL ) {\n\n if ( deviceName != NULL ) {\n\n CFStringAppend(buildName, (deviceName != NULL ) ? deviceName : CFSTR(\"<Unknown Device>\") );\n\n if ( numberOfEntities > 1 ) {\n\n CFStringAppend(buildName, CFSTR(\" \"));\n CFStringAppend(buildName, (endpointName != NULL ) ? endpointName : CFSTR(\"<Unknown Endpoint>\") );\n\n }\n\n } else {\n\n CFStringAppend(buildName, (endpointName != NULL ) ? endpointName : CFSTR(\"<Unknown Device>\") );\n\n }\n\n \/\/ Overwrite the deviceName with our updated one\n deviceInfoName = CFStringCreateCopy(NULL, buildName);\n\n \/\/ And release the temporary string\n CFRelease(buildName);\n\n } else {\n\n \/\/ Overwrite the deviceName with our updated one\n deviceInfoName = CFStringCreateCopy(NULL, deviceName);\n\n }\n\n char *deviceInfoNamePtr = safeCFStringCopyUTF8String ( deviceInfoName );\n char *deviceInfoManufacturerPtr = safeCFStringCopyUTF8String ( endpointManufacturer ); \/\/ The end point manufacturer name is always present\n char *deviceInfoDescriptionPtr = safeCFStringCopyUTF8String ( endpointModel ); \/\/ The end point model name is always present\n\n char *deviceNamePtr = safeCFStringCopyUTF8String ( deviceName );\n char *entityNamePtr = safeCFStringCopyUTF8String ( entityName );\n char *endPointNamePtr = safeCFStringCopyUTF8String ( endpointName );\n\n \/\/ TODO - Have seen reference that the device neds to be initialised to get the version. As we are still getting zero, force the string for now\n const char *deviceInfoVersion = \"Unknown Version\";\n\n \/\/ Create the Java Object\n jobject info = env->NewObject(javaClass,\n constructor,\n env->NewStringUTF(( deviceInfoNamePtr != NULL ) ? deviceInfoNamePtr : \"<Unknown Device>\"),\n env->NewStringUTF(( deviceInfoManufacturerPtr != NULL ) ? deviceInfoManufacturerPtr : \"<Unknown Manufacturer>\"),\n env->NewStringUTF(( deviceInfoDescriptionPtr != NULL ) ? deviceInfoDescriptionPtr : \"<Unknown Description>\"),\n env->NewStringUTF(deviceInfoVersion),\n env->NewStringUTF( ( deviceNamePtr != NULL ) ? deviceNamePtr : \"<Unknown Device>\"),\n deviceReference,\n deviceUniqueID,\n env->NewStringUTF( ( entityNamePtr != NULL) ? entityNamePtr : \"<Unknown Entity>\"),\n entityReference,\n entityUniqueID,\n env->NewStringUTF( ( endPointNamePtr != NULL ) ? endPointNamePtr : \"<Unknown Endpoint>\"),\n endPointReference,\n endpointUniqueID);\n\n free(deviceInfoNamePtr);\n free(deviceInfoManufacturerPtr);\n free(deviceInfoDescriptionPtr);\n free(deviceNamePtr);\n free(entityNamePtr);\n free(endPointNamePtr);\n\n return info;\n\n}\n<commit_msg>Fix typo.<commit_after>\/**\n * Title: CoreMIDI4J\n * Description: Core MIDI Device Provider for Java on OS X\n * Copyright: Copyright (c) 2015-2016\n * Company: x.factory Librarians\n *\n * @author Derek Cook\n *\n * CoreMIDI4J is an open source Service Provider Interface for supporting external MIDI devices on MAC OS X\n *\n * This file is part of the XCODE project that provides the native implementation of CoreMIDI4J\n *\n * CREDITS - This library uses principles established by OSXMIDI4J, but converted so it operates at the JNI level with no additional libraries required\n *\n *\/\n\n#include \"CoreMidiDeviceProvider.h\"\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Native functions for CoreMidiDeviceProvider\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/*\n * Gets the number of MIDI sources provided by the Core MIDI system\n *\n * Class: com_coremidi4j_CoreMidiDeviceProvider\n * Method: getNumberOfSources\n * Signature: ()I\n *\n * @param env\t\tThe JNI environment\n * @param obj The reference to the java object instance that called this native method\n *\n * @return The number of MIDI sources provided by the Core MIDI system\n *\n *\/\n\nJNIEXPORT jint JNICALL Java_uk_co_xfactorylibrarians_coremidi4j_CoreMidiDeviceProvider_getNumberOfSources(JNIEnv *env, jobject obj) {\n\n return (jint) MIDIGetNumberOfSources();\n\n}\n\n\/*\n * Gets the number of MIDI destinations provided by the Core MIDI system\n *\n * Class: com_coremidi4j_CoreMidiDeviceProvider\n * Method: getNumberOfDestinations\n * Signature: ()I\n *\n * @param env The JNI environment\n * @param obj The reference to the java object instance that called this native method\n *\n * @return The number of MIDI destinations provided by the Core MIDI system\n *\n *\/\n\nJNIEXPORT jint JNICALL Java_uk_co_xfactorylibrarians_coremidi4j_CoreMidiDeviceProvider_getNumberOfDestinations(JNIEnv *env, jobject obj) {\n\n return (jint) MIDIGetNumberOfDestinations();\n\n}\n\n\/*\n * Gets the specified Core MIDI Source\n *\n * Class: com_coremidi4j_CoreMidiDeviceProvider\n * Method: getSource\n * Signature: (I)I\n *\n * @param env The JNI environment\n * @param obj The reference to the java object instance that called this native method\n * @param sourceIndex The index of the MIDI source to get\n *\n * @return The specified Core MIDI Source\n *\n * @throws CoreMidiEXception if the source index is not valid\n *\n *\/\n\nJNIEXPORT jint JNICALL Java_uk_co_xfactorylibrarians_coremidi4j_CoreMidiDeviceProvider_getSource(JNIEnv *env, jobject obj, jint sourceIndex) {\n\n if ( sourceIndex >= MIDIGetNumberOfSources() ) {\n\n ThrowException(env,CFSTR(\"MIDIGetSource\"),sourceIndex);\n\n }\n\n return MIDIGetSource(sourceIndex);\n\n}\n\n\/*\n * Gets the specified Core MIDI Destination\n *\n * Class: com_coremidi4j_CoreMidiDeviceProvider\n * Method: getDestination\n * Signature: (I)I\n *\n * @param env The JNI environment\n * @param obj The reference to the java object instance that called this native method\n * @param destinationIndex The index of the MIDI destination to get\n *\n * @return The specified Core MIDI Destination\n *\n * @throws CoreMidiEXception if the destination index is not valid\n *\n *\/\n\nJNIEXPORT jint JNICALL Java_uk_co_xfactorylibrarians_coremidi4j_CoreMidiDeviceProvider_getDestination(JNIEnv *env, jobject obj, jint destinationIndex) {\n\n if ( destinationIndex >= MIDIGetNumberOfDestinations() ) {\n\n ThrowException(env,CFSTR(\"MIDIGetDestination\"), destinationIndex);\n\n }\n\n return MIDIGetDestination(destinationIndex);\n\n}\n\n\/*\n * Gets the unique ID (UID) of the specified end point\n *\n * Class: com_coremidi4j_CoreMidiDeviceProvider\n * Method: getUniqueID\n * Signature: (I)I\n *\n * @param env The JNI environment\n * @param obj The reference to the java object instance that called this native method\n * @param endPointReference The end point reference\n *\n * @return The unique ID (UID) of the specified end point\n *\n *\/\n\nJNIEXPORT jint JNICALL Java_uk_co_xfactorylibrarians_coremidi4j_CoreMidiDeviceProvider_getUniqueID(JNIEnv *env, jobject obj, jint endPointReference) {\n\n SInt32 uid = 0;\n\n MIDIObjectGetIntegerProperty(endPointReference, kMIDIPropertyUniqueID, &uid);\n\n return uid;\n\n}\n\n\/*\n * Safely obtains a C string pointer from a CFStringRef. We must do it this way, because CFStringGetCStringPtr\n * is free to return NULL for a variety of reasons, including simply not having an efficient way to respond.\n * However, this means that it is the responsibility of the caller to free() the returned pointer when it is\n * no longer needed, unless we returned NULL.\n *\n * @param aString The CFStringRef\n *\n * @return A newly allocated C string holding the contents of aString, or NULL\n *\n *\/\nchar * safeCFStringCopyUTF8String(CFStringRef aString) {\n if (aString == NULL) {\n return NULL;\n }\n\n CFIndex length = CFStringGetLength(aString);\n CFIndex maxSize = CFStringGetMaximumSizeForEncoding(length, kCFStringEncodingUTF8) + 1;\n char *buffer = (char *)malloc(maxSize);\n if (CFStringGetCString(aString, buffer, maxSize, kCFStringEncodingUTF8)) {\n return buffer;\n }\n free(buffer); \/\/ We failed\n return NULL;\n}\n\n\/*\n * Safely prints a line describing a retrieved string for debugging purposes.\n * If the string is null, also reports that.\n *\n * @param label Describes the string being printed\n * @param aString The CFStringRef to be printed\n *\n *\/\n\/\/ Uncomment this if you want to perform the (also commented out) debug printing in the function below.\n\/\/void debugPrintCFString(std::string label, CFStringRef aString) {\n\/\/ char *cString = safeCFStringCopyUTF8String(aString);\n\/\/ std::cout << label << ((cString != NULL)? cString : \"<NULL pointer>\") << std::endl;\n\/\/ free(cString);\n\/\/}\n\n\/*\n * Creates and gets a MidiDevice.Info object for the specified end point reference\n *\n * Class: com_coremidi4j_CoreMidiDeviceProvider\n * Method: getMidiDeviceInfo\n * Signature: (I)Ljavax\/sound\/midi\/MidiDevice\/Info;\n *\n * @param env The JNI environment\n * @param obj The reference to the java object instance that called this native method\n * @param endPointReference The end point reference\n *\n * @return A MidiDevice.Info object for the specified end point reference\n *\n *\/\n\nJNIEXPORT jobject JNICALL Java_uk_co_xfactorylibrarians_coremidi4j_CoreMidiDeviceProvider_getMidiDeviceInfo(JNIEnv *env, jobject obj, jint endPointReference) {\n\n MIDIDeviceRef deviceReference = NULL;\n CFStringRef deviceName = NULL;\n CFStringRef deviceManufacturer = NULL;\n CFStringRef deviceModel = NULL;\n SInt32 deviceOffline = NULL;\n SInt32 deviceUniqueID = 0;\n SInt32 deviceDriverVersion = 0;\n\n MIDIEntityRef entityReference = NULL;\n CFStringRef entityName = NULL;\n CFStringRef entityManufacturer = NULL;\n CFStringRef entityModel = NULL;\n SInt32 entityOffline = NULL;\n SInt32 entityUniqueID = 0;\n SInt32 entityDriverVersion = 0;\n\n \/\/ End point reference is in method parameters\n CFStringRef endpointName = NULL;\n CFStringRef endpointManufacturer = NULL;\n CFStringRef endpointModel = NULL;\n SInt32 endpointOffline = NULL;\n SInt32 endpointUniqueID = 0;\n SInt32 endpointDriverVersion = 0;\n\n \/\/ Find the Java CoreMIDIDeviceInfo class and its constructor\n jclass javaClass = env->FindClass(\"uk\/co\/xfactorylibrarians\/coremidi4j\/CoreMidiDeviceInfo\");\n jmethodID constructor = env->GetMethodID(javaClass, \"<init>\", \"(Ljava\/lang\/String;Ljava\/lang\/String;Ljava\/lang\/String;Ljava\/lang\/String;Ljava\/lang\/String;IILjava\/lang\/String;IILjava\/lang\/String;II)V\");\n\n \/\/ Get the endpoint properties\n MIDIObjectGetStringProperty (endPointReference, kMIDIPropertyName, &endpointName);\n MIDIObjectGetStringProperty (endPointReference, kMIDIPropertyModel, &endpointModel);\n MIDIObjectGetStringProperty (endPointReference, kMIDIPropertyManufacturer, &endpointManufacturer);\n MIDIObjectGetIntegerProperty(endPointReference, kMIDIPropertyOffline, &endpointOffline);\n MIDIObjectGetIntegerProperty(endPointReference, kMIDIPropertyUniqueID, &endpointUniqueID);\n MIDIObjectGetIntegerProperty(endPointReference, kMIDIPropertyDriverVersion, &endpointDriverVersion);\n\n \/\/ Get the entity properties\n MIDIEndpointGetEntity(endPointReference, &entityReference);\n\n MIDIObjectGetStringProperty (entityReference, kMIDIPropertyName, &entityName);\n MIDIObjectGetStringProperty (entityReference, kMIDIPropertyModel, &entityModel);\n MIDIObjectGetStringProperty (entityReference, kMIDIPropertyManufacturer, &entityManufacturer);\n MIDIObjectGetIntegerProperty(entityReference, kMIDIPropertyOffline, &entityOffline);\n MIDIObjectGetIntegerProperty(entityReference, kMIDIPropertyUniqueID, &entityUniqueID);\n MIDIObjectGetIntegerProperty(entityReference, kMIDIPropertyDriverVersion, &entityDriverVersion);\n\n \/\/ Get the device properties\n MIDIEntityGetDevice(entityReference, &deviceReference);\n\n MIDIObjectGetStringProperty (deviceReference, kMIDIPropertyName, &deviceName); \/\/ Get this again in case our string build fails\n MIDIObjectGetStringProperty (deviceReference, kMIDIPropertyModel, &deviceModel);\n MIDIObjectGetStringProperty (deviceReference, kMIDIPropertyManufacturer, &deviceManufacturer);\n MIDIObjectGetIntegerProperty(deviceReference, kMIDIPropertyOffline, &deviceOffline);\n MIDIObjectGetIntegerProperty(deviceReference, kMIDIPropertyUniqueID, &deviceUniqueID);\n MIDIObjectGetIntegerProperty(deviceReference, kMIDIPropertyDriverVersion, &deviceDriverVersion);\n\n long numberOfEntities = MIDIDeviceGetNumberOfEntities(deviceReference);\n\n\/\/ Uncomment these lines and debugPrintCFString (above) if you wish to view information as received on the native side during debugging.\n\/\/ std::cout << \"End Point \" << std::endl;\n\/\/ std::cout << \" End Point Reference \" << endPointReference << std::endl;\n\/\/ debugPrintCFString(\" End Point kMIDIPropertyName \", endpointName);\n\/\/ debugPrintCFString(\" End Point kMIDIPropertyModel \", endpointModel);\n\/\/ debugPrintCFString(\" End Point kMIDIPropertyManufacturer \", endpointManufacturer);\n\/\/ std::cout << \" End Point kMIDIPropertyOffline \" << endpointOffline << std::endl;\n\/\/ std::cout << \" End Point kMIDIPropertyUniqueID \" << endpointUniqueID << std::endl;\n\/\/ std::cout << \" End Point kMIDIPropertyDriverVersion \" << endpointDriverVersion << std::endl;\n\/\/ std::cout << std::endl;\n\/\/ std::cout << \" Entity Reference \" << entityReference << std::endl;\n\/\/ debugPrintCFString(\" Entity kMIDIPropertyName \", entityName);\n\/\/ debugPrintCFString(\" Entity kMIDIPropertyModel \", entityModel);\n\/\/ debugPrintCFString(\" Entity kMIDIPropertyManufacturer \", entityManufacturer);\n\/\/ std::cout << \" Entity kMIDIPropertyOffline \" << entityOffline << std::endl;\n\/\/ std::cout << \" Entity kMIDIPropertyUniqueID \" << entityUniqueID << std::endl;\n\/\/ std::cout << \" Entity kMIDIPropertyDriverVersion \" << entityDriverVersion << std::endl;\n\/\/ std::cout << std::endl;\n\/\/ std::cout << \" Device Reference \" << deviceReference << std::endl;\n\/\/ debugPrintCFString(\" Device kMIDIPropertyName \", deviceName);\n\/\/ debugPrintCFString(\" Device kMIDIPropertyModel \", deviceModel);\n\/\/ debugPrintCFString(\" Device kMIDIPropertyManufacturer \", deviceManufacturer);\n\/\/ std::cout << \" Device kMIDIPropertyOffline \" << deviceOffline << std::endl;\n\/\/ std::cout << \" Device kMIDIPropertyUniqueID \" << deviceUniqueID << std::endl;\n\/\/ std::cout << \" Device kMIDIPropertyDriverVersion \" << deviceDriverVersion << std::endl;\n\/\/ std::cout << std::endl;\n\/\/ std::cout << \" Number of entities \" << numberOfEntities << std::endl;\n\/\/ std::cout << std::endl;\n\n \/\/ Build the Device Info name. Add \"CoreMIDI4J - \" to the start of our device name if we can\n \/\/ And if the device has more than one entity then add the entity name\n CFMutableStringRef buildName = CFStringCreateMutable(NULL, 0);\n CFStringRef deviceInfoName;\n\n if ( buildName != NULL ) {\n\n if ( deviceName != NULL ) {\n\n CFStringAppend(buildName, (deviceName != NULL ) ? deviceName : CFSTR(\"<Unknown Device>\") );\n\n if ( numberOfEntities > 1 ) {\n\n CFStringAppend(buildName, CFSTR(\" \"));\n CFStringAppend(buildName, (endpointName != NULL ) ? endpointName : CFSTR(\"<Unknown Endpoint>\") );\n\n }\n\n } else {\n\n CFStringAppend(buildName, (endpointName != NULL ) ? endpointName : CFSTR(\"<Unknown Device>\") );\n\n }\n\n \/\/ Overwrite the deviceName with our updated one\n deviceInfoName = CFStringCreateCopy(NULL, buildName);\n\n \/\/ And release the temporary string\n CFRelease(buildName);\n\n } else {\n\n \/\/ Overwrite the deviceName with our updated one\n deviceInfoName = CFStringCreateCopy(NULL, deviceName);\n\n }\n\n char *deviceInfoNamePtr = safeCFStringCopyUTF8String ( deviceInfoName );\n char *deviceInfoManufacturerPtr = safeCFStringCopyUTF8String ( endpointManufacturer ); \/\/ The end point manufacturer name is always present\n char *deviceInfoDescriptionPtr = safeCFStringCopyUTF8String ( endpointModel ); \/\/ The end point model name is always present\n\n char *deviceNamePtr = safeCFStringCopyUTF8String ( deviceName );\n char *entityNamePtr = safeCFStringCopyUTF8String ( entityName );\n char *endPointNamePtr = safeCFStringCopyUTF8String ( endpointName );\n\n \/\/ TODO - Have seen reference that the device neds to be initialised to get the version. As we are still getting zero, force the string for now\n const char *deviceInfoVersion = \"Unknown Version\";\n\n \/\/ Create the Java Object\n jobject info = env->NewObject(javaClass,\n constructor,\n env->NewStringUTF(( deviceInfoNamePtr != NULL ) ? deviceInfoNamePtr : \"<Unknown Device>\"),\n env->NewStringUTF(( deviceInfoManufacturerPtr != NULL ) ? deviceInfoManufacturerPtr : \"<Unknown Manufacturer>\"),\n env->NewStringUTF(( deviceInfoDescriptionPtr != NULL ) ? deviceInfoDescriptionPtr : \"<Unknown Description>\"),\n env->NewStringUTF(deviceInfoVersion),\n env->NewStringUTF( ( deviceNamePtr != NULL ) ? deviceNamePtr : \"<Unknown Device>\"),\n deviceReference,\n deviceUniqueID,\n env->NewStringUTF( ( entityNamePtr != NULL) ? entityNamePtr : \"<Unknown Entity>\"),\n entityReference,\n entityUniqueID,\n env->NewStringUTF( ( endPointNamePtr != NULL ) ? endPointNamePtr : \"<Unknown Endpoint>\"),\n endPointReference,\n endpointUniqueID);\n\n free(deviceInfoNamePtr);\n free(deviceInfoManufacturerPtr);\n free(deviceInfoDescriptionPtr);\n free(deviceNamePtr);\n free(entityNamePtr);\n free(endPointNamePtr);\n\n return info;\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/* =======================================================================\n Copyright (c) 2011, Institute for Microelectronics,\n Institute for Analysis and Scientific Computing,\n TU Wien.\n\n -----------------\n ViennaGrid - The Vienna Grid Library\n -----------------\n\n Authors: Karl Rupp rupp@iue.tuwien.ac.at\n Josef Weinbub weinbub@iue.tuwien.ac.at\n \n (A list of additional contributors can be found in the PDF manual)\n\n License: MIT (X11), see file LICENSE in the base directory\n======================================================================= *\/\n\n#ifdef _MSC_VER \/\/Visual Studio complains about potentially dangerous things, which are perfectly legal in our context\n #pragma warning( disable : 4355 ) \/\/use of this in member initializer list\n #pragma warning( disable : 4503 ) \/\/truncated name decoration\n#endif\n\n\n#include \"viennagrid\/forwards.h\"\n#include \"viennagrid\/domain.hpp\"\n#include \"viennagrid\/config\/simplex.hpp\"\n#include \"viennagrid\/io\/netgen_reader.hpp\"\n#include \"viennagrid\/io\/vtk_writer.hpp\"\n\n\/\/Point-based algorithms:\n#include \"viennagrid\/algorithm\/cross_prod.hpp\"\n#include \"viennagrid\/algorithm\/inner_prod.hpp\"\n#include \"viennagrid\/algorithm\/norm.hpp\"\n#include \"viennagrid\/algorithm\/spanned_volume.hpp\"\n\n\/\/Cell-based algorithms:\n#include \"viennagrid\/algorithm\/centroid.hpp\"\n#include \"viennagrid\/algorithm\/circumcenter.hpp\"\n#include \"viennagrid\/algorithm\/surface.hpp\"\n#include \"viennagrid\/algorithm\/volume.hpp\"\n\n\/\/Domain-based algorithms:\n#include \"viennagrid\/algorithm\/boundary.hpp\"\n#include \"viennagrid\/algorithm\/refine.hpp\"\n#include \"viennagrid\/algorithm\/voronoi.hpp\"\n\n\nint main()\n{\n typedef viennagrid::config::tetrahedral_3d ConfigType;\n typedef viennagrid::result_of::domain<ConfigType>::type Domain;\n typedef ConfigType::cell_tag CellTag;\n \n typedef viennagrid::result_of::point<ConfigType>::type PointType;\n typedef viennagrid::result_of::ncell<ConfigType, 0>::type VertexType;\n typedef viennagrid::result_of::ncell<ConfigType, 1>::type EdgeType;\n typedef viennagrid::result_of::ncell<ConfigType,\n CellTag::dim>::type CellType;\n\n typedef viennagrid::result_of::ncell_range<Domain, 0>::type VertexRange;\n typedef viennagrid::result_of::ncell_range<Domain, CellTag::dim>::type CellRange;\n \n std::cout << \"------------------------------------------------------------ \" << std::endl;\n std::cout << \"-- ViennaGrid tutorial: Algorithms on points and elements -- \" << std::endl;\n std::cout << \"------------------------------------------------------------ \" << std::endl;\n std::cout << std::endl;\n \n Domain domain;\n \n \/\/\n \/\/ Read domain from Netgen file\n \/\/\n try\n {\n viennagrid::io::netgen_reader reader;\n #ifdef _MSC_VER \/\/Visual Studio builds in a subfolder\n reader(domain, \"..\/..\/examples\/data\/cube48.mesh\");\n #else\n reader(domain, \"..\/examples\/data\/cube48.mesh\");\n #endif\n }\n catch (std::exception & e)\n {\n std::cout << \"Error reading Netgen mesh file: \" << std::endl;\n std::cout << e.what() << std::endl;\n return EXIT_FAILURE;\n }\n\n \n \/\/\n \/\/ Part 1: Point-based algorithms:\n \/\/\n\n \/\/ Extract the first four points of the domain:\n VertexRange vertices = viennagrid::ncells(domain);\n PointType const & p0 = vertices[0].point();\n PointType const & p1 = vertices[1].point();\n PointType const & p2 = vertices[2].point();\n PointType const & p3 = vertices[3].point();\n\n std::cout << \"Point p0: \" << p0 << std::endl;\n std::cout << \"Point p1: \" << p1 << std::endl;\n std::cout << \"Point p2: \" << p2 << std::endl;\n std::cout << \"Point p3: \" << p3 << std::endl;\n \n \/\/ Run a few algorithms:\n std::cout << \"Cross-product of p1 and p2: \" << viennagrid::cross_prod(p1, p2) << std::endl;\n std::cout << \"Inner product of p1 and p2: \" << viennagrid::inner_prod(p1, p2) << std::endl;\n std::cout << \"1-Norm of p2: \" << viennagrid::norm_1(p2) << std::endl;\n std::cout << \"2-Norm of p2: \" << viennagrid::norm_2(p2) << std::endl;\n std::cout << \"Inf-Norm of p2: \" << viennagrid::norm_inf(p2) << std::endl;\n std::cout << \"Length of line [p0, p1]: \" << viennagrid::spanned_volume(p0, p1) << std::endl;\n std::cout << \"Area of triangle [p0, p1, p2]: \" << viennagrid::spanned_volume(p0, p1, p2) << std::endl;\n std::cout << \"Volume of tetrahedron [p0, p1, p2, p3]: \" << viennagrid::spanned_volume(p0, p1, p2, p3) << std::endl;\n \n std::cout << std::endl << \"--------------------------------\" << std::endl << std::endl;\n \n \n \/\/\n \/\/ Part 2: Cell-based algorithms:\n \/\/\n \n \/\/ Extract first cell from domain:\n CellType const & cell = viennagrid::ncells<CellTag::dim>(domain)[0];\n \n std::cout << \"cell: \" << std::endl << cell << std::endl;\n \n \/\/ Run algorithms:\n std::cout << \"Centroid of cell: \" << viennagrid::centroid(cell) << std::endl;\n std::cout << \"Circumcenter of cell: \" << viennagrid::circumcenter(cell) << std::endl;\n std::cout << \"Surface of cell: \" << viennagrid::surface(cell) << std::endl;\n std::cout << \"Volume of cell: \" << viennagrid::volume(cell) << std::endl;\n std::cout << std::endl;\n \n \n \/\/\n \/\/ Part 3: Domain-based algorithms (except interfaces. Refer to the multi-segment tutorial multi_segment.cpp)\n \/\/\n \n \/\/\n \/\/ Write Voronoi info to default ViennaData keys:\n viennagrid::apply_voronoi(domain);\n \n \/\/ Write Voronoi info again, this time using custom keys\n std::string interface_area_key = \"voronoi_interface\";\n std::string box_volume_key = \"voronoi_volume\";\n viennagrid::apply_voronoi(domain, interface_area_key, box_volume_key);\n \n std::cout << \"Voronoi box volume at first vertex: \"\n << viennadata::access<std::string, double>(box_volume_key)(vertices[0])\n << std::endl;\n \n\n \n \/\/ \n \/\/ Refine domain uniformly:\n Domain uniformly_refined_domain = viennagrid::refine_uniformly(domain);\n \/\/Domain uniformly_refined_domain = viennagrid::refine(domain, viennagrid::uniform_refinement_tag()); \/\/equivalent to previous line\n \n \/\/\n \/\/ Adaptive refinement: Tag first three cells in domain for refinement\n CellRange cells = viennagrid::ncells<CellTag::dim>(domain);\n viennadata::access<viennagrid::refinement_key, bool>()(cells[0]) = true;\n viennadata::access<viennagrid::refinement_key, bool>()(cells[1]) = true;\n viennadata::access<viennagrid::refinement_key, bool>()(cells[2]) = true;\n Domain adaptively_refined_domain = viennagrid::refine(domain, viennagrid::local_refinement_tag());\n \/\/Domain adaptively_refined_domain = viennagrid::refine_adaptively(domain); \/\/equivalent to previous line\n \n viennagrid::io::vtk_writer<Domain> writer;\n writer(uniformly_refined_domain, \"uniform_refinement\");\n writer(adaptively_refined_domain, \"local_refinement\");\n \n \n \/\/\n \/\/ Get boundary information of first vertex with respect to the full domain:\n std::cout << \"Boundary flag of first vertex with respect to domain: \"\n << viennagrid::is_boundary(vertices[0], domain) \/\/second argument is the enclosing complex (either a domain or a segment)\n << std::endl << std::endl;\n \n \n \n std::cout << \"-----------------------------------------------\" << std::endl;\n std::cout << \" \\\\o\/ Tutorial finished successfully! \\\\o\/ \" << std::endl;\n std::cout << \"-----------------------------------------------\" << std::endl;\n\n return EXIT_SUCCESS;\n}\n<commit_msg>started to adapt to new domain classes, work in progress!<commit_after>\/* =======================================================================\n Copyright (c) 2011, Institute for Microelectronics,\n Institute for Analysis and Scientific Computing,\n TU Wien.\n\n -----------------\n ViennaGrid - The Vienna Grid Library\n -----------------\n\n Authors: Karl Rupp rupp@iue.tuwien.ac.at\n Josef Weinbub weinbub@iue.tuwien.ac.at\n \n (A list of additional contributors can be found in the PDF manual)\n\n License: MIT (X11), see file LICENSE in the base directory\n======================================================================= *\/\n\n#ifdef _MSC_VER \/\/Visual Studio complains about potentially dangerous things, which are perfectly legal in our context\n #pragma warning( disable : 4355 ) \/\/use of this in member initializer list\n #pragma warning( disable : 4503 ) \/\/truncated name decoration\n#endif\n\n\n#include \"viennagrid\/forwards.hpp\"\n#include \"viennagrid\/domain.hpp\"\n#include \"viennagrid\/config\/simplex.hpp\"\n#include \"viennagrid\/io\/netgen_reader.hpp\"\n#include \"viennagrid\/io\/vtk_writer.hpp\"\n\n\/\/Point-based algorithms:\n#include \"viennagrid\/algorithm\/cross_prod.hpp\"\n#include \"viennagrid\/algorithm\/inner_prod.hpp\"\n#include \"viennagrid\/algorithm\/norm.hpp\"\n#include \"viennagrid\/algorithm\/spanned_volume.hpp\"\n\n\/\/Cell-based algorithms:\n#include \"viennagrid\/algorithm\/centroid.hpp\"\n#include \"viennagrid\/algorithm\/circumcenter.hpp\"\n#include \"viennagrid\/algorithm\/surface.hpp\"\n#include \"viennagrid\/algorithm\/volume.hpp\"\n\n\/\/Domain-based algorithms:\n#include \"viennagrid\/algorithm\/boundary.hpp\"\n#include \"viennagrid\/algorithm\/refine.hpp\"\n#include \"viennagrid\/algorithm\/voronoi.hpp\"\n\n\n#include <typeinfo>\n\nint main()\n{\n \n typedef viennagrid::point_t<double, viennagrid::cartesian_cs<3> > PointType;\n \n typedef viennagrid::result_of::geometric_domain_config< viennagrid::tetrahedron_tag, PointType, viennagrid::storage::pointer_hook_tag >::type DomainConfig;\n typedef viennagrid::result_of::geometric_domain< DomainConfig >::type Domain;\n \n \n\n \n typedef viennagrid::result_of::geometric_view<Domain>::type View;\n \n typedef viennagrid::tetrahedron_tag CellTag;\n \n typedef viennagrid::result_of::element<Domain, viennagrid::tetrahedron_tag>::type CellType;\n typedef viennagrid::result_of::element<Domain, viennagrid::triangle_tag>::type TriangleType;\n typedef viennagrid::result_of::element<Domain, viennagrid::line_tag>::type EdgeType;\n typedef viennagrid::result_of::element<Domain, viennagrid::vertex_tag>::type VertexType;\n typedef viennagrid::result_of::element_hook<Domain, viennagrid::vertex_tag>::type VertexHookType;\n \n typedef viennagrid::result_of::ncell_range<Domain, 0>::type VertexRange;\n typedef viennagrid::result_of::ncell_range<Domain, 3>::type CellRange;\n \n \n\/\/ typedef viennagrid::config::tetrahedral_3d ConfigType;\n\/\/ typedef viennagrid::result_of::domain<ConfigType>::type Domain;\n\/\/ typedef ConfigType::cell_tag CellTag;\n\/\/ \n\/\/ typedef viennagrid::result_of::point<ConfigType>::type PointType;\n\/\/ typedef viennagrid::result_of::ncell<ConfigType, 0>::type VertexType;\n\/\/ typedef viennagrid::result_of::ncell<ConfigType, 1>::type EdgeType;\n\/\/ typedef viennagrid::result_of::ncell<ConfigType,\n\/\/ CellTag::dim>::type CellType;\n\/\/ \n\/\/ typedef viennagrid::result_of::ncell_range<Domain, 0>::type VertexRange;\n\/\/ typedef viennagrid::result_of::ncell_range<Domain, CellTag::dim>::type CellRange;\n \n std::cout << \"------------------------------------------------------------ \" << std::endl;\n std::cout << \"-- ViennaGrid tutorial: Algorithms on points and elements -- \" << std::endl;\n std::cout << \"------------------------------------------------------------ \" << std::endl;\n std::cout << std::endl;\n \n Domain domain;\n std::vector<View> segments;\n \n \/\/\n \/\/ Read domain from Netgen file\n \/\/\n try\n {\n viennagrid::io::netgen_reader<CellType> reader;\n #ifdef _MSC_VER \/\/Visual Studio builds in a subfolder\n reader(domain, segments, \"..\/..\/examples\/data\/cube48.mesh\");\n #else\n reader(domain, segments, \"..\/examples\/data\/cube48.mesh\");\n #endif\n }\n catch (std::exception & e)\n {\n std::cout << \"Error reading Netgen mesh file: \" << std::endl;\n std::cout << e.what() << std::endl;\n return EXIT_FAILURE;\n }\n \n \/\/\n \/\/ Part 1: Point-based algorithms:\n \/\/\n\n \/\/ Extract the first four points of the domain:\n VertexRange vertices = viennagrid::ncells<0>(domain);\n \n PointType const & p0 = viennagrid::point(domain, vertices[0]);\n PointType const & p1 = viennagrid::point(domain, vertices[1]);\n PointType const & p2 = viennagrid::point(domain, vertices[2]);\n PointType const & p3 = viennagrid::point(domain, vertices[3]);\n \n std::cout << \"Point p0: \" << p0 << std::endl;\n std::cout << \"Point p1: \" << p1 << std::endl;\n std::cout << \"Point p2: \" << p2 << std::endl;\n std::cout << \"Point p3: \" << p3 << std::endl;\n \n \/\/ Run a few algorithms:\n std::cout << \"Cross-product of p1 and p2: \" << viennagrid::cross_prod(p1, p2) << std::endl;\n std::cout << \"Inner product of p1 and p2: \" << viennagrid::inner_prod(p1, p2) << std::endl;\n std::cout << \"1-Norm of p2: \" << viennagrid::norm_1(p2) << std::endl;\n std::cout << \"2-Norm of p2: \" << viennagrid::norm_2(p2) << std::endl;\n std::cout << \"Inf-Norm of p2: \" << viennagrid::norm_inf(p2) << std::endl;\n std::cout << \"Length of line [p0, p1]: \" << viennagrid::spanned_volume(p0, p1) << std::endl;\n std::cout << \"Area of triangle [p0, p1, p2]: \" << viennagrid::spanned_volume(p0, p1, p2) << std::endl;\n std::cout << \"Volume of tetrahedron [p0, p1, p2, p3]: \" << viennagrid::spanned_volume(p0, p1, p2, p3) << std::endl;\n \n std::cout << std::endl << \"--------------------------------\" << std::endl << std::endl;\n \n \n \/\/\n \/\/ Part 2: Cell-based algorithms:\n \/\/\n \n \/\/ Extract first cell from domain:\n CellType const & cell = viennagrid::elements<CellTag>(domain)[0];\n \n std::cout << \"cell: \" << std::endl << cell << std::endl;\n \n \/\/ Run algorithms:\n std::cout << \"Centroid of cell: \" << viennagrid::centroid(cell, domain) << std::endl;\n std::cout << \"Circumcenter of cell: \" << viennagrid::circumcenter(cell, domain) << std::endl;\n std::cout << \"Surface of cell: \" << viennagrid::surface(cell, domain) << std::endl;\n std::cout << \"Volume of cell: \" << viennagrid::volume(cell, domain) << std::endl;\n std::cout << std::endl;\n \n std::cout << \"Volume of domain: \" << viennagrid::volume<viennagrid::tetrahedron_tag>(domain) << std::endl;\n std::cout << \"Surface of domain: \" << viennagrid::surface<viennagrid::tetrahedron_tag>(domain) << std::endl;\n \n \n \/\/\n \/\/ Part 3: Domain-based algorithms (except interfaces. Refer to the multi-segment tutorial multi_segment.cpp)\n \/\/\n \n \/\/\n \/\/ Write Voronoi info to default ViennaData keys:\n viennagrid::apply_voronoi<CellType>(domain);\n \n \/\/ Write Voronoi info again, this time using custom keys\n std::string interface_area_key = \"voronoi_interface\";\n std::string box_volume_key = \"voronoi_volume\";\n viennagrid::apply_voronoi<CellType>(domain, interface_area_key, box_volume_key);\n \n std::cout << \"Voronoi box volume at first vertex: \"\n << viennadata::access<std::string, double>(box_volume_key)(vertices[0])\n << std::endl;\n \n\n \n \/\/ \n \/\/ Refine domain uniformly:\n \/\/Domain uniformly_refined_domain = viennagrid::refine_uniformly(domain);\n \/\/Domain uniformly_refined_domain = viennagrid::refine(domain, viennagrid::uniform_refinement_tag()); \/\/equivalent to previous line\n \n \/\/\n \/\/ Adaptive refinement: Tag first three cells in domain for refinement\n CellRange cells = viennagrid::elements<CellTag>(domain);\n viennadata::access<viennagrid::refinement_key, bool>()(cells[0]) = true;\n viennadata::access<viennagrid::refinement_key, bool>()(cells[1]) = true;\n viennadata::access<viennagrid::refinement_key, bool>()(cells[2]) = true;\n \/\/Domain adaptively_refined_domain = viennagrid::refine<CellTag>(domain, viennagrid::local_refinement_tag());\n \/\/Domain adaptively_refined_domain = viennagrid::refine_adaptively(domain); \/\/equivalent to previous line\n \n\/\/ viennagrid::io::vtk_writer<Domain> writer;\n\/\/ writer(uniformly_refined_domain, \"uniform_refinement\");\n\/\/ writer(adaptively_refined_domain, \"local_refinement\");\n \n \n \/\/\n \/\/ Get boundary information of first vertex with respect to the full domain:\n std::cout << \"Boundary flag of first vertex with respect to domain: \"\n << viennagrid::is_boundary(vertices[0], domain) \/\/second argument is the enclosing complex (either a domain or a segment)\n << std::endl << std::endl;\n \n \n \n std::cout << \"-----------------------------------------------\" << std::endl;\n std::cout << \" \\\\o\/ Tutorial finished successfully! \\\\o\/ \" << std::endl;\n std::cout << \"-----------------------------------------------\" << std::endl;\n\n return EXIT_SUCCESS;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2014 Vladimir Alyamkin. All Rights Reserved.\n\n#include \"VaRestPluginPrivatePCH.h\"\n\nFString UVaRestParseManager::ParseURL(TEXT(\"https:\/\/api.parse.com\/1\/\"));\nFString UVaRestParseManager::ParseAppId(TEXT(\"\"));\nFString UVaRestParseManager::ParseApiKey(TEXT(\"\"));\n\nUVaRestParseManager::UVaRestParseManager(const class FPostConstructInitializeProperties& PCIP)\n\t: Super(PCIP)\n{\n\n}\n\nUVaRestParseManager* UVaRestParseManager::ConstructParseRequest(\n\tUObject* WorldContextObject, \n\tERequestVerb::Type Verb,\n\tERequestContentType::Type ContentType)\n{\n\treturn (UVaRestParseManager*)ConstructRequestExt(WorldContextObject, Verb, ContentType);\n}\n\nvoid UVaRestParseManager::ProcessParseURL(\n\tconst FString& ParseModule, \n\tconst FString& ParseClass, \n\tconst FString& ParseObjectId, \n\tconst FString& ParseSessionToken)\n{\n\tFString RequestUrl = ParseURL;\n\n\t\/\/ Build the full request url\n\tif (!ParseModule.IsEmpty())\n\t{\n\t\tRequestUrl += ParseModule;\n\n\t\tif (!ParseClass.IsEmpty())\n\t\t{\n\t\t\tRequestUrl += \"\/\" + ParseClass;\n\n\t\t\tif (!ParseObjectId.IsEmpty())\n\t\t\t{\n\t\t\t\tRequestUrl += \"\/\" + ParseObjectId;\n\t\t\t}\n\t\t}\n\t}\n\n\tTSharedRef<IHttpRequest> HttpRequest = FHttpModule::Get().CreateRequest();\n\tHttpRequest->SetURL(RequestUrl);\n\n\tHttpRequest->SetHeader(\"X-Parse-Application-Id\", ParseAppId);\n\tHttpRequest->SetHeader(\"X-Parse-REST-API-Key\", ParseApiKey);\n\n\tif (!ParseSessionToken.IsEmpty())\n\t{\n\t\tHttpRequest->SetHeader(\"X-Parse-Session-Token\", ParseSessionToken);\n\t}\n\n\tProcessRequest(HttpRequest);\n}\n\nvoid UVaRestParseManager::SetParseAuthData(FString AppId, FString ApiKey)\n{\n\tParseAppId = AppId;\n\tParseApiKey = ApiKey;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Quering helpers\n\nFString UVaRestParseManager::ConstructPointer(const FString& ClassName, const FString& ObjectId)\n{\n\treturn FString::Printf(TEXT(\"{\\\"__type\\\":\\\"Pointer\\\",\\\"className\\\":\\\"%s\\\",\\\"objectId\\\":\\\"%s\\\"}\"), *ClassName, *ObjectId);\n}\n\nFString UVaRestParseManager::ConstructWhereQuerySimple(const FString& Key, const FString& Value)\n{\n\treturn FString::Printf(TEXT(\"where={\\\"%s\\\":%s}\"), *Key, *Value);\n}\n\nFString UVaRestParseManager::ConstructWhereQuery(UVaRestJsonObject* JsonObject)\n{\n\t\/\/ Serialize json data to string\n\tFString OutputString;\n\tTSharedRef< TJsonWriter<> > Writer = TJsonWriterFactory<>::Create(&OutputString);\n\tFJsonSerializer::Serialize(JsonObject->GetRootObject().ToSharedRef(), Writer);\n\n\treturn TEXT(\"where=\") + OutputString;\n}\n\nFString UVaRestParseManager::GetHappyMessage()\n{\n\treturn FString(\"Happy New Year!\");\n}\n<commit_msg>- parse object id is appended to the end of the request even if no class is defined<commit_after>\/\/ Copyright 2014 Vladimir Alyamkin. All Rights Reserved.\n\n#include \"VaRestPluginPrivatePCH.h\"\n\nFString UVaRestParseManager::ParseURL(TEXT(\"https:\/\/api.parse.com\/1\/\"));\nFString UVaRestParseManager::ParseAppId(TEXT(\"\"));\nFString UVaRestParseManager::ParseApiKey(TEXT(\"\"));\n\nUVaRestParseManager::UVaRestParseManager(const class FPostConstructInitializeProperties& PCIP)\n\t: Super(PCIP)\n{\n\n}\n\nUVaRestParseManager* UVaRestParseManager::ConstructParseRequest(\n\tUObject* WorldContextObject, \n\tERequestVerb::Type Verb,\n\tERequestContentType::Type ContentType)\n{\n\treturn (UVaRestParseManager*)ConstructRequestExt(WorldContextObject, Verb, ContentType);\n}\n\nvoid UVaRestParseManager::ProcessParseURL(\n\tconst FString& ParseModule, \n\tconst FString& ParseClass, \n\tconst FString& ParseObjectId, \n\tconst FString& ParseSessionToken)\n{\n\tFString RequestUrl = ParseURL;\n\n\t\/\/ Build the full request url\n\tif (!ParseModule.IsEmpty())\n\t{\n\t\tRequestUrl += ParseModule;\n\n\t\tif (!ParseClass.IsEmpty())\n\t\t{\n\t\t\tRequestUrl += \"\/\" + ParseClass;\n\t\t}\n\n\t\tif (!ParseObjectId.IsEmpty())\n\t\t{\n\t\t\tRequestUrl += \"\/\" + ParseObjectId;\n\t\t}\n\t}\n\n\tTSharedRef<IHttpRequest> HttpRequest = FHttpModule::Get().CreateRequest();\n\tHttpRequest->SetURL(RequestUrl);\n\n\tHttpRequest->SetHeader(\"X-Parse-Application-Id\", ParseAppId);\n\tHttpRequest->SetHeader(\"X-Parse-REST-API-Key\", ParseApiKey);\n\n\tif (!ParseSessionToken.IsEmpty())\n\t{\n\t\tHttpRequest->SetHeader(\"X-Parse-Session-Token\", ParseSessionToken);\n\t}\n\n\tProcessRequest(HttpRequest);\n}\n\nvoid UVaRestParseManager::SetParseAuthData(FString AppId, FString ApiKey)\n{\n\tParseAppId = AppId;\n\tParseApiKey = ApiKey;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Quering helpers\n\nFString UVaRestParseManager::ConstructPointer(const FString& ClassName, const FString& ObjectId)\n{\n\treturn FString::Printf(TEXT(\"{\\\"__type\\\":\\\"Pointer\\\",\\\"className\\\":\\\"%s\\\",\\\"objectId\\\":\\\"%s\\\"}\"), *ClassName, *ObjectId);\n}\n\nFString UVaRestParseManager::ConstructWhereQuerySimple(const FString& Key, const FString& Value)\n{\n\treturn FString::Printf(TEXT(\"where={\\\"%s\\\":%s}\"), *Key, *Value);\n}\n\nFString UVaRestParseManager::ConstructWhereQuery(UVaRestJsonObject* JsonObject)\n{\n\t\/\/ Serialize json data to string\n\tFString OutputString;\n\tTSharedRef< TJsonWriter<> > Writer = TJsonWriterFactory<>::Create(&OutputString);\n\tFJsonSerializer::Serialize(JsonObject->GetRootObject().ToSharedRef(), Writer);\n\n\treturn TEXT(\"where=\") + OutputString;\n}\n\nFString UVaRestParseManager::GetHappyMessage()\n{\n\treturn FString(\"Happy New Year!\");\n}\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: seqstream.cxx,v $\n *\n * $Revision: 1.5 $\n *\n * last change: $Author: kz $ $Date: 2004-10-04 21:07:12 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef _COMPHELPER_SEQSTREAM_HXX\n#include <comphelper\/seqstream.hxx>\n#endif\n\n#include <memory.h> \/\/ for memcpy\n\nnamespace comphelper\n{\nusing namespace ::com::sun::star::lang;\nusing namespace ::com::sun::star::io;\nusing namespace ::com::sun::star::uno;\nusing namespace ::osl;\n\n\/\/---------------------------------------------------------------------------------------------\n\/\/ class SequenceInputStream\n\/\/---------------------------------------------------------------------------------------------\n\n\/\/------------------------------------------------------------------\nSequenceInputStream::SequenceInputStream(const ByteSequence& rData)\n: m_aData(rData)\n, m_nPos(0)\n{\n}\n\n\/\/ checks if closed, returns available size, not mutex-protected\n\/\/------------------------------------------------------------------\ninline sal_Int32 SequenceInputStream::avail()\n{\n if (m_nPos == -1)\n throw NotConnectedException(::rtl::OUString(), *this);\n\n return m_aData.getLength() - m_nPos;\n}\n\n\/\/ com::sun::star::io::XInputStream\n\/\/------------------------------------------------------------------\nsal_Int32 SAL_CALL SequenceInputStream::readBytes( Sequence<sal_Int8>& aData, sal_Int32 nBytesToRead )\n throw(NotConnectedException, BufferSizeExceededException,\n IOException, RuntimeException)\n{\n ::osl::MutexGuard aGuard( m_aMutex );\n\n sal_Int32 nAvail = avail();\n\n if (nBytesToRead < 0)\n throw BufferSizeExceededException(::rtl::OUString(),*this);\n\n if (nAvail < nBytesToRead)\n nBytesToRead = nAvail;\n\n aData.realloc(nBytesToRead);\n memcpy(aData.getArray(), m_aData.getConstArray() + m_nPos, nBytesToRead);\n m_nPos += nBytesToRead;\n\n return nBytesToRead;\n}\n\n\/\/------------------------------------------------------------------\nsal_Int32 SAL_CALL SequenceInputStream::readSomeBytes( Sequence<sal_Int8>& aData, sal_Int32 nMaxBytesToRead )\n throw(NotConnectedException, BufferSizeExceededException,\n IOException, RuntimeException)\n{\n \/\/ all data is available at once\n return readBytes(aData, nMaxBytesToRead);\n}\n\n\/\/------------------------------------------------------------------\nvoid SAL_CALL SequenceInputStream::skipBytes( sal_Int32 nBytesToSkip )\n throw(NotConnectedException, BufferSizeExceededException,\n IOException, RuntimeException)\n{\n ::osl::MutexGuard aGuard( m_aMutex );\n\n sal_Int32 nAvail = avail();\n\n if (nBytesToSkip < 0)\n throw BufferSizeExceededException(::rtl::OUString(),*this);\n\n if (nAvail < nBytesToSkip)\n nBytesToSkip = nAvail;\n\n m_nPos += nBytesToSkip;\n}\n\n\/\/------------------------------------------------------------------\nsal_Int32 SAL_CALL SequenceInputStream::available( )\n throw(NotConnectedException, IOException, RuntimeException)\n{\n ::osl::MutexGuard aGuard( m_aMutex );\n\n return avail();\n}\n\n\/\/------------------------------------------------------------------\nvoid SAL_CALL SequenceInputStream::closeInput( )\n throw(NotConnectedException, IOException, RuntimeException)\n{\n if (m_nPos == -1)\n throw NotConnectedException(::rtl::OUString(), *this);\n\n m_nPos = -1;\n}\n\nvoid SAL_CALL SequenceInputStream::seek( sal_Int64 location ) throw (IllegalArgumentException, IOException, RuntimeException)\n{\n if ( location > m_aData.getLength()-1 || location < 0 || location > SAL_MAX_INT32 )\n throw IllegalArgumentException();\n m_nPos = (sal_Int32) location;\n}\n\nsal_Int64 SAL_CALL SequenceInputStream::getPosition() throw (IOException, RuntimeException)\n{\n return m_nPos;\n}\n\nsal_Int64 SAL_CALL SequenceInputStream::getLength( ) throw (IOException, RuntimeException)\n{\n return m_aData.getLength();\n}\n\n\/\/--------------------------------------------------------------------------\nOSequenceOutputStream::OSequenceOutputStream(Sequence< sal_Int8 >& _rSeq, double _nResizeFactor, sal_Int32 _nMinimumResize, sal_Int32 _nMaximumResize)\n :m_rSequence(_rSeq)\n ,m_nResizeFactor(_nResizeFactor)\n ,m_nMinimumResize(_nMinimumResize)\n ,m_nMaximumResize(_nMaximumResize)\n ,m_nSize(0) \/\/ starting at position 0\n ,m_bConnected(sal_True)\n{\n OSL_ENSURE(m_nResizeFactor > 1, \"OSequenceOutputStream::OSequenceOutputStream : invalid resize factor !\");\n OSL_ENSURE((m_nMaximumResize < 0) || (m_nMaximumResize > m_nMinimumResize),\n \"OSequenceOutputStream::OSequenceOutputStream : these limits don't make any sense !\");\n\n if (m_nResizeFactor <= 1)\n m_nResizeFactor = 1.3;\n if ((m_nMaximumResize >= 0) && (m_nMaximumResize <= m_nMinimumResize))\n m_nMaximumResize = m_nMinimumResize * 2;\n \/\/ this heuristic is as good as any other ... supply better parameters if you don't like it :)\n}\n\n\/\/--------------------------------------------------------------------------\nvoid SAL_CALL OSequenceOutputStream::writeBytes( const Sequence< sal_Int8 >& _rData ) throw(NotConnectedException, BufferSizeExceededException, IOException, RuntimeException)\n{\n MutexGuard aGuard(m_aMutex);\n if (!m_bConnected)\n throw NotConnectedException();\n\n \/\/ ensure the sequence has enoungh space left\n if (m_nSize + _rData.getLength() > m_rSequence.getLength())\n {\n sal_Int32 nCurrentLength = m_rSequence.getLength();\n sal_Int32 nNewLength = nCurrentLength * m_nResizeFactor;\n\n if (m_nMinimumResize > nNewLength - nCurrentLength)\n \/\/ we have a minimum so it's not too inefficient for small sequences and small write requests\n nNewLength = nCurrentLength + m_nMinimumResize;\n\n if ((m_nMaximumResize > 0) && (nNewLength - nCurrentLength > m_nMaximumResize))\n \/\/ such a large step is not allowed\n nNewLength = nCurrentLength + m_nMaximumResize;\n\n if (nNewLength < m_nSize + _rData.getLength())\n { \/\/ it's not enough .... the data would not fit\n\n \/\/ let's take the double amount of the length of the data to be written, as the next write\n \/\/ request could be as large as this one\n sal_Int32 nNewGrowth = _rData.getLength() * 2;\n if ((m_nMaximumResize > 0) && (nNewGrowth > m_nMaximumResize))\n { \/\/ we came to the limit, again ...\n nNewGrowth = m_nMaximumResize;\n if (nNewGrowth + nCurrentLength < m_nSize + _rData.getLength())\n \/\/ but it would not fit if we respect the limit\n nNewGrowth = m_nSize + _rData.getLength() - nCurrentLength;\n }\n nNewLength = nCurrentLength + nNewGrowth;\n }\n\n \/\/ round it off to the next multiple of 4 ...\n nNewLength = (nNewLength + 3) \/ 4 * 4;\n\n m_rSequence.realloc(nNewLength);\n }\n\n OSL_ENSURE(m_rSequence.getLength() >= m_nSize + _rData.getLength(),\n \"ooops ... the realloc algorithm seems to be wrong :( !\");\n\n memcpy(m_rSequence.getArray() + m_nSize, _rData.getConstArray(), _rData.getLength());\n m_nSize += _rData.getLength();\n}\n\n\/\/--------------------------------------------------------------------------\nvoid SAL_CALL OSequenceOutputStream::flush( ) throw(NotConnectedException, BufferSizeExceededException, IOException, RuntimeException)\n{\n MutexGuard aGuard(m_aMutex);\n if (!m_bConnected)\n throw NotConnectedException();\n\n \/\/ nothing to do here\n}\n\n\/\/--------------------------------------------------------------------------\nvoid SAL_CALL OSequenceOutputStream::closeOutput( ) throw(NotConnectedException, BufferSizeExceededException, IOException, RuntimeException)\n{\n MutexGuard aGuard(m_aMutex);\n if (!m_bConnected)\n throw NotConnectedException();\n\n \/\/ cut the sequence to the real size\n m_rSequence.realloc(m_nSize);\n \/\/ and don't allow any further accesses\n m_bConnected = sal_False;\n}\n\n} \/\/ namespace comphelper\n<commit_msg>INTEGRATION: CWS ooo19126 (1.5.116); FILE MERGED 2005\/09\/05 15:24:13 rt 1.5.116.1: #i54170# Change license header: remove SISSL<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: seqstream.cxx,v $\n *\n * $Revision: 1.6 $\n *\n * last change: $Author: rt $ $Date: 2005-09-08 03:01:05 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef _COMPHELPER_SEQSTREAM_HXX\n#include <comphelper\/seqstream.hxx>\n#endif\n\n#include <memory.h> \/\/ for memcpy\n\nnamespace comphelper\n{\nusing namespace ::com::sun::star::lang;\nusing namespace ::com::sun::star::io;\nusing namespace ::com::sun::star::uno;\nusing namespace ::osl;\n\n\/\/---------------------------------------------------------------------------------------------\n\/\/ class SequenceInputStream\n\/\/---------------------------------------------------------------------------------------------\n\n\/\/------------------------------------------------------------------\nSequenceInputStream::SequenceInputStream(const ByteSequence& rData)\n: m_aData(rData)\n, m_nPos(0)\n{\n}\n\n\/\/ checks if closed, returns available size, not mutex-protected\n\/\/------------------------------------------------------------------\ninline sal_Int32 SequenceInputStream::avail()\n{\n if (m_nPos == -1)\n throw NotConnectedException(::rtl::OUString(), *this);\n\n return m_aData.getLength() - m_nPos;\n}\n\n\/\/ com::sun::star::io::XInputStream\n\/\/------------------------------------------------------------------\nsal_Int32 SAL_CALL SequenceInputStream::readBytes( Sequence<sal_Int8>& aData, sal_Int32 nBytesToRead )\n throw(NotConnectedException, BufferSizeExceededException,\n IOException, RuntimeException)\n{\n ::osl::MutexGuard aGuard( m_aMutex );\n\n sal_Int32 nAvail = avail();\n\n if (nBytesToRead < 0)\n throw BufferSizeExceededException(::rtl::OUString(),*this);\n\n if (nAvail < nBytesToRead)\n nBytesToRead = nAvail;\n\n aData.realloc(nBytesToRead);\n memcpy(aData.getArray(), m_aData.getConstArray() + m_nPos, nBytesToRead);\n m_nPos += nBytesToRead;\n\n return nBytesToRead;\n}\n\n\/\/------------------------------------------------------------------\nsal_Int32 SAL_CALL SequenceInputStream::readSomeBytes( Sequence<sal_Int8>& aData, sal_Int32 nMaxBytesToRead )\n throw(NotConnectedException, BufferSizeExceededException,\n IOException, RuntimeException)\n{\n \/\/ all data is available at once\n return readBytes(aData, nMaxBytesToRead);\n}\n\n\/\/------------------------------------------------------------------\nvoid SAL_CALL SequenceInputStream::skipBytes( sal_Int32 nBytesToSkip )\n throw(NotConnectedException, BufferSizeExceededException,\n IOException, RuntimeException)\n{\n ::osl::MutexGuard aGuard( m_aMutex );\n\n sal_Int32 nAvail = avail();\n\n if (nBytesToSkip < 0)\n throw BufferSizeExceededException(::rtl::OUString(),*this);\n\n if (nAvail < nBytesToSkip)\n nBytesToSkip = nAvail;\n\n m_nPos += nBytesToSkip;\n}\n\n\/\/------------------------------------------------------------------\nsal_Int32 SAL_CALL SequenceInputStream::available( )\n throw(NotConnectedException, IOException, RuntimeException)\n{\n ::osl::MutexGuard aGuard( m_aMutex );\n\n return avail();\n}\n\n\/\/------------------------------------------------------------------\nvoid SAL_CALL SequenceInputStream::closeInput( )\n throw(NotConnectedException, IOException, RuntimeException)\n{\n if (m_nPos == -1)\n throw NotConnectedException(::rtl::OUString(), *this);\n\n m_nPos = -1;\n}\n\nvoid SAL_CALL SequenceInputStream::seek( sal_Int64 location ) throw (IllegalArgumentException, IOException, RuntimeException)\n{\n if ( location > m_aData.getLength()-1 || location < 0 || location > SAL_MAX_INT32 )\n throw IllegalArgumentException();\n m_nPos = (sal_Int32) location;\n}\n\nsal_Int64 SAL_CALL SequenceInputStream::getPosition() throw (IOException, RuntimeException)\n{\n return m_nPos;\n}\n\nsal_Int64 SAL_CALL SequenceInputStream::getLength( ) throw (IOException, RuntimeException)\n{\n return m_aData.getLength();\n}\n\n\/\/--------------------------------------------------------------------------\nOSequenceOutputStream::OSequenceOutputStream(Sequence< sal_Int8 >& _rSeq, double _nResizeFactor, sal_Int32 _nMinimumResize, sal_Int32 _nMaximumResize)\n :m_rSequence(_rSeq)\n ,m_nResizeFactor(_nResizeFactor)\n ,m_nMinimumResize(_nMinimumResize)\n ,m_nMaximumResize(_nMaximumResize)\n ,m_nSize(0) \/\/ starting at position 0\n ,m_bConnected(sal_True)\n{\n OSL_ENSURE(m_nResizeFactor > 1, \"OSequenceOutputStream::OSequenceOutputStream : invalid resize factor !\");\n OSL_ENSURE((m_nMaximumResize < 0) || (m_nMaximumResize > m_nMinimumResize),\n \"OSequenceOutputStream::OSequenceOutputStream : these limits don't make any sense !\");\n\n if (m_nResizeFactor <= 1)\n m_nResizeFactor = 1.3;\n if ((m_nMaximumResize >= 0) && (m_nMaximumResize <= m_nMinimumResize))\n m_nMaximumResize = m_nMinimumResize * 2;\n \/\/ this heuristic is as good as any other ... supply better parameters if you don't like it :)\n}\n\n\/\/--------------------------------------------------------------------------\nvoid SAL_CALL OSequenceOutputStream::writeBytes( const Sequence< sal_Int8 >& _rData ) throw(NotConnectedException, BufferSizeExceededException, IOException, RuntimeException)\n{\n MutexGuard aGuard(m_aMutex);\n if (!m_bConnected)\n throw NotConnectedException();\n\n \/\/ ensure the sequence has enoungh space left\n if (m_nSize + _rData.getLength() > m_rSequence.getLength())\n {\n sal_Int32 nCurrentLength = m_rSequence.getLength();\n sal_Int32 nNewLength = nCurrentLength * m_nResizeFactor;\n\n if (m_nMinimumResize > nNewLength - nCurrentLength)\n \/\/ we have a minimum so it's not too inefficient for small sequences and small write requests\n nNewLength = nCurrentLength + m_nMinimumResize;\n\n if ((m_nMaximumResize > 0) && (nNewLength - nCurrentLength > m_nMaximumResize))\n \/\/ such a large step is not allowed\n nNewLength = nCurrentLength + m_nMaximumResize;\n\n if (nNewLength < m_nSize + _rData.getLength())\n { \/\/ it's not enough .... the data would not fit\n\n \/\/ let's take the double amount of the length of the data to be written, as the next write\n \/\/ request could be as large as this one\n sal_Int32 nNewGrowth = _rData.getLength() * 2;\n if ((m_nMaximumResize > 0) && (nNewGrowth > m_nMaximumResize))\n { \/\/ we came to the limit, again ...\n nNewGrowth = m_nMaximumResize;\n if (nNewGrowth + nCurrentLength < m_nSize + _rData.getLength())\n \/\/ but it would not fit if we respect the limit\n nNewGrowth = m_nSize + _rData.getLength() - nCurrentLength;\n }\n nNewLength = nCurrentLength + nNewGrowth;\n }\n\n \/\/ round it off to the next multiple of 4 ...\n nNewLength = (nNewLength + 3) \/ 4 * 4;\n\n m_rSequence.realloc(nNewLength);\n }\n\n OSL_ENSURE(m_rSequence.getLength() >= m_nSize + _rData.getLength(),\n \"ooops ... the realloc algorithm seems to be wrong :( !\");\n\n memcpy(m_rSequence.getArray() + m_nSize, _rData.getConstArray(), _rData.getLength());\n m_nSize += _rData.getLength();\n}\n\n\/\/--------------------------------------------------------------------------\nvoid SAL_CALL OSequenceOutputStream::flush( ) throw(NotConnectedException, BufferSizeExceededException, IOException, RuntimeException)\n{\n MutexGuard aGuard(m_aMutex);\n if (!m_bConnected)\n throw NotConnectedException();\n\n \/\/ nothing to do here\n}\n\n\/\/--------------------------------------------------------------------------\nvoid SAL_CALL OSequenceOutputStream::closeOutput( ) throw(NotConnectedException, BufferSizeExceededException, IOException, RuntimeException)\n{\n MutexGuard aGuard(m_aMutex);\n if (!m_bConnected)\n throw NotConnectedException();\n\n \/\/ cut the sequence to the real size\n m_rSequence.realloc(m_nSize);\n \/\/ and don't allow any further accesses\n m_bConnected = sal_False;\n}\n\n} \/\/ namespace comphelper\n<|endoftext|>"} {"text":"<commit_before>#include \"RepairPartitioningPrototype.h\"\nusing namespace std;\n\nvoid RepairPartitioningPrototype::printIDtoWordMapping(unordered_map<unsigned, string>& IDsToWords, ostream& os)\n{\n\tfor (unordered_map<unsigned, string>::iterator it = IDsToWords.begin(); it != IDsToWords.end(); it++)\n\t{\n\t\tos << it->first << \": \" << it->second << endl;\n\t}\n}\n\nvoid RepairPartitioningPrototype::writeAssociations(const vector<Association>& associations, ostream& os)\n{\n\tfor (size_t i = 0; i < associations.size(); i++)\n\t{\n\t\tos << associations[i];\n\t}\n}\n\ndouble RepairPartitioningPrototype::runRepairPartitioning(\n\tvector<vector<unsigned> > versions,\n\tunordered_map<unsigned, string>& IDsToWords, \n\tunsigned*& offsetsAllVersions, \n\tunsigned*& versionPartitionSizes, \n\tvector<Association>& associations,\n\tunsigned minFragSize, \n\tfloat fragmentationCoefficient, \n\tunsigned repairStoppingPoint, \n\tunsigned numLevelsDown, \n\tunsigned method,\n\tbool printFragments, \n\tbool printAssociations)\n{\n\tRepairAlgorithm repairAlg(versions);\n\n\trepairAlg.run();\n\n\tvector<VersionDataItem> versionData = repairAlg.getVersionData();\n\n\tassociations = repairAlg.getAssociations();\n\n\t\/\/ Use the result of repair to get a partitioning of the document\n\t\/\/ Hopefully this partitioning gives us fragments that occur many times\n\tRepairDocumentPartition partition = RepairDocumentPartition(versionData, associations, numLevelsDown, minFragSize, fragmentationCoefficient, method);\n\n\t\/\/ The offsets that define fragments, for all versions [v0:f0 v0:f1 v0:f2 v1:f0 v1:f1 v2:f0 v2:f1 ...]\n\toffsetsAllVersions = partition.getOffsets();\n\n\t\/\/ The number of fragments in each version\n\tversionPartitionSizes = partition.getVersionSizes();\n\n\tstring outputFilename = \".\/Output\/results.txt\";\n\n\tpartition.writeResults(versions, IDsToWords, outputFilename, printFragments, printAssociations);\n\n\tif (printAssociations)\n\t{\n\t\tcerr << \"*** Associations (symbol -> pair) ***\" << endl;\n\t\twriteAssociations(associations, cerr);\n\t}\n\n\tstringstream command;\n\tcommand << \"start \" << outputFilename.c_str();\n\tsystem(command.str().c_str());\n\n\t\/\/ repairAlg.cleanup();\n\n\treturn partition.getScore();\n}\n\n\ndouble RepairPartitioningPrototype::runRepairPartitioning(\n\tvector<vector<unsigned> > versions, \n\tunsigned*& offsetsAllVersions, \n\tunsigned*& versionPartitionSizes, \n\tvector<Association>& associations,\n\tunsigned minFragSize, \n\tfloat fragmentationCoefficient, \n\tunsigned method)\n{\n\tRepairAlgorithm repairAlg(versions);\n\n\trepairAlg.run();\n\n\tvector<VersionDataItem> versionData = repairAlg.getVersionData();\n\n\tassociations = repairAlg.getAssociations();\n\n\t\/\/ Use the result of repair to get a partitioning of the document\n\t\/\/ Hopefully this partitioning gives us fragments that occur many times\n\tRepairDocumentPartition partition = RepairDocumentPartition(versionData, associations, \n\t\t1, minFragSize, fragmentationCoefficient, method);\n\n\t\/\/ The offsets that define fragments, for all versions [v0:f0 v0:f1 v0:f2 v1:f0 v1:f1 v2:f0 v2:f1 ...]\n\toffsetsAllVersions = partition.getOffsets();\n\n\t\/\/ The number of fragments in each version\n\tversionPartitionSizes = partition.getVersionSizes();\n\n\tstring outputFilename = \".\/Output\/results.txt\";\n\n\tpartition.writeResults(versions, IDsToWords, outputFilename, false, false);\n\n\t\/\/ if (printAssociations)\n\t\/\/ {\n\t\/\/ \tcerr << \"*** Associations (symbol -> pair) ***\" << endl;\n\t\/\/ \twriteAssociations(associations, cerr);\n\t\/\/ }\n\n\t\/\/ stringstream command;\n\t\/\/ command << \"start \" << outputFilename.c_str();\n\t\/\/ system(command.str().c_str());\n\t\n\trepairAlg.cleanup();\n\n\treturn partition.getScore();\n}\n\n\n\nint RepairPartitioningPrototype::run(int argc, char* argv[])\n{\n\t\/\/createOutputDir();\n\n\t\/\/heap, repair\n\tstring test = \"repair\";\n\n\tif (test == \"heap\")\n\t{\n\t\tRandomHeapTest test = RandomHeapTest(1000);\n\t\texit(0);\n\t}\n\n\tif (test == \"repair\")\n\t{\n\t\tProfiler::getInstance().start(\"all\");\n\t\tstring inputFilepath = \".\/Input\/ints\/\";\n\n\t\t\/*\n\t\tInitial tests show that minFragSize should be proportional to document size\n\t\t*\/\n\t\tunsigned minFragSize = 10; \/\/in words\n\n\t\t\/*\n\t\tInitial tests show that repairStoppingPoint shouldn't be too small (repair goes too far for our purposes in this case)\n\t\tAnd it shouldn't be larger than the number of versions (this is trivial, we expect to get repetition \n\t\tat most numVersions times for inter-version repetitions)\n\t\t*\/\n\t\tunsigned repairStoppingPoint = 1; \/\/pairs that occur less than this amount of times will not be replaced\n\n\t\t\/* To what extent are we willing to fragment? See the partitioning algorithm for how this is used *\/\n\t\tfloat fragmentationCoefficient = 1.0;\n\n\t\t\/* A variable used in the primitive way to partition the tree: just go n levels down *\/\n\t\tunsigned numLevelsDown = 3;\n\n\t\t\/* The partitioning alg to use. See Partitioning.h for the enum *\/\n\t\tunsigned method = 0;\n\n\t\tif (argc == 2 && (string) argv[1] == \"help\")\n\t\t{\n\t\t\tcerr << \"Usage:\" << endl;\n\t\t\tcerr << \"\\t\" << argv[0] << \" <directory> <fragmentationCoefficient> <minFragSize> <method>\" << endl;\n\t\t\tcerr << \"\\t\" << argv[0] << \" <directory> <fragmentationCoefficient> <minFragSize>\" << endl;\n\t\t\tcerr << \"\\t\" << argv[0] << \" <directory> <fragmentationCoefficient>\" << endl;\n\t\t\tcerr << \"\\t\" << argv[0] << \" <directory>\" << endl;\n\t\t\tcerr << \"\\t\" << argv[0] << \"\" << endl << endl;\n\t\t\t\n\t\t\tcerr << \"Defaults: \" << endl;\n\t\t\tcerr << \"\\tdirectory: \" << inputFilepath << endl;\n\t\t\tcerr << \"\\tfragmentationCoefficient: \" << fragmentationCoefficient << endl;\n\t\t\tcerr << \"\\tminFragSize: \" << minFragSize << endl;\t\t\t\n\t\t\tcerr << \"\\tmethod: \" << method << endl;\n\t\t\texit(0);\n\t\t}\n\n\t\tif (argc > 1)\n\t\t\tinputFilepath = (string)argv[1];\n\n\t\tif (argc > 2)\n\t\t\tfragmentationCoefficient = atof(argv[2]);\n\n\t\tif (argc > 3)\n\t\t\tminFragSize = atoi(argv[3]);\n\t\t\n\t\tif (argc > 4)\n\t\t\tmethod = atoi(argv[4]);\n\n\t\t\/\/ if (argc > 3)\n\t\t\/\/ \trepairStoppingPoint = atoi(argv[3]);\n\t\t\n\t\tvector<string> inputFilenames = vector<string>();\n\t\tif (getFileNames(inputFilepath, inputFilenames))\n\t\t\treturn errno;\n\n\t\tchar* text;\n\t\t\n\t\tint fileSize;\n\t\t\n\t\tvector<vector<unsigned> > versions = vector<vector<unsigned> >(); \/\/each inner vector is the wordIDs for one version\n\t\t\n\t\tvector<unsigned> wordIDs;\n\t\t\n\t\tunordered_map<unsigned, string> IDsToWords = unordered_map<unsigned, string>();\n\n\t\tunordered_map<unsigned, unsigned> uniqueWordIDs = unordered_map<unsigned, unsigned>();\n\t\t\n\t\tfor (unsigned i = 0; i < inputFilenames.size(); i++)\n\t\t{\n\t\t\tstringstream filenameSS;\n\t\t\tfilenameSS << inputFilepath << inputFilenames[i];\n\t\t\tstring filename = filenameSS.str();\n\t\t\ttext = getText(filename, fileSize);\n\t\t\tif (!text)\n\t\t\t\tcontinue;\n\t\t\twordIDs = stringToWordIDs(text, IDsToWords, uniqueWordIDs);\n\n\t\t\tif (false)\n\t\t\t{\n\t\t\t\tcerr << \"Version \" << i << endl;\n\t\t\t\tfor (unsigned j = 0; j < wordIDs.size(); j++)\n\t\t\t\t{\n\t\t\t\t\tcerr << wordIDs[j] << \",\";\n\t\t\t\t}\n\t\t\t\tcerr << endl << endl;\n\t\t\t}\n\t\t\t\n\t\t\tversions.push_back(wordIDs);\n\t\t\tdelete text;\n\t\t\ttext = NULL;\n\t\t}\n\t\t\n\t\t\/\/ By this time, IDsToWords should contain the mappings of IDs to words in all versions\n\t\t\/\/ printIDtoWordMapping(IDsToWords);\n\t\t\/\/ system(\"pause\");\n\n\t\tvector<Association> associations;\n\n\t\tunsigned* offsetsAllVersions(NULL);\n\t\tunsigned* versionPartitionSizes(NULL);\n\n\t\tdouble score;\n\t\t\/* Both overloads are shown below for testing. Just change the bool to switch. *\/\n\t\tif (false)\n\t\t{\n\t\t\tscore = runRepairPartitioning(versions, IDsToWords, \n\t\t\t\toffsetsAllVersions, versionPartitionSizes, \n\t\t\t\tassociations, minFragSize, \n\t\t\t\tfragmentationCoefficient, \n\t\t\t\trepairStoppingPoint, numLevelsDown,\n\t\t\t\tmethod, true, false);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tscore = runRepairPartitioning(versions, offsetsAllVersions,\n\t\t\t\tversionPartitionSizes, \n\t\t\t\tassociations,\n\t\t\t\tminFragSize,\n\t\t\t\tfragmentationCoefficient, \n\t\t\t\tmethod);\n\t\t}\n\n\t\treturn score;\n\t}\n}<commit_msg>uncomment file with results output<commit_after>#include \"RepairPartitioningPrototype.h\"\nusing namespace std;\n\nvoid RepairPartitioningPrototype::printIDtoWordMapping(unordered_map<unsigned, string>& IDsToWords, ostream& os)\n{\n\tfor (unordered_map<unsigned, string>::iterator it = IDsToWords.begin(); it != IDsToWords.end(); it++)\n\t{\n\t\tos << it->first << \": \" << it->second << endl;\n\t}\n}\n\nvoid RepairPartitioningPrototype::writeAssociations(const vector<Association>& associations, ostream& os)\n{\n\tfor (size_t i = 0; i < associations.size(); i++)\n\t{\n\t\tos << associations[i];\n\t}\n}\n\ndouble RepairPartitioningPrototype::runRepairPartitioning(\n\tvector<vector<unsigned> > versions,\n\tunordered_map<unsigned, string>& IDsToWords, \n\tunsigned*& offsetsAllVersions, \n\tunsigned*& versionPartitionSizes, \n\tvector<Association>& associations,\n\tunsigned minFragSize, \n\tfloat fragmentationCoefficient, \n\tunsigned repairStoppingPoint, \n\tunsigned numLevelsDown, \n\tunsigned method,\n\tbool printFragments, \n\tbool printAssociations)\n{\n\tRepairAlgorithm repairAlg(versions);\n\n\trepairAlg.run();\n\n\tvector<VersionDataItem> versionData = repairAlg.getVersionData();\n\n\tassociations = repairAlg.getAssociations();\n\n\t\/\/ Use the result of repair to get a partitioning of the document\n\t\/\/ Hopefully this partitioning gives us fragments that occur many times\n\tRepairDocumentPartition partition = RepairDocumentPartition(versionData, associations, numLevelsDown, minFragSize, fragmentationCoefficient, method);\n\n\t\/\/ The offsets that define fragments, for all versions [v0:f0 v0:f1 v0:f2 v1:f0 v1:f1 v2:f0 v2:f1 ...]\n\toffsetsAllVersions = partition.getOffsets();\n\n\t\/\/ The number of fragments in each version\n\tversionPartitionSizes = partition.getVersionSizes();\n\n\tstring outputFilename = \".\/Output\/results.txt\";\n\n\tpartition.writeResults(versions, IDsToWords, outputFilename, printFragments, printAssociations);\n\n\tif (printAssociations)\n\t{\n\t\tcerr << \"*** Associations (symbol -> pair) ***\" << endl;\n\t\twriteAssociations(associations, cerr);\n\t}\n\n\tstringstream command;\n\tcommand << \"start \" << outputFilename.c_str();\n\tsystem(command.str().c_str());\n\n\t\/\/ repairAlg.cleanup();\n\n\treturn partition.getScore();\n}\n\n\ndouble RepairPartitioningPrototype::runRepairPartitioning(\n\tvector<vector<unsigned> > versions, \n\tunsigned*& offsetsAllVersions, \n\tunsigned*& versionPartitionSizes, \n\tvector<Association>& associations,\n\tunsigned minFragSize, \n\tfloat fragmentationCoefficient, \n\tunsigned method)\n{\n\tRepairAlgorithm repairAlg(versions);\n\n\trepairAlg.run();\n\n\tvector<VersionDataItem> versionData = repairAlg.getVersionData();\n\n\tassociations = repairAlg.getAssociations();\n\n\t\/\/ Use the result of repair to get a partitioning of the document\n\t\/\/ Hopefully this partitioning gives us fragments that occur many times\n\tRepairDocumentPartition partition = RepairDocumentPartition(versionData, associations, \n\t\t1, minFragSize, fragmentationCoefficient, method);\n\n\t\/\/ The offsets that define fragments, for all versions [v0:f0 v0:f1 v0:f2 v1:f0 v1:f1 v2:f0 v2:f1 ...]\n\toffsetsAllVersions = partition.getOffsets();\n\n\t\/\/ The number of fragments in each version\n\tversionPartitionSizes = partition.getVersionSizes();\n\n\tstring outputFilename = \".\/Output\/results.txt\";\n\n\tunordered_map<unsigned, string> IDsToWords = unordered_map<unsigned, string>();\n\tpartition.writeResults(versions, IDsToWords, outputFilename, false, false);\n\n\t\/\/ if (printAssociations)\n\t\/\/ {\n\t\/\/ \tcerr << \"*** Associations (symbol -> pair) ***\" << endl;\n\t\/\/ \twriteAssociations(associations, cerr);\n\t\/\/ }\n\n\t\/\/ stringstream command;\n\t\/\/ command << \"start \" << outputFilename.c_str();\n\t\/\/ system(command.str().c_str());\n\t\n\trepairAlg.cleanup();\n\n\treturn partition.getScore();\n}\n\n\n\nint RepairPartitioningPrototype::run(int argc, char* argv[])\n{\n\t\/\/createOutputDir();\n\n\t\/\/heap, repair\n\tstring test = \"repair\";\n\n\tif (test == \"heap\")\n\t{\n\t\tRandomHeapTest test = RandomHeapTest(1000);\n\t\texit(0);\n\t}\n\n\tif (test == \"repair\")\n\t{\n\t\tProfiler::getInstance().start(\"all\");\n\t\tstring inputFilepath = \".\/Input\/ints\/\";\n\n\t\t\/*\n\t\tInitial tests show that minFragSize should be proportional to document size\n\t\t*\/\n\t\tunsigned minFragSize = 10; \/\/in words\n\n\t\t\/*\n\t\tInitial tests show that repairStoppingPoint shouldn't be too small (repair goes too far for our purposes in this case)\n\t\tAnd it shouldn't be larger than the number of versions (this is trivial, we expect to get repetition \n\t\tat most numVersions times for inter-version repetitions)\n\t\t*\/\n\t\tunsigned repairStoppingPoint = 1; \/\/pairs that occur less than this amount of times will not be replaced\n\n\t\t\/* To what extent are we willing to fragment? See the partitioning algorithm for how this is used *\/\n\t\tfloat fragmentationCoefficient = 1.0;\n\n\t\t\/* A variable used in the primitive way to partition the tree: just go n levels down *\/\n\t\tunsigned numLevelsDown = 3;\n\n\t\t\/* The partitioning alg to use. See Partitioning.h for the enum *\/\n\t\tunsigned method = 0;\n\n\t\tif (argc == 2 && (string) argv[1] == \"help\")\n\t\t{\n\t\t\tcerr << \"Usage:\" << endl;\n\t\t\tcerr << \"\\t\" << argv[0] << \" <directory> <fragmentationCoefficient> <minFragSize> <method>\" << endl;\n\t\t\tcerr << \"\\t\" << argv[0] << \" <directory> <fragmentationCoefficient> <minFragSize>\" << endl;\n\t\t\tcerr << \"\\t\" << argv[0] << \" <directory> <fragmentationCoefficient>\" << endl;\n\t\t\tcerr << \"\\t\" << argv[0] << \" <directory>\" << endl;\n\t\t\tcerr << \"\\t\" << argv[0] << \"\" << endl << endl;\n\t\t\t\n\t\t\tcerr << \"Defaults: \" << endl;\n\t\t\tcerr << \"\\tdirectory: \" << inputFilepath << endl;\n\t\t\tcerr << \"\\tfragmentationCoefficient: \" << fragmentationCoefficient << endl;\n\t\t\tcerr << \"\\tminFragSize: \" << minFragSize << endl;\t\t\t\n\t\t\tcerr << \"\\tmethod: \" << method << endl;\n\t\t\texit(0);\n\t\t}\n\n\t\tif (argc > 1)\n\t\t\tinputFilepath = (string)argv[1];\n\n\t\tif (argc > 2)\n\t\t\tfragmentationCoefficient = atof(argv[2]);\n\n\t\tif (argc > 3)\n\t\t\tminFragSize = atoi(argv[3]);\n\t\t\n\t\tif (argc > 4)\n\t\t\tmethod = atoi(argv[4]);\n\n\t\t\/\/ if (argc > 3)\n\t\t\/\/ \trepairStoppingPoint = atoi(argv[3]);\n\t\t\n\t\tvector<string> inputFilenames = vector<string>();\n\t\tif (getFileNames(inputFilepath, inputFilenames))\n\t\t\treturn errno;\n\n\t\tchar* text;\n\t\t\n\t\tint fileSize;\n\t\t\n\t\tvector<vector<unsigned> > versions = vector<vector<unsigned> >(); \/\/each inner vector is the wordIDs for one version\n\t\t\n\t\tvector<unsigned> wordIDs;\n\t\t\n\t\tunordered_map<unsigned, string> IDsToWords = unordered_map<unsigned, string>();\n\n\t\tunordered_map<unsigned, unsigned> uniqueWordIDs = unordered_map<unsigned, unsigned>();\n\t\t\n\t\tfor (unsigned i = 0; i < inputFilenames.size(); i++)\n\t\t{\n\t\t\tstringstream filenameSS;\n\t\t\tfilenameSS << inputFilepath << inputFilenames[i];\n\t\t\tstring filename = filenameSS.str();\n\t\t\ttext = getText(filename, fileSize);\n\t\t\tif (!text)\n\t\t\t\tcontinue;\n\t\t\twordIDs = stringToWordIDs(text, IDsToWords, uniqueWordIDs);\n\n\t\t\tif (false)\n\t\t\t{\n\t\t\t\tcerr << \"Version \" << i << endl;\n\t\t\t\tfor (unsigned j = 0; j < wordIDs.size(); j++)\n\t\t\t\t{\n\t\t\t\t\tcerr << wordIDs[j] << \",\";\n\t\t\t\t}\n\t\t\t\tcerr << endl << endl;\n\t\t\t}\n\t\t\t\n\t\t\tversions.push_back(wordIDs);\n\t\t\tdelete text;\n\t\t\ttext = NULL;\n\t\t}\n\t\t\n\t\t\/\/ By this time, IDsToWords should contain the mappings of IDs to words in all versions\n\t\t\/\/ printIDtoWordMapping(IDsToWords);\n\t\t\/\/ system(\"pause\");\n\n\t\tvector<Association> associations;\n\n\t\tunsigned* offsetsAllVersions(NULL);\n\t\tunsigned* versionPartitionSizes(NULL);\n\n\t\tdouble score;\n\t\t\/* Both overloads are shown below for testing. Just change the bool to switch. *\/\n\t\tif (false)\n\t\t{\n\t\t\tscore = runRepairPartitioning(versions, IDsToWords, \n\t\t\t\toffsetsAllVersions, versionPartitionSizes, \n\t\t\t\tassociations, minFragSize, \n\t\t\t\tfragmentationCoefficient, \n\t\t\t\trepairStoppingPoint, numLevelsDown,\n\t\t\t\tmethod, true, false);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tscore = runRepairPartitioning(versions, offsetsAllVersions,\n\t\t\t\tversionPartitionSizes, \n\t\t\t\tassociations,\n\t\t\t\tminFragSize,\n\t\t\t\tfragmentationCoefficient, \n\t\t\t\tmethod);\n\t\t}\n\n\t\treturn score;\n\t}\n}<|endoftext|>"} {"text":"<commit_before>\/*=========================================================================\n\n Program: Insight Segmentation & Registration Toolkit\n Module: itkSymmetricSecondRankTensorTest.cxx\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n Copyright (c) Insight Software Consortium. All rights reserved.\n See ITKCopyright.txt or http:\/\/www.itk.org\/HTML\/Copyright.htm for details.\n\n This software is distributed WITHOUT ANY WARRANTY; without even \n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR \n PURPOSE. See the above copyright notices for more information.\n\n=========================================================================*\/\n#if defined(_MSC_VER)\n#pragma warning ( disable : 4786 )\n#endif\n\n#include <iostream>\n\n#include \"itkSymmetricSecondRankTensor.h\"\n#include \"itkImage.h\"\n#include \"itkImageRegionIterator.h\"\n\nint itkSymmetricSecondRankTensorTest(int, char* [] )\n{\n int i, j;\n \n \/\/ Test it all\n \n float val[6] = {1.8, 0.2, 0.5, 3.4, 2.0, 1.2};\n \n typedef itk::SymmetricSecondRankTensor<float,3> Float3DTensorType;\n typedef itk::SymmetricSecondRankTensor<unsigned char,3> Uchar3DTensorType;\n\n Float3DTensorType pixel(val);\n\n unsigned char pixelInit0[6] = {255, 255, 255,128,34,17};\n unsigned char pixelInit1[6] = {255, 255, 244,19,23,29};\n\n Uchar3DTensorType pixelArray[2];\n pixelArray[0] = pixelInit0;\n pixelArray[1] = pixelInit1;\n \n std::cout << \"sizeof(pixel) = \" << sizeof (pixel) << std::endl;\n if (sizeof(pixel) != 6 * sizeof(Float3DTensorType::ComponentType))\n {\n std::cerr << \"ERROR: sizeof(pixel) == \" << sizeof(pixel) << \" but is should be \" << 6 * sizeof(Float3DTensorType::ComponentType) << std::endl;\n return 1;\n }\n std::cout << \"pixel.GetNumberOfComponents = \" << pixel.GetNumberOfComponents() << std::endl;\n std::cout << \"pixel.GetNthComponent()\" << std::endl;\n for (i = 0; i < pixel.GetNumberOfComponents(); i++)\n {\n std::cout << \"\\tpixel[\" << i << \"] = \" << pixel.GetNthComponent(i) << std::endl;\n }\n\n pixel(0,0) = 11.0; \n pixel(0,1) = 21.0; \n pixel(0,2) = 15.0; \n pixel(1,0) = 11.0; \n pixel(1,1) = 31.0; \n pixel(1,2) = 10.0; \n pixel(2,0) = 11.0; \/\/ these three last element will overwrite its symmetric counterparts\n pixel(2,1) = 41.0; \n pixel(2,2) = 14.0; \n\n std::cout << \"testing the pixel(i,j) APID\" << std::endl;\n for (i = 0; i < pixel.GetNumberOfComponents(); i++)\n {\n std::cout << \"\\tpixel[\" << i << \"] = \" << pixel.GetNthComponent(i) << std::endl;\n }\n \n std::cout << \"pixel[0] = 111; pixel[1] = 222; pixel[2] = 333;\" << std::endl;\n std::cout << \"pixel[3] = 444; pixel[4] = 555; pixel[5] = 666;\" << std::endl;\n \n pixel[0] = 111; pixel[1] = 222; pixel[2] = 333;\n pixel[3] = 444; pixel[4] = 555; pixel[5] = 666;\n\n for (i = 0; i < pixel.GetNumberOfComponents(); i++)\n {\n std::cout << \"\\tpixel[\" << i << \"] = \" << pixel.GetNthComponent(i) << std::endl;\n }\n \n std::cout << \"std::cout << pixel << std::endl;\" << std::endl;\n std::cout << \"\\t\" << pixel << std::endl;\n \n for (j = 0; j < 2; j++)\n {\n std::cout << \"pixelArray[\"<< j << \"].GetNumberOfComponents = \" << pixelArray[j].GetNumberOfComponents() << std::endl;\n std::cout << \"pixelArray[\" << j << \"].GetNthComponent()\" << std::endl;\n for (i = 0; i < pixelArray[j].GetNumberOfComponents(); i++)\n {\n std::cout << \"\\tpixelArray[\" << j << \"].GetNthComponent(\" << i << \") = \" << static_cast<int>(pixelArray[j].GetNthComponent(i)) << std::endl;\n }\n }\n\n std::cout << \"Testing arithmetic methods\" << std::endl;\n Float3DTensorType pa;\n Float3DTensorType pb;\n\n pa[0] = 1.25;\n pa[1] = 3.25;\n pa[2] = 5.25;\n pa[3] = 1.25;\n pa[4] = 3.25;\n pa[5] = 5.25;\n\n pb[0] = 1.55;\n pb[1] = 3.55;\n pb[2] = 5.55;\n pb[3] = 1.55;\n pb[4] = 3.55;\n pb[5] = 5.55;\n\n Float3DTensorType pc;\n \n pc = pa + pb;\n std::cout << \"addition = \" << pc << std::endl;\n\n pc = pa - pb;\n std::cout << \"subtraction = \" << pc << std::endl;\n\n pc += pb;\n std::cout << \"in-place addition = \" << pc << std::endl;\n\n pc -= pb;\n std::cout << \"in-place subtraction = \" << pc << std::endl;\n\n pc = pa * 3.2;\n std::cout << \"product by scalar = \" << pc << std::endl;\n\n\n\n\n \/** Create an Image of tensors *\/\n typedef Float3DTensorType PixelType;\n typedef itk::Image< PixelType, 3 > ImageType;\n \n ImageType::Pointer dti = ImageType::New();\n\n ImageType::SizeType size;\n ImageType::IndexType start;\n ImageType::RegionType region;\n\n size[0] = 128;\n size[1] = 128;\n size[2] = 128;\n\n start[0] = 0;\n start[1] = 0;\n start[2] = 0;\n\n region.SetIndex( start );\n region.SetSize( size );\n\n dti->SetRegions( region );\n dti->Allocate();\n \n ImageType::SpacingType spacing;\n spacing[0] = 0.5;\n spacing[1] = 0.5;\n spacing[2] = 1.5;\n\n ImageType::PointType origin;\n origin[0] = 25.5;\n origin[1] = 25.5;\n origin[2] = 27.5;\n\n dti->SetOrigin( origin );\n dti->SetSpacing( spacing );\n\n PixelType tensor;\n\n tensor[0] = 1.2;\n tensor[1] = 2.2;\n tensor[2] = 3.2;\n tensor[3] = 4.2;\n tensor[4] = 5.2;\n tensor[5] = 6.2;\n\n dti->FillBuffer( tensor );\n \n typedef itk::ImageRegionIterator< ImageType > IteratorType;\n\n IteratorType it( dti, region );\n it.GoToBegin();\n\n while( !it.IsAtEnd() )\n {\n it.Set( tensor );\n ++it;\n }\n\n \/\/ Test Eigen values computation\n {\n typedef itk::SymmetricSecondRankTensor<double,3> Double3DTensorType;\n\n Double3DTensorType tensor;\n \n Double3DTensorType::EigenValuesArrayType eigenValues;\n Double3DTensorType::EigenVectorsMatrixType eigenVectors;\n \n tensor.ComputeEigenAnalysis( eigenValues, eigenVectors );\n\n std::cout << \"EigenValues = \" << std::endl;\n std::cout << eigenValues << std::endl;\n\n std::cout << \"EigenVectors = \" << std::endl;\n std::cout << eigenVectors << std::endl;\n }\n\n return EXIT_SUCCESS;\n}\n\n<commit_msg>ENH: Added trivial test for eigen analysis: a diagonal tensor.<commit_after>\/*=========================================================================\n\n Program: Insight Segmentation & Registration Toolkit\n Module: itkSymmetricSecondRankTensorTest.cxx\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n Copyright (c) Insight Software Consortium. All rights reserved.\n See ITKCopyright.txt or http:\/\/www.itk.org\/HTML\/Copyright.htm for details.\n\n This software is distributed WITHOUT ANY WARRANTY; without even \n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR \n PURPOSE. See the above copyright notices for more information.\n\n=========================================================================*\/\n#if defined(_MSC_VER)\n#pragma warning ( disable : 4786 )\n#endif\n\n#include <iostream>\n\n#include \"itkSymmetricSecondRankTensor.h\"\n#include \"itkImage.h\"\n#include \"itkImageRegionIterator.h\"\n\nint itkSymmetricSecondRankTensorTest(int, char* [] )\n{\n int i, j;\n \n \/\/ Test it all\n \n float val[6] = {1.8, 0.2, 0.5, 3.4, 2.0, 1.2};\n \n typedef itk::SymmetricSecondRankTensor<float,3> Float3DTensorType;\n typedef itk::SymmetricSecondRankTensor<unsigned char,3> Uchar3DTensorType;\n\n Float3DTensorType pixel(val);\n\n unsigned char pixelInit0[6] = {255, 255, 255,128,34,17};\n unsigned char pixelInit1[6] = {255, 255, 244,19,23,29};\n\n Uchar3DTensorType pixelArray[2];\n pixelArray[0] = pixelInit0;\n pixelArray[1] = pixelInit1;\n \n std::cout << \"sizeof(pixel) = \" << sizeof (pixel) << std::endl;\n if (sizeof(pixel) != 6 * sizeof(Float3DTensorType::ComponentType))\n {\n std::cerr << \"ERROR: sizeof(pixel) == \" << sizeof(pixel) << \" but is should be \" << 6 * sizeof(Float3DTensorType::ComponentType) << std::endl;\n return 1;\n }\n std::cout << \"pixel.GetNumberOfComponents = \" << pixel.GetNumberOfComponents() << std::endl;\n std::cout << \"pixel.GetNthComponent()\" << std::endl;\n for (i = 0; i < pixel.GetNumberOfComponents(); i++)\n {\n std::cout << \"\\tpixel[\" << i << \"] = \" << pixel.GetNthComponent(i) << std::endl;\n }\n\n pixel(0,0) = 11.0; \n pixel(0,1) = 21.0; \n pixel(0,2) = 15.0; \n pixel(1,0) = 11.0; \n pixel(1,1) = 31.0; \n pixel(1,2) = 10.0; \n pixel(2,0) = 11.0; \/\/ these three last element will overwrite its symmetric counterparts\n pixel(2,1) = 41.0; \n pixel(2,2) = 14.0; \n\n std::cout << \"testing the pixel(i,j) APID\" << std::endl;\n for (i = 0; i < pixel.GetNumberOfComponents(); i++)\n {\n std::cout << \"\\tpixel[\" << i << \"] = \" << pixel.GetNthComponent(i) << std::endl;\n }\n \n std::cout << \"pixel[0] = 111; pixel[1] = 222; pixel[2] = 333;\" << std::endl;\n std::cout << \"pixel[3] = 444; pixel[4] = 555; pixel[5] = 666;\" << std::endl;\n \n pixel[0] = 111; pixel[1] = 222; pixel[2] = 333;\n pixel[3] = 444; pixel[4] = 555; pixel[5] = 666;\n\n for (i = 0; i < pixel.GetNumberOfComponents(); i++)\n {\n std::cout << \"\\tpixel[\" << i << \"] = \" << pixel.GetNthComponent(i) << std::endl;\n }\n \n std::cout << \"std::cout << pixel << std::endl;\" << std::endl;\n std::cout << \"\\t\" << pixel << std::endl;\n \n for (j = 0; j < 2; j++)\n {\n std::cout << \"pixelArray[\"<< j << \"].GetNumberOfComponents = \" << pixelArray[j].GetNumberOfComponents() << std::endl;\n std::cout << \"pixelArray[\" << j << \"].GetNthComponent()\" << std::endl;\n for (i = 0; i < pixelArray[j].GetNumberOfComponents(); i++)\n {\n std::cout << \"\\tpixelArray[\" << j << \"].GetNthComponent(\" << i << \") = \" << static_cast<int>(pixelArray[j].GetNthComponent(i)) << std::endl;\n }\n }\n\n std::cout << \"Testing arithmetic methods\" << std::endl;\n Float3DTensorType pa;\n Float3DTensorType pb;\n\n pa[0] = 1.25;\n pa[1] = 3.25;\n pa[2] = 5.25;\n pa[3] = 1.25;\n pa[4] = 3.25;\n pa[5] = 5.25;\n\n pb[0] = 1.55;\n pb[1] = 3.55;\n pb[2] = 5.55;\n pb[3] = 1.55;\n pb[4] = 3.55;\n pb[5] = 5.55;\n\n Float3DTensorType pc;\n \n pc = pa + pb;\n std::cout << \"addition = \" << pc << std::endl;\n\n pc = pa - pb;\n std::cout << \"subtraction = \" << pc << std::endl;\n\n pc += pb;\n std::cout << \"in-place addition = \" << pc << std::endl;\n\n pc -= pb;\n std::cout << \"in-place subtraction = \" << pc << std::endl;\n\n pc = pa * 3.2;\n std::cout << \"product by scalar = \" << pc << std::endl;\n\n\n\n\n \/** Create an Image of tensors *\/\n typedef Float3DTensorType PixelType;\n typedef itk::Image< PixelType, 3 > ImageType;\n \n ImageType::Pointer dti = ImageType::New();\n\n ImageType::SizeType size;\n ImageType::IndexType start;\n ImageType::RegionType region;\n\n size[0] = 128;\n size[1] = 128;\n size[2] = 128;\n\n start[0] = 0;\n start[1] = 0;\n start[2] = 0;\n\n region.SetIndex( start );\n region.SetSize( size );\n\n dti->SetRegions( region );\n dti->Allocate();\n \n ImageType::SpacingType spacing;\n spacing[0] = 0.5;\n spacing[1] = 0.5;\n spacing[2] = 1.5;\n\n ImageType::PointType origin;\n origin[0] = 25.5;\n origin[1] = 25.5;\n origin[2] = 27.5;\n\n dti->SetOrigin( origin );\n dti->SetSpacing( spacing );\n\n PixelType tensor;\n\n tensor[0] = 1.2;\n tensor[1] = 2.2;\n tensor[2] = 3.2;\n tensor[3] = 4.2;\n tensor[4] = 5.2;\n tensor[5] = 6.2;\n\n dti->FillBuffer( tensor );\n \n typedef itk::ImageRegionIterator< ImageType > IteratorType;\n\n IteratorType it( dti, region );\n it.GoToBegin();\n\n while( !it.IsAtEnd() )\n {\n it.Set( tensor );\n ++it;\n }\n\n \/\/ Test Eigen values computation\n {\n typedef itk::SymmetricSecondRankTensor<double,3> Double3DTensorType;\n\n Double3DTensorType tensor;\n\n double v[3];\n v[0] = 19.0;\n v[1] = 23.0;\n v[2] = 29.0;\n\n tensor(0,0) = v[0]; \n tensor(0,1) = 0.0; \n tensor(0,2) = 0.0; \n tensor(1,0) = 0.0; \/\/ overrides (0,1)\n tensor(1,1) = v[1]; \n tensor(1,2) = 0.0; \n tensor(2,0) = 0.0; \/\/ overrides (0,2)\n tensor(2,1) = 0.0; \/\/ overrides (1,2)\n tensor(2,2) = v[2]; \n \n std::cout << \"SymmetricTensor = \" << std::endl;\n std::cout << tensor << std::endl;\n\n Double3DTensorType::EigenValuesArrayType eigenValues;\n Double3DTensorType::EigenVectorsMatrixType eigenVectors;\n \n tensor.ComputeEigenAnalysis( eigenValues, eigenVectors );\n\n std::cout << \"EigenValues = \" << std::endl;\n std::cout << eigenValues << std::endl;\n\n std::cout << \"EigenVectors = \" << std::endl;\n std::cout << eigenVectors << std::endl;\n\n const double tolerance = 1e-8;\n\n for(unsigned int i=0; i<3; i++)\n {\n if( fabs( v[i] - eigenValues[i] ) > tolerance )\n {\n std::cerr << \"Eigenvalue computation failed\" << std::endl;\n return EXIT_FAILURE;\n }\n }\n }\n\n return EXIT_SUCCESS;\n}\n\n<|endoftext|>"} {"text":"<commit_before>#include \"blackmagicsdk_video_source.h\"\n\nnamespace gg\n{\n\nVideoSourceBlackmagicSDK::VideoSourceBlackmagicSDK()\n : IVideoSource()\n , _video_buffer(nullptr)\n , _video_buffer_length(0)\n \/\/ This constructor should never be called,\n \/\/ therefore setting I420 arbitrarily for the\n \/\/ buffer video frame here.\n , _buffer_video_frame(VideoFrame(I420))\n , _running(false)\n{\n \/\/ nop\n}\n\n\nVideoSourceBlackmagicSDK::VideoSourceBlackmagicSDK(size_t deck_link_index,\n ColourSpace colour)\n : IVideoSource(colour)\n , _video_buffer(nullptr)\n , _video_buffer_length(0)\n , _buffer_video_frame(VideoFrame(colour, false)) \/\/ TODO manage data?\n , _deck_link(nullptr)\n , _deck_link_input(nullptr)\n , _running(false)\n{\n switch(_colour)\n {\n case BGRA:\n break;\n case I420:\n default:\n release_deck_link();\n throw VideoSourceError(\n \"BlackmagicSDK video source supports only BGRA\"\n );\n }\n\n \/\/ Get an iterator through the available DeckLink ports\n IDeckLinkIterator * deck_link_iterator = CreateDeckLinkIteratorInstance();\n if (deck_link_iterator == nullptr)\n {\n release_deck_link();\n throw VideoSourceError(\"DeckLink drivers do not appear to be installed\");\n }\n\n HRESULT res;\n\n \/\/ Get the desired DeckLink index (port)\n int idx = deck_link_index;\n while ((res = deck_link_iterator->Next(&_deck_link)) == S_OK)\n {\n if (idx == 0)\n break;\n --idx;\n\n _deck_link->Release();\n }\n if (deck_link_iterator != nullptr)\n deck_link_iterator->Release();\n \/\/ No glory: release everything and throw exception\n if (res != S_OK or _deck_link == nullptr)\n {\n release_deck_link();\n throw VideoSourceError(\n std::string(\"Could not get DeckLink device \").append(std::to_string(deck_link_index))\n );\n }\n\n \/\/ Get the input interface of connected DeckLink port\n res = _deck_link->QueryInterface(IID_IDeckLinkInput, reinterpret_cast<void **>(&_deck_link_input));\n \/\/ No glory: release everything and throw exception\n if (res != S_OK)\n {\n release_deck_link();\n throw VideoSourceError(\"Could not connect to any Blackmagic DeckLink device\");\n }\n\n \/\/ Set this object (IDeckLinkInputCallback instance) as callback\n res = _deck_link_input->SetCallback(this);\n \/\/ No glory: release everything and throw exception\n if (res != S_OK)\n {\n release_deck_link();\n throw VideoSourceError(\"Could not set the callback of Blackmagic DeckLink device\");\n }\n\n \/\/ Enable video input\n res = _deck_link_input->EnableVideoInput(\n bmdModeHD1080p6000, bmdFormat8BitBGRA,\n bmdVideoInputFlagDefault | bmdVideoInputEnableFormatDetection\n );\n \/\/ No glory: release everything and throw exception\n if (res != S_OK)\n {\n release_deck_link();\n throw VideoSourceError(\"Could not enable video input of Blackmagic DeckLink device\");\n }\n\n \/\/ Disable audio input\n res = _deck_link_input->DisableAudioInput();\n \/\/ No glory: release everything and throw exception\n if (res != S_OK)\n {\n release_deck_link();\n throw VideoSourceError(\"Could not disable audio input of Blackmagic DeckLink device\");\n }\n}\n\n\nVideoSourceBlackmagicSDK::~VideoSourceBlackmagicSDK()\n{\n \/\/ Release DeckLink members\n release_deck_link();\n\n \/\/ Release allocated memory\n free(_video_buffer);\n \/\/ TODO\n}\n\n\nbool VideoSourceBlackmagicSDK::get_frame_dimensions(int & width, int & height)\n{\n \/\/ TODO\n}\n\n\nbool VideoSourceBlackmagicSDK::get_frame(VideoFrame & frame)\n{\n \/\/ TODO\n return false;\n}\n\n\ndouble VideoSourceBlackmagicSDK::get_frame_rate()\n{\n \/\/ TODO\n return 0;\n}\n\n\nvoid VideoSourceBlackmagicSDK::set_sub_frame(int x, int y, int width, int height)\n{\n \/\/ TODO\n}\n\n\nvoid VideoSourceBlackmagicSDK::get_full_frame()\n{\n \/\/ TODO\n}\n\n\nHRESULT STDMETHODCALLTYPE VideoSourceBlackmagicSDK::QueryInterface(REFIID iid, LPVOID * ppv)\n{\n \/\/ TODO\n}\n\n\nULONG STDMETHODCALLTYPE VideoSourceBlackmagicSDK::AddRef(void)\n{\n \/\/ TODO\n}\n\n\nULONG STDMETHODCALLTYPE VideoSourceBlackmagicSDK::Release(void)\n{\n \/\/ TODO\n}\n\n\nHRESULT STDMETHODCALLTYPE VideoSourceBlackmagicSDK::VideoInputFormatChanged(\n BMDVideoInputFormatChangedEvents events,\n IDeckLinkDisplayMode * display_mode,\n BMDDetectedVideoInputFormatFlags format_flags\n)\n{\n \/\/ TODO\n}\n\n\nHRESULT STDMETHODCALLTYPE VideoSourceBlackmagicSDK::VideoInputFrameArrived(\n IDeckLinkVideoInputFrame * video_frame,\n IDeckLinkAudioInputPacket * audio_packet\n)\n{\n \/\/ TODO\n}\n\n\nvoid VideoSourceBlackmagicSDK::release_deck_link() noexcept\n{\n this->Release();\n\n if (_deck_link_input != nullptr)\n {\n _deck_link_input->Release();\n _deck_link_input = nullptr;\n }\n\n if (_deck_link != nullptr)\n _deck_link->Release();\n}\n\n}\n<commit_msg>Issue #5: BlackmagicSDK video source constructor now starts streaming at the end, destructor stops it<commit_after>#include \"blackmagicsdk_video_source.h\"\n\nnamespace gg\n{\n\nVideoSourceBlackmagicSDK::VideoSourceBlackmagicSDK()\n : IVideoSource()\n , _video_buffer(nullptr)\n , _video_buffer_length(0)\n \/\/ This constructor should never be called,\n \/\/ therefore setting I420 arbitrarily for the\n \/\/ buffer video frame here.\n , _buffer_video_frame(VideoFrame(I420))\n , _running(false)\n{\n \/\/ nop\n}\n\n\nVideoSourceBlackmagicSDK::VideoSourceBlackmagicSDK(size_t deck_link_index,\n ColourSpace colour)\n : IVideoSource(colour)\n , _video_buffer(nullptr)\n , _video_buffer_length(0)\n , _buffer_video_frame(VideoFrame(colour, false)) \/\/ TODO manage data?\n , _deck_link(nullptr)\n , _deck_link_input(nullptr)\n , _running(false)\n{\n switch(_colour)\n {\n case BGRA:\n break;\n case I420:\n default:\n release_deck_link();\n throw VideoSourceError(\n \"BlackmagicSDK video source supports only BGRA\"\n );\n }\n\n \/\/ Get an iterator through the available DeckLink ports\n IDeckLinkIterator * deck_link_iterator = CreateDeckLinkIteratorInstance();\n if (deck_link_iterator == nullptr)\n {\n release_deck_link();\n throw VideoSourceError(\"DeckLink drivers do not appear to be installed\");\n }\n\n HRESULT res;\n\n \/\/ Get the desired DeckLink index (port)\n int idx = deck_link_index;\n while ((res = deck_link_iterator->Next(&_deck_link)) == S_OK)\n {\n if (idx == 0)\n break;\n --idx;\n\n _deck_link->Release();\n }\n if (deck_link_iterator != nullptr)\n deck_link_iterator->Release();\n \/\/ No glory: release everything and throw exception\n if (res != S_OK or _deck_link == nullptr)\n {\n release_deck_link();\n throw VideoSourceError(\n std::string(\"Could not get DeckLink device \").append(std::to_string(deck_link_index))\n );\n }\n\n \/\/ Get the input interface of connected DeckLink port\n res = _deck_link->QueryInterface(IID_IDeckLinkInput, reinterpret_cast<void **>(&_deck_link_input));\n \/\/ No glory: release everything and throw exception\n if (res != S_OK)\n {\n release_deck_link();\n throw VideoSourceError(\"Could not connect to any Blackmagic DeckLink device\");\n }\n\n \/\/ Set this object (IDeckLinkInputCallback instance) as callback\n res = _deck_link_input->SetCallback(this);\n \/\/ No glory: release everything and throw exception\n if (res != S_OK)\n {\n release_deck_link();\n throw VideoSourceError(\"Could not set the callback of Blackmagic DeckLink device\");\n }\n\n \/\/ Enable video input\n res = _deck_link_input->EnableVideoInput(\n bmdModeHD1080p6000, bmdFormat8BitBGRA,\n bmdVideoInputFlagDefault | bmdVideoInputEnableFormatDetection\n );\n \/\/ No glory: release everything and throw exception\n if (res != S_OK)\n {\n release_deck_link();\n throw VideoSourceError(\"Could not enable video input of Blackmagic DeckLink device\");\n }\n\n \/\/ Disable audio input\n res = _deck_link_input->DisableAudioInput();\n \/\/ No glory: release everything and throw exception\n if (res != S_OK)\n {\n release_deck_link();\n throw VideoSourceError(\"Could not disable audio input of Blackmagic DeckLink device\");\n }\n\n \/\/ Start streaming\n _running = true;\n res = _deck_link_input->StartStreams();\n \/\/ No glory: release everything and throw exception\n if (res != S_OK)\n {\n _running = false;\n release_deck_link();\n throw VideoSourceError(\"Could not start streaming from the Blackmagic DeckLink device\");\n }\n}\n\n\nVideoSourceBlackmagicSDK::~VideoSourceBlackmagicSDK()\n{\n \/\/ Make sure streamer thread not trying to access buffer\n std::lock_guard<std::mutex> data_lock_guard(_data_lock);\n _running = false;\n\n \/\/ Stop streaming and disable enabled inputs\n _deck_link_input->StopStreams();\n _deck_link_input->DisableVideoInput();\n\n \/\/ Release DeckLink members\n release_deck_link();\n\n \/\/ Release allocated memory\n free(_video_buffer);\n}\n\n\nbool VideoSourceBlackmagicSDK::get_frame_dimensions(int & width, int & height)\n{\n \/\/ TODO\n}\n\n\nbool VideoSourceBlackmagicSDK::get_frame(VideoFrame & frame)\n{\n \/\/ TODO\n return false;\n}\n\n\ndouble VideoSourceBlackmagicSDK::get_frame_rate()\n{\n \/\/ TODO\n return 0;\n}\n\n\nvoid VideoSourceBlackmagicSDK::set_sub_frame(int x, int y, int width, int height)\n{\n \/\/ TODO\n}\n\n\nvoid VideoSourceBlackmagicSDK::get_full_frame()\n{\n \/\/ TODO\n}\n\n\nHRESULT STDMETHODCALLTYPE VideoSourceBlackmagicSDK::QueryInterface(REFIID iid, LPVOID * ppv)\n{\n \/\/ TODO\n}\n\n\nULONG STDMETHODCALLTYPE VideoSourceBlackmagicSDK::AddRef(void)\n{\n \/\/ TODO\n}\n\n\nULONG STDMETHODCALLTYPE VideoSourceBlackmagicSDK::Release(void)\n{\n \/\/ TODO\n}\n\n\nHRESULT STDMETHODCALLTYPE VideoSourceBlackmagicSDK::VideoInputFormatChanged(\n BMDVideoInputFormatChangedEvents events,\n IDeckLinkDisplayMode * display_mode,\n BMDDetectedVideoInputFormatFlags format_flags\n)\n{\n \/\/ TODO\n}\n\n\nHRESULT STDMETHODCALLTYPE VideoSourceBlackmagicSDK::VideoInputFrameArrived(\n IDeckLinkVideoInputFrame * video_frame,\n IDeckLinkAudioInputPacket * audio_packet\n)\n{\n \/\/ TODO\n}\n\n\nvoid VideoSourceBlackmagicSDK::release_deck_link() noexcept\n{\n this->Release();\n\n if (_deck_link_input != nullptr)\n {\n _deck_link_input->Release();\n _deck_link_input = nullptr;\n }\n\n if (_deck_link != nullptr)\n _deck_link->Release();\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/*=========================================================================\n\n Program: ORFEO Toolbox\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n\n Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.\n See OTBCopyright.txt for details.\n\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notices for more information.\n\n=========================================================================*\/\n\n\n\/\/ iostream is used for general output\n#include <iostream>\n#include <stdlib.h>\n\n#include \"otbMacro.h\"\n#include \"otbVectorImage.h\"\n#include \"otbImageFileReader.h\"\n#include \"otbImageFileWriter.h\"\n#include \"otbMapProjections.h\"\n#include \"itkComplexToModulusImageFilter.h\"\n#include \"otbUnaryImageFunctorWithVectorImageFilter.h\"\n#include \"otbOrthoRectificationFilter.h\"\n#include \"otbMapProjections.h\"\n\nint otbOrthoRectificationFilter(int argc, char* argv[])\n{\n if (argc != 12)\n {\n std::cout << argv[0] <<\n \" <input filename> <output filename> <origin easting> <origin northing> <x size> <y size> <x spacing> <y spacing> <UTM zone> <UTM hemisphere>\"\n << std::endl;\n\n return EXIT_FAILURE;\n }\n\n typedef otb::VectorImage<double, 2> VectorImageType;\n typedef otb::ImageFileReader<VectorImageType> ReaderType;\n typedef otb::ImageFileWriter<VectorImageType> WriterType;\n typedef otb::UtmInverseProjection UtmMapProjectionType;\n typedef otb::OrthoRectificationFilter<VectorImageType, VectorImageType, UtmMapProjectionType> OrthoRectifFilterType;\n\n \/\/Allocate pointer\n ReaderType::Pointer reader = ReaderType::New();\n WriterType::Pointer writer = WriterType::New();\n\n OrthoRectifFilterType::Pointer orthoRectifFilter = OrthoRectifFilterType::New();\n UtmMapProjectionType::Pointer utmMapProjection = UtmMapProjectionType::New();\n\n \/\/ Set parameters ...\n reader->SetFileName(argv[1]);\n writer->SetFileName(argv[2]);\n\n reader->GenerateOutputInformation();\n std::cout << reader->GetOutput() << std::endl;\n\n orthoRectifFilter->SetInput(reader->GetOutput());\n\n VectorImageType::IndexType start;\n start[0] = 0;\n start[1] = 0;\n orthoRectifFilter->SetOutputStartIndex(start);\n\n VectorImageType::SizeType size;\n size[0] = atoi(argv[5]); \/\/ X size\n size[1] = atoi(argv[6]); \/\/Y size\n orthoRectifFilter->SetOutputSize(size);\n\n VectorImageType::SpacingType spacing;\n spacing[0] = atof(argv[7]);\n spacing[1] = atof(argv[8]);\n orthoRectifFilter->SetOutputSpacing(spacing);\n\n VectorImageType::PointType origin;\n origin[0] = strtod(argv[3], NULL); \/\/Origin easting\n origin[1] = strtod(argv[4], NULL); \/\/Origin northing\n orthoRectifFilter->SetOutputOrigin(origin);\n\n utmMapProjection->SetZone(atoi(argv[9]));\n utmMapProjection->SetHemisphere(argv[10][0]);\n orthoRectifFilter->SetMapProjection(utmMapProjection);\n\n \/\/ Displacement Field spacing\n VectorImageType::SpacingType gridSpacing;\n gridSpacing[0] = atof(argv[11]);\n gridSpacing[1] = -atof(argv[11]);\n orthoRectifFilter->SetDisplacementFieldSpacing(gridSpacing);\n\n VectorImageType::PixelType no_data(reader->GetOutput()->GetNumberOfComponentsPerPixel());\n no_data.Fill(0);\n orthoRectifFilter->SetEdgePaddingValue(no_data);\n\n writer->SetInput(orthoRectifFilter->GetOutput());\n writer->SetNumberOfDivisionsTiledStreaming(4);\n writer->Update();\n\n return EXIT_SUCCESS;\n}\n\n\nint otbOrthoRectificationComplexFilter(int argc, char* argv[])\n{\n if (argc != 12)\n {\n std::cout << argv[0] <<\n \" <input filename> <output filename> <origin easting> <origin northing> <x size> <y size> <x spacing> <y spacing> <UTM zone> <UTM hemisphere>\"\n << std::endl;\n\n return EXIT_FAILURE;\n }\n\n typedef otb::VectorImage<std::complex<double>, 2> ComplexVectorImageType;\n typedef otb::VectorImage<double, 2> ModulusVectorImageType;\n typedef otb::UnaryImageFunctorWithVectorImageFilter<\n ComplexVectorImageType,\n ModulusVectorImageType,\n itk::Functor::ComplexToModulus<\n ComplexVectorImageType::InternalPixelType,\n ModulusVectorImageType::InternalPixelType\n >\n > ComplexToModulusFilterType;\n typedef otb::ImageFileReader<ComplexVectorImageType> ReaderType;\n typedef otb::ImageFileWriter<ModulusVectorImageType> WriterType;\n typedef otb::UtmInverseProjection UtmMapProjectionType;\n typedef otb::OrthoRectificationFilter<ModulusVectorImageType, ModulusVectorImageType, UtmMapProjectionType> OrthoRectifFilterType;\n\n \/\/Allocate pointer\n ReaderType::Pointer reader = ReaderType::New();\n reader->SetFileName(argv[1]);\n reader->GenerateOutputInformation();\n std::cout << reader->GetOutput() << std::endl;\n\n ComplexToModulusFilterType::Pointer complexToModulus = ComplexToModulusFilterType::New();\n complexToModulus->SetInput(reader->GetOutput());\n\n UtmMapProjectionType::Pointer utmMapProjection = UtmMapProjectionType::New();\n OrthoRectifFilterType::Pointer orthoRectifFilter = OrthoRectifFilterType::New();\n\n orthoRectifFilter->SetInput(complexToModulus->GetOutput());\n\n ComplexVectorImageType::IndexType start;\n start[0] = 0;\n start[1] = 0;\n orthoRectifFilter->SetOutputStartIndex(start);\n\n ComplexVectorImageType::SizeType size;\n size[0] = atoi(argv[5]); \/\/ X size\n size[1] = atoi(argv[6]); \/\/Y size\n orthoRectifFilter->SetOutputSize(size);\n\n ComplexVectorImageType::SpacingType spacing;\n spacing[0] = atof(argv[7]);\n spacing[1] = atof(argv[8]);\n orthoRectifFilter->SetOutputSpacing(spacing);\n\n ComplexVectorImageType::PointType origin;\n origin[0] = strtod(argv[3], NULL); \/\/Origin easting\n origin[1] = strtod(argv[4], NULL); \/\/Origin northing\n orthoRectifFilter->SetOutputOrigin(origin);\n\n utmMapProjection->SetZone(atoi(argv[9]));\n utmMapProjection->SetHemisphere(argv[10][0]);\n orthoRectifFilter->SetMapProjection(utmMapProjection);\n\n \/\/ Displacement Field spacing\n ComplexVectorImageType::SpacingType gridSpacing;\n gridSpacing[0] = atof(argv[11]);\n gridSpacing[1] = -atof(argv[11]);\n orthoRectifFilter->SetDisplacementFieldSpacing(gridSpacing);\n\n\n WriterType::Pointer writer = WriterType::New();\n writer->SetFileName(argv[2]);\n writer->SetInput(orthoRectifFilter->GetOutput());\n writer->SetNumberOfDivisionsTiledStreaming(4);\n writer->Update();\n\n return EXIT_SUCCESS;\n}\n<commit_msg>DOC: missing doc<commit_after>\/*=========================================================================\n\n Program: ORFEO Toolbox\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n\n Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.\n See OTBCopyright.txt for details.\n\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notices for more information.\n\n=========================================================================*\/\n\n\n\/\/ iostream is used for general output\n#include <iostream>\n#include <stdlib.h>\n\n#include \"otbMacro.h\"\n#include \"otbVectorImage.h\"\n#include \"otbImageFileReader.h\"\n#include \"otbImageFileWriter.h\"\n#include \"otbMapProjections.h\"\n#include \"itkComplexToModulusImageFilter.h\"\n#include \"otbUnaryImageFunctorWithVectorImageFilter.h\"\n#include \"otbOrthoRectificationFilter.h\"\n#include \"otbMapProjections.h\"\n\nint otbOrthoRectificationFilter(int argc, char* argv[])\n{\n if (argc != 12)\n {\n std::cout << argv[0] <<\n \" <input filename> <output filename> <origin easting> <origin northing>\"\n \" <x size> <y size> <x spacing> <y spacing> <UTM zone> <UTM hemisphere>\"\n \" <grid_spacing>\"\n << std::endl;\n\n return EXIT_FAILURE;\n }\n\n typedef otb::VectorImage<double, 2> VectorImageType;\n typedef otb::ImageFileReader<VectorImageType> ReaderType;\n typedef otb::ImageFileWriter<VectorImageType> WriterType;\n typedef otb::UtmInverseProjection UtmMapProjectionType;\n typedef otb::OrthoRectificationFilter<VectorImageType, VectorImageType, UtmMapProjectionType> OrthoRectifFilterType;\n\n \/\/Allocate pointer\n ReaderType::Pointer reader = ReaderType::New();\n WriterType::Pointer writer = WriterType::New();\n\n OrthoRectifFilterType::Pointer orthoRectifFilter = OrthoRectifFilterType::New();\n UtmMapProjectionType::Pointer utmMapProjection = UtmMapProjectionType::New();\n\n \/\/ Set parameters ...\n reader->SetFileName(argv[1]);\n writer->SetFileName(argv[2]);\n\n reader->GenerateOutputInformation();\n std::cout << reader->GetOutput() << std::endl;\n\n orthoRectifFilter->SetInput(reader->GetOutput());\n\n VectorImageType::IndexType start;\n start[0] = 0;\n start[1] = 0;\n orthoRectifFilter->SetOutputStartIndex(start);\n\n VectorImageType::SizeType size;\n size[0] = atoi(argv[5]); \/\/ X size\n size[1] = atoi(argv[6]); \/\/Y size\n orthoRectifFilter->SetOutputSize(size);\n\n VectorImageType::SpacingType spacing;\n spacing[0] = atof(argv[7]);\n spacing[1] = atof(argv[8]);\n orthoRectifFilter->SetOutputSpacing(spacing);\n\n VectorImageType::PointType origin;\n origin[0] = strtod(argv[3], NULL); \/\/Origin easting\n origin[1] = strtod(argv[4], NULL); \/\/Origin northing\n orthoRectifFilter->SetOutputOrigin(origin);\n\n utmMapProjection->SetZone(atoi(argv[9]));\n utmMapProjection->SetHemisphere(argv[10][0]);\n orthoRectifFilter->SetMapProjection(utmMapProjection);\n\n \/\/ Displacement Field spacing\n VectorImageType::SpacingType gridSpacing;\n gridSpacing[0] = atof(argv[11]);\n gridSpacing[1] = -atof(argv[11]);\n orthoRectifFilter->SetDisplacementFieldSpacing(gridSpacing);\n\n VectorImageType::PixelType no_data(reader->GetOutput()->GetNumberOfComponentsPerPixel());\n no_data.Fill(0);\n orthoRectifFilter->SetEdgePaddingValue(no_data);\n\n writer->SetInput(orthoRectifFilter->GetOutput());\n writer->SetNumberOfDivisionsTiledStreaming(4);\n writer->Update();\n\n return EXIT_SUCCESS;\n}\n\n\nint otbOrthoRectificationComplexFilter(int argc, char* argv[])\n{\n if (argc != 12)\n {\n std::cout << argv[0] <<\n \" <input filename> <output filename> <origin easting> <origin northing> <x size> <y size> <x spacing> <y spacing> <UTM zone> <UTM hemisphere>\"\n << std::endl;\n\n return EXIT_FAILURE;\n }\n\n typedef otb::VectorImage<std::complex<double>, 2> ComplexVectorImageType;\n typedef otb::VectorImage<double, 2> ModulusVectorImageType;\n typedef otb::UnaryImageFunctorWithVectorImageFilter<\n ComplexVectorImageType,\n ModulusVectorImageType,\n itk::Functor::ComplexToModulus<\n ComplexVectorImageType::InternalPixelType,\n ModulusVectorImageType::InternalPixelType\n >\n > ComplexToModulusFilterType;\n typedef otb::ImageFileReader<ComplexVectorImageType> ReaderType;\n typedef otb::ImageFileWriter<ModulusVectorImageType> WriterType;\n typedef otb::UtmInverseProjection UtmMapProjectionType;\n typedef otb::OrthoRectificationFilter<ModulusVectorImageType, ModulusVectorImageType, UtmMapProjectionType> OrthoRectifFilterType;\n\n \/\/Allocate pointer\n ReaderType::Pointer reader = ReaderType::New();\n reader->SetFileName(argv[1]);\n reader->GenerateOutputInformation();\n std::cout << reader->GetOutput() << std::endl;\n\n ComplexToModulusFilterType::Pointer complexToModulus = ComplexToModulusFilterType::New();\n complexToModulus->SetInput(reader->GetOutput());\n\n UtmMapProjectionType::Pointer utmMapProjection = UtmMapProjectionType::New();\n OrthoRectifFilterType::Pointer orthoRectifFilter = OrthoRectifFilterType::New();\n\n orthoRectifFilter->SetInput(complexToModulus->GetOutput());\n\n ComplexVectorImageType::IndexType start;\n start[0] = 0;\n start[1] = 0;\n orthoRectifFilter->SetOutputStartIndex(start);\n\n ComplexVectorImageType::SizeType size;\n size[0] = atoi(argv[5]); \/\/ X size\n size[1] = atoi(argv[6]); \/\/Y size\n orthoRectifFilter->SetOutputSize(size);\n\n ComplexVectorImageType::SpacingType spacing;\n spacing[0] = atof(argv[7]);\n spacing[1] = atof(argv[8]);\n orthoRectifFilter->SetOutputSpacing(spacing);\n\n ComplexVectorImageType::PointType origin;\n origin[0] = strtod(argv[3], NULL); \/\/Origin easting\n origin[1] = strtod(argv[4], NULL); \/\/Origin northing\n orthoRectifFilter->SetOutputOrigin(origin);\n\n utmMapProjection->SetZone(atoi(argv[9]));\n utmMapProjection->SetHemisphere(argv[10][0]);\n orthoRectifFilter->SetMapProjection(utmMapProjection);\n\n \/\/ Displacement Field spacing\n ComplexVectorImageType::SpacingType gridSpacing;\n gridSpacing[0] = atof(argv[11]);\n gridSpacing[1] = -atof(argv[11]);\n orthoRectifFilter->SetDisplacementFieldSpacing(gridSpacing);\n\n\n WriterType::Pointer writer = WriterType::New();\n writer->SetFileName(argv[2]);\n writer->SetInput(orthoRectifFilter->GetOutput());\n writer->SetNumberOfDivisionsTiledStreaming(4);\n writer->Update();\n\n return EXIT_SUCCESS;\n}\n<|endoftext|>"} {"text":"<commit_before>#include <sstream>\n#include \"Exceptions.h\"\n#include \"Extensions.h\"\n#include \"UNetReceiver.h\"\n\/\/ -----------------------------------------------------------------------------\nusing namespace std;\nusing namespace UniSetTypes;\nusing namespace UniSetExtensions;\n\/\/ -----------------------------------------------------------------------------\nbool UNetReceiver::PacketCompare::operator()(const UniSetUDP::UDPMessage& lhs,\n\t\t\t\t\t\t\t\t\t\t\tconst UniSetUDP::UDPMessage& rhs) const\n{\n\/\/\tif( lhs.msg.header.num == rhs.msg.header.num )\n\/\/\t\treturn (lhs.msg < rhs.msg);\n\n\treturn lhs.msg.header.num > rhs.msg.header.num;\n}\n\/\/ ------------------------------------------------------------------------------------------\nUNetReceiver::UNetReceiver( const std::string s_host, const ost::tpport_t port, SMInterface* smi ):\nshm(smi),\nrecvpause(10),\nupdatepause(100),\nudp(0),\nrecvTimeout(5000),\nlostTimeout(5000),\nlostPackets(0),\nactivated(false),\nr_thr(0),\nu_thr(0),\npnum(0),\nmaxDifferens(1000),\nwaitClean(false),\nrnum(0),\nmaxProcessingCount(100),\nicache(200),\ncache_init_ok(false)\n{\n\t{\n\t\tostringstream s;\n\t\ts << \"(\" << s_host << \":\" << port << \")\";\n\t\tmyname = s.str();\n\t}\n\n\ttry\n\t{\n\/\/\t\tost::IPV4Cidr ci(s_host.c_str());\n\/\/\t\taddr = ci.getBroadcast();\n\/\/\t\tcerr << \"****************** addr: \" << addr << endl;\n\t\taddr = s_host.c_str();\n\t\tudp = new ost::UDPDuplex(addr,port);\n\t}\n\tcatch( ost::SockException& e )\n\t{\n\t\tostringstream s;\n\t\ts << e.getString() << \": \" << e.getSystemErrorString();\n\t\tdlog[Debug::CRIT] << myname << \"(init): \" << s.str() << std::endl;\n\n\t\tthrow SystemError(s.str());\n\t}\n\n\tr_thr = new ThreadCreator<UNetReceiver>(this, &UNetReceiver::receive);\n\tu_thr = new ThreadCreator<UNetReceiver>(this, &UNetReceiver::update);\n\n\n\tptRecvTimeout.setTiming(recvTimeout);\n}\n\/\/ -----------------------------------------------------------------------------\nUNetReceiver::~UNetReceiver()\n{\n\tdelete r_thr;\n\tdelete u_thr;\n\tdelete udp;\n}\n\/\/ -----------------------------------------------------------------------------\nvoid UNetReceiver::setReceiveTimeout( timeout_t msec )\n{\n\trecvTimeout = msec;\n\tptRecvTimeout.setTiming(msec);\n}\n\/\/ -----------------------------------------------------------------------------\nvoid UNetReceiver::setLostTimeout( timeout_t msec )\n{\n\tlostTimeout = msec;\n\tptLostTimeout.setTiming(msec);\n}\n\/\/ -----------------------------------------------------------------------------\nvoid UNetReceiver::setReceivePause( timeout_t msec )\n{\n\trecvpause = msec;\n}\n\/\/ -----------------------------------------------------------------------------\nvoid UNetReceiver::setUpdatePause( timeout_t msec )\n{\n\tupdatepause = msec;\n}\n\/\/ -----------------------------------------------------------------------------\nvoid UNetReceiver::setMaxProcessingCount( int set )\n{\n\tmaxProcessingCount = set;\n}\n\/\/ -----------------------------------------------------------------------------\nvoid UNetReceiver::setMaxDifferens( unsigned long set )\n{\n\tmaxDifferens = set;\n}\n\/\/ -----------------------------------------------------------------------------\nvoid UNetReceiver::start()\n{\n\tif( !activated )\n\t{\n\t\tactivated = true;\n\t\tu_thr->start();\n\t\tr_thr->start();\n\t}\n}\n\/\/ -----------------------------------------------------------------------------\nvoid UNetReceiver::update()\n{\n\tcerr << \"******************* udpate start\" << endl;\n\twhile(activated)\n\t{\n\t\ttry\n\t\t{\n\t\t\treal_update();\n\t\t}\n\t\tcatch( UniSetTypes::Exception& ex)\n\t\t{\n\t\t\tdlog[Debug::CRIT] << myname << \"(update): \" << ex << std::endl;\n\t\t}\n\t\tcatch(...)\n\t\t{\n\t\t\tdlog[Debug::CRIT] << myname << \"(update): catch ...\" << std::endl;\n\t\t}\n\n\t\tmsleep(updatepause);\n\t}\n}\n\/\/ -----------------------------------------------------------------------------\nvoid UNetReceiver::real_update()\n{\n\tUniSetUDP::UDPMessage p;\n\t\/\/ обрабатываем пока, очередь либо не опустеет\n\t\/\/ либо обнаружится \"дырка\" в последовательности\n\t\/\/ но при этом обрабатываем не больше maxProcessingCount\n\t\/\/ за один раз..\n\tint k = maxProcessingCount;\n\twhile( k>0 )\n\t{\n\t\t{ \/\/ lock qpack\n\t\t\tuniset_mutex_lock l(packMutex);\n\t\t\tif( qpack.empty() )\n\t\t\t\treturn;\n\n\t\t\tp = qpack.top();\n\t\t\tunsigned long sub = labs(p.msg.header.num - pnum);\n\t\t\tif( pnum > 0 )\n\t\t\t{\n\t\t\t\t\/\/ если sub > maxDifferens\n\t\t\t\t\/\/ значит это просто \"разрыв\"\n\t\t\t\t\/\/ и нам ждать lostTimeout не надо\n\t\t\t\t\/\/ сразу начинаем обрабатывать новые пакеты\n\t\t\t\t\/\/ а если > 1 && < maxDifferens\n\t\t\t\t\/\/ значит это временная \"дырка\"\n\t\t\t\t\/\/ и надо подождать lostTimeout\n\t\t\t\t\/\/ чтобы констатировать потерю пакета..\n\t\t\t\tif( sub > 1 && sub < maxDifferens )\n\t\t\t\t{\n\t\t\t\t\tif( !ptLostTimeout.checkTime() )\n\t\t\t\t\t\treturn;\n\n\t\t\t\t\tlostPackets++;\n\t\t\t\t}\n\t\t\t\telse if( p.msg.header.num == pnum )\n\t\t\t\t{\n\t\t\t\t \/* а что делать если идут повторные пакеты ?!\n\t\t\t\t\t* для надёжности лучше обрабатывать..\n\t\t\t\t\t* для \"оптимизации\".. лучше игнорировать\n\t\t\t\t\t*\/\n\t\t\t\t\tqpack.pop(); \/\/ пока выбрали вариант \"оптимизации\"\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tptLostTimeout.reset();\n\n\t\t\t\/\/ удаляем из очереди, только если\n\t\t\t\/\/ всё в порядке с последовательностью..\n\t\t\tqpack.pop();\n\t\t\tpnum = p.msg.header.num;\n\t\t} \/\/ unlock qpack\n\n\t\tk--;\n\n\/\/\t\tcerr << myname << \"(update): \" << p.msg.header << endl;\n\n\t\tinitCache(p, !cache_init_ok);\n\n\t\tfor( size_t i=0; i<p.msg.header.dcount; i++ )\n\t\t{\n\t\t\ttry\n\t\t\t{\n\t\t\t\tUniSetUDP::UDPData& d = p.msg.dat[i];\n\t\t\t\tItemInfo& ii(icache[i]);\n\t\t\t\tif( ii.id != d.id )\n\t\t\t\t{\n\t\t\t\t\tdlog[Debug::WARN] << myname << \"(update): reinit cache for sid=\" << d.id << endl;\n\t\t\t\t\tii.id = d.id;\n\t\t\t\t\tshm->initAIterator(ii.ait);\n\t\t\t\t\tshm->initDIterator(ii.dit);\n\t\t\t\t}\n\n\/\/\t\t\t\tif( d.id == 121 )\n\/\/\t\t\t\t\tcerr << \"****** save id=\" << d.id << \" val=\" << d.val << endl;\n\t\t\t\tif( ii.iotype == UniversalIO::DigitalInput )\n\t\t\t\t\tshm->localSaveState(ii.dit,d.id,d.val,shm->ID());\n\t\t\t\telse if( ii.iotype == UniversalIO::AnalogInput )\n\t\t\t\t\tshm->localSaveValue(ii.ait,d.id,d.val,shm->ID());\n\t\t\t\telse if( ii.iotype == UniversalIO::AnalogOutput )\n\t\t\t\t\tshm->localSetValue(ii.ait,d.id,d.val,shm->ID());\n\t\t\t\telse if( ii.iotype == UniversalIO::DigitalOutput )\n\t\t\t\t\tshm->localSetState(ii.dit,d.id,d.val,shm->ID());\n\t\t\t\telse\n\t\t\t\t dlog[Debug::CRIT] << myname << \"(update): Unknown iotype for sid=\" << d.id << endl;\n\t\t\t}\n\t\t\tcatch( UniSetTypes::Exception& ex)\n\t\t\t{\n\t\t\t\tdlog[Debug::CRIT] << myname << \"(update): \" << ex << std::endl;\n\t\t\t}\n\t\t\tcatch(...)\n\t\t\t{\n\t\t\t\tdlog[Debug::CRIT] << myname << \"(update): catch ...\" << std::endl;\n\t\t\t}\n\t\t}\n\t}\n}\n\n\/\/ -----------------------------------------------------------------------------\nvoid UNetReceiver::stop()\n{\n\tactivated = false;\n\/\/\tmsleep(10);\n\/\/\tu_thr->stop();\n\/\/\tr_thr->stop();\n}\n\/\/ -----------------------------------------------------------------------------\nvoid UNetReceiver::receive()\n{\n\tcout << myname << \": ******************* receive start\" << endl;\n\tptRecvTimeout.setTiming(recvTimeout);\n\twhile( activated )\n\t{\n\t\ttry\n\t\t{\n\t\t\tif( recv() )\n\t\t\t ptRecvTimeout.reset();\n\t\t}\n\t\tcatch( ost::SockException& e )\n\t\t{\n\t\t\tcerr << myname << \"(receive): \" << e.getString() << endl;\n\t\t}\n\t\tcatch( UniSetTypes::Exception& ex)\n\t\t{\n\t\t\tcerr << myname << \"(receive): \" << ex << std::endl;\n\t\t}\n\t\tcatch(...)\n\t\t{\n\t\t\tcerr << myname << \"(receive): catch ...\" << std::endl;\n\t\t}\n\n\t\tmsleep(recvpause);\n\t}\n\n\tcout << myname << \": ************* receive FINISH **********\" << endl;\n}\n\/\/ -----------------------------------------------------------------------------\nbool UNetReceiver::recv()\n{\n\tif( !udp->isInputReady(recvTimeout) )\n\t\treturn false;\n\n\tsize_t ret = udp->UDPReceive::receive(&(pack.msg),sizeof(pack.msg));\n\tif( ret < sizeof(UniSetUDP::UDPHeader) )\n\t{\n\t\tdlog[Debug::CRIT] << myname << \"(receive): FAILED header ret=\" << ret << \" sizeof=\" << sizeof(UniSetUDP::UDPHeader) << endl;\n\t\treturn false;\n\t}\n\n\tsize_t sz = pack.msg.header.dcount * sizeof(UniSetUDP::UDPData) + sizeof(UniSetUDP::UDPHeader);\n\tif( ret < sz )\n\t{\n\t\tdlog[Debug::CRIT] << myname << \"(receive): FAILED data ret=\" << ret << \" sizeof=\" << sz\n\t\t\t << \" packnum=\" << pack.msg.header.num << endl;\n\t\treturn false;\n\t}\n\n\n\tif( rnum>0 && labs(pack.msg.header.num - rnum) > maxDifferens )\n\t{\n\t\t\/* А что делать если мы уже ждём и ещё не \"разгребли предыдущее\".. а тут уже повторный \"разрыв\"\n\t\t * Можно откинуть всё.. что сложили во временную очередь и заново \"копить\" (но тогда теряем информацию)\n\t\t * А можно породолжать складывать во временную, но тогда есть риск \"никогда\" не разгрести временную\n\t\t * очередь, при \"частых обрывах\". Потому-что update будет на каждом разрыве ждать ещё lostTimeout..\n\t\t *\/\n\t\t\/\/ Пока выбираю.. чистить qtmp. Это будет соотвествовать логике работы с картами у которых ограничен буфер приёма.\n\t\t\/\/ Обычно \"кольцевой\". Т.е. если не успели обработать и \"вынуть\" из буфера информацию.. он будет переписан новыми данными\n\t\tif( waitClean )\n\t\t{\n\t\t\tdlog[Debug::CRIT] << myname << \"(receive): reset qtmp..\" << endl;\n\t\t\twhile( !qtmp.empty() )\n\t\t\t\tqtmp.pop();\n\t\t}\n\n\t\twaitClean = true;\n\t}\n\n\trnum = pack.msg.header.num;\n\n#if 0\n\tcerr << myname << \"(receive): recv DATA OK. ret=\" << ret << \" sizeof=\" << sz\n\t\t << \" header: \" << pack.msg.header\n\t\t << \" waitClean=\" << waitClean\n\t\t << endl;\n\tfor( size_t i=0; i<pack.msg.header.dcount; i++ )\n\t{\n\t\tUniSetUDP::UDPData& d = pack.msg.dat[i];\n\t\tcerr << \"****** save id=\" << d.id << \" val=\" << d.val << endl;\n\t}\n#endif\n\n\t{\t\/\/ lock qpack\n\t\tuniset_mutex_lock l(packMutex,500);\n\t\tif( !waitClean )\n\t\t{\n\t\t\tqpack.push(pack);\n\t\t\treturn true;\n\t\t}\n\n\t\tif( !qpack.empty() )\n\t\t{\n\/\/\t\t\tcerr << myname << \"(receive): copy to qtmp...\"\n\/\/\t\t\t\t\t\t\t << \" header: \" << pack.msg.header\n\/\/\t\t\t\t\t\t\t << endl;\n\t\t\tqtmp.push(pack);\n\t\t}\n\t\telse\n\t\t{\n\/\/\t\t \tcerr << myname << \"(receive): copy from qtmp...\" << endl;\n\t\t\t\/\/ очередь освободилась..\n\t\t\t\/\/ то копируем в неё всё что набралось...\n\t\t\twhile( !qtmp.empty() )\n\t\t\t{\n\t\t\t\tqpack.push(qtmp.top());\n\t\t\t\tqtmp.pop();\n\t\t\t}\n\n\t\t\t\/\/ не забываем и текущий поместить в очередь..\n\t\t\tqpack.push(pack);\n\t\t\twaitClean = false;\n\t\t}\n\t}\t\/\/ unlock qpack\n\n\treturn true;\n}\n\/\/ -----------------------------------------------------------------------------\nvoid UNetReceiver::initIterators()\n{\n\tfor( ItemVec::iterator it=icache.begin(); it!=icache.end(); ++it )\n\t{\n\t\tshm->initAIterator(it->ait);\n\t\tshm->initDIterator(it->dit);\n\t}\n}\n\/\/ -----------------------------------------------------------------------------\nvoid UNetReceiver::initCache( UniSetUDP::UDPMessage& pack, bool force )\n{\n\t if( !force && pack.msg.header.dcount == icache.size() )\n\t\t return;\n\n\t dlog[Debug::INFO] << myname << \": init icache..\" << endl;\n\t cache_init_ok = true;\n\n\t icache.resize(pack.msg.header.dcount);\n\t for( size_t i=0; i<icache.size(); i++ )\n\t {\n\t\t ItemInfo& d(icache[i]);\n\t\t if( d.id != pack.msg.dat[i].id )\n\t\t {\n\t\t\t\td.id = pack.msg.dat[i].id;\n\t\t\t\td.iotype = conf->getIOType(d.id);\n\t\t\t\tshm->initAIterator(d.ait);\n\t\t\t\tshm->initDIterator(d.dit);\n\t\t }\n\t }\n}\n\/\/ -----------------------------------------------------------------------------\n<commit_msg>(UNet2): новая версия (реализована посылка)<commit_after>#include <sstream>\n#include \"Exceptions.h\"\n#include \"Extensions.h\"\n#include \"UNetReceiver.h\"\n\/\/ -----------------------------------------------------------------------------\nusing namespace std;\nusing namespace UniSetTypes;\nusing namespace UniSetExtensions;\n\/\/ -----------------------------------------------------------------------------\nbool UNetReceiver::PacketCompare::operator()(const UniSetUDP::UDPMessage& lhs,\n\t\t\t\t\t\t\t\t\t\t\tconst UniSetUDP::UDPMessage& rhs) const\n{\n\/\/\tif( lhs.msg.header.num == rhs.msg.header.num )\n\/\/\t\treturn (lhs.msg < rhs.msg);\n\n\treturn lhs.msg.header.num > rhs.msg.header.num;\n}\n\/\/ ------------------------------------------------------------------------------------------\nUNetReceiver::UNetReceiver( const std::string s_host, const ost::tpport_t port, SMInterface* smi ):\nshm(smi),\nrecvpause(10),\nupdatepause(100),\nudp(0),\nrecvTimeout(5000),\nlostTimeout(5000),\nlostPackets(0),\nactivated(false),\nr_thr(0),\nu_thr(0),\npnum(0),\nmaxDifferens(1000),\nwaitClean(false),\nrnum(0),\nmaxProcessingCount(100),\nicache(200),\ncache_init_ok(false)\n{\n\t{\n\t\tostringstream s;\n\t\ts << \"(\" << s_host << \":\" << port << \")\";\n\t\tmyname = s.str();\n\t}\n\n\ttry\n\t{\n\/\/\t\tost::IPV4Cidr ci(s_host.c_str());\n\/\/\t\taddr = ci.getBroadcast();\n\/\/\t\tcerr << \"****************** addr: \" << addr << endl;\n\t\taddr = s_host.c_str();\n\t\tudp = new ost::UDPDuplex(addr,port);\n\t}\n\tcatch( ost::SockException& e )\n\t{\n\t\tostringstream s;\n\t\ts << e.getString() << \": \" << e.getSystemErrorString();\n\t\tdlog[Debug::CRIT] << myname << \"(init): \" << s.str() << std::endl;\n\n\t\tthrow SystemError(s.str());\n\t}\n\n\tr_thr = new ThreadCreator<UNetReceiver>(this, &UNetReceiver::receive);\n\tu_thr = new ThreadCreator<UNetReceiver>(this, &UNetReceiver::update);\n\n\n\tptRecvTimeout.setTiming(recvTimeout);\n}\n\/\/ -----------------------------------------------------------------------------\nUNetReceiver::~UNetReceiver()\n{\n\tdelete r_thr;\n\tdelete u_thr;\n\tdelete udp;\n}\n\/\/ -----------------------------------------------------------------------------\nvoid UNetReceiver::setReceiveTimeout( timeout_t msec )\n{\n\trecvTimeout = msec;\n\tptRecvTimeout.setTiming(msec);\n}\n\/\/ -----------------------------------------------------------------------------\nvoid UNetReceiver::setLostTimeout( timeout_t msec )\n{\n\tlostTimeout = msec;\n\tptLostTimeout.setTiming(msec);\n}\n\/\/ -----------------------------------------------------------------------------\nvoid UNetReceiver::setReceivePause( timeout_t msec )\n{\n\trecvpause = msec;\n}\n\/\/ -----------------------------------------------------------------------------\nvoid UNetReceiver::setUpdatePause( timeout_t msec )\n{\n\tupdatepause = msec;\n}\n\/\/ -----------------------------------------------------------------------------\nvoid UNetReceiver::setMaxProcessingCount( int set )\n{\n\tmaxProcessingCount = set;\n}\n\/\/ -----------------------------------------------------------------------------\nvoid UNetReceiver::setMaxDifferens( unsigned long set )\n{\n\tmaxDifferens = set;\n}\n\/\/ -----------------------------------------------------------------------------\nvoid UNetReceiver::start()\n{\n\tif( !activated )\n\t{\n\t\tactivated = true;\n\t\tu_thr->start();\n\t\tr_thr->start();\n\t}\n}\n\/\/ -----------------------------------------------------------------------------\nvoid UNetReceiver::update()\n{\n\tcerr << \"******************* udpate start\" << endl;\n\twhile(activated)\n\t{\n\t\ttry\n\t\t{\n\t\t\treal_update();\n\t\t}\n\t\tcatch( UniSetTypes::Exception& ex)\n\t\t{\n\t\t\tdlog[Debug::CRIT] << myname << \"(update): \" << ex << std::endl;\n\t\t}\n\t\tcatch(...)\n\t\t{\n\t\t\tdlog[Debug::CRIT] << myname << \"(update): catch ...\" << std::endl;\n\t\t}\n\n\t\tmsleep(updatepause);\n\t}\n}\n\/\/ -----------------------------------------------------------------------------\nvoid UNetReceiver::real_update()\n{\n\tUniSetUDP::UDPMessage p;\n\t\/\/ обрабатываем пока, очередь либо не опустеет\n\t\/\/ либо обнаружится \"дырка\" в последовательности\n\t\/\/ но при этом обрабатываем не больше maxProcessingCount\n\t\/\/ за один раз..\n\tint k = maxProcessingCount;\n\twhile( k>0 )\n\t{\n\t\t{ \/\/ lock qpack\n\t\t\tuniset_mutex_lock l(packMutex);\n\t\t\tif( qpack.empty() )\n\t\t\t\treturn;\n\n\t\t\tp = qpack.top();\n\t\t\tunsigned long sub = labs(p.msg.header.num - pnum);\n\t\t\tif( pnum > 0 )\n\t\t\t{\n\t\t\t\t\/\/ если sub > maxDifferens\n\t\t\t\t\/\/ значит это просто \"разрыв\"\n\t\t\t\t\/\/ и нам ждать lostTimeout не надо\n\t\t\t\t\/\/ сразу начинаем обрабатывать новые пакеты\n\t\t\t\t\/\/ а если > 1 && < maxDifferens\n\t\t\t\t\/\/ значит это временная \"дырка\"\n\t\t\t\t\/\/ и надо подождать lostTimeout\n\t\t\t\t\/\/ чтобы констатировать потерю пакета..\n\t\t\t\tif( sub > 1 && sub < maxDifferens )\n\t\t\t\t{\n\t\t\t\t\tif( !ptLostTimeout.checkTime() )\n\t\t\t\t\t\treturn;\n\n\t\t\t\t\tlostPackets++;\n\t\t\t\t}\n\t\t\t\telse if( p.msg.header.num == pnum )\n\t\t\t\t{\n\t\t\t\t \/* а что делать если идут повторные пакеты ?!\n\t\t\t\t\t* для надёжности лучше обрабатывать..\n\t\t\t\t\t* для \"оптимизации\".. лучше игнорировать\n\t\t\t\t\t*\/\n\t\t\t\t\tqpack.pop(); \/\/ пока выбрали вариант \"оптимизации\"\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tptLostTimeout.reset();\n\n\t\t\t\/\/ удаляем из очереди, только если\n\t\t\t\/\/ всё в порядке с последовательностью..\n\t\t\tqpack.pop();\n\t\t\tpnum = p.msg.header.num;\n\t\t} \/\/ unlock qpack\n\n\t\tk--;\n\n\/\/\t\tcerr << myname << \"(update): \" << p.msg.header << endl;\n\n\t\tinitCache(p, !cache_init_ok);\n\n\t\tfor( size_t i=0; i<p.msg.header.dcount; i++ )\n\t\t{\n\t\t\ttry\n\t\t\t{\n\t\t\t\tUniSetUDP::UDPData& d = p.msg.dat[i];\n\t\t\t\tItemInfo& ii(icache[i]);\n\t\t\t\tif( ii.id != d.id )\n\t\t\t\t{\n\t\t\t\t\tdlog[Debug::WARN] << myname << \"(update): reinit cache for sid=\" << d.id << endl;\n\t\t\t\t\tii.id = d.id;\n\t\t\t\t\tshm->initAIterator(ii.ait);\n\t\t\t\t\tshm->initDIterator(ii.dit);\n\t\t\t\t}\n\n\t\t\t\tif( ii.iotype == UniversalIO::DigitalInput )\n\t\t\t\t\tshm->localSaveState(ii.dit,d.id,d.val,shm->ID());\n\t\t\t\telse if( ii.iotype == UniversalIO::AnalogInput )\n\t\t\t\t\tshm->localSaveValue(ii.ait,d.id,d.val,shm->ID());\n\t\t\t\telse if( ii.iotype == UniversalIO::AnalogOutput )\n\t\t\t\t\tshm->localSetValue(ii.ait,d.id,d.val,shm->ID());\n\t\t\t\telse if( ii.iotype == UniversalIO::DigitalOutput )\n\t\t\t\t\tshm->localSetState(ii.dit,d.id,d.val,shm->ID());\n\t\t\t\telse\n\t\t\t\t dlog[Debug::CRIT] << myname << \"(update): Unknown iotype for sid=\" << d.id << endl;\n\t\t\t}\n\t\t\tcatch( UniSetTypes::Exception& ex)\n\t\t\t{\n\t\t\t\tdlog[Debug::CRIT] << myname << \"(update): \" << ex << std::endl;\n\t\t\t}\n\t\t\tcatch(...)\n\t\t\t{\n\t\t\t\tdlog[Debug::CRIT] << myname << \"(update): catch ...\" << std::endl;\n\t\t\t}\n\t\t}\n\t}\n}\n\n\/\/ -----------------------------------------------------------------------------\nvoid UNetReceiver::stop()\n{\n\tactivated = false;\n\/\/\tmsleep(10);\n\/\/\tu_thr->stop();\n\/\/\tr_thr->stop();\n}\n\/\/ -----------------------------------------------------------------------------\nvoid UNetReceiver::receive()\n{\n\tdlog[Debug::INFO] << myname << \": ******************* receive start\" << endl;\n\tptRecvTimeout.setTiming(recvTimeout);\n\twhile( activated )\n\t{\n\t\ttry\n\t\t{\n\t\t\tif( recv() )\n\t\t\t ptRecvTimeout.reset();\n\t\t}\n\t\tcatch( ost::SockException& e )\n\t\t{\n\t\t\tdlog[Debug::WARN] << myname << \"(receive): \" << e.getString() << endl;\n\t\t}\n\t\tcatch( UniSetTypes::Exception& ex)\n\t\t{\n\t\t\tdlog[Debug::WARN] << myname << \"(receive): \" << ex << std::endl;\n\t\t}\n\t\tcatch(...)\n\t\t{\n\t\t\tdlog[Debug::WARN] << myname << \"(receive): catch ...\" << std::endl;\n\t\t}\n\n\t\tmsleep(recvpause);\n\t}\n\n\tdlog[Debug::INFO] << myname << \": ************* receive FINISH **********\" << endl;\n}\n\/\/ -----------------------------------------------------------------------------\nbool UNetReceiver::recv()\n{\n\tif( !udp->isInputReady(recvTimeout) )\n\t\treturn false;\n\n\tsize_t ret = udp->UDPReceive::receive(&(pack.msg),sizeof(pack.msg));\n\tif( ret < sizeof(UniSetUDP::UDPHeader) )\n\t{\n\t\tdlog[Debug::CRIT] << myname << \"(receive): FAILED header ret=\" << ret << \" sizeof=\" << sizeof(UniSetUDP::UDPHeader) << endl;\n\t\treturn false;\n\t}\n\n\tsize_t sz = pack.msg.header.dcount * sizeof(UniSetUDP::UDPData) + sizeof(UniSetUDP::UDPHeader);\n\tif( ret < sz )\n\t{\n\t\tdlog[Debug::CRIT] << myname << \"(receive): FAILED data ret=\" << ret << \" sizeof=\" << sz\n\t\t\t << \" packnum=\" << pack.msg.header.num << endl;\n\t\treturn false;\n\t}\n\n\n\tif( rnum>0 && labs(pack.msg.header.num - rnum) > maxDifferens )\n\t{\n\t\t\/* А что делать если мы уже ждём и ещё не \"разгребли предыдущее\".. а тут уже повторный \"разрыв\"\n\t\t * Можно откинуть всё.. что сложили во временную очередь и заново \"копить\" (но тогда теряем информацию)\n\t\t * А можно породолжать складывать во временную, но тогда есть риск \"никогда\" не разгрести временную\n\t\t * очередь, при \"частых обрывах\". Потому-что update будет на каждом разрыве ждать ещё lostTimeout..\n\t\t *\/\n\t\t\/\/ Пока выбираю.. чистить qtmp. Это будет соотвествовать логике работы с картами у которых ограничен буфер приёма.\n\t\t\/\/ Обычно \"кольцевой\". Т.е. если не успели обработать и \"вынуть\" из буфера информацию.. он будет переписан новыми данными\n\t\tif( waitClean )\n\t\t{\n\t\t\tdlog[Debug::CRIT] << myname << \"(receive): reset qtmp..\" << endl;\n\t\t\twhile( !qtmp.empty() )\n\t\t\t\tqtmp.pop();\n\t\t}\n\n\t\twaitClean = true;\n\t}\n\n\trnum = pack.msg.header.num;\n\n#if 0\n\tcerr << myname << \"(receive): recv DATA OK. ret=\" << ret << \" sizeof=\" << sz\n\t\t << \" header: \" << pack.msg.header\n\t\t << \" waitClean=\" << waitClean\n\t\t << endl;\n\tfor( size_t i=0; i<pack.msg.header.dcount; i++ )\n\t{\n\t\tUniSetUDP::UDPData& d = pack.msg.dat[i];\n\t\tcerr << \"****** save id=\" << d.id << \" val=\" << d.val << endl;\n\t}\n#endif\n\n\t{\t\/\/ lock qpack\n\t\tuniset_mutex_lock l(packMutex,500);\n\t\tif( !waitClean )\n\t\t{\n\t\t\tqpack.push(pack);\n\t\t\treturn true;\n\t\t}\n\n\t\tif( !qpack.empty() )\n\t\t{\n\/\/\t\t\tcerr << myname << \"(receive): copy to qtmp...\"\n\/\/\t\t\t\t\t\t\t << \" header: \" << pack.msg.header\n\/\/\t\t\t\t\t\t\t << endl;\n\t\t\tqtmp.push(pack);\n\t\t}\n\t\telse\n\t\t{\n\/\/\t\t \tcerr << myname << \"(receive): copy from qtmp...\" << endl;\n\t\t\t\/\/ очередь освободилась..\n\t\t\t\/\/ то копируем в неё всё что набралось...\n\t\t\twhile( !qtmp.empty() )\n\t\t\t{\n\t\t\t\tqpack.push(qtmp.top());\n\t\t\t\tqtmp.pop();\n\t\t\t}\n\n\t\t\t\/\/ не забываем и текущий поместить в очередь..\n\t\t\tqpack.push(pack);\n\t\t\twaitClean = false;\n\t\t}\n\t}\t\/\/ unlock qpack\n\n\treturn true;\n}\n\/\/ -----------------------------------------------------------------------------\nvoid UNetReceiver::initIterators()\n{\n\tfor( ItemVec::iterator it=icache.begin(); it!=icache.end(); ++it )\n\t{\n\t\tshm->initAIterator(it->ait);\n\t\tshm->initDIterator(it->dit);\n\t}\n}\n\/\/ -----------------------------------------------------------------------------\nvoid UNetReceiver::initCache( UniSetUDP::UDPMessage& pack, bool force )\n{\n\t if( !force && pack.msg.header.dcount == icache.size() )\n\t\t return;\n\n\t dlog[Debug::INFO] << myname << \": init icache..\" << endl;\n\t cache_init_ok = true;\n\n\t icache.resize(pack.msg.header.dcount);\n\t for( size_t i=0; i<icache.size(); i++ )\n\t {\n\t\t ItemInfo& d(icache[i]);\n\t\t if( d.id != pack.msg.dat[i].id )\n\t\t {\n\t\t\t\td.id = pack.msg.dat[i].id;\n\t\t\t\td.iotype = conf->getIOType(d.id);\n\t\t\t\tshm->initAIterator(d.ait);\n\t\t\t\tshm->initDIterator(d.dit);\n\t\t }\n\t }\n}\n\/\/ -----------------------------------------------------------------------------\n<|endoftext|>"} {"text":"<commit_before>#include \"builtin\/io.hpp\"\n#include \"builtin\/bytearray.hpp\"\n#include \"builtin\/class.hpp\"\n#include \"builtin\/fixnum.hpp\"\n#include \"builtin\/string.hpp\"\n\n#include \"vm.hpp\"\n#include \"objectmemory.hpp\"\n\nnamespace rubinius {\n void IO::init(STATE) {\n GO(io).set(state->new_class(\"IO\", G(object), IO::fields));\n GO(iobuffer).set(state->new_class(\"Buffer\", G(object), IOBuffer::fields, G(io)));\n }\n\n IOBuffer* IOBuffer::create(STATE, size_t bytes) {\n IOBuffer* buf = (IOBuffer*)state->new_object(G(iobuffer));\n SET(buf, storage, ByteArray::create(state, bytes));\n SET(buf, total, Fixnum::from(bytes));\n SET(buf, used, Fixnum::from(0));\n\n return buf;\n }\n\n IO* IO::create(STATE, int fd) {\n IO* io = (IO*)state->new_object(G(io));\n SET(io, descriptor, Integer::from(state, fd));\n return io;\n }\n\n void IO::initialize(STATE, int fd, char* mode) {\n SET(this, descriptor, Integer::from(state, fd));\n SET(this, mode, String::create(state, mode));\n }\n\n native_int IO::to_fd() {\n return descriptor->to_native();\n }\n\n OBJECT IO::write(STATE, String* buf) {\n ssize_t cnt = ::write(this->to_fd(), buf->data->bytes, buf->size());\n\n \/\/ TODO: RAISE_FROM_ERRNO\n if(cnt == -1) {\n throw std::runtime_error(\"IO::write primitive failed. (TODO RAISE_FROM_ERRNO)\");\n }\n\n return Integer::from(state, cnt);\n }\n\n void IOBuffer::read_bytes(size_t bytes) {\n used = Fixnum::from(used->to_native() + bytes);\n }\n\n char* IOBuffer::byte_address() {\n return (char*)storage->bytes;\n }\n\n size_t IOBuffer::left() {\n return total->to_native() - used->to_native();\n }\n\n char* IOBuffer::at_unused() {\n char* start = (char*)storage->bytes;\n start += used->to_native();\n return start;\n }\n};\n<commit_msg>Hook up IO's object type<commit_after>#include \"builtin\/io.hpp\"\n#include \"builtin\/bytearray.hpp\"\n#include \"builtin\/class.hpp\"\n#include \"builtin\/fixnum.hpp\"\n#include \"builtin\/string.hpp\"\n\n#include \"vm.hpp\"\n#include \"objectmemory.hpp\"\n\nnamespace rubinius {\n void IO::init(STATE) {\n GO(io).set(state->new_class(\"IO\", G(object), IO::fields));\n G(io)->set_object_type(IOType);\n\n GO(iobuffer).set(state->new_class(\"Buffer\", G(object), IOBuffer::fields, G(io)));\n G(iobuffer)->set_object_type(IOBufferType);\n }\n\n IOBuffer* IOBuffer::create(STATE, size_t bytes) {\n IOBuffer* buf = (IOBuffer*)state->new_object(G(iobuffer));\n SET(buf, storage, ByteArray::create(state, bytes));\n SET(buf, total, Fixnum::from(bytes));\n SET(buf, used, Fixnum::from(0));\n\n return buf;\n }\n\n IO* IO::create(STATE, int fd) {\n IO* io = (IO*)state->new_object(G(io));\n SET(io, descriptor, Integer::from(state, fd));\n return io;\n }\n\n void IO::initialize(STATE, int fd, char* mode) {\n SET(this, descriptor, Integer::from(state, fd));\n SET(this, mode, String::create(state, mode));\n }\n\n native_int IO::to_fd() {\n return descriptor->to_native();\n }\n\n OBJECT IO::write(STATE, String* buf) {\n ssize_t cnt = ::write(this->to_fd(), buf->data->bytes, buf->size());\n\n \/\/ TODO: RAISE_FROM_ERRNO\n if(cnt == -1) {\n throw std::runtime_error(\"IO::write primitive failed. (TODO RAISE_FROM_ERRNO)\");\n }\n\n return Integer::from(state, cnt);\n }\n\n void IOBuffer::read_bytes(size_t bytes) {\n used = Fixnum::from(used->to_native() + bytes);\n }\n\n char* IOBuffer::byte_address() {\n return (char*)storage->bytes;\n }\n\n size_t IOBuffer::left() {\n return total->to_native() - used->to_native();\n }\n\n char* IOBuffer::at_unused() {\n char* start = (char*)storage->bytes;\n start += used->to_native();\n return start;\n }\n};\n<|endoftext|>"} {"text":"<commit_before>namespace factor\n{\n\n\/* Some functions for converting floating point numbers to binary\nrepresentations and vice versa *\/\n\nunion double_bits_pun {\n\tdouble x;\n\tu64 y;\n};\n\ninline static u64 double_bits(double x)\n{\n\tdouble_bits_pun b;\n\tb.x = x;\n\treturn b.y;\n}\n\ninline static double bits_double(u64 y)\n{\n\tdouble_bits_pun b;\n\tb.y = y;\n\treturn b.x;\n}\n\nunion float_bits_pun {\n\tfloat x;\n\tu32 y;\n};\n\ninline static u32 float_bits(float x)\n{\n\tfloat_bits_pun b;\n\tb.x = x;\n\treturn b.y;\n}\n\ninline static float bits_float(u32 y)\n{\n\tfloat_bits_pun b;\n\tb.y = y;\n\treturn b.x;\n}\n\n}\n<commit_msg>VM: Refactor float_bits.hpp to Factor style<commit_after>namespace factor {\n\n\/* Some functions for converting floating point numbers to binary\nrepresentations and vice versa *\/\n\nunion double_bits_pun {\n double x;\n u64 y;\n};\n\ninline static u64 double_bits(double x) {\n double_bits_pun b;\n b.x = x;\n return b.y;\n}\n\ninline static double bits_double(u64 y) {\n double_bits_pun b;\n b.y = y;\n return b.x;\n}\n\nunion float_bits_pun {\n float x;\n u32 y;\n};\n\ninline static u32 float_bits(float x) {\n float_bits_pun b;\n b.x = x;\n return b.y;\n}\n\ninline static float bits_float(u32 y) {\n float_bits_pun b;\n b.y = y;\n return b.x;\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"main.h\"\n#include \"CNetwork.h\"\n#include \"CServer.h\"\n#include \"CUtils.h\"\n\n#include <istream>\n#include <boost\/date_time\/posix_time\/posix_time.hpp>\n\n#include \"format.h\"\n\n\nvoid CNetwork::NetAlive(const boost::system::error_code &error_code, bool from_write)\n{\n\tif (from_write == false)\n\t{\n\t\tif (m_Socket.is_open())\n\t\t{\n\t\t\tstatic string empty_data(\"\\n\");\n\t\t\tm_Socket.async_send(asio::buffer(empty_data), boost::bind(&CNetwork::NetAlive, this, boost::asio::placeholders::error, true));\n\t\t}\n\t\tm_AliveTimer.expires_from_now(boost::posix_time::seconds(60));\n\t\tm_AliveTimer.async_wait(boost::bind(&CNetwork::NetAlive, this, boost::asio::placeholders::error, false));\n\t}\n}\n\n\nvoid CNetwork::Connect(string ip, unsigned short port, unsigned short query_port)\n{\n\tm_SocketDest = tcp::endpoint(asio::ip::address::from_string(ip), query_port);\n\tm_ServerPort = port;\n\tAsyncConnect();\n\tm_IoThread = new thread(boost::bind(&asio::io_service::run, boost::ref(m_IoService)));\n\n\tExecute(fmt::format(\"use port={}\", m_ServerPort));\n}\n\nvoid CNetwork::Disconnect()\n{\n\tif (m_Socket.is_open() == false)\n\t\treturn; \n\n\tm_Socket.close();\n\tm_IoService.stop();\n\t\n\tif (m_IoThread != nullptr)\n\t{\n\t\tif (m_IoThread->get_id() != boost::this_thread::get_id())\n\t\t\tm_IoThread->join();\n\t\tdelete m_IoThread;\n\t\tm_IoThread = nullptr;\n\t}\n}\n\nvoid CNetwork::AsyncRead()\n{\n\tasio::async_read_until(m_Socket, m_ReadStreamBuf, '\\r', boost::bind(&CNetwork::OnRead, this, _1));\n}\n\nvoid CNetwork::AsyncWrite(string &data)\n{\n\tm_CmdWriteBuffer = data;\n\tif (data.at(data.length()-1) != '\\n')\n\t\tm_CmdWriteBuffer.push_back('\\n');\n\n\tm_Socket.async_send(asio::buffer(m_CmdWriteBuffer), boost::bind(&CNetwork::OnWrite, this, _1));\n}\n\nvoid CNetwork::AsyncConnect()\n{\n\tif (m_Socket.is_open())\n\t\tm_Socket.close();\n\n\tm_Socket.async_connect(m_SocketDest, boost::bind(&CNetwork::OnConnect, this, _1));\n}\n\nvoid CNetwork::OnConnect(const boost::system::error_code &error_code)\n{\n\tif (error_code.value() == 0)\n\t{\n\t\tAsyncRead();\n\t}\n\telse\n\t{\n\t\tlogprintf(\">> plugin.TSConnector: Error while connecting to server: \\\"%s\\\"\", error_code.message().c_str());\n\t\tDisconnect();\n\t}\n}\n\n\n\/*\n\t- result data is sent as a string which ends with \"\\n\\r\"\n\t- the Teamspeak3 server can send multiple strings\n\t- the end of a result set is always an error result string\n*\/\nvoid CNetwork::OnRead(const boost::system::error_code &error_code)\n{\n\tif (error_code.value() == 0)\n\t{\n\t\tstatic vector<string> captured_data;\n\t\tstd::istream tmp_stream(&m_ReadStreamBuf);\n\t\tstring read_data;\n\t\tstd::getline(tmp_stream, read_data, '\\r');\n\n#ifdef _DEBUG\n\t\tif (read_data.length() < 512)\n\t\t\tlogprintf(\">>>> %s\", read_data.c_str());\n\t\telse\n\t\t{\n\t\t\tstring shortened_data(read_data);\n\t\t\tshortened_data.resize(256);\n\t\t\tlogprintf(\">>>> %s\", shortened_data.c_str());\n\t\t}\n#endif\n\n\t\t\/\/regex: parse error\n\t\t\/\/if this is an error message, it means that no other result data will come\n\t\tstatic const boost::regex error_rx(\"error id=([0-9]+) msg=([^ \\n]+)\");\n\t\tboost::smatch error_rx_result;\n\t\tif (boost::regex_search(read_data, error_rx_result, error_rx))\n\t\t{\n\t\t\tif (error_rx_result[1].str() == \"0\")\n\t\t\t{\n\t\t\t\tfor (auto i = captured_data.begin(); i != captured_data.end(); ++i)\n\t\t\t\t{\n\t\t\t\t\tstring &data = *i;\n\t\t\t\t\tif (data.find('|') != string::npos) \/\/multiple data rows with '|' as delimiter\n\t\t\t\t\t{\n\t\t\t\t\t\tvector<string> result_set;\n\t\t\t\t\t\tsize_t delim_pos = 0;\n\t\t\t\t\t\tdo\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tsize_t old_delim_pos = delim_pos;\n\t\t\t\t\t\t\tdelim_pos = data.find('|', delim_pos);\n\t\t\t\t\t\t\tstring row = data.substr(old_delim_pos, delim_pos - old_delim_pos);\n\t\t\t\t\t\t\tresult_set.push_back(row);\n\t\t\t\t\t\t} while (delim_pos != string::npos && ++delim_pos);\n\n\t\t\t\t\t\ti = captured_data.erase(i);\n\t\t\t\t\t\tfor (auto j = result_set.begin(), jend = result_set.end(); j != jend; ++j)\n\t\t\t\t\t\t\ti = captured_data.insert(i, *j);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t\/\/call callback and send next command\n\t\t\t\tm_CmdQueueMutex.lock();\n\t\t\t\tif (m_CmdQueue.empty() == false)\n\t\t\t\t{\n\t\t\t\t\tReadCallback_t &callback = m_CmdQueue.front().get<1>();\n\t\t\t\t\tm_CmdQueueMutex.unlock();\n\t\t\t\t\tif (callback.empty() == false)\n\t\t\t\t\t\tcallback(captured_data); \/\/calls the callback\n\t\t\t\t\tm_CmdQueueMutex.lock();\n\t\t\t\t\tm_CmdQueue.pop();\n\n\t\t\t\t\tif (m_CmdQueue.empty() == false)\n\t\t\t\t\t\tAsyncWrite(m_CmdQueue.front().get<0>());\n\t\t\t\t}\n\t\t\t\tm_CmdQueueMutex.unlock();\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tstring error_str(error_rx_result[2].str());\n\t\t\t\tCUtils::Get()->UnEscapeString(error_str);\n\n\t\t\t\tlogprintf(\">> plugin.TSConnector: Error while executing \\\"%s\\\": %s (#%s)\", \n\t\t\t\t\tm_CmdQueue.front().get<0>().c_str(), error_str.c_str(), error_rx_result[1].str().c_str());\n\t\t\t\tm_CmdQueue.pop();\n\t\t\t}\n\n\t\t\tcaptured_data.clear();\n\t\t}\n\t\telse if (read_data.find(\"notify\") == 0)\n\t\t{\n\t\t\t\/\/check if notify is duplicate\n\t\t\tstatic string last_notify_data;\n\t\t\tstatic const vector<string> duplicate_notifies{ \n\t\t\t\t\"notifyclientmoved\", \n\t\t\t\t\"notifycliententerview\", \n\t\t\t\t\"notifyclientleftview\" \n\t\t\t};\n\t\t\tbool is_duplicate = false;\n\t\t\t\n\t\t\tfor (auto &s : duplicate_notifies)\n\t\t\t{\n\t\t\t\tif (read_data.find(s) == 0)\n\t\t\t\t{\n\t\t\t\t\tif (last_notify_data == read_data)\n\t\t\t\t\t\tis_duplicate = true;\n\t\t\t\t\t\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\tif (is_duplicate == false)\n\t\t\t{\n\t\t\t\t\/\/notify event\n\t\t\t\tboost::smatch event_result;\n\t\t\t\tfor (auto &event : m_EventList)\n\t\t\t\t{\n\t\t\t\t\tif (boost::regex_search(read_data, event_result, event.get<0>()))\n\t\t\t\t\t{\n\t\t\t\t\t\tevent.get<1>()(event_result);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tlast_notify_data = read_data;\n\t\t}\n\t\telse\n\t\t{\n\t\t\t\/\/stack the result data if it is not an error or notification message\n\t\t\tcaptured_data.push_back(read_data);\n\t\t}\n\n\t\tAsyncRead();\n\t}\n\telse if (error_code == asio::error::eof)\n\t{\n\t\tAsyncConnect();\n\t}\n\telse\n\t\tlogprintf(\">> plugin.TSConnector: Error while reading: %s (#%d)\", error_code.message().c_str(), error_code.value());\n}\n\nvoid CNetwork::OnWrite(const boost::system::error_code &error_code)\n{\n#ifdef _DEBUG\n\tlogprintf(\"<<<< %s\", m_CmdWriteBuffer.c_str());\n#endif\n\tm_CmdWriteBuffer.clear();\n\tif (error_code.value() != 0)\n\t\tlogprintf(\">> plugin.TSConnector: Error while writing: %s (#%d)\", error_code.message().c_str(), error_code.value());\n}\n\nvoid CNetwork::Execute(string cmd, ReadCallback_t callback)\n{\n\tboost::lock_guard<boost::mutex> queue_lock_guard(m_CmdQueueMutex);\n\tm_CmdQueue.push(boost::make_tuple(boost::move(cmd), boost::move(callback)));\n\tif (m_CmdQueue.size() == 1)\n\t\tAsyncWrite(m_CmdQueue.front().get<0>());\n}\n\n<commit_msg>code improvements<commit_after>#include \"main.h\"\n#include \"CNetwork.h\"\n#include \"CServer.h\"\n#include \"CUtils.h\"\n\n#include <istream>\n#include <boost\/date_time\/posix_time\/posix_time.hpp>\n\n#include \"format.h\"\n\n\nvoid CNetwork::NetAlive(const boost::system::error_code &error_code, bool from_write)\n{\n\tif (from_write == true)\n\t\treturn;\n\t\n\n\tif (m_Socket.is_open())\n\t{\n\t\tstatic string empty_data(\"\\n\");\n\t\tm_Socket.async_send(asio::buffer(empty_data), boost::bind(&CNetwork::NetAlive, this, boost::asio::placeholders::error, true));\n\t}\n\tm_AliveTimer.expires_from_now(boost::posix_time::seconds(60));\n\tm_AliveTimer.async_wait(boost::bind(&CNetwork::NetAlive, this, boost::asio::placeholders::error, false));\n}\n\n\nvoid CNetwork::Connect(string ip, unsigned short port, unsigned short query_port)\n{\n\tm_SocketDest = tcp::endpoint(asio::ip::address::from_string(ip), query_port);\n\tm_ServerPort = port;\n\tAsyncConnect();\n\tm_IoThread = new thread(boost::bind(&asio::io_service::run, boost::ref(m_IoService)));\n\n\tExecute(fmt::format(\"use port={}\", m_ServerPort));\n}\n\nvoid CNetwork::Disconnect()\n{\n\tif (m_Socket.is_open() == false)\n\t\treturn; \n\n\tm_Socket.close();\n\tm_IoService.stop();\n\t\n\tif (m_IoThread != nullptr)\n\t{\n\t\tif (m_IoThread->get_id() != boost::this_thread::get_id())\n\t\t\tm_IoThread->join();\n\t\tdelete m_IoThread;\n\t\tm_IoThread = nullptr;\n\t}\n}\n\nvoid CNetwork::AsyncRead()\n{\n\tasio::async_read_until(m_Socket, m_ReadStreamBuf, '\\r', boost::bind(&CNetwork::OnRead, this, _1));\n}\n\nvoid CNetwork::AsyncWrite(string &data)\n{\n\tm_CmdWriteBuffer = data;\n\tif (data.at(data.length()-1) != '\\n')\n\t\tm_CmdWriteBuffer.push_back('\\n');\n\n\tm_Socket.async_send(asio::buffer(m_CmdWriteBuffer), boost::bind(&CNetwork::OnWrite, this, _1));\n}\n\nvoid CNetwork::AsyncConnect()\n{\n\tif (m_Socket.is_open())\n\t\tm_Socket.close();\n\n\tm_Socket.async_connect(m_SocketDest, boost::bind(&CNetwork::OnConnect, this, _1));\n}\n\nvoid CNetwork::OnConnect(const boost::system::error_code &error_code)\n{\n\tif (error_code.value() == 0)\n\t{\n\t\tAsyncRead();\n\t}\n\telse\n\t{\n\t\tlogprintf(\">> plugin.TSConnector: Error while connecting to server: \\\"%s\\\"\", error_code.message().c_str());\n\t\tDisconnect();\n\t}\n}\n\n\n\/*\n\t- result data is sent as a string which ends with \"\\n\\r\"\n\t- the Teamspeak3 server can send multiple strings\n\t- the end of a result set is always an error result string\n*\/\nvoid CNetwork::OnRead(const boost::system::error_code &error_code)\n{\n\tif (error_code.value() == 0)\n\t{\n\t\tstatic vector<string> captured_data;\n\t\tstd::istream tmp_stream(&m_ReadStreamBuf);\n\t\tstring read_data;\n\t\tstd::getline(tmp_stream, read_data, '\\r');\n\n#ifdef _DEBUG\n\t\tif (read_data.length() < 512)\n\t\t\tlogprintf(\">>>> %s\", read_data.c_str());\n\t\telse\n\t\t{\n\t\t\tstring shortened_data(read_data);\n\t\t\tshortened_data.resize(256);\n\t\t\tlogprintf(\">>>> %s\", shortened_data.c_str());\n\t\t}\n#endif\n\n\t\t\/\/regex: parse error\n\t\t\/\/if this is an error message, it means that no other result data will come\n\t\tstatic const boost::regex error_rx(\"error id=([0-9]+) msg=([^ \\n]+)\");\n\t\tboost::smatch error_rx_result;\n\t\tif (boost::regex_search(read_data, error_rx_result, error_rx))\n\t\t{\n\t\t\tif (error_rx_result[1].str() == \"0\")\n\t\t\t{\n\t\t\t\tfor (auto i = captured_data.begin(); i != captured_data.end(); ++i)\n\t\t\t\t{\n\t\t\t\t\tstring &data = *i;\n\t\t\t\t\tif (data.find('|') != string::npos) \/\/multiple data rows with '|' as delimiter\n\t\t\t\t\t{\n\t\t\t\t\t\tvector<string> result_set;\n\t\t\t\t\t\tsize_t delim_pos = 0;\n\t\t\t\t\t\tdo\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tsize_t old_delim_pos = delim_pos;\n\t\t\t\t\t\t\tdelim_pos = data.find('|', delim_pos);\n\t\t\t\t\t\t\tstring row = data.substr(old_delim_pos, delim_pos - old_delim_pos);\n\t\t\t\t\t\t\tresult_set.push_back(row);\n\t\t\t\t\t\t} while (delim_pos != string::npos && ++delim_pos);\n\n\t\t\t\t\t\ti = captured_data.erase(i);\n\t\t\t\t\t\tfor (auto j = result_set.begin(), jend = result_set.end(); j != jend; ++j)\n\t\t\t\t\t\t\ti = captured_data.insert(i, *j);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t\/\/call callback and send next command\n\t\t\t\tm_CmdQueueMutex.lock();\n\t\t\t\tif (m_CmdQueue.empty() == false)\n\t\t\t\t{\n\t\t\t\t\tReadCallback_t &callback = m_CmdQueue.front().get<1>();\n\t\t\t\t\tm_CmdQueueMutex.unlock();\n\t\t\t\t\tif (callback.empty() == false)\n\t\t\t\t\t\tcallback(captured_data); \/\/calls the callback\n\t\t\t\t\tm_CmdQueueMutex.lock();\n\t\t\t\t\tm_CmdQueue.pop();\n\n\t\t\t\t\tif (m_CmdQueue.empty() == false)\n\t\t\t\t\t\tAsyncWrite(m_CmdQueue.front().get<0>());\n\t\t\t\t}\n\t\t\t\tm_CmdQueueMutex.unlock();\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tstring error_str(error_rx_result[2].str());\n\t\t\t\tCUtils::Get()->UnEscapeString(error_str);\n\n\t\t\t\tlogprintf(\">> plugin.TSConnector: Error while executing \\\"%s\\\": %s (#%s)\", \n\t\t\t\t\tm_CmdQueue.front().get<0>().c_str(), error_str.c_str(), error_rx_result[1].str().c_str());\n\t\t\t\tm_CmdQueue.pop();\n\t\t\t}\n\n\t\t\tcaptured_data.clear();\n\t\t}\n\t\telse if (read_data.find(\"notify\") == 0)\n\t\t{\n\t\t\t\/\/check if notify is duplicate\n\t\t\tstatic string last_notify_data;\n\t\t\tstatic const vector<string> duplicate_notifies{ \n\t\t\t\t\"notifyclientmoved\", \n\t\t\t\t\"notifycliententerview\", \n\t\t\t\t\"notifyclientleftview\" \n\t\t\t};\n\t\t\tbool is_duplicate = false;\n\t\t\t\n\t\t\tfor (auto &s : duplicate_notifies)\n\t\t\t{\n\t\t\t\tif (read_data.find(s) == 0)\n\t\t\t\t{\n\t\t\t\t\tif (last_notify_data == read_data)\n\t\t\t\t\t\tis_duplicate = true;\n\t\t\t\t\t\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\tif (is_duplicate == false)\n\t\t\t{\n\t\t\t\t\/\/notify event\n\t\t\t\tboost::smatch event_result;\n\t\t\t\tfor (auto &event : m_EventList)\n\t\t\t\t{\n\t\t\t\t\tif (boost::regex_search(read_data, event_result, event.get<0>()))\n\t\t\t\t\t{\n\t\t\t\t\t\tevent.get<1>()(event_result);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tlast_notify_data = read_data;\n\t\t}\n\t\telse\n\t\t{\n\t\t\t\/\/stack the result data if it is not an error or notification message\n\t\t\tcaptured_data.push_back(read_data);\n\t\t}\n\n\t\tAsyncRead();\n\t}\n\telse if (error_code == asio::error::eof)\n\t{\n\t\tAsyncConnect();\n\t}\n\telse\n\t\tlogprintf(\">> plugin.TSConnector: Error while reading: %s (#%d)\", error_code.message().c_str(), error_code.value());\n}\n\nvoid CNetwork::OnWrite(const boost::system::error_code &error_code)\n{\n#ifdef _DEBUG\n\tlogprintf(\"<<<< %s\", m_CmdWriteBuffer.c_str());\n#endif\n\tm_CmdWriteBuffer.clear();\n\tif (error_code.value() != 0)\n\t\tlogprintf(\">> plugin.TSConnector: Error while writing: %s (#%d)\", error_code.message().c_str(), error_code.value());\n}\n\nvoid CNetwork::Execute(string cmd, ReadCallback_t callback)\n{\n\tboost::lock_guard<boost::mutex> queue_lock_guard(m_CmdQueueMutex);\n\tm_CmdQueue.push(boost::make_tuple(boost::move(cmd), boost::move(callback)));\n\tif (m_CmdQueue.size() == 1)\n\t\tAsyncWrite(m_CmdQueue.front().get<0>());\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"EdgeHeap.h\"\n#include <cmath>\n\nnamespace ysk {\n \nusing Edge = LightCompleteGraph::Edge;\nusing EdgeWeight = LightCompleteGraph::EdgeWeight;\nusing EdgeId = LightCompleteGraph::EdgeId;\nusing NodeId = LightCompleteGraph::NodeId;\n\nEdgeHeap::EdgeHeap(LightCompleteGraph& param_graph, bool param_pruneZeroEdges) :\n pruneZeroEdges(param_pruneZeroEdges),\n graph(param_graph),\n unprocessed(0),\n icf(param_graph.numEdges(), 0.0),\n icp(param_graph.numEdges(), 0.0),\n edge2forb_rank(2*param_graph.numEdges(), 0),\n edge2perm_rank(2*param_graph.numEdges(), 0)\n{\n initInducedCosts();\n}\n\nvoid EdgeHeap::initInducedCosts() {\n if (verbosity >= 1)\n std::cout<<\"Compute induced cost.\"<<std::endl;\n \/\/ preprocessing: sorted vector of non-zero neighbours for each node\n std::vector<std::vector<NodeId>> nonZeroNeighbours;\n for (NodeId u = 0; u < graph.numNodes(); u++) {\n std::vector<NodeId> n;\n for (NodeId v = 0; v < graph.numNodes(); v++) {\n if (u != v && graph.getWeight(Edge(u,v)) != 0.0) {\n\tn.push_back(v);\n }\n }\n nonZeroNeighbours.push_back(n);\n }\n \n \/\/ compute array: edge -> icf\/icp\n for (NodeId u = 0; u < graph.numNodes(); u++) {\n if (verbosity >= 1)\n std::cout<<\"Completed \"<<(((2*graph.numNodes()-u)*(u+1)\/2)*100\/graph.numEdges())<<\"%\\r\"<<std::flush;\n for (NodeId v = u + 1; v < graph.numNodes(); v++) {\n \/\/ iterate over all edges uv\n Edge uv(u,v);\n EdgeWeight w_uv = graph.getWeight(uv);\n EdgeId id = uv.id();\n \n if (w_uv == 0.0 || w_uv == LightCompleteGraph::Forbidden || w_uv == LightCompleteGraph::Permanent) {\n\ticf[id] = LightCompleteGraph::Forbidden;\n\ticp[id] = LightCompleteGraph::Forbidden;\n\tcontinue;\n } else {\n\tunprocessed++;\n }\n \n \/\/ costs for the edge uv itself\n if (w_uv >= 0) {\t\n\ticf[id] += w_uv;\t\/\/ costs for removing uv\n } else {\n\ticp[id] += -w_uv;\t\/\/ costs for adding uv\n }\n \n \/\/ look at all triangles uvw containing uv. Triangles with a zero edge can be ignored\n std::vector<NodeId> w_vec;\n std::set_intersection(nonZeroNeighbours[u].begin(), nonZeroNeighbours[u].end(), nonZeroNeighbours[v].begin(), nonZeroNeighbours[v].end(), back_inserter(w_vec));\n\n for (NodeId w : w_vec) {\n\tEdge uw(u,w);\n Edge vw(v,w);\n EdgeWeight w_uw = graph.getWeight(uw);\n EdgeWeight w_vw = graph.getWeight(vw);\n\ticf[id] += getIcf(w_uw, w_vw);\n icp[id] += getIcp(w_uw, w_vw);\n }\n }\n }\n \n for (unsigned int i = 0; i < icf.size(); i++){\n if(std::isnan(icf[i])) {\n std::cout<<\"NaN! in icf\"<<std::endl;\n break;\n }\n if(std::isnan(icp[i])) {\n std::cout<<\"NaN! in icp\"<<std::endl;\n break;\n }\n }\n \n \/\/ sort edges by icf and icp values\n for (EdgeId i = 0; i < graph.numEdges(); i++) {\n forb_rank2edge.push_back(i);\n perm_rank2edge.push_back(i);\n }\n \n std::sort(forb_rank2edge.begin(), forb_rank2edge.end(), [this] (EdgeId& a, EdgeId& b) { return icf[a] > icf[b]; });\n std::sort(perm_rank2edge.begin(), perm_rank2edge.end(), [this] (EdgeId& a, EdgeId& b) { return icp[a] > icp[b]; });\n \n for (EdgeId i = 0; i < graph.numEdges(); i++) {\n icf.push_back(LightCompleteGraph::Forbidden);\n icp.push_back(LightCompleteGraph::Forbidden);\n forb_rank2edge.push_back(graph.numEdges()+i);\n perm_rank2edge.push_back(graph.numEdges()+i);\n }\n \n \/\/ save index in sorted vectors for each edge\n for (EdgeId i = 0; i < 2*graph.numEdges(); i++) {\n edge2forb_rank[forb_rank2edge[i]] = i;\n edge2perm_rank[perm_rank2edge[i]] = i;\n }\n}\n\nEdge EdgeHeap::getMaxIcfEdge() const {\n if (forb_rank2edge.size() <= 0) {\n return LightCompleteGraph::InvalidEdge;\n }\n EdgeId ei = forb_rank2edge[0];\n if (icf[ei] < 0) {\n return LightCompleteGraph::InvalidEdge;\n }\n NodeId u = std::ceil(std::sqrt(2*(ei+1)+0.25) - 0.5);\n NodeId v = ei - u * (u-1) \/ 2;\n return Edge(u, v);\n}\n\nEdge EdgeHeap::getMaxIcpEdge() const {\n if (perm_rank2edge.size() <= 0) {\n return LightCompleteGraph::InvalidEdge;\n }\n EdgeId ei = perm_rank2edge[0];\n if (icp[ei] < 0) {\n return LightCompleteGraph::InvalidEdge;\n }\n NodeId u = std::ceil(std::sqrt(2*(ei+1)+0.25) - 0.5);\n NodeId v = ei - u * (u-1) \/ 2;\n return Edge(u, v);\n}\n\nEdgeWeight EdgeHeap::getIcf(const Edge e) const {\n return icf[e.id()];\n}\n\nEdgeWeight EdgeHeap::getIcp(const Edge e) const {\n return icp[e.id()];\n}\n\nvoid EdgeHeap::increaseIcf(const Edge e, const EdgeWeight w) {\n EdgeId id = e.id();\n if (w != 0 && icf[id] >= 0) {\n icf[id] += w;\n icf[id] = std::max(icf[id], 0.0);\n updateHeap(forb_rank2edge, id, w, edge2forb_rank, icf);\n }\n}\n\nvoid EdgeHeap::increaseIcp(const Edge e, const EdgeWeight w) {\n EdgeId id = e.id();\n if (w != 0 && icp[id] >= 0) {\n icp[id] += w;\n icp[id] = std::max(icp[id], 0.0);\n updateHeap(perm_rank2edge, id, w, edge2perm_rank, icp);\n }\n}\n\nvoid EdgeHeap::removeEdge(const Edge e) {\n EdgeId id = e.id();\n if (icf[id] != LightCompleteGraph::Forbidden && icp[id] != LightCompleteGraph::Forbidden) {\n icf[id] = LightCompleteGraph::Forbidden;\n icp[id] = LightCompleteGraph::Forbidden;\n updateHeap(forb_rank2edge, id, LightCompleteGraph::Forbidden, edge2forb_rank, icf);\n updateHeap(perm_rank2edge, id, LightCompleteGraph::Forbidden, edge2perm_rank, icp);\n unprocessed--;\n }\n}\n\nLightCompleteGraph::EdgeWeight EdgeHeap::getIcf(const EdgeWeight uw, const EdgeWeight vw) const {\n if (uw > 0 && vw > 0) {\n \/\/ if both other edges present, remove the cheapest of both\n return std::min(uw, vw); \n } else {\n return 0;\n }\n}\n\nLightCompleteGraph::EdgeWeight EdgeHeap::getIcp(const EdgeWeight uw, const EdgeWeight vw) const {\n if (uw < 0 && vw > 0) {\n return std::min(vw, -uw); \t\/\/ either add uw or remove vw\n } else if (uw > 0 && vw < 0) {\n return std::min(-vw, uw); \t\/\/ either add vw or remove uw\n } else {\n return 0;\n }\n}\n\nint EdgeHeap::numUnprocessed() const {\n return unprocessed;\n}\n\nvoid EdgeHeap::updateHeap(std::vector<EdgeId>& heap, const EdgeId e, const EdgeWeight change, std::vector<EdgeId>& index, const std::vector<EdgeWeight>& score) {\n unsigned int pos = index[e];\n if (change > 0) {\n \/\/ value increased -> move edge upwards in heap\n while(score[heap[pos\/2]] < score[heap[pos]]) {\n \/\/ swap pos and pos\/2\n std::swap(heap[pos], heap[pos\/2]);\n index[heap[pos]] = pos;\n index[heap[pos\/2]] = pos\/2;\n pos = pos\/2;\n }\n } else {\n \/\/ value decreased -> move edge downwards in heap\n while((2*pos < heap.size() && score[heap[pos]] < score[heap[2*pos]])\n || (2*pos+1 < heap.size() && score[heap[pos]] < score[heap[2*pos+1]]) ) {\n if (2*pos+1 < heap.size() && score[heap[2*pos]] < score[heap[2*pos+1]]) {\n \/\/ element 2*pos+1 exists and is larger than 2*pos -> swap pos with 2*pos+1\n std::swap(heap[pos], heap[2*pos+1]);\n index[heap[pos]] = pos;\n index[heap[pos*2+1]] = pos*2+1;\n pos = 2*pos+1;\n } else {\n \/\/ else swap with 2*pos\n std::swap(heap[pos], heap[2*pos]);\n index[heap[pos]] = pos;\n index[heap[pos*2]] = pos*2;\n pos = 2*pos;\n }\n }\n}\n\/\/ bool wrong = false;\n\/\/ unsigned int where = 0;\n\/\/ for (unsigned int i = 0; i < heap.size()\/2; i++) {\n\/\/ if (score[heap[i]] < score[heap[2*i]]) {\n\/\/ wrong = true;\n\/\/ where = i;\n\/\/ }\n\/\/ if (2*i+1 < heap.size() && score[heap[i]] < score[heap[2*i+1]]) {\n\/\/ wrong = true;\n\/\/ where = i;\n\/\/ }\n\/\/ }\n\/\/ if (wrong) {\n\/\/ std::cout<<\"Error in heap (\"<<where<<\") \"<<score[heap[where\/2]]<<\" >= \"<<score[heap[where]]<<\" >= \"<<score[heap[2*where]]<<\" & \"<<score[heap[2*where+1]]<<std::endl;\n\/\/ }\n}\n\n} \/\/ namespace ysk<commit_msg>Fix heuristic calculation crash on verbosity >= 1<commit_after>#include \"EdgeHeap.h\"\n#include <cmath>\n\nnamespace ysk {\n \nusing Edge = LightCompleteGraph::Edge;\nusing EdgeWeight = LightCompleteGraph::EdgeWeight;\nusing EdgeId = LightCompleteGraph::EdgeId;\nusing NodeId = LightCompleteGraph::NodeId;\n\nEdgeHeap::EdgeHeap(LightCompleteGraph& param_graph, bool param_pruneZeroEdges) :\n pruneZeroEdges(param_pruneZeroEdges),\n graph(param_graph),\n unprocessed(0),\n icf(param_graph.numEdges(), 0.0),\n icp(param_graph.numEdges(), 0.0),\n edge2forb_rank(2*param_graph.numEdges(), 0),\n edge2perm_rank(2*param_graph.numEdges(), 0)\n{\n initInducedCosts();\n}\n\nvoid EdgeHeap::initInducedCosts() {\n if (verbosity >= 1)\n std::cout<<\"Compute induced cost.\"<<std::endl;\n \/\/ preprocessing: sorted vector of non-zero neighbours for each node\n std::vector<std::vector<NodeId>> nonZeroNeighbours;\n for (NodeId u = 0; u < graph.numNodes(); u++) {\n std::vector<NodeId> n;\n for (NodeId v = 0; v < graph.numNodes(); v++) {\n if (u != v && graph.getWeight(Edge(u,v)) != 0.0) {\n\tn.push_back(v);\n }\n }\n nonZeroNeighbours.push_back(n);\n }\n \n \/\/ compute array: edge -> icf\/icp\n for (NodeId u = 0; u < graph.numNodes(); u++) {\n if (verbosity >= 1 && graph.numEdges() > 0)\n std::cout<<\"Completed \"<<(((2*graph.numNodes()-u)*(u+1)\/2)*100\/graph.numEdges())<<\"%\\r\"<<std::flush;\n for (NodeId v = u + 1; v < graph.numNodes(); v++) {\n \/\/ iterate over all edges uv\n Edge uv(u,v);\n EdgeWeight w_uv = graph.getWeight(uv);\n EdgeId id = uv.id();\n \n if (w_uv == 0.0 || w_uv == LightCompleteGraph::Forbidden || w_uv == LightCompleteGraph::Permanent) {\n\ticf[id] = LightCompleteGraph::Forbidden;\n\ticp[id] = LightCompleteGraph::Forbidden;\n\tcontinue;\n } else {\n\tunprocessed++;\n }\n \n \/\/ costs for the edge uv itself\n if (w_uv >= 0) {\t\n\ticf[id] += w_uv;\t\/\/ costs for removing uv\n } else {\n\ticp[id] += -w_uv;\t\/\/ costs for adding uv\n }\n \n \/\/ look at all triangles uvw containing uv. Triangles with a zero edge can be ignored\n std::vector<NodeId> w_vec;\n std::set_intersection(nonZeroNeighbours[u].begin(), nonZeroNeighbours[u].end(), nonZeroNeighbours[v].begin(), nonZeroNeighbours[v].end(), back_inserter(w_vec));\n\n for (NodeId w : w_vec) {\n\tEdge uw(u,w);\n Edge vw(v,w);\n EdgeWeight w_uw = graph.getWeight(uw);\n EdgeWeight w_vw = graph.getWeight(vw);\n\ticf[id] += getIcf(w_uw, w_vw);\n icp[id] += getIcp(w_uw, w_vw);\n }\n }\n }\n \n for (unsigned int i = 0; i < icf.size(); i++){\n if(std::isnan(icf[i])) {\n std::cout<<\"NaN! in icf\"<<std::endl;\n break;\n }\n if(std::isnan(icp[i])) {\n std::cout<<\"NaN! in icp\"<<std::endl;\n break;\n }\n }\n \n \/\/ sort edges by icf and icp values\n for (EdgeId i = 0; i < graph.numEdges(); i++) {\n forb_rank2edge.push_back(i);\n perm_rank2edge.push_back(i);\n }\n \n std::sort(forb_rank2edge.begin(), forb_rank2edge.end(), [this] (EdgeId& a, EdgeId& b) { return icf[a] > icf[b]; });\n std::sort(perm_rank2edge.begin(), perm_rank2edge.end(), [this] (EdgeId& a, EdgeId& b) { return icp[a] > icp[b]; });\n \n for (EdgeId i = 0; i < graph.numEdges(); i++) {\n icf.push_back(LightCompleteGraph::Forbidden);\n icp.push_back(LightCompleteGraph::Forbidden);\n forb_rank2edge.push_back(graph.numEdges()+i);\n perm_rank2edge.push_back(graph.numEdges()+i);\n }\n \n \/\/ save index in sorted vectors for each edge\n for (EdgeId i = 0; i < 2*graph.numEdges(); i++) {\n edge2forb_rank[forb_rank2edge[i]] = i;\n edge2perm_rank[perm_rank2edge[i]] = i;\n }\n}\n\nEdge EdgeHeap::getMaxIcfEdge() const {\n if (forb_rank2edge.size() <= 0) {\n return LightCompleteGraph::InvalidEdge;\n }\n EdgeId ei = forb_rank2edge[0];\n if (icf[ei] < 0) {\n return LightCompleteGraph::InvalidEdge;\n }\n NodeId u = std::ceil(std::sqrt(2*(ei+1)+0.25) - 0.5);\n NodeId v = ei - u * (u-1) \/ 2;\n return Edge(u, v);\n}\n\nEdge EdgeHeap::getMaxIcpEdge() const {\n if (perm_rank2edge.size() <= 0) {\n return LightCompleteGraph::InvalidEdge;\n }\n EdgeId ei = perm_rank2edge[0];\n if (icp[ei] < 0) {\n return LightCompleteGraph::InvalidEdge;\n }\n NodeId u = std::ceil(std::sqrt(2*(ei+1)+0.25) - 0.5);\n NodeId v = ei - u * (u-1) \/ 2;\n return Edge(u, v);\n}\n\nEdgeWeight EdgeHeap::getIcf(const Edge e) const {\n return icf[e.id()];\n}\n\nEdgeWeight EdgeHeap::getIcp(const Edge e) const {\n return icp[e.id()];\n}\n\nvoid EdgeHeap::increaseIcf(const Edge e, const EdgeWeight w) {\n EdgeId id = e.id();\n if (w != 0 && icf[id] >= 0) {\n icf[id] += w;\n icf[id] = std::max(icf[id], 0.0);\n updateHeap(forb_rank2edge, id, w, edge2forb_rank, icf);\n }\n}\n\nvoid EdgeHeap::increaseIcp(const Edge e, const EdgeWeight w) {\n EdgeId id = e.id();\n if (w != 0 && icp[id] >= 0) {\n icp[id] += w;\n icp[id] = std::max(icp[id], 0.0);\n updateHeap(perm_rank2edge, id, w, edge2perm_rank, icp);\n }\n}\n\nvoid EdgeHeap::removeEdge(const Edge e) {\n EdgeId id = e.id();\n if (icf[id] != LightCompleteGraph::Forbidden && icp[id] != LightCompleteGraph::Forbidden) {\n icf[id] = LightCompleteGraph::Forbidden;\n icp[id] = LightCompleteGraph::Forbidden;\n updateHeap(forb_rank2edge, id, LightCompleteGraph::Forbidden, edge2forb_rank, icf);\n updateHeap(perm_rank2edge, id, LightCompleteGraph::Forbidden, edge2perm_rank, icp);\n unprocessed--;\n }\n}\n\nLightCompleteGraph::EdgeWeight EdgeHeap::getIcf(const EdgeWeight uw, const EdgeWeight vw) const {\n if (uw > 0 && vw > 0) {\n \/\/ if both other edges present, remove the cheapest of both\n return std::min(uw, vw); \n } else {\n return 0;\n }\n}\n\nLightCompleteGraph::EdgeWeight EdgeHeap::getIcp(const EdgeWeight uw, const EdgeWeight vw) const {\n if (uw < 0 && vw > 0) {\n return std::min(vw, -uw); \t\/\/ either add uw or remove vw\n } else if (uw > 0 && vw < 0) {\n return std::min(-vw, uw); \t\/\/ either add vw or remove uw\n } else {\n return 0;\n }\n}\n\nint EdgeHeap::numUnprocessed() const {\n return unprocessed;\n}\n\nvoid EdgeHeap::updateHeap(std::vector<EdgeId>& heap, const EdgeId e, const EdgeWeight change, std::vector<EdgeId>& index, const std::vector<EdgeWeight>& score) {\n unsigned int pos = index[e];\n if (change > 0) {\n \/\/ value increased -> move edge upwards in heap\n while(score[heap[pos\/2]] < score[heap[pos]]) {\n \/\/ swap pos and pos\/2\n std::swap(heap[pos], heap[pos\/2]);\n index[heap[pos]] = pos;\n index[heap[pos\/2]] = pos\/2;\n pos = pos\/2;\n }\n } else {\n \/\/ value decreased -> move edge downwards in heap\n while((2*pos < heap.size() && score[heap[pos]] < score[heap[2*pos]])\n || (2*pos+1 < heap.size() && score[heap[pos]] < score[heap[2*pos+1]]) ) {\n if (2*pos+1 < heap.size() && score[heap[2*pos]] < score[heap[2*pos+1]]) {\n \/\/ element 2*pos+1 exists and is larger than 2*pos -> swap pos with 2*pos+1\n std::swap(heap[pos], heap[2*pos+1]);\n index[heap[pos]] = pos;\n index[heap[pos*2+1]] = pos*2+1;\n pos = 2*pos+1;\n } else {\n \/\/ else swap with 2*pos\n std::swap(heap[pos], heap[2*pos]);\n index[heap[pos]] = pos;\n index[heap[pos*2]] = pos*2;\n pos = 2*pos;\n }\n }\n}\n\/\/ bool wrong = false;\n\/\/ unsigned int where = 0;\n\/\/ for (unsigned int i = 0; i < heap.size()\/2; i++) {\n\/\/ if (score[heap[i]] < score[heap[2*i]]) {\n\/\/ wrong = true;\n\/\/ where = i;\n\/\/ }\n\/\/ if (2*i+1 < heap.size() && score[heap[i]] < score[heap[2*i+1]]) {\n\/\/ wrong = true;\n\/\/ where = i;\n\/\/ }\n\/\/ }\n\/\/ if (wrong) {\n\/\/ std::cout<<\"Error in heap (\"<<where<<\") \"<<score[heap[where\/2]]<<\" >= \"<<score[heap[where]]<<\" >= \"<<score[heap[2*where]]<<\" & \"<<score[heap[2*where+1]]<<std::endl;\n\/\/ }\n}\n\n} \/\/ namespace ysk<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright(c) Sophist Solutions, Inc. 1990-2014. All rights reserved\n *\/\n#include \"..\/StroikaPreComp.h\"\n\n#if qPlatform_Windows\n#include <windows.h>\n#endif\n#if qPlatform_POSIX && qSupport_Proc_Filesystem\n#include <unistd.h>\n#endif\n\n#include \"..\/Execution\/ErrNoException.h\"\n#include \"..\/Execution\/Exceptions.h\"\n#include \"..\/Memory\/SmallStackBuffer.h\"\n#include \"..\/IO\/FileSystem\/PathName.h\"\n\n#include \"Module.h\"\n\n\nusing namespace Stroika::Foundation;\nusing namespace Stroika::Foundation::Execution;\n\n\n\n\n\n\/*\n ********************************************************************************\n ***************************** Execution::GetEXEDir *****************************\n ********************************************************************************\n *\/\nString Execution::GetEXEDir ()\n{\n return String::FromSDKString (GetEXEDirT ());\n}\n\n\n\n\n\/*\n ********************************************************************************\n ***************************** Execution::GetEXEDirT *****************************\n ********************************************************************************\n *\/\nSDKString Execution::GetEXEDirT ()\n{\n \/\/ Currently this impl depends on String - we may want to redo one cleanly without any dependency on String()...\n \/\/ Docs call for this - but I'm not sure its needed\n return IO::FileSystem::GetFileDirectory (GetEXEPath ()).AsSDKString ();\n}\n\n\n\n\n\n\/*\n ********************************************************************************\n **************************** Execution::GetEXEPath *****************************\n ********************************************************************************\n *\/\nString Execution::GetEXEPath ()\n{\n return String::FromSDKString (GetEXEPathT ());\n}\n\n\n\n\/*\n ********************************************************************************\n **************************** Execution::GetEXEPathT ****************************\n ********************************************************************************\n *\/\nSDKString Execution::GetEXEPathT ()\n{\n \/\/ See also http:\/\/stackoverflow.com\/questions\/1023306\/finding-current-executables-path-without-proc-self-exe\n \/\/ Mac OS X: _NSGetExecutablePath() (man 3 dyld)\n \/\/ Linux: readlink \/proc\/self\/exe\n \/\/ Solaris: getexecname()\n \/\/ FreeBSD: sysctl CTL_KERN KERN_PROC KERN_PROC_PATHNAME -1\n \/\/ BSD with procfs: readlink \/proc\/curproc\/file\n \/\/ Windows: GetModuleFileName() with hModule = nullptr\n \/\/\n#if qPlatform_Windows\n Characters::SDKChar buf[MAX_PATH];\n memset (buf, 0, sizeof (buf));\n Verify (::GetModuleFileName (nullptr, buf, NEltsOf (buf)));\n return buf;\n#elif qPlatform_POSIX && qSupport_Proc_Filesystem\n \/\/ readlink () isn't clear about finding the right size. THe only way to tell it wasn't enuf (maybe) is if all the\n \/\/ bytes passed in are used. That COULD mean it all fit, or there was more. If we get that - double buf size and try again\n Memory::SmallStackBuffer<Characters::SDKChar> buf (1000);\n ssize_t n;\n while ( (n = readlink (\"\/proc\/self\/exe\", buf, buf.GetSize () - 1)) == buf.GetSize ()) {\n buf.GrowToSize (buf.GetSize () * 2);\n }\n if (n < 0) {\n errno_ErrorException::DoThrow (errno);\n }\n Assert (n < buf.GetSize ());\n *(buf.begin () + n) = '\\0';\n return buf.begin ();\n#else\n AssertNotImplemented ();\n return SDKString ();\n#endif\n}\n\n<commit_msg>cleanup memset \/ readlink usag ein Execution::GetEXEPathT ()<commit_after>\/*\n * Copyright(c) Sophist Solutions, Inc. 1990-2014. All rights reserved\n *\/\n#include \"..\/StroikaPreComp.h\"\n\n#if qPlatform_Windows\n#include <windows.h>\n#endif\n#if qPlatform_POSIX && qSupport_Proc_Filesystem\n#include <unistd.h>\n#endif\n\n#include \"..\/Execution\/ErrNoException.h\"\n#include \"..\/Execution\/Exceptions.h\"\n#include \"..\/Memory\/SmallStackBuffer.h\"\n#include \"..\/IO\/FileSystem\/PathName.h\"\n\n#include \"Module.h\"\n\n\nusing namespace Stroika::Foundation;\nusing namespace Stroika::Foundation::Execution;\n\n\n\n\n\n\/*\n ********************************************************************************\n ***************************** Execution::GetEXEDir *****************************\n ********************************************************************************\n *\/\nString Execution::GetEXEDir ()\n{\n return String::FromSDKString (GetEXEDirT ());\n}\n\n\n\n\n\/*\n ********************************************************************************\n ***************************** Execution::GetEXEDirT *****************************\n ********************************************************************************\n *\/\nSDKString Execution::GetEXEDirT ()\n{\n \/\/ Currently this impl depends on String - we may want to redo one cleanly without any dependency on String()...\n \/\/ Docs call for this - but I'm not sure its needed\n return IO::FileSystem::GetFileDirectory (GetEXEPath ()).AsSDKString ();\n}\n\n\n\n\n\n\/*\n ********************************************************************************\n **************************** Execution::GetEXEPath *****************************\n ********************************************************************************\n *\/\nString Execution::GetEXEPath ()\n{\n return String::FromSDKString (GetEXEPathT ());\n}\n\n\n\n\/*\n ********************************************************************************\n **************************** Execution::GetEXEPathT ****************************\n ********************************************************************************\n *\/\nSDKString Execution::GetEXEPathT ()\n{\n \/\/ See also http:\/\/stackoverflow.com\/questions\/1023306\/finding-current-executables-path-without-proc-self-exe\n \/\/ Mac OS X: _NSGetExecutablePath() (man 3 dyld)\n \/\/ Linux: readlink \/proc\/self\/exe\n \/\/ Solaris: getexecname()\n \/\/ FreeBSD: sysctl CTL_KERN KERN_PROC KERN_PROC_PATHNAME -1\n \/\/ BSD with procfs: readlink \/proc\/curproc\/file\n \/\/ Windows: GetModuleFileName() with hModule = nullptr\n \/\/\n#if qPlatform_Windows\n Characters::SDKChar buf[MAX_PATH];\n \/\/memset (buf, 0, sizeof (buf));\n Verify (::GetModuleFileName (nullptr, buf, NEltsOf (buf)));\n buf[NEltsOf (buf) - 1] = '\\0'; \/\/ cheaper and just as safe as memset() - more even. Buffer always nul-terminated, and if GetModuleFileName succeeds will be nul-terminated\n return buf;\n#elif qPlatform_POSIX && qSupport_Proc_Filesystem\n \/\/ readlink () isn't clear about finding the right size. THe only way to tell it wasn't enuf (maybe) is if all the\n \/\/ bytes passed in are used. That COULD mean it all fit, or there was more. If we get that - double buf size and try again\n Memory::SmallStackBuffer<Characters::SDKChar> buf (1000);\n ssize_t n;\n while ( (n = readlink (\"\/proc\/self\/exe\", buf, buf.GetSize ())) == buf.GetSize ()) {\n buf.GrowToSize (buf.GetSize () * 2);\n }\n if (n < 0) {\n errno_ErrorException::DoThrow (errno);\n }\n Assert (n <= buf.GetSize ()); \/\/ could leave no room for NUL-byte, but not needed\n return SDKString (buf.begin (), buf.begin () + n);\n#else\n AssertNotImplemented ();\n return SDKString ();\n#endif\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES)\n *\n * This file is part of Orfeo Toolbox\n *\n * https:\/\/www.orfeo-toolbox.org\/\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"otbWrapperApplication.h\"\n#include \"otbWrapperApplicationFactory.h\"\n#include \"otbWrapperInputFilenameListParameter.h\"\n\nnamespace otb\n{\nnamespace Wrapper\n{\n\nclass TestApplication : public Application\n{\npublic:\n \/** Standard class typedefs. *\/\n typedef TestApplication Self;\n typedef Application Superclass;\n typedef itk::SmartPointer<Self> Pointer;\n typedef itk::SmartPointer<const Self> ConstPointer;\n\n \/** Standard macro *\/\n itkNewMacro(Self);\n\n itkTypeMacro(TestApplication, otb::Application);\n\nprivate:\n void DoInit() ITK_OVERRIDE\n {\n SetName(\"TestApplication\");\n SetDescription(\"This application helps developers to test parameters types\");\n\n SetDocName(\"Test\");\n SetDocLongDescription(\"The purpose of this application is to test parameters types.\");\n SetDocLimitations(\"None\");\n SetDocAuthors(\"OTB-Team\");\n SetDocSeeAlso(\" \");\n\n AddDocTag(\"Test\");\n\n \/\/std::cout << \"TestApplication::DoInit\" << std::endl;\n AddParameter(ParameterType_Empty, \"boolean\", \"Boolean\");\n AddParameter(ParameterType_Int, \"int\", \"Integer\");\n MandatoryOff(\"int\");\n AddParameter(ParameterType_Float, \"float\", \"Float\");\n MandatoryOff(\"float\");\n AddParameter(ParameterType_String, \"string\", \"String\");\n AddParameter(ParameterType_InputFilename, \"filename\", \"File name\");\n AddParameter(ParameterType_OutputFilename, \"outfilename\", \"Output Filename\");\n AddParameter(ParameterType_Directory, \"directory\", \"Directory name\");\n\n\n AddParameter(ParameterType_Choice, \"choice\", \"Choice\");\n AddChoice(\"choice.choice1\", \"Choice 1\");\n AddChoice(\"choice.choice2\", \"Choice 2\");\n AddChoice(\"choice.choice3\", \"Choice 3\");\n AddParameter(ParameterType_Float, \"choice.choice1.floatchoice1\", \"Float of choice1\");\n SetDefaultParameterFloat(\"choice.choice1.floatchoice1\", 0.125);\n AddParameter(ParameterType_Float, \"choice.choice3.floatchoice3\", \"Float of choice3\");\n SetDefaultParameterFloat(\"choice.choice3.floatchoice3\", 5.0);\n\n AddParameter(ParameterType_Group, \"ingroup\", \"Input Group\");\n MandatoryOff(\"ingroup\");\n AddParameter(ParameterType_Float, \"ingroup.integer\", \"Integer of Group\");\n AddParameter(ParameterType_Group, \"ingroup.images\", \"Input Images Group\");\n AddParameter(ParameterType_InputImage, \"ingroup.images.inputimage\", \"Input Image\");\n\n AddParameter(ParameterType_Group, \"outgroup\", \"Output Group\");\n AddParameter(ParameterType_OutputImage, \"outgroup.outputimage\", \"Output Image\");\n\n AddParameter(ParameterType_InputImageList, \"il\", \"Input image list\");\n MandatoryOff(\"il\");\n\n AddParameter( ParameterType_InputFilenameList, \"fl\", \"Input filename list\" );\n MandatoryOff( \"fl\" );\n\n AddParameter( ParameterType_InputVectorDataList, \"vdl\", \"Input vector-data list\" );\n MandatoryOff( \"vdl\" );\n\n AddParameter( ParameterType_StringList, \"sl\", \"Input string list\" );\n MandatoryOff( \"sl\" );\n\n AddParameter(ParameterType_ListView, \"cl\", \"Output Image channels\");\n AddChoice(\"cl.choice1\", \"Choice1\");\n AddChoice(\"cl.choice2\", \"Choice2\");\n MandatoryOff(\"cl\");\n\n AddParameter(ParameterType_ComplexInputImage, \"cin\", \"Input Complex Image\");\n AddParameter(ParameterType_ComplexOutputImage, \"cout\", \"Output Complex Image\");\n\n \/\/ Doc example parameter settings\n SetDocExampleParameterValue(\"boolean\", \"true\");\n SetDocExampleParameterValue(\"filename\", \"myFilename.foo\");\n\n SetOfficialDocLink();\n }\n\n void DoUpdateParameters() ITK_OVERRIDE\n {}\n\n void DoExecute() ITK_OVERRIDE\n {\n if( HasValue(\"il\") && IsParameterEnabled(\"il\") )\n {\n FloatVectorImageListType * imgList = GetParameterImageList( \"il\" );\n SetParameterOutputImage(\n \"outgroup.outputimage\",\n imgList->GetNthElement( 0 )\n );\n }\n else if (HasValue(\"ingroup.images.inputimage\") &&\n IsParameterEnabled(\"ingroup.images.inputimage\",true) )\n {\n SetParameterOutputImage(\"outgroup.outputimage\",\n GetParameterImage(\"ingroup.images.inputimage\"));\n }\n else\n {\n otbAppLogFATAL(\"Waiting at least one input image\");\n }\n\n SetParameterComplexOutputImage(\n \"cout\",\n GetParameterComplexImage( \"cin\" )\n );\n\n PrintStrings( \"fl\" );\n }\n\nprivate:\n void PrintStrings( const std::string & key ) const\n {\n if( !IsParameterEnabled(key) )\n return;\n\n const Parameter * p = GetParameterByKey( key );\n assert( p!=nullptr );\n const StringListInterface * sli =\n dynamic_cast< const StringListInterface * >(p);\n assert( sli!=nullptr );\n\n StringListInterface::StringVector strings;\n\n sli->GetStrings( strings );\n\n std::cout << \"{\" << std::endl;\n {\n for( auto s : strings )\n std::cout << \"'\" << s << \"'\" << std::endl;\n }\n std::cout << \"}\"<< std::endl;\n }\n};\n\n} \/\/ end of namespace Wrapper\n} \/\/ end of namespace otb\n\nOTB_APPLICATION_EXPORT( otb::Wrapper::TestApplication )\n<commit_msg>TEST: fix TestApplication<commit_after>\/*\n * Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES)\n *\n * This file is part of Orfeo Toolbox\n *\n * https:\/\/www.orfeo-toolbox.org\/\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"otbWrapperApplication.h\"\n#include \"otbWrapperApplicationFactory.h\"\n#include \"otbWrapperInputFilenameListParameter.h\"\n\nnamespace otb\n{\nnamespace Wrapper\n{\n\nclass TestApplication : public Application\n{\npublic:\n \/** Standard class typedefs. *\/\n typedef TestApplication Self;\n typedef Application Superclass;\n typedef itk::SmartPointer<Self> Pointer;\n typedef itk::SmartPointer<const Self> ConstPointer;\n\n \/** Standard macro *\/\n itkNewMacro(Self);\n\n itkTypeMacro(TestApplication, otb::Application);\n\nprivate:\n void DoInit() ITK_OVERRIDE\n {\n SetName(\"TestApplication\");\n SetDescription(\"This application helps developers to test parameters types\");\n\n SetDocName(\"Test\");\n SetDocLongDescription(\"The purpose of this application is to test parameters types.\");\n SetDocLimitations(\"None\");\n SetDocAuthors(\"OTB-Team\");\n SetDocSeeAlso(\" \");\n\n AddDocTag(\"Test\");\n\n \/\/std::cout << \"TestApplication::DoInit\" << std::endl;\n AddParameter(ParameterType_Empty, \"boolean\", \"Boolean\");\n AddParameter(ParameterType_Int, \"int\", \"Integer\");\n MandatoryOff(\"int\");\n AddParameter(ParameterType_Float, \"float\", \"Float\");\n MandatoryOff(\"float\");\n AddParameter(ParameterType_String, \"string\", \"String\");\n AddParameter(ParameterType_InputFilename, \"filename\", \"File name\");\n AddParameter(ParameterType_OutputFilename, \"outfilename\", \"Output Filename\");\n AddParameter(ParameterType_Directory, \"directory\", \"Directory name\");\n\n\n AddParameter(ParameterType_Choice, \"choice\", \"Choice\");\n AddChoice(\"choice.choice1\", \"Choice 1\");\n AddChoice(\"choice.choice2\", \"Choice 2\");\n AddChoice(\"choice.choice3\", \"Choice 3\");\n AddParameter(ParameterType_Float, \"choice.choice1.floatchoice1\", \"Float of choice1\");\n SetDefaultParameterFloat(\"choice.choice1.floatchoice1\", 0.125);\n AddParameter(ParameterType_Float, \"choice.choice3.floatchoice3\", \"Float of choice3\");\n SetDefaultParameterFloat(\"choice.choice3.floatchoice3\", 5.0);\n\n AddParameter(ParameterType_Group, \"ingroup\", \"Input Group\");\n MandatoryOff(\"ingroup\");\n AddParameter(ParameterType_Float, \"ingroup.integer\", \"Integer of Group\");\n AddParameter(ParameterType_Group, \"ingroup.images\", \"Input Images Group\");\n AddParameter(ParameterType_InputImage, \"ingroup.images.inputimage\", \"Input Image\");\n\n AddParameter(ParameterType_Group, \"outgroup\", \"Output Group\");\n AddParameter(ParameterType_OutputImage, \"outgroup.outputimage\", \"Output Image\");\n\n AddParameter(ParameterType_InputImageList, \"il\", \"Input image list\");\n MandatoryOff(\"il\");\n\n AddParameter( ParameterType_InputFilenameList, \"fl\", \"Input filename list\" );\n MandatoryOff( \"fl\" );\n\n AddParameter( ParameterType_InputVectorDataList, \"vdl\", \"Input vector-data list\" );\n MandatoryOff( \"vdl\" );\n\n AddParameter( ParameterType_StringList, \"sl\", \"Input string list\" );\n MandatoryOff( \"sl\" );\n\n AddParameter(ParameterType_ListView, \"cl\", \"Output Image channels\");\n AddChoice(\"cl.choice1\", \"Choice1\");\n AddChoice(\"cl.choice2\", \"Choice2\");\n MandatoryOff(\"cl\");\n\n AddParameter(ParameterType_ComplexInputImage, \"cin\", \"Input Complex Image\");\n AddParameter(ParameterType_ComplexOutputImage, \"cout\", \"Output Complex Image\");\n\n \/\/ Doc example parameter settings\n SetDocExampleParameterValue(\"boolean\", \"true\");\n SetDocExampleParameterValue(\"filename\", \"myFilename.foo\");\n\n SetOfficialDocLink();\n }\n\n void DoUpdateParameters() ITK_OVERRIDE\n {}\n\n void DoExecute() ITK_OVERRIDE\n {\n if( HasValue(\"il\") && IsParameterEnabled(\"il\") )\n {\n FloatVectorImageListType * imgList = GetParameterImageList( \"il\" );\n SetParameterOutputImage(\n \"outgroup.outputimage\",\n imgList->GetNthElement( 0 )\n );\n }\n else if (HasValue(\"ingroup.images.inputimage\") && IsParameterEnabled(\"ingroup\") )\n {\n SetParameterOutputImage(\"outgroup.outputimage\",\n GetParameterImage(\"ingroup.images.inputimage\"));\n }\n else\n {\n otbAppLogFATAL(\"Waiting at least one input image\");\n }\n\n SetParameterComplexOutputImage(\n \"cout\",\n GetParameterComplexImage( \"cin\" )\n );\n\n PrintStrings( \"fl\" );\n }\n\nprivate:\n void PrintStrings( const std::string & key ) const\n {\n if( !IsParameterEnabled(key) )\n return;\n\n const Parameter * p = GetParameterByKey( key );\n assert( p!=nullptr );\n const StringListInterface * sli =\n dynamic_cast< const StringListInterface * >(p);\n assert( sli!=nullptr );\n\n StringListInterface::StringVector strings;\n\n sli->GetStrings( strings );\n\n std::cout << \"{\" << std::endl;\n {\n for( auto s : strings )\n std::cout << \"'\" << s << \"'\" << std::endl;\n }\n std::cout << \"}\"<< std::endl;\n }\n};\n\n} \/\/ end of namespace Wrapper\n} \/\/ end of namespace otb\n\nOTB_APPLICATION_EXPORT( otb::Wrapper::TestApplication )\n<|endoftext|>"} {"text":"<commit_before>#include \"group_flux_checker_sequential.h\"\n\nnamespace bart {\n\nnamespace convergence {\n\nGroupFluxCheckerSequential::GroupFluxCheckerSequential(\n std::unique_ptr<FluxCheckerI> &tester)\n : tester_(std::move(tester)) {}\n\nbool GroupFluxCheckerSequential::CheckIfConverged(data::ScalarGroupFluxPtrs ¤t,\n data::ScalarGroupFluxPtrs &last) {\n AssertThrow(current.size() > 0,\n dealii::ExcMessage(\"Current iteration group fluxes has 0 groups\"));\n AssertThrow(last.size() > 0,\n dealii::ExcMessage(\"Last iteration group fluxes has 0 groups\"));\n AssertThrow(last.size() == current.size(),\n dealii::ExcMessage(\"Current & last group iteration fluxes have\"\n \"different sizes\"));\n\n for (auto current_pair = current.cbegin(), last_pair = last.cbegin();\n current_pair != current.cend(), last_pair != last.cend();\n ++current_pair, ++last_pair) {\n\n auto &[current_group_number, current_group_flux_ptr] = *current_pair;\n auto &[last_group_number, last_group_flux_ptr] = *last_pair;\n \n AssertThrow(current_group_number == last_group_number,\n dealii::ExcMessage(\"Current & last group numbers mismatched\"));\n\n if (!tester_->CheckIfConverged(*current_group_flux_ptr,\n *last_group_flux_ptr)) {\n failed_group_ = current_group_number;\n return false;\n }\n }\n return true;\n}\n\nbool GroupFluxCheckerSequential::CheckIfConverged(data::AngularGroupFluxPtrs ¤t,\n data::AngularGroupFluxPtrs &last) {\n AssertThrow(current.size() > 0,\n dealii::ExcMessage(\"Current iteration group fluxes has 0 groups & angles\"));\n AssertThrow(last.size() > 0,\n dealii::ExcMessage(\"Last iteration group fluxes has 0 groups & angles\"));\n AssertThrow(last.size() == current.size(),\n dealii::ExcMessage(\"Current & last group iteration fluxes have\"\n \"different sizes\"));\n \n for (auto current_pair = current.cbegin(), last_pair = last.cbegin();\n current_pair != current.cend(), last_pair != last.cend();\n ++current_pair, ++last_pair) {\n\n auto &[current_dof_pair, current_group_flux_ptr] = *current_pair;\n auto &[last_dof_pair, last_group_flux_ptr] = *last_pair;\n auto &[current_group_number, current_direction] = current_dof_pair;\n auto &[last_group_number, last_direction] = last_dof_pair;\n \n AssertThrow(current_group_number == last_group_number,\n dealii::ExcMessage(\"Current & last group numbers mismatched\"));\n AssertThrow(current_direction == last_direction,\n dealii::ExcMessage(\"Current & last directions mismatched\"));\n\n if (!tester_->CheckIfConverged(*current_group_flux_ptr,\n *last_group_flux_ptr)) {\n failed_group_ = current_group_number;\n failed_angle_ = current_direction;\n return false;\n }\n }\n return true;\n \n}\n\n} \/\/ namespace convergence\n\n} \/\/ namespace bart\n<commit_msg>removed extraneous white space<commit_after>#include \"group_flux_checker_sequential.h\"\n\nnamespace bart {\n\nnamespace convergence {\n\nGroupFluxCheckerSequential::GroupFluxCheckerSequential(\n std::unique_ptr<FluxCheckerI> &tester)\n : tester_(std::move(tester)) {}\n\nbool GroupFluxCheckerSequential::CheckIfConverged(data::ScalarGroupFluxPtrs ¤t,\n data::ScalarGroupFluxPtrs &last) {\n AssertThrow(current.size() > 0,\n dealii::ExcMessage(\"Current iteration group fluxes has 0 groups\"));\n AssertThrow(last.size() > 0,\n dealii::ExcMessage(\"Last iteration group fluxes has 0 groups\"));\n AssertThrow(last.size() == current.size(),\n dealii::ExcMessage(\"Current & last group iteration fluxes have\"\n \"different sizes\"));\n\n for (auto current_pair = current.cbegin(), last_pair = last.cbegin();\n current_pair != current.cend(), last_pair != last.cend();\n ++current_pair, ++last_pair) {\n\n auto &[current_group_number, current_group_flux_ptr] = *current_pair;\n auto &[last_group_number, last_group_flux_ptr] = *last_pair;\n \n AssertThrow(current_group_number == last_group_number,\n dealii::ExcMessage(\"Current & last group numbers mismatched\"));\n\n if (!tester_->CheckIfConverged(*current_group_flux_ptr,\n *last_group_flux_ptr)) {\n failed_group_ = current_group_number;\n return false;\n }\n }\n return true;\n}\n\nbool GroupFluxCheckerSequential::CheckIfConverged(data::AngularGroupFluxPtrs ¤t,\n data::AngularGroupFluxPtrs &last) {\n AssertThrow(current.size() > 0,\n dealii::ExcMessage(\"Current iteration group fluxes has 0 groups & angles\"));\n AssertThrow(last.size() > 0,\n dealii::ExcMessage(\"Last iteration group fluxes has 0 groups & angles\"));\n AssertThrow(last.size() == current.size(),\n dealii::ExcMessage(\"Current & last group iteration fluxes have\"\n \"different sizes\"));\n \n for (auto current_pair = current.cbegin(), last_pair = last.cbegin();\n current_pair != current.cend(), last_pair != last.cend();\n ++current_pair, ++last_pair) {\n\n auto &[current_dof_pair, current_group_flux_ptr] = *current_pair;\n auto &[last_dof_pair, last_group_flux_ptr] = *last_pair;\n auto &[current_group_number, current_direction] = current_dof_pair;\n auto &[last_group_number, last_direction] = last_dof_pair;\n \n AssertThrow(current_group_number == last_group_number,\n dealii::ExcMessage(\"Current & last group numbers mismatched\"));\n AssertThrow(current_direction == last_direction,\n dealii::ExcMessage(\"Current & last directions mismatched\"));\n\n if (!tester_->CheckIfConverged(*current_group_flux_ptr,\n *last_group_flux_ptr)) {\n failed_group_ = current_group_number;\n failed_angle_ = current_direction;\n return false;\n }\n }\n return true;\n}\n\n} \/\/ namespace convergence\n\n} \/\/ namespace bart\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ Copyright 2015 Google Inc.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/\n#include \"Firebase.h\"\n\n\/\/ Detect whether stable version of HTTP library is installed instead of\n\/\/ master branch and patch in missing status and methods.\n#ifndef HTTP_CODE_TEMPORARY_REDIRECT\n#define HTTP_CODE_TEMPORARY_REDIRECT 307\n#define USE_ESP_ARDUINO_CORE_2_0_0\n#endif\n\nnamespace {\nconst char* kFirebaseFingerprint = \"7A 54 06 9B DC 7A 25 B3 86 8D 66 53 48 2C 0B 96 42 C7 B3 0A\";\nconst uint16_t kFirebasePort = 443;\n\nString makeFirebaseURL(const String& path, const String& auth) {\n String url;\n if (path[0] != '\/') {\n url = \"\/\";\n }\n url += path + \".json\";\n if (auth.length() > 0) {\n url += \"?auth=\" + auth;\n }\n return url;\n}\n\n} \/\/ namespace\n\nFirebase::Firebase(const String& host) : host_(host) {\n http_.setReuse(true);\n}\n\nFirebase& Firebase::auth(const String& auth) {\n auth_ = auth;\n return *this;\n}\n\nFirebaseGet Firebase::get(const String& path) {\n return FirebaseGet(host_, auth_, path, &http_);\n}\n\nFirebaseSet Firebase::set(const String& path, const String& value) {\n return FirebaseSet(host_, auth_, path, value, &http_);\n}\n\nFirebasePush Firebase::push(const String& path, const String& value) {\n return FirebasePush(host_, auth_, path, value, &http_);\n}\n\nFirebaseRemove Firebase::remove(const String& path) {\n return FirebaseRemove(host_, auth_, path, &http_);\n}\n\nFirebaseStream Firebase::stream(const String& path) {\n \/\/ TODO: create new client dedicated to stream.\n return FirebaseStream(host_, auth_, path, &http_);\n}\n\n\/\/ FirebaseCall\nFirebaseCall::FirebaseCall(const String& host, const String& auth,\n const char* method, const String& path,\n const String& data, HTTPClient* http) : http_(http) {\n String url = makeFirebaseURL(path, auth);\n http_->setReuse(true);\n http_->begin(host, kFirebasePort, url, true, kFirebaseFingerprint);\n\n bool followRedirect = false;\n if (method == \"STREAM\") {\n method = \"GET\";\n http_->addHeader(\"Accept\", \"text\/event-stream\");\n followRedirect = true;\n }\n\n if (followRedirect) {\n const char* headers[] = {\"Location\"};\n http_->collectHeaders(headers, 1);\n }\n\n int status = http_->sendRequest(method, (uint8_t*)data.c_str(), data.length());\n\n \/\/ TODO: Add a max redirect check\n if (followRedirect) {\n while (status == HTTP_CODE_TEMPORARY_REDIRECT) {\n String location = http_->header(\"Location\");\n http_->setReuse(false);\n http_->end();\n http_->setReuse(true);\n http_->begin(location, kFirebaseFingerprint);\n status = http_->sendRequest(\"GET\", (uint8_t*)NULL, 0);\n }\n }\n\n if (status != 200) {\n#ifdef USE_ESP_ARDUINO_CORE_2_0_0\n error_ = FirebaseError(status, String(method) + \" \" + url + \": \" + status);\n#else\n error_ = FirebaseError(status, String(method) + \" \" + url + \": \" + HTTPClient::errorToString(status));\n#endif\n }\n\n \/\/ if not streaming.\n if (!followRedirect) {\n response_ = http_->getString();\n }\n}\n\nconst JsonObject& FirebaseCall::json() {\n \/\/TODO(edcoyne): This is not efficient, we should do something smarter with\n \/\/the buffers.\n buffer_ = DynamicJsonBuffer();\n return buffer_.parseObject(response());\n}\n\n\/\/ FirebaseGet\nFirebaseGet::FirebaseGet(const String& host, const String& auth,\n const String& path,\n HTTPClient* http)\n : FirebaseCall(host, auth, \"GET\", path, \"\", http) {\n}\n\n\/\/ FirebaseSet\nFirebaseSet::FirebaseSet(const String& host, const String& auth,\n const String& path, const String& value,\n HTTPClient* http)\n : FirebaseCall(host, auth, \"PUT\", path, value, http) {\n if (!error()) {\n \/\/ TODO: parse json\n json_ = response();\n }\n}\n\/\/ FirebasePush\nFirebasePush::FirebasePush(const String& host, const String& auth,\n const String& path, const String& value,\n HTTPClient* http)\n : FirebaseCall(host, auth, \"POST\", path, value, http) {\n if (!error()) {\n name_ = parseResponse()[\"name\"].as<const char*>();\n }\n}\n\n\/\/ FirebasePush\nFirebaseRemove::FirebaseRemove(const String& host, const String& auth,\n const String& path,\n HTTPClient* http)\n : FirebaseCall(host, auth, \"DELETE\", path, \"\", http) {\n}\n\n\/\/ FirebaseStream\nFirebaseStream::FirebaseStream(const String& host, const String& auth,\n const String& path,\n HTTPClient* http)\n : FirebaseCall(host, auth, \"STREAM\", path, \"\", http) {\n}\n\nbool FirebaseStream::available() {\n return http_->getStreamPtr()->available();\n}\n\nFirebaseStream::Event FirebaseStream::read(String& event) {\n auto client = http_->getStreamPtr();\n Event type;\n String typeStr = client->readStringUntil('\\n').substring(7);\n if (typeStr == \"put\") {\n type = Event::PUT;\n } else if (typeStr == \"patch\") {\n type = Event::PATCH;\n } else {\n type = Event::UNKNOWN;\n }\n event = client->readStringUntil('\\n').substring(6);\n client->readStringUntil('\\n'); \/\/ consume separator\n return type;\n}\n<commit_msg>forgot a parseResponse invocation<commit_after>\/\/\n\/\/ Copyright 2015 Google Inc.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/\n#include \"Firebase.h\"\n\n\/\/ Detect whether stable version of HTTP library is installed instead of\n\/\/ master branch and patch in missing status and methods.\n#ifndef HTTP_CODE_TEMPORARY_REDIRECT\n#define HTTP_CODE_TEMPORARY_REDIRECT 307\n#define USE_ESP_ARDUINO_CORE_2_0_0\n#endif\n\nnamespace {\nconst char* kFirebaseFingerprint = \"7A 54 06 9B DC 7A 25 B3 86 8D 66 53 48 2C 0B 96 42 C7 B3 0A\";\nconst uint16_t kFirebasePort = 443;\n\nString makeFirebaseURL(const String& path, const String& auth) {\n String url;\n if (path[0] != '\/') {\n url = \"\/\";\n }\n url += path + \".json\";\n if (auth.length() > 0) {\n url += \"?auth=\" + auth;\n }\n return url;\n}\n\n} \/\/ namespace\n\nFirebase::Firebase(const String& host) : host_(host) {\n http_.setReuse(true);\n}\n\nFirebase& Firebase::auth(const String& auth) {\n auth_ = auth;\n return *this;\n}\n\nFirebaseGet Firebase::get(const String& path) {\n return FirebaseGet(host_, auth_, path, &http_);\n}\n\nFirebaseSet Firebase::set(const String& path, const String& value) {\n return FirebaseSet(host_, auth_, path, value, &http_);\n}\n\nFirebasePush Firebase::push(const String& path, const String& value) {\n return FirebasePush(host_, auth_, path, value, &http_);\n}\n\nFirebaseRemove Firebase::remove(const String& path) {\n return FirebaseRemove(host_, auth_, path, &http_);\n}\n\nFirebaseStream Firebase::stream(const String& path) {\n \/\/ TODO: create new client dedicated to stream.\n return FirebaseStream(host_, auth_, path, &http_);\n}\n\n\/\/ FirebaseCall\nFirebaseCall::FirebaseCall(const String& host, const String& auth,\n const char* method, const String& path,\n const String& data, HTTPClient* http) : http_(http) {\n String url = makeFirebaseURL(path, auth);\n http_->setReuse(true);\n http_->begin(host, kFirebasePort, url, true, kFirebaseFingerprint);\n\n bool followRedirect = false;\n if (method == \"STREAM\") {\n method = \"GET\";\n http_->addHeader(\"Accept\", \"text\/event-stream\");\n followRedirect = true;\n }\n\n if (followRedirect) {\n const char* headers[] = {\"Location\"};\n http_->collectHeaders(headers, 1);\n }\n\n int status = http_->sendRequest(method, (uint8_t*)data.c_str(), data.length());\n\n \/\/ TODO: Add a max redirect check\n if (followRedirect) {\n while (status == HTTP_CODE_TEMPORARY_REDIRECT) {\n String location = http_->header(\"Location\");\n http_->setReuse(false);\n http_->end();\n http_->setReuse(true);\n http_->begin(location, kFirebaseFingerprint);\n status = http_->sendRequest(\"GET\", (uint8_t*)NULL, 0);\n }\n }\n\n if (status != 200) {\n#ifdef USE_ESP_ARDUINO_CORE_2_0_0\n error_ = FirebaseError(status, String(method) + \" \" + url + \": \" + status);\n#else\n error_ = FirebaseError(status, String(method) + \" \" + url + \": \" + HTTPClient::errorToString(status));\n#endif\n }\n\n \/\/ if not streaming.\n if (!followRedirect) {\n response_ = http_->getString();\n }\n}\n\nconst JsonObject& FirebaseCall::json() {\n \/\/TODO(edcoyne): This is not efficient, we should do something smarter with\n \/\/the buffers.\n buffer_ = DynamicJsonBuffer();\n return buffer_.parseObject(response());\n}\n\n\/\/ FirebaseGet\nFirebaseGet::FirebaseGet(const String& host, const String& auth,\n const String& path,\n HTTPClient* http)\n : FirebaseCall(host, auth, \"GET\", path, \"\", http) {\n}\n\n\/\/ FirebaseSet\nFirebaseSet::FirebaseSet(const String& host, const String& auth,\n const String& path, const String& value,\n HTTPClient* http)\n : FirebaseCall(host, auth, \"PUT\", path, value, http) {\n if (!error()) {\n \/\/ TODO: parse json\n json_ = response();\n }\n}\n\/\/ FirebasePush\nFirebasePush::FirebasePush(const String& host, const String& auth,\n const String& path, const String& value,\n HTTPClient* http)\n : FirebaseCall(host, auth, \"POST\", path, value, http) {\n if (!error()) {\n name_ = json()[\"name\"].as<const char*>();\n }\n}\n\n\/\/ FirebasePush\nFirebaseRemove::FirebaseRemove(const String& host, const String& auth,\n const String& path,\n HTTPClient* http)\n : FirebaseCall(host, auth, \"DELETE\", path, \"\", http) {\n}\n\n\/\/ FirebaseStream\nFirebaseStream::FirebaseStream(const String& host, const String& auth,\n const String& path,\n HTTPClient* http)\n : FirebaseCall(host, auth, \"STREAM\", path, \"\", http) {\n}\n\nbool FirebaseStream::available() {\n return http_->getStreamPtr()->available();\n}\n\nFirebaseStream::Event FirebaseStream::read(String& event) {\n auto client = http_->getStreamPtr();\n Event type;\n String typeStr = client->readStringUntil('\\n').substring(7);\n if (typeStr == \"put\") {\n type = Event::PUT;\n } else if (typeStr == \"patch\") {\n type = Event::PATCH;\n } else {\n type = Event::UNKNOWN;\n }\n event = client->readStringUntil('\\n').substring(6);\n client->readStringUntil('\\n'); \/\/ consume separator\n return type;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES)\n *\n * This file is part of Orfeo Toolbox\n *\n * https:\/\/www.orfeo-toolbox.org\/\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"otbWrapperApplication.h\"\n#include \"otbWrapperApplicationFactory.h\"\n\nnamespace otb\n{\nnamespace Wrapper\n{\n\nclass TestApplication : public Application\n{\npublic:\n \/** Standard class typedefs. *\/\n typedef TestApplication Self;\n typedef Application Superclass;\n typedef itk::SmartPointer<Self> Pointer;\n typedef itk::SmartPointer<const Self> ConstPointer;\n\n \/** Standard macro *\/\n itkNewMacro(Self);\n\n itkTypeMacro(TestApplication, otb::Application);\n\nprivate:\n void DoInit() ITK_OVERRIDE\n {\n SetName(\"TestApplication\");\n SetDescription(\"This application helps developers to test parameters types\");\n\n\n SetDocName(\"Test\");\n SetDocLongDescription(\"The purpose of this application is to test parameters types.\");\n SetDocLimitations(\"None\");\n SetDocAuthors(\"OTB-Team\");\n SetDocSeeAlso(\" \");\n\n AddDocTag(\"Test\");\n\n \/\/std::cout << \"TestApplication::DoInit\" << std::endl;\n AddParameter(ParameterType_Empty, \"boolean\", \"Boolean\");\n AddParameter(ParameterType_Int, \"int\", \"Integer\");\n MandatoryOff(\"int\");\n AddParameter(ParameterType_Float, \"float\", \"Float\");\n MandatoryOff(\"float\");\n AddParameter(ParameterType_String, \"string\", \"String\");\n AddParameter(ParameterType_InputFilename, \"filename\", \"File name\");\n AddParameter(ParameterType_OutputFilename, \"outfilename\", \"Output Filename\");\n AddParameter(ParameterType_Directory, \"directory\", \"Directory name\");\n\n\n AddParameter(ParameterType_Choice, \"choice\", \"Choice\");\n AddChoice(\"choice.choice1\", \"Choice 1\");\n AddChoice(\"choice.choice2\", \"Choice 2\");\n AddChoice(\"choice.choice3\", \"Choice 3\");\n AddParameter(ParameterType_Float, \"choice.choice1.floatchoice1\", \"Float of choice1\");\n SetDefaultParameterFloat(\"choice.choice1.floatchoice1\", 0.125);\n AddParameter(ParameterType_Float, \"choice.choice3.floatchoice3\", \"Float of choice3\");\n SetDefaultParameterFloat(\"choice.choice3.floatchoice3\", 5.0);\n\n\n AddParameter(ParameterType_Group, \"ingroup\", \"Input Group\");\n MandatoryOff(\"ingroup\");\n AddParameter(ParameterType_Float, \"ingroup.integer\", \"Integer of Group\");\n AddParameter(ParameterType_Group, \"ingroup.images\", \"Input Images Group\");\n AddParameter(ParameterType_InputImage, \"ingroup.images.inputimage\", \"Input Image\");\n\n AddParameter(ParameterType_Group, \"outgroup\", \"Output Group\");\n AddParameter(ParameterType_OutputImage, \"outgroup.outputimage\", \"Output Image\");\n\n AddParameter(ParameterType_InputImageList, \"il\", \"Input image list\");\n MandatoryOff(\"il\");\n\n AddParameter(ParameterType_ListView, \"cl\", \"Output Image channels\");\n AddChoice(\"cl.choice1\", \"Choice1\");\n AddChoice(\"cl.choice2\", \"Choice2\");\n MandatoryOff(\"cl\");\n\n AddParameter(ParameterType_ComplexInputImage, \"cin\", \"Input Complex Image\");\n AddParameter(ParameterType_ComplexOutputImage, \"cout\", \"Output Complex Image\");\n\n \/\/ Doc example parameter settings\n SetDocExampleParameterValue(\"boolean\", \"true\");\n SetDocExampleParameterValue(\"filename\", \"myFilename.foo\");\n\n SetOfficialDocLink();\n }\n\n void DoUpdateParameters() ITK_OVERRIDE\n {\n \/\/std::cout << \"TestApplication::DoUpdateParameters\" << std::endl;\n }\n\n void DoExecute() ITK_OVERRIDE\n {\n FloatVectorImageListType* imgList = GetParameterImageList(\"il\");\n SetParameterOutputImage(\"outgroup.outputimage\", imgList->GetNthElement(0));\n SetParameterComplexOutputImage(\"cout\", GetParameterComplexImage(\"cin\"));\n \/\/std::cout << \"TestApplication::DoExecute\" << std::endl;\n }\n};\n}\n}\n\nOTB_APPLICATION_EXPORT(otb::Wrapper::TestApplication)\n<commit_msg>ENH: Added Input filename list parameter to Test-App.<commit_after>\/*\n * Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES)\n *\n * This file is part of Orfeo Toolbox\n *\n * https:\/\/www.orfeo-toolbox.org\/\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"otbWrapperApplication.h\"\n#include \"otbWrapperApplicationFactory.h\"\n\nnamespace otb\n{\nnamespace Wrapper\n{\n\nclass TestApplication : public Application\n{\npublic:\n \/** Standard class typedefs. *\/\n typedef TestApplication Self;\n typedef Application Superclass;\n typedef itk::SmartPointer<Self> Pointer;\n typedef itk::SmartPointer<const Self> ConstPointer;\n\n \/** Standard macro *\/\n itkNewMacro(Self);\n\n itkTypeMacro(TestApplication, otb::Application);\n\nprivate:\n void DoInit() ITK_OVERRIDE\n {\n SetName(\"TestApplication\");\n SetDescription(\"This application helps developers to test parameters types\");\n\n\n SetDocName(\"Test\");\n SetDocLongDescription(\"The purpose of this application is to test parameters types.\");\n SetDocLimitations(\"None\");\n SetDocAuthors(\"OTB-Team\");\n SetDocSeeAlso(\" \");\n\n AddDocTag(\"Test\");\n\n \/\/std::cout << \"TestApplication::DoInit\" << std::endl;\n AddParameter(ParameterType_Empty, \"boolean\", \"Boolean\");\n AddParameter(ParameterType_Int, \"int\", \"Integer\");\n MandatoryOff(\"int\");\n AddParameter(ParameterType_Float, \"float\", \"Float\");\n MandatoryOff(\"float\");\n AddParameter(ParameterType_String, \"string\", \"String\");\n AddParameter(ParameterType_InputFilename, \"filename\", \"File name\");\n AddParameter(ParameterType_OutputFilename, \"outfilename\", \"Output Filename\");\n AddParameter(ParameterType_Directory, \"directory\", \"Directory name\");\n\n\n AddParameter(ParameterType_Choice, \"choice\", \"Choice\");\n AddChoice(\"choice.choice1\", \"Choice 1\");\n AddChoice(\"choice.choice2\", \"Choice 2\");\n AddChoice(\"choice.choice3\", \"Choice 3\");\n AddParameter(ParameterType_Float, \"choice.choice1.floatchoice1\", \"Float of choice1\");\n SetDefaultParameterFloat(\"choice.choice1.floatchoice1\", 0.125);\n AddParameter(ParameterType_Float, \"choice.choice3.floatchoice3\", \"Float of choice3\");\n SetDefaultParameterFloat(\"choice.choice3.floatchoice3\", 5.0);\n\n\n AddParameter(ParameterType_Group, \"ingroup\", \"Input Group\");\n MandatoryOff(\"ingroup\");\n AddParameter(ParameterType_Float, \"ingroup.integer\", \"Integer of Group\");\n AddParameter(ParameterType_Group, \"ingroup.images\", \"Input Images Group\");\n AddParameter(ParameterType_InputImage, \"ingroup.images.inputimage\", \"Input Image\");\n\n AddParameter(ParameterType_Group, \"outgroup\", \"Output Group\");\n AddParameter(ParameterType_OutputImage, \"outgroup.outputimage\", \"Output Image\");\n\n AddParameter(ParameterType_InputImageList, \"il\", \"Input image list\");\n MandatoryOff(\"il\");\n\n AddParameter( ParameterType_InputFilenameList, \"fl\", \"Input filename list\" );\n MandatoryOff( \"fl\" );\n\n AddParameter(ParameterType_ListView, \"cl\", \"Output Image channels\");\n AddChoice(\"cl.choice1\", \"Choice1\");\n AddChoice(\"cl.choice2\", \"Choice2\");\n MandatoryOff(\"cl\");\n\n AddParameter(ParameterType_ComplexInputImage, \"cin\", \"Input Complex Image\");\n AddParameter(ParameterType_ComplexOutputImage, \"cout\", \"Output Complex Image\");\n\n \/\/ Doc example parameter settings\n SetDocExampleParameterValue(\"boolean\", \"true\");\n SetDocExampleParameterValue(\"filename\", \"myFilename.foo\");\n\n SetOfficialDocLink();\n }\n\n void DoUpdateParameters() ITK_OVERRIDE\n {\n \/\/std::cout << \"TestApplication::DoUpdateParameters\" << std::endl;\n }\n\n void DoExecute() ITK_OVERRIDE\n {\n FloatVectorImageListType* imgList = GetParameterImageList(\"il\");\n SetParameterOutputImage(\"outgroup.outputimage\", imgList->GetNthElement(0));\n SetParameterComplexOutputImage(\"cout\", GetParameterComplexImage(\"cin\"));\n \/\/std::cout << \"TestApplication::DoExecute\" << std::endl;\n }\n};\n}\n}\n\nOTB_APPLICATION_EXPORT(otb::Wrapper::TestApplication)\n<|endoftext|>"} {"text":"<commit_before>\/*\n This file is part of Akonadi.\n\n Copyright (c) 2006 Cornelius Schumacher <schumacher@kde.org>\n\n This program is free software; you can redistribute it and\/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation; either version 2 of the License, or\n (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with this program; if not, write to the Free Software\n Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,\n USA.\n*\/\n\n#include \"dataprovider.h\"\n\n#include \"agendamodel.h\"\n#include \"contactmodel.h\"\n#include \"dummymodel.h\"\n\n#include <libakonadi\/jobqueue.h>\n#include <libakonadi\/itemappendjob.h>\n#include <libakonadi\/messagefetchjob.h>\n\n#include <libkcal\/calendarlocal.h>\n#include <libkcal\/icalformat.h>\n\n#include <kmessagebox.h>\n#include <klocale.h>\n\n#include <QDebug>\n\nDataProvider::DataProvider()\n : mAgendaModel( 0 ), mContactModel( 0 )\n{\n}\n\nvoid DataProvider::setupEventData()\n{\n mAgendaModel = new AgendaModel();\n mModel = mAgendaModel;\n\n addEvent( 2006, 1, 10, 12, 13, \"Eins\" );\n addEvent( 2006, 1, 10, 15, 20, \"Zwei\" );\n addEvent( 2006, 1, 11, 12, 13, \"Drei\" );\n addEvent( 2006, 1, 12, 12, 13, \"Vier\" );\n addEvent( 2006, 1, 11, 8, 13, \"Fuenf\" );\n addEvent( 2006, 1, 20, 11, 13, \"Sechs\" );\n addEvent( 2006, 1, 21, 11, 13, \"Sieben\" );\n addEvent( 2006, 1, 24, 5, 23, \"Acht\" );\n addEvent( 2006, 1, 26, 0, 23, \"Neun\" );\n\n for( int i = 0; i < 23; ++i ) {\n addEvent( 2006, 2, i, i, i+1, \"Event \" + QString( i ) );\n }\n}\n\nvoid DataProvider::addEvent( int year, int month, int day,\n int startHour, int endHour, const QString &title )\n{\n if ( !mAgendaModel ) return;\n\n Event e;\n \n e.start = QDateTime( QDate( year, month, day ), QTime( startHour, 0 ) );\n e.end = QDateTime( QDate( year, month, day ), QTime( endHour, 0 ) );\n e.title = title;\n \n mAgendaModel->addEvent( e );\n}\n\nvoid DataProvider::setupContactData()\n{\n mContactModel = new ContactModel();\n mModel = mContactModel;\n\n addContact( \"Dummy User\", \"dummy@example.com\" );\n addContact( \"Doris Dauerwurst\" );\n addContact( \"Hans Wurst\", \"hw@abc.de\", \"+493012345\" );\n addContact( \"Herr A\" );\n addContact( \"Herr B\" );\n addContact( \"Herr C\" );\n addContact( \"Herr D\" );\n addContact( \"Herr E\" );\n addContact( \"Herr F\" );\n addContact( \"Herr G\" );\n addContact( \"Herr H\" );\n addContact( \"Klara Klossbruehe\", \"kk@abc.de\" );\n addContact( \"Klaas Klever\" );\n addContact( \"Kater Karlo\" );\n addContact( \"Petrosilius Zwackelmann\" );\n addContact( \"Rumplestilzchen\" );\n addContact( \"Sabine Sonnenschein\", \"sonnenschein@sabine.org\" );\n addContact( \"Sebastian Sauertop\", \"sauertopf@sebastian.org\" );\n addContact( \"Xerxes\", \"xerxes@example.com\" );\n addContact( \"Zacharias Zimplerlich\" );\n}\n\nvoid DataProvider::setupDummyData()\n{\n mModel = new DummyModel();\n}\n\nvoid DataProvider::addContact( const QString &name, const QString &email,\n const QString &phone )\n{\n if ( !mContactModel ) return;\n\n Contact c;\n \n c.name = name;\n c.email = email;\n c.phone = phone;\n \n mContactModel->addContact( c );\n}\n\nStripeView::Model *DataProvider::model() const\n{\n return mModel;\n}\n\nvoid DataProvider::loadFile()\n{\n if ( mAgendaModel ) {\n mAgendaModel->clear();\n \n KCal::CalendarLocal cal( \"UTC\" );\n cal.load( \"kagenda.ics\" );\n \n KCal::Event::List events = cal.events();\n foreach( KCal::Event *event, events ) {\n Event e;\n e.title = event->summary();\n e.start = event->dtStart();\n e.end = event->dtEnd();\n \n mAgendaModel->addEvent( e );\n }\n }\n}\n\nvoid DataProvider::saveFile()\n{\n if ( mAgendaModel ) {\n KCal::CalendarLocal cal( \"UTC\" );\n foreach( Event e, mAgendaModel->events() ) {\n KCal::Event *event = new KCal::Event();\n event->setSummary( e.title );\n event->setDtStart( e.start );\n event->setDtEnd( e.end );\n event->setFloats( false );\n cal.addEvent( event );\n }\n cal.save( \"kagenda.ics\" );\n }\n \n if ( mContactModel ) {\n }\n}\n\nvoid DataProvider::loadAkonadi()\n{\n if ( mAgendaModel ) {\n PIM::MessageFetchJob job( \"res2\/foo2\" );\n if ( !job.exec() ) {\n KMessageBox::error( 0, \"Error fetching messages\" );\n } else {\n \n }\n }\n}\n\nvoid DataProvider::saveAkonadi()\n{\n if ( mAgendaModel ) {\n\/\/ PIM::JobQueue jobQueue( this );\n KCal::ICalFormat format;\n foreach( Event e, mAgendaModel->events() ) {\n KCal::Event *event = new KCal::Event();\n event->setSummary( e.title );\n event->setDtStart( e.start );\n event->setDtEnd( e.end );\n event->setFloats( false );\n QString ical = format.toICalString( event );\n ical = \"aaa\";\n PIM::ItemAppendJob *job = new PIM::ItemAppendJob( \"res2\/foo2\", ical.toUtf8(),\n \"text\/calendar\", this );\n if ( !job->exec() ) {\n KMessageBox::error( 0, i18n(\"Error\") );\n }\n\/\/ jobQueue.addJob( job );\n }\n#if 0\n if ( !jobQueue.exec() ) {\n KMessageBox::error( 0, i18n(\"Error saving to Akonadi\") );\n }\n#endif\n }\n}\n\nvoid DataProvider::load()\n{\n loadFile();\n}\n\nvoid DataProvider::save()\n{\n saveFile();\n qDebug() << \"tick\";\n saveAkonadi();\n qDebug() << \"tack\";\n}\n\n#include \"dataprovider.moc\"\n<commit_msg>Write actual iCalendar.<commit_after>\/*\n This file is part of Akonadi.\n\n Copyright (c) 2006 Cornelius Schumacher <schumacher@kde.org>\n\n This program is free software; you can redistribute it and\/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation; either version 2 of the License, or\n (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with this program; if not, write to the Free Software\n Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,\n USA.\n*\/\n\n#include \"dataprovider.h\"\n\n#include \"agendamodel.h\"\n#include \"contactmodel.h\"\n#include \"dummymodel.h\"\n\n#include <libakonadi\/jobqueue.h>\n#include <libakonadi\/itemappendjob.h>\n#include <libakonadi\/messagefetchjob.h>\n\n#include <libkcal\/calendarlocal.h>\n#include <libkcal\/icalformat.h>\n\n#include <kmessagebox.h>\n#include <klocale.h>\n\n#include <QDebug>\n\nDataProvider::DataProvider()\n : mAgendaModel( 0 ), mContactModel( 0 )\n{\n}\n\nvoid DataProvider::setupEventData()\n{\n mAgendaModel = new AgendaModel();\n mModel = mAgendaModel;\n\n addEvent( 2006, 1, 10, 12, 13, \"Eins\" );\n addEvent( 2006, 1, 10, 15, 20, \"Zwei\" );\n addEvent( 2006, 1, 11, 12, 13, \"Drei\" );\n addEvent( 2006, 1, 12, 12, 13, \"Vier\" );\n addEvent( 2006, 1, 11, 8, 13, \"Fuenf\" );\n addEvent( 2006, 1, 20, 11, 13, \"Sechs\" );\n addEvent( 2006, 1, 21, 11, 13, \"Sieben\" );\n addEvent( 2006, 1, 24, 5, 23, \"Acht\" );\n addEvent( 2006, 1, 26, 0, 23, \"Neun\" );\n\n for( int i = 0; i < 23; ++i ) {\n addEvent( 2006, 2, i, i, i+1, \"Event \" + QString( i ) );\n }\n}\n\nvoid DataProvider::addEvent( int year, int month, int day,\n int startHour, int endHour, const QString &title )\n{\n if ( !mAgendaModel ) return;\n\n Event e;\n \n e.start = QDateTime( QDate( year, month, day ), QTime( startHour, 0 ) );\n e.end = QDateTime( QDate( year, month, day ), QTime( endHour, 0 ) );\n e.title = title;\n \n mAgendaModel->addEvent( e );\n}\n\nvoid DataProvider::setupContactData()\n{\n mContactModel = new ContactModel();\n mModel = mContactModel;\n\n addContact( \"Dummy User\", \"dummy@example.com\" );\n addContact( \"Doris Dauerwurst\" );\n addContact( \"Hans Wurst\", \"hw@abc.de\", \"+493012345\" );\n addContact( \"Herr A\" );\n addContact( \"Herr B\" );\n addContact( \"Herr C\" );\n addContact( \"Herr D\" );\n addContact( \"Herr E\" );\n addContact( \"Herr F\" );\n addContact( \"Herr G\" );\n addContact( \"Herr H\" );\n addContact( \"Klara Klossbruehe\", \"kk@abc.de\" );\n addContact( \"Klaas Klever\" );\n addContact( \"Kater Karlo\" );\n addContact( \"Petrosilius Zwackelmann\" );\n addContact( \"Rumplestilzchen\" );\n addContact( \"Sabine Sonnenschein\", \"sonnenschein@sabine.org\" );\n addContact( \"Sebastian Sauertop\", \"sauertopf@sebastian.org\" );\n addContact( \"Xerxes\", \"xerxes@example.com\" );\n addContact( \"Zacharias Zimplerlich\" );\n}\n\nvoid DataProvider::setupDummyData()\n{\n mModel = new DummyModel();\n}\n\nvoid DataProvider::addContact( const QString &name, const QString &email,\n const QString &phone )\n{\n if ( !mContactModel ) return;\n\n Contact c;\n \n c.name = name;\n c.email = email;\n c.phone = phone;\n \n mContactModel->addContact( c );\n}\n\nStripeView::Model *DataProvider::model() const\n{\n return mModel;\n}\n\nvoid DataProvider::loadFile()\n{\n if ( mAgendaModel ) {\n mAgendaModel->clear();\n \n KCal::CalendarLocal cal( \"UTC\" );\n cal.load( \"kagenda.ics\" );\n \n KCal::Event::List events = cal.events();\n foreach( KCal::Event *event, events ) {\n Event e;\n e.title = event->summary();\n e.start = event->dtStart();\n e.end = event->dtEnd();\n \n mAgendaModel->addEvent( e );\n }\n }\n}\n\nvoid DataProvider::saveFile()\n{\n if ( mAgendaModel ) {\n KCal::CalendarLocal cal( \"UTC\" );\n foreach( Event e, mAgendaModel->events() ) {\n KCal::Event *event = new KCal::Event();\n event->setSummary( e.title );\n event->setDtStart( e.start );\n event->setDtEnd( e.end );\n event->setFloats( false );\n cal.addEvent( event );\n }\n cal.save( \"kagenda.ics\" );\n }\n \n if ( mContactModel ) {\n }\n}\n\nvoid DataProvider::loadAkonadi()\n{\n if ( mAgendaModel ) {\n PIM::MessageFetchJob job( \"res2\/foo2\" );\n if ( !job.exec() ) {\n KMessageBox::error( 0, \"Error fetching messages\" );\n } else {\n \n }\n }\n}\n\nvoid DataProvider::saveAkonadi()\n{\n if ( mAgendaModel ) {\n\/\/ PIM::JobQueue jobQueue( this );\n KCal::ICalFormat format;\n foreach( Event e, mAgendaModel->events() ) {\n KCal::Event *event = new KCal::Event();\n event->setSummary( e.title );\n event->setDtStart( e.start );\n event->setDtEnd( e.end );\n event->setFloats( false );\n QString ical = format.toICalString( event );\n PIM::ItemAppendJob *job = new PIM::ItemAppendJob( \"res2\/foo2\", ical.toUtf8(),\n \"text\/calendar\", this );\n if ( !job->exec() ) {\n KMessageBox::error( 0, i18n(\"Error\") );\n }\n\/\/ jobQueue.addJob( job );\n }\n#if 0\n if ( !jobQueue.exec() ) {\n KMessageBox::error( 0, i18n(\"Error saving to Akonadi\") );\n }\n#endif\n }\n}\n\nvoid DataProvider::load()\n{\n loadFile();\n}\n\nvoid DataProvider::save()\n{\n saveFile();\n qDebug() << \"tick\";\n saveAkonadi();\n qDebug() << \"tack\";\n}\n\n#include \"dataprovider.moc\"\n<|endoftext|>"} {"text":"<commit_before>\/* -*- C++ -*-; c-basic-offset: 4; indent-tabs-mode: nil *\/\n\/*\n * Copyright (c) 2020 Cisco Systems, Inc. and others. All rights reserved.\n *\n * This program and the accompanying materials are made available under the\n * terms of the Eclipse Public License v1.0 which accompanies this distribution,\n * and is available at http:\/\/www.eclipse.org\/legal\/epl-v10.html\n *\/\n\n#include \"MockRpcConnection.h\"\n\nnamespace opflexagent {\n\nvoid ResponseDict::init() {\n uint64_t j = 1001;\n for (unsigned int i = 0 ; i < no_of_span_msgs; i++, j++) {\n d[i].GetAllocator().Clear();\n d[i].Parse(response[i].c_str());\n dict.emplace(j, i);\n }\n j = 2001;\n for (unsigned int i = no_of_span_msgs ; i < (no_of_span_msgs + no_of_netflow_msgs); i++, j++) {\n d[i].GetAllocator().Clear();\n d[i].Parse(response[i].c_str());\n dict.emplace(j, i);\n }\n}\n\nResponseDict& ResponseDict::Instance() {\n static ResponseDict inst;\n if (!inst.isInitialized) {\n inst.init();\n inst.isInitialized = true;\n }\n return inst;\n}\n\nvoid MockRpcConnection::sendTransaction(const uint64_t& reqId, const list<JsonRpcTransactMessage>& requests, Transaction* trans) {\n ResponseDict& rDict = ResponseDict::Instance();\n auto itr = rDict.dict.find(reqId);\n if (itr != rDict.dict.end()) {\n trans->handleTransaction(reqId, rDict.d[itr->second]);\n } else {\n LOG(DEBUG) << \"No response found for req \" << reqId;\n }\n}\n\n}<commit_msg>Better mock JSONRPC requests in UT<commit_after>\/* -*- C++ -*-; c-basic-offset: 4; indent-tabs-mode: nil *\/\n\/*\n * Copyright (c) 2020 Cisco Systems, Inc. and others. All rights reserved.\n *\n * This program and the accompanying materials are made available under the\n * terms of the Eclipse Public License v1.0 which accompanies this distribution,\n * and is available at http:\/\/www.eclipse.org\/legal\/epl-v10.html\n *\/\n\n#include \"MockRpcConnection.h\"\n\nnamespace opflexagent {\n\nvoid ResponseDict::init() {\n uint64_t j = 1001;\n for (unsigned int i = 0 ; i < no_of_span_msgs; i++, j++) {\n d[i].GetAllocator().Clear();\n d[i].Parse(response[i].c_str());\n dict.emplace(j, i);\n }\n j = 2001;\n for (unsigned int i = no_of_span_msgs ; i < (no_of_span_msgs + no_of_netflow_msgs); i++, j++) {\n d[i].GetAllocator().Clear();\n d[i].Parse(response[i].c_str());\n dict.emplace(j, i);\n }\n}\n\nResponseDict& ResponseDict::Instance() {\n static ResponseDict inst;\n if (!inst.isInitialized) {\n inst.init();\n inst.isInitialized = true;\n }\n return inst;\n}\n\nvoid MockRpcConnection::sendTransaction(const uint64_t& reqId, const list<JsonRpcTransactMessage>& requests, Transaction* trans) {\n \/\/ prepare request\n std::shared_ptr<TransactReq> transactReq = std::make_shared<TransactReq>(TransactReq(requests, reqId));\n yajr::rpc::MethodName method(transactReq->getMethod().c_str());\n opflex::jsonrpc::PayloadWrapper wrapper(transactReq.get());\n ::yajr::internal::StringQueue sq;\n yajr::rpc::SendHandler sendHandler(sq);\n wrapper(sendHandler);\n\n \/\/ fake the response\n ResponseDict& rDict = ResponseDict::Instance();\n auto itr = rDict.dict.find(reqId);\n if (itr != rDict.dict.end()) {\n trans->handleTransaction(reqId, rDict.d[itr->second]);\n } else {\n LOG(DEBUG) << \"No response found for req \" << reqId;\n }\n}\n\n}<|endoftext|>"} {"text":"<commit_before>\/*\n * Funambol is a mobile platform developed by Funambol, Inc. \n * Copyright (C) 2008 Funambol, Inc.\n * \n * This program is free software; you can redistribute it and\/or modify it under\n * the terms of the GNU Affero General Public License version 3 as published by\n * the Free Software Foundation with the addition of the following permission \n * added to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED\n * WORK IN WHICH THE COPYRIGHT IS OWNED BY FUNAMBOL, FUNAMBOL DISCLAIMS THE \n * WARRANTY OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.\n * \n * This program is distributed in the hope that it will be useful, but WITHOUT\n * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more\n * details.\n * \n * You should have received a copy of the GNU Affero General Public License \n * along with this program; if not, see http:\/\/www.gnu.org\/licenses or write to\n * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,\n * MA 02110-1301 USA.\n * \n * You can contact Funambol, Inc. headquarters at 643 Bair Island Road, Suite \n * 305, Redwood City, CA 94063, USA, or at email address info@funambol.com.\n * \n * The interactive user interfaces in modified source and object code versions\n * of this program must display Appropriate Legal Notices, as required under\n * Section 5 of the GNU Affero General Public License version 3.\n * \n * In accordance with Section 7(b) of the GNU Affero General Public License\n * version 3, these Appropriate Legal Notices must retain the display of the\n * \"Powered by Funambol\" logo. If the display of the logo is not reasonably \n * feasible for technical reasons, the Appropriate Legal Notices must display\n * the words \"Powered by Funambol\".\n *\/\n\n#include \"base\/fscapi.h\"\n#include \"base\/adapter\/PlatformAdapter.h\"\n#include \"base\/util\/StringBuffer.h\"\n#include \"base\/util\/StringMap.h\"\n#include \"base\/Log.h\"\n\nBEGIN_NAMESPACE\n\nStringBuffer PlatformAdapter::appContext(DEFAULT_APP_CONTEXT);\nStringBuffer PlatformAdapter::homeFolder;\nStringBuffer PlatformAdapter::configFolder;\nbool PlatformAdapter::initialized = false;\n\n\/\/ Initializes the platform-dependent parameters of the library.\nvoid PlatformAdapter::init(const char *appcontext) {\n if(!initialized) {\n appContext = appcontext;\n homeFolder = \"\";\n configFolder = \"\";\n }\n else {\n LOG.error(\"PlatformAdapter::init(): already initialized.\");\n }\n}\n\n\/\/ Initializes the platform-dependent parameters of the library.\nvoid PlatformAdapter::init(const char *appcontext, StringMap& env) {\n if(!initialized) {\n appContext = appcontext;\n homeFolder = env[\"HOME_FOLDER\"];\n configFolder = env[\"CONFIG_FOLDER\"];\n }\n else {\n LOG.error(\"PlatformAdapter::init(): already initialized.\");\n }\n}\n\n\/\/ Returns the application context\nconst StringBuffer& PlatformAdapter::getAppContext() {\n return appContext;\n}\n\n\/\/ Returns the home folder, or an empty string on failure.\nconst StringBuffer& PlatformAdapter::getHomeFolder() {\n if (homeFolder.empty()) {\n LOG.error(\"PlatformAdapter::getHomeFolder: to be implemented\");\n }\n return homeFolder;\n}\n\n\/\/ Returns the home folder, or an empty string on failure.\nconst StringBuffer& PlatformAdapter::getConfigFolder() {\n if (configFolder.empty()){\n LOG.error(\"PlatformAdapter::getConfigFolder: to be implemented\");\n }\n return configFolder;\n}\n\nEND_NAMESPACE\n\n<commit_msg>getHomeFolder()\/getConfigFolder() implementation added<commit_after>\/*\n * Funambol is a mobile platform developed by Funambol, Inc. \n * Copyright (C) 2008 Funambol, Inc.\n * \n * This program is free software; you can redistribute it and\/or modify it under\n * the terms of the GNU Affero General Public License version 3 as published by\n * the Free Software Foundation with the addition of the following permission \n * added to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED\n * WORK IN WHICH THE COPYRIGHT IS OWNED BY FUNAMBOL, FUNAMBOL DISCLAIMS THE \n * WARRANTY OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.\n * \n * This program is distributed in the hope that it will be useful, but WITHOUT\n * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more\n * details.\n * \n * You should have received a copy of the GNU Affero General Public License \n * along with this program; if not, see http:\/\/www.gnu.org\/licenses or write to\n * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,\n * MA 02110-1301 USA.\n * \n * You can contact Funambol, Inc. headquarters at 643 Bair Island Road, Suite \n * 305, Redwood City, CA 94063, USA, or at email address info@funambol.com.\n * \n * The interactive user interfaces in modified source and object code versions\n * of this program must display Appropriate Legal Notices, as required under\n * Section 5 of the GNU Affero General Public License version 3.\n * \n * In accordance with Section 7(b) of the GNU Affero General Public License\n * version 3, these Appropriate Legal Notices must retain the display of the\n * \"Powered by Funambol\" logo. If the display of the logo is not reasonably \n * feasible for technical reasons, the Appropriate Legal Notices must display\n * the words \"Powered by Funambol\".\n *\/\n\n#include \"base\/fscapi.h\"\n#include \"base\/adapter\/PlatformAdapter.h\"\n#include \"base\/util\/StringBuffer.h\"\n#include \"base\/util\/StringMap.h\"\n#include \"base\/util\/stringUtils.h\"\n#include \"base\/Log.h\"\n\n\/\/ include CEikonEnv framework for CEikonEnv::Static()\n#include <eikapp.h> \n#include <eikappui.h> \n#include <eikenv.h>\n\nBEGIN_NAMESPACE\n\nStringBuffer PlatformAdapter::appContext(DEFAULT_APP_CONTEXT);\nStringBuffer PlatformAdapter::homeFolder;\nStringBuffer PlatformAdapter::configFolder;\nbool PlatformAdapter::initialized = false;\n\n\/\/ Initializes the platform-dependent parameters of the library.\nvoid PlatformAdapter::init(const char *appcontext) {\n if(!initialized) {\n appContext = appcontext;\n homeFolder = \"\";\n configFolder = \"\";\n initialized = true;\n }\n else {\n LOG.error(\"PlatformAdapter::init(): already initialized.\");\n }\n}\n\n\/\/ Initializes the platform-dependent parameters of the library.\nvoid PlatformAdapter::init(const char *appcontext, StringMap& env) {\n if(!initialized) {\n appContext = appcontext;\n homeFolder = env[\"HOME_FOLDER\"];\n configFolder = env[\"CONFIG_FOLDER\"];\n initialized = true;\n }\n else {\n LOG.error(\"PlatformAdapter::init(): already initialized.\");\n }\n}\n\n\/\/ Returns the application context\nconst StringBuffer& PlatformAdapter::getAppContext() {\n return appContext;\n}\n\n\/\/ Returns the home folder. On Symbian platform home folder is \n\/\/ the application private folder \nconst StringBuffer& PlatformAdapter::getHomeFolder() {\n if (homeFolder.empty()) {\n TFileName appFullName = CEikonEnv::Static()->EikAppUi()->Application()->AppFullName();\n TParsePtr parse1(appFullName);\n TPtrC currentDrive = parse1.Drive();\n\t\t\n \/\/ Get ONLY the private path (e.g. \"\\private\\2001BBA4\")\n TBuf<KMaxPath> privatePath;\n CEikonEnv::Static()->FsSession().PrivatePath(privatePath);\n TParsePtr parse2(privatePath);\n TPtrC currentPath = parse2.Path();\n\n StringBuffer drive = bufToStringBuffer(currentDrive);\n homeFolder.append(drive);\n StringBuffer path = bufToStringBuffer(currentPath);\n homeFolder.append(path);\n }\n\n return homeFolder;\n}\n\n\/\/ Returns the config folder (on Symbian platform is the same as home folder)\nconst StringBuffer& PlatformAdapter::getConfigFolder() {\n return getHomeFolder();\n}\n\nEND_NAMESPACE\n\n<|endoftext|>"} {"text":"<commit_before>\/*! \\file MatTools.cpp\n \\brief Implements the MatTools class used by the Generic Repository \n \\author Kathryn D. Huff\n *\/\n#include <iostream>\n#include <fstream>\n#include <deque>\n#include <time.h>\n#include <assert.h>\n\n\n#include \"CycException.h\"\n#include \"Logger.h\"\n#include \"Timer.h\"\n#include \"MatTools.h\"\n#include \"Material.h\"\n\nusing namespace std;\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \npair<IsoVector, double> MatTools::sum_mats(deque<mat_rsrc_ptr> mats){\n IsoVector vec;\n CompMapPtr sum_comp = CompMapPtr(new CompMap(MASS));\n double kg = 0;\n\n if( !mats.empty() ){ \n CompMapPtr comp_to_add;\n deque<mat_rsrc_ptr>::iterator mat;\n int iso;\n CompMap::const_iterator comp;\n\n for(mat = mats.begin(); mat != mats.end(); ++mat){ \n kg += (*mat)->mass(MassUnit(KG));\n comp_to_add = (*mat)->isoVector().comp();\n comp_to_add->massify();\n for(comp = (*comp_to_add).begin(); comp != (*comp_to_add).end(); ++comp) {\n iso = comp->first;\n if(sum_comp->count(iso)!=0) {\n (*sum_comp)[iso] = (*sum_comp)[iso] + (comp->second)*kg;\n } else { \n (*sum_comp)[iso] = (comp->second)*kg;\n }\n }\n }\n } else {\n (*sum_comp)[92235] = 0;\n }\n vec = IsoVector(sum_comp);\n return make_pair(vec, kg);\n}\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \nmat_rsrc_ptr MatTools::extract(const CompMapPtr comp_to_rem, double kg_to_rem, deque<mat_rsrc_ptr>& mat_list){\n mat_rsrc_ptr left_over = mat_rsrc_ptr(new Material(comp_to_rem));\n left_over->setQuantity(0);\n while(!mat_list.empty()) { \n left_over->absorb(mat_list.back());\n mat_list.pop_back();\n }\n mat_rsrc_ptr to_ret = left_over->extract(comp_to_rem, kg_to_rem);\n if(left_over->mass(KG)>EPS_KG){ \n mat_list.push_back(left_over);\n }\n return to_ret;\n}\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \nIsoConcMap MatTools::comp_to_conc_map(CompMapPtr comp, double mass, double vol){\n MatTools::validate_finite_pos(vol);\n MatTools::validate_finite_pos(mass);\n\n IsoConcMap to_ret;\n int iso;\n double m_iso;\n CompMap::const_iterator it;\n it=(*comp).begin();\n while(it!= (*comp).end() ){\n iso = (*it).first;\n m_iso=((*it).second)*mass;\n to_ret.insert(make_pair(iso, m_iso\/vol));\n ++it;\n } \n return to_ret;\n}\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \npair<CompMapPtr, double> MatTools::conc_to_comp_map(IsoConcMap conc, double vol){\n MatTools::validate_finite_pos(vol);\n\n CompMapPtr comp = CompMapPtr(new CompMap(MASS));\n double mass(0);\n int iso;\n double c_iso;\n double m_iso;\n CompMap::const_iterator it;\n it=conc.begin();\n while(it!= conc.end() ){\n iso = (*it).first;\n c_iso=((*it).second);\n m_iso = c_iso*vol;\n (*comp)[iso] = m_iso;\n mass+=m_iso;\n ++it;\n } \n (*comp).normalize();\n pair<CompMapPtr, double> to_ret = make_pair(comp, mass);\n return to_ret;\n}\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ndouble MatTools::V_f(double V_T, double theta){\n validate_percent(theta);\n validate_finite_pos(V_T);\n return theta*V_T;\n}\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ndouble MatTools::V_ff(double V_T, double theta, double d){\n validate_percent(d);\n return d*V_f(V_T, theta);\n}\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ndouble MatTools::V_mf(double V_T, double theta, double d){\n return (V_f(V_T,theta) - V_ff(V_T, theta, d));\n}\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ndouble MatTools::V_s(double V_T, double theta){\n return (V_T - V_f(V_T, theta));\n}\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ndouble MatTools::V_ds(double V_T, double theta, double d){\n validate_percent(d);\n return d*V_s(V_T, theta);\n}\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ndouble MatTools::V_ms(double V_T, double theta, double d){\n return (V_s(V_T, theta) - V_ds(V_T, theta, d));\n}\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \nvoid MatTools::validate_percent(double per){\n if( per <= 1 && per >= 0 ){\n return;\n } else if ( per < 0) {\n throw CycRangeException(\"The value is not a valid percent. It is less than zero.\");\n } else if ( per > 1) {\n throw CycRangeException(\"The value is not a valid percent. It is greater than one.\");\n }\n}\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \nvoid MatTools::validate_finite_pos(double pos){\n if( pos >= 0 ){\n return;\n } else if ( pos < 0) {\n throw CycRangeException(\"The value is not positive and finite. It is less than zero.\");\n } else if ( pos >= numeric_limits<double>::infinity() ) {\n throw CycRangeException(\"The value is not positive and finite. It is greater than infty.\");\n }\n\n}\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \nIsoConcMap MatTools::scaleConcMap(IsoConcMap C_0, double scalar){\n double orig;\n IsoConcMap::iterator it;\n for(it = C_0.begin(); it != C_0.end(); ++it) { \n orig = C_0[(*it).first];\n C_0[(*it).first] = orig*scalar;\n }\n return C_0;\n}\n<commit_msg> used eps_rsrc from cyclus (thanks for the hint, @gidden)<commit_after>\/*! \\file MatTools.cpp\n \\brief Implements the MatTools class used by the Generic Repository \n \\author Kathryn D. Huff\n *\/\n#include <iostream>\n#include <fstream>\n#include <deque>\n#include <time.h>\n#include <assert.h>\n\n\n#include \"CycException.h\"\n#include \"CycLimits.h\"\n#include \"MatTools.h\"\n#include \"Material.h\"\n#include \"Logger.h\"\n#include \"Timer.h\"\n\nusing namespace std;\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \npair<IsoVector, double> MatTools::sum_mats(deque<mat_rsrc_ptr> mats){\n IsoVector vec;\n CompMapPtr sum_comp = CompMapPtr(new CompMap(MASS));\n double kg = 0;\n\n if( !mats.empty() ){ \n CompMapPtr comp_to_add;\n deque<mat_rsrc_ptr>::iterator mat;\n int iso;\n CompMap::const_iterator comp;\n\n for(mat = mats.begin(); mat != mats.end(); ++mat){ \n kg += (*mat)->mass(MassUnit(KG));\n comp_to_add = (*mat)->isoVector().comp();\n comp_to_add->massify();\n for(comp = (*comp_to_add).begin(); comp != (*comp_to_add).end(); ++comp) {\n iso = comp->first;\n if(sum_comp->count(iso)!=0) {\n (*sum_comp)[iso] = (*sum_comp)[iso] + (comp->second)*kg;\n } else { \n (*sum_comp)[iso] = (comp->second)*kg;\n }\n }\n }\n } else {\n (*sum_comp)[92235] = 0;\n }\n vec = IsoVector(sum_comp);\n return make_pair(vec, kg);\n}\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \nmat_rsrc_ptr MatTools::extract(const CompMapPtr comp_to_rem, double kg_to_rem, deque<mat_rsrc_ptr>& mat_list){\n mat_rsrc_ptr left_over = mat_rsrc_ptr(new Material(comp_to_rem));\n left_over->setQuantity(0);\n while(!mat_list.empty()) { \n left_over->absorb(mat_list.back());\n mat_list.pop_back();\n }\n mat_rsrc_ptr to_ret = left_over->extract(comp_to_rem, kg_to_rem);\n if(left_over->mass(KG) > cyclus::eps_rsrc()){ \n mat_list.push_back(left_over);\n }\n return to_ret;\n}\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \nIsoConcMap MatTools::comp_to_conc_map(CompMapPtr comp, double mass, double vol){\n MatTools::validate_finite_pos(vol);\n MatTools::validate_finite_pos(mass);\n\n IsoConcMap to_ret;\n int iso;\n double m_iso;\n CompMap::const_iterator it;\n it=(*comp).begin();\n while(it!= (*comp).end() ){\n iso = (*it).first;\n m_iso=((*it).second)*mass;\n to_ret.insert(make_pair(iso, m_iso\/vol));\n ++it;\n } \n return to_ret;\n}\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \npair<CompMapPtr, double> MatTools::conc_to_comp_map(IsoConcMap conc, double vol){\n MatTools::validate_finite_pos(vol);\n\n CompMapPtr comp = CompMapPtr(new CompMap(MASS));\n double mass(0);\n int iso;\n double c_iso;\n double m_iso;\n CompMap::const_iterator it;\n it=conc.begin();\n while(it!= conc.end() ){\n iso = (*it).first;\n c_iso=((*it).second);\n m_iso = c_iso*vol;\n (*comp)[iso] = m_iso;\n mass+=m_iso;\n ++it;\n } \n (*comp).normalize();\n pair<CompMapPtr, double> to_ret = make_pair(comp, mass);\n return to_ret;\n}\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ndouble MatTools::V_f(double V_T, double theta){\n validate_percent(theta);\n validate_finite_pos(V_T);\n return theta*V_T;\n}\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ndouble MatTools::V_ff(double V_T, double theta, double d){\n validate_percent(d);\n return d*V_f(V_T, theta);\n}\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ndouble MatTools::V_mf(double V_T, double theta, double d){\n return (V_f(V_T,theta) - V_ff(V_T, theta, d));\n}\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ndouble MatTools::V_s(double V_T, double theta){\n return (V_T - V_f(V_T, theta));\n}\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ndouble MatTools::V_ds(double V_T, double theta, double d){\n validate_percent(d);\n return d*V_s(V_T, theta);\n}\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ndouble MatTools::V_ms(double V_T, double theta, double d){\n return (V_s(V_T, theta) - V_ds(V_T, theta, d));\n}\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \nvoid MatTools::validate_percent(double per){\n if( per <= 1 && per >= 0 ){\n return;\n } else if ( per < 0) {\n throw CycRangeException(\"The value is not a valid percent. It is less than zero.\");\n } else if ( per > 1) {\n throw CycRangeException(\"The value is not a valid percent. It is greater than one.\");\n }\n}\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \nvoid MatTools::validate_finite_pos(double pos){\n if( pos >= 0 ){\n return;\n } else if ( pos < 0) {\n throw CycRangeException(\"The value is not positive and finite. It is less than zero.\");\n } else if ( pos >= numeric_limits<double>::infinity() ) {\n throw CycRangeException(\"The value is not positive and finite. It is greater than infty.\");\n }\n\n}\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \nIsoConcMap MatTools::scaleConcMap(IsoConcMap C_0, double scalar){\n double orig;\n IsoConcMap::iterator it;\n for(it = C_0.begin(); it != C_0.end(); ++it) { \n orig = C_0[(*it).first];\n C_0[(*it).first] = orig*scalar;\n }\n return C_0;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"Types.hpp\"\n#include \"BufferFormat.hpp\"\n\n#include \"GLContext.hpp\"\n\nPyObject * strsize(PyObject * self, PyObject * args) {\n\tconst char * str;\n\n\tint args_ok = PyArg_ParseTuple(\n\t\targs,\n\t\t\"s\",\n\t\t&str\n\t);\n\n\tif (!args_ok) {\n\t\treturn 0;\n\t}\n\n\tchar first_chr = *str++;\n\tif (first_chr < '1' || first_chr > '9') {\n\t\treturn 0;\n\t}\n\n\tlong long value = first_chr - '0';\n\n\twhile (char chr = *str++) {\n\t\tif (chr < '0' || chr > '9') {\n\t\t\tswitch (chr) {\n\t\t\t\tcase 'G':\n\t\t\t\t\tvalue *= 1024;\n\n\t\t\t\tcase 'M':\n\t\t\t\t\tvalue *= 1024;\n\n\t\t\t\tcase 'K':\n\t\t\t\t\tvalue *= 1024;\n\n\t\t\t\t\tif (*str++ != 'B') {\n\t\t\t\t\t\treturn 0;\n\t\t\t\t\t}\n\n\t\t\t\tcase 'B':\n\t\t\t\t\tif (*str++) {\n\t\t\t\t\t\treturn 0;\n\t\t\t\t\t}\n\n\t\t\t\tcase 0:\n\t\t\t\t\tbreak;\n\n\t\t\t\tdefault:\n\t\t\t\t\treturn 0;\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\n\t\tvalue = value * 10 + chr - '0';\n\t}\n\n\treturn PyLong_FromLongLong(value);\n}\n\nPyObject * fmtdebug(PyObject * self, PyObject * args) {\n\tconst char * str;\n\n\tint args_ok = PyArg_ParseTuple(\n\t\targs,\n\t\t\"s\",\n\t\t&str\n\t);\n\n\tFormatIterator it = FormatIterator(str);\n\tFormatInfo format_info = it.info();\n\n\tPyObject * nodes = PyList_New(0);\n\n\tif (format_info.valid) {\n\t\twhile (FormatNode * node = it.next()) {\n\t\t\tPyObject * obj = PyTuple_New(4);\n\t\t\tPyTuple_SET_ITEM(obj, 0, PyLong_FromLong(node->size));\n\t\t\tPyTuple_SET_ITEM(obj, 1, PyLong_FromLong(node->count));\n\t\t\tPyTuple_SET_ITEM(obj, 2, PyLong_FromLong(node->type));\n\t\t\tPyTuple_SET_ITEM(obj, 3, PyBool_FromLong(node->normalize));\n\t\t\tPyList_Append(nodes, obj);\n\t\t}\n\t}\n\n\tPyObject * res = PyTuple_New(5);\n\tPyTuple_SET_ITEM(res, 0, PyLong_FromLong(format_info.size));\n\tPyTuple_SET_ITEM(res, 1, PyLong_FromLong(format_info.nodes));\n\tPyTuple_SET_ITEM(res, 2, PyLong_FromLong(format_info.divisor));\n\tPyTuple_SET_ITEM(res, 3, PyBool_FromLong(format_info.valid));\n\tPyTuple_SET_ITEM(res, 4, PyList_AsTuple(nodes));\n\tPy_DECREF(nodes);\n\treturn res;\n}\n\nPyObject * set_error_class(PyObject * self, PyObject * args) {\n\tPyObject * error_class;\n\n\tint args_ok = PyArg_ParseTuple(\n\t\targs,\n\t\t\"O\",\n\t\t&error_class\n\t);\n\n\tif (!args_ok) {\n\t\treturn 0;\n\t}\n\n\tPy_INCREF(error_class);\n\tMGLError_TypePtr = error_class;\n\tPy_RETURN_NONE;\n}\n\nPyObject * create_standalone_context(PyObject * self, PyObject * args) {\n\tPyObject * settings;\n\n\tint args_ok = PyArg_ParseTuple(\n\t\targs,\n\t\t\"O\",\n\t\t&settings\n\t);\n\n\tif (!args_ok) {\n\t\treturn 0;\n\t}\n\n\tMGLContext * ctx = (MGLContext *)MGLContext_Type.tp_alloc(&MGLContext_Type, 0);\n\n\tctx->gl_context = CreateGLContext(settings);\n\tctx->wireframe = false;\n\n\tif (PyErr_Occurred()) {\n\t\treturn 0;\n\t}\n\n\tMGLContext_Initialize(ctx);\n\n\tif (PyErr_Occurred()) {\n\t\treturn 0;\n\t}\n\n\tPy_INCREF(ctx);\n\n\tPyObject * result = PyTuple_New(2);\n\tPyTuple_SET_ITEM(result, 0, (PyObject *)ctx);\n\tPyTuple_SET_ITEM(result, 1, PyLong_FromLong(ctx->version_code));\n\treturn result;\n}\n\nPyObject * create_context(PyObject * self) {\n\tMGLContext * ctx = (MGLContext *)MGLContext_Type.tp_alloc(&MGLContext_Type, 0);\n\n\tctx->gl_context = LoadCurrentGLContext();\n\tctx->wireframe = false;\n\n\tif (PyErr_Occurred()) {\n\t\treturn 0;\n\t}\n\n\tMGLContext_Initialize(ctx);\n\n\tif (PyErr_Occurred()) {\n\t\treturn 0;\n\t}\n\n\tPy_INCREF(ctx);\n\n\tPyObject * result = PyTuple_New(2);\n\tPyTuple_SET_ITEM(result, 0, (PyObject *)ctx);\n\tPyTuple_SET_ITEM(result, 1, PyLong_FromLong(ctx->version_code));\n\treturn result;\n}\n\nPyMethodDef MGL_module_methods[] = {\n\t{\"strsize\", (PyCFunction)strsize, METH_VARARGS, 0},\n\t{\"create_standalone_context\", (PyCFunction)create_standalone_context, METH_VARARGS, 0},\n\t{\"create_context\", (PyCFunction)create_context, METH_NOARGS, 0},\n\t{\"set_error_class\", (PyCFunction)set_error_class, METH_VARARGS, 0},\n\t{\"fmtdebug\", (PyCFunction)fmtdebug, METH_VARARGS, 0},\n\t{0},\n};\n\nbool MGL_InitializeModule(PyObject * module) {\n\t{\n\t\tif (PyType_Ready(&MGLAttribute_Type) < 0) {\n\t\t\tPyErr_Format(PyExc_ImportError, \"Cannot register Attribute in %s (%s:%d)\", __FUNCTION__, __FILE__, __LINE__);\n\t\t\treturn false;\n\t\t}\n\n\t\tPy_INCREF(&MGLAttribute_Type);\n\n\t\tPyModule_AddObject(module, \"Attribute\", (PyObject *)&MGLAttribute_Type);\n\t}\n\n\t{\n\t\tif (PyType_Ready(&MGLBuffer_Type) < 0) {\n\t\t\tPyErr_Format(PyExc_ImportError, \"Cannot register Buffer in %s (%s:%d)\", __FUNCTION__, __FILE__, __LINE__);\n\t\t\treturn false;\n\t\t}\n\n\t\tPy_INCREF(&MGLBuffer_Type);\n\n\t\tPyModule_AddObject(module, \"Buffer\", (PyObject *)&MGLBuffer_Type);\n\t}\n\n\t{\n\t\tif (PyType_Ready(&MGLComputeShader_Type) < 0) {\n\t\t\tPyErr_Format(PyExc_ImportError, \"Cannot register ComputeShader in %s (%s:%d)\", __FUNCTION__, __FILE__, __LINE__);\n\t\t\treturn false;\n\t\t}\n\n\t\tPy_INCREF(&MGLComputeShader_Type);\n\n\t\tPyModule_AddObject(module, \"ComputeShader\", (PyObject *)&MGLComputeShader_Type);\n\t}\n\n\t{\n\t\tif (PyType_Ready(&MGLContext_Type) < 0) {\n\t\t\tPyErr_Format(PyExc_ImportError, \"Cannot register Context in %s (%s:%d)\", __FUNCTION__, __FILE__, __LINE__);\n\t\t\treturn false;\n\t\t}\n\n\t\tPy_INCREF(&MGLContext_Type);\n\n\t\tPyModule_AddObject(module, \"Context\", (PyObject *)&MGLContext_Type);\n\t}\n\n\t{\n\t\tif (PyType_Ready(&MGLFramebuffer_Type) < 0) {\n\t\t\tPyErr_Format(PyExc_ImportError, \"Cannot register Framebuffer in %s (%s:%d)\", __FUNCTION__, __FILE__, __LINE__);\n\t\t\treturn false;\n\t\t}\n\n\t\tPy_INCREF(&MGLFramebuffer_Type);\n\n\t\tPyModule_AddObject(module, \"Framebuffer\", (PyObject *)&MGLFramebuffer_Type);\n\t}\n\n\t{\n\t\tif (PyType_Ready(&MGLInvalidObject_Type) < 0) {\n\t\t\tPyErr_Format(PyExc_ImportError, \"Cannot register InvalidObject in %s (%s:%d)\", __FUNCTION__, __FILE__, __LINE__);\n\t\t\treturn false;\n\t\t}\n\n\t\tPy_INCREF(&MGLInvalidObject_Type);\n\n\t\tPyModule_AddObject(module, \"InvalidObject\", (PyObject *)&MGLInvalidObject_Type);\n\t}\n\n\t{\n\t\tif (PyType_Ready(&MGLProgram_Type) < 0) {\n\t\t\tPyErr_Format(PyExc_ImportError, \"Cannot register Program in %s (%s:%d)\", __FUNCTION__, __FILE__, __LINE__);\n\t\t\treturn false;\n\t\t}\n\n\t\tPy_INCREF(&MGLProgram_Type);\n\n\t\tPyModule_AddObject(module, \"Program\", (PyObject *)&MGLProgram_Type);\n\t}\n\n\t{\n\t\tif (PyType_Ready(&MGLQuery_Type) < 0) {\n\t\t\tPyErr_Format(PyExc_ImportError, \"Cannot register Query in %s (%s:%d)\", __FUNCTION__, __FILE__, __LINE__);\n\t\t\treturn false;\n\t\t}\n\n\t\tPy_INCREF(&MGLQuery_Type);\n\n\t\tPyModule_AddObject(module, \"Query\", (PyObject *)&MGLQuery_Type);\n\t}\n\n\t{\n\t\tif (PyType_Ready(&MGLRenderbuffer_Type) < 0) {\n\t\t\tPyErr_Format(PyExc_ImportError, \"Cannot register Renderbuffer in %s (%s:%d)\", __FUNCTION__, __FILE__, __LINE__);\n\t\t\treturn false;\n\t\t}\n\n\t\tPy_INCREF(&MGLRenderbuffer_Type);\n\n\t\tPyModule_AddObject(module, \"Renderbuffer\", (PyObject *)&MGLRenderbuffer_Type);\n\t}\n\n\t{\n\t\tif (PyType_Ready(&MGLScope_Type) < 0) {\n\t\t\tPyErr_Format(PyExc_ImportError, \"Cannot register Scope in %s (%s:%d)\", __FUNCTION__, __FILE__, __LINE__);\n\t\t\treturn false;\n\t\t}\n\n\t\tPy_INCREF(&MGLScope_Type);\n\n\t\tPyModule_AddObject(module, \"Scope\", (PyObject *)&MGLScope_Type);\n\t}\n\n\t{\n\t\tif (PyType_Ready(&MGLTexture_Type) < 0) {\n\t\t\tPyErr_Format(PyExc_ImportError, \"Cannot register Texture in %s (%s:%d)\", __FUNCTION__, __FILE__, __LINE__);\n\t\t\treturn false;\n\t\t}\n\n\t\tPy_INCREF(&MGLTexture_Type);\n\n\t\tPyModule_AddObject(module, \"Texture\", (PyObject *)&MGLTexture_Type);\n\t}\n\n\t{\n\t\tif (PyType_Ready(&MGLTextureCube_Type) < 0) {\n\t\t\tPyErr_Format(PyExc_ImportError, \"Cannot register TextureCube in %s (%s:%d)\", __FUNCTION__, __FILE__, __LINE__);\n\t\t\treturn false;\n\t\t}\n\n\t\tPy_INCREF(&MGLTextureCube_Type);\n\n\t\tPyModule_AddObject(module, \"TextureCube\", (PyObject *)&MGLTextureCube_Type);\n\t}\n\n\t{\n\t\tif (PyType_Ready(&MGLTexture3D_Type) < 0) {\n\t\t\tPyErr_Format(PyExc_ImportError, \"Cannot register Texture3D in %s (%s:%d)\", __FUNCTION__, __FILE__, __LINE__);\n\t\t\treturn false;\n\t\t}\n\n\t\tPy_INCREF(&MGLTexture3D_Type);\n\n\t\tPyModule_AddObject(module, \"Texture3D\", (PyObject *)&MGLTexture3D_Type);\n\t}\n\n\t{\n\t\tif (PyType_Ready(&MGLUniform_Type) < 0) {\n\t\t\tPyErr_Format(PyExc_ImportError, \"Cannot register Uniform in %s (%s:%d)\", __FUNCTION__, __FILE__, __LINE__);\n\t\t\treturn false;\n\t\t}\n\n\t\tPy_INCREF(&MGLUniform_Type);\n\n\t\tPyModule_AddObject(module, \"Uniform\", (PyObject *)&MGLUniform_Type);\n\t}\n\n\t{\n\t\tif (PyType_Ready(&MGLUniformBlock_Type) < 0) {\n\t\t\tPyErr_Format(PyExc_ImportError, \"Cannot register UniformBlock in %s (%s:%d)\", __FUNCTION__, __FILE__, __LINE__);\n\t\t\treturn false;\n\t\t}\n\n\t\tPy_INCREF(&MGLUniformBlock_Type);\n\n\t\tPyModule_AddObject(module, \"UniformBlock\", (PyObject *)&MGLUniformBlock_Type);\n\t}\n\n\t{\n\t\tif (PyType_Ready(&MGLVertexArray_Type) < 0) {\n\t\t\tPyErr_Format(PyExc_ImportError, \"Cannot register VertexArray in %s (%s:%d)\", __FUNCTION__, __FILE__, __LINE__);\n\t\t\treturn false;\n\t\t}\n\n\t\tPy_INCREF(&MGLVertexArray_Type);\n\n\t\tPyModule_AddObject(module, \"VertexArray\", (PyObject *)&MGLVertexArray_Type);\n\t}\n\n\treturn true;\n}\n\nPyModuleDef MGL_moduledef = {\n\tPyModuleDef_HEAD_INIT,\n\t\"mgl\",\n\t0,\n\t-1,\n\tMGL_module_methods,\n\t0,\n\t0,\n\t0,\n\t0,\n};\n\nextern \"C\" PyObject * PyInit_mgl() {\n\tPyObject * module = PyModule_Create(&MGL_moduledef);\n\n\tif (!MGL_InitializeModule(module)) {\n\t\treturn 0;\n\t}\n\n\treturn module;\n}\n<commit_msg>check args<commit_after>#include \"Types.hpp\"\n#include \"BufferFormat.hpp\"\n\n#include \"GLContext.hpp\"\n\nPyObject * strsize(PyObject * self, PyObject * args) {\n\tconst char * str;\n\n\tint args_ok = PyArg_ParseTuple(\n\t\targs,\n\t\t\"s\",\n\t\t&str\n\t);\n\n\tif (!args_ok) {\n\t\treturn 0;\n\t}\n\n\tchar first_chr = *str++;\n\tif (first_chr < '1' || first_chr > '9') {\n\t\treturn 0;\n\t}\n\n\tlong long value = first_chr - '0';\n\n\twhile (char chr = *str++) {\n\t\tif (chr < '0' || chr > '9') {\n\t\t\tswitch (chr) {\n\t\t\t\tcase 'G':\n\t\t\t\t\tvalue *= 1024;\n\n\t\t\t\tcase 'M':\n\t\t\t\t\tvalue *= 1024;\n\n\t\t\t\tcase 'K':\n\t\t\t\t\tvalue *= 1024;\n\n\t\t\t\t\tif (*str++ != 'B') {\n\t\t\t\t\t\treturn 0;\n\t\t\t\t\t}\n\n\t\t\t\tcase 'B':\n\t\t\t\t\tif (*str++) {\n\t\t\t\t\t\treturn 0;\n\t\t\t\t\t}\n\n\t\t\t\tcase 0:\n\t\t\t\t\tbreak;\n\n\t\t\t\tdefault:\n\t\t\t\t\treturn 0;\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\n\t\tvalue = value * 10 + chr - '0';\n\t}\n\n\treturn PyLong_FromLongLong(value);\n}\n\nPyObject * fmtdebug(PyObject * self, PyObject * args) {\n\tconst char * str;\n\n\tint args_ok = PyArg_ParseTuple(\n\t\targs,\n\t\t\"s\",\n\t\t&str\n\t);\n\n\tif (!args_ok) {\n\t\treturn 0;\n\t}\n\n\tFormatIterator it = FormatIterator(str);\n\tFormatInfo format_info = it.info();\n\n\tPyObject * nodes = PyList_New(0);\n\n\tif (format_info.valid) {\n\t\twhile (FormatNode * node = it.next()) {\n\t\t\tPyObject * obj = PyTuple_New(4);\n\t\t\tPyTuple_SET_ITEM(obj, 0, PyLong_FromLong(node->size));\n\t\t\tPyTuple_SET_ITEM(obj, 1, PyLong_FromLong(node->count));\n\t\t\tPyTuple_SET_ITEM(obj, 2, PyLong_FromLong(node->type));\n\t\t\tPyTuple_SET_ITEM(obj, 3, PyBool_FromLong(node->normalize));\n\t\t\tPyList_Append(nodes, obj);\n\t\t}\n\t}\n\n\tPyObject * res = PyTuple_New(5);\n\tPyTuple_SET_ITEM(res, 0, PyLong_FromLong(format_info.size));\n\tPyTuple_SET_ITEM(res, 1, PyLong_FromLong(format_info.nodes));\n\tPyTuple_SET_ITEM(res, 2, PyLong_FromLong(format_info.divisor));\n\tPyTuple_SET_ITEM(res, 3, PyBool_FromLong(format_info.valid));\n\tPyTuple_SET_ITEM(res, 4, PyList_AsTuple(nodes));\n\tPy_DECREF(nodes);\n\treturn res;\n}\n\nPyObject * set_error_class(PyObject * self, PyObject * args) {\n\tPyObject * error_class;\n\n\tint args_ok = PyArg_ParseTuple(\n\t\targs,\n\t\t\"O\",\n\t\t&error_class\n\t);\n\n\tif (!args_ok) {\n\t\treturn 0;\n\t}\n\n\tPy_INCREF(error_class);\n\tMGLError_TypePtr = error_class;\n\tPy_RETURN_NONE;\n}\n\nPyObject * create_standalone_context(PyObject * self, PyObject * args) {\n\tPyObject * settings;\n\n\tint args_ok = PyArg_ParseTuple(\n\t\targs,\n\t\t\"O\",\n\t\t&settings\n\t);\n\n\tif (!args_ok) {\n\t\treturn 0;\n\t}\n\n\tMGLContext * ctx = (MGLContext *)MGLContext_Type.tp_alloc(&MGLContext_Type, 0);\n\n\tctx->gl_context = CreateGLContext(settings);\n\tctx->wireframe = false;\n\n\tif (PyErr_Occurred()) {\n\t\treturn 0;\n\t}\n\n\tMGLContext_Initialize(ctx);\n\n\tif (PyErr_Occurred()) {\n\t\treturn 0;\n\t}\n\n\tPy_INCREF(ctx);\n\n\tPyObject * result = PyTuple_New(2);\n\tPyTuple_SET_ITEM(result, 0, (PyObject *)ctx);\n\tPyTuple_SET_ITEM(result, 1, PyLong_FromLong(ctx->version_code));\n\treturn result;\n}\n\nPyObject * create_context(PyObject * self) {\n\tMGLContext * ctx = (MGLContext *)MGLContext_Type.tp_alloc(&MGLContext_Type, 0);\n\n\tctx->gl_context = LoadCurrentGLContext();\n\tctx->wireframe = false;\n\n\tif (PyErr_Occurred()) {\n\t\treturn 0;\n\t}\n\n\tMGLContext_Initialize(ctx);\n\n\tif (PyErr_Occurred()) {\n\t\treturn 0;\n\t}\n\n\tPy_INCREF(ctx);\n\n\tPyObject * result = PyTuple_New(2);\n\tPyTuple_SET_ITEM(result, 0, (PyObject *)ctx);\n\tPyTuple_SET_ITEM(result, 1, PyLong_FromLong(ctx->version_code));\n\treturn result;\n}\n\nPyMethodDef MGL_module_methods[] = {\n\t{\"strsize\", (PyCFunction)strsize, METH_VARARGS, 0},\n\t{\"create_standalone_context\", (PyCFunction)create_standalone_context, METH_VARARGS, 0},\n\t{\"create_context\", (PyCFunction)create_context, METH_NOARGS, 0},\n\t{\"set_error_class\", (PyCFunction)set_error_class, METH_VARARGS, 0},\n\t{\"fmtdebug\", (PyCFunction)fmtdebug, METH_VARARGS, 0},\n\t{0},\n};\n\nbool MGL_InitializeModule(PyObject * module) {\n\t{\n\t\tif (PyType_Ready(&MGLAttribute_Type) < 0) {\n\t\t\tPyErr_Format(PyExc_ImportError, \"Cannot register Attribute in %s (%s:%d)\", __FUNCTION__, __FILE__, __LINE__);\n\t\t\treturn false;\n\t\t}\n\n\t\tPy_INCREF(&MGLAttribute_Type);\n\n\t\tPyModule_AddObject(module, \"Attribute\", (PyObject *)&MGLAttribute_Type);\n\t}\n\n\t{\n\t\tif (PyType_Ready(&MGLBuffer_Type) < 0) {\n\t\t\tPyErr_Format(PyExc_ImportError, \"Cannot register Buffer in %s (%s:%d)\", __FUNCTION__, __FILE__, __LINE__);\n\t\t\treturn false;\n\t\t}\n\n\t\tPy_INCREF(&MGLBuffer_Type);\n\n\t\tPyModule_AddObject(module, \"Buffer\", (PyObject *)&MGLBuffer_Type);\n\t}\n\n\t{\n\t\tif (PyType_Ready(&MGLComputeShader_Type) < 0) {\n\t\t\tPyErr_Format(PyExc_ImportError, \"Cannot register ComputeShader in %s (%s:%d)\", __FUNCTION__, __FILE__, __LINE__);\n\t\t\treturn false;\n\t\t}\n\n\t\tPy_INCREF(&MGLComputeShader_Type);\n\n\t\tPyModule_AddObject(module, \"ComputeShader\", (PyObject *)&MGLComputeShader_Type);\n\t}\n\n\t{\n\t\tif (PyType_Ready(&MGLContext_Type) < 0) {\n\t\t\tPyErr_Format(PyExc_ImportError, \"Cannot register Context in %s (%s:%d)\", __FUNCTION__, __FILE__, __LINE__);\n\t\t\treturn false;\n\t\t}\n\n\t\tPy_INCREF(&MGLContext_Type);\n\n\t\tPyModule_AddObject(module, \"Context\", (PyObject *)&MGLContext_Type);\n\t}\n\n\t{\n\t\tif (PyType_Ready(&MGLFramebuffer_Type) < 0) {\n\t\t\tPyErr_Format(PyExc_ImportError, \"Cannot register Framebuffer in %s (%s:%d)\", __FUNCTION__, __FILE__, __LINE__);\n\t\t\treturn false;\n\t\t}\n\n\t\tPy_INCREF(&MGLFramebuffer_Type);\n\n\t\tPyModule_AddObject(module, \"Framebuffer\", (PyObject *)&MGLFramebuffer_Type);\n\t}\n\n\t{\n\t\tif (PyType_Ready(&MGLInvalidObject_Type) < 0) {\n\t\t\tPyErr_Format(PyExc_ImportError, \"Cannot register InvalidObject in %s (%s:%d)\", __FUNCTION__, __FILE__, __LINE__);\n\t\t\treturn false;\n\t\t}\n\n\t\tPy_INCREF(&MGLInvalidObject_Type);\n\n\t\tPyModule_AddObject(module, \"InvalidObject\", (PyObject *)&MGLInvalidObject_Type);\n\t}\n\n\t{\n\t\tif (PyType_Ready(&MGLProgram_Type) < 0) {\n\t\t\tPyErr_Format(PyExc_ImportError, \"Cannot register Program in %s (%s:%d)\", __FUNCTION__, __FILE__, __LINE__);\n\t\t\treturn false;\n\t\t}\n\n\t\tPy_INCREF(&MGLProgram_Type);\n\n\t\tPyModule_AddObject(module, \"Program\", (PyObject *)&MGLProgram_Type);\n\t}\n\n\t{\n\t\tif (PyType_Ready(&MGLQuery_Type) < 0) {\n\t\t\tPyErr_Format(PyExc_ImportError, \"Cannot register Query in %s (%s:%d)\", __FUNCTION__, __FILE__, __LINE__);\n\t\t\treturn false;\n\t\t}\n\n\t\tPy_INCREF(&MGLQuery_Type);\n\n\t\tPyModule_AddObject(module, \"Query\", (PyObject *)&MGLQuery_Type);\n\t}\n\n\t{\n\t\tif (PyType_Ready(&MGLRenderbuffer_Type) < 0) {\n\t\t\tPyErr_Format(PyExc_ImportError, \"Cannot register Renderbuffer in %s (%s:%d)\", __FUNCTION__, __FILE__, __LINE__);\n\t\t\treturn false;\n\t\t}\n\n\t\tPy_INCREF(&MGLRenderbuffer_Type);\n\n\t\tPyModule_AddObject(module, \"Renderbuffer\", (PyObject *)&MGLRenderbuffer_Type);\n\t}\n\n\t{\n\t\tif (PyType_Ready(&MGLScope_Type) < 0) {\n\t\t\tPyErr_Format(PyExc_ImportError, \"Cannot register Scope in %s (%s:%d)\", __FUNCTION__, __FILE__, __LINE__);\n\t\t\treturn false;\n\t\t}\n\n\t\tPy_INCREF(&MGLScope_Type);\n\n\t\tPyModule_AddObject(module, \"Scope\", (PyObject *)&MGLScope_Type);\n\t}\n\n\t{\n\t\tif (PyType_Ready(&MGLTexture_Type) < 0) {\n\t\t\tPyErr_Format(PyExc_ImportError, \"Cannot register Texture in %s (%s:%d)\", __FUNCTION__, __FILE__, __LINE__);\n\t\t\treturn false;\n\t\t}\n\n\t\tPy_INCREF(&MGLTexture_Type);\n\n\t\tPyModule_AddObject(module, \"Texture\", (PyObject *)&MGLTexture_Type);\n\t}\n\n\t{\n\t\tif (PyType_Ready(&MGLTextureCube_Type) < 0) {\n\t\t\tPyErr_Format(PyExc_ImportError, \"Cannot register TextureCube in %s (%s:%d)\", __FUNCTION__, __FILE__, __LINE__);\n\t\t\treturn false;\n\t\t}\n\n\t\tPy_INCREF(&MGLTextureCube_Type);\n\n\t\tPyModule_AddObject(module, \"TextureCube\", (PyObject *)&MGLTextureCube_Type);\n\t}\n\n\t{\n\t\tif (PyType_Ready(&MGLTexture3D_Type) < 0) {\n\t\t\tPyErr_Format(PyExc_ImportError, \"Cannot register Texture3D in %s (%s:%d)\", __FUNCTION__, __FILE__, __LINE__);\n\t\t\treturn false;\n\t\t}\n\n\t\tPy_INCREF(&MGLTexture3D_Type);\n\n\t\tPyModule_AddObject(module, \"Texture3D\", (PyObject *)&MGLTexture3D_Type);\n\t}\n\n\t{\n\t\tif (PyType_Ready(&MGLUniform_Type) < 0) {\n\t\t\tPyErr_Format(PyExc_ImportError, \"Cannot register Uniform in %s (%s:%d)\", __FUNCTION__, __FILE__, __LINE__);\n\t\t\treturn false;\n\t\t}\n\n\t\tPy_INCREF(&MGLUniform_Type);\n\n\t\tPyModule_AddObject(module, \"Uniform\", (PyObject *)&MGLUniform_Type);\n\t}\n\n\t{\n\t\tif (PyType_Ready(&MGLUniformBlock_Type) < 0) {\n\t\t\tPyErr_Format(PyExc_ImportError, \"Cannot register UniformBlock in %s (%s:%d)\", __FUNCTION__, __FILE__, __LINE__);\n\t\t\treturn false;\n\t\t}\n\n\t\tPy_INCREF(&MGLUniformBlock_Type);\n\n\t\tPyModule_AddObject(module, \"UniformBlock\", (PyObject *)&MGLUniformBlock_Type);\n\t}\n\n\t{\n\t\tif (PyType_Ready(&MGLVertexArray_Type) < 0) {\n\t\t\tPyErr_Format(PyExc_ImportError, \"Cannot register VertexArray in %s (%s:%d)\", __FUNCTION__, __FILE__, __LINE__);\n\t\t\treturn false;\n\t\t}\n\n\t\tPy_INCREF(&MGLVertexArray_Type);\n\n\t\tPyModule_AddObject(module, \"VertexArray\", (PyObject *)&MGLVertexArray_Type);\n\t}\n\n\treturn true;\n}\n\nPyModuleDef MGL_moduledef = {\n\tPyModuleDef_HEAD_INIT,\n\t\"mgl\",\n\t0,\n\t-1,\n\tMGL_module_methods,\n\t0,\n\t0,\n\t0,\n\t0,\n};\n\nextern \"C\" PyObject * PyInit_mgl() {\n\tPyObject * module = PyModule_Create(&MGL_moduledef);\n\n\tif (!MGL_InitializeModule(module)) {\n\t\treturn 0;\n\t}\n\n\treturn module;\n}\n<|endoftext|>"} {"text":"<commit_before>#include <algorithm>\n#include <map>\n#include <string>\n\n#include \"Prefetch.h\"\n#include \"IRMutator.h\"\n#include \"Bounds.h\"\n#include \"Scope.h\"\n#include \"Util.h\"\n\nnamespace Halide {\nnamespace Internal {\n\nusing std::map;\nusing std::string;\nusing std::vector;\n\nnamespace {\n\n\/\/ We need to be able to make loads from a buffer that refer to the\n\/\/ same original image\/param\/etc. This visitor finds a load to the\n\/\/ buffer we want to load from, and generates a similar load, but with\n\/\/ different args.\nclass MakeSimilarLoad : public IRVisitor {\npublic:\n const std::string &buf_name;\n const std::vector<Expr> &args;\n Expr load;\n\n MakeSimilarLoad(std::string name, const std::vector<Expr> &args)\n : buf_name(name), args(args) {}\n\nprivate:\n using IRVisitor::visit;\n\n void visit(const Call *op) {\n if (op->name == buf_name) {\n load = Call::make(op->type, op->name, args, op->call_type, op->func, op->value_index, op->image, op->param);\n } else {\n IRVisitor::visit(op);\n }\n }\n};\n\nExpr make_similar_load(Stmt s, const std::string &name, const std::vector<Expr> &args) {\n MakeSimilarLoad v(name, args);\n s.accept(&v);\n return v.load;\n}\n\n\/\/ Build a Box representing the bounds of a buffer.\nBox buffer_bounds(const string &buf_name, int dims) {\n Box bounds;\n for (int i = 0; i < dims; i++) {\n string dim_name = std::to_string(i);\n\n Expr buf_min_i = Variable::make(Int(32), buf_name + \".min.\" + dim_name);\n Expr buf_extent_i = Variable::make(Int(32), buf_name + \".extent.\" + dim_name);\n Expr buf_max_i = buf_min_i + buf_extent_i - 1;\n\n bounds.push_back(Interval(buf_min_i, buf_max_i));\n }\n return bounds;\n}\n\nclass InjectPrefetch : public IRMutator {\npublic:\n InjectPrefetch(const map<string, Function> &e) : env(e) { }\n\nprivate:\n const map<string, Function> &env;\n const vector<Prefetch> *prefetches = nullptr;\n Scope<Interval> bounds;\n\nprivate:\n using IRMutator::visit;\n\n void visit(const Let *op) {\n Interval in = bounds_of_expr_in_scope(op->value, bounds);\n bounds.push(op->name, in);\n IRMutator::visit(op);\n bounds.pop(op->name);\n }\n\n void visit(const LetStmt *op) {\n Interval in = bounds_of_expr_in_scope(op->value, bounds);\n bounds.push(op->name, in);\n IRMutator::visit(op);\n bounds.pop(op->name);\n }\n\n void visit(const ProducerConsumer *op) {\n const vector<Prefetch> *old_prefetches = prefetches;\n\n map<string, Function>::const_iterator iter = env.find(op->name);\n internal_assert(iter != env.end()) << \"function not in environment.\\n\";\n prefetches = &iter->second.schedule().prefetches();\n IRMutator::visit(op);\n prefetches = old_prefetches;\n }\n\n Stmt add_prefetch(const string &buf_name, const Box &box, Stmt body) {\n \/\/ Construct the bounds to be prefetched.\n vector<Expr> prefetch_min;\n vector<Expr> prefetch_extent;\n for (size_t i = 0; i < box.size(); i++) {\n prefetch_min.push_back(box[i].min);\n prefetch_extent.push_back(box[i].max - box[i].min + 1);\n }\n\n \/\/ Construct an array of index variables. The first 2 dimensions are handled\n \/\/ by (up to) 2D prefetches, the rest we will generate loops to define.\n vector<string> index_names(box.size());\n vector<Expr> indices(box.size());\n for (size_t i = 0; i < box.size(); i++) {\n index_names[i] = \"prefetch_\" + buf_name + \".\" + std::to_string(i);\n indices[i] = i < 2 ? prefetch_min[i] : Variable::make(Int(32), index_names[i]);\n }\n\n \/\/ Make a load at the index and get the address.\n Expr prefetch_load = make_similar_load(body, buf_name, indices);\n internal_assert(prefetch_load.defined());\n Type type = prefetch_load.type();\n Expr prefetch_addr = Call::make(Handle(), Call::address_of, {prefetch_load}, Call::Intrinsic);\n\n Stmt prefetch;\n Expr stride_0 = Variable::make(Int(32), buf_name + \".stride.0\");\n \/\/ TODO: This is only correct if stride_0 is 1. We need to assert that this is true.\n Expr extent_0_bytes = prefetch_extent[0] * type.bytes();\n if (box.size() == 1) {\n \/\/ The prefetch is only 1 dimensional, just emit a flat prefetch.\n prefetch = Evaluate::make(Call::make(Int(32), Call::prefetch,\n {prefetch_addr, extent_0_bytes},\n Call::PureIntrinsic));\n } else {\n \/\/ Make a 2D prefetch.\n Expr stride_1 = Variable::make(Int(32), buf_name + \".stride.1\");\n Expr stride_1_bytes = stride_1 * type.bytes();\n prefetch = Evaluate::make(Call::make(Int(32), Call::prefetch_2d,\n {prefetch_addr, extent_0_bytes, prefetch_extent[1], stride_1_bytes},\n Call::PureIntrinsic));\n\n \/\/ Make loops for the rest of the dimensions (possibly zero).\n for (size_t i = 2; i < box.size(); i++) {\n prefetch = For::make(index_names[i], prefetch_min[i], prefetch_extent[i],\n ForType::Serial, DeviceAPI::None,\n prefetch);\n }\n }\n\n \/\/ We should only prefetch buffers that are used.\n if (box.maybe_unused()) {\n prefetch = IfThenElse::make(box.used, prefetch);\n }\n\n return Block::make({prefetch, body});\n }\n\n void visit(const For *op) {\n \/\/ Add loop variable to interval scope for any inner loop prefetch\n Expr loop_var = Variable::make(Int(32), op->name);\n bounds.push(op->name, Interval(loop_var, loop_var));\n Stmt body = mutate(op->body);\n bounds.pop(op->name);\n\n if (prefetches) {\n for (const Prefetch &p : *prefetches) {\n if (!ends_with(op->name, \".\" + p.var)) {\n continue;\n }\n \/\/ Add loop variable + prefetch offset to interval scope for box computation\n Expr fetch_at = loop_var + p.offset;\n bounds.push(op->name, Interval(fetch_at, fetch_at));\n map<string, Box> boxes_read = boxes_required(body, bounds);\n bounds.pop(op->name);\n\n \/\/ Don't prefetch buffers that are written to. We assume that these already\n \/\/ have good locality.\n \/\/ TODO: This is not a good assumption. It would be better to have the\n \/\/ prefetch directive specify the buffer that we want to prefetch, instead\n \/\/ of trying to figure out which buffers should be prefetched.\n map<string, Box> boxes_written = boxes_provided(body, bounds);\n for (const auto &b : boxes_written) {\n auto it = boxes_read.find(b.first);\n if (it != boxes_read.end()) {\n debug(2) << \"Not prefetching buffer \" << it->first\n << \" also written in loop \" << op->name << \"\\n\";\n boxes_read.erase(it);\n }\n }\n\n \/\/ TODO: Only prefetch the newly accessed data from the previous iteration.\n \/\/ This should use boxes_touched (instead of boxes_required) so we exclude memory\n \/\/ either read or written.\n for (const auto &b : boxes_read) {\n const std::string &buf_name = b.first;\n\n \/\/ Only prefetch the region that is in bounds.\n Box bounds = buffer_bounds(buf_name, b.second.size());\n Box prefetch_box = box_intersection(b.second, bounds);\n\n body = add_prefetch(buf_name, prefetch_box, body);\n }\n }\n }\n\n if (!body.same_as(op->body)) {\n stmt = For::make(op->name, op->min, op->extent, op->for_type, op->device_api, body);\n } else {\n stmt = op;\n }\n }\n\n};\n\n} \/\/ namespace\n\nStmt inject_prefetch(Stmt s, const std::map<std::string, Function> &env) {\n return InjectPrefetch(env).mutate(s);\n}\n\n}\n}\n<commit_msg>Add more comments\/TODO description.<commit_after>#include <algorithm>\n#include <map>\n#include <string>\n\n#include \"Prefetch.h\"\n#include \"IRMutator.h\"\n#include \"Bounds.h\"\n#include \"Scope.h\"\n#include \"Util.h\"\n\nnamespace Halide {\nnamespace Internal {\n\nusing std::map;\nusing std::string;\nusing std::vector;\n\nnamespace {\n\n\/\/ We need to be able to make loads from a buffer that refer to the\n\/\/ same original image\/param\/etc. This visitor finds a load to the\n\/\/ buffer we want to load from, and generates a similar load, but with\n\/\/ different args.\nclass MakeSimilarLoad : public IRVisitor {\npublic:\n const std::string &buf_name;\n const std::vector<Expr> &args;\n Expr load;\n\n MakeSimilarLoad(std::string name, const std::vector<Expr> &args)\n : buf_name(name), args(args) {}\n\nprivate:\n using IRVisitor::visit;\n\n void visit(const Call *op) {\n if (op->name == buf_name) {\n load = Call::make(op->type, op->name, args, op->call_type, op->func, op->value_index, op->image, op->param);\n } else {\n IRVisitor::visit(op);\n }\n }\n};\n\nExpr make_similar_load(Stmt s, const std::string &name, const std::vector<Expr> &args) {\n MakeSimilarLoad v(name, args);\n s.accept(&v);\n return v.load;\n}\n\n\/\/ Build a Box representing the bounds of a buffer.\nBox buffer_bounds(const string &buf_name, int dims) {\n Box bounds;\n for (int i = 0; i < dims; i++) {\n string dim_name = std::to_string(i);\n\n Expr buf_min_i = Variable::make(Int(32), buf_name + \".min.\" + dim_name);\n Expr buf_extent_i = Variable::make(Int(32), buf_name + \".extent.\" + dim_name);\n Expr buf_max_i = buf_min_i + buf_extent_i - 1;\n\n bounds.push_back(Interval(buf_min_i, buf_max_i));\n }\n return bounds;\n}\n\nclass InjectPrefetch : public IRMutator {\npublic:\n InjectPrefetch(const map<string, Function> &e) : env(e) { }\n\nprivate:\n const map<string, Function> &env;\n const vector<Prefetch> *prefetches = nullptr;\n Scope<Interval> bounds;\n\nprivate:\n using IRMutator::visit;\n\n void visit(const Let *op) {\n Interval in = bounds_of_expr_in_scope(op->value, bounds);\n bounds.push(op->name, in);\n IRMutator::visit(op);\n bounds.pop(op->name);\n }\n\n void visit(const LetStmt *op) {\n Interval in = bounds_of_expr_in_scope(op->value, bounds);\n bounds.push(op->name, in);\n IRMutator::visit(op);\n bounds.pop(op->name);\n }\n\n void visit(const ProducerConsumer *op) {\n const vector<Prefetch> *old_prefetches = prefetches;\n\n map<string, Function>::const_iterator iter = env.find(op->name);\n internal_assert(iter != env.end()) << \"function not in environment.\\n\";\n prefetches = &iter->second.schedule().prefetches();\n IRMutator::visit(op);\n prefetches = old_prefetches;\n }\n\n Stmt add_prefetch(const string &buf_name, const Box &box, Stmt body) {\n \/\/ Construct the bounds to be prefetched.\n vector<Expr> prefetch_min;\n vector<Expr> prefetch_extent;\n for (size_t i = 0; i < box.size(); i++) {\n prefetch_min.push_back(box[i].min);\n prefetch_extent.push_back(box[i].max - box[i].min + 1);\n }\n\n \/\/ Construct an array of index expressions to construct\n \/\/ address_of calls with. The first 2 dimensions are handled\n \/\/ by (up to) 2D prefetches, the rest we will generate loops\n \/\/ to define.\n vector<string> index_names(box.size());\n vector<Expr> indices(box.size());\n for (size_t i = 0; i < box.size(); i++) {\n index_names[i] = \"prefetch_\" + buf_name + \".\" + std::to_string(i);\n indices[i] = i < 2 ? prefetch_min[i] : Variable::make(Int(32), index_names[i]);\n }\n\n \/\/ Make a load at the index and get the address.\n Expr prefetch_load = make_similar_load(body, buf_name, indices);\n internal_assert(prefetch_load.defined());\n Type type = prefetch_load.type();\n Expr prefetch_addr = Call::make(Handle(), Call::address_of, {prefetch_load}, Call::Intrinsic);\n\n Stmt prefetch;\n Expr stride_0 = Variable::make(Int(32), buf_name + \".stride.0\");\n \/\/ TODO: This is only correct if stride_0 is 1. We need to assert that this is true.\n Expr extent_0_bytes = prefetch_extent[0] * type.bytes();\n if (box.size() == 1) {\n \/\/ The prefetch is only 1 dimensional, just emit a flat prefetch.\n prefetch = Evaluate::make(Call::make(Int(32), Call::prefetch,\n {prefetch_addr, extent_0_bytes},\n Call::PureIntrinsic));\n } else {\n \/\/ Make a 2D prefetch.\n Expr stride_1 = Variable::make(Int(32), buf_name + \".stride.1\");\n Expr stride_1_bytes = stride_1 * type.bytes();\n prefetch = Evaluate::make(Call::make(Int(32), Call::prefetch_2d,\n {prefetch_addr, extent_0_bytes, prefetch_extent[1], stride_1_bytes},\n Call::PureIntrinsic));\n\n \/\/ Make loops for the rest of the dimensions (possibly zero).\n for (size_t i = 2; i < box.size(); i++) {\n prefetch = For::make(index_names[i], prefetch_min[i], prefetch_extent[i],\n ForType::Serial, DeviceAPI::None,\n prefetch);\n }\n }\n\n \/\/ We should only prefetch buffers that are used.\n if (box.maybe_unused()) {\n prefetch = IfThenElse::make(box.used, prefetch);\n }\n\n return Block::make({prefetch, body});\n }\n\n void visit(const For *op) {\n \/\/ Add loop variable to interval scope for any inner loop prefetch\n Expr loop_var = Variable::make(Int(32), op->name);\n bounds.push(op->name, Interval(loop_var, loop_var));\n Stmt body = mutate(op->body);\n bounds.pop(op->name);\n\n if (prefetches) {\n for (const Prefetch &p : *prefetches) {\n if (!ends_with(op->name, \".\" + p.var)) {\n continue;\n }\n \/\/ Add loop variable + prefetch offset to interval scope for box computation\n Expr fetch_at = loop_var + p.offset;\n bounds.push(op->name, Interval(fetch_at, fetch_at));\n map<string, Box> boxes_read = boxes_required(body, bounds);\n bounds.pop(op->name);\n\n \/\/ Don't prefetch buffers that are written to. We assume that these already\n \/\/ have good locality.\n \/\/ TODO: This is not a good assumption. It would be better to have the\n \/\/ prefetch directive specify the buffer that we want to prefetch, instead\n \/\/ of trying to figure out which buffers should be prefetched. This would also\n \/\/ mean that we don't need the \"make_similar_load\" hack, because we can make\n \/\/ calls the standard way (using the ImageParam\/Function object referenced in\n \/\/ the prefetch).\n map<string, Box> boxes_written = boxes_provided(body, bounds);\n for (const auto &b : boxes_written) {\n auto it = boxes_read.find(b.first);\n if (it != boxes_read.end()) {\n debug(2) << \"Not prefetching buffer \" << it->first\n << \" also written in loop \" << op->name << \"\\n\";\n boxes_read.erase(it);\n }\n }\n\n \/\/ TODO: Only prefetch the newly accessed data from the previous iteration.\n \/\/ This should use boxes_touched (instead of boxes_required) so we exclude memory\n \/\/ either read or written.\n for (const auto &b : boxes_read) {\n const std::string &buf_name = b.first;\n\n \/\/ Only prefetch the region that is in bounds.\n Box bounds = buffer_bounds(buf_name, b.second.size());\n Box prefetch_box = box_intersection(b.second, bounds);\n\n body = add_prefetch(buf_name, prefetch_box, body);\n }\n }\n }\n\n if (!body.same_as(op->body)) {\n stmt = For::make(op->name, op->min, op->extent, op->for_type, op->device_api, body);\n } else {\n stmt = op;\n }\n }\n\n};\n\n} \/\/ namespace\n\nStmt inject_prefetch(Stmt s, const std::map<std::string, Function> &env) {\n return InjectPrefetch(env).mutate(s);\n}\n\n}\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Universe\n *\n * Copyright 2015 Lubosz Sarnecki <lubosz@gmail.com>\n *\n *\/\n\n#include \"Renderer.h\"\n\n#include \"util.h\"\n#include <gli\/gli.hpp>\n\nRenderer::Renderer(int width, int height) {\n translate_z = -1.f;\n rotate_x = 0.0;\n rotate_y = 0.0;\n\n if (gl3wInit()) {\n fprintf(stderr, \"failed to initialize gl3w\\n\");\n return;\n }\n if (!gl3wIsSupported(4, 5)) {\n fprintf(stderr, \"OpenGL 4.5 not supported\\n\");\n return;\n }\n\n printContextInfo();\n initShaders();\n glUseProgram(shader_programm);\n\n glEnable(GL_VERTEX_PROGRAM_POINT_SIZE);\n\n GLuint tex = initTexture(\"media\/cloud.dds\");\n glBindTexture(GL_TEXTURE_2D, tex);\n\n GLint texLoc = glGetUniformLocation(shader_programm, \"cloud\");\n glUniform1i(texLoc, tex-1);\n\n updateModel();\n updateProjection(width, height);\n\n glClearColor(0.0, 0.0, 0.0, 1.0);\n glDisable(GL_DEPTH_TEST);\n glEnable(GL_BLEND);\n glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);\n\n glBindVertexArray(vao);\n\n glError;\n}\n\nRenderer::~Renderer() {}\n\nvoid Renderer::draw(GLuint positionVBO, GLuint colorVBO, int particleCount) {\n \/\/ render the particles from VBOs\n glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);\n\n glGenVertexArrays(1, &vao);\n glBindVertexArray(vao);\n glEnableVertexAttribArray(0);\n glBindBuffer(GL_ARRAY_BUFFER, positionVBO);\n glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, 0, NULL);\n\n glEnableVertexAttribArray(1);\n glBindBuffer(GL_ARRAY_BUFFER, colorVBO);\n glVertexAttribPointer(1, 4, GL_FLOAT, GL_FALSE, 0, NULL);\n\n glDrawArrays(GL_POINTS, 0, particleCount);\n}\n\nvoid Renderer::printContextInfo() {\n printf(\"GL_RENDERER: %s\\n\", glGetString(GL_RENDERER));\n printf(\"GL_VERSION: %s\\n\", glGetString(GL_VERSION));\n printf(\"GL_SHADING_LANGUAGE_VERSION: %s\\n\",\n glGetString(GL_SHADING_LANGUAGE_VERSION));\n}\n\nGLuint Renderer::initTexture(char const* Filename) {\n gli::texture Texture = gli::load(Filename);\n if (Texture.empty())\n return 0;\n\n gli::gl GL;\n gli::gl::format const Format = GL.translate(Texture.format());\n GLenum Target = GL.translate(Texture.target());\n\n GLuint TextureName = 0;\n glGenTextures(1, &TextureName);\n glBindTexture(Target, TextureName);\n glTexParameteri(Target, GL_TEXTURE_BASE_LEVEL, 0);\n glTexParameteri(Target,\n GL_TEXTURE_MAX_LEVEL, static_cast<GLint>(Texture.levels() - 1));\n \/*\n glTexParameteri(Target, GL_TEXTURE_SWIZZLE_R, Format.Swizzle[0]);\n glTexParameteri(Target, GL_TEXTURE_SWIZZLE_G, Format.Swizzle[1]);\n glTexParameteri(Target, GL_TEXTURE_SWIZZLE_B, Format.Swizzle[2]);\n glTexParameteri(Target, GL_TEXTURE_SWIZZLE_A, Format.Swizzle[3]);\n *\/\n glm::tvec3<GLsizei> const Dimensions(Texture.dimensions());\n GLsizei const FaceTotal =\n static_cast<GLsizei>(Texture.layers() * Texture.faces());\n\n switch (Texture.target()) {\n case gli::TARGET_1D:\n glTexStorage1D(\n Target,\n static_cast<GLint>(Texture.levels()),\n Format.Internal, Dimensions.x);\n break;\n case gli::TARGET_1D_ARRAY:\n case gli::TARGET_2D:\n case gli::TARGET_CUBE:\n glTexStorage2D(\n Target, static_cast<GLint>(Texture.levels()), Format.Internal,\n Dimensions.x,\n Texture.target() == gli::TARGET_2D ? Dimensions.y : FaceTotal);\n break;\n case gli::TARGET_2D_ARRAY:\n case gli::TARGET_3D:\n case gli::TARGET_CUBE_ARRAY:\n glTexStorage3D(\n Target, static_cast<GLint>(Texture.levels()), Format.Internal,\n Dimensions.x, Dimensions.y,\n Texture.target() == gli::TARGET_3D ? Dimensions.z : FaceTotal);\n break;\n default:\n assert(0);\n break;\n }\n\n for (std::size_t Layer = 0; Layer < Texture.layers(); ++Layer)\n for (std::size_t Face = 0; Face < Texture.faces(); ++Face)\n for (std::size_t Level = 0; Level < Texture.levels(); ++Level) {\n GLsizei const LayerGL = static_cast<GLsizei>(Layer);\n glm::tvec3<GLsizei> Dimensions(Texture.dimensions(Level));\n Target = gli::is_target_cube(Texture.target())\n ? static_cast<GLenum>(GL_TEXTURE_CUBE_MAP_POSITIVE_X + Face)\n : Target;\n\n switch (Texture.target()) {\n case gli::TARGET_1D:\n if (gli::is_compressed(Texture.format()))\n glCompressedTexSubImage1D(\n Target, static_cast<GLint>(Level), 0, Dimensions.x,\n Format.Internal, static_cast<GLsizei>(Texture.size(Level)),\n Texture.data(Layer, Face, Level));\n else\n glTexSubImage1D(\n Target, static_cast<GLint>(Level), 0, Dimensions.x,\n Format.External, Format.Type,\n Texture.data(Layer, Face, Level));\n break;\n case gli::TARGET_1D_ARRAY:\n case gli::TARGET_2D:\n case gli::TARGET_CUBE:\n if (gli::is_compressed(Texture.format()))\n glCompressedTexSubImage2D(\n Target, static_cast<GLint>(Level),\n 0, 0,\n Dimensions.x,\n Dimensions.y,\n Format.Internal, static_cast<GLsizei>(Texture.size(Level)),\n Texture.data(Layer, Face, Level));\n else\n glTexSubImage2D(\n Target, static_cast<GLint>(Level),\n 0, 0,\n Dimensions.x,\n Dimensions.y,\n Format.External, Format.Type,\n Texture.data(Layer, Face, Level));\n break;\n case gli::TARGET_2D_ARRAY:\n case gli::TARGET_3D:\n case gli::TARGET_CUBE_ARRAY:\n if (gli::is_compressed(Texture.format()))\n glCompressedTexSubImage3D(\n Target, static_cast<GLint>(Level),\n 0, 0, 0,\n Dimensions.x, Dimensions.y,\n Texture.target() == LayerGL,\n Format.Internal, static_cast<GLsizei>(Texture.size(Level)),\n Texture.data(Layer, Face, Level));\n else\n glTexSubImage3D(\n Target, static_cast<GLint>(Level),\n 0, 0, 0,\n Dimensions.x, Dimensions.y,\n Texture.target() == LayerGL,\n Format.External, Format.Type,\n Texture.data(Layer, Face, Level));\n break;\n default: assert(0); break;\n }\n }\n return TextureName;\n}\n\nvoid Renderer::initShaders() {\n shaders.push_back(readFile(\"gpu\/MVP.vert\"));\n shaders.push_back(readFile(\"gpu\/color.frag\"));\n\n const char* vertex[] = {shaders[0].c_str()};\n const char* fragment[] = {shaders[1].c_str()};\n\n GLuint vs = glCreateShader(GL_VERTEX_SHADER);\n glShaderSource(vs, 1, vertex, NULL);\n glCompileShader(vs);\n GLuint fs = glCreateShader(GL_FRAGMENT_SHADER);\n glShaderSource(fs, 1, fragment, NULL);\n glCompileShader(fs);\n\n shader_programm = glCreateProgram();\n glAttachShader(shader_programm, fs);\n glAttachShader(shader_programm, vs);\n glLinkProgram(shader_programm);\n}\n\nvoid Renderer::rotate(float x, float y) {\n rotate_x += y * 0.2;\n rotate_y += x * 0.2;\n updateModel();\n}\n\nvoid Renderer::translate(float z) {\n translate_z += z * 0.1;\n updateModel();\n}\n\nvoid Renderer::updateModel() {\n model = glm::mat4(1.0f);\n model = glm::translate(glm::mat4(1.0f), glm::vec3(0.0f, 0.0f, translate_z));\n model = glm::rotate(model, rotate_x, glm::vec3(1.0f, 0.0f, 0.0f));\n model = glm::rotate(model, rotate_y, glm::vec3(0.0f, 1.0f, 0.0f));\n updateMVP();\n}\n\nvoid Renderer::updateProjection(int width, int height) {\n glViewport(0, 0, width, height);\n float aspect = static_cast<GLfloat>(width)\n \/ static_cast<GLfloat>(height);\n projection = glm::perspective(90.0f, aspect, 0.1f, 1000.f);\n updateMVP();\n}\n\nvoid Renderer::updateMVP() {\n glm::mat4 mvp = projection * model;\n GLint UniformMVP = glGetUniformLocation(shader_programm, \"mvp\");\n glUniformMatrix4fv(UniformMVP, 1, GL_FALSE, &mvp[0][0]);\n}\n\nvoid Renderer::checkGlError(const char* file, int line) {\n GLenum err(glGetError());\n\n while (err != GL_NO_ERROR) {\n std::string error;\n switch (err) {\n case GL_INVALID_OPERATION:\n error = \"INVALID_OPERATION\";\n break;\n case GL_INVALID_ENUM:\n error = \"INVALID_ENUM\";\n break;\n case GL_INVALID_VALUE:\n error = \"INVALID_VALUE\";\n break;\n case GL_OUT_OF_MEMORY:\n error = \"OUT_OF_MEMORY\";\n break;\n case GL_INVALID_FRAMEBUFFER_OPERATION:\n error = \"INVALID_FRAMEBUFFER_OPERATION\";\n break;\n default:\n error = \"Unknown error\";\n break;\n }\n std::cout\n << \"GL ERROR: GL_\"\n << error << \" \"\n << file << \" \"\n << line << \"\\n\";\n err = glGetError();\n }\n}\n\nGLuint Renderer::createVBO(\n const void* data,\n int dataSize,\n GLenum target,\n GLenum usage) {\n GLuint id;\n glGenBuffers(1, &id);\n glBindBuffer(target, id);\n glBufferData(target, dataSize, data, usage);\n\n \/\/ check data size in VBO is same as input array\n \/\/ if not return 0 and delete VBO\n int bufferSize = 0;\n glGetBufferParameteriv(target, GL_BUFFER_SIZE, &bufferSize);\n if (dataSize != bufferSize) {\n glDeleteBuffers(1, &id);\n id = 0;\n std::cout << \"[createVBO()] Data size is mismatch with input array\\n\";\n }\n glBindBuffer(target, 0);\n return id;\n}\n<commit_msg>renderer: make image loading shorter<commit_after>\/*\n * Universe\n *\n * Copyright 2015 Lubosz Sarnecki <lubosz@gmail.com>\n *\n *\/\n\n#include \"Renderer.h\"\n\n#include \"util.h\"\n#include <gli\/gli.hpp>\n\nRenderer::Renderer(int width, int height) {\n translate_z = -1.f;\n rotate_x = 0.0;\n rotate_y = 0.0;\n\n if (gl3wInit()) {\n fprintf(stderr, \"failed to initialize gl3w\\n\");\n return;\n }\n if (!gl3wIsSupported(4, 5)) {\n fprintf(stderr, \"OpenGL 4.5 not supported\\n\");\n return;\n }\n\n printContextInfo();\n initShaders();\n glUseProgram(shader_programm);\n\n glEnable(GL_VERTEX_PROGRAM_POINT_SIZE);\n\n GLuint tex = initTexture(\"media\/cloud.dds\");\n glBindTexture(GL_TEXTURE_2D, tex);\n\n GLint texLoc = glGetUniformLocation(shader_programm, \"cloud\");\n glUniform1i(texLoc, tex-1);\n\n updateModel();\n updateProjection(width, height);\n\n glClearColor(0.0, 0.0, 0.0, 1.0);\n glDisable(GL_DEPTH_TEST);\n glEnable(GL_BLEND);\n glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);\n\n glBindVertexArray(vao);\n\n glError;\n}\n\nRenderer::~Renderer() {}\n\nvoid Renderer::draw(GLuint positionVBO, GLuint colorVBO, int particleCount) {\n \/\/ render the particles from VBOs\n glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);\n\n glGenVertexArrays(1, &vao);\n glBindVertexArray(vao);\n glEnableVertexAttribArray(0);\n glBindBuffer(GL_ARRAY_BUFFER, positionVBO);\n glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, 0, NULL);\n\n glEnableVertexAttribArray(1);\n glBindBuffer(GL_ARRAY_BUFFER, colorVBO);\n glVertexAttribPointer(1, 4, GL_FLOAT, GL_FALSE, 0, NULL);\n\n glDrawArrays(GL_POINTS, 0, particleCount);\n}\n\nvoid Renderer::printContextInfo() {\n printf(\"GL_RENDERER: %s\\n\", glGetString(GL_RENDERER));\n printf(\"GL_VERSION: %s\\n\", glGetString(GL_VERSION));\n printf(\"GL_SHADING_LANGUAGE_VERSION: %s\\n\",\n glGetString(GL_SHADING_LANGUAGE_VERSION));\n}\n\nGLuint Renderer::initTexture(char const* Filename) {\n gli::texture Texture = gli::load(Filename);\n if (Texture.empty())\n return 0;\n\n gli::gl GL;\n gli::gl::format const Format = GL.translate(Texture.format());\n GLenum Target = GL.translate(Texture.target());\n\n GLuint TextureName = 0;\n glGenTextures(1, &TextureName);\n glBindTexture(Target, TextureName);\n glTexParameteri(Target, GL_TEXTURE_BASE_LEVEL, 0);\n glTexParameteri(Target,\n GL_TEXTURE_MAX_LEVEL, static_cast<GLint>(Texture.levels() - 1));\n\n glm::tvec3<GLsizei> const Dimensions(Texture.dimensions());\n GLsizei const FaceTotal =\n static_cast<GLsizei>(Texture.layers() * Texture.faces());\n\n glTexStorage2D(\n Target, static_cast<GLint>(Texture.levels()), Format.Internal,\n Dimensions.x,\n Texture.target() == gli::TARGET_2D ? Dimensions.y : FaceTotal);\n\n for (std::size_t Layer = 0;\n Layer < Texture.layers(); ++Layer)\n for (std::size_t Face = 0;\n Face < Texture.faces(); ++Face)\n for (std::size_t Level = 0;\n Level < Texture.levels(); ++Level) {\n glm::tvec3<GLsizei> Dimensions(Texture.dimensions(Level));\n\n \/*\n printf(\"layer %ld, face %ld, level %ld, iscompressed %d\\n\",\n Layer, Face, Level,\n gli::is_compressed(Texture.format()));\n *\/\n if (gli::is_compressed(Texture.format()))\n glCompressedTexSubImage2D(\n Target, static_cast<GLint>(Level),\n 0, 0,\n Dimensions.x,\n Dimensions.y,\n Format.Internal, static_cast<GLsizei>(Texture.size(Level)),\n Texture.data(Layer, Face, Level));\n else\n glTexSubImage2D(\n Target, static_cast<GLint>(Level),\n 0, 0,\n Dimensions.x,\n Dimensions.y,\n Format.External, Format.Type,\n Texture.data(Layer, Face, Level));\n }\n return TextureName;\n}\n\nvoid Renderer::initShaders() {\n shaders.push_back(readFile(\"gpu\/MVP.vert\"));\n shaders.push_back(readFile(\"gpu\/color.frag\"));\n\n const char* vertex[] = {shaders[0].c_str()};\n const char* fragment[] = {shaders[1].c_str()};\n\n GLuint vs = glCreateShader(GL_VERTEX_SHADER);\n glShaderSource(vs, 1, vertex, NULL);\n glCompileShader(vs);\n GLuint fs = glCreateShader(GL_FRAGMENT_SHADER);\n glShaderSource(fs, 1, fragment, NULL);\n glCompileShader(fs);\n\n shader_programm = glCreateProgram();\n glAttachShader(shader_programm, fs);\n glAttachShader(shader_programm, vs);\n glLinkProgram(shader_programm);\n}\n\nvoid Renderer::rotate(float x, float y) {\n rotate_x += y * 0.2;\n rotate_y += x * 0.2;\n updateModel();\n}\n\nvoid Renderer::translate(float z) {\n translate_z += z * 0.1;\n updateModel();\n}\n\nvoid Renderer::updateModel() {\n model = glm::mat4(1.0f);\n model = glm::translate(glm::mat4(1.0f), glm::vec3(0.0f, 0.0f, translate_z));\n model = glm::rotate(model, rotate_x, glm::vec3(1.0f, 0.0f, 0.0f));\n model = glm::rotate(model, rotate_y, glm::vec3(0.0f, 1.0f, 0.0f));\n updateMVP();\n}\n\nvoid Renderer::updateProjection(int width, int height) {\n glViewport(0, 0, width, height);\n float aspect = static_cast<GLfloat>(width)\n \/ static_cast<GLfloat>(height);\n projection = glm::perspective(90.0f, aspect, 0.1f, 1000.f);\n updateMVP();\n}\n\nvoid Renderer::updateMVP() {\n glm::mat4 mvp = projection * model;\n GLint UniformMVP = glGetUniformLocation(shader_programm, \"mvp\");\n glUniformMatrix4fv(UniformMVP, 1, GL_FALSE, &mvp[0][0]);\n}\n\nvoid Renderer::checkGlError(const char* file, int line) {\n GLenum err(glGetError());\n\n while (err != GL_NO_ERROR) {\n std::string error;\n switch (err) {\n case GL_INVALID_OPERATION:\n error = \"INVALID_OPERATION\";\n break;\n case GL_INVALID_ENUM:\n error = \"INVALID_ENUM\";\n break;\n case GL_INVALID_VALUE:\n error = \"INVALID_VALUE\";\n break;\n case GL_OUT_OF_MEMORY:\n error = \"OUT_OF_MEMORY\";\n break;\n case GL_INVALID_FRAMEBUFFER_OPERATION:\n error = \"INVALID_FRAMEBUFFER_OPERATION\";\n break;\n default:\n error = \"Unknown error\";\n break;\n }\n std::cout\n << \"GL ERROR: GL_\"\n << error << \" \"\n << file << \" \"\n << line << \"\\n\";\n err = glGetError();\n }\n}\n\nGLuint Renderer::createVBO(\n const void* data,\n int dataSize,\n GLenum target,\n GLenum usage) {\n GLuint id;\n glGenBuffers(1, &id);\n glBindBuffer(target, id);\n glBufferData(target, dataSize, data, usage);\n\n \/\/ check data size in VBO is same as input array\n \/\/ if not return 0 and delete VBO\n int bufferSize = 0;\n glGetBufferParameteriv(target, GL_BUFFER_SIZE, &bufferSize);\n if (dataSize != bufferSize) {\n glDeleteBuffers(1, &id);\n id = 0;\n std::cout << \"[createVBO()] Data size is mismatch with input array\\n\";\n }\n glBindBuffer(target, 0);\n return id;\n}\n<|endoftext|>"} {"text":"<commit_before>\/**\n * Copyright 2013 Da Zheng\n *\n * This file is part of SAFSlib.\n *\n * SAFSlib is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * SAFSlib is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with SAFSlib. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n\n#include \"rand_buf.h\"\n\nrand_buf::rand_buf(int buf_size, int entry_size, int nodeid)\n#ifdef MEMCHECK\n\t: allocator(entry_size)\n#else\n\t\/\/ We don't initialize pages but pin them.\n\t: allocator(std::string(\"rand_buf-\") + itoa(nodeid), entry_size,\n\t\t\tbuf_size, buf_size, nodeid, false, true, 0, false)\n#endif\n{\n\tthis->entry_size = entry_size;\n}\n\nchar *rand_buf::next_entry(int size) {\n#ifdef MEMCHECK\n\treturn (char *) allocator.alloc(size);\n#else\n\tif (size > entry_size)\n\t\treturn (char *) valloc(size);\n\treturn allocator.alloc();\n#if 0\n\tpthread_spin_lock(&lock);\n\tassert(!free_refs.is_empty());\n\tint off = free_refs.pop_front();\n\tassert(marks[off \/ entry_size] == 0);\n\tmarks[off \/ entry_size] = 1;\n\tchar *ret = &buf[off];\n\tpthread_spin_unlock(&lock);\n\treturn ret;\n#endif\n#endif\n}\n\nvoid rand_buf::free_entry(char *buf) {\n#ifdef MEMCHECK\n\tallocator.dealloc(buf);\n#else\n\tif (allocator.contains(buf))\n\t\tallocator.free(buf);\n\telse\n\t\tfree(buf);\n#if 0\n\tpthread_spin_lock(&lock);\n\toff_t off = buf - this->buf;\n\tfree_refs.push_back(off);\n\toff \/= entry_size;\n\tif (marks[off] == 0)\n\t\tprintf(\"%ld: free %p error\\n\", pthread_self(), buf);\n\tassert(marks[off]);\n\tmarks[off] = 0;\n\tpthread_spin_unlock(&lock);\n#endif\n#endif\n}\n<commit_msg>[SAFS]: replace valloc with posix_memalign for larger mem alloc.<commit_after>\/**\n * Copyright 2013 Da Zheng\n *\n * This file is part of SAFSlib.\n *\n * SAFSlib is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * SAFSlib is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with SAFSlib. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n\n#include \"rand_buf.h\"\n\nrand_buf::rand_buf(int buf_size, int entry_size, int nodeid)\n#ifdef MEMCHECK\n\t: allocator(entry_size)\n#else\n\t\/\/ We don't initialize pages but pin them.\n\t: allocator(std::string(\"rand_buf-\") + itoa(nodeid), entry_size,\n\t\t\tbuf_size, buf_size, nodeid, false, true, 0, false)\n#endif\n{\n\tthis->entry_size = entry_size;\n}\n\nchar *rand_buf::next_entry(int size) {\n#ifdef MEMCHECK\n\treturn (char *) allocator.alloc(size);\n#else\n\tif (size > entry_size) {\n\t\tvoid *buf;\n\t\tint ret = posix_memalign(&buf, MIN_BLOCK_SIZE, size);\n\t\tassert(ret == 0);\n\t\treturn (char *) buf;\n\t}\n\treturn allocator.alloc();\n#if 0\n\tpthread_spin_lock(&lock);\n\tassert(!free_refs.is_empty());\n\tint off = free_refs.pop_front();\n\tassert(marks[off \/ entry_size] == 0);\n\tmarks[off \/ entry_size] = 1;\n\tchar *ret = &buf[off];\n\tpthread_spin_unlock(&lock);\n\treturn ret;\n#endif\n#endif\n}\n\nvoid rand_buf::free_entry(char *buf) {\n#ifdef MEMCHECK\n\tallocator.dealloc(buf);\n#else\n\tif (allocator.contains(buf))\n\t\tallocator.free(buf);\n\telse\n\t\tfree(buf);\n#if 0\n\tpthread_spin_lock(&lock);\n\toff_t off = buf - this->buf;\n\tfree_refs.push_back(off);\n\toff \/= entry_size;\n\tif (marks[off] == 0)\n\t\tprintf(\"%ld: free %p error\\n\", pthread_self(), buf);\n\tassert(marks[off]);\n\tmarks[off] = 0;\n\tpthread_spin_unlock(&lock);\n#endif\n#endif\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) Facebook, Inc. and its affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n *\/\n\n#include \"SurfaceHandler.h\"\n\n#include <react\/debug\/react_native_assert.h>\n#include <react\/renderer\/scheduler\/Scheduler.h>\n#include <react\/renderer\/uimanager\/UIManager.h>\n\nnamespace facebook {\nnamespace react {\n\nusing Status = SurfaceHandler::Status;\nusing DisplayMode = SurfaceHandler::DisplayMode;\n\nSurfaceHandler::SurfaceHandler(\n std::string const &moduleName,\n SurfaceId surfaceId) noexcept {\n parameters_.moduleName = moduleName;\n parameters_.surfaceId = surfaceId;\n}\n\nSurfaceHandler::SurfaceHandler(SurfaceHandler &&other) noexcept {\n operator=(std::move(other));\n}\n\nSurfaceHandler &SurfaceHandler::operator=(SurfaceHandler &&other) noexcept {\n std::unique_lock<better::shared_mutex> lock1(linkMutex_, std::defer_lock);\n std::unique_lock<better::shared_mutex> lock2(\n parametersMutex_, std::defer_lock);\n std::unique_lock<better::shared_mutex> lock3(\n other.linkMutex_, std::defer_lock);\n std::unique_lock<better::shared_mutex> lock4(\n other.parametersMutex_, std::defer_lock);\n std::lock(lock1, lock2, lock3, lock4);\n\n link_ = other.link_;\n parameters_ = other.parameters_;\n\n other.link_ = Link{};\n other.parameters_ = Parameters{};\n return *this;\n}\n\n#pragma mark - Surface Life-Cycle Management\n\nStatus SurfaceHandler::getStatus() const noexcept {\n std::shared_lock<better::shared_mutex> lock(linkMutex_);\n return link_.status;\n}\n\nvoid SurfaceHandler::start() const noexcept {\n {\n std::unique_lock<better::shared_mutex> lock(linkMutex_);\n react_native_assert(\n link_.status == Status::Registered && \"Surface must be registered.\");\n react_native_assert(\n getLayoutConstraints().layoutDirection != LayoutDirection::Undefined &&\n \"layoutDirection must be set.\");\n\n auto parameters = Parameters{};\n {\n std::shared_lock<better::shared_mutex> parametersLock(parametersMutex_);\n parameters = parameters_;\n }\n\n auto shadowTree = std::make_unique<ShadowTree>(\n parameters.surfaceId,\n parameters.layoutConstraints,\n parameters.layoutContext,\n *link_.uiManager);\n\n link_.shadowTree = shadowTree.get();\n\n link_.uiManager->startSurface(\n std::move(shadowTree), parameters.moduleName, parameters.props);\n\n link_.status = Status::Running;\n\n applyDisplayMode(parameters.displayMode);\n }\n}\n\nvoid SurfaceHandler::stop() const noexcept {\n auto shadowTree = ShadowTree::Unique{};\n {\n std::unique_lock<better::shared_mutex> lock(linkMutex_);\n react_native_assert(\n link_.status == Status::Running && \"Surface must be running.\");\n\n link_.status = Status::Registered;\n link_.shadowTree = nullptr;\n shadowTree = link_.uiManager->stopSurface(parameters_.surfaceId);\n }\n\n \/\/ As part of stopping a Surface, we need to properly destroy all\n \/\/ mounted views, so we need to commit an empty tree to trigger all\n \/\/ side-effects (including destroying and removing mounted views).\n react_native_assert(shadowTree && \"`shadowTree` must not be null.\");\n shadowTree->commitEmptyTree();\n}\n\nvoid SurfaceHandler::setDisplayMode(DisplayMode displayMode) const noexcept {\n {\n std::unique_lock<better::shared_mutex> lock(parametersMutex_);\n if (parameters_.displayMode == displayMode) {\n return;\n }\n\n parameters_.displayMode = displayMode;\n }\n\n {\n std::shared_lock<better::shared_mutex> lock(linkMutex_);\n\n if (link_.status != Status::Running) {\n return;\n }\n\n applyDisplayMode(displayMode);\n }\n}\n\nDisplayMode SurfaceHandler::getDisplayMode() const noexcept {\n std::shared_lock<better::shared_mutex> lock(parametersMutex_);\n return parameters_.displayMode;\n}\n\n#pragma mark - Accessors\n\nSurfaceId SurfaceHandler::getSurfaceId() const noexcept {\n std::shared_lock<better::shared_mutex> lock(parametersMutex_);\n return parameters_.surfaceId;\n}\n\nvoid SurfaceHandler::setSurfaceId(SurfaceId surfaceId) const noexcept {\n std::unique_lock<better::shared_mutex> lock(parametersMutex_);\n parameters_.surfaceId = surfaceId;\n}\n\nstd::string SurfaceHandler::getModuleName() const noexcept {\n std::shared_lock<better::shared_mutex> lock(parametersMutex_);\n return parameters_.moduleName;\n}\n\nvoid SurfaceHandler::setProps(folly::dynamic const &props) const noexcept {\n std::unique_lock<better::shared_mutex> lock(parametersMutex_);\n parameters_.props = props;\n}\n\nfolly::dynamic SurfaceHandler::getProps() const noexcept {\n std::shared_lock<better::shared_mutex> lock(parametersMutex_);\n return parameters_.props;\n}\n\nstd::shared_ptr<MountingCoordinator const>\nSurfaceHandler::getMountingCoordinator() const noexcept {\n std::shared_lock<better::shared_mutex> lock(linkMutex_);\n react_native_assert(\n link_.status != Status::Unregistered && \"Surface must be registered.\");\n react_native_assert(\n link_.shadowTree && \"`link_.shadowTree` must not be null.\");\n return link_.shadowTree->getMountingCoordinator();\n}\n\n#pragma mark - Layout\n\nSize SurfaceHandler::measure(\n LayoutConstraints const &layoutConstraints,\n LayoutContext const &layoutContext) const noexcept {\n std::shared_lock<better::shared_mutex> lock(linkMutex_);\n\n if (link_.status != Status::Running) {\n return layoutConstraints.clamp({0, 0});\n }\n\n react_native_assert(\n link_.shadowTree && \"`link_.shadowTree` must not be null.\");\n\n auto currentRootShadowNode =\n link_.shadowTree->getCurrentRevision().rootShadowNode;\n\n auto rootShadowNode =\n currentRootShadowNode->clone(layoutConstraints, layoutContext);\n rootShadowNode->layoutIfNeeded();\n return rootShadowNode->getLayoutMetrics().frame.size;\n}\n\nvoid SurfaceHandler::constraintLayout(\n LayoutConstraints const &layoutConstraints,\n LayoutContext const &layoutContext) const noexcept {\n {\n std::unique_lock<better::shared_mutex> lock(parametersMutex_);\n\n if (parameters_.layoutConstraints == layoutConstraints &&\n parameters_.layoutContext == layoutContext) {\n return;\n }\n\n parameters_.layoutConstraints = layoutConstraints;\n parameters_.layoutContext = layoutContext;\n }\n\n {\n std::shared_lock<better::shared_mutex> lock(linkMutex_);\n\n if (link_.status != Status::Running) {\n return;\n }\n\n react_native_assert(\n link_.shadowTree && \"`link_.shadowTree` must not be null.\");\n link_.shadowTree->commit([&](RootShadowNode const &oldRootShadowNode) {\n return oldRootShadowNode.clone(layoutConstraints, layoutContext);\n });\n }\n}\n\nLayoutConstraints SurfaceHandler::getLayoutConstraints() const noexcept {\n std::shared_lock<better::shared_mutex> lock(parametersMutex_);\n return parameters_.layoutConstraints;\n}\n\nLayoutContext SurfaceHandler::getLayoutContext() const noexcept {\n std::shared_lock<better::shared_mutex> lock(parametersMutex_);\n return parameters_.layoutContext;\n}\n\n#pragma mark - Private\n\nvoid SurfaceHandler::applyDisplayMode(DisplayMode displayMode) const noexcept {\n react_native_assert(\n link_.status == Status::Running && \"Surface must be running.\");\n react_native_assert(\n link_.shadowTree && \"`link_.shadowTree` must not be null.\");\n\n switch (displayMode) {\n case DisplayMode::Visible:\n link_.shadowTree->setCommitMode(ShadowTree::CommitMode::Normal);\n break;\n case DisplayMode::Suspended:\n link_.shadowTree->setCommitMode(ShadowTree::CommitMode::Suspended);\n break;\n case DisplayMode::Hidden:\n link_.shadowTree->setCommitMode(ShadowTree::CommitMode::Normal);\n \/\/ Getting a current revision.\n auto revision = link_.shadowTree->getCurrentRevision();\n \/\/ Committing an empty tree to force mounting to disassemble view\n \/\/ hierarchy.\n link_.shadowTree->commitEmptyTree();\n link_.shadowTree->setCommitMode(ShadowTree::CommitMode::Suspended);\n \/\/ Committing the current revision back. It will be mounted only when\n \/\/ `DisplayMode` is changed back to `Normal`.\n link_.shadowTree->commit([&](RootShadowNode const &oldRootShadowNode) {\n return std::static_pointer_cast<RootShadowNode>(\n revision.rootShadowNode->ShadowNode::clone(ShadowNodeFragment{}));\n });\n break;\n }\n}\n\nvoid SurfaceHandler::setUIManager(UIManager const *uiManager) const noexcept {\n std::unique_lock<better::shared_mutex> lock(linkMutex_);\n\n react_native_assert(\n link_.status != Status::Running && \"Surface must not be running.\");\n\n if (link_.uiManager == uiManager) {\n return;\n }\n\n link_.uiManager = uiManager;\n link_.status = uiManager ? Status::Registered : Status::Unregistered;\n}\n\nSurfaceHandler::~SurfaceHandler() noexcept {\n \/\/ TODO(T88046056): Fix Android memory leak before uncommenting changes\n \/\/ react_native_assert(\n \/\/ link_.status == Status::Unregistered &&\n \/\/ \"`SurfaceHandler` must be unregistered (or moved-from) before\n \/\/ deallocation.\");\n}\n\n} \/\/ namespace react\n} \/\/ namespace facebook\n<commit_msg>Update initial props when DisplayMode changes in Fabric<commit_after>\/*\n * Copyright (c) Facebook, Inc. and its affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n *\/\n\n#include \"SurfaceHandler.h\"\n\n#include <react\/debug\/react_native_assert.h>\n#include <react\/renderer\/scheduler\/Scheduler.h>\n#include <react\/renderer\/uimanager\/UIManager.h>\n\nnamespace facebook {\nnamespace react {\n\nusing Status = SurfaceHandler::Status;\nusing DisplayMode = SurfaceHandler::DisplayMode;\n\nSurfaceHandler::SurfaceHandler(\n std::string const &moduleName,\n SurfaceId surfaceId) noexcept {\n parameters_.moduleName = moduleName;\n parameters_.surfaceId = surfaceId;\n}\n\nSurfaceHandler::SurfaceHandler(SurfaceHandler &&other) noexcept {\n operator=(std::move(other));\n}\n\nSurfaceHandler &SurfaceHandler::operator=(SurfaceHandler &&other) noexcept {\n std::unique_lock<better::shared_mutex> lock1(linkMutex_, std::defer_lock);\n std::unique_lock<better::shared_mutex> lock2(\n parametersMutex_, std::defer_lock);\n std::unique_lock<better::shared_mutex> lock3(\n other.linkMutex_, std::defer_lock);\n std::unique_lock<better::shared_mutex> lock4(\n other.parametersMutex_, std::defer_lock);\n std::lock(lock1, lock2, lock3, lock4);\n\n link_ = other.link_;\n parameters_ = other.parameters_;\n\n other.link_ = Link{};\n other.parameters_ = Parameters{};\n return *this;\n}\n\n#pragma mark - Surface Life-Cycle Management\n\nStatus SurfaceHandler::getStatus() const noexcept {\n std::shared_lock<better::shared_mutex> lock(linkMutex_);\n return link_.status;\n}\n\nvoid SurfaceHandler::start() const noexcept {\n {\n std::unique_lock<better::shared_mutex> lock(linkMutex_);\n react_native_assert(\n link_.status == Status::Registered && \"Surface must be registered.\");\n react_native_assert(\n getLayoutConstraints().layoutDirection != LayoutDirection::Undefined &&\n \"layoutDirection must be set.\");\n\n auto parameters = Parameters{};\n {\n std::shared_lock<better::shared_mutex> parametersLock(parametersMutex_);\n parameters = parameters_;\n }\n\n auto shadowTree = std::make_unique<ShadowTree>(\n parameters.surfaceId,\n parameters.layoutConstraints,\n parameters.layoutContext,\n *link_.uiManager);\n\n link_.shadowTree = shadowTree.get();\n\n link_.uiManager->startSurface(\n std::move(shadowTree), parameters.moduleName, parameters.props);\n\n link_.status = Status::Running;\n\n applyDisplayMode(parameters.displayMode);\n }\n}\n\nvoid SurfaceHandler::stop() const noexcept {\n auto shadowTree = ShadowTree::Unique{};\n {\n std::unique_lock<better::shared_mutex> lock(linkMutex_);\n react_native_assert(\n link_.status == Status::Running && \"Surface must be running.\");\n\n link_.status = Status::Registered;\n link_.shadowTree = nullptr;\n shadowTree = link_.uiManager->stopSurface(parameters_.surfaceId);\n }\n\n \/\/ As part of stopping a Surface, we need to properly destroy all\n \/\/ mounted views, so we need to commit an empty tree to trigger all\n \/\/ side-effects (including destroying and removing mounted views).\n react_native_assert(shadowTree && \"`shadowTree` must not be null.\");\n shadowTree->commitEmptyTree();\n}\n\nvoid SurfaceHandler::setDisplayMode(DisplayMode displayMode) const noexcept {\n {\n std::unique_lock<better::shared_mutex> lock(parametersMutex_);\n if (parameters_.displayMode == displayMode) {\n return;\n }\n\n parameters_.displayMode = displayMode;\n }\n\n {\n std::shared_lock<better::shared_mutex> lock(linkMutex_);\n\n if (link_.status != Status::Running) {\n return;\n }\n\n link_.uiManager->setSurfaceProps(\n parameters_.surfaceId, parameters_.moduleName, parameters_.props);\n\n applyDisplayMode(displayMode);\n }\n}\n\nDisplayMode SurfaceHandler::getDisplayMode() const noexcept {\n std::shared_lock<better::shared_mutex> lock(parametersMutex_);\n return parameters_.displayMode;\n}\n\n#pragma mark - Accessors\n\nSurfaceId SurfaceHandler::getSurfaceId() const noexcept {\n std::shared_lock<better::shared_mutex> lock(parametersMutex_);\n return parameters_.surfaceId;\n}\n\nvoid SurfaceHandler::setSurfaceId(SurfaceId surfaceId) const noexcept {\n std::unique_lock<better::shared_mutex> lock(parametersMutex_);\n parameters_.surfaceId = surfaceId;\n}\n\nstd::string SurfaceHandler::getModuleName() const noexcept {\n std::shared_lock<better::shared_mutex> lock(parametersMutex_);\n return parameters_.moduleName;\n}\n\nvoid SurfaceHandler::setProps(folly::dynamic const &props) const noexcept {\n std::unique_lock<better::shared_mutex> lock(parametersMutex_);\n parameters_.props = props;\n}\n\nfolly::dynamic SurfaceHandler::getProps() const noexcept {\n std::shared_lock<better::shared_mutex> lock(parametersMutex_);\n return parameters_.props;\n}\n\nstd::shared_ptr<MountingCoordinator const>\nSurfaceHandler::getMountingCoordinator() const noexcept {\n std::shared_lock<better::shared_mutex> lock(linkMutex_);\n react_native_assert(\n link_.status != Status::Unregistered && \"Surface must be registered.\");\n react_native_assert(\n link_.shadowTree && \"`link_.shadowTree` must not be null.\");\n return link_.shadowTree->getMountingCoordinator();\n}\n\n#pragma mark - Layout\n\nSize SurfaceHandler::measure(\n LayoutConstraints const &layoutConstraints,\n LayoutContext const &layoutContext) const noexcept {\n std::shared_lock<better::shared_mutex> lock(linkMutex_);\n\n if (link_.status != Status::Running) {\n return layoutConstraints.clamp({0, 0});\n }\n\n react_native_assert(\n link_.shadowTree && \"`link_.shadowTree` must not be null.\");\n\n auto currentRootShadowNode =\n link_.shadowTree->getCurrentRevision().rootShadowNode;\n\n auto rootShadowNode =\n currentRootShadowNode->clone(layoutConstraints, layoutContext);\n rootShadowNode->layoutIfNeeded();\n return rootShadowNode->getLayoutMetrics().frame.size;\n}\n\nvoid SurfaceHandler::constraintLayout(\n LayoutConstraints const &layoutConstraints,\n LayoutContext const &layoutContext) const noexcept {\n {\n std::unique_lock<better::shared_mutex> lock(parametersMutex_);\n\n if (parameters_.layoutConstraints == layoutConstraints &&\n parameters_.layoutContext == layoutContext) {\n return;\n }\n\n parameters_.layoutConstraints = layoutConstraints;\n parameters_.layoutContext = layoutContext;\n }\n\n {\n std::shared_lock<better::shared_mutex> lock(linkMutex_);\n\n if (link_.status != Status::Running) {\n return;\n }\n\n react_native_assert(\n link_.shadowTree && \"`link_.shadowTree` must not be null.\");\n link_.shadowTree->commit([&](RootShadowNode const &oldRootShadowNode) {\n return oldRootShadowNode.clone(layoutConstraints, layoutContext);\n });\n }\n}\n\nLayoutConstraints SurfaceHandler::getLayoutConstraints() const noexcept {\n std::shared_lock<better::shared_mutex> lock(parametersMutex_);\n return parameters_.layoutConstraints;\n}\n\nLayoutContext SurfaceHandler::getLayoutContext() const noexcept {\n std::shared_lock<better::shared_mutex> lock(parametersMutex_);\n return parameters_.layoutContext;\n}\n\n#pragma mark - Private\n\nvoid SurfaceHandler::applyDisplayMode(DisplayMode displayMode) const noexcept {\n react_native_assert(\n link_.status == Status::Running && \"Surface must be running.\");\n react_native_assert(\n link_.shadowTree && \"`link_.shadowTree` must not be null.\");\n\n switch (displayMode) {\n case DisplayMode::Visible:\n link_.shadowTree->setCommitMode(ShadowTree::CommitMode::Normal);\n break;\n case DisplayMode::Suspended:\n link_.shadowTree->setCommitMode(ShadowTree::CommitMode::Suspended);\n break;\n case DisplayMode::Hidden:\n link_.shadowTree->setCommitMode(ShadowTree::CommitMode::Normal);\n \/\/ Getting a current revision.\n auto revision = link_.shadowTree->getCurrentRevision();\n \/\/ Committing an empty tree to force mounting to disassemble view\n \/\/ hierarchy.\n link_.shadowTree->commitEmptyTree();\n link_.shadowTree->setCommitMode(ShadowTree::CommitMode::Suspended);\n \/\/ Committing the current revision back. It will be mounted only when\n \/\/ `DisplayMode` is changed back to `Normal`.\n link_.shadowTree->commit([&](RootShadowNode const &oldRootShadowNode) {\n return std::static_pointer_cast<RootShadowNode>(\n revision.rootShadowNode->ShadowNode::clone(ShadowNodeFragment{}));\n });\n break;\n }\n}\n\nvoid SurfaceHandler::setUIManager(UIManager const *uiManager) const noexcept {\n std::unique_lock<better::shared_mutex> lock(linkMutex_);\n\n react_native_assert(\n link_.status != Status::Running && \"Surface must not be running.\");\n\n if (link_.uiManager == uiManager) {\n return;\n }\n\n link_.uiManager = uiManager;\n link_.status = uiManager ? Status::Registered : Status::Unregistered;\n}\n\nSurfaceHandler::~SurfaceHandler() noexcept {\n \/\/ TODO(T88046056): Fix Android memory leak before uncommenting changes\n \/\/ react_native_assert(\n \/\/ link_.status == Status::Unregistered &&\n \/\/ \"`SurfaceHandler` must be unregistered (or moved-from) before\n \/\/ deallocation.\");\n}\n\n} \/\/ namespace react\n} \/\/ namespace facebook\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (C) 2016 xaizek <xaizek@openmailbox.org>\n\/\/\n\/\/ This file is part of uncov.\n\/\/\n\/\/ uncov is free software: you can redistribute it and\/or modify\n\/\/ it under the terms of the GNU Affero General Public License as published by\n\/\/ the Free Software Foundation, either version 3 of the License, or\n\/\/ (at your option) any later version.\n\/\/\n\/\/ uncov is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n\/\/ GNU Affero General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Affero General Public License\n\/\/ along with uncov. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n\n#ifndef UNCOV__COVERAGE_HPP__\n#define UNCOV__COVERAGE_HPP__\n\n#include <string>\n\nclass CovInfo\n{\n friend class CovChange;\n\npublic:\n CovInfo() = default;\n template <typename T>\n explicit CovInfo(const T &coverable)\n : coveredCount(coverable.getCoveredCount()),\n missedCount(coverable.getMissedCount())\n {\n }\n\npublic:\n void add(const CovInfo &rhs);\n std::string formatCoverageRate() const;\n std::string formatLines(const std::string &separator) const;\n\nprivate:\n float getCoverage() const;\n int getRelevantLines() const;\n\nprivate:\n int coveredCount = 0;\n int missedCount = 0;\n};\n\nclass CovChange\n{\npublic:\n CovChange(const CovInfo &oldCov, const CovInfo &newCov);\n\npublic:\n bool isChanged() const;\n std::string formatCoverageRate() const;\n std::string formatLines(const std::string &separator, int width = 0) const;\n\nprivate:\n float coverageChange;\n int coveredChange;\n int missedChange;\n int relevantChange;\n};\n\n#endif \/\/ UNCOV__COVERAGE_HPP__\n<commit_msg>Document coverage.hpp header<commit_after>\/\/ Copyright (C) 2016 xaizek <xaizek@openmailbox.org>\n\/\/\n\/\/ This file is part of uncov.\n\/\/\n\/\/ uncov is free software: you can redistribute it and\/or modify\n\/\/ it under the terms of the GNU Affero General Public License as published by\n\/\/ the Free Software Foundation, either version 3 of the License, or\n\/\/ (at your option) any later version.\n\/\/\n\/\/ uncov is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n\/\/ GNU Affero General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Affero General Public License\n\/\/ along with uncov. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n\n#ifndef UNCOV__COVERAGE_HPP__\n#define UNCOV__COVERAGE_HPP__\n\n#include <string>\n\n\/**\n * @file coverage.hpp\n *\n * Coverage computation and formatting.\n *\/\n\n\/**\n * @brief Computes and formats coverage conformation.\n *\/\nclass CovInfo\n{\n \/\/! To give access to @c coveredCount and @c missedCount.\n friend class CovChange;\n\npublic:\n \/**\n * @brief Constructs empty coverage information.\n *\/\n CovInfo() = default;\n \/**\n * @brief Constructs coverage information from a Coverable.\n *\n * Coverable is any class that implements @c getCoveredCount() and\n * @c getMissedCount() functions that return @c int.\n *\n * @tparam T Type of the Coverable.\n *\n * @param coverable Source of the coverage information.\n *\/\n template <typename T>\n explicit CovInfo(const T &coverable)\n : coveredCount(coverable.getCoveredCount()),\n missedCount(coverable.getMissedCount())\n {\n }\n\npublic:\n \/**\n * @brief Adds coverage information.\n *\n * @param rhs Another coverage information.\n *\/\n void add(const CovInfo &rhs);\n \/**\n * @brief Formats coverage rate in the new state as a string.\n *\n * @returns Formatted string.\n *\/\n std::string formatCoverageRate() const;\n \/**\n * @brief Formats coverage statistics in lines.\n *\n * Format is covered\/missed\/relevant.\n *\n * @param separator Separator of statistics.\n *\n * @returns Formatted string.\n *\/\n std::string formatLines(const std::string &separator) const;\n\nprivate:\n \/**\n * @brief Retrieves rate of source coverage.\n *\n * @returns The rate.\n *\/\n float getCoverage() const;\n \/**\n * @brief Retrieves number of lines that are relevant for code coverage.\n *\n * @returns The number.\n *\/\n int getRelevantLines() const;\n\nprivate:\n int coveredCount = 0; \/\/!< Number of covered lines.\n int missedCount = 0; \/\/!< Number of missed lines.\n};\n\n\/**\n * @brief Computes and formats coverage change.\n *\/\nclass CovChange\n{\npublic:\n \/**\n * @brief Computes coverage change between two states.\n *\n * @param oldCov Old coverage information.\n * @param newCov New coverage information.\n *\/\n CovChange(const CovInfo &oldCov, const CovInfo &newCov);\n\npublic:\n \/**\n * @brief Whether new coverage information differs from the old one.\n *\n * @returns @c true if so, @c false otherwise.\n *\/\n bool isChanged() const;\n \/**\n * @brief Formats change of coverage rate in the new state as a string.\n *\n * @returns Formatted string.\n *\/\n std::string formatCoverageRate() const;\n \/**\n * @brief Formats changes coverage statistics in lines.\n *\n * Format is covered\/missed\/relevant.\n *\n * @param separator Separator of statistics.\n * @param width Minimal width for first and second statistics.\n *\n * @returns Formatted string.\n *\/\n std::string formatLines(const std::string &separator, int width = 0) const;\n\nprivate:\n float coverageChange; \/\/!< Change of covered lines in percents.\n int coveredChange; \/\/!< Change of covered lines in lines.\n int missedChange; \/\/!< Change of missed lines in lines.\n int relevantChange; \/\/!< Change of relevant lines in lines.\n};\n\n#endif \/\/ UNCOV__COVERAGE_HPP__\n<|endoftext|>"} {"text":"<commit_before>\/\/=======================================================================\n\/\/ Copyright (c) 2013-2020 Baptiste Wicht.\n\/\/ Distributed under the terms of the MIT License.\n\/\/ (See accompanying file LICENSE or copy at\n\/\/ http:\/\/opensource.org\/licenses\/MIT)\n\/\/=======================================================================\n\n#include <tuple>\n#include <utility>\n#include <iostream>\n\n#include \"currency.hpp\"\n#include \"assets.hpp\" \/\/ For get_default_currency\n#include \"http.hpp\"\n#include \"date.hpp\"\n#include \"config.hpp\"\n#include \"server_lock.hpp\"\n\nnamespace {\n\nstruct currency_cache_key {\n budget::date date;\n std::string from;\n std::string to;\n\n currency_cache_key(budget::date date, std::string from, std::string to) : date(date), from(from), to(to) {}\n\n friend bool operator==(const currency_cache_key & lhs, const currency_cache_key & rhs){\n if (lhs.date != rhs.date) {\n return false;\n }\n\n if (lhs.from != rhs.from) {\n return false;\n }\n\n return lhs.to == rhs.to;\n }\n};\n\n} \/\/ end of anonymous namespace\n\nnamespace std {\n\ntemplate <>\nstruct hash<currency_cache_key> {\n std::size_t operator()(const currency_cache_key & key) const noexcept {\n auto seed = std::hash<budget::date>()(key.date);\n seed ^= std::hash<std::string>()(key.from) + 0x9e3779b9 + (seed<<6) + (seed>>2);\n seed ^= std::hash<std::string>()(key.to) + 0x9e3779b9 + (seed<<6) + (seed>>2);\n return seed;\n }\n};\n\n} \/\/ end of namespace std\n\nnamespace {\n\n\/\/ OPTIM: If necessary, this could be made faster with a two layer cache\n\/\/ We can take advantages from the low number of currency pair in the first layer\n\/\/ and then the quick hash from the high number of dates\n\nstd::unordered_map<currency_cache_key, double> exchanges;\nbudget::server_lock exchanges_lock;\n\n\/\/ V1 is using free.currencyconverterapi.com\ndouble get_rate_v1(const std::string& from, const std::string& to){\n httplib::Client cli(\"free.currencyconverterapi.com\", 80);\n\n std::string api_complete = \"\/api\/v3\/convert?q=\" + from + \"_\" + to + \"&compact=ultra\";\n\n auto res = cli.Get(api_complete.c_str());\n\n if (!res) {\n std::cout << \"Error accessing exchange rates (no response), setting exchange between \" << from << \" to \" << to << \" to 1\/1\" << std::endl;\n\n return 1.0;\n } else if (res->status != 200) {\n std::cout << \"Error accessing exchange rates (not OK), setting exchange between \" << from << \" to \" << to << \" to 1\/1\" << std::endl;\n\n return 1.0;\n } else {\n auto& buffer = res->body;\n\n if (buffer.find(':') == std::string::npos || buffer.find('}') == std::string::npos) {\n std::cout << \"Error parsing exchange rates, setting exchange between \" << from << \" to \" << to << \" to 1\/1\" << std::endl;\n\n return 1.0;\n } else {\n std::string ratio_result(buffer.begin() + buffer.find(':') + 1, buffer.begin() + buffer.find('}'));\n\n return atof(ratio_result.c_str());\n }\n }\n}\n\n\/\/ V2 is using api.exchangeratesapi.io\ndouble get_rate_v2(const std::string& from, const std::string& to, const std::string& date = \"latest\") {\n httplib::SSLClient cli(\"api.exchangeratesapi.io\", 443);\n\n std::string api_complete = \"\/\" + date + \"?symbols=\" + to + \"&base=\" + from;\n\n auto res = cli.Get(api_complete.c_str());\n\n if (!res) {\n std::cout << \"ERROR: Currency(v2): No response, setting exchange between \" << from << \" to \" << to << \" to 1\/1\" << std::endl;\n std::cout << \"ERROR: Currency(v2): URL is \" << api_complete << std::endl;\n\n return 1.0;\n } else if (res->status != 200) {\n std::cout << \"ERROR: Currency(v2): Error response \" << res->status << \", setting exchange between \" << from << \" to \" << to << \" to 1\/1\" << std::endl;\n std::cout << \"ERROR: Currency(v2): URL is \" << api_complete << std::endl;\n std::cout << \"ERROR: Currency(v2): Response is \" << res->body << std::endl;\n\n return 1.0;\n } else {\n auto& buffer = res->body;\n auto index = \"\\\"\" + to + \"\\\":\";\n\n if (buffer.find(index) == std::string::npos || buffer.find('}') == std::string::npos) {\n std::cout << \"ERROR: Currency(v2): Error parsing exchange rates, setting exchange between \" << from << \" to \" << to << \" to 1\/1\" << std::endl;\n std::cout << \"ERROR: Currency(v2): URL is \" << api_complete << std::endl;\n std::cout << \"ERROR: Currency(v2): Response is \" << res->body << std::endl;\n\n return 1.0;\n } else {\n std::string ratio_result(buffer.begin() + buffer.find(index) + index.size(), buffer.begin() + buffer.find('}'));\n\n return atof(ratio_result.c_str());\n }\n }\n}\n\n} \/\/ end of anonymous namespace\n\nvoid budget::load_currency_cache(){\n std::string file_path = budget::path_to_budget_file(\"currency.cache\");\n std::ifstream file(file_path);\n\n if (!file.is_open() || !file.good()){\n std::cout << \"INFO: Impossible to load Currency Cache\" << std::endl;\n return;\n }\n\n std::string line;\n while (file.good() && getline(file, line)) {\n if (line.empty()) {\n continue;\n }\n\n auto parts = split(line, ':');\n\n currency_cache_key key(date_from_string(parts[0]), parts[1], parts[2]);\n exchanges[key] = budget::to_number<double>(parts[3]);\n }\n\n if (budget::is_server_running()) {\n std::cout << \"INFO: Currency Cache has been loaded from \" << file_path << std::endl;\n std::cout << \"INFO: Currency Cache has \" << exchanges.size() << \" entries \" << std::endl;\n }\n}\n\nvoid budget::save_currency_cache() {\n std::string file_path = budget::path_to_budget_file(\"currency.cache\");\n std::ofstream file(file_path);\n\n if (!file.is_open() || !file.good()){\n std::cout << \"INFO: Impossible to save Currency Cache\" << std::endl;\n return;\n }\n\n {\n server_lock_guard l(exchanges_lock);\n\n for (auto & [key, value] : exchanges) {\n if (value != 1.0) {\n file << key.date << ':' << key.from << ':' << key.to << ':' << value << std::endl;\n }\n }\n }\n\n if (budget::is_server_running()) {\n std::cout << \"INFO: Currency Cache has been saved to \" << file_path << std::endl;\n std::cout << \"INFO: Currency Cache has \" << exchanges.size() << \" entries \" << std::endl;\n }\n}\n\nvoid budget::refresh_currency_cache(){\n std::unordered_map<currency_cache_key, double> copy;\n\n {\n server_lock_guard l(exchanges_lock);\n\n copy = exchanges;\n }\n\n \/\/ Refresh\/Prefetch the current exchange rates\n for (auto & pair : copy) {\n auto& key = pair.first;\n\n exchange_rate(key.from, key.to);\n }\n\n if (budget::is_server_running()) {\n std::cout << \"INFO: Currency Cache has been refreshed\" << std::endl;\n std::cout << \"INFO: Currency Cache has \" << exchanges.size() << \" entries \" << std::endl;\n }\n}\n\ndouble budget::exchange_rate(const std::string& from){\n return exchange_rate(from, get_default_currency());\n}\n\ndouble budget::exchange_rate(const std::string& from, const std::string& to){\n return exchange_rate(from, to, budget::local_day());\n}\n\ndouble budget::exchange_rate(const std::string& from, budget::date d){\n return exchange_rate(from, get_default_currency(), d);\n}\n\ndouble budget::exchange_rate(const std::string& from, const std::string& to, budget::date d){\n assert(from != \"DESIRED\" && to != \"DESIRED\");\n\n if (from == to) {\n return 1.0;\n } else {\n currency_cache_key key(d, from, to);\n\n \/\/ Return directly if we already have the data in cache\n {\n server_lock_guard l(exchanges_lock);\n\n if (exchanges.find(key) != exchanges.end()) {\n return exchanges[key];\n }\n }\n\n \/\/ Otherwise, make the API call without the lock\n\n auto rate = get_rate_v2(from, to, date_to_string(d));\n\n if (budget::is_server_running()) {\n std::cout << \"INFO: Currency: Rate (\" << d << \")\"\n << \" from \" << from << \" to \" << to << \" = \" << rate << std::endl;\n }\n\n \/\/ Update the cache and the reverse cache with the lock\n\n currency_cache_key reverse_key(d, to, from);\n\n {\n server_lock_guard l(exchanges_lock);\n\n exchanges[key] = rate;\n exchanges[reverse_key] = 1.0 \/ rate;\n }\n\n return rate;\n }\n}\n<commit_msg>Do not query exchange rate in the future<commit_after>\/\/=======================================================================\n\/\/ Copyright (c) 2013-2020 Baptiste Wicht.\n\/\/ Distributed under the terms of the MIT License.\n\/\/ (See accompanying file LICENSE or copy at\n\/\/ http:\/\/opensource.org\/licenses\/MIT)\n\/\/=======================================================================\n\n#include <tuple>\n#include <utility>\n#include <iostream>\n\n#include \"currency.hpp\"\n#include \"assets.hpp\" \/\/ For get_default_currency\n#include \"http.hpp\"\n#include \"date.hpp\"\n#include \"config.hpp\"\n#include \"server_lock.hpp\"\n\nnamespace {\n\nstruct currency_cache_key {\n budget::date date;\n std::string from;\n std::string to;\n\n currency_cache_key(budget::date date, std::string from, std::string to) : date(date), from(from), to(to) {}\n\n friend bool operator==(const currency_cache_key & lhs, const currency_cache_key & rhs){\n if (lhs.date != rhs.date) {\n return false;\n }\n\n if (lhs.from != rhs.from) {\n return false;\n }\n\n return lhs.to == rhs.to;\n }\n};\n\n} \/\/ end of anonymous namespace\n\nnamespace std {\n\ntemplate <>\nstruct hash<currency_cache_key> {\n std::size_t operator()(const currency_cache_key & key) const noexcept {\n auto seed = std::hash<budget::date>()(key.date);\n seed ^= std::hash<std::string>()(key.from) + 0x9e3779b9 + (seed<<6) + (seed>>2);\n seed ^= std::hash<std::string>()(key.to) + 0x9e3779b9 + (seed<<6) + (seed>>2);\n return seed;\n }\n};\n\n} \/\/ end of namespace std\n\nnamespace {\n\n\/\/ OPTIM: If necessary, this could be made faster with a two layer cache\n\/\/ We can take advantages from the low number of currency pair in the first layer\n\/\/ and then the quick hash from the high number of dates\n\nstd::unordered_map<currency_cache_key, double> exchanges;\nbudget::server_lock exchanges_lock;\n\n\/\/ V1 is using free.currencyconverterapi.com\ndouble get_rate_v1(const std::string& from, const std::string& to){\n httplib::Client cli(\"free.currencyconverterapi.com\", 80);\n\n std::string api_complete = \"\/api\/v3\/convert?q=\" + from + \"_\" + to + \"&compact=ultra\";\n\n auto res = cli.Get(api_complete.c_str());\n\n if (!res) {\n std::cout << \"Error accessing exchange rates (no response), setting exchange between \" << from << \" to \" << to << \" to 1\/1\" << std::endl;\n\n return 1.0;\n } else if (res->status != 200) {\n std::cout << \"Error accessing exchange rates (not OK), setting exchange between \" << from << \" to \" << to << \" to 1\/1\" << std::endl;\n\n return 1.0;\n } else {\n auto& buffer = res->body;\n\n if (buffer.find(':') == std::string::npos || buffer.find('}') == std::string::npos) {\n std::cout << \"Error parsing exchange rates, setting exchange between \" << from << \" to \" << to << \" to 1\/1\" << std::endl;\n\n return 1.0;\n } else {\n std::string ratio_result(buffer.begin() + buffer.find(':') + 1, buffer.begin() + buffer.find('}'));\n\n return atof(ratio_result.c_str());\n }\n }\n}\n\n\/\/ V2 is using api.exchangeratesapi.io\ndouble get_rate_v2(const std::string& from, const std::string& to, const std::string& date = \"latest\") {\n httplib::SSLClient cli(\"api.exchangeratesapi.io\", 443);\n\n std::string api_complete = \"\/\" + date + \"?symbols=\" + to + \"&base=\" + from;\n\n auto res = cli.Get(api_complete.c_str());\n\n if (!res) {\n std::cout << \"ERROR: Currency(v2): No response, setting exchange between \" << from << \" to \" << to << \" to 1\/1\" << std::endl;\n std::cout << \"ERROR: Currency(v2): URL is \" << api_complete << std::endl;\n\n return 1.0;\n } else if (res->status != 200) {\n std::cout << \"ERROR: Currency(v2): Error response \" << res->status << \", setting exchange between \" << from << \" to \" << to << \" to 1\/1\" << std::endl;\n std::cout << \"ERROR: Currency(v2): URL is \" << api_complete << std::endl;\n std::cout << \"ERROR: Currency(v2): Response is \" << res->body << std::endl;\n\n return 1.0;\n } else {\n auto& buffer = res->body;\n auto index = \"\\\"\" + to + \"\\\":\";\n\n if (buffer.find(index) == std::string::npos || buffer.find('}') == std::string::npos) {\n std::cout << \"ERROR: Currency(v2): Error parsing exchange rates, setting exchange between \" << from << \" to \" << to << \" to 1\/1\" << std::endl;\n std::cout << \"ERROR: Currency(v2): URL is \" << api_complete << std::endl;\n std::cout << \"ERROR: Currency(v2): Response is \" << res->body << std::endl;\n\n return 1.0;\n } else {\n std::string ratio_result(buffer.begin() + buffer.find(index) + index.size(), buffer.begin() + buffer.find('}'));\n\n return atof(ratio_result.c_str());\n }\n }\n}\n\n} \/\/ end of anonymous namespace\n\nvoid budget::load_currency_cache(){\n std::string file_path = budget::path_to_budget_file(\"currency.cache\");\n std::ifstream file(file_path);\n\n if (!file.is_open() || !file.good()){\n std::cout << \"INFO: Impossible to load Currency Cache\" << std::endl;\n return;\n }\n\n std::string line;\n while (file.good() && getline(file, line)) {\n if (line.empty()) {\n continue;\n }\n\n auto parts = split(line, ':');\n\n currency_cache_key key(date_from_string(parts[0]), parts[1], parts[2]);\n exchanges[key] = budget::to_number<double>(parts[3]);\n }\n\n if (budget::is_server_running()) {\n std::cout << \"INFO: Currency Cache has been loaded from \" << file_path << std::endl;\n std::cout << \"INFO: Currency Cache has \" << exchanges.size() << \" entries \" << std::endl;\n }\n}\n\nvoid budget::save_currency_cache() {\n std::string file_path = budget::path_to_budget_file(\"currency.cache\");\n std::ofstream file(file_path);\n\n if (!file.is_open() || !file.good()){\n std::cout << \"INFO: Impossible to save Currency Cache\" << std::endl;\n return;\n }\n\n {\n server_lock_guard l(exchanges_lock);\n\n for (auto & [key, value] : exchanges) {\n if (value != 1.0) {\n file << key.date << ':' << key.from << ':' << key.to << ':' << value << std::endl;\n }\n }\n }\n\n if (budget::is_server_running()) {\n std::cout << \"INFO: Currency Cache has been saved to \" << file_path << std::endl;\n std::cout << \"INFO: Currency Cache has \" << exchanges.size() << \" entries \" << std::endl;\n }\n}\n\nvoid budget::refresh_currency_cache(){\n std::unordered_map<currency_cache_key, double> copy;\n\n {\n server_lock_guard l(exchanges_lock);\n\n copy = exchanges;\n }\n\n \/\/ Refresh\/Prefetch the current exchange rates\n for (auto & pair : copy) {\n auto& key = pair.first;\n\n exchange_rate(key.from, key.to);\n }\n\n if (budget::is_server_running()) {\n std::cout << \"INFO: Currency Cache has been refreshed\" << std::endl;\n std::cout << \"INFO: Currency Cache has \" << exchanges.size() << \" entries \" << std::endl;\n }\n}\n\ndouble budget::exchange_rate(const std::string& from){\n return exchange_rate(from, get_default_currency());\n}\n\ndouble budget::exchange_rate(const std::string& from, const std::string& to){\n return exchange_rate(from, to, budget::local_day());\n}\n\ndouble budget::exchange_rate(const std::string& from, budget::date d){\n return exchange_rate(from, get_default_currency(), d);\n}\n\ndouble budget::exchange_rate(const std::string& from, const std::string& to, budget::date d){\n assert(from != \"DESIRED\" && to != \"DESIRED\");\n\n if (from == to) {\n return 1.0;\n } else if (d > budget::local_day()) {\n return exchange_rate(from, to, budget::local_day());\n } else {\n currency_cache_key key(d, from, to);\n\n \/\/ Return directly if we already have the data in cache\n {\n server_lock_guard l(exchanges_lock);\n\n if (exchanges.find(key) != exchanges.end()) {\n return exchanges[key];\n }\n }\n\n \/\/ Otherwise, make the API call without the lock\n\n auto rate = get_rate_v2(from, to, date_to_string(d));\n\n if (budget::is_server_running()) {\n std::cout << \"INFO: Currency: Rate (\" << d << \")\"\n << \" from \" << from << \" to \" << to << \" = \" << rate << std::endl;\n }\n\n \/\/ Update the cache and the reverse cache with the lock\n\n currency_cache_key reverse_key(d, to, from);\n\n {\n server_lock_guard l(exchanges_lock);\n\n exchanges[key] = rate;\n exchanges[reverse_key] = 1.0 \/ rate;\n }\n\n return rate;\n }\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"database.h\"\n\nMYSQL *DB_conn = NULL;\nMYSQL_RES *DB_result = NULL;\nFILE * DB_log = NULL;\n\nchar DB_buf[16384];\n\nvoid DB_connect() {\n DB_log = fopen(\"database.log\",\"w\");\n\n DB_conn = mysql_init(NULL);\n \n if (DB_conn == NULL) {\n fprintf(DB_log, \"Error %u: %s\\n\", mysql_errno(DB_conn), mysql_error(DB_conn));\n return;\n }\n\n if (mysql_real_connect(DB_conn, DB_HOST, DB_USER, DB_PASS, DB_NAME, 0, NULL, 0) == NULL) {\n fprintf(DB_log,\"Error %u: %s\\n\", mysql_errno(DB_conn), mysql_error(DB_conn));\n return;\n }\n \n fprintf(DB_log,\"Database connecton established.\\n\");\n}\n\nvoid DB_query(char* item ...) {\n char query[1024];\n int i = 0;\n \n query[0] = 0x00;\n \n \/\/\/ Connect to the DB if necessary\n \n if(!DB_conn) DB_connect();\n \n \/\/\/ Assemble the query\n\n va_list v;\n va_start(v, item);\n \n while( item[i] != 0x00 && i < 1000) {\n if(item[i] == '%' && item[i+1] == 'd') {\n sprintf(query,\"%s%d\",query,va_arg(v,int));\n i++;\n } else if(item[i] == '%' && item[i+1] == 'f') {\n sprintf(query,\"%s%f\",query,va_arg(v,double));\n i++;\n } else if(item[i] == '%' && item[i+1] == 's') {\n sprintf(query,\"%s%s\",query,va_arg(v,char*));\n i++;\n } else {\n sprintf(query,\"%s%c\",query,item[i]);\n }\n i++; \n }\n \n va_end(v);\n fprintf(DB_log, \"Executing Query: %s\\n\",query);\n\n \/\/\/ Execute the query\n \n mysql_query(DB_conn, query);\n DB_result = mysql_store_result(DB_conn);\n \n fprintf(DB_log, \"Rows Returned: %d\\n\",mysql_num_rows(DB_result));\n}\n\nchar* DB_resultAsText() {\n int i = 0;\n MYSQL_ROW row;\n int num_fields;\n\n DB_buf[0] = 0x00;\n \n num_fields = mysql_num_fields(DB_result);\n \n while ((row = mysql_fetch_row(DB_result)))\n {\n for(i = 0; i < num_fields; i++)\n {\n sprintf(DB_buf,\"%s%s \",DB_buf, row[i] ? row[i] : \"NULL\");\n }\n sprintf(DB_buf,\"%s\\n\",DB_buf);\n }\n \n mysql_free_result(DB_result); \n\n return DB_buf;\n}\n\nvector<string> DB_getAllDevices() {\n DB_query(\"select distinct DeviceID from aip order by DeviceID ASC;\");\n\n int i = 0;\n MYSQL_ROW row;\n int num_fields;\n \n vector<string> result;\n\n num_fields = mysql_num_fields(DB_result);\n \n while ((row = mysql_fetch_row(DB_result))) {\n DB_buf[0] = 0x00;\n sprintf(DB_buf,\"%s%s \",DB_buf, row[i] ? row[i] : \"NULL\");\n string tmp = string(DB_buf);\n result.push_back(tmp);\n }\n \n mysql_free_result(DB_result); \n\n return result;\n}\n\nmap<string, string> DB_getMostRecentGPS(int device_id) {\n DB_query(\"select Altitude, Rate, Lat, LatRef, Lon, LonRef, Spd, Hdg, Status from gps where DeviceID=%d and Lat != 0 order by Timestamp desc limit 1;\",device_id);\n\n MYSQL_ROW row;\n int num_fields;\n \n map<string, string> result;\n\n num_fields = mysql_num_fields(DB_result);\n \n if (row = mysql_fetch_row(DB_result)) {\n result[\"Altitude\"] = string(row[0]);\n result[\"Rate\"] = string(row[1]);\n result[\"Lat\"] = string(row[2]);\n result[\"LatRef\"] = string(row[3]);\n result[\"Latitude\"] = string(row[2]) + string(row[3]);\n result[\"Lon\"] = string(row[4]);\n result[\"LonRef\"] = string(row[5]);\n result[\"Longitude\"] = string(row[4]) + string(row[5]);\n result[\"Spd\"] = string(row[6]);\n result[\"Hdg\"] = string(row[7]);\n result[\"Status\"] = string(row[8]);\n }\n \n mysql_free_result(DB_result);\n\n return result;\n}\n\nPlot DB_getPlotData(char* table, char* data_column, int device_id) {\n DB_query(\"select UNIX_TIMESTAMP(Timestamp)-UNIX_TIMESTAMP(), Altitude, %s from %s \" \n \"where DeviceId=%d \"\n \"order by Timestamp asc;\",\n data_column, table, device_id);\n Plot result;\n\n MYSQL_ROW row;\n\n while (row = mysql_fetch_row(DB_result)) {\n result.time.push_back(strtod(row[0],NULL));\n result.altitude.push_back(strtod(row[1],NULL));\n result.data.push_back(strtod(row[2],NULL));\n }\n\n mysql_free_result(DB_result); \n \n return result;\n}\n<commit_msg>- added units for status display<commit_after>#include \"database.h\"\n\nMYSQL *DB_conn = NULL;\nMYSQL_RES *DB_result = NULL;\nFILE * DB_log = NULL;\n\nchar DB_buf[16384];\n\nvoid DB_connect() {\n DB_log = fopen(\"database.log\",\"w\");\n\n DB_conn = mysql_init(NULL);\n \n if (DB_conn == NULL) {\n fprintf(DB_log, \"Error %u: %s\\n\", mysql_errno(DB_conn), mysql_error(DB_conn));\n return;\n }\n\n if (mysql_real_connect(DB_conn, DB_HOST, DB_USER, DB_PASS, DB_NAME, 0, NULL, 0) == NULL) {\n fprintf(DB_log,\"Error %u: %s\\n\", mysql_errno(DB_conn), mysql_error(DB_conn));\n return;\n }\n \n fprintf(DB_log,\"Database connecton established.\\n\");\n}\n\nvoid DB_query(char* item ...) {\n char query[1024];\n int i = 0;\n \n query[0] = 0x00;\n \n \/\/\/ Connect to the DB if necessary\n \n if(!DB_conn) DB_connect();\n \n \/\/\/ Assemble the query\n\n va_list v;\n va_start(v, item);\n \n while( item[i] != 0x00 && i < 1000) {\n if(item[i] == '%' && item[i+1] == 'd') {\n sprintf(query,\"%s%d\",query,va_arg(v,int));\n i++;\n } else if(item[i] == '%' && item[i+1] == 'f') {\n sprintf(query,\"%s%f\",query,va_arg(v,double));\n i++;\n } else if(item[i] == '%' && item[i+1] == 's') {\n sprintf(query,\"%s%s\",query,va_arg(v,char*));\n i++;\n } else {\n sprintf(query,\"%s%c\",query,item[i]);\n }\n i++; \n }\n \n va_end(v);\n fprintf(DB_log, \"Executing Query: %s\\n\",query);\n\n \/\/\/ Execute the query\n \n mysql_query(DB_conn, query);\n DB_result = mysql_store_result(DB_conn);\n \n fprintf(DB_log, \"Rows Returned: %d\\n\",mysql_num_rows(DB_result));\n}\n\nchar* DB_resultAsText() {\n int i = 0;\n MYSQL_ROW row;\n int num_fields;\n\n DB_buf[0] = 0x00;\n \n num_fields = mysql_num_fields(DB_result);\n \n while ((row = mysql_fetch_row(DB_result)))\n {\n for(i = 0; i < num_fields; i++)\n {\n sprintf(DB_buf,\"%s%s \",DB_buf, row[i] ? row[i] : \"NULL\");\n }\n sprintf(DB_buf,\"%s\\n\",DB_buf);\n }\n \n mysql_free_result(DB_result); \n\n return DB_buf;\n}\n\nvector<string> DB_getAllDevices() {\n DB_query(\"select distinct DeviceID from aip order by DeviceID ASC;\");\n\n int i = 0;\n MYSQL_ROW row;\n int num_fields;\n \n vector<string> result;\n\n num_fields = mysql_num_fields(DB_result);\n \n while ((row = mysql_fetch_row(DB_result))) {\n DB_buf[0] = 0x00;\n sprintf(DB_buf,\"%s%s \",DB_buf, row[i] ? row[i] : \"NULL\");\n string tmp = string(DB_buf);\n result.push_back(tmp);\n }\n \n mysql_free_result(DB_result); \n\n return result;\n}\n\nmap<string, string> DB_getMostRecentGPS(int device_id) {\n DB_query(\"select Altitude, Rate, Lat, LatRef, Lon, LonRef, Spd, Hdg, Status from gps where DeviceID=%d and Lat != 0 order by Timestamp desc limit 1;\",device_id);\n\n MYSQL_ROW row;\n int num_fields;\n \n char buf[64];\n \n const float M_TO_FT = 3.2808399;\n const float KNOT_TO_MPS = 0.514444444;\n \n map<string, string> result;\n\n num_fields = mysql_num_fields(DB_result);\n \n if (row = mysql_fetch_row(DB_result)) {\n result[\"Altitude\"] = string(row[0]);\n result[\"Altitude_m\"] = string(row[0]);\n sprintf(buf,\"%d\",(int)(atoi(row[0])*M_TO_FT));\n result[\"Altitude_ft\"] = string(buf);\n result[\"Rate\"] = string(row[1]);\n sprintf(buf,\"%d\",atoi(row[1]) - 10000);\n result[\"Rate_m\"] = string(buf);\n sprintf(buf,\"%d\",(int)((atoi(row[1]) - 10000)*M_TO_FT));\n result[\"Rate_ft\"] = string(buf);\n result[\"Lat\"] = string(row[2]);\n result[\"LatRef\"] = string(row[3]);\n result[\"Latitude\"] = string(row[2]) + string(row[3]);\n result[\"Lon\"] = string(row[4]);\n result[\"LonRef\"] = string(row[5]);\n result[\"Longitude\"] = string(row[4]) + string(row[5]);\n result[\"Spd\"] = string(row[6]);\n result[\"Spd_knots\"] = string(row[6]);\n sprintf(buf,\"%d\",(int)(atoi(row[6])*KNOT_TO_MPS));\n result[\"Spd_mps\"] = string(buf);\n result[\"Hdg\"] = string(row[7]);\n result[\"Status\"] = string(row[8]);\n }\n \n mysql_free_result(DB_result);\n\n return result;\n}\n\nPlot DB_getPlotData(char* table, char* data_column, int device_id) {\n DB_query(\"select UNIX_TIMESTAMP(Timestamp)-UNIX_TIMESTAMP(), Altitude, %s from %s \" \n \"where DeviceId=%d \"\n \"order by Timestamp asc;\",\n data_column, table, device_id);\n Plot result;\n\n MYSQL_ROW row;\n\n while (row = mysql_fetch_row(DB_result)) {\n result.time.push_back(strtod(row[0],NULL));\n result.altitude.push_back(strtod(row[1],NULL));\n result.data.push_back(strtod(row[2],NULL));\n }\n\n mysql_free_result(DB_result); \n \n return result;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ license:BSD-3-Clause\n\/\/ copyright-holders:Aaron Giles\n\/***************************************************************************\n\n delegate.c\n\n Templates and classes to enable delegates for callbacks.\n\n***************************************************************************\/\n\n#include <assert.h>\n#include <cstdint>\n#include <stdio.h>\n#include \"delegate.h\"\n\n\n\/\/**************************************************************************\n\/\/ GLOBAL VARIABLES\n\/\/**************************************************************************\n\n#if (USE_DELEGATE_TYPE == DELEGATE_TYPE_COMPATIBLE)\n\ndelegate_mfp::raw_mfp_data delegate_mfp::s_null_mfp = { {0 }};\n\n#endif\n\n\n\n\/\/**************************************************************************\n\/\/ INTERNAL DELEGATE HELPERS\n\/\/**************************************************************************\n\n#if (USE_DELEGATE_TYPE == DELEGATE_TYPE_INTERNAL)\n\n\/\/-------------------------------------------------\n\/\/ delegate_convert_raw - given an object and an raw function, adjust the object base\n\/\/ and return the actual final code pointer\n\/\/-------------------------------------------------\/\/\n\ndelegate_generic_function delegate_mfp::convert_to_generic(delegate_generic_class *&object) const\n{\n#if defined(__arm__) || defined(__ARMEL__) || defined(__aarch64__)\n\t\/\/ apply the \"this\" delta to the object first\n\tobject = reinterpret_cast<delegate_generic_class *>(reinterpret_cast<std::uint8_t *>(object));\n\n\t\/\/ if the low bit of the vtable index is clear, then it is just a raw function pointer\n\tif (m_this_delta==0) {\n#if defined(LOG_DELEGATES)\n\t\tprintf(\"Calculated Addr = %08x\\n\", (uintptr_t)(void*)(m_function));\n#endif\n\t\treturn reinterpret_cast<delegate_generic_function>(m_function);\n\t}\n\tobject = reinterpret_cast<delegate_generic_class *>(reinterpret_cast<std::uint8_t *>(object));\n\n\t\/\/ otherwise, it is the byte index into the vtable where the actual function lives\n\tstd::uint8_t *vtable_base = *reinterpret_cast<std::uint8_t **>(object);\n#if defined(LOG_DELEGATES)\n\tprintf(\"Calculated Addr = %08x (VTAB)\\n\", (uintptr_t)(void*)(*reinterpret_cast<delegate_generic_function *>(vtable_base + m_function + m_this_delta - 1)));\t\t\n#endif\n\treturn *reinterpret_cast<delegate_generic_function *>(vtable_base + m_function + m_this_delta - 1);\n#else\n\t\/\/ apply the \"this\" delta to the object first\n\tobject = reinterpret_cast<delegate_generic_class *>(reinterpret_cast<std::uint8_t *>(object) + m_this_delta);\n\n\t\/\/ if the low bit of the vtable index is clear, then it is just a raw function pointer\n\tif (!(m_function & 1)) {\n#if defined(LOG_DELEGATES)\n\t\tprintf(\"Calculated Addr = %08x\\n\", (uintptr_t)(void*)(m_function));\n#endif\n\t\treturn reinterpret_cast<delegate_generic_function>(m_function);\n\t}\n\n\t\/\/ otherwise, it is the byte index into the vtable where the actual function lives\n\tstd::uint8_t *vtable_base = *reinterpret_cast<std::uint8_t **>(object);\n#if defined(LOG_DELEGATES)\n\tprintf(\"Calculated Addr = %08x (VTAB)\\n\", (uintptr_t)(void*)(*reinterpret_cast<delegate_generic_function *>(vtable_base + m_function - 1)));\t\t\n#endif\n\treturn *reinterpret_cast<delegate_generic_function *>(vtable_base + m_function - 1);\n#endif\n}\n\n#endif\n<commit_msg>Works now on MIPS as well, tested on Creator Ci20<commit_after>\/\/ license:BSD-3-Clause\n\/\/ copyright-holders:Aaron Giles\n\/***************************************************************************\n\n delegate.c\n\n Templates and classes to enable delegates for callbacks.\n\n***************************************************************************\/\n\n#include <assert.h>\n#include <cstdint>\n#include <stdio.h>\n#include \"delegate.h\"\n\n\n\/\/**************************************************************************\n\/\/ GLOBAL VARIABLES\n\/\/**************************************************************************\n\n#if (USE_DELEGATE_TYPE == DELEGATE_TYPE_COMPATIBLE)\n\ndelegate_mfp::raw_mfp_data delegate_mfp::s_null_mfp = { {0 }};\n\n#endif\n\n\n\n\/\/**************************************************************************\n\/\/ INTERNAL DELEGATE HELPERS\n\/\/**************************************************************************\n\n#if (USE_DELEGATE_TYPE == DELEGATE_TYPE_INTERNAL)\n\n\/\/-------------------------------------------------\n\/\/ delegate_convert_raw - given an object and an raw function, adjust the object base\n\/\/ and return the actual final code pointer\n\/\/-------------------------------------------------\/\/\n\ndelegate_generic_function delegate_mfp::convert_to_generic(delegate_generic_class *&object) const\n{\n#if defined(__arm__) || defined(__ARMEL__) || defined(__aarch64__) || defined(__MIPSEL__) || defined(__mips_isa_rev) || defined(__mips64)\n\t\/\/ apply the \"this\" delta to the object first\n\tobject = reinterpret_cast<delegate_generic_class *>(reinterpret_cast<std::uint8_t *>(object));\n\n\t\/\/ if the low bit of the vtable index is clear, then it is just a raw function pointer\n\tif (m_this_delta==0) {\n#if defined(LOG_DELEGATES)\n\t\tprintf(\"Calculated Addr = %08x\\n\", (uintptr_t)(void*)(m_function));\n#endif\n\t\treturn reinterpret_cast<delegate_generic_function>(m_function);\n\t}\n\tobject = reinterpret_cast<delegate_generic_class *>(reinterpret_cast<std::uint8_t *>(object));\n\n\t\/\/ otherwise, it is the byte index into the vtable where the actual function lives\n\tstd::uint8_t *vtable_base = *reinterpret_cast<std::uint8_t **>(object);\n#if defined(LOG_DELEGATES)\n\tprintf(\"Calculated Addr = %08x (VTAB)\\n\", (uintptr_t)(void*)(*reinterpret_cast<delegate_generic_function *>(vtable_base + m_function + m_this_delta - 1)));\t\t\n#endif\n\treturn *reinterpret_cast<delegate_generic_function *>(vtable_base + m_function + m_this_delta - 1);\n#else\n\t\/\/ apply the \"this\" delta to the object first\n\tobject = reinterpret_cast<delegate_generic_class *>(reinterpret_cast<std::uint8_t *>(object) + m_this_delta);\n\n\t\/\/ if the low bit of the vtable index is clear, then it is just a raw function pointer\n\tif (!(m_function & 1)) {\n#if defined(LOG_DELEGATES)\n\t\tprintf(\"Calculated Addr = %08x\\n\", (uintptr_t)(void*)(m_function));\n#endif\n\t\treturn reinterpret_cast<delegate_generic_function>(m_function);\n\t}\n\n\t\/\/ otherwise, it is the byte index into the vtable where the actual function lives\n\tstd::uint8_t *vtable_base = *reinterpret_cast<std::uint8_t **>(object);\n#if defined(LOG_DELEGATES)\n\tprintf(\"Calculated Addr = %08x (VTAB)\\n\", (uintptr_t)(void*)(*reinterpret_cast<delegate_generic_function *>(vtable_base + m_function - 1)));\t\t\n#endif\n\treturn *reinterpret_cast<delegate_generic_function *>(vtable_base + m_function - 1);\n#endif\n}\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/******************************************************************************\\\n * ___ __ *\n * \/\\_ \\ __\/\\ \\ *\n * \\\/\/\\ \\ \/\\_\\ \\ \\____ ___ _____ _____ __ *\n * \\ \\ \\ \\\/\\ \\ \\ '__`\\ \/'___\\\/\\ '__`\\\/\\ '__`\\ \/'__`\\ *\n * \\_\\ \\_\\ \\ \\ \\ \\L\\ \\\/\\ \\__\/\\ \\ \\L\\ \\ \\ \\L\\ \\\/\\ \\L\\.\\_ *\n * \/\\____\\\\ \\_\\ \\_,__\/\\ \\____\\\\ \\ ,__\/\\ \\ ,__\/\\ \\__\/.\\_\\ *\n * \\\/____\/ \\\/_\/\\\/___\/ \\\/____\/ \\ \\ \\\/ \\ \\ \\\/ \\\/__\/\\\/_\/ *\n * \\ \\_\\ \\ \\_\\ *\n * \\\/_\/ \\\/_\/ *\n * *\n * Copyright (C) 2011, 2012 *\n * Dominik Charousset <dominik.charousset@haw-hamburg.de> *\n * *\n * This file is part of libcppa. *\n * libcppa is free software: you can redistribute it and\/or modify it under *\n * the terms of the GNU Lesser General Public License as published by the *\n * Free Software Foundation, either version 3 of the License *\n * or (at your option) any later version. *\n * *\n * libcppa is distributed in the hope that it will be useful, *\n * but WITHOUT ANY WARRANTY; without even the implied warranty of *\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *\n * See the GNU Lesser General Public License for more details. *\n * *\n * You should have received a copy of the GNU Lesser General Public License *\n * along with libcppa. If not, see <http:\/\/www.gnu.org\/licenses\/>. *\n\\******************************************************************************\/\n\n\n#include <stdexcept>\n\n#include \"cppa\/config.hpp\"\n#include \"cppa\/detail\/demangle.hpp\"\n\n#ifdef CPPA_GCC\n#include <cxxabi.h>\n#endif\n\n#include <stdlib.h>\n\nnamespace cppa { namespace detail {\n\nstd::string demangle(const char* decorated) {\n size_t size;\n int status;\n char* undecorated = abi::__cxa_demangle(decorated, nullptr, &size, &status);\n if (status != 0) {\n std::string error_msg = \"Could not demangle type name \";\n error_msg += decorated;\n throw std::logic_error(error_msg);\n }\n std::string result; \/\/ the undecorated typeid name\n result.reserve(size);\n const char* cstr = undecorated;\n \/\/ filter unnecessary characters from undecorated\n char c = *cstr;\n while (c != '\\0') {\n if (c == ' ') {\n char previous_c = result.empty() ? ' ' : *(result.rbegin());\n \/\/ get next non-space character\n for (c = *++cstr; c == ' '; c = *++cstr) { }\n if (c != '\\0') {\n \/\/ skip whitespace unless it separates two alphanumeric\n \/\/ characters (such as in \"unsigned int\")\n if (isalnum(c) && isalnum(previous_c)) {\n result += ' ';\n result += c;\n }\n else {\n result += c;\n }\n c = *++cstr;\n }\n }\n else {\n result += c;\n c = *++cstr;\n }\n }\n free(undecorated);\n return result;\n}\n\n} } \/\/ namespace cppa::detail\n<commit_msg>fixed clang name demangling<commit_after>\/******************************************************************************\\\n * ___ __ *\n * \/\\_ \\ __\/\\ \\ *\n * \\\/\/\\ \\ \/\\_\\ \\ \\____ ___ _____ _____ __ *\n * \\ \\ \\ \\\/\\ \\ \\ '__`\\ \/'___\\\/\\ '__`\\\/\\ '__`\\ \/'__`\\ *\n * \\_\\ \\_\\ \\ \\ \\ \\L\\ \\\/\\ \\__\/\\ \\ \\L\\ \\ \\ \\L\\ \\\/\\ \\L\\.\\_ *\n * \/\\____\\\\ \\_\\ \\_,__\/\\ \\____\\\\ \\ ,__\/\\ \\ ,__\/\\ \\__\/.\\_\\ *\n * \\\/____\/ \\\/_\/\\\/___\/ \\\/____\/ \\ \\ \\\/ \\ \\ \\\/ \\\/__\/\\\/_\/ *\n * \\ \\_\\ \\ \\_\\ *\n * \\\/_\/ \\\/_\/ *\n * *\n * Copyright (C) 2011, 2012 *\n * Dominik Charousset <dominik.charousset@haw-hamburg.de> *\n * *\n * This file is part of libcppa. *\n * libcppa is free software: you can redistribute it and\/or modify it under *\n * the terms of the GNU Lesser General Public License as published by the *\n * Free Software Foundation, either version 3 of the License *\n * or (at your option) any later version. *\n * *\n * libcppa is distributed in the hope that it will be useful, *\n * but WITHOUT ANY WARRANTY; without even the implied warranty of *\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *\n * See the GNU Lesser General Public License for more details. *\n * *\n * You should have received a copy of the GNU Lesser General Public License *\n * along with libcppa. If not, see <http:\/\/www.gnu.org\/licenses\/>. *\n\\******************************************************************************\/\n\n\n#include <stdexcept>\n\n#include \"cppa\/config.hpp\"\n#include \"cppa\/detail\/demangle.hpp\"\n\n#ifdef CPPA_GCC\n#include <cxxabi.h>\n#endif\n\n#include <stdlib.h>\n\nnamespace cppa { namespace detail {\n\nstd::string demangle(const char* decorated) {\n size_t size;\n int status;\n char* undecorated = abi::__cxa_demangle(decorated, nullptr, &size, &status);\n if (status != 0) {\n std::string error_msg = \"Could not demangle type name \";\n error_msg += decorated;\n throw std::logic_error(error_msg);\n }\n std::string result; \/\/ the undecorated typeid name\n result.reserve(size);\n const char* cstr = undecorated;\n \/\/ filter unnecessary characters from undecorated\n char c = *cstr;\n while (c != '\\0') {\n if (c == ' ') {\n char previous_c = result.empty() ? ' ' : *(result.rbegin());\n \/\/ get next non-space character\n for (c = *++cstr; c == ' '; c = *++cstr) { }\n if (c != '\\0') {\n \/\/ skip whitespace unless it separates two alphanumeric\n \/\/ characters (such as in \"unsigned int\")\n if (isalnum(c) && isalnum(previous_c)) {\n result += ' ';\n result += c;\n }\n else {\n result += c;\n }\n c = *++cstr;\n }\n }\n else {\n result += c;\n c = *++cstr;\n }\n }\n free(undecorated);\n# ifdef __clang__\n \/\/ replace \"std::__1::\" with \"std::\" (fixes strange clang names)\n std::string needle = \"std::__1::\";\n std::string fixed_string = \"std::\";\n for (auto pos = result.find(needle); pos != std::string::npos; pos = result.find(needle)) {\n result.replace(pos, needle.size(), fixed_string);\n }\n# endif\n return result;\n}\n\n} } \/\/ namespace cppa::detail\n<|endoftext|>"} {"text":"<commit_before>#include <array>\n#include <stdio.h>\n#include <stdlib.h>\n#include <assert.h>\n#include <time.h>\n#include <math.h>\n#include <omp.h>\n\n#include <xmmintrin.h>\n#include <pmmintrin.h>\n\n#include \"dijkstra.hpp\"\n#include \"min_heap.hpp\"\n#include \"universe.hpp\"\n\n#define AU_TO_M 149597870700.0\n#define LY_TO_M 9460730472580800.0\n\n#if defined(__AVX__)\n#include <immintrin.h>\n#define VECTOR_WIDTH 8\ntypedef __m256 vector_type;\n#elif defined(__SSE__)\n#define VECTOR_WIDTH 4\ntypedef __m128 vector_type;\n#else\n#error \"Here's a nickel kid, buy yourself a real computer.\"\n#endif\n\ninline float __attribute__((always_inline)) entity_distance(Celestial *a, Celestial *b) {\n if (a->system != b->system) return INFINITY;\n\n float dx = a->x - b->x;\n float dy = a->y - b->y;\n float dz = a->z - b->z;\n\n return sqrt(dx * dx + dy * dy + dz * dz);\n}\n\ninline float __attribute__((always_inline)) system_distance(System *a, System *b) {\n float dx = a->x - b->x;\n float dy = a->y - b->y;\n float dz = a->z - b->z;\n\n return sqrt(dx * dx + dy * dy + dz * dz);\n}\n\ndouble get_time(double distance, double v_wrp) {\n double k_accel = v_wrp;\n double k_decel = (v_wrp \/ 3) < 2 ? (v_wrp \/ 3) : 2;\n\n double v_max_wrp = v_wrp * AU_TO_M;\n\n double d_accel = AU_TO_M;\n double d_decel = v_max_wrp \/ k_decel;\n\n double d_min = d_accel + d_decel;\n\n double cruise_time = 0;\n\n if (d_min > distance) {\n v_max_wrp = distance * k_accel * k_decel \/ (k_accel + k_decel);\n } else {\n cruise_time = (distance - d_min) \/ v_max_wrp;\n }\n\n double t_accel = log(v_max_wrp \/ k_accel) \/ k_accel;\n double t_decel = log(v_max_wrp \/ 100) \/ k_decel;\n\n return cruise_time + t_accel + t_decel;\n}\n\nDijkstra::Dijkstra(Universe &u, Celestial *src, Celestial *dst, Parameters *parameters) : universe(u) {\n this->src = src;\n this->dst = dst;\n this->parameters = parameters;\n\n this->prev = new int[this->universe.entity_count];\n this->vist = new int[this->universe.entity_count];\n this->cost = new float[this->universe.entity_count];\n this->type = new enum movement_type[this->universe.entity_count];\n\n this->sys_x = new float[this->universe.system_count + VECTOR_WIDTH];\n this->sys_y = new float[this->universe.system_count + VECTOR_WIDTH];\n this->sys_z = new float[this->universe.system_count + VECTOR_WIDTH];\n\n this->fatigue = new float[this->universe.entity_count];\n this->reactivation = new float[this->universe.entity_count];\n\n this->queue = new MinHeap<float, int>(u.entity_count);\n\n for (int i = 0; i < this->universe.system_count; i++) {\n sys_x[i] = this->universe.systems[i].x;\n sys_y[i] = this->universe.systems[i].y;\n sys_z[i] = this->universe.systems[i].z;\n }\n\n for (int i = 0; i < this->universe.entity_count; i++) {\n\n vist[i] = i == src->seq_id ? 1 : 0;\n prev[i] = i == src->seq_id ? -2 : -1;\n type[i] = STRT;\n cost[i] = i == src->seq_id ? 0.0 : INFINITY;\n\n fatigue[i] = 0.0;\n reactivation[i] = 0.0;\n\n if (celestial_is_relevant(this->universe.entities[i])) {\n queue->insert(cost[i], i);\n }\n }\n}\n\nDijkstra::~Dijkstra() {\n delete[] prev;\n delete[] cost;\n delete[] vist;\n delete[] type;\n\n delete[] sys_x;\n delete[] sys_y;\n delete[] sys_z;\n}\n\nbool Dijkstra::celestial_is_relevant(Celestial &c) {\n return c.is_relevant() || c.id == src->id || (dst && c.id == dst->id);\n}\n\nvoid Dijkstra::solve_w_set(Celestial *ent) {\n System *sys = ent->system;\n\n for (int i = 0; i < sys->entity_count; i++) {\n if (!celestial_is_relevant(sys->entities[i]) || ent == &sys->entities[i]) {\n continue;\n }\n\n update_administration(ent, &sys->entities[i], parameters->align_time + get_time(entity_distance(ent, &sys->entities[i]), parameters->warp_speed), WARP);\n }\n}\n\nvoid Dijkstra::solve_g_set(Celestial *ent) {\n if (ent->destination && parameters->gate_cost >= 0.0) {\n update_administration(ent, ent->destination, parameters->gate_cost, GATE);\n }\n}\n\nvoid Dijkstra::solve_r_set(Celestial *ent) {\n if (ent->bridge && isnan(parameters->jump_range)) {\n update_administration(ent, ent->bridge, system_distance(ent->system, ent->bridge->system) * (1 - parameters->jump_range_reduction), JUMP);\n }\n}\n\nvoid Dijkstra::solve_j_set(Celestial *ent) {\n vector_type x_vec, y_vec, z_vec;\n vector_type x_src_vec, y_src_vec, z_src_vec;\n\n System *jsys, *sys = ent->system;\n\n float distance;\n float range, range_sq;\n\n #if VECTOR_WIDTH == 4\n x_src_vec = _mm_set1_ps(sys->x);\n y_src_vec = _mm_set1_ps(sys->y);\n z_src_vec = _mm_set1_ps(sys->z);\n #elif VECTOR_WIDTH == 8\n x_src_vec = _mm256_set1_ps(sys->x);\n y_src_vec = _mm256_set1_ps(sys->y);\n z_src_vec = _mm256_set1_ps(sys->z);\n #endif\n\n if (!isnan((range = parameters->jump_range)) || !isnan((range = ent->jump_range))) {\n range_sq = pow(range * LY_TO_M, 2.0);\n\n #pragma omp for schedule(guided)\n for (int k = 0; k < this->universe.system_count; k += VECTOR_WIDTH) {\n #if VECTOR_WIDTH == 4\n x_vec = _mm_load_ps(sys_x + k);\n y_vec = _mm_load_ps(sys_y + k);\n z_vec = _mm_load_ps(sys_z + k);\n #elif VECTOR_WIDTH == 8\n x_vec = _mm256_loadu_ps(sys_x + k);\n y_vec = _mm256_loadu_ps(sys_y + k);\n z_vec = _mm256_loadu_ps(sys_z + k);\n #endif\n\n x_vec -= x_src_vec;\n y_vec -= y_src_vec;\n z_vec -= z_src_vec;\n\n x_vec = (x_vec * x_vec) + (y_vec * y_vec) + (z_vec * z_vec);\n\n for (int i = 0; i < VECTOR_WIDTH; i++) {\n if (x_vec[i] > range_sq ||\n k + i >= this->universe.system_count ||\n sys == (jsys = this->universe.systems + i + k) ||\n jsys->security >= 0.5) continue;\n\n distance = sqrt(x_vec[i]) \/ LY_TO_M;\n\n for (int j = ((dst && jsys != dst->system) ? jsys->gates - jsys->entities : 0); j < jsys->entity_count; j++) {\n update_administration(ent, &jsys->entities[j], distance * (1 - parameters->jump_range_reduction), JUMP);\n }\n }\n }\n }\n}\n\nvoid Dijkstra::update_administration(Celestial *a, Celestial *b, float ccost, enum movement_type ctype) {\n float dcost, cur_cost;\n\n if (ctype == JUMP) {\n if (parameters->fatigue_model == FATIGUE_IGNORE) {\n dcost = 10.0;\n } else if (parameters->fatigue_model == FATIGUE_REACTIVATION_COST) {\n dcost = 60 * (ccost + 1);\n } else if (parameters->fatigue_model == FATIGUE_FATIGUE_COST) {\n dcost = 600 * ccost;\n } else if (parameters->fatigue_model == FATIGUE_REACTIVATION_COUNTDOWN) {\n dcost = reactivation[a->seq_id] + 10.0;\n } else if (parameters->fatigue_model == FATIGUE_FATIGUE_COUNTDOWN) {\n dcost = fatigue[a->seq_id] + 10.0;\n } else {\n dcost = INFINITY;\n }\n } else {\n dcost = ccost;\n }\n\n cur_cost = cost[a->seq_id] + dcost;\n\n if (cur_cost <= cost[b->seq_id] && !vist[b->seq_id]) {\n #pragma omp critical\n {\n queue->decrease_raw(cur_cost, b->seq_id);\n prev[b->seq_id] = a->seq_id;\n cost[b->seq_id] = cur_cost;\n type[b->seq_id] = ctype;\n\n fatigue[b->seq_id] = std::max(fatigue[a->seq_id] - dcost, 0.f);\n reactivation[b->seq_id] = std::max(reactivation[a->seq_id] - dcost, 0.f);\n\n if (ctype == JUMP) {\n fatigue[b->seq_id] = std::min(60*60*24*7.f, std::max(fatigue[a->seq_id], 600.f) * (ccost + 1));\n reactivation[b->seq_id] = std::max(fatigue[a->seq_id] \/ 600, 60 * (ccost + 1));\n }\n }\n }\n}\n\nRoute *Dijkstra::get_route() {\n if (!dst) throw 20;\n return get_route(dst);\n}\n\nRoute *Dijkstra::get_route(Celestial *dst) {\n solve_internal();\n\n if (!vist[dst->seq_id]) throw 21;\n\n Route *route = new Route();\n\n route->loops = loops;\n route->cost = cost[dst->seq_id];\n\n for (int c = dst->seq_id; c != -2; c = prev[c]) {\n route->points.push_front((struct waypoint) {&this->universe.entities[c], type[c]});\n }\n\n return route;\n}\n\n\n\nstd::map<Celestial *, float> *Dijkstra::get_all_distances() {\n solve_internal();\n\n std::map<Celestial *, float> *res = new std::map<Celestial *, float>();\n\n if (dst != NULL) throw 10;\n\n for (int i = 0; i < universe.entity_count; i++) {\n if (isfinite(cost[i])) {\n res->emplace(&universe.entities[i], cost[i]);\n }\n }\n\n return res;\n}\n\nvoid Dijkstra::solve_internal() {\n int tmp = -1;\n Celestial *ent;\n\n #pragma omp parallel num_threads(1)\n while (!queue->is_empty() && (!dst || !vist[dst->seq_id]) && (tmp == -1 || !isinf(cost[tmp]))) {\n #pragma omp master\n {\n tmp = queue->extract();\n ent = &this->universe.entities[tmp];\n vist[tmp] = 1;\n\n solve_w_set(ent);\n solve_g_set(ent);\n solve_r_set(ent);\n\n loops++;\n }\n\n #pragma omp barrier\n\n solve_j_set(ent);\n\n #pragma omp barrier\n }\n}\n<commit_msg>Gates are now disabled by setting NaN cost.<commit_after>#include <array>\n#include <stdio.h>\n#include <stdlib.h>\n#include <assert.h>\n#include <time.h>\n#include <math.h>\n#include <omp.h>\n\n#include <xmmintrin.h>\n#include <pmmintrin.h>\n\n#include \"dijkstra.hpp\"\n#include \"min_heap.hpp\"\n#include \"universe.hpp\"\n\n#define AU_TO_M 149597870700.0\n#define LY_TO_M 9460730472580800.0\n\n#if defined(__AVX__)\n#include <immintrin.h>\n#define VECTOR_WIDTH 8\ntypedef __m256 vector_type;\n#elif defined(__SSE__)\n#define VECTOR_WIDTH 4\ntypedef __m128 vector_type;\n#else\n#error \"Here's a nickel kid, buy yourself a real computer.\"\n#endif\n\ninline float __attribute__((always_inline)) entity_distance(Celestial *a, Celestial *b) {\n if (a->system != b->system) return INFINITY;\n\n float dx = a->x - b->x;\n float dy = a->y - b->y;\n float dz = a->z - b->z;\n\n return sqrt(dx * dx + dy * dy + dz * dz);\n}\n\ninline float __attribute__((always_inline)) system_distance(System *a, System *b) {\n float dx = a->x - b->x;\n float dy = a->y - b->y;\n float dz = a->z - b->z;\n\n return sqrt(dx * dx + dy * dy + dz * dz);\n}\n\ndouble get_time(double distance, double v_wrp) {\n double k_accel = v_wrp;\n double k_decel = (v_wrp \/ 3) < 2 ? (v_wrp \/ 3) : 2;\n\n double v_max_wrp = v_wrp * AU_TO_M;\n\n double d_accel = AU_TO_M;\n double d_decel = v_max_wrp \/ k_decel;\n\n double d_min = d_accel + d_decel;\n\n double cruise_time = 0;\n\n if (d_min > distance) {\n v_max_wrp = distance * k_accel * k_decel \/ (k_accel + k_decel);\n } else {\n cruise_time = (distance - d_min) \/ v_max_wrp;\n }\n\n double t_accel = log(v_max_wrp \/ k_accel) \/ k_accel;\n double t_decel = log(v_max_wrp \/ 100) \/ k_decel;\n\n return cruise_time + t_accel + t_decel;\n}\n\nDijkstra::Dijkstra(Universe &u, Celestial *src, Celestial *dst, Parameters *parameters) : universe(u) {\n this->src = src;\n this->dst = dst;\n this->parameters = parameters;\n\n this->prev = new int[this->universe.entity_count];\n this->vist = new int[this->universe.entity_count];\n this->cost = new float[this->universe.entity_count];\n this->type = new enum movement_type[this->universe.entity_count];\n\n this->sys_x = new float[this->universe.system_count + VECTOR_WIDTH];\n this->sys_y = new float[this->universe.system_count + VECTOR_WIDTH];\n this->sys_z = new float[this->universe.system_count + VECTOR_WIDTH];\n\n this->fatigue = new float[this->universe.entity_count];\n this->reactivation = new float[this->universe.entity_count];\n\n this->queue = new MinHeap<float, int>(u.entity_count);\n\n for (int i = 0; i < this->universe.system_count; i++) {\n sys_x[i] = this->universe.systems[i].x;\n sys_y[i] = this->universe.systems[i].y;\n sys_z[i] = this->universe.systems[i].z;\n }\n\n for (int i = 0; i < this->universe.entity_count; i++) {\n\n vist[i] = i == src->seq_id ? 1 : 0;\n prev[i] = i == src->seq_id ? -2 : -1;\n type[i] = STRT;\n cost[i] = i == src->seq_id ? 0.0 : INFINITY;\n\n fatigue[i] = 0.0;\n reactivation[i] = 0.0;\n\n if (celestial_is_relevant(this->universe.entities[i])) {\n queue->insert(cost[i], i);\n }\n }\n}\n\nDijkstra::~Dijkstra() {\n delete[] prev;\n delete[] cost;\n delete[] vist;\n delete[] type;\n\n delete[] sys_x;\n delete[] sys_y;\n delete[] sys_z;\n}\n\nbool Dijkstra::celestial_is_relevant(Celestial &c) {\n return c.is_relevant() || c.id == src->id || (dst && c.id == dst->id);\n}\n\nvoid Dijkstra::solve_w_set(Celestial *ent) {\n System *sys = ent->system;\n\n for (int i = 0; i < sys->entity_count; i++) {\n if (!celestial_is_relevant(sys->entities[i]) || ent == &sys->entities[i]) {\n continue;\n }\n\n update_administration(ent, &sys->entities[i], parameters->align_time + get_time(entity_distance(ent, &sys->entities[i]), parameters->warp_speed), WARP);\n }\n}\n\nvoid Dijkstra::solve_g_set(Celestial *ent) {\n if (ent->destination && !isnan(parameters->gate_cost)) {\n update_administration(ent, ent->destination, parameters->gate_cost, GATE);\n }\n}\n\nvoid Dijkstra::solve_r_set(Celestial *ent) {\n if (ent->bridge && isnan(parameters->jump_range)) {\n update_administration(ent, ent->bridge, system_distance(ent->system, ent->bridge->system) * (1 - parameters->jump_range_reduction), JUMP);\n }\n}\n\nvoid Dijkstra::solve_j_set(Celestial *ent) {\n vector_type x_vec, y_vec, z_vec;\n vector_type x_src_vec, y_src_vec, z_src_vec;\n\n System *jsys, *sys = ent->system;\n\n float distance;\n float range, range_sq;\n\n #if VECTOR_WIDTH == 4\n x_src_vec = _mm_set1_ps(sys->x);\n y_src_vec = _mm_set1_ps(sys->y);\n z_src_vec = _mm_set1_ps(sys->z);\n #elif VECTOR_WIDTH == 8\n x_src_vec = _mm256_set1_ps(sys->x);\n y_src_vec = _mm256_set1_ps(sys->y);\n z_src_vec = _mm256_set1_ps(sys->z);\n #endif\n\n if (!isnan((range = parameters->jump_range)) || !isnan((range = ent->jump_range))) {\n range_sq = pow(range * LY_TO_M, 2.0);\n\n #pragma omp for schedule(guided)\n for (int k = 0; k < this->universe.system_count; k += VECTOR_WIDTH) {\n #if VECTOR_WIDTH == 4\n x_vec = _mm_load_ps(sys_x + k);\n y_vec = _mm_load_ps(sys_y + k);\n z_vec = _mm_load_ps(sys_z + k);\n #elif VECTOR_WIDTH == 8\n x_vec = _mm256_loadu_ps(sys_x + k);\n y_vec = _mm256_loadu_ps(sys_y + k);\n z_vec = _mm256_loadu_ps(sys_z + k);\n #endif\n\n x_vec -= x_src_vec;\n y_vec -= y_src_vec;\n z_vec -= z_src_vec;\n\n x_vec = (x_vec * x_vec) + (y_vec * y_vec) + (z_vec * z_vec);\n\n for (int i = 0; i < VECTOR_WIDTH; i++) {\n if (x_vec[i] > range_sq ||\n k + i >= this->universe.system_count ||\n sys == (jsys = this->universe.systems + i + k) ||\n jsys->security >= 0.5) continue;\n\n distance = sqrt(x_vec[i]) \/ LY_TO_M;\n\n for (int j = ((dst && jsys != dst->system) ? jsys->gates - jsys->entities : 0); j < jsys->entity_count; j++) {\n update_administration(ent, &jsys->entities[j], distance * (1 - parameters->jump_range_reduction), JUMP);\n }\n }\n }\n }\n}\n\nvoid Dijkstra::update_administration(Celestial *a, Celestial *b, float ccost, enum movement_type ctype) {\n float dcost, cur_cost;\n\n if (ctype == JUMP) {\n if (parameters->fatigue_model == FATIGUE_IGNORE) {\n dcost = 10.0;\n } else if (parameters->fatigue_model == FATIGUE_REACTIVATION_COST) {\n dcost = 60 * (ccost + 1);\n } else if (parameters->fatigue_model == FATIGUE_FATIGUE_COST) {\n dcost = 600 * ccost;\n } else if (parameters->fatigue_model == FATIGUE_REACTIVATION_COUNTDOWN) {\n dcost = reactivation[a->seq_id] + 10.0;\n } else if (parameters->fatigue_model == FATIGUE_FATIGUE_COUNTDOWN) {\n dcost = fatigue[a->seq_id] + 10.0;\n } else {\n dcost = INFINITY;\n }\n } else {\n dcost = ccost;\n }\n\n cur_cost = cost[a->seq_id] + dcost;\n\n if (cur_cost <= cost[b->seq_id] && !vist[b->seq_id]) {\n #pragma omp critical\n {\n queue->decrease_raw(cur_cost, b->seq_id);\n prev[b->seq_id] = a->seq_id;\n cost[b->seq_id] = cur_cost;\n type[b->seq_id] = ctype;\n\n fatigue[b->seq_id] = std::max(fatigue[a->seq_id] - dcost, 0.f);\n reactivation[b->seq_id] = std::max(reactivation[a->seq_id] - dcost, 0.f);\n\n if (ctype == JUMP) {\n fatigue[b->seq_id] = std::min(60*60*24*7.f, std::max(fatigue[a->seq_id], 600.f) * (ccost + 1));\n reactivation[b->seq_id] = std::max(fatigue[a->seq_id] \/ 600, 60 * (ccost + 1));\n }\n }\n }\n}\n\nRoute *Dijkstra::get_route() {\n if (!dst) throw 20;\n return get_route(dst);\n}\n\nRoute *Dijkstra::get_route(Celestial *dst) {\n solve_internal();\n\n if (!vist[dst->seq_id]) throw 21;\n\n Route *route = new Route();\n\n route->loops = loops;\n route->cost = cost[dst->seq_id];\n\n for (int c = dst->seq_id; c != -2; c = prev[c]) {\n route->points.push_front((struct waypoint) {&this->universe.entities[c], type[c]});\n }\n\n return route;\n}\n\n\n\nstd::map<Celestial *, float> *Dijkstra::get_all_distances() {\n solve_internal();\n\n std::map<Celestial *, float> *res = new std::map<Celestial *, float>();\n\n if (dst != NULL) throw 10;\n\n for (int i = 0; i < universe.entity_count; i++) {\n if (isfinite(cost[i])) {\n res->emplace(&universe.entities[i], cost[i]);\n }\n }\n\n return res;\n}\n\nvoid Dijkstra::solve_internal() {\n int tmp = -1;\n Celestial *ent;\n\n #pragma omp parallel num_threads(1)\n while (!queue->is_empty() && (!dst || !vist[dst->seq_id]) && (tmp == -1 || !isinf(cost[tmp]))) {\n #pragma omp master\n {\n tmp = queue->extract();\n ent = &this->universe.entities[tmp];\n vist[tmp] = 1;\n\n solve_w_set(ent);\n solve_g_set(ent);\n solve_r_set(ent);\n\n loops++;\n }\n\n #pragma omp barrier\n\n solve_j_set(ent);\n\n #pragma omp barrier\n }\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"openmc\/finalize.h\"\n\n#include \"openmc\/capi.h\"\n#include \"openmc\/constants.h\"\n#include \"openmc\/eigenvalue.h\"\n#include \"openmc\/geometry.h\"\n#include \"openmc\/message_passing.h\"\n#include \"openmc\/nuclide.h\"\n#include \"openmc\/random_lcg.h\"\n#include \"openmc\/settings.h\"\n#include \"openmc\/simulation.h\"\n#include \"openmc\/timer.h\"\n#include \"openmc\/tallies\/tally.h\"\n\nusing namespace openmc;\n\n\/\/ Functions defined in Fortran\nextern \"C\" void free_memory();\nextern \"C\" void reset_timers_f();\n\nint openmc_finalize()\n{\n \/\/ Clear results\n openmc_reset();\n\n \/\/ Reset global variables\n settings::assume_separate = false;\n settings::check_overlaps = false;\n settings::confidence_intervals = false;\n settings::create_fission_neutrons = true;\n settings::electron_treatment = ELECTRON_LED;\n settings::energy_cutoff = {0.0, 1000.0, 0.0, 0.0};\n settings::entropy_on = false;\n settings::gen_per_batch = 1;\n settings::index_entropy_mesh = -1;\n settings::index_ufs_mesh = -1;\n settings::legendre_to_tabular = true;\n settings::legendre_to_tabular_points = -1;\n settings::n_particles = -1;\n settings::output_summary = true;\n settings::output_tallies = true;\n settings::particle_restart_run = false;\n settings::photon_transport = false;\n settings::reduce_tallies = true;\n settings::res_scat_on = false;\n settings::res_scat_method = RES_SCAT_ARES;\n settings::res_scat_energy_min = 0.01;\n settings::res_scat_energy_max = 1000.0;\n settings::restart_run = false;\n settings::run_CE = true;\n settings::run_mode = -1;\n settings::dagmc = false;\n settings::source_latest = false;\n settings::source_separate = false;\n settings::source_write = true;\n settings::survival_biasing = false;\n settings::temperature_default = 293.6;\n settings::temperature_method = TEMPERATURE_NEAREST;\n settings::temperature_multipole = false;\n settings::temperature_range = {0.0, 0.0};\n settings::temperature_tolerance = 10.0;\n settings::trigger_on = false;\n settings::trigger_predict = false;\n settings::trigger_batch_interval = 1;\n settings::ufs_on = false;\n settings::urr_ptables_on = true;\n settings::verbosity = 7;\n settings::weight_cutoff = 0.25;\n settings::weight_survive = 1.0;\n settings::write_all_tracks = false;\n settings::write_initial_source = false;\n\n simulation::keff = 1.0;\n simulation::n_lost_particles = 0;\n simulation::satisfy_triggers = false;\n simulation::total_gen = 0;\n\n energy_max = {INFTY, INFTY};\n energy_min = {0.0, 0.0};\n n_tallies = 0;\n openmc_root_universe = -1;\n openmc_set_seed(DEFAULT_SEED);\n\n \/\/ Deallocate arrays\n free_memory();\n\n \/\/ Free all MPI types\n#ifdef OPENMC_MPI\n MPI_Type_free(&mpi::bank);\n#endif\n\n return 0;\n}\n\nint openmc_reset()\n{\n for (int i = 1; i <= n_tallies; ++i) {\n openmc_tally_reset(i);\n }\n\n \/\/ Reset global tallies (can't really use global_tallies() right now because\n \/\/ it doesn't have any information about whether the underlying buffer was\n \/\/ allocated)\n n_realizations = 0;\n double* buffer = nullptr;\n openmc_global_tallies(&buffer);\n if (buffer) {\n for (int i = 0; i < 3*N_GLOBAL_TALLIES*3; ++i) {\n buffer[i] = 0.0;\n }\n }\n \/\/ auto gt = global_tallies();\n \/\/ std::fill(gt.begin(), gt.end(), 0.0);\n\n simulation::k_col_abs = 0.0;\n simulation::k_col_tra = 0.0;\n simulation::k_abs_tra = 0.0;\n k_sum = {0.0, 0.0};\n\n \/\/ Reset timers\n reset_timers();\n reset_timers_f();\n\n return 0;\n}\n\nint openmc_hard_reset()\n{\n \/\/ Reset all tallies and timers\n openmc_reset();\n\n \/\/ Reset total generations and keff guess\n simulation::keff = 1.0;\n simulation::total_gen = 0;\n\n \/\/ Reset the random number generator state\n openmc_set_seed(DEFAULT_SEED);\n return 0;\n}\n<commit_msg>Fix resetting of global_tallies<commit_after>#include \"openmc\/finalize.h\"\n\n#include \"openmc\/capi.h\"\n#include \"openmc\/constants.h\"\n#include \"openmc\/eigenvalue.h\"\n#include \"openmc\/geometry.h\"\n#include \"openmc\/message_passing.h\"\n#include \"openmc\/nuclide.h\"\n#include \"openmc\/random_lcg.h\"\n#include \"openmc\/settings.h\"\n#include \"openmc\/simulation.h\"\n#include \"openmc\/timer.h\"\n#include \"openmc\/tallies\/tally.h\"\n\nusing namespace openmc;\n\n\/\/ Functions defined in Fortran\nextern \"C\" void free_memory();\nextern \"C\" void reset_timers_f();\n\nint openmc_finalize()\n{\n \/\/ Clear results\n openmc_reset();\n\n \/\/ Reset global variables\n settings::assume_separate = false;\n settings::check_overlaps = false;\n settings::confidence_intervals = false;\n settings::create_fission_neutrons = true;\n settings::electron_treatment = ELECTRON_LED;\n settings::energy_cutoff = {0.0, 1000.0, 0.0, 0.0};\n settings::entropy_on = false;\n settings::gen_per_batch = 1;\n settings::index_entropy_mesh = -1;\n settings::index_ufs_mesh = -1;\n settings::legendre_to_tabular = true;\n settings::legendre_to_tabular_points = -1;\n settings::n_particles = -1;\n settings::output_summary = true;\n settings::output_tallies = true;\n settings::particle_restart_run = false;\n settings::photon_transport = false;\n settings::reduce_tallies = true;\n settings::res_scat_on = false;\n settings::res_scat_method = RES_SCAT_ARES;\n settings::res_scat_energy_min = 0.01;\n settings::res_scat_energy_max = 1000.0;\n settings::restart_run = false;\n settings::run_CE = true;\n settings::run_mode = -1;\n settings::dagmc = false;\n settings::source_latest = false;\n settings::source_separate = false;\n settings::source_write = true;\n settings::survival_biasing = false;\n settings::temperature_default = 293.6;\n settings::temperature_method = TEMPERATURE_NEAREST;\n settings::temperature_multipole = false;\n settings::temperature_range = {0.0, 0.0};\n settings::temperature_tolerance = 10.0;\n settings::trigger_on = false;\n settings::trigger_predict = false;\n settings::trigger_batch_interval = 1;\n settings::ufs_on = false;\n settings::urr_ptables_on = true;\n settings::verbosity = 7;\n settings::weight_cutoff = 0.25;\n settings::weight_survive = 1.0;\n settings::write_all_tracks = false;\n settings::write_initial_source = false;\n\n simulation::keff = 1.0;\n simulation::n_lost_particles = 0;\n simulation::satisfy_triggers = false;\n simulation::total_gen = 0;\n\n energy_max = {INFTY, INFTY};\n energy_min = {0.0, 0.0};\n n_tallies = 0;\n openmc_root_universe = -1;\n openmc_set_seed(DEFAULT_SEED);\n\n \/\/ Deallocate arrays\n free_memory();\n\n \/\/ Free all MPI types\n#ifdef OPENMC_MPI\n MPI_Type_free(&mpi::bank);\n#endif\n\n return 0;\n}\n\nint openmc_reset()\n{\n for (int i = 1; i <= n_tallies; ++i) {\n openmc_tally_reset(i);\n }\n\n \/\/ Reset global tallies (can't really use global_tallies() right now because\n \/\/ it doesn't have any information about whether the underlying buffer was\n \/\/ allocated)\n n_realizations = 0;\n double* buffer = nullptr;\n openmc_global_tallies(&buffer);\n if (buffer) {\n for (int i = 0; i < 3*N_GLOBAL_TALLIES; ++i) {\n buffer[i] = 0.0;\n }\n }\n\n simulation::k_col_abs = 0.0;\n simulation::k_col_tra = 0.0;\n simulation::k_abs_tra = 0.0;\n k_sum = {0.0, 0.0};\n\n \/\/ Reset timers\n reset_timers();\n reset_timers_f();\n\n return 0;\n}\n\nint openmc_hard_reset()\n{\n \/\/ Reset all tallies and timers\n openmc_reset();\n\n \/\/ Reset total generations and keff guess\n simulation::keff = 1.0;\n simulation::total_gen = 0;\n\n \/\/ Reset the random number generator state\n openmc_set_seed(DEFAULT_SEED);\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>#ifndef FLAT_MAP_H\n#define FLAT_MAP_H\n\n\/\/ Heavily inspired from https:\/\/stackoverflow.com\/a\/30938947, credits to\n\/\/ Yakk - Adam Nevraum @ StackOverflow\n\n#include <vector>\n#include <utility>\n#include <algorithm>\n\ntemplate<class Key, class Value, template<class...>class Storage=std::vector>\nstruct flat_map {\n using storage_t = Storage<std::pair<Key, Value>>;\n storage_t storage;\n\n using iterator=decltype(begin(std::declval<storage_t&>()));\n using const_iterator=decltype(begin(std::declval<const storage_t&>()));\n\n \/\/ Constructor\n flat_map() = default;\n flat_map(std::initializer_list<std::pair<Key,Value>> init) : storage(std::move(init)) { }\n\n \/\/ boilerplate:\n iterator begin() {\n using std::begin;\n return begin(storage);\n }\n const_iterator begin() const {\n using std::begin;\n return begin(storage);\n }\n const_iterator cbegin() const {\n using std::begin;\n return begin(storage);\n }\n iterator end() {\n using std::end;\n return end(storage);\n }\n const_iterator end() const {\n using std::end;\n return end(storage);\n }\n const_iterator cend() const {\n using std::end;\n return end(storage);\n }\n size_t size() const {\n return storage.size();\n }\n bool empty() const {\n return storage.empty();\n }\n \/\/ these only have to be valid if called:\n void reserve(size_t n) {\n storage.reserve(n);\n }\n size_t capacity() const {\n return storage.capacity();\n }\n \/\/ map-like interface:\n template<class K, class=std::enable_if_t<std::is_convertible<K, Key>{}>>\n Value& operator[](K&& k){\n auto it = find(k);\n if (it != end()) return it->v;\n storage.emplace_back( std::forward<K>(k), Value{} );\n return storage.back().v;\n }\nprivate:\n template<class K, class=std::enable_if_t<std::is_convertible<K, Key>{}>>\n auto key_match( K& k ) {\n return [&k](const std::pair<Key, Value>& kv){\n return kv.first == k;\n };\n }\npublic:\n template<class K, class=std::enable_if_t<std::is_convertible<K, Key>{}>>\n iterator find(K&& k) {\n return std::find_if( begin(), end(), key_match(k) );\n }\n template<class K, class=std::enable_if_t<std::is_convertible<K, Key>{}>>\n const_iterator find(K&& k) const {\n return const_cast<flat_map*>(this)->find(k);\n }\n iterator erase(const_iterator it) {\n return storage.erase(it);\n }\n template<class P, class=std::enable_if_t<std::is_convertible<P,std::pair<Key, Value>>{}>>\n void insert( P&& value )\n {\n auto it = find(value.first);\n if (it == end())\n storage.emplace_back( std::forward<P>(value) );\n else\n it->second = value.second;\n }\n\n bool operator<(const flat_map &rhs) const\n {\n return storage < rhs.storage;\n }\n};\n#endif \/* FLAT_MAP_H *\/\n<commit_msg>Fix compilation<commit_after>#ifndef FLAT_MAP_H\n#define FLAT_MAP_H\n\n\/\/ Heavily inspired from https:\/\/stackoverflow.com\/a\/30938947, credits to\n\/\/ Yakk - Adam Nevraum @ StackOverflow\n\n#include <vector>\n#include <utility>\n#include <algorithm>\n\ntemplate<class Key, class Value, template<class...>class Storage=std::vector>\nstruct flat_map {\n using storage_t = Storage<std::pair<Key, Value>>;\n storage_t storage;\n\n using iterator=decltype(begin(std::declval<storage_t&>()));\n using const_iterator=decltype(begin(std::declval<const storage_t&>()));\n\n \/\/ Constructor\n flat_map() = default;\n flat_map(std::initializer_list<std::pair<Key,Value>> init) : storage(std::move(init)) { }\n\n \/\/ boilerplate:\n iterator begin() {\n using std::begin;\n return begin(storage);\n }\n const_iterator begin() const {\n using std::begin;\n return begin(storage);\n }\n const_iterator cbegin() const {\n using std::begin;\n return begin(storage);\n }\n iterator end() {\n using std::end;\n return end(storage);\n }\n const_iterator end() const {\n using std::end;\n return end(storage);\n }\n const_iterator cend() const {\n using std::end;\n return end(storage);\n }\n size_t size() const {\n return storage.size();\n }\n bool empty() const {\n return storage.empty();\n }\n \/\/ these only have to be valid if called:\n void reserve(size_t n) {\n storage.reserve(n);\n }\n size_t capacity() const {\n return storage.capacity();\n }\n \/\/ map-like interface:\n template<class K, class=std::enable_if_t<std::is_convertible<K, Key>{}>>\n Value& operator[](K&& k){\n auto it = find(k);\n if (it != end()) return it->second;\n storage.emplace_back( std::forward<K>(k), Value{} );\n return storage.back().second;\n }\nprivate:\n template<class K, class=std::enable_if_t<std::is_convertible<K, Key>{}>>\n auto key_match( K& k ) {\n return [&k](const std::pair<Key, Value>& kv){\n return kv.first == k;\n };\n }\npublic:\n template<class K, class=std::enable_if_t<std::is_convertible<K, Key>{}>>\n iterator find(K&& k) {\n return std::find_if( begin(), end(), key_match(k) );\n }\n template<class K, class=std::enable_if_t<std::is_convertible<K, Key>{}>>\n const_iterator find(K&& k) const {\n return const_cast<flat_map*>(this)->find(k);\n }\n iterator erase(const_iterator it) {\n return storage.erase(it);\n }\n template<class P, class=std::enable_if_t<std::is_convertible<P,std::pair<Key, Value>>{}>>\n void insert( P&& value )\n {\n auto it = find(value.first);\n if (it == end())\n storage.emplace_back( std::forward<P>(value) );\n else\n it->second = value.second;\n }\n\n bool operator<(const flat_map &rhs) const\n {\n return storage < rhs.storage;\n }\n};\n#endif \/* FLAT_MAP_H *\/\n<|endoftext|>"} {"text":"<commit_before>#include <boost\/property_tree\/ptree.hpp>\n#include <boost\/property_tree\/json_parser.hpp>\n#include <boost\/regex.hpp>\n#include \"factorio\/mod-info.hpp\"\n#include <DA\/exception.hpp>\n#include <sstream>\n#define AVHTTP_ENABLE_OPENSSL\n#include <avhttp.hpp>\n#ifdef DEBUG\n\t#include <iostream>\n#endif\nusing namespace\tboost::property_tree;\nusing avhttp::detail::escape_string;\n\nnamespace factorio\n{\nnamespace mod\n{\n\tstd::string get_script(std::string html)\n\ttry\n\t{\n\t\tptree pt;\n\t\tstd::stringstream ss(html);\n\t\tstd::string json;\n\t\twhile(std::getline(ss, json))\n\t\t\tif(json.find(\"window.__INITIAL_STATE__\") != std::string::npos)\n\t\t\t\tbreak;\n\t\tjson = json.substr(json.find('{'));\n\t\tjson = json.substr(0, json.rfind('}') + 1);\n\t\treturn json;\n\t}\n\tDA_CATCH_EXCEPTION\n\tptree search(std::string name)\n\ttry\n\t{\n\t\tusing namespace std;\n\t\tstringstream ss;\n\t\t{\n\t\t\tstd::string url = \"https:\/\/mods.factorio.com\/?q=\";\n\t\t\turl += escape_string(name);\n\t\n\t\t\tboost::asio::io_service io;\n\t\t\tavhttp::http_stream h(io);\n\t\t\th.open(url);\n\t\n\t\t\tss << &h;\n\t\t}\n\t\n\t\tstringstream json(get_script(ss.str()));\n\t\t#ifdef DEBUG\n\t\t\tAVHTTP_LOG_DBG << \"search json:\\n\" << json.str();\n\t\t#endif\n\t\tptree pt;\n\t\tread_json(json, pt);\n\t\n\t\tauto child = pt.get_child(\"mods.modsPages\");\n\t\tfor (const auto & i : child)\n\t\t{\n\t\t\tfor (const auto & j : i.second)\n\t\t\t{\n\t\t\t\tif(j.second.get<string>(\"name\") == name)\n\t\t\t\t{\n\t\t\t\t\treturn j.second;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tDA_THROW_EXCEPTION_1(\"Can't found mod\");\n\t}\n\tDA_CATCH_EXCEPTION\n\tavhttp::url get_url(std::string name) \n\ttry\n\t{\n\t\tauto pt = search(name);\n\t\tstd::string result = \"https:\/\/mods.factorio.com\/mods\/\";\n\t\tresult += escape_string(pt.get<std::string>(\"owner\"));\n\t\tresult += \"\/\";\n\t\tresult += escape_string(name);\n\t\t#ifdef DEBUG\n\t\t\tAVHTTP_LOG_DBG << \"mod url:\" << result;\n\t\t#endif\n\t\treturn result;\n\t}\n\tDA_CATCH_EXCEPTION\n\t\n\tptree info::get_json(avhttp::url url) const\n\ttry\n\t{\n\t\tusing namespace std;\n\t\tboost::asio::io_service io;\n\t\tavhttp::http_stream h(io);\n\t\th.open(url);\n\n\t\tstringstream ss;\n\t\tss << &h;\n\t\t#ifdef DEBUG\n\t\t\tAVHTTP_LOG_DBG << \"mod page:\\n\" << ss.str();\n\t\t#endif\n\n\t\tstringstream json(get_script(ss.str()));\n\t\t#ifdef DEBUG\n\t\t\tAVHTTP_LOG_DBG << \"mod json:\\n\" << json.str();\n\t\t#endif\n\t\tptree pt;\n\t\tread_json(json, pt);\n\t\treturn pt;\n\t}\n\tDA_CATCH_EXCEPTION\n\tinfo::info(std::string name)\n\ttry\n\t{\n\t\tpt = get_json(get_url(name)).get_child(\"mod.mod\");\n\t}\n\tDA_CATCH_EXCEPTION\n\tinfo info::read_name(std::string name)\n\ttry\n\t{\n\t\tpt = search(name);\n\t\treturn *this;\n\t}\n\tDA_CATCH_EXCEPTION\n\tinfo info::read_name_fast(std::string name)\n\ttry\n\t{\n\t\tpt = get_json(get_url(name)).get_child(\"mod.mod\");\n\t\treturn *this;\n\t}\n\tDA_CATCH_EXCEPTION\n\tinfo info::read_full_name(std::string name)\n\ttry\n\t{\n\t\tpt = get_json(\"https:\/\/mods.factorio.com\/mods\/\" + name).get_child(\"mod.mod\");\n\t\treturn *this;\n\t}\n\tDA_CATCH_EXCEPTION\n\tinfo info::read_url(std::string url)\n\ttry\n\t{\n\t\tpt = get_json(url).get_child(\"mod.mod\");\n\t\treturn *this;\n\t}\n\tDA_CATCH_EXCEPTION\n} \/* mod *\/ \n} \/* factorio *\/ \n<commit_msg>fix wrong fast and normal<commit_after>#include <boost\/property_tree\/ptree.hpp>\n#include <boost\/property_tree\/json_parser.hpp>\n#include <boost\/regex.hpp>\n#include \"factorio\/mod-info.hpp\"\n#include <DA\/exception.hpp>\n#include <sstream>\n#define AVHTTP_ENABLE_OPENSSL\n#include <avhttp.hpp>\n#ifdef DEBUG\n\t#include <iostream>\n#endif\nusing namespace\tboost::property_tree;\nusing avhttp::detail::escape_string;\n\nnamespace factorio\n{\nnamespace mod\n{\n\tstd::string get_script(std::string html)\n\ttry\n\t{\n\t\tptree pt;\n\t\tstd::stringstream ss(html);\n\t\tstd::string json;\n\t\twhile(std::getline(ss, json))\n\t\t\tif(json.find(\"window.__INITIAL_STATE__\") != std::string::npos)\n\t\t\t\tbreak;\n\t\tjson = json.substr(json.find('{'));\n\t\tjson = json.substr(0, json.rfind('}') + 1);\n\t\treturn json;\n\t}\n\tDA_CATCH_EXCEPTION\n\tptree search(std::string name)\n\ttry\n\t{\n\t\tusing namespace std;\n\t\tstringstream ss;\n\t\t{\n\t\t\tstd::string url = \"https:\/\/mods.factorio.com\/?q=\";\n\t\t\turl += escape_string(name);\n\t\n\t\t\tboost::asio::io_service io;\n\t\t\tavhttp::http_stream h(io);\n\t\t\th.open(url);\n\t\n\t\t\tss << &h;\n\t\t}\n\t\n\t\tstringstream json(get_script(ss.str()));\n\t\t#ifdef DEBUG\n\t\t\tAVHTTP_LOG_DBG << \"search json:\\n\" << json.str();\n\t\t#endif\n\t\tptree pt;\n\t\tread_json(json, pt);\n\t\n\t\tauto child = pt.get_child(\"mods.modsPages\");\n\t\tfor (const auto & i : child)\n\t\t{\n\t\t\tfor (const auto & j : i.second)\n\t\t\t{\n\t\t\t\tif(j.second.get<string>(\"name\") == name)\n\t\t\t\t{\n\t\t\t\t\treturn j.second;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tDA_THROW_EXCEPTION_1(\"Can't found mod\");\n\t}\n\tDA_CATCH_EXCEPTION\n\tavhttp::url get_url(std::string name) \n\ttry\n\t{\n\t\tauto pt = search(name);\n\t\tstd::string result = \"https:\/\/mods.factorio.com\/mods\/\";\n\t\tresult += escape_string(pt.get<std::string>(\"owner\"));\n\t\tresult += \"\/\";\n\t\tresult += escape_string(name);\n\t\t#ifdef DEBUG\n\t\t\tAVHTTP_LOG_DBG << \"mod url:\" << result;\n\t\t#endif\n\t\treturn result;\n\t}\n\tDA_CATCH_EXCEPTION\n\t\n\tptree info::get_json(avhttp::url url) const\n\ttry\n\t{\n\t\tusing namespace std;\n\t\tboost::asio::io_service io;\n\t\tavhttp::http_stream h(io);\n\t\th.open(url);\n\n\t\tstringstream ss;\n\t\tss << &h;\n\t\t#ifdef DEBUG\n\t\t\tAVHTTP_LOG_DBG << \"mod page:\\n\" << ss.str();\n\t\t#endif\n\n\t\tstringstream json(get_script(ss.str()));\n\t\t#ifdef DEBUG\n\t\t\tAVHTTP_LOG_DBG << \"mod json:\\n\" << json.str();\n\t\t#endif\n\t\tptree pt;\n\t\tread_json(json, pt);\n\t\treturn pt;\n\t}\n\tDA_CATCH_EXCEPTION\n\tinfo::info(std::string name)\n\ttry\n\t{\n\t\tpt = get_json(get_url(name)).get_child(\"mod.mod\");\n\t}\n\tDA_CATCH_EXCEPTION\n\tinfo info::read_name(std::string name)\n\ttry\n\t{\n\t\tpt = get_json(get_url(name)).get_child(\"mod.mod\");\n\t\treturn *this;\n\t}\n\tDA_CATCH_EXCEPTION\n\tinfo info::read_name_fast(std::string name)\n\ttry\n\t{\n\t\tpt = search(name);\n\t\treturn *this;\n\t}\n\tDA_CATCH_EXCEPTION\n\tinfo info::read_full_name(std::string name)\n\ttry\n\t{\n\t\tpt = get_json(\"https:\/\/mods.factorio.com\/mods\/\" + name).get_child(\"mod.mod\");\n\t\treturn *this;\n\t}\n\tDA_CATCH_EXCEPTION\n\tinfo info::read_url(std::string url)\n\ttry\n\t{\n\t\tpt = get_json(url).get_child(\"mod.mod\");\n\t\treturn *this;\n\t}\n\tDA_CATCH_EXCEPTION\n} \/* mod *\/ \n} \/* factorio *\/ \n<|endoftext|>"} {"text":"<commit_before>\/*\n ==============================================================================\n \n Copyright (c) 2014 Jacob Sologub\n \n Permission is hereby granted, free of charge, to any person obtaining a copy \n of this software and associated documentation files (the \"Software\"), to deal \n in the Software without restriction, including without limitation the rights \n to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell \n copies of the Software, and to permit persons to whom the Software is \n furnished to do so, subject to the following conditions:\n \n The above copyright notice and this permission notice shall be included in \n all copies or substantial portions of the Software.\n \n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, \n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE \n AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER \n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, \n OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE \n SOFTWARE.\n\n ==============================================================================\n*\/\n\n#include \"gif2webpMain.h\"\n#include <node.h>\n#include <node_buffer.h>\n#include <v8.h>\n#include <string.h>\n#include <iostream>\n#include <iostream>\n#include <fstream>\n#include <sstream>\n#include <vector>\n\nusing namespace v8;\nusing namespace node;\n\n\/\/ {\n\/\/ source required. <Buffer> Buffer with binary image data.\n\/\/ lossy: optional. <Boolean> Encode image using lossy compression\n\/\/ mixed: optional. <Boolean> For each frame in the image, pick lossy or lossless compression heuristically.\n\/\/ quality: optional. <Number> Quality factor (0:small..100:big)\n\/\/ method: optional. <Number> Compression method Quality (0=fast, 6=slowest)\n\/\/ kmin: optional. <Number> Min distance between key frames\n\/\/ kmax: optional. <Number> Max distance between key frames\n\/\/ filter: optional. <Number> Filter strength (0=off..100)\n\/\/ metadata: optional. <String> comma separated list of metadata to copy from the input to the output if present. Valid values: all, none, icc, xmp (default)\n\/\/ mt: optional. <Boolean> Use multi-threading if available\n\/\/ verbose: optional. <Boolean> Verbose output from gif2webp\n\/\/ }\n\nHandle<Value> convert (const Arguments& args) {\n HandleScope scope;\n\n if (args.Length() < 2) {\n return ThrowException (Exception::TypeError (String::New (\"Wrong number of arguments.\")));\n }\n\n if (!args [0]->IsObject()) {\n return ThrowException (Exception::TypeError (String::New (\"First argument must be be an object.\")));\n }\n\n if (!args [1]->IsFunction()) {\n return ThrowException (Exception::TypeError (String::New (\"Second argument must be a callback function.\")));\n }\n\n Local<Object> options = args [0]->ToObject();\n\n Local<Object> buffer = Local<Object>::Cast (options->Get (String::NewSymbol (\"source\")));\n if (buffer->IsUndefined() || !Buffer::HasInstance (buffer)) {\n return ThrowException (Exception::TypeError (String::New (\"First argument should have \\\"source\\\" key with a Buffer instance\")));\n }\n\n std::vector <std::string> optionArgs;\n\n if (!options->Get (String::NewSymbol (\"lossy\"))->IsUndefined()) {\n Local<Boolean> value = options->Get (String::NewSymbol (\"lossy\"))->ToBoolean();\n\n if (value->Value()) {\n optionArgs.push_back (\"-lossy\");\n }\n }\n\n if (!options->Get (String::NewSymbol (\"mixed\"))->IsUndefined()) {\n Local<Boolean> value = options->Get (String::NewSymbol (\"mixed\"))->ToBoolean();\n if (value->Value()) {\n optionArgs.push_back (\"-mixed\");\n }\n }\n\n if (!options->Get (String::NewSymbol (\"quality\"))->IsUndefined()) {\n Local<Number> value = options->Get (String::NewSymbol (\"quality\"))->ToNumber();\n optionArgs.push_back (\"-q\");\n std::ostringstream s;\n s << (double) value->Value();\n optionArgs.push_back (s.str());\n }\n\n if (!options->Get (String::NewSymbol (\"method\"))->IsUndefined()) {\n Local<Number> value = options->Get (String::NewSymbol (\"method\"))->ToNumber();\n optionArgs.push_back (\"-m\");\n std::ostringstream s;\n s << (double) value->Value();\n optionArgs.push_back (s.str());\n }\n\n if (!options->Get (String::NewSymbol (\"kmin\"))->IsUndefined()) {\n Local<Number> value = options->Get (String::NewSymbol (\"kmin\"))->ToNumber();\n optionArgs.push_back (\"-kmin\");\n std::ostringstream s;\n s << (double) value->Value();\n optionArgs.push_back (s.str());\n }\n\n if (!options->Get (String::NewSymbol (\"kmax\"))->IsUndefined()) {\n Local<Number> value = options->Get (String::NewSymbol (\"kmax\"))->ToNumber();\n optionArgs.push_back (\"-kmax\");\n std::ostringstream s;\n s << (double) value->Value();\n optionArgs.push_back (s.str());\n }\n\n if (!options->Get (String::NewSymbol (\"filter\"))->IsUndefined()) {\n Local<Number> value = options->Get (String::NewSymbol (\"filter\"))->ToNumber();\n optionArgs.push_back (\"-f\");\n std::ostringstream s;\n s << (double) value->Value();\n optionArgs.push_back (s.str());\n }\n\n if (!options->Get (String::NewSymbol (\"metadata\"))->IsUndefined()) {\n Local<String> value = options->Get (String::NewSymbol (\"metadata\"))->ToString();\n String::Utf8Value utf8Value (value);\n optionArgs.push_back (\"-metadata\");\n optionArgs.push_back (std::string (*utf8Value));\n }\n\n if (!options->Get (String::NewSymbol (\"mt\"))->IsUndefined()) {\n Local<Boolean> value = options->Get (String::NewSymbol (\"mt\"))->ToBoolean();\n if (value->Value()) {\n optionArgs.push_back (\"-mt\");\n }\n }\n\n if (!options->Get (String::NewSymbol (\"verbose\"))->IsUndefined()) {\n Local<Boolean> value = options->Get (String::NewSymbol (\"verbose\"))->ToBoolean();\n if (value->Value()) {\n optionArgs.push_back (\"-v\");\n }\n }\n\n const char* convert_argv [optionArgs.size()];\n int convert_argc = optionArgs.size();\n for (int i = 0; i < (int) optionArgs.size(); ++i) {\n convert_argv [i] = optionArgs [i].c_str();\n }\n\n const size_t inDataSize = Buffer::Length (buffer);\n const char* inData = Buffer::Data (buffer);\n\n WebPData outData;\n convert (convert_argc, convert_argv, (char*) inData, inDataSize, &outData);\n\n Local<Object> globalObj = v8::Context::GetCurrent()->Global();\n\n Buffer* slowBuffer = node::Buffer::New (outData.size);\n memcpy (node::Buffer::Data (slowBuffer), outData.bytes, outData.size);\n Local<Function> bufferConstructor = Local<Function>::Cast (globalObj->Get (String::New (\"Buffer\")));\n\n Handle<Value> constructorArgs [3] = { \n slowBuffer->handle_, \n Integer::New (outData.size),\n Integer::New (0) \n };\n\n Local<Object> actualBuffer = bufferConstructor->NewInstance (3, constructorArgs);\n WebPDataClear (&outData);\n\n const unsigned argc = 2;\n Local<Value> argv [argc] = {\n Local<Value>::New (Null()),\n Local<Value>::New (actualBuffer)\n };\n\n Local<Function> callback = Local<Function>::Cast (args [1]);\n callback->Call (Context::GetCurrent()->Global(), argc, argv);\n\n return Undefined();\n}\n\nvoid RegisterModule (v8::Handle<v8::Object> target) {\n target->Set (String::NewSymbol (\"convert\"), FunctionTemplate::New (convert)->GetFunction());\n}\n\nNODE_MODULE (gif2webp, RegisterModule);\n<commit_msg>Added HandleScope#Close call in gif2webp.cpp#convert.<commit_after>\/*\n ==============================================================================\n \n Copyright (c) 2014 Jacob Sologub\n \n Permission is hereby granted, free of charge, to any person obtaining a copy \n of this software and associated documentation files (the \"Software\"), to deal \n in the Software without restriction, including without limitation the rights \n to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell \n copies of the Software, and to permit persons to whom the Software is \n furnished to do so, subject to the following conditions:\n \n The above copyright notice and this permission notice shall be included in \n all copies or substantial portions of the Software.\n \n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, \n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE \n AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER \n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, \n OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE \n SOFTWARE.\n\n ==============================================================================\n*\/\n\n#include \"gif2webpMain.h\"\n#include <node.h>\n#include <node_buffer.h>\n#include <v8.h>\n#include <string.h>\n#include <iostream>\n#include <iostream>\n#include <fstream>\n#include <sstream>\n#include <vector>\n\nusing namespace v8;\nusing namespace node;\n\n\/\/ {\n\/\/ source required. <Buffer> Buffer with binary image data.\n\/\/ lossy: optional. <Boolean> Encode image using lossy compression\n\/\/ mixed: optional. <Boolean> For each frame in the image, pick lossy or lossless compression heuristically.\n\/\/ quality: optional. <Number> Quality factor (0:small..100:big)\n\/\/ method: optional. <Number> Compression method Quality (0=fast, 6=slowest)\n\/\/ kmin: optional. <Number> Min distance between key frames\n\/\/ kmax: optional. <Number> Max distance between key frames\n\/\/ filter: optional. <Number> Filter strength (0=off..100)\n\/\/ metadata: optional. <String> comma separated list of metadata to copy from the input to the output if present. Valid values: all, none, icc, xmp (default)\n\/\/ mt: optional. <Boolean> Use multi-threading if available\n\/\/ verbose: optional. <Boolean> Verbose output from gif2webp\n\/\/ }\n\nHandle<Value> convert (const Arguments& args) {\n HandleScope scope;\n\n if (args.Length() < 2) {\n return ThrowException (Exception::TypeError (String::New (\"Wrong number of arguments.\")));\n }\n\n if (!args [0]->IsObject()) {\n return ThrowException (Exception::TypeError (String::New (\"First argument must be be an object.\")));\n }\n\n if (!args [1]->IsFunction()) {\n return ThrowException (Exception::TypeError (String::New (\"Second argument must be a callback function.\")));\n }\n\n Local<Object> options = args [0]->ToObject();\n\n Local<Object> buffer = Local<Object>::Cast (options->Get (String::NewSymbol (\"source\")));\n if (buffer->IsUndefined() || !Buffer::HasInstance (buffer)) {\n return ThrowException (Exception::TypeError (String::New (\"First argument should have \\\"source\\\" key with a Buffer instance\")));\n }\n\n std::vector <std::string> optionArgs;\n\n if (!options->Get (String::NewSymbol (\"lossy\"))->IsUndefined()) {\n Local<Boolean> value = options->Get (String::NewSymbol (\"lossy\"))->ToBoolean();\n\n if (value->Value()) {\n optionArgs.push_back (\"-lossy\");\n }\n }\n\n if (!options->Get (String::NewSymbol (\"mixed\"))->IsUndefined()) {\n Local<Boolean> value = options->Get (String::NewSymbol (\"mixed\"))->ToBoolean();\n if (value->Value()) {\n optionArgs.push_back (\"-mixed\");\n }\n }\n\n if (!options->Get (String::NewSymbol (\"quality\"))->IsUndefined()) {\n Local<Number> value = options->Get (String::NewSymbol (\"quality\"))->ToNumber();\n optionArgs.push_back (\"-q\");\n std::ostringstream s;\n s << (double) value->Value();\n optionArgs.push_back (s.str());\n }\n\n if (!options->Get (String::NewSymbol (\"method\"))->IsUndefined()) {\n Local<Number> value = options->Get (String::NewSymbol (\"method\"))->ToNumber();\n optionArgs.push_back (\"-m\");\n std::ostringstream s;\n s << (double) value->Value();\n optionArgs.push_back (s.str());\n }\n\n if (!options->Get (String::NewSymbol (\"kmin\"))->IsUndefined()) {\n Local<Number> value = options->Get (String::NewSymbol (\"kmin\"))->ToNumber();\n optionArgs.push_back (\"-kmin\");\n std::ostringstream s;\n s << (double) value->Value();\n optionArgs.push_back (s.str());\n }\n\n if (!options->Get (String::NewSymbol (\"kmax\"))->IsUndefined()) {\n Local<Number> value = options->Get (String::NewSymbol (\"kmax\"))->ToNumber();\n optionArgs.push_back (\"-kmax\");\n std::ostringstream s;\n s << (double) value->Value();\n optionArgs.push_back (s.str());\n }\n\n if (!options->Get (String::NewSymbol (\"filter\"))->IsUndefined()) {\n Local<Number> value = options->Get (String::NewSymbol (\"filter\"))->ToNumber();\n optionArgs.push_back (\"-f\");\n std::ostringstream s;\n s << (double) value->Value();\n optionArgs.push_back (s.str());\n }\n\n if (!options->Get (String::NewSymbol (\"metadata\"))->IsUndefined()) {\n Local<String> value = options->Get (String::NewSymbol (\"metadata\"))->ToString();\n String::Utf8Value utf8Value (value);\n optionArgs.push_back (\"-metadata\");\n optionArgs.push_back (std::string (*utf8Value));\n }\n\n if (!options->Get (String::NewSymbol (\"mt\"))->IsUndefined()) {\n Local<Boolean> value = options->Get (String::NewSymbol (\"mt\"))->ToBoolean();\n if (value->Value()) {\n optionArgs.push_back (\"-mt\");\n }\n }\n\n if (!options->Get (String::NewSymbol (\"verbose\"))->IsUndefined()) {\n Local<Boolean> value = options->Get (String::NewSymbol (\"verbose\"))->ToBoolean();\n if (value->Value()) {\n optionArgs.push_back (\"-v\");\n }\n }\n\n const char* convert_argv [optionArgs.size()];\n int convert_argc = optionArgs.size();\n for (int i = 0; i < (int) optionArgs.size(); ++i) {\n convert_argv [i] = optionArgs [i].c_str();\n }\n\n const size_t inDataSize = Buffer::Length (buffer);\n const char* inData = Buffer::Data (buffer);\n\n WebPData outData;\n convert (convert_argc, convert_argv, (char*) inData, inDataSize, &outData);\n\n Local<Object> globalObj = v8::Context::GetCurrent()->Global();\n\n Buffer* slowBuffer = node::Buffer::New (outData.size);\n memcpy (node::Buffer::Data (slowBuffer), outData.bytes, outData.size);\n Local<Function> bufferConstructor = Local<Function>::Cast (globalObj->Get (String::New (\"Buffer\")));\n\n Handle<Value> constructorArgs [3] = { \n slowBuffer->handle_, \n Integer::New (outData.size),\n Integer::New (0) \n };\n\n Local<Object> actualBuffer = bufferConstructor->NewInstance (3, constructorArgs);\n WebPDataClear (&outData);\n\n const unsigned argc = 2;\n Local<Value> argv [argc] = {\n Local<Value>::New (Null()),\n Local<Value>::New (actualBuffer)\n };\n\n Local<Function> callback = Local<Function>::Cast (args [1]);\n callback->Call (Context::GetCurrent()->Global(), argc, argv);\n\n return scope.Close (Undefined());\n}\n\nvoid RegisterModule (v8::Handle<v8::Object> target) {\n target->Set (String::NewSymbol (\"convert\"), FunctionTemplate::New (convert)->GetFunction());\n}\n\nNODE_MODULE (gif2webp, RegisterModule);\n<|endoftext|>"} {"text":"<commit_before>\/\/\/\n\/\/\/ @file iterator.cpp\n\/\/\/\n\/\/\/ Copyright (C) 2022 Kim Walisch, <kim.walisch@gmail.com>\n\/\/\/\n\/\/\/ This file is distributed under the BSD License. See the COPYING\n\/\/\/ file in the top level directory.\n\/\/\/\n\n#include <primesieve\/iterator.hpp>\n#include <primesieve\/IteratorHelper.hpp>\n#include <primesieve\/PrimeGenerator.hpp>\n#include <primesieve\/macros.hpp>\n#include <primesieve\/pod_vector.hpp>\n\n#include <stdint.h>\n#include <limits>\n\nnamespace {\n\nvoid freeAllMemory(primesieve::iterator* it)\n{\n if (it->memory_)\n {\n using primesieve::IteratorData;\n delete (IteratorData*) it->memory_;\n it->memory_ = nullptr;\n }\n}\n\n} \/\/ namespace\n\nnamespace primesieve {\n\niterator::iterator() noexcept :\n i_(0),\n size_(0),\n start_(0),\n stop_hint_(std::numeric_limits<uint64_t>::max()),\n primes_(nullptr),\n memory_(nullptr)\n{ }\n\niterator::iterator(uint64_t start,\n uint64_t stop_hint) noexcept :\n i_(0),\n size_(0),\n start_(start),\n stop_hint_(stop_hint),\n primes_(nullptr),\n memory_(nullptr)\n{ }\n\n\/\/\/ Move constructor\niterator::iterator(iterator&& other) noexcept :\n i_(other.i_),\n size_(other.size_),\n start_(other.start_),\n stop_hint_(other.stop_hint_),\n primes_(other.primes_),\n memory_(other.memory_)\n{\n other.i_ = 0;\n other.size_ = 0;\n other.start_ = 0;\n other.stop_hint_ = std::numeric_limits<uint64_t>::max();\n other.primes_ = nullptr;\n other.memory_ = nullptr;\n}\n\n\/\/\/ Move assignment operator\niterator& iterator::operator=(iterator&& other) noexcept\n{\n if (this != &other)\n {\n freeAllMemory(this);\n\n i_ = other.i_;\n size_ = other.size_;\n start_ = other.start_;\n stop_hint_ = other.stop_hint_;\n primes_ = other.primes_;\n memory_ = other.memory_;\n\n other.i_ = 0;\n other.size_ = 0;\n other.start_ = 0;\n other.stop_hint_ = std::numeric_limits<uint64_t>::max();\n other.primes_ = nullptr;\n other.memory_ = nullptr;\n }\n\n return *this;\n}\n\nvoid iterator::jump_to(uint64_t start,\n uint64_t stop_hint) noexcept\n{\n i_ = 0;\n size_ = 0;\n start_ = start;\n stop_hint_ = stop_hint;\n primes_ = nullptr;\n\n \/\/ Frees most memory, but keeps some smaller data\n \/\/ structures (e.g. the PreSieve object) that are\n \/\/ useful if the primesieve::iterator is reused.\n \/\/ The remaining memory uses at most 200 kilobytes.\n if (memory_)\n {\n auto& iterData = *(IteratorData*) memory_;\n iterData.stop = start;\n iterData.dist = 0;\n iterData.include_start_number = true;\n iterData.deletePrimeGenerator();\n iterData.deletePrimes();\n }\n}\n\nvoid iterator::clear() noexcept\n{\n jump_to(0);\n}\n\niterator::~iterator()\n{\n freeAllMemory(this);\n}\n\nvoid iterator::generate_next_primes()\n{\n if (!memory_)\n memory_ = new IteratorData(start_);\n\n auto& iterData = *(IteratorData*) memory_;\n auto& primes = iterData.primes;\n\n while (true)\n {\n if (!iterData.primeGenerator)\n {\n IteratorHelper::updateNext(start_, stop_hint_, iterData);\n iterData.primeGenerator = new PrimeGenerator(start_, iterData.stop, iterData.preSieve);\n }\n\n iterData.primeGenerator->fillNextPrimes(primes, &size_);\n primes_ = primes.data();\n i_ = 0;\n\n \/\/ There are 2 different cases here:\n \/\/ 1) The primes array is empty because the next prime > stop.\n \/\/ In this case we reset the primeGenerator object, increase\n \/\/ the start & stop numbers and sieve the next segment.\n \/\/ 2) The primes array is not empty (contains up to 1024 primes),\n \/\/ in this case we return it to the user.\n if_unlikely(size_ == 0)\n iterData.deletePrimeGenerator();\n else\n return;\n }\n}\n\nvoid iterator::generate_prev_primes()\n{\n if (!memory_)\n memory_ = new IteratorData(start_);\n\n auto& iterData = *(IteratorData*) memory_;\n auto& primes = iterData.primes;\n\n \/\/ Special case if generate_next_primes() has\n \/\/ been used before generate_prev_primes().\n if_unlikely(iterData.primeGenerator)\n {\n start_ = primes.front();\n iterData.deletePrimeGenerator();\n ASSERT(!iterData.include_start_number);\n }\n\n \/\/ When sieving backwards the sieving distance is subdivided\n \/\/ into smaller chunks. If we can prove that the total\n \/\/ sieving distance is large we enable pre-sieving.\n if (iterData.dist == 0 &&\n stop_hint_ < start_)\n iterData.preSieve.init(stop_hint_, start_);\n\n do\n {\n IteratorHelper::updatePrev(start_, stop_hint_, iterData);\n PrimeGenerator primeGenerator(start_, iterData.stop, iterData.preSieve);\n primeGenerator.fillPrevPrimes(primes, &size_);\n primes_ = primes.data();\n i_ = size_;\n }\n while (!size_);\n}\n\n} \/\/ namespace\n<commit_msg>Use delegating constructor<commit_after>\/\/\/\n\/\/\/ @file iterator.cpp\n\/\/\/\n\/\/\/ Copyright (C) 2022 Kim Walisch, <kim.walisch@gmail.com>\n\/\/\/\n\/\/\/ This file is distributed under the BSD License. See the COPYING\n\/\/\/ file in the top level directory.\n\/\/\/\n\n#include <primesieve\/iterator.hpp>\n#include <primesieve\/IteratorHelper.hpp>\n#include <primesieve\/PrimeGenerator.hpp>\n#include <primesieve\/macros.hpp>\n#include <primesieve\/pod_vector.hpp>\n\n#include <stdint.h>\n#include <limits>\n\nnamespace {\n\nvoid freeAllMemory(primesieve::iterator* it)\n{\n if (it->memory_)\n {\n using primesieve::IteratorData;\n delete (IteratorData*) it->memory_;\n it->memory_ = nullptr;\n }\n}\n\n} \/\/ namespace\n\nnamespace primesieve {\n\niterator::iterator() noexcept :\n iterator(0)\n{ }\n\niterator::iterator(uint64_t start,\n uint64_t stop_hint) noexcept :\n i_(0),\n size_(0),\n start_(start),\n stop_hint_(stop_hint),\n primes_(nullptr),\n memory_(nullptr)\n{ }\n\n\/\/\/ Move constructor\niterator::iterator(iterator&& other) noexcept :\n i_(other.i_),\n size_(other.size_),\n start_(other.start_),\n stop_hint_(other.stop_hint_),\n primes_(other.primes_),\n memory_(other.memory_)\n{\n other.i_ = 0;\n other.size_ = 0;\n other.start_ = 0;\n other.stop_hint_ = std::numeric_limits<uint64_t>::max();\n other.primes_ = nullptr;\n other.memory_ = nullptr;\n}\n\n\/\/\/ Move assignment operator\niterator& iterator::operator=(iterator&& other) noexcept\n{\n if (this != &other)\n {\n freeAllMemory(this);\n\n i_ = other.i_;\n size_ = other.size_;\n start_ = other.start_;\n stop_hint_ = other.stop_hint_;\n primes_ = other.primes_;\n memory_ = other.memory_;\n\n other.i_ = 0;\n other.size_ = 0;\n other.start_ = 0;\n other.stop_hint_ = std::numeric_limits<uint64_t>::max();\n other.primes_ = nullptr;\n other.memory_ = nullptr;\n }\n\n return *this;\n}\n\nvoid iterator::jump_to(uint64_t start,\n uint64_t stop_hint) noexcept\n{\n i_ = 0;\n size_ = 0;\n start_ = start;\n stop_hint_ = stop_hint;\n primes_ = nullptr;\n\n \/\/ Frees most memory, but keeps some smaller data\n \/\/ structures (e.g. the PreSieve object) that are\n \/\/ useful if the primesieve::iterator is reused.\n \/\/ The remaining memory uses at most 200 kilobytes.\n if (memory_)\n {\n auto& iterData = *(IteratorData*) memory_;\n iterData.stop = start;\n iterData.dist = 0;\n iterData.include_start_number = true;\n iterData.deletePrimeGenerator();\n iterData.deletePrimes();\n }\n}\n\nvoid iterator::clear() noexcept\n{\n jump_to(0);\n}\n\niterator::~iterator()\n{\n freeAllMemory(this);\n}\n\nvoid iterator::generate_next_primes()\n{\n if (!memory_)\n memory_ = new IteratorData(start_);\n\n auto& iterData = *(IteratorData*) memory_;\n auto& primes = iterData.primes;\n\n while (true)\n {\n if (!iterData.primeGenerator)\n {\n IteratorHelper::updateNext(start_, stop_hint_, iterData);\n iterData.primeGenerator = new PrimeGenerator(start_, iterData.stop, iterData.preSieve);\n }\n\n iterData.primeGenerator->fillNextPrimes(primes, &size_);\n primes_ = primes.data();\n i_ = 0;\n\n \/\/ There are 2 different cases here:\n \/\/ 1) The primes array is empty because the next prime > stop.\n \/\/ In this case we reset the primeGenerator object, increase\n \/\/ the start & stop numbers and sieve the next segment.\n \/\/ 2) The primes array is not empty (contains up to 1024 primes),\n \/\/ in this case we return it to the user.\n if_unlikely(size_ == 0)\n iterData.deletePrimeGenerator();\n else\n return;\n }\n}\n\nvoid iterator::generate_prev_primes()\n{\n if (!memory_)\n memory_ = new IteratorData(start_);\n\n auto& iterData = *(IteratorData*) memory_;\n auto& primes = iterData.primes;\n\n \/\/ Special case if generate_next_primes() has\n \/\/ been used before generate_prev_primes().\n if_unlikely(iterData.primeGenerator)\n {\n start_ = primes.front();\n iterData.deletePrimeGenerator();\n ASSERT(!iterData.include_start_number);\n }\n\n \/\/ When sieving backwards the sieving distance is subdivided\n \/\/ into smaller chunks. If we can prove that the total\n \/\/ sieving distance is large we enable pre-sieving.\n if (iterData.dist == 0 &&\n stop_hint_ < start_)\n iterData.preSieve.init(stop_hint_, start_);\n\n do\n {\n IteratorHelper::updatePrev(start_, stop_hint_, iterData);\n PrimeGenerator primeGenerator(start_, iterData.stop, iterData.preSieve);\n primeGenerator.fillPrevPrimes(primes, &size_);\n primes_ = primes.data();\n i_ = size_;\n }\n while (!size_);\n}\n\n} \/\/ namespace\n<|endoftext|>"} {"text":"<commit_before>#include <stdio.h>\n#include <string.h>\n#include <stdlib.h>\n#include <stdint.h>\n\n#include \"keygen.h\"\n#include \"crc32.h\"\n\nstatic char *abt_array =\n (char*)\"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_\";\n\nvoid keygen_init(\n struct keygen *keygen,\n size_t nprefix,\n struct rndinfo *prefix_len,\n struct rndinfo *prefix_dist,\n struct keygen_option *opt)\n{\n keygen->nprefix = nprefix;\n keygen->prefix_len = (struct rndinfo *)malloc(sizeof(struct rndinfo) * nprefix);\n keygen->prefix_dist = (struct rndinfo *)malloc(sizeof(struct rndinfo) * nprefix);\n keygen->opt = *opt;\n keygen->abt_array_size = strlen(abt_array);\n\n memcpy(keygen->prefix_len, prefix_len, sizeof(struct rndinfo) * nprefix);\n memcpy(keygen->prefix_dist, prefix_dist, sizeof(struct rndinfo) * nprefix);\n}\n\nvoid keygen_free(struct keygen *keygen)\n{\n free(keygen->prefix_len);\n free(keygen->prefix_dist);\n}\n\nvoid _crc2key(struct keygen *keygen, uint64_t crc, char *buf, size_t len, uint8_t abt_only)\n{\n int i;\n BDR_RNG_VARS_SET(crc);\n BDR_RNG_NEXTPAIR;\n BDR_RNG_NEXT;\n BDR_RNG_NEXT;\n\n for (i=0;i<len;i+=1){\n BDR_RNG_NEXT;\n BDR_RNG_NEXT;\n if (abt_only) {\n buf[i] = abt_array[(rngz%(keygen->abt_array_size))];\n \/\/buf[i] = 'a' + (rngz%('z'-'a'));\n } else {\n buf[i] = rngz & 0xff;\n }\n }\n}\n\nsize_t _crc2keylen(struct rndinfo *prefix_len, uint64_t crc)\n{\n size_t r;\n BDR_RNG_VARS_SET(crc);\n BDR_RNG_NEXTPAIR;\n BDR_RNG_NEXTPAIR;\n BDR_RNG_NEXTPAIR;\n\n r = get_random(prefix_len, rngz, rngz2);\n return r;\n}\n\nuint32_t keygen_idx2crc(uint64_t idx, uint32_t seed)\n{\n uint32_t crc;\n uint64_t idx64 = idx;\n crc = crc32_8(&idx64, sizeof(idx64), seed);\n crc = crc32_8(&idx64, sizeof(idx64), crc);\n return crc;\n}\n\nuint64_t MurmurHash64A ( const void * key, int len, unsigned int seed )\n{\n const uint64_t m = 0xc6a4a7935bd1e995;\n const int r = 47;\n\n uint64_t h = seed ^ (len * m);\n\n const uint64_t * data = (const uint64_t *)key;\n const uint64_t * end = data + (len\/8);\n\n while(data != end)\n {\n uint64_t k = *data++;\n\n k *= m;\n k ^= k >> r;\n k *= m;\n\n h ^= k;\n h *= m;\n }\n\n const unsigned char * data2 = (const unsigned char*)data;\n\n switch(len & 7)\n {\n case 7: h ^= uint64_t(data2[6]) << 48;\n case 6: h ^= uint64_t(data2[5]) << 40;\n case 5: h ^= uint64_t(data2[4]) << 32;\n case 4: h ^= uint64_t(data2[3]) << 24;\n case 3: h ^= uint64_t(data2[2]) << 16;\n case 2: h ^= uint64_t(data2[1]) << 8;\n case 1: h ^= uint64_t(data2[0]);\n h *= m;\n };\n\n h ^= h >> r;\n h *= m;\n h ^= h >> r;\n\n return h;\n}\n\nsize_t keygen_seed2key(struct keygen *keygen, uint64_t seed, char *buf)\n{\n uint64_t i;\n size_t len, cursor;\n uint64_t seed_local, seed64, rnd_sel;\n\n seed64 = MurmurHash64A(&seed, sizeof(uint64_t), 0);\n BDR_RNG_VARS_SET(seed64);\n BDR_RNG_NEXTPAIR;\n BDR_RNG_NEXTPAIR;\n BDR_RNG_NEXTPAIR;\n\n cursor = 0;\n for (i=0;i<keygen->nprefix;++i){\n if (i+1 == keygen->nprefix) {\n len = _crc2keylen(&keygen->prefix_len[i], seed64);\n _crc2key(keygen, seed64, buf + cursor, len, keygen->opt.abt_only);\n } else {\n BDR_RNG_NEXTPAIR;\n BDR_RNG_NEXTPAIR;\n rnd_sel = get_random(&keygen->prefix_dist[i], rngz, rngz2);\n seed_local = MurmurHash64A(&rnd_sel, sizeof(rnd_sel), 0);\n\n len = _crc2keylen(&keygen->prefix_len[i], seed_local);\n _crc2key(keygen, seed_local, buf + cursor, len, keygen->opt.abt_only);\n }\n\n cursor += len;\n\n if (keygen->opt.delimiter && i != keygen->nprefix-1) {\n buf[cursor] = '\/';\n cursor++;\n }\n }\n buf[cursor] = 0;\n return cursor;\n}\n\n<commit_msg>Fix keygen random number initialization<commit_after>#include <stdio.h>\n#include <string.h>\n#include <stdlib.h>\n#include <stdint.h>\n\n#include \"keygen.h\"\n#include \"crc32.h\"\n\nstatic char *abt_array =\n (char*)\"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_\";\n\nvoid keygen_init(\n struct keygen *keygen,\n size_t nprefix,\n struct rndinfo *prefix_len,\n struct rndinfo *prefix_dist,\n struct keygen_option *opt)\n{\n keygen->nprefix = nprefix;\n keygen->prefix_len = (struct rndinfo *)malloc(sizeof(struct rndinfo) * nprefix);\n keygen->prefix_dist = (struct rndinfo *)malloc(sizeof(struct rndinfo) * nprefix);\n keygen->opt = *opt;\n keygen->abt_array_size = strlen(abt_array);\n\n memcpy(keygen->prefix_len, prefix_len, sizeof(struct rndinfo) * nprefix);\n memcpy(keygen->prefix_dist, prefix_dist, sizeof(struct rndinfo) * nprefix);\n}\n\nvoid keygen_free(struct keygen *keygen)\n{\n free(keygen->prefix_len);\n free(keygen->prefix_dist);\n}\n\nvoid _crc2key(struct keygen *keygen, uint64_t crc, char *buf, size_t len, uint8_t abt_only)\n{\n int i;\n BDR_RNG_VARS_SET(crc);\n BDR_RNG_NEXTPAIR;\n BDR_RNG_NEXT;\n\n for (i=0;i<len;i+=1){\n BDR_RNG_NEXTPAIR;\n if (abt_only) {\n buf[i] = abt_array[(rngz%(keygen->abt_array_size))];\n \/\/buf[i] = 'a' + (rngz%('z'-'a'));\n } else {\n buf[i] = rngz & 0xff;\n }\n }\n}\n\nsize_t _crc2keylen(struct rndinfo *prefix_len, uint64_t crc)\n{\n size_t r;\n BDR_RNG_VARS_SET(crc);\n BDR_RNG_NEXTPAIR;\n BDR_RNG_NEXT;\n\n r = get_random(prefix_len, rngz, rngz2);\n return r;\n}\n\nuint32_t keygen_idx2crc(uint64_t idx, uint32_t seed)\n{\n uint32_t crc;\n uint64_t idx64 = idx;\n crc = crc32_8(&idx64, sizeof(idx64), seed);\n crc = crc32_8(&idx64, sizeof(idx64), crc);\n return crc;\n}\n\nuint64_t MurmurHash64A ( const void * key, int len, unsigned int seed )\n{\n const uint64_t m = 0xc6a4a7935bd1e995;\n const int r = 47;\n\n uint64_t h = seed ^ (len * m);\n\n const uint64_t * data = (const uint64_t *)key;\n const uint64_t * end = data + (len\/8);\n\n while(data != end)\n {\n uint64_t k = *data++;\n\n k *= m;\n k ^= k >> r;\n k *= m;\n\n h ^= k;\n h *= m;\n }\n\n const unsigned char * data2 = (const unsigned char*)data;\n\n switch(len & 7)\n {\n case 7: h ^= uint64_t(data2[6]) << 48;\n case 6: h ^= uint64_t(data2[5]) << 40;\n case 5: h ^= uint64_t(data2[4]) << 32;\n case 4: h ^= uint64_t(data2[3]) << 24;\n case 3: h ^= uint64_t(data2[2]) << 16;\n case 2: h ^= uint64_t(data2[1]) << 8;\n case 1: h ^= uint64_t(data2[0]);\n h *= m;\n };\n\n h ^= h >> r;\n h *= m;\n h ^= h >> r;\n\n return h;\n}\n\nsize_t keygen_seed2key(struct keygen *keygen, uint64_t seed, char *buf)\n{\n uint64_t i;\n size_t len, cursor;\n uint64_t seed_local, seed64, rnd_sel;\n\n seed64 = MurmurHash64A(&seed, sizeof(uint64_t), 0);\n BDR_RNG_VARS_SET(seed64);\n BDR_RNG_NEXTPAIR;\n BDR_RNG_NEXT;\n\n cursor = 0;\n for (i=0;i<keygen->nprefix;++i){\n if (i+1 == keygen->nprefix) {\n len = _crc2keylen(&keygen->prefix_len[i], seed64);\n _crc2key(keygen, seed64, buf + cursor, len, keygen->opt.abt_only);\n } else {\n BDR_RNG_NEXTPAIR;\n BDR_RNG_NEXT;\n rnd_sel = get_random(&keygen->prefix_dist[i], rngz, rngz2);\n seed_local = MurmurHash64A(&rnd_sel, sizeof(rnd_sel), 0);\n\n len = _crc2keylen(&keygen->prefix_len[i], seed_local);\n _crc2key(keygen, seed_local, buf + cursor, len, keygen->opt.abt_only);\n }\n\n cursor += len;\n\n if (keygen->opt.delimiter && i != keygen->nprefix-1) {\n buf[cursor] = '\/';\n cursor++;\n }\n }\n buf[cursor] = 0;\n return cursor;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/**\r\n * memory.cpp - Implementation of memory model\r\n * Define classes and method to operate with memory of simulated architecture\r\n * Copyright 2009 MDSP team\r\n *\/\r\n\r\n\r\n#include <iostream>\r\n#include <cassert>\r\n#include <math.h>\r\n#ifndef MEMORY_HEADER\r\n#define MEMORY_HEADER\r\n#include \"memory.h\"\r\n#endif \/* MEMORY_HEADER*\/\r\n\r\n\/**\r\n * Implementation of class ByteLine\r\n *\/\r\nByteLine::ByteLine()\r\n{\r\n byte_line = new vector<Byte>;\r\n output = DEFAULT_OUT;\r\n}\r\n\r\nByteLine::ByteLine( unsigned int count)\r\n{\r\n byte_line = new vector<Byte>;\r\n output = DEFAULT_OUT;\r\n try\r\n {\r\n (*byte_line).resize( count);\r\n }catch ( std::bad_alloc)\r\n {\r\n cout << \"ERROR: Can not allocate memory!\\n\";\r\n assert( 0);\r\n }\r\n}\r\n\r\nByteLine::ByteLine( const ByteLine& line)\r\n{\r\n output = DEFAULT_OUT;\r\n try\r\n {\r\n byte_line = new vector<Byte>( line.getSizeOfLine());\r\n }catch ( std::bad_alloc)\r\n {\r\n cout << \"ERROR: Can not allocate memory!\\n\";\r\n assert( 0);\r\n }\r\n for ( unsigned int i = 0 ; i < line.getSizeOfLine(); i++)\r\n {\r\n ( *byte_line).at( i).setByteVal( line.getByteVal( i));\r\n }\r\n}\r\nByteLine::ByteLine( const Byte& byte)\r\n{\r\n output = DEFAULT_OUT;\r\n try\r\n {\r\n byte_line = new vector<Byte>;\r\n ( *byte_line).push_back( byte);\r\n }catch ( std::bad_alloc)\r\n {\r\n cout << \"ERROR: Can not allocate memory!\\n\";\r\n assert( 0);\r\n }\r\n}\r\n\r\n \/* Conversion functions ByteLine into hostUInt8, hostUInt16, hostUInt32 *\/\r\nhostUInt8 ByteLine::getHostUInt8()\r\n{\r\n return this->getByteVal( 0);\r\n}\r\n\r\nhostUInt16 ByteLine::getHostUInt16()\r\n{\r\n hostUInt8 temp[] = { this->getByteVal( 1), this->getByteVal( 0)};\r\n hostUInt16 var = 0;\r\n var += temp[ 0];\r\n var = ( var << 8);\r\n var += temp[ 1];\r\n return var;\r\n}\r\n\r\nhostUInt32 ByteLine::getHostUInt32()\r\n{\r\n hostUInt8 temp[] = { this->getByteVal( 3), this->getByteVal( 2), \r\n this->getByteVal( 1), this->getByteVal( 0)};\r\n hostUInt32 var = 0;\r\n for ( int i = 0; i < 3; i++)\r\n {\r\n var += temp[ i];\r\n var = ( var << 8);\r\n }\r\n var += temp[3];\r\n return var;\r\n}\r\n\r\n \/* Private functions converting hostUInt8,16,32 into vector<Byte> *byte_line *\/\r\nvoid ByteLine::convert8( vector<Byte> *byte_line, hostUInt8 var)\r\n{\r\n Byte byte( var);\r\n ( *byte_line).push_back( byte);\r\n}\r\n\r\nvoid ByteLine::convert16( vector<Byte> *byte_line, hostUInt16 var, OrderType type)\r\n{\r\n\/* hostUInt8 temp1 = 0;\r\n hostUInt8 temp2 = 0;\r\n for ( int i = 0; i < 8; i++)\r\n {\r\n if ( var & 1)\r\n temp1 += ( 1 << i);\r\n var = (var >> 1);\r\n }\r\n for ( int i = 0; i < 8; i++)\r\n {\r\n if ( var & 1)\r\n temp2 += ( 1 << i);\r\n var = ( var >> 1);\r\n }\r\n Byte a( temp1);\r\n Byte b( temp2);\r\n if ( type == HIGH_FIRST)\r\n {\r\n ( *byte_line).push_back( a);\r\n ( *byte_line).push_back( b);\r\n } else\r\n {\r\n ( *byte_line).push_back( b);\r\n ( *byte_line).push_back( a);\r\n }\r\n*\/\r\n hostUInt8 temp[2] = { 0, 0};\r\n for ( int i = 0; i < 2; i++)\r\n {\r\n for( int k = 0; k < 8; k++)\r\n {\r\n if ( var & 1)\r\n temp[ i] += ( 1 << k);\r\n var = ( var >> 1);\r\n }\r\n }\r\n Byte byte[] = { temp[ 0], temp[ 1]};\r\n if ( type == HIGH_FIRST)\r\n {\r\n for ( int i = 0; i < 2; i++)\r\n ( *byte_line).push_back( byte[ i]);\r\n } else\r\n {\r\n for ( int i = 2; i > 0; i--)\r\n ( *byte_line).push_back( byte[ i-1]);\r\n }\r\n}\r\n\r\nvoid ByteLine::convert32( vector<Byte> *byte_line, hostUInt32 var, OrderType type)\r\n{\r\n\/*\r\n hostUInt8 temp1 = 0;\r\n hostUInt8 temp2 = 0;\r\n hostUInt8 temp3 = 0;\r\n hostUInt8 temp4 = 0;\r\n for ( int i = 0; i < 8; i++)\r\n {\r\n if ( var & 1)\r\n temp1 += ( 1 << i);\r\n var = (var >> 1);\r\n }\r\n for ( int i = 0; i < 8; i++)\r\n {\r\n if ( var & 1)\r\n temp2 += ( 1 << i);\r\n var = (var >> 1);\r\n }\r\n for ( int i = 0; i < 8; i++)\r\n {\r\n if ( var & 1)\r\n temp3 += ( 1 << i);\r\n var = (var >> 1);\r\n }\r\n for ( int i = 0; i < 8; i++)\r\n {\r\n if ( var & 1)\r\n temp4 += ( 1 << i);\r\n var = (var >> 1);\r\n }\r\n Byte a( temp1);\r\n Byte b( temp2);\r\n Byte c( temp3);\r\n Byte d( temp4);\r\n\r\n if ( type == HIGH_FIRST)\r\n {\r\n ( *byte_line).push_back( a);\r\n ( *byte_line).push_back( b);\r\n ( *byte_line).push_back( c);\r\n ( *byte_line).push_back( d);\r\n } else\r\n {\r\n ( *byte_line).push_back( d);\r\n ( *byte_line).push_back( c);\r\n ( *byte_line).push_back( b);\r\n ( *byte_line).push_back( a);\r\n }\r\n*\/\r\n hostUInt8 temp[4] = { 0, 0, 0, 0};\r\n for ( int i = 0; i < 4; i++)\r\n {\r\n for( int k = 0; k < 8; k++)\r\n {\r\n if ( var & 1)\r\n temp[ i] += ( 1 << k);\r\n var = ( var >> 1);\r\n }\r\n }\r\n Byte byte[] = { temp[ 0], temp[ 1], temp[ 2], temp[ 3]};\r\n if ( type == HIGH_FIRST)\r\n {\r\n for ( int i = 0; i < 4; i++)\r\n ( *byte_line).push_back( byte[ i]);\r\n } else\r\n {\r\n for ( int i = 4; i > 0; i--)\r\n ( *byte_line).push_back( byte[ i-1]);\r\n }\r\n}\r\n\r\n \/* Conversion constructors hostUInt8, hostUInt16 and hostUInt32 in Byteline *\/\r\nByteLine::ByteLine( hostUInt8 var, OrderType type)\r\n{\r\n output = DEFAULT_OUT;\r\n try\r\n {\r\n byte_line = new vector<Byte>;\r\n convert8( byte_line, var);\r\n }catch ( std::bad_alloc)\r\n {\r\n cout << \"ERROR: Can not allocate memory!\\n\";\r\n assert( 0);\r\n }\r\n}\r\n\r\nByteLine::ByteLine( hostUInt16 var, OrderType type)\r\n{\r\n output = DEFAULT_OUT;\r\n try\r\n {\r\n byte_line = new vector<Byte>;\r\n convert16( byte_line, var, type);\r\n }catch ( std::bad_alloc)\r\n {\r\n cout << \"ERROR: Can not allocate memory!\\n\";\r\n assert( 0);\r\n }\r\n}\r\nByteLine::ByteLine( hostUInt32 var, OrderType type)\r\n{\r\n output = DEFAULT_OUT;\r\n try\r\n {\r\n byte_line = new vector<Byte>;\r\n convert32( byte_line, var, type);\r\n }catch ( std::bad_alloc)\r\n {\r\n cout << \"ERROR: Can not allocate memory!\\n\";\r\n assert( 0);\r\n }\r\n}\r\n\r\nByteLine::ByteLine(unsigned int var, ConversionType ctype, OrderType type)\r\n{\r\n output = DEFAULT_OUT;\r\n switch( ctype)\r\n {\r\n case HUINT8:\r\n try\r\n {\r\n byte_line = new vector<Byte>;\r\n convert8( byte_line, var);\r\n }catch ( std::bad_alloc)\r\n {\r\n cout << \"ERROR: Can not allocate memory!\\n\";\r\n assert( 0);\r\n }\r\n break;\r\n case HUINT16:\r\n try\r\n {\r\n byte_line = new vector<Byte>;\r\n convert16( byte_line, var, type);\r\n }catch ( std::bad_alloc)\r\n {\r\n cout << \"ERROR: Can not allocate memory!\\n\";\r\n assert( 0);\r\n }\r\n break;\r\n case HUINT32:\r\n try\r\n {\r\n byte_line = new vector<Byte>;\r\n convert32( byte_line, var, type);\r\n }catch ( std::bad_alloc)\r\n {\r\n cout << \"ERROR: Can not allocate memory!\\n\";\r\n assert( 0);\r\n }\r\n break;\r\n }\r\n}\r\n \r\nhostUInt8 ByteLine::getByteVal( unsigned int byte_num) const\r\n{\r\n if ( byte_num > this->getSizeOfLine())\r\n {\r\n cout << \"ERROR: Size of byte line is less than target byte number!\\n\";\r\n assert( 0);\r\n }\r\n if ( ( *byte_line).empty())\r\n {\r\n cout << \"ERROR: Byte line is empty!\\n\";\r\n assert( 0);\r\n }\r\n return ( *byte_line).at( byte_num).getByteVal();\r\n}\r\n\r\nByte ByteLine::getByte( unsigned int byte_num) const\r\n{\r\n if ( byte_num > this->getSizeOfLine())\r\n {\r\n cout << \"ERROR: Size of byte line is less than target byte number!\\n\";\r\n assert( 0);\r\n }\r\n if ( ( *byte_line).empty())\r\n {\r\n cout << \"ERROR: Byte line is empty!\\n\";\r\n assert( 0);\r\n }\r\n return ( *byte_line).at( byte_num);\r\n}\r\n\r\nvoid ByteLine::setByte( unsigned int byte_num, const Byte& byte)\r\n{\r\n if ( byte_num > this->getSizeOfLine())\r\n {\r\n cout << \"ERROR: Size of byte line is less than target byte number!\\n\";\r\n assert( 0);\r\n }\r\n if ( ( *byte_line).empty())\r\n {\r\n cout << \"ERROR: Byte line is empty!\\n\";\r\n assert( 0);\r\n }\r\n ( *byte_line).at( byte_num) = byte;\r\n}\r\n\r\n\r\nvoid ByteLine::addByte( const Byte& byte)\r\n{\r\n try\r\n {\r\n ( *byte_line).push_back( byte);\r\n }catch ( std::bad_alloc)\r\n {\r\n cout << \"ERROR: Can not allocate memory!\\n\";\r\n assert( 0);\r\n }\r\n}\r\nvoid ByteLine::resizeByteLine( unsigned int count)\r\n{\r\n try\r\n {\r\n ( *byte_line).resize( count);\r\n }catch ( std::bad_alloc)\r\n {\r\n cout << \"ERROR: Can not allocate memory!\\n\";\r\n assert( 0);\r\n }\r\n}\r\n\r\n\r\n\/**\r\n * Implementation of class MemVal\r\n *\/\r\n\r\nvoid MemVal::recountLenght()\r\n{\r\n unsigned int temp = getSizeOfMemVal() % size_of_segmentation;\r\n if ( temp != 0 && size_of_segmentation != 1)\r\n {\r\n temp = size_of_segmentation - temp;\r\n temp += getSizeOfMemVal();\r\n resizeByteLine( temp);\r\n }\r\n}\r\n\r\nByteLine MemVal::getByteLine( unsigned int index, unsigned int count) const\r\n{\r\n if ( getSizeOfMemVal() < index + count)\r\n {\r\n cout << \"ERROR: Size of MemVal is less than target byte number!\\n\";\r\n assert( 0);\r\n }\r\n ByteLine temp( count);\r\n for ( unsigned int i = 0; i < count ; i++)\r\n {\r\n temp.setByte( i, getByte( i + index));\r\n }\r\n return temp;\r\n}\r\nByteLine MemVal::getByteLine() const\r\n{\r\n ByteLine temp( getSizeOfMemVal());\r\n for ( unsigned int i = 0; i < getSizeOfMemVal(); i++)\r\n {\r\n temp.setByte( i, getByte( i));\r\n }\r\n return temp;\r\n}\r\n\r\nvoid MemVal::writeByteLine( const ByteLine& line, unsigned int index)\r\n{\r\n if ( getSizeOfMemVal() < index + line.getSizeOfLine())\r\n {\r\n cout << \"ERROR: Size of MemVal is less than target byte number!\\n\";\r\n assert( 0);\r\n }\r\n for ( unsigned int i = 0; i < line.getSizeOfLine(); i++)\r\n {\r\n setByte( i + index, line.getByte( i));\r\n }\r\n}\r\nvoid MemVal::writeByteLine( const ByteLine & line)\r\n{\r\n if ( getSizeOfMemVal() < line.getSizeOfLine())\r\n {\r\n cout << \"ERROR: Size of MemVal is less than target byte number!\\n\";\r\n assert( 0);\r\n }\r\n for ( unsigned int i = 0; i < line.getSizeOfLine(); i++)\r\n {\r\n setByte( i, line.getByte( i));\r\n }\r\n}\r\n\r\n\r\n\r\n\r\n\/**\r\n * Implementation of Memory Model\r\n *\/\r\n\r\nMemoryModel::MemoryModel( unsigned int size)\r\n{\r\n\tmem_model = new memMap;\r\n\tsize_of_segmentation = size;\r\n\r\n}\r\n\r\n\r\nByteLine MemoryModel::read( mathAddr read_ptr, unsigned int num_of_bytes)\r\n{\r\n\tif ( ( *mem_model).empty())\r\n\t{\r\n\t\tcout << \"ERROR!\\n\";\r\n assert( 0);\r\n\t}\r\n\r\n\tmemMap::iterator pos, start, end;\r\n\tstart = find( read_ptr);\r\n\tmathAddr temp_addr = start->first;\r\n\tend = find( read_ptr + num_of_bytes - 1);\r\n\tif ( start == ( *mem_model).end() || end == ( *mem_model).end())\r\n\t{\r\n\t\tcout << \"ERROR!\\n\";\r\n assert( 0);\r\n\t}\r\n\tMemVal memval = start->second;\r\n\tfor ( pos = start; pos != end; ++pos)\r\n\t{\r\n\t\tif ( countDistance( pos) > 0)\r\n\t\t{\r\n\t\t\tcout << \"ERROR!\\n\";\r\n\t\t\tassert( 0);\r\n\t\t}\r\n\t\tmergeMemVal( pos, &memval);\r\n\r\n\t}\r\n\t( *mem_model).erase( start, end);\r\n\t( *mem_model).erase( end);\r\n\t( *mem_model)[ temp_addr] = memval;\r\n\treturn memval.getByteLine( read_ptr - temp_addr, num_of_bytes);\r\n\r\n\r\n}\r\n\r\n\r\n\r\nvoid MemoryModel::mergeMemVal( memMap::iterator pos, MemVal *mem_val)\r\n{\r\n\tif ( countDistance( pos) > 0)\r\n\t{\r\n\t\t\tmem_val->resizeMemVal( ( pos + 1)->first - pos->first);\r\n\t}\r\n\t\t( *mem_val) = ( *mem_val) + ( pos + 1)->second;\r\n}\r\n\r\n\r\n\r\nvoid MemoryModel::write( mathAddr write_ptr, const ByteLine& line)\r\n{\r\n\tmemMap::iterator pos, start, end ;\r\n\tstart = findOrInit( write_ptr);\r\n\tmathAddr temp_addr = start->first;\r\n\tend = findOrInit( write_ptr + line.getSizeOfLine() - 1);\r\n\r\n\tMemVal memval = start->second;\r\n\tfor ( pos = start; pos != end; ++pos)\r\n\t{\r\n\t\tmergeMemVal( pos, &memval);\r\n\r\n\t}\r\n\t( *mem_model).erase( start, end);\r\n\t( *mem_model).erase( end);\r\n\r\n\tmemval.writeByteLine( line, write_ptr - temp_addr);\r\n\t( *mem_model)[ temp_addr] = memval;\r\n}\r\n\r\n\r\nmemMap::iterator MemoryModel::findOrInit( mathAddr ptr)\r\n{\r\n\tmemMap::iterator pos;\r\n\tMemVal temp( size_of_segmentation);\r\n\tmathAddr addr = ptr - ( ptr % size_of_segmentation);\r\n\r\n\tfor ( pos = ( *mem_model).begin(); pos != ( *mem_model).end(); ++pos)\r\n\t{\r\n\t\tif ( pos == ptr)\r\n\t\t{\r\n\t\t\treturn pos;\r\n\t\t}\r\n\t\tif ( ( pos->first) > ptr)\r\n\t\t{\r\n\t\t\t( *mem_model)[ addr] = temp;\r\n\t\t\tpos = ( *mem_model).find( addr);\r\n\t\t\treturn pos;\r\n\r\n\t\t}\r\n\t}\r\n\t( *mem_model)[ addr] = temp;\r\n\tpos = ( *mem_model).find( addr);\r\n\treturn pos;\r\n\r\n}\r\n\r\n\r\nmemMap::iterator MemoryModel::find( mathAddr ptr)\r\n{\r\n\tmemMap::iterator pos;\r\n\tmathAddr adrr;\r\n\tadrr = ptr - ( ptr % size_of_segmentation);\r\n\tfor ( pos = ( *mem_model).begin(); pos != ( *mem_model).end(); ++pos)\r\n\t{\r\n\t\tif ( pos == ptr)\r\n\t\t{\r\n\t\t\treturn pos;\r\n\t\t}\r\n\t}\r\n\treturn pos = ( *mem_model).end();\r\n}\r\n\r\nunsigned int MemoryModel::countDistance( const memMap::iterator pos)\r\n{\r\n\treturn ( pos + 1)->first - ( pos->first + ( pos->second).getSizeOfMemVal());\r\n}\r\n<commit_msg>Deleting unnecessary comments in my folder<commit_after>\/**\r\n * memory.cpp - Implementation of memory model\r\n * Define classes and method to operate with memory of simulated architecture\r\n * Copyright 2009 MDSP team\r\n *\/\r\n\r\n\r\n#include <iostream>\r\n#include <cassert>\r\n#include <math.h>\r\n#ifndef MEMORY_HEADER\r\n#define MEMORY_HEADER\r\n#include \"memory.h\"\r\n#endif \/* MEMORY_HEADER*\/\r\n\r\n\/**\r\n * Implementation of class ByteLine\r\n *\/\r\nByteLine::ByteLine()\r\n{\r\n byte_line = new vector<Byte>;\r\n output = DEFAULT_OUT;\r\n}\r\n\r\nByteLine::ByteLine( unsigned int count)\r\n{\r\n byte_line = new vector<Byte>;\r\n output = DEFAULT_OUT;\r\n try\r\n {\r\n (*byte_line).resize( count);\r\n }catch ( std::bad_alloc)\r\n {\r\n cout << \"ERROR: Can not allocate memory!\\n\";\r\n assert( 0);\r\n }\r\n}\r\n\r\nByteLine::ByteLine( const ByteLine& line)\r\n{\r\n output = DEFAULT_OUT;\r\n try\r\n {\r\n byte_line = new vector<Byte>( line.getSizeOfLine());\r\n }catch ( std::bad_alloc)\r\n {\r\n cout << \"ERROR: Can not allocate memory!\\n\";\r\n assert( 0);\r\n }\r\n for ( unsigned int i = 0 ; i < line.getSizeOfLine(); i++)\r\n {\r\n ( *byte_line).at( i).setByteVal( line.getByteVal( i));\r\n }\r\n}\r\nByteLine::ByteLine( const Byte& byte)\r\n{\r\n output = DEFAULT_OUT;\r\n try\r\n {\r\n byte_line = new vector<Byte>;\r\n ( *byte_line).push_back( byte);\r\n }catch ( std::bad_alloc)\r\n {\r\n cout << \"ERROR: Can not allocate memory!\\n\";\r\n assert( 0);\r\n }\r\n}\r\n\r\n \/* Conversion functions ByteLine into hostUInt8, hostUInt16, hostUInt32 *\/\r\nhostUInt8 ByteLine::getHostUInt8()\r\n{\r\n return this->getByteVal( 0);\r\n}\r\n\r\nhostUInt16 ByteLine::getHostUInt16()\r\n{\r\n hostUInt8 temp[] = { this->getByteVal( 1), this->getByteVal( 0)};\r\n hostUInt16 var = 0;\r\n var += temp[ 0];\r\n var = ( var << 8);\r\n var += temp[ 1];\r\n return var;\r\n}\r\n\r\nhostUInt32 ByteLine::getHostUInt32()\r\n{\r\n hostUInt8 temp[] = { this->getByteVal( 3), this->getByteVal( 2), \r\n this->getByteVal( 1), this->getByteVal( 0)};\r\n hostUInt32 var = 0;\r\n for ( int i = 0; i < 3; i++)\r\n {\r\n var += temp[ i];\r\n var = ( var << 8);\r\n }\r\n var += temp[3];\r\n return var;\r\n}\r\n\r\n \/* Private functions converting hostUInt8,16,32 into vector<Byte> *byte_line *\/\r\nvoid ByteLine::convert8( vector<Byte> *byte_line, hostUInt8 var)\r\n{\r\n Byte byte( var);\r\n ( *byte_line).push_back( byte);\r\n}\r\n\r\nvoid ByteLine::convert16( vector<Byte> *byte_line, hostUInt16 var, OrderType type)\r\n{\r\n hostUInt8 temp[2] = { 0, 0};\r\n for ( int i = 0; i < 2; i++)\r\n {\r\n for( int k = 0; k < 8; k++)\r\n {\r\n if ( var & 1)\r\n temp[ i] += ( 1 << k);\r\n var = ( var >> 1);\r\n }\r\n }\r\n Byte byte[] = { temp[ 0], temp[ 1]};\r\n if ( type == HIGH_FIRST)\r\n {\r\n for ( int i = 0; i < 2; i++)\r\n ( *byte_line).push_back( byte[ i]);\r\n } else\r\n {\r\n for ( int i = 2; i > 0; i--)\r\n ( *byte_line).push_back( byte[ i-1]);\r\n }\r\n}\r\n\r\nvoid ByteLine::convert32( vector<Byte> *byte_line, hostUInt32 var, OrderType type)\r\n{\r\n hostUInt8 temp[4] = { 0, 0, 0, 0};\r\n for ( int i = 0; i < 4; i++)\r\n {\r\n for( int k = 0; k < 8; k++)\r\n {\r\n if ( var & 1)\r\n temp[ i] += ( 1 << k);\r\n var = ( var >> 1);\r\n }\r\n }\r\n Byte byte[] = { temp[ 0], temp[ 1], temp[ 2], temp[ 3]};\r\n if ( type == HIGH_FIRST)\r\n {\r\n for ( int i = 0; i < 4; i++)\r\n ( *byte_line).push_back( byte[ i]);\r\n } else\r\n {\r\n for ( int i = 4; i > 0; i--)\r\n ( *byte_line).push_back( byte[ i-1]);\r\n }\r\n}\r\n\r\n \/* Conversion constructors hostUInt8, hostUInt16 and hostUInt32 in Byteline *\/\r\nByteLine::ByteLine( hostUInt8 var, OrderType type)\r\n{\r\n output = DEFAULT_OUT;\r\n try\r\n {\r\n byte_line = new vector<Byte>;\r\n convert8( byte_line, var);\r\n }catch ( std::bad_alloc)\r\n {\r\n cout << \"ERROR: Can not allocate memory!\\n\";\r\n assert( 0);\r\n }\r\n}\r\n\r\nByteLine::ByteLine( hostUInt16 var, OrderType type)\r\n{\r\n output = DEFAULT_OUT;\r\n try\r\n {\r\n byte_line = new vector<Byte>;\r\n convert16( byte_line, var, type);\r\n }catch ( std::bad_alloc)\r\n {\r\n cout << \"ERROR: Can not allocate memory!\\n\";\r\n assert( 0);\r\n }\r\n}\r\nByteLine::ByteLine( hostUInt32 var, OrderType type)\r\n{\r\n output = DEFAULT_OUT;\r\n try\r\n {\r\n byte_line = new vector<Byte>;\r\n convert32( byte_line, var, type);\r\n }catch ( std::bad_alloc)\r\n {\r\n cout << \"ERROR: Can not allocate memory!\\n\";\r\n assert( 0);\r\n }\r\n}\r\n\r\nByteLine::ByteLine(unsigned int var, ConversionType ctype, OrderType type)\r\n{\r\n output = DEFAULT_OUT;\r\n switch( ctype)\r\n {\r\n case HUINT8:\r\n try\r\n {\r\n byte_line = new vector<Byte>;\r\n convert8( byte_line, var);\r\n }catch ( std::bad_alloc)\r\n {\r\n cout << \"ERROR: Can not allocate memory!\\n\";\r\n assert( 0);\r\n }\r\n break;\r\n case HUINT16:\r\n try\r\n {\r\n byte_line = new vector<Byte>;\r\n convert16( byte_line, var, type);\r\n }catch ( std::bad_alloc)\r\n {\r\n cout << \"ERROR: Can not allocate memory!\\n\";\r\n assert( 0);\r\n }\r\n break;\r\n case HUINT32:\r\n try\r\n {\r\n byte_line = new vector<Byte>;\r\n convert32( byte_line, var, type);\r\n }catch ( std::bad_alloc)\r\n {\r\n cout << \"ERROR: Can not allocate memory!\\n\";\r\n assert( 0);\r\n }\r\n break;\r\n }\r\n}\r\n \r\nhostUInt8 ByteLine::getByteVal( unsigned int byte_num) const\r\n{\r\n if ( byte_num > this->getSizeOfLine())\r\n {\r\n cout << \"ERROR: Size of byte line is less than target byte number!\\n\";\r\n assert( 0);\r\n }\r\n if ( ( *byte_line).empty())\r\n {\r\n cout << \"ERROR: Byte line is empty!\\n\";\r\n assert( 0);\r\n }\r\n return ( *byte_line).at( byte_num).getByteVal();\r\n}\r\n\r\nByte ByteLine::getByte( unsigned int byte_num) const\r\n{\r\n if ( byte_num > this->getSizeOfLine())\r\n {\r\n cout << \"ERROR: Size of byte line is less than target byte number!\\n\";\r\n assert( 0);\r\n }\r\n if ( ( *byte_line).empty())\r\n {\r\n cout << \"ERROR: Byte line is empty!\\n\";\r\n assert( 0);\r\n }\r\n return ( *byte_line).at( byte_num);\r\n}\r\n\r\nvoid ByteLine::setByte( unsigned int byte_num, const Byte& byte)\r\n{\r\n if ( byte_num > this->getSizeOfLine())\r\n {\r\n cout << \"ERROR: Size of byte line is less than target byte number!\\n\";\r\n assert( 0);\r\n }\r\n if ( ( *byte_line).empty())\r\n {\r\n cout << \"ERROR: Byte line is empty!\\n\";\r\n assert( 0);\r\n }\r\n ( *byte_line).at( byte_num) = byte;\r\n}\r\n\r\n\r\nvoid ByteLine::addByte( const Byte& byte)\r\n{\r\n try\r\n {\r\n ( *byte_line).push_back( byte);\r\n }catch ( std::bad_alloc)\r\n {\r\n cout << \"ERROR: Can not allocate memory!\\n\";\r\n assert( 0);\r\n }\r\n}\r\nvoid ByteLine::resizeByteLine( unsigned int count)\r\n{\r\n try\r\n {\r\n ( *byte_line).resize( count);\r\n }catch ( std::bad_alloc)\r\n {\r\n cout << \"ERROR: Can not allocate memory!\\n\";\r\n assert( 0);\r\n }\r\n}\r\n\r\n\r\n\/**\r\n * Implementation of class MemVal\r\n *\/\r\n\r\nvoid MemVal::recountLenght()\r\n{\r\n unsigned int temp = getSizeOfMemVal() % size_of_segmentation;\r\n if ( temp != 0 && size_of_segmentation != 1)\r\n {\r\n temp = size_of_segmentation - temp;\r\n temp += getSizeOfMemVal();\r\n resizeByteLine( temp);\r\n }\r\n}\r\n\r\nByteLine MemVal::getByteLine( unsigned int index, unsigned int count) const\r\n{\r\n if ( getSizeOfMemVal() < index + count)\r\n {\r\n cout << \"ERROR: Size of MemVal is less than target byte number!\\n\";\r\n assert( 0);\r\n }\r\n ByteLine temp( count);\r\n for ( unsigned int i = 0; i < count ; i++)\r\n {\r\n temp.setByte( i, getByte( i + index));\r\n }\r\n return temp;\r\n}\r\nByteLine MemVal::getByteLine() const\r\n{\r\n ByteLine temp( getSizeOfMemVal());\r\n for ( unsigned int i = 0; i < getSizeOfMemVal(); i++)\r\n {\r\n temp.setByte( i, getByte( i));\r\n }\r\n return temp;\r\n}\r\n\r\nvoid MemVal::writeByteLine( const ByteLine& line, unsigned int index)\r\n{\r\n if ( getSizeOfMemVal() < index + line.getSizeOfLine())\r\n {\r\n cout << \"ERROR: Size of MemVal is less than target byte number!\\n\";\r\n assert( 0);\r\n }\r\n for ( unsigned int i = 0; i < line.getSizeOfLine(); i++)\r\n {\r\n setByte( i + index, line.getByte( i));\r\n }\r\n}\r\nvoid MemVal::writeByteLine( const ByteLine & line)\r\n{\r\n if ( getSizeOfMemVal() < line.getSizeOfLine())\r\n {\r\n cout << \"ERROR: Size of MemVal is less than target byte number!\\n\";\r\n assert( 0);\r\n }\r\n for ( unsigned int i = 0; i < line.getSizeOfLine(); i++)\r\n {\r\n setByte( i, line.getByte( i));\r\n }\r\n}\r\n\r\n\r\n\r\n\r\n\/**\r\n * Implementation of Memory Model\r\n *\/\r\n\r\nMemoryModel::MemoryModel( unsigned int size)\r\n{\r\n\tmem_model = new memMap;\r\n\tsize_of_segmentation = size;\r\n\r\n}\r\n\r\n\r\nByteLine MemoryModel::read( mathAddr read_ptr, unsigned int num_of_bytes)\r\n{\r\n\tif ( ( *mem_model).empty())\r\n\t{\r\n\t\tcout << \"ERROR!\\n\";\r\n assert( 0);\r\n\t}\r\n\r\n\tmemMap::iterator pos, start, end;\r\n\tstart = find( read_ptr);\r\n\tmathAddr temp_addr = start->first;\r\n\tend = find( read_ptr + num_of_bytes - 1);\r\n\tif ( start == ( *mem_model).end() || end == ( *mem_model).end())\r\n\t{\r\n\t\tcout << \"ERROR!\\n\";\r\n assert( 0);\r\n\t}\r\n\tMemVal memval = start->second;\r\n\tfor ( pos = start; pos != end; ++pos)\r\n\t{\r\n\t\tif ( countDistance( pos) > 0)\r\n\t\t{\r\n\t\t\tcout << \"ERROR!\\n\";\r\n\t\t\tassert( 0);\r\n\t\t}\r\n\t\tmergeMemVal( pos, &memval);\r\n\r\n\t}\r\n\t( *mem_model).erase( start, end);\r\n\t( *mem_model).erase( end);\r\n\t( *mem_model)[ temp_addr] = memval;\r\n\treturn memval.getByteLine( read_ptr - temp_addr, num_of_bytes);\r\n\r\n\r\n}\r\n\r\n\r\n\r\nvoid MemoryModel::mergeMemVal( memMap::iterator pos, MemVal *mem_val)\r\n{\r\n\tif ( countDistance( pos) > 0)\r\n\t{\r\n\t\t\tmem_val->resizeMemVal( ( pos + 1)->first - pos->first);\r\n\t}\r\n\t\t( *mem_val) = ( *mem_val) + ( pos + 1)->second;\r\n}\r\n\r\n\r\n\r\nvoid MemoryModel::write( mathAddr write_ptr, const ByteLine& line)\r\n{\r\n\tmemMap::iterator pos, start, end ;\r\n\tstart = findOrInit( write_ptr);\r\n\tmathAddr temp_addr = start->first;\r\n\tend = findOrInit( write_ptr + line.getSizeOfLine() - 1);\r\n\r\n\tMemVal memval = start->second;\r\n\tfor ( pos = start; pos != end; ++pos)\r\n\t{\r\n\t\tmergeMemVal( pos, &memval);\r\n\r\n\t}\r\n\t( *mem_model).erase( start, end);\r\n\t( *mem_model).erase( end);\r\n\r\n\tmemval.writeByteLine( line, write_ptr - temp_addr);\r\n\t( *mem_model)[ temp_addr] = memval;\r\n}\r\n\r\n\r\nmemMap::iterator MemoryModel::findOrInit( mathAddr ptr)\r\n{\r\n\tmemMap::iterator pos;\r\n\tMemVal temp( size_of_segmentation);\r\n\tmathAddr addr = ptr - ( ptr % size_of_segmentation);\r\n\r\n\tfor ( pos = ( *mem_model).begin(); pos != ( *mem_model).end(); ++pos)\r\n\t{\r\n\t\tif ( pos == ptr)\r\n\t\t{\r\n\t\t\treturn pos;\r\n\t\t}\r\n\t\tif ( ( pos->first) > ptr)\r\n\t\t{\r\n\t\t\t( *mem_model)[ addr] = temp;\r\n\t\t\tpos = ( *mem_model).find( addr);\r\n\t\t\treturn pos;\r\n\r\n\t\t}\r\n\t}\r\n\t( *mem_model)[ addr] = temp;\r\n\tpos = ( *mem_model).find( addr);\r\n\treturn pos;\r\n\r\n}\r\n\r\n\r\nmemMap::iterator MemoryModel::find( mathAddr ptr)\r\n{\r\n\tmemMap::iterator pos;\r\n\tmathAddr adrr;\r\n\tadrr = ptr - ( ptr % size_of_segmentation);\r\n\tfor ( pos = ( *mem_model).begin(); pos != ( *mem_model).end(); ++pos)\r\n\t{\r\n\t\tif ( pos == ptr)\r\n\t\t{\r\n\t\t\treturn pos;\r\n\t\t}\r\n\t}\r\n\treturn pos = ( *mem_model).end();\r\n}\r\n\r\nunsigned int MemoryModel::countDistance( const memMap::iterator pos)\r\n{\r\n\treturn ( pos + 1)->first - ( pos->first + ( pos->second).getSizeOfMemVal());\r\n}\r\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2016 Yahoo Inc.\n\/\/ Licensed under the terms of the New-BSD license. Please see LICENSE file in the project root for terms.\n#include <jni.h>\n#include <arpa\/inet.h>\n#include \"addr_support.h\"\n#include \"com_yahoo_wildwest_PowersawValidator.h\"\n\n#define EXPECTED_IPV4 \"192.168.1.111\"\n#define EXPECTED_IPV6 \"2001:4998:0:1::1007\"\n\nint checkAddress(const char *expected, int ai_family,\n const ipv6_sockaddr *addr) {\n if (NULL == expected && NULL == addr) {\n return 0;\n }\n\n if (NULL == expected) {\n return -1;\n }\n\n if (NULL == addr) {\n return -2;\n }\n\n const void *addr_s = NULL;\n \/* get the IP address as string passed to this function *\/\n char ipstr[INET6_ADDRSTRLEN] = { 0, };\n if (ai_family == AF_INET) {\n \/* IPv4 *\/\n const struct sockaddr_in *ipv4 = &(addr->sin);\n addr_s = (const void*) &(ipv4->sin_addr);\n } else {\n \/* IPv6 *\/\n const struct sockaddr_in6 *ipv6 = &(addr->sin6);\n addr_s = (const void*) &(ipv6->sin6_addr);\n }\n\n if (NULL == inet_ntop(ai_family, addr_s, ipstr, sizeof(ipstr))) {\n return -3;\n }\n\n fprintf(stderr, \"comparing %s to %s\\n\", expected, ipstr);\n return strcmp(expected, ipstr);\n}\n\nint checkAddress(const char *expected, const struct addrinfo *addr) {\n if (NULL == expected && NULL == addr) {\n return 0;\n }\n\n if (NULL == expected) {\n return -1;\n }\n\n if (NULL == addr) {\n return -2;\n }\n\n return checkAddress(expected, addr->ai_family,\n (const ipv6_sockaddr*) addr->ai_addr);\n}\n\n\/*\n * Class: com_yahoo_wildwest_PowersawValidator\n * Method: validateIpv4\n * Signature: (JJ)I\n *\/\nJNIEXPORT jint JNICALL Java_com_yahoo_wildwest_PowersawValidator_validateIpv4(\n JNIEnv *, jclass, jlong address, jlong length) {\n fprintf(stderr, \"calling validateIpv6\\n\");\n\n ipv6_sockaddr v6sa;\n memset(&v6sa, 0, sizeof(ipv6_sockaddr));\n unsafeToSockAddr(v6sa, address, length);\n return checkAddress(EXPECTED_IPV4, AF_INET, &v6sa);\n}\n\n\/*\n * Class: com_yahoo_wildwest_PowersawValidator\n * Method: validateIpv6\n * Signature: (JJ)I\n *\/\nJNIEXPORT jint JNICALL Java_com_yahoo_wildwest_PowersawValidator_validateIpv6(\n JNIEnv *, jclass, jlong address, jlong length) {\n fprintf(stderr, \"calling validateIpv6\\n\");\n\n ipv6_sockaddr v6sa;\n memset(&v6sa, 0, sizeof(ipv6_sockaddr));\n unsafeToSockAddr(v6sa, address, length);\n return checkAddress(EXPECTED_IPV6, AF_INET6, &v6sa);\n}\n\n\/*\n * Class: com_yahoo_wildwest_PowersawValidator\n * Method: validateAddresses\n * Signature: (JJ)I\n *\/\nJNIEXPORT jint JNICALL Java_com_yahoo_wildwest_PowersawValidator_validateAddresses(\n JNIEnv *, jclass, jlong addresses, jlong length) {\n\n fprintf(stderr, \"calling validateAddresses\\n\");\n\n ScopedAddrInfo aiScope;\n if (!allocAddrInfo(aiScope, addresses, length)) {\n return -2;\n }\n\n int ret;\n\n \/\/ check the first address\n ret = checkAddress(EXPECTED_IPV4, aiScope.get()->ai_family,\n (const ipv6_sockaddr*) aiScope.get()->ai_addr);\n\n if (0 != ret) {\n return ret;\n }\n\n \/\/ should not be lazy and loop all of them.\n \/\/ that would be way better testing.\n if (NULL != aiScope.get()->ai_next) {\n addrinfo *next = aiScope.get()->ai_next;\n ret = checkAddress(EXPECTED_IPV6, next->ai_family,\n (const ipv6_sockaddr*) next->ai_addr);\n\n if (0 != ret) {\n return ret;\n }\n }\n\n return 0;\n}\n<commit_msg>Add more prints for when things go south<commit_after>\/\/ Copyright 2016 Yahoo Inc.\n\/\/ Licensed under the terms of the New-BSD license. Please see LICENSE file in the project root for terms.\n#include <jni.h>\n#include <arpa\/inet.h>\n#include \"addr_support.h\"\n#include \"com_yahoo_wildwest_PowersawValidator.h\"\n\n#define EXPECTED_IPV4 \"192.168.1.111\"\n#define EXPECTED_IPV6 \"2001:4998:0:1::1007\"\n\nint checkAddress(const char *expected, int ai_family,\n const ipv6_sockaddr *addr, const char*forwho) {\n if (NULL == expected && NULL == addr) {\n return 0;\n }\n\n if (NULL == expected) {\n return -1;\n }\n\n if (NULL == addr) {\n return -2;\n }\n\n const void *addr_s = NULL;\n \/* get the IP address as string passed to this function *\/\n char ipstr[INET6_ADDRSTRLEN] = { 0, };\n if (ai_family == AF_INET) {\n \/* IPv4 *\/\n const struct sockaddr_in *ipv4 = &(addr->sin);\n addr_s = (const void*) &(ipv4->sin_addr);\n } else {\n \/* IPv6 *\/\n const struct sockaddr_in6 *ipv6 = &(addr->sin6);\n addr_s = (const void*) &(ipv6->sin6_addr);\n }\n\n if (NULL == inet_ntop(ai_family, addr_s, ipstr, sizeof(ipstr))) {\n return -3;\n }\n\n fprintf(stderr, \"comparing %s to %s for %s\\n\", expected, ipstr, forwho);\n return strcmp(expected, ipstr);\n}\n\nint checkAddress(const char *expected, const struct addrinfo *addr, const char *forwho) {\n if (NULL == expected && NULL == addr) {\n return 0;\n }\n\n if (NULL == expected) {\n return -1;\n }\n\n if (NULL == addr) {\n return -2;\n }\n\n return checkAddress(expected, addr->ai_family,\n (const ipv6_sockaddr*) addr->ai_addr, forwho);\n}\n\n\/*\n * Class: com_yahoo_wildwest_PowersawValidator\n * Method: validateIpv4\n * Signature: (JJ)I\n *\/\nJNIEXPORT jint JNICALL Java_com_yahoo_wildwest_PowersawValidator_validateIpv4(\n JNIEnv *, jclass, jlong address, jlong length) {\n fprintf(stderr, \"calling validateIpv6\\n\");\n\n ipv6_sockaddr v6sa;\n memset(&v6sa, 0, sizeof(ipv6_sockaddr));\n unsafeToSockAddr(v6sa, address, length);\n return checkAddress(EXPECTED_IPV4, AF_INET, &v6sa,\"validateIpv4\");\n}\n\n\/*\n * Class: com_yahoo_wildwest_PowersawValidator\n * Method: validateIpv6\n * Signature: (JJ)I\n *\/\nJNIEXPORT jint JNICALL Java_com_yahoo_wildwest_PowersawValidator_validateIpv6(\n JNIEnv *, jclass, jlong address, jlong length) {\n fprintf(stderr, \"calling validateIpv6\\n\");\n\n ipv6_sockaddr v6sa;\n memset(&v6sa, 0, sizeof(ipv6_sockaddr));\n unsafeToSockAddr(v6sa, address, length);\n return checkAddress(EXPECTED_IPV6, AF_INET6, &v6sa,\"validateIpv6\");\n}\n\n\/*\n * Class: com_yahoo_wildwest_PowersawValidator\n * Method: validateAddresses\n * Signature: (JJ)I\n *\/\nJNIEXPORT jint JNICALL Java_com_yahoo_wildwest_PowersawValidator_validateAddresses(\n JNIEnv *, jclass, jlong addresses, jlong length) {\n\n fprintf(stderr, \"calling validateAddresses\\n\");\n\n ScopedAddrInfo aiScope;\n if (!allocAddrInfo(aiScope, addresses, length)) {\n return -2;\n }\n\n int ret;\n\n \/\/ check the first address\n ret = checkAddress(EXPECTED_IPV4, aiScope.get()->ai_family,\n (const ipv6_sockaddr*) aiScope.get()->ai_addr,\"validateAddresses:validateIpv4\");\n\n if (0 != ret) {\n return ret;\n }\n\n \/\/ should not be lazy and loop all of them.\n \/\/ that would be way better testing.\n if (NULL != aiScope.get()->ai_next) {\n addrinfo *next = aiScope.get()->ai_next;\n ret = checkAddress(EXPECTED_IPV6, next->ai_family,\n (const ipv6_sockaddr*) next->ai_addr,\"validateAddresses:validateIpv6\");\n\n if (0 != ret) {\n return ret;\n }\n }\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>#ifndef DUNE_STUFF_FUNCTION_CONSTANT_HH\n#define DUNE_STUFF_FUNCTION_CONSTANT_HH\n\n#include <dune\/stuff\/common\/parameter\/tree.hh>\n\n#include \"interface.hh\"\n\nnamespace Dune {\nnamespace Stuff {\n\n\ntemplate< class DomainFieldImp, int domainDim, class RangeFieldImp, int rangeDimCols, int rangeDimRows >\nclass FunctionConstantBase\n : public FunctionInterface< DomainFieldImp, domainDim, RangeFieldImp, rangeDimCols, rangeDimRows >\n , public TimedependentFunctionInterface< DomainFieldImp, domainDim, RangeFieldImp, rangeDimCols, rangeDimRows >\n{\n typedef FunctionInterface< DomainFieldImp, domainDim, RangeFieldImp, rangeDimCols, rangeDimRows > BaseType;\npublic:\n typedef typename BaseType::DomainFieldType DomainFieldType;\n static const unsigned int dimDomain = BaseType::dimDomain;\n typedef typename BaseType::DomainType DomainType;\n typedef typename BaseType::RangeFieldType RangeFieldType;\n static const unsigned int dimRangeCols = BaseType::dimRangeCols;\n static const unsigned int dimRangeRows = BaseType::dimRangeRows;\n typedef typename BaseType::RangeType RangeType;\n\n FunctionConstantBase(const RangeFieldType& constant)\n : constant_(constant)\n {}\n\n FunctionConstantBase(const RangeType& constant)\n : constant_(constant)\n {}\n\n static const std::string id()\n {\n return BaseType::id() + \".constant\";\n }\n\n virtual int order() const\n {\n return 0;\n }\n\n virtual std::string name() const\n {\n return \"function.constant\";\n }\n\n virtual void evaluate(const DomainType& \/*arg*\/, RangeType& ret) const\n {\n ret = constant_;\n }\n\n virtual void evaluate(const DomainType& \/*arg*\/, const double& \/*t*\/, RangeType& ret) const\n {\n ret = constant_;\n }\n\nprivate:\n const RangeType constant_;\n}; \/\/ class FunctionConstantBase\n\n\n\/\/ forward, to allow for specialization\ntemplate< class DomainFieldImp, int domainDim, class RangeFieldImp, int rangeDimCols, int rangeDimRows = 1 >\nclass FunctionConstant\n{\npublic:\n FunctionConstant() = delete;\n}; \/\/ class FunctionConstant\n\n\ntemplate< class DomainFieldImp, int domainDim, class RangeFieldImp >\nclass FunctionConstant< DomainFieldImp, domainDim, RangeFieldImp, 1, 1 >\n : public FunctionConstantBase< DomainFieldImp, domainDim, RangeFieldImp, 1, 1 >\n{\n typedef FunctionConstantBase< DomainFieldImp, domainDim, RangeFieldImp, 1, 1 > BaseType;\npublic:\n typedef FunctionConstant< DomainFieldImp, domainDim, RangeFieldImp, 1, 1 > ThisType;\n\n typedef typename BaseType::RangeFieldType RangeFieldType;\n typedef typename BaseType::RangeType RangeType;\n\n FunctionConstant(const RangeType& constant)\n : BaseType(constant)\n {}\n\n static Dune::ParameterTree createSampleDescription(const std::string subName = \"\")\n {\n Dune::ParameterTree description;\n description[\"value\"] = \"1.0\";\n if (subName.empty())\n return description;\n else {\n Dune::Stuff::Common::ExtendedParameterTree extendedDescription;\n extendedDescription.add(description, subName);\n return extendedDescription;\n }\n } \/\/ ... createSampleDescription(...)\n\n static ThisType* create(const DSC::ExtendedParameterTree description)\n {\n return new ThisType(description.get< RangeFieldType >(\"value\", RangeFieldType(0)));\n } \/\/ ... create(...)\n}; \/\/ class FunctionConstant< ..., 1 >\n\n\n} \/\/ namespace Stuff\n} \/\/ namespace Dune\n\n#endif \/\/ DUNE_STUFF_FUNCTION_CONSTANT_HH\n<commit_msg>[function.constant] added another constructor<commit_after>#ifndef DUNE_STUFF_FUNCTION_CONSTANT_HH\n#define DUNE_STUFF_FUNCTION_CONSTANT_HH\n\n#include <dune\/stuff\/common\/parameter\/tree.hh>\n\n#include \"interface.hh\"\n\nnamespace Dune {\nnamespace Stuff {\n\n\ntemplate< class DomainFieldImp, int domainDim, class RangeFieldImp, int rangeDimCols, int rangeDimRows >\nclass FunctionConstantBase\n : public FunctionInterface< DomainFieldImp, domainDim, RangeFieldImp, rangeDimCols, rangeDimRows >\n , public TimedependentFunctionInterface< DomainFieldImp, domainDim, RangeFieldImp, rangeDimCols, rangeDimRows >\n{\n typedef FunctionInterface< DomainFieldImp, domainDim, RangeFieldImp, rangeDimCols, rangeDimRows > BaseType;\npublic:\n typedef typename BaseType::DomainFieldType DomainFieldType;\n static const unsigned int dimDomain = BaseType::dimDomain;\n typedef typename BaseType::DomainType DomainType;\n typedef typename BaseType::RangeFieldType RangeFieldType;\n static const unsigned int dimRangeCols = BaseType::dimRangeCols;\n static const unsigned int dimRangeRows = BaseType::dimRangeRows;\n typedef typename BaseType::RangeType RangeType;\n\n FunctionConstantBase(const RangeFieldType& constant)\n : constant_(constant)\n {}\n\n FunctionConstantBase(const RangeType& constant)\n : constant_(constant)\n {}\n\n static const std::string id()\n {\n return BaseType::id() + \".constant\";\n }\n\n virtual int order() const\n {\n return 0;\n }\n\n virtual std::string name() const\n {\n return \"function.constant\";\n }\n\n virtual void evaluate(const DomainType& \/*arg*\/, RangeType& ret) const\n {\n ret = constant_;\n }\n\n virtual void evaluate(const DomainType& \/*arg*\/, const double& \/*t*\/, RangeType& ret) const\n {\n ret = constant_;\n }\n\nprivate:\n const RangeType constant_;\n}; \/\/ class FunctionConstantBase\n\n\n\/\/ forward, to allow for specialization\ntemplate< class DomainFieldImp, int domainDim, class RangeFieldImp, int rangeDimCols, int rangeDimRows = 1 >\nclass FunctionConstant\n{\npublic:\n FunctionConstant() = delete;\n}; \/\/ class FunctionConstant\n\n\ntemplate< class DomainFieldImp, int domainDim, class RangeFieldImp >\nclass FunctionConstant< DomainFieldImp, domainDim, RangeFieldImp, 1, 1 >\n : public FunctionConstantBase< DomainFieldImp, domainDim, RangeFieldImp, 1, 1 >\n{\n typedef FunctionConstantBase< DomainFieldImp, domainDim, RangeFieldImp, 1, 1 > BaseType;\npublic:\n typedef FunctionConstant< DomainFieldImp, domainDim, RangeFieldImp, 1, 1 > ThisType;\n\n typedef typename BaseType::RangeFieldType RangeFieldType;\n typedef typename BaseType::RangeType RangeType;\n\n FunctionConstant(const RangeFieldType& constant)\n : BaseType(constant)\n {}\n\n FunctionConstant(const RangeType& constant)\n : BaseType(constant)\n {}\n\n static Dune::ParameterTree createSampleDescription(const std::string subName = \"\")\n {\n Dune::ParameterTree description;\n description[\"value\"] = \"1.0\";\n if (subName.empty())\n return description;\n else {\n Dune::Stuff::Common::ExtendedParameterTree extendedDescription;\n extendedDescription.add(description, subName);\n return extendedDescription;\n }\n } \/\/ ... createSampleDescription(...)\n\n static ThisType* create(const DSC::ExtendedParameterTree description)\n {\n return new ThisType(description.get< RangeFieldType >(\"value\", RangeFieldType(0)));\n } \/\/ ... create(...)\n}; \/\/ class FunctionConstant< ..., 1 >\n\n\n} \/\/ namespace Stuff\n} \/\/ namespace Dune\n\n#endif \/\/ DUNE_STUFF_FUNCTION_CONSTANT_HH\n<|endoftext|>"} {"text":"<commit_before>\/*---------------------------------------------------------------------------*\\\n * OpenSG *\n * *\n * *\n * Copyright (C) 2000-2006 by the OpenSG Forum *\n * *\n * www.opensg.org *\n * *\n * contact: dirk@opensg.org, gerrit.voss@vossg.org, jbehr@zgdv.de *\n * *\n\\*---------------------------------------------------------------------------*\/\n\/*---------------------------------------------------------------------------*\\\n * License *\n * *\n * This library is free software; you can redistribute it and\/or modify it *\n * under the terms of the GNU Library General Public License as published *\n * by the Free Software Foundation, version 2. *\n * *\n * This library is distributed in the hope that it will be useful, but *\n * WITHOUT ANY WARRANTY; without even the implied warranty of *\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *\n * Library General Public License for more details. *\n * *\n * You should have received a copy of the GNU Library General Public *\n * License along with this library; if not, write to the Free Software *\n * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. *\n * *\n\\*---------------------------------------------------------------------------*\/\n\/*---------------------------------------------------------------------------*\\\n * Changes *\n * *\n * *\n * *\n * *\n * *\n * *\n\\*---------------------------------------------------------------------------*\/\n\n\/\/---------------------------------------------------------------------------\n\/\/ Includes\n\/\/---------------------------------------------------------------------------\n\n#include <cstdlib>\n#include <cstdio>\n\n#include <OSGConfig.h>\n\n#include \"OSGCSMTrackball.h\"\n#include \"OSGWindow.h\"\n\nOSG_BEGIN_NAMESPACE\n\n\/\/ Documentation for this class is emitted in the\n\/\/ OSGCSMTrackballBase.cpp file.\n\/\/ To modify it, please change the .fcd file (OSGCSMTrackball.fcd) and\n\/\/ regenerate the base file.\n\n\/***************************************************************************\\\n * Class variables *\n\\***************************************************************************\/\n\n\/***************************************************************************\\\n * Class methods *\n\\***************************************************************************\/\n\nvoid CSMTrackball::initMethod(InitPhase ePhase)\n{\n Inherited::initMethod(ePhase);\n\n if(ePhase == TypeObject::SystemPost)\n {\n }\n}\n\n\n\/***************************************************************************\\\n * Instance methods *\n\\***************************************************************************\/\n\n\/*-------------------------------------------------------------------------*\\\n - private -\n\\*-------------------------------------------------------------------------*\/\n\n\/*----------------------- constructors & destructors ----------------------*\/\n\nCSMTrackball::CSMTrackball(void) :\n Inherited ( ),\n _oTrackball ( ),\n _iLastX (-1),\n _iLastY (-1),\n _iMouseButtons( 0)\n\n{\n _oTrackball.setStartPosition(0, 0, 10, true);\n _oTrackball.setTranslationScale(1.f);\n\n _oTrackball.setMode (Trackball::OSGObject);\n _oTrackball.setSum (true );\n _oTrackball.setTranslationMode (Trackball::OSGFree );\n}\n\nCSMTrackball::CSMTrackball(const CSMTrackball &source) :\n Inherited (source),\n _oTrackball ( ),\n _iLastX (-1 ),\n _iLastY (-1 ),\n _iMouseButtons( 0 )\n\n{\n _oTrackball.setStartPosition(0, 0, 10, true);\n _oTrackball.setTranslationScale(1.f);\n\n _oTrackball.setMode (Trackball::OSGObject);\n _oTrackball.setSum (true );\n _oTrackball.setTranslationMode (Trackball::OSGFree );\n}\n\nCSMTrackball::~CSMTrackball(void)\n{\n}\n\n\/*----------------------------- class specific ----------------------------*\/\n\nvoid CSMTrackball::changed(ConstFieldMaskArg whichField, \n UInt32 origin,\n BitVector details)\n{\n if(0x0000 != (whichField & MouseDataFieldMask))\n {\n const MouseData &mData = _sfMouseData.getValue();\n\n if((0x0000 != (mData.getModifier() & _sfModifierMask.getValue())) ||\n (_sfProcessing.getValue() == true))\n {\n if(mData.getButton() != -1)\n {\n if(mData.getState() == MouseData::ButtonDown)\n {\n switch(mData.getButton())\n {\n case MouseData::LeftButton : \n break;\n \n case MouseData::MiddleButton :\n _oTrackball.setAutoPosition(true);\n break;\n \n case MouseData::RightButton : \n _oTrackball.setAutoPositionNeg(true);\n break;\n }\n\n _iMouseButtons |= 1 << mData.getButton();\n\n editSFProcessing()->setValue(true);\n }\n else\n {\n switch(mData.getButton())\n {\n case MouseData::LeftButton : \n break;\n \n case MouseData::MiddleButton :\n _oTrackball.setAutoPosition(false);\n break;\n \n case MouseData::RightButton : \n _oTrackball.setAutoPositionNeg(false);\n break;\n } \n \n _iMouseButtons &= ~(1 << mData.getButton());\n\n editSFProcessing()->setValue(false);\n }\n }\n else\n {\n if(_sfProcessing.getValue() == true)\n {\n Real32 a,b,c,d;\n\n if(mData.getMode() == MouseData::RelValues)\n {\n a = 0.f;\n b = 0.f;\n\n c = mData.getX();\n d = mData.getY();\n }\n else\n {\n Real32 w = mData.getWindow()->getWidth ();\n Real32 h = mData.getWindow()->getHeight();\n\n Real32 x = mData.getX();\n Real32 y = mData.getY();\n \n a = -2.0 * (_iLastX \/ w - 0.5);\n b = -2.0 * (0.5 - _iLastY \/ h);\n c = -2.0 * ( x \/ w - 0.5 );\n d = -2.0 * (0.5 - y \/ h );\n\n fprintf(stderr, \"%f %f - %f %f\\n\", x, c, y, d);\n }\n\n if(_iMouseButtons & (1 << MouseData::LeftButton))\n {\n _oTrackball.updateRotation(a, b, c, d); \n }\n else if(_iMouseButtons & (1 << MouseData::MiddleButton))\n {\n _oTrackball.updatePosition(a, b, c, d); \n }\n else if(_iMouseButtons & (1 << MouseData::RightButton))\n {\n _oTrackball.updatePositionNeg(a, b, c, d); \n }\n\n editSFMatrixResult()->setValue(\n _oTrackball.getFullTrackballMatrix());\n }\n }\n\n _iLastX = mData.getX();\n _iLastY = mData.getY();\n }\n }\n\n if(0x0000 != (whichField & ReferencePositionFieldMask))\n {\n _oTrackball.setStartPosition(_sfReferencePosition.getValue()[0],\n _sfReferencePosition.getValue()[1],\n _sfReferencePosition.getValue()[2], \n true );\n\n editSFMatrixResult()->setValue(_oTrackball.getFullTrackballMatrix());\n }\n\n if(0x0000 != (whichField & ReferenceMatrixFieldMask))\n {\n Matrix m;\n \n m.setValue(&(_sfReferenceMatrix.getValue()[0][0]));\n \n Quaternion so;\n Vec3f s;\n Vec3f trans;\n Quaternion ro;\n Vec3f cnt;\n \n cnt[0] = _sfTransformCenter.getValue()[0];\n cnt[1] = _sfTransformCenter.getValue()[1];\n cnt[2] = _sfTransformCenter.getValue()[2];\n \n m.getTransform(trans, ro, s, so, cnt);\n \n _oTrackball.setStartRotation(ro, true);\n \n ro.invert();\n ro.multVec(trans, trans);\n \n _oTrackball.setStartPosition(trans[0],\n trans[1],\n trans[2], \n true);\n\n editSFMatrixResult()->setValue(_oTrackball.getFullTrackballMatrix());\n }\n\n if(0x0000 != (whichField & TransformCenterFieldMask))\n {\n _oTrackball.setRotationCenter(_sfTransformCenter.getValue());\n }\n\n if(0x0000 != (whichField & WorldDiagFieldMask))\n {\n _oTrackball.setTranslationScale(((_sfWorldDiag.getValue()[0] +\n _sfWorldDiag.getValue()[1] +\n _sfWorldDiag.getValue()[2]) \/ 5.f) *\n _sfTranslationScaleFactor.getValue());\n }\n\n#if 0\n if(0x0000 != (whichField & ResetFieldMask))\n {\n _oTrackball.reset();\n\n VSC::beginEdit(this, MatrixResultFieldMask);\n {\n _sfMatrixResult.setValue(_oTrackball.getFullTrackballMatrix());\n }\n VSC::endEdit (this, MatrixResultFieldMask);\n }\n#endif\n\n Inherited::changed(whichField, origin, details);\n}\n\nvoid CSMTrackball::dump( UInt32 ,\n const BitVector ) const\n{\n SLOG << \"Dump CSMTrackball NI\" << std::endl;\n}\n\nOSG_END_NAMESPACE\n<commit_msg>fixed: removed noise<commit_after>\/*---------------------------------------------------------------------------*\\\n * OpenSG *\n * *\n * *\n * Copyright (C) 2000-2006 by the OpenSG Forum *\n * *\n * www.opensg.org *\n * *\n * contact: dirk@opensg.org, gerrit.voss@vossg.org, jbehr@zgdv.de *\n * *\n\\*---------------------------------------------------------------------------*\/\n\/*---------------------------------------------------------------------------*\\\n * License *\n * *\n * This library is free software; you can redistribute it and\/or modify it *\n * under the terms of the GNU Library General Public License as published *\n * by the Free Software Foundation, version 2. *\n * *\n * This library is distributed in the hope that it will be useful, but *\n * WITHOUT ANY WARRANTY; without even the implied warranty of *\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *\n * Library General Public License for more details. *\n * *\n * You should have received a copy of the GNU Library General Public *\n * License along with this library; if not, write to the Free Software *\n * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. *\n * *\n\\*---------------------------------------------------------------------------*\/\n\/*---------------------------------------------------------------------------*\\\n * Changes *\n * *\n * *\n * *\n * *\n * *\n * *\n\\*---------------------------------------------------------------------------*\/\n\n\/\/---------------------------------------------------------------------------\n\/\/ Includes\n\/\/---------------------------------------------------------------------------\n\n#include <cstdlib>\n#include <cstdio>\n\n#include <OSGConfig.h>\n\n#include \"OSGCSMTrackball.h\"\n#include \"OSGWindow.h\"\n\nOSG_BEGIN_NAMESPACE\n\n\/\/ Documentation for this class is emitted in the\n\/\/ OSGCSMTrackballBase.cpp file.\n\/\/ To modify it, please change the .fcd file (OSGCSMTrackball.fcd) and\n\/\/ regenerate the base file.\n\n\/***************************************************************************\\\n * Class variables *\n\\***************************************************************************\/\n\n\/***************************************************************************\\\n * Class methods *\n\\***************************************************************************\/\n\nvoid CSMTrackball::initMethod(InitPhase ePhase)\n{\n Inherited::initMethod(ePhase);\n\n if(ePhase == TypeObject::SystemPost)\n {\n }\n}\n\n\n\/***************************************************************************\\\n * Instance methods *\n\\***************************************************************************\/\n\n\/*-------------------------------------------------------------------------*\\\n - private -\n\\*-------------------------------------------------------------------------*\/\n\n\/*----------------------- constructors & destructors ----------------------*\/\n\nCSMTrackball::CSMTrackball(void) :\n Inherited ( ),\n _oTrackball ( ),\n _iLastX (-1),\n _iLastY (-1),\n _iMouseButtons( 0)\n\n{\n _oTrackball.setStartPosition(0, 0, 10, true);\n _oTrackball.setTranslationScale(1.f);\n\n _oTrackball.setMode (Trackball::OSGObject);\n _oTrackball.setSum (true );\n _oTrackball.setTranslationMode (Trackball::OSGFree );\n}\n\nCSMTrackball::CSMTrackball(const CSMTrackball &source) :\n Inherited (source),\n _oTrackball ( ),\n _iLastX (-1 ),\n _iLastY (-1 ),\n _iMouseButtons( 0 )\n\n{\n _oTrackball.setStartPosition(0, 0, 10, true);\n _oTrackball.setTranslationScale(1.f);\n\n _oTrackball.setMode (Trackball::OSGObject);\n _oTrackball.setSum (true );\n _oTrackball.setTranslationMode (Trackball::OSGFree );\n}\n\nCSMTrackball::~CSMTrackball(void)\n{\n}\n\n\/*----------------------------- class specific ----------------------------*\/\n\nvoid CSMTrackball::changed(ConstFieldMaskArg whichField, \n UInt32 origin,\n BitVector details)\n{\n if(0x0000 != (whichField & MouseDataFieldMask))\n {\n const MouseData &mData = _sfMouseData.getValue();\n\n if((0x0000 != (mData.getModifier() & _sfModifierMask.getValue())) ||\n (_sfProcessing.getValue() == true))\n {\n if(mData.getButton() != -1)\n {\n if(mData.getState() == MouseData::ButtonDown)\n {\n switch(mData.getButton())\n {\n case MouseData::LeftButton : \n break;\n \n case MouseData::MiddleButton :\n _oTrackball.setAutoPosition(true);\n break;\n \n case MouseData::RightButton : \n _oTrackball.setAutoPositionNeg(true);\n break;\n }\n\n _iMouseButtons |= 1 << mData.getButton();\n\n editSFProcessing()->setValue(true);\n }\n else\n {\n switch(mData.getButton())\n {\n case MouseData::LeftButton : \n break;\n \n case MouseData::MiddleButton :\n _oTrackball.setAutoPosition(false);\n break;\n \n case MouseData::RightButton : \n _oTrackball.setAutoPositionNeg(false);\n break;\n } \n \n _iMouseButtons &= ~(1 << mData.getButton());\n\n editSFProcessing()->setValue(false);\n }\n }\n else\n {\n if(_sfProcessing.getValue() == true)\n {\n Real32 a,b,c,d;\n\n if(mData.getMode() == MouseData::RelValues)\n {\n a = 0.f;\n b = 0.f;\n\n c = mData.getX();\n d = mData.getY();\n }\n else\n {\n Real32 w = mData.getWindow()->getWidth ();\n Real32 h = mData.getWindow()->getHeight();\n\n Real32 x = mData.getX();\n Real32 y = mData.getY();\n \n a = -2.0 * (_iLastX \/ w - 0.5);\n b = -2.0 * (0.5 - _iLastY \/ h);\n c = -2.0 * ( x \/ w - 0.5 );\n d = -2.0 * (0.5 - y \/ h );\n }\n\n if(_iMouseButtons & (1 << MouseData::LeftButton))\n {\n _oTrackball.updateRotation(a, b, c, d); \n }\n else if(_iMouseButtons & (1 << MouseData::MiddleButton))\n {\n _oTrackball.updatePosition(a, b, c, d); \n }\n else if(_iMouseButtons & (1 << MouseData::RightButton))\n {\n _oTrackball.updatePositionNeg(a, b, c, d); \n }\n\n editSFMatrixResult()->setValue(\n _oTrackball.getFullTrackballMatrix());\n }\n }\n\n _iLastX = mData.getX();\n _iLastY = mData.getY();\n }\n }\n\n if(0x0000 != (whichField & ReferencePositionFieldMask))\n {\n _oTrackball.setStartPosition(_sfReferencePosition.getValue()[0],\n _sfReferencePosition.getValue()[1],\n _sfReferencePosition.getValue()[2], \n true );\n\n editSFMatrixResult()->setValue(_oTrackball.getFullTrackballMatrix());\n }\n\n if(0x0000 != (whichField & ReferenceMatrixFieldMask))\n {\n Matrix m;\n \n m.setValue(&(_sfReferenceMatrix.getValue()[0][0]));\n \n Quaternion so;\n Vec3f s;\n Vec3f trans;\n Quaternion ro;\n Vec3f cnt;\n \n cnt[0] = _sfTransformCenter.getValue()[0];\n cnt[1] = _sfTransformCenter.getValue()[1];\n cnt[2] = _sfTransformCenter.getValue()[2];\n \n m.getTransform(trans, ro, s, so, cnt);\n \n _oTrackball.setStartRotation(ro, true);\n \n ro.invert();\n ro.multVec(trans, trans);\n \n _oTrackball.setStartPosition(trans[0],\n trans[1],\n trans[2], \n true);\n\n editSFMatrixResult()->setValue(_oTrackball.getFullTrackballMatrix());\n }\n\n if(0x0000 != (whichField & TransformCenterFieldMask))\n {\n _oTrackball.setRotationCenter(_sfTransformCenter.getValue());\n }\n\n if(0x0000 != (whichField & WorldDiagFieldMask))\n {\n _oTrackball.setTranslationScale(((_sfWorldDiag.getValue()[0] +\n _sfWorldDiag.getValue()[1] +\n _sfWorldDiag.getValue()[2]) \/ 5.f) *\n _sfTranslationScaleFactor.getValue());\n }\n\n#if 0\n if(0x0000 != (whichField & ResetFieldMask))\n {\n _oTrackball.reset();\n\n VSC::beginEdit(this, MatrixResultFieldMask);\n {\n _sfMatrixResult.setValue(_oTrackball.getFullTrackballMatrix());\n }\n VSC::endEdit (this, MatrixResultFieldMask);\n }\n#endif\n\n Inherited::changed(whichField, origin, details);\n}\n\nvoid CSMTrackball::dump( UInt32 ,\n const BitVector ) const\n{\n SLOG << \"Dump CSMTrackball NI\" << std::endl;\n}\n\nOSG_END_NAMESPACE\n<|endoftext|>"} {"text":"<commit_before>\/*!\r\n * \\file SU2_SOL.cpp\r\n * \\brief Main file for the solution export\/conversion code (SU2_SOL).\r\n * \\author Aerospace Design Laboratory (Stanford University) <http:\/\/su2.stanford.edu>.\r\n * \\version 3.0.0 \"eagle\"\r\n *\r\n * SU2, Copyright (C) 2012-2014 Aerospace Design Laboratory (ADL).\r\n *\r\n * SU2 is free software; you can redistribute it and\/or\r\n * modify it under the terms of the GNU Lesser General Public\r\n * License as published by the Free Software Foundation; either\r\n * version 2.1 of the License, or (at your option) any later version.\r\n *\r\n * SU2 is distributed in the hope that it will be useful,\r\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\r\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\r\n * Lesser General Public License for more details.\r\n *\r\n * You should have received a copy of the GNU Lesser General Public\r\n * License along with SU2. If not, see <http:\/\/www.gnu.org\/licenses\/>.\r\n *\/\r\n\r\n#include \"..\/include\/SU2_SOL.hpp\"\r\n\r\nusing namespace std;\r\n\r\nint main(int argc, char *argv[]) {\r\n\t\/*--- Variable definitions ---*\/\r\n\tunsigned short iZone, nZone;\r\n\tunsigned long iExtIter, nExtIter;\r\n\tofstream ConvHist_file;\r\n\tchar file_name[200];\r\n\tint rank = MASTER_NODE;\r\n int size = SINGLE_NODE;\r\n\r\n#ifndef NO_MPI\r\n\t\/*--- MPI initialization, and buffer setting ---*\/\r\n#ifdef WINDOWS\r\n\tMPI_Init(&argc,&argv);\r\n\tMPI_Comm_rank(MPI_COMM_WORLD,&rank);\r\n\tMPI_Comm_size(MPI_COMM_WORLD,&size);\r\n#else\r\n\tMPI::Init(argc, argv);\r\n\trank = MPI::COMM_WORLD.Get_rank();\r\n\tsize = MPI::COMM_WORLD.Get_size();\r\n#endif\r\n#endif\r\n \r\n\t\/*--- Pointer to different structures that will be used throughout the entire code ---*\/\r\n\tCOutput *output = NULL;\r\n\tCGeometry **geometry = NULL;\r\n\tCSolver **solver = NULL;\r\n\tCConfig **config = NULL;\r\n\t\r\n\t\/*--- Definition of the containers per zones ---*\/\r\n\tsolver = new CSolver*[MAX_ZONES];\r\n\tconfig = new CConfig*[MAX_ZONES];\r\n\tgeometry = new CGeometry *[MAX_ZONES];\r\n\t\r\n\t\/*--- Only one zone is allowed ---*\/\r\n\tnZone = 1;\r\n\t\r\n\tfor (iZone = 0; iZone < nZone; iZone++) {\r\n\t\t\r\n\t\t\/*--- Definition of the configuration class per zones ---*\/\r\n\t\tif (argc == 2) config[iZone] = new CConfig(argv[1], SU2_SOL, iZone, nZone, 0, VERB_HIGH);\r\n\t\telse { strcpy (file_name, \"default.cfg\"); config[iZone] = new CConfig(file_name, SU2_SOL,\r\n iZone, nZone, 0, VERB_HIGH); }\r\n\t\t\r\n#ifndef NO_MPI\r\n\t\t\/*--- Change the name of the input-output files for a parallel computation ---*\/\r\n\t\tconfig[iZone]->SetFileNameDomain(rank+1);\r\n#endif\r\n \r\n\t\t\/*--- Definition of the geometry class and open the mesh file ---*\/\r\n\t\tgeometry[iZone] = new CPhysicalGeometry(config[iZone], iZone+1, nZone);\r\n \r\n \/*--- Create the vertex structure (required for MPI) ---*\/\r\n if (rank == MASTER_NODE) cout << \"Identify vertices.\" <<endl;\r\n geometry[iZone]->SetVertex(config[iZone]);\r\n \r\n \/*--- Perform the non-dimensionalization for the flow equations using the\r\n specified reference values. ---*\/\r\n \r\n\t\tconfig[iZone]->SetNondimensionalization(geometry[iZone]->GetnDim(), iZone);\r\n \r\n }\r\n \r\n#ifndef NO_MPI\r\n \/*--- Synchronization point after the geometrical definition subroutine ---*\/\r\n#ifdef WINDOWS\r\n\tMPI_Barrier(MPI_COMM_WORLD);\r\n#else\r\n\tMPI::COMM_WORLD.Barrier();\r\n#endif\r\n#endif\r\n \r\n if (rank == MASTER_NODE)\r\n cout << endl <<\"------------------------- Solution Postprocessing -----------------------\" << endl;\r\n \r\n#ifndef NO_MPI\r\n \/*--- Synchronization point after the solution subroutine ---*\/\r\n#ifdef WINDOWS\r\n\tMPI_Barrier(MPI_COMM_WORLD);\r\n#else\r\n\tMPI::COMM_WORLD.Barrier();\r\n#endif\r\n#endif\r\n \r\n\t\/*--- Definition of the output class (one for all the zones) ---*\/\r\n\toutput = new COutput();\r\n \r\n \/*--- Check whether this is an unsteady simulation, and call the\r\n solution merging routines accordingly.---*\/\r\n \r\n if (config[ZONE_0]->GetWrt_Unsteady()) {\r\n \r\n \/*--- Unsteady simulation: merge all unsteady time steps. First,\r\n find the frequency and total number of files to write. ---*\/\r\n \r\n double Physical_dt, Physical_t;\r\n unsigned long iExtIter = 0;\r\n bool StopCalc = false;\r\n \r\n \/*--- Check for an unsteady restart. Update ExtIter if necessary. ---*\/\r\n if (config[ZONE_0]->GetWrt_Unsteady() && config[ZONE_0]->GetRestart())\r\n iExtIter = config[ZONE_0]->GetUnst_RestartIter();\r\n \r\n while (iExtIter < config[ZONE_0]->GetnExtIter()) {\r\n \r\n \/*--- Check several conditions in order to merge the correct time step files. ---*\/\r\n Physical_dt = config[ZONE_0]->GetDelta_UnstTime();\r\n Physical_t = (iExtIter+1)*Physical_dt;\r\n if (Physical_t >= config[ZONE_0]->GetTotal_UnstTime())\r\n StopCalc = true;\r\n \r\n if ((iExtIter+1 == config[ZONE_0]->GetnExtIter()) ||\r\n ((iExtIter % config[ZONE_0]->GetWrt_Sol_Freq() == 0) && (iExtIter != 0) &&\r\n !((config[ZONE_0]->GetUnsteady_Simulation() == DT_STEPPING_1ST) ||\r\n (config[ZONE_0]->GetUnsteady_Simulation() == DT_STEPPING_2ND))) ||\r\n (StopCalc) ||\r\n (((config[ZONE_0]->GetUnsteady_Simulation() == DT_STEPPING_1ST) ||\r\n (config[ZONE_0]->GetUnsteady_Simulation() == DT_STEPPING_2ND)) &&\r\n ((iExtIter == 0) || (iExtIter % config[ZONE_0]->GetWrt_Sol_Freq_DualTime() == 0)))) {\r\n \r\n \/*--- Set the current iteration number in the config class. ---*\/\r\n config[ZONE_0]->SetExtIter(iExtIter);\r\n \r\n \/*--- Read in the restart file for this time step ---*\/\r\n for (iZone = 0; iZone < nZone; iZone++) {\r\n \r\n \/*--- Either instantiate the solution class or load a restart file. ---*\/\r\n if (iExtIter == 0 || (config[ZONE_0]->GetRestart() && iExtIter == config[ZONE_0]->GetUnst_RestartIter()))\r\n solver[iZone] = new CBaselineSolver(geometry[iZone], config[iZone], MESH_0);\r\n else\r\n solver[iZone]->LoadRestart(geometry, &solver, config[iZone], int(MESH_0));\r\n }\r\n\r\n if (rank == MASTER_NODE)\r\n cout << \"Writing the volume solution for time step \" << iExtIter << \".\" << endl;\r\n output->SetBaselineResult_Files(solver, geometry, config, iExtIter, nZone);\r\n }\r\n \r\n iExtIter++;\r\n if (StopCalc) break;\r\n }\r\n \r\n } else if (config[ZONE_0]->GetUnsteady_Simulation() == TIME_SPECTRAL) {\r\n\r\n\t \/*--- Time-spectral simulation: merge files for each time instance (each zone). ---*\/\r\n\t unsigned short nTimeSpectral = config[ZONE_0]->GetnTimeInstances();\r\n\t unsigned short iTimeSpectral;\r\n\t for (iTimeSpectral = 0; iTimeSpectral < nTimeSpectral; iTimeSpectral++) {\r\n\r\n\t\t \/*--- Set the current instance number in the config class to \"ExtIter.\" ---*\/\r\n\t\t config[ZONE_0]->SetExtIter(iTimeSpectral);\r\n\r\n\t\t \/*--- Read in the restart file for this time step ---*\/\r\n\t\t \/*--- N.B. In SU2_SOL, nZone != nTimeInstances ---*\/\r\n\t\t for (iZone = 0; iZone < nZone; iZone++) {\r\n\r\n\t\t\t \/*--- Either instantiate the solution class or load a restart file. ---*\/\r\n\t\t\t if (iTimeSpectral == 0)\r\n\t\t\t\t solver[iZone] = new CBaselineSolver(geometry[iZone], config[iZone], MESH_0);\r\n\t\t\t else\r\n\t\t\t\t solver[iZone]->LoadRestart(geometry, &solver, config[iZone], int(MESH_0));\r\n\t\t }\r\n\r\n\t\t \/*--- Print progress in solution writing to the screen. ---*\/\r\n\t\t if (rank == MASTER_NODE) {\r\n\t\t\t cout << \"Writing the volume solution for time instance \" << iTimeSpectral << \".\" << endl;\r\n\t\t }\r\n\r\n\t\t output->SetBaselineResult_Files(solver, geometry, config, iTimeSpectral, nZone);\r\n\t }\r\n } else {\r\n\r\n\t \/*--- Steady simulation: merge the single solution file. ---*\/\r\n\r\n\t for (iZone = 0; iZone < nZone; iZone++) {\r\n\t\t \/*--- Definition of the solution class ---*\/\r\n\t\t solver[iZone] = new CBaselineSolver(geometry[iZone], config[iZone], MESH_0);\r\n\t }\r\n\r\n\t output->SetBaselineResult_Files(solver, geometry, config, 0, nZone);\r\n\r\n }\r\n \r\n\r\n#ifndef NO_MPI\r\n \/*--- Finalize MPI parallelization ---*\/\r\n#ifdef WINDOWS\r\n MPI_Finalize();\r\n#else\r\n MPI::Finalize();\r\n#endif\r\n#endif\r\n \r\n \/*--- End solver ---*\/\r\n if (rank == MASTER_NODE)\r\n cout << endl <<\"------------------------- Exit Success (SU2_SOL) ------------------------\" << endl << endl;\r\n \r\n return EXIT_SUCCESS;\r\n}\r\n<commit_msg>Fixed SU2_SOL so that for unsteady restarts it doesn't require you to write a solution at every iteration<commit_after>\/*!\r\n * \\file SU2_SOL.cpp\r\n * \\brief Main file for the solution export\/conversion code (SU2_SOL).\r\n * \\author Aerospace Design Laboratory (Stanford University) <http:\/\/su2.stanford.edu>.\r\n * \\version 3.0.0 \"eagle\"\r\n *\r\n * SU2, Copyright (C) 2012-2014 Aerospace Design Laboratory (ADL).\r\n *\r\n * SU2 is free software; you can redistribute it and\/or\r\n * modify it under the terms of the GNU Lesser General Public\r\n * License as published by the Free Software Foundation; either\r\n * version 2.1 of the License, or (at your option) any later version.\r\n *\r\n * SU2 is distributed in the hope that it will be useful,\r\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\r\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\r\n * Lesser General Public License for more details.\r\n *\r\n * You should have received a copy of the GNU Lesser General Public\r\n * License along with SU2. If not, see <http:\/\/www.gnu.org\/licenses\/>.\r\n *\/\r\n\r\n#include \"..\/include\/SU2_SOL.hpp\"\r\n\r\nusing namespace std;\r\n\r\nint main(int argc, char *argv[]) {\r\n\t\/*--- Variable definitions ---*\/\r\n\tunsigned short iZone, nZone;\r\n\tofstream ConvHist_file;\r\n\tchar file_name[200];\r\n\tint rank = MASTER_NODE;\r\n int size = SINGLE_NODE;\r\n\r\n#ifndef NO_MPI\r\n\t\/*--- MPI initialization, and buffer setting ---*\/\r\n#ifdef WINDOWS\r\n\tMPI_Init(&argc,&argv);\r\n\tMPI_Comm_rank(MPI_COMM_WORLD,&rank);\r\n\tMPI_Comm_size(MPI_COMM_WORLD,&size);\r\n#else\r\n\tMPI::Init(argc, argv);\r\n\trank = MPI::COMM_WORLD.Get_rank();\r\n\tsize = MPI::COMM_WORLD.Get_size();\r\n#endif\r\n#endif\r\n \r\n\t\/*--- Pointer to different structures that will be used throughout the entire code ---*\/\r\n\tCOutput *output = NULL;\r\n\tCGeometry **geometry = NULL;\r\n\tCSolver **solver = NULL;\r\n\tCConfig **config = NULL;\r\n\t\r\n\t\/*--- Definition of the containers per zones ---*\/\r\n\tsolver = new CSolver*[MAX_ZONES];\r\n\tconfig = new CConfig*[MAX_ZONES];\r\n\tgeometry = new CGeometry *[MAX_ZONES];\r\n\t\r\n\t\/*--- Only one zone is allowed ---*\/\r\n\tnZone = 1;\r\n\t\r\n\tfor (iZone = 0; iZone < nZone; iZone++) {\r\n\t\t\r\n\t\t\/*--- Definition of the configuration class per zones ---*\/\r\n\t\tif (argc == 2) config[iZone] = new CConfig(argv[1], SU2_SOL, iZone, nZone, 0, VERB_HIGH);\r\n\t\telse { strcpy (file_name, \"default.cfg\"); config[iZone] = new CConfig(file_name, SU2_SOL,\r\n iZone, nZone, 0, VERB_HIGH); }\r\n\t\t\r\n#ifndef NO_MPI\r\n\t\t\/*--- Change the name of the input-output files for a parallel computation ---*\/\r\n\t\tconfig[iZone]->SetFileNameDomain(rank+1);\r\n#endif\r\n \r\n\t\t\/*--- Definition of the geometry class and open the mesh file ---*\/\r\n\t\tgeometry[iZone] = new CPhysicalGeometry(config[iZone], iZone+1, nZone);\r\n \r\n \/*--- Create the vertex structure (required for MPI) ---*\/\r\n if (rank == MASTER_NODE) cout << \"Identify vertices.\" <<endl;\r\n geometry[iZone]->SetVertex(config[iZone]);\r\n \r\n \/*--- Perform the non-dimensionalization for the flow equations using the\r\n specified reference values. ---*\/\r\n \r\n\t\tconfig[iZone]->SetNondimensionalization(geometry[iZone]->GetnDim(), iZone);\r\n \r\n }\r\n \r\n#ifndef NO_MPI\r\n \/*--- Synchronization point after the geometrical definition subroutine ---*\/\r\n#ifdef WINDOWS\r\n\tMPI_Barrier(MPI_COMM_WORLD);\r\n#else\r\n\tMPI::COMM_WORLD.Barrier();\r\n#endif\r\n#endif\r\n \r\n if (rank == MASTER_NODE)\r\n cout << endl <<\"------------------------- Solution Postprocessing -----------------------\" << endl;\r\n \r\n#ifndef NO_MPI\r\n \/*--- Synchronization point after the solution subroutine ---*\/\r\n#ifdef WINDOWS\r\n\tMPI_Barrier(MPI_COMM_WORLD);\r\n#else\r\n\tMPI::COMM_WORLD.Barrier();\r\n#endif\r\n#endif\r\n \r\n\t\/*--- Definition of the output class (one for all the zones) ---*\/\r\n\toutput = new COutput();\r\n \r\n \/*--- Check whether this is an unsteady simulation, and call the\r\n solution merging routines accordingly.---*\/\r\n \r\n if (config[ZONE_0]->GetWrt_Unsteady()) {\r\n \r\n \/*--- Unsteady simulation: merge all unsteady time steps. First,\r\n find the frequency and total number of files to write. ---*\/\r\n \r\n double Physical_dt, Physical_t;\r\n unsigned long iExtIter = 0;\r\n bool StopCalc = false;\r\n bool SolutionInstantiated = false;\r\n \r\n \/*--- Check for an unsteady restart. Update ExtIter if necessary. ---*\/\r\n if (config[ZONE_0]->GetWrt_Unsteady() && config[ZONE_0]->GetRestart())\r\n iExtIter = config[ZONE_0]->GetUnst_RestartIter();\r\n \r\n while (iExtIter < config[ZONE_0]->GetnExtIter()) {\r\n \r\n \/*--- Check several conditions in order to merge the correct time step files. ---*\/\r\n Physical_dt = config[ZONE_0]->GetDelta_UnstTime();\r\n Physical_t = (iExtIter+1)*Physical_dt;\r\n if (Physical_t >= config[ZONE_0]->GetTotal_UnstTime())\r\n StopCalc = true;\r\n \r\n if ((iExtIter+1 == config[ZONE_0]->GetnExtIter()) ||\r\n ((iExtIter % config[ZONE_0]->GetWrt_Sol_Freq() == 0) && (iExtIter != 0) &&\r\n !((config[ZONE_0]->GetUnsteady_Simulation() == DT_STEPPING_1ST) ||\r\n (config[ZONE_0]->GetUnsteady_Simulation() == DT_STEPPING_2ND))) ||\r\n (StopCalc) ||\r\n (((config[ZONE_0]->GetUnsteady_Simulation() == DT_STEPPING_1ST) ||\r\n (config[ZONE_0]->GetUnsteady_Simulation() == DT_STEPPING_2ND)) &&\r\n ((iExtIter == 0) || (iExtIter % config[ZONE_0]->GetWrt_Sol_Freq_DualTime() == 0)))) {\r\n\r\n \/*--- Set the current iteration number in the config class. ---*\/\r\n config[ZONE_0]->SetExtIter(iExtIter);\r\n \r\n \/*--- Read in the restart file for this time step ---*\/\r\n for (iZone = 0; iZone < nZone; iZone++) {\r\n \r\n \/*--- Either instantiate the solution class or load a restart file. ---*\/\r\n if (SolutionInstantiated == false && (iExtIter == 0 ||\r\n (config[ZONE_0]->GetRestart() && (iExtIter == config[ZONE_0]->GetUnst_RestartIter() ||\r\n iExtIter % config[ZONE_0]->GetWrt_Sol_Freq_DualTime() == 0 ||\r\n iExtIter+1 == config[ZONE_0]->GetnExtIter())))) {\r\n solver[iZone] = new CBaselineSolver(geometry[iZone], config[iZone], MESH_0);\r\n SolutionInstantiated = true;\r\n }\r\n else\r\n solver[iZone]->LoadRestart(geometry, &solver, config[iZone], int(MESH_0));\r\n }\r\n\r\n if (rank == MASTER_NODE)\r\n cout << \"Writing the volume solution for time step \" << iExtIter << \".\" << endl;\r\n output->SetBaselineResult_Files(solver, geometry, config, iExtIter, nZone);\r\n }\r\n \r\n iExtIter++;\r\n if (StopCalc) break;\r\n }\r\n \r\n } else if (config[ZONE_0]->GetUnsteady_Simulation() == TIME_SPECTRAL) {\r\n\r\n\t \/*--- Time-spectral simulation: merge files for each time instance (each zone). ---*\/\r\n\t unsigned short nTimeSpectral = config[ZONE_0]->GetnTimeInstances();\r\n\t unsigned short iTimeSpectral;\r\n\t for (iTimeSpectral = 0; iTimeSpectral < nTimeSpectral; iTimeSpectral++) {\r\n\r\n\t\t \/*--- Set the current instance number in the config class to \"ExtIter.\" ---*\/\r\n\t\t config[ZONE_0]->SetExtIter(iTimeSpectral);\r\n\r\n\t\t \/*--- Read in the restart file for this time step ---*\/\r\n\t\t \/*--- N.B. In SU2_SOL, nZone != nTimeInstances ---*\/\r\n\t\t for (iZone = 0; iZone < nZone; iZone++) {\r\n\r\n\t\t\t \/*--- Either instantiate the solution class or load a restart file. ---*\/\r\n\t\t\t if (iTimeSpectral == 0)\r\n\t\t\t\t solver[iZone] = new CBaselineSolver(geometry[iZone], config[iZone], MESH_0);\r\n\t\t\t else\r\n\t\t\t\t solver[iZone]->LoadRestart(geometry, &solver, config[iZone], int(MESH_0));\r\n\t\t }\r\n\r\n\t\t \/*--- Print progress in solution writing to the screen. ---*\/\r\n\t\t if (rank == MASTER_NODE) {\r\n\t\t\t cout << \"Writing the volume solution for time instance \" << iTimeSpectral << \".\" << endl;\r\n\t\t }\r\n\r\n\t\t output->SetBaselineResult_Files(solver, geometry, config, iTimeSpectral, nZone);\r\n\t }\r\n } else {\r\n\r\n\t \/*--- Steady simulation: merge the single solution file. ---*\/\r\n\r\n\t for (iZone = 0; iZone < nZone; iZone++) {\r\n\t\t \/*--- Definition of the solution class ---*\/\r\n\t\t solver[iZone] = new CBaselineSolver(geometry[iZone], config[iZone], MESH_0);\r\n\t }\r\n\r\n\t output->SetBaselineResult_Files(solver, geometry, config, 0, nZone);\r\n\r\n }\r\n \r\n\r\n#ifndef NO_MPI\r\n \/*--- Finalize MPI parallelization ---*\/\r\n#ifdef WINDOWS\r\n MPI_Finalize();\r\n#else\r\n MPI::Finalize();\r\n#endif\r\n#endif\r\n \r\n \/*--- End solver ---*\/\r\n if (rank == MASTER_NODE)\r\n cout << endl <<\"------------------------- Exit Success (SU2_SOL) ------------------------\" << endl << endl;\r\n \r\n return EXIT_SUCCESS;\r\n}\r\n<|endoftext|>"} {"text":"<commit_before>#include \"graph.hpp\"\n#include <stack>\n#include <queue>\n#include <algorithm>\n\n#define N 32\n\nusing namespace std;\n\nshared_ptr<Vertex> Graph::getVertex(std::string name) const {\n auto it = this->vertices.begin();\n for (; it != this->vertices.end(); it++) {\n if ((*it)->getName() == name) break;\n }\n return (it != this->vertices.end()) ? *it : nullptr;\n\n}\n\nGraph::Graph(vector<tuple<string, int>> vertices,\n\t vector<tuple<string, string, int>> edges,\n\t bool directed=false) {\n\n this->directed = directed; \t\/\/ Is the graph directed?\n\n \/\/ Build the vertices\n for (auto it = vertices.begin(); it != vertices.end(); it++)\n this->vertices.push_back(make_shared<Vertex>(get<1>(*it), get<0>(*it)));\n\n for (auto it = edges.begin(); it != edges.end(); it++)\n this->edges.push_back(make_shared<Edge>(get<2>(*it),\n\t\t\t\t Graph::getVertex(get<0>(*it)),\n\t\t\t\t Graph::getVertex(get<1>(*it))));\n \/\/ Now make the adjacency list for the vertices\n for (auto it = this->vertices.begin(); it != this->vertices.end(); it++) {\n vector<shared_ptr<Edge>> ie;\n for (auto eit = this->edges.begin(); eit != this->edges.end(); eit++) {\n if ((*it)->getName() == (*eit)->second()->getName()\n\t || (*it)->getName() == (*eit)->first()->getName())\n\tie.push_back(*eit);\n }\n (*it)->setIEdges(ie);\n }\n}\n\nshared_ptr<Vertex> Edge::opposite(string v) {\n if (v == this->first()->getName())\n return this->second();\n else return this->first();\n}\n\nvector<shared_ptr<Vertex>> Vertex::neighbors() {\n vector<shared_ptr<Vertex>> ret;\n for (auto it = this->incidentEdges.begin(); it != this->incidentEdges.end(); it++) {\n ret.push_back((*it)->opposite(this->getName()));\n }\n return ret;\n}\n\nvoid print(shared_ptr<Vertex> v) {\n cout << \" name: \" << v->getName() << endl;\n}\n\n\/\/ DFS for the graph with a function.\ntemplate<typename F>\nstatic void doDFS(Graph g, shared_ptr<Vertex> start, F fun) {\n stack<shared_ptr<Vertex>> s;\n s.push(start);\n\n do\n {\n \/\/ First get all the neighbors\n shared_ptr<Vertex> n = s.top();\n \/\/ Print the name of the node\n fun(n); \/\/ XXX: Look this is a lambda (functor in C++ parlance)\n\t \/\/ from the argument.\n s.pop(); \t\t\t\/\/ Very bad stack interface of C++!\n n->setVisited(true);\n vector<shared_ptr<Vertex>> vns = n->neighbors();\n for (auto it = vns.begin(); it != vns.end(); it++) {\n\tif (!(*it)->getVisited()) {\n\t s.push(*it);\n\t (*it)->setVisited(true);\n\t}\n }\n } while (!s.empty());\n\n g.resetVisited();\n}\n\n\/\/ Topological sort in a directed graph\ntemplate<void (*fun)(shared_ptr<Vertex>)>\nstatic void topological_sort(Graph g) {\n if (!g.getDirected()) return;\n\n \/\/ First make the degree for the vertex.\n queue<shared_ptr<Vertex>> start_vertices;\n vector<shared_ptr<Vertex>> mvertices = g.getVertices();\n for (auto it = mvertices.begin(); it != mvertices.end(); ++it) {\n vector<shared_ptr<Edge>> ves = (*it)->getIEdges();\n for (auto eit = ves.begin(); eit != ves.end(); ++eit) {\n \/\/ Increment your degree if you are the second in the incident-edge\n if ((*eit)->second()->getName() == (*it)->getName())\n\t(*it)->degree += 1;\n }\n if ((*it)->degree == 0) start_vertices.push(g.getVertex((*it)->getName()));\n }\n \/\/ Now we can start going through and doing the actual topological sort.\n do\n {\n \/\/ Process vertices\n shared_ptr<Vertex> el = start_vertices.front();\n start_vertices.pop(); \t\/\/ C++'s horrible API!\n fun(el); \/\/ XXX: Look this is a function pointer from the\n\t \/\/ template argument.\n\n \/\/ Get all its neighbors and if their degree is 0, then push\n \/\/ them onto the queue.\n vector<shared_ptr<Vertex>> eln = el->neighbors();\n for (auto it = eln.begin(); it != eln.end(); ++it) {\n\t(*it)->degree -= 1;\n\tif ((*it)->degree == 0) start_vertices.push(*it);\n }\n } while (!start_vertices.empty());\n\n}\n\nvector<shared_ptr<Vertex>> mst (shared_ptr<Vertex> p, vector<shared_ptr<Vertex>> gvs) {\n vector<shared_ptr<Vertex>> ret;\n \/\/ XXX: Don't forget to remove the parent from the gvs\n auto it = gvs.begin();\n vector<decltype(it)> vits;\n for (; it != gvs.end(); ++it){\n if ((*it)->dist.second->getName() == p->getName()) {\n vits.push_back(it);\n ret.push_back(*it);\n }\n }\n\n \/\/ Now delete the indices from gvs.\n for (auto it = vits.begin(); it != vits.end(); ++it)\n gvs.erase(*it);\n\n return ret;\n}\n\n\/\/ XXX: shortest path and MST together\nvector<shared_ptr<Vertex>> sp_mst(Graph g, shared_ptr<Vertex> start) {\n \/\/ We need to use a priority queue.\n\n \/\/ Declare a pq with a comparator.\n auto comp = [](const shared_ptr<Vertex> e1,\n\t\t const shared_ptr<Vertex> e2){\n return e1->dist.first > e2->dist.first;\n };\n priority_queue<shared_ptr<Vertex>,\n\t\t vector<shared_ptr<Vertex>>,\n\t\t decltype(comp)> pq(comp);\n pq.push(start);\n\n do\n {\n \/\/ First get all the neighbors\n shared_ptr<Vertex> me = pq.top();\n vector<shared_ptr<Edge>> ie = me->getIEdges();\n pq.pop(); \t\t\/\/ remove the top from the pq.\n \/\/ Expand the distance for each neighbor.\n for(shared_ptr<Edge> x : ie) {\n\tshared_ptr<Vertex> men = x->opposite(me->getName());\n\tunsigned xw = x->getWeight();\n\tif (!men->getVisited() && men->dist.first > me->dist.first + xw) {\n\t men->dist.first = me->dist.first+xw;\n\t men->dist.second = me;\n\t pq.push(men); \t\/\/ FIXME: can add same vertex again!\n\t}\n }\n me->setVisited(true);\n } while (!pq.empty());\n\n \/\/ Build the minimum spanning tree\n vector<shared_ptr<Vertex>> gvs = g.getVertices();\n vector<shared_ptr<Vertex>> q;\n q.push_back (start);\n\n \/\/ remove start from gvs.\n auto it = gvs.begin();\n for ( ; it != gvs.end(); ++it)\n if ((*it) == start) break;\n \/\/ remove it from gvs.\n gvs.erase(it);\n\n unsigned counter = 0;\n for (; counter < q.size(); ++counter) {\n auto nn = mst(q[counter], gvs);\n for (auto x: nn)\n q.push_back(x);\n }\n return q;\n\n}\n\n\/\/ XXX: Independent sets (dual of cliques).\nvector<shared_ptr<Vertex>> independent_sets (Graph g){\n vector<shared_ptr<Vertex>> ret {};\n vector<shared_ptr<Vertex>> gvs = g.getVertices();\n vector<shared_ptr<Edge>> ges = g.getEdges();\n unsigned pcount = 0;\n for (unsigned i = (2 << (gvs.size() - 1))-1; i >=1 ; --i) {\n bitset<N> bb(i); \t\t\/\/ FIXME: This is very annoying in C++\n vector<shared_ptr<Vertex>> fe;\n \/\/ Now just get the length of bits that we need.\n bool possibly_return = true;\n unsigned ccount = 0;\n for (int j = gvs.size()-1; j >= 0; --j)\n if (j) {\n\t++ccount;\n\t\/\/ Now get the edge's opposite and check. \n\tfor (auto it = ges.begin(); it != ges.end(); ++it) {\n\t if ((*it)->first()->getName() == gvs[j]->getName()\n\t || (*it)->second()->getName() == gvs[j]->getName()) {\n\t if (find(gvs.begin(), gvs.end(),\n\t\t (*it)->opposite(gvs[j]->getName())) == gvs.end()) {\n\t possibly_return = false;\n\t break;\n\t }\n\t }\n\t}\n\tfe.push_back(gvs[j]);\n }\n \/\/ Now check for intersection.\n if(possibly_return && ccount > pcount)\n ret = fe;\n }\n return ret;\n}\n\nint main(void)\n{\n \/\/ Test program.\n vector<tuple<string, int>> vertices = {make_tuple(\"a\", 1), make_tuple(\"b\", 2),\n\t\t\t\t\t make_tuple(\"c\", 3), make_tuple(\"d\", 4)};\n vector<tuple<string, string, int>> edges = {make_tuple(\"a\", \"b\", 5), make_tuple(\"a\", \"c\", 1),\n\t\t\t\t\t make_tuple(\"a\", \"d\", 4), make_tuple(\"c\", \"d\", 2),\n\t\t\t\t\t make_tuple(\"d\", \"b\", 3)};\n\n \/\/ This is the graph.\n Graph g(vertices, edges, false);\n vector<shared_ptr<Vertex>> mv = g.getVertices();\n\n \/\/ Print the graph using dfs and a std::copy_backward(std::begin(container), std::end(container), std::end(container));\n\n cout << \"DFS\" << endl;\n \/\/ Here lambda is most likely also inlined.\n doDFS(g, g.getVertex(\"a\"), [](shared_ptr<Vertex> x) -> void {cout << x->getName() << endl;});\n\n \/\/ make the graph directed.\n g.setDirected(true);\n\n \/\/ Do topological sort. \n cout << \"Topological sort\" << endl;\n \/\/ Here print should be inlined -- passing print as a function pointer\n \/\/ at compile time as a template argument.\n topological_sort<print>(g);\n\n\n \/\/ Dijkstra's shortest path and minimum spanning tree together\n vector<shared_ptr<Vertex>> tree = sp_mst(g, g.getVertex(\"a\"));\n cout << \"Done mst\" << \"\\n\";\n\n \/\/ Print the tree\n for (auto x : tree)\n cout << x->getName() << \" \";\n cout << \"\\n\";\n\n\n \/\/ Independent sets\n independent_sets(g);\n\n return 0;\n}\n<commit_msg>Something wrong in the result of independent algorithm, needs to be fixed.<commit_after>#include \"graph.hpp\"\n#include <stack>\n#include <queue>\n#include <algorithm>\n\n#define N 32\n\nusing namespace std;\n\nshared_ptr<Vertex> Graph::getVertex(std::string name) const {\n auto it = this->vertices.begin();\n for (; it != this->vertices.end(); it++) {\n if ((*it)->getName() == name) break;\n }\n return (it != this->vertices.end()) ? *it : nullptr;\n\n}\n\nGraph::Graph(vector<tuple<string, int>> vertices,\n\t vector<tuple<string, string, int>> edges,\n\t bool directed=false) {\n\n this->directed = directed; \t\/\/ Is the graph directed?\n\n \/\/ Build the vertices\n for (auto it = vertices.begin(); it != vertices.end(); it++)\n this->vertices.push_back(make_shared<Vertex>(get<1>(*it), get<0>(*it)));\n\n for (auto it = edges.begin(); it != edges.end(); it++)\n this->edges.push_back(make_shared<Edge>(get<2>(*it),\n\t\t\t\t Graph::getVertex(get<0>(*it)),\n\t\t\t\t Graph::getVertex(get<1>(*it))));\n \/\/ Now make the adjacency list for the vertices\n for (auto it = this->vertices.begin(); it != this->vertices.end(); it++) {\n vector<shared_ptr<Edge>> ie;\n for (auto eit = this->edges.begin(); eit != this->edges.end(); eit++) {\n if ((*it)->getName() == (*eit)->second()->getName()\n\t || (*it)->getName() == (*eit)->first()->getName())\n\tie.push_back(*eit);\n }\n (*it)->setIEdges(ie);\n }\n}\n\nshared_ptr<Vertex> Edge::opposite(string v) {\n if (v == this->first()->getName())\n return this->second();\n else return this->first();\n}\n\nvector<shared_ptr<Vertex>> Vertex::neighbors() {\n vector<shared_ptr<Vertex>> ret;\n for (auto it = this->incidentEdges.begin(); it != this->incidentEdges.end(); it++) {\n ret.push_back((*it)->opposite(this->getName()));\n }\n return ret;\n}\n\nvoid print(shared_ptr<Vertex> v) {\n cout << \" name: \" << v->getName() << endl;\n}\n\n\/\/ DFS for the graph with a function.\ntemplate<typename F>\nstatic void doDFS(Graph g, shared_ptr<Vertex> start, F fun) {\n stack<shared_ptr<Vertex>> s;\n s.push(start);\n\n do\n {\n \/\/ First get all the neighbors\n shared_ptr<Vertex> n = s.top();\n \/\/ Print the name of the node\n fun(n); \/\/ XXX: Look this is a lambda (functor in C++ parlance)\n\t \/\/ from the argument.\n s.pop(); \t\t\t\/\/ Very bad stack interface of C++!\n n->setVisited(true);\n vector<shared_ptr<Vertex>> vns = n->neighbors();\n for (auto it = vns.begin(); it != vns.end(); it++) {\n\tif (!(*it)->getVisited()) {\n\t s.push(*it);\n\t (*it)->setVisited(true);\n\t}\n }\n } while (!s.empty());\n\n g.resetVisited();\n}\n\n\/\/ Topological sort in a directed graph\ntemplate<void (*fun)(shared_ptr<Vertex>)>\nstatic void topological_sort(Graph g) {\n if (!g.getDirected()) return;\n\n \/\/ First make the degree for the vertex.\n queue<shared_ptr<Vertex>> start_vertices;\n vector<shared_ptr<Vertex>> mvertices = g.getVertices();\n for (auto it = mvertices.begin(); it != mvertices.end(); ++it) {\n vector<shared_ptr<Edge>> ves = (*it)->getIEdges();\n for (auto eit = ves.begin(); eit != ves.end(); ++eit) {\n \/\/ Increment your degree if you are the second in the incident-edge\n if ((*eit)->second()->getName() == (*it)->getName())\n\t(*it)->degree += 1;\n }\n if ((*it)->degree == 0) start_vertices.push(g.getVertex((*it)->getName()));\n }\n \/\/ Now we can start going through and doing the actual topological sort.\n do\n {\n \/\/ Process vertices\n shared_ptr<Vertex> el = start_vertices.front();\n start_vertices.pop(); \t\/\/ C++'s horrible API!\n fun(el); \/\/ XXX: Look this is a function pointer from the\n\t \/\/ template argument.\n\n \/\/ Get all its neighbors and if their degree is 0, then push\n \/\/ them onto the queue.\n vector<shared_ptr<Vertex>> eln = el->neighbors();\n for (auto it = eln.begin(); it != eln.end(); ++it) {\n\t(*it)->degree -= 1;\n\tif ((*it)->degree == 0) start_vertices.push(*it);\n }\n } while (!start_vertices.empty());\n\n}\n\nvector<shared_ptr<Vertex>> mst (shared_ptr<Vertex> p, vector<shared_ptr<Vertex>> gvs) {\n vector<shared_ptr<Vertex>> ret;\n \/\/ XXX: Don't forget to remove the parent from the gvs\n auto it = gvs.begin();\n vector<decltype(it)> vits;\n for (; it != gvs.end(); ++it){\n if ((*it)->dist.second->getName() == p->getName()) {\n vits.push_back(it);\n ret.push_back(*it);\n }\n }\n\n \/\/ Now delete the indices from gvs.\n for (auto it = vits.begin(); it != vits.end(); ++it)\n gvs.erase(*it);\n\n return ret;\n}\n\n\/\/ XXX: shortest path and MST together\nvector<shared_ptr<Vertex>> sp_mst(Graph g, shared_ptr<Vertex> start) {\n \/\/ We need to use a priority queue.\n start->dist.first = 0;\n\n \/\/ Declare a pq with a comparator.\n auto comp = [](const shared_ptr<Vertex> e1,\n\t\t const shared_ptr<Vertex> e2){\n return e1->dist.first > e2->dist.first;\n };\n priority_queue<shared_ptr<Vertex>,\n\t\t vector<shared_ptr<Vertex>>,\n\t\t decltype(comp)> pq(comp);\n pq.push(start);\n\n do\n {\n \/\/ First get all the neighbors\n shared_ptr<Vertex> me = pq.top();\n vector<shared_ptr<Edge>> ie = me->getIEdges();\n pq.pop(); \t\t\/\/ remove the top from the pq.\n \/\/ Expand the distance for each neighbor.\n for(shared_ptr<Edge> x : ie) {\n\tshared_ptr<Vertex> men = x->opposite(me->getName());\n\tunsigned xw = x->getWeight();\n\tif (!men->getVisited() && men->dist.first > me->dist.first + xw) {\n\t men->dist.first = me->dist.first+xw;\n\t men->dist.second = me;\n\t pq.push(men); \t\/\/ FIXME: can add same vertex again!\n\t}\n }\n me->setVisited(true);\n } while (!pq.empty());\n\n \/\/ Build the minimum spanning tree\n vector<shared_ptr<Vertex>> gvs = g.getVertices();\n vector<shared_ptr<Vertex>> q;\n q.push_back (start);\n\n \/\/ remove start from gvs.\n auto it = gvs.begin();\n for ( ; it != gvs.end(); ++it)\n if ((*it) == start) break;\n \/\/ remove it from gvs.\n gvs.erase(it);\n\n unsigned counter = 0;\n for (; counter < q.size(); ++counter) {\n auto nn = mst(q[counter], gvs);\n for (auto x: nn)\n q.push_back(x);\n }\n return q;\n\n}\n\n\/\/ XXX: Independent sets (dual of cliques).\nvector<shared_ptr<Vertex>> independent_sets (Graph g){\n vector<shared_ptr<Vertex>> ret {};\n vector<shared_ptr<Vertex>> gvs = g.getVertices();\n vector<shared_ptr<Edge>> ges = g.getEdges();\n unsigned pcount = 0;\n for (unsigned i = (2 << (gvs.size() - 1))-1; i >=1 ; --i) {\n bitset<N> bb(i); \t\t\/\/ FIXME: This is very annoying in C++\n vector<shared_ptr<Vertex>> fe;\n \/\/ Now just get the length of bits that we need.\n bool possibly_return = true;\n unsigned ccount = 0;\n for (int j = gvs.size()-1; j >= 0; --j)\n if (j) {\n\t++ccount;\n\t\/\/ Now get the edge's opposite and check. \n\tfor (auto it = ges.begin(); it != ges.end(); ++it) {\n\t if ((*it)->first()->getName() == gvs[j]->getName()\n\t || (*it)->second()->getName() == gvs[j]->getName()) {\n\t if (find(gvs.begin(), gvs.end(),\n\t\t (*it)->opposite(gvs[j]->getName())) == gvs.end()) {\n\t possibly_return = false;\n\t break;\n\t }\n\t }\n\t}\n\tfe.push_back(gvs[j]);\n }\n \/\/ Now check for intersection.\n\tif(possibly_return && ccount > pcount) {\n\t\tret = fe;\n\t\tpcount = ccount;\n\t}\n }\n return ret;\n}\n\nint main(void)\n{\n \/\/ Test program.\n vector<tuple<string, int>> vertices = {make_tuple(\"a\", 1), make_tuple(\"b\", 2),\n\t\t\t\t\t make_tuple(\"c\", 3), make_tuple(\"d\", 4)};\n vector<tuple<string, string, int>> edges = {make_tuple(\"a\", \"b\", 5), make_tuple(\"a\", \"c\", 1),\n\t\t\t\t\t make_tuple(\"a\", \"d\", 4), make_tuple(\"c\", \"d\", 2),\n\t\t\t\t\t make_tuple(\"d\", \"b\", 3)};\n\n \/\/ This is the graph.\n Graph g(vertices, edges, false);\n vector<shared_ptr<Vertex>> mv = g.getVertices();\n\n \/\/ Print the graph using dfs and a std::copy_backward(std::begin(container), std::end(container), std::end(container));\n\n cout << \"DFS\" << endl;\n \/\/ Here lambda is most likely also inlined.\n doDFS(g, g.getVertex(\"a\"), [](shared_ptr<Vertex> x) -> void {cout << x->getName() << endl;});\n\n \/\/ make the graph directed.\n g.setDirected(true);\n\n \/\/ Do topological sort. \n cout << \"Topological sort\" << endl;\n \/\/ Here print should be inlined -- passing print as a function pointer\n \/\/ at compile time as a template argument.\n topological_sort<print>(g);\n\n\n \/\/ Dijkstra's shortest path and minimum spanning tree together\n vector<shared_ptr<Vertex>> tree = sp_mst(g, g.getVertex(\"a\"));\n cout << \"Done mst\" << \"\\n\";\n\n \/\/ Print the tree\n for (auto x : tree)\n cout << x->getName() << \" \";\n cout << \"\\n\";\n\n\n \/\/ Independent sets\n vector<shared_ptr<Vertex>> s = independent_sets(g);\n for (auto x: s)\n cout << x->getName() << \" \";\n cout << \"\\n\";\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/extensions\/api\/bluetooth\/bluetooth_api.h\"\n\n#include \"base\/utf_string_conversions.h\"\n#include \"chrome\/browser\/extensions\/extension_service.h\"\n#include \"chrome\/browser\/profiles\/profile.h\"\n#include \"chrome\/common\/extensions\/api\/experimental_bluetooth.h\"\n#include \"content\/public\/browser\/browser_thread.h\"\n\n#if defined(OS_CHROMEOS)\n#include \"base\/memory\/ref_counted.h\"\n#include \"base\/safe_strerror_posix.h\"\n#include \"base\/synchronization\/lock.h\"\n#include \"chrome\/browser\/chromeos\/bluetooth\/bluetooth_adapter.h\"\n#include \"chrome\/browser\/chromeos\/bluetooth\/bluetooth_device.h\"\n#include \"chrome\/browser\/chromeos\/bluetooth\/bluetooth_socket.h\"\n#include \"chrome\/browser\/chromeos\/extensions\/bluetooth_event_router.h\"\n\n#include <errno.h>\n\nusing chromeos::BluetoothAdapter;\nusing chromeos::BluetoothDevice;\n\nnamespace {\n\nchromeos::ExtensionBluetoothEventRouter* GetEventRouter(Profile* profile) {\n return profile->GetExtensionService()->bluetooth_event_router();\n}\n\nconst chromeos::BluetoothAdapter* GetAdapter(Profile* profile) {\n return GetEventRouter(profile)->adapter();\n}\n\nchromeos::BluetoothAdapter* GetMutableAdapter(Profile* profile) {\n return GetEventRouter(profile)->GetMutableAdapter();\n}\n\n} \/\/ namespace\n#endif\n\nnamespace {\n\nconst char kSocketNotFoundError[] = \"Socket not found: invalid socket id\";\n\n} \/\/ namespace\n\nnamespace Connect = extensions::api::experimental_bluetooth::Connect;\nnamespace Disconnect = extensions::api::experimental_bluetooth::Disconnect;\nnamespace GetDevicesWithServiceName =\n extensions::api::experimental_bluetooth::GetDevicesWithServiceName;\nnamespace GetDevicesWithServiceUUID =\n extensions::api::experimental_bluetooth::GetDevicesWithServiceUUID;\nnamespace Read = extensions::api::experimental_bluetooth::Read;\nnamespace Write = extensions::api::experimental_bluetooth::Write;\n\nnamespace extensions {\nnamespace api {\n\n#if defined(OS_CHROMEOS)\n\nbool BluetoothIsAvailableFunction::RunImpl() {\n result_.reset(Value::CreateBooleanValue(GetAdapter(profile())->IsPresent()));\n return true;\n}\n\nbool BluetoothIsPoweredFunction::RunImpl() {\n result_.reset(Value::CreateBooleanValue(GetAdapter(profile())->IsPowered()));\n return true;\n}\n\nbool BluetoothGetAddressFunction::RunImpl() {\n result_.reset(Value::CreateStringValue(GetAdapter(profile())->address()));\n return true;\n}\n\nbool BluetoothGetDevicesWithServiceUUIDFunction::RunImpl() {\n scoped_ptr<GetDevicesWithServiceUUID::Params> params(\n GetDevicesWithServiceUUID::Params::Create(*args_));\n EXTENSION_FUNCTION_VALIDATE(params.get() != NULL);\n\n const BluetoothAdapter::ConstDeviceList& devices =\n GetAdapter(profile())->GetDevices();\n ListValue* matches = new ListValue;\n for (BluetoothAdapter::ConstDeviceList::const_iterator i =\n devices.begin(); i != devices.end(); ++i) {\n if ((*i)->ProvidesServiceWithUUID(params->uuid)) {\n experimental_bluetooth::Device device;\n device.name = UTF16ToUTF8((*i)->GetName());\n device.address = (*i)->address();\n matches->Append(device.ToValue().release());\n }\n }\n result_.reset(matches);\n\n return true;\n}\n\nBluetoothGetDevicesWithServiceNameFunction::\n BluetoothGetDevicesWithServiceNameFunction() : callbacks_pending_(0) {}\n\nvoid BluetoothGetDevicesWithServiceNameFunction::AddDeviceIfTrue(\n ListValue* list, const BluetoothDevice* device, bool result) {\n DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));\n\n if (result) {\n experimental_bluetooth::Device device_result;\n device_result.name = UTF16ToUTF8(device->GetName());\n device_result.address = device->address();\n list->Append(device_result.ToValue().release());\n }\n\n callbacks_pending_--;\n if (callbacks_pending_ == 0) {\n SendResponse(true);\n Release(); \/\/ Added in RunImpl\n }\n}\n\nbool BluetoothGetDevicesWithServiceNameFunction::RunImpl() {\n DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));\n\n ListValue* matches = new ListValue;\n result_.reset(matches);\n\n BluetoothAdapter::DeviceList devices =\n GetMutableAdapter(profile())->GetDevices();\n if (devices.empty()) {\n SendResponse(true);\n return true;\n }\n\n callbacks_pending_ = devices.size();\n AddRef(); \/\/ Released in AddDeviceIfTrue when callbacks_pending_ == 0\n\n scoped_ptr<GetDevicesWithServiceName::Params> params(\n GetDevicesWithServiceName::Params::Create(*args_));\n EXTENSION_FUNCTION_VALIDATE(params.get() != NULL);\n for (BluetoothAdapter::DeviceList::iterator i = devices.begin();\n i != devices.end(); ++i) {\n (*i)->ProvidesServiceWithName(params->name,\n base::Bind(&BluetoothGetDevicesWithServiceNameFunction::AddDeviceIfTrue,\n this,\n matches,\n *i));\n }\n\n return true;\n}\n\nvoid BluetoothConnectFunction::ConnectToServiceCallback(\n const chromeos::BluetoothDevice* device,\n const std::string& service_uuid,\n scoped_refptr<chromeos::BluetoothSocket> socket) {\n if (socket.get()) {\n int socket_id = GetEventRouter(profile())->RegisterSocket(socket);\n\n experimental_bluetooth::Socket result_socket;\n result_socket.device.address = device->address();\n result_socket.device.name = UTF16ToUTF8(device->GetName());\n result_socket.service_uuid = service_uuid;\n result_socket.id = socket_id;\n result_.reset(result_socket.ToValue().release());\n SendResponse(true);\n } else {\n SendResponse(false);\n }\n\n Release(); \/\/ Added in RunImpl\n}\n\nbool BluetoothConnectFunction::RunImpl() {\n scoped_ptr<Connect::Params> params(Connect::Params::Create(*args_));\n EXTENSION_FUNCTION_VALIDATE(params.get() != NULL);\n\n chromeos::BluetoothDevice* device =\n GetMutableAdapter(profile())->GetDevice(params->device.address);\n if (!device) {\n SendResponse(false);\n return false;\n }\n\n AddRef();\n device->ConnectToService(params->service,\n base::Bind(&BluetoothConnectFunction::ConnectToServiceCallback,\n this,\n device,\n params->service));\n return true;\n}\n\nbool BluetoothDisconnectFunction::RunImpl() {\n scoped_ptr<Disconnect::Params> params(Disconnect::Params::Create(*args_));\n EXTENSION_FUNCTION_VALIDATE(params.get() != NULL);\n return GetEventRouter(profile())->ReleaseSocket(params->socket.id);\n}\n\nbool BluetoothReadFunction::Prepare() {\n scoped_ptr<Read::Params> params(Read::Params::Create(*args_));\n EXTENSION_FUNCTION_VALIDATE(params.get() != NULL);\n\n socket_ = GetEventRouter(profile())->GetSocket(params->socket.id);\n if (socket_.get() == NULL) {\n SetError(kSocketNotFoundError);\n return false;\n }\n\n success_ = false;\n return true;\n}\n\nvoid BluetoothReadFunction::Work() {\n DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::IO));\n CHECK(socket_.get() != NULL);\n\n char* all_bytes = NULL;\n ssize_t buffer_size = 0;\n ssize_t total_bytes_read = 0;\n int errsv;\n while (true) {\n buffer_size += 1024;\n all_bytes = static_cast<char*>(realloc(all_bytes, buffer_size));\n CHECK(all_bytes) << \"Failed to grow Bluetooth socket buffer\";\n\n \/\/ bluetooth sockets are non-blocking, so read until we hit an error\n ssize_t bytes_read = read(socket_->fd(), all_bytes + total_bytes_read,\n buffer_size - total_bytes_read);\n errsv = errno;\n if (bytes_read <= 0)\n break;\n\n total_bytes_read += bytes_read;\n }\n\n if (total_bytes_read > 0) {\n success_ = true;\n result_.reset(base::BinaryValue::Create(all_bytes, total_bytes_read));\n } else {\n success_ = (errsv == EAGAIN || errsv == EWOULDBLOCK);\n free(all_bytes);\n }\n\n if (!success_)\n SetError(safe_strerror(errsv));\n}\n\nbool BluetoothReadFunction::Respond() {\n return success_;\n}\n\nbool BluetoothWriteFunction::Prepare() {\n \/\/ TODO(bryeung): update to new-style parameter passing when ArrayBuffer\n \/\/ support is added\n DictionaryValue* socket;\n EXTENSION_FUNCTION_VALIDATE(args_->GetDictionary(0, &socket));\n int socket_id;\n EXTENSION_FUNCTION_VALIDATE(socket->GetInteger(\"id\", &socket_id));\n\n socket_ = GetEventRouter(profile())->GetSocket(socket_id);\n if (socket_.get() == NULL) {\n SetError(kSocketNotFoundError);\n return false;\n }\n\n base::BinaryValue* tmp_data;\n EXTENSION_FUNCTION_VALIDATE(args_->GetBinary(1, &tmp_data));\n data_to_write_ = tmp_data;\n\n success_ = false;\n return socket_.get() != NULL;\n}\n\nvoid BluetoothWriteFunction::Work() {\n DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::IO));\n\n if (socket_.get() == NULL)\n return;\n\n ssize_t bytes_written = write(socket_->fd(),\n data_to_write_->GetBuffer(), data_to_write_->GetSize());\n int errsv = errno;\n\n if (bytes_written > 0) {\n result_.reset(Value::CreateIntegerValue(bytes_written));\n success_ = true;\n } else {\n result_.reset(0);\n success_ = (errsv == EAGAIN || errsv == EWOULDBLOCK);\n }\n\n if (!success_)\n SetError(safe_strerror(errsv));\n}\n\nbool BluetoothWriteFunction::Respond() {\n return success_;\n}\n\n#else\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ NIY stubs\n\/\/ -----------------------------------------------------------------------------\nbool BluetoothIsAvailableFunction::RunImpl() {\n NOTREACHED() << \"Not implemented yet\";\n return false;\n}\n\nbool BluetoothIsPoweredFunction::RunImpl() {\n NOTREACHED() << \"Not implemented yet\";\n return false;\n}\n\nbool BluetoothGetAddressFunction::RunImpl() {\n NOTREACHED() << \"Not implemented yet\";\n return false;\n}\n\nbool BluetoothGetDevicesWithServiceUUIDFunction::RunImpl() {\n NOTREACHED() << \"Not implemented yet\";\n return false;\n}\n\nbool BluetoothGetDevicesWithServiceNameFunction::RunImpl() {\n NOTREACHED() << \"Not implemented yet\";\n return false;\n}\n\nbool BluetoothConnectFunction::RunImpl() {\n NOTREACHED() << \"Not implemented yet\";\n return false;\n}\n\nbool BluetoothDisconnectFunction::RunImpl() {\n NOTREACHED() << \"Not implemented yet\";\n return false;\n}\n\nbool BluetoothReadFunction::Prepare() {\n return true;\n}\n\nvoid BluetoothReadFunction::Work() {\n}\n\nbool BluetoothReadFunction::Respond() {\n NOTREACHED() << \"Not implemented yet\";\n return false;\n}\n\nbool BluetoothWriteFunction::Prepare() {\n return true;\n}\n\nvoid BluetoothWriteFunction::Work() {\n}\n\nbool BluetoothWriteFunction::Respond() {\n NOTREACHED() << \"Not implemented yet\";\n return false;\n}\n\n#endif\n\nBluetoothReadFunction::BluetoothReadFunction() {}\nBluetoothReadFunction::~BluetoothReadFunction() {}\n\nBluetoothWriteFunction::BluetoothWriteFunction() {}\nBluetoothWriteFunction::~BluetoothWriteFunction() {}\n\nbool BluetoothSetOutOfBandPairingDataFunction::RunImpl() {\n NOTREACHED() << \"Not implemented yet\";\n return false;\n}\n\nbool BluetoothGetOutOfBandPairingDataFunction::RunImpl() {\n NOTREACHED() << \"Not implemented yet\";\n return false;\n}\n\n} \/\/ namespace api\n} \/\/ namespace extensions\n<commit_msg>Improve errors for the bluetooth.connect API<commit_after>\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/extensions\/api\/bluetooth\/bluetooth_api.h\"\n\n#include \"base\/utf_string_conversions.h\"\n#include \"chrome\/browser\/extensions\/extension_service.h\"\n#include \"chrome\/browser\/profiles\/profile.h\"\n#include \"chrome\/common\/extensions\/api\/experimental_bluetooth.h\"\n#include \"content\/public\/browser\/browser_thread.h\"\n\n#if defined(OS_CHROMEOS)\n#include \"base\/memory\/ref_counted.h\"\n#include \"base\/safe_strerror_posix.h\"\n#include \"base\/synchronization\/lock.h\"\n#include \"chrome\/browser\/chromeos\/bluetooth\/bluetooth_adapter.h\"\n#include \"chrome\/browser\/chromeos\/bluetooth\/bluetooth_device.h\"\n#include \"chrome\/browser\/chromeos\/bluetooth\/bluetooth_socket.h\"\n#include \"chrome\/browser\/chromeos\/extensions\/bluetooth_event_router.h\"\n\n#include <errno.h>\n\nusing chromeos::BluetoothAdapter;\nusing chromeos::BluetoothDevice;\n\nnamespace {\n\nchromeos::ExtensionBluetoothEventRouter* GetEventRouter(Profile* profile) {\n return profile->GetExtensionService()->bluetooth_event_router();\n}\n\nconst chromeos::BluetoothAdapter* GetAdapter(Profile* profile) {\n return GetEventRouter(profile)->adapter();\n}\n\nchromeos::BluetoothAdapter* GetMutableAdapter(Profile* profile) {\n return GetEventRouter(profile)->GetMutableAdapter();\n}\n\n} \/\/ namespace\n#endif\n\nnamespace {\n\nconst char kFailedToConnect[] = \"Connection failed\";\nconst char kInvalidDevice[] = \"Invalid device\";\nconst char kSocketNotFoundError[] = \"Socket not found: invalid socket id\";\n\n} \/\/ namespace\n\nnamespace Connect = extensions::api::experimental_bluetooth::Connect;\nnamespace Disconnect = extensions::api::experimental_bluetooth::Disconnect;\nnamespace GetDevicesWithServiceName =\n extensions::api::experimental_bluetooth::GetDevicesWithServiceName;\nnamespace GetDevicesWithServiceUUID =\n extensions::api::experimental_bluetooth::GetDevicesWithServiceUUID;\nnamespace Read = extensions::api::experimental_bluetooth::Read;\nnamespace Write = extensions::api::experimental_bluetooth::Write;\n\nnamespace extensions {\nnamespace api {\n\n#if defined(OS_CHROMEOS)\n\nbool BluetoothIsAvailableFunction::RunImpl() {\n result_.reset(Value::CreateBooleanValue(GetAdapter(profile())->IsPresent()));\n return true;\n}\n\nbool BluetoothIsPoweredFunction::RunImpl() {\n result_.reset(Value::CreateBooleanValue(GetAdapter(profile())->IsPowered()));\n return true;\n}\n\nbool BluetoothGetAddressFunction::RunImpl() {\n result_.reset(Value::CreateStringValue(GetAdapter(profile())->address()));\n return true;\n}\n\nbool BluetoothGetDevicesWithServiceUUIDFunction::RunImpl() {\n scoped_ptr<GetDevicesWithServiceUUID::Params> params(\n GetDevicesWithServiceUUID::Params::Create(*args_));\n EXTENSION_FUNCTION_VALIDATE(params.get() != NULL);\n\n const BluetoothAdapter::ConstDeviceList& devices =\n GetAdapter(profile())->GetDevices();\n ListValue* matches = new ListValue;\n for (BluetoothAdapter::ConstDeviceList::const_iterator i =\n devices.begin(); i != devices.end(); ++i) {\n if ((*i)->ProvidesServiceWithUUID(params->uuid)) {\n experimental_bluetooth::Device device;\n device.name = UTF16ToUTF8((*i)->GetName());\n device.address = (*i)->address();\n matches->Append(device.ToValue().release());\n }\n }\n result_.reset(matches);\n\n return true;\n}\n\nBluetoothGetDevicesWithServiceNameFunction::\n BluetoothGetDevicesWithServiceNameFunction() : callbacks_pending_(0) {}\n\nvoid BluetoothGetDevicesWithServiceNameFunction::AddDeviceIfTrue(\n ListValue* list, const BluetoothDevice* device, bool result) {\n DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));\n\n if (result) {\n experimental_bluetooth::Device device_result;\n device_result.name = UTF16ToUTF8(device->GetName());\n device_result.address = device->address();\n list->Append(device_result.ToValue().release());\n }\n\n callbacks_pending_--;\n if (callbacks_pending_ == 0) {\n SendResponse(true);\n Release(); \/\/ Added in RunImpl\n }\n}\n\nbool BluetoothGetDevicesWithServiceNameFunction::RunImpl() {\n DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));\n\n ListValue* matches = new ListValue;\n result_.reset(matches);\n\n BluetoothAdapter::DeviceList devices =\n GetMutableAdapter(profile())->GetDevices();\n if (devices.empty()) {\n SendResponse(true);\n return true;\n }\n\n callbacks_pending_ = devices.size();\n AddRef(); \/\/ Released in AddDeviceIfTrue when callbacks_pending_ == 0\n\n scoped_ptr<GetDevicesWithServiceName::Params> params(\n GetDevicesWithServiceName::Params::Create(*args_));\n EXTENSION_FUNCTION_VALIDATE(params.get() != NULL);\n for (BluetoothAdapter::DeviceList::iterator i = devices.begin();\n i != devices.end(); ++i) {\n (*i)->ProvidesServiceWithName(params->name,\n base::Bind(&BluetoothGetDevicesWithServiceNameFunction::AddDeviceIfTrue,\n this,\n matches,\n *i));\n }\n\n return true;\n}\n\nvoid BluetoothConnectFunction::ConnectToServiceCallback(\n const chromeos::BluetoothDevice* device,\n const std::string& service_uuid,\n scoped_refptr<chromeos::BluetoothSocket> socket) {\n if (socket.get()) {\n int socket_id = GetEventRouter(profile())->RegisterSocket(socket);\n\n experimental_bluetooth::Socket result_socket;\n result_socket.device.address = device->address();\n result_socket.device.name = UTF16ToUTF8(device->GetName());\n result_socket.service_uuid = service_uuid;\n result_socket.id = socket_id;\n result_.reset(result_socket.ToValue().release());\n SendResponse(true);\n } else {\n SetError(kFailedToConnect);\n SendResponse(false);\n }\n\n Release(); \/\/ Added in RunImpl\n}\n\nbool BluetoothConnectFunction::RunImpl() {\n scoped_ptr<Connect::Params> params(Connect::Params::Create(*args_));\n EXTENSION_FUNCTION_VALIDATE(params.get() != NULL);\n\n chromeos::BluetoothDevice* device =\n GetMutableAdapter(profile())->GetDevice(params->device.address);\n if (!device) {\n SendResponse(false);\n SetError(kInvalidDevice);\n return false;\n }\n\n AddRef();\n device->ConnectToService(params->service,\n base::Bind(&BluetoothConnectFunction::ConnectToServiceCallback,\n this,\n device,\n params->service));\n return true;\n}\n\nbool BluetoothDisconnectFunction::RunImpl() {\n scoped_ptr<Disconnect::Params> params(Disconnect::Params::Create(*args_));\n EXTENSION_FUNCTION_VALIDATE(params.get() != NULL);\n return GetEventRouter(profile())->ReleaseSocket(params->socket.id);\n}\n\nbool BluetoothReadFunction::Prepare() {\n scoped_ptr<Read::Params> params(Read::Params::Create(*args_));\n EXTENSION_FUNCTION_VALIDATE(params.get() != NULL);\n\n socket_ = GetEventRouter(profile())->GetSocket(params->socket.id);\n if (socket_.get() == NULL) {\n SetError(kSocketNotFoundError);\n return false;\n }\n\n success_ = false;\n return true;\n}\n\nvoid BluetoothReadFunction::Work() {\n DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::IO));\n CHECK(socket_.get() != NULL);\n\n char* all_bytes = NULL;\n ssize_t buffer_size = 0;\n ssize_t total_bytes_read = 0;\n int errsv;\n while (true) {\n buffer_size += 1024;\n all_bytes = static_cast<char*>(realloc(all_bytes, buffer_size));\n CHECK(all_bytes) << \"Failed to grow Bluetooth socket buffer\";\n\n \/\/ bluetooth sockets are non-blocking, so read until we hit an error\n ssize_t bytes_read = read(socket_->fd(), all_bytes + total_bytes_read,\n buffer_size - total_bytes_read);\n errsv = errno;\n if (bytes_read <= 0)\n break;\n\n total_bytes_read += bytes_read;\n }\n\n if (total_bytes_read > 0) {\n success_ = true;\n result_.reset(base::BinaryValue::Create(all_bytes, total_bytes_read));\n } else {\n success_ = (errsv == EAGAIN || errsv == EWOULDBLOCK);\n free(all_bytes);\n }\n\n if (!success_)\n SetError(safe_strerror(errsv));\n}\n\nbool BluetoothReadFunction::Respond() {\n return success_;\n}\n\nbool BluetoothWriteFunction::Prepare() {\n \/\/ TODO(bryeung): update to new-style parameter passing when ArrayBuffer\n \/\/ support is added\n DictionaryValue* socket;\n EXTENSION_FUNCTION_VALIDATE(args_->GetDictionary(0, &socket));\n int socket_id;\n EXTENSION_FUNCTION_VALIDATE(socket->GetInteger(\"id\", &socket_id));\n\n socket_ = GetEventRouter(profile())->GetSocket(socket_id);\n if (socket_.get() == NULL) {\n SetError(kSocketNotFoundError);\n return false;\n }\n\n base::BinaryValue* tmp_data;\n EXTENSION_FUNCTION_VALIDATE(args_->GetBinary(1, &tmp_data));\n data_to_write_ = tmp_data;\n\n success_ = false;\n return socket_.get() != NULL;\n}\n\nvoid BluetoothWriteFunction::Work() {\n DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::IO));\n\n if (socket_.get() == NULL)\n return;\n\n ssize_t bytes_written = write(socket_->fd(),\n data_to_write_->GetBuffer(), data_to_write_->GetSize());\n int errsv = errno;\n\n if (bytes_written > 0) {\n result_.reset(Value::CreateIntegerValue(bytes_written));\n success_ = true;\n } else {\n result_.reset(0);\n success_ = (errsv == EAGAIN || errsv == EWOULDBLOCK);\n }\n\n if (!success_)\n SetError(safe_strerror(errsv));\n}\n\nbool BluetoothWriteFunction::Respond() {\n return success_;\n}\n\n#else\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ NIY stubs\n\/\/ -----------------------------------------------------------------------------\nbool BluetoothIsAvailableFunction::RunImpl() {\n NOTREACHED() << \"Not implemented yet\";\n return false;\n}\n\nbool BluetoothIsPoweredFunction::RunImpl() {\n NOTREACHED() << \"Not implemented yet\";\n return false;\n}\n\nbool BluetoothGetAddressFunction::RunImpl() {\n NOTREACHED() << \"Not implemented yet\";\n return false;\n}\n\nbool BluetoothGetDevicesWithServiceUUIDFunction::RunImpl() {\n NOTREACHED() << \"Not implemented yet\";\n return false;\n}\n\nbool BluetoothGetDevicesWithServiceNameFunction::RunImpl() {\n NOTREACHED() << \"Not implemented yet\";\n return false;\n}\n\nbool BluetoothConnectFunction::RunImpl() {\n NOTREACHED() << \"Not implemented yet\";\n return false;\n}\n\nbool BluetoothDisconnectFunction::RunImpl() {\n NOTREACHED() << \"Not implemented yet\";\n return false;\n}\n\nbool BluetoothReadFunction::Prepare() {\n return true;\n}\n\nvoid BluetoothReadFunction::Work() {\n}\n\nbool BluetoothReadFunction::Respond() {\n NOTREACHED() << \"Not implemented yet\";\n return false;\n}\n\nbool BluetoothWriteFunction::Prepare() {\n return true;\n}\n\nvoid BluetoothWriteFunction::Work() {\n}\n\nbool BluetoothWriteFunction::Respond() {\n NOTREACHED() << \"Not implemented yet\";\n return false;\n}\n\n#endif\n\nBluetoothReadFunction::BluetoothReadFunction() {}\nBluetoothReadFunction::~BluetoothReadFunction() {}\n\nBluetoothWriteFunction::BluetoothWriteFunction() {}\nBluetoothWriteFunction::~BluetoothWriteFunction() {}\n\nbool BluetoothSetOutOfBandPairingDataFunction::RunImpl() {\n NOTREACHED() << \"Not implemented yet\";\n return false;\n}\n\nbool BluetoothGetOutOfBandPairingDataFunction::RunImpl() {\n NOTREACHED() << \"Not implemented yet\";\n return false;\n}\n\n} \/\/ namespace api\n} \/\/ namespace extensions\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/browser.h\"\n#include \"chrome\/browser\/browser_list.h\"\n#include \"chrome\/browser\/browser_window.h\"\n#include \"chrome\/browser\/extensions\/browser_action_test_util.h\"\n#include \"chrome\/browser\/extensions\/extension_apitest.h\"\n#include \"chrome\/browser\/extensions\/extensions_service.h\"\n#include \"chrome\/browser\/extensions\/user_script_master.h\"\n#include \"chrome\/browser\/profile.h\"\n#include \"chrome\/browser\/tab_contents\/tab_contents.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/common\/url_constants.h\"\n#include \"chrome\/test\/ui_test_utils.h\"\n#include \"net\/base\/mock_host_resolver.h\"\n\nIN_PROC_BROWSER_TEST_F(ExtensionBrowserTest, IncognitoNoScript) {\n host_resolver()->AddRule(\"*\", \"127.0.0.1\");\n ASSERT_TRUE(test_server()->Start());\n\n \/\/ Loads a simple extension which attempts to change the title of every page\n \/\/ that loads to \"modified\".\n ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII(\"api_test\")\n .AppendASCII(\"incognito\").AppendASCII(\"content_scripts\")));\n\n \/\/ Open incognito window and navigate to test page.\n ui_test_utils::OpenURLOffTheRecord(browser()->profile(),\n GURL(\"http:\/\/www.example.com:1337\/files\/extensions\/test_file.html\"));\n Browser* otr_browser = BrowserList::FindBrowserWithType(\n browser()->profile()->GetOffTheRecordProfile(), Browser::TYPE_NORMAL,\n false);\n TabContents* tab = otr_browser->GetSelectedTabContents();\n\n \/\/ Verify the script didn't run.\n bool result = false;\n ASSERT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractBool(\n tab->render_view_host(), L\"\",\n L\"window.domAutomationController.send(document.title == 'Unmodified')\",\n &result));\n EXPECT_TRUE(result);\n}\n\nIN_PROC_BROWSER_TEST_F(ExtensionBrowserTest, IncognitoYesScript) {\n host_resolver()->AddRule(\"*\", \"127.0.0.1\");\n ASSERT_TRUE(test_server()->Start());\n\n \/\/ Load a dummy extension. This just tests that we don't regress a\n \/\/ crash fix when multiple incognito- and non-incognito-enabled extensions\n \/\/ are mixed.\n ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII(\"api_test\")\n .AppendASCII(\"content_scripts\").AppendASCII(\"all_frames\")));\n\n \/\/ Loads a simple extension which attempts to change the title of every page\n \/\/ that loads to \"modified\".\n ASSERT_TRUE(LoadExtensionIncognito(test_data_dir_.AppendASCII(\"api_test\")\n .AppendASCII(\"incognito\").AppendASCII(\"content_scripts\")));\n\n \/\/ Dummy extension #2.\n ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII(\"api_test\")\n .AppendASCII(\"content_scripts\").AppendASCII(\"isolated_world1\")));\n\n \/\/ Open incognito window and navigate to test page.\n ui_test_utils::OpenURLOffTheRecord(browser()->profile(),\n GURL(\"http:\/\/www.example.com:1337\/files\/extensions\/test_file.html\"));\n Browser* otr_browser = BrowserList::FindBrowserWithType(\n browser()->profile()->GetOffTheRecordProfile(), Browser::TYPE_NORMAL,\n false);\n TabContents* tab = otr_browser->GetSelectedTabContents();\n\n \/\/ Verify the script ran.\n bool result = false;\n ASSERT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractBool(\n tab->render_view_host(), L\"\",\n L\"window.domAutomationController.send(document.title == 'modified')\",\n &result));\n EXPECT_TRUE(result);\n}\n\n\/\/ Tests that an extension which is enabled for incognito mode doesn't\n\/\/ accidentially create and incognito profile.\nIN_PROC_BROWSER_TEST_F(ExtensionApiTest, DontCreateIncognitoProfile) {\n ASSERT_FALSE(browser()->profile()->HasOffTheRecordProfile());\n ASSERT_TRUE(\n RunExtensionTestIncognito(\"incognito\/enumerate_tabs\")) << message_;\n ASSERT_FALSE(browser()->profile()->HasOffTheRecordProfile());\n}\n\n\/\/ Tests that the APIs in an incognito-enabled extension work properly.\nIN_PROC_BROWSER_TEST_F(ExtensionApiTest, Incognito) {\n host_resolver()->AddRule(\"*\", \"127.0.0.1\");\n ASSERT_TRUE(test_server()->Start());\n\n ResultCatcher catcher;\n\n \/\/ Open incognito window and navigate to test page.\n ui_test_utils::OpenURLOffTheRecord(browser()->profile(),\n GURL(\"http:\/\/www.example.com:1337\/files\/extensions\/test_file.html\"));\n\n ASSERT_TRUE(LoadExtensionIncognito(test_data_dir_\n .AppendASCII(\"incognito\").AppendASCII(\"apis\")));\n\n EXPECT_TRUE(catcher.GetNextResult()) << catcher.message();\n}\n\n\/\/ Tests that the APIs in an incognito-enabled split-mode extension work\n\/\/ properly.\nIN_PROC_BROWSER_TEST_F(ExtensionApiTest, IncognitoSplitMode) {\n host_resolver()->AddRule(\"*\", \"127.0.0.1\");\n ASSERT_TRUE(test_server()->Start());\n\n \/\/ We need 2 ResultCatchers because we'll be running the same test in both\n \/\/ regular and incognito mode.\n ResultCatcher catcher;\n catcher.RestrictToProfile(browser()->profile());\n ResultCatcher catcher_incognito;\n catcher_incognito.RestrictToProfile(\n browser()->profile()->GetOffTheRecordProfile());\n\n \/\/ Open incognito window and navigate to test page.\n ui_test_utils::OpenURLOffTheRecord(browser()->profile(),\n GURL(\"http:\/\/www.example.com:1337\/files\/extensions\/test_file.html\"));\n\n ASSERT_TRUE(LoadExtensionIncognito(test_data_dir_\n .AppendASCII(\"incognito\").AppendASCII(\"split\")));\n\n EXPECT_TRUE(catcher.GetNextResult()) << catcher.message();\n EXPECT_TRUE(catcher_incognito.GetNextResult()) << catcher.message();\n}\n\n\/\/ Tests that the APIs in an incognito-disabled extension don't see incognito\n\/\/ events or callbacks.\nIN_PROC_BROWSER_TEST_F(ExtensionApiTest, IncognitoDisabled) {\n host_resolver()->AddRule(\"*\", \"127.0.0.1\");\n ASSERT_TRUE(test_server()->Start());\n\n ResultCatcher catcher;\n\n \/\/ Open incognito window and navigate to test page.\n ui_test_utils::OpenURLOffTheRecord(browser()->profile(),\n GURL(\"http:\/\/www.example.com:1337\/files\/extensions\/test_file.html\"));\n\n ASSERT_TRUE(LoadExtension(test_data_dir_\n .AppendASCII(\"incognito\").AppendASCII(\"apis_disabled\")));\n\n EXPECT_TRUE(catcher.GetNextResult()) << catcher.message();\n}\n\n\/\/ Test that opening a popup from an incognito browser window works properly.\nIN_PROC_BROWSER_TEST_F(ExtensionApiTest, IncognitoPopup) {\n host_resolver()->AddRule(\"*\", \"127.0.0.1\");\n ASSERT_TRUE(test_server()->Start());\n\n ResultCatcher catcher;\n\n ASSERT_TRUE(LoadExtensionIncognito(test_data_dir_\n .AppendASCII(\"incognito\").AppendASCII(\"popup\")));\n\n \/\/ Open incognito window and navigate to test page.\n ui_test_utils::OpenURLOffTheRecord(browser()->profile(),\n GURL(\"http:\/\/www.example.com:1337\/files\/extensions\/test_file.html\"));\n Browser* incognito_browser = BrowserList::FindBrowserWithType(\n browser()->profile()->GetOffTheRecordProfile(), Browser::TYPE_NORMAL,\n false);\n\n \/\/ Simulate the incognito's browser action being clicked.\n BrowserActionTestUtil(incognito_browser).Press(0);\n\n EXPECT_TRUE(catcher.GetNextResult()) << catcher.message();\n}\n<commit_msg>Mark ExtensionApiTest.IncognitoSplitMode flaky on Linux.<commit_after>\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/browser.h\"\n#include \"chrome\/browser\/browser_list.h\"\n#include \"chrome\/browser\/browser_window.h\"\n#include \"chrome\/browser\/extensions\/browser_action_test_util.h\"\n#include \"chrome\/browser\/extensions\/extension_apitest.h\"\n#include \"chrome\/browser\/extensions\/extensions_service.h\"\n#include \"chrome\/browser\/extensions\/user_script_master.h\"\n#include \"chrome\/browser\/profile.h\"\n#include \"chrome\/browser\/tab_contents\/tab_contents.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/common\/url_constants.h\"\n#include \"chrome\/test\/ui_test_utils.h\"\n#include \"net\/base\/mock_host_resolver.h\"\n\nIN_PROC_BROWSER_TEST_F(ExtensionBrowserTest, IncognitoNoScript) {\n host_resolver()->AddRule(\"*\", \"127.0.0.1\");\n ASSERT_TRUE(test_server()->Start());\n\n \/\/ Loads a simple extension which attempts to change the title of every page\n \/\/ that loads to \"modified\".\n ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII(\"api_test\")\n .AppendASCII(\"incognito\").AppendASCII(\"content_scripts\")));\n\n \/\/ Open incognito window and navigate to test page.\n ui_test_utils::OpenURLOffTheRecord(browser()->profile(),\n GURL(\"http:\/\/www.example.com:1337\/files\/extensions\/test_file.html\"));\n Browser* otr_browser = BrowserList::FindBrowserWithType(\n browser()->profile()->GetOffTheRecordProfile(), Browser::TYPE_NORMAL,\n false);\n TabContents* tab = otr_browser->GetSelectedTabContents();\n\n \/\/ Verify the script didn't run.\n bool result = false;\n ASSERT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractBool(\n tab->render_view_host(), L\"\",\n L\"window.domAutomationController.send(document.title == 'Unmodified')\",\n &result));\n EXPECT_TRUE(result);\n}\n\nIN_PROC_BROWSER_TEST_F(ExtensionBrowserTest, IncognitoYesScript) {\n host_resolver()->AddRule(\"*\", \"127.0.0.1\");\n ASSERT_TRUE(test_server()->Start());\n\n \/\/ Load a dummy extension. This just tests that we don't regress a\n \/\/ crash fix when multiple incognito- and non-incognito-enabled extensions\n \/\/ are mixed.\n ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII(\"api_test\")\n .AppendASCII(\"content_scripts\").AppendASCII(\"all_frames\")));\n\n \/\/ Loads a simple extension which attempts to change the title of every page\n \/\/ that loads to \"modified\".\n ASSERT_TRUE(LoadExtensionIncognito(test_data_dir_.AppendASCII(\"api_test\")\n .AppendASCII(\"incognito\").AppendASCII(\"content_scripts\")));\n\n \/\/ Dummy extension #2.\n ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII(\"api_test\")\n .AppendASCII(\"content_scripts\").AppendASCII(\"isolated_world1\")));\n\n \/\/ Open incognito window and navigate to test page.\n ui_test_utils::OpenURLOffTheRecord(browser()->profile(),\n GURL(\"http:\/\/www.example.com:1337\/files\/extensions\/test_file.html\"));\n Browser* otr_browser = BrowserList::FindBrowserWithType(\n browser()->profile()->GetOffTheRecordProfile(), Browser::TYPE_NORMAL,\n false);\n TabContents* tab = otr_browser->GetSelectedTabContents();\n\n \/\/ Verify the script ran.\n bool result = false;\n ASSERT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractBool(\n tab->render_view_host(), L\"\",\n L\"window.domAutomationController.send(document.title == 'modified')\",\n &result));\n EXPECT_TRUE(result);\n}\n\n\/\/ Tests that an extension which is enabled for incognito mode doesn't\n\/\/ accidentially create and incognito profile.\nIN_PROC_BROWSER_TEST_F(ExtensionApiTest, DontCreateIncognitoProfile) {\n ASSERT_FALSE(browser()->profile()->HasOffTheRecordProfile());\n ASSERT_TRUE(\n RunExtensionTestIncognito(\"incognito\/enumerate_tabs\")) << message_;\n ASSERT_FALSE(browser()->profile()->HasOffTheRecordProfile());\n}\n\n\/\/ Tests that the APIs in an incognito-enabled extension work properly.\nIN_PROC_BROWSER_TEST_F(ExtensionApiTest, Incognito) {\n host_resolver()->AddRule(\"*\", \"127.0.0.1\");\n ASSERT_TRUE(test_server()->Start());\n\n ResultCatcher catcher;\n\n \/\/ Open incognito window and navigate to test page.\n ui_test_utils::OpenURLOffTheRecord(browser()->profile(),\n GURL(\"http:\/\/www.example.com:1337\/files\/extensions\/test_file.html\"));\n\n ASSERT_TRUE(LoadExtensionIncognito(test_data_dir_\n .AppendASCII(\"incognito\").AppendASCII(\"apis\")));\n\n EXPECT_TRUE(catcher.GetNextResult()) << catcher.message();\n}\n\n\/\/ Crashes flakily on Linux. http:\/\/crbug.com\/58270\n#if defined(OS_LINUX)\n#define MAYBE_IncognitoSplitMode FLAKY_IncognitoSplitMode\n#else\n#define MAYBE_IncognitoSplitMode IncognitoSplitMode\n#endif\n\n\/\/ Tests that the APIs in an incognito-enabled split-mode extension work\n\/\/ properly.\nIN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_IncognitoSplitMode) {\n host_resolver()->AddRule(\"*\", \"127.0.0.1\");\n ASSERT_TRUE(test_server()->Start());\n\n \/\/ We need 2 ResultCatchers because we'll be running the same test in both\n \/\/ regular and incognito mode.\n ResultCatcher catcher;\n catcher.RestrictToProfile(browser()->profile());\n ResultCatcher catcher_incognito;\n catcher_incognito.RestrictToProfile(\n browser()->profile()->GetOffTheRecordProfile());\n\n \/\/ Open incognito window and navigate to test page.\n ui_test_utils::OpenURLOffTheRecord(browser()->profile(),\n GURL(\"http:\/\/www.example.com:1337\/files\/extensions\/test_file.html\"));\n\n ASSERT_TRUE(LoadExtensionIncognito(test_data_dir_\n .AppendASCII(\"incognito\").AppendASCII(\"split\")));\n\n EXPECT_TRUE(catcher.GetNextResult()) << catcher.message();\n EXPECT_TRUE(catcher_incognito.GetNextResult()) << catcher.message();\n}\n\n\/\/ Tests that the APIs in an incognito-disabled extension don't see incognito\n\/\/ events or callbacks.\nIN_PROC_BROWSER_TEST_F(ExtensionApiTest, IncognitoDisabled) {\n host_resolver()->AddRule(\"*\", \"127.0.0.1\");\n ASSERT_TRUE(test_server()->Start());\n\n ResultCatcher catcher;\n\n \/\/ Open incognito window and navigate to test page.\n ui_test_utils::OpenURLOffTheRecord(browser()->profile(),\n GURL(\"http:\/\/www.example.com:1337\/files\/extensions\/test_file.html\"));\n\n ASSERT_TRUE(LoadExtension(test_data_dir_\n .AppendASCII(\"incognito\").AppendASCII(\"apis_disabled\")));\n\n EXPECT_TRUE(catcher.GetNextResult()) << catcher.message();\n}\n\n\/\/ Test that opening a popup from an incognito browser window works properly.\nIN_PROC_BROWSER_TEST_F(ExtensionApiTest, IncognitoPopup) {\n host_resolver()->AddRule(\"*\", \"127.0.0.1\");\n ASSERT_TRUE(test_server()->Start());\n\n ResultCatcher catcher;\n\n ASSERT_TRUE(LoadExtensionIncognito(test_data_dir_\n .AppendASCII(\"incognito\").AppendASCII(\"popup\")));\n\n \/\/ Open incognito window and navigate to test page.\n ui_test_utils::OpenURLOffTheRecord(browser()->profile(),\n GURL(\"http:\/\/www.example.com:1337\/files\/extensions\/test_file.html\"));\n Browser* incognito_browser = BrowserList::FindBrowserWithType(\n browser()->profile()->GetOffTheRecordProfile(), Browser::TYPE_NORMAL,\n false);\n\n \/\/ Simulate the incognito's browser action being clicked.\n BrowserActionTestUtil(incognito_browser).Press(0);\n\n EXPECT_TRUE(catcher.GetNextResult()) << catcher.message();\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/ui\/views\/extensions\/shell_window_views.h\"\n\n#include \"base\/utf_string_conversions.h\"\n#include \"chrome\/browser\/extensions\/extension_host.h\"\n#include \"chrome\/common\/extensions\/extension.h\"\n#include \"ui\/views\/widget\/widget.h\"\n\nShellWindowViews::ShellWindowViews(ExtensionHost* host)\n : ShellWindow(host) {\n host_->view()->SetContainer(this);\n window_ = new views::Widget;\n views::Widget::InitParams params(views::Widget::InitParams::TYPE_WINDOW);\n params.delegate = this;\n gfx::Rect bounds(0, 0, 512, 384);\n params.bounds = bounds;\n window_->Init(params);\n window_->Show();\n}\n\nShellWindowViews::~ShellWindowViews() {\n}\n\nvoid ShellWindowViews::Close() {\n window_->Close();\n}\n\nvoid ShellWindowViews::DeleteDelegate() {\n delete this;\n}\n\nbool ShellWindowViews::CanResize() const {\n return true;\n}\n\nviews::View* ShellWindowViews::GetContentsView() {\n return host_->view();\n}\n\nstring16 ShellWindowViews::GetWindowTitle() const {\n return UTF8ToUTF16(host_->extension()->name());\n}\n\nviews::Widget* ShellWindowViews::GetWidget() {\n return window_;\n}\n\nconst views::Widget* ShellWindowViews::GetWidget() const {\n return window_;\n}\n\n\/\/ static\nShellWindow* ShellWindow::CreateShellWindow(ExtensionHost* host) {\n return new ShellWindowViews(host);\n}\n<commit_msg>Set windows AppId (for taskbar) for platform apps.<commit_after>\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/ui\/views\/extensions\/shell_window_views.h\"\n\n#include \"base\/utf_string_conversions.h\"\n#include \"chrome\/browser\/extensions\/extension_host.h\"\n#include \"chrome\/common\/extensions\/extension.h\"\n#include \"ui\/views\/widget\/widget.h\"\n\n#if defined(OS_WIN)\n#include \"chrome\/browser\/shell_integration.h\"\n#include \"chrome\/browser\/web_applications\/web_app.h\"\n#include \"ui\/base\/win\/shell.h\"\n#endif \/\/ OS_WIN\n\nShellWindowViews::ShellWindowViews(ExtensionHost* host)\n : ShellWindow(host) {\n host_->view()->SetContainer(this);\n window_ = new views::Widget;\n views::Widget::InitParams params(views::Widget::InitParams::TYPE_WINDOW);\n params.delegate = this;\n gfx::Rect bounds(0, 0, 512, 384);\n params.bounds = bounds;\n window_->Init(params);\n#if defined(OS_WIN)\n std::string app_name = web_app::GenerateApplicationNameFromExtensionId(\n host_->extension()->id());\n ui::win::SetAppIdForWindow(\n ShellIntegration::GetAppId(UTF8ToWide(app_name),\n host_->profile()->GetPath()),\n GetWidget()->GetTopLevelWidget()->GetNativeWindow());\n#endif \/\/ OS_WIN\n window_->Show();\n}\n\nShellWindowViews::~ShellWindowViews() {\n}\n\nvoid ShellWindowViews::Close() {\n window_->Close();\n}\n\nvoid ShellWindowViews::DeleteDelegate() {\n delete this;\n}\n\nbool ShellWindowViews::CanResize() const {\n return true;\n}\n\nviews::View* ShellWindowViews::GetContentsView() {\n return host_->view();\n}\n\nstring16 ShellWindowViews::GetWindowTitle() const {\n return UTF8ToUTF16(host_->extension()->name());\n}\n\nviews::Widget* ShellWindowViews::GetWidget() {\n return window_;\n}\n\nconst views::Widget* ShellWindowViews::GetWidget() const {\n return window_;\n}\n\n\/\/ static\nShellWindow* ShellWindow::CreateShellWindow(ExtensionHost* host) {\n return new ShellWindowViews(host);\n}\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2008 by Sun Microsystems, Inc.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: binaryreader.hxx,v $\n * $Revision: 1.7 $\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * <http:\/\/www.openoffice.org\/license.html>\n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n#ifndef CONFIGMGR_BINARYREADER_HXX\n#define CONFIGMGR_BINARYREADER_HXX\n\n#include <rtl\/ustring.hxx>\n#include <osl\/file.hxx>\n#include <com\/sun\/star\/uno\/Any.hxx>\n#include <com\/sun\/star\/io\/IOException.hpp>\n#include <com\/sun\/star\/lang\/XMultiServiceFactory.hpp>\n#include <com\/sun\/star\/io\/XDataInputStream.hpp>\n\nnamespace configmgr\n{\n \/\/ -----------------------------------------------------------------------------\n namespace backend\n {\n namespace css = com::sun::star;\n\n namespace io = css::io;\n namespace uno = css::uno;\n namespace lang = css::lang;\n\n typedef uno::Reference<lang::XMultiServiceFactory> MultiServiceFactory;\n \/\/ -----------------------------------------------------------------------------\n class BinaryReader\n {\n rtl::OUString m_sFileURL;\n\n uno::Reference<io::XDataInputStream> m_xDataInputStream;\n public:\n explicit BinaryReader (rtl::OUString const & _sFileURL)\n : m_sFileURL(_sFileURL)\n {}\n\n ~BinaryReader()\n {}\n\n public:\n bool open() SAL_THROW( (io::IOException, uno::RuntimeException) );\n void reopen() SAL_THROW( (io::IOException, uno::RuntimeException) );\n void close() SAL_THROW( (io::IOException, uno::RuntimeException) );\n\n typedef uno::Sequence< sal_Int8 > Binary;\n typedef uno::Sequence< rtl::OUString > StringList;\n\n void read(sal_Bool &_nValue) SAL_THROW( (io::IOException, uno::RuntimeException) );\n void read(sal_Int8 &_nValue) SAL_THROW( (io::IOException, uno::RuntimeException) );\n void read(sal_Int16 &_nValue) SAL_THROW( (io::IOException, uno::RuntimeException) );\n void read(sal_Int32 &_nValue) SAL_THROW( (io::IOException, uno::RuntimeException) );\n void read(sal_Int64 &_nValue) SAL_THROW( (io::IOException, uno::RuntimeException) );\n void read(double &_nValue) SAL_THROW( (io::IOException, uno::RuntimeException) );\n void read(rtl::OUString& _aStr) SAL_THROW( (io::IOException, uno::RuntimeException) );\n void read(Binary &_aValue) SAL_THROW( (io::IOException, uno::RuntimeException) );\n void read(StringList &_aValue) SAL_THROW( (io::IOException, uno::RuntimeException) );\n\n private:\n inline uno::Reference<io::XDataInputStream> getDataInputStream();\n };\n \/\/ --------------------------------------------------------------------------\n\n bool readSequenceValue (\n BinaryReader & _rReader,\n uno::Any & _aValue,\n uno::Type const & _aElementType) SAL_THROW( (io::IOException, uno::RuntimeException) );\n\n \/\/ --------------------------------------------------------------------------\n }\n}\n#endif\n<commit_msg>INTEGRATION: CWS sb88 (1.7.10); FILE MERGED 2008\/06\/03 15:29:46 sb 1.7.10.1: #i89553 applied patch by cmc<commit_after>\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2008 by Sun Microsystems, Inc.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: binaryreader.hxx,v $\n * $Revision: 1.8 $\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * <http:\/\/www.openoffice.org\/license.html>\n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n#ifndef CONFIGMGR_BINARYREADER_HXX\n#define CONFIGMGR_BINARYREADER_HXX\n\n#include <rtl\/ustring.hxx>\n#include <osl\/file.hxx>\n#include <com\/sun\/star\/uno\/Any.hxx>\n#include <com\/sun\/star\/io\/IOException.hpp>\n#include <com\/sun\/star\/lang\/XMultiServiceFactory.hpp>\n#include <com\/sun\/star\/io\/XDataInputStream.hpp>\n\nnamespace configmgr\n{\n \/\/ -----------------------------------------------------------------------------\n namespace backend\n {\n namespace css = com::sun::star;\n\n namespace io = css::io;\n namespace uno = css::uno;\n namespace lang = css::lang;\n\n typedef uno::Reference<lang::XMultiServiceFactory> MultiServiceFactory;\n \/\/ -----------------------------------------------------------------------------\n class BinaryReader\n {\n rtl::OUString m_sFileURL;\n\n uno::Reference<io::XDataInputStream> m_xDataInputStream;\n public:\n explicit BinaryReader (rtl::OUString const & _sFileURL)\n : m_sFileURL(_sFileURL)\n {}\n\n ~BinaryReader()\n {}\n\n public:\n bool open() SAL_THROW( (io::IOException, uno::RuntimeException) );\n\n typedef uno::Sequence< sal_Int8 > Binary;\n typedef uno::Sequence< rtl::OUString > StringList;\n\n void read(sal_Bool &_nValue) SAL_THROW( (io::IOException, uno::RuntimeException) );\n void read(sal_Int8 &_nValue) SAL_THROW( (io::IOException, uno::RuntimeException) );\n void read(sal_Int16 &_nValue) SAL_THROW( (io::IOException, uno::RuntimeException) );\n void read(sal_Int32 &_nValue) SAL_THROW( (io::IOException, uno::RuntimeException) );\n void read(sal_Int64 &_nValue) SAL_THROW( (io::IOException, uno::RuntimeException) );\n void read(double &_nValue) SAL_THROW( (io::IOException, uno::RuntimeException) );\n void read(rtl::OUString& _aStr) SAL_THROW( (io::IOException, uno::RuntimeException) );\n void read(Binary &_aValue) SAL_THROW( (io::IOException, uno::RuntimeException) );\n void read(StringList &_aValue) SAL_THROW( (io::IOException, uno::RuntimeException) );\n\n private:\n inline uno::Reference<io::XDataInputStream> getDataInputStream();\n };\n \/\/ --------------------------------------------------------------------------\n\n bool readSequenceValue (\n BinaryReader & _rReader,\n uno::Any & _aValue,\n uno::Type const & _aElementType) SAL_THROW( (io::IOException, uno::RuntimeException) );\n\n \/\/ --------------------------------------------------------------------------\n }\n}\n#endif\n<|endoftext|>"} {"text":"<commit_before>#include \"wm.hpp\"\n#include \"output.hpp\"\n#include \"view.hpp\"\n#include \"debug.hpp\"\n#include \"core.hpp\"\n#include \"workspace-manager.hpp\"\n\n#include \"..\/view\/xdg-shell.hpp\"\n#include \"..\/view\/xdg-shell-v6.hpp\"\n\n#include <linux\/input.h>\n#include \"signal-definitions.hpp\"\n\nvoid wayfire_exit::init(wayfire_config*)\n{\n key = [](uint32_t key)\n {\n wl_display_terminate(core->display);\n };\n\n output->add_key(new_static_option(\"<ctrl> <alt> KEY_BACKSPACE\"), &key);\n}\n\nvoid wayfire_close::init(wayfire_config *config)\n{\n grab_interface->abilities_mask = WF_ABILITY_GRAB_INPUT;\n auto key = config->get_section(\"core\")\n ->get_option(\"close_top_view\", \"<super> KEY_Q | <alt> KEY_FN_F4\");\n\n callback = [=] (wf_activator_source, uint32_t)\n {\n if (!output->activate_plugin(grab_interface))\n return;\n\n output->deactivate_plugin(grab_interface);\n auto view = output->get_active_view();\n if (view && view->role == WF_VIEW_ROLE_TOPLEVEL) view->close();\n };\n\n output->add_activator(key, &callback);\n}\n\nvoid wayfire_focus::init(wayfire_config *)\n{\n grab_interface->name = \"_wf_focus\";\n grab_interface->abilities_mask = WF_ABILITY_CHANGE_VIEW_GEOMETRY;\n\n on_button = [=] (uint32_t button, int x, int y) {\n this->check_focus_surface(core->get_cursor_focus());\n };\n output->add_button(new_static_option(\"BTN_LEFT\"), &on_button);\n\n on_touch = [=] (int x, int y) {\n this->check_focus_surface(core->get_touch_focus());\n };\n output->add_touch(new_static_option(\"\"), &on_touch);\n\n on_view_disappear = [=] (signal_data *data) {\n set_last_focus(nullptr);\n };\n\n on_view_output_change = [=] (signal_data *data)\n {\n if (get_signaled_output(data) != this->output)\n send_done(last_focus); \/\/ will also reset last_focus\n };\n}\n\nvoid wayfire_focus::check_focus_surface(wayfire_surface_t* focus)\n{\n \/* Find the main view *\/\n auto main_surface = focus ? focus->get_main_surface() : nullptr;\n auto view = main_surface ? core->find_view(main_surface) : nullptr;\n\n \/* Close popups from the lastly focused view *\/\n if (last_focus != view)\n send_done(last_focus);\n\n if (!view || !view->is_mapped() || !output->activate_plugin(grab_interface))\n return;\n\n output->deactivate_plugin(grab_interface);\n view->get_output()->focus_view(view);\n set_last_focus(view);\n}\n\nvoid wayfire_focus::send_done(wayfire_view view)\n{\n if (!last_focus)\n return;\n\n std::vector<wayfire_xdg_popup*> popups;\n std::vector<wayfire_xdg6_popup*> popups_v6;\n\n \/* Do not send done while running *\/\n last_focus->for_each_surface([&] (wayfire_surface_t* surface, int, int)\n {\n auto popup = dynamic_cast<wayfire_xdg_popup*> (surface);\n auto popup_v6 = dynamic_cast<wayfire_xdg6_popup*> (surface);\n\n if (popup)\n popups.push_back(popup);\n if (popup_v6)\n popups_v6.push_back(popup_v6);\n });\n\n for (auto popup : popups)\n popup->send_done();\n for (auto popup : popups_v6)\n popup->send_done();\n\n set_last_focus(nullptr);\n}\n\nvoid wayfire_focus::set_last_focus(wayfire_view view)\n{\n if (last_focus)\n {\n last_focus->disconnect_signal(\"disappeared\", &on_view_disappear);\n last_focus->disconnect_signal(\"set-output\", &on_view_output_change);\n }\n\n last_focus = view;\n if (last_focus)\n {\n last_focus->connect_signal(\"disappeared\", &on_view_disappear);\n last_focus->connect_signal(\"set-output\", &on_view_output_change);\n }\n}\n\nvoid wayfire_handle_focus_parent::focus_view(wayfire_view view)\n{\n last_view = view;\n view->get_output()->bring_to_front(view);\n for (auto child : view->children)\n focus_view(child);\n}\n\nvoid wayfire_handle_focus_parent::init(wayfire_config*)\n{\n focus_event = [&] (signal_data *data)\n {\n auto view = get_signaled_view(data);\n if (!view || intercept_recursion)\n return;\n\n\n auto to_focus = view;\n while(to_focus->parent)\n to_focus = to_focus->parent;\n\n focus_view(to_focus);\n\n \/* because output->focus_view() will fire focus-view signal again,\n * we use this flag to know that this is happening and don't fall\n * into the depths of the infinite recursion *\/\n intercept_recursion = true;\n output->focus_view(last_view);\n intercept_recursion = false;\n\n \/* free shared_ptr reference *\/\n last_view.reset();\n };\n output->connect_signal(\"focus-view\", &focus_event);\n}\n<commit_msg>wm: do not allow closing the compositor if output is inhibited<commit_after>#include \"wm.hpp\"\n#include \"output.hpp\"\n#include \"view.hpp\"\n#include \"debug.hpp\"\n#include \"core.hpp\"\n#include \"workspace-manager.hpp\"\n\n#include \"..\/view\/xdg-shell.hpp\"\n#include \"..\/view\/xdg-shell-v6.hpp\"\n#include \"seat\/input-inhibit.hpp\"\n\n#include <linux\/input.h>\n#include \"signal-definitions.hpp\"\n\nvoid wayfire_exit::init(wayfire_config*)\n{\n key = [](uint32_t key)\n {\n if (is_output_inhibited(core->get_active_output()))\n return;\n\n wl_display_terminate(core->display);\n };\n\n output->add_key(new_static_option(\"<ctrl> <alt> KEY_BACKSPACE\"), &key);\n}\n\nvoid wayfire_close::init(wayfire_config *config)\n{\n grab_interface->abilities_mask = WF_ABILITY_GRAB_INPUT;\n auto key = config->get_section(\"core\")\n ->get_option(\"close_top_view\", \"<super> KEY_Q | <alt> KEY_FN_F4\");\n\n callback = [=] (wf_activator_source, uint32_t)\n {\n if (!output->activate_plugin(grab_interface))\n return;\n\n output->deactivate_plugin(grab_interface);\n auto view = output->get_active_view();\n if (view && view->role == WF_VIEW_ROLE_TOPLEVEL) view->close();\n };\n\n output->add_activator(key, &callback);\n}\n\nvoid wayfire_focus::init(wayfire_config *)\n{\n grab_interface->name = \"_wf_focus\";\n grab_interface->abilities_mask = WF_ABILITY_CHANGE_VIEW_GEOMETRY;\n\n on_button = [=] (uint32_t button, int x, int y) {\n this->check_focus_surface(core->get_cursor_focus());\n };\n output->add_button(new_static_option(\"BTN_LEFT\"), &on_button);\n\n on_touch = [=] (int x, int y) {\n this->check_focus_surface(core->get_touch_focus());\n };\n output->add_touch(new_static_option(\"\"), &on_touch);\n\n on_view_disappear = [=] (signal_data *data) {\n set_last_focus(nullptr);\n };\n\n on_view_output_change = [=] (signal_data *data)\n {\n if (get_signaled_output(data) != this->output)\n send_done(last_focus); \/\/ will also reset last_focus\n };\n}\n\nvoid wayfire_focus::check_focus_surface(wayfire_surface_t* focus)\n{\n \/* Find the main view *\/\n auto main_surface = focus ? focus->get_main_surface() : nullptr;\n auto view = main_surface ? core->find_view(main_surface) : nullptr;\n\n \/* Close popups from the lastly focused view *\/\n if (last_focus != view)\n send_done(last_focus);\n\n if (!view || !view->is_mapped() || !output->activate_plugin(grab_interface))\n return;\n\n output->deactivate_plugin(grab_interface);\n view->get_output()->focus_view(view);\n set_last_focus(view);\n}\n\nvoid wayfire_focus::send_done(wayfire_view view)\n{\n if (!last_focus)\n return;\n\n std::vector<wayfire_xdg_popup*> popups;\n std::vector<wayfire_xdg6_popup*> popups_v6;\n\n \/* Do not send done while running *\/\n last_focus->for_each_surface([&] (wayfire_surface_t* surface, int, int)\n {\n auto popup = dynamic_cast<wayfire_xdg_popup*> (surface);\n auto popup_v6 = dynamic_cast<wayfire_xdg6_popup*> (surface);\n\n if (popup)\n popups.push_back(popup);\n if (popup_v6)\n popups_v6.push_back(popup_v6);\n });\n\n for (auto popup : popups)\n popup->send_done();\n for (auto popup : popups_v6)\n popup->send_done();\n\n set_last_focus(nullptr);\n}\n\nvoid wayfire_focus::set_last_focus(wayfire_view view)\n{\n if (last_focus)\n {\n last_focus->disconnect_signal(\"disappeared\", &on_view_disappear);\n last_focus->disconnect_signal(\"set-output\", &on_view_output_change);\n }\n\n last_focus = view;\n if (last_focus)\n {\n last_focus->connect_signal(\"disappeared\", &on_view_disappear);\n last_focus->connect_signal(\"set-output\", &on_view_output_change);\n }\n}\n\nvoid wayfire_handle_focus_parent::focus_view(wayfire_view view)\n{\n last_view = view;\n view->get_output()->bring_to_front(view);\n for (auto child : view->children)\n focus_view(child);\n}\n\nvoid wayfire_handle_focus_parent::init(wayfire_config*)\n{\n focus_event = [&] (signal_data *data)\n {\n auto view = get_signaled_view(data);\n if (!view || intercept_recursion)\n return;\n\n\n auto to_focus = view;\n while(to_focus->parent)\n to_focus = to_focus->parent;\n\n focus_view(to_focus);\n\n \/* because output->focus_view() will fire focus-view signal again,\n * we use this flag to know that this is happening and don't fall\n * into the depths of the infinite recursion *\/\n intercept_recursion = true;\n output->focus_view(last_view);\n intercept_recursion = false;\n\n \/* free shared_ptr reference *\/\n last_view.reset();\n };\n output->connect_signal(\"focus-view\", &focus_event);\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"wm.hpp\"\n#include \"wayfire\/output.hpp\"\n#include \"wayfire\/view.hpp\"\n#include \"wayfire\/core.hpp\"\n#include \"wayfire\/workspace-manager.hpp\"\n#include \"wayfire\/output-layout.hpp\"\n\n#include <wayfire\/util\/log.hpp>\n#include <wayfire\/nonstd\/wlroots-full.hpp>\n\n#include \"..\/output\/output-impl.hpp\"\n#include \"wayfire\/signal-definitions.hpp\"\n\n#include <linux\/input-event-codes.h>\n\nstatic void idle_shutdown(void *data)\n{\n wf::get_core().shutdown();\n}\n\nvoid wayfire_exit::init()\n{\n key = [] (const wf::keybinding_t&)\n {\n auto output_impl =\n static_cast<wf::output_impl_t*>(wf::get_core().get_active_output());\n if (output_impl->is_inhibited())\n {\n return false;\n }\n\n idle_shutdown(nullptr);\n\n return true;\n };\n\n \/\/ make sure to shut down wayfire if destroying the last\n \/\/ nested backend output\n on_output_removed.set_callback([=] (wf::signal_data_t *data)\n {\n auto output = wf::get_signaled_output(data);\n\n bool is_nested_compositor = wlr_output_is_wl(output->handle);\n#if WLR_HAS_X11_BACKEND\n is_nested_compositor |= wlr_output_is_x11(output->handle);\n#endif\n\n int cnt_other_outputs = 0;\n for (auto& wo : wf::get_core().output_layout->get_outputs())\n {\n if ((wo != output) && !wlr_output_is_noop(wo->handle))\n {\n ++cnt_other_outputs;\n }\n }\n\n if (is_nested_compositor && (cnt_other_outputs == 0))\n {\n wl_event_loop_add_idle(wf::get_core().ev_loop, idle_shutdown, nullptr);\n }\n });\n\n output->connect_signal(\"pre-remove\", &on_output_removed);\n output->add_key(wf::create_option_string<wf::keybinding_t>(\n \"<ctrl> <alt> KEY_BACKSPACE\"), &key);\n}\n\nvoid wayfire_exit::fini()\n{\n output->rem_binding(&key);\n}\n\nvoid wayfire_close::init()\n{\n grab_interface->capabilities = wf::CAPABILITY_GRAB_INPUT;\n wf::option_wrapper_t<wf::activatorbinding_t> key(\"core\/close_top_view\");\n callback = [=] (const wf::activator_data_t& ev)\n {\n if (!output->activate_plugin(grab_interface))\n {\n return false;\n }\n\n output->deactivate_plugin(grab_interface);\n auto view = output->get_active_view();\n if (view && (view->role == wf::VIEW_ROLE_TOPLEVEL))\n {\n view->close();\n }\n\n return true;\n };\n\n output->add_activator(key, &callback);\n}\n\nvoid wayfire_close::fini()\n{\n output->rem_binding(&callback);\n}\n\nvoid wayfire_focus::init()\n{\n grab_interface->name = \"_wf_focus\";\n grab_interface->capabilities = wf::CAPABILITY_MANAGE_DESKTOP;\n\n on_wm_focus_request = [=] (wf::signal_data_t *data)\n {\n auto ev = static_cast<wm_focus_request*>(data);\n check_focus_surface(ev->surface);\n };\n output->connect_signal(\"wm-focus-request\", &on_wm_focus_request);\n\n on_button.set_callback([=] (wf::signal_data_t *data)\n {\n auto ev = static_cast<\n wf::input_event_signal<wlr_event_pointer_button>*>(data);\n\n if (ev->event->state != WLR_BUTTON_PRESSED)\n {\n return;\n }\n\n \/* focuse_btns->get_value() does not compile *\/\n wf::option_sptr_t<wf::activatorbinding_t> tmp = focus_btns;\n if ((!focus_modifiers && wf::get_core().get_keyboard_modifiers()) ||\n !tmp->get_value().has_match(wf::buttonbinding_t(0, ev->event->button)))\n {\n return;\n }\n\n this->check_focus_surface(wf::get_core().get_cursor_focus());\n });\n wf::get_core().connect_signal(\"pointer_button\", &on_button);\n\n \/\/ build touch gesture\n auto on_tap = std::make_unique<wf::touch::touch_action_t>(1, true);\n std::vector<std::unique_ptr<wf::touch::gesture_action_t>> actions;\n actions.emplace_back(std::move(on_tap));\n const auto& on_tap_action = [this] ()\n {\n if (wf::get_core().get_active_output() == this->output)\n {\n this->check_focus_surface(wf::get_core().get_touch_focus());\n }\n };\n\n this->tap_gesture =\n std::make_unique<wf::touch::gesture_t>(std::move(actions), on_tap_action);\n wf::get_core().add_touch_gesture(tap_gesture);\n}\n\nvoid wayfire_focus::check_focus_surface(wf::surface_interface_t *focus)\n{\n \/* Find the main view *\/\n auto main_surface = focus ? focus->get_main_surface() : nullptr;\n auto view = dynamic_cast<wf::view_interface_t*>(main_surface);\n\n if (!view || !view->is_mapped() || !view->get_keyboard_focus_surface() ||\n !output->activate_plugin(grab_interface))\n {\n return;\n }\n\n output->deactivate_plugin(grab_interface);\n view->get_output()->focus_view(view->self(), true);\n}\n\nvoid wayfire_focus::fini()\n{\n output->rem_binding(&on_button);\n wf::get_core().rem_touch_gesture(tap_gesture);\n output->disconnect_signal(\"wm-focus-request\", &on_wm_focus_request);\n}\n<commit_msg>core: bring to front on click (#1024)<commit_after>#include \"wm.hpp\"\n#include \"wayfire\/output.hpp\"\n#include \"wayfire\/view.hpp\"\n#include \"wayfire\/core.hpp\"\n#include \"wayfire\/workspace-manager.hpp\"\n#include \"wayfire\/output-layout.hpp\"\n\n#include <wayfire\/util\/log.hpp>\n#include <wayfire\/nonstd\/wlroots-full.hpp>\n\n#include \"..\/output\/output-impl.hpp\"\n#include \"wayfire\/signal-definitions.hpp\"\n\n#include <linux\/input-event-codes.h>\n\nstatic void idle_shutdown(void *data)\n{\n wf::get_core().shutdown();\n}\n\nvoid wayfire_exit::init()\n{\n key = [] (const wf::keybinding_t&)\n {\n auto output_impl =\n static_cast<wf::output_impl_t*>(wf::get_core().get_active_output());\n if (output_impl->is_inhibited())\n {\n return false;\n }\n\n idle_shutdown(nullptr);\n\n return true;\n };\n\n \/\/ make sure to shut down wayfire if destroying the last\n \/\/ nested backend output\n on_output_removed.set_callback([=] (wf::signal_data_t *data)\n {\n auto output = wf::get_signaled_output(data);\n\n bool is_nested_compositor = wlr_output_is_wl(output->handle);\n#if WLR_HAS_X11_BACKEND\n is_nested_compositor |= wlr_output_is_x11(output->handle);\n#endif\n\n int cnt_other_outputs = 0;\n for (auto& wo : wf::get_core().output_layout->get_outputs())\n {\n if ((wo != output) && !wlr_output_is_noop(wo->handle))\n {\n ++cnt_other_outputs;\n }\n }\n\n if (is_nested_compositor && (cnt_other_outputs == 0))\n {\n wl_event_loop_add_idle(wf::get_core().ev_loop, idle_shutdown, nullptr);\n }\n });\n\n output->connect_signal(\"pre-remove\", &on_output_removed);\n output->add_key(wf::create_option_string<wf::keybinding_t>(\n \"<ctrl> <alt> KEY_BACKSPACE\"), &key);\n}\n\nvoid wayfire_exit::fini()\n{\n output->rem_binding(&key);\n}\n\nvoid wayfire_close::init()\n{\n grab_interface->capabilities = wf::CAPABILITY_GRAB_INPUT;\n wf::option_wrapper_t<wf::activatorbinding_t> key(\"core\/close_top_view\");\n callback = [=] (const wf::activator_data_t& ev)\n {\n if (!output->activate_plugin(grab_interface))\n {\n return false;\n }\n\n output->deactivate_plugin(grab_interface);\n auto view = output->get_active_view();\n if (view && (view->role == wf::VIEW_ROLE_TOPLEVEL))\n {\n view->close();\n }\n\n return true;\n };\n\n output->add_activator(key, &callback);\n}\n\nvoid wayfire_close::fini()\n{\n output->rem_binding(&callback);\n}\n\nvoid wayfire_focus::init()\n{\n grab_interface->name = \"_wf_focus\";\n grab_interface->capabilities = wf::CAPABILITY_MANAGE_DESKTOP;\n\n on_wm_focus_request = [=] (wf::signal_data_t *data)\n {\n auto ev = static_cast<wm_focus_request*>(data);\n check_focus_surface(ev->surface);\n };\n output->connect_signal(\"wm-focus-request\", &on_wm_focus_request);\n\n on_button.set_callback([=] (wf::signal_data_t *data)\n {\n auto ev = static_cast<\n wf::input_event_signal<wlr_event_pointer_button>*>(data);\n\n if (ev->event->state != WLR_BUTTON_PRESSED)\n {\n return;\n }\n\n \/* focuse_btns->get_value() does not compile *\/\n wf::option_sptr_t<wf::activatorbinding_t> tmp = focus_btns;\n if ((!focus_modifiers && wf::get_core().get_keyboard_modifiers()) ||\n !tmp->get_value().has_match(wf::buttonbinding_t(0, ev->event->button)))\n {\n return;\n }\n\n this->check_focus_surface(wf::get_core().get_cursor_focus());\n });\n wf::get_core().connect_signal(\"pointer_button\", &on_button);\n\n \/\/ build touch gesture\n auto on_tap = std::make_unique<wf::touch::touch_action_t>(1, true);\n std::vector<std::unique_ptr<wf::touch::gesture_action_t>> actions;\n actions.emplace_back(std::move(on_tap));\n const auto& on_tap_action = [this] ()\n {\n if (wf::get_core().get_active_output() == this->output)\n {\n this->check_focus_surface(wf::get_core().get_touch_focus());\n }\n };\n\n this->tap_gesture =\n std::make_unique<wf::touch::gesture_t>(std::move(actions), on_tap_action);\n wf::get_core().add_touch_gesture(tap_gesture);\n}\n\nvoid wayfire_focus::check_focus_surface(wf::surface_interface_t *focus)\n{\n \/* Find the main view *\/\n auto main_surface = focus ? focus->get_main_surface() : nullptr;\n auto view = dynamic_cast<wf::view_interface_t*>(main_surface);\n\n if (!view || !view->is_mapped() ||\n !output->can_activate_plugin(grab_interface->capabilities))\n {\n return;\n }\n\n auto target_wo = view->get_output();\n if (view->get_keyboard_focus_surface())\n {\n target_wo->focus_view(view->self(), true);\n } else\n {\n target_wo->workspace->bring_to_front(view);\n }\n}\n\nvoid wayfire_focus::fini()\n{\n output->rem_binding(&on_button);\n wf::get_core().rem_touch_gesture(tap_gesture);\n output->disconnect_signal(\"wm-focus-request\", &on_wm_focus_request);\n}\n<|endoftext|>"} {"text":"<commit_before>\/****************************************************************************\n**\n** Copyright (C) 2010 Nokia Corporation and\/or its subsidiary(-ies).\n** All rights reserved.\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n** This file is part of the Qt Mobility Components.\n**\n** $QT_BEGIN_LICENSE:BSD$\n** You may use this file under the terms of the BSD license as follows:\n**\n** \"Redistribution and use in source and binary forms, with or without\n** modification, are permitted provided that the following conditions are\n** met:\n** * Redistributions of source code must retain the above copyright\n** notice, this list of conditions and the following disclaimer.\n** * Redistributions in binary form must reproduce the above copyright\n** notice, this list of conditions and the following disclaimer in\n** the documentation and\/or other materials provided with the\n** distribution.\n** * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor\n** the names of its contributors may be used to endorse or promote\n** products derived from this software without specific prior written\n** permission.\n**\n** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n** \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\"\n** $QT_END_LICENSE$\n**\n****************************************************************************\/\n\n#include \"device.h\"\n#include \"service.h\"\n\n#include <qbluetoothaddress.h>\n#include <qbluetoothdevicediscoveryagent.h>\n#include <qbluetoothlocaldevice.h>\n#include <QMenu>\n#include <QDebug>\n\nDeviceDiscoveryDialog::DeviceDiscoveryDialog(QWidget *parent)\n: QDialog(parent), discoveryAgent(new QBluetoothDeviceDiscoveryAgent),\n localDevice(new QBluetoothLocalDevice),\n ui(new Ui_DeviceDiscovery)\n{\n ui->setupUi(this);\n\n#if defined (Q_OS_SYMBIAN) || defined(Q_OS_WINCE) || defined(Q_WS_MAEMO_5) || defined(Q_WS_MAEMO_6)\n setWindowState(Qt::WindowFullScreen);\n#endif\n\n connect(ui->inquiryType, SIGNAL(toggled(bool)), this, SLOT(setGeneralUnlimited(bool)));\n connect(ui->scan, SIGNAL(clicked()), this, SLOT(startScan()));\n\n connect(discoveryAgent, SIGNAL(deviceDiscovered(const QBluetoothDeviceInfo&)),\n this, SLOT(addDevice(const QBluetoothDeviceInfo&)));\n connect(discoveryAgent, SIGNAL(finished()), this, SLOT(scanFinished()));\n\n connect(ui->list, SIGNAL(itemActivated(QListWidgetItem*)),\n this, SLOT(itemActivated(QListWidgetItem*)));\n\n connect(localDevice, SIGNAL(hostModeStateChanged(QBluetoothLocalDevice::HostMode)),\n this, SLOT(hostModeStateChanged(QBluetoothLocalDevice::HostMode)));\n\n hostModeStateChanged(localDevice->hostMode());\n \/\/ add context menu for devices to be able to pair device\n ui->list->setContextMenuPolicy(Qt::CustomContextMenu);\n connect(ui->list, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(displayPairingMenu(QPoint)));\n connect(localDevice, SIGNAL(pairingFinished(const QBluetoothAddress&, QBluetoothLocalDevice::Pairing))\n , this, SLOT(pairingDone(const QBluetoothAddress&, QBluetoothLocalDevice::Pairing)));\n\n}\n\nDeviceDiscoveryDialog::~DeviceDiscoveryDialog()\n{\n delete discoveryAgent;\n}\n\nvoid DeviceDiscoveryDialog::addDevice(const QBluetoothDeviceInfo &info)\n{\n QString label = QString(\"%1 %2\").arg(info.address().toString()).arg(info.name());\n QList<QListWidgetItem *> items = ui->list->findItems(label, Qt::MatchExactly);\n if(items.empty()) {\n QListWidgetItem *item = new QListWidgetItem(label);\n QBluetoothLocalDevice::Pairing pairingStatus = localDevice->pairingStatus(info.address());\n if (pairingStatus == QBluetoothLocalDevice::Paired || pairingStatus == QBluetoothLocalDevice::AuthorizedPaired )\n item->setTextColor(QColor(Qt::green));\n \n ui->list->addItem(item);\n }\n \n\n}\n\nvoid DeviceDiscoveryDialog::startScan()\n{\n discoveryAgent->start();\n ui->scan->setEnabled(false);\n ui->inquiryType->setEnabled(false);\n}\n\nvoid DeviceDiscoveryDialog::scanFinished()\n{\n ui->scan->setEnabled(true);\n ui->inquiryType->setEnabled(true);\n}\n\nvoid DeviceDiscoveryDialog::setGeneralUnlimited(bool unlimited)\n{\n if (unlimited)\n discoveryAgent->setInquiryType(QBluetoothDeviceDiscoveryAgent::GeneralUnlimitedInquiry);\n else\n discoveryAgent->setInquiryType(QBluetoothDeviceDiscoveryAgent::LimitedInquiry);\n}\n\nvoid DeviceDiscoveryDialog::itemActivated(QListWidgetItem *item)\n{\n QString text = item->text();\n\n int index = text.indexOf(' ');\n\n if (index == -1)\n return;\n\n QBluetoothAddress address(text.left(index));\n QString name(text.mid(index + 1));\n\n ServiceDiscoveryDialog d(name, address);\n d.exec();\n}\n\nvoid DeviceDiscoveryDialog::on_discoverable_clicked(bool clicked)\n{\n if(clicked)\n localDevice->setHostMode(QBluetoothLocalDevice::HostDiscoverable);\n else\n localDevice->setHostMode(QBluetoothLocalDevice::HostConnectable);\n}\n\nvoid DeviceDiscoveryDialog::on_power_clicked(bool clicked)\n{\n if(clicked)\n localDevice->powerOn();\n else\n localDevice->setHostMode(QBluetoothLocalDevice::HostPoweredOff);\n}\n\nvoid DeviceDiscoveryDialog::hostModeStateChanged(QBluetoothLocalDevice::HostMode mode)\n{\n if(mode != QBluetoothLocalDevice::HostPoweredOff)\n ui->power->setChecked(true);\n else\n ui->power->setChecked( false);\n\n if(mode == QBluetoothLocalDevice::HostDiscoverable)\n ui->discoverable->setChecked(true);\n else\n ui->discoverable->setChecked(false);\n\n bool on = !(mode == QBluetoothLocalDevice::HostPoweredOff);\n\n\n ui->scan->setEnabled(on);\n ui->discoverable->setEnabled(on);\n}\nvoid DeviceDiscoveryDialog::displayPairingMenu(const QPoint &pos)\n{\n QMenu menu(this);\n QAction *pairAction = menu.addAction(\"Pair\");\n QAction *removePairAction = menu.addAction(\"Remove Pairing\");\n QAction *chosenAction = menu.exec(ui->list->viewport()->mapToGlobal(pos));\n QListWidgetItem *currentItem = ui->list->currentItem(); \n \n QString text = currentItem->text();\n int index = text.indexOf(' ');\n if (index == -1)\n return;\n\n QBluetoothAddress address (text.left(index));\n if (chosenAction == pairAction) {\n localDevice->requestPairing(address, QBluetoothLocalDevice::Paired);\n } else if (chosenAction == removePairAction) {\n localDevice->requestPairing(address, QBluetoothLocalDevice::Unpaired);\n }\n}\nvoid DeviceDiscoveryDialog::pairingDone(const QBluetoothAddress &address, QBluetoothLocalDevice::Pairing pairing)\n{\n QList<QListWidgetItem *> items = ui->list->findItems(address.toString(), Qt::MatchContains);\n \n if (pairing == QBluetoothLocalDevice::Paired || pairing == QBluetoothLocalDevice::AuthorizedPaired ) {\n for (int var = 0; var < items.count(); ++var) {\n QListWidgetItem *item = items.at(var);\n item->setTextColor(QColor(Qt::green));\n }\n } else {\n for (int var = 0; var < items.count(); ++var) {\n QListWidgetItem *item = items.at(var);\n item->setTextColor(QColor(Qt::red));\n }\n }\n}\n<commit_msg>remove whitespace from device.cpp<commit_after>\/****************************************************************************\n**\n** Copyright (C) 2010 Nokia Corporation and\/or its subsidiary(-ies).\n** All rights reserved.\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n** This file is part of the Qt Mobility Components.\n**\n** $QT_BEGIN_LICENSE:BSD$\n** You may use this file under the terms of the BSD license as follows:\n**\n** \"Redistribution and use in source and binary forms, with or without\n** modification, are permitted provided that the following conditions are\n** met:\n** * Redistributions of source code must retain the above copyright\n** notice, this list of conditions and the following disclaimer.\n** * Redistributions in binary form must reproduce the above copyright\n** notice, this list of conditions and the following disclaimer in\n** the documentation and\/or other materials provided with the\n** distribution.\n** * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor\n** the names of its contributors may be used to endorse or promote\n** products derived from this software without specific prior written\n** permission.\n**\n** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n** \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\"\n** $QT_END_LICENSE$\n**\n****************************************************************************\/\n\n#include \"device.h\"\n#include \"service.h\"\n\n#include <qbluetoothaddress.h>\n#include <qbluetoothdevicediscoveryagent.h>\n#include <qbluetoothlocaldevice.h>\n#include <QMenu>\n#include <QDebug>\n\nDeviceDiscoveryDialog::DeviceDiscoveryDialog(QWidget *parent)\n: QDialog(parent), discoveryAgent(new QBluetoothDeviceDiscoveryAgent),\n localDevice(new QBluetoothLocalDevice),\n ui(new Ui_DeviceDiscovery)\n{\n ui->setupUi(this);\n\n#if defined (Q_OS_SYMBIAN) || defined(Q_OS_WINCE) || defined(Q_WS_MAEMO_5) || defined(Q_WS_MAEMO_6)\n setWindowState(Qt::WindowFullScreen);\n#endif\n\n connect(ui->inquiryType, SIGNAL(toggled(bool)), this, SLOT(setGeneralUnlimited(bool)));\n connect(ui->scan, SIGNAL(clicked()), this, SLOT(startScan()));\n\n connect(discoveryAgent, SIGNAL(deviceDiscovered(const QBluetoothDeviceInfo&)),\n this, SLOT(addDevice(const QBluetoothDeviceInfo&)));\n connect(discoveryAgent, SIGNAL(finished()), this, SLOT(scanFinished()));\n\n connect(ui->list, SIGNAL(itemActivated(QListWidgetItem*)),\n this, SLOT(itemActivated(QListWidgetItem*)));\n\n connect(localDevice, SIGNAL(hostModeStateChanged(QBluetoothLocalDevice::HostMode)),\n this, SLOT(hostModeStateChanged(QBluetoothLocalDevice::HostMode)));\n\n hostModeStateChanged(localDevice->hostMode());\n \/\/ add context menu for devices to be able to pair device\n ui->list->setContextMenuPolicy(Qt::CustomContextMenu);\n connect(ui->list, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(displayPairingMenu(QPoint)));\n connect(localDevice, SIGNAL(pairingFinished(const QBluetoothAddress&, QBluetoothLocalDevice::Pairing))\n , this, SLOT(pairingDone(const QBluetoothAddress&, QBluetoothLocalDevice::Pairing)));\n\n}\n\nDeviceDiscoveryDialog::~DeviceDiscoveryDialog()\n{\n delete discoveryAgent;\n}\n\nvoid DeviceDiscoveryDialog::addDevice(const QBluetoothDeviceInfo &info)\n{\n QString label = QString(\"%1 %2\").arg(info.address().toString()).arg(info.name());\n QList<QListWidgetItem *> items = ui->list->findItems(label, Qt::MatchExactly);\n if(items.empty()) {\n QListWidgetItem *item = new QListWidgetItem(label);\n QBluetoothLocalDevice::Pairing pairingStatus = localDevice->pairingStatus(info.address());\n if (pairingStatus == QBluetoothLocalDevice::Paired || pairingStatus == QBluetoothLocalDevice::AuthorizedPaired )\n item->setTextColor(QColor(Qt::green));\n\n ui->list->addItem(item);\n }\n\n}\n\nvoid DeviceDiscoveryDialog::startScan()\n{\n discoveryAgent->start();\n ui->scan->setEnabled(false);\n ui->inquiryType->setEnabled(false);\n}\n\nvoid DeviceDiscoveryDialog::scanFinished()\n{\n ui->scan->setEnabled(true);\n ui->inquiryType->setEnabled(true);\n}\n\nvoid DeviceDiscoveryDialog::setGeneralUnlimited(bool unlimited)\n{\n if (unlimited)\n discoveryAgent->setInquiryType(QBluetoothDeviceDiscoveryAgent::GeneralUnlimitedInquiry);\n else\n discoveryAgent->setInquiryType(QBluetoothDeviceDiscoveryAgent::LimitedInquiry);\n}\n\nvoid DeviceDiscoveryDialog::itemActivated(QListWidgetItem *item)\n{\n QString text = item->text();\n\n int index = text.indexOf(' ');\n\n if (index == -1)\n return;\n\n QBluetoothAddress address(text.left(index));\n QString name(text.mid(index + 1));\n\n ServiceDiscoveryDialog d(name, address);\n d.exec();\n}\n\nvoid DeviceDiscoveryDialog::on_discoverable_clicked(bool clicked)\n{\n if(clicked)\n localDevice->setHostMode(QBluetoothLocalDevice::HostDiscoverable);\n else\n localDevice->setHostMode(QBluetoothLocalDevice::HostConnectable);\n}\n\nvoid DeviceDiscoveryDialog::on_power_clicked(bool clicked)\n{\n if(clicked)\n localDevice->powerOn();\n else\n localDevice->setHostMode(QBluetoothLocalDevice::HostPoweredOff);\n}\n\nvoid DeviceDiscoveryDialog::hostModeStateChanged(QBluetoothLocalDevice::HostMode mode)\n{\n if(mode != QBluetoothLocalDevice::HostPoweredOff)\n ui->power->setChecked(true);\n else\n ui->power->setChecked( false);\n\n if(mode == QBluetoothLocalDevice::HostDiscoverable)\n ui->discoverable->setChecked(true);\n else\n ui->discoverable->setChecked(false);\n\n bool on = !(mode == QBluetoothLocalDevice::HostPoweredOff);\n\n\n ui->scan->setEnabled(on);\n ui->discoverable->setEnabled(on);\n}\nvoid DeviceDiscoveryDialog::displayPairingMenu(const QPoint &pos)\n{\n QMenu menu(this);\n QAction *pairAction = menu.addAction(\"Pair\");\n QAction *removePairAction = menu.addAction(\"Remove Pairing\");\n QAction *chosenAction = menu.exec(ui->list->viewport()->mapToGlobal(pos));\n QListWidgetItem *currentItem = ui->list->currentItem();\n\n QString text = currentItem->text();\n int index = text.indexOf(' ');\n if (index == -1)\n return;\n\n QBluetoothAddress address (text.left(index));\n if (chosenAction == pairAction) {\n localDevice->requestPairing(address, QBluetoothLocalDevice::Paired);\n } else if (chosenAction == removePairAction) {\n localDevice->requestPairing(address, QBluetoothLocalDevice::Unpaired);\n }\n}\nvoid DeviceDiscoveryDialog::pairingDone(const QBluetoothAddress &address, QBluetoothLocalDevice::Pairing pairing)\n{\n QList<QListWidgetItem *> items = ui->list->findItems(address.toString(), Qt::MatchContains);\n\n if (pairing == QBluetoothLocalDevice::Paired || pairing == QBluetoothLocalDevice::AuthorizedPaired ) {\n for (int var = 0; var < items.count(); ++var) {\n QListWidgetItem *item = items.at(var);\n item->setTextColor(QColor(Qt::green));\n }\n } else {\n for (int var = 0; var < items.count(); ++var) {\n QListWidgetItem *item = items.at(var);\n item->setTextColor(QColor(Qt::red));\n }\n }\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"classes.h\"\n#include \"msvc.h\"\n\n#include <sycl.hpp>\n\n#include <chrono>\n#include <iostream>\n#include <string>\n#include <vector>\n#include <memory>\n\n\nusing std::string;\n\nextern void compute_org(void*, int w, int h, int samps, Ray& cam, Vec& cx, Vec& cy, Vec r, Vec* c);\nextern void compute_org_openmp(void*, int w, int h, int samps, Ray& cam, Vec& cx, Vec& cy, Vec r, Vec* c);\nextern void compute_org_sp(void*, int w, int h, int samps, Ray& cam, Vec& cx, Vec& cy, Vec r, Vec* c);\nextern void compute_org_sp_openmp(void*, int w, int h, int samps, Ray& cam, Vec& cx, Vec& cy, Vec r, Vec* c);\nextern void compute_sycl_gtx(void* dev, int w, int h, int samps, Ray& cam_, Vec& cx_, Vec& cy_, Vec r_, Vec* c_);\n\ninline double clamp(double x) {\n\treturn x < 0 ? 0 : x>1 ? 1 : x;\n}\ninline int toInt(double x) {\n\treturn int(pow(clamp(x), 1 \/ 2.2) * 255 + .5);\n}\n\nvoid to_file(int w, int h, Vec* c, string filename) {\n\tFILE* f = fopen(filename.c_str(), \"w\"); \/\/ Write image to PPM file.\n\tfprintf(f, \"P3\\n%d %d\\n%d\\n\", w, h, 255);\n\tfor(int i = 0; i < w*h; i++) {\n\t\tfprintf(f, \"%d %d %d\\n\", toInt(c[i].x), toInt(c[i].y), toInt(c[i].z));\n\t}\n\tfclose(f);\n}\n\nusing time_point = std::chrono::high_resolution_clock::time_point;\n\nauto now = []() {\n\treturn std::chrono::high_resolution_clock::now();\n};\nauto duration = [](time_point before) {\n\tstatic const float to_seconds = 1e-6f;\n\treturn std::chrono::duration_cast<std::chrono::microseconds>(now() - before).count() * to_seconds;\n};\n\nstruct testInfo {\n\tusing function_ptr = void(*)(void*, int, int, int, Ray&, Vec&, Vec&, Vec, Vec*);\n\tstring name;\n\tfunction_ptr test;\n\tstd::unique_ptr<cl::sycl::device> dev;\n\tfloat lastTime = 0;\n\n\tstatic decltype(now()) startTime;\n\tstatic float totalTime;\n\n\ttestInfo(string name, function_ptr test, cl::sycl::device* dev = nullptr)\n\t\t: name(name), test(test), dev(dev) {}\n\n\ttestInfo(const testInfo&) = delete;\n\ttestInfo(testInfo&& move)\n\t\t: name(std::move(move.name)), test(move.test), dev(std::move(move.dev)) {}\n};\ndecltype(now()) testInfo::startTime = now();\nfloat testInfo::totalTime = 0;\n\nstatic std::vector<const testInfo> tests;\nstatic Ray cam(Vec(50, 52, 295.6), Vec(0, -0.042612, -1).norm()); \/\/ cam pos, dir\n\nbool tester(int w, int h, int samples, Vec& cx, Vec& cy, int iterations, int from, int to) {\n\tusing namespace std;\n\n\tcout << \"samples per pixel: \" << samples << endl;\n\n\tVec r;\n\tvector<Vec> empty_vectors(w*h, 0);\n\tvector<Vec> vectors;\n\tfloat time;\n\n\tfor(int ti = from; ti < to; ++ti) {\n\t\tauto& t = tests[ti];\n\n\t\t\/\/ Quality of Service\n\t\t\/\/ Prevent the user from waiting too long\n\t\tif(t.lastTime > 40) {\n\t\t\tcontinue;\n\t\t}\n\n\t\tcout << \"Running test: \" << t.name << endl;\n\t\tns_erand::reset();\n\t\ttry {\n\t\t\tauto start = now();\n\t\t\tfor(int i = 0; i < iterations; ++i) {\n\t\t\t\tvectors = empty_vectors;\n\t\t\t\tt.test(t.dev.get(), w, h, samples, cam, cx, cy, r, vectors.data());\n\t\t\t}\n\t\t\ttime = (duration(start) \/ (float)iterations);\n\t\t}\n\t\tcatch(cl::sycl::exception& e) {\n\t\t\tcerr << \"SYCL error while testing: \" << e.what() << endl;\n\t\t\tcontinue;\n\t\t}\n\t\tcatch(exception& e) {\n\t\t\tcerr << \"error while testing: \" << e.what() << endl;\n\t\t\tcontinue;\n\t\t}\n\t\tcout << \"time: \" << time << endl;\n\t\t\/\/to_file(w, h, vectors.data(), string(\"image_\") + t.name + \".ppm\");\n\n\t\tt.lastTime = time;\n\n\t\ttestInfo::totalTime = duration(testInfo::startTime);\n\t\tif(testInfo::totalTime > 300) {\n\t\t\tcout << \"exceeded 5 minute limit, stopping\" << endl;\n\t\t\treturn false;\n\t\t}\n\t}\n\t\n\treturn true;\n}\n\ntemplate <class T>\nvoid printInfo(string description, const T& data, int offset = 0) {\n\tstring indent;\n\tfor(int i = 0; i < offset; ++i) {\n\t\tindent += '\\t';\n\t}\n\tstd::cout << indent << description << \": \" << data << std::endl;\n}\n\nvoid getDevices() {\n\tusing namespace std;\n\n\ttry {\n\t\tusing namespace cl::sycl;\n\n\t\tauto platforms = platform::get_platforms();\n\n\t\tint pNum = 0;\n\t\tfor(auto& p : platforms) {\n\t\t\tcout << \"- OpenCL platform \" << pNum << ':' << endl;\n\t\t\t++pNum;\n\n\t\t\tauto openclVersion = p.get_info<info::platform::version>();\n\n\t\t\tprintInfo(\"name\", p.get_info<info::platform::name>(), 1);\n\t\t\tprintInfo(\"vendor\", p.get_info<info::platform::vendor>(), 1);\n\t\t\tprintInfo(\"version\", openclVersion, 1);\n\t\t\tprintInfo(\"profile\", p.get_info<info::platform::profile>(), 1);\n\t\t\tprintInfo(\"extensions\", p.get_info<info::platform::extensions>(), 1);\n\n\t\t\tauto devices = p.get_devices();\n\t\t\tint dNum = 0;\n\n\t\t\tfor(auto& d : devices) {\n\t\t\t\tcout << \"\\t-- OpenCL device \" << dNum << ':' << endl;\n\n\t\t\t\tauto name = d.get_info<info::device::name>();\n\n\t\t\t\tprintInfo(\"name\", d.get_info<info::device::name>(), 2);\n\t\t\t\tprintInfo(\"device_type\", (cl_device_type)d.get_info<info::device::device_type>(), 2);\n\t\t\t\tprintInfo(\"vendor\", d.get_info<info::device::vendor>(), 2);\n\t\t\t\tprintInfo(\"device_version\", d.get_info<info::device::device_version>(), 2);\n\t\t\t\tprintInfo(\"driver_version\", d.get_info<info::device::driver_version>(), 2);\n\t\t\t\tprintInfo(\"opencl_version\", d.get_info<info::device::opencl_version>(), 2);\n\t\t\t\tprintInfo(\"single_fp_config\", d.get_info<info::device::single_fp_config>(), 2);\n\t\t\t\tprintInfo(\"double_fp_config\", d.get_info<info::device::double_fp_config>(), 2);\n\t\t\t\tprintInfo(\"profile\", d.get_info<info::device::profile>(), 2);\n\t\t\t\tprintInfo(\"error_correction_support\", d.get_info<info::device::error_correction_support>(), 2);\n\t\t\t\tprintInfo(\"host_unified_memory\", d.get_info<info::device::host_unified_memory>(), 2);\n\t\t\t\tprintInfo(\"max_clock_frequency\", d.get_info<info::device::max_clock_frequency>(), 2);\n\t\t\t\tprintInfo(\"max_compute_units\", d.get_info<info::device::max_compute_units>(), 2);\n\t\t\t\tprintInfo(\"max_work_item_dimensions\", d.get_info<info::device::max_work_item_dimensions>(), 2);\n\t\t\t\tprintInfo(\"max_work_group_size\", d.get_info<info::device::max_work_group_size>(), 2);\n\n\t\t\t\tprintInfo(\"address_bits\", d.get_info<info::device::address_bits>(), 2);\n\t\t\t\tprintInfo(\"max_mem_alloc_size\", d.get_info<info::device::max_mem_alloc_size>(), 2);\n\t\t\t\tprintInfo(\"global_mem_cache_line_size\", d.get_info<info::device::global_mem_cache_line_size>(), 2);\n\t\t\t\tprintInfo(\"global_mem_cache_size\", d.get_info<info::device::global_mem_cache_size>(), 2);\n\t\t\t\tprintInfo(\"global_mem_size\", d.get_info<info::device::global_mem_size>(), 2);\n\t\t\t\tprintInfo(\"max_constant_buffer_size\", d.get_info<info::device::max_constant_buffer_size>(), 2);\n\t\t\t\tprintInfo(\"max_constant_args\", d.get_info<info::device::max_constant_args>(), 2);\n\t\t\t\tprintInfo(\"local_mem_size\", d.get_info<info::device::local_mem_size>(), 2);\n\t\t\t\tprintInfo(\"extensions\", d.get_info<info::device::extensions>(), 2);\n\n\t\t\t\ttests.emplace_back(name + ' ' + openclVersion, compute_sycl_gtx, new device(std::move(d)));\n\n\t\t\t\t++dNum;\n\t\t\t}\n\t\t}\n\t}\n\tcatch(cl::sycl::exception& e) {\n\t\t\/\/ TODO\n\t\tcout << \"OpenCL not available: \" << e.what() << endl;\n\t}\n}\n\nint main(int argc, char *argv[]) {\n\tusing namespace std;\n\n\tcout << \"smallpt SYCL tester\" << endl;\n\n\ttests.emplace_back(\"org_single\", compute_org_sp);\n\ttests.emplace_back(\"openmp_single\", compute_org_sp_openmp);\n\ttests.emplace_back(\"org\", compute_org);\n\ttests.emplace_back(\"openmp\", compute_org_openmp);\n\n\tgetDevices();\n\n\tint w = 1024;\n\tint h = 768;\n\tVec cx = Vec(w*.5135 \/ h);\n\tVec cy = (cx%cam.d).norm()*.5135;\n\tauto numTests = tests.size();\n\n\tint from = 2;\n\tint to = numTests;\n\tif(argc > 1) {\n\t\tfrom = atoi(argv[1]);\n\t\tif(argc > 2) {\n\t\t\tto = atoi(argv[2]);\n\t\t}\n\t}\n\n\tcout << \"Going through tests in range [\" << from << ',' << to << ')' << endl;\n\n\tif(false) {\n\t\ttester(w, h, 1, cx, cy, 1, from, to);\n\t\tcout << \"Press any key to exit\" << endl;\n\t\tcin.get();\n\t\treturn 0;\n\t}\n\n\t\/\/ Test suite\n\tint iterations = 1;\n\tbool canContinue;\n\n\tfor(int samples = 5; samples < 10000; samples *= 2) {\n\t\tcanContinue = tester(w, h, samples, cx, cy, iterations, from, to);\n\t\tif(!canContinue) {\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tauto time = duration(testInfo::startTime);\n\tcout << \"total test suite duration: \" << time << endl;\n\n\t\/\/cout << \"Press any key to exit\" << endl;\n\t\/\/cin.get();\n\n\treturn 0;\n}\n<commit_msg>smallpt - checking for platform version before adding device to test<commit_after>#include \"classes.h\"\n#include \"msvc.h\"\n\n#include <sycl.hpp>\n\n#include <chrono>\n#include <iostream>\n#include <string>\n#include <vector>\n#include <memory>\n\n\nusing std::string;\n\nextern void compute_org(void*, int w, int h, int samps, Ray& cam, Vec& cx, Vec& cy, Vec r, Vec* c);\nextern void compute_org_openmp(void*, int w, int h, int samps, Ray& cam, Vec& cx, Vec& cy, Vec r, Vec* c);\nextern void compute_org_sp(void*, int w, int h, int samps, Ray& cam, Vec& cx, Vec& cy, Vec r, Vec* c);\nextern void compute_org_sp_openmp(void*, int w, int h, int samps, Ray& cam, Vec& cx, Vec& cy, Vec r, Vec* c);\nextern void compute_sycl_gtx(void* dev, int w, int h, int samps, Ray& cam_, Vec& cx_, Vec& cy_, Vec r_, Vec* c_);\n\ninline double clamp(double x) {\n\treturn x < 0 ? 0 : x>1 ? 1 : x;\n}\ninline int toInt(double x) {\n\treturn int(pow(clamp(x), 1 \/ 2.2) * 255 + .5);\n}\n\nvoid to_file(int w, int h, Vec* c, string filename) {\n\tFILE* f = fopen(filename.c_str(), \"w\"); \/\/ Write image to PPM file.\n\tfprintf(f, \"P3\\n%d %d\\n%d\\n\", w, h, 255);\n\tfor(int i = 0; i < w*h; i++) {\n\t\tfprintf(f, \"%d %d %d\\n\", toInt(c[i].x), toInt(c[i].y), toInt(c[i].z));\n\t}\n\tfclose(f);\n}\n\nusing time_point = std::chrono::high_resolution_clock::time_point;\n\nauto now = []() {\n\treturn std::chrono::high_resolution_clock::now();\n};\nauto duration = [](time_point before) {\n\tstatic const float to_seconds = 1e-6f;\n\treturn std::chrono::duration_cast<std::chrono::microseconds>(now() - before).count() * to_seconds;\n};\n\nstruct testInfo {\n\tusing function_ptr = void(*)(void*, int, int, int, Ray&, Vec&, Vec&, Vec, Vec*);\n\tstring name;\n\tfunction_ptr test;\n\tstd::unique_ptr<cl::sycl::device> dev;\n\tfloat lastTime = 0;\n\n\tstatic decltype(now()) startTime;\n\tstatic float totalTime;\n\n\ttestInfo(string name, function_ptr test, cl::sycl::device* dev = nullptr)\n\t\t: name(name), test(test), dev(dev) {}\n\n\ttestInfo(const testInfo&) = delete;\n\ttestInfo(testInfo&& move)\n\t\t: name(std::move(move.name)), test(move.test), dev(std::move(move.dev)) {}\n};\ndecltype(now()) testInfo::startTime = now();\nfloat testInfo::totalTime = 0;\n\nstatic std::vector<const testInfo> tests;\nstatic Ray cam(Vec(50, 52, 295.6), Vec(0, -0.042612, -1).norm()); \/\/ cam pos, dir\n\nbool tester(int w, int h, int samples, Vec& cx, Vec& cy, int iterations, int from, int to) {\n\tusing namespace std;\n\n\tcout << \"samples per pixel: \" << samples << endl;\n\n\tVec r;\n\tvector<Vec> empty_vectors(w*h, 0);\n\tvector<Vec> vectors;\n\tfloat time;\n\n\tfor(int ti = from; ti < to; ++ti) {\n\t\tauto& t = tests[ti];\n\n\t\t\/\/ Quality of Service\n\t\t\/\/ Prevent the user from waiting too long\n\t\tif(t.lastTime > 40) {\n\t\t\tcontinue;\n\t\t}\n\n\t\tcout << \"Running test: \" << t.name << endl;\n\t\tns_erand::reset();\n\t\ttry {\n\t\t\tauto start = now();\n\t\t\tfor(int i = 0; i < iterations; ++i) {\n\t\t\t\tvectors = empty_vectors;\n\t\t\t\tt.test(t.dev.get(), w, h, samples, cam, cx, cy, r, vectors.data());\n\t\t\t}\n\t\t\ttime = (duration(start) \/ (float)iterations);\n\t\t}\n\t\tcatch(cl::sycl::exception& e) {\n\t\t\tcerr << \"SYCL error while testing: \" << e.what() << endl;\n\t\t\tcontinue;\n\t\t}\n\t\tcatch(exception& e) {\n\t\t\tcerr << \"error while testing: \" << e.what() << endl;\n\t\t\tcontinue;\n\t\t}\n\t\tcout << \"time: \" << time << endl;\n\t\t\/\/to_file(w, h, vectors.data(), string(\"image_\") + t.name + \".ppm\");\n\n\t\tt.lastTime = time;\n\n\t\ttestInfo::totalTime = duration(testInfo::startTime);\n\t\tif(testInfo::totalTime > 300) {\n\t\t\tcout << \"exceeded 5 minute limit, stopping\" << endl;\n\t\t\treturn false;\n\t\t}\n\t}\n\t\n\treturn true;\n}\n\nstruct version {\n\tint major = 0;\n\tint minor = 0;\n\n\tversion(int major, int minor)\n\t\t: major(major), minor(minor) {}\n\tversion(const string& v) {\n\t\t\/\/ https:\/\/www.khronos.org\/registry\/cl\/sdk\/1.2\/docs\/man\/xhtml\/clGetPlatformInfo.html\n\t\tusing namespace std;\n\t\tstring search(\"OpenCL\");\n\t\tauto pos = v.find(search);\n\t\tif(pos != string::npos) {\n\t\t\tpos += search.length() + 1;\t\/\/ Plus one for space\n\t\t\ttry {\n\t\t\t\tmajor = (int)v.at(pos) - '0';\n\t\t\t\tminor = (int)v.at(pos + 2) - '0';; \/\/ Plus one for dot\n\t\t\t}\n\t\t\tcatch(std::exception& e) {}\n\t\t}\n\t}\n};\n\ntemplate <class T>\nvoid printInfo(string description, const T& data, int offset = 0) {\n\tstring indent;\n\tfor(int i = 0; i < offset; ++i) {\n\t\tindent += '\\t';\n\t}\n\tstd::cout << indent << description << \": \" << data << std::endl;\n}\n\nvoid getDevices() {\n\tusing namespace std;\n\n\ttry {\n\t\tusing namespace cl::sycl;\n\n\t\tauto platforms = platform::get_platforms();\n\n\t\tversion required(1, 2);\n\n\t\tint pNum = 0;\n\t\tfor(auto& p : platforms) {\n\t\t\tcout << \"- OpenCL platform \" << pNum << ':' << endl;\n\t\t\t++pNum;\n\n\t\t\tauto openclVersion = p.get_info<info::platform::version>();\n\n\t\t\tversion platformVersion(openclVersion);\n\n\t\t\tprintInfo(\"name\", p.get_info<info::platform::name>(), 1);\n\t\t\tprintInfo(\"vendor\", p.get_info<info::platform::vendor>(), 1);\n\t\t\tprintInfo(\"version\", openclVersion, 1);\n\t\t\tprintInfo(\"profile\", p.get_info<info::platform::profile>(), 1);\n\t\t\tprintInfo(\"extensions\", p.get_info<info::platform::extensions>(), 1);\n\n\t\t\tauto devices = p.get_devices();\n\t\t\tint dNum = 0;\n\n\t\t\tfor(auto& d : devices) {\n\t\t\t\tcout << \"\\t-- OpenCL device \" << dNum << ':' << endl;\n\n\t\t\t\tauto name = d.get_info<info::device::name>();\n\n\t\t\t\tprintInfo(\"name\", d.get_info<info::device::name>(), 2);\n\t\t\t\tprintInfo(\"device_type\", (cl_device_type)d.get_info<info::device::device_type>(), 2);\n\t\t\t\tprintInfo(\"vendor\", d.get_info<info::device::vendor>(), 2);\n\t\t\t\tprintInfo(\"device_version\", d.get_info<info::device::device_version>(), 2);\n\t\t\t\tprintInfo(\"driver_version\", d.get_info<info::device::driver_version>(), 2);\n\t\t\t\tprintInfo(\"opencl_version\", d.get_info<info::device::opencl_version>(), 2);\n\t\t\t\tprintInfo(\"single_fp_config\", d.get_info<info::device::single_fp_config>(), 2);\n\t\t\t\tprintInfo(\"double_fp_config\", d.get_info<info::device::double_fp_config>(), 2);\n\t\t\t\tprintInfo(\"profile\", d.get_info<info::device::profile>(), 2);\n\t\t\t\tprintInfo(\"error_correction_support\", d.get_info<info::device::error_correction_support>(), 2);\n\t\t\t\tprintInfo(\"host_unified_memory\", d.get_info<info::device::host_unified_memory>(), 2);\n\t\t\t\tprintInfo(\"max_clock_frequency\", d.get_info<info::device::max_clock_frequency>(), 2);\n\t\t\t\tprintInfo(\"max_compute_units\", d.get_info<info::device::max_compute_units>(), 2);\n\t\t\t\tprintInfo(\"max_work_item_dimensions\", d.get_info<info::device::max_work_item_dimensions>(), 2);\n\t\t\t\tprintInfo(\"max_work_group_size\", d.get_info<info::device::max_work_group_size>(), 2);\n\n\t\t\t\tprintInfo(\"address_bits\", d.get_info<info::device::address_bits>(), 2);\n\t\t\t\tprintInfo(\"max_mem_alloc_size\", d.get_info<info::device::max_mem_alloc_size>(), 2);\n\t\t\t\tprintInfo(\"global_mem_cache_line_size\", d.get_info<info::device::global_mem_cache_line_size>(), 2);\n\t\t\t\tprintInfo(\"global_mem_cache_size\", d.get_info<info::device::global_mem_cache_size>(), 2);\n\t\t\t\tprintInfo(\"global_mem_size\", d.get_info<info::device::global_mem_size>(), 2);\n\t\t\t\tprintInfo(\"max_constant_buffer_size\", d.get_info<info::device::max_constant_buffer_size>(), 2);\n\t\t\t\tprintInfo(\"max_constant_args\", d.get_info<info::device::max_constant_args>(), 2);\n\t\t\t\tprintInfo(\"local_mem_size\", d.get_info<info::device::local_mem_size>(), 2);\n\t\t\t\tprintInfo(\"extensions\", d.get_info<info::device::extensions>(), 2);\n\n\t\t\t\tif(\n\t\t\t\t\tplatformVersion.major > required.major ||\n\t\t\t\t\t(platformVersion.major == required.major && platformVersion.minor >= required.minor)\n\t\t\t\t) {\n\t\t\t\t\ttests.emplace_back(name + ' ' + openclVersion, compute_sycl_gtx, new device(std::move(d)));\n\t\t\t\t}\n\n\t\t\t\t++dNum;\n\t\t\t}\n\t\t}\n\t}\n\tcatch(cl::sycl::exception& e) {\n\t\t\/\/ TODO\n\t\tcout << \"OpenCL not available: \" << e.what() << endl;\n\t}\n}\n\nint main(int argc, char *argv[]) {\n\tusing namespace std;\n\n\tcout << \"smallpt SYCL tester\" << endl;\n\n\ttests.emplace_back(\"org_single\", compute_org_sp);\n\ttests.emplace_back(\"openmp_single\", compute_org_sp_openmp);\n\ttests.emplace_back(\"org\", compute_org);\n\ttests.emplace_back(\"openmp\", compute_org_openmp);\n\n\tgetDevices();\n\n\tint w = 1024;\n\tint h = 768;\n\tVec cx = Vec(w*.5135 \/ h);\n\tVec cy = (cx%cam.d).norm()*.5135;\n\tauto numTests = tests.size();\n\n\tint from = 2;\n\tint to = numTests;\n\tif(argc > 1) {\n\t\tfrom = atoi(argv[1]);\n\t\tif(argc > 2) {\n\t\t\tto = atoi(argv[2]);\n\t\t}\n\t}\n\n\tcout << \"Going through tests in range [\" << from << ',' << to << ')' << endl;\n\n\tif(false) {\n\t\ttester(w, h, 1, cx, cy, 1, from, to);\n\t\tcout << \"Press any key to exit\" << endl;\n\t\tcin.get();\n\t\treturn 0;\n\t}\n\n\t\/\/ Test suite\n\tint iterations = 1;\n\tbool canContinue;\n\n\tfor(int samples = 5; samples < 10000; samples *= 2) {\n\t\tcanContinue = tester(w, h, samples, cx, cy, iterations, from, to);\n\t\tif(!canContinue) {\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tauto time = duration(testInfo::startTime);\n\tcout << \"total test suite duration: \" << time << endl;\n\n\t\/\/cout << \"Press any key to exit\" << endl;\n\t\/\/cin.get();\n\n\treturn 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/**\n * This file is part of the CernVM File System.\n *\n * Runs mount\/umount commands and removes scratch space on behalf of a\n * repository owner. Server-only utility.\n *\n * This binary does not use the cvmfs infrastructure code to stay lean.\n *\/\n\n#include <sys\/stat.h>\n#include <sys\/xattr.h>\n#include <dirent.h>\n#include <unistd.h>\n#include <errno.h>\n\n#include <cstdlib>\n#include <cstdio>\n#include <cstring>\n\n#include <string>\n\n#include \"platform.h\"\n\nusing namespace std; \/\/ NOLINT\n\nconst char *kSpoolArea = \"\/var\/spool\/cvmfs\";\n\nenum RemountType {\n kRemountRdonly,\n kRemountRw\n};\n\nstatic void GetCredentials(uid_t *calling_uid, uid_t *effective_uid) {\n *calling_uid = getuid();\n *effective_uid = geteuid();\n}\n\nstatic void ExecAsRoot(const char *binary,\n const char *arg1, const char *arg2, const char *arg3)\n{\n char *argv[] = { strdup(binary),\n arg1 ? strdup(arg1) : NULL,\n arg2 ? strdup(arg2) : NULL,\n arg3 ? strdup(arg3) : NULL,\n NULL };\n char *environ[] = { NULL };\n\n int retval = setuid(0);\n if (retval != 0) {\n fprintf(stderr, \"failed to gain root privileges (%d)\\n\", errno);\n exit(1);\n }\n\n execve(binary, argv, environ);\n fprintf(stderr, \"failed to run %s... (%d)\\n\", binary, errno);\n exit(1);\n}\n\n\nstatic void Remount(const string &path, const RemountType how) {\n string remount_option = \"remount,\";\n switch (how) {\n case kRemountRw:\n remount_option += \"rw\";\n break;\n case kRemountRdonly:\n remount_option += \"ro\";\n break;\n default:\n fprintf(stderr, \"internal error\\n\");\n exit(1);\n }\n\n ExecAsRoot(\"\/bin\/mount\", \"-o\", remount_option.c_str(), path.c_str());\n}\n\nstatic void Mount(const string &path) {\n ExecAsRoot(\"\/bin\/mount\", path.c_str(), NULL, NULL);\n}\n\nstatic void Umount(const string &path) {\n ExecAsRoot(\"\/bin\/umount\", path.c_str(), NULL, NULL);\n}\n\nstatic void KillCvmfs(const string &fqrn) {\n \/\/ prevent exploitation like:\n \/\/ fqrn = ..\/..\/..\/..\/usr\/home\/file_with_xattr_user.pid\n if (fqrn.find(\"\/\") != string::npos || fqrn.find(\"\\\\\") != string::npos) {\n fprintf(stderr, \"go away!\\n\");\n exit(1);\n }\n string pid;\n const string mountpoint = string(kSpoolArea) + \"\/\" + fqrn + \"\/rdonly\";\n const bool retval = platform_getxattr(mountpoint.c_str(), \"user.pid\", &pid);\n if (!retval) {\n exit(1);\n }\n ExecAsRoot(\"\/bin\/kill\", \"-9\", pid.c_str(), NULL);\n}\n\nstatic bool ClearWorkingDir() {\n int retval;\n DIR *dirp = opendir(\".\");\n if (dirp == NULL)\n return false;\n platform_dirent64 *dirent;\n while ((dirent = platform_readdir(dirp)) != NULL) {\n if ((strcmp(dirent->d_name, \".\") == 0) || (strcmp(dirent->d_name, \"..\") == 0))\n continue;\n\n platform_stat64 info;\n retval = platform_lstat(dirent->d_name, &info);\n if (retval != 0) {\n closedir(dirp);\n return false;\n }\n\n if (S_ISDIR(info.st_mode)) {\n \/\/ Recursion\n retval = chdir(dirent->d_name);\n if (retval != 0) {\n closedir(dirp);\n return false;\n }\n retval = ClearWorkingDir();\n if (!retval) {\n closedir(dirp);\n return false;\n }\n retval = chdir(\"..\");\n if (retval != 0) {\n closedir(dirp);\n return false;\n }\n retval = rmdir(dirent->d_name);\n if (retval != 0) {\n closedir(dirp);\n return false;\n }\n } else {\n retval = unlink(dirent->d_name);\n if (retval != 0) {\n closedir(dirp);\n return false;\n }\n }\n }\n closedir(dirp);\n return true;\n}\n\nstatic void Usage(const string &exe, FILE *output) {\n fprintf(output,\n \"Usage: %s lock|open|rw_mount|rw_umount|rdonly_mount|rdonly_umount|clear_scratch \"\n \"fqrn\\n\"\n \"Example: %s rw_umount atlas.cern.ch\\n\"\n \"This binary is typically called by cvmfs_server.\\n\",\n exe.c_str(), exe.c_str());\n}\n\n\nint main(int argc, char *argv[]) {\n umask(077);\n int retval;\n\n \/\/ Figure out real and effective uid\n uid_t calling_uid, effective_uid, repository_uid;\n GetCredentials(&calling_uid, &effective_uid);\n if (effective_uid != 0) {\n fprintf(stderr, \"Needs to run as root\\n\");\n return 1;\n }\n\n \/\/ Arguments\n if (argc != 3) {\n Usage(argv[0], stderr);\n return 1;\n }\n const string command = argv[1];\n const string fqrn = argv[2];\n\n \/\/ Verify if repository exists\n platform_stat64 info;\n retval = platform_lstat((string(kSpoolArea) + \"\/\" + fqrn).c_str(), &info);\n if (retval != 0) {\n fprintf(stderr, \"unknown repository: %s\\n\", fqrn.c_str());\n return 1;\n }\n repository_uid = info.st_uid;\n\n \/\/ Verify if caller uid matches\n if ((calling_uid != 0) && (calling_uid != repository_uid)) {\n fprintf(stderr, \"called as %d, repository owned by %d\\n\",\n calling_uid, repository_uid);\n return 1;\n }\n\n if (command == \"lock\") {\n Remount(\"\/cvmfs\/\" + fqrn, kRemountRdonly);\n } else if (command == \"open\") {\n Remount(\"\/cvmfs\/\" + fqrn, kRemountRw);\n } else if (command == \"kill_cvmfs\") {\n KillCvmfs(fqrn);\n } else if (command == \"rw_mount\") {\n Mount(\"\/cvmfs\/\" + fqrn);\n } else if (command == \"rw_umount\") {\n Umount(\"\/cvmfs\/\" + fqrn);\n } else if (command == \"rdonly_mount\") {\n Mount(string(kSpoolArea) + \"\/\" + fqrn + \"\/rdonly\");\n } else if (command == \"rdonly_umount\") {\n Umount(string(kSpoolArea) + \"\/\" + fqrn + \"\/rdonly\");\n } else if (command == \"clear_scratch\") {\n const string scratch_area = string(kSpoolArea) + \"\/\" + fqrn + \"\/scratch\";\n retval = chdir(scratch_area.c_str());\n if (retval != 0) {\n fprintf(stderr, \"failed to chdir to %s\\n\", scratch_area.c_str());\n return 1;\n }\n retval = ClearWorkingDir();\n if (!retval) {\n fprintf(stderr, \"failed to clear %s\\n\", scratch_area.c_str());\n return 1;\n }\n } else {\n Usage(argv[0], stderr);\n return 1;\n }\n\n return 0;\n}\n<commit_msg>add *_lazy_umount to cvmfs_suid_helper<commit_after>\/**\n * This file is part of the CernVM File System.\n *\n * Runs mount\/umount commands and removes scratch space on behalf of a\n * repository owner. Server-only utility.\n *\n * This binary does not use the cvmfs infrastructure code to stay lean.\n *\/\n\n#include <sys\/stat.h>\n#include <sys\/xattr.h>\n#include <dirent.h>\n#include <unistd.h>\n#include <errno.h>\n\n#include <cstdlib>\n#include <cstdio>\n#include <cstring>\n\n#include <string>\n\n#include \"platform.h\"\n\nusing namespace std; \/\/ NOLINT\n\nconst char *kSpoolArea = \"\/var\/spool\/cvmfs\";\n\nenum RemountType {\n kRemountRdonly,\n kRemountRw\n};\n\nstatic void GetCredentials(uid_t *calling_uid, uid_t *effective_uid) {\n *calling_uid = getuid();\n *effective_uid = geteuid();\n}\n\nstatic void ExecAsRoot(const char *binary,\n const char *arg1, const char *arg2, const char *arg3)\n{\n char *argv[] = { strdup(binary),\n arg1 ? strdup(arg1) : NULL,\n arg2 ? strdup(arg2) : NULL,\n arg3 ? strdup(arg3) : NULL,\n NULL };\n char *environ[] = { NULL };\n\n int retval = setuid(0);\n if (retval != 0) {\n fprintf(stderr, \"failed to gain root privileges (%d)\\n\", errno);\n exit(1);\n }\n\n execve(binary, argv, environ);\n fprintf(stderr, \"failed to run %s... (%d)\\n\", binary, errno);\n exit(1);\n}\n\n\nstatic void Remount(const string &path, const RemountType how) {\n string remount_option = \"remount,\";\n switch (how) {\n case kRemountRw:\n remount_option += \"rw\";\n break;\n case kRemountRdonly:\n remount_option += \"ro\";\n break;\n default:\n fprintf(stderr, \"internal error\\n\");\n exit(1);\n }\n\n ExecAsRoot(\"\/bin\/mount\", \"-o\", remount_option.c_str(), path.c_str());\n}\n\nstatic void Mount(const string &path) {\n ExecAsRoot(\"\/bin\/mount\", path.c_str(), NULL, NULL);\n}\n\nstatic void Umount(const string &path) {\n ExecAsRoot(\"\/bin\/umount\", path.c_str(), NULL, NULL);\n}\n\nstatic void LazyUmount(const string &path) {\n ExecAsRoot(\"\/bin\/umount\", \"-l\", path.c_str(), NULL);\n}\n\nstatic void KillCvmfs(const string &fqrn) {\n \/\/ prevent exploitation like:\n \/\/ fqrn = ..\/..\/..\/..\/usr\/home\/file_with_xattr_user.pid\n if (fqrn.find(\"\/\") != string::npos || fqrn.find(\"\\\\\") != string::npos) {\n fprintf(stderr, \"go away!\\n\");\n exit(1);\n }\n string pid;\n const string mountpoint = string(kSpoolArea) + \"\/\" + fqrn + \"\/rdonly\";\n const bool retval = platform_getxattr(mountpoint.c_str(), \"user.pid\", &pid);\n if (!retval) {\n exit(1);\n }\n ExecAsRoot(\"\/bin\/kill\", \"-9\", pid.c_str(), NULL);\n}\n\nstatic bool ClearWorkingDir() {\n int retval;\n DIR *dirp = opendir(\".\");\n if (dirp == NULL)\n return false;\n platform_dirent64 *dirent;\n while ((dirent = platform_readdir(dirp)) != NULL) {\n if ((strcmp(dirent->d_name, \".\") == 0) || (strcmp(dirent->d_name, \"..\") == 0))\n continue;\n\n platform_stat64 info;\n retval = platform_lstat(dirent->d_name, &info);\n if (retval != 0) {\n closedir(dirp);\n return false;\n }\n\n if (S_ISDIR(info.st_mode)) {\n \/\/ Recursion\n retval = chdir(dirent->d_name);\n if (retval != 0) {\n closedir(dirp);\n return false;\n }\n retval = ClearWorkingDir();\n if (!retval) {\n closedir(dirp);\n return false;\n }\n retval = chdir(\"..\");\n if (retval != 0) {\n closedir(dirp);\n return false;\n }\n retval = rmdir(dirent->d_name);\n if (retval != 0) {\n closedir(dirp);\n return false;\n }\n } else {\n retval = unlink(dirent->d_name);\n if (retval != 0) {\n closedir(dirp);\n return false;\n }\n }\n }\n closedir(dirp);\n return true;\n}\n\nstatic void Usage(const string &exe, FILE *output) {\n fprintf(output,\n \"Usage: %s lock|open|rw_mount|rw_umount|rdonly_mount|rdonly_umount|clear_scratch \"\n \"fqrn\\n\"\n \"Example: %s rw_umount atlas.cern.ch\\n\"\n \"This binary is typically called by cvmfs_server.\\n\",\n exe.c_str(), exe.c_str());\n}\n\n\nint main(int argc, char *argv[]) {\n umask(077);\n int retval;\n\n \/\/ Figure out real and effective uid\n uid_t calling_uid, effective_uid, repository_uid;\n GetCredentials(&calling_uid, &effective_uid);\n if (effective_uid != 0) {\n fprintf(stderr, \"Needs to run as root\\n\");\n return 1;\n }\n\n \/\/ Arguments\n if (argc != 3) {\n Usage(argv[0], stderr);\n return 1;\n }\n const string command = argv[1];\n const string fqrn = argv[2];\n\n \/\/ Verify if repository exists\n platform_stat64 info;\n retval = platform_lstat((string(kSpoolArea) + \"\/\" + fqrn).c_str(), &info);\n if (retval != 0) {\n fprintf(stderr, \"unknown repository: %s\\n\", fqrn.c_str());\n return 1;\n }\n repository_uid = info.st_uid;\n\n \/\/ Verify if caller uid matches\n if ((calling_uid != 0) && (calling_uid != repository_uid)) {\n fprintf(stderr, \"called as %d, repository owned by %d\\n\",\n calling_uid, repository_uid);\n return 1;\n }\n\n if (command == \"lock\") {\n Remount(\"\/cvmfs\/\" + fqrn, kRemountRdonly);\n } else if (command == \"open\") {\n Remount(\"\/cvmfs\/\" + fqrn, kRemountRw);\n } else if (command == \"kill_cvmfs\") {\n KillCvmfs(fqrn);\n } else if (command == \"rw_mount\") {\n Mount(\"\/cvmfs\/\" + fqrn);\n } else if (command == \"rw_umount\") {\n Umount(\"\/cvmfs\/\" + fqrn);\n } else if (command == \"rw_lazy_umount\") {\n LazyUmount(\"\/cvmfs\/\" + fqrn);\n } else if (command == \"rdonly_mount\") {\n Mount(string(kSpoolArea) + \"\/\" + fqrn + \"\/rdonly\");\n } else if (command == \"rdonly_umount\") {\n Umount(string(kSpoolArea) + \"\/\" + fqrn + \"\/rdonly\");\n } else if (command == \"rdonly_lazy_umount\") {\n LazyUmount(string(kSpoolArea) + \"\/\" + fqrn + \"\/rdonly\");\n } else if (command == \"clear_scratch\") {\n const string scratch_area = string(kSpoolArea) + \"\/\" + fqrn + \"\/scratch\";\n retval = chdir(scratch_area.c_str());\n if (retval != 0) {\n fprintf(stderr, \"failed to chdir to %s\\n\", scratch_area.c_str());\n return 1;\n }\n retval = ClearWorkingDir();\n if (!retval) {\n fprintf(stderr, \"failed to clear %s\\n\", scratch_area.c_str());\n return 1;\n }\n } else {\n Usage(argv[0], stderr);\n return 1;\n }\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\nLibrary EDK - How to use Extensible Development Kit\nCopyright (C) 2013 Eduardo Moura Sales Martins\nThis library is free software; you can redistribute it and\/or\nmodify it under the terms of the GNU Lesser General Public\nLicense as published by the Free Software Foundation; either\nversion 2.1 of the License, or (at your option) any later version.\nThis library is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\nLesser General Public License for more details.\nYou should have received a copy of the GNU Lesser General Public\nLicense along with this library; if not, write to the Free Software\nFoundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\nemail: edimartin@gmail.com.br\n\nAV: Walmor M. de Souza 392 Casa\nGravatai RS Brazil 94065100\n*\/\n\n\/\/Include the Window\n#include \"edk\/Window.h\"\n\/\/Include the View to render Graphics\n#include \"edk\/ViewGU2D.h\"\n\/\/Include the FontMap render\n#include \"edk\/fonts\/FontMap.h\"\n\nclass RenderView: public edk::ViewGU2D{\npublic:\n RenderView(){}\n ~RenderView(){}\n void load(){\n this->camera.position.x = 7;\n this->camera.position.y = -0.5f;\n this->camera.setSize(16.f,10.f);\n \/\/create the message\n text.createStringMap(\"Hello EDK World\");\n }\n void unload(){\n \/\/remove the message\n text.deleteMap();\n }\n \/\/render the scene in the vew\n void drawScene(){\n \/\/draw the message\n text.draw();\n }\nprivate:\n edk::fonts::FontMap text;\n};\n\nint main(){\n edk::Window win;\n \/\/create the window with the buttons\n win.createWindow(800,600,\"EDK HELLO WORLD\",EDK_WINDOW_BUTTONS);\n \/\/set the background color fo the window\n win.cleanColor = edk::color3ui8(0,0,0);\n\n \/\/Create a view to draw the scene\n RenderView view;\n view.backgroundColor = edk::color4f32(1,1,1,1); \/\/set the viewColor\n view.frame.origin = edk::vec2f32(50,50); \/\/set the view position inside the Window View\n view.frame.size = edk::size2f32(700,500); \/\/set the size of the View\n\n \/\/add the view in the Window\n win.addSubview(&view);\n\n \/\/Loop\n while(win.isOpened()){\n \/\/Clean the Windows\n win.clean();\n \/\/load the Window Events\n win.loadEvents();\n \/\/update the Views with the events pre-loaded\n win.updateViews();\n\n \/\/check if click to close de Window\n if(win.eventButtonClose()){\n \/\/close the window\n win.closeWindow();\n }\n \/\/test if release the ESC key\n if(win.eventGetKeyReleaseSize()){\n for(edk::uint32 i=0u;i<win.eventGetKeyReleaseSize();i++){\n if(win.eventGetKeyRelease(i) == edk::key::escape){\n \/\/close Window\n win.closeWindow();\n }\n }\n }\n \/\/draw the View's\n win.drawView();\n \/\/render the scene\n win.render();\n }\n \/\/remove the view from window\n win.removeSubview(&view);\n return 0;\n}\n\n<commit_msg>Forgot to change the helloEDK main<commit_after>\/*\nLibrary EDK - How to use Extensible Development Kit\nCopyright (C) 2013 Eduardo Moura Sales Martins\nThis library is free software; you can redistribute it and\/or\nmodify it under the terms of the GNU Lesser General Public\nLicense as published by the Free Software Foundation; either\nversion 2.1 of the License, or (at your option) any later version.\nThis library is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\nLesser General Public License for more details.\nYou should have received a copy of the GNU Lesser General Public\nLicense along with this library; if not, write to the Free Software\nFoundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\nemail: edimartin@gmail.com.br\n\nAV: Walmor M. de Souza 392 Casa\nGravatai RS Brazil 94065100\n*\/\n\n\/\/Include the Window\n#include \"edk\/Window.h\"\n\/\/Include the View to render Graphics\n#include \"edk\/ViewGU2D.h\"\n\/\/Include the FontMap render\n#include \"edk\/fonts\/FontMap.h\"\n\nclass RenderView: public edk::ViewGU2D{\npublic:\n RenderView(){}\n ~RenderView(){}\n void load(edk::rectf32){\n this->camera.position.x = 7;\n this->camera.position.y = -0.5f;\n this->camera.setSize(16.f,10.f);\n \/\/create the message\n text.createStringMap(\"Hello EDK World\");\n }\n void unload(){\n \/\/remove the message\n text.deleteMap();\n }\n \/\/render the scene in the vew\n void drawScene(edk::rectf32){\n \/\/draw the message\n text.draw();\n }\nprivate:\n edk::fonts::FontMap text;\n};\n\nint main(){\n edk::Window win;\n \/\/create the window with the buttons\n win.createWindow(800,600,\"EDK HELLO WORLD\",EDK_WINDOW_BUTTONS);\n \/\/set the background color fo the window\n win.cleanColor = edk::color3ui8(0,0,0);\n\n \/\/Create a view to draw the scene\n RenderView view;\n view.backgroundColor = edk::color4f32(1,1,1,1); \/\/set the viewColor\n view.frame.origin = edk::vec2f32(50,50); \/\/set the view position inside the Window View\n view.frame.size = edk::size2f32(700,500); \/\/set the size of the View\n\n \/\/add the view in the Window\n win.addSubview(&view);\n\n \/\/Loop\n while(win.isOpened()){\n \/\/Clean the Windows\n win.clean();\n \/\/load the Window Events\n win.loadEvents();\n \/\/update the Views with the events pre-loaded\n win.updateViews();\n\n \/\/check if click to close de Window\n if(win.eventButtonClose()){\n \/\/close the window\n win.closeWindow();\n }\n \/\/test if release the ESC key\n if(win.eventGetKeyReleaseSize()){\n for(edk::uint32 i=0u;i<win.eventGetKeyReleaseSize();i++){\n if(win.eventGetKeyRelease(i) == edk::key::escape){\n \/\/close Window\n win.closeWindow();\n }\n }\n }\n \/\/draw the View's\n win.drawView();\n \/\/render the scene\n win.render();\n }\n \/\/remove the view from window\n win.removeSubview(&view);\n return 0;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/**\n * This file is part of the CernVM File System.\n *\/\n\n#include \"cvmfs_config.h\"\n#include \"cmd_abort.h\"\n\n#include <cstdio>\n#include <string>\n\n#include \"logging.h\"\n#include \"publish\/cmd_util.h\"\n#include \"publish\/except.h\"\n#include \"publish\/repository.h\"\n#include \"publish\/settings.h\"\n#include \"util\/pointer.h\"\n#include \"util\/posix.h\"\n#include \"util\/string.h\"\n#include \"whitelist.h\"\n\nnamespace publish {\n\nint CmdAbort::Main(const Options &options) {\n SettingsBuilder builder;\n UniquePtr<SettingsPublisher> settings;\n try {\n settings = builder.CreateSettingsPublisher(\n options.plain_args().empty() ? \"\" : options.plain_args()[0].value_str,\n true \/* needs_managed *\/);\n } catch (const EPublish &e) {\n if ((e.failure() == EPublish::kFailRepositoryNotFound) ||\n (e.failure() == EPublish::kFailRepositoryType))\n {\n LogCvmfs(kLogCvmfs, kLogStderr | kLogSyslogErr, \"CernVM-FS error: %s\",\n e.msg().c_str());\n return 1;\n }\n throw;\n }\n\n if (settings->transaction().in_enter_session()) {\n throw EPublish(\n \"aborting a transaction is unsupported within the ephemeral \"\n \"writable shell\",\n EPublish::kFailInvocation);\n }\n\n if (!SwitchCredentials(settings->owner_uid(), settings->owner_gid(),\n false \/* temporarily *\/))\n {\n throw EPublish(\"No write permission to repository\",\n EPublish::kFailPermission);\n }\n\n if (HasPrefix(GetCurrentWorkingDirectory() + \"\/\",\n settings->transaction().spool_area().union_mnt() + \"\/\",\n false \/* ignore_case *\/))\n {\n LogCvmfs(kLogCvmfs, kLogStdout,\n \"Current working directory is in %s. Please release, \"\n \"e.g. by 'cd $HOME'.\",\n settings->transaction().spool_area().union_mnt().c_str());\n return 1;\n }\n\n if (!options.Has(\"force\")) {\n LogCvmfs(kLogCvmfs, kLogStdout | kLogNoLinebreak,\n \"You are about to DISCARD ALL CHANGES OF THE CURRENT TRANSACTION \"\n \"for %s! Are you sure (y\/N)? \", settings->fqrn().c_str());\n char answer[2];\n fgets(answer, 2, stdin);\n if ((answer[0] != 'Y') && (answer[0] != 'y'))\n return EINTR;\n }\n\n std::vector<LsofEntry> lsof_entries =\n Lsof(settings->transaction().spool_area().union_mnt());\n if (!lsof_entries.empty()) {\n if (options.Has(\"force\")) {\n LogCvmfs(kLogCvmfs, kLogStdout,\n \"WARNING: Open file descriptors on %s (possible race!)\"\n \"\\nThe following lsof report might show the culprit:\\n\",\n settings->transaction().spool_area().union_mnt().c_str());\n } else {\n LogCvmfs(kLogCvmfs, kLogStdout,\n \"\\nWARNING! There are open read-only file descriptors in %s\\n\"\n \" --> This is potentially harmful and might cause problems \"\n \"later on.\\n\"\n \" We can anyway perform the requested operation, but this \"\n \"will most likely\\n\"\n \" break other processes with open file descriptors on %s!\\n\"\n \"\\n\"\n \" The following lsof report might show the processes with \"\n \"open file handles\\n\",\n settings->transaction().spool_area().union_mnt().c_str(),\n settings->transaction().spool_area().union_mnt().c_str());\n }\n\n for (unsigned i = 0; i < lsof_entries.size(); ++i) {\n std::string owner_name;\n GetUserNameOf(lsof_entries[i].owner, &owner_name);\n LogCvmfs(kLogCvmfs, kLogStdout, \"%s %d %s %s\",\n lsof_entries[i].executable.c_str(),\n lsof_entries[i].pid,\n owner_name.c_str(),\n lsof_entries[i].path.c_str());\n }\n\n if (!options.Has(\"force\")) {\n LogCvmfs(kLogCvmfs, kLogStdout | kLogNoLinebreak,\n \"\\n Do you want to proceed anyway? (y\/N) \");\n char answer[2];\n fgets(answer, 2, stdin);\n if ((answer[0] != 'Y') && (answer[0] != 'y'))\n return EINTR;\n }\n }\n\n UniquePtr<Publisher> publisher;\n publisher = new Publisher(*settings);\n\n LogCvmfs(kLogCvmfs, kLogSyslog, \"(%s) aborting transaction\",\n settings->fqrn().c_str());\n\n int rvi = CallServerHook(\"abort_before_hook\", settings->fqrn());\n if (rvi != 0) {\n LogCvmfs(kLogCvmfs, kLogStderr | kLogSyslogErr,\n \"abort hook failed, not aborting\");\n return rvi;\n }\n\n try {\n publisher->Abort();\n } catch (const EPublish &e) {\n if (e.failure() == EPublish::kFailTransactionState) {\n LogCvmfs(kLogCvmfs, kLogStderr | kLogSyslogErr, \"%s\", e.msg().c_str());\n return EINVAL;\n }\n }\n\n rvi = CallServerHook(\"abort_after_hook\", settings->fqrn());\n if (rvi != 0) {\n LogCvmfs(kLogCvmfs, kLogStderr | kLogSyslogErr,\n \"post abort hook failed\");\n return rvi;\n }\n\n return 0;\n}\n\n} \/\/ namespace publish\n<commit_msg>[publish] Fix lsof report in abort<commit_after>\/**\n * This file is part of the CernVM File System.\n *\/\n\n#include \"cvmfs_config.h\"\n#include \"cmd_abort.h\"\n\n#include <cstdio>\n#include <string>\n\n#include \"logging.h\"\n#include \"publish\/cmd_util.h\"\n#include \"publish\/except.h\"\n#include \"publish\/repository.h\"\n#include \"publish\/settings.h\"\n#include \"util\/pointer.h\"\n#include \"util\/posix.h\"\n#include \"util\/string.h\"\n#include \"whitelist.h\"\n\nnamespace publish {\n\nint CmdAbort::Main(const Options &options) {\n SettingsBuilder builder;\n UniquePtr<SettingsPublisher> settings;\n try {\n settings = builder.CreateSettingsPublisher(\n options.plain_args().empty() ? \"\" : options.plain_args()[0].value_str,\n true \/* needs_managed *\/);\n } catch (const EPublish &e) {\n if ((e.failure() == EPublish::kFailRepositoryNotFound) ||\n (e.failure() == EPublish::kFailRepositoryType))\n {\n LogCvmfs(kLogCvmfs, kLogStderr | kLogSyslogErr, \"CernVM-FS error: %s\",\n e.msg().c_str());\n return 1;\n }\n throw;\n }\n\n if (settings->transaction().in_enter_session()) {\n throw EPublish(\n \"aborting a transaction is unsupported within the ephemeral \"\n \"writable shell\",\n EPublish::kFailInvocation);\n }\n\n if (!SwitchCredentials(settings->owner_uid(), settings->owner_gid(),\n false \/* temporarily *\/))\n {\n throw EPublish(\"No write permission to repository\",\n EPublish::kFailPermission);\n }\n\n if (HasPrefix(GetCurrentWorkingDirectory() + \"\/\",\n settings->transaction().spool_area().union_mnt() + \"\/\",\n false \/* ignore_case *\/))\n {\n LogCvmfs(kLogCvmfs, kLogStdout,\n \"Current working directory is in %s. Please release, \"\n \"e.g. by 'cd $HOME'.\",\n settings->transaction().spool_area().union_mnt().c_str());\n return 1;\n }\n\n if (!options.Has(\"force\")) {\n LogCvmfs(kLogCvmfs, kLogStdout | kLogNoLinebreak,\n \"You are about to DISCARD ALL CHANGES OF THE CURRENT TRANSACTION \"\n \"for %s! Are you sure (y\/N)? \", settings->fqrn().c_str());\n char answer[3];\n fgets(answer, 3, stdin);\n if ((answer[0] != 'Y') && (answer[0] != 'y'))\n return EINTR;\n }\n\n std::vector<LsofEntry> lsof_entries =\n Lsof(settings->transaction().spool_area().union_mnt());\n if (!lsof_entries.empty()) {\n if (options.Has(\"force\")) {\n LogCvmfs(kLogCvmfs, kLogStdout,\n \"WARNING: Open file descriptors on %s (possible race!)\"\n \"\\nThe following lsof report might show the culprit:\\n\",\n settings->transaction().spool_area().union_mnt().c_str());\n } else {\n LogCvmfs(kLogCvmfs, kLogStdout,\n \"\\nWARNING! There are open read-only file descriptors in %s\\n\"\n \" --> This is potentially harmful and might cause problems \"\n \"later on.\\n\"\n \" We can anyway perform the requested operation, but this \"\n \"will most likely\\n\"\n \" break other processes with open file descriptors on %s!\\n\"\n \"\\n\"\n \" The following lsof report might show the processes with \"\n \"open file handles\\n\",\n settings->transaction().spool_area().union_mnt().c_str(),\n settings->transaction().spool_area().union_mnt().c_str());\n }\n\n for (unsigned i = 0; i < lsof_entries.size(); ++i) {\n std::string owner_name;\n GetUserNameOf(lsof_entries[i].owner, &owner_name);\n LogCvmfs(kLogCvmfs, kLogStdout, \"%s %d %s %s\",\n lsof_entries[i].executable.c_str(),\n lsof_entries[i].pid,\n owner_name.c_str(),\n lsof_entries[i].path.c_str());\n }\n\n if (!options.Has(\"force\")) {\n LogCvmfs(kLogCvmfs, kLogStdout | kLogNoLinebreak,\n \"\\n Do you want to proceed anyway? (y\/N) \");\n char answer[3];\n fgets(answer, 3, stdin);\n if ((answer[0] != 'Y') && (answer[0] != 'y'))\n return EINTR;\n }\n }\n\n UniquePtr<Publisher> publisher;\n publisher = new Publisher(*settings);\n\n LogCvmfs(kLogCvmfs, kLogSyslog, \"(%s) aborting transaction\",\n settings->fqrn().c_str());\n\n int rvi = CallServerHook(\"abort_before_hook\", settings->fqrn());\n if (rvi != 0) {\n LogCvmfs(kLogCvmfs, kLogStderr | kLogSyslogErr,\n \"abort hook failed, not aborting\");\n return rvi;\n }\n\n try {\n publisher->Abort();\n } catch (const EPublish &e) {\n if (e.failure() == EPublish::kFailTransactionState) {\n LogCvmfs(kLogCvmfs, kLogStderr | kLogSyslogErr, \"%s\", e.msg().c_str());\n return EINVAL;\n }\n }\n\n rvi = CallServerHook(\"abort_after_hook\", settings->fqrn());\n if (rvi != 0) {\n LogCvmfs(kLogCvmfs, kLogStderr | kLogSyslogErr,\n \"post abort hook failed\");\n return rvi;\n }\n\n return 0;\n}\n\n} \/\/ namespace publish\n<|endoftext|>"} {"text":"<commit_before>\/\/ dllmain.cpp : Defines the entry point for the DLL application.\n\/\/ Programmed by jasonfish4\n\/* The excessive use of global variables is due to me not wanting to consume stack space, overuse registers, etc...\nwithin an exception signaling function *\/\n\n#define _CRT_SECURE_NO_DEPRECATE\n\n#include \"stdafx.h\"\n#include \"Dispatcher\\rvdbg.h\"\n#include \"Dispatcher\\exceptiondispatcher.h\"\n#include \"dbgredefs.h\"\n#include \"debugoutput.h\"\n#include <winsock.h>\n#include <cstdlib>\n#include <string>\n#include <unordered_map>\n#include <array>\n#include <iostream>\n#include <sstream>\n\n#pragma comment(lib, \"wsock32.lib\")\ntypedef void(*str_comparator_function)();\nvoid protocol_gui_func();\nvoid str_breakpoint();\nvoid str_imode();\nvoid str_pmode();\nvoid str_dbg_get();\nvoid str_dbg_display_regs();\nvoid str_xmmf_display();\nvoid str_xmmd_display();\nvoid str_dbg_run();\n\nconst char* g_module_name; \/\/ Name of the image\nconst char* g_ext_module_name; \/\/ Name of the copy image\nconst char* g_file_path; \/\/ File location to copy image\nstd::uint32_t g_server;\nstd::uint8_t g_protocol_interface;\nstd::uint32_t symbol;\nsockaddr_in g_server_address;\nstd::array<void*, 2> g_threads;\n\nconst std::unordered_map<char, rvdbg::sse_register> xmm_register_map = {\n\t{ '0', rvdbg::sse_register::xmm0 },\n\t{ '1', rvdbg::sse_register::xmm1 },\n\t{ '2', rvdbg::sse_register::xmm2 },\n\t{ '3', rvdbg::sse_register::xmm3 },\n\t{ '4', rvdbg::sse_register::xmm4 },\n\t{ '5', rvdbg::sse_register::xmm5 },\n\t{ '6', rvdbg::sse_register::xmm6 },\n\t{ '7', rvdbg::sse_register::xmm7 }\n};\n\nconst std::unordered_map<char, rvdbg::gp_reg_32> general_register_map = {\n\t{ '0', rvdbg::gp_reg_32::eax },\n\t{ '1', rvdbg::gp_reg_32::ebx },\n\t{ '2', rvdbg::gp_reg_32::ecx },\n\t{ '3', rvdbg::gp_reg_32::edx },\n\t{ '4', rvdbg::gp_reg_32::edi },\n\t{ '5', rvdbg::gp_reg_32::esi },\n\t{ '6', rvdbg::gp_reg_32::ebp },\n\t{ '7', rvdbg::gp_reg_32::esp },\n\t{ '8', rvdbg::gp_reg_32::eip }\n};\n\nconst std::unordered_map<std::string, str_comparator_function> opt_func_table = {\n\t{ std::string(\"**ProtocolGUI\"), &protocol_gui_func },\n\t{ std::string(\"!Breakpoint\"), &str_breakpoint },\n\t{ std::string(\"imode\"), &str_imode },\n\t{ std::string(\"pmode\"), &str_pmode },\n\t{ std::string(\"!DbgGet\"), &str_dbg_get },\n\t{ std::string(\"!DbgDisplayRegisters\"), &str_dbg_display_regs },\n\t{ std::string(\"!xmm-f\"), &str_xmmf_display },\n\t{ std::string(\"!xmm-d\"), &str_xmmd_display },\n\t{ std::string(\"!DbgRun\"), &str_dbg_run },\n};\n\nvoid register_value(char key, std::uint32_t value)\n{\n\trvdbg::set_register(static_cast<std::uint32_t>(general_register_map.at(key)), value);\n}\n\nvoid register_value_fp(char key, bool precision, double value)\n{\n\trvdbg::set_register_fp(static_cast<std::uint32_t>(xmm_register_map.at(key)), precision, value);\n}\n\nvoid protocol_gui_func()\n{\n\tg_protocol_interface = 1;\n}\n\nvoid str_imode()\n{\n\trvdbg::set_exception_mode(dispatcher::exception_type::immediate_exception);\n}\n\nvoid str_pmode()\n{\n\trvdbg::set_exception_mode(dispatcher::exception_type::page_exception);\n}\n\nvoid str_dbg_get()\n{\n\tdbg_io::send_dbg_get(g_server, rvdbg::get_exception_mode(), rvdbg::get_current_section());\n}\n\n\nvoid str_dbg_display_regs()\n{\n\tdbg_io::send_dbg_registers(g_server, g_protocol_interface, rvdbg::get_dbg_exception_address(), rvdbg::get_registers());\n}\n\nvoid str_xmmf_display()\n{\n\tdbg_io::send_dbg_registers(g_server, 2, rvdbg::get_dbg_exception_address(), rvdbg::get_registers());\n}\n\nvoid str_xmmd_display()\n{\n\tdbg_io::send_dbg_registers(g_server, 3, rvdbg::get_dbg_exception_address(), rvdbg::get_registers());\n}\n\nvoid str_dbg_run()\n{\n\tif (rvdbg::is_aeh_present())\n\t{\n\t\trvdbg::continue_debugger();\n\t}\n}\n\nvoid str_breakpoint()\n{\n\tstd::size_t exception_element = dispatcher::check_sector(rvdbg::get_sector());\n\tMEMORY_BASIC_INFORMATION mbi;\n\tif (VirtualQuery(reinterpret_cast<void*>(symbol), &mbi, sizeof(mbi)) != dbg_redef::nullval)\n\t{\n\t\tif (mbi.Protect != static_cast<unsigned long>(dbg_redef::page_protection::page_na))\n\t\t{\n\t\t\tdispatcher::add_exception(rvdbg::get_sector(), exception_element, rvdbg::get_exception_mode(), symbol);\n\t\t}\n\t}\n}\n\nvoid str_get(std::array<char, 128>& snbuffer, std::size_t index)\n{\n\tif (index < rvdbg::get_sector_size())\n\t{\n\t\tstd::snprintf(snbuffer.data(), snbuffer.size(), \"$ symbol: 0x%02X\\r\\n index:%d\\r\\n\", symbol, index);\n\t\tsend(g_server, snbuffer.data(), snbuffer.size(), 0);\n\t}\n\telse\n\t{\n\t\tsend(g_server, \"$ symbol not registered\", sizeof(\"$ symbol not registered\"), 0);\n\t}\n}\n\nvoid dbg_undo(std::size_t index)\n{\n\tif (index < rvdbg::get_sector_size())\n\t{\n\t\tstd::uint32_t old_protect;\n\t\tswitch (rvdbg::get_exception_mode())\n\t\t{\n\t\tcase dispatcher::exception_type::immediate_exception:\n\t\t\tVirtualProtect(reinterpret_cast<void*>(rvdbg::get_sector()[index].dbg_exception_address),\n\t\t\t\t1, static_cast<unsigned long>(dbg_redef::page_protection::page_xrw), reinterpret_cast<unsigned long*>(&old_protect));\n\n\t\t\t*reinterpret_cast<std::uint32_t*>(rvdbg::get_sector()[index].dbg_exception_address) = (rvdbg::get_sector()[index].save_code);\n\n\t\t\tVirtualProtect(reinterpret_cast<void*>(rvdbg::get_sector()[index].dbg_exception_address), 1, \n\t\t\t\told_protect, reinterpret_cast<unsigned long*>(&old_protect));\n\n\t\t\tdispatcher::unlock_sector(rvdbg::get_sector(), index);\n\t\t\tbreak;\n\n\t\tcase dispatcher::exception_type::access_exception:\n\t\t\t\/* UNIMPLEMENTED *\/\n\t\tcase dispatcher::exception_type::page_exception:\n\t\t\tVirtualProtect(reinterpret_cast<void*>(rvdbg::get_sector()[index].dbg_exception_address), 1, \n\t\t\t\trvdbg::get_sector()[index].save_code, reinterpret_cast<unsigned long*>(&old_protect));\n\n\t\t\tdispatcher::unlock_sector(rvdbg::get_sector(), index);\n\t\t\tbreak;\n\t\t}\n\t}\n}\n\nunsigned long __stdcall dbg_synchronization(void* lpParam)\n{\n\twhile (true)\n\t{\n\t\tif (rvdbg::debugger == false)\n\t\t{\n\t\t\tEnterCriticalSection(&rvdbg::repr);\n\t\t\tSleepConditionVariableCS(&rvdbg::reprcondition, &rvdbg::repr, dbg_redef::infinite);\n\t\t\tLeaveCriticalSection(&rvdbg::repr);\n\t\t}\n\t\tif (rvdbg::debugger == true)\n\t\t{\n\t\t\tsend(g_server, \"!DbgModeOn\", strlen(\"!DbgModeOn\"), 0);\n\t\t\trvdbg::debugger = false;\n\t\t}\n\t}\n}\n\nunsigned long __stdcall dispatch_initializer(void* lpParam)\n{\t\n\tWSAData wsa_data;\n\tWSAStartup(MAKEWORD(2, 2), &wsa_data);\n\n\tg_server = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);\n\tg_server_address = { 0 };\n\tg_server_address.sin_addr.s_addr = inet_addr(\"127.0.0.1\");\n\tg_server_address.sin_port = htons(8888);\n\tg_server_address.sin_family = AF_INET;\n\tconnect(g_server, reinterpret_cast<sockaddr*>(&g_server_address), sizeof(g_server_address));\n\n\trvdbg::attach_debugger();\n\trvdbg::set_module(false, g_module_name, g_ext_module_name);\n\trvdbg::set_pause_mode(rvdbg::suspension_mode::suspend_all);\n\trvdbg::assign_thread(g_threads[0]);\n\trvdbg::assign_thread(g_threads[1]);\n\n\tstd::array<char, 128> buffer;\n\tstd::array<char, 128> snbuffer;\n\tstd::istringstream dbg_conversion_stream;\n\n\twhile (true)\n\t{\n\t\tbuffer.fill('\\0');\n\t\tsnbuffer.fill('\\0');\n\t\trecv(g_server, buffer.data(), buffer.size(), 0);\n\n\t\tstd::string receiver;\n\t\treceiver = std::string(buffer.data());\n\t\t\n\t\ttry\n\t\t{\n\t\t\tstr_comparator_function local_func = opt_func_table.at(receiver);\n\t\t\tlocal_func();\n\t\t}\n\t\tcatch (std::out_of_range& e)\n\t\t{\n\t\t\tstd::cerr << \"end of map reached, string being compared is used for parsing\\n\";\n\n\t\t\tif (receiver.substr(0, std::string(\"!Symbol @\").size()) == std::string(\"!Symbol @\"))\n\t\t\t{\n\t\t\t\tif (!receiver.substr(sizeof(\"!Symbol @ \"), receiver.size()).empty())\n\t\t\t\t{\n\t\t\t\t\tstd::sscanf(receiver.substr(sizeof(\"!Symbol @ \"), receiver.size()).c_str(), \"%X\", &symbol);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\telse if (receiver.substr(0, std::string(\"!setreg\").size()) == std::string(\"!setreg\"))\n\t\t\t{\n\t\t\t\tstd::uint32_t regv;\n\t\t\t\tdbg_conversion_stream.str(receiver.substr(std::string(\"!setreg ? \").size(), receiver.size()));\n\t\t\t\tdbg_conversion_stream >> std::hex >> regv;\n\t\t\t\tregister_value(receiver.at(std::string(\"!setreg \").size()), regv);\n\t\t\t}\n\n\t\t\telse if (receiver.substr(0, std::string(\"!fsetreg\").size()) == std::string(\"!fsetreg\"))\n\t\t\t{\n\t\t\t\tdouble regv;\n\t\t\t\tdbg_conversion_stream.str(receiver.substr(std::string(\"!fsetreg ? \").size(), receiver.size()));\n\t\t\t\tdbg_conversion_stream >> regv;\n\t\t\t\tregister_value_fp(receiver.at(std::string(\"!fsetreg \").size()), 0, regv);\n\t\t\t}\n\n\t\t\telse if (receiver.substr(0, std::string(\"!dsetreg\").size()) == std::string(\"!dsetreg\"))\n\t\t\t{\n\t\t\t\tdouble regv;\n\t\t\t\tdbg_conversion_stream.str((receiver.substr(std::string(\"!dsetreg ? \").size(), receiver.size())));\n\t\t\t\tdbg_conversion_stream >> regv;\n\t\t\t\tregister_value_fp(receiver.at(std::string(\"!dsetreg \").size()), 1, regv);\n\t\t\t}\n\n\t\t\telse if (receiver.substr(0, std::string(\"!Undo \").size()) == std::string(\"!Undo \"))\n\t\t\t{\n\t\t\t\tstd::size_t index;\n\t\t\t\tdbg_conversion_stream.str(receiver.substr(std::string(\"!Undo \").size(), receiver.size()));\n\t\t\t\tdbg_conversion_stream >> index;\n\t\t\t\tdbg_undo(index);\n\t\t\t}\n\n\t\t\telse if (receiver == std::string(\"!Get\"))\n\t\t\t{\n\t\t\t\tstd::size_t index = dispatcher::search_sector(rvdbg::get_sector(), symbol);\n\t\t\t\tstr_get(snbuffer, index);\n\t\t\t}\n\n\t\t\telse if (receiver == std::string(\"!Exit\"))\n\t\t\t{\n\t\t\t\tstr_dbg_run();\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\n\trvdbg::detach_debugger();\n\trvdbg::remove_thread(g_threads[0]);\n\trvdbg::remove_thread(g_threads[1]);\n\tclosesocket(g_server);\n\tWSACleanup();\n\tTerminateThread(g_threads[0], 0);\n\treturn 0;\n}\n\nBOOL APIENTRY DllMain(HMODULE hModule, std::uint32_t ul_reason_for_call, void* lpReserved)\n{\n\tswitch (ul_reason_for_call)\n\t{\n\tcase DLL_PROCESS_ATTACH:\n\n\t\tif (use_module) \/\/ currently off by default\n\t\t{\n\t\t\tdll_inject(GetCurrentProcessId(), g_file_path);\n\t\t}\n\n\t\tAllocConsole();\n\t\tfreopen(\"CONOUT$\", \"w\", stdout);\n\t\tfreopen(\"CONOUT$\", \"w\", stderr);\n\t\tInitializeCriticalSection(&rvdbg::repr);\n\t\tInitializeConditionVariable(&rvdbg::reprcondition);\n\t\tg_threads[0] = CreateThread(0, 0, dbg_synchronization, 0, 0, 0);\n\t\tg_threads[1] = CreateThread(0, 0, dispatch_initializer, 0, 0, 0);\n\tcase DLL_THREAD_ATTACH:\n\tcase DLL_THREAD_DETACH:\n\tcase DLL_PROCESS_DETACH:\n\t\tbreak;\n\t}\n\treturn TRUE;\n}\n<commit_msg>Update dllmain.cpp<commit_after>\/\/ dllmain.cpp : Defines the entry point for the DLL application.\n\/\/ Programmed by jasonfish4\n\/* The excessive use of global variables is due to me not wanting to consume stack space, overuse registers, etc...\nwithin an exception signaling function *\/\n\n#define _CRT_SECURE_NO_DEPRECATE\n\n#include \"stdafx.h\"\n#include \"Dispatcher\\rvdbg.h\"\n#include \"Dispatcher\\exceptiondispatcher.h\"\n#include \"dbgredefs.h\"\n#include \"debugoutput.h\"\n#include <winsock.h>\n#include <cstdlib>\n#include <string>\n#include <unordered_map>\n#include <array>\n#include <iostream>\n#include <sstream>\n\n#pragma comment(lib, \"wsock32.lib\")\ntypedef void(*str_comparator_function)();\nvoid protocol_gui_func();\nvoid str_breakpoint();\nvoid str_imode();\nvoid str_pmode();\nvoid str_dbg_get();\nvoid str_dbg_display_regs();\nvoid str_xmmf_display();\nvoid str_xmmd_display();\nvoid str_dbg_run();\n\nconst char* g_module_name; \/\/ Name of the image\nconst char* g_ext_module_name; \/\/ Name of the copy image\nconst char* g_file_path; \/\/ File location to copy image\nstd::uint32_t g_server;\nstd::uint8_t g_protocol_interface;\nstd::uint32_t symbol;\nsockaddr_in g_server_address;\nstd::array<void*, 2> g_threads;\n\nconst std::unordered_map<char, rvdbg::sse_register> xmm_register_map = {\n\t{ '0', rvdbg::sse_register::xmm0 },\n\t{ '1', rvdbg::sse_register::xmm1 },\n\t{ '2', rvdbg::sse_register::xmm2 },\n\t{ '3', rvdbg::sse_register::xmm3 },\n\t{ '4', rvdbg::sse_register::xmm4 },\n\t{ '5', rvdbg::sse_register::xmm5 },\n\t{ '6', rvdbg::sse_register::xmm6 },\n\t{ '7', rvdbg::sse_register::xmm7 }\n};\n\nconst std::unordered_map<char, rvdbg::gp_reg_32> general_register_map = {\n\t{ '0', rvdbg::gp_reg_32::eax },\n\t{ '1', rvdbg::gp_reg_32::ebx },\n\t{ '2', rvdbg::gp_reg_32::ecx },\n\t{ '3', rvdbg::gp_reg_32::edx },\n\t{ '4', rvdbg::gp_reg_32::edi },\n\t{ '5', rvdbg::gp_reg_32::esi },\n\t{ '6', rvdbg::gp_reg_32::ebp },\n\t{ '7', rvdbg::gp_reg_32::esp },\n\t{ '8', rvdbg::gp_reg_32::eip }\n};\n\nconst std::unordered_map<std::string, str_comparator_function> opt_func_table = {\n\t{ std::string(\"**ProtocolGUI\"), &protocol_gui_func },\n\t{ std::string(\"!Breakpoint\"), &str_breakpoint },\n\t{ std::string(\"imode\"), &str_imode },\n\t{ std::string(\"pmode\"), &str_pmode },\n\t{ std::string(\"!DbgGet\"), &str_dbg_get },\n\t{ std::string(\"!DbgDisplayRegisters\"), &str_dbg_display_regs },\n\t{ std::string(\"!xmm-f\"), &str_xmmf_display },\n\t{ std::string(\"!xmm-d\"), &str_xmmd_display },\n\t{ std::string(\"!DbgRun\"), &str_dbg_run },\n};\n\nvoid register_value(char key, std::uint32_t value)\n{\n\trvdbg::set_register(static_cast<std::uint32_t>(general_register_map.at(key)), value);\n}\n\nvoid register_value_fp(char key, bool precision, double value)\n{\n\trvdbg::set_register_fp(static_cast<std::uint32_t>(xmm_register_map.at(key)), precision, value);\n}\n\nvoid protocol_gui_func()\n{\n\tg_protocol_interface = 1;\n}\n\nvoid str_imode()\n{\n\trvdbg::set_exception_mode(dispatcher::exception_type::immediate_exception);\n}\n\nvoid str_pmode()\n{\n\trvdbg::set_exception_mode(dispatcher::exception_type::page_exception);\n}\n\nvoid str_dbg_get()\n{\n\tdbg_io::send_dbg_get(g_server, rvdbg::get_exception_mode(), rvdbg::get_current_section());\n}\n\n\nvoid str_dbg_display_regs()\n{\n\tdbg_io::send_dbg_registers(g_server, g_protocol_interface, rvdbg::get_dbg_exception_address(), rvdbg::get_registers());\n}\n\nvoid str_xmmf_display()\n{\n\tdbg_io::send_dbg_registers(g_server, 2, rvdbg::get_dbg_exception_address(), rvdbg::get_registers());\n}\n\nvoid str_xmmd_display()\n{\n\tdbg_io::send_dbg_registers(g_server, 3, rvdbg::get_dbg_exception_address(), rvdbg::get_registers());\n}\n\nvoid str_dbg_run()\n{\n\tif (rvdbg::is_aeh_present())\n\t{\n\t\trvdbg::continue_debugger();\n\t}\n}\n\nvoid str_breakpoint()\n{\n\tstd::size_t exception_element = dispatcher::check_sector(rvdbg::get_sector());\n\tMEMORY_BASIC_INFORMATION mbi;\n\tif (VirtualQuery(reinterpret_cast<void*>(symbol), &mbi, sizeof(mbi)) != dbg_redef::nullval)\n\t{\n\t\tif (mbi.Protect != static_cast<unsigned long>(dbg_redef::page_protection::page_na))\n\t\t{\n\t\t\tdispatcher::add_exception(rvdbg::get_sector(), exception_element, rvdbg::get_exception_mode(), symbol);\n\t\t}\n\t}\n}\n\nvoid str_get(std::array<char, 128>& snbuffer, std::size_t index)\n{\n\tif (index < rvdbg::get_sector_size())\n\t{\n\t\tstd::snprintf(snbuffer.data(), snbuffer.size(), \"$ symbol: 0x%02X\\r\\n index:%d\\r\\n\", symbol, index);\n\t\tsend(g_server, snbuffer.data(), snbuffer.size(), 0);\n\t}\n\telse\n\t{\n\t\tsend(g_server, \"$ symbol not registered\", sizeof(\"$ symbol not registered\"), 0);\n\t}\n}\n\nvoid dbg_undo(std::size_t index)\n{\n\tif (index < rvdbg::get_sector_size())\n\t{\n\t\tstd::uint32_t old_protect;\n\t\tswitch (rvdbg::get_exception_mode())\n\t\t{\n\t\tcase dispatcher::exception_type::immediate_exception:\n\t\t\tVirtualProtect(reinterpret_cast<void*>(rvdbg::get_sector()[index].dbg_exception_address),\n\t\t\t\t1, static_cast<unsigned long>(dbg_redef::page_protection::page_xrw), reinterpret_cast<unsigned long*>(&old_protect));\n\n\t\t\t*reinterpret_cast<std::uint32_t*>(rvdbg::get_sector()[index].dbg_exception_address) = (rvdbg::get_sector()[index].save_code);\n\n\t\t\tVirtualProtect(reinterpret_cast<void*>(rvdbg::get_sector()[index].dbg_exception_address), 1, \n\t\t\t\told_protect, reinterpret_cast<unsigned long*>(&old_protect));\n\n\t\t\tdispatcher::unlock_sector(rvdbg::get_sector(), index);\n\t\t\tbreak;\n\n\t\tcase dispatcher::exception_type::access_exception:\n\t\t\t\/* UNIMPLEMENTED *\/\n\t\tcase dispatcher::exception_type::page_exception:\n\t\t\tVirtualProtect(reinterpret_cast<void*>(rvdbg::get_sector()[index].dbg_exception_address), 1, \n\t\t\t\trvdbg::get_sector()[index].save_code, reinterpret_cast<unsigned long*>(&old_protect));\n\n\t\t\tdispatcher::unlock_sector(rvdbg::get_sector(), index);\n\t\t\tbreak;\n\t\t}\n\t}\n}\n\nunsigned long __stdcall dbg_synchronization(void* lpParam)\n{\n\twhile (true)\n\t{\n\t\tif (rvdbg::debugger == false)\n\t\t{\n\t\t\tEnterCriticalSection(&rvdbg::repr);\n\t\t\tSleepConditionVariableCS(&rvdbg::reprcondition, &rvdbg::repr, dbg_redef::infinite);\n\t\t\tLeaveCriticalSection(&rvdbg::repr);\n\t\t}\n\t\telse if (rvdbg::debugger == true)\n\t\t{\n\t\t\tsend(g_server, \"!DbgModeOn\", strlen(\"!DbgModeOn\"), 0);\n\t\t\trvdbg::debugger = false;\n\t\t}\n\t}\n}\n\nunsigned long __stdcall dispatch_initializer(void* lpParam)\n{\t\n\tWSAData wsa_data;\n\tWSAStartup(MAKEWORD(2, 2), &wsa_data);\n\n\tg_server = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);\n\tg_server_address = { 0 };\n\tg_server_address.sin_addr.s_addr = inet_addr(\"127.0.0.1\");\n\tg_server_address.sin_port = htons(8888);\n\tg_server_address.sin_family = AF_INET;\n\tconnect(g_server, reinterpret_cast<sockaddr*>(&g_server_address), sizeof(g_server_address));\n\n\trvdbg::attach_debugger();\n\trvdbg::set_module(false, g_module_name, g_ext_module_name);\n\trvdbg::set_pause_mode(rvdbg::suspension_mode::suspend_all);\n\trvdbg::assign_thread(g_threads[0]);\n\trvdbg::assign_thread(g_threads[1]);\n\n\tstd::array<char, 128> buffer;\n\tstd::array<char, 128> snbuffer;\n\tstd::istringstream dbg_conversion_stream;\n\n\twhile (true)\n\t{\n\t\tbuffer.fill('\\0');\n\t\tsnbuffer.fill('\\0');\n\t\trecv(g_server, buffer.data(), buffer.size(), 0);\n\n\t\tstd::string receiver;\n\t\treceiver = std::string(buffer.data());\n\t\t\n\t\ttry\n\t\t{\n\t\t\tstr_comparator_function local_func = opt_func_table.at(receiver);\n\t\t\tlocal_func();\n\t\t}\n\t\tcatch (std::out_of_range& e)\n\t\t{\n\t\t\tstd::cerr << \"end of map reached, string being compared is used for parsing\\n\";\n\n\t\t\tif (receiver.substr(0, std::string(\"!Symbol @\").size()) == std::string(\"!Symbol @\"))\n\t\t\t{\n\t\t\t\tif (!receiver.substr(sizeof(\"!Symbol @ \"), receiver.size()).empty())\n\t\t\t\t{\n\t\t\t\t\tstd::sscanf(receiver.substr(sizeof(\"!Symbol @ \"), receiver.size()).c_str(), \"%X\", &symbol);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\telse if (receiver.substr(0, std::string(\"!setreg\").size()) == std::string(\"!setreg\"))\n\t\t\t{\n\t\t\t\tstd::uint32_t regv;\n\t\t\t\tdbg_conversion_stream.str(receiver.substr(std::string(\"!setreg ? \").size(), receiver.size()));\n\t\t\t\tdbg_conversion_stream >> std::hex >> regv;\n\t\t\t\tregister_value(receiver.at(std::string(\"!setreg \").size()), regv);\n\t\t\t}\n\n\t\t\telse if (receiver.substr(0, std::string(\"!fsetreg\").size()) == std::string(\"!fsetreg\"))\n\t\t\t{\n\t\t\t\tdouble regv;\n\t\t\t\tdbg_conversion_stream.str(receiver.substr(std::string(\"!fsetreg ? \").size(), receiver.size()));\n\t\t\t\tdbg_conversion_stream >> regv;\n\t\t\t\tregister_value_fp(receiver.at(std::string(\"!fsetreg \").size()), 0, regv);\n\t\t\t}\n\n\t\t\telse if (receiver.substr(0, std::string(\"!dsetreg\").size()) == std::string(\"!dsetreg\"))\n\t\t\t{\n\t\t\t\tdouble regv;\n\t\t\t\tdbg_conversion_stream.str((receiver.substr(std::string(\"!dsetreg ? \").size(), receiver.size())));\n\t\t\t\tdbg_conversion_stream >> regv;\n\t\t\t\tregister_value_fp(receiver.at(std::string(\"!dsetreg \").size()), 1, regv);\n\t\t\t}\n\n\t\t\telse if (receiver.substr(0, std::string(\"!Undo \").size()) == std::string(\"!Undo \"))\n\t\t\t{\n\t\t\t\tstd::size_t index;\n\t\t\t\tdbg_conversion_stream.str(receiver.substr(std::string(\"!Undo \").size(), receiver.size()));\n\t\t\t\tdbg_conversion_stream >> index;\n\t\t\t\tdbg_undo(index);\n\t\t\t}\n\n\t\t\telse if (receiver == std::string(\"!Get\"))\n\t\t\t{\n\t\t\t\tstd::size_t index = dispatcher::search_sector(rvdbg::get_sector(), symbol);\n\t\t\t\tstr_get(snbuffer, index);\n\t\t\t}\n\n\t\t\telse if (receiver == std::string(\"!Exit\"))\n\t\t\t{\n\t\t\t\tstr_dbg_run();\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\n\trvdbg::detach_debugger();\n\trvdbg::remove_thread(g_threads[0]);\n\trvdbg::remove_thread(g_threads[1]);\n\tclosesocket(g_server);\n\tWSACleanup();\n\tTerminateThread(g_threads[0], 0);\n\treturn 0;\n}\n\nBOOL APIENTRY DllMain(HMODULE hModule, std::uint32_t ul_reason_for_call, void* lpReserved)\n{\n\tswitch (ul_reason_for_call)\n\t{\n\tcase DLL_PROCESS_ATTACH:\n\n\t\tif (use_module) \/\/ currently off by default\n\t\t{\n\t\t\tdll_inject(GetCurrentProcessId(), g_file_path);\n\t\t}\n\n\t\tAllocConsole();\n\t\tfreopen(\"CONOUT$\", \"w\", stdout);\n\t\tfreopen(\"CONOUT$\", \"w\", stderr);\n\t\tInitializeCriticalSection(&rvdbg::repr);\n\t\tInitializeConditionVariable(&rvdbg::reprcondition);\n\t\tg_threads[0] = CreateThread(0, 0, dbg_synchronization, 0, 0, 0);\n\t\tg_threads[1] = CreateThread(0, 0, dispatch_initializer, 0, 0, 0);\n\tcase DLL_THREAD_ATTACH:\n\tcase DLL_THREAD_DETACH:\n\tcase DLL_PROCESS_DETACH:\n\t\tbreak;\n\t}\n\treturn TRUE;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/RUN: bash make -C %p\/..\/clang\/test\/ CLANG=%p\/clangTestUnloader.sh \n<commit_msg>Adjust to the test with the correct vars.<commit_after>\/\/RUN: make -C %testexecdir\/..\/..\/clang\/ test TESTSUITE=Sema CLANG=%p\/clangTestUnloader.sh\n<|endoftext|>"} {"text":"<commit_before>\/******************************************************************************\n\n This source file is part of the tomviz project.\n\n Copyright Kitware, Inc.\n\n This source code is released under the New BSD License, (the \"License\").\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n\n******************************************************************************\/\n#include \"ModuleSlice.h\"\n\n#include \"DataSource.h\"\n#include \"pqProxiesWidget.h\"\n#include \"pqCoreUtilities.h\"\n#include \"Utilities.h\"\n\n#include \"vtkAlgorithm.h\"\n#include \"vtkCommand.h\"\n#include \"vtkNonOrthoImagePlaneWidget.h\"\n#include \"vtkDataObject.h\"\n#include \"vtkNew.h\"\n#include \"vtkProperty.h\"\n#include \"vtkPVArrayInformation.h\"\n#include \"vtkPVDataInformation.h\"\n#include \"vtkPVDataSetAttributesInformation.h\"\n#include \"vtkRenderWindow.h\"\n#include \"vtkRenderWindowInteractor.h\"\n#include \"vtkScalarsToColors.h\"\n#include \"vtkSMParaViewPipelineControllerWithRendering.h\"\n#include \"vtkSMPropertyHelper.h\"\n#include \"vtkSMPVRepresentationProxy.h\"\n#include \"vtkSMRenderViewProxy.h\"\n#include \"vtkSMSessionProxyManager.h\"\n#include \"vtkSMSourceProxy.h\"\n#include \"vtkSMTransferFunctionManager.h\"\n#include \"vtkSMTransferFunctionProxy.h\"\n#include \"vtkSMViewProxy.h\"\n\n#include <QDebug>\n\nnamespace tomviz\n{\n\n\/\/-----------------------------------------------------------------------------\nModuleSlice::ModuleSlice(QObject* parentObject) : Superclass(parentObject)\n{\n}\n\n\/\/-----------------------------------------------------------------------------\nModuleSlice::~ModuleSlice()\n{\n this->finalize();\n}\n\n\/\/-----------------------------------------------------------------------------\nQIcon ModuleSlice::icon() const\n{\n return QIcon(\":\/pqWidgets\/Icons\/pqSlice24.png\");\n}\n\n\/\/-----------------------------------------------------------------------------\nbool ModuleSlice::initialize(DataSource* data, vtkSMViewProxy* vtkView)\n{\n if (!this->Superclass::initialize(data, vtkView))\n {\n return false;\n }\n\n vtkNew<vtkSMParaViewPipelineControllerWithRendering> controller;\n vtkSMSourceProxy* producer = data->producer();\n vtkSMSessionProxyManager* pxm = producer->GetSessionProxyManager();\n\n \/\/ Create the pass through filter.\n vtkSmartPointer<vtkSMProxy> proxy;\n proxy.TakeReference(pxm->NewProxy(\"filters\", \"PassThrough\"));\n \n \/\/ Create the Properties panel proxy\n this->PropsPanelProxy.TakeReference(\n pxm->NewProxy(\"tomviz_proxies\", \"NonOrthogonalSlice\"));\n\n pqCoreUtilities::connect(\n this->PropsPanelProxy, vtkCommand::PropertyModifiedEvent,\n this, SLOT(onPropertyChanged()));\n\n this->PassThrough = vtkSMSourceProxy::SafeDownCast(proxy);\n Q_ASSERT(this->PassThrough);\n controller->PreInitializeProxy(this->PassThrough);\n vtkSMPropertyHelper(this->PassThrough, \"Input\").Set(producer);\n controller->PostInitializeProxy(this->PassThrough);\n controller->RegisterPipelineProxy(this->PassThrough);\n\n \/\/Create the widget\n const bool widgetSetup = this->setupWidget(vtkView,producer);\n\n if(widgetSetup)\n {\n this->Widget->On();\n this->Widget->InteractionOn();\n }\n\n Q_ASSERT(this->Widget);\n return widgetSetup;\n}\n\n\n\/\/-----------------------------------------------------------------------------\n\/\/should only be called from initialize after the PassThrough has been setup\nbool ModuleSlice::setupWidget(vtkSMViewProxy* vtkView, vtkSMSourceProxy* producer)\n{\n vtkAlgorithm* passThroughAlg = vtkAlgorithm::SafeDownCast(\n this->PassThrough->GetClientSideObject());\n\n vtkRenderWindowInteractor* rwi = vtkView->GetRenderWindow()->GetInteractor();\n\n \/\/determine the name of the property we are coloring by\n const char* propertyName = producer->GetDataInformation()->\n GetPointDataInformation()->\n GetArrayInformation(0)->\n GetName();\n\n if(!rwi||!passThroughAlg||!propertyName)\n {\n return false;\n }\n\n this->Widget = vtkSmartPointer<vtkNonOrthoImagePlaneWidget>::New();\n\n \/\/set the interactor on the widget to be what the current\n \/\/render window is using\n this->Widget->SetInteractor( rwi );\n\n \/\/setup the color of the border of the widget\n {\n double color[3] = {1, 0, 0};\n this->Widget->GetPlaneProperty()->SetColor(color);\n }\n\n \/\/turn texture interpolation to be linear\n this->Widget->TextureInterpolateOn();\n this->Widget->SetResliceInterpolateToLinear();\n\n \/\/Construct the transfer function proxy for the widget\n vtkSMProxy* lut = this->colorMap();\n\n \/\/set the widgets lookup table to be the one that the transfer function\n \/\/manager is using\n vtkScalarsToColors* stc =\n vtkScalarsToColors::SafeDownCast(lut->GetClientSideObject());\n this->Widget->SetLookupTable(stc);\n\n \/\/lastly we set up the input connection\n this->Widget->SetInputConnection(passThroughAlg->GetOutputPort());\n\n Q_ASSERT(rwi);\n Q_ASSERT(passThroughAlg);\n return true;\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid ModuleSlice::updateColorMap()\n{\n Q_ASSERT(this->Widget);\n\n \/\/Construct the transfer function proxy for the widget\n vtkSMProxy* lut = this->colorMap();\n\n \/\/set the widgets lookup table to be the one that the transfer function\n \/\/manager is using\n vtkScalarsToColors* stc =\n vtkScalarsToColors::SafeDownCast(lut->GetClientSideObject());\n this->Widget->SetLookupTable(stc);\n}\n\n\/\/-----------------------------------------------------------------------------\nbool ModuleSlice::finalize()\n{\n vtkNew<vtkSMParaViewPipelineControllerWithRendering> controller;\n controller->UnRegisterProxy(this->PassThrough);\n\n this->PassThrough = NULL;\n\n if(this->Widget != NULL)\n {\n this->Widget->InteractionOff();\n this->Widget->Off();\n }\n\n return true;\n}\n\n\/\/-----------------------------------------------------------------------------\nbool ModuleSlice::setVisibility(bool val)\n{\n Q_ASSERT(this->Widget);\n this->Widget->SetEnabled(val ? 1 : 0);\n return true;\n}\n\n\/\/-----------------------------------------------------------------------------\nbool ModuleSlice::visibility() const\n{\n Q_ASSERT(this->Widget);\n return this->Widget->GetEnabled() != 0;\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid ModuleSlice::addToPanel(pqProxiesWidget* panel)\n{\n QStringList properties;\n properties << \"ShowArrow\";\n panel->addProxy(this->PropsPanelProxy, \"Appearance\", properties, true);\n\n this->Superclass::addToPanel(panel);\n}\n\n\/\/-----------------------------------------------------------------------------\nbool ModuleSlice::serialize(pugi::xml_node& ns) const\n{\n \/\/ FIXME: serialize slice properties.\n return this->Superclass::serialize(ns);\n}\n\n\/\/-----------------------------------------------------------------------------\nbool ModuleSlice::deserialize(const pugi::xml_node& ns)\n{\n \/\/ FIXME: deserialize slice properties.\n return this->Superclass::deserialize(ns);\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid ModuleSlice::onPropertyChanged()\n{\n vtkSMPropertyHelper showProperty(this->PropsPanelProxy, \"ShowArrow\");\n qDebug() << \"onPropertyChanged called.\";\n qDebug() << showProperty.GetAsInt();\n}\n\n}\n<commit_msg>Slice now hides the arrow when ShowArrow property is off -- fixes #23<commit_after>\/******************************************************************************\n\n This source file is part of the tomviz project.\n\n Copyright Kitware, Inc.\n\n This source code is released under the New BSD License, (the \"License\").\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n\n******************************************************************************\/\n#include \"ModuleSlice.h\"\n\n#include \"DataSource.h\"\n#include \"pqProxiesWidget.h\"\n#include \"pqCoreUtilities.h\"\n#include \"Utilities.h\"\n\n#include \"vtkAlgorithm.h\"\n#include \"vtkCommand.h\"\n#include \"vtkNonOrthoImagePlaneWidget.h\"\n#include \"vtkDataObject.h\"\n#include \"vtkNew.h\"\n#include \"vtkProperty.h\"\n#include \"vtkPVArrayInformation.h\"\n#include \"vtkPVDataInformation.h\"\n#include \"vtkPVDataSetAttributesInformation.h\"\n#include \"vtkRenderWindow.h\"\n#include \"vtkRenderWindowInteractor.h\"\n#include \"vtkScalarsToColors.h\"\n#include \"vtkSMParaViewPipelineControllerWithRendering.h\"\n#include \"vtkSMPropertyHelper.h\"\n#include \"vtkSMPVRepresentationProxy.h\"\n#include \"vtkSMRenderViewProxy.h\"\n#include \"vtkSMSessionProxyManager.h\"\n#include \"vtkSMSourceProxy.h\"\n#include \"vtkSMTransferFunctionManager.h\"\n#include \"vtkSMTransferFunctionProxy.h\"\n#include \"vtkSMViewProxy.h\"\n\n#include <QDebug>\n\nnamespace tomviz\n{\n\n\/\/-----------------------------------------------------------------------------\nModuleSlice::ModuleSlice(QObject* parentObject) : Superclass(parentObject)\n{\n}\n\n\/\/-----------------------------------------------------------------------------\nModuleSlice::~ModuleSlice()\n{\n this->finalize();\n}\n\n\/\/-----------------------------------------------------------------------------\nQIcon ModuleSlice::icon() const\n{\n return QIcon(\":\/pqWidgets\/Icons\/pqSlice24.png\");\n}\n\n\/\/-----------------------------------------------------------------------------\nbool ModuleSlice::initialize(DataSource* data, vtkSMViewProxy* vtkView)\n{\n if (!this->Superclass::initialize(data, vtkView))\n {\n return false;\n }\n\n vtkNew<vtkSMParaViewPipelineControllerWithRendering> controller;\n vtkSMSourceProxy* producer = data->producer();\n vtkSMSessionProxyManager* pxm = producer->GetSessionProxyManager();\n\n \/\/ Create the pass through filter.\n vtkSmartPointer<vtkSMProxy> proxy;\n proxy.TakeReference(pxm->NewProxy(\"filters\", \"PassThrough\"));\n \n \/\/ Create the Properties panel proxy\n this->PropsPanelProxy.TakeReference(\n pxm->NewProxy(\"tomviz_proxies\", \"NonOrthogonalSlice\"));\n\n pqCoreUtilities::connect(\n this->PropsPanelProxy, vtkCommand::PropertyModifiedEvent,\n this, SLOT(onPropertyChanged()));\n\n this->PassThrough = vtkSMSourceProxy::SafeDownCast(proxy);\n Q_ASSERT(this->PassThrough);\n controller->PreInitializeProxy(this->PassThrough);\n vtkSMPropertyHelper(this->PassThrough, \"Input\").Set(producer);\n controller->PostInitializeProxy(this->PassThrough);\n controller->RegisterPipelineProxy(this->PassThrough);\n\n \/\/Create the widget\n const bool widgetSetup = this->setupWidget(vtkView,producer);\n\n if(widgetSetup)\n {\n this->Widget->On();\n this->Widget->InteractionOn();\n }\n\n Q_ASSERT(this->Widget);\n return widgetSetup;\n}\n\n\n\/\/-----------------------------------------------------------------------------\n\/\/should only be called from initialize after the PassThrough has been setup\nbool ModuleSlice::setupWidget(vtkSMViewProxy* vtkView, vtkSMSourceProxy* producer)\n{\n vtkAlgorithm* passThroughAlg = vtkAlgorithm::SafeDownCast(\n this->PassThrough->GetClientSideObject());\n\n vtkRenderWindowInteractor* rwi = vtkView->GetRenderWindow()->GetInteractor();\n\n \/\/determine the name of the property we are coloring by\n const char* propertyName = producer->GetDataInformation()->\n GetPointDataInformation()->\n GetArrayInformation(0)->\n GetName();\n\n if(!rwi||!passThroughAlg||!propertyName)\n {\n return false;\n }\n\n this->Widget = vtkSmartPointer<vtkNonOrthoImagePlaneWidget>::New();\n\n \/\/set the interactor on the widget to be what the current\n \/\/render window is using\n this->Widget->SetInteractor( rwi );\n\n \/\/setup the color of the border of the widget\n {\n double color[3] = {1, 0, 0};\n this->Widget->GetPlaneProperty()->SetColor(color);\n }\n\n \/\/turn texture interpolation to be linear\n this->Widget->TextureInterpolateOn();\n this->Widget->SetResliceInterpolateToLinear();\n\n \/\/Construct the transfer function proxy for the widget\n vtkSMProxy* lut = this->colorMap();\n\n \/\/set the widgets lookup table to be the one that the transfer function\n \/\/manager is using\n vtkScalarsToColors* stc =\n vtkScalarsToColors::SafeDownCast(lut->GetClientSideObject());\n this->Widget->SetLookupTable(stc);\n\n \/\/lastly we set up the input connection\n this->Widget->SetInputConnection(passThroughAlg->GetOutputPort());\n\n Q_ASSERT(rwi);\n Q_ASSERT(passThroughAlg);\n return true;\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid ModuleSlice::updateColorMap()\n{\n Q_ASSERT(this->Widget);\n\n \/\/Construct the transfer function proxy for the widget\n vtkSMProxy* lut = this->colorMap();\n\n \/\/set the widgets lookup table to be the one that the transfer function\n \/\/manager is using\n vtkScalarsToColors* stc =\n vtkScalarsToColors::SafeDownCast(lut->GetClientSideObject());\n this->Widget->SetLookupTable(stc);\n}\n\n\/\/-----------------------------------------------------------------------------\nbool ModuleSlice::finalize()\n{\n vtkNew<vtkSMParaViewPipelineControllerWithRendering> controller;\n controller->UnRegisterProxy(this->PassThrough);\n\n this->PassThrough = NULL;\n\n if(this->Widget != NULL)\n {\n this->Widget->InteractionOff();\n this->Widget->Off();\n }\n\n return true;\n}\n\n\/\/-----------------------------------------------------------------------------\nbool ModuleSlice::setVisibility(bool val)\n{\n Q_ASSERT(this->Widget);\n this->Widget->SetEnabled(val ? 1 : 0);\n return true;\n}\n\n\/\/-----------------------------------------------------------------------------\nbool ModuleSlice::visibility() const\n{\n Q_ASSERT(this->Widget);\n return this->Widget->GetEnabled() != 0;\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid ModuleSlice::addToPanel(pqProxiesWidget* panel)\n{\n QStringList properties;\n properties << \"ShowArrow\";\n panel->addProxy(this->PropsPanelProxy, \"Appearance\", properties, true);\n\n this->Superclass::addToPanel(panel);\n}\n\n\/\/-----------------------------------------------------------------------------\nbool ModuleSlice::serialize(pugi::xml_node& ns) const\n{\n \/\/ FIXME: serialize slice properties.\n return this->Superclass::serialize(ns);\n}\n\n\/\/-----------------------------------------------------------------------------\nbool ModuleSlice::deserialize(const pugi::xml_node& ns)\n{\n \/\/ FIXME: deserialize slice properties.\n return this->Superclass::deserialize(ns);\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid ModuleSlice::onPropertyChanged()\n{\n vtkSMPropertyHelper showProperty(this->PropsPanelProxy, \"ShowArrow\");\n \/\/ Not this: it hides the plane as well as the arrow...\n \/\/this->Widget->SetEnabled(showProperty.GetAsInt());\n this->Widget->SetArrowVisibility(showProperty.GetAsInt());\n this->Widget->SetInteraction(showProperty.GetAsInt());\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ The MIT License (MIT)\r\n\r\n\/\/ Copyright (c) 2013 Danny Y., Rapptz\r\n\r\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy of\r\n\/\/ this software and associated documentation files (the \"Software\"), to deal in\r\n\/\/ the Software without restriction, including without limitation the rights to\r\n\/\/ use, copy, modify, merge, publish, distribute, sublicense, and\/or sell copies of\r\n\/\/ the Software, and to permit persons to whom the Software is furnished to do so,\r\n\/\/ subject to the following conditions:\r\n\r\n\/\/ The above copyright notice and this permission notice shall be included in all\r\n\/\/ copies or substantial portions of the Software.\r\n\r\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS\r\n\/\/ FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\r\n\/\/ COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\r\n\/\/ IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\r\n\/\/ CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\r\n\r\n#ifndef SOL_USERDATA_HPP\r\n#define SOL_USERDATA_HPP\r\n\r\n#include \"state.hpp\"\r\n#include \"function_types.hpp\"\r\n#include \"demangle.hpp\"\r\n#include <vector>\r\n\r\nnamespace sol {\r\nnamespace detail {\r\ntemplate<typename T, typename... Args>\r\ninline std::unique_ptr<T> make_unique(Args&&... args) {\r\n return std::unique_ptr<T>(new T(std::forward<Args>(args)...));\r\n}\r\n} \/\/ detail\r\n\r\ntemplate<typename T>\r\nclass userdata {\r\nprivate:\r\n friend table;\r\n static const std::string classname;\r\n static const std::string meta;\r\n\r\n std::string luaname;\r\n std::vector<std::string> functionnames;\r\n std::vector<std::unique_ptr<base_function>> functions;\r\n std::vector<luaL_Reg> functiontable;\r\n\r\n template<typename... TTypes>\r\n struct constructor {\r\n template<typename... Args>\r\n static void do_constructor(lua_State* L, T* obj, call_syntax syntax, int, types<Args...>) {\r\n auto fx = [&obj] (Args&&... args) -> void {\r\n std::allocator<T> alloc{};\r\n alloc.construct(obj, std::forward<Args>(args)...);\r\n };\r\n stack::get_call(L, 1 + static_cast<int>(syntax), fx, types<Args...>());\r\n }\r\n\r\n static void match_constructor(lua_State*, T*, call_syntax, int) {\r\n throw sol_error(\"No matching constructor for the arguments provided\");\r\n }\r\n\r\n template<typename ...CArgs, typename... Args>\r\n static void match_constructor(lua_State* L, T* obj, call_syntax syntax, int argcount, types<CArgs...> t, Args&&... args) {\r\n if (argcount == sizeof...(CArgs)) {\r\n do_constructor(L, obj, syntax, argcount, t);\r\n return;\r\n }\r\n match_constructor(L, obj, syntax, argcount, std::forward<Args>(args)...);\r\n }\r\n\r\n static int construct(lua_State* L) {\r\n call_syntax syntax = stack::get_call_syntax(L, meta);\r\n int argcount = lua_gettop(L);\r\n\r\n void* udata = lua_newuserdata(L, sizeof(T));\r\n T* obj = static_cast<T*>(udata);\r\n match_constructor(L, obj, syntax, argcount - static_cast<int>(syntax), typename std::common_type<TTypes>::type()...);\r\n\r\n luaL_getmetatable(L, meta.c_str());\r\n lua_setmetatable(L, -2);\r\n\r\n return 1;\r\n }\r\n };\r\n\r\n template<std::size_t n>\r\n struct destructor {\r\n static int destruct(lua_State* L) {\r\n userdata_t udata = stack::get<userdata_t>(L, 1);\r\n T* obj = static_cast<T*>(udata.value);\r\n std::allocator<T> alloc{};\r\n alloc.destroy(obj);\r\n return 0;\r\n }\r\n };\r\n\r\n template<std::size_t n>\r\n void build_function_tables() {}\r\n\r\n template<std::size_t n, typename... Args, typename Ret>\r\n void build_function_tables(std::string name,Ret T::* func, Args&&... args) {\r\n typedef typename std::decay<decltype(func)>::type fx_t;\r\n functionnames.push_back(std::move(name));\r\n functions.emplace_back(detail::make_unique<userdata_function<fx_t, T>>(std::move(func)));\r\n functiontable.push_back({ functionnames.back().c_str(), &base_function::userdata<n>::call });\r\n build_function_tables<n + 1>(std::forward<Args>(args)...);\r\n }\r\n\r\npublic:\r\n template<typename... Args>\r\n userdata(Args&&... args): userdata(classname, default_constructor, std::forward<Args>(args)...) {}\r\n\r\n template<typename... Args, typename... CArgs>\r\n userdata(constructors<CArgs...> c, Args&&... args): userdata(classname, std::move(c), std::forward<Args>(args)...) {}\r\n\r\n template<typename... Args, typename... CArgs>\r\n userdata(std::string name, constructors<CArgs...>, Args&&... args): luaname(std::move(name)) {\r\n functionnames.reserve(sizeof...(args) + 2);\r\n functiontable.reserve(sizeof...(args) + 3);\r\n functions.reserve(sizeof...(args) + 2);\r\n build_function_tables<0>(std::forward<Args>(args)...);\r\n\r\n functionnames.push_back(\"new\");\r\n functiontable.push_back({ functionnames.back().c_str(), &constructor<CArgs...>::construct });\r\n functionnames.push_back(\"__gc\");\r\n functiontable.push_back({ functionnames.back().c_str(), &destructor<sizeof...(Args) \/ 2>::destruct });\r\n\r\n functiontable.push_back({ nullptr, nullptr });\r\n }\r\n\r\n template<typename... Args, typename... CArgs>\r\n userdata(const char* name, constructors<CArgs...> c, Args&&... args) :\r\n userdata(std::string(name), std::move(c), std::forward<Args>(args)...) {}\r\n\r\n void register_into(const table& s) {}\r\n};\r\n\r\ntemplate<typename T>\r\nconst std::string userdata<T>::classname = detail::demangle(typeid(T));\r\n\r\ntemplate<typename T>\r\nconst std::string userdata<T>::meta = std::string(\"sol.stateful.\").append(classname);\r\n\r\n} \/\/ sol\r\n\r\n#endif \/\/ SOL_USERDATA_HPP\r\n<commit_msg>Format changes<commit_after>\/\/ The MIT License (MIT)\r\n\r\n\/\/ Copyright (c) 2013 Danny Y., Rapptz\r\n\r\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy of\r\n\/\/ this software and associated documentation files (the \"Software\"), to deal in\r\n\/\/ the Software without restriction, including without limitation the rights to\r\n\/\/ use, copy, modify, merge, publish, distribute, sublicense, and\/or sell copies of\r\n\/\/ the Software, and to permit persons to whom the Software is furnished to do so,\r\n\/\/ subject to the following conditions:\r\n\r\n\/\/ The above copyright notice and this permission notice shall be included in all\r\n\/\/ copies or substantial portions of the Software.\r\n\r\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS\r\n\/\/ FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\r\n\/\/ COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\r\n\/\/ IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\r\n\/\/ CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\r\n\r\n#ifndef SOL_USERDATA_HPP\r\n#define SOL_USERDATA_HPP\r\n\r\n#include \"state.hpp\"\r\n#include \"function_types.hpp\"\r\n#include \"demangle.hpp\"\r\n#include <vector>\r\n\r\nnamespace sol {\r\nnamespace detail {\r\ntemplate<typename T, typename... Args>\r\ninline std::unique_ptr<T> make_unique(Args&&... args) {\r\n return std::unique_ptr<T>(new T(std::forward<Args>(args)...));\r\n}\r\n} \/\/ detail\r\n\r\ntemplate<typename T>\r\nclass userdata {\r\nprivate:\r\n friend table;\r\n static const std::string classname;\r\n static const std::string meta;\r\n\r\n std::string luaname;\r\n std::vector<std::string> functionnames;\r\n std::vector<std::unique_ptr<base_function>> functions;\r\n std::vector<luaL_Reg> functiontable;\r\n\r\n template<typename... TTypes>\r\n struct constructor {\r\n template<typename... Args>\r\n static void do_constructor(lua_State* L, T* obj, call_syntax syntax, int, types<Args...>) {\r\n auto fx = [&obj] (Args&&... args) -> void {\r\n std::allocator<T> alloc{};\r\n alloc.construct(obj, std::forward<Args>(args)...);\r\n };\r\n stack::get_call(L, 1 + static_cast<int>(syntax), fx, types<Args...>());\r\n }\r\n\r\n static void match_constructor(lua_State*, T*, call_syntax, int) {\r\n throw sol_error(\"No matching constructor for the arguments provided\");\r\n }\r\n\r\n template<typename ...CArgs, typename... Args>\r\n static void match_constructor(lua_State* L, T* obj, call_syntax syntax, int argcount, types<CArgs...> t, Args&&... args) {\r\n if (argcount == sizeof...(CArgs)) {\r\n do_constructor(L, obj, syntax, argcount, t);\r\n return;\r\n }\r\n match_constructor(L, obj, syntax, argcount, std::forward<Args>(args)...);\r\n }\r\n\r\n static int construct(lua_State* L) {\r\n call_syntax syntax = stack::get_call_syntax(L, meta);\r\n int argcount = lua_gettop(L);\r\n\r\n void* udata = lua_newuserdata(L, sizeof(T));\r\n T* obj = static_cast<T*>(udata);\r\n match_constructor(L, obj, syntax, argcount - static_cast<int>(syntax), typename std::common_type<TTypes>::type()...);\r\n\r\n luaL_getmetatable(L, meta.c_str());\r\n lua_setmetatable(L, -2);\r\n\r\n return 1;\r\n }\r\n };\r\n\r\n template<std::size_t N>\r\n struct destructor {\r\n static int destruct(lua_State* L) {\r\n userdata_t udata = stack::get<userdata_t>(L, 1);\r\n T* obj = static_cast<T*>(udata.value);\r\n std::allocator<T> alloc{};\r\n alloc.destroy(obj);\r\n return 0;\r\n }\r\n };\r\n\r\n template<std::size_t N>\r\n void build_function_tables() {}\r\n\r\n template<std::size_t N, typename... Args, typename Ret>\r\n void build_function_tables(std::string name, Ret T::* func, Args&&... args) {\r\n typedef typename std::decay<decltype(func)>::type function_type;\r\n functionnames.push_back(std::move(name));\r\n functions.emplace_back(detail::make_unique<userdata_function<function_type, T>>(std::move(func)));\r\n functiontable.push_back({ functionnames.back().c_str(), &base_function::userdata<N>::call });\r\n build_function_tables<N + 1>(std::forward<Args>(args)...);\r\n }\r\n\r\npublic:\r\n template<typename... Args>\r\n userdata(Args&&... args): userdata(classname, default_constructor, std::forward<Args>(args)...) {}\r\n\r\n template<typename... Args, typename... CArgs>\r\n userdata(constructors<CArgs...> c, Args&&... args): userdata(classname, std::move(c), std::forward<Args>(args)...) {}\r\n\r\n template<typename... Args, typename... CArgs>\r\n userdata(std::string name, constructors<CArgs...>, Args&&... args): luaname(std::move(name)) {\r\n functionnames.reserve(sizeof...(args) + 2);\r\n functiontable.reserve(sizeof...(args) + 3);\r\n functions.reserve(sizeof...(args) + 2);\r\n build_function_tables<0>(std::forward<Args>(args)...);\r\n\r\n functionnames.push_back(\"new\");\r\n functiontable.push_back({ functionnames.back().c_str(), &constructor<CArgs...>::construct });\r\n functionnames.push_back(\"__gc\");\r\n functiontable.push_back({ functionnames.back().c_str(), &destructor<sizeof...(Args) \/ 2>::destruct });\r\n\r\n functiontable.push_back({ nullptr, nullptr });\r\n }\r\n\r\n template<typename... Args, typename... CArgs>\r\n userdata(const char* name, constructors<CArgs...> c, Args&&... args) :\r\n userdata(std::string(name), std::move(c), std::forward<Args>(args)...) {}\r\n\r\n void register_into(const table& s) {}\r\n};\r\n\r\ntemplate<typename T>\r\nconst std::string userdata<T>::classname = detail::demangle(typeid(T));\r\n\r\ntemplate<typename T>\r\nconst std::string userdata<T>::meta = std::string(\"sol.stateful.\").append(classname);\r\n\r\n} \/\/ sol\r\n\r\n#endif \/\/ SOL_USERDATA_HPP\r\n<|endoftext|>"} {"text":"<commit_before>\/***************************************************************************\n**\n** Copyright (C) 2010 Nokia Corporation and\/or its subsidiary(-ies).\n** All rights reserved.\n** Contact: Nokia Corporation (directui@nokia.com)\n**\n** This file is part of libmeegotouch.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at directui@nokia.com.\n**\n** This library is free software; you can redistribute it and\/or\n** modify it under the terms of the GNU Lesser General Public\n** License version 2.1 as published by the Free Software Foundation\n** and appearing in the file LICENSE.LGPL included in the packaging\n** of this file.\n**\n****************************************************************************\/\n\n#include \"timedemo.h\"\n#include \"listpage.h\"\n#include \"timedemobenchmark.h\"\n#include \"templatepage.h\"\n\n#include <MApplication>\n#include <MWindow>\n#include <MSceneManager>\n#include <MApplicationPage>\n\n#include <QApplication>\n#include <QTextStream>\n#include <QXmlStreamWriter>\n#include <QFile>\n#include <QTimer>\n\nnamespace\n{\n const int pageDuration = 5000;\n}\n\nTimedemo::Timedemo(ListPage *listPage, const QStringList& demoPageTitles)\n : m_pFrontPage(listPage)\n , m_currentPageIndex(0)\n , m_currentBenchmarkIndex(0)\n , demoPageTitles(demoPageTitles)\n , timingStarted(false)\n , timingStopped(false)\n{\n connect(m_pFrontPage, SIGNAL(appeared()), this, SLOT(showFirstPage()));\n}\n\nvoid Timedemo::setOutputCsv(const QString &filename)\n{\n m_csvFilename = filename;\n}\n\nvoid Timedemo::setFramelog(const QString &filename)\n{\n framelogFilename = filename;\n}\n\nvoid Timedemo::startTiming()\n{\n if (timingStopped || timingStarted) {\n qFatal(\"New timing started, but old one not processed yet.\");\n }\n\n timingStarted = true;\n SwapHook::instance()->startLurking();\n}\n\nvoid Timedemo::stopTiming()\n{\n if (timingStopped || !timingStarted) {\n qFatal(\"Timing already processed or not running yet.\");\n }\n\n SwapHook::instance()->stopLurking();\n\n QSharedPointer<TimedemoBenchmark> benchmark = demoPages[m_currentPageIndex]->benchmarks()[m_currentBenchmarkIndex];\n BenchmarkResult currentResult(SwapHook::instance()->timestamps(), benchmark->type());\n benchmarkResults[m_currentPageIndex].insert(benchmark->name(), currentResult);\n\n timingStopped = true;\n}\n\nvoid Timedemo::showFirstPage()\n{\n if (demoPageTitles.count() == 0) {\n foreach(TimedemoPage *page, m_pFrontPage->pages) {\n demoPages.append(page);\n }\n } else {\n foreach(const QString title, demoPageTitles) {\n TimedemoPage *page;\n if (title == m_pFrontPage->timedemoTitle()) {\n page = m_pFrontPage;\n } else {\n page = m_pFrontPage->findPageByTimedemoTitle(title);\n }\n if (page) {\n demoPages.append(page);\n }\n }\n }\n\n if (demoPages.count() == 0) {\n return;\n }\n\n disconnect(m_pFrontPage, SIGNAL(appeared()), this, SLOT(showFirstPage()));\n m_currentPageIndex = 0;\n benchmarkResults.resize(demoPages.count());\n\n demoPages[m_currentPageIndex]->createBenchmarks(this);\n beginBenchmark();\n}\n\nvoid Timedemo::beginBenchmark()\n{\n if (m_currentBenchmarkIndex >= demoPages[m_currentPageIndex]->benchmarks().count()) {\n \/\/ all benchmarks have been processed, switch to the next page\n showNextPage();\n return;\n }\n\n QSharedPointer<TimedemoBenchmark> benchmark = demoPages[m_currentPageIndex]->benchmarks()[m_currentBenchmarkIndex];\n if (!allBenchmarks.contains(benchmark->name())) {\n allBenchmarks.append(benchmark->name());\n }\n\n connect(benchmark.data(), SIGNAL(finished()), this, SLOT(benchmarkFinished()));\n\n benchmark->start();\n}\n\n\nvoid Timedemo::benchmarkFinished()\n{\n if (!timingStopped) {\n qFatal(\"Benchmark did not stop timing.\");\n }\n\n timingStarted = false;\n timingStopped = false;\n ++m_currentBenchmarkIndex;\n beginBenchmark();\n}\n\nvoid Timedemo::showNextPage()\n{\n ++m_currentPageIndex;\n m_currentBenchmarkIndex = 0;\n\n if (m_currentPageIndex < demoPages.count()) {\n TimedemoPage* currentPage = demoPages[m_currentPageIndex];\n demoPages[m_currentPageIndex]->createBenchmarks(this);\n\n if (currentPage == m_pFrontPage) {\n \/\/ FIXME: the front page needs a special invitation.\n \/\/ otherwise it does not show up again\n if (MApplication::activeWindow()) {\n \/\/ FIXME: why appearSceneWindowNow() and not appear()?\n MApplication::activeWindow()->sceneManager()->appearSceneWindowNow(demoPages[m_currentPageIndex]);\n }\n }\n beginBenchmark();\n } else {\n \/\/ all pages shown, display results:\n displayBenchmarkResults();\n\n qApp->exit(0);\n }\n}\n\nvoid Timedemo::displayBenchmarkResults()\n{\n QTextStream log(stdout, QIODevice::WriteOnly | QIODevice::Text);\n\n QFile statsCsvFile;\n if (m_csvFilename.isEmpty()) {\n statsCsvFile.setFileName(\"\/dev\/null\");\n } else {\n statsCsvFile.setFileName(m_csvFilename);\n }\n\n statsCsvFile.open(QIODevice::WriteOnly | QIODevice::Truncate | QIODevice::Text);\n QTextStream statsCsv(&statsCsvFile);\n\n int pageTitleWidth = 0;\n const int fpsWidth = 5;\n const int fpsUnitWidth = 5;\n const int runtimeWidth = 5;\n const int runtimeUnitWidth = 2;\n const int benchmarkWidth = fpsWidth + fpsUnitWidth + runtimeWidth + runtimeUnitWidth;\n QHash<QString, int> actualWidth;\n\n for (int i = 0; i < benchmarkResults.count(); ++i) {\n TimedemoPage *page = demoPages[i];\n QString title = page->timedemoTitle();\n pageTitleWidth = qMax(pageTitleWidth, title.length());\n }\n pageTitleWidth += 2;\n\n log.setRealNumberNotation(QTextStream::FixedNotation);\n log.setRealNumberPrecision(2);\n log << left << qSetFieldWidth(pageTitleWidth) << \"Page name\";\n statsCsv << \"Page name\";\n\n foreach(const QString& name, allBenchmarks) {\n int width = qMax(benchmarkWidth + 2, name.length() + 2);\n log << qSetFieldWidth(width) << name;\n statsCsv << \", \\\"\" << name << \" [fps]\\\", \\\"\" << name << \" [ms]\\\"\";\n\n actualWidth[name] = width;\n }\n log << qSetFieldWidth(0) << '\\n';\n statsCsv << '\\n';\n\n for (int i = 0; i < benchmarkResults.count(); ++i) {\n TimedemoPage *page = demoPages[i];\n QString title = page->timedemoTitle();\n\n log << qSetFieldWidth(pageTitleWidth) << title;\n statsCsv << \"\\\"\" << title << \"\\\"\";\n\n BenchmarkResultHash results = benchmarkResults[i];\n foreach(const QString& name, allBenchmarks) {\n statsCsv << \", \";\n BenchmarkResultHash::const_iterator resultIter = results.find(name);\n if (resultIter != results.constEnd() && resultIter->fps() != 0 && resultIter->runtime() != 0) {\n log << right\n << qSetFieldWidth(fpsWidth) << resultIter->fps()\n << qSetFieldWidth(fpsUnitWidth) << \"fps |\"\n << qSetFieldWidth(runtimeWidth) << resultIter->runtime()\n << qSetFieldWidth(runtimeUnitWidth) << \"ms\"\n << qSetFieldWidth(actualWidth[name] - benchmarkWidth) << \"\"\n << left;\n } else {\n log << qSetFieldWidth(actualWidth[name]) << center << \"n\/a\" << left;\n }\n statsCsv << resultIter->fps() << \", \" << resultIter->runtime();\n }\n log << qSetFieldWidth(0) << '\\n';\n statsCsv << '\\n';\n }\n\n log.flush();\n statsCsv.flush();\n saveFramelog();\n}\n\nvoid Timedemo::saveFramelog() {\n QFile framelogFile;\n if (framelogFilename.isEmpty()) {\n return;\n } else {\n framelogFile.setFileName(framelogFilename);\n }\n\n framelogFile.open(QIODevice::WriteOnly | QIODevice::Truncate | QIODevice::Text);\n QXmlStreamWriter framelog(&framelogFile);\n framelog.setAutoFormatting(true);\n framelog.writeStartDocument();\n framelog.writeDTD(\"<!DOCTYPE timedemo>\");\n framelog.writeStartElement(\"timedemo\");\n\n for (int i = 0; i < benchmarkResults.count(); ++i) {\n framelog.writeStartElement(\"page\");\n TimedemoPage *page = demoPages[i];\n QString title = page->timedemoTitle();\n\n framelog.writeAttribute(\"id\", title);\n\n BenchmarkResultHash results = benchmarkResults[i];\n foreach(const QString& name, allBenchmarks) {\n BenchmarkResultHash::const_iterator resultIter = results.find(name);\n if (resultIter == results.end()) {\n continue;\n }\n framelog.writeStartElement(\"benchmark\");\n framelog.writeAttribute(\"id\", name);\n framelog.writeTextElement(\"type\", resultIter->type);\n framelog.writeTextElement(\"runtime\", QString::number(resultIter->runtime()));\n QString timestamps;\n foreach(const timestamp ts, resultIter->timestamps) {\n timestamps.append(QString::number(ts) + ',');\n }\n timestamps.truncate(timestamps.size() - 1);\n framelog.writeTextElement(\"frames\", timestamps);\n\n \/\/ \"page\"\n framelog.writeEndElement();\n }\n\n \/\/ \"benchmark\"\n framelog.writeEndElement();\n }\n\n framelog.writeEndElement();\n framelog.writeEndDocument();\n\n framelogFile.flush();\n}\n<commit_msg>Changes: Fix coverity issue 5<commit_after>\/***************************************************************************\n**\n** Copyright (C) 2010 Nokia Corporation and\/or its subsidiary(-ies).\n** All rights reserved.\n** Contact: Nokia Corporation (directui@nokia.com)\n**\n** This file is part of libmeegotouch.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at directui@nokia.com.\n**\n** This library is free software; you can redistribute it and\/or\n** modify it under the terms of the GNU Lesser General Public\n** License version 2.1 as published by the Free Software Foundation\n** and appearing in the file LICENSE.LGPL included in the packaging\n** of this file.\n**\n****************************************************************************\/\n\n#include \"timedemo.h\"\n#include \"listpage.h\"\n#include \"timedemobenchmark.h\"\n#include \"templatepage.h\"\n\n#include <MApplication>\n#include <MWindow>\n#include <MSceneManager>\n#include <MApplicationPage>\n\n#include <QApplication>\n#include <QTextStream>\n#include <QXmlStreamWriter>\n#include <QFile>\n#include <QTimer>\n\nnamespace\n{\n const int pageDuration = 5000;\n}\n\nTimedemo::Timedemo(ListPage *listPage, const QStringList& demoPageTitles)\n : m_pFrontPage(listPage)\n , m_currentPageIndex(0)\n , m_currentBenchmarkIndex(0)\n , demoPageTitles(demoPageTitles)\n , timingStarted(false)\n , timingStopped(false)\n{\n connect(m_pFrontPage, SIGNAL(appeared()), this, SLOT(showFirstPage()));\n}\n\nvoid Timedemo::setOutputCsv(const QString &filename)\n{\n m_csvFilename = filename;\n}\n\nvoid Timedemo::setFramelog(const QString &filename)\n{\n framelogFilename = filename;\n}\n\nvoid Timedemo::startTiming()\n{\n if (timingStopped || timingStarted) {\n qFatal(\"New timing started, but old one not processed yet.\");\n }\n\n timingStarted = true;\n SwapHook::instance()->startLurking();\n}\n\nvoid Timedemo::stopTiming()\n{\n if (timingStopped || !timingStarted) {\n qFatal(\"Timing already processed or not running yet.\");\n }\n\n SwapHook::instance()->stopLurking();\n\n QSharedPointer<TimedemoBenchmark> benchmark = demoPages[m_currentPageIndex]->benchmarks()[m_currentBenchmarkIndex];\n BenchmarkResult currentResult(SwapHook::instance()->timestamps(), benchmark->type());\n benchmarkResults[m_currentPageIndex].insert(benchmark->name(), currentResult);\n\n timingStopped = true;\n}\n\nvoid Timedemo::showFirstPage()\n{\n if (demoPageTitles.count() == 0) {\n foreach(TimedemoPage *page, m_pFrontPage->pages) {\n demoPages.append(page);\n }\n } else {\n foreach(const QString title, demoPageTitles) {\n TimedemoPage *page;\n if (title == m_pFrontPage->timedemoTitle()) {\n page = m_pFrontPage;\n } else {\n page = m_pFrontPage->findPageByTimedemoTitle(title);\n }\n if (page) {\n demoPages.append(page);\n }\n }\n }\n\n if (demoPages.count() == 0) {\n return;\n }\n\n disconnect(m_pFrontPage, SIGNAL(appeared()), this, SLOT(showFirstPage()));\n m_currentPageIndex = 0;\n benchmarkResults.resize(demoPages.count());\n\n demoPages[m_currentPageIndex]->createBenchmarks(this);\n beginBenchmark();\n}\n\nvoid Timedemo::beginBenchmark()\n{\n if (m_currentBenchmarkIndex >= demoPages[m_currentPageIndex]->benchmarks().count()) {\n \/\/ all benchmarks have been processed, switch to the next page\n showNextPage();\n return;\n }\n\n QSharedPointer<TimedemoBenchmark> benchmark = demoPages[m_currentPageIndex]->benchmarks()[m_currentBenchmarkIndex];\n if (!allBenchmarks.contains(benchmark->name())) {\n allBenchmarks.append(benchmark->name());\n }\n\n connect(benchmark.data(), SIGNAL(finished()), this, SLOT(benchmarkFinished()));\n\n benchmark->start();\n}\n\n\nvoid Timedemo::benchmarkFinished()\n{\n if (!timingStopped) {\n qFatal(\"Benchmark did not stop timing.\");\n }\n\n timingStarted = false;\n timingStopped = false;\n ++m_currentBenchmarkIndex;\n beginBenchmark();\n}\n\nvoid Timedemo::showNextPage()\n{\n ++m_currentPageIndex;\n m_currentBenchmarkIndex = 0;\n\n if (m_currentPageIndex < demoPages.count()) {\n TimedemoPage* currentPage = demoPages[m_currentPageIndex];\n demoPages[m_currentPageIndex]->createBenchmarks(this);\n\n if (currentPage == m_pFrontPage) {\n \/\/ FIXME: the front page needs a special invitation.\n \/\/ otherwise it does not show up again\n if (MApplication::activeWindow()) {\n \/\/ FIXME: why appearSceneWindowNow() and not appear()?\n MApplication::activeWindow()->sceneManager()->appearSceneWindowNow(demoPages[m_currentPageIndex]);\n }\n }\n beginBenchmark();\n } else {\n \/\/ all pages shown, display results:\n displayBenchmarkResults();\n\n qApp->exit(0);\n }\n}\n\nvoid Timedemo::displayBenchmarkResults()\n{\n QTextStream log(stdout, QIODevice::WriteOnly | QIODevice::Text);\n\n QFile statsCsvFile;\n if (m_csvFilename.isEmpty()) {\n statsCsvFile.setFileName(\"\/dev\/null\");\n } else {\n statsCsvFile.setFileName(m_csvFilename);\n }\n\n if ( ! statsCsvFile.open(QIODevice::WriteOnly | QIODevice::Truncate | QIODevice::Text) )\n {\n qWarning( \"failed to open stats file: %s\", qPrintable( statsCsvFile.fileName() ) );\n }\n\n QTextStream statsCsv(&statsCsvFile);\n\n int pageTitleWidth = 0;\n const int fpsWidth = 5;\n const int fpsUnitWidth = 5;\n const int runtimeWidth = 5;\n const int runtimeUnitWidth = 2;\n const int benchmarkWidth = fpsWidth + fpsUnitWidth + runtimeWidth + runtimeUnitWidth;\n QHash<QString, int> actualWidth;\n\n for (int i = 0; i < benchmarkResults.count(); ++i) {\n TimedemoPage *page = demoPages[i];\n QString title = page->timedemoTitle();\n pageTitleWidth = qMax(pageTitleWidth, title.length());\n }\n pageTitleWidth += 2;\n\n log.setRealNumberNotation(QTextStream::FixedNotation);\n log.setRealNumberPrecision(2);\n log << left << qSetFieldWidth(pageTitleWidth) << \"Page name\";\n statsCsv << \"Page name\";\n\n foreach(const QString& name, allBenchmarks) {\n int width = qMax(benchmarkWidth + 2, name.length() + 2);\n log << qSetFieldWidth(width) << name;\n statsCsv << \", \\\"\" << name << \" [fps]\\\", \\\"\" << name << \" [ms]\\\"\";\n\n actualWidth[name] = width;\n }\n log << qSetFieldWidth(0) << '\\n';\n statsCsv << '\\n';\n\n for (int i = 0; i < benchmarkResults.count(); ++i) {\n TimedemoPage *page = demoPages[i];\n QString title = page->timedemoTitle();\n\n log << qSetFieldWidth(pageTitleWidth) << title;\n statsCsv << \"\\\"\" << title << \"\\\"\";\n\n BenchmarkResultHash results = benchmarkResults[i];\n foreach(const QString& name, allBenchmarks) {\n statsCsv << \", \";\n BenchmarkResultHash::const_iterator resultIter = results.find(name);\n if (resultIter != results.constEnd() && resultIter->fps() != 0 && resultIter->runtime() != 0) {\n log << right\n << qSetFieldWidth(fpsWidth) << resultIter->fps()\n << qSetFieldWidth(fpsUnitWidth) << \"fps |\"\n << qSetFieldWidth(runtimeWidth) << resultIter->runtime()\n << qSetFieldWidth(runtimeUnitWidth) << \"ms\"\n << qSetFieldWidth(actualWidth[name] - benchmarkWidth) << \"\"\n << left;\n } else {\n log << qSetFieldWidth(actualWidth[name]) << center << \"n\/a\" << left;\n }\n statsCsv << resultIter->fps() << \", \" << resultIter->runtime();\n }\n log << qSetFieldWidth(0) << '\\n';\n statsCsv << '\\n';\n }\n\n log.flush();\n statsCsv.flush();\n saveFramelog();\n}\n\nvoid Timedemo::saveFramelog() {\n QFile framelogFile;\n if (framelogFilename.isEmpty()) {\n return;\n } else {\n framelogFile.setFileName(framelogFilename);\n }\n\n framelogFile.open(QIODevice::WriteOnly | QIODevice::Truncate | QIODevice::Text);\n QXmlStreamWriter framelog(&framelogFile);\n framelog.setAutoFormatting(true);\n framelog.writeStartDocument();\n framelog.writeDTD(\"<!DOCTYPE timedemo>\");\n framelog.writeStartElement(\"timedemo\");\n\n for (int i = 0; i < benchmarkResults.count(); ++i) {\n framelog.writeStartElement(\"page\");\n TimedemoPage *page = demoPages[i];\n QString title = page->timedemoTitle();\n\n framelog.writeAttribute(\"id\", title);\n\n BenchmarkResultHash results = benchmarkResults[i];\n foreach(const QString& name, allBenchmarks) {\n BenchmarkResultHash::const_iterator resultIter = results.find(name);\n if (resultIter == results.end()) {\n continue;\n }\n framelog.writeStartElement(\"benchmark\");\n framelog.writeAttribute(\"id\", name);\n framelog.writeTextElement(\"type\", resultIter->type);\n framelog.writeTextElement(\"runtime\", QString::number(resultIter->runtime()));\n QString timestamps;\n foreach(const timestamp ts, resultIter->timestamps) {\n timestamps.append(QString::number(ts) + ',');\n }\n timestamps.truncate(timestamps.size() - 1);\n framelog.writeTextElement(\"frames\", timestamps);\n\n \/\/ \"page\"\n framelog.writeEndElement();\n }\n\n \/\/ \"benchmark\"\n framelog.writeEndElement();\n }\n\n framelog.writeEndElement();\n framelog.writeEndDocument();\n\n framelogFile.flush();\n}\n<|endoftext|>"} {"text":"<commit_before>\/**\n * Copyright (c) 2013, Timothy Stack\n *\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and\/or other materials provided with the distribution.\n * * Neither the name of Timothy Stack nor the names of its contributors\n * may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ''AS IS'' AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY\n * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON\n * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n * @file lnav_util.cc\n *\n * Dumping ground for useful functions with no other home.\n *\/\n\n#include \"config.h\"\n\n#include <stdio.h>\n#include <fcntl.h>\n#include <ctype.h>\n \n#include <sqlite3.h>\n\n#include \"auto_fd.hh\"\n#include \"lnav_util.hh\"\n\nstd::string hash_string(const std::string &str)\n{\n byte_array<SHA_DIGEST_LENGTH> hash;\n SHA_CTX context;\n\n SHA_Init(&context);\n SHA_Update(&context, str.c_str(), str.length());\n SHA_Final(hash.out(), &context);\n\n return hash.to_string();\n}\n\nstd::string time_ago(time_t last_time)\n{\n time_t delta, current_time = time(NULL);\n const char *fmt;\n char buffer[64];\n int amount;\n\n delta = current_time - last_time;\n if (delta < 0) {\n return \"in the future\";\n }\n else if (delta < 60) {\n return \"just now\";\n }\n else if (delta < (60 * 2)) {\n return \"one minute ago\";\n }\n else if (delta < (60 * 60)) {\n fmt = \"%d minutes ago\";\n amount = delta \/ 60;\n }\n else if (delta < (2 * 60 * 60)) {\n return \"one hour ago\";\n }\n else if (delta < (24 * 60 * 60)) {\n fmt = \"%d hours ago\";\n amount = delta \/ (60 * 60);\n }\n else if (delta < (2 * 24 * 60 * 60)) {\n return \"one day ago\";\n }\n else if (delta < (365 * 24 * 60 * 60)) {\n fmt = \"%d days ago\";\n amount = delta \/ (24 * 60 * 60);\n }\n else {\n return \"over a year ago\";\n }\n\n snprintf(buffer, sizeof(buffer), fmt, amount);\n\n return std::string(buffer);\n}\n\n\/* XXX figure out how to do this with the template *\/\nvoid sqlite_close_wrapper(void *mem)\n{\n sqlite3_close((sqlite3 *)mem);\n}\n\nstd::string get_current_dir(void)\n{\n char cwd[FILENAME_MAX];\n std::string retval = \".\";\n\n if (getcwd(cwd, sizeof(cwd)) == NULL) {\n perror(\"getcwd\");\n }\n else {\n retval = std::string(cwd);\n }\n\n if (retval != \"\/\") {\n retval += \"\/\";\n }\n\n return retval;\n}\n\nbool change_to_parent_dir(void)\n{\n bool retval = false;\n char cwd[3] = \"\";\n\n if (getcwd(cwd, sizeof(cwd)) == NULL) {\n \/* perror(\"getcwd\"); *\/\n }\n if (strcmp(cwd, \"\/\") != 0) {\n if (chdir(\"..\") == -1) {\n perror(\"chdir('..')\");\n }\n else {\n retval = true;\n }\n }\n\n return retval;\n}\n\nfile_format_t detect_file_format(const std::string &filename)\n{\n file_format_t retval = FF_UNKNOWN;\n auto_fd fd;\n\n if ((fd = open(filename.c_str(), O_RDONLY)) != -1) {\n char buffer[32];\n int rc;\n\n if ((rc = read(fd, buffer, sizeof(buffer))) > 0) {\n if (rc > 16 &&\n strncmp(buffer, \"SQLite format 3\", 16) == 0) {\n retval = FF_SQLITE_DB;\n }\n }\n }\n\n return retval;\n}\n\nstatic time_t BAD_DATE = -1;\n\ntime_t tm2sec(const struct tm *t)\n{\n int year;\n time_t days;\n const int dayoffset[12] =\n { 306, 337, 0, 31, 61, 92, 122, 153, 184, 214, 245, 275 };\n\n year = t->tm_year;\n\n if (year < 70 || ((sizeof(time_t) <= 4) && (year >= 138))) {\n return BAD_DATE;\n }\n\n \/* shift new year to 1st March in order to make leap year calc easy *\/\n\n if (t->tm_mon < 2) {\n year--;\n }\n\n \/* Find number of days since 1st March 1900 (in the Gregorian calendar). *\/\n\n days = year * 365 + year \/ 4 - year \/ 100 + (year \/ 100 + 3) \/ 4;\n days += dayoffset[t->tm_mon] + t->tm_mday - 1;\n days -= 25508; \/* 1 jan 1970 is 25508 days since 1 mar 1900 *\/\n\n days = ((days * 24 + t->tm_hour) * 60 + t->tm_min) * 60 + t->tm_sec;\n\n if (days < 0) {\n return BAD_DATE;\n } \/* must have overflowed *\/\n else {\n if (t->tm_zone) {\n days -= t->tm_gmtoff;\n }\n return days;\n } \/* must be a valid time *\/\n}\n\nbool next_format(const char *fmt[], int &index, int &locked_index)\n{\n bool retval = true;\n\n if (locked_index == -1) {\n index += 1;\n if (fmt[index] == NULL) {\n retval = false;\n }\n }\n else if (index == locked_index) {\n retval = false;\n }\n else {\n index = locked_index;\n }\n\n return retval;\n}\n\nstatic const char *time_fmt_with_zone = \"%a %b %d %H:%M:%S \";\n\nconst char *std_time_fmt[] = {\n \"%Y-%m-%d %H:%M:%S\",\n \"%Y-%m-%d %H:%M\",\n \"%Y-%m-%dT%H:%M:%S\",\n \"%Y-%m-%dT%H:%M:%SZ\",\n \"%Y\/%m\/%d %H:%M:%S\",\n \"%Y\/%m\/%d %H:%M\",\n\n \"%a %b %d %H:%M:%S %Y\",\n \"%a %b %d %H:%M:%S %Z %Y\",\n time_fmt_with_zone,\n\n \"%d\/%b\/%Y:%H:%M:%S %z\",\n\n \"%b %d %H:%M:%S\",\n\n NULL,\n};\n\nconst char *date_time_scanner::scan(const char *time_dest,\n const char *time_fmt[],\n struct tm *tm_out,\n struct timeval &tv_out)\n{\n int curr_time_fmt = -1;\n bool found = false;\n const char *retval = NULL;\n\n if (!time_fmt) {\n time_fmt = std_time_fmt;\n }\n\n while (next_format(time_fmt,\n curr_time_fmt,\n this->dts_fmt_lock)) {\n *tm_out = this->dts_base_tm;\n if ((retval = strptime(time_dest,\n time_fmt[curr_time_fmt],\n tm_out)) != NULL) {\n if (time_fmt[curr_time_fmt] == time_fmt_with_zone) {\n int lpc;\n\n for (lpc = 0; retval[lpc] && retval[lpc] != ' '; lpc++) {\n\n }\n if (retval[lpc] == ' ' &&\n sscanf(&retval[lpc], \"%d\", &tm_out->tm_year) == 1) {\n lpc += 1;\n for (; retval[lpc] && isnumber(retval[lpc]); lpc++) {\n\n }\n retval = &retval[lpc];\n }\n }\n\n if (tm_out->tm_year < 70) {\n tm_out->tm_year = 80;\n }\n tv_out.tv_sec = tm2sec(tm_out);\n tv_out.tv_usec = 0;\n\n this->dts_fmt_lock = curr_time_fmt;\n this->dts_fmt_len = retval - time_dest;\n\n \/* Try to pull out the milli\/micro-second value. *\/\n if (retval[0] == '.' || retval[0] == ',') {\n int sub_seconds = 0, sub_len = 0;\n\n if (sscanf(retval + 1, \"%d%n\", &sub_seconds, &sub_len) == 1) {\n switch (sub_len) {\n case 3:\n tv_out.tv_usec = sub_seconds * 100;\n this->dts_fmt_len += 1 + sub_len;\n break;\n case 6:\n tv_out.tv_usec = sub_seconds;\n this->dts_fmt_len += 1 + sub_len;\n break;\n }\n }\n }\n\n found = true;\n break;\n }\n }\n\n if (!found) {\n retval = NULL;\n }\n\n return retval;\n}\n<commit_msg>use isdigit<commit_after>\/**\n * Copyright (c) 2013, Timothy Stack\n *\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and\/or other materials provided with the distribution.\n * * Neither the name of Timothy Stack nor the names of its contributors\n * may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ''AS IS'' AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY\n * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON\n * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n * @file lnav_util.cc\n *\n * Dumping ground for useful functions with no other home.\n *\/\n\n#include \"config.h\"\n\n#include <stdio.h>\n#include <fcntl.h>\n#include <ctype.h>\n\n#include <sqlite3.h>\n\n#include \"auto_fd.hh\"\n#include \"lnav_util.hh\"\n\nstd::string hash_string(const std::string &str)\n{\n byte_array<SHA_DIGEST_LENGTH> hash;\n SHA_CTX context;\n\n SHA_Init(&context);\n SHA_Update(&context, str.c_str(), str.length());\n SHA_Final(hash.out(), &context);\n\n return hash.to_string();\n}\n\nstd::string time_ago(time_t last_time)\n{\n time_t delta, current_time = time(NULL);\n const char *fmt;\n char buffer[64];\n int amount;\n\n delta = current_time - last_time;\n if (delta < 0) {\n return \"in the future\";\n }\n else if (delta < 60) {\n return \"just now\";\n }\n else if (delta < (60 * 2)) {\n return \"one minute ago\";\n }\n else if (delta < (60 * 60)) {\n fmt = \"%d minutes ago\";\n amount = delta \/ 60;\n }\n else if (delta < (2 * 60 * 60)) {\n return \"one hour ago\";\n }\n else if (delta < (24 * 60 * 60)) {\n fmt = \"%d hours ago\";\n amount = delta \/ (60 * 60);\n }\n else if (delta < (2 * 24 * 60 * 60)) {\n return \"one day ago\";\n }\n else if (delta < (365 * 24 * 60 * 60)) {\n fmt = \"%d days ago\";\n amount = delta \/ (24 * 60 * 60);\n }\n else {\n return \"over a year ago\";\n }\n\n snprintf(buffer, sizeof(buffer), fmt, amount);\n\n return std::string(buffer);\n}\n\n\/* XXX figure out how to do this with the template *\/\nvoid sqlite_close_wrapper(void *mem)\n{\n sqlite3_close((sqlite3 *)mem);\n}\n\nstd::string get_current_dir(void)\n{\n char cwd[FILENAME_MAX];\n std::string retval = \".\";\n\n if (getcwd(cwd, sizeof(cwd)) == NULL) {\n perror(\"getcwd\");\n }\n else {\n retval = std::string(cwd);\n }\n\n if (retval != \"\/\") {\n retval += \"\/\";\n }\n\n return retval;\n}\n\nbool change_to_parent_dir(void)\n{\n bool retval = false;\n char cwd[3] = \"\";\n\n if (getcwd(cwd, sizeof(cwd)) == NULL) {\n \/* perror(\"getcwd\"); *\/\n }\n if (strcmp(cwd, \"\/\") != 0) {\n if (chdir(\"..\") == -1) {\n perror(\"chdir('..')\");\n }\n else {\n retval = true;\n }\n }\n\n return retval;\n}\n\nfile_format_t detect_file_format(const std::string &filename)\n{\n file_format_t retval = FF_UNKNOWN;\n auto_fd fd;\n\n if ((fd = open(filename.c_str(), O_RDONLY)) != -1) {\n char buffer[32];\n int rc;\n\n if ((rc = read(fd, buffer, sizeof(buffer))) > 0) {\n if (rc > 16 &&\n strncmp(buffer, \"SQLite format 3\", 16) == 0) {\n retval = FF_SQLITE_DB;\n }\n }\n }\n\n return retval;\n}\n\nstatic time_t BAD_DATE = -1;\n\ntime_t tm2sec(const struct tm *t)\n{\n int year;\n time_t days;\n const int dayoffset[12] =\n { 306, 337, 0, 31, 61, 92, 122, 153, 184, 214, 245, 275 };\n\n year = t->tm_year;\n\n if (year < 70 || ((sizeof(time_t) <= 4) && (year >= 138))) {\n return BAD_DATE;\n }\n\n \/* shift new year to 1st March in order to make leap year calc easy *\/\n\n if (t->tm_mon < 2) {\n year--;\n }\n\n \/* Find number of days since 1st March 1900 (in the Gregorian calendar). *\/\n\n days = year * 365 + year \/ 4 - year \/ 100 + (year \/ 100 + 3) \/ 4;\n days += dayoffset[t->tm_mon] + t->tm_mday - 1;\n days -= 25508; \/* 1 jan 1970 is 25508 days since 1 mar 1900 *\/\n\n days = ((days * 24 + t->tm_hour) * 60 + t->tm_min) * 60 + t->tm_sec;\n\n if (days < 0) {\n return BAD_DATE;\n } \/* must have overflowed *\/\n else {\n if (t->tm_zone) {\n days -= t->tm_gmtoff;\n }\n return days;\n } \/* must be a valid time *\/\n}\n\nbool next_format(const char *fmt[], int &index, int &locked_index)\n{\n bool retval = true;\n\n if (locked_index == -1) {\n index += 1;\n if (fmt[index] == NULL) {\n retval = false;\n }\n }\n else if (index == locked_index) {\n retval = false;\n }\n else {\n index = locked_index;\n }\n\n return retval;\n}\n\nstatic const char *time_fmt_with_zone = \"%a %b %d %H:%M:%S \";\n\nconst char *std_time_fmt[] = {\n \"%Y-%m-%d %H:%M:%S\",\n \"%Y-%m-%d %H:%M\",\n \"%Y-%m-%dT%H:%M:%S\",\n \"%Y-%m-%dT%H:%M:%SZ\",\n \"%Y\/%m\/%d %H:%M:%S\",\n \"%Y\/%m\/%d %H:%M\",\n\n \"%a %b %d %H:%M:%S %Y\",\n \"%a %b %d %H:%M:%S %Z %Y\",\n time_fmt_with_zone,\n\n \"%d\/%b\/%Y:%H:%M:%S %z\",\n\n \"%b %d %H:%M:%S\",\n\n NULL,\n};\n\nconst char *date_time_scanner::scan(const char *time_dest,\n const char *time_fmt[],\n struct tm *tm_out,\n struct timeval &tv_out)\n{\n int curr_time_fmt = -1;\n bool found = false;\n const char *retval = NULL;\n\n if (!time_fmt) {\n time_fmt = std_time_fmt;\n }\n\n while (next_format(time_fmt,\n curr_time_fmt,\n this->dts_fmt_lock)) {\n *tm_out = this->dts_base_tm;\n if ((retval = strptime(time_dest,\n time_fmt[curr_time_fmt],\n tm_out)) != NULL) {\n if (time_fmt[curr_time_fmt] == time_fmt_with_zone) {\n int lpc;\n\n for (lpc = 0; retval[lpc] && retval[lpc] != ' '; lpc++) {\n\n }\n if (retval[lpc] == ' ' &&\n sscanf(&retval[lpc], \"%d\", &tm_out->tm_year) == 1) {\n lpc += 1;\n for (; retval[lpc] && isdigit(retval[lpc]); lpc++) {\n\n }\n retval = &retval[lpc];\n }\n }\n\n if (tm_out->tm_year < 70) {\n tm_out->tm_year = 80;\n }\n tv_out.tv_sec = tm2sec(tm_out);\n tv_out.tv_usec = 0;\n\n this->dts_fmt_lock = curr_time_fmt;\n this->dts_fmt_len = retval - time_dest;\n\n \/* Try to pull out the milli\/micro-second value. *\/\n if (retval[0] == '.' || retval[0] == ',') {\n int sub_seconds = 0, sub_len = 0;\n\n if (sscanf(retval + 1, \"%d%n\", &sub_seconds, &sub_len) == 1) {\n switch (sub_len) {\n case 3:\n tv_out.tv_usec = sub_seconds * 100;\n this->dts_fmt_len += 1 + sub_len;\n break;\n case 6:\n tv_out.tv_usec = sub_seconds;\n this->dts_fmt_len += 1 + sub_len;\n break;\n }\n }\n }\n\n found = true;\n break;\n }\n }\n\n if (!found) {\n retval = NULL;\n }\n\n return retval;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2009 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include <string>\n\n#include \"base\/message_loop.h\"\n#include \"chrome\/browser\/browser.h\"\n#include \"chrome\/browser\/renderer_host\/render_process_host.h\"\n#include \"chrome\/browser\/renderer_host\/web_cache_manager.h\"\n#include \"chrome\/browser\/tab_contents\/tab_contents.h\"\n#include \"chrome\/test\/in_process_browser_test.h\"\n#include \"chrome\/test\/ui_test_utils.h\"\n#include \"testing\/gtest\/include\/gtest\/gtest.h\"\n\nclass WebCacheManagerBrowserTest : public InProcessBrowserTest {\n};\n\n\/\/ Regression test for http:\/\/crbug.com\/12362. If a renderer crashes and the\n\/\/ user navigates to another tab and back, the browser doesn't crash.\n\/\/ TODO(jam): http:\/\/crbug.com\/15288 disabled because it fails on the build bot.\nIN_PROC_BROWSER_TEST_F(WebCacheManagerBrowserTest, DISABLED_CrashOnceOnly) {\n const FilePath kTestDir(FILE_PATH_LITERAL(\"google\"));\n const FilePath kTestFile(FILE_PATH_LITERAL(\"google.html\"));\n GURL url(ui_test_utils::GetTestUrl(kTestDir, kTestFile));\n\n ui_test_utils::NavigateToURL(browser(), url);\n\n browser()->NewTab();\n ui_test_utils::NavigateToURL(browser(), url);\n\n TabContents* tab = browser()->GetTabContentsAt(0);\n ASSERT_TRUE(tab != NULL);\n base::KillProcess(tab->GetRenderProcessHost()->GetHandle(),\n base::PROCESS_END_KILLED_BY_USER, true);\n\n browser()->SelectTabContentsAt(0, true);\n browser()->NewTab();\n ui_test_utils::NavigateToURL(browser(), url);\n\n browser()->SelectTabContentsAt(0, true);\n browser()->NewTab();\n ui_test_utils::NavigateToURL(browser(), url);\n\n \/\/ We would have crashed at the above line with the bug.\n\n browser()->SelectTabContentsAt(0, true);\n browser()->CloseTab();\n browser()->SelectTabContentsAt(0, true);\n browser()->CloseTab();\n browser()->SelectTabContentsAt(0, true);\n browser()->CloseTab();\n\n ui_test_utils::NavigateToURL(browser(), url);\n\n EXPECT_EQ(\n WebCacheManager::GetInstance()->active_renderers_.size(), 1U);\n EXPECT_EQ(\n WebCacheManager::GetInstance()->inactive_renderers_.size(), 0U);\n EXPECT_EQ(\n WebCacheManager::GetInstance()->stats_.size(), 1U);\n}\n<commit_msg>TTF: Re-enable WebCacheManagerBrowserTest.CrashOnceOnly by marking it flaky.<commit_after>\/\/ Copyright (c) 2009 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include <string>\n\n#include \"base\/message_loop.h\"\n#include \"chrome\/browser\/browser.h\"\n#include \"chrome\/browser\/renderer_host\/render_process_host.h\"\n#include \"chrome\/browser\/renderer_host\/web_cache_manager.h\"\n#include \"chrome\/browser\/tab_contents\/tab_contents.h\"\n#include \"chrome\/test\/in_process_browser_test.h\"\n#include \"chrome\/test\/ui_test_utils.h\"\n#include \"testing\/gtest\/include\/gtest\/gtest.h\"\n\nclass WebCacheManagerBrowserTest : public InProcessBrowserTest {\n};\n\n\/\/ Regression test for http:\/\/crbug.com\/12362. If a renderer crashes and the\n\/\/ user navigates to another tab and back, the browser doesn't crash.\n\/\/ Flaky, http:\/\/crbug.com\/15288.\nIN_PROC_BROWSER_TEST_F(WebCacheManagerBrowserTest, FLAKY_CrashOnceOnly) {\n const FilePath kTestDir(FILE_PATH_LITERAL(\"google\"));\n const FilePath kTestFile(FILE_PATH_LITERAL(\"google.html\"));\n GURL url(ui_test_utils::GetTestUrl(kTestDir, kTestFile));\n\n ui_test_utils::NavigateToURL(browser(), url);\n\n browser()->NewTab();\n ui_test_utils::NavigateToURL(browser(), url);\n\n TabContents* tab = browser()->GetTabContentsAt(0);\n ASSERT_TRUE(tab != NULL);\n base::KillProcess(tab->GetRenderProcessHost()->GetHandle(),\n base::PROCESS_END_KILLED_BY_USER, true);\n\n browser()->SelectTabContentsAt(0, true);\n browser()->NewTab();\n ui_test_utils::NavigateToURL(browser(), url);\n\n browser()->SelectTabContentsAt(0, true);\n browser()->NewTab();\n ui_test_utils::NavigateToURL(browser(), url);\n\n \/\/ We would have crashed at the above line with the bug.\n\n browser()->SelectTabContentsAt(0, true);\n browser()->CloseTab();\n browser()->SelectTabContentsAt(0, true);\n browser()->CloseTab();\n browser()->SelectTabContentsAt(0, true);\n browser()->CloseTab();\n\n ui_test_utils::NavigateToURL(browser(), url);\n\n EXPECT_EQ(\n WebCacheManager::GetInstance()->active_renderers_.size(), 1U);\n EXPECT_EQ(\n WebCacheManager::GetInstance()->inactive_renderers_.size(), 0U);\n EXPECT_EQ(\n WebCacheManager::GetInstance()->stats_.size(), 1U);\n}\n<|endoftext|>"} {"text":"<commit_before>\/******************************************************************************\\\n * ___ __ *\n * \/\\_ \\ __\/\\ \\ *\n * \\\/\/\\ \\ \/\\_\\ \\ \\____ ___ _____ _____ __ *\n * \\ \\ \\ \\\/\\ \\ \\ '__`\\ \/'___\\\/\\ '__`\\\/\\ '__`\\ \/'__`\\ *\n * \\_\\ \\_\\ \\ \\ \\ \\L\\ \\\/\\ \\__\/\\ \\ \\L\\ \\ \\ \\L\\ \\\/\\ \\L\\.\\_ *\n * \/\\____\\\\ \\_\\ \\_,__\/\\ \\____\\\\ \\ ,__\/\\ \\ ,__\/\\ \\__\/.\\_\\ *\n * \\\/____\/ \\\/_\/\\\/___\/ \\\/____\/ \\ \\ \\\/ \\ \\ \\\/ \\\/__\/\\\/_\/ *\n * \\ \\_\\ \\ \\_\\ *\n * \\\/_\/ \\\/_\/ *\n * *\n * Copyright (C) 2011-2013 *\n * Dominik Charousset <dominik.charousset@haw-hamburg.de> *\n * *\n * This file is part of libcppa. *\n * libcppa is free software: you can redistribute it and\/or modify it under *\n * the terms of the GNU Lesser General Public License as published by the *\n * Free Software Foundation; either version 2.1 of the License, *\n * or (at your option) any later version. *\n * *\n * libcppa is distributed in the hope that it will be useful, *\n * but WITHOUT ANY WARRANTY; without even the implied warranty of *\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *\n * See the GNU Lesser General Public License for more details. *\n * *\n * You should have received a copy of the GNU Lesser General Public License *\n * along with libcppa. If not, see <http:\/\/www.gnu.org\/licenses\/>. *\n\\******************************************************************************\/\n\n\n#include <ios>\n#include <sstream>\n\n#include \"cppa\/exception.hpp\"\n#include \"cppa\/detail\/fd_util.hpp\"\n\n#if defined(CPPA_LINUX) || defined(CPPA_MACOS)\n\n#include <errno.h>\n#include <netdb.h>\n#include <fcntl.h>\n#include <string.h>\n#include <unistd.h>\n#include <sys\/types.h>\n#include <sys\/socket.h>\n#include <netinet\/in.h>\n#include <netinet\/tcp.h>\n\nnamespace cppa { namespace detail { namespace fd_util {\n\nvoid throw_io_failure(const char* what, bool add_errno_failure) {\n if (add_errno_failure) {\n std::ostringstream oss;\n oss << what << \": \" << strerror(errno)\n << \" [errno: \" << errno << \"]\";\n throw std::ios_base::failure(oss.str());\n }\n throw std::ios_base::failure(what);\n}\n\nint rd_flags(native_socket_type fd) {\n auto flags = fcntl(fd, F_GETFL, 0);\n if (flags == -1) {\n throw_io_failure(\"unable to read socket flags\");\n }\n return flags;\n}\n\nbool nonblocking(native_socket_type fd) {\n return (rd_flags(fd) & O_NONBLOCK) != 0;\n}\n\nvoid nonblocking(native_socket_type fd, bool new_value) {\n auto rf = rd_flags(fd);\n auto wf = new_value ? (rf | O_NONBLOCK) : (rf & (~(O_NONBLOCK)));\n if (fcntl(fd, F_SETFL, wf) < 0) {\n throw_io_failure(\"unable to set file descriptor flags\");\n }\n}\n\nbool tcp_nodelay(native_socket_type fd) {\n int flag;\n auto len = static_cast<socklen_t>(sizeof(flag));\n if (getsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &flag, &len) < 0) {\n throw_io_failure(\"unable to read TCP_NODELAY socket option\");\n }\n return flag != 0;\n}\n\nvoid tcp_nodelay(native_socket_type fd, bool new_value) {\n int flag = new_value ? 1 : 0;\n if (setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &flag, sizeof(flag)) < 0) {\n throw_io_failure(\"unable to set TCP_NODELAY\");\n }\n}\n\nvoid handle_write_result(ssize_t result, bool is_nonblocking_io) {\n if (result < 0) {\n if (is_nonblocking_io) {\n if (errno == EAGAIN || errno == EWOULDBLOCK) {\n return; \/\/ don't throw, just try again\n }\n }\n throw_io_failure(\"cannot write to file descriptor\");\n }\n}\n\nvoid handle_read_result(ssize_t result, bool is_nonblocking_io) {\n handle_write_result(result, is_nonblocking_io);\n if (result == 0) {\n throw_io_failure(\"cannot read from closed socket \/ file handle\");\n }\n}\n\n} } } \/\/ namespace cppa::detail::fd_util\n\n#else\n\n#endif\n<commit_msg>improved error messages in fd_util<commit_after>\/******************************************************************************\\\n * ___ __ *\n * \/\\_ \\ __\/\\ \\ *\n * \\\/\/\\ \\ \/\\_\\ \\ \\____ ___ _____ _____ __ *\n * \\ \\ \\ \\\/\\ \\ \\ '__`\\ \/'___\\\/\\ '__`\\\/\\ '__`\\ \/'__`\\ *\n * \\_\\ \\_\\ \\ \\ \\ \\L\\ \\\/\\ \\__\/\\ \\ \\L\\ \\ \\ \\L\\ \\\/\\ \\L\\.\\_ *\n * \/\\____\\\\ \\_\\ \\_,__\/\\ \\____\\\\ \\ ,__\/\\ \\ ,__\/\\ \\__\/.\\_\\ *\n * \\\/____\/ \\\/_\/\\\/___\/ \\\/____\/ \\ \\ \\\/ \\ \\ \\\/ \\\/__\/\\\/_\/ *\n * \\ \\_\\ \\ \\_\\ *\n * \\\/_\/ \\\/_\/ *\n * *\n * Copyright (C) 2011-2013 *\n * Dominik Charousset <dominik.charousset@haw-hamburg.de> *\n * *\n * This file is part of libcppa. *\n * libcppa is free software: you can redistribute it and\/or modify it under *\n * the terms of the GNU Lesser General Public License as published by the *\n * Free Software Foundation; either version 2.1 of the License, *\n * or (at your option) any later version. *\n * *\n * libcppa is distributed in the hope that it will be useful, *\n * but WITHOUT ANY WARRANTY; without even the implied warranty of *\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *\n * See the GNU Lesser General Public License for more details. *\n * *\n * You should have received a copy of the GNU Lesser General Public License *\n * along with libcppa. If not, see <http:\/\/www.gnu.org\/licenses\/>. *\n\\******************************************************************************\/\n\n\n#include <ios>\n#include <sstream>\n\n#include \"cppa\/exception.hpp\"\n#include \"cppa\/detail\/fd_util.hpp\"\n\n#if defined(CPPA_LINUX) || defined(CPPA_MACOS)\n\n#include <errno.h>\n#include <netdb.h>\n#include <fcntl.h>\n#include <string.h>\n#include <unistd.h>\n#include <sys\/types.h>\n#include <sys\/socket.h>\n#include <netinet\/in.h>\n#include <netinet\/tcp.h>\n\nnamespace cppa { namespace detail { namespace fd_util {\n\nvoid throw_io_failure(const char* what, bool add_errno_failure) {\n if (add_errno_failure) {\n std::ostringstream oss;\n oss << what << \": \" << strerror(errno)\n << \" [errno: \" << errno << \"]\";\n throw std::ios_base::failure(oss.str());\n }\n throw std::ios_base::failure(what);\n}\n\nint rd_flags(native_socket_type fd) {\n auto flags = fcntl(fd, F_GETFL, 0);\n if (flags == -1) throw_io_failure(\"unable to read socket flags\");\n return flags;\n}\n\nbool nonblocking(native_socket_type fd) {\n return (rd_flags(fd) & O_NONBLOCK) != 0;\n}\n\nvoid nonblocking(native_socket_type fd, bool new_value) {\n auto rf = rd_flags(fd);\n auto wf = new_value ? (rf | O_NONBLOCK) : (rf & (~(O_NONBLOCK)));\n if (fcntl(fd, F_SETFL, wf) < 0) {\n throw_io_failure(\"unable to set file descriptor flags\");\n }\n}\n\nbool tcp_nodelay(native_socket_type fd) {\n int flag;\n auto len = static_cast<socklen_t>(sizeof(flag));\n if (getsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &flag, &len) < 0) {\n throw_io_failure(\"unable to read TCP_NODELAY socket option\");\n }\n return flag != 0;\n}\n\nvoid tcp_nodelay(native_socket_type fd, bool new_value) {\n int flag = new_value ? 1 : 0;\n if (setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &flag, sizeof(flag)) < 0) {\n throw_io_failure(\"unable to set TCP_NODELAY\");\n }\n}\n\nvoid handle_io_result(ssize_t res, bool is_nonblock, const char* msg) {\n if (res < 0) {\n \/\/ don't throw for 'failed' non-blocking IO\n if (is_nonblock && (errno == EAGAIN || errno == EWOULDBLOCK)) { }\n else throw_io_failure(msg);\n }\n}\n\nvoid handle_write_result(ssize_t res, bool is_nonblock) {\n handle_io_result(res, is_nonblock, \"cannot write to file descriptor\");\n}\n\nvoid handle_read_result(ssize_t res, bool is_nonblock) {\n handle_io_result(res, is_nonblock, \"cannot read from file descriptor\");\n if (res == 0) throw_io_failure(\"cannot read from closed file descriptor\");\n}\n\n} } } \/\/ namespace cppa::detail::fd_util\n\n#else\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/* Copyright (c) 2016 Baidu, Inc. All Rights Reserve.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License. *\/\n\n\n#include \"ParamUtil.h\"\n\n#include <fenv.h>\n#include <stdio.h>\n\n#include <iostream>\n#include <iomanip>\n#include <sstream>\n#include <limits>\n\n#include <google\/protobuf\/text_format.h>\n#include <paddle\/utils\/Version.h>\n\n#include \"paddle\/utils\/PythonUtil.h\"\n#include \"paddle\/utils\/Stat.h\"\n#include \"paddle\/utils\/Util.h\"\n#include \"paddle\/utils\/GlobalConstants.h\"\n\n#include \"paddle\/gserver\/gradientmachines\/NeuralNetwork.h\"\n#include \"paddle\/gserver\/layers\/ValidationLayer.h\"\n#include \"TesterConfig.h\"\n\nnamespace paddle {\n\nParameterUtil::ParameterUtil(\n const std::shared_ptr<TrainerConfigHelper> &config,\n std::unique_ptr<ParameterUtilConfig> &&intconfig,\n const GradientMachinePtr &gradientMachine,\n const std::shared_ptr<ParameterUpdater> ¶meterUpdater) {\n config_ = config;\n intConfig_ = std::move(intconfig);\n gserver_ = gradientMachine;\n pUpdater_ = parameterUpdater;\n}\n\n\n\nbool ParameterUtil::loadParameters(int passId, bool local, bool remote) {\n constexpr int kBufLen = 100;\n char buf[kBufLen];\n snprintf(buf, kBufLen, \"pass-%05d\", passId);\n std::string doneFile = path::join(config_->getSaveDir(), buf, \"done\");\n if (!fileExist(doneFile.c_str())) return false;\n loadParametersWithPath(path::join(config_->getSaveDir(), buf), local, remote);\n return true;\n}\n\nvoid ParameterUtil::loadParametersWithPath(const std::string& dir,\n bool local, bool remote) {\n if (local) {\n gserver_->loadParameters(dir);\n }\n if (remote && pUpdater_) {\n pUpdater_->loadParametersRemote(dir);\n }\n}\n\nvoid ParameterUtil::saveParametersOnePass(int passId, int passInnerId) {\n pUpdater_->apply();\n saveParameters(passId, passInnerId);\n if (intConfig_->save_only_one_ && passId >= intConfig_->saving_period_) {\n deleteParameters(passId - intConfig_->saving_period_);\n }\n pUpdater_->restore();\n}\n\nvoid ParameterUtil::saveParameters(int passId, int passInnerId) {\n constexpr int kBufLen = 100;\n char buf[kBufLen];\n if (passInnerId > 0) {\n snprintf(buf, kBufLen, \"pass-%05d-%03d\", passId, passInnerId);\n } else {\n snprintf(buf, kBufLen, \"pass-%05d\", passId);\n }\n\n std::string basePath = config_->getSaveDir();\n mkDirRecursively(basePath.c_str());\n\n std::string saveDir = path::join(basePath, buf);\n mkDir(saveDir.c_str());\n if (!intConfig_->load_save_param_pserver_) {\n pUpdater_->getParametersRemote(true \/*full parameter*\/,\n true \/*after apply*\/);\n }\n\n gserver_->saveParameters(saveDir);\n if (intConfig_->load_save_param_pserver_) {\n pUpdater_->saveParametersRemote(saveDir);\n }\n std::string doneFile = path::join(saveDir, \"done\");\n touchFile(doneFile.c_str());\n std::ofstream out(doneFile);\n version::printVersion(out);\n out.close();\n VLOG(1) << \"save dir \" << saveDir;\n saveConfigWithPath(saveDir);\n}\n\nvoid ParameterUtil::deleteParameters(int passId, int passInnerId) {\n constexpr int kBufLen = 100;\n char buf[kBufLen];\n const std::string& saveDir = config_->getSaveDir();\n if (passInnerId > 0) {\n snprintf(buf, kBufLen, \"%s\/pass-%05d-%03d\", saveDir.c_str(), passId,\n passInnerId);\n } else {\n snprintf(buf, kBufLen, \"%s\/pass-%05d\", saveDir.c_str(), passId);\n }\n mkDir(saveDir.c_str());\n LOG(INFO) << \"delete dir \" << buf;\n rmDir(buf);\n}\n\n\nvoid ParameterUtil::saveConfigWithPath(const std::string& path) {\n std::string src;\n \/\/ save config in some path\n if (!intConfig_->config_.empty()) {\n src = intConfig_->config_;\n } else {\n bool ok;\n src = config_->getConfigName(&ok);\n if (!ok) {\n return;\n }\n }\n copyFileToPath(src, path);\n\n \/\/ save other import config file name to path.txt\n std::string ss = path::join(path, \"path.txt\");\n std::ofstream os(ss);\n std::string fileName = path::basename(src);\n CHECK(os.write(fileName.c_str(), fileName.length()))\n << \"Fail to write config file name \" << ss;\n VLOG(1) << \"fileName \" << fileName;\n os.close();\n\n \/\/ copy other import config files\n for (int i = 0; i < config_->getConfig().config_files_size(); ++i) {\n copyFileToPath(config_->getConfig().config_files(i), path);\n }\n}\n\n} \/\/ namespace paddle\n<commit_msg>Make Paddle --save_dir support a directory name (#277)<commit_after>\/* Copyright (c) 2016 Baidu, Inc. All Rights Reserve.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License. *\/\n\n\n#include \"ParamUtil.h\"\n\n#include <fenv.h>\n#include <stdio.h>\n\n#include <iostream>\n#include <iomanip>\n#include <sstream>\n#include <limits>\n\n#include <google\/protobuf\/text_format.h>\n#include <paddle\/utils\/Version.h>\n\n#include \"paddle\/utils\/PythonUtil.h\"\n#include \"paddle\/utils\/Stat.h\"\n#include \"paddle\/utils\/Util.h\"\n#include \"paddle\/utils\/GlobalConstants.h\"\n\n#include \"paddle\/gserver\/gradientmachines\/NeuralNetwork.h\"\n#include \"paddle\/gserver\/layers\/ValidationLayer.h\"\n#include \"TesterConfig.h\"\n\nnamespace paddle {\n\nParameterUtil::ParameterUtil(\n const std::shared_ptr<TrainerConfigHelper> &config,\n std::unique_ptr<ParameterUtilConfig> &&intconfig,\n const GradientMachinePtr &gradientMachine,\n const std::shared_ptr<ParameterUpdater> ¶meterUpdater) {\n config_ = config;\n intConfig_ = std::move(intconfig);\n gserver_ = gradientMachine;\n pUpdater_ = parameterUpdater;\n}\n\n\n\nbool ParameterUtil::loadParameters(int passId, bool local, bool remote) {\n constexpr int kBufLen = 100;\n char buf[kBufLen];\n snprintf(buf, kBufLen, \"pass-%05d\", passId);\n std::string doneFile = path::join(config_->getSaveDir(), buf, \"done\");\n if (!fileExist(doneFile.c_str())) return false;\n loadParametersWithPath(path::join(config_->getSaveDir(), buf), local, remote);\n return true;\n}\n\nvoid ParameterUtil::loadParametersWithPath(const std::string& dir,\n bool local, bool remote) {\n if (local) {\n gserver_->loadParameters(dir);\n }\n if (remote && pUpdater_) {\n pUpdater_->loadParametersRemote(dir);\n }\n}\n\nvoid ParameterUtil::saveParametersOnePass(int passId, int passInnerId) {\n pUpdater_->apply();\n saveParameters(passId, passInnerId);\n if (intConfig_->save_only_one_ && passId >= intConfig_->saving_period_) {\n deleteParameters(passId - intConfig_->saving_period_);\n }\n pUpdater_->restore();\n}\n\nvoid ParameterUtil::saveParameters(int passId, int passInnerId) {\n constexpr int kBufLen = 100;\n char buf[kBufLen];\n if (passInnerId > 0) {\n snprintf(buf, kBufLen, \"pass-%05d-%03d\", passId, passInnerId);\n } else {\n snprintf(buf, kBufLen, \"pass-%05d\", passId);\n }\n\n std::string basePath = config_->getSaveDir();\n if (basePath.find('\/') == std::string::npos) {\n basePath = \".\/\" + basePath;\n }\n mkDirRecursively(basePath.c_str());\n\n std::string saveDir = path::join(basePath, buf);\n mkDir(saveDir.c_str());\n if (!intConfig_->load_save_param_pserver_) {\n pUpdater_->getParametersRemote(true \/*full parameter*\/,\n true \/*after apply*\/);\n }\n\n gserver_->saveParameters(saveDir);\n if (intConfig_->load_save_param_pserver_) {\n pUpdater_->saveParametersRemote(saveDir);\n }\n std::string doneFile = path::join(saveDir, \"done\");\n touchFile(doneFile.c_str());\n std::ofstream out(doneFile);\n version::printVersion(out);\n out.close();\n VLOG(1) << \"save dir \" << saveDir;\n saveConfigWithPath(saveDir);\n}\n\nvoid ParameterUtil::deleteParameters(int passId, int passInnerId) {\n constexpr int kBufLen = 100;\n char buf[kBufLen];\n const std::string& saveDir = config_->getSaveDir();\n if (passInnerId > 0) {\n snprintf(buf, kBufLen, \"%s\/pass-%05d-%03d\", saveDir.c_str(), passId,\n passInnerId);\n } else {\n snprintf(buf, kBufLen, \"%s\/pass-%05d\", saveDir.c_str(), passId);\n }\n mkDir(saveDir.c_str());\n LOG(INFO) << \"delete dir \" << buf;\n rmDir(buf);\n}\n\n\nvoid ParameterUtil::saveConfigWithPath(const std::string& path) {\n std::string src;\n \/\/ save config in some path\n if (!intConfig_->config_.empty()) {\n src = intConfig_->config_;\n } else {\n bool ok;\n src = config_->getConfigName(&ok);\n if (!ok) {\n return;\n }\n }\n copyFileToPath(src, path);\n\n \/\/ save other import config file name to path.txt\n std::string ss = path::join(path, \"path.txt\");\n std::ofstream os(ss);\n std::string fileName = path::basename(src);\n CHECK(os.write(fileName.c_str(), fileName.length()))\n << \"Fail to write config file name \" << ss;\n VLOG(1) << \"fileName \" << fileName;\n os.close();\n\n \/\/ copy other import config files\n for (int i = 0; i < config_->getConfig().config_files_size(); ++i) {\n copyFileToPath(config_->getConfig().config_files(i), path);\n }\n}\n\n} \/\/ namespace paddle\n<|endoftext|>"} {"text":"<commit_before>#include <assert.h>\n#include <cstdio>\n\n#include <set>\n\n#ifndef HAVE_LLVM\n#error \"This code needs LLVM enabled\"\n#endif\n\n#include <llvm\/IR\/LLVMContext.h>\n#include <llvm\/IR\/Module.h>\n#include <llvm\/IR\/Instructions.h>\n#include <llvm\/Support\/SourceMgr.h>\n#include <llvm\/Support\/raw_os_ostream.h>\n#include <llvm\/IRReader\/IRReader.h>\n#include <llvm\/Bitcode\/ReaderWriter.h>\n\n#include <iostream>\n#include <sstream>\n#include <fstream>\n#include <string>\n#include \"llvm\/LLVMDependenceGraph.h\"\n#include \"llvm\/PointsTo.h\"\n#include \"llvm\/ReachingDefs.h\"\n#include \"llvm\/DefUse.h\"\n#include \"llvm\/Slicer.h\"\n#include \"DG2Dot.h\"\n#include \"Utils.h\"\n\nusing namespace dg;\nusing llvm::errs;\n\nstatic std::ostream& printLLVMVal(std::ostream& os, const llvm::Value *val)\n{\n if (!val) {\n os << \"(null)\";\n return os;\n }\n\n std::ostringstream ostr;\n llvm::raw_os_ostream ro(ostr);\n\n if (llvm::isa<llvm::Function>(val)) {\n ro << \"FUNC \" << val->getName().data();\n } else if (llvm::isa<llvm::BasicBlock>(val)) {\n ro << \"label \" << val->getName().data();\n } else {\n ro << *val;\n }\n\n ro.flush();\n\n \/\/ break the string if it is too long\n std::string str = ostr.str();\n if (str.length() > 100) {\n str.resize(40);\n }\n\n \/\/ escape the \"\n size_t pos = 0;\n while ((pos = str.find('\"', pos)) != std::string::npos) {\n str.replace(pos, 1, \"\\\\\\\"\");\n \/\/ we replaced one char with two, so we must shift after the new \"\n pos += 2;\n }\n\n os << str;\n\n return os;\n}\n\nstatic std::ostream& operator<<(std::ostream& os, const analysis::Offset& off)\n{\n if (off.offset == UNKNOWN_OFFSET)\n os << \"UNKNOWN\";\n else\n os << off.offset;\n}\n\nstatic bool debug_def = false;\nstatic bool debug_ptr = false;\n\nstatic bool checkNode(std::ostream& os, LLVMNode *node)\n{\n bool err = false;\n const llvm::Value *val = node->getKey();\n\n if (!val) {\n os << \"\\\\nERR: no value in node\";\n return true;\n }\n\n if (!node->getBBlock()\n && !llvm::isa<llvm::Function>(val)\n && !llvm::isa<llvm::GlobalVariable>(val)) {\n err = true;\n os << \"\\\\nERR: no BB\";\n }\n\n if (debug_ptr) {\n const analysis::PointsToSetT& ptsto = node->getPointsTo();\n if (ptsto.empty() && val->getType()->isPointerTy()) {\n os << \"\\\\lERR: pointer without pointsto set\";\n err = true;\n } else\n os << \"\\\\l -- points-to info --\";\n\n for (auto it : ptsto) {\n os << \"\\\\l[\";\n if (it.isUnknown())\n os << \"unknown\";\n else if (it.obj->isUnknown())\n os << \"unknown mem\";\n else if (it.obj->isNull())\n os << \"nullptr\";\n else\n printLLVMVal(os, it.obj->node->getKey());\n os << \"] + \" << it.offset;\n }\n\n analysis::MemoryObj *mo = node->getMemoryObj();\n if (mo) {\n for (auto it : mo->pointsTo) {\n for(auto it2 : it.second) {\n os << \"\\\\lmem: [\" << it.first << \"] -> [\";\n if (it2.isUnknown())\n os << \"unknown\";\n else if (it2.obj->isUnknown())\n os << \"unknown mem\";\n else if (it2.obj->isNull())\n os << \"nullptr\";\n else\n printLLVMVal(os, it2.obj->node->getKey());\n os << \"] + \" << it2.offset;\n }\n }\n }\n }\n\n if (debug_def) {\n analysis::DefMap *df = node->getData<analysis::DefMap>();\n if (df) {\n os << \"\\\\l -- reaching defs info --\";\n for (auto it : df->getDefs()) {\n for (auto v : it.second) {\n os << \"\\\\l: [\";\n if (it.first.obj->isUnknown())\n os << \"[unknown\";\n else\n printLLVMVal(os, it.first.obj->node->getKey());\n os << \"] + \" << it.first.offset << \" @ \";\n printLLVMVal(os, v->getKey());\n }\n }\n }\n }\n\n return err;\n}\n\nstatic const char *slicing_criterion;\nstatic bool mark_only = false;\nstatic const char *dump_func_only = nullptr;\n\nint main(int argc, char *argv[])\n{\n llvm::LLVMContext context;\n llvm::SMDiagnostic SMD;\n llvm::Module *M;\n const char *module = NULL;\n\n using namespace debug;\n uint32_t opts = PRINT_CFG | PRINT_DD | PRINT_CD;\n\n \/\/ parse options\n for (int i = 1; i < argc; ++i) {\n if (strcmp(argv[i], \"-no-control\") == 0) {\n opts &= ~PRINT_CD;\n } else if (strcmp(argv[i], \"-no-data\") == 0) {\n opts &= ~PRINT_DD;\n } else if (strcmp(argv[i], \"-nocfg\") == 0) {\n opts &= ~PRINT_CFG;\n } else if (strcmp(argv[i], \"-call\") == 0) {\n opts |= PRINT_CALL;\n } else if (strcmp(argv[i], \"-cfgall\") == 0) {\n opts |= PRINT_CFG;\n opts |= PRINT_REV_CFG;\n } else if (strcmp(argv[i], \"-func\") == 0) {\n dump_func_only = argv[++i];\n } else if (strcmp(argv[i], \"-def\") == 0) {\n debug_def = true;\n } else if (strcmp(argv[i], \"-ptr\") == 0) {\n debug_ptr = true;\n } else if (strcmp(argv[i], \"-slice\") == 0) {\n slicing_criterion = argv[++i];\n } else if (strcmp(argv[i], \"-mark\") == 0) {\n mark_only = true;\n slicing_criterion = argv[++i];\n } else {\n module = argv[i];\n }\n }\n\n if (!module) {\n errs() << \"Usage: % IR_module [output_file]\\n\";\n return 1;\n }\n\n M = llvm::ParseIRFile(module, SMD, context);\n if (!M) {\n SMD.print(argv[0], errs());\n return 1;\n }\n\n debug::TimeMeasure tm;\n\n LLVMDependenceGraph d;\n d.build(M);\n\n analysis::LLVMPointsToAnalysis PTA(&d);\n\n tm.start();\n PTA.run();\n tm.stop();\n tm.report(\"INFO: Points-to analysis took\");\n\n std::set<LLVMNode *> callsites;\n if (slicing_criterion) {\n const char *sc[] = {\n slicing_criterion,\n \"klee_assume\",\n NULL\n };\n\n tm.start();\n d.getCallSites(sc, &callsites);\n tm.stop();\n tm.report(\"INFO: Finding slicing criterions took\");\n }\n\n\n analysis::LLVMReachingDefsAnalysis RDA(&d);\n tm.start();\n RDA.run(); \/\/ compute reaching definitions\n tm.stop();\n tm.report(\"INFO: Reaching defs analysis took\");\n\n analysis::LLVMDefUseAnalysis DUA(&d);\n tm.start();\n DUA.run(); \/\/ add def-use edges according that\n tm.stop();\n tm.report(\"INFO: Adding Def-Use edges took\");\n\n tm.start();\n \/\/ add post-dominator frontiers\n d.computePostDominators(true);\n tm.stop();\n tm.report(\"INFO: computing post-dominator frontiers took\");\n\n if (slicing_criterion) {\n LLVMSlicer slicer;\n tm.start();\n\n if (strcmp(slicing_criterion, \"ret\") == 0) {\n if (mark_only)\n slicer.mark(d.getExit());\n else\n slicer.slice(&d, d.getExit());\n } else {\n if (callsites.empty()) {\n errs() << \"ERR: slicing criterion not found: \"\n << slicing_criterion << \"\\n\";\n exit(1);\n }\n\n uint32_t slid = 0;\n for (LLVMNode *start : callsites)\n slid = slicer.mark(start, slid);\n\n if (!mark_only)\n slicer.slice(&d, nullptr, slid);\n }\n\n \/\/ there's overhead but nevermind\n tm.stop();\n tm.report(\"INFO: Slicing took\");\n\n if (!mark_only) {\n std::string fl(module);\n fl.append(\".sliced\");\n std::ofstream ofs(fl);\n llvm::raw_os_ostream output(ofs);\n\n auto st = slicer.getStatistics();\n errs() << \"INFO: Sliced away \" << st.second\n << \" from \" << st.first << \" nodes\\n\";\n\n llvm::WriteBitcodeToFile(M, output);\n }\n }\n\n debug::DG2Dot<LLVMNode> dump(&d, opts);\n\n dump.printKey = printLLVMVal;\n dump.checkNode = checkNode;\n const std::map<const llvm::Value *,\n LLVMDependenceGraph *>& CF = getConstructedFunctions();\n\n dump.start();\n for (auto F : CF) {\n if (dump_func_only && !F.first->getName().equals(dump_func_only))\n continue;\n\n dump.dumpSubgraphStart(F.second, F.first->getName().data());\n\n for (auto B : F.second->getConstructedBlocks()) {\n dump.dumpBBlock(B.second);\n }\n\n for (auto B : F.second->getConstructedBlocks()) {\n dump.dumpBBlockEdges(B.second);\n }\n\n dump.dumpSubgraphEnd(F.second);\n }\n\n dump.end();\n\n return 0;\n}\n<commit_msg>llvm-dg-dump: add -postdom option<commit_after>#include <assert.h>\n#include <cstdio>\n\n#include <set>\n\n#ifndef HAVE_LLVM\n#error \"This code needs LLVM enabled\"\n#endif\n\n#include <llvm\/IR\/LLVMContext.h>\n#include <llvm\/IR\/Module.h>\n#include <llvm\/IR\/Instructions.h>\n#include <llvm\/Support\/SourceMgr.h>\n#include <llvm\/Support\/raw_os_ostream.h>\n#include <llvm\/IRReader\/IRReader.h>\n#include <llvm\/Bitcode\/ReaderWriter.h>\n\n#include <iostream>\n#include <sstream>\n#include <fstream>\n#include <string>\n#include \"llvm\/LLVMDependenceGraph.h\"\n#include \"llvm\/PointsTo.h\"\n#include \"llvm\/ReachingDefs.h\"\n#include \"llvm\/DefUse.h\"\n#include \"llvm\/Slicer.h\"\n#include \"DG2Dot.h\"\n#include \"Utils.h\"\n\nusing namespace dg;\nusing llvm::errs;\n\nstatic std::ostream& printLLVMVal(std::ostream& os, const llvm::Value *val)\n{\n if (!val) {\n os << \"(null)\";\n return os;\n }\n\n std::ostringstream ostr;\n llvm::raw_os_ostream ro(ostr);\n\n if (llvm::isa<llvm::Function>(val)) {\n ro << \"FUNC \" << val->getName().data();\n } else if (llvm::isa<llvm::BasicBlock>(val)) {\n ro << \"label \" << val->getName().data();\n } else {\n ro << *val;\n }\n\n ro.flush();\n\n \/\/ break the string if it is too long\n std::string str = ostr.str();\n if (str.length() > 100) {\n str.resize(40);\n }\n\n \/\/ escape the \"\n size_t pos = 0;\n while ((pos = str.find('\"', pos)) != std::string::npos) {\n str.replace(pos, 1, \"\\\\\\\"\");\n \/\/ we replaced one char with two, so we must shift after the new \"\n pos += 2;\n }\n\n os << str;\n\n return os;\n}\n\nstatic std::ostream& operator<<(std::ostream& os, const analysis::Offset& off)\n{\n if (off.offset == UNKNOWN_OFFSET)\n os << \"UNKNOWN\";\n else\n os << off.offset;\n}\n\nstatic bool debug_def = false;\nstatic bool debug_ptr = false;\n\nstatic bool checkNode(std::ostream& os, LLVMNode *node)\n{\n bool err = false;\n const llvm::Value *val = node->getKey();\n\n if (!val) {\n os << \"\\\\nERR: no value in node\";\n return true;\n }\n\n if (!node->getBBlock()\n && !llvm::isa<llvm::Function>(val)\n && !llvm::isa<llvm::GlobalVariable>(val)) {\n err = true;\n os << \"\\\\nERR: no BB\";\n }\n\n if (debug_ptr) {\n const analysis::PointsToSetT& ptsto = node->getPointsTo();\n if (ptsto.empty() && val->getType()->isPointerTy()) {\n os << \"\\\\lERR: pointer without pointsto set\";\n err = true;\n } else\n os << \"\\\\l -- points-to info --\";\n\n for (auto it : ptsto) {\n os << \"\\\\l[\";\n if (it.isUnknown())\n os << \"unknown\";\n else if (it.obj->isUnknown())\n os << \"unknown mem\";\n else if (it.obj->isNull())\n os << \"nullptr\";\n else\n printLLVMVal(os, it.obj->node->getKey());\n os << \"] + \" << it.offset;\n }\n\n analysis::MemoryObj *mo = node->getMemoryObj();\n if (mo) {\n for (auto it : mo->pointsTo) {\n for(auto it2 : it.second) {\n os << \"\\\\lmem: [\" << it.first << \"] -> [\";\n if (it2.isUnknown())\n os << \"unknown\";\n else if (it2.obj->isUnknown())\n os << \"unknown mem\";\n else if (it2.obj->isNull())\n os << \"nullptr\";\n else\n printLLVMVal(os, it2.obj->node->getKey());\n os << \"] + \" << it2.offset;\n }\n }\n }\n }\n\n if (debug_def) {\n analysis::DefMap *df = node->getData<analysis::DefMap>();\n if (df) {\n os << \"\\\\l -- reaching defs info --\";\n for (auto it : df->getDefs()) {\n for (auto v : it.second) {\n os << \"\\\\l: [\";\n if (it.first.obj->isUnknown())\n os << \"[unknown\";\n else\n printLLVMVal(os, it.first.obj->node->getKey());\n os << \"] + \" << it.first.offset << \" @ \";\n printLLVMVal(os, v->getKey());\n }\n }\n }\n }\n\n return err;\n}\n\nstatic const char *slicing_criterion;\nstatic bool mark_only = false;\nstatic const char *dump_func_only = nullptr;\n\nint main(int argc, char *argv[])\n{\n llvm::LLVMContext context;\n llvm::SMDiagnostic SMD;\n llvm::Module *M;\n const char *module = NULL;\n\n using namespace debug;\n uint32_t opts = PRINT_CFG | PRINT_DD | PRINT_CD;\n\n \/\/ parse options\n for (int i = 1; i < argc; ++i) {\n if (strcmp(argv[i], \"-no-control\") == 0) {\n opts &= ~PRINT_CD;\n } else if (strcmp(argv[i], \"-no-data\") == 0) {\n opts &= ~PRINT_DD;\n } else if (strcmp(argv[i], \"-nocfg\") == 0) {\n opts &= ~PRINT_CFG;\n } else if (strcmp(argv[i], \"-call\") == 0) {\n opts |= PRINT_CALL;\n } else if (strcmp(argv[i], \"-postdom\") == 0) {\n opts |= PRINT_POSTDOM;\n } else if (strcmp(argv[i], \"-cfgall\") == 0) {\n opts |= PRINT_CFG;\n opts |= PRINT_REV_CFG;\n } else if (strcmp(argv[i], \"-func\") == 0) {\n dump_func_only = argv[++i];\n } else if (strcmp(argv[i], \"-def\") == 0) {\n debug_def = true;\n } else if (strcmp(argv[i], \"-ptr\") == 0) {\n debug_ptr = true;\n } else if (strcmp(argv[i], \"-slice\") == 0) {\n slicing_criterion = argv[++i];\n } else if (strcmp(argv[i], \"-mark\") == 0) {\n mark_only = true;\n slicing_criterion = argv[++i];\n } else {\n module = argv[i];\n }\n }\n\n if (!module) {\n errs() << \"Usage: % IR_module [output_file]\\n\";\n return 1;\n }\n\n M = llvm::ParseIRFile(module, SMD, context);\n if (!M) {\n SMD.print(argv[0], errs());\n return 1;\n }\n\n debug::TimeMeasure tm;\n\n LLVMDependenceGraph d;\n d.build(M);\n\n analysis::LLVMPointsToAnalysis PTA(&d);\n\n tm.start();\n PTA.run();\n tm.stop();\n tm.report(\"INFO: Points-to analysis took\");\n\n std::set<LLVMNode *> callsites;\n if (slicing_criterion) {\n const char *sc[] = {\n slicing_criterion,\n \"klee_assume\",\n NULL\n };\n\n tm.start();\n d.getCallSites(sc, &callsites);\n tm.stop();\n tm.report(\"INFO: Finding slicing criterions took\");\n }\n\n\n analysis::LLVMReachingDefsAnalysis RDA(&d);\n tm.start();\n RDA.run(); \/\/ compute reaching definitions\n tm.stop();\n tm.report(\"INFO: Reaching defs analysis took\");\n\n analysis::LLVMDefUseAnalysis DUA(&d);\n tm.start();\n DUA.run(); \/\/ add def-use edges according that\n tm.stop();\n tm.report(\"INFO: Adding Def-Use edges took\");\n\n tm.start();\n \/\/ add post-dominator frontiers\n d.computePostDominators(true);\n tm.stop();\n tm.report(\"INFO: computing post-dominator frontiers took\");\n\n if (slicing_criterion) {\n LLVMSlicer slicer;\n tm.start();\n\n if (strcmp(slicing_criterion, \"ret\") == 0) {\n if (mark_only)\n slicer.mark(d.getExit());\n else\n slicer.slice(&d, d.getExit());\n } else {\n if (callsites.empty()) {\n errs() << \"ERR: slicing criterion not found: \"\n << slicing_criterion << \"\\n\";\n exit(1);\n }\n\n uint32_t slid = 0;\n for (LLVMNode *start : callsites)\n slid = slicer.mark(start, slid);\n\n if (!mark_only)\n slicer.slice(&d, nullptr, slid);\n }\n\n \/\/ there's overhead but nevermind\n tm.stop();\n tm.report(\"INFO: Slicing took\");\n\n if (!mark_only) {\n std::string fl(module);\n fl.append(\".sliced\");\n std::ofstream ofs(fl);\n llvm::raw_os_ostream output(ofs);\n\n auto st = slicer.getStatistics();\n errs() << \"INFO: Sliced away \" << st.second\n << \" from \" << st.first << \" nodes\\n\";\n\n llvm::WriteBitcodeToFile(M, output);\n }\n }\n\n debug::DG2Dot<LLVMNode> dump(&d, opts);\n\n dump.printKey = printLLVMVal;\n dump.checkNode = checkNode;\n const std::map<const llvm::Value *,\n LLVMDependenceGraph *>& CF = getConstructedFunctions();\n\n dump.start();\n for (auto F : CF) {\n if (dump_func_only && !F.first->getName().equals(dump_func_only))\n continue;\n\n dump.dumpSubgraphStart(F.second, F.first->getName().data());\n\n for (auto B : F.second->getConstructedBlocks()) {\n dump.dumpBBlock(B.second);\n }\n\n for (auto B : F.second->getConstructedBlocks()) {\n dump.dumpBBlockEdges(B.second);\n }\n\n dump.dumpSubgraphEnd(F.second);\n }\n\n dump.end();\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2018 Chris Ohk, Youngjoong Kim, SeungHyun Jeon\n\n\/\/ We are making my contributions\/submissions to this project solely in our\n\/\/ personal capacity and are not conveying any rights to any intellectual\n\/\/ property of any third parties.\n\n#include \"gtest\/gtest.h\"\n\n#include <hspp\/Managers\/GameAgent.hpp>\n#include <hspp\/Tasks\/PlayerTasks\/GameEndTask.hpp>\n\nusing namespace Hearthstonepp;\nusing namespace PlayerTasks;\n\nTEST(GameEndTask, GetTaskID)\n{\n const GameEndTask gameEnd;\n EXPECT_EQ(gameEnd.GetTaskID(), +TaskID::GAME_END);\n}\n\nTEST(GameEndTask, Run)\n{\n GameEndTask gameEnd;\n GameAgent agent(CardClass::ROGUE, CardClass::DRUID, PlayerType::PLAYER1);\n\n agent.GetPlayer1().SetID(100);\n\n MetaData result = gameEnd.Run(agent.GetPlayer1());\n EXPECT_EQ(result, MetaData::GAME_END);\n\n TaskMeta meta;\n result = gameEnd.Run(agent.GetPlayer1(), meta);\n EXPECT_EQ(result, MetaData::GAME_END);\n EXPECT_EQ(meta.GetID(), +TaskID::GAME_END);\n EXPECT_EQ(meta.GetStatus(), MetaData::GAME_END);\n EXPECT_EQ(meta.GetUserID(), agent.GetPlayer1().GetID());\n}\n<commit_msg>refactor: Replace GameAgent to Game<commit_after>\/\/ Copyright (c) 2018 Chris Ohk, Youngjoong Kim, SeungHyun Jeon\n\n\/\/ We are making my contributions\/submissions to this project solely in our\n\/\/ personal capacity and are not conveying any rights to any intellectual\n\/\/ property of any third parties.\n\n#include \"gtest\/gtest.h\"\n\n#include <hspp\/Game\/Game.hpp>\n#include <hspp\/Tasks\/PlayerTasks\/GameEndTask.hpp>\n\nusing namespace Hearthstonepp;\nusing namespace PlayerTasks;\n\nTEST(GameEndTask, GetTaskID)\n{\n const GameEndTask gameEnd;\n EXPECT_EQ(gameEnd.GetTaskID(), +TaskID::GAME_END);\n}\n\nTEST(GameEndTask, Run)\n{\n GameEndTask gameEnd;\n Game game(CardClass::ROGUE, CardClass::DRUID, PlayerType::PLAYER1);\n\n game.GetPlayer1().SetID(100);\n\n MetaData result = gameEnd.Run(game.GetPlayer1());\n EXPECT_EQ(result, MetaData::GAME_END);\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"MipsExecutor.h\"\r\n\r\nCMipsExecutor::CMipsExecutor(CMIPS& context, uint32 maxAddress)\r\n: m_context(context)\r\n, m_subTableCount(0)\r\n#ifdef DEBUGGER_INCLUDED\r\n, m_breakpointsDisabledOnce(false)\r\n#endif\r\n{\r\n\tif(maxAddress < 0x10000)\r\n\t{\r\n\t\tmaxAddress = 0x10000;\r\n\t}\r\n\tassert((maxAddress & 0xFFFF) == 0);\r\n\tif(maxAddress == 0)\r\n\t{\r\n\t\tm_subTableCount = 0x10000;\r\n\t}\r\n\telse\r\n\t{\r\n\t\tm_subTableCount = maxAddress \/ 0x10000;\r\n\t}\r\n\tm_blockTable = new CBasicBlock**[m_subTableCount];\r\n\tmemset(m_blockTable, 0, sizeof(CBasicBlock**) * m_subTableCount);\r\n}\r\n\r\nCMipsExecutor::~CMipsExecutor()\r\n{\r\n\tfor(unsigned int i = 0; i < m_subTableCount; i++)\r\n\t{\r\n\t\tCBasicBlock** subTable = m_blockTable[i];\r\n\t\tif(subTable != NULL)\r\n\t\t{\r\n\t\t\tdelete [] subTable;\r\n\t\t}\r\n\t}\r\n\tdelete [] m_blockTable;\r\n}\r\n\r\nvoid CMipsExecutor::Reset()\r\n{\r\n\tClearActiveBlocks();\r\n}\r\n\r\nvoid CMipsExecutor::ClearActiveBlocks()\r\n{\r\n\tfor(unsigned int i = 0; i < m_subTableCount; i++)\r\n\t{\r\n\t\tCBasicBlock** subTable = m_blockTable[i];\r\n\t\tif(subTable != NULL)\r\n\t\t{\r\n\t\t\tfor(uint32 lo = 0; lo < 0x10000; lo += 4)\r\n\t\t\t{\r\n\t\t\t\tauto block = subTable[lo \/ 4];\r\n\t\t\t\tif(block != nullptr)\r\n\t\t\t\t{\r\n\t\t\t\t\t\/\/We reset the values here because the block might\r\n\t\t\t\t\t\/\/still be held by another object (ie.: VuExecutor)\r\n\t\t\t\t\tblock->ClearReferers();\r\n\t\t\t\t\tblock->SetLinkedBlock(0, nullptr);\r\n\t\t\t\t\tblock->SetLinkedBlock(1, nullptr);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tdelete [] subTable;\r\n\t\t\tm_blockTable[i] = NULL;\r\n\t\t}\r\n\t}\r\n\t\r\n\tm_blocks.clear();\r\n}\r\n\r\nvoid CMipsExecutor::ClearActiveBlocksInRange(uint32 start, uint32 end)\r\n{\r\n\tuint32 hiStart = start >> 16;\r\n\tuint32 hiEnd = end >> 16;\r\n\r\n\tstd::set<CBasicBlock*> blocksToDelete;\r\n\r\n\tfor(uint32 hi = hiStart; hi <= hiEnd; hi++)\r\n\t{\r\n\t\tCBasicBlock** table = m_blockTable[hi];\r\n\t\tif(table == nullptr) continue;\r\n\r\n\t\tfor(uint32 lo = 0; lo < 0x10000; lo += 4)\r\n\t\t{\r\n\t\t\tuint32 tableAddress = (hi << 16) | lo;\r\n\t\t\tif(tableAddress < start) continue;\r\n\t\t\tif(tableAddress >= end) continue;\r\n\t\t\tCBasicBlock* block = table[lo \/ 4];\r\n\t\t\tif(block == nullptr) continue;\r\n\t\t\ttable[lo \/ 4] = nullptr;\r\n\t\t\tblocksToDelete.insert(block);\r\n\t\t}\r\n\t}\r\n\r\n\tif(!blocksToDelete.empty())\r\n\t{\r\n\t\t\/\/TODO: Actually delete the blocks, because remove_if only rearranges items leaving us a new end iterator\r\n\t\tm_blocks.remove_if([&] (const BasicBlockPtr& block) { return blocksToDelete.find(block.get()) != std::end(blocksToDelete); });\r\n\t}\r\n}\r\n\r\nint CMipsExecutor::Execute(int cycles)\r\n{\r\n\tCBasicBlock* block(nullptr);\r\n\twhile(cycles > 0)\r\n\t{\r\n\t\tuint32 address = m_context.m_pAddrTranslator(&m_context, m_context.m_State.nPC);\r\n\t\tif(!block || address != block->GetBeginAddress())\r\n\t\t{\r\n\t\t\tblock = FindBlockStartingAt(address);\r\n\t\t\tif(block == NULL)\r\n\t\t\t{\r\n\t\t\t\t\/\/We need to partition the space and compile the blocks\r\n\t\t\t\tPartitionFunction(address);\r\n\t\t\t\tblock = FindBlockStartingAt(address);\r\n\t\t\t\tif(block == NULL)\r\n\t\t\t\t{\r\n\t\t\t\t\tthrow std::runtime_error(\"Couldn't create block starting at address.\");\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tif(!block->IsCompiled())\r\n\t\t\t{\r\n\t\t\t\tblock->Compile();\r\n\t\t\t}\r\n\t\t}\r\n\t\telse if(block != NULL)\r\n\t\t{\r\n\t\t\tblock->SetSelfLoopCount(block->GetSelfLoopCount() + 1);\r\n\t\t}\r\n\r\n#ifdef DEBUGGER_INCLUDED\r\n\t\tif(!m_breakpointsDisabledOnce && MustBreak()) break;\r\n\t\tm_breakpointsDisabledOnce = false;\r\n#endif\r\n\t\tcycles -= block->Execute();\r\n\t\tif(m_context.m_State.nHasException) break;\r\n\t}\r\n\treturn cycles;\r\n}\r\n\r\n#ifdef DEBUGGER_INCLUDED\r\n\r\nbool CMipsExecutor::MustBreak() const\r\n{\r\n\tuint32 currentPc = m_context.m_pAddrTranslator(&m_context, m_context.m_State.nPC);\r\n\tCBasicBlock* block = FindBlockAt(currentPc);\r\n\tfor(auto breakPointIterator(m_context.m_breakpoints.begin());\r\n\t\tbreakPointIterator != m_context.m_breakpoints.end(); breakPointIterator++)\r\n\t{\r\n\t\tuint32 breakPointAddress = *breakPointIterator;\r\n\t\tif(currentPc == breakPointAddress) return true;\r\n\t\tif(block != NULL)\r\n\t\t{\r\n\t\t\tif(breakPointAddress >= block->GetBeginAddress() && breakPointAddress <= block->GetEndAddress()) return true;\r\n\t\t}\r\n\t}\r\n\treturn false;\r\n}\r\n\r\nvoid CMipsExecutor::DisableBreakpointsOnce()\r\n{\r\n\tm_breakpointsDisabledOnce = true;\r\n}\r\n\r\n#endif\r\n\r\nCBasicBlock* CMipsExecutor::FindBlockAt(uint32 address) const\r\n{\r\n\tuint32 hiAddress = address >> 16;\r\n\tuint32 loAddress = address & 0xFFFF;\r\n\tassert(hiAddress < m_subTableCount);\r\n\tCBasicBlock**& subTable = m_blockTable[hiAddress];\r\n\tif(subTable == NULL) return NULL;\r\n\tCBasicBlock* result = subTable[loAddress \/ 4];\r\n\treturn result;\r\n}\r\n\r\nCBasicBlock* CMipsExecutor::FindBlockStartingAt(uint32 address) const\r\n{\r\n\tuint32 hiAddress = address >> 16;\r\n\tuint32 loAddress = address & 0xFFFF;\r\n\tassert(hiAddress < m_subTableCount);\r\n\tCBasicBlock**& subTable = m_blockTable[hiAddress];\r\n\tif(subTable == NULL) return NULL;\r\n\tCBasicBlock* result = subTable[loAddress \/ 4];\r\n\tif((address != 0) && (FindBlockAt(address - 4) == result))\r\n\t{\r\n\t\treturn NULL;\r\n\t}\r\n\treturn result;\r\n}\r\n\r\nvoid CMipsExecutor::CreateBlock(uint32 start, uint32 end)\r\n{\r\n\t{\r\n\t\tCBasicBlock* block = FindBlockAt(start);\r\n\t\tif(block)\r\n\t\t{\r\n\t\t\t\/\/If the block starts and ends at the same place, block already exists and doesn't need\r\n\t\t\t\/\/to be re-created\r\n\t\t\tuint32 otherBegin = block->GetBeginAddress();\r\n\t\t\tuint32 otherEnd = block->GetEndAddress();\r\n\t\t\tif((otherBegin == start) && (otherEnd == end))\r\n\t\t\t{\r\n\t\t\t\treturn;\r\n\t\t\t}\r\n\t\t\tif(otherEnd == end)\r\n\t\t\t{\r\n\t\t\t\t\/\/Repartition the existing block if end of both blocks are the same\r\n\t\t\t\tDeleteBlock(block);\r\n\t\t\t\tCreateBlock(otherBegin, start - 4);\r\n\t\t\t\tassert(FindBlockAt(start) == NULL);\r\n\t\t\t}\r\n\t\t\telse if(otherBegin == start)\r\n\t\t\t{\r\n\t\t\t\tDeleteBlock(block);\r\n\t\t\t\tCreateBlock(end + 4, otherEnd);\r\n\t\t\t\tassert(FindBlockAt(end) == NULL);\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\t\/\/Delete the currently existing block otherwise\r\n\t\t\t\tprintf(\"MipsExecutor: Warning. Deleting block at %0.8X.\\r\\n\", block->GetEndAddress());\r\n\t\t\t\tDeleteBlock(block);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tassert(FindBlockAt(end) == NULL);\r\n\t{\r\n\t\tBasicBlockPtr block = BlockFactory(m_context, start, end);\r\n\t\tfor(uint32 address = block->GetBeginAddress(); address <= block->GetEndAddress(); address += 4)\r\n\t\t{\r\n\t\t\tuint32 hiAddress = address >> 16;\r\n\t\t\tuint32 loAddress = address & 0xFFFF;\r\n\t\t\tassert(hiAddress < m_subTableCount);\r\n\t\t\tCBasicBlock**& subTable = m_blockTable[hiAddress];\r\n\t\t\tif(subTable == NULL)\r\n\t\t\t{\r\n\t\t\t\tconst uint32 subTableSize = 0x10000 \/ 4;\r\n\t\t\t\tsubTable = new CBasicBlock*[subTableSize];\r\n\t\t\t\tmemset(subTable, 0, sizeof(CBasicBlock*) * subTableSize);\r\n\t\t\t}\r\n\t\t\tassert(subTable[loAddress \/ 4] == NULL);\r\n\t\t\tsubTable[loAddress \/ 4] = block.get();\r\n\t\t}\r\n\t\tm_blocks.push_back(std::move(block));\r\n\t}\r\n}\r\n\r\nvoid CMipsExecutor::DeleteBlock(CBasicBlock* block)\r\n{\r\n\tfor(uint32 address = block->GetBeginAddress(); address <= block->GetEndAddress(); address += 4)\r\n\t{\r\n\t\tuint32 hiAddress = address >> 16;\r\n\t\tuint32 loAddress = address & 0xFFFF;\r\n\t\tassert(hiAddress < m_subTableCount);\r\n\t\tCBasicBlock**& subTable = m_blockTable[hiAddress];\r\n\t\tassert(subTable != NULL);\r\n\t\tassert(subTable[loAddress \/ 4] != NULL);\r\n\t\tsubTable[loAddress \/ 4] = NULL;\r\n\t}\r\n\r\n\t\/\/Remove block from our lists\r\n\tauto blockIterator = std::find_if(std::begin(m_blocks), std::end(m_blocks), [&] (const BasicBlockPtr& blockPtr) { return blockPtr.get() == block; });\r\n\tassert(blockIterator != std::end(m_blocks));\r\n\tm_blocks.erase(blockIterator);\r\n}\r\n\r\nCMipsExecutor::BasicBlockPtr CMipsExecutor::BlockFactory(CMIPS& context, uint32 start, uint32 end)\r\n{\r\n\treturn std::make_shared<CBasicBlock>(context, start, end);\r\n}\r\n\r\nvoid CMipsExecutor::PartitionFunction(uint32 functionAddress)\r\n{\r\n\ttypedef std::set<uint32> PartitionPointSet;\r\n\tuint32 endAddress = 0;\r\n\tPartitionPointSet partitionPoints;\r\n\r\n\t\/\/Insert begin point\r\n\tpartitionPoints.insert(functionAddress);\r\n\r\n\t\/\/Find the end\r\n\tfor(uint32 address = functionAddress; ; address += 4)\r\n\t{\r\n\t\t\/\/Probably going too far...\r\n\t\tif((address - functionAddress) > 0x10000)\r\n\t\t{\r\n\t\t\tprintf(\"MipsExecutor: Warning. Found no JR after a big distance.\\r\\n\");\r\n\t\t\tendAddress = address;\r\n\t\t\tpartitionPoints.insert(endAddress);\r\n\t\t\tbreak;\r\n\t\t}\r\n\t\tuint32 opcode = m_context.m_pMemoryMap->GetInstruction(address);\r\n\t\tif(opcode == 0x03E00008)\r\n\t\t{\r\n\t\t\t\/\/+4 for delay slot\r\n\t\t\tendAddress = address + 4;\r\n\t\t\tpartitionPoints.insert(endAddress + 4);\r\n\t\t\tbreak;\r\n\t\t}\r\n\t}\r\n\r\n\t\/\/Find partition points within the function\r\n\tfor(uint32 address = functionAddress; address <= endAddress; address += 4)\r\n\t{\r\n\t\tuint32 opcode = m_context.m_pMemoryMap->GetInstruction(address);\r\n\t\tMIPS_BRANCH_TYPE branchType = m_context.m_pArch->IsInstructionBranch(&m_context, address, opcode);\r\n\t\tif(branchType == MIPS_BRANCH_NORMAL)\r\n\t\t{\r\n\t\t\tpartitionPoints.insert(address + 8);\r\n\t\t\tuint32 target = m_context.m_pArch->GetInstructionEffectiveAddress(&m_context, address, opcode);\r\n\t\t\tif(target > functionAddress && target < endAddress)\r\n\t\t\t{\r\n\t\t\t\tpartitionPoints.insert(target);\r\n\t\t\t}\r\n\t\t}\r\n\t\telse if(branchType == MIPS_BRANCH_NODELAY)\r\n\t\t{\r\n\t\t\tpartitionPoints.insert(address + 4);\r\n\t\t}\r\n\t\t\/\/Check if there's a block already exising that this address\r\n\t\tif(address != endAddress)\r\n\t\t{\r\n\t\t\tCBasicBlock* possibleBlock = FindBlockStartingAt(address);\r\n\t\t\tif(possibleBlock)\r\n\t\t\t{\r\n\t\t\t\t\/\/assert(possibleBlock->GetEndAddress() <= endAddress);\r\n\t\t\t\t\/\/Add its beginning and end in the partition points\r\n\t\t\t\tpartitionPoints.insert(possibleBlock->GetBeginAddress());\r\n\t\t\t\tpartitionPoints.insert(possibleBlock->GetEndAddress() + 4);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\t\/\/Check if blocks are too big\r\n\t{\r\n\t\tuint32 currentPoint = -1;\r\n\t\tfor(PartitionPointSet::const_iterator pointIterator(partitionPoints.begin());\r\n\t\t\tpointIterator != partitionPoints.end(); pointIterator++)\r\n\t\t{\r\n\t\t\tif(currentPoint != -1)\r\n\t\t\t{\r\n\t\t\t\tuint32 startPos = currentPoint;\r\n\t\t\t\tuint32 endPos = *pointIterator;\r\n\t\t\t\tuint32 distance = (endPos - startPos);\r\n\t\t\t\tif(distance > 0x400)\r\n\t\t\t\t{\r\n\t\t\t\t\tuint32 middlePos = ((endPos + startPos) \/ 2) & ~0x03;\r\n\t\t\t\t\tpointIterator = partitionPoints.insert(middlePos).first;\r\n\t\t\t\t\tpointIterator--;\r\n\t\t\t\t\tcontinue;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tcurrentPoint = *pointIterator;\r\n\t\t}\r\n\t}\r\n\r\n\t\/\/Create blocks\r\n\t{\r\n\t\tuint32 currentPoint = -1;\r\n\t\tfor(PartitionPointSet::const_iterator pointIterator(partitionPoints.begin());\r\n\t\t\tpointIterator != partitionPoints.end(); pointIterator++)\r\n\t\t{\r\n\t\t\tif(currentPoint != -1)\r\n\t\t\t{\r\n\t\t\t\tCreateBlock(currentPoint, *pointIterator - 4);\r\n\t\t\t}\r\n\t\t\tcurrentPoint = *pointIterator;\r\n\t\t}\r\n\t}\r\n}\r\n<commit_msg>Revert \"Fixed blocks still being linked to old blocks after ClearActiveBlocks is called.\"<commit_after>#include \"MipsExecutor.h\"\r\n\r\nCMipsExecutor::CMipsExecutor(CMIPS& context, uint32 maxAddress)\r\n: m_context(context)\r\n, m_subTableCount(0)\r\n#ifdef DEBUGGER_INCLUDED\r\n, m_breakpointsDisabledOnce(false)\r\n#endif\r\n{\r\n\tif(maxAddress < 0x10000)\r\n\t{\r\n\t\tmaxAddress = 0x10000;\r\n\t}\r\n\tassert((maxAddress & 0xFFFF) == 0);\r\n\tif(maxAddress == 0)\r\n\t{\r\n\t\tm_subTableCount = 0x10000;\r\n\t}\r\n\telse\r\n\t{\r\n\t\tm_subTableCount = maxAddress \/ 0x10000;\r\n\t}\r\n\tm_blockTable = new CBasicBlock**[m_subTableCount];\r\n\tmemset(m_blockTable, 0, sizeof(CBasicBlock**) * m_subTableCount);\r\n}\r\n\r\nCMipsExecutor::~CMipsExecutor()\r\n{\r\n\tfor(unsigned int i = 0; i < m_subTableCount; i++)\r\n\t{\r\n\t\tCBasicBlock** subTable = m_blockTable[i];\r\n\t\tif(subTable != NULL)\r\n\t\t{\r\n\t\t\tdelete [] subTable;\r\n\t\t}\r\n\t}\r\n\tdelete [] m_blockTable;\r\n}\r\n\r\nvoid CMipsExecutor::Reset()\r\n{\r\n\tClearActiveBlocks();\r\n}\r\n\r\nvoid CMipsExecutor::ClearActiveBlocks()\r\n{\r\n\tfor(unsigned int i = 0; i < m_subTableCount; i++)\r\n\t{\r\n\t\tCBasicBlock** subTable = m_blockTable[i];\r\n\t\tif(subTable != NULL)\r\n\t\t{\r\n\t\t\tdelete [] subTable;\r\n\t\t\tm_blockTable[i] = NULL;\r\n\t\t}\r\n\t}\r\n\t\r\n\tm_blocks.clear();\r\n}\r\n\r\nvoid CMipsExecutor::ClearActiveBlocksInRange(uint32 start, uint32 end)\r\n{\r\n\tuint32 hiStart = start >> 16;\r\n\tuint32 hiEnd = end >> 16;\r\n\r\n\tstd::set<CBasicBlock*> blocksToDelete;\r\n\r\n\tfor(uint32 hi = hiStart; hi <= hiEnd; hi++)\r\n\t{\r\n\t\tCBasicBlock** table = m_blockTable[hi];\r\n\t\tif(table == nullptr) continue;\r\n\r\n\t\tfor(uint32 lo = 0; lo < 0x10000; lo += 4)\r\n\t\t{\r\n\t\t\tuint32 tableAddress = (hi << 16) | lo;\r\n\t\t\tif(tableAddress < start) continue;\r\n\t\t\tif(tableAddress >= end) continue;\r\n\t\t\tCBasicBlock* block = table[lo \/ 4];\r\n\t\t\tif(block == nullptr) continue;\r\n\t\t\ttable[lo \/ 4] = nullptr;\r\n\t\t\tblocksToDelete.insert(block);\r\n\t\t}\r\n\t}\r\n\r\n\tif(!blocksToDelete.empty())\r\n\t{\r\n\t\t\/\/TODO: Actually delete the blocks, because remove_if only rearranges items leaving us a new end iterator\r\n\t\tm_blocks.remove_if([&] (const BasicBlockPtr& block) { return blocksToDelete.find(block.get()) != std::end(blocksToDelete); });\r\n\t}\r\n}\r\n\r\nint CMipsExecutor::Execute(int cycles)\r\n{\r\n\tCBasicBlock* block(nullptr);\r\n\twhile(cycles > 0)\r\n\t{\r\n\t\tuint32 address = m_context.m_pAddrTranslator(&m_context, m_context.m_State.nPC);\r\n\t\tif(!block || address != block->GetBeginAddress())\r\n\t\t{\r\n\t\t\tblock = FindBlockStartingAt(address);\r\n\t\t\tif(block == NULL)\r\n\t\t\t{\r\n\t\t\t\t\/\/We need to partition the space and compile the blocks\r\n\t\t\t\tPartitionFunction(address);\r\n\t\t\t\tblock = FindBlockStartingAt(address);\r\n\t\t\t\tif(block == NULL)\r\n\t\t\t\t{\r\n\t\t\t\t\tthrow std::runtime_error(\"Couldn't create block starting at address.\");\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tif(!block->IsCompiled())\r\n\t\t\t{\r\n\t\t\t\tblock->Compile();\r\n\t\t\t}\r\n\t\t}\r\n\t\telse if(block != NULL)\r\n\t\t{\r\n\t\t\tblock->SetSelfLoopCount(block->GetSelfLoopCount() + 1);\r\n\t\t}\r\n\r\n#ifdef DEBUGGER_INCLUDED\r\n\t\tif(!m_breakpointsDisabledOnce && MustBreak()) break;\r\n\t\tm_breakpointsDisabledOnce = false;\r\n#endif\r\n\t\tcycles -= block->Execute();\r\n\t\tif(m_context.m_State.nHasException) break;\r\n\t}\r\n\treturn cycles;\r\n}\r\n\r\n#ifdef DEBUGGER_INCLUDED\r\n\r\nbool CMipsExecutor::MustBreak() const\r\n{\r\n\tuint32 currentPc = m_context.m_pAddrTranslator(&m_context, m_context.m_State.nPC);\r\n\tCBasicBlock* block = FindBlockAt(currentPc);\r\n\tfor(auto breakPointIterator(m_context.m_breakpoints.begin());\r\n\t\tbreakPointIterator != m_context.m_breakpoints.end(); breakPointIterator++)\r\n\t{\r\n\t\tuint32 breakPointAddress = *breakPointIterator;\r\n\t\tif(currentPc == breakPointAddress) return true;\r\n\t\tif(block != NULL)\r\n\t\t{\r\n\t\t\tif(breakPointAddress >= block->GetBeginAddress() && breakPointAddress <= block->GetEndAddress()) return true;\r\n\t\t}\r\n\t}\r\n\treturn false;\r\n}\r\n\r\nvoid CMipsExecutor::DisableBreakpointsOnce()\r\n{\r\n\tm_breakpointsDisabledOnce = true;\r\n}\r\n\r\n#endif\r\n\r\nCBasicBlock* CMipsExecutor::FindBlockAt(uint32 address) const\r\n{\r\n\tuint32 hiAddress = address >> 16;\r\n\tuint32 loAddress = address & 0xFFFF;\r\n\tassert(hiAddress < m_subTableCount);\r\n\tCBasicBlock**& subTable = m_blockTable[hiAddress];\r\n\tif(subTable == NULL) return NULL;\r\n\tCBasicBlock* result = subTable[loAddress \/ 4];\r\n\treturn result;\r\n}\r\n\r\nCBasicBlock* CMipsExecutor::FindBlockStartingAt(uint32 address) const\r\n{\r\n\tuint32 hiAddress = address >> 16;\r\n\tuint32 loAddress = address & 0xFFFF;\r\n\tassert(hiAddress < m_subTableCount);\r\n\tCBasicBlock**& subTable = m_blockTable[hiAddress];\r\n\tif(subTable == NULL) return NULL;\r\n\tCBasicBlock* result = subTable[loAddress \/ 4];\r\n\tif((address != 0) && (FindBlockAt(address - 4) == result))\r\n\t{\r\n\t\treturn NULL;\r\n\t}\r\n\treturn result;\r\n}\r\n\r\nvoid CMipsExecutor::CreateBlock(uint32 start, uint32 end)\r\n{\r\n\t{\r\n\t\tCBasicBlock* block = FindBlockAt(start);\r\n\t\tif(block)\r\n\t\t{\r\n\t\t\t\/\/If the block starts and ends at the same place, block already exists and doesn't need\r\n\t\t\t\/\/to be re-created\r\n\t\t\tuint32 otherBegin = block->GetBeginAddress();\r\n\t\t\tuint32 otherEnd = block->GetEndAddress();\r\n\t\t\tif((otherBegin == start) && (otherEnd == end))\r\n\t\t\t{\r\n\t\t\t\treturn;\r\n\t\t\t}\r\n\t\t\tif(otherEnd == end)\r\n\t\t\t{\r\n\t\t\t\t\/\/Repartition the existing block if end of both blocks are the same\r\n\t\t\t\tDeleteBlock(block);\r\n\t\t\t\tCreateBlock(otherBegin, start - 4);\r\n\t\t\t\tassert(FindBlockAt(start) == NULL);\r\n\t\t\t}\r\n\t\t\telse if(otherBegin == start)\r\n\t\t\t{\r\n\t\t\t\tDeleteBlock(block);\r\n\t\t\t\tCreateBlock(end + 4, otherEnd);\r\n\t\t\t\tassert(FindBlockAt(end) == NULL);\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\t\/\/Delete the currently existing block otherwise\r\n\t\t\t\tprintf(\"MipsExecutor: Warning. Deleting block at %0.8X.\\r\\n\", block->GetEndAddress());\r\n\t\t\t\tDeleteBlock(block);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tassert(FindBlockAt(end) == NULL);\r\n\t{\r\n\t\tBasicBlockPtr block = BlockFactory(m_context, start, end);\r\n\t\tfor(uint32 address = block->GetBeginAddress(); address <= block->GetEndAddress(); address += 4)\r\n\t\t{\r\n\t\t\tuint32 hiAddress = address >> 16;\r\n\t\t\tuint32 loAddress = address & 0xFFFF;\r\n\t\t\tassert(hiAddress < m_subTableCount);\r\n\t\t\tCBasicBlock**& subTable = m_blockTable[hiAddress];\r\n\t\t\tif(subTable == NULL)\r\n\t\t\t{\r\n\t\t\t\tconst uint32 subTableSize = 0x10000 \/ 4;\r\n\t\t\t\tsubTable = new CBasicBlock*[subTableSize];\r\n\t\t\t\tmemset(subTable, 0, sizeof(CBasicBlock*) * subTableSize);\r\n\t\t\t}\r\n\t\t\tassert(subTable[loAddress \/ 4] == NULL);\r\n\t\t\tsubTable[loAddress \/ 4] = block.get();\r\n\t\t}\r\n\t\tm_blocks.push_back(std::move(block));\r\n\t}\r\n}\r\n\r\nvoid CMipsExecutor::DeleteBlock(CBasicBlock* block)\r\n{\r\n\tfor(uint32 address = block->GetBeginAddress(); address <= block->GetEndAddress(); address += 4)\r\n\t{\r\n\t\tuint32 hiAddress = address >> 16;\r\n\t\tuint32 loAddress = address & 0xFFFF;\r\n\t\tassert(hiAddress < m_subTableCount);\r\n\t\tCBasicBlock**& subTable = m_blockTable[hiAddress];\r\n\t\tassert(subTable != NULL);\r\n\t\tassert(subTable[loAddress \/ 4] != NULL);\r\n\t\tsubTable[loAddress \/ 4] = NULL;\r\n\t}\r\n\r\n\t\/\/Remove block from our lists\r\n\tauto blockIterator = std::find_if(std::begin(m_blocks), std::end(m_blocks), [&] (const BasicBlockPtr& blockPtr) { return blockPtr.get() == block; });\r\n\tassert(blockIterator != std::end(m_blocks));\r\n\tm_blocks.erase(blockIterator);\r\n}\r\n\r\nCMipsExecutor::BasicBlockPtr CMipsExecutor::BlockFactory(CMIPS& context, uint32 start, uint32 end)\r\n{\r\n\treturn std::make_shared<CBasicBlock>(context, start, end);\r\n}\r\n\r\nvoid CMipsExecutor::PartitionFunction(uint32 functionAddress)\r\n{\r\n\ttypedef std::set<uint32> PartitionPointSet;\r\n\tuint32 endAddress = 0;\r\n\tPartitionPointSet partitionPoints;\r\n\r\n\t\/\/Insert begin point\r\n\tpartitionPoints.insert(functionAddress);\r\n\r\n\t\/\/Find the end\r\n\tfor(uint32 address = functionAddress; ; address += 4)\r\n\t{\r\n\t\t\/\/Probably going too far...\r\n\t\tif((address - functionAddress) > 0x10000)\r\n\t\t{\r\n\t\t\tprintf(\"MipsExecutor: Warning. Found no JR after a big distance.\\r\\n\");\r\n\t\t\tendAddress = address;\r\n\t\t\tpartitionPoints.insert(endAddress);\r\n\t\t\tbreak;\r\n\t\t}\r\n\t\tuint32 opcode = m_context.m_pMemoryMap->GetInstruction(address);\r\n\t\tif(opcode == 0x03E00008)\r\n\t\t{\r\n\t\t\t\/\/+4 for delay slot\r\n\t\t\tendAddress = address + 4;\r\n\t\t\tpartitionPoints.insert(endAddress + 4);\r\n\t\t\tbreak;\r\n\t\t}\r\n\t}\r\n\r\n\t\/\/Find partition points within the function\r\n\tfor(uint32 address = functionAddress; address <= endAddress; address += 4)\r\n\t{\r\n\t\tuint32 opcode = m_context.m_pMemoryMap->GetInstruction(address);\r\n\t\tMIPS_BRANCH_TYPE branchType = m_context.m_pArch->IsInstructionBranch(&m_context, address, opcode);\r\n\t\tif(branchType == MIPS_BRANCH_NORMAL)\r\n\t\t{\r\n\t\t\tpartitionPoints.insert(address + 8);\r\n\t\t\tuint32 target = m_context.m_pArch->GetInstructionEffectiveAddress(&m_context, address, opcode);\r\n\t\t\tif(target > functionAddress && target < endAddress)\r\n\t\t\t{\r\n\t\t\t\tpartitionPoints.insert(target);\r\n\t\t\t}\r\n\t\t}\r\n\t\telse if(branchType == MIPS_BRANCH_NODELAY)\r\n\t\t{\r\n\t\t\tpartitionPoints.insert(address + 4);\r\n\t\t}\r\n\t\t\/\/Check if there's a block already exising that this address\r\n\t\tif(address != endAddress)\r\n\t\t{\r\n\t\t\tCBasicBlock* possibleBlock = FindBlockStartingAt(address);\r\n\t\t\tif(possibleBlock)\r\n\t\t\t{\r\n\t\t\t\t\/\/assert(possibleBlock->GetEndAddress() <= endAddress);\r\n\t\t\t\t\/\/Add its beginning and end in the partition points\r\n\t\t\t\tpartitionPoints.insert(possibleBlock->GetBeginAddress());\r\n\t\t\t\tpartitionPoints.insert(possibleBlock->GetEndAddress() + 4);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\t\/\/Check if blocks are too big\r\n\t{\r\n\t\tuint32 currentPoint = -1;\r\n\t\tfor(PartitionPointSet::const_iterator pointIterator(partitionPoints.begin());\r\n\t\t\tpointIterator != partitionPoints.end(); pointIterator++)\r\n\t\t{\r\n\t\t\tif(currentPoint != -1)\r\n\t\t\t{\r\n\t\t\t\tuint32 startPos = currentPoint;\r\n\t\t\t\tuint32 endPos = *pointIterator;\r\n\t\t\t\tuint32 distance = (endPos - startPos);\r\n\t\t\t\tif(distance > 0x400)\r\n\t\t\t\t{\r\n\t\t\t\t\tuint32 middlePos = ((endPos + startPos) \/ 2) & ~0x03;\r\n\t\t\t\t\tpointIterator = partitionPoints.insert(middlePos).first;\r\n\t\t\t\t\tpointIterator--;\r\n\t\t\t\t\tcontinue;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tcurrentPoint = *pointIterator;\r\n\t\t}\r\n\t}\r\n\r\n\t\/\/Create blocks\r\n\t{\r\n\t\tuint32 currentPoint = -1;\r\n\t\tfor(PartitionPointSet::const_iterator pointIterator(partitionPoints.begin());\r\n\t\t\tpointIterator != partitionPoints.end(); pointIterator++)\r\n\t\t{\r\n\t\t\tif(currentPoint != -1)\r\n\t\t\t{\r\n\t\t\t\tCreateBlock(currentPoint, *pointIterator - 4);\r\n\t\t\t}\r\n\t\t\tcurrentPoint = *pointIterator;\r\n\t\t}\r\n\t}\r\n}\r\n<|endoftext|>"} {"text":"<commit_before>\/\/ Begin CVS Header\n\/\/ $Source: \/Volumes\/Home\/Users\/shoops\/cvs\/copasi_dev\/copasi\/elementaryFluxModes\/CSSAMethod.cpp,v $\n\/\/ $Revision: 1.7 $\n\/\/ $Name: $\n\/\/ $Author: shoops $\n\/\/ $Date: 2009\/08\/17 19:56:49 $\n\/\/ End CVS Header\n\n\/\/ Copyright (C) 2008 by Pedro Mendes, Virginia Tech Intellectual\n\/\/ Properties, Inc. and EML Research, gGmbH, University of Heidelberg,\n\/\/ and The University of Manchester.\n\/\/ All rights reserved.\n\n\/**\n * CSSAMethod class.\n * Methods to conduct Stoichiometric Stability Analysis.-\n *\/\n\n#include \"copasi.h\"\n\n#include \"blaswrap.h\"\n#include \"clapackwrap.h\"\n\n#include \"elementaryFluxModes\/CSSAMethod.h\"\n#include \"elementaryFluxModes\/CEFMTask.h\"\n#include \"utilities\/CCopasiProblem.h\"\n#include \"elementaryFluxModes\/CEFMMethod.h\"\n#include \"elementaryFluxModes\/CFluxMode.h\"\n\n#include \"model\/CModel.h\"\n#include \"model\/CState.h\"\n#include \"utilities\/CProcessReport.h\"\n\n\/**\n * Copy constructor.\n * @param \"const CSSAMethod &\" src\n *\/\nCSSAMethod::CSSAMethod(const CSSAMethod & src,\n const CCopasiContainer * pParent):\n CEFMAlgorithm(src, pParent)\n{}\n\nCSSAMethod::CSSAMethod(const CCopasiContainer * pParent) :\n CEFMAlgorithm(CCopasiMethod::stoichiometricStabilityAnalysis, pParent)\n{}\n\n\/\/ taken from CEFMAlgorithm, modified to make reactions reversible, implicitely,\n\/\/ i.e. without changing the model itself.\nbool CSSAMethod::initialize()\n{\n CEFMTask * pTask = dynamic_cast< CEFMTask *>(getObjectParent());\n\n if (pTask == NULL) return false;\n\n mpModel = pTask->getProblem()->getModel();\n\n if (mpModel == NULL) return false;\n\n mFluxModes.clear();\n mReactions.cleanup();\n\n \/* ModelStoi is the transpose of the models stoichiometry matrix *\/\n const CTransposeView< CMatrix< C_FLOAT64 > > ModelStoi(mpModel->getRedStoi());\n\n unsigned C_INT32 row, numRows = ModelStoi.numRows();\n unsigned C_INT32 col, numCols = ModelStoi.numCols();\n\n \/* Get the reactions from the model *\/\n \/* Note: We have as many reactions as we have rows in ModelStoi *\/\n CCopasiVectorNS < CReaction > & Reaction = mpModel->getReactions();\n\n \/* Reversible reaction counter *\/\n mReversible = 0;\n\n for (row = 0; row < numRows; row++)\n {\n if (Reaction[row]->isReversible())\n mReversible++;\n }\n\n unsigned C_INT32 numOrigRows = numRows;\n numRows += mReversible;\n mNumReactions = numRows;\n\n mReversible = 0;\n \/* Size the stoichiometry matrix passed to the algorithm *\/\n mStoi.resize(numRows);\n std::vector< std::vector< C_FLOAT64 > >::iterator it = mStoi.begin();\n std::vector< std::vector< C_FLOAT64 > >::iterator end = mStoi.end();\n\n for (; it != end; ++it)\n it->resize(numCols);\n\n \/* Vector to keep track of the rearrangements necessary to put the *\/\n \/* reversible reactions to the top of stoichiometry matrix *\/\n mReorderedReactions.resize(numRows);\n mIsBackwardReaction.resize(numRows);\n\n unsigned C_INT32 Insert;\n unsigned C_INT32 InsertReversible = 0;\n unsigned C_INT32 InsertIrreversible = numRows - 1;\n\n \/* Build the transpose of the stoichiometry matrix, *\/\n\n \/* sort reversible reactions to the top, count them *\/\n\n \/* and keep track of the rearrangement *\/\n\n \/\/for (row = 0; row < numOrigRows; row++)\n for (row = 0; row < numOrigRows; row++)\n {\n if (Reaction[row]->isReversible())\n {\n Insert = InsertReversible++;\n mIsBackwardReaction[Insert] = true;\n\n mReversible++;\n }\n else\n {\n Insert = InsertIrreversible--;\n mIsBackwardReaction[Insert] = false;\n }\n\n mReorderedReactions[Insert] = Reaction[row];\n\n for (col = 0; col < numCols; col++)\n {\n mStoi[Insert][col] = ModelStoi(row, col);\n\n if (Reaction[row]->isReversible())\n mStoi[InsertReversible - 1][col] = - ModelStoi(row, col);\n }\n }\n\n#ifdef COPASI_DEBUG\n std::cout << \"mStoi:\\n\";\n\n for (int i = 0; i < numRows; ++i)\n {\n for (int j = 0; j < numCols; ++j)\n {\n std::cout << mStoi[i][j];\n std::cout << \" \";\n }\n\n std::cout << std::endl;\n }\n\n#endif\n\n mStep = 0;\n mMaxStep = numCols;\n\n if (mpCallBack)\n mhSteps =\n mpCallBack->addItem(\"Current Step\",\n CCopasiParameter::UINT,\n & mStep,\n & mMaxStep);\n\n return true;\n}\n\nbool CSSAMethod::process(CProcessReport *)\n{\n return false;\n}\n\nbool\nCSSAMethod::calculate()\n{\n if (!initialize()) return false;\n\n if (!mpModel) return false;\n\n \/\/initialize matrices for calculation;\n \/\/ if (mpModel->compileIfNecessary(NULL))\n \/\/ {\n buildStoichiometry();\n buildKineticMatrix();\n buildExtremeCurrents();\n \/\/}\n \/\/ else\n \/\/ return false;\n\n if (!testForMixingStability())\n return false;\n\n return true;\n}\n\nTriLogic\nCSSAMethod::isMixingStable(int indexEC)\n{return mIsMixingStable[indexEC];}\n\nbool\nCSSAMethod::isReactionReversed(int index) const\n{return mIsBackwardReaction[index];}\n\nbool\nCSSAMethod::testForMixingStability()\n{\n decomposeJacobian();\n\n C_INT32 numECs = mExtremeCurrents.size();\n\n C_INT32 ijmax = mTransformedSubJacobians[0].numRows();\n\n mIsMixingStable.clear();\n\n C_FLOAT64 outarray[ijmax*ijmax];\n memset(outarray, 0, ijmax*ijmax*sizeof(C_FLOAT64));\n\n for (int ecIndex = 0; ecIndex < numECs; ++ecIndex)\n {\n C_FLOAT64 *inarray = mTransformedSubJacobians[ecIndex].array();\n\n \/\/ add matrix and its extremeCurrent - upper triangle only\n for (int i = 0; i < ijmax; ++i)\n for (int j = i; j < ijmax; ++j)\n outarray[i + j*ijmax] = inarray[i + j * ijmax] + inarray[j + i * ijmax];\n\n \/\/ get the eigenvalues AND eigenvectors:\n \/\/ input to dsyev_()\n char jobz = 'V';\n char uplo = 'U';\n C_INT32 n = ijmax;\n C_FLOAT64 *A = outarray;\n C_INT32 lda = ijmax;\n C_INT32 lwork = 64 * ijmax;\n \/\/ dsyev_() output\n C_FLOAT64 eigenvalues[ijmax];\n C_FLOAT64 work[lwork];\n C_INT32 info;\n\n dsyev_(&jobz, &uplo, &n, A, &lda, eigenvalues, work, &lwork, &info);\n\n if (info)\n return false; \/\/ maybe raise an exception here, to discriminate from the sane case\n\n CVector<C_FLOAT64> EC = mExtremeCurrents[ecIndex];\n\n \/\/ set the state to 'stable' (1 - stable; 0 - unknown; -1 - not mixing stable)\n TriLogic state = TriTrue;\n\n int partMetabs[ijmax];\n memset(&partMetabs, 0, ijmax*sizeof(int));\n\n for (int j = 0; j < EC.size(); ++j)\n {\n if (EC[j])\n {\n \/\/ if one reaction's kinetic function is not Mass Action Law,\n \/\/ this method is not valid and we can say nothing definite\n \/\/ about the stability of this EC.\n std::string type = mReorderedReactions[j]->getFunction()->getObjectName();\n \/\/ std::cout << \"Reaction type: \" << type << std::endl;\n\n if (type.find(\"Mass action\") == std::string::npos &&\n type.find(\"Constant flux\") == std::string::npos)\n {\n state = TriUnspecified;\n break;\n }\n\n for (int i = 0; i < ijmax; ++i)\n {\n if (mStoi[j][i])\n {\n partMetabs[i] = 1;\n break;\n }\n }\n }\n }\n\n if (state == TriTrue)\n {\n \/\/ eigenvalues are sorted in rising order, and if the last ev is\n \/\/ not positive, we have still to look after zero evs.\n if (eigenvalues[ijmax - 1] > 0)\n state = TriFalse;\n else\n {\n int zeroes = 0;\n\n for (int i = 0; i < ijmax && state == 1; ++i)\n {\n \/\/ only count zero eigenvals if the eigenvector contains a reaction\n \/\/ that is participating in this extreme current.\n if (eigenvalues[i] == 0)\n {\n for (int j = 0; j < ijmax; ++ j)\n if (partMetabs[j] && outarray[i*ijmax + j])\n if (++zeroes)\n break;\n\n if (zeroes == 2)\n state = TriFalse;\n }\n }\n }\n }\n\n#ifdef COPASI_DEBUG\n std::cout << std::endl << std::endl;\n std::cout << \"EC\" << std::endl << \" (\";\n\n for (int j = 0; j < mExtremeCurrents[0].size(); ++j)\n std::cout << mExtremeCurrents[ecIndex][j] << \" \";\n\n std::cout << \")\" << std::endl << std::endl;\n\n std::cout << \"sub-jacobian #\" << ecIndex + 1 << \":\\n\" << mTransformedSubJacobians[ecIndex] << \"\\n\";\n\n std::cout << \"\\nEigenval\\tEigenvector\\tParticipating\" << std::endl;\n\n for (int i = 0; i < ijmax; ++i)\n {\n std::cout << eigenvalues[i] << std::endl;\n\n for (int j = 0; j < ijmax; ++j)\n std::cout << \" \\t\\t\\t\" << outarray[i*ijmax + j] << \"\\t\\t\" << partMetabs[j] << std::endl;\n\n std::cout << std::endl;\n }\n\n if (state == TriUnspecified)\n std::cout << \"unknown\";\n else if (state == TriFalse)\n std::cout << \"not mixing stable\";\n else\n std::cout << \"mixing stable\";\n\n std::cout << std::endl << std::endl;\n#endif \/\/ COPASI_DEBUG\n mIsMixingStable.push_back(state);\n }\n\n#ifdef COPASI_DEBUG\n std::cout << std::endl;\n std::cout << \"There is\/are \" << mIsMixingStable.size()\n << \" extreme current(s) not mixing stable!\" << std::endl;\n#endif \/\/COPASI_DEBUG\n\n return true;\n}\n\nbool\nCSSAMethod::decomposeJacobian()\n{\n mTransformedSubJacobians.clear();\n\n \/\/ parameters for the double matrix multiplication with dgemm_\n char cN = 'N'; \/\/ don't transpose matrices\n C_INT m = mStoichiometry.numRows(); \/\/ the leading dimension of the Stoi.M. and of the resulting M.\n C_INT n = mStoichiometry.numCols(); \/\/ the dimensions of matrix diagE, also used as 'k'.\n\n C_FLOAT64 alpha = 1.;\n C_FLOAT64 beta = 0.;\n\n CMatrix< C_FLOAT64 > product;\n product.resize(m, m);\n\n std::vector< CVector<C_FLOAT64> >::iterator iter;\n\n for (iter = mExtremeCurrents.begin(); iter != mExtremeCurrents.end(); ++iter)\n {\n CMatrix<C_FLOAT64> diagE = diag(*iter);\n\n \/\/ compute N*Ei*kappa^T:\n \/\/ As the representation of the matrices in their arrays is in\n \/\/ transposed (mathematical) order, we compute kappa*Ei*N^T,\n \/\/ which corresponds to\n \/\/ (mTransposedKineticMatrix*diagE)*mStoichiometry\n C_FLOAT64 dummy[m*n];\n dgemm_(&cN, &cN,\n &m, &n, &n, &alpha,\n mTransposedKineticMatrix.array(), &m ,\n diagE.array(), &n,\n &beta, dummy, &m);\n dgemm_(&cN, &cN,\n &m, &m, &n, &alpha,\n dummy, &m,\n mStoichiometry.array(), &n,\n &beta, product.array(), &m);\n\n mTransformedSubJacobians.push_back(product);\n }\n\n return true;\n}\n\nbool\nCSSAMethod::buildStoichiometry()\n{\n if (!mpModel) return false;\n\n \/\/rebuild the stoichiometric matrix with reversible reactions divided into two.\n\n \/\/ build the _transposed_ of stoichiometry, with expanded reversible reactions\n int numRows = mStoi[0].size();\n int numCols = mStoi.size();\n\n mStoichiometry.resize(numRows, numCols);\n memset(mStoichiometry.array(), 0, numRows*numCols*sizeof(C_FLOAT64));\n\n for (int i = 0; i < numRows; ++i)\n for (int j = 0; j < numCols; ++j)\n mStoichiometry(i, j) = mStoi[j][i];\n\n#ifdef COPASI_DEBUG\n std::cout << std::endl << std::endl << \"new stoichiometry:\" << std::endl << mStoichiometry << std::endl;\n#endif\n\n return true;\n}\n\nbool\nCSSAMethod::buildKineticMatrix()\n{\n if (!mpModel) return false;\n\n C_FLOAT64 num_metabolites = mpModel->getNumIndependentReactionMetabs();\n\n C_FLOAT64 num_reactions = mNumReactions;\n\n mTransposedKineticMatrix.resize((C_INT64)num_reactions, (C_INT64)num_metabolites);\n memset(mTransposedKineticMatrix.array(), 0, (int)(num_metabolites*num_reactions*sizeof(C_FLOAT64)));\n\n CCopasiVector< CMetab > & metabOrder = mpModel->getMetabolitesX();\n\n for (int ireac = 0; ireac < mIsBackwardReaction.size(); ++ireac)\n {\n CCopasiVector< CChemEqElement > substrates;\n\n if (mIsBackwardReaction[ireac])\n substrates = mReorderedReactions[ireac]->getChemEq().getProducts();\n else\n substrates = mReorderedReactions[ireac]->getChemEq().getSubstrates();\n\n for (int jsubst = 0; jsubst < substrates.size(); ++jsubst)\n {\n CCopasiVector< CMetab >::iterator found = find(metabOrder.begin(),\n metabOrder.end(),\n substrates[jsubst]->getMetabolite());\n\n if ((*found)->isDependent()) continue;\n\n int kmetab = std::distance(metabOrder.begin(), found);\n mTransposedKineticMatrix[ireac][kmetab] = substrates[jsubst]->getMultiplicity();\n }\n }\n\n#ifdef COPASI_DEBUG\n std::cout << \"transposed kinetic matrix: \" << std::endl\n << mTransposedKineticMatrix << std::endl\n << std::endl;\n#endif \/\/ COPASI_DEBUG\n\n return true;\n}\n\nbool\nCSSAMethod::buildExtremeCurrents()\n{\n mExtremeCurrents.clear();\n\n calculateFluxModes();\n\n std::vector< CFluxMode > fluxmodes = getFluxModes();\n\n CVector< C_FLOAT64 > extremecurrent;\n extremecurrent.resize(mNumReactions);\n\n std::vector< CFluxMode >::iterator iter;\n\n for (iter = fluxmodes.begin(); iter != fluxmodes.end(); ++iter)\n {\n memset(extremecurrent.array(), 0, extremecurrent.size()*sizeof(C_FLOAT64));\n unsigned C_INT32 i;\n\n for (i = 0; i < iter->size(); ++i)\n {\n extremecurrent[iter->getReactionIndex(i)] = iter->getMultiplier(i);\n }\n\n#ifdef COPASI_DEBUG\n std::cout << \"extreme current #\" << distance(fluxmodes.begin(), iter) << std::endl\n << \" \" << extremecurrent << std::endl << std::endl;\n mExtremeCurrents.push_back(extremecurrent);\n#endif\n }\n\n return true;\n}\n<commit_msg>Removed debugging output.<commit_after>\/\/ Begin CVS Header\n\/\/ $Source: \/Volumes\/Home\/Users\/shoops\/cvs\/copasi_dev\/copasi\/elementaryFluxModes\/CSSAMethod.cpp,v $\n\/\/ $Revision: 1.8 $\n\/\/ $Name: $\n\/\/ $Author: shoops $\n\/\/ $Date: 2009\/09\/22 14:58:11 $\n\/\/ End CVS Header\n\n\/\/ Copyright (C) 2008 by Pedro Mendes, Virginia Tech Intellectual\n\/\/ Properties, Inc. and EML Research, gGmbH, University of Heidelberg,\n\/\/ and The University of Manchester.\n\/\/ All rights reserved.\n\n\/**\n * CSSAMethod class.\n * Methods to conduct Stoichiometric Stability Analysis.-\n *\/\n\n#include \"copasi.h\"\n\n#include \"blaswrap.h\"\n#include \"clapackwrap.h\"\n\n#include \"elementaryFluxModes\/CSSAMethod.h\"\n#include \"elementaryFluxModes\/CEFMTask.h\"\n#include \"utilities\/CCopasiProblem.h\"\n#include \"elementaryFluxModes\/CEFMMethod.h\"\n#include \"elementaryFluxModes\/CFluxMode.h\"\n\n#include \"model\/CModel.h\"\n#include \"model\/CState.h\"\n#include \"utilities\/CProcessReport.h\"\n\n\/**\n * Copy constructor.\n * @param \"const CSSAMethod &\" src\n *\/\nCSSAMethod::CSSAMethod(const CSSAMethod & src,\n const CCopasiContainer * pParent):\n CEFMAlgorithm(src, pParent)\n{}\n\nCSSAMethod::CSSAMethod(const CCopasiContainer * pParent) :\n CEFMAlgorithm(CCopasiMethod::stoichiometricStabilityAnalysis, pParent)\n{}\n\n\/\/ taken from CEFMAlgorithm, modified to make reactions reversible, implicitely,\n\/\/ i.e. without changing the model itself.\nbool CSSAMethod::initialize()\n{\n CEFMTask * pTask = dynamic_cast< CEFMTask *>(getObjectParent());\n\n if (pTask == NULL) return false;\n\n mpModel = pTask->getProblem()->getModel();\n\n if (mpModel == NULL) return false;\n\n mFluxModes.clear();\n mReactions.cleanup();\n\n \/* ModelStoi is the transpose of the models stoichiometry matrix *\/\n const CTransposeView< CMatrix< C_FLOAT64 > > ModelStoi(mpModel->getRedStoi());\n\n unsigned C_INT32 row, numRows = ModelStoi.numRows();\n unsigned C_INT32 col, numCols = ModelStoi.numCols();\n\n \/* Get the reactions from the model *\/\n \/* Note: We have as many reactions as we have rows in ModelStoi *\/\n CCopasiVectorNS < CReaction > & Reaction = mpModel->getReactions();\n\n \/* Reversible reaction counter *\/\n mReversible = 0;\n\n for (row = 0; row < numRows; row++)\n {\n if (Reaction[row]->isReversible())\n mReversible++;\n }\n\n unsigned C_INT32 numOrigRows = numRows;\n numRows += mReversible;\n mNumReactions = numRows;\n\n mReversible = 0;\n \/* Size the stoichiometry matrix passed to the algorithm *\/\n mStoi.resize(numRows);\n std::vector< std::vector< C_FLOAT64 > >::iterator it = mStoi.begin();\n std::vector< std::vector< C_FLOAT64 > >::iterator end = mStoi.end();\n\n for (; it != end; ++it)\n it->resize(numCols);\n\n \/* Vector to keep track of the rearrangements necessary to put the *\/\n \/* reversible reactions to the top of stoichiometry matrix *\/\n mReorderedReactions.resize(numRows);\n mIsBackwardReaction.resize(numRows);\n\n unsigned C_INT32 Insert;\n unsigned C_INT32 InsertReversible = 0;\n unsigned C_INT32 InsertIrreversible = numRows - 1;\n\n \/* Build the transpose of the stoichiometry matrix, *\/\n\n \/* sort reversible reactions to the top, count them *\/\n\n \/* and keep track of the rearrangement *\/\n\n \/\/for (row = 0; row < numOrigRows; row++)\n for (row = 0; row < numOrigRows; row++)\n {\n if (Reaction[row]->isReversible())\n {\n Insert = InsertReversible++;\n mIsBackwardReaction[Insert] = true;\n\n mReversible++;\n }\n else\n {\n Insert = InsertIrreversible--;\n mIsBackwardReaction[Insert] = false;\n }\n\n mReorderedReactions[Insert] = Reaction[row];\n\n for (col = 0; col < numCols; col++)\n {\n mStoi[Insert][col] = ModelStoi(row, col);\n\n if (Reaction[row]->isReversible())\n mStoi[InsertReversible - 1][col] = - ModelStoi(row, col);\n }\n }\n\n mStep = 0;\n mMaxStep = numCols;\n\n if (mpCallBack)\n mhSteps =\n mpCallBack->addItem(\"Current Step\",\n CCopasiParameter::UINT,\n & mStep,\n & mMaxStep);\n\n return true;\n}\n\nbool CSSAMethod::process(CProcessReport *)\n{\n return false;\n}\n\nbool\nCSSAMethod::calculate()\n{\n if (!initialize()) return false;\n\n if (!mpModel) return false;\n\n \/\/initialize matrices for calculation;\n \/\/ if (mpModel->compileIfNecessary(NULL))\n \/\/ {\n buildStoichiometry();\n buildKineticMatrix();\n buildExtremeCurrents();\n \/\/}\n \/\/ else\n \/\/ return false;\n\n if (!testForMixingStability())\n return false;\n\n return true;\n}\n\nTriLogic\nCSSAMethod::isMixingStable(int indexEC)\n{return mIsMixingStable[indexEC];}\n\nbool\nCSSAMethod::isReactionReversed(int index) const\n{return mIsBackwardReaction[index];}\n\nbool\nCSSAMethod::testForMixingStability()\n{\n decomposeJacobian();\n\n C_INT32 numECs = mExtremeCurrents.size();\n\n C_INT32 ijmax = mTransformedSubJacobians[0].numRows();\n\n mIsMixingStable.clear();\n\n C_FLOAT64 outarray[ijmax*ijmax];\n memset(outarray, 0, ijmax*ijmax*sizeof(C_FLOAT64));\n\n for (int ecIndex = 0; ecIndex < numECs; ++ecIndex)\n {\n C_FLOAT64 *inarray = mTransformedSubJacobians[ecIndex].array();\n\n \/\/ add matrix and its extremeCurrent - upper triangle only\n for (int i = 0; i < ijmax; ++i)\n for (int j = i; j < ijmax; ++j)\n outarray[i + j*ijmax] = inarray[i + j * ijmax] + inarray[j + i * ijmax];\n\n \/\/ get the eigenvalues AND eigenvectors:\n \/\/ input to dsyev_()\n char jobz = 'V';\n char uplo = 'U';\n C_INT32 n = ijmax;\n C_FLOAT64 *A = outarray;\n C_INT32 lda = ijmax;\n C_INT32 lwork = 64 * ijmax;\n \/\/ dsyev_() output\n C_FLOAT64 eigenvalues[ijmax];\n C_FLOAT64 work[lwork];\n C_INT32 info;\n\n dsyev_(&jobz, &uplo, &n, A, &lda, eigenvalues, work, &lwork, &info);\n\n if (info)\n return false; \/\/ maybe raise an exception here, to discriminate from the sane case\n\n CVector<C_FLOAT64> EC = mExtremeCurrents[ecIndex];\n\n \/\/ set the state to 'stable' (1 - stable; 0 - unknown; -1 - not mixing stable)\n TriLogic state = TriTrue;\n\n int partMetabs[ijmax];\n memset(&partMetabs, 0, ijmax*sizeof(int));\n\n for (int j = 0; j < EC.size(); ++j)\n {\n if (EC[j])\n {\n \/\/ if one reaction's kinetic function is not Mass Action Law,\n \/\/ this method is not valid and we can say nothing definite\n \/\/ about the stability of this EC.\n std::string type = mReorderedReactions[j]->getFunction()->getObjectName();\n\n if (type.find(\"Mass action\") == std::string::npos &&\n type.find(\"Constant flux\") == std::string::npos)\n {\n state = TriUnspecified;\n break;\n }\n\n for (int i = 0; i < ijmax; ++i)\n {\n if (mStoi[j][i])\n {\n partMetabs[i] = 1;\n break;\n }\n }\n }\n }\n\n if (state == TriTrue)\n {\n \/\/ eigenvalues are sorted in rising order, and if the last ev is\n \/\/ not positive, we have still to look after zero evs.\n if (eigenvalues[ijmax - 1] > 0)\n state = TriFalse;\n else\n {\n int zeroes = 0;\n\n for (int i = 0; i < ijmax && state == 1; ++i)\n {\n \/\/ only count zero eigenvals if the eigenvector contains a reaction\n \/\/ that is participating in this extreme current.\n if (eigenvalues[i] == 0)\n {\n for (int j = 0; j < ijmax; ++ j)\n if (partMetabs[j] && outarray[i*ijmax + j])\n if (++zeroes)\n break;\n\n if (zeroes == 2)\n state = TriFalse;\n }\n }\n }\n }\n\n mIsMixingStable.push_back(state);\n }\n\n return true;\n}\n\nbool\nCSSAMethod::decomposeJacobian()\n{\n mTransformedSubJacobians.clear();\n\n \/\/ parameters for the double matrix multiplication with dgemm_\n char cN = 'N'; \/\/ don't transpose matrices\n C_INT m = mStoichiometry.numRows(); \/\/ the leading dimension of the Stoi.M. and of the resulting M.\n C_INT n = mStoichiometry.numCols(); \/\/ the dimensions of matrix diagE, also used as 'k'.\n\n C_FLOAT64 alpha = 1.;\n C_FLOAT64 beta = 0.;\n\n CMatrix< C_FLOAT64 > product;\n product.resize(m, m);\n\n std::vector< CVector<C_FLOAT64> >::iterator iter;\n\n for (iter = mExtremeCurrents.begin(); iter != mExtremeCurrents.end(); ++iter)\n {\n CMatrix<C_FLOAT64> diagE = diag(*iter);\n\n \/\/ compute N*Ei*kappa^T:\n \/\/ As the representation of the matrices in their arrays is in\n \/\/ transposed (mathematical) order, we compute kappa*Ei*N^T,\n \/\/ which corresponds to\n \/\/ (mTransposedKineticMatrix*diagE)*mStoichiometry\n C_FLOAT64 dummy[m*n];\n dgemm_(&cN, &cN,\n &m, &n, &n, &alpha,\n mTransposedKineticMatrix.array(), &m ,\n diagE.array(), &n,\n &beta, dummy, &m);\n dgemm_(&cN, &cN,\n &m, &m, &n, &alpha,\n dummy, &m,\n mStoichiometry.array(), &n,\n &beta, product.array(), &m);\n\n mTransformedSubJacobians.push_back(product);\n }\n\n return true;\n}\n\nbool\nCSSAMethod::buildStoichiometry()\n{\n if (!mpModel) return false;\n\n \/\/rebuild the stoichiometric matrix with reversible reactions divided into two.\n\n \/\/ build the _transposed_ of stoichiometry, with expanded reversible reactions\n int numRows = mStoi[0].size();\n int numCols = mStoi.size();\n\n mStoichiometry.resize(numRows, numCols);\n memset(mStoichiometry.array(), 0, numRows*numCols*sizeof(C_FLOAT64));\n\n for (int i = 0; i < numRows; ++i)\n for (int j = 0; j < numCols; ++j)\n mStoichiometry(i, j) = mStoi[j][i];\n\n return true;\n}\n\nbool\nCSSAMethod::buildKineticMatrix()\n{\n if (!mpModel) return false;\n\n C_FLOAT64 num_metabolites = mpModel->getNumIndependentReactionMetabs();\n\n C_FLOAT64 num_reactions = mNumReactions;\n\n mTransposedKineticMatrix.resize((C_INT64)num_reactions, (C_INT64)num_metabolites);\n memset(mTransposedKineticMatrix.array(), 0, (int)(num_metabolites*num_reactions*sizeof(C_FLOAT64)));\n\n CCopasiVector< CMetab > & metabOrder = mpModel->getMetabolitesX();\n\n for (int ireac = 0; ireac < mIsBackwardReaction.size(); ++ireac)\n {\n CCopasiVector< CChemEqElement > substrates;\n\n if (mIsBackwardReaction[ireac])\n substrates = mReorderedReactions[ireac]->getChemEq().getProducts();\n else\n substrates = mReorderedReactions[ireac]->getChemEq().getSubstrates();\n\n for (int jsubst = 0; jsubst < substrates.size(); ++jsubst)\n {\n CCopasiVector< CMetab >::iterator found = find(metabOrder.begin(),\n metabOrder.end(),\n substrates[jsubst]->getMetabolite());\n\n if ((*found)->isDependent()) continue;\n\n int kmetab = std::distance(metabOrder.begin(), found);\n mTransposedKineticMatrix[ireac][kmetab] = substrates[jsubst]->getMultiplicity();\n }\n }\n\n return true;\n}\n\nbool\nCSSAMethod::buildExtremeCurrents()\n{\n mExtremeCurrents.clear();\n\n calculateFluxModes();\n\n std::vector< CFluxMode > fluxmodes = getFluxModes();\n\n CVector< C_FLOAT64 > extremecurrent;\n extremecurrent.resize(mNumReactions);\n\n std::vector< CFluxMode >::iterator iter;\n\n for (iter = fluxmodes.begin(); iter != fluxmodes.end(); ++iter)\n {\n memset(extremecurrent.array(), 0, extremecurrent.size()*sizeof(C_FLOAT64));\n unsigned C_INT32 i;\n\n for (i = 0; i < iter->size(); ++i)\n {\n extremecurrent[iter->getReactionIndex(i)] = iter->getMultiplier(i);\n }\n }\n\n return true;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * This file is part of the CN24 semantic segmentation software,\n * copyright (C) 2015 Clemens-Alexander Brust (ikosa dot de at gmail dot com).\n *\n * For licensing information, see the LICENSE file included with this project.\n *\/ \n\/**\n * @file runBenchmark.cpp\n *\n * @author Clemens-Alexander Brust (ikosa dot de at gmail dot com)\n *\/\n\n#include <iostream>\n#include <fstream>\n#include <cstring>\n#include <sstream>\n#include <chrono>\n\n#include <cn24.h>\n\nstd::string hardcoded_net = \"# Sample CNN for LabelMeFacade Dataset \\n\\\n#anual rfx=34 rfy=34 factorx=4 factory=4 \\n\\\n \\n\\\n# Network configuration \\n\\\n?convolutional kernels=16 size=7x7 \\n\\\n?maxpooling size=4x4 \\n\\\n?tanh \\n\\\n \\n\\\n?convolutional kernels=12 size=5x5 \\n\\\n?maxpooling size=2x2 \\n\\\n?tanh \\n\\\n \\n\\\n?convolutional kernels=96 size=5x5 \\n\\\n?tanh \\n\\\n \\n\\\n?fullyconnected neurons=512 \\n\\\n?tanh \\n\\\n \\n\\\n?fullyconnected neurons=192 \\n\\\n?tanh \\n\\\n \\n\\\n?fullyconnected neurons=(o) \\n\\\n?output \\n\\\n \\n\\\n# Learning settings \\n\\\nl1=0.000 \\n\\\nl2=0.0008 \\n\\\nlr=0.02 \\n\\\ngamma=0.003 \\n\\\nmomentum=0.9 \\n\\\nexponent=0.75 \\n\\\niterations=100 \\n\\\nsbatchsize=24 \\n\\\npbatchsize=2 \\n\\\nmu=1.75 \\n\\\neta=0.1 \\n\\\n\";\n\nstd::string hardcoded_net_ci = \"# Sample CNN for LabelMeFacade Dataset \\n\\\n#anual rfx=34 rfy=34 factorx=4 factory=4 \\n\\\n \\n\\\n# Network configuration \\n\\\n?convolutional kernels=8 size=7x7 \\n\\\n?maxpooling size=2x2 \\n\\\n \\n\\\n?convolutional kernels=4 size=5x5 \\n\\\n?tanh \\n\\\n \\n\\\n?convolutional kernels=12 size=5x5 \\n\\\n?tanh \\n\\\n \\n\\\n?fullyconnected neurons=64 \\n\\\n?tanh \\n\\\n \\n\\\n?fullyconnected neurons=(o) \\n\\\n?output \\n\\\n \\n\\\n# Learning settings \\n\\\nl1=0.000 \\n\\\nl2=0.0008 \\n\\\nlr=0.02 \\n\\\ngamma=0.003 \\n\\\nmomentum=0.9 \\n\\\nexponent=0.75 \\n\\\niterations=100 \\n\\\nsbatchsize=24 \\n\\\npbatchsize=2 \\n\\\nmu=1.75 \\n\\\neta=0.1 \\n\\\n\";\n\nint main (int argc, char* argv[]) {\n \/\/ Initialize stat descriptor\n Conv::StatDescriptor fps;\n fps.nullable = false;\n fps.description = \"Throughput\";\n fps.unit = \"frames\/s\";\n fps.init_function = [] (Conv::Stat& stat) {\n stat.is_null = false;\n stat.value = 0.0;\n };\n fps.output_function = [] (Conv::HardcodedStats& hc_stats, Conv::Stat& stat) {\n Conv::Stat return_stat = stat;\n return_stat.value = stat.value \/ hc_stats.seconds_elapsed;\n return return_stat;\n };\n fps.update_function = [] (Conv::Stat& stat, double user_value) {\n stat.value += user_value;\n };\n \n \/\/ Initialize CN24\n Conv::System::Init();\n \n \/\/ Register ConsoleStatSink\n Conv::ConsoleStatSink sink;\n Conv::System::stat_aggregator->RegisterSink(&sink);\n \n \/\/ Register fps counter\n Conv::System::stat_aggregator->RegisterStat(&fps);\n \n \/\/ Capture command line arguments\n std::string net_config_fname;\n if(argc > 1) {\n net_config_fname = std::string(argv[1]);\n LOGDEBUG << \"Using user specified net: \" << net_config_fname;\n }\n \n \/\/ Set benchmark arguments\n unsigned int CLASSES = 10;\n unsigned int INPUTMAPS = 3;\n\tunsigned int BENCHMARK_PASSES_FWD = 30;\n\tunsigned int BENCHMARK_PASSES_BWD = 15;\n unsigned int width = 512;\n unsigned int height = 512;\n\n std::istream* net_config_stream;\n \n if(argc > 1 && net_config_fname.compare(0,4,\"--ci\") != 0) {\n \/\/ Open network and dataset configuration files\n std::ifstream* net_config_file = new std::ifstream(net_config_fname,std::ios::in);\n \n if(!net_config_file->good()) {\n FATAL(\"Cannot open net configuration file!\");\n }\n net_config_stream = net_config_file;\n } else {\n if(net_config_fname.compare(0,4,\"--ci\") == 0) {\n LOGINFO << \"Using hardcoded net for continuous integration.\";\n std::stringstream* ss = new std::stringstream(hardcoded_net_ci);\n net_config_stream = ss;\n width = 64;\n height = 64;\n } else {\n LOGINFO << \"Using hardcoded net.\";\n std::stringstream* ss = new std::stringstream(hardcoded_net);\n net_config_stream = ss;\n }\n }\n \n \/\/ Parse network configuration file\n Conv::ConfigurableFactory* factory = new Conv::ConfigurableFactory(*net_config_stream, 238238, false);\n \n\n Conv::Tensor data_tensor(factory->optimal_settings().pbatchsize, width, height, INPUTMAPS);\n data_tensor.Clear();\n\n \/\/ Assemble net\n\tConv::NetGraph graph;\n Conv::InputLayer input_layer(data_tensor);\n\n\tConv::NetGraphNode input_node(&input_layer);\n input_node.is_input = true;\n\n\tgraph.AddNode(&input_node);\n\tbool complete = factory->AddLayers(graph, Conv::NetGraphConnection(&input_node), CLASSES);\n\tif (!complete)\n FATAL(\"Failed completeness check, inspect model!\");\n\tfactory->InitOptimalSettings();\n\n\tLOGINFO << \"Initializing net, this may take a while...\" << std::flush;\n\tgraph.Initialize();\n graph.SetIsTesting(true);\n \n \/\/ Initialize StatAggregator\n Conv::System::stat_aggregator->Initialize();\n \n graph.FeedForward();\n\tgraph.BackPropagate();\n\t\n\tLOGINFO << \"Benchmark information\";\n\tLOGINFO << \"=====================\";\n\t\n\tLOGINFO << \"Input width : \" << width;\n\tLOGINFO << \"Input height : \" << height;\n\tLOGINFO << \"Parallel inputs: \" << factory->optimal_settings().pbatchsize;\n\tLOGINFO << \"=====================\";\n\t\n\tLOGINFO << \"Running forward benchmark...\\n\" << std::flush;\n Conv::System::stat_aggregator->StartRecording();\n\t{\n\t\tfor(unsigned int p = 0; p < BENCHMARK_PASSES_FWD; p++) {\n\t\t\tgraph.FeedForward();\n Conv::System::stat_aggregator->Update(fps.stat_id, (double)(factory->optimal_settings().pbatchsize));\n\t\t\tstd::cout << \".\" << std::flush;\n\t\t}\n\t\tstd::cout << \"\\n\";\n\t}\n Conv::System::stat_aggregator->StopRecording();\n Conv::System::stat_aggregator->Generate();\n\tConv::System::stat_aggregator->Reset();\n \n graph.SetIsTesting(false);\n\tLOGINFO << \"Running forward+backward benchmark...\\n\" << std::flush;\n Conv::System::stat_aggregator->StartRecording();\n\t{\n\t\tfor(unsigned int p = 0; p < BENCHMARK_PASSES_BWD; p++) {\n\t\t\tgraph.FeedForward();\n\t\t\tgraph.BackPropagate();\n Conv::System::stat_aggregator->Update(fps.stat_id, (double)(factory->optimal_settings().pbatchsize));\n\t\t\tstd::cout << \".\" << std::flush;\n\t\t}\n\t\tstd::cout << \"\\n\";\n\t}\n Conv::System::stat_aggregator->StopRecording();\n Conv::System::stat_aggregator->Generate();\n Conv::System::stat_aggregator->Reset();\n \n \/\/ Gradient check\n\tLOGINFO << \"Running sparse gradient check...\" << std::flush;\n auto start_time = std::chrono::system_clock::now();\n Conv::GradientTester::TestGradient(graph, 999, true);\n \n auto stop_time = std::chrono::system_clock::now();\n std::chrono::duration<double> t_diff = stop_time - start_time;\n LOGRESULT << \"Gradient check took \" << t_diff.count() << \" seconds.\" << LOGRESULTEND;\n \n LOGINFO << \"DONE!\";\n LOGEND;\n return 0;\n}\n<commit_msg>runBenchmark: Added random content<commit_after>\/*\n * This file is part of the CN24 semantic segmentation software,\n * copyright (C) 2015 Clemens-Alexander Brust (ikosa dot de at gmail dot com).\n *\n * For licensing information, see the LICENSE file included with this project.\n *\/ \n\n\/**\n * @file runBenchmark.cpp\n *\n * @author Clemens-Alexander Brust (ikosa dot de at gmail dot com)\n *\/\n\n#include <iostream>\n#include <fstream>\n#include <cstring>\n#include <sstream>\n#include <chrono>\n#include <random>\n\n#include <cn24.h>\n\nstd::string hardcoded_net = \"# Sample CNN for LabelMeFacade Dataset \\n\\\n#anual rfx=34 rfy=34 factorx=4 factory=4 \\n\\\n \\n\\\n# Network configuration \\n\\\n?convolutional kernels=16 size=7x7 \\n\\\n?maxpooling size=4x4 \\n\\\n?tanh \\n\\\n \\n\\\n?convolutional kernels=12 size=5x5 \\n\\\n?maxpooling size=2x2 \\n\\\n?tanh \\n\\\n \\n\\\n?convolutional kernels=96 size=5x5 \\n\\\n?tanh \\n\\\n \\n\\\n?fullyconnected neurons=512 \\n\\\n?tanh \\n\\\n \\n\\\n?fullyconnected neurons=192 \\n\\\n?tanh \\n\\\n \\n\\\n?fullyconnected neurons=(o) \\n\\\n?output \\n\\\n \\n\\\n# Learning settings \\n\\\nl1=0.000 \\n\\\nl2=0.0008 \\n\\\nlr=0.02 \\n\\\ngamma=0.003 \\n\\\nmomentum=0.9 \\n\\\nexponent=0.75 \\n\\\niterations=100 \\n\\\nsbatchsize=24 \\n\\\npbatchsize=2 \\n\\\nmu=1.75 \\n\\\neta=0.1 \\n\\\n\";\n\nstd::string hardcoded_net_ci = \"# Sample CNN for LabelMeFacade Dataset \\n\\\n#anual rfx=34 rfy=34 factorx=4 factory=4 \\n\\\n \\n\\\n# Network configuration \\n\\\n?convolutional kernels=8 size=7x7 \\n\\\n?maxpooling size=2x2 \\n\\\n \\n\\\n?convolutional kernels=4 size=5x5 \\n\\\n?tanh \\n\\\n \\n\\\n?convolutional kernels=12 size=5x5 \\n\\\n?tanh \\n\\\n \\n\\\n?fullyconnected neurons=64 \\n\\\n?tanh \\n\\\n \\n\\\n?fullyconnected neurons=(o) \\n\\\n?output \\n\\\n \\n\\\n# Learning settings \\n\\\nl1=0.000 \\n\\\nl2=0.0008 \\n\\\nlr=0.02 \\n\\\ngamma=0.003 \\n\\\nmomentum=0.9 \\n\\\nexponent=0.75 \\n\\\niterations=100 \\n\\\nsbatchsize=24 \\n\\\npbatchsize=2 \\n\\\nmu=1.75 \\n\\\neta=0.1 \\n\\\n\";\n\nint main (int argc, char* argv[]) {\n \/\/ Initialize stat descriptor\n Conv::StatDescriptor fps;\n fps.nullable = false;\n fps.description = \"Throughput\";\n fps.unit = \"frames\/s\";\n fps.init_function = [] (Conv::Stat& stat) {\n stat.is_null = false;\n stat.value = 0.0;\n };\n fps.output_function = [] (Conv::HardcodedStats& hc_stats, Conv::Stat& stat) {\n Conv::Stat return_stat = stat;\n return_stat.value = stat.value \/ hc_stats.seconds_elapsed;\n return return_stat;\n };\n fps.update_function = [] (Conv::Stat& stat, double user_value) {\n stat.value += user_value;\n };\n \n \/\/ Initialize CN24\n Conv::System::Init();\n \n \/\/ Register ConsoleStatSink\n Conv::ConsoleStatSink sink;\n Conv::System::stat_aggregator->RegisterSink(&sink);\n \n \/\/ Register fps counter\n Conv::System::stat_aggregator->RegisterStat(&fps);\n \n \/\/ Capture command line arguments\n std::string net_config_fname;\n if(argc > 1) {\n net_config_fname = std::string(argv[1]);\n LOGDEBUG << \"Using user specified net: \" << net_config_fname;\n }\n \n \/\/ Set benchmark arguments\n unsigned int CLASSES = 10;\n unsigned int INPUTMAPS = 3;\n\tunsigned int BENCHMARK_PASSES_FWD = 30;\n\tunsigned int BENCHMARK_PASSES_BWD = 15;\n unsigned int width = 512;\n unsigned int height = 512;\n\n std::istream* net_config_stream;\n \n if(argc > 1 && net_config_fname.compare(0,4,\"--ci\") != 0) {\n \/\/ Open network and dataset configuration files\n std::ifstream* net_config_file = new std::ifstream(net_config_fname,std::ios::in);\n \n if(!net_config_file->good()) {\n FATAL(\"Cannot open net configuration file!\");\n }\n net_config_stream = net_config_file;\n } else {\n if(net_config_fname.compare(0,4,\"--ci\") == 0) {\n LOGINFO << \"Using hardcoded net for continuous integration.\";\n std::stringstream* ss = new std::stringstream(hardcoded_net_ci);\n net_config_stream = ss;\n width = 64;\n height = 64;\n } else {\n LOGINFO << \"Using hardcoded net.\";\n std::stringstream* ss = new std::stringstream(hardcoded_net);\n net_config_stream = ss;\n }\n }\n \n \/\/ Parse network configuration file\n Conv::ConfigurableFactory* factory = new Conv::ConfigurableFactory(*net_config_stream, 238238, false);\n \n\n Conv::Tensor data_tensor(factory->optimal_settings().pbatchsize, width, height, INPUTMAPS);\n data_tensor.Clear();\n\n \/\/ Generate random contents\n std::mt19937 rand(1337);\n std::uniform_real_distribution<Conv::datum> dist (0.0, 1.0);\n for(unsigned int e = 0; e < data_tensor.elements(); e++) {\n (data_tensor.data_ptr())[e] = dist(rand);\n }\n\n \/\/ Assemble net\n\tConv::NetGraph graph;\n Conv::InputLayer input_layer(data_tensor);\n\n\tConv::NetGraphNode input_node(&input_layer);\n input_node.is_input = true;\n\n\tgraph.AddNode(&input_node);\n\tbool complete = factory->AddLayers(graph, Conv::NetGraphConnection(&input_node), CLASSES);\n\tif (!complete)\n FATAL(\"Failed completeness check, inspect model!\");\n\tfactory->InitOptimalSettings();\n\n\tLOGINFO << \"Initializing net, this may take a while...\" << std::flush;\n\tgraph.Initialize();\n graph.SetIsTesting(true);\n \n \/\/ Initialize StatAggregator\n Conv::System::stat_aggregator->Initialize();\n \n graph.FeedForward();\n\tgraph.BackPropagate();\n\t\n\tLOGINFO << \"Benchmark information\";\n\tLOGINFO << \"=====================\";\n\t\n\tLOGINFO << \"Input width : \" << width;\n\tLOGINFO << \"Input height : \" << height;\n\tLOGINFO << \"Parallel inputs: \" << factory->optimal_settings().pbatchsize;\n\tLOGINFO << \"=====================\";\n\t\n\tLOGINFO << \"Running forward benchmark...\\n\" << std::flush;\n Conv::System::stat_aggregator->StartRecording();\n\t{\n\t\tfor(unsigned int p = 0; p < BENCHMARK_PASSES_FWD; p++) {\n\t\t\tgraph.FeedForward();\n Conv::System::stat_aggregator->Update(fps.stat_id, (double)(factory->optimal_settings().pbatchsize));\n\t\t\tstd::cout << \".\" << std::flush;\n\t\t}\n\t\tstd::cout << \"\\n\";\n\t}\n Conv::System::stat_aggregator->StopRecording();\n Conv::System::stat_aggregator->Generate();\n\tConv::System::stat_aggregator->Reset();\n \n graph.SetIsTesting(false);\n\tLOGINFO << \"Running forward+backward benchmark...\\n\" << std::flush;\n Conv::System::stat_aggregator->StartRecording();\n\t{\n\t\tfor(unsigned int p = 0; p < BENCHMARK_PASSES_BWD; p++) {\n\t\t\tgraph.FeedForward();\n\t\t\tgraph.BackPropagate();\n Conv::System::stat_aggregator->Update(fps.stat_id, (double)(factory->optimal_settings().pbatchsize));\n\t\t\tstd::cout << \".\" << std::flush;\n\t\t}\n\t\tstd::cout << \"\\n\";\n\t}\n Conv::System::stat_aggregator->StopRecording();\n Conv::System::stat_aggregator->Generate();\n Conv::System::stat_aggregator->Reset();\n \n \/\/ Gradient check\n\tLOGINFO << \"Running sparse gradient check...\" << std::flush;\n auto start_time = std::chrono::system_clock::now();\n Conv::GradientTester::TestGradient(graph, 999, true);\n \n auto stop_time = std::chrono::system_clock::now();\n std::chrono::duration<double> t_diff = stop_time - start_time;\n LOGRESULT << \"Gradient check took \" << t_diff.count() << \" seconds.\" << LOGRESULTEND;\n \n LOGINFO << \"DONE!\";\n LOGEND;\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>#include <memory>\n#include <iostream>\n\n#include <eventLoop.hxx>\n\n#include <THandle.hxx>\n#include <TG4Trajectory.hxx>\n\n\/\/\/ User code for the event loop. This can be copied and used as a skeleton\n\/\/\/ for generic user loop programs.\nclass TUserLoop: public CP::TEventLoopFunction {\npublic:\n \/\/\/ Initialize any class specific variables, but most of the work can be\n \/\/\/ done in Initialize. Don't create histograms here!\n TUserLoop() {}\n virtual ~TUserLoop() {};\n\n \/\/\/ Print a usage message. This is generally called when there is a\n \/\/\/ command line input error.\n void Usage(void) {\n }\n\n \/\/\/ Set an option and return true if it is valid. This is called by the\n \/\/\/ event loop command line argument processing code for each \"-O\n \/\/\/ [name]=[value]\" option found on the command line. If the command line\n \/\/\/ has \"-O [name]\" without a value, then the value string will be equal\n \/\/\/ to \"\". This must return false if the option was not correctly\n \/\/\/ processed.\n virtual bool SetOption(std::string option,std::string value=\"\") {\n return false;\n }\n\n \/\/\/ Called for each event inside the event loop, and returns true if the\n \/\/\/ event should be saved to the output file. If the remainder of the\n \/\/\/ current file should be skipped, this should through the\n \/\/\/ ENextEventLoopFile exception. If the daughter class defines this\n \/\/\/ operator, it should not define the Process() method.\n bool operator () (CP::TEvent& event) {\n CP::THandle<CP::TG4TrajectoryContainer> trajectories\n = event.Get<CP::TG4TrajectoryContainer>(\"truth\/G4Trajectories\");\n if (!trajectories) {\n std::cout << \"No Trajectory container\" << std::endl;\n return false;\n }\n trajectories->ls();\n CP::THandle<CP::TG4Trajectory> traj = trajectories->GetTrajectory(1);\n if (!traj) {\n std::cout << \"No Trajectories\" << std::endl;\n }\n std::cout << \"Print the trajectory\" << std::endl;\n traj->ls();\n std::cout << \"Get the initial position\" << std::endl;\n std::cout << \" x \" << traj->GetInitialPosition().X() << std::endl;\n std::cout << \" y \" << traj->GetInitialPosition().Y() << std::endl;\n std::cout << \" z \" << traj->GetInitialPosition().Z() << std::endl;\n std::cout << \"Get the final position\" << std::endl;\n std::cout << \" x \" << traj->GetFinalPosition().X() << std::endl;\n std::cout << \" y \" << traj->GetFinalPosition().Y() << std::endl;\n std::cout << \" z \" << traj->GetFinalPosition().Z() << std::endl;\n\n return true;\n }\n\n \/\/\/ Called after the arguments are processed but before reading the first\n \/\/\/ event. The output file is open so any histograms will be added to the\n \/\/\/ output file.\n virtual void Initialize(void) {\n }\n\n \/\/\/ Called after reading the last event. The output file is still open,\n \/\/\/ so you can add extra information. Because of an ideosyncracy in the\n \/\/\/ way root handles histograms, objects created in Initialize() will\n \/\/\/ already be stored in the output file.\n virtual void Finalize(CP::TRootOutput* output) {\n }\n\nprivate:\n\n};\n\nint main(int argc, char **argv) {\n TUserLoop userLoop;\n CP::eventLoop(argc,argv,userLoop);\n}\n<commit_msg>Add example of how to write to a text file.<commit_after>#include <memory>\n#include <iostream>\n#include <fstream>\n\n#include <eventLoop.hxx>\n\n#include <THandle.hxx>\n#include <TG4Trajectory.hxx>\n\n\/\/\/ User code for the event loop. This can be copied and used as a skeleton\n\/\/\/ for generic user loop programs.\nclass TUserLoop: public CP::TEventLoopFunction {\npublic:\n \/\/\/ Initialize any class specific variables, but most of the work can be\n \/\/\/ done in Initialize. Don't create histograms here!\n TUserLoop() {}\n virtual ~TUserLoop() {};\n\n \/\/\/ Print a usage message. This is generally called when there is a\n \/\/\/ command line input error.\n void Usage(void) {\n }\n\n \/\/\/ Set an option and return true if it is valid. This is called by the\n \/\/\/ event loop command line argument processing code for each \"-O\n \/\/\/ [name]=[value]\" option found on the command line. If the command line\n \/\/\/ has \"-O [name]\" without a value, then the value string will be equal\n \/\/\/ to \"\". This must return false if the option was not correctly\n \/\/\/ processed.\n virtual bool SetOption(std::string option,std::string value=\"\") {\n return false;\n }\n\n \/\/\/ Called for each event inside the event loop, and returns true if the\n \/\/\/ event should be saved to the output file. If the remainder of the\n \/\/\/ current file should be skipped, this should through the\n \/\/\/ ENextEventLoopFile exception. If the daughter class defines this\n \/\/\/ operator, it should not define the Process() method.\n bool operator () (CP::TEvent& event) {\n CP::THandle<CP::TG4TrajectoryContainer> trajectories\n = event.Get<CP::TG4TrajectoryContainer>(\"truth\/G4Trajectories\");\n if (!trajectories) {\n std::cout << \"No Trajectory container\" << std::endl;\n return false;\n }\n trajectories->ls();\n CP::THandle<CP::TG4Trajectory> traj = trajectories->GetTrajectory(1);\n if (!traj) {\n std::cout << \"No Trajectories\" << std::endl;\n }\n std::cout << \"Print the trajectory\" << std::endl;\n traj->ls();\n std::cout << \"Get the initial position\" << std::endl;\n std::cout << \" x \" << traj->GetInitialPosition().X() << std::endl;\n std::cout << \" y \" << traj->GetInitialPosition().Y() << std::endl;\n std::cout << \" z \" << traj->GetInitialPosition().Z() << std::endl;\n std::cout << \"Get the final position\" << std::endl;\n std::cout << \" x \" << traj->GetFinalPosition().X() << std::endl;\n std::cout << \" y \" << traj->GetFinalPosition().Y() << std::endl;\n std::cout << \" z \" << traj->GetFinalPosition().Z() << std::endl;\n\n double dx = traj->GetFinalPosition().X()-traj->GetInitialPosition().X();\n double dy = traj->GetFinalPosition().Y()-traj->GetInitialPosition().Y();\n double dz = traj->GetFinalPosition().Z()-traj->GetInitialPosition().Z();\n\n double length = std::sqrt(dx*dx + dy*dy + dz*dz);\n\n std::cout << length << std::endl;\n\n fOutput << length << std::endl;\n \n return true;\n }\n\n \/\/\/ Called after the arguments are processed but before reading the first\n \/\/\/ event. The output file is open so any histograms will be added to the\n \/\/\/ output file.\n virtual void Initialize(void) {\n fOutput.open(\"proton100.data\");\n }\n\n \/\/\/ Called after reading the last event. The output file is still open,\n \/\/\/ so you can add extra information. Because of an ideosyncracy in the\n \/\/\/ way root handles histograms, objects created in Initialize() will\n \/\/\/ already be stored in the output file.\n virtual void Finalize(CP::TRootOutput* output) {\n fOutput.close();\n }\n\nprivate:\n\n std::ofstream fOutput;\n \n};\n\nint main(int argc, char **argv) {\n TUserLoop userLoop;\n CP::eventLoop(argc,argv,userLoop);\n}\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n#include <iomanip>\n#include <string>\n\n#include <itkImage.h>\n#include <itkLinearInterpolateImageFunction.h>\n#include <itkNearestNeighborInterpolateImageFunction.h>\n#include <itkLabelImageGaussianInterpolateImageFunction.h>\n#include <itkBSplineInterpolateImageFunction.h>\n#include <itkResampleImageFilter.h>\n#include <itkVersorRigid3DTransform.h>\n#include <itkImageFileWriter.h>\n#include <itkImageFileReader.h>\n#include <itkTestingComparisonImageFilter.h>\n#include <itkTimeProbe.h>\n\n#include \"itkLabelImageGenericInterpolateImageFunction.h\"\n#include \"itkLabelSelectionAdaptor.h\"\n\n\/* This demo is a torture test for interpolators: it takes an input label map,\n * rotates it one full turn in ten steps, and writes the result *\/\n\ntemplate <class ImageType>\nvoid\nRotateNTimes(typename ImageType::Pointer input, \n typename itk::InterpolateImageFunction<ImageType,double>* interpolator,\n unsigned int number_of_rotations, std::string outputFilename) {\n\ttypedef itk::VersorRigid3DTransform<double> TransformType;\n\ttypedef itk::ResampleImageFilter<ImageType,ImageType> ResampleFilterType;\n\tTransformType::AxisType axis;\n\taxis[0]=0;\n\taxis[1]=1;\n\taxis[2]=0;\n\tTransformType::InputPointType center;\n\tcenter[0] = 144;\n\tcenter[1] = 86;\n\tcenter[2] = 101;\n\tTransformType::Pointer rot = TransformType::New();\n\trot->SetCenter(center);\n\trot->SetRotation(axis,2.*M_PI\/number_of_rotations);\n\n\ttypename ResampleFilterType::Pointer rs = ResampleFilterType::New();\n\trs->SetInput( input );\n\trs->SetReferenceImage( input );\n\trs->SetUseReferenceImage(true);\n\trs->SetTransform(rot);\n\t\/\/interp->SetSigma(0.3); \/\/ Used for the gaussian interpolator\n\trs->SetInterpolator(interpolator);\n\ttypename ImageType::Pointer out ;\n itk::TimeProbe timer; timer.Start();\n\tfor (unsigned i = 0; i<number_of_rotations; ++i) {\n\t\trs->SetReferenceImage( input );\n\t\trs->SetUseReferenceImage(true);\n\t\trs->Update();\n\t\tout = rs->GetOutput();\n\t\tout->DisconnectPipeline();\n\t\trs->SetInput(out);\n\t\trs->SetTransform(rot);\n\t}\n timer.Stop();\n typedef itk::Testing::ComparisonImageFilter<ImageType,ImageType> ComparisonFilterType;\n typename ComparisonFilterType::Pointer compare = ComparisonFilterType::New();\n compare->SetValidInput( input );\n compare->SetTestInput( out );\n compare->Update();\n std::cout << \"Pixels with differences: \" << std::setw(8) << compare->GetNumberOfPixelsWithDifferences() << \n \" ( \" << std::fixed << std::setprecision(2) << static_cast<double>(compare->GetNumberOfPixelsWithDifferences()) \/\n input->GetLargestPossibleRegion().GetNumberOfPixels() * 100.<< \n \"% ) in \" << timer.GetTotal() << \"s\" << std::endl;\n\ttypedef itk::ImageFileWriter< ImageType > WriterType;\n\ttypename WriterType::Pointer writer = WriterType::New();\n\twriter->SetUseCompression(true);\n\twriter->SetInput( out );\n\twriter->SetFileName(outputFilename);\n\twriter->Write();\n}\n\n\n\/\/ The BSpline interpolator has more arguments than other interpolators, so we set the additional parameter to the default value\nusing namespace std;\ntemplate<class TImage,typename TCoordRep> class BSplineInterpolator : public itk::BSplineInterpolateImageFunction<TImage,TCoordRep> {};\n \nint main(int argc, char *argv[])\n{\n\tstring outputFilename = \"resampled.mha\";\n\tstring inputFilename = \"..\/Source\/classification.mha\";\n\n\ttypedef unsigned char PixelType;\n\tconst unsigned int Dimension = 3;\n\ttypedef itk::Image< PixelType, Dimension > ImageType;\n\n\ttypedef itk::ImageFileReader<ImageType> ReaderType;\n\tReaderType::Pointer r = ReaderType::New();\n\tr->SetFileName(inputFilename);\n\tr->Update();\n\n\tfor( unsigned number_of_rotations=3; number_of_rotations <=7;\n number_of_rotations+=2 ) {\n std::cout << \"Testing with \" << number_of_rotations << \" rotations...\" << std::endl << std::endl;\n\n std::cout << \"Nearest neighbor interpolator... \" << std::flush;\n typedef itk::NearestNeighborInterpolateImageFunction<ImageType,double> NNInterpolatorType;\n NNInterpolatorType::Pointer nn_interp = NNInterpolatorType::New();\n RotateNTimes<ImageType>(r->GetOutput(), nn_interp, number_of_rotations, \"nearest.mha\");\n\n std::cout << \"Linear interpolator... \" << std::flush;\n typedef itk::LinearInterpolateImageFunction<ImageType,double> LInterpolatorType;\n LInterpolatorType::Pointer l_interp = LInterpolatorType::New();\n RotateNTimes<ImageType>(r->GetOutput(), l_interp, number_of_rotations, \"linear.mha\");\n\n std::cout << \"Label Gaussian interpolator type... \" << std::flush;\n typedef itk::LabelImageGaussianInterpolateImageFunction<ImageType,double> LGInterpolatorType;\n LGInterpolatorType::Pointer lg_interp = LGInterpolatorType::New();\n lg_interp->SetSigma(0.3);\n RotateNTimes<ImageType>(r->GetOutput(), lg_interp, number_of_rotations, \"label_gaussian.mha\");\n\n std::cout << \"Generic label interpolator with nearest neighbor... \" << std::flush;\n typedef itk::LabelImageGenericInterpolateImageFunction<ImageType,itk::NearestNeighborInterpolateImageFunction> GNNInterpolatorType;\n GNNInterpolatorType::Pointer gnn_interp = GNNInterpolatorType::New();\n RotateNTimes<ImageType>(r->GetOutput(), gnn_interp, number_of_rotations, \"gl_nearest.mha\");\n\n std::cout << \"Generic label interpolator with linear interpolation... \" << std::flush;\n typedef itk::LabelImageGenericInterpolateImageFunction<ImageType,itk::LinearInterpolateImageFunction> GLInterpolatorType;\n GLInterpolatorType::Pointer gl_interp = GLInterpolatorType::New();\n RotateNTimes<ImageType>(r->GetOutput(), gl_interp, number_of_rotations, \"gl_linear.mha\");\n\n std::cout << \"Generic label interpolator with B-Spline... \" << std::flush;\n typedef itk::LabelImageGenericInterpolateImageFunction<ImageType,BSplineInterpolator> GBSInterpolatorType;\n GBSInterpolatorType::Pointer gbs_interp = GBSInterpolatorType::New();\n RotateNTimes<ImageType>(r->GetOutput(), gbs_interp, number_of_rotations, \"gl_bspline.mha\");\n\n std::cout << std::endl;\n }\n\n\n\treturn EXIT_SUCCESS;\n}\n<commit_msg>clean output and add gaussian interpolation with the Generic interpolator<commit_after>#include <iostream>\n#include <iomanip>\n#include <string>\n#include <sstream>\n\n#include <itkImage.h>\n#include <itkLinearInterpolateImageFunction.h>\n#include <itkNearestNeighborInterpolateImageFunction.h>\n#include <itkLabelImageGaussianInterpolateImageFunction.h>\n#include <itkBSplineInterpolateImageFunction.h>\n#include <itkResampleImageFilter.h>\n#include <itkVersorRigid3DTransform.h>\n#include <itkImageFileWriter.h>\n#include <itkImageFileReader.h>\n#include <itkTestingComparisonImageFilter.h>\n#include <itkTimeProbe.h>\n\n#include \"itkLabelImageGenericInterpolateImageFunction.h\"\n#include \"itkLabelSelectionAdaptor.h\"\n\n\/* This demo is a torture test for interpolators: it takes an input label map,\n * rotates it one full turn in ten steps, and writes the result *\/\n\ntemplate <class ImageType>\nvoid\nRotateNTimes(typename ImageType::Pointer input, \n typename itk::InterpolateImageFunction<ImageType,double>* interpolator,\n unsigned int number_of_rotations, std::string filename_prefix) {\n\ttypedef itk::VersorRigid3DTransform<double> TransformType;\n\ttypedef itk::ResampleImageFilter<ImageType,ImageType> ResampleFilterType;\n\tTransformType::AxisType axis;\n\taxis[0]=0;\n\taxis[1]=1;\n\taxis[2]=0;\n\tTransformType::InputPointType center;\n\tcenter[0] = 144;\n\tcenter[1] = 86;\n\tcenter[2] = 101;\n\tTransformType::Pointer rot = TransformType::New();\n\trot->SetCenter(center);\n\trot->SetRotation(axis,2.*M_PI\/number_of_rotations);\n\n\ttypename ResampleFilterType::Pointer rs = ResampleFilterType::New();\n\trs->SetInput( input );\n\trs->SetReferenceImage( input );\n\trs->SetUseReferenceImage(true);\n\trs->SetTransform(rot);\n\trs->SetInterpolator(interpolator);\n\ttypename ImageType::Pointer out ;\n itk::TimeProbe timer; timer.Start();\n\tfor (unsigned i = 0; i<number_of_rotations; ++i) {\n\t\trs->SetReferenceImage( input );\n\t\trs->SetUseReferenceImage(true);\n\t\trs->Update();\n\t\tout = rs->GetOutput();\n\t\tout->DisconnectPipeline();\n\t\trs->SetInput(out);\n\t\trs->SetTransform(rot);\n\t}\n timer.Stop();\n typedef itk::Testing::ComparisonImageFilter<ImageType,ImageType> ComparisonFilterType;\n typename ComparisonFilterType::Pointer compare = ComparisonFilterType::New();\n compare->SetValidInput( input );\n compare->SetTestInput( out );\n compare->Update();\n std::cout << \"Pixels with differences: \" << std::setw(8) << compare->GetNumberOfPixelsWithDifferences() << \n \" ( \" << std::fixed << std::setprecision(2) << static_cast<double>(compare->GetNumberOfPixelsWithDifferences()) \/\n input->GetLargestPossibleRegion().GetNumberOfPixels() * 100.<< \n \"% ) in \" << timer.GetTotal() << \"s\" << std::endl;\n\ttypedef itk::ImageFileWriter< ImageType > WriterType;\n\ttypename WriterType::Pointer writer = WriterType::New();\n\twriter->SetUseCompression(true);\n\twriter->SetInput( out );\n std::ostringstream fname_stream;\n fname_stream << \"output\/\" << filename_prefix << \"_\" << number_of_rotations << \".mha\";\n\twriter->SetFileName(fname_stream.str());\n\twriter->Write();\n}\n\n\n\/\/ The BSpline interpolator has more arguments than other interpolators, so we set the additional parameter to the default value\nusing namespace std;\ntemplate<class TImage,typename TCoordRep> class BSplineInterpolator : public itk::BSplineInterpolateImageFunction<TImage,TCoordRep> {};\n \nint main(int argc, char *argv[])\n{\n\tstring inputFilename = \"..\/Source\/classification.mha\";\n\n\ttypedef unsigned char PixelType;\n\tconst unsigned int Dimension = 3;\n\ttypedef itk::Image< PixelType, Dimension > ImageType;\n\n\ttypedef itk::ImageFileReader<ImageType> ReaderType;\n\tReaderType::Pointer r = ReaderType::New();\n\tr->SetFileName(inputFilename);\n\tr->Update();\n\n\tfor( unsigned number_of_rotations=3; number_of_rotations <=7;\n number_of_rotations+=2 ) {\n std::cout << \"Testing with \" << number_of_rotations << \" rotations...\" << std::endl << std::endl;\n\n std::cout << \"Nearest neighbor interpolator... \" << std::flush;\n typedef itk::NearestNeighborInterpolateImageFunction<ImageType,double> NNInterpolatorType;\n NNInterpolatorType::Pointer nn_interp = NNInterpolatorType::New();\n RotateNTimes<ImageType>(r->GetOutput(), nn_interp, number_of_rotations, \"nearest\");\n\n std::cout << \"Linear interpolator... \" << std::flush;\n typedef itk::LinearInterpolateImageFunction<ImageType,double> LInterpolatorType;\n LInterpolatorType::Pointer l_interp = LInterpolatorType::New();\n RotateNTimes<ImageType>(r->GetOutput(), l_interp, number_of_rotations, \"linear\");\n\n std::cout << \"Label Gaussian interpolator type... \" << std::flush;\n typedef itk::LabelImageGaussianInterpolateImageFunction<ImageType,double> LGInterpolatorType;\n LGInterpolatorType::Pointer lg_interp = LGInterpolatorType::New();\n lg_interp->SetSigma(0.3);\n RotateNTimes<ImageType>(r->GetOutput(), lg_interp, number_of_rotations, \"label_gaussian\");\n\n std::cout << \"Generic label interpolator with nearest neighbor... \" << std::flush;\n typedef itk::LabelImageGenericInterpolateImageFunction<ImageType,itk::NearestNeighborInterpolateImageFunction> GNNInterpolatorType;\n GNNInterpolatorType::Pointer gnn_interp = GNNInterpolatorType::New();\n RotateNTimes<ImageType>(r->GetOutput(), gnn_interp, number_of_rotations, \"gl_nearest\");\n\n std::cout << \"Generic label interpolator with linear interpolation... \" << std::flush;\n typedef itk::LabelImageGenericInterpolateImageFunction<ImageType,itk::LinearInterpolateImageFunction> GLInterpolatorType;\n GLInterpolatorType::Pointer gl_interp = GLInterpolatorType::New();\n RotateNTimes<ImageType>(r->GetOutput(), gl_interp, number_of_rotations, \"gl_linear\");\n\n std::cout << \"Generic label interpolator with B-Spline interpolation... \" << std::flush;\n typedef itk::LabelImageGenericInterpolateImageFunction<ImageType,BSplineInterpolator> GBSInterpolatorType;\n GBSInterpolatorType::Pointer gbs_interp = GBSInterpolatorType::New();\n RotateNTimes<ImageType>(r->GetOutput(), gbs_interp, number_of_rotations, \"gl_bspline\");\n\n std::cout << \"Generic label interpolator with Gaussian interpolation... \" << std::flush;\n typedef itk::LabelImageGenericInterpolateImageFunction<ImageType,itk::GaussianInterpolateImageFunction> GGInterpolatorType;\n GGInterpolatorType::Pointer gg_interp = GGInterpolatorType::New();\n RotateNTimes<ImageType>(r->GetOutput(), gg_interp, number_of_rotations, \"gl_gaussian\");\n\n std::cout << std::endl;\n }\n\n\n\treturn EXIT_SUCCESS;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 2017, ARM Limited, All Rights Reserved\n * SPDX-License-Identifier: Apache-2.0\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n * not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"mbed.h\"\n#include \"greentea-client\/test_env.h\"\n#include \"unity.h\"\n#include \"utest.h\"\n#include \"wifi_tests.h\"\n\nusing namespace utest::v1;\n\n#if defined(MBED_CONF_APP_WIFI_SECURE_SSID)\n\nvoid wifi_connect_params_channel_fail(void)\n{\n WiFiInterface *wifi = get_interface();\n\n if (wifi->set_channel(1) == NSAPI_ERROR_UNSUPPORTED && wifi->set_channel(36) == NSAPI_ERROR_UNSUPPORTED) {\n TEST_IGNORE_MESSAGE(\"set_channel() not supported\");\n return;\n }\n\n nsapi_error_t error = wifi->connect(MBED_CONF_APP_WIFI_SECURE_SSID, MBED_CONF_APP_WIFI_PASSWORD, get_security(), MBED_CONF_APP_WIFI_CH_SECURE);\n TEST_ASSERT(error==NSAPI_ERROR_CONNECTION_TIMEOUT || error==NSAPI_ERROR_NO_CONNECTION);\n}\n\n#endif \/\/ defined(MBED_CONF_APP_WIFI_SECURE_SSID)\n<commit_msg>Fix WIFI-CONNECT-PARAMS-CHANNEL-FAIL Greentea test case<commit_after>\/*\n * Copyright (c) 2017, ARM Limited, All Rights Reserved\n * SPDX-License-Identifier: Apache-2.0\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n * not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"mbed.h\"\n#include \"greentea-client\/test_env.h\"\n#include \"unity.h\"\n#include \"utest.h\"\n#include \"wifi_tests.h\"\n\nusing namespace utest::v1;\n\n#if defined(MBED_CONF_APP_WIFI_SECURE_SSID)\n\nvoid wifi_connect_params_channel_fail(void)\n{\n WiFiInterface *wifi = get_interface();\n\n if (wifi->set_channel(1) == NSAPI_ERROR_UNSUPPORTED && wifi->set_channel(36) == NSAPI_ERROR_UNSUPPORTED) {\n TEST_IGNORE_MESSAGE(\"set_channel() not supported\");\n return;\n }\n\n nsapi_error_t error = wifi->connect(MBED_CONF_APP_WIFI_SECURE_SSID, MBED_CONF_APP_WIFI_PASSWORD, get_security(), MBED_CONF_APP_WIFI_CH_UNSECURE);\n TEST_ASSERT(error==NSAPI_ERROR_CONNECTION_TIMEOUT || error==NSAPI_ERROR_NO_CONNECTION);\n}\n\n#endif \/\/ defined(MBED_CONF_APP_WIFI_SECURE_SSID)\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2008 by Sun Microsystems, Inc.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: TableWindowAccess.cxx,v $\n * $Revision: 1.13 $\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * <http:\/\/www.openoffice.org\/license.html>\n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_dbaccess.hxx\"\n#ifndef DBACCESS_TABLEWINDOWACCESS_HXX\n#include \"TableWindowAccess.hxx\"\n#endif\n#ifndef DBACCESS_JACCESS_HXX\n#include \"JAccess.hxx\"\n#endif\n#ifndef DBAUI_TABLEWINDOW_HXX\n#include \"TableWindow.hxx\"\n#endif\n#ifndef DBAUI_TABLEWINDOWLISTBOX_HXX\n#include \"TableWindowListBox.hxx\"\n#endif\n#ifndef DBAUI_JOINDESIGNVIEW_HXX\n#include \"JoinDesignView.hxx\"\n#endif\n#ifndef DBAUI_JOINCONTROLLER_HXX\n#include \"JoinController.hxx\"\n#endif\n#ifndef DBAUI_JOINTABLEVIEW_HXX\n#include \"JoinTableView.hxx\"\n#endif\n#ifndef _COM_SUN_STAR_ACCESSIBILITY_ACCESSIBLEROLE_HPP_\n#include <com\/sun\/star\/accessibility\/AccessibleRole.hpp>\n#endif\n#ifndef _COM_SUN_STAR_ACCESSIBILITY_ACCESSIBLERELATIONTYPE_HPP_\n#include <com\/sun\/star\/accessibility\/AccessibleRelationType.hpp>\n#endif\n#ifndef _COM_SUN_STAR_ACCESSIBILITY_ACCESSIBLESTATETYPE_HPP_\n#include <com\/sun\/star\/accessibility\/AccessibleStateType.hpp>\n#endif\n#ifndef _COM_SUN_STAR_ACCESSIBILITY_ACCESSIBLEEVENTID_HPP_\n#include <com\/sun\/star\/accessibility\/AccessibleEventId.hpp>\n#endif\n#ifndef _COMPHELPER_SEQUENCE_HXX_\n#include <comphelper\/sequence.hxx>\n#endif\n#ifndef _DBU_QRY_HRC_\n#include \"dbu_qry.hrc\"\n#endif\n\n\nnamespace dbaui\n{\n using namespace ::com::sun::star::accessibility;\n using namespace ::com::sun::star::uno;\n using namespace ::com::sun::star::beans;\n using namespace ::com::sun::star::lang;\n \/\/ using namespace ::com::sun::star::awt;\n using namespace ::com::sun::star;\n\n OTableWindowAccess::OTableWindowAccess(OTableWindow* _pTable)\n :VCLXAccessibleComponent(_pTable->GetComponentInterface().is() ? _pTable->GetWindowPeer() : NULL)\n ,m_pTable(_pTable)\n {\n }\n \/\/ -----------------------------------------------------------------------------\n void SAL_CALL OTableWindowAccess::disposing()\n {\n m_pTable = NULL;\n VCLXAccessibleComponent::disposing();\n }\n \/\/ -----------------------------------------------------------------------------\n Any SAL_CALL OTableWindowAccess::queryInterface( const Type& aType ) throw (RuntimeException)\n {\n Any aRet(VCLXAccessibleComponent::queryInterface( aType ));\n return aRet.hasValue() ? aRet : OTableWindowAccess_BASE::queryInterface( aType );\n }\n \/\/ -----------------------------------------------------------------------------\n Sequence< Type > SAL_CALL OTableWindowAccess::getTypes( ) throw (RuntimeException)\n {\n return ::comphelper::concatSequences(VCLXAccessibleComponent::getTypes(),OTableWindowAccess_BASE::getTypes());\n }\n \/\/ -----------------------------------------------------------------------------\n ::rtl::OUString SAL_CALL OTableWindowAccess::getImplementationName() throw(RuntimeException)\n {\n return getImplementationName_Static();\n }\n \/\/ -----------------------------------------------------------------------------\n Sequence< ::rtl::OUString > SAL_CALL OTableWindowAccess::getSupportedServiceNames() throw(RuntimeException)\n {\n return getSupportedServiceNames_Static();\n }\n \/\/ -----------------------------------------------------------------------------\n \/\/ XServiceInfo - static methods\n Sequence< ::rtl::OUString > OTableWindowAccess::getSupportedServiceNames_Static(void) throw( RuntimeException )\n {\n Sequence< ::rtl::OUString > aSupported(2);\n aSupported[0] = ::rtl::OUString::createFromAscii(\"com.sun.star.accessibility.Accessible\");\n aSupported[1] = ::rtl::OUString::createFromAscii(\"com.sun.star.accessibility.AccessibleContext\");\n return aSupported;\n }\n \/\/ -----------------------------------------------------------------------------\n ::rtl::OUString OTableWindowAccess::getImplementationName_Static(void) throw( RuntimeException )\n {\n return ::rtl::OUString::createFromAscii(\"org.openoffice.comp.dbu.TableWindowAccessibility\");\n }\n \/\/ -----------------------------------------------------------------------------\n \/\/ XAccessibleContext\n sal_Int32 SAL_CALL OTableWindowAccess::getAccessibleChildCount( ) throw (RuntimeException)\n {\n ::osl::MutexGuard aGuard( m_aMutex );\n sal_Int32 nCount = 0;\n if(m_pTable)\n {\n if(m_pTable->GetTitleCtrl())\n ++nCount;\n if(m_pTable->GetListBox())\n ++nCount;\n }\n return nCount;\n }\n \/\/ -----------------------------------------------------------------------------\n Reference< XAccessible > SAL_CALL OTableWindowAccess::getAccessibleChild( sal_Int32 i ) throw (IndexOutOfBoundsException,RuntimeException)\n {\n ::osl::MutexGuard aGuard( m_aMutex );\n Reference< XAccessible > aRet;\n if(m_pTable)\n {\n switch(i)\n {\n case 0:\n if(m_pTable->GetTitleCtrl())\n {\n aRet = m_pTable->GetTitleCtrl()->GetAccessible();\n break;\n } \/\/ fall through if title control does not exist\n case 1:\n if(m_pTable->GetListBox())\n aRet = m_pTable->GetListBox()->GetAccessible();\n break;\n default:\n throw IndexOutOfBoundsException();\n }\n }\n return aRet;\n }\n \/\/ -----------------------------------------------------------------------------\n sal_Int32 SAL_CALL OTableWindowAccess::getAccessibleIndexInParent( ) throw (RuntimeException)\n {\n ::osl::MutexGuard aGuard( m_aMutex );\n sal_Int32 nIndex = -1;\n if( m_pTable )\n {\n \/\/ search the postion of our table window in the table window map\n OJoinTableView::OTableWindowMap* pMap = m_pTable->getTableView()->GetTabWinMap();\n OJoinTableView::OTableWindowMap::iterator aIter = pMap->begin();\n for (nIndex = 0; aIter != pMap->end() && aIter->second != m_pTable; ++nIndex,++aIter)\n ;\n nIndex = aIter != pMap->end() ? nIndex : -1;\n }\n return nIndex;\n }\n \/\/ -----------------------------------------------------------------------------\n sal_Int16 SAL_CALL OTableWindowAccess::getAccessibleRole( ) throw (RuntimeException)\n {\n return AccessibleRole::PANEL; \/\/ ? or may be an AccessibleRole::WINDOW\n }\n \/\/ -----------------------------------------------------------------------------\n Reference< XAccessibleRelationSet > SAL_CALL OTableWindowAccess::getAccessibleRelationSet( ) throw (RuntimeException)\n {\n ::osl::MutexGuard aGuard( m_aMutex );\n return this;\n }\n \/\/ -----------------------------------------------------------------------------\n \/\/ XAccessibleComponent\n Reference< XAccessible > SAL_CALL OTableWindowAccess::getAccessibleAtPoint( const awt::Point& _aPoint ) throw (RuntimeException)\n {\n ::osl::MutexGuard aGuard( m_aMutex );\n Reference< XAccessible > aRet;\n if( m_pTable )\n {\n Point aPoint(_aPoint.X,_aPoint.Y);\n Rectangle aRect(m_pTable->GetDesktopRectPixel());\n if( aRect.IsInside(aPoint) )\n aRet = this;\n else if( m_pTable->GetListBox()->GetDesktopRectPixel().IsInside(aPoint))\n aRet = m_pTable->GetListBox()->GetAccessible();\n }\n return aRet;\n }\n \/\/ -----------------------------------------------------------------------------\n Reference< XAccessible > OTableWindowAccess::getParentChild(sal_Int32 _nIndex)\n {\n Reference< XAccessible > xReturn;\n Reference< XAccessible > xParent = getAccessibleParent();\n if ( xParent.is() )\n {\n Reference< XAccessibleContext > xParentContext = xParent->getAccessibleContext();\n if ( xParentContext.is() )\n {\n xReturn = xParentContext->getAccessibleChild(_nIndex);\n }\n }\n return xReturn;\n }\n \/\/ -----------------------------------------------------------------------------\n\n sal_Int32 SAL_CALL OTableWindowAccess::getRelationCount( ) throw (RuntimeException)\n {\n ::osl::MutexGuard aGuard( m_aMutex );\n return m_pTable ? m_pTable->getTableView()->getConnectionCount(m_pTable) : sal_Int32(0);\n }\n \/\/ -----------------------------------------------------------------------------\n AccessibleRelation SAL_CALL OTableWindowAccess::getRelation( sal_Int32 nIndex ) throw (IndexOutOfBoundsException, RuntimeException)\n {\n ::osl::MutexGuard aGuard( m_aMutex );\n if( nIndex < 0 || nIndex >= getRelationCount() )\n throw IndexOutOfBoundsException();\n\n AccessibleRelation aRet;\n if( m_pTable )\n {\n OJoinTableView* pView = m_pTable->getTableView();\n ::std::vector<OTableConnection*>::const_iterator aIter = pView->getTableConnections(m_pTable) + nIndex;\n aRet.TargetSet.realloc(1);\n aRet.TargetSet[0] = getParentChild(aIter - pView->getTableConnections()->begin());\n aRet.RelationType = AccessibleRelationType::CONTROLLER_FOR;\n }\n return aRet;\n }\n \/\/ -----------------------------------------------------------------------------\n sal_Bool SAL_CALL OTableWindowAccess::containsRelation( sal_Int16 aRelationType ) throw (RuntimeException)\n {\n ::osl::MutexGuard aGuard( m_aMutex );\n return AccessibleRelationType::CONTROLLER_FOR == aRelationType\n && m_pTable->getTableView()->ExistsAConn(m_pTable);\n }\n \/\/ -----------------------------------------------------------------------------\n AccessibleRelation SAL_CALL OTableWindowAccess::getRelationByType( sal_Int16 aRelationType ) throw (RuntimeException)\n {\n ::osl::MutexGuard aGuard( m_aMutex );\n if( AccessibleRelationType::CONTROLLER_FOR == aRelationType && m_pTable)\n {\n OJoinTableView* pView = m_pTable->getTableView();\n const ::std::vector<OTableConnection*>* pConnectionList = pView->getTableConnections();\n\n ::std::vector<OTableConnection*>::const_iterator aIter = pView->getTableConnections(m_pTable);\n ::std::vector< Reference<XInterface> > aRelations;\n aRelations.reserve(5); \/\/ just guessing\n for (; aIter != pConnectionList->end() ; ++aIter )\n aRelations.push_back(getParentChild(aIter - pConnectionList->begin()));\n\n Reference<XInterface> *pRelations = aRelations.empty() ? 0 : &aRelations[0];\n Sequence< Reference<XInterface> > aSeq(pRelations, aRelations.size());\n return AccessibleRelation(AccessibleRelationType::CONTROLLER_FOR,aSeq);\n }\n return AccessibleRelation();\n }\n \/\/ -----------------------------------------------------------------------------\n sal_Bool OTableWindowAccess::isEditable() const\n {\n return m_pTable && !m_pTable->getTableView()->getDesignView()->getController()->isReadOnly();\n }\n \/\/ -----------------------------------------------------------------------------\n ::rtl::OUString SAL_CALL OTableWindowAccess::getTitledBorderText( ) throw (RuntimeException)\n {\n return getAccessibleName( );\n }\n \/\/ -----------------------------------------------------------------------------\n ::rtl::OUString SAL_CALL OTableWindowAccess::getAccessibleName( ) throw (RuntimeException)\n {\n ::osl::MutexGuard aGuard( m_aMutex );\n ::rtl::OUString sAccessibleName;\n if ( m_pTable )\n sAccessibleName = m_pTable->getTitle();\n return sAccessibleName;\n }\n \/\/ -----------------------------------------------------------------------------\n Reference< XAccessibleContext > SAL_CALL OTableWindowAccess::getAccessibleContext( ) throw (::com::sun::star::uno::RuntimeException)\n {\n return this;\n }\n \/\/ -----------------------------------------------------------------------------\n\n}\n\/\/ -----------------------------------------------------------------------------\n\n<commit_msg>INTEGRATION: CWS dba30d (1.13.30); FILE MERGED 2008\/05\/29 11:30:22 fs 1.13.30.1: during #i80943#: refactoring: IController now passed around as reference, not as pointer<commit_after>\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2008 by Sun Microsystems, Inc.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: TableWindowAccess.cxx,v $\n * $Revision: 1.14 $\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * <http:\/\/www.openoffice.org\/license.html>\n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_dbaccess.hxx\"\n#ifndef DBACCESS_TABLEWINDOWACCESS_HXX\n#include \"TableWindowAccess.hxx\"\n#endif\n#ifndef DBACCESS_JACCESS_HXX\n#include \"JAccess.hxx\"\n#endif\n#ifndef DBAUI_TABLEWINDOW_HXX\n#include \"TableWindow.hxx\"\n#endif\n#ifndef DBAUI_TABLEWINDOWLISTBOX_HXX\n#include \"TableWindowListBox.hxx\"\n#endif\n#ifndef DBAUI_JOINDESIGNVIEW_HXX\n#include \"JoinDesignView.hxx\"\n#endif\n#ifndef DBAUI_JOINCONTROLLER_HXX\n#include \"JoinController.hxx\"\n#endif\n#ifndef DBAUI_JOINTABLEVIEW_HXX\n#include \"JoinTableView.hxx\"\n#endif\n#ifndef _COM_SUN_STAR_ACCESSIBILITY_ACCESSIBLEROLE_HPP_\n#include <com\/sun\/star\/accessibility\/AccessibleRole.hpp>\n#endif\n#ifndef _COM_SUN_STAR_ACCESSIBILITY_ACCESSIBLERELATIONTYPE_HPP_\n#include <com\/sun\/star\/accessibility\/AccessibleRelationType.hpp>\n#endif\n#ifndef _COM_SUN_STAR_ACCESSIBILITY_ACCESSIBLESTATETYPE_HPP_\n#include <com\/sun\/star\/accessibility\/AccessibleStateType.hpp>\n#endif\n#ifndef _COM_SUN_STAR_ACCESSIBILITY_ACCESSIBLEEVENTID_HPP_\n#include <com\/sun\/star\/accessibility\/AccessibleEventId.hpp>\n#endif\n#ifndef _COMPHELPER_SEQUENCE_HXX_\n#include <comphelper\/sequence.hxx>\n#endif\n#ifndef _DBU_QRY_HRC_\n#include \"dbu_qry.hrc\"\n#endif\n\n\nnamespace dbaui\n{\n using namespace ::com::sun::star::accessibility;\n using namespace ::com::sun::star::uno;\n using namespace ::com::sun::star::beans;\n using namespace ::com::sun::star::lang;\n \/\/ using namespace ::com::sun::star::awt;\n using namespace ::com::sun::star;\n\n OTableWindowAccess::OTableWindowAccess(OTableWindow* _pTable)\n :VCLXAccessibleComponent(_pTable->GetComponentInterface().is() ? _pTable->GetWindowPeer() : NULL)\n ,m_pTable(_pTable)\n {\n }\n \/\/ -----------------------------------------------------------------------------\n void SAL_CALL OTableWindowAccess::disposing()\n {\n m_pTable = NULL;\n VCLXAccessibleComponent::disposing();\n }\n \/\/ -----------------------------------------------------------------------------\n Any SAL_CALL OTableWindowAccess::queryInterface( const Type& aType ) throw (RuntimeException)\n {\n Any aRet(VCLXAccessibleComponent::queryInterface( aType ));\n return aRet.hasValue() ? aRet : OTableWindowAccess_BASE::queryInterface( aType );\n }\n \/\/ -----------------------------------------------------------------------------\n Sequence< Type > SAL_CALL OTableWindowAccess::getTypes( ) throw (RuntimeException)\n {\n return ::comphelper::concatSequences(VCLXAccessibleComponent::getTypes(),OTableWindowAccess_BASE::getTypes());\n }\n \/\/ -----------------------------------------------------------------------------\n ::rtl::OUString SAL_CALL OTableWindowAccess::getImplementationName() throw(RuntimeException)\n {\n return getImplementationName_Static();\n }\n \/\/ -----------------------------------------------------------------------------\n Sequence< ::rtl::OUString > SAL_CALL OTableWindowAccess::getSupportedServiceNames() throw(RuntimeException)\n {\n return getSupportedServiceNames_Static();\n }\n \/\/ -----------------------------------------------------------------------------\n \/\/ XServiceInfo - static methods\n Sequence< ::rtl::OUString > OTableWindowAccess::getSupportedServiceNames_Static(void) throw( RuntimeException )\n {\n Sequence< ::rtl::OUString > aSupported(2);\n aSupported[0] = ::rtl::OUString::createFromAscii(\"com.sun.star.accessibility.Accessible\");\n aSupported[1] = ::rtl::OUString::createFromAscii(\"com.sun.star.accessibility.AccessibleContext\");\n return aSupported;\n }\n \/\/ -----------------------------------------------------------------------------\n ::rtl::OUString OTableWindowAccess::getImplementationName_Static(void) throw( RuntimeException )\n {\n return ::rtl::OUString::createFromAscii(\"org.openoffice.comp.dbu.TableWindowAccessibility\");\n }\n \/\/ -----------------------------------------------------------------------------\n \/\/ XAccessibleContext\n sal_Int32 SAL_CALL OTableWindowAccess::getAccessibleChildCount( ) throw (RuntimeException)\n {\n ::osl::MutexGuard aGuard( m_aMutex );\n sal_Int32 nCount = 0;\n if(m_pTable)\n {\n if(m_pTable->GetTitleCtrl())\n ++nCount;\n if(m_pTable->GetListBox())\n ++nCount;\n }\n return nCount;\n }\n \/\/ -----------------------------------------------------------------------------\n Reference< XAccessible > SAL_CALL OTableWindowAccess::getAccessibleChild( sal_Int32 i ) throw (IndexOutOfBoundsException,RuntimeException)\n {\n ::osl::MutexGuard aGuard( m_aMutex );\n Reference< XAccessible > aRet;\n if(m_pTable)\n {\n switch(i)\n {\n case 0:\n if(m_pTable->GetTitleCtrl())\n {\n aRet = m_pTable->GetTitleCtrl()->GetAccessible();\n break;\n } \/\/ fall through if title control does not exist\n case 1:\n if(m_pTable->GetListBox())\n aRet = m_pTable->GetListBox()->GetAccessible();\n break;\n default:\n throw IndexOutOfBoundsException();\n }\n }\n return aRet;\n }\n \/\/ -----------------------------------------------------------------------------\n sal_Int32 SAL_CALL OTableWindowAccess::getAccessibleIndexInParent( ) throw (RuntimeException)\n {\n ::osl::MutexGuard aGuard( m_aMutex );\n sal_Int32 nIndex = -1;\n if( m_pTable )\n {\n \/\/ search the postion of our table window in the table window map\n OJoinTableView::OTableWindowMap* pMap = m_pTable->getTableView()->GetTabWinMap();\n OJoinTableView::OTableWindowMap::iterator aIter = pMap->begin();\n for (nIndex = 0; aIter != pMap->end() && aIter->second != m_pTable; ++nIndex,++aIter)\n ;\n nIndex = aIter != pMap->end() ? nIndex : -1;\n }\n return nIndex;\n }\n \/\/ -----------------------------------------------------------------------------\n sal_Int16 SAL_CALL OTableWindowAccess::getAccessibleRole( ) throw (RuntimeException)\n {\n return AccessibleRole::PANEL; \/\/ ? or may be an AccessibleRole::WINDOW\n }\n \/\/ -----------------------------------------------------------------------------\n Reference< XAccessibleRelationSet > SAL_CALL OTableWindowAccess::getAccessibleRelationSet( ) throw (RuntimeException)\n {\n ::osl::MutexGuard aGuard( m_aMutex );\n return this;\n }\n \/\/ -----------------------------------------------------------------------------\n \/\/ XAccessibleComponent\n Reference< XAccessible > SAL_CALL OTableWindowAccess::getAccessibleAtPoint( const awt::Point& _aPoint ) throw (RuntimeException)\n {\n ::osl::MutexGuard aGuard( m_aMutex );\n Reference< XAccessible > aRet;\n if( m_pTable )\n {\n Point aPoint(_aPoint.X,_aPoint.Y);\n Rectangle aRect(m_pTable->GetDesktopRectPixel());\n if( aRect.IsInside(aPoint) )\n aRet = this;\n else if( m_pTable->GetListBox()->GetDesktopRectPixel().IsInside(aPoint))\n aRet = m_pTable->GetListBox()->GetAccessible();\n }\n return aRet;\n }\n \/\/ -----------------------------------------------------------------------------\n Reference< XAccessible > OTableWindowAccess::getParentChild(sal_Int32 _nIndex)\n {\n Reference< XAccessible > xReturn;\n Reference< XAccessible > xParent = getAccessibleParent();\n if ( xParent.is() )\n {\n Reference< XAccessibleContext > xParentContext = xParent->getAccessibleContext();\n if ( xParentContext.is() )\n {\n xReturn = xParentContext->getAccessibleChild(_nIndex);\n }\n }\n return xReturn;\n }\n \/\/ -----------------------------------------------------------------------------\n\n sal_Int32 SAL_CALL OTableWindowAccess::getRelationCount( ) throw (RuntimeException)\n {\n ::osl::MutexGuard aGuard( m_aMutex );\n return m_pTable ? m_pTable->getTableView()->getConnectionCount(m_pTable) : sal_Int32(0);\n }\n \/\/ -----------------------------------------------------------------------------\n AccessibleRelation SAL_CALL OTableWindowAccess::getRelation( sal_Int32 nIndex ) throw (IndexOutOfBoundsException, RuntimeException)\n {\n ::osl::MutexGuard aGuard( m_aMutex );\n if( nIndex < 0 || nIndex >= getRelationCount() )\n throw IndexOutOfBoundsException();\n\n AccessibleRelation aRet;\n if( m_pTable )\n {\n OJoinTableView* pView = m_pTable->getTableView();\n ::std::vector<OTableConnection*>::const_iterator aIter = pView->getTableConnections(m_pTable) + nIndex;\n aRet.TargetSet.realloc(1);\n aRet.TargetSet[0] = getParentChild(aIter - pView->getTableConnections()->begin());\n aRet.RelationType = AccessibleRelationType::CONTROLLER_FOR;\n }\n return aRet;\n }\n \/\/ -----------------------------------------------------------------------------\n sal_Bool SAL_CALL OTableWindowAccess::containsRelation( sal_Int16 aRelationType ) throw (RuntimeException)\n {\n ::osl::MutexGuard aGuard( m_aMutex );\n return AccessibleRelationType::CONTROLLER_FOR == aRelationType\n && m_pTable->getTableView()->ExistsAConn(m_pTable);\n }\n \/\/ -----------------------------------------------------------------------------\n AccessibleRelation SAL_CALL OTableWindowAccess::getRelationByType( sal_Int16 aRelationType ) throw (RuntimeException)\n {\n ::osl::MutexGuard aGuard( m_aMutex );\n if( AccessibleRelationType::CONTROLLER_FOR == aRelationType && m_pTable)\n {\n OJoinTableView* pView = m_pTable->getTableView();\n const ::std::vector<OTableConnection*>* pConnectionList = pView->getTableConnections();\n\n ::std::vector<OTableConnection*>::const_iterator aIter = pView->getTableConnections(m_pTable);\n ::std::vector< Reference<XInterface> > aRelations;\n aRelations.reserve(5); \/\/ just guessing\n for (; aIter != pConnectionList->end() ; ++aIter )\n aRelations.push_back(getParentChild(aIter - pConnectionList->begin()));\n\n Reference<XInterface> *pRelations = aRelations.empty() ? 0 : &aRelations[0];\n Sequence< Reference<XInterface> > aSeq(pRelations, aRelations.size());\n return AccessibleRelation(AccessibleRelationType::CONTROLLER_FOR,aSeq);\n }\n return AccessibleRelation();\n }\n \/\/ -----------------------------------------------------------------------------\n sal_Bool OTableWindowAccess::isEditable() const\n {\n return m_pTable && !m_pTable->getTableView()->getDesignView()->getController().isReadOnly();\n }\n \/\/ -----------------------------------------------------------------------------\n ::rtl::OUString SAL_CALL OTableWindowAccess::getTitledBorderText( ) throw (RuntimeException)\n {\n return getAccessibleName( );\n }\n \/\/ -----------------------------------------------------------------------------\n ::rtl::OUString SAL_CALL OTableWindowAccess::getAccessibleName( ) throw (RuntimeException)\n {\n ::osl::MutexGuard aGuard( m_aMutex );\n ::rtl::OUString sAccessibleName;\n if ( m_pTable )\n sAccessibleName = m_pTable->getTitle();\n return sAccessibleName;\n }\n \/\/ -----------------------------------------------------------------------------\n Reference< XAccessibleContext > SAL_CALL OTableWindowAccess::getAccessibleContext( ) throw (::com::sun::star::uno::RuntimeException)\n {\n return this;\n }\n \/\/ -----------------------------------------------------------------------------\n\n}\n\/\/ -----------------------------------------------------------------------------\n\n<|endoftext|>"} {"text":"<commit_before>#include <silicium\/alignment_of.hpp>\n#include <silicium\/arithmetic\/add.hpp>\n#include <silicium\/arithmetic\/overflow_or.hpp>\n#include <silicium\/array_view.hpp>\n#include <silicium\/asio\/accepting_source.hpp>\n#include <silicium\/asio\/async.hpp>\n#include <silicium\/asio\/async_source.hpp>\n#include <silicium\/asio\/connecting_observable.hpp>\n#include <silicium\/asio\/connecting_source.hpp>\n#include <silicium\/asio\/post_forwarder.hpp>\n#include <silicium\/asio\/posting_observable.hpp>\n#include <silicium\/asio\/process_output.hpp>\n#include <silicium\/asio\/reading_observable.hpp>\n#include <silicium\/asio\/socket_sink.hpp>\n#include <silicium\/asio\/socket_source.hpp>\n#include <silicium\/asio\/tcp_acceptor.hpp>\n#include <silicium\/asio\/timer.hpp>\n#include <silicium\/asio\/use_observable.hpp>\n#include <silicium\/asio\/writing_observable.hpp>\n#include <silicium\/block_thread.hpp>\n#include <silicium\/boost_threading.hpp>\n#include <silicium\/bounded_int.hpp>\n#include <silicium\/buffer.hpp>\n#include <silicium\/byte.hpp>\n#include <silicium\/byte_order_intrinsics.hpp>\n#include <silicium\/c_string.hpp>\n#include <silicium\/config.hpp>\n#include <silicium\/detail\/argument_of.hpp>\n#include <silicium\/detail\/basic_dynamic_library.hpp>\n#include <silicium\/detail\/element_from_optional_like.hpp>\n#include <silicium\/detail\/integer_sequence.hpp>\n#include <silicium\/detail\/line_source.hpp>\n#include <silicium\/detail\/proper_value_function.hpp>\n#include <silicium\/dynamic_library.hpp>\n#include <silicium\/environment_variables.hpp>\n#include <silicium\/error_code.hpp>\n#include <silicium\/error_handler.hpp>\n#include <silicium\/error_or.hpp>\n#include <silicium\/exchange.hpp>\n#include <silicium\/expected.hpp>\n#include <silicium\/explicit_operator_bool.hpp>\n#include <silicium\/file_handle.hpp>\n#include <silicium\/function.hpp>\n#include <silicium\/future.hpp>\n#include <silicium\/get_last_error.hpp>\n#include <silicium\/html\/generator.hpp>\n#include <silicium\/html\/tree.hpp>\n#include <silicium\/http\/generate_header.hpp>\n#include <silicium\/http\/generate_request.hpp>\n#include <silicium\/http\/generate_response.hpp>\n#include <silicium\/http\/http.hpp>\n#include <silicium\/http\/parse_request.hpp>\n#include <silicium\/http\/parse_response.hpp>\n#include <silicium\/http\/receive_request.hpp>\n#include <silicium\/http\/request_parser_sink.hpp>\n#include <silicium\/http\/uri.hpp>\n#include <silicium\/identity.hpp>\n#include <silicium\/initialize_array.hpp>\n#include <silicium\/is_handle.hpp>\n#include <silicium\/iterator_range.hpp>\n#include <silicium\/make_array.hpp>\n#include <silicium\/make_destructor.hpp>\n#include <silicium\/memory_range.hpp>\n#include <silicium\/move.hpp>\n#include <silicium\/move_if_noexcept.hpp>\n#include <silicium\/native_file_descriptor.hpp>\n#include <silicium\/noexcept_string.hpp>\n#include <silicium\/null_mutex.hpp>\n#include <silicium\/observable\/bridge.hpp>\n#include <silicium\/observable\/cache.hpp>\n#include <silicium\/observable\/constant.hpp>\n#include <silicium\/observable\/consume.hpp>\n#include <silicium\/observable\/coroutine.hpp>\n#include <silicium\/observable\/coroutine_generator.hpp>\n#include <silicium\/observable\/deref_optional.hpp>\n#include <silicium\/observable\/empty.hpp>\n#include <silicium\/observable\/end.hpp>\n#include <silicium\/observable\/enumerate.hpp>\n#include <silicium\/observable\/erase_shared.hpp>\n#include <silicium\/observable\/erase_unique.hpp>\n#include <silicium\/observable\/erased_observer.hpp>\n#include <silicium\/observable\/error_or_enumerate.hpp>\n#include <silicium\/observable\/extensible_observer.hpp>\n#include <silicium\/observable\/filter.hpp>\n#include <silicium\/observable\/finite_state_machine.hpp>\n#include <silicium\/observable\/flatten.hpp>\n#include <silicium\/observable\/for_each.hpp>\n#include <silicium\/observable\/function.hpp>\n#include <silicium\/observable\/function_observer.hpp>\n#include <silicium\/observable\/generator.hpp>\n#include <silicium\/observable\/limited.hpp>\n#include <silicium\/observable\/observable.hpp>\n#include <silicium\/observable\/observer.hpp>\n#include <silicium\/observable\/on_first.hpp>\n#include <silicium\/observable\/ptr.hpp>\n#include <silicium\/observable\/ready_future.hpp>\n#include <silicium\/observable\/ref.hpp>\n#include <silicium\/observable\/source.hpp>\n#include <silicium\/observable\/spawn_coroutine.hpp>\n#include <silicium\/observable\/spawn_observable.hpp>\n#include <silicium\/observable\/take.hpp>\n#include <silicium\/observable\/thread.hpp>\n#include <silicium\/observable\/thread_generator.hpp>\n#include <silicium\/observable\/total_consumer.hpp>\n#include <silicium\/observable\/transform.hpp>\n#include <silicium\/observable\/transform_if_initialized.hpp>\n#include <silicium\/observable\/tuple.hpp>\n#include <silicium\/observable\/variant.hpp>\n#include <silicium\/observable\/virtualized.hpp>\n#include <silicium\/observable\/while.hpp>\n#include <silicium\/observable\/yield_context.hpp>\n#include <silicium\/observable2.hpp>\n#include <silicium\/optional.hpp>\n#include <silicium\/os_string.hpp>\n#include <silicium\/pipe.hpp>\n#include <silicium\/process_handle.hpp>\n#include <silicium\/program_options.hpp>\n#include <silicium\/ptr_adaptor.hpp>\n#include <silicium\/range_value.hpp>\n#include <silicium\/read_file.hpp>\n#include <silicium\/serialization.hpp>\n#include <silicium\/sink\/append.hpp>\n#include <silicium\/sink\/buffer.hpp>\n#include <silicium\/sink\/buffering_sink.hpp>\n#include <silicium\/sink\/container_buffer.hpp>\n#include <silicium\/sink\/copy.hpp>\n#include <silicium\/sink\/function_sink.hpp>\n#include <silicium\/sink\/iterator_sink.hpp>\n#include <silicium\/sink\/multi_sink.hpp>\n#include <silicium\/sink\/ostream_sink.hpp>\n#include <silicium\/sink\/ptr_sink.hpp>\n#include <silicium\/sink\/sink.hpp>\n#include <silicium\/sink\/throwing_sink.hpp>\n#include <silicium\/sink\/virtualized_sink.hpp>\n#include <silicium\/source\/buffering_source.hpp>\n#include <silicium\/source\/empty.hpp>\n#include <silicium\/source\/enumerating_source.hpp>\n#include <silicium\/source\/error_extracting_source.hpp>\n#include <silicium\/source\/filter_source.hpp>\n#include <silicium\/source\/generator_source.hpp>\n#include <silicium\/source\/memory_source.hpp>\n#include <silicium\/source\/observable_source.hpp>\n#include <silicium\/source\/ptr_source.hpp>\n#include <silicium\/source\/range_source.hpp>\n#include <silicium\/source\/received_from_socket_source.hpp>\n#include <silicium\/source\/single_source.hpp>\n#include <silicium\/source\/source.hpp>\n#include <silicium\/source\/throwing_source.hpp>\n#include <silicium\/source\/transforming_source.hpp>\n#include <silicium\/source\/virtualized_source.hpp>\n#include <silicium\/sqlite3.hpp>\n#include <silicium\/std_threading.hpp>\n#include <silicium\/steady_clock.hpp>\n#include <silicium\/success.hpp>\n#include <silicium\/terminate_on_exception.hpp>\n#include <silicium\/then.hpp>\n#include <silicium\/throw_last_error.hpp>\n#include <silicium\/to_shared.hpp>\n#include <silicium\/to_unique.hpp>\n#include <silicium\/trait.hpp>\n#include <silicium\/type_traits.hpp>\n#include <silicium\/utility.hpp>\n#include <silicium\/variant.hpp>\n#include <silicium\/vector.hpp>\n#include <silicium\/version.hpp>\n#include <silicium\/win32\/dynamic_library_impl.hpp>\n#include <silicium\/win32\/process_handle.hpp>\n#include <silicium\/win32\/win32.hpp>\n#include <silicium\/write.hpp>\n#include <silicium\/zlib\/deflating_sink.hpp>\n#include <silicium\/zlib\/inflating_sink.hpp>\n#include <silicium\/zlib\/zlib.hpp>\n<commit_msg>update Win32 #include test<commit_after>#include <silicium\/alignment_of.hpp>\n#include <silicium\/arithmetic\/add.hpp>\n#include <silicium\/arithmetic\/overflow_or.hpp>\n#include <silicium\/array_view.hpp>\n#include <silicium\/asio\/accepting_source.hpp>\n#include <silicium\/asio\/async.hpp>\n#include <silicium\/asio\/async_source.hpp>\n#include <silicium\/asio\/connecting_observable.hpp>\n#include <silicium\/asio\/connecting_source.hpp>\n#include <silicium\/asio\/post_forwarder.hpp>\n#include <silicium\/asio\/posting_observable.hpp>\n#include <silicium\/asio\/process_output.hpp>\n#include <silicium\/asio\/reading_observable.hpp>\n#include <silicium\/asio\/socket_sink.hpp>\n#include <silicium\/asio\/socket_source.hpp>\n#include <silicium\/asio\/tcp_acceptor.hpp>\n#include <silicium\/asio\/timer.hpp>\n#include <silicium\/asio\/use_observable.hpp>\n#include <silicium\/asio\/writing_observable.hpp>\n#include <silicium\/block_thread.hpp>\n#include <silicium\/boost_threading.hpp>\n#include <silicium\/bounded_int.hpp>\n#include <silicium\/buffer.hpp>\n#include <silicium\/byte.hpp>\n#include <silicium\/byte_order_intrinsics.hpp>\n#include <silicium\/c_string.hpp>\n#include <silicium\/config.hpp>\n#include <silicium\/detail\/argument_of.hpp>\n#include <silicium\/detail\/basic_dynamic_library.hpp>\n#include <silicium\/detail\/element_from_optional_like.hpp>\n#include <silicium\/detail\/integer_sequence.hpp>\n#include <silicium\/detail\/line_source.hpp>\n#include <silicium\/detail\/proper_value_function.hpp>\n#include <silicium\/dynamic_library.hpp>\n#include <silicium\/environment_variables.hpp>\n#include <silicium\/error_code.hpp>\n#include <silicium\/error_handler.hpp>\n#include <silicium\/error_or.hpp>\n#include <silicium\/exchange.hpp>\n#include <silicium\/expected.hpp>\n#include <silicium\/explicit_operator_bool.hpp>\n#include <silicium\/file_handle.hpp>\n#include <silicium\/function.hpp>\n#include <silicium\/future.hpp>\n#include <silicium\/get_last_error.hpp>\n#include <silicium\/html\/generator.hpp>\n#include <silicium\/html\/tree.hpp>\n#include <silicium\/http\/generate_header.hpp>\n#include <silicium\/http\/generate_request.hpp>\n#include <silicium\/http\/generate_response.hpp>\n#include <silicium\/http\/http.hpp>\n#include <silicium\/http\/parse_request.hpp>\n#include <silicium\/http\/parse_response.hpp>\n#include <silicium\/http\/receive_request.hpp>\n#include <silicium\/http\/request_parser_sink.hpp>\n#include <silicium\/http\/uri.hpp>\n#include <silicium\/identity.hpp>\n#include <silicium\/initialize_array.hpp>\n#include <silicium\/is_handle.hpp>\n#include <silicium\/iterator_range.hpp>\n#include <silicium\/make_array.hpp>\n#include <silicium\/make_destructor.hpp>\n#include <silicium\/memory_range.hpp>\n#include <silicium\/move.hpp>\n#include <silicium\/move_if_noexcept.hpp>\n#include <silicium\/native_file_descriptor.hpp>\n#include <silicium\/noexcept_string.hpp>\n#include <silicium\/null_mutex.hpp>\n#include <silicium\/observable\/bridge.hpp>\n#include <silicium\/observable\/cache.hpp>\n#include <silicium\/observable\/constant.hpp>\n#include <silicium\/observable\/consume.hpp>\n#include <silicium\/observable\/coroutine.hpp>\n#include <silicium\/observable\/coroutine_generator.hpp>\n#include <silicium\/observable\/deref_optional.hpp>\n#include <silicium\/observable\/empty.hpp>\n#include <silicium\/observable\/end.hpp>\n#include <silicium\/observable\/enumerate.hpp>\n#include <silicium\/observable\/erase_shared.hpp>\n#include <silicium\/observable\/erase_unique.hpp>\n#include <silicium\/observable\/erased_observer.hpp>\n#include <silicium\/observable\/error_or_enumerate.hpp>\n#include <silicium\/observable\/extensible_observer.hpp>\n#include <silicium\/observable\/filter.hpp>\n#include <silicium\/observable\/finite_state_machine.hpp>\n#include <silicium\/observable\/flatten.hpp>\n#include <silicium\/observable\/for_each.hpp>\n#include <silicium\/observable\/function.hpp>\n#include <silicium\/observable\/function_observer.hpp>\n#include <silicium\/observable\/generator.hpp>\n#include <silicium\/observable\/limited.hpp>\n#include <silicium\/observable\/observable.hpp>\n#include <silicium\/observable\/observer.hpp>\n#include <silicium\/observable\/on_first.hpp>\n#include <silicium\/observable\/ptr.hpp>\n#include <silicium\/observable\/ready_future.hpp>\n#include <silicium\/observable\/ref.hpp>\n#include <silicium\/observable\/source.hpp>\n#include <silicium\/observable\/spawn_coroutine.hpp>\n#include <silicium\/observable\/spawn_observable.hpp>\n#include <silicium\/observable\/take.hpp>\n#include <silicium\/observable\/thread.hpp>\n#include <silicium\/observable\/thread_generator.hpp>\n#include <silicium\/observable\/total_consumer.hpp>\n#include <silicium\/observable\/transform.hpp>\n#include <silicium\/observable\/transform_if_initialized.hpp>\n#include <silicium\/observable\/tuple.hpp>\n#include <silicium\/observable\/variant.hpp>\n#include <silicium\/observable\/virtualized.hpp>\n#include <silicium\/observable\/while.hpp>\n#include <silicium\/observable\/yield_context.hpp>\n#include <silicium\/observable2.hpp>\n#include <silicium\/optional.hpp>\n#include <silicium\/os_string.hpp>\n#include <silicium\/pipe.hpp>\n#include <silicium\/process_handle.hpp>\n#include <silicium\/program_options.hpp>\n#include <silicium\/ptr_adaptor.hpp>\n#include <silicium\/range_value.hpp>\n#include <silicium\/read_file.hpp>\n#include <silicium\/serialization.hpp>\n#include <silicium\/sink\/append.hpp>\n#include <silicium\/sink\/buffer.hpp>\n#include <silicium\/sink\/buffering_sink.hpp>\n#include <silicium\/sink\/container_buffer.hpp>\n#include <silicium\/sink\/copy.hpp>\n#include <silicium\/sink\/function_sink.hpp>\n#include <silicium\/sink\/iterator_sink.hpp>\n#include <silicium\/sink\/multi_sink.hpp>\n#include <silicium\/sink\/ostream_sink.hpp>\n#include <silicium\/sink\/ptr_sink.hpp>\n#include <silicium\/sink\/sink.hpp>\n#include <silicium\/sink\/throwing_sink.hpp>\n#include <silicium\/sink\/virtualized_sink.hpp>\n#include <silicium\/source\/buffering_source.hpp>\n#include <silicium\/source\/empty.hpp>\n#include <silicium\/source\/enumerating_source.hpp>\n#include <silicium\/source\/error_extracting_source.hpp>\n#include <silicium\/source\/filter_source.hpp>\n#include <silicium\/source\/generator_source.hpp>\n#include <silicium\/source\/memory_source.hpp>\n#include <silicium\/source\/observable_source.hpp>\n#include <silicium\/source\/ptr_source.hpp>\n#include <silicium\/source\/range_source.hpp>\n#include <silicium\/source\/received_from_socket_source.hpp>\n#include <silicium\/source\/single_source.hpp>\n#include <silicium\/source\/source.hpp>\n#include <silicium\/source\/throwing_source.hpp>\n#include <silicium\/source\/transforming_source.hpp>\n#include <silicium\/source\/virtualized_source.hpp>\n#include <silicium\/std_threading.hpp>\n#include <silicium\/steady_clock.hpp>\n#include <silicium\/success.hpp>\n#include <silicium\/terminate_on_exception.hpp>\n#include <silicium\/then.hpp>\n#include <silicium\/throw_last_error.hpp>\n#include <silicium\/to_shared.hpp>\n#include <silicium\/to_unique.hpp>\n#include <silicium\/trait.hpp>\n#include <silicium\/type_traits.hpp>\n#include <silicium\/utility.hpp>\n#include <silicium\/variant.hpp>\n#include <silicium\/vector.hpp>\n#include <silicium\/version.hpp>\n#include <silicium\/win32\/dynamic_library_impl.hpp>\n#include <silicium\/win32\/process_handle.hpp>\n#include <silicium\/win32\/win32.hpp>\n#include <silicium\/write.hpp>\n#include <silicium\/zlib\/deflating_sink.hpp>\n#include <silicium\/zlib\/inflating_sink.hpp>\n#include <silicium\/zlib\/zlib.hpp>\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2007, 2008 libmv authors.\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to\n\/\/ deal in the Software without restriction, including without limitation the\n\/\/ rights to use, copy, modify, merge, publish, distribute, sublicense, and\/or\n\/\/ sell copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n\/\/ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n\/\/ IN THE SOFTWARE.\n\n#include <cmath>\n\n#include \"libmv\/image\/image.h\"\n#include \"libmv\/image\/convolve.h\"\n\nnamespace libmv {\n\n\/\/ Zero mean Gaussian.\ndouble Gaussian(double x, double sigma) {\n return 1\/sqrt(2*M_PI*sigma*sigma) * exp(-(x*x\/2\/sigma\/sigma));\n}\ndouble GaussianDerivative(double x, double sigma) {\n return -x \/ sigma \/ sigma * Gaussian(x, sigma);\n}\n\/\/ Solve the inverse of the Gaussian for positive x.\ndouble GaussianInversePositive(double y, double sigma) {\n return sqrt(-2 * sigma * sigma * log(y * sigma * sqrt(2*M_PI)));\n}\n\n\/\/ Compute a Gaussian kernel and derivative, such that you can take the\n\/\/ derivitave of an image by convolving with the kernel horizontally then the\n\/\/ derivative vertically to get (eg) the y derivative.\nvoid ComputeGaussianKernel(double sigma, Vec *kernel, Vec *derivative) {\n assert(sigma >= 0.0);\n\n \/\/ 0.004 implies a 3 pixel kernel with 1 pixel sigma.\n const float truncation_factor = 0.004f;\n\n \/\/ Calculate the kernel size based on sigma such that it is odd.\n float precisehalfwidth = GaussianInversePositive(truncation_factor, sigma);\n int width = lround(2*precisehalfwidth);\n if (width % 2 == 0) {\n width++;\n }\n \/\/ Calculate the gaussian kernel and its derivative.\n kernel->resize(width);\n derivative->resize(width);\n *kernel = 0.0;\n *derivative = 0.0;\n int halfwidth = width \/ 2;\n for (int i = -halfwidth; i <= halfwidth; ++i) {\n (*kernel)(i + halfwidth) = Gaussian(i, sigma);\n (*derivative)(i + halfwidth) = GaussianDerivative(i, sigma);\n }\n \/\/ Since images should not get brighter or darker, normalize.\n NormalizeL1(kernel);\n \/\/ Normalize the derivative differently. See\n \/\/ www.cs.duke.edu\/courses\/spring03\/cps296.1\/handouts\/Image%20Processing.pdf\n double factor = 0.;\n for (int i = -halfwidth; i <= halfwidth; ++i) {\n factor -= i*(*derivative)(i+halfwidth);\n }\n *derivative \/= factor;\n}\n\nvoid ConvolveHorizontal(const Array3Df &in,\n const Vec &kernel,\n Array3Df *out_pointer,\n int plane) {\n int halfwidth = kernel.length() \/ 2;\n int num_columns = in.Width();\n int num_rows = in.Height();\n Array3Df &out = *out_pointer;\n if (plane == -1) {\n out.ResizeLike(in);\n plane = 0;\n }\n\n assert(kernel.length() % 2 == 1);\n assert(&in != out_pointer);\n\n for (int j = 0; j < num_rows; ++j) {\n for (int i = 0; i < num_columns; ++i) {\n double sum = 0.0;\n int l = 0;\n for (int k = kernel.length()-1; k >= 0; --k, ++l) {\n int ii = i - halfwidth + l;\n if (0 <= ii && ii < num_columns) {\n sum += in(j, ii) * kernel(k);\n }\n }\n out(j, i, plane) = sum;\n }\n }\n}\n\n\/\/ This could certainly be accelerated.\nvoid ConvolveVertical(const Array3Df &in,\n const Vec &kernel,\n Array3Df *out_pointer,\n int plane) {\n int halfwidth = kernel.length() \/ 2;\n int num_columns = in.Width();\n int num_rows = in.Height();\n Array3Df &out = *out_pointer;\n if (plane == -1) {\n out.ResizeLike(in);\n plane = 0;\n }\n\n assert(kernel.length() % 2 == 1);\n assert(&in != out_pointer);\n\n for (int i = 0; i < num_columns; ++i) {\n for (int j = 0; j < num_rows; ++j) {\n double sum = 0.0;\n int l = 0;\n for (int k = kernel.length()-1; k >= 0; --k, ++l) {\n int jj = j - halfwidth + l;\n if (0 <= jj && jj < num_rows) {\n sum += in(jj, i) * kernel(k);\n }\n }\n out(j, i, plane) = sum;\n }\n }\n}\n\nvoid ConvolveGaussian(const Array3Df &in,\n double sigma,\n Array3Df *out_pointer) {\n Vec kernel, derivative;\n ComputeGaussianKernel(sigma, &kernel, &derivative);\n\n Array3Df tmp;\n ConvolveVertical(in, kernel, &tmp);\n ConvolveHorizontal(tmp, kernel, out_pointer);\n}\n\nvoid BlurredImageAndDerivatives(const Array3Df &in,\n double sigma,\n Array3Df *blurred_image,\n Array3Df *gradient_x,\n Array3Df *gradient_y) {\n Vec kernel, derivative;\n ComputeGaussianKernel(sigma, &kernel, &derivative);\n Array3Df tmp;\n\n \/\/ Compute convolved image.\n ConvolveVertical(in, kernel, &tmp);\n ConvolveHorizontal(tmp, kernel, blurred_image);\n\n \/\/ Compute first derivative in x.\n ConvolveHorizontal(tmp, derivative, gradient_x);\n\n \/\/ Compute first derivative in y.\n ConvolveHorizontal(in, kernel, &tmp);\n ConvolveVertical(tmp, derivative, gradient_y);\n}\n\n\/\/ Compute the gaussian blur of an image and the derivatives of the blurred\n\/\/ image, and store the results in three channels. Since the blurred value and\n\/\/ gradients are closer in memory, this leads to better performance if all\n\/\/ three values are needed at the same time.\nvoid BlurredImageAndDerivativesChannels(const Array3Df &in,\n double sigma,\n Array3Df *blurred_and_gradxy) {\n assert(in.Depth() == 1);\n\n Vec kernel, derivative;\n ComputeGaussianKernel(sigma, &kernel, &derivative);\n\n \/\/ Compute convolved image.\n Array3Df tmp;\n ConvolveVertical(in, kernel, &tmp);\n blurred_and_gradxy->Resize(in.Height(), in.Width(), 3);\n ConvolveHorizontal(tmp, kernel, blurred_and_gradxy, 0);\n\n \/\/ Compute first derivative in x.\n ConvolveHorizontal(tmp, derivative, blurred_and_gradxy, 1);\n\n \/\/ Compute first derivative in y.\n ConvolveHorizontal(in, kernel, &tmp);\n ConvolveVertical(tmp, derivative, blurred_and_gradxy, 2);\n}\n\nvoid BoxFilterHorizontal(const Array3Df &in,\n int window_size,\n Array3Df *out_pointer) {\n Array3Df &out = *out_pointer;\n out.ResizeLike(in);\n int half_width = (window_size - 1) \/ 2;\n\n for (int k = 0; k < in.Depth(); ++k) {\n for (int i=0; i<in.Height(); ++i) {\n float sum = 0;\n \/\/ Init sum.\n for (int j=0; j<half_width; ++j) {\n sum += in(i, j, k);\n }\n \/\/ Fill left border.\n for (int j=0; j < half_width + 1; ++j) {\n sum += in(i, j + half_width, k);\n out(i, j, k) = sum;\n }\n \/\/ Fill interior.\n for (int j = half_width + 1; j<in.Width()-half_width; ++j) {\n sum -= in(i, j - half_width - 1, k);\n sum += in(i, j + half_width, k);\n out(i, j, k) = sum;\n }\n \/\/ Fill right border.\n for (int j = in.Width() - half_width; j<in.Width(); ++j) {\n sum -= in(i, j - half_width - 1, k);\n out(i, j, k) = sum;\n }\n }\n }\n}\n\nvoid BoxFilterVertical(const Array3Df &in,\n int window_size,\n Array3Df *out_pointer) {\n Array3Df &out = *out_pointer;\n out.ResizeLike(in);\n int half_width = (window_size - 1) \/ 2;\n\n for (int k = 0; k < in.Depth(); ++k) {\n for (int j = 0; j < in.Width(); ++j) {\n float sum = 0;\n \/\/ Init sum.\n for (int i=0; i<half_width; ++i) {\n sum += in(i, j, k);\n }\n \/\/ Fill left border.\n for (int i=0; i < half_width + 1; ++i) {\n sum += in(i + half_width, j, k);\n out(i, j, k) = sum;\n }\n \/\/ Fill interior.\n for (int i = half_width + 1; i<in.Height()-half_width; ++i) {\n sum -= in(i - half_width - 1, j, k);\n sum += in(i + half_width, j, k);\n out(i, j, k) = sum;\n }\n \/\/ Fill right border.\n for (int i = in.Height() - half_width; i<in.Height(); ++i) {\n sum -= in(i - half_width - 1, j, k);\n out(i, j, k) = sum;\n }\n }\n }\n}\n\nvoid BoxFilter(const Array3Df &in,\n int box_width,\n Array3Df *out) {\n Array3Df tmp;\n BoxFilterHorizontal(in, box_width, &tmp);\n BoxFilterVertical(tmp, box_width, out);\n};\n\n} \/\/ namespace libmv\n<commit_msg>Start switching to row, column notation.<commit_after>\/\/ Copyright (c) 2007, 2008 libmv authors.\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to\n\/\/ deal in the Software without restriction, including without limitation the\n\/\/ rights to use, copy, modify, merge, publish, distribute, sublicense, and\/or\n\/\/ sell copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n\/\/ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n\/\/ IN THE SOFTWARE.\n\n#include <cmath>\n\n#include \"libmv\/image\/image.h\"\n#include \"libmv\/image\/convolve.h\"\n\nnamespace libmv {\n\n\/\/ Zero mean Gaussian.\ndouble Gaussian(double x, double sigma) {\n return 1\/sqrt(2*M_PI*sigma*sigma) * exp(-(x*x\/2\/sigma\/sigma));\n}\ndouble GaussianDerivative(double x, double sigma) {\n return -x \/ sigma \/ sigma * Gaussian(x, sigma);\n}\n\/\/ Solve the inverse of the Gaussian for positive x.\ndouble GaussianInversePositive(double y, double sigma) {\n return sqrt(-2 * sigma * sigma * log(y * sigma * sqrt(2*M_PI)));\n}\n\n\/\/ Compute a Gaussian kernel and derivative, such that you can take the\n\/\/ derivitave of an image by convolving with the kernel horizontally then the\n\/\/ derivative vertically to get (eg) the y derivative.\nvoid ComputeGaussianKernel(double sigma, Vec *kernel, Vec *derivative) {\n assert(sigma >= 0.0);\n\n \/\/ 0.004 implies a 3 pixel kernel with 1 pixel sigma.\n const float truncation_factor = 0.004f;\n\n \/\/ Calculate the kernel size based on sigma such that it is odd.\n float precisehalfwidth = GaussianInversePositive(truncation_factor, sigma);\n int width = lround(2*precisehalfwidth);\n if (width % 2 == 0) {\n width++;\n }\n \/\/ Calculate the gaussian kernel and its derivative.\n kernel->resize(width);\n derivative->resize(width);\n *kernel = 0.0;\n *derivative = 0.0;\n int halfwidth = width \/ 2;\n for (int i = -halfwidth; i <= halfwidth; ++i) {\n (*kernel)(i + halfwidth) = Gaussian(i, sigma);\n (*derivative)(i + halfwidth) = GaussianDerivative(i, sigma);\n }\n \/\/ Since images should not get brighter or darker, normalize.\n NormalizeL1(kernel);\n \/\/ Normalize the derivative differently. See\n \/\/ www.cs.duke.edu\/courses\/spring03\/cps296.1\/handouts\/Image%20Processing.pdf\n double factor = 0.;\n for (int i = -halfwidth; i <= halfwidth; ++i) {\n factor -= i*(*derivative)(i+halfwidth);\n }\n *derivative \/= factor;\n}\n\nvoid ConvolveHorizontal(const Array3Df &in,\n const Vec &kernel,\n Array3Df *out_pointer,\n int plane) {\n int halfwidth = kernel.length() \/ 2;\n int num_columns = in.Width();\n int num_rows = in.Height();\n Array3Df &out = *out_pointer;\n if (plane == -1) {\n out.ResizeLike(in);\n plane = 0;\n }\n\n assert(kernel.length() % 2 == 1);\n assert(&in != out_pointer);\n\n for (int r = 0; r < num_rows; ++r) {\n for (int c = 0; c < num_columns; ++c) {\n double sum = 0.0;\n int l = 0;\n for (int k = kernel.length() - 1; k >= 0; --k, ++l) {\n int cc = c - halfwidth + l;\n if (0 <= cc && cc < num_columns) {\n sum += in(r, cc) * kernel(k);\n }\n }\n out(r, c, plane) = sum;\n }\n }\n}\n\n\/\/ This could certainly be accelerated.\nvoid ConvolveVertical(const Array3Df &in,\n const Vec &kernel,\n Array3Df *out_pointer,\n int plane) {\n int halfwidth = kernel.length() \/ 2;\n int num_columns = in.Width();\n int num_rows = in.Height();\n Array3Df &out = *out_pointer;\n if (plane == -1) {\n out.ResizeLike(in);\n plane = 0;\n }\n\n assert(kernel.length() % 2 == 1);\n assert(&in != out_pointer);\n\n for (int i = 0; i < num_columns; ++i) {\n for (int j = 0; j < num_rows; ++j) {\n double sum = 0.0;\n int l = 0;\n for (int k = kernel.length()-1; k >= 0; --k, ++l) {\n int jj = j - halfwidth + l;\n if (0 <= jj && jj < num_rows) {\n sum += in(jj, i) * kernel(k);\n }\n }\n out(j, i, plane) = sum;\n }\n }\n}\n\nvoid ConvolveGaussian(const Array3Df &in,\n double sigma,\n Array3Df *out_pointer) {\n Vec kernel, derivative;\n ComputeGaussianKernel(sigma, &kernel, &derivative);\n\n Array3Df tmp;\n ConvolveVertical(in, kernel, &tmp);\n ConvolveHorizontal(tmp, kernel, out_pointer);\n}\n\nvoid BlurredImageAndDerivatives(const Array3Df &in,\n double sigma,\n Array3Df *blurred_image,\n Array3Df *gradient_x,\n Array3Df *gradient_y) {\n Vec kernel, derivative;\n ComputeGaussianKernel(sigma, &kernel, &derivative);\n Array3Df tmp;\n\n \/\/ Compute convolved image.\n ConvolveVertical(in, kernel, &tmp);\n ConvolveHorizontal(tmp, kernel, blurred_image);\n\n \/\/ Compute first derivative in x.\n ConvolveHorizontal(tmp, derivative, gradient_x);\n\n \/\/ Compute first derivative in y.\n ConvolveHorizontal(in, kernel, &tmp);\n ConvolveVertical(tmp, derivative, gradient_y);\n}\n\n\/\/ Compute the gaussian blur of an image and the derivatives of the blurred\n\/\/ image, and store the results in three channels. Since the blurred value and\n\/\/ gradients are closer in memory, this leads to better performance if all\n\/\/ three values are needed at the same time.\nvoid BlurredImageAndDerivativesChannels(const Array3Df &in,\n double sigma,\n Array3Df *blurred_and_gradxy) {\n assert(in.Depth() == 1);\n\n Vec kernel, derivative;\n ComputeGaussianKernel(sigma, &kernel, &derivative);\n\n \/\/ Compute convolved image.\n Array3Df tmp;\n ConvolveVertical(in, kernel, &tmp);\n blurred_and_gradxy->Resize(in.Height(), in.Width(), 3);\n ConvolveHorizontal(tmp, kernel, blurred_and_gradxy, 0);\n\n \/\/ Compute first derivative in x.\n ConvolveHorizontal(tmp, derivative, blurred_and_gradxy, 1);\n\n \/\/ Compute first derivative in y.\n ConvolveHorizontal(in, kernel, &tmp);\n ConvolveVertical(tmp, derivative, blurred_and_gradxy, 2);\n}\n\nvoid BoxFilterHorizontal(const Array3Df &in,\n int window_size,\n Array3Df *out_pointer) {\n Array3Df &out = *out_pointer;\n out.ResizeLike(in);\n int half_width = (window_size - 1) \/ 2;\n\n for (int k = 0; k < in.Depth(); ++k) {\n for (int i=0; i<in.Height(); ++i) {\n float sum = 0;\n \/\/ Init sum.\n for (int j=0; j<half_width; ++j) {\n sum += in(i, j, k);\n }\n \/\/ Fill left border.\n for (int j=0; j < half_width + 1; ++j) {\n sum += in(i, j + half_width, k);\n out(i, j, k) = sum;\n }\n \/\/ Fill interior.\n for (int j = half_width + 1; j<in.Width()-half_width; ++j) {\n sum -= in(i, j - half_width - 1, k);\n sum += in(i, j + half_width, k);\n out(i, j, k) = sum;\n }\n \/\/ Fill right border.\n for (int j = in.Width() - half_width; j<in.Width(); ++j) {\n sum -= in(i, j - half_width - 1, k);\n out(i, j, k) = sum;\n }\n }\n }\n}\n\nvoid BoxFilterVertical(const Array3Df &in,\n int window_size,\n Array3Df *out_pointer) {\n Array3Df &out = *out_pointer;\n out.ResizeLike(in);\n int half_width = (window_size - 1) \/ 2;\n\n for (int k = 0; k < in.Depth(); ++k) {\n for (int j = 0; j < in.Width(); ++j) {\n float sum = 0;\n \/\/ Init sum.\n for (int i=0; i<half_width; ++i) {\n sum += in(i, j, k);\n }\n \/\/ Fill left border.\n for (int i=0; i < half_width + 1; ++i) {\n sum += in(i + half_width, j, k);\n out(i, j, k) = sum;\n }\n \/\/ Fill interior.\n for (int i = half_width + 1; i<in.Height()-half_width; ++i) {\n sum -= in(i - half_width - 1, j, k);\n sum += in(i + half_width, j, k);\n out(i, j, k) = sum;\n }\n \/\/ Fill right border.\n for (int i = in.Height() - half_width; i<in.Height(); ++i) {\n sum -= in(i - half_width - 1, j, k);\n out(i, j, k) = sum;\n }\n }\n }\n}\n\nvoid BoxFilter(const Array3Df &in,\n int box_width,\n Array3Df *out) {\n Array3Df tmp;\n BoxFilterHorizontal(in, box_width, &tmp);\n BoxFilterVertical(tmp, box_width, out);\n};\n\n} \/\/ namespace libmv\n<|endoftext|>"} {"text":"<commit_before>\/**************************************************************************************\/\r\n\/* *\/\r\n\/* Visualization Library *\/\r\n\/* http:\/\/www.visualizationlibrary.com *\/\r\n\/* *\/\r\n\/* Copyright (c) 2005-2010, Michele Bosi *\/\r\n\/* All rights reserved. *\/\r\n\/* *\/\r\n\/* Redistribution and use in source and binary forms, with or without modification, *\/\r\n\/* are permitted provided that the following conditions are met: *\/\r\n\/* *\/\r\n\/* - Redistributions of source code must retain the above copyright notice, this *\/\r\n\/* list of conditions and the following disclaimer. *\/\r\n\/* *\/\r\n\/* - Redistributions in binary form must reproduce the above copyright notice, this *\/\r\n\/* list of conditions and the following disclaimer in the documentation and\/or *\/\r\n\/* other materials provided with the distribution. *\/\r\n\/* *\/\r\n\/* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND *\/\r\n\/* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED *\/\r\n\/* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE *\/\r\n\/* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR *\/\r\n\/* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES *\/\r\n\/* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; *\/\r\n\/* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON *\/\r\n\/* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT *\/\r\n\/* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS *\/\r\n\/* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *\/\r\n\/* *\/\r\n\/**************************************************************************************\/\r\n\r\n#ifndef MultiDrawElements_INCLUDE_ONCE\r\n#define MultiDrawElements_INCLUDE_ONCE\r\n\r\n#include <vl\/Primitives.hpp>\r\n#include <vl\/Array.hpp>\r\n#include <vl\/Log.hpp>\r\n#include <vl\/Say.hpp>\r\n#include <algorithm>\r\n\r\nnamespace vl\r\n{\r\n \/\/------------------------------------------------------------------------------\r\n \/\/ MultiDrawElements\r\n \/\/------------------------------------------------------------------------------\r\n \/** \r\n * Wrapper for the OpenGL function glMultiDrawElements(), see also http:\/\/www.opengl.org\/sdk\/docs\/man\/xhtml\/glMultiDrawElements.xml for more information.\r\n *\r\n *\/\r\n template <typename index_type, GLenum Tgltype, class arr_type>\r\n class MultiDrawElements: public Primitives\r\n {\r\n public:\r\n virtual const char* className() { return \"MultiDrawElements\"; }\r\n\r\n MultiDrawElements(EPrimitiveType primitive = PT_TRIANGLES)\r\n {\r\n #ifndef NDEBUG\r\n mObjectName = className();\r\n #endif\r\n mType = primitive;\r\n mIndexBuffer = new arr_type;\r\n mPrimitiveRestartIndex = ~(index_type)0;\r\n mPrimitiveRestartEnabled = false;\r\n }\r\n\r\n MultiDrawElements& operator=(const MultiDrawElements& other)\r\n {\r\n Primitives::operator=(other);\r\n *indices() = *other.indices();\r\n mPrimitiveRestartEnabled = other.mPrimitiveRestartEnabled;\r\n mPrimitiveRestartIndex = other.mPrimitiveRestartIndex;\r\n setCountVector(other.mCountVector);\r\n return *this;\r\n }\r\n\r\n virtual ref<Primitives> clone() const \r\n { \r\n ref<MultiDrawElements> de = new MultiDrawElements;\r\n *de = *this;\r\n return de;\r\n }\r\n\r\n virtual unsigned int handle() const { return indices()->gpuBuffer()->handle(); }\r\n\r\n virtual size_t indexCount() const { return indices()->size(); }\r\n\r\n virtual size_t indexCountGPU() const { return indices()->sizeGPU(); }\r\n\r\n virtual size_t index(int i) const { return (int)indices()->at(i); }\r\n\r\n arr_type* indices() { return mIndexBuffer.get(); }\r\n const arr_type* indices() const { return mIndexBuffer.get(); }\r\n\r\n virtual void updateVBOs(bool discard_local_data = false)\r\n {\r\n indices()->updateVBO(discard_local_data);\r\n }\r\n\r\n virtual void deleteVBOs()\r\n {\r\n indices()->gpuBuffer()->deleteGLBufferObject();\r\n }\r\n\r\n virtual void clearLocalBuffer()\r\n {\r\n indices()->gpuBuffer()->resize(0);\r\n }\r\n\r\n \/** Returns the number of triangles contained in this primitive set.\r\n * \\note This function returns -1 if primitive restart is enabled. *\/\r\n int triangleCount() const\r\n {\r\n if (primitiveRestartEnabled())\r\n return -1;\r\n\r\n int total_count = 0;\r\n for(size_t i=0; i<mCountVector.size(); ++i)\r\n {\r\n size_t count = mCountVector[i];\r\n switch( mType )\r\n {\r\n case PT_TRIANGLES: total_count += (count \/ 3);\r\n case PT_TRIANGLE_STRIP: total_count += (count - 2);\r\n case PT_TRIANGLE_FAN: total_count += (count - 2);\r\n case PT_QUADS: total_count += (count \/ 4 * 2);\r\n case PT_QUAD_STRIP: total_count += ( (count - 2) \/ 2 ) * 2;\r\n case PT_POLYGON: total_count += (count - 2);\r\n case PT_POINTS:\r\n case PT_LINES:\r\n case PT_LINE_LOOP:\r\n case PT_LINE_STRIP:\r\n default:\r\n break;\r\n }\r\n }\r\n\r\n return total_count;\r\n }\r\n\r\n \/** Returns the number of lines contained in this primitive set.\r\n * \\note This function returns -1 if primitive restart is enabled. *\/\r\n int lineCount() const \r\n {\r\n if (primitiveRestartEnabled())\r\n return -1;\r\n\r\n int total_count = 0;\r\n for(size_t i=0; i<mCountVector.size(); ++i)\r\n {\r\n size_t count = mCountVector[i];\r\n switch( mType )\r\n {\r\n case PT_LINES: total_count += count \/ 2;\r\n case PT_LINE_LOOP: total_count += count;\r\n case PT_LINE_STRIP: total_count += count - 1;\r\n default:\r\n break;\r\n }\r\n }\r\n\r\n return total_count;\r\n }\r\n\r\n \/** Returns the number of points contained in this primitive set.\r\n * \\note This function returns -1 if primitive restart is enabled. *\/\r\n int pointCount() const\r\n {\r\n if (primitiveRestartEnabled())\r\n return -1;\r\n\r\n int total_count = 0;\r\n for(size_t i=0; i<mCountVector.size(); ++i)\r\n {\r\n size_t count = mCountVector[i];\r\n switch( mType )\r\n {\r\n case PT_POINTS: total_count += count;\r\n default:\r\n break;\r\n }\r\n }\r\n\r\n return total_count;\r\n }\r\n\r\n \/** Returns always false. *\/\r\n virtual bool getTriangle( size_t, unsigned int*) const\r\n {\r\n return false;\r\n }\r\n\r\n virtual void render(bool use_vbo) const\r\n {\r\n VL_CHECK(GLEW_VERSION_1_4);\r\n VL_CHECK(!use_vbo || (use_vbo && (GLEW_ARB_vertex_buffer_object||GLEW_VERSION_1_5||GLEW_VERSION_3_0)))\r\n use_vbo &= GLEW_ARB_vertex_buffer_object||GLEW_VERSION_1_5||GLEW_VERSION_3_0; \/\/ && indices()->gpuBuffer()->handle() && indexCountGPU();\r\n if ( !use_vbo && !indexCount() )\r\n return;\r\n\r\n \/\/ primitive restart enable\r\n if(primitiveRestartEnabled())\r\n {\r\n if(GLEW_VERSION_3_1)\r\n {\r\n glEnable(GL_PRIMITIVE_RESTART);\r\n glPrimitiveRestartIndex(primitiveRestartIndex());\r\n }\r\n else\r\n if(GLEW_NV_primitive_restart)\r\n {\r\n glEnable(GL_PRIMITIVE_RESTART_NV);\r\n glPrimitiveRestartIndexNV(primitiveRestartIndex());\r\n }\r\n else\r\n {\r\n vl::Log::error(\"MultiDrawElements error: primitive restart not supported by this OpenGL implementation!\\n\");\r\n VL_TRAP();\r\n return;\r\n }\r\n }\r\n\r\n if (use_vbo && indices()->gpuBuffer()->handle())\r\n {\r\n VL_glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indices()->gpuBuffer()->handle());\r\n }\r\n else\r\n VL_glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);\r\n\r\n if (use_vbo)\r\n {\r\n glMultiDrawElements( \r\n primitiveType(), \r\n (GLsizei*)&mCountVector[0], \r\n indices()->glType(), \r\n (const GLvoid**)&mNULLPointerVector[0], mCountVector.size() \r\n );\r\n }\r\n else\r\n {\r\n glMultiDrawElements( \r\n primitiveType(), \r\n (GLsizei*)&mCountVector[0], \r\n indices()->glType(), \r\n (const GLvoid**)&mPointerVector[0], mCountVector.size() \r\n );\r\n }\r\n\r\n \/\/ primitive restart disable\r\n if(primitiveRestartEnabled())\r\n {\r\n if(GLEW_VERSION_3_1)\r\n glDisable(GL_PRIMITIVE_RESTART);\r\n else\r\n if(GLEW_NV_primitive_restart)\r\n glDisable(GL_PRIMITIVE_RESTART_NV);\r\n }\r\n\r\n if (use_vbo && this->indices()->gpuBuffer()->handle())\r\n VL_glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, 0 );\r\n }\r\n\r\n \/** Sets the vector defining the length of each primitive and automatically computes the pointer \r\n * vectors used to exectue glMultiDrawElements(). *\/\r\n void setCountVector(const std::vector<GLsizei>& vcount)\r\n {\r\n mCountVector = vcount;\r\n\r\n \/\/ set all to null: used when VBO is active.\r\n mNULLPointerVector.resize( vcount.size() );\r\n\r\n \/\/ used when VBOs are not active.\r\n mPointerVector.clear();\r\n const index_type* ptr = (const index_type*)indices()->gpuBuffer()->ptr();\r\n for(size_t i=0; i<vcount.size(); ++i)\r\n {\r\n mPointerVector.push_back(ptr);\r\n ptr += vcount[i];\r\n }\r\n VL_CHECK( ptr - (const index_type*)indices()->gpuBuffer()->ptr() <= indexCount() );\r\n }\r\n\r\n \/** The count vector used as 'count' parameter of glMultiDrawElements. *\/\r\n const std::vector<unsigned int>& countVector() const { return mCountVector; }\r\n\r\n \/** The pointer vector used as 'indices' parameter of glMultiDrawElements. *\/\r\n const std::vector<index_type*>& pointerVector() const { return mPointerVector; }\r\n\r\n \/** Returns the special index which idendifies a primitive restart. By default it is set to ~0 that is 0xFF, 0xFFFF, 0xFFFFFFFF respectively for ubyte, ushort, uint types. *\/\r\n GLuint primitiveRestartIndex() const { return mPrimitiveRestartIndex; }\r\n \/** Sets the special index which idendifies a primitive restart. By default it is set to ~0 that is 0xFF, 0xFFFF, 0xFFFFFFFF respectively for ubyte, ushort, uint types. *\/\r\n void setPrimitiveRestartIndex(GLuint index) { mPrimitiveRestartIndex = index; }\r\n\r\n \/** Returns whether the primitive-restart functionality is enabled or not. See http:\/\/www.opengl.org\/registry\/specs\/NV\/primitive_restart.txt *\/\r\n bool primitiveRestartEnabled() const { return mPrimitiveRestartEnabled; }\r\n \r\n \/** Enables the primitive-restart functionality. See http:\/\/www.opengl.org\/registry\/specs\/NV\/primitive_restart.txt\r\n * \\note Functions like triangleCount(), lineCount(), pointCount() and sortTriangles() should not be used when primitive restart is enabled. *\/\r\n void setPrimitiveRestartEnabled(bool enabled) { mPrimitiveRestartEnabled = enabled; }\r\n\r\n protected:\r\n ref< arr_type > mIndexBuffer;\r\n GLuint mPrimitiveRestartIndex;\r\n bool mPrimitiveRestartEnabled;\r\n\r\n std::vector<GLsizei> mCountVector;\r\n std::vector<const index_type*> mPointerVector;\r\n std::vector<const index_type*> mNULLPointerVector;\r\n };\r\n \/\/------------------------------------------------------------------------------\r\n \/\/ typedefs\r\n \/\/------------------------------------------------------------------------------\r\n \/** A MultiDrawElements using indices of type \\p GLuint. *\/\r\n typedef MultiDrawElements<GLuint, GL_UNSIGNED_INT, ArrayUInt> MultiDrawElementsUInt;\r\n \/\/------------------------------------------------------------------------------\r\n \/** A MultiDrawElements using indices of type \\p GLushort. *\/\r\n typedef MultiDrawElements<GLushort, GL_UNSIGNED_SHORT, ArrayUShort> MultiDrawElementsUShort;\r\n \/\/------------------------------------------------------------------------------\r\n \/** A MultiDrawElements using indices of type \\p GLubyte. *\/\r\n typedef MultiDrawElements<GLubyte, GL_UNSIGNED_BYTE, ArrayUByte> MultiDrawElementsUByte;\r\n \/\/------------------------------------------------------------------------------\r\n}\r\n\r\n#endif\r\n<commit_msg>Added support to glMultiDrawElementsBaseVertex() and compilation fixes<commit_after>\/**************************************************************************************\/\r\n\/* *\/\r\n\/* Visualization Library *\/\r\n\/* http:\/\/www.visualizationlibrary.com *\/\r\n\/* *\/\r\n\/* Copyright (c) 2005-2010, Michele Bosi *\/\r\n\/* All rights reserved. *\/\r\n\/* *\/\r\n\/* Redistribution and use in source and binary forms, with or without modification, *\/\r\n\/* are permitted provided that the following conditions are met: *\/\r\n\/* *\/\r\n\/* - Redistributions of source code must retain the above copyright notice, this *\/\r\n\/* list of conditions and the following disclaimer. *\/\r\n\/* *\/\r\n\/* - Redistributions in binary form must reproduce the above copyright notice, this *\/\r\n\/* list of conditions and the following disclaimer in the documentation and\/or *\/\r\n\/* other materials provided with the distribution. *\/\r\n\/* *\/\r\n\/* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND *\/\r\n\/* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED *\/\r\n\/* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE *\/\r\n\/* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR *\/\r\n\/* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES *\/\r\n\/* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; *\/\r\n\/* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON *\/\r\n\/* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT *\/\r\n\/* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS *\/\r\n\/* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *\/\r\n\/* *\/\r\n\/**************************************************************************************\/\r\n\r\n#ifndef MultiDrawElements_INCLUDE_ONCE\r\n#define MultiDrawElements_INCLUDE_ONCE\r\n\r\n#include <vl\/Primitives.hpp>\r\n#include <vl\/Array.hpp>\r\n#include <vl\/Log.hpp>\r\n#include <vl\/Say.hpp>\r\n#include <algorithm>\r\n\r\nnamespace vl\r\n{\r\n \/\/------------------------------------------------------------------------------\r\n \/\/ MultiDrawElements\r\n \/\/------------------------------------------------------------------------------\r\n \/** \r\n * Wrapper for the OpenGL function glMultiDrawElements(), see also http:\/\/www.opengl.org\/sdk\/docs\/man\/xhtml\/glMultiDrawElements.xml for more information.\r\n *\r\n *\/\r\n template <typename index_type, GLenum Tgltype, class arr_type>\r\n class MultiDrawElements: public Primitives\r\n {\r\n public:\r\n virtual const char* className() { return \"MultiDrawElements\"; }\r\n\r\n MultiDrawElements(EPrimitiveType primitive = PT_TRIANGLES)\r\n {\r\n #ifndef NDEBUG\r\n mObjectName = className();\r\n #endif\r\n mType = primitive;\r\n mIndexBuffer = new arr_type;\r\n mPrimitiveRestartIndex = ~(index_type)0;\r\n mPrimitiveRestartEnabled = false;\r\n }\r\n\r\n MultiDrawElements& operator=(const MultiDrawElements& other)\r\n {\r\n Primitives::operator=(other);\r\n *indices() = *other.indices();\r\n mPrimitiveRestartEnabled = other.mPrimitiveRestartEnabled;\r\n mPrimitiveRestartIndex = other.mPrimitiveRestartIndex;\r\n setCountVector(other.mCountVector);\r\n return *this;\r\n }\r\n\r\n virtual ref<Primitives> clone() const \r\n { \r\n ref<MultiDrawElements> de = new MultiDrawElements;\r\n *de = *this;\r\n return de;\r\n }\r\n\r\n virtual unsigned int handle() const { return indices()->gpuBuffer()->handle(); }\r\n\r\n virtual size_t indexCount() const { return indices()->size(); }\r\n\r\n virtual size_t indexCountGPU() const { return indices()->sizeGPU(); }\r\n\r\n \/** The index returned does not include the the base vertex. *\/\r\n virtual size_t index(int i) const \r\n { \r\n return indices()->at(i);\r\n }\r\n\r\n arr_type* indices() { return mIndexBuffer.get(); }\r\n const arr_type* indices() const { return mIndexBuffer.get(); }\r\n\r\n virtual void updateVBOs(bool discard_local_data = false)\r\n {\r\n indices()->updateVBO(discard_local_data);\r\n }\r\n\r\n virtual void deleteVBOs()\r\n {\r\n indices()->gpuBuffer()->deleteGLBufferObject();\r\n }\r\n\r\n virtual void clearLocalBuffer()\r\n {\r\n indices()->gpuBuffer()->resize(0);\r\n }\r\n\r\n \/** Returns the number of triangles contained in this primitive set.\r\n * \\note This function returns -1 if primitive restart is enabled. *\/\r\n int triangleCount() const\r\n {\r\n if (primitiveRestartEnabled())\r\n return -1;\r\n\r\n int total_count = 0;\r\n for(size_t i=0; i<mCountVector.size(); ++i)\r\n {\r\n size_t count = mCountVector[i];\r\n switch( mType )\r\n {\r\n case PT_TRIANGLES: total_count += (count \/ 3);\r\n case PT_TRIANGLE_STRIP: total_count += (count - 2);\r\n case PT_TRIANGLE_FAN: total_count += (count - 2);\r\n case PT_QUADS: total_count += (count \/ 4 * 2);\r\n case PT_QUAD_STRIP: total_count += ( (count - 2) \/ 2 ) * 2;\r\n case PT_POLYGON: total_count += (count - 2);\r\n case PT_POINTS:\r\n case PT_LINES:\r\n case PT_LINE_LOOP:\r\n case PT_LINE_STRIP:\r\n default:\r\n break;\r\n }\r\n }\r\n\r\n return total_count;\r\n }\r\n\r\n \/** Returns the number of lines contained in this primitive set.\r\n * \\note This function returns -1 if primitive restart is enabled. *\/\r\n int lineCount() const \r\n {\r\n if (primitiveRestartEnabled())\r\n return -1;\r\n\r\n int total_count = 0;\r\n for(size_t i=0; i<mCountVector.size(); ++i)\r\n {\r\n size_t count = mCountVector[i];\r\n switch( mType )\r\n {\r\n case PT_LINES: total_count += count \/ 2;\r\n case PT_LINE_LOOP: total_count += count;\r\n case PT_LINE_STRIP: total_count += count - 1;\r\n default:\r\n break;\r\n }\r\n }\r\n\r\n return total_count;\r\n }\r\n\r\n \/** Returns the number of points contained in this primitive set.\r\n * \\note This function returns -1 if primitive restart is enabled. *\/\r\n int pointCount() const\r\n {\r\n if (primitiveRestartEnabled())\r\n return -1;\r\n\r\n int total_count = 0;\r\n for(size_t i=0; i<mCountVector.size(); ++i)\r\n {\r\n size_t count = mCountVector[i];\r\n switch( mType )\r\n {\r\n case PT_POINTS: total_count += count;\r\n default:\r\n break;\r\n }\r\n }\r\n\r\n return total_count;\r\n }\r\n\r\n \/** Returns always false. *\/\r\n virtual bool getTriangle( size_t, unsigned int*) const\r\n {\r\n return false;\r\n }\r\n\r\n virtual void render(bool use_vbo) const\r\n {\r\n VL_CHECK(GLEW_VERSION_1_4);\r\n VL_CHECK(!use_vbo || (use_vbo && (GLEW_ARB_vertex_buffer_object||GLEW_VERSION_1_5||GLEW_VERSION_3_0)))\r\n use_vbo &= GLEW_ARB_vertex_buffer_object||GLEW_VERSION_1_5||GLEW_VERSION_3_0; \/\/ && indices()->gpuBuffer()->handle() && indexCountGPU();\r\n if ( !use_vbo && !indexCount() )\r\n return;\r\n\r\n \/\/ primitive restart enable\r\n if(primitiveRestartEnabled())\r\n {\r\n if(GLEW_VERSION_3_1)\r\n {\r\n glEnable(GL_PRIMITIVE_RESTART);\r\n glPrimitiveRestartIndex(primitiveRestartIndex());\r\n }\r\n else\r\n if(GLEW_NV_primitive_restart)\r\n {\r\n glEnable(GL_PRIMITIVE_RESTART_NV);\r\n glPrimitiveRestartIndexNV(primitiveRestartIndex());\r\n }\r\n else\r\n {\r\n vl::Log::error(\"MultiDrawElements error: primitive restart not supported by this OpenGL implementation!\\n\");\r\n VL_TRAP();\r\n return;\r\n }\r\n }\r\n\r\n GLvoid **indices_ptr = (GLvoid**)&mPointerVector[0];\r\n if (use_vbo && indices()->gpuBuffer()->handle())\r\n {\r\n VL_glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indices()->gpuBuffer()->handle());\r\n indices_ptr = (GLvoid**)&mNULLPointerVector[0];\r\n }\r\n else\r\n VL_glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);\r\n\r\n if (baseVertices().size())\r\n {\r\n VL_CHECK( baseVertices().size() == pointerVector().size() )\r\n VL_CHECK( baseVertices().size() == countVector().size() )\r\n if (GLEW_ARB_draw_elements_base_vertex || GLEW_VERSION_3_1)\r\n glMultiDrawElementsBaseVertex( \r\n primitiveType(), (GLsizei*)&mCountVector[0], indices()->glType(), indices_ptr, mCountVector.size(), (GLint*)&mBaseVertices[0] \r\n );\r\n else\r\n {\r\n vl::Log::error(\"MultiDrawElements::render(): glMultiDrawElementsBaseVertex() not supported!\\n\"\r\n \"OpenGL 3.1 or GL_ARB_draw_elements_base_vertex extension required.\\n\"\r\n );\r\n }\r\n }\r\n else\r\n glMultiDrawElements( \r\n primitiveType(), (GLsizei*)&mCountVector[0], indices()->glType(), (const GLvoid**)indices_ptr, mCountVector.size() \r\n );\r\n\r\n \/\/ primitive restart disable\r\n if(primitiveRestartEnabled())\r\n {\r\n if(GLEW_VERSION_3_1)\r\n glDisable(GL_PRIMITIVE_RESTART);\r\n else\r\n if(GLEW_NV_primitive_restart)\r\n glDisable(GL_PRIMITIVE_RESTART_NV);\r\n }\r\n\r\n if (use_vbo && this->indices()->gpuBuffer()->handle())\r\n VL_glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, 0 );\r\n }\r\n\r\n \/** Sets the vector defining the length of each primitive and automatically computes the pointer \r\n * vectors used to exectue glMultiDrawElements(). *\/\r\n void setCountVector(const std::vector<GLsizei>& vcount)\r\n {\r\n mCountVector = vcount;\r\n\r\n \/\/ set all to null: used when VBO is active.\r\n mNULLPointerVector.resize( vcount.size() );\r\n\r\n \/\/ used when VBOs are not active.\r\n mPointerVector.clear();\r\n const index_type* ptr = (const index_type*)indices()->gpuBuffer()->ptr();\r\n for(size_t i=0; i<vcount.size(); ++i)\r\n {\r\n mPointerVector.push_back(ptr);\r\n ptr += vcount[i];\r\n }\r\n VL_CHECK( ptr - (const index_type*)indices()->gpuBuffer()->ptr() <= indexCount() );\r\n }\r\n\r\n \/** The count vector used as 'count' parameter of glMultiDrawElements. *\/\r\n const std::vector<GLsizei>& countVector() const { return mCountVector; }\r\n\r\n \/** The pointer vector used as 'indices' parameter of glMultiDrawElements. *\/\r\n const std::vector<const index_type*>& pointerVector() const { return mPointerVector; }\r\n\r\n \/** Returns the special index which idendifies a primitive restart. By default it is set to ~0 that is 0xFF, 0xFFFF, 0xFFFFFFFF respectively for ubyte, ushort, uint types. *\/\r\n GLuint primitiveRestartIndex() const { return mPrimitiveRestartIndex; }\r\n \/** Sets the special index which idendifies a primitive restart. By default it is set to ~0 that is 0xFF, 0xFFFF, 0xFFFFFFFF respectively for ubyte, ushort, uint types. *\/\r\n void setPrimitiveRestartIndex(GLuint index) { mPrimitiveRestartIndex = index; }\r\n\r\n \/** Returns whether the primitive-restart functionality is enabled or not. See http:\/\/www.opengl.org\/registry\/specs\/NV\/primitive_restart.txt *\/\r\n bool primitiveRestartEnabled() const { return mPrimitiveRestartEnabled; }\r\n \r\n \/** Enables the primitive-restart functionality. See http:\/\/www.opengl.org\/registry\/specs\/NV\/primitive_restart.txt\r\n * \\note Functions like triangleCount(), lineCount(), pointCount() and sortTriangles() should not be used when primitive restart is enabled. *\/\r\n void setPrimitiveRestartEnabled(bool enabled) { mPrimitiveRestartEnabled = enabled; }\r\n\r\n \/** Returns the list of base vertices, one for each primitive. This will enable the use \r\n * of glMultiDrawElementsBaseVertex() to render a set of primitives. \r\n * See also http:\/\/www.opengl.org\/sdk\/docs\/man3\/xhtml\/glMultiDrawElementsBaseVertex.xml *\/\r\n void setBaseVertices(const std::vector<GLint>& base_verts) { mBaseVertices = base_verts; }\r\n \/** Returns the list of base vertices, one for each primitive. *\/\r\n const std::vector<GLint>& baseVertices() const { return mBaseVertices; }\r\n \/** Returns the list of base vertices, one for each primitive. *\/\r\n std::vector<GLint>& baseVertices() { return mBaseVertices; }\r\n\r\n protected:\r\n ref< arr_type > mIndexBuffer;\r\n GLuint mPrimitiveRestartIndex;\r\n bool mPrimitiveRestartEnabled;\r\n\r\n std::vector<GLsizei> mCountVector;\r\n std::vector<const index_type*> mPointerVector;\r\n std::vector<const index_type*> mNULLPointerVector;\r\n std::vector<GLint> mBaseVertices;\r\n };\r\n \/\/------------------------------------------------------------------------------\r\n \/\/ typedefs\r\n \/\/------------------------------------------------------------------------------\r\n \/** A MultiDrawElements using indices of type \\p GLuint. *\/\r\n typedef MultiDrawElements<GLuint, GL_UNSIGNED_INT, ArrayUInt> MultiDrawElementsUInt;\r\n \/\/------------------------------------------------------------------------------\r\n \/** A MultiDrawElements using indices of type \\p GLushort. *\/\r\n typedef MultiDrawElements<GLushort, GL_UNSIGNED_SHORT, ArrayUShort> MultiDrawElementsUShort;\r\n \/\/------------------------------------------------------------------------------\r\n \/** A MultiDrawElements using indices of type \\p GLubyte. *\/\r\n typedef MultiDrawElements<GLubyte, GL_UNSIGNED_BYTE, ArrayUByte> MultiDrawElementsUByte;\r\n \/\/------------------------------------------------------------------------------\r\n}\r\n\r\n#endif\r\n<|endoftext|>"} {"text":"<commit_before>\/\/ For conditions of distribution and use, see copyright notice in license.txt\r\n\r\n#include \"StableHeaders.h\"\r\n\r\n#include \"TestModule.h\"\r\n#include \"EC_Dummy.h\"\r\n#include <Poco\/ClassLibrary.h>\r\n#include \"EntityInterface.h\"\r\n\r\n\r\nnamespace Test\r\n{\r\n TestModule::TestModule() : ModuleInterfaceImpl(type_static_)\r\n {\r\n }\r\n\r\n TestModule::~TestModule()\r\n {\r\n }\r\n\r\n \/\/ virtual\r\n void TestModule::Load()\r\n {\r\n using namespace Test;\r\n DECLARE_MODULE_EC(EC_Dummy);\r\n\r\n LogInfo(\"Module \" + Name() + \" loaded.\");\r\n }\r\n\r\n \/\/ virtual\r\n void TestModule::Unload()\r\n {\r\n LogInfo(\"Module \" + Name() + \" unloaded.\");\r\n }\r\n\r\n \/\/ virtual\r\n void TestModule::Initialize()\r\n {\r\n framework_->GetServiceManager()->RegisterService(Foundation::Service::ST_Test, &test_service_);\r\n assert (framework_->GetServiceManager()->IsRegistered(Foundation::Service::ST_Test) &&\r\n \"Failed to register test service\");\r\n\r\n framework_->GetEventManager()->RegisterEventCategory(\"Test\");\r\n\r\n LogInfo(\"Module \" + Name() + \" initialized.\");\r\n }\r\n\r\n \/\/ virtual \r\n void TestModule::Uninitialize()\r\n {\r\n framework_->GetServiceManager()->UnregisterService(&test_service_);\r\n assert (framework_->GetServiceManager()->IsRegistered(Foundation::Service::ST_Test) == false &&\r\n \"Failed to unregister test service\");\r\n\r\n LogInfo(\"Module \" + Name() + \" uninitialized.\");\r\n }\r\n\r\n \/\/ virtual\r\n void TestModule::Update(Core::f64 frametime)\r\n {\r\n LogInfo(\"\");\r\n\r\n assert (VersionMajor() == GetFramework()->GetDefaultConfig().GetSetting<std::string>(Foundation::Framework::ConfigurationGroup(), \"version_major\"));\r\n assert (VersionMinor() == GetFramework()->GetDefaultConfig().GetSetting<std::string>(Foundation::Framework::ConfigurationGroup(), \"version_minor\"));\r\n\r\n \/\/ create new entity\r\n LogInfo(\"Constructing entity with component: \" + Test::EC_Dummy::NameStatic() + \".\");\r\n\r\n Foundation::SceneManagerServiceInterface *sceneManager = \r\n framework_->GetService<Foundation::SceneManagerServiceInterface>(Foundation::Service::ST_SceneManager);\r\n assert(sceneManager != NULL && \"Failed to get SceneManager service\");\r\n\r\n assert(sceneManager->HasScene(\"test_scene\") == false && \"Scene test_scene scene already exists!\");\r\n Foundation::ScenePtr scene = sceneManager->CreateScene(\"test_scene\");\r\n assert(scene.get() && \"Failed to create scene\" );\r\n assert(sceneManager->HasScene(\"test_scene\") && \"Failed to create scene\");\r\n\r\n Foundation::EntityPtr entity = scene->CreateEntity(0);\r\n assert (entity.get() != 0 && \"Failed to create entity.\");\r\n assert (scene->HasEntity(entity->GetId()) && \"Failed to add entity to scene properly!\");\r\n\r\n Foundation::ComponentPtr component = framework_->GetComponentManager()->CreateComponent(Test::EC_Dummy::NameStatic());\r\n assert (component.get() != 0 && \"Failed to create dummy component.\");\r\n\r\n entity->AddEntityComponent(component);\r\n component = entity->GetComponent(component->Name());\r\n assert (component.get() != 0 && \"Failed to get dummy component from entity.\");\r\n\r\n int num_test_components = 0;\r\n for (Foundation::ComponentManager::const_iterator it = \r\n framework_->GetComponentManager()->Begin(Test::EC_Dummy::NameStatic()) ;\r\n it != framework_->GetComponentManager()->End(Test::EC_Dummy::NameStatic()) ;\r\n ++it)\r\n {\r\n assert (it->lock()->Name() == Test::EC_Dummy::NameStatic() && \"Component iterator returned wrong component type.\");\r\n num_test_components++;\r\n }\r\n assert (num_test_components == 1 && \"Component iterator failed.\");\r\n\r\n\r\n Foundation::ScenePtr cloned_scene = scene->Clone(\"Test clone scene\");\r\n assert (sceneManager->HasScene(\"Test clone scene\"));\r\n assert (cloned_scene->HasEntity(entity->GetId()) && \"Failed to clone a scene\");\r\n\r\n Foundation::EntityPtr cloned_entity = entity->Clone(\"Test clone scene\");\r\n component = cloned_entity->GetComponent(component->Name());\r\n assert (component.get() != 0 && \"Failed to clone an entity.\");\r\n\r\n Foundation::EntityPtr cloned_entity2 = cloned_scene->GetEntity(cloned_entity->GetId());\r\n Foundation::EntityPtr entity2 = cloned_scene->CreateEntity(0);\r\n assert (*cloned_entity2.get() == *cloned_entity.get() && \"EntityInterface operator== failed\");\r\n assert (*entity.get() != *entity2.get() && \"EntityInterface operator!= failed\");\r\n assert (*cloned_entity.get() < *entity2.get() && \"EntityInterface operator< failed\");\r\n\r\n\r\n Foundation::ScenePtr scene2 = sceneManager->GetScene(\"test_scene\");\r\n assert(*scene.get() == *scene2.get() && \"SceneInterface operator== failed\");\r\n assert(*scene.get() != *cloned_scene.get() && \"SceneInterface operator!= failed\");\r\n assert(*cloned_scene.get() < *scene.get() && \"SceneInterface operator< failed\");\r\n\r\n Foundation::SceneManager::iterator it = sceneManager->Begin();\r\n Foundation::SceneManager::iterator it_copy = it;\r\n int test_scenes = 0;\r\n for ( ; it_copy != sceneManager->End() ; ++it_copy)\r\n {\r\n if ((*it_copy)->Name() == \"test_scene\")\r\n test_scenes++;\r\n\r\n if ((*it_copy)->Name() == \"Test clone scene\")\r\n test_scenes++;\r\n }\r\n assert (test_scenes == 2 && \"Scene iterator could not find all the scenes!\");\r\n\r\n const Foundation::SceneManagerServiceInterface *const_sceneManager = const_cast<const Foundation::SceneManagerServiceInterface*>(sceneManager);\r\n Foundation::SceneManager::const_iterator c_it = const_sceneManager->Begin();\r\n Foundation::SceneManager::const_iterator c_it_copy = c_it;\r\n test_scenes = 0;\r\n for ( ; c_it_copy != const_sceneManager->End() ; ++c_it_copy)\r\n {\r\n if ((*c_it_copy)->Name() == \"test_scene\")\r\n test_scenes++;\r\n\r\n if ((*c_it_copy)->Name() == \"Test clone scene\")\r\n test_scenes++;\r\n }\r\n assert (test_scenes == 2 && \"Const scene iterator could not find all the scenes!\");\r\n\r\n\r\n\r\n Foundation::TestServiceInterface *test_service = framework_->GetServiceManager()->GetService<Foundation::TestServiceInterface>(Foundation::Service::ST_Test);\r\n assert (test_service != NULL);\r\n assert (test_service->Test());\r\n\r\n\r\n TestEvent test_event;\r\n test_event.test_value_ = 12345;\r\n framework_->GetEventManager()->SendEvent(framework_->GetEventManager()->QueryEventCategory(\"Test\"), 0, NULL);\r\n framework_->GetEventManager()->SendEvent(framework_->GetEventManager()->QueryEventCategory(\"Test\"), 1, &test_event);\r\n\r\n framework_->Exit();\r\n assert (framework_->IsExiting());\r\n\r\n LogInfo(\"\");\r\n }\r\n}\r\n\r\n<commit_msg>Test for removing an entity component from entity.<commit_after>\/\/ For conditions of distribution and use, see copyright notice in license.txt\r\n\r\n#include \"StableHeaders.h\"\r\n\r\n#include \"TestModule.h\"\r\n#include \"EC_Dummy.h\"\r\n#include <Poco\/ClassLibrary.h>\r\n#include \"EntityInterface.h\"\r\n\r\n\r\n\r\nnamespace Test\r\n{\r\n TestModule::TestModule() : ModuleInterfaceImpl(type_static_)\r\n {\r\n }\r\n\r\n TestModule::~TestModule()\r\n {\r\n }\r\n\r\n \/\/ virtual\r\n void TestModule::Load()\r\n {\r\n using namespace Test;\r\n DECLARE_MODULE_EC(EC_Dummy);\r\n\r\n LogInfo(\"Module \" + Name() + \" loaded.\");\r\n }\r\n\r\n \/\/ virtual\r\n void TestModule::Unload()\r\n {\r\n LogInfo(\"Module \" + Name() + \" unloaded.\");\r\n }\r\n\r\n \/\/ virtual\r\n void TestModule::Initialize()\r\n {\r\n framework_->GetServiceManager()->RegisterService(Foundation::Service::ST_Test, &test_service_);\r\n assert (framework_->GetServiceManager()->IsRegistered(Foundation::Service::ST_Test) &&\r\n \"Failed to register test service\");\r\n\r\n framework_->GetEventManager()->RegisterEventCategory(\"Test\");\r\n\r\n LogInfo(\"Module \" + Name() + \" initialized.\");\r\n }\r\n\r\n \/\/ virtual \r\n void TestModule::Uninitialize()\r\n {\r\n framework_->GetServiceManager()->UnregisterService(&test_service_);\r\n assert (framework_->GetServiceManager()->IsRegistered(Foundation::Service::ST_Test) == false &&\r\n \"Failed to unregister test service\");\r\n\r\n LogInfo(\"Module \" + Name() + \" uninitialized.\");\r\n }\r\n\r\n \/\/ virtual\r\n void TestModule::Update(Core::f64 frametime)\r\n {\r\n LogInfo(\"\");\r\n\r\n assert (VersionMajor() == GetFramework()->GetDefaultConfig().GetSetting<std::string>(Foundation::Framework::ConfigurationGroup(), \"version_major\"));\r\n assert (VersionMinor() == GetFramework()->GetDefaultConfig().GetSetting<std::string>(Foundation::Framework::ConfigurationGroup(), \"version_minor\"));\r\n\r\n \/\/ create new entity\r\n LogInfo(\"Constructing entity with component: \" + Test::EC_Dummy::NameStatic() + \".\");\r\n\r\n Foundation::SceneManagerServiceInterface *sceneManager = \r\n framework_->GetService<Foundation::SceneManagerServiceInterface>(Foundation::Service::ST_SceneManager);\r\n assert(sceneManager != NULL && \"Failed to get SceneManager service\");\r\n\r\n assert(sceneManager->HasScene(\"test_scene\") == false && \"Scene test_scene scene already exists!\");\r\n Foundation::ScenePtr scene = sceneManager->CreateScene(\"test_scene\");\r\n assert(scene.get() && \"Failed to create scene\" );\r\n assert(sceneManager->HasScene(\"test_scene\") && \"Failed to create scene\");\r\n\r\n Foundation::EntityPtr entity = scene->CreateEntity(0);\r\n assert (entity.get() != 0 && \"Failed to create entity.\");\r\n assert (scene->HasEntity(entity->GetId()) && \"Failed to add entity to scene properly!\");\r\n\r\n Foundation::ComponentPtr component = framework_->GetComponentManager()->CreateComponent(Test::EC_Dummy::NameStatic());\r\n assert (component.get() != 0 && \"Failed to create dummy component.\");\r\n\r\n entity->AddEntityComponent(component);\r\n component = entity->GetComponent(component->Name());\r\n assert (component.get() != 0 && \"Failed to get dummy component from entity.\");\r\n\r\n Foundation::ComponentPtr component_second = framework_->GetComponentManager()->CreateComponent(Test::EC_Dummy::NameStatic());\r\n entity->AddEntityComponent(component_second);\r\n component = entity->GetComponent(component_second->Name());\r\n assert (component.get() != 0 && \"Failed to get dummy component from entity.\");\r\n entity->RemoveEntityComponent(component_second);\r\n component_second.reset();\r\n\r\n int num_test_components = 0;\r\n for (Foundation::ComponentManager::const_iterator it = \r\n framework_->GetComponentManager()->Begin(Test::EC_Dummy::NameStatic()) ;\r\n it != framework_->GetComponentManager()->End(Test::EC_Dummy::NameStatic()) ;\r\n ++it)\r\n {\r\n assert (it->lock()->Name() == Test::EC_Dummy::NameStatic() && \"Component iterator returned wrong component type.\");\r\n num_test_components++;\r\n }\r\n assert (num_test_components == 1 && \"Component iterator failed.\");\r\n\r\n\r\n Foundation::ScenePtr cloned_scene = scene->Clone(\"Test clone scene\");\r\n assert (sceneManager->HasScene(\"Test clone scene\"));\r\n assert (cloned_scene->HasEntity(entity->GetId()) && \"Failed to clone a scene\");\r\n\r\n Foundation::EntityPtr cloned_entity = entity->Clone(\"Test clone scene\");\r\n component = cloned_entity->GetComponent(component->Name());\r\n assert (component.get() != 0 && \"Failed to clone an entity.\");\r\n\r\n Foundation::EntityPtr cloned_entity2 = cloned_scene->GetEntity(cloned_entity->GetId());\r\n Foundation::EntityPtr entity2 = cloned_scene->CreateEntity(0);\r\n assert (*cloned_entity2.get() == *cloned_entity.get() && \"EntityInterface operator== failed\");\r\n assert (*entity.get() != *entity2.get() && \"EntityInterface operator!= failed\");\r\n assert (*cloned_entity.get() < *entity2.get() && \"EntityInterface operator< failed\");\r\n\r\n\r\n Foundation::ScenePtr scene2 = sceneManager->GetScene(\"test_scene\");\r\n assert(*scene.get() == *scene2.get() && \"SceneInterface operator== failed\");\r\n assert(*scene.get() != *cloned_scene.get() && \"SceneInterface operator!= failed\");\r\n assert(*cloned_scene.get() < *scene.get() && \"SceneInterface operator< failed\");\r\n\r\n Foundation::SceneManager::iterator it = sceneManager->Begin();\r\n Foundation::SceneManager::iterator it_copy = it;\r\n int test_scenes = 0;\r\n for ( ; it_copy != sceneManager->End() ; ++it_copy)\r\n {\r\n if ((*it_copy)->Name() == \"test_scene\")\r\n test_scenes++;\r\n\r\n if ((*it_copy)->Name() == \"Test clone scene\")\r\n test_scenes++;\r\n }\r\n assert (test_scenes == 2 && \"Scene iterator could not find all the scenes!\");\r\n\r\n const Foundation::SceneManagerServiceInterface *const_sceneManager = const_cast<const Foundation::SceneManagerServiceInterface*>(sceneManager);\r\n Foundation::SceneManager::const_iterator c_it = const_sceneManager->Begin();\r\n Foundation::SceneManager::const_iterator c_it_copy = c_it;\r\n test_scenes = 0;\r\n for ( ; c_it_copy != const_sceneManager->End() ; ++c_it_copy)\r\n {\r\n if ((*c_it_copy)->Name() == \"test_scene\")\r\n test_scenes++;\r\n\r\n if ((*c_it_copy)->Name() == \"Test clone scene\")\r\n test_scenes++;\r\n }\r\n assert (test_scenes == 2 && \"Const scene iterator could not find all the scenes!\");\r\n\r\n\r\n\r\n Foundation::TestServiceInterface *test_service = framework_->GetServiceManager()->GetService<Foundation::TestServiceInterface>(Foundation::Service::ST_Test);\r\n assert (test_service != NULL);\r\n assert (test_service->Test());\r\n\r\n\r\n TestEvent test_event;\r\n test_event.test_value_ = 12345;\r\n framework_->GetEventManager()->SendEvent(framework_->GetEventManager()->QueryEventCategory(\"Test\"), 0, NULL);\r\n framework_->GetEventManager()->SendEvent(framework_->GetEventManager()->QueryEventCategory(\"Test\"), 1, &test_event);\r\n\r\n framework_->Exit();\r\n assert (framework_->IsExiting());\r\n\r\n LogInfo(\"\");\r\n }\r\n}\r\n\r\n<|endoftext|>"} {"text":"<commit_before>\/\/ Filename: geomSprite.cxx\n\/\/ Created by: charles (13Jul00)\n\/\/ \n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include <datagram.h>\n#include <datagramIterator.h>\n#include <bamReader.h>\n#include <bamWriter.h>\n#include <ioPtaDatagramShort.h>\n#include <ioPtaDatagramInt.h>\n#include <ioPtaDatagramFloat.h>\n#include <ioPtaDatagramLinMath.h>\n#include <graphicsStateGuardianBase.h>\n\n#include \"geomSprite.h\"\n\nTypeHandle GeomSprite::_type_handle;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Function: GeomSprite\n\/\/ Access: public\n\/\/ Description: constructor\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nGeomSprite::\nGeomSprite(Texture *tex, bool alpha_disable) :\n _texture(tex), _alpha_disable(alpha_disable) {\n _x_texel_ratio.clear();\n _y_texel_ratio.clear();\n\n _theta_bind_type = G_OFF;\n \/\/ note that the other bind types are intentionally left \n \/\/ uninitialized; the arrays themselves can not be set without a\n \/\/ bind type.\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Function: GeomSprite::make_copy\n\/\/ Access: Public, Virtual\n\/\/ Description: Returns a newly-allocated Geom that is a shallow copy\n\/\/ of this one. It will be a different Geom pointer,\n\/\/ but its internal data may or may not be shared with\n\/\/ that of the original Geom.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nGeom *GeomSprite::\nmake_copy() const {\n return new GeomSprite(*this);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Function: GeomSprite::print_draw_immediate\n\/\/ Access:\n\/\/ Description:\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid GeomSprite::\nprint_draw_immediate(void) const {\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Function: GeomSprite::draw_immediate\n\/\/ Access:\n\/\/ Description:\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid GeomSprite::\ndraw_immediate(GraphicsStateGuardianBase *gsg) const {\n gsg->draw_sprite(this);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Function: GeomSprite::write_datagram\n\/\/ Access: Public\n\/\/ Description: Function to write the important information in\n\/\/ the particular object to a Datagram\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid GeomSprite::\nwrite_datagram(BamWriter *manager, Datagram &me) {\n Geom::write_datagram(manager, me);\n WRITE_PTA(manager, me, IPD_float::write_datagram, _x_texel_ratio);\n WRITE_PTA(manager, me, IPD_float::write_datagram, _y_texel_ratio);\n me.add_uint8(_x_bind_type);\n me.add_uint8(_y_bind_type);\n me.add_uint8(_alpha_disable);\n manager->write_pointer(me, _texture);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Function: GeomSprite::make_GeomSprite\n\/\/ Access: Protected\n\/\/ Description: Factory method to generate a GeomSprite object\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nTypedWriteable* GeomSprite::\nmake_GeomSprite(const FactoryParams ¶ms) {\n GeomSprite *me = new GeomSprite;\n BamReader *manager;\n Datagram packet;\n\n parse_params(params, manager, packet);\n DatagramIterator scan(packet);\n\n me->fillin(scan, manager);\n me->make_dirty();\n me->config();\n return me;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Function: GeomSprite::fillin\n\/\/ Access: Protected\n\/\/ Description: Function that reads out of the datagram (or asks\n\/\/ manager to read) all of the data that is needed to\n\/\/ re-create this object and stores it in the appropiate\n\/\/ place\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid GeomSprite::\nfillin(DatagramIterator& scan, BamReader* manager) {\n Geom::fillin(scan, manager);\n READ_PTA(manager, scan, IPD_float::read_datagram, _x_texel_ratio);\n READ_PTA(manager, scan, IPD_float::read_datagram, _y_texel_ratio);\n _x_bind_type = (GeomBindType) scan.get_uint8();\n _y_bind_type = (GeomBindType) scan.get_uint8();\n _alpha_disable = (bool) scan.get_uint8();\n manager->read_pointer(scan, this);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Function: GeomSprite::register_with_factory\n\/\/ Access: Public, Static\n\/\/ Description: Factory method to generate a GeomSprite object\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid GeomSprite::\nregister_with_read_factory(void) {\n BamReader::get_factory()->register_factory(get_class_type(), make_GeomSprite);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Function: GeomSprite::complete_pointers\n\/\/ Access: Public, Static\n\/\/ Description: \n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nint GeomSprite::\ncomplete_pointers(vector_typedWriteable &plist, BamReader *manager) {\n int index = Geom::complete_pointers(plist, manager);\n _texture = DCAST(Texture, plist[index]);\n\n return index + 1;\n}\n<commit_msg>get rid of cl warning<commit_after>\/\/ Filename: geomSprite.cxx\n\/\/ Created by: charles (13Jul00)\n\/\/ \n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include <datagram.h>\n#include <datagramIterator.h>\n#include <bamReader.h>\n#include <bamWriter.h>\n#include <ioPtaDatagramShort.h>\n#include <ioPtaDatagramInt.h>\n#include <ioPtaDatagramFloat.h>\n#include <ioPtaDatagramLinMath.h>\n#include <graphicsStateGuardianBase.h>\n\n#include \"geomSprite.h\"\n\nTypeHandle GeomSprite::_type_handle;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Function: GeomSprite\n\/\/ Access: public\n\/\/ Description: constructor\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nGeomSprite::\nGeomSprite(Texture *tex, bool alpha_disable) :\n _texture(tex), _alpha_disable(alpha_disable) {\n _x_texel_ratio.clear();\n _y_texel_ratio.clear();\n\n _theta_bind_type = G_OFF;\n \/\/ note that the other bind types are intentionally left \n \/\/ uninitialized; the arrays themselves can not be set without a\n \/\/ bind type.\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Function: GeomSprite::make_copy\n\/\/ Access: Public, Virtual\n\/\/ Description: Returns a newly-allocated Geom that is a shallow copy\n\/\/ of this one. It will be a different Geom pointer,\n\/\/ but its internal data may or may not be shared with\n\/\/ that of the original Geom.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nGeom *GeomSprite::\nmake_copy() const {\n return new GeomSprite(*this);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Function: GeomSprite::print_draw_immediate\n\/\/ Access:\n\/\/ Description:\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid GeomSprite::\nprint_draw_immediate(void) const {\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Function: GeomSprite::draw_immediate\n\/\/ Access:\n\/\/ Description:\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid GeomSprite::\ndraw_immediate(GraphicsStateGuardianBase *gsg) const {\n gsg->draw_sprite(this);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Function: GeomSprite::write_datagram\n\/\/ Access: Public\n\/\/ Description: Function to write the important information in\n\/\/ the particular object to a Datagram\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid GeomSprite::\nwrite_datagram(BamWriter *manager, Datagram &me) {\n Geom::write_datagram(manager, me);\n WRITE_PTA(manager, me, IPD_float::write_datagram, _x_texel_ratio);\n WRITE_PTA(manager, me, IPD_float::write_datagram, _y_texel_ratio);\n me.add_uint8(_x_bind_type);\n me.add_uint8(_y_bind_type);\n me.add_uint8(_alpha_disable);\n manager->write_pointer(me, _texture);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Function: GeomSprite::make_GeomSprite\n\/\/ Access: Protected\n\/\/ Description: Factory method to generate a GeomSprite object\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nTypedWriteable* GeomSprite::\nmake_GeomSprite(const FactoryParams ¶ms) {\n GeomSprite *me = new GeomSprite;\n BamReader *manager;\n Datagram packet;\n\n parse_params(params, manager, packet);\n DatagramIterator scan(packet);\n\n me->fillin(scan, manager);\n me->make_dirty();\n me->config();\n return me;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Function: GeomSprite::fillin\n\/\/ Access: Protected\n\/\/ Description: Function that reads out of the datagram (or asks\n\/\/ manager to read) all of the data that is needed to\n\/\/ re-create this object and stores it in the appropiate\n\/\/ place\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid GeomSprite::\nfillin(DatagramIterator& scan, BamReader* manager) {\n Geom::fillin(scan, manager);\n READ_PTA(manager, scan, IPD_float::read_datagram, _x_texel_ratio);\n READ_PTA(manager, scan, IPD_float::read_datagram, _y_texel_ratio);\n _x_bind_type = (GeomBindType) scan.get_uint8();\n _y_bind_type = (GeomBindType) scan.get_uint8();\n _alpha_disable = (scan.get_uint8() !=0);\n manager->read_pointer(scan, this);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Function: GeomSprite::register_with_factory\n\/\/ Access: Public, Static\n\/\/ Description: Factory method to generate a GeomSprite object\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid GeomSprite::\nregister_with_read_factory(void) {\n BamReader::get_factory()->register_factory(get_class_type(), make_GeomSprite);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Function: GeomSprite::complete_pointers\n\/\/ Access: Public, Static\n\/\/ Description: \n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nint GeomSprite::\ncomplete_pointers(vector_typedWriteable &plist, BamReader *manager) {\n int index = Geom::complete_pointers(plist, manager);\n _texture = DCAST(Texture, plist[index]);\n\n return index + 1;\n}\n<|endoftext|>"} {"text":"<commit_before>#include <cstdint>\n#include <iostream>\n#include <numeric> \/\/std::iota\n#include <stdexcept>\n\n#include <adios2.h>\n\n#include <gtest\/gtest.h>\n\nclass ADIOSBZip2Wrapper : public ::testing::Test\n{\npublic:\n ADIOSBZip2Wrapper() : adios(true), io(adios.DeclareIO(\"TestADIOSBZip2\")) {}\n\nprotected:\n adios2::ADIOS adios;\n adios2::IO &io;\n};\n\nTEST_F(ADIOSBZip2Wrapper, UInt100)\n{\n \/** Application variable uints from 0 to 1000 *\/\n std::vector<unsigned int> myUInts(100);\n std::iota(myUInts.begin(), myUInts.end(), 0.f);\n const std::size_t Nx = myUInts.size();\n const std::size_t inputBytes = Nx * sizeof(unsigned int);\n\n \/\/ Define ADIOS variable\n auto &var_UInt = io.DefineVariable<unsigned int>(\"myUInts\", {}, {}, {Nx},\n adios2::ConstantDims);\n\n \/\/ Verify the return type is as expected\n ::testing::StaticAssertTypeEq<decltype(var_UInt),\n adios2::Variable<unsigned int> &>();\n\n \/\/ Define bzip2 transform\n adios2::Operator &adiosBZip2 =\n adios.DefineOperator(\"BZip2Compressor\", \"BZip2\");\n\n const unsigned int bzip2ID =\n var_UInt.AddTransform(adiosBZip2, {{\"BlockSize100K\", \"2\"}});\n\n const std::size_t estimatedSize =\n adiosBZip2.BufferMaxSize(Nx * var_UInt.m_ElementSize);\n std::vector<char> compressedBuffer(estimatedSize);\n size_t compressedSize = adiosBZip2.Compress(\n myUInts.data(), var_UInt.m_Count, var_UInt.m_ElementSize,\n var_UInt.m_Type, compressedBuffer.data(),\n var_UInt.m_OperatorsInfo[bzip2ID].Parameters);\n\n EXPECT_LE(compressedSize, estimatedSize);\n\n compressedBuffer.resize(compressedSize);\n\n \/\/ Allocate original data size\n std::vector<unsigned int> decompressedBuffer(Nx);\n size_t decompressedSize = adiosBZip2.Decompress(\n compressedBuffer.data(), compressedSize, decompressedBuffer.data(),\n decompressedBuffer.size() * sizeof(unsigned int));\n ASSERT_EQ(decompressedSize, Nx);\n\n \/\/ testing data recovery\n for (size_t i = 0; i < Nx; ++i)\n {\n ASSERT_EQ(decompressedBuffer[i], myUInts[i]);\n }\n}\n\nTEST_F(ADIOSBZip2Wrapper, WrongParameterValue)\n{\n \/** Application variable uints from 0 to 1000 *\/\n std::vector<unsigned int> myUInts(100);\n std::iota(myUInts.begin(), myUInts.end(), 0.f);\n const std::size_t Nx = myUInts.size();\n const std::size_t inputBytes = Nx * sizeof(unsigned int);\n\n \/\/ Define ADIOS variable\n auto &var_UInt = io.DefineVariable<unsigned int>(\"myUInts\", {}, {}, {Nx},\n adios2::ConstantDims);\n\n \/\/ Verify the return type is as expected\n ::testing::StaticAssertTypeEq<decltype(var_UInt),\n adios2::Variable<unsigned int> &>();\n\n \/\/ Define bzip2 transform\n adios2::Operator &adiosBZip2 =\n adios.DefineOperator(\"BZip2Compressor\", \"BZip2\");\n\n const unsigned int bzip2ID =\n var_UInt.AddTransform(adiosBZip2, {{\"BlockSize100K\", \"10\"}});\n\n const std::size_t estimatedSize =\n adiosBZip2.BufferMaxSize(Nx * var_UInt.m_ElementSize);\n std::vector<char> compressedBuffer(estimatedSize);\n\n EXPECT_THROW(size_t compressedSize = adiosBZip2.Compress(\n myUInts.data(), var_UInt.m_Count, var_UInt.m_ElementSize,\n var_UInt.m_Type, compressedBuffer.data(),\n var_UInt.m_OperatorsInfo[bzip2ID].Parameters),\n std::invalid_argument);\n}\n\nTEST_F(ADIOSBZip2Wrapper, WrongBZip2Name)\n{\n \/** Application variable uints from 0 to 1000 *\/\n std::vector<unsigned int> myUInts(100);\n std::iota(myUInts.begin(), myUInts.end(), 0.f);\n const std::size_t Nx = myUInts.size();\n const std::size_t inputBytes = Nx * sizeof(unsigned int);\n\n \/\/ Define ADIOS variable\n auto &var_UInt = io.DefineVariable<unsigned int>(\"myUInts\", {}, {}, {Nx},\n adios2::ConstantDims);\n\n \/\/ Verify the return type is as expected\n ::testing::StaticAssertTypeEq<decltype(var_UInt),\n adios2::Variable<unsigned int> &>();\n\n \/\/ Check bzip2 lower case and camel case\n EXPECT_NO_THROW(adios2::Operator &adiosBZip2 =\n adios.DefineOperator(\"BZip2Compressor1\", \"bzip2\"));\n EXPECT_NO_THROW(adios2::Operator &adiosBZip2 =\n adios.DefineOperator(\"BZip2Compressor2\", \"BZip2\"));\n EXPECT_THROW(adios2::Operator &adiosBZip2 =\n adios.DefineOperator(\"BZip2Compressor3\", \"bzip\"),\n std::invalid_argument);\n EXPECT_THROW(adios2::Operator &adiosBZip2 =\n adios.DefineOperator(\"BZip2Compressor4\", \"BZIP2\"),\n std::invalid_argument);\n}\n<commit_msg>Added a check for BZip2 decompression size<commit_after>#include <cstdint>\n#include <iostream>\n#include <numeric> \/\/std::iota\n#include <stdexcept>\n\n#include <adios2.h>\n\n#include <gtest\/gtest.h>\n\nclass ADIOSBZip2Wrapper : public ::testing::Test\n{\npublic:\n ADIOSBZip2Wrapper() : adios(true), io(adios.DeclareIO(\"TestADIOSBZip2\")) {}\n\nprotected:\n adios2::ADIOS adios;\n adios2::IO &io;\n};\n\nTEST_F(ADIOSBZip2Wrapper, UInt100)\n{\n \/** Application variable uints from 0 to 1000 *\/\n std::vector<uint32_t> myUInts(100);\n std::iota(myUInts.begin(), myUInts.end(), 0.f);\n const std::size_t Nx = myUInts.size();\n const std::size_t inputBytes = Nx * sizeof(uint32_t);\n\n \/\/ Define ADIOS variable\n auto &var_UInt = io.DefineVariable<uint32_t>(\"myUInts\", {}, {}, {Nx},\n adios2::ConstantDims);\n\n \/\/ Verify the return type is as expected\n ::testing::StaticAssertTypeEq<decltype(var_UInt),\n adios2::Variable<uint32_t> &>();\n\n \/\/ Define bzip2 transform\n adios2::Operator &adiosBZip2 =\n adios.DefineOperator(\"BZip2Compressor\", \"BZip2\");\n\n const unsigned int bzip2ID =\n var_UInt.AddTransform(adiosBZip2, {{\"BlockSize100K\", \"2\"}});\n\n const std::size_t estimatedSize =\n adiosBZip2.BufferMaxSize(Nx * var_UInt.m_ElementSize);\n std::vector<char> compressedBuffer(estimatedSize);\n size_t compressedSize = adiosBZip2.Compress(\n myUInts.data(), var_UInt.m_Count, var_UInt.m_ElementSize,\n var_UInt.m_Type, compressedBuffer.data(),\n var_UInt.m_OperatorsInfo[bzip2ID].Parameters);\n\n EXPECT_LE(compressedSize, estimatedSize);\n\n compressedBuffer.resize(compressedSize);\n\n \/\/ Allocate original data size\n std::vector<uint32_t> decompressedBuffer(Nx);\n size_t decompressedSize = adiosBZip2.Decompress(\n compressedBuffer.data(), compressedSize, decompressedBuffer.data(),\n decompressedBuffer.size() * sizeof(uint32_t));\n ASSERT_EQ(decompressedSize, inputBytes);\n\n \/\/ testing data recovery\n for (size_t i = 0; i < Nx; ++i)\n {\n ASSERT_EQ(decompressedBuffer[i], myUInts[i]);\n }\n}\n\nTEST_F(ADIOSBZip2Wrapper, WrongParameterValue)\n{\n \/** Application variable uints from 0 to 1000 *\/\n std::vector<unsigned int> myUInts(100);\n std::iota(myUInts.begin(), myUInts.end(), 0.f);\n const std::size_t Nx = myUInts.size();\n const std::size_t inputBytes = Nx * sizeof(unsigned int);\n\n \/\/ Define ADIOS variable\n auto &var_UInt = io.DefineVariable<unsigned int>(\"myUInts\", {}, {}, {Nx},\n adios2::ConstantDims);\n\n \/\/ Verify the return type is as expected\n ::testing::StaticAssertTypeEq<decltype(var_UInt),\n adios2::Variable<unsigned int> &>();\n\n \/\/ Define bzip2 transform\n adios2::Operator &adiosBZip2 =\n adios.DefineOperator(\"BZip2Compressor\", \"BZip2\");\n\n const unsigned int bzip2ID =\n var_UInt.AddTransform(adiosBZip2, {{\"BlockSize100K\", \"10\"}});\n\n const std::size_t estimatedSize =\n adiosBZip2.BufferMaxSize(Nx * var_UInt.m_ElementSize);\n std::vector<char> compressedBuffer(estimatedSize);\n\n EXPECT_THROW(size_t compressedSize = adiosBZip2.Compress(\n myUInts.data(), var_UInt.m_Count, var_UInt.m_ElementSize,\n var_UInt.m_Type, compressedBuffer.data(),\n var_UInt.m_OperatorsInfo[bzip2ID].Parameters),\n std::invalid_argument);\n}\n\nTEST_F(ADIOSBZip2Wrapper, WrongBZip2Name)\n{\n \/** Application variable uints from 0 to 1000 *\/\n std::vector<unsigned int> myUInts(100);\n std::iota(myUInts.begin(), myUInts.end(), 0.f);\n const std::size_t Nx = myUInts.size();\n const std::size_t inputBytes = Nx * sizeof(unsigned int);\n\n \/\/ Define ADIOS variable\n auto &var_UInt = io.DefineVariable<unsigned int>(\"myUInts\", {}, {}, {Nx},\n adios2::ConstantDims);\n\n \/\/ Verify the return type is as expected\n ::testing::StaticAssertTypeEq<decltype(var_UInt),\n adios2::Variable<unsigned int> &>();\n\n \/\/ Check bzip2 lower case and camel case\n EXPECT_NO_THROW(adios2::Operator &adiosBZip2 =\n adios.DefineOperator(\"BZip2Compressor1\", \"bzip2\"));\n EXPECT_NO_THROW(adios2::Operator &adiosBZip2 =\n adios.DefineOperator(\"BZip2Compressor2\", \"BZip2\"));\n EXPECT_THROW(adios2::Operator &adiosBZip2 =\n adios.DefineOperator(\"BZip2Compressor3\", \"bzip\"),\n std::invalid_argument);\n EXPECT_THROW(adios2::Operator &adiosBZip2 =\n adios.DefineOperator(\"BZip2Compressor4\", \"BZIP2\"),\n std::invalid_argument);\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * libMaia - maiaXmlRpcClient.cpp\n * Copyright (c) 2007 Sebastian Wiedenroth <wiedi@frubar.net>\n * and Karl Glatz\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR\n * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF\n * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \"maiaXmlRpcClient.h\"\n#include \"maiaFault.h\"\n\nMaiaXmlRpcClient::MaiaXmlRpcClient(QObject* parent) : QObject(parent),\n\tmanager(this), request() \n{\n\n\trequest.setRawHeader(\"User-Agent\", \"libmaia 0.2\");\n\trequest.setHeader(QNetworkRequest::ContentTypeHeader, \"text\/xml\");\n\n\tconnect(&manager, SIGNAL(finished(QNetworkReply*)),\n\t\tthis, SLOT(replyFinished(QNetworkReply*)));\n}\n\nMaiaXmlRpcClient::MaiaXmlRpcClient(QUrl url, QObject* parent) : QObject(parent),\n\tmanager(this), request(url)\n{\n\trequest.setRawHeader(\"User-Agent\", \"libmaia 0.2\");\n\trequest.setHeader(QNetworkRequest::ContentTypeHeader, \"text\/xml\");\n\n\tconnect(&manager, SIGNAL(finished(QNetworkReply*)),\n\t\tthis, SLOT(replyFinished(QNetworkReply*)));\n\n\tsetUrl(url);\n}\n\nvoid MaiaXmlRpcClient::setUrl(QUrl url) {\n\tif(!url.isValid())\n\t\treturn;\n\t\n\trequest.setUrl(url);\n}\n\nQNetworkReply* MaiaXmlRpcClient::call(QString method, QList<QVariant> args,\n\t\t\t\t\t\t\tQObject* responseObject, const char* responseSlot,\n\t\t\t\t\t\t\tQObject* faultObject, const char* faultSlot) {\n\tMaiaObject* call = new MaiaObject(this);\n\tconnect(call, SIGNAL(aresponse(QVariant &, QNetworkReply *)), responseObject, responseSlot);\n\tconnect(call, SIGNAL(fault(int, const QString &, QNetworkReply *)), faultObject, faultSlot);\n\n\tQNetworkReply* reply = manager.post( request,\n\t\tcall->prepareCall(method, args).toUtf8() );\n\n\tcallmap[reply] = call;\n\treturn reply;\n}\n\nvoid MaiaXmlRpcClient::replyFinished(QNetworkReply* reply) {\n\tQString response;\n\tif(!callmap.contains(reply))\n\t\treturn;\n\tif(reply->error() != QNetworkReply::NoError) {\n\t\tMaiaFault fault(-32300, reply->errorString());\n\t\tresponse = fault.toString();\n\t} else {\n\t\tresponse = QString::fromUtf8(reply->readAll());\n\t}\n\t\n\t\/\/ parseResponse deletes the MaiaObject\n\tcallmap[reply]->parseResponse(response, reply);\n\tdelete reply;\n\tcallmap.remove(reply);\n}\n<commit_msg>bugfix: use deleteLater() for the reply<commit_after>\/*\n * libMaia - maiaXmlRpcClient.cpp\n * Copyright (c) 2007 Sebastian Wiedenroth <wiedi@frubar.net>\n * and Karl Glatz\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR\n * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF\n * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \"maiaXmlRpcClient.h\"\n#include \"maiaFault.h\"\n\nMaiaXmlRpcClient::MaiaXmlRpcClient(QObject* parent) : QObject(parent),\n\tmanager(this), request() \n{\n\n\trequest.setRawHeader(\"User-Agent\", \"libmaia 0.2\");\n\trequest.setHeader(QNetworkRequest::ContentTypeHeader, \"text\/xml\");\n\n\tconnect(&manager, SIGNAL(finished(QNetworkReply*)),\n\t\tthis, SLOT(replyFinished(QNetworkReply*)));\n}\n\nMaiaXmlRpcClient::MaiaXmlRpcClient(QUrl url, QObject* parent) : QObject(parent),\n\tmanager(this), request(url)\n{\n\trequest.setRawHeader(\"User-Agent\", \"libmaia 0.2\");\n\trequest.setHeader(QNetworkRequest::ContentTypeHeader, \"text\/xml\");\n\n\tconnect(&manager, SIGNAL(finished(QNetworkReply*)),\n\t\tthis, SLOT(replyFinished(QNetworkReply*)));\n\n\tsetUrl(url);\n}\n\nvoid MaiaXmlRpcClient::setUrl(QUrl url) {\n\tif(!url.isValid())\n\t\treturn;\n\t\n\trequest.setUrl(url);\n}\n\nQNetworkReply* MaiaXmlRpcClient::call(QString method, QList<QVariant> args,\n\t\t\t\t\t\t\tQObject* responseObject, const char* responseSlot,\n\t\t\t\t\t\t\tQObject* faultObject, const char* faultSlot) {\n\tMaiaObject* call = new MaiaObject(this);\n\tconnect(call, SIGNAL(aresponse(QVariant &, QNetworkReply *)), responseObject, responseSlot);\n\tconnect(call, SIGNAL(fault(int, const QString &, QNetworkReply *)), faultObject, faultSlot);\n\n\tQNetworkReply* reply = manager.post( request,\n\t\tcall->prepareCall(method, args).toUtf8() );\n\n\tcallmap[reply] = call;\n\treturn reply;\n}\n\nvoid MaiaXmlRpcClient::replyFinished(QNetworkReply* reply) {\n\tQString response;\n\tif(!callmap.contains(reply))\n\t\treturn;\n\tif(reply->error() != QNetworkReply::NoError) {\n\t\tMaiaFault fault(-32300, reply->errorString());\n\t\tresponse = fault.toString();\n\t} else {\n\t\tresponse = QString::fromUtf8(reply->readAll());\n\t}\n\t\n\t\/\/ parseResponse deletes the MaiaObject\n\tcallmap[reply]->parseResponse(response, reply);\n\treply->deleteLater();\n\tcallmap.remove(reply);\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ This file is part of the Marble Virtual Globe.\n\/\/\n\/\/ This program is free software licensed under the GNU LGPL. You can\n\/\/ find a copy of this license in LICENSE.txt in the top directory of\n\/\/ the source code.\n\/\/\n\/\/ Copyright 2012 Rene Kuettner <rene@bitkanal.net>\n\/\/\n\n#include \"OrbiterSatellitesModel.h\"\n\n#include <QtCore\/QUrl>\n\n#include \"MarbleDebug.h\"\n#include \"MarbleClock.h\"\n#include \"MarbleDirs.h\"\n\n#include \"mex\/planetarySats.h\"\n\n#include \"OrbiterSatellitesItem.h\"\n\nnamespace Marble {\n\nOrbiterSatellitesModel::OrbiterSatellitesModel(\n GeoDataTreeModel *treeModel,\n const PluginManager *pluginManager,\n const MarbleClock *clock )\n : TrackerPluginModel( treeModel, pluginManager ),\n m_clock( clock ),\n m_lcPlanet( QString() ),\n m_catalogs( QString() )\n{\n connect( m_clock, SIGNAL( timeChanged() ), this, SLOT( update() ) );\n}\n\nOrbiterSatellitesModel::~OrbiterSatellitesModel()\n{\n}\n\nvoid OrbiterSatellitesModel::setPlanet( const QString &planetId )\n{\n if( m_lcPlanet != planetId ) {\n\n mDebug() << \"Planet changed from\" << m_lcPlanet << \"to\" << planetId;\n m_lcPlanet = planetId;\n\n \/\/ reload catalogs\n foreach( const QString &catalog, m_catalogs ) {\n downloadFile( QUrl( catalog ), catalog.section( '\/', -1 ) );\n }\n }\n}\n\nvoid OrbiterSatellitesModel::parseFile( const QString &id,\n const QByteArray &file )\n{\n mDebug() << \"Reading orbiter catalog from:\" << id;\n QTextStream ts(file);\n\n QString planet( m_lcPlanet.left(1).toUpper() + m_lcPlanet.mid(1) );\n char *cplanet = planet.toLocal8Bit().data();\n\n beginUpdateItems();\n\n QString line = ts.readLine();\n for( ; !line.isNull(); line = ts.readLine() ) {\n\n if( line.trimmed().indexOf( \"#\" ) == 0) {\n continue;\n }\n\n QStringList elms = line.split(\", \");\n\n if( elms.size() != 13 ) {\n mDebug() << \"Skipping line:\" << elms << \"(\" << line << \")\";\n continue;\n }\n\n QString name = QString(\"%1 (%2)\").arg( elms[0], elms[1] );\n QString planet( elms[2] );\n\n if( planet.toLower() != m_lcPlanet ) {\n continue;\n }\n\n mDebug() << \"Loading orbiter object:\" << name;\n\n PlanetarySats *planSat = new PlanetarySats();\n\n planSat->setStateVector( elms[6].toFloat() - 2400000.5,\n elms[7].toFloat(), elms[8].toFloat(), elms[9].toFloat(),\n elms[10].toFloat(), elms[11].toFloat(), elms[12].toFloat() );\n\n planSat->setPlanet( cplanet );\n planSat->stateToKepler();\n\n addItem( new OrbiterSatellitesItem( name, planSat, m_clock ) );\n }\n\n endUpdateItems();\n}\n\nvoid OrbiterSatellitesModel::downloadFile(const QUrl &url, const QString &id)\n{\n \/\/ add url to list of known catalogs\n if( !m_catalogs.contains( url.toString() ) ) {\n m_catalogs.append( url.toString() );\n }\n\n TrackerPluginModel::downloadFile( url, id );\n}\n\n} \/\/ namespace Marble\n\n#include \"OrbiterSatellitesModel.moc\"\n\n<commit_msg>SatellitesPlugin: clear satellites when switching planet<commit_after>\/\/\n\/\/ This file is part of the Marble Virtual Globe.\n\/\/\n\/\/ This program is free software licensed under the GNU LGPL. You can\n\/\/ find a copy of this license in LICENSE.txt in the top directory of\n\/\/ the source code.\n\/\/\n\/\/ Copyright 2012 Rene Kuettner <rene@bitkanal.net>\n\/\/\n\n#include \"OrbiterSatellitesModel.h\"\n\n#include <QtCore\/QUrl>\n\n#include \"MarbleDebug.h\"\n#include \"MarbleClock.h\"\n#include \"MarbleDirs.h\"\n\n#include \"mex\/planetarySats.h\"\n\n#include \"OrbiterSatellitesItem.h\"\n\nnamespace Marble {\n\nOrbiterSatellitesModel::OrbiterSatellitesModel(\n GeoDataTreeModel *treeModel,\n const PluginManager *pluginManager,\n const MarbleClock *clock )\n : TrackerPluginModel( treeModel, pluginManager ),\n m_clock( clock ),\n m_lcPlanet( QString() ),\n m_catalogs( QString() )\n{\n connect( m_clock, SIGNAL( timeChanged() ), this, SLOT( update() ) );\n}\n\nOrbiterSatellitesModel::~OrbiterSatellitesModel()\n{\n}\n\nvoid OrbiterSatellitesModel::setPlanet( const QString &planetId )\n{\n if( m_lcPlanet != planetId ) {\n\n mDebug() << \"Planet changed from\" << m_lcPlanet << \"to\" << planetId;\n m_lcPlanet = planetId;\n\n \/\/ reload catalogs\n foreach( const QString &catalog, m_catalogs ) {\n downloadFile( QUrl( catalog ), catalog.section( '\/', -1 ) );\n }\n }\n}\n\nvoid OrbiterSatellitesModel::parseFile( const QString &id,\n const QByteArray &file )\n{\n mDebug() << \"Reading orbiter catalog from:\" << id;\n QTextStream ts(file);\n\n QString planet( m_lcPlanet.left(1).toUpper() + m_lcPlanet.mid(1) );\n char *cplanet = planet.toLocal8Bit().data();\n\n clear();\n\n beginUpdateItems();\n\n QString line = ts.readLine();\n for( ; !line.isNull(); line = ts.readLine() ) {\n\n if( line.trimmed().indexOf( \"#\" ) == 0) {\n continue;\n }\n\n QStringList elms = line.split(\", \");\n\n if( elms.size() != 13 ) {\n mDebug() << \"Skipping line:\" << elms << \"(\" << line << \")\";\n continue;\n }\n\n QString name = QString(\"%1 (%2)\").arg( elms[0], elms[1] );\n QString planet( elms[2] );\n\n if( planet.toLower() != m_lcPlanet ) {\n continue;\n }\n\n mDebug() << \"Loading orbiter object:\" << name;\n\n PlanetarySats *planSat = new PlanetarySats();\n\n planSat->setStateVector( elms[6].toFloat() - 2400000.5,\n elms[7].toFloat(), elms[8].toFloat(), elms[9].toFloat(),\n elms[10].toFloat(), elms[11].toFloat(), elms[12].toFloat() );\n\n planSat->setPlanet( cplanet );\n planSat->stateToKepler();\n\n addItem( new OrbiterSatellitesItem( name, planSat, m_clock ) );\n }\n\n endUpdateItems();\n}\n\nvoid OrbiterSatellitesModel::downloadFile(const QUrl &url, const QString &id)\n{\n \/\/ add url to list of known catalogs\n if( !m_catalogs.contains( url.toString() ) ) {\n m_catalogs.append( url.toString() );\n }\n\n TrackerPluginModel::downloadFile( url, id );\n}\n\n} \/\/ namespace Marble\n\n#include \"OrbiterSatellitesModel.moc\"\n\n<|endoftext|>"} {"text":"<commit_before>#include \"RichHdrWrapper.h\"\n#include \"PEFile.h\"\n#include <iostream>\n\nbool RichHdrWrapper::wrap()\n{\n this->richSign = m_PE->getRichHeaderSign();\n this->dansHdr = m_PE->getRichHeaderBgn(richSign);\n this->compIdCounter = this->compIdCount();\n return true;\n}\n\n\nvoid* RichHdrWrapper::getPtr()\n{\n RICH_SIGNATURE* richSign = m_PE->getRichHeaderSign();\n if (!richSign) {\n return nullptr;\n }\n RICH_DANS_HEADER* dansHdr = m_PE->getRichHeaderBgn(richSign);\n if (!dansHdr) {\n return nullptr;\n }\n return (void*)dansHdr;\n}\n\nsize_t RichHdrWrapper::compIdCount()\n{\n if (!this->richSign || !this->dansHdr) {\n return 0;\n }\n const RICH_DANS_HEADER dans_empty = { 0 };\n const bufsize_t dif = ((ULONGLONG)richSign - (ULONGLONG)dansHdr) - (sizeof(dans_empty.dansId) + sizeof(dans_empty.cPad));\n bufsize_t count = dif \/ sizeof(RICH_COMP_ID);\n return (size_t) count;\n}\n\nbufsize_t RichHdrWrapper::getSize()\n{\n if (!this->richSign || !this->dansHdr) {\n return 0;\n }\n const size_t cnt = this->compIdCounter - 1;\n const bufsize_t dif = sizeof(RICH_DANS_HEADER) + sizeof(RICH_SIGNATURE) + (sizeof(RICH_COMP_ID) * cnt);\n return dif;\n}\n\nsize_t RichHdrWrapper::getFieldsCount()\n{\n if (getSize() == 0) return 0;\n return this->compIdCounter + FIELD_COUNTER - 1;\n}\n\nvoid* RichHdrWrapper::getFieldPtr(size_t fieldId, size_t subField)\n{\n if (!this->richSign || !this->dansHdr) {\n return 0;\n }\n\n const size_t cnt = this->compIdCounter - 1;\n switch (fieldId) {\n case DANS_ID: return (void*) &dansHdr->dansId;\n case CPAD0: return (void*) &dansHdr->cPad[0];\n case CPAD1: return (void*) &dansHdr->cPad[1];\n case CPAD2: return (void*) &dansHdr->cPad[2];\n \/\/case COMP_ID_1: return (void*) &dansHdr->compId;\n \/\/case RICH_ID: return (void*) &richSign->richId;\n \/\/case CHECKSUM: return (void*) &richSign->checksum;\n }\n if (fieldId >= COMP_ID_1 && fieldId <= COMP_ID_1 + cnt)\n {\n size_t compIdNum = fieldId - COMP_ID_1;\n return (void*)(ULONGLONG(&dansHdr->compId) + (sizeof(RICH_COMP_ID)*compIdNum));\n }\n if (fieldId == RICH_ID + cnt) return (void*) &richSign->richId;\n if (fieldId == CHECKSUM + cnt) return (void*) &richSign->checksum;\n return (void*) dansHdr;\n}\n\nQString RichHdrWrapper::getFieldName(size_t fieldId)\n{\n if (!this->richSign || !this->dansHdr) {\n return \"\";\n }\n const size_t cnt = this->compIdCounter - 1;\n\n switch (fieldId) {\n case DANS_ID: return(\"DanS ID\");\n case CPAD0: case CPAD1: case CPAD2: return (\"Checksumed padding\");\n }\n if (fieldId >= COMP_ID_1 && fieldId <= COMP_ID_1 + cnt)\n {\n return(\"Comp ID\");\n }\n if (fieldId == RICH_ID + cnt) return(\"Rich ID\");\n if (fieldId == CHECKSUM + cnt) return(\"Checksum\");\n return \"\";\n}\n\nExecutable::addr_type RichHdrWrapper::containsAddrType(uint32_t fieldId, uint32_t subField)\n{\n return Executable::NOT_ADDR;\n}\n\nQString RichHdrWrapper::translateFieldContent(size_t fieldId)\n{\n if (!this->richSign || !this->dansHdr) {\n return \"\";\n }\n const uint32_t xorVal = this->richSign->checksum;\n const size_t cnt = this->compIdCounter - 1;\n bool isOk = isOk;\n uint64_t num = this->getNumValue(fieldId, &isOk);\n if (!isOk) {\n return \"\";\n }\n switch (fieldId) {\n case DANS_ID:\n case CPAD0: case CPAD1: case CPAD2: {\n uint32_t my_num = static_cast<uint32_t>(num) ^ xorVal;\n return QString::number(my_num, 16);\n }\n }\n if (fieldId >= COMP_ID_1 && fieldId <= COMP_ID_1 + cnt)\n {\n uint64_t xorVal2 = xorVal | ((uint64_t)xorVal << sizeof(uint32_t)*8);\n uint64_t my_num = static_cast<uint64_t>(num) ^ (xorVal2);\n RICH_COMP_ID* myCompId = reinterpret_cast<RICH_COMP_ID*>(&my_num);\n return QString::number(myCompId->CV, 10) + \".\" + QString::number(myCompId->prodId, 10) + \".\" + QString::number(myCompId->count, 10);\n }\n return \"\";\n}\n<commit_msg>[FEATURE] In RichHdr: added \"DanS\" and \"Rich\" keywords in description<commit_after>#include \"RichHdrWrapper.h\"\n#include \"PEFile.h\"\n#include <iostream>\n\nbool RichHdrWrapper::wrap()\n{\n this->richSign = m_PE->getRichHeaderSign();\n this->dansHdr = m_PE->getRichHeaderBgn(richSign);\n this->compIdCounter = this->compIdCount();\n return true;\n}\n\n\nvoid* RichHdrWrapper::getPtr()\n{\n RICH_SIGNATURE* richSign = m_PE->getRichHeaderSign();\n if (!richSign) {\n return nullptr;\n }\n RICH_DANS_HEADER* dansHdr = m_PE->getRichHeaderBgn(richSign);\n if (!dansHdr) {\n return nullptr;\n }\n return (void*)dansHdr;\n}\n\nsize_t RichHdrWrapper::compIdCount()\n{\n if (!this->richSign || !this->dansHdr) {\n return 0;\n }\n const RICH_DANS_HEADER dans_empty = { 0 };\n const bufsize_t dif = ((ULONGLONG)richSign - (ULONGLONG)dansHdr) - (sizeof(dans_empty.dansId) + sizeof(dans_empty.cPad));\n bufsize_t count = dif \/ sizeof(RICH_COMP_ID);\n return (size_t) count;\n}\n\nbufsize_t RichHdrWrapper::getSize()\n{\n if (!this->richSign || !this->dansHdr) {\n return 0;\n }\n const size_t cnt = this->compIdCounter - 1;\n const bufsize_t dif = sizeof(RICH_DANS_HEADER) + sizeof(RICH_SIGNATURE) + (sizeof(RICH_COMP_ID) * cnt);\n return dif;\n}\n\nsize_t RichHdrWrapper::getFieldsCount()\n{\n if (getSize() == 0) return 0;\n return this->compIdCounter + FIELD_COUNTER - 1;\n}\n\nvoid* RichHdrWrapper::getFieldPtr(size_t fieldId, size_t subField)\n{\n if (!this->richSign || !this->dansHdr) {\n return 0;\n }\n\n const size_t cnt = this->compIdCounter - 1;\n switch (fieldId) {\n case DANS_ID: return (void*) &dansHdr->dansId;\n case CPAD0: return (void*) &dansHdr->cPad[0];\n case CPAD1: return (void*) &dansHdr->cPad[1];\n case CPAD2: return (void*) &dansHdr->cPad[2];\n \/\/case COMP_ID_1: return (void*) &dansHdr->compId;\n \/\/case RICH_ID: return (void*) &richSign->richId;\n \/\/case CHECKSUM: return (void*) &richSign->checksum;\n }\n if (fieldId >= COMP_ID_1 && fieldId <= COMP_ID_1 + cnt)\n {\n size_t compIdNum = fieldId - COMP_ID_1;\n return (void*)(ULONGLONG(&dansHdr->compId) + (sizeof(RICH_COMP_ID)*compIdNum));\n }\n if (fieldId == RICH_ID + cnt) return (void*) &richSign->richId;\n if (fieldId == CHECKSUM + cnt) return (void*) &richSign->checksum;\n return (void*) dansHdr;\n}\n\nQString RichHdrWrapper::getFieldName(size_t fieldId)\n{\n if (!this->richSign || !this->dansHdr) {\n return \"\";\n }\n const size_t cnt = this->compIdCounter - 1;\n\n switch (fieldId) {\n case DANS_ID: return(\"DanS ID\");\n case CPAD0: case CPAD1: case CPAD2: return (\"Checksumed padding\");\n }\n if (fieldId >= COMP_ID_1 && fieldId <= COMP_ID_1 + cnt)\n {\n return(\"Comp ID\");\n }\n if (fieldId == RICH_ID + cnt) return(\"Rich ID\");\n if (fieldId == CHECKSUM + cnt) return(\"Checksum\");\n return \"\";\n}\n\nExecutable::addr_type RichHdrWrapper::containsAddrType(uint32_t fieldId, uint32_t subField)\n{\n return Executable::NOT_ADDR;\n}\n\nQString RichHdrWrapper::translateFieldContent(size_t fieldId)\n{\n if (!this->richSign || !this->dansHdr) {\n return \"\";\n }\n const uint32_t xorVal = this->richSign->checksum;\n const size_t cnt = this->compIdCounter - 1;\n\n bool isOk = isOk;\n uint64_t num = this->getNumValue(fieldId, &isOk);\n if (!isOk) {\n return \"?\";\n }\n switch (fieldId) {\n case DANS_ID:\n case CPAD0: case CPAD1: case CPAD2: {\n uint32_t my_num = static_cast<uint32_t>(num) ^ xorVal;\n if (my_num == DANS_HDR_MAGIC) return \"DanS\";\n return QString::number(my_num, 16);\n }\n }\n if (fieldId >= COMP_ID_1 && fieldId <= COMP_ID_1 + cnt)\n {\n uint64_t xorVal2 = xorVal | ((uint64_t)xorVal << sizeof(uint32_t)*8);\n uint64_t my_num = static_cast<uint64_t>(num) ^ (xorVal2);\n RICH_COMP_ID* myCompId = reinterpret_cast<RICH_COMP_ID*>(&my_num);\n return QString::number(myCompId->CV, 10) + \".\" + QString::number(myCompId->prodId, 10) + \".\" + QString::number(myCompId->count, 10);\n }\n if (fieldId == RICH_ID + cnt) {\n if (static_cast<uint32_t>(num) == RICH_HDR_MAGIC) return \"Rich\";\n }\n return \"\";\n}\n<|endoftext|>"} {"text":"<commit_before>\/**************************************************************************\n * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *\n * *\n * Author: The ALICE Off-line Project. *\n * Contributors are mentioned in the code where appropriate. *\n * *\n * Permission to use, copy, modify and distribute this software and its *\n * documentation strictly for non-commercial purposes is hereby granted *\n * without fee, provided that the above copyright notice appears in all *\n * copies and that both the copyright notice and this permission notice *\n * appear in the supporting documentation. The authors make no claims *\n * about the suitability of this software for any purpose. It is *\n * provided \"as is\" without express or implied warranty. *\n **************************************************************************\/\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ \/\/\n\/\/ Base class for the calibration components using \n\/\/ as input TPCseeds and ESDs\n\/\/ Event loop outside of the component\n\/\/\n\/\/\n\/\/ Base functionality to be implemeneted by component \n\/* \n \/\/In some cases only one of this function to be implemented\n virtual void Process(AliESDEvent *event)\n virtual void Process(AliTPCseed *track)\n \/\/\n virtual Long64_t Merge(TCollection *li);\n virtual void Analyze()\n void Terminate();\n*\/\n\/\/ Functionality provided by base class for Algorith debuging:\n\/\/ TTreeSRedirector * cstream = GetDebugStreamer() - get debug streamer which can be use for numerical debugging\n\/\/ \n\n\n\n\/\/ marian.ivanov@cern.ch\n\/\/ \n#include \"AliTPCcalibBase.h\"\n#include \"TSystem.h\"\n#include \"TFile.h\"\n#include \"TTreeStream.h\"\n#include \"TTimeStamp.h\"\n#include \"TGraph.h\"\n#include \"TGraphErrors.h\"\n#include \"TF1.h\"\n#include \"TH1.h\"\n#include \"THnSparse.h\"\n#include \"TH1D.h\"\n#include \"TH2D.h\"\n#include \"TAxis.h\"\n\n\n#include \"AliLog.h\"\n#include \"AliESDEvent.h\"\n\n\nClassImp(AliTPCcalibBase)\n\nAliTPCcalibBase::AliTPCcalibBase():\n TNamed(),\n fDebugStreamer(0),\n fStreamLevel(0), \n fRun(0), \/\/! current Run number\n fEvent(0), \/\/! current Event number\n fTime(0), \/\/! current Time\n fTrigger(0), \/\/! current trigger type\n fMagF(0), \/\/! current magnetic field\n fTriggerMaskReject(-1), \/\/trigger mask - reject trigger\n fTriggerMaskAccept(-1), \/\/trigger mask - accept trigger\n fHasLaser(kFALSE), \/\/flag the laser is overlayed with given event \n fRejectLaser(kTRUE), \/\/flag- reject laser\n fTriggerClass(),\n fCurrentEvent(0), \/\/! current event\n fCurrentTrack(0), \/\/! current esd track\n fCurrentFriendTrack(0), \/\/! current esd track\n fCurrentSeed(0), \/\/! current seed\n fDebugLevel(0)\n{\n \/\/\n \/\/ Constructor\n \/\/\n}\n\nAliTPCcalibBase::AliTPCcalibBase(const char * name, const char * title):\n TNamed(name,title),\n fDebugStreamer(0),\n fStreamLevel(0), \n fRun(0), \/\/! current Run number\n fEvent(0), \/\/! current Event number\n fTime(0), \/\/! current Time\n fTrigger(0), \/\/! current trigger type\n fMagF(0), \/\/! current magnetic field\n fTriggerMaskReject(-1), \/\/trigger mask - reject trigger\n fTriggerMaskAccept(-1), \/\/trigger mask - accept trigger\n fHasLaser(kFALSE), \/\/flag the laser is overlayed with given event \n fRejectLaser(kTRUE), \/\/flag- reject laser\n fTriggerClass(),\n fCurrentEvent(0), \/\/! current event\n fCurrentTrack(0), \/\/! current esd track\n fCurrentFriendTrack(0), \/\/! current esd track\n fCurrentSeed(0), \/\/! current seed\n fDebugLevel(0)\n{\n \/\/\n \/\/ Constructor\n \/\/\n}\n\nAliTPCcalibBase::AliTPCcalibBase(const AliTPCcalibBase&calib):\n TNamed(calib),\n fDebugStreamer(0),\n fStreamLevel(calib.fStreamLevel),\n fRun(0), \/\/! current Run number\n fEvent(0), \/\/! current Event number\n fTime(0), \/\/! current Time\n fTrigger(0), \/\/! current trigger type\n fMagF(0), \/\/! current magnetic field\n fTriggerMaskReject(calib.fTriggerMaskReject), \/\/trigger mask - reject trigger\n fTriggerMaskAccept(calib.fTriggerMaskAccept), \/\/trigger mask - accept trigger\n fHasLaser(calib.fHasLaser), \/\/flag the laser is overlayed with given event\n fRejectLaser(calib.fRejectLaser), \/\/flag- reject laser\n fTriggerClass(calib.fTriggerClass),\n fCurrentEvent(0), \/\/! current event\n fCurrentTrack(0), \/\/! current esd track\n fCurrentFriendTrack(0), \/\/! current esd track\n fCurrentSeed(0), \/\/! current seed\n fDebugLevel(calib.fDebugLevel)\n{\n \/\/\n \/\/ copy constructor\n \/\/\n}\n\nAliTPCcalibBase &AliTPCcalibBase::operator=(const AliTPCcalibBase&calib){\n \/\/\n \/\/ operator=\n \/\/\n ((TNamed *)this)->operator=(calib);\n fDebugStreamer=0;\n fStreamLevel=calib.fStreamLevel;\n fDebugLevel=calib.fDebugLevel;\n return *this;\n}\n\n\nAliTPCcalibBase::~AliTPCcalibBase() {\n \/\/\n \/\/ destructor\n \/\/\n if (fDebugLevel>0) printf(\"AliTPCcalibBase::~AliTPCcalibBase\\n\");\n if (fDebugStreamer) delete fDebugStreamer;\n fDebugStreamer=0;\n}\n\nvoid AliTPCcalibBase::Terminate(){\n \/\/\n \/\/\n \/\/\n if (fDebugLevel>0) printf(\"AliTPCcalibBase::Terminate\\n\");\n if (fDebugStreamer) delete fDebugStreamer;\n fDebugStreamer = 0;\n return;\n}\n\nTTreeSRedirector *AliTPCcalibBase::GetDebugStreamer(){\n \/\/\n \/\/ Get Debug streamer\n \/\/ In case debug streamer not yet initialized and StreamLevel>0 create new one\n \/\/\n if (fStreamLevel==0) return 0;\n if (fDebugStreamer) return fDebugStreamer;\n TString dsName;\n dsName=GetName();\n dsName+=\"Debug.root\";\n dsName.ReplaceAll(\" \",\"\"); \n fDebugStreamer = new TTreeSRedirector(dsName.Data());\n return fDebugStreamer;\n}\n\n\nvoid AliTPCcalibBase::UpdateEventInfo(AliESDEvent * event){\n \/\/\n \/\/\n \/\/\n fRun = event->GetRunNumber();\n fEvent = event->GetEventNumberInFile();\n fTime = event->GetTimeStamp();\n fTrigger = event->GetTriggerMask();\n fMagF = event->GetMagneticField();\n fTriggerClass = event->GetFiredTriggerClasses().Data();\n fHasLaser = HasLaser(event); \n \n}\n\n\nBool_t AliTPCcalibBase::HasLaser(AliESDEvent *event){\n \/\/\n \/\/\n \/\/\n \/\/ Thresholds more than 8 tracks with small dip angle\n \n const Int_t kMinLaserTracks = 8;\n const Float_t kThrLaser = 0.3;\n const Float_t kLaserTgl = 0.01;\n\n Int_t ntracks = event->GetNumberOfTracks();\n if (ntracks<kMinLaserTracks) return kFALSE;\n Float_t nlaser=0;\n Float_t nall=0;\n for (Int_t i=0;i<ntracks;++i) {\n AliESDtrack *track=event->GetTrack(i);\n if (!track) continue;\n if (track->GetTPCNcls()<=0) continue; \n nall++;\n if (TMath::Abs(track->GetTgl())<kLaserTgl) nlaser++;\n }\n if (nlaser>kMinLaserTracks) return kTRUE;\n if (nall>0 && nlaser\/nall>kThrLaser) return kTRUE;\n return kFALSE;\n}\n\n\n\nBool_t AliTPCcalibBase::AcceptTrigger(){\n \/\/\n \/\/ Apply trigger mask - Don't do calibration for non proper triggers\n \/\/ \n if (fTriggerMaskReject==(Int_t)fTrigger) return kFALSE;\n if (fTriggerMaskAccept>0 && fTriggerMaskAccept!=(Int_t)fTrigger) return kFALSE;\n if (fHasLaser && fRejectLaser) return kFALSE;\n return kTRUE;\n}\n\n\nvoid AliTPCcalibBase::RegisterDebugOutput(const char *path){\n \/\/\n \/\/ store - copy debug output to the destination position\n \/\/ currently ONLY for local copy\n if (fDebugLevel>0) printf(\"AliTPCcalibBase::RegisterDebugOutput(%s)\\n\",path);\n if (fStreamLevel==0) return;\n TString dsName;\n dsName=GetName();\n dsName+=\"Debug.root\";\n dsName.ReplaceAll(\" \",\"\"); \n TString dsName2=path;\n gSystem->MakeDirectory(dsName2.Data());\n dsName2+=gSystem->HostName();\n gSystem->MakeDirectory(dsName2.Data());\n dsName2+=\"\/\";\n TTimeStamp s;\n dsName2+=Int_t(s.GetNanoSec());\n dsName2+=\"\/\";\n gSystem->MakeDirectory(dsName2.Data());\n dsName2+=dsName;\n AliInfo(Form(\"copy %s\\t%s\\n\",dsName.Data(),dsName2.Data()));\n printf(\"copy %s\\t%s\\n\",dsName.Data(),dsName2.Data());\n TFile::Cp(dsName.Data(),dsName2.Data());\n}\n\n\n\nTGraphErrors * AliTPCcalibBase::FitSlices(THnSparse *h, Int_t axisDim1, Int_t axisDim2, Int_t minEntries, Int_t nmaxBin, Float_t fracLow, Float_t fracUp, Bool_t useMedian, TTreeSRedirector *cstream, Int_t ival){\n \/\/\n \/\/ Fitting slices of the projection(axisDim1,axisDim2) of a sparse histogram\n \/\/ \n TF1 funcGaus(\"funcGaus\",\"gaus\");\n TH2D * hist = h->Projection(axisDim1, axisDim2);\n Double_t *xvec = new Double_t[hist->GetNbinsX()];\n Double_t *yvec = new Double_t[hist->GetNbinsX()];\n Double_t *xerr = new Double_t[hist->GetNbinsX()];\n Double_t *yerr = new Double_t[hist->GetNbinsX()];\n Int_t counter = 0;\n TH1D * projectionHist =0;\n \/\/\n\n for(Int_t i=1; i <= hist->GetNbinsX(); i++) {\n Int_t nsum=0;\n Int_t imin = i;\n Int_t imax = i;\n\n for (Int_t idelta=0; idelta<nmaxBin; idelta++){\n \/\/\n imin = TMath::Max(i-idelta,1);\n imax = TMath::Min(i+idelta,hist->GetNbinsX());\n nsum = TMath::Nint(hist->Integral(imin,imax,0,hist->GetNbinsY()));\n if (nsum==0) break;\n if (nsum>minEntries) break;\n }\n if (nsum<minEntries) continue;\n \/\/\n hist->GetXaxis()->SetRange(imin,imax);\n projectionHist = hist->ProjectionY(\"gain\",imin,imax);\n \/\/ Determine Median:\n Float_t xMin = projectionHist->GetXaxis()->GetXmin();\n Float_t xMax = projectionHist->GetXaxis()->GetXmax();\n Float_t xMedian = (xMin+xMax)*0.5;\n Float_t integral = 0;\n for(Int_t jbin=1; jbin<projectionHist->GetNbinsX()-1; jbin++) {\n integral+=projectionHist->GetBinContent(jbin);\n }\n \/\/printf(\"Integral %f\\t%f\\n\",integral, projectionHist->GetSum());\n \/\/\n \/\/\n Float_t currentSum=0;\n for(Int_t jbin=1; jbin<projectionHist->GetNbinsX()-1; jbin++) {\n currentSum += projectionHist->GetBinContent(jbin);\n if (currentSum<fracLow*integral) xMin = projectionHist->GetBinCenter(jbin);\n if (currentSum<fracUp*integral) xMax = projectionHist->GetBinCenter(jbin+1); \n if (currentSum<0.5*integral && projectionHist->GetBinContent(jbin)>0){\n\txMedian = (projectionHist->GetBinCenter(jbin)*projectionHist->GetBinContent(jbin)+\n\t\t projectionHist->GetBinCenter(jbin+1)*projectionHist->GetBinContent(jbin+1))\/\n\t (projectionHist->GetBinContent(jbin)+projectionHist->GetBinContent(jbin+1));\n }\n }\n \/\/\n Float_t rms = projectionHist->GetRMS();\n \/\/ i += interval;\n \/\/\n Double_t xcenter = hist->GetMean(); \n Double_t xrms = hist->GetRMS()+hist->GetXaxis()->GetBinWidth(1)\/TMath::Sqrt(12.); \n Double_t binWidth = projectionHist->GetXaxis()->GetBinWidth(1);\n if (rms>0){\n \/\/ cut on +- 4 RMS\n projectionHist->Fit(&funcGaus,\"QN\",\"\",xMin, xMax);\n Double_t chi2 = funcGaus.GetChisquare();\n \/\/ \n xvec[counter] = xcenter;\n yvec[counter] = funcGaus.GetParameter(ival);\n xerr[counter] = xrms;\n yerr[counter] = funcGaus.GetParError(ival); \n if (useMedian) yvec[counter] = xMedian;\n if (cstream){\n\t(*cstream)<<\"fitDebug\"<<\n\t \"xcenter=\"<<xcenter<<\n\t \"xMin=\"<<xMin<<\n\t \"xMax=\"<<xMax<<\n\t \"xMedian=\"<<xMedian<<\n\t \"xFitM\"<<yvec[counter]<<\n\t \"xFitS\"<<yerr[counter]<<\n\t \"chi2=\"<<chi2<<\t \n\t \"\\n\";\n }\n counter++;\n }else{\n xvec[counter] = xcenter;\n yvec[counter] = xMedian;\n xerr[counter] = xrms;\n yerr[counter] = binWidth\/TMath::Sqrt(12.); \n counter++;\n }\n delete projectionHist;\n }\n \n TGraphErrors * graphErrors = new TGraphErrors(counter, xvec, yvec, xerr, yerr);\n delete [] xvec;\n delete [] yvec;\n delete [] xerr;\n delete [] yerr;\n delete hist;\n return graphErrors;\n}\n\n\nvoid AliTPCcalibBase::BinLogX(THnSparse *h, Int_t axisDim) {\n\n \/\/ Method for the correct logarithmic binning of histograms\n\n TAxis *axis = h->GetAxis(axisDim);\n int bins = axis->GetNbins();\n\n Double_t from = axis->GetXmin();\n Double_t to = axis->GetXmax();\n Double_t *new_bins = new Double_t[bins + 1];\n\n new_bins[0] = from;\n Double_t factor = pow(to\/from, 1.\/bins);\n\n for (int i = 1; i <= bins; i++) {\n new_bins[i] = factor * new_bins[i-1];\n }\n axis->Set(bins, new_bins);\n delete [] new_bins;\n\n}\nvoid AliTPCcalibBase::BinLogX(TH1 *h) {\n\n \/\/ Method for the correct logarithmic binning of histograms\n\n TAxis *axis = h->GetXaxis();\n int bins = axis->GetNbins();\n\n Double_t from = axis->GetXmin();\n Double_t to = axis->GetXmax();\n Double_t *new_bins = new Double_t[bins + 1];\n\n new_bins[0] = from;\n Double_t factor = pow(to\/from, 1.\/bins);\n\n for (int i = 1; i <= bins; i++) {\n new_bins[i] = factor * new_bins[i-1];\n }\n axis->Set(bins, new_bins);\n delete [] new_bins;\n\n}\n<commit_msg>Use event specie to identufy laser events (Marian)<commit_after>\/**************************************************************************\n * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *\n * *\n * Author: The ALICE Off-line Project. *\n * Contributors are mentioned in the code where appropriate. *\n * *\n * Permission to use, copy, modify and distribute this software and its *\n * documentation strictly for non-commercial purposes is hereby granted *\n * without fee, provided that the above copyright notice appears in all *\n * copies and that both the copyright notice and this permission notice *\n * appear in the supporting documentation. The authors make no claims *\n * about the suitability of this software for any purpose. It is *\n * provided \"as is\" without express or implied warranty. *\n **************************************************************************\/\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ \/\/\n\/\/ Base class for the calibration components using \n\/\/ as input TPCseeds and ESDs\n\/\/ Event loop outside of the component\n\/\/\n\/\/\n\/\/ Base functionality to be implemeneted by component \n\/* \n \/\/In some cases only one of this function to be implemented\n virtual void Process(AliESDEvent *event)\n virtual void Process(AliTPCseed *track)\n \/\/\n virtual Long64_t Merge(TCollection *li);\n virtual void Analyze()\n void Terminate();\n*\/\n\/\/ Functionality provided by base class for Algorith debuging:\n\/\/ TTreeSRedirector * cstream = GetDebugStreamer() - get debug streamer which can be use for numerical debugging\n\/\/ \n\n\n\n\/\/ marian.ivanov@cern.ch\n\/\/ \n#include \"AliTPCcalibBase.h\"\n#include \"TSystem.h\"\n#include \"TFile.h\"\n#include \"TTreeStream.h\"\n#include \"TTimeStamp.h\"\n#include \"TGraph.h\"\n#include \"TGraphErrors.h\"\n#include \"TF1.h\"\n#include \"TH1.h\"\n#include \"THnSparse.h\"\n#include \"TH1D.h\"\n#include \"TH2D.h\"\n#include \"TAxis.h\"\n#include \"AliRecoParam.h\"\n\n\n#include \"AliLog.h\"\n#include \"AliESDEvent.h\"\n\n\nClassImp(AliTPCcalibBase)\n\nAliTPCcalibBase::AliTPCcalibBase():\n TNamed(),\n fDebugStreamer(0),\n fStreamLevel(0), \n fRun(0), \/\/! current Run number\n fEvent(0), \/\/! current Event number\n fTime(0), \/\/! current Time\n fTrigger(0), \/\/! current trigger type\n fMagF(0), \/\/! current magnetic field\n fTriggerMaskReject(-1), \/\/trigger mask - reject trigger\n fTriggerMaskAccept(-1), \/\/trigger mask - accept trigger\n fHasLaser(kFALSE), \/\/flag the laser is overlayed with given event \n fRejectLaser(kTRUE), \/\/flag- reject laser\n fTriggerClass(),\n fCurrentEvent(0), \/\/! current event\n fCurrentTrack(0), \/\/! current esd track\n fCurrentFriendTrack(0), \/\/! current esd track\n fCurrentSeed(0), \/\/! current seed\n fDebugLevel(0)\n{\n \/\/\n \/\/ Constructor\n \/\/\n}\n\nAliTPCcalibBase::AliTPCcalibBase(const char * name, const char * title):\n TNamed(name,title),\n fDebugStreamer(0),\n fStreamLevel(0), \n fRun(0), \/\/! current Run number\n fEvent(0), \/\/! current Event number\n fTime(0), \/\/! current Time\n fTrigger(0), \/\/! current trigger type\n fMagF(0), \/\/! current magnetic field\n fTriggerMaskReject(-1), \/\/trigger mask - reject trigger\n fTriggerMaskAccept(-1), \/\/trigger mask - accept trigger\n fHasLaser(kFALSE), \/\/flag the laser is overlayed with given event \n fRejectLaser(kTRUE), \/\/flag- reject laser\n fTriggerClass(),\n fCurrentEvent(0), \/\/! current event\n fCurrentTrack(0), \/\/! current esd track\n fCurrentFriendTrack(0), \/\/! current esd track\n fCurrentSeed(0), \/\/! current seed\n fDebugLevel(0)\n{\n \/\/\n \/\/ Constructor\n \/\/\n}\n\nAliTPCcalibBase::AliTPCcalibBase(const AliTPCcalibBase&calib):\n TNamed(calib),\n fDebugStreamer(0),\n fStreamLevel(calib.fStreamLevel),\n fRun(0), \/\/! current Run number\n fEvent(0), \/\/! current Event number\n fTime(0), \/\/! current Time\n fTrigger(0), \/\/! current trigger type\n fMagF(0), \/\/! current magnetic field\n fTriggerMaskReject(calib.fTriggerMaskReject), \/\/trigger mask - reject trigger\n fTriggerMaskAccept(calib.fTriggerMaskAccept), \/\/trigger mask - accept trigger\n fHasLaser(calib.fHasLaser), \/\/flag the laser is overlayed with given event\n fRejectLaser(calib.fRejectLaser), \/\/flag- reject laser\n fTriggerClass(calib.fTriggerClass),\n fCurrentEvent(0), \/\/! current event\n fCurrentTrack(0), \/\/! current esd track\n fCurrentFriendTrack(0), \/\/! current esd track\n fCurrentSeed(0), \/\/! current seed\n fDebugLevel(calib.fDebugLevel)\n{\n \/\/\n \/\/ copy constructor\n \/\/\n}\n\nAliTPCcalibBase &AliTPCcalibBase::operator=(const AliTPCcalibBase&calib){\n \/\/\n \/\/ operator=\n \/\/\n ((TNamed *)this)->operator=(calib);\n fDebugStreamer=0;\n fStreamLevel=calib.fStreamLevel;\n fDebugLevel=calib.fDebugLevel;\n return *this;\n}\n\n\nAliTPCcalibBase::~AliTPCcalibBase() {\n \/\/\n \/\/ destructor\n \/\/\n if (fDebugLevel>0) printf(\"AliTPCcalibBase::~AliTPCcalibBase\\n\");\n if (fDebugStreamer) delete fDebugStreamer;\n fDebugStreamer=0;\n}\n\nvoid AliTPCcalibBase::Terminate(){\n \/\/\n \/\/\n \/\/\n if (fDebugLevel>0) printf(\"AliTPCcalibBase::Terminate\\n\");\n if (fDebugStreamer) delete fDebugStreamer;\n fDebugStreamer = 0;\n return;\n}\n\nTTreeSRedirector *AliTPCcalibBase::GetDebugStreamer(){\n \/\/\n \/\/ Get Debug streamer\n \/\/ In case debug streamer not yet initialized and StreamLevel>0 create new one\n \/\/\n if (fStreamLevel==0) return 0;\n if (fDebugStreamer) return fDebugStreamer;\n TString dsName;\n dsName=GetName();\n dsName+=\"Debug.root\";\n dsName.ReplaceAll(\" \",\"\"); \n fDebugStreamer = new TTreeSRedirector(dsName.Data());\n return fDebugStreamer;\n}\n\n\nvoid AliTPCcalibBase::UpdateEventInfo(AliESDEvent * event){\n \/\/\n \/\/\n \/\/\n fRun = event->GetRunNumber();\n fEvent = event->GetEventNumberInFile();\n fTime = event->GetTimeStamp();\n fTrigger = event->GetTriggerMask();\n fMagF = event->GetMagneticField();\n fTriggerClass = event->GetFiredTriggerClasses().Data();\n fHasLaser = HasLaser(event); \n \n}\n\n\nBool_t AliTPCcalibBase::HasLaser(AliESDEvent *event){\n \/\/\n \/\/\n \/\/\n \/\/ Use event specie\n Bool_t isLaser=kFALSE;\n UInt_t specie = event->GetEventSpecie(); \/\/ select only cosmic events\n if (specie==AliRecoParam::kCalib) {\n isLaser = kTRUE;\n }\n return isLaser;\n}\n\n\n\nBool_t AliTPCcalibBase::AcceptTrigger(){\n \/\/\n \/\/ Apply trigger mask - Don't do calibration for non proper triggers\n \/\/ \n if (fTriggerMaskReject==(Int_t)fTrigger) return kFALSE;\n if (fTriggerMaskAccept>0 && fTriggerMaskAccept!=(Int_t)fTrigger) return kFALSE;\n if (fHasLaser && fRejectLaser) return kFALSE;\n return kTRUE;\n}\n\n\nvoid AliTPCcalibBase::RegisterDebugOutput(const char *path){\n \/\/\n \/\/ store - copy debug output to the destination position\n \/\/ currently ONLY for local copy\n if (fDebugLevel>0) printf(\"AliTPCcalibBase::RegisterDebugOutput(%s)\\n\",path);\n if (fStreamLevel==0) return;\n TString dsName;\n dsName=GetName();\n dsName+=\"Debug.root\";\n dsName.ReplaceAll(\" \",\"\"); \n TString dsName2=path;\n gSystem->MakeDirectory(dsName2.Data());\n dsName2+=gSystem->HostName();\n gSystem->MakeDirectory(dsName2.Data());\n dsName2+=\"\/\";\n TTimeStamp s;\n dsName2+=Int_t(s.GetNanoSec());\n dsName2+=\"\/\";\n gSystem->MakeDirectory(dsName2.Data());\n dsName2+=dsName;\n AliInfo(Form(\"copy %s\\t%s\\n\",dsName.Data(),dsName2.Data()));\n printf(\"copy %s\\t%s\\n\",dsName.Data(),dsName2.Data());\n TFile::Cp(dsName.Data(),dsName2.Data());\n}\n\n\n\nTGraphErrors * AliTPCcalibBase::FitSlices(THnSparse *h, Int_t axisDim1, Int_t axisDim2, Int_t minEntries, Int_t nmaxBin, Float_t fracLow, Float_t fracUp, Bool_t useMedian, TTreeSRedirector *cstream, Int_t ival){\n \/\/\n \/\/ Fitting slices of the projection(axisDim1,axisDim2) of a sparse histogram\n \/\/ \n TF1 funcGaus(\"funcGaus\",\"gaus\");\n TH2D * hist = h->Projection(axisDim1, axisDim2);\n Double_t *xvec = new Double_t[hist->GetNbinsX()];\n Double_t *yvec = new Double_t[hist->GetNbinsX()];\n Double_t *xerr = new Double_t[hist->GetNbinsX()];\n Double_t *yerr = new Double_t[hist->GetNbinsX()];\n Int_t counter = 0;\n TH1D * projectionHist =0;\n \/\/\n\n for(Int_t i=1; i <= hist->GetNbinsX(); i++) {\n Int_t nsum=0;\n Int_t imin = i;\n Int_t imax = i;\n\n for (Int_t idelta=0; idelta<nmaxBin; idelta++){\n \/\/\n imin = TMath::Max(i-idelta,1);\n imax = TMath::Min(i+idelta,hist->GetNbinsX());\n nsum = TMath::Nint(hist->Integral(imin,imax,0,hist->GetNbinsY()));\n if (nsum==0) break;\n if (nsum>minEntries) break;\n }\n if (nsum<minEntries) continue;\n \/\/\n hist->GetXaxis()->SetRange(imin,imax);\n projectionHist = hist->ProjectionY(\"gain\",imin,imax);\n \/\/ Determine Median:\n Float_t xMin = projectionHist->GetXaxis()->GetXmin();\n Float_t xMax = projectionHist->GetXaxis()->GetXmax();\n Float_t xMedian = (xMin+xMax)*0.5;\n Float_t integral = 0;\n for(Int_t jbin=1; jbin<projectionHist->GetNbinsX()-1; jbin++) {\n integral+=projectionHist->GetBinContent(jbin);\n }\n \/\/printf(\"Integral %f\\t%f\\n\",integral, projectionHist->GetSum());\n \/\/\n \/\/\n Float_t currentSum=0;\n for(Int_t jbin=1; jbin<projectionHist->GetNbinsX()-1; jbin++) {\n currentSum += projectionHist->GetBinContent(jbin);\n if (currentSum<fracLow*integral) xMin = projectionHist->GetBinCenter(jbin);\n if (currentSum<fracUp*integral) xMax = projectionHist->GetBinCenter(jbin+1); \n if (currentSum<0.5*integral && projectionHist->GetBinContent(jbin)>0){\n\txMedian = (projectionHist->GetBinCenter(jbin)*projectionHist->GetBinContent(jbin)+\n\t\t projectionHist->GetBinCenter(jbin+1)*projectionHist->GetBinContent(jbin+1))\/\n\t (projectionHist->GetBinContent(jbin)+projectionHist->GetBinContent(jbin+1));\n }\n }\n \/\/\n Float_t rms = projectionHist->GetRMS();\n \/\/ i += interval;\n \/\/\n Double_t xcenter = hist->GetMean(); \n Double_t xrms = hist->GetRMS()+hist->GetXaxis()->GetBinWidth(1)\/TMath::Sqrt(12.); \n Double_t binWidth = projectionHist->GetXaxis()->GetBinWidth(1);\n if (rms>0){\n \/\/ cut on +- 4 RMS\n projectionHist->Fit(&funcGaus,\"QN\",\"\",xMin, xMax);\n Double_t chi2 = funcGaus.GetChisquare();\n \/\/ \n xvec[counter] = xcenter;\n yvec[counter] = funcGaus.GetParameter(ival);\n xerr[counter] = xrms;\n yerr[counter] = funcGaus.GetParError(ival); \n if (useMedian) yvec[counter] = xMedian;\n if (cstream){\n\t(*cstream)<<\"fitDebug\"<<\n\t \"xcenter=\"<<xcenter<<\n\t \"xMin=\"<<xMin<<\n\t \"xMax=\"<<xMax<<\n\t \"xMedian=\"<<xMedian<<\n\t \"xFitM\"<<yvec[counter]<<\n\t \"xFitS\"<<yerr[counter]<<\n\t \"chi2=\"<<chi2<<\t \n\t \"\\n\";\n }\n counter++;\n }else{\n xvec[counter] = xcenter;\n yvec[counter] = xMedian;\n xerr[counter] = xrms;\n yerr[counter] = binWidth\/TMath::Sqrt(12.); \n counter++;\n }\n delete projectionHist;\n }\n \n TGraphErrors * graphErrors = new TGraphErrors(counter, xvec, yvec, xerr, yerr);\n delete [] xvec;\n delete [] yvec;\n delete [] xerr;\n delete [] yerr;\n delete hist;\n return graphErrors;\n}\n\n\nvoid AliTPCcalibBase::BinLogX(THnSparse *h, Int_t axisDim) {\n\n \/\/ Method for the correct logarithmic binning of histograms\n\n TAxis *axis = h->GetAxis(axisDim);\n int bins = axis->GetNbins();\n\n Double_t from = axis->GetXmin();\n Double_t to = axis->GetXmax();\n Double_t *new_bins = new Double_t[bins + 1];\n\n new_bins[0] = from;\n Double_t factor = pow(to\/from, 1.\/bins);\n\n for (int i = 1; i <= bins; i++) {\n new_bins[i] = factor * new_bins[i-1];\n }\n axis->Set(bins, new_bins);\n delete [] new_bins;\n\n}\nvoid AliTPCcalibBase::BinLogX(TH1 *h) {\n\n \/\/ Method for the correct logarithmic binning of histograms\n\n TAxis *axis = h->GetXaxis();\n int bins = axis->GetNbins();\n\n Double_t from = axis->GetXmin();\n Double_t to = axis->GetXmax();\n Double_t *new_bins = new Double_t[bins + 1];\n\n new_bins[0] = from;\n Double_t factor = pow(to\/from, 1.\/bins);\n\n for (int i = 1; i <= bins; i++) {\n new_bins[i] = factor * new_bins[i-1];\n }\n axis->Set(bins, new_bins);\n delete [] new_bins;\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2017 Sony Corporation. All Rights Reserved.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include <nbla\/computation_graph\/computation_graph.hpp>\n\n#include <algorithm>\n#include <memory>\n\nnamespace nbla {\n\nusing std::make_shared;\n\nstatic void set_function_inputs(CgFunctionPtr func,\n const vector<CgVariablePtr> &inputs) {\n \/\/ Check need_grad\n bool need_grad = false;\n int rank = 0;\n for (auto i : inputs) {\n need_grad |= i->need_grad_state();\n rank = std::max(rank, i->rank());\n i->insert_function_reference(func);\n }\n func->set_need_grad(need_grad);\n func->set_rank_(rank);\n func->set_inputs_(inputs);\n}\n\nvector<CgVariablePtr> create_function_outputs(CgFunctionPtr cg_f, int n_outputs,\n bool prohibit_clear_output) {\n \/\/ Check inplace outputs size and create outputs.\n if (n_outputs < 0) {\n n_outputs = cg_f->function()->min_outputs();\n }\n vector<CgVariablePtr> outputs(n_outputs);\n for (int i = 0; i < n_outputs; ++i) {\n auto v = make_shared<CgVariable>();\n v->set_need_grad_state(cg_f->need_grad());\n v->set_parent(cg_f);\n v->set_prohibit_clear_data(prohibit_clear_output);\n outputs[i] = v;\n }\n \/\/ Weak references are held inside.\n cg_f->set_outputs(outputs);\n \/\/ Return strong references.\n return outputs;\n}\n\nvector<CgVariablePtr> connect(CgFunctionPtr cg_f,\n const vector<CgVariablePtr> &inputs,\n int n_outputs, vector<NdArrayPtr> inplace_outputs,\n bool execute) {\n set_function_inputs(cg_f, inputs);\n\n \/\/ check if data can be cleared or not.\n bool persistent = false, inplace = false, prohibit_clear = false;\n for (int i = 0; i < inputs.size(); ++i) {\n auto inp = inputs[i];\n persistent |= inp->rank() == 0 || inp->persistent();\n prohibit_clear |= inp->prohibit_clear_data();\n inplace |= cg_f->function()->inplace_data(i) > 0;\n }\n\n bool prohibit_output_clear = (prohibit_clear || persistent) && inplace;\n\n vector<CgVariablePtr> outputs =\n create_function_outputs(cg_f, n_outputs, prohibit_output_clear);\n\n \/\/ Setup function.\n cg_f->setup();\n\n \/\/ Verify connections.\n cg_f->verify_during_forward();\n\n \/\/ Function inputs and outputs must be Variables.\n vector<Variable *> finputs(inputs.size());\n vector<Variable *> foutputs(outputs.size());\n for (int i = 0; i < inputs.size(); ++i) {\n finputs[i] = inputs[i]->variable().get();\n }\n for (int i = 0; i < outputs.size(); ++i) {\n foutputs[i] = outputs[i]->variable().get();\n }\n\n \/\/ Set array reference to function output buffer if size matches.\n for (int i = 0; i < outputs.size(); ++i) {\n if (i >= inplace_outputs.size() || !inplace_outputs[i])\n continue;\n NBLA_CHECK(inplace_outputs[i]->size() == foutputs[i]->size(),\n error_code::value,\n \"In-place array size and function output size must match. \"\n \"inplace_outputs[%d]: %d != function_output[%d]: %d.\",\n inplace_outputs[i]->size(), foutputs[i]->size());\n foutputs[i]->data()->set_array(inplace_outputs[i]->array());\n }\n\n if (execute) {\n \/\/ Execute Forward.\n cg_f->function()->forward(finputs, foutputs);\n }\n return outputs;\n}\n\nvoid steal_variable_from_to(CgVariablePtr from, CgVariablePtr to) {\n \/\/ A. The shape must the same\n NBLA_CHECK(\n to->variable()->shape() == from->variable()->shape(), error_code::value,\n \"Variable shapes of from and to must match. from != to : (%s) != (%s).\",\n string_join(from->variable()->shape(), \", \").c_str(),\n string_join(to->variable()->shape(), \", \").c_str());\n \/\/ B. Get a parent function of from\n auto parent = from->parent();\n NBLA_CHECK(parent != nullptr, error_code::value,\n \"The 1st argument CgVariablePtr must have a parent function (must \"\n \"be an output of a function.\");\n\n \/\/ C. Forget parent of from and rewire the parent function to to variable.\n from->set_parent(nullptr);\n to->set_parent(parent);\n\n \/\/ D. Replace an output variable reference of the parent function with to\n \/\/ variable.\n auto outputs = parent->outputs();\n std::replace(outputs.begin(), outputs.end(), from, to);\n parent->set_outputs(outputs);\n\n \/\/ E. Copy flags.\n to->set_allow_modify_data(from->allow_modify_data());\n if (from->need_grad_is_set()) {\n to->set_need_grad(from->need_grad());\n } else {\n to->unset_need_grad();\n }\n to->set_prohibit_clear_data(from->prohibit_clear_data());\n\n \/\/ F. Reference contents\n to->set_variable(from->variable());\n\n \/\/ G. Set setup flag.\n to->mark_need_setup();\n}\n\nvoid forward_all(const vector<CgVariablePtr> variables, bool clear_buffer,\n bool clear_no_need_grad, function_hook_type function_pre_hook,\n function_hook_type function_post_hook) {\n unordered_set<CgFunctionPtr> fclosed;\n for (int i = 0; i < variables.size(); ++i) {\n variables[i]->forward(clear_buffer, clear_no_need_grad, &fclosed,\n function_pre_hook, function_post_hook);\n }\n}\n}\n<commit_msg>[c++] Python-like API allows optional input by nullptr<commit_after>\/\/ Copyright (c) 2017 Sony Corporation. All Rights Reserved.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include <nbla\/computation_graph\/computation_graph.hpp>\n\n#include <algorithm>\n#include <memory>\n\nnamespace nbla {\n\nusing std::make_shared;\n\nstatic void set_function_inputs(CgFunctionPtr func,\n const vector<CgVariablePtr> &inputs) {\n \/\/ Check need_grad\n bool need_grad = false;\n int rank = 0;\n for (auto i : inputs) {\n need_grad |= i->need_grad_state();\n rank = std::max(rank, i->rank());\n i->insert_function_reference(func);\n }\n func->set_need_grad(need_grad);\n func->set_rank_(rank);\n func->set_inputs_(inputs);\n}\n\nvector<CgVariablePtr> create_function_outputs(CgFunctionPtr cg_f, int n_outputs,\n bool prohibit_clear_output) {\n \/\/ Check inplace outputs size and create outputs.\n if (n_outputs < 0) {\n n_outputs = cg_f->function()->min_outputs();\n }\n vector<CgVariablePtr> outputs(n_outputs);\n for (int i = 0; i < n_outputs; ++i) {\n auto v = make_shared<CgVariable>();\n v->set_need_grad_state(cg_f->need_grad());\n v->set_parent(cg_f);\n v->set_prohibit_clear_data(prohibit_clear_output);\n outputs[i] = v;\n }\n \/\/ Weak references are held inside.\n cg_f->set_outputs(outputs);\n \/\/ Return strong references.\n return outputs;\n}\n\nvector<CgVariablePtr> connect(CgFunctionPtr cg_f,\n const vector<CgVariablePtr> &inputs_orig,\n int n_outputs, vector<NdArrayPtr> inplace_outputs,\n bool execute) {\n \/\/ Filter null inputs (since cpp functions doesn't handle optional inputs in\n \/\/ functions.cpp)\n vector<CgVariablePtr> inputs;\n for (auto &inp : inputs_orig) {\n if (inp) {\n inputs.push_back(inp);\n }\n }\n\n set_function_inputs(cg_f, inputs);\n\n \/\/ check if data can be cleared or not.\n bool persistent = false, inplace = false, prohibit_clear = false;\n for (int i = 0; i < inputs.size(); ++i) {\n auto inp = inputs[i];\n persistent |= inp->rank() == 0 || inp->persistent();\n prohibit_clear |= inp->prohibit_clear_data();\n inplace |= cg_f->function()->inplace_data(i) > 0;\n }\n\n bool prohibit_output_clear = (prohibit_clear || persistent) && inplace;\n\n vector<CgVariablePtr> outputs =\n create_function_outputs(cg_f, n_outputs, prohibit_output_clear);\n\n \/\/ Setup function.\n cg_f->setup();\n\n \/\/ Verify connections.\n cg_f->verify_during_forward();\n\n \/\/ Function inputs and outputs must be Variables.\n vector<Variable *> finputs(inputs.size());\n vector<Variable *> foutputs(outputs.size());\n for (int i = 0; i < inputs.size(); ++i) {\n finputs[i] = inputs[i]->variable().get();\n }\n for (int i = 0; i < outputs.size(); ++i) {\n foutputs[i] = outputs[i]->variable().get();\n }\n\n \/\/ Set array reference to function output buffer if size matches.\n for (int i = 0; i < outputs.size(); ++i) {\n if (i >= inplace_outputs.size() || !inplace_outputs[i])\n continue;\n NBLA_CHECK(inplace_outputs[i]->size() == foutputs[i]->size(),\n error_code::value,\n \"In-place array size and function output size must match. \"\n \"inplace_outputs[%d]: %d != function_output[%d]: %d.\",\n inplace_outputs[i]->size(), foutputs[i]->size());\n foutputs[i]->data()->set_array(inplace_outputs[i]->array());\n }\n\n if (execute) {\n \/\/ Execute Forward.\n cg_f->function()->forward(finputs, foutputs);\n }\n return outputs;\n}\n\nvoid steal_variable_from_to(CgVariablePtr from, CgVariablePtr to) {\n \/\/ A. The shape must the same\n NBLA_CHECK(\n to->variable()->shape() == from->variable()->shape(), error_code::value,\n \"Variable shapes of from and to must match. from != to : (%s) != (%s).\",\n string_join(from->variable()->shape(), \", \").c_str(),\n string_join(to->variable()->shape(), \", \").c_str());\n \/\/ B. Get a parent function of from\n auto parent = from->parent();\n NBLA_CHECK(parent != nullptr, error_code::value,\n \"The 1st argument CgVariablePtr must have a parent function (must \"\n \"be an output of a function.\");\n\n \/\/ C. Forget parent of from and rewire the parent function to to variable.\n from->set_parent(nullptr);\n to->set_parent(parent);\n\n \/\/ D. Replace an output variable reference of the parent function with to\n \/\/ variable.\n auto outputs = parent->outputs();\n std::replace(outputs.begin(), outputs.end(), from, to);\n parent->set_outputs(outputs);\n\n \/\/ E. Copy flags.\n to->set_allow_modify_data(from->allow_modify_data());\n if (from->need_grad_is_set()) {\n to->set_need_grad(from->need_grad());\n } else {\n to->unset_need_grad();\n }\n to->set_prohibit_clear_data(from->prohibit_clear_data());\n\n \/\/ F. Reference contents\n to->set_variable(from->variable());\n\n \/\/ G. Set setup flag.\n to->mark_need_setup();\n}\n\nvoid forward_all(const vector<CgVariablePtr> variables, bool clear_buffer,\n bool clear_no_need_grad, function_hook_type function_pre_hook,\n function_hook_type function_post_hook) {\n unordered_set<CgFunctionPtr> fclosed;\n for (int i = 0; i < variables.size(); ++i) {\n variables[i]->forward(clear_buffer, clear_no_need_grad, &fclosed,\n function_pre_hook, function_post_hook);\n }\n}\n}\n<|endoftext|>"} {"text":"<commit_before>\/******************************************************************************\n * Copyright 2018 The Apollo Authors. All Rights Reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *****************************************************************************\/\n\n#include \"cyber\/transport\/shm\/condition_notifier.h\"\n\n#include <sys\/ipc.h>\n#include <sys\/shm.h>\n#include <thread>\n\n#include \"cyber\/common\/log.h\"\n#include \"cyber\/common\/util.h\"\n\nnamespace apollo {\nnamespace cyber {\nnamespace transport {\n\nusing common::Hash;\n\nConditionNotifier::ConditionNotifier() {\n key_ = static_cast<key_t>(Hash(\"\/apollo\/cyber\/transport\/shm\/notifier\"));\n ADEBUG << \"condition notifier key: \" << key_;\n shm_size_ = sizeof(Indicator);\n\n if (!Init()) {\n AERROR << \"fail to init condition notifier.\";\n is_shutdown_.store(true);\n return;\n }\n next_seq_ = indicator_->next_seq.load();\n ADEBUG << \"next_seq: \" << next_seq_;\n}\n\nConditionNotifier::~ConditionNotifier() { Shutdown(); }\n\nvoid ConditionNotifier::Shutdown() {\n if (is_shutdown_.exchange(true)) {\n return;\n }\n\n std::this_thread::sleep_for(std::chrono::milliseconds(100));\n Reset();\n}\n\nbool ConditionNotifier::Notify(const ReadableInfo& info) {\n if (is_shutdown_.load()) {\n ADEBUG << \"notifier is shutdown.\";\n return false;\n }\n\n uint64_t seq = indicator_->next_seq.fetch_add(1);\n uint64_t idx = seq % kBufLength;\n indicator_->infos[idx] = info;\n indicator_->seqs[idx] = seq;\n\n return true;\n}\n\nbool ConditionNotifier::Listen(int timeout_ms, ReadableInfo* info) {\n if (info == nullptr) {\n AERROR << \"info nullptr.\";\n return false;\n }\n\n if (is_shutdown_.load()) {\n ADEBUG << \"notifier is shutdown.\";\n return false;\n }\n\n int timeout_us = timeout_ms * 1000;\n while (!is_shutdown_.load()) {\n uint64_t seq = indicator_->next_seq.load();\n if (seq != next_seq_) {\n auto idx = next_seq_ % kBufLength;\n if (indicator_->seqs[idx] == next_seq_) {\n *info = indicator_->infos[idx];\n ++next_seq_;\n return true;\n } else {\n ADEBUG << \"seq[\" << next_seq_ << \"] is writing, can not read now.\";\n }\n }\n\n if (timeout_us > 0) {\n std::this_thread::sleep_for(std::chrono::microseconds(50));\n timeout_us -= 50;\n } else {\n return false;\n }\n }\n return false;\n}\n\nbool ConditionNotifier::Init() { return OpenOrCreate(); }\n\nbool ConditionNotifier::OpenOrCreate() {\n \/\/ create managed_shm_\n int retry = 0;\n int shmid = 0;\n while (retry < 2) {\n shmid = shmget(key_, shm_size_, 0644 | IPC_CREAT | IPC_EXCL);\n if (shmid != -1) {\n break;\n }\n\n if (EINVAL == errno) {\n AINFO << \"need larger space, recreate.\";\n Reset();\n Remove();\n ++retry;\n } else if (EEXIST == errno) {\n ADEBUG << \"shm already exist, open only.\";\n return OpenOnly();\n } else {\n break;\n }\n }\n\n if (shmid == -1) {\n AERROR << \"create shm failed, error code: \" << strerror(errno);\n return false;\n }\n\n \/\/ attach managed_shm_\n managed_shm_ = shmat(shmid, nullptr, 0);\n if (managed_shm_ == reinterpret_cast<void*>(-1)) {\n AERROR << \"attach shm failed.\";\n shmctl(shmid, IPC_RMID, 0);\n return false;\n }\n\n \/\/ create indicator_\n indicator_ = new (managed_shm_) Indicator();\n if (indicator_ == nullptr) {\n AERROR << \"create indicator failed.\";\n shmdt(managed_shm_);\n managed_shm_ = nullptr;\n shmctl(shmid, IPC_RMID, 0);\n return false;\n }\n\n ADEBUG << \"open or create true.\";\n return true;\n}\n\nbool ConditionNotifier::OpenOnly() {\n \/\/ get managed_shm_\n int shmid = shmget(key_, 0, 0644);\n if (shmid == -1) {\n AERROR << \"get shm failed.\";\n return false;\n }\n\n \/\/ attach managed_shm_\n managed_shm_ = shmat(shmid, nullptr, 0);\n if (managed_shm_ == reinterpret_cast<void*>(-1)) {\n AERROR << \"attach shm failed.\";\n return false;\n }\n\n \/\/ get indicator_\n indicator_ = reinterpret_cast<Indicator*>(managed_shm_);\n if (indicator_ == nullptr) {\n AERROR << \"get indicator failed.\";\n shmdt(managed_shm_);\n managed_shm_ = nullptr;\n return false;\n }\n\n ADEBUG << \"open true.\";\n return true;\n}\n\nbool ConditionNotifier::Remove() {\n int shmid = shmget(key_, 0, 0644);\n if (shmid == -1 || shmctl(shmid, IPC_RMID, 0) == -1) {\n AERROR << \"remove shm failed, error code: \" << strerror(errno);\n return false;\n }\n ADEBUG << \"remove success.\";\n\n return true;\n}\n\nvoid ConditionNotifier::Reset() {\n indicator_ = nullptr;\n if (managed_shm_ != nullptr) {\n shmdt(managed_shm_);\n managed_shm_ = nullptr;\n }\n}\n\n} \/\/ namespace transport\n} \/\/ namespace cyber\n} \/\/ namespace apollo\n<commit_msg>cyber: bug fix for condition notifier<commit_after>\/******************************************************************************\n * Copyright 2018 The Apollo Authors. All Rights Reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *****************************************************************************\/\n\n#include \"cyber\/transport\/shm\/condition_notifier.h\"\n\n#include <sys\/ipc.h>\n#include <sys\/shm.h>\n#include <thread>\n\n#include \"cyber\/common\/log.h\"\n#include \"cyber\/common\/util.h\"\n\nnamespace apollo {\nnamespace cyber {\nnamespace transport {\n\nusing common::Hash;\n\nConditionNotifier::ConditionNotifier() {\n key_ = static_cast<key_t>(Hash(\"\/apollo\/cyber\/transport\/shm\/notifier\"));\n ADEBUG << \"condition notifier key: \" << key_;\n shm_size_ = sizeof(Indicator);\n\n if (!Init()) {\n AERROR << \"fail to init condition notifier.\";\n is_shutdown_.store(true);\n return;\n }\n next_seq_ = indicator_->next_seq.load();\n ADEBUG << \"next_seq: \" << next_seq_;\n}\n\nConditionNotifier::~ConditionNotifier() { Shutdown(); }\n\nvoid ConditionNotifier::Shutdown() {\n if (is_shutdown_.exchange(true)) {\n return;\n }\n\n std::this_thread::sleep_for(std::chrono::milliseconds(100));\n Reset();\n}\n\nbool ConditionNotifier::Notify(const ReadableInfo& info) {\n if (is_shutdown_.load()) {\n ADEBUG << \"notifier is shutdown.\";\n return false;\n }\n\n uint64_t seq = indicator_->next_seq.fetch_add(1);\n uint64_t idx = seq % kBufLength;\n indicator_->infos[idx] = info;\n indicator_->seqs[idx] = seq;\n\n return true;\n}\n\nbool ConditionNotifier::Listen(int timeout_ms, ReadableInfo* info) {\n if (info == nullptr) {\n AERROR << \"info nullptr.\";\n return false;\n }\n\n if (is_shutdown_.load()) {\n ADEBUG << \"notifier is shutdown.\";\n return false;\n }\n\n int timeout_us = timeout_ms * 1000;\n while (!is_shutdown_.load()) {\n uint64_t seq = indicator_->next_seq.load();\n if (seq != next_seq_) {\n auto idx = next_seq_ % kBufLength;\n auto actual_seq = indicator_->seqs[idx];\n if (actual_seq >= next_seq_) {\n next_seq_ = actual_seq;\n *info = indicator_->infos[idx];\n ++next_seq_;\n return true;\n } else {\n ADEBUG << \"seq[\" << next_seq_ << \"] is writing, can not read now.\";\n }\n }\n\n if (timeout_us > 0) {\n std::this_thread::sleep_for(std::chrono::microseconds(50));\n timeout_us -= 50;\n } else {\n return false;\n }\n }\n return false;\n}\n\nbool ConditionNotifier::Init() { return OpenOrCreate(); }\n\nbool ConditionNotifier::OpenOrCreate() {\n \/\/ create managed_shm_\n int retry = 0;\n int shmid = 0;\n while (retry < 2) {\n shmid = shmget(key_, shm_size_, 0644 | IPC_CREAT | IPC_EXCL);\n if (shmid != -1) {\n break;\n }\n\n if (EINVAL == errno) {\n AINFO << \"need larger space, recreate.\";\n Reset();\n Remove();\n ++retry;\n } else if (EEXIST == errno) {\n ADEBUG << \"shm already exist, open only.\";\n return OpenOnly();\n } else {\n break;\n }\n }\n\n if (shmid == -1) {\n AERROR << \"create shm failed, error code: \" << strerror(errno);\n return false;\n }\n\n \/\/ attach managed_shm_\n managed_shm_ = shmat(shmid, nullptr, 0);\n if (managed_shm_ == reinterpret_cast<void*>(-1)) {\n AERROR << \"attach shm failed.\";\n shmctl(shmid, IPC_RMID, 0);\n return false;\n }\n\n \/\/ create indicator_\n indicator_ = new (managed_shm_) Indicator();\n if (indicator_ == nullptr) {\n AERROR << \"create indicator failed.\";\n shmdt(managed_shm_);\n managed_shm_ = nullptr;\n shmctl(shmid, IPC_RMID, 0);\n return false;\n }\n\n ADEBUG << \"open or create true.\";\n return true;\n}\n\nbool ConditionNotifier::OpenOnly() {\n \/\/ get managed_shm_\n int shmid = shmget(key_, 0, 0644);\n if (shmid == -1) {\n AERROR << \"get shm failed.\";\n return false;\n }\n\n \/\/ attach managed_shm_\n managed_shm_ = shmat(shmid, nullptr, 0);\n if (managed_shm_ == reinterpret_cast<void*>(-1)) {\n AERROR << \"attach shm failed.\";\n return false;\n }\n\n \/\/ get indicator_\n indicator_ = reinterpret_cast<Indicator*>(managed_shm_);\n if (indicator_ == nullptr) {\n AERROR << \"get indicator failed.\";\n shmdt(managed_shm_);\n managed_shm_ = nullptr;\n return false;\n }\n\n ADEBUG << \"open true.\";\n return true;\n}\n\nbool ConditionNotifier::Remove() {\n int shmid = shmget(key_, 0, 0644);\n if (shmid == -1 || shmctl(shmid, IPC_RMID, 0) == -1) {\n AERROR << \"remove shm failed, error code: \" << strerror(errno);\n return false;\n }\n ADEBUG << \"remove success.\";\n\n return true;\n}\n\nvoid ConditionNotifier::Reset() {\n indicator_ = nullptr;\n if (managed_shm_ != nullptr) {\n shmdt(managed_shm_);\n managed_shm_ = nullptr;\n }\n}\n\n} \/\/ namespace transport\n} \/\/ namespace cyber\n} \/\/ namespace apollo\n<|endoftext|>"} {"text":"<commit_before>\/**\n * base-n, 1.0\n * Copyright (C) 2012 Andrzej Zawadzki (azawadzki@gmail.com)\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n**\/\n#ifndef BASEN_HPP\n#define BASEN_HPP\n\n#include <algorithm>\n#include <cctype>\n#include <cassert>\n#include <cstring>\n\nnamespace bn\n{\n\ntemplate<class Iter1, class Iter2>\nvoid encode_b16(Iter1 start, Iter1 end, Iter2 out);\n\ntemplate<class Iter1, class Iter2>\nvoid encode_b32(Iter1 start, Iter1 end, Iter2 out);\n\ntemplate<class Iter1, class Iter2>\nvoid encode_b64(Iter1 start, Iter1 end, Iter2 out);\n\ntemplate<class Iter1, class Iter2>\nvoid decode_b16(Iter1 start, Iter1 end, Iter2 out);\n\ntemplate<class Iter1, class Iter2>\nvoid decode_b32(Iter1 start, Iter1 end, Iter2 out);\n\ntemplate<class Iter1, class Iter2>\nvoid decode_b64(Iter1 start, Iter1 end, Iter2 out);\n\nnamespace impl\n{\n\nconst int Error = -1;\n\nnamespace {\n\nchar extract_partial_bits(char value, size_t start_bit, size_t bits_count)\n{\n assert(start_bit + bits_count < 8);\n \/\/ shift extracted bits to the beginning of the byte\n char t1 = value >> (8 - bits_count - start_bit);\n \/\/ mask out bits on the left\n char t2 = t1 & ~(0xff << bits_count);\n return t2;\n}\n\nchar extract_overlapping_bits(char previous, char next, size_t start_bit, size_t bits_count)\n{\n assert(start_bit + bits_count < 16);\n size_t bits_count_in_previous = 8 - start_bit;\n size_t bits_count_in_next = bits_count - bits_count_in_previous;\n char t1 = previous << bits_count_in_next;\n char t2 = next >> (8 - bits_count_in_next) & ~(0xff << bits_count_in_next) ;\n return (t1 | t2) & ~(0xff << bits_count);\n}\n\n}\n\nstruct b16_conversion_traits\n{\n static size_t group_length()\n {\n return 4;\n }\n\n static char encode(unsigned int index)\n {\n const char* const dictionary = \"0123456789ABCDEF\";\n assert(index < strlen(dictionary));\n return dictionary[index];\n }\n\n static char decode(char c)\n {\n if (c >= '0' && c <= '9') {\n return c - '0';\n } else if (c >= 'A' && c <= 'F') {\n return c - 'A' + 10;\n }\n return Error;\n }\n};\n\nstruct b32_conversion_traits\n{\n static size_t group_length()\n {\n return 5;\n }\n\n static char encode(unsigned int index)\n {\n const char * dictionary = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567\";\n assert(index < strlen(dictionary));\n return dictionary[index];\n }\n\n static char decode(char c)\n {\n if (c >= 'A' && c <= 'Z') {\n return c - 'A';\n } else if (c >= '2' && c <= '7') {\n return c - '2' + 26;\n }\n return Error;\n }\n};\n\nstruct b64_conversion_traits\n{\n static size_t group_length()\n {\n return 6;\n }\n\n static char encode(unsigned int index)\n {\n const char* const dictionary = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+\/\";\n assert(index < strlen(dictionary));\n return dictionary[index];\n }\n\n static char decode(char c)\n {\n const int alph_len = 26;\n if (c >= 'A' && c <= 'Z') {\n return c - 'A';\n } else if (c >= 'a' && c <= 'z') {\n return c - 'a' + alph_len * 1;\n } else if (c >= '0' && c <= '9') {\n return c - '0' + alph_len * 2;\n } else if (c == '+') {\n return c - '+' + alph_len * 2 + 10;\n } else if (c == '\/') {\n return c - '\/' + alph_len * 2 + 11;\n }\n return Error;\n }\n};\n\ntemplate<class ConversionTraits, class Iter1, class Iter2>\nvoid decode(Iter1 start, Iter1 end, Iter2 out)\n{\n Iter1 iter = start;\n size_t output_current_bit = 0;\n char buffer = 0;\n\n while (iter != end) {\n if (std::isspace(*iter)) {\n ++iter;\n continue;\n }\n char value = ConversionTraits::decode(*iter);\n if (value == Error) {\n \/\/ malformed data, but let's go on...\n ++iter;\n continue;\n }\n size_t bits_in_current_byte = std::min<size_t>(output_current_bit + ConversionTraits::group_length(), 8) - output_current_bit;\n if (bits_in_current_byte == ConversionTraits::group_length()) {\n \/\/ the value fits within current byte, so we can extract it directly\n buffer |= value << (8 - output_current_bit - ConversionTraits::group_length());\n output_current_bit += ConversionTraits::group_length();\n \/\/ check if we filled up current byte completely; in such case we flush output and continue\n if (output_current_bit == 8) {\n *out++ = buffer;\n buffer = 0;\n output_current_bit = 0;\n }\n } else {\n \/\/ the value spans across the current and the next byte\n size_t bits_in_next_byte = ConversionTraits::group_length() - bits_in_current_byte;\n \/\/ fill the current byte and flush it to our output\n buffer |= value >> bits_in_next_byte;\n *out++ = buffer;\n buffer = 0;\n \/\/ save the remainder of our value in the buffer; it will be flushed\n \/\/ during next iterations\n buffer |= value << (8 - bits_in_next_byte);\n output_current_bit = bits_in_next_byte;\n }\n ++iter;\n }\n}\n\ntemplate<class ConversionTraits, class Iter1, class Iter2>\nvoid encode(Iter1 start, Iter1 end, Iter2 out)\n{\n Iter1 iter = start;\n size_t start_bit = 0;\n bool has_backlog = false;\n char backlog = 0;\n\n while (has_backlog || iter != end) {\n if (!has_backlog) {\n if (start_bit + ConversionTraits::group_length() < 8) {\n \/\/ the value fits within single byte, so we can extract it\n \/\/ directly\n char v = extract_partial_bits(*iter, start_bit, ConversionTraits::group_length());\n *out++ = ConversionTraits::encode(v);\n \/\/ since we know that start_bit + ConversionTraits::group_length() < 8 we don't need to go\n \/\/ to the next byte\n start_bit += ConversionTraits::group_length();\n } else {\n \/\/ our bits are spanning across byte border; we need to keep the\n \/\/ starting point and move over to next byte.\n backlog = *iter++;\n has_backlog = true;\n }\n } else {\n \/\/ encode value which is made from bits spanning across byte\n \/\/ boundary\n char v;\n if (iter == end)\n v = extract_overlapping_bits(backlog, 0, start_bit, ConversionTraits::group_length());\n else\n v = extract_overlapping_bits(backlog, *iter, start_bit, ConversionTraits::group_length());\n *out++ = ConversionTraits::encode(v);\n has_backlog = false;\n start_bit = (start_bit + ConversionTraits::group_length()) % 8;\n }\n }\n}\n\n} \/\/ impl\n\nusing namespace bn::impl;\n\ntemplate<class Iter1, class Iter2>\nvoid encode_b16(Iter1 start, Iter1 end, Iter2 out)\n{\n encode<b16_conversion_traits>(start, end, out);\n}\n\ntemplate<class Iter1, class Iter2>\nvoid encode_b32(Iter1 start, Iter1 end, Iter2 out)\n{\n encode<b32_conversion_traits>(start, end, out);\n}\n\ntemplate<class Iter1, class Iter2>\nvoid encode_b64(Iter1 start, Iter1 end, Iter2 out)\n{\n encode<b64_conversion_traits>(start, end, out);\n}\n\ntemplate<class Iter1, class Iter2>\nvoid decode_b16(Iter1 start, Iter1 end, Iter2 out)\n{\n decode<b16_conversion_traits>(start, end, out);\n}\n\ntemplate<class Iter1, class Iter2>\nvoid decode_b32(Iter1 start, Iter1 end, Iter2 out)\n{\n decode<b32_conversion_traits>(start, end, out);\n}\n\ntemplate<class Iter1, class Iter2>\nvoid decode_b64(Iter1 start, Iter1 end, Iter2 out)\n{\n decode<b64_conversion_traits>(start, end, out);\n}\n\n} \/\/ bn\n\n#endif \/\/ BASEN_HPP\n<commit_msg>Fixing SVACE error on 3rd party template<commit_after>\/**\n * base-n, 1.0\n * Copyright (C) 2012 Andrzej Zawadzki (azawadzki@gmail.com)\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n**\/\n\n\/*\n * In the original file, static analysis complains about return type from decode methods\n * not being testable against Error constant (due to difference of type sizes).\n *\n * Modified decode methods to return error through an out parameter instead.\n *\/\n\n#ifndef BASEN_HPP\n#define BASEN_HPP\n\n#include <algorithm>\n#include <cctype>\n#include <cassert>\n#include <cstring>\n\nnamespace bn\n{\n\ntemplate<class Iter1, class Iter2>\nvoid encode_b16(Iter1 start, Iter1 end, Iter2 out);\n\ntemplate<class Iter1, class Iter2>\nvoid encode_b32(Iter1 start, Iter1 end, Iter2 out);\n\ntemplate<class Iter1, class Iter2>\nvoid encode_b64(Iter1 start, Iter1 end, Iter2 out);\n\ntemplate<class Iter1, class Iter2>\nvoid decode_b16(Iter1 start, Iter1 end, Iter2 out);\n\ntemplate<class Iter1, class Iter2>\nvoid decode_b32(Iter1 start, Iter1 end, Iter2 out);\n\ntemplate<class Iter1, class Iter2>\nvoid decode_b64(Iter1 start, Iter1 end, Iter2 out);\n\nnamespace impl\n{\n\nconst int Error = -1;\n\nnamespace {\n\nchar extract_partial_bits(char value, size_t start_bit, size_t bits_count)\n{\n assert(start_bit + bits_count < 8);\n \/\/ shift extracted bits to the beginning of the byte\n char t1 = value >> (8 - bits_count - start_bit);\n \/\/ mask out bits on the left\n char t2 = t1 & ~(0xff << bits_count);\n return t2;\n}\n\nchar extract_overlapping_bits(char previous, char next, size_t start_bit, size_t bits_count)\n{\n assert(start_bit + bits_count < 16);\n size_t bits_count_in_previous = 8 - start_bit;\n size_t bits_count_in_next = bits_count - bits_count_in_previous;\n char t1 = previous << bits_count_in_next;\n char t2 = next >> (8 - bits_count_in_next) & ~(0xff << bits_count_in_next) ;\n return (t1 | t2) & ~(0xff << bits_count);\n}\n\n}\n\nstruct b16_conversion_traits\n{\n static size_t group_length()\n {\n return 4;\n }\n\n static char encode(unsigned int index)\n {\n const char* const dictionary = \"0123456789ABCDEF\";\n assert(index < strlen(dictionary));\n return dictionary[index];\n }\n\n \/*\n * In the original file, error code was passed through return value, but used int -1 (out of range of char).\n * Separated error value from return value by using out parameter.\n *\/\n static char decode(char c, bool& error)\n {\n error=false;\n if (c >= '0' && c <= '9') {\n return c - '0';\n } else if (c >= 'A' && c <= 'F') {\n return c - 'A' + 10;\n }\n error=true;\n return 0;\n }\n};\n\nstruct b32_conversion_traits\n{\n static size_t group_length()\n {\n return 5;\n }\n\n static char encode(unsigned int index)\n {\n const char * dictionary = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567\";\n assert(index < strlen(dictionary));\n return dictionary[index];\n }\n\n \/*\n * In the original file, error code was passed through return value, but used int -1 (out of range of char).\n * Separated error value from return value by using out parameter.\n *\/\n static char decode(char c, bool& error)\n {\n error=false;\n if (c >= 'A' && c <= 'Z') {\n return c - 'A';\n } else if (c >= '2' && c <= '7') {\n return c - '2' + 26;\n }\n error=true;\n return 0;\n }\n};\n\nstruct b64_conversion_traits\n{\n static size_t group_length()\n {\n return 6;\n }\n\n static char encode(unsigned int index)\n {\n const char* const dictionary = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+\/\";\n assert(index < strlen(dictionary));\n return dictionary[index];\n }\n\n \/*\n * In the original file, error code was passed through return value, but used int -1 (out of range of char).\n * Separated error value from return value by using out parameter.\n *\/\n static char decode(char c, bool& error)\n {\n error=false;\n const int alph_len = 26;\n if (c >= 'A' && c <= 'Z') {\n return c - 'A';\n } else if (c >= 'a' && c <= 'z') {\n return c - 'a' + alph_len * 1;\n } else if (c >= '0' && c <= '9') {\n return c - '0' + alph_len * 2;\n } else if (c == '+') {\n return c - '+' + alph_len * 2 + 10;\n } else if (c == '\/') {\n return c - '\/' + alph_len * 2 + 11;\n }\n error=true;\n return 0;\n }\n};\n\ntemplate<class ConversionTraits, class Iter1, class Iter2>\nvoid decode(Iter1 start, Iter1 end, Iter2 out)\n{\n Iter1 iter = start;\n size_t output_current_bit = 0;\n char buffer = 0;\n\n while (iter != end) {\n if (std::isspace(*iter)) {\n ++iter;\n continue;\n }\n\n \/*\n * In the original file, error value was out of range of return type.\n * Separated error value from return value by using out parameter.\n *\/\n bool error=false;\n char value = ConversionTraits::decode(*iter, error);\n if (error) {\n \/\/ malformed data, but let's go on...\n ++iter;\n continue;\n }\n size_t bits_in_current_byte = std::min<size_t>(output_current_bit + ConversionTraits::group_length(), 8) - output_current_bit;\n if (bits_in_current_byte == ConversionTraits::group_length()) {\n \/\/ the value fits within current byte, so we can extract it directly\n buffer |= value << (8 - output_current_bit - ConversionTraits::group_length());\n output_current_bit += ConversionTraits::group_length();\n \/\/ check if we filled up current byte completely; in such case we flush output and continue\n if (output_current_bit == 8) {\n *out++ = buffer;\n buffer = 0;\n output_current_bit = 0;\n }\n } else {\n \/\/ the value spans across the current and the next byte\n size_t bits_in_next_byte = ConversionTraits::group_length() - bits_in_current_byte;\n \/\/ fill the current byte and flush it to our output\n buffer |= value >> bits_in_next_byte;\n *out++ = buffer;\n buffer = 0;\n \/\/ save the remainder of our value in the buffer; it will be flushed\n \/\/ during next iterations\n buffer |= value << (8 - bits_in_next_byte);\n output_current_bit = bits_in_next_byte;\n }\n ++iter;\n }\n}\n\ntemplate<class ConversionTraits, class Iter1, class Iter2>\nvoid encode(Iter1 start, Iter1 end, Iter2 out)\n{\n Iter1 iter = start;\n size_t start_bit = 0;\n bool has_backlog = false;\n char backlog = 0;\n\n while (has_backlog || iter != end) {\n if (!has_backlog) {\n if (start_bit + ConversionTraits::group_length() < 8) {\n \/\/ the value fits within single byte, so we can extract it\n \/\/ directly\n char v = extract_partial_bits(*iter, start_bit, ConversionTraits::group_length());\n *out++ = ConversionTraits::encode(v);\n \/\/ since we know that start_bit + ConversionTraits::group_length() < 8 we don't need to go\n \/\/ to the next byte\n start_bit += ConversionTraits::group_length();\n } else {\n \/\/ our bits are spanning across byte border; we need to keep the\n \/\/ starting point and move over to next byte.\n backlog = *iter++;\n has_backlog = true;\n }\n } else {\n \/\/ encode value which is made from bits spanning across byte\n \/\/ boundary\n char v;\n if (iter == end)\n v = extract_overlapping_bits(backlog, 0, start_bit, ConversionTraits::group_length());\n else\n v = extract_overlapping_bits(backlog, *iter, start_bit, ConversionTraits::group_length());\n *out++ = ConversionTraits::encode(v);\n has_backlog = false;\n start_bit = (start_bit + ConversionTraits::group_length()) % 8;\n }\n }\n}\n\n} \/\/ impl\n\nusing namespace bn::impl;\n\ntemplate<class Iter1, class Iter2>\nvoid encode_b16(Iter1 start, Iter1 end, Iter2 out)\n{\n encode<b16_conversion_traits>(start, end, out);\n}\n\ntemplate<class Iter1, class Iter2>\nvoid encode_b32(Iter1 start, Iter1 end, Iter2 out)\n{\n encode<b32_conversion_traits>(start, end, out);\n}\n\ntemplate<class Iter1, class Iter2>\nvoid encode_b64(Iter1 start, Iter1 end, Iter2 out)\n{\n encode<b64_conversion_traits>(start, end, out);\n}\n\ntemplate<class Iter1, class Iter2>\nvoid decode_b16(Iter1 start, Iter1 end, Iter2 out)\n{\n decode<b16_conversion_traits>(start, end, out);\n}\n\ntemplate<class Iter1, class Iter2>\nvoid decode_b32(Iter1 start, Iter1 end, Iter2 out)\n{\n decode<b32_conversion_traits>(start, end, out);\n}\n\ntemplate<class Iter1, class Iter2>\nvoid decode_b64(Iter1 start, Iter1 end, Iter2 out)\n{\n decode<b64_conversion_traits>(start, end, out);\n}\n\n} \/\/ bn\n\n#endif \/\/ BASEN_HPP\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements. See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership. The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied. See the License for the\n * specific language governing permissions and limitations\n * under the License.\n *\/\n\n\/*!\n * \\file mkldnn_fully_connected.cc\n * \\brief\n * \\author Da Zheng\n*\/\n\n#include \"..\/fully_connected-inl.h\"\n#include \".\/mkldnn_base-inl.h\"\n\n#if MXNET_USE_MKLDNN == 1\nnamespace mxnet {\nnamespace op {\n\ninline static mkldnn::inner_product_forward::primitive_desc GetIPFwd(\n const NDArray &data, const NDArray &weight, const NDArray *bias,\n const mkldnn::memory::desc &out_md) {\n auto data_md = GetMemDesc(data);\n auto weight_md = GetMemDesc(weight);\n auto engine = CpuEngine::Get()->get_engine();\n if (bias) {\n auto bias_md = GetMemDesc(*bias);\n mkldnn::inner_product_forward::desc ipFwd_desc(mkldnn::prop_kind::forward_training,\n data_md, weight_md, bias_md, out_md);\n return mkldnn::inner_product_forward::primitive_desc(ipFwd_desc, engine);\n } else {\n mkldnn::inner_product_forward::desc ipFwd_desc(mkldnn::prop_kind::forward_training,\n data_md, weight_md, out_md);\n return mkldnn::inner_product_forward::primitive_desc(ipFwd_desc, engine);\n }\n}\n\ninline static mkldnn::inner_product_backward_data::primitive_desc GetIpBwdData(\n const NDArray &data, const NDArray &weight, const NDArray &output,\n mkldnn::inner_product_forward::primitive_desc ipFwd_pd) {\n auto data_md = GetMemDesc(data);\n auto weight_md = GetMemDesc(weight);\n auto out_md = GetMemDesc(output);\n auto engine = CpuEngine::Get()->get_engine();\n mkldnn::inner_product_backward_data::desc desc(data_md, weight_md, out_md);\n return mkldnn::inner_product_backward_data::primitive_desc(desc, engine, ipFwd_pd);\n}\n\ninline static mkldnn::inner_product_backward_weights::primitive_desc GetIPBwdWeights(\n const NDArray &data, const NDArray &weight, const NDArray *bias,\n const NDArray &output, mkldnn::inner_product_forward::primitive_desc ipFwd_pd) {\n auto data_md = GetMemDesc(data);\n auto weight_md = GetMemDesc(weight);\n auto out_md = GetMemDesc(output);\n auto engine = CpuEngine::Get()->get_engine();\n if (bias) {\n auto bias_md = GetMemDesc(*bias);\n mkldnn::inner_product_backward_weights::desc ipBwdWeights_desc(data_md,\n weight_md, bias_md, out_md);\n return mkldnn::inner_product_backward_weights::primitive_desc(\n ipBwdWeights_desc, engine, ipFwd_pd);\n } else {\n mkldnn::inner_product_backward_weights::desc ipBwdWeights_desc(data_md,\n weight_md, out_md);\n return mkldnn::inner_product_backward_weights::primitive_desc(\n ipBwdWeights_desc, engine, ipFwd_pd);\n }\n}\n\nvoid MKLDNNFCForward(const nnvm::NodeAttrs& attrs, const OpContext &ctx,\n const std::vector<NDArray> &in_data,\n const std::vector<OpReqType> &req,\n const std::vector<NDArray> &out_data) {\n TmpMemMgr::Get()->Init(ctx.requested[fullc::kTempSpace]);\n const FullyConnectedParam& param = nnvm::get<FullyConnectedParam>(attrs.parsed);\n const TShape& ishape = in_data[fullc::kData].shape();\n const TShape& oshape = out_data[fullc::kOut].shape();\n NDArray weight = in_data[fullc::kWeight];\n NDArray data = in_data[fullc::kData];\n \/\/ If the input data is a view of an MKLDNN array, we should create a new\n \/\/ NDArray with reordered data.\n if (data.IsMKLDNNData() && data.IsView())\n data = in_data[fullc::kData].Reorder2Default();\n\n auto out_md = GetMemDesc(out_data[fullc::kOut]);\n if (data.shape().ndim() != 2 && !param.flatten) {\n data = data.MKLDNNDataReshape(Shape2(ishape.ProdShape(0, ishape.ndim()-1),\n ishape[ishape.ndim()-1]));\n mkldnn::memory::dims out_dims{static_cast<int>(oshape.ProdShape(0, oshape.ndim()-1)),\n static_cast<int>(oshape[ishape.ndim()-1])};\n out_md = mkldnn::memory::desc(out_dims, get_mkldnn_type(out_data[fullc::kOut].dtype()),\n mkldnn::memory::format::any);\n } else if (data.shape().ndim() != 2) {\n data = data.MKLDNNDataReshape(Shape2(ishape[0], ishape.ProdShape(1, ishape.ndim())));\n mkldnn::memory::dims out_dims{static_cast<int>(oshape[0]),\n static_cast<int>(oshape.ProdShape(1, oshape.ndim()))};\n out_md = mkldnn::memory::desc(out_dims, get_mkldnn_type(out_data[fullc::kOut].dtype()),\n mkldnn::memory::format::any);\n }\n\n mkldnn::inner_product_forward::primitive_desc ipFwd_pd = GetIPFwd(data, weight,\n param.no_bias ? nullptr : &in_data[fullc::kBias], out_md);\n auto data_mem = data.GetMKLDNNDataReorder(ipFwd_pd.src_primitive_desc());\n auto weight_mem = weight.GetMKLDNNDataReorder(ipFwd_pd.weights_primitive_desc());\n auto out_mem = CreateMKLDNNMem(out_data[fullc::kOut],\n ipFwd_pd.dst_primitive_desc(), req[fullc::kOut]);\n if (param.no_bias) {\n MKLDNNStream::Get()->RegisterPrim(mkldnn::inner_product_forward(\n ipFwd_pd, *data_mem, *weight_mem, *out_mem.second));\n } else {\n auto bias_mem = in_data[fullc::kBias].GetMKLDNNDataReorder(ipFwd_pd.bias_primitive_desc());\n MKLDNNStream::Get()->RegisterPrim(mkldnn::inner_product_forward(ipFwd_pd,\n *data_mem, *weight_mem, *bias_mem, *out_mem.second));\n }\n CommitOutput(out_data[fullc::kOut], out_mem);\n MKLDNNStream::Get()->Submit();\n}\n\nvoid MKLDNNFCBackward(const nnvm::NodeAttrs& attrs, const OpContext &ctx,\n const std::vector<NDArray> &inputs,\n const std::vector<OpReqType> &req,\n const std::vector<NDArray> &outputs) {\n TmpMemMgr::Get()->Init(ctx.requested[fullc::kTempSpace]);\n const std::vector<NDArray> &in_grad = outputs;\n const FullyConnectedParam& param = nnvm::get<FullyConnectedParam>(attrs.parsed);\n const TShape& ishape = inputs[fullc::kData + 1].shape();\n const TShape& oshape = inputs[fullc::kOut].shape();\n\n NDArray weight = inputs[fullc::kWeight + 1];\n NDArray data = inputs[fullc::kData + 1];\n if (data.shape().ndim() != 2 && !param.flatten)\n data = data.MKLDNNDataReshape(Shape2(ishape.ProdShape(0, ishape.ndim()-1),\n ishape[ishape.ndim()-1]));\n else if (data.shape().ndim() != 2)\n data = data.MKLDNNDataReshape(Shape2(ishape[0],\n ishape.ProdShape(1, ishape.ndim())));\n NDArray out_grad = inputs[fullc::kOut];\n if (out_grad.shape().ndim() != 2 && !param.flatten)\n out_grad = out_grad.MKLDNNDataReshape(Shape2(oshape.ProdShape(0, oshape.ndim()-1),\n oshape[oshape.ndim()-1]));\n else if (out_grad.shape().ndim() != 2)\n out_grad = out_grad.MKLDNNDataReshape(Shape2(oshape[0],\n oshape.ProdShape(1, oshape.ndim())));\n\n mkldnn::inner_product_forward::primitive_desc ipFwd_pd = GetIPFwd(data, weight,\n param.no_bias ? nullptr : &in_grad[fullc::kBias], GetMemDesc(out_grad));\n\n CHECK_NE(req[fullc::kWeight], kWriteInplace) << \"cannot write weight inplace\";\n if (req[fullc::kData]) {\n mkldnn::inner_product_backward_data::primitive_desc ipBwdData_pd = GetIpBwdData(\n data, weight, out_grad, ipFwd_pd);\n auto out_grad_mem = out_grad.GetMKLDNNDataReorder(\n ipBwdData_pd.diff_dst_primitive_desc());\n auto weight_mem = weight.GetMKLDNNDataReorder(ipBwdData_pd.weights_primitive_desc());\n auto in_grad_mem = CreateMKLDNNMem(in_grad[fullc::kData],\n ipBwdData_pd.diff_src_primitive_desc(),\n req[fullc::kData]);\n MKLDNNStream::Get()->RegisterPrim(mkldnn::inner_product_backward_data(\n ipBwdData_pd, *out_grad_mem, *weight_mem, *in_grad_mem.second));\n CommitOutput(in_grad[fullc::kData], in_grad_mem);\n }\n if (req[fullc::kWeight]) {\n mkldnn::inner_product_backward_weights::primitive_desc ipBwdWeights_pd\n = GetIPBwdWeights(data, weight, param.no_bias ? nullptr : &in_grad[fullc::kBias],\n out_grad, ipFwd_pd);\n auto out_grad_mem = out_grad.GetMKLDNNDataReorder(\n ipBwdWeights_pd.diff_dst_primitive_desc());\n auto data_mem = data.GetMKLDNNDataReorder(ipBwdWeights_pd.src_primitive_desc());\n auto in_grad_weight = CreateMKLDNNWeightGrad(in_grad[fullc::kWeight],\n ipBwdWeights_pd.diff_weights_primitive_desc(),\n req[fullc::kWeight]);\n mkldnn_output_t in_grad_bias;\n if (param.no_bias) {\n MKLDNNStream::Get()->RegisterPrim(mkldnn::inner_product_backward_weights(\n ipBwdWeights_pd, *data_mem, *out_grad_mem, *in_grad_weight.second));\n } else {\n in_grad_bias = CreateMKLDNNMem(in_grad[fullc::kBias],\n ipBwdWeights_pd.diff_bias_primitive_desc(),\n req[fullc::kBias]);\n MKLDNNStream::Get()->RegisterPrim(mkldnn::inner_product_backward_weights(\n ipBwdWeights_pd, *data_mem, *out_grad_mem, *in_grad_weight.second,\n *in_grad_bias.second));\n }\n CommitOutput(in_grad[fullc::kWeight], in_grad_weight);\n CommitOutput(in_grad[fullc::kBias], in_grad_bias);\n }\n MKLDNNStream::Get()->Submit();\n}\n\n} \/\/ namespace op\n} \/\/ namespace mxnet\n#endif \/\/ MXNET_USE_MKLDNN == 1\n<commit_msg>use correct prop_kind for mkl-dnn FC layer (#10442)<commit_after>\/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements. See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership. The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied. See the License for the\n * specific language governing permissions and limitations\n * under the License.\n *\/\n\n\/*!\n * \\file mkldnn_fully_connected.cc\n * \\brief\n * \\author Da Zheng\n*\/\n\n#include \"..\/fully_connected-inl.h\"\n#include \".\/mkldnn_base-inl.h\"\n\n#if MXNET_USE_MKLDNN == 1\nnamespace mxnet {\nnamespace op {\n\ninline static mkldnn::inner_product_forward::primitive_desc GetIPFwd(\n const NDArray &data, const NDArray &weight, const NDArray *bias,\n const mkldnn::memory::desc &out_md, const bool is_train) {\n auto data_md = GetMemDesc(data);\n auto weight_md = GetMemDesc(weight);\n auto engine = CpuEngine::Get()->get_engine();\n auto propagation =\n is_train ? mkldnn::prop_kind::forward_training : mkldnn::prop_kind::forward_scoring;\n if (bias) {\n auto bias_md = GetMemDesc(*bias);\n mkldnn::inner_product_forward::desc ipFwd_desc(propagation,\n data_md, weight_md, bias_md, out_md);\n return mkldnn::inner_product_forward::primitive_desc(ipFwd_desc, engine);\n } else {\n mkldnn::inner_product_forward::desc ipFwd_desc(propagation,\n data_md, weight_md, out_md);\n return mkldnn::inner_product_forward::primitive_desc(ipFwd_desc, engine);\n }\n}\n\ninline static mkldnn::inner_product_backward_data::primitive_desc GetIpBwdData(\n const NDArray &data, const NDArray &weight, const NDArray &output,\n mkldnn::inner_product_forward::primitive_desc ipFwd_pd) {\n auto data_md = GetMemDesc(data);\n auto weight_md = GetMemDesc(weight);\n auto out_md = GetMemDesc(output);\n auto engine = CpuEngine::Get()->get_engine();\n mkldnn::inner_product_backward_data::desc desc(data_md, weight_md, out_md);\n return mkldnn::inner_product_backward_data::primitive_desc(desc, engine, ipFwd_pd);\n}\n\ninline static mkldnn::inner_product_backward_weights::primitive_desc GetIPBwdWeights(\n const NDArray &data, const NDArray &weight, const NDArray *bias,\n const NDArray &output, mkldnn::inner_product_forward::primitive_desc ipFwd_pd) {\n auto data_md = GetMemDesc(data);\n auto weight_md = GetMemDesc(weight);\n auto out_md = GetMemDesc(output);\n auto engine = CpuEngine::Get()->get_engine();\n if (bias) {\n auto bias_md = GetMemDesc(*bias);\n mkldnn::inner_product_backward_weights::desc ipBwdWeights_desc(data_md,\n weight_md, bias_md, out_md);\n return mkldnn::inner_product_backward_weights::primitive_desc(\n ipBwdWeights_desc, engine, ipFwd_pd);\n } else {\n mkldnn::inner_product_backward_weights::desc ipBwdWeights_desc(data_md,\n weight_md, out_md);\n return mkldnn::inner_product_backward_weights::primitive_desc(\n ipBwdWeights_desc, engine, ipFwd_pd);\n }\n}\n\nvoid MKLDNNFCForward(const nnvm::NodeAttrs& attrs, const OpContext &ctx,\n const std::vector<NDArray> &in_data,\n const std::vector<OpReqType> &req,\n const std::vector<NDArray> &out_data) {\n TmpMemMgr::Get()->Init(ctx.requested[fullc::kTempSpace]);\n const FullyConnectedParam& param = nnvm::get<FullyConnectedParam>(attrs.parsed);\n const TShape& ishape = in_data[fullc::kData].shape();\n const TShape& oshape = out_data[fullc::kOut].shape();\n NDArray weight = in_data[fullc::kWeight];\n NDArray data = in_data[fullc::kData];\n \/\/ If the input data is a view of an MKLDNN array, we should create a new\n \/\/ NDArray with reordered data.\n if (data.IsMKLDNNData() && data.IsView())\n data = in_data[fullc::kData].Reorder2Default();\n\n auto out_md = GetMemDesc(out_data[fullc::kOut]);\n if (data.shape().ndim() != 2 && !param.flatten) {\n data = data.MKLDNNDataReshape(Shape2(ishape.ProdShape(0, ishape.ndim()-1),\n ishape[ishape.ndim()-1]));\n mkldnn::memory::dims out_dims{static_cast<int>(oshape.ProdShape(0, oshape.ndim()-1)),\n static_cast<int>(oshape[ishape.ndim()-1])};\n out_md = mkldnn::memory::desc(out_dims, get_mkldnn_type(out_data[fullc::kOut].dtype()),\n mkldnn::memory::format::any);\n } else if (data.shape().ndim() != 2) {\n data = data.MKLDNNDataReshape(Shape2(ishape[0], ishape.ProdShape(1, ishape.ndim())));\n mkldnn::memory::dims out_dims{static_cast<int>(oshape[0]),\n static_cast<int>(oshape.ProdShape(1, oshape.ndim()))};\n out_md = mkldnn::memory::desc(out_dims, get_mkldnn_type(out_data[fullc::kOut].dtype()),\n mkldnn::memory::format::any);\n }\n\n mkldnn::inner_product_forward::primitive_desc ipFwd_pd = GetIPFwd(data, weight,\n param.no_bias ? nullptr : &in_data[fullc::kBias], out_md, ctx.is_train);\n auto data_mem = data.GetMKLDNNDataReorder(ipFwd_pd.src_primitive_desc());\n auto weight_mem = weight.GetMKLDNNDataReorder(ipFwd_pd.weights_primitive_desc());\n auto out_mem = CreateMKLDNNMem(out_data[fullc::kOut],\n ipFwd_pd.dst_primitive_desc(), req[fullc::kOut]);\n if (param.no_bias) {\n MKLDNNStream::Get()->RegisterPrim(mkldnn::inner_product_forward(\n ipFwd_pd, *data_mem, *weight_mem, *out_mem.second));\n } else {\n auto bias_mem = in_data[fullc::kBias].GetMKLDNNDataReorder(ipFwd_pd.bias_primitive_desc());\n MKLDNNStream::Get()->RegisterPrim(mkldnn::inner_product_forward(ipFwd_pd,\n *data_mem, *weight_mem, *bias_mem, *out_mem.second));\n }\n CommitOutput(out_data[fullc::kOut], out_mem);\n MKLDNNStream::Get()->Submit();\n}\n\nvoid MKLDNNFCBackward(const nnvm::NodeAttrs& attrs, const OpContext &ctx,\n const std::vector<NDArray> &inputs,\n const std::vector<OpReqType> &req,\n const std::vector<NDArray> &outputs) {\n TmpMemMgr::Get()->Init(ctx.requested[fullc::kTempSpace]);\n const std::vector<NDArray> &in_grad = outputs;\n const FullyConnectedParam& param = nnvm::get<FullyConnectedParam>(attrs.parsed);\n const TShape& ishape = inputs[fullc::kData + 1].shape();\n const TShape& oshape = inputs[fullc::kOut].shape();\n\n NDArray weight = inputs[fullc::kWeight + 1];\n NDArray data = inputs[fullc::kData + 1];\n if (data.shape().ndim() != 2 && !param.flatten)\n data = data.MKLDNNDataReshape(Shape2(ishape.ProdShape(0, ishape.ndim()-1),\n ishape[ishape.ndim()-1]));\n else if (data.shape().ndim() != 2)\n data = data.MKLDNNDataReshape(Shape2(ishape[0],\n ishape.ProdShape(1, ishape.ndim())));\n NDArray out_grad = inputs[fullc::kOut];\n if (out_grad.shape().ndim() != 2 && !param.flatten)\n out_grad = out_grad.MKLDNNDataReshape(Shape2(oshape.ProdShape(0, oshape.ndim()-1),\n oshape[oshape.ndim()-1]));\n else if (out_grad.shape().ndim() != 2)\n out_grad = out_grad.MKLDNNDataReshape(Shape2(oshape[0],\n oshape.ProdShape(1, oshape.ndim())));\n\n mkldnn::inner_product_forward::primitive_desc ipFwd_pd = GetIPFwd(data, weight,\n param.no_bias ? nullptr : &in_grad[fullc::kBias], GetMemDesc(out_grad), ctx.is_train);\n\n CHECK_NE(req[fullc::kWeight], kWriteInplace) << \"cannot write weight inplace\";\n if (req[fullc::kData]) {\n mkldnn::inner_product_backward_data::primitive_desc ipBwdData_pd = GetIpBwdData(\n data, weight, out_grad, ipFwd_pd);\n auto out_grad_mem = out_grad.GetMKLDNNDataReorder(\n ipBwdData_pd.diff_dst_primitive_desc());\n auto weight_mem = weight.GetMKLDNNDataReorder(ipBwdData_pd.weights_primitive_desc());\n auto in_grad_mem = CreateMKLDNNMem(in_grad[fullc::kData],\n ipBwdData_pd.diff_src_primitive_desc(),\n req[fullc::kData]);\n MKLDNNStream::Get()->RegisterPrim(mkldnn::inner_product_backward_data(\n ipBwdData_pd, *out_grad_mem, *weight_mem, *in_grad_mem.second));\n CommitOutput(in_grad[fullc::kData], in_grad_mem);\n }\n if (req[fullc::kWeight]) {\n mkldnn::inner_product_backward_weights::primitive_desc ipBwdWeights_pd\n = GetIPBwdWeights(data, weight, param.no_bias ? nullptr : &in_grad[fullc::kBias],\n out_grad, ipFwd_pd);\n auto out_grad_mem = out_grad.GetMKLDNNDataReorder(\n ipBwdWeights_pd.diff_dst_primitive_desc());\n auto data_mem = data.GetMKLDNNDataReorder(ipBwdWeights_pd.src_primitive_desc());\n auto in_grad_weight = CreateMKLDNNWeightGrad(in_grad[fullc::kWeight],\n ipBwdWeights_pd.diff_weights_primitive_desc(),\n req[fullc::kWeight]);\n mkldnn_output_t in_grad_bias;\n if (param.no_bias) {\n MKLDNNStream::Get()->RegisterPrim(mkldnn::inner_product_backward_weights(\n ipBwdWeights_pd, *data_mem, *out_grad_mem, *in_grad_weight.second));\n } else {\n in_grad_bias = CreateMKLDNNMem(in_grad[fullc::kBias],\n ipBwdWeights_pd.diff_bias_primitive_desc(),\n req[fullc::kBias]);\n MKLDNNStream::Get()->RegisterPrim(mkldnn::inner_product_backward_weights(\n ipBwdWeights_pd, *data_mem, *out_grad_mem, *in_grad_weight.second,\n *in_grad_bias.second));\n }\n CommitOutput(in_grad[fullc::kWeight], in_grad_weight);\n CommitOutput(in_grad[fullc::kBias], in_grad_bias);\n }\n MKLDNNStream::Get()->Submit();\n}\n\n} \/\/ namespace op\n} \/\/ namespace mxnet\n#endif \/\/ MXNET_USE_MKLDNN == 1\n<|endoftext|>"} {"text":"<commit_before>\n#include \"config_interrogatedb.cxx\"\n#include \"indexRemapper.cxx\"\n#include \"interrogateComponent.cxx\"\n#include \"interrogateElement.cxx\"\n#include \"interrogateFunction.cxx\"\n#include \"interrogateFunctionWrapper.cxx\"\n#include \"interrogate_datafile.cxx\"\n#include \"interrogate_interface.cxx\"\n#include \"vector_int.cxx\"\n\n<commit_msg>*** empty log message ***<commit_after>\n#include \"vector_int.cxx\"\n#include \"config_interrogatedb.cxx\"\n#include \"indexRemapper.cxx\"\n#include \"interrogateComponent.cxx\"\n#include \"interrogateElement.cxx\"\n#include \"interrogateFunction.cxx\"\n#include \"interrogateFunctionWrapper.cxx\"\n#include \"interrogate_datafile.cxx\"\n#include \"interrogate_interface.cxx\"\n\n\n<|endoftext|>"} {"text":"<commit_before>#include <gtest\/gtest.h>\n#include <test\/models\/model_test_fixture.hpp>\n\nclass Models_BasicEstimators_NormalMixture : \n public Model_Test_Fixture<Models_BasicEstimators_NormalMixture> {\nprotected:\n virtual void SetUp() {\n }\npublic:\n static std::vector<std::string> get_model_path() {\n std::vector<std::string> model_path;\n model_path.push_back(\"models\");\n model_path.push_back(\"basic_estimators\");\n model_path.push_back(\"normal_mixture\");\n return model_path;\n }\n static bool has_data() {\n return true;\n }\n\n static bool has_init() {\n return false;\n \n }\n static int num_iterations() {\n \/\/return 8000;\n return 200;\n }\n\n static std::vector<int> skip_chains_test() {\n std::vector<int> params_to_skip;\n return params_to_skip;\n }\n\n static void populate_chains() {\n if (chains->num_kept_samples() == 0) {\n for (int chain = 0; chain < num_chains; chain++) {\n std::ifstream ifstream;\n stan::io::stan_csv stan_csv;\n ifstream.open(get_csv_file(chain).c_str());\n stan_csv = stan::io::stan_csv_reader::parse(ifstream);\n ifstream.close();\n\n\n int theta = 3;\n int mu1 = 4;\n int mu2 = 5;\n int log_theta = 6;\n int log_1mtheta = 7;\n \/\/ if theta > 0.5, swap values\n if (stan_csv.samples.col(theta).mean() > 0.5) {\n stan_csv.samples.col(theta) = 1.0 - stan_csv.samples.col(theta).array();\n \n Eigen::VectorXd tmp;\n tmp = stan_csv.samples.col(mu1);\n stan_csv.samples.col(mu1) = stan_csv.samples.col(mu2);\n stan_csv.samples.col(mu2) = tmp;\n \n tmp = stan_csv.samples.col(log_theta);\n stan_csv.samples.col(log_theta) = stan_csv.samples.col(log_1mtheta);\n stan_csv.samples.col(log_1mtheta) = tmp;\n }\n\n chains->add(stan_csv);\n }\n }\n }\n\n static std::vector<std::pair<int, double> >\n get_expected_values() {\n using std::make_pair;\n std::vector<std::pair<int, double> > expected_values;\n\n expected_values.push_back(make_pair(chains->index(\"theta\"), 0.2916));\n expected_values.push_back(make_pair(chains->index(\"mu[1]\"), -10.001));\n expected_values.push_back(make_pair(chains->index(\"mu[2]\"), 10.026));\n \n return expected_values;\n }\n\n};\n\nINSTANTIATE_TYPED_TEST_CASE_P(Models_BasicEstimators_NormalMixture,\n Model_Test_Fixture,\n Models_BasicEstimators_NormalMixture);\n<commit_msg>fixes issue #63.<commit_after>#include <gtest\/gtest.h>\n#include <test\/models\/model_test_fixture.hpp>\n\nclass Models_BasicEstimators_NormalMixture : \n public Model_Test_Fixture<Models_BasicEstimators_NormalMixture> {\nprotected:\n virtual void SetUp() {\n }\npublic:\n static std::vector<std::string> get_model_path() {\n std::vector<std::string> model_path;\n model_path.push_back(\"models\");\n model_path.push_back(\"basic_estimators\");\n model_path.push_back(\"normal_mixture\");\n return model_path;\n }\n static bool has_data() {\n return true;\n }\n\n static bool has_init() {\n return false;\n \n }\n static int num_iterations() {\n \/\/return 8000;\n return 200;\n }\n\n static std::vector<int> skip_chains_test() {\n std::vector<int> params_to_skip;\n return params_to_skip;\n }\n\n static int find(const Eigen::Matrix<std::string,Eigen::Dynamic,1>& header,\n const std::string& var) {\n for (int i = 0; i < header.size(); i++)\n if (header(i) == var)\n return i;\n return -1;\n }\n\n static void populate_chains() {\n if (chains->num_kept_samples() == 0) {\n for (int chain = 1; chain <= num_chains; chain++) {\n std::ifstream ifstream;\n stan::io::stan_csv stan_csv;\n ifstream.open(get_csv_file(chain).c_str());\n stan_csv = stan::io::stan_csv_reader::parse(ifstream);\n ifstream.close();\n \n int theta = find(stan_csv.header, \"theta\");\n int mu1 = find(stan_csv.header, \"mu[1]\");\n int mu2 = find(stan_csv.header, \"mu[2]\");\n int log_theta = find(stan_csv.header, \"log_theta\");\n int log_1mtheta = find(stan_csv.header, \"log_one_minus_theta\");\n\n \/\/ if theta > 0.5, swap values\n if (stan_csv.samples.col(theta).mean() > 0.5) {\n stan_csv.samples.col(theta) = 1.0 - stan_csv.samples.col(theta).array();\n\n Eigen::VectorXd tmp;\n tmp = stan_csv.samples.col(mu1);\n stan_csv.samples.col(mu1) = stan_csv.samples.col(mu2);\n stan_csv.samples.col(mu2) = tmp;\n \n tmp = stan_csv.samples.col(log_theta);\n stan_csv.samples.col(log_theta) = stan_csv.samples.col(log_1mtheta);\n stan_csv.samples.col(log_1mtheta) = tmp;\n }\n chains->add(stan_csv);\n }\n }\n }\n\n static std::vector<std::pair<int, double> >\n get_expected_values() {\n using std::make_pair;\n std::vector<std::pair<int, double> > expected_values;\n\n expected_values.push_back(make_pair(chains->index(\"theta\"), 0.2916));\n expected_values.push_back(make_pair(chains->index(\"mu[1]\"), -10.001));\n expected_values.push_back(make_pair(chains->index(\"mu[2]\"), 10.026));\n \n return expected_values;\n }\n\n};\n\nINSTANTIATE_TYPED_TEST_CASE_P(Models_BasicEstimators_NormalMixture,\n Model_Test_Fixture,\n Models_BasicEstimators_NormalMixture);\n<|endoftext|>"} {"text":"<commit_before>\/*\n * InputStreamMgr.cpp\n *\n * Created on: Mar 21, 2013\n * Author: nek3d\n *\/\n\n#include \"InputStreamMgr.h\"\n#include <cstring> \/\/for memset\n#include \"gzstream.h\"\n#include \"CompressionTools.h\"\n\nconst char *InputStreamMgr::FIFO_STRING_LITERAL = \"\/dev\/fd\";\n\nInputStreamMgr::InputStreamMgr(const string &filename, bool buildScanBuffer)\n:\n _filename(filename),\n _pushBackStreamBuf(NULL),\n _inputFileStream(NULL),\n _infStreamBuf(NULL),\n _oldInputStream(NULL),\n _isStdin(false),\n _isGzipped(false),\n _isBam(false),\n _isBgzipped(false),\n _tmpZipBuf(NULL),\n _bamRuledOut(false),\n _streamFinished(false),\n _numBytesInBuffer(0),\n _bamReader(NULL),\n _bgStream(NULL),\n _eofHit(false)\n{\n\t_possibleBamCode.resize(4, 0);\n}\n\n\nInputStreamMgr::~InputStreamMgr() {\n\tdelete _pushBackStreamBuf;\n\t_pushBackStreamBuf = NULL;\n\n\tdelete _inputFileStream;\n\t_inputFileStream = NULL;\n\n\tdelete _oldInputStream;\n\t_oldInputStream = NULL;\n\n\tdelete _infStreamBuf;\n\t_infStreamBuf = NULL;\n\n\tif(_bamReader) _bamReader->Close();\n\tdelete _bamReader;\n\n\tdelete _bgStream;\n\t_bgStream = NULL;\n\n\tdelete _finalInputStream;\n\t_finalInputStream = NULL;\n\n\tdelete [] _tmpZipBuf;\n\t_tmpZipBuf = NULL;\n}\n\nbool InputStreamMgr::init()\n{\n\tif (_filename == \"-\" || _filename == \"stdin\") { \/\/stdin\n\t\t_isStdin = true;\n\t\t\/\/peek at the first char of stdin to see if this is gzipped.\n\t\tif ((unsigned char)cin.peek() == 0x1f) {\n\t\t\t_isGzipped = true;\n\t\t}\n\t\t_pushBackStreamBuf = new PushBackStreamBuf(cin.rdbuf());\n\t} else {\n\t\tif (strncmp(_filename.c_str(), FIFO_STRING_LITERAL, strlen(FIFO_STRING_LITERAL)) == 0) {\n\t\t\t_isStdin = true;\n\t\t}\n\t\t_inputFileStream = new ifstream(_filename.c_str());\n\t\tif (_inputFileStream->fail()) {\n\t\t\tcerr << \"Error: Unable to open file \" << _filename << \". Exiting.\" << endl;\n\t\t\tdelete _inputFileStream;\n\t\t\t_inputFileStream = NULL;\n\t\t\texit(1);\n\t\t}\n\t\t\/\/peek at the first char of stdin to see if this is gzipped.\n\t\tif ((unsigned char)_inputFileStream->peek() == 0x1f) {\n\t\t\t_isGzipped = true;\n\t\t}\n\t\t_pushBackStreamBuf = new PushBackStreamBuf(_inputFileStream->rdbuf());\n\t}\n\t\/\/now we have a PushBackStreamBuf. Make a new stream.\n\t_finalInputStream = new istream(_pushBackStreamBuf);\n\tpopulateScanBuffer();\n\treturn true;\n}\n\nint InputStreamMgr::read(char *data, size_t dataSize)\n{\n\tsize_t origRead = 0;\n\tif (!_saveDataStr.empty()) {\n\t\t\/\/must first copy contents of savedData into requested data read buffer.\n\t\tif (dataSize >= _saveDataStr.size()) {\n\t\t\t\/\/They asked for the same amount of data or more than we saved. Give them all the saved data,\n\t\t\t\/\/then decrement the requested data size accordingly.\n\t\t\torigRead = _saveDataStr.size();\n\t\t\tmemcpy(data, _saveDataStr.c_str(), origRead);\n\t\t\tdata += origRead;\n\t\t\tdataSize -= origRead;\n\t\t\t_saveDataStr.clear();\n\t\t} else {\n\t\t\t\/\/This part is tricky. They want less data than we saved. Give them what they\n\t\t\t\/\/requested, then delete from the front of the saveDataStr by using it's substr method.\n\t\t\tmemcpy(data, _saveDataStr.c_str(), dataSize);\n\t\t\tstring newDataStr;\n\t\t\tnewDataStr = _saveDataStr.substr(dataSize, _saveDataStr.size() - dataSize);\n\t\t\t_saveDataStr = newDataStr;\n\t\t\treturn dataSize;\n\t\t}\n\t}\n\tif (_streamFinished) {\n\t\treturn origRead;\n\t}\n\tif (_isBgzipped) {\n\t\tssize_t rc;\n\t\tif((rc = bgzf_read(_bgStream, data, dataSize)) < 0)\n\t\t\treturn -1;\n\n\t\treturn (int)(origRead + rc);\n\t}\n\t_finalInputStream->read(data, dataSize);\n\treturn origRead + _finalInputStream->gcount();\n}\n\nbool InputStreamMgr::populateScanBuffer()\n{\n\t_scanBuffer.clear();\n\t_saveDataStr.clear();\n\tint numChars=0;\n\tint currChar = 0;\n\twhile (1) {\n\t\tif (_isGzipped && _bamRuledOut) {\n\t\t\treturn readZipChunk();\n\t\t}\n\t\tcurrChar = _pushBackStreamBuf->sbumpc();\n\t\t\/\/Stop when EOF hit.\n\t\tif (currChar == EOF) {\n\t\t\t_eofHit = true;\n\t\t\tbreak;\n\t\t}\n\t\tnumChars++;\n\t\t_scanBuffer.push_back(currChar);\n\t\tif (_isGzipped) {\n\t\t\tif (!_bamRuledOut && detectBamOrBgzip(numChars, currChar)) {\n\t\t\t\t\/\/we now know the file is in bgzipped format\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\tif (numChars == 0) {\n\t\t\t\tcontinue; \/\/this will only happen when we've just discovered that this\n\t\t\t\t\/\/is definitely not BAM, and want to start over.\n\t\t\t}\n\t\t}\n\n\t\t\/\/Stop if we have the minimum number of bytes and newline is hit.\n\t\t\/\/For gzip, stop at SCAN_BUFFER_SIZE.\n\t\tif (currChar == '\\n' && numChars >= MIN_SCAN_BUFFER_SIZE ){\n\t\t\tbreak;\n\t\t}\n\t}\n\t_numBytesInBuffer = _scanBuffer.size();\n\t\/\/append it to the savedDataStr.\n \t_scanBuffer.toStr(_saveDataStr, true);\n\tif (_numBytesInBuffer == 0) return false;\n\treturn true;\n}\n\nbool InputStreamMgr::detectBamOrBgzip(int &numChars, int currChar)\n{\n\t\/\/Look for the BAM magic string \"BAM\\1\" in the first fouur characters of the input stream.\n\t\/\/In compressed form, the first char is the gzip signifier, which was already found.\n\t\/\/The next three are the integers 139, 8, and 4.\n\tif (numChars < 5) {\n\t\t_possibleBamCode[numChars -1] = currChar;\n\t\t\/\/special: test for BAM\n\t\tif (numChars == 4 && _possibleBamCode[1] == 139 && _possibleBamCode[2] == 8 && _possibleBamCode[3] == 4) {\n\t\t\t\/\/BAM magic string detected.This is either a BAM or bgzip file. To find out which, we have to try and\n\t\t\t\/\/open the file as BAM, with a BAM reader, and see if the header and references are both non-empty.\n\t\t\t\/\/However, if they are empty, we will have had to save all bytes consumed in the attempt, meaning still\n\t\t\t\/\/fill the scanBuffer and push it back onto the pushBackStream as normal.\n\t\t\tfor (; numChars < BAM_SCAN_BUFFER_SIZE; numChars++) {\n\t\t\t\tcurrChar = _pushBackStreamBuf->sbumpc();\n\t\t\t\t\/\/Stop when EOF hit.\n\t\t\t\tif (currChar == EOF) {\n\t\t\t\t\t_eofHit = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\t_scanBuffer.push_back(currChar);\n\n\t\t\t}\n\t\t\t_pushBackStreamBuf->pushBack(_scanBuffer);\n\n\t\t\t\/\/ok, now all the data read so far is saved in the scan buffer, and pushbackstream is reset.\n\t\t\t\/\/now we make a BamReader and try to open the file.\n\n\n\t\t\t_bamReader = new BamTools::BamReader();\n\t\t\tif (!_bamReader->OpenStream(_finalInputStream)) {\n\t\t\t\t\/\/This is NOT a bam file, but it is bgzipped.\n\t\t\t\t_pushBackStreamBuf->clear();\n\t\t\t\t\/\/Put all bytes read so far back onto the scan buffer, then reset\n\t\t\t\t\/\/everything so that we're effectively starting over.\n\t\t\t\t_pushBackStreamBuf->pushBack(_scanBuffer);\n\t\t\t\t_scanBuffer.clear();\n\t\t\t\tnumChars = 0;\n\t\t\t\t_isBam = false;\n\t\t\t\t_isBgzipped = true;\n\t\t\t\t_bamRuledOut = true;\n\t\t\t\t_numBytesInBuffer = 0;\n\t\t\t\tdelete _bamReader;\n\t\t\t\t_bamReader = NULL;\n\t\t\t\t_finalInputStream->clear();\n\n\n\t\t\t\tBamTools::stream_data_t* cb_data = new BamTools::stream_data_t(*_finalInputStream);\n\t\t\t\thFILE_callback_ops ops;\n\t\t\t\tmemset(&ops, 0, sizeof(ops));\n\t\t\t\tops.read = BamTools::stream_data_t::read;\n\t\t\t\tops.close = BamTools::stream_data_t::close;\n\t\t\t\tops.cb_data = cb_data;\n\t\t\t\thFILE* hp = hopen_callback(ops, \"rb\");\n\t\t\t\tif(nullptr == hp) return false;\n\t\t\t\tif(nullptr == (_bgStream = bgzf_hopen(hp, \"rb\")))\n\t\t\t\t\treturn false;\n\t\t\t\t\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\t\/\/This is a BAM file.\n\t\t\t_isBam = true;\n\t\t\t_numBytesInBuffer = _scanBuffer.size();\n\t\t\treturn true;\n\t\t} else if (numChars == 4) {\n\t\t\t\/\/This is a gzipped file, and it is not bgzipped or BAM.\n\t\t\t_pushBackStreamBuf->clear();\n\t\t\t_pushBackStreamBuf->pushBack(_scanBuffer);\n\t\t\t_scanBuffer.clear();\n\t\t\tnumChars = 0;\n\t\t\t_isBam = false;\n\t\t\t_isBgzipped = false;\n\t\t\t_bamRuledOut = true;\n\t\t\t_numBytesInBuffer = 0;\n\t\t\t_infStreamBuf = new InflateStreamBuf(_finalInputStream);\n\t\t\tdelete _oldInputStream;\n\t\t\t_oldInputStream = _finalInputStream;\n\t\t\t_finalInputStream = new istream(_infStreamBuf);\n\t\t\treturn false;\n\t\t}\n\t}\n\treturn false;\n}\n\nbool InputStreamMgr::readZipChunk()\n{\n\tif (_tmpZipBuf == NULL) {\n\t\t_tmpZipBuf = new char[SCAN_BUFFER_SIZE +1];\n\t}\n\tmemset(_tmpZipBuf, 0, SCAN_BUFFER_SIZE +1);\n\tsize_t numCharsRead = read(_tmpZipBuf, (size_t)SCAN_BUFFER_SIZE);\n\t_saveDataStr.append(_tmpZipBuf);\n\t_numBytesInBuffer = _saveDataStr.size();\n\tif ((int)numCharsRead < SCAN_BUFFER_SIZE) {\n\t\t_streamFinished = true;\n\t}\n\tif (numCharsRead == 0) return false;\n\treturn true;\n}\n\nbool InputStreamMgr::resetStream()\n{\n\t_saveDataStr.clear();\n\tif (!_isBam && !_isStdin && !_isGzipped) {\n\t\t\/\/For non-compressed, non-stdin file input, just re-open the file.\n\t\tdelete _finalInputStream;\n\t\t_finalInputStream = new ifstream(_filename.c_str());\n\t\treturn true;\n\t}\n\treturn false;\n}\n\n\n<commit_msg>Cram support<commit_after>\/*\n * InputStreamMgr.cpp\n *\n * Created on: Mar 21, 2013\n * Author: nek3d\n *\/\n\n#include \"InputStreamMgr.h\"\n#include <cstring> \/\/for memset\n#include \"gzstream.h\"\n#include \"CompressionTools.h\"\n\nconst char *InputStreamMgr::FIFO_STRING_LITERAL = \"\/dev\/fd\";\n\nInputStreamMgr::InputStreamMgr(const string &filename, bool buildScanBuffer)\n:\n _filename(filename),\n _pushBackStreamBuf(NULL),\n _inputFileStream(NULL),\n _infStreamBuf(NULL),\n _oldInputStream(NULL),\n _isStdin(false),\n _isGzipped(false),\n _isBam(false),\n _isBgzipped(false),\n _tmpZipBuf(NULL),\n _bamRuledOut(false),\n _streamFinished(false),\n _numBytesInBuffer(0),\n _bamReader(NULL),\n _bgStream(NULL),\n _eofHit(false)\n{\n\t_possibleBamCode.resize(4, 0);\n}\n\n\nInputStreamMgr::~InputStreamMgr() {\n\tdelete _pushBackStreamBuf;\n\t_pushBackStreamBuf = NULL;\n\n\tdelete _inputFileStream;\n\t_inputFileStream = NULL;\n\n\tdelete _oldInputStream;\n\t_oldInputStream = NULL;\n\n\tdelete _infStreamBuf;\n\t_infStreamBuf = NULL;\n\n\tif(_bamReader) _bamReader->Close();\n\tdelete _bamReader;\n\n\tdelete _bgStream;\n\t_bgStream = NULL;\n\n\tdelete _finalInputStream;\n\t_finalInputStream = NULL;\n\n\tdelete [] _tmpZipBuf;\n\t_tmpZipBuf = NULL;\n}\n\nbool InputStreamMgr::init()\n{\n\tif (_filename == \"-\" || _filename == \"stdin\") { \/\/stdin\n\t\t_isStdin = true;\n\t\t\/\/peek at the first char of stdin to see if this is gzipped.\n\t\tif ((unsigned char)cin.peek() == 0x1f) {\n\t\t\t_isGzipped = true;\n\t\t}\n\t\t_pushBackStreamBuf = new PushBackStreamBuf(cin.rdbuf());\n\t} else {\n\t\tif (strncmp(_filename.c_str(), FIFO_STRING_LITERAL, strlen(FIFO_STRING_LITERAL)) == 0) {\n\t\t\t_isStdin = true;\n\t\t}\n\t\t_inputFileStream = new ifstream(_filename.c_str());\n\t\tif (_inputFileStream->fail()) {\n\t\t\tcerr << \"Error: Unable to open file \" << _filename << \". Exiting.\" << endl;\n\t\t\tdelete _inputFileStream;\n\t\t\t_inputFileStream = NULL;\n\t\t\texit(1);\n\t\t}\n\t\t\/\/peek at the first char of stdin to see if this is gzipped.\n\t\tif ((unsigned char)_inputFileStream->peek() == 0x1f) {\n\t\t\t_isGzipped = true;\n\t\t}\n\t\t_pushBackStreamBuf = new PushBackStreamBuf(_inputFileStream->rdbuf());\n\t}\n\t\/\/now we have a PushBackStreamBuf. Make a new stream.\n\t_finalInputStream = new istream(_pushBackStreamBuf);\n\tpopulateScanBuffer();\n\treturn true;\n}\n\nint InputStreamMgr::read(char *data, size_t dataSize)\n{\n\tsize_t origRead = 0;\n\tif (!_saveDataStr.empty()) {\n\t\t\/\/must first copy contents of savedData into requested data read buffer.\n\t\tif (dataSize >= _saveDataStr.size()) {\n\t\t\t\/\/They asked for the same amount of data or more than we saved. Give them all the saved data,\n\t\t\t\/\/then decrement the requested data size accordingly.\n\t\t\torigRead = _saveDataStr.size();\n\t\t\tmemcpy(data, _saveDataStr.c_str(), origRead);\n\t\t\tdata += origRead;\n\t\t\tdataSize -= origRead;\n\t\t\t_saveDataStr.clear();\n\t\t} else {\n\t\t\t\/\/This part is tricky. They want less data than we saved. Give them what they\n\t\t\t\/\/requested, then delete from the front of the saveDataStr by using it's substr method.\n\t\t\tmemcpy(data, _saveDataStr.c_str(), dataSize);\n\t\t\tstring newDataStr;\n\t\t\tnewDataStr = _saveDataStr.substr(dataSize, _saveDataStr.size() - dataSize);\n\t\t\t_saveDataStr = newDataStr;\n\t\t\treturn dataSize;\n\t\t}\n\t}\n\tif (_streamFinished) {\n\t\treturn origRead;\n\t}\n\tif (_isBgzipped) {\n\t\tssize_t rc;\n\t\tif((rc = bgzf_read(_bgStream, data, dataSize)) < 0)\n\t\t\treturn -1;\n\n\t\treturn (int)(origRead + rc);\n\t}\n\t_finalInputStream->read(data, dataSize);\n\treturn origRead + _finalInputStream->gcount();\n}\n\nbool InputStreamMgr::populateScanBuffer()\n{\n\t_scanBuffer.clear();\n\t_saveDataStr.clear();\n\tint numChars=0;\n\tint currChar = 0;\n\tchar cram_code[4];\n\twhile (1) {\n\t\tif (_isGzipped && _bamRuledOut) {\n\t\t\treturn readZipChunk();\n\t\t}\n\t\tcurrChar = _pushBackStreamBuf->sbumpc();\n\t\t\/\/Stop when EOF hit.\n\t\tif (currChar == EOF) {\n\t\t\t_eofHit = true;\n\t\t\tbreak;\n\t\t}\n\t\tnumChars++;\n\t\t_scanBuffer.push_back(currChar);\n\t\tif (_isGzipped) {\n\t\t\tif (!_bamRuledOut && detectBamOrBgzip(numChars, currChar)) {\n\t\t\t\t\/\/we now know the file is in bgzipped format\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\tif (numChars == 0) {\n\t\t\t\tcontinue; \/\/this will only happen when we've just discovered that this\n\t\t\t\t\/\/is definitely not BAM, and want to start over.\n\t\t\t}\n\t\t}\n\t else\n\t {\n\t\t\tif(numChars <= 4) cram_code[numChars-1] = currChar;\n\t\t\tif(numChars == 4 && memcmp(cram_code, \"CRAM\", 4) == 0)\n\t\t\t{\n\t\t\t\tfor (; numChars < BAM_SCAN_BUFFER_SIZE; numChars++) {\n\t\t\t\t\tcurrChar = _pushBackStreamBuf->sbumpc();\n\t\t\t\t\t\/\/Stop when EOF hit.\n\t\t\t\t\tif (currChar == EOF) {\n\t\t\t\t\t\t_eofHit = true;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\t_scanBuffer.push_back(currChar);\n\n\t\t\t\t}\n\t\t\t\t_pushBackStreamBuf->pushBack(_scanBuffer);\n\n\t\t\t\t_bamReader = new BamTools::BamReader();\n\t\t\t\tif (_bamReader->OpenStream(_finalInputStream))\n\t\t\t\t{\n\t\t\t\t\t_isBam = true;\n\t\t\t\t\t_numBytesInBuffer = _scanBuffer.size();\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\telse return false;\n\t\t\t}\n\t\t}\n\n\n\t\t\/\/Stop if we have the minimum number of bytes and newline is hit.\n\t\t\/\/For gzip, stop at SCAN_BUFFER_SIZE.\n\t\tif (currChar == '\\n' && numChars >= MIN_SCAN_BUFFER_SIZE ){\n\t\t\tbreak;\n\t\t}\n\t}\n\t_numBytesInBuffer = _scanBuffer.size();\n\t\/\/append it to the savedDataStr.\n \t_scanBuffer.toStr(_saveDataStr, true);\n\tif (_numBytesInBuffer == 0) return false;\n\treturn true;\n}\n\nbool InputStreamMgr::detectBamOrBgzip(int &numChars, int currChar)\n{\n\t\/\/Look for the BAM magic string \"BAM\\1\" in the first fouur characters of the input stream.\n\t\/\/In compressed form, the first char is the gzip signifier, which was already found.\n\t\/\/The next three are the integers 139, 8, and 4.\n\tif (numChars < 5) {\n\t\t_possibleBamCode[numChars -1] = currChar;\n\t\t\/\/special: test for BAM\n\t\tif (numChars == 4 && _possibleBamCode[1] == 139 && _possibleBamCode[2] == 8 && _possibleBamCode[3] == 4) {\n\t\t\t\/\/BAM magic string detected.This is either a BAM or bgzip file. To find out which, we have to try and\n\t\t\t\/\/open the file as BAM, with a BAM reader, and see if the header and references are both non-empty.\n\t\t\t\/\/However, if they are empty, we will have had to save all bytes consumed in the attempt, meaning still\n\t\t\t\/\/fill the scanBuffer and push it back onto the pushBackStream as normal.\n\t\t\tfor (; numChars < BAM_SCAN_BUFFER_SIZE; numChars++) {\n\t\t\t\tcurrChar = _pushBackStreamBuf->sbumpc();\n\t\t\t\t\/\/Stop when EOF hit.\n\t\t\t\tif (currChar == EOF) {\n\t\t\t\t\t_eofHit = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\t_scanBuffer.push_back(currChar);\n\n\t\t\t}\n\t\t\t_pushBackStreamBuf->pushBack(_scanBuffer);\n\n\t\t\t\/\/ok, now all the data read so far is saved in the scan buffer, and pushbackstream is reset.\n\t\t\t\/\/now we make a BamReader and try to open the file.\n\n\n\t\t\t_bamReader = new BamTools::BamReader();\n\t\t\tif (!_bamReader->OpenStream(_finalInputStream)) {\n\t\t\t\t\/\/This is NOT a bam file, but it is bgzipped.\n\t\t\t\t_pushBackStreamBuf->clear();\n\t\t\t\t\/\/Put all bytes read so far back onto the scan buffer, then reset\n\t\t\t\t\/\/everything so that we're effectively starting over.\n\t\t\t\t_pushBackStreamBuf->pushBack(_scanBuffer);\n\t\t\t\t_scanBuffer.clear();\n\t\t\t\tnumChars = 0;\n\t\t\t\t_isBam = false;\n\t\t\t\t_isBgzipped = true;\n\t\t\t\t_bamRuledOut = true;\n\t\t\t\t_numBytesInBuffer = 0;\n\t\t\t\tdelete _bamReader;\n\t\t\t\t_bamReader = NULL;\n\t\t\t\t_finalInputStream->clear();\n\n\n\t\t\t\tBamTools::stream_data_t* cb_data = new BamTools::stream_data_t(*_finalInputStream);\n\t\t\t\thFILE_callback_ops ops;\n\t\t\t\tmemset(&ops, 0, sizeof(ops));\n\t\t\t\tops.read = BamTools::stream_data_t::read;\n\t\t\t\tops.close = BamTools::stream_data_t::close;\n\t\t\t\tops.cb_data = cb_data;\n\t\t\t\thFILE* hp = hopen_callback(ops, \"rb\");\n\t\t\t\tif(nullptr == hp) return false;\n\t\t\t\tif(nullptr == (_bgStream = bgzf_hopen(hp, \"rb\")))\n\t\t\t\t\treturn false;\n\t\t\t\t\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\t\/\/This is a BAM file.\n\t\t\t_isBam = true;\n\t\t\t_numBytesInBuffer = _scanBuffer.size();\n\t\t\treturn true;\n\t\t} else if (numChars == 4) {\n\t\t\t\/\/This is a gzipped file, and it is not bgzipped or BAM.\n\t\t\t_pushBackStreamBuf->clear();\n\t\t\t_pushBackStreamBuf->pushBack(_scanBuffer);\n\t\t\t_scanBuffer.clear();\n\t\t\tnumChars = 0;\n\t\t\t_isBam = false;\n\t\t\t_isBgzipped = false;\n\t\t\t_bamRuledOut = true;\n\t\t\t_numBytesInBuffer = 0;\n\t\t\t_infStreamBuf = new InflateStreamBuf(_finalInputStream);\n\t\t\tdelete _oldInputStream;\n\t\t\t_oldInputStream = _finalInputStream;\n\t\t\t_finalInputStream = new istream(_infStreamBuf);\n\t\t\treturn false;\n\t\t}\n\t}\n\treturn false;\n}\n\nbool InputStreamMgr::readZipChunk()\n{\n\tif (_tmpZipBuf == NULL) {\n\t\t_tmpZipBuf = new char[SCAN_BUFFER_SIZE +1];\n\t}\n\tmemset(_tmpZipBuf, 0, SCAN_BUFFER_SIZE +1);\n\tsize_t numCharsRead = read(_tmpZipBuf, (size_t)SCAN_BUFFER_SIZE);\n\t_saveDataStr.append(_tmpZipBuf);\n\t_numBytesInBuffer = _saveDataStr.size();\n\tif ((int)numCharsRead < SCAN_BUFFER_SIZE) {\n\t\t_streamFinished = true;\n\t}\n\tif (numCharsRead == 0) return false;\n\treturn true;\n}\n\nbool InputStreamMgr::resetStream()\n{\n\t_saveDataStr.clear();\n\tif (!_isBam && !_isStdin && !_isGzipped) {\n\t\t\/\/For non-compressed, non-stdin file input, just re-open the file.\n\t\tdelete _finalInputStream;\n\t\t_finalInputStream = new ifstream(_filename.c_str());\n\t\treturn true;\n\t}\n\treturn false;\n}\n\n\n<|endoftext|>"} {"text":"<commit_before>#include \"Particle3DBuilder.h\"\n#include \"PackParticle3D.h\"\n#include \"PackNodeFactory.h\"\n#include \"P3dSprBuilder.h\"\n\n#include <ee\/Visitor.h>\n\n#include <easyparticle3d.h>\n\n#include <ps_3d.h>\n\nnamespace erespacker\n{\n\nParticle3DBuilder::Particle3DBuilder()\n{\n}\n\nParticle3DBuilder::~Particle3DBuilder()\n{\n\tstd::map<const eparticle3d::Symbol*, const PackParticle3D*>::iterator\n\t\titr = m_map_data.begin();\n\tfor ( ; itr != m_map_data.end(); ++itr) {\n\t\tdelete itr->second;\n\t}\n}\n\nvoid Particle3DBuilder::Traverse(ee::Visitor& visitor) const\n{\n\tstd::map<const eparticle3d::Symbol*, const PackParticle3D*>::const_iterator \n\t\titr = m_map_data.begin();\n\tfor ( ; itr != m_map_data.end(); ++itr) {\n\t\tbool has_next;\n\t\tvisitor.Visit(const_cast<PackParticle3D*>(itr->second), has_next);\n\t\tif (!has_next) {\n\t\t\tbreak;\n\t\t}\n\t}\n}\n\nconst IPackNode* Particle3DBuilder::Create(const eparticle3d::Symbol* symbol, P3dSprBuilder* spr_builder)\n{\n\tstd::map<const eparticle3d::Symbol*, const PackParticle3D*>::iterator \n\t\titr = m_map_data.find(symbol);\n\tif (itr != m_map_data.end()) {\n\t\treturn itr->second;\n\t}\n\n\tPackParticle3D* node = new PackParticle3D;\n\tLoad(symbol, node);\n\tm_map_data.insert(std::make_pair(symbol, node));\n\tspr_builder->Create(symbol, node);\n\treturn node;\n}\n\nvoid Particle3DBuilder::Load(const eparticle3d::Symbol* symbol, PackParticle3D* ps)\n{\n\tconst p3d_emitter_cfg* cfg = symbol->GetEmitterCfg();\n\t\n\tps->static_mode = cfg->static_mode;\n\n\tps->emission_time = cfg->emission_time;\n\tps->count = cfg->count;\n\n\tps->life = cfg->life;\n\tps->life_var = cfg->life_var;\n\n\tps->hori = cfg->hori;\n\tps->hori_var = cfg->hori_var;\n\tps->vert = cfg->vert;\n\tps->vert_var = cfg->vert_var;\n\n\tps->radial_spd = cfg->radial_spd;\n\tps->radial_spd_var = cfg->radial_spd_var;\n\tps->tangential_spd = cfg->tangential_spd;\n\tps->tangential_spd_var = cfg->tangential_spd_var;\n\tps->angular_spd = cfg->angular_spd;\n\tps->angular_spd_var = cfg->angular_spd_var;\n\n\tps->dis_region = cfg->dis_region;\n\tps->dis_region_var = cfg->dis_region_var;\n\tps->dis_spd = cfg->dis_spd;\n\tps->dis_spd_var = cfg->dis_spd_var;\n\n\tps->gravity = cfg->gravity;\n\n\tps->linear_acc = cfg->linear_acc;\n\tps->linear_acc_var = cfg->linear_acc_var;\n\n\tps->fadeout_time = cfg->fadeout_time;\n\n\tps->ground = cfg->ground;\n\n\tps->start_radius = cfg->start_radius;\n\tps->start_height = cfg->start_height;\n\n\tps->orient_to_movement = cfg->orient_to_movement;\n\n\tps->components.reserve(cfg->symbol_count);\n\tfor (int i = 0; i < cfg->symbol_count; ++i) \n\t{\n\t\tconst p3d_symbol& p_symbol = cfg->symbols[i];\n\n\t\tPackParticle3D::Component comp;\n\n\t\tcomp.count = p_symbol.count;\n\n\t\tcomp.scale_start = p_symbol.scale_start;\n\t\tcomp.scale_end = p_symbol.scale_end;\n\n\t\tcomp.angle = p_symbol.angle;\n\t\tcomp.angle_var = p_symbol.angle_var;\n\n\t\tcomp.col_mul = s2::Color((int)(p_symbol.col_mul.r * 255), (int)(p_symbol.col_mul.g * 255), \n\t\t\t(int)(p_symbol.col_mul.b * 255), (int)(p_symbol.col_mul.a * 255)).ToABGR();\n\t\tcomp.col_add = s2::Color((int)(p_symbol.col_add.r * 255), (int)(p_symbol.col_add.g * 255), \n\t\t\t(int)(p_symbol.col_add.b * 255), (int)(p_symbol.col_add.a * 255)).ToABGR();\n\t\tcomp.alpha_start = p_symbol.alpha_start * 255.0f + 0.5f;\n\t\tcomp.alpha_end = p_symbol.alpha_end * 255.0f + 0.5f;\n\n\t\tee::Symbol* symbol = static_cast<ee::Symbol*>(p_symbol.ud);\n\t\tcomp.node = PackNodeFactory::Instance()->Create(symbol);\n\n\t\tps->components.push_back(comp);\n\t}\n}\n\n}<commit_msg>[FIXED] pack p3d color, use argb format<commit_after>#include \"Particle3DBuilder.h\"\n#include \"PackParticle3D.h\"\n#include \"PackNodeFactory.h\"\n#include \"P3dSprBuilder.h\"\n\n#include <ee\/Visitor.h>\n#include <ee\/trans_color.h>\n\n#include <easyparticle3d.h>\n\n#include <ps_3d.h>\n\nnamespace erespacker\n{\n\nParticle3DBuilder::Particle3DBuilder()\n{\n}\n\nParticle3DBuilder::~Particle3DBuilder()\n{\n\tstd::map<const eparticle3d::Symbol*, const PackParticle3D*>::iterator\n\t\titr = m_map_data.begin();\n\tfor ( ; itr != m_map_data.end(); ++itr) {\n\t\tdelete itr->second;\n\t}\n}\n\nvoid Particle3DBuilder::Traverse(ee::Visitor& visitor) const\n{\n\tstd::map<const eparticle3d::Symbol*, const PackParticle3D*>::const_iterator \n\t\titr = m_map_data.begin();\n\tfor ( ; itr != m_map_data.end(); ++itr) {\n\t\tbool has_next;\n\t\tvisitor.Visit(const_cast<PackParticle3D*>(itr->second), has_next);\n\t\tif (!has_next) {\n\t\t\tbreak;\n\t\t}\n\t}\n}\n\nconst IPackNode* Particle3DBuilder::Create(const eparticle3d::Symbol* symbol, P3dSprBuilder* spr_builder)\n{\n\tstd::map<const eparticle3d::Symbol*, const PackParticle3D*>::iterator \n\t\titr = m_map_data.find(symbol);\n\tif (itr != m_map_data.end()) {\n\t\treturn itr->second;\n\t}\n\n\tPackParticle3D* node = new PackParticle3D;\n\tLoad(symbol, node);\n\tm_map_data.insert(std::make_pair(symbol, node));\n\tspr_builder->Create(symbol, node);\n\treturn node;\n}\n\nvoid Particle3DBuilder::Load(const eparticle3d::Symbol* symbol, PackParticle3D* ps)\n{\n\tconst p3d_emitter_cfg* cfg = symbol->GetEmitterCfg();\n\t\n\tps->static_mode = cfg->static_mode;\n\n\tps->emission_time = cfg->emission_time;\n\tps->count = cfg->count;\n\n\tps->life = cfg->life;\n\tps->life_var = cfg->life_var;\n\n\tps->hori = cfg->hori;\n\tps->hori_var = cfg->hori_var;\n\tps->vert = cfg->vert;\n\tps->vert_var = cfg->vert_var;\n\n\tps->radial_spd = cfg->radial_spd;\n\tps->radial_spd_var = cfg->radial_spd_var;\n\tps->tangential_spd = cfg->tangential_spd;\n\tps->tangential_spd_var = cfg->tangential_spd_var;\n\tps->angular_spd = cfg->angular_spd;\n\tps->angular_spd_var = cfg->angular_spd_var;\n\n\tps->dis_region = cfg->dis_region;\n\tps->dis_region_var = cfg->dis_region_var;\n\tps->dis_spd = cfg->dis_spd;\n\tps->dis_spd_var = cfg->dis_spd_var;\n\n\tps->gravity = cfg->gravity;\n\n\tps->linear_acc = cfg->linear_acc;\n\tps->linear_acc_var = cfg->linear_acc_var;\n\n\tps->fadeout_time = cfg->fadeout_time;\n\n\tps->ground = cfg->ground;\n\n\tps->start_radius = cfg->start_radius;\n\tps->start_height = cfg->start_height;\n\n\tps->orient_to_movement = cfg->orient_to_movement;\n\n\tps->components.reserve(cfg->symbol_count);\n\tfor (int i = 0; i < cfg->symbol_count; ++i) \n\t{\n\t\tconst p3d_symbol& p_symbol = cfg->symbols[i];\n\n\t\tPackParticle3D::Component comp;\n\n\t\tcomp.count = p_symbol.count;\n\n\t\tcomp.scale_start = p_symbol.scale_start;\n\t\tcomp.scale_end = p_symbol.scale_end;\n\n\t\tcomp.angle = p_symbol.angle;\n\t\tcomp.angle_var = p_symbol.angle_var;\n\n\t\ts2::Color mul((int)(p_symbol.col_mul.r * 255), (int)(p_symbol.col_mul.g * 255), \n\t\t\t(int)(p_symbol.col_mul.b * 255), (int)(p_symbol.col_mul.a * 255));\n\t\ts2::Color add((int)(p_symbol.col_add.r * 255), (int)(p_symbol.col_add.g * 255), \n\t\t\t(int)(p_symbol.col_add.b * 255), (int)(p_symbol.col_add.a * 255));\n\t\tcomp.col_mul = ee::color2int(mul, ee::PT_ARGB);\n\t\tcomp.col_add = ee::color2int(add, ee::PT_ARGB);\n\t\tcomp.alpha_start = p_symbol.alpha_start * 255.0f + 0.5f;\n\t\tcomp.alpha_end = p_symbol.alpha_end * 255.0f + 0.5f;\n\n\t\tee::Symbol* symbol = static_cast<ee::Symbol*>(p_symbol.ud);\n\t\tcomp.node = PackNodeFactory::Instance()->Create(symbol);\n\n\t\tps->components.push_back(comp);\n\t}\n}\n\n}<|endoftext|>"} {"text":"<commit_before>\/\/ WlanTest.cpp : Defines the entry point for the console application.\n\/\/\n\n\/\/ #include \"stdafx.h\"\n#include <stdio.h>\n#include <tchar.h>\n\n#include <conio.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <windows.h>\n#include <wlanapi.h>\n\n#define WLAN_CLIENT_VERSION_VISTA 2\n\nvoid SetInterface(WLAN_INTF_OPCODE opcode, PVOID* pData, GUID* InterfaceGuid)\n{\n\tDWORD dwResult = 0;\n\tHANDLE hClient = NULL;\n\tDWORD dwCurVersion = 0;\n\tDWORD outsize = 0;\n\n\t\/\/ Open Handle for the set operation\n\tdwResult = WlanOpenHandle(WLAN_CLIENT_VERSION_VISTA, NULL, &dwCurVersion, &hClient);\n\tdwResult = WlanSetInterface(hClient, InterfaceGuid, opcode, sizeof(ULONG), pData, NULL);\n\tWlanCloseHandle(hClient, NULL);\n\n}\n\n\/\/ enumerate wireless interfaces\nUINT EnumInterface(HANDLE hClient, WLAN_INTERFACE_INFO sInfo[64])\n{\n\tDWORD dwError = ERROR_SUCCESS;\n\tPWLAN_INTERFACE_INFO_LIST pIntfList = NULL;\n\tUINT i = 0;\n\n\t__try\n\t{\n\t\t\/\/ enumerate wireless interfaces\n\t\tif ((dwError = WlanEnumInterfaces(\n\t\t\thClient,\n\t\t\tNULL, \/\/ reserved\n\t\t\t&pIntfList\n\t\t\t)) != ERROR_SUCCESS)\n\t\t{\n\t\t\t__leave;\n\t\t}\n\n\t\t\/\/ print out interface information\n\t\tfor (i = 0; i < pIntfList->dwNumberOfItems; i++)\n\t\t{\n\t\t\tmemcpy(&sInfo[i], &pIntfList->InterfaceInfo[i], sizeof(WLAN_INTERFACE_INFO));\n\t\t}\n\n\t\treturn pIntfList->dwNumberOfItems;\n\t}\n\t__finally\n\t{\n\t\t\/\/ clean up\n\t\tif (pIntfList != NULL)\n\t\t{\n\t\t\tWlanFreeMemory(pIntfList);\n\t\t}\n\t}\n\treturn 0;\n}\n\n\/\/ open a WLAN client handle and check version\nDWORD\nOpenHandleAndCheckVersion(\nPHANDLE phClient\n)\n{\n\tDWORD dwError = ERROR_SUCCESS;\n\tDWORD dwServiceVersion;\n\tHANDLE hClient = NULL;\n\n\t__try\n\t{\n\t\t*phClient = NULL;\n\n\t\t\/\/ open a handle to the service\n\t\tif ((dwError = WlanOpenHandle(\n\t\t\tWLAN_API_VERSION,\n\t\t\tNULL, \/\/ reserved\n\t\t\t&dwServiceVersion,\n\t\t\t&hClient\n\t\t\t)) != ERROR_SUCCESS)\n\t\t{\n\t\t\t__leave;\n\t\t}\n\n\t\t\/\/ check service version\n\t\tif (WLAN_API_VERSION_MAJOR(dwServiceVersion) < WLAN_API_VERSION_MAJOR(WLAN_API_VERSION_2_0))\n\t\t{\n\t\t\t\/\/ No-op, because the version check is for demonstration purpose only.\n\t\t\t\/\/ You can add your own logic here.\n\t\t}\n\n\t\t*phClient = hClient;\n\n\t\t\/\/ set hClient to NULL so it will not be closed\n\t\thClient = NULL;\n\t}\n\t__finally\n\t{\n\t\tif (hClient != NULL)\n\t\t{\n\t\t\t\/\/ clean up\n\t\t\tWlanCloseHandle(\n\t\t\t\thClient,\n\t\t\t\tNULL \/\/ reserved\n\t\t\t\t);\n\t\t}\n\t}\n\n\treturn dwError;\n}\n\n\/\/ get interface state string\nLPWSTR\nGetInterfaceStateString(__in WLAN_INTERFACE_STATE wlanInterfaceState)\n{\n\tLPWSTR strRetCode;\n\n\tswitch (wlanInterfaceState)\n\t{\n\tcase wlan_interface_state_not_ready:\n\t\tstrRetCode = L\"\\\"not ready\\\"\";\n\t\tbreak;\n\tcase wlan_interface_state_connected:\n\t\tstrRetCode = L\"\\\"connected\\\"\";\n\t\tbreak;\n\tcase wlan_interface_state_ad_hoc_network_formed:\n\t\tstrRetCode = L\"\\\"ad hoc network formed\\\"\";\n\t\tbreak;\n\tcase wlan_interface_state_disconnecting:\n\t\tstrRetCode = L\"\\\"disconnecting\\\"\";\n\t\tbreak;\n\tcase wlan_interface_state_disconnected:\n\t\tstrRetCode = L\"\\\"disconnected\\\"\";\n\t\tbreak;\n\tcase wlan_interface_state_associating:\n\t\tstrRetCode = L\"\\\"associating\\\"\";\n\t\tbreak;\n\tcase wlan_interface_state_discovering:\n\t\tstrRetCode = L\"\\\"discovering\\\"\";\n\t\tbreak;\n\tcase wlan_interface_state_authenticating:\n\t\tstrRetCode = L\"\\\"authenticating\\\"\";\n\t\tbreak;\n\tdefault:\n\t\tstrRetCode = L\"\\\"invalid interface state\\\"\";\n\t}\n\n\treturn strRetCode;\n}\n\nint main()\n{\n\tHANDLE hClient = NULL;\n\tWLAN_INTERFACE_INFO sInfo[64];\n\tRPC_CSTR strGuid = NULL;\n\n\tTCHAR szBuffer[256];\n\tDWORD dwRead;\n\tif (OpenHandleAndCheckVersion(&hClient) != ERROR_SUCCESS)\n\t\treturn -1;\n\n\tUINT nCount = EnumInterface(hClient, sInfo);\n\tfor (UINT i = 0; i < nCount; ++i)\n\t{\n\t\tif (UuidToStringA(&sInfo[i].InterfaceGuid, &strGuid) == RPC_S_OK)\n\t\t{\n\t\t\tprintf((\"%d. %s\\n\\tDescription: %S\\n\\tState: %S\\n\"),\n\t\t\t\ti,\n\t\t\t\tstrGuid,\n\t\t\t\tsInfo[i].strInterfaceDescription,\n\t\t\t\tGetInterfaceStateString(sInfo[i].isState));\n\n\t\t\tRpcStringFreeA(&strGuid);\n\t\t}\n\t}\n\n\tUINT nChoice = 0;\n\tprintf(\"Enter the choice (0, 1,..) of the wireless card you want to operate on:\\n\");\n\n\tif (ReadConsole(GetStdHandle(STD_INPUT_HANDLE), szBuffer, _countof(szBuffer), &dwRead, NULL) == FALSE)\n\t{\n\t\tputs(\"Error input.\");\n\t\treturn -1;\n\t}\n\tszBuffer[dwRead] = 0;\n\tnChoice = _ttoi(szBuffer);\n\n\tif (nChoice > nCount)\n\t{\n\t\tputs(\"No such index.\");\n\t\treturn -1;\n\t}\n\n\tUINT nSTate = 0;\n\t\/\/ULONG targetOperationMode = DOT11_OPERATION_MODE_EXTENSIBLE_STATION;\n\tULONG targetOperationMode = DOT11_OPERATION_MODE_NETWORK_MONITOR;\n\tprintf(\"Enter the state (0, 1 or 2) you want to switch to for the chosen wireless card:\\n\");\n\tprintf(\"0: Managed Mode (ExtSTA)\\n1: Monitor Mode (NetMon)\\n2: Master Mode (ExtAP)\\n\");\n\n\tif (ReadConsole(GetStdHandle(STD_INPUT_HANDLE), szBuffer, _countof(szBuffer), &dwRead, NULL) == FALSE)\n\t{\n\t\tputs(\"Error input.\");\n\t\treturn -1;\n\t}\n\tszBuffer[dwRead] = 0;\n\tnSTate = _ttoi(szBuffer);\n\n\tif (nSTate != 0 && nSTate != 1 && nSTate != 2)\n\t{\n\t\tputs(\"Only 0, 1 and 2 are valid inputs.\");\n\t\treturn -1;\n\t}\n\tif (nSTate == 0)\n\t{\n\t\ttargetOperationMode = DOT11_OPERATION_MODE_EXTENSIBLE_STATION;\n\t}\n\tif (nSTate == 1)\n\t{\n\t\ttargetOperationMode = DOT11_OPERATION_MODE_NETWORK_MONITOR;\n\t}\n\telse \/\/ nSTate == 2\n\t{\n\t\ttargetOperationMode = DOT11_OPERATION_MODE_EXTENSIBLE_AP;\n\t}\n\n\tSetInterface(wlan_intf_opcode_current_operation_mode, (PVOID*)&targetOperationMode, &sInfo[nChoice].InterfaceGuid);\n\n\treturn 0;\n}\n\n<commit_msg>Added error code display when error occurs.<commit_after>\/\/ WlanHelper.cpp : Defines the entry point for the console application.\n\/\/\n\n\/\/ #include \"stdafx.h\"\n#include <stdio.h>\n#include <tchar.h>\n\n#include <conio.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <windows.h>\n#include <wlanapi.h>\n\n#define WLAN_CLIENT_VERSION_VISTA 2\n\nDWORD SetInterface(WLAN_INTF_OPCODE opcode, PVOID* pData, GUID* InterfaceGuid)\n{\n\tDWORD dwResult = 0;\n\tHANDLE hClient = NULL;\n\tDWORD dwCurVersion = 0;\n\tDWORD outsize = 0;\n\n\t\/\/ Open Handle for the set operation\n\tdwResult = WlanOpenHandle(WLAN_CLIENT_VERSION_VISTA, NULL, &dwCurVersion, &hClient);\n\tdwResult = WlanSetInterface(hClient, InterfaceGuid, opcode, sizeof(ULONG), pData, NULL);\n\tWlanCloseHandle(hClient, NULL);\n\n\treturn dwResult;\n}\n\n\/\/ enumerate wireless interfaces\nUINT EnumInterface(HANDLE hClient, WLAN_INTERFACE_INFO sInfo[64])\n{\n\tDWORD dwError = ERROR_SUCCESS;\n\tPWLAN_INTERFACE_INFO_LIST pIntfList = NULL;\n\tUINT i = 0;\n\n\t__try\n\t{\n\t\t\/\/ enumerate wireless interfaces\n\t\tif ((dwError = WlanEnumInterfaces(\n\t\t\thClient,\n\t\t\tNULL, \/\/ reserved\n\t\t\t&pIntfList\n\t\t\t)) != ERROR_SUCCESS)\n\t\t{\n\t\t\t__leave;\n\t\t}\n\n\t\t\/\/ print out interface information\n\t\tfor (i = 0; i < pIntfList->dwNumberOfItems; i++)\n\t\t{\n\t\t\tmemcpy(&sInfo[i], &pIntfList->InterfaceInfo[i], sizeof(WLAN_INTERFACE_INFO));\n\t\t}\n\n\t\treturn pIntfList->dwNumberOfItems;\n\t}\n\t__finally\n\t{\n\t\t\/\/ clean up\n\t\tif (pIntfList != NULL)\n\t\t{\n\t\t\tWlanFreeMemory(pIntfList);\n\t\t}\n\t}\n\treturn 0;\n}\n\n\/\/ open a WLAN client handle and check version\nDWORD\nOpenHandleAndCheckVersion(\nPHANDLE phClient\n)\n{\n\tDWORD dwError = ERROR_SUCCESS;\n\tDWORD dwServiceVersion;\n\tHANDLE hClient = NULL;\n\n\t__try\n\t{\n\t\t*phClient = NULL;\n\n\t\t\/\/ open a handle to the service\n\t\tif ((dwError = WlanOpenHandle(\n\t\t\tWLAN_API_VERSION,\n\t\t\tNULL, \/\/ reserved\n\t\t\t&dwServiceVersion,\n\t\t\t&hClient\n\t\t\t)) != ERROR_SUCCESS)\n\t\t{\n\t\t\t__leave;\n\t\t}\n\n\t\t\/\/ check service version\n\t\tif (WLAN_API_VERSION_MAJOR(dwServiceVersion) < WLAN_API_VERSION_MAJOR(WLAN_API_VERSION_2_0))\n\t\t{\n\t\t\t\/\/ No-op, because the version check is for demonstration purpose only.\n\t\t\t\/\/ You can add your own logic here.\n\t\t}\n\n\t\t*phClient = hClient;\n\n\t\t\/\/ set hClient to NULL so it will not be closed\n\t\thClient = NULL;\n\t}\n\t__finally\n\t{\n\t\tif (hClient != NULL)\n\t\t{\n\t\t\t\/\/ clean up\n\t\t\tWlanCloseHandle(\n\t\t\t\thClient,\n\t\t\t\tNULL \/\/ reserved\n\t\t\t\t);\n\t\t}\n\t}\n\n\treturn dwError;\n}\n\n\/\/ get interface state string\nLPWSTR\nGetInterfaceStateString(__in WLAN_INTERFACE_STATE wlanInterfaceState)\n{\n\tLPWSTR strRetCode;\n\n\tswitch (wlanInterfaceState)\n\t{\n\tcase wlan_interface_state_not_ready:\n\t\tstrRetCode = L\"\\\"not ready\\\"\";\n\t\tbreak;\n\tcase wlan_interface_state_connected:\n\t\tstrRetCode = L\"\\\"connected\\\"\";\n\t\tbreak;\n\tcase wlan_interface_state_ad_hoc_network_formed:\n\t\tstrRetCode = L\"\\\"ad hoc network formed\\\"\";\n\t\tbreak;\n\tcase wlan_interface_state_disconnecting:\n\t\tstrRetCode = L\"\\\"disconnecting\\\"\";\n\t\tbreak;\n\tcase wlan_interface_state_disconnected:\n\t\tstrRetCode = L\"\\\"disconnected\\\"\";\n\t\tbreak;\n\tcase wlan_interface_state_associating:\n\t\tstrRetCode = L\"\\\"associating\\\"\";\n\t\tbreak;\n\tcase wlan_interface_state_discovering:\n\t\tstrRetCode = L\"\\\"discovering\\\"\";\n\t\tbreak;\n\tcase wlan_interface_state_authenticating:\n\t\tstrRetCode = L\"\\\"authenticating\\\"\";\n\t\tbreak;\n\tdefault:\n\t\tstrRetCode = L\"\\\"invalid interface state\\\"\";\n\t}\n\n\treturn strRetCode;\n}\n\nint main()\n{\n\tHANDLE hClient = NULL;\n\tWLAN_INTERFACE_INFO sInfo[64];\n\tRPC_CSTR strGuid = NULL;\n\n\tTCHAR szBuffer[256];\n\tDWORD dwRead;\n\tif (OpenHandleAndCheckVersion(&hClient) != ERROR_SUCCESS)\n\t\treturn -1;\n\n\tUINT nCount = EnumInterface(hClient, sInfo);\n\tfor (UINT i = 0; i < nCount; ++i)\n\t{\n\t\tif (UuidToStringA(&sInfo[i].InterfaceGuid, &strGuid) == RPC_S_OK)\n\t\t{\n\t\t\tprintf((\"%d. %s\\n\\tDescription: %S\\n\\tState: %S\\n\"),\n\t\t\t\ti,\n\t\t\t\tstrGuid,\n\t\t\t\tsInfo[i].strInterfaceDescription,\n\t\t\t\tGetInterfaceStateString(sInfo[i].isState));\n\n\t\t\tRpcStringFreeA(&strGuid);\n\t\t}\n\t}\n\n\tUINT nChoice = 0;\n\tprintf(\"Enter the choice (0, 1,..) of the wireless card you want to operate on:\\n\");\n\n\tif (ReadConsole(GetStdHandle(STD_INPUT_HANDLE), szBuffer, _countof(szBuffer), &dwRead, NULL) == FALSE)\n\t{\n\t\tputs(\"Error input.\");\n\t\treturn -1;\n\t}\n\tszBuffer[dwRead] = 0;\n\tnChoice = _ttoi(szBuffer);\n\n\tif (nChoice > nCount)\n\t{\n\t\tputs(\"No such index.\");\n\t\treturn -1;\n\t}\n\n\tUINT nSTate = 0;\n\t\/\/ULONG targetOperationMode = DOT11_OPERATION_MODE_EXTENSIBLE_STATION;\n\tULONG targetOperationMode = DOT11_OPERATION_MODE_NETWORK_MONITOR;\n\tprintf(\"Enter the state (0, 1 or 2) you want to switch to for the chosen wireless card:\\n\");\n\tprintf(\"0: Managed Mode (ExtSTA)\\n1: Monitor Mode (NetMon)\\n2: Master Mode (ExtAP)\\n\");\n\n\tif (ReadConsole(GetStdHandle(STD_INPUT_HANDLE), szBuffer, _countof(szBuffer), &dwRead, NULL) == FALSE)\n\t{\n\t\tputs(\"Error input.\");\n\t\treturn -1;\n\t}\n\tszBuffer[dwRead] = 0;\n\tnSTate = _ttoi(szBuffer);\n\n\tif (nSTate != 0 && nSTate != 1 && nSTate != 2)\n\t{\n\t\tputs(\"Only 0, 1 and 2 are valid inputs.\");\n\t\treturn -1;\n\t}\n\tif (nSTate == 0)\n\t{\n\t\ttargetOperationMode = DOT11_OPERATION_MODE_EXTENSIBLE_STATION;\n\t}\n\telse if (nSTate == 1)\n\t{\n\t\ttargetOperationMode = DOT11_OPERATION_MODE_NETWORK_MONITOR;\n\t}\n\telse \/\/ nSTate == 2\n\t{\n\t\ttargetOperationMode = DOT11_OPERATION_MODE_EXTENSIBLE_AP;\n\t}\n\n\tDWORD dwResult = SetInterface(wlan_intf_opcode_current_operation_mode, (PVOID*)&targetOperationMode, &sInfo[nChoice].InterfaceGuid);\n\tif (dwResult != ERROR_SUCCESS)\n\t{\n\t\tprintf(\"SetInterface error, error code = %d\\n\", dwResult);\n\t\tsystem(\"PAUSE\");\n\t}\n\telse\n\t{\n\t\tprintf(\"SetInterface success!\\n\");\n\t}\n\n\treturn 0;\n}\n\n<|endoftext|>"} {"text":"<commit_before>#include <stdlib.h> \/\/ malloc, free\n#include <string.h> \/\/ memset\n\n#include <apoapsis_stb_image.h>\n\n#include \"Common.h\"\n#include \"PhysFS.h\"\n#include \"OpenGL.h\"\n#include \"Image.h\"\n\n\nbool CreateImage( Image* image, int width, int height, int bpp )\n{\n memset(image, 0, sizeof(Image));\n\n image->width = width;\n image->height = height;\n image->bpp = bpp;\n\n switch(image->bpp)\n {\n case 1:\n image->format = GL_LUMINANCE;\n break;\n\n case 2:\n image->format = GL_LUMINANCE_ALPHA;\n break;\n\n case 3:\n image->format = GL_RGB;\n break;\n\n case 4:\n image->format = GL_RGBA;\n break;\n\n default:\n Error(\"Can't create image (Unknown BPP -> %d)\", image->bpp);\n return false;\n }\n\n image->type = GL_UNSIGNED_BYTE;\n\n image->data = (char*)malloc(width*height*bpp);\n\n return true;\n}\n\nstatic int PhysFSRead( void* user, char* data, int size )\n{\n PHYSFS_File* file = (PHYSFS_File*)user;\n return (int)PHYSFS_readBytes(file, data, size);\n}\n\nstatic void PhysFSSkip( void* user, int offset )\n{\n PHYSFS_File* file = (PHYSFS_File*)user;\n const int currentPosition = PHYSFS_tell(file);\n assert(currentPosition >= 0);\n const int newPosition = currentPosition + offset;\n const int success = PHYSFS_seek(file, newPosition);\n assert(success);\n}\n\nstatic int PhysFSEOF( void* user )\n{\n PHYSFS_File* file = (PHYSFS_File*)user;\n return PHYSFS_eof(file);\n}\n\nstatic const stbi_io_callbacks PhysFSCallbacks =\n{\n PhysFSRead,\n PhysFSSkip,\n PhysFSEOF\n};\n\nbool LoadImage( Image* image, const char* vfsPath )\n{\n memset(image, 0, sizeof(Image));\n\n PHYSFS_File* file = PHYSFS_openRead(vfsPath);\n if(!file)\n {\n Error(\"Can't load '%s': %s\", vfsPath, PHYSFS_getLastError());\n return false;\n }\n\n image->data = (char*)stbi_load_from_callbacks(&PhysFSCallbacks,\n file,\n &image->width,\n &image->height,\n &image->bpp,\n STBI_default);\n PHYSFS_close(file);\n if(!image->data)\n {\n Error(\"Can't load '%s': %s\", vfsPath, stbi_failure_reason());\n return false;\n }\n\n switch(image->bpp)\n {\n case 1:\n image->format = GL_LUMINANCE;\n break;\n\n case 2:\n image->format = GL_LUMINANCE_ALPHA;\n break;\n\n case 3:\n image->format = GL_RGB;\n break;\n\n case 4:\n image->format = GL_RGBA;\n break;\n\n default:\n Error(\"Can't load '%s': Unknown BPP -> %d\", vfsPath, image->bpp);\n free(image->data);\n return false;\n }\n\n image->type = GL_UNSIGNED_BYTE;\n\n return true;\n}\n\nvoid FreeImage( const Image* image )\n{\n if(image->data)\n free(image->data);\n}\n<commit_msg>Flip images loaded by stb_image.<commit_after>#include <stdlib.h> \/\/ malloc, free\n#include <string.h> \/\/ memset, memcpy\n\n#include <apoapsis_stb_image.h>\n\n#include \"Common.h\"\n#include \"PhysFS.h\"\n#include \"OpenGL.h\"\n#include \"Image.h\"\n\n\nbool CreateImage( Image* image, int width, int height, int bpp )\n{\n memset(image, 0, sizeof(Image));\n\n image->width = width;\n image->height = height;\n image->bpp = bpp;\n\n switch(image->bpp)\n {\n case 1:\n image->format = GL_LUMINANCE;\n break;\n\n case 2:\n image->format = GL_LUMINANCE_ALPHA;\n break;\n\n case 3:\n image->format = GL_RGB;\n break;\n\n case 4:\n image->format = GL_RGBA;\n break;\n\n default:\n Error(\"Can't create image (Unknown BPP -> %d)\", image->bpp);\n return false;\n }\n\n image->type = GL_UNSIGNED_BYTE;\n\n image->data = (char*)malloc(width*height*bpp);\n\n return true;\n}\n\nstatic int PhysFSRead( void* user, char* data, int size )\n{\n PHYSFS_File* file = (PHYSFS_File*)user;\n return (int)PHYSFS_readBytes(file, data, size);\n}\n\nstatic void PhysFSSkip( void* user, int offset )\n{\n PHYSFS_File* file = (PHYSFS_File*)user;\n const int currentPosition = PHYSFS_tell(file);\n assert(currentPosition >= 0);\n const int newPosition = currentPosition + offset;\n const int success = PHYSFS_seek(file, newPosition);\n assert(success);\n}\n\nstatic int PhysFSEOF( void* user )\n{\n PHYSFS_File* file = (PHYSFS_File*)user;\n return PHYSFS_eof(file);\n}\n\nstatic const stbi_io_callbacks PhysFSCallbacks =\n{\n PhysFSRead,\n PhysFSSkip,\n PhysFSEOF\n};\n\nstatic void FlipImageVertically( Image* image )\n{\n const char* oldData = image->data;\n const int width = image->width;\n const int height = image->height;\n const int bpp = image->bpp;\n\n const int size = width * height * bpp;\n char* newData = (char*)malloc(size);\n\n const int lineLength = bpp * width;\n\n for(int y = 0; y < height; y++)\n {\n char* dstStart = &newData[lineLength * y];\n const char* srcStart = &oldData[lineLength * (height-y)];\n memcpy(dstStart, srcStart, lineLength);\n }\n\n free(image->data);\n image->data = newData;\n}\n\nbool LoadImage( Image* image, const char* vfsPath )\n{\n memset(image, 0, sizeof(Image));\n\n PHYSFS_File* file = PHYSFS_openRead(vfsPath);\n if(!file)\n {\n Error(\"Can't load '%s': %s\", vfsPath, PHYSFS_getLastError());\n return false;\n }\n\n image->data = (char*)stbi_load_from_callbacks(&PhysFSCallbacks,\n file,\n &image->width,\n &image->height,\n &image->bpp,\n STBI_default);\n PHYSFS_close(file);\n if(!image->data)\n {\n Error(\"Can't load '%s': %s\", vfsPath, stbi_failure_reason());\n return false;\n }\n\n FlipImageVertically(image);\n\n switch(image->bpp)\n {\n case 1:\n image->format = GL_LUMINANCE;\n break;\n\n case 2:\n image->format = GL_LUMINANCE_ALPHA;\n break;\n\n case 3:\n image->format = GL_RGB;\n break;\n\n case 4:\n image->format = GL_RGBA;\n break;\n\n default:\n Error(\"Can't load '%s': Unknown BPP -> %d\", vfsPath, image->bpp);\n free(image->data);\n return false;\n }\n\n image->type = GL_UNSIGNED_BYTE;\n\n return true;\n}\n\nvoid FreeImage( const Image* image )\n{\n if(image->data)\n free(image->data);\n}\n<|endoftext|>"} {"text":"<commit_before>#include <map>\n#include <vector>\n#include <thread>\n#include <mutex>\n\n#include <assert.h>\n#include <string.h>\n#include <unistd.h>\n#include <stdio.h>\n\n#ifdef WIN32\n\t#include <winsock2.h>\n\t#include <ws2tcpip.h>\n#else \/\/ WIN32\n\t#include <sys\/socket.h>\n\t#include <netinet\/in.h>\n\t#include <netinet\/tcp.h>\n\t#include <netdb.h>\n\t#include <fcntl.h>\n#endif \/\/ !WIN32\n\n#define BITCOIN_UA_LENGTH 24\n#define BITCOIN_UA {'\/', 'R', 'e', 'l', 'a', 'y', 'N', 'e', 't', 'w', 'o', 'r', 'k', 'C', 'l', 'i', 'e', 'n', 't', ':', '4', '2', '\/', '\\0'}\n\n#include \"crypto\/sha2.h\"\n#include \"flaggedarrayset.h\"\n#include \"relayprocess.h\"\n#include \"utils.h\"\n#include \"p2pclient.h\"\n\n\n\n\n\n\/***********************************************\n **** Relay network client processing class ****\n ***********************************************\/\nclass RelayNetworkClient : public OutboundPersistentConnection {\nprivate:\n\tRELAY_DECLARE_CLASS_VARS\n\n\tconst std::function<void (std::vector<unsigned char>&)> provide_block;\n\tconst std::function<void (std::shared_ptr<std::vector<unsigned char> >&)> provide_transaction;\n\tconst std::function<void (void)> on_connected;\n\n\tstd::atomic_bool connected;\n\n\tRelayNodeCompressor compressor;\n\npublic:\n\tRelayNetworkClient(const char* serverHostIn,\n\t\t\t\t\t\tconst std::function<void (std::vector<unsigned char>&)>& provide_block_in,\n\t\t\t\t\t\tconst std::function<void (std::shared_ptr<std::vector<unsigned char> >&)>& provide_transaction_in,\n\t\t\t\t\t\tconst std::function<void (void)>& on_connected_in)\n\t\t\t: OutboundPersistentConnection(serverHostIn, 8336), RELAY_DECLARE_CONSTRUCTOR_EXTENDS,\n\t\t\tprovide_block(provide_block_in), provide_transaction(provide_transaction_in), on_connected(on_connected_in),\n\t\t\tconnected(false), compressor(false) {\n\t\tconstruction_done();\n\t}\n\nprivate:\n\tvoid on_disconnect() {\n\t\tconnected = false;\n\t}\n\n\tvoid net_process(const std::function<void(const char*)>& disconnect) {\n\t\tcompressor.reset();\n\n\t\trelay_msg_header version_header = { RELAY_MAGIC_BYTES, VERSION_TYPE, htonl(strlen(VERSION_STRING)) };\n\t\tmaybe_do_send_bytes((char*)&version_header, sizeof(version_header));\n\t\tmaybe_do_send_bytes(VERSION_STRING, strlen(VERSION_STRING));\n\n\t\tconnected = true;\n\n\t\twhile (true) {\n\t\t\trelay_msg_header header;\n\t\t\tif (read_all((char*)&header, 4*3) != 4*3)\n\t\t\t\treturn disconnect(\"failed to read message header\");\n\n\t\t\tif (header.magic != RELAY_MAGIC_BYTES)\n\t\t\t\treturn disconnect(\"invalid magic bytes\");\n\n\t\t\tuint32_t message_size = ntohl(header.length);\n\n\t\t\tif (message_size > 1000000)\n\t\t\t\treturn disconnect(\"got message too large\");\n\n\t\t\tif (header.type == VERSION_TYPE) {\n\t\t\t\tchar data[message_size];\n\t\t\t\tif (read_all(data, message_size) < (int64_t)(message_size))\n\t\t\t\t\treturn disconnect(\"failed to read version message\");\n\n\t\t\t\tif (strncmp(VERSION_STRING, data, std::min(sizeof(VERSION_STRING), size_t(message_size))))\n\t\t\t\t\treturn disconnect(\"unknown version string\");\n\t\t\t\telse {\n\t\t\t\t\tprintf(\"Connected to relay node with protocol version %s\\n\", VERSION_STRING);\n\t\t\t\t\ton_connected();\n\t\t\t\t}\n\t\t\t} else if (header.type == MAX_VERSION_TYPE) {\n\t\t\t\tchar data[message_size];\n\t\t\t\tif (read_all(data, message_size) < (int64_t)(message_size))\n\t\t\t\t\treturn disconnect(\"failed to read max_version string\");\n\n\t\t\t\tif (strncmp(VERSION_STRING, data, std::min(sizeof(VERSION_STRING), size_t(message_size))))\n\t\t\t\t\tprintf(\"Relay network is using a later version (PLEASE UPGRADE)\\n\");\n\t\t\t\telse\n\t\t\t\t\treturn disconnect(\"got MAX_VERSION of same version as us\");\n\t\t\t} else if (header.type == BLOCK_TYPE) {\n\t\t\t\tstd::function<ssize_t(char*, size_t)> do_read = [&](char* buf, size_t count) { return this->read_all(buf, count); };\n\t\t\t\tauto res = compressor.decompress_relay_block(do_read, message_size, false);\n\t\t\t\tif (std::get<2>(res))\n\t\t\t\t\treturn disconnect(std::get<2>(res));\n\n\t\t\t\tprovide_block(*std::get<1>(res));\n\n\t\t\t\tauto fullhash = *std::get<3>(res).get();\n\t\t\t\tstruct tm tm;\n\t\t\t\ttime_t now = time(NULL);\n\t\t\t\tgmtime_r(&now, &tm);\n\t\t\t\tprintf(\"[%d-%02d-%02d %02d:%02d:%02d+00] \", tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec);\n\t\t\t\tfor (unsigned int i = 0; i < fullhash.size(); i++)\n\t\t\t\t\tprintf(\"%02x\", fullhash[fullhash.size() - i - 1]);\n\t\t\t\tprintf(\" recv'd, size %lu with %u bytes on the wire\\n\", (unsigned long)std::get<1>(res)->size() - sizeof(bitcoin_msg_header), std::get<0>(res));\n\t\t\t} else if (header.type == END_BLOCK_TYPE) {\n\t\t\t} else if (header.type == TRANSACTION_TYPE) {\n\t\t\t\tif (!compressor.maybe_recv_tx_of_size(message_size, true))\n\t\t\t\t\treturn disconnect(\"got freely relayed transaction too large\");\n\n\t\t\t\tauto tx = std::make_shared<std::vector<unsigned char> > (message_size);\n\t\t\t\tif (read_all((char*)&(*tx)[0], message_size) < (int64_t)(message_size))\n\t\t\t\t\treturn disconnect(\"failed to read loose transaction data\");\n\n\t\t\t\tcompressor.recv_tx(tx);\n\t\t\t\tprovide_transaction(tx);\n\t\t\t\tprintf(\"Received transaction of size %u from relay server\\n\", message_size);\n\t\t\t} else\n\t\t\t\treturn disconnect(\"got unknown message type\");\n\t\t}\n\t}\n\npublic:\n\tvoid receive_transaction(const std::shared_ptr<std::vector<unsigned char> >& tx, int token, bool send_oob) {\n\t\tif (!connected)\n\t\t\treturn;\n\n\t\tstd::shared_ptr<std::vector<unsigned char> > msgptr;\n\t\tif (send_oob)\n\t\t\tmsgptr = compressor.tx_to_msg(tx, true);\n\t\telse\n\t\t\tmsgptr = compressor.get_relay_transaction(tx);\n\t\tif (!msgptr.use_count())\n\t\t\treturn;\n\n\t\tauto& msg = *msgptr.get();\n\n\t\tmaybe_do_send_bytes((char*)&msg[0], msg.size(), token);\n\t\tprintf(\"Sent transaction of size %lu%s to relay server\\n\", (unsigned long)tx->size(), send_oob ? \" (out-of-band)\" : \"\");\n\t}\n\n\tvoid receive_block(const std::vector<unsigned char>& block, int token) {\n\t\tif (!connected)\n\t\t\treturn;\n\n\t\tstd::vector<unsigned char> fullhash(32);\n\t\tgetblockhash(fullhash, block, sizeof(struct bitcoin_msg_header));\n\n\t\tauto tuple = compressor.maybe_compress_block(fullhash, block, false);\n\t\tif (std::get<1>(tuple)) {\n\t\t\tprintf(\"Failed to process block from bitcoind (%s)\\n\", std::get<1>(tuple));\n\t\t\treturn;\n\t\t}\n\t\tauto compressed_block = std::get<0>(tuple);\n\n\t\tmaybe_do_send_bytes((char*)&(*compressed_block)[0], compressed_block->size(), token);\n\t\tstruct relay_msg_header header = { RELAY_MAGIC_BYTES, END_BLOCK_TYPE, 0 };\n\t\tmaybe_do_send_bytes((char*)&header, sizeof(header), token);\n\n\t\tprint_hash(&fullhash[0]);\n\t\tprintf(\" sent, size %lu with %lu bytes on the wire\\n\", (unsigned long)block.size(), (unsigned long)compressed_block->size());\n\t}\n};\n\nclass P2PClient : public P2PRelayer {\npublic:\n\tP2PClient(const char* serverHostIn, uint16_t serverPortIn,\n\t\t\t\tconst std::function<void (std::vector<unsigned char>&, const std::chrono::system_clock::time_point&)>& provide_block_in,\n\t\t\t\tconst std::function<void (std::shared_ptr<std::vector<unsigned char> >&)>& provide_transaction_in,\n\t\t\t\tconst std::function<void (void)>& mempools_done_in) :\n\t\t\tP2PRelayer(serverHostIn, serverPortIn, provide_block_in, provide_transaction_in, NULL, mempools_done_in, NULL, true)\n\t\t{ construction_done(); }\n\nprivate:\n\tstd::vector<unsigned char> generate_version() {\n\t\tstruct bitcoin_version_with_header version_msg;\n\t\tversion_msg.version.start.timestamp = htole64(time(0));\n\t\tversion_msg.version.start.user_agent_length = BITCOIN_UA_LENGTH; \/\/ Work around apparent gcc bug\n\t\treturn std::vector<unsigned char>((unsigned char*)&version_msg, (unsigned char*)&version_msg + sizeof(version_msg));\n\t}\n};\n\n\n#define HOSTNAMES_TO_TEST 20\n#define CONNECT_TESTS 20\nstd::chrono::milliseconds connect_durations[HOSTNAMES_TO_TEST];\nvoid test_node(int node) {\n\tconst char* relay = \"public.%02d.relay.mattcorallo.com\";\n\tchar host[strlen(relay)];\n\tsprintf(host, relay, node);\n\tsockaddr_in6 addr;\n\tif (!lookup_address(host, &addr) ||\n\t\t\t(addr.sin6_addr.s6_addr[15] == 0 && addr.sin6_addr.s6_addr[14] == 0 && addr.sin6_addr.s6_addr[13] == 0 && addr.sin6_addr.s6_addr[12] == 0)) {\n\t\tconnect_durations[node] = std::chrono::milliseconds::max();\n\t\treturn;\n\t}\n\n\taddr.sin6_port = htons(8336);\n\n\tauto start = std::chrono::steady_clock::now();\n\tfor (int i = 0; i < CONNECT_TESTS; i++) {\n\t\tint sock = socket(AF_INET6, SOCK_STREAM, 0);\n\t\tALWAYS_ASSERT(sock > 0);\n\n\t\tint v6only = 0;\n\t\tsetsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY, (char *)&v6only, sizeof(v6only));\n\n\t\tconnect(sock, (struct sockaddr*)&addr, sizeof(addr));\n\t\tclose(sock);\n\t}\n\tconnect_durations[node] = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now() - start);\n}\n\n\n\nint main(int argc, char** argv) {\n\tbool validPort = false;\n\ttry { std::stoul(argv[2]); validPort = true; } catch (std::exception& e) {}\n\tif ((argc != 3 && argc != 4) || !validPort) {\n\t\tprintf(\"USAGE: %s BITCOIND_ADDRESS BITCOIND_PORT [ server ]\\n\", argv[0]);\n\t\tprintf(\"Relay server is automatically selected by pinging available servers, unless one is specified\\n\");\n\t\treturn -1;\n\t}\n\n#ifdef WIN32\n\tWSADATA wsaData;\n\tif (WSAStartup(MAKEWORD(2,2), &wsaData))\n\t\treturn -1;\n#endif\n\n\tconst char* relay = \"public.%02d.relay.mattcorallo.com\";\n\tchar host[std::max(argc == 3 ? 0 : strlen(argv[3]), strlen(relay))];\n\tif (argc == 3) {\n\t\twhile (true) {\n\t\t\tstd::list<std::thread> threads;\n\t\t\tfor (int i = 0; i < HOSTNAMES_TO_TEST; i++)\n\t\t\t\tthreads.emplace_back(test_node, i);\n\t\t\tfor (int i = 0; i < HOSTNAMES_TO_TEST; i++) {\n\t\t\t\tthreads.front().join();\n\t\t\t\tthreads.pop_front();\n\t\t\t}\n\n\t\t\tint min = -1; std::chrono::milliseconds min_duration(std::chrono::milliseconds::max());\n\t\t\tfor (int i = 0; i < HOSTNAMES_TO_TEST; i++) {\n\t\t\t\tif (connect_durations[i] != std::chrono::milliseconds::max()) {\n\t\t\t\t\tstd::string aka;\n\t\t\t\t\tsprintf(host, relay, i);\n\t\t\t\t\tprintf(\"Server %d (%s) took %lld ms to respond %d times.\\n\", i, lookup_cname(host, aka) ? aka.c_str() : \"\", (long long int)connect_durations[i].count(), CONNECT_TESTS);\n\t\t\t\t}\n\t\t\t\tif (connect_durations[i] < min_duration) {\n\t\t\t\t\tmin_duration = connect_durations[i];\n\t\t\t\t\tmin = i;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tstd::this_thread::sleep_for(std::chrono::seconds(10)); \/\/ Wait for server to open up our slot again\n\t\t\tif (min == -1) {\n\t\t\t\tprintf(\"No servers responded\\n\");\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tsprintf(host, relay, min);\n\t\t}\n\t} else\n\t\tmemcpy(host, argv[3], strlen(argv[3]) + 1);\n\tprintf(\"Using server %s\\n\", host);\n\n\tstd::atomic_int relayToken(0);\n\tRelayNetworkClient* relayClient;\n\tP2PClient p2p(argv[1], std::stoul(argv[2]),\n\t\t\t\t\t[&](std::vector<unsigned char>& bytes, const std::chrono::system_clock::time_point&) { relayClient->receive_block(bytes, relayToken); },\n\t\t\t\t\t[&](std::shared_ptr<std::vector<unsigned char> >& bytes) {\n\t\t\t\t\t\trelayClient->receive_transaction(bytes, relayToken, !p2p.maybe_supports_mempool());\n\t\t\t\t\t},\n\t\t\t\t\t[&]() {\n\t\t\t\t\t\trelayClient->release_send_mutex(relayToken);\n\t\t\t\t\t\trelayToken = 0;\n\t\t\t\t\t\tif (!p2p.maybe_supports_mempool())\n\t\t\t\t\t\t\tp2p.regularly_request_mempool_and_dont_fetch_loose_txn = false;\n\t\t\t\t\t});\n\trelayClient = new RelayNetworkClient(host,\n\t\t\t\t\t\t\t\t\t\t[&](std::vector<unsigned char>& bytes) { p2p.receive_block(bytes); },\n\t\t\t\t\t\t\t\t\t\t[&](std::shared_ptr<std::vector<unsigned char> >& bytes) {\n\t\t\t\t\t\t\t\t\t\t\tp2p.receive_transaction(bytes);\n\t\t\t\t\t\t\t\t\t\t\tif (!p2p.maybe_supports_mempool())\n\t\t\t\t\t\t\t\t\t\t\t\trelayClient->receive_transaction(bytes, relayToken, false);\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t[&]() {\n\t\t\t\t\t\t\t\t\t\t\trelayToken = relayClient->get_send_mutex();\n\t\t\t\t\t\t\t\t\t\t\trelayClient->do_throttle_outbound(relayToken);\n\t\t\t\t\t\t\t\t\t\t\tp2p.request_mempool();\n\t\t\t\t\t\t\t\t\t\t});\n\n\twhile (true) { sleep(1000); }\n}\n<commit_msg>Fix client server search<commit_after>#include <map>\n#include <vector>\n#include <thread>\n#include <mutex>\n\n#include <assert.h>\n#include <string.h>\n#include <unistd.h>\n#include <stdio.h>\n\n#ifdef WIN32\n\t#include <winsock2.h>\n\t#include <ws2tcpip.h>\n#else \/\/ WIN32\n\t#include <sys\/socket.h>\n\t#include <netinet\/in.h>\n\t#include <netinet\/tcp.h>\n\t#include <netdb.h>\n\t#include <fcntl.h>\n#endif \/\/ !WIN32\n\n#define BITCOIN_UA_LENGTH 24\n#define BITCOIN_UA {'\/', 'R', 'e', 'l', 'a', 'y', 'N', 'e', 't', 'w', 'o', 'r', 'k', 'C', 'l', 'i', 'e', 'n', 't', ':', '4', '2', '\/', '\\0'}\n\n#include \"crypto\/sha2.h\"\n#include \"flaggedarrayset.h\"\n#include \"relayprocess.h\"\n#include \"utils.h\"\n#include \"p2pclient.h\"\n\n\n\n\n\n\/***********************************************\n **** Relay network client processing class ****\n ***********************************************\/\nclass RelayNetworkClient : public OutboundPersistentConnection {\nprivate:\n\tRELAY_DECLARE_CLASS_VARS\n\n\tconst std::function<void (std::vector<unsigned char>&)> provide_block;\n\tconst std::function<void (std::shared_ptr<std::vector<unsigned char> >&)> provide_transaction;\n\tconst std::function<void (void)> on_connected;\n\n\tstd::atomic_bool connected;\n\n\tRelayNodeCompressor compressor;\n\npublic:\n\tRelayNetworkClient(const char* serverHostIn,\n\t\t\t\t\t\tconst std::function<void (std::vector<unsigned char>&)>& provide_block_in,\n\t\t\t\t\t\tconst std::function<void (std::shared_ptr<std::vector<unsigned char> >&)>& provide_transaction_in,\n\t\t\t\t\t\tconst std::function<void (void)>& on_connected_in)\n\t\t\t: OutboundPersistentConnection(serverHostIn, 8336), RELAY_DECLARE_CONSTRUCTOR_EXTENDS,\n\t\t\tprovide_block(provide_block_in), provide_transaction(provide_transaction_in), on_connected(on_connected_in),\n\t\t\tconnected(false), compressor(false) {\n\t\tconstruction_done();\n\t}\n\nprivate:\n\tvoid on_disconnect() {\n\t\tconnected = false;\n\t}\n\n\tvoid net_process(const std::function<void(const char*)>& disconnect) {\n\t\tcompressor.reset();\n\n\t\trelay_msg_header version_header = { RELAY_MAGIC_BYTES, VERSION_TYPE, htonl(strlen(VERSION_STRING)) };\n\t\tmaybe_do_send_bytes((char*)&version_header, sizeof(version_header));\n\t\tmaybe_do_send_bytes(VERSION_STRING, strlen(VERSION_STRING));\n\n\t\tconnected = true;\n\n\t\twhile (true) {\n\t\t\trelay_msg_header header;\n\t\t\tif (read_all((char*)&header, 4*3) != 4*3)\n\t\t\t\treturn disconnect(\"failed to read message header\");\n\n\t\t\tif (header.magic != RELAY_MAGIC_BYTES)\n\t\t\t\treturn disconnect(\"invalid magic bytes\");\n\n\t\t\tuint32_t message_size = ntohl(header.length);\n\n\t\t\tif (message_size > 1000000)\n\t\t\t\treturn disconnect(\"got message too large\");\n\n\t\t\tif (header.type == VERSION_TYPE) {\n\t\t\t\tchar data[message_size];\n\t\t\t\tif (read_all(data, message_size) < (int64_t)(message_size))\n\t\t\t\t\treturn disconnect(\"failed to read version message\");\n\n\t\t\t\tif (strncmp(VERSION_STRING, data, std::min(sizeof(VERSION_STRING), size_t(message_size))))\n\t\t\t\t\treturn disconnect(\"unknown version string\");\n\t\t\t\telse {\n\t\t\t\t\tprintf(\"Connected to relay node with protocol version %s\\n\", VERSION_STRING);\n\t\t\t\t\ton_connected();\n\t\t\t\t}\n\t\t\t} else if (header.type == MAX_VERSION_TYPE) {\n\t\t\t\tchar data[message_size];\n\t\t\t\tif (read_all(data, message_size) < (int64_t)(message_size))\n\t\t\t\t\treturn disconnect(\"failed to read max_version string\");\n\n\t\t\t\tif (strncmp(VERSION_STRING, data, std::min(sizeof(VERSION_STRING), size_t(message_size))))\n\t\t\t\t\tprintf(\"Relay network is using a later version (PLEASE UPGRADE)\\n\");\n\t\t\t\telse\n\t\t\t\t\treturn disconnect(\"got MAX_VERSION of same version as us\");\n\t\t\t} else if (header.type == BLOCK_TYPE) {\n\t\t\t\tstd::function<ssize_t(char*, size_t)> do_read = [&](char* buf, size_t count) { return this->read_all(buf, count); };\n\t\t\t\tauto res = compressor.decompress_relay_block(do_read, message_size, false);\n\t\t\t\tif (std::get<2>(res))\n\t\t\t\t\treturn disconnect(std::get<2>(res));\n\n\t\t\t\tprovide_block(*std::get<1>(res));\n\n\t\t\t\tauto fullhash = *std::get<3>(res).get();\n\t\t\t\tstruct tm tm;\n\t\t\t\ttime_t now = time(NULL);\n\t\t\t\tgmtime_r(&now, &tm);\n\t\t\t\tprintf(\"[%d-%02d-%02d %02d:%02d:%02d+00] \", tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec);\n\t\t\t\tfor (unsigned int i = 0; i < fullhash.size(); i++)\n\t\t\t\t\tprintf(\"%02x\", fullhash[fullhash.size() - i - 1]);\n\t\t\t\tprintf(\" recv'd, size %lu with %u bytes on the wire\\n\", (unsigned long)std::get<1>(res)->size() - sizeof(bitcoin_msg_header), std::get<0>(res));\n\t\t\t} else if (header.type == END_BLOCK_TYPE) {\n\t\t\t} else if (header.type == TRANSACTION_TYPE) {\n\t\t\t\tif (!compressor.maybe_recv_tx_of_size(message_size, true))\n\t\t\t\t\treturn disconnect(\"got freely relayed transaction too large\");\n\n\t\t\t\tauto tx = std::make_shared<std::vector<unsigned char> > (message_size);\n\t\t\t\tif (read_all((char*)&(*tx)[0], message_size) < (int64_t)(message_size))\n\t\t\t\t\treturn disconnect(\"failed to read loose transaction data\");\n\n\t\t\t\tcompressor.recv_tx(tx);\n\t\t\t\tprovide_transaction(tx);\n\t\t\t\tprintf(\"Received transaction of size %u from relay server\\n\", message_size);\n\t\t\t} else\n\t\t\t\treturn disconnect(\"got unknown message type\");\n\t\t}\n\t}\n\npublic:\n\tvoid receive_transaction(const std::shared_ptr<std::vector<unsigned char> >& tx, int token, bool send_oob) {\n\t\tif (!connected)\n\t\t\treturn;\n\n\t\tstd::shared_ptr<std::vector<unsigned char> > msgptr;\n\t\tif (send_oob)\n\t\t\tmsgptr = compressor.tx_to_msg(tx, true);\n\t\telse\n\t\t\tmsgptr = compressor.get_relay_transaction(tx);\n\t\tif (!msgptr.use_count())\n\t\t\treturn;\n\n\t\tauto& msg = *msgptr.get();\n\n\t\tmaybe_do_send_bytes((char*)&msg[0], msg.size(), token);\n\t\tprintf(\"Sent transaction of size %lu%s to relay server\\n\", (unsigned long)tx->size(), send_oob ? \" (out-of-band)\" : \"\");\n\t}\n\n\tvoid receive_block(const std::vector<unsigned char>& block, int token) {\n\t\tif (!connected)\n\t\t\treturn;\n\n\t\tstd::vector<unsigned char> fullhash(32);\n\t\tgetblockhash(fullhash, block, sizeof(struct bitcoin_msg_header));\n\n\t\tauto tuple = compressor.maybe_compress_block(fullhash, block, false);\n\t\tif (std::get<1>(tuple)) {\n\t\t\tprintf(\"Failed to process block from bitcoind (%s)\\n\", std::get<1>(tuple));\n\t\t\treturn;\n\t\t}\n\t\tauto compressed_block = std::get<0>(tuple);\n\n\t\tmaybe_do_send_bytes((char*)&(*compressed_block)[0], compressed_block->size(), token);\n\t\tstruct relay_msg_header header = { RELAY_MAGIC_BYTES, END_BLOCK_TYPE, 0 };\n\t\tmaybe_do_send_bytes((char*)&header, sizeof(header), token);\n\n\t\tprint_hash(&fullhash[0]);\n\t\tprintf(\" sent, size %lu with %lu bytes on the wire\\n\", (unsigned long)block.size(), (unsigned long)compressed_block->size());\n\t}\n};\n\nclass P2PClient : public P2PRelayer {\npublic:\n\tP2PClient(const char* serverHostIn, uint16_t serverPortIn,\n\t\t\t\tconst std::function<void (std::vector<unsigned char>&, const std::chrono::system_clock::time_point&)>& provide_block_in,\n\t\t\t\tconst std::function<void (std::shared_ptr<std::vector<unsigned char> >&)>& provide_transaction_in,\n\t\t\t\tconst std::function<void (void)>& mempools_done_in) :\n\t\t\tP2PRelayer(serverHostIn, serverPortIn, provide_block_in, provide_transaction_in, NULL, mempools_done_in, NULL, true)\n\t\t{ construction_done(); }\n\nprivate:\n\tstd::vector<unsigned char> generate_version() {\n\t\tstruct bitcoin_version_with_header version_msg;\n\t\tversion_msg.version.start.timestamp = htole64(time(0));\n\t\tversion_msg.version.start.user_agent_length = BITCOIN_UA_LENGTH; \/\/ Work around apparent gcc bug\n\t\treturn std::vector<unsigned char>((unsigned char*)&version_msg, (unsigned char*)&version_msg + sizeof(version_msg));\n\t}\n};\n\n\n#define HOSTNAMES_TO_TEST 20\n#define CONNECT_TESTS 20\nstd::chrono::milliseconds connect_durations[HOSTNAMES_TO_TEST];\nvoid test_node(int node) {\n\tconst char* relay = \"public.%02d.relay.mattcorallo.com\";\n\tchar host[strlen(relay)];\n\tsprintf(host, relay, node);\n\tsockaddr_in6 addr;\n\tif (!lookup_address(host, &addr) ||\n\t\t\t(addr.sin6_addr.s6_addr[15] == 0 && addr.sin6_addr.s6_addr[14] == 0 && addr.sin6_addr.s6_addr[13] == 0 && addr.sin6_addr.s6_addr[12] == 0)) {\n\t\tconnect_durations[node] = std::chrono::milliseconds::max();\n\t\treturn;\n\t}\n\n\taddr.sin6_port = htons(8336);\n\n\tauto start = std::chrono::steady_clock::now();\n\tfor (int i = 0; i < CONNECT_TESTS; i++) {\n\t\tint sock = socket(AF_INET6, SOCK_STREAM, 0);\n\t\tALWAYS_ASSERT(sock > 0);\n\n\t\tint v6only = 0;\n\t\tsetsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY, (char *)&v6only, sizeof(v6only));\n\n\t\tconnect(sock, (struct sockaddr*)&addr, sizeof(addr));\n\t\tclose(sock);\n\t}\n\tconnect_durations[node] = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now() - start);\n}\n\n\n\nint main(int argc, char** argv) {\n\tbool validPort = false;\n\ttry { std::stoul(argv[2]); validPort = true; } catch (std::exception& e) {}\n\tif ((argc != 3 && argc != 4) || !validPort) {\n\t\tprintf(\"USAGE: %s BITCOIND_ADDRESS BITCOIND_PORT [ server ]\\n\", argv[0]);\n\t\tprintf(\"Relay server is automatically selected by pinging available servers, unless one is specified\\n\");\n\t\treturn -1;\n\t}\n\n#ifdef WIN32\n\tWSADATA wsaData;\n\tif (WSAStartup(MAKEWORD(2,2), &wsaData))\n\t\treturn -1;\n#endif\n\n\tconst char* relay = \"public.%02d.relay.mattcorallo.com\";\n\tchar host[std::max(argc == 3 ? 0 : strlen(argv[3]), strlen(relay))];\n\tif (argc == 3) {\n\t\twhile (true) {\n\t\t\tstd::list<std::thread> threads;\n\t\t\tfor (int i = 0; i < HOSTNAMES_TO_TEST; i++)\n\t\t\t\tthreads.emplace_back(test_node, i);\n\t\t\tfor (int i = 0; i < HOSTNAMES_TO_TEST; i++) {\n\t\t\t\tthreads.front().join();\n\t\t\t\tthreads.pop_front();\n\t\t\t}\n\n\t\t\tint min = -1; std::chrono::milliseconds min_duration(std::chrono::milliseconds::max());\n\t\t\tfor (int i = 0; i < HOSTNAMES_TO_TEST; i++) {\n\t\t\t\tif (connect_durations[i] != std::chrono::milliseconds::max()) {\n\t\t\t\t\tstd::string aka;\n\t\t\t\t\tsprintf(host, relay, i);\n\t\t\t\t\tprintf(\"Server %d (%s) took %lld ms to respond %d times.\\n\", i, lookup_cname(host, aka) ? aka.c_str() : \"\", (long long int)connect_durations[i].count(), CONNECT_TESTS);\n\t\t\t\t}\n\t\t\t\tif (connect_durations[i] < min_duration) {\n\t\t\t\t\tmin_duration = connect_durations[i];\n\t\t\t\t\tmin = i;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tstd::this_thread::sleep_for(std::chrono::seconds(10)); \/\/ Wait for server to open up our slot again\n\t\t\tif (min == -1) {\n\t\t\t\tprintf(\"No servers responded\\n\");\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tsprintf(host, relay, min);\n\t\t\tbreak;\n\t\t}\n\t} else\n\t\tmemcpy(host, argv[3], strlen(argv[3]) + 1);\n\tprintf(\"Using server %s\\n\", host);\n\n\tstd::atomic_int relayToken(0);\n\tRelayNetworkClient* relayClient;\n\tP2PClient p2p(argv[1], std::stoul(argv[2]),\n\t\t\t\t\t[&](std::vector<unsigned char>& bytes, const std::chrono::system_clock::time_point&) { relayClient->receive_block(bytes, relayToken); },\n\t\t\t\t\t[&](std::shared_ptr<std::vector<unsigned char> >& bytes) {\n\t\t\t\t\t\trelayClient->receive_transaction(bytes, relayToken, !p2p.maybe_supports_mempool());\n\t\t\t\t\t},\n\t\t\t\t\t[&]() {\n\t\t\t\t\t\trelayClient->release_send_mutex(relayToken);\n\t\t\t\t\t\trelayToken = 0;\n\t\t\t\t\t\tif (!p2p.maybe_supports_mempool())\n\t\t\t\t\t\t\tp2p.regularly_request_mempool_and_dont_fetch_loose_txn = false;\n\t\t\t\t\t});\n\trelayClient = new RelayNetworkClient(host,\n\t\t\t\t\t\t\t\t\t\t[&](std::vector<unsigned char>& bytes) { p2p.receive_block(bytes); },\n\t\t\t\t\t\t\t\t\t\t[&](std::shared_ptr<std::vector<unsigned char> >& bytes) {\n\t\t\t\t\t\t\t\t\t\t\tp2p.receive_transaction(bytes);\n\t\t\t\t\t\t\t\t\t\t\tif (!p2p.maybe_supports_mempool())\n\t\t\t\t\t\t\t\t\t\t\t\trelayClient->receive_transaction(bytes, relayToken, false);\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t[&]() {\n\t\t\t\t\t\t\t\t\t\t\trelayToken = relayClient->get_send_mutex();\n\t\t\t\t\t\t\t\t\t\t\trelayClient->do_throttle_outbound(relayToken);\n\t\t\t\t\t\t\t\t\t\t\tp2p.request_mempool();\n\t\t\t\t\t\t\t\t\t\t});\n\n\twhile (true) { sleep(1000); }\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ Aspia Project\n\/\/ Copyright (C) 2019 Dmitry Chapyshev <dmitry@aspia.ru>\n\/\/\n\/\/ This program is free software: you can redistribute it and\/or modify\n\/\/ it under the terms of the GNU General Public License as published by\n\/\/ the Free Software Foundation, either version 3 of the License, or\n\/\/ (at your option) any later version.\n\/\/\n\/\/ This program is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n\/\/ GNU General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU General Public License\n\/\/ along with this program. If not, see <https:\/\/www.gnu.org\/licenses\/>.\n\/\/\n\n#include \"base\/win\/service.h\"\n\n#include \"base\/logging.h\"\n#include \"base\/message_loop\/message_loop_task_runner.h\"\n#include \"base\/strings\/string_util.h\"\n#include \"base\/threading\/simple_thread.h\"\n\nnamespace base::win {\n\nnamespace {\n\nclass ServiceThread : public SimpleThread\n{\npublic:\n ServiceThread(Service* service);\n ~ServiceThread();\n\n using EventCallback = std::function<void()>;\n\n void setStatus(DWORD status);\n void doEvent(EventCallback callback);\n\n static ServiceThread* self;\n\n enum class State\n {\n NOT_STARTED,\n ERROR_OCCURRED,\n SERVICE_MAIN_CALLED,\n MESSAGE_LOOP_CREATED,\n RUNNING_AS_CONSOLE,\n RUNNING_AS_SERVICE\n };\n\n std::condition_variable startup_condition;\n std::mutex startup_lock;\n State startup_state = State::NOT_STARTED;\n\n std::condition_variable event_condition;\n std::mutex event_lock;\n bool event_processed = false;\n\nprotected:\n \/\/ SimpleThread implementation.\n void run() override;\n\nprivate:\n static void WINAPI serviceMain(DWORD argc, LPWSTR* argv);\n static DWORD WINAPI serviceControlHandler(\n DWORD control_code, DWORD event_type, LPVOID event_data, LPVOID context);\n\n Service* service_;\n std::shared_ptr<TaskRunner> task_runner_;\n\n SERVICE_STATUS_HANDLE status_handle_ = nullptr;\n SERVICE_STATUS status_;\n\n DISALLOW_COPY_AND_ASSIGN(ServiceThread);\n};\n\n\/\/================================================================================================\n\/\/ ServiceThread implementation.\n\/\/================================================================================================\n\nServiceThread* ServiceThread::self = nullptr;\n\nServiceThread::ServiceThread(Service* service)\n : service_(service)\n{\n DCHECK(!self);\n self = this;\n\n task_runner_ = service->taskRunner();\n DCHECK(task_runner_);\n\n memset(&status_, 0, sizeof(status_));\n}\n\nServiceThread::~ServiceThread()\n{\n setStatus(SERVICE_STOPPED);\n stop();\n\n DCHECK(self);\n self = nullptr;\n}\n\nvoid ServiceThread::setStatus(DWORD status)\n{\n status_.dwServiceType = SERVICE_WIN32;\n status_.dwControlsAccepted = 0;\n status_.dwCurrentState = status;\n status_.dwWin32ExitCode = NO_ERROR;\n status_.dwServiceSpecificExitCode = NO_ERROR;\n status_.dwWaitHint = 0;\n\n if (status == SERVICE_RUNNING)\n {\n status_.dwControlsAccepted =\n SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN | SERVICE_ACCEPT_SESSIONCHANGE;\n }\n\n if (status != SERVICE_RUNNING && status != SERVICE_STOPPED)\n ++status_.dwCheckPoint;\n else\n status_.dwCheckPoint = 0;\n\n if (!SetServiceStatus(status_handle_, &status_))\n {\n PLOG(LS_WARNING) << \"SetServiceStatus failed\";\n return;\n }\n}\n\nvoid ServiceThread::doEvent(EventCallback callback)\n{\n std::unique_lock lock(event_lock);\n event_processed = false;\n\n task_runner_->postTask([callback]()\n {\n std::scoped_lock lock(self->event_lock);\n\n callback();\n\n \/\/ Set the event flag is processed.\n self->event_processed = true;\n\n \/\/ Notify waiting thread for the end of processing.\n self->event_condition.notify_all();\n });\n\n \/\/ Wait for the event to be processed by the application.\n while (!event_processed)\n event_condition.wait(lock);\n}\n\nvoid ServiceThread::run()\n{\n SERVICE_TABLE_ENTRYW service_table[2];\n\n service_table[0].lpServiceName = const_cast<wchar_t*>(asWide(service_->name()));\n service_table[0].lpServiceProc = ServiceThread::serviceMain;\n service_table[1].lpServiceName = nullptr;\n service_table[1].lpServiceProc = nullptr;\n\n if (!StartServiceCtrlDispatcherW(service_table))\n {\n std::scoped_lock lock(self->startup_lock);\n\n DWORD error_code = GetLastError();\n if (error_code == ERROR_FAILED_SERVICE_CONTROLLER_CONNECT)\n {\n self->startup_state = State::RUNNING_AS_CONSOLE;\n }\n else\n {\n LOG(LS_WARNING) << \"StartServiceCtrlDispatcherW failed: \"\n << SystemError(error_code).toString();\n self->startup_state = State::ERROR_OCCURRED;\n }\n\n self->startup_condition.notify_all();\n }\n}\n\n\/\/ static\nvoid WINAPI ServiceThread::serviceMain(DWORD \/* argc *\/, LPWSTR* \/* argv *\/)\n{\n if (!self)\n return;\n\n \/\/ Start creating the MessageLoop instance.\n {\n std::scoped_lock lock(self->startup_lock);\n self->startup_state = State::SERVICE_MAIN_CALLED;\n self->startup_condition.notify_all();\n }\n\n \/\/ Waiting for the completion of the creation.\n {\n std::unique_lock lock(self->startup_lock);\n\n while (self->startup_state != State::MESSAGE_LOOP_CREATED)\n self->startup_condition.wait(lock);\n\n self->startup_state = State::RUNNING_AS_SERVICE;\n }\n\n self->status_handle_ = RegisterServiceCtrlHandlerExW(\n asWide(self->service_->name()), serviceControlHandler, nullptr);\n\n if (!self->status_handle_)\n {\n PLOG(LS_WARNING) << \"RegisterServiceCtrlHandlerExW failed\";\n return;\n }\n\n self->setStatus(SERVICE_START_PENDING);\n self->doEvent(std::bind(&Service::onStart, self->service_));\n self->setStatus(SERVICE_RUNNING);\n}\n\n\/\/ static\nDWORD WINAPI ServiceThread::serviceControlHandler(\n DWORD control_code, DWORD event_type, LPVOID event_data, LPVOID \/* context *\/)\n{\n switch (control_code)\n {\n case SERVICE_CONTROL_INTERROGATE:\n return NO_ERROR;\n\n case SERVICE_CONTROL_SESSIONCHANGE:\n {\n if (!self)\n return NO_ERROR;\n\n SessionStatus session_status = static_cast<SessionStatus>(event_type);\n SessionId session_id =\n reinterpret_cast<WTSSESSION_NOTIFICATION*>(event_data)->dwSessionId;\n\n self->doEvent(std::bind(\n &Service::onSessionEvent, self->service_, session_status, session_id));\n }\n return NO_ERROR;\n\n case SERVICE_CONTROL_SHUTDOWN:\n case SERVICE_CONTROL_STOP:\n {\n if (!self)\n return NO_ERROR;\n\n if (control_code == SERVICE_CONTROL_STOP)\n self->setStatus(SERVICE_STOP_PENDING);\n\n self->doEvent(std::bind(&Service::onStop, self->service_));\n }\n return NO_ERROR;\n\n default:\n return ERROR_CALL_NOT_IMPLEMENTED;\n }\n}\n\n} \/\/ namespace\n\nService::Service(std::u16string_view name, MessageLoop::Type type)\n : type_(type),\n name_(name)\n{\n \/\/ Nothing\n}\n\nService::~Service() = default;\n\nvoid Service::exec()\n{\n std::unique_ptr<ServiceThread> service_thread = std::make_unique<ServiceThread>(this);\n\n \/\/ Waiting for the launch ServiceThread::serviceMain.\n {\n std::unique_lock lock(service_thread->startup_lock);\n service_thread->startup_state = ServiceThread::State::NOT_STARTED;\n\n \/\/ Starts handler thread.\n service_thread->start();\n\n while (service_thread->startup_state == ServiceThread::State::NOT_STARTED)\n service_thread->startup_condition.wait(lock);\n\n if (service_thread->startup_state == ServiceThread::State::ERROR_OCCURRED)\n return;\n }\n\n message_loop_ = std::make_unique<MessageLoop>(type_);\n task_runner_ = message_loop_->taskRunner();\n\n \/\/ Now we can complete the registration of the service.\n {\n std::scoped_lock lock(service_thread->startup_lock);\n service_thread->startup_state = ServiceThread::State::MESSAGE_LOOP_CREATED;\n service_thread->startup_condition.notify_all();\n }\n\n message_loop_->run();\n\n service_thread.reset();\n message_loop_.reset();\n}\n\n} \/\/ namespace base::win\n<commit_msg>- Creating a message loop at the very beginning.<commit_after>\/\/\n\/\/ Aspia Project\n\/\/ Copyright (C) 2019 Dmitry Chapyshev <dmitry@aspia.ru>\n\/\/\n\/\/ This program is free software: you can redistribute it and\/or modify\n\/\/ it under the terms of the GNU General Public License as published by\n\/\/ the Free Software Foundation, either version 3 of the License, or\n\/\/ (at your option) any later version.\n\/\/\n\/\/ This program is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n\/\/ GNU General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU General Public License\n\/\/ along with this program. If not, see <https:\/\/www.gnu.org\/licenses\/>.\n\/\/\n\n#include \"base\/win\/service.h\"\n\n#include \"base\/logging.h\"\n#include \"base\/message_loop\/message_loop_task_runner.h\"\n#include \"base\/strings\/string_util.h\"\n#include \"base\/threading\/simple_thread.h\"\n\nnamespace base::win {\n\nnamespace {\n\nclass ServiceThread : public SimpleThread\n{\npublic:\n ServiceThread(Service* service);\n ~ServiceThread();\n\n using EventCallback = std::function<void()>;\n\n void setStatus(DWORD status);\n void doEvent(EventCallback callback);\n\n static ServiceThread* self;\n\n enum class State\n {\n NOT_STARTED,\n ERROR_OCCURRED,\n SERVICE_MAIN_CALLED,\n MESSAGE_LOOP_CREATED,\n RUNNING_AS_CONSOLE,\n RUNNING_AS_SERVICE\n };\n\n std::condition_variable startup_condition;\n std::mutex startup_lock;\n State startup_state = State::NOT_STARTED;\n\n std::condition_variable event_condition;\n std::mutex event_lock;\n bool event_processed = false;\n\nprotected:\n \/\/ SimpleThread implementation.\n void run() override;\n\nprivate:\n static void WINAPI serviceMain(DWORD argc, LPWSTR* argv);\n static DWORD WINAPI serviceControlHandler(\n DWORD control_code, DWORD event_type, LPVOID event_data, LPVOID context);\n\n Service* service_;\n std::shared_ptr<TaskRunner> task_runner_;\n\n SERVICE_STATUS_HANDLE status_handle_ = nullptr;\n SERVICE_STATUS status_;\n\n DISALLOW_COPY_AND_ASSIGN(ServiceThread);\n};\n\n\/\/================================================================================================\n\/\/ ServiceThread implementation.\n\/\/================================================================================================\n\nServiceThread* ServiceThread::self = nullptr;\n\nServiceThread::ServiceThread(Service* service)\n : service_(service)\n{\n DCHECK(!self);\n self = this;\n\n task_runner_ = service->taskRunner();\n DCHECK(task_runner_);\n\n memset(&status_, 0, sizeof(status_));\n}\n\nServiceThread::~ServiceThread()\n{\n setStatus(SERVICE_STOPPED);\n stop();\n\n DCHECK(self);\n self = nullptr;\n}\n\nvoid ServiceThread::setStatus(DWORD status)\n{\n status_.dwServiceType = SERVICE_WIN32;\n status_.dwControlsAccepted = 0;\n status_.dwCurrentState = status;\n status_.dwWin32ExitCode = NO_ERROR;\n status_.dwServiceSpecificExitCode = NO_ERROR;\n status_.dwWaitHint = 0;\n\n if (status == SERVICE_RUNNING)\n {\n status_.dwControlsAccepted =\n SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN | SERVICE_ACCEPT_SESSIONCHANGE;\n }\n\n if (status != SERVICE_RUNNING && status != SERVICE_STOPPED)\n ++status_.dwCheckPoint;\n else\n status_.dwCheckPoint = 0;\n\n if (!SetServiceStatus(status_handle_, &status_))\n {\n PLOG(LS_WARNING) << \"SetServiceStatus failed\";\n return;\n }\n}\n\nvoid ServiceThread::doEvent(EventCallback callback)\n{\n std::unique_lock lock(event_lock);\n event_processed = false;\n\n task_runner_->postTask([callback]()\n {\n std::scoped_lock lock(self->event_lock);\n\n callback();\n\n \/\/ Set the event flag is processed.\n self->event_processed = true;\n\n \/\/ Notify waiting thread for the end of processing.\n self->event_condition.notify_all();\n });\n\n \/\/ Wait for the event to be processed by the application.\n while (!event_processed)\n event_condition.wait(lock);\n}\n\nvoid ServiceThread::run()\n{\n SERVICE_TABLE_ENTRYW service_table[2];\n\n service_table[0].lpServiceName = const_cast<wchar_t*>(asWide(service_->name()));\n service_table[0].lpServiceProc = ServiceThread::serviceMain;\n service_table[1].lpServiceName = nullptr;\n service_table[1].lpServiceProc = nullptr;\n\n if (!StartServiceCtrlDispatcherW(service_table))\n {\n std::scoped_lock lock(self->startup_lock);\n\n DWORD error_code = GetLastError();\n if (error_code == ERROR_FAILED_SERVICE_CONTROLLER_CONNECT)\n {\n self->startup_state = State::RUNNING_AS_CONSOLE;\n }\n else\n {\n LOG(LS_WARNING) << \"StartServiceCtrlDispatcherW failed: \"\n << SystemError(error_code).toString();\n self->startup_state = State::ERROR_OCCURRED;\n }\n\n self->startup_condition.notify_all();\n }\n}\n\n\/\/ static\nvoid WINAPI ServiceThread::serviceMain(DWORD \/* argc *\/, LPWSTR* \/* argv *\/)\n{\n if (!self)\n return;\n\n \/\/ Start creating the MessageLoop instance.\n {\n std::scoped_lock lock(self->startup_lock);\n self->startup_state = State::SERVICE_MAIN_CALLED;\n self->startup_condition.notify_all();\n }\n\n \/\/ Waiting for the completion of the creation.\n {\n std::unique_lock lock(self->startup_lock);\n\n while (self->startup_state != State::MESSAGE_LOOP_CREATED)\n self->startup_condition.wait(lock);\n\n self->startup_state = State::RUNNING_AS_SERVICE;\n }\n\n self->status_handle_ = RegisterServiceCtrlHandlerExW(\n asWide(self->service_->name()), serviceControlHandler, nullptr);\n\n if (!self->status_handle_)\n {\n PLOG(LS_WARNING) << \"RegisterServiceCtrlHandlerExW failed\";\n return;\n }\n\n self->setStatus(SERVICE_START_PENDING);\n self->doEvent(std::bind(&Service::onStart, self->service_));\n self->setStatus(SERVICE_RUNNING);\n}\n\n\/\/ static\nDWORD WINAPI ServiceThread::serviceControlHandler(\n DWORD control_code, DWORD event_type, LPVOID event_data, LPVOID \/* context *\/)\n{\n switch (control_code)\n {\n case SERVICE_CONTROL_INTERROGATE:\n return NO_ERROR;\n\n case SERVICE_CONTROL_SESSIONCHANGE:\n {\n if (!self)\n return NO_ERROR;\n\n SessionStatus session_status = static_cast<SessionStatus>(event_type);\n SessionId session_id =\n reinterpret_cast<WTSSESSION_NOTIFICATION*>(event_data)->dwSessionId;\n\n self->doEvent(std::bind(\n &Service::onSessionEvent, self->service_, session_status, session_id));\n }\n return NO_ERROR;\n\n case SERVICE_CONTROL_SHUTDOWN:\n case SERVICE_CONTROL_STOP:\n {\n if (!self)\n return NO_ERROR;\n\n if (control_code == SERVICE_CONTROL_STOP)\n self->setStatus(SERVICE_STOP_PENDING);\n\n self->doEvent(std::bind(&Service::onStop, self->service_));\n }\n return NO_ERROR;\n\n default:\n return ERROR_CALL_NOT_IMPLEMENTED;\n }\n}\n\n} \/\/ namespace\n\nService::Service(std::u16string_view name, MessageLoop::Type type)\n : type_(type),\n name_(name)\n{\n \/\/ Nothing\n}\n\nService::~Service() = default;\n\nvoid Service::exec()\n{\n message_loop_ = std::make_unique<MessageLoop>(type_);\n task_runner_ = message_loop_->taskRunner();\n\n std::unique_ptr<ServiceThread> service_thread = std::make_unique<ServiceThread>(this);\n\n \/\/ Waiting for the launch ServiceThread::serviceMain.\n {\n std::unique_lock lock(service_thread->startup_lock);\n service_thread->startup_state = ServiceThread::State::NOT_STARTED;\n\n \/\/ Starts handler thread.\n service_thread->start();\n\n while (service_thread->startup_state == ServiceThread::State::NOT_STARTED)\n service_thread->startup_condition.wait(lock);\n\n if (service_thread->startup_state == ServiceThread::State::ERROR_OCCURRED)\n return;\n }\n\n \/\/ Now we can complete the registration of the service.\n {\n std::scoped_lock lock(service_thread->startup_lock);\n service_thread->startup_state = ServiceThread::State::MESSAGE_LOOP_CREATED;\n service_thread->startup_condition.notify_all();\n }\n\n message_loop_->run();\n\n service_thread.reset();\n message_loop_.reset();\n}\n\n} \/\/ namespace base::win\n<|endoftext|>"} {"text":"<commit_before>\/* This file is part of the KDE project\n Copyright (C) 2005-2007 Matthias Kretz <kretz@kde.org>\n\n This library is free software; you can redistribute it and\/or\n modify it under the terms of the GNU Library General Public\n License version 2 as published by the Free Software Foundation.\n\n This library is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n Library General Public License for more details.\n\n You should have received a copy of the GNU Library General Public License\n along with this library; see the file COPYING.LIB. If not, write to\n the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,\n Boston, MA 02110-1301, USA.\n\n*\/\n\n#include \"videowidget.h\"\n#include \"videowidget_p.h\"\n#include \"videowidgetinterface.h\"\n#include \"factory.h\"\n#include \"phonondefs_p.h\"\n#include \"phononnamespace_p.h\"\n\n#include <QtGui\/QAction>\n\n#define PHONON_INTERFACENAME VideoWidgetInterface\n\nnamespace Phonon\n{\n\nVideoWidget::VideoWidget(QWidget *parent)\n : QWidget(parent)\n , Phonon::AbstractVideoOutput(*new VideoWidgetPrivate(this))\n{\n K_D(VideoWidget);\n d->init();\n d->createBackendObject();\n setMouseTracking(true);\n}\n\nVideoWidget::VideoWidget(VideoWidgetPrivate &dd, QWidget *parent)\n : QWidget(parent),\n Phonon::AbstractVideoOutput(dd)\n{\n K_D(VideoWidget);\n d->init();\n}\n\nvoid VideoWidgetPrivate::init()\n{\n Q_Q(VideoWidget);\n QObject::connect(&cursorTimer, SIGNAL(timeout()), q, SLOT(_k_cursorTimeout()));\n cursorTimer.start();\n}\n\nvoid VideoWidget::mouseMoveEvent(QMouseEvent *)\n{\n K_D(VideoWidget);\n if (Qt::BlankCursor == cursor().shape()) {\n unsetCursor();\n d->cursorTimer.start();\n }\n}\n\nvoid VideoWidgetPrivate::_k_cursorTimeout()\n{\n Q_Q(VideoWidget);\n if (Qt::ArrowCursor == q->cursor().shape()) {\n q->setCursor(Qt::BlankCursor);\n }\n}\n\nvoid VideoWidgetPrivate::createBackendObject()\n{\n if (m_backendObject)\n return;\n Q_Q(VideoWidget);\n m_backendObject = Factory::createVideoWidget(q);\n if (m_backendObject) {\n setupBackendObject();\n }\n}\n\n#define PHONON_CLASSNAME VideoWidget\n\nPHONON_INTERFACE_GETTER(Phonon::VideoWidget::AspectRatio, aspectRatio, d->aspectRatio)\nPHONON_INTERFACE_SETTER(setAspectRatio, aspectRatio, Phonon::VideoWidget::AspectRatio)\n\nPHONON_INTERFACE_GETTER(Phonon::VideoWidget::ScaleMode, scaleMode, d->scaleMode)\nPHONON_INTERFACE_SETTER(setScaleMode, scaleMode, Phonon::VideoWidget::ScaleMode)\n\nPHONON_INTERFACE_GETTER(qreal, brightness, d->brightness)\nPHONON_INTERFACE_SETTER(setBrightness, brightness, qreal)\n\nPHONON_INTERFACE_GETTER(qreal, contrast, d->contrast)\nPHONON_INTERFACE_SETTER(setContrast, contrast, qreal)\n\nPHONON_INTERFACE_GETTER(qreal, hue, d->hue)\nPHONON_INTERFACE_SETTER(setHue, hue, qreal)\n\nPHONON_INTERFACE_GETTER(qreal, saturation, d->saturation)\nPHONON_INTERFACE_SETTER(setSaturation, saturation, qreal)\n\nvoid VideoWidget::setFullScreen(bool newFullScreen)\n{\n pDebug() << Q_FUNC_INFO << newFullScreen;\n K_D(VideoWidget);\n \/\/ TODO: disable screensaver? or should we leave that responsibility to the\n \/\/ application?\n Qt::WindowFlags flags = windowFlags();\n if (newFullScreen) {\n d->changeFlags = !(flags & Qt::Window);\n if (d->changeFlags) {\n flags &= ~Qt::SubWindow;\n flags |= Qt::Window;\n } \/\/ else it's a toplevel window already\n } else if (d->changeFlags && parent()) {\n flags &= ~Qt::Window;\n flags |= Qt::SubWindow;\n }\n setWindowFlags(flags);\n if (newFullScreen) {\n showFullScreen();\n } else {\n showNormal();\n }\n}\n\nvoid VideoWidget::exitFullScreen()\n{\n setFullScreen(false);\n}\n\nvoid VideoWidget::enterFullScreen()\n{\n setFullScreen(true);\n}\n\nbool VideoWidgetPrivate::aboutToDeleteBackendObject()\n{\n aspectRatio = pINTERFACE_CALL(aspectRatio());\n scaleMode = pINTERFACE_CALL(scaleMode());\n return AbstractVideoOutputPrivate::aboutToDeleteBackendObject();\n}\n\nvoid VideoWidgetPrivate::setupBackendObject()\n{\n Q_Q(VideoWidget);\n Q_ASSERT(m_backendObject);\n \/\/AbstractVideoOutputPrivate::setupBackendObject();\n pDebug() << \"calling setAspectRatio on the backend \" << aspectRatio;\n pINTERFACE_CALL(setAspectRatio(aspectRatio));\n pINTERFACE_CALL(setScaleMode(scaleMode));\n\n QWidget *w = pINTERFACE_CALL(widget());\n if (w) {\n layout.addWidget(w);\n q->setSizePolicy(w->sizePolicy());\n w->setMouseTracking(true);\n }\n}\n\n\/*\nQSize VideoWidget::sizeHint()\n{\n if (k_ptr->backendObject())\n {\n QWidget *w = pINTERFACE_CALL(widget());\n if (w)\n return w->sizeHint();\n }\n return QSize(0, 0);\n}\n\nQSize VideoWidget::minimumSizeHint()\n{\n if (k_ptr->backendObject())\n {\n QWidget *w = pINTERFACE_CALL(widget());\n if (w)\n return w->minimumSizeHint();\n }\n return QSize(0, 0);\n} *\/\n\n} \/\/namespace Phonon\n\n#include \"moc_videowidget.cpp\"\n\n#undef PHONON_CLASSNAME\n\/\/ vim: sw=4 ts=4 tw=80\n<commit_msg>there is no need to start the timer in the constructor.<commit_after>\/* This file is part of the KDE project\n Copyright (C) 2005-2007 Matthias Kretz <kretz@kde.org>\n\n This library is free software; you can redistribute it and\/or\n modify it under the terms of the GNU Library General Public\n License version 2 as published by the Free Software Foundation.\n\n This library is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n Library General Public License for more details.\n\n You should have received a copy of the GNU Library General Public License\n along with this library; see the file COPYING.LIB. If not, write to\n the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,\n Boston, MA 02110-1301, USA.\n\n*\/\n\n#include \"videowidget.h\"\n#include \"videowidget_p.h\"\n#include \"videowidgetinterface.h\"\n#include \"factory.h\"\n#include \"phonondefs_p.h\"\n#include \"phononnamespace_p.h\"\n\n#include <QtGui\/QAction>\n\n#define PHONON_INTERFACENAME VideoWidgetInterface\n\nnamespace Phonon\n{\n\nVideoWidget::VideoWidget(QWidget *parent)\n : QWidget(parent)\n , Phonon::AbstractVideoOutput(*new VideoWidgetPrivate(this))\n{\n K_D(VideoWidget);\n d->init();\n d->createBackendObject();\n setMouseTracking(true);\n}\n\nVideoWidget::VideoWidget(VideoWidgetPrivate &dd, QWidget *parent)\n : QWidget(parent),\n Phonon::AbstractVideoOutput(dd)\n{\n K_D(VideoWidget);\n d->init();\n}\n\nvoid VideoWidgetPrivate::init()\n{\n Q_Q(VideoWidget);\n QObject::connect(&cursorTimer, SIGNAL(timeout()), q, SLOT(_k_cursorTimeout()));\n}\n\nvoid VideoWidget::mouseMoveEvent(QMouseEvent *)\n{\n K_D(VideoWidget);\n if (Qt::BlankCursor == cursor().shape()) {\n unsetCursor();\n d->cursorTimer.start();\n }\n}\n\nvoid VideoWidgetPrivate::_k_cursorTimeout()\n{\n Q_Q(VideoWidget);\n if (Qt::ArrowCursor == q->cursor().shape()) {\n q->setCursor(Qt::BlankCursor);\n }\n}\n\nvoid VideoWidgetPrivate::createBackendObject()\n{\n if (m_backendObject)\n return;\n Q_Q(VideoWidget);\n m_backendObject = Factory::createVideoWidget(q);\n if (m_backendObject) {\n setupBackendObject();\n }\n}\n\n#define PHONON_CLASSNAME VideoWidget\n\nPHONON_INTERFACE_GETTER(Phonon::VideoWidget::AspectRatio, aspectRatio, d->aspectRatio)\nPHONON_INTERFACE_SETTER(setAspectRatio, aspectRatio, Phonon::VideoWidget::AspectRatio)\n\nPHONON_INTERFACE_GETTER(Phonon::VideoWidget::ScaleMode, scaleMode, d->scaleMode)\nPHONON_INTERFACE_SETTER(setScaleMode, scaleMode, Phonon::VideoWidget::ScaleMode)\n\nPHONON_INTERFACE_GETTER(qreal, brightness, d->brightness)\nPHONON_INTERFACE_SETTER(setBrightness, brightness, qreal)\n\nPHONON_INTERFACE_GETTER(qreal, contrast, d->contrast)\nPHONON_INTERFACE_SETTER(setContrast, contrast, qreal)\n\nPHONON_INTERFACE_GETTER(qreal, hue, d->hue)\nPHONON_INTERFACE_SETTER(setHue, hue, qreal)\n\nPHONON_INTERFACE_GETTER(qreal, saturation, d->saturation)\nPHONON_INTERFACE_SETTER(setSaturation, saturation, qreal)\n\nvoid VideoWidget::setFullScreen(bool newFullScreen)\n{\n pDebug() << Q_FUNC_INFO << newFullScreen;\n K_D(VideoWidget);\n \/\/ TODO: disable screensaver? or should we leave that responsibility to the\n \/\/ application?\n Qt::WindowFlags flags = windowFlags();\n if (newFullScreen) {\n d->changeFlags = !(flags & Qt::Window);\n if (d->changeFlags) {\n flags &= ~Qt::SubWindow;\n flags |= Qt::Window;\n } \/\/ else it's a toplevel window already\n } else if (d->changeFlags && parent()) {\n flags &= ~Qt::Window;\n flags |= Qt::SubWindow;\n }\n setWindowFlags(flags);\n if (newFullScreen) {\n showFullScreen();\n } else {\n showNormal();\n }\n}\n\nvoid VideoWidget::exitFullScreen()\n{\n setFullScreen(false);\n}\n\nvoid VideoWidget::enterFullScreen()\n{\n setFullScreen(true);\n}\n\nbool VideoWidgetPrivate::aboutToDeleteBackendObject()\n{\n aspectRatio = pINTERFACE_CALL(aspectRatio());\n scaleMode = pINTERFACE_CALL(scaleMode());\n return AbstractVideoOutputPrivate::aboutToDeleteBackendObject();\n}\n\nvoid VideoWidgetPrivate::setupBackendObject()\n{\n Q_Q(VideoWidget);\n Q_ASSERT(m_backendObject);\n \/\/AbstractVideoOutputPrivate::setupBackendObject();\n pDebug() << \"calling setAspectRatio on the backend \" << aspectRatio;\n pINTERFACE_CALL(setAspectRatio(aspectRatio));\n pINTERFACE_CALL(setScaleMode(scaleMode));\n\n QWidget *w = pINTERFACE_CALL(widget());\n if (w) {\n layout.addWidget(w);\n q->setSizePolicy(w->sizePolicy());\n w->setMouseTracking(true);\n }\n}\n\n\/*\nQSize VideoWidget::sizeHint()\n{\n if (k_ptr->backendObject())\n {\n QWidget *w = pINTERFACE_CALL(widget());\n if (w)\n return w->sizeHint();\n }\n return QSize(0, 0);\n}\n\nQSize VideoWidget::minimumSizeHint()\n{\n if (k_ptr->backendObject())\n {\n QWidget *w = pINTERFACE_CALL(widget());\n if (w)\n return w->minimumSizeHint();\n }\n return QSize(0, 0);\n} *\/\n\n} \/\/namespace Phonon\n\n#include \"moc_videowidget.cpp\"\n\n#undef PHONON_CLASSNAME\n\/\/ vim: sw=4 ts=4 tw=80\n<|endoftext|>"} {"text":"<commit_before>\/*=========================================================================\n\n Program: ORFEO Toolbox\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n\n Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.\n See OTBCopyright.txt for details.\n\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notices for more information.\n\n =========================================================================*\/\n\n#include \"otbDEMConvert.h\"\n\n#include \"otbImage.h\"\n#include \"otbVectorImage.h\"\n#include \"otbImageFileReader.h\"\n#include \"otbStreamingImageFileWriter.h\"\n\n\/\/ OSSIM include\n#include <ossim\/base\/ossimKeywordNames.h>\n#include <ossim\/base\/ossimStdOutProgress.h>\n#include <ossim\/base\/ossimFilename.h>\n#include <ossim\/base\/ossimKeywordlist.h>\n#include <ossim\/imaging\/ossimJpegWriter.h>\n#include <ossim\/imaging\/ossimImageHandler.h>\n#include <ossim\/imaging\/ossimImageSource.h>\n#include <ossim\/imaging\/ossimImageHandlerRegistry.h>\n#include <ossim\/imaging\/ossimImageWriterFactoryRegistry.h>\n#include <ossim\/imaging\/ossimImageWriterFactory.h>\n#include <ossim\/imaging\/ossimImageFileWriter.h>\n#include <ossim\/imaging\/ossimCacheTileSource.h>\n#include <ossim\/imaging\/ossimBandSelector.h>\n#include <ossim\/imaging\/ossimCibCadrgTileSource.h>\n\nnamespace otb\n{\n\n\ntemplate<typename TPixelType>\nint generic_convert_to_tif(otb::ApplicationOptionsResult* parseResult, ossimFilename tempFilename)\n{\n typedef otb::VectorImage<TPixelType> ImageType;\n typedef otb::ImageFileReader<ImageType> ReaderType;\n typedef otb::StreamingImageFileWriter<ImageType> WriterType;\n\n typename ReaderType::Pointer reader = ReaderType::New();\n typename WriterType::Pointer writer = WriterType::New();\n\n reader->SetFileName(parseResult->GetInputImage().c_str());\n writer->SetFileName(tempFilename); \n\n writer->SetInput(reader->GetOutput());\n writer->Update();\n\n return EXIT_SUCCESS;\n}\n\n\nint DEMConvert::Describe(ApplicationDescriptor* descriptor)\n{\n descriptor->SetName(\"DEMConvertApplication\");\n descriptor->SetDescription(\"Convert a DEM file into a general raster (.ras, .geom and .omd)\");\n descriptor->AddInputImage();\n descriptor->AddOption(\"OutputPath\", \"The filename (or path filename) of the output. It generates a Output.geom, Output.omd and Output.ras file.\",\"out\", 1, true,ApplicationDescriptor::String);\n descriptor->AddOption(\"KeepTif\", \"Keep the temporary generate tif file.\",\"ktif\", 0, false,ApplicationDescriptor::Boolean);\n \n return EXIT_SUCCESS;\n}\n\n\n\/* The main is simple : read image using OTB and write it as a tif.\n* Read this tif using OSSIM and convert it as a general raster file (.ras, .geom and . omd)\n* first write the image as a tif (supported by OSSIM) allows to not only be abble to work\n* with OSSIM supported format but any more.\n*\/\n\nint DEMConvert::Execute(otb::ApplicationOptionsResult* parseResult)\n{\n \/\/ Load input and output filename\n const char * input_file = parseResult->GetInputImage().c_str();\n\n ossimFilename tempFilename(parseResult->GetParameterString(\"OutputPath\"));\n tempFilename += \"_DEMConvert.tif\";\n \n \/\/ Search for the input \n typedef otb::VectorImage<double, 2> InputImageType;\n typedef otb::ImageFileReader<InputImageType> ReaderType;\n ReaderType::Pointer reader=ReaderType::New();\n reader->SetFileName(input_file);\n reader->UpdateOutputInformation();\n\n \/\/ Generate the tif image using OTB\n \/\/ We keep the same pixel type\n std::string componentTypeInfo(reader->GetImageIO()->GetComponentTypeInfo().name());\n if( componentTypeInfo == typeid(unsigned char).name())\n {\n generic_convert_to_tif<unsigned char>(parseResult, tempFilename);\n }\n else if( componentTypeInfo == typeid(char).name())\n {\n generic_convert_to_tif<char>(parseResult, tempFilename);\n }\n else if( componentTypeInfo == typeid(unsigned short).name())\n {\n generic_convert_to_tif<unsigned short>(parseResult, tempFilename);\n }\n else if( componentTypeInfo == typeid(short).name())\n {\n generic_convert_to_tif<short>(parseResult, tempFilename);\n }\n else if( componentTypeInfo == typeid(unsigned int).name())\n {\n generic_convert_to_tif<unsigned int>(parseResult, tempFilename);\n }\n else if( componentTypeInfo == typeid(int).name())\n {\n generic_convert_to_tif<int>(parseResult, tempFilename);\n }\n else if( componentTypeInfo == typeid(unsigned long).name())\n {\n generic_convert_to_tif<unsigned long>(parseResult, tempFilename);\n }\n else if( componentTypeInfo == typeid(long).name())\n {\n generic_convert_to_tif<long>(parseResult, tempFilename);\n }\n else if( componentTypeInfo == typeid(float).name())\n {\n generic_convert_to_tif<float>(parseResult, tempFilename);\n }\n else if( componentTypeInfo == typeid(double).name())\n {\n generic_convert_to_tif<double>(parseResult, tempFilename);\n }\n else\n {\n itkExceptionMacro(\"This appication doesn't support image pixel type \" << componentTypeInfo);\n return EXIT_FAILURE;\n }\n\n\n \/\/ Keyword list to initialize image writers with.\n ossimKeywordlist kwl;\n const char* PREFIX = \"imagewriter.\";\n \/\/ Define the output file type\n const ossimString output_type(\"general_raster_bil\");\n kwl.add(PREFIX, ossimKeywordNames::TYPE_KW, output_type.c_str(), true);\n \n \/\/ Get an image handler for the input file.\n ossimRefPtr<ossimImageHandler> ih = ossimImageHandlerRegistry::instance()->open(tempFilename);\n \n \/\/ Initialize the \n if (ih->getErrorStatus() == ossimErrorCodes::OSSIM_ERROR)\n {\n itkExceptionMacro(\"Error reading image: \" << input_file << \"Exiting application...\"); \n return EXIT_FAILURE;\n }\n \n ih->initialize();\n \n ossimRefPtr<ossimImageSource> source = ih.get();\n ossimRefPtr<ossimBandSelector> bs = 0;\n \n \n \/\/ Get the image rectangle for the rrLevel selected.\n ossimIrect output_rect;\n output_rect = source->getBoundingRect(0);\n\n ossimRefPtr<ossimImageFileWriter> writer =\n ossimImageWriterFactoryRegistry::instance()->createWriter(kwl, PREFIX);\n\n writer->connectMyInputTo(0, source.get());\n writer->open(ossimFilename(parseResult->GetParameterString(\"OutputPath\"))+\".ras\");\n \n \/\/ Add a listener to get percent complete.\n ossimStdOutProgress prog(0, true);\n writer->addListener(&prog);\n\n if (writer->getErrorStatus() == ossimErrorCodes::OSSIM_OK)\n {\n if( (ih->getOutputScalarType() != OSSIM_UCHAR) &&\n (PTR_CAST(ossimJpegWriter, writer.get()) ) )\n {\n writer->setScaleToEightBitFlag(true);\n }\n\n ossimRefPtr<ossimCacheTileSource> cache = new ossimCacheTileSource;\n ossimIpt tileWidthHeight(ih->getImageTileWidth(),\n ih->getImageTileHeight());\n \/\/ only use the cache if its stripped\n if(static_cast<ossim_uint32>(tileWidthHeight.x) ==\n ih->getBoundingRect().width())\n {\n cache->connectMyInputTo(0, source.get());\n cache->setTileSize(tileWidthHeight);\n writer->connectMyInputTo(0, cache.get());\n }\n else\n {\n writer->connectMyInputTo(0, source.get());\n }\n writer->initialize();\n writer->setAreaOfInterest(output_rect); \/\/ Set the output rectangle.\n \n try\n {\n writer->execute();\n }\n catch(std::exception& e)\n {\n itkExceptionMacro(\"Error occurs writing the ouput image...\");\n return EXIT_FAILURE;\n }\n \n }\n else\n {\n itkExceptionMacro(\"Error detected in the image writer...\");\n return EXIT_FAILURE;\n }\n\n\n\n if ( parseResult->IsOptionPresent(\"KeepTif\") == false)\n {\n bool resRemove = tempFilename.remove();\n if( resRemove == false )\n {\n std::cout<<\"Enable to erase the output temporary file \"<<tempFilename<<\".\"<<std::endl;\n }\n }\n\n return EXIT_SUCCESS;\n}\n\n\n} \/\/ namespace otb\n<commit_msg>ENH : refactoring, direct ras writing with OTB, no more cache tif image<commit_after>\/*=========================================================================\n\n Program: ORFEO Toolbox\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n\n Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.\n See OTBCopyright.txt for details.\n\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notices for more information.\n\n =========================================================================*\/\n\n#include \"otbDEMConvert.h\"\n\n#include \"otbImage.h\"\n#include \"otbVectorImage.h\"\n#include \"otbImageFileReader.h\"\n#include \"otbStreamingImageFileWriter.h\"\n#include \"otbStreamingMinMaxVectorImageFilter.h\"\n\n\/\/ OSSIM include\n#include <ossim\/base\/ossimKeywordNames.h>\n#include <ossim\/base\/ossimStdOutProgress.h>\n#include <ossim\/base\/ossimFilename.h>\n#include <ossim\/base\/ossimKeywordlist.h>\n#include <ossim\/imaging\/ossimJpegWriter.h>\n#include <ossim\/imaging\/ossimImageHandler.h>\n#include <ossim\/imaging\/ossimImageSource.h>\n#include <ossim\/imaging\/ossimImageHandlerRegistry.h>\n#include <ossim\/imaging\/ossimImageWriterFactoryRegistry.h>\n#include <ossim\/imaging\/ossimImageWriterFactory.h>\n#include <ossim\/imaging\/ossimImageFileWriter.h>\n\/\/#include <ossim\/imaging\/ossimCacheTileSource.h>\n\/\/#include <ossim\/imaging\/ossimBandSelector.h>\n\/\/#include <ossim\/imaging\/ossimCibCadrgTileSource.h>\n#include <ossim\/base\/ossimEndian.h>\n#include <ossim\/base\/ossimScalarTypeLut.h>\n#include <ossim\/imaging\/ossimMetadataFileWriter.h>\n\/\/#include <ossim\/base\/ossimSource.h>\n#include <ossim\/imaging\/ossimGeomFileWriter.h>\n\nnamespace otb\n{\n\n\ntemplate<typename TPixelType>\nint generic_convert_to_ras(otb::ApplicationOptionsResult* parseResult, ossimFilename rasFilename)\n{\n typedef otb::VectorImage<TPixelType> ImageType;\n typedef otb::ImageFileReader<ImageType> ReaderType;\n typedef otb::StreamingImageFileWriter<ImageType> WriterType;\n \n\n typename ReaderType::Pointer reader = ReaderType::New();\n typename WriterType::Pointer writer = WriterType::New();\n\n reader->SetFileName(parseResult->GetInputImage().c_str());\n writer->SetFileName(rasFilename); \n\n writer->SetInput(reader->GetOutput());\n writer->Update();\n\n return EXIT_SUCCESS;\n}\n\n\nint DEMConvert::Describe(ApplicationDescriptor* descriptor)\n{\n descriptor->SetName(\"DEMConvertApplication\");\n descriptor->SetDescription(\"Convert a DEM file into a general raster (.ras, .geom and .omd)\");\n descriptor->AddInputImage();\n descriptor->AddOption(\"OutputPath\", \"The filename (or path filename) of the output. It generates a Output.geom, Output.omd and Output.ras file.\",\"out\", 1, true, ApplicationDescriptor::String);\n \n return EXIT_SUCCESS;\n}\n\n\n\/* The main is simple : read image using OTB and write it as a tif.\n* Read this tif using OSSIM and convert it as a general raster file (.ras, .geom and . omd)\n* first write the image as a tif (supported by OSSIM) allows to not only be abble to work\n* with OSSIM supported format but any more.\n*\/\n\nint DEMConvert::Execute(otb::ApplicationOptionsResult* parseResult)\n{\n \/\/ Load input and output filename\n const char * input_file = parseResult->GetInputImage().c_str();\n\n ossimFilename rasFilename(parseResult->GetParameterString(\"OutputPath\"));\n rasFilename += \".ras\";\n \n \/\/ Search for the input \n typedef otb::VectorImage<double, 2> InputImageType;\n typedef otb::ImageFileReader<InputImageType> ReaderType;\n typedef otb::StreamingMinMaxVectorImageFilter<InputImageType> MinMaxCalculatorType;\n \n ReaderType::Pointer reader=ReaderType::New();\n reader->SetFileName(input_file);\n reader->UpdateOutputInformation();\n\n \/\/ Generate the tif image using OTB\n \/\/ We keep the same pixel type\n std::string componentTypeInfo(reader->GetImageIO()->GetComponentTypeInfo().name());\n if( componentTypeInfo == typeid(unsigned char).name())\n {\n generic_convert_to_ras<unsigned char>(parseResult, rasFilename);\n }\n else if( componentTypeInfo == typeid(char).name())\n {\n generic_convert_to_ras<char>(parseResult, rasFilename);\n }\n else if( componentTypeInfo == typeid(unsigned short).name())\n {\n generic_convert_to_ras<unsigned short>(parseResult, rasFilename);\n }\n else if( componentTypeInfo == typeid(short).name())\n {\n generic_convert_to_ras<short>(parseResult, rasFilename);\n }\n else if( componentTypeInfo == typeid(unsigned int).name())\n {\n generic_convert_to_ras<unsigned int>(parseResult, rasFilename);\n }\n else if( componentTypeInfo == typeid(int).name())\n {\n generic_convert_to_ras<int>(parseResult, rasFilename);\n }\n else if( componentTypeInfo == typeid(unsigned long).name())\n {\n generic_convert_to_ras<unsigned long>(parseResult, rasFilename);\n }\n else if( componentTypeInfo == typeid(long).name())\n {\n generic_convert_to_ras<long>(parseResult, rasFilename);\n }\n else if( componentTypeInfo == typeid(float).name())\n {\n generic_convert_to_ras<float>(parseResult, rasFilename);\n }\n else if( componentTypeInfo == typeid(double).name())\n {\n generic_convert_to_ras<double>(parseResult, rasFilename);\n }\n else\n {\n itkExceptionMacro(\"This appication doesn't support image pixel type \" << componentTypeInfo);\n return EXIT_FAILURE;\n }\n\n\n \/\/ Keyword list to initialize image writers with.\n ossimKeywordlist kwl;\n const char* PREFIX = \"imagewriter.\";\n \/\/ Define the output file type\n const ossimString output_type(\"general_raster_bil\");\n kwl.add(PREFIX, ossimKeywordNames::TYPE_KW, output_type.c_str(), true);\n \n \/\/ Get an image handler for the input file.\n ossimRefPtr<ossimImageHandler> ih = ossimImageHandlerRegistry::instance()->open(rasFilename);\n \n \/\/ Initialize the \n if (ih->getErrorStatus() == ossimErrorCodes::OSSIM_ERROR)\n {\n itkExceptionMacro(\"Error reading image: \" << input_file << \"Exiting application...\"); \n return EXIT_FAILURE;\n }\n \n ih->initialize();\n \n ossimRefPtr<ossimImageSource> source = ih.get();\n \n ossimString interleaveType = \"bil\";\n ossimString scalar = ossimScalarTypeLut::instance()->getEntryString(ih->getOutputScalarType());\n \n \/\/ Compute image min\/max\n MinMaxCalculatorType::Pointer minMax = MinMaxCalculatorType::New();\n minMax->SetInput(reader->GetOutput());\n minMax->Update();\n \n\/*\n std::vector<double> minVect;\n std::vector<double> maxVect;\n for (unsigned int i=0; i<reader->GetOutput()->GetNumberOfComponentsPerPixel(); ++i)\n {\n minVect.push_back( static_cast<double>(ih->getMinPixelValue(i) ) );\n maxVect.push_back( static_cast<double>(ih->getMaxPixelValue(i) ) );\n }\n *\/\n \n \/***************************************************************************\n ************************** WRITE OMD file\n ****************************************************************************\/\n \/\/ Make a header file name from the image file.\n ossimFilename headerFile(rasFilename);\n headerFile.setExtension(\".omd\"); \/\/ ossim meta data\n\n std::ofstream os;\n os.open(headerFile.c_str(), ios::out);\n if (!os)\n {\n itkExceptionMacro(\" Error: Could not open: \" << headerFile);\n return EXIT_FAILURE;\n }\n \n os << \"\/\/ *** ossim meta data general raster header file ***\\n\"\n << ossimKeywordNames::IMAGE_FILE_KW << \": \"\n << rasFilename.file().c_str() << \"\\n\"\n << ossimKeywordNames::IMAGE_TYPE_KW << \": \"\n << output_type << \"\\n\"\n << ossimKeywordNames::INTERLEAVE_TYPE_KW << \": \"\n << interleaveType.c_str() << \"\\n\"\n << ossimKeywordNames::NUMBER_BANDS_KW << \": \"\n << reader->GetOutput()->GetNumberOfComponentsPerPixel() << \"\\n\"\n << ossimKeywordNames::NUMBER_LINES_KW << \": \"\n << ih->getNumberOfLines() << \"\\n\"\/\/(theAreaOfInterest.lr().y - theAreaOfInterest.ul().y + 1) << \"\\n\"\n << ossimKeywordNames::NUMBER_SAMPLES_KW << \": \"\n << ih->getNumberOfSamples() << \"\\n\"\/\/(theAreaOfInterest.lr().x - theAreaOfInterest.ul().x + 1) << \"\\n\"\n << ossimKeywordNames::SCALAR_TYPE_KW << \": \"\n << scalar.c_str() << \"\\n\"\n << ossimKeywordNames::BYTE_ORDER_KW <<\": \"\n << ((ossimEndian().getSystemEndianType()==OSSIM_BIG_ENDIAN)?\"big_endian\":\"little_endian\")\n << \"\\n\"\n << std::endl;\n\n \/\/ Output the null\/min\/max for each band.\n os << \"\\n\/\/ NOTE: Bands are one based, band1 is the first band.\"\n << std::endl;\n\n for (ossim_uint32 i=0; i<reader->GetOutput()->GetNumberOfComponentsPerPixel(); ++i)\n {\n ossimString prefix = ossimKeywordNames::BAND_KW +\n ossimString::toString(i+1) + \".\";\n \n ossimString null_pix = ossimString::toString(ih->getNullPixelValue(i));\n ossimString min_pix = ossimString::toString(minMax->GetMinimum()[i]);\n ossimString max_pix = ossimString::toString(minMax->GetMaximum()[i]);\n \n os << prefix.c_str() << ossimKeywordNames::NULL_VALUE_KW << \": \"\n << null_pix.c_str() << \"\\n\"\n << prefix << ossimKeywordNames::MIN_VALUE_KW << \": \"\n << min_pix.c_str() << \"\\n\"\n << prefix << ossimKeywordNames::MAX_VALUE_KW << \": \"\n << max_pix.c_str() << std::endl;\n }\n \n os.close();\n\n\n \/***************************************************************************\n ************************** WRITE GEOM file\n ***************************************************************************\/\n \/\/ Make the file name.\n ossimFilename geomFile( rasFilename );\n geomFile.setExtension(ossimString(\"geom\"));\n \n \/\/ Make the writer.\n ossimRefPtr<ossimMetadataFileWriter> geoWriter = new ossimGeomFileWriter();\n\n \/\/ Set things up.\n geoWriter->connectMyInputTo(0, source.get());\n geoWriter->setFilename(geomFile);\n geoWriter->initialize();\n geoWriter->setPixelType(OSSIM_PIXEL_IS_POINT);\n source.get()->initialize();\n geoWriter->setAreaOfInterest( ih->getBoundingRect() );\n\n \/\/ Write it to disk.\n try\n {\n geoWriter->execute();\n }\n catch(std::exception& e)\n {\n itkExceptionMacro(\"Error occurs writing geom file...\");\n return EXIT_FAILURE;\n }\n\n return EXIT_SUCCESS;\n}\n\n\n\n} \/\/ namespace otb\n<|endoftext|>"} {"text":"<commit_before>\/\/=====================================================================\/\/\n\/*! @file\n @brief VL53L0X 距離センサー・サンプル\n @author 平松邦仁 (hira@rvf-rc45.net)\n\t@copyright\tCopyright (C) 2017 Kunihito Hiramatsu @n\n\t\t\t\tReleased under the MIT license @n\n\t\t\t\thttps:\/\/github.com\/hirakuni45\/R8C\/blob\/master\/LICENSE\n*\/\n\/\/=====================================================================\/\/\n#include <cstring>\n#include \"system.hpp\"\n#include \"clock.hpp\"\n#include \"port.hpp\"\n#include \"common\/command.hpp\"\n#include \"common\/format.hpp\"\n#include \"common\/intr_utils.hpp\"\n#include \"common\/port_map.hpp\"\n#include \"common\/uart_io.hpp\"\n#include \"common\/fifo.hpp\"\n#include \"common\/trb_io.hpp\"\n#include \"chip\/VL53L0X.hpp\"\n\nnamespace {\n\n\ttypedef device::trb_io<utils::null_task, uint8_t> timer_b;\n\ttimer_b timer_b_;\n\n\ttypedef utils::fifo<uint8_t, 16> buffer;\n\ttypedef device::uart_io<device::UART0, buffer, buffer> uart;\n\tuart uart_;\n\n\t\/\/ I2C ポートの定義クラス\n\t\/\/ P4_B5 (12): SDA\n\ttypedef device::PORT<device::PORT4, device::bitpos::B5> sda_port;\n\t\/\/ P1_B7 (13): SCL\n\ttypedef device::PORT<device::PORT1, device::bitpos::B7> scl_port;\n\n\ttypedef device::iica_io<sda_port, scl_port> iica;\n\tiica\ti2c_;\n\ttypedef chip::VL53L0X<iica> VLX;\n\tVLX\t\tvlx_(i2c_);\n\n\tutils::command<64> command_;\n}\n\nextern \"C\" {\n\n\tvoid sci_putch(char ch) {\n\t\tuart_.putch(ch);\n\t}\n\n\n\tchar sci_getch(void) {\n\t\treturn uart_.getch();\n\t}\n\n\n\tuint16_t sci_length() {\n\t\treturn uart_.length();\n\t}\n\n\n\tvoid sci_puts(const char* str) {\n\t\tuart_.puts(str);\n\t}\n\n\n\tvoid TIMER_RB_intr(void) {\n\t\ttimer_b_.itask();\n\t\tvlx_.add_millis(10);\n\t}\n\n\n\tvoid UART0_TX_intr(void) {\n\t\tuart_.isend();\n\t}\n\n\n\tvoid UART0_RX_intr(void) {\n\t\tuart_.irecv();\n\t}\n\n}\n\n\nnamespace {\n\n\n\n}\n\n\/\/ __attribute__ ((section (\".exttext\")))\nint main(int argc, char *argv[])\n{\n\tusing namespace device;\n\n\/\/ クロック関係レジスタ・プロテクト解除\n\tPRCR.PRC0 = 1;\n\n\/\/ 高速オンチップオシレーターへ切り替え(20MHz)\n\/\/ ※ F_CLK を設定する事(Makefile内)\n\tOCOCR.HOCOE = 1;\n\tutils::delay::micro_second(1); \/\/ >=30us(125KHz)\n\tSCKCR.HSCKSEL = 1;\n\tCKSTPR.SCKSEL = 1;\n\n\t\/\/ タイマーB初期化\n\t{\n\t\tuint8_t ir_level = 2;\n\t\ttimer_b_.start_timer(100, ir_level);\n\t}\n\n\t\/\/ UART の設定 (P1_4: TXD0[out], P1_5: RXD0[in])\n\t\/\/ ※シリアルライターでは、RXD 端子は、P1_6 となっているので注意!\n\t{\n\t\tutils::PORT_MAP(utils::port_map::P14::TXD0);\n\t\tutils::PORT_MAP(utils::port_map::P15::RXD0);\n\t\tuint8_t ir_level = 1;\n\t\tuart_.start(57600, ir_level);\n\t}\n\n\t\/\/ I2C クラスの初期化\n\t{\n\t\ti2c_.start(iica::speed::fast);\n\t}\n\n\t\/\/ VL53L0X を開始\n\tif(!vlx_.start()) {\n\t\tutils::format(\"VL53L0X start fail\\n\");\n\t} else {\n\t\t\/\/ 20ms\n\t\tvlx_.set_measurement_timing_budget(200000);\n\t}\n\n\tsci_puts(\"Start R8C VL53L0X monitor\\n\");\n\tcommand_.set_prompt(\"# \");\n\n\t\/\/ LED シグナル用ポートを出力\n\tPD1.B0 = 1;\n\n\tuint8_t cnt = 0;\n\tuint8_t itv = 0;\n\twhile(1) {\n\t\ttimer_b_.sync();\n\n\t\tif(cnt >= 20) {\n\t\t\tcnt = 0;\n\t\t}\n\t\tif(cnt < 10) P1.B0 = 1;\n\t\telse P1.B0 = 0;\n\t\t++cnt;\n\n\t\t++itv;\n\t\tif(itv >= 100) {\n\t\t\tauto len = vlx_.read_range_single_millimeters();\n\t\t\tutils::format(\"Length: %d\\n\") % len;\n\t\t\titv = 0;\n\t\t}\n\n\t\t\/\/ コマンド入力と、コマンド解析\n\t\tif(command_.service()) {\n\t\t\tuint8_t cmdn = command_.get_words();\n\t\t\tif(cmdn >= 1) {\n\t\t\t\tif(command_.cmp_word(0, \"date\")) {\n\t\t\t\t\tif(cmdn == 1) {\n\n\t\t\t\t\t} else {\n\n\t\t\t\t\t}\n\t\t\t\t} else if(command_.cmp_word(0, \"help\")) {\n\/\/\t\t\t\t\tsci_puts(\"date\\n\");\n\/\/\t\t\t\t\tsci_puts(\"date yyyy\/mm\/dd hh:mm[:ss]\\n\");\n\t\t\t\t} else {\n\t\t\t\t\tchar buff[12];\n\t\t\t\t\tif(command_.get_word(0, sizeof(buff), buff)) {\n\t\t\t\t\t\tutils::format(\"Command error: %s\\n\") % buff;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n<commit_msg>update print interval<commit_after>\/\/=====================================================================\/\/\n\/*! @file\n @brief VL53L0X 距離センサー・サンプル\n @author 平松邦仁 (hira@rvf-rc45.net)\n\t@copyright\tCopyright (C) 2017 Kunihito Hiramatsu @n\n\t\t\t\tReleased under the MIT license @n\n\t\t\t\thttps:\/\/github.com\/hirakuni45\/R8C\/blob\/master\/LICENSE\n*\/\n\/\/=====================================================================\/\/\n#include <cstring>\n#include \"system.hpp\"\n#include \"clock.hpp\"\n#include \"port.hpp\"\n#include \"common\/command.hpp\"\n#include \"common\/format.hpp\"\n#include \"common\/intr_utils.hpp\"\n#include \"common\/port_map.hpp\"\n#include \"common\/uart_io.hpp\"\n#include \"common\/fifo.hpp\"\n#include \"common\/trb_io.hpp\"\n#include \"chip\/VL53L0X.hpp\"\n\nnamespace {\n\n\ttypedef device::trb_io<utils::null_task, uint8_t> timer_b;\n\ttimer_b timer_b_;\n\n\ttypedef utils::fifo<uint8_t, 16> buffer;\n\ttypedef device::uart_io<device::UART0, buffer, buffer> uart;\n\tuart uart_;\n\n\t\/\/ I2C ポートの定義クラス\n\t\/\/ P4_B5 (12): SDA\n\ttypedef device::PORT<device::PORT4, device::bitpos::B5> sda_port;\n\t\/\/ P1_B7 (13): SCL\n\ttypedef device::PORT<device::PORT1, device::bitpos::B7> scl_port;\n\n\ttypedef device::iica_io<sda_port, scl_port> iica;\n\tiica\ti2c_;\n\ttypedef chip::VL53L0X<iica> VLX;\n\tVLX\t\tvlx_(i2c_);\n\n\tutils::command<64> command_;\n}\n\nextern \"C\" {\n\n\tvoid sci_putch(char ch) {\n\t\tuart_.putch(ch);\n\t}\n\n\n\tchar sci_getch(void) {\n\t\treturn uart_.getch();\n\t}\n\n\n\tuint16_t sci_length() {\n\t\treturn uart_.length();\n\t}\n\n\n\tvoid sci_puts(const char* str) {\n\t\tuart_.puts(str);\n\t}\n\n\n\tvoid TIMER_RB_intr(void) {\n\t\ttimer_b_.itask();\n\t\tvlx_.add_millis(10);\n\t}\n\n\n\tvoid UART0_TX_intr(void) {\n\t\tuart_.isend();\n\t}\n\n\n\tvoid UART0_RX_intr(void) {\n\t\tuart_.irecv();\n\t}\n\n}\n\n\nnamespace {\n\n\n\n}\n\n\/\/ __attribute__ ((section (\".exttext\")))\nint main(int argc, char *argv[])\n{\n\tusing namespace device;\n\n\/\/ クロック関係レジスタ・プロテクト解除\n\tPRCR.PRC0 = 1;\n\n\/\/ 高速オンチップオシレーターへ切り替え(20MHz)\n\/\/ ※ F_CLK を設定する事(Makefile内)\n\tOCOCR.HOCOE = 1;\n\tutils::delay::micro_second(1); \/\/ >=30us(125KHz)\n\tSCKCR.HSCKSEL = 1;\n\tCKSTPR.SCKSEL = 1;\n\n\t\/\/ タイマーB初期化\n\t{\n\t\tuint8_t ir_level = 2;\n\t\ttimer_b_.start_timer(100, ir_level);\n\t}\n\n\t\/\/ UART の設定 (P1_4: TXD0[out], P1_5: RXD0[in])\n\t\/\/ ※シリアルライターでは、RXD 端子は、P1_6 となっているので注意!\n\t{\n\t\tutils::PORT_MAP(utils::port_map::P14::TXD0);\n\t\tutils::PORT_MAP(utils::port_map::P15::RXD0);\n\t\tuint8_t ir_level = 1;\n\t\tuart_.start(57600, ir_level);\n\t}\n\n\t\/\/ I2C クラスの初期化\n\t{\n\t\ti2c_.start(iica::speed::fast);\n\t}\n\n\t\/\/ VL53L0X を開始\n\tif(!vlx_.start()) {\n\t\tutils::format(\"VL53L0X start fail\\n\");\n\t} else {\n\t\t\/\/ 20ms\n\t\tvlx_.set_measurement_timing_budget(200000);\n\t}\n\n\tsci_puts(\"Start R8C VL53L0X monitor\\n\");\n\tcommand_.set_prompt(\"# \");\n\n\t\/\/ LED シグナル用ポートを出力\n\tPD1.B0 = 1;\n\n\tuint8_t cnt = 0;\n\tuint8_t itv = 0;\n\twhile(1) {\n\t\ttimer_b_.sync();\n\n\t\tif(cnt >= 20) {\n\t\t\tcnt = 0;\n\t\t}\n\t\tif(cnt < 10) P1.B0 = 1;\n\t\telse P1.B0 = 0;\n\t\t++cnt;\n\n\t\t++itv;\n\t\tif(itv >= 50) {\n\t\t\tauto len = vlx_.read_range_single_millimeters();\n\t\t\tutils::format(\"Length: %d\\n\") % len;\n\t\t\titv = 0;\n\t\t}\n\n\t\t\/\/ コマンド入力と、コマンド解析\n\t\tif(command_.service()) {\n\t\t\tuint8_t cmdn = command_.get_words();\n\t\t\tif(cmdn >= 1) {\n\t\t\t\tif(command_.cmp_word(0, \"date\")) {\n\t\t\t\t\tif(cmdn == 1) {\n\n\t\t\t\t\t} else {\n\n\t\t\t\t\t}\n\t\t\t\t} else if(command_.cmp_word(0, \"help\")) {\n\/\/\t\t\t\t\tsci_puts(\"date\\n\");\n\/\/\t\t\t\t\tsci_puts(\"date yyyy\/mm\/dd hh:mm[:ss]\\n\");\n\t\t\t\t} else {\n\t\t\t\t\tchar buff[12];\n\t\t\t\t\tif(command_.get_word(0, sizeof(buff), buff)) {\n\t\t\t\t\t\tutils::format(\"Command error: %s\\n\") % buff;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"amd64.h\"\n#include \"distribution.hh\"\n#include \"spinbarrier.hh\"\n#include \"libutil.h\"\n#include \"xsys.h\"\n\n#include <fcntl.h>\n#include <spawn.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <unistd.h>\n#include <sys\/stat.h>\n#include <sys\/wait.h>\n\n#include <string>\n#include <thread>\n\n\/\/ Set to 1 to manage the queue manager's life time from this program.\n\/\/ Set to 0 if the queue manager is started and stopped outside of\n\/\/ mailbench.\n#define START_QMAN 1\n\nusing std::string;\n\nenum { warmup_secs = 1 };\nenum { duration = 5 };\n\nconst char *message =\n \"Received: from incoming.csail.mit.edu (incoming.csail.mit.edu [128.30.2.16])\\n\"\n \" by metroplex (Cyrus v2.2.13-Debian-2.2.13-14+lenny5) with LMTPA;\\n\"\n \" Tue, 19 Mar 2013 22:45:50 -0400\\n\"\n \"X-Sieve: CMU Sieve 2.2\\n\"\n \"Received: from mailhub-auth-3.mit.edu ([18.9.21.43])\\n\"\n \" by incoming.csail.mit.edu with esmtps\\n\"\n \" (TLS1.0:DHE_RSA_AES_256_CBC_SHA1:32)\\n\"\n \" (Exim 4.72)\\n\"\n \" (envelope-from <xxxxxxxx@MIT.EDU>)\\n\"\n \" id 1UI92E-0007D2-7N\\n\"\n \" for xxxxxxxxx@csail.mit.edu; Tue, 19 Mar 2013 22:45:50 -0400\\n\"\n \"Received: from outgoing.mit.edu (OUTGOING-AUTH-1.MIT.EDU [18.9.28.11])\\n\"\n \" by mailhub-auth-3.mit.edu (8.13.8\/8.9.2) with ESMTP id r2K2jnO5025684\\n\"\n \" for <xxxxxxxx@mit.edu>; Tue, 19 Mar 2013 22:45:49 -0400\\n\"\n \"Received: from xxxxxxxxx.csail.mit.edu (xxxxxxxxx.csail.mit.edu [18.26.4.91])\\n\"\n \" (authenticated bits=0)\\n\"\n \" (User authenticated as xxxxxxxx@ATHENA.MIT.EDU)\\n\"\n \" by outgoing.mit.edu (8.13.8\/8.12.4) with ESMTP id r2K2jmc7032022\\n\"\n \" (version=TLSv1\/SSLv3 cipher=DHE-RSA-AES128-SHA bits=128 verify=NOT)\\n\"\n \" for <xxxxxxxx@mit.edu>; Tue, 19 Mar 2013 22:45:49 -0400\\n\"\n \"Received: from xxxxxxx by xxxxxxxxx.csail.mit.edu with local (Exim 4.80)\\n\"\n \" (envelope-from <xxxxxxxx@mit.edu>)\\n\"\n \" id 1UI92C-0000il-4L\\n\"\n \" for xxxxxxxx@mit.edu; Tue, 19 Mar 2013 22:45:48 -0400\\n\"\n \"From: Austin Clements <xxxxxxxx@MIT.EDU>\\n\"\n \"To: xxxxxxxx@mit.edu\\n\"\n \"Subject: Test message\\n\"\n \"User-Agent: Notmuch\/0.15+6~g7d4cb73 (http:\/\/notmuchmail.org) Emacs\/23.4.1\\n\"\n \" (i486-pc-linux-gnu)\\n\"\n \"Date: Tue, 19 Mar 2013 22:45:48 -0400\\n\"\n \"Message-ID: <874ng6vler.fsf@xxxxxxxxx.csail.mit.edu>\\n\"\n \"MIME-Version: 1.0\\n\"\n \"Content-Type: text\/plain; charset=us-ascii\\n\"\n \"\\n\"\n \"Hello.\\n\";\n\nextern char **environ;\n\nstatic spin_barrier bar;\n\nstatic concurrent_distribution<uint64_t> start_tsc, stop_tsc;\nstatic concurrent_distribution<uint64_t> start_usec, stop_usec;\nstatic concurrent_distribution<uint64_t> count;\n\nstatic volatile bool stop __mpalign__;\nstatic volatile bool warmup;\nstatic __padout__ __attribute__((unused));\n\nstatic void\ntimer_thread(void)\n{\n warmup = true;\n bar.join();\n bar.join();\n sleep(warmup_secs);\n warmup = false;\n sleep(duration);\n stop = true;\n}\n\nstatic void\nxwaitpid(int pid, const char *cmd)\n{\n int status;\n if (waitpid(pid, &status, 0) < 0)\n edie(\"waitpid %s failed\", cmd);\n if (!WIFEXITED(status) || WEXITSTATUS(status))\n die(\"status %d from %s\", status, cmd);\n}\n\nstatic void\ndo_mua(int cpu, string spooldir, string msgpath)\n{\n const char *argv[] = {\".\/mail-enqueue\", spooldir.c_str(), \"user\", nullptr};\n#if defined(XV6_USER)\n int errno;\n#endif\n setaffinity(cpu);\n\n \/\/ Open message file (alternatively, we could use an open spawn\n \/\/ action)\n int msgfd = open(msgpath.c_str(), O_RDONLY|O_CLOEXEC|O_ANYFD);\n if (msgfd < 0)\n edie(\"open %s failed\", msgpath.c_str());\n\n bool mywarmup = true;\n uint64_t mycount = 0;\n while (!stop) {\n if (__builtin_expect(warmup != mywarmup, 0)) {\n mywarmup = warmup;\n mycount = 0;\n start_usec.add(now_usec());\n start_tsc.add(rdtsc());\n }\n\n if (lseek(msgfd, 0, SEEK_SET) < 0)\n edie(\"lseek failed\");\n\n pid_t pid;\n posix_spawn_file_actions_t actions;\n if ((errno = posix_spawn_file_actions_init(&actions)))\n edie(\"posix_spawn_file_actions_init failed\");\n if ((errno = posix_spawn_file_actions_adddup2(&actions, msgfd, 0)))\n edie(\"posix_spawn_file_actions_adddup2 failed\");\n if ((errno = posix_spawn(&pid, argv[0], &actions, nullptr,\n const_cast<char *const*>(argv), environ)))\n edie(\"posix_spawn failed\");\n if ((errno = posix_spawn_file_actions_destroy(&actions)))\n edie(\"posix_spawn_file_actions_destroy failed\");\n xwaitpid(pid, argv[0]);\n\n ++mycount;\n }\n\n stop_usec.add(now_usec());\n stop_tsc.add(rdtsc());\n count.add(mycount);\n}\n\nstatic void\nxmkdir(const string &d)\n{\n if (mkdir(d.c_str(), 0777) < 0)\n edie(\"failed to mkdir %s\", d.c_str());\n}\n\nstatic void\ncreate_spool(const string &base)\n{\n xmkdir(base);\n xmkdir(base + \"\/pid\");\n xmkdir(base + \"\/todo\");\n xmkdir(base + \"\/mess\");\n}\n\nstatic void\ncreate_maildir(const string &base)\n{\n xmkdir(base);\n xmkdir(base + \"\/tmp\");\n xmkdir(base + \"\/new\");\n xmkdir(base + \"\/cur\");\n}\n\nvoid\nusage(const char *argv0)\n{\n fprintf(stderr, \"Usage: %s basedir nthreads\\n\", argv0);\n exit(2);\n}\n\nint\nmain(int argc, char **argv)\n{\n if (argc != 3)\n usage(argv[0]);\n\n string basedir(argv[1]);\n const char *nthreads_str = argv[2];\n int nthreads = atoi(nthreads_str);\n if (nthreads <= 0)\n usage(argv[0]);\n\n \/\/ Create spool and inboxes\n \/\/ XXX This terminology is wrong. The spool is where mail\n \/\/ ultimately gets delivered to.\n string spooldir = basedir + \"\/spool\";\n if (START_QMAN)\n create_spool(spooldir);\n string mailroot = basedir + \"\/mail\";\n xmkdir(mailroot);\n create_maildir(mailroot + \"\/user\");\n\n pid_t qman_pid;\n if (START_QMAN) {\n \/\/ Start queue manager\n const char *qman[] = {\".\/mail-qman\", spooldir.c_str(), mailroot.c_str(),\n nthreads_str, nullptr};\n if (posix_spawn(&qman_pid, qman[0], nullptr, nullptr,\n const_cast<char *const*>(qman), environ) != 0)\n die(\"posix_spawn %s failed\", qman[0]);\n sleep(1);\n }\n\n \/\/ Write message to a file\n int fd = open((basedir + \"\/msg\").c_str(), O_CREAT|O_WRONLY, 0666);\n if (fd < 0)\n edie(\"open\");\n xwrite(fd, message, strlen(message));\n close(fd);\n\n printf(\"# --cores=%d --duration=%ds\\n\", nthreads, duration);\n\n \/\/ Run benchmark\n bar.init(nthreads + 1);\n\n std::thread timer(timer_thread);\n\n std::thread *threads = new std::thread[nthreads];\n for (int i = 0; i < nthreads; ++i)\n threads[i] = std::thread(do_mua, i, basedir + \"\/spool\", basedir + \"\/msg\");\n\n \/\/ Wait\n timer.join();\n for (int i = 0; i < nthreads; ++i)\n threads[i].join();\n\n if (START_QMAN) {\n \/\/ Kill qman and wait for it to exit\n const char *enq[] = {\".\/mail-enqueue\", \"--exit\", spooldir.c_str(), nullptr};\n pid_t enq_pid;\n if (posix_spawn(&enq_pid, enq[0], nullptr, nullptr,\n const_cast<char *const*>(enq), environ) != 0)\n die(\"posix_spawn %s failed\", enq[0]);\n xwaitpid(enq_pid, \"mail-enqueue --exit\");\n xwaitpid(qman_pid, \"mail-qman\");\n }\n\n \/\/ Summarize\n printf(\"%lu start usec skew\\n\", start_usec.span());\n printf(\"%lu stop usec skew\\n\", stop_usec.span());\n uint64_t usec = stop_usec.mean() - start_usec.mean();\n printf(\"%f secs\\n\", (double)usec \/ 1e6);\n printf(\"%lu cycles\\n\", stop_tsc.mean() - start_tsc.mean());\n\n uint64_t iters = count.sum();\n printf(\"%lu iters\\n\", iters);\n if (iters) {\n printf(\"%lu cycles\/iter\\n\", (stop_tsc.sum() - start_tsc.sum()) \/ iters);\n printf(\"%lu iters\/sec\\n\", iters * 1000000 \/ usec);\n }\n\n printf(\"\\n\");\n}\n<commit_msg>mailbench: s\/iter\/message\/<commit_after>#include \"amd64.h\"\n#include \"distribution.hh\"\n#include \"spinbarrier.hh\"\n#include \"libutil.h\"\n#include \"xsys.h\"\n\n#include <fcntl.h>\n#include <spawn.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <unistd.h>\n#include <sys\/stat.h>\n#include <sys\/wait.h>\n\n#include <string>\n#include <thread>\n\n\/\/ Set to 1 to manage the queue manager's life time from this program.\n\/\/ Set to 0 if the queue manager is started and stopped outside of\n\/\/ mailbench.\n#define START_QMAN 1\n\nusing std::string;\n\nenum { warmup_secs = 1 };\nenum { duration = 5 };\n\nconst char *message =\n \"Received: from incoming.csail.mit.edu (incoming.csail.mit.edu [128.30.2.16])\\n\"\n \" by metroplex (Cyrus v2.2.13-Debian-2.2.13-14+lenny5) with LMTPA;\\n\"\n \" Tue, 19 Mar 2013 22:45:50 -0400\\n\"\n \"X-Sieve: CMU Sieve 2.2\\n\"\n \"Received: from mailhub-auth-3.mit.edu ([18.9.21.43])\\n\"\n \" by incoming.csail.mit.edu with esmtps\\n\"\n \" (TLS1.0:DHE_RSA_AES_256_CBC_SHA1:32)\\n\"\n \" (Exim 4.72)\\n\"\n \" (envelope-from <xxxxxxxx@MIT.EDU>)\\n\"\n \" id 1UI92E-0007D2-7N\\n\"\n \" for xxxxxxxxx@csail.mit.edu; Tue, 19 Mar 2013 22:45:50 -0400\\n\"\n \"Received: from outgoing.mit.edu (OUTGOING-AUTH-1.MIT.EDU [18.9.28.11])\\n\"\n \" by mailhub-auth-3.mit.edu (8.13.8\/8.9.2) with ESMTP id r2K2jnO5025684\\n\"\n \" for <xxxxxxxx@mit.edu>; Tue, 19 Mar 2013 22:45:49 -0400\\n\"\n \"Received: from xxxxxxxxx.csail.mit.edu (xxxxxxxxx.csail.mit.edu [18.26.4.91])\\n\"\n \" (authenticated bits=0)\\n\"\n \" (User authenticated as xxxxxxxx@ATHENA.MIT.EDU)\\n\"\n \" by outgoing.mit.edu (8.13.8\/8.12.4) with ESMTP id r2K2jmc7032022\\n\"\n \" (version=TLSv1\/SSLv3 cipher=DHE-RSA-AES128-SHA bits=128 verify=NOT)\\n\"\n \" for <xxxxxxxx@mit.edu>; Tue, 19 Mar 2013 22:45:49 -0400\\n\"\n \"Received: from xxxxxxx by xxxxxxxxx.csail.mit.edu with local (Exim 4.80)\\n\"\n \" (envelope-from <xxxxxxxx@mit.edu>)\\n\"\n \" id 1UI92C-0000il-4L\\n\"\n \" for xxxxxxxx@mit.edu; Tue, 19 Mar 2013 22:45:48 -0400\\n\"\n \"From: Austin Clements <xxxxxxxx@MIT.EDU>\\n\"\n \"To: xxxxxxxx@mit.edu\\n\"\n \"Subject: Test message\\n\"\n \"User-Agent: Notmuch\/0.15+6~g7d4cb73 (http:\/\/notmuchmail.org) Emacs\/23.4.1\\n\"\n \" (i486-pc-linux-gnu)\\n\"\n \"Date: Tue, 19 Mar 2013 22:45:48 -0400\\n\"\n \"Message-ID: <874ng6vler.fsf@xxxxxxxxx.csail.mit.edu>\\n\"\n \"MIME-Version: 1.0\\n\"\n \"Content-Type: text\/plain; charset=us-ascii\\n\"\n \"\\n\"\n \"Hello.\\n\";\n\nextern char **environ;\n\nstatic spin_barrier bar;\n\nstatic concurrent_distribution<uint64_t> start_tsc, stop_tsc;\nstatic concurrent_distribution<uint64_t> start_usec, stop_usec;\nstatic concurrent_distribution<uint64_t> count;\n\nstatic volatile bool stop __mpalign__;\nstatic volatile bool warmup;\nstatic __padout__ __attribute__((unused));\n\nstatic void\ntimer_thread(void)\n{\n warmup = true;\n bar.join();\n bar.join();\n sleep(warmup_secs);\n warmup = false;\n sleep(duration);\n stop = true;\n}\n\nstatic void\nxwaitpid(int pid, const char *cmd)\n{\n int status;\n if (waitpid(pid, &status, 0) < 0)\n edie(\"waitpid %s failed\", cmd);\n if (!WIFEXITED(status) || WEXITSTATUS(status))\n die(\"status %d from %s\", status, cmd);\n}\n\nstatic void\ndo_mua(int cpu, string spooldir, string msgpath)\n{\n const char *argv[] = {\".\/mail-enqueue\", spooldir.c_str(), \"user\", nullptr};\n#if defined(XV6_USER)\n int errno;\n#endif\n setaffinity(cpu);\n\n \/\/ Open message file (alternatively, we could use an open spawn\n \/\/ action)\n int msgfd = open(msgpath.c_str(), O_RDONLY|O_CLOEXEC|O_ANYFD);\n if (msgfd < 0)\n edie(\"open %s failed\", msgpath.c_str());\n\n bool mywarmup = true;\n uint64_t mycount = 0;\n while (!stop) {\n if (__builtin_expect(warmup != mywarmup, 0)) {\n mywarmup = warmup;\n mycount = 0;\n start_usec.add(now_usec());\n start_tsc.add(rdtsc());\n }\n\n if (lseek(msgfd, 0, SEEK_SET) < 0)\n edie(\"lseek failed\");\n\n pid_t pid;\n posix_spawn_file_actions_t actions;\n if ((errno = posix_spawn_file_actions_init(&actions)))\n edie(\"posix_spawn_file_actions_init failed\");\n if ((errno = posix_spawn_file_actions_adddup2(&actions, msgfd, 0)))\n edie(\"posix_spawn_file_actions_adddup2 failed\");\n if ((errno = posix_spawn(&pid, argv[0], &actions, nullptr,\n const_cast<char *const*>(argv), environ)))\n edie(\"posix_spawn failed\");\n if ((errno = posix_spawn_file_actions_destroy(&actions)))\n edie(\"posix_spawn_file_actions_destroy failed\");\n xwaitpid(pid, argv[0]);\n\n ++mycount;\n }\n\n stop_usec.add(now_usec());\n stop_tsc.add(rdtsc());\n count.add(mycount);\n}\n\nstatic void\nxmkdir(const string &d)\n{\n if (mkdir(d.c_str(), 0777) < 0)\n edie(\"failed to mkdir %s\", d.c_str());\n}\n\nstatic void\ncreate_spool(const string &base)\n{\n xmkdir(base);\n xmkdir(base + \"\/pid\");\n xmkdir(base + \"\/todo\");\n xmkdir(base + \"\/mess\");\n}\n\nstatic void\ncreate_maildir(const string &base)\n{\n xmkdir(base);\n xmkdir(base + \"\/tmp\");\n xmkdir(base + \"\/new\");\n xmkdir(base + \"\/cur\");\n}\n\nvoid\nusage(const char *argv0)\n{\n fprintf(stderr, \"Usage: %s basedir nthreads\\n\", argv0);\n exit(2);\n}\n\nint\nmain(int argc, char **argv)\n{\n if (argc != 3)\n usage(argv[0]);\n\n string basedir(argv[1]);\n const char *nthreads_str = argv[2];\n int nthreads = atoi(nthreads_str);\n if (nthreads <= 0)\n usage(argv[0]);\n\n \/\/ Create spool and inboxes\n \/\/ XXX This terminology is wrong. The spool is where mail\n \/\/ ultimately gets delivered to.\n string spooldir = basedir + \"\/spool\";\n if (START_QMAN)\n create_spool(spooldir);\n string mailroot = basedir + \"\/mail\";\n xmkdir(mailroot);\n create_maildir(mailroot + \"\/user\");\n\n pid_t qman_pid;\n if (START_QMAN) {\n \/\/ Start queue manager\n const char *qman[] = {\".\/mail-qman\", spooldir.c_str(), mailroot.c_str(),\n nthreads_str, nullptr};\n if (posix_spawn(&qman_pid, qman[0], nullptr, nullptr,\n const_cast<char *const*>(qman), environ) != 0)\n die(\"posix_spawn %s failed\", qman[0]);\n sleep(1);\n }\n\n \/\/ Write message to a file\n int fd = open((basedir + \"\/msg\").c_str(), O_CREAT|O_WRONLY, 0666);\n if (fd < 0)\n edie(\"open\");\n xwrite(fd, message, strlen(message));\n close(fd);\n\n printf(\"# --cores=%d --duration=%ds\\n\", nthreads, duration);\n\n \/\/ Run benchmark\n bar.init(nthreads + 1);\n\n std::thread timer(timer_thread);\n\n std::thread *threads = new std::thread[nthreads];\n for (int i = 0; i < nthreads; ++i)\n threads[i] = std::thread(do_mua, i, basedir + \"\/spool\", basedir + \"\/msg\");\n\n \/\/ Wait\n timer.join();\n for (int i = 0; i < nthreads; ++i)\n threads[i].join();\n\n if (START_QMAN) {\n \/\/ Kill qman and wait for it to exit\n const char *enq[] = {\".\/mail-enqueue\", \"--exit\", spooldir.c_str(), nullptr};\n pid_t enq_pid;\n if (posix_spawn(&enq_pid, enq[0], nullptr, nullptr,\n const_cast<char *const*>(enq), environ) != 0)\n die(\"posix_spawn %s failed\", enq[0]);\n xwaitpid(enq_pid, \"mail-enqueue --exit\");\n xwaitpid(qman_pid, \"mail-qman\");\n }\n\n \/\/ Summarize\n printf(\"%lu start usec skew\\n\", start_usec.span());\n printf(\"%lu stop usec skew\\n\", stop_usec.span());\n uint64_t usec = stop_usec.mean() - start_usec.mean();\n printf(\"%f secs\\n\", (double)usec \/ 1e6);\n printf(\"%lu cycles\\n\", stop_tsc.mean() - start_tsc.mean());\n\n uint64_t messages = count.sum();\n printf(\"%lu messages\\n\", messages);\n if (messages) {\n printf(\"%lu cycles\/message\\n\",\n (stop_tsc.sum() - start_tsc.sum()) \/ messages);\n printf(\"%lu messages\/sec\\n\", messages * 1000000 \/ usec);\n }\n\n printf(\"\\n\");\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"mainwindow.h\"\n#include \"ui_mainwindow.h\"\n#include <QMessageBox>\n#include <iostream>\n#include <QCloseEvent>\n#include <QColorDialog>\n#include <chrono>\n#include <thread>\n#include \"icononbuttonhandler.h\"\n#include \"inputwindow.h\"\n#include \"Video\/shapes\/shape.h\"\n\nusing namespace std;\nusing namespace cv;\n\n\/**\n * @brief MainWindow::MainWindow\n * Constructor\n * @param parent a QWidget variable\n *\/\nMainWindow::MainWindow(QWidget *parent) :\n QMainWindow(parent),\n ui(new Ui::MainWindow){\n ui->setupUi(this);\n\n this->selectedProject = nullptr;\n this->selectedVideo = nullptr;\n\n video_slider = findChild<QSlider*>(\"videoSlider\");\n iconOnButtonHandler = new IconOnButtonHandler();\n iconOnButtonHandler->set_pictures_to_buttons(ui);\n\n fileHandler = new FileHandler();\n set_shortcuts();\n\n \/\/ Add this object as a listener to videoFrame.\n ui->videoFrame->installEventFilter(this);\n\n ui->ProjectTree->setContextMenuPolicy(Qt::CustomContextMenu);\n connect(ui->ProjectTree, &QTreeWidget::customContextMenuRequested, this, &MainWindow::prepare_menu);\n\n mvideo_player = new video_player();\n QObject::connect(mvideo_player, SIGNAL(processedImage(QImage)),\n this, SLOT(update_video(QImage)));\n QObject::connect(mvideo_player, SIGNAL(currentFrame(int)),\n this, SLOT(set_video_slider_pos(int)));\n\n \/\/Used for rescaling the source image for video playback\n mvideo_player->set_frame_height(ui->videoFrame->height());\n mvideo_player->set_frame_width(ui->videoFrame->width());\n}\n\n\/**\n * @brief MainWindow::~MainWindow\n * Destructor\n *\/\n\nMainWindow::~MainWindow() {\n\n delete iconOnButtonHandler;\n delete fileHandler;\n delete mvideo_player;\n delete ui;\n}\n\n\/**\n * @brief MainWindow::set_shortcuts\n * Function to set shortcuts on actions\n *\/\nvoid MainWindow::set_shortcuts(){\n ui->actionExit->setShortcut(tr(\"Ctrl+e\"));\n}\n\n\/**\n * @brief MainWindow::set_status_bar\n * @param status text to show in the statusbar\n * @param timer time to show it in the bar in ms, 750ms is standard\n *\/\nvoid MainWindow::set_status_bar(string status, int timer){\n ui->statusBar->showMessage(QString::fromStdString(status), timer);\n}\n\n\/**\n * @brief MainWindow::on_fastBackwardButton_clicked\n * The button supposed to play the video slower\n *\n *\/\nvoid MainWindow::on_fastBackwardButton_clicked(){\n\n}\n\n\n\/**\n * @brief MainWindow::on_playPauseButton_clicked\n * The button supposed to play and pause the video\n *\/\nvoid MainWindow::on_playPauseButton_clicked() {\n if (mvideo_player->is_paused() || mvideo_player->is_stopped()) {\n set_status_bar(\"Playing\");\n iconOnButtonHandler->set_icon(\"pause\", ui->playPauseButton);\/\/changes the icon on the play button to a pause-icon\n mvideo_player->start();\n } else {\n set_status_bar(\"Paused\");\n iconOnButtonHandler->set_icon(\"play\", ui->playPauseButton);\n mvideo_player->play_pause();\n mvideo_player->wait();\n }\n}\n\n\n\/**\n * @brief MainWindow::on_fastForwardButton_clicked\n * The button supposed to play the video faster\n *\/\nvoid MainWindow::on_fastForwardButton_clicked(){\n\n}\n\n\/**\n * @brief MainWindow::on_stopButton_clicked\n * The button supposed to stop the video\n *\/\nvoid MainWindow::on_stopButton_clicked() {\n set_status_bar(\"Stopped\");\n if (!mvideo_player->is_paused()) {\n iconOnButtonHandler->set_icon(\"play\", ui->playPauseButton);\n }\n\n mvideo_player->stop_video();\n}\n\n\/**\n * @brief MainWindow::on_nextFrameButton_clicked\n * The button supposed to play the next frame of the video\n *\/\nvoid MainWindow::on_nextFrameButton_clicked() {\n if (mvideo_player->is_paused()) {\n set_status_bar(\"Went forward a frame\");\n mvideo_player->next_frame();\n } else {\n set_status_bar(\"Needs to be paused\");\n }\n}\n\n\/**\n * @brief MainWindow::on_previousFrameButton_clicked\n * The button supposed to play the previous frame of the video\n *\/\nvoid MainWindow::on_previousFrameButton_clicked() {\n if (mvideo_player->is_paused()) {\n set_status_bar(\"Went back a frame\");\n mvideo_player->previous_frame();\n } else {\n set_status_bar(\"Needs to be paused\");\n }\n}\n\n\/**\n * @brief MainWindow::update_video\n * Sets the videoFrame pixmap to the current frame from video\n * @param frame\n *\/\nvoid MainWindow::update_video(QImage frame) {\n ui->videoFrame->setPixmap(QPixmap::fromImage(frame));\n}\n\n\/**\n * @brief MainWindow::set_video_slider_pos\n * Sets the position of slider in video to position pos\n * @param pos\n *\/\nvoid MainWindow::set_video_slider_pos(int pos) {\n if (pos <= video_slider->maximum()) {\n video_slider->setSliderPosition(pos);\n }\n}\n\n\/**\n * @brief MainWindow::resizeEvent\n * Used for rescaling the source image for video playback\n * @param event\n *\/\nvoid MainWindow::resizeEvent(QResizeEvent* event) {\n QMainWindow::resizeEvent(event);\n mvideo_player->set_frame_height(ui->videoFrame->height());\n mvideo_player->set_frame_width(ui->videoFrame->width());\n}\n\n\/**\n * @brief MainWindow::on_videoSlider_valueChanged\n * Update the slider to where the mouse is\n * @param newPos current position of the slider\n *\/\nvoid MainWindow::on_videoSlider_valueChanged(int newPos){\n \/\/ Make slider to follow the mouse directly and not by pageStep steps\n Qt::MouseButtons btns = QApplication::mouseButtons();\n QPoint localMousePos = ui->videoSlider->mapFromGlobal(QCursor::pos());\n bool clickOnSlider = (btns & Qt::LeftButton) &&\n (localMousePos.x() >= 0 && localMousePos.y() >= 0 &&\n localMousePos.x() < ui->videoSlider->size().width() &&\n localMousePos.y() < ui->videoSlider->size().height());\n if (clickOnSlider)\n {\n \/\/ Attention! The following works only for Horizontal, Left-to-right sliders\n float posRatio = localMousePos.x() \/ (float )ui->videoSlider->size().width();\n int sliderRange = ui->videoSlider->maximum() - ui->videoSlider->minimum();\n int sliderPosUnderMouse = ui->videoSlider->minimum() + sliderRange * posRatio;\n if (sliderPosUnderMouse != newPos)\n {\n ui->videoSlider->setValue(sliderPosUnderMouse);\n return;\n }\n }\n}\n\/**\n * @brief MainWindow::closeEvent\n * asks if you are sure you want to quit.\n * @param event closing\n *\/\nvoid MainWindow::closeEvent (QCloseEvent *event){\n set_status_bar(\"Closing\");\n QMessageBox::StandardButton resBtn = QMessageBox::question( this, \"Exit\",\n tr(\"Are you sure you want to quit?\\n\"),\n QMessageBox::No | QMessageBox::Yes,\n QMessageBox::No);\n\n if (resBtn != QMessageBox::Yes) {\n event->ignore();\n } else {\n event->accept();\n }\n}\n\/**\n * @brief MainWindow::on_actionExit_triggered\n * sends a closeEvent when you press exit\n *\/\nvoid MainWindow::on_actionExit_triggered(){\n this->close();\n}\n\n\/**\n * @brief MainWindow::on_bookmarkButton_clicked\n * the button supposed to add a bookmark\n *\/\nvoid MainWindow::on_bookmarkButton_clicked(){\n}\n\n\/**\n * @brief MainWindow::on_actionAddProject_triggered\n *\/\nvoid MainWindow::on_actionAddProject_triggered() {\n ACTION action = ADD_PROJECT;\n inputWindow = new inputwindow(this, action, \"Project name:\");\n inputWindow->show();\n set_status_bar(\"Adding project, need name\");\n}\n\n\/**\n * @brief MainWindow::inputSwitchCase\n * @param input the input from the user\n * @param action the action that was triggered earlier\n *\/\nvoid MainWindow::input_switch_case(ACTION action, QString qInput) {\n std::string input = qInput.toStdString();\n switch(action){\n case ADD_PROJECT: {\n int id = fileHandler->create_project(input)->m_id;\n MyQTreeWidgetItem *projectInTree = new MyQTreeWidgetItem(TYPE::PROJECT, qInput, id);\n projectInTree->setText(0, qInput);\n selectedProject = projectInTree;\n ui->ProjectTree->addTopLevelItem(projectInTree);\n set_status_bar(\"Project \" + input + \" created.\");\n delete inputWindow;\n break;\n }\n case CANCEL: {\n set_status_bar(\"Cancel\");\n break;\n }\n case ADD_VIDEO: {\n fileHandler->add_video(fileHandler->get_project(selectedProject->id), input);\n MyQTreeWidgetItem *videoInTree = new MyQTreeWidgetItem(TYPE::VIDEO, qInput);\n videoInTree->setText(0, qInput);\n selectedProject->addChild(videoInTree);\n set_status_bar(\"Video \" + input + \" added.\");\n break;\n }\n default:\n break;\n\n }\n}\n\/**\n * @brief MainWindow::on_ProjectTree_itemClicked\n * @param item the item in the projectTree that was clicked\n * @param column the column in the tree\n *\/\nvoid MainWindow::on_ProjectTree_itemClicked(QTreeWidgetItem *item, int column) {\n MyQTreeWidgetItem *newitem = (MyQTreeWidgetItem*)item;\n std::cout << newitem->id << std::endl;\n}\n\n \/** @brief MainWindow::on_actionShow_hide_overview_triggered\n * Toggles the showing\/hiding of the overlay.\n * Invoked by menu item.\n *\/\nvoid MainWindow::on_actionShow_hide_overview_triggered() {\n mvideo_player->toggle_overlay();\n if (mvideo_player->is_showing_overlay()) {\n set_status_bar(\"Overlay: On.\");\n } else {\n set_status_bar(\"Overlay: Off.\");\n }\n}\n\n\/**\n * @brief MainWindow::on_actionColour_triggered\n * Selects a colour for the overlay drawing tool.\n *\/\nvoid MainWindow::on_actionColour_triggered() {\n QColor col = QColorDialog::getColor();\n mvideo_player->set_overlay_colour(col);\n string msg = \"Color: \";\n msg.append(col.name().toStdString());\n set_status_bar(msg);\n}\n\n\/**\n * @brief MainWindow::on_actionRectangle_triggered\n * Selects the rectangle shape for the overlay drawing tool.\n *\/\nvoid MainWindow::on_actionRectangle_triggered() {\n mvideo_player->set_overlay_tool(RECTANGLE);\n set_status_bar(\"Tool: rectangle.\");\n}\n\n\/**\n * @brief MainWindow::on_actionCircle_triggered\n * Selects the circle shape for the overlay drawing tool.\n *\/\nvoid MainWindow::on_actionCircle_triggered() {\n mvideo_player->set_overlay_tool(CIRCLE);\n set_status_bar(\"Tool: circle.\");\n}\n\n\/**\n * @brief MainWindow::on_actionLine_triggered\n * Selects the line shape for the overlay drawing tool.\n *\/\nvoid MainWindow::on_actionLine_triggered() {\n mvideo_player->set_overlay_tool(LINE);\n set_status_bar(\"Tool: line.\");\n}\n\n\/**\n * @brief MainWindow::on_actionArrow_triggered\n * Selects the arrow shape for the overlay drawing tool.\n *\/\nvoid MainWindow::on_actionArrow_triggered() {\n mvideo_player->set_overlay_tool(ARROW);\n set_status_bar(\"Tool: arrow.\");\n}\n\n\/**\n * @brief MainWindow::on_actionPen_triggered\n * Selects the pen for the overlay drawing tool.\n *\/\nvoid MainWindow::on_actionPen_triggered() {\n mvideo_player->set_overlay_tool(PEN);\n set_status_bar(\"Tool: pen.\");\n}\n\n\/**\n * @brief MainWindow::eventFilter\n * Listener function for all eventFilters MainWindow has installed.\n * @param obj the object invoking the event\n * @param event the invooked event\n * @return Returns true if the event matched any of the overlay's\n * functionality, else false.\n * (Returning false means that the event is sent to the\n * target object instead, but not if true is returned.)\n *\/\nbool MainWindow::eventFilter(QObject *obj, QEvent *event) {\n \/\/ Check who invoked the event.\n if (qobject_cast<QLabel*>(obj)==ui->videoFrame) {\n \/\/ Cast to a mouse event to get the mouse position.\n QMouseEvent *mouseEvent = static_cast<QMouseEvent*>(event);\n QPoint pos = mouseEvent->pos();\n \/\/ Check what kind of event.\n if (event->type() == QEvent::MouseButtonPress) {\n mvideo_player->video_mouse_pressed(pos);\n return true;\n } else if (event->type() == QEvent::MouseButtonRelease) {\n mvideo_player->video_mouse_released(pos);\n return true;\n } else if (event->type() == QEvent::MouseMove) {\n mvideo_player->video_mouse_moved(pos);\n return true;\n }\n }\n return false;\n}\n\/**\n * @brief MainWindow::prepare_menu\n * @param pos\n * Creates context menu on right-click in tree view\n *\/\nvoid MainWindow::prepare_menu(const QPoint & pos) {\n QTreeWidget *tree = ui->ProjectTree;\n\n MyQTreeWidgetItem *item = (MyQTreeWidgetItem*)tree->itemAt( pos );\n\n QMenu menu(this);\n\n if(item == nullptr) {\n\n } else if(item->type == TYPE::PROJECT) {\n selectedProject = item;\n QAction *addVideo = new QAction(QIcon(\"\"), tr(\"&Add video\"), this);\n addVideo->setStatusTip(tr(\"Add video\"));\n menu.addAction(addVideo);\n connect(addVideo, SIGNAL(triggered()), this, SLOT(add_video()));\n } else if(item->type == TYPE::VIDEO) {\n selectedVideo = item;\n QAction *loadVideo = new QAction(QIcon(\"\"), tr(\"&Play video\"), this);\n loadVideo->setStatusTip(tr(\"Play video\"));\n menu.addAction(loadVideo);\n connect(loadVideo, SIGNAL(triggered()), this, SLOT(play_video()));\n }\n\n\n\n QPoint pt(pos);\n menu.exec( tree->mapToGlobal(pos) );\n}\n\/**\n * @brief MainWindow::add_video\n * Prompts user with file browser to add video\n * to selected project\n *\/\nvoid MainWindow::add_video() {\n QString dir = QFileDialog::getOpenFileName(this, tr(\"Choose video\"),WORKSPACE,tr(\"*.avi;;*.mkv;;*.mov;;*.mp4\"));\n input_switch_case(ACTION::ADD_VIDEO, dir);\n}\n\/**\n * @brief MainWindow::play_video\n * Loads selected video, flips playbutton to pause\n * plays video from beginning\n *\n *\/\nvoid MainWindow::play_video() {\n mvideo_player->load_video(selectedVideo->name.toStdString());\n iconOnButtonHandler->set_icon(\"pause\", ui->playPauseButton);\n video_slider->setMaximum(mvideo_player->get_num_frames());\n mvideo_player->set_playback_frame(0);\n}\n\/**\n * @todo To be implemented\n * @brief MainWindow::set_selected_project\n * @param newSelectedProject\n *\/\nvoid MainWindow::set_selected_project(MyQTreeWidgetItem *newSelectedProject){\n \/*if(selectedProject) {\n std::cout << \"1\" << std::endl;\n selectedProject = newSelectedProject;\n std::cout << \"2\" << std::endl;\n QString string = selectedProject->text(0);\n std::cout << \"3\" << std::endl;\n string.append(\" <--\");\n std::cout << \"4\" << std::endl;\n selectedProject->setText(0, string);\n std::cout << \"5\" << std::endl;\n } else if (selectedProject != newSelectedProject) {\n QString string = selectedProject->text(0);\n string.chop(4);\n selectedProject->setText(0, string);\n selectedProject = newSelectedProject;\n string = selectedProject->text(0);\n string.append(\" <--\");\n selectedProject->setText(0, string);\n }*\/\n selectedProject = newSelectedProject;\n}\n\/**\n * @brief MainWindow::on_actionSave_triggered\n * saves project which is selected in tree view,\n * checks if there is one\n *\/\nvoid MainWindow::on_actionSave_triggered()\n{\n if(selectedProject != nullptr) {\n this->fileHandler->save_project(this->selectedProject->id);\n std::string text = \"Saved project \" + this->selectedProject->name.toStdString();\n set_status_bar(text);\n } else {\n set_status_bar(\"Nothing to save\");\n }\n}\n<commit_msg>Fixed outcommented code<commit_after>#include \"mainwindow.h\"\n#include \"ui_mainwindow.h\"\n#include <QMessageBox>\n#include <iostream>\n#include <QCloseEvent>\n#include <QColorDialog>\n#include <chrono>\n#include <thread>\n#include \"icononbuttonhandler.h\"\n#include \"inputwindow.h\"\n#include \"Video\/shapes\/shape.h\"\n\nusing namespace std;\nusing namespace cv;\n\n\/**\n * @brief MainWindow::MainWindow\n * Constructor\n * @param parent a QWidget variable\n *\/\nMainWindow::MainWindow(QWidget *parent) :\n QMainWindow(parent),\n ui(new Ui::MainWindow){\n ui->setupUi(this);\n\n this->selectedProject = nullptr;\n this->selectedVideo = nullptr;\n\n video_slider = findChild<QSlider*>(\"videoSlider\");\n iconOnButtonHandler = new IconOnButtonHandler();\n iconOnButtonHandler->set_pictures_to_buttons(ui);\n\n fileHandler = new FileHandler();\n set_shortcuts();\n\n \/\/ Add this object as a listener to videoFrame.\n ui->videoFrame->installEventFilter(this);\n\n ui->ProjectTree->setContextMenuPolicy(Qt::CustomContextMenu);\n connect(ui->ProjectTree, &QTreeWidget::customContextMenuRequested, this, &MainWindow::prepare_menu);\n\n mvideo_player = new video_player();\n QObject::connect(mvideo_player, SIGNAL(processedImage(QImage)),\n this, SLOT(update_video(QImage)));\n QObject::connect(mvideo_player, SIGNAL(currentFrame(int)),\n this, SLOT(set_video_slider_pos(int)));\n\n \/\/Used for rescaling the source image for video playback\n mvideo_player->set_frame_height(ui->videoFrame->height());\n mvideo_player->set_frame_width(ui->videoFrame->width());\n}\n\n\/**\n * @brief MainWindow::~MainWindow\n * Destructor\n *\/\n\nMainWindow::~MainWindow() {\n\n delete iconOnButtonHandler;\n delete fileHandler;\n delete mvideo_player;\n delete ui;\n}\n\n\/**\n * @brief MainWindow::set_shortcuts\n * Function to set shortcuts on actions\n *\/\nvoid MainWindow::set_shortcuts(){\n ui->actionExit->setShortcut(tr(\"Ctrl+e\"));\n}\n\n\/**\n * @brief MainWindow::set_status_bar\n * @param status text to show in the statusbar\n * @param timer time to show it in the bar in ms, 750ms is standard\n *\/\nvoid MainWindow::set_status_bar(string status, int timer){\n ui->statusBar->showMessage(QString::fromStdString(status), timer);\n}\n\n\/**\n * @brief MainWindow::on_fastBackwardButton_clicked\n * The button supposed to play the video slower\n *\n *\/\nvoid MainWindow::on_fastBackwardButton_clicked(){\n\n}\n\n\n\/**\n * @brief MainWindow::on_playPauseButton_clicked\n * The button supposed to play and pause the video\n *\/\nvoid MainWindow::on_playPauseButton_clicked() {\n if (mvideo_player->is_paused() || mvideo_player->is_stopped()) {\n set_status_bar(\"Playing\");\n iconOnButtonHandler->set_icon(\"pause\", ui->playPauseButton);\/\/changes the icon on the play button to a pause-icon\n mvideo_player->start();\n } else {\n set_status_bar(\"Paused\");\n iconOnButtonHandler->set_icon(\"play\", ui->playPauseButton);\n mvideo_player->play_pause();\n mvideo_player->wait();\n }\n}\n\n\n\/**\n * @brief MainWindow::on_fastForwardButton_clicked\n * The button supposed to play the video faster\n *\/\nvoid MainWindow::on_fastForwardButton_clicked(){\n\n}\n\n\/**\n * @brief MainWindow::on_stopButton_clicked\n * The button supposed to stop the video\n *\/\nvoid MainWindow::on_stopButton_clicked() {\n set_status_bar(\"Stopped\");\n if (!mvideo_player->is_paused()) {\n iconOnButtonHandler->set_icon(\"play\", ui->playPauseButton);\n }\n\n mvideo_player->stop_video();\n}\n\n\/**\n * @brief MainWindow::on_nextFrameButton_clicked\n * The button supposed to play the next frame of the video\n *\/\nvoid MainWindow::on_nextFrameButton_clicked() {\n if (mvideo_player->is_paused()) {\n set_status_bar(\"Went forward a frame\");\n mvideo_player->next_frame();\n } else {\n set_status_bar(\"Needs to be paused\");\n }\n}\n\n\/**\n * @brief MainWindow::on_previousFrameButton_clicked\n * The button supposed to play the previous frame of the video\n *\/\nvoid MainWindow::on_previousFrameButton_clicked() {\n if (mvideo_player->is_paused()) {\n set_status_bar(\"Went back a frame\");\n mvideo_player->previous_frame();\n } else {\n set_status_bar(\"Needs to be paused\");\n }\n}\n\n\/**\n * @brief MainWindow::update_video\n * Sets the videoFrame pixmap to the current frame from video\n * @param frame\n *\/\nvoid MainWindow::update_video(QImage frame) {\n ui->videoFrame->setPixmap(QPixmap::fromImage(frame));\n}\n\n\/**\n * @brief MainWindow::set_video_slider_pos\n * Sets the position of slider in video to position pos\n * @param pos\n *\/\nvoid MainWindow::set_video_slider_pos(int pos) {\n if (pos <= video_slider->maximum()) {\n video_slider->setSliderPosition(pos);\n }\n}\n\n\/**\n * @brief MainWindow::resizeEvent\n * Used for rescaling the source image for video playback\n * @param event\n *\/\nvoid MainWindow::resizeEvent(QResizeEvent* event) {\n QMainWindow::resizeEvent(event);\n mvideo_player->set_frame_height(ui->videoFrame->height());\n mvideo_player->set_frame_width(ui->videoFrame->width());\n}\n\n\/**\n * @brief MainWindow::on_videoSlider_valueChanged\n * Update the slider to where the mouse is\n * @param newPos current position of the slider\n *\/\nvoid MainWindow::on_videoSlider_valueChanged(int newPos){\n \/\/ Make slider to follow the mouse directly and not by pageStep steps\n Qt::MouseButtons btns = QApplication::mouseButtons();\n QPoint localMousePos = ui->videoSlider->mapFromGlobal(QCursor::pos());\n bool clickOnSlider = (btns & Qt::LeftButton) &&\n (localMousePos.x() >= 0 && localMousePos.y() >= 0 &&\n localMousePos.x() < ui->videoSlider->size().width() &&\n localMousePos.y() < ui->videoSlider->size().height());\n if (clickOnSlider)\n {\n \/\/ Attention! The following works only for Horizontal, Left-to-right sliders\n float posRatio = localMousePos.x() \/ (float )ui->videoSlider->size().width();\n int sliderRange = ui->videoSlider->maximum() - ui->videoSlider->minimum();\n int sliderPosUnderMouse = ui->videoSlider->minimum() + sliderRange * posRatio;\n if (sliderPosUnderMouse != newPos)\n {\n ui->videoSlider->setValue(sliderPosUnderMouse);\n return;\n }\n }\n}\n\/**\n * @brief MainWindow::closeEvent\n * asks if you are sure you want to quit.\n * @param event closing\n *\/\nvoid MainWindow::closeEvent (QCloseEvent *event){\n set_status_bar(\"Closing\");\n QMessageBox::StandardButton resBtn = QMessageBox::question( this, \"Exit\",\n tr(\"Are you sure you want to quit?\\n\"),\n QMessageBox::No | QMessageBox::Yes,\n QMessageBox::No);\n\n if (resBtn != QMessageBox::Yes) {\n event->ignore();\n } else {\n event->accept();\n }\n}\n\/**\n * @brief MainWindow::on_actionExit_triggered\n * sends a closeEvent when you press exit\n *\/\nvoid MainWindow::on_actionExit_triggered(){\n this->close();\n}\n\n\/**\n * @brief MainWindow::on_bookmarkButton_clicked\n * the button supposed to add a bookmark\n *\/\nvoid MainWindow::on_bookmarkButton_clicked(){\n}\n\n\/**\n * @brief MainWindow::on_actionAddProject_triggered\n *\/\nvoid MainWindow::on_actionAddProject_triggered() {\n ACTION action = ADD_PROJECT;\n inputWindow = new inputwindow(this, action, \"Project name:\");\n inputWindow->show();\n set_status_bar(\"Adding project, need name\");\n}\n\n\/**\n * @brief MainWindow::inputSwitchCase\n * @param input the input from the user\n * @param action the action that was triggered earlier\n *\/\nvoid MainWindow::input_switch_case(ACTION action, QString qInput) {\n std::string input = qInput.toStdString();\n switch(action){\n case ADD_PROJECT: {\n int id = fileHandler->create_project(input)->m_id;\n MyQTreeWidgetItem *projectInTree = new MyQTreeWidgetItem(TYPE::PROJECT, qInput, id);\n projectInTree->setText(0, qInput);\n selectedProject = projectInTree;\n ui->ProjectTree->addTopLevelItem(projectInTree);\n set_status_bar(\"Project \" + input + \" created.\");\n delete inputWindow;\n break;\n }\n case CANCEL: {\n set_status_bar(\"Cancel\");\n break;\n }\n case ADD_VIDEO: {\n fileHandler->add_video(fileHandler->get_project(selectedProject->id), input);\n MyQTreeWidgetItem *videoInTree = new MyQTreeWidgetItem(TYPE::VIDEO, qInput);\n videoInTree->setText(0, qInput);\n selectedProject->addChild(videoInTree);\n set_status_bar(\"Video \" + input + \" added.\");\n break;\n }\n default:\n break;\n\n }\n}\n\/**\n * @brief MainWindow::on_ProjectTree_itemClicked\n * @param item the item in the projectTree that was clicked\n * @param column the column in the tree\n *\/\nvoid MainWindow::on_ProjectTree_itemClicked(QTreeWidgetItem *item, int column) {\n MyQTreeWidgetItem *newitem = (MyQTreeWidgetItem*)item;\n std::cout << newitem->id << std::endl;\n}\n\n \/** @brief MainWindow::on_actionShow_hide_overview_triggered\n * Toggles the showing\/hiding of the overlay.\n * Invoked by menu item.\n *\/\nvoid MainWindow::on_actionShow_hide_overview_triggered() {\n mvideo_player->toggle_overlay();\n if (mvideo_player->is_showing_overlay()) {\n set_status_bar(\"Overlay: On.\");\n } else {\n set_status_bar(\"Overlay: Off.\");\n }\n}\n\n\/**\n * @brief MainWindow::on_actionColour_triggered\n * Selects a colour for the overlay drawing tool.\n *\/\nvoid MainWindow::on_actionColour_triggered() {\n QColor col = QColorDialog::getColor();\n mvideo_player->set_overlay_colour(col);\n string msg = \"Color: \";\n msg.append(col.name().toStdString());\n set_status_bar(msg);\n}\n\n\/**\n * @brief MainWindow::on_actionRectangle_triggered\n * Selects the rectangle shape for the overlay drawing tool.\n *\/\nvoid MainWindow::on_actionRectangle_triggered() {\n mvideo_player->set_overlay_tool(RECTANGLE);\n set_status_bar(\"Tool: rectangle.\");\n}\n\n\/**\n * @brief MainWindow::on_actionCircle_triggered\n * Selects the circle shape for the overlay drawing tool.\n *\/\nvoid MainWindow::on_actionCircle_triggered() {\n mvideo_player->set_overlay_tool(CIRCLE);\n set_status_bar(\"Tool: circle.\");\n}\n\n\/**\n * @brief MainWindow::on_actionLine_triggered\n * Selects the line shape for the overlay drawing tool.\n *\/\nvoid MainWindow::on_actionLine_triggered() {\n mvideo_player->set_overlay_tool(LINE);\n set_status_bar(\"Tool: line.\");\n}\n\n\/**\n * @brief MainWindow::on_actionArrow_triggered\n * Selects the arrow shape for the overlay drawing tool.\n *\/\nvoid MainWindow::on_actionArrow_triggered() {\n mvideo_player->set_overlay_tool(ARROW);\n set_status_bar(\"Tool: arrow.\");\n}\n\n\/**\n * @brief MainWindow::on_actionPen_triggered\n * Selects the pen for the overlay drawing tool.\n *\/\nvoid MainWindow::on_actionPen_triggered() {\n mvideo_player->set_overlay_tool(PEN);\n set_status_bar(\"Tool: pen.\");\n}\n\n\/**\n * @brief MainWindow::eventFilter\n * Listener function for all eventFilters MainWindow has installed.\n * @param obj the object invoking the event\n * @param event the invooked event\n * @return Returns true if the event matched any of the overlay's\n * functionality, else false.\n * (Returning false means that the event is sent to the\n * target object instead, but not if true is returned.)\n *\/\nbool MainWindow::eventFilter(QObject *obj, QEvent *event) {\n \/\/ Check who invoked the event.\n if (qobject_cast<QLabel*>(obj)==ui->videoFrame) {\n \/\/ Cast to a mouse event to get the mouse position.\n QMouseEvent *mouseEvent = static_cast<QMouseEvent*>(event);\n QPoint pos = mouseEvent->pos();\n \/\/ Check what kind of event.\n if (event->type() == QEvent::MouseButtonPress) {\n mvideo_player->video_mouse_pressed(pos);\n return true;\n } else if (event->type() == QEvent::MouseButtonRelease) {\n mvideo_player->video_mouse_released(pos);\n return true;\n } else if (event->type() == QEvent::MouseMove) {\n mvideo_player->video_mouse_moved(pos);\n return true;\n }\n }\n return false;\n}\n\/**\n * @brief MainWindow::prepare_menu\n * @param pos\n * Creates context menu on right-click in tree view\n *\/\nvoid MainWindow::prepare_menu(const QPoint & pos) {\n QTreeWidget *tree = ui->ProjectTree;\n\n MyQTreeWidgetItem *item = (MyQTreeWidgetItem*)tree->itemAt( pos );\n\n QMenu menu(this);\n\n if(item == nullptr) {\n\n } else if(item->type == TYPE::PROJECT) {\n selectedProject = item;\n QAction *addVideo = new QAction(QIcon(\"\"), tr(\"&Add video\"), this);\n addVideo->setStatusTip(tr(\"Add video\"));\n menu.addAction(addVideo);\n connect(addVideo, SIGNAL(triggered()), this, SLOT(add_video()));\n } else if(item->type == TYPE::VIDEO) {\n selectedVideo = item;\n QAction *loadVideo = new QAction(QIcon(\"\"), tr(\"&Play video\"), this);\n loadVideo->setStatusTip(tr(\"Play video\"));\n menu.addAction(loadVideo);\n connect(loadVideo, SIGNAL(triggered()), this, SLOT(play_video()));\n }\n\n\n\n QPoint pt(pos);\n menu.exec( tree->mapToGlobal(pos) );\n}\n\/**\n * @brief MainWindow::add_video\n * Prompts user with file browser to add video\n * to selected project\n *\/\nvoid MainWindow::add_video() {\n QString dir = QFileDialog::getOpenFileName(this, tr(\"Choose video\"),WORKSPACE,tr(\"*.avi;;*.mkv;;*.mov;;*.mp4\"));\n input_switch_case(ACTION::ADD_VIDEO, dir);\n}\n\/**\n * @brief MainWindow::play_video\n * Loads selected video, flips playbutton to pause\n * plays video from beginning\n *\n *\/\nvoid MainWindow::play_video() {\n mvideo_player->load_video(selectedVideo->name.toStdString());\n iconOnButtonHandler->set_icon(\"pause\", ui->playPauseButton);\n video_slider->setMaximum(mvideo_player->get_num_frames());\n mvideo_player->set_playback_frame(0);\n}\n\/**\n * @brief MainWindow::set_selected_project\n * @param newSelectedProject\n *\/\nvoid MainWindow::set_selected_project(MyQTreeWidgetItem *newSelectedProject){\n if(selectedProject) {\n selectedProject = newSelectedProject;\n QString string = selectedProject->text(0);\n string.append(\" <--\");\n selectedProject->setText(0, string);\n } else if (selectedProject != newSelectedProject) {\n QString string = selectedProject->text(0);\n string.chop(4);\n selectedProject->setText(0, string);\n selectedProject = newSelectedProject;\n string = selectedProject->text(0);\n string.append(\" <--\");\n selectedProject->setText(0, string);\n }\n}\n\/**\n * @brief MainWindow::on_actionSave_triggered\n * saves project which is selected in tree view,\n * checks if there is one\n *\/\nvoid MainWindow::on_actionSave_triggered()\n{\n if(selectedProject != nullptr) {\n this->fileHandler->save_project(this->selectedProject->id);\n std::string text = \"Saved project \" + this->selectedProject->name.toStdString();\n set_status_bar(text);\n } else {\n set_status_bar(\"Nothing to save\");\n }\n}\n<|endoftext|>"} {"text":"<commit_before>#include <stdio.h>\n#include <stdlib.h>\n#include <unistd.h>\n#include <string.h>\n#include <signal.h>\n#include <netinet\/in.h>\n#include <sys\/socket.h>\n#include <sys\/types.h> \n#include <sys\/wait.h>\n#include <dirent.h>\n#include <fcntl.h>\n#include <errno.h>\n#include <string>\n#include <functional>\n#include <unordered_map>\n#include <list>\n#include <algorithm>\n#include <iostream>\n#include <sstream>\n#include <map>\n\n#if defined(__APPLE__) || defined(__GNUC__) && __GNUC__ * 10 + __GNUC_MINOR__ >= 49\n#include <regex>\n#endif\n\n#include <assert.h>\n#include <vector>\n#include <fstream>\n#include <future>\n\n#define BUF_SIZE 4096\n#define MAX_LISTEN 128\n\nnamespace Cappuccino{\n\t\n\tnamespace Log{\n\n\t\tstatic int LogLevel = 0;\n\t\tstatic void debug(std::string msg){\n\t\t\tif(LogLevel >= 1){\n\t\t\t\tstd::cout << msg << std::endl;\n\t\t\t}\n\t\t}\n\n\t\tstatic void info(std::string msg){\n\t\t\tif(LogLevel >= 2){\n\t\t\t\tstd::cout << msg << std::endl;\n\t\t\t}\n\t\t}\n\t};\n\n\tclass Request;\n\tclass Response;\n\n\tstruct {\n\t\tint port = 1204;\n\t\tint sockfd = 0;\n\t\tint sessionfd = 0;\n\t fd_set mask1fds, mask2fds;\n\n\t\tstd::shared_ptr<std::string> view_root;\n\t\tstd::shared_ptr<std::string> static_root;\n\n\t\tstd::unordered_map<std::string,\n\t\t\tstd::function<Response(std::shared_ptr<Request>)>\n\t\t> routes;\n\n\t} context;\n\n\tnamespace signal_utils{\n\n\t\tvoid signal_handler(int signal){\n\t\t\tclose(context.sessionfd);\n\t\t\tclose(context.sockfd);\n\t\t\texit(0);\n\t\t}\n\n\t\tvoid signal_handler_child(int SignalName){\n\t\t\twhile(waitpid(-1,NULL,WNOHANG)>0){}\n\t signal(SIGCHLD, signal_utils::signal_handler_child);\n\t\t}\n\n\t\tvoid init_signal(){\n\t\t\tif(signal(SIGINT, signal_utils::signal_handler) == SIG_ERR){\n\t\t\t\texit(1);\n\t\t\t}\n\t\t\tif(signal(SIGCHLD, signal_utils::signal_handler_child) == SIG_ERR){\n\t\t\t\texit(1);\n\t\t\t}\n\t\t}\n\t}\n\n\tnamespace utils{\n\t\tstd::vector<std::string> split(const std::string& str, std::string delim) noexcept{\n\t\t\tstd::vector<std::string> result;\n\t\t std::string::size_type pos = 0;\n\t\t while(pos != std::string::npos ){\n\t\t std::string::size_type p = str.find(delim, pos);\n\t\t if(p == std::string::npos){\n\t\t result.push_back(str.substr(pos));\n\t\t break;\n\t\t }else{\n\t\t result.push_back(str.substr(pos, p - pos));\n\t\t }\n\t\t pos = p + delim.size();\n\t\t }\n\t\t return result;\n\t\t}\n\t};\n\n\tvoid init_socket(){\n\t struct sockaddr_in server;\n\t\tif((context.sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0){\n\t\t\texit(EXIT_FAILURE);\n\t\t}\n\t\tmemset( &server, 0, sizeof(server));\n\t\tserver.sin_family = AF_INET;\t\n\t\tserver.sin_addr.s_addr = INADDR_ANY;\n\t\tserver.sin_port = htons(context.port);\n\n\t\tchar opt = 1;\n\t\tsetsockopt(context.sockfd, SOL_SOCKET, SO_REUSEADDR, (char *)&opt, sizeof(char));\n\n\t\tint temp = 1;\n \t\tif(setsockopt(context.sockfd, SOL_SOCKET, SO_REUSEADDR,\n\t &temp, sizeof(int))){\n\t\t}\n\t\t\n\t\tif (bind(context.sockfd, (struct sockaddr *) &server, sizeof(server)) < 0) {\n\t\t\texit(EXIT_FAILURE);\n\t\t}\n\n\t\tif(listen(context.sockfd, MAX_LISTEN) < 0) {\n\t\t\texit(EXIT_FAILURE);\n\t\t}\n\n\t FD_ZERO(&context.mask1fds);\n\t FD_SET(context.sockfd, &context.mask1fds);\n\t}\n\n\tusing namespace std;\n\n\n\tstring openFile(string aFilename){\n\t\tauto filename = aFilename;\n\t\tstd::ifstream ifs( filename, std::ios::in | std::ios::binary);\n\t\tif(ifs.fail()){\t\t\n\t\t\tthrow std::runtime_error(\"No such file or directory \\\"\"+ filename +\"\\\"\\n\");\n\t\t}\n\t\tifs.seekg( 0, std::ios::end);\n\t\tauto pos = ifs.tellg();\n\t\tifs.seekg( 0, std::ios::beg);\n\n\t\tstd::vector<char> buf(pos);\n\t\tifs.read(buf.data(), pos);\n\t\treturn string(buf.begin(), buf.end());;\n\t}\n\n\tvoid option(int argc, char *argv[]) noexcept{\n\t\tchar result;\n\t\twhile((result = getopt(argc,argv,\"dp:\")) != -1){\n\t\t\tswitch(result){\n\t\t\tcase 'd':\n\t\t\t\tLog::LogLevel = 1;\t\n\t\t\t\tbreak;\n\t\t\tcase 'p':\n\t\t\t\tcontext.port = atoi(optarg);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\n\tclass Request{\n\t\tmap<string, string> headerset;\n\t\tmap<string, string> paramset;\n\t public:\n\t\tRequest(string method, string url,string protocol):\n\t\tmethod(move(method)),\n\t\turl(move(url)),\n\t\tprotocol(move(protocol))\n\t\t{}\n\n\t\tconst string method;\n\t\tconst string url;\n\t\tconst string protocol;\n\n\t\tvoid addHeader(string key,string value){\n\t\t\theaderset[key] = move(value);\n\t\t}\n\n\t\tvoid addParams(string key,string value){\n\t\t\tparamset[key] = move(value);\n\t\t}\n\n\t\tstring header(string key){\n\t\t\tif(headerset.find(key) == headerset.end())\n\t\t\t\treturn \"INVALID\";\n\t\t\treturn headerset[key];\n\t\t}\n\n\t\tstring params(string key){\n\t\t\tif(paramset.find(key) == paramset.end())\n\t\t\t\treturn \"INVALID\";\n\t\t\treturn paramset[key];\n\t\t}\n\t};\n\n class Response{\n\t\tint status_;\n\t\tstring message_;\n\t\tstring url_;\n\t\tstring body_;\n\t\tstring protocol_;\n public:\n\n\t\tResponse(weak_ptr<Request> req){\n\t\t\tauto r = req.lock();\n\t\t\tif(r){\n\t\t\t\turl_ = r->url;\n\t\t\t\tprotocol_ = r->protocol;\n\t\t\t}else{\n\t\t\t\tthrow std::runtime_error(\"Request expired!\\n\");\n\t\t\t}\n\t\t}\n\n\t\tResponse(int st,string msg,string pro, string bod):\n\t\t\tstatus_(st),\n\t\t\tmessage_(msg),\n\t\t\tbody_(bod),\n\t\t\tprotocol_(pro)\n\t\t{}\n\n\t\tResponse* message(string msg){\n\t\t\tmessage_ = msg;\n\t\t\treturn this;\n\t\t}\n\n\t\tResponse* status(int st){\n\t\t\tstatus_ = st;\n\t\t\treturn this;\n\t\t}\n\n\t\tResponse* file(string filename){\n\t\t\tbody_ = openFile(*context.view_root + \"\/\" + filename);\n\t\t\treturn this;\n\t\t}\n\n \toperator string(){\n \t\treturn protocol_ + \" \" + to_string(status_) +\" \"+ message_ + \"\\n\\n\" + body_;\n \t}\n };\n\n\tstring createResponse(char* req) noexcept{\n\t\tauto lines = utils::split(string(req), \"\\n\");\n\t\tif(lines.empty())\n\t\t\treturn Response(400, \"Bad Request\", \"HTTP\/1.1\", \"NN\");\n \n\t\tauto tops = utils::split(lines[0], \" \");\n\t\tif(tops.size() < 3)\n\t\t\treturn Response(401, \"Bad Request\", \"HTTP\/1.1\", \"NN\");\n\n\t\tcout<< tops[0] << \" \" << tops[1] << \" \" <<tops[2] << endl;\n\n\t\tauto request = shared_ptr<Request>(new Request(tops[0],tops[1],tops[2]));\n\n\t\tif(context.routes.find(tops[1]) != context.routes.end()){\n\t\t\treturn context.routes[tops[1]](move(request));\n\t\t}\n\n\t\treturn Response( 404,\"Not found\", tops[2], \"AA\");\n\t}\n\n\tstring receiveProcess(int sessionfd){\n\t\tchar buf[BUF_SIZE] = {};\n\n\t\tif (recv(sessionfd, buf, sizeof(buf), 0) < 0) {\n\t\t\texit(EXIT_FAILURE);\n\t\t}\n\t\tdo{\n\t\t\tif(strstr(buf, \"\\r\\n\")){\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tif (strlen(buf) >= sizeof(buf)) {\n\t\t\t\tmemset(&buf, 0, sizeof(buf));\n\t\t\t}\n\t\t}while(read(sessionfd, buf+strlen(buf), sizeof(buf) - strlen(buf)) > 0);\n\t\treturn createResponse(buf);\t\n\t}\n\t\n\n\tvoid load(string directory, string filename) noexcept{\n\t\tif(filename == \".\" || filename == \"..\") return;\n\t\tif(filename!=\"\")\n\t\t\tdirectory += \"\/\" + filename;\n\t\tDIR* dir = opendir(directory.c_str());\n\t\tif(dir != NULL){\n\t\t\tstruct dirent* dent;\n\t dent = readdir(dir);\n\t\t while(dent!=NULL){\n\t\t dent = readdir(dir);\n\t\t if(dent!=NULL)\n\t\t\t load(directory, string(dent->d_name));\n\t\t }\n\t\t closedir(dir);\n\t\t\tdelete dent;\n\t\t\tdelete dir;\n\t\t}else{\n\t\t\tcout<<\"add \"<<directory<< endl;\n\t\t\tcontext.routes.insert( make_pair(\n\t\t\t\t\"\/\" + directory, \n\t\t\t\t[directory,filename](std::shared_ptr<Request> request) -> Cappuccino::Response{\n\t\t\t\t\treturn Response(200,\"OK\",\"HTTP\/1.1\",openFile(directory));\n\t\t\t\t}\n\t\t\t));\t\t\t\n\t\t}\n\t}\n\n\tvoid loadStaticFiles() noexcept{\n\t\tload(*context.static_root,\"\");\n\t}\n\n\tvoid route(string url,std::function<Response(std::shared_ptr<Request>)> F){\n\t\tcontext.routes.insert( make_pair( move(url), move(F) ));\n\t}\n\n\tvoid root(string r){\n\t\tcontext.view_root = make_shared<string>(move(r));\n\t}\n\t\n\tvoid resource(string s){\n\t\tcontext.static_root = make_shared<string>(move(s));\n\t}\n\n\tvoid run(){\n\n\t\tinit_socket();\n\t\tsignal_utils::init_signal();\n\t\tloadStaticFiles();\n\n\t int cd[FD_SETSIZE];\n\t\tstruct sockaddr_in client;\n int fd;\n struct timeval tv;\n\n\t for(int i = 0;i < FD_SETSIZE; i++){\n\t cd[i] = 0;\n\t }\n\n\t\tint I = 0;\n\t while(1) {\n\t\n\t\t\tif(I>5){\n\t\t\t\treturn;\n\t\t\t}\t\n\t\t\t\n\n\t tv.tv_sec = 0;\n\t tv.tv_usec = 0;\n\n\t memcpy(&context.mask2fds, &context.mask1fds, sizeof(context.mask1fds));\n\n\t int select_result = select(FD_SETSIZE, &context.mask2fds, (fd_set *)0, (fd_set *)0, &tv);\n\t if(select_result < 1) {\n\t for(fd = 0; fd < FD_SETSIZE; fd++) {\n\t if(cd[fd] == 1) {\n\t close(fd);\n\t FD_CLR(fd, &context.mask1fds);\n\t cd[fd] = 0;\n\t }\n\t }\n\t continue;\n\t }\n\t\t\tfor(fd = 0; fd < FD_SETSIZE; fd++){\n\t if(FD_ISSET(fd,&context.mask2fds)) {\n\t if(fd == context.sockfd) {\n\t \tmemset( &client, 0, sizeof(client));\n\t\t\t\t\t\tint len = sizeof(client);\n\t int clientfd = accept(context.sockfd, \n\t (struct sockaddr *)&client,(socklen_t *) &len);\n\t FD_SET(clientfd, &context.mask1fds);\n\t }else {\n\t if(cd[fd] == 1) {\n\t close(fd);\n\t FD_CLR(fd, &context.mask1fds);\n\t cd[fd] = 0;\n\t } else {\n\t\t\t\t\t\t\tstring response = receiveProcess(fd);\n\t\t\t\t\t\t\twrite(fd, response.c_str(), response.size());\n\t cd[fd] = 1;\n\n\t\t\t\t\t\t\tI++;\n\t\n\t }\n\t }\n\t }\n\t }\n\t }\t \n\t}\n\n\tvoid Cappuccino(int argc, char *argv[]) {\n\t\toption(argc, argv);\n\t\tcontext.view_root = make_shared<string>(\"\");\n\t\tcontext.static_root = make_shared<string>(\"public\");\n\t}\n};\n\nnamespace Cocoa{\n\tusing namespace Cappuccino;\n\tusing namespace std;\n\n\t\/\/ Unit Test\t\n\tvoid testOpenFile(){\n\t\tstring res = openFile(\"html\/index.html\");\n\t\tauto lines = utils::split(res, \"\\n\");\n\t\tassert(!lines.empty());\n\t}\n\n\tvoid testOpenInvalidFile(){\n\t\ttry{\n\t\t\tstring res = openFile(\"html\/index\");\n\t\t}catch(std::runtime_error e){\n\t\t\tcout<< e.what() << endl;\n\t\t}\n\t}\n};\n\n<commit_msg>[Imp] clean include, use unordered_map<commit_after>#include <cstdio>\n#include <cstdlib>\n#include <unistd.h>\n#include <string>\n#include <csignal>\n#include <netinet\/in.h>\n#include <sys\/socket.h>\n#include <sys\/types.h> \n#include <sys\/wait.h>\n#include <dirent.h>\n#include <fcntl.h>\n#include <errno.h>\n#include <functional>\n#include <unordered_map>\n#include <algorithm>\n#include <iostream>\n#include <sstream>\n\n#if defined(__APPLE__) || defined(__GNUC__) && __GNUC__ * 10 + __GNUC_MINOR__ >= 49\n#include <regex>\n#endif\n\n#include <cassert>\n#include <vector>\n#include <fstream>\n#include <future>\n\n#define BUF_SIZE 4096\n#define MAX_LISTEN 128\n\nnamespace Cappuccino{\n\t\n\tnamespace Log{\n\n\t\tstatic int LogLevel = 0;\n\t\tstatic void debug(std::string msg){\n\t\t\tif(LogLevel >= 1){\n\t\t\t\tstd::cout << msg << std::endl;\n\t\t\t}\n\t\t}\n\n\t\tstatic void info(std::string msg){\n\t\t\tif(LogLevel >= 2){\n\t\t\t\tstd::cout << msg << std::endl;\n\t\t\t}\n\t\t}\n\t};\n\n\tclass Request;\n\tclass Response;\n\n\tstruct {\n\t\tint port = 1204;\n\t\tint sockfd = 0;\n\t\tint sessionfd = 0;\n\t fd_set mask1fds, mask2fds;\n\n\t\tstd::shared_ptr<std::string> view_root;\n\t\tstd::shared_ptr<std::string> static_root;\n\n\t\tstd::unordered_map<std::string,\n\t\t\tstd::function<Response(std::shared_ptr<Request>)>\n\t\t> routes;\n\n\t} context;\n\n\tnamespace signal_utils{\n\n\t\tvoid signal_handler(int signal){\n\t\t\tclose(context.sessionfd);\n\t\t\tclose(context.sockfd);\n\t\t\texit(0);\n\t\t}\n\n\t\tvoid signal_handler_child(int SignalName){\n\t\t\twhile(waitpid(-1,NULL,WNOHANG)>0){}\n\t signal(SIGCHLD, signal_utils::signal_handler_child);\n\t\t}\n\n\t\tvoid init_signal(){\n\t\t\tif(signal(SIGINT, signal_utils::signal_handler) == SIG_ERR){\n\t\t\t\texit(1);\n\t\t\t}\n\t\t\tif(signal(SIGCHLD, signal_utils::signal_handler_child) == SIG_ERR){\n\t\t\t\texit(1);\n\t\t\t}\n\t\t}\n\t}\n\n\tnamespace utils{\n\t\tstd::vector<std::string> split(const std::string& str, std::string delim) noexcept{\n\t\t\tstd::vector<std::string> result;\n\t\t std::string::size_type pos = 0;\n\t\t while(pos != std::string::npos ){\n\t\t std::string::size_type p = str.find(delim, pos);\n\t\t if(p == std::string::npos){\n\t\t result.push_back(str.substr(pos));\n\t\t break;\n\t\t }else{\n\t\t result.push_back(str.substr(pos, p - pos));\n\t\t }\n\t\t pos = p + delim.size();\n\t\t }\n\t\t return result;\n\t\t}\n\t};\n\n\tvoid init_socket(){\n\t struct sockaddr_in server;\n\t\tif((context.sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0){\n\t\t\texit(EXIT_FAILURE);\n\t\t}\n\t\tmemset( &server, 0, sizeof(server));\n\t\tserver.sin_family = AF_INET;\t\n\t\tserver.sin_addr.s_addr = INADDR_ANY;\n\t\tserver.sin_port = htons(context.port);\n\n\t\tchar opt = 1;\n\t\tsetsockopt(context.sockfd, SOL_SOCKET, SO_REUSEADDR, (char *)&opt, sizeof(char));\n\n\t\tint temp = 1;\n \t\tif(setsockopt(context.sockfd, SOL_SOCKET, SO_REUSEADDR,\n\t &temp, sizeof(int))){\n\t\t}\n\t\t\n\t\tif (bind(context.sockfd, (struct sockaddr *) &server, sizeof(server)) < 0) {\n\t\t\texit(EXIT_FAILURE);\n\t\t}\n\n\t\tif(listen(context.sockfd, MAX_LISTEN) < 0) {\n\t\t\texit(EXIT_FAILURE);\n\t\t}\n\n\t FD_ZERO(&context.mask1fds);\n\t FD_SET(context.sockfd, &context.mask1fds);\n\t}\n\n\tusing namespace std;\n\n\n\tstring openFile(string aFilename){\n\t\tauto filename = aFilename;\n\t\tstd::ifstream ifs( filename, std::ios::in | std::ios::binary);\n\t\tif(ifs.fail()){\t\t\n\t\t\tthrow std::runtime_error(\"No such file or directory \\\"\"+ filename +\"\\\"\\n\");\n\t\t}\n\t\tifs.seekg( 0, std::ios::end);\n\t\tauto pos = ifs.tellg();\n\t\tifs.seekg( 0, std::ios::beg);\n\n\t\tstd::vector<char> buf(pos);\n\t\tifs.read(buf.data(), pos);\n\t\treturn string(buf.begin(), buf.end());;\n\t}\n\n\tvoid option(int argc, char *argv[]) noexcept{\n\t\tchar result;\n\t\twhile((result = getopt(argc,argv,\"dp:\")) != -1){\n\t\t\tswitch(result){\n\t\t\tcase 'd':\n\t\t\t\tLog::LogLevel = 1;\t\n\t\t\t\tbreak;\n\t\t\tcase 'p':\n\t\t\t\tcontext.port = atoi(optarg);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\n\tclass Request{\n\t\tunordered_map<string, string> headerset;\n\t\tunordered_map<string, string> paramset;\n\t public:\n\t\tRequest(string method, string url,string protocol):\n\t\tmethod(move(method)),\n\t\turl(move(url)),\n\t\tprotocol(move(protocol))\n\t\t{}\n\n\t\tconst string method;\n\t\tconst string url;\n\t\tconst string protocol;\n\n\t\tvoid addHeader(string key,string value){\n\t\t\theaderset[key] = move(value);\n\t\t}\n\n\t\tvoid addParams(string key,string value){\n\t\t\tparamset[key] = move(value);\n\t\t}\n\n\t\tstring header(string key){\n\t\t\tif(headerset.find(key) == headerset.end())\n\t\t\t\treturn \"INVALID\";\n\t\t\treturn headerset[key];\n\t\t}\n\n\t\tstring params(string key){\n\t\t\tif(paramset.find(key) == paramset.end())\n\t\t\t\treturn \"INVALID\";\n\t\t\treturn paramset[key];\n\t\t}\n\t};\n\n class Response{\n\t\tint status_;\n\t\tstring message_;\n\t\tstring url_;\n\t\tstring body_;\n\t\tstring protocol_;\n public:\n\n\t\tResponse(weak_ptr<Request> req){\n\t\t\tauto r = req.lock();\n\t\t\tif(r){\n\t\t\t\turl_ = r->url;\n\t\t\t\tprotocol_ = r->protocol;\n\t\t\t}else{\n\t\t\t\tthrow std::runtime_error(\"Request expired!\\n\");\n\t\t\t}\n\t\t}\n\n\t\tResponse(int st,string msg,string pro, string bod):\n\t\t\tstatus_(st),\n\t\t\tmessage_(msg),\n\t\t\tbody_(bod),\n\t\t\tprotocol_(pro)\n\t\t{}\n\n\t\tResponse* message(string msg){\n\t\t\tmessage_ = msg;\n\t\t\treturn this;\n\t\t}\n\n\t\tResponse* status(int st){\n\t\t\tstatus_ = st;\n\t\t\treturn this;\n\t\t}\n\n\t\tResponse* file(string filename){\n\t\t\tbody_ = openFile(*context.view_root + \"\/\" + filename);\n\t\t\treturn this;\n\t\t}\n\n \toperator string(){\n \t\treturn protocol_ + \" \" + to_string(status_) +\" \"+ message_ + \"\\n\\n\" + body_;\n \t}\n };\n\n\tstring createResponse(char* req) noexcept{\n\t\tauto lines = utils::split(string(req), \"\\n\");\n\t\tif(lines.empty())\n\t\t\treturn Response(400, \"Bad Request\", \"HTTP\/1.1\", \"NN\");\n \n\t\tauto tops = utils::split(lines[0], \" \");\n\t\tif(tops.size() < 3)\n\t\t\treturn Response(401, \"Bad Request\", \"HTTP\/1.1\", \"NN\");\n\n\t\tcout<< tops[0] << \" \" << tops[1] << \" \" <<tops[2] << endl;\n\n\t\tauto request = shared_ptr<Request>(new Request(tops[0],tops[1],tops[2]));\n\n\t\tif(context.routes.find(tops[1]) != context.routes.end()){\n\t\t\treturn context.routes[tops[1]](move(request));\n\t\t}\n\n\t\treturn Response( 404,\"Not found\", tops[2], \"AA\");\n\t}\n\n\tstring receiveProcess(int sessionfd){\n\t\tchar buf[BUF_SIZE] = {};\n\n\t\tif (recv(sessionfd, buf, sizeof(buf), 0) < 0) {\n\t\t\texit(EXIT_FAILURE);\n\t\t}\n\t\tdo{\n\t\t\tif(strstr(buf, \"\\r\\n\")){\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tif (strlen(buf) >= sizeof(buf)) {\n\t\t\t\tmemset(&buf, 0, sizeof(buf));\n\t\t\t}\n\t\t}while(read(sessionfd, buf+strlen(buf), sizeof(buf) - strlen(buf)) > 0);\n\t\treturn createResponse(buf);\t\n\t}\n\t\n\n\tvoid load(string directory, string filename) noexcept{\n\t\tif(filename == \".\" || filename == \"..\") return;\n\t\tif(filename!=\"\")\n\t\t\tdirectory += \"\/\" + filename;\n\t\tDIR* dir = opendir(directory.c_str());\n\t\tif(dir != NULL){\n\t\t\tstruct dirent* dent;\n\t dent = readdir(dir);\n\t\t while(dent!=NULL){\n\t\t dent = readdir(dir);\n\t\t if(dent!=NULL)\n\t\t\t load(directory, string(dent->d_name));\n\t\t }\n\t\t closedir(dir);\n\t\t\tdelete dent;\n\t\t\tdelete dir;\n\t\t}else{\n\t\t\tcout<<\"add \"<<directory<< endl;\n\t\t\tcontext.routes.insert( make_pair(\n\t\t\t\t\"\/\" + directory, \n\t\t\t\t[directory,filename](std::shared_ptr<Request> request) -> Cappuccino::Response{\n\t\t\t\t\treturn Response(200,\"OK\",\"HTTP\/1.1\",openFile(directory));\n\t\t\t\t}\n\t\t\t));\t\t\t\n\t\t}\n\t}\n\n\tvoid loadStaticFiles() noexcept{\n\t\tload(*context.static_root,\"\");\n\t}\n\n\tvoid route(string url,std::function<Response(std::shared_ptr<Request>)> F){\n\t\tcontext.routes.insert( make_pair( move(url), move(F) ));\n\t}\n\n\tvoid root(string r){\n\t\tcontext.view_root = make_shared<string>(move(r));\n\t}\n\t\n\tvoid resource(string s){\n\t\tcontext.static_root = make_shared<string>(move(s));\n\t}\n\n\tvoid run(){\n\n\t\tinit_socket();\n\t\tsignal_utils::init_signal();\n\t\tloadStaticFiles();\n\n\t int cd[FD_SETSIZE];\n\t\tstruct sockaddr_in client;\n int fd;\n struct timeval tv;\n\n\t for(int i = 0;i < FD_SETSIZE; i++){\n\t cd[i] = 0;\n\t }\n\n\t\tint I = 0;\n\t while(1) {\n\t\n\t\t\tif(I>5){\n\t\t\t\treturn;\n\t\t\t}\t\n\t\t\t\n\n\t tv.tv_sec = 0;\n\t tv.tv_usec = 0;\n\n\t memcpy(&context.mask2fds, &context.mask1fds, sizeof(context.mask1fds));\n\n\t int select_result = select(FD_SETSIZE, &context.mask2fds, (fd_set *)0, (fd_set *)0, &tv);\n\t if(select_result < 1) {\n\t for(fd = 0; fd < FD_SETSIZE; fd++) {\n\t if(cd[fd] == 1) {\n\t close(fd);\n\t FD_CLR(fd, &context.mask1fds);\n\t cd[fd] = 0;\n\t }\n\t }\n\t continue;\n\t }\n\t\t\tfor(fd = 0; fd < FD_SETSIZE; fd++){\n\t if(FD_ISSET(fd,&context.mask2fds)) {\n\t if(fd == context.sockfd) {\n\t \tmemset( &client, 0, sizeof(client));\n\t\t\t\t\t\tint len = sizeof(client);\n\t int clientfd = accept(context.sockfd, \n\t (struct sockaddr *)&client,(socklen_t *) &len);\n\t FD_SET(clientfd, &context.mask1fds);\n\t }else {\n\t if(cd[fd] == 1) {\n\t close(fd);\n\t FD_CLR(fd, &context.mask1fds);\n\t cd[fd] = 0;\n\t } else {\n\t\t\t\t\t\t\tstring response = receiveProcess(fd);\n\t\t\t\t\t\t\twrite(fd, response.c_str(), response.size());\n\t cd[fd] = 1;\n\n\t\t\t\t\t\t\tI++;\n\t\n\t }\n\t }\n\t }\n\t }\n\t }\t \n\t}\n\n\tvoid Cappuccino(int argc, char *argv[]) {\n\t\toption(argc, argv);\n\t\tcontext.view_root = make_shared<string>(\"\");\n\t\tcontext.static_root = make_shared<string>(\"public\");\n\t}\n};\n\nnamespace Cocoa{\n\tusing namespace Cappuccino;\n\tusing namespace std;\n\n\t\/\/ Unit Test\t\n\tvoid testOpenFile(){\n\t\tstring res = openFile(\"html\/index.html\");\n\t\tauto lines = utils::split(res, \"\\n\");\n\t\tassert(!lines.empty());\n\t}\n\n\tvoid testOpenInvalidFile(){\n\t\ttry{\n\t\t\tstring res = openFile(\"html\/index\");\n\t\t}catch(std::runtime_error e){\n\t\t\tcout<< e.what() << endl;\n\t\t}\n\t}\n};\n\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: ToolBoxHelper.cxx,v $\n *\n * $Revision: 1.2 $\n *\n * last change: $Author: vg $ $Date: 2003-04-17 13:26:48 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the License); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an AS IS basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n#ifndef DBAUI_TOOLBOXHELPER_HXX\n#include \"ToolBoxHelper.hxx\"\n#endif\n#ifndef _SV_TOOLBOX_HXX\n#include <vcl\/toolbox.hxx>\n#endif\n#ifndef _SV_SVAPP_HXX\n#include <vcl\/svapp.hxx>\n#endif\n#ifndef INCLUDED_SVTOOLS_MISCOPT_HXX\n#include <svtools\/miscopt.hxx>\n#endif\n#ifndef DBAUI_TOOLS_HXX\n#include \"UITools.hxx\"\n#endif\n#ifndef _SVTOOLS_IMGDEF_HXX\n#include <svtools\/imgdef.hxx>\n#endif\n#ifndef _DBAUI_MODULE_DBU_HXX_\n#include \"moduledbu.hxx\"\n#endif\n\nnamespace dbaui\n{\n OToolBoxHelper::OToolBoxHelper()\n : m_bIsHiContrast(sal_False)\n ,m_pToolBox(NULL)\n ,m_nBitmapSet( getCurrentSymbolSet() )\n {\n SvtMiscOptions().AddListener( LINK( this, OToolBoxHelper, ConfigOptionsChanged ) );\n Application::AddEventListener( LINK( this, OToolBoxHelper, SettingsChanged ) );\n }\n \/\/ -----------------------------------------------------------------------------\n OToolBoxHelper::~OToolBoxHelper()\n {\n SvtMiscOptions().RemoveListener( LINK( this, OToolBoxHelper, ConfigOptionsChanged ) );\n Application::RemoveEventListener( LINK( this, OToolBoxHelper, SettingsChanged ) );\n }\n \/\/ -----------------------------------------------------------------------------\n sal_Int16 OToolBoxHelper::getCurrentSymbolSet()\n {\n sal_Int16 eOptSymbolSet = SvtMiscOptions().GetSymbolSet();\n\n if ( eOptSymbolSet == SFX_SYMBOLS_AUTO )\n {\n \/\/ Use system settings, we have to retrieve the toolbar icon size from the\n \/\/ Application class\n ULONG nStyleIconSize = Application::GetSettings().GetStyleSettings().GetToolbarIconSize();\n if ( nStyleIconSize == STYLE_TOOLBAR_ICONSIZE_LARGE )\n eOptSymbolSet = SFX_SYMBOLS_LARGE;\n else\n eOptSymbolSet = SFX_SYMBOLS_SMALL;\n }\n\n return eOptSymbolSet;\n }\n\n \/\/ -----------------------------------------------------------------------------\n void OToolBoxHelper::checkImageList()\n {\n if ( m_pToolBox )\n {\n sal_Int16 nCurBitmapSet = getCurrentSymbolSet();\n if ( nCurBitmapSet != m_nBitmapSet ||\n m_bIsHiContrast != m_pToolBox->GetBackground().GetColor().IsDark() )\n {\n m_nBitmapSet = nCurBitmapSet;\n m_bIsHiContrast = m_pToolBox->GetBackground().GetColor().IsDark();\n\n\n m_pToolBox->SetImageList( ModuleRes( getImageListId(m_nBitmapSet,m_bIsHiContrast) ) );\n Size aTbOldSize = m_pToolBox->GetSizePixel();\n adjustToolBoxSize(m_pToolBox);\n Size aTbNewSize = m_pToolBox->GetSizePixel();\n resizeControls(Size(aTbNewSize.Width() - aTbOldSize.Width(),\n aTbNewSize.Height() - aTbOldSize.Height())\n );\n }\n }\n }\n \/\/ -----------------------------------------------------------------------------\n IMPL_LINK(OToolBoxHelper, ConfigOptionsChanged, SvtMiscOptions*, _pOptions)\n {\n if ( m_pToolBox )\n {\n SvtMiscOptions aOptions;\n \/\/ check if imagelist changed\n checkImageList();\n if ( aOptions.GetToolboxStyle() != m_pToolBox->GetOutStyle() )\n m_pToolBox->SetOutStyle(aOptions.GetToolboxStyle());\n }\n\n return 0L;\n }\n \/\/ -----------------------------------------------------------------------------\n IMPL_LINK(OToolBoxHelper, SettingsChanged, void*, _pVoid)\n {\n if ( m_pToolBox )\n {\n \/\/ check if imagelist changed\n checkImageList();\n }\n\n return 0L;\n }\n \/\/ -----------------------------------------------------------------------------\n void OToolBoxHelper::setToolBox(ToolBox* _pTB)\n {\n sal_Bool bFirstTime = (m_pToolBox == NULL);\n m_pToolBox = _pTB;\n if ( m_pToolBox )\n {\n \/\/ m_bIsHiContrast = m_pToolBox->GetBackground().GetColor().IsDark();\n ConfigOptionsChanged(NULL);\n if ( bFirstTime )\n adjustToolBoxSize(m_pToolBox);\n }\n }\n\/\/ -----------------------------------------------------------------------------\n} \/\/ namespace\n\/\/ -----------------------------------------------------------------------------\n\n<commit_msg>INTEGRATION: CWS dba05 (1.2.4); FILE MERGED 2003\/04\/30 14:44:48 oj 1.2.4.3: #109263# filter only usefull events 2003\/04\/30 13:27:21 oj 1.2.4.2: #109216# set -1 as default for bitmaps, will be changed afterwards 2003\/04\/30 11:08:59 oj 1.2.4.1: #109216# set small as default for bitmaps, will be changed afterwards<commit_after>\/*************************************************************************\n *\n * $RCSfile: ToolBoxHelper.cxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: vg $ $Date: 2003-05-19 12:55:49 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the License); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an AS IS basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n#ifndef DBAUI_TOOLBOXHELPER_HXX\n#include \"ToolBoxHelper.hxx\"\n#endif\n#ifndef _SV_TOOLBOX_HXX\n#include <vcl\/toolbox.hxx>\n#endif\n#ifndef _SV_SVAPP_HXX\n#include <vcl\/svapp.hxx>\n#endif\n#ifndef INCLUDED_SVTOOLS_MISCOPT_HXX\n#include <svtools\/miscopt.hxx>\n#endif\n#ifndef DBAUI_TOOLS_HXX\n#include \"UITools.hxx\"\n#endif\n#ifndef _SVTOOLS_IMGDEF_HXX\n#include <svtools\/imgdef.hxx>\n#endif\n#ifndef _DBAUI_MODULE_DBU_HXX_\n#include \"moduledbu.hxx\"\n#endif\n#include <vcl\/event.hxx>\n\nnamespace dbaui\n{\n OToolBoxHelper::OToolBoxHelper()\n : m_bIsHiContrast(sal_False)\n ,m_pToolBox(NULL)\n ,m_nBitmapSet(-1 )\n {\n OSL_ENSURE(m_nBitmapSet != getCurrentSymbolSet(),\"BitmapSet should not be identical\");\n SvtMiscOptions().AddListener( LINK( this, OToolBoxHelper, ConfigOptionsChanged ) );\n Application::AddEventListener( LINK( this, OToolBoxHelper, SettingsChanged ) );\n }\n \/\/ -----------------------------------------------------------------------------\n OToolBoxHelper::~OToolBoxHelper()\n {\n SvtMiscOptions().RemoveListener( LINK( this, OToolBoxHelper, ConfigOptionsChanged ) );\n Application::RemoveEventListener( LINK( this, OToolBoxHelper, SettingsChanged ) );\n }\n \/\/ -----------------------------------------------------------------------------\n sal_Int16 OToolBoxHelper::getCurrentSymbolSet()\n {\n sal_Int16 eOptSymbolSet = SvtMiscOptions().GetSymbolSet();\n\n if ( eOptSymbolSet == SFX_SYMBOLS_AUTO )\n {\n \/\/ Use system settings, we have to retrieve the toolbar icon size from the\n \/\/ Application class\n ULONG nStyleIconSize = Application::GetSettings().GetStyleSettings().GetToolbarIconSize();\n if ( nStyleIconSize == STYLE_TOOLBAR_ICONSIZE_LARGE )\n eOptSymbolSet = SFX_SYMBOLS_LARGE;\n else\n eOptSymbolSet = SFX_SYMBOLS_SMALL;\n }\n\n return eOptSymbolSet;\n }\n\n \/\/ -----------------------------------------------------------------------------\n void OToolBoxHelper::checkImageList()\n {\n if ( m_pToolBox )\n {\n sal_Int16 nCurBitmapSet = getCurrentSymbolSet();\n if ( nCurBitmapSet != m_nBitmapSet ||\n m_bIsHiContrast != m_pToolBox->GetBackground().GetColor().IsDark() )\n {\n m_nBitmapSet = nCurBitmapSet;\n m_bIsHiContrast = m_pToolBox->GetBackground().GetColor().IsDark();\n\n\n m_pToolBox->SetImageList( ModuleRes( getImageListId(m_nBitmapSet,m_bIsHiContrast) ) );\n Size aTbOldSize = m_pToolBox->GetSizePixel();\n adjustToolBoxSize(m_pToolBox);\n Size aTbNewSize = m_pToolBox->GetSizePixel();\n resizeControls(Size(aTbNewSize.Width() - aTbOldSize.Width(),\n aTbNewSize.Height() - aTbOldSize.Height())\n );\n }\n }\n }\n \/\/ -----------------------------------------------------------------------------\n IMPL_LINK(OToolBoxHelper, ConfigOptionsChanged, SvtMiscOptions*, _pOptions)\n {\n if ( m_pToolBox )\n {\n SvtMiscOptions aOptions;\n \/\/ check if imagelist changed\n checkImageList();\n if ( aOptions.GetToolboxStyle() != m_pToolBox->GetOutStyle() )\n m_pToolBox->SetOutStyle(aOptions.GetToolboxStyle());\n }\n\n return 0L;\n }\n \/\/ -----------------------------------------------------------------------------\n IMPL_LINK(OToolBoxHelper, SettingsChanged, VclWindowEvent*, _pEvt)\n {\n if ( m_pToolBox && _pEvt && _pEvt->GetId() == VCLEVENT_APPLICATION_DATACHANGED )\n {\n DataChangedEvent* pData = reinterpret_cast<DataChangedEvent*>(_pEvt->GetData());\n if ( pData && ((( pData->GetType() == DATACHANGED_SETTINGS ) ||\n ( pData->GetType() == DATACHANGED_DISPLAY )) &&\n ( pData->GetFlags() & SETTINGS_STYLE )))\n \/\/ check if imagelist changed\n checkImageList();\n }\n\n return 0L;\n }\n \/\/ -----------------------------------------------------------------------------\n void OToolBoxHelper::setToolBox(ToolBox* _pTB)\n {\n sal_Bool bFirstTime = (m_pToolBox == NULL);\n m_pToolBox = _pTB;\n if ( m_pToolBox )\n {\n \/\/ m_bIsHiContrast = m_pToolBox->GetBackground().GetColor().IsDark();\n ConfigOptionsChanged(NULL);\n if ( bFirstTime )\n adjustToolBoxSize(m_pToolBox);\n }\n }\n\/\/ -----------------------------------------------------------------------------\n} \/\/ namespace\n\/\/ -----------------------------------------------------------------------------\n\n<|endoftext|>"} {"text":"<commit_before>\/*ckwg +5\n * Copyright 2011 by Kitware, Inc. All Rights Reserved. Please refer to\n * KITWARE_LICENSE.TXT for licensing information, or contact General Counsel,\n * Kitware, Inc., 28 Corporate Drive, Clifton Park, NY 12065.\n *\/\n\n#include <vistk\/pipeline\/edge.h>\n#include <vistk\/pipeline\/edge_exception.h>\n#include <vistk\/pipeline\/stamp.h>\n\n#include <boost\/python.hpp>\n#include <boost\/python\/suite\/indexing\/vector_indexing_suite.hpp>\n\n\/**\n * \\file edge.cxx\n *\n * \\brief Python bindings for \\link vistk::edge\\endlink.\n *\/\n\nusing namespace boost::python;\n\nstatic vistk::datum_t edge_datum_datum(vistk::edge_datum_t const& edatum);\nstatic void edge_datum_datum_set(vistk::edge_datum_t& edatum, vistk::datum_t const& dat);\nstatic vistk::stamp_t edge_datum_stamp(vistk::edge_datum_t const& edatum);\nstatic void edge_datum_stamp_set(vistk::edge_datum_t& edatum, vistk::stamp_t const& st);\n\nstatic void translator(vistk::edge_exception const& e);\n\nBOOST_PYTHON_MODULE(edge)\n{\n register_exception_translator<\n vistk::edge_exception>(translator);\n\n class_<vistk::edge_datum_t>(\"EdgeDatum\"\n , no_init)\n .def(init<vistk::datum_t, vistk::stamp_t>())\n .add_property(\"datum\", &edge_datum_datum, &edge_datum_datum_set)\n .add_property(\"stamp\", &edge_datum_stamp, &edge_datum_stamp_set)\n ;\n class_<vistk::edge_data_t>(\"EdgeData\")\n .def(vector_indexing_suite<vistk::edge_data_t>())\n ;\n class_<vistk::edges_t>(\"Edges\")\n .def(vector_indexing_suite<vistk::edges_t>())\n ;\n\n class_<vistk::edge, vistk::edge_t, boost::noncopyable>(\"Edge\"\n , no_init)\n .def(init<vistk::config_t>())\n .def(\"makes_dependency\", &vistk::edge::makes_dependency)\n .def(\"has_data\", &vistk::edge::has_data)\n .def(\"full_of_data\", &vistk::edge::full_of_data)\n .def(\"datum_count\", &vistk::edge::datum_count)\n .def(\"push_datum\", &vistk::edge::push_datum)\n .def(\"get_datum\", &vistk::edge::get_datum)\n .def(\"peek_datum\", &vistk::edge::peek_datum)\n .def(\"pop_datum\", &vistk::edge::pop_datum)\n .def(\"set_required_by_downstream\", &vistk::edge::set_required_by_downstream)\n .def(\"required_by_downstream\", &vistk::edge::required_by_downstream)\n .def(\"set_upstream_process\", &vistk::edge::set_upstream_process)\n .def(\"set_downstream_process\", &vistk::edge::set_downstream_process)\n ;\n}\n\nvistk::datum_t\nedge_datum_datum(vistk::edge_datum_t const& edatum)\n{\n return edatum.get<0>();\n}\n\nvoid\nedge_datum_datum_set(vistk::edge_datum_t& edatum, vistk::datum_t const& dat)\n{\n boost::get<0>(edatum) = dat;\n}\n\nvistk::stamp_t\nedge_datum_stamp(vistk::edge_datum_t const& edatum)\n{\n return edatum.get<1>();\n}\n\nvoid\nedge_datum_stamp_set(vistk::edge_datum_t& edatum, vistk::stamp_t const& st)\n{\n boost::get<1>(edatum) = st;\n}\n\nvoid\ntranslator(vistk::edge_exception const& e)\n{\n PyErr_SetString(PyExc_RuntimeError, e.what());\n}\n<commit_msg>Add docstrings to edge bindings<commit_after>\/*ckwg +5\n * Copyright 2011 by Kitware, Inc. All Rights Reserved. Please refer to\n * KITWARE_LICENSE.TXT for licensing information, or contact General Counsel,\n * Kitware, Inc., 28 Corporate Drive, Clifton Park, NY 12065.\n *\/\n\n#include <vistk\/pipeline\/edge.h>\n#include <vistk\/pipeline\/edge_exception.h>\n#include <vistk\/pipeline\/stamp.h>\n\n#include <boost\/python.hpp>\n#include <boost\/python\/suite\/indexing\/vector_indexing_suite.hpp>\n\n\/**\n * \\file edge.cxx\n *\n * \\brief Python bindings for \\link vistk::edge\\endlink.\n *\/\n\nusing namespace boost::python;\n\nstatic vistk::datum_t edge_datum_datum(vistk::edge_datum_t const& edatum);\nstatic void edge_datum_datum_set(vistk::edge_datum_t& edatum, vistk::datum_t const& dat);\nstatic vistk::stamp_t edge_datum_stamp(vistk::edge_datum_t const& edatum);\nstatic void edge_datum_stamp_set(vistk::edge_datum_t& edatum, vistk::stamp_t const& st);\n\nstatic void translator(vistk::edge_exception const& e);\n\nBOOST_PYTHON_MODULE(edge)\n{\n register_exception_translator<\n vistk::edge_exception>(translator);\n\n class_<vistk::edge_datum_t>(\"EdgeDatum\"\n , no_init)\n .def(init<vistk::datum_t, vistk::stamp_t>())\n .add_property(\"datum\", &edge_datum_datum, &edge_datum_datum_set\n , \"The datum in the packet.\")\n .add_property(\"stamp\", &edge_datum_stamp, &edge_datum_stamp_set\n , \"The stamp of the packet.\")\n ;\n class_<vistk::edge_data_t>(\"EdgeData\"\n , \"A collection of data packets that may be passed through an edge.\")\n .def(vector_indexing_suite<vistk::edge_data_t>())\n ;\n class_<vistk::edges_t>(\"Edges\"\n , \"A collection of edges.\")\n .def(vector_indexing_suite<vistk::edges_t>())\n ;\n\n class_<vistk::edge, vistk::edge_t, boost::noncopyable>(\"Edge\"\n , \"A communication channel between processes.\"\n , no_init)\n .def(init<vistk::config_t>())\n .def(\"makes_dependency\", &vistk::edge::makes_dependency\n , \"Returns True if the edge implies a dependency from downstream on upstream.\")\n .def(\"has_data\", &vistk::edge::has_data\n , \"Returns True if the edge contains data, False otherwise.\")\n .def(\"full_of_data\", &vistk::edge::full_of_data\n , \"Returns True if the edge cannot hold anymore data, False otherwise.\")\n .def(\"datum_count\", &vistk::edge::datum_count\n , \"Returns the number of data packets within the edge.\")\n .def(\"push_datum\", &vistk::edge::push_datum\n , (arg(\"datum\"))\n , \"Pushes a datum packet into the edge.\")\n .def(\"get_datum\", &vistk::edge::get_datum\n , \"Returns the next datum packet from the edge, removing it in the process.\")\n .def(\"peek_datum\", &vistk::edge::peek_datum\n , \"Returns the next datum packet from the edge.\")\n .def(\"pop_datum\", &vistk::edge::pop_datum\n , \"Remove the next datum packet from the edge.\")\n .def(\"set_required_by_downstream\", &vistk::edge::set_required_by_downstream\n , (arg(\"required\"))\n , \"Set whether the data within the edge is required by downstream to work.\")\n .def(\"required_by_downstream\", &vistk::edge::required_by_downstream\n , \"Returns True if the downstream process needs the data in the edge.\")\n .def(\"set_upstream_process\", &vistk::edge::set_upstream_process\n , (arg(\"process\"))\n , \"Set the process which is feeding data into the edge.\")\n .def(\"set_downstream_process\", &vistk::edge::set_downstream_process\n , (arg(\"process\"))\n , \"Set the process which is reading data from the edge.\")\n ;\n}\n\nvistk::datum_t\nedge_datum_datum(vistk::edge_datum_t const& edatum)\n{\n return edatum.get<0>();\n}\n\nvoid\nedge_datum_datum_set(vistk::edge_datum_t& edatum, vistk::datum_t const& dat)\n{\n boost::get<0>(edatum) = dat;\n}\n\nvistk::stamp_t\nedge_datum_stamp(vistk::edge_datum_t const& edatum)\n{\n return edatum.get<1>();\n}\n\nvoid\nedge_datum_stamp_set(vistk::edge_datum_t& edatum, vistk::stamp_t const& st)\n{\n boost::get<1>(edatum) = st;\n}\n\nvoid\ntranslator(vistk::edge_exception const& e)\n{\n PyErr_SetString(PyExc_RuntimeError, e.what());\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"Actor.h\"\nActor::Actor(Model* model, Vector3f const position, Vector3f const rotation) :\n\tmodel(model),\n\tposition(position),\n\trotation(rotation)\n{\n\tdPosition.elementArray[0]=0.0f;\n\tdPosition.elementArray[1]=0.0f;\n\tdPosition.elementArray[2]=0.0f;\n\tdRotation.elementArray[0]=0.0f;\n\tdRotation.elementArray[1]=0.0f;\n\tdRotation.elementArray[2]=0.0f;\n}\nActor::Actor(Model* model, Vector3f const position, Vector3f const dPosition, Vector3f const rotation, Vector3f const dRotation) :\n\tmodel(model),\n\tposition(position),\n\tdPosition(dPosition),\n\trotation(rotation),\n\tdRotation(dRotation)\n{\n}\nActor::Actor(const Actor& actor) :\n\tmodel(actor.model),\n\tposition(actor.position),\n\tdPosition(actor.dPosition),\n\trotation(actor.rotation),\n\tdRotation(actor.dRotation)\n{\n}\nActor::~Actor()\n{\n}\nconst Model& Actor::getModel() const\n{\n\treturn *model;\n}\nconst Vector3f& Actor::getPositionVector3f() const\n{\n\treturn position;\n}\nvoid Actor::tick(double dt)\n{\n\tposition[0] += dPosition[0] * dt;\n\tposition[1] += dPosition[1] * dt;\n\tposition[2] += dPosition[2] * dt;\n\t\n\treturn;\n}\n<commit_msg>fixing build<commit_after>#include \"Actor.h\"\nActor::Actor(Model* model, Vector3f const position, Vector3f const rotation) :\n\tmodel(model),\n\tposition(position),\n\trotation(rotation)\n{\n\tdPosition.elementArray[0]=0.0f;\n\tdPosition.elementArray[1]=0.0f;\n\tdPosition.elementArray[2]=0.0f;\n\tdRotation.elementArray[0]=0.0f;\n\tdRotation.elementArray[1]=0.0f;\n\tdRotation.elementArray[2]=0.0f;\n}\nActor::Actor(Model* model, Vector3f const position, Vector3f const dPosition, Vector3f const rotation, Vector3f const dRotation) :\n\tmodel(model),\n\tposition(position),\n\tdPosition(dPosition),\n\trotation(rotation),\n\tdRotation(dRotation)\n{\n}\nActor::Actor(const Actor& actor) :\n\tmodel(actor.model),\n\tposition(actor.position),\n\tdPosition(actor.dPosition),\n\trotation(actor.rotation),\n\tdRotation(actor.dRotation)\n{\n}\nActor::~Actor()\n{\n}\nconst Model& Actor::getModel() const\n{\n\treturn *model;\n}\nconst Vector3f& Actor::getPositionVector3f() const\n{\n\treturn position;\n}\nvoid Actor::tick(double dt)\n{\n\tposition[0] += dPosition[0] * (float)dt;\n\tposition[1] += dPosition[1] * (float)dt;\n\tposition[2] += dPosition[2] * (float)dt;\n\t\n\treturn;\n}\n<|endoftext|>"} {"text":"<commit_before>\n\/\/ Add this line to Tex: \\newcommand{\\wikilist}[1]{\\iffalse #1 \\fi}\n\n\/\/---------------------------Includes----------------------------------------------\/\/\n#include <stdio.h>\n#include <string>\n#include <list>\n#include <iostream>\n#include <fstream>\n#include <sstream>\n#include <cstring>\n#include <functional>\n\n\n\n\n\/\/---------------------------Struct ItemDef----------------------------------------\/\/\nstruct ItemDef {\n enum Type {\n ID_Item = 0,\n ID_Enum = 1\n };\/\/end Enum\n\n int32_t depth;\n Type type[33];\n std::string options;\n};\/\/end Struct\n\n\n\n\/\/---------------------------Forward Declarations----------------------------------\/\/\nbool addFilename (std::list<std::string> &filenames, const std::string &name);\nstd::string trim (const std::string& str);\nbool getLine (std::istream &in, std::string &out);\nItemDef getListDepth (const std::string &s);\nvoid generateList (std::list<std::string> &block, std::ostream &out);\nbool renameFile (const std::string &oldName, const std::string &newName);\nvoid extendBlockComment (std::istream &in, std::ostream &out);\nvoid extendBlockCommand (std::istream &in, std::ostream &out);\n\n\n\n\/\/---------------------------Start Main--------------------------------------------\/\/\nint main (int argc, char *argv[]) {\n if (argc < 2) {\n printf (\"WikiToTex <file> [<file> ...]\\n\");\n return 0;\n }\n\n std::list<std::string> filenames;\n bool recursive = false;\n\n std::function<void(const std::string&)> recursiveAddFilename = [&filenames,&recursiveAddFilename](const std::string &f) {\n std::ifstream file (f, std::ios::in);\n std::string line;\n\n while (getLine (file, line) ) {\n std::string tline = trim (line);\n std::string name;\n size_t pos;\n\n if ( (pos = tline.find (\"\\\\input{\") ) != std::string::npos)\n name = tline.substr (pos + 7, tline.size () - (pos+7) - 1);\n else if ( (pos = tline.find (\"\\\\include{\") ) != std::string::npos)\n name = tline.substr (pos + 9, tline.size () - (pos+9) - 1);\n\n if (name.size () && addFilename (filenames, name) )\n recursiveAddFilename (name);\n }\/\/end while\n\n file.close ();\n };\/\/end Lambda\n\n for (int32_t i = 1; i < argc; ++i) {\n std::string arg = argv[i];\n if (arg == \"-r\") { \/\/TODO extend\n recursive = true;\n continue;\n }\n\n bool ret = addFilename (filenames, argv[i]);\n\n if (ret && recursive)\n recursiveAddFilename (argv[i]);\n }\/\/end for\n\n for (std::string &filename : filenames) {\n std::ifstream file (filename, std::ios::in);\n std::ostringstream output;\n std::string line;\n bool modified = false;\n\n if (!file.is_open () ) {\n std::cerr << \"file \\\"\" << filename << \"\\\" does not exist.\" << std::endl;\n continue;\n }\n\n\n while (getLine (file, line) ) {\n std::string tline = trim (line);\n if (line == \"%!wikilist\") {\n modified = true;\n extendBlockComment (file, output);\n } else if (tline == \"\\\\wikilist{\") {\n modified = true;\n extendBlockCommand (file, output);\n } else\n output << line << \"\\n\";\n }\n\n file.close ();\n\n if (modified) {\n renameFile (filename, filename + \".bak\");\n\n std::ofstream out (filename, std::ios::out);\n \/\/std::ofstream out (filename + \".tmp\", std::ios::out);\n\n std::string outS = output.str (); \/\/ We want to remove the last linebreak (will summarize on multiple calls)\n\n out << outS.substr (0, outS.size () - 1);\n }\n }\n\n return 0;\n}\/\/end Main\n\n\n\n\/\/---------------------------Start addFilename-------------------------------------\/\/\n\/\/ Append Filename if exist, try combinations\nstatic std::string addFilename_suffix[] = {\"\", \".tex\"};\n\nbool addFilename (std::list<std::string> &filenames, const std::string &name) {\n\/\/printf (\"name: %s\\n\", name.c_str());\n std::string filename;\n\n for (std::string &a : addFilename_suffix) {\n std::string s = name + a;\n\n FILE *f = fopen (s.c_str (), \"r\");\n\n if (f) {\n fclose (f);\n filename = s;\n break;\n }\n }\/\/end for\n\n if (filename.size () ) {\n filenames.push_back (filename);\n return true;\n } else\n return false;\n}\/\/end Fct\n\n\n\n\/\/---------------------------Start trim--------------------------------------------\/\/\n\/\/ http:\/\/stackoverflow.com\/questions\/25829143\/c-trim-whitespace-from-a-string\nstd::string trim (const std::string& str) {\n if (!str.size()) return str;\n size_t first = str.find_first_not_of(' ');\n size_t last = str.find_last_not_of(' ');\n return str.substr(first, (last-first+1));\n}\/\/end Fct\n\n\n\n\/\/---------------------------Start getLine-----------------------------------------\/\/\nbool getLine (std::istream &in, std::string &out) {\n if (in.fail() || in.eof() ) {\n out = \"\";\n return false;\n }\n\n const int32_t maxLength = 8192;\n char buffer[maxLength];\n\n in.getline (buffer, maxLength);\n\n out = buffer;\n\n return true;\n}\/\/end Fct\n\n\n\n\/\/---------------------------Start getListDepth------------------------------------\/\/\nItemDef getListDepth (const std::string &s) {\n ItemDef ret = {0};\n\n for (int32_t i = 0; i < s.size (); ++i) {\n if (s.at(i) == '-') {\n ret.type[ret.depth] = ItemDef::ID_Item;\n ++ret.depth;\n } else if (s.at(i) == '#') {\n ret.type[ret.depth] = ItemDef::ID_Enum;\n ++ret.depth;\n } else\n break;\n }\n\n return ret;\n}\/\/end Fct\n\n\n\n\/\/---------------------------Start extendBlockComment------------------------------\/\/\n#ifdef __linux__\nbool renameFile (const std::string &oldName, const std::string &newName) {\n return !rename (oldName.c_str (), newName.c_str () );\n}\/\/end Fct\n#endif\n\n\n\n\/\/---------------------------Start generateList------------------------------------\/\/\nvoid generateList (std::list<std::string> &block, std::ostream &out) {\n std::string tline;\n int32_t spaces = 3;\n int32_t depth = 0;\n char buffer[100];\n ItemDef defaults[33];\n std::string ItemOpt;\n\n\n out << \"%begin wikilist\\n\";\n\n\n for (std::string &s : block) {\n tline = trim (s);\n\n if (tline[0] == '%') {\n if (tline.find (\"%option\") == 0) {\n std::string opt = trim (tline.substr (7) );\n char num[3] = { opt[0], opt[1], 0 };\n if (num[0] < '0' || num[0] > '9') continue;\n if (num[1] < '0' || num[1] > '9') num[1] = 0;\n uint32_t n = std::stoi (num) - 1;\n if (n < 33) defaults[n].options = trim (opt.substr (1 + (num[1] != 0) ) );\n\n } else if (tline.find (\"%item\") == 0) {\n ItemOpt = trim (tline.substr (5) );\n }\n\n continue;\n }\n\n ItemDef id = getListDepth (tline);\n\n if (id.depth == 0) {\n out << tline << \"\\n\";\n continue;\n }\n\n\n while (id.depth > depth) {\n memset (buffer, ' ', depth * spaces); buffer[depth * spaces] = 0;\n out << buffer << \"\\\\begin{itemize}\";\n if (defaults[depth].options.size () )\n out << \"[\" << defaults[depth].options << \"]\";\n out << \"\\n\";\n ++depth;\n }\n\n while (id.depth < depth) {\n --depth;\n memset (buffer, ' ', depth * spaces); buffer[depth * spaces] = 0;\n out << buffer << \"\\\\end{itemize}\\n\";\n ItemOpt.clear ();\n }\n\n memset (buffer, ' ', depth * spaces); buffer[depth * spaces] = 0;\n out << buffer << \"\\\\item\";\n if (ItemOpt.size () )\n out << \"[\" << ItemOpt << \"]\";\n out << \" \" << trim (tline.substr (id.depth) ) << \"\\n\";\n }\/\/end for\n\n while (0 < depth) {\n --depth;\n memset (buffer, ' ', depth * spaces); buffer[depth * spaces] = 0;\n out << buffer << \"\\\\end{itemize}\\n\";\n }\n\n out << \"%end wikilist\\n\";\n}\/\/end Fct\n\n\n\n\/\/---------------------------Start extendBlockComment------------------------------\/\/\nvoid extendBlockComment (std::istream &in, std::ostream &out) {\n std::string line;\n std::string eline;\n std::list<std::string> block;\n block.push_back (\"%!wikilist\");\n bool cleanup = false;\n\n while (getLine (in, line) ) {\n if (cleanup) {\n if (line == \"%end wikilist\")\n break;\n } else if (line.size () == 0) {\n break;\n } else if (line.at (0) == '%') {\n block.push_back (line);\n } else if (line == \"%begin wikilist\")\n cleanup = true;\n else {\n eline = line + \"\\n\";\n break;\n }\n }\/\/end while\n\n for (std::string &s : block)\n out << s << \"\\n\";\n\n block.pop_front (); \/\/ Remove initialzation line\n\n generateList (block, out);\n\n if (eline.size () )\n out << eline;\n}\/\/end Fct\n\n\n\n\/\/---------------------------Start extendBlockCommand------------------------------\/\/\nvoid extendBlockCommand (std::istream &in, std::ostream &out) {\n std::string line;\n std::string tline;\n std::string eline;\n std::list<std::string> block;\n block.push_back (\"\\\\wikilist{\");\n bool cleanup = false;\n bool append = true;\n\n while (getLine (in, line) ) {\n tline = trim (line);\n\n if (cleanup) {\n if (line == \"%end wikilist\")\n break;\n } else if (append && !tline.size () ) {\n } else if (append && tline.at (0) == '}') {\n append = false;\n } else if (!append && line == \"%begin wikilist\") {\n cleanup = true;\n } else if (append) {\n block.push_back (line);\n } else {\n eline = line + \"\\n\";\n break;\n }\n }\/\/end while\n\n block.push_back (\"}\");\n\n for (std::string &s : block)\n out << s << \"\\n\";\n\n block.pop_front (); \/\/ Remove initialzation line\n block.pop_back (); \/\/ Remove closing line\n\n generateList (block, out);\n\n if (eline.size () )\n out << eline;\n}\/\/end Fct\n<commit_msg>Fix for commented form.<commit_after>\n\/\/ Add this line to Tex: \\newcommand{\\wikilist}[1]{\\iffalse #1 \\fi}\n\n\/\/---------------------------Includes----------------------------------------------\/\/\n#include <stdio.h>\n#include <string>\n#include <list>\n#include <iostream>\n#include <fstream>\n#include <sstream>\n#include <cstring>\n#include <functional>\n\n\n\n\n\/\/---------------------------Struct ItemDef----------------------------------------\/\/\nstruct ItemDef {\n enum Type {\n ID_Item = 0,\n ID_Enum = 1\n };\/\/end Enum\n\n int32_t depth;\n Type type[33];\n std::string options;\n};\/\/end Struct\n\n\n\n\/\/---------------------------Forward Declarations----------------------------------\/\/\nbool addFilename (std::list<std::string> &filenames, const std::string &name);\nstd::string trim (const std::string& str);\nbool getLine (std::istream &in, std::string &out);\nItemDef getListDepth (const std::string &s);\nvoid generateList (std::list<std::string> &block, std::ostream &out);\nbool renameFile (const std::string &oldName, const std::string &newName);\nvoid extendBlockComment (std::istream &in, std::ostream &out);\nvoid extendBlockCommand (std::istream &in, std::ostream &out);\n\n\n\n\/\/---------------------------Start Main--------------------------------------------\/\/\nint main (int argc, char *argv[]) {\n if (argc < 2) {\n printf (\"WikiToTex <file> [<file> ...]\\n\");\n return 0;\n }\n\n std::list<std::string> filenames;\n bool recursive = false;\n\n std::function<void(const std::string&)> recursiveAddFilename = [&filenames,&recursiveAddFilename](const std::string &f) {\n std::ifstream file (f, std::ios::in);\n std::string line;\n\n while (getLine (file, line) ) {\n std::string tline = trim (line);\n std::string name;\n size_t pos;\n\n if ( (pos = tline.find (\"\\\\input{\") ) != std::string::npos)\n name = tline.substr (pos + 7, tline.size () - (pos+7) - 1);\n else if ( (pos = tline.find (\"\\\\include{\") ) != std::string::npos)\n name = tline.substr (pos + 9, tline.size () - (pos+9) - 1);\n\n if (name.size () && addFilename (filenames, name) )\n recursiveAddFilename (name);\n }\/\/end while\n\n file.close ();\n };\/\/end Lambda\n\n for (int32_t i = 1; i < argc; ++i) {\n std::string arg = argv[i];\n if (arg == \"-r\") { \/\/TODO extend\n recursive = true;\n continue;\n }\n\n bool ret = addFilename (filenames, argv[i]);\n\n if (ret && recursive)\n recursiveAddFilename (argv[i]);\n }\/\/end for\n\n for (std::string &filename : filenames) {\n std::ifstream file (filename, std::ios::in);\n std::ostringstream output;\n std::string line;\n bool modified = false;\n\n if (!file.is_open () ) {\n std::cerr << \"file \\\"\" << filename << \"\\\" does not exist.\" << std::endl;\n continue;\n }\n\n\n while (getLine (file, line) ) {\n std::string tline = trim (line);\n if (line == \"%!wikilist\") {\n modified = true;\n extendBlockComment (file, output);\n } else if (tline == \"\\\\wikilist{\") {\n modified = true;\n extendBlockCommand (file, output);\n } else\n output << line << \"\\n\";\n }\n\n file.close ();\n\n if (modified) {\n renameFile (filename, filename + \".bak\");\n\n std::ofstream out (filename, std::ios::out);\n \/\/std::ofstream out (filename + \".tmp\", std::ios::out);\n\n std::string outS = output.str (); \/\/ We want to remove the last linebreak (will summarize on multiple calls)\n\n out << outS.substr (0, outS.size () - 1);\n }\n }\n\n return 0;\n}\/\/end Main\n\n\n\n\/\/---------------------------Start addFilename-------------------------------------\/\/\n\/\/ Append Filename if exist, try combinations\nstatic std::string addFilename_suffix[] = {\"\", \".tex\"};\n\nbool addFilename (std::list<std::string> &filenames, const std::string &name) {\n\/\/printf (\"name: %s\\n\", name.c_str());\n std::string filename;\n\n for (std::string &a : addFilename_suffix) {\n std::string s = name + a;\n\n FILE *f = fopen (s.c_str (), \"r\");\n\n if (f) {\n fclose (f);\n filename = s;\n break;\n }\n }\/\/end for\n\n if (filename.size () ) {\n filenames.push_back (filename);\n return true;\n } else\n return false;\n}\/\/end Fct\n\n\n\n\/\/---------------------------Start trim--------------------------------------------\/\/\n\/\/ http:\/\/stackoverflow.com\/questions\/25829143\/c-trim-whitespace-from-a-string\nstd::string trim (const std::string& str) {\n if (!str.size()) return str;\n size_t first = str.find_first_not_of(' ');\n size_t last = str.find_last_not_of(' ');\n return str.substr(first, (last-first+1));\n}\/\/end Fct\n\n\n\n\/\/---------------------------Start getLine-----------------------------------------\/\/\nbool getLine (std::istream &in, std::string &out) {\n if (in.fail() || in.eof() ) {\n out = \"\";\n return false;\n }\n\n const int32_t maxLength = 8192;\n char buffer[maxLength];\n\n in.getline (buffer, maxLength);\n\n out = buffer;\n\n return true;\n}\/\/end Fct\n\n\n\n\/\/---------------------------Start getListDepth------------------------------------\/\/\nItemDef getListDepth (const std::string &s) {\n ItemDef ret = {0};\n\n for (int32_t i = 0; i < s.size (); ++i) {\n if (s.at(i) == '-') {\n ret.type[ret.depth] = ItemDef::ID_Item;\n ++ret.depth;\n } else if (s.at(i) == '#') {\n ret.type[ret.depth] = ItemDef::ID_Enum;\n ++ret.depth;\n } else\n break;\n }\n\n return ret;\n}\/\/end Fct\n\n\n\n\/\/---------------------------Start extendBlockComment------------------------------\/\/\n#ifdef __linux__\nbool renameFile (const std::string &oldName, const std::string &newName) {\n return !rename (oldName.c_str (), newName.c_str () );\n}\/\/end Fct\n#endif\n\n\n\n\/\/---------------------------Start generateList------------------------------------\/\/\nvoid generateList (std::list<std::string> &block, std::ostream &out) {\n std::string tline;\n int32_t spaces = 3;\n int32_t depth = 0;\n char buffer[100];\n ItemDef defaults[33];\n std::string ItemOpt;\n\n\n out << \"%begin wikilist\\n\";\n\n\n for (std::string &s : block) {\n tline = trim (s);\n\n if (tline[0] == '%') {\n if (tline.find (\"%option\") == 0) {\n std::string opt = trim (tline.substr (7) );\n char num[3] = { opt[0], opt[1], 0 };\n if (num[0] < '0' || num[0] > '9') continue;\n if (num[1] < '0' || num[1] > '9') num[1] = 0;\n uint32_t n = std::stoi (num) - 1;\n if (n < 33) defaults[n].options = trim (opt.substr (1 + (num[1] != 0) ) );\n\n } else if (tline.find (\"%item\") == 0) {\n ItemOpt = trim (tline.substr (5) );\n }\n\n continue;\n }\n\n ItemDef id = getListDepth (tline);\n\n if (id.depth == 0) {\n out << tline << \"\\n\";\n continue;\n }\n\n\n while (id.depth > depth) {\n memset (buffer, ' ', depth * spaces); buffer[depth * spaces] = 0;\n out << buffer << \"\\\\begin{itemize}\";\n if (defaults[depth].options.size () )\n out << \"[\" << defaults[depth].options << \"]\";\n out << \"\\n\";\n ++depth;\n }\n\n while (id.depth < depth) {\n --depth;\n memset (buffer, ' ', depth * spaces); buffer[depth * spaces] = 0;\n out << buffer << \"\\\\end{itemize}\\n\";\n ItemOpt.clear ();\n }\n\n memset (buffer, ' ', depth * spaces); buffer[depth * spaces] = 0;\n out << buffer << \"\\\\item\";\n if (ItemOpt.size () )\n out << \"[\" << ItemOpt << \"]\";\n out << \" \" << trim (tline.substr (id.depth) ) << \"\\n\";\n }\/\/end for\n\n while (0 < depth) {\n --depth;\n memset (buffer, ' ', depth * spaces); buffer[depth * spaces] = 0;\n out << buffer << \"\\\\end{itemize}\\n\";\n }\n\n out << \"%end wikilist\\n\";\n}\/\/end Fct\n\n\n\n\/\/---------------------------Start extendBlockComment------------------------------\/\/\nvoid extendBlockComment (std::istream &in, std::ostream &out) {\n std::string line;\n std::string eline;\n std::list<std::string> block;\n block.push_back (\"%!wikilist\");\n bool cleanup = false;\n\n while (getLine (in, line) ) {\n if (cleanup) {\n if (line == \"%end wikilist\")\n break;\n } else if (line.size () == 0) {\n break;\n } else if (line.at (0) == '%') {\n block.push_back (line.substr (1) );\n } else if (line == \"%begin wikilist\")\n cleanup = true;\n else {\n eline = line + \"\\n\";\n break;\n }\n }\/\/end while\n\n for (std::string &s : block)\n out << s << \"\\n\";\n\n block.pop_front (); \/\/ Remove initialzation line\n\n generateList (block, out);\n\n if (eline.size () )\n out << eline;\n}\/\/end Fct\n\n\n\n\/\/---------------------------Start extendBlockCommand------------------------------\/\/\nvoid extendBlockCommand (std::istream &in, std::ostream &out) {\n std::string line;\n std::string tline;\n std::string eline;\n std::list<std::string> block;\n block.push_back (\"\\\\wikilist{\");\n bool cleanup = false;\n bool append = true;\n\n while (getLine (in, line) ) {\n tline = trim (line);\n\n if (cleanup) {\n if (line == \"%end wikilist\")\n break;\n } else if (append && !tline.size () ) {\n } else if (append && tline.at (0) == '}') {\n append = false;\n } else if (!append && line == \"%begin wikilist\") {\n cleanup = true;\n } else if (append) {\n block.push_back (line);\n } else {\n eline = line + \"\\n\";\n break;\n }\n }\/\/end while\n\n block.push_back (\"}\");\n\n for (std::string &s : block)\n out << s << \"\\n\";\n\n block.pop_front (); \/\/ Remove initialzation line\n block.pop_back (); \/\/ Remove closing line\n\n generateList (block, out);\n\n if (eline.size () )\n out << eline;\n}\/\/end Fct\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright 2013 Facebook, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"folly\/PackedSyncPtr.h\"\n\n#include <cinttypes>\n#include <gtest\/gtest.h>\n#include <thread>\n#include <unordered_map>\n#include <utility>\n\nusing folly::PackedSyncPtr;\n\nnamespace {\n\n\/\/ Compile time check for packability. This requires that\n\/\/ PackedSyncPtr is a POD struct on gcc.\nstruct ignore { PackedSyncPtr<int> foo; char c; } __attribute__((packed));\nstatic_assert(sizeof(ignore) == 9, \"PackedSyncPtr wasn't packable\");\n\n}\n\nTEST(PackedSyncPtr, Basic) {\n PackedSyncPtr<std::pair<int,int>> sp;\n sp.init(new std::pair<int,int>[2]);\n EXPECT_EQ(sizeof(sp), 8);\n sp->first = 5;\n EXPECT_EQ(sp[0].first, 5);\n sp[1].second = 7;\n EXPECT_EQ(sp[1].second, 7);\n sp.lock();\n EXPECT_EQ(sp[1].second, 7);\n sp[0].first = 9;\n EXPECT_EQ(sp->first, 9);\n sp.unlock();\n EXPECT_EQ((sp.get() + 1)->second, 7);\n\n sp.lock();\n EXPECT_EQ(sp.extra(), 0);\n sp.setExtra(0x13);\n EXPECT_EQ(sp.extra(), 0x13);\n EXPECT_EQ((sp.get() + 1)->second, 7);\n delete sp.get();\n auto newP = new std::pair<int,int>();\n sp.set(newP);\n EXPECT_EQ(sp.extra(), 0x13);\n EXPECT_EQ(sp.get(), newP);\n sp.unlock();\n}\n\n\/\/ Here we use the PackedSyncPtr to lock the whole SyncVec (base, *base, and sz)\ntemplate<typename T>\nstruct SyncVec {\n PackedSyncPtr<T> base;\n SyncVec() { base.init(); }\n void push_back(const T& t) {\n base.set((T*) realloc(base.get(),\n (base.extra() + 1) * sizeof(T)));\n base[base.extra()] = t;\n base.setExtra(base.extra() + 1);\n }\n void lock() {\n base.lock();\n }\n void unlock() {\n base.unlock();\n }\n\n T* begin() const { return base.get(); }\n T* end() const { return base.get() + base.extra(); }\n};\ntypedef SyncVec<intptr_t> VecT;\ntypedef std::unordered_map<int64_t, VecT> Map;\nconst int mapCap = 1317;\nconst int nthrs = 297;\nstatic Map map(mapCap);\n\n\/\/ Each app thread inserts it's ID into every vec in map\n\/\/ map is read only, so doesn't need any additional locking\nvoid appThread(intptr_t id) {\n for (auto& kv : map) {\n kv.second.lock();\n kv.second.push_back(id);\n kv.second.unlock();\n }\n}\n\nTEST(PackedSyncPtr, Application) {\n for (int64_t i = 0; i < mapCap \/ 2; ++i) {\n map.insert(std::make_pair(i, VecT()));\n }\n std::vector<std::thread> thrs;\n for (intptr_t i = 0; i < nthrs; i++) {\n thrs.push_back(std::thread(appThread, i));\n }\n for (auto& t : thrs) {\n t.join();\n }\n\n for (auto& kv : map) {\n \/\/ Make sure every thread successfully inserted it's ID into every vec\n std::set<intptr_t> idsFound;\n for (auto& elem : kv.second) {\n EXPECT_TRUE(idsFound.insert(elem).second); \/\/ check for dups\n }\n EXPECT_EQ(idsFound.size(), nthrs); \/\/ check they are all there\n }\n}\n\nTEST(PackedSyncPtr, extraData) {\n PackedSyncPtr<int> p;\n p.init();\n int* unaligned = reinterpret_cast<int*>(0xf003);\n p.lock();\n p.set(unaligned);\n uintptr_t* bytes = reinterpret_cast<uintptr_t*>(&p);\n LOG(INFO) << \"Bytes integer is: 0x\" << std::hex << *bytes;\n EXPECT_EQ(p.get(), unaligned);\n p.unlock();\n}\n<commit_msg>folly: avoid ASAN-detected new[] vs \"delete\" mismatch<commit_after>\/*\n * Copyright 2013 Facebook, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"folly\/PackedSyncPtr.h\"\n\n#include <cinttypes>\n#include <gtest\/gtest.h>\n#include <thread>\n#include <unordered_map>\n#include <utility>\n\nusing folly::PackedSyncPtr;\n\nnamespace {\n\n\/\/ Compile time check for packability. This requires that\n\/\/ PackedSyncPtr is a POD struct on gcc.\nstruct ignore { PackedSyncPtr<int> foo; char c; } __attribute__((packed));\nstatic_assert(sizeof(ignore) == 9, \"PackedSyncPtr wasn't packable\");\n\n}\n\nTEST(PackedSyncPtr, Basic) {\n PackedSyncPtr<std::pair<int,int>> sp;\n sp.init(new std::pair<int,int>[2]);\n EXPECT_EQ(sizeof(sp), 8);\n sp->first = 5;\n EXPECT_EQ(sp[0].first, 5);\n sp[1].second = 7;\n EXPECT_EQ(sp[1].second, 7);\n sp.lock();\n EXPECT_EQ(sp[1].second, 7);\n sp[0].first = 9;\n EXPECT_EQ(sp->first, 9);\n sp.unlock();\n EXPECT_EQ((sp.get() + 1)->second, 7);\n\n sp.lock();\n EXPECT_EQ(sp.extra(), 0);\n sp.setExtra(0x13);\n EXPECT_EQ(sp.extra(), 0x13);\n EXPECT_EQ((sp.get() + 1)->second, 7);\n delete[] sp.get();\n auto newP = new std::pair<int,int>();\n sp.set(newP);\n EXPECT_EQ(sp.extra(), 0x13);\n EXPECT_EQ(sp.get(), newP);\n sp.unlock();\n}\n\n\/\/ Here we use the PackedSyncPtr to lock the whole SyncVec (base, *base, and sz)\ntemplate<typename T>\nstruct SyncVec {\n PackedSyncPtr<T> base;\n SyncVec() { base.init(); }\n void push_back(const T& t) {\n base.set((T*) realloc(base.get(),\n (base.extra() + 1) * sizeof(T)));\n base[base.extra()] = t;\n base.setExtra(base.extra() + 1);\n }\n void lock() {\n base.lock();\n }\n void unlock() {\n base.unlock();\n }\n\n T* begin() const { return base.get(); }\n T* end() const { return base.get() + base.extra(); }\n};\ntypedef SyncVec<intptr_t> VecT;\ntypedef std::unordered_map<int64_t, VecT> Map;\nconst int mapCap = 1317;\nconst int nthrs = 297;\nstatic Map map(mapCap);\n\n\/\/ Each app thread inserts it's ID into every vec in map\n\/\/ map is read only, so doesn't need any additional locking\nvoid appThread(intptr_t id) {\n for (auto& kv : map) {\n kv.second.lock();\n kv.second.push_back(id);\n kv.second.unlock();\n }\n}\n\nTEST(PackedSyncPtr, Application) {\n for (int64_t i = 0; i < mapCap \/ 2; ++i) {\n map.insert(std::make_pair(i, VecT()));\n }\n std::vector<std::thread> thrs;\n for (intptr_t i = 0; i < nthrs; i++) {\n thrs.push_back(std::thread(appThread, i));\n }\n for (auto& t : thrs) {\n t.join();\n }\n\n for (auto& kv : map) {\n \/\/ Make sure every thread successfully inserted it's ID into every vec\n std::set<intptr_t> idsFound;\n for (auto& elem : kv.second) {\n EXPECT_TRUE(idsFound.insert(elem).second); \/\/ check for dups\n }\n EXPECT_EQ(idsFound.size(), nthrs); \/\/ check they are all there\n }\n}\n\nTEST(PackedSyncPtr, extraData) {\n PackedSyncPtr<int> p;\n p.init();\n int* unaligned = reinterpret_cast<int*>(0xf003);\n p.lock();\n p.set(unaligned);\n uintptr_t* bytes = reinterpret_cast<uintptr_t*>(&p);\n LOG(INFO) << \"Bytes integer is: 0x\" << std::hex << *bytes;\n EXPECT_EQ(p.get(), unaligned);\n p.unlock();\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ SciTE - Scintilla based Text Editor\n\/** @file GUIWin.cxx\n ** Interface to platform GUI facilities.\n ** Split off from Scintilla's Platform.h to avoid SciTE depending on implementation of Scintilla.\n **\/\n\/\/ Copyright 1998-2010 by Neil Hodgson <neilh@scintilla.org>\n\/\/ The License.txt file describes the conditions under which this software may be distributed.\n\n#include <stdio.h>\n#include <time.h>\n\n#include <string>\n#include <vector>\n\n#ifdef __MINGW_H\n#define _WIN32_IE\t0x0400\n#endif\n\n#undef _WIN32_WINNT\n#define _WIN32_WINNT 0x0500\n#ifdef _MSC_VER\n\/\/ windows.h, et al, use a lot of nameless struct\/unions - can't fix it, so allow it\n#pragma warning(disable: 4201)\n#endif\n#include <windows.h>\n#ifdef _MSC_VER\n\/\/ okay, that's done, don't allow it in our code\n#pragma warning(default: 4201)\n#pragma warning(disable: 4244)\n#endif\n\n#include \"Scintilla.h\"\n#include \"GUI.h\"\n\nnamespace GUI {\n\nenum { SURROGATE_LEAD_FIRST = 0xD800 };\nenum { SURROGATE_TRAIL_FIRST = 0xDC00 };\nenum { SURROGATE_TRAIL_LAST = 0xDFFF };\n\nstatic unsigned int UTF8Length(const wchar_t *uptr, size_t tlen) {\n\tunsigned int len = 0;\n\tfor (size_t i = 0; i < tlen && uptr[i];) {\n\t\tunsigned int uch = uptr[i];\n\t\tif (uch < 0x80) {\n\t\t\tlen++;\n\t\t} else if (uch < 0x800) {\n\t\t\tlen += 2;\n\t\t} else if ((uch >= SURROGATE_LEAD_FIRST) &&\n\t\t\t(uch <= SURROGATE_TRAIL_LAST)) {\n\t\t\tlen += 4;\n\t\t\ti++;\n\t\t} else {\n\t\t\tlen += 3;\n\t\t}\n\t\ti++;\n\t}\n\treturn len;\n}\n\nstatic void UTF8FromUTF16(const wchar_t *uptr, size_t tlen, char *putf, size_t len) {\n\tint k = 0;\n\tfor (size_t i = 0; i < tlen && uptr[i];) {\n\t\tunsigned int uch = uptr[i];\n\t\tif (uch < 0x80) {\n\t\t\tputf[k++] = static_cast<char>(uch);\n\t\t} else if (uch < 0x800) {\n\t\t\tputf[k++] = static_cast<char>(0xC0 | (uch >> 6));\n\t\t\tputf[k++] = static_cast<char>(0x80 | (uch & 0x3f));\n\t\t} else if ((uch >= SURROGATE_LEAD_FIRST) &&\n\t\t\t(uch <= SURROGATE_TRAIL_LAST)) {\n\t\t\t\/\/ Half a surrogate pair\n\t\t\ti++;\n\t\t\tunsigned int xch = 0x10000 + ((uch & 0x3ff) << 10) + (uptr[i] & 0x3ff);\n\t\t\tputf[k++] = static_cast<char>(0xF0 | (xch >> 18));\n\t\t\tputf[k++] = static_cast<char>(0x80 | ((xch >> 12) & 0x3f));\n\t\t\tputf[k++] = static_cast<char>(0x80 | ((xch >> 6) & 0x3f));\n\t\t\tputf[k++] = static_cast<char>(0x80 | (xch & 0x3f));\n\t\t} else {\n\t\t\tputf[k++] = static_cast<char>(0xE0 | (uch >> 12));\n\t\t\tputf[k++] = static_cast<char>(0x80 | ((uch >> 6) & 0x3f));\n\t\t\tputf[k++] = static_cast<char>(0x80 | (uch & 0x3f));\n\t\t}\n\t\ti++;\n\t}\n\tputf[len] = '\\0';\n}\n\nstatic size_t UTF16Length(const char *s, unsigned int len) {\n\tsize_t ulen = 0;\n\tsize_t charLen;\n\tfor (size_t i=0; i<len;) {\n\t\tunsigned char ch = static_cast<unsigned char>(s[i]);\n\t\tif (ch < 0x80) {\n\t\t\tcharLen = 1;\n\t\t} else if (ch < 0x80 + 0x40 + 0x20) {\n\t\t\tcharLen = 2;\n\t\t} else if (ch < 0x80 + 0x40 + 0x20 + 0x10) {\n\t\t\tcharLen = 3;\n\t\t} else {\n\t\t\tcharLen = 4;\n\t\t\tulen++;\n\t\t}\n\t\ti += charLen;\n\t\tulen++;\n\t}\n\treturn ulen;\n}\n\nstatic size_t UTF16FromUTF8(const char *s, size_t len, gui_char *tbuf, size_t tlen) {\n\tsize_t ui=0;\n\tconst unsigned char *us = reinterpret_cast<const unsigned char *>(s);\n\tsize_t i=0;\n\twhile ((i<len) && (ui<tlen)) {\n\t\tunsigned char ch = us[i++];\n\t\tif (ch < 0x80) {\n\t\t\ttbuf[ui] = ch;\n\t\t} else if (ch < 0x80 + 0x40 + 0x20) {\n\t\t\ttbuf[ui] = static_cast<wchar_t>((ch & 0x1F) << 6);\n\t\t\tch = us[i++];\n\t\t\ttbuf[ui] = static_cast<wchar_t>(tbuf[ui] + (ch & 0x7F));\n\t\t} else if (ch < 0x80 + 0x40 + 0x20 + 0x10) {\n\t\t\ttbuf[ui] = static_cast<wchar_t>((ch & 0xF) << 12);\n\t\t\tch = us[i++];\n\t\t\ttbuf[ui] = static_cast<wchar_t>(tbuf[ui] + ((ch & 0x7F) << 6));\n\t\t\tch = us[i++];\n\t\t\ttbuf[ui] = static_cast<wchar_t>(tbuf[ui] + (ch & 0x7F));\n\t\t} else {\n\t\t\t\/\/ Outside the BMP so need two surrogates\n\t\t\tint val = (ch & 0x7) << 18;\n\t\t\tch = us[i++];\n\t\t\tval += (ch & 0x3F) << 12;\n\t\t\tch = us[i++];\n\t\t\tval += (ch & 0x3F) << 6;\n\t\t\tch = us[i++];\n\t\t\tval += (ch & 0x3F);\n\t\t\ttbuf[ui] = static_cast<wchar_t>(((val - 0x10000) >> 10) + SURROGATE_LEAD_FIRST);\n\t\t\tui++;\n\t\t\ttbuf[ui] = static_cast<wchar_t>((val & 0x3ff) + SURROGATE_TRAIL_FIRST);\n\t\t}\n\t\tui++;\n\t}\n\treturn ui;\n}\n\ngui_string StringFromUTF8(const char *s) {\n\tsize_t sLen = s ? strlen(s) : 0;\n\tsize_t wideLen = UTF16Length(s, static_cast<int>(sLen));\n\tstd::vector<gui_char> vgc(wideLen + 1);\n\tsize_t outLen = UTF16FromUTF8(s, sLen, &vgc[0], wideLen);\n\tvgc[outLen] = 0;\n\treturn gui_string(&vgc[0], outLen);\n}\n\nstd::string UTF8FromString(const gui_string &s) {\n\tsize_t sLen = s.size();\n\tsize_t narrowLen = UTF8Length(s.c_str(), sLen);\n\tstd::vector<char> vc(narrowLen + 1);\n\tUTF8FromUTF16(s.c_str(), sLen, &vc[0], narrowLen);\n\treturn std::string(&vc[0], narrowLen);\n}\n\ngui_string StringFromInteger(int i) {\n\tchar number[32];\n\tsprintf(number, \"%0d\", i);\n\tgui_char gnumber[32];\n\tsize_t n=0;\n\twhile (number[n]) {\n\t\tgnumber[n] = static_cast<gui_char>(number[n]);\n\t\tn++;\n\t}\n\tgnumber[n] = 0;\n\treturn gui_string(gnumber);\n}\n\nvoid Window::Destroy() {\n\tif (wid)\n\t\t::DestroyWindow(reinterpret_cast<HWND>(wid));\n\twid = 0;\n}\n\nbool Window::HasFocus() {\n\treturn ::GetFocus() == wid;\n}\n\nRectangle Window::GetPosition() {\n\tRECT rc;\n\t::GetWindowRect(reinterpret_cast<HWND>(wid), &rc);\n\treturn Rectangle(rc.left, rc.top, rc.right, rc.bottom);\n}\n\nvoid Window::SetPosition(Rectangle rc) {\n\t::SetWindowPos(reinterpret_cast<HWND>(wid),\n\t\t0, rc.left, rc.top, rc.Width(), rc.Height(), SWP_NOZORDER|SWP_NOACTIVATE);\n}\n\nRectangle Window::GetClientPosition() {\n\tRECT rc={0,0,0,0};\n\tif (wid)\n\t\t::GetClientRect(reinterpret_cast<HWND>(wid), &rc);\n\treturn Rectangle(rc.left, rc.top, rc.right, rc.bottom);\n}\n\nvoid Window::Show(bool show) {\n\tif (show)\n\t\t::ShowWindow(reinterpret_cast<HWND>(wid), SW_SHOWNOACTIVATE);\n\telse\n\t\t::ShowWindow(reinterpret_cast<HWND>(wid), SW_HIDE);\n}\n\nvoid Window::InvalidateAll() {\n\t::InvalidateRect(reinterpret_cast<HWND>(wid), NULL, FALSE);\n}\n\nvoid Window::SetTitle(const gui_char *s) {\n\t::SetWindowTextW(reinterpret_cast<HWND>(wid), s);\n}\n\nvoid Menu::CreatePopUp() {\n\tDestroy();\n\tmid = ::CreatePopupMenu();\n}\n\nvoid Menu::Destroy() {\n\tif (mid)\n\t\t::DestroyMenu(reinterpret_cast<HMENU>(mid));\n\tmid = 0;\n}\n\nvoid Menu::Show(Point pt, Window &w) {\n\t::TrackPopupMenu(reinterpret_cast<HMENU>(mid),\n\t\t0, pt.x - 4, pt.y, 0,\n\t\treinterpret_cast<HWND>(w.GetID()), NULL);\n\tDestroy();\n}\n\nstatic bool initialisedET = false;\nstatic bool usePerformanceCounter = false;\nstatic LARGE_INTEGER frequency;\n\nElapsedTime::ElapsedTime() {\n\tif (!initialisedET) {\n\t\tusePerformanceCounter = ::QueryPerformanceFrequency(&frequency) != 0;\n\t\tinitialisedET = true;\n\t}\n\tif (usePerformanceCounter) {\n\t\tLARGE_INTEGER timeVal;\n\t\t::QueryPerformanceCounter(&timeVal);\n\t\tbigBit = timeVal.HighPart;\n\t\tlittleBit = timeVal.LowPart;\n\t} else {\n\t\tbigBit = clock();\n\t}\n}\n\ndouble ElapsedTime::Duration(bool reset) {\n\tdouble result;\n\tlong endBigBit;\n\tlong endLittleBit;\n\n\tif (usePerformanceCounter) {\n\t\tLARGE_INTEGER lEnd;\n\t\t::QueryPerformanceCounter(&lEnd);\n\t\tendBigBit = lEnd.HighPart;\n\t\tendLittleBit = lEnd.LowPart;\n\t\tLARGE_INTEGER lBegin;\n\t\tlBegin.HighPart = bigBit;\n\t\tlBegin.LowPart = littleBit;\n\t\tdouble elapsed = lEnd.QuadPart - lBegin.QuadPart;\n\t\tresult = elapsed \/ static_cast<double>(frequency.QuadPart);\n\t} else {\n\t\tendBigBit = clock();\n\t\tendLittleBit = 0;\n\t\tdouble elapsed = endBigBit - bigBit;\n\t\tresult = elapsed \/ CLOCKS_PER_SEC;\n\t}\n\tif (reset) {\n\t\tbigBit = endBigBit;\n\t\tlittleBit = endLittleBit;\n\t}\n\treturn result;\n}\n\nsptr_t ScintillaWindow::Send(unsigned int msg, uptr_t wParam, sptr_t lParam) {\n\treturn ::SendMessage(reinterpret_cast<HWND>(GetID()), msg, wParam, lParam);\n}\n\nsptr_t ScintillaWindow::SendPointer(unsigned int msg, uptr_t wParam, void *lParam) {\n\treturn ::SendMessage(reinterpret_cast<HWND>(GetID()), msg, wParam, reinterpret_cast<LPARAM>(lParam));\n}\n\nbool IsDBCSLeadByte(int codePage, char ch) {\n\tif (SC_CP_UTF8 == codePage)\n\t\t\/\/ For lexing, all characters >= 0x80 are treated the\n\t\t\/\/ same so none is considered a lead byte.\n\t\treturn false;\n\telse\n\t\treturn ::IsDBCSLeadByteEx(codePage, ch) != 0;\n}\n\n}\n<commit_msg>Ensure fully initialized. From Coverity warnings.<commit_after>\/\/ SciTE - Scintilla based Text Editor\n\/** @file GUIWin.cxx\n ** Interface to platform GUI facilities.\n ** Split off from Scintilla's Platform.h to avoid SciTE depending on implementation of Scintilla.\n **\/\n\/\/ Copyright 1998-2010 by Neil Hodgson <neilh@scintilla.org>\n\/\/ The License.txt file describes the conditions under which this software may be distributed.\n\n#include <stdio.h>\n#include <time.h>\n\n#include <string>\n#include <vector>\n\n#ifdef __MINGW_H\n#define _WIN32_IE\t0x0400\n#endif\n\n#undef _WIN32_WINNT\n#define _WIN32_WINNT 0x0500\n#ifdef _MSC_VER\n\/\/ windows.h, et al, use a lot of nameless struct\/unions - can't fix it, so allow it\n#pragma warning(disable: 4201)\n#endif\n#include <windows.h>\n#ifdef _MSC_VER\n\/\/ okay, that's done, don't allow it in our code\n#pragma warning(default: 4201)\n#pragma warning(disable: 4244)\n#endif\n\n#include \"Scintilla.h\"\n#include \"GUI.h\"\n\nnamespace GUI {\n\nenum { SURROGATE_LEAD_FIRST = 0xD800 };\nenum { SURROGATE_TRAIL_FIRST = 0xDC00 };\nenum { SURROGATE_TRAIL_LAST = 0xDFFF };\n\nstatic unsigned int UTF8Length(const wchar_t *uptr, size_t tlen) {\n\tunsigned int len = 0;\n\tfor (size_t i = 0; i < tlen && uptr[i];) {\n\t\tunsigned int uch = uptr[i];\n\t\tif (uch < 0x80) {\n\t\t\tlen++;\n\t\t} else if (uch < 0x800) {\n\t\t\tlen += 2;\n\t\t} else if ((uch >= SURROGATE_LEAD_FIRST) &&\n\t\t\t(uch <= SURROGATE_TRAIL_LAST)) {\n\t\t\tlen += 4;\n\t\t\ti++;\n\t\t} else {\n\t\t\tlen += 3;\n\t\t}\n\t\ti++;\n\t}\n\treturn len;\n}\n\nstatic void UTF8FromUTF16(const wchar_t *uptr, size_t tlen, char *putf, size_t len) {\n\tint k = 0;\n\tfor (size_t i = 0; i < tlen && uptr[i];) {\n\t\tunsigned int uch = uptr[i];\n\t\tif (uch < 0x80) {\n\t\t\tputf[k++] = static_cast<char>(uch);\n\t\t} else if (uch < 0x800) {\n\t\t\tputf[k++] = static_cast<char>(0xC0 | (uch >> 6));\n\t\t\tputf[k++] = static_cast<char>(0x80 | (uch & 0x3f));\n\t\t} else if ((uch >= SURROGATE_LEAD_FIRST) &&\n\t\t\t(uch <= SURROGATE_TRAIL_LAST)) {\n\t\t\t\/\/ Half a surrogate pair\n\t\t\ti++;\n\t\t\tunsigned int xch = 0x10000 + ((uch & 0x3ff) << 10) + (uptr[i] & 0x3ff);\n\t\t\tputf[k++] = static_cast<char>(0xF0 | (xch >> 18));\n\t\t\tputf[k++] = static_cast<char>(0x80 | ((xch >> 12) & 0x3f));\n\t\t\tputf[k++] = static_cast<char>(0x80 | ((xch >> 6) & 0x3f));\n\t\t\tputf[k++] = static_cast<char>(0x80 | (xch & 0x3f));\n\t\t} else {\n\t\t\tputf[k++] = static_cast<char>(0xE0 | (uch >> 12));\n\t\t\tputf[k++] = static_cast<char>(0x80 | ((uch >> 6) & 0x3f));\n\t\t\tputf[k++] = static_cast<char>(0x80 | (uch & 0x3f));\n\t\t}\n\t\ti++;\n\t}\n\tputf[len] = '\\0';\n}\n\nstatic size_t UTF16Length(const char *s, unsigned int len) {\n\tsize_t ulen = 0;\n\tsize_t charLen;\n\tfor (size_t i=0; i<len;) {\n\t\tunsigned char ch = static_cast<unsigned char>(s[i]);\n\t\tif (ch < 0x80) {\n\t\t\tcharLen = 1;\n\t\t} else if (ch < 0x80 + 0x40 + 0x20) {\n\t\t\tcharLen = 2;\n\t\t} else if (ch < 0x80 + 0x40 + 0x20 + 0x10) {\n\t\t\tcharLen = 3;\n\t\t} else {\n\t\t\tcharLen = 4;\n\t\t\tulen++;\n\t\t}\n\t\ti += charLen;\n\t\tulen++;\n\t}\n\treturn ulen;\n}\n\nstatic size_t UTF16FromUTF8(const char *s, size_t len, gui_char *tbuf, size_t tlen) {\n\tsize_t ui=0;\n\tconst unsigned char *us = reinterpret_cast<const unsigned char *>(s);\n\tsize_t i=0;\n\twhile ((i<len) && (ui<tlen)) {\n\t\tunsigned char ch = us[i++];\n\t\tif (ch < 0x80) {\n\t\t\ttbuf[ui] = ch;\n\t\t} else if (ch < 0x80 + 0x40 + 0x20) {\n\t\t\ttbuf[ui] = static_cast<wchar_t>((ch & 0x1F) << 6);\n\t\t\tch = us[i++];\n\t\t\ttbuf[ui] = static_cast<wchar_t>(tbuf[ui] + (ch & 0x7F));\n\t\t} else if (ch < 0x80 + 0x40 + 0x20 + 0x10) {\n\t\t\ttbuf[ui] = static_cast<wchar_t>((ch & 0xF) << 12);\n\t\t\tch = us[i++];\n\t\t\ttbuf[ui] = static_cast<wchar_t>(tbuf[ui] + ((ch & 0x7F) << 6));\n\t\t\tch = us[i++];\n\t\t\ttbuf[ui] = static_cast<wchar_t>(tbuf[ui] + (ch & 0x7F));\n\t\t} else {\n\t\t\t\/\/ Outside the BMP so need two surrogates\n\t\t\tint val = (ch & 0x7) << 18;\n\t\t\tch = us[i++];\n\t\t\tval += (ch & 0x3F) << 12;\n\t\t\tch = us[i++];\n\t\t\tval += (ch & 0x3F) << 6;\n\t\t\tch = us[i++];\n\t\t\tval += (ch & 0x3F);\n\t\t\ttbuf[ui] = static_cast<wchar_t>(((val - 0x10000) >> 10) + SURROGATE_LEAD_FIRST);\n\t\t\tui++;\n\t\t\ttbuf[ui] = static_cast<wchar_t>((val & 0x3ff) + SURROGATE_TRAIL_FIRST);\n\t\t}\n\t\tui++;\n\t}\n\treturn ui;\n}\n\ngui_string StringFromUTF8(const char *s) {\n\tsize_t sLen = s ? strlen(s) : 0;\n\tsize_t wideLen = UTF16Length(s, static_cast<int>(sLen));\n\tstd::vector<gui_char> vgc(wideLen + 1);\n\tsize_t outLen = UTF16FromUTF8(s, sLen, &vgc[0], wideLen);\n\tvgc[outLen] = 0;\n\treturn gui_string(&vgc[0], outLen);\n}\n\nstd::string UTF8FromString(const gui_string &s) {\n\tsize_t sLen = s.size();\n\tsize_t narrowLen = UTF8Length(s.c_str(), sLen);\n\tstd::vector<char> vc(narrowLen + 1);\n\tUTF8FromUTF16(s.c_str(), sLen, &vc[0], narrowLen);\n\treturn std::string(&vc[0], narrowLen);\n}\n\ngui_string StringFromInteger(int i) {\n\tchar number[32];\n\tsprintf(number, \"%0d\", i);\n\tgui_char gnumber[32];\n\tsize_t n=0;\n\twhile (number[n]) {\n\t\tgnumber[n] = static_cast<gui_char>(number[n]);\n\t\tn++;\n\t}\n\tgnumber[n] = 0;\n\treturn gui_string(gnumber);\n}\n\nvoid Window::Destroy() {\n\tif (wid)\n\t\t::DestroyWindow(reinterpret_cast<HWND>(wid));\n\twid = 0;\n}\n\nbool Window::HasFocus() {\n\treturn ::GetFocus() == wid;\n}\n\nRectangle Window::GetPosition() {\n\tRECT rc;\n\t::GetWindowRect(reinterpret_cast<HWND>(wid), &rc);\n\treturn Rectangle(rc.left, rc.top, rc.right, rc.bottom);\n}\n\nvoid Window::SetPosition(Rectangle rc) {\n\t::SetWindowPos(reinterpret_cast<HWND>(wid),\n\t\t0, rc.left, rc.top, rc.Width(), rc.Height(), SWP_NOZORDER|SWP_NOACTIVATE);\n}\n\nRectangle Window::GetClientPosition() {\n\tRECT rc={0,0,0,0};\n\tif (wid)\n\t\t::GetClientRect(reinterpret_cast<HWND>(wid), &rc);\n\treturn Rectangle(rc.left, rc.top, rc.right, rc.bottom);\n}\n\nvoid Window::Show(bool show) {\n\tif (show)\n\t\t::ShowWindow(reinterpret_cast<HWND>(wid), SW_SHOWNOACTIVATE);\n\telse\n\t\t::ShowWindow(reinterpret_cast<HWND>(wid), SW_HIDE);\n}\n\nvoid Window::InvalidateAll() {\n\t::InvalidateRect(reinterpret_cast<HWND>(wid), NULL, FALSE);\n}\n\nvoid Window::SetTitle(const gui_char *s) {\n\t::SetWindowTextW(reinterpret_cast<HWND>(wid), s);\n}\n\nvoid Menu::CreatePopUp() {\n\tDestroy();\n\tmid = ::CreatePopupMenu();\n}\n\nvoid Menu::Destroy() {\n\tif (mid)\n\t\t::DestroyMenu(reinterpret_cast<HMENU>(mid));\n\tmid = 0;\n}\n\nvoid Menu::Show(Point pt, Window &w) {\n\t::TrackPopupMenu(reinterpret_cast<HMENU>(mid),\n\t\t0, pt.x - 4, pt.y, 0,\n\t\treinterpret_cast<HWND>(w.GetID()), NULL);\n\tDestroy();\n}\n\nstatic bool initialisedET = false;\nstatic bool usePerformanceCounter = false;\nstatic LARGE_INTEGER frequency;\n\nElapsedTime::ElapsedTime() {\n\tif (!initialisedET) {\n\t\tusePerformanceCounter = ::QueryPerformanceFrequency(&frequency) != 0;\n\t\tinitialisedET = true;\n\t}\n\tif (usePerformanceCounter) {\n\t\tLARGE_INTEGER timeVal;\n\t\t::QueryPerformanceCounter(&timeVal);\n\t\tbigBit = timeVal.HighPart;\n\t\tlittleBit = timeVal.LowPart;\n\t} else {\n\t\tbigBit = clock();\n\t\tlittleBit = 0;\n\t}\n}\n\ndouble ElapsedTime::Duration(bool reset) {\n\tdouble result;\n\tlong endBigBit;\n\tlong endLittleBit;\n\n\tif (usePerformanceCounter) {\n\t\tLARGE_INTEGER lEnd;\n\t\t::QueryPerformanceCounter(&lEnd);\n\t\tendBigBit = lEnd.HighPart;\n\t\tendLittleBit = lEnd.LowPart;\n\t\tLARGE_INTEGER lBegin;\n\t\tlBegin.HighPart = bigBit;\n\t\tlBegin.LowPart = littleBit;\n\t\tdouble elapsed = lEnd.QuadPart - lBegin.QuadPart;\n\t\tresult = elapsed \/ static_cast<double>(frequency.QuadPart);\n\t} else {\n\t\tendBigBit = clock();\n\t\tendLittleBit = 0;\n\t\tdouble elapsed = endBigBit - bigBit;\n\t\tresult = elapsed \/ CLOCKS_PER_SEC;\n\t}\n\tif (reset) {\n\t\tbigBit = endBigBit;\n\t\tlittleBit = endLittleBit;\n\t}\n\treturn result;\n}\n\nsptr_t ScintillaWindow::Send(unsigned int msg, uptr_t wParam, sptr_t lParam) {\n\treturn ::SendMessage(reinterpret_cast<HWND>(GetID()), msg, wParam, lParam);\n}\n\nsptr_t ScintillaWindow::SendPointer(unsigned int msg, uptr_t wParam, void *lParam) {\n\treturn ::SendMessage(reinterpret_cast<HWND>(GetID()), msg, wParam, reinterpret_cast<LPARAM>(lParam));\n}\n\nbool IsDBCSLeadByte(int codePage, char ch) {\n\tif (SC_CP_UTF8 == codePage)\n\t\t\/\/ For lexing, all characters >= 0x80 are treated the\n\t\t\/\/ same so none is considered a lead byte.\n\t\treturn false;\n\telse\n\t\treturn ::IsDBCSLeadByteEx(codePage, ch) != 0;\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/=======================================================================\n\/\/ Copyright Baptiste Wicht 2011-2014.\n\/\/ Distributed under the MIT License.\n\/\/ (See accompanying file LICENSE or copy at\n\/\/ http:\/\/opensource.org\/licenses\/MIT)\n\/\/=======================================================================\n\n#include \"Variable.hpp\"\n\n#include \"mtac\/cse.hpp\"\n#include \"mtac\/Utils.hpp\"\n\nusing namespace eddic;\n\nbool mtac::are_equivalent(mtac::Quadruple& quadruple, const expression& exp){\n if(exp.op == quadruple.op && exp.type == quadruple.result->type()){\n if(exp.arg1 == *quadruple.arg1 && exp.arg2 == *quadruple.arg2){\n return true;\n } else if(mtac::is_commutative(quadruple.op) && exp.arg1 == *quadruple.arg2 && exp.arg2 == *quadruple.arg1){\n return true;\n }\n }\n\n return false;\n}\n\nbool mtac::is_interesting(mtac::Quadruple& quadruple){\n if(boost::get<std::shared_ptr<Variable>>(&*quadruple.arg1)){\n return true;\n }\n \n if(boost::get<std::shared_ptr<Variable>>(&*quadruple.arg2)){\n return true;\n }\n\n return false;\n}\n\nbool mtac::is_valid(mtac::Quadruple& quadruple, const mtac::escaped_variables& escaped){\n if(quadruple.op == mtac::Operator::DOT){\n if(auto* ptr = boost::get<std::shared_ptr<Variable>>(&*quadruple.arg1)){\n if((*ptr)->type()->is_pointer()){\n return false;\n }\n }\n }\n \n if(auto* ptr = boost::get<std::shared_ptr<Variable>>(&*quadruple.arg1)){\n if(escaped.find(*ptr) != escaped.end()){\n return false;\n }\n }\n \n if(auto* ptr = boost::get<std::shared_ptr<Variable>>(&*quadruple.arg2)){\n if(escaped.find(*ptr) != escaped.end()){\n return false;\n }\n }\n\n return true;\n}\n\nbool mtac::is_commutative(mtac::Operator op){\n return op == mtac::Operator::ADD || op == mtac::Operator::FADD || op == mtac::Operator::MUL || op == mtac::Operator::FMUL;\n}\n\nbool mtac::is_expression(mtac::Operator op){\n return (op >= mtac::Operator::ADD && op <= mtac::Operator::FDIV) || op == mtac::Operator::DOT;\n}\n\nbool mtac::is_killing(mtac::Quadruple& quadruple, const mtac::expression& expression){\n eddic_assert(quadruple.result, \"is_killing should only be called on quadruple erasing the result, thus having a result\");\n\n if(auto* ptr = boost::get<std::shared_ptr<Variable>>(&expression.arg1)){\n if(quadruple.result == *ptr){\n return true;\n }\n }\n\n if(auto* ptr = boost::get<std::shared_ptr<Variable>>(&expression.arg2)){\n if(quadruple.result == *ptr){\n return true;\n }\n }\n\n return false;\n}\n\nstd::ostream& mtac::operator<<(std::ostream& stream, const expression& expression){\n return stream << \"{\" << expression.arg1 << \" \" << static_cast<unsigned int>(expression.op) << \" \" << expression.arg2 << \"}\";\n}\n\nmtac::Operator mtac::assign_op(mtac::Operator op){\n if(op == mtac::Operator::DOT){\n return mtac::Operator::ASSIGN;\n } else if(op <= mtac::Operator::ADD && op <= mtac::Operator::MOD){\n return mtac::Operator::ASSIGN;\n } else if(op <= mtac::Operator::FADD && op <= mtac::Operator::FDIV){\n return mtac::Operator::FASSIGN;\n }\n\n eddic_unreachable(\"This is not an expression operator\");\n}\n<commit_msg>Fix operators conversion<commit_after>\/\/=======================================================================\n\/\/ Copyright Baptiste Wicht 2011-2014.\n\/\/ Distributed under the MIT License.\n\/\/ (See accompanying file LICENSE or copy at\n\/\/ http:\/\/opensource.org\/licenses\/MIT)\n\/\/=======================================================================\n\n#include \"Variable.hpp\"\n\n#include \"mtac\/cse.hpp\"\n#include \"mtac\/Utils.hpp\"\n\nusing namespace eddic;\n\nbool mtac::are_equivalent(mtac::Quadruple& quadruple, const expression& exp){\n if(exp.op == quadruple.op && exp.type == quadruple.result->type()){\n if(exp.arg1 == *quadruple.arg1 && exp.arg2 == *quadruple.arg2){\n return true;\n } else if(mtac::is_commutative(quadruple.op) && exp.arg1 == *quadruple.arg2 && exp.arg2 == *quadruple.arg1){\n return true;\n }\n }\n\n return false;\n}\n\nbool mtac::is_interesting(mtac::Quadruple& quadruple){\n if(boost::get<std::shared_ptr<Variable>>(&*quadruple.arg1)){\n return true;\n }\n \n if(boost::get<std::shared_ptr<Variable>>(&*quadruple.arg2)){\n return true;\n }\n\n return false;\n}\n\nbool mtac::is_valid(mtac::Quadruple& quadruple, const mtac::escaped_variables& escaped){\n if(quadruple.op == mtac::Operator::DOT){\n if(auto* ptr = boost::get<std::shared_ptr<Variable>>(&*quadruple.arg1)){\n if((*ptr)->type()->is_pointer()){\n return false;\n }\n }\n }\n \n if(auto* ptr = boost::get<std::shared_ptr<Variable>>(&*quadruple.arg1)){\n if(escaped.find(*ptr) != escaped.end()){\n return false;\n }\n }\n \n if(auto* ptr = boost::get<std::shared_ptr<Variable>>(&*quadruple.arg2)){\n if(escaped.find(*ptr) != escaped.end()){\n return false;\n }\n }\n\n return true;\n}\n\nbool mtac::is_commutative(mtac::Operator op){\n return op == mtac::Operator::ADD || op == mtac::Operator::FADD || op == mtac::Operator::MUL || op == mtac::Operator::FMUL;\n}\n\nbool mtac::is_expression(mtac::Operator op){\n return (op >= mtac::Operator::ADD && op <= mtac::Operator::FDIV) || op == mtac::Operator::DOT;\n}\n\nbool mtac::is_killing(mtac::Quadruple& quadruple, const mtac::expression& expression){\n eddic_assert(quadruple.result, \"is_killing should only be called on quadruple erasing the result, thus having a result\");\n\n if(auto* ptr = boost::get<std::shared_ptr<Variable>>(&expression.arg1)){\n if(quadruple.result == *ptr){\n return true;\n }\n }\n\n if(auto* ptr = boost::get<std::shared_ptr<Variable>>(&expression.arg2)){\n if(quadruple.result == *ptr){\n return true;\n }\n }\n\n return false;\n}\n\nstd::ostream& mtac::operator<<(std::ostream& stream, const expression& expression){\n return stream << \"{\" << expression.arg1 << \" \" << static_cast<unsigned int>(expression.op) << \" \" << expression.arg2 << \"}\";\n}\n\nmtac::Operator mtac::assign_op(mtac::Operator op){\n if(op == mtac::Operator::DOT){\n return mtac::Operator::ASSIGN;\n } else if(op >= mtac::Operator::ADD && op <= mtac::Operator::MOD){\n return mtac::Operator::ASSIGN;\n } else if(op >= mtac::Operator::FADD && op <= mtac::Operator::FDIV){\n return mtac::Operator::FASSIGN;\n }\n\n eddic_unreachable(\"This is not an expression operator\");\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"console.h\"\n#include <iostream>\n#include <string>\n#include \"person.h\"\n#include \"data.h\"\n\nusing namespace std;\n\nConsole::Console()\n{\n\n}\nvoid Console::getInfo()\n{\n string command;\n<<<<<<< HEAD\n\n do\n {\n\n=======\n do\n {\n>>>>>>> 888c7ccfc49884cc4dfb3f9426f21de5655fac63\n cout << \"Please enter one of the following commands: \" << endl;\n cout << \"Add - for adding scientist to the list\" << endl;\n cout << \"View - for viewing the whole list\" << endl;\n cout << \"Search - for searching for names in the list\" << endl;\n cout << \"Exit - quits\" << endl;\n\n cin >> command;\n\n<<<<<<< HEAD\n\n\n=======\n>>>>>>> 888c7ccfc49884cc4dfb3f9426f21de5655fac63\n if (command == \"Add\" || command == \"add\")\n {\n string name;\n char gender;\n int birth;\n int death;\n\n cout << \"Enter name of scientist: \";\n cin >> name;\n do{\n cout << \"Gender (f\/m): \";\n cin >> gender;\n if(!(gender == 'm') && !(gender == 'f'))\n cout << \"Invalid input!\" <<endl;\n }\n while((gender != 'f') && (gender != 'm'));\n\n cout << \"Enter year of birth: \";\n cin >> birth;\n cout << \"Enter year of death, unless N\/A: \";\n cin >> death;\n\n Person newData(name, gender, birth, death);\n dat.writeData(newData);\n\n }\n else if (command == \"View\" || command == \"view\")\n {\n\n }\n else if (command == \"Search\" || command == \"search\")\n {\n\n }\n\n }while((command != \"Exit\") && (command != \"exit\"));\n}\n\nvoid Console::getSort()\n{\n int sort;\n\n cout << \"Please enter one of the following commands: \" << endl;\n cout << \"1 - for alphabetical order\" << endl;\n cout << \"2 - sort by gender\" << endl;\n cout << \"3 - sort by age (youngest to oldest)\" << endl;\n cin >> sort;\n\n if(sort == 1)\n {\n\n }\n else if(sort == 2)\n {\n\n }\n else if(sort == 3)\n {\n\n }\n}\n<commit_msg>línur og drasl<commit_after>#include \"console.h\"\n#include <iostream>\n#include <string>\n#include \"person.h\"\n#include \"data.h\"\n\nusing namespace std;\n\nConsole::Console()\n{\n\n}\nvoid Console::getInfo()\n{\n string command;\n\n do\n {\n\n cout << \"--------------------------------------------\" << endl;\n cout << \"Please enter one of the following commands: \" << endl;\n cout << \"Add - for adding scientist to the list\" << endl;\n cout << \"View - for viewing the whole list\" << endl;\n cout << \"Search - for searching for names in the list\" << endl;\n cout << \"Exit - quits\" << endl;\n cout << \"--------------------------------------------\" << endl;\n\n cin >> command;\n\n if (command == \"Add\" || command == \"add\")\n {\n string name;\n char gender;\n int birth;\n int death;\n\n cout << \"Enter name of scientist: \";\n cin >> name;\n do{\n cout << \"Gender (f\/m): \";\n cin >> gender;\n if(!(gender == 'm') && !(gender == 'f'))\n cout << \"Invalid input!\" <<endl;\n }\n while((gender != 'f') && (gender != 'm'));\n\n cout << \"Enter year of birth: \";\n cin >> birth;\n cout << \"Enter year of death, unless N\/A: \";\n cin >> death;\n cout << endl;\n\n Person newData(name, gender, birth, death);\n dat.writeData(newData);\n\n }\n else if (command == \"View\" || command == \"view\")\n {\n\n }\n else if (command == \"Search\" || command == \"search\")\n {\n\n }\n\n }while((command != \"Exit\") && (command != \"exit\"));\n}\n\nvoid Console::getSort()\n{\n int sort;\n\n cout << \"Please enter one of the following commands: \" << endl;\n cout << \"1 - for alphabetical order\" << endl;\n cout << \"2 - sort by gender\" << endl;\n cout << \"3 - sort by age (youngest to oldest)\" << endl;\n cin >> sort;\n\n if(sort == 1)\n {\n\n }\n else if(sort == 2)\n {\n\n }\n else if(sort == 3)\n {\n\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\r\n\/\/ cFile.cpp\r\n\r\n\/\/ Implements the cFile class providing an OS-independent abstraction of a file.\r\n\r\n#include \"Globals.h\" \/\/ NOTE: MSVC stupidness requires this to be the same across all modules\r\n\r\n#include \"cFile.h\"\r\n\r\n\r\n\r\n\r\n\r\n\r\n\/\/\/ Simple constructor - creates an unopened file object, use Open() to open \/ create a real file\r\ncFile::cFile(void) :\r\n\t#ifdef USE_STDIO_FILE\r\n\tm_File(NULL)\r\n\t#else\r\n\tm_File(INVALID_HANDLE_VALUE)\r\n\t#endif \/\/ USE_STDIO_FILE\r\n{\r\n\t\/\/ Nothing needed yet\r\n}\r\n\r\n\r\n\r\n\r\n\r\n\/\/\/ Constructs and opens \/ creates the file specified, use IsOpen() to check for success\r\ncFile::cFile(const char * iFileName, EMode iMode) :\r\n\t#ifdef USE_STDIO_FILE\r\n\tm_File(NULL)\r\n\t#else\r\n\tm_File(INVALID_HANDLE_VALUE)\r\n\t#endif \/\/ USE_STDIO_FILE\r\n{\r\n\tOpen(iFileName, iMode);\r\n}\r\n\r\n\r\n\r\n\r\n\r\n\/\/\/ Auto-closes the file, if open\r\ncFile::~cFile()\r\n{\r\n\tif (IsOpen())\r\n\t{\r\n\t\tClose();\r\n\t}\r\n}\r\n\r\n\r\n\r\n\r\n\r\nbool cFile::Open(const char * iFileName, EMode iMode)\r\n{\r\n\tassert(!IsOpen()); \/\/ You should close the file before opening another one\r\n\t\r\n\tif (IsOpen())\r\n\t{\r\n\t\tClose();\r\n\t}\r\n\t\r\n\tconst char * Mode = NULL;\r\n\tswitch (iMode)\r\n\t{\r\n\t\tcase fmRead: Mode = \"rb\"; break;\r\n\t\tcase fmWrite: Mode = \"wb\"; break;\r\n\t\tcase fmReadWrite: Mode = \"ab+\"; break;\r\n\t\tdefault:\r\n\t\t{\r\n\t\t\tassert(!\"Unhandled file mode\");\r\n\t\t\treturn false;\r\n\t\t}\r\n\t}\r\n\tm_File = fopen(iFileName, Mode);\r\n\treturn (m_File != NULL);\r\n}\r\n\r\n\r\n\r\n\r\n\r\nvoid cFile::Close(void)\r\n{\r\n\tassert(IsOpen()); \/\/ You should not close file objects that don't have an open file.\r\n\t\r\n\tif (!IsOpen())\r\n\t{\r\n\t\treturn;\r\n\t}\r\n\r\n\tfclose(m_File);\r\n}\r\n\r\n\r\n\r\n\r\n\r\nbool cFile::IsOpen(void) const\r\n{\r\n\treturn (m_File != NULL);\r\n}\r\n\r\n\r\n\r\n\r\n\r\nbool cFile::IsEOF(void) const\r\n{\r\n\tassert(IsOpen());\r\n\t\r\n\tif (!IsOpen())\r\n\t{\r\n\t\t\/\/ Unopened files behave as at EOF\r\n\t\treturn true;\r\n\t}\r\n\t\r\n\treturn (feof(m_File) != 0);\r\n}\r\n\r\n\r\n\r\n\r\n\r\n\/\/\/ Reads up to iNumBytes bytes into iBuffer, returns the number of bytes actually read, or -1 on failure; asserts if not open\r\nint cFile::Read (void * iBuffer, int iNumBytes)\r\n{\r\n\tassert(IsOpen());\r\n\t\r\n\tif (!IsOpen())\r\n\t{\r\n\t\treturn -1;\r\n\t}\r\n\t\r\n\treturn fread(iBuffer, 1, iNumBytes, m_File); \/\/ fread() returns the portion of Count parameter actually read, so we need to send iNumBytes as Count\r\n}\r\n\r\n\r\n\r\n\r\n\r\n\/\/\/ Writes up to iNumBytes bytes from iBuffer, returns the number of bytes actually written, or -1 on failure; asserts if not open\r\nint cFile::Write(const void * iBuffer, int iNumBytes)\r\n{\r\n\tassert(IsOpen());\r\n\t\r\n\tif (!IsOpen())\r\n\t{\r\n\t\treturn -1;\r\n\t}\r\n\r\n\treturn fwrite(iBuffer, 1, iNumBytes, m_File); \/\/ fwrite() returns the portion of Count parameter actually written, so we need to send iNumBytes as Count\r\n}\r\n\r\n\r\n\r\n\r\n\r\n\/\/\/ Seeks to iPosition bytes from file start, returns old position or -1 for failure\r\nint cFile::Seek (int iPosition)\r\n{\r\n\tassert(IsOpen());\r\n\t\r\n\tif (!IsOpen())\r\n\t{\r\n\t\treturn -1;\r\n\t}\r\n\t\r\n\tif (fseek(m_File, iPosition, SEEK_SET) != 0)\r\n\t{\r\n\t\treturn -1;\r\n\t}\r\n\treturn ftell(m_File);\r\n}\r\n\r\n\r\n\r\n\r\n\r\n\r\n\/\/\/ Returns the current position (bytes from file start)\r\nint cFile::Tell (void) const\r\n{\r\n\tassert(IsOpen());\r\n\t\r\n\tif (!IsOpen())\r\n\t{\r\n\t\treturn -1;\r\n\t}\r\n\t\r\n\treturn ftell(m_File);\r\n}\r\n\r\n\r\n\r\n\r\n\r\n\/\/\/ Returns the size of file, in bytes, or -1 for failure; asserts if not open\r\nint cFile::GetSize(void) const\r\n{\r\n\tassert(IsOpen());\r\n\t\r\n\tif (!IsOpen())\r\n\t{\r\n\t\treturn -1;\r\n\t}\r\n\t\r\n\tint CurPos = ftell(m_File);\r\n\tif (CurPos < 0)\r\n\t{\r\n\t\treturn -1;\r\n\t}\r\n\tif (fseek(m_File, 0, SEEK_END) != 0)\r\n\t{\r\n\t\treturn -1;\r\n\t}\r\n\tint res = ftell(m_File);\r\n\tif (fseek(m_File, CurPos, SEEK_SET) != 0)\r\n\t{\r\n\t\treturn -1;\r\n\t}\r\n\treturn res;\r\n}\r\n\r\n\r\n\r\n\r\n<commit_msg>Fixed a sigsegv on *nix (cFile double-closing files)<commit_after>\r\n\/\/ cFile.cpp\r\n\r\n\/\/ Implements the cFile class providing an OS-independent abstraction of a file.\r\n\r\n#include \"Globals.h\" \/\/ NOTE: MSVC stupidness requires this to be the same across all modules\r\n\r\n#include \"cFile.h\"\r\n\r\n\r\n\r\n\r\n\r\n\r\n\/\/\/ Simple constructor - creates an unopened file object, use Open() to open \/ create a real file\r\ncFile::cFile(void) :\r\n\t#ifdef USE_STDIO_FILE\r\n\tm_File(NULL)\r\n\t#else\r\n\tm_File(INVALID_HANDLE_VALUE)\r\n\t#endif \/\/ USE_STDIO_FILE\r\n{\r\n\t\/\/ Nothing needed yet\r\n}\r\n\r\n\r\n\r\n\r\n\r\n\/\/\/ Constructs and opens \/ creates the file specified, use IsOpen() to check for success\r\ncFile::cFile(const char * iFileName, EMode iMode) :\r\n\t#ifdef USE_STDIO_FILE\r\n\tm_File(NULL)\r\n\t#else\r\n\tm_File(INVALID_HANDLE_VALUE)\r\n\t#endif \/\/ USE_STDIO_FILE\r\n{\r\n\tOpen(iFileName, iMode);\r\n}\r\n\r\n\r\n\r\n\r\n\r\n\/\/\/ Auto-closes the file, if open\r\ncFile::~cFile()\r\n{\r\n\tif (IsOpen())\r\n\t{\r\n\t\tClose();\r\n\t}\r\n}\r\n\r\n\r\n\r\n\r\n\r\nbool cFile::Open(const char * iFileName, EMode iMode)\r\n{\r\n\tassert(!IsOpen()); \/\/ You should close the file before opening another one\r\n\t\r\n\tif (IsOpen())\r\n\t{\r\n\t\tClose();\r\n\t}\r\n\t\r\n\tconst char * Mode = NULL;\r\n\tswitch (iMode)\r\n\t{\r\n\t\tcase fmRead: Mode = \"rb\"; break;\r\n\t\tcase fmWrite: Mode = \"wb\"; break;\r\n\t\tcase fmReadWrite: Mode = \"ab+\"; break;\r\n\t\tdefault:\r\n\t\t{\r\n\t\t\tassert(!\"Unhandled file mode\");\r\n\t\t\treturn false;\r\n\t\t}\r\n\t}\r\n\tm_File = fopen(iFileName, Mode);\r\n\treturn (m_File != NULL);\r\n}\r\n\r\n\r\n\r\n\r\n\r\nvoid cFile::Close(void)\r\n{\r\n\tassert(IsOpen()); \/\/ You should not close file objects that don't have an open file.\r\n\t\r\n\tif (!IsOpen())\r\n\t{\r\n\t\treturn;\r\n\t}\r\n\r\n\tfclose(m_File);\r\n\tm_File = NULL;\r\n}\r\n\r\n\r\n\r\n\r\n\r\nbool cFile::IsOpen(void) const\r\n{\r\n\treturn (m_File != NULL);\r\n}\r\n\r\n\r\n\r\n\r\n\r\nbool cFile::IsEOF(void) const\r\n{\r\n\tassert(IsOpen());\r\n\t\r\n\tif (!IsOpen())\r\n\t{\r\n\t\t\/\/ Unopened files behave as at EOF\r\n\t\treturn true;\r\n\t}\r\n\t\r\n\treturn (feof(m_File) != 0);\r\n}\r\n\r\n\r\n\r\n\r\n\r\n\/\/\/ Reads up to iNumBytes bytes into iBuffer, returns the number of bytes actually read, or -1 on failure; asserts if not open\r\nint cFile::Read (void * iBuffer, int iNumBytes)\r\n{\r\n\tassert(IsOpen());\r\n\t\r\n\tif (!IsOpen())\r\n\t{\r\n\t\treturn -1;\r\n\t}\r\n\t\r\n\treturn fread(iBuffer, 1, iNumBytes, m_File); \/\/ fread() returns the portion of Count parameter actually read, so we need to send iNumBytes as Count\r\n}\r\n\r\n\r\n\r\n\r\n\r\n\/\/\/ Writes up to iNumBytes bytes from iBuffer, returns the number of bytes actually written, or -1 on failure; asserts if not open\r\nint cFile::Write(const void * iBuffer, int iNumBytes)\r\n{\r\n\tassert(IsOpen());\r\n\t\r\n\tif (!IsOpen())\r\n\t{\r\n\t\treturn -1;\r\n\t}\r\n\r\n\treturn fwrite(iBuffer, 1, iNumBytes, m_File); \/\/ fwrite() returns the portion of Count parameter actually written, so we need to send iNumBytes as Count\r\n}\r\n\r\n\r\n\r\n\r\n\r\n\/\/\/ Seeks to iPosition bytes from file start, returns old position or -1 for failure\r\nint cFile::Seek (int iPosition)\r\n{\r\n\tassert(IsOpen());\r\n\t\r\n\tif (!IsOpen())\r\n\t{\r\n\t\treturn -1;\r\n\t}\r\n\t\r\n\tif (fseek(m_File, iPosition, SEEK_SET) != 0)\r\n\t{\r\n\t\treturn -1;\r\n\t}\r\n\treturn ftell(m_File);\r\n}\r\n\r\n\r\n\r\n\r\n\r\n\r\n\/\/\/ Returns the current position (bytes from file start)\r\nint cFile::Tell (void) const\r\n{\r\n\tassert(IsOpen());\r\n\t\r\n\tif (!IsOpen())\r\n\t{\r\n\t\treturn -1;\r\n\t}\r\n\t\r\n\treturn ftell(m_File);\r\n}\r\n\r\n\r\n\r\n\r\n\r\n\/\/\/ Returns the size of file, in bytes, or -1 for failure; asserts if not open\r\nint cFile::GetSize(void) const\r\n{\r\n\tassert(IsOpen());\r\n\t\r\n\tif (!IsOpen())\r\n\t{\r\n\t\treturn -1;\r\n\t}\r\n\t\r\n\tint CurPos = ftell(m_File);\r\n\tif (CurPos < 0)\r\n\t{\r\n\t\treturn -1;\r\n\t}\r\n\tif (fseek(m_File, 0, SEEK_END) != 0)\r\n\t{\r\n\t\treturn -1;\r\n\t}\r\n\tint res = ftell(m_File);\r\n\tif (fseek(m_File, CurPos, SEEK_SET) != 0)\r\n\t{\r\n\t\treturn -1;\r\n\t}\r\n\treturn res;\r\n}\r\n\r\n\r\n\r\n\r\n<|endoftext|>"} {"text":"<commit_before>#include \"photoeffects.hpp\"\n#include <math.h>\n\nusing namespace cv;\n\n#define MAX_KERNELSIZE 15\n\nint edgeBlur(InputArray src, OutputArray dst, int indentTop, int indentLeft)\n{\n CV_Assert(src.type() == CV_8UC3);\n dst.create(src.size(), src.type());\n Mat image = src.getMat(), outputImage = dst.getMat();\n \n CV_Assert(indentTop >= 0 && indentTop <= (image.rows \/ 2 - 10));\n CV_Assert(indentLeft >= 0 && indentLeft <= (image.cols \/ 2 - 10));\n\n float halfWidth = (image.cols \/ 2.0f) * (image.cols \/ 2.0f);\n float halfHeight = (image.rows \/ 2.0f) * (image.rows \/ 2.0f);\n float a = (image.cols \/ 2.0f - indentLeft) \n * (image.cols \/ 2.0f - indentLeft);\n float b = (image.rows \/ 2.0f - indentTop) \n * (image.rows \/ 2.0f - indentTop);\n int kSizeEdges = halfWidth \/ a + halfHeight \/ b;\n\n kSizeEdges = MIN(kSizeEdges, MAX_KERNELSIZE);\n Mat bearingImage(image.rows + 2 * kSizeEdges,\n image.cols + 2 * kSizeEdges,\n CV_8UC3);\n copyMakeBorder(image, bearingImage, kSizeEdges, kSizeEdges,\n kSizeEdges, kSizeEdges, BORDER_REPLICATE);\n\n\n for (int i = kSizeEdges; i < bearingImage.rows - kSizeEdges; i++)\n {\n for (int j = kSizeEdges; j < bearingImage.cols - kSizeEdges; j++)\n {\n int size;\n Vec3f sumF;\n Vec3b Color;\n float sumC = 0.0f, coeff;\n float bearHalfWidth = bearingImage.cols \/ 2.0f;\n float bearHalfHeight = bearingImage.rows \/ 2.0f;\n float radius = (bearHalfHeight - i)\n * (bearHalfHeight - i)\n \/ b\n\n + (bearHalfWidth - j)\n * (bearHalfWidth - j)\n \/ a;\n if (radius < 1.0f)\n {\n outputImage.at<Vec3b>(i - kSizeEdges, j - kSizeEdges) =\n bearingImage.at<Vec3b>(i, j);\n continue;\n }\n size = radius;\n radius = 2.0f * (radius - 0.5f) * (radius - 0.5f);\n size = MIN(size, kSizeEdges);\n for (int x = -size; x <= size; x++)\n {\n for (int y = -size; y <= size; y++)\n {\n coeff = 1.0f \/ (CV_PI * radius)\n * exp(- (x * x + y * y) \/ radius);\n\n Color = bearingImage.at<Vec3b>(x + i, y + j);\n sumF += (Vec3f) (coeff * Color);\n sumC += coeff;\n }\n }\n sumF *= (1.0f \/ sumC);\n outputImage.at<Vec3b>(i - kSizeEdges, j - kSizeEdges) = sumF;\n }\n }\n\n return 0;\n}\n<commit_msg>Strange effect<commit_after>#include \"photoeffects.hpp\"\n#include <math.h>\n\nusing namespace cv;\n\n#define MAX_KERNELSIZE 15\n\nint edgeBlur(InputArray src, OutputArray dst, int indentTop, int indentLeft)\n{\n CV_Assert(src.type() == CV_8UC3);\n dst.create(src.size(), src.type());\n Mat image = src.getMat(), outputImage = dst.getMat();\n \n CV_Assert(indentTop >= 0 && indentTop <= (image.rows \/ 2 - 10));\n CV_Assert(indentLeft >= 0 && indentLeft <= (image.cols \/ 2 - 10));\n\n float halfWidth = (image.cols \/ 2.0f) * (image.cols \/ 2.0f);\n float halfHeight = (image.rows \/ 2.0f) * (image.rows \/ 2.0f);\n float a = (image.cols \/ 2.0f - indentLeft) \n * (image.cols \/ 2.0f - indentLeft);\n float b = (image.rows \/ 2.0f - indentTop) \n * (image.rows \/ 2.0f - indentTop);\n int kSizeEdges = halfWidth \/ a + halfHeight \/ b;\n\n kSizeEdges = MIN(kSizeEdges, MAX_KERNELSIZE);\n Mat bearingImage(image.rows + 2 * kSizeEdges,\n image.cols + 2 * kSizeEdges,\n CV_8UC3);\n copyMakeBorder(image, bearingImage, kSizeEdges, kSizeEdges,\n kSizeEdges, kSizeEdges, BORDER_REPLICATE);\n\n\n for (int i = kSizeEdges; i < bearingImage.rows - kSizeEdges; i++)\n {\n for (int j = kSizeEdges; j < bearingImage.cols - kSizeEdges; j++)\n {\n int size;\n Vec3f sumF;\n Vec3b Color;\n float sumC = 0.0f, coeff;\n float bearHalfWidth = bearingImage.cols \/ 2.0f;\n float bearHalfHeight = bearingImage.rows \/ 2.0f;\n float radius = (bearHalfHeight - i)\n * (bearHalfHeight - i)\n \/ b\n\n + (bearHalfWidth - j)\n * (bearHalfWidth - j)\n \/ a;\n if (radius < 1.0f)\n {\n outputImage.at<Vec3b>(i - kSizeEdges, j - kSizeEdges) =\n bearingImage.at<Vec3b>(i, j);\n continue;\n }\n size = radius;\n radius = 2.0f * (radius - 0.5f) * (radius - 0.5f);\n size = MIN(size, kSizeEdges);\n for (int x = -size; x <= size; x++)\n {\n for (int y = -size; y <= size; y++)\n {\n coeff = 1.0f \/ (CV_PI * radius)\n * exp(- (x * x + y * y) \/ radius);\n\n Color = bearingImage.at<Vec3b>(x + i, y + j);\n sumF += coeff * Color;\n sumC += coeff;\n }\n }\n sumF *= (1.0f \/ sumC);\n outputImage.at<Vec3b>(i - kSizeEdges, j - kSizeEdges) = sumF;\n }\n }\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>#ifndef INCLUDING_MPL_APPLY_V_HPP\n#define INCLUDING_MPL_APPLY_V_HPP\n\n#include <utility>\n\n#include \"mpl_utils.hpp\"\n\nnamespace mpl {\n\n\tnamespace detail::apply_values {\n\n\t\ttemplate <typename TFunctor, typename TTuple, size_t... Indices>\n\t\tconstexpr auto impl(TFunctor const & functor, TTuple && t, std::index_sequence<Indices...>)\n\t\t{\n\t\t\treturn functor(std::get<Indices>(std::forward<TTuple>(t))...);\n\t\t}\n\n\t\ttemplate <typename TFunctor, typename TTuple, size_t... Indices>\n\t\tconstexpr auto impl(TFunctor & functor, TTuple && t, std::index_sequence<Indices...>)\n\t\t{\n\t\t \treturn functor(std::get<Indices>(std::forward<TTuple>(t))...);\n\t\t}\n\n\t}\n\n\ttemplate<typename TFunctor, typename TTuple>\n\tconstexpr auto apply_values(TFunctor && functor, TTuple && elements) {\n\t\treturn impl(\n\t\t\tstd::forward<TFunctor>(functor),\n\t\t\tstd::forward<TTuple>(elements),\n\t\t\tdetail::sequence(std::forward<TTuple>(elements))\n\t\t);\n\t}\n\n}\n\n#define INCLUDED_MPL_APPLY_VALUES_HPP\n#elif !defined(INCLUDED_MPL_APPLY_VALUES_HPP)\n#\terror circular inclusion\n#endif<commit_msg>Add mpl::apply_v_constructor.<commit_after>#ifndef INCLUDING_MPL_APPLY_V_HPP\n#define INCLUDING_MPL_APPLY_V_HPP\n\n#include <utility>\n\n#include \"mpl_utils.hpp\"\n#include \"mpl_indices.hpp\"\n\nnamespace mpl {\n\n\tnamespace detail::apply_values {\n\n\t\ttemplate <typename TFunctor, typename TTuple, size_t... Indices>\n\t\tconstexpr auto impl(TFunctor const & functor, TTuple && t, std::index_sequence<Indices...>)\n\t\t{\n\t\t\treturn functor(std::get<Indices>(std::forward<TTuple>(t))...);\n\t\t}\n\n\t\ttemplate <typename TFunctor, typename TTuple, size_t... Indices>\n\t\tconstexpr auto impl(TFunctor & functor, TTuple && t, std::index_sequence<Indices...>)\n\t\t{\n\t\t \treturn functor(std::get<Indices>(std::forward<TTuple>(t))...);\n\t\t}\n\n\t\ttemplate <typename T, typename TTuple, size_t... Indices>\n\t\tconstexpr auto impl_ctor(TTuple && t, std::index_sequence<Indices...>) {\n\t\t\treturn T(std::get<Indices>(std::forward<TTuple>(t))...);\n\t\t}\n\t}\n\n\ttemplate<typename TFunctor, typename TTuple>\n\tconstexpr auto apply_v(TFunctor && functor, TTuple && elements) {\n\t\treturn impl(\n\t\t\tstd::forward<TFunctor>(functor),\n\t\t\tstd::forward<TTuple>(elements),\n\t\t\tindices_of<TTuple>()\n\t\t);\n\t}\n\n\ttemplate<typename T, typename TTuple>\n\tconstexpr auto apply_v_constructor(TTuple && elements) {\t\t\n\t\treturn detail::apply_values::impl_ctor<T>(\n\t\t\tstd::forward<TTuple>(elements),\n\t\t\tindices_of<TTuple>()\n\t\t);\n\t}\n}\n\n#define INCLUDED_MPL_APPLY_VALUES_HPP\n#elif !defined(INCLUDED_MPL_APPLY_VALUES_HPP)\n#\terror circular inclusion\n#endif<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (C) 2014 The Android Open Source Project\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include <stdint.h>\n#include <unicode\/uchar.h>\n#include <unicode\/utf16.h>\n#include <algorithm>\n\n#include <minikin\/Emoji.h>\n#include <minikin\/GraphemeBreak.h>\n#include \"MinikinInternal.h\"\n#include \"utils\/WindowsUtils.h\"\n\nnamespace minikin {\n\nint32_t tailoredGraphemeClusterBreak(uint32_t c) {\n \/\/ Characters defined as Control that we want to treat them as Extend.\n \/\/ These are curated manually.\n if (c == 0x00AD \/\/ SHY\n || c == 0x061C \/\/ ALM\n || c == 0x180E \/\/ MONGOLIAN VOWEL SEPARATOR\n || c == 0x200B \/\/ ZWSP\n || c == 0x200E \/\/ LRM\n || c == 0x200F \/\/ RLM\n || (0x202A <= c && c <= 0x202E) \/\/ LRE, RLE, PDF, LRO, RLO\n || ((c | 0xF) ==\n 0x206F) \/\/ WJ, invisible math operators, LRI, RLI, FSI, PDI,\n \/\/ and the deprecated invisible format controls\n || c == 0xFEFF \/\/ BOM\n || ((c | 0x7F) ==\n 0xE007F)) \/\/ recently undeprecated tag characters in Plane 14\n return U_GCB_EXTEND;\n \/\/ THAI CHARACTER SARA AM is treated as a normal letter by most other\n \/\/ implementations: they allow a grapheme break before it.\n else if (c == 0x0E33)\n return U_GCB_OTHER;\n else\n return u_getIntPropertyValue(c, UCHAR_GRAPHEME_CLUSTER_BREAK);\n}\n\n\/\/ Returns true for all characters whose IndicSyllabicCategory is Pure_Killer.\n\/\/ From http:\/\/www.unicode.org\/Public\/9.0.0\/ucd\/IndicSyllabicCategory.txt\nbool isPureKiller(uint32_t c) {\n return (c == 0x0E3A || c == 0x0E4E || c == 0x0F84 || c == 0x103A ||\n c == 0x1714 || c == 0x1734 || c == 0x17D1 || c == 0x1BAA ||\n c == 0x1BF2 || c == 0x1BF3 || c == 0xA806 || c == 0xA953 ||\n c == 0xABED || c == 0x11134 || c == 0x112EA || c == 0x1172B);\n}\n\nbool GraphemeBreak::isGraphemeBreak(const float* advances,\n const uint16_t* buf,\n size_t start,\n size_t count,\n const size_t offset) {\n \/\/ This implementation closely follows Unicode Standard Annex #29 on\n \/\/ Unicode Text Segmentation (http:\/\/www.unicode.org\/reports\/tr29\/),\n \/\/ implementing a tailored version of extended grapheme clusters.\n \/\/ The GB rules refer to section 3.1.1, Grapheme Cluster Boundary Rules.\n\n \/\/ Rule GB1, sot ÷; Rule GB2, ÷ eot\n if (offset <= start || offset >= start + count) {\n return true;\n }\n if (U16_IS_TRAIL(buf[offset])) {\n \/\/ Don't break a surrogate pair, but a lonely trailing surrogate pair is a\n \/\/ break\n return !U16_IS_LEAD(buf[offset - 1]);\n }\n uint32_t c1 = 0;\n uint32_t c2 = 0;\n size_t offset_back = offset;\n size_t offset_forward = offset;\n U16_PREV(buf, start, offset_back, c1);\n U16_NEXT(buf, offset_forward, start + count, c2);\n int32_t p1 = tailoredGraphemeClusterBreak(c1);\n int32_t p2 = tailoredGraphemeClusterBreak(c2);\n \/\/ Rule GB3, CR x LF\n if (p1 == U_GCB_CR && p2 == U_GCB_LF) {\n return false;\n }\n \/\/ Rule GB4, (Control | CR | LF) ÷\n if (p1 == U_GCB_CONTROL || p1 == U_GCB_CR || p1 == U_GCB_LF) {\n return true;\n }\n \/\/ Rule GB5, ÷ (Control | CR | LF)\n if (p2 == U_GCB_CONTROL || p2 == U_GCB_CR || p2 == U_GCB_LF) {\n return true;\n }\n \/\/ Rule GB6, L x ( L | V | LV | LVT )\n if (p1 == U_GCB_L &&\n (p2 == U_GCB_L || p2 == U_GCB_V || p2 == U_GCB_LV || p2 == U_GCB_LVT)) {\n return false;\n }\n \/\/ Rule GB7, ( LV | V ) x ( V | T )\n if ((p1 == U_GCB_LV || p1 == U_GCB_V) && (p2 == U_GCB_V || p2 == U_GCB_T)) {\n return false;\n }\n \/\/ Rule GB8, ( LVT | T ) x T\n if ((p1 == U_GCB_LVT || p1 == U_GCB_T) && p2 == U_GCB_T) {\n return false;\n }\n \/\/ Rule GB9, x (Extend | ZWJ); Rule GB9a, x SpacingMark; Rule GB9b, Prepend x\n if (p2 == U_GCB_EXTEND || p2 == U_GCB_ZWJ || p2 == U_GCB_SPACING_MARK ||\n p1 == U_GCB_PREPEND) {\n return false;\n }\n\n \/\/ This is used to decide font-dependent grapheme clusters. If we don't have\n \/\/ the advance information, we become conservative in grapheme breaking and\n \/\/ assume that it has no advance.\n const bool c2_has_advance =\n (advances != nullptr && advances[offset - start] != 0.0);\n\n \/\/ All the following rules are font-dependent, in the way that if we know c2\n \/\/ has an advance, we definitely know that it cannot form a grapheme with the\n \/\/ character(s) before it. So we make the decision in favor a grapheme break\n \/\/ early.\n if (c2_has_advance) {\n return true;\n }\n\n \/\/ Note: For Rule GB10 and GB11 below, we do not use the Unicode line breaking\n \/\/ properties for determining emoji-ness and carry our own data, because our\n \/\/ data could be more fresh than what ICU provides.\n \/\/\n \/\/ Tailored version of Rule GB10, (E_Base | EBG) Extend* × E_Modifier.\n \/\/ The rule itself says do not break between emoji base and emoji modifiers,\n \/\/ skipping all Extend characters. Variation selectors are considered Extend,\n \/\/ so they are handled fine.\n \/\/\n \/\/ We tailor this by requiring that an actual ligature is formed. If the font\n \/\/ doesn't form a ligature, we allow a break before the modifier.\n if (isEmojiModifier(c2)) {\n uint32_t c0 = c1;\n size_t offset_backback = offset_back;\n int32_t p0 = p1;\n if (p0 == U_GCB_EXTEND && offset_backback > start) {\n \/\/ skip over emoji variation selector\n U16_PREV(buf, start, offset_backback, c0);\n p0 = tailoredGraphemeClusterBreak(c0);\n }\n if (isEmojiBase(c0)) {\n return false;\n }\n }\n\n \/\/ Tailored version of Rule GB11, ZWJ × (Glue_After_Zwj | EBG)\n \/\/ We try to make emoji sequences with ZWJ a single grapheme cluster, but only\n \/\/ if they actually merge to one cluster. So we are more relaxed than the UAX\n \/\/ #29 rules in accepting any emoji character after the ZWJ, but are tighter\n \/\/ in that we only treat it as one cluster if a ligature is actually formed\n \/\/ and we also require the character before the ZWJ to also be an emoji.\n if (p1 == U_GCB_ZWJ && isEmoji(c2) && offset_back > start) {\n \/\/ look at character before ZWJ to see that both can participate in an\n \/\/ emoji zwj sequence\n uint32_t c0 = 0;\n size_t offset_backback = offset_back;\n U16_PREV(buf, start, offset_backback, c0);\n if (c0 == 0xFE0F && offset_backback > start) {\n \/\/ skip over emoji variation selector\n U16_PREV(buf, start, offset_backback, c0);\n }\n if (isEmoji(c0)) {\n return false;\n }\n }\n\n \/\/ Tailored version of Rule GB12 and Rule GB13 that look at even-odd cases.\n \/\/ sot (RI RI)* RI x RI\n \/\/ [^RI] (RI RI)* RI x RI\n \/\/\n \/\/ If we have font information, we have already broken the cluster if and only\n \/\/ if the second character had no advance, which means a ligature was formed.\n \/\/ If we don't, we look back like UAX #29 recommends, but only up to 1000 code\n \/\/ units.\n if (p1 == U_GCB_REGIONAL_INDICATOR && p2 == U_GCB_REGIONAL_INDICATOR) {\n if (advances != nullptr) {\n \/\/ We have advances information. But if we are here, we already know c2\n \/\/ has no advance. So we should definitely disallow a break.\n return false;\n } else {\n \/\/ Look at up to 1000 code units.\n const size_t lookback_barrier =\n std::max((ssize_t)start, (ssize_t)offset_back - 1000);\n size_t offset_backback = offset_back;\n while (offset_backback > lookback_barrier) {\n uint32_t c0 = 0;\n U16_PREV(buf, lookback_barrier, offset_backback, c0);\n if (tailoredGraphemeClusterBreak(c0) != U_GCB_REGIONAL_INDICATOR) {\n offset_backback += U16_LENGTH(c0);\n break;\n }\n }\n \/\/ The number 4 comes from the number of code units in a whole flag.\n return (offset - offset_backback) % 4 == 0;\n }\n }\n \/\/ Cluster Indic syllables together (tailoring of UAX #29).\n \/\/ Immediately after each virama (that is not just a pure killer) followed by\n \/\/ a letter, we disallow grapheme breaks (if we are here, we don't know about\n \/\/ advances, or we already know that c2 has no advance).\n if (u_getIntPropertyValue(c1, UCHAR_CANONICAL_COMBINING_CLASS) == 9 \/\/ virama\n && !isPureKiller(c1) &&\n u_getIntPropertyValue(c2, UCHAR_GENERAL_CATEGORY) == U_OTHER_LETTER) {\n return false;\n }\n \/\/ Rule GB999, Any ÷ Any\n return true;\n}\n\nsize_t GraphemeBreak::getTextRunCursor(const float* advances,\n const uint16_t* buf,\n size_t start,\n size_t count,\n size_t offset,\n MoveOpt opt) {\n switch (opt) {\n case AFTER:\n if (offset < start + count) {\n offset++;\n }\n \/\/ fall through\n case AT_OR_AFTER:\n while (!isGraphemeBreak(advances, buf, start, count, offset)) {\n offset++;\n }\n break;\n case BEFORE:\n if (offset > start) {\n offset--;\n }\n \/\/ fall through\n case AT_OR_BEFORE:\n while (!isGraphemeBreak(advances, buf, start, count, offset)) {\n offset--;\n }\n break;\n case AT:\n if (!isGraphemeBreak(advances, buf, start, count, offset)) {\n offset = (size_t)-1;\n }\n break;\n }\n return offset;\n}\n\n} \/\/ namespace minikin\n<commit_msg>Eliminate unused write to local (#8541)<commit_after>\/*\n * Copyright (C) 2014 The Android Open Source Project\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include <stdint.h>\n#include <unicode\/uchar.h>\n#include <unicode\/utf16.h>\n#include <algorithm>\n\n#include <minikin\/Emoji.h>\n#include <minikin\/GraphemeBreak.h>\n#include \"MinikinInternal.h\"\n#include \"utils\/WindowsUtils.h\"\n\nnamespace minikin {\n\nint32_t tailoredGraphemeClusterBreak(uint32_t c) {\n \/\/ Characters defined as Control that we want to treat them as Extend.\n \/\/ These are curated manually.\n if (c == 0x00AD \/\/ SHY\n || c == 0x061C \/\/ ALM\n || c == 0x180E \/\/ MONGOLIAN VOWEL SEPARATOR\n || c == 0x200B \/\/ ZWSP\n || c == 0x200E \/\/ LRM\n || c == 0x200F \/\/ RLM\n || (0x202A <= c && c <= 0x202E) \/\/ LRE, RLE, PDF, LRO, RLO\n || ((c | 0xF) ==\n 0x206F) \/\/ WJ, invisible math operators, LRI, RLI, FSI, PDI,\n \/\/ and the deprecated invisible format controls\n || c == 0xFEFF \/\/ BOM\n || ((c | 0x7F) ==\n 0xE007F)) \/\/ recently undeprecated tag characters in Plane 14\n return U_GCB_EXTEND;\n \/\/ THAI CHARACTER SARA AM is treated as a normal letter by most other\n \/\/ implementations: they allow a grapheme break before it.\n else if (c == 0x0E33)\n return U_GCB_OTHER;\n else\n return u_getIntPropertyValue(c, UCHAR_GRAPHEME_CLUSTER_BREAK);\n}\n\n\/\/ Returns true for all characters whose IndicSyllabicCategory is Pure_Killer.\n\/\/ From http:\/\/www.unicode.org\/Public\/9.0.0\/ucd\/IndicSyllabicCategory.txt\nbool isPureKiller(uint32_t c) {\n return (c == 0x0E3A || c == 0x0E4E || c == 0x0F84 || c == 0x103A ||\n c == 0x1714 || c == 0x1734 || c == 0x17D1 || c == 0x1BAA ||\n c == 0x1BF2 || c == 0x1BF3 || c == 0xA806 || c == 0xA953 ||\n c == 0xABED || c == 0x11134 || c == 0x112EA || c == 0x1172B);\n}\n\nbool GraphemeBreak::isGraphemeBreak(const float* advances,\n const uint16_t* buf,\n size_t start,\n size_t count,\n const size_t offset) {\n \/\/ This implementation closely follows Unicode Standard Annex #29 on\n \/\/ Unicode Text Segmentation (http:\/\/www.unicode.org\/reports\/tr29\/),\n \/\/ implementing a tailored version of extended grapheme clusters.\n \/\/ The GB rules refer to section 3.1.1, Grapheme Cluster Boundary Rules.\n\n \/\/ Rule GB1, sot ÷; Rule GB2, ÷ eot\n if (offset <= start || offset >= start + count) {\n return true;\n }\n if (U16_IS_TRAIL(buf[offset])) {\n \/\/ Don't break a surrogate pair, but a lonely trailing surrogate pair is a\n \/\/ break\n return !U16_IS_LEAD(buf[offset - 1]);\n }\n uint32_t c1 = 0;\n uint32_t c2 = 0;\n size_t offset_back = offset;\n size_t offset_forward = offset;\n U16_PREV(buf, start, offset_back, c1);\n U16_NEXT(buf, offset_forward, start + count, c2);\n int32_t p1 = tailoredGraphemeClusterBreak(c1);\n int32_t p2 = tailoredGraphemeClusterBreak(c2);\n \/\/ Rule GB3, CR x LF\n if (p1 == U_GCB_CR && p2 == U_GCB_LF) {\n return false;\n }\n \/\/ Rule GB4, (Control | CR | LF) ÷\n if (p1 == U_GCB_CONTROL || p1 == U_GCB_CR || p1 == U_GCB_LF) {\n return true;\n }\n \/\/ Rule GB5, ÷ (Control | CR | LF)\n if (p2 == U_GCB_CONTROL || p2 == U_GCB_CR || p2 == U_GCB_LF) {\n return true;\n }\n \/\/ Rule GB6, L x ( L | V | LV | LVT )\n if (p1 == U_GCB_L &&\n (p2 == U_GCB_L || p2 == U_GCB_V || p2 == U_GCB_LV || p2 == U_GCB_LVT)) {\n return false;\n }\n \/\/ Rule GB7, ( LV | V ) x ( V | T )\n if ((p1 == U_GCB_LV || p1 == U_GCB_V) && (p2 == U_GCB_V || p2 == U_GCB_T)) {\n return false;\n }\n \/\/ Rule GB8, ( LVT | T ) x T\n if ((p1 == U_GCB_LVT || p1 == U_GCB_T) && p2 == U_GCB_T) {\n return false;\n }\n \/\/ Rule GB9, x (Extend | ZWJ); Rule GB9a, x SpacingMark; Rule GB9b, Prepend x\n if (p2 == U_GCB_EXTEND || p2 == U_GCB_ZWJ || p2 == U_GCB_SPACING_MARK ||\n p1 == U_GCB_PREPEND) {\n return false;\n }\n\n \/\/ This is used to decide font-dependent grapheme clusters. If we don't have\n \/\/ the advance information, we become conservative in grapheme breaking and\n \/\/ assume that it has no advance.\n const bool c2_has_advance =\n (advances != nullptr && advances[offset - start] != 0.0);\n\n \/\/ All the following rules are font-dependent, in the way that if we know c2\n \/\/ has an advance, we definitely know that it cannot form a grapheme with the\n \/\/ character(s) before it. So we make the decision in favor a grapheme break\n \/\/ early.\n if (c2_has_advance) {\n return true;\n }\n\n \/\/ Note: For Rule GB10 and GB11 below, we do not use the Unicode line breaking\n \/\/ properties for determining emoji-ness and carry our own data, because our\n \/\/ data could be more fresh than what ICU provides.\n \/\/\n \/\/ Tailored version of Rule GB10, (E_Base | EBG) Extend* × E_Modifier.\n \/\/ The rule itself says do not break between emoji base and emoji modifiers,\n \/\/ skipping all Extend characters. Variation selectors are considered Extend,\n \/\/ so they are handled fine.\n \/\/\n \/\/ We tailor this by requiring that an actual ligature is formed. If the font\n \/\/ doesn't form a ligature, we allow a break before the modifier.\n if (isEmojiModifier(c2)) {\n uint32_t c0 = c1;\n size_t offset_backback = offset_back;\n int32_t p0 = p1;\n if (p0 == U_GCB_EXTEND && offset_backback > start) {\n \/\/ skip over emoji variation selector\n U16_PREV(buf, start, offset_backback, c0);\n }\n if (isEmojiBase(c0)) {\n return false;\n }\n }\n\n \/\/ Tailored version of Rule GB11, ZWJ × (Glue_After_Zwj | EBG)\n \/\/ We try to make emoji sequences with ZWJ a single grapheme cluster, but only\n \/\/ if they actually merge to one cluster. So we are more relaxed than the UAX\n \/\/ #29 rules in accepting any emoji character after the ZWJ, but are tighter\n \/\/ in that we only treat it as one cluster if a ligature is actually formed\n \/\/ and we also require the character before the ZWJ to also be an emoji.\n if (p1 == U_GCB_ZWJ && isEmoji(c2) && offset_back > start) {\n \/\/ look at character before ZWJ to see that both can participate in an\n \/\/ emoji zwj sequence\n uint32_t c0 = 0;\n size_t offset_backback = offset_back;\n U16_PREV(buf, start, offset_backback, c0);\n if (c0 == 0xFE0F && offset_backback > start) {\n \/\/ skip over emoji variation selector\n U16_PREV(buf, start, offset_backback, c0);\n }\n if (isEmoji(c0)) {\n return false;\n }\n }\n\n \/\/ Tailored version of Rule GB12 and Rule GB13 that look at even-odd cases.\n \/\/ sot (RI RI)* RI x RI\n \/\/ [^RI] (RI RI)* RI x RI\n \/\/\n \/\/ If we have font information, we have already broken the cluster if and only\n \/\/ if the second character had no advance, which means a ligature was formed.\n \/\/ If we don't, we look back like UAX #29 recommends, but only up to 1000 code\n \/\/ units.\n if (p1 == U_GCB_REGIONAL_INDICATOR && p2 == U_GCB_REGIONAL_INDICATOR) {\n if (advances != nullptr) {\n \/\/ We have advances information. But if we are here, we already know c2\n \/\/ has no advance. So we should definitely disallow a break.\n return false;\n } else {\n \/\/ Look at up to 1000 code units.\n const size_t lookback_barrier =\n std::max((ssize_t)start, (ssize_t)offset_back - 1000);\n size_t offset_backback = offset_back;\n while (offset_backback > lookback_barrier) {\n uint32_t c0 = 0;\n U16_PREV(buf, lookback_barrier, offset_backback, c0);\n if (tailoredGraphemeClusterBreak(c0) != U_GCB_REGIONAL_INDICATOR) {\n offset_backback += U16_LENGTH(c0);\n break;\n }\n }\n \/\/ The number 4 comes from the number of code units in a whole flag.\n return (offset - offset_backback) % 4 == 0;\n }\n }\n \/\/ Cluster Indic syllables together (tailoring of UAX #29).\n \/\/ Immediately after each virama (that is not just a pure killer) followed by\n \/\/ a letter, we disallow grapheme breaks (if we are here, we don't know about\n \/\/ advances, or we already know that c2 has no advance).\n if (u_getIntPropertyValue(c1, UCHAR_CANONICAL_COMBINING_CLASS) == 9 \/\/ virama\n && !isPureKiller(c1) &&\n u_getIntPropertyValue(c2, UCHAR_GENERAL_CATEGORY) == U_OTHER_LETTER) {\n return false;\n }\n \/\/ Rule GB999, Any ÷ Any\n return true;\n}\n\nsize_t GraphemeBreak::getTextRunCursor(const float* advances,\n const uint16_t* buf,\n size_t start,\n size_t count,\n size_t offset,\n MoveOpt opt) {\n switch (opt) {\n case AFTER:\n if (offset < start + count) {\n offset++;\n }\n \/\/ fall through\n case AT_OR_AFTER:\n while (!isGraphemeBreak(advances, buf, start, count, offset)) {\n offset++;\n }\n break;\n case BEFORE:\n if (offset > start) {\n offset--;\n }\n \/\/ fall through\n case AT_OR_BEFORE:\n while (!isGraphemeBreak(advances, buf, start, count, offset)) {\n offset--;\n }\n break;\n case AT:\n if (!isGraphemeBreak(advances, buf, start, count, offset)) {\n offset = (size_t)-1;\n }\n break;\n }\n return offset;\n}\n\n} \/\/ namespace minikin\n<|endoftext|>"} {"text":"<commit_before>\n\nenum disir_status\nbasic_section(struct disir_mold **mold)\n{\n enum disir_status status;\n struct disir_context *context_section;\n struct disir_context *context_mold;\n\n\n status = dc_mold_begin (&context_mold);\n if (status != DISIR_STATUS_OK)\n goto error;\n\n status = dc_add_documentation (context_mold, \"test_doc\", strlen (\"test_doc\"));\n if (status != DISIR_STATUS_OK)\n goto error;\n\n status = dc_begin (context_mold, DISIR_CONTEXT_SECTION, &context_section);\n if (status != DISIR_STATUS_OK)\n goto error;\n\n status = dc_set_name (context_section, \"section_name\", strlen (\"section_name\"));\n if (status != DISIR_STATUS_OK)\n goto error;\n\n status = dc_add_keyval_string (context_section, \"k1\", \"k1value\", \"k1value doc\", NULL);\n if (status != DISIR_STATUS_OK)\n goto error;\n\n status = dc_add_keyval_string (context_section, \"k2\", \"k2value\", \"k2value doc\", NULL);\n if (status != DISIR_STATUS_OK)\n goto error;\n\n status = dc_add_keyval_string (context_section, \"k3\", \"k3value\", \"k3value doc\", NULL);\n if (status != DISIR_STATUS_OK)\n goto error;\n\n status = dc_finalize (&context_section);\n if (status != DISIR_STATUS_OK);\n goto error;\n\n status = dc_mold_finalize (&context_mold, mold);\n if (status != DISIR_STATUS_OK)\n goto error;\n\n return DISIR_STATUS_OK;\nerror:\n if (context_section)\n {\n dc_destroy (&context_section);\n }\n if (context_mold)\n {\n dc_destroy (&context_mold);\n }\n return status;\n}\n\n<commit_msg>fix: remove semicolon in if-statement.<commit_after>\n\nenum disir_status\nbasic_section(struct disir_mold **mold)\n{\n enum disir_status status;\n struct disir_context *context_section;\n struct disir_context *context_mold;\n\n\n status = dc_mold_begin (&context_mold);\n if (status != DISIR_STATUS_OK)\n goto error;\n\n status = dc_add_documentation (context_mold, \"test_doc\", strlen (\"test_doc\"));\n if (status != DISIR_STATUS_OK)\n goto error;\n\n status = dc_begin (context_mold, DISIR_CONTEXT_SECTION, &context_section);\n if (status != DISIR_STATUS_OK)\n goto error;\n\n status = dc_set_name (context_section, \"section_name\", strlen (\"section_name\"));\n if (status != DISIR_STATUS_OK)\n goto error;\n\n status = dc_add_keyval_string (context_section, \"k1\", \"k1value\", \"k1value doc\", NULL);\n if (status != DISIR_STATUS_OK)\n goto error;\n\n status = dc_add_keyval_string (context_section, \"k2\", \"k2value\", \"k2value doc\", NULL);\n if (status != DISIR_STATUS_OK)\n goto error;\n\n status = dc_add_keyval_string (context_section, \"k3\", \"k3value\", \"k3value doc\", NULL);\n if (status != DISIR_STATUS_OK)\n goto error;\n\n status = dc_finalize (&context_section);\n if (status != DISIR_STATUS_OK)\n goto error;\n\n status = dc_mold_finalize (&context_mold, mold);\n if (status != DISIR_STATUS_OK)\n goto error;\n\n return DISIR_STATUS_OK;\nerror:\n if (context_section)\n {\n dc_destroy (&context_section);\n }\n if (context_mold)\n {\n dc_destroy (&context_mold);\n }\n return status;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 2015 Dmitry Marakasov <amdmi3@amdmi3.ru>\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n *\/\n\n#include <binfmt\/Buffer.hh>\n\n#include <binfmt\/internal\/ManagedChunk.hh>\n\n#include <algorithm>\n\nnamespace BinFmt {\n\nBuffer::Buffer(std::shared_ptr<Internal::Chunk> chunk, size_t offset, size_t size) : chunk_(chunk), offset_(offset), size_(size) {\n\tsize_t real_size = chunk_->GetSize();\n\tif (offset_ > real_size)\n\t\toffset_ = real_size;\n\tif (size_ > real_size - offset_)\n\t\tsize_ = real_size - offset_;\n}\n\nBuffer::Buffer(size_t size) : chunk_(new Internal::ManagedChunk(size)) {\n}\n\nBuffer::~Buffer() {\n}\n\n\/\/ Modifiers\nvoid Buffer::Realloc(size_t size) {\n\tInternal::ManagedChunk* chunk = new Internal::ManagedChunk(0, size);\n\tchunk->Append(chunk_->GetData() + offset_, std::min(size, size_));\n\tchunk_.reset(chunk);\n\toffset_ = 0;\n}\n\nvoid Buffer::Reserve(size_t size) {\n\tReserveGreedy(size, size);\n}\n\nvoid Buffer::ReserveGreedy(size_t needed, size_t desired) {\n\t\/\/ we'll not shrink\n\tif (needed < size_)\n\t\tneeded = size_;\n\tif (desired < needed)\n\t\tdesired = needed;\n\n\t\/\/ ensure chunk is appendable (slice ends where chunk used space ends, e.g.\n\t\/\/ there's no data possibly used by other slice we may override) and that\n\t\/\/ there's enough space\n\tif (offset_ + size_ != chunk_->GetSize() || needed > chunk_->GetCapacity() - offset_)\n\t\tRealloc(desired);\n}\n\nvoid Buffer::Append(Byte data) {\n\tAppend(&data, 1);\n}\n\nvoid Buffer::Append(const Byte* data, size_t size) {\n\tReserveGreedy(size_ + size, std::max(size_ + size, size_ * 2));\n\tchunk_->Append(data, size);\n\tsize_ += size;\n}\n\nvoid Buffer::Append(const Byte* start, const Byte* end) {\n\tAppend(start, end - start);\n}\n\nvoid Buffer::Append(const Slicable& data) {\n\tBuffer slice = data.GetSlice();\n\tAppend(slice.GetData(), slice.GetSize());\n}\n\n\/\/ Pointer\/size getters\nByte* Buffer::GetData() {\n\treturn chunk_->GetData() + offset_;\n}\n\nconst Byte* Buffer::GetData() const {\n\treturn chunk_->GetData() + offset_;\n}\n\nsize_t Buffer::GetSize() const {\n\treturn size_;\n}\n\nsize_t Buffer::GetCapacity() const {\n\treturn chunk_->GetCapacity() - offset_;\n}\n\n\/\/ subslice\nBuffer Buffer::GetSlice(size_t offset, size_t size) const {\n\tif (offset > size_)\n\t\toffset = size_;\n\tif (size > size_ - offset)\n\t\tsize = size_ - offset;\n\n\treturn Buffer(chunk_, offset_ + offset, size);\n}\n\nByte Buffer::operator[](size_t offset) const {\n\tconst Byte* offptr = chunk_->GetData() + offset_ + offset;\n\treturn *offptr;\n}\n\nuint8_t Buffer::GetU8(size_t offset) const {\n\tconst Byte* offptr = chunk_->GetData() + offset_ + offset;\n\treturn (uint8_t)*offptr;\n}\n\nint8_t Buffer::GetS8(size_t offset) const {\n\tconst Byte* offptr = chunk_->GetData() + offset_ + offset;\n\treturn (int8_t)*offptr;\n}\n\nuint16_t Buffer::GetU16LE(size_t offset) const {\n\tconst Byte* offptr = chunk_->GetData() + offset_ + offset;\n\treturn (uint16_t)(uint8_t)*(offptr)\n\t\t| ((uint16_t)(uint8_t)*(offptr + 1) << 8);\n}\n\nint16_t Buffer::GetS16LE(size_t offset) const {\n\treturn (int16_t)GetU16LE(offset);\n}\n\nuint16_t Buffer::GetU16BE(size_t offset) const {\n\tconst Byte* offptr = chunk_->GetData() + offset_ + offset;\n\treturn ((uint16_t)(uint8_t)*(offptr) << 8)\n\t\t| (uint16_t)(uint8_t)*(offptr + 1);\n}\nint16_t Buffer::GetS16BE(size_t offset) const {\n\treturn (int16_t)GetU16BE(offset);\n}\n\nuint32_t Buffer::GetU32LE(size_t offset) const {\n\tconst Byte* offptr = chunk_->GetData() + offset_ + offset;\n\treturn (uint32_t)(uint8_t)*(offptr)\n\t\t| ((uint32_t)(uint8_t)*(offptr + 1) << 8)\n\t\t| ((uint32_t)(uint8_t)*(offptr + 2) << 16)\n\t\t| ((uint32_t)(uint8_t)*(offptr + 3) << 24);\n}\n\nint32_t Buffer::GetS32LE(size_t offset) const {\n\treturn (int32_t)GetU32LE(offset);\n}\n\nuint32_t Buffer::GetU32BE(size_t offset) const {\n\tconst Byte* offptr = chunk_->GetData() + offset_ + offset;\n\treturn ((uint32_t)(uint8_t)*(offptr) << 24)\n\t\t| ((uint32_t)(uint8_t)*(offptr + 1) << 16)\n\t\t| ((uint32_t)(uint8_t)*(offptr + 2) << 8)\n\t\t| (uint32_t)(uint8_t)*(offptr + 3);\n}\n\nint32_t Buffer::GetS32BE(size_t offset) const {\n\treturn (int32_t)GetU32BE(offset);\n}\n\nstd::string Buffer::GetString(size_t offset, size_t length) const {\n\tif (offset > size_)\n\t\toffset = size_;\n\tif (length > size_ - offset)\n\t\tlength = size_ - offset;\n\tconst Byte* start = chunk_->GetData() + offset_ + offset;\n\tconst Byte* zeropos = std::find(start, start + length, (Byte)0);\n\tif (zeropos != start + length)\n\t\tlength = zeropos - start;\n\treturn std::string(reinterpret_cast<const char*>(start), length);\n}\n\n}\n<commit_msg>Fix unitialized members<commit_after>\/*\n * Copyright (c) 2015 Dmitry Marakasov <amdmi3@amdmi3.ru>\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n *\/\n\n#include <binfmt\/Buffer.hh>\n\n#include <binfmt\/internal\/ManagedChunk.hh>\n\n#include <algorithm>\n\nnamespace BinFmt {\n\nBuffer::Buffer(std::shared_ptr<Internal::Chunk> chunk, size_t offset, size_t size) : chunk_(chunk), offset_(offset), size_(size) {\n\tsize_t real_size = chunk_->GetSize();\n\tif (offset_ > real_size)\n\t\toffset_ = real_size;\n\tif (size_ > real_size - offset_)\n\t\tsize_ = real_size - offset_;\n}\n\nBuffer::Buffer(size_t size) : chunk_(new Internal::ManagedChunk(size)), offset_(0), size_(size) {\n}\n\nBuffer::~Buffer() {\n}\n\n\/\/ Modifiers\nvoid Buffer::Realloc(size_t size) {\n\tInternal::ManagedChunk* chunk = new Internal::ManagedChunk(0, size);\n\tchunk->Append(chunk_->GetData() + offset_, std::min(size, size_));\n\tchunk_.reset(chunk);\n\toffset_ = 0;\n}\n\nvoid Buffer::Reserve(size_t size) {\n\tReserveGreedy(size, size);\n}\n\nvoid Buffer::ReserveGreedy(size_t needed, size_t desired) {\n\t\/\/ we'll not shrink\n\tif (needed < size_)\n\t\tneeded = size_;\n\tif (desired < needed)\n\t\tdesired = needed;\n\n\t\/\/ ensure chunk is appendable (slice ends where chunk used space ends, e.g.\n\t\/\/ there's no data possibly used by other slice we may override) and that\n\t\/\/ there's enough space\n\tif (offset_ + size_ != chunk_->GetSize() || needed > chunk_->GetCapacity() - offset_)\n\t\tRealloc(desired);\n}\n\nvoid Buffer::Append(Byte data) {\n\tAppend(&data, 1);\n}\n\nvoid Buffer::Append(const Byte* data, size_t size) {\n\tReserveGreedy(size_ + size, std::max(size_ + size, size_ * 2));\n\tchunk_->Append(data, size);\n\tsize_ += size;\n}\n\nvoid Buffer::Append(const Byte* start, const Byte* end) {\n\tAppend(start, end - start);\n}\n\nvoid Buffer::Append(const Slicable& data) {\n\tBuffer slice = data.GetSlice();\n\tAppend(slice.GetData(), slice.GetSize());\n}\n\n\/\/ Pointer\/size getters\nByte* Buffer::GetData() {\n\treturn chunk_->GetData() + offset_;\n}\n\nconst Byte* Buffer::GetData() const {\n\treturn chunk_->GetData() + offset_;\n}\n\nsize_t Buffer::GetSize() const {\n\treturn size_;\n}\n\nsize_t Buffer::GetCapacity() const {\n\treturn chunk_->GetCapacity() - offset_;\n}\n\n\/\/ subslice\nBuffer Buffer::GetSlice(size_t offset, size_t size) const {\n\tif (offset > size_)\n\t\toffset = size_;\n\tif (size > size_ - offset)\n\t\tsize = size_ - offset;\n\n\treturn Buffer(chunk_, offset_ + offset, size);\n}\n\nByte Buffer::operator[](size_t offset) const {\n\tconst Byte* offptr = chunk_->GetData() + offset_ + offset;\n\treturn *offptr;\n}\n\nuint8_t Buffer::GetU8(size_t offset) const {\n\tconst Byte* offptr = chunk_->GetData() + offset_ + offset;\n\treturn (uint8_t)*offptr;\n}\n\nint8_t Buffer::GetS8(size_t offset) const {\n\tconst Byte* offptr = chunk_->GetData() + offset_ + offset;\n\treturn (int8_t)*offptr;\n}\n\nuint16_t Buffer::GetU16LE(size_t offset) const {\n\tconst Byte* offptr = chunk_->GetData() + offset_ + offset;\n\treturn (uint16_t)(uint8_t)*(offptr)\n\t\t| ((uint16_t)(uint8_t)*(offptr + 1) << 8);\n}\n\nint16_t Buffer::GetS16LE(size_t offset) const {\n\treturn (int16_t)GetU16LE(offset);\n}\n\nuint16_t Buffer::GetU16BE(size_t offset) const {\n\tconst Byte* offptr = chunk_->GetData() + offset_ + offset;\n\treturn ((uint16_t)(uint8_t)*(offptr) << 8)\n\t\t| (uint16_t)(uint8_t)*(offptr + 1);\n}\nint16_t Buffer::GetS16BE(size_t offset) const {\n\treturn (int16_t)GetU16BE(offset);\n}\n\nuint32_t Buffer::GetU32LE(size_t offset) const {\n\tconst Byte* offptr = chunk_->GetData() + offset_ + offset;\n\treturn (uint32_t)(uint8_t)*(offptr)\n\t\t| ((uint32_t)(uint8_t)*(offptr + 1) << 8)\n\t\t| ((uint32_t)(uint8_t)*(offptr + 2) << 16)\n\t\t| ((uint32_t)(uint8_t)*(offptr + 3) << 24);\n}\n\nint32_t Buffer::GetS32LE(size_t offset) const {\n\treturn (int32_t)GetU32LE(offset);\n}\n\nuint32_t Buffer::GetU32BE(size_t offset) const {\n\tconst Byte* offptr = chunk_->GetData() + offset_ + offset;\n\treturn ((uint32_t)(uint8_t)*(offptr) << 24)\n\t\t| ((uint32_t)(uint8_t)*(offptr + 1) << 16)\n\t\t| ((uint32_t)(uint8_t)*(offptr + 2) << 8)\n\t\t| (uint32_t)(uint8_t)*(offptr + 3);\n}\n\nint32_t Buffer::GetS32BE(size_t offset) const {\n\treturn (int32_t)GetU32BE(offset);\n}\n\nstd::string Buffer::GetString(size_t offset, size_t length) const {\n\tif (offset > size_)\n\t\toffset = size_;\n\tif (length > size_ - offset)\n\t\tlength = size_ - offset;\n\tconst Byte* start = chunk_->GetData() + offset_ + offset;\n\tconst Byte* zeropos = std::find(start, start + length, (Byte)0);\n\tif (zeropos != start + length)\n\t\tlength = zeropos - start;\n\treturn std::string(reinterpret_cast<const char*>(start), length);\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before>\n#include <sys\/stat.h>\n#include <iostream>\n#include <string>\nusing namespace std;\n\n#include \"config.h\"\n\n#include \"mds\/MDCluster.h\"\n#include \"mds\/MDS.h\"\n#include \"osd\/OSD.h\"\n#include \"client\/Client.h\"\n#include \"client\/SyntheticClient.h\"\n\n#include \"msg\/TCPMessenger.h\"\n\n#include \"common\/Timer.h\"\n\n#define NUMMDS g_conf.num_mds\n#define NUMOSD g_conf.num_osd\n#define NUMCLIENT g_conf.num_client\n\nclass C_Test : public Context {\npublic:\n void finish(int r) {\n\tcout << \"C_Test->finish(\" << r << \")\" << endl;\n }\n};\n\n\n#include \"msg\/mpistarter.cc\"\n\nutime_t tick_start;\n\nclass C_Tick : public Context {\npublic:\n void finish(int) {\n\tutime_t now = g_clock.now() - tick_start;\n\tdout(0) << \"tick +\" << g_conf.tick << \" -> \" << now << endl;\n\tg_timer.add_event_after(g_conf.tick, new C_Tick);\n }\n};\n\nclass C_Die : public Context {\npublic:\n void finish(int) {\n\tcerr << \"die\" << endl;\n\texit(1);\n }\n};\n\nclass C_Debug : public Context {\n public:\n void finish(int) {\n\tint size = &g_conf.debug_after - &g_conf.debug;\n\tmemcpy((char*)&g_conf.debug, (char*)&g_debug_after_conf.debug, size);\n\tdout(0) << \"debug_after flipping debug settings\" << endl;\n }\n};\n\n\nint main(int argc, char **argv) \n{\n vector<char*> args;\n argv_to_vec(argc, argv, args);\n\n parse_config_options(args);\n\n parse_syn_options(args);\n\n if (g_conf.kill_after) \n\tg_timer.add_event_after(g_conf.kill_after, new C_Die);\n if (g_conf.debug_after) \n\tg_timer.add_event_after(g_conf.debug_after, new C_Debug);\n\n if (g_conf.tick) {\n\ttick_start = g_clock.now();\n\tg_timer.add_event_after(g_conf.tick, new C_Tick);\n }\n\n vector<char*> nargs;\n for (unsigned i=0; i<args.size(); i++) {\n\t\/\/cout << \"a \" << args[i] << endl;\n\t\/\/ unknown arg, pass it on.\n\tnargs.push_back(args[i]);\n }\n\n args = nargs;\n if (!args.empty()) {\n\tfor (unsigned i=0; i<args.size(); i++)\n\t cout << \"stray arg \" << args[i] << endl;\n }\n assert(args.empty());\n\n\n \/\/ start up tcp messenger via MPI\n pair<int,int> mpiwho = mpi_bootstrap_tcp(argc, argv);\n int myrank = mpiwho.first;\n int world = mpiwho.second;\n\n if (myrank == 0)\n\tcerr << \"nummds \" << NUMMDS << \" numosd \" << NUMOSD << \" numclient \" << NUMCLIENT << endl;\n assert(NUMMDS + NUMOSD + (NUMCLIENT?1:0) <= world);\n\n MDCluster *mdc = new MDCluster(NUMMDS, NUMOSD);\n\n\n char hostname[100];\n gethostname(hostname,100);\n int pid = getpid();\n\n int started = 0;\n\n \/\/if (myrank == 0) g_conf.debug = 20;\n\n \/\/ create mds\n MDS *mds[NUMMDS];\n for (int i=0; i<NUMMDS; i++) {\n\tif (myrank != g_conf.tcp_skip_rank0+i) continue;\n\tTCPMessenger *m = new TCPMessenger(MSG_ADDR_MDS(i));\n\tcerr << \"mds\" << i << \" on tcprank \" << tcpmessenger_get_rank() << \" \" << hostname << \".\" << pid << endl;\n\tmds[i] = new MDS(mdc, i, m);\n\tmds[i]->init();\n\tstarted++;\n }\n \n \/\/ create osd\n OSD *osd[NUMOSD];\n for (int i=0; i<NUMOSD; i++) {\n\tif (myrank != g_conf.tcp_skip_rank0+NUMMDS + i) continue;\n\tTCPMessenger *m = new TCPMessenger(MSG_ADDR_OSD(i));\n\tcerr << \"osd\" << i << \" on tcprank \" << tcpmessenger_get_rank() << \" \" << hostname << \".\" << pid << endl;\n\tosd[i] = new OSD(i, m);\n\tosd[i]->init();\n\tstarted++;\n }\n \n \/\/ create client\n int client_nodes = world - NUMMDS - NUMOSD - g_conf.tcp_skip_rank0;\n int clients_per_node = 1;\n if (NUMCLIENT) clients_per_node = (NUMCLIENT-1) \/ client_nodes + 1;\n set<int> clientlist;\n Client *client[NUMCLIENT];\n SyntheticClient *syn[NUMCLIENT];\n for (int i=0; i<NUMCLIENT; i++) {\n\t\/\/if (myrank != NUMMDS + NUMOSD + i % client_nodes) continue;\n\tif (myrank != g_conf.tcp_skip_rank0+NUMMDS + NUMOSD + i \/ clients_per_node) continue;\n\tclientlist.insert(i);\n\tclient[i] = new Client(new TCPMessenger(MSG_ADDR_CLIENT(i)) );\n\n\t\/\/ logger?\n\tif (client_logger == 0) {\n\t char s[80];\n\t sprintf(s,\"clnode.%d\", myrank);\n\t client_logger = new Logger(s, &client_logtype);\n\n\t client_logtype.add_inc(\"lsum\");\n\t client_logtype.add_inc(\"lnum\");\n\t client_logtype.add_inc(\"lwsum\");\n\t client_logtype.add_inc(\"lwnum\");\n\t client_logtype.add_inc(\"lrsum\");\n\t client_logtype.add_inc(\"lrnum\");\n\t client_logtype.add_inc(\"trsum\");\n\t client_logtype.add_inc(\"trnum\");\n\t}\n\n\tclient[i]->init();\n\tstarted++;\n }\n\n int nclients = 0;\n for (set<int>::iterator it = clientlist.begin();\n\t it != clientlist.end();\n\t it++) {\n\tint i = *it;\n\n\n\tclient[i]->mount();\n\t\n\t\/\/cout << \"starting synthetic client on rank \" << myrank << endl;\n\tsyn[i] = new SyntheticClient(client[i]);\n\n\tsyn[i]->start_thread();\n\t\n\tnclients++;\n }\n if (nclients) {\n\tcerr << nclients << \" clients on tcprank \" << tcpmessenger_get_rank() << \" \" << hostname << \".\" << pid << endl;\n }\n\n for (set<int>::iterator it = clientlist.begin();\n\t it != clientlist.end();\n\t it++) {\n\tint i = *it;\n\n\t\/\/\t cout << \"waiting for synthetic client\" << i << \" to finish\" << endl;\n\tsyn[i]->join_thread();\n\tdelete syn[i];\n\t\n\tclient[i]->unmount();\n\t\/\/cout << \"client\" << i << \" unmounted\" << endl;\n\tclient[i]->shutdown();\n }\n \n\n if (myrank && !started) {\n\t\/\/dout(1) << \"IDLE\" << endl;\n\tcerr << \"idle on tcprank \" << tcpmessenger_get_rank() << \" \" << hostname << \".\" << pid << endl; \n\ttcpmessenger_stop_rankserver();\n }\n\n \/\/ wait for everything to finish\n tcpmessenger_wait();\n\n if (started) cerr << \"tcpsyn finishing\" << endl;\n \n tcpmessenger_shutdown(); \n \n\n \/*\n \/\/ cleanup\n for (int i=0; i<NUMMDS; i++) {\n\tif (myrank != MPI_DEST_TO_RANK(MSG_ADDR_MDS(i),world)) continue;\n\tdelete mds[i];\n }\n for (int i=0; i<NUMOSD; i++) {\n\tif (myrank != MPI_DEST_TO_RANK(MSG_ADDR_OSD(i),world)) continue;\n\tdelete osd[i];\n }\n for (int i=0; i<NUMCLIENT; i++) {\n\tif (myrank != MPI_DEST_TO_RANK(MSG_ADDR_CLIENT(i),world)) continue;\n\tdelete client[i];\n }\n *\/\n delete mdc;\n\n \n return 0;\n}\n\n<commit_msg>*** empty log message ***<commit_after>\n#include <sys\/stat.h>\n#include <iostream>\n#include <string>\nusing namespace std;\n\n#include \"config.h\"\n\n#include \"mds\/MDCluster.h\"\n#include \"mds\/MDS.h\"\n#include \"osd\/OSD.h\"\n#include \"client\/Client.h\"\n#include \"client\/SyntheticClient.h\"\n\n#include \"msg\/TCPMessenger.h\"\n\n#include \"common\/Timer.h\"\n\n#define NUMMDS g_conf.num_mds\n#define NUMOSD g_conf.num_osd\n#define NUMCLIENT g_conf.num_client\n\nclass C_Test : public Context {\npublic:\n void finish(int r) {\n\tcout << \"C_Test->finish(\" << r << \")\" << endl;\n }\n};\n\n\n#include \"msg\/mpistarter.cc\"\n\nutime_t tick_start;\nint tick_count = 0;\n\nclass C_Tick : public Context {\npublic:\n void finish(int) {\n\tutime_t now = g_clock.now() - tick_start;\n\tdout(0) << \"tick +\" << g_conf.tick << \" -> \" << now << \" (\" << tick_count << \")\" << endl;\n\ttick_count += g_conf.tick;\n\tutime_t next = tick_start;\n\tnext.sec_ref() += tick_count;\n\tg_timer.add_event_at(next, new C_Tick);\n }\n};\n\nclass C_Die : public Context {\npublic:\n void finish(int) {\n\tcerr << \"die\" << endl;\n\texit(1);\n }\n};\n\nclass C_Debug : public Context {\n public:\n void finish(int) {\n\tint size = &g_conf.debug_after - &g_conf.debug;\n\tmemcpy((char*)&g_conf.debug, (char*)&g_debug_after_conf.debug, size);\n\tdout(0) << \"debug_after flipping debug settings\" << endl;\n }\n};\n\n\nint main(int argc, char **argv) \n{\n vector<char*> args;\n argv_to_vec(argc, argv, args);\n\n parse_config_options(args);\n\n parse_syn_options(args);\n\n if (g_conf.kill_after) \n\tg_timer.add_event_after(g_conf.kill_after, new C_Die);\n if (g_conf.debug_after) \n\tg_timer.add_event_after(g_conf.debug_after, new C_Debug);\n\n if (g_conf.tick) {\n\ttick_start = g_clock.now();\n\tg_timer.add_event_after(g_conf.tick, new C_Tick);\n }\n\n vector<char*> nargs;\n for (unsigned i=0; i<args.size(); i++) {\n\t\/\/cout << \"a \" << args[i] << endl;\n\t\/\/ unknown arg, pass it on.\n\tnargs.push_back(args[i]);\n }\n\n args = nargs;\n if (!args.empty()) {\n\tfor (unsigned i=0; i<args.size(); i++)\n\t cout << \"stray arg \" << args[i] << endl;\n }\n assert(args.empty());\n\n\n \/\/ start up tcp messenger via MPI\n pair<int,int> mpiwho = mpi_bootstrap_tcp(argc, argv);\n int myrank = mpiwho.first;\n int world = mpiwho.second;\n\n if (myrank == 0)\n\tcerr << \"nummds \" << NUMMDS << \" numosd \" << NUMOSD << \" numclient \" << NUMCLIENT << endl;\n assert(NUMMDS + NUMOSD + (NUMCLIENT?1:0) <= world);\n\n MDCluster *mdc = new MDCluster(NUMMDS, NUMOSD);\n\n\n char hostname[100];\n gethostname(hostname,100);\n int pid = getpid();\n\n int started = 0;\n\n \/\/if (myrank == 0) g_conf.debug = 20;\n\n \/\/ create mds\n MDS *mds[NUMMDS];\n for (int i=0; i<NUMMDS; i++) {\n\tif (myrank != g_conf.tcp_skip_rank0+i) continue;\n\tTCPMessenger *m = new TCPMessenger(MSG_ADDR_MDS(i));\n\tcerr << \"mds\" << i << \" on tcprank \" << tcpmessenger_get_rank() << \" \" << hostname << \".\" << pid << endl;\n\tmds[i] = new MDS(mdc, i, m);\n\tmds[i]->init();\n\tstarted++;\n }\n \n \/\/ create osd\n OSD *osd[NUMOSD];\n for (int i=0; i<NUMOSD; i++) {\n\tif (myrank != g_conf.tcp_skip_rank0+NUMMDS + i) continue;\n\tTCPMessenger *m = new TCPMessenger(MSG_ADDR_OSD(i));\n\tcerr << \"osd\" << i << \" on tcprank \" << tcpmessenger_get_rank() << \" \" << hostname << \".\" << pid << endl;\n\tosd[i] = new OSD(i, m);\n\tosd[i]->init();\n\tstarted++;\n }\n \n \/\/ create client\n int client_nodes = world - NUMMDS - NUMOSD - g_conf.tcp_skip_rank0;\n int clients_per_node = 1;\n if (NUMCLIENT) clients_per_node = (NUMCLIENT-1) \/ client_nodes + 1;\n set<int> clientlist;\n Client *client[NUMCLIENT];\n SyntheticClient *syn[NUMCLIENT];\n for (int i=0; i<NUMCLIENT; i++) {\n\t\/\/if (myrank != NUMMDS + NUMOSD + i % client_nodes) continue;\n\tif (myrank != g_conf.tcp_skip_rank0+NUMMDS + NUMOSD + i \/ clients_per_node) continue;\n\tclientlist.insert(i);\n\tclient[i] = new Client(new TCPMessenger(MSG_ADDR_CLIENT(i)) );\n\n\t\/\/ logger?\n\tif (client_logger == 0) {\n\t char s[80];\n\t sprintf(s,\"clnode.%d\", myrank);\n\t client_logger = new Logger(s, &client_logtype);\n\n\t client_logtype.add_inc(\"lsum\");\n\t client_logtype.add_inc(\"lnum\");\n\t client_logtype.add_inc(\"lwsum\");\n\t client_logtype.add_inc(\"lwnum\");\n\t client_logtype.add_inc(\"lrsum\");\n\t client_logtype.add_inc(\"lrnum\");\n\t client_logtype.add_inc(\"trsum\");\n\t client_logtype.add_inc(\"trnum\");\n\t}\n\n\tclient[i]->init();\n\tstarted++;\n }\n\n int nclients = 0;\n for (set<int>::iterator it = clientlist.begin();\n\t it != clientlist.end();\n\t it++) {\n\tint i = *it;\n\n\n\tclient[i]->mount();\n\t\n\t\/\/cout << \"starting synthetic client on rank \" << myrank << endl;\n\tsyn[i] = new SyntheticClient(client[i]);\n\n\tsyn[i]->start_thread();\n\t\n\tnclients++;\n }\n if (nclients) {\n\tcerr << nclients << \" clients on tcprank \" << tcpmessenger_get_rank() << \" \" << hostname << \".\" << pid << endl;\n }\n\n for (set<int>::iterator it = clientlist.begin();\n\t it != clientlist.end();\n\t it++) {\n\tint i = *it;\n\n\t\/\/\t cout << \"waiting for synthetic client\" << i << \" to finish\" << endl;\n\tsyn[i]->join_thread();\n\tdelete syn[i];\n\t\n\tclient[i]->unmount();\n\t\/\/cout << \"client\" << i << \" unmounted\" << endl;\n\tclient[i]->shutdown();\n }\n \n\n if (myrank && !started) {\n\t\/\/dout(1) << \"IDLE\" << endl;\n\tcerr << \"idle on tcprank \" << tcpmessenger_get_rank() << \" \" << hostname << \".\" << pid << endl; \n\ttcpmessenger_stop_rankserver();\n }\n\n \/\/ wait for everything to finish\n tcpmessenger_wait();\n\n if (started) cerr << \"tcpsyn finishing\" << endl;\n \n tcpmessenger_shutdown(); \n \n\n \/*\n \/\/ cleanup\n for (int i=0; i<NUMMDS; i++) {\n\tif (myrank != MPI_DEST_TO_RANK(MSG_ADDR_MDS(i),world)) continue;\n\tdelete mds[i];\n }\n for (int i=0; i<NUMOSD; i++) {\n\tif (myrank != MPI_DEST_TO_RANK(MSG_ADDR_OSD(i),world)) continue;\n\tdelete osd[i];\n }\n for (int i=0; i<NUMCLIENT; i++) {\n\tif (myrank != MPI_DEST_TO_RANK(MSG_ADDR_CLIENT(i),world)) continue;\n\tdelete client[i];\n }\n *\/\n delete mdc;\n\n \n return 0;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n * VapourSynth D2V Plugin\n *\n * Copyright (c) 2012 Derek Buitenhuis\n *\n * This file is part of d2vsource.\n *\n * d2vsource is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * d2vsource is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with d2vsource; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n *\/\n\nextern \"C\" {\n#include <stdint.h>\n#include <stdlib.h>\n}\n\n#include <algorithm>\n\n#include <VapourSynth.h>\n#include <VSHelper.h>\n\n#include \"applyrff.hpp\"\n#include \"d2v.hpp\"\n#include \"gop.hpp\"\n\nvoid VS_CC rffInit(VSMap *in, VSMap *out, void **instanceData, VSNode *node, VSCore *core, const VSAPI *vsapi)\n{\n rffData *d = (rffData *) *instanceData;\n vsapi->setVideoInfo(&d->vi, 1, node);\n}\n\nconst VSFrameRef *VS_CC rffGetFrame(int n, int activationReason, void **instanceData, void **frameData,\n VSFrameContext *frameCtx, VSCore *core, const VSAPI *vsapi)\n{\n const rffData *d = (const rffData *) *instanceData;\n const VSFrameRef *st, *sb;\n VSFrameRef *f;\n string msg;\n int top, bottom;\n int i;\n bool samefields;\n\n \/* What frames to use for fields. *\/\n top = d->frames[n].top;\n bottom = d->frames[n].bottom;\n\n samefields = top == bottom;\n\n \/* Request out source frames. *\/\n if (activationReason == arInitial) {\n if (samefields) {\n vsapi->requestFrameFilter(top, d->node, frameCtx);\n } else {\n vsapi->requestFrameFilter(min(top, bottom), d->node, frameCtx);\n vsapi->requestFrameFilter(max(top, bottom), d->node, frameCtx);\n }\n return NULL;\n }\n\n \/* Check if we're ready yet. *\/\n if (activationReason != arAllFramesReady)\n return NULL;\n\n \/* Source and destination frames. *\/\n st = vsapi->getFrameFilter(top, d->node, frameCtx);\n sb = samefields ? NULL : vsapi->getFrameFilter(bottom, d->node, frameCtx);\n\n \/* Copy into VS's buffers. *\/\n if (samefields) {\n f = vsapi->copyFrame(st, core);\n } else {\n int dst_stride[3], srct_stride[3], srcb_stride[3];\n\n f = vsapi->newVideoFrame(d->vi.format, d->vi.width, d->vi.height, NULL, core);\n\n for (i = 0; i < d->vi.format->numPlanes; i++) {\n dst_stride[i] = vsapi->getStride(f, i);\n srct_stride[i] = vsapi->getStride(st, i);\n srcb_stride[i] = vsapi->getStride(sb, i);\n\n uint8_t *dstp = vsapi->getWritePtr(f, i);\n const uint8_t *srctp = vsapi->getReadPtr(st, i);\n const uint8_t *srcbp = vsapi->getReadPtr(sb, i);\n int width = vsapi->getFrameWidth(f, i);\n int height = vsapi->getFrameHeight(f, i);\n\n vs_bitblt(dstp, dst_stride[i] * 2,\n srctp, srct_stride[i] * 2,\n width * d->vi.format->bytesPerSample, height \/ 2);\n\n vs_bitblt(dstp + dst_stride[i], dst_stride[i] * 2,\n srcbp + srcb_stride[i], srcb_stride[i] * 2,\n width * d->vi.format->bytesPerSample, height \/ 2);\n }\n }\n\n \/*\n * Set progressive\/interlaced flag.\n *\n * This assumes the d2v has been properly run through d2vfix,\n * so that there is only one field order.\n *\n * This is probably wildly wrong. I hope nothign relies on this.\n *\/\n if (samefields) {\n VSMap *props = vsapi->getFramePropsRW(f);\n frame top_f = d->d2v->frames[top];\n\n vsapi->propSetInt(props, \"_FieldBased\",\n 1 + !!(d->d2v->gops[top_f.gop].flags[top_f.offset] & FRAME_FLAG_TFF), paReplace);\n }\n\n vsapi->freeFrame(st);\n if (!samefields)\n vsapi->freeFrame(sb);\n\n return f;\n}\n\nvoid VS_CC rffFree(void *instanceData, VSCore *core, const VSAPI *vsapi)\n{\n rffData *d = (rffData *) instanceData;\n vsapi->freeNode(d->node);\n d2vfreep(&d->d2v);\n d->frames.clear();\n delete d;\n}\n\nvoid VS_CC rffCreate(const VSMap *in, VSMap *out, void *userData, VSCore *core, const VSAPI *vsapi)\n{\n rffData *data;\n fieldFrame ff = { -1, -1 };\n string msg;\n int total_fields;\n int i;\n\n \/* Allocate our private data. *\/\n data = new(nothrow) rffData;\n if (!data) {\n vsapi->setError(out, \"Cannot allocate private data.\");\n return;\n }\n\n \/* Parse the D2V to get flags. *\/\n data->d2v = d2vparse((char *) vsapi->propGetData(in, \"d2v\", 0, 0), msg);\n if (!data->d2v) {\n vsapi->setError(out, msg.c_str());\n delete data;\n return;\n }\n\n \/* Get our frame info and copy it, so we can modify it after. *\/\n data->node = vsapi->propGetNode(in, \"clip\", 0, 0);\n data->vi = *vsapi->getVideoInfo(data->node);\n\n \/*\n * Parse all the RFF flags to figure out which fields go\n * with which frames, and out total number of frames after\n * apply the RFF flags.\n *\/\n total_fields = 0;\n data->frames.push_back(ff);\n for(i = 0; i < data->vi.numFrames; i++) {\n frame f = data->d2v->frames[i];\n int rff = data->d2v->gops[f.gop].flags[f.offset] & FRAME_FLAG_RFF;\n int pos = data->frames.size() - 1;\n\n if (rff) {\n if (data->frames[pos].top == -1) {\n data->frames[pos].top = i;\n data->frames[pos].bottom = i;\n\n ff.top = i;\n ff.bottom = -1;\n } else if (data->frames[pos].bottom == -1) {\n data->frames[pos].bottom = i;\n\n ff.top = i;\n ff.bottom = i;\n } else {\n ff.top = i;\n ff.bottom = i;\n\n data->frames.push_back(ff);\n\n ff.bottom = -1;\n }\n } else {\n if (data->frames[pos].top == -1) {\n data->frames[pos].top = i;\n data->frames[pos].bottom = i;\n\n ff.top = -1;\n ff.bottom = -1;\n } else if (data->frames[pos].bottom == -1) {\n data->frames[pos].bottom = i;\n\n ff.top = i;\n ff.bottom = -1;\n } else {\n ff.top = i;\n ff.bottom = i;\n }\n }\n data->frames.push_back(ff);\n\n total_fields += 2 + rff;\n }\n\n data->vi.numFrames = total_fields \/ 2;\n\n vsapi->createFilter(in, out, \"applyrff\", rffInit, rffGetFrame, rffFree, fmParallel, nfMakeLinear, data, core);\n}\n<commit_msg>applyrff: Correctly handle bottom field first streams<commit_after>\/*\n * VapourSynth D2V Plugin\n *\n * Copyright (c) 2012 Derek Buitenhuis\n *\n * This file is part of d2vsource.\n *\n * d2vsource is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * d2vsource is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with d2vsource; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n *\/\n\nextern \"C\" {\n#include <stdint.h>\n#include <stdlib.h>\n}\n\n#include <algorithm>\n\n#include <VapourSynth.h>\n#include <VSHelper.h>\n\n#include \"applyrff.hpp\"\n#include \"d2v.hpp\"\n#include \"gop.hpp\"\n\nvoid VS_CC rffInit(VSMap *in, VSMap *out, void **instanceData, VSNode *node, VSCore *core, const VSAPI *vsapi)\n{\n rffData *d = (rffData *) *instanceData;\n vsapi->setVideoInfo(&d->vi, 1, node);\n}\n\nconst VSFrameRef *VS_CC rffGetFrame(int n, int activationReason, void **instanceData, void **frameData,\n VSFrameContext *frameCtx, VSCore *core, const VSAPI *vsapi)\n{\n const rffData *d = (const rffData *) *instanceData;\n const VSFrameRef *st, *sb;\n VSFrameRef *f;\n string msg;\n int top, bottom;\n int i;\n bool samefields;\n\n \/* What frames to use for fields. *\/\n top = d->frames[n].top;\n bottom = d->frames[n].bottom;\n\n samefields = top == bottom;\n\n \/* Request out source frames. *\/\n if (activationReason == arInitial) {\n if (samefields) {\n vsapi->requestFrameFilter(top, d->node, frameCtx);\n } else {\n vsapi->requestFrameFilter(min(top, bottom), d->node, frameCtx);\n vsapi->requestFrameFilter(max(top, bottom), d->node, frameCtx);\n }\n return NULL;\n }\n\n \/* Check if we're ready yet. *\/\n if (activationReason != arAllFramesReady)\n return NULL;\n\n \/* Source and destination frames. *\/\n st = vsapi->getFrameFilter(top, d->node, frameCtx);\n sb = samefields ? NULL : vsapi->getFrameFilter(bottom, d->node, frameCtx);\n\n \/* Copy into VS's buffers. *\/\n if (samefields) {\n f = vsapi->copyFrame(st, core);\n } else {\n int dst_stride[3], srct_stride[3], srcb_stride[3];\n\n f = vsapi->newVideoFrame(d->vi.format, d->vi.width, d->vi.height, NULL, core);\n\n for (i = 0; i < d->vi.format->numPlanes; i++) {\n dst_stride[i] = vsapi->getStride(f, i);\n srct_stride[i] = vsapi->getStride(st, i);\n srcb_stride[i] = vsapi->getStride(sb, i);\n\n uint8_t *dstp = vsapi->getWritePtr(f, i);\n const uint8_t *srctp = vsapi->getReadPtr(st, i);\n const uint8_t *srcbp = vsapi->getReadPtr(sb, i);\n int width = vsapi->getFrameWidth(f, i);\n int height = vsapi->getFrameHeight(f, i);\n\n vs_bitblt(dstp, dst_stride[i] * 2,\n srctp, srct_stride[i] * 2,\n width * d->vi.format->bytesPerSample, height \/ 2);\n\n vs_bitblt(dstp + dst_stride[i], dst_stride[i] * 2,\n srcbp + srcb_stride[i], srcb_stride[i] * 2,\n width * d->vi.format->bytesPerSample, height \/ 2);\n }\n }\n\n \/*\n * Set progressive\/interlaced flag.\n *\n * This assumes the d2v has been properly run through d2vfix,\n * so that there is only one field order.\n *\n * This is probably wildly wrong. I hope nothign relies on this.\n *\/\n if (samefields) {\n VSMap *props = vsapi->getFramePropsRW(f);\n frame top_f = d->d2v->frames[top];\n\n vsapi->propSetInt(props, \"_FieldBased\",\n 1 + !!(d->d2v->gops[top_f.gop].flags[top_f.offset] & FRAME_FLAG_TFF), paReplace);\n }\n\n vsapi->freeFrame(st);\n if (!samefields)\n vsapi->freeFrame(sb);\n\n return f;\n}\n\nvoid VS_CC rffFree(void *instanceData, VSCore *core, const VSAPI *vsapi)\n{\n rffData *d = (rffData *) instanceData;\n vsapi->freeNode(d->node);\n d2vfreep(&d->d2v);\n d->frames.clear();\n delete d;\n}\n\nvoid VS_CC rffCreate(const VSMap *in, VSMap *out, void *userData, VSCore *core, const VSAPI *vsapi)\n{\n rffData *data;\n fieldFrame ff = { -1, -1 };\n string msg;\n int total_fields;\n int i;\n\n \/* Allocate our private data. *\/\n data = new(nothrow) rffData;\n if (!data) {\n vsapi->setError(out, \"Cannot allocate private data.\");\n return;\n }\n\n \/* Parse the D2V to get flags. *\/\n data->d2v = d2vparse((char *) vsapi->propGetData(in, \"d2v\", 0, 0), msg);\n if (!data->d2v) {\n vsapi->setError(out, msg.c_str());\n delete data;\n return;\n }\n\n \/* Get our frame info and copy it, so we can modify it after. *\/\n data->node = vsapi->propGetNode(in, \"clip\", 0, 0);\n data->vi = *vsapi->getVideoInfo(data->node);\n\n \/*\n * Parse all the RFF flags to figure out which fields go\n * with which frames, and out total number of frames after\n * apply the RFF flags.\n *\/\n total_fields = 0;\n data->frames.push_back(ff);\n for(i = 0; i < data->vi.numFrames; i++) {\n frame f = data->d2v->frames[i];\n int rff = data->d2v->gops[f.gop].flags[f.offset] & FRAME_FLAG_RFF;\n int tff = data->d2v->gops[f.gop].flags[f.offset] & FRAME_FLAG_TFF;\n int pos = data->frames.size() - 1;\n\n int *pos_first, *pos_second, *ff_first, *ff_second;\n if (tff) {\n pos_first = &data->frames[pos].top;\n pos_second = &data->frames[pos].bottom;\n ff_first = &ff.top;\n ff_second = &ff.bottom;\n } else {\n pos_first = &data->frames[pos].bottom;\n pos_second = &data->frames[pos].top;\n ff_first = &ff.bottom;\n ff_second = &ff.top;\n }\n\n if (rff) {\n if (*pos_first == -1) {\n *pos_first = i;\n *pos_second = i;\n\n *ff_first = i;\n *ff_second = -1;\n } else if (*pos_second == -1) {\n *pos_second = i;\n\n *ff_first = i;\n *ff_second = i;\n } else {\n *ff_first = i;\n *ff_second = i;\n\n data->frames.push_back(ff);\n\n *ff_second = -1;\n }\n } else {\n if (*pos_first == -1) {\n *pos_first = i;\n *pos_second = i;\n\n *ff_first = -1;\n *ff_second = -1;\n } else if (*pos_second == -1) {\n *pos_second = i;\n\n *ff_first = i;\n *ff_second = -1;\n } else {\n *ff_first = i;\n *ff_second = i;\n }\n }\n data->frames.push_back(ff);\n\n total_fields += 2 + rff;\n }\n\n data->vi.numFrames = total_fields \/ 2;\n\n vsapi->createFilter(in, out, \"applyrff\", rffInit, rffGetFrame, rffFree, fmParallel, nfMakeLinear, data, core);\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/*****************************************************\n\/\/\n\/\/ Dialog which report the earning made with stake over time\n\/\/ Original coding by Remy5\n\/\/\n\n#include \"stakereportdialog.h\"\n#include \"ui_stakereportdialog.h\"\n\n#include \"guiconstants.h\"\n#include \"walletmodel.h\"\n#include \"sequenceunits.h\"\n#include \"rpc\/rpcserver.h\"\n#include \"optionsmodel.h\"\n#include \"main.h\"\n#include \"chain.h\"\n#include \"util.h\"\n\n#include \"wallet\/wallet.h\"\n#include \"wallet\/walletdb.h\"\n\n#include <QWidget>\n#include <QDateTime>\n#include <QTimer>\n#include <QClipboard>\n\n\/\/ using namespace json_spirit;\nusing namespace boost;\nusing namespace std;\n\nstruct StakePeriodRange_T {\n int64_t Start;\n int64_t End;\n int64_t Total;\n int Count;\n string Name;\n};\n\ntypedef vector<StakePeriodRange_T> vStakePeriodRange_T;\n\nextern vStakePeriodRange_T PrepareRangeForStakeReport();\nextern int GetStakeSubTotal(vStakePeriodRange_T& aRange, const isminefilter filter);\n\nStakeReportDialog::StakeReportDialog(QWidget *parent) :\n QDialog(parent),\n ui(new Ui::StakeReportDialog)\n{\n ui->setupUi(this);\n\n QTableWidget *TableW = ui->StakeReportTable;\n\n alreadyConnected = false;\n\n \/\/ fill the table with clone of row 0\n for(int y=TableW->rowCount(); --y >= 1;)\n for(int x=TableW->columnCount(); --x >= 0;)\n TableW->setItem(y, x,\n TableW->item(0, x)->clone());\n\n TableW->horizontalHeader()->resizeSection(1,160);\n\n QApplication::processEvents();\n\n updateStakeReportNow(); \/\/ 1st update\n}\n\nStakeReportDialog::~StakeReportDialog()\n{\n delete ui;\n}\n\nvoid StakeReportDialog::setModel(WalletModel *model)\n{\n this->ex_model = model;\n\n if(ex_model && ex_model->getOptionsModel() && !alreadyConnected)\n {\n alreadyConnected = true;\n\n connect(ex_model->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit(int)));\n connect(ui->button_Refresh, SIGNAL(clicked()), this, SLOT(updateStakeReportNow()));\n connect(ui->CopytoClipboard, SIGNAL(clicked()), this, SLOT(CopyAllToClipboard()));\n\n disablereportupdate = GetBoolArg(\"-disablereportupdate\", false);\n\n if (!disablereportupdate)\n {\n QTimer *timer = new QTimer(this);\n connect(timer, SIGNAL(timeout()), this, SLOT(updateStakeReportTimer()));\n \tconnect(ex_model, SIGNAL(balanceChanged(qint64, qint64, qint64, qint64)), this, SLOT(updateStakeReportbalanceChanged(qint64, qint64, qint64, qint64)));\n\n timer->start(MODEL_UPDATE_DELAY*5);\n }\n }\n}\n\nvoid StakeReportDialog::updateStakeReportbalanceChanged(qint64, qint64, qint64, qint64)\n{\n StakeReportDialog::updateStakeReportNow();\n}\n\nvoid StakeReportDialog::updateDisplayUnit(int)\n{\n StakeReportDialog::updateStakeReportNow();\n}\n\nvoid StakeReportDialog::updateStakeReportTimer()\n{\n static int lastBest = 0 ;\n if (lastBest != chainActive.Height())\n {\n lastBest = chainActive.Height();\n StakeReportDialog::updateStakeReport(false);\n }\n}\n\nvoid StakeReportDialog::showEvent( QShowEvent* event )\n{\n QWidget::showEvent( event );\n StakeReportDialog::updateStakeReportNow();\n}\n\n\/\/ Extendable localtime format\nQString HalfDate(int64_t nTime, QString TimeMode=\"\")\n{\n QDateTime OrigDate = QDateTime::fromTime_t((qint32)nTime);\n QString LocalDate = OrigDate.date().toString(\"yyyy-MM-dd\");\n if (TimeMode != \"\")\n LocalDate += \" \" + OrigDate.toString(TimeMode);\n\n return LocalDate;\n}\n\n\/\/ format Sequencevalue with all trailing zero\nQString Coin_0Pad(int nUnit, int64_t amount)\n{\n QString result = SequenceUnits::format(nUnit, amount);\n\n int poin = result.indexOf(\".\") + 1;\n poin += SequenceUnits::decimals(nUnit);\n\n return result.leftJustified(poin, '0');\n}\n\nvoid StakeReportDialog::updateStakeReportNow()\n{\n updateStakeReport(true);\n}\n\nvoid StakeReportDialog::updateStakeReport(bool fImmediate=false)\n{\n static vStakePeriodRange_T aRange;\n int nItemCounted=0;\n\n if (fImmediate) nLastReportUpdate = 0;\n\n if (this->isHidden())\n return;\n\n int64_t nTook = GetTimeMillis();\n\n \/\/ Skip report recalc if not immediate or before 5 minutes from last\n if (GetTime() - nLastReportUpdate > 300)\n {\n QApplication::processEvents();\n\n ui->TimeTook->setText(tr(\"Please wait...\"));\n ui->TimeTook->repaint();\n QApplication::processEvents();\n\n aRange = PrepareRangeForStakeReport();\n\n \/\/ get subtotal calc\n nItemCounted = GetStakeSubTotal(aRange, ISMINE_SPENDABLE);\n\n nLastReportUpdate = GetTime();\n\n nTook = GetTimeMillis() - nTook;\n\n }\n\n int64_t nTook2 = GetTimeMillis();\n\n \/\/ actually update labels\n int nDisplayUnit = SequenceUnits::SEQ;\n if (ex_model && ex_model->getOptionsModel())\n nDisplayUnit = ex_model->getOptionsModel()->getDisplayUnit();\n\n ui->L_Coin->setText(SequenceUnits::name(nDisplayUnit) + \" \" + tr(\"SubTotal\"));\n\n QTableWidget *TableW = ui->StakeReportTable;\n\n TableW->horizontalHeaderItem(1)->setText(SequenceUnits::name(nDisplayUnit) + \" \" +tr(\"Amount\"));\n\n int i=30;\n\n TableW->setSortingEnabled(false);\n for(int y=0; y<i; y++)\n {\n TableW->item(y,0)->setText(HalfDate(aRange[y].Start));\n TableW->item(y,1)->setText(Coin_0Pad(nDisplayUnit, aRange[y].Total));\n TableW->item(y,2)->setText(QString::number(aRange[y].Count));\n }\n TableW->setSortingEnabled(true);\n\n ui->Amount_24H->setText(Coin_0Pad(nDisplayUnit, aRange[i].Total) + tr(\" DYN\"));\n ui->Stake_24H->setText(QString::number(aRange[i++].Count));\n ui->Amount_7D->setText(Coin_0Pad(nDisplayUnit, aRange[i].Total) + tr(\" DYN\"));\n ui->Stake_7D->setText(QString::number(aRange[i++].Count));\n ui->Amount_30D->setText(Coin_0Pad(nDisplayUnit, aRange[i].Total) + tr(\" DYN\"));\n ui->Stake_30D->setText(QString::number(aRange[i++].Count));\n ui->Amount_365D->setText(Coin_0Pad(nDisplayUnit, aRange[i].Total) + tr(\" DYN\"));\n ui->Stake_365D->setText(QString::number(aRange[i++].Count));\n\n ui->Amount_Last->setText(tr(\"Amount: \") + Coin_0Pad(nDisplayUnit, aRange[i].Total) + tr(\" DYN\"));\n ui->L_LastStakeTime->setText(tr(\"Latest stake date: \") + HalfDate(aRange[i].Start, \"hh:mm\"));\n\n ui->Stake_Counted->setText(tr(\"Stakes analysed: \") + QString::number(nItemCounted));\n if (nItemCounted)\n ui->TimeTook->setText(tr(\"Last Recalc took \") + QString::number(nTook) + \"ms\");\n\n ui->TimeTook_2->setText(tr(\"Refresh took \") + QString::number(GetTimeMillis() -nTook2) + \"ms\");\n\n string sRefreshType = disablereportupdate ? \"Manual refresh\" : \"Auto refresh\";\n\n string strCurr_block_info = strprintf(\"%s - %s : %6d @ %s\\nhash %s\\n\",\n sRefreshType.c_str(), \"Current Block\", chainActive.Height(),\n HalfDate((chainActive.Tip()->GetMedianTimePast()+1), \"hh:mm:ss\").toStdString().c_str(),\n chainActive.Tip()->GetBlockHash().ToString());\n\n ui->L_CurrentBlock->setText(strCurr_block_info.c_str() );\n\n}\n\nQString GridGetLabelTextAt(QGridLayout * Grid, int row, int column, QString Empty = \"\")\n{\n if (Grid && Grid->itemAtPosition(row, column) &&\n Grid->itemAtPosition(row, column)->widget())\n return ((QLabel *) Grid->itemAtPosition(row, column)->widget())->text();\n else\n return Empty;\n}\n\nvoid StakeReportDialog::CopyAllToClipboard()\n{\n QString Repo;\n\n Repo += \" Sequence Stake Mini Report\\n\";\n Repo += \" ----------------------\\n\";\n\n QString RowForm = \"%1 %2 %3\\n\";\n\n for(int y=0; y<ui->gridLayout->rowCount(); y++)\n {\n if (y == 5)\n Repo += \"\\n\"; \/\/ separator line\n else\n Repo += RowForm\n .arg(GridGetLabelTextAt(ui->gridLayout, y,0), -16)\n .arg(GridGetLabelTextAt(ui->gridLayout, y,1), 16)\n .arg(GridGetLabelTextAt(ui->gridLayout, y,2), 7);\n }\n\n Repo += \"\\n\";\n\n QTableWidget *TableW = ui->StakeReportTable;\n RowForm = \"%1, %2, %3\\n\";\n\n Repo += RowForm\n .arg(TableW->horizontalHeaderItem(0)->text(), -10)\n .arg(TableW->horizontalHeaderItem(1)->text(), 16)\n .arg(TableW->horizontalHeaderItem(2)->text(), 7);\n\n for(int y=0; y<30; y++)\n {\n Repo += RowForm\n .arg(TableW->item(y,0)->text(), -10)\n .arg(TableW->item(y,1)->text(), 16)\n .arg(TableW->item(y,2)->text(), 7);\n }\n\n Repo += \"\\n\" + ui->L_CurrentBlock->text() + \"\\n\";\n\n QApplication::clipboard()->setText(Repo);\n\n}<commit_msg>Amend<commit_after>\/\/*****************************************************\n\/\/\n\/\/ Dialog which report the earning made with stake over time\n\/\/ Original coding by Remy5\n\/\/\n\n#include \"stakereportdialog.h\"\n#include \"ui_rpcconsole.h\"\n\n#include \"guiconstants.h\"\n#include \"walletmodel.h\"\n#include \"sequenceunits.h\"\n#include \"rpc\/rpcserver.h\"\n#include \"optionsmodel.h\"\n#include \"main.h\"\n#include \"chain.h\"\n#include \"util.h\"\n\n#include \"wallet\/wallet.h\"\n#include \"wallet\/walletdb.h\"\n\n#include <QWidget>\n#include <QDateTime>\n#include <QTimer>\n#include <QClipboard>\n\n\/\/ using namespace json_spirit;\nusing namespace boost;\nusing namespace std;\n\nstruct StakePeriodRange_T {\n int64_t Start;\n int64_t End;\n int64_t Total;\n int Count;\n string Name;\n};\n\ntypedef vector<StakePeriodRange_T> vStakePeriodRange_T;\n\nextern vStakePeriodRange_T PrepareRangeForStakeReport();\nextern int GetStakeSubTotal(vStakePeriodRange_T& aRange, const isminefilter filter);\n\nStakeReportDialog::StakeReportDialog(QWidget *parent) :\n QDialog(parent),\n ui(new Ui::StakeReportDialog)\n{\n ui->setupUi(this);\n\n QTableWidget *TableW = ui->StakeReportTable;\n\n alreadyConnected = false;\n\n \/\/ fill the table with clone of row 0\n for(int y=TableW->rowCount(); --y >= 1;)\n for(int x=TableW->columnCount(); --x >= 0;)\n TableW->setItem(y, x,\n TableW->item(0, x)->clone());\n\n TableW->horizontalHeader()->resizeSection(1,160);\n\n QApplication::processEvents();\n\n updateStakeReportNow(); \/\/ 1st update\n}\n\nStakeReportDialog::~StakeReportDialog()\n{\n delete ui;\n}\n\nvoid StakeReportDialog::setModel(WalletModel *model)\n{\n this->ex_model = model;\n\n if(ex_model && ex_model->getOptionsModel() && !alreadyConnected)\n {\n alreadyConnected = true;\n\n connect(ex_model->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit(int)));\n connect(ui->button_Refresh, SIGNAL(clicked()), this, SLOT(updateStakeReportNow()));\n connect(ui->CopytoClipboard, SIGNAL(clicked()), this, SLOT(CopyAllToClipboard()));\n\n disablereportupdate = GetBoolArg(\"-disablereportupdate\", false);\n\n if (!disablereportupdate)\n {\n QTimer *timer = new QTimer(this);\n connect(timer, SIGNAL(timeout()), this, SLOT(updateStakeReportTimer()));\n \tconnect(ex_model, SIGNAL(balanceChanged(qint64, qint64, qint64, qint64)), this, SLOT(updateStakeReportbalanceChanged(qint64, qint64, qint64, qint64)));\n\n timer->start(MODEL_UPDATE_DELAY*5);\n }\n }\n}\n\nvoid StakeReportDialog::updateStakeReportbalanceChanged(qint64, qint64, qint64, qint64)\n{\n StakeReportDialog::updateStakeReportNow();\n}\n\nvoid StakeReportDialog::updateDisplayUnit(int)\n{\n StakeReportDialog::updateStakeReportNow();\n}\n\nvoid StakeReportDialog::updateStakeReportTimer()\n{\n static int lastBest = 0 ;\n if (lastBest != chainActive.Height())\n {\n lastBest = chainActive.Height();\n StakeReportDialog::updateStakeReport(false);\n }\n}\n\nvoid StakeReportDialog::showEvent( QShowEvent* event )\n{\n QWidget::showEvent( event );\n StakeReportDialog::updateStakeReportNow();\n}\n\n\/\/ Extendable localtime format\nQString HalfDate(int64_t nTime, QString TimeMode=\"\")\n{\n QDateTime OrigDate = QDateTime::fromTime_t((qint32)nTime);\n QString LocalDate = OrigDate.date().toString(\"yyyy-MM-dd\");\n if (TimeMode != \"\")\n LocalDate += \" \" + OrigDate.toString(TimeMode);\n\n return LocalDate;\n}\n\n\/\/ format Sequencevalue with all trailing zero\nQString Coin_0Pad(int nUnit, int64_t amount)\n{\n QString result = SequenceUnits::format(nUnit, amount);\n\n int poin = result.indexOf(\".\") + 1;\n poin += SequenceUnits::decimals(nUnit);\n\n return result.leftJustified(poin, '0');\n}\n\nvoid StakeReportDialog::updateStakeReportNow()\n{\n updateStakeReport(true);\n}\n\nvoid StakeReportDialog::updateStakeReport(bool fImmediate=false)\n{\n static vStakePeriodRange_T aRange;\n int nItemCounted=0;\n\n if (fImmediate) nLastReportUpdate = 0;\n\n if (this->isHidden())\n return;\n\n int64_t nTook = GetTimeMillis();\n\n \/\/ Skip report recalc if not immediate or before 5 minutes from last\n if (GetTime() - nLastReportUpdate > 300)\n {\n QApplication::processEvents();\n\n ui->TimeTook->setText(tr(\"Please wait...\"));\n ui->TimeTook->repaint();\n QApplication::processEvents();\n\n aRange = PrepareRangeForStakeReport();\n\n \/\/ get subtotal calc\n nItemCounted = GetStakeSubTotal(aRange, ISMINE_SPENDABLE);\n\n nLastReportUpdate = GetTime();\n\n nTook = GetTimeMillis() - nTook;\n\n }\n\n int64_t nTook2 = GetTimeMillis();\n\n \/\/ actually update labels\n int nDisplayUnit = SequenceUnits::SEQ;\n if (ex_model && ex_model->getOptionsModel())\n nDisplayUnit = ex_model->getOptionsModel()->getDisplayUnit();\n\n ui->L_Coin->setText(SequenceUnits::name(nDisplayUnit) + \" \" + tr(\"SubTotal\"));\n\n QTableWidget *TableW = ui->StakeReportTable;\n\n TableW->horizontalHeaderItem(1)->setText(SequenceUnits::name(nDisplayUnit) + \" \" +tr(\"Amount\"));\n\n int i=30;\n\n TableW->setSortingEnabled(false);\n for(int y=0; y<i; y++)\n {\n TableW->item(y,0)->setText(HalfDate(aRange[y].Start));\n TableW->item(y,1)->setText(Coin_0Pad(nDisplayUnit, aRange[y].Total));\n TableW->item(y,2)->setText(QString::number(aRange[y].Count));\n }\n TableW->setSortingEnabled(true);\n\n ui->Amount_24H->setText(Coin_0Pad(nDisplayUnit, aRange[i].Total) + tr(\" SEQ\"));\n ui->Stake_24H->setText(QString::number(aRange[i++].Count));\n ui->Amount_7D->setText(Coin_0Pad(nDisplayUnit, aRange[i].Total) + tr(\" SEQ\"));\n ui->Stake_7D->setText(QString::number(aRange[i++].Count));\n ui->Amount_30D->setText(Coin_0Pad(nDisplayUnit, aRange[i].Total) + tr(\" SEQ\"));\n ui->Stake_30D->setText(QString::number(aRange[i++].Count));\n ui->Amount_365D->setText(Coin_0Pad(nDisplayUnit, aRange[i].Total) + tr(\" SEQ\"));\n ui->Stake_365D->setText(QString::number(aRange[i++].Count));\n\n ui->Amount_Last->setText(tr(\"Amount: \") + Coin_0Pad(nDisplayUnit, aRange[i].Total) + tr(\" SEQ\"));\n ui->L_LastStakeTime->setText(tr(\"Latest stake date: \") + HalfDate(aRange[i].Start, \"hh:mm\"));\n\n ui->Stake_Counted->setText(tr(\"Stakes analysed: \") + QString::number(nItemCounted));\n if (nItemCounted)\n ui->TimeTook->setText(tr(\"Last Recalc took \") + QString::number(nTook) + \"ms\");\n\n ui->TimeTook_2->setText(tr(\"Refresh took \") + QString::number(GetTimeMillis() -nTook2) + \"ms\");\n\n string sRefreshType = disablereportupdate ? \"Manual refresh\" : \"Auto refresh\";\n\n string strCurr_block_info = strprintf(\"%s - %s : %6d @ %s\\nhash %s\\n\",\n sRefreshType.c_str(), \"Current Block\", chainActive.Height(),\n HalfDate((chainActive.Tip()->GetMedianTimePast()+1), \"hh:mm:ss\").toStdString().c_str(),\n chainActive.Tip()->GetBlockHash().ToString());\n\n ui->L_CurrentBlock->setText(strCurr_block_info.c_str() );\n\n}\n\nQString GridGetLabelTextAt(QGridLayout * Grid, int row, int column, QString Empty = \"\")\n{\n if (Grid && Grid->itemAtPosition(row, column) &&\n Grid->itemAtPosition(row, column)->widget())\n return ((QLabel *) Grid->itemAtPosition(row, column)->widget())->text();\n else\n return Empty;\n}\n\nvoid StakeReportDialog::CopyAllToClipboard()\n{\n QString Repo;\n\n Repo += \" Sequence Stake Mini Report\\n\";\n Repo += \" ----------------------\\n\";\n\n QString RowForm = \"%1 %2 %3\\n\";\n\n for(int y=0; y<ui->gridLayout->rowCount(); y++)\n {\n if (y == 5)\n Repo += \"\\n\"; \/\/ separator line\n else\n Repo += RowForm\n .arg(GridGetLabelTextAt(ui->gridLayout, y,0), -16)\n .arg(GridGetLabelTextAt(ui->gridLayout, y,1), 16)\n .arg(GridGetLabelTextAt(ui->gridLayout, y,2), 7);\n }\n\n Repo += \"\\n\";\n\n QTableWidget *TableW = ui->StakeReportTable;\n RowForm = \"%1, %2, %3\\n\";\n\n Repo += RowForm\n .arg(TableW->horizontalHeaderItem(0)->text(), -10)\n .arg(TableW->horizontalHeaderItem(1)->text(), 16)\n .arg(TableW->horizontalHeaderItem(2)->text(), 7);\n\n for(int y=0; y<30; y++)\n {\n Repo += RowForm\n .arg(TableW->item(y,0)->text(), -10)\n .arg(TableW->item(y,1)->text(), 16)\n .arg(TableW->item(y,2)->text(), 7);\n }\n\n Repo += \"\\n\" + ui->L_CurrentBlock->text() + \"\\n\";\n\n QApplication::clipboard()->setText(Repo);\n\n}<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2011-2015 The Bitcoin Core developers\n\/\/ Copyright (c) 2015-2017 The Bitcoin Unlimited developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \"transactionrecord.h\"\n\n#include \"consensus\/consensus.h\"\n#include \"dstencode.h\"\n#include \"main.h\"\n#include \"timedata.h\"\n\n#include <stdint.h>\n\n#include <boost\/foreach.hpp>\n\n\/* Return positive answer if transaction should be shown in list.\n *\/\nbool TransactionRecord::showTransaction(const CWalletTx &wtx)\n{\n if (wtx.IsCoinBase())\n {\n \/\/ Ensures we show generated coins \/ mined transactions at depth 1\n if (!wtx.IsInMainChain())\n {\n return false;\n }\n }\n return true;\n}\n\n\/*\n * Decompose CWallet transaction to model transaction records.\n *\/\nQList<TransactionRecord> TransactionRecord::decomposeTransaction(const CWallet *wallet, const CWalletTx &wtx)\n{\n QList<TransactionRecord> parts;\n int64_t nTime = wtx.GetTxTime();\n CAmount nCredit = wtx.GetCredit(ISMINE_ALL);\n CAmount nDebit = wtx.GetDebit(ISMINE_ALL);\n CAmount nNet = nCredit - nDebit;\n uint256 hash = wtx.GetHash();\n std::map<std::string, std::string> mapValue = wtx.mapValue;\n\n if (nNet > 0 || wtx.IsCoinBase())\n {\n \/\/\n \/\/ Credit\n \/\/\n std::string labelPublic = \"\";\n BOOST_FOREACH (const CTxOut &txout, wtx.vout)\n {\n isminetype mine = wallet->IsMine(txout);\n if (mine)\n {\n TransactionRecord sub(hash, nTime);\n CTxDestination address;\n sub.idx = parts.size(); \/\/ sequence number\n sub.credit = txout.nValue;\n sub.involvesWatchAddress = mine & ISMINE_WATCH_ONLY;\n\n \/\/ the public label refers to the following utxo\n if (labelPublic == \"\")\n {\n labelPublic = getLabelPublic(txout.scriptPubKey);\n if (labelPublic != \"\")\n continue;\n }\n\n if (wtx.IsCoinBase())\n {\n \/\/ Generated\n sub.type = TransactionRecord::Generated;\n }\n else if (ExtractDestination(txout.scriptPubKey, address) && wallet->IsMine(address))\n {\n \/\/ Received by Bitcoin Address\n sub.type = TransactionRecord::RecvWithAddress;\n if (labelPublic == \"\")\n sub.addresses.push_back(std::make_pair(EncodeDestination(address), txout.scriptPubKey));\n else\n sub.addresses.push_back(\n std::make_pair(\"<\" + labelPublic + \"> \" + EncodeDestination(address), txout.scriptPubKey));\n }\n else\n {\n \/\/ Received by IP connection (deprecated features), or a multisignature or other non-simple\n \/\/ transaction\n sub.type = TransactionRecord::RecvFromOther;\n sub.addresses.push_back(std::make_pair(mapValue[\"from\"], txout.scriptPubKey));\n }\n\n parts.append(sub);\n }\n\n labelPublic = \"\";\n }\n }\n else\n {\n bool involvesWatchAddress = false;\n isminetype fAllToMe = ISMINE_SPENDABLE;\n BOOST_FOREACH (const CTxOut &txout, wtx.vout)\n {\n isminetype mine = wallet->IsMine(txout);\n if (mine & ISMINE_WATCH_ONLY)\n involvesWatchAddress = true;\n if (fAllToMe > mine)\n fAllToMe = mine;\n }\n\n \/\/ load all tx addresses for user display\/filter\n AddressList listAllAddresses;\n CTxDestination address;\n BOOST_FOREACH (const CTxOut &txout, wtx.vout)\n {\n if (!fAllToMe && wallet->IsMine(txout))\n {\n continue; \/\/ skip change if some tx went to somewhere else\n }\n \/\/ get public label if it exists\n std::string labelPublic = getLabelPublic(txout.scriptPubKey);\n if (labelPublic != \"\")\n \/\/ use public label before address\n listAllAddresses.push_back(std::make_pair(\"<\" + labelPublic + \">\", txout.scriptPubKey));\n else if (ExtractDestination(txout.scriptPubKey, address))\n \/\/ a standard address\n listAllAddresses.push_back(std::make_pair(EncodeDestination(address), txout.scriptPubKey));\n\n else\n \/\/ add the unknown scriptPubKey as n\/a - TODO could also skip these if there is no need to\n \/\/ display\/filter??\n listAllAddresses.push_back(std::make_pair(\"n\/a\", txout.scriptPubKey));\n }\n\n isminetype fAllFromMe = ISMINE_SPENDABLE;\n BOOST_FOREACH (const CTxIn &txin, wtx.vin)\n {\n isminetype mine = wallet->IsMine(txin);\n if (mine & ISMINE_WATCH_ONLY)\n involvesWatchAddress = true;\n if (fAllFromMe > mine)\n fAllFromMe = mine;\n }\n\n if (fAllFromMe && fAllToMe)\n {\n \/\/ Payment to self\n CAmount nChange = wtx.GetChange();\n parts.append(TransactionRecord(\n hash, nTime, TransactionRecord::SendToSelf, listAllAddresses, -(nDebit - nChange), nCredit - nChange));\n\n \/\/ maybe pass to TransactionRecord as constructor argument\n parts.last().involvesWatchAddress = involvesWatchAddress;\n }\n else if (fAllFromMe)\n {\n \/\/\n \/\/ Debit\n \/\/\n CAmount nTxFee = nDebit - wtx.GetValueOut();\n\n for (unsigned int nOut = 0; nOut < wtx.vout.size(); nOut++)\n {\n const CTxOut &txout = wtx.vout[nOut];\n\n if (wallet->IsMine(txout))\n {\n \/\/ Ignore parts sent to self, as this is usually the change\n \/\/ from a transaction sent back to our own address.\n continue;\n }\n\n TransactionRecord sub(hash, nTime);\n sub.idx = parts.size();\n sub.involvesWatchAddress = involvesWatchAddress;\n\n CTxDestination address;\n std::string labelPublic = getLabelPublic(txout.scriptPubKey);\n if (labelPublic != \"\")\n continue;\n else if (ExtractDestination(txout.scriptPubKey, address))\n {\n \/\/ Sent to Bitcoin Address\n sub.type = TransactionRecord::SendToAddress;\n \/\/ sub.addresses.push_back(std::make_pair(EncodeDestination(address), txout.scriptPubKey));\n }\n else\n {\n \/\/ Sent to IP, or other non-address transaction like OP_EVAL\n sub.type = TransactionRecord::SendToOther;\n \/\/ sub.addresses.push_back(std::make_pair(mapValue[\"to\"], txout.scriptPubKey));\n }\n\n sub.addresses = listAllAddresses;\n\n CAmount nValue = txout.nValue;\n \/* Add fee to first output *\/\n if (nTxFee > 0)\n {\n nValue += nTxFee;\n nTxFee = 0;\n }\n sub.debit = -nValue;\n\n parts.append(sub);\n }\n }\n else\n {\n \/\/\n \/\/ Mixed debit transaction, can't break down payees\n \/\/\n parts.append(TransactionRecord(hash, nTime, TransactionRecord::Other, listAllAddresses, nNet, 0));\n parts.last().involvesWatchAddress = involvesWatchAddress;\n }\n }\n\n return parts;\n}\n\nvoid TransactionRecord::updateStatus(const CWalletTx &wtx)\n{\n AssertLockHeld(cs_main);\n \/\/ Determine transaction status\n\n \/\/ Find the block the tx is in\n CBlockIndex *pindex = NULL;\n BlockMap::iterator mi = mapBlockIndex.find(wtx.hashBlock);\n if (mi != mapBlockIndex.end())\n pindex = (*mi).second;\n\n \/\/ Sort order, unrecorded transactions sort to the top\n status.sortKey = strprintf(\"%010d-%01d-%010u-%03d\", (pindex ? pindex->nHeight : std::numeric_limits<int>::max()),\n (wtx.IsCoinBase() ? 1 : 0), wtx.nTimeReceived, idx);\n status.countsForBalance = wtx.IsTrusted() && !(wtx.GetBlocksToMaturity() > 0);\n status.depth = wtx.GetDepthInMainChain();\n status.cur_num_blocks = chainActive.Height();\n\n if (!CheckFinalTx(wtx))\n {\n if (wtx.nLockTime < LOCKTIME_THRESHOLD)\n {\n status.status = TransactionStatus::OpenUntilBlock;\n status.open_for = wtx.nLockTime - chainActive.Height();\n }\n else\n {\n status.status = TransactionStatus::OpenUntilDate;\n status.open_for = wtx.nLockTime;\n }\n }\n \/\/ For generated transactions, determine maturity\n else if (type == TransactionRecord::Generated)\n {\n if (wtx.GetBlocksToMaturity() > 0)\n {\n status.status = TransactionStatus::Immature;\n\n if (wtx.IsInMainChain())\n {\n status.matures_in = wtx.GetBlocksToMaturity();\n\n \/\/ Check if the block was requested by anyone\n if (GetAdjustedTime() - wtx.nTimeReceived > 2 * 60 && wtx.GetRequestCount() == 0)\n status.status = TransactionStatus::MaturesWarning;\n }\n else\n {\n status.status = TransactionStatus::NotAccepted;\n }\n }\n else\n {\n status.status = TransactionStatus::Confirmed;\n }\n }\n else\n {\n if (status.depth < 0)\n {\n status.status = TransactionStatus::Conflicted;\n }\n else if (GetAdjustedTime() - wtx.nTimeReceived > 2 * 60 && wtx.GetRequestCount() == 0)\n {\n status.status = TransactionStatus::Offline;\n }\n else if (status.depth == 0)\n {\n status.status = TransactionStatus::Unconfirmed;\n }\n else if (status.depth < RecommendedNumConfirmations)\n {\n status.status = TransactionStatus::Confirming;\n }\n else\n {\n status.status = TransactionStatus::Confirmed;\n }\n }\n}\n\nbool TransactionRecord::statusUpdateNeeded()\n{\n AssertLockHeld(cs_main);\n return status.cur_num_blocks != chainActive.Height();\n}\n\nQString TransactionRecord::getTxID() const\n{\n return QString::fromStdString(hash.ToString());\n}\n\nint TransactionRecord::getOutputIndex() const\n{\n return idx;\n}\n<commit_msg>fix formatting<commit_after>\/\/ Copyright (c) 2011-2015 The Bitcoin Core developers\n\/\/ Copyright (c) 2015-2017 The Bitcoin Unlimited developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \"transactionrecord.h\"\n\n#include \"consensus\/consensus.h\"\n#include \"dstencode.h\"\n#include \"main.h\"\n#include \"timedata.h\"\n\n#include <stdint.h>\n\n#include <boost\/foreach.hpp>\n\n\/* Return positive answer if transaction should be shown in list.\n *\/\nbool TransactionRecord::showTransaction(const CWalletTx &wtx)\n{\n if (wtx.IsCoinBase())\n {\n \/\/ Ensures we show generated coins \/ mined transactions at depth 1\n if (!wtx.IsInMainChain())\n {\n return false;\n }\n }\n return true;\n}\n\n\/*\n * Decompose CWallet transaction to model transaction records.\n *\/\nQList<TransactionRecord> TransactionRecord::decomposeTransaction(const CWallet *wallet, const CWalletTx &wtx)\n{\n QList<TransactionRecord> parts;\n int64_t nTime = wtx.GetTxTime();\n CAmount nCredit = wtx.GetCredit(ISMINE_ALL);\n CAmount nDebit = wtx.GetDebit(ISMINE_ALL);\n CAmount nNet = nCredit - nDebit;\n uint256 hash = wtx.GetHash();\n std::map<std::string, std::string> mapValue = wtx.mapValue;\n\n if (nNet > 0 || wtx.IsCoinBase())\n {\n \/\/\n \/\/ Credit\n \/\/\n std::string labelPublic = \"\";\n BOOST_FOREACH (const CTxOut &txout, wtx.vout)\n {\n isminetype mine = wallet->IsMine(txout);\n if (mine)\n {\n TransactionRecord sub(hash, nTime);\n CTxDestination address;\n sub.idx = parts.size(); \/\/ sequence number\n sub.credit = txout.nValue;\n sub.involvesWatchAddress = mine & ISMINE_WATCH_ONLY;\n\n \/\/ the public label refers to the following utxo\n if (labelPublic == \"\")\n {\n labelPublic = getLabelPublic(txout.scriptPubKey);\n if (labelPublic != \"\")\n continue;\n }\n\n if (wtx.IsCoinBase())\n {\n \/\/ Generated\n sub.type = TransactionRecord::Generated;\n }\n else if (ExtractDestination(txout.scriptPubKey, address) && wallet->IsMine(address))\n {\n \/\/ Received by Bitcoin Address\n sub.type = TransactionRecord::RecvWithAddress;\n if (labelPublic == \"\")\n sub.addresses.push_back(std::make_pair(EncodeDestination(address), txout.scriptPubKey));\n else\n sub.addresses.push_back(\n std::make_pair(\"<\" + labelPublic + \"> \" + EncodeDestination(address), txout.scriptPubKey));\n }\n else\n {\n \/\/ Received by IP connection (deprecated features), or a multisignature or other non-simple\n \/\/ transaction\n sub.type = TransactionRecord::RecvFromOther;\n sub.addresses.push_back(std::make_pair(mapValue[\"from\"], txout.scriptPubKey));\n }\n\n parts.append(sub);\n }\n\n labelPublic = \"\";\n }\n }\n else\n {\n bool involvesWatchAddress = false;\n isminetype fAllToMe = ISMINE_SPENDABLE;\n BOOST_FOREACH (const CTxOut &txout, wtx.vout)\n {\n isminetype mine = wallet->IsMine(txout);\n if (mine & ISMINE_WATCH_ONLY)\n involvesWatchAddress = true;\n if (fAllToMe > mine)\n fAllToMe = mine;\n }\n\n \/\/ load all tx addresses for user display\/filter\n AddressList listAllAddresses;\n CTxDestination address;\n BOOST_FOREACH (const CTxOut &txout, wtx.vout)\n {\n if (!fAllToMe && wallet->IsMine(txout))\n {\n continue; \/\/ skip change if some tx went to somewhere else\n }\n \/\/ get public label if it exists\n std::string labelPublic = getLabelPublic(txout.scriptPubKey);\n if (labelPublic != \"\")\n \/\/ use public label before address\n listAllAddresses.push_back(std::make_pair(\"<\" + labelPublic + \">\", txout.scriptPubKey));\n else if (ExtractDestination(txout.scriptPubKey, address))\n \/\/ a standard address\n listAllAddresses.push_back(std::make_pair(EncodeDestination(address), txout.scriptPubKey));\n\n else\n \/\/ add the unknown scriptPubKey as n\/a - TODO could also skip these if there is no need to\n \/\/ display\/filter??\n listAllAddresses.push_back(std::make_pair(\"n\/a\", txout.scriptPubKey));\n }\n\n isminetype fAllFromMe = ISMINE_SPENDABLE;\n BOOST_FOREACH (const CTxIn &txin, wtx.vin)\n {\n isminetype mine = wallet->IsMine(txin);\n if (mine & ISMINE_WATCH_ONLY)\n involvesWatchAddress = true;\n if (fAllFromMe > mine)\n fAllFromMe = mine;\n }\n\n if (fAllFromMe && fAllToMe)\n {\n \/\/ Payment to self\n CAmount nChange = wtx.GetChange();\n parts.append(TransactionRecord(\n hash, nTime, TransactionRecord::SendToSelf, listAllAddresses, -(nDebit - nChange), nCredit - nChange));\n\n \/\/ maybe pass to TransactionRecord as constructor argument\n parts.last().involvesWatchAddress = involvesWatchAddress;\n }\n else if (fAllFromMe)\n {\n \/\/\n \/\/ Debit\n \/\/\n CAmount nTxFee = nDebit - wtx.GetValueOut();\n\n for (unsigned int nOut = 0; nOut < wtx.vout.size(); nOut++)\n {\n const CTxOut &txout = wtx.vout[nOut];\n\n if (wallet->IsMine(txout))\n {\n \/\/ Ignore parts sent to self, as this is usually the change\n \/\/ from a transaction sent back to our own address.\n continue;\n }\n\n TransactionRecord sub(hash, nTime);\n sub.idx = parts.size();\n sub.involvesWatchAddress = involvesWatchAddress;\n\n CTxDestination address;\n std::string labelPublic = getLabelPublic(txout.scriptPubKey);\n if (labelPublic != \"\")\n continue;\n else if (ExtractDestination(txout.scriptPubKey, address))\n {\n \/\/ Sent to Bitcoin Address\n sub.type = TransactionRecord::SendToAddress;\n \/\/ sub.addresses.push_back(std::make_pair(EncodeDestination(address), txout.scriptPubKey));\n }\n else\n {\n \/\/ Sent to IP, or other non-address transaction like OP_EVAL\n sub.type = TransactionRecord::SendToOther;\n \/\/ sub.addresses.push_back(std::make_pair(mapValue[\"to\"], txout.scriptPubKey));\n }\n\n sub.addresses = listAllAddresses;\n\n CAmount nValue = txout.nValue;\n \/* Add fee to first output *\/\n if (nTxFee > 0)\n {\n nValue += nTxFee;\n nTxFee = 0;\n }\n sub.debit = -nValue;\n\n parts.append(sub);\n }\n }\n else\n {\n \/\/\n \/\/ Mixed debit transaction, can't break down payees\n \/\/\n parts.append(TransactionRecord(hash, nTime, TransactionRecord::Other, listAllAddresses, nNet, 0));\n parts.last().involvesWatchAddress = involvesWatchAddress;\n }\n }\n\n return parts;\n}\n\nvoid TransactionRecord::updateStatus(const CWalletTx &wtx)\n{\n AssertLockHeld(cs_main);\n \/\/ Determine transaction status\n\n \/\/ Find the block the tx is in\n CBlockIndex *pindex = NULL;\n BlockMap::iterator mi = mapBlockIndex.find(wtx.hashBlock);\n if (mi != mapBlockIndex.end())\n pindex = (*mi).second;\n\n \/\/ Sort order, unrecorded transactions sort to the top\n status.sortKey = strprintf(\"%010d-%01d-%010u-%03d\", (pindex ? pindex->nHeight : std::numeric_limits<int>::max()),\n (wtx.IsCoinBase() ? 1 : 0), wtx.nTimeReceived, idx);\n status.countsForBalance = wtx.IsTrusted() && !(wtx.GetBlocksToMaturity() > 0);\n status.depth = wtx.GetDepthInMainChain();\n status.cur_num_blocks = chainActive.Height();\n\n if (!CheckFinalTx(wtx))\n {\n if (wtx.nLockTime < LOCKTIME_THRESHOLD)\n {\n status.status = TransactionStatus::OpenUntilBlock;\n status.open_for = wtx.nLockTime - chainActive.Height();\n }\n else\n {\n status.status = TransactionStatus::OpenUntilDate;\n status.open_for = wtx.nLockTime;\n }\n }\n \/\/ For generated transactions, determine maturity\n else if (type == TransactionRecord::Generated)\n {\n if (wtx.GetBlocksToMaturity() > 0)\n {\n status.status = TransactionStatus::Immature;\n\n if (wtx.IsInMainChain())\n {\n status.matures_in = wtx.GetBlocksToMaturity();\n\n \/\/ Check if the block was requested by anyone\n if (GetAdjustedTime() - wtx.nTimeReceived > 2 * 60 && wtx.GetRequestCount() == 0)\n status.status = TransactionStatus::MaturesWarning;\n }\n else\n {\n status.status = TransactionStatus::NotAccepted;\n }\n }\n else\n {\n status.status = TransactionStatus::Confirmed;\n }\n }\n else\n {\n if (status.depth < 0)\n {\n status.status = TransactionStatus::Conflicted;\n }\n else if (GetAdjustedTime() - wtx.nTimeReceived > 2 * 60 && wtx.GetRequestCount() == 0)\n {\n status.status = TransactionStatus::Offline;\n }\n else if (status.depth == 0)\n {\n status.status = TransactionStatus::Unconfirmed;\n }\n else if (status.depth < RecommendedNumConfirmations)\n {\n status.status = TransactionStatus::Confirming;\n }\n else\n {\n status.status = TransactionStatus::Confirmed;\n }\n }\n}\n\nbool TransactionRecord::statusUpdateNeeded()\n{\n AssertLockHeld(cs_main);\n return status.cur_num_blocks != chainActive.Height();\n}\n\nQString TransactionRecord::getTxID() const { return QString::fromStdString(hash.ToString()); }\nint TransactionRecord::getOutputIndex() const { return idx; }\n<|endoftext|>"} {"text":"<commit_before>\/*ckwg +5\n * Copyright 2012 by Kitware, Inc. All Rights Reserved. Please refer to\n * KITWARE_LICENSE.TXT for licensing information, or contact General Counsel,\n * Kitware, Inc., 28 Corporate Drive, Clifton Park, NY 12065.\n *\/\n\n#include \"read_video_gravl_process.h\"\n\n#include <processes\/helpers\/image\/format.h>\n#include <processes\/helpers\/image\/read.h>\n\n#include <vistk\/pipeline\/config.h>\n#include <vistk\/pipeline\/datum.h>\n#include <vistk\/pipeline\/process_exception.h>\n\n#include <gravl\/core\/api\/data_block.h>\n#include <gravl\/core\/api\/frame_ptr.h>\n#include <gravl\/core\/api\/image.h>\n#include <gravl\/core\/api\/image_data.h>\n#include <gravl\/core\/api\/resource_ptr.h>\n\n#include <gravl\/raf\/raf.h>\n\n#include <vil\/vil_image_view.h>\n\n#include <string>\n\n\/**\n * \\file read_video_gravl_process.cxx\n *\n * \\brief Implementation of the read video gravl process.\n *\/\n\nstatic size_t compute_block_size(gravl::image::dimension dim,\n gravl::image::stride s);\ntemplate <typename T> static T* compute_block_start(\n T* top_left, gravl::image::dimension dim, gravl::image::stride s);\ntemplate <typename T> static T* compute_top_left(\n T* top_left, gravl::image::dimension dim, gravl::image::stride s);\n\nnamespace vistk\n{\n\nclass read_video_gravl_process::priv\n{\n public:\n priv(std::string const& input_uri);\n ~priv();\n\n std::string const uri;\n\n gravl::resource_ptr resource;\n gravl::data_block* video;\n\n static config::key_t const config_pixtype;\n static config::key_t const config_pixfmt;\n static config::key_t const config_uri;\n static config::key_t const config_verify;\n static config::value_t const default_pixtype;\n static config::value_t const default_pixfmt;\n static config::value_t const default_verify;\n static port_t const port_output;\n};\n\nconfig::key_t const read_video_gravl_process::priv::config_pixtype = config::key_t(\"pixtype\");\nconfig::key_t const read_video_gravl_process::priv::config_pixfmt = config::key_t(\"pixfmt\");\nconfig::key_t const read_video_gravl_process::priv::config_uri = config::key_t(\"input\");\nconfig::value_t const read_video_gravl_process::priv::default_pixtype = config::value_t(pixtypes::pixtype_byte());\nconfig::value_t const read_video_gravl_process::priv::default_pixfmt = config::value_t(pixfmts::pixfmt_rgb());\nprocess::port_t const read_video_gravl_process::priv::port_output = port_t(\"image\");\n\nread_video_gravl_process\n::read_video_gravl_process(config_t const& config)\n : process(config)\n{\n declare_configuration_key(\n priv::config_pixtype,\n priv::default_pixtype,\n config::description_t(\"The pixel type of the input images.\"));\n declare_configuration_key(\n priv::config_pixfmt,\n priv::default_pixfmt,\n config::description_t(\"The pixel format of the input images.\"));\n declare_configuration_key(\n priv::config_uri,\n config::value_t(),\n config::description_t(\"The URI of the resource.\"));\n\n pixtype_t const pixtype = config_value<pixtype_t>(priv::config_pixtype);\n pixfmt_t const pixfmt = config_value<pixfmt_t>(priv::config_pixfmt);\n\n port_type_t const port_type_output = port_type_for_pixtype(pixtype, pixfmt);\n\n port_flags_t required;\n\n required.insert(flag_required);\n\n declare_output_port(\n priv::port_output,\n port_type_output,\n required,\n port_description_t(\"The images that are read in.\"));\n}\n\nread_video_gravl_process\n::~read_video_gravl_process()\n{\n}\n\nvoid\nread_video_gravl_process\n::_configure()\n{\n \/\/ Configure the process.\n {\n pixtype_t const pixtype = config_value<pixtype_t>(priv::config_pixtype);\n std::string const uri = config_value<std::string>(priv::config_uri);\n\n d.reset(new priv(uri));\n }\n\n if (d->uri.empty())\n {\n static std::string const reason = \"The URI given was empty\";\n config::value_t const value = config::value_t(d->uri);\n\n throw invalid_configuration_value_exception(name(), priv::config_uri, value, reason);\n }\n\n d->resource = gravl::raf::get_resource(d->uri.c_str());\n if (!d->resource)\n {\n std::string const reason = \"Failed to open the resource: \" + d->uri;\n\n throw invalid_configuration_exception(name(), reason);\n }\n\n d->video = d->resource.get_data<gravl::data_block>();\n if (!d->video)\n {\n static std::string const reason = \"Failed to obtain data_block from resource\";\n\n throw invalid_configuration_exception(name(), reason);\n }\n\n process::_configure();\n}\n\nvoid\nread_video_gravl_process\n::_init()\n{\n d->video->rewind();\n\n process::_init();\n}\n\nvoid\nread_video_gravl_process\n::_step()\n{\n datum_t dat;\n\n if (d->video->at_end())\n {\n mark_process_as_complete();\n dat = datum::complete_datum();\n }\n else if (!d->video)\n {\n static datum::error_t const err_string = datum::error_t(\"Error with input file stream\");\n\n dat = datum::error_datum(err_string);\n }\n else\n {\n gravl::frame_ptr const frame = d->video->current_frame();\n gravl::image_data const* const image_data = frame.get_const_data<gravl::image_data>();\n gravl::image const image = (image_data ? image_data->pixels() : gravl::image());\n\n if (!image || image.format() != gravl::image::format_of<uint8_t>())\n {\n dat = datum::empty_datum();\n }\n else\n {\n gravl::image::dimension const dim = image.dimensions();\n gravl::image::stride const ps = image.strides();\n uint8_t const* const top_left = image.data<uint8_t>();\n size_t const size = compute_block_size(dim, ps);\n\n \/\/ Ugh, there is no way to create a vil_image_view from existing data\n \/\/ without arranging for said existing data to stick around, so stuck\n \/\/ having to copy the data (again) :-(\n vil_memory_chunk* const mem = new vil_memory_chunk(size, VIL_PIXEL_FORMAT_BYTE);\n uint8_t* const buffer = reinterpret_cast<uint8_t*>(mem->data());\n memcpy(buffer, compute_block_start(top_left, dim, ps), size);\n\n vil_image_view<vxl_byte> const vil(vil_memory_chunk_sptr(mem),\n compute_top_left(buffer, dim, ps),\n dim.width, dim.height, dim.planes,\n ps.width, ps.height, ps.planes);\n dat = datum::new_datum(vil);\n }\n\n d->video->advance();\n }\n\n push_datum_to_port(priv::port_output, dat);\n\n process::_step();\n}\n\nread_video_gravl_process::priv\n::priv(std::string const& input_uri)\n : uri(input_uri)\n{\n}\n\nread_video_gravl_process::priv\n::~priv()\n{\n}\n\n}\n\nsize_t\nsabs(ptrdiff_t a)\n{\n return static_cast<size_t>((a < 0 ? -a : a));\n}\n\nsize_t\ncompute_block_size(gravl::image::dimension dim, gravl::image::stride s)\n{\n return ((dim.width - 1) * sabs(s.width)) +\n ((dim.height - 1) * sabs(s.height)) +\n ((dim.planes - 1) * sabs(s.planes)) + 1;\n}\n\nptrdiff_t\ncompute_offset(gravl::image::dimension dim, gravl::image::stride s)\n{\n ptrdiff_t result = 0;\n if (s.width < 0)\n {\n result -= s.width * (dim.width - 1);\n }\n if (s.height < 0)\n {\n result -= s.height * (dim.height - 1);\n }\n if (s.planes < 0)\n {\n result -= s.planes * (dim.planes - 1);\n }\n return result;\n}\n\ntemplate <typename T>\nT*\ncompute_block_start(\n T* top_left, gravl::image::dimension dim, gravl::image::stride s)\n{\n return top_left - compute_offset(dim, s);\n}\n\ntemplate <typename T>\nT*\ncompute_top_left(\n T* top_left, gravl::image::dimension dim, gravl::image::stride s)\n{\n return top_left + compute_offset(dim, s);\n}\n<commit_msg>Fix pixel type handling in gravl reader<commit_after>\/*ckwg +5\n * Copyright 2012 by Kitware, Inc. All Rights Reserved. Please refer to\n * KITWARE_LICENSE.TXT for licensing information, or contact General Counsel,\n * Kitware, Inc., 28 Corporate Drive, Clifton Park, NY 12065.\n *\/\n\n#include \"read_video_gravl_process.h\"\n\n#include <processes\/helpers\/image\/format.h>\n#include <processes\/helpers\/image\/read.h>\n\n#include <vistk\/pipeline\/config.h>\n#include <vistk\/pipeline\/datum.h>\n#include <vistk\/pipeline\/process_exception.h>\n\n#include <gravl\/core\/api\/data_block.h>\n#include <gravl\/core\/api\/frame_ptr.h>\n#include <gravl\/core\/api\/image.h>\n#include <gravl\/core\/api\/image_data.h>\n#include <gravl\/core\/api\/resource_ptr.h>\n\n#include <gravl\/raf\/raf.h>\n\n#include <vil\/vil_image_view.h>\n\n#include <string>\n\n\/**\n * \\file read_video_gravl_process.cxx\n *\n * \\brief Implementation of the read video gravl process.\n *\/\n\ntemplate <typename PixType> static vistk::datum_t convert_image(\n gravl::data_block* video, vistk::pixtype_t const& pixtype,\n vil_pixel_format pixfmt);\n\nnamespace vistk\n{\n\nclass read_video_gravl_process::priv\n{\n public:\n priv(std::string const& input_uri);\n ~priv();\n\n std::string const uri;\n\n gravl::resource_ptr resource;\n gravl::data_block* video;\n\n static config::key_t const config_pixtype;\n static config::key_t const config_pixfmt;\n static config::key_t const config_uri;\n static config::key_t const config_verify;\n static config::value_t const default_pixtype;\n static config::value_t const default_pixfmt;\n static config::value_t const default_verify;\n static port_t const port_output;\n};\n\nconfig::key_t const read_video_gravl_process::priv::config_pixtype = config::key_t(\"pixtype\");\nconfig::key_t const read_video_gravl_process::priv::config_pixfmt = config::key_t(\"pixfmt\");\nconfig::key_t const read_video_gravl_process::priv::config_uri = config::key_t(\"input\");\nconfig::value_t const read_video_gravl_process::priv::default_pixtype = config::value_t(pixtypes::pixtype_byte());\nconfig::value_t const read_video_gravl_process::priv::default_pixfmt = config::value_t(pixfmts::pixfmt_rgb());\nprocess::port_t const read_video_gravl_process::priv::port_output = port_t(\"image\");\n\nread_video_gravl_process\n::read_video_gravl_process(config_t const& config)\n : process(config)\n{\n declare_configuration_key(\n priv::config_pixtype,\n priv::default_pixtype,\n config::description_t(\"The pixel type of the input images.\"));\n declare_configuration_key(\n priv::config_pixfmt,\n priv::default_pixfmt,\n config::description_t(\"The pixel format of the input images.\"));\n declare_configuration_key(\n priv::config_uri,\n config::value_t(),\n config::description_t(\"The URI of the resource.\"));\n\n pixtype_t const pixtype = config_value<pixtype_t>(priv::config_pixtype);\n pixfmt_t const pixfmt = config_value<pixfmt_t>(priv::config_pixfmt);\n\n port_type_t const port_type_output = port_type_for_pixtype(pixtype, pixfmt);\n\n port_flags_t required;\n\n required.insert(flag_required);\n\n declare_output_port(\n priv::port_output,\n port_type_output,\n required,\n port_description_t(\"The images that are read in.\"));\n}\n\nread_video_gravl_process\n::~read_video_gravl_process()\n{\n}\n\nvoid\nread_video_gravl_process\n::_configure()\n{\n \/\/ Configure the process.\n {\n pixtype_t const pixtype = config_value<pixtype_t>(priv::config_pixtype);\n std::string const uri = config_value<std::string>(priv::config_uri);\n\n d.reset(new priv(uri));\n }\n\n if (d->uri.empty())\n {\n static std::string const reason = \"The URI given was empty\";\n config::value_t const value = config::value_t(d->uri);\n\n throw invalid_configuration_value_exception(name(), priv::config_uri, value, reason);\n }\n\n d->resource = gravl::raf::get_resource(d->uri.c_str());\n if (!d->resource)\n {\n std::string const reason = \"Failed to open the resource: \" + d->uri;\n\n throw invalid_configuration_exception(name(), reason);\n }\n\n d->video = d->resource.get_data<gravl::data_block>();\n if (!d->video)\n {\n static std::string const reason = \"Failed to obtain data_block from resource\";\n\n throw invalid_configuration_exception(name(), reason);\n }\n\n process::_configure();\n}\n\nvoid\nread_video_gravl_process\n::_init()\n{\n d->video->rewind();\n\n process::_init();\n}\n\nvoid\nread_video_gravl_process\n::_step()\n{\n datum_t dat;\n\n if (d->video->at_end())\n {\n mark_process_as_complete();\n dat = datum::complete_datum();\n }\n else if (!d->video)\n {\n static datum::error_t const err_string = datum::error_t(\"Error with input file stream\");\n\n dat = datum::error_datum(err_string);\n }\n else\n {\n pixtype_t const pixtype = config_value<pixtype_t>(priv::config_pixtype);\n if (pixtype == pixtypes::pixtype_byte()) \/\/ uint8_t\n {\n dat = convert_image<uint8_t>(d->video, pixtype, VIL_PIXEL_FORMAT_BYTE);\n }\n\/\/ else if (pixtype == pixtypes::pixtype_short()) \/\/ uint16_t - TODO\n\/\/ {\n\/\/ dat = convert_image<uint16_t>(d->video, pixtype, VIL_PIXEL_FORMAT_INT_16);\n\/\/ }\n\/\/ else if (pixtype == pixtypes::pixtype_int()) \/\/ uint32_t - TODO\n\/\/ {\n\/\/ dat = convert_image<uint32_t>(d->video, pixtype, VIL_PIXEL_FORMAT_INT_32);\n\/\/ }\n\/\/ else if (pixtype == pixtypes::pixtype_long()) \/\/ uint64_t - TODO\n\/\/ {\n\/\/ dat = convert_image<uint64_t>(d->video, pixtype, VIL_PIXEL_FORMAT_INT_64);\n\/\/ }\n else if (pixtype == pixtypes::pixtype_float()) \/\/ float\n {\n dat = convert_image<float>(d->video, pixtype, VIL_PIXEL_FORMAT_FLOAT);\n }\n else if (pixtype == pixtypes::pixtype_double()) \/\/ double\n {\n dat = convert_image<double>(d->video, pixtype, VIL_PIXEL_FORMAT_DOUBLE);\n }\n else\n {\n std::string const reason = \"The pixtype \\'\" + pixtype + \"\\' \"\n \"is not supported\";\n throw invalid_configuration_exception(name(), reason);\n }\n\n d->video->advance();\n }\n\n push_datum_to_port(priv::port_output, dat);\n\n process::_step();\n}\n\nread_video_gravl_process::priv\n::priv(std::string const& input_uri)\n : uri(input_uri)\n{\n}\n\nread_video_gravl_process::priv\n::~priv()\n{\n}\n\n}\n\nstatic size_t compute_block_size(gravl::image::dimension dim,\n gravl::image::stride s);\ntemplate <typename T> static T* compute_block_start(\n T* top_left, gravl::image::dimension dim, gravl::image::stride s);\ntemplate <typename T> static T* compute_top_left(\n T* top_left, gravl::image::dimension dim, gravl::image::stride s);\n\ntemplate <typename PixType>\nvistk::datum_t convert_image(\n gravl::data_block* video, vistk::pixtype_t const& pixtype,\n vil_pixel_format pixfmt)\n{\n gravl::frame_ptr const frame = video->current_frame();\n gravl::image_data const* const image_data =\n frame.get_const_data<gravl::image_data>();\n gravl::image const image =\n (image_data ? image_data->pixels() : gravl::image());\n\n if (!image)\n {\n return vistk::datum::empty_datum();\n }\n else if (image.format() != gravl::image::format_of<PixType>())\n {\n std::stringstream reason;\n reason << \"Unable to convert the image: the image pixel type \"\n << image.format() << \" does not match the port output type \"\n << '\\'' << pixtype << '\\'';\n return vistk::datum::error_datum(reason.str());\n }\n else\n {\n gravl::image::dimension const dim = image.dimensions();\n gravl::image::stride const ps = image.strides();\n PixType const* const top_left = image.data<PixType>();\n size_t const size = compute_block_size(dim, ps);\n\n \/\/ vil_image_view is implicitly mutable, even though the ctors would\n \/\/ appear to suggest otherwise... so we must copy the pixels\n vil_memory_chunk* const mem = new vil_memory_chunk(size, pixfmt);\n PixType* const buffer = reinterpret_cast<PixType*>(mem->data());\n memcpy(buffer, compute_block_start(top_left, dim, ps), size);\n\n vil_image_view<PixType> const vil(vil_memory_chunk_sptr(mem),\n compute_top_left(buffer, dim, ps),\n dim.width, dim.height, dim.planes,\n ps.width, ps.height, ps.planes);\n return vistk::datum::new_datum(vil);\n }\n}\n\nstatic size_t\nsabs(ptrdiff_t a)\n{\n return static_cast<size_t>((a < 0 ? -a : a));\n}\n\nsize_t\ncompute_block_size(gravl::image::dimension dim, gravl::image::stride s)\n{\n return ((dim.width - 1) * sabs(s.width)) +\n ((dim.height - 1) * sabs(s.height)) +\n ((dim.planes - 1) * sabs(s.planes)) + 1;\n}\n\nstatic ptrdiff_t\ncompute_offset(gravl::image::dimension dim, gravl::image::stride s)\n{\n ptrdiff_t result = 0;\n if (s.width < 0)\n {\n result -= s.width * (dim.width - 1);\n }\n if (s.height < 0)\n {\n result -= s.height * (dim.height - 1);\n }\n if (s.planes < 0)\n {\n result -= s.planes * (dim.planes - 1);\n }\n return result;\n}\n\ntemplate <typename T>\nT*\ncompute_block_start(\n T* top_left, gravl::image::dimension dim, gravl::image::stride s)\n{\n return top_left - compute_offset(dim, s);\n}\n\ntemplate <typename T>\nT*\ncompute_top_left(\n T* top_left, gravl::image::dimension dim, gravl::image::stride s)\n{\n return top_left + compute_offset(dim, s);\n}\n<|endoftext|>"} {"text":"<commit_before>\/**\n * \\file\n * \\brief Mutex class implementation\n *\n * \\author Copyright (C) 2014 Kamil Szczygiel http:\/\/www.distortec.com http:\/\/www.freddiechopin.info\n *\n * \\par License\n * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not\n * distributed with this file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\n * \\date 2014-09-27\n *\/\n\n#include \"distortos\/scheduler\/Mutex.hpp\"\n\n#include \"distortos\/scheduler\/schedulerInstance.hpp\"\n#include \"distortos\/scheduler\/Scheduler.hpp\"\n\n#include \"distortos\/architecture\/InterruptMaskingLock.hpp\"\n\n#include <cerrno>\n\nnamespace distortos\n{\n\nnamespace scheduler\n{\n\n\/*---------------------------------------------------------------------------------------------------------------------+\n| public functions\n+---------------------------------------------------------------------------------------------------------------------*\/\n\nMutex::Mutex(const Type type) :\n\t\tblockedList_{schedulerInstance.getThreadControlBlockListAllocator(), ThreadControlBlock::State::BlockedOnMutex},\n\t\towner_{},\n\t\trecursiveLocksCount_{},\n\t\ttype_{type}\n{\n\n}\n\nint Mutex::lock()\n{\n\tarchitecture::InterruptMaskingLock interruptMaskingLock;\n\n\tif (owner_ == nullptr)\n\t{\n\t\towner_ = &schedulerInstance.getCurrentThreadControlBlock();\n\t\treturn 0;\n\t}\n\n\tif (type_ == Type::ErrorChecking && owner_ == &schedulerInstance.getCurrentThreadControlBlock())\n\t\treturn EDEADLK;\n\n\tschedulerInstance.block(blockedList_);\n\treturn 0;\n}\n\nint Mutex::tryLock()\n{\n\tarchitecture::InterruptMaskingLock interruptMaskingLock;\n\treturn tryLockInternal();\n}\n\nint Mutex::tryLockFor(const TickClock::duration duration)\n{\n\treturn tryLockUntil(TickClock::now() + duration + TickClock::duration{1});\n}\n\nint Mutex::tryLockUntil(const TickClock::time_point timePoint)\n{\n\tarchitecture::InterruptMaskingLock interruptMaskingLock;\n\n\tif (owner_ == nullptr)\n\t{\n\t\towner_ = &schedulerInstance.getCurrentThreadControlBlock();\n\t\treturn 0;\n\t}\n\n\treturn schedulerInstance.blockUntil(blockedList_, timePoint);\n}\n\nint Mutex::unlock()\n{\n\tarchitecture::InterruptMaskingLock interruptMaskingLock;\n\n\tif (type_ != Type::Normal && owner_ != &schedulerInstance.getCurrentThreadControlBlock())\n\t\treturn EPERM;\n\n\tif (blockedList_.empty() == false)\n\t{\n\t\towner_ = &blockedList_.begin()->get();\t\/\/ pass ownership to the unblocked thread\n\t\tschedulerInstance.unblock(blockedList_.begin());\n\t}\n\telse\n\t\towner_ = nullptr;\n\n\treturn 0;\n}\n\n\/*---------------------------------------------------------------------------------------------------------------------+\n| private functions\n+---------------------------------------------------------------------------------------------------------------------*\/\n\nint Mutex::tryLockInternal()\n{\n\tif (owner_ == nullptr)\n\t{\n\t\towner_ = &schedulerInstance.getCurrentThreadControlBlock();\n\t\treturn 0;\n\t}\n\n\treturn EBUSY;\n}\n\n}\t\/\/ namespace scheduler\n\n}\t\/\/ namespace distortos\n<commit_msg>Mutex: implement main part of Mutex::lock() with Mutex::tryLockInternal()<commit_after>\/**\n * \\file\n * \\brief Mutex class implementation\n *\n * \\author Copyright (C) 2014 Kamil Szczygiel http:\/\/www.distortec.com http:\/\/www.freddiechopin.info\n *\n * \\par License\n * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not\n * distributed with this file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\n * \\date 2014-09-27\n *\/\n\n#include \"distortos\/scheduler\/Mutex.hpp\"\n\n#include \"distortos\/scheduler\/schedulerInstance.hpp\"\n#include \"distortos\/scheduler\/Scheduler.hpp\"\n\n#include \"distortos\/architecture\/InterruptMaskingLock.hpp\"\n\n#include <cerrno>\n\nnamespace distortos\n{\n\nnamespace scheduler\n{\n\n\/*---------------------------------------------------------------------------------------------------------------------+\n| public functions\n+---------------------------------------------------------------------------------------------------------------------*\/\n\nMutex::Mutex(const Type type) :\n\t\tblockedList_{schedulerInstance.getThreadControlBlockListAllocator(), ThreadControlBlock::State::BlockedOnMutex},\n\t\towner_{},\n\t\trecursiveLocksCount_{},\n\t\ttype_{type}\n{\n\n}\n\nint Mutex::lock()\n{\n\tarchitecture::InterruptMaskingLock interruptMaskingLock;\n\n\tconst auto ret = tryLockInternal();\n\tif (ret == 0 || ret == EAGAIN)\t\/\/ lock successful or recursive lock not possible?\n\t\treturn ret;\n\n\tif (type_ == Type::ErrorChecking && owner_ == &schedulerInstance.getCurrentThreadControlBlock())\n\t\treturn EDEADLK;\n\n\tschedulerInstance.block(blockedList_);\n\treturn 0;\n}\n\nint Mutex::tryLock()\n{\n\tarchitecture::InterruptMaskingLock interruptMaskingLock;\n\treturn tryLockInternal();\n}\n\nint Mutex::tryLockFor(const TickClock::duration duration)\n{\n\treturn tryLockUntil(TickClock::now() + duration + TickClock::duration{1});\n}\n\nint Mutex::tryLockUntil(const TickClock::time_point timePoint)\n{\n\tarchitecture::InterruptMaskingLock interruptMaskingLock;\n\n\tif (owner_ == nullptr)\n\t{\n\t\towner_ = &schedulerInstance.getCurrentThreadControlBlock();\n\t\treturn 0;\n\t}\n\n\treturn schedulerInstance.blockUntil(blockedList_, timePoint);\n}\n\nint Mutex::unlock()\n{\n\tarchitecture::InterruptMaskingLock interruptMaskingLock;\n\n\tif (type_ != Type::Normal && owner_ != &schedulerInstance.getCurrentThreadControlBlock())\n\t\treturn EPERM;\n\n\tif (blockedList_.empty() == false)\n\t{\n\t\towner_ = &blockedList_.begin()->get();\t\/\/ pass ownership to the unblocked thread\n\t\tschedulerInstance.unblock(blockedList_.begin());\n\t}\n\telse\n\t\towner_ = nullptr;\n\n\treturn 0;\n}\n\n\/*---------------------------------------------------------------------------------------------------------------------+\n| private functions\n+---------------------------------------------------------------------------------------------------------------------*\/\n\nint Mutex::tryLockInternal()\n{\n\tif (owner_ == nullptr)\n\t{\n\t\towner_ = &schedulerInstance.getCurrentThreadControlBlock();\n\t\treturn 0;\n\t}\n\n\treturn EBUSY;\n}\n\n}\t\/\/ namespace scheduler\n\n}\t\/\/ namespace distortos\n<|endoftext|>"} {"text":"<commit_before>#include \"string.h\"\n#include <vector>\n\nusing namespace std;\n\nnamespace wobble {\nnamespace str {\n\nnamespace {\n\n\/**\n * Return the substring of 'str' without all leading characters for which\n * 'classifier' returns true.\n *\/\ntemplate<typename FUN>\nstd::string lstrip(const std::string& str, const FUN& classifier)\n{\n if (str.empty())\n return str;\n\n size_t beg = 0;\n while (beg < str.size() && classifier(str[beg]))\n ++beg;\n\n return str.substr(beg, str.size() - beg + 1);\n}\n\n\/**\n * Return the substring of 'str' without all trailing characters for which\n * 'classifier' returns true.\n *\/\ntemplate<typename FUN>\nstd::string rstrip(const std::string& str, const FUN& classifier)\n{\n if (str.empty())\n return str;\n\n size_t end = str.size();\n while (end > 0 && classifier(str[end - 1]))\n --end;\n\n if (end == 0)\n return std::string();\n else\n return str.substr(0, end);\n}\n\n\/**\n * Return the substring of 'str' without all leading and trailing characters\n * for which 'classifier' returns true.\n *\/\ntemplate<typename FUN>\nstd::string strip(const std::string& str, const FUN& classifier)\n{\n if (str.empty())\n return str;\n\n size_t beg = 0;\n size_t end = str.size() - 1;\n while (beg < end && classifier(str[beg]))\n ++beg;\n while (end >= beg && classifier(str[end]))\n --end;\n\n return str.substr(beg, end-beg+1);\n}\n\n}\n\n\nstd::string lstrip(const std::string& str)\n{\n return lstrip(str, ::isspace);\n}\n\nstd::string rstrip(const std::string& str)\n{\n return rstrip(str, ::isspace);\n}\n\nstd::string strip(const std::string& str)\n{\n return strip(str, ::isspace);\n}\n\nstd::string basename(const std::string& pathname)\n{\n size_t pos = pathname.rfind(\"\/\");\n if (pos == std::string::npos)\n return pathname;\n else\n return pathname.substr(pos+1);\n}\n\nstd::string dirname(const std::string& pathname)\n{\n if (pathname.empty()) return \".\";\n\n \/\/ Skip trailing separators\n size_t end = pathname.size();\n while (end > 0 && pathname[end - 1] == '\/')\n --end;\n\n \/\/ If the result is empty again, then the string was only \/ characters\n if (!end) return \"\/\";\n\n \/\/ Find the previous separator\n end = pathname.rfind(\"\/\", end - 1);\n\n if (end == std::string::npos)\n \/\/ No previous separator found, everything should be chopped\n return std::string(\".\");\n else\n {\n while (end > 0 && pathname[end - 1] == '\/')\n --end;\n if (!end) return \"\/\";\n return pathname.substr(0, end);\n }\n}\n\nvoid appendpath(std::string& dest, const char* path2)\n{\n if (!*path2)\n return;\n\n if (dest.empty())\n {\n dest = path2;\n return;\n }\n\n if (dest[dest.size() - 1] == '\/')\n if (path2[0] == '\/')\n dest += (path2 + 1);\n else\n dest += path2;\n else\n if (path2[0] == '\/')\n dest += path2;\n else\n {\n dest += '\/';\n dest += path2;\n }\n}\n\nvoid appendpath(std::string& dest, const std::string& path2)\n{\n if (path2.empty())\n return;\n\n if (dest.empty())\n {\n dest = path2;\n return;\n }\n\n if (dest[dest.size() - 1] == '\/')\n if (path2[0] == '\/')\n dest += path2.substr(1);\n else\n dest += path2;\n else\n if (path2[0] == '\/')\n dest += path2;\n else\n {\n dest += '\/';\n dest += path2;\n }\n}\n\nstd::string joinpath(const std::string& path1, const std::string& path2)\n{\n string res = path1;\n appendpath(res, path2);\n return res;\n}\n\nstd::string normpath(const std::string& pathname)\n{\n vector<string> st;\n if (pathname[0] == '\/')\n st.push_back(\"\/\");\n\n Split split(pathname, \"\/\");\n for (const auto& i: split)\n {\n if (i == \".\" || i.empty()) continue;\n if (i == \"..\")\n if (st.back() == \"..\")\n st.emplace_back(i);\n else if (st.back() == \"\/\")\n continue;\n else\n st.pop_back();\n else\n st.emplace_back(i);\n }\n\n if (st.empty())\n return \".\";\n\n string res;\n for (const auto& i: st)\n appendpath(res, i);\n return res;\n}\n\nSplit::const_iterator::const_iterator(const Split& split)\n : split(&split)\n{\n if (split.str.empty())\n this->split = nullptr;\n else\n {\n \/\/ Ignore leading separators if skip_end is true\n if (split.skip_empty) skip_separators();\n ++*this;\n }\n}\n\nSplit::const_iterator::~const_iterator()\n{\n}\n\nstd::string Split::const_iterator::remainder() const\n{\n if (end == std::string::npos)\n return std::string();\n else\n return split->str.substr(end);\n};\n\nvoid Split::const_iterator::skip_separators()\n{\n const std::string& str = split->str;\n const std::string& sep = split->sep;\n\n while (end + sep.size() <= str.size())\n {\n unsigned i = 0;\n for ( ; i < sep.size(); ++i)\n if (str[end + i] != sep[i])\n break;\n if (i < sep.size())\n break;\n else\n end += sep.size();\n }\n}\n\nSplit::const_iterator& Split::const_iterator::operator++()\n{\n if (!split) return *this;\n\n const std::string& str = split->str;\n const std::string& sep = split->sep;\n bool skip_empty = split->skip_empty;\n\n \/\/\/ Convert into an end iterator\n if (end == std::string::npos)\n {\n split = nullptr;\n return *this;\n }\n\n \/\/\/ The string ended with an iterator, and we do not skip empty tokens:\n \/\/\/ return it\n if (end == str.size())\n {\n cur = string();\n end = std::string::npos;\n return *this;\n }\n\n \/\/\/ Position of the first character past the token that starts at 'end'\n size_t tok_end;\n if (sep.empty())\n \/\/\/ If separator is empty, advance one character at a time\n tok_end = end + 1;\n else\n {\n \/\/\/ The token ends at the next separator\n tok_end = str.find(sep, end);\n }\n\n \/\/\/ No more separators found, return from end to the end of the string\n if (tok_end == std::string::npos)\n {\n cur = str.substr(end);\n end = std::string::npos;\n return *this;\n }\n\n \/\/\/ We have the boundaries of the current token\n cur = str.substr(end, tok_end - end);\n\n \/\/\/ Skip the separator\n end = tok_end + sep.size();\n\n \/\/\/ Skip all the following separators if skip_empty is true\n if (skip_empty)\n {\n skip_separators();\n if (end == str.size())\n {\n end = std::string::npos;\n return *this;\n }\n }\n\n return *this;\n}\n\nconst std::string& Split::const_iterator::operator*() const { return cur; }\nconst std::string* Split::const_iterator::operator->() const { return &cur; }\n\nbool Split::const_iterator::operator==(const const_iterator& ti) const\n{\n if (!split && !ti.split) return true;\n if (split != ti.split) return false;\n return end == ti.end;\n}\n\nbool Split::const_iterator::operator!=(const const_iterator& ti) const\n{\n if (!split && !ti.split) return false;\n if (split != ti.split) return true;\n return end != ti.end;\n}\n\n\nstd::string encode_cstring(const std::string& str)\n{\n string res;\n for (string::const_iterator i = str.begin(); i != str.end(); ++i)\n if (*i == '\\n')\n res += \"\\\\n\";\n else if (*i == '\\t')\n res += \"\\\\t\";\n else if (*i == 0 || iscntrl(*i))\n {\n char buf[5];\n snprintf(buf, 5, \"\\\\x%02x\", (unsigned int)*i);\n res += buf;\n }\n else if (*i == '\"' || *i == '\\\\')\n {\n res += \"\\\\\";\n res += *i;\n }\n else\n res += *i;\n return res;\n}\n\nstd::string decode_cstring(const std::string& str, size_t& lenParsed)\n{\n string res;\n string::const_iterator i = str.begin();\n for ( ; i != str.end() && *i != '\"'; ++i)\n if (*i == '\\\\' && (i+1) != str.end())\n {\n switch (*(i+1))\n {\n case 'n': res += '\\n'; break;\n case 't': res += '\\t'; break;\n case 'x': {\n size_t j;\n char buf[5] = \"0x\\0\\0\";\n \/\/ Read up to 2 extra hex digits\n for (j = 0; j < 2 && i+2+j != str.end() && isxdigit(*(i+2+j)); ++j)\n buf[2+j] = *(i+2+j);\n i += j;\n res += (char)atoi(buf);\n break;\n }\n default:\n res += *(i+1);\n break;\n }\n ++i;\n } else\n res += *i;\n if (i != str.end() && *i == '\"')\n ++i;\n lenParsed = i - str.begin();\n return res;\n}\n\nstd::string encode_url(const std::string& str)\n{\n string res;\n for (string::const_iterator i = str.begin(); i != str.end(); ++i)\n {\n if ( (*i >= '0' && *i <= '9') || (*i >= 'A' && *i <= 'Z')\n || (*i >= 'a' && *i <= 'z') || *i == '-' || *i == '_'\n || *i == '!' || *i == '*' || *i == '\\'' || *i == '(' || *i == ')')\n res += *i;\n else {\n char buf[4];\n snprintf(buf, 4, \"%%%02x\", static_cast<unsigned>(static_cast<unsigned char>(*i)));\n res += buf;\n }\n }\n return res;\n}\n\nstd::string decode_url(const std::string& str)\n{\n string res;\n for (size_t i = 0; i < str.size(); ++i)\n {\n if (str[i] == '%')\n {\n \/\/ If there's a partial %something at the end, ignore it\n if (i >= str.size() - 2)\n return res;\n res += static_cast<char>(strtoul(str.substr(i+1, 2).c_str(), 0, 16));\n i += 2;\n }\n else\n res += str[i];\n }\n return res;\n}\n\nstatic const char* base64 = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+\/\";\n\ntemplate<typename T>\nstatic const char invbase64(const T& idx)\n{\n static const char data[] = {62,0,0,0,63,52,53,54,55,56,57,58,59,60,61,0,0,0,0,0,0,0,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,0,0,0,0,0,0,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51};\n if (idx < 43) return 0;\n if (static_cast<unsigned>(idx) > 43 + (sizeof(data)\/sizeof(data[0]))) return 0;\n return data[idx - 43];\n}\n\nstd::string encode_base64(const std::string& str)\n{\n return encode_base64(str.data(), str.size());\n}\n\nstd::string encode_base64(const void* data, size_t size)\n{\n std::string res;\n const uint8_t* str = (const uint8_t*)data;\n\n for (size_t i = 0; i < size; i += 3)\n {\n \/\/ Pack every triplet into 24 bits\n unsigned int enc;\n if (i + 3 < size)\n enc = (str[i] << 16) | (str[i + 1] << 8) | str[i + 2];\n else\n {\n enc = (str[i] << 16);\n if (i + 1 < size)\n enc |= str[i + 1] << 8;\n if (i + 2 < size)\n enc |= str[i + 2];\n }\n\n \/\/ Divide in 4 6-bit values and use them as indexes in the base64 char\n \/\/ array\n for (int j = 18; j >= 0; j -= 6)\n res += base64[(enc >> j) & 63];\n }\n\n \/\/ Replace padding characters with '='\n if (size % 3)\n for (size_t i = 0; i < 3 - (size % 3); ++i)\n res[res.size() - i - 1] = '=';\n\n return res;\n}\n\nstd::string decode_base64(const std::string& str)\n{\n std::string res;\n\n for (size_t i = 0; i < str.size(); i += 4)\n {\n \/\/ Pack every quadruplet into 24 bits\n unsigned int enc;\n if (i+4 < str.size())\n {\n enc = (invbase64(str[i]) << 18)\n + (invbase64(str[i+1]) << 12)\n + (invbase64(str[i+2]) << 6)\n + (invbase64(str[i+3]));\n } else {\n enc = (invbase64(str[i]) << 18);\n if (i+1 < str.size())\n enc += (invbase64(str[i+1]) << 12);\n if (i+2 < str.size())\n enc += (invbase64(str[i+2]) << 6);\n if (i+3 < str.size())\n enc += (invbase64(str[i+3]));\n }\n\n \/\/ Divide in 3 8-bit values and append them to the result\n res += enc >> 16 & 0xff;\n res += enc >> 8 & 0xff;\n res += enc & 0xff;\n }\n\n \/\/ Remove trailing padding\n if (str.size() > 0)\n for (size_t i = str.size() - 1; str[i] == '='; --i)\n {\n if (res.size() > 0)\n res.resize(res.size() - 1);\n if (i == 0 || res.size() == 0 )\n break;\n }\n\n return res;\n}\n\n\n}\n}\n<commit_msg>Changed strip algorithm to prevent an assertion on some distributions<commit_after>#include \"string.h\"\n#include <vector>\n\nusing namespace std;\n\nnamespace wobble {\nnamespace str {\n\nnamespace {\n\n\/**\n * Return the substring of 'str' without all leading characters for which\n * 'classifier' returns true.\n *\/\ntemplate<typename FUN>\nstd::string lstrip(const std::string& str, const FUN& classifier)\n{\n if (str.empty())\n return str;\n\n size_t beg = 0;\n while (beg < str.size() && classifier(str[beg]))\n ++beg;\n\n return str.substr(beg, str.size() - beg + 1);\n}\n\n\/**\n * Return the substring of 'str' without all trailing characters for which\n * 'classifier' returns true.\n *\/\ntemplate<typename FUN>\nstd::string rstrip(const std::string& str, const FUN& classifier)\n{\n if (str.empty())\n return str;\n\n size_t end = str.size();\n while (end > 0 && classifier(str[end - 1]))\n --end;\n\n if (end == 0)\n return std::string();\n else\n return str.substr(0, end);\n}\n\n\/**\n * Return the substring of 'str' without all leading and trailing characters\n * for which 'classifier' returns true.\n *\/\ntemplate<typename FUN>\nstd::string strip(const std::string& str, const FUN& classifier)\n{\n if (str.empty())\n return str;\n\n size_t beg = 0;\n size_t end = str.size();\n while (beg < end && classifier(str[beg]))\n ++beg;\n while (beg < end && classifier(str[end - 1]))\n --end;\n\n return str.substr(beg, end - beg);\n}\n\n}\n\n\nstd::string lstrip(const std::string& str)\n{\n return lstrip(str, ::isspace);\n}\n\nstd::string rstrip(const std::string& str)\n{\n return rstrip(str, ::isspace);\n}\n\nstd::string strip(const std::string& str)\n{\n return strip(str, ::isspace);\n}\n\nstd::string basename(const std::string& pathname)\n{\n size_t pos = pathname.rfind(\"\/\");\n if (pos == std::string::npos)\n return pathname;\n else\n return pathname.substr(pos+1);\n}\n\nstd::string dirname(const std::string& pathname)\n{\n if (pathname.empty()) return \".\";\n\n \/\/ Skip trailing separators\n size_t end = pathname.size();\n while (end > 0 && pathname[end - 1] == '\/')\n --end;\n\n \/\/ If the result is empty again, then the string was only \/ characters\n if (!end) return \"\/\";\n\n \/\/ Find the previous separator\n end = pathname.rfind(\"\/\", end - 1);\n\n if (end == std::string::npos)\n \/\/ No previous separator found, everything should be chopped\n return std::string(\".\");\n else\n {\n while (end > 0 && pathname[end - 1] == '\/')\n --end;\n if (!end) return \"\/\";\n return pathname.substr(0, end);\n }\n}\n\nvoid appendpath(std::string& dest, const char* path2)\n{\n if (!*path2)\n return;\n\n if (dest.empty())\n {\n dest = path2;\n return;\n }\n\n if (dest[dest.size() - 1] == '\/')\n if (path2[0] == '\/')\n dest += (path2 + 1);\n else\n dest += path2;\n else\n if (path2[0] == '\/')\n dest += path2;\n else\n {\n dest += '\/';\n dest += path2;\n }\n}\n\nvoid appendpath(std::string& dest, const std::string& path2)\n{\n if (path2.empty())\n return;\n\n if (dest.empty())\n {\n dest = path2;\n return;\n }\n\n if (dest[dest.size() - 1] == '\/')\n if (path2[0] == '\/')\n dest += path2.substr(1);\n else\n dest += path2;\n else\n if (path2[0] == '\/')\n dest += path2;\n else\n {\n dest += '\/';\n dest += path2;\n }\n}\n\nstd::string joinpath(const std::string& path1, const std::string& path2)\n{\n string res = path1;\n appendpath(res, path2);\n return res;\n}\n\nstd::string normpath(const std::string& pathname)\n{\n vector<string> st;\n if (pathname[0] == '\/')\n st.push_back(\"\/\");\n\n Split split(pathname, \"\/\");\n for (const auto& i: split)\n {\n if (i == \".\" || i.empty()) continue;\n if (i == \"..\")\n if (st.back() == \"..\")\n st.emplace_back(i);\n else if (st.back() == \"\/\")\n continue;\n else\n st.pop_back();\n else\n st.emplace_back(i);\n }\n\n if (st.empty())\n return \".\";\n\n string res;\n for (const auto& i: st)\n appendpath(res, i);\n return res;\n}\n\nSplit::const_iterator::const_iterator(const Split& split)\n : split(&split)\n{\n if (split.str.empty())\n this->split = nullptr;\n else\n {\n \/\/ Ignore leading separators if skip_end is true\n if (split.skip_empty) skip_separators();\n ++*this;\n }\n}\n\nSplit::const_iterator::~const_iterator()\n{\n}\n\nstd::string Split::const_iterator::remainder() const\n{\n if (end == std::string::npos)\n return std::string();\n else\n return split->str.substr(end);\n};\n\nvoid Split::const_iterator::skip_separators()\n{\n const std::string& str = split->str;\n const std::string& sep = split->sep;\n\n while (end + sep.size() <= str.size())\n {\n unsigned i = 0;\n for ( ; i < sep.size(); ++i)\n if (str[end + i] != sep[i])\n break;\n if (i < sep.size())\n break;\n else\n end += sep.size();\n }\n}\n\nSplit::const_iterator& Split::const_iterator::operator++()\n{\n if (!split) return *this;\n\n const std::string& str = split->str;\n const std::string& sep = split->sep;\n bool skip_empty = split->skip_empty;\n\n \/\/\/ Convert into an end iterator\n if (end == std::string::npos)\n {\n split = nullptr;\n return *this;\n }\n\n \/\/\/ The string ended with an iterator, and we do not skip empty tokens:\n \/\/\/ return it\n if (end == str.size())\n {\n cur = string();\n end = std::string::npos;\n return *this;\n }\n\n \/\/\/ Position of the first character past the token that starts at 'end'\n size_t tok_end;\n if (sep.empty())\n \/\/\/ If separator is empty, advance one character at a time\n tok_end = end + 1;\n else\n {\n \/\/\/ The token ends at the next separator\n tok_end = str.find(sep, end);\n }\n\n \/\/\/ No more separators found, return from end to the end of the string\n if (tok_end == std::string::npos)\n {\n cur = str.substr(end);\n end = std::string::npos;\n return *this;\n }\n\n \/\/\/ We have the boundaries of the current token\n cur = str.substr(end, tok_end - end);\n\n \/\/\/ Skip the separator\n end = tok_end + sep.size();\n\n \/\/\/ Skip all the following separators if skip_empty is true\n if (skip_empty)\n {\n skip_separators();\n if (end == str.size())\n {\n end = std::string::npos;\n return *this;\n }\n }\n\n return *this;\n}\n\nconst std::string& Split::const_iterator::operator*() const { return cur; }\nconst std::string* Split::const_iterator::operator->() const { return &cur; }\n\nbool Split::const_iterator::operator==(const const_iterator& ti) const\n{\n if (!split && !ti.split) return true;\n if (split != ti.split) return false;\n return end == ti.end;\n}\n\nbool Split::const_iterator::operator!=(const const_iterator& ti) const\n{\n if (!split && !ti.split) return false;\n if (split != ti.split) return true;\n return end != ti.end;\n}\n\n\nstd::string encode_cstring(const std::string& str)\n{\n string res;\n for (string::const_iterator i = str.begin(); i != str.end(); ++i)\n if (*i == '\\n')\n res += \"\\\\n\";\n else if (*i == '\\t')\n res += \"\\\\t\";\n else if (*i == 0 || iscntrl(*i))\n {\n char buf[5];\n snprintf(buf, 5, \"\\\\x%02x\", (unsigned int)*i);\n res += buf;\n }\n else if (*i == '\"' || *i == '\\\\')\n {\n res += \"\\\\\";\n res += *i;\n }\n else\n res += *i;\n return res;\n}\n\nstd::string decode_cstring(const std::string& str, size_t& lenParsed)\n{\n string res;\n string::const_iterator i = str.begin();\n for ( ; i != str.end() && *i != '\"'; ++i)\n if (*i == '\\\\' && (i+1) != str.end())\n {\n switch (*(i+1))\n {\n case 'n': res += '\\n'; break;\n case 't': res += '\\t'; break;\n case 'x': {\n size_t j;\n char buf[5] = \"0x\\0\\0\";\n \/\/ Read up to 2 extra hex digits\n for (j = 0; j < 2 && i+2+j != str.end() && isxdigit(*(i+2+j)); ++j)\n buf[2+j] = *(i+2+j);\n i += j;\n res += (char)atoi(buf);\n break;\n }\n default:\n res += *(i+1);\n break;\n }\n ++i;\n } else\n res += *i;\n if (i != str.end() && *i == '\"')\n ++i;\n lenParsed = i - str.begin();\n return res;\n}\n\nstd::string encode_url(const std::string& str)\n{\n string res;\n for (string::const_iterator i = str.begin(); i != str.end(); ++i)\n {\n if ( (*i >= '0' && *i <= '9') || (*i >= 'A' && *i <= 'Z')\n || (*i >= 'a' && *i <= 'z') || *i == '-' || *i == '_'\n || *i == '!' || *i == '*' || *i == '\\'' || *i == '(' || *i == ')')\n res += *i;\n else {\n char buf[4];\n snprintf(buf, 4, \"%%%02x\", static_cast<unsigned>(static_cast<unsigned char>(*i)));\n res += buf;\n }\n }\n return res;\n}\n\nstd::string decode_url(const std::string& str)\n{\n string res;\n for (size_t i = 0; i < str.size(); ++i)\n {\n if (str[i] == '%')\n {\n \/\/ If there's a partial %something at the end, ignore it\n if (i >= str.size() - 2)\n return res;\n res += static_cast<char>(strtoul(str.substr(i+1, 2).c_str(), 0, 16));\n i += 2;\n }\n else\n res += str[i];\n }\n return res;\n}\n\nstatic const char* base64 = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+\/\";\n\ntemplate<typename T>\nstatic const char invbase64(const T& idx)\n{\n static const char data[] = {62,0,0,0,63,52,53,54,55,56,57,58,59,60,61,0,0,0,0,0,0,0,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,0,0,0,0,0,0,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51};\n if (idx < 43) return 0;\n if (static_cast<unsigned>(idx) > 43 + (sizeof(data)\/sizeof(data[0]))) return 0;\n return data[idx - 43];\n}\n\nstd::string encode_base64(const std::string& str)\n{\n return encode_base64(str.data(), str.size());\n}\n\nstd::string encode_base64(const void* data, size_t size)\n{\n std::string res;\n const uint8_t* str = (const uint8_t*)data;\n\n for (size_t i = 0; i < size; i += 3)\n {\n \/\/ Pack every triplet into 24 bits\n unsigned int enc;\n if (i + 3 < size)\n enc = (str[i] << 16) | (str[i + 1] << 8) | str[i + 2];\n else\n {\n enc = (str[i] << 16);\n if (i + 1 < size)\n enc |= str[i + 1] << 8;\n if (i + 2 < size)\n enc |= str[i + 2];\n }\n\n \/\/ Divide in 4 6-bit values and use them as indexes in the base64 char\n \/\/ array\n for (int j = 18; j >= 0; j -= 6)\n res += base64[(enc >> j) & 63];\n }\n\n \/\/ Replace padding characters with '='\n if (size % 3)\n for (size_t i = 0; i < 3 - (size % 3); ++i)\n res[res.size() - i - 1] = '=';\n\n return res;\n}\n\nstd::string decode_base64(const std::string& str)\n{\n std::string res;\n\n for (size_t i = 0; i < str.size(); i += 4)\n {\n \/\/ Pack every quadruplet into 24 bits\n unsigned int enc;\n if (i+4 < str.size())\n {\n enc = (invbase64(str[i]) << 18)\n + (invbase64(str[i+1]) << 12)\n + (invbase64(str[i+2]) << 6)\n + (invbase64(str[i+3]));\n } else {\n enc = (invbase64(str[i]) << 18);\n if (i+1 < str.size())\n enc += (invbase64(str[i+1]) << 12);\n if (i+2 < str.size())\n enc += (invbase64(str[i+2]) << 6);\n if (i+3 < str.size())\n enc += (invbase64(str[i+3]));\n }\n\n \/\/ Divide in 3 8-bit values and append them to the result\n res += enc >> 16 & 0xff;\n res += enc >> 8 & 0xff;\n res += enc & 0xff;\n }\n\n \/\/ Remove trailing padding\n if (str.size() > 0)\n for (size_t i = str.size() - 1; str[i] == '='; --i)\n {\n if (res.size() > 0)\n res.resize(res.size() - 1);\n if (i == 0 || res.size() == 0 )\n break;\n }\n\n return res;\n}\n\n\n}\n}\n<|endoftext|>"} {"text":"<commit_before>\n#pragma once\n\n#include \"physics\/euler_solver.hpp\"\n\n#include <algorithm>\n\n#include \"geometry\/grassmann.hpp\"\n#include \"numerics\/elliptic_functions.hpp\"\n#include \"numerics\/elliptic_integrals.hpp\"\n#include \"quantities\/elementary_functions.hpp\"\n#include \"quantities\/si.hpp\"\n\nnamespace principia {\nnamespace physics {\nnamespace internal_euler_solver {\n\nusing geometry::Vector;\nusing numerics::EllipticF;\nusing numerics::EllipticΠ;\nusing numerics::JacobiAmplitude;\nusing numerics::JacobiSNCNDN;\nusing quantities::Abs;\nusing quantities::ArcTan;\nusing quantities::ArcTanh;\nusing quantities::Cosh;\nusing quantities::Pow;\nusing quantities::Tanh;\nusing quantities::Energy;\nusing quantities::Inverse;\nusing quantities::Sqrt;\nusing quantities::Square;\nusing quantities::SquareRoot;\nusing quantities::SIUnit;\nusing quantities::Time;\nusing quantities::si::Joule;\nusing quantities::si::Radian;\n\ntemplate<typename InertialFrame, typename PrincipalAxesFrame>\nEulerSolver<InertialFrame, PrincipalAxesFrame>::EulerSolver(\n R3Element<MomentOfInertia> const& moments_of_inertia,\n AngularMomentumBivector const& initial_angular_momentum,\n AttitudeRotation const& initial_attitude,\n Instant const& initial_time)\n : moments_of_inertia_(moments_of_inertia),\n initial_angular_momentum_(initial_angular_momentum),\n initial_attitude_(initial_attitude),\n initial_time_(initial_time) {\n CHECK_LE(I₁_, I₂_);\n CHECK_LE(I₂_, I₃_);\n\n auto const& m = initial_angular_momentum.coordinates();\n\n auto const I₁₂ = I₁_ - I₂_;\n auto const I₁₃ = I₁_ - I₃_;\n auto const I₂₁ = -I₁₂;\n auto const I₂₃ = I₂_ - I₃_;\n auto const I₃₁ = -I₁₃;\n auto const I₃₂ = -I₂₃;\n\n \/\/ The formulæ for the Δs in Celledoni cannot be used directly because of\n \/\/ cancellations.\n auto const Δ₁ = m.y * m.y * I₂₁ \/ I₂_ + m.z * m.z * I₃₁ \/ I₃_;\n auto const Δ₂ = m.x * m.x * I₁₂ \/ I₁_ + m.z * m.z * I₃₂ \/ I₃_;\n auto const Δ₃ = m.x * m.x * I₃₁ \/ I₁_ + m.y * m.y * I₃₂ \/ I₂_;\n DCHECK_LE(Square<AngularMomentum>(), Δ₁);\n DCHECK_LE(Square<AngularMomentum>(), Δ₃);\n\n auto const G² = initial_angular_momentum_.Norm²();\n auto const two_T = m.x * m.x \/ I₁_ + m.y * m.y \/ I₂_ + m.z * m.z \/ I₃_;\n\n B₁₃_ = Sqrt(I₁_ * Δ₃ \/ I₃₁);\n B₃₁_ = Sqrt(I₃_ * Δ₁ \/ I₃₁);\n\n \/\/ Note that Celledoni et al. give k, but we need mc = 1 - k^2. We write mc\n \/\/ in a way that reduces cancellations when k is close to 1.\n if (Δ₂ < Square<AngularMomentum>()) {\n B₂₁_ = Sqrt(I₂_ * Δ₁ \/ I₂₁);\n mc_ = -Δ₂ * I₃₁ \/ (Δ₃ * I₂₁);\n ν_ = EllipticF(ArcTan(m.y \/ B₂₁_, m.z \/ B₃₁_), mc_);\n λ₃_ = Sqrt(Δ₃ * I₂₁ \/ (I₁_ * I₂_ * I₃_));\n if (m.x < AngularMomentum()) {\n B₁₃_ = -B₁₃_;\n } else {\n λ₃_ = -λ₃_;\n }\n auto const B₂₃² = -I₂_ * Δ₃ \/ I₃₂;\n DCHECK_LE(Square<AngularMomentum>(), B₂₃²);\n n_ = G² \/ B₂₃²;\n ψ_Π_offset = EllipticΠ(-ν_, n_, mc_);\n ψ_Π_multiplier_ = Δ₂ \/ (λ₃_ * I₂_ * G_);\n ψ_t_multiplier_ = two_T \/ G_;\n formula_ = Formula::i;\n } else if (Square<AngularMomentum>() < Δ₂) {\n B₂₃_ = Sqrt(I₂_ * Δ₃ \/ I₃₂);\n mc_ = Δ₂ * I₃₁ \/ (Δ₁ * I₃₂);\n ν_ = EllipticF(ArcTan(m.y \/ B₂₃_, m.x \/ B₁₃_), mc_);\n λ₁_ = Sqrt(Δ₁ * I₃₂ \/ (I₁_ * I₂_ * I₃_));\n if (m.z < AngularMomentum()) {\n B₃₁_ = -B₃₁_;\n } else {\n λ₁_ = -λ₁_;\n }\n auto const B₂₁² = I₂_ * Δ₁ \/ I₂₁;\n DCHECK_LE(Square<AngularMomentum>(), B₂₁²);\n n_ = G² \/ B₂₁²;\n ψ_Π_offset = EllipticΠ(-ν_, n_, mc_);\n ψ_Π_multiplier_ = Δ₂ \/ (λ₁_ * I₂_ * G_);\n ψ_t_multiplier_ = two_T \/ G_;\n formula_ = Formula::ii;\n } else {\n CHECK_EQ(Square<AngularMomentum>(), Δ₂);\n if (I₃₁ == MomentOfInertia()) {\n \/\/ The degenerate case of a sphere. It would create NaNs.\n DCHECK_EQ(MomentOfInertia(), I₂₁);\n DCHECK_EQ(MomentOfInertia(), I₃₂);\n formula_ = Formula::Sphere;\n } else {\n G_ = Sqrt(G²);\n ν_ = -ArcTanh(m.y \/ G_);\n λ₂_ = Sqrt(Δ₁ * Δ₃ \/ (I₁_ * I₃_)) \/ G_;\n if (m.x < AngularMomentum()) {\n B₁₃_ = -B₁₃_;\n λ₂_ = -λ₂_;\n }\n if (m.z < AngularMomentum()) {\n B₃₁_ = -B₃₁_;\n λ₂_ = -λ₂_;\n }\n formula_ = Formula::iii;\n }\n }\n}\n\ntemplate<typename InertialFrame, typename PrincipalAxesFrame>\ntypename EulerSolver<InertialFrame, PrincipalAxesFrame>::AngularMomentumBivector\nEulerSolver<InertialFrame, PrincipalAxesFrame>::AngularMomentumAt(\n Instant const& time) const {\n Time const Δt = time - initial_time_;\n switch (formula_) {\n case Formula::i: {\n double sn;\n double cn;\n double dn;\n JacobiSNCNDN(λ₃_ * Δt - ν_, mc_, sn, cn, dn);\n return AngularMomentumBivector({B₁₃_ * dn, -B₂₁_ * sn, B₃₁_ * cn});\n }\n case Formula::ii: {\n double sn;\n double cn;\n double dn;\n JacobiSNCNDN(λ₁_ * Δt - ν_, mc_, sn, cn, dn);\n return AngularMomentumBivector({B₁₃_ * cn, -B₂₃_ * sn, B₃₁_ * dn});\n }\n case Formula::iii: {\n Angle const angle = λ₂_ * Δt - ν_;\n double const sech = 1.0 \/ Cosh(angle);\n return AngularMomentumBivector(\n {B₁₃_ * sech, G_ * Tanh(angle), B₃₁_ * sech});\n }\n case Formula::Sphere : {\n \/\/ NOTE(phl): It's unclear how the formulæ degenerate in this case, but\n \/\/ surely λ₃_ becomes 0, so the dependency in time disappears, so this is\n \/\/ my best guess.\n return initial_angular_momentum_;\n }\n default:\n LOG(FATAL) << \"Unexpected formula \" << static_cast<int>(formula_);\n };\n}\n\ntemplate<typename InertialFrame, typename PrincipalAxesFrame>\ntypename EulerSolver<InertialFrame, PrincipalAxesFrame>::AttitudeRotation\nEulerSolver<InertialFrame, PrincipalAxesFrame>::AttitudeAt(\n AngularMomentumBivector const& angular_momentum,\n Instant const& time) const {\n auto const& m = angular_momentum.coordinates();\n Time const Δt = time - initial_time_;\n switch (formula_) {\n case Formula::i: {\n \/\/ Note that the sign of λ has been integrated in λ₃_ at construction.\n Angle const φ = JacobiAmplitude(λ₃_ * Δt - ν_, mc_);\n Angle const ψ = ψ_t_multiplier_ * Δt +\n ψ_Π_multiplier_ * (EllipticΠ(φ, n_, mc_) - ψ_Π_offset);\n }\n case Formula::ii: {\n \/\/ Note that the sign of λ has been integrated in λ₁_ at construction.\n Angle const φ = JacobiAmplitude(λ₁_ * Δt - ν_, mc_);\n Angle const ψ = ψ_t_multiplier_ * Δt +\n ψ_Π_multiplier_ * (EllipticΠ(φ, n_, mc_) - ψ_Π_offset);\n }\n case Formula::iii: {\n }\n case Formula::Sphere : {\n }\n default:\n LOG(FATAL) << \"Unexpected formula \" << static_cast<int>(formula_);\n };\n return AttitudeRotation::Identity();\n}\n\n} \/\/ namespace internal_euler_solver\n} \/\/ namespace physics\n} \/\/ namespace principia\n<commit_msg>A bit of case iii.<commit_after>\n#pragma once\n\n#include \"physics\/euler_solver.hpp\"\n\n#include <algorithm>\n\n#include \"geometry\/grassmann.hpp\"\n#include \"numerics\/elliptic_functions.hpp\"\n#include \"numerics\/elliptic_integrals.hpp\"\n#include \"quantities\/elementary_functions.hpp\"\n#include \"quantities\/si.hpp\"\n\nnamespace principia {\nnamespace physics {\nnamespace internal_euler_solver {\n\nusing geometry::Vector;\nusing numerics::EllipticF;\nusing numerics::EllipticΠ;\nusing numerics::JacobiAmplitude;\nusing numerics::JacobiSNCNDN;\nusing quantities::Abs;\nusing quantities::ArcTan;\nusing quantities::ArcTanh;\nusing quantities::Cosh;\nusing quantities::Pow;\nusing quantities::Tanh;\nusing quantities::Energy;\nusing quantities::Inverse;\nusing quantities::Sqrt;\nusing quantities::Square;\nusing quantities::SquareRoot;\nusing quantities::SIUnit;\nusing quantities::Time;\nusing quantities::si::Joule;\nusing quantities::si::Radian;\n\ntemplate<typename InertialFrame, typename PrincipalAxesFrame>\nEulerSolver<InertialFrame, PrincipalAxesFrame>::EulerSolver(\n R3Element<MomentOfInertia> const& moments_of_inertia,\n AngularMomentumBivector const& initial_angular_momentum,\n AttitudeRotation const& initial_attitude,\n Instant const& initial_time)\n : moments_of_inertia_(moments_of_inertia),\n initial_angular_momentum_(initial_angular_momentum),\n initial_attitude_(initial_attitude),\n initial_time_(initial_time) {\n CHECK_LE(I₁_, I₂_);\n CHECK_LE(I₂_, I₃_);\n\n auto const& m = initial_angular_momentum.coordinates();\n\n auto const I₁₂ = I₁_ - I₂_;\n auto const I₁₃ = I₁_ - I₃_;\n auto const I₂₁ = -I₁₂;\n auto const I₂₃ = I₂_ - I₃_;\n auto const I₃₁ = -I₁₃;\n auto const I₃₂ = -I₂₃;\n\n \/\/ The formulæ for the Δs in Celledoni cannot be used directly because of\n \/\/ cancellations.\n auto const Δ₁ = m.y * m.y * I₂₁ \/ I₂_ + m.z * m.z * I₃₁ \/ I₃_;\n auto const Δ₂ = m.x * m.x * I₁₂ \/ I₁_ + m.z * m.z * I₃₂ \/ I₃_;\n auto const Δ₃ = m.x * m.x * I₃₁ \/ I₁_ + m.y * m.y * I₃₂ \/ I₂_;\n DCHECK_LE(Square<AngularMomentum>(), Δ₁);\n DCHECK_LE(Square<AngularMomentum>(), Δ₃);\n\n auto const G² = initial_angular_momentum_.Norm²();\n auto const two_T = m.x * m.x \/ I₁_ + m.y * m.y \/ I₂_ + m.z * m.z \/ I₃_;\n\n auto const B₂₃² = I₂_ * Δ₃ \/ I₃₂;\n auto const B₂₁² = I₂_ * Δ₁ \/ I₂₁;\n DCHECK_LE(Square<AngularMomentum>(), B₂₃²);\n DCHECK_LE(Square<AngularMomentum>(), B₂₁²);\n\n B₁₃_ = Sqrt(I₁_ * Δ₃ \/ I₃₁);\n B₃₁_ = Sqrt(I₃_ * Δ₁ \/ I₃₁);\n\n \/\/ Note that Celledoni et al. give k, but we need mc = 1 - k^2. We write mc\n \/\/ in a way that reduces cancellations when k is close to 1.\n if (Δ₂ < Square<AngularMomentum>()) {\n B₂₁_ = Sqrt(B₂₁²);\n mc_ = -Δ₂ * I₃₁ \/ (Δ₃ * I₂₁);\n ν_ = EllipticF(ArcTan(m.y \/ B₂₁_, m.z \/ B₃₁_), mc_);\n λ₃_ = Sqrt(Δ₃ * I₂₁ \/ (I₁_ * I₂_ * I₃_));\n if (m.x < AngularMomentum()) {\n B₁₃_ = -B₁₃_;\n } else {\n λ₃_ = -λ₃_;\n }\n n_ = G² \/ B₂₃²;\n ψ_Π_offset = EllipticΠ(-ν_, n_, mc_);\n ψ_Π_multiplier_ = Δ₂ \/ (λ₃_ * I₂_ * G_);\n ψ_t_multiplier_ = two_T \/ G_;\n formula_ = Formula::i;\n } else if (Square<AngularMomentum>() < Δ₂) {\n B₂₃_ = Sqrt(B₂₃²);\n mc_ = Δ₂ * I₃₁ \/ (Δ₁ * I₃₂);\n ν_ = EllipticF(ArcTan(m.y \/ B₂₃_, m.x \/ B₁₃_), mc_);\n λ₁_ = Sqrt(Δ₁ * I₃₂ \/ (I₁_ * I₂_ * I₃_));\n if (m.z < AngularMomentum()) {\n B₃₁_ = -B₃₁_;\n } else {\n λ₁_ = -λ₁_;\n }\n n_ = G² \/ B₂₁²;\n ψ_Π_offset = EllipticΠ(-ν_, n_, mc_);\n ψ_Π_multiplier_ = Δ₂ \/ (λ₁_ * I₂_ * G_);\n ψ_t_multiplier_ = two_T \/ G_;\n formula_ = Formula::ii;\n } else {\n CHECK_EQ(Square<AngularMomentum>(), Δ₂);\n if (I₃₁ == MomentOfInertia()) {\n \/\/ The degenerate case of a sphere. It would create NaNs.\n DCHECK_EQ(MomentOfInertia(), I₂₁);\n DCHECK_EQ(MomentOfInertia(), I₃₂);\n formula_ = Formula::Sphere;\n } else {\n G_ = Sqrt(G²);\n ν_ = -ArcTanh(m.y \/ G_);\n λ₂_ = Sqrt(Δ₁ * Δ₃ \/ (I₁_ * I₃_)) \/ G_;\n if (m.x < AngularMomentum()) {\n B₁₃_ = -B₁₃_;\n λ₂_ = -λ₂_;\n }\n if (m.z < AngularMomentum()) {\n B₃₁_ = -B₃₁_;\n λ₂_ = -λ₂_;\n }\n \/\/ Not quite an elliptic integral characteristic, but we'll stick to that\n \/\/ notation.\n n_ = G² * G² \/ (B₂₁² * B₂₃²);\n formula_ = Formula::iii;\n }\n }\n}\n\ntemplate<typename InertialFrame, typename PrincipalAxesFrame>\ntypename EulerSolver<InertialFrame, PrincipalAxesFrame>::AngularMomentumBivector\nEulerSolver<InertialFrame, PrincipalAxesFrame>::AngularMomentumAt(\n Instant const& time) const {\n Time const Δt = time - initial_time_;\n switch (formula_) {\n case Formula::i: {\n double sn;\n double cn;\n double dn;\n JacobiSNCNDN(λ₃_ * Δt - ν_, mc_, sn, cn, dn);\n return AngularMomentumBivector({B₁₃_ * dn, -B₂₁_ * sn, B₃₁_ * cn});\n }\n case Formula::ii: {\n double sn;\n double cn;\n double dn;\n JacobiSNCNDN(λ₁_ * Δt - ν_, mc_, sn, cn, dn);\n return AngularMomentumBivector({B₁₃_ * cn, -B₂₃_ * sn, B₃₁_ * dn});\n }\n case Formula::iii: {\n Angle const angle = λ₂_ * Δt - ν_;\n double const sech = 1.0 \/ Cosh(angle);\n return AngularMomentumBivector(\n {B₁₃_ * sech, G_ * Tanh(angle), B₃₁_ * sech});\n }\n case Formula::Sphere : {\n \/\/ NOTE(phl): It's unclear how the formulæ degenerate in this case, but\n \/\/ surely λ₃_ becomes 0, so the dependency in time disappears, so this is\n \/\/ my best guess.\n return initial_angular_momentum_;\n }\n default:\n LOG(FATAL) << \"Unexpected formula \" << static_cast<int>(formula_);\n };\n}\n\ntemplate<typename InertialFrame, typename PrincipalAxesFrame>\ntypename EulerSolver<InertialFrame, PrincipalAxesFrame>::AttitudeRotation\nEulerSolver<InertialFrame, PrincipalAxesFrame>::AttitudeAt(\n AngularMomentumBivector const& angular_momentum,\n Instant const& time) const {\n auto const& m = angular_momentum.coordinates();\n Time const Δt = time - initial_time_;\n switch (formula_) {\n case Formula::i: {\n \/\/ Note that the sign of λ has been integrated in λ₃_ at construction.\n Angle const φ = JacobiAmplitude(λ₃_ * Δt - ν_, mc_);\n Angle const ψ = ψ_t_multiplier_ * Δt +\n ψ_Π_multiplier_ * (EllipticΠ(φ, n_, mc_) - ψ_Π_offset);\n }\n case Formula::ii: {\n \/\/ Note that the sign of λ has been integrated in λ₁_ at construction.\n Angle const φ = JacobiAmplitude(λ₁_ * Δt - ν_, mc_);\n Angle const ψ = ψ_t_multiplier_ * Δt +\n ψ_Π_multiplier_ * (EllipticΠ(φ, n_, mc_) - ψ_Π_offset);\n }\n case Formula::iii: {\n }\n case Formula::Sphere : {\n }\n default:\n LOG(FATAL) << \"Unexpected formula \" << static_cast<int>(formula_);\n };\n return AttitudeRotation::Identity();\n}\n\n} \/\/ namespace internal_euler_solver\n} \/\/ namespace physics\n} \/\/ namespace principia\n<|endoftext|>"} {"text":"<commit_before>#define DOCTEST_CONFIG_IMPLEMENT\n#include \"doctest.h\"\n#include \"iguana\/json_reader.hpp\"\n#include <iguana\/json.hpp>\n#include <iguana\/json_util.hpp>\n#include <iostream>\n#include <optional>\n\nstruct point_t {\n int x;\n double y;\n};\nREFLECTION(point_t, x, y);\n\nstruct person {\n std::string name;\n bool ok;\n};\nREFLECTION(person, name, ok);\n\nstruct bool_t {\n bool ok;\n};\nREFLECTION(bool_t, ok);\n\nstruct optional_t {\n std::optional<bool> p;\n};\nREFLECTION(optional_t, p);\n\nstruct char_t {\n char ch;\n};\nREFLECTION(char_t, ch);\n\n\/\/ nested object\nstruct simple_nested_t {\n int id;\n person p;\n};\nREFLECTION(simple_nested_t, id, p);\n\n\/\/ c array\nstruct arr_t {\n int arr[2];\n};\nREFLECTION(arr_t, arr);\n\n\/\/ std array\nstruct std_array_t {\n std::array<int, 2> arr;\n};\nREFLECTION(std_array_t, arr);\n\n\/\/ vector\nstruct vector_t {\n std::vector<int> arr;\n};\nREFLECTION(vector_t, arr);\n\nstruct two_fields_t {\n std::array<int, 2> a;\n std::vector<std::string> v;\n};\nREFLECTION(two_fields_t, a, v);\n\n\/\/ map TODO\n\n\/\/ list, set, unordered map... TODO\n\nTEST_CASE(\"test simple object\") {\n std::string_view str = R\"({\"name\": \"tom\", \"ok\":true})\";\n\n person p{};\n iguana::from_json(p, std::begin(str), std::end(str));\n CHECK(p.name == \"tom\");\n CHECK(p.ok == true);\n\n SUBCASE(\"random order of fields\") {\n person p1{};\n std::string_view str1 = R\"({\"ok\":true, \"name\": \"tom\"})\";\n iguana::from_json(p1, std::begin(str1), std::end(str1));\n CHECK(p1.name == \"tom\");\n CHECK(p1.ok == true);\n }\n}\n\nTEST_CASE(\"test two_fields object\") {\n two_fields_t obj{{1, 2}, {\"aa\", \"bb\"}};\n iguana::string_stream ss;\n iguana::json::to_json(ss, obj);\n\n std::string str = ss.str();\n two_fields_t p{};\n iguana::from_json(p, std::begin(str), std::end(str));\n CHECK(p.v == obj.v);\n}\n\nTEST_CASE(\"test simple nested object\") {\n simple_nested_t t{.id = 1, {.name = \"tom\", .ok = false}};\n iguana::string_stream ss;\n iguana::json::to_json(ss, t);\n\n std::string str = ss.str();\n simple_nested_t p{};\n iguana::from_json(p, std::begin(str), std::end(str));\n\n CHECK(t.id == p.id);\n CHECK(t.p.name == p.p.name);\n CHECK(t.p.ok == p.p.ok);\n}\n\nTEST_CASE(\"test c array and std::array\") {\n arr_t arr{{1, 2}};\n iguana::string_stream ss;\n iguana::json::to_json(ss, arr);\n arr_t arr1{};\n std::string str = ss.str();\n\n iguana::from_json(arr1, std::begin(str), std::end(str));\n CHECK(arr.arr[0] == arr1.arr[0]);\n CHECK(arr.arr[1] == arr1.arr[1]);\n\n std_array_t arr2{};\n iguana::from_json(arr2, std::begin(str), std::end(str));\n CHECK(arr.arr[0] == arr2.arr[0]);\n CHECK(arr.arr[1] == arr2.arr[1]);\n\n vector_t vec;\n iguana::from_json(vec, std::begin(str), std::end(str));\n CHECK(vec.arr.size() == arr2.arr.size());\n CHECK(arr2.arr[0] == vec.arr[0]);\n CHECK(arr2.arr[1] == vec.arr[1]);\n}\n\nTEST_CASE(\"test bool, null, char, int, float\") {\n {\n optional_t p{};\n std::string str = R\"({\"p\": false})\";\n iguana::from_json(p, std::begin(str), std::end(str));\n CHECK(p.p.has_value());\n CHECK(*p.p == false);\n\n std::string str1 = R\"({\"p\": null})\";\n optional_t p1{};\n iguana::from_json(p1, std::begin(str1), std::end(str1));\n CHECK(!p1.p.has_value());\n }\n {\n char_t p{};\n std::string str = R\"({\"ch\": \"t\"})\";\n iguana::from_json(p, std::begin(str), std::end(str));\n CHECK(p.ch == 't');\n }\n\n {\n bool_t p{};\n std::string str = R\"({\"ok\": true})\";\n iguana::from_json(p, std::begin(str), std::end(str));\n CHECK(p.ok == true);\n }\n\n {\n point_t p{};\n std::string str = R\"({\"x\" : 1, \"y\" : 2})\";\n iguana::from_json(p, std::begin(str), std::end(str));\n CHECK(p.x == 1);\n CHECK(p.y == double(2));\n }\n}\n\nTEST_CASE(\"test vector\") {\n vector_t arr{{1, 2}};\n iguana::string_stream ss;\n iguana::json::to_json(ss, arr);\n\n std::string str = ss.str();\n vector_t p{};\n iguana::from_json(p, std::begin(str), std::end(str));\n CHECK(arr.arr == p.arr);\n}\n\nTEST_CASE(\"check some types\") {\n using value_type = std::variant<int point_t::*, double point_t::*>;\n constexpr auto map = iguana::get_iguana_struct_map<point_t>();\n static_assert(map.size() == 2);\n static_assert(map.at(\"x\") ==\n value_type{std::in_place_index_t<0>{}, &point_t::x});\n static_assert(map.at(\"y\") ==\n value_type{std::in_place_index_t<1>{}, &point_t::y});\n}\n\n\/\/ doctest comments\n\/\/ 'function' : must be 'attribute' - see issue #182\nDOCTEST_MSVC_SUPPRESS_WARNING_WITH_PUSH(4007)\nint main(int argc, char **argv) { return doctest::Context(argc, argv).run(); }\nDOCTEST_MSVC_SUPPRESS_WARNING_POP<commit_msg>fix compile error on gcc10<commit_after>#define DOCTEST_CONFIG_IMPLEMENT\n#include \"doctest.h\"\n#include \"iguana\/json_reader.hpp\"\n#include <iguana\/json.hpp>\n#include <iguana\/json_util.hpp>\n#include <iostream>\n#include <optional>\n\nstruct point_t {\n int x;\n double y;\n};\nREFLECTION(point_t, x, y);\n\nstruct person {\n std::string name;\n bool ok;\n};\nREFLECTION(person, name, ok);\n\nstruct bool_t {\n bool ok;\n};\nREFLECTION(bool_t, ok);\n\nstruct optional_t {\n std::optional<bool> p;\n};\nREFLECTION(optional_t, p);\n\nstruct char_t {\n char ch;\n};\nREFLECTION(char_t, ch);\n\n\/\/ nested object\nstruct simple_nested_t {\n int id;\n person p;\n};\nREFLECTION(simple_nested_t, id, p);\n\n\/\/ c array\nstruct arr_t {\n int arr[2];\n};\nREFLECTION(arr_t, arr);\n\n\/\/ std array\nstruct std_array_t {\n std::array<int, 2> arr;\n};\nREFLECTION(std_array_t, arr);\n\n\/\/ vector\nstruct vector_t {\n std::vector<int> arr;\n};\nREFLECTION(vector_t, arr);\n\nstruct two_fields_t {\n std::array<int, 2> a;\n std::vector<std::string> v;\n};\nREFLECTION(two_fields_t, a, v);\n\n\/\/ map TODO\nstruct map_t {\n std::map<int, std::string> map;\n};\nREFLECTION(map_t, map);\n\n\/\/ list, set, unordered map... TODO\n\nTEST_CASE(\"test simple object\") {\n std::string_view str = R\"({\"name\": \"tom\", \"ok\":true})\";\n\n person p{};\n iguana::from_json(p, std::begin(str), std::end(str));\n CHECK(p.name == \"tom\");\n CHECK(p.ok == true);\n\n SUBCASE(\"random order of fields\") {\n person p1{};\n std::string_view str1 = R\"({\"ok\":true, \"name\": \"tom\"})\";\n iguana::from_json(p1, std::begin(str1), std::end(str1));\n CHECK(p1.name == \"tom\");\n CHECK(p1.ok == true);\n }\n}\n\nTEST_CASE(\"test two_fields object\") {\n two_fields_t obj{{1, 2}, {\"aa\", \"bb\"}};\n iguana::string_stream ss;\n iguana::json::to_json(ss, obj);\n\n std::string str = ss.str();\n two_fields_t p{};\n iguana::from_json(p, std::begin(str), std::end(str));\n CHECK(p.v == obj.v);\n}\n\nTEST_CASE(\"test simple nested object\") {\n person o{.name = \"tom\", .ok = false};\n simple_nested_t t{1, o};\n iguana::string_stream ss;\n iguana::json::to_json(ss, t);\n\n std::string str = ss.str();\n simple_nested_t p{};\n iguana::from_json(p, std::begin(str), std::end(str));\n\n CHECK(t.id == p.id);\n CHECK(t.p.name == p.p.name);\n CHECK(t.p.ok == p.p.ok);\n}\n\nTEST_CASE(\"test c array and std::array\") {\n arr_t arr{{1, 2}};\n iguana::string_stream ss;\n iguana::json::to_json(ss, arr);\n arr_t arr1{};\n std::string str = ss.str();\n\n iguana::from_json(arr1, std::begin(str), std::end(str));\n CHECK(arr.arr[0] == arr1.arr[0]);\n CHECK(arr.arr[1] == arr1.arr[1]);\n\n std_array_t arr2{};\n iguana::from_json(arr2, std::begin(str), std::end(str));\n CHECK(arr.arr[0] == arr2.arr[0]);\n CHECK(arr.arr[1] == arr2.arr[1]);\n\n vector_t vec;\n iguana::from_json(vec, std::begin(str), std::end(str));\n CHECK(vec.arr.size() == arr2.arr.size());\n CHECK(arr2.arr[0] == vec.arr[0]);\n CHECK(arr2.arr[1] == vec.arr[1]);\n}\n\nTEST_CASE(\"test bool, null, char, int, float\") {\n {\n optional_t p{};\n std::string str = R\"({\"p\": false})\";\n iguana::from_json(p, std::begin(str), std::end(str));\n CHECK(p.p.has_value());\n CHECK(*p.p == false);\n\n std::string str1 = R\"({\"p\": null})\";\n optional_t p1{};\n iguana::from_json(p1, std::begin(str1), std::end(str1));\n CHECK(!p1.p.has_value());\n }\n {\n char_t p{};\n std::string str = R\"({\"ch\": \"t\"})\";\n iguana::from_json(p, std::begin(str), std::end(str));\n CHECK(p.ch == 't');\n }\n\n {\n bool_t p{};\n std::string str = R\"({\"ok\": true})\";\n iguana::from_json(p, std::begin(str), std::end(str));\n CHECK(p.ok == true);\n }\n\n {\n point_t p{};\n std::string str = R\"({\"x\" : 1, \"y\" : 2})\";\n iguana::from_json(p, std::begin(str), std::end(str));\n CHECK(p.x == 1);\n CHECK(p.y == double(2));\n }\n}\n\nTEST_CASE(\"test vector\") {\n vector_t arr{{1, 2}};\n iguana::string_stream ss;\n iguana::json::to_json(ss, arr);\n\n std::string str = ss.str();\n vector_t p{};\n iguana::from_json(p, std::begin(str), std::end(str));\n CHECK(arr.arr == p.arr);\n}\n\nTEST_CASE(\"check some types\") {\n using value_type = std::variant<int point_t::*, double point_t::*>;\n constexpr auto map = iguana::get_iguana_struct_map<point_t>();\n static_assert(map.size() == 2);\n static_assert(map.at(\"x\") ==\n value_type{std::in_place_index_t<0>{}, &point_t::x});\n static_assert(map.at(\"y\") ==\n value_type{std::in_place_index_t<1>{}, &point_t::y});\n}\n\n\/\/ doctest comments\n\/\/ 'function' : must be 'attribute' - see issue #182\nDOCTEST_MSVC_SUPPRESS_WARNING_WITH_PUSH(4007)\nint main(int argc, char **argv) { return doctest::Context(argc, argv).run(); }\nDOCTEST_MSVC_SUPPRESS_WARNING_POP<|endoftext|>"} {"text":"<commit_before>\n\/*\n * Copyright (C) 2010, Victor Semionov\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND\n * CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES,\n * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\n * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS\n * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,\n * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE\n * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH\n * DAMAGE.\n *\/\n\n#include <climits>\n\n#include <string>\n#include <vector>\n#include <set>\n#include <ostream>\n#include <iostream>\n\n#include \"Poco\/Util\/ServerApplication.h\"\n#include \"Poco\/URI.h\"\n#include \"Poco\/File.h\"\n#include \"Poco\/DirectoryIterator.h\"\n#include \"Poco\/NumberFormatter.h\"\n\n#include \"IndigoRequestHandler.h\"\n#include \"IndigoConfiguration.h\"\n\nusing namespace std;\n\nusing namespace Poco;\nusing namespace Poco::Util;\nusing namespace Poco::Net;\n\nPOCO_DECLARE_EXCEPTION(, ShareNotFoundException, ApplicationException)\nPOCO_IMPLEMENT_EXCEPTION(ShareNotFoundException, ApplicationException, \"ShareNotFoundException\")\n\nIndigoRequestHandler::IndigoRequestHandler()\n{\n}\n\nvoid IndigoRequestHandler::handleRequest(HTTPServerRequest &request, HTTPServerResponse &response)\n{\n\tlogRequest(request);\n\n\tconst string &method = request.getMethod();\n\n\tif (method != HTTPRequest::HTTP_GET)\n\t{\n\t\tsendMethodNotAllowed(response);\n\t\treturn;\n\t}\n\n\tURI uri;\n\ttry\n\t{\n\t\turi = request.getURI();\n\t}\n\tcatch (SyntaxException &se)\n\t{\n\t\tsendBadRequest(response);\n\t\treturn;\n\t}\n\n\tPath uriPath(uri.getPath(), Path::PATH_UNIX);\n\n\tif (!uriPath.isAbsolute())\n\t{\n\t\tsendBadRequest(response);\n\t\treturn;\n\t}\n\n\tconst IndigoConfiguration &configuration = IndigoConfiguration::get();\n\n\ttry\n\t{\n\t\tif (uriPath.isDirectory() && uriPath.depth() == 0)\n\t\t{\n\t\t\tif (configuration.virtualRoot())\n\t\t\t{\n\t\t\t\tsendVirtualIndex(response);\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\n\t\tconst Path &fsPath = resolveFSPath(uriPath);\n\t\tconst string &target = fsPath.toString();\n\n\t\tFile f(target);\n\t\tif (f.isDirectory())\n\t\t{\n\t\t\tif (uriPath.isDirectory())\n\t\t\t{\n\t\t\t\tsendDirectoryIndex(response, target, uriPath.toString(Path::PATH_UNIX));\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tPath uriDirPath = uriPath;\n\t\t\t\turiDirPath.makeDirectory();\n\t\t\t\tredirectToDirectory(response, uriDirPath.toString(Path::PATH_UNIX), false);\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tsendFile(response, target);\n\t\t}\n\t}\n\tcatch (ShareNotFoundException &snfe)\n\t{\n\t\tsendNotFound(response);\n\t}\n\tcatch (FileNotFoundException &fnfe)\n\t{\n\t\tsendNotFound(response);\n\t}\n\tcatch (FileAccessDeniedException &fade)\n\t{\n\t\tsendForbidden(response);\n\t}\n\tcatch (FileException &fe)\n\t{\n\t\tsendInternalServerError(response);\n\t}\n\tcatch (PathSyntaxException &pse)\n\t{\n\t\tsendNotImplemented(response);\n\t}\n\tcatch (...)\n\t{\n\t\tsendInternalServerError(response);\n\t}\n}\n\nPath IndigoRequestHandler::resolveFSPath(const Path &uriPath)\n{\n\tconst IndigoConfiguration &configuration = IndigoConfiguration::get();\n\n\tconst string &shareName = uriPath[0];\n\tstring base = configuration.getSharePath(shareName);\n\tbool share = true;\n\n\tif (base.empty())\n\t{\n\t\tbase = configuration.getRoot();\n\t\tif (base.empty())\n\t\t\tthrow ShareNotFoundException();\n\n\t\tshare = false;\n\t}\n\n\tPath fsPath(base);\n\n\tif (share)\n\t{\n\t\tfsPath.makeDirectory();\n\n\t\tconst int d = uriPath.depth();\n\t\tfor (int i = 1; i <= d; i++)\n\t\t\tfsPath.pushDirectory(uriPath[i]);\n\t}\n\telse\n\t{\n\t\tfsPath.append(uriPath);\n\t}\n\n\tfsPath.makeFile();\n\treturn fsPath;\n}\n\nvoid IndigoRequestHandler::sendFile(HTTPServerResponse &response, const string &path)\n{\n\tconst string &ext = Path(path).getExtension();\n\tconst string &mediaType = IndigoConfiguration::get().getMimeType(ext);\n\tresponse.sendFile(path, mediaType);\n}\n\nvoid IndigoRequestHandler::sendDirectoryListing(HTTPServerResponse &response, const string &dirURI, const vector<string> &entries)\n{\n\tbool root = (dirURI == \"\/\");\n\n\tresponse.setContentType(\"text\/html\");\n\tresponse.setContentLength(HTTPResponse::UNKNOWN_CONTENT_LENGTH);\n\tresponse.setChunkedTransferEncoding(true);\n\n\tostream &out = response.send();\n\n\tout << \"<html>\" << endl;\n\tout << \"<head>\" << endl;\n\tout << \"<title>\";\n\tout << \"Index of \" << dirURI;\n\tout << \"<\/title>\" << endl;\n\tout << \"<\/head>\" << endl;\n\tout << \"<body>\" << endl;\n\tout << \"<h1>\";\n\tout << \"Index of \" << dirURI;\n\tout << \"<\/h1>\" << endl;\n\n\tif (!root)\n\t{\n\t\tout << \"<a href=\\\"..\/\\\"><Parent Directory><\/a><br>\" << endl;\n\t}\n\n\tconst int l = entries.size();\n\tfor (int i = 0; i < l; i++)\n\t{\n\t\tout << \"<a href=\\\"\" << entries[i] << \"\\\">\" << entries[i] << \"<\/a>\" << \"<br>\" << endl;\n\t}\n\n\tout << \"<\/body>\" << endl;\n\tout << \"<\/html>\" << endl;\n}\n\nstring IndigoRequestHandler::findVirtualIndex()\n{\n\tconst IndigoConfiguration &configuration = IndigoConfiguration::get();\n\n\tconst set<string> indexes = configuration.getIndexes();\n\n\tset<string>::const_iterator it;\n\tset<string>::const_iterator end = indexes.end();\n\tfor (it = indexes.begin(); it != end; ++it)\n\t{\n\t\ttry\n\t\t{\n\t\t\tconst Path &index = resolveFSPath(Path(\"\/\" + *it, Path::PATH_UNIX));\n\t\t\tFile f(index);\n\t\t\tif (f.isFile())\n\t\t\t{\n\t\t\t\treturn index.toString();\n\t\t\t}\n\t\t}\n\t\tcatch (ShareNotFoundException &snfe)\n\t\t{\n\t\t}\n\t\tcatch (FileException &fe)\n\t\t{\n\t\t}\n\t\tcatch (PathSyntaxException &pse)\n\t\t{\n\t\t}\n\t}\n\n\treturn \"\";\n}\n\nvoid IndigoRequestHandler::sendVirtualIndex(HTTPServerResponse &response)\n{\n\tconst IndigoConfiguration &configuration = IndigoConfiguration::get();\n\n\tconst string &index = findVirtualIndex();\n\tif (!index.empty())\n\t{\n\t\tsendFile(response, index);\n\t\treturn;\n\t}\n\n\tif (!configuration.getAutoIndex())\n\t\tthrow ShareNotFoundException();\n\n\tconst set<string> &shares = configuration.getShares();\n\tvector<string> entries;\n\n\tset<string>::const_iterator it;\n\tconst set<string>::const_iterator &end = shares.end();\n\tfor (it = shares.begin(); it != end; ++it)\n\t{\n\t\tconst string &shareName = *it;\n\t\ttry\n\t\t{\n\t\t\tconst Path &fsPath = resolveFSPath(Path(\"\/\" + shareName, Path::PATH_UNIX));\n\t\t\tFile f(fsPath);\n\n\t\t\tif (!f.isHidden())\n\t\t\t{\n\t\t\t\tstring entry = shareName;\n\t\t\t\tif (f.isDirectory())\n\t\t\t\t\tentry += '\/';\n\n\t\t\t\tentries.push_back(entry);\n\t\t\t}\n\t\t}\n\t\tcatch (ShareNotFoundException &snfe)\n\t\t{\n\t\t}\n\t\tcatch (FileException &fe)\n\t\t{\n\t\t}\n\t\tcatch (PathSyntaxException &pse)\n\t\t{\n\t\t}\n\t}\n\n\tsendDirectoryListing(response, \"\/\", entries);\n}\n\nstring IndigoRequestHandler::findDirectoryIndex(const string &base)\n{\n\tconst IndigoConfiguration &configuration = IndigoConfiguration::get();\n\n\tconst set<string> indexes = configuration.getIndexes(true);\n\n\tset<string>::const_iterator it;\n\tset<string>::const_iterator end = indexes.end();\n\tfor (it = indexes.begin(); it != end; ++it)\n\t{\n\t\ttry\n\t\t{\n\t\t\tstring index = base;\n\t\t\tif (index[index.length() - 1] != Path::separator())\n\t\t\t\tindex += Path::separator();\n\t\t\tindex += *it;\n\n\t\t\tFile f(index);\n\t\t\tif (f.isFile())\n\t\t\t{\n\t\t\t\treturn index;\n\t\t\t}\n\t\t}\n\t\tcatch (FileException &fe)\n\t\t{\n\t\t}\n\t\tcatch (PathSyntaxException &pse)\n\t\t{\n\t\t}\n\t}\n\n\treturn \"\";\n}\n\nvoid IndigoRequestHandler::sendDirectoryIndex(HTTPServerResponse &response, const string &path, const string &dirURI)\n{\n\tconst IndigoConfiguration &configuration = IndigoConfiguration::get();\n\n\tconst string &index = findDirectoryIndex(path);\n\tif (!index.empty())\n\t{\n\t\tsendFile(response, index);\n\t\treturn;\n\t}\n\n\tif (!configuration.getAutoIndex())\n\t\tthrow FileNotFoundException();\n\n\tvector<string> entries;\n\n\tDirectoryIterator it(path);\n\tDirectoryIterator end;\n\twhile (it != end)\n\t{\n\t\ttry\n\t\t{\n\t\t\tif (!it->isHidden())\n\t\t\t{\n\t\t\t\tstring entry = it.name();\n\t\t\t\tif (it->isDirectory())\n\t\t\t\t\tentry += '\/';\n\n\t\t\t\tentries.push_back(entry);\n\t\t\t}\n\t\t}\n\t\tcatch (FileException &fe)\n\t\t{\n\t\t}\n\t\tcatch (PathSyntaxException &pse)\n\t\t{\n\t\t}\n\n\t\t++it;\n\t}\n\n\tsendDirectoryListing(response, dirURI, entries);\n}\n\nvoid IndigoRequestHandler::redirectToDirectory(HTTPServerResponse &response, const string &dirURI, bool permanent)\n{\n\tif (!permanent)\n\t{\n\t\tresponse.redirect(dirURI);\n\t}\n\telse\n\t{\n\t\tresponse.setStatusAndReason(HTTPResponse::HTTP_MOVED_PERMANENTLY);\n\t\tresponse.setContentLength(0);\n\t\tresponse.setChunkedTransferEncoding(false);\n\t\tresponse.set(\"Location\", dirURI);\n\t\tresponse.send();\n\t}\n}\n\nvoid IndigoRequestHandler::logRequest(const HTTPServerRequest &request)\n{\n\tconst ServerApplication &app = dynamic_cast<ServerApplication &>(Application::instance());\n\tif (app.isInteractive())\n\t{\n\t\tconst string &method = request.getMethod();\n\t\tconst string &uri = request.getURI();\n\t\tconst string &host = request.clientAddress().host().toString();\n\n\t\tstring logString = host + \" - \" + method + \" \" + uri;\n\n\t\tapp.logger().information(logString);\n\t}\n}\n\nvoid IndigoRequestHandler::sendError(HTTPServerResponse &response, int code)\n{\n\tif (response.sent())\n\t\treturn;\n\n\tresponse.setStatusAndReason(HTTPResponse::HTTPStatus(code));\n\tresponse.setChunkedTransferEncoding(true);\n\tresponse.setContentType(\"text\/html\");\n\n\tconst string &reason = response.getReason();\n\n\tostream &out = response.send();\n\tout << \"<html>\";\n\tout << \"<head><title>\" + NumberFormatter::format(code) + \" \" + reason + \"<\/title><\/head>\";\n\tout << \"<body><h1>\" + reason + \"<\/h1><\/body>\";\n\tout << \"<\/html>\";\n}\n\nvoid IndigoRequestHandler::sendMethodNotAllowed(HTTPServerResponse &response)\n{\n\tsendError(response, HTTPResponse::HTTP_METHOD_NOT_ALLOWED);\n}\n\nvoid IndigoRequestHandler::sendRequestURITooLong(HTTPServerResponse &response)\n{\n\tsendError(response, HTTPResponse::HTTP_REQUESTURITOOLONG);\n}\n\nvoid IndigoRequestHandler::sendBadRequest(HTTPServerResponse &response)\n{\n\tsendError(response, HTTPResponse::HTTP_BAD_REQUEST);\n}\n\nvoid IndigoRequestHandler::sendNotImplemented(HTTPServerResponse &response)\n{\n\tsendError(response, HTTPResponse::HTTP_NOT_IMPLEMENTED);\n}\n\nvoid IndigoRequestHandler::sendNotFound(HTTPServerResponse &response)\n{\n\tsendError(response, HTTPResponse::HTTP_NOT_FOUND);\n}\n\nvoid IndigoRequestHandler::sendForbidden(HTTPServerResponse &response)\n{\n\tsendError(response, HTTPResponse::HTTP_FORBIDDEN);\n}\n\nvoid IndigoRequestHandler::sendInternalServerError(HTTPServerResponse &response)\n{\n\tsendError(response, HTTPResponse::HTTP_INTERNAL_SERVER_ERROR);\n}\n<commit_msg>Refactoring.<commit_after>\n\/*\n * Copyright (C) 2010, Victor Semionov\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND\n * CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES,\n * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\n * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS\n * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,\n * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE\n * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH\n * DAMAGE.\n *\/\n\n#include <climits>\n\n#include <string>\n#include <vector>\n#include <set>\n#include <ostream>\n#include <iostream>\n\n#include \"Poco\/Util\/ServerApplication.h\"\n#include \"Poco\/URI.h\"\n#include \"Poco\/File.h\"\n#include \"Poco\/DirectoryIterator.h\"\n#include \"Poco\/NumberFormatter.h\"\n\n#include \"IndigoRequestHandler.h\"\n#include \"IndigoConfiguration.h\"\n\nusing namespace std;\n\nusing namespace Poco;\nusing namespace Poco::Util;\nusing namespace Poco::Net;\n\nPOCO_DECLARE_EXCEPTION(, ShareNotFoundException, ApplicationException)\nPOCO_IMPLEMENT_EXCEPTION(ShareNotFoundException, ApplicationException, \"ShareNotFoundException\")\n\nIndigoRequestHandler::IndigoRequestHandler()\n{\n}\n\nvoid IndigoRequestHandler::handleRequest(HTTPServerRequest &request, HTTPServerResponse &response)\n{\n\tlogRequest(request);\n\n\tconst string &method = request.getMethod();\n\n\tif (method != HTTPRequest::HTTP_GET)\n\t{\n\t\tsendMethodNotAllowed(response);\n\t\treturn;\n\t}\n\n\tURI uri;\n\ttry\n\t{\n\t\turi = request.getURI();\n\t}\n\tcatch (SyntaxException &se)\n\t{\n\t\tsendBadRequest(response);\n\t\treturn;\n\t}\n\n\tPath uriPath(uri.getPath(), Path::PATH_UNIX);\n\n\tif (!uriPath.isAbsolute())\n\t{\n\t\tsendBadRequest(response);\n\t\treturn;\n\t}\n\n\tconst IndigoConfiguration &configuration = IndigoConfiguration::get();\n\n\ttry\n\t{\n\t\tif (uriPath.isDirectory() && uriPath.depth() == 0)\n\t\t{\n\t\t\tif (configuration.virtualRoot())\n\t\t\t{\n\t\t\t\tsendVirtualIndex(response);\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\n\t\tconst Path &fsPath = resolveFSPath(uriPath);\n\t\tconst string &target = fsPath.toString();\n\n\t\tFile f(target);\n\t\tif (f.isDirectory())\n\t\t{\n\t\t\tif (uriPath.isDirectory())\n\t\t\t{\n\t\t\t\tsendDirectoryIndex(response, target, uriPath.toString(Path::PATH_UNIX));\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tPath uriDirPath = uriPath;\n\t\t\t\turiDirPath.makeDirectory();\n\t\t\t\tredirectToDirectory(response, uriDirPath.toString(Path::PATH_UNIX), false);\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tsendFile(response, target);\n\t\t}\n\t}\n\tcatch (ShareNotFoundException &snfe)\n\t{\n\t\tsendNotFound(response);\n\t}\n\tcatch (FileNotFoundException &fnfe)\n\t{\n\t\tsendNotFound(response);\n\t}\n\tcatch (FileAccessDeniedException &fade)\n\t{\n\t\tsendForbidden(response);\n\t}\n\tcatch (FileException &fe)\n\t{\n\t\tsendInternalServerError(response);\n\t}\n\tcatch (PathSyntaxException &pse)\n\t{\n\t\tsendNotImplemented(response);\n\t}\n\tcatch (...)\n\t{\n\t\tsendInternalServerError(response);\n\t}\n}\n\nPath IndigoRequestHandler::resolveFSPath(const Path &uriPath)\n{\n\tconst IndigoConfiguration &configuration = IndigoConfiguration::get();\n\n\tconst string &shareName = uriPath[0];\n\tstring base = configuration.getSharePath(shareName);\n\tbool share = true;\n\n\tif (base.empty())\n\t{\n\t\tbase = configuration.getRoot();\n\t\tif (base.empty())\n\t\t\tthrow ShareNotFoundException();\n\n\t\tshare = false;\n\t}\n\n\tPath fsPath(base);\n\n\tif (share)\n\t{\n\t\tfsPath.makeDirectory();\n\n\t\tconst int d = uriPath.depth();\n\t\tfor (int i = 1; i <= d; i++)\n\t\t\tfsPath.pushDirectory(uriPath[i]);\n\t}\n\telse\n\t{\n\t\tfsPath.append(uriPath);\n\t}\n\n\tfsPath.makeFile();\n\treturn fsPath;\n}\n\nvoid IndigoRequestHandler::sendFile(HTTPServerResponse &response, const string &path)\n{\n\tconst string &ext = Path(path).getExtension();\n\tconst string &mediaType = IndigoConfiguration::get().getMimeType(ext);\n\tresponse.sendFile(path, mediaType);\n}\n\nvoid IndigoRequestHandler::sendDirectoryListing(HTTPServerResponse &response, const string &dirURI, const vector<string> &entries)\n{\n\tbool root = (dirURI == \"\/\");\n\n\tresponse.setContentType(\"text\/html\");\n\tresponse.setContentLength(HTTPResponse::UNKNOWN_CONTENT_LENGTH);\n\tresponse.setChunkedTransferEncoding(true);\n\n\tostream &out = response.send();\n\n\tout << \"<html>\" << endl;\n\tout << \"<head>\" << endl;\n\tout << \"<title>\";\n\tout << \"Index of \" << dirURI;\n\tout << \"<\/title>\" << endl;\n\tout << \"<\/head>\" << endl;\n\tout << \"<body>\" << endl;\n\tout << \"<h1>\";\n\tout << \"Index of \" << dirURI;\n\tout << \"<\/h1>\" << endl;\n\n\tif (!root)\n\t{\n\t\tout << \"<a href=\\\"..\/\\\"><Parent Directory><\/a><br>\" << endl;\n\t}\n\n\tconst int l = entries.size();\n\tfor (int i = 0; i < l; i++)\n\t{\n\t\tout << \"<a href=\\\"\" << entries[i] << \"\\\">\" << entries[i] << \"<\/a>\" << \"<br>\" << endl;\n\t}\n\n\tout << \"<\/body>\" << endl;\n\tout << \"<\/html>\" << endl;\n}\n\nstring IndigoRequestHandler::findVirtualIndex()\n{\n\tconst IndigoConfiguration &configuration = IndigoConfiguration::get();\n\n\tconst set<string> indexes = configuration.getIndexes();\n\n\tset<string>::const_iterator it;\n\tset<string>::const_iterator end = indexes.end();\n\tfor (it = indexes.begin(); it != end; ++it)\n\t{\n\t\ttry\n\t\t{\n\t\t\tconst Path indexURI = Path('\/' + *it, Path::PATH_UNIX);\n\t\t\tconst Path &index = resolveFSPath(indexURI);\n\t\t\tFile f(index);\n\t\t\tif (f.isFile())\n\t\t\t{\n\t\t\t\treturn index.toString();\n\t\t\t}\n\t\t}\n\t\tcatch (ShareNotFoundException &snfe)\n\t\t{\n\t\t}\n\t\tcatch (FileException &fe)\n\t\t{\n\t\t}\n\t\tcatch (PathSyntaxException &pse)\n\t\t{\n\t\t}\n\t}\n\n\treturn \"\";\n}\n\nvoid IndigoRequestHandler::sendVirtualIndex(HTTPServerResponse &response)\n{\n\tconst IndigoConfiguration &configuration = IndigoConfiguration::get();\n\n\tconst string &index = findVirtualIndex();\n\tif (!index.empty())\n\t{\n\t\tsendFile(response, index);\n\t\treturn;\n\t}\n\n\tif (!configuration.getAutoIndex())\n\t\tthrow ShareNotFoundException();\n\n\tconst set<string> &shares = configuration.getShares();\n\tvector<string> entries;\n\n\tset<string>::const_iterator it;\n\tconst set<string>::const_iterator &end = shares.end();\n\tfor (it = shares.begin(); it != end; ++it)\n\t{\n\t\tconst string &shareName = *it;\n\t\ttry\n\t\t{\n\t\t\tconst Path shareURI = Path('\/' + shareName, Path::PATH_UNIX);\n\t\t\tconst Path &fsPath = resolveFSPath(shareURI);\n\t\t\tFile f(fsPath);\n\n\t\t\tif (!f.isHidden())\n\t\t\t{\n\t\t\t\tstring entry = shareName;\n\t\t\t\tif (f.isDirectory())\n\t\t\t\t\tentry += '\/';\n\n\t\t\t\tentries.push_back(entry);\n\t\t\t}\n\t\t}\n\t\tcatch (ShareNotFoundException &snfe)\n\t\t{\n\t\t}\n\t\tcatch (FileException &fe)\n\t\t{\n\t\t}\n\t\tcatch (PathSyntaxException &pse)\n\t\t{\n\t\t}\n\t}\n\n\tsendDirectoryListing(response, \"\/\", entries);\n}\n\nstring IndigoRequestHandler::findDirectoryIndex(const string &base)\n{\n\tconst IndigoConfiguration &configuration = IndigoConfiguration::get();\n\n\tconst set<string> indexes = configuration.getIndexes(true);\n\n\tset<string>::const_iterator it;\n\tset<string>::const_iterator end = indexes.end();\n\tfor (it = indexes.begin(); it != end; ++it)\n\t{\n\t\ttry\n\t\t{\n\t\t\tstring index = base;\n\t\t\tif (index[index.length() - 1] != Path::separator())\n\t\t\t\tindex += Path::separator();\n\t\t\tindex += *it;\n\n\t\t\tFile f(index);\n\t\t\tif (f.isFile())\n\t\t\t{\n\t\t\t\treturn index;\n\t\t\t}\n\t\t}\n\t\tcatch (FileException &fe)\n\t\t{\n\t\t}\n\t\tcatch (PathSyntaxException &pse)\n\t\t{\n\t\t}\n\t}\n\n\treturn \"\";\n}\n\nvoid IndigoRequestHandler::sendDirectoryIndex(HTTPServerResponse &response, const string &path, const string &dirURI)\n{\n\tconst IndigoConfiguration &configuration = IndigoConfiguration::get();\n\n\tconst string &index = findDirectoryIndex(path);\n\tif (!index.empty())\n\t{\n\t\tsendFile(response, index);\n\t\treturn;\n\t}\n\n\tif (!configuration.getAutoIndex())\n\t\tthrow FileNotFoundException();\n\n\tvector<string> entries;\n\n\tDirectoryIterator it(path);\n\tDirectoryIterator end;\n\twhile (it != end)\n\t{\n\t\ttry\n\t\t{\n\t\t\tif (!it->isHidden())\n\t\t\t{\n\t\t\t\tstring entry = it.name();\n\t\t\t\tif (it->isDirectory())\n\t\t\t\t\tentry += '\/';\n\n\t\t\t\tentries.push_back(entry);\n\t\t\t}\n\t\t}\n\t\tcatch (FileException &fe)\n\t\t{\n\t\t}\n\t\tcatch (PathSyntaxException &pse)\n\t\t{\n\t\t}\n\n\t\t++it;\n\t}\n\n\tsendDirectoryListing(response, dirURI, entries);\n}\n\nvoid IndigoRequestHandler::redirectToDirectory(HTTPServerResponse &response, const string &dirURI, bool permanent)\n{\n\tif (!permanent)\n\t{\n\t\tresponse.redirect(dirURI);\n\t}\n\telse\n\t{\n\t\tresponse.setStatusAndReason(HTTPResponse::HTTP_MOVED_PERMANENTLY);\n\t\tresponse.setContentLength(0);\n\t\tresponse.setChunkedTransferEncoding(false);\n\t\tresponse.set(\"Location\", dirURI);\n\t\tresponse.send();\n\t}\n}\n\nvoid IndigoRequestHandler::logRequest(const HTTPServerRequest &request)\n{\n\tconst ServerApplication &app = dynamic_cast<ServerApplication &>(Application::instance());\n\tif (app.isInteractive())\n\t{\n\t\tconst string &method = request.getMethod();\n\t\tconst string &uri = request.getURI();\n\t\tconst string &host = request.clientAddress().host().toString();\n\n\t\tstring logString = host + \" - \" + method + \" \" + uri;\n\n\t\tapp.logger().information(logString);\n\t}\n}\n\nvoid IndigoRequestHandler::sendError(HTTPServerResponse &response, int code)\n{\n\tif (response.sent())\n\t\treturn;\n\n\tresponse.setStatusAndReason(HTTPResponse::HTTPStatus(code));\n\tresponse.setChunkedTransferEncoding(true);\n\tresponse.setContentType(\"text\/html\");\n\n\tconst string &reason = response.getReason();\n\n\tostream &out = response.send();\n\tout << \"<html>\";\n\tout << \"<head><title>\" + NumberFormatter::format(code) + \" \" + reason + \"<\/title><\/head>\";\n\tout << \"<body><h1>\" + reason + \"<\/h1><\/body>\";\n\tout << \"<\/html>\";\n}\n\nvoid IndigoRequestHandler::sendMethodNotAllowed(HTTPServerResponse &response)\n{\n\tsendError(response, HTTPResponse::HTTP_METHOD_NOT_ALLOWED);\n}\n\nvoid IndigoRequestHandler::sendRequestURITooLong(HTTPServerResponse &response)\n{\n\tsendError(response, HTTPResponse::HTTP_REQUESTURITOOLONG);\n}\n\nvoid IndigoRequestHandler::sendBadRequest(HTTPServerResponse &response)\n{\n\tsendError(response, HTTPResponse::HTTP_BAD_REQUEST);\n}\n\nvoid IndigoRequestHandler::sendNotImplemented(HTTPServerResponse &response)\n{\n\tsendError(response, HTTPResponse::HTTP_NOT_IMPLEMENTED);\n}\n\nvoid IndigoRequestHandler::sendNotFound(HTTPServerResponse &response)\n{\n\tsendError(response, HTTPResponse::HTTP_NOT_FOUND);\n}\n\nvoid IndigoRequestHandler::sendForbidden(HTTPServerResponse &response)\n{\n\tsendError(response, HTTPResponse::HTTP_FORBIDDEN);\n}\n\nvoid IndigoRequestHandler::sendInternalServerError(HTTPServerResponse &response)\n{\n\tsendError(response, HTTPResponse::HTTP_INTERNAL_SERVER_ERROR);\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ This is actually a C++ file - it's got a .c extension to make make happy\n\n\/\/ This is actually DES-X, not triple DES.\n\n#include <iostream> \/\/ for couts for debugging\n\n#include \"modes.h\"\n#include \"des.h\"\n#include \"filters.h\"\n\n\/\/extern \"C\"\n\/\/{\n#include \"Python.h\"\n\/\/}\n\nUSING_NAMESPACE(CryptoPP)\n\nPyObject *TripleDESCBCError;\n\nclass MemoryException : public std::exception\n{\npublic:\n\texplicit MemoryException() {}\n\tvirtual ~MemoryException() throw() {}\n};\n\n#define xdelete(p) delete (p); p = NULL\n#define xdeletear(p) delete[] (p); p = NULL\n\ntypedef struct\n{\n\tPyObject_HEAD\n\tbyte *key;\n} tripledescbc;\n\nstatic PyObject *tripledescbc_new(tripledescbc *self, PyObject *args);\n\nstatic void tripledescbc_delete(tripledescbc *self);\n\nstatic PyObject *tripledescbc_encrypt(tripledescbc *self, PyObject *args);\n\nstatic PyObject *tripledescbc_decrypt(tripledescbc *self, PyObject *args);\n\nstatic PyObject *tripledescbc_getattr(tripledescbc *self, char* name);\n\nstatichere PyTypeObject tripledescbc_type = {\n PyObject_HEAD_INIT(&PyType_Type)\n 0, \/*ob_size*\/\n \"DES-XEX3CBC\", \/*tp_name*\/\n sizeof(tripledescbc), \/*tp_size*\/\n 0, \/*tp_itemsize*\/\n \/* methods *\/\n (destructor)tripledescbc_delete, \/*tp_dealloc*\/\n 0, \/*tp_print*\/\n (getattrfunc)tripledescbc_getattr, \/*tp_getattr*\/\n 0, \/*tp_setattr*\/\n 0, \/*tp_compare*\/\n 0, \/*tp_repr*\/\n 0, \/*tp_as_number*\/\n 0, \/*tp_as_sequence*\/\n 0, \/*tp_as_mapping*\/\n 0, \/*tp_hash*\/\n 0, \/*tp_call*\/\n 0, \/*tp_str*\/\n 0, \/*tp_getattro*\/\n 0, \/*tp_setattro*\/\n 0, \/*tp_as_buffer*\/\n 0, \/*tp_xxx4*\/\n 0, \/*tp_doc*\/\n};\n\nstatic PyMethodDef tripledescbc_methods[] = {\n {\"encrypt\", (PyCFunction)tripledescbc_encrypt, METH_VARARGS, \n \"Returns an encrypted string.\\n\"\n \"Accepts an IV string of length 8 and a plaintext string.\\n\"\n \"Encrypts in CBC mode with ciphertext stealing.\\n\"\n \"Always returns a ciphertext of the exact same length as the plaintext.\"\n }, \n {\"decrypt\", (PyCFunction)tripledescbc_decrypt, METH_VARARGS, \n \"Returns a decrypted string.\\n\"\n \"Accepts an IV string of length 8 and a ciphertext string.\\n\"\n \"Decrypts in CBC mode with ciphertext stealing.\\n\"\n \"Always returns a plaintext of the exact same length as the ciphertext.\"\n }, \n {NULL, NULL}\t\/* sentinel *\/\n};\n\nstatic PyObject *tripledescbc_getattr(tripledescbc *self, char* name)\n{\n\treturn Py_FindMethod(tripledescbc_methods, (PyObject *)self, name);\n}\n\nstatic void tripledescbc_delete(tripledescbc *self) {\n\tif(self != NULL) {\n\t\txdeletear(self->key);\n\t\tPyMem_DEL(self);\n\t}\n}\n\nstatic PyObject *tripledescbc_new(tripledescbc *self, PyObject *args) {\n\ttripledescbc *newself = NULL;\n\ttry {\n\t\tbyte *key;\n\t\tint keylength;\n\t\tif(!PyArg_ParseTuple(args, \"s#\", &key, &keylength)) {\n\t\t\tthrow Exception(Exception::INVALID_ARGUMENT, \"wrong type of parameters passed in from Python\");\n\t\t}\n\t\tif(keylength != 24) {\n\t\t\tthrow Exception(Exception::INVALID_ARGUMENT, \"triple DES key length must be 24\");\n\t\t}\n\t\tif(!(newself = PyObject_NEW(tripledescbc, &tripledescbc_type))) {\n\t\t throw MemoryException();\n\t\t}\n\t\tbyte *keycopy = new byte[24];\n\t\tmemcpy(keycopy, key, 24);\n\t\t\/\/\t\tprintf(\"in tripledescbc_new(); keycopy: %p, key: %p\\n\", keycopy, key);\n\t\tnewself->key = keycopy;\n\t\treturn (PyObject *)newself;\n\t}\n\tcatch(CryptoPP::Exception &e) {\n\t\ttripledescbc_delete(newself);\n\t\tPyErr_SetString(TripleDESCBCError, e.what());\n\t\treturn NULL;\n\t}\n\tcatch(MemoryException &e)\n\t{\n\t\ttripledescbc_delete(newself);\n\t\tPyErr_SetString(PyExc_MemoryError, \"Can't allocate memory to do set up keys for en\/decryption\");\n\t\treturn NULL;\n\t}\n}\n\n#define _MIN_UNSAFE(x, y) ((x)<(y)?(x):(y))\nstatic PyObject *tripledescbc_encrypt(tripledescbc *self, PyObject *args) {\n\t\/\/\tstd::cout << \"hello enc 0\" << std::endl; std::cout.flush();\n\tPyObject *result = NULL;\n\tbyte *ciphertext = NULL;\n\ttry {\n\t\tbyte *iv;\n\t\tunsigned int ivlength;\n\t\tbyte *text;\n\t\tunsigned int textlength;\n\t\tif(!PyArg_ParseTuple(args, \"s#s#\", &iv, &ivlength, &text, &textlength)) {\n\t\t\tthrow Exception(Exception::INVALID_ARGUMENT, \"wrong type of parameters passed in from Python\");\n\t\t}\n\t\tif(ivlength != 8) {\n\t\t\tthrow Exception(Exception::INVALID_ARGUMENT, \"IV length must be 8\");\n\t\t}\n\t\t\/\/\t\tstd::cout << \"hello enc 0.7\" << std::endl; std::cout.flush();\n\t\t\/\/\t\tstd::cout << \"hello enc 0.7.1, self: \" << self << std::endl; std::cout.flush();\n\t\t\/\/\t\tstd::cout << \"hello enc 0.7.2, self->key: \";\n\t\t\/\/\t\tstd::cout << self->key;\n\t\t\/\/\t\tstd::cout << std::endl;\n\t\t\/\/\t\tstd::cout.flush();\n\t\t\/\/\tstd::cout << \"hello enc 0.7.3, iv: \" << iv << std::endl; std::cout.flush();\n\t\tCBC_CTS_Mode<DES_XEX3>::Encryption encryption(self->key, 24, iv);\n\t\t\/\/\t\tstd::cout << \"hello enc 0.8\" << std::endl; std::cout.flush();\n\t\tciphertext = new byte[textlength];\n\t\t\/\/\t\tstd::cout << \"hello enc 0.9\" << std::endl; std::cout.flush();\n\t\tif (ciphertext == NULL) {\n\t\t\tthrow MemoryException();\n\t\t}\n\t\t\/\/\t\tstd::cout << \"hello enc 1\" << std::endl; std::cout.flush();\n\t\tStreamTransformationFilter encryptor(encryption, new ArraySink(ciphertext, textlength));\n\t\t\/\/\t\tstd::cout << \"hello enc 2\" << std::endl; std::cout.flush();\n\t\tencryptor.PutMessageEnd(text, textlength);\n\t\t\/\/\t\tstd::cout << \"hello enc 3\" << std::endl; std::cout.flush();\n\t\tresult = Py_BuildValue(\"s#\", ciphertext, textlength);\n\t\t\/\/\t\tstd::cout << \"hello enc 4\" << std::endl; std::cout.flush();\n\t\tif(result == NULL) {\n\t\t\tthrow MemoryException();\n\t\t}\n\t\t\/\/\t\tstd::cout << \"hello enc 5\" << std::endl; std::cout.flush();\n\t\txdeletear(ciphertext);\n\t\t\/\/\t\tstd::cout << \"hello enc 6\" << std::endl; std::cout.flush();\n\t\treturn result;\n\t}\n\tcatch(CryptoPP::Exception &e) {\n\t\tif(result != NULL) {\n\t\t\tPyMem_DEL(result);\n\t\t}\n\t\txdeletear(ciphertext);\n\t\tPyErr_SetString(TripleDESCBCError, e.what());\n\t\treturn NULL;\n\t}\n\tcatch(MemoryException &e) {\n\t\tif(result != NULL) {\n\t\t\tPyMem_DEL(result);\n\t\t}\n\t\txdeletear(ciphertext);\n\t\tPyErr_SetString(PyExc_MemoryError, \"Can't allocate memory to do encryption\");\n\t\treturn NULL;\n\t}\n\tstd::cout << \"goodbye enc\" << std::endl; std::cout.flush();\n}\n\nstatic PyObject *tripledescbc_decrypt(tripledescbc *self, PyObject *args) {\n\tstd::cout << \"hello dec 0\" << std::endl; std::cout.flush();\n\tPyObject *result = NULL;\n\tbyte *plaintext = NULL;\n\ttry {\n\t\tbyte *iv;\n\t\tunsigned int ivlength;\n\t\tbyte *text;\n\t\tunsigned int textlength;\n\t\tif(!PyArg_ParseTuple(args, \"s#s#\", &iv, &ivlength, &text, &textlength)) {\n\t\t\tthrow Exception(Exception::INVALID_ARGUMENT, \"wrong type of parameters passed in from Python\");\n\t\t}\n\t\tif(ivlength != 8) {\n\t\t\tthrow Exception(Exception::INVALID_ARGUMENT, \"IV length must be 8\");\n\t\t}\n\t\tCBC_CTS_Mode<DES_XEX3>::Decryption decryption(self->key, 24, iv);\n\t\tplaintext = new byte[textlength];\n\t\tif (plaintext == NULL) {\n\t\t\tthrow MemoryException();\n\t\t}\n\t\tStreamTransformationFilter decryptor(decryption, new ArraySink(plaintext, textlength));\n\t\tdecryptor.PutMessageEnd(text, textlength);\n\t\tresult = Py_BuildValue(\"s#\", plaintext, textlength);\n\t\tif(result == NULL) {\n\t\t\tthrow MemoryException();\n\t\t}\n\t\txdeletear(plaintext);\n\t\treturn result;\n\t}\n\tcatch(CryptoPP::Exception &e) {\n\t\tif(result != NULL) {\n\t\t\tPyMem_DEL(result);\n\t\t}\n\t\txdeletear(plaintext);\n\t\tPyErr_SetString(TripleDESCBCError, e.what());\n\t\treturn NULL;\n\t}\n\tcatch(MemoryException &e) {\n\t\tif(result != NULL) {\n\t\t\tPyMem_DEL(result);\n\t\t}\n\t\txdeletear(plaintext);\n\t\tPyErr_SetString(PyExc_MemoryError, \"Can't allocate memory to do decryption\");\n\t\treturn NULL;\n\t}\n}\n\nPyMethodDef tripledescbc_functions[] = {\n {\"new\", (PyCFunction)tripledescbc_new, METH_VARARGS, \n \"Constructs a new tripledescbc.\\n\"\n \"Accepts a key of length 24.\"\n }, \n {NULL, NULL}\t\/* Sentinel *\/\n};\n\nchar* tripledescbc_doc =\n\"Does 3DES encryption and decyption in CBC mode with ciphertext stealing.\\n\"\n\"Always uses a key of length 24 and initialization vectors of length 8.\\n\"\n\"\\n\"\n\"Class methods are - \\n\"\n\"new(key) - constructor\\n\"\n\"\\n\"\n\"Instance methods are - \\n\"\n\"encrypt(iv, plaintext) - encrypt a string\\n\"\n\"decrypt(iv, ciphertext) - decrypt a string\";\n\n\/* Initialize this module. *\/\n\nextern \"C\"\n{\nDL_EXPORT(void)\ninittripledescbc()\n{\n PyObject *m, *d;\n\tm = Py_InitModule3(\"tripledescbc\", tripledescbc_functions, tripledescbc_doc);\n d = PyModule_GetDict(m);\n TripleDESCBCError = PyErr_NewException(\"tripledescbc.Error\", NULL, NULL);\n PyDict_SetItemString(d, \"Error\", TripleDESCBCError);\n}\n}\n\n<commit_msg> * comment out debug printouts in tripledescbc.cpp (already committed to Mnet v0.6)<commit_after>\/\/ This is actually a C++ file - it's got a .c extension to make make happy\n\n\/\/ This is actually DES-X, not triple DES.\n\n#include <iostream> \/\/ for couts for debugging\n\n#include \"modes.h\"\n#include \"des.h\"\n#include \"filters.h\"\n\n\/\/extern \"C\"\n\/\/{\n#include \"Python.h\"\n\/\/}\n\nUSING_NAMESPACE(CryptoPP)\n\nPyObject *TripleDESCBCError;\n\nclass MemoryException : public std::exception\n{\npublic:\n\texplicit MemoryException() {}\n\tvirtual ~MemoryException() throw() {}\n};\n\n#define xdelete(p) delete (p); p = NULL\n#define xdeletear(p) delete[] (p); p = NULL\n\ntypedef struct\n{\n\tPyObject_HEAD\n\tbyte *key;\n} tripledescbc;\n\nstatic PyObject *tripledescbc_new(tripledescbc *self, PyObject *args);\n\nstatic void tripledescbc_delete(tripledescbc *self);\n\nstatic PyObject *tripledescbc_encrypt(tripledescbc *self, PyObject *args);\n\nstatic PyObject *tripledescbc_decrypt(tripledescbc *self, PyObject *args);\n\nstatic PyObject *tripledescbc_getattr(tripledescbc *self, char* name);\n\nstatichere PyTypeObject tripledescbc_type = {\n PyObject_HEAD_INIT(&PyType_Type)\n 0, \/*ob_size*\/\n \"DES-XEX3CBC\", \/*tp_name*\/\n sizeof(tripledescbc), \/*tp_size*\/\n 0, \/*tp_itemsize*\/\n \/* methods *\/\n (destructor)tripledescbc_delete, \/*tp_dealloc*\/\n 0, \/*tp_print*\/\n (getattrfunc)tripledescbc_getattr, \/*tp_getattr*\/\n 0, \/*tp_setattr*\/\n 0, \/*tp_compare*\/\n 0, \/*tp_repr*\/\n 0, \/*tp_as_number*\/\n 0, \/*tp_as_sequence*\/\n 0, \/*tp_as_mapping*\/\n 0, \/*tp_hash*\/\n 0, \/*tp_call*\/\n 0, \/*tp_str*\/\n 0, \/*tp_getattro*\/\n 0, \/*tp_setattro*\/\n 0, \/*tp_as_buffer*\/\n 0, \/*tp_xxx4*\/\n 0, \/*tp_doc*\/\n};\n\nstatic PyMethodDef tripledescbc_methods[] = {\n {\"encrypt\", (PyCFunction)tripledescbc_encrypt, METH_VARARGS, \n \"Returns an encrypted string.\\n\"\n \"Accepts an IV string of length 8 and a plaintext string.\\n\"\n \"Encrypts in CBC mode with ciphertext stealing.\\n\"\n \"Always returns a ciphertext of the exact same length as the plaintext.\"\n }, \n {\"decrypt\", (PyCFunction)tripledescbc_decrypt, METH_VARARGS, \n \"Returns a decrypted string.\\n\"\n \"Accepts an IV string of length 8 and a ciphertext string.\\n\"\n \"Decrypts in CBC mode with ciphertext stealing.\\n\"\n \"Always returns a plaintext of the exact same length as the ciphertext.\"\n }, \n {NULL, NULL}\t\/* sentinel *\/\n};\n\nstatic PyObject *tripledescbc_getattr(tripledescbc *self, char* name)\n{\n\treturn Py_FindMethod(tripledescbc_methods, (PyObject *)self, name);\n}\n\nstatic void tripledescbc_delete(tripledescbc *self) {\n\tif(self != NULL) {\n\t\txdeletear(self->key);\n\t\tPyMem_DEL(self);\n\t}\n}\n\nstatic PyObject *tripledescbc_new(tripledescbc *self, PyObject *args) {\n\ttripledescbc *newself = NULL;\n\ttry {\n\t\tbyte *key;\n\t\tint keylength;\n\t\tif(!PyArg_ParseTuple(args, \"s#\", &key, &keylength)) {\n\t\t\tthrow Exception(Exception::INVALID_ARGUMENT, \"wrong type of parameters passed in from Python\");\n\t\t}\n\t\tif(keylength != 24) {\n\t\t\tthrow Exception(Exception::INVALID_ARGUMENT, \"triple DES key length must be 24\");\n\t\t}\n\t\tif(!(newself = PyObject_NEW(tripledescbc, &tripledescbc_type))) {\n\t\t throw MemoryException();\n\t\t}\n\t\tbyte *keycopy = new byte[24];\n\t\tmemcpy(keycopy, key, 24);\n\t\t\/\/\t\tprintf(\"in tripledescbc_new(); keycopy: %p, key: %p\\n\", keycopy, key);\n\t\tnewself->key = keycopy;\n\t\treturn (PyObject *)newself;\n\t}\n\tcatch(CryptoPP::Exception &e) {\n\t\ttripledescbc_delete(newself);\n\t\tPyErr_SetString(TripleDESCBCError, e.what());\n\t\treturn NULL;\n\t}\n\tcatch(MemoryException &e)\n\t{\n\t\ttripledescbc_delete(newself);\n\t\tPyErr_SetString(PyExc_MemoryError, \"Can't allocate memory to do set up keys for en\/decryption\");\n\t\treturn NULL;\n\t}\n}\n\n#define _MIN_UNSAFE(x, y) ((x)<(y)?(x):(y))\nstatic PyObject *tripledescbc_encrypt(tripledescbc *self, PyObject *args) {\n\t\/\/\tstd::cout << \"hello enc 0\" << std::endl; std::cout.flush();\n\tPyObject *result = NULL;\n\tbyte *ciphertext = NULL;\n\ttry {\n\t\tbyte *iv;\n\t\tunsigned int ivlength;\n\t\tbyte *text;\n\t\tunsigned int textlength;\n\t\tif(!PyArg_ParseTuple(args, \"s#s#\", &iv, &ivlength, &text, &textlength)) {\n\t\t\tthrow Exception(Exception::INVALID_ARGUMENT, \"wrong type of parameters passed in from Python\");\n\t\t}\n\t\tif(ivlength != 8) {\n\t\t\tthrow Exception(Exception::INVALID_ARGUMENT, \"IV length must be 8\");\n\t\t}\n\t\t\/\/\t\tstd::cout << \"hello enc 0.7\" << std::endl; std::cout.flush();\n\t\t\/\/\t\tstd::cout << \"hello enc 0.7.1, self: \" << self << std::endl; std::cout.flush();\n\t\t\/\/\t\tstd::cout << \"hello enc 0.7.2, self->key: \";\n\t\t\/\/\t\tstd::cout << self->key;\n\t\t\/\/\t\tstd::cout << std::endl;\n\t\t\/\/\t\tstd::cout.flush();\n\t\t\/\/\tstd::cout << \"hello enc 0.7.3, iv: \" << iv << std::endl; std::cout.flush();\n\t\tCBC_CTS_Mode<DES_XEX3>::Encryption encryption(self->key, 24, iv);\n\t\t\/\/\t\tstd::cout << \"hello enc 0.8\" << std::endl; std::cout.flush();\n\t\tciphertext = new byte[textlength];\n\t\t\/\/\t\tstd::cout << \"hello enc 0.9\" << std::endl; std::cout.flush();\n\t\tif (ciphertext == NULL) {\n\t\t\tthrow MemoryException();\n\t\t}\n\t\t\/\/\t\tstd::cout << \"hello enc 1\" << std::endl; std::cout.flush();\n\t\tStreamTransformationFilter encryptor(encryption, new ArraySink(ciphertext, textlength));\n\t\t\/\/\t\tstd::cout << \"hello enc 2\" << std::endl; std::cout.flush();\n\t\tencryptor.PutMessageEnd(text, textlength);\n\t\t\/\/\t\tstd::cout << \"hello enc 3\" << std::endl; std::cout.flush();\n\t\tresult = Py_BuildValue(\"s#\", ciphertext, textlength);\n\t\t\/\/\t\tstd::cout << \"hello enc 4\" << std::endl; std::cout.flush();\n\t\tif(result == NULL) {\n\t\t\tthrow MemoryException();\n\t\t}\n\t\t\/\/\t\tstd::cout << \"hello enc 5\" << std::endl; std::cout.flush();\n\t\txdeletear(ciphertext);\n\t\t\/\/\t\tstd::cout << \"hello enc 6\" << std::endl; std::cout.flush();\n\t\treturn result;\n\t}\n\tcatch(CryptoPP::Exception &e) {\n\t\tif(result != NULL) {\n\t\t\tPyMem_DEL(result);\n\t\t}\n\t\txdeletear(ciphertext);\n\t\tPyErr_SetString(TripleDESCBCError, e.what());\n\t\treturn NULL;\n\t}\n\tcatch(MemoryException &e) {\n\t\tif(result != NULL) {\n\t\t\tPyMem_DEL(result);\n\t\t}\n\t\txdeletear(ciphertext);\n\t\tPyErr_SetString(PyExc_MemoryError, \"Can't allocate memory to do encryption\");\n\t\treturn NULL;\n\t}\n\t\/\/\tstd::cout << \"goodbye enc\" << std::endl; std::cout.flush();\n}\n\nstatic PyObject *tripledescbc_decrypt(tripledescbc *self, PyObject *args) {\n\t\/\/\tstd::cout << \"hello dec 0\" << std::endl; std::cout.flush();\n\tPyObject *result = NULL;\n\tbyte *plaintext = NULL;\n\ttry {\n\t\tbyte *iv;\n\t\tunsigned int ivlength;\n\t\tbyte *text;\n\t\tunsigned int textlength;\n\t\tif(!PyArg_ParseTuple(args, \"s#s#\", &iv, &ivlength, &text, &textlength)) {\n\t\t\tthrow Exception(Exception::INVALID_ARGUMENT, \"wrong type of parameters passed in from Python\");\n\t\t}\n\t\tif(ivlength != 8) {\n\t\t\tthrow Exception(Exception::INVALID_ARGUMENT, \"IV length must be 8\");\n\t\t}\n\t\tCBC_CTS_Mode<DES_XEX3>::Decryption decryption(self->key, 24, iv);\n\t\tplaintext = new byte[textlength];\n\t\tif (plaintext == NULL) {\n\t\t\tthrow MemoryException();\n\t\t}\n\t\tStreamTransformationFilter decryptor(decryption, new ArraySink(plaintext, textlength));\n\t\tdecryptor.PutMessageEnd(text, textlength);\n\t\tresult = Py_BuildValue(\"s#\", plaintext, textlength);\n\t\tif(result == NULL) {\n\t\t\tthrow MemoryException();\n\t\t}\n\t\txdeletear(plaintext);\n\t\treturn result;\n\t}\n\tcatch(CryptoPP::Exception &e) {\n\t\tif(result != NULL) {\n\t\t\tPyMem_DEL(result);\n\t\t}\n\t\txdeletear(plaintext);\n\t\tPyErr_SetString(TripleDESCBCError, e.what());\n\t\treturn NULL;\n\t}\n\tcatch(MemoryException &e) {\n\t\tif(result != NULL) {\n\t\t\tPyMem_DEL(result);\n\t\t}\n\t\txdeletear(plaintext);\n\t\tPyErr_SetString(PyExc_MemoryError, \"Can't allocate memory to do decryption\");\n\t\treturn NULL;\n\t}\n}\n\nPyMethodDef tripledescbc_functions[] = {\n {\"new\", (PyCFunction)tripledescbc_new, METH_VARARGS, \n \"Constructs a new tripledescbc.\\n\"\n \"Accepts a key of length 24.\"\n }, \n {NULL, NULL}\t\/* Sentinel *\/\n};\n\nchar* tripledescbc_doc =\n\"Does 3DES encryption and decyption in CBC mode with ciphertext stealing.\\n\"\n\"Always uses a key of length 24 and initialization vectors of length 8.\\n\"\n\"\\n\"\n\"Class methods are - \\n\"\n\"new(key) - constructor\\n\"\n\"\\n\"\n\"Instance methods are - \\n\"\n\"encrypt(iv, plaintext) - encrypt a string\\n\"\n\"decrypt(iv, ciphertext) - decrypt a string\";\n\n\/* Initialize this module. *\/\n\nextern \"C\"\n{\nDL_EXPORT(void)\ninittripledescbc()\n{\n PyObject *m, *d;\n\tm = Py_InitModule3(\"tripledescbc\", tripledescbc_functions, tripledescbc_doc);\n d = PyModule_GetDict(m);\n TripleDESCBCError = PyErr_NewException(\"tripledescbc.Error\", NULL, NULL);\n PyDict_SetItemString(d, \"Error\", TripleDESCBCError);\n}\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/* This file is part of Zanshin Todo.\n\n Copyright 2011 Kevin Ottens <ervin@kde.org>\n\n This program is free software; you can redistribute it and\/or\n modify it under the terms of the GNU General Public License as\n published by the Free Software Foundation; either version 2 of\n the License or (at your option) version 3 or any later version\n accepted by the membership of KDE e.V. (or its successor approved\n by the membership of KDE e.V.), which shall act as a proxy\n defined in Section 14 of version 3 of the license.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with this program; if not, write to the Free Software\n Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,\n USA.\n*\/\n\n#include \"zanshinrunner.h\"\n\n#include <KDE\/Akonadi\/CollectionFetchJob>\n#include <KDE\/Akonadi\/CollectionFetchScope>\n#include <KDE\/Akonadi\/Item>\n#include <KDE\/Akonadi\/ItemCreateJob>\n\n#include <KDE\/KCalCore\/Todo>\n\n#include <KDE\/KDebug>\n#include <KDE\/KIcon>\n#include <KDE\/KLocale>\n\nZanshinRunner::ZanshinRunner(QObject *parent, const QVariantList &args)\n : Plasma::AbstractRunner(parent, args)\n{\n setObjectName(QLatin1String(\"Zanshin\"));\n setIgnoredTypes(Plasma::RunnerContext::Directory | Plasma::RunnerContext::File |\n Plasma::RunnerContext::NetworkLocation | Plasma::RunnerContext::Help);\n\n connect(this, SIGNAL(prepare()), this, SLOT(prep()));\n connect(this, SIGNAL(teardown()), this, SLOT(down()));\n}\n\nZanshinRunner::~ZanshinRunner()\n{\n}\n\nvoid ZanshinRunner::match(Plasma::RunnerContext &context)\n{\n const QString command = context.query().trimmed();\n\n if (!command.startsWith(\"todo:\", Qt::CaseInsensitive)) {\n return;\n }\n\n const QString summary = command.mid(5).trimmed();\n\n if (summary.isEmpty()) {\n return;\n }\n\n QList<Plasma::QueryMatch> matches;\n\n Plasma::QueryMatch match(this);\n match.setData(summary);\n match.setType(Plasma::QueryMatch::ExactMatch);\n match.setIcon(KIcon(\"office-calendar\"));\n match.setText(i18n(\"Add \\\"%1\\\" to your todo list\", summary));\n match.setRelevance(1.0);\n\n matches << match;\n context.addMatches(context.query(), matches);\n}\n\nvoid ZanshinRunner::run(const Plasma::RunnerContext &context, const Plasma::QueryMatch &match)\n{\n Q_UNUSED(context)\n\n Akonadi::CollectionFetchJob *job = new Akonadi::CollectionFetchJob(Akonadi::Collection::root(),\n Akonadi::CollectionFetchJob::Recursive);\n job->fetchScope().setContentMimeTypes(QStringList() << \"application\/x-vnd.akonadi.calendar.todo\");\n job->exec();\n\n Akonadi::Collection::List cols = job->collections();\n\n if (cols.isEmpty()) {\n return;\n }\n\n KCalCore::Todo::Ptr todo(new KCalCore::Todo);\n todo->setSummary(match.data().toString());\n\n Akonadi::Item item;\n item.setMimeType(\"application\/x-vnd.akonadi.calendar.todo\");\n item.setPayload<KCalCore::Todo::Ptr>(todo);\n\n new Akonadi::ItemCreateJob(item, cols.first());\n}\n\n#include \"zanshinrunner.moc\"\n<commit_msg>Add todo in default collection<commit_after>\/* This file is part of Zanshin Todo.\n\n Copyright 2011 Kevin Ottens <ervin@kde.org>\n\n This program is free software; you can redistribute it and\/or\n modify it under the terms of the GNU General Public License as\n published by the Free Software Foundation; either version 2 of\n the License or (at your option) version 3 or any later version\n accepted by the membership of KDE e.V. (or its successor approved\n by the membership of KDE e.V.), which shall act as a proxy\n defined in Section 14 of version 3 of the license.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with this program; if not, write to the Free Software\n Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,\n USA.\n*\/\n\n#include \"zanshinrunner.h\"\n\n#include <KDE\/Akonadi\/CollectionFetchJob>\n#include <KDE\/Akonadi\/CollectionFetchScope>\n#include <KDE\/Akonadi\/Item>\n#include <KDE\/Akonadi\/ItemCreateJob>\n\n#include <KDE\/KCalCore\/Todo>\n\n#include <KDE\/KDebug>\n#include <KDE\/KIcon>\n#include <KDE\/KLocale>\n\nZanshinRunner::ZanshinRunner(QObject *parent, const QVariantList &args)\n : Plasma::AbstractRunner(parent, args)\n{\n setObjectName(QLatin1String(\"Zanshin\"));\n setIgnoredTypes(Plasma::RunnerContext::Directory | Plasma::RunnerContext::File |\n Plasma::RunnerContext::NetworkLocation | Plasma::RunnerContext::Help);\n\n connect(this, SIGNAL(prepare()), this, SLOT(prep()));\n connect(this, SIGNAL(teardown()), this, SLOT(down()));\n}\n\nZanshinRunner::~ZanshinRunner()\n{\n}\n\nvoid ZanshinRunner::match(Plasma::RunnerContext &context)\n{\n const QString command = context.query().trimmed();\n\n if (!command.startsWith(\"todo:\", Qt::CaseInsensitive)) {\n return;\n }\n\n const QString summary = command.mid(5).trimmed();\n\n if (summary.isEmpty()) {\n return;\n }\n\n QList<Plasma::QueryMatch> matches;\n\n Plasma::QueryMatch match(this);\n match.setData(summary);\n match.setType(Plasma::QueryMatch::ExactMatch);\n match.setIcon(KIcon(\"office-calendar\"));\n match.setText(i18n(\"Add \\\"%1\\\" to your todo list\", summary));\n match.setRelevance(1.0);\n\n matches << match;\n context.addMatches(context.query(), matches);\n}\n\nvoid ZanshinRunner::run(const Plasma::RunnerContext &context, const Plasma::QueryMatch &match)\n{\n Q_UNUSED(context)\n\n Akonadi::CollectionFetchJob *job = new Akonadi::CollectionFetchJob(Akonadi::Collection::root(),\n Akonadi::CollectionFetchJob::Recursive);\n job->fetchScope().setContentMimeTypes(QStringList() << \"application\/x-vnd.akonadi.calendar.todo\");\n job->exec();\n\n Akonadi::Collection::List cols = job->collections();\n\n if (cols.isEmpty()) {\n return;\n }\n\n Akonadi::Collection collection;\n\n KConfig zanshin(\"zanshinrc\");\n KConfigGroup config(&zanshin, \"General\");\n\n qint64 defaultCollectionId = config.readEntry(\"defaultCollection\", -1);\n\n if (defaultCollectionId > 0) {\n foreach (Akonadi::Collection col, cols) {\n if (col.id() == defaultCollectionId) {\n collection = col;\n break;\n }\n }\n }\n\n if (!collection.isValid()) {\n collection = cols.first();\n }\n\n KCalCore::Todo::Ptr todo(new KCalCore::Todo);\n todo->setSummary(match.data().toString());\n\n Akonadi::Item item;\n item.setMimeType(\"application\/x-vnd.akonadi.calendar.todo\");\n item.setPayload<KCalCore::Todo::Ptr>(todo);\n\n new Akonadi::ItemCreateJob(item, collection);\n}\n\n#include \"zanshinrunner.moc\"\n<|endoftext|>"} {"text":"<commit_before>\/\/ Standard library\n#include <iostream> \/\/\/ @todo Remove\n\n\/\/ Boost\n#include <boost\/python.hpp>\n\n\/\/ PyCairo\n#include <pycairo\/pycairo.h>\n\/\/ See http:\/\/www.cairographics.org\/documentation\/pycairo\/2\/pycairo_c_api.html\nstatic Pycairo_CAPI_t* Pycairo_CAPI;\n\n\/\/ DrawTurksHead\n#include <TurksHead\/TurksHead.hpp>\n\nnamespace {\n\nclass PythonTurksHead : public TurksHead::TurksHead, public boost::python::wrapper< TurksHead::TurksHead > {\npublic:\n PythonTurksHead( int leads, int bights, double innerRadius, double outerRadius, double lineWidth ) :\n TurksHead::TurksHead( leads, bights, innerRadius, outerRadius, lineWidth ),\n pythonComputeColorHsv( this->get_override( \"\" ) ),\n pythonComputeColorHsvInit( false )\n {\n }\n\n PythonTurksHead( const TurksHead::TurksHead& t ) :\n TurksHead::TurksHead( t ),\n pythonComputeColorHsv( this->get_override( \"\" ) ),\n pythonComputeColorHsvInit( false )\n {\n }\n\n void draw( boost::python::object context ) {\n TurksHead::draw( Cairo::RefPtr< Cairo::Context >( new Cairo::Context( PycairoContext_GET( context.ptr() ) ) ) );\n }\n\n double getAltitude( int k, int theta ) {\n return TurksHead::TurksHead::getAltitude(\n TurksHead::TurksHead::Path( k ),\n TurksHead::TurksHead::Theta( theta )\n );\n }\n\nprivate:\n boost::tuple< double, double, double > computeColorHsv( int k, int theta ) const {\n if( !pythonComputeColorHsvInit ) {\n pythonComputeColorHsv = this->get_override( \"computeColorHsv\" );\n pythonComputeColorHsvInit = true;\n }\n if( pythonComputeColorHsv ) {\n boost::python::tuple r = pythonComputeColorHsv( k, theta );\n double h = boost::python::extract< double >( r[0] );\n double s = boost::python::extract< double >( r[1] );\n double v = boost::python::extract< double >( r[2] );\n return boost::make_tuple( h, s, v );\n } else {\n return TurksHead::TurksHead::computeColorHsv( k, theta );\n }\n }\n\nprivate:\n mutable boost::python::override pythonComputeColorHsv;\n mutable bool pythonComputeColorHsvInit;\n};\n\n}\n\nBOOST_PYTHON_MODULE( _turkshead ) {\n Pycairo_IMPORT; \/\/ Initialization of Pycairo_CAPI\n\n \/\/\/ @todo Look at http:\/\/www.boost.org\/doc\/libs\/1_43_0\/libs\/parameter\/doc\/html\/python.html to add named parameters to the constructor\n boost::python::class_< PythonTurksHead >( \"TurksHead\", boost::python::init< int, int, double, double, double >() )\n .def( \"draw\", &PythonTurksHead::draw )\n .add_property( \"p\", &TurksHead::TurksHead::getP )\n .add_property( \"q\", &TurksHead::TurksHead::getQ )\n .add_property( \"d\", &TurksHead::TurksHead::getD )\n .def( \"getAltitude\", &PythonTurksHead::getAltitude )\n ;\n}\n<commit_msg>Remove namespace\/class ambiguities<commit_after>\/\/ Standard library\n#include <iostream> \/\/\/ @todo Remove\n\n\/\/ Boost\n#include <boost\/python.hpp>\n\n\/\/ PyCairo\n#include <pycairo\/pycairo.h>\n\/\/ See http:\/\/www.cairographics.org\/documentation\/pycairo\/2\/pycairo_c_api.html\nstatic Pycairo_CAPI_t* Pycairo_CAPI;\n\n\/\/ DrawTurksHead\n#include <TurksHead\/TurksHead.hpp>\n\nnamespace {\n\nclass PythonTurksHead : public ::TurksHead::TurksHead, public boost::python::wrapper< ::TurksHead::TurksHead > {\npublic:\n PythonTurksHead( int leads, int bights, double innerRadius, double outerRadius, double lineWidth ) :\n ::TurksHead::TurksHead( leads, bights, innerRadius, outerRadius, lineWidth ),\n pythonComputeColorHsv( this->get_override( \"\" ) ),\n pythonComputeColorHsvInit( false )\n {\n }\n\n PythonTurksHead( const ::TurksHead::TurksHead& t ) :\n ::TurksHead::TurksHead( t ),\n pythonComputeColorHsv( this->get_override( \"\" ) ),\n pythonComputeColorHsvInit( false )\n {\n }\n\n void draw( boost::python::object context ) {\n ::TurksHead::TurksHead::draw( Cairo::RefPtr< Cairo::Context >( new Cairo::Context( PycairoContext_GET( context.ptr() ) ) ) );\n }\n\n double getAltitude( int k, int theta ) {\n return ::TurksHead::TurksHead::getAltitude(\n ::TurksHead::TurksHead::Path( k ),\n ::TurksHead::TurksHead::Theta( theta )\n );\n }\n\nprivate:\n boost::tuple< double, double, double > computeColorHsv( int k, int theta ) const {\n if( !pythonComputeColorHsvInit ) {\n pythonComputeColorHsv = this->get_override( \"computeColorHsv\" );\n pythonComputeColorHsvInit = true;\n }\n if( pythonComputeColorHsv ) {\n boost::python::tuple r = pythonComputeColorHsv( k, theta );\n double h = boost::python::extract< double >( r[0] );\n double s = boost::python::extract< double >( r[1] );\n double v = boost::python::extract< double >( r[2] );\n return boost::make_tuple( h, s, v );\n } else {\n return ::TurksHead::TurksHead::computeColorHsv( k, theta );\n }\n }\n\nprivate:\n mutable boost::python::override pythonComputeColorHsv;\n mutable bool pythonComputeColorHsvInit;\n};\n\n}\n\nBOOST_PYTHON_MODULE( _turkshead ) {\n Pycairo_IMPORT; \/\/ Initialization of Pycairo_CAPI\n\n \/\/\/ @todo Look at http:\/\/www.boost.org\/doc\/libs\/1_43_0\/libs\/parameter\/doc\/html\/python.html to add named parameters to the constructor\n boost::python::class_< PythonTurksHead >( \"TurksHead\", boost::python::init< int, int, double, double, double >() )\n .def( \"draw\", &PythonTurksHead::draw )\n .add_property( \"p\", &::TurksHead::TurksHead::getP )\n .add_property( \"q\", &::TurksHead::TurksHead::getQ )\n .add_property( \"d\", &::TurksHead::TurksHead::getD )\n .def( \"getAltitude\", &PythonTurksHead::getAltitude )\n ;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"fileexplorer.h\"\n#include \"ui_fileexplorer.h\"\n\nFileExplorer::FileExplorer(QFileSystemModel *filesmodel, QWidget *parent) :\n QWidget(parent),\n ui(new Ui::FileExplorer), files_model_(filesmodel)\n{\n ui->setupUi(this);\n\n \/\/ path Edit\n ui->pathEdit->setText( QDir::homePath() );\n QCompleter *completer = new QCompleter(this);\n completer->setModel(new QDirModel(completer));\n completer->setCaseSensitivity(Qt::CaseInsensitive);\n ui->pathEdit->setCompleter(completer);\n\n \/\/ short cut\n sc_editpath_ = new QShortcut(QKeySequence(tr(\"Ctrl+L\", \"Edit path\")),this);\n connect(sc_editpath_, SIGNAL(activated()), ui->pathEdit, SLOT(setFocus()));\n\n \/\/ dir View\n dir_model_ = new QFileSystemModel(this);\n dir_proxy_model_ = new FSfilterProxyModel(this);\n dir_model_->setRootPath(QDir::rootPath());\n dir_model_->setFilter(QDir::NoDotAndDotDot | QDir::AllDirs);\n dir_proxy_model_->setSourceModel(dir_model_);\n ui->dirView->setModel(dir_proxy_model_);\n ui->dirView->header()->setSectionResizeMode(QHeaderView::ResizeToContents);\n connect(ui->dirView->selectionModel(), SIGNAL(currentChanged(QModelIndex,QModelIndex)),\n this, SLOT(onCurrentDirChanged(QModelIndex,QModelIndex)));\n\n \/\/ files View\n ui->filesView->setModel(files_model_);\n ui->filesView->setItemDelegate(new RankDelegate(this));\n\n ui->filesView->setEditTriggers(QAbstractItemView::DoubleClicked\n | QAbstractItemView::SelectedClicked);\n ui->filesView->setSelectionBehavior(QAbstractItemView::SelectRows);\n ui->filesView->horizontalHeader()->setSectionResizeMode(QHeaderView::ResizeToContents);\n connect(ui->filesView->selectionModel(), SIGNAL(currentChanged(QModelIndex,QModelIndex)),\n this, SLOT(onCurrentFileChanged(QModelIndex,QModelIndex)));\n\n \/\/ handle path change\n connect(this, SIGNAL(sigPath(QString)), this, SLOT(setPath(QString)));\n}\n\nFileExplorer::~FileExplorer()\n{\n delete ui;\n}\n\nQString FileExplorer::currentPath() const\n{\n return ui->pathEdit->text();\n}\n\nvoid FileExplorer::onCurrentDirChanged(QModelIndex current, QModelIndex previous)\n{\n emit sigPath( dir_model_->filePath(dir_proxy_model_->mapToSource( current)) );\n}\n\nvoid FileExplorer::onCurrentFileChanged(QModelIndex current, QModelIndex previous)\n{\n if (files_model_->filePath(current) != files_model_->filePath(previous))\n emit sigFilePath( files_model_->filePath(current));\n\n if (current.column() == 0){\n emit sigFileNameSelected(true);\n } else {\n emit sigFileNameSelected(false);\n }\n}\n\nvoid FileExplorer::setPath(QString path)\n{\n ui->pathEdit->setText(path);\n\n QModelIndex din = dir_proxy_model_->mapFromSource(dir_model_->index(path));\n ui->dirView->scrollTo(din);\n ui->dirView->collapse(din);\n ui->dirView->setCurrentIndex(din);\n ui->dirView->resizeColumnToContents(din.column());\n\n ui->filesView->setRootIndex(files_model_->setRootPath(path));\n}\n\nvoid FileExplorer::on_pathEdit_editingFinished()\n{\n finfo_.setFile(ui->pathEdit->text());\n if (finfo_.isDir()) {\n emit sigPath(finfo_.filePath());\n } else if ( finfo_.isFile()) {\n emit sigPath(finfo_.path());\n emit sigFilePath(finfo_.filePath());\n }\n}\n<commit_msg>filter dir completer.<commit_after>#include \"fileexplorer.h\"\n#include \"ui_fileexplorer.h\"\n\nFileExplorer::FileExplorer(QFileSystemModel *filesmodel, QWidget *parent) :\n QWidget(parent),\n ui(new Ui::FileExplorer), files_model_(filesmodel)\n{\n ui->setupUi(this);\n\n \/\/ path Edit\n ui->pathEdit->setText( QDir::homePath() );\n QCompleter *completer = new QCompleter(this);\n QStringList fli(\"*\");\n completer->setModel(new QDirModel(fli,\n QDir::NoDotAndDotDot | QDir::AllDirs,\n QDir::Name));\n completer->setCaseSensitivity(Qt::CaseInsensitive);\n ui->pathEdit->setCompleter(completer);\n\n \/\/ short cut\n sc_editpath_ = new QShortcut(QKeySequence(tr(\"Ctrl+L\", \"Edit path\")),this);\n connect(sc_editpath_, SIGNAL(activated()), ui->pathEdit, SLOT(setFocus()));\n\n \/\/ dir View\n dir_model_ = new QFileSystemModel(this);\n dir_proxy_model_ = new FSfilterProxyModel(this);\n dir_model_->setRootPath(QDir::rootPath());\n dir_model_->setFilter(QDir::NoDotAndDotDot | QDir::AllDirs);\n dir_proxy_model_->setSourceModel(dir_model_);\n ui->dirView->setModel(dir_proxy_model_);\n ui->dirView->header()->setSectionResizeMode(QHeaderView::ResizeToContents);\n connect(ui->dirView->selectionModel(), SIGNAL(currentChanged(QModelIndex,QModelIndex)),\n this, SLOT(onCurrentDirChanged(QModelIndex,QModelIndex)));\n\n \/\/ files View\n ui->filesView->setModel(files_model_);\n ui->filesView->setItemDelegate(new RankDelegate(this));\n\n ui->filesView->setEditTriggers(QAbstractItemView::DoubleClicked\n | QAbstractItemView::SelectedClicked);\n ui->filesView->setSelectionBehavior(QAbstractItemView::SelectRows);\n ui->filesView->horizontalHeader()->setSectionResizeMode(QHeaderView::ResizeToContents);\n connect(ui->filesView->selectionModel(), SIGNAL(currentChanged(QModelIndex,QModelIndex)),\n this, SLOT(onCurrentFileChanged(QModelIndex,QModelIndex)));\n\n \/\/ handle path change\n connect(this, SIGNAL(sigPath(QString)), this, SLOT(setPath(QString)));\n}\n\nFileExplorer::~FileExplorer()\n{\n delete ui;\n}\n\nQString FileExplorer::currentPath() const\n{\n return ui->pathEdit->text();\n}\n\nvoid FileExplorer::onCurrentDirChanged(QModelIndex current, QModelIndex previous)\n{\n emit sigPath( dir_model_->filePath(dir_proxy_model_->mapToSource( current)) );\n}\n\nvoid FileExplorer::onCurrentFileChanged(QModelIndex current, QModelIndex previous)\n{\n if (files_model_->filePath(current) != files_model_->filePath(previous))\n emit sigFilePath( files_model_->filePath(current));\n\n if (current.column() == 0){\n emit sigFileNameSelected(true);\n } else {\n emit sigFileNameSelected(false);\n }\n}\n\nvoid FileExplorer::setPath(QString path)\n{\n ui->pathEdit->setText(path);\n\n QModelIndex din = dir_proxy_model_->mapFromSource(dir_model_->index(path));\n ui->dirView->scrollTo(din);\n ui->dirView->collapse(din);\n ui->dirView->setCurrentIndex(din);\n ui->dirView->resizeColumnToContents(din.column());\n\n ui->filesView->setRootIndex(files_model_->setRootPath(path));\n}\n\nvoid FileExplorer::on_pathEdit_editingFinished()\n{\n finfo_.setFile(ui->pathEdit->text());\n if (finfo_.isDir()) {\n emit sigPath(finfo_.filePath());\n } else if ( finfo_.isFile()) {\n emit sigPath(finfo_.path());\n emit sigFilePath(finfo_.filePath());\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ This file is part of OpenMVG, an Open Multiple View Geometry C++ library.\n\n\/\/ Copyright (c) 2016 cDc <cdc.seacave@gmail.com>, Pierre MOULON\n\n\/\/ This Source Code Form is subject to the terms of the Mozilla Public\n\/\/ License, v. 2.0. If a copy of the MPL was not distributed with this\n\/\/ file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n\n#include \"openMVG\/cameras\/Camera_Pinhole.hpp\"\n#include \"openMVG\/cameras\/Camera_undistort_image.hpp\"\n#include \"openMVG\/image\/image_io.hpp\"\n#include \"openMVG\/sfm\/sfm_data.hpp\"\n#include \"openMVG\/sfm\/sfm_data_io.hpp\"\n\n#define _USE_EIGEN\n#include \"InterfaceMVS.h\"\n\n#include \"third_party\/cmdLine\/cmdLine.h\"\n#include \"third_party\/stlplus3\/filesystemSimplified\/file_system.hpp\"\n#include \"third_party\/progress\/progress_display.hpp\"\n\nusing namespace openMVG;\nusing namespace openMVG::cameras;\nusing namespace openMVG::geometry;\nusing namespace openMVG::image;\nusing namespace openMVG::sfm;\n\n#include <atomic>\n#include <cstdlib>\n#include <string>\n\n#ifdef OPENMVG_USE_OPENMP\n#include <omp.h>\n#endif\n\nbool exportToOpenMVS(\n const SfM_Data & sfm_data,\n const std::string & sOutFile,\n const std::string & sOutDir,\n const int iNumThreads = 0\n )\n{\n \/\/ Create undistorted images directory structure\n if (!stlplus::is_folder(sOutDir))\n {\n stlplus::folder_create(sOutDir);\n if (!stlplus::is_folder(sOutDir))\n {\n std::cerr << \"Cannot access to one of the desired output directory\" << std::endl;\n return false;\n }\n }\n\n \/\/ Export data :\n MVS::Interface scene;\n size_t nPoses(0);\n const uint32_t nViews((uint32_t)sfm_data.GetViews().size());\n\n C_Progress_display my_progress_bar(nViews,\n std::cout, \"\\n- PROCESS VIEWS -\\n\");\n\n \/\/ OpenMVG can have not contiguous index, use a map to create the required OpenMVS contiguous ID index\n std::map<openMVG::IndexT, uint32_t> map_intrinsic, map_view;\n\n \/\/ define a platform with all the intrinsic group\n for (const auto& intrinsic: sfm_data.GetIntrinsics())\n {\n if (isPinhole(intrinsic.second->getType()))\n {\n const Pinhole_Intrinsic * cam = dynamic_cast<const Pinhole_Intrinsic*>(intrinsic.second.get());\n if (map_intrinsic.count(intrinsic.first) == 0)\n map_intrinsic.insert(std::make_pair(intrinsic.first, scene.platforms.size()));\n MVS::Interface::Platform platform;\n \/\/ add the camera\n MVS::Interface::Platform::Camera camera;\n camera.K = cam->K();\n \/\/ sub-pose\n camera.R = Mat3::Identity();\n camera.C = Vec3::Zero();\n platform.cameras.push_back(camera);\n scene.platforms.push_back(platform);\n }\n }\n\n \/\/ define images & poses\n scene.images.reserve(nViews);\n for (const auto& view : sfm_data.GetViews())\n {\n map_view[view.first] = scene.images.size();\n MVS::Interface::Image image;\n const std::string srcImage = stlplus::create_filespec(sfm_data.s_root_path, view.second->s_Img_path);\n image.name = stlplus::create_filespec(sOutDir, view.second->s_Img_path);\n image.platformID = map_intrinsic.at(view.second->id_intrinsic);\n MVS::Interface::Platform& platform = scene.platforms[image.platformID];\n image.cameraID = 0;\n if (!stlplus::is_file(srcImage))\n {\n std::cout << \"Cannot read the corresponding image: \" << srcImage << std::endl;\n return EXIT_FAILURE;\n }\n if (sfm_data.IsPoseAndIntrinsicDefined(view.second.get()))\n {\n MVS::Interface::Platform::Pose pose;\n image.poseID = platform.poses.size();\n const openMVG::geometry::Pose3 poseMVG(sfm_data.GetPoseOrDie(view.second.get()));\n pose.R = poseMVG.rotation();\n pose.C = poseMVG.center();\n platform.poses.push_back(pose);\n ++nPoses;\n }\n else\n {\n \/\/ image have not valid pose, so set an undefined pose\n image.poseID = NO_ID;\n \/\/ just copy the image\n \/\/stlplus::file_copy(srcImage, image.name);\n }\n scene.images.emplace_back(image);\n ++my_progress_bar;\n }\n\n \/\/ Export undistorted images\n C_Progress_display my_progress_bar_images(sfm_data.views.size(),\n std::cout, \"\\n- UNDISTORT IMAGES -\\n\" );\n std::atomic<bool> bOk(true); \/\/ Use a boolean to track the status of the loop process\n#ifdef OPENMVG_USE_OPENMP\n const unsigned int nb_max_thread = (iNumThreads > 0)? iNumThreads : omp_get_max_threads();\n\n #pragma omp parallel for schedule(dynamic) num_threads(nb_max_thread)\n#endif\n for (int i = 0; i < static_cast<int>(sfm_data.views.size()); ++i)\n {\n ++my_progress_bar_images;\n\n if (!bOk)\n continue;\n\n Views::const_iterator iterViews = sfm_data.views.begin();\n std::advance(iterViews, i);\n const View * view = iterViews->second.get();\n\n \/\/ Get image paths\n const std::string srcImage = stlplus::create_filespec(sfm_data.s_root_path, view->s_Img_path);\n const std::string imageName = stlplus::create_filespec(sOutDir, view->s_Img_path);\n\n if (!stlplus::is_file(srcImage))\n {\n std::cerr << \"Cannot read the corresponding image: \" << srcImage << std::endl;\n bOk = false;\n continue;\n }\n if (sfm_data.IsPoseAndIntrinsicDefined(view))\n {\n \/\/ export undistorted images\n const openMVG::cameras::IntrinsicBase * cam = sfm_data.GetIntrinsics().at(view->id_intrinsic).get();\n if (cam->have_disto())\n {\n \/\/ undistort image and save it\n Image<openMVG::image::RGBColor> imageRGB, imageRGB_ud;\n try\n {\n if (ReadImage(srcImage.c_str(), &imageRGB))\n {\n UndistortImage(imageRGB, cam, imageRGB_ud, BLACK);\n bOk = WriteImage(imageName.c_str(), imageRGB_ud);\n }\n else\n {\n bOk = false;\n }\n }\n catch (const std::bad_alloc& e)\n {\n bOk = false;\n }\n }\n else\n {\n \/\/ just copy image\n stlplus::file_copy(srcImage, imageName);\n }\n }\n else\n {\n \/\/ just copy the image\n stlplus::file_copy(srcImage, imageName);\n }\n }\n\n if (!bOk)\n {\n std::cerr << \"Catched a memory error in the image conversion.\"\n << \" Please consider to use less threads ([-n|--numThreads]).\" << std::endl;\n return EXIT_FAILURE;\n }\n\n \/\/ define structure\n scene.vertices.reserve(sfm_data.GetLandmarks().size());\n for (const auto& vertex: sfm_data.GetLandmarks())\n {\n const Landmark & landmark = vertex.second;\n MVS::Interface::Vertex vert;\n MVS::Interface::Vertex::ViewArr& views = vert.views;\n for (const auto& observation: landmark.obs)\n {\n const auto it(map_view.find(observation.first));\n if (it != map_view.end()) {\n MVS::Interface::Vertex::View view;\n view.imageID = it->second;\n view.confidence = 0;\n views.push_back(view);\n }\n }\n if (views.size() < 2)\n continue;\n std::sort(\n views.begin(), views.end(),\n [] (const MVS::Interface::Vertex::View& view0, const MVS::Interface::Vertex::View& view1)\n {\n return view0.imageID < view1.imageID;\n }\n );\n vert.X = landmark.X.cast<float>();\n scene.vertices.push_back(vert);\n }\n\n \/\/ normalize camera intrinsics\n for (size_t p=0; p<scene.platforms.size(); ++p)\n {\n MVS::Interface::Platform& platform = scene.platforms[p];\n for (size_t c=0; c<platform.cameras.size(); ++c) {\n MVS::Interface::Platform::Camera& camera = platform.cameras[c];\n \/\/ find one image using this camera\n MVS::Interface::Image* pImage(nullptr);\n for (MVS::Interface::Image& image: scene.images)\n {\n if (image.platformID == p && image.cameraID == c && image.poseID != NO_ID)\n {\n pImage = ℑ\n break;\n }\n }\n if (!pImage)\n {\n std::cerr << \"error: no image using camera \" << c << \" of platform \" << p << std::endl;\n continue;\n }\n \/\/ read image meta-data\n ImageHeader imageHeader;\n ReadImageHeader(pImage->name.c_str(), &imageHeader);\n const double fScale(1.0\/std::max(imageHeader.width, imageHeader.height));\n camera.K(0, 0) *= fScale;\n camera.K(1, 1) *= fScale;\n camera.K(0, 2) *= fScale;\n camera.K(1, 2) *= fScale;\n }\n }\n\n \/\/ write OpenMVS data\n if (!MVS::ARCHIVE::SerializeSave(scene, sOutFile))\n return false;\n\n std::cout\n << \"Scene saved to OpenMVS interface format:\\n\"\n << \" #platforms: \" << scene.platforms.size() << std::endl;\n for (int i = 0; i < scene.platforms.size(); ++i)\n {\n std::cout << \" platform ( \" << i << \" ) #cameras: \" << scene.platforms[i].cameras.size() << std::endl;\n }\n std::cout\n << \" \" << scene.images.size() << \" images (\" << nPoses << \" calibrated)\\n\"\n << \" \" << scene.vertices.size() << \" Landmarks\\n\";\n return true;\n}\n\nint main(int argc, char *argv[])\n{\n CmdLine cmd;\n std::string sSfM_Data_Filename;\n std::string sOutFile = \"scene.mvs\";\n std::string sOutDir = \"undistorted_images\";\n int iNumThreads = 0;\n\n cmd.add( make_option('i', sSfM_Data_Filename, \"sfmdata\") );\n cmd.add( make_option('o', sOutFile, \"outfile\") );\n cmd.add( make_option('d', sOutDir, \"outdir\") );\n#ifdef OPENMVG_USE_OPENMP\n cmd.add( make_option('n', iNumThreads, \"numThreads\") );\n#endif\n\n try {\n if (argc == 1) throw std::string(\"Invalid command line parameter.\");\n cmd.process(argc, argv);\n } catch (const std::string& s) {\n std::cerr << \"Usage: \" << argv[0] << '\\n'\n << \"[-i|--sfmdata] filename, the SfM_Data file to convert\\n\"\n << \"[-o|--outfile] OpenMVS scene file\\n\"\n << \"[-d|--outdir] undistorted images path\\n\"\n#ifdef OPENMVG_USE_OPENMP\n << \"[-n|--numThreads] number of thread(s)\\n\"\n#endif\n << std::endl;\n\n std::cerr << s << std::endl;\n return EXIT_FAILURE;\n }\n\n if (stlplus::extension_part(sOutFile) != \"mvs\") {\n std::cerr << std::endl\n << \"Invalid output file extension: \" << sOutFile << std::endl\n << \"You must use a filename with a .mvs extension.\" << std::endl;\n return EXIT_FAILURE;\n }\n\n \/\/ Read the input SfM scene\n SfM_Data sfm_data;\n if (!Load(sfm_data, sSfM_Data_Filename, ESfM_Data(ALL))) {\n std::cerr << std::endl\n << \"The input SfM_Data file \\\"\"<< sSfM_Data_Filename << \"\\\" cannot be read.\" << std::endl;\n return EXIT_FAILURE;\n }\n\n \/\/ Export OpenMVS data structure\n if (!exportToOpenMVS(sfm_data, sOutFile, sOutDir, iNumThreads))\n {\n std::cerr << std::endl\n << \"The output openMVS scene file cannot be written\" << std::endl;\n return EXIT_FAILURE;\n }\n\n return EXIT_SUCCESS;\n}\n<commit_msg>[software] fix: main_openMVG2openMVS support grayscale images (#1709)<commit_after>\/\/ This file is part of OpenMVG, an Open Multiple View Geometry C++ library.\n\n\/\/ Copyright (c) 2016 cDc <cdc.seacave@gmail.com>, Pierre MOULON\n\n\/\/ This Source Code Form is subject to the terms of the Mozilla Public\n\/\/ License, v. 2.0. If a copy of the MPL was not distributed with this\n\/\/ file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n\n#include \"openMVG\/cameras\/Camera_Pinhole.hpp\"\n#include \"openMVG\/cameras\/Camera_undistort_image.hpp\"\n#include \"openMVG\/image\/image_io.hpp\"\n#include \"openMVG\/sfm\/sfm_data.hpp\"\n#include \"openMVG\/sfm\/sfm_data_io.hpp\"\n\n#define _USE_EIGEN\n#include \"InterfaceMVS.h\"\n\n#include \"third_party\/cmdLine\/cmdLine.h\"\n#include \"third_party\/stlplus3\/filesystemSimplified\/file_system.hpp\"\n#include \"third_party\/progress\/progress_display.hpp\"\n\nusing namespace openMVG;\nusing namespace openMVG::cameras;\nusing namespace openMVG::geometry;\nusing namespace openMVG::image;\nusing namespace openMVG::sfm;\n\n#include <atomic>\n#include <cstdlib>\n#include <string>\n\n#ifdef OPENMVG_USE_OPENMP\n#include <omp.h>\n#endif\n\nbool exportToOpenMVS(\n const SfM_Data & sfm_data,\n const std::string & sOutFile,\n const std::string & sOutDir,\n const int iNumThreads = 0\n )\n{\n \/\/ Create undistorted images directory structure\n if (!stlplus::is_folder(sOutDir))\n {\n stlplus::folder_create(sOutDir);\n if (!stlplus::is_folder(sOutDir))\n {\n std::cerr << \"Cannot access to one of the desired output directory\" << std::endl;\n return false;\n }\n }\n\n \/\/ Export data :\n MVS::Interface scene;\n size_t nPoses(0);\n const uint32_t nViews((uint32_t)sfm_data.GetViews().size());\n\n C_Progress_display my_progress_bar(nViews,\n std::cout, \"\\n- PROCESS VIEWS -\\n\");\n\n \/\/ OpenMVG can have not contiguous index, use a map to create the required OpenMVS contiguous ID index\n std::map<openMVG::IndexT, uint32_t> map_intrinsic, map_view;\n\n \/\/ define a platform with all the intrinsic group\n for (const auto& intrinsic: sfm_data.GetIntrinsics())\n {\n if (isPinhole(intrinsic.second->getType()))\n {\n const Pinhole_Intrinsic * cam = dynamic_cast<const Pinhole_Intrinsic*>(intrinsic.second.get());\n if (map_intrinsic.count(intrinsic.first) == 0)\n map_intrinsic.insert(std::make_pair(intrinsic.first, scene.platforms.size()));\n MVS::Interface::Platform platform;\n \/\/ add the camera\n MVS::Interface::Platform::Camera camera;\n camera.K = cam->K();\n \/\/ sub-pose\n camera.R = Mat3::Identity();\n camera.C = Vec3::Zero();\n platform.cameras.push_back(camera);\n scene.platforms.push_back(platform);\n }\n }\n\n \/\/ define images & poses\n scene.images.reserve(nViews);\n for (const auto& view : sfm_data.GetViews())\n {\n map_view[view.first] = scene.images.size();\n MVS::Interface::Image image;\n const std::string srcImage = stlplus::create_filespec(sfm_data.s_root_path, view.second->s_Img_path);\n image.name = stlplus::create_filespec(sOutDir, view.second->s_Img_path);\n image.platformID = map_intrinsic.at(view.second->id_intrinsic);\n MVS::Interface::Platform& platform = scene.platforms[image.platformID];\n image.cameraID = 0;\n if (!stlplus::is_file(srcImage))\n {\n std::cout << \"Cannot read the corresponding image: \" << srcImage << std::endl;\n return EXIT_FAILURE;\n }\n if (sfm_data.IsPoseAndIntrinsicDefined(view.second.get()))\n {\n MVS::Interface::Platform::Pose pose;\n image.poseID = platform.poses.size();\n const openMVG::geometry::Pose3 poseMVG(sfm_data.GetPoseOrDie(view.second.get()));\n pose.R = poseMVG.rotation();\n pose.C = poseMVG.center();\n platform.poses.push_back(pose);\n ++nPoses;\n }\n else\n {\n \/\/ image have not valid pose, so set an undefined pose\n image.poseID = NO_ID;\n \/\/ just copy the image\n \/\/stlplus::file_copy(srcImage, image.name);\n }\n scene.images.emplace_back(image);\n ++my_progress_bar;\n }\n\n \/\/ Export undistorted images\n C_Progress_display my_progress_bar_images(sfm_data.views.size(),\n std::cout, \"\\n- UNDISTORT IMAGES -\\n\" );\n std::atomic<bool> bOk(true); \/\/ Use a boolean to track the status of the loop process\n#ifdef OPENMVG_USE_OPENMP\n const unsigned int nb_max_thread = (iNumThreads > 0)? iNumThreads : omp_get_max_threads();\n\n #pragma omp parallel for schedule(dynamic) num_threads(nb_max_thread)\n#endif\n for (int i = 0; i < static_cast<int>(sfm_data.views.size()); ++i)\n {\n ++my_progress_bar_images;\n\n if (!bOk)\n continue;\n\n Views::const_iterator iterViews = sfm_data.views.begin();\n std::advance(iterViews, i);\n const View * view = iterViews->second.get();\n\n \/\/ Get image paths\n const std::string srcImage = stlplus::create_filespec(sfm_data.s_root_path, view->s_Img_path);\n const std::string imageName = stlplus::create_filespec(sOutDir, view->s_Img_path);\n\n if (!stlplus::is_file(srcImage))\n {\n std::cerr << \"Cannot read the corresponding image: \" << srcImage << std::endl;\n bOk = false;\n continue;\n }\n if (sfm_data.IsPoseAndIntrinsicDefined(view))\n {\n \/\/ export undistorted images\n const openMVG::cameras::IntrinsicBase * cam = sfm_data.GetIntrinsics().at(view->id_intrinsic).get();\n if (cam->have_disto())\n {\n \/\/ undistort image and save it\n Image<openMVG::image::RGBColor> imageRGB, imageRGB_ud;\n Image<uint8_t> image_gray, image_gray_ud;\n try\n {\n if (ReadImage(srcImage.c_str(), &imageRGB))\n {\n UndistortImage(imageRGB, cam, imageRGB_ud, BLACK);\n bOk = WriteImage(imageName.c_str(), imageRGB_ud);\n }\n else \/\/ If RGBColor reading fails, try to read as gray image\n if (ReadImage(srcImage.c_str(), &image_gray))\n {\n UndistortImage(image_gray, cam, image_gray_ud, BLACK);\n const bool bRes = WriteImage(imageName.c_str(), image_gray_ud);\n bOk = bOk & bRes;\n }\n else\n {\n bOk = false;\n }\n }\n catch (const std::bad_alloc& e)\n {\n bOk = false;\n }\n }\n else\n {\n \/\/ just copy image\n stlplus::file_copy(srcImage, imageName);\n }\n }\n else\n {\n \/\/ just copy the image\n stlplus::file_copy(srcImage, imageName);\n }\n }\n\n if (!bOk)\n {\n std::cerr << \"Catched a memory error in the image conversion.\"\n << \" Please consider to use less threads ([-n|--numThreads]).\" << std::endl;\n return EXIT_FAILURE;\n }\n\n \/\/ define structure\n scene.vertices.reserve(sfm_data.GetLandmarks().size());\n for (const auto& vertex: sfm_data.GetLandmarks())\n {\n const Landmark & landmark = vertex.second;\n MVS::Interface::Vertex vert;\n MVS::Interface::Vertex::ViewArr& views = vert.views;\n for (const auto& observation: landmark.obs)\n {\n const auto it(map_view.find(observation.first));\n if (it != map_view.end()) {\n MVS::Interface::Vertex::View view;\n view.imageID = it->second;\n view.confidence = 0;\n views.push_back(view);\n }\n }\n if (views.size() < 2)\n continue;\n std::sort(\n views.begin(), views.end(),\n [] (const MVS::Interface::Vertex::View& view0, const MVS::Interface::Vertex::View& view1)\n {\n return view0.imageID < view1.imageID;\n }\n );\n vert.X = landmark.X.cast<float>();\n scene.vertices.push_back(vert);\n }\n\n \/\/ normalize camera intrinsics\n for (size_t p=0; p<scene.platforms.size(); ++p)\n {\n MVS::Interface::Platform& platform = scene.platforms[p];\n for (size_t c=0; c<platform.cameras.size(); ++c) {\n MVS::Interface::Platform::Camera& camera = platform.cameras[c];\n \/\/ find one image using this camera\n MVS::Interface::Image* pImage(nullptr);\n for (MVS::Interface::Image& image: scene.images)\n {\n if (image.platformID == p && image.cameraID == c && image.poseID != NO_ID)\n {\n pImage = ℑ\n break;\n }\n }\n if (!pImage)\n {\n std::cerr << \"error: no image using camera \" << c << \" of platform \" << p << std::endl;\n continue;\n }\n \/\/ read image meta-data\n ImageHeader imageHeader;\n ReadImageHeader(pImage->name.c_str(), &imageHeader);\n const double fScale(1.0\/std::max(imageHeader.width, imageHeader.height));\n camera.K(0, 0) *= fScale;\n camera.K(1, 1) *= fScale;\n camera.K(0, 2) *= fScale;\n camera.K(1, 2) *= fScale;\n }\n }\n\n \/\/ write OpenMVS data\n if (!MVS::ARCHIVE::SerializeSave(scene, sOutFile))\n return false;\n\n std::cout\n << \"Scene saved to OpenMVS interface format:\\n\"\n << \" #platforms: \" << scene.platforms.size() << std::endl;\n for (int i = 0; i < scene.platforms.size(); ++i)\n {\n std::cout << \" platform ( \" << i << \" ) #cameras: \" << scene.platforms[i].cameras.size() << std::endl;\n }\n std::cout\n << \" \" << scene.images.size() << \" images (\" << nPoses << \" calibrated)\\n\"\n << \" \" << scene.vertices.size() << \" Landmarks\\n\";\n return true;\n}\n\nint main(int argc, char *argv[])\n{\n CmdLine cmd;\n std::string sSfM_Data_Filename;\n std::string sOutFile = \"scene.mvs\";\n std::string sOutDir = \"undistorted_images\";\n int iNumThreads = 0;\n\n cmd.add( make_option('i', sSfM_Data_Filename, \"sfmdata\") );\n cmd.add( make_option('o', sOutFile, \"outfile\") );\n cmd.add( make_option('d', sOutDir, \"outdir\") );\n#ifdef OPENMVG_USE_OPENMP\n cmd.add( make_option('n', iNumThreads, \"numThreads\") );\n#endif\n\n try {\n if (argc == 1) throw std::string(\"Invalid command line parameter.\");\n cmd.process(argc, argv);\n } catch (const std::string& s) {\n std::cerr << \"Usage: \" << argv[0] << '\\n'\n << \"[-i|--sfmdata] filename, the SfM_Data file to convert\\n\"\n << \"[-o|--outfile] OpenMVS scene file\\n\"\n << \"[-d|--outdir] undistorted images path\\n\"\n#ifdef OPENMVG_USE_OPENMP\n << \"[-n|--numThreads] number of thread(s)\\n\"\n#endif\n << std::endl;\n\n std::cerr << s << std::endl;\n return EXIT_FAILURE;\n }\n\n if (stlplus::extension_part(sOutFile) != \"mvs\") {\n std::cerr << std::endl\n << \"Invalid output file extension: \" << sOutFile << std::endl\n << \"You must use a filename with a .mvs extension.\" << std::endl;\n return EXIT_FAILURE;\n }\n\n \/\/ Read the input SfM scene\n SfM_Data sfm_data;\n if (!Load(sfm_data, sSfM_Data_Filename, ESfM_Data(ALL))) {\n std::cerr << std::endl\n << \"The input SfM_Data file \\\"\"<< sSfM_Data_Filename << \"\\\" cannot be read.\" << std::endl;\n return EXIT_FAILURE;\n }\n\n \/\/ Export OpenMVS data structure\n if (!exportToOpenMVS(sfm_data, sOutFile, sOutDir, iNumThreads))\n {\n std::cerr << std::endl\n << \"The output openMVS scene file cannot be written\" << std::endl;\n return EXIT_FAILURE;\n }\n\n return EXIT_SUCCESS;\n}\n<|endoftext|>"} {"text":"<commit_before>#include <cmath>\n\n#include <glm\/gtc\/matrix_transform.hpp>\n#include <SDL2\/SDL.h>\n\n#include <zombye\/core\/game.hpp>\n#include <zombye\/ecs\/entity_manager.hpp>\n#include <zombye\/gameplay\/states\/play_state.hpp>\n#include <zombye\/input\/input_manager.hpp>\n#include <zombye\/input\/input_system.hpp>\n#include <zombye\/input\/joystick.hpp>\n#include <zombye\/input\/mouse.hpp>\n#include <zombye\/physics\/shapes\/box_shape.hpp>\n#include <zombye\/physics\/physics_component.hpp>\n#include <zombye\/rendering\/animation_component.hpp>\n#include <zombye\/rendering\/camera_component.hpp>\n#include <zombye\/rendering\/rendering_system.hpp>\n#include <zombye\/scripting\/scripting_system.hpp>\n#include <zombye\/utils\/logger.hpp>\n#include <zombye\/utils\/state_machine.hpp>\n\nzombye::play_state::play_state(zombye::state_machine *sm) : sm_(sm) {\n auto input = sm->get_game()->input();\n input_ = input->create_manager();\n\n \/*input_->register_action(\"FIRE\", []() {\n zombye::log(\"Peng Peng!\");\n });*\/\n input_->register_actions(*sm->get_game(), \"scripts\/input\/play_state.as\");\n\n input_->register_action(\"FIRE_END\", []() {\n zombye::log(\"No more peng :(\");\n });\n\n auto first_joystick = input->first_joystick();\n\n if(first_joystick) {\n input_->register_event(\"FIRE\", first_joystick->button_A());\n input_->register_event(\"FIRE\", first_joystick->button_B());\n\n input_->register_up_event(\"FIRE_END\", first_joystick->button_A());\n input_->register_up_event(\"FIRE_END\", first_joystick->button_B());\n }\n\n input_->register_event(\"FIRE\", input->mouse()->left_button());\n input_->register_keyboard_event(\"FIRE\", \"space\");\n input_->register_up_event(\"FIRE_END\", input->mouse()->left_button());\n input_->register_keyboard_up_event(\"FIRE_END\", \"space\");\n\n input_->register_keyboard_event(\"move_forward_begin\", \"w\");\n input_->register_keyboard_up_event(\"move_forward_end\", \"w\");\n input_->register_keyboard_event(\"move_backward_begin\", \"s\");\n input_->register_keyboard_up_event(\"move_backward_end\", \"s\");\n input_->register_keyboard_event(\"move_right_begin\", \"d\");\n input_->register_keyboard_up_event(\"move_right_end\", \"d\");\n input_->register_keyboard_event(\"move_left_begin\", \"a\");\n input_->register_keyboard_up_event(\"move_left_end\", \"a\");\n}\n\nvoid zombye::play_state::enter() {\n zombye::log(\"enter play state\");\n\n auto& game = *sm_->get_game();\n\n auto& scripting_system = game.scripting_system();\n scripting_system.begin_module(\"MyModule\");\n scripting_system.load_script(\"scripts\/test.as\");\n scripting_system.end_module();\n scripting_system.exec(\"void main()\", \"MyModule\");\n}\n\nvoid zombye::play_state::leave() {\n zombye::log(\"leave play state\");\n}\n\nvoid zombye::play_state::update(float delta_time) {\n input_->handle_input();\n}\n<commit_msg>Remove hardcoded action\/key registration and load input config instead.<commit_after>#include <cmath>\n\n#include <glm\/gtc\/matrix_transform.hpp>\n#include <SDL2\/SDL.h>\n\n#include <zombye\/core\/game.hpp>\n#include <zombye\/ecs\/entity_manager.hpp>\n#include <zombye\/gameplay\/states\/play_state.hpp>\n#include <zombye\/input\/input_manager.hpp>\n#include <zombye\/input\/input_system.hpp>\n#include <zombye\/input\/joystick.hpp>\n#include <zombye\/input\/mouse.hpp>\n#include <zombye\/physics\/shapes\/box_shape.hpp>\n#include <zombye\/physics\/physics_component.hpp>\n#include <zombye\/rendering\/animation_component.hpp>\n#include <zombye\/rendering\/camera_component.hpp>\n#include <zombye\/rendering\/rendering_system.hpp>\n#include <zombye\/scripting\/scripting_system.hpp>\n#include <zombye\/utils\/logger.hpp>\n#include <zombye\/utils\/state_machine.hpp>\n\nzombye::play_state::play_state(zombye::state_machine *sm) : sm_(sm) {\n auto input = sm->get_game()->input();\n input_ = input->create_manager();\n\n \/*input_->register_action(\"FIRE\", []() {\n zombye::log(\"Peng Peng!\");\n });*\/\n input_->register_actions(*sm->get_game(), \"scripts\/input\/play_state.as\");\n input_->load_config(*sm->get_game(), \"config\/input\/play_state.json\");\n\n input_->register_action(\"FIRE_END\", []() {\n zombye::log(\"No more peng :(\");\n });\n\n auto first_joystick = input->first_joystick();\n\n if(first_joystick) {\n input_->register_event(\"FIRE\", first_joystick->button_A());\n input_->register_event(\"FIRE\", first_joystick->button_B());\n\n input_->register_up_event(\"FIRE_END\", first_joystick->button_A());\n input_->register_up_event(\"FIRE_END\", first_joystick->button_B());\n }\n\n input_->register_event(\"FIRE\", input->mouse()->left_button());\n input_->register_keyboard_event(\"FIRE\", \"space\");\n input_->register_up_event(\"FIRE_END\", input->mouse()->left_button());\n input_->register_keyboard_up_event(\"FIRE_END\", \"space\");\n}\n\nvoid zombye::play_state::enter() {\n zombye::log(\"enter play state\");\n\n auto& game = *sm_->get_game();\n\n auto& scripting_system = game.scripting_system();\n scripting_system.begin_module(\"MyModule\");\n scripting_system.load_script(\"scripts\/test.as\");\n scripting_system.end_module();\n scripting_system.exec(\"void main()\", \"MyModule\");\n}\n\nvoid zombye::play_state::leave() {\n zombye::log(\"leave play state\");\n}\n\nvoid zombye::play_state::update(float delta_time) {\n input_->handle_input();\n}\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: localfilehelper.cxx,v $\n *\n * $Revision: 1.15 $\n *\n * last change: $Author: rt $ $Date: 2005-09-09 09:50:32 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef _COM_SUN_STAR_SDBC_XRESULTSET_HPP_\n#include <com\/sun\/star\/sdbc\/XResultSet.hpp>\n#endif\n#ifndef _COM_SUN_STAR_UCB_XCONTENTACCESS_HPP_\n#include <com\/sun\/star\/ucb\/XContentAccess.hpp>\n#endif\n\n#ifndef _COM_SUN_STAR_UCB_COMMANDABORTEDEXCEPTION_HPP_\n#include <com\/sun\/star\/ucb\/CommandAbortedException.hpp>\n#endif\n\n#include <unotools\/localfilehelper.hxx>\n#include <ucbhelper\/fileidentifierconverter.hxx>\n#include <ucbhelper\/contentbroker.hxx>\n#include <rtl\/ustring.hxx>\n#include <osl\/file.hxx>\n#include <tools\/debug.hxx>\n#include <tools\/list.hxx>\n#include <tools\/urlobj.hxx>\n#include <ucbhelper\/content.hxx>\n\nusing namespace ::osl;\nusing namespace ::com::sun::star::uno;\nusing namespace ::com::sun::star::ucb;\n\nnamespace utl\n{\n\nsal_Bool LocalFileHelper::ConvertSystemPathToURL( const String& rName, const String& rBaseURL, String& rReturn )\n{\n rReturn = ::rtl::OUString();\n\n ::ucb::ContentBroker* pBroker = ::ucb::ContentBroker::get();\n if ( !pBroker )\n {\n rtl::OUString aRet;\n if ( FileBase::getFileURLFromSystemPath( rName, aRet ) == FileBase::E_None )\n rReturn = aRet;\n }\n else\n {\n ::com::sun::star::uno::Reference< ::com::sun::star::ucb::XContentProviderManager > xManager =\n pBroker->getContentProviderManagerInterface();\n try\n {\n rReturn = ::ucb::getFileURLFromSystemPath( xManager, rBaseURL, rName );\n }\n catch ( ::com::sun::star::uno::RuntimeException& )\n {\n return sal_False;\n }\n }\n\n return ( rReturn.Len() != 0 );\n}\n\nsal_Bool LocalFileHelper::ConvertURLToSystemPath( const String& rName, String& rReturn )\n{\n rReturn = ::rtl::OUString();\n ::ucb::ContentBroker* pBroker = ::ucb::ContentBroker::get();\n if ( !pBroker )\n {\n rtl::OUString aRet;\n if( FileBase::getSystemPathFromFileURL( rName, aRet ) == FileBase::E_None )\n rReturn = aRet;\n }\n else\n {\n ::com::sun::star::uno::Reference< ::com::sun::star::ucb::XContentProviderManager > xManager =\n pBroker->getContentProviderManagerInterface();\n try\n {\n rReturn = ::ucb::getSystemPathFromFileURL( xManager, rName );\n }\n catch ( ::com::sun::star::uno::RuntimeException& )\n {\n }\n }\n\n return ( rReturn.Len() != 0 );\n}\n\nsal_Bool LocalFileHelper::ConvertPhysicalNameToURL( const String& rName, String& rReturn )\n{\n rReturn = ::rtl::OUString();\n ::ucb::ContentBroker* pBroker = ::ucb::ContentBroker::get();\n if ( !pBroker )\n {\n rtl::OUString aRet;\n if ( FileBase::getFileURLFromSystemPath( rName, aRet ) == FileBase::E_None )\n rReturn = aRet;\n }\n else\n {\n ::com::sun::star::uno::Reference< ::com::sun::star::ucb::XContentProviderManager > xManager =\n pBroker->getContentProviderManagerInterface();\n\n try\n {\n rtl::OUString aBase( ::ucb::getLocalFileURL( xManager ) );\n rReturn = ::ucb::getFileURLFromSystemPath( xManager, aBase, rName );\n }\n catch ( ::com::sun::star::uno::RuntimeException& )\n {\n }\n }\n\n return ( rReturn.Len() != 0 );\n}\n\nsal_Bool LocalFileHelper::ConvertURLToPhysicalName( const String& rName, String& rReturn )\n{\n rReturn = ::rtl::OUString();\n ::ucb::ContentBroker* pBroker = ::ucb::ContentBroker::get();\n if ( !pBroker )\n {\n ::rtl::OUString aRet;\n if ( FileBase::getSystemPathFromFileURL( rName, aRet ) == FileBase::E_None )\n rReturn = aRet;\n }\n else\n {\n ::com::sun::star::uno::Reference< ::com::sun::star::ucb::XContentProviderManager > xManager =\n pBroker->getContentProviderManagerInterface();\n try\n {\n INetURLObject aObj( rName );\n INetURLObject aLocal( ::ucb::getLocalFileURL( xManager ) );\n if ( aObj.GetProtocol() == aLocal.GetProtocol() )\n rReturn = ::ucb::getSystemPathFromFileURL( xManager, rName );\n }\n catch ( ::com::sun::star::uno::RuntimeException& )\n {\n }\n }\n\n return ( rReturn.Len() != 0 );\n}\n\nsal_Bool LocalFileHelper::IsLocalFile( const String& rName )\n{\n String aTmp;\n return ConvertURLToPhysicalName( rName, aTmp );\n}\n\nsal_Bool LocalFileHelper::IsFileContent( const String& rName )\n{\n String aTmp;\n return ConvertURLToSystemPath( rName, aTmp );\n}\n\nDECLARE_LIST( StringList_Impl, ::rtl::OUString* )\n\n::com::sun::star::uno::Sequence < ::rtl::OUString > LocalFileHelper::GetFolderContents( const ::rtl::OUString& rFolder, sal_Bool bFolder )\n{\n StringList_Impl* pFiles = NULL;\n try\n {\n ::ucb::Content aCnt( rFolder, Reference< XCommandEnvironment > () );\n Reference< ::com::sun::star::sdbc::XResultSet > xResultSet;\n ::com::sun::star::uno::Sequence< ::rtl::OUString > aProps(1);\n ::rtl::OUString* pProps = aProps.getArray();\n pProps[0] == ::rtl::OUString::createFromAscii( \"Url\" );\n\n try\n {\n ::ucb::ResultSetInclude eInclude = bFolder ? ::ucb::INCLUDE_FOLDERS_AND_DOCUMENTS : ::ucb::INCLUDE_DOCUMENTS_ONLY;\n xResultSet = aCnt.createCursor( aProps, eInclude );\n }\n catch( ::com::sun::star::ucb::CommandAbortedException& )\n {\n }\n catch( Exception& )\n {\n }\n\n if ( xResultSet.is() )\n {\n pFiles = new StringList_Impl;\n Reference< XContentAccess > xContentAccess( xResultSet, UNO_QUERY );\n try\n {\n while ( xResultSet->next() )\n {\n ::rtl::OUString aId = xContentAccess->queryContentIdentifierString();\n ::rtl::OUString* pFile = new ::rtl::OUString( aId );\n pFiles->Insert( pFile, LIST_APPEND );\n }\n }\n catch( ::com::sun::star::ucb::CommandAbortedException& )\n {\n }\n catch( Exception& )\n {\n }\n }\n }\n catch( Exception& )\n {\n }\n\n if ( pFiles )\n {\n ULONG nCount = pFiles->Count();\n Sequence < ::rtl::OUString > aRet( nCount );\n ::rtl::OUString* pRet = aRet.getArray();\n for ( USHORT i = 0; i < nCount; ++i )\n {\n ::rtl::OUString* pFile = pFiles->GetObject(i);\n pRet[i] = *( pFile );\n delete pFile;\n }\n delete pFiles;\n return aRet;\n }\n else\n return Sequence < ::rtl::OUString > ();\n}\n\n};\n<commit_msg>INTEGRATION: CWS warnings01 (1.15.16); FILE MERGED 2005\/10\/27 10:51:18 pl 1.15.16.1: #i55991# removed warnings for solaris platform<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: localfilehelper.cxx,v $\n *\n * $Revision: 1.16 $\n *\n * last change: $Author: hr $ $Date: 2006-06-19 14:09:39 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef _COM_SUN_STAR_SDBC_XRESULTSET_HPP_\n#include <com\/sun\/star\/sdbc\/XResultSet.hpp>\n#endif\n#ifndef _COM_SUN_STAR_UCB_XCONTENTACCESS_HPP_\n#include <com\/sun\/star\/ucb\/XContentAccess.hpp>\n#endif\n\n#ifndef _COM_SUN_STAR_UCB_COMMANDABORTEDEXCEPTION_HPP_\n#include <com\/sun\/star\/ucb\/CommandAbortedException.hpp>\n#endif\n\n#include <unotools\/localfilehelper.hxx>\n#include <ucbhelper\/fileidentifierconverter.hxx>\n#include <ucbhelper\/contentbroker.hxx>\n#include <rtl\/ustring.hxx>\n#include <osl\/file.hxx>\n#include <tools\/debug.hxx>\n#include <tools\/list.hxx>\n#include <tools\/urlobj.hxx>\n#include <ucbhelper\/content.hxx>\n\nusing namespace ::osl;\nusing namespace ::com::sun::star::uno;\nusing namespace ::com::sun::star::ucb;\n\nnamespace utl\n{\n\nsal_Bool LocalFileHelper::ConvertSystemPathToURL( const String& rName, const String& rBaseURL, String& rReturn )\n{\n rReturn = ::rtl::OUString();\n\n ::ucb::ContentBroker* pBroker = ::ucb::ContentBroker::get();\n if ( !pBroker )\n {\n rtl::OUString aRet;\n if ( FileBase::getFileURLFromSystemPath( rName, aRet ) == FileBase::E_None )\n rReturn = aRet;\n }\n else\n {\n ::com::sun::star::uno::Reference< ::com::sun::star::ucb::XContentProviderManager > xManager =\n pBroker->getContentProviderManagerInterface();\n try\n {\n rReturn = ::ucb::getFileURLFromSystemPath( xManager, rBaseURL, rName );\n }\n catch ( ::com::sun::star::uno::RuntimeException& )\n {\n return sal_False;\n }\n }\n\n return ( rReturn.Len() != 0 );\n}\n\nsal_Bool LocalFileHelper::ConvertURLToSystemPath( const String& rName, String& rReturn )\n{\n rReturn = ::rtl::OUString();\n ::ucb::ContentBroker* pBroker = ::ucb::ContentBroker::get();\n if ( !pBroker )\n {\n rtl::OUString aRet;\n if( FileBase::getSystemPathFromFileURL( rName, aRet ) == FileBase::E_None )\n rReturn = aRet;\n }\n else\n {\n ::com::sun::star::uno::Reference< ::com::sun::star::ucb::XContentProviderManager > xManager =\n pBroker->getContentProviderManagerInterface();\n try\n {\n rReturn = ::ucb::getSystemPathFromFileURL( xManager, rName );\n }\n catch ( ::com::sun::star::uno::RuntimeException& )\n {\n }\n }\n\n return ( rReturn.Len() != 0 );\n}\n\nsal_Bool LocalFileHelper::ConvertPhysicalNameToURL( const String& rName, String& rReturn )\n{\n rReturn = ::rtl::OUString();\n ::ucb::ContentBroker* pBroker = ::ucb::ContentBroker::get();\n if ( !pBroker )\n {\n rtl::OUString aRet;\n if ( FileBase::getFileURLFromSystemPath( rName, aRet ) == FileBase::E_None )\n rReturn = aRet;\n }\n else\n {\n ::com::sun::star::uno::Reference< ::com::sun::star::ucb::XContentProviderManager > xManager =\n pBroker->getContentProviderManagerInterface();\n\n try\n {\n rtl::OUString aBase( ::ucb::getLocalFileURL( xManager ) );\n rReturn = ::ucb::getFileURLFromSystemPath( xManager, aBase, rName );\n }\n catch ( ::com::sun::star::uno::RuntimeException& )\n {\n }\n }\n\n return ( rReturn.Len() != 0 );\n}\n\nsal_Bool LocalFileHelper::ConvertURLToPhysicalName( const String& rName, String& rReturn )\n{\n rReturn = ::rtl::OUString();\n ::ucb::ContentBroker* pBroker = ::ucb::ContentBroker::get();\n if ( !pBroker )\n {\n ::rtl::OUString aRet;\n if ( FileBase::getSystemPathFromFileURL( rName, aRet ) == FileBase::E_None )\n rReturn = aRet;\n }\n else\n {\n ::com::sun::star::uno::Reference< ::com::sun::star::ucb::XContentProviderManager > xManager =\n pBroker->getContentProviderManagerInterface();\n try\n {\n INetURLObject aObj( rName );\n INetURLObject aLocal( ::ucb::getLocalFileURL( xManager ) );\n if ( aObj.GetProtocol() == aLocal.GetProtocol() )\n rReturn = ::ucb::getSystemPathFromFileURL( xManager, rName );\n }\n catch ( ::com::sun::star::uno::RuntimeException& )\n {\n }\n }\n\n return ( rReturn.Len() != 0 );\n}\n\nsal_Bool LocalFileHelper::IsLocalFile( const String& rName )\n{\n String aTmp;\n return ConvertURLToPhysicalName( rName, aTmp );\n}\n\nsal_Bool LocalFileHelper::IsFileContent( const String& rName )\n{\n String aTmp;\n return ConvertURLToSystemPath( rName, aTmp );\n}\n\nDECLARE_LIST( StringList_Impl, ::rtl::OUString* )\n\n::com::sun::star::uno::Sequence < ::rtl::OUString > LocalFileHelper::GetFolderContents( const ::rtl::OUString& rFolder, sal_Bool bFolder )\n{\n StringList_Impl* pFiles = NULL;\n try\n {\n ::ucb::Content aCnt( rFolder, Reference< XCommandEnvironment > () );\n Reference< ::com::sun::star::sdbc::XResultSet > xResultSet;\n ::com::sun::star::uno::Sequence< ::rtl::OUString > aProps(1);\n ::rtl::OUString* pProps = aProps.getArray();\n pProps[0] = ::rtl::OUString::createFromAscii( \"Url\" );\n\n try\n {\n ::ucb::ResultSetInclude eInclude = bFolder ? ::ucb::INCLUDE_FOLDERS_AND_DOCUMENTS : ::ucb::INCLUDE_DOCUMENTS_ONLY;\n xResultSet = aCnt.createCursor( aProps, eInclude );\n }\n catch( ::com::sun::star::ucb::CommandAbortedException& )\n {\n }\n catch( Exception& )\n {\n }\n\n if ( xResultSet.is() )\n {\n pFiles = new StringList_Impl;\n Reference< XContentAccess > xContentAccess( xResultSet, UNO_QUERY );\n try\n {\n while ( xResultSet->next() )\n {\n ::rtl::OUString aId = xContentAccess->queryContentIdentifierString();\n ::rtl::OUString* pFile = new ::rtl::OUString( aId );\n pFiles->Insert( pFile, LIST_APPEND );\n }\n }\n catch( ::com::sun::star::ucb::CommandAbortedException& )\n {\n }\n catch( Exception& )\n {\n }\n }\n }\n catch( Exception& )\n {\n }\n\n if ( pFiles )\n {\n ULONG nCount = pFiles->Count();\n Sequence < ::rtl::OUString > aRet( nCount );\n ::rtl::OUString* pRet = aRet.getArray();\n for ( USHORT i = 0; i < nCount; ++i )\n {\n ::rtl::OUString* pFile = pFiles->GetObject(i);\n pRet[i] = *( pFile );\n delete pFile;\n }\n delete pFiles;\n return aRet;\n }\n else\n return Sequence < ::rtl::OUString > ();\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ This file is part of SWGANH which is released under the MIT license.\n\/\/ See file LICENSE or go to http:\/\/swganh.com\/LICENSE\n\n#include \"connection_service.h\"\n\n#include <boost\/bind.hpp>\n#include <boost\/date_time\/posix_time\/posix_time.hpp>\n#include <boost\/lexical_cast.hpp>\n#include \"swganh\/logger.h\"\n\n#include \"swganh\/crc.h\"\n#include \"swganh\/event_dispatcher.h\"\n#include \"swganh\/network\/resolver.h\"\n#include \"swganh\/network\/server.h\"\n#include \"swganh\/plugin\/plugin_manager.h\"\n#include \"swganh\/service\/service_directory_interface.h\"\n#include \"swganh\/service\/service_manager.h\"\n\n#include \"swganh\/app\/swganh_kernel.h\"\n\n#include \"swganh_core\/character\/character_service_interface.h\"\n#include \"swganh_core\/character\/character_provider_interface.h\"\n#include \"ping_server.h\"\n#include \"connection_client.h\"\n#include \"swganh_core\/connection\/providers\/session_provider_interface.h\"\n\n#include \"swganh_core\/object\/object.h\"\n#include \"swganh_core\/object\/player\/player.h\"\n\nusing namespace swganh::app;\nusing namespace swganh::event_dispatcher;\nusing namespace swganh::network;\nusing namespace swganh::service;\nusing namespace swganh::character;\nusing namespace swganh::connection;\nusing namespace swganh::connection;\nusing namespace swganh::login;\nusing namespace swganh::messages;\nusing namespace swganh::object;\nusing namespace swganh::simulation;\n\nusing namespace std;\n\nusing swganh::ValueEvent;\n\nusing boost::asio::ip::udp;\nusing swganh::app::SwganhKernel;\n\nConnectionService::ConnectionService(\n string listen_address,\n uint16_t listen_port,\n uint16_t ping_port,\n SwganhKernel* kernel)\n : ConnectionServiceInterface(kernel)\n , kernel_(kernel)\n , ping_server_(nullptr)\n\t, active_(kernel->GetIoThreadPool())\n , listen_address_(listen_address)\n , listen_port_(listen_port)\n , ping_port_(ping_port)\n{ \n SetServiceDescription(ServiceDescription(\n \"Connection Service\",\n \"connection\",\n \"0.1\",\n swganh::network::resolve_to_string(listen_address_),\n 0,\n listen_port_,\n ping_port_));\n}\n\nConnectionService::~ConnectionService()\n{\n session_timer_->cancel();\n}\n\nvoid ConnectionService::Initialize()\n{\n session_provider_ = kernel_->GetPluginManager()->CreateObject<swganh::connection::providers::SessionProviderInterface>(\"Login::SessionProvider\");\n character_provider_ = kernel_->GetPluginManager()->CreateObject<CharacterProviderInterface>(\"Character::CharacterProvider\");\n\n character_service_ = kernel_->GetServiceManager()->GetService<CharacterServiceInterface>(\"CharacterService\");\n login_service_ = kernel_->GetServiceManager()->GetService<LoginServiceInterface>(\"LoginService\");\n simulation_service_ = kernel_->GetServiceManager()->GetService<SimulationServiceInterface>(\"SimulationService\");\n}\n\nvoid ConnectionService::Startup() {\n\tping_server_ = make_shared<PingServer>(kernel_->GetIoThreadPool(), ping_port_);\n\n character_service_ = kernel_->GetServiceManager()->GetService<CharacterServiceInterface>(\"CharacterService\");\n login_service_ = kernel_->GetServiceManager()->GetService<LoginServiceInterface>(\"LoginService\");\n simulation_service_ = kernel_->GetServiceManager()->GetService<SimulationServiceInterface>(\"SimulationService\");\n \n RegisterMessageHandler(&ConnectionService::HandleClientIdMsg_, this);\n RegisterMessageHandler(&ConnectionService::HandleCmdSceneReady_, this);\n\n StartListening(listen_port_);\n}\n\nvoid ConnectionService::Shutdown() {\n StopListening();\n}\n\nconst string& ConnectionService::listen_address() {\n return listen_address_;\n}\n\nuint16_t ConnectionService::listen_port() {\n return listen_port_;\n}\n\nshared_ptr<Session> ConnectionService::CreateSession(const udp::endpoint& endpoint)\n{\n shared_ptr<ConnectionClient> session = nullptr;\n\n {\n boost::lock_guard<boost::mutex> lg(session_map_mutex_);\n if (session_map_.find(endpoint) == session_map_.end())\n {\n session = make_shared<ConnectionClient>(this, kernel_->GetCpuThreadPool(), endpoint);\n session_map_.insert(make_pair(endpoint, session));\n\t\t\tLOG(info) << \"Created Connection Service Session for \" << endpoint.address().to_string();\n }\n }\n\n return session;\n}\n\nbool ConnectionService::RemoveSession(std::shared_ptr<Session> session) {\n {\n boost::lock_guard<boost::mutex> lg(session_map_mutex_);\n session_map_.erase(session->remote_endpoint());\n\t}\n\n auto connection_client = static_pointer_cast<ConnectionClient>(session);\n\n if (auto controller = connection_client->GetController())\n {\n kernel_->GetEventDispatcher()->Dispatch(std::make_shared<ValueEvent<uint64_t>>(\"Connection::ControllerConnectionClosed\", controller->GetId()));\n\t}\n\n LOG(info) << \"Removing disconnected client\";\n\tsession_provider_->EndGameSession(connection_client->GetPlayerId());\n\n\t\n return true;\n}\n\nshared_ptr<Session> ConnectionService::GetSession(const udp::endpoint& endpoint) {\n {\n boost::lock_guard<boost::mutex> lg(session_map_mutex_);\n\n auto find_iter = session_map_.find(endpoint);\n if (find_iter != session_map_.end())\n {\n\t\t\treturn find_iter->second;\n }\n }\n\n return CreateSession(endpoint);\n}\n\nstd::shared_ptr<ConnectionClientInterface> ConnectionService::FindConnectionByPlayerId(uint64_t player_id)\n{\n shared_ptr<ConnectionClientInterface> connection = nullptr;\n\n {\n boost::lock_guard<boost::mutex> lg(session_map_mutex_);\n\n auto find_iter = find_if(\n begin(session_map_),\n end(session_map_),\n [player_id] (SessionMap::value_type& item)\n {\n return item.second->GetPlayerId() == player_id;\n });\n\n if (find_iter != end(session_map_))\n {\n connection = find_iter->second;\n }\n }\n\n return connection;\n}\n\nvoid ConnectionService::HandleCmdSceneReady_(\n const shared_ptr<ConnectionClientInterface>& client, \n CmdSceneReady* message)\n{\n DLOG(info) << \"Handling CmdSceneReady\";\n\n client->SendTo(CmdSceneReady());\n\n\tauto object = simulation_service_->GetObjectById(client->GetController()->GetId());\n\n kernel_->GetEventDispatcher()->Dispatch(\n make_shared<ValueEvent<shared_ptr<Object>>>(\"ObjectReadyEvent\", object));\n}\n\nvoid ConnectionService::HandleClientIdMsg_(\n const shared_ptr<ConnectionClientInterface>& client, \n ClientIdMsg* message)\n{\n DLOG(info) << \"Handling ClientIdMsg\";\n\n \/\/ get session key from login service\n uint32_t account_id = login_service_->GetAccountBySessionKey(message->session_hash);\n\n \/\/ authorized\n if (! account_id) {\n LOG(warning) << \"Account_id not found from session key, unauthorized access.\";\n return;\n }\n\n \/\/ gets player from account\n uint64_t player_id = session_provider_->GetPlayerId(account_id);\n\n \/\/ authorized\n if (! player_id) {\n LOG(warning) << \"No player found for the requested account, unauthorized access.\";\n return;\n }\n\n auto existing_session_connection = FindConnectionByPlayerId(player_id);\n if (existing_session_connection)\n {\n existing_session_connection->Close();\n }\n\n \/\/ creates a new session and stores it for later use\n if (!session_provider_->CreateGameSession(player_id, client->connection_id())) {\n DLOG(warning) << \"Player Not Inserted into Session Map because No Game Session Created!\";\n }\n\n client->Connect(account_id, player_id);\n\n ClientPermissionsMessage client_permissions;\n client_permissions.galaxy_available = kernel_->GetServiceDirectory()->galaxy().status();\n client_permissions.available_character_slots = static_cast<uint8_t>(character_provider_->GetMaxCharacters(account_id));\n \/\/\/ @TODO: Replace with configurable value\n client_permissions.unlimited_characters = 0;\n\n client->SendTo(client_permissions);\n}\n<commit_msg>Explicitly stop controlling the object before dispatching the ControllerConnectionClosed event<commit_after>\/\/ This file is part of SWGANH which is released under the MIT license.\n\/\/ See file LICENSE or go to http:\/\/swganh.com\/LICENSE\n\n#include \"connection_service.h\"\n\n#include <boost\/bind.hpp>\n#include <boost\/date_time\/posix_time\/posix_time.hpp>\n#include <boost\/lexical_cast.hpp>\n#include \"swganh\/logger.h\"\n\n#include \"swganh\/crc.h\"\n#include \"swganh\/event_dispatcher.h\"\n#include \"swganh\/network\/resolver.h\"\n#include \"swganh\/network\/server.h\"\n#include \"swganh\/plugin\/plugin_manager.h\"\n#include \"swganh\/service\/service_directory_interface.h\"\n#include \"swganh\/service\/service_manager.h\"\n\n#include \"swganh\/app\/swganh_kernel.h\"\n\n#include \"swganh_core\/character\/character_service_interface.h\"\n#include \"swganh_core\/character\/character_provider_interface.h\"\n#include \"ping_server.h\"\n#include \"connection_client.h\"\n#include \"swganh_core\/connection\/providers\/session_provider_interface.h\"\n\n#include \"swganh_core\/object\/object.h\"\n#include \"swganh_core\/object\/player\/player.h\"\n\nusing namespace swganh::app;\nusing namespace swganh::event_dispatcher;\nusing namespace swganh::network;\nusing namespace swganh::service;\nusing namespace swganh::character;\nusing namespace swganh::connection;\nusing namespace swganh::connection;\nusing namespace swganh::login;\nusing namespace swganh::messages;\nusing namespace swganh::object;\nusing namespace swganh::simulation;\n\nusing namespace std;\n\nusing swganh::ValueEvent;\n\nusing boost::asio::ip::udp;\nusing swganh::app::SwganhKernel;\n\nConnectionService::ConnectionService(\n string listen_address,\n uint16_t listen_port,\n uint16_t ping_port,\n SwganhKernel* kernel)\n : ConnectionServiceInterface(kernel)\n , kernel_(kernel)\n , ping_server_(nullptr)\n\t, active_(kernel->GetIoThreadPool())\n , listen_address_(listen_address)\n , listen_port_(listen_port)\n , ping_port_(ping_port)\n{ \n SetServiceDescription(ServiceDescription(\n \"Connection Service\",\n \"connection\",\n \"0.1\",\n swganh::network::resolve_to_string(listen_address_),\n 0,\n listen_port_,\n ping_port_));\n}\n\nConnectionService::~ConnectionService()\n{\n session_timer_->cancel();\n}\n\nvoid ConnectionService::Initialize()\n{\n session_provider_ = kernel_->GetPluginManager()->CreateObject<swganh::connection::providers::SessionProviderInterface>(\"Login::SessionProvider\");\n character_provider_ = kernel_->GetPluginManager()->CreateObject<CharacterProviderInterface>(\"Character::CharacterProvider\");\n\n character_service_ = kernel_->GetServiceManager()->GetService<CharacterServiceInterface>(\"CharacterService\");\n login_service_ = kernel_->GetServiceManager()->GetService<LoginServiceInterface>(\"LoginService\");\n simulation_service_ = kernel_->GetServiceManager()->GetService<SimulationServiceInterface>(\"SimulationService\");\n}\n\nvoid ConnectionService::Startup() {\n\tping_server_ = make_shared<PingServer>(kernel_->GetIoThreadPool(), ping_port_);\n\n character_service_ = kernel_->GetServiceManager()->GetService<CharacterServiceInterface>(\"CharacterService\");\n login_service_ = kernel_->GetServiceManager()->GetService<LoginServiceInterface>(\"LoginService\");\n simulation_service_ = kernel_->GetServiceManager()->GetService<SimulationServiceInterface>(\"SimulationService\");\n \n RegisterMessageHandler(&ConnectionService::HandleClientIdMsg_, this);\n RegisterMessageHandler(&ConnectionService::HandleCmdSceneReady_, this);\n\n StartListening(listen_port_);\n}\n\nvoid ConnectionService::Shutdown() {\n StopListening();\n}\n\nconst string& ConnectionService::listen_address() {\n return listen_address_;\n}\n\nuint16_t ConnectionService::listen_port() {\n return listen_port_;\n}\n\nshared_ptr<Session> ConnectionService::CreateSession(const udp::endpoint& endpoint)\n{\n shared_ptr<ConnectionClient> session = nullptr;\n\n {\n boost::lock_guard<boost::mutex> lg(session_map_mutex_);\n if (session_map_.find(endpoint) == session_map_.end())\n {\n session = make_shared<ConnectionClient>(this, kernel_->GetCpuThreadPool(), endpoint);\n session_map_.insert(make_pair(endpoint, session));\n\t\t\tLOG(info) << \"Created Connection Service Session for \" << endpoint.address().to_string();\n }\n }\n\n return session;\n}\n\nbool ConnectionService::RemoveSession(std::shared_ptr<Session> session) {\n {\n boost::lock_guard<boost::mutex> lg(session_map_mutex_);\n session_map_.erase(session->remote_endpoint());\n\t}\n\n auto connection_client = static_pointer_cast<ConnectionClient>(session);\n\n if (auto controller = connection_client->GetController()) {\n simulation_service_->StopControllingObject(controller->GetId());\n\n kernel_->GetEventDispatcher()->Dispatch(std::make_shared<ValueEvent<uint64_t>>(\"Connection::ControllerConnectionClosed\", controller->GetId()));\n\t}\n\n LOG(info) << \"Removing disconnected client\";\n\tsession_provider_->EndGameSession(connection_client->GetPlayerId());\n\n\t\n return true;\n}\n\nshared_ptr<Session> ConnectionService::GetSession(const udp::endpoint& endpoint) {\n {\n boost::lock_guard<boost::mutex> lg(session_map_mutex_);\n\n auto find_iter = session_map_.find(endpoint);\n if (find_iter != session_map_.end())\n {\n\t\t\treturn find_iter->second;\n }\n }\n\n return CreateSession(endpoint);\n}\n\nstd::shared_ptr<ConnectionClientInterface> ConnectionService::FindConnectionByPlayerId(uint64_t player_id)\n{\n shared_ptr<ConnectionClientInterface> connection = nullptr;\n\n {\n boost::lock_guard<boost::mutex> lg(session_map_mutex_);\n\n auto find_iter = find_if(\n begin(session_map_),\n end(session_map_),\n [player_id] (SessionMap::value_type& item)\n {\n return item.second->GetPlayerId() == player_id;\n });\n\n if (find_iter != end(session_map_))\n {\n connection = find_iter->second;\n }\n }\n\n return connection;\n}\n\nvoid ConnectionService::HandleCmdSceneReady_(\n const shared_ptr<ConnectionClientInterface>& client, \n CmdSceneReady* message)\n{\n DLOG(info) << \"Handling CmdSceneReady\";\n\n client->SendTo(CmdSceneReady());\n\n\tauto object = simulation_service_->GetObjectById(client->GetController()->GetId());\n\n kernel_->GetEventDispatcher()->Dispatch(\n make_shared<ValueEvent<shared_ptr<Object>>>(\"ObjectReadyEvent\", object));\n}\n\nvoid ConnectionService::HandleClientIdMsg_(\n const shared_ptr<ConnectionClientInterface>& client, \n ClientIdMsg* message)\n{\n DLOG(info) << \"Handling ClientIdMsg\";\n\n \/\/ get session key from login service\n uint32_t account_id = login_service_->GetAccountBySessionKey(message->session_hash);\n\n \/\/ authorized\n if (! account_id) {\n LOG(warning) << \"Account_id not found from session key, unauthorized access.\";\n return;\n }\n\n \/\/ gets player from account\n uint64_t player_id = session_provider_->GetPlayerId(account_id);\n\n \/\/ authorized\n if (! player_id) {\n LOG(warning) << \"No player found for the requested account, unauthorized access.\";\n return;\n }\n\n auto existing_session_connection = FindConnectionByPlayerId(player_id);\n if (existing_session_connection)\n {\n existing_session_connection->Close();\n }\n\n \/\/ creates a new session and stores it for later use\n if (!session_provider_->CreateGameSession(player_id, client->connection_id())) {\n DLOG(warning) << \"Player Not Inserted into Session Map because No Game Session Created!\";\n }\n\n client->Connect(account_id, player_id);\n\n ClientPermissionsMessage client_permissions;\n client_permissions.galaxy_available = kernel_->GetServiceDirectory()->galaxy().status();\n client_permissions.available_character_slots = static_cast<uint8_t>(character_provider_->GetMaxCharacters(account_id));\n \/\/\/ @TODO: Replace with configurable value\n client_permissions.unlimited_characters = 0;\n\n client->SendTo(client_permissions);\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Software License Agreement (BSD License)\n *\n * Point Cloud Library (PCL) - www.pointclouds.org\n * Copyright (c) 2012-, Open Perception, Inc.\n *\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following\n * disclaimer in the documentation and\/or other materials provided\n * with the distribution.\n * * Neither the name of the copyright holder(s) nor the names of its\n * contributors may be used to endorse or promote products derived\n * from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n *\/\n\n#ifndef PCL_FILTERS_IMPL_FRUSTUM_CULLING_HPP_\n#define PCL_FILTERS_IMPL_FRUSTUM_CULLING_HPP_\n\n#include <pcl\/filters\/frustum_culling.h>\n#include <vector>\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate <typename PointT> void\npcl::FrustumCulling<PointT>::applyFilter (PointCloud& output)\n{\n Eigen::Vector4f pl_n; \/\/ near plane \n Eigen::Vector4f pl_f; \/\/ far plane\n Eigen::Vector4f pl_t; \/\/ top plane\n Eigen::Vector4f pl_b; \/\/ bottom plane\n Eigen::Vector4f pl_r; \/\/ right plane\n Eigen::Vector4f pl_l; \/\/ left plane\n\n Eigen::Vector3f view = camera_pose_.block (0, 0, 3, 1); \/\/ view vector for the camera - first column of the rotation matrix\n Eigen::Vector3f up = camera_pose_.block (0, 1, 3, 1); \/\/ up vector for the camera - second column of the rotation matix\n Eigen::Vector3f right = camera_pose_.block (0, 2, 3, 1); \/\/ right vector for the camera - third column of the rotation matrix\n Eigen::Vector3f T = camera_pose_.block (0, 3, 3, 1); \/\/ The (X, Y, Z) position of the camera w.r.t origin\n\n vfov_ = float (vfov_ * M_PI \/ 180); \/\/ degrees to radians\n hfov_ = float (hfov_ * M_PI \/ 180); \/\/ degrees to radians\n \n float np_h = float (2 * tan (vfov_ \/ 2) * np_dist_); \/\/ near plane height\n float np_w = float (2 * tan (hfov_ \/ 2) * np_dist_); \/\/ near plane width\n\n\n float fp_h = float (2 * tan (vfov_ \/ 2) * fp_dist_); \/\/ far plane height\n float fp_w = float (2 * tan (hfov_ \/ 2) * fp_dist_); \/\/ far plane width\n\n Eigen::Vector3f fp_c (T + view * fp_dist_); \/\/ far plane center\n Eigen::Vector3f fp_tl (fp_c + (up * fp_h \/ 2) - (right * fp_w \/ 2)); \/\/ Top left corner of the far plane\n Eigen::Vector3f fp_tr (fp_c + (up * fp_h \/ 2) + (right * fp_w \/ 2)); \/\/ Top right corner of the far plane\n Eigen::Vector3f fp_bl (fp_c - (up * fp_h \/ 2) - (right * fp_w \/ 2)); \/\/ Bottom left corner of the far plane\n Eigen::Vector3f fp_br (fp_c - (up * fp_h \/ 2) + (right * fp_w \/ 2)); \/\/ Bottom right corner of the far plane\n\n Eigen::Vector3f np_c (T + view * np_dist_); \/\/ near plane center\n \/\/Eigen::Vector3f np_tl = np_c + (up * np_h\/2) - (right * np_w\/2); \/\/ Top left corner of the near plane\n Eigen::Vector3f np_tr (np_c + (up * np_h \/ 2) + (right * np_w \/ 2)); \/\/ Top right corner of the near plane\n Eigen::Vector3f np_bl (np_c - (up * np_h \/ 2) - (right * np_w \/ 2)); \/\/ Bottom left corner of the near plane\n Eigen::Vector3f np_br (np_c - (up * np_h \/ 2) + (right * np_w \/ 2)); \/\/ Bottom right corner of the near plane\n\n\n pl_f.block (0, 0, 3, 1) = (fp_bl - fp_br).cross (fp_tr - fp_br); \/\/ Far plane equation - cross product of the \n pl_f (3) = -fp_c.dot (pl_f.block (0, 0, 3, 1)); \/\/ perpendicular edges of the far plane\n\n pl_n.block (0, 0, 3, 1) = (np_tr - np_br).cross (np_bl - np_br); \/\/ Near plane equation - cross product of the \n pl_n (3) = -np_c.dot (pl_n.block (0, 0, 3, 1)); \/\/ perpendicular edges of the far plane\n\n Eigen::Vector3f a (fp_bl - T); \/\/ Vector connecting the camera and far plane bottom left\n Eigen::Vector3f b (fp_br - T); \/\/ Vector connecting the camera and far plane bottom right\n Eigen::Vector3f c (fp_tr - T); \/\/ Vector connecting the camera and far plane top right\n Eigen::Vector3f d (fp_tl - T); \/\/ Vector connecting the camera and far plane top left\n\n \/\/ Frustum and the vectors a, b, c and d. T is the position of the camera\n \/\/ _________\n \/\/ \/| . |\n \/\/ d \/ | c . |\n \/\/ \/ | __._____| \n \/\/ \/ \/ . .\n \/\/ a <---\/-\/ . .\n \/\/ \/ \/ . . b\n \/\/ \/ .\n \/\/ . \n \/\/ T\n \/\/\n\n pl_r.block (0, 0, 3, 1) = b.cross (c);\n pl_l.block (0, 0, 3, 1) = d.cross (a);\n pl_t.block (0, 0, 3, 1) = c.cross (d);\n pl_b.block (0, 0, 3, 1) = a.cross (b);\n\n pl_r (3) = -T.dot (pl_r.block (0, 0, 3, 1));\n pl_l (3) = -T.dot (pl_l.block (0, 0, 3, 1));\n pl_t (3) = -T.dot (pl_t.block (0, 0, 3, 1));\n pl_b (3) = -T.dot (pl_b.block (0, 0, 3, 1));\n\n output.reserve (input_->points.size ());\n for (int i = 0; i < int (input_->points.size ()); i++) \n {\n Eigen::Vector4f pt (input_->points[i].x, input_->points[i].y, input_->points[i].z, 1.0f);\n\n if ( (pt.dot (pl_l) <= 0) && \n (pt.dot (pl_r) <= 0) &&\n (pt.dot (pl_t) <= 0) && \n (pt.dot (pl_b) <= 0) && \n (pt.dot (pl_f) <= 0) &&\n (pt.dot (pl_n) <= 0) )\n {\n output.points.push_back (input_->points[i]);\n }\n }\n output.width = 1;\n output.height = uint32_t (output.points.size ());\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate <typename PointT> void\npcl::FrustumCulling<PointT>::applyFilter (std::vector<int> &indices)\n{\n int indices_count = 0;\n int removed_indices_count = 0;\n\n Eigen::Vector4f pl_n; \/\/ near plane \n Eigen::Vector4f pl_f; \/\/ far plane\n Eigen::Vector4f pl_t; \/\/ top plane\n Eigen::Vector4f pl_b; \/\/ bottom plane\n Eigen::Vector4f pl_r; \/\/ right plane\n Eigen::Vector4f pl_l; \/\/ left plane\n\n Eigen::Vector3f view = camera_pose_.block (0, 0, 3, 1); \/\/ view vector for the camera - first column of the rotation matrix\n Eigen::Vector3f up = camera_pose_.block (0, 1, 3, 1); \/\/ up vector for the camera - second column of the rotation matix\n Eigen::Vector3f right = camera_pose_.block (0, 2, 3, 1); \/\/ right vector for the camera - third column of the rotation matrix\n Eigen::Vector3f T = camera_pose_.block (0, 3, 3, 1); \/\/ The (X, Y, Z) position of the camera w.r.t origin\n\n\n vfov_ = float (vfov_ * M_PI \/ 180); \/\/ degrees to radians\n hfov_ = float (hfov_ * M_PI \/ 180); \/\/ degrees to radians\n \n float np_h = float (2 * tan (vfov_ \/ 2) * np_dist_); \/\/ near plane height\n float np_w = float (2 * tan (hfov_ \/ 2) * np_dist_); \/\/ near plane width\n\n float fp_h = float (2 * tan (vfov_ \/ 2) * fp_dist_); \/\/ far plane height\n float fp_w = float (2 * tan (hfov_ \/ 2) * fp_dist_); \/\/ far plane width\n\n Eigen::Vector3f fp_c (T + view * fp_dist_); \/\/ far plane center\n Eigen::Vector3f fp_tl (fp_c + (up * fp_h \/ 2) - (right * fp_w \/ 2)); \/\/ Top left corner of the far plane\n Eigen::Vector3f fp_tr (fp_c + (up * fp_h \/ 2) + (right * fp_w \/ 2)); \/\/ Top right corner of the far plane\n Eigen::Vector3f fp_bl (fp_c - (up * fp_h \/ 2) - (right * fp_w \/ 2)); \/\/ Bottom left corner of the far plane\n Eigen::Vector3f fp_br (fp_c - (up * fp_h \/ 2) + (right * fp_w \/ 2)); \/\/ Bottom right corner of the far plane\n\n Eigen::Vector3f np_c (T + view * np_dist_); \/\/ near plane center\n \/\/Eigen::Vector3f np_tl = np_c + (up * np_h\/2) - (right * np_w\/2); \/\/ Top left corner of the near plane\n Eigen::Vector3f np_tr (np_c + (up * np_h \/ 2) + (right * np_w \/ 2)); \/\/ Top right corner of the near plane\n Eigen::Vector3f np_bl (np_c - (up * np_h \/ 2) - (right * np_w \/ 2)); \/\/ Bottom left corner of the near plane\n Eigen::Vector3f np_br (np_c - (up * np_h \/ 2) + (right * np_w \/ 2)); \/\/ Bottom right corner of the near plane\n\n pl_f.block (0, 0, 3, 1) = (fp_bl - fp_br).cross (fp_tr - fp_br); \/\/ Far plane equation - cross product of the \n pl_f (3) = -fp_c.dot (pl_f.block (0, 0, 3, 1)); \/\/ perpendicular edges of the far plane\n\n pl_n.block (0, 0, 3, 1) = (np_tr - np_br).cross (np_bl - np_br); \/\/ Near plane equation - cross product of the \n pl_n (3) = -np_c.dot (pl_n.block (0, 0, 3, 1)); \/\/ perpendicular edges of the far plane\n\n Eigen::Vector3f a (fp_bl - T); \/\/ Vector connecting the camera and far plane bottom left\n Eigen::Vector3f b (fp_br - T); \/\/ Vector connecting the camera and far plane bottom right\n Eigen::Vector3f c (fp_tr - T); \/\/ Vector connecting the camera and far plane top right\n Eigen::Vector3f d (fp_tl - T); \/\/ Vector connecting the camera and far plane top left\n\n \/\/ Frustum and the vectors a, b, c and d. T is the position of the camera\n \/\/ _________\n \/\/ \/| . |\n \/\/ d \/ | c . |\n \/\/ \/ | __._____| \n \/\/ \/ \/ . .\n \/\/ a <---\/-\/ . .\n \/\/ \/ \/ . . b\n \/\/ \/ .\n \/\/ . \n \/\/ T\n \/\/\n\n pl_r.block (0, 0, 3, 1) = b.cross (c);\n pl_l.block (0, 0, 3, 1) = d.cross (a);\n pl_t.block (0, 0, 3, 1) = c.cross (d);\n pl_b.block (0, 0, 3, 1) = a.cross (b);\n\n pl_r (3) = -T.dot (pl_r.block (0, 0, 3, 1));\n pl_l (3) = -T.dot (pl_l.block (0, 0, 3, 1));\n pl_t (3) = -T.dot (pl_t.block (0, 0, 3, 1));\n pl_b (3) = -T.dot (pl_b.block (0, 0, 3, 1));\n\n removed_indices_->reserve (indices.size ());\n\n for (int i = 0; i < int (indices.size ()); i++) \n {\n Eigen::Vector4f pt (input_->points[indices[i]].x,\n input_->points[indices[i]].y,\n input_->points[indices[i]].z,\n 1.0f);\n\n if ( (pt.dot (pl_l) <= 0) && \n (pt.dot (pl_r) <= 0) &&\n (pt.dot (pl_t) <= 0) && \n (pt.dot (pl_b) <= 0) && \n (pt.dot (pl_f) <= 0) &&\n (pt.dot (pl_n) <= 0) )\n {\n if (extract_removed_indices_)\n {\n (*removed_indices_)[removed_indices_count++] = static_cast<int> (i);\n }\n else \n {\n indices[indices_count++] = (*indices_)[i];\n }\n }\n }\n indices.resize (indices_count);\n removed_indices_->resize (removed_indices_count);\n}\n\n#define PCL_INSTANTIATE_FrustumCulling(T) template class PCL_EXPORTS pcl::FrustumCulling<T>;\n\n#endif\n<commit_msg>* fixed bug #855: pcl_filters frustum_culling.h\/cpp fails ambiguous use of =<commit_after>\/*\n * Software License Agreement (BSD License)\n *\n * Point Cloud Library (PCL) - www.pointclouds.org\n * Copyright (c) 2012-, Open Perception, Inc.\n *\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following\n * disclaimer in the documentation and\/or other materials provided\n * with the distribution.\n * * Neither the name of the copyright holder(s) nor the names of its\n * contributors may be used to endorse or promote products derived\n * from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n *\/\n\n#ifndef PCL_FILTERS_IMPL_FRUSTUM_CULLING_HPP_\n#define PCL_FILTERS_IMPL_FRUSTUM_CULLING_HPP_\n\n#include <pcl\/filters\/frustum_culling.h>\n#include <vector>\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate <typename PointT> void\npcl::FrustumCulling<PointT>::applyFilter (PointCloud& output)\n{\n Eigen::Vector4f pl_n; \/\/ near plane \n Eigen::Vector4f pl_f; \/\/ far plane\n Eigen::Vector4f pl_t; \/\/ top plane\n Eigen::Vector4f pl_b; \/\/ bottom plane\n Eigen::Vector4f pl_r; \/\/ right plane\n Eigen::Vector4f pl_l; \/\/ left plane\n\n Eigen::Vector3f view = camera_pose_.block (0, 0, 3, 1); \/\/ view vector for the camera - first column of the rotation matrix\n Eigen::Vector3f up = camera_pose_.block (0, 1, 3, 1); \/\/ up vector for the camera - second column of the rotation matix\n Eigen::Vector3f right = camera_pose_.block (0, 2, 3, 1); \/\/ right vector for the camera - third column of the rotation matrix\n Eigen::Vector3f T = camera_pose_.block (0, 3, 3, 1); \/\/ The (X, Y, Z) position of the camera w.r.t origin\n\n vfov_ = float (vfov_ * M_PI \/ 180); \/\/ degrees to radians\n hfov_ = float (hfov_ * M_PI \/ 180); \/\/ degrees to radians\n \n float np_h = float (2 * tan (vfov_ \/ 2) * np_dist_); \/\/ near plane height\n float np_w = float (2 * tan (hfov_ \/ 2) * np_dist_); \/\/ near plane width\n\n\n float fp_h = float (2 * tan (vfov_ \/ 2) * fp_dist_); \/\/ far plane height\n float fp_w = float (2 * tan (hfov_ \/ 2) * fp_dist_); \/\/ far plane width\n\n Eigen::Vector3f fp_c (T + view * fp_dist_); \/\/ far plane center\n Eigen::Vector3f fp_tl (fp_c + (up * fp_h \/ 2) - (right * fp_w \/ 2)); \/\/ Top left corner of the far plane\n Eigen::Vector3f fp_tr (fp_c + (up * fp_h \/ 2) + (right * fp_w \/ 2)); \/\/ Top right corner of the far plane\n Eigen::Vector3f fp_bl (fp_c - (up * fp_h \/ 2) - (right * fp_w \/ 2)); \/\/ Bottom left corner of the far plane\n Eigen::Vector3f fp_br (fp_c - (up * fp_h \/ 2) + (right * fp_w \/ 2)); \/\/ Bottom right corner of the far plane\n\n Eigen::Vector3f np_c (T + view * np_dist_); \/\/ near plane center\n \/\/Eigen::Vector3f np_tl = np_c + (up * np_h\/2) - (right * np_w\/2); \/\/ Top left corner of the near plane\n Eigen::Vector3f np_tr (np_c + (up * np_h \/ 2) + (right * np_w \/ 2)); \/\/ Top right corner of the near plane\n Eigen::Vector3f np_bl (np_c - (up * np_h \/ 2) - (right * np_w \/ 2)); \/\/ Bottom left corner of the near plane\n Eigen::Vector3f np_br (np_c - (up * np_h \/ 2) + (right * np_w \/ 2)); \/\/ Bottom right corner of the near plane\n\n\n pl_f.block (0, 0, 3, 1).matrix () = (fp_bl - fp_br).cross (fp_tr - fp_br); \/\/ Far plane equation - cross product of the \n pl_f (3) = -fp_c.dot (pl_f.block (0, 0, 3, 1)); \/\/ perpendicular edges of the far plane\n\n pl_n.block (0, 0, 3, 1).matrix () = (np_tr - np_br).cross (np_bl - np_br); \/\/ Near plane equation - cross product of the \n pl_n (3) = -np_c.dot (pl_n.block (0, 0, 3, 1)); \/\/ perpendicular edges of the far plane\n\n Eigen::Vector3f a (fp_bl - T); \/\/ Vector connecting the camera and far plane bottom left\n Eigen::Vector3f b (fp_br - T); \/\/ Vector connecting the camera and far plane bottom right\n Eigen::Vector3f c (fp_tr - T); \/\/ Vector connecting the camera and far plane top right\n Eigen::Vector3f d (fp_tl - T); \/\/ Vector connecting the camera and far plane top left\n\n \/\/ Frustum and the vectors a, b, c and d. T is the position of the camera\n \/\/ _________\n \/\/ \/| . |\n \/\/ d \/ | c . |\n \/\/ \/ | __._____| \n \/\/ \/ \/ . .\n \/\/ a <---\/-\/ . .\n \/\/ \/ \/ . . b\n \/\/ \/ .\n \/\/ . \n \/\/ T\n \/\/\n\n pl_r.block (0, 0, 3, 1).matrix () = b.cross (c);\n pl_l.block (0, 0, 3, 1).matrix () = d.cross (a);\n pl_t.block (0, 0, 3, 1).matrix () = c.cross (d);\n pl_b.block (0, 0, 3, 1).matrix () = a.cross (b);\n\n pl_r (3) = -T.dot (pl_r.block (0, 0, 3, 1));\n pl_l (3) = -T.dot (pl_l.block (0, 0, 3, 1));\n pl_t (3) = -T.dot (pl_t.block (0, 0, 3, 1));\n pl_b (3) = -T.dot (pl_b.block (0, 0, 3, 1));\n\n output.reserve (input_->points.size ());\n for (int i = 0; i < int (input_->points.size ()); i++) \n {\n Eigen::Vector4f pt (input_->points[i].x, input_->points[i].y, input_->points[i].z, 1.0f);\n\n if ( (pt.dot (pl_l) <= 0) && \n (pt.dot (pl_r) <= 0) &&\n (pt.dot (pl_t) <= 0) && \n (pt.dot (pl_b) <= 0) && \n (pt.dot (pl_f) <= 0) &&\n (pt.dot (pl_n) <= 0) )\n {\n output.points.push_back (input_->points[i]);\n }\n }\n output.width = 1;\n output.height = uint32_t (output.points.size ());\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate <typename PointT> void\npcl::FrustumCulling<PointT>::applyFilter (std::vector<int> &indices)\n{\n int indices_count = 0;\n int removed_indices_count = 0;\n\n Eigen::Vector4f pl_n; \/\/ near plane \n Eigen::Vector4f pl_f; \/\/ far plane\n Eigen::Vector4f pl_t; \/\/ top plane\n Eigen::Vector4f pl_b; \/\/ bottom plane\n Eigen::Vector4f pl_r; \/\/ right plane\n Eigen::Vector4f pl_l; \/\/ left plane\n\n Eigen::Vector3f view = camera_pose_.block (0, 0, 3, 1); \/\/ view vector for the camera - first column of the rotation matrix\n Eigen::Vector3f up = camera_pose_.block (0, 1, 3, 1); \/\/ up vector for the camera - second column of the rotation matix\n Eigen::Vector3f right = camera_pose_.block (0, 2, 3, 1); \/\/ right vector for the camera - third column of the rotation matrix\n Eigen::Vector3f T = camera_pose_.block (0, 3, 3, 1); \/\/ The (X, Y, Z) position of the camera w.r.t origin\n\n\n vfov_ = float (vfov_ * M_PI \/ 180); \/\/ degrees to radians\n hfov_ = float (hfov_ * M_PI \/ 180); \/\/ degrees to radians\n \n float np_h = float (2 * tan (vfov_ \/ 2) * np_dist_); \/\/ near plane height\n float np_w = float (2 * tan (hfov_ \/ 2) * np_dist_); \/\/ near plane width\n\n float fp_h = float (2 * tan (vfov_ \/ 2) * fp_dist_); \/\/ far plane height\n float fp_w = float (2 * tan (hfov_ \/ 2) * fp_dist_); \/\/ far plane width\n\n Eigen::Vector3f fp_c (T + view * fp_dist_); \/\/ far plane center\n Eigen::Vector3f fp_tl (fp_c + (up * fp_h \/ 2) - (right * fp_w \/ 2)); \/\/ Top left corner of the far plane\n Eigen::Vector3f fp_tr (fp_c + (up * fp_h \/ 2) + (right * fp_w \/ 2)); \/\/ Top right corner of the far plane\n Eigen::Vector3f fp_bl (fp_c - (up * fp_h \/ 2) - (right * fp_w \/ 2)); \/\/ Bottom left corner of the far plane\n Eigen::Vector3f fp_br (fp_c - (up * fp_h \/ 2) + (right * fp_w \/ 2)); \/\/ Bottom right corner of the far plane\n\n Eigen::Vector3f np_c (T + view * np_dist_); \/\/ near plane center\n \/\/Eigen::Vector3f np_tl = np_c + (up * np_h\/2) - (right * np_w\/2); \/\/ Top left corner of the near plane\n Eigen::Vector3f np_tr (np_c + (up * np_h \/ 2) + (right * np_w \/ 2)); \/\/ Top right corner of the near plane\n Eigen::Vector3f np_bl (np_c - (up * np_h \/ 2) - (right * np_w \/ 2)); \/\/ Bottom left corner of the near plane\n Eigen::Vector3f np_br (np_c - (up * np_h \/ 2) + (right * np_w \/ 2)); \/\/ Bottom right corner of the near plane\n\n pl_f.block (0, 0, 3, 1).matrix () = (fp_bl - fp_br).cross (fp_tr - fp_br); \/\/ Far plane equation - cross product of the \n pl_f (3) = -fp_c.dot (pl_f.block (0, 0, 3, 1)); \/\/ perpendicular edges of the far plane\n\n pl_n.block (0, 0, 3, 1).matrix () = (np_tr - np_br).cross (np_bl - np_br); \/\/ Near plane equation - cross product of the \n pl_n (3) = -np_c.dot (pl_n.block (0, 0, 3, 1)); \/\/ perpendicular edges of the far plane\n\n Eigen::Vector3f a (fp_bl - T); \/\/ Vector connecting the camera and far plane bottom left\n Eigen::Vector3f b (fp_br - T); \/\/ Vector connecting the camera and far plane bottom right\n Eigen::Vector3f c (fp_tr - T); \/\/ Vector connecting the camera and far plane top right\n Eigen::Vector3f d (fp_tl - T); \/\/ Vector connecting the camera and far plane top left\n\n \/\/ Frustum and the vectors a, b, c and d. T is the position of the camera\n \/\/ _________\n \/\/ \/| . |\n \/\/ d \/ | c . |\n \/\/ \/ | __._____| \n \/\/ \/ \/ . .\n \/\/ a <---\/-\/ . .\n \/\/ \/ \/ . . b\n \/\/ \/ .\n \/\/ . \n \/\/ T\n \/\/\n\n pl_r.block (0, 0, 3, 1).matrix () = b.cross (c);\n pl_l.block (0, 0, 3, 1).matrix () = d.cross (a);\n pl_t.block (0, 0, 3, 1).matrix () = c.cross (d);\n pl_b.block (0, 0, 3, 1).matrix () = a.cross (b);\n\n pl_r (3) = -T.dot (pl_r.block (0, 0, 3, 1));\n pl_l (3) = -T.dot (pl_l.block (0, 0, 3, 1));\n pl_t (3) = -T.dot (pl_t.block (0, 0, 3, 1));\n pl_b (3) = -T.dot (pl_b.block (0, 0, 3, 1));\n\n removed_indices_->reserve (indices.size ());\n\n for (int i = 0; i < int (indices.size ()); i++) \n {\n Eigen::Vector4f pt (input_->points[indices[i]].x,\n input_->points[indices[i]].y,\n input_->points[indices[i]].z,\n 1.0f);\n\n if ( (pt.dot (pl_l) <= 0) && \n (pt.dot (pl_r) <= 0) &&\n (pt.dot (pl_t) <= 0) && \n (pt.dot (pl_b) <= 0) && \n (pt.dot (pl_f) <= 0) &&\n (pt.dot (pl_n) <= 0) )\n {\n if (extract_removed_indices_)\n {\n (*removed_indices_)[removed_indices_count++] = static_cast<int> (i);\n }\n else \n {\n indices[indices_count++] = (*indices_)[i];\n }\n }\n }\n indices.resize (indices_count);\n removed_indices_->resize (removed_indices_count);\n}\n\n#define PCL_INSTANTIATE_FrustumCulling(T) template class PCL_EXPORTS pcl::FrustumCulling<T>;\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/*****************************************************************************\n *\n * This file is part of Mapnik (c++ mapping toolkit)\n *\n * Copyright (C) 2011 Artem Pavlenko\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n *\n *****************************************************************************\/\n\n#include \"postgis_featureset.hpp\"\n#include \"resultset.hpp\"\n#include \"cursorresultset.hpp\"\n\n\/\/ mapnik\n#include <mapnik\/global.hpp>\n#include <mapnik\/wkb.hpp>\n#include <mapnik\/unicode.hpp>\n#include <mapnik\/sql_utils.hpp>\n#include <mapnik\/feature_factory.hpp>\n#include <mapnik\/util\/conversions.hpp>\n\n\/\/ boost\n#include <boost\/algorithm\/string.hpp>\n#include <boost\/spirit\/include\/qi.hpp>\n\n\/\/ stl\n#include <sstream>\n#include <string>\n\nusing boost::trim_copy;\nusing mapnik::geometry_type;\nusing mapnik::byte;\nusing mapnik::geometry_utils;\nusing mapnik::feature_factory;\nusing mapnik::context_ptr;\n\npostgis_featureset::postgis_featureset(boost::shared_ptr<IResultSet> const& rs,\n context_ptr const& ctx,\n std::string const& encoding,\n bool key_field)\n : rs_(rs),\n ctx_(ctx),\n tr_(new transcoder(encoding)),\n totalGeomSize_(0),\n feature_id_(1),\n key_field_(key_field)\n{\n}\n\nfeature_ptr postgis_featureset::next()\n{\n if (rs_->next())\n {\n \/\/ new feature\n unsigned pos = 1;\n feature_ptr feature;\n\n if (key_field_)\n {\n \/\/ create feature with user driven id from attribute\n int oid = rs_->getTypeOID(pos);\n const char* buf = rs_->getValue(pos);\n std::string name = rs_->getFieldName(pos);\n\n \/\/ validation happens of this type at bind()\n int val;\n if (oid == 20)\n {\n val = int8net(buf);\n }\n else if (oid == 21)\n {\n val = int2net(buf);\n }\n else\n {\n val = int4net(buf);\n }\n\n feature = feature_factory::create(ctx_, val);\n \/\/ TODO - extend feature class to know\n \/\/ that its id is also an attribute to avoid\n \/\/ this duplication\n feature->put(name,val);\n ++pos;\n }\n else\n {\n \/\/ fallback to auto-incrementing id\n feature = feature_factory::create(ctx_, feature_id_);\n ++feature_id_;\n }\n\n \/\/ parse geometry\n int size = rs_->getFieldLength(0);\n const char *data = rs_->getValue(0);\n geometry_utils::from_wkb(feature->paths(), data, size);\n totalGeomSize_ += size;\n\n int num_attrs = ctx_->size() + 1;\n for (; pos < num_attrs; ++pos)\n {\n std::string name = rs_->getFieldName(pos);\n\n if (rs_->isNull(pos))\n {\n feature->put(name, mapnik::value_null());\n }\n else\n {\n const char* buf = rs_->getValue(pos);\n const int oid = rs_->getTypeOID(pos);\n switch (oid)\n {\n case 16: \/\/bool\n {\n feature->put(name, (buf[0] != 0));\n break;\n }\n\n case 23: \/\/int4\n {\n int val = int4net(buf);\n feature->put(name, val);\n break;\n }\n\n case 21: \/\/int2\n {\n int val = int2net(buf);\n feature->put(name, val);\n break;\n }\n\n case 20: \/\/int8\/BigInt\n {\n int val = int8net(buf);\n feature->put(name, val);\n break;\n }\n\n case 700: \/\/float4\n {\n float val;\n float4net(val, buf);\n feature->put(name, val);\n break;\n }\n\n case 701: \/\/float8\n {\n double val;\n float8net(val, buf);\n feature->put(name, val);\n break;\n }\n\n case 25: \/\/text\n case 1043: \/\/varchar\n {\n feature->put(name, tr_->transcode(buf));\n break;\n }\n\n case 1042: \/\/bpchar\n {\n feature->put(name, tr_->transcode(trim_copy(std::string(buf)).c_str()));\n break;\n }\n\n case 1700: \/\/numeric\n {\n double val;\n std::string str = mapnik::sql_utils::numeric2string(buf);\n if (mapnik::util::string2double(str, val))\n {\n feature->put(name, val);\n }\n break;\n }\n\n default:\n {\n#ifdef MAPNIK_DEBUG\n std::clog << \"Postgis Plugin: uknown OID = \" << oid << std::endl;\n#endif\n break;\n }\n }\n }\n }\n return feature;\n }\n else\n {\n rs_->close();\n return feature_ptr();\n }\n}\n\n\npostgis_featureset::~postgis_featureset()\n{\n rs_->close();\n}\n<commit_msg>make note of need for 64bit int support in code comments for postgis plugin - refs #895<commit_after>\/*****************************************************************************\n *\n * This file is part of Mapnik (c++ mapping toolkit)\n *\n * Copyright (C) 2011 Artem Pavlenko\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n *\n *****************************************************************************\/\n\n#include \"postgis_featureset.hpp\"\n#include \"resultset.hpp\"\n#include \"cursorresultset.hpp\"\n\n\/\/ mapnik\n#include <mapnik\/global.hpp>\n#include <mapnik\/wkb.hpp>\n#include <mapnik\/unicode.hpp>\n#include <mapnik\/sql_utils.hpp>\n#include <mapnik\/feature_factory.hpp>\n#include <mapnik\/util\/conversions.hpp>\n\n\/\/ boost\n#include <boost\/algorithm\/string.hpp>\n#include <boost\/spirit\/include\/qi.hpp>\n\n\/\/ stl\n#include <sstream>\n#include <string>\n\nusing boost::trim_copy;\nusing mapnik::geometry_type;\nusing mapnik::byte;\nusing mapnik::geometry_utils;\nusing mapnik::feature_factory;\nusing mapnik::context_ptr;\n\npostgis_featureset::postgis_featureset(boost::shared_ptr<IResultSet> const& rs,\n context_ptr const& ctx,\n std::string const& encoding,\n bool key_field)\n : rs_(rs),\n ctx_(ctx),\n tr_(new transcoder(encoding)),\n totalGeomSize_(0),\n feature_id_(1),\n key_field_(key_field)\n{\n}\n\nfeature_ptr postgis_featureset::next()\n{\n if (rs_->next())\n {\n \/\/ new feature\n unsigned pos = 1;\n feature_ptr feature;\n\n if (key_field_)\n {\n \/\/ create feature with user driven id from attribute\n int oid = rs_->getTypeOID(pos);\n const char* buf = rs_->getValue(pos);\n std::string name = rs_->getFieldName(pos);\n\n \/\/ validation happens of this type at bind()\n int val;\n if (oid == 20)\n {\n val = int8net(buf);\n }\n else if (oid == 21)\n {\n val = int2net(buf);\n }\n else\n {\n val = int4net(buf);\n }\n\n feature = feature_factory::create(ctx_, val);\n \/\/ TODO - extend feature class to know\n \/\/ that its id is also an attribute to avoid\n \/\/ this duplication\n feature->put(name,val);\n ++pos;\n }\n else\n {\n \/\/ fallback to auto-incrementing id\n feature = feature_factory::create(ctx_, feature_id_);\n ++feature_id_;\n }\n\n \/\/ parse geometry\n int size = rs_->getFieldLength(0);\n const char *data = rs_->getValue(0);\n geometry_utils::from_wkb(feature->paths(), data, size);\n totalGeomSize_ += size;\n\n int num_attrs = ctx_->size() + 1;\n for (; pos < num_attrs; ++pos)\n {\n std::string name = rs_->getFieldName(pos);\n\n if (rs_->isNull(pos))\n {\n feature->put(name, mapnik::value_null());\n }\n else\n {\n const char* buf = rs_->getValue(pos);\n const int oid = rs_->getTypeOID(pos);\n switch (oid)\n {\n case 16: \/\/bool\n {\n feature->put(name, (buf[0] != 0));\n break;\n }\n\n case 23: \/\/int4\n {\n int val = int4net(buf);\n feature->put(name, val);\n break;\n }\n\n case 21: \/\/int2\n {\n int val = int2net(buf);\n feature->put(name, val);\n break;\n }\n\n case 20: \/\/int8\/BigInt\n {\n \/\/ TODO - need to support boost::uint64_t in mapnik::value\n \/\/ https:\/\/github.com\/mapnik\/mapnik\/issues\/895\n int val = int8net(buf);\n feature->put(name, val);\n break;\n }\n\n case 700: \/\/float4\n {\n float val;\n float4net(val, buf);\n feature->put(name, val);\n break;\n }\n\n case 701: \/\/float8\n {\n double val;\n float8net(val, buf);\n feature->put(name, val);\n break;\n }\n\n case 25: \/\/text\n case 1043: \/\/varchar\n {\n feature->put(name, tr_->transcode(buf));\n break;\n }\n\n case 1042: \/\/bpchar\n {\n feature->put(name, tr_->transcode(trim_copy(std::string(buf)).c_str()));\n break;\n }\n\n case 1700: \/\/numeric\n {\n double val;\n std::string str = mapnik::sql_utils::numeric2string(buf);\n if (mapnik::util::string2double(str, val))\n {\n feature->put(name, val);\n }\n break;\n }\n\n default:\n {\n#ifdef MAPNIK_DEBUG\n std::clog << \"Postgis Plugin: uknown OID = \" << oid << std::endl;\n#endif\n break;\n }\n }\n }\n }\n return feature;\n }\n else\n {\n rs_->close();\n return feature_ptr();\n }\n}\n\n\npostgis_featureset::~postgis_featureset()\n{\n rs_->close();\n}\n<|endoftext|>"} {"text":"<commit_before>\n#include <stdio.h>\n#include <string>\n#include <iostream>\n#include <fstream>\n#include <vector>\n#include \"api\/BamReader.h\"\n#include \"transrate-pileup.h\"\n\nusing namespace BamTools;\n\nusing namespace std;\n\nstruct ContigRecord {\n int bases_mapped;\n int p_seq_true;\n int bridges;\n int length;\n string name;\n int fragments_mapped;\n int both_mapped;\n int properpair;\n int good;\n int bases_uncovered;\n double p_unique;\n double p_not_segmented;\n};\n\nclass BetterBam {\n int realistic_distance;\n int seq_count;\n int i,j;\n uint32_t nm_tag;\n int ldist;\n int rdist;\n int maxL=0;\n std::string file;\n BamReader reader;\n BamAlignment alignment;\n public:\n std::vector<ContigRecord> array;\n BetterBam (std::string);\n\n \/\/ loop through all cigar operations and check they are not S\n bool check_cigar(BamAlignment alignment) {\n int numCigarOps = alignment.CigarData.size();\n bool check = false;\n for (int i = 0; i < numCigarOps; ++i) {\n const CigarOp& op = alignment.CigarData.at(i);\n if (op.Type != 'S') {\n check = true;\n }\n }\n return check;\n }\n\n \/\/ set realistic distance between pairs to have 0.03% false positive rate\n void set_fragment_size(int size, int sd) {\n realistic_distance = size + 3 * sd;\n }\n\n int load_bam() {\n if (!reader.Open(file)) {\n cerr << \"Could not open BAM file\" << endl;\n return 1;\n }\n \/\/ get sam header\n SamSequenceDictionary dictionary = reader.GetHeader().Sequences;\n seq_count = dictionary.Size();\n array.resize(seq_count);\n \/\/ get an iterator for looping over the sequences in the header\n std::vector<SamSequence>::iterator it = dictionary.Begin();\n \/\/ fill the vector with intial values\n for (i = 0; i < seq_count; i++) {\n array[i].bases_mapped = 0;\n array[i].p_seq_true = 0;\n array[i].bridges = 0;\n if (it[i].HasLength()) {\n array[i].length = atoi(it[i].Length.c_str());\n if (array[i].length > maxL) {\n maxL = array[i].length;\n }\n } else {\n array[i].length = 0;\n }\n array[i].name = it[i].Name;\n array[i].fragments_mapped = 0;\n array[i].both_mapped = 0;\n array[i].properpair = 0;\n array[i].good = 0;\n array[i].bases_uncovered = 0;\n array[i].p_unique = 0;\n array[i].p_not_segmented = 1;\n }\n \/\/ loop through bam file\n i = -2;\n TransratePileup pileup(maxL);\n int ref_length = -1;\n while (reader.GetNextAlignment(alignment)) {\n\n \/\/ read must be mapped\n if (!alignment.IsMapped()) {\n continue;\n }\n\n \/\/ alignment must have a valid cigar sting\n if (!check_cigar(alignment)) {\n continue;\n }\n\n \/\/ check this read comes from the currently loaded contig\n \/\/ if not, load the new contig\n if (alignment.RefID != i) {\n if (i>=0) {\n array[i].bases_uncovered = pileup.getBasesUncovered();\n array[i].p_unique = pileup.getUniqueBases();\n array[i].p_not_segmented = pileup.p_not_segmented();\n }\n i = alignment.RefID;\n ref_length = array[i].length;\n pileup.clearCoverage(ref_length);\n }\n\n \/\/ we only care about the primary alignment of each fragment\n if (!alignment.IsPrimaryAlignment()) {\n continue;\n }\n\n pileup.addAlignment(alignment);\n\n array[i].bases_mapped += alignment.Length;\n\n \/\/ store edit distance for sequence accuracy calculation\n if (alignment.HasTag(\"NM\")) {\n if (alignment.GetTag(\"NM\", nm_tag)) {\n array[i].p_seq_true += nm_tag;\n }\n }\n\n \/\/ count fragments where either or both mates mapped\n if (alignment.IsFirstMate() ||\n (alignment.IsSecondMate() && !alignment.IsMateMapped())) {\n array[i].fragments_mapped++;\n }\n\n \/\/ from now on ignore fragments unless both mates mapped\n if (!(alignment.IsFirstMate() && alignment.IsMateMapped())) {\n continue;\n }\n\n array[i].both_mapped++;\n\n \/\/ mates must align to same contig, otherwise we record a bridge\n if (alignment.RefID != alignment.MateRefID) {\n array[i].bridges++;\n continue;\n }\n\n \/\/ fragment length must be plausible\n ldist = max(alignment.Position-alignment.MatePosition,\n alignment.MatePosition-alignment.Position);\n if (ldist > realistic_distance) {\n \/\/ mates are too far apart\n continue;\n }\n\n \/\/ read orientation must match the generated library\n \/\/ in this case we only test for FR\/RF orientation,\n \/\/ that is - we expect mates to be on opposite strands\n bool is_reversed = alignment.IsReverseStrand();\n bool is_mate_reversed = alignment.IsMateReverseStrand();\n\n if (!is_reversed && is_mate_reversed) {\n \/\/ in FR orientation, first read must start\n \/\/ before second read\n if (alignment.Position < alignment.MatePosition) {\n array[i].good++;\n }\n } else if (is_reversed && !is_mate_reversed) {\n \/\/ in RF orientation, second read must start\n \/\/ before first read\n if (alignment.MatePosition < alignment.Position) {\n array[i].good++;\n }\n }\n }\n array[i].bases_uncovered = pileup.getBasesUncovered();\n array[i].p_unique = pileup.getUniqueBases();\n array[i].p_not_segmented = pileup.p_not_segmented();\n\n reader.Close();\n return 0;\n }\n\n int get_seq_count() {\n return seq_count;\n }\n\n ContigRecord get_info(int i) {\n return array.at(i);\n }\n\n int get_bases_mapped(int i) {\n return array.at(i).bases_mapped;\n }\n};\n\n\/\/constructor\nBetterBam::BetterBam (std::string s) {\n file = s;\n realistic_distance = 350;\n}\n\nint main (int argc, char* argv[]) {\n if (argc == 3) {\n string infile = argv[1];\n BetterBam bam (infile);\n bam.load_bam();\n int i;\n\n std::ofstream output;\n output.open (argv[2]);\n output << \"name,p_seq_true,bridges,length,fragments_mapped,\"\n \"both_mapped,properpair,good,bases_uncovered,p_unique,\"\n \"p_not_segmented\" << endl;\n for (i = 0; i < bam.get_seq_count(); i++) {\n output << bam.get_info(i).name << \",\";\n if (bam.get_info(i).bases_mapped>0) {\n output << 1-((double)bam.get_info(i).p_seq_true\/bam.get_info(i).bases_mapped) << \",\";\n } else {\n output << \"1,\";\n }\n output << bam.get_info(i).bridges << \",\";\n output << bam.get_info(i).length << \",\";\n output << bam.get_info(i).fragments_mapped << \",\";\n output << bam.get_info(i).both_mapped << \",\";\n output << bam.get_info(i).properpair << \",\";\n output << bam.get_info(i).good << \",\";\n output << bam.get_info(i).bases_uncovered << \",\";\n output << bam.get_info(i).p_unique << \",\";\n output << bam.get_info(i).p_not_segmented << endl;\n }\n output.close();\n return 0;\n } else {\n cout << \"bam-read version 0.3.4\\n\"\n << \"Usage:\\n\"\n << \"bam-read <bam_file> <output_csv>\" << endl;\n return 1;\n }\n}\n<commit_msg>increased realistic distance<commit_after>\n#include <stdio.h>\n#include <string>\n#include <iostream>\n#include <fstream>\n#include <vector>\n#include \"api\/BamReader.h\"\n#include \"transrate-pileup.h\"\n\nusing namespace BamTools;\n\nusing namespace std;\n\nstruct ContigRecord {\n int bases_mapped;\n int p_seq_true;\n int bridges;\n int length;\n string name;\n int fragments_mapped;\n int both_mapped;\n int properpair;\n int good;\n int bases_uncovered;\n double p_unique;\n double p_not_segmented;\n};\n\nclass BetterBam {\n int realistic_distance;\n int seq_count;\n int i,j;\n uint32_t nm_tag;\n int ldist;\n int rdist;\n int maxL=0;\n std::string file;\n BamReader reader;\n BamAlignment alignment;\n public:\n std::vector<ContigRecord> array;\n BetterBam (std::string);\n\n \/\/ loop through all cigar operations and check they are not S\n bool check_cigar(BamAlignment alignment) {\n int numCigarOps = alignment.CigarData.size();\n bool check = false;\n for (int i = 0; i < numCigarOps; ++i) {\n const CigarOp& op = alignment.CigarData.at(i);\n if (op.Type != 'S') {\n check = true;\n }\n }\n return check;\n }\n\n \/\/ set realistic distance between pairs to have 0.03% false positive rate\n void set_fragment_size(int size, int sd) {\n realistic_distance = size + 3 * sd;\n }\n\n int load_bam() {\n if (!reader.Open(file)) {\n cerr << \"Could not open BAM file\" << endl;\n return 1;\n }\n \/\/ get sam header\n SamSequenceDictionary dictionary = reader.GetHeader().Sequences;\n seq_count = dictionary.Size();\n array.resize(seq_count);\n \/\/ get an iterator for looping over the sequences in the header\n std::vector<SamSequence>::iterator it = dictionary.Begin();\n \/\/ fill the vector with intial values\n for (i = 0; i < seq_count; i++) {\n array[i].bases_mapped = 0;\n array[i].p_seq_true = 0;\n array[i].bridges = 0;\n if (it[i].HasLength()) {\n array[i].length = atoi(it[i].Length.c_str());\n if (array[i].length > maxL) {\n maxL = array[i].length;\n }\n } else {\n array[i].length = 0;\n }\n array[i].name = it[i].Name;\n array[i].fragments_mapped = 0;\n array[i].both_mapped = 0;\n array[i].properpair = 0;\n array[i].good = 0;\n array[i].bases_uncovered = 0;\n array[i].p_unique = 0;\n array[i].p_not_segmented = 1;\n }\n \/\/ loop through bam file\n i = -2;\n TransratePileup pileup(maxL);\n int ref_length = -1;\n while (reader.GetNextAlignment(alignment)) {\n\n \/\/ read must be mapped\n if (!alignment.IsMapped()) {\n continue;\n }\n\n \/\/ alignment must have a valid cigar sting\n if (!check_cigar(alignment)) {\n continue;\n }\n\n \/\/ check this read comes from the currently loaded contig\n \/\/ if not, load the new contig\n if (alignment.RefID != i) {\n if (i>=0) {\n array[i].bases_uncovered = pileup.getBasesUncovered();\n array[i].p_unique = pileup.getUniqueBases();\n array[i].p_not_segmented = pileup.p_not_segmented();\n }\n i = alignment.RefID;\n ref_length = array[i].length;\n pileup.clearCoverage(ref_length);\n }\n\n \/\/ we only care about the primary alignment of each fragment\n if (!alignment.IsPrimaryAlignment()) {\n continue;\n }\n\n pileup.addAlignment(alignment);\n\n array[i].bases_mapped += alignment.Length;\n\n \/\/ store edit distance for sequence accuracy calculation\n if (alignment.HasTag(\"NM\")) {\n if (alignment.GetTag(\"NM\", nm_tag)) {\n array[i].p_seq_true += nm_tag;\n }\n }\n\n \/\/ count fragments where either or both mates mapped\n if (alignment.IsFirstMate() ||\n (alignment.IsSecondMate() && !alignment.IsMateMapped())) {\n array[i].fragments_mapped++;\n }\n\n \/\/ from now on ignore fragments unless both mates mapped\n if (!(alignment.IsFirstMate() && alignment.IsMateMapped())) {\n continue;\n }\n\n array[i].both_mapped++;\n\n \/\/ mates must align to same contig, otherwise we record a bridge\n if (alignment.RefID != alignment.MateRefID) {\n array[i].bridges++;\n continue;\n }\n\n \/\/ fragment length must be plausible\n ldist = max(alignment.Position-alignment.MatePosition,\n alignment.MatePosition-alignment.Position);\n if (ldist > realistic_distance) {\n \/\/ mates are too far apart\n continue;\n }\n\n \/\/ read orientation must match the generated library\n \/\/ in this case we only test for FR\/RF orientation,\n \/\/ that is - we expect mates to be on opposite strands\n bool is_reversed = alignment.IsReverseStrand();\n bool is_mate_reversed = alignment.IsMateReverseStrand();\n\n if (!is_reversed && is_mate_reversed) {\n \/\/ in FR orientation, first read must start\n \/\/ before second read\n if (alignment.Position < alignment.MatePosition) {\n array[i].good++;\n }\n } else if (is_reversed && !is_mate_reversed) {\n \/\/ in RF orientation, second read must start\n \/\/ before first read\n if (alignment.MatePosition < alignment.Position) {\n array[i].good++;\n }\n }\n }\n array[i].bases_uncovered = pileup.getBasesUncovered();\n array[i].p_unique = pileup.getUniqueBases();\n array[i].p_not_segmented = pileup.p_not_segmented();\n\n reader.Close();\n return 0;\n }\n\n int get_seq_count() {\n return seq_count;\n }\n\n ContigRecord get_info(int i) {\n return array.at(i);\n }\n\n int get_bases_mapped(int i) {\n return array.at(i).bases_mapped;\n }\n};\n\n\/\/constructor\nBetterBam::BetterBam (std::string s) {\n file = s;\n realistic_distance = 450;\n}\n\nint main (int argc, char* argv[]) {\n if (argc == 3) {\n string infile = argv[1];\n BetterBam bam (infile);\n bam.load_bam();\n int i;\n\n std::ofstream output;\n output.open (argv[2]);\n output << \"name,p_seq_true,bridges,length,fragments_mapped,\"\n \"both_mapped,properpair,good,bases_uncovered,p_unique,\"\n \"p_not_segmented\" << endl;\n for (i = 0; i < bam.get_seq_count(); i++) {\n output << bam.get_info(i).name << \",\";\n if (bam.get_info(i).bases_mapped>0) {\n output << 1-((double)bam.get_info(i).p_seq_true\/bam.get_info(i).bases_mapped) << \",\";\n } else {\n output << \"1,\";\n }\n output << bam.get_info(i).bridges << \",\";\n output << bam.get_info(i).length << \",\";\n output << bam.get_info(i).fragments_mapped << \",\";\n output << bam.get_info(i).both_mapped << \",\";\n output << bam.get_info(i).properpair << \",\";\n output << bam.get_info(i).good << \",\";\n output << bam.get_info(i).bases_uncovered << \",\";\n output << bam.get_info(i).p_unique << \",\";\n output << bam.get_info(i).p_not_segmented << endl;\n }\n output.close();\n return 0;\n } else {\n cout << \"bam-read version 0.3.4\\n\"\n << \"Usage:\\n\"\n << \"bam-read <bam_file> <output_csv>\" << endl;\n return 1;\n }\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"include-opencv.hpp\"\n#include <algorithm>\n#include <cstdint>\n#include <fmo\/assert.hpp>\n#include <fmo\/common.hpp>\n#include <mutex>\n#include <vector>\n#include <fmo\/stripgen.hpp>\n\nnamespace fmo {\n struct StripGenImpl : public cv::ParallelLoopBody {\n using batch_t = uint64_t;\n using rle_t = int16_t;\n\n enum {\n WIDTH = sizeof(batch_t),\n };\n\n StripGenImpl(const fmo::Mat& img, int minHeight, int minGap, int step,\n std::vector<rle_t>& rle, std::vector<StripRepr>& temp,\n std::vector<StripRepr>& out, int& noiseOut, int numThreads)\n : mDims(img.dims()),\n mRleStep(mDims.height + 4),\n mRleSz(mRleStep * WIDTH),\n mTempSz((mRleSz + 1) \/ 2),\n mSkip(int(img.skip()) \/ WIDTH),\n mStep(step),\n mMinHeight(minHeight),\n mMinGap(minGap),\n mData((const batch_t*)(img.data())),\n mRle(&rle),\n mOut(&out),\n mNoiseOut(&noiseOut),\n mTemp(&temp),\n mNumThreads(numThreads) {\n FMO_ASSERT(int(img.skip()) % WIDTH == 0, \"StripGen::operator(): bad skip\");\n mRle->resize(mRleSz * mNumThreads);\n mTemp->resize(mTempSz * mNumThreads);\n mOut->clear();\n *mNoiseOut = 0;\n }\n\n virtual void operator()(const cv::Range& r) const override {\n const int threadNum = r.start;\n rle_t* const rle = mRle->data() + (mRleSz * threadNum);\n StripRepr* const temp = mTemp->data() + (mTempSz * threadNum);\n const int16_t step = int16_t(mStep);\n const int16_t halfStep = int16_t(mStep \/ 2);\n const int pad = std::max(0, std::max(mMinHeight, mMinGap));\n const int numBatches = mDims.width \/ WIDTH;\n const int batchFirst = (threadNum * numBatches) \/ mNumThreads;\n const int batchLast = ((threadNum + 1) * numBatches) \/ mNumThreads;\n const int colFirst = batchFirst * WIDTH;\n const int colLast = batchLast * WIDTH;\n const int skip = mSkip;\n const int minHeight = mMinHeight;\n const Dims dims = mDims;\n const int minGap = mMinGap;\n StripRepr* tempEnd = temp;\n\n int16_t origX = int16_t(halfStep + (colFirst * step));\n int noise = 0;\n rle_t* front[WIDTH];\n const batch_t* colData = mData + batchFirst;\n\n for (int w = 0; w < WIDTH; w++) { front[w] = rle + (w * mRleStep); }\n\n for (int col = colFirst; col < colLast; col += WIDTH, colData++) {\n const batch_t* data = colData;\n rle_t* back[WIDTH];\n int n[WIDTH];\n\n for (int w = 0; w < WIDTH; w++) {\n back[w] = front[w];\n\n \/\/ add top of image\n *back[w] = rle_t(-pad);\n n[w] = 1;\n }\n\n \/\/ must start with a black segment\n if (*data != 0) {\n for (int w = 0; w < WIDTH; w++) {\n if (((const uint8_t*)(data))[w] != 0) {\n *++(back[w]) = rle_t(0);\n n[w]++;\n }\n }\n }\n data += skip;\n\n \/\/ store indices of changes\n for (int row = 1; row < dims.height; row++, data += skip) {\n const batch_t* prev = data - skip;\n if (*data != *prev) {\n for (int w = 0; w < WIDTH; w++) {\n if (((const uint8_t*)(data))[w] != ((const uint8_t*)(prev))[w]) {\n if ((n[w] & 1) == 0 && (row - *(back[w])) < minHeight) {\n \/\/ remove noise\n back[w]--;\n n[w]--;\n noise++;\n } else {\n *++(back[w]) = rle_t(row);\n n[w]++;\n }\n }\n }\n }\n }\n\n for (int w = 0; w < WIDTH; w++, origX += int16_t(step)) {\n \/\/ must end with a black segment\n if ((n[w] & 1) == 0) {\n *++(back[w]) = rle_t(dims.height);\n n[w]++;\n }\n\n \/\/ add bottom of image\n *++(back[w]) = rle_t(dims.height + pad);\n n[w]++;\n\n \/\/ report white segments as strips if all conditions are met\n rle_t* lastWhite = back[w] - 1;\n for (rle_t* i = front[w]; i < lastWhite; i += 2) {\n if (*(i + 1) - *(i + 0) >= minGap && *(i + 3) - *(i + 2) >= minGap) {\n int halfHeight = (*(i + 2) - *(i + 1)) * halfStep;\n int origY = (*(i + 2) + *(i + 1)) * halfStep;\n tempEnd->pos = {int16_t(origX), int16_t(origY)};\n tempEnd->halfDims = {int16_t(halfStep), int16_t(halfHeight)};\n tempEnd++;\n }\n }\n }\n\n \/\/ move data outside\n {\n std::lock_guard<std::mutex> lock(mMutex);\n\n mOut->insert(mOut->end(), temp, tempEnd);\n tempEnd = temp;\n\n *mNoiseOut += noise;\n noise = 0;\n }\n }\n }\n\n private:\n const Dims mDims;\n const int mRleStep;\n const int mRleSz;\n const int mTempSz;\n const int mSkip;\n const int mStep;\n const int mMinHeight;\n const int mMinGap;\n const batch_t* const mData;\n std::vector<rle_t>* const mRle;\n std::vector<StripRepr>* const mTemp;\n std::vector<StripRepr>* const mOut;\n int* const mNoiseOut;\n const int mNumThreads;\n mutable std::mutex mMutex;\n };\n\n void NewStripGen::operator()(const fmo::Mat& img, int minHeight, int minGap, int step,\n std::vector<StripRepr>& out, int& outNoise) {\n \/\/ run in parallel\n int numThreads = cv::getNumThreads();\n StripGenImpl job{img, minHeight, minGap, step, mRle, mTemp, out, outNoise, numThreads};\n cv::parallel_for_(cv::Range{0, numThreads}, job);\n\n \/\/ order strips by their top edge\n auto stripComp = [] (const StripRepr& l, const StripRepr& r) {\n if (l.pos.x == r.pos.x) {\n return (l.pos.y - l.halfDims.height) < (r.pos.y - r.halfDims.height);\n } else {\n return l.pos.x < r.pos.x;\n }\n };\n std::sort(begin(out), end(out), stripComp);\n }\n}\n<commit_msg>Fix GCC warning<commit_after>#include \"include-opencv.hpp\"\n#include <algorithm>\n#include <cstdint>\n#include <fmo\/assert.hpp>\n#include <fmo\/common.hpp>\n#include <mutex>\n#include <vector>\n#include <fmo\/stripgen.hpp>\n\nnamespace fmo {\n struct StripGenImpl : public cv::ParallelLoopBody {\n using batch_t = uint64_t;\n using rle_t = int16_t;\n\n enum {\n WIDTH = sizeof(batch_t),\n };\n\n StripGenImpl(const fmo::Mat& img, int minHeight, int minGap, int step,\n std::vector<rle_t>& rle, std::vector<StripRepr>& temp,\n std::vector<StripRepr>& out, int& noiseOut, int numThreads)\n : mDims(img.dims()),\n mRleStep(mDims.height + 4),\n mRleSz(mRleStep * WIDTH),\n mTempSz((mRleSz + 1) \/ 2),\n mSkip(int(img.skip()) \/ WIDTH),\n mStep(step),\n mMinHeight(minHeight),\n mMinGap(minGap),\n mData((const batch_t*)(img.data())),\n mRle(&rle),\n mTemp(&temp),\n mOut(&out),\n mNoiseOut(&noiseOut),\n mNumThreads(numThreads) {\n FMO_ASSERT(int(img.skip()) % WIDTH == 0, \"StripGen::operator(): bad skip\");\n mRle->resize(mRleSz * mNumThreads);\n mTemp->resize(mTempSz * mNumThreads);\n mOut->clear();\n *mNoiseOut = 0;\n }\n\n virtual void operator()(const cv::Range& r) const override {\n const int threadNum = r.start;\n rle_t* const rle = mRle->data() + (mRleSz * threadNum);\n StripRepr* const temp = mTemp->data() + (mTempSz * threadNum);\n const int16_t step = int16_t(mStep);\n const int16_t halfStep = int16_t(mStep \/ 2);\n const int pad = std::max(0, std::max(mMinHeight, mMinGap));\n const int numBatches = mDims.width \/ WIDTH;\n const int batchFirst = (threadNum * numBatches) \/ mNumThreads;\n const int batchLast = ((threadNum + 1) * numBatches) \/ mNumThreads;\n const int colFirst = batchFirst * WIDTH;\n const int colLast = batchLast * WIDTH;\n const int skip = mSkip;\n const int minHeight = mMinHeight;\n const Dims dims = mDims;\n const int minGap = mMinGap;\n StripRepr* tempEnd = temp;\n\n int16_t origX = int16_t(halfStep + (colFirst * step));\n int noise = 0;\n rle_t* front[WIDTH];\n const batch_t* colData = mData + batchFirst;\n\n for (int w = 0; w < WIDTH; w++) { front[w] = rle + (w * mRleStep); }\n\n for (int col = colFirst; col < colLast; col += WIDTH, colData++) {\n const batch_t* data = colData;\n rle_t* back[WIDTH];\n int n[WIDTH];\n\n for (int w = 0; w < WIDTH; w++) {\n back[w] = front[w];\n\n \/\/ add top of image\n *back[w] = rle_t(-pad);\n n[w] = 1;\n }\n\n \/\/ must start with a black segment\n if (*data != 0) {\n for (int w = 0; w < WIDTH; w++) {\n if (((const uint8_t*)(data))[w] != 0) {\n *++(back[w]) = rle_t(0);\n n[w]++;\n }\n }\n }\n data += skip;\n\n \/\/ store indices of changes\n for (int row = 1; row < dims.height; row++, data += skip) {\n const batch_t* prev = data - skip;\n if (*data != *prev) {\n for (int w = 0; w < WIDTH; w++) {\n if (((const uint8_t*)(data))[w] != ((const uint8_t*)(prev))[w]) {\n if ((n[w] & 1) == 0 && (row - *(back[w])) < minHeight) {\n \/\/ remove noise\n back[w]--;\n n[w]--;\n noise++;\n } else {\n *++(back[w]) = rle_t(row);\n n[w]++;\n }\n }\n }\n }\n }\n\n for (int w = 0; w < WIDTH; w++, origX += int16_t(step)) {\n \/\/ must end with a black segment\n if ((n[w] & 1) == 0) {\n *++(back[w]) = rle_t(dims.height);\n n[w]++;\n }\n\n \/\/ add bottom of image\n *++(back[w]) = rle_t(dims.height + pad);\n n[w]++;\n\n \/\/ report white segments as strips if all conditions are met\n rle_t* lastWhite = back[w] - 1;\n for (rle_t* i = front[w]; i < lastWhite; i += 2) {\n if (*(i + 1) - *(i + 0) >= minGap && *(i + 3) - *(i + 2) >= minGap) {\n int halfHeight = (*(i + 2) - *(i + 1)) * halfStep;\n int origY = (*(i + 2) + *(i + 1)) * halfStep;\n tempEnd->pos = {int16_t(origX), int16_t(origY)};\n tempEnd->halfDims = {int16_t(halfStep), int16_t(halfHeight)};\n tempEnd++;\n }\n }\n }\n\n \/\/ move data outside\n {\n std::lock_guard<std::mutex> lock(mMutex);\n\n mOut->insert(mOut->end(), temp, tempEnd);\n tempEnd = temp;\n\n *mNoiseOut += noise;\n noise = 0;\n }\n }\n }\n\n private:\n const Dims mDims;\n const int mRleStep;\n const int mRleSz;\n const int mTempSz;\n const int mSkip;\n const int mStep;\n const int mMinHeight;\n const int mMinGap;\n const batch_t* const mData;\n std::vector<rle_t>* const mRle;\n std::vector<StripRepr>* const mTemp;\n std::vector<StripRepr>* const mOut;\n int* const mNoiseOut;\n const int mNumThreads;\n mutable std::mutex mMutex;\n };\n\n void NewStripGen::operator()(const fmo::Mat& img, int minHeight, int minGap, int step,\n std::vector<StripRepr>& out, int& outNoise) {\n \/\/ run in parallel\n int numThreads = cv::getNumThreads();\n StripGenImpl job{img, minHeight, minGap, step, mRle, mTemp, out, outNoise, numThreads};\n cv::parallel_for_(cv::Range{0, numThreads}, job);\n\n \/\/ order strips by their top edge\n auto stripComp = [] (const StripRepr& l, const StripRepr& r) {\n if (l.pos.x == r.pos.x) {\n return (l.pos.y - l.halfDims.height) < (r.pos.y - r.halfDims.height);\n } else {\n return l.pos.x < r.pos.x;\n }\n };\n std::sort(begin(out), end(out), stripComp);\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ Copyright (C) 2004 Stefan Seefeld\n\/\/ All rights reserved.\n\/\/ Licensed to the public under the terms of the GNU LGPL (>= 2),\n\/\/ see the file COPYING for details.\n\/\/\n#ifndef Synopsis_SymbolLookup_hh_\n#define Synopsis_SymbolLookup_hh_\n\n#include <Synopsis\/SymbolLookup\/Symbol.hh>\n#include <Synopsis\/SymbolLookup\/Scope.hh>\n#include <Synopsis\/SymbolLookup\/Scopes.hh>\n#include <Synopsis\/SymbolLookup\/Walker.hh>\n\n#endif\n<commit_msg>Refactoring Part 1<commit_after><|endoftext|>"} {"text":"<commit_before>\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License\n\n#include <signal.h>\n#include <stdio.h>\n#include <stdlib.h>\n#ifndef __WINDOWS__\n#include <unistd.h>\n#endif \/\/ __WINDOWS__\n#include <sys\/types.h>\n\n#ifdef __linux__\n#include <sys\/prctl.h>\n#endif \/\/ __linux__\n#include <sys\/types.h>\n\n#include <string>\n\n#include <glog\/logging.h>\n\n#include <process\/future.hpp>\n#include <process\/reap.hpp>\n#include <process\/subprocess.hpp>\n\n#include <stout\/error.hpp>\n#include <stout\/lambda.hpp>\n#include <stout\/foreach.hpp>\n#include <stout\/option.hpp>\n#include <stout\/os.hpp>\n#include <stout\/strings.hpp>\n#include <stout\/try.hpp>\n\nusing std::map;\nusing std::string;\nusing std::vector;\n\nnamespace process {\n\nusing InputFileDescriptors = Subprocess::IO::InputFileDescriptors;\nusing OutputFileDescriptors = Subprocess::IO::OutputFileDescriptors;\n\n\nSubprocess::ParentHook::ParentHook(\n const lambda::function<Try<Nothing>(pid_t)>& _parent_setup)\n : parent_setup(_parent_setup) {}\n\n\nSubprocess::ChildHook::ChildHook(\n const lambda::function<Try<Nothing>()>& _child_setup)\n : child_setup(_child_setup) {}\n\n\nSubprocess::ChildHook Subprocess::ChildHook::CHDIR(\n const std::string& working_directory)\n{\n return Subprocess::ChildHook([working_directory]() -> Try<Nothing> {\n if (::chdir(working_directory.c_str()) == -1) {\n return Error(\"Could not chdir\");\n }\n\n return Nothing();\n });\n}\n\n\nSubprocess::ChildHook Subprocess::ChildHook::SETSID()\n{\n return Subprocess::ChildHook([]() -> Try<Nothing> {\n \/\/ Put child into its own process session to prevent slave suicide\n \/\/ on child process SIGKILL\/SIGTERM.\n if (::setsid() == -1) {\n return Error(\"Could not setsid\");\n }\n\n return Nothing();\n });\n}\n\n\ninline void signalHandler(int signal)\n{\n \/\/ Send SIGKILL to every process in the process group of the\n \/\/ calling process.\n kill(0, SIGKILL);\n abort();\n}\n\n\nSubprocess::ChildHook Subprocess::ChildHook::SUPERVISOR()\n{\n return Subprocess::ChildHook([]() -> Try<Nothing> {\n#ifdef __linux__\n \/\/ Send SIGTERM to the current process if the parent (i.e., the\n \/\/ slave) exits.\n \/\/ NOTE:: This function should always succeed because we are passing\n \/\/ in a valid signal.\n prctl(PR_SET_PDEATHSIG, SIGTERM);\n\n \/\/ Put the current process into a separate process group so that\n \/\/ we can kill it and all its children easily.\n if (setpgid(0, 0) != 0) {\n return Error(\"Could not start supervisor process.\");\n }\n\n \/\/ Install a SIGTERM handler which will kill the current process\n \/\/ group. Since we already setup the death signal above, the\n \/\/ signal handler will be triggered when the parent (e.g., the\n \/\/ slave) exits.\n if (os::signals::install(SIGTERM, &signalHandler) != 0) {\n return Error(\"Could not start supervisor process.\");\n }\n\n pid_t pid = fork();\n if (pid == -1) {\n return Error(\"Could not start supervisor process.\");\n } else if (pid == 0) {\n \/\/ Child. This is the process that is going to exec the\n \/\/ process if zero is returned.\n\n \/\/ We setup death signal for the process as well in case\n \/\/ someone, though unlikely, accidentally kill the parent of\n \/\/ this process (the bookkeeping process).\n prctl(PR_SET_PDEATHSIG, SIGKILL);\n\n \/\/ NOTE: We don't need to clear the signal handler explicitly\n \/\/ because the subsequent 'exec' will clear them.\n return Nothing();\n } else {\n \/\/ Parent. This is the bookkeeping process which will wait for\n \/\/ the child process to finish.\n\n \/\/ Close the files to prevent interference on the communication\n \/\/ between the slave and the child process.\n ::close(STDIN_FILENO);\n ::close(STDOUT_FILENO);\n ::close(STDERR_FILENO);\n\n \/\/ Block until the child process finishes.\n int status = 0;\n if (waitpid(pid, &status, 0) == -1) {\n abort();\n }\n\n \/\/ Forward the exit status if the child process exits normally.\n if (WIFEXITED(status)) {\n _exit(WEXITSTATUS(status));\n }\n\n abort();\n UNREACHABLE();\n }\n#endif\n return Nothing();\n });\n}\n\n\nnamespace internal {\n\nstatic void cleanup(\n const Future<Option<int>>& result,\n Promise<Option<int>>* promise,\n const Subprocess& subprocess)\n{\n CHECK(!result.isPending());\n CHECK(!result.isDiscarded());\n\n if (result.isFailed()) {\n promise->fail(result.failure());\n } else {\n promise->set(result.get());\n }\n\n delete promise;\n}\n\n} \/\/ namespace internal {\n\n\n\/\/ Executes a subprocess.\n\/\/\n\/\/ NOTE: On Windows, components of the `path` and `argv` that need to be quoted\n\/\/ are expected to have been quoted before they are passed to `subprocess. For\n\/\/ example, either of these may contain paths with spaces in them, like\n\/\/ `C:\\\"Program Files\"\\foo.exe`, where notably the character sequence `\\\"` does\n\/\/ is not escaped quote, but instead a path separator and the start of a path\n\/\/ component. Since the semantics of quoting are shell-dependent, it is not\n\/\/ practical to attempt to re-parse the command that is passed in and properly\n\/\/ escape it. Therefore, incorrectly-quoted command arguments will probably\n\/\/ lead the child process to terminate with an error.\nTry<Subprocess> subprocess(\n const string& path,\n vector<string> argv,\n const Subprocess::IO& in,\n const Subprocess::IO& out,\n const Subprocess::IO& err,\n const flags::FlagsBase* flags,\n const Option<map<string, string>>& environment,\n const Option<lambda::function<\n pid_t(const lambda::function<int()>&)>>& _clone,\n const vector<Subprocess::ParentHook>& parent_hooks,\n const vector<Subprocess::ChildHook>& child_hooks)\n{\n \/\/ File descriptors for redirecting stdin\/stdout\/stderr.\n \/\/ These file descriptors are used for different purposes depending\n \/\/ on the specified I\/O modes.\n \/\/ See `Subprocess::PIPE`, `Subprocess::PATH`, and `Subprocess::FD`.\n InputFileDescriptors stdinfds;\n OutputFileDescriptors stdoutfds;\n OutputFileDescriptors stderrfds;\n\n \/\/ Prepare the file descriptor(s) for stdin.\n Try<InputFileDescriptors> input = in.input();\n if (input.isError()) {\n return Error(input.error());\n }\n\n stdinfds = input.get();\n\n \/\/ Prepare the file descriptor(s) for stdout.\n Try<OutputFileDescriptors> output = out.output();\n if (output.isError()) {\n process::internal::close(stdinfds, stdoutfds, stderrfds);\n return Error(output.error());\n }\n\n stdoutfds = output.get();\n\n \/\/ Prepare the file descriptor(s) for stderr.\n output = err.output();\n if (output.isError()) {\n process::internal::close(stdinfds, stdoutfds, stderrfds);\n return Error(output.error());\n }\n\n stderrfds = output.get();\n\n#ifndef __WINDOWS__\n \/\/ TODO(jieyu): Consider using O_CLOEXEC for atomic close-on-exec.\n Try<Nothing> cloexec = internal::cloexec(stdinfds, stdoutfds, stderrfds);\n if (cloexec.isError()) {\n process::internal::close(stdinfds, stdoutfds, stderrfds);\n return Error(\"Failed to cloexec: \" + cloexec.error());\n }\n#endif \/\/ __WINDOWS__\n\n \/\/ Prepare the arguments. If the user specifies the 'flags', we will\n \/\/ stringify them and append them to the existing arguments.\n if (flags != nullptr) {\n foreachvalue (const flags::Flag& flag, *flags) {\n Option<string> value = flag.stringify(*flags);\n if (value.isSome()) {\n argv.push_back(\"--\" + flag.effective_name().value + \"=\" + value.get());\n }\n }\n }\n\n \/\/ Parent.\n Subprocess process;\n\n \/\/ Create child, passing in stdin\/stdout\/stderr handles. We store the\n \/\/ information and data structures we need to manage the lifecycle of the\n \/\/ child (e.g., the PID of the child) in `process.data`.\n \/\/\n \/\/ NOTE: We use lexical blocking around the `#ifdef` to limit use of data\n \/\/ structures declared in the `#ifdef`. Since objects like `pid` will go out\n \/\/ of scope at the end of the block, there is no chance we will accidentally\n \/\/ define something in (say) the `__WINDOWS__` branch and then attempt to use\n \/\/ it in the non-`__WINDOWS__` branch.\n {\n#ifndef __WINDOWS__\n Try<pid_t> pid = internal::cloneChild(\n path,\n argv,\n environment,\n _clone,\n parent_hooks,\n child_hooks,\n stdinfds,\n stdoutfds,\n stderrfds);\n\n if (pid.isError()) {\n return Error(pid.error());\n }\n\n process.data->pid = pid.get();\n#else\n \/\/ TODO(joerg84): Consider using the childHooks and parentHooks here.\n Try<PROCESS_INFORMATION> processInformation = internal::createChildProcess(\n path, argv, environment, stdinfds, stdoutfds, stderrfds);\n\n if (processInformation.isError()) {\n process::internal::close(stdinfds, stdoutfds, stderrfds);\n return Error(\n \"Could not launch child process\" + processInformation.error());\n }\n\n if (processInformation.get().dwProcessId == -1) {\n \/\/ Save the errno as 'close' below might overwrite it.\n ErrnoError error(\"Failed to clone\");\n process::internal::close(stdinfds, stdoutfds, stderrfds);\n return error;\n }\n\n process.data->processInformation = processInformation.get();\n process.data->pid = processInformation.get().dwProcessId;\n#endif \/\/ __WINDOWS__\n }\n\n \/\/ Close the child-ends of the file descriptors that are created\n \/\/ by this function.\n os::close(stdinfds.read);\n os::close(stdoutfds.write);\n os::close(stderrfds.write);\n\n \/\/ For any pipes, store the parent side of the pipe so that\n \/\/ the user can communicate with the subprocess.\n process.data->in = stdinfds.write;\n process.data->out = stdoutfds.read;\n process.data->err = stderrfds.read;\n\n \/\/ Rather than directly exposing the future from process::reap, we\n \/\/ must use an explicit promise so that we can ensure we can receive\n \/\/ the termination signal. Otherwise, the caller can discard the\n \/\/ reap future, and we will not know when it is safe to close the\n \/\/ file descriptors.\n Promise<Option<int>>* promise = new Promise<Option<int>>();\n process.data->status = promise->future();\n\n \/\/ We need to bind a copy of this Subprocess into the onAny callback\n \/\/ below to ensure that we don't close the file descriptors before\n \/\/ the subprocess has terminated (i.e., because the caller doesn't\n \/\/ keep a copy of this Subprocess around themselves).\n process::reap(process.data->pid)\n .onAny(lambda::bind(internal::cleanup, lambda::_1, promise, process));\n\n return process;\n}\n\n} \/\/ namespace process {\n<commit_msg>Windows: Fixed subprocess and setsid compilation errors.<commit_after>\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License\n\n#include <signal.h>\n#include <stdio.h>\n#include <stdlib.h>\n#ifndef __WINDOWS__\n#include <unistd.h>\n#endif \/\/ __WINDOWS__\n#include <sys\/types.h>\n\n#ifdef __linux__\n#include <sys\/prctl.h>\n#endif \/\/ __linux__\n#include <sys\/types.h>\n\n#include <string>\n\n#include <glog\/logging.h>\n\n#include <process\/future.hpp>\n#include <process\/reap.hpp>\n#include <process\/subprocess.hpp>\n\n#include <stout\/error.hpp>\n#include <stout\/lambda.hpp>\n#include <stout\/foreach.hpp>\n#include <stout\/option.hpp>\n#include <stout\/os.hpp>\n#include <stout\/strings.hpp>\n#include <stout\/try.hpp>\n\nusing std::map;\nusing std::string;\nusing std::vector;\n\nnamespace process {\n\nusing InputFileDescriptors = Subprocess::IO::InputFileDescriptors;\nusing OutputFileDescriptors = Subprocess::IO::OutputFileDescriptors;\n\n\nSubprocess::ParentHook::ParentHook(\n const lambda::function<Try<Nothing>(pid_t)>& _parent_setup)\n : parent_setup(_parent_setup) {}\n\n\nSubprocess::ChildHook::ChildHook(\n const lambda::function<Try<Nothing>()>& _child_setup)\n : child_setup(_child_setup) {}\n\n\nSubprocess::ChildHook Subprocess::ChildHook::CHDIR(\n const std::string& working_directory)\n{\n return Subprocess::ChildHook([working_directory]() -> Try<Nothing> {\n if (::chdir(working_directory.c_str()) == -1) {\n return Error(\"Could not chdir\");\n }\n\n return Nothing();\n });\n}\n\n\nSubprocess::ChildHook Subprocess::ChildHook::SETSID()\n{\n return Subprocess::ChildHook([]() -> Try<Nothing> {\n \/\/ TODO(josephw): By default, child processes on Windows do not\n \/\/ terminate when the parent terminates. We need to implement\n \/\/ `JobObject` support to change this default.\n#ifndef __WINDOWS__\n \/\/ Put child into its own process session to prevent slave suicide\n \/\/ on child process SIGKILL\/SIGTERM.\n if (::setsid() == -1) {\n return Error(\"Could not setsid\");\n }\n#endif \/\/ __WINDOWS__\n\n return Nothing();\n });\n}\n\n\n#ifdef __linux__\ninline void signalHandler(int signal)\n{\n \/\/ Send SIGKILL to every process in the process group of the\n \/\/ calling process.\n kill(0, SIGKILL);\n abort();\n}\n#endif \/\/ __linux__\n\n\nSubprocess::ChildHook Subprocess::ChildHook::SUPERVISOR()\n{\n return Subprocess::ChildHook([]() -> Try<Nothing> {\n#ifdef __linux__\n \/\/ Send SIGTERM to the current process if the parent (i.e., the\n \/\/ slave) exits.\n \/\/ NOTE:: This function should always succeed because we are passing\n \/\/ in a valid signal.\n prctl(PR_SET_PDEATHSIG, SIGTERM);\n\n \/\/ Put the current process into a separate process group so that\n \/\/ we can kill it and all its children easily.\n if (setpgid(0, 0) != 0) {\n return Error(\"Could not start supervisor process.\");\n }\n\n \/\/ Install a SIGTERM handler which will kill the current process\n \/\/ group. Since we already setup the death signal above, the\n \/\/ signal handler will be triggered when the parent (e.g., the\n \/\/ slave) exits.\n if (os::signals::install(SIGTERM, &signalHandler) != 0) {\n return Error(\"Could not start supervisor process.\");\n }\n\n pid_t pid = fork();\n if (pid == -1) {\n return Error(\"Could not start supervisor process.\");\n } else if (pid == 0) {\n \/\/ Child. This is the process that is going to exec the\n \/\/ process if zero is returned.\n\n \/\/ We setup death signal for the process as well in case\n \/\/ someone, though unlikely, accidentally kill the parent of\n \/\/ this process (the bookkeeping process).\n prctl(PR_SET_PDEATHSIG, SIGKILL);\n\n \/\/ NOTE: We don't need to clear the signal handler explicitly\n \/\/ because the subsequent 'exec' will clear them.\n return Nothing();\n } else {\n \/\/ Parent. This is the bookkeeping process which will wait for\n \/\/ the child process to finish.\n\n \/\/ Close the files to prevent interference on the communication\n \/\/ between the slave and the child process.\n ::close(STDIN_FILENO);\n ::close(STDOUT_FILENO);\n ::close(STDERR_FILENO);\n\n \/\/ Block until the child process finishes.\n int status = 0;\n if (waitpid(pid, &status, 0) == -1) {\n abort();\n }\n\n \/\/ Forward the exit status if the child process exits normally.\n if (WIFEXITED(status)) {\n _exit(WEXITSTATUS(status));\n }\n\n abort();\n UNREACHABLE();\n }\n#endif \/\/ __linux__\n return Nothing();\n });\n}\n\n\nnamespace internal {\n\nstatic void cleanup(\n const Future<Option<int>>& result,\n Promise<Option<int>>* promise,\n const Subprocess& subprocess)\n{\n CHECK(!result.isPending());\n CHECK(!result.isDiscarded());\n\n if (result.isFailed()) {\n promise->fail(result.failure());\n } else {\n promise->set(result.get());\n }\n\n delete promise;\n}\n\n} \/\/ namespace internal {\n\n\n\/\/ Executes a subprocess.\n\/\/\n\/\/ NOTE: On Windows, components of the `path` and `argv` that need to be quoted\n\/\/ are expected to have been quoted before they are passed to `subprocess. For\n\/\/ example, either of these may contain paths with spaces in them, like\n\/\/ `C:\\\"Program Files\"\\foo.exe`, where notably the character sequence `\\\"` does\n\/\/ is not escaped quote, but instead a path separator and the start of a path\n\/\/ component. Since the semantics of quoting are shell-dependent, it is not\n\/\/ practical to attempt to re-parse the command that is passed in and properly\n\/\/ escape it. Therefore, incorrectly-quoted command arguments will probably\n\/\/ lead the child process to terminate with an error.\nTry<Subprocess> subprocess(\n const string& path,\n vector<string> argv,\n const Subprocess::IO& in,\n const Subprocess::IO& out,\n const Subprocess::IO& err,\n const flags::FlagsBase* flags,\n const Option<map<string, string>>& environment,\n const Option<lambda::function<\n pid_t(const lambda::function<int()>&)>>& _clone,\n const vector<Subprocess::ParentHook>& parent_hooks,\n const vector<Subprocess::ChildHook>& child_hooks)\n{\n \/\/ File descriptors for redirecting stdin\/stdout\/stderr.\n \/\/ These file descriptors are used for different purposes depending\n \/\/ on the specified I\/O modes.\n \/\/ See `Subprocess::PIPE`, `Subprocess::PATH`, and `Subprocess::FD`.\n InputFileDescriptors stdinfds;\n OutputFileDescriptors stdoutfds;\n OutputFileDescriptors stderrfds;\n\n \/\/ Prepare the file descriptor(s) for stdin.\n Try<InputFileDescriptors> input = in.input();\n if (input.isError()) {\n return Error(input.error());\n }\n\n stdinfds = input.get();\n\n \/\/ Prepare the file descriptor(s) for stdout.\n Try<OutputFileDescriptors> output = out.output();\n if (output.isError()) {\n process::internal::close(stdinfds, stdoutfds, stderrfds);\n return Error(output.error());\n }\n\n stdoutfds = output.get();\n\n \/\/ Prepare the file descriptor(s) for stderr.\n output = err.output();\n if (output.isError()) {\n process::internal::close(stdinfds, stdoutfds, stderrfds);\n return Error(output.error());\n }\n\n stderrfds = output.get();\n\n#ifndef __WINDOWS__\n \/\/ TODO(jieyu): Consider using O_CLOEXEC for atomic close-on-exec.\n Try<Nothing> cloexec = internal::cloexec(stdinfds, stdoutfds, stderrfds);\n if (cloexec.isError()) {\n process::internal::close(stdinfds, stdoutfds, stderrfds);\n return Error(\"Failed to cloexec: \" + cloexec.error());\n }\n#endif \/\/ __WINDOWS__\n\n \/\/ Prepare the arguments. If the user specifies the 'flags', we will\n \/\/ stringify them and append them to the existing arguments.\n if (flags != nullptr) {\n foreachvalue (const flags::Flag& flag, *flags) {\n Option<string> value = flag.stringify(*flags);\n if (value.isSome()) {\n argv.push_back(\"--\" + flag.effective_name().value + \"=\" + value.get());\n }\n }\n }\n\n \/\/ Parent.\n Subprocess process;\n\n \/\/ Create child, passing in stdin\/stdout\/stderr handles. We store the\n \/\/ information and data structures we need to manage the lifecycle of the\n \/\/ child (e.g., the PID of the child) in `process.data`.\n \/\/\n \/\/ NOTE: We use lexical blocking around the `#ifdef` to limit use of data\n \/\/ structures declared in the `#ifdef`. Since objects like `pid` will go out\n \/\/ of scope at the end of the block, there is no chance we will accidentally\n \/\/ define something in (say) the `__WINDOWS__` branch and then attempt to use\n \/\/ it in the non-`__WINDOWS__` branch.\n {\n#ifndef __WINDOWS__\n Try<pid_t> pid = internal::cloneChild(\n path,\n argv,\n environment,\n _clone,\n parent_hooks,\n child_hooks,\n stdinfds,\n stdoutfds,\n stderrfds);\n\n if (pid.isError()) {\n return Error(pid.error());\n }\n\n process.data->pid = pid.get();\n#else\n \/\/ TODO(joerg84): Consider using the childHooks and parentHooks here.\n Try<PROCESS_INFORMATION> processInformation = internal::createChildProcess(\n path, argv, environment, stdinfds, stdoutfds, stderrfds);\n\n if (processInformation.isError()) {\n process::internal::close(stdinfds, stdoutfds, stderrfds);\n return Error(\n \"Could not launch child process\" + processInformation.error());\n }\n\n if (processInformation.get().dwProcessId == -1) {\n \/\/ Save the errno as 'close' below might overwrite it.\n ErrnoError error(\"Failed to clone\");\n process::internal::close(stdinfds, stdoutfds, stderrfds);\n return error;\n }\n\n process.data->processInformation = processInformation.get();\n process.data->pid = processInformation.get().dwProcessId;\n#endif \/\/ __WINDOWS__\n }\n\n \/\/ Close the child-ends of the file descriptors that are created\n \/\/ by this function.\n os::close(stdinfds.read);\n os::close(stdoutfds.write);\n os::close(stderrfds.write);\n\n \/\/ For any pipes, store the parent side of the pipe so that\n \/\/ the user can communicate with the subprocess.\n process.data->in = stdinfds.write;\n process.data->out = stdoutfds.read;\n process.data->err = stderrfds.read;\n\n \/\/ Rather than directly exposing the future from process::reap, we\n \/\/ must use an explicit promise so that we can ensure we can receive\n \/\/ the termination signal. Otherwise, the caller can discard the\n \/\/ reap future, and we will not know when it is safe to close the\n \/\/ file descriptors.\n Promise<Option<int>>* promise = new Promise<Option<int>>();\n process.data->status = promise->future();\n\n \/\/ We need to bind a copy of this Subprocess into the onAny callback\n \/\/ below to ensure that we don't close the file descriptors before\n \/\/ the subprocess has terminated (i.e., because the caller doesn't\n \/\/ keep a copy of this Subprocess around themselves).\n process::reap(process.data->pid)\n .onAny(lambda::bind(internal::cleanup, lambda::_1, promise, process));\n\n return process;\n}\n\n} \/\/ namespace process {\n<|endoftext|>"} {"text":"<commit_before>\/*\n * This source file is part of EasyPaint.\n *\n * Copyright (c) 2012 EasyPaint <https:\/\/github.com\/Gr1N\/EasyPaint>\n *\n * Permission is hereby granted, free of charge, to any person obtaining\n * a copy of this software and associated documentation files (the\n * \"Software\"), to deal in the Software without restriction, including\n * without limitation the rights to use, copy, modify, merge, publish,\n * distribute, sublicense, and\/or sell copies of the Software, and to\n * permit persons to whom the Software is furnished to do so, subject to\n * the following conditions:\n *\n * The above copyright notice and this permission notice shall be included\n * in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\n * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\n * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n *\/\n\n#include <QtGui\/QApplication>\n#include <QtCore\/QStringList>\n#include <QtCore\/QDebug>\n#include <QtCore\/QFile>\n#include <QtCore\/QTranslator>\n\n#include \"mainwindow.h\"\n#include \"datasingleton.h\"\n\nvoid printHelpMessage()\n{\n qDebug()<<\"EasyPaint - simple graphics painting program\\n\"\n \"Usage: easypaint [options] [filename]\\n\\n\"\n \"Options:\\n\"\n \"\\t-h, --help\\t\\tshow this help message and exit\\n\"\n \"\\t-v, --version\\t\\tshow program's version number and exit\";\n}\n\nvoid printVersion()\n{\n qDebug()<<\"0.0.1\";\n}\n\nint main(int argc, char *argv[])\n{\n QApplication a(argc, argv);\n a.setApplicationName(\"EasyPaint\");\n a.setApplicationVersion(\"0.0.1\");\n\n QStringList args = a.arguments();\n\n QRegExp rxArgHelp(\"--help\");\n QRegExp rxArgH(\"-h\");\n QRegExp rxArgVersion(\"--version\");\n QRegExp rxArgV(\"-v\");\n\n bool isHelp(false), isVer(false);\n QStringList filePaths;\n\n for(int i(1); i < args.size(); ++i)\n {\n if (rxArgHelp.indexIn(args.at(i)) != -1 ||\n rxArgH.indexIn(args.at(i)) != -1)\n {\n isHelp = true;\n }\n else if (rxArgVersion.indexIn(args.at(i)) != -1 ||\n rxArgV.indexIn(args.at(i)) != -1)\n {\n isVer = true;\n }\n else\n {\n if(QFile::exists(args.at(i)))\n {\n filePaths.append(args.at(i));\n }\n }\n\n }\n\n if(isHelp)\n {\n printHelpMessage();\n return 0;\n }\n else if(isVer)\n {\n printVersion();\n return 0;\n }\n\n QTranslator appTranslator;\n QString translationsPath(\"\/usr\/share\/easypaint\/translations\/\");\n QString appLanguage = DataSingleton::Instance()->getAppLanguage();\n if(appLanguage == \"system\")\n {\n appTranslator.load(translationsPath + \"easypaint_\" + QLocale::system().name());\n }\n else\n {\n appTranslator.load(translationsPath + appLanguage);\n }\n a.installTranslator(&appTranslator);\n\n MainWindow w(filePaths);\n w.show();\n\n return a.exec();\n}\n<commit_msg>Switch to version 0.1.0<commit_after>\/*\n * This source file is part of EasyPaint.\n *\n * Copyright (c) 2012 EasyPaint <https:\/\/github.com\/Gr1N\/EasyPaint>\n *\n * Permission is hereby granted, free of charge, to any person obtaining\n * a copy of this software and associated documentation files (the\n * \"Software\"), to deal in the Software without restriction, including\n * without limitation the rights to use, copy, modify, merge, publish,\n * distribute, sublicense, and\/or sell copies of the Software, and to\n * permit persons to whom the Software is furnished to do so, subject to\n * the following conditions:\n *\n * The above copyright notice and this permission notice shall be included\n * in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\n * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\n * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n *\/\n\n#include <QtGui\/QApplication>\n#include <QtCore\/QStringList>\n#include <QtCore\/QDebug>\n#include <QtCore\/QFile>\n#include <QtCore\/QTranslator>\n\n#include \"mainwindow.h\"\n#include \"datasingleton.h\"\n\nvoid printHelpMessage()\n{\n qDebug()<<\"EasyPaint - simple graphics painting program\\n\"\n \"Usage: easypaint [options] [filename]\\n\\n\"\n \"Options:\\n\"\n \"\\t-h, --help\\t\\tshow this help message and exit\\n\"\n \"\\t-v, --version\\t\\tshow program's version number and exit\";\n}\n\nvoid printVersion()\n{\n qDebug()<<\"0.1.0\";\n}\n\nint main(int argc, char *argv[])\n{\n QApplication a(argc, argv);\n a.setApplicationName(\"EasyPaint\");\n a.setApplicationVersion(\"0.0.1\");\n\n QStringList args = a.arguments();\n\n QRegExp rxArgHelp(\"--help\");\n QRegExp rxArgH(\"-h\");\n QRegExp rxArgVersion(\"--version\");\n QRegExp rxArgV(\"-v\");\n\n bool isHelp(false), isVer(false);\n QStringList filePaths;\n\n for(int i(1); i < args.size(); ++i)\n {\n if (rxArgHelp.indexIn(args.at(i)) != -1 ||\n rxArgH.indexIn(args.at(i)) != -1)\n {\n isHelp = true;\n }\n else if (rxArgVersion.indexIn(args.at(i)) != -1 ||\n rxArgV.indexIn(args.at(i)) != -1)\n {\n isVer = true;\n }\n else\n {\n if(QFile::exists(args.at(i)))\n {\n filePaths.append(args.at(i));\n }\n }\n\n }\n\n if(isHelp)\n {\n printHelpMessage();\n return 0;\n }\n else if(isVer)\n {\n printVersion();\n return 0;\n }\n\n QTranslator appTranslator;\n QString translationsPath(\"\/usr\/share\/easypaint\/translations\/\");\n QString appLanguage = DataSingleton::Instance()->getAppLanguage();\n if(appLanguage == \"system\")\n {\n appTranslator.load(translationsPath + \"easypaint_\" + QLocale::system().name());\n }\n else\n {\n appTranslator.load(translationsPath + appLanguage);\n }\n a.installTranslator(&appTranslator);\n\n MainWindow w(filePaths);\n w.show();\n\n return a.exec();\n}\n<|endoftext|>"} {"text":"<commit_before>\/* Copyright 2013 - 2015 Yurii Litvinov and CyberTech Labs Ltd.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License. *\/\n\n#include \"controller.h\"\n\n#include <QtCore\/QProcess>\n#include <QtCore\/QFileInfo>\n\n#include <QtXml\/QDomDocument>\n\n#include <trikKernel\/configurer.h>\n#include <trikKernel\/fileUtils.h>\n#include <trikKernel\/paths.h>\n#include <trikKernel\/exceptions\/internalErrorException.h>\n#include <trikControl\/brickFactory.h>\n#include <trikNetwork\/mailboxFactory.h>\n#include <trikNetwork\/gamepadFactory.h>\n#include <trikWiFi\/trikWiFi.h>\n\n#include \"runningWidget.h\"\n#include \"autoRunner.h\"\n\nusing namespace trikGui;\n\nconst int communicatorPort = 8888;\nconst int telemetryPort = 9000;\n\nController::Controller(const QString &configPath)\n\t: mBrick(trikControl::BrickFactory::create(configPath, trikKernel::Paths::mediaPath()))\n{\n\tif (configPath.isEmpty()) {\n\t\tthrow trikKernel::InternalErrorException(\"Config path is empty\");\n\t}\n\n\tauto correctedConfigPath = configPath.endsWith('\/') ? configPath : configPath + '\/';\n\n\ttrikKernel::Configurer configurer(correctedConfigPath + \"system-config.xml\"\n\t\t\t, correctedConfigPath + \"model-config.xml\");\n\t\/\/configurer.attributeByDevice(\"gamepad\", \"optional\");\n\n\tmGamepad.reset(trikNetwork::GamepadFactory::create(configurer));\n\tconnect(mGamepad.data(), SIGNAL(disconnect()), this, SIGNAL(gamepadDisconnected()));\n\tconnect(mGamepad.data(), SIGNAL(connected()), this, SIGNAL(gamepadConnected()));\n\n\tmMailbox.reset(trikNetwork::MailboxFactory::create(configurer));\n\tmTelemetry.reset(new trikTelemetry::TrikTelemetry(*mBrick, *mGamepad));\n\tmScriptRunner.reset(new trikScriptRunner::TrikScriptRunner(*mBrick, mMailbox.data(), mGamepad.data()));\n\tmCommunicator.reset(new trikCommunicator::TrikCommunicator(*mScriptRunner, configurer.version()));\n\n\tmWiFi.reset(new trikWiFi::TrikWiFi(\"\/tmp\/trikwifi\", \"\/var\/run\/wpa_supplicant\/wlan0\", this));\n\tconnect(mWiFi.data(), SIGNAL(connected()), this, SIGNAL(wiFiConnected()));\n\tconnect(mWiFi.data(), SIGNAL(disconnected(trikWiFi::DisconnectReason)), this, SIGNAL(wiFiDisconnected()));\n\n\tconnect(mCommunicator.data(), SIGNAL(stopCommandReceived()), this, SLOT(abortExecution()));\n\tconnect(mCommunicator.data(), SIGNAL(connected()), this, SLOT(updateCommunicatorStatus()));\n\tconnect(mCommunicator.data(), SIGNAL(disconnected()), this, SLOT(updateCommunicatorStatus()));\n\tconnect(mTelemetry.data(), SIGNAL(connected()), this, SLOT(updateCommunicatorStatus()));\n\tconnect(mTelemetry.data(), SIGNAL(disconnected()), this, SLOT(updateCommunicatorStatus()));\n\tconnect(mMailbox.data(), SIGNAL(connectionStatusChanged(bool)), this, SIGNAL(mailboxStatusChanged(bool)));\n\n\tconnect(mScriptRunner.data(), SIGNAL(completed(QString, int)), this, SLOT(scriptExecutionCompleted(QString, int)));\n\n\tconnect(mScriptRunner.data(), SIGNAL(startedScript(QString, int))\n\t\t\t, this, SLOT(scriptExecutionFromFileStarted(QString, int)));\n\n\tconnect(mScriptRunner.data(), SIGNAL(startedDirectScript(int))\n\t\t\t, this, SLOT(directScriptExecutionStarted(int)));\n\n\tconnect(mBrick.data(), SIGNAL(stopped()), this, SIGNAL(brickStopped()));\n\n\tmCommunicator->startServer(communicatorPort);\n\tmTelemetry->startServer(telemetryPort);\n\n\tmAutoRunner.reset(new AutoRunner(*this));\n\n\tmBrick->led()->green();\n}\n\nController::~Controller()\n{\n\tmBrick->led()->orange();\n}\n\nvoid Controller::runFile(const QString &filePath)\n{\n\tQFileInfo const fileInfo(filePath);\n\tif (fileInfo.suffix() == \"qts\" || fileInfo.suffix() == \"js\") {\n\t\tmScriptRunner->run(trikKernel::FileUtils::readFromFile(fileInfo.canonicalFilePath()), fileInfo.baseName());\n\t} else if (fileInfo.suffix() == \"wav\" || fileInfo.suffix() == \"mp3\") {\n\t\tmScriptRunner->run(\"brick.playSound(\\\"\" + fileInfo.canonicalFilePath() + \"\\\");\", fileInfo.baseName());\n\t} else if (fileInfo.suffix() == \"sh\") {\n\t\tQProcess::startDetached(\"sh\", {filePath});\n\t} else if (fileInfo.isExecutable()) {\n\t\tQProcess::startDetached(filePath);\n\t}\n}\n\nvoid Controller::abortExecution()\n{\n\temit hideScriptWidgets();\n\tmScriptRunner->abort();\n\n\t\/\/ Now script engine will stop (after some time maybe) and send \"completed\" signal, which will be caught and\n\t\/\/ processed as if a script finished by itself.\n}\n\ntrikControl::BrickInterface &Controller::brick()\n{\n\treturn *mBrick;\n}\n\ntrikNetwork::MailboxInterface *Controller::mailbox()\n{\n\treturn mMailbox.data();\n}\n\ntrikWiFi::TrikWiFi &Controller::wiFi()\n{\n\treturn *mWiFi;\n}\n\nbool Controller::communicatorConnectionStatus()\n{\n\treturn mTelemetry->activeConnections() > 0 && mCommunicator->activeConnections() > 0;\n}\n\nbool Controller::gamepadConnectionStatus() const\n{\n\tif (mGamepad != nullptr){\n\t\treturn mGamepad->isConnected();\n\t}\n\treturn false;\n}\n\nvoid Controller::updateCommunicatorStatus()\n{\n\temit communicatorStatusChanged(communicatorConnectionStatus());\n}\n\nvoid Controller::scriptExecutionCompleted(const QString &error, int scriptId)\n{\n\tif (error.isEmpty()) {\n\t\temit hideRunningWidget(scriptId);\n\t} else {\n\t\tmCommunicator->sendMessage(\"error: \" + error);\n\t\temit showError(error, scriptId);\n\t}\n\n\tmBrick->reset();\n\n\tif (mMailbox) {\n\t\tmMailbox->clearQueue();\n\t}\n\n\tif (mGamepad) {\n\t\tmGamepad->reset();\n\t}\n\n\tmBrick->led()->green();\n}\n\nvoid Controller::scriptExecutionFromFileStarted(const QString &fileName, int scriptId)\n{\n\temit showRunningWidget(fileName, scriptId);\n}\n\nvoid Controller::directScriptExecutionStarted(int scriptId)\n{\n\tscriptExecutionFromFileStarted(tr(\"direct command\"), scriptId);\n}\n<commit_msg>fixed build<commit_after>\/* Copyright 2013 - 2015 Yurii Litvinov and CyberTech Labs Ltd.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License. *\/\n\n#include \"controller.h\"\n\n#include <QtCore\/QProcess>\n#include <QtCore\/QFileInfo>\n\n#include <QtXml\/QDomDocument>\n\n#include <trikKernel\/configurer.h>\n#include <trikKernel\/fileUtils.h>\n#include <trikKernel\/paths.h>\n#include <trikKernel\/exceptions\/internalErrorException.h>\n#include <trikControl\/brickFactory.h>\n#include <trikNetwork\/mailboxFactory.h>\n#include <trikNetwork\/gamepadFactory.h>\n#include <trikWiFi\/trikWiFi.h>\n\n#include \"runningWidget.h\"\n#include \"autoRunner.h\"\n\nusing namespace trikGui;\n\nconst int communicatorPort = 8888;\nconst int telemetryPort = 9000;\n\nController::Controller(const QString &configPath)\n\t: mBrick(trikControl::BrickFactory::create(configPath, trikKernel::Paths::mediaPath()))\n{\n\tif (configPath.isEmpty()) {\n\t\tthrow trikKernel::InternalErrorException(\"Config path is empty\");\n\t}\n\n\tauto correctedConfigPath = configPath.endsWith('\/') ? configPath : configPath + '\/';\n\n\ttrikKernel::Configurer configurer(correctedConfigPath + \"system-config.xml\"\n\t\t\t, correctedConfigPath + \"model-config.xml\");\n\n\tmGamepad.reset(trikNetwork::GamepadFactory::create(configurer));\n\tconnect(mGamepad.data(), SIGNAL(disconnect()), this, SIGNAL(gamepadDisconnected()));\n\tconnect(mGamepad.data(), SIGNAL(connected()), this, SIGNAL(gamepadConnected()));\n\n\tmMailbox.reset(trikNetwork::MailboxFactory::create(configurer));\n\tmTelemetry.reset(new trikTelemetry::TrikTelemetry(*mBrick, *mGamepad));\n\tmScriptRunner.reset(new trikScriptRunner::TrikScriptRunner(*mBrick, mMailbox.data(), mGamepad.data()));\n\tmCommunicator.reset(new trikCommunicator::TrikCommunicator(*mScriptRunner, configurer.version()));\n\n\tmWiFi.reset(new trikWiFi::TrikWiFi(\"\/tmp\/trikwifi\", \"\/var\/run\/wpa_supplicant\/wlan0\", this));\n\tconnect(mWiFi.data(), SIGNAL(connected()), this, SIGNAL(wiFiConnected()));\n\tconnect(mWiFi.data(), SIGNAL(disconnected(trikWiFi::DisconnectReason)), this, SIGNAL(wiFiDisconnected()));\n\n\tconnect(mCommunicator.data(), SIGNAL(stopCommandReceived()), this, SLOT(abortExecution()));\n\tconnect(mCommunicator.data(), SIGNAL(connected()), this, SLOT(updateCommunicatorStatus()));\n\tconnect(mCommunicator.data(), SIGNAL(disconnected()), this, SLOT(updateCommunicatorStatus()));\n\tconnect(mTelemetry.data(), SIGNAL(connected()), this, SLOT(updateCommunicatorStatus()));\n\tconnect(mTelemetry.data(), SIGNAL(disconnected()), this, SLOT(updateCommunicatorStatus()));\n\tconnect(mMailbox.data(), SIGNAL(connectionStatusChanged(bool)), this, SIGNAL(mailboxStatusChanged(bool)));\n\n\tconnect(mScriptRunner.data(), SIGNAL(completed(QString, int)), this, SLOT(scriptExecutionCompleted(QString, int)));\n\n\tconnect(mScriptRunner.data(), SIGNAL(startedScript(QString, int))\n\t\t\t, this, SLOT(scriptExecutionFromFileStarted(QString, int)));\n\n\tconnect(mScriptRunner.data(), SIGNAL(startedDirectScript(int))\n\t\t\t, this, SLOT(directScriptExecutionStarted(int)));\n\n\tconnect(mBrick.data(), SIGNAL(stopped()), this, SIGNAL(brickStopped()));\n\n\tmCommunicator->startServer(communicatorPort);\n\tmTelemetry->startServer(telemetryPort);\n\n\tmAutoRunner.reset(new AutoRunner(*this));\n\n\tmBrick->led()->green();\n}\n\nController::~Controller()\n{\n\tmBrick->led()->orange();\n}\n\nvoid Controller::runFile(const QString &filePath)\n{\n\tQFileInfo const fileInfo(filePath);\n\tif (fileInfo.suffix() == \"qts\" || fileInfo.suffix() == \"js\") {\n\t\tmScriptRunner->run(trikKernel::FileUtils::readFromFile(fileInfo.canonicalFilePath()), fileInfo.baseName());\n\t} else if (fileInfo.suffix() == \"wav\" || fileInfo.suffix() == \"mp3\") {\n\t\tmScriptRunner->run(\"brick.playSound(\\\"\" + fileInfo.canonicalFilePath() + \"\\\");\", fileInfo.baseName());\n\t} else if (fileInfo.suffix() == \"sh\") {\n\t\tQProcess::startDetached(\"sh\", {filePath});\n\t} else if (fileInfo.isExecutable()) {\n\t\tQProcess::startDetached(filePath);\n\t}\n}\n\nvoid Controller::abortExecution()\n{\n\temit hideScriptWidgets();\n\tmScriptRunner->abort();\n\n\t\/\/ Now script engine will stop (after some time maybe) and send \"completed\" signal, which will be caught and\n\t\/\/ processed as if a script finished by itself.\n}\n\ntrikControl::BrickInterface &Controller::brick()\n{\n\treturn *mBrick;\n}\n\ntrikNetwork::MailboxInterface *Controller::mailbox()\n{\n\treturn mMailbox.data();\n}\n\ntrikWiFi::TrikWiFi &Controller::wiFi()\n{\n\treturn *mWiFi;\n}\n\nbool Controller::communicatorConnectionStatus()\n{\n\treturn mTelemetry->activeConnections() > 0 && mCommunicator->activeConnections() > 0;\n}\n\nbool Controller::gamepadConnectionStatus() const\n{\n\tif (mGamepad != nullptr) {\n\t\treturn mGamepad->isConnected();\n\t} else {\n\treturn false;\n\t}\n}\n\nvoid Controller::updateCommunicatorStatus()\n{\n\temit communicatorStatusChanged(communicatorConnectionStatus());\n}\n\nvoid Controller::scriptExecutionCompleted(const QString &error, int scriptId)\n{\n\tif (error.isEmpty()) {\n\t\temit hideRunningWidget(scriptId);\n\t} else {\n\t\tmCommunicator->sendMessage(\"error: \" + error);\n\t\temit showError(error, scriptId);\n\t}\n\n\tmBrick->reset();\n\n\tif (mMailbox) {\n\t\tmMailbox->clearQueue();\n\t}\n\n\tif (mGamepad) {\n\t\tmGamepad->reset();\n\t}\n\n\tmBrick->led()->green();\n}\n\nvoid Controller::scriptExecutionFromFileStarted(const QString &fileName, int scriptId)\n{\n\temit showRunningWidget(fileName, scriptId);\n}\n\nvoid Controller::directScriptExecutionStarted(int scriptId)\n{\n\tscriptExecutionFromFileStarted(tr(\"direct command\"), scriptId);\n}\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2008 by Sun Microsystems, Inc.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: edittoolbarcontroller.cxx,v $\n * $Revision: 1.5 $\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * <http:\/\/www.openoffice.org\/license.html>\n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_framework.hxx\"\n\n#ifndef __FRAMEWORK_UIELEMENT_EDITTOOLBARCONTROLLER_HXX\n#include \"uielement\/edittoolbarcontroller.hxx\"\n#endif\n\n\/\/_________________________________________________________________________________________________________________\n\/\/ my own includes\n\/\/_________________________________________________________________________________________________________________\n\n#ifndef __FRAMEWORK_TOOLBAR_HXX_\n#include \"uielement\/toolbar.hxx\"\n#endif\n\n\/\/_________________________________________________________________________________________________________________\n\/\/ interface includes\n\/\/_________________________________________________________________________________________________________________\n#include <com\/sun\/star\/util\/XURLTransformer.hpp>\n#include <com\/sun\/star\/frame\/XDispatchProvider.hpp>\n#include <com\/sun\/star\/beans\/PropertyValue.hpp>\n#include <com\/sun\/star\/lang\/DisposedException.hpp>\n#include <com\/sun\/star\/frame\/status\/ItemStatus.hpp>\n#include <com\/sun\/star\/frame\/status\/ItemState.hpp>\n#include <com\/sun\/star\/frame\/status\/Visibility.hpp>\n#include <com\/sun\/star\/frame\/XControlNotificationListener.hpp>\n\n\/\/_________________________________________________________________________________________________________________\n\/\/ other includes\n\/\/_________________________________________________________________________________________________________________\n#include <svtools\/toolboxcontroller.hxx>\n#include <vos\/mutex.hxx>\n#include <vcl\/svapp.hxx>\n#ifndef _VCL_MNEMONIC_HXX_\n#include <vcl\/mnemonic.hxx>\n#endif\n#include <tools\/urlobj.hxx>\n\nusing namespace ::rtl;\nusing namespace ::com::sun::star;\nusing namespace ::com::sun::star::uno;\nusing namespace ::com::sun::star::beans;\nusing namespace ::com::sun::star::lang;\nusing namespace ::com::sun::star::frame;\nusing namespace ::com::sun::star::frame::status;\nusing namespace ::com::sun::star::util;\n\nnamespace framework\n{\n\n\/\/ ------------------------------------------------------------------\n\n\/\/ Wrapper class to notify controller about events from edit.\n\/\/ Unfortunaltly the events are notifed through virtual methods instead\n\/\/ of Listeners.\n\nclass EditControl : public Edit\n{\n public:\n EditControl( Window* pParent, WinBits nStyle, IEditListener* pEditListener );\n virtual ~EditControl();\n\n virtual void Modify();\n virtual void KeyInput( const ::KeyEvent& rKEvt );\n virtual void GetFocus();\n virtual void LoseFocus();\n virtual long PreNotify( NotifyEvent& rNEvt );\n\n private:\n IEditListener* m_pEditListener;\n};\n\nEditControl::EditControl( Window* pParent, WinBits nStyle, IEditListener* pEditListener ) :\n Edit( pParent, nStyle )\n , m_pEditListener( pEditListener )\n{\n}\n\nEditControl::~EditControl()\n{\n m_pEditListener = 0;\n}\n\nvoid EditControl::Modify()\n{\n Edit::Modify();\n if ( m_pEditListener )\n m_pEditListener->Modify();\n}\n\nvoid EditControl::KeyInput( const ::KeyEvent& rKEvt )\n{\n Edit::KeyInput( rKEvt );\n if ( m_pEditListener )\n m_pEditListener->KeyInput( rKEvt );\n}\n\nvoid EditControl::GetFocus()\n{\n Edit::GetFocus();\n if ( m_pEditListener )\n m_pEditListener->GetFocus();\n}\n\nvoid EditControl::LoseFocus()\n{\n Edit::LoseFocus();\n if ( m_pEditListener )\n m_pEditListener->LoseFocus();\n}\n\nlong EditControl::PreNotify( NotifyEvent& rNEvt )\n{\n long nRet( 0 );\n if ( m_pEditListener )\n nRet = m_pEditListener->PreNotify( rNEvt );\n if ( nRet == 0 )\n nRet = Edit::PreNotify( rNEvt );\n\n return nRet;\n}\n\n\/\/ ------------------------------------------------------------------\n\nEditToolbarController::EditToolbarController(\n const Reference< XMultiServiceFactory >& rServiceManager,\n const Reference< XFrame >& rFrame,\n ToolBox* pToolbar,\n USHORT nID,\n sal_Int32 nWidth,\n const OUString& aCommand ) :\n ComplexToolbarController( rServiceManager, rFrame, pToolbar, nID, aCommand )\n , m_pEditControl( 0 )\n{\n m_pEditControl = new EditControl( m_pToolbar, WB_BORDER, this );\n if ( nWidth == 0 )\n nWidth = 100;\n\n \/\/ Calculate height of the edit field according to the application font height\n sal_Int32 nHeight = getFontSizePixel( m_pEditControl ) + 6 + 1;\n\n m_pEditControl->SetSizePixel( ::Size( nWidth, nHeight ));\n m_pToolbar->SetItemWindow( m_nID, m_pEditControl );\n}\n\n\/\/ ------------------------------------------------------------------\n\nEditToolbarController::~EditToolbarController()\n{\n}\n\n\/\/ ------------------------------------------------------------------\n\nvoid SAL_CALL EditToolbarController::dispose()\nthrow ( RuntimeException )\n{\n vos::OGuard aSolarMutexGuard( Application::GetSolarMutex() );\n\n m_pToolbar->SetItemWindow( m_nID, 0 );\n delete m_pEditControl;\n\n ComplexToolbarController::dispose();\n\n m_pEditControl = 0;\n}\n\n\/\/ ------------------------------------------------------------------\n\nvoid SAL_CALL EditToolbarController::execute( sal_Int16 KeyModifier )\nthrow ( RuntimeException )\n{\n Reference< XDispatch > xDispatch;\n Reference< XURLTransformer > xURLTransformer;\n OUString aCommandURL;\n OUString aSelectedText;\n ::com::sun::star::util::URL aTargetURL;\n\n {\n vos::OGuard aSolarMutexGuard( Application::GetSolarMutex() );\n\n if ( m_bDisposed )\n throw DisposedException();\n\n if ( m_bInitialized &&\n m_xFrame.is() &&\n m_xServiceManager.is() &&\n m_aCommandURL.getLength() )\n {\n xURLTransformer = m_xURLTransformer;\n xDispatch = getDispatchFromCommand( m_aCommandURL );\n aCommandURL = m_aCommandURL;\n aTargetURL = getInitializedURL();\n aSelectedText = m_pEditControl->GetText();\n }\n }\n\n if ( xDispatch.is() && aTargetURL.Complete.getLength() > 0 )\n {\n Sequence<PropertyValue> aArgs( 2 );\n\n \/\/ Add key modifier to argument list\n aArgs[0].Name = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( \"KeyModifier\" ));\n aArgs[0].Value <<= KeyModifier;\n aArgs[1].Name = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( \"Text\" ));\n aArgs[1].Value <<= aSelectedText;\n\n \/\/ Execute dispatch asynchronously\n ExecuteInfo* pExecuteInfo = new ExecuteInfo;\n pExecuteInfo->xDispatch = xDispatch;\n pExecuteInfo->aTargetURL = aTargetURL;\n pExecuteInfo->aArgs = aArgs;\n Application::PostUserEvent( STATIC_LINK(0, ComplexToolbarController , ExecuteHdl_Impl), pExecuteInfo );\n }\n}\n\n\/\/ ------------------------------------------------------------------\n\nvoid EditToolbarController::Modify()\n{\n notifyTextChanged( m_pEditControl->GetText() );\n}\n\nvoid EditToolbarController::KeyInput( const ::KeyEvent& \/*rKEvt*\/ )\n{\n}\n\nvoid EditToolbarController::GetFocus()\n{\n notifyFocusGet();\n}\n\nvoid EditToolbarController::LoseFocus()\n{\n notifyFocusLost();\n}\n\nlong EditToolbarController::PreNotify( NotifyEvent& rNEvt )\n{\n if( rNEvt.GetType() == EVENT_KEYINPUT )\n {\n const ::KeyEvent* pKeyEvent = rNEvt.GetKeyEvent();\n const KeyCode& rKeyCode = pKeyEvent->GetKeyCode();\n if(( rKeyCode.GetModifier() | rKeyCode.GetCode()) == KEY_RETURN )\n {\n \/\/ Call execute only with non-empty text\n if ( m_pEditControl->GetText().Len() > 0 )\n execute( rKeyCode.GetModifier() );\n return 1;\n }\n }\n\n return 0;\n}\n\n\/\/ --------------------------------------------------------\n\nvoid EditToolbarController::executeControlCommand( const ::com::sun::star::frame::ControlCommand& rControlCommand )\n{\n if ( rControlCommand.Command.equalsAsciiL( \"SetText\", 7 ))\n {\n for ( sal_Int32 i = 0; i < rControlCommand.Arguments.getLength(); i++ )\n {\n if ( rControlCommand.Arguments[i].Name.equalsAsciiL( \"Text\", 4 ))\n {\n rtl::OUString aText;\n rControlCommand.Arguments[i].Value >>= aText;\n m_pEditControl->SetText( aText );\n\n \/\/ send notification\n notifyTextChanged( aText );\n break;\n }\n }\n }\n}\n\n} \/\/ namespace\n<commit_msg>INTEGRATION: CWS obo30 (1.5.40); FILE MERGED 2008\/06\/05 14:55:31 obo 1.5.40.2: #i90100# missing EOL 2008\/05\/29 14:43:45 obo 1.5.40.1: #i90100# ambigous Reference during ENABLE_PCH build<commit_after>\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2008 by Sun Microsystems, Inc.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: edittoolbarcontroller.cxx,v $\n * $Revision: 1.6 $\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * <http:\/\/www.openoffice.org\/license.html>\n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_framework.hxx\"\n\n#ifndef __FRAMEWORK_UIELEMENT_EDITTOOLBARCONTROLLER_HXX\n#include \"uielement\/edittoolbarcontroller.hxx\"\n#endif\n\n\/\/_________________________________________________________________________________________________________________\n\/\/ my own includes\n\/\/_________________________________________________________________________________________________________________\n\n#ifndef __FRAMEWORK_TOOLBAR_HXX_\n#include \"uielement\/toolbar.hxx\"\n#endif\n\n\/\/_________________________________________________________________________________________________________________\n\/\/ interface includes\n\/\/_________________________________________________________________________________________________________________\n#include <com\/sun\/star\/util\/XURLTransformer.hpp>\n#include <com\/sun\/star\/frame\/XDispatchProvider.hpp>\n#include <com\/sun\/star\/beans\/PropertyValue.hpp>\n#include <com\/sun\/star\/lang\/DisposedException.hpp>\n#include <com\/sun\/star\/frame\/status\/ItemStatus.hpp>\n#include <com\/sun\/star\/frame\/status\/ItemState.hpp>\n#include <com\/sun\/star\/frame\/status\/Visibility.hpp>\n#include <com\/sun\/star\/frame\/XControlNotificationListener.hpp>\n\n\/\/_________________________________________________________________________________________________________________\n\/\/ other includes\n\/\/_________________________________________________________________________________________________________________\n#include <svtools\/toolboxcontroller.hxx>\n#include <vos\/mutex.hxx>\n#include <vcl\/svapp.hxx>\n#ifndef _VCL_MNEMONIC_HXX_\n#include <vcl\/mnemonic.hxx>\n#endif\n#include <tools\/urlobj.hxx>\n\nusing namespace ::com::sun::star;\nusing namespace ::com::sun::star::uno;\nusing namespace ::com::sun::star::beans;\nusing namespace ::com::sun::star::lang;\nusing namespace ::com::sun::star::frame;\nusing namespace ::com::sun::star::frame::status;\nusing namespace ::com::sun::star::util;\n\nnamespace framework\n{\n\n\/\/ ------------------------------------------------------------------\n\n\/\/ Wrapper class to notify controller about events from edit.\n\/\/ Unfortunaltly the events are notifed through virtual methods instead\n\/\/ of Listeners.\n\nclass EditControl : public Edit\n{\n public:\n EditControl( Window* pParent, WinBits nStyle, IEditListener* pEditListener );\n virtual ~EditControl();\n\n virtual void Modify();\n virtual void KeyInput( const ::KeyEvent& rKEvt );\n virtual void GetFocus();\n virtual void LoseFocus();\n virtual long PreNotify( NotifyEvent& rNEvt );\n\n private:\n IEditListener* m_pEditListener;\n};\n\nEditControl::EditControl( Window* pParent, WinBits nStyle, IEditListener* pEditListener ) :\n Edit( pParent, nStyle )\n , m_pEditListener( pEditListener )\n{\n}\n\nEditControl::~EditControl()\n{\n m_pEditListener = 0;\n}\n\nvoid EditControl::Modify()\n{\n Edit::Modify();\n if ( m_pEditListener )\n m_pEditListener->Modify();\n}\n\nvoid EditControl::KeyInput( const ::KeyEvent& rKEvt )\n{\n Edit::KeyInput( rKEvt );\n if ( m_pEditListener )\n m_pEditListener->KeyInput( rKEvt );\n}\n\nvoid EditControl::GetFocus()\n{\n Edit::GetFocus();\n if ( m_pEditListener )\n m_pEditListener->GetFocus();\n}\n\nvoid EditControl::LoseFocus()\n{\n Edit::LoseFocus();\n if ( m_pEditListener )\n m_pEditListener->LoseFocus();\n}\n\nlong EditControl::PreNotify( NotifyEvent& rNEvt )\n{\n long nRet( 0 );\n if ( m_pEditListener )\n nRet = m_pEditListener->PreNotify( rNEvt );\n if ( nRet == 0 )\n nRet = Edit::PreNotify( rNEvt );\n\n return nRet;\n}\n\n\/\/ ------------------------------------------------------------------\n\nEditToolbarController::EditToolbarController(\n const Reference< XMultiServiceFactory >& rServiceManager,\n const Reference< XFrame >& rFrame,\n ToolBox* pToolbar,\n USHORT nID,\n sal_Int32 nWidth,\n const ::rtl::OUString& aCommand ) :\n ComplexToolbarController( rServiceManager, rFrame, pToolbar, nID, aCommand )\n , m_pEditControl( 0 )\n{\n m_pEditControl = new EditControl( m_pToolbar, WB_BORDER, this );\n if ( nWidth == 0 )\n nWidth = 100;\n\n \/\/ Calculate height of the edit field according to the application font height\n sal_Int32 nHeight = getFontSizePixel( m_pEditControl ) + 6 + 1;\n\n m_pEditControl->SetSizePixel( ::Size( nWidth, nHeight ));\n m_pToolbar->SetItemWindow( m_nID, m_pEditControl );\n}\n\n\/\/ ------------------------------------------------------------------\n\nEditToolbarController::~EditToolbarController()\n{\n}\n\n\/\/ ------------------------------------------------------------------\n\nvoid SAL_CALL EditToolbarController::dispose()\nthrow ( RuntimeException )\n{\n vos::OGuard aSolarMutexGuard( Application::GetSolarMutex() );\n\n m_pToolbar->SetItemWindow( m_nID, 0 );\n delete m_pEditControl;\n\n ComplexToolbarController::dispose();\n\n m_pEditControl = 0;\n}\n\n\/\/ ------------------------------------------------------------------\n\nvoid SAL_CALL EditToolbarController::execute( sal_Int16 KeyModifier )\nthrow ( RuntimeException )\n{\n Reference< XDispatch > xDispatch;\n Reference< XURLTransformer > xURLTransformer;\n ::rtl::OUString aCommandURL;\n ::rtl::OUString aSelectedText;\n ::com::sun::star::util::URL aTargetURL;\n\n {\n vos::OGuard aSolarMutexGuard( Application::GetSolarMutex() );\n\n if ( m_bDisposed )\n throw DisposedException();\n\n if ( m_bInitialized &&\n m_xFrame.is() &&\n m_xServiceManager.is() &&\n m_aCommandURL.getLength() )\n {\n xURLTransformer = m_xURLTransformer;\n xDispatch = getDispatchFromCommand( m_aCommandURL );\n aCommandURL = m_aCommandURL;\n aTargetURL = getInitializedURL();\n aSelectedText = m_pEditControl->GetText();\n }\n }\n\n if ( xDispatch.is() && aTargetURL.Complete.getLength() > 0 )\n {\n Sequence<PropertyValue> aArgs( 2 );\n\n \/\/ Add key modifier to argument list\n aArgs[0].Name = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( \"KeyModifier\" ));\n aArgs[0].Value <<= KeyModifier;\n aArgs[1].Name = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( \"Text\" ));\n aArgs[1].Value <<= aSelectedText;\n\n \/\/ Execute dispatch asynchronously\n ExecuteInfo* pExecuteInfo = new ExecuteInfo;\n pExecuteInfo->xDispatch = xDispatch;\n pExecuteInfo->aTargetURL = aTargetURL;\n pExecuteInfo->aArgs = aArgs;\n Application::PostUserEvent( STATIC_LINK(0, ComplexToolbarController , ExecuteHdl_Impl), pExecuteInfo );\n }\n}\n\n\/\/ ------------------------------------------------------------------\n\nvoid EditToolbarController::Modify()\n{\n notifyTextChanged( m_pEditControl->GetText() );\n}\n\nvoid EditToolbarController::KeyInput( const ::KeyEvent& \/*rKEvt*\/ )\n{\n}\n\nvoid EditToolbarController::GetFocus()\n{\n notifyFocusGet();\n}\n\nvoid EditToolbarController::LoseFocus()\n{\n notifyFocusLost();\n}\n\nlong EditToolbarController::PreNotify( NotifyEvent& rNEvt )\n{\n if( rNEvt.GetType() == EVENT_KEYINPUT )\n {\n const ::KeyEvent* pKeyEvent = rNEvt.GetKeyEvent();\n const KeyCode& rKeyCode = pKeyEvent->GetKeyCode();\n if(( rKeyCode.GetModifier() | rKeyCode.GetCode()) == KEY_RETURN )\n {\n \/\/ Call execute only with non-empty text\n if ( m_pEditControl->GetText().Len() > 0 )\n execute( rKeyCode.GetModifier() );\n return 1;\n }\n }\n\n return 0;\n}\n\n\/\/ --------------------------------------------------------\n\nvoid EditToolbarController::executeControlCommand( const ::com::sun::star::frame::ControlCommand& rControlCommand )\n{\n if ( rControlCommand.Command.equalsAsciiL( \"SetText\", 7 ))\n {\n for ( sal_Int32 i = 0; i < rControlCommand.Arguments.getLength(); i++ )\n {\n if ( rControlCommand.Arguments[i].Name.equalsAsciiL( \"Text\", 4 ))\n {\n rtl::OUString aText;\n rControlCommand.Arguments[i].Value >>= aText;\n m_pEditControl->SetText( aText );\n\n \/\/ send notification\n notifyTextChanged( aText );\n break;\n }\n }\n }\n}\n\n} \/\/ namespace\n\n<|endoftext|>"} {"text":"<commit_before>\/* IBM_PROLOG_BEGIN_TAG *\/\n\/* This is an automatically generated prolog. *\/\n\/* *\/\n\/* $Source: src\/usr\/diag\/prdf\/plat\/pegasus\/prdfDramRepairs.C $ *\/\n\/* *\/\n\/* OpenPOWER HostBoot Project *\/\n\/* *\/\n\/* COPYRIGHT International Business Machines Corp. 2012,2014 *\/\n\/* *\/\n\/* Licensed under the Apache License, Version 2.0 (the \"License\"); *\/\n\/* you may not use this file except in compliance with the License. *\/\n\/* You may obtain a copy of the License at *\/\n\/* *\/\n\/* http:\/\/www.apache.org\/licenses\/LICENSE-2.0 *\/\n\/* *\/\n\/* Unless required by applicable law or agreed to in writing, software *\/\n\/* distributed under the License is distributed on an \"AS IS\" BASIS, *\/\n\/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or *\/\n\/* implied. See the License for the specific language governing *\/\n\/* permissions and limitations under the License. *\/\n\/* *\/\n\/* IBM_PROLOG_END_TAG *\/\n\n\/** @file prdfDramRepairs.C *\/\n\n#include <diag\/prdf\/prdfMain.H>\n#include <diag\/prdf\/common\/prdf_service_codes.H>\n#include \"common\/iipconst.h\"\n#include <prdfGlobal.H>\n#include <prdfTrace.H>\n#include <prdfErrlUtil.H>\n#include \"common\/prdfEnums.H\"\n#include \"common\/plat\/pegasus\/prdfCenMbaCaptureData.H\"\n#include \"common\/plat\/pegasus\/prdfCalloutUtil.H\"\n#include \"common\/plat\/pegasus\/prdfCenDqBitmap.H\"\n#include \"common\/plat\/pegasus\/prdfCenMarkstore.H\"\n#include \"common\/plat\/pegasus\/prdfCenMbaExtraSig.H\"\n#include \"common\/plat\/pegasus\/prdfCenSymbol.H\"\n#include \"common\/plat\/pegasus\/prdfMemoryMru.H\"\n#include \"framework\/service\/prdfPlatServices.H\"\n#include \"plat\/pegasus\/prdfPlatCalloutUtil.H\"\n\nusing namespace HWAS;\nusing namespace std;\nusing namespace TARGETING;\n\nnamespace PRDF\n{\n\nusing namespace PlatServices;\n\nnamespace RDR \/\/ local utility functions to support PRDF::restoreDramRepairs()\n{\n\n\/\/ Creates and returns an error log.\nerrlHndl_t createErrl( uint32_t i_reasonCode, TargetHandle_t i_mba,\n uint32_t i_signature )\n{\n uint64_t userdata12 = PRDF_GET_UINT64_FROM_UINT32( getHuid(i_mba), 0 );\n uint64_t userdata34 = PRDF_GET_UINT64_FROM_UINT32( i_signature, 0 );\n\n \/\/ Note that the error log tags are not needed because PRD uses its own\n \/\/ signature parser.\n\n return new ERRORLOG::ErrlEntry(\n ERRORLOG::ERRL_SEV_PREDICTIVE, \/\/ severity\n PRDF_RESTORE_DRAM_REPAIR, \/\/ module ID\n i_reasonCode, \/\/ reason code\n userdata12, \/\/ user data 1 & 2\n userdata34 ); \/\/ user data 3 & 4\n}\n\n\/\/------------------------------------------------------------------------------\n\n\/\/ If an error log is given, will add DRAM repairs FFDC and traces to error log,\n\/\/ then commit the error log.\nvoid commitErrl( errlHndl_t i_errl, TargetHandle_t i_mba )\n{\n if ( NULL != i_errl )\n {\n \/\/ Add capture data\n CenMbaCaptureData::addMemEccData( i_mba, i_errl );\n\n \/\/ Add traces\n i_errl->collectTrace( PRDF_COMP_NAME, 512 );\n\n \/\/ Commit the error log\n ERRORLOG::errlCommit( i_errl, PRDF_COMP_ID );\n }\n}\n\n\/\/------------------------------------------------------------------------------\n\n\/\/ If there were analysis errors, will create and commit an error log with 2nd\n\/\/ level support callout.\nvoid commitSoftError( uint32_t i_reasonCode, TargetHandle_t i_mba,\n uint32_t i_signature, bool i_analysisErrors )\n{\n if ( i_analysisErrors )\n {\n errlHndl_t errl = createErrl( i_reasonCode, i_mba, i_signature );\n errl->addProcedureCallout( EPUB_PRC_LVL_SUPP, SRCI_PRIORITY_HIGH );\n commitErrl( errl, i_mba );\n }\n}\n\n\/\/------------------------------------------------------------------------------\n\nbool processRepairedRanks( TargetHandle_t i_mba, uint8_t i_repairedRankMask )\n{\n #define PRDF_FUNC \"[processRepairedRanks] \"\n\n \/\/ The bits in i_repairedRankMask represent ranks that have repairs. Query\n \/\/ hardware and compare against RAS policies.\n\n bool o_calloutMade = false;\n bool analysisErrors = false;\n\n errlHndl_t errl = NULL; \/\/ Initially NULL, will create if needed.\n\n for ( uint8_t r = 0; r < MASTER_RANKS_PER_MBA; ++r )\n {\n if ( 0 == (i_repairedRankMask & (0x80 >> r)) )\n {\n continue; \/\/ this rank didn't have any repairs\n }\n\n CenRank rank ( r );\n CenMark mark;\n\n if ( SUCCESS != mssGetMarkStore(i_mba, rank, mark) )\n {\n PRDF_ERR( PRDF_FUNC\"mssGetMarkStore() failed: MBA=0x%08x rank=%d\",\n getHuid(i_mba), rank.getMaster() );\n analysisErrors = true;\n continue; \/\/ skip this rank\n }\n\n CenSymbol sp0, sp1, sp;\n\n if ( SUCCESS != mssGetSteerMux(i_mba, rank, sp0, sp1, sp))\n {\n PRDF_ERR( PRDF_FUNC\"mssGetSteerMux() failed: MBA=0x%08x rank=%d\",\n getHuid(i_mba), rank.getMaster() );\n analysisErrors = true;\n continue; \/\/ skip this rank\n }\n\n if ( (sp0.isValid() || sp1.isValid() || sp.isValid()) &&\n mark.getCM().isValid() )\n {\n \/\/ This rank has both a steer and a chip mark. Call out the DIMM\n \/\/ with the chip mark.\n\n if ( NULL == errl )\n {\n errl = createErrl( PRDF_DETECTED_FAIL_HARDWARE, i_mba,\n PRDFSIG_RdrRepairsUsed );\n }\n\n MemoryMru memoryMru( i_mba, rank, mark.getCM() );\n CalloutUtil::calloutMemoryMru( errl, memoryMru,\n SRCI_PRIORITY_HIGH,\n HWAS::DELAYED_DECONFIG,\n HWAS::GARD_Predictive );\n o_calloutMade = true;\n }\n }\n\n \/\/ Commit the error log, if needed.\n commitErrl( errl, i_mba );\n\n \/\/ Commit an additional error log indicating something failed in the\n \/\/ analysis, if needed.\n commitSoftError( PRDF_DETECTED_FAIL_SOFTWARE, i_mba,\n PRDFSIG_RdrInternalFail, analysisErrors );\n\n return o_calloutMade;\n\n #undef PRDF_FUNC\n}\n\n\/\/------------------------------------------------------------------------------\n\nbool processBadDimms( TargetHandle_t i_mba, uint8_t i_badDimmMask )\n{\n #define PRDF_FUNC \"[processBadDimms] \"\n\n \/\/ The bits in i_badDimmMask represent DIMMs that have exceeded the\n \/\/ available repairs. Callout these DIMMs.\n\n bool o_calloutMade = false;\n bool analysisErrors = false;\n\n errlHndl_t errl = NULL; \/\/ Initially NULL, will create if needed.\n\n \/\/ Iterate the list of all DIMMs be\n TargetHandleList dimms = getConnected( i_mba, TYPE_DIMM );\n for ( TargetHandleList::iterator i = dimms.begin(); i < dimms.end(); i++ )\n {\n uint8_t port = 0, dimm = 0;\n\n if ( SUCCESS != getMbaPort(*i, port) )\n {\n PRDF_ERR( PRDF_FUNC\"getMbaPort() failed: DIMM=0x%08x\", getHuid(*i));\n analysisErrors = true;\n continue; \/\/ skip this dimm\n }\n\n if ( SUCCESS != getMbaDimm(*i, dimm) )\n {\n PRDF_ERR( PRDF_FUNC\"getMbaDimm() failed: DIMM=0x%08x\", getHuid(*i));\n analysisErrors = true;\n continue; \/\/ skip this dimm\n }\n\n \/\/ The 4 bits of i_badDimmMask is defined as p0d0, p0d1, p1d0, and p1d1.\n uint8_t mask = 0x8 >> (port * PORT_SLCT_PER_MBA + dimm);\n\n if ( 0 != (i_badDimmMask & mask) )\n {\n if ( NULL == errl )\n {\n errl = createErrl( PRDF_DETECTED_FAIL_HARDWARE, i_mba,\n PRDFSIG_RdrRepairUnavail );\n }\n\n o_calloutMade = true;\n errl->addHwCallout( *i, SRCI_PRIORITY_HIGH, HWAS::DELAYED_DECONFIG,\n HWAS::GARD_Predictive );\n }\n }\n\n \/\/ Commit the error log, if needed.\n commitErrl( errl, i_mba );\n\n \/\/ Commit an additional error log indicating something failed in the\n \/\/ analysis, if needed.\n commitSoftError( PRDF_DETECTED_FAIL_SOFTWARE, i_mba,\n PRDFSIG_RdrInternalFail, analysisErrors );\n\n return o_calloutMade;\n\n #undef PRDF_FUNC\n}\n\n\/\/------------------------------------------------------------------------------\n\nbool screenBadDqs( TargetHandle_t i_mba, const std::vector<CenRank> & i_ranks )\n{\n #define PRDF_FUNC \"[screenBadDqs] \"\n\n \/\/ Callout any attached DIMMs that have any bad DQs.\n\n bool o_calloutMade = false;\n bool analysisErrors = false;\n\n for ( std::vector<CenRank>::const_iterator rank = i_ranks.begin();\n rank != i_ranks.end(); rank++ )\n {\n \/\/ The HW procedure to read the bad DQ attribute will callout the DIMM\n \/\/ if it has DRAM Repairs VPD and the DISABLE_DRAM_REPAIRS MNFG policy\n \/\/ flag is set. PRD will simply need to iterate through all the ranks\n \/\/ to ensure all DIMMs are screen and the procedure will do the rest.\n\n CenDqBitmap bitmap;\n if ( SUCCESS != getBadDqBitmap(i_mba, *rank, bitmap, true) )\n {\n PRDF_ERR( PRDF_FUNC\"getBadDqBitmap() failed: MBA=0x%08x rank=%d\",\n getHuid(i_mba), rank->getMaster() );\n analysisErrors = true;\n continue; \/\/ skip this rank\n }\n }\n\n \/\/ Commit an additional error log indicating something failed in the\n \/\/ analysis, if needed.\n commitSoftError( PRDF_DETECTED_FAIL_SOFTWARE, i_mba,\n PRDFSIG_RdrInternalFail, analysisErrors );\n\n return o_calloutMade;\n\n #undef PRDF_FUNC\n}\n\n\/\/------------------------------------------------------------------------------\n\nvoid deployDramSpares( TargetHandle_t i_mba,\n const std::vector<CenRank> & i_ranks )\n{\n bool x4 = isDramWidthX4(i_mba);\n\n for ( std::vector<CenRank>::const_iterator rank = i_ranks.begin();\n rank != i_ranks.end(); rank++ )\n {\n \/\/ Doesn't matter which DRAM is spared as long as they are all spared.\n \/\/ Also, make sure the ECC spare is on a different DRAM than the spare\n \/\/ DRAM.\n CenSymbol symPort0 = CenSymbol::fromDimmDq( i_mba, *rank, 0, 0 );\n CenSymbol symPort1 = CenSymbol::fromDimmDq( i_mba, *rank, 0, 1 );\n CenSymbol symEccSp = CenSymbol::fromDimmDq( i_mba, *rank, 8, 0 );\n\n int32_t l_rc = SUCCESS;\n\n l_rc = mssSetSteerMux( i_mba, *rank, symPort0, false );\n l_rc |= mssSetSteerMux( i_mba, *rank, symPort1, false );\n\n if ( x4 )\n l_rc |= mssSetSteerMux( i_mba, *rank, symEccSp, true );\n\n if ( SUCCESS != l_rc )\n {\n \/\/ mssSetSteerMux() will print a trace and commit the error log,\n \/\/ however, we need to handle the return code or we get a compile\n \/\/ warning in Hostboot.\n continue;\n }\n }\n}\n\n} \/\/ end namespace RDR\n\n\/\/------------------------------------------------------------------------------\n\/\/ External functions - declared in prdfMain.H\n\/\/------------------------------------------------------------------------------\n\nint32_t restoreDramRepairs( TargetHandle_t i_mba )\n{\n #define PRDF_FUNC \"PRDF::restoreDramRepairs\"\n\n PRDF_ENTER( PRDF_FUNC\"(0x%08x)\", getHuid(i_mba) );\n\n \/\/ will unlock when going out of scope\n PRDF_SYSTEM_SCOPELOCK;\n\n bool calloutMade = false;\n\n do\n {\n std::vector<CenRank> ranks;\n int32_t l_rc = getMasterRanks( i_mba, ranks );\n if ( SUCCESS != l_rc )\n {\n PRDF_ERR( \"[\"PRDF_FUNC\"] getMasterRanks() failed\" );\n\n RDR::commitSoftError( PRDF_DETECTED_FAIL_SOFTWARE, i_mba,\n PRDFSIG_RdrInternalFail, true );\n\n break; \/\/ Assume user meant to disable DRAM repairs.\n }\n\n bool spareDramDeploy = mnfgSpareDramDeploy();\n\n if ( spareDramDeploy )\n {\n \/\/ Deploy all spares for MNFG corner tests.\n RDR::deployDramSpares( i_mba, ranks );\n }\n\n if ( areDramRepairsDisabled() )\n {\n \/\/ DRAM Repairs are disabled in MNFG mode, so screen all DIMMs with\n \/\/ VPD information.\n if ( RDR::screenBadDqs(i_mba, ranks) ) calloutMade = true;\n\n \/\/ No need to continue because there will not be anything to\n \/\/ restore.\n break;\n }\n\n if ( spareDramDeploy )\n {\n \/\/ This is an error. The MNFG spare DRAM deply bit is set, but DRAM\n \/\/ Repairs have not been disabled.\n\n PRDF_ERR( \"[\"PRDF_FUNC\"] MNFG spare deploy enabled, but DRAM \"\n \"repairs are not disabled\" );\n\n RDR::commitSoftError( PRDF_INVALID_CONFIG, i_mba,\n PRDFSIG_RdrInvalidConfig, true );\n\n break; \/\/ Assume user meant to disable DRAM repairs.\n }\n\n uint8_t rankMask = 0, dimmMask = 0;\n if ( SUCCESS != mssRestoreDramRepairs(i_mba, rankMask, dimmMask) )\n {\n \/\/ Can't check anything if this doesn't work.\n PRDF_ERR( \"[\"PRDF_FUNC\"] mssRestoreDramRepairs() failed\" );\n break;\n }\n\n \/\/ Callout DIMMs with too many bad bits and not enough repairs available\n if ( RDR::processBadDimms(i_mba, dimmMask) ) calloutMade = true;\n\n \/\/ Check repaired ranks for RAS policy violations.\n if ( RDR::processRepairedRanks(i_mba, rankMask) ) calloutMade = true;\n\n } while(0);\n\n PRDF_EXIT( PRDF_FUNC\"(0x%08x)\", getHuid(i_mba) );\n\n return calloutMade ? FAIL : SUCCESS;\n\n #undef PRDF_FUNC\n}\n\n} \/\/ end namespace PRDF\n\n<commit_msg>PRD: add IS DIMM support for restore DRAM repairs<commit_after>\/* IBM_PROLOG_BEGIN_TAG *\/\n\/* This is an automatically generated prolog. *\/\n\/* *\/\n\/* $Source: src\/usr\/diag\/prdf\/plat\/pegasus\/prdfDramRepairs.C $ *\/\n\/* *\/\n\/* OpenPOWER HostBoot Project *\/\n\/* *\/\n\/* Contributors Listed Below - COPYRIGHT 2013,2014 *\/\n\/* [+] International Business Machines Corp. *\/\n\/* *\/\n\/* *\/\n\/* Licensed under the Apache License, Version 2.0 (the \"License\"); *\/\n\/* you may not use this file except in compliance with the License. *\/\n\/* You may obtain a copy of the License at *\/\n\/* *\/\n\/* http:\/\/www.apache.org\/licenses\/LICENSE-2.0 *\/\n\/* *\/\n\/* Unless required by applicable law or agreed to in writing, software *\/\n\/* distributed under the License is distributed on an \"AS IS\" BASIS, *\/\n\/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or *\/\n\/* implied. See the License for the specific language governing *\/\n\/* permissions and limitations under the License. *\/\n\/* *\/\n\/* IBM_PROLOG_END_TAG *\/\n\n\/** @file prdfDramRepairs.C *\/\n\n#include <diag\/prdf\/prdfMain.H>\n#include <diag\/prdf\/common\/prdf_service_codes.H>\n#include \"common\/iipconst.h\"\n#include <prdfGlobal.H>\n#include <prdfTrace.H>\n#include <prdfErrlUtil.H>\n#include \"common\/prdfEnums.H\"\n#include \"common\/plat\/pegasus\/prdfCenMbaCaptureData.H\"\n#include \"common\/plat\/pegasus\/prdfCalloutUtil.H\"\n#include \"common\/plat\/pegasus\/prdfCenDqBitmap.H\"\n#include \"common\/plat\/pegasus\/prdfCenMarkstore.H\"\n#include \"common\/plat\/pegasus\/prdfCenMbaExtraSig.H\"\n#include \"common\/plat\/pegasus\/prdfCenSymbol.H\"\n#include \"common\/plat\/pegasus\/prdfMemoryMru.H\"\n#include \"framework\/service\/prdfPlatServices.H\"\n#include \"plat\/pegasus\/prdfPlatCalloutUtil.H\"\n\nusing namespace HWAS;\nusing namespace std;\nusing namespace TARGETING;\n\nnamespace PRDF\n{\n\nusing namespace PlatServices;\n\nnamespace RDR \/\/ local utility functions to support PRDF::restoreDramRepairs()\n{\n\n\/\/ Creates and returns an error log.\nerrlHndl_t createErrl( uint32_t i_reasonCode, TargetHandle_t i_mba,\n uint32_t i_signature )\n{\n uint64_t userdata12 = PRDF_GET_UINT64_FROM_UINT32( getHuid(i_mba), 0 );\n uint64_t userdata34 = PRDF_GET_UINT64_FROM_UINT32( i_signature, 0 );\n\n \/\/ Note that the error log tags are not needed because PRD uses its own\n \/\/ signature parser.\n\n return new ERRORLOG::ErrlEntry(\n ERRORLOG::ERRL_SEV_PREDICTIVE, \/\/ severity\n PRDF_RESTORE_DRAM_REPAIR, \/\/ module ID\n i_reasonCode, \/\/ reason code\n userdata12, \/\/ user data 1 & 2\n userdata34 ); \/\/ user data 3 & 4\n}\n\n\/\/------------------------------------------------------------------------------\n\n\/\/ If an error log is given, will add DRAM repairs FFDC and traces to error log,\n\/\/ then commit the error log.\nvoid commitErrl( errlHndl_t i_errl, TargetHandle_t i_mba )\n{\n if ( NULL != i_errl )\n {\n \/\/ Add capture data\n CenMbaCaptureData::addMemEccData( i_mba, i_errl );\n\n \/\/ Add traces\n i_errl->collectTrace( PRDF_COMP_NAME, 512 );\n\n \/\/ Commit the error log\n ERRORLOG::errlCommit( i_errl, PRDF_COMP_ID );\n }\n}\n\n\/\/------------------------------------------------------------------------------\n\n\/\/ If there were analysis errors, will create and commit an error log with 2nd\n\/\/ level support callout.\nvoid commitSoftError( uint32_t i_reasonCode, TargetHandle_t i_mba,\n uint32_t i_signature, bool i_analysisErrors )\n{\n if ( i_analysisErrors )\n {\n errlHndl_t errl = createErrl( i_reasonCode, i_mba, i_signature );\n errl->addProcedureCallout( EPUB_PRC_LVL_SUPP, SRCI_PRIORITY_HIGH );\n commitErrl( errl, i_mba );\n }\n}\n\n\/\/------------------------------------------------------------------------------\n\nbool processRepairedRanks( TargetHandle_t i_mba, uint8_t i_repairedRankMask )\n{\n #define PRDF_FUNC \"[processRepairedRanks] \"\n\n \/\/ The bits in i_repairedRankMask represent ranks that have repairs. Query\n \/\/ hardware and compare against RAS policies.\n\n bool o_calloutMade = false;\n bool analysisErrors = false;\n\n errlHndl_t errl = NULL; \/\/ Initially NULL, will create if needed.\n\n bool isCen = false;\n int32_t l_rc = isMembufOnDimm( i_mba, isCen );\n if ( SUCCESS != l_rc )\n {\n PRDF_ERR( PRDF_FUNC\"isMembufOnDimm() failed\" );\n analysisErrors = true;\n }\n else\n {\n bool isX4 = isDramWidthX4( i_mba );\n\n for ( uint8_t r = 0; r < MASTER_RANKS_PER_MBA; ++r )\n {\n if ( 0 == (i_repairedRankMask & (0x80 >> r)) )\n {\n continue; \/\/ this rank didn't have any repairs\n }\n\n CenRank rank ( r );\n CenMark mark;\n\n if ( SUCCESS != mssGetMarkStore(i_mba, rank, mark) )\n {\n PRDF_ERR( PRDF_FUNC\"mssGetMarkStore() failed: MBA=0x%08x \"\n \"rank=%d\", getHuid(i_mba), rank.getMaster() );\n analysisErrors = true;\n continue; \/\/ skip this rank\n }\n\n CenSymbol sp0, sp1, ecc;\n\n if ( SUCCESS != mssGetSteerMux(i_mba, rank, sp0, sp1, ecc) )\n {\n PRDF_ERR( PRDF_FUNC\"mssGetSteerMux() failed: MBA=0x%08x \"\n \"rank=%d\", getHuid(i_mba), rank.getMaster() );\n analysisErrors = true;\n continue; \/\/ skip this rank\n }\n\n if ( mark.getCM().isValid() && \/\/ chip mark\n ( isCen || mark.getSM().isValid() ) && \/\/ symbol mark\n (!isCen || (sp0.isValid() || sp1.isValid())) && \/\/ DRAM spare\n (!isX4 || ecc.isValid() ) ) \/\/ ECC spare\n {\n \/\/ This rank has both a steer and a chip mark. Call out the DIMM\n \/\/ with the chip mark.\n\n if ( NULL == errl )\n {\n errl = createErrl( PRDF_DETECTED_FAIL_HARDWARE, i_mba,\n PRDFSIG_RdrRepairsUsed );\n }\n\n MemoryMru memoryMru( i_mba, rank, mark.getCM() );\n CalloutUtil::calloutMemoryMru( errl, memoryMru,\n SRCI_PRIORITY_HIGH,\n HWAS::DELAYED_DECONFIG,\n HWAS::GARD_Predictive );\n o_calloutMade = true;\n }\n }\n }\n\n \/\/ Commit the error log, if needed.\n commitErrl( errl, i_mba );\n\n \/\/ Commit an additional error log indicating something failed in the\n \/\/ analysis, if needed.\n commitSoftError( PRDF_DETECTED_FAIL_SOFTWARE, i_mba,\n PRDFSIG_RdrInternalFail, analysisErrors );\n\n return o_calloutMade;\n\n #undef PRDF_FUNC\n}\n\n\/\/------------------------------------------------------------------------------\n\nbool processBadDimms( TargetHandle_t i_mba, uint8_t i_badDimmMask )\n{\n #define PRDF_FUNC \"[processBadDimms] \"\n\n \/\/ The bits in i_badDimmMask represent DIMMs that have exceeded the\n \/\/ available repairs. Callout these DIMMs.\n\n bool o_calloutMade = false;\n bool analysisErrors = false;\n\n errlHndl_t errl = NULL; \/\/ Initially NULL, will create if needed.\n\n \/\/ Iterate the list of all DIMMs be\n TargetHandleList dimms = getConnected( i_mba, TYPE_DIMM );\n for ( TargetHandleList::iterator i = dimms.begin(); i < dimms.end(); i++ )\n {\n uint8_t port = 0, dimm = 0;\n\n if ( SUCCESS != getMbaPort(*i, port) )\n {\n PRDF_ERR( PRDF_FUNC\"getMbaPort() failed: DIMM=0x%08x\", getHuid(*i));\n analysisErrors = true;\n continue; \/\/ skip this dimm\n }\n\n if ( SUCCESS != getMbaDimm(*i, dimm) )\n {\n PRDF_ERR( PRDF_FUNC\"getMbaDimm() failed: DIMM=0x%08x\", getHuid(*i));\n analysisErrors = true;\n continue; \/\/ skip this dimm\n }\n\n \/\/ The 4 bits of i_badDimmMask is defined as p0d0, p0d1, p1d0, and p1d1.\n uint8_t mask = 0x8 >> (port * PORT_SLCT_PER_MBA + dimm);\n\n if ( 0 != (i_badDimmMask & mask) )\n {\n if ( NULL == errl )\n {\n errl = createErrl( PRDF_DETECTED_FAIL_HARDWARE, i_mba,\n PRDFSIG_RdrRepairUnavail );\n }\n\n o_calloutMade = true;\n errl->addHwCallout( *i, SRCI_PRIORITY_HIGH, HWAS::DELAYED_DECONFIG,\n HWAS::GARD_Predictive );\n }\n }\n\n \/\/ Commit the error log, if needed.\n commitErrl( errl, i_mba );\n\n \/\/ Commit an additional error log indicating something failed in the\n \/\/ analysis, if needed.\n commitSoftError( PRDF_DETECTED_FAIL_SOFTWARE, i_mba,\n PRDFSIG_RdrInternalFail, analysisErrors );\n\n return o_calloutMade;\n\n #undef PRDF_FUNC\n}\n\n\/\/------------------------------------------------------------------------------\n\nbool screenBadDqs( TargetHandle_t i_mba, const std::vector<CenRank> & i_ranks )\n{\n #define PRDF_FUNC \"[screenBadDqs] \"\n\n \/\/ Callout any attached DIMMs that have any bad DQs.\n\n bool o_calloutMade = false;\n bool analysisErrors = false;\n\n for ( std::vector<CenRank>::const_iterator rank = i_ranks.begin();\n rank != i_ranks.end(); rank++ )\n {\n \/\/ The HW procedure to read the bad DQ attribute will callout the DIMM\n \/\/ if it has DRAM Repairs VPD and the DISABLE_DRAM_REPAIRS MNFG policy\n \/\/ flag is set. PRD will simply need to iterate through all the ranks\n \/\/ to ensure all DIMMs are screen and the procedure will do the rest.\n\n CenDqBitmap bitmap;\n if ( SUCCESS != getBadDqBitmap(i_mba, *rank, bitmap, true) )\n {\n PRDF_ERR( PRDF_FUNC\"getBadDqBitmap() failed: MBA=0x%08x rank=%d\",\n getHuid(i_mba), rank->getMaster() );\n analysisErrors = true;\n continue; \/\/ skip this rank\n }\n }\n\n \/\/ Commit an additional error log indicating something failed in the\n \/\/ analysis, if needed.\n commitSoftError( PRDF_DETECTED_FAIL_SOFTWARE, i_mba,\n PRDFSIG_RdrInternalFail, analysisErrors );\n\n return o_calloutMade;\n\n #undef PRDF_FUNC\n}\n\n\/\/------------------------------------------------------------------------------\n\nvoid deployDramSpares( TargetHandle_t i_mba,\n const std::vector<CenRank> & i_ranks )\n{\n bool x4 = isDramWidthX4(i_mba);\n\n for ( std::vector<CenRank>::const_iterator rank = i_ranks.begin();\n rank != i_ranks.end(); rank++ )\n {\n \/\/ Doesn't matter which DRAM is spared as long as they are all spared.\n \/\/ Also, make sure the ECC spare is on a different DRAM than the spare\n \/\/ DRAM.\n CenSymbol symPort0 = CenSymbol::fromDimmDq( i_mba, *rank, 0, 0 );\n CenSymbol symPort1 = CenSymbol::fromDimmDq( i_mba, *rank, 0, 1 );\n CenSymbol symEccSp = CenSymbol::fromDimmDq( i_mba, *rank, 8, 0 );\n\n int32_t l_rc = SUCCESS;\n\n l_rc = mssSetSteerMux( i_mba, *rank, symPort0, false );\n l_rc |= mssSetSteerMux( i_mba, *rank, symPort1, false );\n\n if ( x4 )\n l_rc |= mssSetSteerMux( i_mba, *rank, symEccSp, true );\n\n if ( SUCCESS != l_rc )\n {\n \/\/ mssSetSteerMux() will print a trace and commit the error log,\n \/\/ however, we need to handle the return code or we get a compile\n \/\/ warning in Hostboot.\n continue;\n }\n }\n}\n\n} \/\/ end namespace RDR\n\n\/\/------------------------------------------------------------------------------\n\/\/ External functions - declared in prdfMain.H\n\/\/------------------------------------------------------------------------------\n\nint32_t restoreDramRepairs( TargetHandle_t i_mba )\n{\n #define PRDF_FUNC \"PRDF::restoreDramRepairs\"\n\n PRDF_ENTER( PRDF_FUNC\"(0x%08x)\", getHuid(i_mba) );\n\n \/\/ will unlock when going out of scope\n PRDF_SYSTEM_SCOPELOCK;\n\n bool calloutMade = false;\n\n do\n {\n std::vector<CenRank> ranks;\n int32_t l_rc = getMasterRanks( i_mba, ranks );\n if ( SUCCESS != l_rc )\n {\n PRDF_ERR( \"[\"PRDF_FUNC\"] getMasterRanks() failed\" );\n\n RDR::commitSoftError( PRDF_DETECTED_FAIL_SOFTWARE, i_mba,\n PRDFSIG_RdrInternalFail, true );\n\n break; \/\/ Assume user meant to disable DRAM repairs.\n }\n\n bool spareDramDeploy = mnfgSpareDramDeploy();\n\n if ( spareDramDeploy )\n {\n \/\/ Deploy all spares for MNFG corner tests.\n RDR::deployDramSpares( i_mba, ranks );\n }\n\n if ( areDramRepairsDisabled() )\n {\n \/\/ DRAM Repairs are disabled in MNFG mode, so screen all DIMMs with\n \/\/ VPD information.\n if ( RDR::screenBadDqs(i_mba, ranks) ) calloutMade = true;\n\n \/\/ No need to continue because there will not be anything to\n \/\/ restore.\n break;\n }\n\n if ( spareDramDeploy )\n {\n \/\/ This is an error. The MNFG spare DRAM deply bit is set, but DRAM\n \/\/ Repairs have not been disabled.\n\n PRDF_ERR( \"[\"PRDF_FUNC\"] MNFG spare deploy enabled, but DRAM \"\n \"repairs are not disabled\" );\n\n RDR::commitSoftError( PRDF_INVALID_CONFIG, i_mba,\n PRDFSIG_RdrInvalidConfig, true );\n\n break; \/\/ Assume user meant to disable DRAM repairs.\n }\n\n uint8_t rankMask = 0, dimmMask = 0;\n if ( SUCCESS != mssRestoreDramRepairs(i_mba, rankMask, dimmMask) )\n {\n \/\/ Can't check anything if this doesn't work.\n PRDF_ERR( \"[\"PRDF_FUNC\"] mssRestoreDramRepairs() failed\" );\n break;\n }\n\n \/\/ Callout DIMMs with too many bad bits and not enough repairs available\n if ( RDR::processBadDimms(i_mba, dimmMask) ) calloutMade = true;\n\n \/\/ Check repaired ranks for RAS policy violations.\n if ( RDR::processRepairedRanks(i_mba, rankMask) ) calloutMade = true;\n\n } while(0);\n\n PRDF_EXIT( PRDF_FUNC\"(0x%08x)\", getHuid(i_mba) );\n\n return calloutMade ? FAIL : SUCCESS;\n\n #undef PRDF_FUNC\n}\n\n} \/\/ end namespace PRDF\n\n<|endoftext|>"} {"text":"<commit_before>\/*\r\n *\r\n * Copyright (C) 2009, Joacim Jacobsson ( j dot jacobsson at gmail dot com )\r\n * All rights reserved.\r\n *\r\n * See LICENSE file for details\r\n *\r\n *\/\r\n\r\n#include \"BehaviorTreeNode.h\"\r\n#include \"..\/NodeToNodeArrow.h\"\r\n#include <btree\/btree.h>\r\n\r\n#include <QtGui\/QtGui>\r\n\r\nconst char* const g_NodeResourcePaths[_E_MAX_GRIST_TYPES_] = {\r\n\t\":\/nodes\/unknown.svg\",\r\n\t\":\/nodes\/sequence.svg\",\r\n\t\":\/nodes\/selector.svg\",\r\n\t\":\/nodes\/parallel.svg\",\r\n\t\":\/nodes\/dyn_selector.svg\",\r\n\t\":\/nodes\/decorator.svg\",\r\n\t\":\/nodes\/action.svg\"\r\n};\r\n\r\nBehaviorTreeNode::BehaviorTreeNode( Node* n, BehaviorTreeNode* parent )\r\n\t: QGraphicsSvgItem( g_NodeResourcePaths[n->m_Grist.m_Type] )\r\n\t, m_Node( n )\r\n\t, m_PreviousParent( 0x0 )\r\n\t, m_MouseState( E_MS_NONE )\r\n{\r\n\tsetFlag( QGraphicsItem::ItemIsMovable, true );\r\n\tsetFlag( QGraphicsItem::ItemIsSelectable, true );\r\n\tsetFlag( QGraphicsItem::ItemStacksBehindParent, false );\r\n\r\n\tif( parent )\r\n\t\tsetParentItem( parent );\r\n\tsetZValue( 0.0 );\r\n}\r\n\r\nvoid BehaviorTreeNode::removeArrow(NodeToNodeArrow *arrow)\r\n{\r\n\tint index = m_Arrows.indexOf(arrow);\r\n\r\n\tif (index != -1)\r\n\t\tm_Arrows.removeAt(index);\r\n}\r\n\r\nvoid BehaviorTreeNode::removeArrows()\r\n{\r\n\tforeach( NodeToNodeArrow *arrow, m_Arrows )\r\n\t{\r\n\t\tarrow->startItem()->removeArrow(arrow);\r\n\t\tarrow->endItem()->removeArrow(arrow);\r\n\t\tscene()->removeItem(arrow);\r\n\t\tdelete arrow;\r\n\t}\r\n}\r\n\r\nvoid BehaviorTreeNode::addArrow(NodeToNodeArrow *arrow)\r\n{\r\n\tm_Arrows.append(arrow);\r\n}\r\n\r\nQVariant BehaviorTreeNode::itemChange( GraphicsItemChange change, const QVariant &value )\r\n{\r\n\tswitch( change )\r\n\t{\r\n\tcase ItemSelectedChange:\r\n\t\tupdate();\r\n\t\tbreak;\r\n\tcase ItemPositionChange:\r\n\t\tbreak;\r\n\t}\r\n\treturn QGraphicsSvgItem::itemChange( change, value );\r\n}\r\n\r\nvoid BehaviorTreeNode::mousePressEvent( QGraphicsSceneMouseEvent* event )\r\n{\r\n\tif( event->button() == Qt::LeftButton )\r\n\t{\r\n\t\tm_MouseState = E_MS_LB_DOWN;\r\n\t\tm_StartPos = event->screenPos();\r\n\t\tif( parentItem() )\r\n\t\t{\r\n\t\t\tm_PreviousParent = parentItem();\r\n\t\t\tQPointF position( scenePos() );\r\n\t\t\tsetParentItem( 0x0 );\r\n\t\t\tsetPos( position );\r\n\t\t}\r\n\t}\r\n\tQGraphicsSvgItem::mousePressEvent( event );\r\n}\r\n\r\nvoid BehaviorTreeNode::mouseReleaseEvent( QGraphicsSceneMouseEvent* event )\r\n{\r\n\tif( event->button() == Qt::LeftButton )\r\n\t{\r\n\t\tm_MouseState = E_MS_NONE;\r\n\t\tsetZValue( 0.0 );\r\n\t\tif( m_PreviousParent )\r\n\t\t{\r\n\t\t\tsetPos( m_PreviousParent->mapFromScene( scenePos() ) );\r\n\t\t\tsetParentItem( m_PreviousParent );\r\n\t\t\tm_PreviousParent = 0x0;\r\n\t\t}\r\n\t}\r\n\tQGraphicsSvgItem::mouseReleaseEvent( event );\r\n}\r\n\r\nvoid BehaviorTreeNode::mouseMoveEvent( QGraphicsSceneMouseEvent* event )\r\n{\r\n\tif( m_MouseState == E_MS_LB_DOWN )\r\n\t{\r\n\t\tif( m_StartPos != event->screenPos() )\r\n\t\t{\r\n\t\t\tm_MouseState = E_MS_DRAGGING;\r\n\t\t\tsetZValue( 1.0 );\r\n\t\t}\r\n\t}\r\n\tQGraphicsSvgItem::mouseMoveEvent( event );\r\n}\r\n<commit_msg>Unlinking node's when dragging.<commit_after>\/*\r\n *\r\n * Copyright (C) 2009, Joacim Jacobsson ( j dot jacobsson at gmail dot com )\r\n * All rights reserved.\r\n *\r\n * See LICENSE file for details\r\n *\r\n *\/\r\n\r\n#include \"BehaviorTreeNode.h\"\r\n#include \"..\/NodeToNodeArrow.h\"\r\n#include <btree\/btree.h>\r\n\r\n#include <QtGui\/QtGui>\r\n\r\nconst char* const g_NodeResourcePaths[_E_MAX_GRIST_TYPES_] = {\r\n\t\":\/nodes\/unknown.svg\",\r\n\t\":\/nodes\/sequence.svg\",\r\n\t\":\/nodes\/selector.svg\",\r\n\t\":\/nodes\/parallel.svg\",\r\n\t\":\/nodes\/dyn_selector.svg\",\r\n\t\":\/nodes\/decorator.svg\",\r\n\t\":\/nodes\/action.svg\"\r\n};\r\n\r\nBehaviorTreeNode::BehaviorTreeNode( Node* n, BehaviorTreeNode* parent )\r\n\t: QGraphicsSvgItem( g_NodeResourcePaths[n->m_Grist.m_Type] )\r\n\t, m_Node( n )\r\n\t, m_PreviousParent( 0x0 )\r\n\t, m_MouseState( E_MS_NONE )\r\n{\r\n\tsetFlag( QGraphicsItem::ItemIsMovable, true );\r\n\tsetFlag( QGraphicsItem::ItemIsSelectable, true );\r\n\tsetFlag( QGraphicsItem::ItemStacksBehindParent, false );\r\n\r\n\tif( parent )\r\n\t\tsetParentItem( parent );\r\n\tsetZValue( 0.0 );\r\n}\r\n\r\nvoid BehaviorTreeNode::removeArrow(NodeToNodeArrow *arrow)\r\n{\r\n\tint index = m_Arrows.indexOf(arrow);\r\n\r\n\tif (index != -1)\r\n\t\tm_Arrows.removeAt(index);\r\n}\r\n\r\nvoid BehaviorTreeNode::removeArrows()\r\n{\r\n\tforeach( NodeToNodeArrow *arrow, m_Arrows )\r\n\t{\r\n\t\tarrow->startItem()->removeArrow(arrow);\r\n\t\tarrow->endItem()->removeArrow(arrow);\r\n\t\tscene()->removeItem(arrow);\r\n\t\tdelete arrow;\r\n\t}\r\n}\r\n\r\nvoid BehaviorTreeNode::addArrow(NodeToNodeArrow *arrow)\r\n{\r\n\tm_Arrows.append(arrow);\r\n}\r\n\r\nQVariant BehaviorTreeNode::itemChange( GraphicsItemChange change, const QVariant &value )\r\n{\r\n\tswitch( change )\r\n\t{\r\n\tcase ItemSelectedChange:\r\n\t\tupdate();\r\n\t\tbreak;\r\n\tcase ItemPositionChange:\r\n\t\tbreak;\r\n\t}\r\n\treturn QGraphicsSvgItem::itemChange( change, value );\r\n}\r\n\r\nvoid BehaviorTreeNode::mousePressEvent( QGraphicsSceneMouseEvent* event )\r\n{\r\n\tif( event->button() == Qt::LeftButton )\r\n\t{\r\n\t\tm_MouseState = E_MS_LB_DOWN;\r\n\t\tm_StartPos = event->screenPos();\r\n\t\tif( parentItem() )\r\n\t\t{\r\n\t\t\tm_PreviousParent = parentItem();\r\n\t\t\tQPointF position( scenePos() );\r\n\t\t\tsetParentItem( 0x0 );\r\n\t\t\tsetPos( position );\r\n\t\t}\r\n\t}\r\n\tQGraphicsSvgItem::mousePressEvent( event );\r\n}\r\n\r\nvoid BehaviorTreeNode::mouseReleaseEvent( QGraphicsSceneMouseEvent* event )\r\n{\r\n\tif( event->button() == Qt::LeftButton )\r\n\t{\r\n\t\tm_MouseState = E_MS_NONE;\r\n\t\tsetZValue( 0.0 );\r\n\t\tif( m_PreviousParent )\r\n\t\t{\r\n\t\t\tsetPos( m_PreviousParent->mapFromScene( scenePos() ) );\r\n\t\t\tsetParentItem( m_PreviousParent );\r\n\t\t\tm_PreviousParent = 0x0;\r\n\t\t}\r\n\t}\r\n\tQGraphicsSvgItem::mouseReleaseEvent( event );\r\n}\r\n\r\nvoid BehaviorTreeNode::mouseMoveEvent( QGraphicsSceneMouseEvent* event )\r\n{\r\n\tif( m_MouseState == E_MS_LB_DOWN )\r\n\t{\r\n\t\tif( m_StartPos != event->screenPos() )\r\n\t\t{\r\n\t\t\tm_MouseState = E_MS_DRAGGING;\r\n\t\t\tsetZValue( 1.0 );\r\n\r\n\t\t\tUnlinkNodeFromParentAndSiblings( m_Node );\r\n\r\n\t\t}\r\n\t}\r\n\tQGraphicsSvgItem::mouseMoveEvent( event );\r\n}\r\n<|endoftext|>"} {"text":"<commit_before>\/* Copyright © 2016 Taylor C. Richberger <taywee@gmx.com>\n * This code is released under the license described in the LICENSE file\n *\/\n\n#include <string>\n#include <vector>\n\nnamespace args\n{\n class ArgumentParser\n {\n private:\n std::string prog;\n std::string description;\n std::string epilog;\n\n public:\n ArgumentParser(\n const std::string &prog,\n const std::string &description,\n const std::string &epilog = std::string()) : prog(prog), description(description), epilog(epilog) {}\n\n void ParseArgs(const std::vector<std::string> &args)\n {\n }\n\n void ParseCLI(const int argc, const char * const * const argv)\n {\n std::vector<std::string> args;\n for (int i = 1; i < argc; ++i)\n {\n args.emplace_back(argv[i]);\n }\n ParseArgs(args);\n }\n };\n}\n<commit_msg>add validators, add more body to library<commit_after>\/* Copyright © 2016 Taylor C. Richberger <taywee@gmx.com>\n * This code is released under the license described in the LICENSE file\n *\/\n\n#include <string>\n#include <vector>\n#include <list>\n#include <functional>\n\nnamespace args\n{\n class Base\n {\n protected:\n bool matched;\n\n public:\n Base() : matched(false) {}\n virtual ~Base() {}\n\n virtual bool Matched() const\n {\n return matched;\n }\n };\n\n class Group : public Base\n {\n private:\n std::vector<Base*> children;\n std::function<bool(int, int)> validator;\n\n public:\n\n Group(const std::function<bool(int, int)> &validator = Validators::DontCare) : validator(validator) {}\n virtual ~Group() {}\n\n void Add(Base &child)\n {\n children.emplace_back(&child);\n }\n\n int MatchedChildren() const\n {\n int sum = 0;\n for (const Base * child: children)\n {\n if (child->Matched())\n {\n ++sum;\n }\n }\n return sum;\n }\n\n virtual bool Matched() const override\n {\n return validator(children.size(), MatchedChildren());\n }\n\n struct Validators\n {\n static bool Xor(int children, int matched)\n {\n return matched == 1;\n }\n\n static bool AtLeastOne(int children, int matched)\n {\n return matched >= 1;\n }\n\n static bool AtMostOne(int children, int matched)\n {\n return matched <= 1;\n }\n\n static bool All(int children, int matched)\n {\n return children == matched;\n }\n\n static bool DontCare(int children, int matched)\n {\n return true;\n }\n\n static bool CareTooMuch(int children, int matched)\n {\n return false;\n }\n\n static bool None(int children, int matched)\n {\n return matched == 0;\n }\n };\n };\n\n class ArgumentParser\n {\n private:\n std::string prog;\n std::string description;\n std::string epilog;\n\n Group args;\n\n public:\n ArgumentParser(\n const std::string &prog,\n const std::string &description,\n const std::string &epilog = std::string()) : prog(prog), description(description), epilog(epilog) {}\n\n void ParseArgs(const std::vector<std::string> &args)\n {\n }\n\n void ParseCLI(const int argc, const char * const * const argv)\n {\n std::vector<std::string> args;\n for (int i = 1; i < argc; ++i)\n {\n args.emplace_back(argv[i]);\n }\n ParseArgs(args);\n }\n };\n}\n<|endoftext|>"} {"text":"<commit_before>\/**\n *\n * Copyright 2007-2013 IMP Inventors. All rights reserved.\n *\n *\/\n#include \"rmfplugin.h\"\n#include <RMF\/exceptions.h>\n\nnamespace {\n\nvoid close_rmf_read(void *mydata) {\n Data *data = reinterpret_cast<Data *>(mydata);\n delete data;\n}\n\nvoid *open_rmf_read(const char *filename, const char *, int *natoms) {\n RMF_TRACE(\"open_rmf_read\");\n try {\n return new Data(filename, natoms);\n }\n catch (std::exception &e) {\n std::cerr << \"Caught exception: \" << e.what() << std::endl;\n *natoms = MOLFILE_NUMATOMS_NONE;\n return NULL;\n }\n}\n\nint read_rmf_structure(void *mydata, int *optflags, molfile_atom_t *atoms) {\n RMF_TRACE(\"read_rmf_structure\");\n try {\n Data *data = reinterpret_cast<Data *>(mydata);\n return data->read_structure(optflags, atoms);\n }\n catch (const std::exception &e) {\n std::cerr << \"Caught exception: \" << e.what() << std::endl;\n return VMDPLUGIN_ERROR;\n }\n}\n\nint read_rmf_timestep(void *mydata, int natoms, molfile_timestep_t *frame) {\n RMF_TRACE(\"Begin read_rmf_timestep: \" << natoms);\n try {\n Data *data = reinterpret_cast<Data *>(mydata);\n return data->read_timestep(frame);\n }\n catch (const std::exception &e) {\n std::cerr << \"Caught exception: \" << e.what() << std::endl;\n return VMDPLUGIN_ERROR;\n }\n}\n\nint read_rmf_bonds(void *mydata, int *nbonds, int **fromptr, int **toptr,\n float **bondorderptr, int **bondtype, int *nbondtypes,\n char ***bondtypename) {\n RMF_TRACE(\"Begin read_rmf_bonds\");\n try {\n Data *data = reinterpret_cast<Data *>(mydata);\n return data->read_bonds(nbonds, fromptr, toptr, bondorderptr, bondtype,\n nbondtypes, bondtypename);\n }\n catch (const std::exception &e) {\n std::cerr << \"Caught exception: \" << e.what() << std::endl;\n return VMDPLUGIN_ERROR;\n }\n}\n\nint read_rmf_graphics(void *mydata, int *nelem,\n const molfile_graphics_t **gdata) {\n RMF_TRACE(\"read_rmf_graphics\");\n try {\n Data *data = reinterpret_cast<Data *>(mydata);\n return data->read_graphics(nelem, gdata);\n }\n catch (const std::exception &e) {\n std::cerr << \"Caught exception: \" << e.what() << std::endl;\n return VMDPLUGIN_ERROR;\n }\n}\nint read_rmf_timestep_metadata(void *mydata,\n molfile_timestep_metadata_t *tdata) {\n RMF_TRACE(\"read_rmf_timestep_metadata\");\n try {\n Data *data = reinterpret_cast<Data *>(mydata);\n return data->read_timestep_metadata(tdata);\n }\n catch (const std::exception &e) {\n std::cerr << e.what() << std::endl;\n return VMDPLUGIN_ERROR;\n }\n}\n\nvoid init_plugin(molfile_plugin_t &plugin) {\n memset(&plugin, 0, sizeof(molfile_plugin_t));\n plugin.abiversion = vmdplugin_ABIVERSION;\n plugin.type = MOLFILE_PLUGIN_TYPE;\n plugin.name = \"rmf\";\n plugin.prettyname = \"RMF\";\n plugin.author = \"Daniel Russel\";\n plugin.majorv = 0;\n plugin.minorv = 9;\n \/\/ try this\n plugin.is_reentrant = VMDPLUGIN_THREADSAFE;\n plugin.open_file_read = open_rmf_read;\n plugin.read_structure = read_rmf_structure;\n plugin.read_bonds = read_rmf_bonds;\n plugin.read_rawgraphics = read_rmf_graphics;\n plugin.close_file_read = close_rmf_read;\n plugin.read_timestep_metadata = read_rmf_timestep_metadata;\n plugin.read_next_timestep = read_rmf_timestep;\n}\n\nvoid init_plugins() {\n init_plugin(plugin);\n plugin.name = \"rmf\";\n plugin.prettyname = \"RMF\";\n plugin.filename_extension = \"rmf\";\n init_plugin(plugin3);\n plugin3.name = \"rmf3\";\n plugin3.prettyname = \"RMF3\";\n plugin3.filename_extension = \"rmf3\";\n init_plugin(pluginz);\n pluginz.name = \"rmfz\";\n pluginz.prettyname = \"RMFz\";\n pluginz.filename_extension = \"rmfz\";\n \/\/ init_plugin(pluginrestraints);\n \/\/ pluginrestraints.name = \"rmf-with-restraints\";\n \/\/ pluginrestraints.prettyname = \"RMF with restraints\";\n \/\/ pluginrestraints.filename_extension = \"rmf-with-restraints\";\n \/\/ pluginrestraints.read_bonds = read_rmf_bonds_and_restraints;\n}\n}\n\nVMDPLUGIN_API int VMDPLUGIN_init() {\n init_plugins();\n RMF::set_log_level(\"trace\");\n return VMDPLUGIN_SUCCESS;\n}\nVMDPLUGIN_API int VMDPLUGIN_register(void *v, vmdplugin_register_cb cb) {\n std::cout << \"Register\" << std::endl;\n (*cb)(v, (vmdplugin_t *)&plugin);\n (*cb)(v, (vmdplugin_t *)&plugin3);\n (*cb)(v, (vmdplugin_t *)&pluginz);\n return 0;\n}\nVMDPLUGIN_API int VMDPLUGIN_fini() {\n std::cout << \"Fini\" << std::endl;\n return VMDPLUGIN_SUCCESS;\n}\n<commit_msg>use boost lamba to unify catch code<commit_after>\/**\n *\n * Copyright 2007-2013 IMP Inventors. All rights reserved.\n *\n *\/\n#include \"rmfplugin.h\"\n#include <RMF\/exceptions.h>\n#include <boost\/bind.hpp>\n#include <boost\/lambda\/construct.hpp>\n\nnamespace {\n\ntemplate <class M>\nint catch_exceptions(std::string name, void *mydata, M m) {\n RMF_TRACE(name);\n try {\n Data *data = reinterpret_cast<Data *>(mydata);\n return m(data);\n }\n catch (std::exception &e) {\n std::cerr << \"Caught exception: \" << e.what() << std::endl;\n return VMDPLUGIN_ERROR;\n }\n}\n\nvoid close_rmf_read(void *mydata) {\n Data *data = reinterpret_cast<Data *>(mydata);\n delete data;\n}\n\nvoid *open_rmf_read(const char *filename, const char *, int *natoms) {\n RMF_TRACE(\"open rmf file\");\n try {\n return new Data(filename, natoms);\n }\n catch (std::exception &e) {\n std::cerr << \"Caught exception: \" << e.what() << std::endl;\n *natoms = MOLFILE_NUMATOMS_NONE;\n return NULL;\n }\n}\n\nint read_rmf_structure(void *mydata, int *optflags, molfile_atom_t *atoms) {\n return catch_exceptions(\n \"read rmf structure\", mydata,\n boost::bind(&Data::read_structure, _1, optflags, atoms));\n}\n\nint read_rmf_timestep(void *mydata, int, molfile_timestep_t *frame) {\n return catch_exceptions(\"read rmf timestep\", mydata,\n boost::bind(&Data::read_timestep, _1, frame));\n}\n\nint read_rmf_bonds(void *mydata, int *nbonds, int **fromptr, int **toptr,\n float **bondorderptr, int **bondtype, int *nbondtypes,\n char ***bondtypename) {\n return catch_exceptions(\n \"read rmf bonds\", mydata,\n boost::bind(&Data::read_bonds, _1, nbonds, fromptr, toptr, bondorderptr,\n bondtype, nbondtypes, bondtypename));\n}\n\nint read_rmf_graphics(void *mydata, int *nelem,\n const molfile_graphics_t **gdata) {\n return catch_exceptions(\"read rmf graphics\", mydata,\n boost::bind(&Data::read_graphics, _1, nelem, gdata));\n}\nint read_rmf_timestep_metadata(void *mydata,\n molfile_timestep_metadata_t *tdata) {\n return catch_exceptions(\n \"read rmf timestep metadata\", mydata,\n boost::bind(&Data::read_timestep_metadata, _1, tdata));\n}\n\nvoid init_plugin(molfile_plugin_t &plugin) {\n memset(&plugin, 0, sizeof(molfile_plugin_t));\n plugin.abiversion = vmdplugin_ABIVERSION;\n plugin.type = MOLFILE_PLUGIN_TYPE;\n plugin.name = \"rmf\";\n plugin.prettyname = \"RMF\";\n plugin.author = \"Daniel Russel\";\n plugin.majorv = 0;\n plugin.minorv = 9;\n plugin.is_reentrant = VMDPLUGIN_THREADSAFE;\n plugin.open_file_read = open_rmf_read;\n plugin.read_structure = read_rmf_structure;\n plugin.read_bonds = read_rmf_bonds;\n plugin.read_rawgraphics = read_rmf_graphics;\n plugin.close_file_read = close_rmf_read;\n plugin.read_timestep_metadata = read_rmf_timestep_metadata;\n plugin.read_next_timestep = read_rmf_timestep;\n}\n\nvoid init_plugins() {\n init_plugin(plugin);\n plugin.name = \"rmf\";\n plugin.prettyname = \"RMF\";\n plugin.filename_extension = \"rmf\";\n init_plugin(plugin3);\n plugin3.name = \"rmf3\";\n plugin3.prettyname = \"RMF3\";\n plugin3.filename_extension = \"rmf3\";\n init_plugin(pluginz);\n pluginz.name = \"rmfz\";\n pluginz.prettyname = \"RMFz\";\n pluginz.filename_extension = \"rmfz\";\n}\n}\n\nVMDPLUGIN_API int VMDPLUGIN_init() {\n init_plugins();\n RMF::set_log_level(\"trace\");\n return VMDPLUGIN_SUCCESS;\n}\nVMDPLUGIN_API int VMDPLUGIN_register(void *v, vmdplugin_register_cb cb) {\n std::cout << \"Register\" << std::endl;\n (*cb)(v, (vmdplugin_t *)&plugin);\n (*cb)(v, (vmdplugin_t *)&plugin3);\n (*cb)(v, (vmdplugin_t *)&pluginz);\n return 0;\n}\nVMDPLUGIN_API int VMDPLUGIN_fini() {\n std::cout << \"Fini\" << std::endl;\n return VMDPLUGIN_SUCCESS;\n}\n<|endoftext|>"} {"text":"<commit_before>#ifndef AMGCL_SOLVER_BICGSTABL_HPP\n#define AMGCL_SOLVER_BICGSTABL_HPP\n\n\/*\nThe MIT License\n\nCopyright (c) 2012-2017 Denis Demidov <dennis.demidov@gmail.com>\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n*\/\n\n\/**\n * \\file amgcl\/solver\/bicgstabl.hpp\n * \\author Denis Demidov <dennis.demidov@gmail.com>\n * \\brief BiCGStab(L) iterative method.\n *\/\n\n#include <boost\/tuple\/tuple.hpp>\n#include <boost\/multi_array.hpp>\n\n#include <amgcl\/backend\/interface.hpp>\n#include <amgcl\/solver\/detail\/default_inner_product.hpp>\n#include <amgcl\/util.hpp>\n\nnamespace amgcl {\nnamespace solver {\n\n\/** BiCGStab(L) method.\n * \\rst\n * Generalization of BiCGStab method [SlDi93]_.\n * \\endrst\n *\/\ntemplate <\n class Backend,\n class InnerProduct = detail::default_inner_product\n >\nclass bicgstabl {\n public:\n typedef Backend backend_type;\n\n typedef typename Backend::vector vector;\n typedef typename Backend::value_type value_type;\n typedef typename Backend::params backend_params;\n\n typedef typename math::scalar_of<value_type>::type scalar_type;\n\n typedef typename math::inner_product_impl<\n typename math::rhs_of<value_type>::type\n >::return_type coef_type;\n\n\n \/\/\/ Solver parameters.\n struct params {\n \/\/\/ Order of the method.\n int L;\n\n \/\/\/ Maximum number of iterations.\n size_t maxiter;\n\n \/\/\/ Target relative residual error.\n scalar_type tol;\n\n \/\/\/ Target absolute residual error.\n scalar_type abstol;\n\n params(int L = 2, size_t maxiter = 100, scalar_type tol = 1e-8)\n : L(L), maxiter(maxiter), tol(tol),\n abstol(std::numeric_limits<scalar_type>::min())\n {\n precondition(L > 0, \"L in BiCGStab(L) should be >=1\");\n }\n\n params(const boost::property_tree::ptree &p)\n : AMGCL_PARAMS_IMPORT_VALUE(p, L),\n AMGCL_PARAMS_IMPORT_VALUE(p, maxiter),\n AMGCL_PARAMS_IMPORT_VALUE(p, tol),\n AMGCL_PARAMS_IMPORT_VALUE(p, abstol)\n {\n AMGCL_PARAMS_CHECK(p, (L)(maxiter)(tol)(abstol));\n }\n\n void get(boost::property_tree::ptree &p, const std::string &path) const {\n AMGCL_PARAMS_EXPORT_VALUE(p, path, L);\n AMGCL_PARAMS_EXPORT_VALUE(p, path, maxiter);\n AMGCL_PARAMS_EXPORT_VALUE(p, path, tol);\n AMGCL_PARAMS_EXPORT_VALUE(p, path, abstol);\n }\n };\n\n \/\/\/ Preallocates necessary data structures for the system of size \\p n.\n bicgstabl(\n size_t n,\n const params &prm = params(),\n const backend_params &backend_prm = backend_params(),\n const InnerProduct &inner_product = InnerProduct()\n )\n : prm(prm), n(n),\n r0( Backend::create_vector(n, backend_prm) ),\n q ( Backend::create_vector(n, backend_prm) ),\n r(prm.L + 1), u(prm.L + 1),\n tau(boost::extents[prm.L][prm.L]),\n sigma(prm.L), gamma(prm.L), gamma1(prm.L), gamma2(prm.L),\n inner_product(inner_product)\n {\n for(int i = 0; i <= prm.L; ++i) {\n r[i] = Backend::create_vector(n, backend_prm);\n u[i] = Backend::create_vector(n, backend_prm);\n }\n }\n\n \/* Computes the solution for the given system matrix \\p A and the\n * right-hand side \\p rhs. Returns the number of iterations made and\n * the achieved residual as a ``boost::tuple``. The solution vector\n * \\p x provides initial approximation in input and holds the computed\n * solution on output.\n *\n * The system matrix may differ from the matrix used during\n * initialization. This may be used for the solution of non-stationary\n * problems with slowly changing coefficients. There is a strong chance\n * that a preconditioner built for a time step will act as a reasonably\n * good preconditioner for several subsequent time steps [DeSh12]_.\n *\/\n template <class Matrix, class Precond, class Vec1, class Vec2>\n boost::tuple<size_t, scalar_type> operator()(\n Matrix const &A,\n Precond const &P,\n Vec1 const &rhs,\n#ifdef BOOST_NO_CXX11_RVALUE_REFERENCES\n Vec2 &x\n#else\n Vec2 &&x\n#endif\n ) const\n {\n static const coef_type one = math::identity<coef_type>();\n static const coef_type zero = math::zero<coef_type>();\n\n const int L = prm.L;\n\n backend::residual(rhs, A, x, *r0);\n\n scalar_type norm_rhs = norm(rhs);\n if (norm_rhs < amgcl::detail::eps<scalar_type>(n)) {\n backend::clear(x);\n return boost::make_tuple(0, norm_rhs);\n }\n\n scalar_type res_norm = norm(*r0);\n scalar_type eps = std::max(prm.tol * norm_rhs, prm.abstol);\n\n if(res_norm < eps)\n return boost::make_tuple(0, res_norm \/ norm_rhs);\n\n backend::copy(*r0, *r[0]);\n backend::clear( *u[0] );\n coef_type rho0 = one, alpha = zero, omega = one;\n\n size_t iter = 0;\n\n for(; res_norm > eps && iter < prm.maxiter; iter += prm.L) {\n rho0 = -omega * rho0;\n\n \/\/ Bi-CG part\n for(int j = 0; j < L; ++j) {\n precondition(!math::is_zero(rho0), \"Zero rho in BiCGStab(L)\");\n\n coef_type rho1 = inner_product(*r[j], *r0);\n coef_type beta = alpha * rho1 \/ rho0;\n rho0 = rho1;\n\n for(int i = 0; i <= j; ++i)\n backend::axpby(one, *r[i], -beta, *u[i]);\n\n P.apply(*u[j], *q);\n backend::spmv(one, A, *q, zero, *u[j+1]);\n\n alpha = inner_product(*u[j+1], *r0);\n\n if (math::is_zero(alpha)) break;\n\n alpha = rho0 \/ alpha;\n\n for(int i = 0; i <= j; ++i)\n backend::axpby(-alpha, *u[i+1], one, *r[i]);\n\n backend::axpby(alpha, *u[0], one, x);\n\n res_norm = norm(*r[j]);\n if (res_norm <= eps) goto done;\n\n P.apply(*r[j], *q);\n backend::spmv(one, A, *q, zero, *r[j+1]);\n }\n\n \/\/ MR part\n for(int j = 0; j < L; ++j) {\n for(int i = 0; i < j; ++i) {\n tau[i][j] = inner_product(*r[j+1], *r[i+1]) \/ sigma[i];\n backend::axpby(-tau[i][j], *r[i+1], one, *r[j+1]);\n }\n sigma[j] = inner_product(*r[j+1], *r[j+1]);\n gamma1[j] = inner_product(*r[0], *r[j+1]) \/ sigma[j];\n }\n\n omega = gamma[L-1] = gamma1[L-1];\n for(int j = L-2; j >= 0; --j) {\n gamma[j] = gamma1[j];\n for(int i = j+1; i < L; ++i)\n gamma[j] -= tau[j][i] * gamma[i];\n }\n\n for(int j = 0; j < L-1; ++j) {\n gamma2[j] = gamma[j+1];\n for(int i = j+1; i < L-1; ++i)\n gamma2[j] += tau[j][i] * gamma[i+1];\n }\n\n \/\/ Update\n backend::axpby(gamma[0], *r[0], one, x);\n backend::axpby(-gamma1[L-1], *r[L], one, *r[0]);\n backend::axpby(-gamma[L-1], *u[L], one, *u[0]);\n\n for(int j = 1; j < L; ++j) {\n backend::axpby(-gamma[j-1], *u[j], one, *u[0]);\n backend::axpby(gamma2[j-1], *r[j], one, x);\n backend::axpby(-gamma1[j-1], *r[j], one, *r[0]);\n }\n\n res_norm = norm(*r[0]);\n }\n\ndone:\n P.apply(x, *q);\n backend::copy(*q, x);\n backend::residual(rhs, A, x, *r0);\n res_norm = norm(*r0);\n\n return boost::make_tuple(iter, res_norm \/ norm_rhs);\n }\n\n \/* Computes the solution for the given right-hand side \\p rhs. The\n * system matrix is the same that was used for the setup of the\n * preconditioner \\p P. Returns the number of iterations made and the\n * achieved residual as a ``boost::tuple``. The solution vector \\p x\n * provides initial approximation in input and holds the computed\n * solution on output.\n *\/\n template <class Precond, class Vec1, class Vec2>\n boost::tuple<size_t, scalar_type> operator()(\n Precond const &P,\n Vec1 const &rhs,\n#ifdef BOOST_NO_CXX11_RVALUE_REFERENCES\n Vec2 &x\n#else\n Vec2 &&x\n#endif\n ) const\n {\n return (*this)(P.system_matrix(), P, rhs, x);\n }\n\n\n friend std::ostream& operator<<(std::ostream &os, const bicgstabl &s) {\n return os << \"bicgstab(\" << s.prm.L << \"): \" << s.n << \" unknowns\";\n }\n public:\n params prm;\n\n private:\n size_t n;\n\n mutable boost::shared_ptr< vector > r0;\n mutable boost::shared_ptr< vector > q;\n\n mutable std::vector< boost::shared_ptr< vector > > r;\n mutable std::vector< boost::shared_ptr< vector > > u;\n\n mutable boost::multi_array<coef_type, 2> tau;\n mutable std::vector<coef_type> sigma;\n mutable std::vector<coef_type> gamma, gamma1, gamma2;\n\n InnerProduct inner_product;\n\n template <class Vec>\n scalar_type norm(const Vec &x) const {\n return sqrt(math::norm(inner_product(x, x)));\n }\n};\n\n} \/\/ namespace solver\n} \/\/ namespace amgcl\n\n\n#endif\n<commit_msg>Support non-zero initial condition in BiCGStab(L)<commit_after>#ifndef AMGCL_SOLVER_BICGSTABL_HPP\n#define AMGCL_SOLVER_BICGSTABL_HPP\n\n\/*\nThe MIT License\n\nCopyright (c) 2012-2017 Denis Demidov <dennis.demidov@gmail.com>\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n*\/\n\n\/**\n * \\file amgcl\/solver\/bicgstabl.hpp\n * \\author Denis Demidov <dennis.demidov@gmail.com>\n * \\brief BiCGStab(L) iterative method.\n *\/\n\n#include <boost\/tuple\/tuple.hpp>\n#include <boost\/multi_array.hpp>\n\n#include <amgcl\/backend\/interface.hpp>\n#include <amgcl\/solver\/detail\/default_inner_product.hpp>\n#include <amgcl\/util.hpp>\n\nnamespace amgcl {\nnamespace solver {\n\n\/** BiCGStab(L) method.\n * \\rst\n * Generalization of BiCGStab method [SlDi93]_.\n * \\endrst\n *\/\ntemplate <\n class Backend,\n class InnerProduct = detail::default_inner_product\n >\nclass bicgstabl {\n public:\n typedef Backend backend_type;\n\n typedef typename Backend::vector vector;\n typedef typename Backend::value_type value_type;\n typedef typename Backend::params backend_params;\n\n typedef typename math::scalar_of<value_type>::type scalar_type;\n\n typedef typename math::inner_product_impl<\n typename math::rhs_of<value_type>::type\n >::return_type coef_type;\n\n\n \/\/\/ Solver parameters.\n struct params {\n \/\/\/ Order of the method.\n int L;\n\n \/\/\/ Maximum number of iterations.\n size_t maxiter;\n\n \/\/\/ Target relative residual error.\n scalar_type tol;\n\n \/\/\/ Target absolute residual error.\n scalar_type abstol;\n\n params(int L = 2, size_t maxiter = 100, scalar_type tol = 1e-8)\n : L(L), maxiter(maxiter), tol(tol),\n abstol(std::numeric_limits<scalar_type>::min())\n {\n precondition(L > 0, \"L in BiCGStab(L) should be >=1\");\n }\n\n params(const boost::property_tree::ptree &p)\n : AMGCL_PARAMS_IMPORT_VALUE(p, L),\n AMGCL_PARAMS_IMPORT_VALUE(p, maxiter),\n AMGCL_PARAMS_IMPORT_VALUE(p, tol),\n AMGCL_PARAMS_IMPORT_VALUE(p, abstol)\n {\n AMGCL_PARAMS_CHECK(p, (L)(maxiter)(tol)(abstol));\n }\n\n void get(boost::property_tree::ptree &p, const std::string &path) const {\n AMGCL_PARAMS_EXPORT_VALUE(p, path, L);\n AMGCL_PARAMS_EXPORT_VALUE(p, path, maxiter);\n AMGCL_PARAMS_EXPORT_VALUE(p, path, tol);\n AMGCL_PARAMS_EXPORT_VALUE(p, path, abstol);\n }\n };\n\n \/\/\/ Preallocates necessary data structures for the system of size \\p n.\n bicgstabl(\n size_t n,\n const params &prm = params(),\n const backend_params &backend_prm = backend_params(),\n const InnerProduct &inner_product = InnerProduct()\n )\n : prm(prm), n(n),\n r0( Backend::create_vector(n, backend_prm) ),\n x0( Backend::create_vector(n, backend_prm) ),\n q ( Backend::create_vector(n, backend_prm) ),\n r(prm.L + 1), u(prm.L + 1),\n tau(boost::extents[prm.L][prm.L]),\n sigma(prm.L), gamma(prm.L), gamma1(prm.L), gamma2(prm.L),\n inner_product(inner_product)\n {\n for(int i = 0; i <= prm.L; ++i) {\n r[i] = Backend::create_vector(n, backend_prm);\n u[i] = Backend::create_vector(n, backend_prm);\n }\n }\n\n \/* Computes the solution for the given system matrix \\p A and the\n * right-hand side \\p rhs. Returns the number of iterations made and\n * the achieved residual as a ``boost::tuple``. The solution vector\n * \\p x provides initial approximation in input and holds the computed\n * solution on output.\n *\n * The system matrix may differ from the matrix used during\n * initialization. This may be used for the solution of non-stationary\n * problems with slowly changing coefficients. There is a strong chance\n * that a preconditioner built for a time step will act as a reasonably\n * good preconditioner for several subsequent time steps [DeSh12]_.\n *\/\n template <class Matrix, class Precond, class Vec1, class Vec2>\n boost::tuple<size_t, scalar_type> operator()(\n Matrix const &A,\n Precond const &P,\n Vec1 const &rhs,\n#ifdef BOOST_NO_CXX11_RVALUE_REFERENCES\n Vec2 &x\n#else\n Vec2 &&x\n#endif\n ) const\n {\n static const coef_type one = math::identity<coef_type>();\n static const coef_type zero = math::zero<coef_type>();\n\n const int L = prm.L;\n\n scalar_type norm_rhs = norm(rhs);\n if (norm_rhs < amgcl::detail::eps<scalar_type>(n)) {\n backend::clear(x);\n return boost::make_tuple(0, norm_rhs);\n }\n\n backend::residual(rhs, A, x, *r0);\n\n scalar_type res_norm = norm(*r0);\n scalar_type eps = std::max(prm.tol * norm_rhs, prm.abstol);\n\n if(res_norm < eps)\n return boost::make_tuple(0, res_norm \/ norm_rhs);\n\n backend::copy(*r0, *r[0]);\n backend::clear(*u[0]);\n backend::clear(*x0);\n coef_type rho0 = one, alpha = zero, omega = one;\n\n size_t iter = 0;\n\n for(; res_norm > eps && iter < prm.maxiter; iter += prm.L) {\n rho0 = -omega * rho0;\n\n \/\/ Bi-CG part\n for(int j = 0; j < L; ++j) {\n precondition(!math::is_zero(rho0), \"Zero rho in BiCGStab(L)\");\n\n coef_type rho1 = inner_product(*r[j], *r0);\n coef_type beta = alpha * rho1 \/ rho0;\n rho0 = rho1;\n\n for(int i = 0; i <= j; ++i)\n backend::axpby(one, *r[i], -beta, *u[i]);\n\n P.apply(*u[j], *q);\n backend::spmv(one, A, *q, zero, *u[j+1]);\n\n alpha = inner_product(*u[j+1], *r0);\n\n if (math::is_zero(alpha)) break;\n\n alpha = rho0 \/ alpha;\n\n for(int i = 0; i <= j; ++i)\n backend::axpby(-alpha, *u[i+1], one, *r[i]);\n\n backend::axpby(alpha, *u[0], one, *x0);\n\n res_norm = norm(*r[j]);\n if (res_norm <= eps) goto done;\n\n P.apply(*r[j], *q);\n backend::spmv(one, A, *q, zero, *r[j+1]);\n }\n\n \/\/ MR part\n for(int j = 0; j < L; ++j) {\n for(int i = 0; i < j; ++i) {\n tau[i][j] = inner_product(*r[j+1], *r[i+1]) \/ sigma[i];\n backend::axpby(-tau[i][j], *r[i+1], one, *r[j+1]);\n }\n sigma[j] = inner_product(*r[j+1], *r[j+1]);\n gamma1[j] = inner_product(*r[0], *r[j+1]) \/ sigma[j];\n }\n\n omega = gamma[L-1] = gamma1[L-1];\n for(int j = L-2; j >= 0; --j) {\n gamma[j] = gamma1[j];\n for(int i = j+1; i < L; ++i)\n gamma[j] -= tau[j][i] * gamma[i];\n }\n\n for(int j = 0; j < L-1; ++j) {\n gamma2[j] = gamma[j+1];\n for(int i = j+1; i < L-1; ++i)\n gamma2[j] += tau[j][i] * gamma[i+1];\n }\n\n \/\/ Update\n backend::axpby(gamma[0], *r[0], one, *x0);\n backend::axpby(-gamma1[L-1], *r[L], one, *r[0]);\n backend::axpby(-gamma[L-1], *u[L], one, *u[0]);\n\n for(int j = 1; j < L; ++j) {\n backend::axpby(-gamma[j-1], *u[j], one, *u[0]);\n backend::axpby(gamma2[j-1], *r[j], one, *x0);\n backend::axpby(-gamma1[j-1], *r[j], one, *r[0]);\n }\n\n res_norm = norm(*r[0]);\n }\n\ndone:\n P.apply(*x0, *q);\n backend::axpby(one, *q, one, x);\n backend::residual(rhs, A, x, *r0);\n res_norm = norm(*r0);\n\n return boost::make_tuple(iter, res_norm \/ norm_rhs);\n }\n\n \/* Computes the solution for the given right-hand side \\p rhs. The\n * system matrix is the same that was used for the setup of the\n * preconditioner \\p P. Returns the number of iterations made and the\n * achieved residual as a ``boost::tuple``. The solution vector \\p x\n * provides initial approximation in input and holds the computed\n * solution on output.\n *\/\n template <class Precond, class Vec1, class Vec2>\n boost::tuple<size_t, scalar_type> operator()(\n Precond const &P,\n Vec1 const &rhs,\n#ifdef BOOST_NO_CXX11_RVALUE_REFERENCES\n Vec2 &x\n#else\n Vec2 &&x\n#endif\n ) const\n {\n return (*this)(P.system_matrix(), P, rhs, x);\n }\n\n\n friend std::ostream& operator<<(std::ostream &os, const bicgstabl &s) {\n return os << \"bicgstab(\" << s.prm.L << \"): \" << s.n << \" unknowns\";\n }\n public:\n params prm;\n\n private:\n size_t n;\n\n mutable boost::shared_ptr< vector > r0;\n mutable boost::shared_ptr< vector > x0;\n mutable boost::shared_ptr< vector > q;\n\n mutable std::vector< boost::shared_ptr< vector > > r;\n mutable std::vector< boost::shared_ptr< vector > > u;\n\n mutable boost::multi_array<coef_type, 2> tau;\n mutable std::vector<coef_type> sigma;\n mutable std::vector<coef_type> gamma, gamma1, gamma2;\n\n InnerProduct inner_product;\n\n template <class Vec>\n scalar_type norm(const Vec &x) const {\n return sqrt(math::norm(inner_product(x, x)));\n }\n};\n\n} \/\/ namespace solver\n} \/\/ namespace amgcl\n\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2015 GitHub, Inc.\n\/\/ Use of this source code is governed by the MIT license that can be\n\/\/ found in the LICENSE file.\n\n#include \"atom\/common\/native_mate_converters\/content_converter.h\"\n\n#include <string>\n#include <vector>\n\n#include \"atom\/browser\/api\/atom_api_web_contents.h\"\n#include \"atom\/browser\/web_contents_permission_helper.h\"\n#include \"atom\/common\/native_mate_converters\/blink_converter.h\"\n#include \"atom\/common\/native_mate_converters\/callback.h\"\n#include \"atom\/common\/native_mate_converters\/gurl_converter.h\"\n#include \"atom\/common\/native_mate_converters\/string16_converter.h\"\n#include \"atom\/common\/native_mate_converters\/ui_base_types_converter.h\"\n#include \"brave\/browser\/api\/navigation_controller.h\"\n#include \"brave\/browser\/api\/navigation_handle.h\"\n#include \"content\/public\/browser\/navigation_controller.h\"\n#include \"content\/public\/browser\/navigation_entry.h\"\n#include \"content\/public\/browser\/navigation_handle.h\"\n#include \"content\/public\/browser\/web_contents.h\"\n#include \"content\/public\/common\/context_menu_params.h\"\n#include \"native_mate\/dictionary.h\"\n\nnamespace {\n\nvoid ExecuteCommand(content::WebContents* web_contents,\n int action,\n const content::CustomContextMenuContext& context) {\n web_contents->ExecuteCustomContextMenuCommand(action, context);\n}\n\n\/\/ Forward declaration for nested recursive call.\nv8::Local<v8::Value> MenuToV8(v8::Isolate* isolate,\n content::WebContents* web_contents,\n const content::CustomContextMenuContext& context,\n const std::vector<content::MenuItem>& menu);\n\nv8::Local<v8::Value> MenuItemToV8(\n v8::Isolate* isolate,\n content::WebContents* web_contents,\n const content::CustomContextMenuContext& context,\n const content::MenuItem& item) {\n mate::Dictionary v8_item = mate::Dictionary::CreateEmpty(isolate);\n switch (item.type) {\n case content::MenuItem::CHECKABLE_OPTION:\n case content::MenuItem::GROUP:\n v8_item.Set(\"checked\", item.checked);\n case content::MenuItem::OPTION:\n case content::MenuItem::SUBMENU:\n v8_item.Set(\"label\", item.label);\n v8_item.Set(\"enabled\", item.enabled);\n default:\n v8_item.Set(\"type\", item.type);\n }\n if (item.type == content::MenuItem::SUBMENU)\n v8_item.Set(\"submenu\",\n MenuToV8(isolate, web_contents, context, item.submenu));\n else if (item.action > 0)\n v8_item.Set(\"click\",\n base::Bind(ExecuteCommand, web_contents, item.action, context));\n return v8_item.GetHandle();\n}\n\nv8::Local<v8::Value> MenuToV8(v8::Isolate* isolate,\n content::WebContents* web_contents,\n const content::CustomContextMenuContext& context,\n const std::vector<content::MenuItem>& menu) {\n std::vector<v8::Local<v8::Value>> v8_menu;\n for (const auto& menu_item : menu)\n v8_menu.push_back(MenuItemToV8(isolate, web_contents, context, menu_item));\n return mate::ConvertToV8(isolate, v8_menu);\n}\n\n} \/\/ namespace\n\nnamespace mate {\n\n\/\/ static\nv8::Local<v8::Value> Converter<content::MenuItem::Type>::ToV8(\n v8::Isolate* isolate, const content::MenuItem::Type& val) {\n switch (val) {\n case content::MenuItem::CHECKABLE_OPTION:\n return StringToV8(isolate, \"checkbox\");\n case content::MenuItem::GROUP:\n return StringToV8(isolate, \"radio\");\n case content::MenuItem::SEPARATOR:\n return StringToV8(isolate, \"separator\");\n case content::MenuItem::SUBMENU:\n return StringToV8(isolate, \"submenu\");\n case content::MenuItem::OPTION:\n default:\n return StringToV8(isolate, \"normal\");\n }\n}\n\n\/\/ static\nv8::Local<v8::Value> Converter<ContextMenuParamsWithWebContents>::ToV8(\n v8::Isolate* isolate, const ContextMenuParamsWithWebContents& val) {\n const auto& params = val.first;\n mate::Dictionary dict = mate::Dictionary::CreateEmpty(isolate);\n dict.Set(\"x\", params.x);\n dict.Set(\"y\", params.y);\n dict.Set(\"linkURL\", params.link_url);\n dict.Set(\"linkText\", params.link_text);\n dict.Set(\"pageURL\", params.page_url);\n dict.Set(\"frameURL\", params.frame_url);\n dict.Set(\"srcURL\", params.src_url);\n dict.Set(\"mediaType\", params.media_type);\n dict.Set(\"mediaFlags\", MediaFlagsToV8(isolate, params.media_flags));\n bool has_image_contents =\n (params.media_type == blink::WebContextMenuData::kMediaTypeImage) &&\n params.has_image_contents;\n dict.Set(\"hasImageContents\", has_image_contents);\n dict.Set(\"isEditable\", params.is_editable);\n dict.Set(\"editFlags\", EditFlagsToV8(isolate, params.edit_flags));\n dict.Set(\"selectionText\", params.selection_text);\n dict.Set(\"titleText\", params.title_text);\n dict.Set(\"misspelledWord\", params.misspelled_word);\n dict.Set(\"dictionarySuggestions\", params.dictionary_suggestions);\n dict.Set(\"frameCharset\", params.frame_charset);\n dict.Set(\"inputFieldType\", params.input_field_type);\n dict.Set(\"menuSourceType\", params.source_type);\n dict.Set(\"properties\", params.properties);\n\n if (params.custom_context.request_id || params.custom_context.is_pepper_menu)\n dict.Set(\"menu\", MenuToV8(isolate, val.second, params.custom_context,\n params.custom_items));\n return mate::ConvertToV8(isolate, dict);\n}\n\n\/\/ static\nbool Converter<blink::mojom::PermissionStatus>::FromV8(\n v8::Isolate* isolate,\n v8::Local<v8::Value> val,\n blink::mojom::PermissionStatus* out) {\n bool result;\n if (!ConvertFromV8(isolate, val, &result))\n return false;\n\n if (result)\n *out = blink::mojom::PermissionStatus::GRANTED;\n else\n *out = blink::mojom::PermissionStatus::DENIED;\n\n return true;\n}\n\n\/\/ static\nv8::Local<v8::Value> Converter<content::PermissionType>::ToV8(\n v8::Isolate* isolate, const content::PermissionType& val) {\n using PermissionType = atom::WebContentsPermissionHelper::PermissionType;\n switch (val) {\n case content::PermissionType::MIDI_SYSEX:\n return StringToV8(isolate, \"midiSysex\");\n case content::PermissionType::PUSH_MESSAGING:\n return StringToV8(isolate, \"pushMessaging\");\n case content::PermissionType::NOTIFICATIONS:\n return StringToV8(isolate, \"notifications\");\n case content::PermissionType::GEOLOCATION:\n return StringToV8(isolate, \"geolocation\");\n case content::PermissionType::AUDIO_CAPTURE:\n case content::PermissionType::VIDEO_CAPTURE:\n return StringToV8(isolate, \"media\");\n case content::PermissionType::PROTECTED_MEDIA_IDENTIFIER:\n return StringToV8(isolate, \"mediaKeySystem\");\n case content::PermissionType::MIDI:\n return StringToV8(isolate, \"midi\");\n default:\n break;\n }\n\n if (val == (content::PermissionType)(PermissionType::POINTER_LOCK))\n return StringToV8(isolate, \"pointerLock\");\n else if (val == (content::PermissionType)(PermissionType::FULLSCREEN))\n return StringToV8(isolate, \"fullscreen\");\n else if (val == (content::PermissionType)(PermissionType::OPEN_EXTERNAL))\n return StringToV8(isolate, \"openExternal\");\n else if (val == (content::PermissionType)\n (PermissionType::PROTOCOL_REGISTRATION))\n return StringToV8(isolate, \"protocolRegistration\");\n\n return StringToV8(isolate, \"unknown\");\n}\n\n\/\/ static\nbool Converter<content::StopFindAction>::FromV8(\n v8::Isolate* isolate,\n v8::Local<v8::Value> val,\n content::StopFindAction* out) {\n std::string action;\n if (!ConvertFromV8(isolate, val, &action))\n return false;\n\n if (action == \"clearSelection\")\n *out = content::STOP_FIND_ACTION_CLEAR_SELECTION;\n else if (action == \"keepSelection\")\n *out = content::STOP_FIND_ACTION_KEEP_SELECTION;\n else if (action == \"activateSelection\")\n *out = content::STOP_FIND_ACTION_ACTIVATE_SELECTION;\n else\n return false;\n\n return true;\n}\n\n\/\/ static\nv8::Local<v8::Value> Converter<content::WebContents*>::ToV8(\n v8::Isolate* isolate, content::WebContents* val) {\n if (!val)\n return v8::Null(isolate);\n return atom::api::WebContents::CreateFrom(isolate, val).ToV8();\n}\n\n\/\/ static\nbool Converter<content::WebContents*>::FromV8(\n v8::Isolate* isolate,\n v8::Local<v8::Value> val,\n content::WebContents** out) {\n atom::api::WebContents* web_contents = nullptr;\n if (!ConvertFromV8(isolate, val, &web_contents) || !web_contents)\n return false;\n\n *out = web_contents->web_contents();\n return true;\n}\n\n\/\/ static\nv8::Local<v8::Value> Converter<content::NavigationHandle*>::ToV8(\n v8::Isolate* isolate, content::NavigationHandle* val) {\n if (!val)\n return v8::Null(isolate);\n return brave::NavigationHandle::CreateFrom(isolate, val).ToV8();\n}\n\n\/\/ static\nv8::Local<v8::Value> Converter<content::NavigationEntry*>::ToV8(\n v8::Isolate* isolate, content::NavigationEntry* val) {\n if (!val)\n return v8::Null(isolate);\n\n mate::Dictionary dict = mate::Dictionary::CreateEmpty(isolate);\n dict.Set(\"uniqueId\", val->GetUniqueID());\n dict.Set(\"pageType\", val->GetPageType());\n dict.Set(\"url\", val->GetURL());\n dict.Set(\"referrer\", val->GetReferrer().url);\n dict.Set(\"virtualURL\", val->GetVirtualURL());\n dict.Set(\"title\", val->GetTitle());\n dict.Set(\"displayTitle\", val->GetTitleForDisplay());\n dict.Set(\"viewSourceMode\", val->IsViewSourceMode());\n dict.Set(\"transitionType\", val->GetTransitionType());\n dict.Set(\"hasPostData\", val->GetHasPostData());\n \/\/ GetFavicon\n \/\/ GetSSL\n dict.Set(\"originalRequestURL\", val->GetOriginalRequestURL());\n dict.Set(\"isOverridingUserAgent\", val->GetIsOverridingUserAgent());\n dict.Set(\"timestamp\", val->GetTimestamp().ToDoubleT());\n dict.Set(\"httpStatusCode\", val->GetHttpStatusCode());\n dict.Set(\"isRestored\", val->IsRestored());\n dict.Set(\"extraHeaders\", val->GetExtraHeaders());\n\n return mate::ConvertToV8(isolate, dict);\n}\n\n\/\/ static\nv8::Local<v8::Value> Converter<content::NavigationController*>::ToV8(\n v8::Isolate* isolate, content::NavigationController* val) {\n if (!val)\n return v8::Null(isolate);\n return brave::NavigationController::CreateFrom(isolate, val).ToV8();\n}\n\n\/\/ static\nv8::Local<v8::Value> Converter<content::ReloadType>::ToV8(\n v8::Isolate* isolate, const content::ReloadType& val) {\n switch (val) {\n case content::ReloadType::NONE:\n return StringToV8(isolate, \"none\");\n case content::ReloadType::NORMAL:\n return StringToV8(isolate, \"normal\");\n case content::ReloadType::BYPASSING_CACHE:\n return StringToV8(isolate, \"bypassingCache\");\n case content::ReloadType::ORIGINAL_REQUEST_URL:\n return StringToV8(isolate, \"originalRequestUrl\");\n case content::ReloadType::DISABLE_LOFI_MODE:\n return StringToV8(isolate, \"disableLofiMode\");\n default:\n break;\n }\n\n return StringToV8(isolate, \"unknown\");\n}\n\n\/\/ static\nv8::Local<v8::Value> Converter<content::PageType>::ToV8(\n v8::Isolate* isolate, const content::PageType& val) {\n switch (val) {\n case content::PageType::PAGE_TYPE_NORMAL:\n return StringToV8(isolate, \"normal\");\n case content::PageType::PAGE_TYPE_ERROR:\n return StringToV8(isolate, \"error\");\n case content::PageType::PAGE_TYPE_INTERSTITIAL:\n return StringToV8(isolate, \"interstitial\");\n default:\n return StringToV8(isolate, \"unknown\");\n }\n}\n\n\/\/ static\nv8::Local<v8::Value> Converter<content::RestoreType>::ToV8(\n v8::Isolate* isolate, const content::RestoreType& val) {\n switch (val) {\n case content::RestoreType::LAST_SESSION_EXITED_CLEANLY:\n return StringToV8(isolate, \"lastSessionExitedCleanly\");\n case content::RestoreType::LAST_SESSION_CRASHED:\n return StringToV8(isolate, \"lastSessionCrashed\");\n case content::RestoreType::CURRENT_SESSION:\n return StringToV8(isolate, \"currentSession\");\n default:\n return StringToV8(isolate, \"none\");\n }\n}\n\n\/\/ static\nv8::Local<v8::Value> Converter<ui::PageTransition>::ToV8(\n v8::Isolate* isolate, const ui::PageTransition& val) {\n if (ui::PageTransitionCoreTypeIs(val,\n ui::PageTransition::PAGE_TRANSITION_LINK))\n return StringToV8(isolate, \"link\");\n if (ui::PageTransitionCoreTypeIs(val,\n ui::PageTransition::PAGE_TRANSITION_TYPED))\n return StringToV8(isolate, \"typed\");\n if (ui::PageTransitionCoreTypeIs(val,\n ui::PageTransition::PAGE_TRANSITION_AUTO_BOOKMARK))\n return StringToV8(isolate, \"autoBookmark\");\n if (ui::PageTransitionCoreTypeIs(val,\n ui::PageTransition::PAGE_TRANSITION_AUTO_SUBFRAME))\n return StringToV8(isolate, \"autoSubframe\");\n if (ui::PageTransitionCoreTypeIs(val,\n ui::PageTransition::PAGE_TRANSITION_MANUAL_SUBFRAME))\n return StringToV8(isolate, \"manualSubframe\");\n if (ui::PageTransitionCoreTypeIs(val,\n ui::PageTransition::PAGE_TRANSITION_GENERATED))\n return StringToV8(isolate, \"generated\");\n if (ui::PageTransitionCoreTypeIs(val,\n ui::PageTransition::PAGE_TRANSITION_AUTO_TOPLEVEL))\n return StringToV8(isolate, \"autoToplevel\");\n if (ui::PageTransitionCoreTypeIs(val,\n ui::PageTransition::PAGE_TRANSITION_FORM_SUBMIT))\n return StringToV8(isolate, \"formSubmit\");\n if (ui::PageTransitionCoreTypeIs(val,\n ui::PageTransition::PAGE_TRANSITION_RELOAD))\n return StringToV8(isolate, \"reload\");\n if (ui::PageTransitionCoreTypeIs(val,\n ui::PageTransition::PAGE_TRANSITION_KEYWORD))\n return StringToV8(isolate, \"keyword\");\n if (ui::PageTransitionCoreTypeIs(val,\n ui::PageTransition::PAGE_TRANSITION_KEYWORD_GENERATED))\n return StringToV8(isolate, \"keywordGenerated\");\n\n return StringToV8(isolate, \"unknown\");\n}\n\n} \/\/ namespace mate\n<commit_msg>content::ReloadType::DISABLE_LOFI_MODE was renamed to DISABLE_PREVIEWS<commit_after>\/\/ Copyright (c) 2015 GitHub, Inc.\n\/\/ Use of this source code is governed by the MIT license that can be\n\/\/ found in the LICENSE file.\n\n#include \"atom\/common\/native_mate_converters\/content_converter.h\"\n\n#include <string>\n#include <vector>\n\n#include \"atom\/browser\/api\/atom_api_web_contents.h\"\n#include \"atom\/browser\/web_contents_permission_helper.h\"\n#include \"atom\/common\/native_mate_converters\/blink_converter.h\"\n#include \"atom\/common\/native_mate_converters\/callback.h\"\n#include \"atom\/common\/native_mate_converters\/gurl_converter.h\"\n#include \"atom\/common\/native_mate_converters\/string16_converter.h\"\n#include \"atom\/common\/native_mate_converters\/ui_base_types_converter.h\"\n#include \"brave\/browser\/api\/navigation_controller.h\"\n#include \"brave\/browser\/api\/navigation_handle.h\"\n#include \"content\/public\/browser\/navigation_controller.h\"\n#include \"content\/public\/browser\/navigation_entry.h\"\n#include \"content\/public\/browser\/navigation_handle.h\"\n#include \"content\/public\/browser\/web_contents.h\"\n#include \"content\/public\/common\/context_menu_params.h\"\n#include \"native_mate\/dictionary.h\"\n\nnamespace {\n\nvoid ExecuteCommand(content::WebContents* web_contents,\n int action,\n const content::CustomContextMenuContext& context) {\n web_contents->ExecuteCustomContextMenuCommand(action, context);\n}\n\n\/\/ Forward declaration for nested recursive call.\nv8::Local<v8::Value> MenuToV8(v8::Isolate* isolate,\n content::WebContents* web_contents,\n const content::CustomContextMenuContext& context,\n const std::vector<content::MenuItem>& menu);\n\nv8::Local<v8::Value> MenuItemToV8(\n v8::Isolate* isolate,\n content::WebContents* web_contents,\n const content::CustomContextMenuContext& context,\n const content::MenuItem& item) {\n mate::Dictionary v8_item = mate::Dictionary::CreateEmpty(isolate);\n switch (item.type) {\n case content::MenuItem::CHECKABLE_OPTION:\n case content::MenuItem::GROUP:\n v8_item.Set(\"checked\", item.checked);\n case content::MenuItem::OPTION:\n case content::MenuItem::SUBMENU:\n v8_item.Set(\"label\", item.label);\n v8_item.Set(\"enabled\", item.enabled);\n default:\n v8_item.Set(\"type\", item.type);\n }\n if (item.type == content::MenuItem::SUBMENU)\n v8_item.Set(\"submenu\",\n MenuToV8(isolate, web_contents, context, item.submenu));\n else if (item.action > 0)\n v8_item.Set(\"click\",\n base::Bind(ExecuteCommand, web_contents, item.action, context));\n return v8_item.GetHandle();\n}\n\nv8::Local<v8::Value> MenuToV8(v8::Isolate* isolate,\n content::WebContents* web_contents,\n const content::CustomContextMenuContext& context,\n const std::vector<content::MenuItem>& menu) {\n std::vector<v8::Local<v8::Value>> v8_menu;\n for (const auto& menu_item : menu)\n v8_menu.push_back(MenuItemToV8(isolate, web_contents, context, menu_item));\n return mate::ConvertToV8(isolate, v8_menu);\n}\n\n} \/\/ namespace\n\nnamespace mate {\n\n\/\/ static\nv8::Local<v8::Value> Converter<content::MenuItem::Type>::ToV8(\n v8::Isolate* isolate, const content::MenuItem::Type& val) {\n switch (val) {\n case content::MenuItem::CHECKABLE_OPTION:\n return StringToV8(isolate, \"checkbox\");\n case content::MenuItem::GROUP:\n return StringToV8(isolate, \"radio\");\n case content::MenuItem::SEPARATOR:\n return StringToV8(isolate, \"separator\");\n case content::MenuItem::SUBMENU:\n return StringToV8(isolate, \"submenu\");\n case content::MenuItem::OPTION:\n default:\n return StringToV8(isolate, \"normal\");\n }\n}\n\n\/\/ static\nv8::Local<v8::Value> Converter<ContextMenuParamsWithWebContents>::ToV8(\n v8::Isolate* isolate, const ContextMenuParamsWithWebContents& val) {\n const auto& params = val.first;\n mate::Dictionary dict = mate::Dictionary::CreateEmpty(isolate);\n dict.Set(\"x\", params.x);\n dict.Set(\"y\", params.y);\n dict.Set(\"linkURL\", params.link_url);\n dict.Set(\"linkText\", params.link_text);\n dict.Set(\"pageURL\", params.page_url);\n dict.Set(\"frameURL\", params.frame_url);\n dict.Set(\"srcURL\", params.src_url);\n dict.Set(\"mediaType\", params.media_type);\n dict.Set(\"mediaFlags\", MediaFlagsToV8(isolate, params.media_flags));\n bool has_image_contents =\n (params.media_type == blink::WebContextMenuData::kMediaTypeImage) &&\n params.has_image_contents;\n dict.Set(\"hasImageContents\", has_image_contents);\n dict.Set(\"isEditable\", params.is_editable);\n dict.Set(\"editFlags\", EditFlagsToV8(isolate, params.edit_flags));\n dict.Set(\"selectionText\", params.selection_text);\n dict.Set(\"titleText\", params.title_text);\n dict.Set(\"misspelledWord\", params.misspelled_word);\n dict.Set(\"dictionarySuggestions\", params.dictionary_suggestions);\n dict.Set(\"frameCharset\", params.frame_charset);\n dict.Set(\"inputFieldType\", params.input_field_type);\n dict.Set(\"menuSourceType\", params.source_type);\n dict.Set(\"properties\", params.properties);\n\n if (params.custom_context.request_id || params.custom_context.is_pepper_menu)\n dict.Set(\"menu\", MenuToV8(isolate, val.second, params.custom_context,\n params.custom_items));\n return mate::ConvertToV8(isolate, dict);\n}\n\n\/\/ static\nbool Converter<blink::mojom::PermissionStatus>::FromV8(\n v8::Isolate* isolate,\n v8::Local<v8::Value> val,\n blink::mojom::PermissionStatus* out) {\n bool result;\n if (!ConvertFromV8(isolate, val, &result))\n return false;\n\n if (result)\n *out = blink::mojom::PermissionStatus::GRANTED;\n else\n *out = blink::mojom::PermissionStatus::DENIED;\n\n return true;\n}\n\n\/\/ static\nv8::Local<v8::Value> Converter<content::PermissionType>::ToV8(\n v8::Isolate* isolate, const content::PermissionType& val) {\n using PermissionType = atom::WebContentsPermissionHelper::PermissionType;\n switch (val) {\n case content::PermissionType::MIDI_SYSEX:\n return StringToV8(isolate, \"midiSysex\");\n case content::PermissionType::PUSH_MESSAGING:\n return StringToV8(isolate, \"pushMessaging\");\n case content::PermissionType::NOTIFICATIONS:\n return StringToV8(isolate, \"notifications\");\n case content::PermissionType::GEOLOCATION:\n return StringToV8(isolate, \"geolocation\");\n case content::PermissionType::AUDIO_CAPTURE:\n case content::PermissionType::VIDEO_CAPTURE:\n return StringToV8(isolate, \"media\");\n case content::PermissionType::PROTECTED_MEDIA_IDENTIFIER:\n return StringToV8(isolate, \"mediaKeySystem\");\n case content::PermissionType::MIDI:\n return StringToV8(isolate, \"midi\");\n default:\n break;\n }\n\n if (val == (content::PermissionType)(PermissionType::POINTER_LOCK))\n return StringToV8(isolate, \"pointerLock\");\n else if (val == (content::PermissionType)(PermissionType::FULLSCREEN))\n return StringToV8(isolate, \"fullscreen\");\n else if (val == (content::PermissionType)(PermissionType::OPEN_EXTERNAL))\n return StringToV8(isolate, \"openExternal\");\n else if (val == (content::PermissionType)\n (PermissionType::PROTOCOL_REGISTRATION))\n return StringToV8(isolate, \"protocolRegistration\");\n\n return StringToV8(isolate, \"unknown\");\n}\n\n\/\/ static\nbool Converter<content::StopFindAction>::FromV8(\n v8::Isolate* isolate,\n v8::Local<v8::Value> val,\n content::StopFindAction* out) {\n std::string action;\n if (!ConvertFromV8(isolate, val, &action))\n return false;\n\n if (action == \"clearSelection\")\n *out = content::STOP_FIND_ACTION_CLEAR_SELECTION;\n else if (action == \"keepSelection\")\n *out = content::STOP_FIND_ACTION_KEEP_SELECTION;\n else if (action == \"activateSelection\")\n *out = content::STOP_FIND_ACTION_ACTIVATE_SELECTION;\n else\n return false;\n\n return true;\n}\n\n\/\/ static\nv8::Local<v8::Value> Converter<content::WebContents*>::ToV8(\n v8::Isolate* isolate, content::WebContents* val) {\n if (!val)\n return v8::Null(isolate);\n return atom::api::WebContents::CreateFrom(isolate, val).ToV8();\n}\n\n\/\/ static\nbool Converter<content::WebContents*>::FromV8(\n v8::Isolate* isolate,\n v8::Local<v8::Value> val,\n content::WebContents** out) {\n atom::api::WebContents* web_contents = nullptr;\n if (!ConvertFromV8(isolate, val, &web_contents) || !web_contents)\n return false;\n\n *out = web_contents->web_contents();\n return true;\n}\n\n\/\/ static\nv8::Local<v8::Value> Converter<content::NavigationHandle*>::ToV8(\n v8::Isolate* isolate, content::NavigationHandle* val) {\n if (!val)\n return v8::Null(isolate);\n return brave::NavigationHandle::CreateFrom(isolate, val).ToV8();\n}\n\n\/\/ static\nv8::Local<v8::Value> Converter<content::NavigationEntry*>::ToV8(\n v8::Isolate* isolate, content::NavigationEntry* val) {\n if (!val)\n return v8::Null(isolate);\n\n mate::Dictionary dict = mate::Dictionary::CreateEmpty(isolate);\n dict.Set(\"uniqueId\", val->GetUniqueID());\n dict.Set(\"pageType\", val->GetPageType());\n dict.Set(\"url\", val->GetURL());\n dict.Set(\"referrer\", val->GetReferrer().url);\n dict.Set(\"virtualURL\", val->GetVirtualURL());\n dict.Set(\"title\", val->GetTitle());\n dict.Set(\"displayTitle\", val->GetTitleForDisplay());\n dict.Set(\"viewSourceMode\", val->IsViewSourceMode());\n dict.Set(\"transitionType\", val->GetTransitionType());\n dict.Set(\"hasPostData\", val->GetHasPostData());\n \/\/ GetFavicon\n \/\/ GetSSL\n dict.Set(\"originalRequestURL\", val->GetOriginalRequestURL());\n dict.Set(\"isOverridingUserAgent\", val->GetIsOverridingUserAgent());\n dict.Set(\"timestamp\", val->GetTimestamp().ToDoubleT());\n dict.Set(\"httpStatusCode\", val->GetHttpStatusCode());\n dict.Set(\"isRestored\", val->IsRestored());\n dict.Set(\"extraHeaders\", val->GetExtraHeaders());\n\n return mate::ConvertToV8(isolate, dict);\n}\n\n\/\/ static\nv8::Local<v8::Value> Converter<content::NavigationController*>::ToV8(\n v8::Isolate* isolate, content::NavigationController* val) {\n if (!val)\n return v8::Null(isolate);\n return brave::NavigationController::CreateFrom(isolate, val).ToV8();\n}\n\n\/\/ static\nv8::Local<v8::Value> Converter<content::ReloadType>::ToV8(\n v8::Isolate* isolate, const content::ReloadType& val) {\n switch (val) {\n case content::ReloadType::NONE:\n return StringToV8(isolate, \"none\");\n case content::ReloadType::NORMAL:\n return StringToV8(isolate, \"normal\");\n case content::ReloadType::BYPASSING_CACHE:\n return StringToV8(isolate, \"bypassingCache\");\n case content::ReloadType::ORIGINAL_REQUEST_URL:\n return StringToV8(isolate, \"originalRequestUrl\");\n case content::ReloadType::DISABLE_PREVIEWS:\n return StringToV8(isolate, \"disableLofiMode\");\n default:\n break;\n }\n\n return StringToV8(isolate, \"unknown\");\n}\n\n\/\/ static\nv8::Local<v8::Value> Converter<content::PageType>::ToV8(\n v8::Isolate* isolate, const content::PageType& val) {\n switch (val) {\n case content::PageType::PAGE_TYPE_NORMAL:\n return StringToV8(isolate, \"normal\");\n case content::PageType::PAGE_TYPE_ERROR:\n return StringToV8(isolate, \"error\");\n case content::PageType::PAGE_TYPE_INTERSTITIAL:\n return StringToV8(isolate, \"interstitial\");\n default:\n return StringToV8(isolate, \"unknown\");\n }\n}\n\n\/\/ static\nv8::Local<v8::Value> Converter<content::RestoreType>::ToV8(\n v8::Isolate* isolate, const content::RestoreType& val) {\n switch (val) {\n case content::RestoreType::LAST_SESSION_EXITED_CLEANLY:\n return StringToV8(isolate, \"lastSessionExitedCleanly\");\n case content::RestoreType::LAST_SESSION_CRASHED:\n return StringToV8(isolate, \"lastSessionCrashed\");\n case content::RestoreType::CURRENT_SESSION:\n return StringToV8(isolate, \"currentSession\");\n default:\n return StringToV8(isolate, \"none\");\n }\n}\n\n\/\/ static\nv8::Local<v8::Value> Converter<ui::PageTransition>::ToV8(\n v8::Isolate* isolate, const ui::PageTransition& val) {\n if (ui::PageTransitionCoreTypeIs(val,\n ui::PageTransition::PAGE_TRANSITION_LINK))\n return StringToV8(isolate, \"link\");\n if (ui::PageTransitionCoreTypeIs(val,\n ui::PageTransition::PAGE_TRANSITION_TYPED))\n return StringToV8(isolate, \"typed\");\n if (ui::PageTransitionCoreTypeIs(val,\n ui::PageTransition::PAGE_TRANSITION_AUTO_BOOKMARK))\n return StringToV8(isolate, \"autoBookmark\");\n if (ui::PageTransitionCoreTypeIs(val,\n ui::PageTransition::PAGE_TRANSITION_AUTO_SUBFRAME))\n return StringToV8(isolate, \"autoSubframe\");\n if (ui::PageTransitionCoreTypeIs(val,\n ui::PageTransition::PAGE_TRANSITION_MANUAL_SUBFRAME))\n return StringToV8(isolate, \"manualSubframe\");\n if (ui::PageTransitionCoreTypeIs(val,\n ui::PageTransition::PAGE_TRANSITION_GENERATED))\n return StringToV8(isolate, \"generated\");\n if (ui::PageTransitionCoreTypeIs(val,\n ui::PageTransition::PAGE_TRANSITION_AUTO_TOPLEVEL))\n return StringToV8(isolate, \"autoToplevel\");\n if (ui::PageTransitionCoreTypeIs(val,\n ui::PageTransition::PAGE_TRANSITION_FORM_SUBMIT))\n return StringToV8(isolate, \"formSubmit\");\n if (ui::PageTransitionCoreTypeIs(val,\n ui::PageTransition::PAGE_TRANSITION_RELOAD))\n return StringToV8(isolate, \"reload\");\n if (ui::PageTransitionCoreTypeIs(val,\n ui::PageTransition::PAGE_TRANSITION_KEYWORD))\n return StringToV8(isolate, \"keyword\");\n if (ui::PageTransitionCoreTypeIs(val,\n ui::PageTransition::PAGE_TRANSITION_KEYWORD_GENERATED))\n return StringToV8(isolate, \"keywordGenerated\");\n\n return StringToV8(isolate, \"unknown\");\n}\n\n} \/\/ namespace mate\n<|endoftext|>"} {"text":"<commit_before>#pragma once\n\n#include <c2py\/callback_wrapper.hpp>\n\n#include \"iTapTradeAPI.h\"\n\nnamespace c2py\n{\n \/\/ \/\/ TapAPIOrderInfoNotice\n \/\/ struct FixedTapAPIOrderInfoNotice : ITapTrade::TapAPIOrderInfoNotice\n \/\/ {\n \/\/ ITapTrade::TapAPIOrderInfo order_info;\n \/\/ \n \/\/ \/\/ copy from original structure\n \/\/ FixedTapAPIOrderInfoNotice(const ITapTrade::TapAPIOrderInfoNotice* info)\n \/\/ : TapAPIOrderInfoNotice(*info), order_info(info->OrderInfo != nullptr ? *info->OrderInfo : ITapTrade::TapAPIOrderInfo{})\n \/\/ {\n \/\/ \/\/ fix pointer if there is one\n \/\/ this->OrderInfo = info->OrderInfo != nullptr ? &this->order_info : nullptr;\n \/\/ }\n \/\/ \n \/\/ \/\/ copy constructor\n \/\/ FixedTapAPIOrderInfoNotice(const FixedTapAPIOrderInfoNotice& fixed)\n \/\/ : TapAPIOrderInfoNotice(fixed), order_info(fixed.order_info)\n \/\/ {\n \/\/ \/\/ fix pointer if there is one\n \/\/ this->OrderInfo = this->OrderInfo != nullptr ? &this->order_info : nullptr;\n \/\/ }\n \/\/ };\n \/\/ \/\/ TapAPIPositionProfit\n \/\/ struct FixedTapAPIPositionProfitNotice : ITapTrade::TapAPIPositionProfitNotice\n \/\/ {\n \/\/ ITapTrade::TapAPIPositionProfit data;\n \/\/ \n \/\/ \/\/ copy from original structure\n \/\/ FixedTapAPIPositionProfitNotice(const ITapTrade::TapAPIPositionProfitNotice* info)\n \/\/ : TapAPIPositionProfitNotice(*info), data(info->Data != nullptr ? *info->Data : ITapTrade::TapAPIPositionProfit{})\n \/\/ {\n \/\/ \/\/ fix pointer if there is one\n \/\/ this->Data = info->Data != nullptr ? &this->data : nullptr;\n \/\/ }\n \/\/ \n \/\/ \/\/ copy constructor\n \/\/ FixedTapAPIPositionProfitNotice(const FixedTapAPIPositionProfitNotice& fixed)\n \/\/ : TapAPIPositionProfitNotice(fixed), data(fixed.data)\n \/\/ {\n \/\/ \/\/ fix pointer if there is one\n \/\/ this->Data = this->Data != nullptr ? &this->data : nullptr;\n \/\/ }\n \/\/ };\n \/\/ \n \/\/ namespace arg_helper\n \/\/ {\n \/\/ inline auto save(const ITapTrade::TapAPIOrderInfoNotice* info)\n \/\/ { \/\/ match char []\n \/\/ return FixedTapAPIOrderInfoNotice(info);\n \/\/ }\n \/\/ \n \/\/ template <>\n \/\/ struct loader<ITapTrade::TapAPIOrderInfoNotice>\n \/\/ {\n \/\/ inline FixedTapAPIOrderInfoNotice operator ()(FixedTapAPIOrderInfoNotice& val)\n \/\/ {\n \/\/ return val;\n \/\/ }\n \/\/ };\n \/\/ \n \/\/ inline auto save(const ITapTrade::TapAPIPositionProfitNotice* info)\n \/\/ { \/\/ match char []\n \/\/ return FixedTapAPIPositionProfitNotice(info);\n \/\/ }\n \/\/ \n \/\/ template <>\n \/\/ struct loader<ITapTrade::TapAPIPositionProfitNotice>\n \/\/ {\n \/\/ inline FixedTapAPIPositionProfitNotice operator ()(FixedTapAPIPositionProfitNotice& val)\n \/\/ {\n \/\/ return val;\n \/\/ }\n \/\/ };\n \/\/ }\n\n template<>\n struct callback_wrapper<&ITapTrade::ITapTradeAPINotify::OnRspOrderAction>\n {\n inline static void call(ITapTrade::ITapTradeAPINotify* instance, const char* py_func_name, ITapTrade::TAPIUINT32 sessionID, ITapTrade::TAPIINT32 errorCode, const ITapTrade::TapAPIOrderActionRsp* info)\n {\n ITapTrade::TapAPIOrderInfo orderInfo;\n if (info->OrderInfo != nullptr)\n {\n orderInfo = *info->OrderInfo;\n }\n ITapTrade::TapAPIOrderActionRsp copied_info = *info;\n auto task = [=]() mutable\n {\n if (copied_info.OrderInfo != nullptr)\n {\n copied_info.OrderInfo = &orderInfo; \/\/ ensure pointer is pointer to the correct address(address changes after constructed lambda)\n }\n try\n {\n return default_callback_wrapper<&ITapTrade::ITapTradeAPINotify::OnRspOrderAction>::sync(instance, py_func_name, sessionID, errorCode, &copied_info);\n }\n catch (const async_dispatch_exception& e)\n {\n async_callback_exception_handler::handle_excepiton(e);\n }\n\n };\n dispatcher::instance().add(std::move(task));\n }\n };\n \n template<>\n struct callback_wrapper<&ITapTrade::ITapTradeAPINotify::OnRtnOrder>\n {\n inline static void call(ITapTrade::ITapTradeAPINotify* instance, const char* py_func_name, const ITapTrade::TapAPIOrderInfoNotice* info)\n {\n ITapTrade::TapAPIOrderInfo orderInfo;\n if (info->OrderInfo != nullptr)\n {\n orderInfo = *info->OrderInfo;\n }\n ITapTrade::TapAPIOrderInfoNotice copied_info = *info;\n auto task = [=]() mutable\n {\n if (copied_info.OrderInfo != nullptr)\n {\n copied_info.OrderInfo = &orderInfo; \/\/ ensure pointer is pointer to the correct address(address changes after constructed lambda)\n }\n try\n {\n return default_callback_wrapper<&ITapTrade::ITapTradeAPINotify::OnRtnOrder>::sync(instance, py_func_name, &copied_info);\n }\n catch (const async_dispatch_exception& e)\n {\n async_callback_exception_handler::handle_excepiton(e);\n }\n };\n dispatcher::instance().add(std::move(task));\n }\n };\n\n template<>\n struct callback_wrapper<&ITapTrade::ITapTradeAPINotify::OnRtnPositionProfit>\n {\n inline static void call(ITapTrade::ITapTradeAPINotify* instance, const char* py_func_name, const ITapTrade::TapAPIPositionProfitNotice* info)\n {\n\n ITapTrade::TapAPIPositionProfit profit;\n if (info->Data != nullptr)\n {\n profit = *info->Data;\n }\n ITapTrade::TapAPIPositionProfitNotice copied_info = *info;\n auto task = [=]() mutable\n {\n if (copied_info.Data != nullptr)\n {\n copied_info.Data = &profit; \/\/ ensure pointer is pointer to the correct address(address changes after constructed lambda)\n }\n try\n {\n return default_callback_wrapper<&ITapTrade::ITapTradeAPINotify::OnRtnPositionProfit>::sync(instance, py_func_name, &copied_info);\n }\n catch (const async_dispatch_exception& e)\n {\n async_callback_exception_handler::handle_excepiton(e);\n }\n };\n dispatcher::instance().add(std::move(task));\n }\n };\n}\n<commit_msg>Delete custom_wrappers.hpp<commit_after><|endoftext|>"} {"text":"<commit_before>\/* -*- mode: C++; c-basic-offset: 4; indent-tabs-mode: nil -*- *\/\n\n#pragma once\n\n#include <map>\n#include <string>\n\n#include <db.h>\n\n#include \"exceptions.hpp\"\n\nnamespace ftcxx {\n\n class DBEnv {\n public:\n explicit DBEnv(DB_ENV *e, bool close_on_destroy=false)\n : _env(e),\n _close_on_destroy(close_on_destroy)\n {}\n\n ~DBEnv() {\n if (_env && _close_on_destroy) {\n close();\n }\n }\n\n DBEnv(const DBEnv &) = delete;\n DBEnv& operator=(const DBEnv &) = delete;\n\n DBEnv(DBEnv &&o)\n : _env(nullptr),\n _close_on_destroy(false)\n {\n std::swap(_env, o._env);\n std::swap(_close_on_destroy, o._close_on_destroy);\n }\n\n DBEnv& operator=(DBEnv &&o) {\n std::swap(_env, o._env);\n std::swap(_close_on_destroy, o._close_on_destroy);\n return *this;\n }\n\n DB_ENV *env() const { return _env; }\n\n void close() {\n int r = _env->close(_env, 0);\n handle_ft_retval(r);\n _env = nullptr;\n }\n\n typedef std::map<std::string, TOKU_ENGINE_STATUS_ROW_S> Status;\n void get_status(Status &status, fs_redzone_state &redzone_state, uint64_t &env_panic, std::string &panic_string) const;\n\n void log_flush() {\n int r = _env->log_flush(_env, NULL);\n handle_ft_retval(r);\n }\n\n private:\n DB_ENV *_env;\n bool _close_on_destroy;\n };\n\n class DBEnvBuilder {\n typedef int (*bt_compare_func)(DB *, const DBT *, const DBT *);\n bt_compare_func _bt_compare;\n\n typedef int (*update_func)(DB *, const DBT *, const DBT *, const DBT *, void (*)(const DBT *, void *), void *);\n update_func _update_function;\n\n generate_row_for_put_func _generate_row_for_put;\n generate_row_for_del_func _generate_row_for_del;\n\n uint32_t _cleaner_period;\n uint32_t _cleaner_iterations;\n uint32_t _checkpointing_period;\n\n uint64_t _lk_max_memory;\n uint64_t _lock_wait_time_msec;\n\n typedef uint64_t (*get_lock_wait_time_cb_func)(uint64_t);\n get_lock_wait_time_cb_func _get_lock_wait_time_cb;\n lock_timeout_callback _lock_timeout_callback;\n uint64_t (*_loader_memory_size_callback)(void);\n\n uint32_t _cachesize_gbytes;\n uint32_t _cachesize_bytes;\n\n std::string _lg_dir;\n std::string _tmp_dir;\n\n bool _direct_io;\n bool _compress_buffers;\n\n public:\n DBEnvBuilder()\n : _bt_compare(nullptr),\n _update_function(nullptr),\n _generate_row_for_put(nullptr),\n _generate_row_for_del(nullptr),\n _cleaner_period(0),\n _cleaner_iterations(0),\n _checkpointing_period(0),\n _lk_max_memory(0),\n _lock_wait_time_msec(0),\n _get_lock_wait_time_cb(nullptr),\n _lock_timeout_callback(nullptr),\n _loader_memory_size_callback(nullptr),\n _cachesize_gbytes(0),\n _cachesize_bytes(0),\n _lg_dir(\"\"),\n _tmp_dir(\"\"),\n _direct_io(false),\n _compress_buffers(true)\n {}\n\n DBEnv open(const char *env_dir, uint32_t flags, int mode) const {\n db_env_set_direct_io(_direct_io);\n db_env_set_compress_buffers_before_eviction(_compress_buffers);\n\n DB_ENV *env;\n int r = db_env_create(&env, 0);\n handle_ft_retval(r);\n\n if (_bt_compare) {\n r = env->set_default_bt_compare(env, _bt_compare);\n handle_ft_retval(r);\n }\n\n if (_update_function) {\n env->set_update(env, _update_function);\n }\n\n if (_generate_row_for_put) {\n r = env->set_generate_row_callback_for_put(env, _generate_row_for_put);\n handle_ft_retval(r);\n }\n\n if (_generate_row_for_del) {\n r = env->set_generate_row_callback_for_del(env, _generate_row_for_del);\n handle_ft_retval(r);\n }\n\n if (_lk_max_memory) {\n r = env->set_lk_max_memory(env, _lk_max_memory);\n handle_ft_retval(r);\n }\n\n if (_lock_wait_time_msec || _get_lock_wait_time_cb) {\n uint64_t wait_time = _lock_wait_time_msec;\n if (!wait_time) {\n r = env->get_lock_timeout(env, &wait_time);\n handle_ft_retval(r);\n }\n r = env->set_lock_timeout(env, wait_time, _get_lock_wait_time_cb);\n handle_ft_retval(r);\n }\n\n if (_lock_timeout_callback) {\n r = env->set_lock_timeout_callback(env, _lock_timeout_callback);\n handle_ft_retval(r);\n }\n\n if (_loader_memory_size_callback) {\n env->set_loader_memory_size(env, _loader_memory_size_callback);\n }\n\n if (_cachesize_gbytes || _cachesize_bytes) {\n r = env->set_cachesize(env, _cachesize_gbytes, _cachesize_bytes, 1);\n handle_ft_retval(r);\n }\n\n if (!_lg_dir.empty()) {\n r = env->set_lg_dir(env, _lg_dir.c_str());\n handle_ft_retval(r);\n }\n\n if (!_tmp_dir.empty()) {\n r = env->set_tmp_dir(env, _tmp_dir.c_str());\n handle_ft_retval(r);\n }\n\n r = env->open(env, env_dir, flags, mode);\n handle_ft_retval(r);\n\n if (_cleaner_period) {\n r = env->cleaner_set_period(env, _cleaner_period);\n handle_ft_retval(r);\n }\n\n if (_cleaner_iterations) {\n r = env->cleaner_set_iterations(env, _cleaner_iterations);\n handle_ft_retval(r);\n }\n\n if (_checkpointing_period) {\n r = env->checkpointing_set_period(env, _checkpointing_period);\n handle_ft_retval(r);\n }\n\n return DBEnv(env, true);\n }\n\n DBEnvBuilder& set_direct_io(bool direct_io) {\n _direct_io = direct_io;\n return *this;\n }\n\n DBEnvBuilder& set_compress_buffers_before_eviction(bool compress_buffers) {\n _compress_buffers = compress_buffers;\n return *this;\n }\n\n DBEnvBuilder& set_default_bt_compare(bt_compare_func bt_compare) {\n _bt_compare = bt_compare;\n return *this;\n }\n\n DBEnvBuilder& set_update(update_func update_function) {\n _update_function = update_function;\n return *this;\n }\n\n DBEnvBuilder& set_generate_row_callback_for_put(generate_row_for_put_func generate_row_for_put) {\n _generate_row_for_put = generate_row_for_put;\n return *this;\n }\n\n DBEnvBuilder& set_generate_row_callback_for_del(generate_row_for_del_func generate_row_for_del) {\n _generate_row_for_del = generate_row_for_del;\n return *this;\n }\n\n DBEnvBuilder& cleaner_set_period(uint32_t period) {\n _cleaner_period = period;\n return *this;\n }\n\n DBEnvBuilder& cleaner_set_iterations(uint32_t iterations) {\n _cleaner_iterations = iterations;\n return *this;\n }\n\n DBEnvBuilder& checkpointing_set_period(uint32_t period) {\n _checkpointing_period = period;\n return *this;\n }\n\n DBEnvBuilder& set_lk_max_memory(uint64_t sz) {\n _lk_max_memory = sz;\n return *this;\n }\n\n DBEnvBuilder& set_lock_wait_time_msec(uint64_t lock_wait_time_msec) {\n _lock_wait_time_msec = lock_wait_time_msec;\n return *this;\n }\n\n DBEnvBuilder& set_lock_wait_time_cb(get_lock_wait_time_cb_func get_lock_wait_time_cb) {\n _get_lock_wait_time_cb = get_lock_wait_time_cb;\n return *this;\n }\n\n DBEnvBuilder& set_lock_timeout_callback(lock_timeout_callback callback) {\n _lock_timeout_callback = callback;\n return *this;\n }\n\n DBEnvBuilder& set_loader_memory_size(uint64_t (*callback)(void)) {\n _loader_memory_size_callback = callback;\n return *this;\n }\n\n DBEnvBuilder& set_cachesize(uint32_t gbytes, uint32_t bytes) {\n _cachesize_gbytes = gbytes;\n _cachesize_bytes = bytes;\n return *this;\n }\n\n DBEnvBuilder& set_lg_dir(const char *lg_dir) {\n _lg_dir = std::string(lg_dir);\n return *this;\n }\n\n DBEnvBuilder& set_tmp_dir(const char *tmp_dir) {\n _tmp_dir = std::string(tmp_dir);\n return *this;\n }\n };\n\n} \/\/ namespace ftcxx\n<commit_msg>ftcxx: Add log flush period<commit_after>\/* -*- mode: C++; c-basic-offset: 4; indent-tabs-mode: nil -*- *\/\n\n#pragma once\n\n#include <map>\n#include <string>\n\n#include <db.h>\n\n#include \"exceptions.hpp\"\n\nnamespace ftcxx {\n\n class DBEnv {\n public:\n explicit DBEnv(DB_ENV *e, bool close_on_destroy=false)\n : _env(e),\n _close_on_destroy(close_on_destroy)\n {}\n\n ~DBEnv() {\n if (_env && _close_on_destroy) {\n close();\n }\n }\n\n DBEnv(const DBEnv &) = delete;\n DBEnv& operator=(const DBEnv &) = delete;\n\n DBEnv(DBEnv &&o)\n : _env(nullptr),\n _close_on_destroy(false)\n {\n std::swap(_env, o._env);\n std::swap(_close_on_destroy, o._close_on_destroy);\n }\n\n DBEnv& operator=(DBEnv &&o) {\n std::swap(_env, o._env);\n std::swap(_close_on_destroy, o._close_on_destroy);\n return *this;\n }\n\n DB_ENV *env() const { return _env; }\n\n void close() {\n int r = _env->close(_env, 0);\n handle_ft_retval(r);\n _env = nullptr;\n }\n\n typedef std::map<std::string, TOKU_ENGINE_STATUS_ROW_S> Status;\n void get_status(Status &status, fs_redzone_state &redzone_state, uint64_t &env_panic, std::string &panic_string) const;\n\n void log_flush() {\n int r = _env->log_flush(_env, NULL);\n handle_ft_retval(r);\n }\n\n private:\n DB_ENV *_env;\n bool _close_on_destroy;\n };\n\n class DBEnvBuilder {\n typedef int (*bt_compare_func)(DB *, const DBT *, const DBT *);\n bt_compare_func _bt_compare;\n\n typedef int (*update_func)(DB *, const DBT *, const DBT *, const DBT *, void (*)(const DBT *, void *), void *);\n update_func _update_function;\n\n generate_row_for_put_func _generate_row_for_put;\n generate_row_for_del_func _generate_row_for_del;\n\n uint32_t _cleaner_period;\n uint32_t _cleaner_iterations;\n uint32_t _checkpointing_period;\n uint32_t _fsync_log_period_msec;\n\n uint64_t _lk_max_memory;\n uint64_t _lock_wait_time_msec;\n\n typedef uint64_t (*get_lock_wait_time_cb_func)(uint64_t);\n get_lock_wait_time_cb_func _get_lock_wait_time_cb;\n lock_timeout_callback _lock_timeout_callback;\n uint64_t (*_loader_memory_size_callback)(void);\n\n uint32_t _cachesize_gbytes;\n uint32_t _cachesize_bytes;\n\n std::string _lg_dir;\n std::string _tmp_dir;\n\n bool _direct_io;\n bool _compress_buffers;\n\n public:\n DBEnvBuilder()\n : _bt_compare(nullptr),\n _update_function(nullptr),\n _generate_row_for_put(nullptr),\n _generate_row_for_del(nullptr),\n _cleaner_period(0),\n _cleaner_iterations(0),\n _checkpointing_period(0),\n _fsync_log_period_msec(0),\n _lk_max_memory(0),\n _lock_wait_time_msec(0),\n _get_lock_wait_time_cb(nullptr),\n _lock_timeout_callback(nullptr),\n _loader_memory_size_callback(nullptr),\n _cachesize_gbytes(0),\n _cachesize_bytes(0),\n _lg_dir(\"\"),\n _tmp_dir(\"\"),\n _direct_io(false),\n _compress_buffers(true)\n {}\n\n DBEnv open(const char *env_dir, uint32_t flags, int mode) const {\n db_env_set_direct_io(_direct_io);\n db_env_set_compress_buffers_before_eviction(_compress_buffers);\n\n DB_ENV *env;\n int r = db_env_create(&env, 0);\n handle_ft_retval(r);\n\n if (_bt_compare) {\n r = env->set_default_bt_compare(env, _bt_compare);\n handle_ft_retval(r);\n }\n\n if (_update_function) {\n env->set_update(env, _update_function);\n }\n\n if (_generate_row_for_put) {\n r = env->set_generate_row_callback_for_put(env, _generate_row_for_put);\n handle_ft_retval(r);\n }\n\n if (_generate_row_for_del) {\n r = env->set_generate_row_callback_for_del(env, _generate_row_for_del);\n handle_ft_retval(r);\n }\n\n if (_lk_max_memory) {\n r = env->set_lk_max_memory(env, _lk_max_memory);\n handle_ft_retval(r);\n }\n\n if (_lock_wait_time_msec || _get_lock_wait_time_cb) {\n uint64_t wait_time = _lock_wait_time_msec;\n if (!wait_time) {\n r = env->get_lock_timeout(env, &wait_time);\n handle_ft_retval(r);\n }\n r = env->set_lock_timeout(env, wait_time, _get_lock_wait_time_cb);\n handle_ft_retval(r);\n }\n\n if (_lock_timeout_callback) {\n r = env->set_lock_timeout_callback(env, _lock_timeout_callback);\n handle_ft_retval(r);\n }\n\n if (_loader_memory_size_callback) {\n env->set_loader_memory_size(env, _loader_memory_size_callback);\n }\n\n if (_cachesize_gbytes || _cachesize_bytes) {\n r = env->set_cachesize(env, _cachesize_gbytes, _cachesize_bytes, 1);\n handle_ft_retval(r);\n }\n\n if (!_lg_dir.empty()) {\n r = env->set_lg_dir(env, _lg_dir.c_str());\n handle_ft_retval(r);\n }\n\n if (!_tmp_dir.empty()) {\n r = env->set_tmp_dir(env, _tmp_dir.c_str());\n handle_ft_retval(r);\n }\n\n r = env->open(env, env_dir, flags, mode);\n handle_ft_retval(r);\n\n if (_cleaner_period) {\n r = env->cleaner_set_period(env, _cleaner_period);\n handle_ft_retval(r);\n }\n\n if (_cleaner_iterations) {\n r = env->cleaner_set_iterations(env, _cleaner_iterations);\n handle_ft_retval(r);\n }\n\n if (_checkpointing_period) {\n r = env->checkpointing_set_period(env, _checkpointing_period);\n handle_ft_retval(r);\n }\n\n if (_fsync_log_period_msec) {\n env->change_fsync_log_period(env, _fsync_log_period_msec);\n }\n\n return DBEnv(env, true);\n }\n\n DBEnvBuilder& set_direct_io(bool direct_io) {\n _direct_io = direct_io;\n return *this;\n }\n\n DBEnvBuilder& set_compress_buffers_before_eviction(bool compress_buffers) {\n _compress_buffers = compress_buffers;\n return *this;\n }\n\n DBEnvBuilder& set_default_bt_compare(bt_compare_func bt_compare) {\n _bt_compare = bt_compare;\n return *this;\n }\n\n DBEnvBuilder& set_update(update_func update_function) {\n _update_function = update_function;\n return *this;\n }\n\n DBEnvBuilder& set_generate_row_callback_for_put(generate_row_for_put_func generate_row_for_put) {\n _generate_row_for_put = generate_row_for_put;\n return *this;\n }\n\n DBEnvBuilder& set_generate_row_callback_for_del(generate_row_for_del_func generate_row_for_del) {\n _generate_row_for_del = generate_row_for_del;\n return *this;\n }\n\n DBEnvBuilder& cleaner_set_period(uint32_t period) {\n _cleaner_period = period;\n return *this;\n }\n\n DBEnvBuilder& cleaner_set_iterations(uint32_t iterations) {\n _cleaner_iterations = iterations;\n return *this;\n }\n\n DBEnvBuilder& checkpointing_set_period(uint32_t period) {\n _checkpointing_period = period;\n return *this;\n }\n\n DBEnvBuilder& change_fsync_log_period(uint32_t period) {\n _fsync_log_period_msec = period;\n return *this;\n }\n\n DBEnvBuilder& set_lk_max_memory(uint64_t sz) {\n _lk_max_memory = sz;\n return *this;\n }\n\n DBEnvBuilder& set_lock_wait_time_msec(uint64_t lock_wait_time_msec) {\n _lock_wait_time_msec = lock_wait_time_msec;\n return *this;\n }\n\n DBEnvBuilder& set_lock_wait_time_cb(get_lock_wait_time_cb_func get_lock_wait_time_cb) {\n _get_lock_wait_time_cb = get_lock_wait_time_cb;\n return *this;\n }\n\n DBEnvBuilder& set_lock_timeout_callback(lock_timeout_callback callback) {\n _lock_timeout_callback = callback;\n return *this;\n }\n\n DBEnvBuilder& set_loader_memory_size(uint64_t (*callback)(void)) {\n _loader_memory_size_callback = callback;\n return *this;\n }\n\n DBEnvBuilder& set_cachesize(uint32_t gbytes, uint32_t bytes) {\n _cachesize_gbytes = gbytes;\n _cachesize_bytes = bytes;\n return *this;\n }\n\n DBEnvBuilder& set_lg_dir(const char *lg_dir) {\n _lg_dir = std::string(lg_dir);\n return *this;\n }\n\n DBEnvBuilder& set_tmp_dir(const char *tmp_dir) {\n _tmp_dir = std::string(tmp_dir);\n return *this;\n }\n };\n\n} \/\/ namespace ftcxx\n<|endoftext|>"} {"text":"<commit_before>\/****************************************************************************\n**\n** Copyright (c) 2008-2009 Nokia Corporation and\/or its subsidiary(-ies).\n**\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n** This file is part of the Qt Mobility Components.\n**\n** $QT_BEGIN_LICENSE:LGPL$\n** No Commercial Usage\n** This file contains pre-release code and may not be distributed.\n** You may use this file in accordance with the terms and conditions\n** contained in the Technology Preview License Agreement accompanying\n** this package.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Nokia gives you certain\n** additional rights. These rights are described in the Nokia Qt LGPL\n** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this\n** package.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at http:\/\/qt.nokia.com\/contact.\n** $QT_END_LICENSE$\n**\n****************************************************************************\/\n\n#include <QFile>\n#include <QtGui\/QIcon>\n#include \"v4lvideodevicecontrol.h\"\n#include \"v4lcamerasession.h\"\n\nV4LVideoDeviceControl::V4LVideoDeviceControl(QObject *parent)\n : QVideoDeviceControl(parent)\n{\n m_session = qobject_cast<V4LCameraSession*>(parent);\n\n QString name;\n QFile video0(\"\/sys\/class\/video4linux\/video0\/name\");\n if (video0.exists()) {\n devices.append(\"dev\/video0\");\n char str[30];\n memset(str,0,30);\n video0.open(QIODevice::ReadOnly);\n video0.read(str,30);\n name = QString(str);\n descriptions.append(name.simplified());\n video0.close();\n }\n\n QFile video1(\"\/sys\/class\/video4linux\/video1\/name\");\n if (video0.exists()) {\n devices.append(\"dev\/video1\");\n char str[30];\n memset(str,0,30);\n video1.open(QIODevice::ReadOnly);\n video1.read(str,30);\n name = QString(str);\n descriptions.append(name.simplified());\n video1.close();\n }\n selected = 0;\n}\n\nint V4LVideoDeviceControl::deviceCount() const\n{\n return devices.count();\n}\n\nQString V4LVideoDeviceControl::name(int index) const\n{\n if(index >= 0 && index <= devices.count())\n return devices.at(index);\n\n return QString();\n}\n\nQString V4LVideoDeviceControl::description(int index) const\n{\n if(index >= 0 && index <= descriptions.count())\n return descriptions.at(index);\n\n return QString();\n}\n\nQIcon V4LVideoDeviceControl::icon(int index) const\n{\n Q_UNUSED(index)\n\n return QIcon();\n}\n\nint V4LVideoDeviceControl::defaultDevice() const\n{\n return 0;\n}\n\nint V4LVideoDeviceControl::selectedDevice() const\n{\n return selected;\n}\n\nvoid V4LVideoDeviceControl::setSelectedDevice(int index)\n{\n if(index >= 0 && index <= devices.count()) {\n if (m_session)\n m_session->setDevice(devices.at(index));\n selected = index;\n }\n}\n\n<commit_msg>Fixed bug in v4l plugin, wasnt setting device correctly.<commit_after>\/****************************************************************************\n**\n** Copyright (c) 2008-2009 Nokia Corporation and\/or its subsidiary(-ies).\n**\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n** This file is part of the Qt Mobility Components.\n**\n** $QT_BEGIN_LICENSE:LGPL$\n** No Commercial Usage\n** This file contains pre-release code and may not be distributed.\n** You may use this file in accordance with the terms and conditions\n** contained in the Technology Preview License Agreement accompanying\n** this package.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Nokia gives you certain\n** additional rights. These rights are described in the Nokia Qt LGPL\n** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this\n** package.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at http:\/\/qt.nokia.com\/contact.\n** $QT_END_LICENSE$\n**\n****************************************************************************\/\n\n#include <QFile>\n#include <QtGui\/QIcon>\n#include \"v4lvideodevicecontrol.h\"\n#include \"v4lcamerasession.h\"\n\nV4LVideoDeviceControl::V4LVideoDeviceControl(QObject *parent)\n : QVideoDeviceControl(parent)\n{\n m_session = qobject_cast<V4LCameraSession*>(parent);\n\n QString name;\n QFile video0(\"\/sys\/class\/video4linux\/video0\/name\");\n if (video0.exists()) {\n devices.append(\"\/dev\/video0\");\n char str[30];\n memset(str,0,30);\n video0.open(QIODevice::ReadOnly);\n video0.read(str,30);\n name = QString(str);\n descriptions.append(name.simplified());\n video0.close();\n }\n\n QFile video1(\"\/sys\/class\/video4linux\/video1\/name\");\n if (video0.exists()) {\n devices.append(\"\/dev\/video1\");\n char str[30];\n memset(str,0,30);\n video1.open(QIODevice::ReadOnly);\n video1.read(str,30);\n name = QString(str);\n descriptions.append(name.simplified());\n video1.close();\n }\n selected = 0;\n}\n\nint V4LVideoDeviceControl::deviceCount() const\n{\n return devices.count();\n}\n\nQString V4LVideoDeviceControl::name(int index) const\n{\n if(index >= 0 && index <= devices.count())\n return devices.at(index);\n\n return QString();\n}\n\nQString V4LVideoDeviceControl::description(int index) const\n{\n if(index >= 0 && index <= descriptions.count())\n return descriptions.at(index);\n\n return QString();\n}\n\nQIcon V4LVideoDeviceControl::icon(int index) const\n{\n Q_UNUSED(index)\n\n return QIcon();\n}\n\nint V4LVideoDeviceControl::defaultDevice() const\n{\n return 0;\n}\n\nint V4LVideoDeviceControl::selectedDevice() const\n{\n return selected;\n}\n\nvoid V4LVideoDeviceControl::setSelectedDevice(int index)\n{\n if(index >= 0 && index <= devices.count()) {\n if (m_session)\n m_session->setDevice(devices.at(index));\n selected = index;\n }\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/** @file\n @brief Header\n\n @date 2016\n\n @author\n Sensics, Inc.\n <http:\/\/sensics.com>\n\n*\/\n\n\/\/ Copyright 2016 Sensics, Inc.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ \thttp:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#ifndef INCLUDED_UVCImageSource_cpp_GUID_2563F019_11B6_4F61_9E8C_C3ED2A573AF6\n#define INCLUDED_UVCImageSource_cpp_GUID_2563F019_11B6_4F61_9E8C_C3ED2A573AF6\n\n\/\/ Internal Includes\n#include \"ImageSource.h\"\n#include \"ImageSourceFactories.h\"\n\n\/\/ Library\/third-party includes\n#include <libuvc\/libuvc.h>\n#include <opencv2\/core\/core_c.h>\n\n\/\/ Standard includes\n#include <memory>\n#include <stdexcept>\n#include <string>\n#include <iostream>\n#include <cstdio>\n#include <unistd.h>\n#include <mutex>\n\nnamespace osvr {\nnamespace vbtracker {\n class UVCImageSource : public ImageSource {\n public:\n \/\/\/ Constructor\n UVCImageSource(int vendor_id = 0, int product_id = 0, const char* serial_number = nullptr);\n\n \/\/\/ Destructor\n virtual ~UVCImageSource();\n\n \/\/\/ @return true if the camera\/image source is OK\n virtual bool ok() const override;\n\n \/\/\/ Trigger camera capture. May not necessarily include retrieval.\n \/\/\/ Blocks until an image is available. or failure occurs.\n \/\/\/\n \/\/\/ Timestamp after this call returns.\n \/\/\/\n \/\/\/ @return false if the camera failed.\n virtual bool grab() override;\n\n \/\/\/ Get resolution of the images from this source.\n virtual cv::Size resolution() const override;\n\n \/\/\/ For those devices that naturally read a non-corrupt color image,\n \/\/\/ overriding just this method will let the default implementation of\n \/\/\/ retrieve() do the RGB to Gray for you.\n virtual void retrieveColor(cv::Mat &color) override;\n\n protected:\n \/\/\/ This callback function is called each time a new frame is received\n \/\/\/ from the video stream.\n \/\/@{\n static void callback(uvc_frame_t *frame, void *ptr);\n void callback(uvc_frame_t *frame);\n \/\/@}\n\n private:\n uvc_context_t* uvcContext_;\n uvc_device_t* camera_;\n uvc_device_handle_t* cameraHandle_;\n uvc_stream_ctrl_t streamControl_;\n\n cv::Size resolution_; \/\/< resolution of camera\n uvc_frame_t* frame_; \/\/< raw UVC frame\n\n std::mutex mutex_; \/\/< to protect frame_\n };\n\n using UVCImageSourcePtr = std::unique_ptr<UVCImageSource>;\n\n UVCImageSource::UVCImageSource(int vendor_id, int product_id, const char* serial_number) :\n uvcContext_{nullptr}, camera_{nullptr}, cameraHandle_{nullptr}, streamControl_{}, resolution_{0, 0}, frame_{nullptr}\n {\n \/\/ TODO\n\n \/\/ Initialize the libuvc context\n const auto init_res = uvc_init(&uvcContext_, nullptr);\n if (UVC_SUCCESS != init_res) {\n throw std::runtime_error(\"Error initializing UVC context: \" + std::string(uvc_strerror(init_res)));\n }\n\n \/\/ Find the requested camera\n const auto find_res = uvc_find_device(uvcContext_, &camera_, vendor_id, product_id, serial_number);\n if (UVC_SUCCESS != find_res) {\n uvc_exit(uvcContext_);\n throw std::runtime_error(\"Error finding requested camera: \" + std::string(uvc_strerror(find_res)));\n }\n\n \/\/ Try to open the device -- requires exclusive access\n const auto open_res = uvc_open(camera_, &cameraHandle_);\n if (UVC_SUCCESS != open_res) {\n uvc_unref_device(camera_);\n uvc_exit(uvcContext_);\n throw std::runtime_error(\"Error opening camera: \" + std::string(uvc_strerror(open_res)));\n }\n \/\/uvc_print_diag(cameraHandle_, stdout);\n\n \/\/ Setup streaming parameters\n const int resolution_x = 640; \/\/ pixels\n const int resolution_y = 480; \/\/ pixels\n resolution_ = cvSize(resolution_x, resolution_y);\n const int frame_rate = 100; \/\/ fps\n const auto setup_res = uvc_get_stream_ctrl_format_size(cameraHandle_,\n &streamControl_,\n UVC_FRAME_FORMAT_MJPEG,\n resolution_x,\n resolution_y,\n frame_rate);\n \/\/uvc_print_stream_ctrl(&streamControl_, stdout);\n if (UVC_SUCCESS != setup_res) {\n std::cerr << \"Error setting up requested stream format. \"\n + std::string(uvc_strerror(setup_res));\n }\n\n \/\/ Start streaming video.\n const auto stream_res = uvc_start_streaming(cameraHandle_, &streamControl_, &UVCImageSource::callback, this, 0);\n if (UVC_SUCCESS != stream_res) {\n uvc_close(cameraHandle_);\n uvc_unref_device(camera_);\n uvc_exit(uvcContext_);\n throw std::runtime_error(\"Error streaming from camera: \" + std::string(uvc_strerror(stream_res)));\n }\n\n }\n\n UVCImageSource::~UVCImageSource()\n {\n \/\/ Stop streaming video\n uvc_stop_streaming(cameraHandle_);\n\n \/\/ Release our handle on the camera\n uvc_close(cameraHandle_);\n\n \/\/ Release the device descriptor\n uvc_unref_device(camera_);\n\n \/\/ Close the UVC context. This closes and cleans up any existing device\n \/\/ handles, and it closes the libusb context if one was not provided\n uvc_exit(uvcContext_);\n }\n\n bool UVCImageSource::ok() const\n {\n \/\/ TODO\n return true;\n }\n\n bool UVCImageSource::grab()\n {\n \/\/ libuvc doesn't provide for separate grab() and retrieve() operations.\n \/\/ Instead, grab() will set a flag to alert the callback function that\n \/\/ we wish to store the next frame and retrieve() will return that\n \/\/ frame.\n std::lock_guard<std::mutex> guard(mutex_);\n return (frame_ != nullptr);\n }\n\n cv::Size UVCImageSource::resolution() const\n {\n return resolution_;\n }\n\n void UVCImageSource::retrieveColor(cv::Mat &color)\n {\n \/\/ libuvc doesn't provide for separate grab() and retrieve() operations.\n \/\/ Instead, grab() will set a flag to alert the callback function that\n \/\/ we wish to store the next frame and retrieve() will return that\n \/\/ frame.\n\n std::lock_guard<std::mutex> guard(mutex_);\n\n if (!frame_) {\n throw std::runtime_error(\"Error: There's no frame available.\");\n }\n\n \/\/ We'll convert the image from YUV\/JPEG to rgb, so allocate space\n auto rgb = uvc_allocate_frame(frame_->width * frame_->height * 3);\n if (!rgb) {\n throw std::runtime_error(\"Error: Unable to allocate the rgb frame.\");\n }\n\n \/\/ Do the rgb conversion\n auto convert_ret = uvc_mjpeg2rgb(frame_, rgb);\n if (UVC_SUCCESS != convert_ret) {\n \/\/ Try any2rgb() instead\n auto any_ret = uvc_any2rgb(frame_, rgb);\n if (UVC_SUCCESS != any_ret) {\n uvc_free_frame(rgb);\n throw std::runtime_error(\"Error: Unable to convert frame to rgb: \" + std::string(uvc_strerror(convert_ret)));\n }\n }\n\n \/\/ Convert the image to at cv::Mat\n color = cv::Mat(rgb->height, rgb->width, CV_8UC3, rgb->data).clone();\n\n uvc_free_frame(rgb);\n }\n\n void UVCImageSource::callback(uvc_frame_t *frame, void *ptr)\n {\n auto me = static_cast<UVCImageSource*>(ptr);\n me->callback(frame);\n }\n\n void UVCImageSource::callback(uvc_frame_t *frame)\n {\n \/\/ Just copy the UVC frame to keep things quick. We'll do any conversion\n \/\/ upon request in the retrieveColor() method.\n std::lock_guard<std::mutex> guard(mutex_);\n if (frame_)\n uvc_free_frame(frame_);\n frame_ = uvc_allocate_frame(frame->data_bytes);\n uvc_duplicate_frame(frame, frame_);\n }\n\n \/\/\/ Factory method to open a USB video class (UVC) device as an image\n \/\/\/ source.\n ImageSourcePtr openUVCCamera(int vendor_id, int product_id, const char* serial_number)\n {\n auto ret = ImageSourcePtr{};\n try {\n auto source = new UVCImageSource(vendor_id, product_id, serial_number);\n ret.reset(source);\n } catch (const std::exception& e) {\n std::cerr << \"Caught exception initializing UVC camera image source: \" << e.what() << std::endl;\n }\n return ret;\n }\n\n \/\/\/ Factory method to open the HDK camera as an image source via libuvc.\n ImageSourcePtr openHDKCameraUVC()\n {\n const int vendor_id = 0x0bda;\n const int product_id = 0x57e8;\n return openUVCCamera(vendor_id, product_id);\n }\n\n} \/\/ namespace vbtracker\n} \/\/ namespace osvr\n\n#endif \/\/ INCLUDED_UVCImageSource_cpp_GUID_2563F019_11B6_4F61_9E8C_C3ED2A573AF6\n\n<commit_msg>Added slight buffering to UVCImageSource which fixes dropped frames due to races between the camera and processing threads.<commit_after>\/** @file\n @brief Header\n\n @date 2016\n\n @author\n Sensics, Inc.\n <http:\/\/sensics.com>\n\n*\/\n\n\/\/ Copyright 2016 Sensics, Inc.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ \thttp:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#ifndef INCLUDED_UVCImageSource_cpp_GUID_2563F019_11B6_4F61_9E8C_C3ED2A573AF6\n#define INCLUDED_UVCImageSource_cpp_GUID_2563F019_11B6_4F61_9E8C_C3ED2A573AF6\n\n\/\/ Internal Includes\n#include \"ImageSource.h\"\n#include \"ImageSourceFactories.h\"\n\n\/\/ Library\/third-party includes\n#include <libuvc\/libuvc.h>\n#include <opencv2\/core\/core_c.h>\n\n\/\/ Standard includes\n#include <memory>\n#include <stdexcept>\n#include <string>\n#include <iostream>\n#include <cstdio>\n#include <unistd.h>\n#include <mutex>\n#include <condition_variable>\n#include <queue>\n\nnamespace osvr {\nnamespace vbtracker {\n class UVCImageSource : public ImageSource {\n public:\n \/\/\/ Constructor\n UVCImageSource(int vendor_id = 0, int product_id = 0, const char* serial_number = nullptr);\n\n \/\/\/ Destructor\n virtual ~UVCImageSource();\n\n \/\/\/ @return true if the camera\/image source is OK\n virtual bool ok() const override;\n\n \/\/\/ Trigger camera capture. May not necessarily include retrieval.\n \/\/\/ Blocks until an image is available. or failure occurs.\n \/\/\/\n \/\/\/ Timestamp after this call returns.\n \/\/\/\n \/\/\/ @return false if the camera failed.\n virtual bool grab() override;\n\n \/\/\/ Get resolution of the images from this source.\n virtual cv::Size resolution() const override;\n\n \/\/\/ For those devices that naturally read a non-corrupt color image,\n \/\/\/ overriding just this method will let the default implementation of\n \/\/\/ retrieve() do the RGB to Gray for you.\n virtual void retrieveColor(cv::Mat &color) override;\n\n protected:\n \/\/\/ This callback function is called each time a new frame is received\n \/\/\/ from the video stream.\n \/\/@{\n static void callback(uvc_frame_t *frame, void *ptr);\n void callback(uvc_frame_t *frame);\n \/\/@}\n\n private:\n uvc_context_t* uvcContext_;\n uvc_device_t* camera_;\n uvc_device_handle_t* cameraHandle_;\n uvc_stream_ctrl_t streamControl_;\n\n cv::Size resolution_; \/\/< resolution of camera\n std::queue<uvc_frame_t*> frames_; \/\/< raw UVC frames\n\n std::mutex mutex_; \/\/< to protect frames_\n std::condition_variable frames_available_; \/\/< To allo grab() to wait for frames to become available\n };\n\n using UVCImageSourcePtr = std::unique_ptr<UVCImageSource>;\n\n UVCImageSource::UVCImageSource(int vendor_id, int product_id, const char* serial_number) :\n uvcContext_{nullptr}, camera_{nullptr}, cameraHandle_{nullptr}, streamControl_{}, resolution_{0, 0}\n {\n \/\/ TODO\n\n \/\/ Initialize the libuvc context\n const auto init_res = uvc_init(&uvcContext_, nullptr);\n if (UVC_SUCCESS != init_res) {\n throw std::runtime_error(\"Error initializing UVC context: \" + std::string(uvc_strerror(init_res)));\n }\n\n \/\/ Find the requested camera\n const auto find_res = uvc_find_device(uvcContext_, &camera_, vendor_id, product_id, serial_number);\n if (UVC_SUCCESS != find_res) {\n uvc_exit(uvcContext_);\n throw std::runtime_error(\"Error finding requested camera: \" + std::string(uvc_strerror(find_res)));\n }\n\n \/\/ Try to open the device -- requires exclusive access\n const auto open_res = uvc_open(camera_, &cameraHandle_);\n if (UVC_SUCCESS != open_res) {\n uvc_unref_device(camera_);\n uvc_exit(uvcContext_);\n throw std::runtime_error(\"Error opening camera: \" + std::string(uvc_strerror(open_res)));\n }\n \/\/uvc_print_diag(cameraHandle_, stdout);\n\n \/\/ Setup streaming parameters\n const int resolution_x = 640; \/\/ pixels\n const int resolution_y = 480; \/\/ pixels\n resolution_ = cvSize(resolution_x, resolution_y);\n const int frame_rate = 100; \/\/ fps\n const auto setup_res = uvc_get_stream_ctrl_format_size(cameraHandle_,\n &streamControl_,\n UVC_FRAME_FORMAT_MJPEG,\n resolution_x,\n resolution_y,\n frame_rate);\n \/\/uvc_print_stream_ctrl(&streamControl_, stdout);\n if (UVC_SUCCESS != setup_res) {\n std::cerr << \"Error setting up requested stream format. \"\n + std::string(uvc_strerror(setup_res));\n }\n\n \/\/ Start streaming video.\n const auto stream_res = uvc_start_streaming(cameraHandle_, &streamControl_, &UVCImageSource::callback, this, 0);\n if (UVC_SUCCESS != stream_res) {\n uvc_close(cameraHandle_);\n uvc_unref_device(camera_);\n uvc_exit(uvcContext_);\n throw std::runtime_error(\"Error streaming from camera: \" + std::string(uvc_strerror(stream_res)));\n }\n\n }\n\n UVCImageSource::~UVCImageSource()\n {\n \/\/ Stop streaming video\n uvc_stop_streaming(cameraHandle_);\n\n \/\/ Release our handle on the camera\n uvc_close(cameraHandle_);\n\n \/\/ Release the device descriptor\n uvc_unref_device(camera_);\n\n \/\/ Close the UVC context. This closes and cleans up any existing device\n \/\/ handles, and it closes the libusb context if one was not provided\n uvc_exit(uvcContext_);\n }\n\n bool UVCImageSource::ok() const\n {\n \/\/ TODO\n return true;\n }\n\n bool UVCImageSource::grab()\n {\n \/\/Gain access to frames_ queue\n std::unique_lock<std::mutex> lock(mutex_);\n\n \/\/Check if there are any frames available\n if (frames_.empty())\n\t\/\/Wait for some frames to become available\n\tframes_available_.wait(lock);\n\n \/\/Good to go!\n return !frames_.empty();\n }\n\n cv::Size UVCImageSource::resolution() const\n {\n return resolution_;\n }\n\n void UVCImageSource::retrieveColor(cv::Mat &color)\n {\n uvc_frame_t* current_frame;\n \n {\n\t \/\/Grab a frame from the queue, but don't keep the queue locked!\n\t std::lock_guard<std::mutex> lock(mutex_);\n\t \n\t if (frames_.empty()) {\n\t throw std::runtime_error(\"Error: There's no frames available.\");\n\t }\n\t \n\t current_frame = frames_.front();\n\t frames_.pop();\n };\n\t\n \/\/ We'll convert the image from YUV\/JPEG to rgb, so allocate space\n auto rgb = uvc_allocate_frame(current_frame->width * current_frame->height * 3);\n if (!rgb) {\n throw std::runtime_error(\"Error: Unable to allocate the rgb frame.\");\n }\n\n \/\/ Do the rgb conversion\n auto convert_ret = uvc_mjpeg2rgb(current_frame, rgb);\n if (UVC_SUCCESS != convert_ret) {\n \/\/ Try any2rgb() instead\n auto any_ret = uvc_any2rgb(current_frame, rgb);\n if (UVC_SUCCESS != any_ret) {\n uvc_free_frame(rgb);\n throw std::runtime_error(\"Error: Unable to convert frame to rgb: \" + std::string(uvc_strerror(convert_ret)));\n }\n }\n\n \/\/ Convert the image to at cv::Mat\n color = cv::Mat(rgb->height, rgb->width, CV_8UC3, rgb->data).clone();\n\n uvc_free_frame(current_frame);\n uvc_free_frame(rgb);\n }\n\n void UVCImageSource::callback(uvc_frame_t *frame, void *ptr)\n {\n auto me = static_cast<UVCImageSource*>(ptr);\n me->callback(frame);\n }\n\n void UVCImageSource::callback(uvc_frame_t *frame)\n {\n \/\/ Just copy the UVC frame to keep things quick (cannot drop\n \/\/ frames or we'll lose tracking!). We'll do any conversion\n \/\/ upon request in the retrieveColor() method.\n\n \/\/Copy the frame, then look for the lock\n uvc_frame_t* copied_frame = uvc_allocate_frame(frame->data_bytes);\n uvc_duplicate_frame(frame, copied_frame);\n\n std::lock_guard<std::mutex> lock(mutex_);\n\tframes_.push(copied_frame);\n\tif (frames_.size() > 100) {\n\t std::cerr << \"WARNING! Dropping frames from video tracker as they are not being processed fast enough! This will disrupt tracking.\";\n\t while (!frames_.empty()) {\n\t uvc_free_frame(frames_.front());\n\t frames_.pop();\n\t }\n\t}\n\tframes_available_.notify_one();\n }\n\n \/\/\/ Factory method to open a USB video class (UVC) device as an image\n \/\/\/ source.\n ImageSourcePtr openUVCCamera(int vendor_id, int product_id, const char* serial_number)\n {\n auto ret = ImageSourcePtr{};\n try {\n auto source = new UVCImageSource(vendor_id, product_id, serial_number);\n ret.reset(source);\n } catch (const std::exception& e) {\n std::cerr << \"Caught exception initializing UVC camera image source: \" << e.what() << std::endl;\n }\n return ret;\n }\n\n \/\/\/ Factory method to open the HDK camera as an image source via libuvc.\n ImageSourcePtr openHDKCameraUVC()\n {\n const int vendor_id = 0x0bda;\n const int product_id = 0x57e8;\n return openUVCCamera(vendor_id, product_id);\n }\n\n} \/\/ namespace vbtracker\n} \/\/ namespace osvr\n\n#endif \/\/ INCLUDED_UVCImageSource_cpp_GUID_2563F019_11B6_4F61_9E8C_C3ED2A573AF6\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright 1999-2000,2004-2005 The Apache Software Foundation.\n * \n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * \n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n\/*\n * $Id$\n *\/\n\n#include <windows.h>\n\n#include <xercesc\/util\/FileManagers\/WindowsFileMgr.hpp>\n#include <xercesc\/util\/Janitor.hpp>\n#include <xercesc\/util\/XMLString.hpp>\n#include <xercesc\/util\/XMLUniDefs.hpp>\n\n\nXERCES_CPP_NAMESPACE_BEGIN\n\nstatic bool isBackSlash(XMLCh c) {\n return c == chBackSlash ||\n c == chYenSign ||\n c == chWonSign;\n}\n\nWindowsFileMgr::WindowsFileMgr()\n{\n \/\/ Figure out if we are on NT and save that flag for later use\n OSVERSIONINFO OSVer;\n OSVer.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);\n ::GetVersionEx(&OSVer);\n _onNT = (OSVer.dwPlatformId == VER_PLATFORM_WIN32_NT);\n}\n\n\nWindowsFileMgr::~WindowsFileMgr()\n{\n}\n\n\nFileHandle\nWindowsFileMgr::open(const XMLCh* fileName, bool toWrite, MemoryManager* const manager)\n{\n \/\/ Watch for obvious wierdness\n if (!fileName)\n return 0;\n\n \/\/\n \/\/ We have to play a little trick here. If its \/x:.....\n \/\/ style fully qualified path, we have to toss the leading \/\n \/\/ character.\n \/\/\n const XMLCh* nameToOpen = fileName;\n if (*fileName == chForwardSlash)\n {\n if (XMLString::stringLen(fileName) > 3)\n {\n if (*(fileName + 2) == chColon)\n {\n const XMLCh chDrive = *(fileName + 1);\n if (((chDrive >= chLatin_A) && (chDrive <= chLatin_Z))\n || ((chDrive >= chLatin_a) && (chDrive <= chLatin_z)))\n {\n nameToOpen = fileName + 1;\n }\n }\n\n \/\/ Similarly for UNC paths\n if ( *(fileName + 1) == *(fileName + 2) &&\n (*(fileName + 1) == chForwardSlash ||\n *(fileName + 1) == chBackSlash) )\n {\n nameToOpen = fileName + 1;\n }\n }\n }\n\n \/\/ Ok, this might look stupid but its a semi-expedient way to deal\n \/\/ with a thorny problem. Shift-JIS and some other Asian encodings\n \/\/ are fundamentally broken and map both the backslash and the Yen\n \/\/ sign to the same code point. Transcoders have to pick one or the\n \/\/ other to map '\\' to Unicode and tend to choose the Yen sign.\n \/\/\n \/\/ Unicode Yen or Won signs as directory separators will fail.\n \/\/\n \/\/ So, we will check this path name for Yen or won signs and, if they are\n \/\/ there, we'll replace them with slashes.\n \/\/\n \/\/ A further twist: we replace Yen and Won with forward slashes rather\n \/\/ than back slashes. Either form of slash will work as a directory\n \/\/ separator. On Win 95 and 98, though, Unicode back-slashes may\n \/\/ fail to transode back to 8-bit 0x5C with some Unicode converters\n \/\/ to some of the problematic code pages. Forward slashes always\n \/\/ transcode correctly back to 8 bit char * form.\n \/\/\n XMLCh *tmpUName = 0;\n\n const XMLCh* srcPtr = nameToOpen;\n while (*srcPtr)\n {\n if (*srcPtr == chYenSign ||\n *srcPtr == chWonSign)\n break;\n srcPtr++;\n }\n\n \/\/\n \/\/ If we found a yen, then we have to create a temp file name. Else\n \/\/ go with the file name as is and save the overhead.\n \/\/\n if (*srcPtr)\n {\n tmpUName = XMLString::replicate(nameToOpen, manager);\n\n XMLCh* tmpPtr = tmpUName;\n while (*tmpPtr)\n {\n if (*tmpPtr == chYenSign ||\n *tmpPtr == chWonSign)\n *tmpPtr = chForwardSlash;\n tmpPtr++;\n }\n nameToOpen = tmpUName;\n }\n FileHandle retVal = 0;\n if (_onNT)\n {\n retVal = ::CreateFileW\n (\n (LPCWSTR) nameToOpen\n , toWrite?GENERIC_WRITE:GENERIC_READ\n , FILE_SHARE_READ\n , 0\n , toWrite?CREATE_ALWAYS:OPEN_EXISTING\n , toWrite?FILE_ATTRIBUTE_NORMAL:FILE_FLAG_SEQUENTIAL_SCAN\n , 0\n );\n }\n else\n {\n \/\/\n \/\/ We are Win 95 \/ 98. Take the Unicode file name back to (char *)\n \/\/ so that we can open it.\n \/\/\n char* tmpName = XMLString::transcode(nameToOpen, manager);\n retVal = ::CreateFileA\n (\n tmpName\n , toWrite?GENERIC_WRITE:GENERIC_READ\n , FILE_SHARE_READ\n , 0\n , toWrite?CREATE_ALWAYS:OPEN_EXISTING\n , toWrite?FILE_ATTRIBUTE_NORMAL:FILE_FLAG_SEQUENTIAL_SCAN\n , 0\n );\n manager->deallocate(tmpName);\/\/delete [] tmpName;\n }\n\n if (tmpUName)\n manager->deallocate(tmpUName);\/\/delete [] tmpUName;\n\n if (retVal == INVALID_HANDLE_VALUE)\n return 0;\n\n return retVal;\n}\n\n\nFileHandle\nWindowsFileMgr::open(const char* path, bool toWrite, MemoryManager* const manager)\n{\n FileHandle retVal = ::CreateFileA\n (\n path\n , toWrite?GENERIC_WRITE:GENERIC_READ\n , FILE_SHARE_READ\n , 0\n , toWrite?OPEN_ALWAYS:OPEN_EXISTING\n , toWrite?FILE_ATTRIBUTE_NORMAL:FILE_FLAG_SEQUENTIAL_SCAN\n , 0\n );\n\n if (retVal == INVALID_HANDLE_VALUE)\n return 0;\n\n return retVal;\n}\n\n\nFileHandle\nWindowsFileMgr::openStdIn(MemoryManager* const manager)\n{\n \/\/\n \/\/ Get the standard input handle. Duplicate it and return that copy\n \/\/ since the outside world cannot tell the difference and will shut\n \/\/ down this handle when its done with it. If we gave out the orignal,\n \/\/ shutting it would prevent any further output.\n \/\/\n HANDLE stdInOrg = ::GetStdHandle(STD_INPUT_HANDLE);\n if (stdInOrg == INVALID_HANDLE_VALUE) {\n XMLCh stdinStr[] = {chLatin_s, chLatin_t, chLatin_d, chLatin_i, chLatin_n, chNull};\n ThrowXMLwithMemMgr1(XMLPlatformUtilsException, XMLExcepts::File_CouldNotOpenFile, stdinStr, manager);\n }\n\n HANDLE retHandle;\n if (!::DuplicateHandle\n (\n ::GetCurrentProcess()\n , stdInOrg\n , ::GetCurrentProcess()\n , &retHandle\n , 0\n , FALSE\n , DUPLICATE_SAME_ACCESS))\n {\n ThrowXMLwithMemMgr(XMLPlatformUtilsException, XMLExcepts::File_CouldNotDupHandle, manager);\n }\n return retHandle;\n}\n\n\nvoid\nWindowsFileMgr::close(FileHandle f, MemoryManager* const manager)\n{\n if (!f)\n\t\tThrowXMLwithMemMgr(XMLPlatformUtilsException, XMLExcepts::CPtr_PointerIsZero, manager);\n\n if (!::CloseHandle(f))\n ThrowXMLwithMemMgr(XMLPlatformUtilsException, XMLExcepts::File_CouldNotCloseFile, manager);\n}\n\n\nvoid\nWindowsFileMgr::reset(FileHandle f, MemoryManager* const manager)\n{\n if (!f)\n\t\tThrowXMLwithMemMgr(XMLPlatformUtilsException, XMLExcepts::CPtr_PointerIsZero, manager);\n\n \/\/ Seek to the start of the file\n if (::SetFilePointer(f, 0, 0, FILE_BEGIN) == 0xFFFFFFFF)\n ThrowXMLwithMemMgr(XMLPlatformUtilsException, XMLExcepts::File_CouldNotResetFile, manager);\n}\n\n\nXMLFilePos\nWindowsFileMgr::curPos(FileHandle f, MemoryManager* const manager)\n{\n if (!f)\n\t\tThrowXMLwithMemMgr(XMLPlatformUtilsException, XMLExcepts::CPtr_PointerIsZero, manager);\n\t\t \n \/\/ Get the current position\n const unsigned int curPos = ::SetFilePointer(f, 0, 0, FILE_CURRENT);\n if (curPos == 0xFFFFFFFF)\n ThrowXMLwithMemMgr(XMLPlatformUtilsException, XMLExcepts::File_CouldNotGetCurPos, manager);\n\n return curPos;\n}\n\n\nXMLFilePos\nWindowsFileMgr::size(FileHandle f, MemoryManager* const manager)\n{\n if (!f)\n\t\tThrowXMLwithMemMgr(XMLPlatformUtilsException, XMLExcepts::CPtr_PointerIsZero, manager);\n\t\n DWORD high;\n DWORD low=GetFileSize(f, &high);\n if(low==INVALID_FILE_SIZE)\n \/\/ TODO: find a better exception\n\t\tThrowXMLwithMemMgr(XMLPlatformUtilsException, XMLExcepts::File_CouldNotGetCurPos, manager);\n\n return low;\n}\n\n\nXMLSize_t\nWindowsFileMgr::read(FileHandle f, XMLSize_t byteCount, XMLByte* buffer, MemoryManager* const manager)\n{\n if (!f || !buffer)\n\t\tThrowXMLwithMemMgr(XMLPlatformUtilsException, XMLExcepts::CPtr_PointerIsZero, manager);\n\t\t\n unsigned long bytesRead = 0;\n if (!::ReadFile(f, buffer, byteCount, &bytesRead, 0))\n {\n \/\/\n \/\/ Check specially for a broken pipe error. If we get this, it just\n \/\/ means no more data from the pipe, so return zero.\n \/\/\n if (::GetLastError() != ERROR_BROKEN_PIPE)\n ThrowXMLwithMemMgr(XMLPlatformUtilsException, XMLExcepts::File_CouldNotReadFromFile, manager);\n }\n return (unsigned int)bytesRead;\n}\n\n\nvoid\nWindowsFileMgr::write(FileHandle f, XMLSize_t byteCount, const XMLByte* buffer, MemoryManager* const manager)\n{\n if (!f || !buffer)\n\t\tThrowXMLwithMemMgr(XMLPlatformUtilsException, XMLExcepts::CPtr_PointerIsZero, manager);\n\n const XMLByte* tmpFlush = buffer;\n\n while (true)\n {\n unsigned long bytesWritten = 0;\n if (!::WriteFile(f, tmpFlush, byteCount, &bytesWritten, 0))\n ThrowXMLwithMemMgr(XMLPlatformUtilsException, XMLExcepts::File_CouldNotWriteToFile, manager);\n\n if (bytesWritten < byteCount) \/\/incomplete write\n {\n tmpFlush+=bytesWritten;\n byteCount-=bytesWritten;\n }\n else\n return;\n }\n}\n\n\nXMLCh*\nWindowsFileMgr::getFullPath(const XMLCh* const srcPath, MemoryManager* const manager)\n{\n \/\/\n \/\/ If we are on NT, then use wide character APIs, else use ASCII APIs.\n \/\/ We have to do it manually since we are only built in ASCII mode from\n \/\/ the standpoint of the APIs.\n \/\/\n if (_onNT)\n {\n \/\/ Use a local buffer that is big enough for the largest legal path\n const unsigned int bufSize = 1024;\n XMLCh tmpPath[bufSize + 1];\n\n XMLCh* namePart = 0;\n if (!::GetFullPathNameW((LPCWSTR)srcPath, bufSize, (LPWSTR)tmpPath, (LPWSTR*)&namePart))\n return 0;\n\n \/\/ Return a copy of the path\n return XMLString::replicate(tmpPath, manager);\n }\n else\n {\n \/\/ Transcode the incoming string\n char* tmpSrcPath = XMLString::transcode(srcPath, manager);\n ArrayJanitor<char> janSrcPath(tmpSrcPath, manager);\n\n \/\/ Use a local buffer that is big enough for the largest legal path\n const unsigned int bufSize = 511;\n char tmpPath[511 + 1];\n\n char* namePart = 0;\n if (!::GetFullPathNameA(tmpSrcPath, bufSize, tmpPath, &namePart))\n return 0;\n\n \/\/ Return a transcoded copy of the path\n return XMLString::transcode(tmpPath, manager);\n }\n}\n\n\nXMLCh*\nWindowsFileMgr::getCurrentDirectory(MemoryManager* const manager)\n{\n \/\/\n \/\/ If we are on NT, then use wide character APIs, else use ASCII APIs.\n \/\/ We have to do it manually since we are only built in ASCII mode from\n \/\/ the standpoint of the APIs.\n \/\/\n if (_onNT)\n {\n \/\/ Use a local buffer that is big enough for the largest legal path\n const unsigned int bufSize = 1024;\n XMLCh tmpPath[bufSize + 1];\n\n if (!::GetCurrentDirectoryW(bufSize, (LPWSTR)tmpPath))\n return 0;\n\n \/\/ Return a copy of the path\n return XMLString::replicate(tmpPath, manager);\n }\n else\n {\n \/\/ Use a local buffer that is big enough for the largest legal path\n const unsigned int bufSize = 511;\n char tmpPath[511 + 1];\n\n if (!::GetCurrentDirectoryA(bufSize, tmpPath))\n return 0;\n\n \/\/ Return a transcoded copy of the path\n return XMLString::transcode(tmpPath, manager);\n }\n}\n\n\nbool\nWindowsFileMgr::isRelative(const XMLCh* const toCheck, MemoryManager* const manager)\n{\n \/\/ Check for pathological case of empty path\n if (!toCheck || !toCheck[0])\n return false;\n\n \/\/\n \/\/ If its starts with a drive, then it cannot be relative. Note that\n \/\/ we checked the drive not being empty above, so worst case its one\n \/\/ char long and the check of the 1st char will fail because its really\n \/\/ a null character.\n \/\/\n if (toCheck[1] == chColon)\n {\n if (((toCheck[0] >= chLatin_A) && (toCheck[0] <= chLatin_Z))\n || ((toCheck[0] >= chLatin_a) && (toCheck[0] <= chLatin_z)))\n {\n return false;\n }\n }\n\n \/\/\n \/\/ If it starts with a double slash, then it cannot be relative since\n \/\/ it's a remote file.\n \/\/\n if (isBackSlash(toCheck[0]) && isBackSlash(toCheck[1]))\n return false;\n\n \/\/ Else assume its a relative path\n return true;\n}\n\n\nXERCES_CPP_NAMESPACE_END\n\n<commit_msg>Previous versions of xercesc would treat \\directory\\file.xml as a relative path. Fix for compatiblity.<commit_after>\/*\n * Copyright 1999-2000,2004-2005 The Apache Software Foundation.\n * \n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * \n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n\/*\n * $Id$\n *\/\n\n#include <windows.h>\n\n#include <xercesc\/util\/FileManagers\/WindowsFileMgr.hpp>\n#include <xercesc\/util\/Janitor.hpp>\n#include <xercesc\/util\/XMLString.hpp>\n#include <xercesc\/util\/XMLUniDefs.hpp>\n\n\nXERCES_CPP_NAMESPACE_BEGIN\n\nstatic bool isBackSlash(XMLCh c) {\n return c == chBackSlash ||\n c == chYenSign ||\n c == chWonSign;\n}\n\nWindowsFileMgr::WindowsFileMgr()\n{\n \/\/ Figure out if we are on NT and save that flag for later use\n OSVERSIONINFO OSVer;\n OSVer.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);\n ::GetVersionEx(&OSVer);\n _onNT = (OSVer.dwPlatformId == VER_PLATFORM_WIN32_NT);\n}\n\n\nWindowsFileMgr::~WindowsFileMgr()\n{\n}\n\n\nFileHandle\nWindowsFileMgr::open(const XMLCh* fileName, bool toWrite, MemoryManager* const manager)\n{\n \/\/ Watch for obvious wierdness\n if (!fileName)\n return 0;\n\n \/\/\n \/\/ We have to play a little trick here. If its \/x:.....\n \/\/ style fully qualified path, we have to toss the leading \/\n \/\/ character.\n \/\/\n const XMLCh* nameToOpen = fileName;\n if (*fileName == chForwardSlash)\n {\n if (XMLString::stringLen(fileName) > 3)\n {\n if (*(fileName + 2) == chColon)\n {\n const XMLCh chDrive = *(fileName + 1);\n if (((chDrive >= chLatin_A) && (chDrive <= chLatin_Z))\n || ((chDrive >= chLatin_a) && (chDrive <= chLatin_z)))\n {\n nameToOpen = fileName + 1;\n }\n }\n\n \/\/ Similarly for UNC paths\n if ( *(fileName + 1) == *(fileName + 2) &&\n (*(fileName + 1) == chForwardSlash ||\n *(fileName + 1) == chBackSlash) )\n {\n nameToOpen = fileName + 1;\n }\n }\n }\n\n \/\/ Ok, this might look stupid but its a semi-expedient way to deal\n \/\/ with a thorny problem. Shift-JIS and some other Asian encodings\n \/\/ are fundamentally broken and map both the backslash and the Yen\n \/\/ sign to the same code point. Transcoders have to pick one or the\n \/\/ other to map '\\' to Unicode and tend to choose the Yen sign.\n \/\/\n \/\/ Unicode Yen or Won signs as directory separators will fail.\n \/\/\n \/\/ So, we will check this path name for Yen or won signs and, if they are\n \/\/ there, we'll replace them with slashes.\n \/\/\n \/\/ A further twist: we replace Yen and Won with forward slashes rather\n \/\/ than back slashes. Either form of slash will work as a directory\n \/\/ separator. On Win 95 and 98, though, Unicode back-slashes may\n \/\/ fail to transode back to 8-bit 0x5C with some Unicode converters\n \/\/ to some of the problematic code pages. Forward slashes always\n \/\/ transcode correctly back to 8 bit char * form.\n \/\/\n XMLCh *tmpUName = 0;\n\n const XMLCh* srcPtr = nameToOpen;\n while (*srcPtr)\n {\n if (*srcPtr == chYenSign ||\n *srcPtr == chWonSign)\n break;\n srcPtr++;\n }\n\n \/\/\n \/\/ If we found a yen, then we have to create a temp file name. Else\n \/\/ go with the file name as is and save the overhead.\n \/\/\n if (*srcPtr)\n {\n tmpUName = XMLString::replicate(nameToOpen, manager);\n\n XMLCh* tmpPtr = tmpUName;\n while (*tmpPtr)\n {\n if (*tmpPtr == chYenSign ||\n *tmpPtr == chWonSign)\n *tmpPtr = chForwardSlash;\n tmpPtr++;\n }\n nameToOpen = tmpUName;\n }\n FileHandle retVal = 0;\n if (_onNT)\n {\n retVal = ::CreateFileW\n (\n (LPCWSTR) nameToOpen\n , toWrite?GENERIC_WRITE:GENERIC_READ\n , FILE_SHARE_READ\n , 0\n , toWrite?CREATE_ALWAYS:OPEN_EXISTING\n , toWrite?FILE_ATTRIBUTE_NORMAL:FILE_FLAG_SEQUENTIAL_SCAN\n , 0\n );\n }\n else\n {\n \/\/\n \/\/ We are Win 95 \/ 98. Take the Unicode file name back to (char *)\n \/\/ so that we can open it.\n \/\/\n char* tmpName = XMLString::transcode(nameToOpen, manager);\n retVal = ::CreateFileA\n (\n tmpName\n , toWrite?GENERIC_WRITE:GENERIC_READ\n , FILE_SHARE_READ\n , 0\n , toWrite?CREATE_ALWAYS:OPEN_EXISTING\n , toWrite?FILE_ATTRIBUTE_NORMAL:FILE_FLAG_SEQUENTIAL_SCAN\n , 0\n );\n manager->deallocate(tmpName);\/\/delete [] tmpName;\n }\n\n if (tmpUName)\n manager->deallocate(tmpUName);\/\/delete [] tmpUName;\n\n if (retVal == INVALID_HANDLE_VALUE)\n return 0;\n\n return retVal;\n}\n\n\nFileHandle\nWindowsFileMgr::open(const char* path, bool toWrite, MemoryManager* const manager)\n{\n FileHandle retVal = ::CreateFileA\n (\n path\n , toWrite?GENERIC_WRITE:GENERIC_READ\n , FILE_SHARE_READ\n , 0\n , toWrite?OPEN_ALWAYS:OPEN_EXISTING\n , toWrite?FILE_ATTRIBUTE_NORMAL:FILE_FLAG_SEQUENTIAL_SCAN\n , 0\n );\n\n if (retVal == INVALID_HANDLE_VALUE)\n return 0;\n\n return retVal;\n}\n\n\nFileHandle\nWindowsFileMgr::openStdIn(MemoryManager* const manager)\n{\n \/\/\n \/\/ Get the standard input handle. Duplicate it and return that copy\n \/\/ since the outside world cannot tell the difference and will shut\n \/\/ down this handle when its done with it. If we gave out the orignal,\n \/\/ shutting it would prevent any further output.\n \/\/\n HANDLE stdInOrg = ::GetStdHandle(STD_INPUT_HANDLE);\n if (stdInOrg == INVALID_HANDLE_VALUE) {\n XMLCh stdinStr[] = {chLatin_s, chLatin_t, chLatin_d, chLatin_i, chLatin_n, chNull};\n ThrowXMLwithMemMgr1(XMLPlatformUtilsException, XMLExcepts::File_CouldNotOpenFile, stdinStr, manager);\n }\n\n HANDLE retHandle;\n if (!::DuplicateHandle\n (\n ::GetCurrentProcess()\n , stdInOrg\n , ::GetCurrentProcess()\n , &retHandle\n , 0\n , FALSE\n , DUPLICATE_SAME_ACCESS))\n {\n ThrowXMLwithMemMgr(XMLPlatformUtilsException, XMLExcepts::File_CouldNotDupHandle, manager);\n }\n return retHandle;\n}\n\n\nvoid\nWindowsFileMgr::close(FileHandle f, MemoryManager* const manager)\n{\n if (!f)\n\t\tThrowXMLwithMemMgr(XMLPlatformUtilsException, XMLExcepts::CPtr_PointerIsZero, manager);\n\n if (!::CloseHandle(f))\n ThrowXMLwithMemMgr(XMLPlatformUtilsException, XMLExcepts::File_CouldNotCloseFile, manager);\n}\n\n\nvoid\nWindowsFileMgr::reset(FileHandle f, MemoryManager* const manager)\n{\n if (!f)\n\t\tThrowXMLwithMemMgr(XMLPlatformUtilsException, XMLExcepts::CPtr_PointerIsZero, manager);\n\n \/\/ Seek to the start of the file\n if (::SetFilePointer(f, 0, 0, FILE_BEGIN) == 0xFFFFFFFF)\n ThrowXMLwithMemMgr(XMLPlatformUtilsException, XMLExcepts::File_CouldNotResetFile, manager);\n}\n\n\nXMLFilePos\nWindowsFileMgr::curPos(FileHandle f, MemoryManager* const manager)\n{\n if (!f)\n\t\tThrowXMLwithMemMgr(XMLPlatformUtilsException, XMLExcepts::CPtr_PointerIsZero, manager);\n\t\t \n \/\/ Get the current position\n const unsigned int curPos = ::SetFilePointer(f, 0, 0, FILE_CURRENT);\n if (curPos == 0xFFFFFFFF)\n ThrowXMLwithMemMgr(XMLPlatformUtilsException, XMLExcepts::File_CouldNotGetCurPos, manager);\n\n return curPos;\n}\n\n\nXMLFilePos\nWindowsFileMgr::size(FileHandle f, MemoryManager* const manager)\n{\n if (!f)\n\t\tThrowXMLwithMemMgr(XMLPlatformUtilsException, XMLExcepts::CPtr_PointerIsZero, manager);\n\t\n DWORD high;\n DWORD low=GetFileSize(f, &high);\n if(low==INVALID_FILE_SIZE)\n \/\/ TODO: find a better exception\n\t\tThrowXMLwithMemMgr(XMLPlatformUtilsException, XMLExcepts::File_CouldNotGetCurPos, manager);\n\n return low;\n}\n\n\nXMLSize_t\nWindowsFileMgr::read(FileHandle f, XMLSize_t byteCount, XMLByte* buffer, MemoryManager* const manager)\n{\n if (!f || !buffer)\n\t\tThrowXMLwithMemMgr(XMLPlatformUtilsException, XMLExcepts::CPtr_PointerIsZero, manager);\n\t\t\n unsigned long bytesRead = 0;\n if (!::ReadFile(f, buffer, byteCount, &bytesRead, 0))\n {\n \/\/\n \/\/ Check specially for a broken pipe error. If we get this, it just\n \/\/ means no more data from the pipe, so return zero.\n \/\/\n if (::GetLastError() != ERROR_BROKEN_PIPE)\n ThrowXMLwithMemMgr(XMLPlatformUtilsException, XMLExcepts::File_CouldNotReadFromFile, manager);\n }\n return (unsigned int)bytesRead;\n}\n\n\nvoid\nWindowsFileMgr::write(FileHandle f, XMLSize_t byteCount, const XMLByte* buffer, MemoryManager* const manager)\n{\n if (!f || !buffer)\n\t\tThrowXMLwithMemMgr(XMLPlatformUtilsException, XMLExcepts::CPtr_PointerIsZero, manager);\n\n const XMLByte* tmpFlush = buffer;\n\n while (true)\n {\n unsigned long bytesWritten = 0;\n if (!::WriteFile(f, tmpFlush, byteCount, &bytesWritten, 0))\n ThrowXMLwithMemMgr(XMLPlatformUtilsException, XMLExcepts::File_CouldNotWriteToFile, manager);\n\n if (bytesWritten < byteCount) \/\/incomplete write\n {\n tmpFlush+=bytesWritten;\n byteCount-=bytesWritten;\n }\n else\n return;\n }\n}\n\n\nXMLCh*\nWindowsFileMgr::getFullPath(const XMLCh* const srcPath, MemoryManager* const manager)\n{\n \/\/\n \/\/ If we are on NT, then use wide character APIs, else use ASCII APIs.\n \/\/ We have to do it manually since we are only built in ASCII mode from\n \/\/ the standpoint of the APIs.\n \/\/\n if (_onNT)\n {\n \/\/ Use a local buffer that is big enough for the largest legal path\n const unsigned int bufSize = 1024;\n XMLCh tmpPath[bufSize + 1];\n\n XMLCh* namePart = 0;\n if (!::GetFullPathNameW((LPCWSTR)srcPath, bufSize, (LPWSTR)tmpPath, (LPWSTR*)&namePart))\n return 0;\n\n \/\/ Return a copy of the path\n return XMLString::replicate(tmpPath, manager);\n }\n else\n {\n \/\/ Transcode the incoming string\n char* tmpSrcPath = XMLString::transcode(srcPath, manager);\n ArrayJanitor<char> janSrcPath(tmpSrcPath, manager);\n\n \/\/ Use a local buffer that is big enough for the largest legal path\n const unsigned int bufSize = 511;\n char tmpPath[511 + 1];\n\n char* namePart = 0;\n if (!::GetFullPathNameA(tmpSrcPath, bufSize, tmpPath, &namePart))\n return 0;\n\n \/\/ Return a transcoded copy of the path\n return XMLString::transcode(tmpPath, manager);\n }\n}\n\n\nXMLCh*\nWindowsFileMgr::getCurrentDirectory(MemoryManager* const manager)\n{\n \/\/\n \/\/ If we are on NT, then use wide character APIs, else use ASCII APIs.\n \/\/ We have to do it manually since we are only built in ASCII mode from\n \/\/ the standpoint of the APIs.\n \/\/\n if (_onNT)\n {\n \/\/ Use a local buffer that is big enough for the largest legal path\n const unsigned int bufSize = 1024;\n XMLCh tmpPath[bufSize + 1];\n\n if (!::GetCurrentDirectoryW(bufSize, (LPWSTR)tmpPath))\n return 0;\n\n \/\/ Return a copy of the path\n return XMLString::replicate(tmpPath, manager);\n }\n else\n {\n \/\/ Use a local buffer that is big enough for the largest legal path\n const unsigned int bufSize = 511;\n char tmpPath[511 + 1];\n\n if (!::GetCurrentDirectoryA(bufSize, tmpPath))\n return 0;\n\n \/\/ Return a transcoded copy of the path\n return XMLString::transcode(tmpPath, manager);\n }\n}\n\n\nbool\nWindowsFileMgr::isRelative(const XMLCh* const toCheck, MemoryManager* const manager)\n{\n \/\/ Check for pathological case of empty path\n if (!toCheck || !toCheck[0])\n return false;\n\n \/\/\n \/\/ If its starts with a drive, then it cannot be relative. Note that\n \/\/ we checked the drive not being empty above, so worst case its one\n \/\/ char long and the check of the 1st char will fail because its really\n \/\/ a null character.\n \/\/\n if (toCheck[1] == chColon)\n {\n if (((toCheck[0] >= chLatin_A) && (toCheck[0] <= chLatin_Z))\n || ((toCheck[0] >= chLatin_a) && (toCheck[0] <= chLatin_z)))\n {\n return false;\n }\n }\n\n \/\/\n \/\/ If it starts with a double slash, then it cannot be relative since\n \/\/ it's a remote file.\n \/\/\n if (isBackSlash(toCheck[0]))\n return false;\n\n \/\/ Else assume its a relative path\n return true;\n}\n\n\nXERCES_CPP_NAMESPACE_END\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n * The Apache Software License, Version 1.1\n *\n * Copyright (c) 1999-2000 The Apache Software Foundation. All rights\n * reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n *\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in\n * the documentation and\/or other materials provided with the\n * distribution.\n *\n * 3. The end-user documentation included with the redistribution,\n * if any, must include the following acknowledgment:\n * \"This product includes software developed by the\n * Apache Software Foundation (http:\/\/www.apache.org\/).\"\n * Alternately, this acknowledgment may appear in the software itself,\n * if and wherever such third-party acknowledgments normally appear.\n *\n * 4. The names \"Xerces\" and \"Apache Software Foundation\" must\n * not be used to endorse or promote products derived from this\n * software without prior written permission. For written\n * permission, please contact apache\\@apache.org.\n *\n * 5. Products derived from this software may not be called \"Apache\",\n * nor may \"Apache\" appear in their name, without prior written\n * permission of the Apache Software Foundation.\n *\n * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED\n * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR\n * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF\n * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT\n * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n * ====================================================================\n *\n * This software consists of voluntary contributions made by many\n * individuals on behalf of the Apache Software Foundation, and was\n * originally based on software copyright (c) 1999, International\n * Business Machines, Inc., http:\/\/www.ibm.com . For more information\n * on the Apache Software Foundation, please see\n * <http:\/\/www.apache.org\/>.\n *\/\n\n\/*\n * $Log$\n * Revision 1.12 2003\/02\/17 19:56:03 peiyongz\n * Re-prioritize search order for error message files.\n *\n * Revision 1.11 2002\/12\/12 16:53:25 peiyongz\n * Message file name changed.\n *\n * Revision 1.10 2002\/12\/06 16:29:17 peiyongz\n * $XERCESCROOT\/msg created as home directory for message files, and\n * set default locale.\n *\n * Revision 1.9 2002\/12\/04 18:11:23 peiyongz\n * use $XERCESCROOT to search for icu resource bundle if XERCESC_NLS_HOME\n * undefined\n *\n * Revision 1.8 2002\/11\/20 20:28:17 peiyongz\n * fix to warning C4018: '>' : signed\/unsigned mismatch\n *\n * Revision 1.7 2002\/11\/12 17:27:49 tng\n * DOM Message: add new domain for DOM Messages.\n *\n * Revision 1.6 2002\/11\/04 22:24:43 peiyongz\n * Locale setting for message loader\n *\n * Revision 1.5 2002\/11\/04 15:10:40 tng\n * C++ Namespace Support.\n *\n * Revision 1.4 2002\/10\/10 21:07:55 peiyongz\n * load resource files using environement vars and base name\n *\n * Revision 1.3 2002\/10\/02 17:08:50 peiyongz\n * XMLString::equals() to replace XMLString::compareString()\n *\n * Revision 1.2 2002\/09\/30 22:20:40 peiyongz\n * Build with ICU MsgLoader\n *\n * Revision 1.1.1.1 2002\/02\/01 22:22:19 peiyongz\n * sane_include\n *\n * Revision 1.7 2002\/01\/21 14:52:25 tng\n * [Bug 5847] ICUMsgLoader can't be compiled with gcc 3.0.3 and ICU2. And also fix the memory leak introduced by Bug 2730 fix.\n *\n * Revision 1.6 2001\/11\/01 23:39:18 jasons\n * 2001-11-01 Jason E. Stewart <jason@openinformatics.com>\n *\n * \t* src\/util\/MsgLoaders\/ICU\/ICUMsgLoader.hpp (Repository):\n * \t* src\/util\/MsgLoaders\/ICU\/ICUMsgLoader.cpp (Repository):\n * \tUpdated to compile with ICU-1.8.1\n *\n * Revision 1.5 2000\/03\/02 19:55:14 roddey\n * This checkin includes many changes done while waiting for the\n * 1.1.0 code to be finished. I can't list them all here, but a list is\n * available elsewhere.\n *\n * Revision 1.4 2000\/02\/06 07:48:21 rahulj\n * Year 2K copyright swat.\n *\n * Revision 1.3 2000\/01\/19 00:58:38 roddey\n * Update to support new ICU 1.4 release.\n *\n * Revision 1.2 1999\/11\/19 21:24:03 aruna1\n * incorporated ICU 1.3.1 related changes int he file\n *\n * Revision 1.1.1.1 1999\/11\/09 01:07:23 twl\n * Initial checkin\n *\n * Revision 1.4 1999\/11\/08 20:45:26 rahul\n * Swat for adding in Product name and CVS comment log variable.\n *\n *\/\n\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ Includes\n\/\/ ---------------------------------------------------------------------------\n#include <xercesc\/util\/XercesDefs.hpp>\n#include <xercesc\/util\/PlatformUtils.hpp>\n#include <xercesc\/util\/XMLMsgLoader.hpp>\n#include <xercesc\/util\/XMLString.hpp>\n#include <xercesc\/util\/XMLUniDefs.hpp>\n#include <xercesc\/util\/Janitor.hpp>\n#include \"ICUMsgLoader.hpp\"\n#include \"unicode\/uloc.h\"\n#include \"string.h\"\n#include <stdio.h>\n#include <stdlib.h>\n\nXERCES_CPP_NAMESPACE_BEGIN\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ Local static methods\n\/\/ ---------------------------------------------------------------------------\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ Public Constructors and Destructor\n\/\/ ---------------------------------------------------------------------------\nICUMsgLoader::ICUMsgLoader(const XMLCh* const msgDomain)\n:fLocaleBundle(0)\n,fDomainBundle(0)\n{\n \/***\n\t Validate msgDomain\n ***\/\n if (!XMLString::equals(msgDomain, XMLUni::fgXMLErrDomain) &&\n !XMLString::equals(msgDomain, XMLUni::fgExceptDomain) &&\n !XMLString::equals(msgDomain, XMLUni::fgXMLDOMMsgDomain) &&\n !XMLString::equals(msgDomain, XMLUni::fgValidityDomain) )\n {\n XMLPlatformUtils::panic(XMLPlatformUtils::Panic_UnknownMsgDomain);\n }\n\n \/***\n\tResolve domainName\n ***\/\n int index = XMLString::lastIndexOf(msgDomain, chForwardSlash);\n char* domainName = XMLString::transcode(&(msgDomain[index + 1]));\n ArrayJanitor<char> jan1(domainName);\n\n \/***\n Location resolution priority\n \n 1. XMLMsgLoader::getNLSHome(), set by user through\n XMLPlatformUtils::Initialize(), which provides user-specified\n location where the message loader shall retrieve error messages.\n\n 2. envrionment var: XERCESC_NLS_HOME\n\n 3. path $XERCESCROOT\/msg\n ***\/\n\n char locationBuf[1024];\n memset(locationBuf, 0, sizeof locationBuf);\n const char const *nlsHome = XMLMsgLoader::getNLSHome();\n\n if (nlsHome)\n {\n \tstrcpy(locationBuf, nlsHome);\n strcat(locationBuf, U_FILE_SEP_STRING);\n }\n else\n {\n nlsHome = getenv(\"XERCESC_NLS_HOME\");\n if (nlsHome)\n {\n strcpy(locationBuf, nlsHome);\n strcat(locationBuf, U_FILE_SEP_STRING);\n }\n else\n {\n nlsHome = getenv(\"XERCESCROOT\");\n if (nlsHome)\n {\n strcpy(locationBuf, nlsHome);\n strcat(locationBuf, U_FILE_SEP_STRING);\n strcat(locationBuf, \"msg\");\n strcat(locationBuf, U_FILE_SEP_STRING); \n }\n else\n {\n \/***\n leave it to ICU to decide where to search\n for the error message.\n ***\/\n }\n } \n }\n\n \/***\n\tOpen the locale-specific resource bundle\n ***\/\n strcat(locationBuf, \"XercesMessages\");\n UErrorCode err = U_ZERO_ERROR;\n uloc_setDefault(\"en_US\", &err); \/\/ in case user-specified locale unavailable\n err = U_ZERO_ERROR;\n fLocaleBundle = ures_open(locationBuf, XMLMsgLoader::getLocale(), &err);\n if (!U_SUCCESS(err) || fLocaleBundle == NULL)\n {\n XMLPlatformUtils::panic(XMLPlatformUtils::Panic_CantLoadMsgDomain);\n }\n\n \/***\n\tOpen the domain specific resource bundle within\n\tthe locale-specific resource bundle\n ***\/\n err = U_ZERO_ERROR;\n fDomainBundle = ures_getByKey(fLocaleBundle, domainName, NULL, &err);\n if (!U_SUCCESS(err) || fDomainBundle == NULL)\n {\n XMLPlatformUtils::panic(XMLPlatformUtils::Panic_CantLoadMsgDomain);\n }\n\n}\n\nICUMsgLoader::~ICUMsgLoader()\n{\n ures_close(fDomainBundle);\n ures_close(fLocaleBundle);\n}\n\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ Implementation of the virtual message loader API\n\/\/ ---------------------------------------------------------------------------\nbool ICUMsgLoader::loadMsg( const XMLMsgLoader::XMLMsgId msgToLoad\n , XMLCh* const toFill\n , const unsigned int maxChars)\n{\n UErrorCode err = U_ZERO_ERROR;\n int32_t strLen = 0;\n\n \/\/ Assuming array format\n const UChar *name = ures_getStringByIndex(fDomainBundle, (int32_t)msgToLoad-1, &strLen, &err);\n\n if (!U_SUCCESS(err) || (name == NULL))\n {\n return false;\n }\n\n int retStrLen = strLen > (int32_t)maxChars ? maxChars : strLen;\n\n if (sizeof(UChar)==sizeof(XMLCh))\n {\n XMLString::moveChars(toFill, (XMLCh*)name, retStrLen);\n toFill[retStrLen] = (XMLCh) 0;\n }\n else\n {\n XMLCh* retStr = toFill;\n const UChar *srcPtr = name;\n\n while (retStrLen--)\n *retStr++ = *srcPtr++;\n\n *retStr = 0;\n }\n\n return true;\n}\n\n\nbool ICUMsgLoader::loadMsg( const XMLMsgLoader::XMLMsgId msgToLoad\n , XMLCh* const toFill\n , const unsigned int maxChars\n , const XMLCh* const repText1\n , const XMLCh* const repText2\n , const XMLCh* const repText3\n , const XMLCh* const repText4)\n{\n \/\/ Call the other version to load up the message\n if (!loadMsg(msgToLoad, toFill, maxChars))\n return false;\n\n \/\/ And do the token replacement\n XMLString::replaceTokens(toFill, maxChars, repText1, repText2, repText3, repText4);\n return true;\n}\n\n\nbool ICUMsgLoader::loadMsg( const XMLMsgLoader::XMLMsgId msgToLoad\n , XMLCh* const toFill\n , const unsigned int maxChars\n , const char* const repText1\n , const char* const repText2\n , const char* const repText3\n , const char* const repText4)\n{\n \/\/\n \/\/ Transcode the provided parameters and call the other version,\n \/\/ which will do the replacement work.\n \/\/\n XMLCh* tmp1 = 0;\n XMLCh* tmp2 = 0;\n XMLCh* tmp3 = 0;\n XMLCh* tmp4 = 0;\n\n bool bRet = false;\n if (repText1)\n tmp1 = XMLString::transcode(repText1);\n if (repText2)\n tmp2 = XMLString::transcode(repText2);\n if (repText3)\n tmp3 = XMLString::transcode(repText3);\n if (repText4)\n tmp4 = XMLString::transcode(repText4);\n\n bRet = loadMsg(msgToLoad, toFill, maxChars, tmp1, tmp2, tmp3, tmp4);\n\n if (tmp1)\n delete [] tmp1;\n if (tmp2)\n delete [] tmp2;\n if (tmp3)\n delete [] tmp3;\n if (tmp4)\n delete [] tmp4;\n\n return bRet;\n}\n\nXERCES_CPP_NAMESPACE_END\n<commit_msg>Compilation error on Solaris.<commit_after>\/*\n * The Apache Software License, Version 1.1\n *\n * Copyright (c) 1999-2000 The Apache Software Foundation. All rights\n * reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n *\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in\n * the documentation and\/or other materials provided with the\n * distribution.\n *\n * 3. The end-user documentation included with the redistribution,\n * if any, must include the following acknowledgment:\n * \"This product includes software developed by the\n * Apache Software Foundation (http:\/\/www.apache.org\/).\"\n * Alternately, this acknowledgment may appear in the software itself,\n * if and wherever such third-party acknowledgments normally appear.\n *\n * 4. The names \"Xerces\" and \"Apache Software Foundation\" must\n * not be used to endorse or promote products derived from this\n * software without prior written permission. For written\n * permission, please contact apache\\@apache.org.\n *\n * 5. Products derived from this software may not be called \"Apache\",\n * nor may \"Apache\" appear in their name, without prior written\n * permission of the Apache Software Foundation.\n *\n * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED\n * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR\n * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF\n * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT\n * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n * ====================================================================\n *\n * This software consists of voluntary contributions made by many\n * individuals on behalf of the Apache Software Foundation, and was\n * originally based on software copyright (c) 1999, International\n * Business Machines, Inc., http:\/\/www.ibm.com . For more information\n * on the Apache Software Foundation, please see\n * <http:\/\/www.apache.org\/>.\n *\/\n\n\/*\n * $Log$\n * Revision 1.13 2003\/02\/19 15:37:57 peiyongz\n * Compilation error on Solaris.\n *\n * Revision 1.12 2003\/02\/17 19:56:03 peiyongz\n * Re-prioritize search order for error message files.\n *\n * Revision 1.11 2002\/12\/12 16:53:25 peiyongz\n * Message file name changed.\n *\n * Revision 1.10 2002\/12\/06 16:29:17 peiyongz\n * $XERCESCROOT\/msg created as home directory for message files, and\n * set default locale.\n *\n * Revision 1.9 2002\/12\/04 18:11:23 peiyongz\n * use $XERCESCROOT to search for icu resource bundle if XERCESC_NLS_HOME\n * undefined\n *\n * Revision 1.8 2002\/11\/20 20:28:17 peiyongz\n * fix to warning C4018: '>' : signed\/unsigned mismatch\n *\n * Revision 1.7 2002\/11\/12 17:27:49 tng\n * DOM Message: add new domain for DOM Messages.\n *\n * Revision 1.6 2002\/11\/04 22:24:43 peiyongz\n * Locale setting for message loader\n *\n * Revision 1.5 2002\/11\/04 15:10:40 tng\n * C++ Namespace Support.\n *\n * Revision 1.4 2002\/10\/10 21:07:55 peiyongz\n * load resource files using environement vars and base name\n *\n * Revision 1.3 2002\/10\/02 17:08:50 peiyongz\n * XMLString::equals() to replace XMLString::compareString()\n *\n * Revision 1.2 2002\/09\/30 22:20:40 peiyongz\n * Build with ICU MsgLoader\n *\n * Revision 1.1.1.1 2002\/02\/01 22:22:19 peiyongz\n * sane_include\n *\n * Revision 1.7 2002\/01\/21 14:52:25 tng\n * [Bug 5847] ICUMsgLoader can't be compiled with gcc 3.0.3 and ICU2. And also fix the memory leak introduced by Bug 2730 fix.\n *\n * Revision 1.6 2001\/11\/01 23:39:18 jasons\n * 2001-11-01 Jason E. Stewart <jason@openinformatics.com>\n *\n * \t* src\/util\/MsgLoaders\/ICU\/ICUMsgLoader.hpp (Repository):\n * \t* src\/util\/MsgLoaders\/ICU\/ICUMsgLoader.cpp (Repository):\n * \tUpdated to compile with ICU-1.8.1\n *\n * Revision 1.5 2000\/03\/02 19:55:14 roddey\n * This checkin includes many changes done while waiting for the\n * 1.1.0 code to be finished. I can't list them all here, but a list is\n * available elsewhere.\n *\n * Revision 1.4 2000\/02\/06 07:48:21 rahulj\n * Year 2K copyright swat.\n *\n * Revision 1.3 2000\/01\/19 00:58:38 roddey\n * Update to support new ICU 1.4 release.\n *\n * Revision 1.2 1999\/11\/19 21:24:03 aruna1\n * incorporated ICU 1.3.1 related changes int he file\n *\n * Revision 1.1.1.1 1999\/11\/09 01:07:23 twl\n * Initial checkin\n *\n * Revision 1.4 1999\/11\/08 20:45:26 rahul\n * Swat for adding in Product name and CVS comment log variable.\n *\n *\/\n\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ Includes\n\/\/ ---------------------------------------------------------------------------\n#include <xercesc\/util\/XercesDefs.hpp>\n#include <xercesc\/util\/PlatformUtils.hpp>\n#include <xercesc\/util\/XMLMsgLoader.hpp>\n#include <xercesc\/util\/XMLString.hpp>\n#include <xercesc\/util\/XMLUniDefs.hpp>\n#include <xercesc\/util\/Janitor.hpp>\n#include \"ICUMsgLoader.hpp\"\n#include \"unicode\/uloc.h\"\n#include \"string.h\"\n#include <stdio.h>\n#include <stdlib.h>\n\nXERCES_CPP_NAMESPACE_BEGIN\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ Local static methods\n\/\/ ---------------------------------------------------------------------------\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ Public Constructors and Destructor\n\/\/ ---------------------------------------------------------------------------\nICUMsgLoader::ICUMsgLoader(const XMLCh* const msgDomain)\n:fLocaleBundle(0)\n,fDomainBundle(0)\n{\n \/***\n\t Validate msgDomain\n ***\/\n if (!XMLString::equals(msgDomain, XMLUni::fgXMLErrDomain) &&\n !XMLString::equals(msgDomain, XMLUni::fgExceptDomain) &&\n !XMLString::equals(msgDomain, XMLUni::fgXMLDOMMsgDomain) &&\n !XMLString::equals(msgDomain, XMLUni::fgValidityDomain) )\n {\n XMLPlatformUtils::panic(XMLPlatformUtils::Panic_UnknownMsgDomain);\n }\n\n \/***\n\tResolve domainName\n ***\/\n int index = XMLString::lastIndexOf(msgDomain, chForwardSlash);\n char* domainName = XMLString::transcode(&(msgDomain[index + 1]));\n ArrayJanitor<char> jan1(domainName);\n\n \/***\n Location resolution priority\n \n 1. XMLMsgLoader::getNLSHome(), set by user through\n XMLPlatformUtils::Initialize(), which provides user-specified\n location where the message loader shall retrieve error messages.\n\n 2. envrionment var: XERCESC_NLS_HOME\n\n 3. path $XERCESCROOT\/msg\n ***\/\n\n char locationBuf[1024];\n memset(locationBuf, 0, sizeof locationBuf);\n const char *nlsHome = XMLMsgLoader::getNLSHome();\n\n if (nlsHome)\n {\n \tstrcpy(locationBuf, nlsHome);\n strcat(locationBuf, U_FILE_SEP_STRING);\n }\n else\n {\n nlsHome = getenv(\"XERCESC_NLS_HOME\");\n if (nlsHome)\n {\n strcpy(locationBuf, nlsHome);\n strcat(locationBuf, U_FILE_SEP_STRING);\n }\n else\n {\n nlsHome = getenv(\"XERCESCROOT\");\n if (nlsHome)\n {\n strcpy(locationBuf, nlsHome);\n strcat(locationBuf, U_FILE_SEP_STRING);\n strcat(locationBuf, \"msg\");\n strcat(locationBuf, U_FILE_SEP_STRING); \n }\n else\n {\n \/***\n leave it to ICU to decide where to search\n for the error message.\n ***\/\n }\n } \n }\n\n \/***\n\tOpen the locale-specific resource bundle\n ***\/\n strcat(locationBuf, \"XercesMessages\");\n UErrorCode err = U_ZERO_ERROR;\n uloc_setDefault(\"en_US\", &err); \/\/ in case user-specified locale unavailable\n err = U_ZERO_ERROR;\n fLocaleBundle = ures_open(locationBuf, XMLMsgLoader::getLocale(), &err);\n if (!U_SUCCESS(err) || fLocaleBundle == NULL)\n {\n XMLPlatformUtils::panic(XMLPlatformUtils::Panic_CantLoadMsgDomain);\n }\n\n \/***\n\tOpen the domain specific resource bundle within\n\tthe locale-specific resource bundle\n ***\/\n err = U_ZERO_ERROR;\n fDomainBundle = ures_getByKey(fLocaleBundle, domainName, NULL, &err);\n if (!U_SUCCESS(err) || fDomainBundle == NULL)\n {\n XMLPlatformUtils::panic(XMLPlatformUtils::Panic_CantLoadMsgDomain);\n }\n\n}\n\nICUMsgLoader::~ICUMsgLoader()\n{\n ures_close(fDomainBundle);\n ures_close(fLocaleBundle);\n}\n\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ Implementation of the virtual message loader API\n\/\/ ---------------------------------------------------------------------------\nbool ICUMsgLoader::loadMsg( const XMLMsgLoader::XMLMsgId msgToLoad\n , XMLCh* const toFill\n , const unsigned int maxChars)\n{\n UErrorCode err = U_ZERO_ERROR;\n int32_t strLen = 0;\n\n \/\/ Assuming array format\n const UChar *name = ures_getStringByIndex(fDomainBundle, (int32_t)msgToLoad-1, &strLen, &err);\n\n if (!U_SUCCESS(err) || (name == NULL))\n {\n return false;\n }\n\n int retStrLen = strLen > (int32_t)maxChars ? maxChars : strLen;\n\n if (sizeof(UChar)==sizeof(XMLCh))\n {\n XMLString::moveChars(toFill, (XMLCh*)name, retStrLen);\n toFill[retStrLen] = (XMLCh) 0;\n }\n else\n {\n XMLCh* retStr = toFill;\n const UChar *srcPtr = name;\n\n while (retStrLen--)\n *retStr++ = *srcPtr++;\n\n *retStr = 0;\n }\n\n return true;\n}\n\n\nbool ICUMsgLoader::loadMsg( const XMLMsgLoader::XMLMsgId msgToLoad\n , XMLCh* const toFill\n , const unsigned int maxChars\n , const XMLCh* const repText1\n , const XMLCh* const repText2\n , const XMLCh* const repText3\n , const XMLCh* const repText4)\n{\n \/\/ Call the other version to load up the message\n if (!loadMsg(msgToLoad, toFill, maxChars))\n return false;\n\n \/\/ And do the token replacement\n XMLString::replaceTokens(toFill, maxChars, repText1, repText2, repText3, repText4);\n return true;\n}\n\n\nbool ICUMsgLoader::loadMsg( const XMLMsgLoader::XMLMsgId msgToLoad\n , XMLCh* const toFill\n , const unsigned int maxChars\n , const char* const repText1\n , const char* const repText2\n , const char* const repText3\n , const char* const repText4)\n{\n \/\/\n \/\/ Transcode the provided parameters and call the other version,\n \/\/ which will do the replacement work.\n \/\/\n XMLCh* tmp1 = 0;\n XMLCh* tmp2 = 0;\n XMLCh* tmp3 = 0;\n XMLCh* tmp4 = 0;\n\n bool bRet = false;\n if (repText1)\n tmp1 = XMLString::transcode(repText1);\n if (repText2)\n tmp2 = XMLString::transcode(repText2);\n if (repText3)\n tmp3 = XMLString::transcode(repText3);\n if (repText4)\n tmp4 = XMLString::transcode(repText4);\n\n bRet = loadMsg(msgToLoad, toFill, maxChars, tmp1, tmp2, tmp3, tmp4);\n\n if (tmp1)\n delete [] tmp1;\n if (tmp2)\n delete [] tmp2;\n if (tmp3)\n delete [] tmp3;\n if (tmp4)\n delete [] tmp4;\n\n return bRet;\n}\n\nXERCES_CPP_NAMESPACE_END\n<|endoftext|>"} {"text":"<commit_before>#include <hash_db.h>\n\n#include <QtCore\/QDebug>\n#include <QtCore\/QFileInfo>\n#include <QtCore\/QString>\n#include <QtCore\/QStringList>\n#include <QtCore\/QVariant>\n\n#include <QtSql\/QSqlDatabase>\n#include <QtSql\/QSqlQuery>\n#include <QtSql\/QSqlError>\n#include <QtSql\/QSqlRecord>\n\nQStringList schemas = (\n\tQStringList() <<\n\t\tQString(\"CREATE TABLE IF NOT EXISTS master_directory (hash TEXT NOT NULL PRIMARY KEY, path TEXT NOT NULL)\") <<\n\t\tQString(\"CREATE TABLE IF NOT EXISTS checked_directory (id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, hash TEXT NOT NULL, path TEXT NOT NULL)\") <<\n\t\tQString(\"CREATE TABLE IF NOT EXISTS master_files (hash TEXT NOT NULL PRIMARY KEY, path TEXT NOT NULL)\") <<\n\t\tQString(\"CREATE TABLE IF NOT EXISTS checked_files (id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, hash TEXT NOT NULL, path TEXT NOT NULL)\")\n);\n\nQStringList resetSchemas = (\n\tQStringList() <<\n\t\tQString(\"DROP TABLE IF EXISTS checked_files\") <<\n\t\tQString(\"DROP TABLE IF EXISTS master_files\") <<\n\t\tQString(\"DROP TABLE IF EXISTS checked_directory\") <<\n\t\tQString(\"DROP TABLE IF EXISTS master_directory\")\n);\n\n#define MAKE_QT_SQL_STATEMENT(name, the_db, the_statement)\t\t\t\t\t\\\n\tname = QSqlQuery(the_db); \t\t\t\t\t\t\t\t\t\t\t\t\\\n if (!name.prepare(the_statement))\t\t\t\t\t\t\t\t\t\t\\\n\t\t{\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\t\tqDebug() << \"Failed to prepare \" << the_statement;\t\t\t\t\t\\\n\t\tqDebug() << \"Error: \" << name.lastError();\t\t\t\t\t\t\t\\\n\t\t}\n\nHashDb::HashDb(QObject* _parent) : QObject(_parent)\n\t{\n\tdb = QSqlDatabase::addDatabase(\"QSQLITE\");\n\t\/\/ db.setDatabaseName(\":memory:\");\n\tdb.setDatabaseName(\"test_db.sqlite\");\n\tdb.open();\n\tinit_database();\n\tMAKE_QT_SQL_STATEMENT(SQL_INSERT_DIRECTORY, db, \"INSERT INTO master_directory (hash, path) VALUES(:hash, :path);\");\n\tMAKE_QT_SQL_STATEMENT(SQL_HAS_DIRECTORY_BY_HASH, db, \"SELECT hash, path FROM master_directory WHERE hash = :hash;\");\n\tMAKE_QT_SQL_STATEMENT(SQL_CHECK_INSERT_DIRECTORY, db, \"INSERT INTO checked_directory (hash, path) VALUES (:hash, :path);\");\n\n\tMAKE_QT_SQL_STATEMENT(SQL_INSERT_FILE, db, \"INSERT INTO master_files (hash, path) VALUES(:hash, :path);\");\n\tMAKE_QT_SQL_STATEMENT(SQL_HAS_FILE_BY_HASH, db, \"SELECT hash, path FROM master_files WHERE hash = :hash;\");\n\tMAKE_QT_SQL_STATEMENT(SQL_CHECK_INSERT_FILE, db, \"INSERT INTO checked_files (hash, path) VALUES(:hash, :path);\");\n\n\tMAKE_QT_SQL_STATEMENT(SQL_NEW_DIRECTORIES, db, \"SELECT hash, path FROM checked_directory WHERE hash NOT IN (SELECT hash FROM master_directory)\");\n\tSQL_NEW_DIRECTORIES.setForwardOnly(true);\n\n\tMAKE_QT_SQL_STATEMENT(SQL_MISSING_DIRECTORIES, db, \"SELECT hash, path FROM master_directory WHERE hash NOT IN (SELECT hash FROM checked_directory)\");\n\tSQL_MISSING_DIRECTORIES.setForwardOnly(true);\n\n\tMAKE_QT_SQL_STATEMENT(SQL_NEW_FILES, db, \"SELECT hash, path FROM checked_files WHERE hash NOT IN (SELECT hash FROM master_files)\");\n\tSQL_NEW_FILES.setForwardOnly(true);\n\n\tMAKE_QT_SQL_STATEMENT(SQL_MISSING_FILES, db, \"SELECT hash, path FROM master_files WHERE hash NOT IN (SELECT hash FROM checked_files)\");\n\tSQL_MISSING_FILES.setForwardOnly(true);\n\t}\n\nHashDb::~HashDb()\n\t{\n\tdb.close();\n\t}\n\nvoid HashDb::init_database()\n\t{\n\tif (db.isOpen())\n\t\t{\n\t\tfor (QStringList::iterator iter = resetSchemas.begin();\n\t\t\t iter != resetSchemas.end();\n\t\t\t ++iter)\n\t\t\t {\n\t\t\t QSqlQuery setup(db);\n\t\t\t setup.prepare((*iter));\n\t\t\t if (!setup.exec())\n\t\t\t \t{\n\t\t\t\tQ_EMIT message(\"Failed to drop table...\");\n\t\t\t\tQ_EMIT message(QString(\"Query: %1\").arg(setup.executedQuery()));\n\t\t\t\tQ_EMIT message(QString(\"Error: %1\").arg(setup.lastError().text()));\n\n\t\t\t\tqDebug() << \"Failed to drop table...\";\n\t\t\t\tqDebug() << \"Query: \" << setup.executedQuery();\n\t\t\t\tqDebug() << \"Error: \" << setup.lastError();\n\t\t\t\t}\n\t \t\t setup.clear();\n\t\t\t db.commit();\n\t\t\t }\n\t\tfor (QStringList::iterator iter = schemas.begin();\n\t\t\t iter != schemas.end();\n\t\t\t ++iter)\n\t\t\t {\n\t\t\t QSqlQuery setup(db);\n\t\t\t setup.prepare((*iter));\n\t\t\t if (!setup.exec())\n\t\t\t \t{\n\t\t\t\tQ_EMIT message(\"Failed to create table...\");\n\t\t\t\tQ_EMIT message(QString(\"Query: %1\").arg(setup.executedQuery()));\n\t\t\t\tQ_EMIT message(QString(\"Error: %1\").arg(setup.lastError().text()));\n\n\t\t\t\tqDebug() << \"Failed to create table...\";\n\t\t\t\tqDebug() << \"Query: \" << setup.executedQuery();\n\t\t\t\tqDebug() << \"Error: \" << setup.lastError();\n\t\t\t\t}\n\t\t\t setup.clear();\n\t\t\t db.commit();\n\t\t\t }\n\t\t }\n\t}\nvoid HashDb::resetDatabase()\n\t{\n\tQ_EMIT message(\"Resetting database...\");\n\tinit_database();\n\t}\n\nvoid HashDb::addDirectory(QString _path, QByteArray _hash, bool _generate)\n\t{\n\tif (db.isOpen())\n\t\t{\n\t\tQSqlQuery insertion;\n\t\tif (_generate)\n\t\t\t{\n\t\t\tQ_EMIT message(\"Mode: Generate\");\n\t\t\tinsertion = SQL_INSERT_DIRECTORY;\n\t\t\t}\n\t\telse\n\t\t\t{\n\t\t\tQ_EMIT message(\"Mode: Validate\");\n\t\t\tinsertion = SQL_CHECK_INSERT_DIRECTORY;\n\t\t\t}\n\t\tinsertion.bindValue(\":hash\", QVariant(_hash));\n\t\tinsertion.bindValue(\":path\", _path);\n\t\tif (insertion.exec())\n\t\t\t{\n\t\t\tdb.commit();\n\t\t\t}\n\t\telse\n\t\t\t{\n\t\t\tQ_EMIT message(QString(\"Failed to insert directory %1 with hash %2 into database\").arg(_path).arg(QString(_hash)));\n\t\t\tQ_EMIT message(QString(\"Query: %1\").arg(insertion.executedQuery()));\n\t\t\tQMapIterator<QString, QVariant> bv = insertion.boundValues();\n\t\t\twhile(bv.hasNext())\n\t\t\t\t{\n\t\t\t\tbv.next();\n\t\t\t\tQ_EMIT message(QString(\"Mapped - Key: %1, Value: %2\").arg(bv.key()).arg(bv.value().toString()));\n\t\t\t\t}\n\t\t\tQ_EMIT message(QString(\"Error: %1\").arg(insertion.lastError().text()));\n\t\t\t}\n\t\t}\n\t}\nvoid HashDb::addFile(QString _path, QByteArray _hash, bool _generate)\n\t{\n\tif (db.isOpen())\n\t\t{\n\t\tdb.transaction();\n\t\tQSqlQuery insertion(db);\n\t\tif (_generate)\n\t\t\t{\n\t\t\tQ_EMIT message(\"Mode: Generate\");\n\t\t\tinsertion = SQL_INSERT_FILE;\n\t\t\t}\n\t\telse\n\t\t\t{\n\t\t\tQ_EMIT message(\"Mode: Validate\");\n\t\t\tinsertion = SQL_CHECK_INSERT_FILE;\n\t\t\t}\n\t\tinsertion.bindValue(\":hash\", _hash);\n\t\tinsertion.bindValue(\":path\", _path);\n\t\tif (insertion.exec())\n\t\t\t{\n\t\t\tdb.commit();\n\t\t\t}\n\t\telse\n\t\t\t{\n\t\t\tQ_EMIT message(QString(\"Failed to insert file %1 with hash %2 into database\").arg(_path).arg(QString(_hash)));\n\t\t\tQ_EMIT message(QString(\"Query: %1\").arg(insertion.executedQuery()));\n\t\t\tQMapIterator<QString, QVariant> bv = insertion.boundValues();\n\t\t\twhile(bv.hasNext())\n\t\t\t\t{\n\t\t\t\tbv.next();\n\t\t\t\tQ_EMIT message(QString(\"Mapped - Key: %1, Value: %2\").arg(bv.key(), bv.value().toString()));\n\t\t\t\t}\n\t\t\tQ_EMIT message(QString(\"Error: %1\").arg(insertion.lastError().text()));\n\t\t\tdb.rollback();\n\t\t\t}\n\t\t}\n\t}\nvoid HashDb::generateMissingObjects()\n\t{\n\tif (db.isOpen())\n\t\t{\n\t\tint col_path = 1;\n\t\tif (SQL_MISSING_FILES.exec())\n\t\t\t{\n\t\t\twhile (SQL_MISSING_FILES.next())\n\t\t\t\t{\n\t\t\t\tQString path = SQL_MISSING_FILES.value(col_path).toString();\n\t\t\t\tQ_EMIT message_missing(path);\n\t\t\t\t}\n\t\t\t}\n\t\telse\n\t\t\t{\n\t\t\tQ_EMIT message(QString(\"Failed to retrieve missing records from the database\"));\n\t\t\tQ_EMIT message(QString(\"Query: %1\").arg(SQL_MISSING_FILES.executedQuery()));\n\t\t\tQ_EMIT message(QString(\"Error: %1\").arg(SQL_MISSING_FILES.lastError().text()));\n\t\t\t}\n\t\t}\n\t}\nvoid HashDb::generateNewObjects()\n\t{\n\tif (db.isOpen())\n\t\t{\n\t\tint col_path = 1;\n\t\tif (SQL_NEW_FILES.exec())\n\t\t\t{\n\t\t\twhile (SQL_NEW_FILES.next())\n\t\t\t\t{\n\t\t\t\tQString path = SQL_NEW_FILES.value(col_path).toString();\n\t\t\t\tQ_EMIT message_new(path);\n\t\t\t\t}\n\t\t\t}\n\t\telse\n\t\t\t{\n\t\t\tQ_EMIT message(QString(\"Failed to retrieve new records from the database\"));\n\t\t\tQ_EMIT message(QString(\"Query: %1\").arg(SQL_NEW_FILES.executedQuery()));\n\t\t\tQ_EMIT message(QString(\"Error: %1\").arg(SQL_NEW_FILES.lastError().text()));\n\t\t\t}\n\t\t}\n\t}\nvoid HashDb::copyMissingObjects(QString _source_path, QString _destination_path)\n\t{\n\tif (db.isOpen())\n\t\t{\n\t\tint col_path = 1;\n\t\tif (SQL_MISSING_FILES.exec())\n\t\t\t{\n\t\t\tint count = 0;\n\t\t\twhile (SQL_MISSING_FILES.next())\n\t\t\t\t{\n\t\t\t\tQString path = SQL_MISSING_FILES.value(col_path).toString();\n\t\t\t\tQString new_path = path;\n\t\t\t\tnew_path.replace(_source_path, _destination_path);\n\n\t\t\t\tQFileInfo source_info(path);\n\t\t\t\tQFileInfo destination_info(new_path); \n\n\t\t\t\t\/*\n\t\t\t\tqDebug() << \"Processing Path: \" << path;\n\t\t\t\tqDebug() << \" File Name: \" << source_info.fileName();\n\t\t\t\tqDebug() << \" File Path: \" << source_info.absolutePath();\n\t\t\t\tqDebug() << \" Source Path: \" << _source_path;\n\n\t\t\t\tqDebug() << \"Generated Path: \" << new_path;\n\t\t\t\tqDebug() << \" File Name: \" << destination_info.fileName();\n\t\t\t\tqDebug() << \" File Path: \" << destination_info.absolutePath();\n\t\t\t\tqDebug() << \"Destination Path: \" << _destination_path;\n\t\t\t\t*\/\n\n\t\t\t\tQ_EMIT copyFile(count, path, new_path);\n\t\t\t\t++count;\n\t\t\t\t}\n\t\t\t}\n\t\telse\n\t\t\t{\n\t\t\tQ_EMIT message(QString(\"Failed to retrieve missing records from the database\"));\n\t\t\tQ_EMIT message(QString(\"Query: %1\").arg(SQL_MISSING_FILES.executedQuery()));\n\t\t\tQ_EMIT message(QString(\"Error: %1\").arg(SQL_MISSING_FILES.lastError().text()));\n\t\t\t}\n\t\t}\n\t}\n<commit_msg>Restore<commit_after>#include <hash_db.h>\n\n#include <QtCore\/QDebug>\n#include <QtCore\/QFileInfo>\n#include <QtCore\/QString>\n#include <QtCore\/QStringList>\n#include <QtCore\/QVariant>\n\n#include <QtSql\/QSqlDatabase>\n#include <QtSql\/QSqlQuery>\n#include <QtSql\/QSqlError>\n#include <QtSql\/QSqlRecord>\n\nQStringList schemas = (\n\tQStringList() <<\n\t\tQString(\"CREATE TABLE IF NOT EXISTS master_directory (hash TEXT NOT NULL PRIMARY KEY, path TEXT NOT NULL)\") <<\n\t\tQString(\"CREATE TABLE IF NOT EXISTS checked_directory (id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, hash TEXT NOT NULL, path TEXT NOT NULL)\") <<\n\t\tQString(\"CREATE TABLE IF NOT EXISTS master_files (hash TEXT NOT NULL PRIMARY KEY, path TEXT NOT NULL)\") <<\n\t\tQString(\"CREATE TABLE IF NOT EXISTS checked_files (id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, hash TEXT NOT NULL, path TEXT NOT NULL)\")\n);\n\nQStringList resetSchemas = (\n\tQStringList() <<\n\t\tQString(\"DROP TABLE IF EXISTS checked_files\") <<\n\t\tQString(\"DROP TABLE IF EXISTS master_files\") <<\n\t\tQString(\"DROP TABLE IF EXISTS checked_directory\") <<\n\t\tQString(\"DROP TABLE IF EXISTS master_directory\")\n);\n\n#define MAKE_QT_SQL_STATEMENT(name, the_db, the_statement)\t\t\t\t\t\\\n\tname = QSqlQuery(the_db); \t\t\t\t\t\t\t\t\t\t\t\t\\\n if (!name.prepare(the_statement))\t\t\t\t\t\t\t\t\t\t\\\n\t\t{\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\t\tqDebug() << \"Failed to prepare \" << the_statement;\t\t\t\t\t\\\n\t\tqDebug() << \"Error: \" << name.lastError();\t\t\t\t\t\t\t\\\n\t\t}\n\nHashDb::HashDb(QObject* _parent) : QObject(_parent)\n\t{\n\tdb = QSqlDatabase::addDatabase(\"QSQLITE\");\n\tdb.setDatabaseName(\":memory:\");\n\tdb.open();\n\tinit_database();\n\tMAKE_QT_SQL_STATEMENT(SQL_INSERT_DIRECTORY, db, \"INSERT INTO master_directory (hash, path) VALUES(:hash, :path);\");\n\tMAKE_QT_SQL_STATEMENT(SQL_HAS_DIRECTORY_BY_HASH, db, \"SELECT hash, path FROM master_directory WHERE hash = :hash;\");\n\tMAKE_QT_SQL_STATEMENT(SQL_CHECK_INSERT_DIRECTORY, db, \"INSERT INTO checked_directory (hash, path) VALUES (:hash, :path);\");\n\n\tMAKE_QT_SQL_STATEMENT(SQL_INSERT_FILE, db, \"INSERT INTO master_files (hash, path) VALUES(:hash, :path);\");\n\tMAKE_QT_SQL_STATEMENT(SQL_HAS_FILE_BY_HASH, db, \"SELECT hash, path FROM master_files WHERE hash = :hash;\");\n\tMAKE_QT_SQL_STATEMENT(SQL_CHECK_INSERT_FILE, db, \"INSERT INTO checked_files (hash, path) VALUES(:hash, :path);\");\n\n\tMAKE_QT_SQL_STATEMENT(SQL_NEW_DIRECTORIES, db, \"SELECT hash, path FROM checked_directory WHERE hash NOT IN (SELECT hash FROM master_directory)\");\n\tSQL_NEW_DIRECTORIES.setForwardOnly(true);\n\n\tMAKE_QT_SQL_STATEMENT(SQL_MISSING_DIRECTORIES, db, \"SELECT hash, path FROM master_directory WHERE hash NOT IN (SELECT hash FROM checked_directory)\");\n\tSQL_MISSING_DIRECTORIES.setForwardOnly(true);\n\n\tMAKE_QT_SQL_STATEMENT(SQL_NEW_FILES, db, \"SELECT hash, path FROM checked_files WHERE hash NOT IN (SELECT hash FROM master_files)\");\n\tSQL_NEW_FILES.setForwardOnly(true);\n\n\tMAKE_QT_SQL_STATEMENT(SQL_MISSING_FILES, db, \"SELECT hash, path FROM master_files WHERE hash NOT IN (SELECT hash FROM checked_files)\");\n\tSQL_MISSING_FILES.setForwardOnly(true);\n\t}\n\nHashDb::~HashDb()\n\t{\n\tdb.close();\n\t}\n\nvoid HashDb::init_database()\n\t{\n\tif (db.isOpen())\n\t\t{\n\t\tfor (QStringList::iterator iter = resetSchemas.begin();\n\t\t\t iter != resetSchemas.end();\n\t\t\t ++iter)\n\t\t\t {\n\t\t\t QSqlQuery setup(db);\n\t\t\t setup.prepare((*iter));\n\t\t\t if (!setup.exec())\n\t\t\t \t{\n\t\t\t\tQ_EMIT message(\"Failed to drop table...\");\n\t\t\t\tQ_EMIT message(QString(\"Query: %1\").arg(setup.executedQuery()));\n\t\t\t\tQ_EMIT message(QString(\"Error: %1\").arg(setup.lastError().text()));\n\n\t\t\t\t\/*\n\t\t\t\tqDebug() << \"Failed to drop table...\";\n\t\t\t\tqDebug() << \"Query: \" << setup.executedQuery();\n\t\t\t\tqDebug() << \"Error: \" << setup.lastError();\n\t\t\t\t*\/\n\t\t\t\t}\n\t \t\t setup.clear();\n\t\t\t db.commit();\n\t\t\t }\n\t\tfor (QStringList::iterator iter = schemas.begin();\n\t\t\t iter != schemas.end();\n\t\t\t ++iter)\n\t\t\t {\n\t\t\t QSqlQuery setup(db);\n\t\t\t setup.prepare((*iter));\n\t\t\t if (!setup.exec())\n\t\t\t \t{\n\t\t\t\tQ_EMIT message(\"Failed to create table...\");\n\t\t\t\tQ_EMIT message(QString(\"Query: %1\").arg(setup.executedQuery()));\n\t\t\t\tQ_EMIT message(QString(\"Error: %1\").arg(setup.lastError().text()));\n\n\t\t\t\tqDebug() << \"Failed to create table...\";\n\t\t\t\tqDebug() << \"Query: \" << setup.executedQuery();\n\t\t\t\tqDebug() << \"Error: \" << setup.lastError();\n\t\t\t\t}\n\t\t\t setup.clear();\n\t\t\t db.commit();\n\t\t\t }\n\t\t }\n\t}\nvoid HashDb::resetDatabase()\n\t{\n\tQ_EMIT message(\"Resetting database...\");\n\tinit_database();\n\t}\n\nvoid HashDb::addDirectory(QString _path, QByteArray _hash, bool _generate)\n\t{\n\tif (db.isOpen())\n\t\t{\n\t\tQSqlQuery insertion;\n\t\tif (_generate)\n\t\t\t{\n\t\t\tQ_EMIT message(\"Mode: Generate\");\n\t\t\tinsertion = SQL_INSERT_DIRECTORY;\n\t\t\t}\n\t\telse\n\t\t\t{\n\t\t\tQ_EMIT message(\"Mode: Validate\");\n\t\t\tinsertion = SQL_CHECK_INSERT_DIRECTORY;\n\t\t\t}\n\t\tinsertion.bindValue(\":hash\", QVariant(_hash));\n\t\tinsertion.bindValue(\":path\", _path);\n\t\tif (insertion.exec())\n\t\t\t{\n\t\t\tdb.commit();\n\t\t\t}\n\t\telse\n\t\t\t{\n\t\t\tQ_EMIT message(QString(\"Failed to insert directory %1 with hash %2 into database\").arg(_path).arg(QString(_hash)));\n\t\t\tQ_EMIT message(QString(\"Query: %1\").arg(insertion.executedQuery()));\n\t\t\tQMapIterator<QString, QVariant> bv = insertion.boundValues();\n\t\t\twhile(bv.hasNext())\n\t\t\t\t{\n\t\t\t\tbv.next();\n\t\t\t\tQ_EMIT message(QString(\"Mapped - Key: %1, Value: %2\").arg(bv.key()).arg(bv.value().toString()));\n\t\t\t\t}\n\t\t\tQ_EMIT message(QString(\"Error: %1\").arg(insertion.lastError().text()));\n\t\t\t}\n\t\t}\n\t}\nvoid HashDb::addFile(QString _path, QByteArray _hash, bool _generate)\n\t{\n\tif (db.isOpen())\n\t\t{\n\t\tdb.transaction();\n\t\tQSqlQuery insertion(db);\n\t\tif (_generate)\n\t\t\t{\n\t\t\tQ_EMIT message(\"Mode: Generate\");\n\t\t\tinsertion = SQL_INSERT_FILE;\n\t\t\t}\n\t\telse\n\t\t\t{\n\t\t\tQ_EMIT message(\"Mode: Validate\");\n\t\t\tinsertion = SQL_CHECK_INSERT_FILE;\n\t\t\t}\n\t\tinsertion.bindValue(\":hash\", _hash);\n\t\tinsertion.bindValue(\":path\", _path);\n\t\tif (insertion.exec())\n\t\t\t{\n\t\t\tdb.commit();\n\t\t\t}\n\t\telse\n\t\t\t{\n\t\t\tQ_EMIT message(QString(\"Failed to insert file %1 with hash %2 into database\").arg(_path).arg(QString(_hash)));\n\t\t\tQ_EMIT message(QString(\"Query: %1\").arg(insertion.executedQuery()));\n\t\t\tQMapIterator<QString, QVariant> bv = insertion.boundValues();\n\t\t\twhile(bv.hasNext())\n\t\t\t\t{\n\t\t\t\tbv.next();\n\t\t\t\tQ_EMIT message(QString(\"Mapped - Key: %1, Value: %2\").arg(bv.key(), bv.value().toString()));\n\t\t\t\t}\n\t\t\tQ_EMIT message(QString(\"Error: %1\").arg(insertion.lastError().text()));\n\t\t\tdb.rollback();\n\t\t\t}\n\t\t}\n\t}\nvoid HashDb::generateMissingObjects()\n\t{\n\tif (db.isOpen())\n\t\t{\n\t\tint col_path = 1;\n\t\tif (SQL_MISSING_FILES.exec())\n\t\t\t{\n\t\t\twhile (SQL_MISSING_FILES.next())\n\t\t\t\t{\n\t\t\t\tQString path = SQL_MISSING_FILES.value(col_path).toString();\n\t\t\t\tQ_EMIT message_missing(path);\n\t\t\t\t}\n\t\t\t}\n\t\telse\n\t\t\t{\n\t\t\tQ_EMIT message(QString(\"Failed to retrieve missing records from the database\"));\n\t\t\tQ_EMIT message(QString(\"Query: %1\").arg(SQL_MISSING_FILES.executedQuery()));\n\t\t\tQ_EMIT message(QString(\"Error: %1\").arg(SQL_MISSING_FILES.lastError().text()));\n\t\t\t}\n\t\t}\n\t}\nvoid HashDb::generateNewObjects()\n\t{\n\tif (db.isOpen())\n\t\t{\n\t\tint col_path = 1;\n\t\tif (SQL_NEW_FILES.exec())\n\t\t\t{\n\t\t\twhile (SQL_NEW_FILES.next())\n\t\t\t\t{\n\t\t\t\tQString path = SQL_NEW_FILES.value(col_path).toString();\n\t\t\t\tQ_EMIT message_new(path);\n\t\t\t\t}\n\t\t\t}\n\t\telse\n\t\t\t{\n\t\t\tQ_EMIT message(QString(\"Failed to retrieve new records from the database\"));\n\t\t\tQ_EMIT message(QString(\"Query: %1\").arg(SQL_NEW_FILES.executedQuery()));\n\t\t\tQ_EMIT message(QString(\"Error: %1\").arg(SQL_NEW_FILES.lastError().text()));\n\t\t\t}\n\t\t}\n\t}\nvoid HashDb::copyMissingObjects(QString _source_path, QString _destination_path)\n\t{\n\tif (db.isOpen())\n\t\t{\n\t\tint col_path = 1;\n\t\tif (SQL_MISSING_FILES.exec())\n\t\t\t{\n\t\t\tint count = 0;\n\t\t\twhile (SQL_MISSING_FILES.next())\n\t\t\t\t{\n\t\t\t\tQString path = SQL_MISSING_FILES.value(col_path).toString();\n\t\t\t\tQString new_path = path;\n\t\t\t\tnew_path.replace(_source_path, _destination_path);\n\n\t\t\t\tQFileInfo source_info(path);\n\t\t\t\tQFileInfo destination_info(new_path); \n\n\t\t\t\t\/*\n\t\t\t\tqDebug() << \"Processing Path: \" << path;\n\t\t\t\tqDebug() << \" File Name: \" << source_info.fileName();\n\t\t\t\tqDebug() << \" File Path: \" << source_info.absolutePath();\n\t\t\t\tqDebug() << \" Source Path: \" << _source_path;\n\n\t\t\t\tqDebug() << \"Generated Path: \" << new_path;\n\t\t\t\tqDebug() << \" File Name: \" << destination_info.fileName();\n\t\t\t\tqDebug() << \" File Path: \" << destination_info.absolutePath();\n\t\t\t\tqDebug() << \"Destination Path: \" << _destination_path;\n\t\t\t\t*\/\n\n\t\t\t\tQ_EMIT copyFile(count, path, new_path);\n\t\t\t\t++count;\n\t\t\t\t}\n\t\t\t}\n\t\telse\n\t\t\t{\n\t\t\tQ_EMIT message(QString(\"Failed to retrieve missing records from the database\"));\n\t\t\tQ_EMIT message(QString(\"Query: %1\").arg(SQL_MISSING_FILES.executedQuery()));\n\t\t\tQ_EMIT message(QString(\"Error: %1\").arg(SQL_MISSING_FILES.lastError().text()));\n\t\t\t}\n\t\t}\n\t}\n<|endoftext|>"} {"text":"<commit_before>#include <string>\n\n#include \"SMT2Lib.h\"\n\nstatic const std::string parityDef =\n \"(define-fun parity_flag ((x!1 (_ BitVec 8))) (_ BitVec 1)\"\n \"; x ^= x >> 4;\"\n \"; v &= 0xf;\"\n \"; return (0x6996 >> v) & 1;\"\n \"((_ extract 0 0)\"\n \"(bvlshr\"\n \"(_ bv27030 16)\"\n \"((_ zero_extend 8)\"\n \"(bvand\"\n \"(bvxor\"\n \"x!1\"\n \"(bvlshr x!1 (_ bv4 8)))\"\n \"(_ bv15 8)))))\";\n\n\nstd::string smt2lib::init()\n{\n return \"(set-logic QF_AUFBV)\" + parityDef;\n}\n\n\/* Returns the 'bv' syntax based on a value and a size.\n * Mainly used for the SMT translation *\/\nstd::string smt2lib::bv(uint64_t value, uint64_t size)\n{\n return \"(_ bv\" + std::to_string(value) + \" \" + std::to_string(size) + \")\";\n}\n\n\n\/* Returns the 'bv' syntax with sign extension applied to it. *\/\nstd::string smt2lib::sx(std::string expr, uint64_t size)\n{\n return \"((_ sign_extend \" + std::to_string(size) + \") \" + expr + \")\";\n}\n\n\n\/* Returns the 'bv' syntax with zero extension applied to it. *\/\nstd::string smt2lib::zx(std::string expr, uint64_t size)\n{\n return \"((_ zero_extend \" + std::to_string(size) + \") \" + expr + \")\";;\n}\n\n\n\/* Returns the 'bvadd' syntax. *\/\nstd::string smt2lib::bvadd(std::string op1, std::string op2)\n{\n return \"(bvadd \" + op1 + \" \" + op2 + \")\";\n}\n\n\n\/* Returns the 'bvxor' syntax. *\/\nstd::string smt2lib::bvxor(std::string op1, std::string op2)\n{\n return \"(bvxor \" + op1 + \" \" + op2 + \")\";\n}\n\n\n\/* Returns the 'bvand' syntax. *\/\nstd::string smt2lib::bvand(std::string op1, std::string op2)\n{\n return \"(bvand \" + op1 + \" \" + op2 + \")\";\n}\n\n\n\/* Returns the 'bvnot' syntax. *\/\nstd::string smt2lib::bvnot(std::string op1)\n{\n return \"(bvnot \" + op1 + \")\";\n}\n\n\n\/*\n * Returns the 'bvult' syntax.\n * bvult: unsigned less than\n *\/\nstd::string smt2lib::bvult(std::string op1, std::string op2)\n{\n return \"(bvult \" + op1 + \" \" + op2 + \")\";\n}\n\n\n\/* Returns the 'extract' syntax based on a regSize.\n * Mainly used for the SMT translation *\/\nstd::string smt2lib::extract(uint64_t regSize)\n{\n std::stringstream stream;\n\n switch(regSize){\n case 1:\n stream << \"(_ extract 7 0)\";\n break;\n case 2:\n stream << \"(_ extract 15 0)\";\n break;\n case 4:\n stream << \"(_ extract 31 0)\";\n break;\n case 8:\n stream << \"(_ extract 63 0)\";\n break;\n }\n\n return stream.str();\n}\n\n\n\/* Returns the 'extract' syntax. *\/\nstd::string smt2lib::extract(uint64_t high, uint64_t low)\n{\n return \"(_ extract \" + std::to_string(high) + \" \" + std::to_string(low) + \")\";\n}\n\n\n\/* Returns the 'extract' syntax. *\/\nstd::string smt2lib::extract(uint64_t high, uint64_t low, std::string expr)\n{\n return \"(\" + smt2lib::extract(high, low) + \" \" + expr + \")\";\n}\n\n\n\/* Returns the 'declare' syntax is symbolic variable and a bit vector.\n * Mainly used for the SMT translation *\/\nstd::string smt2lib::declare(uint64_t idSymVar, uint64_t BitVecSize)\n{\n std::stringstream stream;\n\n switch(BitVecSize){\n case 1:\n stream << \"(declare-fun SymVar_\" << idSymVar << \" () (_ BitVec 8))\";\n break;\n case 2:\n stream << \"(declare-fun SymVar_\" << idSymVar << \" () (_ BitVec 16))\";\n break;\n case 4:\n stream << \"(declare-fun SymVar_\" << idSymVar << \" () (_ BitVec 32))\";\n break;\n case 8:\n stream << \"(declare-fun SymVar_\" << idSymVar << \" () (_ BitVec 64))\";\n break;\n }\n\n return stream.str();\n}\n\n\n\/* Returns the 'assert' syntax. *\/\nstd::string smt2lib::smtAssert(std::string expr)\n{\n return \"(assert \" + expr + \")\";\n}\n\n\n\/* Returns the 'equal' syntax. *\/\nstd::string smt2lib::equal(std::string op1, std::string op2)\n{\n return \"(= \" + op1 + \" \" + op2 + \")\";\n}\n\n\n\/* Returns a call to the parity function.\n * Returns the parity flag of one byte. If the number of bits set to 1 is even,\n * it returns (_ bv0 1) and (_ bv1 1) otherwise. *\/\nstd::string smt2lib::parityFlag(std::string expr)\n{\n return \"(parity_flag \" + expr + \")\";\n}\n<commit_msg>Fix a mistake \")\" in the PF flag formulae<commit_after>#include <string>\n\n#include \"SMT2Lib.h\"\n\nstatic const std::string parityDef =\n \"(define-fun parity_flag ((x!1 (_ BitVec 8))) (_ BitVec 1)\"\n \"; x ^= x >> 4;\"\n \"; v &= 0xf;\"\n \"; return (0x6996 >> v) & 1;\"\n \"((_ extract 0 0)\"\n \"(bvlshr\"\n \"(_ bv27030 16)\"\n \"((_ zero_extend 8)\"\n \"(bvand\"\n \"(bvxor\"\n \"x!1\"\n \"(bvlshr x!1 (_ bv4 8)))\"\n \"(_ bv15 8))))))\";\n\n\nstd::string smt2lib::init()\n{\n return \"(set-logic QF_AUFBV)\" + parityDef;\n}\n\n\/* Returns the 'bv' syntax based on a value and a size.\n * Mainly used for the SMT translation *\/\nstd::string smt2lib::bv(uint64_t value, uint64_t size)\n{\n return \"(_ bv\" + std::to_string(value) + \" \" + std::to_string(size) + \")\";\n}\n\n\n\/* Returns the 'bv' syntax with sign extension applied to it. *\/\nstd::string smt2lib::sx(std::string expr, uint64_t size)\n{\n return \"((_ sign_extend \" + std::to_string(size) + \") \" + expr + \")\";\n}\n\n\n\/* Returns the 'bv' syntax with zero extension applied to it. *\/\nstd::string smt2lib::zx(std::string expr, uint64_t size)\n{\n return \"((_ zero_extend \" + std::to_string(size) + \") \" + expr + \")\";;\n}\n\n\n\/* Returns the 'bvadd' syntax. *\/\nstd::string smt2lib::bvadd(std::string op1, std::string op2)\n{\n return \"(bvadd \" + op1 + \" \" + op2 + \")\";\n}\n\n\n\/* Returns the 'bvxor' syntax. *\/\nstd::string smt2lib::bvxor(std::string op1, std::string op2)\n{\n return \"(bvxor \" + op1 + \" \" + op2 + \")\";\n}\n\n\n\/* Returns the 'bvand' syntax. *\/\nstd::string smt2lib::bvand(std::string op1, std::string op2)\n{\n return \"(bvand \" + op1 + \" \" + op2 + \")\";\n}\n\n\n\/* Returns the 'bvnot' syntax. *\/\nstd::string smt2lib::bvnot(std::string op1)\n{\n return \"(bvnot \" + op1 + \")\";\n}\n\n\n\/*\n * Returns the 'bvult' syntax.\n * bvult: unsigned less than\n *\/\nstd::string smt2lib::bvult(std::string op1, std::string op2)\n{\n return \"(bvult \" + op1 + \" \" + op2 + \")\";\n}\n\n\n\/* Returns the 'extract' syntax based on a regSize.\n * Mainly used for the SMT translation *\/\nstd::string smt2lib::extract(uint64_t regSize)\n{\n std::stringstream stream;\n\n switch(regSize){\n case 1:\n stream << \"(_ extract 7 0)\";\n break;\n case 2:\n stream << \"(_ extract 15 0)\";\n break;\n case 4:\n stream << \"(_ extract 31 0)\";\n break;\n case 8:\n stream << \"(_ extract 63 0)\";\n break;\n }\n\n return stream.str();\n}\n\n\n\/* Returns the 'extract' syntax. *\/\nstd::string smt2lib::extract(uint64_t high, uint64_t low)\n{\n return \"(_ extract \" + std::to_string(high) + \" \" + std::to_string(low) + \")\";\n}\n\n\n\/* Returns the 'extract' syntax. *\/\nstd::string smt2lib::extract(uint64_t high, uint64_t low, std::string expr)\n{\n return \"(\" + smt2lib::extract(high, low) + \" \" + expr + \")\";\n}\n\n\n\/* Returns the 'declare' syntax is symbolic variable and a bit vector.\n * Mainly used for the SMT translation *\/\nstd::string smt2lib::declare(uint64_t idSymVar, uint64_t BitVecSize)\n{\n std::stringstream stream;\n\n switch(BitVecSize){\n case 1:\n stream << \"(declare-fun SymVar_\" << idSymVar << \" () (_ BitVec 8))\";\n break;\n case 2:\n stream << \"(declare-fun SymVar_\" << idSymVar << \" () (_ BitVec 16))\";\n break;\n case 4:\n stream << \"(declare-fun SymVar_\" << idSymVar << \" () (_ BitVec 32))\";\n break;\n case 8:\n stream << \"(declare-fun SymVar_\" << idSymVar << \" () (_ BitVec 64))\";\n break;\n }\n\n return stream.str();\n}\n\n\n\/* Returns the 'assert' syntax. *\/\nstd::string smt2lib::smtAssert(std::string expr)\n{\n return \"(assert \" + expr + \")\";\n}\n\n\n\/* Returns the 'equal' syntax. *\/\nstd::string smt2lib::equal(std::string op1, std::string op2)\n{\n return \"(= \" + op1 + \" \" + op2 + \")\";\n}\n\n\n\/* Returns a call to the parity function.\n * Returns the parity flag of one byte. If the number of bits set to 1 is even,\n * it returns (_ bv0 1) and (_ bv1 1) otherwise. *\/\nstd::string smt2lib::parityFlag(std::string expr)\n{\n return \"(parity_flag \" + expr + \")\";\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"coverage.h\"\n#include \"featurecoverage.h\"\n#include \"feature.h\"\n#include \"featureiterator.h\"\n#include \"drawingcolor.h\"\n#include \"drawerfactory.h\"\n#include \"rootdrawer.h\"\n#include \"table.h\"\n#include \"range.h\"\n#include \"itemrange.h\"\n#include \"colorrange.h\"\n#include \"colorlookup.h\"\n#include \"representation.h\"\n#include \"attributevisualproperties.h\"\n#include \"featurelayerdrawer.h\"\n#include \"tesselation\/ilwistesselator.h\"\n#include \"openglhelper.h\"\n\nusing namespace Ilwis;\nusing namespace Geodrawer;\n\nREGISTER_DRAWER(FeatureLayerDrawer)\n\nFeatureLayerDrawer::FeatureLayerDrawer(DrawerInterface *parentDrawer, RootDrawer *rootdrawer) : LayerDrawer(\"FeatureLayerDrawer\", parentDrawer, rootdrawer)\n{\n}\n\nDrawerInterface *FeatureLayerDrawer::create(DrawerInterface *parentDrawer, RootDrawer *rootdrawer)\n{\n return new FeatureLayerDrawer(parentDrawer, rootdrawer) ;\n}\n\n\nbool FeatureLayerDrawer::prepare(DrawerInterface::PreparationType prepType, const IOOptions &options, QOpenGLContext *openglContext)\n{\n if(!LayerDrawer::prepare(prepType, options, openglContext))\n return false;\n\n if ( hasType(prepType, DrawerInterface::ptGEOMETRY) && !isPrepared(DrawerInterface::ptGEOMETRY)){\n std::vector<VertexPosition> vertices;\n std::vector<VertexColor> colors;\n\n _indices = std::vector<VertexIndex>();\n\n\n IFeatureCoverage features = coverage().as<FeatureCoverage>();\n if ( !features.isValid()){\n return ERROR2(ERR_COULDNT_CREATE_OBJECT_FOR_2,\"FeatureCoverage\", TR(\"Visualization\"));\n }\n AttributeVisualProperties attr = visualAttribute(activeAttribute());\n \/\/int columnIndex = features->attributeDefinitions().columnIndex(activeAttribute());\n for(const SPFeatureI& feature : features){\n quint32 noOfVertices = OpenGLHelper::getVertices(rootDrawer()->coordinateSystem(), features->coordinateSystem(), feature->geometry(), feature->featureid(), vertices, _indices, _boundaryIndex);\n for(int i =0; i < noOfVertices; ++i){\n QColor clr = attr.value2color(feature(activeAttribute()));\n colors.push_back(VertexColor(clr.redF(), clr.greenF(), clr.blueF(), 1.0));\n }\n\n }\n\n\n if(!initGeometry(openglContext, vertices, colors))\n return false;\n\n _prepared |= DrawerInterface::ptGEOMETRY;\n\n }\n\n return true;\n}\n\nvoid FeatureLayerDrawer::unprepare(DrawerInterface::PreparationType prepType)\n{\n LayerDrawer::unprepare(prepType);\n\n if ( hasType(prepType, DrawerInterface::ptGEOMETRY)) {\n _prepared &= ~ ptGEOMETRY;\n }\n}\n\nvoid FeatureLayerDrawer::setActiveVisualAttribute(const QString &attr)\n{\n IFeatureCoverage features = coverage().as<FeatureCoverage>();\n if ( features.isValid()) {\n if ( features->attributeDefinitions().columnIndex(attr) != iUNDEF){\n\n IRepresentation newrpr = Representation::defaultRepresentation(features->attributeDefinitions().columndefinition(attr).datadef().domain());\n if ( newrpr.isValid()){\n LayerDrawer::setActiveVisualAttribute(attr);\n }\n }\n }\n}\n\nvoid FeatureLayerDrawer::coverage(const ICoverage &cov)\n{\n LayerDrawer::coverage(cov);\n setActiveVisualAttribute(sUNDEF);\n IFeatureCoverage features = coverage().as<FeatureCoverage>();\n\n for(int i = 0; i < features->attributeDefinitions().definitionCount(); ++i){\n IlwisTypes attrType = features->attributeDefinitions().columndefinition(i).datadef().domain()->ilwisType();\n if ( hasType(attrType, itNUMERICDOMAIN | itITEMDOMAIN)){\n AttributeVisualProperties props(features->attributeDefinitions().columndefinition(i).datadef().domain());\n if ( attrType == itNUMERICDOMAIN){\n SPNumericRange numrange = features->attributeDefinitions().columndefinition(i).datadef().range<NumericRange>();\n props.actualRange(NumericRange(numrange->min(), numrange->max(), numrange->resolution()));\n }\n visualAttribute(features->attributeDefinitions().columndefinition(i).name(), props);\n \/\/ try to find a reasonable default for the activeattribute\n if ( activeAttribute() == sUNDEF){\n if ( features->attributeDefinitions().columnIndex(FEATUREVALUECOLUMN) != iUNDEF){\n setActiveVisualAttribute(FEATUREVALUECOLUMN);\n }else if ( features->attributeDefinitions().columnIndex(COVERAGEKEYCOLUMN) != iUNDEF){\n setActiveVisualAttribute(COVERAGEKEYCOLUMN);\n }\n else if ( hasType(features->attributeDefinitions().columndefinition(i).datadef().domain()->ilwisType(), itNUMERICDOMAIN)){\n setActiveVisualAttribute(features->attributeDefinitions().columndefinition(i).name());\n }\n }\n }\n }\n}\n\nICoverage FeatureLayerDrawer::coverage() const\n{\n return SpatialDataDrawer::coverage();\n}\n\n\nbool FeatureLayerDrawer::draw(QOpenGLContext *openglContext, const IOOptions&) {\n if ( !openglContext){\n return ERROR2(QString(\"%1 : %2\"),TR(\"Drawing failed\"),TR(\"Invalid OpenGL context passed\"));\n }\n\n if ( !isActive())\n return false;\n\n if (!isPrepared()){\n return false;\n }\n\n _shaders.bind();\n\n openglContext->functions()->glBindBuffer(GL_ARRAY_BUFFER,_vboPosition);\n\n int vertexLocation = _shaders.attributeLocation(\"position\");\n openglContext->functions()->glVertexAttribPointer(vertexLocation,3,GL_FLOAT,FALSE,0,0);\n openglContext->functions()->glEnableVertexAttribArray(vertexLocation);\n\n openglContext->functions()->glBindBuffer(GL_ARRAY_BUFFER,_vboColor);\n\n int colorLocation = _shaders.attributeLocation(\"vertexColor\");\n openglContext->functions()->glVertexAttribPointer(colorLocation,4,GL_FLOAT,FALSE,0, 0);\n openglContext->functions()->glEnableVertexAttribArray(colorLocation);\n\n\n\n for(int i =0; i < _indices.size(); ++i){\n if ( _indices[i]._geomtype == itLINE){\n glDrawArrays(GL_LINE_STRIP,_indices[i]._start,_indices[i]._count);\n } else if ( _indices[i]._geomtype == itPOLYGON ){\n glDrawArrays(GL_TRIANGLE_FAN,_indices[i]._start,_indices[i]._count);\n }\n }\n\n openglContext->functions()->glBindBuffer(GL_ARRAY_BUFFER, 0);\n openglContext->functions()->glDisableVertexAttribArray(colorLocation);\n openglContext->functions()->glDisableVertexAttribArray(vertexLocation);\n\n _shaders.release();\n\n return true;\n}\n<commit_msg>item domain is setting properties for the attributevizualization<commit_after>#include \"coverage.h\"\n#include \"featurecoverage.h\"\n#include \"feature.h\"\n#include \"featureiterator.h\"\n#include \"drawingcolor.h\"\n#include \"drawerfactory.h\"\n#include \"rootdrawer.h\"\n#include \"table.h\"\n#include \"range.h\"\n#include \"itemrange.h\"\n#include \"colorrange.h\"\n#include \"colorlookup.h\"\n#include \"representation.h\"\n#include \"attributevisualproperties.h\"\n#include \"featurelayerdrawer.h\"\n#include \"tesselation\/ilwistesselator.h\"\n#include \"openglhelper.h\"\n\nusing namespace Ilwis;\nusing namespace Geodrawer;\n\nREGISTER_DRAWER(FeatureLayerDrawer)\n\nFeatureLayerDrawer::FeatureLayerDrawer(DrawerInterface *parentDrawer, RootDrawer *rootdrawer) : LayerDrawer(\"FeatureLayerDrawer\", parentDrawer, rootdrawer)\n{\n}\n\nDrawerInterface *FeatureLayerDrawer::create(DrawerInterface *parentDrawer, RootDrawer *rootdrawer)\n{\n return new FeatureLayerDrawer(parentDrawer, rootdrawer) ;\n}\n\n\nbool FeatureLayerDrawer::prepare(DrawerInterface::PreparationType prepType, const IOOptions &options, QOpenGLContext *openglContext)\n{\n if(!LayerDrawer::prepare(prepType, options, openglContext))\n return false;\n\n if ( hasType(prepType, DrawerInterface::ptGEOMETRY) && !isPrepared(DrawerInterface::ptGEOMETRY)){\n std::vector<VertexPosition> vertices;\n std::vector<VertexColor> colors;\n\n _indices = std::vector<VertexIndex>();\n\n\n IFeatureCoverage features = coverage().as<FeatureCoverage>();\n if ( !features.isValid()){\n return ERROR2(ERR_COULDNT_CREATE_OBJECT_FOR_2,\"FeatureCoverage\", TR(\"Visualization\"));\n }\n AttributeVisualProperties attr = visualAttribute(activeAttribute());\n \/\/int columnIndex = features->attributeDefinitions().columnIndex(activeAttribute());\n for(const SPFeatureI& feature : features){\n quint32 noOfVertices = OpenGLHelper::getVertices(rootDrawer()->coordinateSystem(), features->coordinateSystem(), feature->geometry(), feature->featureid(), vertices, _indices, _boundaryIndex);\n for(int i =0; i < noOfVertices; ++i){\n QColor clr = attr.value2color(feature(activeAttribute()));\n colors.push_back(VertexColor(clr.redF(), clr.greenF(), clr.blueF(), 1.0));\n }\n\n }\n\n\n if(!initGeometry(openglContext, vertices, colors))\n return false;\n\n _prepared |= DrawerInterface::ptGEOMETRY;\n\n }\n\n return true;\n}\n\nvoid FeatureLayerDrawer::unprepare(DrawerInterface::PreparationType prepType)\n{\n LayerDrawer::unprepare(prepType);\n\n if ( hasType(prepType, DrawerInterface::ptGEOMETRY)) {\n _prepared &= ~ ptGEOMETRY;\n }\n}\n\nvoid FeatureLayerDrawer::setActiveVisualAttribute(const QString &attr)\n{\n IFeatureCoverage features = coverage().as<FeatureCoverage>();\n if ( features.isValid()) {\n if ( features->attributeDefinitions().columnIndex(attr) != iUNDEF){\n\n IRepresentation newrpr = Representation::defaultRepresentation(features->attributeDefinitions().columndefinition(attr).datadef().domain());\n if ( newrpr.isValid()){\n LayerDrawer::setActiveVisualAttribute(attr);\n }\n }\n }\n}\n\nvoid FeatureLayerDrawer::coverage(const ICoverage &cov)\n{\n LayerDrawer::coverage(cov);\n setActiveVisualAttribute(sUNDEF);\n IFeatureCoverage features = coverage().as<FeatureCoverage>();\n\n for(int i = 0; i < features->attributeDefinitions().definitionCount(); ++i){\n IlwisTypes attrType = features->attributeDefinitions().columndefinition(i).datadef().domain()->ilwisType();\n if ( hasType(attrType, itNUMERICDOMAIN | itITEMDOMAIN)){\n AttributeVisualProperties props(features->attributeDefinitions().columndefinition(i).datadef().domain());\n if ( attrType == itNUMERICDOMAIN){\n SPNumericRange numrange = features->attributeDefinitions().columndefinition(i).datadef().range<NumericRange>();\n props.actualRange(NumericRange(numrange->min(), numrange->max(), numrange->resolution()));\n } else if ( attrType == itITEMDOMAIN){\n int count = features->attributeDefinitions().columndefinition(i).datadef().domain()->range<>()->count();\n props.actualRange(NumericRange(0, count - 1,1));\n }\n visualAttribute(features->attributeDefinitions().columndefinition(i).name(), props);\n \/\/ try to find a reasonable default for the activeattribute\n if ( activeAttribute() == sUNDEF){\n if ( features->attributeDefinitions().columnIndex(FEATUREVALUECOLUMN) != iUNDEF){\n setActiveVisualAttribute(FEATUREVALUECOLUMN);\n }else if ( features->attributeDefinitions().columnIndex(COVERAGEKEYCOLUMN) != iUNDEF){\n setActiveVisualAttribute(COVERAGEKEYCOLUMN);\n }\n else if ( hasType(features->attributeDefinitions().columndefinition(i).datadef().domain()->ilwisType(), itNUMERICDOMAIN)){\n setActiveVisualAttribute(features->attributeDefinitions().columndefinition(i).name());\n }\n }\n }\n }\n}\n\nICoverage FeatureLayerDrawer::coverage() const\n{\n return SpatialDataDrawer::coverage();\n}\n\n\nbool FeatureLayerDrawer::draw(QOpenGLContext *openglContext, const IOOptions&) {\n if ( !openglContext){\n return ERROR2(QString(\"%1 : %2\"),TR(\"Drawing failed\"),TR(\"Invalid OpenGL context passed\"));\n }\n\n if ( !isActive())\n return false;\n\n if (!isPrepared()){\n return false;\n }\n\n _shaders.bind();\n\n openglContext->functions()->glBindBuffer(GL_ARRAY_BUFFER,_vboPosition);\n\n int vertexLocation = _shaders.attributeLocation(\"position\");\n openglContext->functions()->glVertexAttribPointer(vertexLocation,3,GL_FLOAT,FALSE,0,0);\n openglContext->functions()->glEnableVertexAttribArray(vertexLocation);\n\n openglContext->functions()->glBindBuffer(GL_ARRAY_BUFFER,_vboColor);\n\n int colorLocation = _shaders.attributeLocation(\"vertexColor\");\n openglContext->functions()->glVertexAttribPointer(colorLocation,4,GL_FLOAT,FALSE,0, 0);\n openglContext->functions()->glEnableVertexAttribArray(colorLocation);\n\n\n\n for(int i =0; i < _indices.size(); ++i){\n if ( _indices[i]._geomtype == itLINE){\n glDrawArrays(GL_LINE_STRIP,_indices[i]._start,_indices[i]._count);\n } else if ( _indices[i]._geomtype == itPOLYGON ){\n glDrawArrays(GL_TRIANGLE_FAN,_indices[i]._start,_indices[i]._count);\n }\n }\n\n openglContext->functions()->glBindBuffer(GL_ARRAY_BUFFER, 0);\n openglContext->functions()->glDisableVertexAttribArray(colorLocation);\n openglContext->functions()->glDisableVertexAttribArray(vertexLocation);\n\n _shaders.release();\n\n return true;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ vim:ts=2:sw=2:expandtab:autoindent:filetype=cpp:\n\/*\nThe MIT License\n\nCopyright (c) 2008, 2009 Aristid Breitkreuz, Ash Berlin, Ruediger Sonderfeld\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n*\/\n\n#include \"flusspferd\/context.hpp\"\n#include \"flusspferd\/object.hpp\"\n#include \"flusspferd\/exception.hpp\"\n#include \"flusspferd\/local_root_scope.hpp\"\n#include \"flusspferd\/spidermonkey\/context.hpp\"\n#include \"flusspferd\/spidermonkey\/value.hpp\"\n#include \"flusspferd\/spidermonkey\/object.hpp\"\n#include \"flusspferd\/spidermonkey\/runtime.hpp\"\n#include \"flusspferd\/current_context_scope.hpp\"\n#include <boost\/unordered_map.hpp>\n#include <cstring>\n#include <cstdio>\n#include <js\/jsapi.h>\n\n#ifndef FLUSSPFERD_STACKCHUNKSIZE\n#define FLUSSPFERD_STACKCHUNKSIZE 8192\n#endif\n\nusing namespace flusspferd;\n\nnamespace {\n static JSClass global_class = {\n \"global\", JSCLASS_GLOBAL_FLAGS,\n JS_PropertyStub, JS_PropertyStub, JS_PropertyStub, JS_PropertyStub,\n JS_EnumerateStub, JS_ResolveStub, JS_ConvertStub, JS_FinalizeStub,\n JSCLASS_NO_OPTIONAL_MEMBERS\n };\n}\n\nstruct context::context_private {\n typedef boost::shared_ptr<root_object> root_object_ptr;\n boost::unordered_map<std::string, root_object_ptr> prototypes;\n boost::unordered_map<std::string, root_object_ptr> constructors;\n};\n\nclass context::impl {\npublic:\n impl()\n : context(JS_NewContext(Impl::get_runtime(),\n FLUSSPFERD_STACKCHUNKSIZE)),\n destroy(true)\n {\n if(!context)\n throw exception(\"Could not create Spidermonkey Context\");\n\n uint32 options = JS_GetOptions(context);\n\n options |= JSOPTION_VAROBJFIX;\n options |= JSOPTION_STRICT;\n options |= JSOPTION_DONT_REPORT_UNCAUGHT;\n options &= ~JSOPTION_XML;\n\n JS_SetVersion(context, JSVersion(JS_VERSION));\n JS_SetOptions(context, options);\n\n#ifdef JS_THREADSAFE\n JS_BeginRequest(context);\n#endif\n\n JSObject *global_ = JS_NewObject(context, &global_class, 0x0, 0x0);\n if(!global_)\n throw exception(\"Could not create Global Object\");\n\n \/\/ Set it so that it doesn't get GCd (play it safe)\n JS_SetGlobalObject(context, global_);\n\n if(!JS_InitStandardClasses(context, global_))\n throw exception(\"Could not initialize Global Object\");\n\n JS_DeleteProperty(context, global_, \"XML\");\n\n \/\/ Set the global object as an empty object which has its proto as the\n \/\/ 'true' global object with the std classes on it\n JSObject *pub_global = JS_NewObject(context, &global_class, global_, NULL);\n if(!global_)\n throw exception(\"Could not create Global Shim Object\");\n\n JS_SetGlobalObject(context, pub_global);\n\n JS_SetContextPrivate(context, static_cast<void*>(new context_private));\n }\n\n explicit impl(JSContext *context)\n : context(context), destroy(false)\n { }\n\n ~impl() {\n if (destroy) {\n {\n current_context_scope scope(Impl::wrap_context(context));\n delete get_private();\n JS_DestroyContext(context);\n }\n }\n }\n\n bool is_valid() {\n return context;\n }\n\n context_private *get_private() {\n return static_cast<context_private*>(JS_GetContextPrivate(context));\n }\n\n JSContext *context;\n bool destroy;\n};\n\nstruct context::detail {\n JSContext *c;\n detail(JSContext *ct) : c(ct) { }\n\n static JSContext *get(context &co) {\n return co.p->context;\n }\n};\n\nJSContext *Impl::get_context(context &co) {\n return context::detail::get(co);\n}\n\ncontext Impl::wrap_context(JSContext *c) {\n return context(c);\n}\n\ncontext::context()\n{ }\ncontext::context(context::detail const &d)\n : p(new impl(d.c))\n{\n if (!p->is_valid())\n p.reset();\n}\ncontext::~context() { }\n\ncontext context::create() {\n context c;\n c.p.reset(new impl);\n return c;\n}\n\nbool context::is_valid() const {\n return p;\n}\n\nobject context::global() {\n JSObject *o = JS_GetGlobalObject(p->context);\n if (!o) {\n throw exception(\"No global object\");\n }\n return Impl::wrap_object(o);\n}\n\nobject context::scope_chain() {\n JSObject *o = JS_GetScopeChain(p->context);\n if (!o) {\n \/\/ Weird! In Spidermonkey 1.7, sometimes it seems like JS_GetScopeChain\n \/\/ returns NULL without setting an error.\n \/\/ In that case, we simply return the global object. It caused a problem.\n if (JS_IsExceptionPending(p->context))\n throw exception(\"No scope chain\");\n else\n return this->global();\n }\n return Impl::wrap_object(o);\n}\n\nvoid context::add_prototype(std::string const &name, object const &proto) {\n p->get_private()->prototypes[name] =\n context_private::root_object_ptr(new root_object(proto));\n}\n\nobject context::prototype(std::string const &name) const {\n context_private::root_object_ptr ptr = p->get_private()->prototypes[name];\n return ptr ? *ptr : object();\n}\n\nvoid context::add_constructor(std::string const &name, object const &ctor) {\n p->get_private()->constructors[name] =\n context_private::root_object_ptr(new root_object(ctor));\n}\n\nobject context::constructor(std::string const &name) const {\n context_private::root_object_ptr ptr = p->get_private()->constructors[name];\n return ptr ? *ptr : object();\n}\n\nvoid context::gc() {\n JS_GC(p->context);\n}\n\nvoid context::set_thread() {\n assert(JS_SetContextThread(p->context) == 0);\n}\n\nvoid context::clear_thread() {\n \/\/assert(\n JS_ClearContextThread(p->context);\n \/\/ == js_GetCurrentThread(p->context->runtime)->id);\n}\n<commit_msg>core: Report warnings from spidermonkey<commit_after>\/\/ vim:ts=2:sw=2:expandtab:autoindent:filetype=cpp:\n\/*\nThe MIT License\n\nCopyright (c) 2008, 2009 Aristid Breitkreuz, Ash Berlin, Ruediger Sonderfeld\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n*\/\n\n#include \"flusspferd\/context.hpp\"\n#include \"flusspferd\/object.hpp\"\n#include \"flusspferd\/exception.hpp\"\n#include \"flusspferd\/local_root_scope.hpp\"\n#include \"flusspferd\/spidermonkey\/context.hpp\"\n#include \"flusspferd\/spidermonkey\/value.hpp\"\n#include \"flusspferd\/spidermonkey\/object.hpp\"\n#include \"flusspferd\/spidermonkey\/runtime.hpp\"\n#include \"flusspferd\/current_context_scope.hpp\"\n#include <boost\/unordered_map.hpp>\n#include <cstring>\n#include <cstdio>\n#include <iostream>\n#include <js\/jsapi.h>\n\n#ifndef FLUSSPFERD_STACKCHUNKSIZE\n#define FLUSSPFERD_STACKCHUNKSIZE 8192\n#endif\n\nusing namespace flusspferd;\n\nnamespace {\n static JSClass global_class = {\n \"global\", JSCLASS_GLOBAL_FLAGS,\n JS_PropertyStub, JS_PropertyStub, JS_PropertyStub, JS_PropertyStub,\n JS_EnumerateStub, JS_ResolveStub, JS_ConvertStub, JS_FinalizeStub,\n JSCLASS_NO_OPTIONAL_MEMBERS\n };\n}\n\nstruct context::context_private {\n typedef boost::shared_ptr<root_object> root_object_ptr;\n boost::unordered_map<std::string, root_object_ptr> prototypes;\n boost::unordered_map<std::string, root_object_ptr> constructors;\n};\n\nclass context::impl {\npublic:\n impl()\n : context(JS_NewContext(Impl::get_runtime(),\n FLUSSPFERD_STACKCHUNKSIZE)),\n destroy(true)\n {\n if(!context)\n throw exception(\"Could not create Spidermonkey Context\");\n\n uint32 options = JS_GetOptions(context);\n\n options |= JSOPTION_VAROBJFIX;\n options |= JSOPTION_STRICT;\n options |= JSOPTION_DONT_REPORT_UNCAUGHT;\n options &= ~JSOPTION_XML;\n\n JS_SetVersion(context, JSVersion(JS_VERSION));\n JS_SetOptions(context, options);\n\n#ifdef JS_THREADSAFE\n JS_BeginRequest(context);\n#endif\n\n JS_SetErrorReporter(context, spidermonkey_error_reporter);\n\n JSObject *global_ = JS_NewObject(context, &global_class, 0x0, 0x0);\n if(!global_)\n throw exception(\"Could not create Global Object\");\n\n \/\/ Set it so that it doesn't get GCd (play it safe)\n JS_SetGlobalObject(context, global_);\n\n if(!JS_InitStandardClasses(context, global_))\n throw exception(\"Could not initialize Global Object\");\n\n JS_DeleteProperty(context, global_, \"XML\");\n\n \/\/ Set the global object as an empty object which has its proto as the\n \/\/ 'true' global object with the std classes on it\n JSObject *pub_global = JS_NewObject(context, &global_class, global_, NULL);\n if(!global_)\n throw exception(\"Could not create Global Shim Object\");\n\n JS_SetGlobalObject(context, pub_global);\n\n JS_SetContextPrivate(context, static_cast<void*>(new context_private));\n }\n\n explicit impl(JSContext *context)\n : context(context), destroy(false)\n { }\n\n ~impl() {\n if (destroy) {\n {\n current_context_scope scope(Impl::wrap_context(context));\n delete get_private();\n JS_DestroyContext(context);\n }\n }\n }\n\n bool is_valid() {\n return context;\n }\n\n context_private *get_private() {\n return static_cast<context_private*>(JS_GetContextPrivate(context));\n }\n\n static void spidermonkey_error_reporter(JSContext *cx, char const *message, JSErrorReport *report) {\n\n if (!report || JSREPORT_IS_EXCEPTION(report->flags)) {\n return;\n }\n\n std::cerr << (JSREPORT_IS_STRICT(report->flags) ? \"Strict warning: \" : \"Warning: \")\n << message;\n\n if (report->filename) {\n std::cerr << \" at \" << report->filename;\n\n if (report->lineno) {\n std::cerr << \":\" << report->lineno;\n }\n }\n std::cerr << std::endl;\n\n }\n\n JSContext *context;\n bool destroy;\n};\n\nstruct context::detail {\n JSContext *c;\n detail(JSContext *ct) : c(ct) { }\n\n static JSContext *get(context &co) {\n return co.p->context;\n }\n};\n\nJSContext *Impl::get_context(context &co) {\n return context::detail::get(co);\n}\n\ncontext Impl::wrap_context(JSContext *c) {\n return context(c);\n}\n\ncontext::context()\n{ }\ncontext::context(context::detail const &d)\n : p(new impl(d.c))\n{\n if (!p->is_valid())\n p.reset();\n}\ncontext::~context() { }\n\ncontext context::create() {\n context c;\n c.p.reset(new impl);\n return c;\n}\n\nbool context::is_valid() const {\n return p;\n}\n\nobject context::global() {\n JSObject *o = JS_GetGlobalObject(p->context);\n if (!o) {\n throw exception(\"No global object\");\n }\n return Impl::wrap_object(o);\n}\n\nobject context::scope_chain() {\n JSObject *o = JS_GetScopeChain(p->context);\n if (!o) {\n \/\/ Weird! In Spidermonkey 1.7, sometimes it seems like JS_GetScopeChain\n \/\/ returns NULL without setting an error.\n \/\/ In that case, we simply return the global object. It caused a problem.\n if (JS_IsExceptionPending(p->context))\n throw exception(\"No scope chain\");\n else\n return this->global();\n }\n return Impl::wrap_object(o);\n}\n\nvoid context::add_prototype(std::string const &name, object const &proto) {\n p->get_private()->prototypes[name] =\n context_private::root_object_ptr(new root_object(proto));\n}\n\nobject context::prototype(std::string const &name) const {\n context_private::root_object_ptr ptr = p->get_private()->prototypes[name];\n return ptr ? *ptr : object();\n}\n\nvoid context::add_constructor(std::string const &name, object const &ctor) {\n p->get_private()->constructors[name] =\n context_private::root_object_ptr(new root_object(ctor));\n}\n\nobject context::constructor(std::string const &name) const {\n context_private::root_object_ptr ptr = p->get_private()->constructors[name];\n return ptr ? *ptr : object();\n}\n\nvoid context::gc() {\n JS_GC(p->context);\n}\n\nvoid context::set_thread() {\n assert(JS_SetContextThread(p->context) == 0);\n}\n\nvoid context::clear_thread() {\n \/\/assert(\n JS_ClearContextThread(p->context);\n \/\/ == js_GetCurrentThread(p->context->runtime)->id);\n}\n<|endoftext|>"} {"text":"<commit_before>\n#pragma GCC diagnostic ignored \"-Wconversion\"\n#include <libdevcrypto\/SHA3.h>\n#include <libevm\/FeeStructure.h>\n#include <libevm\/ExtVMFace.h>\n\n#include \"Utils.h\"\n\nextern \"C\"\n{\n\t#ifdef _MSC_VER\n\t\t#define EXPORT __declspec(dllexport)\n\t#else\n\t\t#define EXPORT\n\t#endif\n\n\tusing namespace dev;\n\tusing namespace dev::eth;\n\tusing jit::i256;\n\n\tEXPORT void env_sload(ExtVMFace* _env, i256* _index, i256* o_value)\n\t{\n\t\tauto index = llvm2eth(*_index);\n\t\tauto value = _env->store(index); \/\/ Interface uses native endianness\n\t\t*o_value = eth2llvm(value);\n\t}\n\n\tEXPORT void env_sstore(ExtVMFace* _env, i256* _index, i256* _value)\n\t{\n\t\tauto index = llvm2eth(*_index);\n\t\tauto value = llvm2eth(*_value);\n\n\t\tif (value == 0 && _env->store(index) != 0)\t\/\/ If delete\n\t\t\t_env->sub.refunds += c_sstoreRefundGas;\t\/\/ Increase refund counter\n\n\t\t_env->setStore(index, value);\t\/\/ Interface uses native endianness\n\t}\n\n\tEXPORT void env_balance(ExtVMFace* _env, h256* _address, i256* o_value)\n\t{\n\t\tauto u = _env->balance(right160(*_address));\n\t\t*o_value = eth2llvm(u);\n\t}\n\n\tEXPORT void env_blockhash(ExtVMFace* _env, i256* _number, h256* o_hash)\n\t{\n\t\t*o_hash = _env->blockhash(llvm2eth(*_number));\n\t}\n\n\tEXPORT void env_create(ExtVMFace* _env, int64_t* io_gas, i256* _endowment, byte* _initBeg, uint64_t _initSize, h256* o_address)\n\t{\n\t\tauto endowment = llvm2eth(*_endowment);\n\t\tif (_env->balance(_env->myAddress) >= endowment && _env->depth < 1024)\n\t\t{\n\t\t\t_env->subBalance(endowment);\n\t\t\tu256 gas = *io_gas;\n\t\t\th256 address(_env->create(endowment, gas, {_initBeg, _initSize}, {}), h256::AlignRight);\n\t\t\t*io_gas = static_cast<int64_t>(gas);\n\t\t\t*o_address = address;\n\t\t}\n\t\telse\n\t\t\t*o_address = {};\n\t}\n\n\tEXPORT bool env_call(ExtVMFace* _env, int64_t* io_gas, h256* _receiveAddress, i256* _value, byte* _inBeg, uint64_t _inSize, byte* _outBeg, uint64_t _outSize, h256* _codeAddress)\n\t{\n\t\tauto value = llvm2eth(*_value);\n\t\tif (_env->balance(_env->myAddress) >= value && _env->depth < 1024)\n\t\t{\n\t\t\t_env->subBalance(value);\n\t\t\tauto receiveAddress = right160(*_receiveAddress);\n\t\t\tauto inRef = bytesConstRef{_inBeg, _inSize};\n\t\t\tauto outRef = bytesRef{_outBeg, _outSize};\n\t\t\tauto codeAddress = right160(*_codeAddress);\n\t\t\tu256 gas = *io_gas;\n\t\t\tauto ret = _env->call(receiveAddress, value, inRef, gas, outRef, {}, {}, codeAddress);\n\t\t\t*io_gas = static_cast<int64_t>(gas);\n\t\t\treturn ret;\n\t\t}\n\n\t\treturn false;\n\t}\n\n\tEXPORT void env_sha3(byte* _begin, uint64_t _size, h256* o_hash)\n\t{\n\t\tauto hash = sha3({_begin, _size});\n\t\t*o_hash = hash;\n\t}\n\n\tEXPORT byte const* env_extcode(ExtVMFace* _env, h256* _addr256, uint64_t* o_size)\n\t{\n\t\tauto addr = right160(*_addr256);\n\t\tauto& code = _env->codeAt(addr);\n\t\t*o_size = code.size();\n\t\treturn code.data();\n\t}\n\n\tEXPORT void env_log(ExtVMFace* _env, byte* _beg, uint64_t _size, h256* _topic1, h256* _topic2, h256* _topic3, h256* _topic4)\n\t{\n\t\tdev::h256s topics;\n\n\t\tif (_topic1)\n\t\t\ttopics.push_back(*_topic1);\n\n\t\tif (_topic2)\n\t\t\ttopics.push_back(*_topic2);\n\n\t\tif (_topic3)\n\t\t\ttopics.push_back(*_topic3);\n\n\t\tif (_topic4)\n\t\t\ttopics.push_back(*_topic4);\n\n\t\t_env->log(std::move(topics), {_beg, _size});\n\t}\n}\n\n<commit_msg>fix evmjit build<commit_after>\n#pragma GCC diagnostic ignored \"-Wconversion\"\n#include <libdevcrypto\/SHA3.h>\n#include <libethcore\/Params.h>\n#include <libevm\/ExtVMFace.h>\n\n#include \"Utils.h\"\n\nextern \"C\"\n{\n\t#ifdef _MSC_VER\n\t\t#define EXPORT __declspec(dllexport)\n\t#else\n\t\t#define EXPORT\n\t#endif\n\n\tusing namespace dev;\n\tusing namespace dev::eth;\n\tusing jit::i256;\n\n\tEXPORT void env_sload(ExtVMFace* _env, i256* _index, i256* o_value)\n\t{\n\t\tauto index = llvm2eth(*_index);\n\t\tauto value = _env->store(index); \/\/ Interface uses native endianness\n\t\t*o_value = eth2llvm(value);\n\t}\n\n\tEXPORT void env_sstore(ExtVMFace* _env, i256* _index, i256* _value)\n\t{\n\t\tauto index = llvm2eth(*_index);\n\t\tauto value = llvm2eth(*_value);\n\n\t\tif (value == 0 && _env->store(index) != 0)\t\/\/ If delete\n\t\t\t_env->sub.refunds += c_sstoreRefundGas;\t\/\/ Increase refund counter\n\n\t\t_env->setStore(index, value);\t\/\/ Interface uses native endianness\n\t}\n\n\tEXPORT void env_balance(ExtVMFace* _env, h256* _address, i256* o_value)\n\t{\n\t\tauto u = _env->balance(right160(*_address));\n\t\t*o_value = eth2llvm(u);\n\t}\n\n\tEXPORT void env_blockhash(ExtVMFace* _env, i256* _number, h256* o_hash)\n\t{\n\t\t*o_hash = _env->blockhash(llvm2eth(*_number));\n\t}\n\n\tEXPORT void env_create(ExtVMFace* _env, int64_t* io_gas, i256* _endowment, byte* _initBeg, uint64_t _initSize, h256* o_address)\n\t{\n\t\tauto endowment = llvm2eth(*_endowment);\n\t\tif (_env->balance(_env->myAddress) >= endowment && _env->depth < 1024)\n\t\t{\n\t\t\t_env->subBalance(endowment);\n\t\t\tu256 gas = *io_gas;\n\t\t\th256 address(_env->create(endowment, gas, {_initBeg, _initSize}, {}), h256::AlignRight);\n\t\t\t*io_gas = static_cast<int64_t>(gas);\n\t\t\t*o_address = address;\n\t\t}\n\t\telse\n\t\t\t*o_address = {};\n\t}\n\n\tEXPORT bool env_call(ExtVMFace* _env, int64_t* io_gas, h256* _receiveAddress, i256* _value, byte* _inBeg, uint64_t _inSize, byte* _outBeg, uint64_t _outSize, h256* _codeAddress)\n\t{\n\t\tauto value = llvm2eth(*_value);\n\t\tif (_env->balance(_env->myAddress) >= value && _env->depth < 1024)\n\t\t{\n\t\t\t_env->subBalance(value);\n\t\t\tauto receiveAddress = right160(*_receiveAddress);\n\t\t\tauto inRef = bytesConstRef{_inBeg, _inSize};\n\t\t\tauto outRef = bytesRef{_outBeg, _outSize};\n\t\t\tauto codeAddress = right160(*_codeAddress);\n\t\t\tu256 gas = *io_gas;\n\t\t\tauto ret = _env->call(receiveAddress, value, inRef, gas, outRef, {}, {}, codeAddress);\n\t\t\t*io_gas = static_cast<int64_t>(gas);\n\t\t\treturn ret;\n\t\t}\n\n\t\treturn false;\n\t}\n\n\tEXPORT void env_sha3(byte* _begin, uint64_t _size, h256* o_hash)\n\t{\n\t\tauto hash = sha3({_begin, _size});\n\t\t*o_hash = hash;\n\t}\n\n\tEXPORT byte const* env_extcode(ExtVMFace* _env, h256* _addr256, uint64_t* o_size)\n\t{\n\t\tauto addr = right160(*_addr256);\n\t\tauto& code = _env->codeAt(addr);\n\t\t*o_size = code.size();\n\t\treturn code.data();\n\t}\n\n\tEXPORT void env_log(ExtVMFace* _env, byte* _beg, uint64_t _size, h256* _topic1, h256* _topic2, h256* _topic3, h256* _topic4)\n\t{\n\t\tdev::h256s topics;\n\n\t\tif (_topic1)\n\t\t\ttopics.push_back(*_topic1);\n\n\t\tif (_topic2)\n\t\t\ttopics.push_back(*_topic2);\n\n\t\tif (_topic3)\n\t\t\ttopics.push_back(*_topic3);\n\n\t\tif (_topic4)\n\t\t\ttopics.push_back(*_topic4);\n\n\t\t_env->log(std::move(topics), {_beg, _size});\n\t}\n}\n\n<|endoftext|>"} {"text":"<commit_before>#include \"problemes.h\"\n#include \"combinatoire.h\"\n#include \"utilitaires.h\"\n#include \"chiffres.h\"\n#include \"timer.h\"\n\ntypedef unsigned long long nombre;\n\nnamespace {\n nombre g(nombre n, nombre m) {\n nombre c = combinatoire::coefficient_binomial(n, m);\n nombre k = 0;\n while (c % 2 == 0) {\n ++k;\n c >>= 1;\n }\n\n return k;\n }\n\n nombre F(nombre n) {\n size_t m = n + 1;\n size_t resultat = 0;\n for (size_t f = 2; f <= m; f *= 2) {\n resultat += (m % f != 0);\n }\n\n return resultat;\n }\n\n nombre S(nombre N) {\n \/\/ size_t resultat = 0;\n \/\/ for (size_t m = 2; m <= N + 1; ++m) {\n \/\/ for (size_t f = 2; f <= m; f *= 2) {\n \/\/ resultat += (m % f != 0);\n \/\/ }\n \/\/ }\n \/\/\n \/\/ return resultat;\n\n size_t L = N + 1;\n size_t resultat = 0;\n for (size_t f = 2; f < L; f *= 2) {\n resultat += L - (L \/ f + (f - 1));\n }\n\n return resultat;\n }\n}\n\nENREGISTRER_PROBLEME(704, \"Eulercoin\") {\n \/\/ Define g(n, m) to be the largest integer k such that 2^k divides (n, m). For example,\n \/\/ (12 5) = 792 = 2^3 x 3² x 11, hence g(12, 5).\n \/\/\n \/\/ Then define F(n) = { max(g(n, m) : 0 <= m <= n }. F(10) = 3 and F(100) = 6.\n \/\/\n \/\/ Let S(N) = Sum_n=1..N F(n). You are given that S(100) = 389 and S(10'000'000) = 203222840.\n \/\/\n \/\/ Find S(10^16).\n std::cout << \"g(12, 5) = \" << g(12, 5) << std::endl;\n std::cout << \"F(10) = \" << F(10) << std::endl;\n std::cout << \"F(100) = \" << F(100) << std::endl;\n std::cout << \"S(100) = \" << S(100) << std::endl;\n std::cout << \"S(10'000'000) = \" << S(10'000'000) << std::endl;\n\n \/\/ for (size_t n = 0; n < 30; ++n) {\n \/\/ std::cout << n << '\\t';\n \/\/ std::cout << std::string(30 - n, ' ');\n \/\/ for (size_t p = 0; p <= n; ++p) {\n \/\/ std::cout << g(n, p) << ' ';\n \/\/ }\n \/\/ nombre ligne = n;\n \/\/ auto c = chiffres::extraire_chiffres(ligne, 2);\n \/\/ std::cout << std::string(30 - n, ' ')\n \/\/ << F(n) << \" \"\n \/\/ << \" (\"\n \/\/ << std::count(c.begin(), c.end(), 0) << \", \"\n \/\/ << std::count(c.begin(), c.end(), 1) << ')'\n \/\/ << \"\\t\" << c << std::endl;\n \/\/ }\n\n size_t resultat = S(puissance::puissance<size_t>(10, 16u));\n return std::to_string(resultat);\n}\n<commit_msg>Update probleme704.cpp<commit_after>#include \"problemes.h\"\n#include \"combinatoire.h\"\n#include \"utilitaires.h\"\n#include \"chiffres.h\"\n#include \"timer.h\"\n\ntypedef unsigned long long nombre;\n\nnamespace {\n nombre g(nombre n, nombre m) {\n nombre c = combinatoire::coefficient_binomial(n, m);\n nombre k = 0;\n while (c % 2 == 0) {\n ++k;\n c >>= 1u;\n }\n\n return k;\n }\n\n nombre F(nombre n) {\n size_t m = n + 1;\n size_t resultat = 0;\n for (size_t f = 2; f <= m; f *= 2) {\n resultat += (m % f != 0);\n }\n\n return resultat;\n }\n\n nombre S(nombre N) {\n \/\/ size_t resultat = 0;\n \/\/ for (size_t m = 2; m <= N + 1; ++m) {\n \/\/ for (size_t f = 2; f <= m; f *= 2) {\n \/\/ resultat += (m % f != 0);\n \/\/ }\n \/\/ }\n \/\/\n \/\/ return resultat;\n\n size_t L = N + 1;\n size_t resultat = 0;\n for (size_t f = 2; f < L; f *= 2) {\n resultat += L - (L \/ f + (f - 1));\n }\n\n return resultat;\n }\n}\n\nENREGISTRER_PROBLEME(704, \"Eulercoin\") {\n \/\/ Define g(n, m) to be the largest integer k such that 2^k divides (n, m). For example,\n \/\/ (12 5) = 792 = 2^3 x 3² x 11, hence g(12, 5).\n \/\/\n \/\/ Then define F(n) = { max(g(n, m) : 0 <= m <= n }. F(10) = 3 and F(100) = 6.\n \/\/\n \/\/ Let S(N) = Sum_n=1..N F(n). You are given that S(100) = 389 and S(10'000'000) = 203222840.\n \/\/\n \/\/ Find S(10^16).\n std::cout << \"g(12, 5) = \" << g(12, 5) << std::endl;\n std::cout << \"F(10) = \" << F(10) << std::endl;\n std::cout << \"F(100) = \" << F(100) << std::endl;\n std::cout << \"S(100) = \" << S(100) << std::endl;\n std::cout << \"S(10'000'000) = \" << S(10'000'000) << std::endl;\n\n \/\/ for (size_t n = 0; n < 30; ++n) {\n \/\/ std::cout << n << '\\t';\n \/\/ std::cout << std::string(30 - n, ' ');\n \/\/ for (size_t p = 0; p <= n; ++p) {\n \/\/ std::cout << g(n, p) << ' ';\n \/\/ }\n \/\/ nombre ligne = n;\n \/\/ auto c = chiffres::extraire_chiffres(ligne, 2);\n \/\/ std::cout << std::string(30 - n, ' ')\n \/\/ << F(n) << \" \"\n \/\/ << \" (\"\n \/\/ << std::count(c.begin(), c.end(), 0) << \", \"\n \/\/ << std::count(c.begin(), c.end(), 1) << ')'\n \/\/ << \"\\t\" << c << std::endl;\n \/\/ }\n\n size_t resultat = S(puissance::puissance<size_t>(10, 16u));\n return std::to_string(resultat);\n}\n<|endoftext|>"} {"text":"<commit_before>#ifndef BBPROJECTMANAGERCONSTANTS_HPP_INCLUDED\n#define BBPROJECTMANAGERCONSTANTS_HPP_INCLUDED\n\nnamespace BoostBuildProjectManager {\nnamespace Constants {\n\nchar const PROJECT_CONTEXT[] = \"BoostBuildProjectManager.ProjectContext\";\nchar const PROJECT_ID[] = \"BoostBuildProjectManager.BoostBuildProject\";\n\nchar const MIMETYPE_PROJECT[] = \"text\/x-boostbuild-project\";\nchar const MIMETYPE_JAMFILE[] = \"application\/vnd.boostbuild.v2\";\nchar const MIMETYPE_FILES[] = \"application\/vnd.boostbuild.files\";\n\n} \/\/ namespace Constants\n} \/\/ namespace BoostBuildProjectManager\n\n#endif \/\/ BBPROJECTMANAGERCONSTANTS_HPP_INCLUDED\n<commit_msg>Tweak mimetype for Jamfile.v2.files<commit_after>#ifndef BBPROJECTMANAGERCONSTANTS_HPP_INCLUDED\n#define BBPROJECTMANAGERCONSTANTS_HPP_INCLUDED\n\nnamespace BoostBuildProjectManager {\nnamespace Constants {\n\nchar const PROJECT_CONTEXT[] = \"BoostBuildProjectManager.ProjectContext\";\nchar const PROJECT_ID[] = \"BoostBuildProjectManager.BoostBuildProject\";\n\nchar const MIMETYPE_PROJECT[] = \"text\/x-boostbuild-project\";\nchar const MIMETYPE_JAMFILE[] = \"application\/vnd.boostbuild.v2\";\nchar const MIMETYPE_FILES[] = \"application\/vnd.qtcreator.boostbuild.files\";\n\n} \/\/ namespace Constants\n} \/\/ namespace BoostBuildProjectManager\n\n#endif \/\/ BBPROJECTMANAGERCONSTANTS_HPP_INCLUDED\n<|endoftext|>"} {"text":"<commit_before>\/**\n * @file\n * @author Jason Lingle\n * @date 2012.02.06\n * @brief Implementation of the GameAdvertiser class\n *\/\n\n#include <cstring>\n#include <iostream>\n#include <vector>\n\n#include \"game_advertiser.hxx\"\n#include \"antenna.hxx\"\n#include \"tuner.hxx\"\n#include \"abuhops.hxx\"\n#include \"io.hxx\"\n\nusing namespace std;\n\nstatic const byte trigger[] = {'A', 'b', 'e', 'n', 'd', 's', 'u', 'c', 'h'};\n\nGameAdvertiser::GameAdvertiser(Tuner* tuner_,\n bool v6_,\n Uint32 overseerid_,\n byte peerCount_,\n bool passwordProtected_,\n const char* gameMode_,\n bool isInternet_)\n: tuner(tuner_), v6(v6_),\n overseerid(overseerid_),\n peerCount(peerCount_),\n passwordProtected(passwordProtected_),\n isInternet(isInternet_)\n{\n setGameMode(gameMode_);\n if (!isInternet)\n tuner->trigger(trigger, sizeof(trigger), this);\n}\n\nGameAdvertiser::~GameAdvertiser() {\n if (!isInternet)\n tuner->untrigger(trigger, sizeof(trigger));\n}\n\nvoid GameAdvertiser::setOverseerId(Uint32 oid) {\n overseerid = oid;\n postIfNeeded();\n}\n\nvoid GameAdvertiser::setPeerCount(byte cnt) {\n peerCount = cnt;\n postIfNeeded();\n}\n\nvoid GameAdvertiser::setGameMode(const char* mode) {\n strncpy(gameMode, mode, 4);\n postIfNeeded();\n}\n\nvoid GameAdvertiser::process(const Antenna::endpoint& source,\n Antenna* antenna, Tuner* tuner,\n const byte* data, unsigned len)\nnoth {\n \/\/Ignore if it is the wrong protocol, or this is an Internet game\n if (v6 == (source.protocol() == asio::ip::udp::v6()) && !isInternet) {\n \/\/OK\n byte pack[] = {\n 'A', 'b', 'e', 'n', 'd', 's', 'p', 'i', 'e', 'l',\n (byte)(overseerid >> 24),\n (byte)(overseerid >> 16),\n (byte)(overseerid >> 8),\n (byte)(overseerid >> 0),\n peerCount, passwordProtected,\n (byte)gameMode[0], (byte)gameMode[1],\n (byte)gameMode[2], (byte)gameMode[3],\n };\n try {\n antenna->send(source, pack, sizeof(pack));\n } catch (asio::system_error e) {\n cerr << \"Warning: Unable to respond to Abendsuch from \" << source\n << \": \" << e.what() << endl;\n }\n }\n}\n\nvoid GameAdvertiser::postIfNeeded() {\n if (isInternet) {\n vector<byte> pack(10 + 4 + 2 + 2*(v6? 8*2+2 : 4+2) + 4);\n memcpy(&pack[0], \"Abendspiel\", 10);\n byte* dst = &pack[10];\n io::write(dst, overseerid);\n io::write(dst, peerCount);\n io::write(dst, (byte)v6);\n if (v6) {\n GlobalID& gid(*antenna.getGlobalID6());\n io::a6fromhbo(dst, gid.la6);\n dst += 2*8;\n io::write(dst, gid.lport);\n io::a6fromhbo(dst, gid.ia6);\n dst += 2*8;\n io::write(dst, gid.iport);\n } else {\n GlobalID& gid(*antenna.getGlobalID4());\n memcpy(dst, gid.la4, 4);\n dst += 4;\n io::write(dst, gid.lport);\n memcpy(dst, gid.ia4, 4);\n dst += 4;\n io::write(dst, gid.iport);\n }\n\n memcpy(dst, gameMode, sizeof(gameMode));\n\n abuhops::post(v6, &pack[0], pack.size());\n }\n}\n<commit_msg>Fix byte order of OID in Abendspiel LAN packets.<commit_after>\/**\n * @file\n * @author Jason Lingle\n * @date 2012.02.06\n * @brief Implementation of the GameAdvertiser class\n *\/\n\n#include <cstring>\n#include <iostream>\n#include <vector>\n\n#include \"game_advertiser.hxx\"\n#include \"antenna.hxx\"\n#include \"tuner.hxx\"\n#include \"abuhops.hxx\"\n#include \"io.hxx\"\n\nusing namespace std;\n\nstatic const byte trigger[] = {'A', 'b', 'e', 'n', 'd', 's', 'u', 'c', 'h'};\n\nGameAdvertiser::GameAdvertiser(Tuner* tuner_,\n bool v6_,\n Uint32 overseerid_,\n byte peerCount_,\n bool passwordProtected_,\n const char* gameMode_,\n bool isInternet_)\n: tuner(tuner_), v6(v6_),\n overseerid(overseerid_),\n peerCount(peerCount_),\n passwordProtected(passwordProtected_),\n isInternet(isInternet_)\n{\n setGameMode(gameMode_);\n if (!isInternet)\n tuner->trigger(trigger, sizeof(trigger), this);\n}\n\nGameAdvertiser::~GameAdvertiser() {\n if (!isInternet)\n tuner->untrigger(trigger, sizeof(trigger));\n}\n\nvoid GameAdvertiser::setOverseerId(Uint32 oid) {\n overseerid = oid;\n postIfNeeded();\n}\n\nvoid GameAdvertiser::setPeerCount(byte cnt) {\n peerCount = cnt;\n postIfNeeded();\n}\n\nvoid GameAdvertiser::setGameMode(const char* mode) {\n strncpy(gameMode, mode, 4);\n postIfNeeded();\n}\n\nvoid GameAdvertiser::process(const Antenna::endpoint& source,\n Antenna* antenna, Tuner* tuner,\n const byte* data, unsigned len)\nnoth {\n \/\/Ignore if it is the wrong protocol, or this is an Internet game\n if (v6 == (source.protocol() == asio::ip::udp::v6()) && !isInternet) {\n \/\/OK\n byte pack[] = {\n 'A', 'b', 'e', 'n', 'd', 's', 'p', 'i', 'e', 'l',\n (byte)(overseerid >> 0),\n (byte)(overseerid >> 8),\n (byte)(overseerid >> 16),\n (byte)(overseerid >> 24),\n peerCount, passwordProtected,\n (byte)gameMode[0], (byte)gameMode[1],\n (byte)gameMode[2], (byte)gameMode[3],\n };\n try {\n antenna->send(source, pack, sizeof(pack));\n } catch (asio::system_error e) {\n cerr << \"Warning: Unable to respond to Abendsuch from \" << source\n << \": \" << e.what() << endl;\n }\n }\n}\n\nvoid GameAdvertiser::postIfNeeded() {\n if (isInternet) {\n vector<byte> pack(10 + 4 + 2 + 2*(v6? 8*2+2 : 4+2) + 4);\n memcpy(&pack[0], \"Abendspiel\", 10);\n byte* dst = &pack[10];\n io::write(dst, overseerid);\n io::write(dst, peerCount);\n io::write(dst, (byte)v6);\n if (v6) {\n GlobalID& gid(*antenna.getGlobalID6());\n io::a6fromhbo(dst, gid.la6);\n dst += 2*8;\n io::write(dst, gid.lport);\n io::a6fromhbo(dst, gid.ia6);\n dst += 2*8;\n io::write(dst, gid.iport);\n } else {\n GlobalID& gid(*antenna.getGlobalID4());\n memcpy(dst, gid.la4, 4);\n dst += 4;\n io::write(dst, gid.lport);\n memcpy(dst, gid.ia4, 4);\n dst += 4;\n io::write(dst, gid.iport);\n }\n\n memcpy(dst, gameMode, sizeof(gameMode));\n\n abuhops::post(v6, &pack[0], pack.size());\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Copyright 2017 Realm Inc.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"sync\/sync_permission.hpp\"\n\n#include \"impl\/notification_wrapper.hpp\"\n#include \"impl\/object_accessor_impl.hpp\"\n#include \"object_schema.hpp\"\n#include \"property.hpp\"\n\n#include \"sync\/sync_config.hpp\"\n#include \"sync\/sync_manager.hpp\"\n#include \"sync\/sync_session.hpp\"\n#include \"sync\/sync_user.hpp\"\n#include \"util\/event_loop_signal.hpp\"\n#include \"util\/uuid.hpp\"\n\n#include <realm\/query_expression.hpp>\n\nusing namespace realm;\nusing namespace std::chrono;\n\n\/\/ MARK: - Utility\n\nnamespace {\n\n\/\/ Make a handler that extracts either an exception pointer, or the string value\n\/\/ of the property with the specified name.\nPermissions::AsyncOperationHandler make_handler_extracting_property(std::string property,\n Permissions::PermissionOfferCallback callback)\n{\n return [property=std::move(property),\n callback=std::move(callback)](Object* object, std::exception_ptr exception) {\n if (exception) {\n callback(none, exception);\n } else {\n CppContext context;\n auto token = any_cast<std::string>(object->get_property_value<util::Any>(context, property));\n callback(util::make_optional<std::string>(std::move(token)), nullptr);\n }\n };\n}\n\nAccessLevel extract_access_level(Object& permission, CppContext& context)\n{\n auto may_manage = permission.get_property_value<util::Any>(context, \"mayManage\");\n if (may_manage.has_value() && any_cast<bool>(may_manage))\n return AccessLevel::Admin;\n\n auto may_write = permission.get_property_value<util::Any>(context, \"mayWrite\");\n if (may_write.has_value() && any_cast<bool>(may_write))\n return AccessLevel::Write;\n\n auto may_read = permission.get_property_value<util::Any>(context, \"mayRead\");\n if (may_read.has_value() && any_cast<bool>(may_read))\n return AccessLevel::Read;\n\n return AccessLevel::None;\n}\n\n\/\/\/ Turn a system time point value into the 64-bit integer representing ns since the Unix epoch.\nint64_t ns_since_unix_epoch(const system_clock::time_point& point)\n{\n tm unix_epoch{};\n unix_epoch.tm_year = 70;\n time_t epoch_time = mktime(&unix_epoch);\n auto epoch_point = system_clock::from_time_t(epoch_time);\n return duration_cast<nanoseconds>(point - epoch_point).count();\n}\n\n} \/\/ anonymous namespace\n\n\/\/ MARK: - Permission\n\nPermission::Permission(Object& permission)\n{\n CppContext context;\n path = any_cast<std::string>(permission.get_property_value<util::Any>(context, \"path\"));\n access = extract_access_level(permission, context);\n condition = Condition(any_cast<std::string>(permission.get_property_value<util::Any>(context, \"userId\")));\n updated_at = any_cast<Timestamp>(permission.get_property_value<util::Any>(context, \"updatedAt\"));\n}\n\nPermission::Permission(std::string path, AccessLevel access, Condition condition, Timestamp updated_at)\n: path(std::move(path))\n, access(access)\n, condition(std::move(condition))\n, updated_at(std::move(updated_at))\n{ }\n\nstd::string Permission::description_for_access_level(AccessLevel level)\n{\n switch (level) {\n case AccessLevel::None: return \"none\";\n case AccessLevel::Read: return \"read\";\n case AccessLevel::Write: return \"write\";\n case AccessLevel::Admin: return \"admin\";\n }\n REALM_UNREACHABLE();\n}\n\nbool Permission::paths_are_equivalent(std::string path_1, std::string path_2,\n const std::string& user_id_1, const std::string& user_id_2)\n{\n REALM_ASSERT_DEBUG(path_1.length() > 0);\n REALM_ASSERT_DEBUG(path_2.length() > 0);\n if (path_1 == path_2) {\n \/\/ If both paths are identical and contain `\/~\/`, the user IDs must match.\n return (path_1.find(\"\/~\/\") == std::string::npos) || (user_id_1 == user_id_2);\n }\n \/\/ Make substitutions for the first `\/~\/` in the string.\n size_t index = path_1.find(\"\/~\/\");\n if (index != std::string::npos)\n path_1.replace(index + 1, 1, user_id_1);\n\n index = path_2.find(\"\/~\/\");\n if (index != std::string::npos)\n path_2.replace(index + 1, 1, user_id_2);\n\n return path_1 == path_2;\n}\n\n\/\/ MARK: - Permissions\n\nvoid Permissions::get_permissions(std::shared_ptr<SyncUser> user,\n PermissionResultsCallback callback,\n const ConfigMaker& make_config)\n{\n auto realm = Permissions::permission_realm(user, make_config);\n auto table = ObjectStore::table_for_object_type(realm->read_group(), \"Permission\");\n auto results = std::make_shared<_impl::NotificationWrapper<Results>>(std::move(realm), *table);\n\n \/\/ `get_permissions` works by temporarily adding an async notifier to the permission Realm.\n \/\/ This notifier will run the `async` callback until the Realm contains permissions or\n \/\/ an error happens. When either of these two things happen, the notifier will be\n \/\/ unregistered by nulling out the `results_wrapper` container.\n auto async = [results, callback=std::move(callback)](CollectionChangeSet, std::exception_ptr ex) mutable {\n if (ex) {\n callback(Results(), ex);\n results.reset();\n return;\n }\n if (results->size() > 0) {\n \/\/ We monitor the raw results. The presence of a `__management` Realm indicates\n \/\/ that the permissions have been downloaded (hence, we wait until size > 0).\n TableRef table = ObjectStore::table_for_object_type(results->get_realm()->read_group(), \"Permission\");\n size_t col_idx = table->get_descriptor()->get_column_index(\"path\");\n auto query = !(table->column<StringData>(col_idx).ends_with(\"\/__permission\")\n || table->column<StringData>(col_idx).ends_with(\"\/__management\"));\n \/\/ Call the callback with our new permissions object. This object will exclude the\n \/\/ private Realms.\n callback(results->filter(std::move(query)), nullptr);\n results.reset();\n }\n };\n results->add_notification_callback(std::move(async));\n}\n\nvoid Permissions::set_permission(std::shared_ptr<SyncUser> user,\n Permission permission,\n PermissionChangeCallback callback,\n const ConfigMaker& make_config)\n{\n auto props = AnyDict{\n {\"userId\", permission.condition.user_id},\n {\"realmUrl\", user->server_url() + permission.path},\n {\"mayRead\", permission.access != AccessLevel::None},\n {\"mayWrite\", permission.access == AccessLevel::Write || permission.access == AccessLevel::Admin},\n {\"mayManage\", permission.access == AccessLevel::Admin},\n };\n if (permission.condition.type == Permission::Condition::Type::KeyValue) {\n props.insert({\"metadataKey\", permission.condition.key_value.first});\n props.insert({\"metadataValue\", permission.condition.key_value.second});\n }\n auto cb = [callback=std::move(callback)](Object*, std::exception_ptr exception) {\n callback(exception);\n };\n perform_async_operation(\"PermissionChange\", std::move(user), std::move(cb), std::move(props), make_config);\n}\n\nvoid Permissions::delete_permission(std::shared_ptr<SyncUser> user,\n Permission permission,\n PermissionChangeCallback callback,\n const ConfigMaker& make_config)\n{\n permission.access = AccessLevel::None;\n set_permission(std::move(user), std::move(permission), std::move(callback), make_config);\n}\n\nvoid Permissions::make_offer(std::shared_ptr<SyncUser> user,\n PermissionOffer offer,\n PermissionOfferCallback callback,\n const ConfigMaker& make_config)\n{\n auto props = AnyDict{\n {\"expiresAt\", std::move(offer.expiration)},\n {\"userId\", user->identity()},\n {\"realmUrl\", user->server_url() + offer.path},\n {\"mayRead\", offer.access != AccessLevel::None},\n {\"mayWrite\", offer.access == AccessLevel::Write || offer.access == AccessLevel::Admin},\n {\"mayManage\", offer.access == AccessLevel::Admin},\n };\n perform_async_operation(\"PermissionOffer\",\n std::move(user),\n make_handler_extracting_property(\"token\", std::move(callback)),\n std::move(props),\n make_config);\n}\n\nvoid Permissions::accept_offer(std::shared_ptr<SyncUser> user,\n const std::string& token,\n PermissionOfferCallback callback,\n const ConfigMaker& make_config)\n{\n perform_async_operation(\"PermissionOfferResponse\",\n std::move(user),\n make_handler_extracting_property(\"realmUrl\", std::move(callback)),\n AnyDict{ {\"token\", token} },\n make_config);\n}\n\nvoid Permissions::perform_async_operation(const std::string& object_type,\n std::shared_ptr<SyncUser> user,\n AsyncOperationHandler handler,\n AnyDict additional_props,\n const ConfigMaker& make_config)\n{;\n auto realm = Permissions::management_realm(std::move(user), make_config);\n CppContext context;\n\n \/\/ Get the current time.\n int64_t ns_since_epoch = ns_since_unix_epoch(system_clock::now());\n int64_t s_arg = ns_since_epoch \/ (int64_t)Timestamp::nanoseconds_per_second;\n int32_t ns_arg = ns_since_epoch % Timestamp::nanoseconds_per_second;\n\n auto props = AnyDict{\n {\"id\", util::uuid_string()},\n {\"createdAt\", Timestamp(s_arg, ns_arg)},\n {\"updatedAt\", Timestamp(s_arg, ns_arg)},\n };\n props.insert(additional_props.begin(), additional_props.end());\n\n \/\/ Write the permission object.\n realm->begin_transaction();\n auto raw = Object::create<util::Any>(context, realm, *realm->schema().find(object_type), std::move(props), false);\n auto object = std::make_shared<_impl::NotificationWrapper<Object>>(std::move(raw));\n realm->commit_transaction();\n\n \/\/ Observe the permission object until the permission change has been processed or failed.\n \/\/ The notifier is automatically unregistered upon the completion of the permission\n \/\/ change, one way or another.\n auto block = [object, handler=std::move(handler)](CollectionChangeSet, std::exception_ptr ex) mutable {\n if (ex) {\n handler(nullptr, ex);\n object.reset();\n return;\n }\n\n CppContext context;\n auto status_code = object->get_property_value<util::Any>(context, \"statusCode\");\n if (!status_code.has_value()) {\n \/\/ Continue waiting for the sync server to complete the operation.\n return;\n }\n\n \/\/ Determine whether an error happened or not.\n if (auto code = any_cast<long long>(status_code)) {\n \/\/ The permission change failed because an error was returned from the server.\n auto status = object->get_property_value<util::Any>(context, \"statusMessage\");\n std::string error_str = (status.has_value()\n ? any_cast<std::string>(status)\n : util::format(\"Error code: %1\", code));\n handler(nullptr, std::make_exception_ptr(PermissionActionException(error_str, code)));\n }\n else {\n handler(object.get(), nullptr);\n }\n object.reset();\n };\n object->add_notification_callback(std::move(block));\n}\n\nSharedRealm Permissions::management_realm(std::shared_ptr<SyncUser> user, const ConfigMaker& make_config)\n{\n \/\/ FIXME: maybe we should cache the management Realm on the user, so we don't need to open it every time.\n const auto realm_url = util::format(\"realm%1\/~\/__management\", user->server_url().substr(4));\n Realm::Config config = make_config(user, std::move(realm_url));\n config.sync_config->stop_policy = SyncSessionStopPolicy::Immediately;\n config.schema = Schema{\n {\"PermissionChange\", {\n Property{\"id\", PropertyType::String, Property::IsPrimary{true}},\n Property{\"createdAt\", PropertyType::Date},\n Property{\"updatedAt\", PropertyType::Date},\n Property{\"statusCode\", PropertyType::Int|PropertyType::Nullable},\n Property{\"statusMessage\", PropertyType::String|PropertyType::Nullable},\n Property{\"userId\", PropertyType::String},\n Property{\"metadataKey\", PropertyType::String|PropertyType::Nullable},\n Property{\"metadataValue\", PropertyType::String|PropertyType::Nullable},\n Property{\"metadataNameSpace\", PropertyType::String|PropertyType::Nullable},\n Property{\"realmUrl\", PropertyType::String},\n Property{\"mayRead\", PropertyType::Bool|PropertyType::Nullable},\n Property{\"mayWrite\", PropertyType::Bool|PropertyType::Nullable},\n Property{\"mayManage\", PropertyType::Bool|PropertyType::Nullable},\n }},\n {\"PermissionOffer\", {\n Property{\"id\", PropertyType::String, Property::IsPrimary{true}},\n Property{\"createdAt\", PropertyType::Date},\n Property{\"updatedAt\", PropertyType::Date},\n Property{\"expiresAt\", PropertyType::Date|PropertyType::Nullable},\n Property{\"statusCode\", PropertyType::Int|PropertyType::Nullable},\n Property{\"statusMessage\", PropertyType::String|PropertyType::Nullable},\n Property{\"token\", PropertyType::String|PropertyType::Nullable},\n Property{\"realmUrl\", PropertyType::String},\n Property{\"mayRead\", PropertyType::Bool},\n Property{\"mayWrite\", PropertyType::Bool},\n Property{\"mayManage\", PropertyType::Bool},\n }},\n {\"PermissionOfferResponse\", {\n Property{\"id\", PropertyType::String, Property::IsPrimary{true}},\n Property{\"createdAt\", PropertyType::Date},\n Property{\"updatedAt\", PropertyType::Date},\n Property{\"statusCode\", PropertyType::Int|PropertyType::Nullable},\n Property{\"statusMessage\", PropertyType::String|PropertyType::Nullable},\n Property{\"token\", PropertyType::String},\n Property{\"realmUrl\", PropertyType::String|PropertyType::Nullable},\n }},\n };\n config.schema_version = 0;\n auto shared_realm = Realm::get_shared_realm(std::move(config));\n user->register_management_session(config.path);\n return shared_realm;\n}\n\nSharedRealm Permissions::permission_realm(std::shared_ptr<SyncUser> user, const ConfigMaker& make_config)\n{\n \/\/ FIXME: maybe we should cache the permission Realm on the user, so we don't need to open it every time.\n const auto realm_url = util::format(\"realm%1\/~\/__permission\", user->server_url().substr(4));\n Realm::Config config = make_config(user, std::move(realm_url));\n config.sync_config->stop_policy = SyncSessionStopPolicy::Immediately;\n config.schema = Schema{\n {\"Permission\", {\n {\"updatedAt\", PropertyType::Date},\n {\"userId\", PropertyType::String},\n {\"path\", PropertyType::String},\n {\"mayRead\", PropertyType::Bool},\n {\"mayWrite\", PropertyType::Bool},\n {\"mayManage\", PropertyType::Bool},\n }}\n };\n config.schema_version = 0;\n auto shared_realm = Realm::get_shared_realm(std::move(config));\n user->register_permission_session(config.path);\n return shared_realm;\n}\n<commit_msg>Fix two use-after-move issues flagged in sync-related code<commit_after>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Copyright 2017 Realm Inc.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"sync\/sync_permission.hpp\"\n\n#include \"impl\/notification_wrapper.hpp\"\n#include \"impl\/object_accessor_impl.hpp\"\n#include \"object_schema.hpp\"\n#include \"property.hpp\"\n\n#include \"sync\/sync_config.hpp\"\n#include \"sync\/sync_manager.hpp\"\n#include \"sync\/sync_session.hpp\"\n#include \"sync\/sync_user.hpp\"\n#include \"util\/event_loop_signal.hpp\"\n#include \"util\/uuid.hpp\"\n\n#include <realm\/query_expression.hpp>\n\nusing namespace realm;\nusing namespace std::chrono;\n\n\/\/ MARK: - Utility\n\nnamespace {\n\n\/\/ Make a handler that extracts either an exception pointer, or the string value\n\/\/ of the property with the specified name.\nPermissions::AsyncOperationHandler make_handler_extracting_property(std::string property,\n Permissions::PermissionOfferCallback callback)\n{\n return [property=std::move(property),\n callback=std::move(callback)](Object* object, std::exception_ptr exception) {\n if (exception) {\n callback(none, exception);\n } else {\n CppContext context;\n auto token = any_cast<std::string>(object->get_property_value<util::Any>(context, property));\n callback(util::make_optional<std::string>(std::move(token)), nullptr);\n }\n };\n}\n\nAccessLevel extract_access_level(Object& permission, CppContext& context)\n{\n auto may_manage = permission.get_property_value<util::Any>(context, \"mayManage\");\n if (may_manage.has_value() && any_cast<bool>(may_manage))\n return AccessLevel::Admin;\n\n auto may_write = permission.get_property_value<util::Any>(context, \"mayWrite\");\n if (may_write.has_value() && any_cast<bool>(may_write))\n return AccessLevel::Write;\n\n auto may_read = permission.get_property_value<util::Any>(context, \"mayRead\");\n if (may_read.has_value() && any_cast<bool>(may_read))\n return AccessLevel::Read;\n\n return AccessLevel::None;\n}\n\n\/\/\/ Turn a system time point value into the 64-bit integer representing ns since the Unix epoch.\nint64_t ns_since_unix_epoch(const system_clock::time_point& point)\n{\n tm unix_epoch{};\n unix_epoch.tm_year = 70;\n time_t epoch_time = mktime(&unix_epoch);\n auto epoch_point = system_clock::from_time_t(epoch_time);\n return duration_cast<nanoseconds>(point - epoch_point).count();\n}\n\n} \/\/ anonymous namespace\n\n\/\/ MARK: - Permission\n\nPermission::Permission(Object& permission)\n{\n CppContext context;\n path = any_cast<std::string>(permission.get_property_value<util::Any>(context, \"path\"));\n access = extract_access_level(permission, context);\n condition = Condition(any_cast<std::string>(permission.get_property_value<util::Any>(context, \"userId\")));\n updated_at = any_cast<Timestamp>(permission.get_property_value<util::Any>(context, \"updatedAt\"));\n}\n\nPermission::Permission(std::string path, AccessLevel access, Condition condition, Timestamp updated_at)\n: path(std::move(path))\n, access(access)\n, condition(std::move(condition))\n, updated_at(std::move(updated_at))\n{ }\n\nstd::string Permission::description_for_access_level(AccessLevel level)\n{\n switch (level) {\n case AccessLevel::None: return \"none\";\n case AccessLevel::Read: return \"read\";\n case AccessLevel::Write: return \"write\";\n case AccessLevel::Admin: return \"admin\";\n }\n REALM_UNREACHABLE();\n}\n\nbool Permission::paths_are_equivalent(std::string path_1, std::string path_2,\n const std::string& user_id_1, const std::string& user_id_2)\n{\n REALM_ASSERT_DEBUG(path_1.length() > 0);\n REALM_ASSERT_DEBUG(path_2.length() > 0);\n if (path_1 == path_2) {\n \/\/ If both paths are identical and contain `\/~\/`, the user IDs must match.\n return (path_1.find(\"\/~\/\") == std::string::npos) || (user_id_1 == user_id_2);\n }\n \/\/ Make substitutions for the first `\/~\/` in the string.\n size_t index = path_1.find(\"\/~\/\");\n if (index != std::string::npos)\n path_1.replace(index + 1, 1, user_id_1);\n\n index = path_2.find(\"\/~\/\");\n if (index != std::string::npos)\n path_2.replace(index + 1, 1, user_id_2);\n\n return path_1 == path_2;\n}\n\n\/\/ MARK: - Permissions\n\nvoid Permissions::get_permissions(std::shared_ptr<SyncUser> user,\n PermissionResultsCallback callback,\n const ConfigMaker& make_config)\n{\n auto realm = Permissions::permission_realm(user, make_config);\n auto table = ObjectStore::table_for_object_type(realm->read_group(), \"Permission\");\n auto results = std::make_shared<_impl::NotificationWrapper<Results>>(std::move(realm), *table);\n\n \/\/ `get_permissions` works by temporarily adding an async notifier to the permission Realm.\n \/\/ This notifier will run the `async` callback until the Realm contains permissions or\n \/\/ an error happens. When either of these two things happen, the notifier will be\n \/\/ unregistered by nulling out the `results_wrapper` container.\n auto async = [results, callback=std::move(callback)](CollectionChangeSet, std::exception_ptr ex) mutable {\n if (ex) {\n callback(Results(), ex);\n results.reset();\n return;\n }\n if (results->size() > 0) {\n \/\/ We monitor the raw results. The presence of a `__management` Realm indicates\n \/\/ that the permissions have been downloaded (hence, we wait until size > 0).\n TableRef table = ObjectStore::table_for_object_type(results->get_realm()->read_group(), \"Permission\");\n size_t col_idx = table->get_descriptor()->get_column_index(\"path\");\n auto query = !(table->column<StringData>(col_idx).ends_with(\"\/__permission\")\n || table->column<StringData>(col_idx).ends_with(\"\/__management\"));\n \/\/ Call the callback with our new permissions object. This object will exclude the\n \/\/ private Realms.\n callback(results->filter(std::move(query)), nullptr);\n results.reset();\n }\n };\n results->add_notification_callback(std::move(async));\n}\n\nvoid Permissions::set_permission(std::shared_ptr<SyncUser> user,\n Permission permission,\n PermissionChangeCallback callback,\n const ConfigMaker& make_config)\n{\n auto props = AnyDict{\n {\"userId\", permission.condition.user_id},\n {\"realmUrl\", user->server_url() + permission.path},\n {\"mayRead\", permission.access != AccessLevel::None},\n {\"mayWrite\", permission.access == AccessLevel::Write || permission.access == AccessLevel::Admin},\n {\"mayManage\", permission.access == AccessLevel::Admin},\n };\n if (permission.condition.type == Permission::Condition::Type::KeyValue) {\n props.insert({\"metadataKey\", permission.condition.key_value.first});\n props.insert({\"metadataValue\", permission.condition.key_value.second});\n }\n auto cb = [callback=std::move(callback)](Object*, std::exception_ptr exception) {\n callback(exception);\n };\n perform_async_operation(\"PermissionChange\", std::move(user), std::move(cb), std::move(props), make_config);\n}\n\nvoid Permissions::delete_permission(std::shared_ptr<SyncUser> user,\n Permission permission,\n PermissionChangeCallback callback,\n const ConfigMaker& make_config)\n{\n permission.access = AccessLevel::None;\n set_permission(std::move(user), std::move(permission), std::move(callback), make_config);\n}\n\nvoid Permissions::make_offer(std::shared_ptr<SyncUser> user,\n PermissionOffer offer,\n PermissionOfferCallback callback,\n const ConfigMaker& make_config)\n{\n auto props = AnyDict{\n {\"expiresAt\", std::move(offer.expiration)},\n {\"userId\", user->identity()},\n {\"realmUrl\", user->server_url() + offer.path},\n {\"mayRead\", offer.access != AccessLevel::None},\n {\"mayWrite\", offer.access == AccessLevel::Write || offer.access == AccessLevel::Admin},\n {\"mayManage\", offer.access == AccessLevel::Admin},\n };\n perform_async_operation(\"PermissionOffer\",\n std::move(user),\n make_handler_extracting_property(\"token\", std::move(callback)),\n std::move(props),\n make_config);\n}\n\nvoid Permissions::accept_offer(std::shared_ptr<SyncUser> user,\n const std::string& token,\n PermissionOfferCallback callback,\n const ConfigMaker& make_config)\n{\n perform_async_operation(\"PermissionOfferResponse\",\n std::move(user),\n make_handler_extracting_property(\"realmUrl\", std::move(callback)),\n AnyDict{ {\"token\", token} },\n make_config);\n}\n\nvoid Permissions::perform_async_operation(const std::string& object_type,\n std::shared_ptr<SyncUser> user,\n AsyncOperationHandler handler,\n AnyDict additional_props,\n const ConfigMaker& make_config)\n{;\n auto realm = Permissions::management_realm(std::move(user), make_config);\n CppContext context;\n\n \/\/ Get the current time.\n int64_t ns_since_epoch = ns_since_unix_epoch(system_clock::now());\n int64_t s_arg = ns_since_epoch \/ (int64_t)Timestamp::nanoseconds_per_second;\n int32_t ns_arg = ns_since_epoch % Timestamp::nanoseconds_per_second;\n\n auto props = AnyDict{\n {\"id\", util::uuid_string()},\n {\"createdAt\", Timestamp(s_arg, ns_arg)},\n {\"updatedAt\", Timestamp(s_arg, ns_arg)},\n };\n props.insert(additional_props.begin(), additional_props.end());\n\n \/\/ Write the permission object.\n realm->begin_transaction();\n auto raw = Object::create<util::Any>(context, realm, *realm->schema().find(object_type), std::move(props), false);\n auto object = std::make_shared<_impl::NotificationWrapper<Object>>(std::move(raw));\n realm->commit_transaction();\n\n \/\/ Observe the permission object until the permission change has been processed or failed.\n \/\/ The notifier is automatically unregistered upon the completion of the permission\n \/\/ change, one way or another.\n auto block = [object, handler=std::move(handler)](CollectionChangeSet, std::exception_ptr ex) mutable {\n if (ex) {\n handler(nullptr, ex);\n object.reset();\n return;\n }\n\n CppContext context;\n auto status_code = object->get_property_value<util::Any>(context, \"statusCode\");\n if (!status_code.has_value()) {\n \/\/ Continue waiting for the sync server to complete the operation.\n return;\n }\n\n \/\/ Determine whether an error happened or not.\n if (auto code = any_cast<long long>(status_code)) {\n \/\/ The permission change failed because an error was returned from the server.\n auto status = object->get_property_value<util::Any>(context, \"statusMessage\");\n std::string error_str = (status.has_value()\n ? any_cast<std::string>(status)\n : util::format(\"Error code: %1\", code));\n handler(nullptr, std::make_exception_ptr(PermissionActionException(error_str, code)));\n }\n else {\n handler(object.get(), nullptr);\n }\n object.reset();\n };\n object->add_notification_callback(std::move(block));\n}\n\nSharedRealm Permissions::management_realm(std::shared_ptr<SyncUser> user, const ConfigMaker& make_config)\n{\n \/\/ FIXME: maybe we should cache the management Realm on the user, so we don't need to open it every time.\n const auto realm_url = util::format(\"realm%1\/~\/__management\", user->server_url().substr(4));\n Realm::Config config = make_config(user, std::move(realm_url));\n config.sync_config->stop_policy = SyncSessionStopPolicy::Immediately;\n config.schema = Schema{\n {\"PermissionChange\", {\n Property{\"id\", PropertyType::String, Property::IsPrimary{true}},\n Property{\"createdAt\", PropertyType::Date},\n Property{\"updatedAt\", PropertyType::Date},\n Property{\"statusCode\", PropertyType::Int|PropertyType::Nullable},\n Property{\"statusMessage\", PropertyType::String|PropertyType::Nullable},\n Property{\"userId\", PropertyType::String},\n Property{\"metadataKey\", PropertyType::String|PropertyType::Nullable},\n Property{\"metadataValue\", PropertyType::String|PropertyType::Nullable},\n Property{\"metadataNameSpace\", PropertyType::String|PropertyType::Nullable},\n Property{\"realmUrl\", PropertyType::String},\n Property{\"mayRead\", PropertyType::Bool|PropertyType::Nullable},\n Property{\"mayWrite\", PropertyType::Bool|PropertyType::Nullable},\n Property{\"mayManage\", PropertyType::Bool|PropertyType::Nullable},\n }},\n {\"PermissionOffer\", {\n Property{\"id\", PropertyType::String, Property::IsPrimary{true}},\n Property{\"createdAt\", PropertyType::Date},\n Property{\"updatedAt\", PropertyType::Date},\n Property{\"expiresAt\", PropertyType::Date|PropertyType::Nullable},\n Property{\"statusCode\", PropertyType::Int|PropertyType::Nullable},\n Property{\"statusMessage\", PropertyType::String|PropertyType::Nullable},\n Property{\"token\", PropertyType::String|PropertyType::Nullable},\n Property{\"realmUrl\", PropertyType::String},\n Property{\"mayRead\", PropertyType::Bool},\n Property{\"mayWrite\", PropertyType::Bool},\n Property{\"mayManage\", PropertyType::Bool},\n }},\n {\"PermissionOfferResponse\", {\n Property{\"id\", PropertyType::String, Property::IsPrimary{true}},\n Property{\"createdAt\", PropertyType::Date},\n Property{\"updatedAt\", PropertyType::Date},\n Property{\"statusCode\", PropertyType::Int|PropertyType::Nullable},\n Property{\"statusMessage\", PropertyType::String|PropertyType::Nullable},\n Property{\"token\", PropertyType::String},\n Property{\"realmUrl\", PropertyType::String|PropertyType::Nullable},\n }},\n };\n config.schema_version = 0;\n auto shared_realm = Realm::get_shared_realm(std::move(config));\n user->register_management_session(shared_realm->config().path);\n return shared_realm;\n}\n\nSharedRealm Permissions::permission_realm(std::shared_ptr<SyncUser> user, const ConfigMaker& make_config)\n{\n \/\/ FIXME: maybe we should cache the permission Realm on the user, so we don't need to open it every time.\n const auto realm_url = util::format(\"realm%1\/~\/__permission\", user->server_url().substr(4));\n Realm::Config config = make_config(user, std::move(realm_url));\n config.sync_config->stop_policy = SyncSessionStopPolicy::Immediately;\n config.schema = Schema{\n {\"Permission\", {\n {\"updatedAt\", PropertyType::Date},\n {\"userId\", PropertyType::String},\n {\"path\", PropertyType::String},\n {\"mayRead\", PropertyType::Bool},\n {\"mayWrite\", PropertyType::Bool},\n {\"mayManage\", PropertyType::Bool},\n }}\n };\n config.schema_version = 0;\n auto shared_realm = Realm::get_shared_realm(std::move(config));\n user->register_permission_session(shared_realm->config().path);\n return shared_realm;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"attributesmodel.h\"\n\n#include <QBrush>\n\n#include <model\/devisersettings.h>\n#include <model\/deviserattribute.h>\n\nAttributesModel::AttributesModel(\n QObject * parent,\n QList<DeviserAttribute*>* data)\n : QAbstractTableModel(parent)\n , mData(data)\n{\n\n}\n\nint\nAttributesModel::rowCount(const QModelIndex &) const\n{\n return mData->count();\n}\n\nint\nAttributesModel::columnCount(const QModelIndex &) const\n{\n return 6;\n}\n\n\nQt::ItemFlags\nAttributesModel::flags(const QModelIndex &index) const\n{\n if (!index.isValid())\n return Qt::ItemIsEnabled;\n return QAbstractTableModel::flags(index) | Qt::ItemIsEditable;\n}\n\nQVariant\nAttributesModel::data(const QModelIndex &index, int role) const\n{\n if (role == Qt::ToolTipRole)\n {\n switch(index.column())\n {\n case NAME:\n return \"The name of the attribute\/element to be used by code generation. The XML output may use a different name (see <b>XML Name<\/b>). This field is required.\";\n case TYPE:\n return \"The type of the attribute\/element. Allowed values are: SId, SIdRef, string, bool, double, int, unsigned int, IDREF, UnitSId, UnitSIdRef, enum, element, lo_element, inline_lo_element. This field is required.\";\n case REQUIRED:\n return \"States whether the attribute or element is mandatory. This should be <b>true<\/b> if the attribute\/element is mandatory; <b>false<\/b> if not.\";\n case ELEMENT:\n return \"This field provides additional information depending on the <b>Type<\/b> of the attribute\/element. It may be the name of the element, enumeration or object being referenced. This field is required for attributes of type SIdRef, array, enum, element, lo_element, inline_lo_element, vector.\";\n case ABSTRACT:\n return \"States whether this element is a base class. This should be <b>true<\/b> if the element is a base class and therefore not instantiated directly; <b>false<\/b> if not.\";\n case XMLName:\n return \"The name of the attribute\/element as used by the XML output. If blank, this defaults to the <b>Name<\/b> given.\";\n default:\n return QVariant();\n }\n }\n\n if (role == Qt::BackgroundRole)\n {\n switch(index.column())\n {\n case TYPE:\n case NAME:\n if (index.data().toString().isEmpty())\n return QBrush(DeviserSettings::getInstance()->getValidationColor());\n else\n return QVariant();\n\n case ELEMENT:\n {\n QString element = index.data().toString();\n if (!element.isEmpty())\n return QVariant();\n\n QString type = index.model()->index(index.row(), TYPE).data().toString();\n if (type == \"element\"\n || type == \"inline_lo_element\"\n || type == \"lo_element\"\n || type == \"enum\"\n || type == \"array\"\n || type == \"vector\"\n || type == \"SIdRef\"\n || type == \"IDREF\"\n )\n return QBrush(DeviserSettings::getInstance()->getValidationColor());\n else\n return QVariant();\n }\n default:\n return QVariant();\n }\n\n }\n\n if (role != Qt::DisplayRole &&\n role != Qt::EditRole ) return QVariant();\n\n\n\n const DeviserAttribute* attr = (*mData)[index.row()];\n\n switch(index.column())\n {\n case NAME:\n return attr->getName();\n case TYPE:\n return attr->getType();\n case REQUIRED:\n return attr->getRequired();\n case ELEMENT:\n return attr->getElement();\n case ABSTRACT:\n return attr->getAbstract();\n case XMLName:\n return attr->getXMLName();\n default:\n return QVariant();\n }\n\n}\n\nbool\nAttributesModel::setData(const QModelIndex &index,\n const QVariant &value, int role \/*= Qt::EditRole*\/)\n{\n if (role != Qt::DisplayRole && role != Qt::EditRole) return false;\n DeviserAttribute* attr = (*mData)[index.row()];\n if (attr == NULL) return false;\n\n switch(index.column())\n {\n case NAME:\n attr->setName(value.toString());\n return true;\n case TYPE:\n attr->setType(value.toString());\n return true;\n case REQUIRED:\n attr->setRequired(value.toBool());\n return true;\n case ELEMENT:\n attr->setElement(value.toString());\n return true;\n case ABSTRACT:\n attr->setAbstract(value.toBool());\n return true;\n case XMLName:\n attr->setXMLName(value.toString());\n return true;\n default:\n return false;\n }\n\n}\n\nQVariant\nAttributesModel::headerData(int section,\n Qt::Orientation orientation,\n int role) const\n{\n if (orientation != Qt::Horizontal) return QVariant();\n\n if (role != Qt::DisplayRole) return QVariant();\n\n switch(section)\n {\n case NAME:\n return \"Name\";\n case TYPE:\n return \"Type\";\n case REQUIRED:\n return \"Required\";\n case ELEMENT:\n return \"Element\";\n case ABSTRACT:\n return \"isBaseClass\";\n case XMLName:\n return \"XML name\";\n default:\n return QVariant();\n }\n\n}\n\nvoid AttributesModel::beginAdding()\n{\n beginInsertRows(QModelIndex(),mData->count(),mData->count());\n}\n\nvoid AttributesModel::endAdding()\n{\n endInsertRows();\n}\n\nvoid\nAttributesModel::addAttribute(DeviserAttribute* attr)\n{\n beginInsertRows(QModelIndex(),mData->count(),mData->count());\n mData->append(attr);\n endInsertRows();\n}\n\nDeviserAttribute*\nAttributesModel::getAttribute(int row)\n{\n if (row < 0 || row >= mData->count())\n return NULL;\n return (*mData)[row];\n}\n\nDeviserAttribute*\nAttributesModel::removeAttribute(int row)\n{\n beginRemoveRows(QModelIndex(),row,row);\n DeviserAttribute* result = getAttribute(row);\n mData->removeAt(row);\n endRemoveRows();\n result->deleteLater();\n return result;\n}\n\n\n<commit_msg>IDREF does not need element<commit_after>#include \"attributesmodel.h\"\n\n#include <QBrush>\n\n#include <model\/devisersettings.h>\n#include <model\/deviserattribute.h>\n\nAttributesModel::AttributesModel(\n QObject * parent,\n QList<DeviserAttribute*>* data)\n : QAbstractTableModel(parent)\n , mData(data)\n{\n\n}\n\nint\nAttributesModel::rowCount(const QModelIndex &) const\n{\n return mData->count();\n}\n\nint\nAttributesModel::columnCount(const QModelIndex &) const\n{\n return 6;\n}\n\n\nQt::ItemFlags\nAttributesModel::flags(const QModelIndex &index) const\n{\n if (!index.isValid())\n return Qt::ItemIsEnabled;\n return QAbstractTableModel::flags(index) | Qt::ItemIsEditable;\n}\n\nQVariant\nAttributesModel::data(const QModelIndex &index, int role) const\n{\n if (role == Qt::ToolTipRole)\n {\n switch(index.column())\n {\n case NAME:\n return \"The name of the attribute\/element to be used by code generation. The XML output may use a different name (see <b>XML Name<\/b>). This field is required.\";\n case TYPE:\n return \"The type of the attribute\/element. Allowed values are: SId, SIdRef, string, bool, double, int, unsigned int, IDREF, UnitSId, UnitSIdRef, enum, element, lo_element, inline_lo_element. This field is required.\";\n case REQUIRED:\n return \"States whether the attribute or element is mandatory. This should be <b>true<\/b> if the attribute\/element is mandatory; <b>false<\/b> if not.\";\n case ELEMENT:\n return \"This field provides additional information depending on the <b>Type<\/b> of the attribute\/element. It may be the name of the element, enumeration or object being referenced. This field is required for attributes of type SIdRef, array, enum, element, lo_element, inline_lo_element, vector.\";\n case ABSTRACT:\n return \"States whether this element is a base class. This should be <b>true<\/b> if the element is a base class and therefore not instantiated directly; <b>false<\/b> if not.\";\n case XMLName:\n return \"The name of the attribute\/element as used by the XML output. If blank, this defaults to the <b>Name<\/b> given.\";\n default:\n return QVariant();\n }\n }\n\n if (role == Qt::BackgroundRole)\n {\n switch(index.column())\n {\n case TYPE:\n case NAME:\n if (index.data().toString().isEmpty())\n return QBrush(DeviserSettings::getInstance()->getValidationColor());\n else\n return QVariant();\n\n case ELEMENT:\n {\n QString element = index.data().toString();\n if (!element.isEmpty())\n return QVariant();\n\n QString type = index.model()->index(index.row(), TYPE).data().toString();\n if (type == \"element\"\n || type == \"inline_lo_element\"\n || type == \"lo_element\"\n || type == \"enum\"\n || type == \"array\"\n || type == \"vector\"\n || type == \"SIdRef\"\n\/\/ || type == \"IDREF\"\n )\n return QBrush(DeviserSettings::getInstance()->getValidationColor());\n else\n return QVariant();\n }\n default:\n return QVariant();\n }\n\n }\n\n if (role != Qt::DisplayRole &&\n role != Qt::EditRole ) return QVariant();\n\n\n\n const DeviserAttribute* attr = (*mData)[index.row()];\n\n switch(index.column())\n {\n case NAME:\n return attr->getName();\n case TYPE:\n return attr->getType();\n case REQUIRED:\n return attr->getRequired();\n case ELEMENT:\n return attr->getElement();\n case ABSTRACT:\n return attr->getAbstract();\n case XMLName:\n return attr->getXMLName();\n default:\n return QVariant();\n }\n\n}\n\nbool\nAttributesModel::setData(const QModelIndex &index,\n const QVariant &value, int role \/*= Qt::EditRole*\/)\n{\n if (role != Qt::DisplayRole && role != Qt::EditRole) return false;\n DeviserAttribute* attr = (*mData)[index.row()];\n if (attr == NULL) return false;\n\n switch(index.column())\n {\n case NAME:\n attr->setName(value.toString());\n return true;\n case TYPE:\n attr->setType(value.toString());\n return true;\n case REQUIRED:\n attr->setRequired(value.toBool());\n return true;\n case ELEMENT:\n attr->setElement(value.toString());\n return true;\n case ABSTRACT:\n attr->setAbstract(value.toBool());\n return true;\n case XMLName:\n attr->setXMLName(value.toString());\n return true;\n default:\n return false;\n }\n\n}\n\nQVariant\nAttributesModel::headerData(int section,\n Qt::Orientation orientation,\n int role) const\n{\n if (orientation != Qt::Horizontal) return QVariant();\n\n if (role != Qt::DisplayRole) return QVariant();\n\n switch(section)\n {\n case NAME:\n return \"Name\";\n case TYPE:\n return \"Type\";\n case REQUIRED:\n return \"Required\";\n case ELEMENT:\n return \"Element\";\n case ABSTRACT:\n return \"isBaseClass\";\n case XMLName:\n return \"XML name\";\n default:\n return QVariant();\n }\n\n}\n\nvoid AttributesModel::beginAdding()\n{\n beginInsertRows(QModelIndex(),mData->count(),mData->count());\n}\n\nvoid AttributesModel::endAdding()\n{\n endInsertRows();\n}\n\nvoid\nAttributesModel::addAttribute(DeviserAttribute* attr)\n{\n beginInsertRows(QModelIndex(),mData->count(),mData->count());\n mData->append(attr);\n endInsertRows();\n}\n\nDeviserAttribute*\nAttributesModel::getAttribute(int row)\n{\n if (row < 0 || row >= mData->count())\n return NULL;\n return (*mData)[row];\n}\n\nDeviserAttribute*\nAttributesModel::removeAttribute(int row)\n{\n beginRemoveRows(QModelIndex(),row,row);\n DeviserAttribute* result = getAttribute(row);\n mData->removeAt(row);\n endRemoveRows();\n result->deleteLater();\n return result;\n}\n\n\n<|endoftext|>"} {"text":"<commit_before>template <int num_rotors>\nvoid RocketSystem<num_rotors>::init() {\n getAccelerometer()->init();\n getGyroscope()->init();\n}\n\ntemplate <int num_rotors>\nvoid RocketSystem<num_rotors>::update() {\n \/\/ Poll the IMU\n accelerometer_reading_t accel_reading = getAccelerometer()->readAccel();\n gyroscope_reading_t gyro_reading = getGyroscope()->readGyro();\n\n \/\/ Update the attitude estimate\n attitude_estimate_t estimate = getAttitudeEstimator()->update(accel_reading, gyro_reading);\n\n \/\/ Poll for controller input\n controller_input_t input = getInputSource()->read();\n\n \/\/ Run the controllers\n angular_position_setpoint_t angular_setpoint = {\n .pitch_pos_sp = input.pitch_sp,\n .roll_pos_sp = input.roll_sp,\n .yaw_pos_sp = input.yaw_sp,\n .throttle_sp = input.throttle_sp\n };\n\n actuator_setpoint_t actuator_setpoint = runController(estimate, angular_setpoint);\n\n \/\/ Update motor outputs\n getMotorMapper()->run(actuator_setpoint);\n}\n<commit_msg>Fix missed roll\/pitch\/yaw change in `RocketSystem`.<commit_after>template <int num_rotors>\nvoid RocketSystem<num_rotors>::init() {\n getAccelerometer()->init();\n getGyroscope()->init();\n}\n\ntemplate <int num_rotors>\nvoid RocketSystem<num_rotors>::update() {\n \/\/ Poll the IMU\n accelerometer_reading_t accel_reading = getAccelerometer()->readAccel();\n gyroscope_reading_t gyro_reading = getGyroscope()->readGyro();\n\n \/\/ Update the attitude estimate\n attitude_estimate_t estimate = getAttitudeEstimator()->update(accel_reading, gyro_reading);\n\n \/\/ Poll for controller input\n controller_input_t input = getInputSource()->read();\n\n \/\/ Run the controllers\n angular_position_setpoint_t angular_setpoint = {\n .roll_pos_sp = input.roll_sp,\n .pitch_pos_sp = input.pitch_sp,\n .yaw_pos_sp = input.yaw_sp,\n .throttle_sp = input.throttle_sp\n };\n\n actuator_setpoint_t actuator_setpoint = runController(estimate, angular_setpoint);\n\n \/\/ Update motor outputs\n getMotorMapper()->run(actuator_setpoint);\n}\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: tp_LegendPosition.cxx,v $\n *\n * $Revision: 1.6 $\n *\n * last change: $Author: kz $ $Date: 2007-05-10 16:32:27 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_chart2.hxx\"\n#include \"tp_LegendPosition.hxx\"\n\n#include \"ResId.hxx\"\n#include \"TabPages.hrc\"\n#include \"SchSfxItemIds.hxx\"\n\n\/\/#include \"schattr.hxx\"\n#ifndef _SVX_CHRTITEM_HXX \/\/autogen\n#include <svx\/chrtitem.hxx>\n#endif\n\/*\n#include \"schresid.hxx\"\n#include \"chtmodel.hxx\"\n#include \"attrib.hxx\"\n#include \"attrib.hrc\"\n*\/\n\/\/.............................................................................\nnamespace chart\n{\n\/\/.............................................................................\n\nSchLegendPosTabPage::SchLegendPosTabPage(Window* pWindow,\n const SfxItemSet& rInAttrs) :\n SfxTabPage(pWindow, SchResId(TP_LEGEND_POS), rInAttrs),\n aGrpLegend(this, SchResId(GRP_LEGEND)),\n aRbtLeft(this, SchResId(RBT_LEFT)),\n aRbtTop(this, SchResId(RBT_TOP)),\n aRbtBottom(this, SchResId(RBT_BOTTOM)),\n aRbtRight(this, SchResId(RBT_RIGHT))\n{\n FreeResource();\n}\n\nSchLegendPosTabPage::~SchLegendPosTabPage()\n{\n}\n\nSfxTabPage* SchLegendPosTabPage::Create(Window* pWindow,\n const SfxItemSet& rOutAttrs)\n{\n return new SchLegendPosTabPage(pWindow, rOutAttrs);\n}\n\nBOOL SchLegendPosTabPage::FillItemSet(SfxItemSet& rOutAttrs)\n{\n SvxChartLegendPos ePos;\n\n if (aRbtLeft.IsChecked())\n ePos = CHLEGEND_LEFT;\n else if (aRbtTop.IsChecked())\n ePos = CHLEGEND_TOP;\n else if (aRbtRight.IsChecked())\n ePos = CHLEGEND_RIGHT;\n else if (aRbtBottom.IsChecked())\n ePos = CHLEGEND_BOTTOM;\n else\n ePos = CHLEGEND_NONE;\n\n rOutAttrs.Put(SvxChartLegendPosItem(ePos, SCHATTR_LEGEND_POS));\n\n return TRUE;\n}\n\nvoid SchLegendPosTabPage::Reset(const SfxItemSet& rInAttrs)\n{\n SvxChartLegendPos ePos = CHLEGEND_NONE;\n\n const SfxPoolItem* pPoolItem = NULL;\n if( rInAttrs.GetItemState( SCHATTR_LEGEND_POS,\n TRUE, &pPoolItem ) != SFX_ITEM_SET )\n pPoolItem = &(rInAttrs.GetPool()->GetDefaultItem( SCHATTR_LEGEND_POS ));\n\n if( pPoolItem )\n ePos = ((const SvxChartLegendPosItem*)pPoolItem)->GetValue();\n\n switch( ePos )\n {\n case CHLEGEND_LEFT:\n aRbtLeft.Check(TRUE);\n break;\n case CHLEGEND_TOP:\n aRbtTop.Check(TRUE);\n break;\n case CHLEGEND_RIGHT:\n aRbtRight.Check(TRUE);\n break;\n case CHLEGEND_BOTTOM:\n aRbtBottom.Check(TRUE);\n break;\n default:\n break;\n }\n}\n\n\/\/.............................................................................\n} \/\/namespace chart\n\/\/.............................................................................\n<commit_msg>INTEGRATION: CWS chart2mst3 (1.2.4); FILE MERGED 2007\/05\/14 20:03:23 bm 1.2.4.7: RESYNC: (1.4-1.6); FILE MERGED 2006\/10\/18 17:04:43 bm 1.2.4.6: RESYNC: (1.3-1.4); FILE MERGED 2006\/02\/20 14:45:45 iha 1.2.4.5: move SchItemPool from controller to view lib -> ChartItemPool 2006\/01\/06 20:27:26 iha 1.2.4.4: added legendposition to wizard and restructured legend postiion control classes 2005\/10\/07 11:19:40 bm 1.2.4.3: RESYNC: (1.2-1.3); FILE MERGED 2004\/09\/07 10:04:17 bm 1.2.4.2: fixed order of members to fit order in dialog 2004\/06\/01 18:52:40 iha 1.2.4.1: no warnings+cleanup<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: tp_LegendPosition.cxx,v $\n *\n * $Revision: 1.7 $\n *\n * last change: $Author: vg $ $Date: 2007-05-22 17:45:52 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_chart2.hxx\"\n#include \"tp_LegendPosition.hxx\"\n#include \"ResId.hxx\"\n#include \"TabPages.hrc\"\n#include \"res_LegendPosition.hxx\"\n#include \"chartview\/ChartSfxItemIds.hxx\"\n#include \"NoWarningThisInCTOR.hxx\"\n\n#ifndef _SVX_CHRTITEM_HXX\n#include <svx\/chrtitem.hxx>\n#endif\n\n\/\/.............................................................................\nnamespace chart\n{\n\/\/.............................................................................\n\nSchLegendPosTabPage::SchLegendPosTabPage(Window* pWindow,\n const SfxItemSet& rInAttrs)\n : SfxTabPage( pWindow, SchResId(TP_LEGEND_POS), rInAttrs )\n , aGrpLegend( this, SchResId(GRP_LEGEND) )\n , m_apLegendPositionResources( new LegendPositionResources(this) )\n{\n FreeResource();\n}\n\nSchLegendPosTabPage::~SchLegendPosTabPage()\n{\n}\n\nSfxTabPage* SchLegendPosTabPage::Create(Window* pWindow,\n const SfxItemSet& rOutAttrs)\n{\n return new SchLegendPosTabPage(pWindow, rOutAttrs);\n}\n\nBOOL SchLegendPosTabPage::FillItemSet(SfxItemSet& rOutAttrs)\n{\n m_apLegendPositionResources->writeToItemSet(rOutAttrs);\n return TRUE;\n}\n\nvoid SchLegendPosTabPage::Reset(const SfxItemSet& rInAttrs)\n{\n m_apLegendPositionResources->initFromItemSet(rInAttrs);\n}\n\n\/\/.............................................................................\n} \/\/namespace chart\n\/\/.............................................................................\n<|endoftext|>"} {"text":"<commit_before>#include \"SoundSystem_oal.h\"\n#include \"Channel_oal.h\"\n#include \"DebugActor.h\"\n#include \"utils\/stringUtils.h\"\n#include \"pthread.h\"\n#include \"..\/oal.h\"\n#include \"..\/null\/SoundSystemNull.h\"\n\n\/\/#ifdef EMSCRIPTEN\n\/\/#include \"..\/emscripten\/SoundSystemEmscripten.h\n\/\/#endif\n\nnamespace oxygine\n{\n void check();\n\n SoundSystem* SoundSystem::create()\n {\n if (!SoundSystem::instance)\n SoundSystem::instance = new SoundSystemOAL;\n\n return SoundSystem::instance;\n }\n\n SoundSystemOAL::SoundSystemOAL(): _device(0), _context(0), _volume(1.0)\n {\n#ifdef __S3E__\n\/\/ alcInit();\n#endif\n }\n\n SoundSystemOAL::~SoundSystemOAL()\n {\n }\n\n\n void SoundSystemOAL::setContext()\n {\n alcMakeContextCurrent(_context);\n check();\n }\n\n void SoundSystemOAL::pause()\n {\n log::messageln(\"SoundSystemOAL::pause\");\n \/*\n for (channels::iterator i = _channels.begin(); i != _channels.end(); ++i)\n {\n ChannelOAL& channel = *i;\n channel.pause();\n }\n *\/\n\n#if defined(__ANDROID__)\n \/\/android needs special workaround\n alcSuspend();\n#endif\n\n#if defined(__S3E__)\n alcSuspendContext(_context);\n alcMakeContextCurrent(0);\n#endif\n }\n\n void SoundSystemOAL::resume()\n {\n log::messageln(\"SoundSystemOAL::resume\");\n\n#if defined(__ANDROID__)\n alcResume();\n#endif\n\n#if defined(__S3E__)\n alcMakeContextCurrent(_context);\n alcProcessContext(_context);\n#endif\n\n\n\n \/*\n for (channels::iterator i = _channels.begin(); i != _channels.end(); ++i)\n {\n ChannelOAL& channel = *i;\n channel.resume();\n }\n *\/\n }\n\n void SoundSystemOAL::stop()\n {\n _channels.stop();\n }\n\n void SoundSystemOAL::setVolume(float v)\n {\n _volume = v;\n _channels.setVolume(v);\n check();\n }\n\n void SoundSystemOAL::init(int channels_num)\n {\n log::messageln(\"SoundSystemOAL init\");\n#ifdef __ANDROID__\n _device = alcOpenDevice(\"opensles\");\n#else\n _device = alcOpenDevice(0);\n#endif\n if (!_device)\n {\n log::messageln(\"can't create alc device\");\n return;\n }\n\n _context = alcCreateContext(_device, 0);\n\n if (!_context)\n {\n log::messageln(\"can't create alc context\");\n return;\n }\n\n alcMakeContextCurrent(_context);\n\n\n \/*\n ALCint nummono, numstereo;\n alcGetIntegerv(_device, ALC_MONO_SOURCES, 1, &nummono);\n alcGetIntegerv(_device, ALC_STEREO_SOURCES, 1, &numstereo);\n *\/\n\n _channels._channels.resize(channels_num);\n\n for (int i = 0; i < channels_num; ++i)\n {\n ALuint source = 0;\n alGenSources(1, &source);\n check();\n\n _channels._channels[i].init(this, i, source);\n }\n\n\n ChannelOAL::runThread();\n check();\n }\n\n void SoundSystemOAL::release()\n {\n stop();\n\n ChannelOAL::stopThread();\n _channels._channels.clear();\n alcMakeContextCurrent(0);\n alcDestroyContext(_context);\n _context = 0;\n\n alcCloseDevice(_device);\n _device = 0;\n }\n\n SoundOAL* SoundSystemOAL::createSound(std::vector<unsigned char>& buffer, bool swap)\n {\n if (!_context)\n return 0;\n\n SoundOAL* sound = 0;\n sound = new SoundOAL();\n sound->init(buffer, swap);\n check();\n\n return sound;\n }\n\n SoundOAL* SoundSystemOAL::createSound(const char* path)\n {\n if (!_context)\n return 0;\n\n SoundOAL* sound = 0;\n sound = new SoundOAL();\n bool res = sound->init(path);\n if (!res)\n {\n delete sound;\n return 0;\n }\n check();\n\n return sound;\n }\n\n void SoundSystemOAL::update()\n {\n if (!_device)\n return;\n\n _channels.update();\n check();\n\n if (DebugActor::instance)\n {\n char str[255];\n safe_sprintf(str, \"channels: %d\\n\", _channels._channels.size() - getFreeChannelsNum());\n DebugActor::instance->addDebugString(str);\n }\n }\n\n int SoundSystemOAL::getFreeChannelsNum()\n {\n return _channels.getFreeNum();\n }\n\n ChannelOAL* SoundSystemOAL::getFreeChannel()\n {\n ChannelOAL* channel = _channels.getFree();\n check();\n return channel;\n }\n}\n<commit_msg>minor<commit_after>#include \"SoundSystem_oal.h\"\n#include \"Channel_oal.h\"\n#include \"DebugActor.h\"\n#include \"utils\/stringUtils.h\"\n#include \"pthread.h\"\n#include \"..\/oal.h\"\n#include \"..\/null\/SoundSystemNull.h\"\n\n\/\/#ifdef EMSCRIPTEN\n\/\/#include \"..\/emscripten\/SoundSystemEmscripten.h\n\/\/#endif\n\nnamespace oxygine\n{\n void check();\n\n SoundSystem* SoundSystem::create()\n {\n if (!SoundSystem::instance)\n SoundSystem::instance = new SoundSystemOAL;\n\n return SoundSystem::instance;\n }\n\n SoundSystemOAL::SoundSystemOAL(): _device(0), _context(0), _volume(1.0)\n {\n#ifdef __S3E__\n\/\/ alcInit();\n#endif\n }\n\n SoundSystemOAL::~SoundSystemOAL()\n {\n }\n\n\n void SoundSystemOAL::setContext()\n {\n alcMakeContextCurrent(_context);\n check();\n }\n\n void SoundSystemOAL::pause()\n {\n log::messageln(\"SoundSystemOAL::pause\");\n \/*\n for (channels::iterator i = _channels.begin(); i != _channels.end(); ++i)\n {\n ChannelOAL& channel = *i;\n channel.pause();\n }\n *\/\n\n#if defined(__ANDROID__)\n \/\/android needs special workaround\n alcSuspend();\n#endif\n\n#if defined(__S3E__)\n alcSuspendContext(_context);\n alcMakeContextCurrent(0);\n#endif\n }\n\n void SoundSystemOAL::resume()\n {\n log::messageln(\"SoundSystemOAL::resume\");\n\n#if defined(__ANDROID__)\n alcResume();\n#endif\n\n#if defined(__S3E__)\n alcMakeContextCurrent(_context);\n alcProcessContext(_context);\n#endif\n\n\n\n \/*\n for (channels::iterator i = _channels.begin(); i != _channels.end(); ++i)\n {\n ChannelOAL& channel = *i;\n channel.resume();\n }\n *\/\n }\n\n void SoundSystemOAL::stop()\n {\n _channels.stop();\n }\n\n void SoundSystemOAL::setVolume(float v)\n {\n _volume = v;\n _channels.setVolume(v);\n check();\n }\n\n void SoundSystemOAL::init(int channels_num)\n {\n log::messageln(\"SoundSystemOAL init\");\n#ifdef __ANDROID__\n _device = alcOpenDevice(\"opensles\");\n#else\n _device = alcOpenDevice(0);\n#endif\n if (!_device)\n {\n log::messageln(\"can't create alc device\");\n return;\n }\n\n _context = alcCreateContext(_device, 0);\n\n if (!_context)\n {\n log::messageln(\"can't create alc context\");\n return;\n }\n\n alcMakeContextCurrent(_context);\n\n\n \/*\n ALCint nummono, numstereo;\n alcGetIntegerv(_device, ALC_MONO_SOURCES, 1, &nummono);\n alcGetIntegerv(_device, ALC_STEREO_SOURCES, 1, &numstereo);\n *\/\n\n _channels._channels.resize(channels_num);\n\n for (int i = 0; i < channels_num; ++i)\n {\n ALuint source = 0;\n alGenSources(1, &source);\n check();\n\n _channels._channels[i].init(this, i, source);\n }\n\n\n ChannelOAL::runThread();\n check();\n }\n\n void SoundSystemOAL::release()\n {\n stop();\n\n ChannelOAL::stopThread();\n _channels._channels.clear();\n alcMakeContextCurrent(0);\n alcDestroyContext(_context);\n _context = 0;\n\n alcCloseDevice(_device);\n _device = 0;\n }\n\n SoundOAL* SoundSystemOAL::createSound(std::vector<unsigned char>& buffer, bool swap)\n {\n if (!_context)\n return 0;\n\n SoundOAL* sound = 0;\n sound = new SoundOAL();\n sound->init(buffer, swap);\n check();\n\n return sound;\n }\n\n SoundOAL* SoundSystemOAL::createSound(const char* path)\n {\n if (!_context)\n return 0;\n\n SoundOAL* sound = 0;\n sound = new SoundOAL();\n bool res = sound->init(path);\n if (!res)\n {\n delete sound;\n return 0;\n }\n check();\n\n return sound;\n }\n\n void SoundSystemOAL::update()\n {\n if (!_device)\n return;\n\n _channels.update();\n check();\n\n if (DebugActor::instance)\n {\n char str[255];\n safe_sprintf(str, \"channels: %d\", _channels._channels.size() - getFreeChannelsNum());\n DebugActor::instance->addDebugString(str);\n }\n }\n\n int SoundSystemOAL::getFreeChannelsNum()\n {\n return _channels.getFreeNum();\n }\n\n ChannelOAL* SoundSystemOAL::getFreeChannel()\n {\n ChannelOAL* channel = _channels.getFree();\n check();\n return channel;\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/chromeos\/extensions\/echo_private_api.h\"\n\n#include <string>\n\n#include \"base\/bind.h\"\n#include \"base\/files\/file_util.h\"\n#include \"base\/location.h\"\n#include \"base\/prefs\/pref_registry_simple.h\"\n#include \"base\/prefs\/pref_service.h\"\n#include \"base\/prefs\/scoped_user_pref_update.h\"\n#include \"base\/strings\/stringprintf.h\"\n#include \"base\/strings\/utf_string_conversions.h\"\n#include \"base\/time\/time.h\"\n#include \"base\/values.h\"\n#include \"chrome\/browser\/browser_process.h\"\n#include \"chrome\/browser\/chromeos\/settings\/cros_settings.h\"\n#include \"chrome\/browser\/chromeos\/ui\/echo_dialog_view.h\"\n#include \"chrome\/browser\/ui\/browser.h\"\n#include \"chrome\/browser\/ui\/browser_window.h\"\n#include \"chrome\/common\/extensions\/api\/echo_private.h\"\n#include \"chrome\/common\/pref_names.h\"\n#include \"chromeos\/system\/statistics_provider.h\"\n#include \"content\/public\/browser\/browser_thread.h\"\n#include \"extensions\/common\/extension.h\"\n\nnamespace echo_api = extensions::api::echo_private;\n\nusing content::BrowserThread;\n\nnamespace {\n\n\/\/ URL of \"More info\" link shown in echo dialog in GetUserConsent function.\nconst char kMoreInfoLink[] =\n \"chrome-extension:\/\/honijodknafkokifofgiaalefdiedpko\/main.html?\"\n \"answer=2677280\";\n\n} \/\/ namespace\n\nnamespace chromeos {\n\nnamespace echo_offer {\n\nvoid RegisterPrefs(PrefRegistrySimple* registry) {\n registry->RegisterDictionaryPref(prefs::kEchoCheckedOffers);\n}\n\n} \/\/ namespace echo_offer\n\n} \/\/ namespace chromeos\n\nEchoPrivateGetRegistrationCodeFunction::\n EchoPrivateGetRegistrationCodeFunction() {}\n\nEchoPrivateGetRegistrationCodeFunction::\n ~EchoPrivateGetRegistrationCodeFunction() {}\n\nvoid EchoPrivateGetRegistrationCodeFunction::GetRegistrationCode(\n const std::string& type) {\n \/\/ Possible ECHO code type and corresponding key name in StatisticsProvider.\n const std::string kCouponType = \"COUPON_CODE\";\n const std::string kGroupType = \"GROUP_CODE\";\n\n chromeos::system::StatisticsProvider* provider =\n chromeos::system::StatisticsProvider::GetInstance();\n std::string result;\n if (type == kCouponType) {\n provider->GetMachineStatistic(chromeos::system::kOffersCouponCodeKey,\n &result);\n } else if (type == kGroupType) {\n provider->GetMachineStatistic(chromeos::system::kOffersGroupCodeKey,\n &result);\n }\n\n results_ = echo_api::GetRegistrationCode::Results::Create(result);\n SendResponse(true);\n}\n\nbool EchoPrivateGetRegistrationCodeFunction::RunSync() {\n scoped_ptr<echo_api::GetRegistrationCode::Params> params =\n echo_api::GetRegistrationCode::Params::Create(*args_);\n EXTENSION_FUNCTION_VALIDATE(params);\n GetRegistrationCode(params->type);\n return true;\n}\n\nEchoPrivateSetOfferInfoFunction::EchoPrivateSetOfferInfoFunction() {}\n\nEchoPrivateSetOfferInfoFunction::~EchoPrivateSetOfferInfoFunction() {}\n\nbool EchoPrivateSetOfferInfoFunction::RunSync() {\n scoped_ptr<echo_api::SetOfferInfo::Params> params =\n echo_api::SetOfferInfo::Params::Create(*args_);\n EXTENSION_FUNCTION_VALIDATE(params);\n\n const std::string& service_id = params->id;\n base::DictionaryValue* dict = params->offer_info.\n additional_properties.DeepCopyWithoutEmptyChildren();\n\n PrefService* local_state = g_browser_process->local_state();\n DictionaryPrefUpdate offer_update(local_state, prefs::kEchoCheckedOffers);\n offer_update->SetWithoutPathExpansion(\"echo.\" + service_id, dict);\n return true;\n}\n\nEchoPrivateGetOfferInfoFunction::EchoPrivateGetOfferInfoFunction() {}\n\nEchoPrivateGetOfferInfoFunction::~EchoPrivateGetOfferInfoFunction() {}\n\nbool EchoPrivateGetOfferInfoFunction::RunSync() {\n scoped_ptr<echo_api::GetOfferInfo::Params> params =\n echo_api::GetOfferInfo::Params::Create(*args_);\n EXTENSION_FUNCTION_VALIDATE(params);\n\n const std::string& service_id = params->id;\n PrefService* local_state = g_browser_process->local_state();\n const base::DictionaryValue* offer_infos = local_state->\n GetDictionary(prefs::kEchoCheckedOffers);\n\n const base::DictionaryValue* offer_info = NULL;\n if (!offer_infos->GetDictionaryWithoutPathExpansion(\n \"echo.\" + service_id, &offer_info)) {\n error_ = \"Not found\";\n return false;\n }\n\n echo_api::GetOfferInfo::Results::Result result;\n result.additional_properties.MergeDictionary(offer_info);\n results_ = echo_api::GetOfferInfo::Results::Create(result);\n return true;\n}\n\nEchoPrivateGetOobeTimestampFunction::EchoPrivateGetOobeTimestampFunction() {\n}\n\nEchoPrivateGetOobeTimestampFunction::~EchoPrivateGetOobeTimestampFunction() {\n}\n\nbool EchoPrivateGetOobeTimestampFunction::RunAsync() {\n BrowserThread::PostTaskAndReplyWithResult(\n BrowserThread::FILE, FROM_HERE,\n base::Bind(\n &EchoPrivateGetOobeTimestampFunction::GetOobeTimestampOnFileThread,\n this),\n base::Bind(\n &EchoPrivateGetOobeTimestampFunction::SendResponse, this));\n return true;\n}\n\n\/\/ Get the OOBE timestamp from file \/home\/chronos\/.oobe_completed.\n\/\/ The timestamp is used to determine when the user first activates the device.\n\/\/ If we can get the timestamp info, return it as yyyy-mm-dd, otherwise, return\n\/\/ an empty string.\nbool EchoPrivateGetOobeTimestampFunction::GetOobeTimestampOnFileThread() {\n DCHECK_CURRENTLY_ON(BrowserThread::FILE);\n\n const char kOobeTimestampFile[] = \"\/home\/chronos\/.oobe_completed\";\n std::string timestamp = \"\";\n base::File::Info fileInfo;\n if (base::GetFileInfo(base::FilePath(kOobeTimestampFile), &fileInfo)) {\n base::Time::Exploded ctime;\n fileInfo.creation_time.UTCExplode(&ctime);\n timestamp += base::StringPrintf(\"%u-%u-%u\",\n ctime.year,\n ctime.month,\n ctime.day_of_month);\n }\n results_ = echo_api::GetOobeTimestamp::Results::Create(timestamp);\n return true;\n}\n\nEchoPrivateGetUserConsentFunction::EchoPrivateGetUserConsentFunction()\n : redeem_offers_allowed_(false) {\n}\n\n\/\/ static\nscoped_refptr<EchoPrivateGetUserConsentFunction>\nEchoPrivateGetUserConsentFunction::CreateForTest(\n const DialogShownTestCallback& dialog_shown_callback) {\n scoped_refptr<EchoPrivateGetUserConsentFunction> function(\n new EchoPrivateGetUserConsentFunction());\n function->dialog_shown_callback_ = dialog_shown_callback;\n return function;\n}\n\nEchoPrivateGetUserConsentFunction::~EchoPrivateGetUserConsentFunction() {}\n\nbool EchoPrivateGetUserConsentFunction::RunAsync() {\n CheckRedeemOffersAllowed();\n return true;\n}\n\nvoid EchoPrivateGetUserConsentFunction::OnAccept() {\n Finalize(true);\n}\n\nvoid EchoPrivateGetUserConsentFunction::OnCancel() {\n Finalize(false);\n}\n\nvoid EchoPrivateGetUserConsentFunction::OnMoreInfoLinkClicked() {\n chrome::NavigateParams params(\n GetProfile(), GURL(kMoreInfoLink), ui::PAGE_TRANSITION_LINK);\n \/\/ Open the link in a new window. The echo dialog is modal, so the current\n \/\/ window is useless until the dialog is closed.\n params.disposition = NEW_WINDOW;\n chrome::Navigate(¶ms);\n}\n\nvoid EchoPrivateGetUserConsentFunction::CheckRedeemOffersAllowed() {\n chromeos::CrosSettingsProvider::TrustedStatus status =\n chromeos::CrosSettings::Get()->PrepareTrustedValues(base::Bind(\n &EchoPrivateGetUserConsentFunction::CheckRedeemOffersAllowed,\n this));\n if (status == chromeos::CrosSettingsProvider::TEMPORARILY_UNTRUSTED)\n return;\n\n bool allow = true;\n chromeos::CrosSettings::Get()->GetBoolean(\n chromeos::kAllowRedeemChromeOsRegistrationOffers, &allow);\n\n OnRedeemOffersAllowedChecked(allow);\n}\n\nvoid EchoPrivateGetUserConsentFunction::OnRedeemOffersAllowedChecked(\n bool is_allowed) {\n redeem_offers_allowed_ = is_allowed;\n\n scoped_ptr<echo_api::GetUserConsent::Params> params =\n echo_api::GetUserConsent::Params::Create(*args_);\n\n \/\/ Verify that the passed origin URL is valid.\n GURL service_origin = GURL(params->consent_requester.origin);\n if (!service_origin.is_valid()) {\n error_ = \"Invalid origin.\";\n SendResponse(false);\n return;\n }\n\n \/\/ Add ref to ensure the function stays around until the dialog listener is\n \/\/ called. The reference is release in |Finalize|.\n AddRef();\n\n \/\/ Create and show the dialog.\n chromeos::EchoDialogView* dialog = new chromeos::EchoDialogView(this);\n if (redeem_offers_allowed_) {\n dialog->InitForEnabledEcho(\n base::UTF8ToUTF16(params->consent_requester.service_name),\n base::UTF8ToUTF16(params->consent_requester.origin));\n } else {\n dialog->InitForDisabledEcho();\n }\n dialog->Show(GetCurrentBrowser()->window()->GetNativeWindow());\n\n \/\/ If there is a dialog_shown_callback_, invoke it with the created dialog.\n if (!dialog_shown_callback_.is_null())\n dialog_shown_callback_.Run(dialog);\n}\n\nvoid EchoPrivateGetUserConsentFunction::Finalize(bool consent) {\n \/\/ Consent should not be true if offers redeeming is disabled.\n CHECK(redeem_offers_allowed_ || !consent);\n results_ = echo_api::GetUserConsent::Results::Create(consent);\n SendResponse(true);\n\n \/\/ Release the reference added in |OnRedeemOffersAllowedChecked|, before\n \/\/ showing the dialog.\n Release();\n}\n<commit_msg>Fix crash in echoPrivate.getUserConsent when there are no browser windows<commit_after>\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/chromeos\/extensions\/echo_private_api.h\"\n\n#include <string>\n\n#include \"base\/bind.h\"\n#include \"base\/files\/file_util.h\"\n#include \"base\/location.h\"\n#include \"base\/prefs\/pref_registry_simple.h\"\n#include \"base\/prefs\/pref_service.h\"\n#include \"base\/prefs\/scoped_user_pref_update.h\"\n#include \"base\/strings\/stringprintf.h\"\n#include \"base\/strings\/utf_string_conversions.h\"\n#include \"base\/time\/time.h\"\n#include \"base\/values.h\"\n#include \"chrome\/browser\/browser_process.h\"\n#include \"chrome\/browser\/chromeos\/settings\/cros_settings.h\"\n#include \"chrome\/browser\/chromeos\/ui\/echo_dialog_view.h\"\n#include \"chrome\/browser\/ui\/browser.h\"\n#include \"chrome\/common\/extensions\/api\/echo_private.h\"\n#include \"chrome\/common\/pref_names.h\"\n#include \"chromeos\/system\/statistics_provider.h\"\n#include \"content\/public\/browser\/browser_thread.h\"\n#include \"content\/public\/browser\/web_contents.h\"\n#include \"extensions\/common\/extension.h\"\n\nnamespace echo_api = extensions::api::echo_private;\n\nusing content::BrowserThread;\n\nnamespace {\n\n\/\/ URL of \"More info\" link shown in echo dialog in GetUserConsent function.\nconst char kMoreInfoLink[] =\n \"chrome-extension:\/\/honijodknafkokifofgiaalefdiedpko\/main.html?\"\n \"answer=2677280\";\n\n} \/\/ namespace\n\nnamespace chromeos {\n\nnamespace echo_offer {\n\nvoid RegisterPrefs(PrefRegistrySimple* registry) {\n registry->RegisterDictionaryPref(prefs::kEchoCheckedOffers);\n}\n\n} \/\/ namespace echo_offer\n\n} \/\/ namespace chromeos\n\nEchoPrivateGetRegistrationCodeFunction::\n EchoPrivateGetRegistrationCodeFunction() {}\n\nEchoPrivateGetRegistrationCodeFunction::\n ~EchoPrivateGetRegistrationCodeFunction() {}\n\nvoid EchoPrivateGetRegistrationCodeFunction::GetRegistrationCode(\n const std::string& type) {\n \/\/ Possible ECHO code type and corresponding key name in StatisticsProvider.\n const std::string kCouponType = \"COUPON_CODE\";\n const std::string kGroupType = \"GROUP_CODE\";\n\n chromeos::system::StatisticsProvider* provider =\n chromeos::system::StatisticsProvider::GetInstance();\n std::string result;\n if (type == kCouponType) {\n provider->GetMachineStatistic(chromeos::system::kOffersCouponCodeKey,\n &result);\n } else if (type == kGroupType) {\n provider->GetMachineStatistic(chromeos::system::kOffersGroupCodeKey,\n &result);\n }\n\n results_ = echo_api::GetRegistrationCode::Results::Create(result);\n SendResponse(true);\n}\n\nbool EchoPrivateGetRegistrationCodeFunction::RunSync() {\n scoped_ptr<echo_api::GetRegistrationCode::Params> params =\n echo_api::GetRegistrationCode::Params::Create(*args_);\n EXTENSION_FUNCTION_VALIDATE(params);\n GetRegistrationCode(params->type);\n return true;\n}\n\nEchoPrivateSetOfferInfoFunction::EchoPrivateSetOfferInfoFunction() {}\n\nEchoPrivateSetOfferInfoFunction::~EchoPrivateSetOfferInfoFunction() {}\n\nbool EchoPrivateSetOfferInfoFunction::RunSync() {\n scoped_ptr<echo_api::SetOfferInfo::Params> params =\n echo_api::SetOfferInfo::Params::Create(*args_);\n EXTENSION_FUNCTION_VALIDATE(params);\n\n const std::string& service_id = params->id;\n base::DictionaryValue* dict = params->offer_info.\n additional_properties.DeepCopyWithoutEmptyChildren();\n\n PrefService* local_state = g_browser_process->local_state();\n DictionaryPrefUpdate offer_update(local_state, prefs::kEchoCheckedOffers);\n offer_update->SetWithoutPathExpansion(\"echo.\" + service_id, dict);\n return true;\n}\n\nEchoPrivateGetOfferInfoFunction::EchoPrivateGetOfferInfoFunction() {}\n\nEchoPrivateGetOfferInfoFunction::~EchoPrivateGetOfferInfoFunction() {}\n\nbool EchoPrivateGetOfferInfoFunction::RunSync() {\n scoped_ptr<echo_api::GetOfferInfo::Params> params =\n echo_api::GetOfferInfo::Params::Create(*args_);\n EXTENSION_FUNCTION_VALIDATE(params);\n\n const std::string& service_id = params->id;\n PrefService* local_state = g_browser_process->local_state();\n const base::DictionaryValue* offer_infos = local_state->\n GetDictionary(prefs::kEchoCheckedOffers);\n\n const base::DictionaryValue* offer_info = NULL;\n if (!offer_infos->GetDictionaryWithoutPathExpansion(\n \"echo.\" + service_id, &offer_info)) {\n error_ = \"Not found\";\n return false;\n }\n\n echo_api::GetOfferInfo::Results::Result result;\n result.additional_properties.MergeDictionary(offer_info);\n results_ = echo_api::GetOfferInfo::Results::Create(result);\n return true;\n}\n\nEchoPrivateGetOobeTimestampFunction::EchoPrivateGetOobeTimestampFunction() {\n}\n\nEchoPrivateGetOobeTimestampFunction::~EchoPrivateGetOobeTimestampFunction() {\n}\n\nbool EchoPrivateGetOobeTimestampFunction::RunAsync() {\n BrowserThread::PostTaskAndReplyWithResult(\n BrowserThread::FILE, FROM_HERE,\n base::Bind(\n &EchoPrivateGetOobeTimestampFunction::GetOobeTimestampOnFileThread,\n this),\n base::Bind(\n &EchoPrivateGetOobeTimestampFunction::SendResponse, this));\n return true;\n}\n\n\/\/ Get the OOBE timestamp from file \/home\/chronos\/.oobe_completed.\n\/\/ The timestamp is used to determine when the user first activates the device.\n\/\/ If we can get the timestamp info, return it as yyyy-mm-dd, otherwise, return\n\/\/ an empty string.\nbool EchoPrivateGetOobeTimestampFunction::GetOobeTimestampOnFileThread() {\n DCHECK_CURRENTLY_ON(BrowserThread::FILE);\n\n const char kOobeTimestampFile[] = \"\/home\/chronos\/.oobe_completed\";\n std::string timestamp = \"\";\n base::File::Info fileInfo;\n if (base::GetFileInfo(base::FilePath(kOobeTimestampFile), &fileInfo)) {\n base::Time::Exploded ctime;\n fileInfo.creation_time.UTCExplode(&ctime);\n timestamp += base::StringPrintf(\"%u-%u-%u\",\n ctime.year,\n ctime.month,\n ctime.day_of_month);\n }\n results_ = echo_api::GetOobeTimestamp::Results::Create(timestamp);\n return true;\n}\n\nEchoPrivateGetUserConsentFunction::EchoPrivateGetUserConsentFunction()\n : redeem_offers_allowed_(false) {\n}\n\n\/\/ static\nscoped_refptr<EchoPrivateGetUserConsentFunction>\nEchoPrivateGetUserConsentFunction::CreateForTest(\n const DialogShownTestCallback& dialog_shown_callback) {\n scoped_refptr<EchoPrivateGetUserConsentFunction> function(\n new EchoPrivateGetUserConsentFunction());\n function->dialog_shown_callback_ = dialog_shown_callback;\n return function;\n}\n\nEchoPrivateGetUserConsentFunction::~EchoPrivateGetUserConsentFunction() {}\n\nbool EchoPrivateGetUserConsentFunction::RunAsync() {\n CheckRedeemOffersAllowed();\n return true;\n}\n\nvoid EchoPrivateGetUserConsentFunction::OnAccept() {\n Finalize(true);\n}\n\nvoid EchoPrivateGetUserConsentFunction::OnCancel() {\n Finalize(false);\n}\n\nvoid EchoPrivateGetUserConsentFunction::OnMoreInfoLinkClicked() {\n chrome::NavigateParams params(\n GetProfile(), GURL(kMoreInfoLink), ui::PAGE_TRANSITION_LINK);\n \/\/ Open the link in a new window. The echo dialog is modal, so the current\n \/\/ window is useless until the dialog is closed.\n params.disposition = NEW_WINDOW;\n chrome::Navigate(¶ms);\n}\n\nvoid EchoPrivateGetUserConsentFunction::CheckRedeemOffersAllowed() {\n chromeos::CrosSettingsProvider::TrustedStatus status =\n chromeos::CrosSettings::Get()->PrepareTrustedValues(base::Bind(\n &EchoPrivateGetUserConsentFunction::CheckRedeemOffersAllowed,\n this));\n if (status == chromeos::CrosSettingsProvider::TEMPORARILY_UNTRUSTED)\n return;\n\n bool allow = true;\n chromeos::CrosSettings::Get()->GetBoolean(\n chromeos::kAllowRedeemChromeOsRegistrationOffers, &allow);\n\n OnRedeemOffersAllowedChecked(allow);\n}\n\nvoid EchoPrivateGetUserConsentFunction::OnRedeemOffersAllowedChecked(\n bool is_allowed) {\n redeem_offers_allowed_ = is_allowed;\n\n scoped_ptr<echo_api::GetUserConsent::Params> params =\n echo_api::GetUserConsent::Params::Create(*args_);\n\n \/\/ Verify that the passed origin URL is valid.\n GURL service_origin = GURL(params->consent_requester.origin);\n if (!service_origin.is_valid()) {\n error_ = \"Invalid origin.\";\n SendResponse(false);\n return;\n }\n\n content::WebContents* web_contents = GetAssociatedWebContents();\n if (!web_contents) {\n error_ = \"No web contents.\";\n SendResponse(false);\n return;\n }\n\n \/\/ Add ref to ensure the function stays around until the dialog listener is\n \/\/ called. The reference is release in |Finalize|.\n AddRef();\n\n \/\/ Create and show the dialog.\n chromeos::EchoDialogView* dialog = new chromeos::EchoDialogView(this);\n if (redeem_offers_allowed_) {\n dialog->InitForEnabledEcho(\n base::UTF8ToUTF16(params->consent_requester.service_name),\n base::UTF8ToUTF16(params->consent_requester.origin));\n } else {\n dialog->InitForDisabledEcho();\n }\n dialog->Show(web_contents->GetTopLevelNativeWindow());\n\n \/\/ If there is a dialog_shown_callback_, invoke it with the created dialog.\n if (!dialog_shown_callback_.is_null())\n dialog_shown_callback_.Run(dialog);\n}\n\nvoid EchoPrivateGetUserConsentFunction::Finalize(bool consent) {\n \/\/ Consent should not be true if offers redeeming is disabled.\n CHECK(redeem_offers_allowed_ || !consent);\n results_ = echo_api::GetUserConsent::Results::Create(consent);\n SendResponse(true);\n\n \/\/ Release the reference added in |OnRedeemOffersAllowedChecked|, before\n \/\/ showing the dialog.\n Release();\n}\n<|endoftext|>"} {"text":"<commit_before>\n#include <qregexp.h>\n#include <qstylesheet.h>\n\n#include <kdebug.h>\n#include \"oscarmessage.h\"\n#include \"rtf2html.h\"\n\nOscarMessage::OscarMessage()\n{\n\ttimestamp = QDateTime::currentDateTime();\n}\n\nvoid OscarMessage::setText(const QString &txt, MessageFormat format)\n{\n\tif(format == AimHtml)\n\t{\n\t\tkdDebug(14150) << k_funcinfo <<\n\t\t\t\"AIM message text: \" << txt << endl;\n\n\t\tmText = txt;\n\t\tmText.replace(\n\t\t\tQRegExp(\"<html.*>(.*)<\/html>\", false),\n\t\t\t\"\\\\1\");\n\n\t\tmText.replace(\n\t\t\tQRegExp(\"<body.*>(.*)<\/body>\", false),\n\t\t\t\"\\\\1\");\n\n\t\tmText.replace(\n\t\t\tQRegExp(\"<font(.*)back=\\\"(.*)\\\"(.*)>(.*)<\/font>\", false),\n\t\t\t\"<font\\\\1style=\\\"background-color:\\\\2\\\"\\\\3>\\\\4<\/font>\");\n\t}\n\telse if (format == Plain)\n\t{\n\t\tmText = QStyleSheet::escape(txt);\n\t\tmText.replace(\"\\n\",\n\t\t\t\"<br\/>\");\n\t\tmText.replace(\"\\t\",\n\t\t\t\"     \");\n\t\tmText.replace(QRegExp(\"\\\\s\\\\s\"),\n\t\t\t\"  \");\n\t}\n\telse\n\t{\n\t\tRTF2HTML parser;\n\t\t\/*kdDebug(14150) << k_funcinfo <<\n\t\t\t\"Original message text: \" << txt << endl;*\/\n\t\t\/\/TODO: encoding\n\t\tmText = parser.Parse(txt.latin1(), \"\");\n\t\t\/*kdDebug(14150) << k_funcinfo <<\n\t\t\t\"Message text after RTF2HTML: \" << mText << endl;*\/\n\t}\n}\n\nconst QString &OscarMessage::text()\n{\n\treturn mText;\n}\n\n\nconst OscarMessage::MessageType OscarMessage::type()\n{\n\treturn mType;\n}\n\nvoid OscarMessage::setType(const MessageType val)\n{\n\tmType = val;\n}\n<commit_msg>Make Nicholas Pilon happy although it does not affect the outcome of the regexp, there is no html tag more complex than that in aim html<commit_after>\n#include <qregexp.h>\n#include <qstylesheet.h>\n\n#include <kdebug.h>\n#include \"oscarmessage.h\"\n#include \"rtf2html.h\"\n\nOscarMessage::OscarMessage()\n{\n\ttimestamp = QDateTime::currentDateTime();\n}\n\nvoid OscarMessage::setText(const QString &txt, MessageFormat format)\n{\n\tif(format == AimHtml)\n\t{\n\t\tkdDebug(14150) << k_funcinfo <<\n\t\t\t\"AIM message text: \" << txt << endl;\n\n\t\tmText = txt;\n\t\tmText.replace(\n\t\t\tQRegExp(\"<html.*>(.*)<\/html>\", false),\n\t\t\t\"\\\\1\");\n\n\t\tmText.replace(\n\t\t\tQRegExp(\"<body.*>(.*)<\/body>\", false),\n\t\t\t\"\\\\1\");\n\n\t\tQRegExp re(\"<font(.*)back=\\\"(.*)\\\"(.*)>(.*)<\/font>\", false);\n\t\tre.setMinimal(true);\n\t\tmText.replace(re,\n\t\t\t\"<font\\\\1style=\\\"background-color:\\\\2\\\"\\\\3>\\\\4<\/font>\");\n\t}\n\telse if (format == Plain)\n\t{\n\t\tmText = QStyleSheet::escape(txt);\n\t\tmText.replace(\"\\n\",\n\t\t\t\"<br\/>\");\n\t\tmText.replace(\"\\t\",\n\t\t\t\"     \");\n\t\tmText.replace(QRegExp(\"\\\\s\\\\s\"),\n\t\t\t\"  \");\n\t}\n\telse\n\t{\n\t\tRTF2HTML parser;\n\t\t\/*kdDebug(14150) << k_funcinfo <<\n\t\t\t\"Original message text: \" << txt << endl;*\/\n\t\t\/\/TODO: encoding\n\t\tmText = parser.Parse(txt.latin1(), \"\");\n\t\t\/*kdDebug(14150) << k_funcinfo <<\n\t\t\t\"Message text after RTF2HTML: \" << mText << endl;*\/\n\t}\n}\n\nconst QString &OscarMessage::text()\n{\n\treturn mText;\n}\n\n\nconst OscarMessage::MessageType OscarMessage::type()\n{\n\treturn mType;\n}\n\nvoid OscarMessage::setType(const MessageType val)\n{\n\tmType = val;\n}\n<|endoftext|>"} {"text":"<commit_before>#include <pamix_ui.hpp>\n\n#include <pamix.hpp>\n\nvoid pamix_ui::reset() {\n\tm_Entries = nullptr;\n\tm_VolumeBarLineNums.clear();\n\tm_EntrySizes.clear();\n\tm_NumDrawnEntries = 0;\n\tm_NumSkippedEntries = 0;\n\tm_SelectedEntry = m_SelectedChannel = 0;\n}\n\nvoid pamix_ui::drawVolumeBar(int y, int x, int width, double fill, double maxFill) const {\n\n\tint segments = width - 2;\n\n\tif (segments <= 0)\n\t\treturn;\n\n\tif (fill < 0)\n\t\tfill = 0;\n\telse if (fill > maxFill)\n\t\tfill = maxFill;\n\n\tauto filled = (unsigned) (fill \/ maxFill * (double) segments);\n\tif (filled > segments)\n\t\tfilled = (unsigned) segments;\n\n\tmvaddstr(y, x++, \"[\");\n\tmvaddstr(y, x + segments, \"]\");\n\n\tauto indexColorA = (int) (segments * ((double) 1 \/ 3));\n\tauto indexColorB = (int) (segments * ((double) 2 \/ 3));\n\n\tFEAT_UNICODE_STRING meter;\n\n\tmeter.append(filled, SYM_VOLBAR);\n\tmeter.append((unsigned) segments - filled, SYM_SPACE);\n\tattron(COLOR_PAIR(1));\n\tFEAT_UNICODE_MVADDNSTR(y, x, meter.c_str(), indexColorA);\n\tattroff(COLOR_PAIR(1));\n\tattron(COLOR_PAIR(2));\n\tFEAT_UNICODE_MVADDNSTR(y, x + indexColorA, meter.c_str() + indexColorA, indexColorB - indexColorA);\n\tattroff(COLOR_PAIR(2));\n\tattron(COLOR_PAIR(3));\n\tFEAT_UNICODE_MVADDNSTR(y, x + indexColorB, meter.c_str() + indexColorB, segments - indexColorB);\n\tattroff(COLOR_PAIR(3));\n}\n\nvoid string_maxlen_abs(std::string &str, unsigned max) {\n\tif (str.length() > max) {\n\t\tstr = str.substr(0, max - 2);\n\t\tstr.append(\"..\");\n\t}\n}\n\nvoid string_maxlen_pct(std::string &str, double maxPct) {\n\tstring_maxlen_abs(str, (unsigned) (COLS * maxPct));\n}\n\nvoid pamix_ui::redrawAll() {\n\tstd::lock_guard<std::mutex> lockGuard(m_DrawMutex);\n\n\tif (!m_paInterface->isConnected()) {\n\t\tclear();\n\t\tmvprintw(1, 1, \"No connection to pulseaudio yet\");\n\t\trefresh();\n\t\treturn;\n\t}\n\n\tclear();\n\tdrawHeader();\n\n\tunsigned lineNumber = 2;\n\tunsigned entryIndex = 0;\n\n\tauto entryIter = m_Entries->begin();\n\tfor (auto end = m_Entries->end(); entryIter != end; entryIter++, entryIndex++)\n\t\tm_EntrySizes[entryIndex] = entryIter->second->m_Lock ? (char) 1 : entryIter->second->m_PAVolume.channels;\n\n\tentryIndex = m_NumSkippedEntries;\n\tentryIter = std::next(m_Entries->begin(), entryIndex);\n\n\tfor (auto end = m_Entries->end(); entryIter != end; entryIter++, entryIndex++) {\n\t\tEntry *entry = entryIter->second.get();\n\n\t\tstd::string applicationName = entryIter->second ? entry->m_Name : \"\";\n\t\tpa_volume_t averageVolume = pa_cvolume_avg(&entry->m_PAVolume);\n\t\tchar numChannels = entry->m_Lock ? (char) 1 : entry->m_PAVolume.channels;\n\t\tbool isSelectedEntry = entryIndex == m_SelectedEntry;\n\n\t\tif (lineNumber + numChannels + 2 > (unsigned) LINES)\n\t\t\tbreak;\n\n\t\tlineNumber = drawEntryControlMeters(entry, entryIndex, lineNumber);\n\n\t\tdouble volumePeak = entry->m_Peak;\n\t\tm_VolumeBarLineNums[entryIter->first] = lineNumber;\n\t\tif (entry->m_Meter)\n\t\t\tdrawVolumeBar(lineNumber++, 1, COLS - 2, volumePeak, 1.0);\n\n\t\tstring_maxlen_pct(applicationName, 0.4);\n\t\tif (isSelectedEntry)\n\t\t\tattron(A_STANDOUT);\n\t\tmvprintw(lineNumber++, 1, applicationName.c_str());\n\t\tattroff(A_STANDOUT);\n\n\t\tbool isMuted = entry->m_Mute || averageVolume == PA_VOLUME_MUTED;\n\t\tprintw(\" %s %s\", isMuted ? SYM_MUTE : \"\", entry->m_Lock ? SYM_LOCK : \"\");\n\n\t\tint curX = 0, curY = 0;\n\t\tgetyx(stdscr, curY, curX);\n\t\tunsigned remainingChars = (unsigned) COLS - curX - 3;\n\n\t\tstd::string displayName = getEntryDisplayName(entry);\n\t\tif (remainingChars < displayName.length()) {\n\t\t\tstring_maxlen_abs(displayName, remainingChars);\n\t\t\tremainingChars = 0;\n\t\t} else {\n\t\t\tremainingChars -= displayName.length();\n\t\t}\n\n\t\tmvprintw(curY, curX + remainingChars + 1, displayName.c_str());\n\t\tlineNumber++;\n\t}\n\n\tm_NumDrawnEntries = entryIndex - m_NumSkippedEntries;\n\trefresh();\n}\n\nunsigned int pamix_ui::drawEntryControlMeters(const Entry *entry, unsigned entryIndex, unsigned int lineNumber) const {\n\tpa_volume_t averageVolume = pa_cvolume_avg(&entry->m_PAVolume);\n\tdouble dB = pa_sw_volume_to_dB(averageVolume);\n\tdouble vol = averageVolume \/ (double) PA_VOLUME_NORM;\n\tchar numChannels = entry->m_Lock ? (char) 1 : entry->m_PAVolume.channels;\n\tbool isSelectedEntry = entryIndex == m_SelectedEntry;\n\tif (entry->m_Meter) {\n\t\tif (entry->m_Lock) {\n\t\t\tdrawVolumeBar(lineNumber, 32, COLS - 33, vol, MAX_VOL);\n\n\t\t\tstd::string descriptionTemplate = \"%.2fdB (%.2f)\";\n\t\t\tif (isSelectedEntry)\n\t\t\t\tdescriptionTemplate.insert(0, SYM_ARROW);\n\t\t\tmvprintw(lineNumber++, 1, descriptionTemplate.c_str(), dB, vol);\n\t\t} else {\n\t\t\tfor (char channel = 0; channel < numChannels; channel++) {\n\t\t\t\tstd::string descriptionTemplate = \"%.*s %.2fdB (%.2f)\";\n\n\t\t\t\tuint32_t volume = entry->m_PAVolume.values[channel];\n\t\t\t\tbool isSelectedChannel = isSelectedEntry && channel == m_SelectedChannel;\n\t\t\t\tdouble channel_dB = pa_sw_volume_to_dB(volume);\n\t\t\t\tdouble channel_pct = volume \/ (double) PA_VOLUME_NORM;\n\t\t\t\tpa_channel_position_t channelPosition = entry->m_PAChannelMap.map[channel];\n\t\t\t\tstd::string channelPrettyName = pa_channel_position_to_pretty_string(channelPosition);\n\n\t\t\t\tdrawVolumeBar(lineNumber, 32, COLS - 33, channel_pct, MAX_VOL);\n\t\t\t\tif (isSelectedChannel)\n\t\t\t\t\tdescriptionTemplate.insert(0, SYM_ARROW);\n\n\t\t\t\tunsigned indent = isSelectedChannel ? 13 : 15;\n\t\t\t\tmvprintw(lineNumber++, 1, descriptionTemplate.c_str(), indent, channelPrettyName.c_str(), channel_dB,\n\t\t\t\t channel_pct);\n\t\t\t}\n\t\t}\n\t}\n\treturn lineNumber;\n}\n\nvoid pamix_ui::redrawVolumeBars() {\n\tstd::lock_guard<std::mutex> lockGuard(m_DrawMutex);\n\n\tauto it = std::next(m_Entries->begin(), m_NumSkippedEntries);\n\tuint32_t index = 0;\n\tfor (auto end = m_Entries->end(); it != end; it++, index++) {\n\t\tif (index >= m_NumSkippedEntries + m_NumDrawnEntries)\n\t\t\tbreak;\n\t\tuint32_t y = m_VolumeBarLineNums[it->first];\n\t\tif (it->second->m_Meter)\n\t\t\tdrawVolumeBar(y, 1, COLS - 2, it->second->m_Peak, 1.0);\n\t}\n\n\trefresh();\n}\n\nvoid pamix_ui::drawHeader() const {\n\tmvprintw(0, 1, \"%d\/%d\", m_Entries->empty() ? 0 : m_SelectedEntry + 1, m_Entries->size());\n\tmvprintw(0, 10, \"%s\", entryTypeNames[m_EntriesType]);\n}\n\nstd::string pamix_ui::getEntryDisplayName(Entry *entry) {\n\tswitch (m_EntriesType) {\n\t\tcase ENTRY_SINK:\n\t\tcase ENTRY_SOURCE: {\n\t\t\tauto deviceEntry = ((DeviceEntry *) entry);\n\t\t\tif (deviceEntry != nullptr) {\n\t\t\t\tconst DeviceEntry::DeviceProfile *deviceProfile = deviceEntry->getPortProfile();\n\t\t\t\tif (deviceProfile != nullptr)\n\t\t\t\t\treturn deviceProfile->description.empty() ? deviceProfile->name : deviceProfile->description;\n\t\t\t\telse\n\t\t\t\t\treturn deviceEntry->m_Name;\n\t\t\t}\n\t\t\treturn \"\";\n\t\t}\n\t\tcase ENTRY_SINKINPUT: {\n\t\t\tauto sinkInput = (SinkInputEntry *) entry;\n\t\t\treturn m_paInterface->getSinks()[sinkInput->m_Device]->m_Name;\n\t\t}\n\t\tcase ENTRY_SOURCEOUTPUT: {\n\t\t\tauto sourceOutput = (SourceOutputEntry *) entry;\n\t\t\treturn m_paInterface->getSources()[sourceOutput->m_Device]->m_Name;\n\t\t}\n\t\tcase ENTRY_CARDS: {\n\t\t\treturn ((CardEntry *) entry)->m_Profiles[((CardEntry *) entry)->m_Profile].description;\n\t\t}\n\t\tdefault:\n\t\t\treturn \"UNKNOWN ENTRY TYPE\";\n\t}\n}\n\npamix_ui::pamix_ui(PAInterface *paInterface) : m_paInterface(paInterface) {\n\treset();\n}\n\nvoid pamix_ui::selectEntries(entry_type type) {\n\tswitch (type) {\n\t\tcase ENTRY_SINK:\n\t\t\tm_Entries = &m_paInterface->getSinks();\n\t\t\tbreak;\n\t\tcase ENTRY_SOURCE:\n\t\t\tm_Entries = &m_paInterface->getSources();\n\t\t\tbreak;\n\t\tcase ENTRY_SINKINPUT:\n\t\t\tm_Entries = &m_paInterface->getSinkInputs();\n\t\t\tbreak;\n\t\tcase ENTRY_SOURCEOUTPUT:\n\t\t\tm_Entries = &m_paInterface->getSourceOutputs();\n\t\t\tbreak;\n\t\tcase ENTRY_CARDS:\n\t\t\tm_Entries = &m_paInterface->getCards();\n\t\t\tbreak;\n\t\tdefault:\n\t\t\treturn;\n\t}\n\tm_EntriesType = type;\n\n\tif (m_SelectedEntry > 0 && m_SelectedEntry >= m_Entries->size())\n\t\tm_SelectedEntry = (unsigned) m_Entries->size() - 1;\n\tauto currentEntry = getSelectedEntryIterator();\n\tif (currentEntry != m_Entries->end() && m_SelectedChannel > 0 &&\n\t m_SelectedChannel >= currentEntry->second->m_PAVolume.channels)\n\t\tm_SelectedChannel = (unsigned) currentEntry->second->m_PAVolume.channels - 1;\n}\n\nint pamix_ui::getKeyInput() {\n\tstd::lock_guard<std::mutex> guard(m_DrawMutex);\n\treturn getch();\n}\n\npamix_entry_iter_t pamix_ui::getSelectedEntryIterator() {\n\tif (m_SelectedEntry < m_Entries->size())\n\t\treturn std::next(m_Entries->begin(), m_SelectedEntry);\n\telse\n\t\treturn m_Entries->end();\n}\n\nvoid pamix_ui::adjustDisplayedEntries() {\n\tif (!m_Entries->empty())\n\t\treturn;\n\tif (m_SelectedEntry >= m_NumSkippedEntries && m_SelectedEntry < m_NumSkippedEntries + m_NumDrawnEntries)\n\t\treturn;\n\tif (m_SelectedEntry < m_NumSkippedEntries) {\n\t\t\/\/ scroll up until selected is at top\n\t\tm_NumSkippedEntries = m_SelectedEntry;\n\t} else {\n\t\t\/\/ scroll down until selected is at bottom\n\t\tuint32_t linesToFree = 0;\n\t\tuint32_t idx = m_NumSkippedEntries + m_NumDrawnEntries;\n\t\tfor (; idx <= m_SelectedEntry; idx++)\n\t\t\tlinesToFree += m_EntrySizes[idx] + 2;\n\n\t\tuint32_t linesFreed = 0;\n\t\tidx = m_NumSkippedEntries;\n\t\twhile (linesFreed < linesToFree)\n\t\t\tlinesFreed += m_EntrySizes[idx++] + 2;\n\t\tm_NumSkippedEntries = idx;\n\t}\n}\n\nvoid pamix_ui::selectNext(bool includeChannels) {\n\tmoveSelection(1, includeChannels);\n}\n\nvoid pamix_ui::selectPrevious(bool includeChannels) {\n\tmoveSelection(-1, includeChannels);\n}\n\nvoid pamix_ui::moveSelection(int delta, bool includeChannels) {\n\tif (m_SelectedEntry < m_Entries->size()) {\n\t\tauto it = getSelectedEntryIterator();\n\n\t\tint step = delta > 0 ? 1 : -1;\n\n\t\tfor (int i = 0, numSteps = delta < 0 ? -delta : delta; i < numSteps; i++) {\n\t\t\tauto entryThresh = static_cast<int>(delta < 0 ? 0 : m_Entries->size() - 1);\n\n\t\t\tif (includeChannels && m_EntriesType != ENTRY_CARDS) {\n\t\t\t\tbool isLocked = it->second->m_Lock;\n\t\t\t\tint channelThresh = it->second->m_PAVolume.channels - 1;\n\t\t\t\tif (delta < 0)\n\t\t\t\t\tchannelThresh = 0;\n\n\t\t\t\tif (!isLocked && m_SelectedChannel != channelThresh) {\n\t\t\t\t\tm_SelectedChannel += step;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif ((step == -1 && it == m_Entries->begin()) || (step == 1 && it == m_Entries->end()))\n\t\t\t\tbreak;\n\n\t\t\tif (m_SelectedEntry != entryThresh) {\n\t\t\t\tit = std::next(it, step);\n\t\t\t\tm_SelectedEntry += step;\n\n\t\t\t\tm_SelectedChannel = static_cast<unsigned int>(delta < 0 ? it->second->m_PAVolume.channels - (char) 1 : 0);\n\t\t\t}\n\t\t}\n\t}\n\tadjustDisplayedEntries();\n}\n\n<commit_msg>fix bug preventing entries from being scrolled.<commit_after>#include <pamix_ui.hpp>\n\n#include <pamix.hpp>\n\nvoid pamix_ui::reset() {\n\tm_Entries = nullptr;\n\tm_VolumeBarLineNums.clear();\n\tm_EntrySizes.clear();\n\tm_NumDrawnEntries = 0;\n\tm_NumSkippedEntries = 0;\n\tm_SelectedEntry = m_SelectedChannel = 0;\n}\n\nvoid pamix_ui::drawVolumeBar(int y, int x, int width, double fill, double maxFill) const {\n\n\tint segments = width - 2;\n\n\tif (segments <= 0)\n\t\treturn;\n\n\tif (fill < 0)\n\t\tfill = 0;\n\telse if (fill > maxFill)\n\t\tfill = maxFill;\n\n\tauto filled = (unsigned) (fill \/ maxFill * (double) segments);\n\tif (filled > segments)\n\t\tfilled = (unsigned) segments;\n\n\tmvaddstr(y, x++, \"[\");\n\tmvaddstr(y, x + segments, \"]\");\n\n\tauto indexColorA = (int) (segments * ((double) 1 \/ 3));\n\tauto indexColorB = (int) (segments * ((double) 2 \/ 3));\n\n\tFEAT_UNICODE_STRING meter;\n\n\tmeter.append(filled, SYM_VOLBAR);\n\tmeter.append((unsigned) segments - filled, SYM_SPACE);\n\tattron(COLOR_PAIR(1));\n\tFEAT_UNICODE_MVADDNSTR(y, x, meter.c_str(), indexColorA);\n\tattroff(COLOR_PAIR(1));\n\tattron(COLOR_PAIR(2));\n\tFEAT_UNICODE_MVADDNSTR(y, x + indexColorA, meter.c_str() + indexColorA, indexColorB - indexColorA);\n\tattroff(COLOR_PAIR(2));\n\tattron(COLOR_PAIR(3));\n\tFEAT_UNICODE_MVADDNSTR(y, x + indexColorB, meter.c_str() + indexColorB, segments - indexColorB);\n\tattroff(COLOR_PAIR(3));\n}\n\nvoid string_maxlen_abs(std::string &str, unsigned max) {\n\tif (str.length() > max) {\n\t\tstr = str.substr(0, max - 2);\n\t\tstr.append(\"..\");\n\t}\n}\n\nvoid string_maxlen_pct(std::string &str, double maxPct) {\n\tstring_maxlen_abs(str, (unsigned) (COLS * maxPct));\n}\n\nvoid pamix_ui::redrawAll() {\n\tstd::lock_guard<std::mutex> lockGuard(m_DrawMutex);\n\n\tif (!m_paInterface->isConnected()) {\n\t\tclear();\n\t\tmvprintw(1, 1, \"No connection to pulseaudio yet\");\n\t\trefresh();\n\t\treturn;\n\t}\n\n\tclear();\n\tdrawHeader();\n\n\tunsigned lineNumber = 2;\n\tunsigned entryIndex = 0;\n\n\tauto entryIter = m_Entries->begin();\n\tfor (auto end = m_Entries->end(); entryIter != end; entryIter++, entryIndex++)\n\t\tm_EntrySizes[entryIndex] = entryIter->second->m_Lock ? (char) 1 : entryIter->second->m_PAVolume.channels;\n\n\tentryIndex = m_NumSkippedEntries;\n\tentryIter = std::next(m_Entries->begin(), entryIndex);\n\n\tfor (auto end = m_Entries->end(); entryIter != end; entryIter++, entryIndex++) {\n\t\tEntry *entry = entryIter->second.get();\n\n\t\tstd::string applicationName = entryIter->second ? entry->m_Name : \"\";\n\t\tpa_volume_t averageVolume = pa_cvolume_avg(&entry->m_PAVolume);\n\t\tchar numChannels = entry->m_Lock ? (char) 1 : entry->m_PAVolume.channels;\n\t\tbool isSelectedEntry = entryIndex == m_SelectedEntry;\n\n\t\tif (lineNumber + numChannels + 2 > (unsigned) LINES)\n\t\t\tbreak;\n\n\t\tlineNumber = drawEntryControlMeters(entry, entryIndex, lineNumber);\n\n\t\tdouble volumePeak = entry->m_Peak;\n\t\tm_VolumeBarLineNums[entryIter->first] = lineNumber;\n\t\tif (entry->m_Meter)\n\t\t\tdrawVolumeBar(lineNumber++, 1, COLS - 2, volumePeak, 1.0);\n\n\t\tstring_maxlen_pct(applicationName, 0.4);\n\t\tif (isSelectedEntry)\n\t\t\tattron(A_STANDOUT);\n\t\tmvprintw(lineNumber++, 1, applicationName.c_str());\n\t\tattroff(A_STANDOUT);\n\n\t\tbool isMuted = entry->m_Mute || averageVolume == PA_VOLUME_MUTED;\n\t\tprintw(\" %s %s\", isMuted ? SYM_MUTE : \"\", entry->m_Lock ? SYM_LOCK : \"\");\n\n\t\tint curX = 0, curY = 0;\n\t\tgetyx(stdscr, curY, curX);\n\t\tunsigned remainingChars = (unsigned) COLS - curX - 3;\n\n\t\tstd::string displayName = getEntryDisplayName(entry);\n\t\tif (remainingChars < displayName.length()) {\n\t\t\tstring_maxlen_abs(displayName, remainingChars);\n\t\t\tremainingChars = 0;\n\t\t} else {\n\t\t\tremainingChars -= displayName.length();\n\t\t}\n\n\t\tmvprintw(curY, curX + remainingChars + 1, displayName.c_str());\n\t\tlineNumber++;\n\t}\n\n\tm_NumDrawnEntries = entryIndex - m_NumSkippedEntries;\n\trefresh();\n}\n\nunsigned int pamix_ui::drawEntryControlMeters(const Entry *entry, unsigned entryIndex, unsigned int lineNumber) const {\n\tpa_volume_t averageVolume = pa_cvolume_avg(&entry->m_PAVolume);\n\tdouble dB = pa_sw_volume_to_dB(averageVolume);\n\tdouble vol = averageVolume \/ (double) PA_VOLUME_NORM;\n\tchar numChannels = entry->m_Lock ? (char) 1 : entry->m_PAVolume.channels;\n\tbool isSelectedEntry = entryIndex == m_SelectedEntry;\n\tif (entry->m_Meter) {\n\t\tif (entry->m_Lock) {\n\t\t\tdrawVolumeBar(lineNumber, 32, COLS - 33, vol, MAX_VOL);\n\n\t\t\tstd::string descriptionTemplate = \"%.2fdB (%.2f)\";\n\t\t\tif (isSelectedEntry)\n\t\t\t\tdescriptionTemplate.insert(0, SYM_ARROW);\n\t\t\tmvprintw(lineNumber++, 1, descriptionTemplate.c_str(), dB, vol);\n\t\t} else {\n\t\t\tfor (char channel = 0; channel < numChannels; channel++) {\n\t\t\t\tstd::string descriptionTemplate = \"%.*s %.2fdB (%.2f)\";\n\n\t\t\t\tuint32_t volume = entry->m_PAVolume.values[channel];\n\t\t\t\tbool isSelectedChannel = isSelectedEntry && channel == m_SelectedChannel;\n\t\t\t\tdouble channel_dB = pa_sw_volume_to_dB(volume);\n\t\t\t\tdouble channel_pct = volume \/ (double) PA_VOLUME_NORM;\n\t\t\t\tpa_channel_position_t channelPosition = entry->m_PAChannelMap.map[channel];\n\t\t\t\tstd::string channelPrettyName = pa_channel_position_to_pretty_string(channelPosition);\n\n\t\t\t\tdrawVolumeBar(lineNumber, 32, COLS - 33, channel_pct, MAX_VOL);\n\t\t\t\tif (isSelectedChannel)\n\t\t\t\t\tdescriptionTemplate.insert(0, SYM_ARROW);\n\n\t\t\t\tunsigned indent = isSelectedChannel ? 13 : 15;\n\t\t\t\tmvprintw(lineNumber++, 1, descriptionTemplate.c_str(), indent, channelPrettyName.c_str(), channel_dB,\n\t\t\t\t channel_pct);\n\t\t\t}\n\t\t}\n\t}\n\treturn lineNumber;\n}\n\nvoid pamix_ui::redrawVolumeBars() {\n\tstd::lock_guard<std::mutex> lockGuard(m_DrawMutex);\n\n\tauto it = std::next(m_Entries->begin(), m_NumSkippedEntries);\n\tuint32_t index = 0;\n\tfor (auto end = m_Entries->end(); it != end; it++, index++) {\n\t\tif (index >= m_NumSkippedEntries + m_NumDrawnEntries)\n\t\t\tbreak;\n\t\tuint32_t y = m_VolumeBarLineNums[it->first];\n\t\tif (it->second->m_Meter)\n\t\t\tdrawVolumeBar(y, 1, COLS - 2, it->second->m_Peak, 1.0);\n\t}\n\n\trefresh();\n}\n\nvoid pamix_ui::drawHeader() const {\n\tmvprintw(0, 1, \"%d\/%d\", m_Entries->empty() ? 0 : m_SelectedEntry + 1, m_Entries->size());\n\tmvprintw(0, 10, \"%s\", entryTypeNames[m_EntriesType]);\n}\n\nstd::string pamix_ui::getEntryDisplayName(Entry *entry) {\n\tswitch (m_EntriesType) {\n\t\tcase ENTRY_SINK:\n\t\tcase ENTRY_SOURCE: {\n\t\t\tauto deviceEntry = ((DeviceEntry *) entry);\n\t\t\tif (deviceEntry != nullptr) {\n\t\t\t\tconst DeviceEntry::DeviceProfile *deviceProfile = deviceEntry->getPortProfile();\n\t\t\t\tif (deviceProfile != nullptr)\n\t\t\t\t\treturn deviceProfile->description.empty() ? deviceProfile->name : deviceProfile->description;\n\t\t\t\telse\n\t\t\t\t\treturn deviceEntry->m_Name;\n\t\t\t}\n\t\t\treturn \"\";\n\t\t}\n\t\tcase ENTRY_SINKINPUT: {\n\t\t\tauto sinkInput = (SinkInputEntry *) entry;\n\t\t\treturn m_paInterface->getSinks()[sinkInput->m_Device]->m_Name;\n\t\t}\n\t\tcase ENTRY_SOURCEOUTPUT: {\n\t\t\tauto sourceOutput = (SourceOutputEntry *) entry;\n\t\t\treturn m_paInterface->getSources()[sourceOutput->m_Device]->m_Name;\n\t\t}\n\t\tcase ENTRY_CARDS: {\n\t\t\treturn ((CardEntry *) entry)->m_Profiles[((CardEntry *) entry)->m_Profile].description;\n\t\t}\n\t\tdefault:\n\t\t\treturn \"UNKNOWN ENTRY TYPE\";\n\t}\n}\n\npamix_ui::pamix_ui(PAInterface *paInterface) : m_paInterface(paInterface) {\n\treset();\n}\n\nvoid pamix_ui::selectEntries(entry_type type) {\n\tswitch (type) {\n\t\tcase ENTRY_SINK:\n\t\t\tm_Entries = &m_paInterface->getSinks();\n\t\t\tbreak;\n\t\tcase ENTRY_SOURCE:\n\t\t\tm_Entries = &m_paInterface->getSources();\n\t\t\tbreak;\n\t\tcase ENTRY_SINKINPUT:\n\t\t\tm_Entries = &m_paInterface->getSinkInputs();\n\t\t\tbreak;\n\t\tcase ENTRY_SOURCEOUTPUT:\n\t\t\tm_Entries = &m_paInterface->getSourceOutputs();\n\t\t\tbreak;\n\t\tcase ENTRY_CARDS:\n\t\t\tm_Entries = &m_paInterface->getCards();\n\t\t\tbreak;\n\t\tdefault:\n\t\t\treturn;\n\t}\n\tm_EntriesType = type;\n\n\tif (m_SelectedEntry > 0 && m_SelectedEntry >= m_Entries->size())\n\t\tm_SelectedEntry = (unsigned) m_Entries->size() - 1;\n\tauto currentEntry = getSelectedEntryIterator();\n\tif (currentEntry != m_Entries->end() && m_SelectedChannel > 0 &&\n\t m_SelectedChannel >= currentEntry->second->m_PAVolume.channels)\n\t\tm_SelectedChannel = (unsigned) currentEntry->second->m_PAVolume.channels - 1;\n}\n\nint pamix_ui::getKeyInput() {\n\tstd::lock_guard<std::mutex> guard(m_DrawMutex);\n\treturn getch();\n}\n\npamix_entry_iter_t pamix_ui::getSelectedEntryIterator() {\n\tif (m_SelectedEntry < m_Entries->size())\n\t\treturn std::next(m_Entries->begin(), m_SelectedEntry);\n\telse\n\t\treturn m_Entries->end();\n}\n\nvoid pamix_ui::adjustDisplayedEntries() {\n\tif (m_Entries->empty())\n\t\treturn;\n\tif (m_SelectedEntry >= m_NumSkippedEntries && m_SelectedEntry < m_NumSkippedEntries + m_NumDrawnEntries)\n\t\treturn;\n\tif (m_SelectedEntry < m_NumSkippedEntries) {\n\t\t\/\/ scroll up until selected is at top\n\t\tm_NumSkippedEntries = m_SelectedEntry;\n\t} else {\n\t\t\/\/ scroll down until selected is at bottom\n\t\tuint32_t linesToFree = 0;\n\t\tuint32_t idx = m_NumSkippedEntries + m_NumDrawnEntries;\n\t\tfor (; idx <= m_SelectedEntry; idx++)\n\t\t\tlinesToFree += m_EntrySizes[idx] + 2;\n\n\t\tuint32_t linesFreed = 0;\n\t\tidx = m_NumSkippedEntries;\n\t\twhile (linesFreed < linesToFree)\n\t\t\tlinesFreed += m_EntrySizes[idx++] + 2;\n\t\tm_NumSkippedEntries = idx;\n\t}\n}\n\nvoid pamix_ui::selectNext(bool includeChannels) {\n\tmoveSelection(1, includeChannels);\n}\n\nvoid pamix_ui::selectPrevious(bool includeChannels) {\n\tmoveSelection(-1, includeChannels);\n}\n\nvoid pamix_ui::moveSelection(int delta, bool includeChannels) {\n\tif (m_SelectedEntry < m_Entries->size()) {\n\t\tauto it = getSelectedEntryIterator();\n\n\t\tint step = delta > 0 ? 1 : -1;\n\n\t\tfor (int i = 0, numSteps = delta < 0 ? -delta : delta; i < numSteps; i++) {\n\t\t\tauto entryThresh = static_cast<int>(delta < 0 ? 0 : m_Entries->size() - 1);\n\n\t\t\tif (includeChannels && m_EntriesType != ENTRY_CARDS) {\n\t\t\t\tbool isLocked = it->second->m_Lock;\n\t\t\t\tint channelThresh = it->second->m_PAVolume.channels - 1;\n\t\t\t\tif (delta < 0)\n\t\t\t\t\tchannelThresh = 0;\n\n\t\t\t\tif (!isLocked && m_SelectedChannel != channelThresh) {\n\t\t\t\t\tm_SelectedChannel += step;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif ((step == -1 && it == m_Entries->begin()) || (step == 1 && it == m_Entries->end()))\n\t\t\t\tbreak;\n\n\t\t\tif (m_SelectedEntry != entryThresh) {\n\t\t\t\tit = std::next(it, step);\n\t\t\t\tm_SelectedEntry += step;\n\n\t\t\t\tm_SelectedChannel = static_cast<unsigned int>(delta < 0 ? it->second->m_PAVolume.channels - (char) 1 : 0);\n\t\t\t}\n\t\t}\n\t}\n\tadjustDisplayedEntries();\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2009 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"base\/command_line.h\"\n#include \"chrome\/browser\/extensions\/extension_apitest.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n\nIN_PROC_BROWSER_TEST_F(ExtensionApiTest, History) {\n CommandLine::ForCurrentProcess()->AppendSwitch(\n switches::kEnableExperimentalExtensionApis);\n\n host_resolver()->AddRule(\"www.a.com\", \"127.0.0.1\");\n host_resolver()->AddRule(\"www.b.com\", \"127.0.0.1\");\n StartHTTPServer();\n\n ASSERT_TRUE(RunExtensionTest(\"history\")) << message_;\n}\n<commit_msg>Disable flaky test. See http:\/\/crbug.com\/26296 BUG=26296 TEST=none Review URL: http:\/\/codereview.chromium.org\/346021<commit_after>\/\/ Copyright (c) 2009 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"base\/command_line.h\"\n#include \"chrome\/browser\/extensions\/extension_apitest.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n\n\/\/ Flaky, http:\/\/crbug.com\/26296.\nIN_PROC_BROWSER_TEST_F(ExtensionApiTest, DISABLED_History) {\n CommandLine::ForCurrentProcess()->AppendSwitch(\n switches::kEnableExperimentalExtensionApis);\n\n host_resolver()->AddRule(\"www.a.com\", \"127.0.0.1\");\n host_resolver()->AddRule(\"www.b.com\", \"127.0.0.1\");\n StartHTTPServer();\n\n ASSERT_TRUE(RunExtensionTest(\"history\")) << message_;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2015-2016 The Bitcoin Core developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include <vector>\n#include \"prevector.h\"\n\n#include \"serialize.h\"\n#include \"streams.h\"\n\n#include \"test\/test_bitcoin.h\"\n\n#include <boost\/test\/unit_test.hpp>\n\nBOOST_FIXTURE_TEST_SUITE(PrevectorTests, TestingSetup)\n\ntemplate<unsigned int N, typename T>\nclass prevector_tester {\n typedef std::vector<T> realtype;\n realtype real_vector;\n realtype real_vector_alt;\n\n typedef prevector<N, T> pretype;\n pretype pre_vector;\n pretype pre_vector_alt;\n\n typedef typename pretype::size_type Size;\n bool passed = true;\n FastRandomContext rand_cache;\n uint256 rand_seed;\n\n\n template <typename A, typename B>\n void local_check_equal(A a, B b)\n {\n local_check(a == b);\n }\n void local_check(bool b) \n {\n passed &= b;\n }\n void test() {\n const pretype& const_pre_vector = pre_vector;\n local_check_equal(real_vector.size(), pre_vector.size());\n local_check_equal(real_vector.empty(), pre_vector.empty());\n for (Size s = 0; s < real_vector.size(); s++) {\n local_check(real_vector[s] == pre_vector[s]);\n local_check(&(pre_vector[s]) == &(pre_vector.begin()[s]));\n local_check(&(pre_vector[s]) == &*(pre_vector.begin() + s));\n local_check(&(pre_vector[s]) == &*((pre_vector.end() + s) - real_vector.size()));\n }\n \/\/ local_check(realtype(pre_vector) == real_vector);\n local_check(pretype(real_vector.begin(), real_vector.end()) == pre_vector);\n local_check(pretype(pre_vector.begin(), pre_vector.end()) == pre_vector);\n size_t pos = 0;\n BOOST_FOREACH(const T& v, pre_vector) {\n local_check(v == real_vector[pos++]);\n }\n BOOST_REVERSE_FOREACH(const T& v, pre_vector) {\n local_check(v == real_vector[--pos]);\n }\n BOOST_FOREACH(const T& v, const_pre_vector) {\n local_check(v == real_vector[pos++]);\n }\n BOOST_REVERSE_FOREACH(const T& v, const_pre_vector) {\n local_check(v == real_vector[--pos]);\n }\n CDataStream ss1(SER_DISK, 0);\n CDataStream ss2(SER_DISK, 0);\n ss1 << real_vector;\n ss2 << pre_vector;\n local_check_equal(ss1.size(), ss2.size());\n for (Size s = 0; s < ss1.size(); s++) {\n local_check_equal(ss1[s], ss2[s]);\n }\n }\n\npublic:\n void resize(Size s) {\n real_vector.resize(s);\n local_check_equal(real_vector.size(), s);\n pre_vector.resize(s);\n local_check_equal(pre_vector.size(), s);\n test();\n }\n\n void reserve(Size s) {\n real_vector.reserve(s);\n local_check(real_vector.capacity() >= s);\n pre_vector.reserve(s);\n local_check(pre_vector.capacity() >= s);\n test();\n }\n\n void insert(Size position, const T& value) {\n real_vector.insert(real_vector.begin() + position, value);\n pre_vector.insert(pre_vector.begin() + position, value);\n test();\n }\n\n void insert(Size position, Size count, const T& value) {\n real_vector.insert(real_vector.begin() + position, count, value);\n pre_vector.insert(pre_vector.begin() + position, count, value);\n test();\n }\n\n template<typename I>\n void insert_range(Size position, I first, I last) {\n real_vector.insert(real_vector.begin() + position, first, last);\n pre_vector.insert(pre_vector.begin() + position, first, last);\n test();\n }\n\n void erase(Size position) {\n real_vector.erase(real_vector.begin() + position);\n pre_vector.erase(pre_vector.begin() + position);\n test();\n }\n\n void erase(Size first, Size last) {\n real_vector.erase(real_vector.begin() + first, real_vector.begin() + last);\n pre_vector.erase(pre_vector.begin() + first, pre_vector.begin() + last);\n test();\n }\n\n void update(Size pos, const T& value) {\n real_vector[pos] = value;\n pre_vector[pos] = value;\n test();\n }\n\n void push_back(const T& value) {\n real_vector.push_back(value);\n pre_vector.push_back(value);\n test();\n }\n\n void pop_back() {\n real_vector.pop_back();\n pre_vector.pop_back();\n test();\n }\n\n void clear() {\n real_vector.clear();\n pre_vector.clear();\n }\n\n void assign(Size n, const T& value) {\n real_vector.assign(n, value);\n pre_vector.assign(n, value);\n }\n\n Size size() {\n return real_vector.size();\n }\n\n Size capacity() {\n return pre_vector.capacity();\n }\n\n void shrink_to_fit() {\n pre_vector.shrink_to_fit();\n test();\n }\n\n void swap() {\n real_vector.swap(real_vector_alt);\n pre_vector.swap(pre_vector_alt);\n test();\n }\n\n void move() {\n real_vector = std::move(real_vector_alt);\n real_vector_alt.clear();\n pre_vector = std::move(pre_vector_alt);\n pre_vector_alt.clear();\n }\n\n void copy() {\n real_vector = real_vector_alt;\n pre_vector = pre_vector_alt;\n }\n\n ~prevector_tester() {\n BOOST_CHECK_MESSAGE(passed, \"insecure_rand: \" + rand_seed.ToString());\n }\n\n prevector_tester() {\n seed_insecure_rand();\n rand_seed = insecure_rand_seed;\n rand_cache = insecure_rand_ctx;\n }\n};\n\nBOOST_AUTO_TEST_CASE(PrevectorTestInt)\n{\n for (int j = 0; j < 64; j++) {\n prevector_tester<8, int> test;\n for (int i = 0; i < 2048; i++) {\n int r = insecure_rand();\n if ((r % 4) == 0) {\n test.insert(insecure_randrange(test.size() + 1), insecure_rand());\n }\n if (test.size() > 0 && ((r >> 2) % 4) == 1) {\n test.erase(insecure_randrange(test.size()));\n }\n if (((r >> 4) % 8) == 2) {\n int new_size = std::max<int>(0, std::min<int>(30, test.size() + (insecure_randrange(5)) - 2));\n test.resize(new_size);\n }\n if (((r >> 7) % 8) == 3) {\n test.insert(insecure_randrange(test.size() + 1), 1 + insecure_randrange(2), insecure_rand());\n }\n if (((r >> 10) % 8) == 4) {\n int del = std::min<int>(test.size(), 1 + (insecure_randrange(2)));\n int beg = insecure_randrange(test.size() + 1 - del);\n test.erase(beg, beg + del);\n }\n if (((r >> 13) % 16) == 5) {\n test.push_back(insecure_rand());\n }\n if (test.size() > 0 && ((r >> 17) % 16) == 6) {\n test.pop_back();\n }\n if (((r >> 21) % 32) == 7) {\n int values[4];\n int num = 1 + (insecure_randrange(4));\n for (int k = 0; k < num; k++) {\n values[k] = insecure_rand();\n }\n test.insert_range(insecure_randrange(test.size() + 1), values, values + num);\n }\n if (((r >> 26) % 32) == 8) {\n int del = std::min<int>(test.size(), 1 + (insecure_randrange(4)));\n int beg = insecure_randrange(test.size() + 1 - del);\n test.erase(beg, beg + del);\n }\n r = insecure_rand();\n if (r % 32 == 9) {\n test.reserve(insecure_randrange(32));\n }\n if ((r >> 5) % 64 == 10) {\n test.shrink_to_fit();\n }\n if (test.size() > 0) {\n test.update(insecure_randrange(test.size()), insecure_rand());\n }\n if (((r >> 11) % 1024) == 11) {\n test.clear();\n }\n if (((r >> 21) % 512) == 12) {\n test.assign(insecure_randrange(32), insecure_rand());\n }\n if (((r >> 15) % 8) == 3) {\n test.swap();\n }\n if (((r >> 15) % 16) == 8) {\n test.copy();\n }\n if (((r >> 15) % 32) == 18) {\n test.move();\n }\n }\n }\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n<commit_msg>Use randbits instead of ad-hoc emulation in prevector tests<commit_after>\/\/ Copyright (c) 2015-2016 The Bitcoin Core developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include <vector>\n#include \"prevector.h\"\n\n#include \"serialize.h\"\n#include \"streams.h\"\n\n#include \"test\/test_bitcoin.h\"\n\n#include <boost\/test\/unit_test.hpp>\n\nBOOST_FIXTURE_TEST_SUITE(PrevectorTests, TestingSetup)\n\ntemplate<unsigned int N, typename T>\nclass prevector_tester {\n typedef std::vector<T> realtype;\n realtype real_vector;\n realtype real_vector_alt;\n\n typedef prevector<N, T> pretype;\n pretype pre_vector;\n pretype pre_vector_alt;\n\n typedef typename pretype::size_type Size;\n bool passed = true;\n FastRandomContext rand_cache;\n uint256 rand_seed;\n\n\n template <typename A, typename B>\n void local_check_equal(A a, B b)\n {\n local_check(a == b);\n }\n void local_check(bool b) \n {\n passed &= b;\n }\n void test() {\n const pretype& const_pre_vector = pre_vector;\n local_check_equal(real_vector.size(), pre_vector.size());\n local_check_equal(real_vector.empty(), pre_vector.empty());\n for (Size s = 0; s < real_vector.size(); s++) {\n local_check(real_vector[s] == pre_vector[s]);\n local_check(&(pre_vector[s]) == &(pre_vector.begin()[s]));\n local_check(&(pre_vector[s]) == &*(pre_vector.begin() + s));\n local_check(&(pre_vector[s]) == &*((pre_vector.end() + s) - real_vector.size()));\n }\n \/\/ local_check(realtype(pre_vector) == real_vector);\n local_check(pretype(real_vector.begin(), real_vector.end()) == pre_vector);\n local_check(pretype(pre_vector.begin(), pre_vector.end()) == pre_vector);\n size_t pos = 0;\n BOOST_FOREACH(const T& v, pre_vector) {\n local_check(v == real_vector[pos++]);\n }\n BOOST_REVERSE_FOREACH(const T& v, pre_vector) {\n local_check(v == real_vector[--pos]);\n }\n BOOST_FOREACH(const T& v, const_pre_vector) {\n local_check(v == real_vector[pos++]);\n }\n BOOST_REVERSE_FOREACH(const T& v, const_pre_vector) {\n local_check(v == real_vector[--pos]);\n }\n CDataStream ss1(SER_DISK, 0);\n CDataStream ss2(SER_DISK, 0);\n ss1 << real_vector;\n ss2 << pre_vector;\n local_check_equal(ss1.size(), ss2.size());\n for (Size s = 0; s < ss1.size(); s++) {\n local_check_equal(ss1[s], ss2[s]);\n }\n }\n\npublic:\n void resize(Size s) {\n real_vector.resize(s);\n local_check_equal(real_vector.size(), s);\n pre_vector.resize(s);\n local_check_equal(pre_vector.size(), s);\n test();\n }\n\n void reserve(Size s) {\n real_vector.reserve(s);\n local_check(real_vector.capacity() >= s);\n pre_vector.reserve(s);\n local_check(pre_vector.capacity() >= s);\n test();\n }\n\n void insert(Size position, const T& value) {\n real_vector.insert(real_vector.begin() + position, value);\n pre_vector.insert(pre_vector.begin() + position, value);\n test();\n }\n\n void insert(Size position, Size count, const T& value) {\n real_vector.insert(real_vector.begin() + position, count, value);\n pre_vector.insert(pre_vector.begin() + position, count, value);\n test();\n }\n\n template<typename I>\n void insert_range(Size position, I first, I last) {\n real_vector.insert(real_vector.begin() + position, first, last);\n pre_vector.insert(pre_vector.begin() + position, first, last);\n test();\n }\n\n void erase(Size position) {\n real_vector.erase(real_vector.begin() + position);\n pre_vector.erase(pre_vector.begin() + position);\n test();\n }\n\n void erase(Size first, Size last) {\n real_vector.erase(real_vector.begin() + first, real_vector.begin() + last);\n pre_vector.erase(pre_vector.begin() + first, pre_vector.begin() + last);\n test();\n }\n\n void update(Size pos, const T& value) {\n real_vector[pos] = value;\n pre_vector[pos] = value;\n test();\n }\n\n void push_back(const T& value) {\n real_vector.push_back(value);\n pre_vector.push_back(value);\n test();\n }\n\n void pop_back() {\n real_vector.pop_back();\n pre_vector.pop_back();\n test();\n }\n\n void clear() {\n real_vector.clear();\n pre_vector.clear();\n }\n\n void assign(Size n, const T& value) {\n real_vector.assign(n, value);\n pre_vector.assign(n, value);\n }\n\n Size size() {\n return real_vector.size();\n }\n\n Size capacity() {\n return pre_vector.capacity();\n }\n\n void shrink_to_fit() {\n pre_vector.shrink_to_fit();\n test();\n }\n\n void swap() {\n real_vector.swap(real_vector_alt);\n pre_vector.swap(pre_vector_alt);\n test();\n }\n\n void move() {\n real_vector = std::move(real_vector_alt);\n real_vector_alt.clear();\n pre_vector = std::move(pre_vector_alt);\n pre_vector_alt.clear();\n }\n\n void copy() {\n real_vector = real_vector_alt;\n pre_vector = pre_vector_alt;\n }\n\n ~prevector_tester() {\n BOOST_CHECK_MESSAGE(passed, \"insecure_rand: \" + rand_seed.ToString());\n }\n\n prevector_tester() {\n seed_insecure_rand();\n rand_seed = insecure_rand_seed;\n rand_cache = insecure_rand_ctx;\n }\n};\n\nBOOST_AUTO_TEST_CASE(PrevectorTestInt)\n{\n for (int j = 0; j < 64; j++) {\n prevector_tester<8, int> test;\n for (int i = 0; i < 2048; i++) {\n if (insecure_randbits(2) == 0) {\n test.insert(insecure_randrange(test.size() + 1), insecure_rand());\n }\n if (test.size() > 0 && insecure_randbits(2) == 1) {\n test.erase(insecure_randrange(test.size()));\n }\n if (insecure_randbits(3) == 2) {\n int new_size = std::max<int>(0, std::min<int>(30, test.size() + (insecure_randrange(5)) - 2));\n test.resize(new_size);\n }\n if (insecure_randbits(3) == 3) {\n test.insert(insecure_randrange(test.size() + 1), 1 + insecure_randrange(2), insecure_rand());\n }\n if (insecure_randbits(3) == 4) {\n int del = std::min<int>(test.size(), 1 + (insecure_randrange(2)));\n int beg = insecure_randrange(test.size() + 1 - del);\n test.erase(beg, beg + del);\n }\n if (insecure_randbits(4) == 5) {\n test.push_back(insecure_rand());\n }\n if (test.size() > 0 && insecure_randbits(4) == 6) {\n test.pop_back();\n }\n if (insecure_randbits(5) == 7) {\n int values[4];\n int num = 1 + (insecure_randrange(4));\n for (int k = 0; k < num; k++) {\n values[k] = insecure_rand();\n }\n test.insert_range(insecure_randrange(test.size() + 1), values, values + num);\n }\n if (insecure_randbits(5) == 8) {\n int del = std::min<int>(test.size(), 1 + (insecure_randrange(4)));\n int beg = insecure_randrange(test.size() + 1 - del);\n test.erase(beg, beg + del);\n }\n if (insecure_randbits(5) == 9) {\n test.reserve(insecure_randrange(32));\n }\n if (insecure_randbits(6) == 10) {\n test.shrink_to_fit();\n }\n if (test.size() > 0) {\n test.update(insecure_randrange(test.size()), insecure_rand());\n }\n if (insecure_randbits(10) == 11) {\n test.clear();\n }\n if (insecure_randbits(9) == 12) {\n test.assign(insecure_randrange(32), insecure_rand());\n }\n if (insecure_randbits(3) == 3) {\n test.swap();\n }\n if (insecure_randbits(4) == 8) {\n test.copy();\n }\n if (insecure_randbits(5) == 18) {\n test.move();\n }\n }\n }\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"base\/command_line.h\"\n#include \"chrome\/browser\/extensions\/extension_apitest.h\"\n#include \"net\/base\/mock_host_resolver.h\"\n\nclass ExtensionHistoryApiTest : public ExtensionApiTest {\n public:\n virtual void SetUpInProcessBrowserTestFixture() {\n ExtensionApiTest::SetUpInProcessBrowserTestFixture();\n\n host_resolver()->AddRule(\"www.a.com\", \"127.0.0.1\");\n host_resolver()->AddRule(\"www.b.com\", \"127.0.0.1\");\n\n ASSERT_TRUE(StartTestServer());\n }\n};\n\n\/\/ Flaky, http:\/\/crbug.com\/26296.\nIN_PROC_BROWSER_TEST_F(ExtensionHistoryApiTest, FLAKY_MiscSearch) {\n ASSERT_TRUE(RunExtensionSubtest(\"history\", \"misc_search.html\")) << message_;\n}\n\nIN_PROC_BROWSER_TEST_F(ExtensionHistoryApiTest, TimedSearch) {\n ASSERT_TRUE(RunExtensionSubtest(\"history\", \"timed_search.html\")) << message_;\n}\n\nIN_PROC_BROWSER_TEST_F(ExtensionHistoryApiTest, Delete) {\n ASSERT_TRUE(RunExtensionSubtest(\"history\", \"delete.html\")) << message_;\n}\n\n\/\/ Flaky, http:\/\/crbug.com\/26296.\nIN_PROC_BROWSER_TEST_F(ExtensionHistoryApiTest, FLAKY_GetVisits) {\n ASSERT_TRUE(RunExtensionSubtest(\"history\", \"get_visits.html\")) << message_;\n}\n<commit_msg>Mark all history tests as flaky. They no longer time out or crash, but still fail flakily.<commit_after>\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"base\/command_line.h\"\n#include \"chrome\/browser\/extensions\/extension_apitest.h\"\n#include \"net\/base\/mock_host_resolver.h\"\n\nclass ExtensionHistoryApiTest : public ExtensionApiTest {\n public:\n virtual void SetUpInProcessBrowserTestFixture() {\n ExtensionApiTest::SetUpInProcessBrowserTestFixture();\n\n host_resolver()->AddRule(\"www.a.com\", \"127.0.0.1\");\n host_resolver()->AddRule(\"www.b.com\", \"127.0.0.1\");\n\n ASSERT_TRUE(StartTestServer());\n }\n};\n\n\/\/ Flaky, http:\/\/crbug.com\/26296.\nIN_PROC_BROWSER_TEST_F(ExtensionHistoryApiTest, FLAKY_MiscSearch) {\n ASSERT_TRUE(RunExtensionSubtest(\"history\", \"misc_search.html\")) << message_;\n}\n\n\/\/ Flaky, http:\/\/crbug.com\/26296.\nIN_PROC_BROWSER_TEST_F(ExtensionHistoryApiTest, FLAKY_TimedSearch) {\n ASSERT_TRUE(RunExtensionSubtest(\"history\", \"timed_search.html\")) << message_;\n}\n\n\/\/ Flaky, http:\/\/crbug.com\/26296.\nIN_PROC_BROWSER_TEST_F(ExtensionHistoryApiTest, FLAKY_Delete) {\n ASSERT_TRUE(RunExtensionSubtest(\"history\", \"delete.html\")) << message_;\n}\n\n\/\/ Flaky, http:\/\/crbug.com\/26296.\nIN_PROC_BROWSER_TEST_F(ExtensionHistoryApiTest, FLAKY_GetVisits) {\n ASSERT_TRUE(RunExtensionSubtest(\"history\", \"get_visits.html\")) << message_;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*****************************************************************************\n * Project: RooFit *\n * Package: RooFitCore *\n * @(#)root\/roofitcore:$Id$\n * Authors: *\n * WV, Wouter Verkerke, UC Santa Barbara, verkerke@slac.stanford.edu *\n * DK, David Kirkby, UC Irvine, dkirkby@uci.edu *\n * *\n * Copyright (c) 2000-2005, Regents of the University of California *\n * and Stanford University. All rights reserved. *\n * *\n * Redistribution and use in source and binary forms, *\n * with or without modification, are permitted according to the terms *\n * listed in LICENSE (http:\/\/roofit.sourceforge.net\/license.txt) *\n *****************************************************************************\/\n\n\/**\n\\file RooNumIntConfig.cxx\n\\class RooNumIntConfig\n\\ingroup Roofitcore\n\nRooNumIntConfig holds the configuration parameters of the various\nnumeric integrators used by RooRealIntegral. RooRealIntegral and RooAbsPdf\nuse this class in the (normalization) integral configuration interface\n**\/\n\n#include \"RooFit.h\"\n#include \"Riostream.h\"\n\n#include \"RooNumIntConfig.h\"\n#include \"RooArgSet.h\"\n#include \"RooAbsIntegrator.h\"\n#include \"RooNumIntFactory.h\"\n#include \"RooMsgService.h\"\n\n#include \"TClass.h\"\n\n\n\nusing namespace std;\n\nClassImp(RooNumIntConfig)\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Return reference to instance of default numeric integrator configuration object\n\nRooNumIntConfig& RooNumIntConfig::defaultConfig() \n{\n static RooNumIntConfig theConfig;\n static bool initStarted = false;\n\n if (!initStarted) {\n \/\/ This is needed to break a deadlock. We need the RooNumIntFactory constructor\n \/\/ to initialise us, but this constructor will call back to us again.\n \/\/ Here, we ensure that we can return the instance to the factory constructor by\n \/\/ flipping the bool, but we only return to the outside world when the factory\n \/\/ is done constructing (i.e. we leave this block).\n initStarted = true;\n RooNumIntFactory::instance();\n }\n\n return theConfig;\n}\n\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Constructor \n\nRooNumIntConfig::RooNumIntConfig() : \n _epsAbs(1e-7),\n _epsRel(1e-7),\n _printEvalCounter(kFALSE),\n _method1D(\"method1D\",\"1D integration method\"),\n _method2D(\"method2D\",\"2D integration method\"),\n _methodND(\"methodND\",\"ND integration method\"),\n _method1DOpen(\"method1DOpen\",\"1D integration method in open domain\"),\n _method2DOpen(\"method2DOpen\",\"2D integration method in open domain\"),\n _methodNDOpen(\"methodNDOpen\",\"ND integration method in open domain\")\n{\n \/\/ Set all methods to undefined\n \/\/ Defined methods will be registered by static initialization routines\n \/\/ of the various numeric integrator engines\n _method1D.defineType(\"N\/A\",0) ;\n _method2D.defineType(\"N\/A\",0) ;\n _methodND.defineType(\"N\/A\",0) ;\n _method1DOpen.defineType(\"N\/A\",0) ;\n _method2DOpen.defineType(\"N\/A\",0) ;\n _methodNDOpen.defineType(\"N\/A\",0) ;\n}\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Destructor\n\nRooNumIntConfig::~RooNumIntConfig()\n{\n \/\/ Delete all configuration data\n _configSets.Delete() ;\n}\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Copy constructor\n\nRooNumIntConfig::RooNumIntConfig(const RooNumIntConfig& other) :\n TObject(other), RooPrintable(other),\n _epsAbs(other._epsAbs),\n _epsRel(other._epsRel),\n _printEvalCounter(other._printEvalCounter),\n _method1D(other._method1D),\n _method2D(other._method2D),\n _methodND(other._methodND),\n _method1DOpen(other._method1DOpen),\n _method2DOpen(other._method2DOpen),\n _methodNDOpen(other._methodNDOpen)\n{\n \/\/ Clone all configuration dat\n TIterator* iter = other._configSets.MakeIterator() ;\n RooArgSet* set ;\n while((set=(RooArgSet*)iter->Next())) {\n RooArgSet* setCopy = (RooArgSet*) set->snapshot() ;\n setCopy->setName(set->GetName()) ;\n _configSets.Add(setCopy);\n }\n delete iter ;\n}\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Assignment operator from other RooNumIntConfig\n\nRooNumIntConfig& RooNumIntConfig::operator=(const RooNumIntConfig& other) \n{\n \/\/ Prevent self-assignment \n if (&other==this) {\n return *this ;\n }\n\n \/\/ Copy common properties\n _epsAbs = other._epsAbs ;\n _epsRel = other._epsRel ;\n _method1D.setIndex(other._method1D.getCurrentIndex()) ;\n _method2D.setIndex(other._method2D.getCurrentIndex()) ;\n _methodND.setIndex(other._methodND.getCurrentIndex()) ;\n _method1DOpen.setIndex(other._method1DOpen.getCurrentIndex()) ;\n _method2DOpen.setIndex(other._method2DOpen.getCurrentIndex()) ;\n _methodNDOpen.setIndex(other._methodNDOpen.getCurrentIndex()) ;\n\n \/\/ Delete old integrator-specific configuration data\n _configSets.Delete() ;\n\n \/\/ Copy new integrator-specific data\n TIterator* iter = other._configSets.MakeIterator() ;\n RooArgSet* set ;\n while((set=(RooArgSet*)iter->Next())) {\n RooArgSet* setCopy = (RooArgSet*) set->snapshot() ;\n setCopy->setName(set->GetName()) ;\n _configSets.Add(setCopy);\n }\n delete iter ;\n\n return *this ;\n}\n\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Add a configuration section for a particular integrator. Integrator name and capabilities are\n\/\/\/ automatically determined from instance passed as 'proto'. The defaultConfig object is associated\n\/\/\/ as the default configuration for the integrator. \n\nBool_t RooNumIntConfig::addConfigSection(const RooAbsIntegrator* proto, const RooArgSet& inDefaultConfig)\n{\n std::string name = proto->IsA()->GetName() ;\n\n \/\/ Register integrator for appropriate dimensionalities\n if (proto->canIntegrate1D()) {\n _method1D.defineType(name) ;\n if (proto->canIntegrateOpenEnded()) {\n _method1DOpen.defineType(name) ;\n }\n }\n\n if (proto->canIntegrate2D()) {\n _method2D.defineType(name) ;\n if (proto->canIntegrateOpenEnded()) {\n _method2DOpen.defineType(name) ;\n }\n }\n\n if (proto->canIntegrateND()) {\n _methodND.defineType(name) ;\n if (proto->canIntegrateOpenEnded()) {\n _methodNDOpen.defineType(name) ;\n }\n }\n \n \/\/ Store default configuration parameters\n RooArgSet* config = (RooArgSet*) inDefaultConfig.snapshot() ;\n config->setName(name.c_str());\n _configSets.Add(config) ;\n\n return kFALSE ;\n}\n\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Return section with configuration parameters for integrator with given (class) name\n\nRooArgSet& RooNumIntConfig::getConfigSection(const char* name) \n{\n return const_cast<RooArgSet&>((const_cast<const RooNumIntConfig*>(this)->getConfigSection(name))) ;\n}\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Retrieve configuration information specific to integrator with given name\n\nconst RooArgSet& RooNumIntConfig::getConfigSection(const char* name) const\n{\n static RooArgSet dummy ;\n RooArgSet* config = (RooArgSet*) _configSets.FindObject(name) ;\n if (!config) {\n oocoutE((TObject*)0,InputArguments) << \"RooNumIntConfig::getIntegrator: ERROR: no configuration stored for integrator '\" << name << \"'\" << endl ;\n return dummy ;\n }\n return *config ;\n}\n\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Set absolute convergence criteria (convergence if abs(Err)<newEpsAbs)\n\nvoid RooNumIntConfig::setEpsAbs(Double_t newEpsAbs)\n{\n if (newEpsAbs<0) {\n oocoutE((TObject*)0,InputArguments) << \"RooNumIntConfig::setEpsAbs: ERROR: target absolute precision must be greater or equal than zero\" << endl ;\n return ;\n }\n _epsAbs = newEpsAbs ;\n}\n\n\nRooPrintable::StyleOption RooNumIntConfig::defaultPrintStyle(Option_t* opt) const \n{ \n if (!opt) {\n return kStandard ;\n }\n\n TString o(opt) ;\n o.ToLower() ;\n\n if (o.Contains(\"v\")) {\n return kVerbose ;\n }\n return kStandard ; \n}\n\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Set relative convergence criteria (convergence if abs(Err)\/abs(Int)<newEpsRel)\n\nvoid RooNumIntConfig::setEpsRel(Double_t newEpsRel) \n{\n if (newEpsRel<0) {\n oocoutE((TObject*)0,InputArguments) << \"RooNumIntConfig::setEpsRel: ERROR: target absolute precision must be greater or equal than zero\" << endl ;\n return ;\n }\n _epsRel = newEpsRel ;\n}\n\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Detailed printing interface\n\nvoid RooNumIntConfig::printMultiline(ostream &os, Int_t \/*content*\/, Bool_t verbose, TString indent) const\n{\n os << indent << \"Requested precision: \" << _epsAbs << \" absolute, \" << _epsRel << \" relative\" << endl << endl ;\n if (_printEvalCounter) {\n os << indent << \"Printing of function evaluation counter for each integration enabled\" << endl << endl ;\n }\n \n os << indent << \"1-D integration method: \" << _method1D.getCurrentLabel() ;\n if (_method1DOpen.getCurrentIndex()!=_method1D.getCurrentIndex()) {\n os << \" (\" << _method1DOpen.getCurrentLabel() << \" if open-ended)\" << endl ;\n } else {\n os << endl ;\n }\n os << indent << \"2-D integration method: \" << _method2D.getCurrentLabel() ;\n if (_method2DOpen.getCurrentIndex()!=_method2D.getCurrentIndex()) {\n os << \" (\" << _method2DOpen.getCurrentLabel() << \" if open-ended)\" << endl ;\n } else {\n os << endl ;\n }\n os << indent << \"N-D integration method: \" << _methodND.getCurrentLabel() ;\n if (_methodNDOpen.getCurrentIndex()!=_methodND.getCurrentIndex()) {\n os << \" (\" << _methodNDOpen.getCurrentLabel() << \" if open-ended)\" << endl ;\n } else {\n os << endl ;\n }\n \n if (verbose) {\n\n os << endl << \"Available integration methods:\" << endl << endl ;\n TIterator* cIter = _configSets.MakeIterator() ;\n RooArgSet* configSet ;\n while ((configSet=(RooArgSet*)cIter->Next())) {\n\n os << indent << \"*** \" << configSet->GetName() << \" ***\" << endl ;\n os << indent << \"Capabilities: \" ;\n const RooAbsIntegrator* proto = RooNumIntFactory::instance().getProtoIntegrator(configSet->GetName()) ;\n if (proto->canIntegrate1D()) os << \"[1-D] \" ;\n if (proto->canIntegrate2D()) os << \"[2-D] \" ;\n if (proto->canIntegrateND()) os << \"[N-D] \" ;\n if (proto->canIntegrateOpenEnded()) os << \"[OpenEnded] \" ;\n os << endl ;\n\n os << \"Configuration: \" << endl ;\n configSet->printMultiline(os,kName|kValue) ;\n \/\/configSet->writeToStream(os,kFALSE) ;\n\n const char* depName = RooNumIntFactory::instance().getDepIntegratorName(configSet->GetName()) ;\n if (strlen(depName)>0) {\n\tos << indent << \"(Depends on '\" << depName << \"')\" << endl ;\n }\n os << endl ;\n\n }\n\n delete cIter ;\n }\n}\n<commit_msg>[RF] Correct an error message.<commit_after>\/*****************************************************************************\n * Project: RooFit *\n * Package: RooFitCore *\n * @(#)root\/roofitcore:$Id$\n * Authors: *\n * WV, Wouter Verkerke, UC Santa Barbara, verkerke@slac.stanford.edu *\n * DK, David Kirkby, UC Irvine, dkirkby@uci.edu *\n * *\n * Copyright (c) 2000-2005, Regents of the University of California *\n * and Stanford University. All rights reserved. *\n * *\n * Redistribution and use in source and binary forms, *\n * with or without modification, are permitted according to the terms *\n * listed in LICENSE (http:\/\/roofit.sourceforge.net\/license.txt) *\n *****************************************************************************\/\n\n\/**\n\\file RooNumIntConfig.cxx\n\\class RooNumIntConfig\n\\ingroup Roofitcore\n\nRooNumIntConfig holds the configuration parameters of the various\nnumeric integrators used by RooRealIntegral. RooRealIntegral and RooAbsPdf\nuse this class in the (normalization) integral configuration interface\n**\/\n\n#include \"RooFit.h\"\n#include \"Riostream.h\"\n\n#include \"RooNumIntConfig.h\"\n#include \"RooArgSet.h\"\n#include \"RooAbsIntegrator.h\"\n#include \"RooNumIntFactory.h\"\n#include \"RooMsgService.h\"\n\n#include \"TClass.h\"\n\n\n\nusing namespace std;\n\nClassImp(RooNumIntConfig)\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Return reference to instance of default numeric integrator configuration object\n\nRooNumIntConfig& RooNumIntConfig::defaultConfig() \n{\n static RooNumIntConfig theConfig;\n static bool initStarted = false;\n\n if (!initStarted) {\n \/\/ This is needed to break a deadlock. We need the RooNumIntFactory constructor\n \/\/ to initialise us, but this constructor will call back to us again.\n \/\/ Here, we ensure that we can return the instance to the factory constructor by\n \/\/ flipping the bool, but we only return to the outside world when the factory\n \/\/ is done constructing (i.e. we leave this block).\n initStarted = true;\n RooNumIntFactory::instance();\n }\n\n return theConfig;\n}\n\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Constructor \n\nRooNumIntConfig::RooNumIntConfig() : \n _epsAbs(1e-7),\n _epsRel(1e-7),\n _printEvalCounter(kFALSE),\n _method1D(\"method1D\",\"1D integration method\"),\n _method2D(\"method2D\",\"2D integration method\"),\n _methodND(\"methodND\",\"ND integration method\"),\n _method1DOpen(\"method1DOpen\",\"1D integration method in open domain\"),\n _method2DOpen(\"method2DOpen\",\"2D integration method in open domain\"),\n _methodNDOpen(\"methodNDOpen\",\"ND integration method in open domain\")\n{\n \/\/ Set all methods to undefined\n \/\/ Defined methods will be registered by static initialization routines\n \/\/ of the various numeric integrator engines\n _method1D.defineType(\"N\/A\",0) ;\n _method2D.defineType(\"N\/A\",0) ;\n _methodND.defineType(\"N\/A\",0) ;\n _method1DOpen.defineType(\"N\/A\",0) ;\n _method2DOpen.defineType(\"N\/A\",0) ;\n _methodNDOpen.defineType(\"N\/A\",0) ;\n}\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Destructor\n\nRooNumIntConfig::~RooNumIntConfig()\n{\n \/\/ Delete all configuration data\n _configSets.Delete() ;\n}\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Copy constructor\n\nRooNumIntConfig::RooNumIntConfig(const RooNumIntConfig& other) :\n TObject(other), RooPrintable(other),\n _epsAbs(other._epsAbs),\n _epsRel(other._epsRel),\n _printEvalCounter(other._printEvalCounter),\n _method1D(other._method1D),\n _method2D(other._method2D),\n _methodND(other._methodND),\n _method1DOpen(other._method1DOpen),\n _method2DOpen(other._method2DOpen),\n _methodNDOpen(other._methodNDOpen)\n{\n \/\/ Clone all configuration dat\n TIterator* iter = other._configSets.MakeIterator() ;\n RooArgSet* set ;\n while((set=(RooArgSet*)iter->Next())) {\n RooArgSet* setCopy = (RooArgSet*) set->snapshot() ;\n setCopy->setName(set->GetName()) ;\n _configSets.Add(setCopy);\n }\n delete iter ;\n}\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Assignment operator from other RooNumIntConfig\n\nRooNumIntConfig& RooNumIntConfig::operator=(const RooNumIntConfig& other) \n{\n \/\/ Prevent self-assignment \n if (&other==this) {\n return *this ;\n }\n\n \/\/ Copy common properties\n _epsAbs = other._epsAbs ;\n _epsRel = other._epsRel ;\n _method1D.setIndex(other._method1D.getCurrentIndex()) ;\n _method2D.setIndex(other._method2D.getCurrentIndex()) ;\n _methodND.setIndex(other._methodND.getCurrentIndex()) ;\n _method1DOpen.setIndex(other._method1DOpen.getCurrentIndex()) ;\n _method2DOpen.setIndex(other._method2DOpen.getCurrentIndex()) ;\n _methodNDOpen.setIndex(other._methodNDOpen.getCurrentIndex()) ;\n\n \/\/ Delete old integrator-specific configuration data\n _configSets.Delete() ;\n\n \/\/ Copy new integrator-specific data\n TIterator* iter = other._configSets.MakeIterator() ;\n RooArgSet* set ;\n while((set=(RooArgSet*)iter->Next())) {\n RooArgSet* setCopy = (RooArgSet*) set->snapshot() ;\n setCopy->setName(set->GetName()) ;\n _configSets.Add(setCopy);\n }\n delete iter ;\n\n return *this ;\n}\n\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Add a configuration section for a particular integrator. Integrator name and capabilities are\n\/\/\/ automatically determined from instance passed as 'proto'. The defaultConfig object is associated\n\/\/\/ as the default configuration for the integrator. \n\nBool_t RooNumIntConfig::addConfigSection(const RooAbsIntegrator* proto, const RooArgSet& inDefaultConfig)\n{\n std::string name = proto->IsA()->GetName() ;\n\n \/\/ Register integrator for appropriate dimensionalities\n if (proto->canIntegrate1D()) {\n _method1D.defineType(name) ;\n if (proto->canIntegrateOpenEnded()) {\n _method1DOpen.defineType(name) ;\n }\n }\n\n if (proto->canIntegrate2D()) {\n _method2D.defineType(name) ;\n if (proto->canIntegrateOpenEnded()) {\n _method2DOpen.defineType(name) ;\n }\n }\n\n if (proto->canIntegrateND()) {\n _methodND.defineType(name) ;\n if (proto->canIntegrateOpenEnded()) {\n _methodNDOpen.defineType(name) ;\n }\n }\n \n \/\/ Store default configuration parameters\n RooArgSet* config = (RooArgSet*) inDefaultConfig.snapshot() ;\n config->setName(name.c_str());\n _configSets.Add(config) ;\n\n return kFALSE ;\n}\n\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Return section with configuration parameters for integrator with given (class) name\n\nRooArgSet& RooNumIntConfig::getConfigSection(const char* name) \n{\n return const_cast<RooArgSet&>((const_cast<const RooNumIntConfig*>(this)->getConfigSection(name))) ;\n}\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Retrieve configuration information specific to integrator with given name\n\nconst RooArgSet& RooNumIntConfig::getConfigSection(const char* name) const\n{\n static RooArgSet dummy ;\n RooArgSet* config = (RooArgSet*) _configSets.FindObject(name) ;\n if (!config) {\n oocoutE((TObject*)0,InputArguments) << \"RooNumIntConfig::getConfigSection: ERROR: no configuration stored for integrator '\" << name << \"'\" << endl ;\n return dummy ;\n }\n return *config ;\n}\n\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Set absolute convergence criteria (convergence if abs(Err)<newEpsAbs)\n\nvoid RooNumIntConfig::setEpsAbs(Double_t newEpsAbs)\n{\n if (newEpsAbs<0) {\n oocoutE((TObject*)0,InputArguments) << \"RooNumIntConfig::setEpsAbs: ERROR: target absolute precision must be greater or equal than zero\" << endl ;\n return ;\n }\n _epsAbs = newEpsAbs ;\n}\n\n\nRooPrintable::StyleOption RooNumIntConfig::defaultPrintStyle(Option_t* opt) const \n{ \n if (!opt) {\n return kStandard ;\n }\n\n TString o(opt) ;\n o.ToLower() ;\n\n if (o.Contains(\"v\")) {\n return kVerbose ;\n }\n return kStandard ; \n}\n\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Set relative convergence criteria (convergence if abs(Err)\/abs(Int)<newEpsRel)\n\nvoid RooNumIntConfig::setEpsRel(Double_t newEpsRel) \n{\n if (newEpsRel<0) {\n oocoutE((TObject*)0,InputArguments) << \"RooNumIntConfig::setEpsRel: ERROR: target absolute precision must be greater or equal than zero\" << endl ;\n return ;\n }\n _epsRel = newEpsRel ;\n}\n\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Detailed printing interface\n\nvoid RooNumIntConfig::printMultiline(ostream &os, Int_t \/*content*\/, Bool_t verbose, TString indent) const\n{\n os << indent << \"Requested precision: \" << _epsAbs << \" absolute, \" << _epsRel << \" relative\" << endl << endl ;\n if (_printEvalCounter) {\n os << indent << \"Printing of function evaluation counter for each integration enabled\" << endl << endl ;\n }\n \n os << indent << \"1-D integration method: \" << _method1D.getCurrentLabel() ;\n if (_method1DOpen.getCurrentIndex()!=_method1D.getCurrentIndex()) {\n os << \" (\" << _method1DOpen.getCurrentLabel() << \" if open-ended)\" << endl ;\n } else {\n os << endl ;\n }\n os << indent << \"2-D integration method: \" << _method2D.getCurrentLabel() ;\n if (_method2DOpen.getCurrentIndex()!=_method2D.getCurrentIndex()) {\n os << \" (\" << _method2DOpen.getCurrentLabel() << \" if open-ended)\" << endl ;\n } else {\n os << endl ;\n }\n os << indent << \"N-D integration method: \" << _methodND.getCurrentLabel() ;\n if (_methodNDOpen.getCurrentIndex()!=_methodND.getCurrentIndex()) {\n os << \" (\" << _methodNDOpen.getCurrentLabel() << \" if open-ended)\" << endl ;\n } else {\n os << endl ;\n }\n \n if (verbose) {\n\n os << endl << \"Available integration methods:\" << endl << endl ;\n TIterator* cIter = _configSets.MakeIterator() ;\n RooArgSet* configSet ;\n while ((configSet=(RooArgSet*)cIter->Next())) {\n\n os << indent << \"*** \" << configSet->GetName() << \" ***\" << endl ;\n os << indent << \"Capabilities: \" ;\n const RooAbsIntegrator* proto = RooNumIntFactory::instance().getProtoIntegrator(configSet->GetName()) ;\n if (proto->canIntegrate1D()) os << \"[1-D] \" ;\n if (proto->canIntegrate2D()) os << \"[2-D] \" ;\n if (proto->canIntegrateND()) os << \"[N-D] \" ;\n if (proto->canIntegrateOpenEnded()) os << \"[OpenEnded] \" ;\n os << endl ;\n\n os << \"Configuration: \" << endl ;\n configSet->printMultiline(os,kName|kValue) ;\n \/\/configSet->writeToStream(os,kFALSE) ;\n\n const char* depName = RooNumIntFactory::instance().getDepIntegratorName(configSet->GetName()) ;\n if (strlen(depName)>0) {\n\tos << indent << \"(Depends on '\" << depName << \"')\" << endl ;\n }\n os << endl ;\n\n }\n\n delete cIter ;\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"base\/format_macros.h\"\n#include \"base\/string_util.h\"\n#include \"base\/stringprintf.h\"\n#include \"base\/utf_string_conversions.h\"\n#include \"chrome\/browser\/autocomplete\/autocomplete.h\"\n#include \"chrome\/browser\/autocomplete\/autocomplete_edit.h\"\n#include \"chrome\/browser\/autocomplete\/autocomplete_match.h\"\n#include \"chrome\/browser\/autocomplete\/autocomplete_popup_model.h\"\n#include \"chrome\/browser\/extensions\/extension_apitest.h\"\n#include \"chrome\/browser\/profiles\/profile.h\"\n#include \"chrome\/browser\/search_engines\/template_url.h\"\n#include \"chrome\/browser\/search_engines\/template_url_service.h\"\n#include \"chrome\/browser\/search_engines\/template_url_service_factory.h\"\n#include \"chrome\/browser\/ui\/browser.h\"\n#include \"chrome\/browser\/ui\/browser_window.h\"\n#include \"chrome\/browser\/ui\/omnibox\/location_bar.h\"\n#include \"chrome\/browser\/ui\/omnibox\/omnibox_view.h\"\n#include \"chrome\/common\/chrome_notification_types.h\"\n#include \"chrome\/common\/url_constants.h\"\n#include \"chrome\/test\/base\/ui_test_utils.h\"\n#include \"content\/public\/browser\/notification_types.h\"\n#include \"content\/public\/browser\/notification_service.h\"\n\n#if defined(TOOLKIT_GTK)\n#include \"chrome\/browser\/ui\/gtk\/browser_window_gtk.h\"\n#endif\n\nnamespace {\n\nstring16 AutocompleteResultAsString(const AutocompleteResult& result) {\n std::string output(base::StringPrintf(\"{%\" PRIuS \"} \", result.size()));\n for (size_t i = 0; i < result.size(); ++i) {\n AutocompleteMatch match = result.match_at(i);\n std::string provider_name = match.provider->name();\n output.append(base::StringPrintf(\"[\\\"%s\\\" by \\\"%s\\\"] \",\n UTF16ToUTF8(match.contents).c_str(),\n provider_name.c_str()));\n }\n return UTF8ToUTF16(output);\n}\n\n} \/\/ namespace\n\nclass OmniboxApiTest : public ExtensionApiTest {\n protected:\n LocationBar* GetLocationBar(Browser* browser) const {\n return browser->window()->GetLocationBar();\n }\n\n AutocompleteController* GetAutocompleteController(Browser* browser) const {\n return GetLocationBar(browser)->location_entry()->model()->popup_model()->\n autocomplete_controller();\n }\n\n void WaitForTemplateURLServiceToLoad() {\n ui_test_utils::WindowedNotificationObserver loaded_observer(\n chrome::NOTIFICATION_TEMPLATE_URL_SERVICE_LOADED,\n content::NotificationService::AllSources());\n TemplateURLService* model =\n TemplateURLServiceFactory::GetForProfile(browser()->profile());\n model->Load();\n if (!model->loaded())\n loaded_observer.Wait();\n }\n\n \/\/ TODO(phajdan.jr): Get rid of this wait-in-a-loop pattern.\n void WaitForAutocompleteDone(AutocompleteController* controller) {\n while (!controller->done()) {\n ui_test_utils::WindowedNotificationObserver ready_observer(\n chrome::NOTIFICATION_AUTOCOMPLETE_CONTROLLER_RESULT_READY,\n content::Source<AutocompleteController>(controller));\n ready_observer.Wait();\n }\n }\n};\n\n#if defined(OS_CHROMEOS)\n\/\/ The test fails on chromeos gtk bot, and linux chromeos aura although it\n\/\/ passes locally. crbug.com\/113455 and crbug.com\/114721\n#define MAYBE_Basic DISABLED_Basic\n#else\n#define MAYBE_Basic Basic\n#endif\n\nIN_PROC_BROWSER_TEST_F(OmniboxApiTest, MAYBE_Basic) {\n#if defined(TOOLKIT_GTK)\n \/\/ Disable the timer because, on Lucid at least, it triggers resize\/move\n \/\/ behavior in the browser window, which dismisses the autocomplete popup\n \/\/ before the results can be read.\n static_cast<BrowserWindowGtk*>(\n browser()->window())->DisableDebounceTimerForTests(true);\n#endif\n\n ASSERT_TRUE(RunExtensionTest(\"omnibox\")) << message_;\n\n \/\/ The results depend on the TemplateURLService being loaded. Make sure it is\n \/\/ loaded so that the autocomplete results are consistent.\n WaitForTemplateURLServiceToLoad();\n\n LocationBar* location_bar = GetLocationBar(browser());\n AutocompleteController* autocomplete_controller =\n GetAutocompleteController(browser());\n\n \/\/ Test that our extension's keyword is suggested to us when we partially type\n \/\/ it.\n {\n autocomplete_controller->Start(\n ASCIIToUTF16(\"keywor\"), string16(), true, false, true,\n AutocompleteInput::ALL_MATCHES);\n WaitForAutocompleteDone(autocomplete_controller);\n EXPECT_TRUE(autocomplete_controller->done());\n\n \/\/ Now, peek into the controller to see if it has the results we expect.\n \/\/ First result should be to search for what was typed, second should be to\n \/\/ enter \"extension keyword\" mode.\n const AutocompleteResult& result = autocomplete_controller->result();\n ASSERT_EQ(2U, result.size()) << AutocompleteResultAsString(result);\n AutocompleteMatch match = result.match_at(0);\n EXPECT_EQ(AutocompleteMatch::SEARCH_WHAT_YOU_TYPED, match.type);\n EXPECT_FALSE(match.deletable);\n\n match = result.match_at(1);\n ASSERT_TRUE(match.template_url);\n EXPECT_TRUE(match.template_url->IsExtensionKeyword());\n EXPECT_EQ(ASCIIToUTF16(\"keyword\"), match.template_url->keyword());\n }\n\n \/\/ Test that our extension can send suggestions back to us.\n {\n autocomplete_controller->Start(\n ASCIIToUTF16(\"keyword suggestio\"), string16(), true, false, true,\n AutocompleteInput::ALL_MATCHES);\n WaitForAutocompleteDone(autocomplete_controller);\n EXPECT_TRUE(autocomplete_controller->done());\n\n \/\/ Now, peek into the controller to see if it has the results we expect.\n \/\/ First result should be to invoke the keyword with what we typed, 2-4\n \/\/ should be to invoke with suggestions from the extension, and the last\n \/\/ should be to search for what we typed.\n const AutocompleteResult& result = autocomplete_controller->result();\n ASSERT_EQ(5U, result.size()) << AutocompleteResultAsString(result);\n\n ASSERT_TRUE(result.match_at(0).template_url);\n EXPECT_EQ(ASCIIToUTF16(\"keyword suggestio\"),\n result.match_at(0).fill_into_edit);\n EXPECT_EQ(ASCIIToUTF16(\"keyword suggestion1\"),\n result.match_at(1).fill_into_edit);\n EXPECT_EQ(ASCIIToUTF16(\"keyword suggestion2\"),\n result.match_at(2).fill_into_edit);\n EXPECT_EQ(ASCIIToUTF16(\"keyword suggestion3\"),\n result.match_at(3).fill_into_edit);\n\n string16 description =\n ASCIIToUTF16(\"Description with style: <match>, [dim], (url till end)\");\n EXPECT_EQ(description, result.match_at(1).contents);\n ASSERT_EQ(6u, result.match_at(1).contents_class.size());\n\n EXPECT_EQ(0u,\n result.match_at(1).contents_class[0].offset);\n EXPECT_EQ(ACMatchClassification::NONE,\n result.match_at(1).contents_class[0].style);\n\n EXPECT_EQ(description.find('<'),\n result.match_at(1).contents_class[1].offset);\n EXPECT_EQ(ACMatchClassification::MATCH,\n result.match_at(1).contents_class[1].style);\n\n EXPECT_EQ(description.find('>') + 1u,\n result.match_at(1).contents_class[2].offset);\n EXPECT_EQ(ACMatchClassification::NONE,\n result.match_at(1).contents_class[2].style);\n\n EXPECT_EQ(description.find('['),\n result.match_at(1).contents_class[3].offset);\n EXPECT_EQ(ACMatchClassification::DIM,\n result.match_at(1).contents_class[3].style);\n\n EXPECT_EQ(description.find(']') + 1u,\n result.match_at(1).contents_class[4].offset);\n EXPECT_EQ(ACMatchClassification::NONE,\n result.match_at(1).contents_class[4].style);\n\n EXPECT_EQ(description.find('('),\n result.match_at(1).contents_class[5].offset);\n EXPECT_EQ(ACMatchClassification::URL,\n result.match_at(1).contents_class[5].style);\n\n AutocompleteMatch match = result.match_at(4);\n EXPECT_EQ(AutocompleteMatch::SEARCH_WHAT_YOU_TYPED, match.type);\n EXPECT_FALSE(match.deletable);\n }\n\n {\n ResultCatcher catcher;\n location_bar->location_entry()->OnBeforePossibleChange();\n location_bar->location_entry()->SetUserText(\n ASCIIToUTF16(\"keyword command\"));\n location_bar->location_entry()->OnAfterPossibleChange();\n location_bar->AcceptInput();\n \/\/ This checks that the keyword provider (via javascript)\n \/\/ gets told to navigate to the string \"command\".\n EXPECT_TRUE(catcher.GetNextResult()) << catcher.message();\n }\n}\n\n#if defined(OS_CHROMEOS) && !defined(USE_AURA)\n\/\/ The test fails on chromeos gtk bot, although it passes locally.\n\/\/ crbug.com\/113455.\n#define MAYBE_PopupStaysClosed DISABLED_PopupStaysClosed\n#else\n#define MAYBE_PopupStaysClosed PopupStaysClosed\n#endif\n\n\/\/ Tests that the autocomplete popup doesn't reopen after accepting input for\n\/\/ a given query.\n\/\/ http:\/\/crbug.com\/88552\nIN_PROC_BROWSER_TEST_F(OmniboxApiTest, MAYBE_PopupStaysClosed) {\n#if defined(TOOLKIT_GTK)\n \/\/ Disable the timer because, on Lucid at least, it triggers resize\/move\n \/\/ behavior in the browser window, which dismisses the autocomplete popup\n \/\/ before the results can be read.\n static_cast<BrowserWindowGtk*>(\n browser()->window())->DisableDebounceTimerForTests(true);\n#endif\n\n ASSERT_TRUE(RunExtensionTest(\"omnibox\")) << message_;\n\n \/\/ The results depend on the TemplateURLService being loaded. Make sure it is\n \/\/ loaded so that the autocomplete results are consistent.\n WaitForTemplateURLServiceToLoad();\n\n LocationBar* location_bar = GetLocationBar(browser());\n AutocompleteController* autocomplete_controller =\n GetAutocompleteController(browser());\n AutocompletePopupModel* popup_model =\n GetLocationBar(browser())->location_entry()->model()->popup_model();\n\n \/\/ Input a keyword query and wait for suggestions from the extension.\n location_bar->location_entry()->OnBeforePossibleChange();\n location_bar->location_entry()->SetUserText(ASCIIToUTF16(\"keyword comman\"));\n location_bar->location_entry()->OnAfterPossibleChange();\n WaitForAutocompleteDone(autocomplete_controller);\n EXPECT_TRUE(autocomplete_controller->done());\n EXPECT_TRUE(popup_model->IsOpen());\n\n \/\/ Quickly type another query and accept it before getting suggestions back\n \/\/ for the query. The popup will close after accepting input - ensure that it\n \/\/ does not reopen when the extension returns its suggestions.\n ResultCatcher catcher;\n\n \/\/ TODO: Rather than send this second request by talking to the controller\n \/\/ directly, figure out how to send it via the proper calls to\n \/\/ location_bar or location_bar->().\n autocomplete_controller->Start(\n ASCIIToUTF16(\"keyword command\"), string16(), true, false, true,\n AutocompleteInput::ALL_MATCHES);\n location_bar->AcceptInput();\n WaitForAutocompleteDone(autocomplete_controller);\n EXPECT_TRUE(autocomplete_controller->done());\n \/\/ This checks that the keyword provider (via javascript)\n \/\/ gets told to navigate to the string \"command\".\n EXPECT_TRUE(catcher.GetNextResult()) << catcher.message();\n EXPECT_FALSE(popup_model->IsOpen());\n}\n\n\/\/ Tests that we get suggestions from and send input to the incognito context\n\/\/ of an incognito split mode extension.\n\/\/ http:\/\/crbug.com\/100927\n\/\/ Test flaky on linux: http:\/\/crbug.com\/101219\nIN_PROC_BROWSER_TEST_F(OmniboxApiTest, DISABLED_IncognitoSplitMode) {\n#if defined(TOOLKIT_GTK)\n \/\/ Disable the timer because, on Lucid at least, it triggers resize\/move\n \/\/ behavior in the browser window, which dismisses the autocomplete popup\n \/\/ before the results can be read.\n static_cast<BrowserWindowGtk*>(\n browser()->window())->DisableDebounceTimerForTests(true);\n#endif\n\n ResultCatcher catcher_incognito;\n catcher_incognito.RestrictToProfile(\n browser()->profile()->GetOffTheRecordProfile());\n\n ASSERT_TRUE(RunExtensionTestIncognito(\"omnibox\")) << message_;\n\n \/\/ Open an incognito window and wait for the incognito extension process to\n \/\/ respond.\n Browser* incognito_browser = CreateIncognitoBrowser();\n ASSERT_TRUE(catcher_incognito.GetNextResult()) << catcher_incognito.message();\n\n \/\/ The results depend on the TemplateURLService being loaded. Make sure it is\n \/\/ loaded so that the autocomplete results are consistent.\n WaitForTemplateURLServiceToLoad();\n\n LocationBar* location_bar = GetLocationBar(incognito_browser);\n AutocompleteController* autocomplete_controller =\n GetAutocompleteController(incognito_browser);\n\n \/\/ Test that we get the incognito-specific suggestions.\n {\n autocomplete_controller->Start(\n ASCIIToUTF16(\"keyword suggestio\"), string16(), true, false, true,\n AutocompleteInput::ALL_MATCHES);\n WaitForAutocompleteDone(autocomplete_controller);\n EXPECT_TRUE(autocomplete_controller->done());\n\n \/\/ First result should be to invoke the keyword with what we typed, 2-4\n \/\/ should be to invoke with suggestions from the extension, and the last\n \/\/ should be to search for what we typed.\n const AutocompleteResult& result = autocomplete_controller->result();\n ASSERT_EQ(5U, result.size()) << AutocompleteResultAsString(result);\n ASSERT_TRUE(result.match_at(0).template_url);\n EXPECT_EQ(ASCIIToUTF16(\"keyword suggestion3 incognito\"),\n result.match_at(3).fill_into_edit);\n }\n\n \/\/ Test that our input is sent to the incognito context. The test will do a\n \/\/ text comparison and succeed only if \"command incognito\" is sent to the\n \/\/ incognito context.\n {\n ResultCatcher catcher;\n autocomplete_controller->Start(\n ASCIIToUTF16(\"keyword command incognito\"), string16(),\n true, false, true, AutocompleteInput::ALL_MATCHES);\n location_bar->AcceptInput();\n EXPECT_TRUE(catcher.GetNextResult()) << catcher.message();\n }\n}\n<commit_msg>Revert 122457 - Disable OmniboxApiTest.Basic on ChromiumOS. The offending patch was reverted.<commit_after>\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"base\/format_macros.h\"\n#include \"base\/string_util.h\"\n#include \"base\/stringprintf.h\"\n#include \"base\/utf_string_conversions.h\"\n#include \"chrome\/browser\/autocomplete\/autocomplete.h\"\n#include \"chrome\/browser\/autocomplete\/autocomplete_edit.h\"\n#include \"chrome\/browser\/autocomplete\/autocomplete_match.h\"\n#include \"chrome\/browser\/autocomplete\/autocomplete_popup_model.h\"\n#include \"chrome\/browser\/extensions\/extension_apitest.h\"\n#include \"chrome\/browser\/profiles\/profile.h\"\n#include \"chrome\/browser\/search_engines\/template_url.h\"\n#include \"chrome\/browser\/search_engines\/template_url_service.h\"\n#include \"chrome\/browser\/search_engines\/template_url_service_factory.h\"\n#include \"chrome\/browser\/ui\/browser.h\"\n#include \"chrome\/browser\/ui\/browser_window.h\"\n#include \"chrome\/browser\/ui\/omnibox\/location_bar.h\"\n#include \"chrome\/browser\/ui\/omnibox\/omnibox_view.h\"\n#include \"chrome\/common\/chrome_notification_types.h\"\n#include \"chrome\/common\/url_constants.h\"\n#include \"chrome\/test\/base\/ui_test_utils.h\"\n#include \"content\/public\/browser\/notification_types.h\"\n#include \"content\/public\/browser\/notification_service.h\"\n\n#if defined(TOOLKIT_GTK)\n#include \"chrome\/browser\/ui\/gtk\/browser_window_gtk.h\"\n#endif\n\nnamespace {\n\nstring16 AutocompleteResultAsString(const AutocompleteResult& result) {\n std::string output(base::StringPrintf(\"{%\" PRIuS \"} \", result.size()));\n for (size_t i = 0; i < result.size(); ++i) {\n AutocompleteMatch match = result.match_at(i);\n std::string provider_name = match.provider->name();\n output.append(base::StringPrintf(\"[\\\"%s\\\" by \\\"%s\\\"] \",\n UTF16ToUTF8(match.contents).c_str(),\n provider_name.c_str()));\n }\n return UTF8ToUTF16(output);\n}\n\n} \/\/ namespace\n\nclass OmniboxApiTest : public ExtensionApiTest {\n protected:\n LocationBar* GetLocationBar(Browser* browser) const {\n return browser->window()->GetLocationBar();\n }\n\n AutocompleteController* GetAutocompleteController(Browser* browser) const {\n return GetLocationBar(browser)->location_entry()->model()->popup_model()->\n autocomplete_controller();\n }\n\n void WaitForTemplateURLServiceToLoad() {\n ui_test_utils::WindowedNotificationObserver loaded_observer(\n chrome::NOTIFICATION_TEMPLATE_URL_SERVICE_LOADED,\n content::NotificationService::AllSources());\n TemplateURLService* model =\n TemplateURLServiceFactory::GetForProfile(browser()->profile());\n model->Load();\n if (!model->loaded())\n loaded_observer.Wait();\n }\n\n \/\/ TODO(phajdan.jr): Get rid of this wait-in-a-loop pattern.\n void WaitForAutocompleteDone(AutocompleteController* controller) {\n while (!controller->done()) {\n ui_test_utils::WindowedNotificationObserver ready_observer(\n chrome::NOTIFICATION_AUTOCOMPLETE_CONTROLLER_RESULT_READY,\n content::Source<AutocompleteController>(controller));\n ready_observer.Wait();\n }\n }\n};\n\n#if defined(OS_CHROMEOS) && !defined(USE_AURA)\n\/\/ The test fails on chromeos gtk bot, although it passes locally.\n\/\/ crbug.com\/113455.\n#define MAYBE_Basic DISABLED_Basic\n#else\n#define MAYBE_Basic Basic\n#endif\n\nIN_PROC_BROWSER_TEST_F(OmniboxApiTest, MAYBE_Basic) {\n#if defined(TOOLKIT_GTK)\n \/\/ Disable the timer because, on Lucid at least, it triggers resize\/move\n \/\/ behavior in the browser window, which dismisses the autocomplete popup\n \/\/ before the results can be read.\n static_cast<BrowserWindowGtk*>(\n browser()->window())->DisableDebounceTimerForTests(true);\n#endif\n\n ASSERT_TRUE(RunExtensionTest(\"omnibox\")) << message_;\n\n \/\/ The results depend on the TemplateURLService being loaded. Make sure it is\n \/\/ loaded so that the autocomplete results are consistent.\n WaitForTemplateURLServiceToLoad();\n\n LocationBar* location_bar = GetLocationBar(browser());\n AutocompleteController* autocomplete_controller =\n GetAutocompleteController(browser());\n\n \/\/ Test that our extension's keyword is suggested to us when we partially type\n \/\/ it.\n {\n autocomplete_controller->Start(\n ASCIIToUTF16(\"keywor\"), string16(), true, false, true,\n AutocompleteInput::ALL_MATCHES);\n WaitForAutocompleteDone(autocomplete_controller);\n EXPECT_TRUE(autocomplete_controller->done());\n\n \/\/ Now, peek into the controller to see if it has the results we expect.\n \/\/ First result should be to search for what was typed, second should be to\n \/\/ enter \"extension keyword\" mode.\n const AutocompleteResult& result = autocomplete_controller->result();\n ASSERT_EQ(2U, result.size()) << AutocompleteResultAsString(result);\n AutocompleteMatch match = result.match_at(0);\n EXPECT_EQ(AutocompleteMatch::SEARCH_WHAT_YOU_TYPED, match.type);\n EXPECT_FALSE(match.deletable);\n\n match = result.match_at(1);\n ASSERT_TRUE(match.template_url);\n EXPECT_TRUE(match.template_url->IsExtensionKeyword());\n EXPECT_EQ(ASCIIToUTF16(\"keyword\"), match.template_url->keyword());\n }\n\n \/\/ Test that our extension can send suggestions back to us.\n {\n autocomplete_controller->Start(\n ASCIIToUTF16(\"keyword suggestio\"), string16(), true, false, true,\n AutocompleteInput::ALL_MATCHES);\n WaitForAutocompleteDone(autocomplete_controller);\n EXPECT_TRUE(autocomplete_controller->done());\n\n \/\/ Now, peek into the controller to see if it has the results we expect.\n \/\/ First result should be to invoke the keyword with what we typed, 2-4\n \/\/ should be to invoke with suggestions from the extension, and the last\n \/\/ should be to search for what we typed.\n const AutocompleteResult& result = autocomplete_controller->result();\n ASSERT_EQ(5U, result.size()) << AutocompleteResultAsString(result);\n\n ASSERT_TRUE(result.match_at(0).template_url);\n EXPECT_EQ(ASCIIToUTF16(\"keyword suggestio\"),\n result.match_at(0).fill_into_edit);\n EXPECT_EQ(ASCIIToUTF16(\"keyword suggestion1\"),\n result.match_at(1).fill_into_edit);\n EXPECT_EQ(ASCIIToUTF16(\"keyword suggestion2\"),\n result.match_at(2).fill_into_edit);\n EXPECT_EQ(ASCIIToUTF16(\"keyword suggestion3\"),\n result.match_at(3).fill_into_edit);\n\n string16 description =\n ASCIIToUTF16(\"Description with style: <match>, [dim], (url till end)\");\n EXPECT_EQ(description, result.match_at(1).contents);\n ASSERT_EQ(6u, result.match_at(1).contents_class.size());\n\n EXPECT_EQ(0u,\n result.match_at(1).contents_class[0].offset);\n EXPECT_EQ(ACMatchClassification::NONE,\n result.match_at(1).contents_class[0].style);\n\n EXPECT_EQ(description.find('<'),\n result.match_at(1).contents_class[1].offset);\n EXPECT_EQ(ACMatchClassification::MATCH,\n result.match_at(1).contents_class[1].style);\n\n EXPECT_EQ(description.find('>') + 1u,\n result.match_at(1).contents_class[2].offset);\n EXPECT_EQ(ACMatchClassification::NONE,\n result.match_at(1).contents_class[2].style);\n\n EXPECT_EQ(description.find('['),\n result.match_at(1).contents_class[3].offset);\n EXPECT_EQ(ACMatchClassification::DIM,\n result.match_at(1).contents_class[3].style);\n\n EXPECT_EQ(description.find(']') + 1u,\n result.match_at(1).contents_class[4].offset);\n EXPECT_EQ(ACMatchClassification::NONE,\n result.match_at(1).contents_class[4].style);\n\n EXPECT_EQ(description.find('('),\n result.match_at(1).contents_class[5].offset);\n EXPECT_EQ(ACMatchClassification::URL,\n result.match_at(1).contents_class[5].style);\n\n AutocompleteMatch match = result.match_at(4);\n EXPECT_EQ(AutocompleteMatch::SEARCH_WHAT_YOU_TYPED, match.type);\n EXPECT_FALSE(match.deletable);\n }\n\n {\n ResultCatcher catcher;\n location_bar->location_entry()->OnBeforePossibleChange();\n location_bar->location_entry()->SetUserText(\n ASCIIToUTF16(\"keyword command\"));\n location_bar->location_entry()->OnAfterPossibleChange();\n location_bar->AcceptInput();\n \/\/ This checks that the keyword provider (via javascript)\n \/\/ gets told to navigate to the string \"command\".\n EXPECT_TRUE(catcher.GetNextResult()) << catcher.message();\n }\n}\n\n#if defined(OS_CHROMEOS) && !defined(USE_AURA)\n\/\/ The test fails on chromeos gtk bot, although it passes locally.\n\/\/ crbug.com\/113455.\n#define MAYBE_PopupStaysClosed DISABLED_PopupStaysClosed\n#else\n#define MAYBE_PopupStaysClosed PopupStaysClosed\n#endif\n\n\/\/ Tests that the autocomplete popup doesn't reopen after accepting input for\n\/\/ a given query.\n\/\/ http:\/\/crbug.com\/88552\nIN_PROC_BROWSER_TEST_F(OmniboxApiTest, MAYBE_PopupStaysClosed) {\n#if defined(TOOLKIT_GTK)\n \/\/ Disable the timer because, on Lucid at least, it triggers resize\/move\n \/\/ behavior in the browser window, which dismisses the autocomplete popup\n \/\/ before the results can be read.\n static_cast<BrowserWindowGtk*>(\n browser()->window())->DisableDebounceTimerForTests(true);\n#endif\n\n ASSERT_TRUE(RunExtensionTest(\"omnibox\")) << message_;\n\n \/\/ The results depend on the TemplateURLService being loaded. Make sure it is\n \/\/ loaded so that the autocomplete results are consistent.\n WaitForTemplateURLServiceToLoad();\n\n LocationBar* location_bar = GetLocationBar(browser());\n AutocompleteController* autocomplete_controller =\n GetAutocompleteController(browser());\n AutocompletePopupModel* popup_model =\n GetLocationBar(browser())->location_entry()->model()->popup_model();\n\n \/\/ Input a keyword query and wait for suggestions from the extension.\n location_bar->location_entry()->OnBeforePossibleChange();\n location_bar->location_entry()->SetUserText(ASCIIToUTF16(\"keyword comman\"));\n location_bar->location_entry()->OnAfterPossibleChange();\n WaitForAutocompleteDone(autocomplete_controller);\n EXPECT_TRUE(autocomplete_controller->done());\n EXPECT_TRUE(popup_model->IsOpen());\n\n \/\/ Quickly type another query and accept it before getting suggestions back\n \/\/ for the query. The popup will close after accepting input - ensure that it\n \/\/ does not reopen when the extension returns its suggestions.\n ResultCatcher catcher;\n\n \/\/ TODO: Rather than send this second request by talking to the controller\n \/\/ directly, figure out how to send it via the proper calls to\n \/\/ location_bar or location_bar->().\n autocomplete_controller->Start(\n ASCIIToUTF16(\"keyword command\"), string16(), true, false, true,\n AutocompleteInput::ALL_MATCHES);\n location_bar->AcceptInput();\n WaitForAutocompleteDone(autocomplete_controller);\n EXPECT_TRUE(autocomplete_controller->done());\n \/\/ This checks that the keyword provider (via javascript)\n \/\/ gets told to navigate to the string \"command\".\n EXPECT_TRUE(catcher.GetNextResult()) << catcher.message();\n EXPECT_FALSE(popup_model->IsOpen());\n}\n\n\/\/ Tests that we get suggestions from and send input to the incognito context\n\/\/ of an incognito split mode extension.\n\/\/ http:\/\/crbug.com\/100927\n\/\/ Test flaky on linux: http:\/\/crbug.com\/101219\nIN_PROC_BROWSER_TEST_F(OmniboxApiTest, DISABLED_IncognitoSplitMode) {\n#if defined(TOOLKIT_GTK)\n \/\/ Disable the timer because, on Lucid at least, it triggers resize\/move\n \/\/ behavior in the browser window, which dismisses the autocomplete popup\n \/\/ before the results can be read.\n static_cast<BrowserWindowGtk*>(\n browser()->window())->DisableDebounceTimerForTests(true);\n#endif\n\n ResultCatcher catcher_incognito;\n catcher_incognito.RestrictToProfile(\n browser()->profile()->GetOffTheRecordProfile());\n\n ASSERT_TRUE(RunExtensionTestIncognito(\"omnibox\")) << message_;\n\n \/\/ Open an incognito window and wait for the incognito extension process to\n \/\/ respond.\n Browser* incognito_browser = CreateIncognitoBrowser();\n ASSERT_TRUE(catcher_incognito.GetNextResult()) << catcher_incognito.message();\n\n \/\/ The results depend on the TemplateURLService being loaded. Make sure it is\n \/\/ loaded so that the autocomplete results are consistent.\n WaitForTemplateURLServiceToLoad();\n\n LocationBar* location_bar = GetLocationBar(incognito_browser);\n AutocompleteController* autocomplete_controller =\n GetAutocompleteController(incognito_browser);\n\n \/\/ Test that we get the incognito-specific suggestions.\n {\n autocomplete_controller->Start(\n ASCIIToUTF16(\"keyword suggestio\"), string16(), true, false, true,\n AutocompleteInput::ALL_MATCHES);\n WaitForAutocompleteDone(autocomplete_controller);\n EXPECT_TRUE(autocomplete_controller->done());\n\n \/\/ First result should be to invoke the keyword with what we typed, 2-4\n \/\/ should be to invoke with suggestions from the extension, and the last\n \/\/ should be to search for what we typed.\n const AutocompleteResult& result = autocomplete_controller->result();\n ASSERT_EQ(5U, result.size()) << AutocompleteResultAsString(result);\n ASSERT_TRUE(result.match_at(0).template_url);\n EXPECT_EQ(ASCIIToUTF16(\"keyword suggestion3 incognito\"),\n result.match_at(3).fill_into_edit);\n }\n\n \/\/ Test that our input is sent to the incognito context. The test will do a\n \/\/ text comparison and succeed only if \"command incognito\" is sent to the\n \/\/ incognito context.\n {\n ResultCatcher catcher;\n autocomplete_controller->Start(\n ASCIIToUTF16(\"keyword command incognito\"), string16(),\n true, false, true, AutocompleteInput::ALL_MATCHES);\n location_bar->AcceptInput();\n EXPECT_TRUE(catcher.GetNextResult()) << catcher.message();\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright 2009-2020 The VOTCA Development Team (http:\/\/www.votca.org)\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *\/\n\n#define BOOST_TEST_MAIN\n\n#define BOOST_TEST_MODULE calculator_test\n#include \"..\/..\/include\/votca\/tools\/calculator.h\"\n#include <boost\/filesystem.hpp>\n#include <boost\/test\/unit_test.hpp>\n#include <fstream>\n\nusing namespace ::votca;\n\nBOOST_AUTO_TEST_SUITE(calculator_test)\n\nBOOST_AUTO_TEST_CASE(load_defaults_test) {\n\n class TestCalc : public tools::Calculator {\n\n public:\n std::string Identify() override { return \"testcalc\"; }\n\n void Initialize(const tools::Property &user_options) override {\n\n \/\/ Create folder for test\n const char dir_path[] = \"calculators\";\n boost::filesystem::path dir(dir_path);\n boost::filesystem::create_directory(dir);\n dir.append(\"xml\");\n boost::filesystem::create_directory(dir);\n\n std::ofstream defaults(\"calculators\/xml\/testcalc.xml\");\n defaults << \"<options>\\n\"\n << \"<testcalc>\\n\"\n << \"<option1>0<\/option1>\\n\"\n << \"<option2>3.141592<\/option2>\\n\"\n << \"<\/testcalc>\\n\"\n << \"<\/options>\";\n defaults.close();\n\n \/\/ Load and check the options\n tools::Property final_opt =\n LoadDefaultsAndUpdateWithUserOptions(\"calculators\", user_options);\n\n Index prop1 = final_opt.get(\"option1\").as<votca::Index>();\n std::string prop2 = final_opt.get(\"option2\").as<std::string>();\n BOOST_CHECK_EQUAL(prop1, 42);\n BOOST_CHECK_EQUAL(prop2, \"3.141592\");\n }\n };\n\n setenv(\"VOTCASHARE\", \".\", 1);\n char buff[FILENAME_MAX];\n std::cout << \"WARNING: the VOTCASHARE env. variable has been updated to \"\n << getcwd(buff, FILENAME_MAX) << \"\\n\";\n\n \/\/ Generate user options\n tools::Property user_options;\n\n tools::Property &opt = user_options.add(\"options\", \"\");\n tools::Property &opt_test = opt.add(\"testcalc\", \"\");\n opt_test.add(\"option1\", \"42\");\n\n TestCalc test_calc;\n test_calc.Initialize(user_options);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n<commit_msg>added test for #226<commit_after>\/*\n * Copyright 2009-2020 The VOTCA Development Team (http:\/\/www.votca.org)\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *\/\n\n#define BOOST_TEST_MAIN\n\n#define BOOST_TEST_MODULE calculator_test\n#include \"..\/..\/include\/votca\/tools\/calculator.h\"\n#include <boost\/filesystem.hpp>\n#include <boost\/test\/unit_test.hpp>\n#include <fstream>\n\nusing namespace ::votca;\n\nBOOST_AUTO_TEST_SUITE(calculator_test)\n\nBOOST_AUTO_TEST_CASE(load_defaults_test) {\n\n class TestCalc : public tools::Calculator {\n\n public:\n std::string Identify() override { return \"testcalc\"; }\n\n void Initialize(const tools::Property &user_options) override {\n\n \/\/ Create folder for test\n const char dir_path[] = \"calculators\";\n boost::filesystem::path dir(dir_path);\n boost::filesystem::create_directory(dir);\n dir.append(\"xml\");\n boost::filesystem::create_directory(dir);\n\n std::ofstream defaults(\"calculators\/xml\/testcalc.xml\");\n defaults << \"<options>\\n\"\n << \"<testcalc>\\n\"\n << \"<option1>0<\/option1>\\n\"\n << \"<option2>3.141592<\/option2>\\n\"\n << \"<\/testcalc>\\n\"\n << \"<\/options>\";\n defaults.close();\n\n \/\/ Load and check the options\n tools::Property final_opt =\n LoadDefaultsAndUpdateWithUserOptions(\"calculators\", user_options);\n\n Index prop1 = final_opt.get(\"option1\").as<votca::Index>();\n std::string prop2 = final_opt.get(\"option2\").as<std::string>();\n std::string prop3 = final_opt.get(\"option3\").as<std::string>();\n BOOST_CHECK_EQUAL(prop1, 42);\n BOOST_CHECK_EQUAL(prop2, \"3.141592\");\n BOOST_CHECK_EQUAL(prop3, \"some_value\");\n }\n };\n\n setenv(\"VOTCASHARE\", \".\", 1);\n char buff[FILENAME_MAX];\n std::cout << \"WARNING: the VOTCASHARE env. variable has been updated to \"\n << getcwd(buff, FILENAME_MAX) << \"\\n\";\n\n \/\/ Generate user options\n tools::Property user_options;\n\n tools::Property &opt = user_options.add(\"options\", \"\");\n tools::Property &opt_test = opt.add(\"testcalc\", \"\");\n opt_test.add(\"option1\", \"42\");\n opt_test.add(\"option3\", \"some_value\");\n\n TestCalc test_calc;\n test_calc.Initialize(user_options);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n<|endoftext|>"} {"text":"<commit_before> \n\/* ========================================\n\n * File Name : 16.cpp\n\n * Creation Date : 09-08-2020\n\n * Last Modified : St 12. srpna 2020, 22:27:49\n\n * Created By : Karel Ha <mathemage@gmail.com>\n\n * URL : https:\/\/www.facebook.com\/codingcompetitions\/hacker-cup\/2019\/round-1\/problems\/B\n\n * Points Gained (in case of online contest) :\n\n ==========================================*\/\n\n#include <bits\/stdc++.h>\n\nusing namespace std;\n\n#define REP(I,N) FOR(I,0,N)\n#define FOR(i, begin, end) for (__typeof(end) i = (begin) - ((begin) > (end)); i != (end) - ((begin) > (end)); i += 1 - 2 * ((begin) > (end)))\n#define ALL(A) (A).begin(), (A).end()\n#define MSG(a) cout << #a << \" == \" << (a) << endl;\n\nconst int CLEAN = -1;\n\ntemplate <typename T>\nstring NumberToString ( T Number ) {\n ostringstream ss;\n ss << Number;\n return ss.str();\n}\n\n#define ERR(args...) { vector<string> _v = split(#args, ','); err(_v.begin(), args); }\nvector<string> split(const string& s, char c) {\n vector<string> v;\n stringstream ss(s);\n string x;\n while (getline(ss, x, c))\n v.emplace_back(x);\n return move(v);\n}\nvoid err(vector<string>::iterator it) {}\ntemplate<typename T, typename... Args>\nvoid err(vector<string>::iterator it, T a, Args... args) {\n cout << it -> substr((*it)[0] == ' ', it -> length()) << \" = \" << a << endl;\n err(++it, args...);\n}\n\n#define MOD 1000000007\n#define UNDEF MOD\n#define N_MAX 1000000\n\nvector<int> powers(N_MAX + 1, UNDEF);\n\nint mod_power(int base, int exp) {\n if (powers[exp] == UNDEF) {\n powers[0] = 1;\n FOR(i, 1, exp + 1) {\n powers[i] = (powers[i-1] * base) % MOD;\n\/\/ cout << endl; MSG(i) MSG(powers[i])\n }\n }\n return powers[exp];\n}\n\nint get_result(const string & V, int K) {\n int N = V.size();\n\n int init_balance = 0; \/\/ n_B - n_A\n int balance = 0;\n FOR(i, N-K, N) {\n init_balance += (V[i] == 'A') ? (-1) : 1;\n balance = max(balance, init_balance);\n\/\/ MSG(init_balance)\n }\n\/\/ cout << endl << \"inital balance: \"; MSG(balance)\n\n int result = 0;\n FOR(j, N-K, 0) {\n\/\/ MSG(j) MSG(V[j])\n\/\/ cout << \"0: \"; MSG(balance)\n balance = max(balance, 0);\n balance += (V[j] == 'A') ? (-1) : 1;\n\/\/ cout << \"1: \"; MSG(balance) MSG(result)\n\n if (balance > K) { \/\/ over threshold\n balance -= 2; \/\/ swap 'B' for 'A'\n result += mod_power(2, j + 1); \/\/ pay the charge\n\/\/ MSG(mod_power(2, j + 1))\n result %= MOD; \/\/ TODO: use memo table of pows\n }\n\/\/ cout << \"2: \"; MSG(balance) MSG(result)\n }\n\n return result;\n}\n\nint main() {\n int T;\n cin >> T;\n\/\/ MSG(T)\n\n REP(t,T) {\n int N, K;\n cin >> N >> K;\n\/\/ MSG(N) MSG(K)\n\n string V;\n V.reserve(N);\n cin >> V;\n\/\/ MSG(V) cout << endl;\n\n cout << \"Case #\" << t+1 << \": \" << get_result(V, K) << endl;\n }\n\n return 0;\n}\n<commit_msg>Pre-compute entire powers() at once<commit_after> \n\/* ========================================\n\n * File Name : 16.cpp\n\n * Creation Date : 09-08-2020\n\n * Last Modified : St 12. srpna 2020, 22:34:28\n\n * Created By : Karel Ha <mathemage@gmail.com>\n\n * URL : https:\/\/www.facebook.com\/codingcompetitions\/hacker-cup\/2019\/round-1\/problems\/B\n\n * Points Gained (in case of online contest) :\n\n ==========================================*\/\n\n#include <bits\/stdc++.h>\n\nusing namespace std;\n\n#define REP(I,N) FOR(I,0,N)\n#define FOR(i, begin, end) for (__typeof(end) i = (begin) - ((begin) > (end)); i != (end) - ((begin) > (end)); i += 1 - 2 * ((begin) > (end)))\n#define ALL(A) (A).begin(), (A).end()\n#define MSG(a) cout << #a << \" == \" << (a) << endl;\n\nconst int CLEAN = -1;\n\ntemplate <typename T>\nstring NumberToString ( T Number ) {\n ostringstream ss;\n ss << Number;\n return ss.str();\n}\n\n#define ERR(args...) { vector<string> _v = split(#args, ','); err(_v.begin(), args); }\nvector<string> split(const string& s, char c) {\n vector<string> v;\n stringstream ss(s);\n string x;\n while (getline(ss, x, c))\n v.emplace_back(x);\n return move(v);\n}\nvoid err(vector<string>::iterator it) {}\ntemplate<typename T, typename... Args>\nvoid err(vector<string>::iterator it, T a, Args... args) {\n cout << it -> substr((*it)[0] == ' ', it -> length()) << \" = \" << a << endl;\n err(++it, args...);\n}\n\n#define MOD 1000000007\n#define UNDEF -1\n#define N_MAX 1000000\n\nvector<int> powers(N_MAX + 1, UNDEF);\n\nint mod_power(int base, int exp) {\n if (powers[exp] == UNDEF) { \/\/ not pre-computed yet -> pre-compute powers[]\n powers[0] = 1;\n FOR(i, 1, powers.size()) {\n powers[i] = (powers[i-1] * base) % MOD;\n\/\/ cout << endl; MSG(i) MSG(powers[i])\n }\n }\n return powers[exp];\n}\n\nint get_result(const string & V, int K) {\n int N = V.size();\n\n int init_balance = 0; \/\/ n_B - n_A\n int balance = 0;\n FOR(i, N-K, N) {\n init_balance += (V[i] == 'A') ? (-1) : 1;\n balance = max(balance, init_balance);\n\/\/ MSG(init_balance)\n }\n\/\/ cout << endl << \"inital balance: \"; MSG(balance)\n\n int result = 0;\n FOR(j, N-K, 0) {\n\/\/ MSG(j) MSG(V[j])\n\/\/ cout << \"0: \"; MSG(balance)\n balance = max(balance, 0);\n balance += (V[j] == 'A') ? (-1) : 1;\n\/\/ cout << \"1: \"; MSG(balance) MSG(result)\n\n if (balance > K) { \/\/ over threshold\n balance -= 2; \/\/ swap 'B' for 'A'\n result += mod_power(2, j + 1); \/\/ pay the charge\n\/\/ MSG(mod_power(2, j + 1))\n result %= MOD; \/\/ TODO: use memo table of pows\n }\n\/\/ cout << \"2: \"; MSG(balance) MSG(result)\n }\n\n return result;\n}\n\nint main() {\n int T;\n cin >> T;\n\/\/ MSG(T)\n\n REP(t,T) {\n int N, K;\n cin >> N >> K;\n\/\/ MSG(N) MSG(K)\n\n string V;\n V.reserve(N);\n cin >> V;\n\/\/ MSG(V) cout << endl;\n\n cout << \"Case #\" << t+1 << \": \" << get_result(V, K) << endl;\n }\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Copyright (c) 2013 Adam Roben <adam@roben.org>. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE-CHROMIUM file.\n\n#include \"browser\/inspectable_web_contents_impl.h\"\n\n#include \"browser\/browser_client.h\"\n#include \"browser\/browser_context.h\"\n#include \"browser\/browser_main_parts.h\"\n#include \"browser\/inspectable_web_contents_delegate.h\"\n#include \"browser\/inspectable_web_contents_view.h\"\n\n#include \"base\/json\/json_reader.h\"\n#include \"base\/prefs\/pref_registry_simple.h\"\n#include \"base\/prefs\/pref_service.h\"\n#include \"base\/strings\/stringprintf.h\"\n#include \"base\/strings\/utf_string_conversions.h\"\n#include \"base\/values.h\"\n#include \"content\/public\/browser\/devtools_agent_host.h\"\n#include \"content\/public\/browser\/devtools_client_host.h\"\n#include \"content\/public\/browser\/devtools_http_handler.h\"\n#include \"content\/public\/browser\/devtools_manager.h\"\n#include \"content\/public\/browser\/render_frame_host.h\"\n#include \"content\/public\/browser\/render_view_host.h\"\n\nnamespace brightray {\n\nnamespace {\n\nconst char kChromeUIDevToolsURL[] = \"chrome-devtools:\/\/devtools\/devtools.html?\"\n \"can_dock=true&&\"\n \"experiments=true\";\nconst char kDevToolsBoundsPref[] = \"brightray.devtools.bounds\";\n\nconst char kFrontendHostId[] = \"id\";\nconst char kFrontendHostMethod[] = \"method\";\nconst char kFrontendHostParams[] = \"params\";\n\nvoid RectToDictionary(const gfx::Rect& bounds, base::DictionaryValue* dict) {\n dict->SetInteger(\"x\", bounds.x());\n dict->SetInteger(\"y\", bounds.y());\n dict->SetInteger(\"width\", bounds.width());\n dict->SetInteger(\"height\", bounds.height());\n}\n\nvoid DictionaryToRect(const base::DictionaryValue& dict, gfx::Rect* bounds) {\n int x = 0, y = 0, width = 800, height = 600;\n dict.GetInteger(\"x\", &x);\n dict.GetInteger(\"y\", &y);\n dict.GetInteger(\"width\", &width);\n dict.GetInteger(\"height\", &height);\n *bounds = gfx::Rect(x, y, width, height);\n}\n\nbool ParseMessage(const std::string& message,\n std::string* method,\n base::ListValue* params,\n int* id) {\n scoped_ptr<base::Value> parsed_message(base::JSONReader::Read(message));\n if (!parsed_message)\n return false;\n\n base::DictionaryValue* dict = NULL;\n if (!parsed_message->GetAsDictionary(&dict))\n return false;\n if (!dict->GetString(kFrontendHostMethod, method))\n return false;\n\n \/\/ \"params\" is optional.\n if (dict->HasKey(kFrontendHostParams)) {\n base::ListValue* internal_params;\n if (dict->GetList(kFrontendHostParams, &internal_params))\n params->Swap(internal_params);\n else\n return false;\n }\n\n *id = 0;\n dict->GetInteger(kFrontendHostId, id);\n return true;\n}\n\n} \/\/ namespace\n\n\/\/ Implemented separately on each platform.\nInspectableWebContentsView* CreateInspectableContentsView(\n InspectableWebContentsImpl* inspectable_web_contents_impl);\n\nvoid InspectableWebContentsImpl::RegisterPrefs(PrefRegistrySimple* registry) {\n auto bounds_dict = make_scoped_ptr(new base::DictionaryValue);\n RectToDictionary(gfx::Rect(0, 0, 800, 600), bounds_dict.get());\n registry->RegisterDictionaryPref(kDevToolsBoundsPref, bounds_dict.release());\n}\n\nInspectableWebContentsImpl::InspectableWebContentsImpl(\n content::WebContents* web_contents)\n : web_contents_(web_contents),\n delegate_(nullptr) {\n auto context = static_cast<BrowserContext*>(web_contents_->GetBrowserContext());\n auto bounds_dict = context->prefs()->GetDictionary(kDevToolsBoundsPref);\n if (bounds_dict)\n DictionaryToRect(*bounds_dict, &devtools_bounds_);\n\n view_.reset(CreateInspectableContentsView(this));\n}\n\nInspectableWebContentsImpl::~InspectableWebContentsImpl() {\n}\n\nInspectableWebContentsView* InspectableWebContentsImpl::GetView() const {\n return view_.get();\n}\n\ncontent::WebContents* InspectableWebContentsImpl::GetWebContents() const {\n return web_contents_.get();\n}\n\nvoid InspectableWebContentsImpl::ShowDevTools() {\n \/\/ Show devtools only after it has done loading, this is to make sure the\n \/\/ SetIsDocked is called *BEFORE* ShowDevTools.\n if (!devtools_web_contents_) {\n embedder_message_dispatcher_.reset(\n new DevToolsEmbedderMessageDispatcher(this));\n\n auto create_params = content::WebContents::CreateParams(\n web_contents_->GetBrowserContext());\n devtools_web_contents_.reset(content::WebContents::Create(create_params));\n\n Observe(devtools_web_contents_.get());\n devtools_web_contents_->SetDelegate(this);\n\n agent_host_ = content::DevToolsAgentHost::GetOrCreateFor(\n web_contents_->GetRenderViewHost());\n frontend_host_.reset(\n content::DevToolsClientHost::CreateDevToolsFrontendHost(\n devtools_web_contents_.get(), this));\n content::DevToolsManager::GetInstance()->RegisterDevToolsClientHostFor(\n agent_host_, frontend_host_.get());\n\n GURL devtools_url(kChromeUIDevToolsURL);\n devtools_web_contents_->GetController().LoadURL(\n devtools_url,\n content::Referrer(),\n content::PAGE_TRANSITION_AUTO_TOPLEVEL,\n std::string());\n } else {\n view_->ShowDevTools();\n }\n}\n\nvoid InspectableWebContentsImpl::CloseDevTools() {\n if (devtools_web_contents_) {\n view_->CloseDevTools();\n devtools_web_contents_.reset();\n web_contents_->Focus();\n }\n}\n\nbool InspectableWebContentsImpl::IsDevToolsViewShowing() {\n return devtools_web_contents_ && view_->IsDevToolsViewShowing();\n}\n\ngfx::Rect InspectableWebContentsImpl::GetDevToolsBounds() const {\n return devtools_bounds_;\n}\n\nvoid InspectableWebContentsImpl::SaveDevToolsBounds(const gfx::Rect& bounds) {\n auto context = static_cast<BrowserContext*>(web_contents_->GetBrowserContext());\n base::DictionaryValue bounds_dict;\n RectToDictionary(bounds, &bounds_dict);\n context->prefs()->Set(kDevToolsBoundsPref, bounds_dict);\n devtools_bounds_ = bounds;\n}\n\nvoid InspectableWebContentsImpl::ActivateWindow() {\n}\n\nvoid InspectableWebContentsImpl::CloseWindow() {\n devtools_web_contents()->DispatchBeforeUnload(false);\n}\n\nvoid InspectableWebContentsImpl::SetContentsResizingStrategy(\n const gfx::Insets& insets, const gfx::Size& min_size) {\n DevToolsContentsResizingStrategy strategy(insets, min_size);\n if (contents_resizing_strategy_.Equals(strategy))\n return;\n\n contents_resizing_strategy_.CopyFrom(strategy);\n view_->SetContentsResizingStrategy(contents_resizing_strategy_);\n}\n\nvoid InspectableWebContentsImpl::InspectElementCompleted() {\n}\n\nvoid InspectableWebContentsImpl::MoveWindow(int x, int y) {\n}\n\nvoid InspectableWebContentsImpl::SetIsDocked(bool docked) {\n view_->SetIsDocked(docked);\n}\n\nvoid InspectableWebContentsImpl::OpenInNewTab(const std::string& url) {\n}\n\nvoid InspectableWebContentsImpl::SaveToFile(\n const std::string& url, const std::string& content, bool save_as) {\n if (delegate_)\n delegate_->DevToolsSaveToFile(url, content, save_as);\n}\n\nvoid InspectableWebContentsImpl::AppendToFile(\n const std::string& url, const std::string& content) {\n if (delegate_)\n delegate_->DevToolsAppendToFile(url, content);\n}\n\nvoid InspectableWebContentsImpl::RequestFileSystems() {\n devtools_web_contents()->GetMainFrame()->ExecuteJavaScript(\n base::ASCIIToUTF16(\"InspectorFrontendAPI.fileSystemsLoaded([])\"));\n}\n\nvoid InspectableWebContentsImpl::AddFileSystem() {\n}\n\nvoid InspectableWebContentsImpl::RemoveFileSystem(\n const std::string& file_system_path) {\n}\n\nvoid InspectableWebContentsImpl::UpgradeDraggedFileSystemPermissions(\n const std::string& file_system_url) {\n}\n\nvoid InspectableWebContentsImpl::IndexPath(\n int request_id, const std::string& file_system_path) {\n}\n\nvoid InspectableWebContentsImpl::StopIndexing(int request_id) {\n}\n\nvoid InspectableWebContentsImpl::SearchInPath(\n int request_id,\n const std::string& file_system_path,\n const std::string& query) {\n}\n\nvoid InspectableWebContentsImpl::ZoomIn() {\n}\n\nvoid InspectableWebContentsImpl::ZoomOut() {\n}\n\nvoid InspectableWebContentsImpl::ResetZoom() {\n}\n\nvoid InspectableWebContentsImpl::DispatchOnEmbedder(\n const std::string& message) {\n std::string method;\n base::ListValue params;\n int id;\n if (!ParseMessage(message, &method, ¶ms, &id)) {\n LOG(ERROR) << \"Invalid message was sent to embedder: \" << message;\n return;\n }\n\n std::string error = embedder_message_dispatcher_->Dispatch(method, ¶ms);\n if (id) {\n std::string ack = base::StringPrintf(\n \"InspectorFrontendAPI.embedderMessageAck(%d, \\\"%s\\\");\", id, error.c_str());\n devtools_web_contents()->GetMainFrame()->ExecuteJavaScript(base::UTF8ToUTF16(ack));\n }\n}\n\nvoid InspectableWebContentsImpl::InspectedContentsClosing() {\n}\n\nvoid InspectableWebContentsImpl::AboutToNavigateRenderView(\n content::RenderViewHost* render_view_host) {\n content::DevToolsClientHost::SetupDevToolsFrontendClient(\n web_contents()->GetRenderViewHost());\n}\n\nvoid InspectableWebContentsImpl::DidFinishLoad(int64 frame_id,\n const GURL& validated_url,\n bool is_main_frame,\n content::RenderViewHost*) {\n if (!is_main_frame)\n return;\n\n view_->ShowDevTools();\n}\n\nvoid InspectableWebContentsImpl::WebContentsDestroyed() {\n content::DevToolsManager::GetInstance()->ClientHostClosing(\n frontend_host_.get());\n Observe(nullptr);\n agent_host_ = nullptr;\n frontend_host_.reset();\n}\n\nvoid InspectableWebContentsImpl::HandleKeyboardEvent(\n content::WebContents* source,\n const content::NativeWebKeyboardEvent& event) {\n auto delegate = web_contents_->GetDelegate();\n if (delegate)\n delegate->HandleKeyboardEvent(source, event);\n}\n\nvoid InspectableWebContentsImpl::CloseContents(content::WebContents* source) {\n CloseDevTools();\n}\n\n} \/\/ namespace brightray\n<commit_msg>Implement zoom messages for devtools.<commit_after>\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Copyright (c) 2013 Adam Roben <adam@roben.org>. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE-CHROMIUM file.\n\n#include \"browser\/inspectable_web_contents_impl.h\"\n\n#include \"browser\/browser_client.h\"\n#include \"browser\/browser_context.h\"\n#include \"browser\/browser_main_parts.h\"\n#include \"browser\/inspectable_web_contents_delegate.h\"\n#include \"browser\/inspectable_web_contents_view.h\"\n\n#include \"base\/json\/json_reader.h\"\n#include \"base\/prefs\/pref_registry_simple.h\"\n#include \"base\/prefs\/pref_service.h\"\n#include \"base\/strings\/stringprintf.h\"\n#include \"base\/strings\/utf_string_conversions.h\"\n#include \"base\/values.h\"\n#include \"content\/public\/browser\/devtools_agent_host.h\"\n#include \"content\/public\/browser\/devtools_client_host.h\"\n#include \"content\/public\/browser\/devtools_http_handler.h\"\n#include \"content\/public\/browser\/devtools_manager.h\"\n#include \"content\/public\/browser\/host_zoom_map.h\"\n#include \"content\/public\/browser\/render_frame_host.h\"\n#include \"content\/public\/browser\/render_view_host.h\"\n\nnamespace brightray {\n\nnamespace {\n\nconst double kPresetZoomFactors[] = { 0.25, 0.333, 0.5, 0.666, 0.75, 0.9, 1.0,\n 1.1, 1.25, 1.5, 1.75, 2.0, 2.5, 3.0, 4.0,\n 5.0 };\n\nconst char kDevToolsScheme[] = \"chrome-devtools\";\nconst char kDevToolsHost[] = \"devtools\";\nconst char kChromeUIDevToolsURL[] = \"chrome-devtools:\/\/devtools\/devtools.html?\"\n \"can_dock=true&&\"\n \"experiments=true\";\nconst char kDevToolsBoundsPref[] = \"brightray.devtools.bounds\";\n\nconst char kFrontendHostId[] = \"id\";\nconst char kFrontendHostMethod[] = \"method\";\nconst char kFrontendHostParams[] = \"params\";\n\nvoid RectToDictionary(const gfx::Rect& bounds, base::DictionaryValue* dict) {\n dict->SetInteger(\"x\", bounds.x());\n dict->SetInteger(\"y\", bounds.y());\n dict->SetInteger(\"width\", bounds.width());\n dict->SetInteger(\"height\", bounds.height());\n}\n\nvoid DictionaryToRect(const base::DictionaryValue& dict, gfx::Rect* bounds) {\n int x = 0, y = 0, width = 800, height = 600;\n dict.GetInteger(\"x\", &x);\n dict.GetInteger(\"y\", &y);\n dict.GetInteger(\"width\", &width);\n dict.GetInteger(\"height\", &height);\n *bounds = gfx::Rect(x, y, width, height);\n}\n\nbool ParseMessage(const std::string& message,\n std::string* method,\n base::ListValue* params,\n int* id) {\n scoped_ptr<base::Value> parsed_message(base::JSONReader::Read(message));\n if (!parsed_message)\n return false;\n\n base::DictionaryValue* dict = NULL;\n if (!parsed_message->GetAsDictionary(&dict))\n return false;\n if (!dict->GetString(kFrontendHostMethod, method))\n return false;\n\n \/\/ \"params\" is optional.\n if (dict->HasKey(kFrontendHostParams)) {\n base::ListValue* internal_params;\n if (dict->GetList(kFrontendHostParams, &internal_params))\n params->Swap(internal_params);\n else\n return false;\n }\n\n *id = 0;\n dict->GetInteger(kFrontendHostId, id);\n return true;\n}\n\ndouble GetZoomLevelForWebContents(content::WebContents* web_contents) {\n content::HostZoomMap* host_zoom_map = content::HostZoomMap::GetForBrowserContext(\n web_contents->GetBrowserContext());\n return host_zoom_map->GetZoomLevelForHostAndScheme(kDevToolsScheme, kDevToolsHost);\n}\n\nvoid SetZoomLevelForWebContents(content::WebContents* web_contents, double level) {\n content::HostZoomMap* host_zoom_map = content::HostZoomMap::GetForBrowserContext(\n web_contents->GetBrowserContext());\n return host_zoom_map->SetZoomLevelForHostAndScheme(kDevToolsScheme, kDevToolsHost, level);\n}\n\ndouble GetNextZoomLevel(double level, bool out) {\n double factor = content::ZoomLevelToZoomFactor(level);\n size_t size = arraysize(kPresetZoomFactors);\n for (size_t i = 0; i < size; ++i) {\n if (!content::ZoomValuesEqual(kPresetZoomFactors[i], factor))\n continue;\n if (out && i > 0)\n return content::ZoomFactorToZoomLevel(kPresetZoomFactors[i - 1]);\n if (!out && i != size - 1)\n return content::ZoomFactorToZoomLevel(kPresetZoomFactors[i + 1]);\n }\n return level;\n}\n\n} \/\/ namespace\n\n\/\/ Implemented separately on each platform.\nInspectableWebContentsView* CreateInspectableContentsView(\n InspectableWebContentsImpl* inspectable_web_contents_impl);\n\nvoid InspectableWebContentsImpl::RegisterPrefs(PrefRegistrySimple* registry) {\n auto bounds_dict = make_scoped_ptr(new base::DictionaryValue);\n RectToDictionary(gfx::Rect(0, 0, 800, 600), bounds_dict.get());\n registry->RegisterDictionaryPref(kDevToolsBoundsPref, bounds_dict.release());\n}\n\nInspectableWebContentsImpl::InspectableWebContentsImpl(\n content::WebContents* web_contents)\n : web_contents_(web_contents),\n delegate_(nullptr) {\n auto context = static_cast<BrowserContext*>(web_contents_->GetBrowserContext());\n auto bounds_dict = context->prefs()->GetDictionary(kDevToolsBoundsPref);\n if (bounds_dict)\n DictionaryToRect(*bounds_dict, &devtools_bounds_);\n\n view_.reset(CreateInspectableContentsView(this));\n}\n\nInspectableWebContentsImpl::~InspectableWebContentsImpl() {\n}\n\nInspectableWebContentsView* InspectableWebContentsImpl::GetView() const {\n return view_.get();\n}\n\ncontent::WebContents* InspectableWebContentsImpl::GetWebContents() const {\n return web_contents_.get();\n}\n\nvoid InspectableWebContentsImpl::ShowDevTools() {\n \/\/ Show devtools only after it has done loading, this is to make sure the\n \/\/ SetIsDocked is called *BEFORE* ShowDevTools.\n if (!devtools_web_contents_) {\n embedder_message_dispatcher_.reset(\n new DevToolsEmbedderMessageDispatcher(this));\n\n auto create_params = content::WebContents::CreateParams(\n web_contents_->GetBrowserContext());\n devtools_web_contents_.reset(content::WebContents::Create(create_params));\n\n Observe(devtools_web_contents_.get());\n devtools_web_contents_->SetDelegate(this);\n\n agent_host_ = content::DevToolsAgentHost::GetOrCreateFor(\n web_contents_->GetRenderViewHost());\n frontend_host_.reset(\n content::DevToolsClientHost::CreateDevToolsFrontendHost(\n devtools_web_contents_.get(), this));\n content::DevToolsManager::GetInstance()->RegisterDevToolsClientHostFor(\n agent_host_, frontend_host_.get());\n\n GURL devtools_url(kChromeUIDevToolsURL);\n devtools_web_contents_->GetController().LoadURL(\n devtools_url,\n content::Referrer(),\n content::PAGE_TRANSITION_AUTO_TOPLEVEL,\n std::string());\n } else {\n view_->ShowDevTools();\n }\n}\n\nvoid InspectableWebContentsImpl::CloseDevTools() {\n if (devtools_web_contents_) {\n view_->CloseDevTools();\n devtools_web_contents_.reset();\n web_contents_->Focus();\n }\n}\n\nbool InspectableWebContentsImpl::IsDevToolsViewShowing() {\n return devtools_web_contents_ && view_->IsDevToolsViewShowing();\n}\n\ngfx::Rect InspectableWebContentsImpl::GetDevToolsBounds() const {\n return devtools_bounds_;\n}\n\nvoid InspectableWebContentsImpl::SaveDevToolsBounds(const gfx::Rect& bounds) {\n auto context = static_cast<BrowserContext*>(web_contents_->GetBrowserContext());\n base::DictionaryValue bounds_dict;\n RectToDictionary(bounds, &bounds_dict);\n context->prefs()->Set(kDevToolsBoundsPref, bounds_dict);\n devtools_bounds_ = bounds;\n}\n\nvoid InspectableWebContentsImpl::ActivateWindow() {\n}\n\nvoid InspectableWebContentsImpl::CloseWindow() {\n devtools_web_contents()->DispatchBeforeUnload(false);\n}\n\nvoid InspectableWebContentsImpl::SetContentsResizingStrategy(\n const gfx::Insets& insets, const gfx::Size& min_size) {\n DevToolsContentsResizingStrategy strategy(insets, min_size);\n if (contents_resizing_strategy_.Equals(strategy))\n return;\n\n contents_resizing_strategy_.CopyFrom(strategy);\n view_->SetContentsResizingStrategy(contents_resizing_strategy_);\n}\n\nvoid InspectableWebContentsImpl::InspectElementCompleted() {\n}\n\nvoid InspectableWebContentsImpl::MoveWindow(int x, int y) {\n}\n\nvoid InspectableWebContentsImpl::SetIsDocked(bool docked) {\n view_->SetIsDocked(docked);\n}\n\nvoid InspectableWebContentsImpl::OpenInNewTab(const std::string& url) {\n}\n\nvoid InspectableWebContentsImpl::SaveToFile(\n const std::string& url, const std::string& content, bool save_as) {\n if (delegate_)\n delegate_->DevToolsSaveToFile(url, content, save_as);\n}\n\nvoid InspectableWebContentsImpl::AppendToFile(\n const std::string& url, const std::string& content) {\n if (delegate_)\n delegate_->DevToolsAppendToFile(url, content);\n}\n\nvoid InspectableWebContentsImpl::RequestFileSystems() {\n devtools_web_contents()->GetMainFrame()->ExecuteJavaScript(\n base::ASCIIToUTF16(\"InspectorFrontendAPI.fileSystemsLoaded([])\"));\n}\n\nvoid InspectableWebContentsImpl::AddFileSystem() {\n}\n\nvoid InspectableWebContentsImpl::RemoveFileSystem(\n const std::string& file_system_path) {\n}\n\nvoid InspectableWebContentsImpl::UpgradeDraggedFileSystemPermissions(\n const std::string& file_system_url) {\n}\n\nvoid InspectableWebContentsImpl::IndexPath(\n int request_id, const std::string& file_system_path) {\n}\n\nvoid InspectableWebContentsImpl::StopIndexing(int request_id) {\n}\n\nvoid InspectableWebContentsImpl::SearchInPath(\n int request_id,\n const std::string& file_system_path,\n const std::string& query) {\n}\n\nvoid InspectableWebContentsImpl::ZoomIn() {\n double level = GetZoomLevelForWebContents(devtools_web_contents());\n SetZoomLevelForWebContents(devtools_web_contents(), GetNextZoomLevel(level, false));\n}\n\nvoid InspectableWebContentsImpl::ZoomOut() {\n double level = GetZoomLevelForWebContents(devtools_web_contents());\n SetZoomLevelForWebContents(devtools_web_contents(), GetNextZoomLevel(level, true));\n}\n\nvoid InspectableWebContentsImpl::ResetZoom() {\n SetZoomLevelForWebContents(devtools_web_contents(), 0.);\n}\n\nvoid InspectableWebContentsImpl::DispatchOnEmbedder(\n const std::string& message) {\n std::string method;\n base::ListValue params;\n int id;\n if (!ParseMessage(message, &method, ¶ms, &id)) {\n LOG(ERROR) << \"Invalid message was sent to embedder: \" << message;\n return;\n }\n\n std::string error = embedder_message_dispatcher_->Dispatch(method, ¶ms);\n if (id) {\n std::string ack = base::StringPrintf(\n \"InspectorFrontendAPI.embedderMessageAck(%d, \\\"%s\\\");\", id, error.c_str());\n devtools_web_contents()->GetMainFrame()->ExecuteJavaScript(base::UTF8ToUTF16(ack));\n }\n}\n\nvoid InspectableWebContentsImpl::InspectedContentsClosing() {\n}\n\nvoid InspectableWebContentsImpl::AboutToNavigateRenderView(\n content::RenderViewHost* render_view_host) {\n content::DevToolsClientHost::SetupDevToolsFrontendClient(\n web_contents()->GetRenderViewHost());\n}\n\nvoid InspectableWebContentsImpl::DidFinishLoad(int64 frame_id,\n const GURL& validated_url,\n bool is_main_frame,\n content::RenderViewHost*) {\n if (!is_main_frame)\n return;\n\n view_->ShowDevTools();\n}\n\nvoid InspectableWebContentsImpl::WebContentsDestroyed() {\n content::DevToolsManager::GetInstance()->ClientHostClosing(\n frontend_host_.get());\n Observe(nullptr);\n agent_host_ = nullptr;\n frontend_host_.reset();\n}\n\nvoid InspectableWebContentsImpl::HandleKeyboardEvent(\n content::WebContents* source,\n const content::NativeWebKeyboardEvent& event) {\n auto delegate = web_contents_->GetDelegate();\n if (delegate)\n delegate->HandleKeyboardEvent(source, event);\n}\n\nvoid InspectableWebContentsImpl::CloseContents(content::WebContents* source) {\n CloseDevTools();\n}\n\n} \/\/ namespace brightray\n<|endoftext|>"} {"text":"<commit_before>#include <cstdio>\n#include <ros\/ros.h>\n#include <image_transport\/image_transport.h>\n#include <cv_bridge\/cv_bridge.h>\n#include <sensor_msgs\/image_encodings.h>\n#include <opencv2\/core\/core.hpp>\n#include <opencv2\/highgui\/highgui.hpp>\n\n#include <string>\n\nusing namespace std;\n\n#define USAGE \"Usage: \\n\" \\\n \" occupancy_im_saver -h\\n\"\\\n \" occupancy_im_saver [-c <to store color map>] [-f file path]\"\n#define DEFAULT_FILE \"\/tmp\/occupancy_image.png\"\n\nvoid imCb(const sensor_msgs::ImageConstPtr im_msg);\n\nstring file_path;\nstring topic_name = \"occupancy_image\";\nbool awaiting_image = false;\n\nint main(int argc, char** argv)\n{\n file_path = DEFAULT_FILE;\n for(int i=1; i<argc; i++)\n {\n if(!strcmp(argv[i], \"-h\"))\n {\n puts(USAGE);\n return 0;\n }\n else if(!strcmp(argv[i], \"-c\"))\n {\n topic_name += \"_color\";\n }\n else if(!strcmp(argv[i], \"-f\"))\n {\n if(++i < argc)\n file_path = argv[i];\n else\n {\n puts(USAGE);\n return 1;\n }\n }\n else\n {\n puts(USAGE);\n return 1;\n }\n }\n\n ros::init(argc, argv, \"occupancy_image_publisher\");\n ros::NodeHandle n;\n image_transport::ImageTransport it(n);\n image_transport::Subscriber im_sub = it.subscribe(topic_name,1,imCb);\n\n awaiting_image = true;\n ROS_INFO(\"Wainting for image with topic name: %s\", topic_name.c_str());\n ros::Rate r(5);\n while (n.ok() && awaiting_image) {\n ros::spinOnce();\n r.sleep();\n }\n return 0;\n}\n\nvoid imCb(const sensor_msgs::ImageConstPtr im_msg)\n{\n cv_bridge::CvImageConstPtr cv_ptr;\n \/\/ Convert image to opencv\n try\n {\n cv_ptr = cv_bridge::toCvShare(im_msg, sensor_msgs::image_encodings::BGR8);\n }\n catch (cv_bridge::Exception& e)\n {\n ROS_ERROR(\"cv_bridge exception: %s\", e.what());\n return;\n }\n ROS_INFO(\"Storing image to path: %s\", file_path.c_str());\n cv::imwrite(file_path, cv_ptr->image);\n awaiting_image = false;\n}\n<commit_msg>store occupancy without name conflict with occupancy publisher<commit_after>#include <cstdio>\n#include <ros\/ros.h>\n#include <image_transport\/image_transport.h>\n#include <cv_bridge\/cv_bridge.h>\n#include <sensor_msgs\/image_encodings.h>\n#include <opencv2\/core\/core.hpp>\n#include <opencv2\/highgui\/highgui.hpp>\n\n#include <string>\n\nusing namespace std;\n\n#define USAGE \"Usage: \\n\" \\\n \" occupancy_im_saver -h\\n\"\\\n \" occupancy_im_saver [-c <to store color map>] [-f file path]\"\n#define DEFAULT_FILE \"\/tmp\/occupancy_image.png\"\n\nvoid imCb(const sensor_msgs::ImageConstPtr im_msg);\n\nstring file_path;\nstring topic_name = \"\/occupancy_image\";\nbool awaiting_image = false;\n\nint main(int argc, char** argv)\n{\n file_path = DEFAULT_FILE;\n for(int i=1; i<argc; i++)\n {\n if(!strcmp(argv[i], \"-h\"))\n {\n puts(USAGE);\n return 0;\n }\n else if(!strcmp(argv[i], \"-c\"))\n {\n topic_name += \"_color\";\n }\n else if(!strcmp(argv[i], \"-f\"))\n {\n if(++i < argc)\n file_path = argv[i];\n else\n {\n puts(USAGE);\n return 1;\n }\n }\n else\n {\n puts(USAGE);\n return 1;\n }\n }\n\n ros::init(argc, argv, \"occupancy_image_saver\");\n ros::NodeHandle n;\n image_transport::ImageTransport it(n);\n image_transport::Subscriber im_sub = it.subscribe(topic_name,1,imCb);\n\n awaiting_image = true;\n ROS_INFO(\"Wainting for image with topic name: %s\", topic_name.c_str());\n ros::Rate r(5);\n while (n.ok() && awaiting_image) {\n ros::spinOnce();\n r.sleep();\n }\n return 0;\n}\n\nvoid imCb(const sensor_msgs::ImageConstPtr im_msg)\n{\n cv_bridge::CvImageConstPtr cv_ptr;\n \/\/ Convert image to opencv\n try\n {\n cv_ptr = cv_bridge::toCvShare(im_msg, sensor_msgs::image_encodings::BGR8);\n }\n catch (cv_bridge::Exception& e)\n {\n ROS_ERROR(\"cv_bridge exception: %s\", e.what());\n return;\n }\n ROS_INFO(\"Storing image to path: %s\", file_path.c_str());\n cv::imwrite(file_path, cv_ptr->image);\n awaiting_image = false;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"collision.h\"\n\nCollision::Collision(){\n}\n bool Collision::SphereVersusSphere(int x1 ,int y1 ,int z1 ,int size1 ,int x2 ,int y2 ,int z2 ,int size2){\n\n\n\n return ((x1 - x2) * (x1 - x2) +\n (y1 - y2) * (y1 - y2) +\n (z1 - z2) * (z1 - z2)) >= ((size1+size2) * (size1+size2));\n }\n\n bool Collision::SphereVersusPoint(int sphereX ,int sphereY ,int sphereZ ,int sphereSize ,int PointX ,int PointY ,int PointZ){\n\n\n\n return ((sphereX - PointX) * (sphereX - PointX) +\n (sphereY - PointY) * (sphereY - PointY) +\n (sphereZ - PointZ) * (sphereZ - PointZ) >= (sphereSize * sphereSize));\n }\n\n bool Collision::BoxVersusPoint(int PointX ,int PointY ,int PointZ ,int boxMinX ,int boxMinY ,int boxMinZ ,int boxMaxX ,int boxMaxY ,int boxMaxZ){\n\n\n\n return (PointX >= boxMinX && PointX <= boxMaxX) &&\n (PointY >= boxMinY && PointY <= boxMaxY) &&\n (PointZ >= boxMinZ && PointZ <= boxMaxZ);\n }\n\n bool Collision::BoxVersusBox(int boxMinX1 ,int boxMinY1 ,int boxMinZ1 ,int boxMaxX1 ,int boxMaxY1 ,int boxMaxZ1 ,int boxMinX2 ,int boxMinY2 ,int boxMinZ2 ,int boxMaxX2 ,int boxMaxY2 ,int boxMaxZ2){\n\n return (boxMinX1 <= boxMaxX2 && boxMaxX1 >= boxMinX2) &&\n (boxMinY1 <= boxMaxY2 && boxMaxY1 >= boxMinY2) &&\n (boxMinZ1 <= boxMaxZ2 && boxMaxZ1 >= boxMinZ2);\n\n }\n\n bool Collision::SphereVersusBox(int sphereX ,int sphereY ,int sphereZ ,int sphereSize ,int boxMinX ,int boxMinY ,int boxMinZ ,int boxMaxX ,int boxMaxY ,int boxMaxZ){\n \/\/Math.max(box.minX, Math.min(sphere.x, box.maxX);\n int x = Max(boxMinX, Min(sphereX ,boxMaxX));\n int y = Max(boxMinY, Min(sphereY ,boxMaxY));\n int z = Max(boxMinZ, Min(sphereZ ,boxMaxZ));\n\n return (x - sphereX) * (x - sphereX) +\n (y - sphereY) * (y - sphereY) +\n (z - sphereZ) * (z - sphereZ) < (sphereSize * sphereSize);\n }\n\n int Collision::Min(int i1 ,int i2){\n if(i1 < i2){\n return i1;\n }else{\n return i2;\n }\n }\n\n int Collision::Max(int i1 ,int i2){\n if(i1 > i2){\n return i1;\n }else{\n return i2;\n }\n }\n\n<commit_msg>nothing<commit_after>#include \"collision.h\"\n\nCollision::Collision(){\n}\n bool Collision::SphereVersusSphere(int x1 ,int y1 ,int z1 ,int size1 ,int x2 ,int y2 ,int z2 ,int size2){\n\n return ((x1 - x2) * (x1 - x2) +\n (y1 - y2) * (y1 - y2) +\n (z1 - z2) * (z1 - z2)) >= ((size1+size2) * (size1+size2));\n }\n\n bool Collision::SphereVersusPoint(int sphereX ,int sphereY ,int sphereZ ,int sphereSize ,int PointX ,int PointY ,int PointZ){\n\n\n\n return ((sphereX - PointX) * (sphereX - PointX) +\n (sphereY - PointY) * (sphereY - PointY) +\n (sphereZ - PointZ) * (sphereZ - PointZ) >= (sphereSize * sphereSize));\n }\n\n bool Collision::BoxVersusPoint(int PointX ,int PointY ,int PointZ ,int boxMinX ,int boxMinY ,int boxMinZ ,int boxMaxX ,int boxMaxY ,int boxMaxZ){\n\n\n\n return (PointX >= boxMinX && PointX <= boxMaxX) &&\n (PointY >= boxMinY && PointY <= boxMaxY) &&\n (PointZ >= boxMinZ && PointZ <= boxMaxZ);\n }\n\n bool Collision::BoxVersusBox(int boxMinX1 ,int boxMinY1 ,int boxMinZ1 ,int boxMaxX1 ,int boxMaxY1 ,int boxMaxZ1 ,int boxMinX2 ,int boxMinY2 ,int boxMinZ2 ,int boxMaxX2 ,int boxMaxY2 ,int boxMaxZ2){\n\n return (boxMinX1 <= boxMaxX2 && boxMaxX1 >= boxMinX2) &&\n (boxMinY1 <= boxMaxY2 && boxMaxY1 >= boxMinY2) &&\n (boxMinZ1 <= boxMaxZ2 && boxMaxZ1 >= boxMinZ2);\n\n }\n\n bool Collision::SphereVersusBox(int sphereX ,int sphereY ,int sphereZ ,int sphereSize ,int boxMinX ,int boxMinY ,int boxMinZ ,int boxMaxX ,int boxMaxY ,int boxMaxZ){\n \/\/Math.max(box.minX, Math.min(sphere.x, box.maxX);\n int x = Max(boxMinX, Min(sphereX ,boxMaxX));\n int y = Max(boxMinY, Min(sphereY ,boxMaxY));\n int z = Max(boxMinZ, Min(sphereZ ,boxMaxZ));\n\n return (x - sphereX) * (x - sphereX) +\n (y - sphereY) * (y - sphereY) +\n (z - sphereZ) * (z - sphereZ) < (sphereSize * sphereSize);\n }\n\n int Collision::Min(int i1 ,int i2){\n if(i1 < i2){\n return i1;\n }else{\n return i2;\n }\n }\n\n int Collision::Max(int i1 ,int i2){\n if(i1 > i2){\n return i1;\n }else{\n return i2;\n }\n }\n\n<|endoftext|>"} {"text":"<commit_before>\/*****************************************************************************\n * Licensed to Qualys, Inc. (QUALYS) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * QUALYS licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n ****************************************************************************\/\n\n\/**\n * @file\n * @brief Predicate --- Standard String Implementation\n *\n * @author Christopher Alfeld <calfeld@qualys.com>\n *\/\n\n#include <predicate\/standard_string.hpp>\n\n#include <predicate\/call_factory.hpp>\n#include <predicate\/call_helpers.hpp>\n#include <predicate\/validate.hpp>\n\n#include <boost\/regex.hpp>\n\nusing namespace std;\n\nnamespace IronBee {\nnamespace Predicate {\nnamespace Standard {\n\nstruct StringReplaceRx::data_t\n{\n boost::regex expression;\n string replacement;\n};\n\nStringReplaceRx::StringReplaceRx() :\n m_data(new data_t())\n{\n \/\/ nop\n}\n\nstring StringReplaceRx::name() const\n{\n return \"stringReplaceRx\";\n}\n\nbool StringReplaceRx::validate(NodeReporter reporter) const\n{\n bool result = true;\n result = Validate::n_children(reporter, 3) && result;\n result = Validate::nth_child_is_string(reporter, 0) && result;\n result = Validate::nth_child_is_string(reporter, 1) && result;\n\n return result;\n}\n\nvoid StringReplaceRx::pre_eval(Environment environment, NodeReporter reporter)\n{\n \/\/ Validation guarantees that the first two children are string\n \/\/ literals and thus can be evaluated with default EvalContext.\n\n node_list_t::const_iterator child_i = children().begin();\n Value expression_value = literal_value(*child_i);\n ++child_i;\n Value replacement_value = literal_value(*child_i);\n\n ConstByteString expression = expression_value.value_as_byte_string();\n ConstByteString replacement = replacement_value.value_as_byte_string();\n\n if (! expression) {\n reporter.error(\"Missing expression.\");\n return;\n }\n if (! replacement) {\n reporter.error(\"Missing replacement.\");\n return;\n }\n\n try {\n m_data->expression.assign(\n expression.const_data(), expression.length(),\n boost::regex_constants::normal\n );\n }\n catch (const boost::bad_expression& e) {\n reporter.error(\"Could not compile regexp: \" + expression.to_s() + \" (\" + e.what() + \")\");\n return;\n }\n\n m_data->replacement = replacement.to_s();\n}\n\nValue StringReplaceRx::value_calculate(\n Value v,\n GraphEvalState& graph_eval_state,\n EvalContext context\n) const\n{\n if (! m_data) {\n BOOST_THROW_EXCEPTION(\n einval() << errinfo_what(\n \"Evaluation without pre evaluation!\"\n )\n );\n }\n\n if (v.type() != Value::BYTE_STRING) {\n return Value();\n }\n\n ConstByteString text = v.value_as_byte_string();\n boost::shared_ptr<vector<char> > result(new vector<char>());\n \/\/ value_to_data() ensures that a copy is associated with the memory\n \/\/ pool and will be deleted when the memory pool goes away.\n assert(context.memory_pool());\n value_to_data(result, context.memory_pool().ib());\n\n boost::regex_replace(\n back_inserter(*result),\n text.const_data(), text.const_data() + text.length(),\n m_data->expression,\n m_data->replacement\n );\n\n return Field::create_byte_string(\n context.memory_pool(),\n v.name(), v.name_length(),\n ByteString::create_alias(\n context.memory_pool(),\n result->data(), result->size()\n )\n );\n}\n\nvoid StringReplaceRx::eval_calculate(\n GraphEvalState& graph_eval_state,\n EvalContext context\n) const\n{\n const node_p& input_node = children().back();\n\n map_calculate(input_node, graph_eval_state, context);\n}\n\nvoid load_string(CallFactory& to)\n{\n to\n .add<StringReplaceRx>()\n ;\n}\n\n} \/\/ Standard\n} \/\/ Predicate\n} \/\/ IronBee\n<commit_msg>predicate\/standard_string: Fix bug in StringReplaceRx that occurred when the result was the empty string.<commit_after>\/*****************************************************************************\n * Licensed to Qualys, Inc. (QUALYS) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * QUALYS licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n ****************************************************************************\/\n\n\/**\n * @file\n * @brief Predicate --- Standard String Implementation\n *\n * @author Christopher Alfeld <calfeld@qualys.com>\n *\/\n\n#include <predicate\/standard_string.hpp>\n\n#include <predicate\/call_factory.hpp>\n#include <predicate\/call_helpers.hpp>\n#include <predicate\/validate.hpp>\n\n#include <boost\/regex.hpp>\n\nusing namespace std;\n\nnamespace IronBee {\nnamespace Predicate {\nnamespace Standard {\n\nstruct StringReplaceRx::data_t\n{\n boost::regex expression;\n string replacement;\n};\n\nStringReplaceRx::StringReplaceRx() :\n m_data(new data_t())\n{\n \/\/ nop\n}\n\nstring StringReplaceRx::name() const\n{\n return \"stringReplaceRx\";\n}\n\nbool StringReplaceRx::validate(NodeReporter reporter) const\n{\n bool result = true;\n result = Validate::n_children(reporter, 3) && result;\n result = Validate::nth_child_is_string(reporter, 0) && result;\n result = Validate::nth_child_is_string(reporter, 1) && result;\n\n return result;\n}\n\nvoid StringReplaceRx::pre_eval(Environment environment, NodeReporter reporter)\n{\n \/\/ Validation guarantees that the first two children are string\n \/\/ literals and thus can be evaluated with default EvalContext.\n\n node_list_t::const_iterator child_i = children().begin();\n Value expression_value = literal_value(*child_i);\n ++child_i;\n Value replacement_value = literal_value(*child_i);\n\n ConstByteString expression = expression_value.value_as_byte_string();\n ConstByteString replacement = replacement_value.value_as_byte_string();\n\n if (! expression) {\n reporter.error(\"Missing expression.\");\n return;\n }\n if (! replacement) {\n reporter.error(\"Missing replacement.\");\n return;\n }\n\n try {\n m_data->expression.assign(\n expression.const_data(), expression.length(),\n boost::regex_constants::normal\n );\n }\n catch (const boost::bad_expression& e) {\n reporter.error(\"Could not compile regexp: \" + expression.to_s() + \" (\" + e.what() + \")\");\n return;\n }\n\n m_data->replacement = replacement.to_s();\n}\n\nValue StringReplaceRx::value_calculate(\n Value v,\n GraphEvalState& graph_eval_state,\n EvalContext context\n) const\n{\n if (! m_data) {\n BOOST_THROW_EXCEPTION(\n einval() << errinfo_what(\n \"Evaluation without pre evaluation!\"\n )\n );\n }\n\n if (v.type() != Value::BYTE_STRING) {\n return Value();\n }\n\n ConstByteString text = v.value_as_byte_string();\n boost::shared_ptr<vector<char> > result(new vector<char>());\n \/\/ Ensure that result.data() is non-null, even if we never insert\n \/\/ anything.\n result->reserve(1);\n\n \/\/ value_to_data() ensures that a copy is associated with the memory\n \/\/ pool and will be deleted when the memory pool goes away.\n assert(context.memory_pool());\n value_to_data(result, context.memory_pool().ib());\n\n boost::regex_replace(\n back_inserter(*result),\n text.const_data(), text.const_data() + text.length(),\n m_data->expression,\n m_data->replacement\n );\n\n return Field::create_byte_string(\n context.memory_pool(),\n v.name(), v.name_length(),\n ByteString::create_alias(\n context.memory_pool(),\n result->data(), result->size()\n )\n );\n}\n\nvoid StringReplaceRx::eval_calculate(\n GraphEvalState& graph_eval_state,\n EvalContext context\n) const\n{\n const node_p& input_node = children().back();\n\n map_calculate(input_node, graph_eval_state, context);\n}\n\nvoid load_string(CallFactory& to)\n{\n to\n .add<StringReplaceRx>()\n ;\n}\n\n} \/\/ Standard\n} \/\/ Predicate\n} \/\/ IronBee\n<|endoftext|>"} {"text":"<commit_before>#include <tightdb\/column_mixed.hpp>\n\nnamespace tightdb {\n\nColumnMixed::~ColumnMixed()\n{\n delete m_types;\n delete m_refs;\n delete m_data;\n delete m_array;\n}\n\nvoid ColumnMixed::Destroy()\n{\n if (m_array != NULL)\n m_array->Destroy();\n}\n\nvoid ColumnMixed::SetParent(ArrayParent *parent, size_t pndx)\n{\n m_array->SetParent(parent, pndx);\n}\n\nvoid ColumnMixed::UpdateFromParent()\n{\n if (!m_array->UpdateFromParent())\n return;\n\n m_types->UpdateFromParent();\n m_refs->UpdateFromParent();\n if (m_data)\n m_data->UpdateFromParent();\n}\n\n\nvoid ColumnMixed::Create(Allocator& alloc, const Table* table, size_t column_ndx)\n{\n m_array = new Array(COLUMN_HASREFS, NULL, 0, alloc);\n\n m_types = new Column(COLUMN_NORMAL, alloc);\n m_refs = new RefsColumn(alloc, table, column_ndx);\n\n m_array->add(m_types->GetRef());\n m_array->add(m_refs->GetRef());\n\n m_types->SetParent(m_array, 0);\n m_refs->SetParent(m_array, 1);\n}\n\nvoid ColumnMixed::Create(Allocator& alloc, const Table* table, size_t column_ndx,\n ArrayParent* parent, size_t ndx_in_parent, size_t ref)\n{\n m_array = new Array(ref, parent, ndx_in_parent, alloc);\n TIGHTDB_ASSERT(m_array->Size() == 2 || m_array->Size() == 3);\n\n const size_t types_ref = m_array->GetAsRef(0);\n const size_t refs_ref = m_array->GetAsRef(1);\n\n m_types = new Column(types_ref, m_array, 0, alloc);\n m_refs = new RefsColumn(alloc, table, column_ndx, m_array, 1, refs_ref);\n TIGHTDB_ASSERT(m_types->Size() == m_refs->Size());\n\n \/\/ Binary column with values that does not fit in refs\n \/\/ is only there if needed\n if (m_array->Size() == 3) {\n const size_t data_ref = m_array->GetAsRef(2);\n m_data = new ColumnBinary(data_ref, m_array, 2, alloc);\n }\n}\n\nvoid ColumnMixed::InitDataColumn()\n{\n if (m_data)\n return;\n\n TIGHTDB_ASSERT(m_array->Size() == 2);\n\n \/\/ Create new data column for items that do not fit in refs\n m_data = new ColumnBinary(m_array->GetAllocator());\n const size_t ref = m_data->GetRef();\n\n m_array->add(ref);\n m_data->SetParent(m_array, 2);\n}\n\nvoid ColumnMixed::clear_value(size_t ndx, MixedColType newtype)\n{\n TIGHTDB_ASSERT(ndx < m_types->Size());\n\n const MixedColType type = (MixedColType)m_types->Get(ndx);\n if (type != MIXED_COL_INT) {\n switch (type) {\n case MIXED_COL_INT_NEG:\n case MIXED_COL_BOOL:\n case MIXED_COL_DATE:\n case MIXED_COL_FLOAT:\n case MIXED_COL_DOUBLE:\n case MIXED_COL_DOUBLE_NEG:\n break;\n case MIXED_COL_STRING:\n case MIXED_COL_BINARY:\n {\n \/\/ If item is in middle of the column, we just clear\n \/\/ it to avoid having to adjust refs to following items\n const size_t ref = m_refs->GetAsRef(ndx) >> 1;\n if (ref == m_data->Size()-1) \n m_data->Delete(ref);\n else \n m_data->Set(ref, \"\", 0);\n break;\n }\n case MIXED_COL_TABLE:\n {\n \/\/ Delete entire table\n const size_t ref = m_refs->GetAsRef(ndx);\n Array top(ref, (Array*)NULL, 0, m_array->GetAllocator());\n top.Destroy();\n break;\n }\n default:\n TIGHTDB_ASSERT(false);\n }\n }\n if (type != newtype) \n m_types->Set(ndx, newtype);\n}\n\nvoid ColumnMixed::Delete(size_t ndx)\n{\n TIGHTDB_ASSERT(ndx < m_types->Size());\n\n \/\/ Remove refs or binary data\n clear_value(ndx, MIXED_COL_INT);\n\n m_types->Delete(ndx);\n m_refs->Delete(ndx);\n\n invalidate_subtables();\n}\n\nvoid ColumnMixed::Clear()\n{\n m_types->Clear();\n m_refs->Clear();\n if (m_data)\n m_data->Clear();\n}\n\nDataType ColumnMixed::get_type(size_t ndx) const TIGHTDB_NOEXCEPT\n{\n TIGHTDB_ASSERT(ndx < m_types->Size());\n MixedColType coltype = static_cast<MixedColType>(m_types->Get(ndx));\n switch (coltype) {\n case MIXED_COL_INT_NEG: return type_Int;\n case MIXED_COL_DOUBLE_NEG: return type_Double;\n default: return static_cast<ColumnType>(coltype); \/\/ all others must be in sync with ColumnType\n }\n}\n\nvoid ColumnMixed::fill(size_t count)\n{\n TIGHTDB_ASSERT(is_empty());\n\n \/\/ Fill column with default values\n \/\/ TODO: this is a very naive approach\n \/\/ we could speedup by creating full nodes directly\n for (size_t i = 0; i < count; ++i) {\n m_types->Insert(i, MIXED_COL_INT);\n }\n for (size_t i = 0; i < count; ++i) {\n m_refs->Insert(i, 1); \/\/ 1 is zero shifted one and low bit set;\n }\n\n#ifdef TIGHTDB_DEBUG\n Verify();\n#endif\n}\n\n\nvoid ColumnMixed::set_string(size_t ndx, const char* value)\n{\n TIGHTDB_ASSERT(ndx < m_types->Size());\n InitDataColumn();\n\n const MixedColType type = (MixedColType)m_types->Get(ndx);\n const size_t len = strlen(value)+1;\n\n \/\/ See if we can reuse data position\n if (type == MIXED_COL_STRING) {\n const size_t ref = m_refs->GetAsRef(ndx) >> 1;\n m_data->Set(ref, value, len);\n }\n else if (type == MIXED_COL_BINARY) {\n const size_t ref = m_refs->GetAsRef(ndx) >> 1;\n m_data->Set(ref, value, len);\n m_types->Set(ndx, MIXED_COL_STRING);\n }\n else {\n \/\/ Remove refs or binary data\n clear_value(ndx, MIXED_COL_STRING);\n\n \/\/ Add value to data column\n const size_t ref = m_data->Size();\n m_data->add(value, len);\n\n \/\/ Shift value one bit and set lowest bit to indicate that this is not a ref\n const int64_t v = (ref << 1) + 1;\n\n m_types->Set(ndx, MIXED_COL_STRING);\n m_refs->Set(ndx, v);\n }\n}\n\nvoid ColumnMixed::set_binary(size_t ndx, const char* value, size_t len)\n{\n TIGHTDB_ASSERT(ndx < m_types->Size());\n InitDataColumn();\n\n const MixedColType type = (MixedColType)m_types->Get(ndx);\n\n \/\/ See if we can reuse data position\n if (type == MIXED_COL_STRING) {\n const size_t ref = m_refs->GetAsRef(ndx) >> 1;\n m_data->Set(ref, value, len);\n m_types->Set(ndx, MIXED_COL_BINARY);\n }\n else if (type == MIXED_COL_BINARY) {\n const size_t ref = m_refs->GetAsRef(ndx) >> 1;\n m_data->Set(ref, value, len);\n }\n else {\n \/\/ Remove refs or binary data\n clear_value(ndx, MIXED_COL_BINARY);\n\n \/\/ Add value to data column\n const size_t ref = m_data->Size();\n m_data->add(value, len);\n\n \/\/ Shift value one bit and set lowest bit to indicate that this is not a ref\n const int64_t v = (ref << 1) + 1;\n\n m_types->Set(ndx, MIXED_COL_BINARY);\n m_refs->Set(ndx, v);\n }\n}\n\nbool ColumnMixed::Compare(const ColumnMixed& c) const\n{\n const size_t n = Size();\n if (c.Size() != n)\n return false;\n\n for (size_t i=0; i<n; ++i) {\n const DataType type = get_type(i);\n if (c.get_type(i) != type)\n return false;\n switch (type) {\n case type_Int:\n if (get_int(i) != c.get_int(i)) return false;\n break;\n case type_Bool:\n if (get_bool(i) != c.get_bool(i)) return false;\n break;\n case type_Date:\n if (get_date(i) != c.get_date(i)) return false;\n break;\n case type_Float:\n if (get_float(i) != c.get_float(i)) return false;\n break;\n case type_Double:\n if (get_double(i) != c.get_double(i)) return false;\n break;\n case type_String:\n if (strcmp(get_string(i), c.get_string(i)) != 0) return false;\n break;\n case type_Binary:\n {\n const BinaryData d1 = get_binary(i);\n const BinaryData d2 = c.get_binary(i);\n if (d1.len != d2.len || !std::equal(d1.pointer, d1.pointer+d1.len, d2.pointer))\n return false;\n }\n break;\n case type_Table:\n {\n ConstTableRef t1 = get_subtable_ptr(i)->get_table_ref();\n ConstTableRef t2 = c.get_subtable_ptr(i)->get_table_ref();\n if (*t1 != *t2)\n return false;\n }\n break;\n case type_Mixed:\n TIGHTDB_ASSERT(false);\n break;\n }\n }\n return true;\n}\n\n\n#ifdef TIGHTDB_DEBUG\n\nvoid ColumnMixed::Verify() const\n{\n m_array->Verify();\n m_types->Verify();\n m_refs->Verify();\n if (m_data) m_data->Verify();\n\n \/\/ types and refs should be in sync\n const size_t types_len = m_types->Size();\n const size_t refs_len = m_refs->Size();\n TIGHTDB_ASSERT(types_len == refs_len);\n\n \/\/ Verify each sub-table\n const size_t count = Size();\n for (size_t i = 0; i < count; ++i) {\n const size_t tref = m_refs->GetAsRef(i);\n if (tref == 0 || tref & 0x1) continue;\n ConstTableRef subtable = m_refs->get_subtable(i);\n subtable->Verify();\n }\n}\n\nvoid ColumnMixed::ToDot(std::ostream& out, const char* title) const\n{\n const size_t ref = GetRef();\n\n out << \"subgraph cluster_columnmixed\" << ref << \" {\" << std::endl;\n out << \" label = \\\"ColumnMixed\";\n if (title) out << \"\\\\n'\" << title << \"'\";\n out << \"\\\";\" << std::endl;\n\n m_array->ToDot(out, \"mixed_top\");\n\n \/\/ Write sub-tables\n const size_t count = Size();\n for (size_t i = 0; i < count; ++i) {\n const MixedColType type = (MixedColType)m_types->Get(i);\n if (type != MIXED_COL_TABLE) continue;\n ConstTableRef subtable = m_refs->get_subtable(i);\n subtable->to_dot(out);\n }\n\n m_types->ToDot(out, \"types\");\n m_refs->ToDot(out, \"refs\");\n\n if (m_array->Size() > 2) {\n m_data->ToDot(out, \"data\");\n }\n\n out << \"}\" << std::endl;\n}\n\n#endif \/\/ TIGHTDB_DEBUG\n\n} \/\/ namespace tightdb\n<commit_msg>Fix for: Merge branch 'error_handling_plus_float' into column_type_rename<commit_after>#include <tightdb\/column_mixed.hpp>\n\nnamespace tightdb {\n\nColumnMixed::~ColumnMixed()\n{\n delete m_types;\n delete m_refs;\n delete m_data;\n delete m_array;\n}\n\nvoid ColumnMixed::Destroy()\n{\n if (m_array != NULL)\n m_array->Destroy();\n}\n\nvoid ColumnMixed::SetParent(ArrayParent *parent, size_t pndx)\n{\n m_array->SetParent(parent, pndx);\n}\n\nvoid ColumnMixed::UpdateFromParent()\n{\n if (!m_array->UpdateFromParent())\n return;\n\n m_types->UpdateFromParent();\n m_refs->UpdateFromParent();\n if (m_data)\n m_data->UpdateFromParent();\n}\n\n\nvoid ColumnMixed::Create(Allocator& alloc, const Table* table, size_t column_ndx)\n{\n m_array = new Array(COLUMN_HASREFS, NULL, 0, alloc);\n\n m_types = new Column(COLUMN_NORMAL, alloc);\n m_refs = new RefsColumn(alloc, table, column_ndx);\n\n m_array->add(m_types->GetRef());\n m_array->add(m_refs->GetRef());\n\n m_types->SetParent(m_array, 0);\n m_refs->SetParent(m_array, 1);\n}\n\nvoid ColumnMixed::Create(Allocator& alloc, const Table* table, size_t column_ndx,\n ArrayParent* parent, size_t ndx_in_parent, size_t ref)\n{\n m_array = new Array(ref, parent, ndx_in_parent, alloc);\n TIGHTDB_ASSERT(m_array->Size() == 2 || m_array->Size() == 3);\n\n const size_t types_ref = m_array->GetAsRef(0);\n const size_t refs_ref = m_array->GetAsRef(1);\n\n m_types = new Column(types_ref, m_array, 0, alloc);\n m_refs = new RefsColumn(alloc, table, column_ndx, m_array, 1, refs_ref);\n TIGHTDB_ASSERT(m_types->Size() == m_refs->Size());\n\n \/\/ Binary column with values that does not fit in refs\n \/\/ is only there if needed\n if (m_array->Size() == 3) {\n const size_t data_ref = m_array->GetAsRef(2);\n m_data = new ColumnBinary(data_ref, m_array, 2, alloc);\n }\n}\n\nvoid ColumnMixed::InitDataColumn()\n{\n if (m_data)\n return;\n\n TIGHTDB_ASSERT(m_array->Size() == 2);\n\n \/\/ Create new data column for items that do not fit in refs\n m_data = new ColumnBinary(m_array->GetAllocator());\n const size_t ref = m_data->GetRef();\n\n m_array->add(ref);\n m_data->SetParent(m_array, 2);\n}\n\nvoid ColumnMixed::clear_value(size_t ndx, MixedColType newtype)\n{\n TIGHTDB_ASSERT(ndx < m_types->Size());\n\n const MixedColType type = (MixedColType)m_types->Get(ndx);\n if (type != MIXED_COL_INT) {\n switch (type) {\n case MIXED_COL_INT_NEG:\n case MIXED_COL_BOOL:\n case MIXED_COL_DATE:\n case MIXED_COL_FLOAT:\n case MIXED_COL_DOUBLE:\n case MIXED_COL_DOUBLE_NEG:\n break;\n case MIXED_COL_STRING:\n case MIXED_COL_BINARY:\n {\n \/\/ If item is in middle of the column, we just clear\n \/\/ it to avoid having to adjust refs to following items\n const size_t ref = m_refs->GetAsRef(ndx) >> 1;\n if (ref == m_data->Size()-1) \n m_data->Delete(ref);\n else \n m_data->Set(ref, \"\", 0);\n break;\n }\n case MIXED_COL_TABLE:\n {\n \/\/ Delete entire table\n const size_t ref = m_refs->GetAsRef(ndx);\n Array top(ref, (Array*)NULL, 0, m_array->GetAllocator());\n top.Destroy();\n break;\n }\n default:\n TIGHTDB_ASSERT(false);\n }\n }\n if (type != newtype) \n m_types->Set(ndx, newtype);\n}\n\nvoid ColumnMixed::Delete(size_t ndx)\n{\n TIGHTDB_ASSERT(ndx < m_types->Size());\n\n \/\/ Remove refs or binary data\n clear_value(ndx, MIXED_COL_INT);\n\n m_types->Delete(ndx);\n m_refs->Delete(ndx);\n\n invalidate_subtables();\n}\n\nvoid ColumnMixed::Clear()\n{\n m_types->Clear();\n m_refs->Clear();\n if (m_data)\n m_data->Clear();\n}\n\nDataType ColumnMixed::get_type(size_t ndx) const TIGHTDB_NOEXCEPT\n{\n TIGHTDB_ASSERT(ndx < m_types->Size());\n MixedColType coltype = static_cast<MixedColType>(m_types->Get(ndx));\n switch (coltype) {\n case MIXED_COL_INT_NEG: return type_Int;\n case MIXED_COL_DOUBLE_NEG: return type_Double;\n default: return static_cast<DataType>(coltype); \/\/ all others must be in sync with ColumnType\n }\n}\n\nvoid ColumnMixed::fill(size_t count)\n{\n TIGHTDB_ASSERT(is_empty());\n\n \/\/ Fill column with default values\n \/\/ TODO: this is a very naive approach\n \/\/ we could speedup by creating full nodes directly\n for (size_t i = 0; i < count; ++i) {\n m_types->Insert(i, MIXED_COL_INT);\n }\n for (size_t i = 0; i < count; ++i) {\n m_refs->Insert(i, 1); \/\/ 1 is zero shifted one and low bit set;\n }\n\n#ifdef TIGHTDB_DEBUG\n Verify();\n#endif\n}\n\n\nvoid ColumnMixed::set_string(size_t ndx, const char* value)\n{\n TIGHTDB_ASSERT(ndx < m_types->Size());\n InitDataColumn();\n\n const MixedColType type = (MixedColType)m_types->Get(ndx);\n const size_t len = strlen(value)+1;\n\n \/\/ See if we can reuse data position\n if (type == MIXED_COL_STRING) {\n const size_t ref = m_refs->GetAsRef(ndx) >> 1;\n m_data->Set(ref, value, len);\n }\n else if (type == MIXED_COL_BINARY) {\n const size_t ref = m_refs->GetAsRef(ndx) >> 1;\n m_data->Set(ref, value, len);\n m_types->Set(ndx, MIXED_COL_STRING);\n }\n else {\n \/\/ Remove refs or binary data\n clear_value(ndx, MIXED_COL_STRING);\n\n \/\/ Add value to data column\n const size_t ref = m_data->Size();\n m_data->add(value, len);\n\n \/\/ Shift value one bit and set lowest bit to indicate that this is not a ref\n const int64_t v = (ref << 1) + 1;\n\n m_types->Set(ndx, MIXED_COL_STRING);\n m_refs->Set(ndx, v);\n }\n}\n\nvoid ColumnMixed::set_binary(size_t ndx, const char* value, size_t len)\n{\n TIGHTDB_ASSERT(ndx < m_types->Size());\n InitDataColumn();\n\n const MixedColType type = (MixedColType)m_types->Get(ndx);\n\n \/\/ See if we can reuse data position\n if (type == MIXED_COL_STRING) {\n const size_t ref = m_refs->GetAsRef(ndx) >> 1;\n m_data->Set(ref, value, len);\n m_types->Set(ndx, MIXED_COL_BINARY);\n }\n else if (type == MIXED_COL_BINARY) {\n const size_t ref = m_refs->GetAsRef(ndx) >> 1;\n m_data->Set(ref, value, len);\n }\n else {\n \/\/ Remove refs or binary data\n clear_value(ndx, MIXED_COL_BINARY);\n\n \/\/ Add value to data column\n const size_t ref = m_data->Size();\n m_data->add(value, len);\n\n \/\/ Shift value one bit and set lowest bit to indicate that this is not a ref\n const int64_t v = (ref << 1) + 1;\n\n m_types->Set(ndx, MIXED_COL_BINARY);\n m_refs->Set(ndx, v);\n }\n}\n\nbool ColumnMixed::Compare(const ColumnMixed& c) const\n{\n const size_t n = Size();\n if (c.Size() != n)\n return false;\n\n for (size_t i=0; i<n; ++i) {\n const DataType type = get_type(i);\n if (c.get_type(i) != type)\n return false;\n switch (type) {\n case type_Int:\n if (get_int(i) != c.get_int(i)) return false;\n break;\n case type_Bool:\n if (get_bool(i) != c.get_bool(i)) return false;\n break;\n case type_Date:\n if (get_date(i) != c.get_date(i)) return false;\n break;\n case type_Float:\n if (get_float(i) != c.get_float(i)) return false;\n break;\n case type_Double:\n if (get_double(i) != c.get_double(i)) return false;\n break;\n case type_String:\n if (strcmp(get_string(i), c.get_string(i)) != 0) return false;\n break;\n case type_Binary:\n {\n const BinaryData d1 = get_binary(i);\n const BinaryData d2 = c.get_binary(i);\n if (d1.len != d2.len || !std::equal(d1.pointer, d1.pointer+d1.len, d2.pointer))\n return false;\n }\n break;\n case type_Table:\n {\n ConstTableRef t1 = get_subtable_ptr(i)->get_table_ref();\n ConstTableRef t2 = c.get_subtable_ptr(i)->get_table_ref();\n if (*t1 != *t2)\n return false;\n }\n break;\n case type_Mixed:\n TIGHTDB_ASSERT(false);\n break;\n }\n }\n return true;\n}\n\n\n#ifdef TIGHTDB_DEBUG\n\nvoid ColumnMixed::Verify() const\n{\n m_array->Verify();\n m_types->Verify();\n m_refs->Verify();\n if (m_data) m_data->Verify();\n\n \/\/ types and refs should be in sync\n const size_t types_len = m_types->Size();\n const size_t refs_len = m_refs->Size();\n TIGHTDB_ASSERT(types_len == refs_len);\n\n \/\/ Verify each sub-table\n const size_t count = Size();\n for (size_t i = 0; i < count; ++i) {\n const size_t tref = m_refs->GetAsRef(i);\n if (tref == 0 || tref & 0x1) continue;\n ConstTableRef subtable = m_refs->get_subtable(i);\n subtable->Verify();\n }\n}\n\nvoid ColumnMixed::ToDot(std::ostream& out, const char* title) const\n{\n const size_t ref = GetRef();\n\n out << \"subgraph cluster_columnmixed\" << ref << \" {\" << std::endl;\n out << \" label = \\\"ColumnMixed\";\n if (title) out << \"\\\\n'\" << title << \"'\";\n out << \"\\\";\" << std::endl;\n\n m_array->ToDot(out, \"mixed_top\");\n\n \/\/ Write sub-tables\n const size_t count = Size();\n for (size_t i = 0; i < count; ++i) {\n const MixedColType type = (MixedColType)m_types->Get(i);\n if (type != MIXED_COL_TABLE) continue;\n ConstTableRef subtable = m_refs->get_subtable(i);\n subtable->to_dot(out);\n }\n\n m_types->ToDot(out, \"types\");\n m_refs->ToDot(out, \"refs\");\n\n if (m_array->Size() > 2) {\n m_data->ToDot(out, \"data\");\n }\n\n out << \"}\" << std::endl;\n}\n\n#endif \/\/ TIGHTDB_DEBUG\n\n} \/\/ namespace tightdb\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/sync\/notifier\/server_notifier_thread.h\"\n\n#include <string>\n#include <vector>\n\n#include \"base\/logging.h\"\n#include \"chrome\/browser\/sync\/notifier\/chrome_invalidation_client.h\"\n#include \"googleurl\/src\/gurl.h\"\n#include \"jingle\/notifier\/base\/notifier_options.h\"\n#include \"jingle\/notifier\/listener\/notification_defines.h\"\n#include \"talk\/xmpp\/xmppclient.h\"\n#include \"webkit\/glue\/webkit_glue.h\"\n\nnamespace sync_notifier {\n\nServerNotifierThread::ServerNotifierThread(\n const notifier::NotifierOptions& notifier_options,\n const std::string& state, StateWriter* state_writer)\n : notifier::MediatorThreadImpl(notifier_options),\n state_(state),\n state_writers_(new ObserverListThreadSafe<StateWriter>()),\n state_writer_(state_writer) {\n DCHECK_EQ(notifier::NOTIFICATION_SERVER,\n notifier_options.notification_method);\n DCHECK(state_writer_);\n state_writers_->AddObserver(state_writer_);\n}\n\nServerNotifierThread::~ServerNotifierThread() {}\n\nvoid ServerNotifierThread::ListenForUpdates() {\n DCHECK_EQ(MessageLoop::current(), parent_message_loop_);\n worker_message_loop()->PostTask(\n FROM_HERE,\n NewRunnableMethod(this, &ServerNotifierThread::DoListenForUpdates));\n}\n\nvoid ServerNotifierThread::SubscribeForUpdates(\n const std::vector<std::string>& subscribed_services_list) {\n DCHECK_EQ(MessageLoop::current(), parent_message_loop_);\n worker_message_loop()->PostTask(\n FROM_HERE,\n NewRunnableMethod(\n this, &ServerNotifierThread::RegisterTypesAndSignalSubscribed));\n}\n\nvoid ServerNotifierThread::Logout() {\n DCHECK_EQ(MessageLoop::current(), parent_message_loop_);\n state_writers_->RemoveObserver(state_writer_);\n state_writer_ = NULL;\n worker_message_loop()->PostTask(\n FROM_HERE,\n NewRunnableMethod(this,\n &ServerNotifierThread::StopInvalidationListener));\n MediatorThreadImpl::Logout();\n}\n\nvoid ServerNotifierThread::SendNotification(\n const OutgoingNotificationData& data) {\n DCHECK_EQ(MessageLoop::current(), parent_message_loop_);\n NOTREACHED() << \"Shouldn't send notifications if ServerNotifierThread is \"\n \"used\";\n}\n\nvoid ServerNotifierThread::OnInvalidate(\n syncable::ModelType model_type,\n const std::string& payload) {\n DCHECK_EQ(MessageLoop::current(), worker_message_loop());\n DCHECK_GE(model_type, syncable::FIRST_REAL_MODEL_TYPE);\n DCHECK_LT(model_type, syncable::MODEL_TYPE_COUNT);\n VLOG(1) << \"OnInvalidate: \" << syncable::ModelTypeToString(model_type);\n\n syncable::ModelTypeBitSet model_types;\n model_types[model_type] = true;\n IncomingNotificationData notification_data;\n notification_data.service_url = model_types.to_string();\n notification_data.service_specific_data = payload;\n observers_->Notify(&Observer::OnIncomingNotification, notification_data);\n}\n\nvoid ServerNotifierThread::OnInvalidateAll() {\n DCHECK_EQ(MessageLoop::current(), worker_message_loop());\n VLOG(1) << \"OnInvalidateAll\";\n\n syncable::ModelTypeBitSet model_types;\n model_types.set(); \/\/ InvalidateAll, so set all datatypes to true.\n IncomingNotificationData notification_data;\n notification_data.service_specific_data = model_types.to_string();\n observers_->Notify(&Observer::OnIncomingNotification, notification_data);\n}\n\nvoid ServerNotifierThread::WriteState(const std::string& state) {\n DCHECK_EQ(MessageLoop::current(), worker_message_loop());\n VLOG(1) << \"WriteState\";\n state_writers_->Notify(&StateWriter::WriteState, state);\n}\n\nvoid ServerNotifierThread::DoListenForUpdates() {\n DCHECK_EQ(MessageLoop::current(), worker_message_loop());\n if (!base_task_.get()) {\n return;\n }\n\n if (chrome_invalidation_client_.get()) {\n \/\/ If we already have an invalidation client, simply change the\n \/\/ base task.\n chrome_invalidation_client_->ChangeBaseTask(base_task_);\n } else {\n \/\/ Otherwise, create the invalidation client.\n chrome_invalidation_client_.reset(new ChromeInvalidationClient());\n\n \/\/ TODO(akalin): Make cache_guid() part of the client ID. If we do\n \/\/ so and we somehow propagate it up to the server somehow, we can\n \/\/ make it so that we won't receive any notifications that were\n \/\/ generated from our own changes.\n const std::string kClientId = \"server_notifier_thread\";\n \/\/ Use user agent as |client_info| so we can use it for debugging\n \/\/ server-side.\n const std::string& client_info = webkit_glue::GetUserAgent(GURL());\n chrome_invalidation_client_->Start(\n kClientId, client_info, state_, this, this, base_task_);\n state_.clear();\n }\n}\n\nvoid ServerNotifierThread::RegisterTypesAndSignalSubscribed() {\n DCHECK_EQ(MessageLoop::current(), worker_message_loop());\n if (!chrome_invalidation_client_.get()) {\n return;\n }\n chrome_invalidation_client_->RegisterTypes();\n observers_->Notify(&Observer::OnSubscriptionStateChange, true);\n}\n\nvoid ServerNotifierThread::StopInvalidationListener() {\n DCHECK_EQ(MessageLoop::current(), worker_message_loop());\n chrome_invalidation_client_.reset();\n}\n\n} \/\/ namespace sync_notifier\n<commit_msg>[SYNC] Fix server notifier's InvalidateAll().<commit_after>\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/sync\/notifier\/server_notifier_thread.h\"\n\n#include <string>\n#include <vector>\n\n#include \"base\/logging.h\"\n#include \"chrome\/browser\/sync\/notifier\/chrome_invalidation_client.h\"\n#include \"googleurl\/src\/gurl.h\"\n#include \"jingle\/notifier\/base\/notifier_options.h\"\n#include \"jingle\/notifier\/listener\/notification_defines.h\"\n#include \"talk\/xmpp\/xmppclient.h\"\n#include \"webkit\/glue\/webkit_glue.h\"\n\nnamespace sync_notifier {\n\nServerNotifierThread::ServerNotifierThread(\n const notifier::NotifierOptions& notifier_options,\n const std::string& state, StateWriter* state_writer)\n : notifier::MediatorThreadImpl(notifier_options),\n state_(state),\n state_writers_(new ObserverListThreadSafe<StateWriter>()),\n state_writer_(state_writer) {\n DCHECK_EQ(notifier::NOTIFICATION_SERVER,\n notifier_options.notification_method);\n DCHECK(state_writer_);\n state_writers_->AddObserver(state_writer_);\n}\n\nServerNotifierThread::~ServerNotifierThread() {}\n\nvoid ServerNotifierThread::ListenForUpdates() {\n DCHECK_EQ(MessageLoop::current(), parent_message_loop_);\n worker_message_loop()->PostTask(\n FROM_HERE,\n NewRunnableMethod(this, &ServerNotifierThread::DoListenForUpdates));\n}\n\nvoid ServerNotifierThread::SubscribeForUpdates(\n const std::vector<std::string>& subscribed_services_list) {\n DCHECK_EQ(MessageLoop::current(), parent_message_loop_);\n worker_message_loop()->PostTask(\n FROM_HERE,\n NewRunnableMethod(\n this, &ServerNotifierThread::RegisterTypesAndSignalSubscribed));\n}\n\nvoid ServerNotifierThread::Logout() {\n DCHECK_EQ(MessageLoop::current(), parent_message_loop_);\n state_writers_->RemoveObserver(state_writer_);\n state_writer_ = NULL;\n worker_message_loop()->PostTask(\n FROM_HERE,\n NewRunnableMethod(this,\n &ServerNotifierThread::StopInvalidationListener));\n MediatorThreadImpl::Logout();\n}\n\nvoid ServerNotifierThread::SendNotification(\n const OutgoingNotificationData& data) {\n DCHECK_EQ(MessageLoop::current(), parent_message_loop_);\n NOTREACHED() << \"Shouldn't send notifications if ServerNotifierThread is \"\n \"used\";\n}\n\nvoid ServerNotifierThread::OnInvalidate(\n syncable::ModelType model_type,\n const std::string& payload) {\n DCHECK_EQ(MessageLoop::current(), worker_message_loop());\n DCHECK_GE(model_type, syncable::FIRST_REAL_MODEL_TYPE);\n DCHECK_LT(model_type, syncable::MODEL_TYPE_COUNT);\n VLOG(1) << \"OnInvalidate: \" << syncable::ModelTypeToString(model_type);\n\n syncable::ModelTypeBitSet model_types;\n model_types[model_type] = true;\n IncomingNotificationData notification_data;\n notification_data.service_url = model_types.to_string();\n notification_data.service_specific_data = payload;\n observers_->Notify(&Observer::OnIncomingNotification, notification_data);\n}\n\nvoid ServerNotifierThread::OnInvalidateAll() {\n DCHECK_EQ(MessageLoop::current(), worker_message_loop());\n VLOG(1) << \"OnInvalidateAll\";\n\n syncable::ModelTypeBitSet model_types;\n model_types.set(); \/\/ InvalidateAll, so set all datatypes to true.\n IncomingNotificationData notification_data;\n notification_data.service_url = model_types.to_string();\n notification_data.service_specific_data = std::string(); \/\/ No payload.\n observers_->Notify(&Observer::OnIncomingNotification, notification_data);\n}\n\nvoid ServerNotifierThread::WriteState(const std::string& state) {\n DCHECK_EQ(MessageLoop::current(), worker_message_loop());\n VLOG(1) << \"WriteState\";\n state_writers_->Notify(&StateWriter::WriteState, state);\n}\n\nvoid ServerNotifierThread::DoListenForUpdates() {\n DCHECK_EQ(MessageLoop::current(), worker_message_loop());\n if (!base_task_.get()) {\n return;\n }\n\n if (chrome_invalidation_client_.get()) {\n \/\/ If we already have an invalidation client, simply change the\n \/\/ base task.\n chrome_invalidation_client_->ChangeBaseTask(base_task_);\n } else {\n \/\/ Otherwise, create the invalidation client.\n chrome_invalidation_client_.reset(new ChromeInvalidationClient());\n\n \/\/ TODO(akalin): Make cache_guid() part of the client ID. If we do\n \/\/ so and we somehow propagate it up to the server somehow, we can\n \/\/ make it so that we won't receive any notifications that were\n \/\/ generated from our own changes.\n const std::string kClientId = \"server_notifier_thread\";\n \/\/ Use user agent as |client_info| so we can use it for debugging\n \/\/ server-side.\n const std::string& client_info = webkit_glue::GetUserAgent(GURL());\n chrome_invalidation_client_->Start(\n kClientId, client_info, state_, this, this, base_task_);\n state_.clear();\n }\n}\n\nvoid ServerNotifierThread::RegisterTypesAndSignalSubscribed() {\n DCHECK_EQ(MessageLoop::current(), worker_message_loop());\n if (!chrome_invalidation_client_.get()) {\n return;\n }\n chrome_invalidation_client_->RegisterTypes();\n observers_->Notify(&Observer::OnSubscriptionStateChange, true);\n}\n\nvoid ServerNotifierThread::StopInvalidationListener() {\n DCHECK_EQ(MessageLoop::current(), worker_message_loop());\n chrome_invalidation_client_.reset();\n}\n\n} \/\/ namespace sync_notifier\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2015 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include <string>\n\n#include \"base\/command_line.h\"\n#include \"base\/compiler_specific.h\"\n#include \"chrome\/browser\/devtools\/devtools_window_testing.h\"\n#include \"chrome\/browser\/extensions\/extension_browsertest.h\"\n#include \"chrome\/browser\/extensions\/extension_service.h\"\n#include \"chrome\/browser\/extensions\/extension_util.h\"\n#include \"chrome\/browser\/ui\/browser_finder.h\"\n#include \"chrome\/browser\/ui\/browser_iterator.h\"\n#include \"chrome\/browser\/ui\/extensions\/app_launch_params.h\"\n#include \"chrome\/browser\/ui\/extensions\/application_launch.h\"\n#include \"chrome\/browser\/ui\/extensions\/hosted_app_browser_controller.h\"\n#include \"chrome\/browser\/ui\/tabs\/tab_strip_model.h\"\n#include \"chrome\/browser\/web_applications\/web_app.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/test\/base\/ui_test_utils.h\"\n#include \"content\/public\/browser\/web_contents.h\"\n#include \"extensions\/browser\/extension_registry.h\"\n#include \"extensions\/common\/constants.h\"\n#include \"extensions\/common\/extension.h\"\n#include \"extensions\/common\/extension_set.h\"\n\nusing content::WebContents;\nusing extensions::Extension;\n\nnamespace {\n\n\/\/ Used by ShouldLocationBarForXXX. Performs a navigation and then checks that\n\/\/ the location bar visibility is as expcted.\nvoid NavigateAndCheckForLocationBar(Browser* browser,\n const std::string& url_string,\n bool expected_visibility) {\n GURL url(url_string);\n ui_test_utils::NavigateToURL(browser, url);\n EXPECT_EQ(expected_visibility,\n browser->hosted_app_controller()->ShouldShowLocationBar());\n}\n\n} \/\/ namespace\n\nclass HostedAppTest : public ExtensionBrowserTest {\n public:\n HostedAppTest() : app_browser_(nullptr) {}\n ~HostedAppTest() override {}\n\n protected:\n void SetupApp(const std::string& app_folder, bool is_bookmark_app) {\n const Extension* app = InstallExtensionWithSourceAndFlags(\n test_data_dir_.AppendASCII(app_folder), 1,\n extensions::Manifest::INTERNAL,\n is_bookmark_app ? extensions::Extension::FROM_BOOKMARK\n : extensions::Extension::NO_FLAGS);\n ASSERT_TRUE(app);\n\n \/\/ Launch it in a window.\n ASSERT_TRUE(OpenApplication(AppLaunchParams(\n browser()->profile(), app, extensions::LAUNCH_CONTAINER_WINDOW,\n NEW_WINDOW, extensions::SOURCE_TEST)));\n\n for (chrome::BrowserIterator it; !it.done(); it.Next()) {\n if (*it == browser())\n continue;\n\n std::string browser_app_id =\n web_app::GetExtensionIdFromApplicationName((*it)->app_name());\n if (browser_app_id == app->id()) {\n app_browser_ = *it;\n break;\n }\n }\n\n ASSERT_TRUE(app_browser_);\n ASSERT_TRUE(app_browser_ != browser());\n }\n\n Browser* app_browser_;\n};\n\n\/\/ Check that the location bar is shown correctly for HTTP bookmark apps.\nIN_PROC_BROWSER_TEST_F(HostedAppTest,\n ShouldShowLocationBarForHTTPBookmarkApp) {\n base::CommandLine::ForCurrentProcess()->AppendSwitch(\n switches::kEnableNewBookmarkApps);\n\n SetupApp(\"app\", true);\n\n \/\/ Navigate to the app's launch page; the location bar should be hidden.\n NavigateAndCheckForLocationBar(\n app_browser_, \"http:\/\/www.example.com\/empty.html\", false);\n\n \/\/ Navigate to another page on the same origin; the location bar should still\n \/\/ hidden.\n NavigateAndCheckForLocationBar(\n app_browser_, \"http:\/\/www.example.com\/blah\", false);\n\n \/\/ Navigate to the https version of the site; the location bar should\n \/\/ be hidden.\n NavigateAndCheckForLocationBar(\n app_browser_, \"https:\/\/www.example.com\/blah\", false);\n\n \/\/ Navigate to different origin; the location bar should now be visible.\n NavigateAndCheckForLocationBar(\n app_browser_, \"http:\/\/www.foo.com\/blah\", true);\n\n \/\/ Navigate back to the app's origin; the location bar should now be hidden.\n NavigateAndCheckForLocationBar(\n app_browser_, \"http:\/\/www.example.com\/blah\", false);\n}\n\n\/\/ Check that the location bar is shown correctly for HTTPS bookmark apps.\nIN_PROC_BROWSER_TEST_F(HostedAppTest,\n ShouldShowLocationBarForHTTPSBookmarkApp) {\n base::CommandLine::ForCurrentProcess()->AppendSwitch(\n switches::kEnableNewBookmarkApps);\n\n SetupApp(\"https_app\", true);\n\n \/\/ Navigate to the app's launch page; the location bar should be hidden.\n NavigateAndCheckForLocationBar(\n app_browser_, \"https:\/\/www.example.com\/empty.html\", false);\n\n \/\/ Navigate to another page on the same origin; the location bar should still\n \/\/ hidden.\n NavigateAndCheckForLocationBar(\n app_browser_, \"https:\/\/www.example.com\/blah\", false);\n\n \/\/ Navigate to the http version of the site; the location bar should\n \/\/ be visible for the https version as it is now on a less secure version\n \/\/ of its host.\n NavigateAndCheckForLocationBar(\n app_browser_, \"http:\/\/www.example.com\/blah\", true);\n\n \/\/ Navigate to different origin; the location bar should now be visible.\n NavigateAndCheckForLocationBar(\n app_browser_, \"http:\/\/www.foo.com\/blah\", true);\n\n \/\/ Navigate back to the app's origin; the location bar should now be hidden.\n NavigateAndCheckForLocationBar(\n app_browser_, \"https:\/\/www.example.com\/blah\", false);\n}\n\n\/\/ Check that the location bar is shown correctly for normal hosted apps.\nIN_PROC_BROWSER_TEST_F(HostedAppTest,\n ShouldShowLocationBarForHostedApp) {\n SetupApp(\"app\", false);\n\n \/\/ Navigate to the app's launch page; the location bar should be hidden.\n NavigateAndCheckForLocationBar(\n app_browser_, \"http:\/\/www.example.com\/empty.html\", false);\n\n \/\/ Navigate to another page on the same origin; the location bar should still\n \/\/ hidden.\n NavigateAndCheckForLocationBar(\n app_browser_, \"http:\/\/www.example.com\/blah\", false);\n\n \/\/ Navigate to the https version of the site; the location bar should\n \/\/ be hidden.\n NavigateAndCheckForLocationBar(\n app_browser_, \"https:\/\/www.example.com\/blah\", false);\n\n \/\/ Navigate to different origin; the location bar should now be visible.\n NavigateAndCheckForLocationBar(\n app_browser_, \"http:\/\/www.foo.com\/blah\", true);\n\n \/\/ Navigate back to the app's origin; the location bar should now be hidden.\n NavigateAndCheckForLocationBar(\n app_browser_, \"http:\/\/www.example.com\/blah\", false);\n}\n\n\/\/ Check that the location bar is shown correctly for hosted apps that specify\n\/\/ start URLs without the 'www.' prefix.\nIN_PROC_BROWSER_TEST_F(HostedAppTest,\n LocationBarForHostedAppWithoutWWW) {\n SetupApp(\"app_no_www\", false);\n\n \/\/ Navigate to the app's launch page; the location bar should be hidden.\n NavigateAndCheckForLocationBar(\n app_browser_, \"http:\/\/example.com\/empty.html\", false);\n\n \/\/ Navigate to the app's launch page with the 'www.' prefis; the location bar\n \/\/ should be hidden.\n NavigateAndCheckForLocationBar(\n app_browser_, \"http:\/\/www.example.com\/empty.html\", false);\n\n \/\/ Navigate to different origin; the location bar should now be visible.\n NavigateAndCheckForLocationBar(\n app_browser_, \"http:\/\/www.foo.com\/blah\", true);\n\n \/\/ Navigate back to the app's origin; the location bar should now be hidden.\n NavigateAndCheckForLocationBar(\n app_browser_, \"http:\/\/example.com\/blah\", false);\n}\n\n\/\/ Open a normal browser window, a hosted app window, a legacy packaged app\n\/\/ window and a dev tools window, and check that the web app frame feature is\n\/\/ supported correctly.\nIN_PROC_BROWSER_TEST_F(HostedAppTest, ShouldUseWebAppFrame) {\n base::CommandLine::ForCurrentProcess()->AppendSwitch(\n switches::kEnableWebAppFrame);\n\n \/\/ Load a hosted app.\n const Extension* bookmark_app = InstallExtensionWithSourceAndFlags(\n test_data_dir_.AppendASCII(\"app\"),\n 1,\n extensions::Manifest::INTERNAL,\n extensions::Extension::FROM_BOOKMARK);\n ASSERT_TRUE(bookmark_app);\n\n \/\/ Launch it in a window, as AppLauncherHandler::HandleLaunchApp() would.\n WebContents* bookmark_app_window = OpenApplication(AppLaunchParams(\n browser()->profile(), bookmark_app, extensions::LAUNCH_CONTAINER_WINDOW,\n NEW_WINDOW, extensions::SOURCE_UNTRACKED));\n ASSERT_TRUE(bookmark_app_window);\n\n \/\/ Load a packaged app.\n ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII(\"packaged_app\")));\n const Extension* packaged_app = nullptr;\n extensions::ExtensionRegistry* registry =\n extensions::ExtensionRegistry::Get(browser()->profile());\n for (const scoped_refptr<const extensions::Extension>& extension :\n registry->enabled_extensions()) {\n if (extension->name() == \"Packaged App Test\")\n packaged_app = extension.get();\n }\n ASSERT_TRUE(packaged_app);\n\n \/\/ Launch it in a window, as AppLauncherHandler::HandleLaunchApp() would.\n WebContents* packaged_app_window = OpenApplication(AppLaunchParams(\n browser()->profile(), packaged_app, extensions::LAUNCH_CONTAINER_WINDOW,\n NEW_WINDOW, extensions::SOURCE_UNTRACKED));\n ASSERT_TRUE(packaged_app_window);\n\n DevToolsWindow* devtools_window =\n DevToolsWindowTesting::OpenDevToolsWindowSync(browser(), false);\n\n \/\/ The launch should have created a new app browser and a dev tools browser.\n ASSERT_EQ(4u, chrome::GetBrowserCount(browser()->profile(),\n browser()->host_desktop_type()));\n\n \/\/ Find the new browsers.\n Browser* bookmark_app_browser = nullptr;\n Browser* packaged_app_browser = nullptr;\n Browser* dev_tools_browser = nullptr;\n for (chrome::BrowserIterator it; !it.done(); it.Next()) {\n if (*it == browser()) {\n continue;\n } else if ((*it)->app_name() == DevToolsWindow::kDevToolsApp) {\n dev_tools_browser = *it;\n } else if ((*it)->tab_strip_model()->GetActiveWebContents() ==\n bookmark_app_window) {\n bookmark_app_browser = *it;\n } else {\n packaged_app_browser = *it;\n }\n }\n ASSERT_TRUE(dev_tools_browser);\n ASSERT_TRUE(bookmark_app_browser);\n ASSERT_TRUE(bookmark_app_browser != browser());\n ASSERT_TRUE(packaged_app_browser);\n ASSERT_TRUE(packaged_app_browser != browser());\n ASSERT_TRUE(packaged_app_browser != bookmark_app_browser);\n\n EXPECT_FALSE(browser()->SupportsWindowFeature(Browser::FEATURE_WEBAPPFRAME));\n EXPECT_FALSE(\n dev_tools_browser->SupportsWindowFeature(Browser::FEATURE_WEBAPPFRAME));\n EXPECT_EQ(browser()->host_desktop_type() == chrome::HOST_DESKTOP_TYPE_ASH,\n bookmark_app_browser->SupportsWindowFeature(\n Browser::FEATURE_WEBAPPFRAME));\n EXPECT_FALSE(packaged_app_browser->SupportsWindowFeature(\n Browser::FEATURE_WEBAPPFRAME));\n\n DevToolsWindowTesting::CloseDevToolsWindowSync(devtools_window);\n}\n<commit_msg>Split up and minimise hosted app location bar tests.<commit_after>\/\/ Copyright 2015 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include <string>\n\n#include \"base\/command_line.h\"\n#include \"base\/compiler_specific.h\"\n#include \"chrome\/browser\/devtools\/devtools_window_testing.h\"\n#include \"chrome\/browser\/extensions\/extension_browsertest.h\"\n#include \"chrome\/browser\/extensions\/extension_service.h\"\n#include \"chrome\/browser\/extensions\/extension_util.h\"\n#include \"chrome\/browser\/ui\/browser_finder.h\"\n#include \"chrome\/browser\/ui\/browser_iterator.h\"\n#include \"chrome\/browser\/ui\/extensions\/app_launch_params.h\"\n#include \"chrome\/browser\/ui\/extensions\/application_launch.h\"\n#include \"chrome\/browser\/ui\/extensions\/hosted_app_browser_controller.h\"\n#include \"chrome\/browser\/ui\/tabs\/tab_strip_model.h\"\n#include \"chrome\/browser\/web_applications\/web_app.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/test\/base\/ui_test_utils.h\"\n#include \"content\/public\/browser\/web_contents.h\"\n#include \"extensions\/browser\/extension_registry.h\"\n#include \"extensions\/common\/constants.h\"\n#include \"extensions\/common\/extension.h\"\n#include \"extensions\/common\/extension_set.h\"\n\nusing content::WebContents;\nusing extensions::Extension;\n\nnamespace {\n\n\/\/ Used by ShouldLocationBarForXXX. Performs a navigation and then checks that\n\/\/ the location bar visibility is as expcted.\nvoid NavigateAndCheckForLocationBar(Browser* browser,\n const std::string& url_string,\n bool expected_visibility) {\n GURL url(url_string);\n ui_test_utils::NavigateToURL(browser, url);\n EXPECT_EQ(expected_visibility,\n browser->hosted_app_controller()->ShouldShowLocationBar());\n}\n\n} \/\/ namespace\n\nclass HostedAppTest : public ExtensionBrowserTest {\n public:\n HostedAppTest() : app_browser_(nullptr) {}\n ~HostedAppTest() override {}\n\n protected:\n void SetupApp(const std::string& app_folder, bool is_bookmark_app) {\n const Extension* app = InstallExtensionWithSourceAndFlags(\n test_data_dir_.AppendASCII(app_folder), 1,\n extensions::Manifest::INTERNAL,\n is_bookmark_app ? extensions::Extension::FROM_BOOKMARK\n : extensions::Extension::NO_FLAGS);\n ASSERT_TRUE(app);\n\n \/\/ Launch it in a window.\n ASSERT_TRUE(OpenApplication(AppLaunchParams(\n browser()->profile(), app, extensions::LAUNCH_CONTAINER_WINDOW,\n NEW_WINDOW, extensions::SOURCE_TEST)));\n\n for (chrome::BrowserIterator it; !it.done(); it.Next()) {\n if (*it == browser())\n continue;\n\n std::string browser_app_id =\n web_app::GetExtensionIdFromApplicationName((*it)->app_name());\n if (browser_app_id == app->id()) {\n app_browser_ = *it;\n break;\n }\n }\n\n ASSERT_TRUE(app_browser_);\n ASSERT_TRUE(app_browser_ != browser());\n }\n\n Browser* app_browser_;\n};\n\n\/\/ Check that the location bar is shown correctly for bookmark apps.\nIN_PROC_BROWSER_TEST_F(HostedAppTest,\n ShouldShowLocationBarForBookmarkApp) {\n base::CommandLine::ForCurrentProcess()->AppendSwitch(\n switches::kEnableNewBookmarkApps);\n\n SetupApp(\"app\", true);\n\n \/\/ Navigate to the app's launch page; the location bar should be hidden.\n NavigateAndCheckForLocationBar(\n app_browser_, \"http:\/\/www.example.com\/empty.html\", false);\n\n \/\/ Navigate to another page on the same origin; the location bar should still\n \/\/ hidden.\n NavigateAndCheckForLocationBar(\n app_browser_, \"http:\/\/www.example.com\/blah\", false);\n\n \/\/ Navigate to different origin; the location bar should now be visible.\n NavigateAndCheckForLocationBar(\n app_browser_, \"http:\/\/www.foo.com\/blah\", true);\n}\n\n\/\/ Check that the location bar is shown correctly for HTTP bookmark apps when\n\/\/ they navigate to a HTTPS page on the same origin.\nIN_PROC_BROWSER_TEST_F(HostedAppTest,\n ShouldShowLocationBarForHTTPBookmarkApp) {\n base::CommandLine::ForCurrentProcess()->AppendSwitch(\n switches::kEnableNewBookmarkApps);\n\n SetupApp(\"app\", true);\n\n \/\/ Navigate to the app's launch page; the location bar should be hidden.\n NavigateAndCheckForLocationBar(\n app_browser_, \"http:\/\/www.example.com\/empty.html\", false);\n\n \/\/ Navigate to the https version of the site; the location bar should\n \/\/ be hidden.\n NavigateAndCheckForLocationBar(\n app_browser_, \"https:\/\/www.example.com\/blah\", false);\n}\n\n\/\/ Check that the location bar is shown correctly for HTTPS bookmark apps when\n\/\/ they navigate to a HTTP page on the same origin.\nIN_PROC_BROWSER_TEST_F(HostedAppTest,\n ShouldShowLocationBarForHTTPSBookmarkApp) {\n base::CommandLine::ForCurrentProcess()->AppendSwitch(\n switches::kEnableNewBookmarkApps);\n\n SetupApp(\"https_app\", true);\n\n \/\/ Navigate to the app's launch page; the location bar should be hidden.\n NavigateAndCheckForLocationBar(\n app_browser_, \"https:\/\/www.example.com\/empty.html\", false);\n\n \/\/ Navigate to the http version of the site; the location bar should\n \/\/ be visible for the https version as it is now on a less secure version\n \/\/ of its host.\n NavigateAndCheckForLocationBar(\n app_browser_, \"http:\/\/www.example.com\/blah\", true);\n}\n\n\/\/ Check that the location bar is shown correctly for normal hosted apps.\nIN_PROC_BROWSER_TEST_F(HostedAppTest,\n ShouldShowLocationBarForHostedApp) {\n SetupApp(\"app\", false);\n\n \/\/ Navigate to the app's launch page; the location bar should be hidden.\n NavigateAndCheckForLocationBar(\n app_browser_, \"http:\/\/www.example.com\/empty.html\", false);\n\n \/\/ Navigate to another page on the same origin; the location bar should still\n \/\/ hidden.\n NavigateAndCheckForLocationBar(\n app_browser_, \"http:\/\/www.example.com\/blah\", false);\n\n \/\/ Navigate to different origin; the location bar should now be visible.\n NavigateAndCheckForLocationBar(\n app_browser_, \"http:\/\/www.foo.com\/blah\", true);\n}\n\n\/\/ Check that the location bar is shown correctly for hosted apps that specify\n\/\/ start URLs without the 'www.' prefix.\nIN_PROC_BROWSER_TEST_F(HostedAppTest,\n LocationBarForHostedAppWithoutWWW) {\n SetupApp(\"app_no_www\", false);\n\n \/\/ Navigate to the app's launch page; the location bar should be hidden.\n NavigateAndCheckForLocationBar(\n app_browser_, \"http:\/\/example.com\/empty.html\", false);\n\n \/\/ Navigate to the app's launch page with the 'www.' prefis; the location bar\n \/\/ should be hidden.\n NavigateAndCheckForLocationBar(\n app_browser_, \"http:\/\/www.example.com\/empty.html\", false);\n\n \/\/ Navigate to different origin; the location bar should now be visible.\n NavigateAndCheckForLocationBar(\n app_browser_, \"http:\/\/www.foo.com\/blah\", true);\n}\n\n\/\/ Open a normal browser window, a hosted app window, a legacy packaged app\n\/\/ window and a dev tools window, and check that the web app frame feature is\n\/\/ supported correctly.\nIN_PROC_BROWSER_TEST_F(HostedAppTest, ShouldUseWebAppFrame) {\n base::CommandLine::ForCurrentProcess()->AppendSwitch(\n switches::kEnableWebAppFrame);\n\n \/\/ Load a hosted app.\n const Extension* bookmark_app = InstallExtensionWithSourceAndFlags(\n test_data_dir_.AppendASCII(\"app\"),\n 1,\n extensions::Manifest::INTERNAL,\n extensions::Extension::FROM_BOOKMARK);\n ASSERT_TRUE(bookmark_app);\n\n \/\/ Launch it in a window, as AppLauncherHandler::HandleLaunchApp() would.\n WebContents* bookmark_app_window = OpenApplication(AppLaunchParams(\n browser()->profile(), bookmark_app, extensions::LAUNCH_CONTAINER_WINDOW,\n NEW_WINDOW, extensions::SOURCE_UNTRACKED));\n ASSERT_TRUE(bookmark_app_window);\n\n \/\/ Load a packaged app.\n ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII(\"packaged_app\")));\n const Extension* packaged_app = nullptr;\n extensions::ExtensionRegistry* registry =\n extensions::ExtensionRegistry::Get(browser()->profile());\n for (const scoped_refptr<const extensions::Extension>& extension :\n registry->enabled_extensions()) {\n if (extension->name() == \"Packaged App Test\")\n packaged_app = extension.get();\n }\n ASSERT_TRUE(packaged_app);\n\n \/\/ Launch it in a window, as AppLauncherHandler::HandleLaunchApp() would.\n WebContents* packaged_app_window = OpenApplication(AppLaunchParams(\n browser()->profile(), packaged_app, extensions::LAUNCH_CONTAINER_WINDOW,\n NEW_WINDOW, extensions::SOURCE_UNTRACKED));\n ASSERT_TRUE(packaged_app_window);\n\n DevToolsWindow* devtools_window =\n DevToolsWindowTesting::OpenDevToolsWindowSync(browser(), false);\n\n \/\/ The launch should have created a new app browser and a dev tools browser.\n ASSERT_EQ(4u, chrome::GetBrowserCount(browser()->profile(),\n browser()->host_desktop_type()));\n\n \/\/ Find the new browsers.\n Browser* bookmark_app_browser = nullptr;\n Browser* packaged_app_browser = nullptr;\n Browser* dev_tools_browser = nullptr;\n for (chrome::BrowserIterator it; !it.done(); it.Next()) {\n if (*it == browser()) {\n continue;\n } else if ((*it)->app_name() == DevToolsWindow::kDevToolsApp) {\n dev_tools_browser = *it;\n } else if ((*it)->tab_strip_model()->GetActiveWebContents() ==\n bookmark_app_window) {\n bookmark_app_browser = *it;\n } else {\n packaged_app_browser = *it;\n }\n }\n ASSERT_TRUE(dev_tools_browser);\n ASSERT_TRUE(bookmark_app_browser);\n ASSERT_TRUE(bookmark_app_browser != browser());\n ASSERT_TRUE(packaged_app_browser);\n ASSERT_TRUE(packaged_app_browser != browser());\n ASSERT_TRUE(packaged_app_browser != bookmark_app_browser);\n\n EXPECT_FALSE(browser()->SupportsWindowFeature(Browser::FEATURE_WEBAPPFRAME));\n EXPECT_FALSE(\n dev_tools_browser->SupportsWindowFeature(Browser::FEATURE_WEBAPPFRAME));\n EXPECT_EQ(browser()->host_desktop_type() == chrome::HOST_DESKTOP_TYPE_ASH,\n bookmark_app_browser->SupportsWindowFeature(\n Browser::FEATURE_WEBAPPFRAME));\n EXPECT_FALSE(packaged_app_browser->SupportsWindowFeature(\n Browser::FEATURE_WEBAPPFRAME));\n\n DevToolsWindowTesting::CloseDevToolsWindowSync(devtools_window);\n}\n<|endoftext|>"} {"text":"<commit_before><commit_msg>Kill dead code.<commit_after><|endoftext|>"} {"text":"<commit_before>\n\/\/ @(#)root\/proof:$Id$\n\/\/ Author: G. Ganis Nov 2006\n\n\/*************************************************************************\n * Copyright (C) 1995-2005, Rene Brun and Fons Rademakers. *\n * All rights reserved. *\n * *\n * For the licensing terms see $ROOTSYS\/LICENSE. *\n * For the list of contributors see $ROOTSYS\/README\/CREDITS. *\n *************************************************************************\/\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ \/\/\n\/\/ TProofChain \/\/\n\/\/ \/\/\n\/\/ A TChain proxy on PROOF. \/\/\n\/\/ Uses an internal TDSet to handle processing. \/\/\n\/\/ \/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"TProofChain.h\"\n#include \"TDSet.h\"\n#include \"TList.h\"\n#include \"TProof.h\"\n#include \"TROOT.h\"\n#include \"TEventList.h\"\n#include \"TEntryList.h\"\n\nClassImp(TProofChain)\n\n\/\/______________________________________________________________________________\nTProofChain::TProofChain() : TChain()\n{\n \/\/ Crates a new Proof chain proxy containing the files from the TDSet.\n\n fChain = 0;\n fTree = 0;\n fSet = 0;\n fDirectory = gDirectory;\n fDrawFeedback = 0;\n}\n\n\/\/______________________________________________________________________________\nTProofChain::TProofChain(TChain *chain) : TChain()\n{\n \/\/ Crates a new Proof chain proxy containing the files from the TDSet.\n\n fChain = chain;\n fTree = 0;\n fSet = chain ? new TDSet((const TChain &)(*chain)) : 0;\n fDirectory = gDirectory;\n fDrawFeedback = 0;\n if (gProof)\n gProof->AddChain(chain);\n}\n\n\/\/______________________________________________________________________________\nTProofChain::~TProofChain()\n{\n \/\/ Destructor\n\n if (fChain) {\n SafeDelete(fSet);\n \/\/ Remove the chain from the private lists in the TProof objects\n TIter nxp(gROOT->GetListOfSockets());\n TObject *o = 0;\n TProof *p = 0;\n while ((o = nxp()))\n if ((p = dynamic_cast<TProof *>(o)))\n p->RemoveChain(fChain);\n fChain->SetProof(0);\n } else {\n \/\/ Not owner\n fSet = 0;\n }\n SafeDelete(fTree);\n fDirectory = 0;\n\n}\n\n\/\/______________________________________________________________________________\nTProofChain::TProofChain(TDSet *dset, Bool_t gettreeheader)\n{\n \/\/ Constructor from existing data set\n\n fChain = 0;\n fTree = 0;\n fSet = dset;\n fDirectory = gDirectory;\n fDrawFeedback = 0;\n if (gProof) {\n ConnectProof();\n if (gettreeheader && dset)\n fTree = gProof->GetTreeHeader(dset);\n }\n}\n\n\/\/______________________________________________________________________________\nvoid TProofChain::Browse(TBrowser *b)\n{\n \/\/ Forwards the execution to the dummy tree header.\n \/\/ See TTree::Browse().\n\n fSet->Browse(b);\n}\n\n\/\/______________________________________________________________________________\nLong64_t TProofChain::Draw(const char *varexp, const TCut &selection,\n Option_t *option, Long64_t nentries, Long64_t firstentry)\n{\n \/\/ Forwards the execution to the TDSet.\n \/\/ Returns -1 in case of error or number of selected events in case of success.\n \/\/ See TDSet::Browse().\n\n if (!gProof) {\n Error(\"Draw\", \"no active PROOF session\");\n return -1;\n }\n ConnectProof();\n\n if (fDrawFeedback)\n gProof->SetDrawFeedbackOption(fDrawFeedback, option);\n fReadEntry = firstentry;\n\n \/\/ Set either the entry-list (priority) or the event-list\n if (fEntryList) {\n fSet->SetEntryList(fEntryList);\n } else if (fEventList) {\n fSet->SetEntryList(fEventList);\n }\n\n Long64_t rv = fSet->Draw(varexp, selection, option, nentries, firstentry);\n return rv;\n}\n\n\/\/______________________________________________________________________________\nLong64_t TProofChain::Draw(const char *varexp, const char *selection,\n Option_t *option,Long64_t nentries, Long64_t firstentry)\n{\n \/\/ Forwards the execution to the TDSet.\n \/\/ Returns -1 in case of error or number of selected events in case of success.\n \/\/ See TDSet::Browse().\n\n if (!gProof) {\n Error(\"Draw\", \"no active PROOF session\");\n return -1;\n }\n ConnectProof();\n\n if (fDrawFeedback)\n gProof->SetDrawFeedbackOption(fDrawFeedback, option);\n fReadEntry = firstentry;\n\n \/\/ Set either the entry-list (priority) or the event-list\n if (fEntryList) {\n fSet->SetEntryList(fEntryList);\n } else if (fEventList) {\n fSet->SetEntryList(fEventList);\n }\n\n Long64_t rv = fSet->Draw(varexp, selection, option, nentries, firstentry);\n return rv;\n}\n\n\/\/______________________________________________________________________________\nTBranch *TProofChain::FindBranch(const char* branchname)\n{\n \/\/ Forwards the execution to the dummy tree header.\n \/\/ See TTree::FindBranch().\n\n return (fTree ? fTree->FindBranch(branchname) : (TBranch *)0);\n}\n\n\/\/______________________________________________________________________________\nTLeaf *TProofChain::FindLeaf(const char* searchname)\n{\n \/\/ Forwards the execution to the dummy tree header.\n \/\/ See TTree::FindLeaf().\n\n return (fTree ? fTree->FindLeaf(searchname) : (TLeaf *)0);\n}\n\n\/\/______________________________________________________________________________\nTBranch *TProofChain::GetBranch(const char *name)\n{\n \/\/ Forwards the execution to the dummy tree header.\n \/\/ See TTree::GetBranch().\n\n return (fTree ? fTree->GetBranch(name) : (TBranch *)0);\n}\n\n\/\/______________________________________________________________________________\nBool_t TProofChain::GetBranchStatus(const char *branchname) const\n{\n \/\/ Forwards the execution to the dummy tree header.\n \/\/ See TTree::GetBranchStatus().\n\n return (fTree ? fTree->GetBranchStatus(branchname) : kFALSE);\n}\n\n\/\/______________________________________________________________________________\nTVirtualTreePlayer *TProofChain::GetPlayer()\n{\n \/\/ Forwards the execution to the dummy tree header.\n \/\/ See TTree::GetPlayer().\n\n if (!fTree)\n if (gProof) {\n fTree = gProof->GetTreeHeader(fSet);\n ConnectProof();\n }\n\n return (fTree ? fTree->GetPlayer() : (TVirtualTreePlayer *)0);\n}\n\n\/\/______________________________________________________________________________\nLong64_t TProofChain::Process(const char *filename, Option_t *option,\n Long64_t nentries, Long64_t firstentry)\n{\n \/\/ Forwards the execution to the TDSet.\n \/\/ The return value is -1 in case of error and TSelector::GetStatus() in\n \/\/ in case of success.\n \/\/ See TDSet::Process().\n\n \/\/ Set either the entry-list (priority) or the event-list\n if (fEntryList) {\n fSet->SetEntryList(fEntryList);\n } else if (fEventList) {\n fSet->SetEntryList(fEventList);\n }\n\n return fSet->Process(filename, option, nentries, firstentry);\n}\n\n\/\/______________________________________________________________________________\nLong64_t TProofChain::Process(TSelector *selector, Option_t *option,\n Long64_t nentries, Long64_t firstentry)\n{\n \/\/ Not implemented in TProofChain. Shouldn't be used.\n \/\/ The return value is -1 in case of error and TSelector::GetStatus() in\n \/\/ in case of success.\n\n if (selector || option || nentries || firstentry) { }\n \/\/ return fSet->Process(selector, option, nentries, firstentry);\n Warning(\"Process\", \"not implemented\"); \/\/ TODO\n return -1;\n}\n\n\/\/______________________________________________________________________________\nvoid TProofChain::SetDebug(Int_t level, Long64_t min, Long64_t max)\n{\n \/\/ See TTree::SetDebug\n\n TTree::SetDebug(level, min, max);\n}\n\n\/\/______________________________________________________________________________\nvoid TProofChain::SetName(const char *name)\n{\n \/\/ See TTree::GetName.\n\n TTree::SetName(name);\n}\n\n\/\/______________________________________________________________________________\nLong64_t TProofChain::GetEntries() const\n{\n \/\/ Returns the total number of entries in the TProofChain, which is\n \/\/ the number of entries in the TDSet that it holds.\n\n \/\/ this was used for holding the total number of entries\n return (fTree ? fTree->GetMaxEntryLoop() : (Long64_t)(-1));\n}\n\n\/\/______________________________________________________________________________\nLong64_t TProofChain::GetEntries(const char *)\n{\n \/\/ See TTree::GetEntries(const char *selection)\n \/\/ Not implemented in TProofChain. Shouldn't be used.\n\n return Long64_t(-1);\n}\n\n\/\/______________________________________________________________________________\nvoid TProofChain::Progress(Long64_t total, Long64_t processed)\n{\n \/\/ Changes the number of processed entries.\n\n if (gROOT->IsInterrupted() && gProof)\n gProof->StopProcess(kTRUE);\n if (total) { }\n\n fReadEntry = processed;\n}\n\n\/\/______________________________________________________________________________\nLong64_t TProofChain::GetReadEntry() const\n{\n \/\/ Returns the number of processed entries.\n\n return fReadEntry;\n}\n\n\/\/______________________________________________________________________________\nvoid TProofChain::ReleaseProof()\n{\n \/\/ Releases PROOF. Disconnect the \"progress\" signal.\n\n if (!gProof)\n return;\n gProof->Disconnect(\"Progress(Long64_t,Long64_t)\",\n this, \"Progress(Long64_t,Long64_t)\");\n if (fDrawFeedback)\n gProof->DeleteDrawFeedback(fDrawFeedback);\n fDrawFeedback = 0;\n}\n\n\/\/______________________________________________________________________________\nvoid TProofChain::ConnectProof()\n{\n \/\/ Connects the proof - creates a \"DrawFeedback\" and connects the\n \/\/ \"Progress\" signal.\n\n if (gProof && !fDrawFeedback) {\n fDrawFeedback = gProof->CreateDrawFeedback();\n\n gProof->Connect(\"Progress(Long64_t,Long64_t)\", \"TProofChain\",\n this, \"Progress(Long64_t,Long64_t)\");\n }\n}\n<commit_msg>Avoid recursive destruction (fix bug #30608)<commit_after>\n\/\/ @(#)root\/proof:$Id$\n\/\/ Author: G. Ganis Nov 2006\n\n\/*************************************************************************\n * Copyright (C) 1995-2005, Rene Brun and Fons Rademakers. *\n * All rights reserved. *\n * *\n * For the licensing terms see $ROOTSYS\/LICENSE. *\n * For the list of contributors see $ROOTSYS\/README\/CREDITS. *\n *************************************************************************\/\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ \/\/\n\/\/ TProofChain \/\/\n\/\/ \/\/\n\/\/ A TChain proxy on PROOF. \/\/\n\/\/ Uses an internal TDSet to handle processing. \/\/\n\/\/ \/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"TProofChain.h\"\n#include \"TDSet.h\"\n#include \"TList.h\"\n#include \"TProof.h\"\n#include \"TROOT.h\"\n#include \"TEventList.h\"\n#include \"TEntryList.h\"\n\nClassImp(TProofChain)\n\n\/\/______________________________________________________________________________\nTProofChain::TProofChain() : TChain()\n{\n \/\/ Crates a new Proof chain proxy containing the files from the TDSet.\n\n fChain = 0;\n fTree = 0;\n fSet = 0;\n fDirectory = gDirectory;\n fDrawFeedback = 0;\n}\n\n\/\/______________________________________________________________________________\nTProofChain::TProofChain(TChain *chain) : TChain()\n{\n \/\/ Crates a new Proof chain proxy containing the files from the TDSet.\n\n fChain = chain;\n fTree = 0;\n fSet = chain ? new TDSet((const TChain &)(*chain)) : 0;\n fDirectory = gDirectory;\n fDrawFeedback = 0;\n if (gProof)\n gProof->AddChain(chain);\n}\n\n\/\/______________________________________________________________________________\nTProofChain::~TProofChain()\n{\n \/\/ Destructor\n\n if (fChain) {\n SafeDelete(fSet);\n \/\/ Remove the chain from the private lists in the TProof objects\n TIter nxp(gROOT->GetListOfSockets());\n TObject *o = 0;\n TProof *p = 0;\n while ((o = nxp()))\n if ((p = dynamic_cast<TProof *>(o)))\n p->RemoveChain(fChain);\n fChain = 0;\n } else {\n \/\/ Not owner\n fSet = 0;\n }\n SafeDelete(fTree);\n fDirectory = 0;\n\n}\n\n\/\/______________________________________________________________________________\nTProofChain::TProofChain(TDSet *dset, Bool_t gettreeheader)\n{\n \/\/ Constructor from existing data set\n\n fChain = 0;\n fTree = 0;\n fSet = dset;\n fDirectory = gDirectory;\n fDrawFeedback = 0;\n if (gProof) {\n ConnectProof();\n if (gettreeheader && dset)\n fTree = gProof->GetTreeHeader(dset);\n }\n}\n\n\/\/______________________________________________________________________________\nvoid TProofChain::Browse(TBrowser *b)\n{\n \/\/ Forwards the execution to the dummy tree header.\n \/\/ See TTree::Browse().\n\n fSet->Browse(b);\n}\n\n\/\/______________________________________________________________________________\nLong64_t TProofChain::Draw(const char *varexp, const TCut &selection,\n Option_t *option, Long64_t nentries, Long64_t firstentry)\n{\n \/\/ Forwards the execution to the TDSet.\n \/\/ Returns -1 in case of error or number of selected events in case of success.\n \/\/ See TDSet::Browse().\n\n if (!gProof) {\n Error(\"Draw\", \"no active PROOF session\");\n return -1;\n }\n ConnectProof();\n\n if (fDrawFeedback)\n gProof->SetDrawFeedbackOption(fDrawFeedback, option);\n fReadEntry = firstentry;\n\n \/\/ Set either the entry-list (priority) or the event-list\n if (fEntryList) {\n fSet->SetEntryList(fEntryList);\n } else if (fEventList) {\n fSet->SetEntryList(fEventList);\n }\n\n Long64_t rv = fSet->Draw(varexp, selection, option, nentries, firstentry);\n return rv;\n}\n\n\/\/______________________________________________________________________________\nLong64_t TProofChain::Draw(const char *varexp, const char *selection,\n Option_t *option,Long64_t nentries, Long64_t firstentry)\n{\n \/\/ Forwards the execution to the TDSet.\n \/\/ Returns -1 in case of error or number of selected events in case of success.\n \/\/ See TDSet::Browse().\n\n if (!gProof) {\n Error(\"Draw\", \"no active PROOF session\");\n return -1;\n }\n ConnectProof();\n\n if (fDrawFeedback)\n gProof->SetDrawFeedbackOption(fDrawFeedback, option);\n fReadEntry = firstentry;\n\n \/\/ Set either the entry-list (priority) or the event-list\n if (fEntryList) {\n fSet->SetEntryList(fEntryList);\n } else if (fEventList) {\n fSet->SetEntryList(fEventList);\n }\n\n Long64_t rv = fSet->Draw(varexp, selection, option, nentries, firstentry);\n return rv;\n}\n\n\/\/______________________________________________________________________________\nTBranch *TProofChain::FindBranch(const char* branchname)\n{\n \/\/ Forwards the execution to the dummy tree header.\n \/\/ See TTree::FindBranch().\n\n return (fTree ? fTree->FindBranch(branchname) : (TBranch *)0);\n}\n\n\/\/______________________________________________________________________________\nTLeaf *TProofChain::FindLeaf(const char* searchname)\n{\n \/\/ Forwards the execution to the dummy tree header.\n \/\/ See TTree::FindLeaf().\n\n return (fTree ? fTree->FindLeaf(searchname) : (TLeaf *)0);\n}\n\n\/\/______________________________________________________________________________\nTBranch *TProofChain::GetBranch(const char *name)\n{\n \/\/ Forwards the execution to the dummy tree header.\n \/\/ See TTree::GetBranch().\n\n return (fTree ? fTree->GetBranch(name) : (TBranch *)0);\n}\n\n\/\/______________________________________________________________________________\nBool_t TProofChain::GetBranchStatus(const char *branchname) const\n{\n \/\/ Forwards the execution to the dummy tree header.\n \/\/ See TTree::GetBranchStatus().\n\n return (fTree ? fTree->GetBranchStatus(branchname) : kFALSE);\n}\n\n\/\/______________________________________________________________________________\nTVirtualTreePlayer *TProofChain::GetPlayer()\n{\n \/\/ Forwards the execution to the dummy tree header.\n \/\/ See TTree::GetPlayer().\n\n if (!fTree)\n if (gProof) {\n fTree = gProof->GetTreeHeader(fSet);\n ConnectProof();\n }\n\n return (fTree ? fTree->GetPlayer() : (TVirtualTreePlayer *)0);\n}\n\n\/\/______________________________________________________________________________\nLong64_t TProofChain::Process(const char *filename, Option_t *option,\n Long64_t nentries, Long64_t firstentry)\n{\n \/\/ Forwards the execution to the TDSet.\n \/\/ The return value is -1 in case of error and TSelector::GetStatus() in\n \/\/ in case of success.\n \/\/ See TDSet::Process().\n\n \/\/ Set either the entry-list (priority) or the event-list\n if (fEntryList) {\n fSet->SetEntryList(fEntryList);\n } else if (fEventList) {\n fSet->SetEntryList(fEventList);\n }\n\n return fSet->Process(filename, option, nentries, firstentry);\n}\n\n\/\/______________________________________________________________________________\nLong64_t TProofChain::Process(TSelector *selector, Option_t *option,\n Long64_t nentries, Long64_t firstentry)\n{\n \/\/ Not implemented in TProofChain. Shouldn't be used.\n \/\/ The return value is -1 in case of error and TSelector::GetStatus() in\n \/\/ in case of success.\n\n if (selector || option || nentries || firstentry) { }\n \/\/ return fSet->Process(selector, option, nentries, firstentry);\n Warning(\"Process\", \"not implemented\"); \/\/ TODO\n return -1;\n}\n\n\/\/______________________________________________________________________________\nvoid TProofChain::SetDebug(Int_t level, Long64_t min, Long64_t max)\n{\n \/\/ See TTree::SetDebug\n\n TTree::SetDebug(level, min, max);\n}\n\n\/\/______________________________________________________________________________\nvoid TProofChain::SetName(const char *name)\n{\n \/\/ See TTree::GetName.\n\n TTree::SetName(name);\n}\n\n\/\/______________________________________________________________________________\nLong64_t TProofChain::GetEntries() const\n{\n \/\/ Returns the total number of entries in the TProofChain, which is\n \/\/ the number of entries in the TDSet that it holds.\n\n \/\/ this was used for holding the total number of entries\n return (fTree ? fTree->GetMaxEntryLoop() : (Long64_t)(-1));\n}\n\n\/\/______________________________________________________________________________\nLong64_t TProofChain::GetEntries(const char *)\n{\n \/\/ See TTree::GetEntries(const char *selection)\n \/\/ Not implemented in TProofChain. Shouldn't be used.\n\n return Long64_t(-1);\n}\n\n\/\/______________________________________________________________________________\nvoid TProofChain::Progress(Long64_t total, Long64_t processed)\n{\n \/\/ Changes the number of processed entries.\n\n if (gROOT->IsInterrupted() && gProof)\n gProof->StopProcess(kTRUE);\n if (total) { }\n\n fReadEntry = processed;\n}\n\n\/\/______________________________________________________________________________\nLong64_t TProofChain::GetReadEntry() const\n{\n \/\/ Returns the number of processed entries.\n\n return fReadEntry;\n}\n\n\/\/______________________________________________________________________________\nvoid TProofChain::ReleaseProof()\n{\n \/\/ Releases PROOF. Disconnect the \"progress\" signal.\n\n if (!gProof)\n return;\n gProof->Disconnect(\"Progress(Long64_t,Long64_t)\",\n this, \"Progress(Long64_t,Long64_t)\");\n if (fDrawFeedback)\n gProof->DeleteDrawFeedback(fDrawFeedback);\n fDrawFeedback = 0;\n}\n\n\/\/______________________________________________________________________________\nvoid TProofChain::ConnectProof()\n{\n \/\/ Connects the proof - creates a \"DrawFeedback\" and connects the\n \/\/ \"Progress\" signal.\n\n if (gProof && !fDrawFeedback) {\n fDrawFeedback = gProof->CreateDrawFeedback();\n\n gProof->Connect(\"Progress(Long64_t,Long64_t)\", \"TProofChain\",\n this, \"Progress(Long64_t,Long64_t)\");\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2013-2014 Sandstorm Development Group, Inc. and contributors\n\/\/ Licensed under the MIT License:\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n\/\/ THE SOFTWARE.\n\n#include \"module-loader.h\"\n#include \"lexer.h\"\n#include \"parser.h\"\n#include <kj\/vector.h>\n#include <kj\/mutex.h>\n#include <kj\/debug.h>\n#include <kj\/io.h>\n#include <capnp\/message.h>\n#include <map>\n\nnamespace capnp {\nnamespace compiler {\n\nclass ModuleLoader::Impl {\npublic:\n Impl(GlobalErrorReporter& errorReporter)\n : errorReporter(errorReporter) {}\n\n void addImportPath(kj::ReadableDirectory& dir) {\n searchPath.add(&dir);\n }\n\n kj::Maybe<Module&> loadModule(kj::ReadableDirectory& dir, kj::PathPtr path);\n kj::Maybe<Module&> loadModuleFromSearchPath(kj::PathPtr path);\n kj::Maybe<kj::Array<const byte>> readEmbed(kj::ReadableDirectory& dir, kj::PathPtr path);\n kj::Maybe<kj::Array<const byte>> readEmbedFromSearchPath(kj::PathPtr path);\n GlobalErrorReporter& getErrorReporter() { return errorReporter; }\n\nprivate:\n GlobalErrorReporter& errorReporter;\n kj::Vector<kj::ReadableDirectory*> searchPath;\n std::map<std::pair<kj::ReadableDirectory*, kj::PathPtr>, kj::Own<Module>> modules;\n};\n\nclass ModuleLoader::ModuleImpl final: public Module {\npublic:\n ModuleImpl(ModuleLoader::Impl& loader, kj::Own<kj::ReadableFile> file,\n kj::ReadableDirectory& sourceDir, kj::PathPtr path)\n : loader(loader), file(kj::mv(file)), sourceDir(sourceDir), path(path.clone()),\n sourceNameStr(path.toString()) {\n KJ_REQUIRE(path.size() > 0);\n }\n\n kj::PathPtr getPath() {\n return path;\n }\n\n kj::StringPtr getSourceName() override {\n return sourceNameStr;\n }\n\n Orphan<ParsedFile> loadContent(Orphanage orphanage) override {\n kj::Array<const char> content = file->mmap(0, file->stat().size).releaseAsChars();\n\n lineBreaks = nullptr; \/\/ In case loadContent() is called multiple times.\n lineBreaks = lineBreaksSpace.construct(content);\n\n MallocMessageBuilder lexedBuilder;\n auto statements = lexedBuilder.initRoot<LexedStatements>();\n lex(content, statements, *this);\n\n auto parsed = orphanage.newOrphan<ParsedFile>();\n parseFile(statements.getStatements(), parsed.get(), *this);\n return parsed;\n }\n\n kj::Maybe<Module&> importRelative(kj::StringPtr importPath) override {\n if (importPath.size() > 0 && importPath[0] == '\/') {\n return loader.loadModuleFromSearchPath(kj::Path::parse(importPath.slice(1)));\n } else {\n return loader.loadModule(sourceDir, path.parent().eval(importPath));\n }\n }\n\n kj::Maybe<kj::Array<const byte>> embedRelative(kj::StringPtr embedPath) override {\n if (embedPath.size() > 0 && embedPath[0] == '\/') {\n return loader.readEmbedFromSearchPath(kj::Path::parse(embedPath.slice(1)));\n } else {\n return loader.readEmbed(sourceDir, path.parent().eval(embedPath));\n }\n }\n\n void addError(uint32_t startByte, uint32_t endByte, kj::StringPtr message) override {\n auto& lines = *KJ_REQUIRE_NONNULL(lineBreaks,\n \"Can't report errors until loadContent() is called.\");\n\n loader.getErrorReporter().addError(sourceDir, path,\n lines.toSourcePos(startByte), lines.toSourcePos(endByte), message);\n }\n\n bool hadErrors() override {\n return loader.getErrorReporter().hadErrors();\n }\n\nprivate:\n ModuleLoader::Impl& loader;\n kj::Own<kj::ReadableFile> file;\n kj::ReadableDirectory& sourceDir;\n kj::Path path;\n kj::String sourceNameStr;\n\n kj::SpaceFor<LineBreakTable> lineBreaksSpace;\n kj::Maybe<kj::Own<LineBreakTable>> lineBreaks;\n};\n\n\/\/ =======================================================================================\n\nkj::Maybe<Module&> ModuleLoader::Impl::loadModule(\n kj::ReadableDirectory& dir, kj::PathPtr path) {\n auto iter = modules.find(std::make_pair(&dir, path));\n if (iter != modules.end()) {\n \/\/ Return existing file.\n return *iter->second;\n }\n\n KJ_IF_MAYBE(file, dir.tryOpenFile(path)) {\n auto module = kj::heap<ModuleImpl>(*this, kj::mv(*file), dir, path);\n auto& result = *module;\n modules.insert(std::make_pair(std::make_pair(&dir, result.getPath()), kj::mv(module)));\n return result;\n } else {\n \/\/ No such file.\n return nullptr;\n }\n}\n\nkj::Maybe<Module&> ModuleLoader::Impl::loadModuleFromSearchPath(kj::PathPtr path) {\n for (auto candidate: searchPath) {\n KJ_IF_MAYBE(module, loadModule(*candidate, path)) {\n return *module;\n }\n }\n return nullptr;\n}\n\nkj::Maybe<kj::Array<const byte>> ModuleLoader::Impl::readEmbed(\n kj::ReadableDirectory& dir, kj::PathPtr path) {\n KJ_IF_MAYBE(file, dir.tryOpenFile(path)) {\n return file->get()->mmap(0, file->get()->stat().size);\n }\n return nullptr;\n}\n\nkj::Maybe<kj::Array<const byte>> ModuleLoader::Impl::readEmbedFromSearchPath(kj::PathPtr path) {\n for (auto candidate: searchPath) {\n KJ_IF_MAYBE(module, readEmbed(*candidate, path)) {\n return kj::mv(*module);\n }\n }\n return nullptr;\n}\n\n\/\/ =======================================================================================\n\nModuleLoader::ModuleLoader(GlobalErrorReporter& errorReporter)\n : impl(kj::heap<Impl>(errorReporter)) {}\nModuleLoader::~ModuleLoader() noexcept(false) {}\n\nvoid ModuleLoader::addImportPath(kj::ReadableDirectory& dir) {\n impl->addImportPath(dir);\n}\n\nkj::Maybe<Module&> ModuleLoader::loadModule(kj::ReadableDirectory& dir, kj::PathPtr path) {\n return impl->loadModule(dir, path);\n}\n\n} \/\/ namespace compiler\n} \/\/ namespace capnp\n<commit_msg>Fix cmake: Use heuristics to detect when the same file is mapped in multiple locations.<commit_after>\/\/ Copyright (c) 2013-2014 Sandstorm Development Group, Inc. and contributors\n\/\/ Licensed under the MIT License:\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n\/\/ THE SOFTWARE.\n\n#include \"module-loader.h\"\n#include \"lexer.h\"\n#include \"parser.h\"\n#include <kj\/vector.h>\n#include <kj\/mutex.h>\n#include <kj\/debug.h>\n#include <kj\/io.h>\n#include <capnp\/message.h>\n#include <unordered_map>\n\nnamespace capnp {\nnamespace compiler {\n\nnamespace {\n\nstruct FileKey {\n \/\/ Key type for the modules map. We need to implement some complicated heuristics to detect when\n \/\/ two files are actually the same underlying file on disk, in order to handle the case where\n \/\/ people have mapped the same file into multiple locations in the import tree, whether by\n \/\/ passing overlapping import paths, weird symlinks, or whatever.\n \/\/\n \/\/ This is probably over-engineered.\n\n kj::ReadableDirectory& baseDir;\n kj::PathPtr path;\n kj::ReadableFile* file; \/\/ should be Maybe<ReadableFile&> but annoying const-copy issues come up.\n uint64_t hashCode;\n uint64_t size;\n kj::Date lastModified;\n\n FileKey(kj::ReadableDirectory& baseDir, kj::PathPtr path)\n : baseDir(baseDir), path(path), file(nullptr),\n hashCode(0), size(0), lastModified(kj::UNIX_EPOCH) {}\n FileKey(kj::ReadableDirectory& baseDir, kj::PathPtr path, kj::ReadableFile& file)\n : FileKey(baseDir, path, file, file.stat()) {}\n\n FileKey(kj::ReadableDirectory& baseDir, kj::PathPtr path, kj::ReadableFile& file,\n kj::FsNode::Metadata meta)\n : baseDir(baseDir), path(path), file(&file),\n hashCode(meta.hashCode), size(meta.size), lastModified(meta.lastModified) {}\n\n bool operator==(const FileKey& other) const {\n \/\/ Allow matching on baseDir and path without a file.\n if (&baseDir == &other.baseDir && path == other.path) return true;\n if (file == nullptr || other.file == nullptr) return false;\n\n \/\/ Try comparing various file metadata to rule out obvious differences.\n if (hashCode != other.hashCode) return false;\n if (size != other.size || lastModified != other.lastModified) return false;\n if (path.size() > 0 && other.path.size() > 0 &&\n path[path.size() - 1] != other.path[other.path.size() - 1]) {\n \/\/ Names differ, so probably not the same file.\n return false;\n }\n\n \/\/ Same file hash, but different paths, but same size and modification date. This could be a\n \/\/ case of two different import paths overlapping and containing the same file. We'll need to\n \/\/ check the content.\n auto mapping1 = file->mmap(0, size);\n auto mapping2 = other.file->mmap(0, size);\n if (memcmp(mapping1.begin(), mapping2.begin(), size) != 0) return false;\n\n if (path == other.path) {\n \/\/ Exactly the same content was mapped at exactly the same path relative to two different\n \/\/ import directories. This can only really happen if this was one of the files passed on\n \/\/ the command line, but its --src-prefix is not also an import path, but some other\n \/\/ directory containing the same file was given as an import path. Whatever, we'll ignore\n \/\/ this.\n return true;\n }\n\n \/\/ Exactly the same content!\n static bool warned = false;\n if (!warned) {\n KJ_LOG(WARNING,\n \"Found exactly the same source file mapped at two different paths. This suggests \"\n \"that your -I and --src-prefix flags are overlapping or inconsistent. Remember, these \"\n \"flags should only specify directories that are logical 'roots' of the source tree. \"\n \"It should never be the case that one of the import directories contains another one of \"\n \"them.\",\n path, other.path);\n warned = true;\n }\n\n return true;\n }\n};\n\nstruct FileKeyHash {\n size_t operator()(const FileKey& key) const {\n if (sizeof(size_t) < sizeof(key.hashCode)) {\n \/\/ 32-bit system, do more mixing\n return (key.hashCode >> 32) * 31 + static_cast<size_t>(key.hashCode) +\n key.size * 103 + (key.lastModified - kj::UNIX_EPOCH) \/ kj::MILLISECONDS * 73;\n } else {\n return key.hashCode + key.size * 103 +\n (key.lastModified - kj::UNIX_EPOCH) \/ kj::NANOSECONDS * 73;\n }\n }\n};\n\n};\n\nclass ModuleLoader::Impl {\npublic:\n Impl(GlobalErrorReporter& errorReporter)\n : errorReporter(errorReporter) {}\n\n void addImportPath(kj::ReadableDirectory& dir) {\n searchPath.add(&dir);\n }\n\n kj::Maybe<Module&> loadModule(kj::ReadableDirectory& dir, kj::PathPtr path);\n kj::Maybe<Module&> loadModuleFromSearchPath(kj::PathPtr path);\n kj::Maybe<kj::Array<const byte>> readEmbed(kj::ReadableDirectory& dir, kj::PathPtr path);\n kj::Maybe<kj::Array<const byte>> readEmbedFromSearchPath(kj::PathPtr path);\n GlobalErrorReporter& getErrorReporter() { return errorReporter; }\n\nprivate:\n GlobalErrorReporter& errorReporter;\n kj::Vector<kj::ReadableDirectory*> searchPath;\n std::unordered_map<FileKey, kj::Own<Module>, FileKeyHash> modules;\n};\n\nclass ModuleLoader::ModuleImpl final: public Module {\npublic:\n ModuleImpl(ModuleLoader::Impl& loader, kj::Own<kj::ReadableFile> file,\n kj::ReadableDirectory& sourceDir, kj::Path pathParam)\n : loader(loader), file(kj::mv(file)), sourceDir(sourceDir), path(kj::mv(pathParam)),\n sourceNameStr(path.toString()) {\n KJ_REQUIRE(path.size() > 0);\n }\n\n kj::PathPtr getPath() {\n return path;\n }\n\n kj::StringPtr getSourceName() override {\n return sourceNameStr;\n }\n\n Orphan<ParsedFile> loadContent(Orphanage orphanage) override {\n kj::Array<const char> content = file->mmap(0, file->stat().size).releaseAsChars();\n\n lineBreaks = nullptr; \/\/ In case loadContent() is called multiple times.\n lineBreaks = lineBreaksSpace.construct(content);\n\n MallocMessageBuilder lexedBuilder;\n auto statements = lexedBuilder.initRoot<LexedStatements>();\n lex(content, statements, *this);\n\n auto parsed = orphanage.newOrphan<ParsedFile>();\n parseFile(statements.getStatements(), parsed.get(), *this);\n return parsed;\n }\n\n kj::Maybe<Module&> importRelative(kj::StringPtr importPath) override {\n if (importPath.size() > 0 && importPath[0] == '\/') {\n return loader.loadModuleFromSearchPath(kj::Path::parse(importPath.slice(1)));\n } else {\n return loader.loadModule(sourceDir, path.parent().eval(importPath));\n }\n }\n\n kj::Maybe<kj::Array<const byte>> embedRelative(kj::StringPtr embedPath) override {\n if (embedPath.size() > 0 && embedPath[0] == '\/') {\n return loader.readEmbedFromSearchPath(kj::Path::parse(embedPath.slice(1)));\n } else {\n return loader.readEmbed(sourceDir, path.parent().eval(embedPath));\n }\n }\n\n void addError(uint32_t startByte, uint32_t endByte, kj::StringPtr message) override {\n auto& lines = *KJ_REQUIRE_NONNULL(lineBreaks,\n \"Can't report errors until loadContent() is called.\");\n\n loader.getErrorReporter().addError(sourceDir, path,\n lines.toSourcePos(startByte), lines.toSourcePos(endByte), message);\n }\n\n bool hadErrors() override {\n return loader.getErrorReporter().hadErrors();\n }\n\nprivate:\n ModuleLoader::Impl& loader;\n kj::Own<kj::ReadableFile> file;\n kj::ReadableDirectory& sourceDir;\n kj::Path path;\n kj::String sourceNameStr;\n\n kj::SpaceFor<LineBreakTable> lineBreaksSpace;\n kj::Maybe<kj::Own<LineBreakTable>> lineBreaks;\n};\n\n\/\/ =======================================================================================\n\nkj::Maybe<Module&> ModuleLoader::Impl::loadModule(\n kj::ReadableDirectory& dir, kj::PathPtr path) {\n auto iter = modules.find(FileKey(dir, path));\n if (iter != modules.end()) {\n \/\/ Return existing file.\n return *iter->second;\n }\n\n KJ_IF_MAYBE(file, dir.tryOpenFile(path)) {\n auto pathCopy = path.clone();\n auto key = FileKey(dir, pathCopy, **file);\n auto module = kj::heap<ModuleImpl>(*this, kj::mv(*file), dir, kj::mv(pathCopy));\n auto& result = *module;\n auto insertResult = modules.insert(std::make_pair(key, kj::mv(module)));\n if (insertResult.second) {\n return result;\n } else {\n \/\/ Now that we have the file open, we noticed a collision. Return the old file.\n return *insertResult.first->second;\n }\n } else {\n \/\/ No such file.\n return nullptr;\n }\n}\n\nkj::Maybe<Module&> ModuleLoader::Impl::loadModuleFromSearchPath(kj::PathPtr path) {\n for (auto candidate: searchPath) {\n KJ_IF_MAYBE(module, loadModule(*candidate, path)) {\n return *module;\n }\n }\n return nullptr;\n}\n\nkj::Maybe<kj::Array<const byte>> ModuleLoader::Impl::readEmbed(\n kj::ReadableDirectory& dir, kj::PathPtr path) {\n KJ_IF_MAYBE(file, dir.tryOpenFile(path)) {\n return file->get()->mmap(0, file->get()->stat().size);\n }\n return nullptr;\n}\n\nkj::Maybe<kj::Array<const byte>> ModuleLoader::Impl::readEmbedFromSearchPath(kj::PathPtr path) {\n for (auto candidate: searchPath) {\n KJ_IF_MAYBE(module, readEmbed(*candidate, path)) {\n return kj::mv(*module);\n }\n }\n return nullptr;\n}\n\n\/\/ =======================================================================================\n\nModuleLoader::ModuleLoader(GlobalErrorReporter& errorReporter)\n : impl(kj::heap<Impl>(errorReporter)) {}\nModuleLoader::~ModuleLoader() noexcept(false) {}\n\nvoid ModuleLoader::addImportPath(kj::ReadableDirectory& dir) {\n impl->addImportPath(dir);\n}\n\nkj::Maybe<Module&> ModuleLoader::loadModule(kj::ReadableDirectory& dir, kj::PathPtr path) {\n return impl->loadModule(dir, path);\n}\n\n} \/\/ namespace compiler\n} \/\/ namespace capnp\n<|endoftext|>"} {"text":"<commit_before><commit_msg>coverity#737139 Uncaught exception<commit_after><|endoftext|>"} {"text":"<commit_before>#include <Nazara\/Utility.hpp>\n#include <Nazara\/Renderer.hpp>\n#include <Nazara\/Shader.hpp>\n#include <Nazara\/Shader\/SpirvConstantCache.hpp>\n#include <Nazara\/Shader\/SpirvPrinter.hpp>\n#include <array>\n#include <iostream>\n\nint main()\n{\n\tNz::Initializer<Nz::Renderer> loader;\n\tif (!loader)\n\t{\n\t\tstd::cout << \"Failed to initialize Vulkan\" << std::endl;\n\t\treturn __LINE__;\n\t}\n\n\tNz::RenderWindow window;\n\n\tNz::MeshParams meshParams;\n\tmeshParams.matrix = Nz::Matrix4f::Rotate(Nz::EulerAnglesf(0.f, 90.f, 180.f)) * Nz::Matrix4f::Scale(Nz::Vector3f(0.002f));\n\tmeshParams.vertexDeclaration = Nz::VertexDeclaration::Get(Nz::VertexLayout_XYZ_Normal_UV);\n\n\tNz::String windowTitle = \"Vulkan Test\";\n\tif (!window.Create(Nz::VideoMode(800, 600, 32), windowTitle))\n\t{\n\t\tstd::cout << \"Failed to create Window\" << std::endl;\n\t\treturn __LINE__;\n\t}\n\n\tstd::shared_ptr<Nz::RenderDevice> device = window.GetRenderDevice();\n\n\tauto fragmentShader = device->InstantiateShaderStage(Nz::ShaderStageType::Fragment, Nz::ShaderLanguage::NazaraBinary, \"frag.shader\");\n\tif (!fragmentShader)\n\t{\n\t\tstd::cout << \"Failed to instantiate fragment shader\" << std::endl;\n\t\treturn __LINE__;\n\t}\n\n\tauto vertexShader = device->InstantiateShaderStage(Nz::ShaderStageType::Vertex, Nz::ShaderLanguage::NazaraBinary, \"vert.shader\");\n\tif (!vertexShader)\n\t{\n\t\tstd::cout << \"Failed to instantiate fragment shader\" << std::endl;\n\t\treturn __LINE__;\n\t}\n\n\tNz::MeshRef drfreak = Nz::Mesh::LoadFromFile(\"resources\/Spaceship\/spaceship.obj\", meshParams);\n\n\tif (!drfreak)\n\t{\n\t\tNazaraError(\"Failed to load model\");\n\t\treturn __LINE__;\n\t}\n\n\tNz::StaticMesh* drfreakMesh = static_cast<Nz::StaticMesh*>(drfreak->GetSubMesh(0));\n\n\tconst Nz::VertexBuffer* drfreakVB = drfreakMesh->GetVertexBuffer();\n\tconst Nz::IndexBuffer* drfreakIB = drfreakMesh->GetIndexBuffer();\n\n\t\/\/ Index buffer\n\tstd::cout << \"Index count: \" << drfreakIB->GetIndexCount() << std::endl;\n\n\t\/\/ Vertex buffer\n\tstd::cout << \"Vertex count: \" << drfreakVB->GetVertexCount() << std::endl;\n\n\t\/\/ Texture\n\tNz::ImageRef drfreakImage = Nz::Image::LoadFromFile(\"resources\/Spaceship\/Texture\/diffuse.png\");\n\tif (!drfreakImage || !drfreakImage->Convert(Nz::PixelFormat_RGBA8))\n\t{\n\t\tNazaraError(\"Failed to load image\");\n\t\treturn __LINE__;\n\t}\n\n\tNz::TextureInfo texParams;\n\ttexParams.pixelFormat = drfreakImage->GetFormat();\n\ttexParams.type = drfreakImage->GetType();\n\ttexParams.width = drfreakImage->GetWidth();\n\ttexParams.height = drfreakImage->GetHeight();\n\ttexParams.depth = drfreakImage->GetDepth();\n\n\tstd::unique_ptr<Nz::Texture> texture = device->InstantiateTexture(texParams);\n\tif (!texture->Update(drfreakImage->GetConstPixels()))\n\t{\n\t\tNazaraError(\"Failed to update texture\");\n\t\treturn __LINE__;\n\t}\n\n\tstd::unique_ptr<Nz::TextureSampler> textureSampler = device->InstantiateTextureSampler({});\n\n\tstruct\n\t{\n\t\tNz::Matrix4f projectionMatrix;\n\t\tNz::Matrix4f modelMatrix;\n\t\tNz::Matrix4f viewMatrix;\n\t}\n\tubo;\n\n\tNz::Vector2ui windowSize = window.GetSize();\n\tubo.projectionMatrix = Nz::Matrix4f::Perspective(70.f, float(windowSize.x) \/ windowSize.y, 0.1f, 1000.f);\n\tubo.viewMatrix = Nz::Matrix4f::Translate(Nz::Vector3f::Backward() * 1);\n\tubo.modelMatrix = Nz::Matrix4f::Translate(Nz::Vector3f::Forward() * 2 + Nz::Vector3f::Right());\n\n\tNz::UInt32 uniformSize = sizeof(ubo);\n\n\tNz::RenderPipelineLayoutInfo pipelineLayoutInfo;\n\tauto& uboBinding = pipelineLayoutInfo.bindings.emplace_back();\n\tuboBinding.index = 0;\n\tuboBinding.shaderStageFlags = Nz::ShaderStageType::Vertex;\n\tuboBinding.type = Nz::ShaderBindingType::UniformBuffer;\n\n\tauto& textureBinding = pipelineLayoutInfo.bindings.emplace_back();\n\ttextureBinding.index = 1;\n\ttextureBinding.shaderStageFlags = Nz::ShaderStageType::Fragment;\n\ttextureBinding.type = Nz::ShaderBindingType::Texture;\n\n\tstd::shared_ptr<Nz::RenderPipelineLayout> renderPipelineLayout = device->InstantiateRenderPipelineLayout(std::move(pipelineLayoutInfo));\n\n\tNz::ShaderBindingPtr shaderBinding = renderPipelineLayout->AllocateShaderBinding();\n\n\tstd::unique_ptr<Nz::AbstractBuffer> uniformBuffer = device->InstantiateBuffer(Nz::BufferType_Uniform);\n\tif (!uniformBuffer->Initialize(uniformSize, Nz::BufferUsage_DeviceLocal))\n\t{\n\t\tNazaraError(\"Failed to create uniform buffer\");\n\t\treturn __LINE__;\n\t}\n\n\tshaderBinding->Update({\n\t\t{\n\t\t\t0,\n\t\t\tNz::ShaderBinding::UniformBufferBinding {\n\t\t\t\tuniformBuffer.get(), 0, uniformSize\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\t1,\n\t\t\tNz::ShaderBinding::TextureBinding {\n\t\t\t\ttexture.get(), textureSampler.get()\n\t\t\t}\n\t\t}\n\t});\n\n\tNz::RenderPipelineInfo pipelineInfo;\n\tpipelineInfo.pipelineLayout = renderPipelineLayout;\n\n\tpipelineInfo.depthBuffer = true;\n\tpipelineInfo.shaderStages.emplace_back(fragmentShader);\n\tpipelineInfo.shaderStages.emplace_back(vertexShader);\n\n\tauto& vertexBuffer = pipelineInfo.vertexBuffers.emplace_back();\n\tvertexBuffer.binding = 0;\n\tvertexBuffer.declaration = drfreakVB->GetVertexDeclaration();\n\n\tstd::unique_ptr<Nz::RenderPipeline> pipeline = device->InstantiateRenderPipeline(pipelineInfo);\n\n\tNz::RenderDevice* renderDevice = window.GetRenderDevice().get();\n\n\tNz::RenderWindowImpl* windowImpl = window.GetImpl();\n\tstd::unique_ptr<Nz::CommandPool> commandPool = windowImpl->CreateCommandPool(Nz::QueueType::Graphics);\n\n\tNz::RenderBuffer* renderBufferIB = static_cast<Nz::RenderBuffer*>(drfreakIB->GetBuffer()->GetImpl());\n\tNz::RenderBuffer* renderBufferVB = static_cast<Nz::RenderBuffer*>(drfreakVB->GetBuffer()->GetImpl());\n\n\tif (!renderBufferIB->Synchronize(renderDevice))\n\t{\n\t\tNazaraError(\"Failed to synchronize render buffer\");\n\t\treturn __LINE__;\n\t}\n\n\tif (!renderBufferVB->Synchronize(renderDevice))\n\t{\n\t\tNazaraError(\"Failed to synchronize render buffer\");\n\t\treturn __LINE__;\n\t}\n\n\tNz::AbstractBuffer* indexBufferImpl = renderBufferIB->GetHardwareBuffer(renderDevice);\n\tNz::AbstractBuffer* vertexBufferImpl = renderBufferVB->GetHardwareBuffer(renderDevice);\n\n\tNz::CommandBufferPtr drawCommandBuffer;\n\tauto RebuildCommandBuffer = [&]\n\t{\n\t\tNz::Vector2ui windowSize = window.GetSize();\n\n\t\tdrawCommandBuffer = commandPool->BuildCommandBuffer([&](Nz::CommandBufferBuilder& builder)\n\t\t{\n\t\t\tNz::Recti renderRect(0, 0, window.GetSize().x, window.GetSize().y);\n\n\t\t\tNz::CommandBufferBuilder::ClearValues clearValues[2];\n\t\t\tclearValues[0].color = Nz::Color::Black;\n\t\t\tclearValues[1].depth = 1.f;\n\t\t\tclearValues[1].stencil = 0;\n\n\t\t\tbuilder.BeginDebugRegion(\"Main window rendering\", Nz::Color::Green);\n\t\t\t{\n\t\t\t\tbuilder.BeginRenderPass(windowImpl->GetFramebuffer(), windowImpl->GetRenderPass(), renderRect, { clearValues[0], clearValues[1] });\n\t\t\t\t{\n\t\t\t\t\tbuilder.BindIndexBuffer(indexBufferImpl);\n\t\t\t\t\tbuilder.BindPipeline(*pipeline);\n\t\t\t\t\tbuilder.BindVertexBuffer(0, vertexBufferImpl);\n\t\t\t\t\tbuilder.BindShaderBinding(*shaderBinding);\n\n\t\t\t\t\tbuilder.SetScissor(Nz::Recti{ 0, 0, int(windowSize.x), int(windowSize.y) });\n\t\t\t\t\tbuilder.SetViewport(Nz::Recti{ 0, 0, int(windowSize.x), int(windowSize.y) });\n\n\t\t\t\t\tbuilder.DrawIndexed(drfreakIB->GetIndexCount());\n\t\t\t\t}\n\t\t\t\tbuilder.EndRenderPass();\n\t\t\t}\n\t\t\tbuilder.EndDebugRegion();\n\t\t});\n\t};\n\tRebuildCommandBuffer();\n\n\n\tNz::Vector3f viewerPos = Nz::Vector3f::Zero();\n\n\tNz::EulerAnglesf camAngles(0.f, 0.f, 0.f);\n\tNz::Quaternionf camQuat(camAngles);\n\n\twindow.EnableEventPolling(true);\n\n\tNz::Clock updateClock;\n\tNz::Clock secondClock;\n\tunsigned int fps = 0;\n\tbool uboUpdate = true;\n\n\t\/\/Nz::Mouse::SetRelativeMouseMode(true);\n\n\twhile (window.IsOpen())\n\t{\n\t\tNz::WindowEvent event;\n\t\twhile (window.PollEvent(&event))\n\t\t{\n\t\t\tswitch (event.type)\n\t\t\t{\n\t\t\t\tcase Nz::WindowEventType_Quit:\n\t\t\t\t\twindow.Close();\n\t\t\t\t\tbreak;\n\n\t\t\t\t\/*case Nz::WindowEventType_MouseMoved: \/\/ La souris a bougé\n\t\t\t\t{\n\t\t\t\t\t\/\/ Gestion de la caméra free-fly (Rotation)\n\t\t\t\t\tfloat sensitivity = 0.3f; \/\/ Sensibilité de la souris\n\n\t\t\t\t\t\/\/ On modifie l'angle de la caméra grâce au déplacement relatif sur X de la souris\n\t\t\t\t\tcamAngles.yaw = Nz::NormalizeAngle(camAngles.yaw - event.mouseMove.deltaX*sensitivity);\n\n\t\t\t\t\t\/\/ Idem, mais pour éviter les problèmes de calcul de la matrice de vue, on restreint les angles\n\t\t\t\t\tcamAngles.pitch = Nz::Clamp(camAngles.pitch + event.mouseMove.deltaY*sensitivity, -89.f, 89.f);\n\n\t\t\t\t\tcamQuat = camAngles;\n\t\t\t\t\t\n\t\t\t\t\tuboUpdate = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}*\/\n\n\t\t\t\tcase Nz::WindowEventType_Resized:\n\t\t\t\t{\n\t\t\t\t\tNz::Vector2ui windowSize = window.GetSize();\n\t\t\t\t\tubo.projectionMatrix = Nz::Matrix4f::Perspective(70.f, float(windowSize.x) \/ windowSize.y, 0.1f, 1000.f);\n\t\t\t\t\tuboUpdate = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\tdefault:\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\tif (updateClock.GetMilliseconds() > 1000 \/ 60)\n\t\t{\n\t\t\tfloat cameraSpeed = 2.f * updateClock.GetSeconds();\n\t\t\tupdateClock.Restart();\n\n\t\t\tif (Nz::Keyboard::IsKeyPressed(Nz::Keyboard::VKey::Up) || Nz::Keyboard::IsKeyPressed(Nz::Keyboard::VKey::Z))\n\t\t\t\tviewerPos += camQuat * Nz::Vector3f::Forward() * cameraSpeed;\n\n\t\t\t\/\/ Si la flèche du bas ou la touche S est pressée, on recule\n\t\t\tif (Nz::Keyboard::IsKeyPressed(Nz::Keyboard::VKey::Down) || Nz::Keyboard::IsKeyPressed(Nz::Keyboard::VKey::S))\n\t\t\t\tviewerPos += camQuat * Nz::Vector3f::Backward() * cameraSpeed;\n\n\t\t\t\/\/ Etc...\n\t\t\tif (Nz::Keyboard::IsKeyPressed(Nz::Keyboard::VKey::Left) || Nz::Keyboard::IsKeyPressed(Nz::Keyboard::VKey::Q))\n\t\t\t\tviewerPos += camQuat * Nz::Vector3f::Left() * cameraSpeed;\n\n\t\t\t\/\/ Etc...\n\t\t\tif (Nz::Keyboard::IsKeyPressed(Nz::Keyboard::VKey::Right) || Nz::Keyboard::IsKeyPressed(Nz::Keyboard::VKey::D))\n\t\t\t\tviewerPos += camQuat * Nz::Vector3f::Right() * cameraSpeed;\n\n\t\t\t\/\/ Majuscule pour monter, notez l'utilisation d'une direction globale (Non-affectée par la rotation)\n\t\t\tif (Nz::Keyboard::IsKeyPressed(Nz::Keyboard::VKey::LShift) || Nz::Keyboard::IsKeyPressed(Nz::Keyboard::VKey::RShift))\n\t\t\t\tviewerPos += Nz::Vector3f::Up() * cameraSpeed;\n\n\t\t\t\/\/ Contrôle (Gauche ou droite) pour descendre dans l'espace global, etc...\n\t\t\tif (Nz::Keyboard::IsKeyPressed(Nz::Keyboard::VKey::LControl) || Nz::Keyboard::IsKeyPressed(Nz::Keyboard::VKey::RControl))\n\t\t\t\tviewerPos += Nz::Vector3f::Down() * cameraSpeed;\n\n\t\t\tuboUpdate = true;\n\t\t}\n\n\t\tNz::RenderFrame frame = windowImpl->Acquire();\n\t\tif (!frame)\n\t\t\tcontinue;\n\n\t\tif (frame.IsFramebufferInvalidated())\n\t\t\tRebuildCommandBuffer();\n\n\t\tubo.viewMatrix = Nz::Matrix4f::ViewMatrix(viewerPos, camAngles);\n\n\t\tif (uboUpdate)\n\t\t{\n\t\t\tauto& allocation = frame.GetUploadPool().Allocate(uniformSize);\n\n\t\t\tstd::memcpy(allocation.mappedPtr, &ubo, sizeof(ubo));\n\n\t\t\tframe.Execute([&](Nz::CommandBufferBuilder& builder)\n\t\t\t{\n\t\t\t\tbuilder.BeginDebugRegion(\"UBO Update\", Nz::Color::Yellow);\n\t\t\t\t{\n\t\t\t\t\tbuilder.PreTransferBarrier();\n\t\t\t\t\tbuilder.CopyBuffer(allocation, uniformBuffer.get());\n\t\t\t\t\tbuilder.PostTransferBarrier();\n\t\t\t\t}\n\t\t\t\tbuilder.EndDebugRegion();\n\t\t\t}, Nz::QueueType::Transfer);\n\n\t\t\tuboUpdate = false;\n\t\t}\n\n\t\tframe.SubmitCommandBuffer(drawCommandBuffer.get(), Nz::QueueType::Graphics);\n\n\t\tframe.Present();\n\n\t\twindow.Display();\n\n\t\t\/\/ On incrémente le compteur de FPS improvisé\n\t\tfps++;\n\n\t\tif (secondClock.GetMilliseconds() >= 1000) \/\/ Toutes les secondes\n\t\t{\n\t\t\t\/\/ Et on insère ces données dans le titre de la fenêtre\n\t\t\twindow.SetTitle(windowTitle + \" - \" + Nz::String::Number(fps) + \" FPS\");\n\n\t\t\t\/*\n\t\t\tNote: En C++11 il est possible d'insérer de l'Unicode de façon standard, quel que soit l'encodage du fichier,\n\t\t\tvia quelque chose de similaire à u8\"Cha\\u00CEne de caract\\u00E8res\".\n\t\t\tCependant, si le code source est encodé en UTF-8 (Comme c'est le cas dans ce fichier),\n\t\t\tcela fonctionnera aussi comme ceci : \"Chaîne de caractères\".\n\t\t\t*\/\n\n\t\t\t\/\/ Et on réinitialise le compteur de FPS\n\t\t\tfps = 0;\n\n\t\t\t\/\/ Et on relance l'horloge pour refaire ça dans une seconde\n\t\t\tsecondClock.Restart();\n\t\t}\n\t}\n\n\treturn EXIT_SUCCESS;\n}\n<commit_msg>RenderTest: Make UBO Dynamic<commit_after>#include <Nazara\/Utility.hpp>\n#include <Nazara\/Renderer.hpp>\n#include <Nazara\/Shader.hpp>\n#include <Nazara\/Shader\/SpirvConstantCache.hpp>\n#include <Nazara\/Shader\/SpirvPrinter.hpp>\n#include <array>\n#include <iostream>\n\nint main()\n{\n\tNz::Initializer<Nz::Renderer> loader;\n\tif (!loader)\n\t{\n\t\tstd::cout << \"Failed to initialize Vulkan\" << std::endl;\n\t\treturn __LINE__;\n\t}\n\n\tNz::RenderWindow window;\n\n\tNz::MeshParams meshParams;\n\tmeshParams.matrix = Nz::Matrix4f::Rotate(Nz::EulerAnglesf(0.f, 90.f, 180.f)) * Nz::Matrix4f::Scale(Nz::Vector3f(0.002f));\n\tmeshParams.vertexDeclaration = Nz::VertexDeclaration::Get(Nz::VertexLayout_XYZ_Normal_UV);\n\n\tNz::String windowTitle = \"Vulkan Test\";\n\tif (!window.Create(Nz::VideoMode(800, 600, 32), windowTitle))\n\t{\n\t\tstd::cout << \"Failed to create Window\" << std::endl;\n\t\treturn __LINE__;\n\t}\n\n\tstd::shared_ptr<Nz::RenderDevice> device = window.GetRenderDevice();\n\n\tauto fragmentShader = device->InstantiateShaderStage(Nz::ShaderStageType::Fragment, Nz::ShaderLanguage::NazaraBinary, \"frag.shader\");\n\tif (!fragmentShader)\n\t{\n\t\tstd::cout << \"Failed to instantiate fragment shader\" << std::endl;\n\t\treturn __LINE__;\n\t}\n\n\tauto vertexShader = device->InstantiateShaderStage(Nz::ShaderStageType::Vertex, Nz::ShaderLanguage::NazaraBinary, \"vert.shader\");\n\tif (!vertexShader)\n\t{\n\t\tstd::cout << \"Failed to instantiate fragment shader\" << std::endl;\n\t\treturn __LINE__;\n\t}\n\n\tNz::MeshRef drfreak = Nz::Mesh::LoadFromFile(\"resources\/Spaceship\/spaceship.obj\", meshParams);\n\n\tif (!drfreak)\n\t{\n\t\tNazaraError(\"Failed to load model\");\n\t\treturn __LINE__;\n\t}\n\n\tNz::StaticMesh* drfreakMesh = static_cast<Nz::StaticMesh*>(drfreak->GetSubMesh(0));\n\n\tconst Nz::VertexBuffer* drfreakVB = drfreakMesh->GetVertexBuffer();\n\tconst Nz::IndexBuffer* drfreakIB = drfreakMesh->GetIndexBuffer();\n\n\t\/\/ Index buffer\n\tstd::cout << \"Index count: \" << drfreakIB->GetIndexCount() << std::endl;\n\n\t\/\/ Vertex buffer\n\tstd::cout << \"Vertex count: \" << drfreakVB->GetVertexCount() << std::endl;\n\n\t\/\/ Texture\n\tNz::ImageRef drfreakImage = Nz::Image::LoadFromFile(\"resources\/Spaceship\/Texture\/diffuse.png\");\n\tif (!drfreakImage || !drfreakImage->Convert(Nz::PixelFormat_RGBA8))\n\t{\n\t\tNazaraError(\"Failed to load image\");\n\t\treturn __LINE__;\n\t}\n\n\tNz::TextureInfo texParams;\n\ttexParams.pixelFormat = drfreakImage->GetFormat();\n\ttexParams.type = drfreakImage->GetType();\n\ttexParams.width = drfreakImage->GetWidth();\n\ttexParams.height = drfreakImage->GetHeight();\n\ttexParams.depth = drfreakImage->GetDepth();\n\n\tstd::unique_ptr<Nz::Texture> texture = device->InstantiateTexture(texParams);\n\tif (!texture->Update(drfreakImage->GetConstPixels()))\n\t{\n\t\tNazaraError(\"Failed to update texture\");\n\t\treturn __LINE__;\n\t}\n\n\tstd::unique_ptr<Nz::TextureSampler> textureSampler = device->InstantiateTextureSampler({});\n\n\tstruct\n\t{\n\t\tNz::Matrix4f projectionMatrix;\n\t\tNz::Matrix4f modelMatrix;\n\t\tNz::Matrix4f viewMatrix;\n\t}\n\tubo;\n\n\tNz::Vector2ui windowSize = window.GetSize();\n\tubo.projectionMatrix = Nz::Matrix4f::Perspective(70.f, float(windowSize.x) \/ windowSize.y, 0.1f, 1000.f);\n\tubo.viewMatrix = Nz::Matrix4f::Translate(Nz::Vector3f::Backward() * 1);\n\tubo.modelMatrix = Nz::Matrix4f::Translate(Nz::Vector3f::Forward() * 2 + Nz::Vector3f::Right());\n\n\tNz::UInt32 uniformSize = sizeof(ubo);\n\n\tNz::RenderPipelineLayoutInfo pipelineLayoutInfo;\n\tauto& uboBinding = pipelineLayoutInfo.bindings.emplace_back();\n\tuboBinding.index = 0;\n\tuboBinding.shaderStageFlags = Nz::ShaderStageType::Vertex;\n\tuboBinding.type = Nz::ShaderBindingType::UniformBuffer;\n\n\tauto& textureBinding = pipelineLayoutInfo.bindings.emplace_back();\n\ttextureBinding.index = 1;\n\ttextureBinding.shaderStageFlags = Nz::ShaderStageType::Fragment;\n\ttextureBinding.type = Nz::ShaderBindingType::Texture;\n\n\tstd::shared_ptr<Nz::RenderPipelineLayout> renderPipelineLayout = device->InstantiateRenderPipelineLayout(std::move(pipelineLayoutInfo));\n\n\tNz::ShaderBindingPtr shaderBinding = renderPipelineLayout->AllocateShaderBinding();\n\n\tstd::unique_ptr<Nz::AbstractBuffer> uniformBuffer = device->InstantiateBuffer(Nz::BufferType_Uniform);\n\tif (!uniformBuffer->Initialize(uniformSize, Nz::BufferUsage_DeviceLocal | Nz::BufferUsage_Dynamic))\n\t{\n\t\tNazaraError(\"Failed to create uniform buffer\");\n\t\treturn __LINE__;\n\t}\n\n\tshaderBinding->Update({\n\t\t{\n\t\t\t0,\n\t\t\tNz::ShaderBinding::UniformBufferBinding {\n\t\t\t\tuniformBuffer.get(), 0, uniformSize\n\t\t\t}\n\t\t},\n\t\t{\n\t\t\t1,\n\t\t\tNz::ShaderBinding::TextureBinding {\n\t\t\t\ttexture.get(), textureSampler.get()\n\t\t\t}\n\t\t}\n\t});\n\n\tNz::RenderPipelineInfo pipelineInfo;\n\tpipelineInfo.pipelineLayout = renderPipelineLayout;\n\n\tpipelineInfo.depthBuffer = true;\n\tpipelineInfo.shaderStages.emplace_back(fragmentShader);\n\tpipelineInfo.shaderStages.emplace_back(vertexShader);\n\n\tauto& vertexBuffer = pipelineInfo.vertexBuffers.emplace_back();\n\tvertexBuffer.binding = 0;\n\tvertexBuffer.declaration = drfreakVB->GetVertexDeclaration();\n\n\tstd::unique_ptr<Nz::RenderPipeline> pipeline = device->InstantiateRenderPipeline(pipelineInfo);\n\n\tNz::RenderDevice* renderDevice = window.GetRenderDevice().get();\n\n\tNz::RenderWindowImpl* windowImpl = window.GetImpl();\n\tstd::unique_ptr<Nz::CommandPool> commandPool = windowImpl->CreateCommandPool(Nz::QueueType::Graphics);\n\n\tNz::RenderBuffer* renderBufferIB = static_cast<Nz::RenderBuffer*>(drfreakIB->GetBuffer()->GetImpl());\n\tNz::RenderBuffer* renderBufferVB = static_cast<Nz::RenderBuffer*>(drfreakVB->GetBuffer()->GetImpl());\n\n\tif (!renderBufferIB->Synchronize(renderDevice))\n\t{\n\t\tNazaraError(\"Failed to synchronize render buffer\");\n\t\treturn __LINE__;\n\t}\n\n\tif (!renderBufferVB->Synchronize(renderDevice))\n\t{\n\t\tNazaraError(\"Failed to synchronize render buffer\");\n\t\treturn __LINE__;\n\t}\n\n\tNz::AbstractBuffer* indexBufferImpl = renderBufferIB->GetHardwareBuffer(renderDevice);\n\tNz::AbstractBuffer* vertexBufferImpl = renderBufferVB->GetHardwareBuffer(renderDevice);\n\n\tNz::CommandBufferPtr drawCommandBuffer;\n\tauto RebuildCommandBuffer = [&]\n\t{\n\t\tNz::Vector2ui windowSize = window.GetSize();\n\n\t\tdrawCommandBuffer = commandPool->BuildCommandBuffer([&](Nz::CommandBufferBuilder& builder)\n\t\t{\n\t\t\tNz::Recti renderRect(0, 0, window.GetSize().x, window.GetSize().y);\n\n\t\t\tNz::CommandBufferBuilder::ClearValues clearValues[2];\n\t\t\tclearValues[0].color = Nz::Color::Black;\n\t\t\tclearValues[1].depth = 1.f;\n\t\t\tclearValues[1].stencil = 0;\n\n\t\t\tbuilder.BeginDebugRegion(\"Main window rendering\", Nz::Color::Green);\n\t\t\t{\n\t\t\t\tbuilder.BeginRenderPass(windowImpl->GetFramebuffer(), windowImpl->GetRenderPass(), renderRect, { clearValues[0], clearValues[1] });\n\t\t\t\t{\n\t\t\t\t\tbuilder.BindIndexBuffer(indexBufferImpl);\n\t\t\t\t\tbuilder.BindPipeline(*pipeline);\n\t\t\t\t\tbuilder.BindVertexBuffer(0, vertexBufferImpl);\n\t\t\t\t\tbuilder.BindShaderBinding(*shaderBinding);\n\n\t\t\t\t\tbuilder.SetScissor(Nz::Recti{ 0, 0, int(windowSize.x), int(windowSize.y) });\n\t\t\t\t\tbuilder.SetViewport(Nz::Recti{ 0, 0, int(windowSize.x), int(windowSize.y) });\n\n\t\t\t\t\tbuilder.DrawIndexed(drfreakIB->GetIndexCount());\n\t\t\t\t}\n\t\t\t\tbuilder.EndRenderPass();\n\t\t\t}\n\t\t\tbuilder.EndDebugRegion();\n\t\t});\n\t};\n\tRebuildCommandBuffer();\n\n\n\tNz::Vector3f viewerPos = Nz::Vector3f::Zero();\n\n\tNz::EulerAnglesf camAngles(0.f, 0.f, 0.f);\n\tNz::Quaternionf camQuat(camAngles);\n\n\twindow.EnableEventPolling(true);\n\n\tNz::Clock updateClock;\n\tNz::Clock secondClock;\n\tunsigned int fps = 0;\n\tbool uboUpdate = true;\n\n\t\/\/Nz::Mouse::SetRelativeMouseMode(true);\n\n\twhile (window.IsOpen())\n\t{\n\t\tNz::WindowEvent event;\n\t\twhile (window.PollEvent(&event))\n\t\t{\n\t\t\tswitch (event.type)\n\t\t\t{\n\t\t\t\tcase Nz::WindowEventType_Quit:\n\t\t\t\t\twindow.Close();\n\t\t\t\t\tbreak;\n\n\t\t\t\t\/*case Nz::WindowEventType_MouseMoved: \/\/ La souris a bougé\n\t\t\t\t{\n\t\t\t\t\t\/\/ Gestion de la caméra free-fly (Rotation)\n\t\t\t\t\tfloat sensitivity = 0.3f; \/\/ Sensibilité de la souris\n\n\t\t\t\t\t\/\/ On modifie l'angle de la caméra grâce au déplacement relatif sur X de la souris\n\t\t\t\t\tcamAngles.yaw = Nz::NormalizeAngle(camAngles.yaw - event.mouseMove.deltaX*sensitivity);\n\n\t\t\t\t\t\/\/ Idem, mais pour éviter les problèmes de calcul de la matrice de vue, on restreint les angles\n\t\t\t\t\tcamAngles.pitch = Nz::Clamp(camAngles.pitch + event.mouseMove.deltaY*sensitivity, -89.f, 89.f);\n\n\t\t\t\t\tcamQuat = camAngles;\n\t\t\t\t\t\n\t\t\t\t\tuboUpdate = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}*\/\n\n\t\t\t\tcase Nz::WindowEventType_Resized:\n\t\t\t\t{\n\t\t\t\t\tNz::Vector2ui windowSize = window.GetSize();\n\t\t\t\t\tubo.projectionMatrix = Nz::Matrix4f::Perspective(70.f, float(windowSize.x) \/ windowSize.y, 0.1f, 1000.f);\n\t\t\t\t\tuboUpdate = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\tdefault:\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\tif (updateClock.GetMilliseconds() > 1000 \/ 60)\n\t\t{\n\t\t\tfloat cameraSpeed = 2.f * updateClock.GetSeconds();\n\t\t\tupdateClock.Restart();\n\n\t\t\tif (Nz::Keyboard::IsKeyPressed(Nz::Keyboard::VKey::Up) || Nz::Keyboard::IsKeyPressed(Nz::Keyboard::VKey::Z))\n\t\t\t\tviewerPos += camQuat * Nz::Vector3f::Forward() * cameraSpeed;\n\n\t\t\t\/\/ Si la flèche du bas ou la touche S est pressée, on recule\n\t\t\tif (Nz::Keyboard::IsKeyPressed(Nz::Keyboard::VKey::Down) || Nz::Keyboard::IsKeyPressed(Nz::Keyboard::VKey::S))\n\t\t\t\tviewerPos += camQuat * Nz::Vector3f::Backward() * cameraSpeed;\n\n\t\t\t\/\/ Etc...\n\t\t\tif (Nz::Keyboard::IsKeyPressed(Nz::Keyboard::VKey::Left) || Nz::Keyboard::IsKeyPressed(Nz::Keyboard::VKey::Q))\n\t\t\t\tviewerPos += camQuat * Nz::Vector3f::Left() * cameraSpeed;\n\n\t\t\t\/\/ Etc...\n\t\t\tif (Nz::Keyboard::IsKeyPressed(Nz::Keyboard::VKey::Right) || Nz::Keyboard::IsKeyPressed(Nz::Keyboard::VKey::D))\n\t\t\t\tviewerPos += camQuat * Nz::Vector3f::Right() * cameraSpeed;\n\n\t\t\t\/\/ Majuscule pour monter, notez l'utilisation d'une direction globale (Non-affectée par la rotation)\n\t\t\tif (Nz::Keyboard::IsKeyPressed(Nz::Keyboard::VKey::LShift) || Nz::Keyboard::IsKeyPressed(Nz::Keyboard::VKey::RShift))\n\t\t\t\tviewerPos += Nz::Vector3f::Up() * cameraSpeed;\n\n\t\t\t\/\/ Contrôle (Gauche ou droite) pour descendre dans l'espace global, etc...\n\t\t\tif (Nz::Keyboard::IsKeyPressed(Nz::Keyboard::VKey::LControl) || Nz::Keyboard::IsKeyPressed(Nz::Keyboard::VKey::RControl))\n\t\t\t\tviewerPos += Nz::Vector3f::Down() * cameraSpeed;\n\n\t\t\tuboUpdate = true;\n\t\t}\n\n\t\tNz::RenderFrame frame = windowImpl->Acquire();\n\t\tif (!frame)\n\t\t\tcontinue;\n\n\t\tif (frame.IsFramebufferInvalidated())\n\t\t\tRebuildCommandBuffer();\n\n\t\tubo.viewMatrix = Nz::Matrix4f::ViewMatrix(viewerPos, camAngles);\n\n\t\tif (uboUpdate)\n\t\t{\n\t\t\tauto& allocation = frame.GetUploadPool().Allocate(uniformSize);\n\n\t\t\tstd::memcpy(allocation.mappedPtr, &ubo, sizeof(ubo));\n\n\t\t\tframe.Execute([&](Nz::CommandBufferBuilder& builder)\n\t\t\t{\n\t\t\t\tbuilder.BeginDebugRegion(\"UBO Update\", Nz::Color::Yellow);\n\t\t\t\t{\n\t\t\t\t\tbuilder.PreTransferBarrier();\n\t\t\t\t\tbuilder.CopyBuffer(allocation, uniformBuffer.get());\n\t\t\t\t\tbuilder.PostTransferBarrier();\n\t\t\t\t}\n\t\t\t\tbuilder.EndDebugRegion();\n\t\t\t}, Nz::QueueType::Transfer);\n\n\t\t\tuboUpdate = false;\n\t\t}\n\n\t\tframe.SubmitCommandBuffer(drawCommandBuffer.get(), Nz::QueueType::Graphics);\n\n\t\tframe.Present();\n\n\t\twindow.Display();\n\n\t\t\/\/ On incrémente le compteur de FPS improvisé\n\t\tfps++;\n\n\t\tif (secondClock.GetMilliseconds() >= 1000) \/\/ Toutes les secondes\n\t\t{\n\t\t\t\/\/ Et on insère ces données dans le titre de la fenêtre\n\t\t\twindow.SetTitle(windowTitle + \" - \" + Nz::String::Number(fps) + \" FPS\");\n\n\t\t\t\/*\n\t\t\tNote: En C++11 il est possible d'insérer de l'Unicode de façon standard, quel que soit l'encodage du fichier,\n\t\t\tvia quelque chose de similaire à u8\"Cha\\u00CEne de caract\\u00E8res\".\n\t\t\tCependant, si le code source est encodé en UTF-8 (Comme c'est le cas dans ce fichier),\n\t\t\tcela fonctionnera aussi comme ceci : \"Chaîne de caractères\".\n\t\t\t*\/\n\n\t\t\t\/\/ Et on réinitialise le compteur de FPS\n\t\t\tfps = 0;\n\n\t\t\t\/\/ Et on relance l'horloge pour refaire ça dans une seconde\n\t\t\tsecondClock.Restart();\n\t\t}\n\t}\n\n\treturn EXIT_SUCCESS;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2013 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"ash\/accelerators\/exit_warning_handler.h\"\n\n#include \"ash\/shell.h\"\n#include \"ash\/shell_delegate.h\"\n#include \"ash\/shell_window_ids.h\"\n#include \"base\/strings\/utf_string_conversions.h\"\n#include \"base\/time\/time.h\"\n#include \"base\/timer\/timer.h\"\n#include \"grit\/ash_strings.h\"\n#include \"ui\/aura\/root_window.h\"\n#include \"ui\/base\/accessibility\/accessible_view_state.h\"\n#include \"ui\/base\/l10n\/l10n_util.h\"\n#include \"ui\/base\/resource\/resource_bundle.h\"\n#include \"ui\/gfx\/canvas.h\"\n#include \"ui\/gfx\/font.h\"\n#include \"ui\/views\/controls\/label.h\"\n#include \"ui\/views\/layout\/fill_layout.h\"\n#include \"ui\/views\/view.h\"\n#include \"ui\/views\/widget\/widget.h\"\n#include \"ui\/views\/widget\/widget_delegate.h\"\n\nnamespace ash {\nnamespace {\n\nconst int64 kTimeOutMilliseconds = 2000;\nconst SkColor kForegroundColor = 0xFFFFFFFF;\nconst SkColor kBackgroundColor = 0xE0808080;\nconst int kHorizontalMarginAroundText = 100;\nconst int kVerticalMarginAroundText = 100;\n\nclass ExitWarningLabel : public views::Label {\n public:\n ExitWarningLabel() {}\n\n virtual ~ExitWarningLabel() {}\n\n private:\n virtual void PaintText(gfx::Canvas* canvas,\n const string16& text,\n const gfx::Rect& text_bounds,\n int flags) OVERRIDE {\n \/\/ Turn off subpixel rendering.\n views::Label::PaintText(canvas,\n text,\n text_bounds,\n flags | gfx::Canvas::NO_SUBPIXEL_RENDERING);\n }\n\n DISALLOW_COPY_AND_ASSIGN(ExitWarningLabel);\n};\n\nclass ExitWarningWidgetDelegateView : public views::WidgetDelegateView {\n public:\n ExitWarningWidgetDelegateView() : text_width_(0), width_(0), height_(0) {\n text_ = l10n_util::GetStringUTF16(IDS_ASH_EXIT_WARNING_POPUP_TEXT);\n accessible_name_ =\n l10n_util::GetStringUTF16(IDS_ASH_EXIT_WARNING_POPUP_TEXT_ACCESSIBLE);\n ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance();\n font_ = rb.GetFont(ui::ResourceBundle::LargeFont);\n text_width_ = font_.GetStringWidth(text_);\n width_ = text_width_ + kHorizontalMarginAroundText;\n height_ = font_.GetHeight() + kVerticalMarginAroundText;\n views::Label* label = new ExitWarningLabel;\n label->SetText(text_);\n label->SetHorizontalAlignment(gfx::ALIGN_CENTER);\n label->SetFont(font_);\n label->SetEnabledColor(kForegroundColor);\n label->SetDisabledColor(kForegroundColor);\n label->SetAutoColorReadabilityEnabled(false);\n AddChildView(label);\n SetLayoutManager(new views::FillLayout);\n }\n\n virtual gfx::Size GetPreferredSize() OVERRIDE {\n return gfx::Size(width_, height_);\n }\n\n virtual void OnPaint(gfx::Canvas* canvas) OVERRIDE {\n canvas->FillRect(GetLocalBounds(), kBackgroundColor);\n views::WidgetDelegateView::OnPaint(canvas);\n }\n\n virtual void GetAccessibleState(ui::AccessibleViewState* state) OVERRIDE {\n state->name = accessible_name_;\n state->role = ui::AccessibilityTypes::ROLE_ALERT;\n }\n\n private:\n base::string16 text_;\n base::string16 accessible_name_;\n gfx::Font font_;\n int text_width_;\n int width_;\n int height_;\n\n DISALLOW_COPY_AND_ASSIGN(ExitWarningWidgetDelegateView);\n};\n\n} \/\/ namespace\n\nExitWarningHandler::ExitWarningHandler()\n : state_(IDLE),\n stub_timer_for_test_(false) {\n}\n\nExitWarningHandler::~ExitWarningHandler() {\n \/\/ Note: If a timer is outstanding, it is stopped in its destructor.\n Hide();\n}\n\nvoid ExitWarningHandler::HandleAccelerator() {\n ShellDelegate* shell_delegate = Shell::GetInstance()->delegate();\n switch (state_) {\n case IDLE:\n state_ = WAIT_FOR_DOUBLE_PRESS;\n Show();\n StartTimer();\n shell_delegate->RecordUserMetricsAction(UMA_ACCEL_EXIT_FIRST_Q);\n break;\n case WAIT_FOR_DOUBLE_PRESS:\n state_ = EXITING;\n CancelTimer();\n Hide();\n shell_delegate->RecordUserMetricsAction(UMA_ACCEL_EXIT_SECOND_Q);\n shell_delegate->Exit();\n break;\n case EXITING:\n break;\n default:\n NOTREACHED();\n break;\n }\n}\n\nvoid ExitWarningHandler::TimerAction() {\n Hide();\n if (state_ == WAIT_FOR_DOUBLE_PRESS)\n state_ = IDLE;\n}\n\nvoid ExitWarningHandler::StartTimer() {\n if (stub_timer_for_test_)\n return;\n timer_.Start(FROM_HERE,\n base::TimeDelta::FromMilliseconds(kTimeOutMilliseconds),\n this,\n &ExitWarningHandler::TimerAction);\n}\n\nvoid ExitWarningHandler::CancelTimer() {\n timer_.Stop();\n}\n\nvoid ExitWarningHandler::Show() {\n if (widget_)\n return;\n aura::RootWindow* root_window = Shell::GetActiveRootWindow();\n ExitWarningWidgetDelegateView* delegate = new ExitWarningWidgetDelegateView;\n gfx::Size rs = root_window->bounds().size();\n gfx::Size ps = delegate->GetPreferredSize();\n gfx::Rect bounds((rs.width() - ps.width()) \/ 2,\n (rs.height() - ps.height()) \/ 3,\n ps.width(), ps.height());\n views::Widget::InitParams params;\n params.type = views::Widget::InitParams::TYPE_POPUP;\n params.opacity = views::Widget::InitParams::TRANSLUCENT_WINDOW;\n params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;\n params.accept_events = false;\n params.can_activate = false;\n params.keep_on_top = true;\n params.remove_standard_frame = true;\n params.delegate = delegate;\n params.bounds = bounds;\n params.parent = Shell::GetContainer(\n root_window,\n internal::kShellWindowId_SettingBubbleContainer);\n widget_.reset(new views::Widget);\n widget_->Init(params);\n widget_->SetContentsView(delegate);\n widget_->GetNativeView()->SetName(\"ExitWarningWindow\");\n widget_->Show();\n\n delegate->NotifyAccessibilityEvent(ui::AccessibilityTypes::EVENT_ALERT, true);\n}\n\nvoid ExitWarningHandler::Hide() {\n widget_.reset();\n}\n\n} \/\/ namespace ash\n<commit_msg>ash: Make exit warning dialog transparent black<commit_after>\/\/ Copyright 2013 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"ash\/accelerators\/exit_warning_handler.h\"\n\n#include \"ash\/shell.h\"\n#include \"ash\/shell_delegate.h\"\n#include \"ash\/shell_window_ids.h\"\n#include \"base\/strings\/utf_string_conversions.h\"\n#include \"base\/time\/time.h\"\n#include \"base\/timer\/timer.h\"\n#include \"grit\/ash_strings.h\"\n#include \"ui\/aura\/root_window.h\"\n#include \"ui\/base\/accessibility\/accessible_view_state.h\"\n#include \"ui\/base\/l10n\/l10n_util.h\"\n#include \"ui\/base\/resource\/resource_bundle.h\"\n#include \"ui\/gfx\/canvas.h\"\n#include \"ui\/gfx\/font.h\"\n#include \"ui\/views\/controls\/label.h\"\n#include \"ui\/views\/layout\/fill_layout.h\"\n#include \"ui\/views\/view.h\"\n#include \"ui\/views\/widget\/widget.h\"\n#include \"ui\/views\/widget\/widget_delegate.h\"\n\nnamespace ash {\nnamespace {\n\nconst int64 kTimeOutMilliseconds = 2000;\n\/\/ Color of the text of the warning message.\nconst SkColor kTextColor = SK_ColorWHITE;\n\/\/ Color of the window background.\nconst SkColor kWindowBackgroundColor = SkColorSetARGB(0xC0, 0x0, 0x0, 0x0);\n\/\/ Radius of the rounded corners of the window.\nconst int kWindowCornerRadius = 2;\nconst int kHorizontalMarginAroundText = 100;\nconst int kVerticalMarginAroundText = 100;\n\nclass ExitWarningLabel : public views::Label {\n public:\n ExitWarningLabel() {}\n\n virtual ~ExitWarningLabel() {}\n\n private:\n virtual void PaintText(gfx::Canvas* canvas,\n const string16& text,\n const gfx::Rect& text_bounds,\n int flags) OVERRIDE {\n \/\/ Turn off subpixel rendering.\n views::Label::PaintText(canvas,\n text,\n text_bounds,\n flags | gfx::Canvas::NO_SUBPIXEL_RENDERING);\n }\n\n DISALLOW_COPY_AND_ASSIGN(ExitWarningLabel);\n};\n\nclass ExitWarningWidgetDelegateView : public views::WidgetDelegateView {\n public:\n ExitWarningWidgetDelegateView() : text_width_(0), width_(0), height_(0) {\n text_ = l10n_util::GetStringUTF16(IDS_ASH_EXIT_WARNING_POPUP_TEXT);\n accessible_name_ =\n l10n_util::GetStringUTF16(IDS_ASH_EXIT_WARNING_POPUP_TEXT_ACCESSIBLE);\n ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance();\n font_ = rb.GetFont(ui::ResourceBundle::LargeFont);\n text_width_ = font_.GetStringWidth(text_);\n width_ = text_width_ + kHorizontalMarginAroundText;\n height_ = font_.GetHeight() + kVerticalMarginAroundText;\n views::Label* label = new ExitWarningLabel;\n label->SetText(text_);\n label->SetHorizontalAlignment(gfx::ALIGN_CENTER);\n label->SetFont(font_);\n label->SetEnabledColor(kTextColor);\n label->SetDisabledColor(kTextColor);\n label->SetAutoColorReadabilityEnabled(false);\n AddChildView(label);\n SetLayoutManager(new views::FillLayout);\n }\n\n virtual gfx::Size GetPreferredSize() OVERRIDE {\n return gfx::Size(width_, height_);\n }\n\n virtual void OnPaint(gfx::Canvas* canvas) OVERRIDE {\n SkPaint paint;\n paint.setStyle(SkPaint::kFill_Style);\n paint.setColor(kWindowBackgroundColor);\n canvas->DrawRoundRect(GetLocalBounds(), kWindowCornerRadius, paint);\n views::WidgetDelegateView::OnPaint(canvas);\n }\n\n virtual void GetAccessibleState(ui::AccessibleViewState* state) OVERRIDE {\n state->name = accessible_name_;\n state->role = ui::AccessibilityTypes::ROLE_ALERT;\n }\n\n private:\n base::string16 text_;\n base::string16 accessible_name_;\n gfx::Font font_;\n int text_width_;\n int width_;\n int height_;\n\n DISALLOW_COPY_AND_ASSIGN(ExitWarningWidgetDelegateView);\n};\n\n} \/\/ namespace\n\nExitWarningHandler::ExitWarningHandler()\n : state_(IDLE),\n stub_timer_for_test_(false) {\n}\n\nExitWarningHandler::~ExitWarningHandler() {\n \/\/ Note: If a timer is outstanding, it is stopped in its destructor.\n Hide();\n}\n\nvoid ExitWarningHandler::HandleAccelerator() {\n ShellDelegate* shell_delegate = Shell::GetInstance()->delegate();\n switch (state_) {\n case IDLE:\n state_ = WAIT_FOR_DOUBLE_PRESS;\n Show();\n StartTimer();\n shell_delegate->RecordUserMetricsAction(UMA_ACCEL_EXIT_FIRST_Q);\n break;\n case WAIT_FOR_DOUBLE_PRESS:\n state_ = EXITING;\n CancelTimer();\n Hide();\n shell_delegate->RecordUserMetricsAction(UMA_ACCEL_EXIT_SECOND_Q);\n shell_delegate->Exit();\n break;\n case EXITING:\n break;\n default:\n NOTREACHED();\n break;\n }\n}\n\nvoid ExitWarningHandler::TimerAction() {\n Hide();\n if (state_ == WAIT_FOR_DOUBLE_PRESS)\n state_ = IDLE;\n}\n\nvoid ExitWarningHandler::StartTimer() {\n if (stub_timer_for_test_)\n return;\n timer_.Start(FROM_HERE,\n base::TimeDelta::FromMilliseconds(kTimeOutMilliseconds),\n this,\n &ExitWarningHandler::TimerAction);\n}\n\nvoid ExitWarningHandler::CancelTimer() {\n timer_.Stop();\n}\n\nvoid ExitWarningHandler::Show() {\n if (widget_)\n return;\n aura::RootWindow* root_window = Shell::GetActiveRootWindow();\n ExitWarningWidgetDelegateView* delegate = new ExitWarningWidgetDelegateView;\n gfx::Size rs = root_window->bounds().size();\n gfx::Size ps = delegate->GetPreferredSize();\n gfx::Rect bounds((rs.width() - ps.width()) \/ 2,\n (rs.height() - ps.height()) \/ 3,\n ps.width(), ps.height());\n views::Widget::InitParams params;\n params.type = views::Widget::InitParams::TYPE_POPUP;\n params.opacity = views::Widget::InitParams::TRANSLUCENT_WINDOW;\n params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;\n params.accept_events = false;\n params.can_activate = false;\n params.keep_on_top = true;\n params.remove_standard_frame = true;\n params.delegate = delegate;\n params.bounds = bounds;\n params.parent = Shell::GetContainer(\n root_window,\n internal::kShellWindowId_SettingBubbleContainer);\n widget_.reset(new views::Widget);\n widget_->Init(params);\n widget_->SetContentsView(delegate);\n widget_->GetNativeView()->SetName(\"ExitWarningWindow\");\n widget_->Show();\n\n delegate->NotifyAccessibilityEvent(ui::AccessibilityTypes::EVENT_ALERT, true);\n}\n\nvoid ExitWarningHandler::Hide() {\n widget_.reset();\n}\n\n} \/\/ namespace ash\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n\n#include \"occa.hpp\"\n\nint main(int argc, char **argv){\n int entries = 5;\n\n float *a = new float[entries];\n float *b = new float[entries];\n float *ab = new float[entries];\n\n for(int i = 0; i < entries; ++i){\n a[i] = i;\n b[i] = 1 - i;\n ab[i] = 0;\n }\n\n \/\/ occa::availableDevices<occa::OpenCL>();\n\n occa::device device;\n occa::kernel addVectors;\n occa::memory o_a, o_b, o_ab;\n\n device.setup(\"mode = OpenMP , schedule = compact, chunk = 10\");\n \/\/ device.setup(\"mode = OpenCL , platformID = 0, deviceID = 0\");\n \/\/ device.setup(\"mode = CUDA , deviceID = 0\");\n \/\/ device.setup(\"mode = Pthreads, threadCount = 1, schedule = compact\");\n \/\/ device.setup(\"mode = COI , deviceID = 0\");\n\n o_a = device.malloc(entries*sizeof(float));\n o_b = device.malloc(entries*sizeof(float));\n o_ab = device.malloc(entries*sizeof(float));\n\n addVectors = device.buildKernelFromSource(\"addVectors.okl\",\n \"addVectors\");\n\n \/\/---[ Don't need to set these up when using OKL ]--------\n \/\/ int dims = 1;\n \/\/ int itemsPerGroup(16);\n \/\/ int groups((entries + itemsPerGroup - 1)\/itemsPerGroup);\n \/\/========================================================\n\n \/\/ addVectors.setWorkingDims(dims, itemsPerGroup, groups);\n\n o_a.copyFrom(a);\n o_b.copyFrom(b);\n\n occa::initTimer(device);\n\n occa::tic(\"addVectors\");\n\n addVectors(entries, o_a, o_b, o_ab);\n\n double elapsedTime = occa::toc(\"addVectors\", addVectors);\n\n o_ab.copyTo(ab);\n\n std::cout << \"Elapsed time = \" << elapsedTime << \" s\" << std::endl;\n\n occa::printTimer();\n\n for(int i = 0; i < 5; ++i)\n std::cout << i << \": \" << ab[i] << '\\n';\n\n for(int i = 0; i < entries; ++i){\n if(ab[i] != (a[i] + b[i]))\n throw 1;\n }\n\n delete [] a;\n delete [] b;\n delete [] ab;\n\n addVectors.free();\n o_a.free();\n o_b.free();\n o_ab.free();\n device.free();\n\n return 0;\n}\n<commit_msg>[Example] Updated device setup on addVectors example<commit_after>#include <iostream>\n\n#include \"occa.hpp\"\n\nint main(int argc, char **argv){\n int entries = 5;\n\n float *a = new float[entries];\n float *b = new float[entries];\n float *ab = new float[entries];\n\n for(int i = 0; i < entries; ++i){\n a[i] = i;\n b[i] = 1 - i;\n ab[i] = 0;\n }\n\n \/\/ occa::availableDevices<occa::OpenCL>();\n\n occa::device device;\n occa::kernel addVectors;\n occa::memory o_a, o_b, o_ab;\n\n device.setup(\"mode = OpenMP , schedule = compact, chunk = 10\");\n\n \/\/---[ Device setup with string flags ]-------------------\n \/\/ device.setup(\"mode = OpenMP , schedule = compact, chunk = 10\");\n \/\/ device.setup(\"mode = OpenCL , platformID = 0, deviceID = 0\");\n \/\/ device.setup(\"mode = CUDA , deviceID = 0\");\n \/\/ device.setup(\"mode = Pthreads, threadCount = 4, schedule = compact, pinnedCores = [0, 0, 1, 1]\");\n \/\/ device.setup(\"mode = COI , deviceID = 0\");\n \/\/========================================================\n\n \/\/---[ Device setup with Python-like arguments ]----------\n \/\/ device.setup(\"OpenMP\",\n \/\/ occa::schedule = \"compact\",\n \/\/ occa::chunk = 10);\n \/\/\n \/\/ device.setup(\"OpenCL\",\n \/\/ occa::platformID = 0,\n \/\/ occa::deviceID = 0);\n \/\/\n \/\/ device.setup(\"CUDA\",\n \/\/ occa::deviceID = 0);\n \/\/\n \/\/ device.setup(\"Pthreads\",\n \/\/ occa::threadCount = 4,\n \/\/ occa::schedule = \"compact\",\n \/\/ occa::pinnedCores = \"[0, 0, 1, 1]\");\n \/\/\n \/\/ device.setup(\"COI\",\n \/\/ occa::deviceID = 0);\n \/\/========================================================\n\n o_a = device.malloc(entries*sizeof(float));\n o_b = device.malloc(entries*sizeof(float));\n o_ab = device.malloc(entries*sizeof(float));\n\n addVectors = device.buildKernelFromSource(\"addVectors.okl\",\n \"addVectors\");\n\n \/\/---[ Don't need to set these up when using OKL ]--------\n \/\/ int dims = 1;\n \/\/ int itemsPerGroup(16);\n \/\/ int groups((entries + itemsPerGroup - 1)\/itemsPerGroup);\n \/\/========================================================\n\n \/\/ addVectors.setWorkingDims(dims, itemsPerGroup, groups);\n\n o_a.copyFrom(a);\n o_b.copyFrom(b);\n\n occa::initTimer(device);\n\n occa::tic(\"addVectors\");\n\n addVectors(entries, o_a, o_b, o_ab);\n\n double elapsedTime = occa::toc(\"addVectors\", addVectors);\n\n o_ab.copyTo(ab);\n\n std::cout << \"Elapsed time = \" << elapsedTime << \" s\" << std::endl;\n\n occa::printTimer();\n\n for(int i = 0; i < 5; ++i)\n std::cout << i << \": \" << ab[i] << '\\n';\n\n for(int i = 0; i < entries; ++i){\n if(ab[i] != (a[i] + b[i]))\n throw 1;\n }\n\n delete [] a;\n delete [] b;\n delete [] ab;\n\n addVectors.free();\n o_a.free();\n o_b.free();\n o_ab.free();\n device.free();\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- *\/\n\/*\n * This file is part of the LibreOffice project.\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\n * This file incorporates work covered by the following license notice:\n *\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed\n * with this work for additional information regarding copyright\n * ownership. The ASF licenses this file to you under the Apache\n * License, Version 2.0 (the \"License\"); you may not use this file\n * except in compliance with the License. You may obtain a copy of\n * the License at http:\/\/www.apache.org\/licenses\/LICENSE-2.0 .\n *\/\n\n#include <sfx2\/sidebar\/ResourceDefinitions.hrc>\n#include <sfx2\/sidebar\/Theme.hxx>\n#include <sfx2\/sidebar\/ControlFactory.hxx>\n#include \"ChartElementsPanel.hxx\"\n#include \"ChartController.hxx\"\n#include <sfx2\/bindings.hxx>\n#include <sfx2\/dispatch.hxx>\n#include <sfx2\/imagemgr.hxx>\n#include <vcl\/fixed.hxx>\n#include <vcl\/lstbox.hxx>\n#include <vcl\/field.hxx>\n#include <vcl\/toolbox.hxx>\n#include <svl\/intitem.hxx>\n#include <svl\/stritem.hxx>\n\n#include \"LegendHelper.hxx\"\n#include \"TitleHelper.hxx\"\n\n#include \"ChartModel.hxx\"\n\nusing namespace css;\nusing namespace css::uno;\nusing ::sfx2::sidebar::Theme;\n\nnamespace chart { namespace sidebar {\n\nnamespace {\n\nChartModel* getChartModel(css::uno::Reference<css::frame::XModel> xModel)\n{\n ChartModel* pModel = dynamic_cast<ChartModel*>(xModel.get());\n\n return pModel;\n}\n\nbool isLegendVisible(css::uno::Reference<css::frame::XModel> xModel)\n{\n ChartModel* pModel = getChartModel(xModel);\n if (!pModel)\n return false;\n\n Reference< beans::XPropertySet > xLegendProp( LegendHelper::getLegend(*pModel), uno::UNO_QUERY );\n if( xLegendProp.is())\n {\n try\n {\n bool bShow = false;\n if( xLegendProp->getPropertyValue( \"Show\") >>= bShow )\n {\n return bShow;\n }\n }\n catch(const uno::Exception &)\n {\n }\n }\n\n return false;\n}\n\nbool isTitleVisisble(css::uno::Reference<css::frame::XModel> xModel, TitleHelper::eTitleType eTitle)\n{\n return TitleHelper::getTitle(eTitle, xModel).is();\n}\n\n}\n\nChartElementsPanel::ChartElementsPanel(\n vcl::Window* pParent,\n const css::uno::Reference<css::frame::XFrame>& rxFrame,\n SfxBindings* pBindings,\n ChartController* pController)\n : PanelLayout(pParent, \"ChartElementsPanel\", \"modules\/schart\/ui\/sidebarelements.ui\", rxFrame),\n mxFrame(rxFrame),\n maContext(),\n mpBindings(pBindings),\n mxModel(pController->getModel())\n{\n get(mpCBTitle, \"checkbutton_title\");\n get(mpCBSubtitle, \"checkbutton_subtitle\");\n get(mpCBXAxis, \"checkbutton_x_axis\");\n get(mpCBXAxisTitle, \"checkbutton_x_axis_title\");\n get(mpCBYAxis, \"checkbutton_y_axis\");\n get(mpCBYAxisTitle, \"checkbutton_y_axis_title\");\n get(mpCBZAxis, \"checkbutton_z_axis\");\n get(mpCBZAxisTitle, \"checkbutton_z_axis_title\");\n get(mpCB2ndXAxis, \"checkbutton_2nd_x_axis\");\n get(mpCB2ndXAxisTitle, \"checkbutton_2nd_x_axis_title\");\n get(mpCB2ndYAxis, \"checkbutton_2nd_y_axis\");\n get(mpCB2ndYAxisTitle, \"checkbutton_2nd_y_axis_title\");\n get(mpCBLegend, \"checkbutton_legend\");\n get(mpCBGridVertical, \"checkbutton_gridline_vertical\");\n get(mpCBGridHorizontal, \"checkbutton_gridline_horizontal\");\n get(mpCBShowLabel, \"checkbutton_label\");\n get(mpCBTrendline, \"checkbutton_trendline\");\n}\n\nChartElementsPanel::~ChartElementsPanel()\n{\n disposeOnce();\n}\n\nvoid ChartElementsPanel::dispose()\n{\n mpCBTitle.clear();\n mpCBSubtitle.clear();\n mpCBXAxis.clear();\n mpCBXAxisTitle.clear();\n mpCBYAxis.clear();\n mpCBYAxisTitle.clear();\n mpCBZAxis.clear();\n mpCBZAxisTitle.clear();\n mpCB2ndXAxis.clear();\n mpCB2ndXAxisTitle.clear();\n mpCB2ndYAxis.clear();\n mpCB2ndYAxisTitle.clear();\n mpCBLegend.clear();\n mpCBGridVertical.clear();\n mpCBGridHorizontal.clear();\n mpCBShowLabel.clear();\n mpCBTrendline.clear();\n\n PanelLayout::dispose();\n}\n\nvoid ChartElementsPanel::Initialize()\n{\n updateData();\n}\n\nvoid ChartElementsPanel::updateData()\n{\n mpCBLegend->Check(isLegendVisible(mxModel));\n mpCBTitle->Check(isTitleVisisble(mxModel, TitleHelper::MAIN_TITLE));\n mpCBSubtitle->Check(isTitleVisisble(mxModel, TitleHelper::SUB_TITLE));\n mpCBXAxisTitle->Check(isTitleVisisble(mxModel, TitleHelper::X_AXIS_TITLE));\n mpCBYAxisTitle->Check(isTitleVisisble(mxModel, TitleHelper::Y_AXIS_TITLE));\n mpCBZAxisTitle->Check(isTitleVisisble(mxModel, TitleHelper::Z_AXIS_TITLE));\n mpCB2ndXAxisTitle->Check(isTitleVisisble(mxModel, TitleHelper::SECONDARY_X_AXIS_TITLE));\n mpCB2ndYAxisTitle->Check(isTitleVisisble(mxModel, TitleHelper::SECONDARY_Y_AXIS_TITLE));\n}\n\nVclPtr<vcl::Window> ChartElementsPanel::Create (\n vcl::Window* pParent,\n const css::uno::Reference<css::frame::XFrame>& rxFrame,\n SfxBindings* pBindings, ChartController* pController)\n{\n if (pParent == NULL)\n throw lang::IllegalArgumentException(\"no parent Window given to ChartElementsPanel::Create\", NULL, 0);\n if ( ! rxFrame.is())\n throw lang::IllegalArgumentException(\"no XFrame given to ChartElementsPanel::Create\", NULL, 1);\n if (pBindings == NULL)\n throw lang::IllegalArgumentException(\"no SfxBindings given to ChartElementsPanel::Create\", NULL, 2);\n\n return VclPtr<ChartElementsPanel>::Create(\n pParent, rxFrame, pBindings, pController);\n}\n\nvoid ChartElementsPanel::DataChanged(\n const DataChangedEvent& )\n{\n updateData();\n}\n\nvoid ChartElementsPanel::HandleContextChange(\n const ::sfx2::sidebar::EnumContext& rContext)\n{\n if(maContext == rContext)\n {\n \/\/ Nothing to do.\n return;\n }\n\n maContext = rContext;\n updateData();\n}\n\nvoid ChartElementsPanel::NotifyItemUpdate(\n sal_uInt16 \/*nSID*\/,\n SfxItemState \/*eState*\/,\n const SfxPoolItem* \/*pState*\/,\n const bool )\n{\n}\n\n}} \/\/ end of namespace ::chart::sidebar\n\n\/* vim:set shiftwidth=4 softtabstop=4 expandtab: *\/\n<commit_msg>wire gridlines in chart elements panel<commit_after>\/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- *\/\n\/*\n * This file is part of the LibreOffice project.\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\n * This file incorporates work covered by the following license notice:\n *\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed\n * with this work for additional information regarding copyright\n * ownership. The ASF licenses this file to you under the Apache\n * License, Version 2.0 (the \"License\"); you may not use this file\n * except in compliance with the License. You may obtain a copy of\n * the License at http:\/\/www.apache.org\/licenses\/LICENSE-2.0 .\n *\/\n\n#include <sfx2\/sidebar\/ResourceDefinitions.hrc>\n#include <sfx2\/sidebar\/Theme.hxx>\n#include <sfx2\/sidebar\/ControlFactory.hxx>\n#include \"ChartElementsPanel.hxx\"\n#include \"ChartController.hxx\"\n#include <sfx2\/bindings.hxx>\n#include <sfx2\/dispatch.hxx>\n#include <sfx2\/imagemgr.hxx>\n#include <vcl\/fixed.hxx>\n#include <vcl\/lstbox.hxx>\n#include <vcl\/field.hxx>\n#include <vcl\/toolbox.hxx>\n#include <svl\/intitem.hxx>\n#include <svl\/stritem.hxx>\n\n#include \"LegendHelper.hxx\"\n#include \"TitleHelper.hxx\"\n#include \"ChartModelHelper.hxx\"\n#include \"AxisHelper.hxx\"\n\n#include \"ChartModel.hxx\"\n\nusing namespace css;\nusing namespace css::uno;\nusing ::sfx2::sidebar::Theme;\n\nnamespace chart { namespace sidebar {\n\nnamespace {\n\nenum class GridType\n{\n VERT_MAJOR,\n VERT_MINOR,\n HOR_MAJOR,\n HOR_MINOR\n};\n\nChartModel* getChartModel(css::uno::Reference<css::frame::XModel> xModel)\n{\n ChartModel* pModel = dynamic_cast<ChartModel*>(xModel.get());\n\n return pModel;\n}\n\nbool isLegendVisible(css::uno::Reference<css::frame::XModel> xModel)\n{\n ChartModel* pModel = getChartModel(xModel);\n if (!pModel)\n return false;\n\n Reference< beans::XPropertySet > xLegendProp( LegendHelper::getLegend(*pModel), uno::UNO_QUERY );\n if( xLegendProp.is())\n {\n try\n {\n bool bShow = false;\n if( xLegendProp->getPropertyValue( \"Show\") >>= bShow )\n {\n return bShow;\n }\n }\n catch(const uno::Exception &)\n {\n }\n }\n\n return false;\n}\n\nbool isTitleVisisble(css::uno::Reference<css::frame::XModel> xModel, TitleHelper::eTitleType eTitle)\n{\n return TitleHelper::getTitle(eTitle, xModel).is();\n}\n\nbool isGridVisible(css::uno::Reference<css::frame::XModel> xModel, GridType eType)\n{\n Reference< chart2::XDiagram > xDiagram(ChartModelHelper::findDiagram(xModel));\n if(xDiagram.is())\n {\n sal_Int32 nDimensionIndex = 0;\n if (eType == GridType::HOR_MAJOR || eType == GridType::HOR_MINOR)\n nDimensionIndex = 1;\n sal_Int32 nCooSysIndex = 0;\n\n bool bMajor = (eType == GridType::HOR_MAJOR || eType == GridType::VERT_MAJOR);\n\n bool bHasGrid = AxisHelper::isGridShown(nDimensionIndex, nCooSysIndex, bMajor, xDiagram);\n return bHasGrid;\n }\n return false;\n}\n\n}\n\nChartElementsPanel::ChartElementsPanel(\n vcl::Window* pParent,\n const css::uno::Reference<css::frame::XFrame>& rxFrame,\n SfxBindings* pBindings,\n ChartController* pController)\n : PanelLayout(pParent, \"ChartElementsPanel\", \"modules\/schart\/ui\/sidebarelements.ui\", rxFrame),\n mxFrame(rxFrame),\n maContext(),\n mpBindings(pBindings),\n mxModel(pController->getModel())\n{\n get(mpCBTitle, \"checkbutton_title\");\n get(mpCBSubtitle, \"checkbutton_subtitle\");\n get(mpCBXAxis, \"checkbutton_x_axis\");\n get(mpCBXAxisTitle, \"checkbutton_x_axis_title\");\n get(mpCBYAxis, \"checkbutton_y_axis\");\n get(mpCBYAxisTitle, \"checkbutton_y_axis_title\");\n get(mpCBZAxis, \"checkbutton_z_axis\");\n get(mpCBZAxisTitle, \"checkbutton_z_axis_title\");\n get(mpCB2ndXAxis, \"checkbutton_2nd_x_axis\");\n get(mpCB2ndXAxisTitle, \"checkbutton_2nd_x_axis_title\");\n get(mpCB2ndYAxis, \"checkbutton_2nd_y_axis\");\n get(mpCB2ndYAxisTitle, \"checkbutton_2nd_y_axis_title\");\n get(mpCBLegend, \"checkbutton_legend\");\n get(mpCBGridVertical, \"checkbutton_gridline_vertical\");\n get(mpCBGridHorizontal, \"checkbutton_gridline_horizontal\");\n get(mpCBShowLabel, \"checkbutton_label\");\n get(mpCBTrendline, \"checkbutton_trendline\");\n}\n\nChartElementsPanel::~ChartElementsPanel()\n{\n disposeOnce();\n}\n\nvoid ChartElementsPanel::dispose()\n{\n mpCBTitle.clear();\n mpCBSubtitle.clear();\n mpCBXAxis.clear();\n mpCBXAxisTitle.clear();\n mpCBYAxis.clear();\n mpCBYAxisTitle.clear();\n mpCBZAxis.clear();\n mpCBZAxisTitle.clear();\n mpCB2ndXAxis.clear();\n mpCB2ndXAxisTitle.clear();\n mpCB2ndYAxis.clear();\n mpCB2ndYAxisTitle.clear();\n mpCBLegend.clear();\n mpCBGridVertical.clear();\n mpCBGridHorizontal.clear();\n mpCBShowLabel.clear();\n mpCBTrendline.clear();\n\n PanelLayout::dispose();\n}\n\nvoid ChartElementsPanel::Initialize()\n{\n updateData();\n}\n\nvoid ChartElementsPanel::updateData()\n{\n mpCBLegend->Check(isLegendVisible(mxModel));\n mpCBTitle->Check(isTitleVisisble(mxModel, TitleHelper::MAIN_TITLE));\n mpCBSubtitle->Check(isTitleVisisble(mxModel, TitleHelper::SUB_TITLE));\n mpCBXAxisTitle->Check(isTitleVisisble(mxModel, TitleHelper::X_AXIS_TITLE));\n mpCBYAxisTitle->Check(isTitleVisisble(mxModel, TitleHelper::Y_AXIS_TITLE));\n mpCBZAxisTitle->Check(isTitleVisisble(mxModel, TitleHelper::Z_AXIS_TITLE));\n mpCB2ndXAxisTitle->Check(isTitleVisisble(mxModel, TitleHelper::SECONDARY_X_AXIS_TITLE));\n mpCB2ndYAxisTitle->Check(isTitleVisisble(mxModel, TitleHelper::SECONDARY_Y_AXIS_TITLE));\n mpCBGridVertical->Check(isGridVisible(mxModel, GridType::VERT_MAJOR));\n mpCBGridHorizontal->Check(isGridVisible(mxModel, GridType::HOR_MAJOR));\n}\n\nVclPtr<vcl::Window> ChartElementsPanel::Create (\n vcl::Window* pParent,\n const css::uno::Reference<css::frame::XFrame>& rxFrame,\n SfxBindings* pBindings, ChartController* pController)\n{\n if (pParent == NULL)\n throw lang::IllegalArgumentException(\"no parent Window given to ChartElementsPanel::Create\", NULL, 0);\n if ( ! rxFrame.is())\n throw lang::IllegalArgumentException(\"no XFrame given to ChartElementsPanel::Create\", NULL, 1);\n if (pBindings == NULL)\n throw lang::IllegalArgumentException(\"no SfxBindings given to ChartElementsPanel::Create\", NULL, 2);\n\n return VclPtr<ChartElementsPanel>::Create(\n pParent, rxFrame, pBindings, pController);\n}\n\nvoid ChartElementsPanel::DataChanged(\n const DataChangedEvent& )\n{\n updateData();\n}\n\nvoid ChartElementsPanel::HandleContextChange(\n const ::sfx2::sidebar::EnumContext& rContext)\n{\n if(maContext == rContext)\n {\n \/\/ Nothing to do.\n return;\n }\n\n maContext = rContext;\n updateData();\n}\n\nvoid ChartElementsPanel::NotifyItemUpdate(\n sal_uInt16 \/*nSID*\/,\n SfxItemState \/*eState*\/,\n const SfxPoolItem* \/*pState*\/,\n const bool )\n{\n}\n\n}} \/\/ end of namespace ::chart::sidebar\n\n\/* vim:set shiftwidth=4 softtabstop=4 expandtab: *\/\n<|endoftext|>"} {"text":"<commit_before>#include \"input\/Input.hpp\"\r\n#include \"input\/ControllableCamera.hpp\"\r\n#include \"resources\/ResourcesManager.hpp\"\r\n#include \"graphics\/GPU.hpp\"\r\n#include \"graphics\/Framebuffer.hpp\"\r\n#include \"system\/Config.hpp\"\r\n#include \"system\/System.hpp\"\r\n#include \"system\/Window.hpp\"\r\n#include \"generation\/Random.hpp\"\r\n#include \"Common.hpp\"\r\n\r\n\/**\r\n \\defgroup Playground Playground\r\n \\brief A basic playground for testing ideas.\r\n \\ingroup Applications\r\n *\/\r\n\r\n\/**\r\n The main function of the playground.\r\n \\param argc the number of input arguments.\r\n \\param argv a pointer to the raw input arguments.\r\n \\return a general error code.\r\n \\ingroup Playground\r\n *\/\r\nint main(int argc, char ** argv) {\r\n\r\n\t\/\/ First, init\/parse\/load configuration.\r\n\tRenderingConfig config(std::vector<std::string>(argv, argv + argc));\r\n\tif(config.showHelp()) {\r\n\t\treturn 0;\r\n\t}\r\n\r\n\tWindow window(\"Playground\", config, false);\r\n\t\r\n\tif(!config.resourcesPath.empty()){\r\n\t\tResources::manager().addResources(config.resourcesPath);\r\n\t}\r\n\t\r\n\t\/\/ Seed random generator.\r\n\tRandom::seed();\r\n\t\/\/ Query the renderer identifier, and the supported GPU API version.\r\n\tstd::string vendor, renderer, version, shaderVersion;\r\n\tGPU::deviceInfos(vendor, renderer, version, shaderVersion);\r\n\tLog::Info() << Log::GPU << \"Vendor: \" << vendor << \".\" << std::endl;\r\n\tLog::Info() << Log::GPU << \"Internal renderer: \" << renderer << \".\" << std::endl;\r\n\tLog::Info() << Log::GPU << \"Versions: Driver: \" << version << \", API: \" << shaderVersion << \".\" << std::endl;\r\n\r\n\t\/\/ Query the extensions.\r\n\tconst std::vector<std::string> extensions = GPU::supportedExtensions();\r\n\t\/\/ Log extensions.\r\n\tsize_t extensionCount = extensions.size();\r\n\tfor(const auto& ext : extensions){\r\n\t\tif(ext[0] == '-'){\r\n\t\t\t--extensionCount;\r\n\t\t}\r\n\t}\r\n\r\n\tif(!extensions.empty()) {\r\n\t\tLog::Info() << Log::GPU << \"Extensions detected (\" << extensionCount << \"): \" << std::endl;\r\n\t\tfor(size_t i = 0; i < extensions.size(); ++i) {\r\n\t\t\tconst bool isHeader = extensions[i][0] == '-';\r\n\t\t\tLog::Info() << (isHeader ? \"\\n\" : \"\") << extensions[i] << (isHeader ? \"\\n\" : \", \") << std::flush;\r\n\t\t}\r\n\t\tLog::Info() << std::endl;\r\n\t}\r\n\tconst std::string titleHeader = \"Extensions (\" + std::to_string(extensionCount) + \")\";\r\n\r\n\tGPU::setDepthState(true, TestFunction::LESS, true);\r\n\tGPU::setCullState(true, Faces::BACK);\r\n\tGPU::setBlendState(false);\r\n\r\n\t\/\/ Setup the timer.\r\n\tdouble timer\t\t = System::time();\r\n\tdouble fullTime\t\t = 0.0;\r\n\tdouble remainingTime = 0.0;\r\n\tconst double dt\t\t = 1.0 \/ 120.0; \/\/ Small physics timestep.\r\n\r\n\tProgram * program = Resources::manager().getProgram(\"object\", \"object_basic\", \"object_basic_random\");\r\n\tconst Mesh * mesh\t\t= Resources::manager().getMesh(\"light_sphere\", Storage::GPU);\r\n\r\n\tProgram * program2 = Resources::manager().getProgram(\"object_basic_color\");\r\n\tMesh mesh2(\"Plane\");\r\n\tmesh2.positions = {glm::vec3(-0.5f, -0.5f, 0.5f), glm::vec3(0.5f, -0.5f, 0.5f), glm::vec3(0.5f, 0.5f, 0.5f), glm::vec3(-0.5f, 0.5f, 0.5f)};\r\n\tmesh2.colors = {glm::vec3(1.0f, 0.0f, 0.0f), glm::vec3(0.0f, 1.0f, 0.0f), glm::vec3(0.0f, 0.0f, 1.0f), glm::vec3(0.0f, 0.0f, 0.0f)};\r\n\tmesh2.indices = {0, 1, 2, 0, 2, 3};\r\n\tmesh2.upload();\r\n\r\n\tMesh mesh3(\"Triangle\");\r\n\tmesh3.positions = {glm::vec3(-0.5f, -0.5f, 0.1f), glm::vec3(0.5f, -0.5f, 0.1f), glm::vec3(0.0f, 1.0f, 0.1f)};\r\n\tmesh3.colors = {glm::vec3(1.0f, 1.0f, 0.0f), glm::vec3(0.0f, 1.0f, 1.0f), glm::vec3(1.0f, 0.0f, 1.0f)};\r\n\tmesh3.indices = {0, 2, 1};\r\n\tmesh3.upload();\r\n\r\n\r\n\tControllableCamera camera;\r\n\r\n\tcamera.pose(glm::vec3(0.0f,0.0f,3.0f), glm::vec3(0.0f), glm::vec3(0.0f, 1.0f, 0.0f));\r\n\tcamera.projection(config.screenResolution[0] \/ config.screenResolution[1], 1.34f, 0.1f, 100.0f);\r\n\tbool showImGuiDemo = false;\r\n\r\n\tconst Texture* tex = Resources::manager().getTexture(\"debug-grid\", {Layout::RGBA16F, Filter::LINEAR_LINEAR, Wrap::CLAMP}, Storage::GPU);\r\n\r\n\tTexture tex2(\"textest\");\r\n\ttex2.width = tex2.height = 8;\r\n\ttex2.depth = tex2.levels = 1;\r\n\ttex2.shape = TextureShape::D2;\r\n\ttex2.images.emplace_back(tex2.width, tex2.height, 4);\r\n\tauto& texData = tex2.images.back();\r\n\r\n\r\n\r\n\tuint count = 0;\r\n\tDescriptor desc = {Layout::RGBA8, Filter::LINEAR, Wrap::CLAMP};\r\n\tFramebuffer fb(400, 300, desc , true, \"testfb\");\r\n\t\r\n\t\/\/ Start the display\/interaction loop.\r\n\twhile(window.nextFrame()) {\r\n\t\t\r\n\t\t\/\/ Reload resources.\r\n\t\tif(Input::manager().triggered(Input::Key::P)) {\r\n\t\t\tResources::manager().reload();\r\n\t\t}\r\n\r\n\t\t\/\/ Compute the time elapsed since last frame\r\n\t\tconst double currentTime = System::time();\r\n\t\tdouble frameTime\t\t = currentTime - timer;\r\n\t\ttimer\t\t\t\t\t = currentTime;\r\n\r\n\t\tcamera.update();\r\n\r\n\t\t\/\/ Physics simulation\r\n\t\t\/\/ First avoid super high frametime by clamping.\r\n\t\tif(frameTime > 0.2) {\r\n\t\t\tframeTime = 0.2;\r\n\t\t}\r\n\t\t\/\/ Accumulate new frame time.\r\n\t\tremainingTime += frameTime;\r\n\t\t\/\/ Instead of bounding at dt, we lower our requirement (1 order of magnitude).\r\n\t\twhile(remainingTime > 0.2 * dt) {\r\n\t\t\tdouble deltaTime = fmin(remainingTime, dt);\r\n\t\t\t\/\/ Update physics and camera.\r\n\t\t\tcamera.physics(deltaTime);\r\n\t\t\t\/\/ Update timers.\r\n\t\t\tfullTime += deltaTime;\r\n\t\t\tremainingTime -= deltaTime;\r\n\t\t}\r\n\r\n\t\tif(Input::manager().resized()){\r\n\t\t\tfb.resize(Input::manager().size());\r\n\t\t}\r\n\r\n\t\t\/\/ Render.\r\n\t\tconst glm::ivec2 screenSize = Input::manager().size();\r\n\t\tconst glm::mat4 MVP\t\t = camera.projection() * camera.view();\r\n\t\tfb.bind(glm::vec4(0.2f, 0.3f, 0.25f, 1.0f), 1.0f);\r\n\t\tGPU::setViewport(0, 0, screenSize[0], screenSize[1]);\r\n\t\tprogram->use();\r\n\t\tprogram->uniform(\"mvp\", MVP);\r\n\t\t\/\/GPU::drawMesh(*mesh);\r\n\t\t\/\/GPU::setBlendState(true, BlendEquation::ADD, BlendFunction::SRC_ALPHA, BlendFunction::ONE_MINUS_SRC_ALPHA);\r\n\r\n\t\tfor(uint dy = 0; dy < tex2.height; ++dy){\r\n\t\t\tfor(uint dx = 0; dx < tex2.width; ++dx){\r\n\t\t\t\tfloat r = 0.0f; float g = 0.0f; float b = 0.0f;\r\n\t\t\t\tuint x = (dx + count)%8;\r\n\t\t\t\tuint y = (dy + count)%8;\r\n\t\t\t\tif(x < 2){\r\n\t\t\t\t\tr = 1.0f;\r\n\t\t\t\t} else if (x < 4){\r\n\t\t\t\t\tg = 1.0f;\r\n\t\t\t\t} else if(x < 6){\r\n\t\t\t\t\tb = 1.0f;\r\n\t\t\t\t}\r\n\t\t\t\tif(y < 2){\r\n\t\t\t\t\tb = 0.5f;\r\n\t\t\t\t} else if (y < 4){\r\n\t\t\t\t\tr = 0.5f;\r\n\t\t\t\t} else if(y < 6){\r\n\t\t\t\t\tg = 0.5f;\r\n\t\t\t\t}\r\n\t\t\t\tr = float(count % 60)\/60.0f;\r\n\t\t\t\ttexData.rgba(x,y) = glm::vec4(r,g,b,0.5f);\r\n\t\t\t}\r\n\t\t}\r\n\t\t++count;\r\n\t\ttex2.upload({Layout::RGBA32F, Filter::NEAREST_LINEAR, Wrap::CLAMP}, true);\r\n\r\n\t\tprogram2->use();\r\n\t\tprogram2->uniform(\"mvp\", MVP);\r\n\t\tprogram2->uniform(\"color\", glm::vec3(1.0f, 0.5f, 0.0f));\r\n\t\tprogram2->texture(tex, 0);\r\n\t\tGPU::drawMesh(mesh2);\r\n\t\t\/\/GPU::setCullState(true, Faces::BACK);\r\n\t\t\/\/GPU::setBlendState(false);\r\n\t\tfloat angle = float(count % 360)\/360.0 * glm::two_pi<float>();\r\n\t\tglm::mat3 rot = glm::mat3(glm::rotate(glm::mat4(1.0f), angle, glm::vec3(0.0f, 0.0f, 1.0f)));\r\n\r\n\t\tmesh3.positions.clear();\r\n\t\tmesh3.positions = {rot * glm::vec3(-0.5f, -0.5f, 0.1f), rot * glm::vec3(0.5f, -0.5f, 0.1f), rot * glm::vec3(0.0f, 1.0f, 0.1f)};\r\n\t\tmesh3.upload();\r\n\r\n\t\tprogram2->texture(tex2, 0);\r\n\t\tprogram2->uniform(\"color\", glm::vec3(0.0f, 0.5f, 1.0f));\r\n\t\tGPU::drawMesh(mesh3);\r\n\r\n\t\t\/\/GPU::setViewport(screenSize[0]\/2, 0, screenSize[0]\/2, screenSize[1]);\r\n\t\t\/\/GPU::drawMesh(mesh2);\r\n\t\t\/\/GPU::drawMesh(mesh3);\r\n\r\n\t\t\/\/Framebuffer::backbuffer()->bind();\r\n\r\n\r\n\t\tImGui::Text(\"ImGui is functional!\");\r\n\t\tImGui::SameLine();\r\n\t\tImGui::Checkbox(\"Show demo\", &showImGuiDemo);\r\n\t\tImGui::Text(\"%.1f ms, %.1f fps\", frameTime * 1000.0f, 1.0f\/frameTime);\r\n\t\tImGui::Separator();\r\n\r\n\t\tImGui::Text(\"OpengGL vendor: %s\", vendor.c_str());\r\n\t\tImGui::Text(\"Internal renderer: %s\", renderer.c_str());\r\n\t\tImGui::Text(\"Versions: Driver: %s, GLSL: %s\", version.c_str(), shaderVersion.c_str());\r\n\t\tif(ImGui::CollapsingHeader(titleHeader.c_str())) {\r\n\t\t\tfor(const auto & ext : extensions) {\r\n\t\t\t\tImGui::Text(\"%s\", ext.c_str());\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tif(showImGuiDemo) {\r\n\t\t\tImGui::ShowDemoWindow();\r\n\t\t}\r\n\r\n\r\n\t}\r\n\r\n\treturn 0;\r\n}\r\n<commit_msg>Playground: update test loop.<commit_after>#include \"input\/Input.hpp\"\r\n#include \"input\/ControllableCamera.hpp\"\r\n#include \"resources\/ResourcesManager.hpp\"\r\n#include \"graphics\/GPU.hpp\"\r\n#include \"graphics\/Framebuffer.hpp\"\r\n#include \"system\/Config.hpp\"\r\n#include \"system\/System.hpp\"\r\n#include \"system\/Window.hpp\"\r\n#include \"generation\/Random.hpp\"\r\n#include \"Common.hpp\"\r\n\r\n\/**\r\n \\defgroup Playground Playground\r\n \\brief A basic playground for testing ideas.\r\n \\ingroup Applications\r\n *\/\r\n\r\n\/**\r\n The main function of the playground.\r\n \\param argc the number of input arguments.\r\n \\param argv a pointer to the raw input arguments.\r\n \\return a general error code.\r\n \\ingroup Playground\r\n *\/\r\nint main(int argc, char ** argv) {\r\n\r\n\t\/\/ First, init\/parse\/load configuration.\r\n\tRenderingConfig config(std::vector<std::string>(argv, argv + argc));\r\n\tif(config.showHelp()) {\r\n\t\treturn 0;\r\n\t}\r\n\r\n\tWindow window(\"Playground\", config, false);\r\n\t\r\n\tif(!config.resourcesPath.empty()){\r\n\t\tResources::manager().addResources(config.resourcesPath);\r\n\t}\r\n\t\r\n\t\/\/ Seed random generator.\r\n\tRandom::seed();\r\n\t\/\/ Query the renderer identifier, and the supported GPU API version.\r\n\tstd::string vendor, renderer, version, shaderVersion;\r\n\tGPU::deviceInfos(vendor, renderer, version, shaderVersion);\r\n\tLog::Info() << Log::GPU << \"Vendor: \" << vendor << \".\" << std::endl;\r\n\tLog::Info() << Log::GPU << \"Internal renderer: \" << renderer << \".\" << std::endl;\r\n\tLog::Info() << Log::GPU << \"Versions: Driver: \" << version << \", API: \" << shaderVersion << \".\" << std::endl;\r\n\r\n\t\/\/ Query the extensions.\r\n\tconst std::vector<std::string> extensions = GPU::supportedExtensions();\r\n\t\/\/ Log extensions.\r\n\tsize_t extensionCount = extensions.size();\r\n\tfor(const auto& ext : extensions){\r\n\t\tif(ext[0] == '-'){\r\n\t\t\t--extensionCount;\r\n\t\t}\r\n\t}\r\n\r\n\tif(!extensions.empty()) {\r\n\t\tLog::Info() << Log::GPU << \"Extensions detected (\" << extensionCount << \"): \" << std::endl;\r\n\t\tfor(size_t i = 0; i < extensions.size(); ++i) {\r\n\t\t\tconst bool isHeader = extensions[i][0] == '-';\r\n\t\t\tLog::Info() << (isHeader ? \"\\n\" : \"\") << extensions[i] << (isHeader ? \"\\n\" : \", \") << std::flush;\r\n\t\t}\r\n\t\tLog::Info() << std::endl;\r\n\t}\r\n\tconst std::string titleHeader = \"Extensions (\" + std::to_string(extensionCount) + \")\";\r\n\r\n\tGPU::setDepthState(true, TestFunction::LESS, true);\r\n\tGPU::setCullState(true, Faces::BACK);\r\n\tGPU::setBlendState(false);\r\n\r\n\t\/\/ Setup the timer.\r\n\tdouble timer\t\t = System::time();\r\n\tdouble fullTime\t\t = 0.0;\r\n\tdouble remainingTime = 0.0;\r\n\tconst double dt\t\t = 1.0 \/ 120.0; \/\/ Small physics timestep.\r\n\r\n\tProgram * program = Resources::manager().getProgram(\"object\", \"object_basic\", \"object_basic_random\");\r\n\tconst Mesh * mesh\t\t= Resources::manager().getMesh(\"light_sphere\", Storage::GPU);\r\n\r\n\tProgram * program2 = Resources::manager().getProgram(\"object_basic_color\");\r\n\tMesh mesh2(\"Plane\");\r\n\tmesh2.positions = {glm::vec3(-0.5f, -0.5f, 0.5f), glm::vec3(0.5f, -0.5f, 0.5f), glm::vec3(0.5f, 0.5f, 0.5f), glm::vec3(-0.5f, 0.5f, 0.5f)};\r\n\tmesh2.colors = {glm::vec3(1.0f, 0.0f, 0.0f), glm::vec3(0.0f, 1.0f, 0.0f), glm::vec3(0.0f, 0.0f, 1.0f), glm::vec3(0.0f, 0.0f, 0.0f)};\r\n\tmesh2.indices = {0, 1, 2, 0, 2, 3};\r\n\tmesh2.upload();\r\n\r\n\tMesh mesh3(\"Triangle\");\r\n\tmesh3.positions = {glm::vec3(-0.5f, -0.5f, 0.1f), glm::vec3(0.5f, -0.5f, 0.1f), glm::vec3(0.0f, 1.0f, 0.1f)};\r\n\tmesh3.colors = {glm::vec3(1.0f, 1.0f, 0.0f), glm::vec3(0.0f, 1.0f, 1.0f), glm::vec3(1.0f, 0.0f, 1.0f)};\r\n\tmesh3.indices = {0, 2, 1};\r\n\tmesh3.upload();\r\n\r\n\r\n\tControllableCamera camera;\r\n\r\n\tcamera.pose(glm::vec3(0.0f,0.0f,3.0f), glm::vec3(0.0f), glm::vec3(0.0f, 1.0f, 0.0f));\r\n\tcamera.projection(config.screenResolution[0] \/ config.screenResolution[1], 1.34f, 0.1f, 100.0f);\r\n\tbool showImGuiDemo = false;\r\n\r\n\tconst Texture* tex = Resources::manager().getTexture(\"debug-grid\", {Layout::RGBA16F, Filter::LINEAR_LINEAR, Wrap::CLAMP}, Storage::GPU);\r\n\r\n\tTexture tex2(\"textest\");\r\n\ttex2.width = tex2.height = 8;\r\n\ttex2.depth = tex2.levels = 1;\r\n\ttex2.shape = TextureShape::D2;\r\n\ttex2.images.emplace_back(tex2.width, tex2.height, 4);\r\n\tauto& texData = tex2.images.back();\r\n\r\n\r\n\r\n\tuint count = 0;\r\n\tDescriptor desc = {Layout::RGBA8, Filter::LINEAR, Wrap::CLAMP};\r\n\tFramebuffer fb(400, 300, desc , true, \"testfb\");\r\n\t\r\n\t\/\/ Start the display\/interaction loop.\r\n\twhile(window.nextFrame()) {\r\n\t\t\r\n\t\t\/\/ Reload resources.\r\n\t\tif(Input::manager().triggered(Input::Key::P)) {\r\n\t\t\tResources::manager().reload();\r\n\t\t}\r\n\r\n\t\t\/\/ Compute the time elapsed since last frame\r\n\t\tconst double currentTime = System::time();\r\n\t\tdouble frameTime\t\t = currentTime - timer;\r\n\t\ttimer\t\t\t\t\t = currentTime;\r\n\r\n\t\tcamera.update();\r\n\r\n\t\t\/\/ Physics simulation\r\n\t\t\/\/ First avoid super high frametime by clamping.\r\n\t\tif(frameTime > 0.2) {\r\n\t\t\tframeTime = 0.2;\r\n\t\t}\r\n\t\t\/\/ Accumulate new frame time.\r\n\t\tremainingTime += frameTime;\r\n\t\t\/\/ Instead of bounding at dt, we lower our requirement (1 order of magnitude).\r\n\t\twhile(remainingTime > 0.2 * dt) {\r\n\t\t\tdouble deltaTime = fmin(remainingTime, dt);\r\n\t\t\t\/\/ Update physics and camera.\r\n\t\t\tcamera.physics(deltaTime);\r\n\t\t\t\/\/ Update timers.\r\n\t\t\tfullTime += deltaTime;\r\n\t\t\tremainingTime -= deltaTime;\r\n\t\t}\r\n\r\n\t\tif(Input::manager().resized()){\r\n\t\t\tfb.resize(Input::manager().size());\r\n\t\t}\r\n\r\n\t\t\/\/ Render.\r\n\t\tconst glm::ivec2 screenSize = Input::manager().size();\r\n\t\tconst glm::mat4 MVP\t\t = camera.projection() * camera.view();\r\n\t\tfb.bind(glm::vec4(0.2f, 0.3f, 0.25f, 1.0f), 1.0f, Framebuffer::Operation::DONTCARE);\r\n\r\n\t\tfb.setViewport();\r\n\r\n\t\tprogram->use();\r\n\t\tprogram->uniform(\"mvp\", MVP);\r\n\t\t\/\/GPU::drawMesh(*mesh);\r\n\t\t\/\/GPU::setBlendState(true, BlendEquation::ADD, BlendFunction::SRC_ALPHA, BlendFunction::ONE_MINUS_SRC_ALPHA);\r\n\r\n\t\tfor(uint dy = 0; dy < tex2.height; ++dy){\r\n\t\t\tfor(uint dx = 0; dx < tex2.width; ++dx){\r\n\t\t\t\tfloat r = 0.0f; float g = 0.0f; float b = 0.0f;\r\n\t\t\t\tuint x = (dx + count)%8;\r\n\t\t\t\tuint y = (dy + count)%8;\r\n\t\t\t\tif(x < 2){\r\n\t\t\t\t\tr = 1.0f;\r\n\t\t\t\t} else if (x < 4){\r\n\t\t\t\t\tg = 1.0f;\r\n\t\t\t\t} else if(x < 6){\r\n\t\t\t\t\tb = 1.0f;\r\n\t\t\t\t}\r\n\t\t\t\tif(y < 2){\r\n\t\t\t\t\tb = 0.5f;\r\n\t\t\t\t} else if (y < 4){\r\n\t\t\t\t\tr = 0.5f;\r\n\t\t\t\t} else if(y < 6){\r\n\t\t\t\t\tg = 0.5f;\r\n\t\t\t\t}\r\n\t\t\t\tr = float(count % 60)\/60.0f;\r\n\t\t\t\ttexData.rgba(x,y) = glm::vec4(r,g,b,0.5f);\r\n\t\t\t}\r\n\t\t}\r\n\t\t++count;\r\n\t\ttex2.upload({Layout::RGBA32F, Filter::NEAREST_LINEAR, Wrap::CLAMP}, true);\r\n\r\n\t\tprogram2->use();\r\n\t\tprogram2->uniform(\"mvp\", MVP);\r\n\t\tprogram2->uniform(\"color\", glm::vec3(1.0f, 0.5f, 0.0f));\r\n\t\tprogram2->texture(tex, 0);\r\n\t\tGPU::drawMesh(mesh2);\r\n\t\t\/\/GPU::setCullState(true, Faces::BACK);\r\n\t\t\/\/GPU::setBlendState(false);\r\n\t\tfloat angle = float(count % 360)\/360.0 * glm::two_pi<float>();\r\n\t\tglm::mat3 rot = glm::mat3(glm::rotate(glm::mat4(1.0f), angle, glm::vec3(0.0f, 0.0f, 1.0f)));\r\n\r\n\t\tmesh3.positions.clear();\r\n\t\tmesh3.positions = {rot * glm::vec3(-0.5f, -0.5f, 0.1f), rot * glm::vec3(0.5f, -0.5f, 0.1f), rot * glm::vec3(0.0f, 1.0f, 0.1f)};\r\n\t\tmesh3.upload();\r\n\r\n\t\tprogram2->texture(tex2, 0);\r\n\t\tprogram2->uniform(\"color\", glm::vec3(0.0f, 0.5f, 1.0f));\r\n\t\tGPU::drawMesh(mesh3);\r\n\r\n\t\t\/\/GPU::setViewport(screenSize[0]\/2, 0, screenSize[0]\/2, screenSize[1]);\r\n\t\t\/\/GPU::drawMesh(mesh2);\r\n\t\t\/\/GPU::drawMesh(mesh3);\r\n\r\n\t\t\/\/Framebuffer::backbuffer()->bind(glm::vec4(1.0f, 0.5f, 0.2f, 1.0f), 1.0f, Framebuffer::Operation::DONTCARE);\r\n\t\t\/\/Framebuffer::backbuffer()->setViewport();\r\n\t\tGPU::blit(fb, *Framebuffer::backbuffer(), Filter::LINEAR);\r\n\r\n\r\n\t\tImGui::Text(\"ImGui is functional!\");\r\n\t\tImGui::SameLine();\r\n\t\tImGui::Checkbox(\"Show demo\", &showImGuiDemo);\r\n\t\tImGui::Text(\"%.1f ms, %.1f fps\", frameTime * 1000.0f, 1.0f\/frameTime);\r\n\t\tImGui::Separator();\r\n\r\n\t\tImGui::Text(\"OpengGL vendor: %s\", vendor.c_str());\r\n\t\tImGui::Text(\"Internal renderer: %s\", renderer.c_str());\r\n\t\tImGui::Text(\"Versions: Driver: %s, GLSL: %s\", version.c_str(), shaderVersion.c_str());\r\n\t\tif(ImGui::CollapsingHeader(titleHeader.c_str())) {\r\n\t\t\tfor(const auto & ext : extensions) {\r\n\t\t\t\tImGui::Text(\"%s\", ext.c_str());\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tif(showImGuiDemo) {\r\n\t\t\tImGui::ShowDemoWindow();\r\n\t\t}\r\n\r\n\r\n\t}\r\n\r\n\treturn 0;\r\n}\r\n<|endoftext|>"} {"text":"<commit_before><commit_msg>handle all kinds of condition entries correctly in the dialog<commit_after><|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2009 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/automation\/url_request_automation_job.h\"\n\n#include \"base\/message_loop.h\"\n#include \"base\/time.h\"\n#include \"chrome\/browser\/automation\/automation_resource_message_filter.h\"\n#include \"chrome\/browser\/renderer_host\/render_view_host.h\"\n#include \"chrome\/browser\/renderer_host\/resource_dispatcher_host.h\"\n#include \"chrome\/browser\/renderer_host\/resource_dispatcher_host_request_info.h\"\n#include \"chrome\/test\/automation\/automation_messages.h\"\n#include \"net\/base\/io_buffer.h\"\n#include \"net\/base\/net_errors.h\"\n#include \"net\/http\/http_util.h\"\n#include \"net\/url_request\/url_request.h\"\n#include \"net\/url_request\/url_request_context.h\"\n\nusing base::Time;\nusing base::TimeDelta;\n\n\/\/ The list of filtered headers that are removed from requests sent via\n\/\/ StartAsync(). These must be lower case.\nstatic const char* kFilteredHeaderStrings[] = {\n \"accept\",\n \"authorization\",\n \"cache-control\",\n \"connection\",\n \"cookie\",\n \"expect\",\n \"if-match\",\n \"if-modified-since\",\n \"if-none-match\",\n \"if-range\",\n \"if-unmodified-since\",\n \"max-forwards\",\n \"proxy-authorization\",\n \"te\",\n \"upgrade\",\n \"via\"\n};\n\n\/\/ This class manages the interception of network requests for automation.\n\/\/ It looks at the request, and creates an intercept job if it indicates\n\/\/ that it should use automation channel.\n\/\/ NOTE: All methods must be called on the IO thread.\nclass AutomationRequestInterceptor : public URLRequest::Interceptor {\n public:\n AutomationRequestInterceptor() {\n URLRequest::RegisterRequestInterceptor(this);\n }\n\n virtual ~AutomationRequestInterceptor() {\n URLRequest::UnregisterRequestInterceptor(this);\n }\n\n \/\/ URLRequest::Interceptor\n virtual URLRequestJob* MaybeIntercept(URLRequest* request);\n\n private:\n DISALLOW_COPY_AND_ASSIGN(AutomationRequestInterceptor);\n};\n\nURLRequestJob* AutomationRequestInterceptor::MaybeIntercept(\n URLRequest* request) {\n if (request->url().SchemeIs(\"http\") || request->url().SchemeIs(\"https\")) {\n ResourceDispatcherHostRequestInfo* request_info =\n ResourceDispatcherHost::InfoForRequest(request);\n if (request_info) {\n AutomationResourceMessageFilter::AutomationDetails details;\n if (AutomationResourceMessageFilter::LookupRegisteredRenderView(\n request_info->child_id(), request_info->route_id(), &details)) {\n URLRequestAutomationJob* job = new URLRequestAutomationJob(request,\n details.tab_handle, details.filter);\n return job;\n }\n }\n }\n\n return NULL;\n}\n\nstatic URLRequest::Interceptor* GetAutomationRequestInterceptor() {\n return Singleton<AutomationRequestInterceptor>::get();\n}\n\nint URLRequestAutomationJob::instance_count_ = 0;\n\nURLRequestAutomationJob::URLRequestAutomationJob(\n URLRequest* request, int tab, AutomationResourceMessageFilter* filter)\n : URLRequestJob(request), id_(0), tab_(tab), message_filter_(filter),\n pending_buf_size_(0), redirect_status_(0) {\n DLOG(INFO) << \"URLRequestAutomationJob create. Count: \" << ++instance_count_;\n if (message_filter_) {\n id_ = message_filter_->NewRequestId();\n DCHECK(id_);\n } else {\n NOTREACHED();\n }\n}\n\nURLRequestAutomationJob::~URLRequestAutomationJob() {\n DLOG(INFO) << \"URLRequestAutomationJob delete. Count: \" << --instance_count_;\n Cleanup();\n}\n\nbool URLRequestAutomationJob::InitializeInterceptor() {\n \/\/ AutomationRequestInterceptor will register itself when it\n \/\/ is first created.\n URLRequest::Interceptor* interceptor = GetAutomationRequestInterceptor();\n return (interceptor != NULL);\n}\n\n\/\/ URLRequestJob Implementation.\nvoid URLRequestAutomationJob::Start() {\n \/\/ Start reading asynchronously so that all error reporting and data\n \/\/ callbacks happen as they would for network requests.\n MessageLoop::current()->PostTask(FROM_HERE, NewRunnableMethod(\n this, &URLRequestAutomationJob::StartAsync));\n}\n\nvoid URLRequestAutomationJob::Kill() {\n if (message_filter_.get()) {\n message_filter_->Send(new AutomationMsg_RequestEnd(0, tab_, id_,\n URLRequestStatus(URLRequestStatus::CANCELED, 0)));\n }\n DisconnectFromMessageFilter();\n URLRequestJob::Kill();\n}\n\nbool URLRequestAutomationJob::ReadRawData(\n net::IOBuffer* buf, int buf_size, int* bytes_read) {\n DLOG(INFO) << \"URLRequestAutomationJob: \" <<\n request_->url().spec() << \" - read pending: \" << buf_size;\n pending_buf_ = buf;\n pending_buf_size_ = buf_size;\n\n message_filter_->Send(new AutomationMsg_RequestRead(0, tab_, id_,\n buf_size));\n SetStatus(URLRequestStatus(URLRequestStatus::IO_PENDING, 0));\n return false;\n}\n\nbool URLRequestAutomationJob::GetMimeType(std::string* mime_type) const {\n if (!mime_type_.empty()) {\n *mime_type = mime_type_;\n } else if (headers_) {\n headers_->GetMimeType(mime_type);\n }\n\n return (!mime_type->empty());\n}\n\nbool URLRequestAutomationJob::GetCharset(std::string* charset) {\n if (headers_)\n return headers_->GetCharset(charset);\n return false;\n}\n\nvoid URLRequestAutomationJob::GetResponseInfo(net::HttpResponseInfo* info) {\n if (headers_)\n info->headers = headers_;\n if (request_->url().SchemeIsSecure()) {\n \/\/ Make up a fake certificate for this response since we don't have\n \/\/ access to the real SSL info.\n const char* kCertIssuer = \"Chrome Internal\";\n const int kLifetimeDays = 100;\n\n info->ssl_info.cert =\n new net::X509Certificate(request_->url().GetWithEmptyPath().spec(),\n kCertIssuer,\n Time::Now(),\n Time::Now() +\n TimeDelta::FromDays(kLifetimeDays));\n info->ssl_info.cert_status = 0;\n info->ssl_info.security_bits = 0;\n }\n}\n\nint URLRequestAutomationJob::GetResponseCode() const {\n if (headers_)\n return headers_->response_code();\n\n static const int kDefaultResponseCode = 200;\n return kDefaultResponseCode;\n}\n\nbool URLRequestAutomationJob::IsRedirectResponse(\n GURL* location, int* http_status_code) {\n static const int kDefaultHttpRedirectResponseCode = 301;\n\n if (!redirect_url_.empty()) {\n DLOG_IF(ERROR, redirect_status_ == 0) << \"Missing redirect status?\";\n *http_status_code = redirect_status_ ? redirect_status_ :\n kDefaultHttpRedirectResponseCode;\n *location = GURL(redirect_url_);\n return true;\n } else {\n DCHECK(redirect_status_ == 0)\n << \"Unexpectedly have redirect status but no URL\";\n }\n\n return false;\n}\n\nint URLRequestAutomationJob::MayFilterMessage(const IPC::Message& message) {\n switch (message.type()) {\n case AutomationMsg_RequestStarted::ID:\n case AutomationMsg_RequestData::ID:\n case AutomationMsg_RequestEnd::ID: {\n void* iter = NULL;\n int tab = 0;\n int id = 0;\n if (message.ReadInt(&iter, &tab) && message.ReadInt(&iter, &id)) {\n DCHECK(id);\n return id;\n }\n break;\n }\n }\n\n return 0;\n}\n\nvoid URLRequestAutomationJob::OnMessage(const IPC::Message& message) {\n IPC_BEGIN_MESSAGE_MAP(URLRequestAutomationJob, message)\n IPC_MESSAGE_HANDLER(AutomationMsg_RequestStarted, OnRequestStarted)\n IPC_MESSAGE_HANDLER(AutomationMsg_RequestData, OnDataAvailable)\n IPC_MESSAGE_HANDLER(AutomationMsg_RequestEnd, OnRequestEnd)\n IPC_END_MESSAGE_MAP()\n}\n\nvoid URLRequestAutomationJob::OnRequestStarted(\n int tab, int id, const IPC::AutomationURLResponse& response) {\n DLOG(INFO) << \"URLRequestAutomationJob: \" <<\n request_->url().spec() << \" - response started.\";\n set_expected_content_size(response.content_length);\n mime_type_ = response.mime_type;\n\n redirect_url_ = response.redirect_url;\n redirect_status_ = response.redirect_status;\n DCHECK(redirect_status_ == 0 || redirect_status_ == 200 ||\n (redirect_status_ >= 300 && redirect_status_ < 400));\n\n GURL url_for_cookies =\n GURL(redirect_url_.empty() ? request_->url().spec().c_str() :\n redirect_url_.c_str());\n\n URLRequestContext* ctx = request_->context();\n\n if (!response.headers.empty()) {\n headers_ = new net::HttpResponseHeaders(\n net::HttpUtil::AssembleRawHeaders(response.headers.data(),\n response.headers.size()));\n \/\/ Parse and set HTTP cookies.\n const std::string name = \"Set-Cookie\";\n std::string value;\n std::vector<std::string> response_cookies;\n\n void* iter = NULL;\n while (headers_->EnumerateHeader(&iter, name, &value)) {\n if (request_->context()->InterceptCookie(request_, &value))\n response_cookies.push_back(value);\n }\n\n if (response_cookies.size()) {\n if (ctx && ctx->cookie_store() &&\n ctx->cookie_policy()->CanSetCookie(\n url_for_cookies, request_->first_party_for_cookies())) {\n net::CookieOptions options;\n options.set_include_httponly();\n ctx->cookie_store()->SetCookiesWithOptions(url_for_cookies,\n response_cookies,\n options);\n }\n }\n }\n\n if (ctx && ctx->cookie_store() && !response.persistent_cookies.empty() &&\n ctx->cookie_policy()->CanSetCookie(\n url_for_cookies, request_->first_party_for_cookies())) {\n StringTokenizer cookie_parser(response.persistent_cookies, \";\");\n\n while (cookie_parser.GetNext()) {\n net::CookieOptions options;\n ctx->cookie_store()->SetCookieWithOptions(url_for_cookies,\n cookie_parser.token(),\n options);\n }\n }\n\n NotifyHeadersComplete();\n}\n\nvoid URLRequestAutomationJob::OnDataAvailable(\n int tab, int id, const std::string& bytes) {\n DLOG(INFO) << \"URLRequestAutomationJob: \" <<\n request_->url().spec() << \" - data available, Size: \" << bytes.size();\n DCHECK(!bytes.empty());\n\n \/\/ The request completed, and we have all the data.\n \/\/ Clear any IO pending status.\n SetStatus(URLRequestStatus());\n\n if (pending_buf_ && pending_buf_->data()) {\n DCHECK_GE(pending_buf_size_, bytes.size());\n const int bytes_to_copy = std::min(bytes.size(), pending_buf_size_);\n memcpy(pending_buf_->data(), &bytes[0], bytes_to_copy);\n\n pending_buf_ = NULL;\n pending_buf_size_ = 0;\n\n NotifyReadComplete(bytes_to_copy);\n }\n}\n\nvoid URLRequestAutomationJob::OnRequestEnd(\n int tab, int id, const URLRequestStatus& status) {\n DLOG(INFO) << \"URLRequestAutomationJob: \" <<\n request_->url().spec() << \" - request end. Status: \" << status.status();\n\n \/\/ TODO(tommi): When we hit certificate errors, notify the delegate via\n \/\/ OnSSLCertificateError(). Right now we don't have the certificate\n \/\/ so we don't. We could possibly call OnSSLCertificateError with a NULL\n \/\/ certificate, but I'm not sure if all implementations expect it.\n \/\/ if (status.status() == URLRequestStatus::FAILED &&\n \/\/ net::IsCertificateError(status.os_error()) && request_->delegate()) {\n \/\/ request_->delegate()->OnSSLCertificateError(request_, status.os_error(),\n \/\/ NULL);\n \/\/ }\n\n DisconnectFromMessageFilter();\n NotifyDone(status);\n\n \/\/ Reset any pending reads.\n if (pending_buf_) {\n pending_buf_ = NULL;\n pending_buf_size_ = 0;\n NotifyReadComplete(0);\n }\n}\n\nvoid URLRequestAutomationJob::Cleanup() {\n headers_ = NULL;\n mime_type_.erase();\n\n id_ = 0;\n tab_ = 0;\n\n DCHECK(message_filter_ == NULL);\n DisconnectFromMessageFilter();\n\n pending_buf_ = NULL;\n pending_buf_size_ = 0;\n}\n\nvoid URLRequestAutomationJob::StartAsync() {\n DLOG(INFO) << \"URLRequestAutomationJob: start request: \" <<\n (request_ ? request_->url().spec() : \"NULL request\");\n\n \/\/ If the job is cancelled before we got a chance to start it\n \/\/ we have nothing much to do here.\n if (is_done())\n return;\n\n if (!request_) {\n NotifyStartError(URLRequestStatus(URLRequestStatus::FAILED,\n net::ERR_FAILED));\n return;\n }\n\n \/\/ Register this request with automation message filter.\n message_filter_->RegisterRequest(this);\n\n \/\/ Strip unwanted headers.\n std::string new_request_headers(\n net::HttpUtil::StripHeaders(request_->extra_request_headers(),\n kFilteredHeaderStrings,\n arraysize(kFilteredHeaderStrings)));\n\n \/\/ Ensure that we do not send username and password fields in the referrer.\n GURL referrer(request_->GetSanitizedReferrer());\n\n \/\/ The referrer header must be suppressed if the preceding URL was\n \/\/ a secure one and the new one is not.\n if (referrer.SchemeIsSecure() && !request_->url().SchemeIsSecure()) {\n DLOG(INFO) <<\n \"Suppressing referrer header since going from secure to non-secure\";\n referrer = GURL();\n }\n\n \/\/ Ask automation to start this request.\n IPC::AutomationURLRequest automation_request = {\n request_->url().spec(),\n request_->method(),\n referrer.spec(),\n new_request_headers,\n request_->get_upload()\n };\n\n DCHECK(message_filter_);\n message_filter_->Send(new AutomationMsg_RequestStart(0, tab_, id_,\n automation_request));\n}\n\nvoid URLRequestAutomationJob::DisconnectFromMessageFilter() {\n if (message_filter_) {\n message_filter_->UnRegisterRequest(this);\n message_filter_ = NULL;\n }\n}\n<commit_msg>Fix a dlog that could dereference a null pointer.<commit_after>\/\/ Copyright (c) 2009 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/automation\/url_request_automation_job.h\"\n\n#include \"base\/message_loop.h\"\n#include \"base\/time.h\"\n#include \"chrome\/browser\/automation\/automation_resource_message_filter.h\"\n#include \"chrome\/browser\/renderer_host\/render_view_host.h\"\n#include \"chrome\/browser\/renderer_host\/resource_dispatcher_host.h\"\n#include \"chrome\/browser\/renderer_host\/resource_dispatcher_host_request_info.h\"\n#include \"chrome\/test\/automation\/automation_messages.h\"\n#include \"net\/base\/io_buffer.h\"\n#include \"net\/base\/net_errors.h\"\n#include \"net\/http\/http_util.h\"\n#include \"net\/url_request\/url_request.h\"\n#include \"net\/url_request\/url_request_context.h\"\n\nusing base::Time;\nusing base::TimeDelta;\n\n\/\/ The list of filtered headers that are removed from requests sent via\n\/\/ StartAsync(). These must be lower case.\nstatic const char* kFilteredHeaderStrings[] = {\n \"accept\",\n \"authorization\",\n \"cache-control\",\n \"connection\",\n \"cookie\",\n \"expect\",\n \"if-match\",\n \"if-modified-since\",\n \"if-none-match\",\n \"if-range\",\n \"if-unmodified-since\",\n \"max-forwards\",\n \"proxy-authorization\",\n \"te\",\n \"upgrade\",\n \"via\"\n};\n\n\/\/ This class manages the interception of network requests for automation.\n\/\/ It looks at the request, and creates an intercept job if it indicates\n\/\/ that it should use automation channel.\n\/\/ NOTE: All methods must be called on the IO thread.\nclass AutomationRequestInterceptor : public URLRequest::Interceptor {\n public:\n AutomationRequestInterceptor() {\n URLRequest::RegisterRequestInterceptor(this);\n }\n\n virtual ~AutomationRequestInterceptor() {\n URLRequest::UnregisterRequestInterceptor(this);\n }\n\n \/\/ URLRequest::Interceptor\n virtual URLRequestJob* MaybeIntercept(URLRequest* request);\n\n private:\n DISALLOW_COPY_AND_ASSIGN(AutomationRequestInterceptor);\n};\n\nURLRequestJob* AutomationRequestInterceptor::MaybeIntercept(\n URLRequest* request) {\n if (request->url().SchemeIs(\"http\") || request->url().SchemeIs(\"https\")) {\n ResourceDispatcherHostRequestInfo* request_info =\n ResourceDispatcherHost::InfoForRequest(request);\n if (request_info) {\n AutomationResourceMessageFilter::AutomationDetails details;\n if (AutomationResourceMessageFilter::LookupRegisteredRenderView(\n request_info->child_id(), request_info->route_id(), &details)) {\n URLRequestAutomationJob* job = new URLRequestAutomationJob(request,\n details.tab_handle, details.filter);\n return job;\n }\n }\n }\n\n return NULL;\n}\n\nstatic URLRequest::Interceptor* GetAutomationRequestInterceptor() {\n return Singleton<AutomationRequestInterceptor>::get();\n}\n\nint URLRequestAutomationJob::instance_count_ = 0;\n\nURLRequestAutomationJob::URLRequestAutomationJob(\n URLRequest* request, int tab, AutomationResourceMessageFilter* filter)\n : URLRequestJob(request), id_(0), tab_(tab), message_filter_(filter),\n pending_buf_size_(0), redirect_status_(0) {\n DLOG(INFO) << \"URLRequestAutomationJob create. Count: \" << ++instance_count_;\n if (message_filter_) {\n id_ = message_filter_->NewRequestId();\n DCHECK(id_);\n } else {\n NOTREACHED();\n }\n}\n\nURLRequestAutomationJob::~URLRequestAutomationJob() {\n DLOG(INFO) << \"URLRequestAutomationJob delete. Count: \" << --instance_count_;\n Cleanup();\n}\n\nbool URLRequestAutomationJob::InitializeInterceptor() {\n \/\/ AutomationRequestInterceptor will register itself when it\n \/\/ is first created.\n URLRequest::Interceptor* interceptor = GetAutomationRequestInterceptor();\n return (interceptor != NULL);\n}\n\n\/\/ URLRequestJob Implementation.\nvoid URLRequestAutomationJob::Start() {\n \/\/ Start reading asynchronously so that all error reporting and data\n \/\/ callbacks happen as they would for network requests.\n MessageLoop::current()->PostTask(FROM_HERE, NewRunnableMethod(\n this, &URLRequestAutomationJob::StartAsync));\n}\n\nvoid URLRequestAutomationJob::Kill() {\n if (message_filter_.get()) {\n message_filter_->Send(new AutomationMsg_RequestEnd(0, tab_, id_,\n URLRequestStatus(URLRequestStatus::CANCELED, 0)));\n }\n DisconnectFromMessageFilter();\n URLRequestJob::Kill();\n}\n\nbool URLRequestAutomationJob::ReadRawData(\n net::IOBuffer* buf, int buf_size, int* bytes_read) {\n DLOG(INFO) << \"URLRequestAutomationJob: \" <<\n request_->url().spec() << \" - read pending: \" << buf_size;\n pending_buf_ = buf;\n pending_buf_size_ = buf_size;\n\n message_filter_->Send(new AutomationMsg_RequestRead(0, tab_, id_,\n buf_size));\n SetStatus(URLRequestStatus(URLRequestStatus::IO_PENDING, 0));\n return false;\n}\n\nbool URLRequestAutomationJob::GetMimeType(std::string* mime_type) const {\n if (!mime_type_.empty()) {\n *mime_type = mime_type_;\n } else if (headers_) {\n headers_->GetMimeType(mime_type);\n }\n\n return (!mime_type->empty());\n}\n\nbool URLRequestAutomationJob::GetCharset(std::string* charset) {\n if (headers_)\n return headers_->GetCharset(charset);\n return false;\n}\n\nvoid URLRequestAutomationJob::GetResponseInfo(net::HttpResponseInfo* info) {\n if (headers_)\n info->headers = headers_;\n if (request_->url().SchemeIsSecure()) {\n \/\/ Make up a fake certificate for this response since we don't have\n \/\/ access to the real SSL info.\n const char* kCertIssuer = \"Chrome Internal\";\n const int kLifetimeDays = 100;\n\n info->ssl_info.cert =\n new net::X509Certificate(request_->url().GetWithEmptyPath().spec(),\n kCertIssuer,\n Time::Now(),\n Time::Now() +\n TimeDelta::FromDays(kLifetimeDays));\n info->ssl_info.cert_status = 0;\n info->ssl_info.security_bits = 0;\n }\n}\n\nint URLRequestAutomationJob::GetResponseCode() const {\n if (headers_)\n return headers_->response_code();\n\n static const int kDefaultResponseCode = 200;\n return kDefaultResponseCode;\n}\n\nbool URLRequestAutomationJob::IsRedirectResponse(\n GURL* location, int* http_status_code) {\n static const int kDefaultHttpRedirectResponseCode = 301;\n\n if (!redirect_url_.empty()) {\n DLOG_IF(ERROR, redirect_status_ == 0) << \"Missing redirect status?\";\n *http_status_code = redirect_status_ ? redirect_status_ :\n kDefaultHttpRedirectResponseCode;\n *location = GURL(redirect_url_);\n return true;\n } else {\n DCHECK(redirect_status_ == 0)\n << \"Unexpectedly have redirect status but no URL\";\n }\n\n return false;\n}\n\nint URLRequestAutomationJob::MayFilterMessage(const IPC::Message& message) {\n switch (message.type()) {\n case AutomationMsg_RequestStarted::ID:\n case AutomationMsg_RequestData::ID:\n case AutomationMsg_RequestEnd::ID: {\n void* iter = NULL;\n int tab = 0;\n int id = 0;\n if (message.ReadInt(&iter, &tab) && message.ReadInt(&iter, &id)) {\n DCHECK(id);\n return id;\n }\n break;\n }\n }\n\n return 0;\n}\n\nvoid URLRequestAutomationJob::OnMessage(const IPC::Message& message) {\n IPC_BEGIN_MESSAGE_MAP(URLRequestAutomationJob, message)\n IPC_MESSAGE_HANDLER(AutomationMsg_RequestStarted, OnRequestStarted)\n IPC_MESSAGE_HANDLER(AutomationMsg_RequestData, OnDataAvailable)\n IPC_MESSAGE_HANDLER(AutomationMsg_RequestEnd, OnRequestEnd)\n IPC_END_MESSAGE_MAP()\n}\n\nvoid URLRequestAutomationJob::OnRequestStarted(\n int tab, int id, const IPC::AutomationURLResponse& response) {\n DLOG(INFO) << \"URLRequestAutomationJob: \" <<\n request_->url().spec() << \" - response started.\";\n set_expected_content_size(response.content_length);\n mime_type_ = response.mime_type;\n\n redirect_url_ = response.redirect_url;\n redirect_status_ = response.redirect_status;\n DCHECK(redirect_status_ == 0 || redirect_status_ == 200 ||\n (redirect_status_ >= 300 && redirect_status_ < 400));\n\n GURL url_for_cookies =\n GURL(redirect_url_.empty() ? request_->url().spec().c_str() :\n redirect_url_.c_str());\n\n URLRequestContext* ctx = request_->context();\n\n if (!response.headers.empty()) {\n headers_ = new net::HttpResponseHeaders(\n net::HttpUtil::AssembleRawHeaders(response.headers.data(),\n response.headers.size()));\n \/\/ Parse and set HTTP cookies.\n const std::string name = \"Set-Cookie\";\n std::string value;\n std::vector<std::string> response_cookies;\n\n void* iter = NULL;\n while (headers_->EnumerateHeader(&iter, name, &value)) {\n if (request_->context()->InterceptCookie(request_, &value))\n response_cookies.push_back(value);\n }\n\n if (response_cookies.size()) {\n if (ctx && ctx->cookie_store() &&\n ctx->cookie_policy()->CanSetCookie(\n url_for_cookies, request_->first_party_for_cookies())) {\n net::CookieOptions options;\n options.set_include_httponly();\n ctx->cookie_store()->SetCookiesWithOptions(url_for_cookies,\n response_cookies,\n options);\n }\n }\n }\n\n if (ctx && ctx->cookie_store() && !response.persistent_cookies.empty() &&\n ctx->cookie_policy()->CanSetCookie(\n url_for_cookies, request_->first_party_for_cookies())) {\n StringTokenizer cookie_parser(response.persistent_cookies, \";\");\n\n while (cookie_parser.GetNext()) {\n net::CookieOptions options;\n ctx->cookie_store()->SetCookieWithOptions(url_for_cookies,\n cookie_parser.token(),\n options);\n }\n }\n\n NotifyHeadersComplete();\n}\n\nvoid URLRequestAutomationJob::OnDataAvailable(\n int tab, int id, const std::string& bytes) {\n DLOG(INFO) << \"URLRequestAutomationJob: \" <<\n request_->url().spec() << \" - data available, Size: \" << bytes.size();\n DCHECK(!bytes.empty());\n\n \/\/ The request completed, and we have all the data.\n \/\/ Clear any IO pending status.\n SetStatus(URLRequestStatus());\n\n if (pending_buf_ && pending_buf_->data()) {\n DCHECK_GE(pending_buf_size_, bytes.size());\n const int bytes_to_copy = std::min(bytes.size(), pending_buf_size_);\n memcpy(pending_buf_->data(), &bytes[0], bytes_to_copy);\n\n pending_buf_ = NULL;\n pending_buf_size_ = 0;\n\n NotifyReadComplete(bytes_to_copy);\n }\n}\n\nvoid URLRequestAutomationJob::OnRequestEnd(\n int tab, int id, const URLRequestStatus& status) {\n DLOG(INFO) << \"URLRequestAutomationJob: \"\n << request_ ? request_->url().spec().c_str() : \"(null)\"\n << \" - request end. Status: \" << status.status();\n\n \/\/ TODO(tommi): When we hit certificate errors, notify the delegate via\n \/\/ OnSSLCertificateError(). Right now we don't have the certificate\n \/\/ so we don't. We could possibly call OnSSLCertificateError with a NULL\n \/\/ certificate, but I'm not sure if all implementations expect it.\n \/\/ if (status.status() == URLRequestStatus::FAILED &&\n \/\/ net::IsCertificateError(status.os_error()) && request_->delegate()) {\n \/\/ request_->delegate()->OnSSLCertificateError(request_, status.os_error(),\n \/\/ NULL);\n \/\/ }\n\n DisconnectFromMessageFilter();\n NotifyDone(status);\n\n \/\/ Reset any pending reads.\n if (pending_buf_) {\n pending_buf_ = NULL;\n pending_buf_size_ = 0;\n NotifyReadComplete(0);\n }\n}\n\nvoid URLRequestAutomationJob::Cleanup() {\n headers_ = NULL;\n mime_type_.erase();\n\n id_ = 0;\n tab_ = 0;\n\n DCHECK(message_filter_ == NULL);\n DisconnectFromMessageFilter();\n\n pending_buf_ = NULL;\n pending_buf_size_ = 0;\n}\n\nvoid URLRequestAutomationJob::StartAsync() {\n DLOG(INFO) << \"URLRequestAutomationJob: start request: \" <<\n (request_ ? request_->url().spec() : \"NULL request\");\n\n \/\/ If the job is cancelled before we got a chance to start it\n \/\/ we have nothing much to do here.\n if (is_done())\n return;\n\n if (!request_) {\n NotifyStartError(URLRequestStatus(URLRequestStatus::FAILED,\n net::ERR_FAILED));\n return;\n }\n\n \/\/ Register this request with automation message filter.\n message_filter_->RegisterRequest(this);\n\n \/\/ Strip unwanted headers.\n std::string new_request_headers(\n net::HttpUtil::StripHeaders(request_->extra_request_headers(),\n kFilteredHeaderStrings,\n arraysize(kFilteredHeaderStrings)));\n\n \/\/ Ensure that we do not send username and password fields in the referrer.\n GURL referrer(request_->GetSanitizedReferrer());\n\n \/\/ The referrer header must be suppressed if the preceding URL was\n \/\/ a secure one and the new one is not.\n if (referrer.SchemeIsSecure() && !request_->url().SchemeIsSecure()) {\n DLOG(INFO) <<\n \"Suppressing referrer header since going from secure to non-secure\";\n referrer = GURL();\n }\n\n \/\/ Ask automation to start this request.\n IPC::AutomationURLRequest automation_request = {\n request_->url().spec(),\n request_->method(),\n referrer.spec(),\n new_request_headers,\n request_->get_upload()\n };\n\n DCHECK(message_filter_);\n message_filter_->Send(new AutomationMsg_RequestStart(0, tab_, id_,\n automation_request));\n}\n\nvoid URLRequestAutomationJob::DisconnectFromMessageFilter() {\n if (message_filter_) {\n message_filter_->UnRegisterRequest(this);\n message_filter_ = NULL;\n }\n}\n<|endoftext|>"} {"text":"<commit_before><commit_msg>cairo_restore without matching cairo_save<commit_after><|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2009 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"base\/ref_counted.h\"\n#include \"chrome\/browser\/browser.h\"\n#include \"chrome\/browser\/renderer_host\/render_view_host.h\"\n#include \"chrome\/browser\/extensions\/autoupdate_interceptor.h\"\n#include \"chrome\/browser\/extensions\/extension_browsertest.h\"\n#include \"chrome\/browser\/extensions\/extension_host.h\"\n#include \"chrome\/browser\/extensions\/extensions_service.h\"\n#include \"chrome\/browser\/extensions\/extension_updater.h\"\n#include \"chrome\/browser\/profile.h\"\n#include \"chrome\/browser\/tab_contents\/tab_contents.h\"\n#include \"chrome\/common\/notification_service.h\"\n#include \"chrome\/common\/url_constants.h\"\n#include \"chrome\/test\/ui_test_utils.h\"\n\nclass ExtensionManagementTest : public ExtensionBrowserTest {\n protected:\n \/\/ Helper method that returns whether the extension is at the given version.\n \/\/ This calls version(), which must be defined in the extension's bg page,\n \/\/ as well as asking the extension itself.\n bool IsExtensionAtVersion(Extension* extension,\n const std::string& expected_version) {\n \/\/ Test that the extension's version from the manifest and reported by the\n \/\/ background page is correct. This is to ensure that the processes are in\n \/\/ sync with the Extension.\n ExtensionProcessManager* manager = browser()->profile()->\n GetExtensionProcessManager();\n ExtensionHost* ext_host = manager->GetBackgroundHostForExtension(extension);\n EXPECT_TRUE(ext_host);\n if (!ext_host)\n return false;\n\n std::string version_from_bg;\n bool exec = ui_test_utils::ExecuteJavaScriptAndExtractString(\n ext_host->render_view_host(), L\"\", L\"version()\", &version_from_bg);\n EXPECT_TRUE(exec);\n if (!exec)\n return false;\n\n if (version_from_bg != expected_version ||\n extension->VersionString() != expected_version)\n return false;\n return true;\n }\n\n \/\/ Helper method that installs a low permission extension then updates\n \/\/ to the second version requiring increased permissions. Returns whether\n \/\/ the operation was completed successfully.\n bool InstallAndUpdateIncreasingPermissionsExtension() {\n ExtensionsService* service = browser()->profile()->GetExtensionsService();\n TabContents* contents = browser()->GetSelectedTabContents();\n if (service->HasInstalledExtensions() || !contents)\n return false;\n\n \/\/ Install the initial version, which should happen just fine.\n if (!InstallExtension(\n test_data_dir_.AppendASCII(\"permissions-low-v1.crx\"), 1))\n return false;\n EXPECT_EQ(0, contents->infobar_delegate_count());\n\n \/\/ Upgrade to a version that wants more permissions. We should disable the\n \/\/ extension and prompt the user to reenable.\n if (service->extensions()->size() != 1u)\n return false;\n if (!UpdateExtension(\n service->extensions()->at(0)->id(),\n test_data_dir_.AppendASCII(\"permissions-high-v2.crx\"), -1))\n return false;\n EXPECT_EQ(1, contents->infobar_delegate_count());\n EXPECT_EQ(0u, service->extensions()->size());\n if (service->disabled_extensions()->size() != 1u)\n return false;\n return true;\n }\n};\n\n\/\/ Tests that installing the same version does not overwrite.\nIN_PROC_BROWSER_TEST_F(ExtensionManagementTest, InstallSameVersion) {\n ExtensionsService* service = browser()->profile()->GetExtensionsService();\n ASSERT_FALSE(service->HasInstalledExtensions());\n ASSERT_TRUE(InstallExtension(\n test_data_dir_.AppendASCII(\"install\/install.crx\"), 1));\n\n \/\/ Install an extension with the same version. The previous install should\n \/\/ be kept.\n ASSERT_TRUE(InstallExtension(\n test_data_dir_.AppendASCII(\"install\/install_same_version.crx\"), 0));\n EXPECT_TRUE(IsExtensionAtVersion(service->extensions()->at(0), \"1.0\"));\n}\n\nIN_PROC_BROWSER_TEST_F(ExtensionManagementTest, InstallOlderVersion) {\n ExtensionsService* service = browser()->profile()->GetExtensionsService();\n ASSERT_FALSE(service->HasInstalledExtensions());\n ASSERT_TRUE(InstallExtension(\n test_data_dir_.AppendASCII(\"install\/install.crx\"), 1));\n ASSERT_TRUE(InstallExtension(\n test_data_dir_.AppendASCII(\"install\/install_older_version.crx\"), 0));\n EXPECT_TRUE(IsExtensionAtVersion(service->extensions()->at(0), \"1.0\"));\n}\n\nIN_PROC_BROWSER_TEST_F(ExtensionManagementTest, InstallThenCancel) {\n ExtensionsService* service = browser()->profile()->GetExtensionsService();\n ASSERT_FALSE(service->HasInstalledExtensions());\n ASSERT_TRUE(InstallExtension(\n test_data_dir_.AppendASCII(\"install\/install.crx\"), 1));\n\n \/\/ Cancel this install.\n StartInstallButCancel(test_data_dir_.AppendASCII(\"install\/install_v2.crx\"));\n EXPECT_TRUE(IsExtensionAtVersion(service->extensions()->at(0), \"1.0\"));\n}\n\n\/\/ Tests that installing and uninstalling extensions don't crash with an\n\/\/ incognito window open.\nIN_PROC_BROWSER_TEST_F(ExtensionManagementTest, Incognito) {\n \/\/ Open an incognito window to the extensions management page. We just\n \/\/ want to make sure that we don't crash while playing with extensions when\n \/\/ this guy is around.\n ui_test_utils::OpenURLOffTheRecord(browser()->profile(),\n GURL(chrome::kChromeUIExtensionsURL));\n\n ASSERT_TRUE(InstallExtension(test_data_dir_.AppendASCII(\"good.crx\"), 1));\n UninstallExtension(\"ldnnhddmnhbkjipkidpdiheffobcpfmf\");\n}\n\n\/\/ Tests the process of updating an extension to one that requires higher\n\/\/ permissions.\nIN_PROC_BROWSER_TEST_F(ExtensionManagementTest, UpdatePermissions) {\n ExtensionsService* service = browser()->profile()->GetExtensionsService();\n ASSERT_TRUE(InstallAndUpdateIncreasingPermissionsExtension());\n\n \/\/ Now try reenabling it, which should also dismiss the infobar.\n service->EnableExtension(service->disabled_extensions()->at(0)->id());\n TabContents* contents = browser()->GetSelectedTabContents();\n ASSERT_TRUE(contents);\n EXPECT_EQ(0, contents->infobar_delegate_count());\n EXPECT_EQ(1u, service->extensions()->size());\n EXPECT_EQ(0u, service->disabled_extensions()->size());\n}\n\n\/\/ Tests that we can uninstall a disabled extension.\nIN_PROC_BROWSER_TEST_F(ExtensionManagementTest, UninstallDisabled) {\n ExtensionsService* service = browser()->profile()->GetExtensionsService();\n ASSERT_TRUE(InstallAndUpdateIncreasingPermissionsExtension());\n\n \/\/ Now try uninstalling it.\n UninstallExtension(service->disabled_extensions()->at(0)->id());\n EXPECT_EQ(0u, service->extensions()->size());\n EXPECT_EQ(0u, service->disabled_extensions()->size());\n ASSERT_FALSE(service->HasInstalledExtensions());\n}\n\n\/\/ Tests that disabling and re-enabling an extension works.\nIN_PROC_BROWSER_TEST_F(ExtensionManagementTest, DisableEnable) {\n ExtensionProcessManager* manager = browser()->profile()->\n GetExtensionProcessManager();\n ExtensionsService* service = browser()->profile()->GetExtensionsService();\n\n \/\/ Load an extension, expect the background page to be available.\n ASSERT_FALSE(service->HasInstalledExtensions());\n ASSERT_TRUE(LoadExtension(\n test_data_dir_.AppendASCII(\"good\").AppendASCII(\"Extensions\")\n .AppendASCII(\"bjafgdebaacbbbecmhlhpofkepfkgcpa\")\n .AppendASCII(\"1.0\")));\n ASSERT_EQ(1u, service->extensions()->size());\n EXPECT_EQ(0u, service->disabled_extensions()->size());\n Extension* extension = service->extensions()->at(0);\n EXPECT_TRUE(manager->GetBackgroundHostForExtension(extension));\n ASSERT_TRUE(service->HasInstalledExtensions());\n\n \/\/ After disabling, the background page should go away.\n service->DisableExtension(\"bjafgdebaacbbbecmhlhpofkepfkgcpa\");\n EXPECT_EQ(0u, service->extensions()->size());\n EXPECT_EQ(1u, service->disabled_extensions()->size());\n EXPECT_FALSE(manager->GetBackgroundHostForExtension(extension));\n ASSERT_TRUE(service->HasInstalledExtensions());\n\n \/\/ And bring it back.\n service->EnableExtension(\"bjafgdebaacbbbecmhlhpofkepfkgcpa\");\n EXPECT_EQ(1u, service->extensions()->size());\n EXPECT_EQ(0u, service->disabled_extensions()->size());\n EXPECT_TRUE(manager->GetBackgroundHostForExtension(extension));\n ASSERT_TRUE(service->HasInstalledExtensions());\n}\n\n\/\/ TODO(asargent): This test seems to crash on linux buildbots.\n\/\/ (http:\/\/crbug.com\/31737)\n#if !defined(OS_LINUX)\n\/\/ Tests extension autoupdate.\nIN_PROC_BROWSER_TEST_F(ExtensionManagementTest, AutoUpdate) {\n FilePath basedir = test_data_dir_.AppendASCII(\"autoupdate\");\n \/\/ Note: This interceptor gets requests on the IO thread.\n scoped_refptr<AutoUpdateInterceptor> interceptor(new AutoUpdateInterceptor());\n URLFetcher::enable_interception_for_tests(true);\n\n interceptor->SetResponseOnIOThread(\"http:\/\/localhost\/autoupdate\/manifest\",\n basedir.AppendASCII(\"manifest_v2.xml\"));\n interceptor->SetResponseOnIOThread(\"http:\/\/localhost\/autoupdate\/v2.crx\",\n basedir.AppendASCII(\"v2.crx\"));\n\n \/\/ Install version 1 of the extension.\n ExtensionsService* service = browser()->profile()->GetExtensionsService();\n ASSERT_FALSE(service->HasInstalledExtensions());\n ASSERT_TRUE(InstallExtension(basedir.AppendASCII(\"v1.crx\"), 1));\n const ExtensionList* extensions = service->extensions();\n ASSERT_TRUE(service->HasInstalledExtensions());\n ASSERT_EQ(1u, extensions->size());\n ASSERT_EQ(\"ogjcoiohnmldgjemafoockdghcjciccf\", extensions->at(0)->id());\n ASSERT_EQ(\"1.0\", extensions->at(0)->VersionString());\n\n \/\/ We don't want autoupdate blacklist checks.\n service->updater()->set_blacklist_checks_enabled(false);\n\n \/\/ Run autoupdate and make sure version 2 of the extension was installed.\n service->updater()->CheckNow();\n ASSERT_TRUE(WaitForExtensionInstall());\n extensions = service->extensions();\n ASSERT_EQ(1u, extensions->size());\n ASSERT_EQ(\"ogjcoiohnmldgjemafoockdghcjciccf\", extensions->at(0)->id());\n ASSERT_EQ(\"2.0\", extensions->at(0)->VersionString());\n\n \/\/ Now try doing an update to version 3, which has been incorrectly\n \/\/ signed. This should fail.\n interceptor->SetResponseOnIOThread(\"http:\/\/localhost\/autoupdate\/manifest\",\n basedir.AppendASCII(\"manifest_v3.xml\"));\n interceptor->SetResponseOnIOThread(\"http:\/\/localhost\/autoupdate\/v3.crx\",\n basedir.AppendASCII(\"v3.crx\"));\n\n service->updater()->CheckNow();\n ASSERT_TRUE(WaitForExtensionInstallError());\n\n \/\/ Make sure the extension state is the same as before.\n extensions = service->extensions();\n ASSERT_EQ(1u, extensions->size());\n ASSERT_EQ(\"ogjcoiohnmldgjemafoockdghcjciccf\", extensions->at(0)->id());\n ASSERT_EQ(\"2.0\", extensions->at(0)->VersionString());\n}\n#endif \/\/ !defined(OS_LINUX)\n<commit_msg>Disable UninstallDisabled and UpdatePermissions temporarily. BUG=none TEST=none TBR=asargent Review URL: http:\/\/codereview.chromium.org\/552077<commit_after>\/\/ Copyright (c) 2009 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"base\/ref_counted.h\"\n#include \"chrome\/browser\/browser.h\"\n#include \"chrome\/browser\/renderer_host\/render_view_host.h\"\n#include \"chrome\/browser\/extensions\/autoupdate_interceptor.h\"\n#include \"chrome\/browser\/extensions\/extension_browsertest.h\"\n#include \"chrome\/browser\/extensions\/extension_host.h\"\n#include \"chrome\/browser\/extensions\/extensions_service.h\"\n#include \"chrome\/browser\/extensions\/extension_updater.h\"\n#include \"chrome\/browser\/profile.h\"\n#include \"chrome\/browser\/tab_contents\/tab_contents.h\"\n#include \"chrome\/common\/notification_service.h\"\n#include \"chrome\/common\/url_constants.h\"\n#include \"chrome\/test\/ui_test_utils.h\"\n\nclass ExtensionManagementTest : public ExtensionBrowserTest {\n protected:\n \/\/ Helper method that returns whether the extension is at the given version.\n \/\/ This calls version(), which must be defined in the extension's bg page,\n \/\/ as well as asking the extension itself.\n bool IsExtensionAtVersion(Extension* extension,\n const std::string& expected_version) {\n \/\/ Test that the extension's version from the manifest and reported by the\n \/\/ background page is correct. This is to ensure that the processes are in\n \/\/ sync with the Extension.\n ExtensionProcessManager* manager = browser()->profile()->\n GetExtensionProcessManager();\n ExtensionHost* ext_host = manager->GetBackgroundHostForExtension(extension);\n EXPECT_TRUE(ext_host);\n if (!ext_host)\n return false;\n\n std::string version_from_bg;\n bool exec = ui_test_utils::ExecuteJavaScriptAndExtractString(\n ext_host->render_view_host(), L\"\", L\"version()\", &version_from_bg);\n EXPECT_TRUE(exec);\n if (!exec)\n return false;\n\n if (version_from_bg != expected_version ||\n extension->VersionString() != expected_version)\n return false;\n return true;\n }\n\n \/\/ Helper method that installs a low permission extension then updates\n \/\/ to the second version requiring increased permissions. Returns whether\n \/\/ the operation was completed successfully.\n bool InstallAndUpdateIncreasingPermissionsExtension() {\n ExtensionsService* service = browser()->profile()->GetExtensionsService();\n TabContents* contents = browser()->GetSelectedTabContents();\n if (service->HasInstalledExtensions() || !contents)\n return false;\n\n \/\/ Install the initial version, which should happen just fine.\n if (!InstallExtension(\n test_data_dir_.AppendASCII(\"permissions-low-v1.crx\"), 1))\n return false;\n EXPECT_EQ(0, contents->infobar_delegate_count());\n\n \/\/ Upgrade to a version that wants more permissions. We should disable the\n \/\/ extension and prompt the user to reenable.\n if (service->extensions()->size() != 1u)\n return false;\n if (!UpdateExtension(\n service->extensions()->at(0)->id(),\n test_data_dir_.AppendASCII(\"permissions-high-v2.crx\"), -1))\n return false;\n EXPECT_EQ(1, contents->infobar_delegate_count());\n EXPECT_EQ(0u, service->extensions()->size());\n if (service->disabled_extensions()->size() != 1u)\n return false;\n return true;\n }\n};\n\n\/\/ Tests that installing the same version does not overwrite.\nIN_PROC_BROWSER_TEST_F(ExtensionManagementTest, InstallSameVersion) {\n ExtensionsService* service = browser()->profile()->GetExtensionsService();\n ASSERT_FALSE(service->HasInstalledExtensions());\n ASSERT_TRUE(InstallExtension(\n test_data_dir_.AppendASCII(\"install\/install.crx\"), 1));\n\n \/\/ Install an extension with the same version. The previous install should\n \/\/ be kept.\n ASSERT_TRUE(InstallExtension(\n test_data_dir_.AppendASCII(\"install\/install_same_version.crx\"), 0));\n EXPECT_TRUE(IsExtensionAtVersion(service->extensions()->at(0), \"1.0\"));\n}\n\nIN_PROC_BROWSER_TEST_F(ExtensionManagementTest, InstallOlderVersion) {\n ExtensionsService* service = browser()->profile()->GetExtensionsService();\n ASSERT_FALSE(service->HasInstalledExtensions());\n ASSERT_TRUE(InstallExtension(\n test_data_dir_.AppendASCII(\"install\/install.crx\"), 1));\n ASSERT_TRUE(InstallExtension(\n test_data_dir_.AppendASCII(\"install\/install_older_version.crx\"), 0));\n EXPECT_TRUE(IsExtensionAtVersion(service->extensions()->at(0), \"1.0\"));\n}\n\nIN_PROC_BROWSER_TEST_F(ExtensionManagementTest, InstallThenCancel) {\n ExtensionsService* service = browser()->profile()->GetExtensionsService();\n ASSERT_FALSE(service->HasInstalledExtensions());\n ASSERT_TRUE(InstallExtension(\n test_data_dir_.AppendASCII(\"install\/install.crx\"), 1));\n\n \/\/ Cancel this install.\n StartInstallButCancel(test_data_dir_.AppendASCII(\"install\/install_v2.crx\"));\n EXPECT_TRUE(IsExtensionAtVersion(service->extensions()->at(0), \"1.0\"));\n}\n\n\/\/ Tests that installing and uninstalling extensions don't crash with an\n\/\/ incognito window open.\nIN_PROC_BROWSER_TEST_F(ExtensionManagementTest, Incognito) {\n \/\/ Open an incognito window to the extensions management page. We just\n \/\/ want to make sure that we don't crash while playing with extensions when\n \/\/ this guy is around.\n ui_test_utils::OpenURLOffTheRecord(browser()->profile(),\n GURL(chrome::kChromeUIExtensionsURL));\n\n ASSERT_TRUE(InstallExtension(test_data_dir_.AppendASCII(\"good.crx\"), 1));\n UninstallExtension(\"ldnnhddmnhbkjipkidpdiheffobcpfmf\");\n}\n\n\/\/ Tests the process of updating an extension to one that requires higher\n\/\/ permissions.\nIN_PROC_BROWSER_TEST_F(ExtensionManagementTest, DISABLED_UpdatePermissions) {\n ExtensionsService* service = browser()->profile()->GetExtensionsService();\n ASSERT_TRUE(InstallAndUpdateIncreasingPermissionsExtension());\n\n \/\/ Now try reenabling it, which should also dismiss the infobar.\n service->EnableExtension(service->disabled_extensions()->at(0)->id());\n TabContents* contents = browser()->GetSelectedTabContents();\n ASSERT_TRUE(contents);\n EXPECT_EQ(0, contents->infobar_delegate_count());\n EXPECT_EQ(1u, service->extensions()->size());\n EXPECT_EQ(0u, service->disabled_extensions()->size());\n}\n\n\/\/ Tests that we can uninstall a disabled extension.\nIN_PROC_BROWSER_TEST_F(ExtensionManagementTest, DISABLED_UninstallDisabled) {\n ExtensionsService* service = browser()->profile()->GetExtensionsService();\n ASSERT_TRUE(InstallAndUpdateIncreasingPermissionsExtension());\n\n \/\/ Now try uninstalling it.\n UninstallExtension(service->disabled_extensions()->at(0)->id());\n EXPECT_EQ(0u, service->extensions()->size());\n EXPECT_EQ(0u, service->disabled_extensions()->size());\n ASSERT_FALSE(service->HasInstalledExtensions());\n}\n\n\/\/ Tests that disabling and re-enabling an extension works.\nIN_PROC_BROWSER_TEST_F(ExtensionManagementTest, DisableEnable) {\n ExtensionProcessManager* manager = browser()->profile()->\n GetExtensionProcessManager();\n ExtensionsService* service = browser()->profile()->GetExtensionsService();\n\n \/\/ Load an extension, expect the background page to be available.\n ASSERT_FALSE(service->HasInstalledExtensions());\n ASSERT_TRUE(LoadExtension(\n test_data_dir_.AppendASCII(\"good\").AppendASCII(\"Extensions\")\n .AppendASCII(\"bjafgdebaacbbbecmhlhpofkepfkgcpa\")\n .AppendASCII(\"1.0\")));\n ASSERT_EQ(1u, service->extensions()->size());\n EXPECT_EQ(0u, service->disabled_extensions()->size());\n Extension* extension = service->extensions()->at(0);\n EXPECT_TRUE(manager->GetBackgroundHostForExtension(extension));\n ASSERT_TRUE(service->HasInstalledExtensions());\n\n \/\/ After disabling, the background page should go away.\n service->DisableExtension(\"bjafgdebaacbbbecmhlhpofkepfkgcpa\");\n EXPECT_EQ(0u, service->extensions()->size());\n EXPECT_EQ(1u, service->disabled_extensions()->size());\n EXPECT_FALSE(manager->GetBackgroundHostForExtension(extension));\n ASSERT_TRUE(service->HasInstalledExtensions());\n\n \/\/ And bring it back.\n service->EnableExtension(\"bjafgdebaacbbbecmhlhpofkepfkgcpa\");\n EXPECT_EQ(1u, service->extensions()->size());\n EXPECT_EQ(0u, service->disabled_extensions()->size());\n EXPECT_TRUE(manager->GetBackgroundHostForExtension(extension));\n ASSERT_TRUE(service->HasInstalledExtensions());\n}\n\n\/\/ TODO(asargent): This test seems to crash on linux buildbots.\n\/\/ (http:\/\/crbug.com\/31737)\n#if !defined(OS_LINUX)\n\/\/ Tests extension autoupdate.\nIN_PROC_BROWSER_TEST_F(ExtensionManagementTest, AutoUpdate) {\n FilePath basedir = test_data_dir_.AppendASCII(\"autoupdate\");\n \/\/ Note: This interceptor gets requests on the IO thread.\n scoped_refptr<AutoUpdateInterceptor> interceptor(new AutoUpdateInterceptor());\n URLFetcher::enable_interception_for_tests(true);\n\n interceptor->SetResponseOnIOThread(\"http:\/\/localhost\/autoupdate\/manifest\",\n basedir.AppendASCII(\"manifest_v2.xml\"));\n interceptor->SetResponseOnIOThread(\"http:\/\/localhost\/autoupdate\/v2.crx\",\n basedir.AppendASCII(\"v2.crx\"));\n\n \/\/ Install version 1 of the extension.\n ExtensionsService* service = browser()->profile()->GetExtensionsService();\n ASSERT_FALSE(service->HasInstalledExtensions());\n ASSERT_TRUE(InstallExtension(basedir.AppendASCII(\"v1.crx\"), 1));\n const ExtensionList* extensions = service->extensions();\n ASSERT_TRUE(service->HasInstalledExtensions());\n ASSERT_EQ(1u, extensions->size());\n ASSERT_EQ(\"ogjcoiohnmldgjemafoockdghcjciccf\", extensions->at(0)->id());\n ASSERT_EQ(\"1.0\", extensions->at(0)->VersionString());\n\n \/\/ We don't want autoupdate blacklist checks.\n service->updater()->set_blacklist_checks_enabled(false);\n\n \/\/ Run autoupdate and make sure version 2 of the extension was installed.\n service->updater()->CheckNow();\n ASSERT_TRUE(WaitForExtensionInstall());\n extensions = service->extensions();\n ASSERT_EQ(1u, extensions->size());\n ASSERT_EQ(\"ogjcoiohnmldgjemafoockdghcjciccf\", extensions->at(0)->id());\n ASSERT_EQ(\"2.0\", extensions->at(0)->VersionString());\n\n \/\/ Now try doing an update to version 3, which has been incorrectly\n \/\/ signed. This should fail.\n interceptor->SetResponseOnIOThread(\"http:\/\/localhost\/autoupdate\/manifest\",\n basedir.AppendASCII(\"manifest_v3.xml\"));\n interceptor->SetResponseOnIOThread(\"http:\/\/localhost\/autoupdate\/v3.crx\",\n basedir.AppendASCII(\"v3.crx\"));\n\n service->updater()->CheckNow();\n ASSERT_TRUE(WaitForExtensionInstallError());\n\n \/\/ Make sure the extension state is the same as before.\n extensions = service->extensions();\n ASSERT_EQ(1u, extensions->size());\n ASSERT_EQ(\"ogjcoiohnmldgjemafoockdghcjciccf\", extensions->at(0)->id());\n ASSERT_EQ(\"2.0\", extensions->at(0)->VersionString());\n}\n#endif \/\/ !defined(OS_LINUX)\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 2015 Cryptonomex, Inc., and contributors.\n *\n * The MIT License\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n *\/\n\n#include <algorithm>\n#include <iomanip>\n#include <iostream>\n#include <iterator>\n\n#include <fc\/io\/json.hpp>\n#include <fc\/io\/stdio.hpp>\n#include <fc\/network\/http\/server.hpp>\n#include <fc\/network\/http\/websocket.hpp>\n#include <fc\/rpc\/cli.hpp>\n#include <fc\/rpc\/http_api.hpp>\n#include <fc\/rpc\/websocket_api.hpp>\n#include <fc\/smart_ref_impl.hpp>\n\n#include <graphene\/app\/api.hpp>\n#include <graphene\/chain\/protocol\/protocol.hpp>\n#include <graphene\/egenesis\/egenesis.hpp>\n#include <graphene\/utilities\/key_conversion.hpp>\n#include <graphene\/wallet\/wallet.hpp>\n\n#include <fc\/interprocess\/signals.hpp>\n#include <boost\/program_options.hpp>\n\n#include <fc\/log\/console_appender.hpp>\n#include <fc\/log\/file_appender.hpp>\n#include <fc\/log\/logger.hpp>\n#include <fc\/log\/logger_config.hpp>\n\n#ifdef WIN32\n# include <signal.h>\n#else\n# include <csignal>\n#endif\n\nusing namespace graphene::app;\nusing namespace graphene::chain;\nusing namespace graphene::utilities;\nusing namespace graphene::wallet;\nusing namespace std;\nnamespace bpo = boost::program_options;\n\nint main( int argc, char** argv )\n{\n try {\n\n boost::program_options::options_description opts;\n opts.add_options()\n (\"help,h\", \"Print this help message and exit.\")\n (\"server-rpc-endpoint,s\", bpo::value<string>()->implicit_value(\"ws:\/\/127.0.0.1:8090\"), \"Server websocket RPC endpoint\")\n (\"server-rpc-user,u\", bpo::value<string>(), \"Server Username\")\n (\"server-rpc-password,p\", bpo::value<string>(), \"Server Password\")\n (\"rpc-endpoint,r\", bpo::value<string>()->implicit_value(\"127.0.0.1:8091\"), \"Endpoint for wallet websocket RPC to listen on\")\n (\"rpc-tls-endpoint,t\", bpo::value<string>()->implicit_value(\"127.0.0.1:8092\"), \"Endpoint for wallet websocket TLS RPC to listen on\")\n (\"rpc-tls-certificate,c\", bpo::value<string>()->implicit_value(\"server.pem\"), \"PEM certificate for wallet websocket TLS RPC\")\n (\"rpc-http-endpoint,H\", bpo::value<string>()->implicit_value(\"127.0.0.1:8093\"), \"Endpoint for wallet HTTP RPC to listen on\")\n (\"daemon,d\", \"Run the wallet in daemon mode\" )\n (\"wallet-file,w\", bpo::value<string>()->implicit_value(\"wallet.json\"), \"wallet to load\")\n (\"chain-id\", bpo::value<string>(), \"chain ID to connect to\");\n\n bpo::variables_map options;\n\n bpo::store( bpo::parse_command_line(argc, argv, opts), options );\n\n if( options.count(\"help\") )\n {\n std::cout << opts << \"\\n\";\n return 0;\n }\n\n fc::path data_dir;\n fc::logging_config cfg;\n fc::path log_dir = data_dir \/ \"logs\";\n\n fc::file_appender::config ac;\n ac.filename = log_dir \/ \"rpc\" \/ \"rpc.log\";\n ac.flush = true;\n ac.rotate = true;\n ac.rotation_interval = fc::hours( 1 );\n ac.rotation_limit = fc::days( 1 );\n\n std::cout << \"Logging RPC to file: \" << (data_dir \/ ac.filename).preferred_string() << \"\\n\";\n\n cfg.appenders.push_back(fc::appender_config( \"default\", \"console\", fc::variant(fc::console_appender::config())));\n cfg.appenders.push_back(fc::appender_config( \"rpc\", \"file\", fc::variant(ac)));\n\n cfg.loggers = { fc::logger_config(\"default\"), fc::logger_config( \"rpc\") };\n cfg.loggers.front().level = fc::log_level::info;\n cfg.loggers.front().appenders = {\"default\"};\n cfg.loggers.back().level = fc::log_level::debug;\n cfg.loggers.back().appenders = {\"rpc\"};\n\n \/\/fc::configure_logging( cfg );\n\n fc::ecc::private_key committee_private_key = fc::ecc::private_key::regenerate(fc::sha256::hash(string(\"null_key\")));\n\n idump( (key_to_wif( committee_private_key ) ) );\n\n fc::ecc::private_key nathan_private_key = fc::ecc::private_key::regenerate(fc::sha256::hash(string(\"nathan\")));\n public_key_type nathan_pub_key = nathan_private_key.get_public_key();\n idump( (nathan_pub_key) );\n idump( (key_to_wif( nathan_private_key ) ) );\n\n \/\/\n \/\/ TODO: We read wallet_data twice, once in main() to grab the\n \/\/ socket info, again in wallet_api when we do\n \/\/ load_wallet_file(). Seems like this could be better\n \/\/ designed.\n \/\/\n wallet_data wdata;\n\n fc::path wallet_file( options.count(\"wallet-file\") ? options.at(\"wallet-file\").as<string>() : \"wallet.json\");\n if( fc::exists( wallet_file ) )\n {\n wdata = fc::json::from_file( wallet_file ).as<wallet_data>();\n if( options.count(\"chain-id\") )\n {\n \/\/ the --chain-id on the CLI must match the chain ID embedded in the wallet file\n if( chain_id_type(options.at(\"chain-id\").as<std::string>()) != wdata.chain_id )\n {\n std::cout << \"Chain ID in wallet file does not match specified chain ID\\n\";\n return 1;\n }\n }\n }\n else\n {\n if( options.count(\"chain-id\") )\n {\n wdata.chain_id = chain_id_type(options.at(\"chain-id\").as<std::string>());\n std::cout << \"Starting a new wallet with chain ID \" << wdata.chain_id.str() << \" (from CLI)\\n\";\n }\n else\n {\n wdata.chain_id = graphene::egenesis::get_egenesis_chain_id();\n std::cout << \"Starting a new wallet with chain ID \" << wdata.chain_id.str() << \" (from egenesis)\\n\";\n }\n }\n\n \/\/ but allow CLI to override\n if( options.count(\"server-rpc-endpoint\") )\n wdata.ws_server = options.at(\"server-rpc-endpoint\").as<std::string>();\n if( options.count(\"server-rpc-user\") )\n wdata.ws_user = options.at(\"server-rpc-user\").as<std::string>();\n if( options.count(\"server-rpc-password\") )\n wdata.ws_password = options.at(\"server-rpc-password\").as<std::string>();\n\n fc::http::websocket_client client;\n idump((wdata.ws_server));\n auto con = client.connect( wdata.ws_server );\n auto apic = std::make_shared<fc::rpc::websocket_api_connection>(*con);\n\n auto remote_api = apic->get_remote_api< login_api >(1);\n edump((wdata.ws_user)(wdata.ws_password) );\n \/\/ TODO: Error message here\n FC_ASSERT( remote_api->login( wdata.ws_user, wdata.ws_password ) );\n\n auto wapiptr = std::make_shared<wallet_api>( wdata, remote_api );\n wapiptr->set_wallet_filename( wallet_file.generic_string() );\n wapiptr->load_wallet_file();\n\n fc::api<wallet_api> wapi(wapiptr);\n\n auto wallet_cli = std::make_shared<fc::rpc::cli>();\n for( auto& name_formatter : wapiptr->get_result_formatters() )\n wallet_cli->format_result( name_formatter.first, name_formatter.second );\n\n boost::signals2::scoped_connection closed_connection(con->closed.connect([=]{\n cerr << \"Server has disconnected us.\\n\";\n wallet_cli->stop();\n }));\n (void)(closed_connection);\n\n if( wapiptr->is_new() )\n {\n std::cout << \"Please use the set_password method to initialize a new wallet before continuing\\n\";\n wallet_cli->set_prompt( \"new >>> \" );\n } else\n wallet_cli->set_prompt( \"locked >>> \" );\n\n boost::signals2::scoped_connection locked_connection(wapiptr->lock_changed.connect([&](bool locked) {\n wallet_cli->set_prompt( locked ? \"locked >>> \" : \"unlocked >>> \" );\n }));\n\n auto _websocket_server = std::make_shared<fc::http::websocket_server>();\n if( options.count(\"rpc-endpoint\") )\n {\n _websocket_server->on_connection([&]( const fc::http::websocket_connection_ptr& c ){\n std::cout << \"here... \\n\";\n wlog(\".\" );\n auto wsc = std::make_shared<fc::rpc::websocket_api_connection>(*c);\n wsc->register_api(wapi);\n c->set_session_data( wsc );\n });\n ilog( \"Listening for incoming RPC requests on ${p}\", (\"p\", options.at(\"rpc-endpoint\").as<string>() ));\n _websocket_server->listen( fc::ip::endpoint::from_string(options.at(\"rpc-endpoint\").as<string>()) );\n _websocket_server->start_accept();\n }\n\n string cert_pem = \"server.pem\";\n if( options.count( \"rpc-tls-certificate\" ) )\n cert_pem = options.at(\"rpc-tls-certificate\").as<string>();\n\n auto _websocket_tls_server = std::make_shared<fc::http::websocket_tls_server>(cert_pem);\n if( options.count(\"rpc-tls-endpoint\") )\n {\n _websocket_tls_server->on_connection([&]( const fc::http::websocket_connection_ptr& c ){\n auto wsc = std::make_shared<fc::rpc::websocket_api_connection>(*c);\n wsc->register_api(wapi);\n c->set_session_data( wsc );\n });\n ilog( \"Listening for incoming TLS RPC requests on ${p}\", (\"p\", options.at(\"rpc-tls-endpoint\").as<string>() ));\n _websocket_tls_server->listen( fc::ip::endpoint::from_string(options.at(\"rpc-tls-endpoint\").as<string>()) );\n _websocket_tls_server->start_accept();\n }\n\n auto _http_server = std::make_shared<fc::http::server>();\n if( options.count(\"rpc-http-endpoint\" ) )\n {\n ilog( \"Listening for incoming HTTP RPC requests on ${p}\", (\"p\", options.at(\"rpc-http-endpoint\").as<string>() ) );\n _http_server->listen( fc::ip::endpoint::from_string( options.at( \"rpc-http-endpoint\" ).as<string>() ) );\n \/\/\n \/\/ due to implementation, on_request() must come AFTER listen()\n \/\/\n _http_server->on_request(\n [&]( const fc::http::request& req, const fc::http::server::response& resp )\n {\n std::shared_ptr< fc::rpc::http_api_connection > conn =\n std::make_shared< fc::rpc::http_api_connection>();\n conn->register_api( wapi );\n conn->on_request( req, resp );\n } );\n }\n\n if( !options.count( \"daemon\" ) )\n {\n wallet_cli->register_api( wapi );\n wallet_cli->start();\n wallet_cli->wait();\n }\n else\n {\n fc::promise<int>::ptr exit_promise = new fc::promise<int>(\"UNIX Signal Handler\");\n fc::set_signal_handler([&exit_promise](int signal) {\n exit_promise->set_value(signal);\n }, SIGINT);\n\n ilog( \"Entering Daemon Mode, ^C to exit\" );\n exit_promise->wait();\n }\n\n wapi->save_wallet_file(wallet_file.generic_string());\n locked_connection.disconnect();\n closed_connection.disconnect();\n }\n catch ( const fc::exception& e )\n {\n std::cout << e.to_detail_string() << \"\\n\";\n return -1;\n }\n return 0;\n}\n<commit_msg>change default cli_wallet rpc port to 9090<commit_after>\/*\n * Copyright (c) 2015 Cryptonomex, Inc., and contributors.\n *\n * The MIT License\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n *\/\n\n#include <algorithm>\n#include <iomanip>\n#include <iostream>\n#include <iterator>\n\n#include <fc\/io\/json.hpp>\n#include <fc\/io\/stdio.hpp>\n#include <fc\/network\/http\/server.hpp>\n#include <fc\/network\/http\/websocket.hpp>\n#include <fc\/rpc\/cli.hpp>\n#include <fc\/rpc\/http_api.hpp>\n#include <fc\/rpc\/websocket_api.hpp>\n#include <fc\/smart_ref_impl.hpp>\n\n#include <graphene\/app\/api.hpp>\n#include <graphene\/chain\/protocol\/protocol.hpp>\n#include <graphene\/egenesis\/egenesis.hpp>\n#include <graphene\/utilities\/key_conversion.hpp>\n#include <graphene\/wallet\/wallet.hpp>\n\n#include <fc\/interprocess\/signals.hpp>\n#include <boost\/program_options.hpp>\n\n#include <fc\/log\/console_appender.hpp>\n#include <fc\/log\/file_appender.hpp>\n#include <fc\/log\/logger.hpp>\n#include <fc\/log\/logger_config.hpp>\n\n#ifdef WIN32\n# include <signal.h>\n#else\n# include <csignal>\n#endif\n\nusing namespace graphene::app;\nusing namespace graphene::chain;\nusing namespace graphene::utilities;\nusing namespace graphene::wallet;\nusing namespace std;\nnamespace bpo = boost::program_options;\n\nint main( int argc, char** argv )\n{\n try {\n\n boost::program_options::options_description opts;\n opts.add_options()\n (\"help,h\", \"Print this help message and exit.\")\n (\"server-rpc-endpoint,s\", bpo::value<string>()->implicit_value(\"ws:\/\/127.0.0.1:9090\"), \"Server websocket RPC endpoint\")\n (\"server-rpc-user,u\", bpo::value<string>(), \"Server Username\")\n (\"server-rpc-password,p\", bpo::value<string>(), \"Server Password\")\n (\"rpc-endpoint,r\", bpo::value<string>()->implicit_value(\"127.0.0.1:8091\"), \"Endpoint for wallet websocket RPC to listen on\")\n (\"rpc-tls-endpoint,t\", bpo::value<string>()->implicit_value(\"127.0.0.1:8092\"), \"Endpoint for wallet websocket TLS RPC to listen on\")\n (\"rpc-tls-certificate,c\", bpo::value<string>()->implicit_value(\"server.pem\"), \"PEM certificate for wallet websocket TLS RPC\")\n (\"rpc-http-endpoint,H\", bpo::value<string>()->implicit_value(\"127.0.0.1:8093\"), \"Endpoint for wallet HTTP RPC to listen on\")\n (\"daemon,d\", \"Run the wallet in daemon mode\" )\n (\"wallet-file,w\", bpo::value<string>()->implicit_value(\"wallet.json\"), \"wallet to load\")\n (\"chain-id\", bpo::value<string>(), \"chain ID to connect to\");\n\n bpo::variables_map options;\n\n bpo::store( bpo::parse_command_line(argc, argv, opts), options );\n\n if( options.count(\"help\") )\n {\n std::cout << opts << \"\\n\";\n return 0;\n }\n\n fc::path data_dir;\n fc::logging_config cfg;\n fc::path log_dir = data_dir \/ \"logs\";\n\n fc::file_appender::config ac;\n ac.filename = log_dir \/ \"rpc\" \/ \"rpc.log\";\n ac.flush = true;\n ac.rotate = true;\n ac.rotation_interval = fc::hours( 1 );\n ac.rotation_limit = fc::days( 1 );\n\n std::cout << \"Logging RPC to file: \" << (data_dir \/ ac.filename).preferred_string() << \"\\n\";\n\n cfg.appenders.push_back(fc::appender_config( \"default\", \"console\", fc::variant(fc::console_appender::config())));\n cfg.appenders.push_back(fc::appender_config( \"rpc\", \"file\", fc::variant(ac)));\n\n cfg.loggers = { fc::logger_config(\"default\"), fc::logger_config( \"rpc\") };\n cfg.loggers.front().level = fc::log_level::info;\n cfg.loggers.front().appenders = {\"default\"};\n cfg.loggers.back().level = fc::log_level::debug;\n cfg.loggers.back().appenders = {\"rpc\"};\n\n \/\/fc::configure_logging( cfg );\n\n fc::ecc::private_key committee_private_key = fc::ecc::private_key::regenerate(fc::sha256::hash(string(\"null_key\")));\n\n idump( (key_to_wif( committee_private_key ) ) );\n\n fc::ecc::private_key nathan_private_key = fc::ecc::private_key::regenerate(fc::sha256::hash(string(\"nathan\")));\n public_key_type nathan_pub_key = nathan_private_key.get_public_key();\n idump( (nathan_pub_key) );\n idump( (key_to_wif( nathan_private_key ) ) );\n\n \/\/\n \/\/ TODO: We read wallet_data twice, once in main() to grab the\n \/\/ socket info, again in wallet_api when we do\n \/\/ load_wallet_file(). Seems like this could be better\n \/\/ designed.\n \/\/\n wallet_data wdata;\n\n fc::path wallet_file( options.count(\"wallet-file\") ? options.at(\"wallet-file\").as<string>() : \"wallet.json\");\n if( fc::exists( wallet_file ) )\n {\n wdata = fc::json::from_file( wallet_file ).as<wallet_data>();\n if( options.count(\"chain-id\") )\n {\n \/\/ the --chain-id on the CLI must match the chain ID embedded in the wallet file\n if( chain_id_type(options.at(\"chain-id\").as<std::string>()) != wdata.chain_id )\n {\n std::cout << \"Chain ID in wallet file does not match specified chain ID\\n\";\n return 1;\n }\n }\n }\n else\n {\n if( options.count(\"chain-id\") )\n {\n wdata.chain_id = chain_id_type(options.at(\"chain-id\").as<std::string>());\n std::cout << \"Starting a new wallet with chain ID \" << wdata.chain_id.str() << \" (from CLI)\\n\";\n }\n else\n {\n wdata.chain_id = graphene::egenesis::get_egenesis_chain_id();\n std::cout << \"Starting a new wallet with chain ID \" << wdata.chain_id.str() << \" (from egenesis)\\n\";\n }\n }\n\n \/\/ but allow CLI to override\n if( options.count(\"server-rpc-endpoint\") )\n wdata.ws_server = options.at(\"server-rpc-endpoint\").as<std::string>();\n if( options.count(\"server-rpc-user\") )\n wdata.ws_user = options.at(\"server-rpc-user\").as<std::string>();\n if( options.count(\"server-rpc-password\") )\n wdata.ws_password = options.at(\"server-rpc-password\").as<std::string>();\n\n fc::http::websocket_client client;\n idump((wdata.ws_server));\n auto con = client.connect( wdata.ws_server );\n auto apic = std::make_shared<fc::rpc::websocket_api_connection>(*con);\n\n auto remote_api = apic->get_remote_api< login_api >(1);\n edump((wdata.ws_user)(wdata.ws_password) );\n \/\/ TODO: Error message here\n FC_ASSERT( remote_api->login( wdata.ws_user, wdata.ws_password ) );\n\n auto wapiptr = std::make_shared<wallet_api>( wdata, remote_api );\n wapiptr->set_wallet_filename( wallet_file.generic_string() );\n wapiptr->load_wallet_file();\n\n fc::api<wallet_api> wapi(wapiptr);\n\n auto wallet_cli = std::make_shared<fc::rpc::cli>();\n for( auto& name_formatter : wapiptr->get_result_formatters() )\n wallet_cli->format_result( name_formatter.first, name_formatter.second );\n\n boost::signals2::scoped_connection closed_connection(con->closed.connect([=]{\n cerr << \"Server has disconnected us.\\n\";\n wallet_cli->stop();\n }));\n (void)(closed_connection);\n\n if( wapiptr->is_new() )\n {\n std::cout << \"Please use the set_password method to initialize a new wallet before continuing\\n\";\n wallet_cli->set_prompt( \"new >>> \" );\n } else\n wallet_cli->set_prompt( \"locked >>> \" );\n\n boost::signals2::scoped_connection locked_connection(wapiptr->lock_changed.connect([&](bool locked) {\n wallet_cli->set_prompt( locked ? \"locked >>> \" : \"unlocked >>> \" );\n }));\n\n auto _websocket_server = std::make_shared<fc::http::websocket_server>();\n if( options.count(\"rpc-endpoint\") )\n {\n _websocket_server->on_connection([&]( const fc::http::websocket_connection_ptr& c ){\n std::cout << \"here... \\n\";\n wlog(\".\" );\n auto wsc = std::make_shared<fc::rpc::websocket_api_connection>(*c);\n wsc->register_api(wapi);\n c->set_session_data( wsc );\n });\n ilog( \"Listening for incoming RPC requests on ${p}\", (\"p\", options.at(\"rpc-endpoint\").as<string>() ));\n _websocket_server->listen( fc::ip::endpoint::from_string(options.at(\"rpc-endpoint\").as<string>()) );\n _websocket_server->start_accept();\n }\n\n string cert_pem = \"server.pem\";\n if( options.count( \"rpc-tls-certificate\" ) )\n cert_pem = options.at(\"rpc-tls-certificate\").as<string>();\n\n auto _websocket_tls_server = std::make_shared<fc::http::websocket_tls_server>(cert_pem);\n if( options.count(\"rpc-tls-endpoint\") )\n {\n _websocket_tls_server->on_connection([&]( const fc::http::websocket_connection_ptr& c ){\n auto wsc = std::make_shared<fc::rpc::websocket_api_connection>(*c);\n wsc->register_api(wapi);\n c->set_session_data( wsc );\n });\n ilog( \"Listening for incoming TLS RPC requests on ${p}\", (\"p\", options.at(\"rpc-tls-endpoint\").as<string>() ));\n _websocket_tls_server->listen( fc::ip::endpoint::from_string(options.at(\"rpc-tls-endpoint\").as<string>()) );\n _websocket_tls_server->start_accept();\n }\n\n auto _http_server = std::make_shared<fc::http::server>();\n if( options.count(\"rpc-http-endpoint\" ) )\n {\n ilog( \"Listening for incoming HTTP RPC requests on ${p}\", (\"p\", options.at(\"rpc-http-endpoint\").as<string>() ) );\n _http_server->listen( fc::ip::endpoint::from_string( options.at( \"rpc-http-endpoint\" ).as<string>() ) );\n \/\/\n \/\/ due to implementation, on_request() must come AFTER listen()\n \/\/\n _http_server->on_request(\n [&]( const fc::http::request& req, const fc::http::server::response& resp )\n {\n std::shared_ptr< fc::rpc::http_api_connection > conn =\n std::make_shared< fc::rpc::http_api_connection>();\n conn->register_api( wapi );\n conn->on_request( req, resp );\n } );\n }\n\n if( !options.count( \"daemon\" ) )\n {\n wallet_cli->register_api( wapi );\n wallet_cli->start();\n wallet_cli->wait();\n }\n else\n {\n fc::promise<int>::ptr exit_promise = new fc::promise<int>(\"UNIX Signal Handler\");\n fc::set_signal_handler([&exit_promise](int signal) {\n exit_promise->set_value(signal);\n }, SIGINT);\n\n ilog( \"Entering Daemon Mode, ^C to exit\" );\n exit_promise->wait();\n }\n\n wapi->save_wallet_file(wallet_file.generic_string());\n locked_connection.disconnect();\n closed_connection.disconnect();\n }\n catch ( const fc::exception& e )\n {\n std::cout << e.to_detail_string() << \"\\n\";\n return -1;\n }\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2011 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"base\/file_path.h\"\n#include \"base\/file_util.h\"\n#include \"base\/path_service.h\"\n#include \"base\/string_number_conversions.h\"\n#include \"base\/string_util.h\"\n#include \"testing\/gtest\/include\/gtest\/gtest.h\"\n#include \"v8\/include\/v8.h\"\n#include \"v8\/include\/v8-profiler.h\"\n#include \"webkit\/glue\/webkit_glue.h\"\n#include \"webkit\/tools\/test_shell\/test_shell.h\"\n#include \"webkit\/tools\/test_shell\/test_shell_test.h\"\n\nclass ListenerLeakTest : public TestShellTest {\n};\n\nstatic int GetNumObjects(const char* constructor) {\n v8::HandleScope scope;\n const v8::HeapSnapshot* snapshot =\n v8::HeapProfiler::TakeSnapshot(v8::String::New(\"\"),\n v8::HeapSnapshot::kFull);\n CHECK(snapshot);\n int count = 0;\n for (int i = 0; i < snapshot->GetNodesCount(); ++i) {\n const v8::HeapGraphNode* node = snapshot->GetNode(i);\n if (node->GetType() != v8::HeapGraphNode::kObject)\n continue;\n v8::String::AsciiValue node_name(node->GetName());\n if (strcmp(constructor, *node_name) == 0)\n ++count;\n }\n return count;\n}\n\n\/\/ This test tries to create a reference cycle between node and its listener.\n\/\/ See http:\/\/crbug\/17400.\nTEST_F(ListenerLeakTest, ReferenceCycle) {\n FilePath listener_file;\n ASSERT_TRUE(PathService::Get(base::DIR_SOURCE_ROOT, &listener_file));\n listener_file = listener_file.Append(FILE_PATH_LITERAL(\"webkit\"))\n .Append(FILE_PATH_LITERAL(\"data\"))\n .Append(FILE_PATH_LITERAL(\"listener\"))\n .Append(FILE_PATH_LITERAL(\"listener_leak1.html\"));\n test_shell_->LoadFile(listener_file);\n test_shell_->WaitTestFinished();\n ASSERT_EQ(0, GetNumObjects(\"EventListenerLeakTestObject1\"));\n}\n\n\/\/ This test sets node onclick many times to expose a possible memory\n\/\/ leak where all listeners get referenced by the node.\nTEST_F(ListenerLeakTest, HiddenReferences) {\n FilePath listener_file;\n ASSERT_TRUE(PathService::Get(base::DIR_SOURCE_ROOT, &listener_file));\n listener_file = listener_file.Append(FILE_PATH_LITERAL(\"webkit\"))\n .Append(FILE_PATH_LITERAL(\"data\"))\n .Append(FILE_PATH_LITERAL(\"listener\"))\n .Append(FILE_PATH_LITERAL(\"listener_leak2.html\"));\n test_shell_->LoadFile(listener_file);\n test_shell_->WaitTestFinished();\n ASSERT_EQ(1, GetNumObjects(\"EventListenerLeakTestObject2\"));\n}\n\n<commit_msg>Get ListenerLeakTests ready for V8's r9000.<commit_after>\/\/ Copyright (c) 2011 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"base\/file_path.h\"\n#include \"base\/file_util.h\"\n#include \"base\/path_service.h\"\n#include \"base\/string_number_conversions.h\"\n#include \"base\/string_util.h\"\n#include \"testing\/gtest\/include\/gtest\/gtest.h\"\n#include \"v8\/include\/v8.h\"\n#include \"v8\/include\/v8-profiler.h\"\n#include \"webkit\/glue\/webkit_glue.h\"\n#include \"webkit\/tools\/test_shell\/test_shell.h\"\n#include \"webkit\/tools\/test_shell\/test_shell_test.h\"\n\nclass ListenerLeakTest : public TestShellTest {\n};\n\nstatic const v8::HeapGraphNode* GetProperty(const v8::HeapGraphNode* node,\n v8::HeapGraphEdge::Type type,\n const char* name) {\n for (int i = 0, count = node->GetChildrenCount(); i < count; ++i) {\n const v8::HeapGraphEdge* prop = node->GetChild(i);\n if (prop->GetType() == type) {\n v8::String::AsciiValue prop_name(prop->GetName());\n if (strcmp(name, *prop_name) == 0) return prop->GetToNode();\n }\n }\n return NULL;\n}\n\nstatic int GetNumObjects(const char* constructor) {\n v8::HandleScope scope;\n const v8::HeapSnapshot* snapshot =\n v8::HeapProfiler::TakeSnapshot(v8::String::New(\"\"),\n v8::HeapSnapshot::kFull);\n CHECK(snapshot);\n int count = 0;\n for (int i = 0; i < snapshot->GetNodesCount(); ++i) {\n const v8::HeapGraphNode* node = snapshot->GetNode(i);\n if (node->GetType() != v8::HeapGraphNode::kObject) continue;\n v8::String::AsciiValue node_name(node->GetName());\n if (strcmp(constructor, *node_name) == 0) {\n const v8::HeapGraphNode* constructor_prop =\n GetProperty(node, v8::HeapGraphEdge::kProperty, \"constructor\");\n \/\/ Skip an Object instance named after the constructor.\n if (constructor_prop != NULL) {\n v8::String::AsciiValue constructor_name(constructor_prop->GetName());\n if (strcmp(constructor, *constructor_name) == 0) continue;\n }\n ++count;\n }\n }\n return count;\n}\n\n\/\/ This test tries to create a reference cycle between node and its listener.\n\/\/ See http:\/\/crbug\/17400.\nTEST_F(ListenerLeakTest, ReferenceCycle) {\n FilePath listener_file;\n ASSERT_TRUE(PathService::Get(base::DIR_SOURCE_ROOT, &listener_file));\n listener_file = listener_file.Append(FILE_PATH_LITERAL(\"webkit\"))\n .Append(FILE_PATH_LITERAL(\"data\"))\n .Append(FILE_PATH_LITERAL(\"listener\"))\n .Append(FILE_PATH_LITERAL(\"listener_leak1.html\"));\n test_shell_->LoadFile(listener_file);\n test_shell_->WaitTestFinished();\n ASSERT_EQ(0, GetNumObjects(\"EventListenerLeakTestObject1\"));\n}\n\n\/\/ This test sets node onclick many times to expose a possible memory\n\/\/ leak where all listeners get referenced by the node.\nTEST_F(ListenerLeakTest, HiddenReferences) {\n FilePath listener_file;\n ASSERT_TRUE(PathService::Get(base::DIR_SOURCE_ROOT, &listener_file));\n listener_file = listener_file.Append(FILE_PATH_LITERAL(\"webkit\"))\n .Append(FILE_PATH_LITERAL(\"data\"))\n .Append(FILE_PATH_LITERAL(\"listener\"))\n .Append(FILE_PATH_LITERAL(\"listener_leak2.html\"));\n test_shell_->LoadFile(listener_file);\n test_shell_->WaitTestFinished();\n ASSERT_EQ(1, GetNumObjects(\"EventListenerLeakTestObject2\"));\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (C) 2018 ScyllaDB\n *\/\n\n\/*\n * This file is part of Scylla.\n *\n * Scylla is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * Scylla is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with Scylla. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n\n#pragma once\n\n#include <type_traits>\n\n#include \"imr\/core.hh\"\n#include \"imr\/alloc.hh\"\n#include \"imr\/concepts.hh\"\n\nnamespace imr {\nnamespace utils {\n\nclass basic_object {\npublic:\n struct tags {\n class back_pointer { };\n class object { };\n };\nprotected:\n uint8_t* _data = nullptr;\n\n friend struct methods::mover<imr::tagged_type<tags::back_pointer, imr::pod<basic_object*>>>;\nprotected:\n explicit basic_object(uint8_t* ptr) noexcept : _data(ptr) { }\n\n void set_data(uint8_t* ptr) noexcept { _data = ptr; }\npublic:\n basic_object() = default;\n basic_object(basic_object&& other) noexcept : _data(std::exchange(other._data, nullptr)) { }\n basic_object(const basic_object&) = delete;\n};\n\ntemplate<typename Context, typename... State>\nclass object_context {\n std::tuple<State...> _state;\nprivate:\n template<size_t... Index>\n Context create(const uint8_t* ptr, std::index_sequence<Index...>) const noexcept {\n return Context(ptr, std::get<Index>(_state)...);\n }\npublic:\n object_context(const uint8_t*, State... state) : _state { state... } { }\n template<typename Tag, typename... Args>\n Context context_for(const uint8_t* ptr, Args&&... args) const noexcept {\n return create(ptr, std::index_sequence_for<State...>());\n }\n};\n\n}\n\nnamespace methods {\n\ntemplate<>\nstruct mover<imr::tagged_type<utils::basic_object::tags::back_pointer, imr::pod<utils::basic_object*>>> {\n static void run(uint8_t* ptr, ...) {\n auto bptr = imr::tagged_type<utils::basic_object::tags::back_pointer, imr::pod<utils::basic_object*>>::make_view(ptr).load();\n bptr->_data = ptr;\n }\n};\n\n}\n\nnamespace utils {\n\n\/\/\/ Unique pointer to an IMR object\n\/\/\/\n\/\/\/ This is an LSA-aware unique-owner pointer to an IMR object.\ntemplate<typename Structure>\nclass object : public basic_object {\npublic:\n using structure = imr::structure<\n imr::member<tags::back_pointer, imr::tagged_type<tags::back_pointer, imr::pod<basic_object*>>>,\n imr::member<tags::object, Structure>\n >;\n static constexpr size_t size_overhead = sizeof(basic_object*);\nprivate:\n explicit object(uint8_t* ptr) noexcept\n : basic_object(ptr)\n {\n structure::template get_member<tags::back_pointer>(_data).store(this);\n }\npublic:\n object() = default;\n object(object&& other) noexcept : basic_object(std::move(other)) {\n if (_data) {\n structure::template get_member<tags::back_pointer>(_data).store(this);\n }\n }\n\n object& operator=(object&& other) noexcept {\n swap(other);\n return *this;\n }\n\n ~object() {\n if (_data) {\n imr::methods::destroy<structure>(_data);\n current_allocator().free(_data);\n }\n }\n\n void swap(object& other) noexcept {\n std::swap(_data, other._data);\n if (_data) {\n structure::template get_member<tags::back_pointer>(_data).store(this);\n }\n if (other._data) {\n structure::template get_member<tags::back_pointer>(other._data).store(&other);\n }\n }\n\n explicit operator bool() const noexcept { return bool(_data); }\n\n uint8_t* get() noexcept { return _data ? _data + structure::template offset_of<tags::object>(_data) : nullptr; }\n const uint8_t* get() const noexcept { return _data ? _data + structure::template offset_of<tags::object>(_data) : nullptr; }\n\n \/\/\/ Creates an IMR object from a raw writer\n \/\/\/\n \/\/\/ This low-level function creates an IMR object owned by `object` using\n \/\/\/ a raw writer (i.e. does not necessarily follow the standard IMR\n \/\/\/ serialisation process). This is useful for fast copying of trivial\n \/\/\/ IMR objects.\n \/\/\/\n \/\/\/ \\note This function could be deprecated once the IMR starts supporting\n \/\/\/ copying IMR objects.\n template<typename RawWriter>\n GCC6_CONCEPT(requires requires (RawWriter wr, uint8_t* ptr) {\n { wr(ptr) } noexcept;\n })\n static object make_raw(size_t len, RawWriter&& wr, allocation_strategy::migrate_fn migrate = &imr::alloc::default_lsa_migrate_fn<structure>::migrate_fn) {\n object obj;\n auto ptr = static_cast<uint8_t*>(current_allocator().alloc(migrate, sizeof(void*) + len, 1));\n wr(ptr + sizeof(void*));\n auto view = structure::make_view(ptr);\n view.template get<tags::back_pointer>().store(&obj);\n obj.set_data(ptr);\n return obj;\n }\n\n \/\/\/ Create an IMR objects\n template<typename Writer>\n GCC6_CONCEPT(requires WriterAllocator<Writer, Structure>)\n static object make(Writer&& object_writer,\n allocation_strategy::migrate_fn migrate = &imr::alloc::default_lsa_migrate_fn<structure>::migrate_fn) {\n struct alloc_deleter {\n size_t _size;\n\n void operator()(uint8_t* ptr) {\n current_allocator().free(ptr, _size);\n }\n };\n using alloc_unique_ptr = std::unique_ptr<uint8_t[], alloc_deleter>;\n\n auto writer = [&object_writer] (auto&& ser, auto&& alloc) {\n return object_writer(ser.serialize(nullptr).serialize_nested(), alloc).done();\n };\n\n auto& alloc = current_allocator();\n alloc::object_allocator allocator(alloc);\n auto obj_size = structure::size_when_serialized(writer, allocator.get_sizer());\n auto ptr = alloc_unique_ptr(static_cast<uint8_t*>(alloc.alloc(migrate, obj_size, 1)), alloc_deleter { obj_size });\n allocator.allocate_all();\n structure::serialize(ptr.get(), writer, allocator.get_serializer());\n return object(ptr.release());\n }\n};\n\n}\n\n}\n<commit_msg>imr::utils::object_context: fix context_for for backpointer<commit_after>\/*\n * Copyright (C) 2018 ScyllaDB\n *\/\n\n\/*\n * This file is part of Scylla.\n *\n * Scylla is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * Scylla is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with Scylla. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n\n#pragma once\n\n#include <type_traits>\n\n#include \"imr\/core.hh\"\n#include \"imr\/alloc.hh\"\n#include \"imr\/concepts.hh\"\n\nnamespace imr {\nnamespace utils {\n\nclass basic_object {\npublic:\n struct tags {\n class back_pointer { };\n class object { };\n };\nprotected:\n uint8_t* _data = nullptr;\n\n friend struct methods::mover<imr::tagged_type<tags::back_pointer, imr::pod<basic_object*>>>;\nprotected:\n explicit basic_object(uint8_t* ptr) noexcept : _data(ptr) { }\n\n void set_data(uint8_t* ptr) noexcept { _data = ptr; }\npublic:\n basic_object() = default;\n basic_object(basic_object&& other) noexcept : _data(std::exchange(other._data, nullptr)) { }\n basic_object(const basic_object&) = delete;\n};\n\ntemplate<typename Context, typename... State>\nclass object_context {\n std::tuple<State...> _state;\nprivate:\n template<size_t... Index>\n Context create(const uint8_t* ptr, std::index_sequence<Index...>) const noexcept {\n return Context(ptr, std::get<Index>(_state)...);\n }\npublic:\n object_context(const uint8_t*, State... state) : _state { state... } { }\n template<typename Tag, typename... Args>\n auto context_for(const uint8_t* ptr, Args&&... args) const noexcept {\n if constexpr (std::is_same_v<Tag, basic_object::tags::back_pointer>) {\n return no_context_t();\n } else {\n return create(ptr, std::index_sequence_for<State...>());\n }\n }\n};\n\n}\n\nnamespace methods {\n\ntemplate<>\nstruct mover<imr::tagged_type<utils::basic_object::tags::back_pointer, imr::pod<utils::basic_object*>>> {\n static void run(uint8_t* ptr, ...) {\n auto bptr = imr::tagged_type<utils::basic_object::tags::back_pointer, imr::pod<utils::basic_object*>>::make_view(ptr).load();\n bptr->_data = ptr;\n }\n};\n\n}\n\nnamespace utils {\n\n\/\/\/ Unique pointer to an IMR object\n\/\/\/\n\/\/\/ This is an LSA-aware unique-owner pointer to an IMR object.\ntemplate<typename Structure>\nclass object : public basic_object {\npublic:\n using structure = imr::structure<\n imr::member<tags::back_pointer, imr::tagged_type<tags::back_pointer, imr::pod<basic_object*>>>,\n imr::member<tags::object, Structure>\n >;\n static constexpr size_t size_overhead = sizeof(basic_object*);\nprivate:\n explicit object(uint8_t* ptr) noexcept\n : basic_object(ptr)\n {\n structure::template get_member<tags::back_pointer>(_data).store(this);\n }\npublic:\n object() = default;\n object(object&& other) noexcept : basic_object(std::move(other)) {\n if (_data) {\n structure::template get_member<tags::back_pointer>(_data).store(this);\n }\n }\n\n object& operator=(object&& other) noexcept {\n swap(other);\n return *this;\n }\n\n ~object() {\n if (_data) {\n imr::methods::destroy<structure>(_data);\n current_allocator().free(_data);\n }\n }\n\n void swap(object& other) noexcept {\n std::swap(_data, other._data);\n if (_data) {\n structure::template get_member<tags::back_pointer>(_data).store(this);\n }\n if (other._data) {\n structure::template get_member<tags::back_pointer>(other._data).store(&other);\n }\n }\n\n explicit operator bool() const noexcept { return bool(_data); }\n\n uint8_t* get() noexcept { return _data ? _data + structure::template offset_of<tags::object>(_data) : nullptr; }\n const uint8_t* get() const noexcept { return _data ? _data + structure::template offset_of<tags::object>(_data) : nullptr; }\n\n \/\/\/ Creates an IMR object from a raw writer\n \/\/\/\n \/\/\/ This low-level function creates an IMR object owned by `object` using\n \/\/\/ a raw writer (i.e. does not necessarily follow the standard IMR\n \/\/\/ serialisation process). This is useful for fast copying of trivial\n \/\/\/ IMR objects.\n \/\/\/\n \/\/\/ \\note This function could be deprecated once the IMR starts supporting\n \/\/\/ copying IMR objects.\n template<typename RawWriter>\n GCC6_CONCEPT(requires requires (RawWriter wr, uint8_t* ptr) {\n { wr(ptr) } noexcept;\n })\n static object make_raw(size_t len, RawWriter&& wr, allocation_strategy::migrate_fn migrate = &imr::alloc::default_lsa_migrate_fn<structure>::migrate_fn) {\n object obj;\n auto ptr = static_cast<uint8_t*>(current_allocator().alloc(migrate, sizeof(void*) + len, 1));\n wr(ptr + sizeof(void*));\n auto view = structure::make_view(ptr);\n view.template get<tags::back_pointer>().store(&obj);\n obj.set_data(ptr);\n return obj;\n }\n\n \/\/\/ Create an IMR objects\n template<typename Writer>\n GCC6_CONCEPT(requires WriterAllocator<Writer, Structure>)\n static object make(Writer&& object_writer,\n allocation_strategy::migrate_fn migrate = &imr::alloc::default_lsa_migrate_fn<structure>::migrate_fn) {\n struct alloc_deleter {\n size_t _size;\n\n void operator()(uint8_t* ptr) {\n current_allocator().free(ptr, _size);\n }\n };\n using alloc_unique_ptr = std::unique_ptr<uint8_t[], alloc_deleter>;\n\n auto writer = [&object_writer] (auto&& ser, auto&& alloc) {\n return object_writer(ser.serialize(nullptr).serialize_nested(), alloc).done();\n };\n\n auto& alloc = current_allocator();\n alloc::object_allocator allocator(alloc);\n auto obj_size = structure::size_when_serialized(writer, allocator.get_sizer());\n auto ptr = alloc_unique_ptr(static_cast<uint8_t*>(alloc.alloc(migrate, obj_size, 1)), alloc_deleter { obj_size });\n allocator.allocate_all();\n structure::serialize(ptr.get(), writer, allocator.get_serializer());\n return object(ptr.release());\n }\n};\n\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/=======================================================================\n\/\/ Copyright Baptiste Wicht 2011.\n\/\/ Distributed under the Boost Software License, Version 1.0.\n\/\/ (See accompanying file LICENSE_1_0.txt or copy at\n\/\/ http:\/\/www.boost.org\/LICENSE_1_0.txt)\n\/\/=======================================================================\n\n#include <iostream>\n#include <cstdio>\n\n#include \"Compiler.hpp\"\n\n#include \"Target.hpp\"\n\n#include \"Utils.hpp\"\n#include \"DebugStopWatch.hpp\"\n#include \"Options.hpp\"\n\n#include \"StringPool.hpp\"\n#include \"FunctionTable.hpp\"\n#include \"SemanticalException.hpp\"\n#include \"AssemblyFileWriter.hpp\"\n\n#include \"parser\/SpiritParser.hpp\"\n#include \"ast\/SourceFile.hpp\"\n\n\/\/Annotators\n#include \"DefaultValues.hpp\"\n#include \"ContextAnnotator.hpp\"\n#include \"FunctionsAnnotator.hpp\"\n#include \"VariablesAnnotator.hpp\"\n\n\/\/Checkers\n#include \"StringChecker.hpp\"\n#include \"TypeChecker.hpp\"\n\n\/\/Visitors\n#include \"DependenciesResolver.hpp\"\n#include \"OptimizationEngine.hpp\"\n#include \"TransformerEngine.hpp\"\n#include \"WarningsEngine.hpp\"\n#include \"DebugVisitor.hpp\"\n\n\/\/Three Address Code\n#include \"tac\/Program.hpp\"\n#include \"tac\/Compiler.hpp\"\n#include \"tac\/BasicBlockExtractor.hpp\"\n#include \"tac\/TemporaryAllocator.hpp\"\n#include \"tac\/LivenessAnalyzer.hpp\"\n#include \"tac\/Optimizer.hpp\"\n#include \"tac\/Printer.hpp\"\n\n\/\/Code generation\n#include \"asm\/IntelX86CodeGenerator.hpp\"\n\n#ifdef DEBUG\nstatic const bool debug = true;\n#else\nstatic const bool debug = false;\n#endif\n\n#define TIMER_START(name) StopWatch name_timer; \n#define TIMER_END(name) if(debug){std::cout << #name << \" took \" << name_timer.elapsed() << \"s\" << std::endl;}\n\nusing namespace eddic;\n\nvoid exec(const std::string& command);\n\nint Compiler::compile(const std::string& file) {\n std::cout << \"Compile \" << file << std::endl;\n\n if(TargetDetermined && Target64){\n std::cout << \"Warning : Looks like you're running a 64 bit system. This compiler only outputs 32 bits assembly.\" << std::endl; \n }\n\n StopWatch timer;\n \n int code = compileOnly(file);\n\n std::cout << \"Compilation took \" << timer.elapsed() << \"s\" << std::endl;\n\n return code;\n}\n\nint Compiler::compileOnly(const std::string& file) {\n std::string output = options[\"output\"].as<std::string>();\n\n int code = 0;\n try {\n TIMER_START(parsing)\n\n parser::SpiritParser parser;\n\n \/\/The program to build\n ast::SourceFile program;\n\n \/\/Parse the file into the program\n bool parsing = parser.parse(file, program); \n\n TIMER_END(parsing)\n\n if(parsing){\n \/\/Symbol tables\n FunctionTable functionTable;\n StringPool pool;\n\n \/\/Read dependencies\n includeDependencies(program, parser);\n\n \/\/Apply some cleaning transformations\n clean(program);\n \n \/\/Annotate the AST with more informations\n defineDefaultValues(program);\n \n \/\/Fill the string pool\n checkStrings(program, pool);\n\n \/\/Add some more informations to the AST\n defineContexts(program);\n defineVariables(program);\n defineFunctions(program, functionTable);\n\n \/\/Transform the AST\n transform(program);\n\n \/\/Static analysis\n checkTypes(program);\n\n \/\/Check for warnings\n checkForWarnings(program, functionTable);\n \n \/\/Optimize the AST\n optimize(program, functionTable, pool);\n \n tac::Program tacProgram;\n\n \/\/Generate Three-Address-Code language\n tac::Compiler compiler;\n compiler.compile(program, pool, tacProgram);\n\n \/\/Separate into basic blocks\n tac::BasicBlockExtractor extractor;\n extractor.extract(tacProgram);\n\n \/\/Allocate storage for the temporaries that need to be stored\n tac::TemporaryAllocator allocator;\n allocator.allocate(tacProgram);\n\n tac::Optimizer optimizer;\n optimizer.optimize(tacProgram);\n\n \/\/Compute liveness of variables\n tac::LivenessAnalyzer liveness;\n liveness.compute(tacProgram);\n\n \/\/Generate assembly from TAC\n AssemblyFileWriter writer(\"output.asm\");\n as::IntelX86CodeGenerator generator(writer);\n generator.generate(tacProgram, pool); \n writer.write(); \n\n \/\/If it's necessary, assemble and link the assembly\n if(!options.count(\"assembly\")){\n exec(\"as --32 -o output.o output.asm\");\n exec(\"ld -S -m elf_i386 output.o -o \" + output);\n\n \/\/Remove temporary files\n remove(\"output.asm\");\n remove(\"output.o\");\n }\n }\n } catch (const SemanticalException& e) {\n std::cout << e.what() << std::endl;\n code = 1;\n }\n\n return code;\n}\n\nvoid eddic::defineDefaultValues(ast::SourceFile& program){\n DebugStopWatch<debug> timer(\"Annotate with default values\");\n DefaultValues values;\n values.fill(program);\n}\n\nvoid eddic::defineContexts(ast::SourceFile& program){\n DebugStopWatch<debug> timer(\"Annotate contexts\");\n ContextAnnotator annotator;\n annotator.annotate(program);\n}\n\nvoid eddic::defineVariables(ast::SourceFile& program){\n DebugStopWatch<debug> timer(\"Annotate variables\");\n VariablesAnnotator annotator;\n annotator.annotate(program);\n}\n\nvoid eddic::defineFunctions(ast::SourceFile& program, FunctionTable& functionTable){\n DebugStopWatch<debug> timer(\"Annotate functions\");\n FunctionsAnnotator annotator;\n annotator.annotate(program, functionTable);\n}\n\nvoid eddic::checkStrings(ast::SourceFile& program, StringPool& pool){\n DebugStopWatch<debug> timer(\"Strings checking\");\n StringChecker checker;\n checker.check(program, pool);\n}\n\nvoid eddic::checkTypes(ast::SourceFile& program){\n DebugStopWatch<debug> timer(\"Types checking\");\n TypeChecker checker;\n checker.check(program); \n}\n\nvoid eddic::checkForWarnings(ast::SourceFile& program, FunctionTable& table){\n DebugStopWatch<debug> timer(\"Check for warnings\");\n WarningsEngine engine;\n engine.check(program, table);\n}\n\nvoid eddic::clean(ast::SourceFile& program){\n DebugStopWatch<debug> timer(\"Cleaning\");\n TransformerEngine engine;\n engine.clean(program);\n}\n\nvoid eddic::transform(ast::SourceFile& program){\n DebugStopWatch<debug> timer(\"Transformation\");\n TransformerEngine engine;\n engine.transform(program);\n}\n\nvoid eddic::optimize(ast::SourceFile& program, FunctionTable& functionTable, StringPool& pool){\n DebugStopWatch<debug> timer(\"Optimization\");\n OptimizationEngine engine;\n engine.optimize(program, functionTable, pool);\n}\n\nvoid eddic::includeDependencies(ast::SourceFile& sourceFile, parser::SpiritParser& parser){\n DebugStopWatch<debug> timer(\"Resolve dependencies\");\n DependenciesResolver resolver(parser);\n resolver.resolve(sourceFile);\n}\n\nvoid exec(const std::string& command) {\n DebugStopWatch<debug> timer(\"Exec \" + command);\n \n if(debug){\n std::cout << \"eddic : exec command : \" << command << std::endl;\n }\n\n std::string result = execCommand(command);\n\n if(result.size() > 0){\n std::cout << result << std::endl;\n }\n}\n\nvoid eddic::warn(const std::string& warning){\n std::cout << \"warning: \" << warning << std::endl;\n}\n<commit_msg>Add debugging symbols to the executable if the options is set<commit_after>\/\/=======================================================================\n\/\/ Copyright Baptiste Wicht 2011.\n\/\/ Distributed under the Boost Software License, Version 1.0.\n\/\/ (See accompanying file LICENSE_1_0.txt or copy at\n\/\/ http:\/\/www.boost.org\/LICENSE_1_0.txt)\n\/\/=======================================================================\n\n#include <iostream>\n#include <cstdio>\n\n#include \"Compiler.hpp\"\n\n#include \"Target.hpp\"\n\n#include \"Utils.hpp\"\n#include \"DebugStopWatch.hpp\"\n#include \"Options.hpp\"\n\n#include \"StringPool.hpp\"\n#include \"FunctionTable.hpp\"\n#include \"SemanticalException.hpp\"\n#include \"AssemblyFileWriter.hpp\"\n\n#include \"parser\/SpiritParser.hpp\"\n#include \"ast\/SourceFile.hpp\"\n\n\/\/Annotators\n#include \"DefaultValues.hpp\"\n#include \"ContextAnnotator.hpp\"\n#include \"FunctionsAnnotator.hpp\"\n#include \"VariablesAnnotator.hpp\"\n\n\/\/Checkers\n#include \"StringChecker.hpp\"\n#include \"TypeChecker.hpp\"\n\n\/\/Visitors\n#include \"DependenciesResolver.hpp\"\n#include \"OptimizationEngine.hpp\"\n#include \"TransformerEngine.hpp\"\n#include \"WarningsEngine.hpp\"\n#include \"DebugVisitor.hpp\"\n\n\/\/Three Address Code\n#include \"tac\/Program.hpp\"\n#include \"tac\/Compiler.hpp\"\n#include \"tac\/BasicBlockExtractor.hpp\"\n#include \"tac\/TemporaryAllocator.hpp\"\n#include \"tac\/LivenessAnalyzer.hpp\"\n#include \"tac\/Optimizer.hpp\"\n#include \"tac\/Printer.hpp\"\n\n\/\/Code generation\n#include \"asm\/IntelX86CodeGenerator.hpp\"\n\n#ifdef DEBUG\nstatic const bool debug = true;\n#else\nstatic const bool debug = false;\n#endif\n\n#define TIMER_START(name) StopWatch name_timer; \n#define TIMER_END(name) if(debug){std::cout << #name << \" took \" << name_timer.elapsed() << \"s\" << std::endl;}\n\nusing namespace eddic;\n\nvoid exec(const std::string& command);\n\nint Compiler::compile(const std::string& file) {\n std::cout << \"Compile \" << file << std::endl;\n\n if(TargetDetermined && Target64){\n std::cout << \"Warning : Looks like you're running a 64 bit system. This compiler only outputs 32 bits assembly.\" << std::endl; \n }\n\n StopWatch timer;\n \n int code = compileOnly(file);\n\n std::cout << \"Compilation took \" << timer.elapsed() << \"s\" << std::endl;\n\n return code;\n}\n\nint Compiler::compileOnly(const std::string& file) {\n std::string output = options[\"output\"].as<std::string>();\n\n int code = 0;\n try {\n TIMER_START(parsing)\n\n parser::SpiritParser parser;\n\n \/\/The program to build\n ast::SourceFile program;\n\n \/\/Parse the file into the program\n bool parsing = parser.parse(file, program); \n\n TIMER_END(parsing)\n\n if(parsing){\n \/\/Symbol tables\n FunctionTable functionTable;\n StringPool pool;\n\n \/\/Read dependencies\n includeDependencies(program, parser);\n\n \/\/Apply some cleaning transformations\n clean(program);\n \n \/\/Annotate the AST with more informations\n defineDefaultValues(program);\n \n \/\/Fill the string pool\n checkStrings(program, pool);\n\n \/\/Add some more informations to the AST\n defineContexts(program);\n defineVariables(program);\n defineFunctions(program, functionTable);\n\n \/\/Transform the AST\n transform(program);\n\n \/\/Static analysis\n checkTypes(program);\n\n \/\/Check for warnings\n checkForWarnings(program, functionTable);\n \n \/\/Optimize the AST\n optimize(program, functionTable, pool);\n \n tac::Program tacProgram;\n\n \/\/Generate Three-Address-Code language\n tac::Compiler compiler;\n compiler.compile(program, pool, tacProgram);\n\n \/\/Separate into basic blocks\n tac::BasicBlockExtractor extractor;\n extractor.extract(tacProgram);\n\n \/\/Allocate storage for the temporaries that need to be stored\n tac::TemporaryAllocator allocator;\n allocator.allocate(tacProgram);\n\n tac::Optimizer optimizer;\n optimizer.optimize(tacProgram);\n\n \/\/Compute liveness of variables\n tac::LivenessAnalyzer liveness;\n liveness.compute(tacProgram);\n\n \/\/Generate assembly from TAC\n AssemblyFileWriter writer(\"output.asm\");\n as::IntelX86CodeGenerator generator(writer);\n generator.generate(tacProgram, pool); \n writer.write(); \n\n \/\/If it's necessary, assemble and link the assembly\n if(!options.count(\"assembly\")){\n if(options.count(\"debug\")){\n exec(\"as -g --32 -o output.o output.asm\");\n exec(\"ld -m elf_i386 output.o -o \" + output);\n } else {\n exec(\"as --32 -o output.o output.asm\");\n exec(\"ld -S -m elf_i386 output.o -o \" + output);\n }\n\n \/\/Remove temporary files\n remove(\"output.asm\");\n remove(\"output.o\");\n }\n }\n } catch (const SemanticalException& e) {\n std::cout << e.what() << std::endl;\n code = 1;\n }\n\n return code;\n}\n\nvoid eddic::defineDefaultValues(ast::SourceFile& program){\n DebugStopWatch<debug> timer(\"Annotate with default values\");\n DefaultValues values;\n values.fill(program);\n}\n\nvoid eddic::defineContexts(ast::SourceFile& program){\n DebugStopWatch<debug> timer(\"Annotate contexts\");\n ContextAnnotator annotator;\n annotator.annotate(program);\n}\n\nvoid eddic::defineVariables(ast::SourceFile& program){\n DebugStopWatch<debug> timer(\"Annotate variables\");\n VariablesAnnotator annotator;\n annotator.annotate(program);\n}\n\nvoid eddic::defineFunctions(ast::SourceFile& program, FunctionTable& functionTable){\n DebugStopWatch<debug> timer(\"Annotate functions\");\n FunctionsAnnotator annotator;\n annotator.annotate(program, functionTable);\n}\n\nvoid eddic::checkStrings(ast::SourceFile& program, StringPool& pool){\n DebugStopWatch<debug> timer(\"Strings checking\");\n StringChecker checker;\n checker.check(program, pool);\n}\n\nvoid eddic::checkTypes(ast::SourceFile& program){\n DebugStopWatch<debug> timer(\"Types checking\");\n TypeChecker checker;\n checker.check(program); \n}\n\nvoid eddic::checkForWarnings(ast::SourceFile& program, FunctionTable& table){\n DebugStopWatch<debug> timer(\"Check for warnings\");\n WarningsEngine engine;\n engine.check(program, table);\n}\n\nvoid eddic::clean(ast::SourceFile& program){\n DebugStopWatch<debug> timer(\"Cleaning\");\n TransformerEngine engine;\n engine.clean(program);\n}\n\nvoid eddic::transform(ast::SourceFile& program){\n DebugStopWatch<debug> timer(\"Transformation\");\n TransformerEngine engine;\n engine.transform(program);\n}\n\nvoid eddic::optimize(ast::SourceFile& program, FunctionTable& functionTable, StringPool& pool){\n DebugStopWatch<debug> timer(\"Optimization\");\n OptimizationEngine engine;\n engine.optimize(program, functionTable, pool);\n}\n\nvoid eddic::includeDependencies(ast::SourceFile& sourceFile, parser::SpiritParser& parser){\n DebugStopWatch<debug> timer(\"Resolve dependencies\");\n DependenciesResolver resolver(parser);\n resolver.resolve(sourceFile);\n}\n\nvoid exec(const std::string& command) {\n DebugStopWatch<debug> timer(\"Exec \" + command);\n \n if(debug){\n std::cout << \"eddic : exec command : \" << command << std::endl;\n }\n\n std::string result = execCommand(command);\n\n if(result.size() > 0){\n std::cout << result << std::endl;\n }\n}\n\nvoid eddic::warn(const std::string& warning){\n std::cout << \"warning: \" << warning << std::endl;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/dom_ui\/fileicon_source.h\"\n\n#include \"base\/gfx\/png_encoder.h\"\n#include \"base\/string_util.h\"\n#include \"chrome\/browser\/browser_process.h\"\n#include \"chrome\/common\/time_format.h\"\n#include \"grit\/generated_resources.h\"\n\n\/\/ The path used in internal URLs to file icon data.\nstatic const char kFileIconPath[] = \"fileicon\";\n\nFileIconSource::FileIconSource()\n : DataSource(kFileIconPath, MessageLoop::current()) {}\n\nFileIconSource::~FileIconSource() {\n cancelable_consumer_.CancelAllRequests();\n}\n\nvoid FileIconSource::StartDataRequest(const std::string& path,\n int request_id) {\n IconManager* im = g_browser_process->icon_manager();\n\n \/\/ Fast look up.\n SkBitmap* icon = im->LookupIcon(UTF8ToWide(path), IconLoader::NORMAL);\n\n if (icon) {\n std::vector<unsigned char> png_bytes;\n PNGEncoder::EncodeBGRASkBitmap(*icon, false, &png_bytes);\n\n scoped_refptr<RefCountedBytes> icon_data = new RefCountedBytes(png_bytes);\n SendResponse(request_id, icon_data);\n } else {\n \/\/ Icon was not in cache, go fetch it slowly.\n IconManager::Handle h = im->LoadIcon(UTF8ToWide(path), IconLoader::NORMAL,\n &cancelable_consumer_,\n NewCallback(this, &FileIconSource::OnFileIconDataAvailable));\n\n \/\/ Attach the ChromeURLDataManager request ID to the history request.\n cancelable_consumer_.SetClientData(im, h, request_id);\n }\n}\n\nvoid FileIconSource::OnFileIconDataAvailable(IconManager::Handle handle,\n SkBitmap* icon) {\n IconManager* im = g_browser_process->icon_manager();\n int request_id = cancelable_consumer_.GetClientData(im, handle);\n\n if (icon) {\n std::vector<unsigned char> png_bytes;\n PNGEncoder::EncodeBGRASkBitmap(*icon, false, &png_bytes);\n\n scoped_refptr<RefCountedBytes> icon_data = new RefCountedBytes(png_bytes);\n SendResponse(request_id, icon_data);\n } else {\n \/\/ TODO(glen): send a dummy icon.\n SendResponse(request_id, NULL);\n }\n}<commit_msg>Show icons for exe files in download manager. Issue was that the paths were coming in with the wrong slash direction and escaping, which was OK for non-exes, but strangely bad for exes.<commit_after>\/\/ Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/dom_ui\/fileicon_source.h\"\n\n#include \"base\/gfx\/png_encoder.h\"\n#include \"base\/string_util.h\"\n#include \"chrome\/browser\/browser_process.h\"\n#include \"chrome\/common\/time_format.h\"\n#include \"grit\/generated_resources.h\"\n#include \"net\/base\/escape.h\"\n\n\/\/ The path used in internal URLs to file icon data.\nstatic const char kFileIconPath[] = \"fileicon\";\n\nFileIconSource::FileIconSource()\n : DataSource(kFileIconPath, MessageLoop::current()) {}\n\nFileIconSource::~FileIconSource() {\n cancelable_consumer_.CancelAllRequests();\n}\n\nvoid FileIconSource::StartDataRequest(const std::string& path,\n int request_id) {\n IconManager* im = g_browser_process->icon_manager();\n\n \/\/ The path we receive has the wrong slashes and escaping for what we need;\n \/\/ this only appears to matter for getting icons from .exe files.\n std::string escaped_path = UnescapeURLComponent(path, UnescapeRule::SPACES);\n std::replace(escaped_path.begin(), escaped_path.end(), '\/', '\\\\');\n\n \/\/ Fast look up.\n SkBitmap* icon = im->LookupIcon(UTF8ToWide(escaped_path), IconLoader::NORMAL);\n\n if (icon) {\n std::vector<unsigned char> png_bytes;\n PNGEncoder::EncodeBGRASkBitmap(*icon, false, &png_bytes);\n\n scoped_refptr<RefCountedBytes> icon_data = new RefCountedBytes(png_bytes);\n SendResponse(request_id, icon_data);\n } else {\n \/\/ Icon was not in cache, go fetch it slowly.\n IconManager::Handle h = im->LoadIcon(UTF8ToWide(escaped_path), \n IconLoader::NORMAL,\n &cancelable_consumer_,\n NewCallback(this, &FileIconSource::OnFileIconDataAvailable));\n\n \/\/ Attach the ChromeURLDataManager request ID to the history request.\n cancelable_consumer_.SetClientData(im, h, request_id);\n }\n}\n\nvoid FileIconSource::OnFileIconDataAvailable(IconManager::Handle handle,\n SkBitmap* icon) {\n IconManager* im = g_browser_process->icon_manager();\n int request_id = cancelable_consumer_.GetClientData(im, handle);\n\n if (icon) {\n std::vector<unsigned char> png_bytes;\n PNGEncoder::EncodeBGRASkBitmap(*icon, false, &png_bytes);\n\n scoped_refptr<RefCountedBytes> icon_data = new RefCountedBytes(png_bytes);\n SendResponse(request_id, icon_data);\n } else {\n \/\/ TODO(glen): send a dummy icon.\n SendResponse(request_id, NULL);\n }\n}<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2009 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/gtk\/bookmark_utils_gtk.h\"\n\n#include \"app\/gtk_dnd_util.h\"\n#include \"app\/l10n_util.h\"\n#include \"app\/resource_bundle.h\"\n#include \"base\/gfx\/gtk_util.h\"\n#include \"base\/pickle.h\"\n#include \"base\/string_util.h\"\n#include \"chrome\/browser\/bookmarks\/bookmark_drag_data.h\"\n#include \"chrome\/browser\/bookmarks\/bookmark_model.h\"\n#include \"chrome\/browser\/bookmarks\/bookmark_utils.h\"\n#include \"chrome\/browser\/gtk\/gtk_chrome_button.h\"\n#include \"chrome\/browser\/gtk\/gtk_theme_provider.h\"\n#include \"chrome\/browser\/profile.h\"\n#include \"chrome\/common\/gtk_util.h\"\n\nnamespace {\n\n\/\/ Used in gtk_selection_data_set(). (I assume from this parameter that gtk has\n\/\/ to some really exotic hardware...)\nconst int kBitsInAByte = 8;\n\n\/\/ Maximum number of characters on a bookmark button.\nconst size_t kMaxCharsOnAButton = 15;\n\n\/\/ Max size of each component of the button tooltips.\nconst size_t kMaxTooltipTitleLength = 100;\nconst size_t kMaxTooltipURLLength = 400;\n\n\/\/ Only used for the background of the drag widget.\nconst GdkColor kBackgroundColor = GDK_COLOR_RGB(0xe6, 0xed, 0xf4);\n\n\/\/ Padding between the chrome button highlight border and the contents (favicon,\n\/\/ text).\n\/\/ TODO(estade): we need to adjust the top and bottom padding, but first we need\n\/\/ to give the bookmark bar more space (at the expense of the toolbar).\nconst int kButtonPaddingTop = 0;\nconst int kButtonPaddingBottom = 0;\nconst int kButtonPaddingLeft = 2;\nconst int kButtonPaddingRight = 0;\n\nvoid* AsVoid(const BookmarkNode* node) {\n return const_cast<BookmarkNode*>(node);\n}\n\n} \/\/ namespace\n\nnamespace bookmark_utils {\n\nconst char kBookmarkNode[] = \"bookmark-node\";\n\n\/\/ Spacing between the buttons on the bar.\nconst int kBarButtonPadding = 4;\n\nGdkPixbuf* GetPixbufForNode(const BookmarkNode* node, BookmarkModel* model,\n bool native) {\n GdkPixbuf* pixbuf;\n\n if (node->is_url()) {\n if (model->GetFavIcon(node).width() != 0) {\n pixbuf = gfx::GdkPixbufFromSkBitmap(&model->GetFavIcon(node));\n } else {\n pixbuf = GtkThemeProvider::GetDefaultFavicon(native);\n g_object_ref(pixbuf);\n }\n } else {\n pixbuf = GtkThemeProvider::GetFolderIcon(native);\n g_object_ref(pixbuf);\n }\n\n return pixbuf;\n}\n\nGtkWidget* GetDragRepresentation(const BookmarkNode* node,\n BookmarkModel* model,\n GtkThemeProvider* provider) {\n \/\/ Build a windowed representation for our button.\n GtkWidget* window = gtk_window_new(GTK_WINDOW_POPUP);\n if (!provider->UseGtkTheme()) {\n \/\/ TODO(erg): Theme wise, which color should I be picking here?\n \/\/ COLOR_BUTTON_BACKGROUND doesn't match the default theme!\n gtk_widget_modify_bg(window, GTK_STATE_NORMAL, &kBackgroundColor);\n }\n gtk_widget_realize(window);\n\n GtkWidget* frame = gtk_frame_new(NULL);\n gtk_frame_set_shadow_type(GTK_FRAME(frame), GTK_SHADOW_OUT);\n gtk_container_add(GTK_CONTAINER(window), frame);\n gtk_widget_show(frame);\n\n GtkWidget* floating_button = provider->BuildChromeButton();\n bookmark_utils::ConfigureButtonForNode(node, model, floating_button,\n provider);\n gtk_container_add(GTK_CONTAINER(frame), floating_button);\n gtk_widget_show(floating_button);\n\n return window;\n}\n\nvoid ConfigureButtonForNode(const BookmarkNode* node, BookmarkModel* model,\n GtkWidget* button, GtkThemeProvider* provider) {\n GtkWidget* former_child = gtk_bin_get_child(GTK_BIN(button));\n if (former_child)\n gtk_container_remove(GTK_CONTAINER(button), former_child);\n\n std::string tooltip = BuildTooltipFor(node);\n if (!tooltip.empty())\n gtk_widget_set_tooltip_markup(button, tooltip.c_str());\n\n \/\/ We pack the button manually (rather than using gtk_button_set_*) so that\n \/\/ we can have finer control over its label.\n GdkPixbuf* pixbuf = bookmark_utils::GetPixbufForNode(node, model,\n provider->UseGtkTheme());\n GtkWidget* image = gtk_image_new_from_pixbuf(pixbuf);\n g_object_unref(pixbuf);\n\n GtkWidget* box = gtk_hbox_new(FALSE, kBarButtonPadding);\n gtk_box_pack_start(GTK_BOX(box), image, FALSE, FALSE, 0);\n\n std::string label_string = WideToUTF8(node->GetTitle());\n if (!label_string.empty()) {\n GtkWidget* label = gtk_label_new(label_string.c_str());\n gtk_label_set_max_width_chars(GTK_LABEL(label), kMaxCharsOnAButton);\n gtk_label_set_ellipsize(GTK_LABEL(label), PANGO_ELLIPSIZE_END);\n gtk_box_pack_start(GTK_BOX(box), label, FALSE, FALSE, 0);\n SetButtonTextColors(label, provider);\n }\n\n GtkWidget* alignment = gtk_alignment_new(0.0, 0.0, 1.0, 1.0);\n \/\/ If we are not showing the label, don't set any padding, so that the icon\n \/\/ will just be centered.\n if (label_string.c_str()) {\n gtk_alignment_set_padding(GTK_ALIGNMENT(alignment),\n kButtonPaddingTop, kButtonPaddingBottom,\n kButtonPaddingLeft, kButtonPaddingRight);\n }\n gtk_container_add(GTK_CONTAINER(alignment), box);\n gtk_container_add(GTK_CONTAINER(button), alignment);\n\n g_object_set_data(G_OBJECT(button), bookmark_utils::kBookmarkNode,\n AsVoid(node));\n\n gtk_widget_show_all(alignment);\n}\n\nstd::string BuildTooltipFor(const BookmarkNode* node) {\n const std::string& url = node->GetURL().possibly_invalid_spec();\n const std::string& title = WideToUTF8(node->GetTitle());\n\n std::string truncated_url = WideToUTF8(l10n_util::TruncateString(\n UTF8ToWide(url), kMaxTooltipURLLength));\n gchar* escaped_url_cstr = g_markup_escape_text(truncated_url.c_str(),\n truncated_url.size());\n std::string escaped_url(escaped_url_cstr);\n g_free(escaped_url_cstr);\n\n std::string tooltip;\n if (url == title || title.empty()) {\n return escaped_url;\n } else {\n std::string truncated_title = WideToUTF8(l10n_util::TruncateString(\n node->GetTitle(), kMaxTooltipTitleLength));\n gchar* escaped_title_cstr = g_markup_escape_text(truncated_title.c_str(),\n truncated_title.size());\n std::string escaped_title(escaped_title_cstr);\n g_free(escaped_title_cstr);\n\n if (!escaped_url.empty())\n return std::string(\"<b>\") + escaped_title + \"<\/b>\\n\" + escaped_url;\n else\n return std::string(\"<b>\") + escaped_title + \"<\/b>\";\n }\n}\n\nconst BookmarkNode* BookmarkNodeForWidget(GtkWidget* widget) {\n return reinterpret_cast<const BookmarkNode*>(\n g_object_get_data(G_OBJECT(widget), bookmark_utils::kBookmarkNode));\n}\n\nvoid SetButtonTextColors(GtkWidget* label, GtkThemeProvider* provider) {\n if (provider->UseGtkTheme()) {\n gtk_util::SetLabelColor(label, NULL);\n } else {\n GdkColor color = provider->GetGdkColor(\n BrowserThemeProvider::COLOR_BOOKMARK_TEXT);\n gtk_util::SetLabelColor(label, &color);\n }\n}\n\n\/\/ DnD-related -----------------------------------------------------------------\n\nvoid WriteBookmarkToSelection(const BookmarkNode* node,\n GtkSelectionData* selection_data,\n guint target_type,\n Profile* profile) {\n DCHECK(node);\n std::vector<const BookmarkNode*> nodes;\n nodes.push_back(node);\n WriteBookmarksToSelection(nodes, selection_data, target_type, profile);\n}\n\nvoid WriteBookmarksToSelection(const std::vector<const BookmarkNode*>& nodes,\n GtkSelectionData* selection_data,\n guint target_type,\n Profile* profile) {\n switch (target_type) {\n case GtkDndUtil::CHROME_BOOKMARK_ITEM: {\n BookmarkDragData data(nodes);\n Pickle pickle;\n data.WriteToPickle(profile, &pickle);\n\n gtk_selection_data_set(selection_data, selection_data->target,\n kBitsInAByte,\n static_cast<const guchar*>(pickle.data()),\n pickle.size());\n break;\n }\n case GtkDndUtil::TEXT_URI_LIST: {\n gchar** uris = reinterpret_cast<gchar**>(malloc(sizeof(gchar*) *\n (nodes.size() + 1)));\n for (size_t i = 0; i < nodes.size(); ++i) {\n \/\/ If the node is a folder, this will be empty. TODO(estade): figure out\n \/\/ if there are any ramifications to passing an empty URI. After a\n \/\/ little testing, it seems fine.\n const GURL& url = nodes[i]->GetURL();\n \/\/ This const cast should be safe as gtk_selection_data_set_uris()\n \/\/ makes copies.\n uris[i] = const_cast<gchar*>(url.spec().c_str());\n }\n uris[nodes.size()] = NULL;\n\n gtk_selection_data_set_uris(selection_data, uris);\n free(uris);\n break;\n }\n default: {\n DLOG(ERROR) << \"Unsupported drag get type!\";\n }\n }\n}\n\nstd::vector<const BookmarkNode*> GetNodesFromSelection(\n GdkDragContext* context,\n GtkSelectionData* selection_data,\n guint target_type,\n Profile* profile,\n gboolean* delete_selection_data,\n gboolean* dnd_success) {\n *delete_selection_data = FALSE;\n *dnd_success = FALSE;\n\n if ((selection_data != NULL) && (selection_data->length >= 0)) {\n if (context->action == GDK_ACTION_MOVE) {\n *delete_selection_data = TRUE;\n }\n\n switch (target_type) {\n case GtkDndUtil::CHROME_BOOKMARK_ITEM: {\n *dnd_success = TRUE;\n Pickle pickle(reinterpret_cast<char*>(selection_data->data),\n selection_data->length);\n BookmarkDragData drag_data;\n drag_data.ReadFromPickle(&pickle);\n return drag_data.GetNodes(profile);\n }\n default: {\n DLOG(ERROR) << \"Unsupported drag received type: \" << target_type;\n }\n }\n }\n\n return std::vector<const BookmarkNode*>();\n}\n\nbool CreateNewBookmarkFromNamedUrl(GtkSelectionData* selection_data,\n BookmarkModel* model, const BookmarkNode* parent, int idx) {\n GURL url;\n string16 title;\n if (!GtkDndUtil::ExtractNamedURL(selection_data, &url, &title))\n return false;\n\n model->AddURL(parent, idx, UTF16ToWideHack(title), url);\n return true;\n}\n\nbool CreateNewBookmarksFromURIList(GtkSelectionData* selection_data,\n BookmarkModel* model, const BookmarkNode* parent, int idx) {\n std::vector<GURL> urls;\n GtkDndUtil::ExtractURIList(selection_data, &urls);\n for (size_t i = 0; i < urls.size(); ++i) {\n std::string title = GetNameForURL(urls[i]);\n model->AddURL(parent, idx++, UTF8ToWide(title), urls[i]);\n }\n return true;\n}\n\n} \/\/ namespace bookmark_utils\n<commit_msg>GTK: Don't ellipsize the Other Bookmarks button.<commit_after>\/\/ Copyright (c) 2009 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/gtk\/bookmark_utils_gtk.h\"\n\n#include \"app\/gtk_dnd_util.h\"\n#include \"app\/l10n_util.h\"\n#include \"app\/resource_bundle.h\"\n#include \"base\/gfx\/gtk_util.h\"\n#include \"base\/pickle.h\"\n#include \"base\/string_util.h\"\n#include \"chrome\/browser\/bookmarks\/bookmark_drag_data.h\"\n#include \"chrome\/browser\/bookmarks\/bookmark_model.h\"\n#include \"chrome\/browser\/bookmarks\/bookmark_utils.h\"\n#include \"chrome\/browser\/gtk\/gtk_chrome_button.h\"\n#include \"chrome\/browser\/gtk\/gtk_theme_provider.h\"\n#include \"chrome\/browser\/profile.h\"\n#include \"chrome\/common\/gtk_util.h\"\n\nnamespace {\n\n\/\/ Used in gtk_selection_data_set(). (I assume from this parameter that gtk has\n\/\/ to some really exotic hardware...)\nconst int kBitsInAByte = 8;\n\n\/\/ Maximum number of characters on a bookmark button.\nconst size_t kMaxCharsOnAButton = 15;\n\n\/\/ Max size of each component of the button tooltips.\nconst size_t kMaxTooltipTitleLength = 100;\nconst size_t kMaxTooltipURLLength = 400;\n\n\/\/ Only used for the background of the drag widget.\nconst GdkColor kBackgroundColor = GDK_COLOR_RGB(0xe6, 0xed, 0xf4);\n\n\/\/ Padding between the chrome button highlight border and the contents (favicon,\n\/\/ text).\n\/\/ TODO(estade): we need to adjust the top and bottom padding, but first we need\n\/\/ to give the bookmark bar more space (at the expense of the toolbar).\nconst int kButtonPaddingTop = 0;\nconst int kButtonPaddingBottom = 0;\nconst int kButtonPaddingLeft = 2;\nconst int kButtonPaddingRight = 0;\n\nvoid* AsVoid(const BookmarkNode* node) {\n return const_cast<BookmarkNode*>(node);\n}\n\n} \/\/ namespace\n\nnamespace bookmark_utils {\n\nconst char kBookmarkNode[] = \"bookmark-node\";\n\n\/\/ Spacing between the buttons on the bar.\nconst int kBarButtonPadding = 4;\n\nGdkPixbuf* GetPixbufForNode(const BookmarkNode* node, BookmarkModel* model,\n bool native) {\n GdkPixbuf* pixbuf;\n\n if (node->is_url()) {\n if (model->GetFavIcon(node).width() != 0) {\n pixbuf = gfx::GdkPixbufFromSkBitmap(&model->GetFavIcon(node));\n } else {\n pixbuf = GtkThemeProvider::GetDefaultFavicon(native);\n g_object_ref(pixbuf);\n }\n } else {\n pixbuf = GtkThemeProvider::GetFolderIcon(native);\n g_object_ref(pixbuf);\n }\n\n return pixbuf;\n}\n\nGtkWidget* GetDragRepresentation(const BookmarkNode* node,\n BookmarkModel* model,\n GtkThemeProvider* provider) {\n \/\/ Build a windowed representation for our button.\n GtkWidget* window = gtk_window_new(GTK_WINDOW_POPUP);\n if (!provider->UseGtkTheme()) {\n \/\/ TODO(erg): Theme wise, which color should I be picking here?\n \/\/ COLOR_BUTTON_BACKGROUND doesn't match the default theme!\n gtk_widget_modify_bg(window, GTK_STATE_NORMAL, &kBackgroundColor);\n }\n gtk_widget_realize(window);\n\n GtkWidget* frame = gtk_frame_new(NULL);\n gtk_frame_set_shadow_type(GTK_FRAME(frame), GTK_SHADOW_OUT);\n gtk_container_add(GTK_CONTAINER(window), frame);\n gtk_widget_show(frame);\n\n GtkWidget* floating_button = provider->BuildChromeButton();\n bookmark_utils::ConfigureButtonForNode(node, model, floating_button,\n provider);\n gtk_container_add(GTK_CONTAINER(frame), floating_button);\n gtk_widget_show(floating_button);\n\n return window;\n}\n\nvoid ConfigureButtonForNode(const BookmarkNode* node, BookmarkModel* model,\n GtkWidget* button, GtkThemeProvider* provider) {\n GtkWidget* former_child = gtk_bin_get_child(GTK_BIN(button));\n if (former_child)\n gtk_container_remove(GTK_CONTAINER(button), former_child);\n\n std::string tooltip = BuildTooltipFor(node);\n if (!tooltip.empty())\n gtk_widget_set_tooltip_markup(button, tooltip.c_str());\n\n \/\/ We pack the button manually (rather than using gtk_button_set_*) so that\n \/\/ we can have finer control over its label.\n GdkPixbuf* pixbuf = bookmark_utils::GetPixbufForNode(node, model,\n provider->UseGtkTheme());\n GtkWidget* image = gtk_image_new_from_pixbuf(pixbuf);\n g_object_unref(pixbuf);\n\n GtkWidget* box = gtk_hbox_new(FALSE, kBarButtonPadding);\n gtk_box_pack_start(GTK_BOX(box), image, FALSE, FALSE, 0);\n\n std::string label_string = WideToUTF8(node->GetTitle());\n if (!label_string.empty()) {\n GtkWidget* label = gtk_label_new(label_string.c_str());\n\n \/\/ Ellipsize long bookmark names.\n if (node != model->other_node()) {\n gtk_label_set_max_width_chars(GTK_LABEL(label), kMaxCharsOnAButton);\n gtk_label_set_ellipsize(GTK_LABEL(label), PANGO_ELLIPSIZE_END);\n }\n\n gtk_box_pack_start(GTK_BOX(box), label, FALSE, FALSE, 0);\n SetButtonTextColors(label, provider);\n }\n\n GtkWidget* alignment = gtk_alignment_new(0.0, 0.0, 1.0, 1.0);\n \/\/ If we are not showing the label, don't set any padding, so that the icon\n \/\/ will just be centered.\n if (label_string.c_str()) {\n gtk_alignment_set_padding(GTK_ALIGNMENT(alignment),\n kButtonPaddingTop, kButtonPaddingBottom,\n kButtonPaddingLeft, kButtonPaddingRight);\n }\n gtk_container_add(GTK_CONTAINER(alignment), box);\n gtk_container_add(GTK_CONTAINER(button), alignment);\n\n g_object_set_data(G_OBJECT(button), bookmark_utils::kBookmarkNode,\n AsVoid(node));\n\n gtk_widget_show_all(alignment);\n}\n\nstd::string BuildTooltipFor(const BookmarkNode* node) {\n const std::string& url = node->GetURL().possibly_invalid_spec();\n const std::string& title = WideToUTF8(node->GetTitle());\n\n std::string truncated_url = WideToUTF8(l10n_util::TruncateString(\n UTF8ToWide(url), kMaxTooltipURLLength));\n gchar* escaped_url_cstr = g_markup_escape_text(truncated_url.c_str(),\n truncated_url.size());\n std::string escaped_url(escaped_url_cstr);\n g_free(escaped_url_cstr);\n\n std::string tooltip;\n if (url == title || title.empty()) {\n return escaped_url;\n } else {\n std::string truncated_title = WideToUTF8(l10n_util::TruncateString(\n node->GetTitle(), kMaxTooltipTitleLength));\n gchar* escaped_title_cstr = g_markup_escape_text(truncated_title.c_str(),\n truncated_title.size());\n std::string escaped_title(escaped_title_cstr);\n g_free(escaped_title_cstr);\n\n if (!escaped_url.empty())\n return std::string(\"<b>\") + escaped_title + \"<\/b>\\n\" + escaped_url;\n else\n return std::string(\"<b>\") + escaped_title + \"<\/b>\";\n }\n}\n\nconst BookmarkNode* BookmarkNodeForWidget(GtkWidget* widget) {\n return reinterpret_cast<const BookmarkNode*>(\n g_object_get_data(G_OBJECT(widget), bookmark_utils::kBookmarkNode));\n}\n\nvoid SetButtonTextColors(GtkWidget* label, GtkThemeProvider* provider) {\n if (provider->UseGtkTheme()) {\n gtk_util::SetLabelColor(label, NULL);\n } else {\n GdkColor color = provider->GetGdkColor(\n BrowserThemeProvider::COLOR_BOOKMARK_TEXT);\n gtk_util::SetLabelColor(label, &color);\n }\n}\n\n\/\/ DnD-related -----------------------------------------------------------------\n\nvoid WriteBookmarkToSelection(const BookmarkNode* node,\n GtkSelectionData* selection_data,\n guint target_type,\n Profile* profile) {\n DCHECK(node);\n std::vector<const BookmarkNode*> nodes;\n nodes.push_back(node);\n WriteBookmarksToSelection(nodes, selection_data, target_type, profile);\n}\n\nvoid WriteBookmarksToSelection(const std::vector<const BookmarkNode*>& nodes,\n GtkSelectionData* selection_data,\n guint target_type,\n Profile* profile) {\n switch (target_type) {\n case GtkDndUtil::CHROME_BOOKMARK_ITEM: {\n BookmarkDragData data(nodes);\n Pickle pickle;\n data.WriteToPickle(profile, &pickle);\n\n gtk_selection_data_set(selection_data, selection_data->target,\n kBitsInAByte,\n static_cast<const guchar*>(pickle.data()),\n pickle.size());\n break;\n }\n case GtkDndUtil::TEXT_URI_LIST: {\n gchar** uris = reinterpret_cast<gchar**>(malloc(sizeof(gchar*) *\n (nodes.size() + 1)));\n for (size_t i = 0; i < nodes.size(); ++i) {\n \/\/ If the node is a folder, this will be empty. TODO(estade): figure out\n \/\/ if there are any ramifications to passing an empty URI. After a\n \/\/ little testing, it seems fine.\n const GURL& url = nodes[i]->GetURL();\n \/\/ This const cast should be safe as gtk_selection_data_set_uris()\n \/\/ makes copies.\n uris[i] = const_cast<gchar*>(url.spec().c_str());\n }\n uris[nodes.size()] = NULL;\n\n gtk_selection_data_set_uris(selection_data, uris);\n free(uris);\n break;\n }\n default: {\n DLOG(ERROR) << \"Unsupported drag get type!\";\n }\n }\n}\n\nstd::vector<const BookmarkNode*> GetNodesFromSelection(\n GdkDragContext* context,\n GtkSelectionData* selection_data,\n guint target_type,\n Profile* profile,\n gboolean* delete_selection_data,\n gboolean* dnd_success) {\n *delete_selection_data = FALSE;\n *dnd_success = FALSE;\n\n if ((selection_data != NULL) && (selection_data->length >= 0)) {\n if (context->action == GDK_ACTION_MOVE) {\n *delete_selection_data = TRUE;\n }\n\n switch (target_type) {\n case GtkDndUtil::CHROME_BOOKMARK_ITEM: {\n *dnd_success = TRUE;\n Pickle pickle(reinterpret_cast<char*>(selection_data->data),\n selection_data->length);\n BookmarkDragData drag_data;\n drag_data.ReadFromPickle(&pickle);\n return drag_data.GetNodes(profile);\n }\n default: {\n DLOG(ERROR) << \"Unsupported drag received type: \" << target_type;\n }\n }\n }\n\n return std::vector<const BookmarkNode*>();\n}\n\nbool CreateNewBookmarkFromNamedUrl(GtkSelectionData* selection_data,\n BookmarkModel* model, const BookmarkNode* parent, int idx) {\n GURL url;\n string16 title;\n if (!GtkDndUtil::ExtractNamedURL(selection_data, &url, &title))\n return false;\n\n model->AddURL(parent, idx, UTF16ToWideHack(title), url);\n return true;\n}\n\nbool CreateNewBookmarksFromURIList(GtkSelectionData* selection_data,\n BookmarkModel* model, const BookmarkNode* parent, int idx) {\n std::vector<GURL> urls;\n GtkDndUtil::ExtractURIList(selection_data, &urls);\n for (size_t i = 0; i < urls.size(); ++i) {\n std::string title = GetNameForURL(urls[i]);\n model->AddURL(parent, idx++, UTF8ToWide(title), urls[i]);\n }\n return true;\n}\n\n} \/\/ namespace bookmark_utils\n<|endoftext|>"} {"text":"<commit_before>\/\/\/ \\file ROOT\/RFitPanel.cxx\n\/\/\/ \\ingroup WebGui ROOT7\n\/\/\/ \\author Sergey Linev <S.Linev@gsi.de>\n\/\/\/ \\date 2017-10-24\n\/\/\/ \\warning This is part of the ROOT 7 prototype! It will change without notice. It might trigger earthquakes. Feedback\n\/\/\/ is welcome!\n\n\/*************************************************************************\n * Copyright (C) 1995-2017, Rene Brun and Fons Rademakers. *\n * All rights reserved. *\n * *\n * For the licensing terms see $ROOTSYS\/LICENSE. *\n * For the list of contributors see $ROOTSYS\/README\/CREDITS. *\n *************************************************************************\/\n\n#include <ROOT\/RFitPanel.hxx>\n\n#include <ROOT\/RWebWindowsManager.hxx>\n#include <ROOT\/TLogger.hxx>\n#include \"ROOT\/TDirectory.hxx\"\n\n#include \"TString.h\"\n#include \"TROOT.h\"\n#include \"TBufferJSON.h\"\n\n\/** \\class ROOT::Experimental::RFitPanel\n\\ingroup webdisplay\n\nweb-based FitPanel prototype.\n*\/\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Returns RWebWindow instance, used to display FitPanel\n\nstd::shared_ptr<ROOT::Experimental::RWebWindow> ROOT::Experimental::RFitPanel::GetWindow()\n{\n if (!fWindow) {\n fWindow = RWebWindowsManager::Instance()->CreateWindow();\n\n fWindow->SetPanelName(\"FitPanel\");\n\n fWindow->SetDataCallBack([this](unsigned connid, const std::string &arg) { ProcessData(connid, arg); });\n\n fWindow->SetGeometry(300, 500); \/\/ configure predefined geometry\n }\n\n return fWindow;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Show FitPanel\n\nvoid ROOT::Experimental::RFitPanel::Show(const std::string &where)\n{\n GetWindow()->Show(where);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Hide FitPanel\n\nvoid ROOT::Experimental::RFitPanel::Hide()\n{\n if (!fWindow)\n return;\n\n fWindow->CloseConnections();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Process data from FitPanel\n\/\/\/ OpenUI5-based FitPanel sends commands or status changes\n\nvoid ROOT::Experimental::RFitPanel::ProcessData(unsigned connid, const std::string &arg)\n{\n if (arg == \"CONN_READY\") {\n fConnId = connid;\n printf(\"FitPanel connection established %u\\n\", fConnId);\n fWindow->Send(fConnId, \"INITDONE\");\n\n RFitPanelModel model;\n model.fDataNames.emplace_back(\"1\", \"RootData1\");\n model.fDataNames.emplace_back(\"2\", \"RootData2\");\n model.fDataNames.emplace_back(\"3\", \"RootData3\");\n model.fSelectDataId = \"1\";\n\n model.fModelNames.emplace_back(\"1\", \"RootModel1\");\n model.fModelNames.emplace_back(\"2\", \"RootModel2\");\n model.fModelNames.emplace_back(\"3\", \"RootModel3\");\n model.fSelectModelId = \"3\";\n\n TString json = TBufferJSON::ToJSON(&model);\n\n fWindow->Send(fConnId, std::string(\"MODEL:\") + json.Data());\n\n return;\n }\n\n if (arg == \"CONN_CLOSED\") {\n printf(\"FitPanel connection closed\\n\");\n fConnId = 0;\n return;\n }\n\n if (arg.find(\"DOFIT:\") == 0) {\n TString exec;\n#ifdef _MSC_VER\n exec.Form(\"((ROOT::Experimental::RFitPanel *) 0x%p)->DoFit(%s);\", this, arg.c_str() + 6);\n#else\n exec.Form(\"((ROOT::Experimental::RFitPanel *) %p)->DoFit(%s);\", this, arg.c_str() + 6);\n#endif\n printf(\"Execute %s\\n\", exec.Data());\n gROOT->ProcessLine(exec.Data());\n return;\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Let use canvas to display fit results\n\nvoid ROOT::Experimental::RFitPanel::UseCanvas(std::shared_ptr<RCanvas> &canv)\n{\n if (!fCanvas) {\n fCanvas = canv;\n } else {\n R__ERROR_HERE(\"ShowIn\") << \"FitPanel already bound to the canvas - change is not yet supported\";\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Dummy function, called when \"Fit\" button pressed in UI\n\nvoid ROOT::Experimental::RFitPanel::DoFit(const std::string &dname, const std::string &mname)\n{\n printf(\"DoFit %s %s\\n\", dname.c_str(), mname.c_str());\n\n bool first_time = false;\n\n if (!fCanvas) {\n fCanvas = Experimental::RCanvas::Create(\"FitPanel Canvas\");\n first_time = true;\n }\n\n if (!fFitHist) {\n\n \/\/ Create the histogram.\n auto xaxis = std::make_shared<ROOT::Experimental::RAxisConfig>(10, 0., 10.);\n\n fFitHist = std::make_shared<ROOT::Experimental::RH1D>(*xaxis.get());\n\n \/\/ Fill a few points.\n fFitHist->Fill(5);\n fFitHist->Fill(6);\n fFitHist->Fill(6);\n fFitHist->Fill(7);\n\n fCanvas->Draw(fFitHist)->SetLineColor(Experimental::RColor::kBlue);\n\n \/\/ workaround to keep histogram in the lists\n ROOT::Experimental::TDirectory::Heap().Add(\"fitaxis\", xaxis);\n\n if (first_time) {\n fCanvas->Show();\n \/\/ fCanvas->Update();\n } else {\n fCanvas->Modified();\n \/\/ fCanvas->Update();\n }\n }\n}\n<commit_msg>v7 fitpanel: use proper include for drawing histogram<commit_after>\/\/\/ \\file ROOT\/RFitPanel.cxx\n\/\/\/ \\ingroup WebGui ROOT7\n\/\/\/ \\author Sergey Linev <S.Linev@gsi.de>\n\/\/\/ \\date 2017-10-24\n\/\/\/ \\warning This is part of the ROOT 7 prototype! It will change without notice. It might trigger earthquakes. Feedback\n\/\/\/ is welcome!\n\n\/*************************************************************************\n * Copyright (C) 1995-2017, Rene Brun and Fons Rademakers. *\n * All rights reserved. *\n * *\n * For the licensing terms see $ROOTSYS\/LICENSE. *\n * For the list of contributors see $ROOTSYS\/README\/CREDITS. *\n *************************************************************************\/\n\n#include <ROOT\/RFitPanel.hxx>\n\n#include <ROOT\/RWebWindowsManager.hxx>\n#include <ROOT\/RHistDrawable.hxx>\n#include <ROOT\/TLogger.hxx>\n#include \"ROOT\/TDirectory.hxx\"\n\n#include \"TString.h\"\n#include \"TROOT.h\"\n#include \"TBufferJSON.h\"\n\n\/** \\class ROOT::Experimental::RFitPanel\n\\ingroup webdisplay\n\nweb-based FitPanel prototype.\n*\/\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Returns RWebWindow instance, used to display FitPanel\n\nstd::shared_ptr<ROOT::Experimental::RWebWindow> ROOT::Experimental::RFitPanel::GetWindow()\n{\n if (!fWindow) {\n fWindow = RWebWindowsManager::Instance()->CreateWindow();\n\n fWindow->SetPanelName(\"FitPanel\");\n\n fWindow->SetDataCallBack([this](unsigned connid, const std::string &arg) { ProcessData(connid, arg); });\n\n fWindow->SetGeometry(300, 500); \/\/ configure predefined geometry\n }\n\n return fWindow;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Show FitPanel\n\nvoid ROOT::Experimental::RFitPanel::Show(const std::string &where)\n{\n GetWindow()->Show(where);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Hide FitPanel\n\nvoid ROOT::Experimental::RFitPanel::Hide()\n{\n if (!fWindow)\n return;\n\n fWindow->CloseConnections();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Process data from FitPanel\n\/\/\/ OpenUI5-based FitPanel sends commands or status changes\n\nvoid ROOT::Experimental::RFitPanel::ProcessData(unsigned connid, const std::string &arg)\n{\n if (arg == \"CONN_READY\") {\n fConnId = connid;\n printf(\"FitPanel connection established %u\\n\", fConnId);\n fWindow->Send(fConnId, \"INITDONE\");\n\n RFitPanelModel model;\n model.fDataNames.emplace_back(\"1\", \"RootData1\");\n model.fDataNames.emplace_back(\"2\", \"RootData2\");\n model.fDataNames.emplace_back(\"3\", \"RootData3\");\n model.fSelectDataId = \"1\";\n\n model.fModelNames.emplace_back(\"1\", \"RootModel1\");\n model.fModelNames.emplace_back(\"2\", \"RootModel2\");\n model.fModelNames.emplace_back(\"3\", \"RootModel3\");\n model.fSelectModelId = \"3\";\n\n TString json = TBufferJSON::ToJSON(&model);\n\n fWindow->Send(fConnId, std::string(\"MODEL:\") + json.Data());\n\n return;\n }\n\n if (arg == \"CONN_CLOSED\") {\n printf(\"FitPanel connection closed\\n\");\n fConnId = 0;\n return;\n }\n\n if (arg.find(\"DOFIT:\") == 0) {\n TString exec;\n#ifdef _MSC_VER\n exec.Form(\"((ROOT::Experimental::RFitPanel *) 0x%p)->DoFit(%s);\", this, arg.c_str() + 6);\n#else\n exec.Form(\"((ROOT::Experimental::RFitPanel *) %p)->DoFit(%s);\", this, arg.c_str() + 6);\n#endif\n printf(\"Execute %s\\n\", exec.Data());\n gROOT->ProcessLine(exec.Data());\n return;\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Let use canvas to display fit results\n\nvoid ROOT::Experimental::RFitPanel::UseCanvas(std::shared_ptr<RCanvas> &canv)\n{\n if (!fCanvas) {\n fCanvas = canv;\n } else {\n R__ERROR_HERE(\"ShowIn\") << \"FitPanel already bound to the canvas - change is not yet supported\";\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Dummy function, called when \"Fit\" button pressed in UI\n\nvoid ROOT::Experimental::RFitPanel::DoFit(const std::string &dname, const std::string &mname)\n{\n printf(\"DoFit %s %s\\n\", dname.c_str(), mname.c_str());\n\n bool first_time = false;\n\n if (!fCanvas) {\n fCanvas = Experimental::RCanvas::Create(\"FitPanel Canvas\");\n first_time = true;\n }\n\n if (!fFitHist) {\n\n \/\/ Create the histogram.\n auto xaxis = std::make_shared<ROOT::Experimental::RAxisConfig>(10, 0., 10.);\n\n fFitHist = std::make_shared<ROOT::Experimental::RH1D>(*xaxis.get());\n\n \/\/ Fill a few points.\n fFitHist->Fill(5);\n fFitHist->Fill(6);\n fFitHist->Fill(6);\n fFitHist->Fill(7);\n\n fCanvas->Draw(fFitHist)->SetLineColor(Experimental::RColor::kBlue);\n\n \/\/ workaround to keep histogram in the lists\n ROOT::Experimental::TDirectory::Heap().Add(\"fitaxis\", xaxis);\n\n if (first_time) {\n fCanvas->Show();\n \/\/ fCanvas->Update();\n } else {\n fCanvas->Modified();\n \/\/ fCanvas->Update();\n }\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/common\/extensions\/permissions\/api_permission.h\"\n\n#include \"chrome\/common\/extensions\/permissions\/permissions_info.h\"\n#include \"grit\/generated_resources.h\"\n#include \"ui\/base\/l10n\/l10n_util.h\"\n\nnamespace {\n\nconst char kOldUnlimitedStoragePermission[] = \"unlimited_storage\";\nconst char kWindowsPermission[] = \"windows\";\nconst char kTemporaryBackgroundAlias[] = \"background_alias_do_not_use\";\n\n} \/\/ namespace\n\nnamespace extensions {\n\n\/\/\n\/\/ APIPermission\n\/\/\n\nAPIPermission::~APIPermission() {}\n\nPermissionMessage APIPermission::GetMessage_() const {\n return PermissionMessage(\n message_id_, l10n_util::GetStringUTF16(l10n_message_id_));\n}\n\nAPIPermission::APIPermission(\n ID id,\n const char* name,\n int l10n_message_id,\n PermissionMessage::ID message_id,\n int flags)\n : id_(id),\n name_(name),\n flags_(flags),\n l10n_message_id_(l10n_message_id),\n message_id_(message_id) {}\n\n\/\/ static\nvoid APIPermission::RegisterAllPermissions(\n PermissionsInfo* info) {\n\n struct PermissionRegistration {\n APIPermission::ID id;\n const char* name;\n int flags;\n int l10n_message_id;\n PermissionMessage::ID message_id;\n } PermissionsToRegister[] = {\n \/\/ Register permissions for all extension types.\n { kBackground, \"background\" },\n { kClipboardRead, \"clipboardRead\", kFlagNone,\n IDS_EXTENSION_PROMPT_WARNING_CLIPBOARD,\n PermissionMessage::kClipboard },\n { kClipboardWrite, \"clipboardWrite\" },\n { kDeclarativeWebRequest, \"declarativeWebRequest\" },\n { kDownloads, \"downloads\", kFlagNone,\n IDS_EXTENSION_PROMPT_WARNING_DOWNLOADS,\n PermissionMessage::kDownloads },\n { kExperimental, \"experimental\", kFlagCannotBeOptional },\n { kGeolocation, \"geolocation\", kFlagCannotBeOptional,\n IDS_EXTENSION_PROMPT_WARNING_GEOLOCATION,\n PermissionMessage::kGeolocation },\n { kNotification, \"notifications\" },\n { kUnlimitedStorage, \"unlimitedStorage\", kFlagCannotBeOptional },\n\n \/\/ Register hosted and packaged app permissions.\n { kAppNotifications, \"appNotifications\" },\n\n \/\/ Register extension permissions.\n { kActiveTab, \"activeTab\" },\n { kAlarms, \"alarms\" },\n { kBookmark, \"bookmarks\", kFlagNone,\n IDS_EXTENSION_PROMPT_WARNING_BOOKMARKS,\n PermissionMessage::kBookmarks },\n { kBrowserTag, \"browserTag\", kFlagCannotBeOptional },\n { kBrowsingData, \"browsingData\" },\n { kCommands, \"commands\" },\n { kContentSettings, \"contentSettings\", kFlagNone,\n IDS_EXTENSION_PROMPT_WARNING_CONTENT_SETTINGS,\n PermissionMessage::kContentSettings },\n { kContextMenus, \"contextMenus\" },\n { kCookie, \"cookies\" },\n { kFileBrowserHandler, \"fileBrowserHandler\", kFlagCannotBeOptional },\n { kFontSettings, \"fontSettings\", kFlagCannotBeOptional },\n { kHistory, \"history\", kFlagNone,\n IDS_EXTENSION_PROMPT_WARNING_BROWSING_HISTORY,\n PermissionMessage::kBrowsingHistory },\n { kIdle, \"idle\" },\n { kInput, \"input\", kFlagNone,\n IDS_EXTENSION_PROMPT_WARNING_INPUT,\n PermissionMessage::kInput },\n { kManagement, \"management\", kFlagNone,\n IDS_EXTENSION_PROMPT_WARNING_MANAGEMENT,\n PermissionMessage::kManagement },\n { kMediaGalleries, \"mediaGalleries\" },\n { kMediaGalleriesRead, \"mediaGalleriesRead\" },\n { kPageCapture, \"pageCapture\", kFlagNone,\n IDS_EXTENSION_PROMPT_WARNING_ALL_PAGES_CONTENT,\n PermissionMessage::kAllPageContent },\n { kPrivacy, \"privacy\", kFlagNone,\n IDS_EXTENSION_PROMPT_WARNING_PRIVACY,\n PermissionMessage::kPrivacy },\n { kStorage, \"storage\" },\n { kTab, \"tabs\", kFlagNone,\n IDS_EXTENSION_PROMPT_WARNING_TABS,\n PermissionMessage::kTabs },\n { kTopSites, \"topSites\", kFlagNone,\n IDS_EXTENSION_PROMPT_WARNING_BROWSING_HISTORY,\n PermissionMessage::kBrowsingHistory },\n { kTts, \"tts\", 0, kFlagCannotBeOptional },\n { kTtsEngine, \"ttsEngine\", kFlagCannotBeOptional,\n IDS_EXTENSION_PROMPT_WARNING_TTS_ENGINE,\n PermissionMessage::kTtsEngine },\n { kUsb, \"usb\", kFlagNone,\n IDS_EXTENSION_PROMPT_WARNING_USB,\n PermissionMessage::kNone },\n { kWebNavigation, \"webNavigation\", kFlagNone,\n IDS_EXTENSION_PROMPT_WARNING_TABS, PermissionMessage::kTabs },\n { kWebRequest, \"webRequest\" },\n { kWebRequestBlocking, \"webRequestBlocking\" },\n\n \/\/ Register private permissions.\n { kChromeosInfoPrivate, \"chromeosInfoPrivate\", kFlagCannotBeOptional },\n { kFileBrowserHandlerInternal, \"fileBrowserHandlerInternal\",\n kFlagCannotBeOptional },\n { kFileBrowserPrivate, \"fileBrowserPrivate\", kFlagCannotBeOptional },\n { kManagedModePrivate, \"managedModePrivate\", kFlagCannotBeOptional },\n { kMediaPlayerPrivate, \"mediaPlayerPrivate\", kFlagCannotBeOptional },\n { kMetricsPrivate, \"metricsPrivate\", kFlagCannotBeOptional },\n { kSystemPrivate, \"systemPrivate\", kFlagCannotBeOptional },\n { kChromeAuthPrivate, \"chromeAuthPrivate\", kFlagCannotBeOptional },\n { kInputMethodPrivate, \"inputMethodPrivate\", kFlagCannotBeOptional },\n { kEchoPrivate, \"echoPrivate\", kFlagCannotBeOptional },\n { kTerminalPrivate, \"terminalPrivate\", kFlagCannotBeOptional },\n { kWallpaperPrivate, \"wallpaperPrivate\", kFlagCannotBeOptional },\n { kWebRequestInternal, \"webRequestInternal\" },\n { kWebSocketProxyPrivate, \"webSocketProxyPrivate\", kFlagCannotBeOptional },\n { kWebstorePrivate, \"webstorePrivate\", kFlagCannotBeOptional },\n\n \/\/ Full url access permissions.\n { kProxy, \"proxy\", kFlagImpliesFullURLAccess | kFlagCannotBeOptional },\n { kDebugger, \"debugger\", kFlagImpliesFullURLAccess | kFlagCannotBeOptional,\n IDS_EXTENSION_PROMPT_WARNING_DEBUGGER,\n PermissionMessage::kDebugger },\n { kDevtools, \"devtools\",\n kFlagImpliesFullURLAccess | kFlagCannotBeOptional },\n { kPlugin, \"plugin\",\n kFlagImpliesFullURLAccess | kFlagImpliesFullAccess |\n kFlagCannotBeOptional,\n IDS_EXTENSION_PROMPT_WARNING_FULL_ACCESS,\n PermissionMessage::kFullAccess },\n\n \/\/ Platform-app permissions.\n { kSocket, \"socket\", kFlagCannotBeOptional },\n { kAppWindow, \"app.window\" },\n { kAudioCapture, \"audioCapture\", kFlagNone,\n IDS_EXTENSION_PROMPT_WARNING_AUDIO_CAPTURE,\n PermissionMessage::kAudioCapture },\n { kVideoCapture, \"videoCapture\", kFlagNone,\n IDS_EXTENSION_PROMPT_WARNING_VIDEO_CAPTURE,\n PermissionMessage::kVideoCapture },\n { kFileSystem, \"fileSystem\" },\n { kFileSystemWrite, \"fileSystemWrite\", kFlagNone,\n IDS_EXTENSION_PROMPT_WARNING_FILE_SYSTEM_WRITE,\n PermissionMessage::kFileSystemWrite },\n { kMediaGalleriesAllGalleries, \"mediaGalleriesAllGalleries\",\n kFlagCannotBeOptional,\n IDS_EXTENSION_PROMPT_WARNING_MEDIA_GALLERIES_ALL_GALLERIES,\n PermissionMessage::kMediaGalleriesAllGalleries },\n };\n\n for (size_t i = 0; i < ARRAYSIZE_UNSAFE(PermissionsToRegister); ++i) {\n const PermissionRegistration& pr = PermissionsToRegister[i];\n info->RegisterPermission(\n pr.id, pr.name, pr.l10n_message_id,\n pr.message_id ? pr.message_id : PermissionMessage::kNone,\n pr.flags);\n }\n\n \/\/ Register aliases.\n info->RegisterAlias(\"unlimitedStorage\", kOldUnlimitedStoragePermission);\n info->RegisterAlias(\"tabs\", kWindowsPermission);\n \/\/ TODO(mihaip): Should be removed for the M20 branch, see\n \/\/ http:\/\/crbug.com\/120447 for more details.\n info->RegisterAlias(\"background\", kTemporaryBackgroundAlias);\n}\n\n} \/\/ namespace extensions\n<commit_msg>Explain why the 'fileSystem' permission has no permission string<commit_after>\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/common\/extensions\/permissions\/api_permission.h\"\n\n#include \"chrome\/common\/extensions\/permissions\/permissions_info.h\"\n#include \"grit\/generated_resources.h\"\n#include \"ui\/base\/l10n\/l10n_util.h\"\n\nnamespace {\n\nconst char kOldUnlimitedStoragePermission[] = \"unlimited_storage\";\nconst char kWindowsPermission[] = \"windows\";\nconst char kTemporaryBackgroundAlias[] = \"background_alias_do_not_use\";\n\n} \/\/ namespace\n\nnamespace extensions {\n\n\/\/\n\/\/ APIPermission\n\/\/\n\nAPIPermission::~APIPermission() {}\n\nPermissionMessage APIPermission::GetMessage_() const {\n return PermissionMessage(\n message_id_, l10n_util::GetStringUTF16(l10n_message_id_));\n}\n\nAPIPermission::APIPermission(\n ID id,\n const char* name,\n int l10n_message_id,\n PermissionMessage::ID message_id,\n int flags)\n : id_(id),\n name_(name),\n flags_(flags),\n l10n_message_id_(l10n_message_id),\n message_id_(message_id) {}\n\n\/\/ static\nvoid APIPermission::RegisterAllPermissions(\n PermissionsInfo* info) {\n\n struct PermissionRegistration {\n APIPermission::ID id;\n const char* name;\n int flags;\n int l10n_message_id;\n PermissionMessage::ID message_id;\n } PermissionsToRegister[] = {\n \/\/ Register permissions for all extension types.\n { kBackground, \"background\" },\n { kClipboardRead, \"clipboardRead\", kFlagNone,\n IDS_EXTENSION_PROMPT_WARNING_CLIPBOARD,\n PermissionMessage::kClipboard },\n { kClipboardWrite, \"clipboardWrite\" },\n { kDeclarativeWebRequest, \"declarativeWebRequest\" },\n { kDownloads, \"downloads\", kFlagNone,\n IDS_EXTENSION_PROMPT_WARNING_DOWNLOADS,\n PermissionMessage::kDownloads },\n { kExperimental, \"experimental\", kFlagCannotBeOptional },\n { kGeolocation, \"geolocation\", kFlagCannotBeOptional,\n IDS_EXTENSION_PROMPT_WARNING_GEOLOCATION,\n PermissionMessage::kGeolocation },\n { kNotification, \"notifications\" },\n { kUnlimitedStorage, \"unlimitedStorage\", kFlagCannotBeOptional },\n\n \/\/ Register hosted and packaged app permissions.\n { kAppNotifications, \"appNotifications\" },\n\n \/\/ Register extension permissions.\n { kActiveTab, \"activeTab\" },\n { kAlarms, \"alarms\" },\n { kBookmark, \"bookmarks\", kFlagNone,\n IDS_EXTENSION_PROMPT_WARNING_BOOKMARKS,\n PermissionMessage::kBookmarks },\n { kBrowserTag, \"browserTag\", kFlagCannotBeOptional },\n { kBrowsingData, \"browsingData\" },\n { kCommands, \"commands\" },\n { kContentSettings, \"contentSettings\", kFlagNone,\n IDS_EXTENSION_PROMPT_WARNING_CONTENT_SETTINGS,\n PermissionMessage::kContentSettings },\n { kContextMenus, \"contextMenus\" },\n { kCookie, \"cookies\" },\n { kFileBrowserHandler, \"fileBrowserHandler\", kFlagCannotBeOptional },\n { kFontSettings, \"fontSettings\", kFlagCannotBeOptional },\n { kHistory, \"history\", kFlagNone,\n IDS_EXTENSION_PROMPT_WARNING_BROWSING_HISTORY,\n PermissionMessage::kBrowsingHistory },\n { kIdle, \"idle\" },\n { kInput, \"input\", kFlagNone,\n IDS_EXTENSION_PROMPT_WARNING_INPUT,\n PermissionMessage::kInput },\n { kManagement, \"management\", kFlagNone,\n IDS_EXTENSION_PROMPT_WARNING_MANAGEMENT,\n PermissionMessage::kManagement },\n { kMediaGalleries, \"mediaGalleries\" },\n { kMediaGalleriesRead, \"mediaGalleriesRead\" },\n { kPageCapture, \"pageCapture\", kFlagNone,\n IDS_EXTENSION_PROMPT_WARNING_ALL_PAGES_CONTENT,\n PermissionMessage::kAllPageContent },\n { kPrivacy, \"privacy\", kFlagNone,\n IDS_EXTENSION_PROMPT_WARNING_PRIVACY,\n PermissionMessage::kPrivacy },\n { kStorage, \"storage\" },\n { kTab, \"tabs\", kFlagNone,\n IDS_EXTENSION_PROMPT_WARNING_TABS,\n PermissionMessage::kTabs },\n { kTopSites, \"topSites\", kFlagNone,\n IDS_EXTENSION_PROMPT_WARNING_BROWSING_HISTORY,\n PermissionMessage::kBrowsingHistory },\n { kTts, \"tts\", 0, kFlagCannotBeOptional },\n { kTtsEngine, \"ttsEngine\", kFlagCannotBeOptional,\n IDS_EXTENSION_PROMPT_WARNING_TTS_ENGINE,\n PermissionMessage::kTtsEngine },\n { kUsb, \"usb\", kFlagNone,\n IDS_EXTENSION_PROMPT_WARNING_USB,\n PermissionMessage::kNone },\n { kWebNavigation, \"webNavigation\", kFlagNone,\n IDS_EXTENSION_PROMPT_WARNING_TABS, PermissionMessage::kTabs },\n { kWebRequest, \"webRequest\" },\n { kWebRequestBlocking, \"webRequestBlocking\" },\n\n \/\/ Register private permissions.\n { kChromeosInfoPrivate, \"chromeosInfoPrivate\", kFlagCannotBeOptional },\n { kFileBrowserHandlerInternal, \"fileBrowserHandlerInternal\",\n kFlagCannotBeOptional },\n { kFileBrowserPrivate, \"fileBrowserPrivate\", kFlagCannotBeOptional },\n { kManagedModePrivate, \"managedModePrivate\", kFlagCannotBeOptional },\n { kMediaPlayerPrivate, \"mediaPlayerPrivate\", kFlagCannotBeOptional },\n { kMetricsPrivate, \"metricsPrivate\", kFlagCannotBeOptional },\n { kSystemPrivate, \"systemPrivate\", kFlagCannotBeOptional },\n { kChromeAuthPrivate, \"chromeAuthPrivate\", kFlagCannotBeOptional },\n { kInputMethodPrivate, \"inputMethodPrivate\", kFlagCannotBeOptional },\n { kEchoPrivate, \"echoPrivate\", kFlagCannotBeOptional },\n { kTerminalPrivate, \"terminalPrivate\", kFlagCannotBeOptional },\n { kWallpaperPrivate, \"wallpaperPrivate\", kFlagCannotBeOptional },\n { kWebRequestInternal, \"webRequestInternal\" },\n { kWebSocketProxyPrivate, \"webSocketProxyPrivate\", kFlagCannotBeOptional },\n { kWebstorePrivate, \"webstorePrivate\", kFlagCannotBeOptional },\n\n \/\/ Full url access permissions.\n { kProxy, \"proxy\", kFlagImpliesFullURLAccess | kFlagCannotBeOptional },\n { kDebugger, \"debugger\", kFlagImpliesFullURLAccess | kFlagCannotBeOptional,\n IDS_EXTENSION_PROMPT_WARNING_DEBUGGER,\n PermissionMessage::kDebugger },\n { kDevtools, \"devtools\",\n kFlagImpliesFullURLAccess | kFlagCannotBeOptional },\n { kPlugin, \"plugin\",\n kFlagImpliesFullURLAccess | kFlagImpliesFullAccess |\n kFlagCannotBeOptional,\n IDS_EXTENSION_PROMPT_WARNING_FULL_ACCESS,\n PermissionMessage::kFullAccess },\n\n \/\/ Platform-app permissions.\n { kSocket, \"socket\", kFlagCannotBeOptional },\n { kAppWindow, \"app.window\" },\n { kAudioCapture, \"audioCapture\", kFlagNone,\n IDS_EXTENSION_PROMPT_WARNING_AUDIO_CAPTURE,\n PermissionMessage::kAudioCapture },\n { kVideoCapture, \"videoCapture\", kFlagNone,\n IDS_EXTENSION_PROMPT_WARNING_VIDEO_CAPTURE,\n PermissionMessage::kVideoCapture },\n \/\/ \"fileSystem\" has no permission string because read-only access is only\n \/\/ granted after the user has been shown a file chooser dialog and selected\n \/\/ a file. Selecting the file is considered consent to read it.\n { kFileSystem, \"fileSystem\" },\n { kFileSystemWrite, \"fileSystemWrite\", kFlagNone,\n IDS_EXTENSION_PROMPT_WARNING_FILE_SYSTEM_WRITE,\n PermissionMessage::kFileSystemWrite },\n { kMediaGalleriesAllGalleries, \"mediaGalleriesAllGalleries\",\n kFlagCannotBeOptional,\n IDS_EXTENSION_PROMPT_WARNING_MEDIA_GALLERIES_ALL_GALLERIES,\n PermissionMessage::kMediaGalleriesAllGalleries },\n };\n\n for (size_t i = 0; i < ARRAYSIZE_UNSAFE(PermissionsToRegister); ++i) {\n const PermissionRegistration& pr = PermissionsToRegister[i];\n info->RegisterPermission(\n pr.id, pr.name, pr.l10n_message_id,\n pr.message_id ? pr.message_id : PermissionMessage::kNone,\n pr.flags);\n }\n\n \/\/ Register aliases.\n info->RegisterAlias(\"unlimitedStorage\", kOldUnlimitedStoragePermission);\n info->RegisterAlias(\"tabs\", kWindowsPermission);\n \/\/ TODO(mihaip): Should be removed for the M20 branch, see\n \/\/ http:\/\/crbug.com\/120447 for more details.\n info->RegisterAlias(\"background\", kTemporaryBackgroundAlias);\n}\n\n} \/\/ namespace extensions\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: pe_evalu.cxx,v $\n *\n * $Revision: 1.7 $\n *\n * last change: $Author: vg $ $Date: 2007-09-18 14:19:58 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#include <precomp.h>\n#include <s2_luidl\/pe_evalu.hxx>\n\n\/\/ NOT FULLY DECLARED SERVICES\n#include <ary\/idl\/i_enumvalue.hxx>\n#include <ary\/idl\/i_gate.hxx>\n#include <ary\/idl\/ip_ce.hxx>\n#include <ary_i\/codeinf2.hxx>\n#include <s2_luidl\/tk_ident.hxx>\n#include <s2_luidl\/tk_punct.hxx>\n#include <s2_luidl\/tk_const.hxx>\n\n\nnamespace csi\n{\nnamespace uidl\n{\n\n\n#ifdef DF\n#undef DF\n#endif\n#define DF &PE_Value::On_Default\n\nPE_Value::F_TOK\nPE_Value::aDispatcher[PE_Value::e_STATES_MAX][PE_Value::tt_MAX] =\n { { DF, DF, DF }, \/\/ e_none\n { &PE_Value::On_expect_name_Identifier,\n DF, DF }, \/\/ expect_name\n { DF, &PE_Value::On_got_name_Punctuation,\n &PE_Value::On_got_name_Assignment } \/\/ got_name\n };\n\n\n\ninline void\nPE_Value::CallHandler( const char * i_sTokenText,\n E_TokenType i_eTokenType )\n { (this->*aDispatcher[eState][i_eTokenType])(i_sTokenText); }\n\n\n\n\n\nPE_Value::PE_Value( udmstri & o_rName,\n udmstri & o_rAssignment,\n bool i_bIsConst )\n : eState(e_none),\n pName(&o_rName),\n pAssignment(&o_rAssignment),\n bIsConst(i_bIsConst)\n{\n}\n\nvoid\nPE_Value::EstablishContacts( UnoIDL_PE * io_pParentPE,\n ary::n22::Repository & io_rRepository,\n TokenProcessing_Result & o_rResult )\n{\n UnoIDL_PE::EstablishContacts(io_pParentPE,io_rRepository,o_rResult);\n}\n\nPE_Value::~PE_Value()\n{\n}\n\nvoid\nPE_Value::ProcessToken( const Token & i_rToken )\n{\n i_rToken.Trigger(*this);\n}\n\nvoid\nPE_Value::Process_Identifier( const TokIdentifier & i_rToken )\n{\n CallHandler(i_rToken.Text(), tt_identifier);\n}\n\nvoid\nPE_Value::Process_Punctuation( const TokPunctuation & i_rToken )\n{\n CallHandler(i_rToken.Text(), tt_punctuation);\n}\n\nvoid\nPE_Value::Process_Assignment( const TokAssignment & i_rToken )\n{\n CallHandler(i_rToken.Text(), tt_assignment);\n}\n\nvoid\nPE_Value::On_expect_name_Identifier(const char * i_sText)\n{\n *pName = i_sText;\n SetResult(done,stay);\n eState = got_name;\n}\n\nvoid\nPE_Value::On_got_name_Punctuation(const char * i_sText)\n{\n if ( i_sText[0] == ',' AND NOT IsConst()\n OR i_sText[0] == ';' AND IsConst() )\n {\n SetResult(done,pop_success);\n eState = e_none;\n }\n else if (i_sText[0] == '}' AND NOT IsConst())\n {\n SetResult(not_done,pop_success);\n eState = e_none;\n }\n else\n On_Default(i_sText);\n}\n\nvoid\nPE_Value::On_got_name_Assignment(const char * i_sText)\n{\n *pAssignment = i_sText;\n SetResult(done,pop_success);\n eState = e_none;\n}\n\nvoid\nPE_Value::On_Default(const char * )\n{\n SetResult(not_done,pop_failure);\n}\n\nvoid\nPE_Value::InitData()\n{\n eState = expect_name;\n\n *pName = \"\";\n *pAssignment = \"\";\n}\n\nvoid\nPE_Value::TransferData()\n{\n csv_assert(pName->length() > 0);\n eState = e_none;\n}\n\nUnoIDL_PE &\nPE_Value::MyPE()\n{\n return *this;\n}\n\n} \/\/ namespace uidl\n} \/\/ namespace csi\n\n<commit_msg>INTEGRATION: CWS adc18 (1.7.2); FILE MERGED 2007\/10\/19 10:37:31 np 1.7.2.2: #i81775# 2007\/10\/18 15:23:20 np 1.7.2.1: #i81775#<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: pe_evalu.cxx,v $\n *\n * $Revision: 1.8 $\n *\n * last change: $Author: hr $ $Date: 2007-11-02 17:06:44 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#include <precomp.h>\n#include <s2_luidl\/pe_evalu.hxx>\n\n\/\/ NOT FULLY DECLARED SERVICES\n#include <ary\/idl\/i_enumvalue.hxx>\n#include <ary\/idl\/i_gate.hxx>\n#include <ary\/idl\/ip_ce.hxx>\n#include <ary\/doc\/d_oldidldocu.hxx>\n#include <s2_luidl\/tk_ident.hxx>\n#include <s2_luidl\/tk_punct.hxx>\n#include <s2_luidl\/tk_const.hxx>\n\n\nnamespace csi\n{\nnamespace uidl\n{\n\n\n#ifdef DF\n#undef DF\n#endif\n#define DF &PE_Value::On_Default\n\nPE_Value::F_TOK\nPE_Value::aDispatcher[PE_Value::e_STATES_MAX][PE_Value::tt_MAX] =\n { { DF, DF, DF }, \/\/ e_none\n { &PE_Value::On_expect_name_Identifier,\n DF, DF }, \/\/ expect_name\n { DF, &PE_Value::On_got_name_Punctuation,\n &PE_Value::On_got_name_Assignment } \/\/ got_name\n };\n\n\n\ninline void\nPE_Value::CallHandler( const char * i_sTokenText,\n E_TokenType i_eTokenType )\n { (this->*aDispatcher[eState][i_eTokenType])(i_sTokenText); }\n\n\n\n\n\nPE_Value::PE_Value( String & o_rName,\n String & o_rAssignment,\n bool i_bIsConst )\n : eState(e_none),\n pName(&o_rName),\n pAssignment(&o_rAssignment),\n bIsConst(i_bIsConst)\n{\n}\n\nvoid\nPE_Value::EstablishContacts( UnoIDL_PE * io_pParentPE,\n ary::Repository & io_rRepository,\n TokenProcessing_Result & o_rResult )\n{\n UnoIDL_PE::EstablishContacts(io_pParentPE,io_rRepository,o_rResult);\n}\n\nPE_Value::~PE_Value()\n{\n}\n\nvoid\nPE_Value::ProcessToken( const Token & i_rToken )\n{\n i_rToken.Trigger(*this);\n}\n\nvoid\nPE_Value::Process_Identifier( const TokIdentifier & i_rToken )\n{\n CallHandler(i_rToken.Text(), tt_identifier);\n}\n\nvoid\nPE_Value::Process_Punctuation( const TokPunctuation & i_rToken )\n{\n CallHandler(i_rToken.Text(), tt_punctuation);\n}\n\nvoid\nPE_Value::Process_Assignment( const TokAssignment & i_rToken )\n{\n CallHandler(i_rToken.Text(), tt_assignment);\n}\n\nvoid\nPE_Value::On_expect_name_Identifier(const char * i_sText)\n{\n *pName = i_sText;\n SetResult(done,stay);\n eState = got_name;\n}\n\nvoid\nPE_Value::On_got_name_Punctuation(const char * i_sText)\n{\n if ( i_sText[0] == ',' AND NOT IsConst()\n OR i_sText[0] == ';' AND IsConst() )\n {\n SetResult(done,pop_success);\n eState = e_none;\n }\n else if (i_sText[0] == '}' AND NOT IsConst())\n {\n SetResult(not_done,pop_success);\n eState = e_none;\n }\n else\n On_Default(i_sText);\n}\n\nvoid\nPE_Value::On_got_name_Assignment(const char * i_sText)\n{\n *pAssignment = i_sText;\n SetResult(done,pop_success);\n eState = e_none;\n}\n\nvoid\nPE_Value::On_Default(const char * )\n{\n SetResult(not_done,pop_failure);\n}\n\nvoid\nPE_Value::InitData()\n{\n eState = expect_name;\n\n *pName = \"\";\n *pAssignment = \"\";\n}\n\nvoid\nPE_Value::TransferData()\n{\n csv_assert(pName->length() > 0);\n eState = e_none;\n}\n\nUnoIDL_PE &\nPE_Value::MyPE()\n{\n return *this;\n}\n\n} \/\/ namespace uidl\n} \/\/ namespace csi\n\n<|endoftext|>"} {"text":"<commit_before><commit_msg>Task: Lexer::Type::word arguments are dequoted before being stored<commit_after><|endoftext|>"} {"text":"<commit_before>#line 2 \"togo\/utility\/utility.hpp\"\n\/**\n@copyright MIT license; see @ref index or the accompanying LICENSE file.\n\n@file\n@brief Utilities.\n@ingroup utility\n*\/\n\n#pragma once\n\n#include <togo\/config.hpp>\n#include <togo\/types.hpp>\n#include <togo\/error\/assert.hpp>\n#include <togo\/utility\/types.hpp>\n#include <togo\/utility\/traits.hpp>\n#include <togo\/utility\/constraints.hpp>\n\n#include <type_traits>\n\nnamespace togo {\n\n\/**\n\t@addtogroup utility\n\t@{\n*\/\n\n\/** @name Type utilities *\/ \/\/\/ @{\n\n\/\/\/ Cast unsigned integral to signed integral.\ntemplate<class T>\ninline constexpr typename std::make_signed<T>::type\nsigned_cast(T const value) noexcept {\n\treturn static_cast<typename std::make_signed<T>::type>(value);\n}\n\n\/\/\/ Cast signed integral to unsigned integral.\ntemplate<class T>\ninline constexpr typename std::make_unsigned<T>::type\nunsigned_cast(T const value) noexcept {\n\treturn static_cast<typename std::make_unsigned<T>::type>(value);\n}\n\n\/\/\/ Get number of elements in bounded array.\ntemplate<class T, unsigned N>\ninline constexpr unsigned\narray_extent(T const (&)[N]) noexcept {\n\treturn N;\n}\n\n\/\/\/ Get number of elements in bounded array.\ntemplate<class T, class U, unsigned N>\ninline constexpr unsigned\narray_extent(T const (U::* const)[N]) noexcept {\n\treturn N;\n}\n\n\/\/\/ Get sizeof type or 0 if the type is empty.\ntemplate<class T>\ninline constexpr unsigned\nsizeof_empty() noexcept {\n\treturn std::is_empty<T>::value ? 0 : sizeof(T);\n}\n\n\/\/\/ @}\n\n\/** @name Misc utilities *\/ \/\/\/ @{\n\n\/\/\/ Make an rvalue reference.\n\/\/\/\n\/\/\/ This is equivalent to std::move(), whose name is totally bonkers.\ntemplate<class T>\ninline constexpr remove_ref<T>&& rvalue_ref(T&& x) noexcept {\n\treturn static_cast<remove_ref<T>&&>(x);\n}\n\n\/\/\/ Retain value category when passing to another function.\n\/\/\/\n\/\/\/ This is equivalent to std::forward().\ntemplate<class T>\ninline constexpr T&& forward(remove_ref<T>& x) noexcept {\n\treturn static_cast<T&&>(x);\n}\n\ntemplate<class T>\ninline constexpr T&& forward(remove_ref<T>&& x) noexcept {\n\tstatic_assert(\n\t\t!is_lvalue_reference<T>::value,\n\t\t\"rvalue cannot be forwarded as an lvalue\"\n\t);\n\treturn static_cast<T&&>(x);\n}\n\n\/\/\/ A type as an unevaluated value.\n\/\/\/\n\/\/\/ This is equivalent to std::declval().\ntemplate<class T>\ninline add_rvalue_ref<T> type_value() noexcept;\n\n\/\/\/ Swap the values of two references.\ntemplate<class T>\ninline void swap(T& x, T& y) {\n\tT temp = x;\n\tx = y;\n\ty = temp;\n}\n\n\/\/\/ Less-than comparison operator wrapper.\ntemplate<class T>\ninline bool less(T const& x, T const& y) {\n\treturn x < y;\n}\n\n\/\/\/ Greater-than comparison operator wrapper.\ntemplate<class T>\ninline bool greater(T const& x, T const& y) {\n\treturn x > y;\n}\n\n\/\/\/ @}\n\n\/** @name Arithmetic utilities *\/ \/\/\/ @{\n\n\/\/\/ Get the smallest of two values.\ntemplate<class T>\ninline constexpr T min(T const x, T const y) noexcept {\n\tTOGO_CONSTRAIN_INTEGRAL(T);\n\treturn x < y ? x : y;\n}\n\n\/\/\/ Get the largest of two values.\ntemplate<class T>\ninline constexpr T max(T const x, T const y) noexcept {\n\tTOGO_CONSTRAIN_INTEGRAL(T);\n\treturn x > y ? x : y;\n}\n\n\/\/\/ Clamp a value between a minimum and maximum.\ntemplate<class T>\ninline constexpr T clamp(T const x, T const minimum, T const maximum) noexcept {\n\tTOGO_CONSTRAIN_INTEGRAL(T);\n\treturn\n\t\t x < minimum\n\t\t? minimum\n\t\t: x > maximum\n\t\t? maximum\n\t\t: x\n\t;\n}\n\n\/\/\/ @}\n\n\/** @name Memory utilities *\/ \/\/\/ @{\n\n\/\/\/ Advance pointer by bytes.\n\/\/\/ @warning This advances by bytes, not sizeof(T).\ntemplate<class T>\ninline T* pointer_add(T* p, u32 const bytes) noexcept {\n\treturn reinterpret_cast<T*>(\n\t\treinterpret_cast<type_if<is_const<T>::value, char const*, char*>>(p) + bytes\n\t);\n}\n\n\/\/\/ Aligns a pointer by moving it forward.\ntemplate<class T>\ninline T* pointer_align(T* p, u32 const align) noexcept {\n\tu32 const m = reinterpret_cast<std::uintptr_t>(p) % align;\n\tif (m) {\n\t\tp = pointer_add(p, align - m);\n\t}\n\treturn p;\n}\n\n\/\/\/ @}\n\n\/** @name Enum utilities *\/ \/\/\/ @{\n\n\/\/\/ Return true whether an enum value is non-zero.\ntemplate<class T>\ninline constexpr bool enum_bool(T const value) {\n\tstatic_assert(\n\t\tstd::is_enum<T>::value,\n\t\t\"T must be an enum\"\n\t);\n\treturn static_cast<typename std::underlying_type<T>::type>(value);\n}\n\n\/** @cond INTERNAL *\/\ntemplate<class FlagT, class = enable_if<enable_enum_bitwise_ops<FlagT>::value>>\ninline constexpr FlagT operator|(FlagT const& x, FlagT const& y) noexcept {\n\treturn static_cast<FlagT>(\n\t\tstatic_cast<unsigned>(x) | static_cast<unsigned>(y)\n\t);\n}\n\ntemplate<class FlagT, class = enable_if<enable_enum_bitwise_ops<FlagT>::value>>\ninline constexpr FlagT operator&(FlagT const& x, FlagT const& y) noexcept {\n\treturn static_cast<FlagT>(\n\t\tstatic_cast<unsigned>(x) & static_cast<unsigned>(y)\n\t);\n}\n\ntemplate<class FlagT, class = enable_if<enable_enum_bitwise_ops<FlagT>::value>>\ninline constexpr FlagT operator~(FlagT const& x) noexcept {\n\treturn static_cast<FlagT>(\n\t\t~static_cast<unsigned>(x)\n\t);\n}\n\ntemplate<class FlagT, class = enable_if<enable_enum_bitwise_ops<FlagT>::value>>\ninline constexpr FlagT& operator|=(FlagT& x, FlagT const& y) noexcept {\n\treturn x = static_cast<FlagT>(\n\t\tstatic_cast<unsigned>(x) | static_cast<unsigned>(y)\n\t);\n}\n\ntemplate<class FlagT, class = enable_if<enable_enum_bitwise_ops<FlagT>::value>>\ninline constexpr FlagT& operator&=(FlagT& x, FlagT const& y) noexcept {\n\treturn x = static_cast<FlagT>(\n\t\tstatic_cast<unsigned>(x) & static_cast<unsigned>(y)\n\t);\n}\n\/** @endcond *\/ \/\/ INTERNAL\n\n\/\/\/ @}\n\n\/** @name Collection utilities *\/ \/\/\/ @{\n\ntemplate<class T>\nstruct ArrayRef {\n\tT* _begin;\n\tT* _end;\n\n\tinline ArrayRef(T* const begin, T* const end)\n\t\t: _begin(begin)\n\t\t, _end(end)\n\t{}\n\n\ttemplate<class U, class = enable_if<std::is_convertible<U, T>::value>>\n\tinline ArrayRef(ArrayRef<U> const& other)\n\t\t: _begin(other._begin)\n\t\t, _end(other._end)\n\t{}\n\n\t\/\/\/ Number of items.\n\tunsigned size() const {\n\t\treturn _end - _begin;\n\t}\n\n\t\/\/\/ Access value by index.\n\tT& operator[](unsigned const i) {\n\t\tTOGO_DEBUG_ASSERTE(_begin + i < _end);\n\t\treturn _begin[i];\n\t}\n\n\t\/\/\/ Access value by index.\n\tT const& operator[](unsigned const i) const {\n\t\tTOGO_DEBUG_ASSERTE(_begin + i < _end);\n\t\treturn _begin[i];\n\t}\n};\n\n\/\/\/ Make reference to array.\ntemplate<class T>\ninline ArrayRef<T> array_ref(unsigned const size, T* const data) {\n\treturn ArrayRef<T>{data, data + size};\n}\n\n\/** @cond INTERNAL *\/\ntemplate<class T>\ninline T* begin(ArrayRef<T> const& ar) { return ar._begin; }\n\ntemplate<class T>\ninline T const* cbegin(ArrayRef<T> const& ar) { return ar._begin; }\n\ntemplate<class T>\ninline T* end(ArrayRef<T> const& ar) { return ar._end; }\n\ntemplate<class T>\ninline T const* cend(ArrayRef<T> const& ar) { return ar._end; }\n\/** @endcond *\/ \/\/ INTERNAL\n\n\/\/\/ @}\n\n\/** @} *\/ \/\/ end of doc-group utility\n\n} \/\/ namespace togo\n<commit_msg>utility: added null_ref_tag ArrayRef<T> ctor.<commit_after>#line 2 \"togo\/utility\/utility.hpp\"\n\/**\n@copyright MIT license; see @ref index or the accompanying LICENSE file.\n\n@file\n@brief Utilities.\n@ingroup utility\n*\/\n\n#pragma once\n\n#include <togo\/config.hpp>\n#include <togo\/types.hpp>\n#include <togo\/error\/assert.hpp>\n#include <togo\/utility\/types.hpp>\n#include <togo\/utility\/tags.hpp>\n#include <togo\/utility\/traits.hpp>\n#include <togo\/utility\/constraints.hpp>\n\n#include <type_traits>\n\nnamespace togo {\n\n\/**\n\t@addtogroup utility\n\t@{\n*\/\n\n\/** @name Type utilities *\/ \/\/\/ @{\n\n\/\/\/ Cast unsigned integral to signed integral.\ntemplate<class T>\ninline constexpr typename std::make_signed<T>::type\nsigned_cast(T const value) noexcept {\n\treturn static_cast<typename std::make_signed<T>::type>(value);\n}\n\n\/\/\/ Cast signed integral to unsigned integral.\ntemplate<class T>\ninline constexpr typename std::make_unsigned<T>::type\nunsigned_cast(T const value) noexcept {\n\treturn static_cast<typename std::make_unsigned<T>::type>(value);\n}\n\n\/\/\/ Get number of elements in bounded array.\ntemplate<class T, unsigned N>\ninline constexpr unsigned\narray_extent(T const (&)[N]) noexcept {\n\treturn N;\n}\n\n\/\/\/ Get number of elements in bounded array.\ntemplate<class T, class U, unsigned N>\ninline constexpr unsigned\narray_extent(T const (U::* const)[N]) noexcept {\n\treturn N;\n}\n\n\/\/\/ Get sizeof type or 0 if the type is empty.\ntemplate<class T>\ninline constexpr unsigned\nsizeof_empty() noexcept {\n\treturn std::is_empty<T>::value ? 0 : sizeof(T);\n}\n\n\/\/\/ @}\n\n\/** @name Misc utilities *\/ \/\/\/ @{\n\n\/\/\/ Make an rvalue reference.\n\/\/\/\n\/\/\/ This is equivalent to std::move(), whose name is totally bonkers.\ntemplate<class T>\ninline constexpr remove_ref<T>&& rvalue_ref(T&& x) noexcept {\n\treturn static_cast<remove_ref<T>&&>(x);\n}\n\n\/\/\/ Retain value category when passing to another function.\n\/\/\/\n\/\/\/ This is equivalent to std::forward().\ntemplate<class T>\ninline constexpr T&& forward(remove_ref<T>& x) noexcept {\n\treturn static_cast<T&&>(x);\n}\n\ntemplate<class T>\ninline constexpr T&& forward(remove_ref<T>&& x) noexcept {\n\tstatic_assert(\n\t\t!is_lvalue_reference<T>::value,\n\t\t\"rvalue cannot be forwarded as an lvalue\"\n\t);\n\treturn static_cast<T&&>(x);\n}\n\n\/\/\/ A type as an unevaluated value.\n\/\/\/\n\/\/\/ This is equivalent to std::declval().\ntemplate<class T>\ninline add_rvalue_ref<T> type_value() noexcept;\n\n\/\/\/ Swap the values of two references.\ntemplate<class T>\ninline void swap(T& x, T& y) {\n\tT temp = x;\n\tx = y;\n\ty = temp;\n}\n\n\/\/\/ Less-than comparison operator wrapper.\ntemplate<class T>\ninline bool less(T const& x, T const& y) {\n\treturn x < y;\n}\n\n\/\/\/ Greater-than comparison operator wrapper.\ntemplate<class T>\ninline bool greater(T const& x, T const& y) {\n\treturn x > y;\n}\n\n\/\/\/ @}\n\n\/** @name Arithmetic utilities *\/ \/\/\/ @{\n\n\/\/\/ Get the smallest of two values.\ntemplate<class T>\ninline constexpr T min(T const x, T const y) noexcept {\n\tTOGO_CONSTRAIN_INTEGRAL(T);\n\treturn x < y ? x : y;\n}\n\n\/\/\/ Get the largest of two values.\ntemplate<class T>\ninline constexpr T max(T const x, T const y) noexcept {\n\tTOGO_CONSTRAIN_INTEGRAL(T);\n\treturn x > y ? x : y;\n}\n\n\/\/\/ Clamp a value between a minimum and maximum.\ntemplate<class T>\ninline constexpr T clamp(T const x, T const minimum, T const maximum) noexcept {\n\tTOGO_CONSTRAIN_INTEGRAL(T);\n\treturn\n\t\t x < minimum\n\t\t? minimum\n\t\t: x > maximum\n\t\t? maximum\n\t\t: x\n\t;\n}\n\n\/\/\/ @}\n\n\/** @name Memory utilities *\/ \/\/\/ @{\n\n\/\/\/ Advance pointer by bytes.\n\/\/\/ @warning This advances by bytes, not sizeof(T).\ntemplate<class T>\ninline T* pointer_add(T* p, u32 const bytes) noexcept {\n\treturn reinterpret_cast<T*>(\n\t\treinterpret_cast<type_if<is_const<T>::value, char const*, char*>>(p) + bytes\n\t);\n}\n\n\/\/\/ Aligns a pointer by moving it forward.\ntemplate<class T>\ninline T* pointer_align(T* p, u32 const align) noexcept {\n\tu32 const m = reinterpret_cast<std::uintptr_t>(p) % align;\n\tif (m) {\n\t\tp = pointer_add(p, align - m);\n\t}\n\treturn p;\n}\n\n\/\/\/ @}\n\n\/** @name Enum utilities *\/ \/\/\/ @{\n\n\/\/\/ Return true whether an enum value is non-zero.\ntemplate<class T>\ninline constexpr bool enum_bool(T const value) {\n\tstatic_assert(\n\t\tstd::is_enum<T>::value,\n\t\t\"T must be an enum\"\n\t);\n\treturn static_cast<typename std::underlying_type<T>::type>(value);\n}\n\n\/** @cond INTERNAL *\/\ntemplate<class FlagT, class = enable_if<enable_enum_bitwise_ops<FlagT>::value>>\ninline constexpr FlagT operator|(FlagT const& x, FlagT const& y) noexcept {\n\treturn static_cast<FlagT>(\n\t\tstatic_cast<unsigned>(x) | static_cast<unsigned>(y)\n\t);\n}\n\ntemplate<class FlagT, class = enable_if<enable_enum_bitwise_ops<FlagT>::value>>\ninline constexpr FlagT operator&(FlagT const& x, FlagT const& y) noexcept {\n\treturn static_cast<FlagT>(\n\t\tstatic_cast<unsigned>(x) & static_cast<unsigned>(y)\n\t);\n}\n\ntemplate<class FlagT, class = enable_if<enable_enum_bitwise_ops<FlagT>::value>>\ninline constexpr FlagT operator~(FlagT const& x) noexcept {\n\treturn static_cast<FlagT>(\n\t\t~static_cast<unsigned>(x)\n\t);\n}\n\ntemplate<class FlagT, class = enable_if<enable_enum_bitwise_ops<FlagT>::value>>\ninline constexpr FlagT& operator|=(FlagT& x, FlagT const& y) noexcept {\n\treturn x = static_cast<FlagT>(\n\t\tstatic_cast<unsigned>(x) | static_cast<unsigned>(y)\n\t);\n}\n\ntemplate<class FlagT, class = enable_if<enable_enum_bitwise_ops<FlagT>::value>>\ninline constexpr FlagT& operator&=(FlagT& x, FlagT const& y) noexcept {\n\treturn x = static_cast<FlagT>(\n\t\tstatic_cast<unsigned>(x) & static_cast<unsigned>(y)\n\t);\n}\n\/** @endcond *\/ \/\/ INTERNAL\n\n\/\/\/ @}\n\n\/** @name Collection utilities *\/ \/\/\/ @{\n\ntemplate<class T>\nstruct ArrayRef {\n\tT* _begin;\n\tT* _end;\n\n\tinline ArrayRef(null_ref_tag const)\n\t\t: _begin(nullptr)\n\t\t, _end(nullptr)\n\t{}\n\n\tinline ArrayRef(T* const begin, T* const end)\n\t\t: _begin(begin)\n\t\t, _end(end)\n\t{}\n\n\ttemplate<class U, class = enable_if<std::is_convertible<U, T>::value>>\n\tinline ArrayRef(ArrayRef<U> const& other)\n\t\t: _begin(other._begin)\n\t\t, _end(other._end)\n\t{}\n\n\t\/\/\/ Number of items.\n\tunsigned size() const {\n\t\treturn _end - _begin;\n\t}\n\n\t\/\/\/ Access value by index.\n\tT& operator[](unsigned const i) {\n\t\tTOGO_DEBUG_ASSERTE(_begin + i < _end);\n\t\treturn _begin[i];\n\t}\n\n\t\/\/\/ Access value by index.\n\tT const& operator[](unsigned const i) const {\n\t\tTOGO_DEBUG_ASSERTE(_begin + i < _end);\n\t\treturn _begin[i];\n\t}\n};\n\n\/\/\/ Make reference to array.\ntemplate<class T>\ninline ArrayRef<T> array_ref(unsigned const size, T* const data) {\n\treturn ArrayRef<T>{data, data + size};\n}\n\n\/** @cond INTERNAL *\/\ntemplate<class T>\ninline T* begin(ArrayRef<T> const& ar) { return ar._begin; }\n\ntemplate<class T>\ninline T const* cbegin(ArrayRef<T> const& ar) { return ar._begin; }\n\ntemplate<class T>\ninline T* end(ArrayRef<T> const& ar) { return ar._end; }\n\ntemplate<class T>\ninline T const* cend(ArrayRef<T> const& ar) { return ar._end; }\n\/** @endcond *\/ \/\/ INTERNAL\n\n\/\/\/ @}\n\n\/** @} *\/ \/\/ end of doc-group utility\n\n} \/\/ namespace togo\n<|endoftext|>"} {"text":"<commit_before>\/***************************************************************************\n**\n** Copyright (C) 2010 Nokia Corporation and\/or its subsidiary(-ies).\n** All rights reserved.\n** Contact: Nokia Corporation (testabilitydriver@nokia.com)\n**\n** This file is part of Testability Driver.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at testabilitydriver@nokia.com .\n**\n** This library is free software; you can redistribute it and\/or\n** modify it under the terms of the GNU Lesser General Public\n** License version 2.1 as published by the Free Software Foundation\n** and appearing in the file LICENSE.LGPL included in the packaging\n** of this file.\n**\n****************************************************************************\/\n\n\n\n#include <QtPlugin>\n#include <QDebug>\n#include <QHash>\n\n#include <QVariant>\n\n\/\/#include <QDomElement>\n\/\/#include <QDomDocument>\n\n#include <visualizeraccessor.h>\n#include <tasqtdatamodel.h>\n\n#include <tdriver_tabbededitor.h>\n\/\/\n\/\/#include <dispatcher.h>\n\/\/#include <includes.h>\n\nQ_EXPORT_PLUGIN2(visualizeraccessor, VisualizerAccessor)\n\n\/\/ fixture version information\nstatic QString FIXTURE_NAME = \"VisualizerAccessor\";\nstatic QString FIXTURE_VERSION = \"0.1\";\nstatic QString FIXTURE_DESCRIPTION = \"API for accessing applications internal Qt methods\";\n\n\/\/ hash keys\nstatic QString CLASS_NAME = \"class\";\nstatic QString METHOD_NAME = \"method\";\nstatic QString METHOD_ARGS = \"args\";\n\n\/\/ Constructor\nVisualizerAccessor::VisualizerAccessor( QObject *parent ) : QObject( parent )\n{\n\n}\n\n\nbool VisualizerAccessor::execute(void * objectInstance, QString commandName, QHash<QString, QString> parameters, QString & resultString)\n{\n qDebug() << \"VisualizerAccessor::execute\";\n qDebug() << \"command:\" << commandName;\n qDebug() << \"parameters\" << parameters;\n\n bool result = false;\n resultString = commandName;\n\n static QStringList valid_commands(QStringList() << \"ping\" << \"editor_save\" << \"editor_load\");\n\n if (!valid_commands.contains(commandName)) {\n resultString += \" error: invalid command\";\n }\n\n \/\/ first commands that do not need editor instance\n else if (commandName == \"ping\") {\n if (parameters.contains(\"data\")) resultString = parameters[\"data\"];\n else resultString = \"pong\";\n result = true;\n }\n\n \/\/ then commands that need editor instance\n else {\n \/\/ TODO: add code to check that objectInstance really is a QObject pointer\n TDriverTabbedEditor *tabs = qobject_cast<TDriverTabbedEditor*>(\n reinterpret_cast<QObject*>(objectInstance));\n QString className = (tabs) ? tabs->metaObject()->className() : \"<invalid>\";\n\n if (!tabs) {\n resultString = (commandName + \" error: invalid object @0x%1 class name '%2'\")\n .arg(reinterpret_cast<uint>(objectInstance), 8, 16, QChar('0'))\n .arg(className);\n }\n\n else if (commandName == \"editor_save\") {\n if (parameters.contains(\"filename\")) {\n int index = QVariant(parameters.value(\"tabindex\", \"-1\")).toInt(&result);\n if (result) {\n result = tabs->saveFile(parameters[\"filename\"], index, true);\n resultString += \": saveFile called\";\n }\n else {\n resultString += \" error: invalid tab index\";\n }\n }\n else {\n resultString += \" error: missing command parameter: filename\";\n }\n }\n\n else if (commandName == \"editor_load\") {\n if (parameters.contains(\"filename\")) {\n result = tabs->loadFile(parameters[\"filename\"], QVariant(parameters.value(\"istemplate\", false)).toBool());\n resultString += \": loadFile called\";\n }\n else\n resultString += \" error: missing command parameter: filename\";\n }\n }\n\n return result;\n\n}\n<commit_msg>Fixed one more 64 bit incompatible cast from pointer to integer, in fixture.<commit_after>\/***************************************************************************\n**\n** Copyright (C) 2010 Nokia Corporation and\/or its subsidiary(-ies).\n** All rights reserved.\n** Contact: Nokia Corporation (testabilitydriver@nokia.com)\n**\n** This file is part of Testability Driver.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at testabilitydriver@nokia.com .\n**\n** This library is free software; you can redistribute it and\/or\n** modify it under the terms of the GNU Lesser General Public\n** License version 2.1 as published by the Free Software Foundation\n** and appearing in the file LICENSE.LGPL included in the packaging\n** of this file.\n**\n****************************************************************************\/\n\n\n\n#include <QtPlugin>\n#include <QDebug>\n#include <QHash>\n\n#include <QVariant>\n\n\/\/#include <QDomElement>\n\/\/#include <QDomDocument>\n\n#include <visualizeraccessor.h>\n#include <tasqtdatamodel.h>\n\n#include <tdriver_tabbededitor.h>\n\/\/\n\/\/#include <dispatcher.h>\n\/\/#include <includes.h>\n\nQ_EXPORT_PLUGIN2(visualizeraccessor, VisualizerAccessor)\n\n\/\/ fixture version information\nstatic QString FIXTURE_NAME = \"VisualizerAccessor\";\nstatic QString FIXTURE_VERSION = \"0.1\";\nstatic QString FIXTURE_DESCRIPTION = \"API for accessing applications internal Qt methods\";\n\n\/\/ hash keys\nstatic QString CLASS_NAME = \"class\";\nstatic QString METHOD_NAME = \"method\";\nstatic QString METHOD_ARGS = \"args\";\n\n\/\/ Constructor\nVisualizerAccessor::VisualizerAccessor( QObject *parent ) : QObject( parent )\n{\n\n}\n\n\nbool VisualizerAccessor::execute(void * objectInstance, QString commandName, QHash<QString, QString> parameters, QString & resultString)\n{\n qDebug() << \"VisualizerAccessor::execute\";\n qDebug() << \"command:\" << commandName;\n qDebug() << \"parameters\" << parameters;\n\n bool result = false;\n resultString = commandName;\n\n static QStringList valid_commands(QStringList() << \"ping\" << \"editor_save\" << \"editor_load\");\n\n if (!valid_commands.contains(commandName)) {\n resultString += \" error: invalid command\";\n }\n\n \/\/ first commands that do not need editor instance\n else if (commandName == \"ping\") {\n if (parameters.contains(\"data\")) resultString = parameters[\"data\"];\n else resultString = \"pong\";\n result = true;\n }\n\n \/\/ then commands that need editor instance\n else {\n \/\/ TODO: add code to check that objectInstance really is a QObject pointer\n TDriverTabbedEditor *tabs = qobject_cast<TDriverTabbedEditor*>(\n reinterpret_cast<QObject*>(objectInstance));\n QString className = (tabs) ? tabs->metaObject()->className() : \"<invalid>\";\n\n if (!tabs) {\n resultString = (commandName + \" error: invalid object @0x%1 class name '%2'\")\n .arg(reinterpret_cast<ulong>(objectInstance), 8, 16, QChar('0'))\n .arg(className);\n }\n\n else if (commandName == \"editor_save\") {\n if (parameters.contains(\"filename\")) {\n int index = QVariant(parameters.value(\"tabindex\", \"-1\")).toInt(&result);\n if (result) {\n result = tabs->saveFile(parameters[\"filename\"], index, true);\n resultString += \": saveFile called\";\n }\n else {\n resultString += \" error: invalid tab index\";\n }\n }\n else {\n resultString += \" error: missing command parameter: filename\";\n }\n }\n\n else if (commandName == \"editor_load\") {\n if (parameters.contains(\"filename\")) {\n result = tabs->loadFile(parameters[\"filename\"], QVariant(parameters.value(\"istemplate\", false)).toBool());\n resultString += \": loadFile called\";\n }\n else\n resultString += \" error: missing command parameter: filename\";\n }\n }\n\n return result;\n\n}\n<|endoftext|>"} {"text":"<commit_before>\n#include \"Gameboy.hpp\"\n\n#include \"OpenGLWindow.hpp\"\n#include \"DbWindow.hpp\"\n#include \"registerAddr.hpp\"\n\n#include \"Cpu.hpp\"\n#include \"Gpu.hpp\"\n#include \"Memory.hpp\"\n#include \"Timer.hpp\"\n#include \"Audio.hpp\"\n\nvoid setLowBit(Memory *memory, uint16_t addr, uint8_t bit)\n{\n\tmemory->write_byte(addr, (uint8_t)((0x01 << bit) ^ memory->read_byte(addr)), true);\n}\n\nvoid setHightBit(Memory *memory, uint16_t addr, uint8_t bit)\n{\n\tmemory->write_byte(addr, (uint8_t)((0x01 << bit) | memory->read_byte(addr)), true);\n}\n\nGameboy::Gameboy(const char *path) :\n\t_window(OpenGLWindow::Instance())\n\t, _windowDebug(nullptr)\n\t, _thread(nullptr)\n\t, _romPath(path)\n{\n\t_stepMode.store(false);\n\t_willRun.store(false);\n\n\tconnect(_window, &OpenGLWindow::openRomSign, this, &Gameboy::openRomSlot);\n\tconnect(_window, &OpenGLWindow::gbDbSign, this, &Gameboy::gbDbSlot);\n\tconnect(_window, &OpenGLWindow::keyPressSign, this, &Gameboy::KeyPress);\n\tconnect(_window, &OpenGLWindow::keyReleaseSign, this, &Gameboy::KeyRelease);\n\tconnect(_window, &OpenGLWindow::gbTypeSign, this, &Gameboy::gbTypeSlot);\n\tconnect(_window, &OpenGLWindow::gbComPlay, this, &Gameboy::switchPlaySlot);\n\tconnect(_window, &OpenGLWindow::gbComPause, this, &Gameboy::switchPauseSlot);\n\tconnect(_window, &OpenGLWindow::gbComStop, this, &Gameboy::resetPressedSlot);\n\tconnect(_window, &OpenGLWindow::gbSoundSign, this, &Gameboy::soundSlot);\n\n\t_window->show();\n#ifdef DEBUG\n\tgbDbSlot(); \/\/ Open Debug window\n\treset();\n#endif\n}\n\nGameboy::~Gameboy()\n{\n\tthis->_memory->saverom();\n\tdelete this->_windowDebug;\n\tthis->stopThread();\n}\n\nvoid\tGameboy::stopThread()\n{\n\t_stepMode.store(true);\n\t_willRun.store(false);\n\tif (_thread)\n\t{\n\t\t_thread->join();\n\t\tdelete _thread;\n\t\t_thread = nullptr;\n\t}\n}\n\nvoid\tGameboy::gstep()\n{\n\tstep();\n\tif (isBreakpoint(_cpu->_cpuRegister.PC))\n\t\t_stepMode.store(true);\n}\n\nvoid\tGameboy::run()\n{\n\twhile (_willRun.load())\n\t{\n\t\tif (!_stepMode.load())\n\t\t{\n\t\t\tgstep();\n\t\t}\n\t}\n}\n\nvoid\tGameboy::reset(void)\n{\n\tif (_willRun.load())\n\t{\n\t\tstopThread();\n\t}\n\t\n\tif (_romPath.length())\n\t{\n\t\tthis->_memory->reset();\n\t\tthis->_memory->setAudio(_audio);\n\t\tthis->_clock->reset();\n\t\tthis->_audio->reset(_memory->getRomType() == GBC);\n\t\tthis->_cyclesAcc = 0;\n\t\tif (_memory->loadRom(_romPath.c_str(), this->_hardware) == 0)\n\t\t{\n\t\t\thtype\t\thardRom;\n\t\t\thardRom = (this->_hardware == AUTO) ? this->_memory->getRomType() : this->_hardware;\n\t\t\tthis->_cpu->init(hardRom);\n\t\t\tthis->_gpu->init(); \/\/ TODO pour passer hardware au gpu: this->_gpu->init(hardRom)\n\t\t\t_willRun.store(true);\n\t\t\t_thread = new std::thread(&Gameboy::run, this);\n\t\t}\n\t}\n\telse\n\t\tstd::cerr << \"Gameboy: No rom path defined\" << std::endl;\n}\n\nvoid\tGameboy::gbTypeSlot(htype hardware)\n{\n\tthis->_hardware = hardware;\n}\n\nvoid\tGameboy::stepPressedSlot(unsigned int count)\n{\n\t_stepMode.store(true);\n\twhile (count--) {\n\t\tgstep();\n\t\tif (isBreakpoint(_cpu->_cpuRegister.PC))\n\t\t\tbreak ;\n\t}\n}\n\n#include \"registerAddr.hpp\"\nvoid\tGameboy::framePressedSlot()\n{\n\t_stepMode.store(true);\n\tbool\t\t\tcte = true;\n\n\tuint16_t\tstart;\n\tstart = _memory->read_byte(REGISTER_LY);\n\twhile (start == _memory->read_byte(REGISTER_LY) && cte) {\n\t\tgstep();\n\t\tcte = !isBreakpoint(_cpu->_cpuRegister.PC);\n\t}\n\twhile (start != _memory->read_byte(REGISTER_LY) && cte) {\n\t\tgstep();\n\t\tcte = !isBreakpoint(_cpu->_cpuRegister.PC);\n\t}\n}\n\nvoid\tGameboy::resetPressedSlot()\n{\n\t_stepMode.store(true);\n\treset();\n}\n\nvoid\tGameboy::openRomSlot(std::string path)\n{\n\t_romPath = path;\n\treset();\n\t_stepMode.store(false);\n}\n\nvoid\tGameboy::gbDbSlot()\n{\n\t_windowDebug = new DbWindow(&_cpu->_cpuRegister, _memory, &_breakpoints);\n\tconnect(_windowDebug, &DbWindow::stepPressedSign, this, &Gameboy::stepPressedSlot);\n\tconnect(_windowDebug, &DbWindow::framePressedSign, this, &Gameboy::framePressedSlot);\n\tconnect(_windowDebug, &DbWindow::runPressedSign, this, &Gameboy::switchStepModeSlot);\n\tconnect(_windowDebug, &DbWindow::resetPressedSign, this, &Gameboy::resetPressedSlot);\n\tconnect(_windowDebug, &DbWindow::openPressedSign, this, &Gameboy::openRomSlot);\n\n\tconnect(_windowDebug, &DbWindow::bpAddSign, this, &Gameboy::addBreakpointSlot);\n\tconnect(_windowDebug, &DbWindow::bpDelSign, this, &Gameboy::delBreakpointSlot);\n\n\t_windowDebug->show();\n\t_stepMode.store(true);\n}\n\nvoid\tGameboy::switchPlaySlot(void)\n{\n\t_stepMode.store(false);\n}\n\nvoid\tGameboy::switchPauseSlot(void)\n{\n\t_stepMode.store(true);\n}\n\nvoid\tGameboy::soundSlot(bool on)\n{\n\t_audio->enable(on);\n}\n\nvoid\tGameboy::switchStepModeSlot(void)\n{\n\t_stepMode.store(!_stepMode.load());\n}\n\nvoid\tGameboy::addBreakpointSlot(uint16_t addr)\n{\n\tauto it = std::find(_breakpoints.begin(), _breakpoints.end(), addr);\n\n\tif (it == _breakpoints.end())\n\t\t_breakpoints.push_back(addr);\n}\n\nvoid\tGameboy::delBreakpointSlot(uint16_t addr)\n{\n\t_breakpoints.remove(addr);\n}\n\nbool\tGameboy::isBreakpoint(uint16_t addr)\n{\n\tauto it = std::find(_breakpoints.begin(), _breakpoints.end(), addr);\n\n\treturn (it != _breakpoints.end());\n}\n\n\nvoid\tGameboy::KeyPress(int key)\n{\n\tswitch(key)\n\t{\n\t\tcase RIGHT:\n\t\t\t_memory->key[0] &= 0x0e;\n\t\t\tsetLowBit(_memory, REGISTER_INPUT, 0);\n\t\t\tsetHightBit(_memory, REGISTER_IF, 4);\n\t\t\t_cpu->setStop(false);\n\t\t\tbreak;\n\t\tcase A_BUTTON:\n\t\t\t_memory->key[1] &= 0x0e;\n\t\t\tsetLowBit(_memory, REGISTER_INPUT, 0);\n\t\t\tsetHightBit(_memory, REGISTER_IF, 4);\n\t\t\t_cpu->setStop(false);\n\t\t\tbreak;\n\t\tcase LEFT:\n\t\t\t_memory->key[0] &= 0x0D;\n\t\t\tsetLowBit(_memory, REGISTER_INPUT, 1);\n\t\t\tsetHightBit(_memory, REGISTER_IF, 4);\n\t\t\t_cpu->setStop(false);\n\t\t\tbreak;\n\t\tcase B_BUTTON:\n\t\t\t_memory->key[1] &= 0x0D;\n\t\t\tsetLowBit(_memory, REGISTER_INPUT, 1);\n\t\t\tsetHightBit(_memory, REGISTER_IF, 4);\n\t\t\t_cpu->setStop(false);\n\t\t\tbreak;\n\t\tcase UP:\n\t\t\t_memory->key[0] &= 0x0B;\n\t\t\tsetLowBit(_memory, REGISTER_INPUT, 2);\n\t\t\tsetHightBit(_memory, REGISTER_IF, 4);\n\t\t\t_cpu->setStop(false);\n\t\t\tbreak;\n\t\tcase SELECT:\n\t\t\t_memory->key[1] &= 0x0B;\n\t\t\tsetLowBit(_memory, REGISTER_INPUT, 2);\n\t\t\tsetHightBit(_memory, REGISTER_IF, 4);\n\t\t\t_cpu->setStop(false);\n\t\t\tbreak;\n\t\tcase DOWN:\n\t\t\t_memory->key[0] &= 0x07;\n\t\t\tsetLowBit(_memory, REGISTER_INPUT, 3);\n\t\t\tsetHightBit(_memory, REGISTER_IF, 4);\n\t\t\t_cpu->setStop(false);\n\t\t\tbreak;\n\t\tcase START:\n\t\t\t_memory->key[1] &= 0x07;\n\t\t\tsetLowBit(_memory, REGISTER_INPUT, 3);\n\t\t\tsetHightBit(_memory, REGISTER_IF, 4);\n\t\t\t_cpu->setStop(false);\n\t\t\tbreak;\n\t}\n}\n\nvoid\tGameboy::KeyRelease(int key)\n{\n\tswitch(key)\n\t{\n\t\tcase RIGHT:\n\t\t\t_memory->key[0] |= 0x01;\n\t\t\tsetHightBit(_memory, REGISTER_INPUT, 0);\n\t\t\t_cpu->setStop(false);\n\t\t\tbreak;\n\t\tcase A_BUTTON:\n\t\t\t_memory->key[1] |= 0x01;\n\t\t\tsetHightBit(_memory, REGISTER_INPUT, 0);\n\t\t\t_cpu->setStop(false);\n\t\t\tbreak;\n\t\tcase LEFT:\n\t\t\t_memory->key[0] |= 0x02;\n\t\t\tsetHightBit(_memory, REGISTER_INPUT, 1);\n\t\t\t_cpu->setStop(false);\n\t\t\tbreak;\n\t\tcase B_BUTTON:\n\t\t\t_memory->key[1] |= 0x02;\n\t\t\tsetHightBit(_memory, REGISTER_INPUT, 1);\n\t\t\t_cpu->setStop(false);\n\t\t\tbreak;\n\t\tcase UP:\n\t\t\t_memory->key[0] |= 0x04;\n\t\t\tsetHightBit(_memory, REGISTER_INPUT, 2);\n\t\t\t_cpu->setStop(false);\n\t\t\tbreak;\n\t\tcase SELECT:\n\t\t\t_memory->key[1] |= 0x04;\n\t\t\tsetHightBit(_memory, REGISTER_INPUT, 2);\n\t\t\t_cpu->setStop(false);\n\t\t\tbreak;\n\t\tcase DOWN:\n\t\t\t_memory->key[0] |= 0x08;\n\t\t\tsetHightBit(_memory, REGISTER_INPUT, 3);\n\t\t\t_cpu->setStop(false);\n\t\t\tbreak;\n\t\tcase START:\n\t\t\t_memory->key[1] |= 0x08;\n\t\t\tsetHightBit(_memory, REGISTER_INPUT, 3);\n\t\t\t_cpu->setStop(false);\n\t\t\tbreak;\n\t}\n}\n\n<commit_msg>Ajout message WARNING segment fault<commit_after>\n#include \"Gameboy.hpp\"\n\n#include \"OpenGLWindow.hpp\"\n#include \"DbWindow.hpp\"\n#include \"registerAddr.hpp\"\n\n#include \"Cpu.hpp\"\n#include \"Gpu.hpp\"\n#include \"Memory.hpp\"\n#include \"Timer.hpp\"\n#include \"Audio.hpp\"\n\nvoid setLowBit(Memory *memory, uint16_t addr, uint8_t bit)\n{\n\tmemory->write_byte(addr, (uint8_t)((0x01 << bit) ^ memory->read_byte(addr)), true);\n}\n\nvoid setHightBit(Memory *memory, uint16_t addr, uint8_t bit)\n{\n\tmemory->write_byte(addr, (uint8_t)((0x01 << bit) | memory->read_byte(addr)), true);\n}\n\nGameboy::Gameboy(const char *path) :\n\t_window(OpenGLWindow::Instance())\n\t, _windowDebug(nullptr)\n\t, _thread(nullptr)\n\t, _romPath(path)\n{\n\t_stepMode.store(false);\n\t_willRun.store(false);\n\n\tconnect(_window, &OpenGLWindow::openRomSign, this, &Gameboy::openRomSlot);\n\tconnect(_window, &OpenGLWindow::gbDbSign, this, &Gameboy::gbDbSlot);\n\tconnect(_window, &OpenGLWindow::keyPressSign, this, &Gameboy::KeyPress);\n\tconnect(_window, &OpenGLWindow::keyReleaseSign, this, &Gameboy::KeyRelease);\n\tconnect(_window, &OpenGLWindow::gbTypeSign, this, &Gameboy::gbTypeSlot);\n\tconnect(_window, &OpenGLWindow::gbComPlay, this, &Gameboy::switchPlaySlot);\n\tconnect(_window, &OpenGLWindow::gbComPause, this, &Gameboy::switchPauseSlot);\n\tconnect(_window, &OpenGLWindow::gbComStop, this, &Gameboy::resetPressedSlot);\n\tconnect(_window, &OpenGLWindow::gbSoundSign, this, &Gameboy::soundSlot);\n\n\t_window->show();\n#ifdef DEBUG\n\tgbDbSlot(); \/\/ Open Debug window. WARNING: Peux generer SGFAULT random\n\treset();\n#endif\n}\n\nGameboy::~Gameboy()\n{\n\tthis->_memory->saverom();\n\tdelete this->_windowDebug;\n\tthis->stopThread();\n}\n\nvoid\tGameboy::stopThread()\n{\n\t_stepMode.store(true);\n\t_willRun.store(false);\n\tif (_thread)\n\t{\n\t\t_thread->join();\n\t\tdelete _thread;\n\t\t_thread = nullptr;\n\t}\n}\n\nvoid\tGameboy::gstep()\n{\n\tstep();\n\tif (isBreakpoint(_cpu->_cpuRegister.PC))\n\t\t_stepMode.store(true);\n}\n\nvoid\tGameboy::run()\n{\n\twhile (_willRun.load())\n\t{\n\t\tif (!_stepMode.load())\n\t\t{\n\t\t\tgstep();\n\t\t}\n\t}\n}\n\nvoid\tGameboy::reset(void)\n{\n\tif (_willRun.load())\n\t{\n\t\tstopThread();\n\t}\n\t\n\tif (_romPath.length())\n\t{\n\t\tthis->_memory->reset();\n\t\tthis->_memory->setAudio(_audio);\n\t\tthis->_clock->reset();\n\t\tthis->_audio->reset(_memory->getRomType() == GBC);\n\t\tthis->_cyclesAcc = 0;\n\t\tif (_memory->loadRom(_romPath.c_str(), this->_hardware) == 0)\n\t\t{\n\t\t\thtype\t\thardRom;\n\t\t\thardRom = (this->_hardware == AUTO) ? this->_memory->getRomType() : this->_hardware;\n\t\t\tthis->_cpu->init(hardRom);\n\t\t\tthis->_gpu->init(); \/\/ TODO pour passer hardware au gpu: this->_gpu->init(hardRom)\n\t\t\t_willRun.store(true);\n\t\t\t_thread = new std::thread(&Gameboy::run, this);\n\t\t}\n\t}\n\telse\n\t\tstd::cerr << \"Gameboy: No rom path defined\" << std::endl;\n}\n\nvoid\tGameboy::gbTypeSlot(htype hardware)\n{\n\tthis->_hardware = hardware;\n}\n\nvoid\tGameboy::stepPressedSlot(unsigned int count)\n{\n\t_stepMode.store(true);\n\twhile (count--) {\n\t\tgstep();\n\t\tif (isBreakpoint(_cpu->_cpuRegister.PC))\n\t\t\tbreak ;\n\t}\n}\n\n#include \"registerAddr.hpp\"\nvoid\tGameboy::framePressedSlot()\n{\n\t_stepMode.store(true);\n\tbool\t\t\tcte = true;\n\n\tuint16_t\tstart;\n\tstart = _memory->read_byte(REGISTER_LY);\n\twhile (start == _memory->read_byte(REGISTER_LY) && cte) {\n\t\tgstep();\n\t\tcte = !isBreakpoint(_cpu->_cpuRegister.PC);\n\t}\n\twhile (start != _memory->read_byte(REGISTER_LY) && cte) {\n\t\tgstep();\n\t\tcte = !isBreakpoint(_cpu->_cpuRegister.PC);\n\t}\n}\n\nvoid\tGameboy::resetPressedSlot()\n{\n\t_stepMode.store(true);\n\treset();\n}\n\nvoid\tGameboy::openRomSlot(std::string path)\n{\n\t_romPath = path;\n\treset();\n\t_stepMode.store(false);\n}\n\nvoid\tGameboy::gbDbSlot()\n{\n\t_windowDebug = new DbWindow(&_cpu->_cpuRegister, _memory, &_breakpoints);\n\tconnect(_windowDebug, &DbWindow::stepPressedSign, this, &Gameboy::stepPressedSlot);\n\tconnect(_windowDebug, &DbWindow::framePressedSign, this, &Gameboy::framePressedSlot);\n\tconnect(_windowDebug, &DbWindow::runPressedSign, this, &Gameboy::switchStepModeSlot);\n\tconnect(_windowDebug, &DbWindow::resetPressedSign, this, &Gameboy::resetPressedSlot);\n\tconnect(_windowDebug, &DbWindow::openPressedSign, this, &Gameboy::openRomSlot);\n\n\tconnect(_windowDebug, &DbWindow::bpAddSign, this, &Gameboy::addBreakpointSlot);\n\tconnect(_windowDebug, &DbWindow::bpDelSign, this, &Gameboy::delBreakpointSlot);\n\n\t_windowDebug->show();\n\t_stepMode.store(true);\n}\n\nvoid\tGameboy::switchPlaySlot(void)\n{\n\t_stepMode.store(false);\n}\n\nvoid\tGameboy::switchPauseSlot(void)\n{\n\t_stepMode.store(true);\n}\n\nvoid\tGameboy::soundSlot(bool on)\n{\n\t_audio->enable(on);\n}\n\nvoid\tGameboy::switchStepModeSlot(void)\n{\n\t_stepMode.store(!_stepMode.load());\n}\n\nvoid\tGameboy::addBreakpointSlot(uint16_t addr)\n{\n\tauto it = std::find(_breakpoints.begin(), _breakpoints.end(), addr);\n\n\tif (it == _breakpoints.end())\n\t\t_breakpoints.push_back(addr);\n}\n\nvoid\tGameboy::delBreakpointSlot(uint16_t addr)\n{\n\t_breakpoints.remove(addr);\n}\n\nbool\tGameboy::isBreakpoint(uint16_t addr)\n{\n\tauto it = std::find(_breakpoints.begin(), _breakpoints.end(), addr);\n\n\treturn (it != _breakpoints.end());\n}\n\n\nvoid\tGameboy::KeyPress(int key)\n{\n\tswitch(key)\n\t{\n\t\tcase RIGHT:\n\t\t\t_memory->key[0] &= 0x0e;\n\t\t\tsetLowBit(_memory, REGISTER_INPUT, 0);\n\t\t\tsetHightBit(_memory, REGISTER_IF, 4);\n\t\t\t_cpu->setStop(false);\n\t\t\tbreak;\n\t\tcase A_BUTTON:\n\t\t\t_memory->key[1] &= 0x0e;\n\t\t\tsetLowBit(_memory, REGISTER_INPUT, 0);\n\t\t\tsetHightBit(_memory, REGISTER_IF, 4);\n\t\t\t_cpu->setStop(false);\n\t\t\tbreak;\n\t\tcase LEFT:\n\t\t\t_memory->key[0] &= 0x0D;\n\t\t\tsetLowBit(_memory, REGISTER_INPUT, 1);\n\t\t\tsetHightBit(_memory, REGISTER_IF, 4);\n\t\t\t_cpu->setStop(false);\n\t\t\tbreak;\n\t\tcase B_BUTTON:\n\t\t\t_memory->key[1] &= 0x0D;\n\t\t\tsetLowBit(_memory, REGISTER_INPUT, 1);\n\t\t\tsetHightBit(_memory, REGISTER_IF, 4);\n\t\t\t_cpu->setStop(false);\n\t\t\tbreak;\n\t\tcase UP:\n\t\t\t_memory->key[0] &= 0x0B;\n\t\t\tsetLowBit(_memory, REGISTER_INPUT, 2);\n\t\t\tsetHightBit(_memory, REGISTER_IF, 4);\n\t\t\t_cpu->setStop(false);\n\t\t\tbreak;\n\t\tcase SELECT:\n\t\t\t_memory->key[1] &= 0x0B;\n\t\t\tsetLowBit(_memory, REGISTER_INPUT, 2);\n\t\t\tsetHightBit(_memory, REGISTER_IF, 4);\n\t\t\t_cpu->setStop(false);\n\t\t\tbreak;\n\t\tcase DOWN:\n\t\t\t_memory->key[0] &= 0x07;\n\t\t\tsetLowBit(_memory, REGISTER_INPUT, 3);\n\t\t\tsetHightBit(_memory, REGISTER_IF, 4);\n\t\t\t_cpu->setStop(false);\n\t\t\tbreak;\n\t\tcase START:\n\t\t\t_memory->key[1] &= 0x07;\n\t\t\tsetLowBit(_memory, REGISTER_INPUT, 3);\n\t\t\tsetHightBit(_memory, REGISTER_IF, 4);\n\t\t\t_cpu->setStop(false);\n\t\t\tbreak;\n\t}\n}\n\nvoid\tGameboy::KeyRelease(int key)\n{\n\tswitch(key)\n\t{\n\t\tcase RIGHT:\n\t\t\t_memory->key[0] |= 0x01;\n\t\t\tsetHightBit(_memory, REGISTER_INPUT, 0);\n\t\t\t_cpu->setStop(false);\n\t\t\tbreak;\n\t\tcase A_BUTTON:\n\t\t\t_memory->key[1] |= 0x01;\n\t\t\tsetHightBit(_memory, REGISTER_INPUT, 0);\n\t\t\t_cpu->setStop(false);\n\t\t\tbreak;\n\t\tcase LEFT:\n\t\t\t_memory->key[0] |= 0x02;\n\t\t\tsetHightBit(_memory, REGISTER_INPUT, 1);\n\t\t\t_cpu->setStop(false);\n\t\t\tbreak;\n\t\tcase B_BUTTON:\n\t\t\t_memory->key[1] |= 0x02;\n\t\t\tsetHightBit(_memory, REGISTER_INPUT, 1);\n\t\t\t_cpu->setStop(false);\n\t\t\tbreak;\n\t\tcase UP:\n\t\t\t_memory->key[0] |= 0x04;\n\t\t\tsetHightBit(_memory, REGISTER_INPUT, 2);\n\t\t\t_cpu->setStop(false);\n\t\t\tbreak;\n\t\tcase SELECT:\n\t\t\t_memory->key[1] |= 0x04;\n\t\t\tsetHightBit(_memory, REGISTER_INPUT, 2);\n\t\t\t_cpu->setStop(false);\n\t\t\tbreak;\n\t\tcase DOWN:\n\t\t\t_memory->key[0] |= 0x08;\n\t\t\tsetHightBit(_memory, REGISTER_INPUT, 3);\n\t\t\t_cpu->setStop(false);\n\t\t\tbreak;\n\t\tcase START:\n\t\t\t_memory->key[1] |= 0x08;\n\t\t\tsetHightBit(_memory, REGISTER_INPUT, 3);\n\t\t\t_cpu->setStop(false);\n\t\t\tbreak;\n\t}\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2009 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/platform_util.h\"\n\n#include <gtk\/gtk.h>\n\n#include \"app\/gtk_util.h\"\n#include \"base\/file_util.h\"\n#include \"base\/process_util.h\"\n#include \"base\/utf_string_conversions.h\"\n#include \"chrome\/common\/process_watcher.h\"\n#include \"googleurl\/src\/gurl.h\"\n\n#include \"chrome\/browser\/chrome_thread.h\"\n#include \"chrome\/browser\/browser_list.h\"\n#include \"chrome\/browser\/dom_ui\/filebrowse_ui.h\"\n#include \"chrome\/browser\/dom_ui\/mediaplayer_ui.h\"\n\nclass Profile;\n\nnamespace platform_util {\n\n\/\/ TODO(estade): It would be nice to be able to select the file in the file\n\/\/ manager, but that probably requires extending xdg-open. For now just\n\/\/ show the folder.\nvoid ShowItemInFolder(const FilePath& full_path) {\n FilePath dir = full_path.DirName();\n if (!file_util::DirectoryExists(dir))\n return;\n\n Profile* profile;\n profile = BrowserList::GetLastActive()->profile();\n\n FileBrowseUI::OpenPopup(profile,\n dir.value(),\n FileBrowseUI::kPopupWidth,\n FileBrowseUI::kPopupHeight);\n}\n\nvoid OpenItem(const FilePath& full_path) {\n std::string ext = full_path.Extension();\n \/\/ For things supported natively by the browser, we should open it\n \/\/ in a tab.\n if (ext == \".jpg\" ||\n ext == \".jpeg\" ||\n ext == \".png\" ||\n ext == \".gif\" ||\n ext == \".html\" ||\n ext == \".htm\") {\n std::string path;\n path = \"file:\/\/\";\n path += full_path.value();\n if (!ChromeThread::CurrentlyOn(ChromeThread::UI)) {\n bool result = ChromeThread::PostTask(\n ChromeThread::UI, FROM_HERE,\n NewRunnableFunction(&OpenItem, full_path));\n DCHECK(result);\n return;\n }\n Browser* browser = BrowserList::GetLastActive();\n browser->AddTabWithURL(\n GURL(path), GURL(), PageTransition::LINK,\n true, -1, false, NULL);\n return;\n }\n if (ext == \".avi\" ||\n ext == \".mp4\" ||\n ext == \".mp3\" ||\n ext == \".mkv\" ||\n ext == \".ogg\") {\n MediaPlayer* mediaplayer = MediaPlayer::Get();\n std::string url = \"file:\/\/\";\n url += full_path.value();\n GURL gurl(url);\n mediaplayer->EnqueueMediaURL(gurl);\n return;\n }\n}\n\nvoid OpenExternal(const GURL& url) {\n\n}\n\n} \/\/ namespace platform_util\n<commit_msg>Fixing opening files on chromeos.<commit_after>\/\/ Copyright (c) 2009 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/platform_util.h\"\n\n#include <gtk\/gtk.h>\n\n#include \"app\/gtk_util.h\"\n#include \"base\/file_util.h\"\n#include \"base\/process_util.h\"\n#include \"base\/utf_string_conversions.h\"\n#include \"chrome\/common\/process_watcher.h\"\n#include \"googleurl\/src\/gurl.h\"\n\n#include \"chrome\/browser\/chrome_thread.h\"\n#include \"chrome\/browser\/browser_list.h\"\n#include \"chrome\/browser\/dom_ui\/filebrowse_ui.h\"\n#include \"chrome\/browser\/dom_ui\/mediaplayer_ui.h\"\n\nclass Profile;\n\nnamespace platform_util {\n\n\/\/ TODO(estade): It would be nice to be able to select the file in the file\n\/\/ manager, but that probably requires extending xdg-open. For now just\n\/\/ show the folder.\nvoid ShowItemInFolder(const FilePath& full_path) {\n FilePath dir = full_path.DirName();\n if (!file_util::DirectoryExists(dir))\n return;\n\n Profile* profile;\n profile = BrowserList::GetLastActive()->profile();\n\n FileBrowseUI::OpenPopup(profile,\n dir.value(),\n FileBrowseUI::kPopupWidth,\n FileBrowseUI::kPopupHeight);\n}\n\nvoid OpenItem(const FilePath& full_path) {\n std::string ext = full_path.Extension();\n \/\/ For things supported natively by the browser, we should open it\n \/\/ in a tab.\n if (ext == \".jpg\" ||\n ext == \".jpeg\" ||\n ext == \".png\" ||\n ext == \".gif\" ||\n ext == \".html\" ||\n ext == \".htm\") {\n std::string path;\n path = \"file:\/\/\";\n path.append(full_path.value());\n if (!ChromeThread::CurrentlyOn(ChromeThread::UI)) {\n bool result = ChromeThread::PostTask(\n ChromeThread::UI, FROM_HERE,\n NewRunnableFunction(&OpenItem, full_path));\n DCHECK(result);\n return;\n }\n Browser* browser = BrowserList::GetLastActive();\n browser->AddTabWithURL(\n GURL(path), GURL(), PageTransition::LINK, -1, Browser::ADD_SELECTED,\n NULL, std::string());\n return;\n }\n if (ext == \".avi\" ||\n ext == \".mp4\" ||\n ext == \".mp3\" ||\n ext == \".mkv\" ||\n ext == \".ogg\") {\n MediaPlayer* mediaplayer = MediaPlayer::Get();\n std::string url = \"file:\/\/\";\n url += full_path.value();\n GURL gurl(url);\n mediaplayer->EnqueueMediaURL(gurl);\n return;\n }\n}\n\nvoid OpenExternal(const GURL& url) {\n\n}\n\n} \/\/ namespace platform_util\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/views\/first_run_bubble.h\"\n\n#include \"chrome\/app\/locales\/locale_settings.h\"\n#include \"chrome\/browser\/browser.h\"\n#include \"chrome\/browser\/browser_list.h\"\n#include \"chrome\/browser\/browser_window.h\"\n#include \"chrome\/browser\/options_window.h\"\n#include \"chrome\/browser\/template_url_model.h\"\n#include \"chrome\/browser\/views\/standard_layout.h\"\n#include \"chrome\/common\/l10n_util.h\"\n#include \"chrome\/common\/resource_bundle.h\"\n#include \"chrome\/views\/event.h\"\n#include \"chrome\/views\/label.h\"\n#include \"chrome\/views\/native_button.h\"\n#include \"chrome\/views\/window.h\"\n\n#include \"chromium_strings.h\"\n#include \"generated_resources.h\"\n\nnamespace {\n\n\/\/ How much extra padding to put around our content over what\n\/\/ infobubble provides.\nstatic const int kBubblePadding = 4;\n\n\/\/ TODO(cpu): bug 1187517. It is possible that there is no default provider.\n\/\/ we should make sure there is none at first run.\nstd::wstring GetDefaultSearchEngineName() {\n Browser* browser = BrowserList::GetLastActive();\n DCHECK(browser);\n const TemplateURL* const default_provider =\n browser->profile()->GetTemplateURLModel()->GetDefaultSearchProvider();\n DCHECK(default_provider);\n return default_provider->short_name();\n}\n\n} \/\/ namespace\n\n\/\/ Implements the client view inside the first run bubble. It is kind of a\n\/\/ dialog-ish view, but is not a true dialog.\nclass FirstRunBubbleView : public ChromeViews::View,\n public ChromeViews::NativeButton::Listener {\n public:\n explicit FirstRunBubbleView(FirstRunBubble* bubble_window)\n : bubble_window_(bubble_window),\n label1_(NULL),\n label2_(NULL),\n label3_(NULL),\n keep_button_(NULL),\n change_button_(NULL) {\n ChromeFont& font =\n ResourceBundle::GetSharedInstance().GetFont(ResourceBundle::MediumFont);\n\n label1_ = new ChromeViews::Label(l10n_util::GetString(IDS_FR_BUBBLE_TITLE));\n label1_->SetFont(font.DeriveFont(3, ChromeFont::BOLD));\n label1_->SetHorizontalAlignment(ChromeViews::Label::ALIGN_LEFT);\n AddChildView(label1_);\n\n CSize ps;\n GetPreferredSize(&ps);\n\n label2_ =\n new ChromeViews::Label(l10n_util::GetString(IDS_FR_BUBBLE_SUBTEXT));\n label2_->SetMultiLine(true);\n label2_->SetFont(font);\n label2_->SetHorizontalAlignment(ChromeViews::Label::ALIGN_LEFT);\n label2_->SizeToFit(ps.cx - kBubblePadding * 2);\n AddChildView(label2_);\n\n std::wstring question_str\n = l10n_util::GetStringF(IDS_FR_BUBBLE_QUESTION,\n GetDefaultSearchEngineName());\n label3_ = new ChromeViews::Label(question_str);\n label3_->SetMultiLine(true);\n label3_->SetFont(font);\n label3_->SetHorizontalAlignment(ChromeViews::Label::ALIGN_LEFT);\n label3_->SizeToFit(ps.cx - kBubblePadding * 2);\n AddChildView(label3_);\n\n std::wstring keep_str = l10n_util::GetStringF(IDS_FR_BUBBLE_OK,\n GetDefaultSearchEngineName());\n keep_button_ = new ChromeViews::NativeButton(keep_str, true);\n keep_button_->SetListener(this);\n AddChildView(keep_button_);\n\n std::wstring change_str = l10n_util::GetString(IDS_FR_BUBBLE_CHANGE);\n change_button_ = new ChromeViews::NativeButton(change_str);\n change_button_->SetListener(this);\n AddChildView(change_button_);\n }\n\n \/\/ Overridden from ChromeViews::View.\n virtual void DidChangeBounds(const CRect& previous, const CRect& current) {\n Layout();\n }\n\n \/\/ Overridden from NativeButton::Listener.\n virtual void ButtonPressed(ChromeViews::NativeButton* sender) {\n bubble_window_->Close();\n if (change_button_ == sender) {\n Browser* browser = BrowserList::GetLastActive();\n if (browser) {\n ShowOptionsWindow(OPTIONS_PAGE_GENERAL, OPTIONS_GROUP_DEFAULT_SEARCH,\n browser->profile());\n }\n }\n }\n\n \/\/ Overridden from ChromeViews::View.\n virtual void Layout() {\n CSize canvas;\n GetPreferredSize(&canvas);\n\n CSize pref_size;\n \/\/ The multiline business that follows is dirty hacks to get around\n \/\/ bug 1325257.\n label1_->SetMultiLine(false);\n label1_->GetPreferredSize(&pref_size);\n label1_->SetMultiLine(true);\n label1_->SizeToFit(canvas.cx - kBubblePadding * 2);\n label1_->SetBounds(kBubblePadding, kBubblePadding, \n canvas.cx - kBubblePadding * 2,\n pref_size.cy);\n\n int next_v_space = label1_->y() + pref_size.cy +\n kRelatedControlSmallVerticalSpacing;\n\n label2_->GetPreferredSize(&pref_size);\n label2_->SetBounds(kBubblePadding, next_v_space,\n canvas.cx - kBubblePadding * 2,\n pref_size.cy);\n\n next_v_space = label2_->y() + label2_->height() +\n kPanelSubVerticalSpacing;\n\n label3_->GetPreferredSize(&pref_size);\n label3_->SetBounds(kBubblePadding, next_v_space,\n canvas.cx - kBubblePadding * 2,\n pref_size.cy);\n\n change_button_->GetPreferredSize(&pref_size);\n change_button_->SetBounds(canvas.cx - pref_size.cx - kBubblePadding,\n canvas.cy - pref_size.cy - kButtonVEdgeMargin,\n pref_size.cx, pref_size.cy);\n\n keep_button_->GetPreferredSize(&pref_size);\n keep_button_->SetBounds(change_button_->x() - pref_size.cx -\n kRelatedButtonHSpacing, change_button_->y(),\n pref_size.cx, pref_size.cy);\n }\n\n virtual void ViewHierarchyChanged(bool is_add, View* parent, View* child) {\n if (keep_button_)\n keep_button_->RequestFocus();\n }\n\n \/\/ Overridden from ChromeViews::View.\n virtual void GetPreferredSize(CSize *out) {\n DCHECK(out);\n *out = ChromeViews::Window::GetLocalizedContentsSize(\n IDS_FIRSTRUNBUBBLE_DIALOG_WIDTH_CHARS,\n IDS_FIRSTRUNBUBBLE_DIALOG_HEIGHT_LINES).ToSIZE();\n }\n\n private:\n FirstRunBubble* bubble_window_;\n ChromeViews::Label* label1_;\n ChromeViews::Label* label2_;\n ChromeViews::Label* label3_;\n ChromeViews::NativeButton* change_button_;\n ChromeViews::NativeButton* keep_button_;\n DISALLOW_EVIL_CONSTRUCTORS(FirstRunBubbleView);\n};\n\n\/\/ Keep the bubble around for kLingerTime milliseconds, to prevent accidental\n\/\/ closure.\nstatic const int kLingerTime = 1000;\n\nvoid FirstRunBubble::OnActivate(UINT action, BOOL minimized, HWND window) {\n \/\/ We might get re-enabled right before we are closed (sequence is: we get\n \/\/ deactivated, we call close, before we are actually closed we get\n \/\/ reactivated). Don't do the disabling of the parent in such cases.\n if (action == WA_ACTIVE && !has_been_activated_) {\n has_been_activated_ = true;\n\n \/\/ Disable the browser to prevent accidental rapid clicks from closing the\n \/\/ bubble.\n ::EnableWindow(GetParent(), false);\n\n MessageLoop::current()->PostDelayedTask(FROM_HERE,\n enable_window_method_factory_.NewRunnableMethod(\n &FirstRunBubble::EnableParent),\n kLingerTime);\n }\n InfoBubble::OnActivate(action, minimized, window);\n}\n\nvoid FirstRunBubble::InfoBubbleClosing(InfoBubble* info_bubble) {\n \/\/ Make sure our parent window is re-enabled.\n if (!IsWindowEnabled(GetParent()))\n ::EnableWindow(GetParent(), true);\n enable_window_method_factory_.RevokeAll();\n}\n\nFirstRunBubble* FirstRunBubble::Show(HWND parent_hwnd,\n const gfx::Rect& position_relative_to) {\n FirstRunBubble* window = new FirstRunBubble();\n ChromeViews::View* view = new FirstRunBubbleView(window);\n window->SetDelegate(window);\n window->Init(parent_hwnd, position_relative_to, view);\n BrowserWindow* frame = window->GetHostingWindow();\n DCHECK(frame);\n frame->InfoBubbleShowing();\n window->ShowWindow(SW_SHOW);\n return window;\n}\n\nvoid FirstRunBubble::EnableParent() {\n ::EnableWindow(GetParent(), true);\n}\n\n<commit_msg>Fix for a crash in the info bubble at first run - Null deref in GetDefaultSearchEngineName - This is a stopgap fix<commit_after>\/\/ Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/views\/first_run_bubble.h\"\n\n#include \"chrome\/app\/locales\/locale_settings.h\"\n#include \"chrome\/browser\/browser.h\"\n#include \"chrome\/browser\/browser_list.h\"\n#include \"chrome\/browser\/browser_window.h\"\n#include \"chrome\/browser\/options_window.h\"\n#include \"chrome\/browser\/template_url_model.h\"\n#include \"chrome\/browser\/views\/standard_layout.h\"\n#include \"chrome\/common\/l10n_util.h\"\n#include \"chrome\/common\/resource_bundle.h\"\n#include \"chrome\/views\/event.h\"\n#include \"chrome\/views\/label.h\"\n#include \"chrome\/views\/native_button.h\"\n#include \"chrome\/views\/window.h\"\n\n#include \"chromium_strings.h\"\n#include \"generated_resources.h\"\n\nnamespace {\n\n\/\/ How much extra padding to put around our content over what\n\/\/ infobubble provides.\nstatic const int kBubblePadding = 4;\n\nstd::wstring GetDefaultSearchEngineName() {\n Browser* browser = BrowserList::GetLastActive();\n DCHECK(browser);\n const TemplateURL* const default_provider =\n browser->profile()->GetTemplateURLModel()->GetDefaultSearchProvider();\n if (!default_provider) {\n \/\/ TODO(cpu): bug 1187517. It is possible to have no default provider.\n \/\/ returning an empty string is a stopgap measure for the crash\n \/\/ http:\/\/code.google.com\/p\/chromium\/issues\/detail?id=2573\n return std::wstring();\n }\n return default_provider->short_name();\n}\n\n} \/\/ namespace\n\n\/\/ Implements the client view inside the first run bubble. It is kind of a\n\/\/ dialog-ish view, but is not a true dialog.\nclass FirstRunBubbleView : public ChromeViews::View,\n public ChromeViews::NativeButton::Listener {\n public:\n explicit FirstRunBubbleView(FirstRunBubble* bubble_window)\n : bubble_window_(bubble_window),\n label1_(NULL),\n label2_(NULL),\n label3_(NULL),\n keep_button_(NULL),\n change_button_(NULL) {\n ChromeFont& font =\n ResourceBundle::GetSharedInstance().GetFont(ResourceBundle::MediumFont);\n\n label1_ = new ChromeViews::Label(l10n_util::GetString(IDS_FR_BUBBLE_TITLE));\n label1_->SetFont(font.DeriveFont(3, ChromeFont::BOLD));\n label1_->SetHorizontalAlignment(ChromeViews::Label::ALIGN_LEFT);\n AddChildView(label1_);\n\n CSize ps;\n GetPreferredSize(&ps);\n\n label2_ =\n new ChromeViews::Label(l10n_util::GetString(IDS_FR_BUBBLE_SUBTEXT));\n label2_->SetMultiLine(true);\n label2_->SetFont(font);\n label2_->SetHorizontalAlignment(ChromeViews::Label::ALIGN_LEFT);\n label2_->SizeToFit(ps.cx - kBubblePadding * 2);\n AddChildView(label2_);\n\n std::wstring question_str\n = l10n_util::GetStringF(IDS_FR_BUBBLE_QUESTION,\n GetDefaultSearchEngineName());\n label3_ = new ChromeViews::Label(question_str);\n label3_->SetMultiLine(true);\n label3_->SetFont(font);\n label3_->SetHorizontalAlignment(ChromeViews::Label::ALIGN_LEFT);\n label3_->SizeToFit(ps.cx - kBubblePadding * 2);\n AddChildView(label3_);\n\n std::wstring keep_str = l10n_util::GetStringF(IDS_FR_BUBBLE_OK,\n GetDefaultSearchEngineName());\n keep_button_ = new ChromeViews::NativeButton(keep_str, true);\n keep_button_->SetListener(this);\n AddChildView(keep_button_);\n\n std::wstring change_str = l10n_util::GetString(IDS_FR_BUBBLE_CHANGE);\n change_button_ = new ChromeViews::NativeButton(change_str);\n change_button_->SetListener(this);\n AddChildView(change_button_);\n }\n\n \/\/ Overridden from ChromeViews::View.\n virtual void DidChangeBounds(const CRect& previous, const CRect& current) {\n Layout();\n }\n\n \/\/ Overridden from NativeButton::Listener.\n virtual void ButtonPressed(ChromeViews::NativeButton* sender) {\n bubble_window_->Close();\n if (change_button_ == sender) {\n Browser* browser = BrowserList::GetLastActive();\n if (browser) {\n ShowOptionsWindow(OPTIONS_PAGE_GENERAL, OPTIONS_GROUP_DEFAULT_SEARCH,\n browser->profile());\n }\n }\n }\n\n \/\/ Overridden from ChromeViews::View.\n virtual void Layout() {\n CSize canvas;\n GetPreferredSize(&canvas);\n\n CSize pref_size;\n \/\/ The multiline business that follows is dirty hacks to get around\n \/\/ bug 1325257.\n label1_->SetMultiLine(false);\n label1_->GetPreferredSize(&pref_size);\n label1_->SetMultiLine(true);\n label1_->SizeToFit(canvas.cx - kBubblePadding * 2);\n label1_->SetBounds(kBubblePadding, kBubblePadding, \n canvas.cx - kBubblePadding * 2,\n pref_size.cy);\n\n int next_v_space = label1_->y() + pref_size.cy +\n kRelatedControlSmallVerticalSpacing;\n\n label2_->GetPreferredSize(&pref_size);\n label2_->SetBounds(kBubblePadding, next_v_space,\n canvas.cx - kBubblePadding * 2,\n pref_size.cy);\n\n next_v_space = label2_->y() + label2_->height() +\n kPanelSubVerticalSpacing;\n\n label3_->GetPreferredSize(&pref_size);\n label3_->SetBounds(kBubblePadding, next_v_space,\n canvas.cx - kBubblePadding * 2,\n pref_size.cy);\n\n change_button_->GetPreferredSize(&pref_size);\n change_button_->SetBounds(canvas.cx - pref_size.cx - kBubblePadding,\n canvas.cy - pref_size.cy - kButtonVEdgeMargin,\n pref_size.cx, pref_size.cy);\n\n keep_button_->GetPreferredSize(&pref_size);\n keep_button_->SetBounds(change_button_->x() - pref_size.cx -\n kRelatedButtonHSpacing, change_button_->y(),\n pref_size.cx, pref_size.cy);\n }\n\n virtual void ViewHierarchyChanged(bool is_add, View* parent, View* child) {\n if (keep_button_)\n keep_button_->RequestFocus();\n }\n\n \/\/ Overridden from ChromeViews::View.\n virtual void GetPreferredSize(CSize *out) {\n DCHECK(out);\n *out = ChromeViews::Window::GetLocalizedContentsSize(\n IDS_FIRSTRUNBUBBLE_DIALOG_WIDTH_CHARS,\n IDS_FIRSTRUNBUBBLE_DIALOG_HEIGHT_LINES).ToSIZE();\n }\n\n private:\n FirstRunBubble* bubble_window_;\n ChromeViews::Label* label1_;\n ChromeViews::Label* label2_;\n ChromeViews::Label* label3_;\n ChromeViews::NativeButton* change_button_;\n ChromeViews::NativeButton* keep_button_;\n DISALLOW_EVIL_CONSTRUCTORS(FirstRunBubbleView);\n};\n\n\/\/ Keep the bubble around for kLingerTime milliseconds, to prevent accidental\n\/\/ closure.\nstatic const int kLingerTime = 1000;\n\nvoid FirstRunBubble::OnActivate(UINT action, BOOL minimized, HWND window) {\n \/\/ We might get re-enabled right before we are closed (sequence is: we get\n \/\/ deactivated, we call close, before we are actually closed we get\n \/\/ reactivated). Don't do the disabling of the parent in such cases.\n if (action == WA_ACTIVE && !has_been_activated_) {\n has_been_activated_ = true;\n\n \/\/ Disable the browser to prevent accidental rapid clicks from closing the\n \/\/ bubble.\n ::EnableWindow(GetParent(), false);\n\n MessageLoop::current()->PostDelayedTask(FROM_HERE,\n enable_window_method_factory_.NewRunnableMethod(\n &FirstRunBubble::EnableParent),\n kLingerTime);\n }\n InfoBubble::OnActivate(action, minimized, window);\n}\n\nvoid FirstRunBubble::InfoBubbleClosing(InfoBubble* info_bubble) {\n \/\/ Make sure our parent window is re-enabled.\n if (!IsWindowEnabled(GetParent()))\n ::EnableWindow(GetParent(), true);\n enable_window_method_factory_.RevokeAll();\n}\n\nFirstRunBubble* FirstRunBubble::Show(HWND parent_hwnd,\n const gfx::Rect& position_relative_to) {\n FirstRunBubble* window = new FirstRunBubble();\n ChromeViews::View* view = new FirstRunBubbleView(window);\n window->SetDelegate(window);\n window->Init(parent_hwnd, position_relative_to, view);\n BrowserWindow* frame = window->GetHostingWindow();\n DCHECK(frame);\n frame->InfoBubbleShowing();\n window->ShowWindow(SW_SHOW);\n return window;\n}\n\nvoid FirstRunBubble::EnableParent() {\n ::EnableWindow(GetParent(), true);\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright 2013 Google Inc.\n *\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n *\/\n\n#include \"gm.h\"\n#include \"SkCanvas.h\"\n#include \"SkPath.h\"\n\n\/\/ Reproduces https:\/\/code.google.com\/p\/chromium\/issues\/detail?id=279014\n\nstatic const SkScalar kWidth = SkIntToScalar(640);\nstatic const SkScalar kHeight = SkIntToScalar(480);\nstatic const SkScalar kAngle = 0.305f;\n\n\/\/ Renders a string art shape.\n\/\/ The particular shape rendered can be controlled by adjusting kAngle, from 0 to 1\n\nclass StringArtGM : public skiagm::GM {\npublic:\n StringArtGM() {}\n\nprotected:\n virtual SkString onShortName() {\n return SkString(\"stringart\");\n }\n\n virtual SkISize onISize() {\n return SkISize::Make(kWidth, kHeight);\n }\n\n virtual void onDraw(SkCanvas* canvas) {\n SkScalar angle = kAngle*SK_ScalarPI + SkScalarHalf(SK_ScalarPI);\n SkScalar size = SkMinScalar(kWidth, kHeight);\n SkPoint center = SkPoint::Make(SkScalarHalf(kWidth), SkScalarHalf(kHeight));\n SkScalar length = 5;\n SkScalar step = angle;\n\n SkPath path;\n path.moveTo(center);\n\n while (length < (SkScalarHalf(size) - 10.f))\n {\n SkPoint rp = SkPoint::Make(length*SkScalarCos(step) + center.fX,\n length*SkScalarSin(step) + center.fY);\n path.lineTo(rp);\n length += SkScalarDiv(angle, SkScalarHalf(SK_ScalarPI));\n step += angle;\n }\n path.close();\n\n SkPaint paint;\n paint.setAntiAlias(true);\n paint.setStyle(SkPaint::kStroke_Style);\n paint.setColor(0xFF007700);\n\n canvas->drawPath(path, paint);\n }\n\nprivate:\n typedef GM INHERITED;\n};\n\nDEF_GM( return new StringArtGM; )\n<commit_msg>One more try at fixing warnings<commit_after>\/*\n * Copyright 2013 Google Inc.\n *\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n *\/\n\n#include \"gm.h\"\n#include \"SkCanvas.h\"\n#include \"SkPath.h\"\n\n\/\/ Reproduces https:\/\/code.google.com\/p\/chromium\/issues\/detail?id=279014\n\nstatic const int kWidth = 640;\nstatic const int kHeight = 480;\nstatic const SkScalar kAngle = 0.305f;\n\n\/\/ Renders a string art shape.\n\/\/ The particular shape rendered can be controlled by adjusting kAngle, from 0 to 1\n\nclass StringArtGM : public skiagm::GM {\npublic:\n StringArtGM() {}\n\nprotected:\n virtual SkString onShortName() {\n return SkString(\"stringart\");\n }\n\n virtual SkISize onISize() {\n return SkISize::Make(kWidth, kHeight);\n }\n\n virtual void onDraw(SkCanvas* canvas) {\n SkScalar angle = kAngle*SK_ScalarPI + SkScalarHalf(SK_ScalarPI);\n SkScalar size = SkIntToScalar(SkMin32(kWidth, kHeight));\n SkPoint center = SkPoint::Make(SkScalarHalf(kWidth), SkScalarHalf(kHeight));\n SkScalar length = 5;\n SkScalar step = angle;\n\n SkPath path;\n path.moveTo(center);\n\n while (length < (SkScalarHalf(size) - 10.f))\n {\n SkPoint rp = SkPoint::Make(length*SkScalarCos(step) + center.fX,\n length*SkScalarSin(step) + center.fY);\n path.lineTo(rp);\n length += SkScalarDiv(angle, SkScalarHalf(SK_ScalarPI));\n step += angle;\n }\n path.close();\n\n SkPaint paint;\n paint.setAntiAlias(true);\n paint.setStyle(SkPaint::kStroke_Style);\n paint.setColor(0xFF007700);\n\n canvas->drawPath(path, paint);\n }\n\nprivate:\n typedef GM INHERITED;\n};\n\nDEF_GM( return new StringArtGM; )\n<|endoftext|>"} {"text":"<commit_before>\n\/*\n * Copyright 2012 Google Inc.\n *\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n *\/\n#include \"gm.h\"\n\n#include \"SkColorPriv.h\"\n#include \"SkGeometry.h\"\n#include \"SkShader.h\"\n\nstatic void tesselate(const SkPath& src, SkPath* dst) {\n SkPath::Iter iter(src, true);\n SkPoint pts[4];\n SkPath::Verb verb;\n while ((verb = iter.next(pts)) != SkPath::kDone_Verb) {\n switch (verb) {\n case SkPath::kMove_Verb:\n dst->moveTo(pts[0]);\n break;\n case SkPath::kLine_Verb:\n dst->lineTo(pts[1]);\n break;\n case SkPath::kQuad_Verb: {\n SkPoint p;\n for (int i = 1; i <= 8; ++i) {\n SkEvalQuadAt(pts, i \/ 8.0f, &p, NULL);\n dst->lineTo(p);\n }\n } break;\n case SkPath::kCubic_Verb: {\n SkPoint p;\n for (int i = 1; i <= 8; ++i) {\n SkEvalCubicAt(pts, i \/ 8.0f, &p, NULL, NULL);\n dst->lineTo(p);\n }\n } break;\n }\n }\n}\n\nstatic void setFade(SkPaint* paint, bool showGL) {\n paint->setAlpha(showGL ? 0x66 : 0xFF);\n}\n\nstatic void setGLFrame(SkPaint* paint) {\n paint->setColor(0xFFFF0000);\n paint->setStyle(SkPaint::kStroke_Style);\n paint->setAntiAlias(true);\n paint->setStrokeWidth(1.1f);\n}\n\nstatic void show_mesh(SkCanvas* canvas, const SkRect& r) {\n SkPaint paint;\n setGLFrame(&paint);\n \n canvas->drawRect(r, paint);\n canvas->drawLine(r.fLeft, r.fTop, r.fRight, r.fBottom, paint);\n}\n\nstatic void drawLine(SkCanvas* canvas, const SkPoint& p0, const SkPoint& p1,\n const SkPaint& paint) {\n canvas->drawLine(p0.fX, p0.fY, p1.fX, p1.fY, paint);\n}\n\nstatic void show_mesh(SkCanvas* canvas, const SkPoint pts[],\n const uint16_t indices[], int count) {\n SkPaint paint;\n setGLFrame(&paint);\n\n for (int i = 0; i < count - 2; ++i) {\n drawLine(canvas, pts[indices[i]], pts[indices[i+1]], paint);\n drawLine(canvas, pts[indices[i+1]], pts[indices[i+2]], paint);\n drawLine(canvas, pts[indices[i+2]], pts[indices[i]], paint);\n }\n}\n\nstatic void show_glframe(SkCanvas* canvas, const SkPath& path) {\n SkPaint paint;\n setGLFrame(&paint);\n canvas->drawPath(path, paint);\n}\n\nstatic void show_mesh_between(SkCanvas* canvas, const SkPath& p0, const SkPath& p1) {\n SkPath d0, d1;\n tesselate(p0, &d0);\n tesselate(p1, &d1);\n \n SkPoint pts0[256*2], pts1[256];\n int count = d0.getPoints(pts0, SK_ARRAY_COUNT(pts0));\n int count1 = d1.getPoints(pts1, SK_ARRAY_COUNT(pts1));\n SkASSERT(count == count1);\n memcpy(&pts0[count], pts1, count * sizeof(SkPoint));\n \n uint16_t indices[256*6];\n uint16_t* ndx = indices;\n for (int i = 0; i < count; ++i) {\n *ndx++ = i;\n *ndx++ = i + count;\n }\n *ndx++ = 0;\n\n show_mesh(canvas, pts0, indices, ndx - indices);\n}\n\nstatic void show_fan(SkCanvas* canvas, const SkPath& path, SkScalar cx, SkScalar cy) {\n SkPaint paint;\n setGLFrame(&paint);\n\n canvas->drawPath(path, paint);\n\n SkPoint pts[256];\n int count = path.getPoints(pts, SK_ARRAY_COUNT(pts));\n for (int i = 0; i < count; ++i) {\n canvas->drawLine(pts[i].fX, pts[i].fY, cx, cy, paint);\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\ntypedef void (*DrawProc)(SkCanvas* canvas, bool showGL, int flags);\n\nstatic void draw_line(SkCanvas* canvas, bool showGL, int flags) {\n SkPaint paint;\n paint.setAntiAlias(true);\n \n canvas->drawLine(50, 50, 400, 100, paint);\n \n canvas->rotate(40);\n setFade(&paint, showGL);\n paint.setStrokeWidth(40);\n canvas->drawLine(100, 50, 450, 50, paint);\n if (showGL) {\n show_mesh(canvas, SkRect::MakeLTRB(100, 50-20, 450, 50+20));\n }\n}\n\nstatic void draw_rect(SkCanvas* canvas, bool showGL, int flags) {\n SkPaint paint;\n paint.setAntiAlias(true);\n\n SkRect r = SkRect::MakeLTRB(50, 70, 250, 370);\n\n setFade(&paint, showGL);\n canvas->drawRect(r, paint);\n if (showGL) {\n show_mesh(canvas, r);\n }\n\n canvas->translate(320, 0);\n\n paint.setStyle(SkPaint::kStroke_Style);\n paint.setStrokeWidth(25);\n canvas->drawRect(r, paint);\n if (showGL) {\n SkScalar rad = paint.getStrokeWidth() \/ 2;\n SkPoint pts[8];\n r.outset(rad, rad);\n r.toQuad(&pts[0]);\n r.inset(rad*2, rad*2);\n r.toQuad(&pts[4]);\n \n const uint16_t indices[] = {\n 0, 4, 1, 5, 2, 6, 3, 7, 0, 4\n };\n show_mesh(canvas, pts, indices, SK_ARRAY_COUNT(indices));\n }\n}\n\nstatic void draw_oval(SkCanvas* canvas, bool showGL, int flags) {\n SkPaint paint;\n paint.setAntiAlias(true);\n \n SkRect r = SkRect::MakeLTRB(50, 70, 250, 370);\n \n setFade(&paint, showGL);\n canvas->drawOval(r, paint);\n if (showGL) {\n switch (flags) {\n case 0: {\n SkPath path;\n path.addOval(r);\n show_glframe(canvas, path);\n } break;\n case 1:\n case 2: {\n SkPath src, dst;\n src.addOval(r);\n tesselate(src, &dst);\n show_fan(canvas, dst, r.centerX(), r.centerY());\n } break;\n }\n }\n \n canvas->translate(320, 0);\n \n paint.setStyle(SkPaint::kStroke_Style);\n paint.setStrokeWidth(25);\n canvas->drawOval(r, paint);\n if (showGL) {\n switch (flags) {\n case 0: {\n SkPath path;\n SkScalar rad = paint.getStrokeWidth() \/ 2;\n r.outset(rad, rad);\n path.addOval(r);\n r.inset(rad*2, rad*2);\n path.addOval(r);\n show_glframe(canvas, path);\n } break;\n case 1: {\n SkPath path0, path1;\n SkScalar rad = paint.getStrokeWidth() \/ 2;\n r.outset(rad, rad);\n path0.addOval(r);\n r.inset(rad*2, rad*2);\n path1.addOval(r);\n show_mesh_between(canvas, path0, path1);\n } break;\n case 2: {\n SkScalar rad = paint.getStrokeWidth() \/ 2;\n r.outset(rad, rad);\n SkPaint paint;\n paint.setAlpha(0x33);\n canvas->drawRect(r, paint);\n show_mesh(canvas, r);\n } break;\n }\n }\n}\n\n#include \"SkImageDecoder.h\"\nstatic void draw_image(SkCanvas* canvas, bool showGL, int flags) {\n SkPaint paint;\n paint.setAntiAlias(true);\n paint.setFilterBitmap(true);\n setFade(&paint, showGL);\n\n SkBitmap bm;\n SkImageDecoder::DecodeFile(\"\/skimages\/startrek.png\", &bm);\n SkRect r = SkRect::MakeWH(bm.width(), bm.height());\n\n canvas->save();\n canvas->translate(30, 30);\n canvas->scale(0.8f, 0.8f);\n canvas->drawBitmap(bm, 0, 0, &paint);\n if (showGL) {\n show_mesh(canvas, r);\n }\n canvas->restore();\n\n canvas->translate(210, 290);\n canvas->rotate(-35);\n canvas->drawBitmap(bm, 0, 0, &paint);\n if (showGL) {\n show_mesh(canvas, r);\n }\n}\n\nstatic void draw_text(SkCanvas* canvas, bool showGL, int flags) {\n SkPaint paint;\n paint.setAntiAlias(true);\n const char text[] = \"Graphics at Google\";\n size_t len = strlen(text);\n setFade(&paint, showGL);\n\n canvas->translate(40, 50);\n for (int i = 0; i < 10; ++i) {\n paint.setTextSize(12 + i * 3);\n canvas->drawText(text, len, 0, 0, paint);\n if (showGL) {\n SkRect bounds[256];\n SkScalar widths[256];\n int count = paint.getTextWidths(text, len, widths, bounds);\n SkScalar adv = 0;\n for (int j = 0; j < count; ++j) {\n bounds[j].offset(adv, 0);\n show_mesh(canvas, bounds[j]);\n adv += widths[j];\n }\n }\n canvas->translate(0, paint.getTextSize() * 3 \/ 2);\n }\n}\n\nstatic const struct {\n DrawProc fProc;\n const char* fName;\n} gRec[] = {\n { draw_line, \"Lines\" },\n { draw_rect, \"Rects\" },\n { draw_oval, \"Ovals\" },\n { draw_image, \"Images\" },\n { draw_text, \"Text\" },\n};\n\nclass TalkGM : public skiagm::GM {\n DrawProc fProc;\n SkString fName;\n bool fShowGL;\n int fFlags;\n\npublic:\n TalkGM(int index, bool showGL, int flags = 0) {\n fProc = gRec[index].fProc;\n fName.set(gRec[index].fName);\n if (showGL) {\n fName.append(\"-gl\");\n }\n fShowGL = showGL;\n fFlags = flags;\n }\n\nprotected:\n virtual SkString onShortName() {\n return fName;\n }\n\n virtual SkISize onISize() {\n return SkISize::Make(640, 480);\n }\n\n virtual void onDraw(SkCanvas* canvas) {\n SkRect dst = SkRect::MakeWH(canvas->getDevice()->width(), canvas->getDevice()->height());\n SkRect src = SkRect::MakeWH(640, 480);\n SkMatrix matrix;\n matrix.setRectToRect(src, dst, SkMatrix::kCenter_ScaleToFit);\n \n canvas->concat(matrix);\n fProc(canvas, fShowGL, fFlags);\n }\n\nprivate:\n typedef skiagm::GM INHERITED;\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#define GM_CONCAT(X,Y) GM_CONCAT_IMPL(X,Y)\n#define GM_CONCAT_IMPL(X,Y) X##Y\n\n#define FACTORY_NAME GM_CONCAT(Factory, __LINE__)\n#define REGISTRY_NAME GM_CONCAT(gReg, __LINE__)\n\n#define ADD_GM(Class, args) \\\n static skiagm::GM* FACTORY_NAME(void*) { return new Class args; } \\\n static skiagm::GMRegistry REGISTRY_NAME(FACTORY_NAME);\n\nADD_GM(TalkGM, (0, false))\nADD_GM(TalkGM, (0, true))\nADD_GM(TalkGM, (1, false))\nADD_GM(TalkGM, (1, true))\nADD_GM(TalkGM, (2, false))\nADD_GM(TalkGM, (2, true))\nADD_GM(TalkGM, (2, true, 1))\nADD_GM(TalkGM, (2, true, 2))\nADD_GM(TalkGM, (3, false))\nADD_GM(TalkGM, (3, true))\nADD_GM(TalkGM, (4, false))\nADD_GM(TalkGM, (4, true))\n \n\/\/static GM* MyFactory(void*) { return new TalkGM(0, false); }\n\/\/static GMRegistry reg(MyFactory);\n\n\n<commit_msg>Sanitizing source files in Skia_Periodic_House_Keeping<commit_after>\n\/*\n * Copyright 2012 Google Inc.\n *\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n *\/\n#include \"gm.h\"\n\n#include \"SkColorPriv.h\"\n#include \"SkGeometry.h\"\n#include \"SkShader.h\"\n\nstatic void tesselate(const SkPath& src, SkPath* dst) {\n SkPath::Iter iter(src, true);\n SkPoint pts[4];\n SkPath::Verb verb;\n while ((verb = iter.next(pts)) != SkPath::kDone_Verb) {\n switch (verb) {\n case SkPath::kMove_Verb:\n dst->moveTo(pts[0]);\n break;\n case SkPath::kLine_Verb:\n dst->lineTo(pts[1]);\n break;\n case SkPath::kQuad_Verb: {\n SkPoint p;\n for (int i = 1; i <= 8; ++i) {\n SkEvalQuadAt(pts, i \/ 8.0f, &p, NULL);\n dst->lineTo(p);\n }\n } break;\n case SkPath::kCubic_Verb: {\n SkPoint p;\n for (int i = 1; i <= 8; ++i) {\n SkEvalCubicAt(pts, i \/ 8.0f, &p, NULL, NULL);\n dst->lineTo(p);\n }\n } break;\n }\n }\n}\n\nstatic void setFade(SkPaint* paint, bool showGL) {\n paint->setAlpha(showGL ? 0x66 : 0xFF);\n}\n\nstatic void setGLFrame(SkPaint* paint) {\n paint->setColor(0xFFFF0000);\n paint->setStyle(SkPaint::kStroke_Style);\n paint->setAntiAlias(true);\n paint->setStrokeWidth(1.1f);\n}\n\nstatic void show_mesh(SkCanvas* canvas, const SkRect& r) {\n SkPaint paint;\n setGLFrame(&paint);\n\n canvas->drawRect(r, paint);\n canvas->drawLine(r.fLeft, r.fTop, r.fRight, r.fBottom, paint);\n}\n\nstatic void drawLine(SkCanvas* canvas, const SkPoint& p0, const SkPoint& p1,\n const SkPaint& paint) {\n canvas->drawLine(p0.fX, p0.fY, p1.fX, p1.fY, paint);\n}\n\nstatic void show_mesh(SkCanvas* canvas, const SkPoint pts[],\n const uint16_t indices[], int count) {\n SkPaint paint;\n setGLFrame(&paint);\n\n for (int i = 0; i < count - 2; ++i) {\n drawLine(canvas, pts[indices[i]], pts[indices[i+1]], paint);\n drawLine(canvas, pts[indices[i+1]], pts[indices[i+2]], paint);\n drawLine(canvas, pts[indices[i+2]], pts[indices[i]], paint);\n }\n}\n\nstatic void show_glframe(SkCanvas* canvas, const SkPath& path) {\n SkPaint paint;\n setGLFrame(&paint);\n canvas->drawPath(path, paint);\n}\n\nstatic void show_mesh_between(SkCanvas* canvas, const SkPath& p0, const SkPath& p1) {\n SkPath d0, d1;\n tesselate(p0, &d0);\n tesselate(p1, &d1);\n\n SkPoint pts0[256*2], pts1[256];\n int count = d0.getPoints(pts0, SK_ARRAY_COUNT(pts0));\n int count1 = d1.getPoints(pts1, SK_ARRAY_COUNT(pts1));\n SkASSERT(count == count1);\n memcpy(&pts0[count], pts1, count * sizeof(SkPoint));\n\n uint16_t indices[256*6];\n uint16_t* ndx = indices;\n for (int i = 0; i < count; ++i) {\n *ndx++ = i;\n *ndx++ = i + count;\n }\n *ndx++ = 0;\n\n show_mesh(canvas, pts0, indices, ndx - indices);\n}\n\nstatic void show_fan(SkCanvas* canvas, const SkPath& path, SkScalar cx, SkScalar cy) {\n SkPaint paint;\n setGLFrame(&paint);\n\n canvas->drawPath(path, paint);\n\n SkPoint pts[256];\n int count = path.getPoints(pts, SK_ARRAY_COUNT(pts));\n for (int i = 0; i < count; ++i) {\n canvas->drawLine(pts[i].fX, pts[i].fY, cx, cy, paint);\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\ntypedef void (*DrawProc)(SkCanvas* canvas, bool showGL, int flags);\n\nstatic void draw_line(SkCanvas* canvas, bool showGL, int flags) {\n SkPaint paint;\n paint.setAntiAlias(true);\n\n canvas->drawLine(50, 50, 400, 100, paint);\n\n canvas->rotate(40);\n setFade(&paint, showGL);\n paint.setStrokeWidth(40);\n canvas->drawLine(100, 50, 450, 50, paint);\n if (showGL) {\n show_mesh(canvas, SkRect::MakeLTRB(100, 50-20, 450, 50+20));\n }\n}\n\nstatic void draw_rect(SkCanvas* canvas, bool showGL, int flags) {\n SkPaint paint;\n paint.setAntiAlias(true);\n\n SkRect r = SkRect::MakeLTRB(50, 70, 250, 370);\n\n setFade(&paint, showGL);\n canvas->drawRect(r, paint);\n if (showGL) {\n show_mesh(canvas, r);\n }\n\n canvas->translate(320, 0);\n\n paint.setStyle(SkPaint::kStroke_Style);\n paint.setStrokeWidth(25);\n canvas->drawRect(r, paint);\n if (showGL) {\n SkScalar rad = paint.getStrokeWidth() \/ 2;\n SkPoint pts[8];\n r.outset(rad, rad);\n r.toQuad(&pts[0]);\n r.inset(rad*2, rad*2);\n r.toQuad(&pts[4]);\n\n const uint16_t indices[] = {\n 0, 4, 1, 5, 2, 6, 3, 7, 0, 4\n };\n show_mesh(canvas, pts, indices, SK_ARRAY_COUNT(indices));\n }\n}\n\nstatic void draw_oval(SkCanvas* canvas, bool showGL, int flags) {\n SkPaint paint;\n paint.setAntiAlias(true);\n\n SkRect r = SkRect::MakeLTRB(50, 70, 250, 370);\n\n setFade(&paint, showGL);\n canvas->drawOval(r, paint);\n if (showGL) {\n switch (flags) {\n case 0: {\n SkPath path;\n path.addOval(r);\n show_glframe(canvas, path);\n } break;\n case 1:\n case 2: {\n SkPath src, dst;\n src.addOval(r);\n tesselate(src, &dst);\n show_fan(canvas, dst, r.centerX(), r.centerY());\n } break;\n }\n }\n\n canvas->translate(320, 0);\n\n paint.setStyle(SkPaint::kStroke_Style);\n paint.setStrokeWidth(25);\n canvas->drawOval(r, paint);\n if (showGL) {\n switch (flags) {\n case 0: {\n SkPath path;\n SkScalar rad = paint.getStrokeWidth() \/ 2;\n r.outset(rad, rad);\n path.addOval(r);\n r.inset(rad*2, rad*2);\n path.addOval(r);\n show_glframe(canvas, path);\n } break;\n case 1: {\n SkPath path0, path1;\n SkScalar rad = paint.getStrokeWidth() \/ 2;\n r.outset(rad, rad);\n path0.addOval(r);\n r.inset(rad*2, rad*2);\n path1.addOval(r);\n show_mesh_between(canvas, path0, path1);\n } break;\n case 2: {\n SkScalar rad = paint.getStrokeWidth() \/ 2;\n r.outset(rad, rad);\n SkPaint paint;\n paint.setAlpha(0x33);\n canvas->drawRect(r, paint);\n show_mesh(canvas, r);\n } break;\n }\n }\n}\n\n#include \"SkImageDecoder.h\"\nstatic void draw_image(SkCanvas* canvas, bool showGL, int flags) {\n SkPaint paint;\n paint.setAntiAlias(true);\n paint.setFilterBitmap(true);\n setFade(&paint, showGL);\n\n SkBitmap bm;\n SkImageDecoder::DecodeFile(\"\/skimages\/startrek.png\", &bm);\n SkRect r = SkRect::MakeWH(bm.width(), bm.height());\n\n canvas->save();\n canvas->translate(30, 30);\n canvas->scale(0.8f, 0.8f);\n canvas->drawBitmap(bm, 0, 0, &paint);\n if (showGL) {\n show_mesh(canvas, r);\n }\n canvas->restore();\n\n canvas->translate(210, 290);\n canvas->rotate(-35);\n canvas->drawBitmap(bm, 0, 0, &paint);\n if (showGL) {\n show_mesh(canvas, r);\n }\n}\n\nstatic void draw_text(SkCanvas* canvas, bool showGL, int flags) {\n SkPaint paint;\n paint.setAntiAlias(true);\n const char text[] = \"Graphics at Google\";\n size_t len = strlen(text);\n setFade(&paint, showGL);\n\n canvas->translate(40, 50);\n for (int i = 0; i < 10; ++i) {\n paint.setTextSize(12 + i * 3);\n canvas->drawText(text, len, 0, 0, paint);\n if (showGL) {\n SkRect bounds[256];\n SkScalar widths[256];\n int count = paint.getTextWidths(text, len, widths, bounds);\n SkScalar adv = 0;\n for (int j = 0; j < count; ++j) {\n bounds[j].offset(adv, 0);\n show_mesh(canvas, bounds[j]);\n adv += widths[j];\n }\n }\n canvas->translate(0, paint.getTextSize() * 3 \/ 2);\n }\n}\n\nstatic const struct {\n DrawProc fProc;\n const char* fName;\n} gRec[] = {\n { draw_line, \"Lines\" },\n { draw_rect, \"Rects\" },\n { draw_oval, \"Ovals\" },\n { draw_image, \"Images\" },\n { draw_text, \"Text\" },\n};\n\nclass TalkGM : public skiagm::GM {\n DrawProc fProc;\n SkString fName;\n bool fShowGL;\n int fFlags;\n\npublic:\n TalkGM(int index, bool showGL, int flags = 0) {\n fProc = gRec[index].fProc;\n fName.set(gRec[index].fName);\n if (showGL) {\n fName.append(\"-gl\");\n }\n fShowGL = showGL;\n fFlags = flags;\n }\n\nprotected:\n virtual SkString onShortName() {\n return fName;\n }\n\n virtual SkISize onISize() {\n return SkISize::Make(640, 480);\n }\n\n virtual void onDraw(SkCanvas* canvas) {\n SkRect dst = SkRect::MakeWH(canvas->getDevice()->width(), canvas->getDevice()->height());\n SkRect src = SkRect::MakeWH(640, 480);\n SkMatrix matrix;\n matrix.setRectToRect(src, dst, SkMatrix::kCenter_ScaleToFit);\n\n canvas->concat(matrix);\n fProc(canvas, fShowGL, fFlags);\n }\n\nprivate:\n typedef skiagm::GM INHERITED;\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#define GM_CONCAT(X,Y) GM_CONCAT_IMPL(X,Y)\n#define GM_CONCAT_IMPL(X,Y) X##Y\n\n#define FACTORY_NAME GM_CONCAT(Factory, __LINE__)\n#define REGISTRY_NAME GM_CONCAT(gReg, __LINE__)\n\n#define ADD_GM(Class, args) \\\n static skiagm::GM* FACTORY_NAME(void*) { return new Class args; } \\\n static skiagm::GMRegistry REGISTRY_NAME(FACTORY_NAME);\n\nADD_GM(TalkGM, (0, false))\nADD_GM(TalkGM, (0, true))\nADD_GM(TalkGM, (1, false))\nADD_GM(TalkGM, (1, true))\nADD_GM(TalkGM, (2, false))\nADD_GM(TalkGM, (2, true))\nADD_GM(TalkGM, (2, true, 1))\nADD_GM(TalkGM, (2, true, 2))\nADD_GM(TalkGM, (3, false))\nADD_GM(TalkGM, (3, true))\nADD_GM(TalkGM, (4, false))\nADD_GM(TalkGM, (4, true))\n\n\/\/static GM* MyFactory(void*) { return new TalkGM(0, false); }\n\/\/static GMRegistry reg(MyFactory);\n\n\n<|endoftext|>"} {"text":"<commit_before>\n\/*\n * Copyright 2012 Google Inc.\n *\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n *\/\n#include \"gm.h\"\n\n#include \"SkColorPriv.h\"\n#include \"SkGeometry.h\"\n#include \"SkShader.h\"\n\nstatic void tesselate(const SkPath& src, SkPath* dst) {\n SkPath::Iter iter(src, true);\n SkPoint pts[4];\n SkPath::Verb verb;\n while ((verb = iter.next(pts)) != SkPath::kDone_Verb) {\n switch (verb) {\n case SkPath::kMove_Verb:\n dst->moveTo(pts[0]);\n break;\n case SkPath::kLine_Verb:\n dst->lineTo(pts[1]);\n break;\n case SkPath::kQuad_Verb: {\n SkPoint p;\n for (int i = 1; i <= 8; ++i) {\n SkEvalQuadAt(pts, i \/ 8.0f, &p, NULL);\n dst->lineTo(p);\n }\n } break;\n case SkPath::kCubic_Verb: {\n SkPoint p;\n for (int i = 1; i <= 8; ++i) {\n SkEvalCubicAt(pts, i \/ 8.0f, &p, NULL, NULL);\n dst->lineTo(p);\n }\n } break;\n }\n }\n}\n\nstatic void setFade(SkPaint* paint, bool showGL) {\n paint->setAlpha(showGL ? 0x66 : 0xFF);\n}\n\nstatic void setGLFrame(SkPaint* paint) {\n paint->setColor(0xFFFF0000);\n paint->setStyle(SkPaint::kStroke_Style);\n paint->setAntiAlias(true);\n paint->setStrokeWidth(1.1f);\n}\n\nstatic void show_mesh(SkCanvas* canvas, const SkRect& r) {\n SkPaint paint;\n setGLFrame(&paint);\n\n canvas->drawRect(r, paint);\n canvas->drawLine(r.fLeft, r.fTop, r.fRight, r.fBottom, paint);\n}\n\nstatic void drawLine(SkCanvas* canvas, const SkPoint& p0, const SkPoint& p1,\n const SkPaint& paint) {\n canvas->drawLine(p0.fX, p0.fY, p1.fX, p1.fY, paint);\n}\n\nstatic void show_mesh(SkCanvas* canvas, const SkPoint pts[],\n const uint16_t indices[], int count) {\n SkPaint paint;\n setGLFrame(&paint);\n\n for (int i = 0; i < count - 2; ++i) {\n drawLine(canvas, pts[indices[i]], pts[indices[i+1]], paint);\n drawLine(canvas, pts[indices[i+1]], pts[indices[i+2]], paint);\n drawLine(canvas, pts[indices[i+2]], pts[indices[i]], paint);\n }\n}\n\nstatic void show_glframe(SkCanvas* canvas, const SkPath& path) {\n SkPaint paint;\n setGLFrame(&paint);\n canvas->drawPath(path, paint);\n}\n\nstatic void show_mesh_between(SkCanvas* canvas, const SkPath& p0, const SkPath& p1) {\n SkPath d0, d1;\n tesselate(p0, &d0);\n tesselate(p1, &d1);\n\n SkPoint pts0[256*2], pts1[256];\n int count = d0.getPoints(pts0, SK_ARRAY_COUNT(pts0));\n int count1 = d1.getPoints(pts1, SK_ARRAY_COUNT(pts1));\n SkASSERT(count == count1);\n memcpy(&pts0[count], pts1, count * sizeof(SkPoint));\n\n uint16_t indices[256*6];\n uint16_t* ndx = indices;\n for (int i = 0; i < count; ++i) {\n *ndx++ = i;\n *ndx++ = i + count;\n }\n *ndx++ = 0;\n\n show_mesh(canvas, pts0, indices, ndx - indices);\n}\n\nstatic void show_fan(SkCanvas* canvas, const SkPath& path, SkScalar cx, SkScalar cy) {\n SkPaint paint;\n setGLFrame(&paint);\n\n canvas->drawPath(path, paint);\n\n SkPoint pts[256];\n int count = path.getPoints(pts, SK_ARRAY_COUNT(pts));\n for (int i = 0; i < count; ++i) {\n canvas->drawLine(pts[i].fX, pts[i].fY, cx, cy, paint);\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\ntypedef void (*DrawProc)(SkCanvas* canvas, bool showGL, int flags);\n\nstatic void draw_line(SkCanvas* canvas, bool showGL, int flags) {\n SkPaint paint;\n paint.setAntiAlias(true);\n\n canvas->drawLine(50, 50, 400, 100, paint);\n\n canvas->rotate(40);\n setFade(&paint, showGL);\n paint.setStrokeWidth(40);\n canvas->drawLine(100, 50, 450, 50, paint);\n if (showGL) {\n show_mesh(canvas, SkRect::MakeLTRB(100, 50-20, 450, 50+20));\n }\n}\n\nstatic void draw_rect(SkCanvas* canvas, bool showGL, int flags) {\n SkPaint paint;\n paint.setAntiAlias(true);\n\n SkRect r = SkRect::MakeLTRB(50, 70, 250, 370);\n\n setFade(&paint, showGL);\n canvas->drawRect(r, paint);\n if (showGL) {\n show_mesh(canvas, r);\n }\n\n canvas->translate(320, 0);\n\n paint.setStyle(SkPaint::kStroke_Style);\n paint.setStrokeWidth(25);\n canvas->drawRect(r, paint);\n if (showGL) {\n SkScalar rad = paint.getStrokeWidth() \/ 2;\n SkPoint pts[8];\n r.outset(rad, rad);\n r.toQuad(&pts[0]);\n r.inset(rad*2, rad*2);\n r.toQuad(&pts[4]);\n\n const uint16_t indices[] = {\n 0, 4, 1, 5, 2, 6, 3, 7, 0, 4\n };\n show_mesh(canvas, pts, indices, SK_ARRAY_COUNT(indices));\n }\n}\n\nstatic void draw_oval(SkCanvas* canvas, bool showGL, int flags) {\n SkPaint paint;\n paint.setAntiAlias(true);\n\n SkRect r = SkRect::MakeLTRB(50, 70, 250, 370);\n\n setFade(&paint, showGL);\n canvas->drawOval(r, paint);\n if (showGL) {\n switch (flags) {\n case 0: {\n SkPath path;\n path.addOval(r);\n show_glframe(canvas, path);\n } break;\n case 1:\n case 2: {\n SkPath src, dst;\n src.addOval(r);\n tesselate(src, &dst);\n show_fan(canvas, dst, r.centerX(), r.centerY());\n } break;\n }\n }\n\n canvas->translate(320, 0);\n\n paint.setStyle(SkPaint::kStroke_Style);\n paint.setStrokeWidth(25);\n canvas->drawOval(r, paint);\n if (showGL) {\n switch (flags) {\n case 0: {\n SkPath path;\n SkScalar rad = paint.getStrokeWidth() \/ 2;\n r.outset(rad, rad);\n path.addOval(r);\n r.inset(rad*2, rad*2);\n path.addOval(r);\n show_glframe(canvas, path);\n } break;\n case 1: {\n SkPath path0, path1;\n SkScalar rad = paint.getStrokeWidth() \/ 2;\n r.outset(rad, rad);\n path0.addOval(r);\n r.inset(rad*2, rad*2);\n path1.addOval(r);\n show_mesh_between(canvas, path0, path1);\n } break;\n case 2: {\n SkScalar rad = paint.getStrokeWidth() \/ 2;\n r.outset(rad, rad);\n SkPaint paint;\n paint.setAlpha(0x33);\n canvas->drawRect(r, paint);\n show_mesh(canvas, r);\n } break;\n }\n }\n}\n\n#include \"SkImageDecoder.h\"\nstatic void draw_image(SkCanvas* canvas, bool showGL, int flags) {\n SkPaint paint;\n paint.setAntiAlias(true);\n paint.setFilterBitmap(true);\n setFade(&paint, showGL);\n\n SkBitmap bm;\n SkImageDecoder::DecodeFile(\"\/skimages\/startrek.png\", &bm);\n SkRect r = SkRect::MakeWH(bm.width(), bm.height());\n\n canvas->save();\n canvas->translate(30, 30);\n canvas->scale(0.8f, 0.8f);\n canvas->drawBitmap(bm, 0, 0, &paint);\n if (showGL) {\n show_mesh(canvas, r);\n }\n canvas->restore();\n\n canvas->translate(210, 290);\n canvas->rotate(-35);\n canvas->drawBitmap(bm, 0, 0, &paint);\n if (showGL) {\n show_mesh(canvas, r);\n }\n}\n\nstatic void draw_text(SkCanvas* canvas, bool showGL, int flags) {\n SkPaint paint;\n paint.setAntiAlias(true);\n const char text[] = \"Graphics at Google\";\n size_t len = strlen(text);\n setFade(&paint, showGL);\n\n canvas->translate(40, 50);\n for (int i = 0; i < 10; ++i) {\n paint.setTextSize(12 + i * 3);\n canvas->drawText(text, len, 0, 0, paint);\n if (showGL) {\n SkRect bounds[256];\n SkScalar widths[256];\n int count = paint.getTextWidths(text, len, widths, bounds);\n SkScalar adv = 0;\n for (int j = 0; j < count; ++j) {\n bounds[j].offset(adv, 0);\n show_mesh(canvas, bounds[j]);\n adv += widths[j];\n }\n }\n canvas->translate(0, paint.getTextSize() * 3 \/ 2);\n }\n}\n\nstatic const struct {\n DrawProc fProc;\n const char* fName;\n} gRec[] = {\n { draw_line, \"Lines\" },\n { draw_rect, \"Rects\" },\n { draw_oval, \"Ovals\" },\n { draw_image, \"Images\" },\n { draw_text, \"Text\" },\n};\n\nclass TalkGM : public skiagm::GM {\n DrawProc fProc;\n SkString fName;\n bool fShowGL;\n int fFlags;\n\npublic:\n TalkGM(int index, bool showGL, int flags = 0) {\n fProc = gRec[index].fProc;\n fName.set(gRec[index].fName);\n if (showGL) {\n fName.append(\"-gl\");\n }\n fShowGL = showGL;\n fFlags = flags;\n }\n\nprotected:\n virtual SkString onShortName() {\n return fName;\n }\n\n virtual SkISize onISize() {\n return SkISize::Make(640, 480);\n }\n\n virtual void onDraw(SkCanvas* canvas) {\n SkRect dst = SkRect::MakeWH(canvas->getDevice()->width(), canvas->getDevice()->height());\n SkRect src = SkRect::MakeWH(640, 480);\n SkMatrix matrix;\n matrix.setRectToRect(src, dst, SkMatrix::kCenter_ScaleToFit);\n\n canvas->concat(matrix);\n fProc(canvas, fShowGL, fFlags);\n }\n\nprivate:\n typedef skiagm::GM INHERITED;\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#define GM_CONCAT(X,Y) GM_CONCAT_IMPL(X,Y)\n#define GM_CONCAT_IMPL(X,Y) X##Y\n\n#define FACTORY_NAME GM_CONCAT(Factory, __LINE__)\n#define REGISTRY_NAME GM_CONCAT(gReg, __LINE__)\n\n#define ADD_GM(Class, args) \\\n static skiagm::GM* FACTORY_NAME(void*) { return new Class args; } \\\n static skiagm::GMRegistry REGISTRY_NAME(FACTORY_NAME);\n\nADD_GM(TalkGM, (0, false))\nADD_GM(TalkGM, (0, true))\nADD_GM(TalkGM, (1, false))\nADD_GM(TalkGM, (1, true))\nADD_GM(TalkGM, (2, false))\nADD_GM(TalkGM, (2, true))\nADD_GM(TalkGM, (2, true, 1))\nADD_GM(TalkGM, (2, true, 2))\nADD_GM(TalkGM, (3, false))\nADD_GM(TalkGM, (3, true))\nADD_GM(TalkGM, (4, false))\nADD_GM(TalkGM, (4, true))\n\n\/\/static GM* MyFactory(void*) { return new TalkGM(0, false); }\n\/\/static GMRegistry reg(MyFactory);\n\n\n<commit_msg>update<commit_after>\n\/*\n * Copyright 2012 Google Inc.\n *\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n *\/\n#include \"gm.h\"\n\n#include \"SkColorPriv.h\"\n#include \"SkGeometry.h\"\n#include \"SkShader.h\"\n\n#define WIRE_FRAME_WIDTH 1.1f\n\nstatic void tesselate(const SkPath& src, SkPath* dst) {\n SkPath::Iter iter(src, true);\n SkPoint pts[4];\n SkPath::Verb verb;\n while ((verb = iter.next(pts)) != SkPath::kDone_Verb) {\n switch (verb) {\n case SkPath::kMove_Verb:\n dst->moveTo(pts[0]);\n break;\n case SkPath::kLine_Verb:\n dst->lineTo(pts[1]);\n break;\n case SkPath::kQuad_Verb: {\n SkPoint p;\n for (int i = 1; i <= 8; ++i) {\n SkEvalQuadAt(pts, i \/ 8.0f, &p, NULL);\n dst->lineTo(p);\n }\n } break;\n case SkPath::kCubic_Verb: {\n SkPoint p;\n for (int i = 1; i <= 8; ++i) {\n SkEvalCubicAt(pts, i \/ 8.0f, &p, NULL, NULL);\n dst->lineTo(p);\n }\n } break;\n }\n }\n}\n\nstatic void setFade(SkPaint* paint, bool showGL) {\n paint->setAlpha(showGL ? 0x66 : 0xFF);\n}\n\nstatic void setGLFrame(SkPaint* paint) {\n paint->setColor(0xFFFF0000);\n paint->setStyle(SkPaint::kStroke_Style);\n paint->setAntiAlias(true);\n paint->setStrokeWidth(WIRE_FRAME_WIDTH);\n}\n\nstatic void show_mesh(SkCanvas* canvas, const SkRect& r) {\n SkPaint paint;\n setGLFrame(&paint);\n\n canvas->drawRect(r, paint);\n canvas->drawLine(r.fLeft, r.fTop, r.fRight, r.fBottom, paint);\n}\n\nstatic void drawLine(SkCanvas* canvas, const SkPoint& p0, const SkPoint& p1,\n const SkPaint& paint) {\n canvas->drawLine(p0.fX, p0.fY, p1.fX, p1.fY, paint);\n}\n\nstatic void show_mesh(SkCanvas* canvas, const SkPoint pts[],\n const uint16_t indices[], int count) {\n SkPaint paint;\n setGLFrame(&paint);\n\n for (int i = 0; i < count - 2; ++i) {\n drawLine(canvas, pts[indices[i]], pts[indices[i+1]], paint);\n drawLine(canvas, pts[indices[i+1]], pts[indices[i+2]], paint);\n drawLine(canvas, pts[indices[i+2]], pts[indices[i]], paint);\n }\n}\n\nstatic void show_glframe(SkCanvas* canvas, const SkPath& path) {\n SkPaint paint;\n setGLFrame(&paint);\n canvas->drawPath(path, paint);\n}\n\nstatic void show_mesh_between(SkCanvas* canvas, const SkPath& p0, const SkPath& p1) {\n SkPath d0, d1;\n tesselate(p0, &d0);\n tesselate(p1, &d1);\n\n SkPoint pts0[256*2], pts1[256];\n int count = d0.getPoints(pts0, SK_ARRAY_COUNT(pts0));\n int count1 = d1.getPoints(pts1, SK_ARRAY_COUNT(pts1));\n SkASSERT(count == count1);\n memcpy(&pts0[count], pts1, count * sizeof(SkPoint));\n\n uint16_t indices[256*6];\n uint16_t* ndx = indices;\n for (int i = 0; i < count; ++i) {\n *ndx++ = i;\n *ndx++ = i + count;\n }\n *ndx++ = 0;\n\n show_mesh(canvas, pts0, indices, ndx - indices);\n}\n\nstatic void show_fan(SkCanvas* canvas, const SkPath& path, SkScalar cx, SkScalar cy) {\n SkPaint paint;\n setGLFrame(&paint);\n\n canvas->drawPath(path, paint);\n\n SkPoint pts[256];\n int count = path.getPoints(pts, SK_ARRAY_COUNT(pts));\n for (int i = 0; i < count; ++i) {\n canvas->drawLine(pts[i].fX, pts[i].fY, cx, cy, paint);\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\ntypedef void (*DrawProc)(SkCanvas* canvas, bool showGL, int flags);\n\nstatic void draw_line(SkCanvas* canvas, bool showGL, int flags) {\n SkPaint paint;\n paint.setAntiAlias(true);\n\n if (showGL) {\n setGLFrame(&paint);\n }\n canvas->drawLine(50, 50, 400, 100, paint);\n paint.setColor(SK_ColorBLACK);\n\n canvas->rotate(40);\n setFade(&paint, showGL);\n paint.setStrokeWidth(40);\n canvas->drawLine(100, 50, 450, 50, paint);\n if (showGL) {\n show_mesh(canvas, SkRect::MakeLTRB(100, 50-20, 450, 50+20));\n }\n}\n\nstatic void draw_rect(SkCanvas* canvas, bool showGL, int flags) {\n SkPaint paint;\n paint.setAntiAlias(true);\n\n SkRect r = SkRect::MakeLTRB(50, 70, 250, 370);\n\n setFade(&paint, showGL);\n canvas->drawRect(r, paint);\n if (showGL) {\n show_mesh(canvas, r);\n }\n\n canvas->translate(320, 0);\n\n paint.setStyle(SkPaint::kStroke_Style);\n paint.setStrokeWidth(25);\n canvas->drawRect(r, paint);\n if (showGL) {\n SkScalar rad = paint.getStrokeWidth() \/ 2;\n SkPoint pts[8];\n r.outset(rad, rad);\n r.toQuad(&pts[0]);\n r.inset(rad*2, rad*2);\n r.toQuad(&pts[4]);\n\n const uint16_t indices[] = {\n 0, 4, 1, 5, 2, 6, 3, 7, 0, 4\n };\n show_mesh(canvas, pts, indices, SK_ARRAY_COUNT(indices));\n }\n}\n\nstatic void draw_oval(SkCanvas* canvas, bool showGL, int flags) {\n SkPaint paint;\n paint.setAntiAlias(true);\n\n SkRect r = SkRect::MakeLTRB(50, 70, 250, 370);\n\n setFade(&paint, showGL);\n canvas->drawOval(r, paint);\n if (showGL) {\n switch (flags) {\n case 0: {\n SkPath path;\n path.addOval(r);\n show_glframe(canvas, path);\n } break;\n case 1:\n case 3: {\n SkPath src, dst;\n src.addOval(r);\n tesselate(src, &dst);\n show_fan(canvas, dst, r.centerX(), r.centerY());\n } break;\n case 2: {\n SkPaint p(paint);\n show_mesh(canvas, r);\n setGLFrame(&p);\n paint.setStyle(SkPaint::kFill_Style);\n canvas->drawCircle(r.centerX(), r.centerY(), 3, p);\n } break;\n }\n }\n\n canvas->translate(320, 0);\n\n paint.setStyle(SkPaint::kStroke_Style);\n paint.setStrokeWidth(25);\n canvas->drawOval(r, paint);\n if (showGL) {\n switch (flags) {\n case 0: {\n SkPath path;\n SkScalar rad = paint.getStrokeWidth() \/ 2;\n r.outset(rad, rad);\n path.addOval(r);\n r.inset(rad*2, rad*2);\n path.addOval(r);\n show_glframe(canvas, path);\n } break;\n case 1: {\n SkPath path0, path1;\n SkScalar rad = paint.getStrokeWidth() \/ 2;\n r.outset(rad, rad);\n path0.addOval(r);\n r.inset(rad*2, rad*2);\n path1.addOval(r);\n show_mesh_between(canvas, path0, path1);\n } break;\n case 2: {\n SkPath path;\n path.addOval(r);\n show_glframe(canvas, path);\n SkScalar rad = paint.getStrokeWidth() \/ 2;\n r.outset(rad, rad);\n show_mesh(canvas, r);\n } break;\n case 3: {\n SkScalar rad = paint.getStrokeWidth() \/ 2;\n r.outset(rad, rad);\n SkPaint paint;\n paint.setAlpha(0x33);\n canvas->drawRect(r, paint);\n show_mesh(canvas, r);\n } break;\n }\n }\n}\n\n#include \"SkImageDecoder.h\"\nstatic void draw_image(SkCanvas* canvas, bool showGL, int flags) {\n SkPaint paint;\n paint.setAntiAlias(true);\n paint.setFilterBitmap(true);\n setFade(&paint, showGL);\n\n SkBitmap bm;\n SkImageDecoder::DecodeFile(\"\/skimages\/startrek.png\", &bm);\n SkRect r = SkRect::MakeWH(bm.width(), bm.height());\n\n canvas->save();\n canvas->translate(30, 30);\n canvas->scale(0.8f, 0.8f);\n canvas->drawBitmap(bm, 0, 0, &paint);\n if (showGL) {\n show_mesh(canvas, r);\n }\n canvas->restore();\n\n canvas->translate(210, 290);\n canvas->rotate(-35);\n canvas->drawBitmap(bm, 0, 0, &paint);\n if (showGL) {\n show_mesh(canvas, r);\n }\n}\n\nstatic void draw_text(SkCanvas* canvas, bool showGL, int flags) {\n SkPaint paint;\n paint.setAntiAlias(true);\n const char text[] = \"Graphics at Google\";\n size_t len = strlen(text);\n setFade(&paint, showGL);\n\n canvas->translate(40, 50);\n for (int i = 0; i < 10; ++i) {\n paint.setTextSize(12 + i * 3);\n canvas->drawText(text, len, 0, 0, paint);\n if (showGL) {\n SkRect bounds[256];\n SkScalar widths[256];\n int count = paint.getTextWidths(text, len, widths, bounds);\n SkScalar adv = 0;\n for (int j = 0; j < count; ++j) {\n bounds[j].offset(adv, 0);\n show_mesh(canvas, bounds[j]);\n adv += widths[j];\n }\n }\n canvas->translate(0, paint.getTextSize() * 3 \/ 2);\n }\n}\n\nstatic const struct {\n DrawProc fProc;\n const char* fName;\n} gRec[] = {\n { draw_line, \"Lines\" },\n { draw_rect, \"Rects\" },\n { draw_oval, \"Ovals\" },\n { draw_image, \"Images\" },\n { draw_text, \"Text\" },\n};\n\nclass TalkGM : public skiagm::GM {\n DrawProc fProc;\n SkString fName;\n bool fShowGL;\n int fFlags;\n\npublic:\n TalkGM(int index, bool showGL, int flags = 0) {\n fProc = gRec[index].fProc;\n fName.set(gRec[index].fName);\n if (showGL) {\n fName.append(\"-gl\");\n }\n fShowGL = showGL;\n fFlags = flags;\n }\n\nprotected:\n virtual SkString onShortName() {\n return fName;\n }\n\n virtual SkISize onISize() {\n return SkISize::Make(640, 480);\n }\n\n virtual void onDraw(SkCanvas* canvas) {\n SkRect dst = SkRect::MakeWH(canvas->getDevice()->width(), canvas->getDevice()->height());\n SkRect src = SkRect::MakeWH(640, 480);\n SkMatrix matrix;\n matrix.setRectToRect(src, dst, SkMatrix::kCenter_ScaleToFit);\n\n canvas->concat(matrix);\n fProc(canvas, fShowGL, fFlags);\n }\n\nprivate:\n typedef skiagm::GM INHERITED;\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#define GM_CONCAT(X,Y) GM_CONCAT_IMPL(X,Y)\n#define GM_CONCAT_IMPL(X,Y) X##Y\n\n#define FACTORY_NAME GM_CONCAT(Factory, __LINE__)\n#define REGISTRY_NAME GM_CONCAT(gReg, __LINE__)\n\n#define ADD_GM(Class, args) \\\n static skiagm::GM* FACTORY_NAME(void*) { return new Class args; } \\\n static skiagm::GMRegistry REGISTRY_NAME(FACTORY_NAME);\n\nADD_GM(TalkGM, (0, false))\nADD_GM(TalkGM, (0, true))\nADD_GM(TalkGM, (1, false))\nADD_GM(TalkGM, (1, true))\nADD_GM(TalkGM, (2, false))\nADD_GM(TalkGM, (2, true))\nADD_GM(TalkGM, (2, true, 1))\nADD_GM(TalkGM, (2, true, 2))\nADD_GM(TalkGM, (2, true, 3))\nADD_GM(TalkGM, (3, false))\nADD_GM(TalkGM, (3, true))\nADD_GM(TalkGM, (4, false))\nADD_GM(TalkGM, (4, true))\n\n\/\/static GM* MyFactory(void*) { return new TalkGM(0, false); }\n\/\/static GMRegistry reg(MyFactory);\n\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ Game_Music_Emu https:\/\/bitbucket.org\/mpyne\/game-music-emu\/\n\n#include \"Nsfe_Emu.h\"\n\n#include \"blargg_endian.h\"\n#include <string.h>\n#include <ctype.h>\n\n\/* Copyright (C) 2005-2006 Shay Green. This module is free software; you\ncan redistribute it and\/or modify it under the terms of the GNU Lesser\nGeneral Public License as published by the Free Software Foundation; either\nversion 2.1 of the License, or (at your option) any later version. This\nmodule is distributed in the hope that it will be useful, but WITHOUT ANY\nWARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\nFOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more\ndetails. You should have received a copy of the GNU Lesser General Public\nLicense along with this module; if not, write to the Free Software Foundation,\nInc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA *\/\n\n#include \"blargg_source.h\"\n\nNsfe_Info::Nsfe_Info() { playlist_disabled = false; }\n\nNsfe_Info::~Nsfe_Info() { }\n\ninline void Nsfe_Info::unload()\n{\n\ttrack_name_data.clear();\n\ttrack_names.clear();\n\tplaylist.clear();\n\ttrack_times.clear();\n}\n\n\/\/ TODO: if no playlist, treat as if there is a playlist that is just 1,2,3,4,5... ?\nvoid Nsfe_Info::disable_playlist( bool b )\n{\n\tplaylist_disabled = b;\n\tinfo.track_count = playlist.size();\n\tif ( !info.track_count || playlist_disabled )\n\t\tinfo.track_count = actual_track_count_;\n}\n\nint Nsfe_Info::remap_track( int track ) const\n{\n\tif ( !playlist_disabled && (unsigned) track < playlist.size() )\n\t\ttrack = playlist [track];\n\treturn track;\n}\n\n\/\/ Read multiple strings and separate into individual strings\nstatic blargg_err_t read_strs( Data_Reader& in, long size, blargg_vector<char>& chars,\n\t\tblargg_vector<const char*>& strs )\n{\n\tRETURN_ERR( chars.resize( size + 1 ) );\n\tchars [size] = 0; \/\/ in case last string doesn't have terminator\n\tRETURN_ERR( in.read( &chars [0], size ) );\n\t\n\tRETURN_ERR( strs.resize( 128 ) );\n\tint count = 0;\n\tfor ( int i = 0; i < size; i++ )\n\t{\n\t\tif ( (int) strs.size() <= count )\n\t\t\tRETURN_ERR( strs.resize( count * 2 ) );\n\t\tstrs [count++] = &chars [i];\n\t\twhile ( i < size && chars [i] )\n\t\t\ti++;\n\t}\n\t\n\treturn strs.resize( count );\n}\n\n\/\/ Copy in to out, where out has out_max characters allocated. Truncate to\n\/\/ out_max - 1 characters.\nstatic void copy_str( const char* in, char* out, int out_max )\n{\n\tout [out_max - 1] = 0;\n\tstrncpy( out, in, out_max - 1 );\n}\n\nstruct nsfe_info_t\n{\n\tbyte load_addr [2];\n\tbyte init_addr [2];\n\tbyte play_addr [2];\n\tbyte speed_flags;\n\tbyte chip_flags;\n\tbyte track_count;\n\tbyte first_track;\n\tbyte unused [6];\n};\n\nblargg_err_t Nsfe_Info::load( Data_Reader& in, Nsf_Emu* nsf_emu )\n{\n\tint const nsfe_info_size = 16;\n\tassert( offsetof (nsfe_info_t,unused [6]) == nsfe_info_size );\n\t\n\t\/\/ check header\n\tbyte signature [4];\n\tblargg_err_t err = in.read( signature, sizeof signature );\n\tif ( err )\n\t\treturn (err == in.eof_error ? gme_wrong_file_type : err);\n\tif ( memcmp( signature, \"NSFE\", 4 ) )\n\t\treturn gme_wrong_file_type;\n\t\n\t\/\/ free previous info\n\ttrack_name_data.clear();\n\ttrack_names.clear();\n\tplaylist.clear();\n\ttrack_times.clear();\n\t\n\t\/\/ default nsf header\n\tstatic const Nsf_Emu::header_t base_header =\n\t{\n\t\t{'N','E','S','M','\\x1A'},\/\/ tag\n\t\t1, \/\/ version\n\t\t1, 1, \/\/ track count, first track\n\t\t{0,0},{0,0},{0,0}, \/\/ addresses\n\t\t\"\",\"\",\"\", \/\/ strings\n\t\t{0x1A, 0x41}, \/\/ NTSC rate\n\t\t{0,0,0,0,0,0,0,0}, \/\/ banks\n\t\t{0x20, 0x4E}, \/\/ PAL rate\n\t\t0, 0, \/\/ flags\n\t\t{0,0,0,0} \/\/ unused\n\t};\n\tNsf_Emu::header_t& header = info;\n\theader = base_header;\n\t\n\t\/\/ parse tags\n\tint phase = 0;\n\twhile ( phase != 3 )\n\t{\n\t\t\/\/ read size and tag\n\t\tbyte block_header [2] [4];\n\t\tRETURN_ERR( in.read( block_header, sizeof block_header ) );\n\t\tblargg_long size = get_le32( block_header [0] );\n\t\tblargg_long tag = get_le32( block_header [1] );\n\n\t\tif ( size <= 0 )\n\t\t\treturn \"Corrupt file\";\n\t\t\n\t\t\/\/debug_printf( \"tag: %c%c%c%c\\n\", char(tag), char(tag>>8), char(tag>>16), char(tag>>24) );\n\t\t\n\t\tswitch ( tag )\n\t\t{\n\t\t\tcase BLARGG_4CHAR('O','F','N','I'): {\n\t\t\t\tcheck( phase == 0 );\n\t\t\t\tif ( size < 8 )\n\t\t\t\t\treturn \"Corrupt file\";\n\t\t\t\t\n\t\t\t\tnsfe_info_t finfo;\n\t\t\t\tfinfo.track_count = 1;\n\t\t\t\tfinfo.first_track = 0;\n\t\t\t\t\n\t\t\t\tRETURN_ERR( in.read( &finfo, min( size, (blargg_long) nsfe_info_size ) ) );\n\t\t\t\tif ( size > nsfe_info_size )\n\t\t\t\t\tRETURN_ERR( in.skip( size - nsfe_info_size ) );\n\t\t\t\tphase = 1;\n\t\t\t\tinfo.speed_flags = finfo.speed_flags;\n\t\t\t\tinfo.chip_flags = finfo.chip_flags;\n\t\t\t\tinfo.track_count = finfo.track_count;\n\t\t\t\tthis->actual_track_count_ = finfo.track_count;\n\t\t\t\tinfo.first_track = finfo.first_track;\n\t\t\t\tmemcpy( info.load_addr, finfo.load_addr, 2 * 3 );\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\t\n\t\t\tcase BLARGG_4CHAR('K','N','A','B'):\n\t\t\t\tif ( size > (int) sizeof info.banks )\n\t\t\t\t\treturn \"Corrupt file\";\n\t\t\t\tRETURN_ERR( in.read( info.banks, size ) );\n\t\t\t\tbreak;\n\t\t\t\n\t\t\tcase BLARGG_4CHAR('h','t','u','a'): {\n\t\t\t\tblargg_vector<char> chars;\n\t\t\t\tblargg_vector<const char*> strs;\n\t\t\t\tRETURN_ERR( read_strs( in, size, chars, strs ) );\n\t\t\t\tint n = strs.size();\n\t\t\t\t\n\t\t\t\tif ( n > 3 )\n\t\t\t\t\tcopy_str( strs [3], info.dumper, sizeof info.dumper );\n\t\t\t\t\n\t\t\t\tif ( n > 2 )\n\t\t\t\t\tcopy_str( strs [2], info.copyright, sizeof info.copyright );\n\t\t\t\t\n\t\t\t\tif ( n > 1 )\n\t\t\t\t\tcopy_str( strs [1], info.author, sizeof info.author );\n\t\t\t\t\n\t\t\t\tif ( n > 0 )\n\t\t\t\t\tcopy_str( strs [0], info.game, sizeof info.game );\n\t\t\t\t\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\t\n\t\t\tcase BLARGG_4CHAR('e','m','i','t'):\n\t\t\t\tRETURN_ERR( track_times.resize( size \/ 4 ) );\n\t\t\t\tRETURN_ERR( in.read( track_times.begin(), track_times.size() * 4 ) );\n\t\t\t\tbreak;\n\t\t\t\n\t\t\tcase BLARGG_4CHAR('l','b','l','t'):\n\t\t\t\tRETURN_ERR( read_strs( in, size, track_name_data, track_names ) );\n\t\t\t\tbreak;\n\t\t\t\n\t\t\tcase BLARGG_4CHAR('t','s','l','p'):\n\t\t\t\tRETURN_ERR( playlist.resize( size ) );\n\t\t\t\tRETURN_ERR( in.read( &playlist [0], size ) );\n\t\t\t\tbreak;\n\t\t\t\n\t\t\tcase BLARGG_4CHAR('A','T','A','D'): {\n\t\t\t\tcheck( phase == 1 );\n\t\t\t\tphase = 2;\n\t\t\t\tif ( !nsf_emu )\n\t\t\t\t{\n\t\t\t\t\tRETURN_ERR( in.skip( size ) );\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tSubset_Reader sub( &in, size ); \/\/ limit emu to nsf data\n\t\t\t\t\tRemaining_Reader rem( &header, Nsf_Emu::header_size, &sub );\n\t\t\t\t\tRETURN_ERR( nsf_emu->load( rem ) );\n\t\t\t\t\tcheck( rem.remain() == 0 );\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\t\n\t\t\tcase BLARGG_4CHAR('D','N','E','N'):\n\t\t\t\tcheck( phase == 2 );\n\t\t\t\tphase = 3;\n\t\t\t\tbreak;\n\t\t\t\n\t\t\tdefault:\n\t\t\t\t\/\/ tags that can be skipped start with a lowercase character\n\t\t\t\tcheck( islower( (tag >> 24) & 0xFF ) );\n\t\t\t\tRETURN_ERR( in.skip( size ) );\n\t\t\t\tbreak;\n\t\t}\n\t}\n\t\n\treturn 0;\n}\n\nblargg_err_t Nsfe_Info::track_info_( track_info_t* out, int track ) const\n{\n\tint remapped = remap_track( track );\n\tif ( (unsigned) remapped < track_times.size() )\n\t{\n\t\tlong length = (int32_t) get_le32( track_times [remapped] );\n\t\tif ( length > 0 )\n\t\t\tout->length = length;\n\t}\n\tif ( (unsigned) remapped < track_names.size() )\n\t\tGme_File::copy_field_( out->song, track_names [remapped] );\n\t\n\tGME_COPY_FIELD( info, out, game );\n\tGME_COPY_FIELD( info, out, author );\n\tGME_COPY_FIELD( info, out, copyright );\n\tGME_COPY_FIELD( info, out, dumper );\n\treturn 0;\n}\n\nNsfe_Emu::Nsfe_Emu()\n{\n\tloading = false;\n\tset_type( gme_nsfe_type );\n}\n\nNsfe_Emu::~Nsfe_Emu() { }\n\nvoid Nsfe_Emu::unload()\n{\n\tif ( !loading )\n\t\tinfo.unload(); \/\/ TODO: extremely hacky!\n\tNsf_Emu::unload();\n}\n\nblargg_err_t Nsfe_Emu::track_info_( track_info_t* out, int track ) const\n{\n\treturn info.track_info_( out, track );\n}\n\nstruct Nsfe_File : Gme_Info_\n{\n\tNsfe_Info info;\n\t\n\tNsfe_File() { set_type( gme_nsfe_type ); }\n\t\n\tblargg_err_t load_( Data_Reader& in )\n\t{\n\t\tRETURN_ERR( info.load( in, 0 ) );\n\t\tinfo.disable_playlist( false );\n\t\tset_track_count( info.info.track_count );\n\t\treturn 0;\n\t}\n\t\n\tblargg_err_t track_info_( track_info_t* out, int track ) const\n\t{\n\t\treturn info.track_info_( out, track );\n\t}\n};\n\nstatic Music_Emu* new_nsfe_emu () { return BLARGG_NEW Nsfe_Emu ; }\nstatic Music_Emu* new_nsfe_file() { return BLARGG_NEW Nsfe_File; }\n\nstatic gme_type_t_ const gme_nsfe_type_ = { \"Nintendo NES\", 0, &new_nsfe_emu, &new_nsfe_file, \"NSFE\", 1 };\nBLARGG_EXPORT extern gme_type_t const gme_nsfe_type = &gme_nsfe_type_;\n\n\nblargg_err_t Nsfe_Emu::load_( Data_Reader& in )\n{\n\tif ( loading )\n\t\treturn Nsf_Emu::load_( in );\n\t\n\t\/\/ TODO: this hacky recursion-avoidance could have subtle problems\n\tloading = true;\n\tblargg_err_t err = info.load( in, this );\n\tloading = false;\n\tdisable_playlist( false );\n\treturn err;\n}\n\nvoid Nsfe_Emu::disable_playlist( bool b )\n{\n\tinfo.disable_playlist( b );\n\tset_track_count( info.info.track_count );\n}\n\nvoid Nsfe_Emu::clear_playlist_()\n{\n\tdisable_playlist();\n\tNsf_Emu::clear_playlist_();\n}\n\nblargg_err_t Nsfe_Emu::start_track_( int track )\n{\n\treturn Nsf_Emu::start_track_( info.remap_track( track ) );\n}\n<commit_msg>nsfe: Some blocks can have a 0-sized header, don't fail for those.<commit_after>\/\/ Game_Music_Emu https:\/\/bitbucket.org\/mpyne\/game-music-emu\/\n\n#include \"Nsfe_Emu.h\"\n\n#include \"blargg_endian.h\"\n#include <string.h>\n#include <ctype.h>\n\n\/* Copyright (C) 2005-2006 Shay Green. This module is free software; you\ncan redistribute it and\/or modify it under the terms of the GNU Lesser\nGeneral Public License as published by the Free Software Foundation; either\nversion 2.1 of the License, or (at your option) any later version. This\nmodule is distributed in the hope that it will be useful, but WITHOUT ANY\nWARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\nFOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more\ndetails. You should have received a copy of the GNU Lesser General Public\nLicense along with this module; if not, write to the Free Software Foundation,\nInc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA *\/\n\n#include \"blargg_source.h\"\n\nNsfe_Info::Nsfe_Info() { playlist_disabled = false; }\n\nNsfe_Info::~Nsfe_Info() { }\n\ninline void Nsfe_Info::unload()\n{\n\ttrack_name_data.clear();\n\ttrack_names.clear();\n\tplaylist.clear();\n\ttrack_times.clear();\n}\n\n\/\/ TODO: if no playlist, treat as if there is a playlist that is just 1,2,3,4,5... ?\nvoid Nsfe_Info::disable_playlist( bool b )\n{\n\tplaylist_disabled = b;\n\tinfo.track_count = playlist.size();\n\tif ( !info.track_count || playlist_disabled )\n\t\tinfo.track_count = actual_track_count_;\n}\n\nint Nsfe_Info::remap_track( int track ) const\n{\n\tif ( !playlist_disabled && (unsigned) track < playlist.size() )\n\t\ttrack = playlist [track];\n\treturn track;\n}\n\n\/\/ Read multiple strings and separate into individual strings\nstatic blargg_err_t read_strs( Data_Reader& in, long size, blargg_vector<char>& chars,\n\t\tblargg_vector<const char*>& strs )\n{\n\tRETURN_ERR( chars.resize( size + 1 ) );\n\tchars [size] = 0; \/\/ in case last string doesn't have terminator\n\tRETURN_ERR( in.read( &chars [0], size ) );\n\t\n\tRETURN_ERR( strs.resize( 128 ) );\n\tint count = 0;\n\tfor ( int i = 0; i < size; i++ )\n\t{\n\t\tif ( (int) strs.size() <= count )\n\t\t\tRETURN_ERR( strs.resize( count * 2 ) );\n\t\tstrs [count++] = &chars [i];\n\t\twhile ( i < size && chars [i] )\n\t\t\ti++;\n\t}\n\t\n\treturn strs.resize( count );\n}\n\n\/\/ Copy in to out, where out has out_max characters allocated. Truncate to\n\/\/ out_max - 1 characters.\nstatic void copy_str( const char* in, char* out, int out_max )\n{\n\tout [out_max - 1] = 0;\n\tstrncpy( out, in, out_max - 1 );\n}\n\nstruct nsfe_info_t\n{\n\tbyte load_addr [2];\n\tbyte init_addr [2];\n\tbyte play_addr [2];\n\tbyte speed_flags;\n\tbyte chip_flags;\n\tbyte track_count;\n\tbyte first_track;\n\tbyte unused [6];\n};\n\nblargg_err_t Nsfe_Info::load( Data_Reader& in, Nsf_Emu* nsf_emu )\n{\n\tint const nsfe_info_size = 16;\n\tassert( offsetof (nsfe_info_t,unused [6]) == nsfe_info_size );\n\t\n\t\/\/ check header\n\tbyte signature [4];\n\tblargg_err_t err = in.read( signature, sizeof signature );\n\tif ( err )\n\t\treturn (err == in.eof_error ? gme_wrong_file_type : err);\n\tif ( memcmp( signature, \"NSFE\", 4 ) )\n\t\treturn gme_wrong_file_type;\n\t\n\t\/\/ free previous info\n\ttrack_name_data.clear();\n\ttrack_names.clear();\n\tplaylist.clear();\n\ttrack_times.clear();\n\t\n\t\/\/ default nsf header\n\tstatic const Nsf_Emu::header_t base_header =\n\t{\n\t\t{'N','E','S','M','\\x1A'},\/\/ tag\n\t\t1, \/\/ version\n\t\t1, 1, \/\/ track count, first track\n\t\t{0,0},{0,0},{0,0}, \/\/ addresses\n\t\t\"\",\"\",\"\", \/\/ strings\n\t\t{0x1A, 0x41}, \/\/ NTSC rate\n\t\t{0,0,0,0,0,0,0,0}, \/\/ banks\n\t\t{0x20, 0x4E}, \/\/ PAL rate\n\t\t0, 0, \/\/ flags\n\t\t{0,0,0,0} \/\/ unused\n\t};\n\tNsf_Emu::header_t& header = info;\n\theader = base_header;\n\t\n\t\/\/ parse tags\n\tint phase = 0;\n\twhile ( phase != 3 )\n\t{\n\t\t\/\/ read size and tag\n\t\tbyte block_header [2] [4];\n\t\tRETURN_ERR( in.read( block_header, sizeof block_header ) );\n\t\tblargg_long size = get_le32( block_header [0] );\n\t\tblargg_long tag = get_le32( block_header [1] );\n\n\t\tif ( size < 0 )\n\t\t\treturn \"Corrupt file\";\n\t\t\n\t\t\/\/debug_printf( \"tag: %c%c%c%c\\n\", char(tag), char(tag>>8), char(tag>>16), char(tag>>24) );\n\t\t\n\t\tswitch ( tag )\n\t\t{\n\t\t\tcase BLARGG_4CHAR('O','F','N','I'): {\n\t\t\t\tcheck( phase == 0 );\n\t\t\t\tif ( size < 8 )\n\t\t\t\t\treturn \"Corrupt file\";\n\t\t\t\t\n\t\t\t\tnsfe_info_t finfo;\n\t\t\t\tfinfo.track_count = 1;\n\t\t\t\tfinfo.first_track = 0;\n\t\t\t\t\n\t\t\t\tRETURN_ERR( in.read( &finfo, min( size, (blargg_long) nsfe_info_size ) ) );\n\t\t\t\tif ( size > nsfe_info_size )\n\t\t\t\t\tRETURN_ERR( in.skip( size - nsfe_info_size ) );\n\t\t\t\tphase = 1;\n\t\t\t\tinfo.speed_flags = finfo.speed_flags;\n\t\t\t\tinfo.chip_flags = finfo.chip_flags;\n\t\t\t\tinfo.track_count = finfo.track_count;\n\t\t\t\tthis->actual_track_count_ = finfo.track_count;\n\t\t\t\tinfo.first_track = finfo.first_track;\n\t\t\t\tmemcpy( info.load_addr, finfo.load_addr, 2 * 3 );\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\t\n\t\t\tcase BLARGG_4CHAR('K','N','A','B'):\n\t\t\t\tif ( size > (int) sizeof info.banks )\n\t\t\t\t\treturn \"Corrupt file\";\n\t\t\t\tRETURN_ERR( in.read( info.banks, size ) );\n\t\t\t\tbreak;\n\t\t\t\n\t\t\tcase BLARGG_4CHAR('h','t','u','a'): {\n\t\t\t\tblargg_vector<char> chars;\n\t\t\t\tblargg_vector<const char*> strs;\n\t\t\t\tRETURN_ERR( read_strs( in, size, chars, strs ) );\n\t\t\t\tint n = strs.size();\n\t\t\t\t\n\t\t\t\tif ( n > 3 )\n\t\t\t\t\tcopy_str( strs [3], info.dumper, sizeof info.dumper );\n\t\t\t\t\n\t\t\t\tif ( n > 2 )\n\t\t\t\t\tcopy_str( strs [2], info.copyright, sizeof info.copyright );\n\t\t\t\t\n\t\t\t\tif ( n > 1 )\n\t\t\t\t\tcopy_str( strs [1], info.author, sizeof info.author );\n\t\t\t\t\n\t\t\t\tif ( n > 0 )\n\t\t\t\t\tcopy_str( strs [0], info.game, sizeof info.game );\n\t\t\t\t\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\t\n\t\t\tcase BLARGG_4CHAR('e','m','i','t'):\n\t\t\t\tRETURN_ERR( track_times.resize( size \/ 4 ) );\n\t\t\t\tRETURN_ERR( in.read( track_times.begin(), track_times.size() * 4 ) );\n\t\t\t\tbreak;\n\t\t\t\n\t\t\tcase BLARGG_4CHAR('l','b','l','t'):\n\t\t\t\tRETURN_ERR( read_strs( in, size, track_name_data, track_names ) );\n\t\t\t\tbreak;\n\t\t\t\n\t\t\tcase BLARGG_4CHAR('t','s','l','p'):\n\t\t\t\tRETURN_ERR( playlist.resize( size ) );\n\t\t\t\tRETURN_ERR( in.read( &playlist [0], size ) );\n\t\t\t\tbreak;\n\t\t\t\n\t\t\tcase BLARGG_4CHAR('A','T','A','D'): {\n\t\t\t\tcheck( phase == 1 );\n\t\t\t\tphase = 2;\n\t\t\t\tif ( !nsf_emu )\n\t\t\t\t{\n\t\t\t\t\tRETURN_ERR( in.skip( size ) );\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tSubset_Reader sub( &in, size ); \/\/ limit emu to nsf data\n\t\t\t\t\tRemaining_Reader rem( &header, Nsf_Emu::header_size, &sub );\n\t\t\t\t\tRETURN_ERR( nsf_emu->load( rem ) );\n\t\t\t\t\tcheck( rem.remain() == 0 );\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\t\n\t\t\tcase BLARGG_4CHAR('D','N','E','N'):\n\t\t\t\tcheck( phase == 2 );\n\t\t\t\tphase = 3;\n\t\t\t\tbreak;\n\t\t\t\n\t\t\tdefault:\n\t\t\t\t\/\/ tags that can be skipped start with a lowercase character\n\t\t\t\tcheck( islower( (tag >> 24) & 0xFF ) );\n\t\t\t\tRETURN_ERR( in.skip( size ) );\n\t\t\t\tbreak;\n\t\t}\n\t}\n\t\n\treturn 0;\n}\n\nblargg_err_t Nsfe_Info::track_info_( track_info_t* out, int track ) const\n{\n\tint remapped = remap_track( track );\n\tif ( (unsigned) remapped < track_times.size() )\n\t{\n\t\tlong length = (int32_t) get_le32( track_times [remapped] );\n\t\tif ( length > 0 )\n\t\t\tout->length = length;\n\t}\n\tif ( (unsigned) remapped < track_names.size() )\n\t\tGme_File::copy_field_( out->song, track_names [remapped] );\n\t\n\tGME_COPY_FIELD( info, out, game );\n\tGME_COPY_FIELD( info, out, author );\n\tGME_COPY_FIELD( info, out, copyright );\n\tGME_COPY_FIELD( info, out, dumper );\n\treturn 0;\n}\n\nNsfe_Emu::Nsfe_Emu()\n{\n\tloading = false;\n\tset_type( gme_nsfe_type );\n}\n\nNsfe_Emu::~Nsfe_Emu() { }\n\nvoid Nsfe_Emu::unload()\n{\n\tif ( !loading )\n\t\tinfo.unload(); \/\/ TODO: extremely hacky!\n\tNsf_Emu::unload();\n}\n\nblargg_err_t Nsfe_Emu::track_info_( track_info_t* out, int track ) const\n{\n\treturn info.track_info_( out, track );\n}\n\nstruct Nsfe_File : Gme_Info_\n{\n\tNsfe_Info info;\n\t\n\tNsfe_File() { set_type( gme_nsfe_type ); }\n\t\n\tblargg_err_t load_( Data_Reader& in )\n\t{\n\t\tRETURN_ERR( info.load( in, 0 ) );\n\t\tinfo.disable_playlist( false );\n\t\tset_track_count( info.info.track_count );\n\t\treturn 0;\n\t}\n\t\n\tblargg_err_t track_info_( track_info_t* out, int track ) const\n\t{\n\t\treturn info.track_info_( out, track );\n\t}\n};\n\nstatic Music_Emu* new_nsfe_emu () { return BLARGG_NEW Nsfe_Emu ; }\nstatic Music_Emu* new_nsfe_file() { return BLARGG_NEW Nsfe_File; }\n\nstatic gme_type_t_ const gme_nsfe_type_ = { \"Nintendo NES\", 0, &new_nsfe_emu, &new_nsfe_file, \"NSFE\", 1 };\nBLARGG_EXPORT extern gme_type_t const gme_nsfe_type = &gme_nsfe_type_;\n\n\nblargg_err_t Nsfe_Emu::load_( Data_Reader& in )\n{\n\tif ( loading )\n\t\treturn Nsf_Emu::load_( in );\n\t\n\t\/\/ TODO: this hacky recursion-avoidance could have subtle problems\n\tloading = true;\n\tblargg_err_t err = info.load( in, this );\n\tloading = false;\n\tdisable_playlist( false );\n\treturn err;\n}\n\nvoid Nsfe_Emu::disable_playlist( bool b )\n{\n\tinfo.disable_playlist( b );\n\tset_track_count( info.info.track_count );\n}\n\nvoid Nsfe_Emu::clear_playlist_()\n{\n\tdisable_playlist();\n\tNsf_Emu::clear_playlist_();\n}\n\nblargg_err_t Nsfe_Emu::start_track_( int track )\n{\n\treturn Nsf_Emu::start_track_( info.remap_track( track ) );\n}\n<|endoftext|>"} {"text":"<commit_before>#include <cstdlib>\n#include <cstring>\n#include <cstdio>\n#include <ctype.h>\n\n#include \"..\/hunspell\/csutil.hxx\"\n#include \"latexparser.hxx\"\n\n#ifndef W32\nusing namespace std;\n#endif\n\nstatic struct {\n\tconst char * pat[2];\n\tint arg;\n} PATTERN[] = {\n\t{ { \"\\\\(\", \"\\\\)\" } , 0 },\n\t{ { \"$$\", \"$$\" } , 0 },\n\t{ { \"$\", \"$\" } , 0 },\n\t{ { \"\\\\begin{math}\", \"\\\\end{math}\" } , 0 },\n\t{ { \"\\\\[\", \"\\\\]\" } , 0 },\n\t{ { \"\\\\begin{displaymath}\", \"\\\\end{displaymath}\" } , 0 },\n\t{ { \"\\\\begin{equation}\", \"\\\\end{equation}\" } , 0 },\n\t{ { \"\\\\begin{equation*}\", \"\\\\end{equation*}\" } , 0 },\n\t{ { \"\\\\cite\", NULL } , 1 },\n\t{ { \"\\\\nocite\", NULL } , 1 },\n\t{ { \"\\\\index\", NULL } , 1 },\n\t{ { \"\\\\label\", NULL } , 1 },\n\t{ { \"\\\\ref\", NULL } , 1 },\n\t{ { \"\\\\pageref\", NULL } , 1 },\n\t{ { \"\\\\parbox\", NULL } , 1 },\n\t{ { \"\\\\begin{verbatim}\", \"\\\\end{verbatim}\" } , 0 },\n\t{ { \"\\\\verb+\", \"+\" } , 0 },\n\t{ { \"\\\\verb|\", \"|\" } , 0 },\n\t{ { \"\\\\verb#\", \"#\" } , 0 },\n\t{ { \"\\\\verb*\", \"*\" } , 0 },\n\t{ { \"\\\\documentstyle\", \"\\\\begin{document}\" } , 0 },\n\t{ { \"\\\\documentclass\", \"\\\\begin{document}\" } , 0 },\n\/\/\t{ { \"\\\\documentclass\", NULL } , 1 },\n\t{ { \"\\\\usepackage\", NULL } , 1 },\n\t{ { \"\\\\includeonly\", NULL } , 1 },\n\t{ { \"\\\\include\", NULL } , 1 },\n\t{ { \"\\\\input\", NULL } , 1 },\n\t{ { \"\\\\vspace\", NULL } , 1 },\n\t{ { \"\\\\setlength\", NULL } , 2 },\n\t{ { \"\\\\addtolength\", NULL } , 2 },\n\t{ { \"\\\\settowidth\", NULL } , 2 },\n\t{ { \"\\\\rule\", NULL } , 2 },\n\t{ { \"\\\\hspace\", NULL } , 1 } ,\n\t{ { \"\\\\vspace\", NULL } , 1 } ,\n\t{ { \"\\\\\\\\[\", \"]\" } , 0 },\n\t{ { \"\\\\pagebreak[\", \"]\" } , 0 } ,\n\t{ { \"\\\\nopagebreak[\", \"]\" } , 0 } ,\n\t{ { \"\\\\enlargethispage\", NULL } , 1 } ,\n\t{ { \"\\\\begin{tabular}\", NULL } , 1 } ,\n\t{ { \"\\\\addcontentsline\", NULL } , 2 } ,\n\t{ { \"\\\\begin{thebibliography}\", NULL } , 1 } ,\n\t{ { \"\\\\bibliography\", NULL } , 1 } ,\n\t{ { \"\\\\bibliographystyle\", NULL } , 1 } ,\n\t{ { \"\\\\bibitem\", NULL } , 1 } ,\n\t{ { \"\\\\begin\", NULL } , 1 } ,\n\t{ { \"\\\\end\", NULL } , 1 } ,\n\t{ { \"\\\\pagestyle\", NULL } , 1 } ,\n\t{ { \"\\\\pagenumbering\", NULL } , 1 } ,\n\t{ { \"\\\\thispagestyle\", NULL } , 1 } ,\n\t{ { \"\\\\newtheorem\", NULL } , 2 },\n\t{ { \"\\\\newcommand\", NULL } , 2 },\n\t{ { \"\\\\renewcommand\", NULL } , 2 },\n\t{ { \"\\\\setcounter\", NULL } , 2 },\n\t{ { \"\\\\addtocounter\", NULL } , 1 },\n\t{ { \"\\\\stepcounter\", NULL } , 1 },\n\t{ { \"\\\\selectlanguage\", NULL } , 1 },\n\t{ { \"\\\\inputencoding\", NULL } , 1 },\n\t{ { \"\\\\hyphenation\", NULL } , 1 },\n\t{ { \"\\\\definecolor\", NULL } , 3 },\n\t{ { \"\\\\color\", NULL } , 1 },\n\t{ { \"\\\\textcolor\", NULL } , 1 },\n\t{ { \"\\\\pagecolor\", NULL } , 1 },\n\t{ { \"\\\\colorbox\", NULL } , 2 },\n\t{ { \"\\\\fcolorbox\", NULL } , 2 },\n\t{ { \"\\\\declaregraphicsextensions\", NULL } , 1 },\n\t{ { \"\\\\psfig\", NULL } , 1 },\n\t{ { \"\\\\url\", NULL } , 1 },\n\t{ { \"\\\\eqref\", NULL } , 1 },\n\t{ { \"\\\\vskip\", NULL } , 1 },\n\t{ { \"\\\\vglue\", NULL } , 1 },\n\t{ { \"\\'\\'\", NULL } , 1 }\n};\n\n#define PATTERN_LEN (sizeof(PATTERN) \/ sizeof(PATTERN[0]))\n\nLaTeXParser::LaTeXParser(const char * wordchars)\n{\n\tinit(wordchars);\n}\n\nLaTeXParser::LaTeXParser(unsigned short * wordchars, int len)\n{\n\tinit(wordchars, len);\n}\n\nLaTeXParser::~LaTeXParser() \n{\n}\n\nint LaTeXParser::look_pattern(int col)\n{\n\tfor (unsigned int i = 0; i < PATTERN_LEN; i++) {\n\t\tchar * j = line[actual] + head;\n\t\tconst char * k = PATTERN[i].pat[col];\n\t\tif (! k) continue;\n\t\twhile ((*k != '\\0') && (tolower(*j) == *k)) {\n\t\t\tj++;\n\t\t\tk++;\n\t\t}\n\t\tif (*k == '\\0') return i;\n\t}\n\treturn -1;\n}\n\n\/*\n * LaTeXParser\n *\n * state 0: not wordchar\n * state 1: wordchar\n * state 2: comments\n * state 3: commands \n * state 4: commands with arguments\n * state 5: % comment\n *\n *\/\n\n\nchar * LaTeXParser::next_token()\n{\n\tint i;\n\tint slash = 0;\n\tint apostrophe;\n\tfor (;;) {\n\t\t\/\/ fprintf(stderr,\"depth: %d, state: %d, , arg: %d, token: %s\\n\",depth,state,arg,line[actual]+head);\n\t\t\n\t\tswitch (state)\n\t\t{\n\t\tcase 0: \/\/ non word chars\n\t\t\tif ((pattern_num = look_pattern(0)) != -1) {\n\t\t\t\tif (PATTERN[pattern_num].pat[1]) {\n\t\t\t\t\tstate = 2;\n\t\t\t\t} else {\n\t\t\t\t\tstate = 4;\n\t\t\t\t\tdepth = 0;\n\t\t\t\t\targ = 0;\n\t\t\t\t\topt = 1;\n\t\t\t\t}\n\t\t\t\thead += strlen(PATTERN[pattern_num].pat[0]) - 1;\n\t\t\t} else if (line[actual][head] == '%') {\n\t\t\t\t\tstate = 5;\n\t\t\t} else if (is_wordchar(line[actual] + head)) {\n\t\t\t\tstate = 1;\n\t\t\t\ttoken = head;\n\t\t\t} else if (line[actual][head] == '\\\\') {\n\t\t\t\tif (line[actual][head + 1] == '\\\\' || \/\/ \\\\ (linebreak)\n\t\t\t\t\t(line[actual][head + 1] == '$') || \/\/ \\$ (dollar sign)\n\t\t\t\t\t(line[actual][head + 1] == '%')) { \/\/ \\% (percent)\n\t\t\t\t\thead++;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tstate = 3;\n\t\t\t} else if (line[actual][head] == '%') {\n\t\t\t\tif ((head==0) || (line[actual][head - 1] != '\\\\')) state = 5;\n\t\t\t}\n\t\t\tbreak;\n\t\tcase 1: \/\/ wordchar\n\t\t\tapostrophe = 0;\n\t\t\tif (! is_wordchar(line[actual] + head) ||\n\t\t\t (line[actual][head] == '\\'' && line[actual][head+1] == '\\'' && ++apostrophe)) {\n\t\t\t\tstate = 0;\n\t\t\t\tchar * t = alloc_token(token, &head);\n\t\t\t\tif (apostrophe) head += 2;\n\t\t\t\tif (t) return t;\n\t\t\t}\n\t\t\tbreak;\n\t\tcase 2: \/\/ comment, labels, etc\n\t\t\tif (((i = look_pattern(1)) != -1) && \n\t\t\t\t(strcmp(PATTERN[i].pat[1],PATTERN[pattern_num].pat[1]) == 0)) {\n\t\t\t\t\tstate = 0;\n\t\t\t\t\thead += strlen(PATTERN[pattern_num].pat[1]) - 1;\n\t\t\t}\n\t\t\tbreak;\n\t\tcase 3: \/\/ command\n\t\t\tif ((tolower(line[actual][head]) < 'a') || (tolower(line[actual][head]) > 'z')) {\n\t\t\t\tstate = 0;\n\t\t\t\thead--;\n\t\t\t}\n\t\t\tbreak;\n\t\tcase 4: \/\/ command with arguments\n\t\t\tif (slash && (line[actual][head] != '\\0')) {\n\t\t\t\tslash = 0;\n\t\t\t\thead++;\n\t\t\t\tbreak;\n\t\t\t} else if (line[actual][head]=='\\\\') {\n\t\t\t\tslash = 1;\n\t\t\t} else if ((line[actual][head] == '{') ||\n\t\t\t\t((opt) && (line[actual][head] == '['))) {\n\t\t\t\t\tdepth++;\n\t\t\t\t\topt = 0;\n\t\t\t} else if (line[actual][head] == '}') {\n\t\t\t\tdepth--;\n\t\t\t\tif (depth == 0) { \n\t\t\t\t\topt = 1;\n\t\t\t\t\targ++;\n\t\t\t\t}\n\t\t\t\tif (((depth == 0) && (arg == PATTERN[pattern_num].arg)) ||\n\t\t\t\t\t(depth < 0) ) {\n\t\t\t\t\t\tstate = 0; \/\/ XXX not handles the last optional arg.\n\t\t\t\t}\n\t\t\t} else if (line[actual][head] == ']') depth--;\n\t\t} \/\/ case\n if (next_char(line[actual], &head)) {\n\t\t\tif (state == 5) state = 0;\n\t\t\treturn NULL;\n\t\t}\n\t}\n}\n<commit_msg>coverity#17929 Uninitialized scalar field<commit_after>#include <cstdlib>\n#include <cstring>\n#include <cstdio>\n#include <ctype.h>\n\n#include \"..\/hunspell\/csutil.hxx\"\n#include \"latexparser.hxx\"\n\n#ifndef W32\nusing namespace std;\n#endif\n\nstatic struct {\n\tconst char * pat[2];\n\tint arg;\n} PATTERN[] = {\n\t{ { \"\\\\(\", \"\\\\)\" } , 0 },\n\t{ { \"$$\", \"$$\" } , 0 },\n\t{ { \"$\", \"$\" } , 0 },\n\t{ { \"\\\\begin{math}\", \"\\\\end{math}\" } , 0 },\n\t{ { \"\\\\[\", \"\\\\]\" } , 0 },\n\t{ { \"\\\\begin{displaymath}\", \"\\\\end{displaymath}\" } , 0 },\n\t{ { \"\\\\begin{equation}\", \"\\\\end{equation}\" } , 0 },\n\t{ { \"\\\\begin{equation*}\", \"\\\\end{equation*}\" } , 0 },\n\t{ { \"\\\\cite\", NULL } , 1 },\n\t{ { \"\\\\nocite\", NULL } , 1 },\n\t{ { \"\\\\index\", NULL } , 1 },\n\t{ { \"\\\\label\", NULL } , 1 },\n\t{ { \"\\\\ref\", NULL } , 1 },\n\t{ { \"\\\\pageref\", NULL } , 1 },\n\t{ { \"\\\\parbox\", NULL } , 1 },\n\t{ { \"\\\\begin{verbatim}\", \"\\\\end{verbatim}\" } , 0 },\n\t{ { \"\\\\verb+\", \"+\" } , 0 },\n\t{ { \"\\\\verb|\", \"|\" } , 0 },\n\t{ { \"\\\\verb#\", \"#\" } , 0 },\n\t{ { \"\\\\verb*\", \"*\" } , 0 },\n\t{ { \"\\\\documentstyle\", \"\\\\begin{document}\" } , 0 },\n\t{ { \"\\\\documentclass\", \"\\\\begin{document}\" } , 0 },\n\/\/\t{ { \"\\\\documentclass\", NULL } , 1 },\n\t{ { \"\\\\usepackage\", NULL } , 1 },\n\t{ { \"\\\\includeonly\", NULL } , 1 },\n\t{ { \"\\\\include\", NULL } , 1 },\n\t{ { \"\\\\input\", NULL } , 1 },\n\t{ { \"\\\\vspace\", NULL } , 1 },\n\t{ { \"\\\\setlength\", NULL } , 2 },\n\t{ { \"\\\\addtolength\", NULL } , 2 },\n\t{ { \"\\\\settowidth\", NULL } , 2 },\n\t{ { \"\\\\rule\", NULL } , 2 },\n\t{ { \"\\\\hspace\", NULL } , 1 } ,\n\t{ { \"\\\\vspace\", NULL } , 1 } ,\n\t{ { \"\\\\\\\\[\", \"]\" } , 0 },\n\t{ { \"\\\\pagebreak[\", \"]\" } , 0 } ,\n\t{ { \"\\\\nopagebreak[\", \"]\" } , 0 } ,\n\t{ { \"\\\\enlargethispage\", NULL } , 1 } ,\n\t{ { \"\\\\begin{tabular}\", NULL } , 1 } ,\n\t{ { \"\\\\addcontentsline\", NULL } , 2 } ,\n\t{ { \"\\\\begin{thebibliography}\", NULL } , 1 } ,\n\t{ { \"\\\\bibliography\", NULL } , 1 } ,\n\t{ { \"\\\\bibliographystyle\", NULL } , 1 } ,\n\t{ { \"\\\\bibitem\", NULL } , 1 } ,\n\t{ { \"\\\\begin\", NULL } , 1 } ,\n\t{ { \"\\\\end\", NULL } , 1 } ,\n\t{ { \"\\\\pagestyle\", NULL } , 1 } ,\n\t{ { \"\\\\pagenumbering\", NULL } , 1 } ,\n\t{ { \"\\\\thispagestyle\", NULL } , 1 } ,\n\t{ { \"\\\\newtheorem\", NULL } , 2 },\n\t{ { \"\\\\newcommand\", NULL } , 2 },\n\t{ { \"\\\\renewcommand\", NULL } , 2 },\n\t{ { \"\\\\setcounter\", NULL } , 2 },\n\t{ { \"\\\\addtocounter\", NULL } , 1 },\n\t{ { \"\\\\stepcounter\", NULL } , 1 },\n\t{ { \"\\\\selectlanguage\", NULL } , 1 },\n\t{ { \"\\\\inputencoding\", NULL } , 1 },\n\t{ { \"\\\\hyphenation\", NULL } , 1 },\n\t{ { \"\\\\definecolor\", NULL } , 3 },\n\t{ { \"\\\\color\", NULL } , 1 },\n\t{ { \"\\\\textcolor\", NULL } , 1 },\n\t{ { \"\\\\pagecolor\", NULL } , 1 },\n\t{ { \"\\\\colorbox\", NULL } , 2 },\n\t{ { \"\\\\fcolorbox\", NULL } , 2 },\n\t{ { \"\\\\declaregraphicsextensions\", NULL } , 1 },\n\t{ { \"\\\\psfig\", NULL } , 1 },\n\t{ { \"\\\\url\", NULL } , 1 },\n\t{ { \"\\\\eqref\", NULL } , 1 },\n\t{ { \"\\\\vskip\", NULL } , 1 },\n\t{ { \"\\\\vglue\", NULL } , 1 },\n\t{ { \"\\'\\'\", NULL } , 1 }\n};\n\n#define PATTERN_LEN (sizeof(PATTERN) \/ sizeof(PATTERN[0]))\n\nLaTeXParser::LaTeXParser(const char * wordchars)\n : pattern_num(0)\n , depth(0)\n , arg(0)\n , opt(0)\n{\n\tinit(wordchars);\n}\n\nLaTeXParser::LaTeXParser(unsigned short * wordchars, int len)\n : pattern_num(0)\n , depth(0)\n , arg(0)\n , opt(0)\n{\n\tinit(wordchars, len);\n}\n\nLaTeXParser::~LaTeXParser() \n{\n}\n\nint LaTeXParser::look_pattern(int col)\n{\n\tfor (unsigned int i = 0; i < PATTERN_LEN; i++) {\n\t\tchar * j = line[actual] + head;\n\t\tconst char * k = PATTERN[i].pat[col];\n\t\tif (! k) continue;\n\t\twhile ((*k != '\\0') && (tolower(*j) == *k)) {\n\t\t\tj++;\n\t\t\tk++;\n\t\t}\n\t\tif (*k == '\\0') return i;\n\t}\n\treturn -1;\n}\n\n\/*\n * LaTeXParser\n *\n * state 0: not wordchar\n * state 1: wordchar\n * state 2: comments\n * state 3: commands \n * state 4: commands with arguments\n * state 5: % comment\n *\n *\/\n\n\nchar * LaTeXParser::next_token()\n{\n\tint i;\n\tint slash = 0;\n\tint apostrophe;\n\tfor (;;) {\n\t\t\/\/ fprintf(stderr,\"depth: %d, state: %d, , arg: %d, token: %s\\n\",depth,state,arg,line[actual]+head);\n\t\t\n\t\tswitch (state)\n\t\t{\n\t\tcase 0: \/\/ non word chars\n\t\t\tif ((pattern_num = look_pattern(0)) != -1) {\n\t\t\t\tif (PATTERN[pattern_num].pat[1]) {\n\t\t\t\t\tstate = 2;\n\t\t\t\t} else {\n\t\t\t\t\tstate = 4;\n\t\t\t\t\tdepth = 0;\n\t\t\t\t\targ = 0;\n\t\t\t\t\topt = 1;\n\t\t\t\t}\n\t\t\t\thead += strlen(PATTERN[pattern_num].pat[0]) - 1;\n\t\t\t} else if (line[actual][head] == '%') {\n\t\t\t\t\tstate = 5;\n\t\t\t} else if (is_wordchar(line[actual] + head)) {\n\t\t\t\tstate = 1;\n\t\t\t\ttoken = head;\n\t\t\t} else if (line[actual][head] == '\\\\') {\n\t\t\t\tif (line[actual][head + 1] == '\\\\' || \/\/ \\\\ (linebreak)\n\t\t\t\t\t(line[actual][head + 1] == '$') || \/\/ \\$ (dollar sign)\n\t\t\t\t\t(line[actual][head + 1] == '%')) { \/\/ \\% (percent)\n\t\t\t\t\thead++;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tstate = 3;\n\t\t\t} else if (line[actual][head] == '%') {\n\t\t\t\tif ((head==0) || (line[actual][head - 1] != '\\\\')) state = 5;\n\t\t\t}\n\t\t\tbreak;\n\t\tcase 1: \/\/ wordchar\n\t\t\tapostrophe = 0;\n\t\t\tif (! is_wordchar(line[actual] + head) ||\n\t\t\t (line[actual][head] == '\\'' && line[actual][head+1] == '\\'' && ++apostrophe)) {\n\t\t\t\tstate = 0;\n\t\t\t\tchar * t = alloc_token(token, &head);\n\t\t\t\tif (apostrophe) head += 2;\n\t\t\t\tif (t) return t;\n\t\t\t}\n\t\t\tbreak;\n\t\tcase 2: \/\/ comment, labels, etc\n\t\t\tif (((i = look_pattern(1)) != -1) && \n\t\t\t\t(strcmp(PATTERN[i].pat[1],PATTERN[pattern_num].pat[1]) == 0)) {\n\t\t\t\t\tstate = 0;\n\t\t\t\t\thead += strlen(PATTERN[pattern_num].pat[1]) - 1;\n\t\t\t}\n\t\t\tbreak;\n\t\tcase 3: \/\/ command\n\t\t\tif ((tolower(line[actual][head]) < 'a') || (tolower(line[actual][head]) > 'z')) {\n\t\t\t\tstate = 0;\n\t\t\t\thead--;\n\t\t\t}\n\t\t\tbreak;\n\t\tcase 4: \/\/ command with arguments\n\t\t\tif (slash && (line[actual][head] != '\\0')) {\n\t\t\t\tslash = 0;\n\t\t\t\thead++;\n\t\t\t\tbreak;\n\t\t\t} else if (line[actual][head]=='\\\\') {\n\t\t\t\tslash = 1;\n\t\t\t} else if ((line[actual][head] == '{') ||\n\t\t\t\t((opt) && (line[actual][head] == '['))) {\n\t\t\t\t\tdepth++;\n\t\t\t\t\topt = 0;\n\t\t\t} else if (line[actual][head] == '}') {\n\t\t\t\tdepth--;\n\t\t\t\tif (depth == 0) { \n\t\t\t\t\topt = 1;\n\t\t\t\t\targ++;\n\t\t\t\t}\n\t\t\t\tif (((depth == 0) && (arg == PATTERN[pattern_num].arg)) ||\n\t\t\t\t\t(depth < 0) ) {\n\t\t\t\t\t\tstate = 0; \/\/ XXX not handles the last optional arg.\n\t\t\t\t}\n\t\t\t} else if (line[actual][head] == ']') depth--;\n\t\t} \/\/ case\n if (next_char(line[actual], &head)) {\n\t\t\tif (state == 5) state = 0;\n\t\t\treturn NULL;\n\t\t}\n\t}\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"surfacefeaturesextractor.h\"\n#include <vtkDoubleArray.h>\n#include <sstream>\n#include <vtkObjectFactory.h>\n\n#if !defined(M_PI)\n#define M_PI 3.14159265358979323846264338327950288 \/* pi *\/\n#endif\n\n\nvtkStandardNewMacro(SurfaceFeaturesExtractor);\n\n\/**\n* Constructor SurfaceFeaturesExtractor()\n*\/\nSurfaceFeaturesExtractor::SurfaceFeaturesExtractor(){\n\tthis->inputSurface = vtkSmartPointer<vtkPolyData>::New();\n\tthis->outputSurface = vtkSmartPointer<vtkPolyData>::New();\n\n\tthis->intermediateSurface = vtkSmartPointer<vtkPolyData>::New();\n}\n\n\/**\n* Destructor SurfaceFeaturesExtractor()\n*\/\nSurfaceFeaturesExtractor::~SurfaceFeaturesExtractor(){}\n\n\/**\n* Function SetInput() for SurfaceFeaturesExtractor\n*\/\nvoid SurfaceFeaturesExtractor::SetInput(vtkSmartPointer<vtkPolyData> input, std::vector< vtkSmartPointer<vtkPolyData> > list, std::vector<std::string> landmarkFile)\n{\n\tthis->meanShapesList = list;\n\tthis->inputSurface = input;\n\tthis->landmarkFile = landmarkFile;\n}\n\n\/**\n * Function init_output() for SurfaceFeaturesExtractor\n *\/\nvoid SurfaceFeaturesExtractor::init_output()\n{\n\tthis->intermediateSurface = this->inputSurface;\n\tthis->outputSurface = this->inputSurface;\n}\n\n\/** \n * Function compute_normals()\n *\/\nvoid SurfaceFeaturesExtractor::compute_normals()\n{\n\tvtkSmartPointer<vtkPolyDataNormals> NormalFilter = vtkSmartPointer<vtkPolyDataNormals>::New();\n\tNormalFilter->SetInputData(this->intermediateSurface);\n\n\tNormalFilter->ComputePointNormalsOn();\n NormalFilter->ComputeCellNormalsOff();\n NormalFilter->SetFlipNormals(0);\n NormalFilter->SplittingOff();\n\tNormalFilter->FlipNormalsOff();\n\tNormalFilter->ConsistencyOff();\n\n\tNormalFilter->Update();\n\tthis->intermediateSurface = NormalFilter->GetOutput();\n}\n\n\/** \n * Function compute_positions()\n *\/\nvoid SurfaceFeaturesExtractor::compute_positions()\n{\n std::string name = \"Position\";\n int nbPoints = this->intermediateSurface->GetNumberOfPoints();\n\n\tvtkSmartPointer<vtkFloatArray> position = vtkSmartPointer<vtkFloatArray>::New();\n\tposition->SetNumberOfComponents(3);\n\tposition->SetName(name.c_str());\n\n\tfor(int i=0; i<nbPoints; i++)\n\t{\n\t\tdouble* p = new double[3];\n\t\tp = this->intermediateSurface->GetPoint(i);\n\n\t\tposition->InsertNextTuple3(p[0],p[1],p[2]);\n\n\t}\n\t\n\tthis->intermediateSurface->GetPointData()->SetActiveVectors(name.c_str());\n\tthis->intermediateSurface->GetPointData()->SetVectors(position);\n\n}\n\n\/** \n * Function compute_distances()\n *\/\nvoid SurfaceFeaturesExtractor::compute_distances()\n{\n\tint nbPoints = this->intermediateSurface->GetNumberOfPoints();\n\n\t\/\/ Load each mean groupe shape & create labels\n\tstd::vector<std::string> meanDistLabels;\n\tfor (size_t k=0; k<this->meanShapesList.size(); k++)\n\t{\n\t\tstd::ostringstream k_temp;\n \tk_temp << k;\n \tstd::string k_char = k_temp.str();\n\t\t\/\/ std::string k_char = static_cast<std::ostringstream*>( &( std::ostringstream() << k) )->str();\n\t\tmeanDistLabels.push_back(\"distanceGroup\"+k_char);\n\t}\n\t\/\/for (int k=0; k<this->meanShapesList.size(); k++) \n\t\/\/\tstd::cout<<meanDistLabels[k]<<std::endl;\n\n\tfor(size_t k=0; k<meanShapesList.size(); k++)\n\t{\n\t\tvtkSmartPointer<vtkFloatArray> meanDistance = vtkSmartPointer<vtkFloatArray>::New() ;\n\t\tmeanDistance->SetName(meanDistLabels[k].c_str());\n\n\t\tfor (int i=0; i<nbPoints; i++)\n\t\t{\n\t\t\tdouble* p1 = new double[3];\n\t\t\tp1 = this->intermediateSurface->GetPoint(i);\n\t\t\t\n\t\t\tdouble* p2 = new double[3];\n\t\t\tp2 = meanShapesList[k]->GetPoint(i);\n\n\t\t\tdouble dist = sqrt( (p1[0]-p2[0])*(p1[0]-p2[0]) + (p1[1]-p2[1])*(p1[1]-p2[1]) + (p1[2]-p2[2])*(p1[2]-p2[2]) );\n\n\t\t\tmeanDistance->InsertNextTuple1(dist);\n\n\t\t\tthis->intermediateSurface->GetPointData()->SetActiveScalars(meanDistLabels[k].c_str());\n\t\t\tthis->intermediateSurface->GetPointData()->SetScalars(meanDistance);\n\t\t\t\n\t\t}\n\t}\n}\n\n\nvoid SurfaceFeaturesExtractor::compute_maxcurvatures()\t\t\/\/ Kappa2\n{\n\tvtkSmartPointer<vtkCurvatures> curvaturesFilter = vtkSmartPointer<vtkCurvatures>::New();\n\n\tcurvaturesFilter->SetInputDataObject(this->intermediateSurface);\n\tcurvaturesFilter->SetCurvatureTypeToMaximum();\n\tcurvaturesFilter->Update();\n\n\tthis->intermediateSurface = curvaturesFilter->GetOutput();\n}\nvoid SurfaceFeaturesExtractor::compute_mincurvatures()\t\t\/\/ Kappa1\n{\n\tvtkSmartPointer<vtkCurvatures> curvaturesFilter = vtkSmartPointer<vtkCurvatures>::New();\n\n\tcurvaturesFilter->SetInputDataObject(this->intermediateSurface);\n\tcurvaturesFilter->SetCurvatureTypeToMinimum();\n\tcurvaturesFilter->Update();\n\n\tthis->intermediateSurface = curvaturesFilter->GetOutput();\t\n}\nvoid SurfaceFeaturesExtractor::compute_gaussiancurvatures()\t\/\/ G\n{\n\tvtkSmartPointer<vtkCurvatures> curvaturesFilter = vtkSmartPointer<vtkCurvatures>::New();\n\n\tcurvaturesFilter->SetInputDataObject(this->intermediateSurface);\n\tcurvaturesFilter->SetCurvatureTypeToGaussian();\n\tcurvaturesFilter->Update();\n\n\tthis->intermediateSurface = curvaturesFilter->GetOutput();\n}\nvoid SurfaceFeaturesExtractor::compute_meancurvatures()\t\t\/\/ H\n{\n\tvtkSmartPointer<vtkCurvatures> curvaturesFilter = vtkSmartPointer<vtkCurvatures>::New();\n\n\tcurvaturesFilter->SetInputDataObject(this->intermediateSurface);\n\tcurvaturesFilter->SetCurvatureTypeToMean();\n\tcurvaturesFilter->Update();\n\n\tthis->intermediateSurface = curvaturesFilter->GetOutput();\n}\n\nvoid SurfaceFeaturesExtractor::compute_shapeindex()\t\t\t\/\/ S\n{\n\t\/\/ std::cout<<\" :: Function compute_shapeindex\"<<std::endl;\n\n\tint nbPoints = this->intermediateSurface->GetNumberOfPoints();\n\n\tvtkSmartPointer<vtkFloatArray> shapeIndexArray = vtkSmartPointer<vtkFloatArray>::New() ;\n\n\t\/\/ vtkDataArray* minCurvArray = this->intermediateSurface->GetPointData()->GetScalars(\"Minimum_Curvature\");\n\t\/\/ vtkDataArray* maxCurvArray = this->intermediateSurface->GetPointData()->GetScalars(\"Maximum_Curvature\");\n\n\tvtkSmartPointer<vtkDataArray> minCurvArray = this->intermediateSurface->GetPointData()->GetScalars(\"Minimum_Curvature\");\n\tvtkSmartPointer<vtkDataArray> maxCurvArray = this->intermediateSurface->GetPointData()->GetScalars(\"Maximum_Curvature\");\n\n\tshapeIndexArray->SetName(\"Shape_Index\");\n\n\tfor (int i=0; i<nbPoints; i++)\n\t{\n\t\tdouble k1 = minCurvArray->GetTuple1(i);\n\t\tdouble k2 = maxCurvArray->GetTuple1(i);\n\t\t\n\t\tdouble value = (2 \/ M_PI) * (atan( (k2 + k1) \/ (k2 - k1) ) );\n\t\tif( value != value )\n \tvalue = 0;\n\n\t\tshapeIndexArray->InsertNextTuple1(value);\n\t}\n\n\tthis->intermediateSurface->GetPointData()->SetActiveScalars(\"Shape_Index\");\n\tthis->intermediateSurface->GetPointData()->SetScalars(shapeIndexArray);\n}\n\nvoid SurfaceFeaturesExtractor::compute_curvedness()\t\t\t\/\/ C\n{\n\t\/\/ std::cout<<\" :: Function compute_curvedness\"<<std::endl;\n\n\tint nbPoints = this->intermediateSurface->GetNumberOfPoints();\n\n\tvtkSmartPointer<vtkFloatArray> curvednessArray = vtkSmartPointer<vtkFloatArray>::New() ;\n\n\t\/\/ vtkDataArray* minCurvArray = this->intermediateSurface->GetPointData()->GetScalars(\"Minimum_Curvature\");\n\t\/\/ vtkDataArray* maxCurvArray = this->intermediateSurface->GetPointData()->GetScalars(\"Maximum_Curvature\");\n\n\tvtkSmartPointer<vtkDataArray> minCurvArray = this->intermediateSurface->GetPointData()->GetScalars(\"Minimum_Curvature\");\n\tvtkSmartPointer<vtkDataArray> maxCurvArray = this->intermediateSurface->GetPointData()->GetScalars(\"Maximum_Curvature\");\n\n\tcurvednessArray->SetName(\"Curvedness\");\n\n\tfor (int i=0; i<nbPoints; i++)\n\t{\n\t\tdouble k1 = minCurvArray->GetTuple1(i);\n\t\tdouble k2 = maxCurvArray->GetTuple1(i);\n\t\t\n\t\tdouble value = sqrt( (pow(k1, 2) + pow(k2, 2) ) \/ 2);\n\n\t\tcurvednessArray->InsertNextTuple1(value);\n\n\t\tthis->intermediateSurface->GetPointData()->SetActiveScalars(\"Curvedness\");\n\t\tthis->intermediateSurface->GetPointData()->SetScalars(curvednessArray);\n\t}\n\n}\n\nvoid SurfaceFeaturesExtractor::scalar_indexPoint()\n{\n\tint nbPoints = this->intermediateSurface->GetNumberOfPoints();\n\n\tvtkSmartPointer<vtkFloatArray> indexPointArray = vtkSmartPointer<vtkFloatArray>::New() ;\n\n\tindexPointArray->SetName(\"Index_Points\");\n\n\tfor (int i=0; i<nbPoints; i++)\n\t{\n\t\tindexPointArray->InsertNextTuple1(i);\n\n\t\tthis->intermediateSurface->GetPointData()->SetActiveScalars(\"Index_Points\");\n\t\tthis->intermediateSurface->GetPointData()->SetScalars(indexPointArray);\n\t}\n}\n\nvoid SurfaceFeaturesExtractor::store_landmarks_vtk()\n{\n\t\/\/std::cout << \" Functions store landmarks_vtk \" << std::endl;\n\n\t\/\/ Build a locator\n\tvtkSmartPointer<vtkPointLocator> pointLocator = vtkPointLocator::New();\n\tpointLocator->SetDataSet(this->intermediateSurface);\n\tpointLocator->BuildLocator();\n\n\n\t\/\/ ---------- Reading FCSV file ----------\n\n\t#define NB_LINES 250\n\t#define NB_WORDS 250\n\n\t\/\/ Get the Surface filename from the command line\n\tstd::fstream fcsvfile(this->landmarkFile[0].c_str());\n\tstd::string line, mot;\n\tstd::string words[NB_LINES][NB_WORDS]; \/\/ !!!! WARNING DEFINE AND TO PROTECT IF SUPERIOR TO 20\n\tint i,j;\n\tint* landmarkPids; \n\tint NbLandmarks;\n\n\tif(fcsvfile)\n\t{\n\t\tgetline(fcsvfile, line);\n\t\tfcsvfile>>mot;\n\t\twhile(mot==\"#\")\n\t\t{\n\t\t\tif(getline(fcsvfile, line))\n\t\t\t\tfcsvfile>>mot;\n\t\t\telse\n\t\t\t\tmot=\"#\";\n\t\t}\n\n\t\ti=0;\n\t\tdo\n\t\t{\n\t\t\tstd::size_t pos_end, pos1;\n\t\t\tj=0;\n\t\t\tdo\n\t\t\t{\n\t\t\t\tstd::size_t pos0 = 0;\n\t\t\t\tpos1 = mot.find(',');\n\t\t\t\tpos_end = mot.find(\",,\");\n\t\t\t\twords[i][j] = mot.substr(pos0, pos1-pos0);\n\t\t\t\tmot = mot.substr(pos1+1);\n\t\t\t\tj++;\n\t\t\t}\n\t\t\twhile(pos1+1<pos_end);\n\t\t\ti++;\n\t\t}\n\t\twhile(fcsvfile>>mot);\n\n\t\tNbLandmarks = i;\n\t\tlandmarkPids = new int[NbLandmarks]; \n\n\t\tfor (int i = 0; i < NbLandmarks; ++i)\n\t\t{\n\t\t\tdouble x = atof(words[i][1].c_str());\n\t\t\tdouble y = atof(words[i][2].c_str());\n\t\t\tdouble z = atof(words[i][3].c_str());\n \n \/\/ Find closest point\n vtkIdType ptId;\n double p[] = {0.0, 0.0, 0.0};\n p[0] = x; p[1] = y; p[2] = z;\n ptId = pointLocator->FindClosestPoint(p);\n landmarkPids[i] = ptId;\n\n\t\t\/\/ std::cout << \"landmark \" << i << \" position \" << x << \",\" << y << \",\" << z << \" and the corresponding Pid is \" << landmarkPids[i] << std::endl;\n\t\t}\n\t}\n\telse\n\t\tstd::cout<<\"Error !\";\n\n\n\t\/\/ ---------- Encode landmarks in FCSV file ----------\n\tvtkSmartPointer<vtkDoubleArray> landmarksArray = vtkSmartPointer<vtkDoubleArray>::New();\n\tlandmarksArray->SetName(\"Landmarks\");\n\tlandmarksArray->SetNumberOfComponents(1);\n\n\tfor(int ID = 0; ID < this->intermediateSurface->GetNumberOfPoints(); ID++)\n\t{\n\t\tdouble exists = 0.0;\n\t\tfor (int i = 0; i < NbLandmarks; ++i)\n\t\t{\n\t\t\tdouble diff = landmarkPids[i] - ID;\n\t\t\tif (diff == 0)\n\t\t\t{\n\t\t\t\texists = i+1;\n\t\t\t\t\/\/std::cout << \"Landmark ID \" << exists << std::endl;\n\t\t\t\tbreak;\n\t\t\t} \n\t\t}\n\t\tlandmarksArray->InsertNextValue(exists);\n\t}\n\tlandmarksArray->Resize(this->intermediateSurface->GetNumberOfPoints());\n\tthis->intermediateSurface->GetPointData()->AddArray(landmarksArray);\n\n\t\/\/delete[] landmarkPids;\n\n}\n\n\n\/**\n * Function Update()\n *\/\nvoid SurfaceFeaturesExtractor::Update()\n{\n\tthis->init_output();\n\n\t\/\/ Compute normal for each vertex\n\tthis->compute_normals();\n\n\t\/\/ Compute position of each point\n\tthis->compute_positions();\n\n\t\/\/ Compute distance to each mean groups\n\tif (this->meanShapesList.size() > 0)\n\t\tthis->compute_distances();\n\n\t\/\/ Compute curvatures at each point\n\tthis->compute_maxcurvatures();\n\tthis->compute_mincurvatures();\n\tthis->compute_gaussiancurvatures();\n\tthis->compute_meancurvatures();\n\n\t\/\/ Shape Index and Curvedness\n\tthis->compute_shapeindex();\n\tthis->compute_curvedness();\n\t\n\n\t\/\/ this->scalar_indexPoint();\n\n\tif (this->landmarkFile.size() == 1)\n\t\tthis->store_landmarks_vtk();\n\n\tthis->outputSurface = this->intermediateSurface;\n}\n\n\/**\n * Function GetOutput()\n *\/\nvtkSmartPointer<vtkPolyData> SurfaceFeaturesExtractor::GetOutput()\n{\n\treturn this->outputSurface;\n}\n\n\n<commit_msg>COMP: Fix -Wmaybe-uninitialized warnings in SurfaceFeaturesExtractor CLI<commit_after>#include \"surfacefeaturesextractor.h\"\n#include <vtkDoubleArray.h>\n#include <sstream>\n#include <vtkObjectFactory.h>\n\n#if !defined(M_PI)\n#define M_PI 3.14159265358979323846264338327950288 \/* pi *\/\n#endif\n\n\nvtkStandardNewMacro(SurfaceFeaturesExtractor);\n\n\/**\n* Constructor SurfaceFeaturesExtractor()\n*\/\nSurfaceFeaturesExtractor::SurfaceFeaturesExtractor(){\n\tthis->inputSurface = vtkSmartPointer<vtkPolyData>::New();\n\tthis->outputSurface = vtkSmartPointer<vtkPolyData>::New();\n\n\tthis->intermediateSurface = vtkSmartPointer<vtkPolyData>::New();\n}\n\n\/**\n* Destructor SurfaceFeaturesExtractor()\n*\/\nSurfaceFeaturesExtractor::~SurfaceFeaturesExtractor(){}\n\n\/**\n* Function SetInput() for SurfaceFeaturesExtractor\n*\/\nvoid SurfaceFeaturesExtractor::SetInput(vtkSmartPointer<vtkPolyData> input, std::vector< vtkSmartPointer<vtkPolyData> > list, std::vector<std::string> landmarkFile)\n{\n\tthis->meanShapesList = list;\n\tthis->inputSurface = input;\n\tthis->landmarkFile = landmarkFile;\n}\n\n\/**\n * Function init_output() for SurfaceFeaturesExtractor\n *\/\nvoid SurfaceFeaturesExtractor::init_output()\n{\n\tthis->intermediateSurface = this->inputSurface;\n\tthis->outputSurface = this->inputSurface;\n}\n\n\/** \n * Function compute_normals()\n *\/\nvoid SurfaceFeaturesExtractor::compute_normals()\n{\n\tvtkSmartPointer<vtkPolyDataNormals> NormalFilter = vtkSmartPointer<vtkPolyDataNormals>::New();\n\tNormalFilter->SetInputData(this->intermediateSurface);\n\n\tNormalFilter->ComputePointNormalsOn();\n NormalFilter->ComputeCellNormalsOff();\n NormalFilter->SetFlipNormals(0);\n NormalFilter->SplittingOff();\n\tNormalFilter->FlipNormalsOff();\n\tNormalFilter->ConsistencyOff();\n\n\tNormalFilter->Update();\n\tthis->intermediateSurface = NormalFilter->GetOutput();\n}\n\n\/** \n * Function compute_positions()\n *\/\nvoid SurfaceFeaturesExtractor::compute_positions()\n{\n std::string name = \"Position\";\n int nbPoints = this->intermediateSurface->GetNumberOfPoints();\n\n\tvtkSmartPointer<vtkFloatArray> position = vtkSmartPointer<vtkFloatArray>::New();\n\tposition->SetNumberOfComponents(3);\n\tposition->SetName(name.c_str());\n\n\tfor(int i=0; i<nbPoints; i++)\n\t{\n\t\tdouble* p = new double[3];\n\t\tp = this->intermediateSurface->GetPoint(i);\n\n\t\tposition->InsertNextTuple3(p[0],p[1],p[2]);\n\n\t}\n\t\n\tthis->intermediateSurface->GetPointData()->SetActiveVectors(name.c_str());\n\tthis->intermediateSurface->GetPointData()->SetVectors(position);\n\n}\n\n\/** \n * Function compute_distances()\n *\/\nvoid SurfaceFeaturesExtractor::compute_distances()\n{\n\tint nbPoints = this->intermediateSurface->GetNumberOfPoints();\n\n\t\/\/ Load each mean groupe shape & create labels\n\tstd::vector<std::string> meanDistLabels;\n\tfor (size_t k=0; k<this->meanShapesList.size(); k++)\n\t{\n\t\tstd::ostringstream k_temp;\n \tk_temp << k;\n \tstd::string k_char = k_temp.str();\n\t\t\/\/ std::string k_char = static_cast<std::ostringstream*>( &( std::ostringstream() << k) )->str();\n\t\tmeanDistLabels.push_back(\"distanceGroup\"+k_char);\n\t}\n\t\/\/for (int k=0; k<this->meanShapesList.size(); k++) \n\t\/\/\tstd::cout<<meanDistLabels[k]<<std::endl;\n\n\tfor(size_t k=0; k<meanShapesList.size(); k++)\n\t{\n\t\tvtkSmartPointer<vtkFloatArray> meanDistance = vtkSmartPointer<vtkFloatArray>::New() ;\n\t\tmeanDistance->SetName(meanDistLabels[k].c_str());\n\n\t\tfor (int i=0; i<nbPoints; i++)\n\t\t{\n\t\t\tdouble* p1 = new double[3];\n\t\t\tp1 = this->intermediateSurface->GetPoint(i);\n\t\t\t\n\t\t\tdouble* p2 = new double[3];\n\t\t\tp2 = meanShapesList[k]->GetPoint(i);\n\n\t\t\tdouble dist = sqrt( (p1[0]-p2[0])*(p1[0]-p2[0]) + (p1[1]-p2[1])*(p1[1]-p2[1]) + (p1[2]-p2[2])*(p1[2]-p2[2]) );\n\n\t\t\tmeanDistance->InsertNextTuple1(dist);\n\n\t\t\tthis->intermediateSurface->GetPointData()->SetActiveScalars(meanDistLabels[k].c_str());\n\t\t\tthis->intermediateSurface->GetPointData()->SetScalars(meanDistance);\n\t\t\t\n\t\t}\n\t}\n}\n\n\nvoid SurfaceFeaturesExtractor::compute_maxcurvatures()\t\t\/\/ Kappa2\n{\n\tvtkSmartPointer<vtkCurvatures> curvaturesFilter = vtkSmartPointer<vtkCurvatures>::New();\n\n\tcurvaturesFilter->SetInputDataObject(this->intermediateSurface);\n\tcurvaturesFilter->SetCurvatureTypeToMaximum();\n\tcurvaturesFilter->Update();\n\n\tthis->intermediateSurface = curvaturesFilter->GetOutput();\n}\nvoid SurfaceFeaturesExtractor::compute_mincurvatures()\t\t\/\/ Kappa1\n{\n\tvtkSmartPointer<vtkCurvatures> curvaturesFilter = vtkSmartPointer<vtkCurvatures>::New();\n\n\tcurvaturesFilter->SetInputDataObject(this->intermediateSurface);\n\tcurvaturesFilter->SetCurvatureTypeToMinimum();\n\tcurvaturesFilter->Update();\n\n\tthis->intermediateSurface = curvaturesFilter->GetOutput();\t\n}\nvoid SurfaceFeaturesExtractor::compute_gaussiancurvatures()\t\/\/ G\n{\n\tvtkSmartPointer<vtkCurvatures> curvaturesFilter = vtkSmartPointer<vtkCurvatures>::New();\n\n\tcurvaturesFilter->SetInputDataObject(this->intermediateSurface);\n\tcurvaturesFilter->SetCurvatureTypeToGaussian();\n\tcurvaturesFilter->Update();\n\n\tthis->intermediateSurface = curvaturesFilter->GetOutput();\n}\nvoid SurfaceFeaturesExtractor::compute_meancurvatures()\t\t\/\/ H\n{\n\tvtkSmartPointer<vtkCurvatures> curvaturesFilter = vtkSmartPointer<vtkCurvatures>::New();\n\n\tcurvaturesFilter->SetInputDataObject(this->intermediateSurface);\n\tcurvaturesFilter->SetCurvatureTypeToMean();\n\tcurvaturesFilter->Update();\n\n\tthis->intermediateSurface = curvaturesFilter->GetOutput();\n}\n\nvoid SurfaceFeaturesExtractor::compute_shapeindex()\t\t\t\/\/ S\n{\n\t\/\/ std::cout<<\" :: Function compute_shapeindex\"<<std::endl;\n\n\tint nbPoints = this->intermediateSurface->GetNumberOfPoints();\n\n\tvtkSmartPointer<vtkFloatArray> shapeIndexArray = vtkSmartPointer<vtkFloatArray>::New() ;\n\n\t\/\/ vtkDataArray* minCurvArray = this->intermediateSurface->GetPointData()->GetScalars(\"Minimum_Curvature\");\n\t\/\/ vtkDataArray* maxCurvArray = this->intermediateSurface->GetPointData()->GetScalars(\"Maximum_Curvature\");\n\n\tvtkSmartPointer<vtkDataArray> minCurvArray = this->intermediateSurface->GetPointData()->GetScalars(\"Minimum_Curvature\");\n\tvtkSmartPointer<vtkDataArray> maxCurvArray = this->intermediateSurface->GetPointData()->GetScalars(\"Maximum_Curvature\");\n\n\tshapeIndexArray->SetName(\"Shape_Index\");\n\n\tfor (int i=0; i<nbPoints; i++)\n\t{\n\t\tdouble k1 = minCurvArray->GetTuple1(i);\n\t\tdouble k2 = maxCurvArray->GetTuple1(i);\n\t\t\n\t\tdouble value = (2 \/ M_PI) * (atan( (k2 + k1) \/ (k2 - k1) ) );\n\t\tif( value != value )\n \tvalue = 0;\n\n\t\tshapeIndexArray->InsertNextTuple1(value);\n\t}\n\n\tthis->intermediateSurface->GetPointData()->SetActiveScalars(\"Shape_Index\");\n\tthis->intermediateSurface->GetPointData()->SetScalars(shapeIndexArray);\n}\n\nvoid SurfaceFeaturesExtractor::compute_curvedness()\t\t\t\/\/ C\n{\n\t\/\/ std::cout<<\" :: Function compute_curvedness\"<<std::endl;\n\n\tint nbPoints = this->intermediateSurface->GetNumberOfPoints();\n\n\tvtkSmartPointer<vtkFloatArray> curvednessArray = vtkSmartPointer<vtkFloatArray>::New() ;\n\n\t\/\/ vtkDataArray* minCurvArray = this->intermediateSurface->GetPointData()->GetScalars(\"Minimum_Curvature\");\n\t\/\/ vtkDataArray* maxCurvArray = this->intermediateSurface->GetPointData()->GetScalars(\"Maximum_Curvature\");\n\n\tvtkSmartPointer<vtkDataArray> minCurvArray = this->intermediateSurface->GetPointData()->GetScalars(\"Minimum_Curvature\");\n\tvtkSmartPointer<vtkDataArray> maxCurvArray = this->intermediateSurface->GetPointData()->GetScalars(\"Maximum_Curvature\");\n\n\tcurvednessArray->SetName(\"Curvedness\");\n\n\tfor (int i=0; i<nbPoints; i++)\n\t{\n\t\tdouble k1 = minCurvArray->GetTuple1(i);\n\t\tdouble k2 = maxCurvArray->GetTuple1(i);\n\t\t\n\t\tdouble value = sqrt( (pow(k1, 2) + pow(k2, 2) ) \/ 2);\n\n\t\tcurvednessArray->InsertNextTuple1(value);\n\n\t\tthis->intermediateSurface->GetPointData()->SetActiveScalars(\"Curvedness\");\n\t\tthis->intermediateSurface->GetPointData()->SetScalars(curvednessArray);\n\t}\n\n}\n\nvoid SurfaceFeaturesExtractor::scalar_indexPoint()\n{\n\tint nbPoints = this->intermediateSurface->GetNumberOfPoints();\n\n\tvtkSmartPointer<vtkFloatArray> indexPointArray = vtkSmartPointer<vtkFloatArray>::New() ;\n\n\tindexPointArray->SetName(\"Index_Points\");\n\n\tfor (int i=0; i<nbPoints; i++)\n\t{\n\t\tindexPointArray->InsertNextTuple1(i);\n\n\t\tthis->intermediateSurface->GetPointData()->SetActiveScalars(\"Index_Points\");\n\t\tthis->intermediateSurface->GetPointData()->SetScalars(indexPointArray);\n\t}\n}\n\nvoid SurfaceFeaturesExtractor::store_landmarks_vtk()\n{\n\t\/\/std::cout << \" Functions store landmarks_vtk \" << std::endl;\n\n\t\/\/ Build a locator\n\tvtkSmartPointer<vtkPointLocator> pointLocator = vtkPointLocator::New();\n\tpointLocator->SetDataSet(this->intermediateSurface);\n\tpointLocator->BuildLocator();\n\n\n\t\/\/ ---------- Reading FCSV file ----------\n\n\t#define NB_LINES 250\n\t#define NB_WORDS 250\n\n\t\/\/ Get the Surface filename from the command line\n\tstd::fstream fcsvfile(this->landmarkFile[0].c_str());\n\tstd::string line, mot;\n\tstd::string words[NB_LINES][NB_WORDS]; \/\/ !!!! WARNING DEFINE AND TO PROTECT IF SUPERIOR TO 20\n\tint i,j;\n\tint* landmarkPids = NULL;\n\tint NbLandmarks = 0;\n\n\tif(fcsvfile)\n\t{\n\t\tgetline(fcsvfile, line);\n\t\tfcsvfile>>mot;\n\t\twhile(mot==\"#\")\n\t\t{\n\t\t\tif(getline(fcsvfile, line))\n\t\t\t\tfcsvfile>>mot;\n\t\t\telse\n\t\t\t\tmot=\"#\";\n\t\t}\n\n\t\ti=0;\n\t\tdo\n\t\t{\n\t\t\tstd::size_t pos_end, pos1;\n\t\t\tj=0;\n\t\t\tdo\n\t\t\t{\n\t\t\t\tstd::size_t pos0 = 0;\n\t\t\t\tpos1 = mot.find(',');\n\t\t\t\tpos_end = mot.find(\",,\");\n\t\t\t\twords[i][j] = mot.substr(pos0, pos1-pos0);\n\t\t\t\tmot = mot.substr(pos1+1);\n\t\t\t\tj++;\n\t\t\t}\n\t\t\twhile(pos1+1<pos_end);\n\t\t\ti++;\n\t\t}\n\t\twhile(fcsvfile>>mot);\n\n\t\tNbLandmarks = i;\n\t\tlandmarkPids = new int[NbLandmarks]; \n\n\t\tfor (int i = 0; i < NbLandmarks; ++i)\n\t\t{\n\t\t\tdouble x = atof(words[i][1].c_str());\n\t\t\tdouble y = atof(words[i][2].c_str());\n\t\t\tdouble z = atof(words[i][3].c_str());\n \n \/\/ Find closest point\n vtkIdType ptId;\n double p[] = {0.0, 0.0, 0.0};\n p[0] = x; p[1] = y; p[2] = z;\n ptId = pointLocator->FindClosestPoint(p);\n landmarkPids[i] = ptId;\n\n\t\t\/\/ std::cout << \"landmark \" << i << \" position \" << x << \",\" << y << \",\" << z << \" and the corresponding Pid is \" << landmarkPids[i] << std::endl;\n\t\t}\n\t}\n\telse\n\t\tstd::cout<<\"Error !\";\n\n\n\t\/\/ ---------- Encode landmarks in FCSV file ----------\n\tvtkSmartPointer<vtkDoubleArray> landmarksArray = vtkSmartPointer<vtkDoubleArray>::New();\n\tlandmarksArray->SetName(\"Landmarks\");\n\tlandmarksArray->SetNumberOfComponents(1);\n\n\tfor(int ID = 0; ID < this->intermediateSurface->GetNumberOfPoints(); ID++)\n\t{\n\t\tdouble exists = 0.0;\n\t\tfor (int i = 0; i < NbLandmarks; ++i)\n\t\t{\n\t\t\tdouble diff = landmarkPids[i] - ID;\n\t\t\tif (diff == 0)\n\t\t\t{\n\t\t\t\texists = i+1;\n\t\t\t\t\/\/std::cout << \"Landmark ID \" << exists << std::endl;\n\t\t\t\tbreak;\n\t\t\t} \n\t\t}\n\t\tlandmarksArray->InsertNextValue(exists);\n\t}\n\tlandmarksArray->Resize(this->intermediateSurface->GetNumberOfPoints());\n\tthis->intermediateSurface->GetPointData()->AddArray(landmarksArray);\n\n\t\/\/delete[] landmarkPids;\n\n}\n\n\n\/**\n * Function Update()\n *\/\nvoid SurfaceFeaturesExtractor::Update()\n{\n\tthis->init_output();\n\n\t\/\/ Compute normal for each vertex\n\tthis->compute_normals();\n\n\t\/\/ Compute position of each point\n\tthis->compute_positions();\n\n\t\/\/ Compute distance to each mean groups\n\tif (this->meanShapesList.size() > 0)\n\t\tthis->compute_distances();\n\n\t\/\/ Compute curvatures at each point\n\tthis->compute_maxcurvatures();\n\tthis->compute_mincurvatures();\n\tthis->compute_gaussiancurvatures();\n\tthis->compute_meancurvatures();\n\n\t\/\/ Shape Index and Curvedness\n\tthis->compute_shapeindex();\n\tthis->compute_curvedness();\n\t\n\n\t\/\/ this->scalar_indexPoint();\n\n\tif (this->landmarkFile.size() == 1)\n\t\tthis->store_landmarks_vtk();\n\n\tthis->outputSurface = this->intermediateSurface;\n}\n\n\/**\n * Function GetOutput()\n *\/\nvtkSmartPointer<vtkPolyData> SurfaceFeaturesExtractor::GetOutput()\n{\n\treturn this->outputSurface;\n}\n\n\n<|endoftext|>"} {"text":"<commit_before>\/******************************************************************************\n * The MIT License (MIT)\n *\n * Copyright (c) 2016-2018 Baldur Karlsson\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n ******************************************************************************\/\n\n#include <execinfo.h>\n#include <stdio.h>\n#include <string.h>\n#include <map>\n#include <vector>\n#include \"os\/os_specific.h\"\n\nvoid *renderdocBase = NULL;\nvoid *renderdocEnd = NULL;\n\nclass LinuxCallstack : public Callstack::Stackwalk\n{\npublic:\n LinuxCallstack()\n {\n RDCEraseEl(addrs);\n numLevels = 0;\n Collect();\n }\n LinuxCallstack(uint64_t *calls, size_t num) { Set(calls, num); }\n ~LinuxCallstack() {}\n void Set(uint64_t *calls, size_t num)\n {\n numLevels = num;\n for(int i = 0; i < numLevels; i++)\n addrs[i] = calls[i];\n }\n\n size_t NumLevels() const { return size_t(numLevels); }\n const uint64_t *GetAddrs() const { return addrs; }\nprivate:\n LinuxCallstack(const Callstack::Stackwalk &other);\n\n void Collect()\n {\n void *addrs_ptr[ARRAY_COUNT(addrs)];\n\n numLevels = backtrace(addrs_ptr, ARRAY_COUNT(addrs));\n\n int offs = 0;\n \/\/ if we want to trim levels of the stack, we can do that here\n \/\/ by incrementing offs and decrementing numLevels\n while(numLevels > 0 && addrs_ptr[offs] >= renderdocBase && addrs_ptr[offs] < renderdocEnd)\n {\n offs++;\n numLevels--;\n }\n\n for(int i = 0; i < numLevels; i++)\n addrs[i] = (uint64_t)addrs_ptr[i + offs];\n }\n\n uint64_t addrs[128];\n int numLevels;\n};\n\nnamespace Callstack\n{\nvoid Init()\n{\n \/\/ look for our own line\n FILE *f = FileIO::fopen(\"\/proc\/self\/maps\", \"r\");\n\n if(f)\n {\n while(!feof(f))\n {\n char line[512] = {0};\n if(fgets(line, 511, f))\n {\n if(strstr(line, \"librenderdoc\") && strstr(line, \"r-xp\"))\n {\n sscanf(line, \"%p-%p\", &renderdocBase, &renderdocEnd);\n break;\n }\n }\n }\n\n FileIO::fclose(f);\n }\n}\n\nStackwalk *Collect()\n{\n return new LinuxCallstack();\n}\n\nStackwalk *Create()\n{\n return new LinuxCallstack(NULL, 0);\n}\n\nbool GetLoadedModules(byte *buf, size_t &size)\n{\n \/\/ we just dump the whole file rather than pre-parsing, that way we can improve\n \/\/ parsing without needing to recapture\n FILE *f = FileIO::fopen(\"\/proc\/self\/maps\", \"r\");\n\n if(buf)\n memcpy(buf, \"LNUXCALL\", 8);\n\n size += 8;\n\n byte dummy[512];\n\n while(!feof(f))\n {\n byte *readbuf = buf ? buf + size : dummy;\n size += FileIO::fread(readbuf, 1, 512, f);\n }\n\n FileIO::fclose(f);\n\n return true;\n}\n\nstruct LookupModule\n{\n uint64_t base;\n uint64_t end;\n char path[2048];\n};\n\nclass LinuxResolver : public Callstack::StackResolver\n{\npublic:\n LinuxResolver(vector<LookupModule> modules) { m_Modules = modules; }\n Callstack::AddressDetails GetAddr(uint64_t addr)\n {\n EnsureCached(addr);\n\n return m_Cache[addr];\n }\n\nprivate:\n void EnsureCached(uint64_t addr)\n {\n auto it = m_Cache.insert(\n std::pair<uint64_t, Callstack::AddressDetails>(addr, Callstack::AddressDetails()));\n if(!it.second)\n return;\n\n Callstack::AddressDetails &ret = it.first->second;\n\n ret.filename = \"Unknown\";\n ret.line = 0;\n ret.function = StringFormat::Fmt(\"0x%08llx\", addr);\n\n for(size_t i = 0; i < m_Modules.size(); i++)\n {\n if(addr >= m_Modules[i].base && addr < m_Modules[i].end)\n {\n uint64_t relative = addr - m_Modules[i].base;\n string cmd =\n StringFormat::Fmt(\"addr2line -j.text -fCe \\\"%s\\\" 0x%llx\", m_Modules[i].path, relative);\n\n FILE *f = ::popen(cmd.c_str(), \"r\");\n\n char result[2048] = {0};\n fread(result, 1, 2047, f);\n\n fclose(f);\n\n char *line2 = strchr(result, '\\n');\n if(line2)\n {\n *line2 = 0;\n line2++;\n }\n\n ret.function = result;\n\n if(line2)\n {\n char *last = line2 + strlen(line2) - 1;\n uint32_t mul = 1;\n ret.line = 0;\n while(*last >= '0' && *last <= '9')\n {\n ret.line += mul * (uint32_t(*last) - uint32_t('0'));\n *last = 0;\n last--;\n mul *= 10;\n }\n if(*last == ':')\n *last = 0;\n\n ret.filename = line2;\n }\n\n break;\n }\n }\n }\n\n std::vector<LookupModule> m_Modules;\n std::map<uint64_t, Callstack::AddressDetails> m_Cache;\n};\n\nStackResolver *MakeResolver(byte *moduleDB, size_t DBSize, RENDERDOC_ProgressCallback progress)\n{\n \/\/ we look in the original locations for the files, we don't prompt if we can't\n \/\/ find the file, or the file doesn't have symbols (and we don't validate that\n \/\/ the file is the right version). A good option for doing this would be\n \/\/ http:\/\/github.com\/mlabbe\/nativefiledialog\n\n if(DBSize < 8 || memcmp(moduleDB, \"LNUXCALL\", 8))\n {\n RDCWARN(\"Can't load callstack resolve for this log. Possibly from another platform?\");\n return NULL;\n }\n\n char *start = (char *)(moduleDB + 8);\n char *search = start;\n char *dbend = (char *)(moduleDB + DBSize);\n\n vector<LookupModule> modules;\n\n while(search && search < dbend)\n {\n if(progress)\n progress(float(search - start) \/ float(DBSize));\n\n \/\/ find .text segments\n {\n long unsigned int base = 0, end = 0;\n\n int inode = 0;\n int offs = 0;\n \/\/ base-end perms offset devid inode offs\n int num = sscanf(search, \"%lx-%lx r-xp %*x %*x:%*x %d %n\", &base, &end, &inode, &offs);\n\n \/\/ we don't care about inode actually, we ust use it to verify that\n \/\/ we read all 3 params (and so perms == r-xp)\n if(num == 3 && offs > 0)\n {\n LookupModule mod = {0};\n\n mod.base = (uint64_t)base;\n mod.end = (uint64_t)end;\n\n search += offs;\n while(search < dbend && (*search == ' ' || *search == '\\t'))\n search++;\n\n if(search < dbend && *search != '[' && *search != 0 && *search != '\\n')\n {\n size_t n = ARRAY_COUNT(mod.path) - 1;\n mod.path[n] = 0;\n for(size_t i = 0; i < n; i++)\n {\n if(search[i] == 0 || search[i] == '\\n')\n {\n mod.path[i] = 0;\n break;\n }\n if(search + i >= dbend)\n {\n mod.path[i] = 0;\n break;\n }\n mod.path[i] = search[i];\n }\n\n \/\/ addr2line wants offsets relative to text section, have to find offset of .text section\n \/\/ in this\n \/\/ mmapped section\n\n int textoffs = 0;\n string cmd = StringFormat::Fmt(\"readelf -WS \\\"%s\\\"\", mod.path);\n\n FILE *f = ::popen(cmd.c_str(), \"r\");\n\n char result[4096] = {0};\n fread(result, 1, 4095, f);\n\n fclose(f);\n\n \/\/ find .text line\n char *find = strstr(result, \".text\");\n\n if(find)\n {\n find += 5;\n\n while(isalpha(*find) || isspace(*find))\n find++;\n\n \/\/ virtual address is listed first, we want the offset\n sscanf(find, \"%*x %x\", &textoffs);\n\n mod.base += textoffs;\n\n modules.push_back(mod);\n }\n }\n }\n }\n\n if(progress)\n progress(RDCMIN(1.0f, float(search - start) \/ float(DBSize)));\n\n if(search >= dbend)\n break;\n\n search = strchr(search, '\\n');\n if(search)\n search++;\n }\n\n return new LinuxResolver(modules);\n}\n};\n<commit_msg>Fix handling of addr2line output in linux callstacks<commit_after>\/******************************************************************************\n * The MIT License (MIT)\n *\n * Copyright (c) 2016-2018 Baldur Karlsson\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n ******************************************************************************\/\n\n#include <execinfo.h>\n#include <stdio.h>\n#include <string.h>\n#include <map>\n#include <vector>\n#include \"os\/os_specific.h\"\n\nvoid *renderdocBase = NULL;\nvoid *renderdocEnd = NULL;\n\nclass LinuxCallstack : public Callstack::Stackwalk\n{\npublic:\n LinuxCallstack()\n {\n RDCEraseEl(addrs);\n numLevels = 0;\n Collect();\n }\n LinuxCallstack(uint64_t *calls, size_t num) { Set(calls, num); }\n ~LinuxCallstack() {}\n void Set(uint64_t *calls, size_t num)\n {\n numLevels = num;\n for(int i = 0; i < numLevels; i++)\n addrs[i] = calls[i];\n }\n\n size_t NumLevels() const { return size_t(numLevels); }\n const uint64_t *GetAddrs() const { return addrs; }\nprivate:\n LinuxCallstack(const Callstack::Stackwalk &other);\n\n void Collect()\n {\n void *addrs_ptr[ARRAY_COUNT(addrs)];\n\n numLevels = backtrace(addrs_ptr, ARRAY_COUNT(addrs));\n\n int offs = 0;\n \/\/ if we want to trim levels of the stack, we can do that here\n \/\/ by incrementing offs and decrementing numLevels\n while(numLevels > 0 && addrs_ptr[offs] >= renderdocBase && addrs_ptr[offs] < renderdocEnd)\n {\n offs++;\n numLevels--;\n }\n\n for(int i = 0; i < numLevels; i++)\n addrs[i] = (uint64_t)addrs_ptr[i + offs];\n }\n\n uint64_t addrs[128];\n int numLevels;\n};\n\nnamespace Callstack\n{\nvoid Init()\n{\n \/\/ look for our own line\n FILE *f = FileIO::fopen(\"\/proc\/self\/maps\", \"r\");\n\n if(f)\n {\n while(!feof(f))\n {\n char line[512] = {0};\n if(fgets(line, 511, f))\n {\n if(strstr(line, \"librenderdoc\") && strstr(line, \"r-xp\"))\n {\n sscanf(line, \"%p-%p\", &renderdocBase, &renderdocEnd);\n break;\n }\n }\n }\n\n FileIO::fclose(f);\n }\n}\n\nStackwalk *Collect()\n{\n return new LinuxCallstack();\n}\n\nStackwalk *Create()\n{\n return new LinuxCallstack(NULL, 0);\n}\n\nbool GetLoadedModules(byte *buf, size_t &size)\n{\n \/\/ we just dump the whole file rather than pre-parsing, that way we can improve\n \/\/ parsing without needing to recapture\n FILE *f = FileIO::fopen(\"\/proc\/self\/maps\", \"r\");\n\n size = 0;\n\n if(buf)\n memcpy(buf, \"LNUXCALL\", 8);\n\n size += 8;\n\n byte dummy[512];\n\n while(!feof(f))\n {\n byte *readbuf = buf ? buf + size : dummy;\n size += FileIO::fread(readbuf, 1, 512, f);\n }\n\n FileIO::fclose(f);\n\n return true;\n}\n\nstruct LookupModule\n{\n uint64_t base;\n uint64_t end;\n char path[2048];\n};\n\nclass LinuxResolver : public Callstack::StackResolver\n{\npublic:\n LinuxResolver(vector<LookupModule> modules) { m_Modules = modules; }\n Callstack::AddressDetails GetAddr(uint64_t addr)\n {\n EnsureCached(addr);\n\n return m_Cache[addr];\n }\n\nprivate:\n void EnsureCached(uint64_t addr)\n {\n auto it = m_Cache.insert(\n std::pair<uint64_t, Callstack::AddressDetails>(addr, Callstack::AddressDetails()));\n if(!it.second)\n return;\n\n Callstack::AddressDetails &ret = it.first->second;\n\n ret.filename = \"Unknown\";\n ret.line = 0;\n ret.function = StringFormat::Fmt(\"0x%08llx\", addr);\n\n for(size_t i = 0; i < m_Modules.size(); i++)\n {\n if(addr >= m_Modules[i].base && addr < m_Modules[i].end)\n {\n uint64_t relative = addr - m_Modules[i].base;\n string cmd =\n StringFormat::Fmt(\"addr2line -j.text -fCe \\\"%s\\\" 0x%llx\", m_Modules[i].path, relative);\n\n FILE *f = ::popen(cmd.c_str(), \"r\");\n\n char result[2048] = {0};\n fread(result, 1, 2047, f);\n\n fclose(f);\n\n char *line2 = strchr(result, '\\n');\n if(line2)\n {\n *line2 = 0;\n line2++;\n }\n\n ret.function = result;\n\n if(line2)\n {\n char *linenum = line2 + strlen(line2) - 1;\n while(linenum > line2 && *linenum != ':')\n linenum--;\n\n ret.line = 0;\n\n if(*linenum == ':')\n {\n *linenum = 0;\n linenum++;\n\n while(*linenum >= '0' && *linenum <= '9')\n {\n ret.line *= 10;\n ret.line += (uint32_t(*linenum) - uint32_t('0'));\n linenum++;\n }\n }\n\n ret.filename = line2;\n }\n\n break;\n }\n }\n }\n\n std::vector<LookupModule> m_Modules;\n std::map<uint64_t, Callstack::AddressDetails> m_Cache;\n};\n\nStackResolver *MakeResolver(byte *moduleDB, size_t DBSize, RENDERDOC_ProgressCallback progress)\n{\n \/\/ we look in the original locations for the files, we don't prompt if we can't\n \/\/ find the file, or the file doesn't have symbols (and we don't validate that\n \/\/ the file is the right version). A good option for doing this would be\n \/\/ http:\/\/github.com\/mlabbe\/nativefiledialog\n\n if(DBSize < 8 || memcmp(moduleDB, \"LNUXCALL\", 8))\n {\n RDCWARN(\"Can't load callstack resolve for this log. Possibly from another platform?\");\n return NULL;\n }\n\n char *start = (char *)(moduleDB + 8);\n char *search = start;\n char *dbend = (char *)(moduleDB + DBSize);\n\n vector<LookupModule> modules;\n\n while(search && search < dbend)\n {\n if(progress)\n progress(float(search - start) \/ float(DBSize));\n\n \/\/ find .text segments\n {\n long unsigned int base = 0, end = 0;\n\n int inode = 0;\n int offs = 0;\n \/\/ base-end perms offset devid inode offs\n int num = sscanf(search, \"%lx-%lx r-xp %*x %*x:%*x %d %n\", &base, &end, &inode, &offs);\n\n \/\/ we don't care about inode actually, we ust use it to verify that\n \/\/ we read all 3 params (and so perms == r-xp)\n if(num == 3 && offs > 0)\n {\n LookupModule mod = {0};\n\n mod.base = (uint64_t)base;\n mod.end = (uint64_t)end;\n\n search += offs;\n while(search < dbend && (*search == ' ' || *search == '\\t'))\n search++;\n\n if(search < dbend && *search != '[' && *search != 0 && *search != '\\n')\n {\n size_t n = ARRAY_COUNT(mod.path) - 1;\n mod.path[n] = 0;\n for(size_t i = 0; i < n; i++)\n {\n if(search[i] == 0 || search[i] == '\\n')\n {\n mod.path[i] = 0;\n break;\n }\n if(search + i >= dbend)\n {\n mod.path[i] = 0;\n break;\n }\n mod.path[i] = search[i];\n }\n\n \/\/ addr2line wants offsets relative to text section, have to find offset of .text section\n \/\/ in this\n \/\/ mmapped section\n\n int textoffs = 0;\n string cmd = StringFormat::Fmt(\"readelf -WS \\\"%s\\\"\", mod.path);\n\n FILE *f = ::popen(cmd.c_str(), \"r\");\n\n char result[4096] = {0};\n fread(result, 1, 4095, f);\n\n fclose(f);\n\n \/\/ find .text line\n char *find = strstr(result, \".text\");\n\n if(find)\n {\n find += 5;\n\n while(isalpha(*find) || isspace(*find))\n find++;\n\n \/\/ virtual address is listed first, we want the offset\n sscanf(find, \"%*x %x\", &textoffs);\n\n mod.base += textoffs;\n\n modules.push_back(mod);\n }\n }\n }\n }\n\n if(progress)\n progress(RDCMIN(1.0f, float(search - start) \/ float(DBSize)));\n\n if(search >= dbend)\n break;\n\n search = strchr(search, '\\n');\n if(search)\n search++;\n }\n\n return new LinuxResolver(modules);\n}\n};\n<|endoftext|>"} {"text":"<commit_before>\/******************************************************************************\n * The MIT License (MIT)\n *\n * Copyright (c) 2019-2020 Baldur Karlsson\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n ******************************************************************************\/\n\n#include <execinfo.h>\n#include <stdio.h>\n#include <string.h>\n#include <map>\n#include \"common\/common.h\"\n#include \"common\/formatting.h\"\n#include \"os\/os_specific.h\"\n\nvoid *renderdocBase = NULL;\nvoid *renderdocEnd = NULL;\n\nclass LinuxCallstack : public Callstack::Stackwalk\n{\npublic:\n LinuxCallstack()\n {\n RDCEraseEl(addrs);\n numLevels = 0;\n Collect();\n }\n LinuxCallstack(uint64_t *calls, size_t num) { Set(calls, num); }\n ~LinuxCallstack() {}\n void Set(uint64_t *calls, size_t num)\n {\n numLevels = num;\n for(size_t i = 0; i < numLevels; i++)\n addrs[i] = calls[i];\n }\n\n size_t NumLevels() const { return numLevels; }\n const uint64_t *GetAddrs() const { return addrs; }\nprivate:\n LinuxCallstack(const Callstack::Stackwalk &other);\n\n void Collect()\n {\n void *addrs_ptr[ARRAY_COUNT(addrs)];\n\n int ret = backtrace(addrs_ptr, ARRAY_COUNT(addrs));\n\n numLevels = 0;\n if(ret > 0)\n numLevels = (size_t)ret;\n\n int offs = 0;\n \/\/ if we want to trim levels of the stack, we can do that here\n \/\/ by incrementing offs and decrementing numLevels\n while(numLevels > 0 && addrs_ptr[offs] >= renderdocBase && addrs_ptr[offs] < renderdocEnd)\n {\n offs++;\n numLevels--;\n }\n\n for(size_t i = 0; i < numLevels; i++)\n addrs[i] = (uint64_t)addrs_ptr[i + offs];\n }\n\n uint64_t addrs[128];\n size_t numLevels;\n};\n\nnamespace Callstack\n{\nvoid Init()\n{\n \/\/ look for our own line\n FILE *f = FileIO::fopen(\"\/proc\/self\/maps\", \"r\");\n\n if(f)\n {\n while(!feof(f))\n {\n char line[512] = {0};\n if(fgets(line, 511, f))\n {\n if(strstr(line, \"librenderdoc\") && strstr(line, \"r-xp\"))\n {\n sscanf(line, \"%p-%p\", &renderdocBase, &renderdocEnd);\n break;\n }\n }\n }\n\n FileIO::fclose(f);\n }\n}\n\nStackwalk *Collect()\n{\n return new LinuxCallstack();\n}\n\nStackwalk *Create()\n{\n return new LinuxCallstack(NULL, 0);\n}\n\nbool GetLoadedModules(byte *buf, size_t &size)\n{\n \/\/ we just dump the whole file rather than pre-parsing, that way we can improve\n \/\/ parsing without needing to recapture\n FILE *f = FileIO::fopen(\"\/proc\/self\/maps\", \"r\");\n\n size = 0;\n\n if(buf)\n memcpy(buf, \"LNUXCALL\", 8);\n\n size += 8;\n\n byte dummy[512];\n\n while(!feof(f))\n {\n byte *readbuf = buf ? buf + size : dummy;\n size += FileIO::fread(readbuf, 1, 512, f);\n }\n\n FileIO::fclose(f);\n\n return true;\n}\n\nstruct LookupModule\n{\n uint64_t base;\n uint64_t end;\n uint64_t offset;\n char path[2048];\n};\n\nclass LinuxResolver : public Callstack::StackResolver\n{\npublic:\n LinuxResolver(rdcarray<LookupModule> modules) { m_Modules = modules; }\n Callstack::AddressDetails GetAddr(uint64_t addr)\n {\n EnsureCached(addr);\n\n return m_Cache[addr];\n }\n\nprivate:\n void EnsureCached(uint64_t addr)\n {\n auto it = m_Cache.insert(\n std::pair<uint64_t, Callstack::AddressDetails>(addr, Callstack::AddressDetails()));\n if(!it.second)\n return;\n\n Callstack::AddressDetails &ret = it.first->second;\n\n ret.filename = \"Unknown\";\n ret.line = 0;\n ret.function = StringFormat::Fmt(\"0x%08llx\", addr);\n\n for(size_t i = 0; i < m_Modules.size(); i++)\n {\n if(addr >= m_Modules[i].base && addr < m_Modules[i].end)\n {\n uint64_t relative = addr - m_Modules[i].base + m_Modules[i].offset;\n rdcstr cmd = StringFormat::Fmt(\"addr2line -fCe \\\"%s\\\" 0x%llx\", m_Modules[i].path, relative);\n\n FILE *f = ::popen(cmd.c_str(), \"r\");\n\n char result[2048] = {0};\n fread(result, 1, 2047, f);\n\n fclose(f);\n\n char *line2 = strchr(result, '\\n');\n if(line2)\n {\n *line2 = 0;\n line2++;\n }\n\n ret.function = result;\n\n if(line2)\n {\n char *linenum = line2 + strlen(line2) - 1;\n while(linenum > line2 && *linenum != ':')\n linenum--;\n\n ret.line = 0;\n\n if(*linenum == ':')\n {\n *linenum = 0;\n linenum++;\n\n while(*linenum >= '0' && *linenum <= '9')\n {\n ret.line *= 10;\n ret.line += (uint32_t(*linenum) - uint32_t('0'));\n linenum++;\n }\n }\n\n ret.filename = line2;\n }\n\n break;\n }\n }\n }\n\n rdcarray<LookupModule> m_Modules;\n std::map<uint64_t, Callstack::AddressDetails> m_Cache;\n};\n\nStackResolver *MakeResolver(bool interactive, byte *moduleDB, size_t DBSize,\n RENDERDOC_ProgressCallback progress)\n{\n \/\/ we look in the original locations for the files, we don't prompt if we can't\n \/\/ find the file, or the file doesn't have symbols (and we don't validate that\n \/\/ the file is the right version). A good option for doing this would be\n \/\/ http:\/\/github.com\/mlabbe\/nativefiledialog\n\n if(DBSize < 8 || memcmp(moduleDB, \"LNUXCALL\", 8))\n {\n RDCWARN(\"Can't load callstack resolve for this log. Possibly from another platform?\");\n return NULL;\n }\n\n char *start = (char *)(moduleDB + 8);\n char *search = start;\n char *dbend = (char *)(moduleDB + DBSize);\n\n rdcarray<LookupModule> modules;\n\n while(search && search < dbend)\n {\n if(progress)\n progress(float(search - start) \/ float(DBSize));\n\n \/\/ find .text segments\n {\n long unsigned int base = 0, end = 0, offset = 0;\n\n int inode = 0;\n int offs = 0;\n \/\/ base-end perms offset devid inode offs\n int num = sscanf(search, \"%lx-%lx r-xp %lx %*x:%*x %d %n\", &base, &end, &offset,\n &inode, &offs);\n\n \/\/ we don't care about inode actually, we ust use it to verify that\n \/\/ we read all 4 params (and so perms == r-xp)\n if(num == 4 && offs > 0)\n {\n LookupModule mod = {0};\n\n mod.base = (uint64_t)base;\n mod.end = (uint64_t)end;\n mod.offset = (uint64_t)offset;\n\n search += offs;\n while(search < dbend && (*search == ' ' || *search == '\\t'))\n search++;\n\n if(search < dbend && *search != '[' && *search != 0 && *search != '\\n')\n {\n size_t n = ARRAY_COUNT(mod.path) - 1;\n mod.path[n] = 0;\n for(size_t i = 0; i < n; i++)\n {\n if(search[i] == 0 || search[i] == '\\n')\n {\n mod.path[i] = 0;\n break;\n }\n if(search + i >= dbend)\n {\n mod.path[i] = 0;\n break;\n }\n mod.path[i] = search[i];\n }\n\n modules.push_back(mod);\n }\n }\n }\n\n if(progress)\n progress(RDCMIN(1.0f, float(search - start) \/ float(DBSize)));\n\n if(search >= dbend)\n break;\n\n search = strchr(search, '\\n');\n if(search)\n search++;\n }\n\n return new LinuxResolver(modules);\n}\n};\n<commit_msg>Use dl_iterate_phdr to generate non-PIE compatible mapping. Closes #1773<commit_after>\/******************************************************************************\n * The MIT License (MIT)\n *\n * Copyright (c) 2019-2020 Baldur Karlsson\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n ******************************************************************************\/\n\n\/\/ for dl_iterate_phdr\n#ifndef _GNU_SOURCE\n#define _GNU_SOURCE\n#endif\n\n#include <execinfo.h>\n#include <link.h>\n#include <stdio.h>\n#include <string.h>\n#include <map>\n#include \"common\/common.h\"\n#include \"common\/formatting.h\"\n#include \"os\/os_specific.h\"\n\nvoid *renderdocBase = NULL;\nvoid *renderdocEnd = NULL;\n\nclass LinuxCallstack : public Callstack::Stackwalk\n{\npublic:\n LinuxCallstack()\n {\n RDCEraseEl(addrs);\n numLevels = 0;\n Collect();\n }\n LinuxCallstack(uint64_t *calls, size_t num) { Set(calls, num); }\n ~LinuxCallstack() {}\n void Set(uint64_t *calls, size_t num)\n {\n numLevels = num;\n for(size_t i = 0; i < numLevels; i++)\n addrs[i] = calls[i];\n }\n\n size_t NumLevels() const { return numLevels; }\n const uint64_t *GetAddrs() const { return addrs; }\nprivate:\n LinuxCallstack(const Callstack::Stackwalk &other);\n\n void Collect()\n {\n void *addrs_ptr[ARRAY_COUNT(addrs)];\n\n int ret = backtrace(addrs_ptr, ARRAY_COUNT(addrs));\n\n numLevels = 0;\n if(ret > 0)\n numLevels = (size_t)ret;\n\n int offs = 0;\n \/\/ if we want to trim levels of the stack, we can do that here\n \/\/ by incrementing offs and decrementing numLevels\n while(numLevels > 0 && addrs_ptr[offs] >= renderdocBase && addrs_ptr[offs] < renderdocEnd)\n {\n offs++;\n numLevels--;\n }\n\n for(size_t i = 0; i < numLevels; i++)\n addrs[i] = (uint64_t)addrs_ptr[i + offs];\n }\n\n uint64_t addrs[128];\n size_t numLevels;\n};\n\nnamespace Callstack\n{\nvoid Init()\n{\n \/\/ look for our own line\n FILE *f = FileIO::fopen(\"\/proc\/self\/maps\", \"r\");\n\n if(f)\n {\n while(!feof(f))\n {\n char line[512] = {0};\n if(fgets(line, 511, f))\n {\n if(strstr(line, \"librenderdoc\") && strstr(line, \"r-xp\"))\n {\n sscanf(line, \"%p-%p\", &renderdocBase, &renderdocEnd);\n break;\n }\n }\n }\n\n FileIO::fclose(f);\n }\n}\n\nStackwalk *Collect()\n{\n return new LinuxCallstack();\n}\n\nStackwalk *Create()\n{\n return new LinuxCallstack(NULL, 0);\n}\n\nstatic int dl_iterate_callback(struct dl_phdr_info *info, size_t size, void *data)\n{\n if(info->dlpi_name == NULL)\n {\n RDCLOG(\"Skipping NULL entry!\");\n return 0;\n }\n\n rdcstr *out = (rdcstr *)data;\n\n rdcstr name = info->dlpi_name;\n if(name.empty())\n FileIO::GetExecutableFilename(name);\n\n name = FileIO::GetFullPathname(name);\n\n for(int j = 0; j < info->dlpi_phnum; j++)\n {\n uint32_t rxMask = PF_R | PF_X;\n if(info->dlpi_phdr[j].p_type == PT_LOAD && (info->dlpi_phdr[j].p_flags & rxMask) == rxMask)\n {\n uint64_t baseAddr = info->dlpi_addr + info->dlpi_phdr[j].p_vaddr;\n *out += StringFormat::Fmt(\"%llx-%llx r-xp %08x 123:45 12345678 %s\\n\", baseAddr,\n baseAddr + info->dlpi_phdr[j].p_memsz, info->dlpi_phdr[j].p_vaddr,\n name.c_str());\n }\n }\n\n return 0;\n}\n\nbool GetLoadedModules(byte *buf, size_t &size)\n{\n size = 0;\n\n if(buf)\n {\n memcpy(buf, \"LNUXCALL\", 8);\n buf += 8;\n }\n\n size += 8;\n\n \/\/ generate a fake \/proc\/self\/maps. This is mostly for backwards compatibility, we could generate\n \/\/ a more compact representation. The slight difference is that we change how we calculate the\n \/\/ offset for each segment, so that we handle non-PIE executables properly.\n rdcstr fake_maps;\n\n dl_iterate_phdr(dl_iterate_callback, &fake_maps);\n\n size += fake_maps.size();\n\n if(buf)\n memcpy(buf, fake_maps.data(), fake_maps.size());\n\n return true;\n}\n\nstruct LookupModule\n{\n uint64_t base;\n uint64_t end;\n uint64_t offset;\n char path[2048];\n};\n\nclass LinuxResolver : public Callstack::StackResolver\n{\npublic:\n LinuxResolver(rdcarray<LookupModule> modules) { m_Modules = modules; }\n Callstack::AddressDetails GetAddr(uint64_t addr)\n {\n EnsureCached(addr);\n\n return m_Cache[addr];\n }\n\nprivate:\n void EnsureCached(uint64_t addr)\n {\n auto it = m_Cache.insert(\n std::pair<uint64_t, Callstack::AddressDetails>(addr, Callstack::AddressDetails()));\n if(!it.second)\n return;\n\n Callstack::AddressDetails &ret = it.first->second;\n\n ret.filename = \"Unknown\";\n ret.line = 0;\n ret.function = StringFormat::Fmt(\"0x%08llx\", addr);\n\n for(size_t i = 0; i < m_Modules.size(); i++)\n {\n if(addr >= m_Modules[i].base && addr < m_Modules[i].end)\n {\n RDCLOG(\"%llx relative to module %llx-%llx, with offset %llx\", addr, m_Modules[i].base,\n m_Modules[i].end, m_Modules[i].offset);\n uint64_t relative = addr - m_Modules[i].base + m_Modules[i].offset;\n rdcstr cmd = StringFormat::Fmt(\"addr2line -fCe \\\"%s\\\" 0x%llx\", m_Modules[i].path, relative);\n\n RDCLOG(\": %s\", cmd.c_str());\n\n FILE *f = ::popen(cmd.c_str(), \"r\");\n\n char result[2048] = {0};\n fread(result, 1, 2047, f);\n\n fclose(f);\n\n char *line2 = strchr(result, '\\n');\n if(line2)\n {\n *line2 = 0;\n line2++;\n }\n\n ret.function = result;\n\n if(line2)\n {\n char *linenum = line2 + strlen(line2) - 1;\n while(linenum > line2 && *linenum != ':')\n linenum--;\n\n ret.line = 0;\n\n if(*linenum == ':')\n {\n *linenum = 0;\n linenum++;\n\n while(*linenum >= '0' && *linenum <= '9')\n {\n ret.line *= 10;\n ret.line += (uint32_t(*linenum) - uint32_t('0'));\n linenum++;\n }\n }\n\n ret.filename = line2;\n }\n\n break;\n }\n }\n }\n\n rdcarray<LookupModule> m_Modules;\n std::map<uint64_t, Callstack::AddressDetails> m_Cache;\n};\n\nStackResolver *MakeResolver(bool interactive, byte *moduleDB, size_t DBSize,\n RENDERDOC_ProgressCallback progress)\n{\n \/\/ we look in the original locations for the files, we don't prompt if we can't\n \/\/ find the file, or the file doesn't have symbols (and we don't validate that\n \/\/ the file is the right version). A good option for doing this would be\n \/\/ http:\/\/github.com\/mlabbe\/nativefiledialog\n\n if(DBSize < 8 || memcmp(moduleDB, \"LNUXCALL\", 8))\n {\n RDCWARN(\"Can't load callstack resolve for this log. Possibly from another platform?\");\n return NULL;\n }\n\n char *start = (char *)(moduleDB + 8);\n char *search = start;\n char *dbend = (char *)(moduleDB + DBSize);\n\n rdcarray<LookupModule> modules;\n\n while(search && search < dbend)\n {\n if(progress)\n progress(float(search - start) \/ float(DBSize));\n\n \/\/ find .text segments\n {\n long unsigned int base = 0, end = 0, offset = 0;\n\n int inode = 0;\n int offs = 0;\n \/\/ base-end perms offset devid inode offs\n int num = sscanf(search, \"%lx-%lx r-xp %lx %*x:%*x %d %n\", &base, &end, &offset,\n &inode, &offs);\n\n \/\/ we don't care about inode actually, we ust use it to verify that\n \/\/ we read all 4 params (and so perms == r-xp)\n if(num == 4 && offs > 0)\n {\n LookupModule mod = {0};\n\n mod.base = (uint64_t)base;\n mod.end = (uint64_t)end;\n mod.offset = (uint64_t)offset;\n\n search += offs;\n while(search < dbend && (*search == ' ' || *search == '\\t'))\n search++;\n\n if(search < dbend && *search != '[' && *search != 0 && *search != '\\n')\n {\n size_t n = ARRAY_COUNT(mod.path) - 1;\n mod.path[n] = 0;\n for(size_t i = 0; i < n; i++)\n {\n if(search[i] == 0 || search[i] == '\\n')\n {\n mod.path[i] = 0;\n break;\n }\n if(search + i >= dbend)\n {\n mod.path[i] = 0;\n break;\n }\n mod.path[i] = search[i];\n }\n\n modules.push_back(mod);\n }\n }\n }\n\n if(progress)\n progress(RDCMIN(1.0f, float(search - start) \/ float(DBSize)));\n\n if(search >= dbend)\n break;\n\n search = strchr(search, '\\n');\n if(search)\n search++;\n }\n\n return new LinuxResolver(modules);\n}\n};\n<|endoftext|>"} {"text":"<commit_before>#ifndef MDSYSEX_H__\n#define MDSYSEX_H__\n\n#include \"WProgram.h\"\n#include \"Midi.h\"\n#include \"MidiSysex.hh\"\n#include \"Vector.hh\"\n#include \"Callback.hh\"\n#include \"MD.h\"\n\ntypedef enum {\n MD_NONE,\n \n MD_GET_CURRENT_KIT,\n MD_GET_KIT,\n \n MD_GET_CURRENT_GLOBAL,\n MD_GET_GLOBAL,\n \n MD_DONE\n} getCurrentKitStatus_t;\n\nclass MDSysexListenerClass : public MidiSysexListenerClass {\npublic:\n CallbackVector<MDCallback,4> onGlobalMessageCallbacks;\n CallbackVector<MDCallback,4> onKitMessageCallbacks;\n CallbackVector<MDCallback,4> onSongMessageCallbacks;\n CallbackVector<MDCallback,4> onPatternMessageCallbacks;\n CallbackVector2<MDCallback,4,uint8_t,uint8_t> onStatusResponseCallbacks;\n \n bool isMDMessage;\n uint8_t msgType;\n\n MDSysexListenerClass() : MidiSysexListenerClass() {\n ids[0] = 0;\n ids[1] = 0x20;\n ids[2] = 0x3c;\n }\n\n void addOnStatusResponseCallback(MDCallback *obj, md_status_callback_ptr_t func) {\n onStatusResponseCallbacks.add(obj, func);\n }\n void removeOnStatusResponseCallback(MDCallback *obj, md_status_callback_ptr_t func) {\n onStatusResponseCallbacks.remove(obj, func);\n }\n void removeOnStatusResponseCallback(MDCallback *obj) {\n onStatusResponseCallbacks.remove(obj);\n }\n\n void addOnGlobalMessageCallback(MDCallback *obj, md_callback_ptr_t func) {\n onGlobalMessageCallbacks.add(obj, func);\n }\n void removeOnGlobalMessageCallback(MDCallback *obj, md_callback_ptr_t func) {\n onGlobalMessageCallbacks.remove(obj, func);\n }\n void removeOnGlobalMessageCallback(MDCallback *obj) {\n onGlobalMessageCallbacks.remove(obj);\n }\n \n void addOnKitMessageCallback(MDCallback *obj, md_callback_ptr_t func) {\n onKitMessageCallbacks.add(obj, func);\n }\n void removeOnKitMessageCallback(MDCallback *obj, md_callback_ptr_t func) {\n onKitMessageCallbacks.remove(obj, func);\n }\n void removeOnKitMessageCallback(MDCallback *obj) {\n onKitMessageCallbacks.remove(obj);\n }\n \n void addOnPatternMessageCallback(MDCallback *obj, md_callback_ptr_t func) {\n onPatternMessageCallbacks.add(obj, func);\n }\n void removeOnPatternMessageCallback(MDCallback *obj, md_callback_ptr_t func) {\n onPatternMessageCallbacks.remove(obj, func);\n }\n void removeOnPatternMessageCallback(MDCallback *obj) {\n onPatternMessageCallbacks.remove(obj);\n }\n \n void addOnSongMessageCallback(MDCallback *obj, md_callback_ptr_t func) {\n onSongMessageCallbacks.add(obj, func);\n }\n void removeOnSongMessageCallback(MDCallback *obj, md_callback_ptr_t func) {\n onSongMessageCallbacks.remove(obj, func);\n }\n void removeOnSongMessageCallback(MDCallback *obj) {\n onSongMessageCallbacks.remove(obj);\n }\n \n virtual void start();\n virtual void handleByte(uint8_t byte);\n virtual void end();\n\n void setup();\n};\n\n#include \"MDMessages.hh\"\n\nextern MDSysexListenerClass MDSysexListener;\n\n#endif \/* MDSYSEX_H__ *\/\n<commit_msg>cosmetics<commit_after>#ifndef MDSYSEX_H__\n#define MDSYSEX_H__\n\n#include \"WProgram.h\"\n#include \"Midi.h\"\n#include \"MidiSysex.hh\"\n#include \"Vector.hh\"\n#include \"Callback.hh\"\n#include \"MD.h\"\n\ntypedef enum {\n MD_NONE,\n \n MD_GET_CURRENT_KIT,\n MD_GET_KIT,\n \n MD_GET_CURRENT_GLOBAL,\n MD_GET_GLOBAL,\n \n MD_DONE\n} getCurrentKitStatus_t;\n\nclass MDSysexListenerClass : public MidiSysexListenerClass {\npublic:\n CallbackVector<MDCallback,4> onGlobalMessageCallbacks;\n CallbackVector<MDCallback,4> onKitMessageCallbacks;\n CallbackVector<MDCallback,4> onSongMessageCallbacks;\n CallbackVector<MDCallback,4> onPatternMessageCallbacks;\n CallbackVector2<MDCallback,4,uint8_t,uint8_t> onStatusResponseCallbacks;\n \n bool isMDMessage;\n uint8_t msgType;\n\n MDSysexListenerClass() : MidiSysexListenerClass() {\n ids[0] = 0;\n ids[1] = 0x20;\n ids[2] = 0x3c;\n }\n\n virtual void start();\n virtual void handleByte(uint8_t byte);\n virtual void end();\n\n void setup();\n\n void addOnStatusResponseCallback(MDCallback *obj, md_status_callback_ptr_t func) {\n onStatusResponseCallbacks.add(obj, func);\n }\n void removeOnStatusResponseCallback(MDCallback *obj, md_status_callback_ptr_t func) {\n onStatusResponseCallbacks.remove(obj, func);\n }\n void removeOnStatusResponseCallback(MDCallback *obj) {\n onStatusResponseCallbacks.remove(obj);\n }\n\n void addOnGlobalMessageCallback(MDCallback *obj, md_callback_ptr_t func) {\n onGlobalMessageCallbacks.add(obj, func);\n }\n void removeOnGlobalMessageCallback(MDCallback *obj, md_callback_ptr_t func) {\n onGlobalMessageCallbacks.remove(obj, func);\n }\n void removeOnGlobalMessageCallback(MDCallback *obj) {\n onGlobalMessageCallbacks.remove(obj);\n }\n \n void addOnKitMessageCallback(MDCallback *obj, md_callback_ptr_t func) {\n onKitMessageCallbacks.add(obj, func);\n }\n void removeOnKitMessageCallback(MDCallback *obj, md_callback_ptr_t func) {\n onKitMessageCallbacks.remove(obj, func);\n }\n void removeOnKitMessageCallback(MDCallback *obj) {\n onKitMessageCallbacks.remove(obj);\n }\n \n void addOnPatternMessageCallback(MDCallback *obj, md_callback_ptr_t func) {\n onPatternMessageCallbacks.add(obj, func);\n }\n void removeOnPatternMessageCallback(MDCallback *obj, md_callback_ptr_t func) {\n onPatternMessageCallbacks.remove(obj, func);\n }\n void removeOnPatternMessageCallback(MDCallback *obj) {\n onPatternMessageCallbacks.remove(obj);\n }\n \n void addOnSongMessageCallback(MDCallback *obj, md_callback_ptr_t func) {\n onSongMessageCallbacks.add(obj, func);\n }\n void removeOnSongMessageCallback(MDCallback *obj, md_callback_ptr_t func) {\n onSongMessageCallbacks.remove(obj, func);\n }\n void removeOnSongMessageCallback(MDCallback *obj) {\n onSongMessageCallbacks.remove(obj);\n }\n \n};\n\n#include \"MDMessages.hh\"\n\nextern MDSysexListenerClass MDSysexListener;\n\n#endif \/* MDSYSEX_H__ *\/\n<|endoftext|>"} {"text":"<commit_before>\/*=========================================================================\n\n Program: ORFEO Toolbox\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n\n Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.\n See OTBCopyright.txt for details.\n\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notices for more information.\n\n=========================================================================*\/\n\n#include \"otbImage.h\"\n#include \"itkPointSet.h\"\n#include \"otbLineSpatialObjectListToRightAnglePointSetFilter.h\"\n#include \"otbLineSpatialObjectList.h\"\n#include \"otbDrawLineSpatialObjectListFilter.h\"\n#include \"otbLineSegmentDetector.h\"\n\n#include \"otbImageFileReader.h\"\n#include \"otbImageFileWriter.h\"\n\n#include <iostream>\n#include <fstream>\n\nint main( int argc, char * argv[] )\n{\n const char * infname = argv[1]; \n const char * outfname = argv[2];\n \n const unsigned int Dimension = 2;\n typedef float PixelType;\n \n \/** Typedefs *\/\n typedef otb::Image<PixelType ,Dimension> ImageType;\n typedef otb::ImageFileReader<ImageType> ReaderType;\n typedef otb::ImageFileWriter<ImageType> WriterType;\n typedef otb::LineSpatialObjectList LinesListType;\n typedef LinesListType::LineType LineType;\n typedef std::vector<LineType*> VectorLines;\n typedef itk::PointSet<VectorLines , Dimension> PointSetType;\n typedef otb::LineSegmentDetector<ImageType , PixelType> lsdFilterType;\n typedef otb::LineSpatialObjectListToRightAnglePointSetFilter<ImageType,\n LinesListType, PointSetType>\n RightAngleFilterType;\n \n \/** Creatop, of an instance of the filters *\/\n RightAngleFilterType::Pointer rightAngleFilter =\n RightAngleFilterType::New();\n ReaderType::Pointer reader = ReaderType::New();\n PointSetType::Pointer segmentOrtho = PointSetType::New(); \n lsdFilterType::Pointer lsdFilter = lsdFilterType::New();\n\n\n \n\n \/\/ Begin the process\n reader->SetFileName(infname);\n lsdFilter->SetInput(reader->GetOutput()); \n \n rightAngleFilter->SetInputImage(reader->GetOutput());\n rightAngleFilter->SetInput(lsdFilter->GetOutput());\n rightAngleFilter->Update();\n\n\n \/** Print the right angles coordinate in the output file*\/\n segmentOrtho = rightAngleFilter->GetOutput();\n PointSetType::PointType pRight;\n VectorLines outputVectorLines;\n LinesListType::Pointer outputLinesList = LinesListType::New();\n \n std::ofstream outfile(outfname);\n for (unsigned int i = 0; i<segmentOrtho->GetNumberOfPoints() ; i++)\n {\n segmentOrtho->GetPoint(i, &pRight);\n outfile << \" Right Angle found in point : \" << pRight << std::endl;\n \n \/** Exemple To extract The coordinate of the segment (Just for example)*\/\n segmentOrtho->GetPointData(i, &outputVectorLines);\n outputLinesList->push_back(outputVectorLines[0]);\n outputLinesList->push_back(outputVectorLines[1]);\n }\n outfile.close();\n \n return EXIT_SUCCESS;\n}\n\n<commit_msg>DOC: RightAngleDetectionExample line drawing<commit_after>\/*=========================================================================\n\n Program: ORFEO Toolbox\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n\n Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.\n See OTBCopyright.txt for details.\n\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notices for more information.\n\n=========================================================================*\/\n\n#include \"otbImage.h\"\n#include \"itkPointSet.h\"\n#include \"otbLineSpatialObjectListToRightAnglePointSetFilter.h\"\n#include \"otbLineSpatialObjectList.h\"\n#include \"otbDrawLineSpatialObjectListFilter.h\"\n#include \"otbLineSegmentDetector.h\"\n\n#include \"otbImageFileReader.h\"\n#include \"otbImageFileWriter.h\"\n\n#include <iostream>\n#include <fstream>\n\nint main( int argc, char * argv[] )\n{\n const char * infname = argv[1]; \n const char * outfname = argv[2];\n \n const unsigned int Dimension = 2;\n typedef float PixelType;\n \n \/** Typedefs *\/\n typedef otb::Image<PixelType ,Dimension> ImageType;\n typedef otb::ImageFileReader<ImageType> ReaderType;\n typedef otb::ImageFileWriter<ImageType> WriterType;\n typedef otb::LineSpatialObjectList LinesListType;\n typedef LinesListType::LineType LineType;\n typedef std::vector<LineType*> VectorLines;\n typedef itk::PointSet<VectorLines , Dimension> PointSetType;\n typedef otb::LineSegmentDetector<ImageType , PixelType> lsdFilterType;\n typedef otb::LineSpatialObjectListToRightAnglePointSetFilter<ImageType,\n LinesListType, PointSetType>\n RightAngleFilterType;\n \n \/** Creatop, of an instance of the filters *\/\n RightAngleFilterType::Pointer rightAngleFilter =\n RightAngleFilterType::New();\n ReaderType::Pointer reader = ReaderType::New();\n PointSetType::Pointer segmentOrtho = PointSetType::New(); \n lsdFilterType::Pointer lsdFilter = lsdFilterType::New();\n\n\n \n\n \/\/ Begin the process\n reader->SetFileName(infname);\n lsdFilter->SetInput(reader->GetOutput()); \n \n rightAngleFilter->SetInputImage(reader->GetOutput());\n rightAngleFilter->SetInput(lsdFilter->GetOutput());\n rightAngleFilter->Update();\n\n\n \/** Print the right angles coordinate in the output file*\/\n segmentOrtho = rightAngleFilter->GetOutput();\n PointSetType::PointType pRight;\n VectorLines outputVectorLines;\n LinesListType::Pointer outputLinesList = LinesListType::New();\n \n for (unsigned int i = 0; i<segmentOrtho->GetNumberOfPoints() ; i++)\n {\n segmentOrtho->GetPoint(i, &pRight);\n segmentOrtho->GetPointData(i, &outputVectorLines);\n outputLinesList->push_back(outputVectorLines[0]);\n outputLinesList->push_back(outputVectorLines[1]);\n }\n\n typedef otb::DrawLineSpatialObjectListFilter< ImageType,\n ImageType > DrawLineListType;\n DrawLineListType::Pointer drawLineFilter = DrawLineListType::New();\n\n drawLineFilter->SetInput(reader->GetOutput());\n drawLineFilter->SetInputLineSpatialObjectList(outputLinesList);\n\n WriterType::Pointer writer = WriterType::New();\n writer->SetInput(drawLineFilter->GetOutput());\n writer->SetFileName(outfname);\n\n \n reader->GenerateOutputInformation();\n writer->Update();\n\n \n return EXIT_SUCCESS;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright(c) Sophist Solutions, Inc. 1990-2014. All rights reserved\n *\/\n#ifndef _Stroika_Foundation_Traversal_Iterable_inl_\n#define _Stroika_Foundation_Traversal_Iterable_inl_\n\n\n\/*\n ********************************************************************************\n ***************************** Implementation Details ***************************\n ********************************************************************************\n *\/\n#include \"..\/Debug\/Assertions.h\"\n\n\n\nnamespace Stroika {\n namespace Foundation {\n namespace Traversal {\n\n\n \/*\n ********************************************************************************\n *************************** Iterable<T>::_IRep *********************************\n ********************************************************************************\n *\/\n template <typename T>\n inline bool Iterable<T>::_IRep::_IsEmpty () const\n {\n return GetLength () == 0;\n }\n template <typename T>\n inline void Iterable<T>::_IRep::_Apply (_APPLY_ARGTYPE doToElement) const\n {\n RequireNotNull (doToElement);\n for (Iterator<T> i = MakeIterator (this); i != Iterable<T>::end (); ++i) {\n (doToElement) (*i);\n }\n }\n template <typename T>\n inline Iterator<T> Iterable<T>::_IRep::_FindFirstThat (_APPLYUNTIL_ARGTYPE doToElement, IteratorOwnerID suggestedOwner) const\n {\n RequireNotNull (doToElement);\n for (Iterator<T> i = MakeIterator (suggestedOwner); i != Iterable<T>::end (); ++i) {\n if ((doToElement) (*i)) {\n return i;\n }\n }\n return end ();\n }\n\n\n \/*\n ********************************************************************************\n ********************************** Iterable<T> *********************************\n ********************************************************************************\n *\/\n template <typename T>\n inline Iterable<T>::Iterable (const _SharedPtrIRep& rep) noexcept\n:\n fRep_ (rep)\n {\n Require (fRep_.GetSharingState () != Memory::SharedByValue_State::eNull);\n }\n template <typename T>\n inline Iterable<T>::Iterable (const Iterable<T>& from) noexcept\n:\n fRep_ (from.fRep_)\n {\n Require (fRep_.GetSharingState () != Memory::SharedByValue_State::eNull);\n }\n template <typename T>\n inline Iterable<T>::Iterable (Iterable<T>&& from) noexcept\n:\n fRep_ (std::move (from.fRep_))\n {\n Require (fRep_.GetSharingState () != Memory::SharedByValue_State::eNull);\n }\n template <typename T>\n inline Iterable<T>::Iterable (_SharedPtrIRep&& rep) noexcept\n:\n fRep_ (std::move (rep))\n {\n Require (fRep_.GetSharingState () != Memory::SharedByValue_State::eNull);\n }\n template <typename T>\n inline Iterable<T>::~Iterable ()\n {\n }\n template <typename T>\n inline Iterable<T>& Iterable<T>::operator= (const Iterable<T>& rhs)\n {\n RequireNotNull (rhs.fRep_.get ());\n fRep_ = rhs.fRep_;\n return *this;\n }\n template <typename T>\n inline typename Iterable<T>::_SharedPtrIRep Iterable<T>::Clone_ (const _IRep& rep, IteratorOwnerID forIterableEnvelope)\n {\n return rep.Clone (forIterableEnvelope);\n }\n template <typename T>\n inline Memory::SharedByValue_State Iterable<T>::_GetSharingState () const\n {\n return fRep_.GetSharingState ();\n }\n template <typename T>\n inline typename Iterable<T>::_IRep& Iterable<T>::_GetRep ()\n {\n \/\/EnsureNotNull (fRep_.get ());\n \/\/ subtle - but we must use the get () overload that allows passing in our Copy forward parameters\n \/\/ instead of using operator* (which doesnt allow passsing in the copy forward paramters).\n \/\/\n \/\/ Note - our copy forward paramters are the container envelope pointer\n return *(fRep_.get (this));\n }\n template <typename T>\n inline const typename Iterable<T>::_IRep& Iterable<T>::_GetRep () const\n {\n EnsureNotNull (fRep_.get ());\n return *fRep_;\n }\n template <typename T>\n inline const typename Iterable<T>::_IRep& Iterable<T>::_ConstGetRep () const\n {\n EnsureNotNull (fRep_.get ());\n return *fRep_;\n }\n template <typename T>\n inline Iterator<T> Iterable<T>::MakeIterator () const\n {\n return _GetRep ().MakeIterator (this);\n }\n template <typename T>\n inline size_t Iterable<T>::GetLength () const\n {\n return _GetRep ().GetLength ();\n }\n template <typename T>\n inline bool Iterable<T>::IsEmpty () const\n {\n return _GetRep ().IsEmpty ();\n }\n template <typename T>\n template <typename EQUALS_COMPARER>\n bool Iterable<T>::Contains (const T& element) const\n {\n for (T i : *this) {\n if (EQUALS_COMPARER::Equals (i, element)) {\n return true;\n }\n }\n return false;\n }\n template <typename T>\n template <typename RHS_CONTAINER_TYPE, typename EQUALS_COMPARER>\n bool Iterable<T>::SetEquals (const RHS_CONTAINER_TYPE& rhs) const\n {\n \/*\n * An extremely in-efficient but space-constant implementation. N^2 and check\n * a contains b and b contains a\n *\/\n for (auto ti : *this) {\n bool contained = false;\n for (auto ri : rhs) {\n if (EQUALS_COMPARER::Equals (ti, ri)) {\n contained = true;\n break;\n }\n }\n if (not contained) {\n return false;\n }\n }\n for (auto ri : rhs) {\n bool contained = false;\n for (auto ti : *this) {\n if (EQUALS_COMPARER::Equals (ti, ri)) {\n contained = true;\n break;\n }\n }\n if (not contained) {\n return false;\n }\n }\n return true;\n }\n template <typename T>\n template <typename RHS_CONTAINER_TYPE, typename EQUALS_COMPARER>\n bool Iterable<T>::MultiSetEquals (const RHS_CONTAINER_TYPE& rhs) const\n {\n auto tallyOf = [] (const Iterable<T>& c, T item) -> size_t {\n size_t total = 0;\n for (auto ti : c)\n {\n if (EQUALS_COMPARER::Equals (ti, item)) {\n total++;\n }\n }\n return total;\n };\n \/*\n * An extremely in-efficient but space-constant implementation. N^3 and check\n * a contains b and b contains a\n *\/\n for (auto ti : *this) {\n if (tallyOf (*this, ti) != tallyOf (rhs, ti)) {\n return false;\n }\n }\n for (auto ti : rhs) {\n if (tallyOf (*this, ti) != tallyOf (rhs, ti)) {\n return false;\n }\n }\n return true;\n }\n template <typename T>\n template <typename RHS_CONTAINER_TYPE, typename EQUALS_COMPARER>\n bool Iterable<T>::ExactEquals (const RHS_CONTAINER_TYPE& rhs) const\n {\n Iterator<T> li = MakeIterator ();\n Iterator<T> le = end ();\n auto ri = rhs.begin ();\n auto re = rhs.end ();\n for (; li != le and ri != re; ++ri, ++li) {\n if (not EQUALS_COMPARER::Equals (*li, *ri)) {\n return false;\n }\n }\n \/\/ only true if we get to end at the same time\n return li == le and ri == re;\n }\n template <typename T>\n inline bool Iterable<T>::empty () const\n {\n return IsEmpty ();\n }\n template <typename T>\n inline size_t Iterable<T>::length () const\n {\n return GetLength ();\n }\n template <typename T>\n inline size_t Iterable<T>::size () const\n {\n return GetLength ();\n }\n template <typename T>\n inline Iterator<T> Iterable<T>::begin () const\n {\n return MakeIterator ();\n }\n template <typename T>\n inline Iterator<T> Iterable<T>::end ()\n {\n return (Iterator<T>::GetEmptyIterator ());\n }\n template <typename T>\n inline void Iterable<T>::ApplyStatic (void (*doToElement) (const T& item)) const\n {\n RequireNotNull (doToElement);\n _GetRep ().Apply (doToElement);\n }\n template <typename T>\n inline void Iterable<T>::Apply (const function<void(const T& item)>& doToElement) const\n {\n RequireNotNull (doToElement);\n _GetRep ().Apply (doToElement);\n }\n template <typename T>\n inline Iterator<T> Iterable<T>::ApplyUntilTrue (const function<bool(const T& item)>& doToElement) const\n {\n RequireNotNull (doToElement);\n return _GetRep ().FindFirstThat (doToElement, this);\n }\n template <typename T>\n inline Iterator<T> Iterable<T>::ApplyUntilTrueStatic (bool (*doToElement) (const T& item)) const\n {\n RequireNotNull (doToElement);\n return _GetRep ().FindFirstThat (doToElement, this);\n }\n template <typename T>\n inline Iterator<T> Iterable<T>::FindFirstThat (const function<bool(const T& item)>& doToElement) const\n {\n RequireNotNull (doToElement);\n return _GetRep ().FindFirstThat (doToElement, this);\n }\n template <typename T>\n bool Iterable<T>::ContainsWith (const function<bool(const T& item)>& doToElement) const\n {\n for (T i : *this) {\n if (doToElement (i)) {\n return true;\n }\n }\n return false;\n }\n template <typename T>\n template <typename CONTAINER_OF_T>\n CONTAINER_OF_T Iterable<T>::As () const\n {\n return CONTAINER_OF_T (this->begin (), this->end ());\n }\n template <typename T>\n inline typename Iterable<T>::_ReadOnlyIterableIRepReference Iterable<T>::_GetReadOnlyIterableIRepReference () const\n {\n return _ReadOnlyIterableIRepReference (fRep_);\n }\n\n\n }\n }\n}\n#endif \/* _Stroika_Foundation_Traversal_Iterable_inl_ *\/\n<commit_msg>Assertions\/internal checking in Iterable wtih MOVE ctors<commit_after>\/*\n * Copyright(c) Sophist Solutions, Inc. 1990-2014. All rights reserved\n *\/\n#ifndef _Stroika_Foundation_Traversal_Iterable_inl_\n#define _Stroika_Foundation_Traversal_Iterable_inl_\n\n\n\/*\n ********************************************************************************\n ***************************** Implementation Details ***************************\n ********************************************************************************\n *\/\n#include \"..\/Debug\/Assertions.h\"\n\n\n\nnamespace Stroika {\n namespace Foundation {\n namespace Traversal {\n\n\n \/*\n ********************************************************************************\n *************************** Iterable<T>::_IRep *********************************\n ********************************************************************************\n *\/\n template <typename T>\n inline bool Iterable<T>::_IRep::_IsEmpty () const\n {\n return GetLength () == 0;\n }\n template <typename T>\n inline void Iterable<T>::_IRep::_Apply (_APPLY_ARGTYPE doToElement) const\n {\n RequireNotNull (doToElement);\n for (Iterator<T> i = MakeIterator (this); i != Iterable<T>::end (); ++i) {\n (doToElement) (*i);\n }\n }\n template <typename T>\n inline Iterator<T> Iterable<T>::_IRep::_FindFirstThat (_APPLYUNTIL_ARGTYPE doToElement, IteratorOwnerID suggestedOwner) const\n {\n RequireNotNull (doToElement);\n for (Iterator<T> i = MakeIterator (suggestedOwner); i != Iterable<T>::end (); ++i) {\n if ((doToElement) (*i)) {\n return i;\n }\n }\n return end ();\n }\n\n\n \/*\n ********************************************************************************\n ********************************** Iterable<T> *********************************\n ********************************************************************************\n *\/\n template <typename T>\n inline Iterable<T>::Iterable (const _SharedPtrIRep& rep) noexcept\n:\n fRep_ (rep)\n {\n Require (fRep_.GetSharingState () != Memory::SharedByValue_State::eNull);\n }\n template <typename T>\n inline Iterable<T>::Iterable (const Iterable<T>& from) noexcept\n:\n fRep_ (from.fRep_)\n {\n Require (fRep_.GetSharingState () != Memory::SharedByValue_State::eNull);\n }\n template <typename T>\n inline Iterable<T>::Iterable (Iterable<T>&& from) noexcept\n:\n fRep_ (std::move (from.fRep_))\n {\n Require (fRep_.GetSharingState () != Memory::SharedByValue_State::eNull);\n Require (from.fRep_ == nullptr); \/\/ after move\n }\n template <typename T>\n inline Iterable<T>::Iterable (_SharedPtrIRep&& rep) noexcept\n:\n fRep_ (std::move (rep))\n {\n Require (fRep_.GetSharingState () != Memory::SharedByValue_State::eNull);\n Require (rep == nullptr); \/\/ after move\n }\n template <typename T>\n inline Iterable<T>::~Iterable ()\n {\n }\n template <typename T>\n inline Iterable<T>& Iterable<T>::operator= (const Iterable<T>& rhs)\n {\n RequireNotNull (rhs.fRep_.get ());\n fRep_ = rhs.fRep_;\n return *this;\n }\n template <typename T>\n inline typename Iterable<T>::_SharedPtrIRep Iterable<T>::Clone_ (const _IRep& rep, IteratorOwnerID forIterableEnvelope)\n {\n return rep.Clone (forIterableEnvelope);\n }\n template <typename T>\n inline Memory::SharedByValue_State Iterable<T>::_GetSharingState () const\n {\n return fRep_.GetSharingState ();\n }\n template <typename T>\n inline typename Iterable<T>::_IRep& Iterable<T>::_GetRep ()\n {\n \/\/EnsureNotNull (fRep_.get ());\n \/\/ subtle - but we must use the get () overload that allows passing in our Copy forward parameters\n \/\/ instead of using operator* (which doesnt allow passsing in the copy forward paramters).\n \/\/\n \/\/ Note - our copy forward paramters are the container envelope pointer\n return *(fRep_.get (this));\n }\n template <typename T>\n inline const typename Iterable<T>::_IRep& Iterable<T>::_GetRep () const\n {\n EnsureNotNull (fRep_.get ());\n return *fRep_;\n }\n template <typename T>\n inline const typename Iterable<T>::_IRep& Iterable<T>::_ConstGetRep () const\n {\n EnsureNotNull (fRep_.get ());\n return *fRep_;\n }\n template <typename T>\n inline Iterator<T> Iterable<T>::MakeIterator () const\n {\n return _GetRep ().MakeIterator (this);\n }\n template <typename T>\n inline size_t Iterable<T>::GetLength () const\n {\n return _GetRep ().GetLength ();\n }\n template <typename T>\n inline bool Iterable<T>::IsEmpty () const\n {\n return _GetRep ().IsEmpty ();\n }\n template <typename T>\n template <typename EQUALS_COMPARER>\n bool Iterable<T>::Contains (const T& element) const\n {\n for (T i : *this) {\n if (EQUALS_COMPARER::Equals (i, element)) {\n return true;\n }\n }\n return false;\n }\n template <typename T>\n template <typename RHS_CONTAINER_TYPE, typename EQUALS_COMPARER>\n bool Iterable<T>::SetEquals (const RHS_CONTAINER_TYPE& rhs) const\n {\n \/*\n * An extremely in-efficient but space-constant implementation. N^2 and check\n * a contains b and b contains a\n *\/\n for (auto ti : *this) {\n bool contained = false;\n for (auto ri : rhs) {\n if (EQUALS_COMPARER::Equals (ti, ri)) {\n contained = true;\n break;\n }\n }\n if (not contained) {\n return false;\n }\n }\n for (auto ri : rhs) {\n bool contained = false;\n for (auto ti : *this) {\n if (EQUALS_COMPARER::Equals (ti, ri)) {\n contained = true;\n break;\n }\n }\n if (not contained) {\n return false;\n }\n }\n return true;\n }\n template <typename T>\n template <typename RHS_CONTAINER_TYPE, typename EQUALS_COMPARER>\n bool Iterable<T>::MultiSetEquals (const RHS_CONTAINER_TYPE& rhs) const\n {\n auto tallyOf = [] (const Iterable<T>& c, T item) -> size_t {\n size_t total = 0;\n for (auto ti : c)\n {\n if (EQUALS_COMPARER::Equals (ti, item)) {\n total++;\n }\n }\n return total;\n };\n \/*\n * An extremely in-efficient but space-constant implementation. N^3 and check\n * a contains b and b contains a\n *\/\n for (auto ti : *this) {\n if (tallyOf (*this, ti) != tallyOf (rhs, ti)) {\n return false;\n }\n }\n for (auto ti : rhs) {\n if (tallyOf (*this, ti) != tallyOf (rhs, ti)) {\n return false;\n }\n }\n return true;\n }\n template <typename T>\n template <typename RHS_CONTAINER_TYPE, typename EQUALS_COMPARER>\n bool Iterable<T>::ExactEquals (const RHS_CONTAINER_TYPE& rhs) const\n {\n Iterator<T> li = MakeIterator ();\n Iterator<T> le = end ();\n auto ri = rhs.begin ();\n auto re = rhs.end ();\n for (; li != le and ri != re; ++ri, ++li) {\n if (not EQUALS_COMPARER::Equals (*li, *ri)) {\n return false;\n }\n }\n \/\/ only true if we get to end at the same time\n return li == le and ri == re;\n }\n template <typename T>\n inline bool Iterable<T>::empty () const\n {\n return IsEmpty ();\n }\n template <typename T>\n inline size_t Iterable<T>::length () const\n {\n return GetLength ();\n }\n template <typename T>\n inline size_t Iterable<T>::size () const\n {\n return GetLength ();\n }\n template <typename T>\n inline Iterator<T> Iterable<T>::begin () const\n {\n return MakeIterator ();\n }\n template <typename T>\n inline Iterator<T> Iterable<T>::end ()\n {\n return (Iterator<T>::GetEmptyIterator ());\n }\n template <typename T>\n inline void Iterable<T>::ApplyStatic (void (*doToElement) (const T& item)) const\n {\n RequireNotNull (doToElement);\n _GetRep ().Apply (doToElement);\n }\n template <typename T>\n inline void Iterable<T>::Apply (const function<void(const T& item)>& doToElement) const\n {\n RequireNotNull (doToElement);\n _GetRep ().Apply (doToElement);\n }\n template <typename T>\n inline Iterator<T> Iterable<T>::ApplyUntilTrue (const function<bool(const T& item)>& doToElement) const\n {\n RequireNotNull (doToElement);\n return _GetRep ().FindFirstThat (doToElement, this);\n }\n template <typename T>\n inline Iterator<T> Iterable<T>::ApplyUntilTrueStatic (bool (*doToElement) (const T& item)) const\n {\n RequireNotNull (doToElement);\n return _GetRep ().FindFirstThat (doToElement, this);\n }\n template <typename T>\n inline Iterator<T> Iterable<T>::FindFirstThat (const function<bool(const T& item)>& doToElement) const\n {\n RequireNotNull (doToElement);\n return _GetRep ().FindFirstThat (doToElement, this);\n }\n template <typename T>\n bool Iterable<T>::ContainsWith (const function<bool(const T& item)>& doToElement) const\n {\n for (T i : *this) {\n if (doToElement (i)) {\n return true;\n }\n }\n return false;\n }\n template <typename T>\n template <typename CONTAINER_OF_T>\n CONTAINER_OF_T Iterable<T>::As () const\n {\n return CONTAINER_OF_T (this->begin (), this->end ());\n }\n template <typename T>\n inline typename Iterable<T>::_ReadOnlyIterableIRepReference Iterable<T>::_GetReadOnlyIterableIRepReference () const\n {\n return _ReadOnlyIterableIRepReference (fRep_);\n }\n\n\n }\n }\n}\n#endif \/* _Stroika_Foundation_Traversal_Iterable_inl_ *\/\n<|endoftext|>"} {"text":"<commit_before>\/\/---------------------------------------------------------------------------\n\/\/ $Id$\n\/\/ Version: $Name$\n\/\/\n\/\/ Copyright (C) 2005, 2006, 2008, 2009, 2010, 2011, 2012 by the deal.II authors\n\/\/\n\/\/ This file is subject to QPL and may not be distributed\n\/\/ without copyright and license information. Please refer\n\/\/ to the file deal.II\/doc\/license.html for the text and\n\/\/ further information on this license.\n\/\/\n\/\/---------------------------------------------------------------------------\n\n#include <deal.II\/base\/mpi.h>\n#include <deal.II\/base\/utilities.h>\n#include <deal.II\/base\/exceptions.h>\n\n#include <cstddef>\n#include <iostream>\n\n#ifdef DEAL_II_USE_TRILINOS\n# ifdef DEAL_II_COMPILER_SUPPORTS_MPI\n# include <Epetra_MpiComm.h>\n# include <deal.II\/lac\/vector_memory.h>\n# include <deal.II\/lac\/trilinos_vector.h>\n# include <deal.II\/lac\/trilinos_block_vector.h>\n# endif\n#endif\n\n#ifdef DEAL_II_USE_PETSC\n# ifdef DEAL_II_COMPILER_SUPPORTS_MPI\n# include <petscsys.h>\n#include <deal.II\/lac\/petsc_block_vector.h>\n#include <deal.II\/lac\/petsc_parallel_block_vector.h>\n#include <deal.II\/lac\/petsc_vector.h>\n#include <deal.II\/lac\/petsc_parallel_vector.h>\n# endif\n#endif\n\n\nDEAL_II_NAMESPACE_OPEN\n\n\nnamespace Utilities\n{\n\n namespace MPI\n {\n#ifdef DEAL_II_COMPILER_SUPPORTS_MPI\n \/\/ Unfortunately, we have to work\n \/\/ around an oddity in the way PETSc\n \/\/ and some gcc versions interact. If\n \/\/ we use PETSc's MPI dummy\n \/\/ implementation, it expands the\n \/\/ calls to the two MPI functions\n \/\/ basically as ``(n_jobs=1, 0)'',\n \/\/ i.e. it assigns the number one to\n \/\/ the variable holding the number of\n \/\/ jobs, and then uses the comma\n \/\/ operator to let the entire\n \/\/ expression have the value zero. The\n \/\/ latter is important, since\n \/\/ ``MPI_Comm_size'' returns an error\n \/\/ code that we may want to check (we\n \/\/ don't here, but one could in\n \/\/ principle), and the trick with the\n \/\/ comma operator makes sure that both\n \/\/ the number of jobs is correctly\n \/\/ assigned, and the return value is\n \/\/ zero. Unfortunately, if some recent\n \/\/ versions of gcc detect that the\n \/\/ comma expression just stands by\n \/\/ itself, i.e. the result is not\n \/\/ assigned to another variable, then\n \/\/ they warn ``right-hand operand of\n \/\/ comma has no effect''. This\n \/\/ unwanted side effect can be\n \/\/ suppressed by casting the result of\n \/\/ the entire expression to type\n \/\/ ``void'' -- not beautiful, but\n \/\/ helps calming down unwarranted\n \/\/ compiler warnings...\n unsigned int n_mpi_processes (const MPI_Comm &mpi_communicator)\n {\n int n_jobs=1;\n (void) MPI_Comm_size (mpi_communicator, &n_jobs);\n\n return n_jobs;\n }\n\n\n unsigned int this_mpi_process (const MPI_Comm &mpi_communicator)\n {\n int rank=0;\n (void) MPI_Comm_rank (mpi_communicator, &rank);\n\n return rank;\n }\n\n\n MPI_Comm duplicate_communicator (const MPI_Comm &mpi_communicator)\n {\n MPI_Comm new_communicator;\n MPI_Comm_dup (mpi_communicator, &new_communicator);\n return new_communicator;\n }\n\n\n std::vector<unsigned int>\n compute_point_to_point_communication_pattern (const MPI_Comm & mpi_comm,\n const std::vector<unsigned int> & destinations)\n {\n unsigned int myid = Utilities::MPI::this_mpi_process(mpi_comm);\n unsigned int n_procs = Utilities::MPI::n_mpi_processes(mpi_comm);\n\n for (unsigned int i=0; i<destinations.size(); ++i)\n {\n Assert (destinations[i] < n_procs,\n ExcIndexRange (destinations[i], 0, n_procs));\n Assert (destinations[i] != myid,\n ExcMessage (\"There is no point in communicating with ourselves.\"));\n }\n\n\n \/\/ let all processors\n \/\/ communicate the maximal\n \/\/ number of destinations they\n \/\/ have\n const unsigned int max_n_destinations\n = Utilities::MPI::max (destinations.size(), mpi_comm);\n\n \/\/ now that we know the number\n \/\/ of data packets every\n \/\/ processor wants to send, set\n \/\/ up a buffer with the maximal\n \/\/ size and copy our\n \/\/ destinations in there,\n \/\/ padded with -1's\n std::vector<unsigned int> my_destinations(max_n_destinations,\n numbers::invalid_unsigned_int);\n std::copy (destinations.begin(), destinations.end(),\n my_destinations.begin());\n\n \/\/ now exchange these (we could\n \/\/ communicate less data if we\n \/\/ used MPI_Allgatherv, but\n \/\/ we'd have to communicate\n \/\/ my_n_destinations to all\n \/\/ processors in this case,\n \/\/ which is more expensive than\n \/\/ the reduction operation\n \/\/ above in MPI_Allreduce)\n std::vector<unsigned int> all_destinations (max_n_destinations * n_procs);\n MPI_Allgather (&my_destinations[0], max_n_destinations, MPI_UNSIGNED,\n &all_destinations[0], max_n_destinations, MPI_UNSIGNED,\n mpi_comm);\n\n \/\/ now we know who is going to\n \/\/ communicate with\n \/\/ whom. collect who is going\n \/\/ to communicate with us!\n std::vector<unsigned int> origins;\n for (unsigned int i=0; i<n_procs; ++i)\n for (unsigned int j=0; j<max_n_destinations; ++j)\n if (all_destinations[i*max_n_destinations + j] == myid)\n origins.push_back (i);\n else if (all_destinations[i*max_n_destinations + j] ==\n numbers::invalid_unsigned_int)\n break;\n\n return origins;\n }\n\n\n namespace\n {\n \/\/ custom MIP_Op for\n \/\/ calculate_collective_mpi_min_max_avg\n void max_reduce ( const void * in_lhs_,\n void * inout_rhs_,\n int * len,\n MPI_Datatype * )\n {\n const MinMaxAvg * in_lhs = static_cast<const MinMaxAvg*>(in_lhs_);\n MinMaxAvg * inout_rhs = static_cast<MinMaxAvg*>(inout_rhs_);\n\n Assert(*len==1, ExcInternalError());\n\n inout_rhs->sum += in_lhs->sum;\n if (inout_rhs->min>in_lhs->min)\n {\n inout_rhs->min = in_lhs->min;\n inout_rhs->min_index = in_lhs->min_index;\n }\n else if (inout_rhs->min == in_lhs->min)\n { \/\/ choose lower cpu index when tied to make operator cumutative\n if (inout_rhs->min_index > in_lhs->min_index)\n inout_rhs->min_index = in_lhs->min_index;\n }\n\n if (inout_rhs->max < in_lhs->max)\n {\n inout_rhs->max = in_lhs->max;\n inout_rhs->max_index = in_lhs->max_index;\n }\n else if (inout_rhs->max == in_lhs->max)\n { \/\/ choose lower cpu index when tied to make operator cumutative\n if (inout_rhs->max_index > in_lhs->max_index)\n inout_rhs->max_index = in_lhs->max_index;\n }\n }\n }\n\n\n\n MinMaxAvg\n min_max_avg(const double my_value,\n const MPI_Comm &mpi_communicator)\n {\n MinMaxAvg result;\n\n const unsigned int my_id\n = dealii::Utilities::MPI::this_mpi_process(mpi_communicator);\n const unsigned int numproc\n = dealii::Utilities::MPI::n_mpi_processes(mpi_communicator);\n\n MPI_Op op;\n int ierr = MPI_Op_create((MPI_User_function *)&max_reduce, true, &op);\n AssertThrow(ierr == MPI_SUCCESS, ExcInternalError());\n\n MinMaxAvg in;\n in.sum = in.min = in.max = my_value;\n in.min_index = in.max_index = my_id;\n\n MPI_Datatype type;\n int lengths[]={3,2};\n MPI_Aint displacements[]={0,offsetof(MinMaxAvg, min_index)};\n MPI_Datatype types[]={MPI_DOUBLE, MPI_INT};\n\n ierr = MPI_Type_struct(2, lengths, displacements, types, &type);\n AssertThrow(ierr == MPI_SUCCESS, ExcInternalError());\n\n ierr = MPI_Type_commit(&type);\n ierr = MPI_Allreduce (&in, &result, 1, type, op, mpi_communicator);\n AssertThrow(ierr == MPI_SUCCESS, ExcInternalError());\n\n ierr = MPI_Type_free (&type);\n AssertThrow(ierr == MPI_SUCCESS, ExcInternalError());\n\n ierr = MPI_Op_free(&op);\n AssertThrow(ierr == MPI_SUCCESS, ExcInternalError());\n\n result.avg = result.sum \/ numproc;\n\n return result;\n }\n\n#else\n\n unsigned int n_mpi_processes (const MPI_Comm &)\n {\n return 1;\n }\n\n\n\n unsigned int this_mpi_process (const MPI_Comm &)\n {\n return 0;\n }\n\n\n MPI_Comm duplicate_communicator (const MPI_Comm &mpi_communicator)\n {\n return mpi_communicator;\n }\n\n\n\n\n MinMaxAvg\n min_max_avg(const double my_value,\n const MPI_Comm &)\n {\n MinMaxAvg result;\n\n result.sum = my_value;\n result.avg = my_value;\n result.min = my_value;\n result.max = my_value;\n result.min_index = 0;\n result.max_index = 0;\n\n return result;\n }\n\n#endif\n\n\n\n\n MPI_InitFinalize::MPI_InitFinalize (int &argc,\n char** &argv)\n :\n owns_mpi (true)\n {\n static bool constructor_has_already_run = false;\n Assert (constructor_has_already_run == false,\n ExcMessage (\"You can only create a single object of this class \"\n \"in a program since it initializes the MPI system.\"));\n\n#ifdef DEAL_II_COMPILER_SUPPORTS_MPI\n \/\/ if we have PETSc, we will initialize it and let it handle MPI.\n \/\/ Otherwise, we will do it.\n#ifdef DEAL_II_USE_PETSC\n PetscInitialize(&argc, &argv, PETSC_NULL, PETSC_NULL);\n#else\n int MPI_has_been_started = 0;\n MPI_Initialized(&MPI_has_been_started);\n AssertThrow (MPI_has_been_started == 0,\n ExcMessage (\"MPI error. You can only start MPI once!\"));\n\n int mpi_err;\n mpi_err = MPI_Init (&argc, &argv);\n AssertThrow (mpi_err == 0,\n ExcMessage (\"MPI could not be initialized.\"));\n#endif\n#else\n \/\/ make sure the compiler doesn't warn\n \/\/ about these variables\n (void)argc;\n (void)argv;\n#endif\n\n constructor_has_already_run = true;\n }\n\n\n MPI_InitFinalize::~MPI_InitFinalize()\n {\n#ifdef DEAL_II_COMPILER_SUPPORTS_MPI\n\n \/\/ make memory pool release all\n \/\/ vectors that are no longer\n \/\/ used at this point. this is\n \/\/ relevant because the static\n \/\/ object destructors run for\n \/\/ these vectors at the end of\n \/\/ the program would run after\n \/\/ MPI_Finalize is called,\n \/\/ leading to errors\n \/\/\n# if defined(DEAL_II_USE_TRILINOS) && !defined(__APPLE__)\n \/\/ TODO: On Mac OS X, shared libs can\n \/\/ only depend on other libs listed\n \/\/ later on the command line. This\n \/\/ means that libbase can't depend on\n \/\/ liblac, and we can't destroy the\n \/\/ memory pool here as long as we have\n \/\/ separate libraries. Consequently,\n \/\/ the #ifdef above. Deal will then\n \/\/ just continue to seg fault upon\n \/\/ completion of main()\n GrowingVectorMemory<TrilinosWrappers::MPI::Vector>\n ::release_unused_memory ();\n GrowingVectorMemory<TrilinosWrappers::MPI::BlockVector>\n ::release_unused_memory ();\n# endif\n\n\t\t\t\t \/\/ Same for PETSc.\n#ifdef DEAL_II_USE_PETSC\n GrowingVectorMemory<PETScWrappers::MPI::Vector>\n ::release_unused_memory ();\n GrowingVectorMemory<PETScWrappers::MPI::BlockVector>\n ::release_unused_memory ();\n GrowingVectorMemory<PETScWrappers::Vector>\n ::release_unused_memory ();\n GrowingVectorMemory<PETScWrappers::BlockVector>\n ::release_unused_memory ();\n\n\t\t\t\t \/\/ now end PETSc.\n PetscFinalize();\n#else\n\n\n int mpi_err = 0;\n\n int MPI_has_been_started = 0;\n MPI_Initialized(&MPI_has_been_started);\n if (Utilities::System::program_uses_mpi() == true && owns_mpi == true &&\n MPI_has_been_started != 0)\n {\n if (std::uncaught_exception())\n {\n std::cerr << \"ERROR: Uncaught exception in MPI_InitFinalize on proc \"\n << this_mpi_process(MPI_COMM_WORLD)\n << \". Skipping MPI_Finalize() to avoid a deadlock.\"\n << std::endl;\n }\n else\n mpi_err = MPI_Finalize();\n }\n\n\n AssertThrow (mpi_err == 0,\n ExcMessage (\"An error occurred while calling MPI_Finalize()\"));\n#endif\n#endif\n }\n\n\n } \/\/ end of namespace MPI\n\n} \/\/ end of namespace Utilities\n\nDEAL_II_NAMESPACE_CLOSE\n<commit_msg>Add missing vector_memory header (for PETSc).<commit_after>\/\/---------------------------------------------------------------------------\n\/\/ $Id$\n\/\/ Version: $Name$\n\/\/\n\/\/ Copyright (C) 2005, 2006, 2008, 2009, 2010, 2011, 2012 by the deal.II authors\n\/\/\n\/\/ This file is subject to QPL and may not be distributed\n\/\/ without copyright and license information. Please refer\n\/\/ to the file deal.II\/doc\/license.html for the text and\n\/\/ further information on this license.\n\/\/\n\/\/---------------------------------------------------------------------------\n\n#include <deal.II\/base\/mpi.h>\n#include <deal.II\/base\/utilities.h>\n#include <deal.II\/base\/exceptions.h>\n\n#include <cstddef>\n#include <iostream>\n\n#ifdef DEAL_II_USE_TRILINOS\n# ifdef DEAL_II_COMPILER_SUPPORTS_MPI\n# include <Epetra_MpiComm.h>\n# include <deal.II\/lac\/vector_memory.h>\n# include <deal.II\/lac\/trilinos_vector.h>\n# include <deal.II\/lac\/trilinos_block_vector.h>\n# endif\n#endif\n\n#ifdef DEAL_II_USE_PETSC\n# ifdef DEAL_II_COMPILER_SUPPORTS_MPI\n# include <petscsys.h>\n#include <deal.II\/lac\/vector_memory.h>\n#include <deal.II\/lac\/petsc_block_vector.h>\n#include <deal.II\/lac\/petsc_parallel_block_vector.h>\n#include <deal.II\/lac\/petsc_vector.h>\n#include <deal.II\/lac\/petsc_parallel_vector.h>\n# endif\n#endif\n\n\nDEAL_II_NAMESPACE_OPEN\n\n\nnamespace Utilities\n{\n\n namespace MPI\n {\n#ifdef DEAL_II_COMPILER_SUPPORTS_MPI\n \/\/ Unfortunately, we have to work\n \/\/ around an oddity in the way PETSc\n \/\/ and some gcc versions interact. If\n \/\/ we use PETSc's MPI dummy\n \/\/ implementation, it expands the\n \/\/ calls to the two MPI functions\n \/\/ basically as ``(n_jobs=1, 0)'',\n \/\/ i.e. it assigns the number one to\n \/\/ the variable holding the number of\n \/\/ jobs, and then uses the comma\n \/\/ operator to let the entire\n \/\/ expression have the value zero. The\n \/\/ latter is important, since\n \/\/ ``MPI_Comm_size'' returns an error\n \/\/ code that we may want to check (we\n \/\/ don't here, but one could in\n \/\/ principle), and the trick with the\n \/\/ comma operator makes sure that both\n \/\/ the number of jobs is correctly\n \/\/ assigned, and the return value is\n \/\/ zero. Unfortunately, if some recent\n \/\/ versions of gcc detect that the\n \/\/ comma expression just stands by\n \/\/ itself, i.e. the result is not\n \/\/ assigned to another variable, then\n \/\/ they warn ``right-hand operand of\n \/\/ comma has no effect''. This\n \/\/ unwanted side effect can be\n \/\/ suppressed by casting the result of\n \/\/ the entire expression to type\n \/\/ ``void'' -- not beautiful, but\n \/\/ helps calming down unwarranted\n \/\/ compiler warnings...\n unsigned int n_mpi_processes (const MPI_Comm &mpi_communicator)\n {\n int n_jobs=1;\n (void) MPI_Comm_size (mpi_communicator, &n_jobs);\n\n return n_jobs;\n }\n\n\n unsigned int this_mpi_process (const MPI_Comm &mpi_communicator)\n {\n int rank=0;\n (void) MPI_Comm_rank (mpi_communicator, &rank);\n\n return rank;\n }\n\n\n MPI_Comm duplicate_communicator (const MPI_Comm &mpi_communicator)\n {\n MPI_Comm new_communicator;\n MPI_Comm_dup (mpi_communicator, &new_communicator);\n return new_communicator;\n }\n\n\n std::vector<unsigned int>\n compute_point_to_point_communication_pattern (const MPI_Comm & mpi_comm,\n const std::vector<unsigned int> & destinations)\n {\n unsigned int myid = Utilities::MPI::this_mpi_process(mpi_comm);\n unsigned int n_procs = Utilities::MPI::n_mpi_processes(mpi_comm);\n\n for (unsigned int i=0; i<destinations.size(); ++i)\n {\n Assert (destinations[i] < n_procs,\n ExcIndexRange (destinations[i], 0, n_procs));\n Assert (destinations[i] != myid,\n ExcMessage (\"There is no point in communicating with ourselves.\"));\n }\n\n\n \/\/ let all processors\n \/\/ communicate the maximal\n \/\/ number of destinations they\n \/\/ have\n const unsigned int max_n_destinations\n = Utilities::MPI::max (destinations.size(), mpi_comm);\n\n \/\/ now that we know the number\n \/\/ of data packets every\n \/\/ processor wants to send, set\n \/\/ up a buffer with the maximal\n \/\/ size and copy our\n \/\/ destinations in there,\n \/\/ padded with -1's\n std::vector<unsigned int> my_destinations(max_n_destinations,\n numbers::invalid_unsigned_int);\n std::copy (destinations.begin(), destinations.end(),\n my_destinations.begin());\n\n \/\/ now exchange these (we could\n \/\/ communicate less data if we\n \/\/ used MPI_Allgatherv, but\n \/\/ we'd have to communicate\n \/\/ my_n_destinations to all\n \/\/ processors in this case,\n \/\/ which is more expensive than\n \/\/ the reduction operation\n \/\/ above in MPI_Allreduce)\n std::vector<unsigned int> all_destinations (max_n_destinations * n_procs);\n MPI_Allgather (&my_destinations[0], max_n_destinations, MPI_UNSIGNED,\n &all_destinations[0], max_n_destinations, MPI_UNSIGNED,\n mpi_comm);\n\n \/\/ now we know who is going to\n \/\/ communicate with\n \/\/ whom. collect who is going\n \/\/ to communicate with us!\n std::vector<unsigned int> origins;\n for (unsigned int i=0; i<n_procs; ++i)\n for (unsigned int j=0; j<max_n_destinations; ++j)\n if (all_destinations[i*max_n_destinations + j] == myid)\n origins.push_back (i);\n else if (all_destinations[i*max_n_destinations + j] ==\n numbers::invalid_unsigned_int)\n break;\n\n return origins;\n }\n\n\n namespace\n {\n \/\/ custom MIP_Op for\n \/\/ calculate_collective_mpi_min_max_avg\n void max_reduce ( const void * in_lhs_,\n void * inout_rhs_,\n int * len,\n MPI_Datatype * )\n {\n const MinMaxAvg * in_lhs = static_cast<const MinMaxAvg*>(in_lhs_);\n MinMaxAvg * inout_rhs = static_cast<MinMaxAvg*>(inout_rhs_);\n\n Assert(*len==1, ExcInternalError());\n\n inout_rhs->sum += in_lhs->sum;\n if (inout_rhs->min>in_lhs->min)\n {\n inout_rhs->min = in_lhs->min;\n inout_rhs->min_index = in_lhs->min_index;\n }\n else if (inout_rhs->min == in_lhs->min)\n { \/\/ choose lower cpu index when tied to make operator cumutative\n if (inout_rhs->min_index > in_lhs->min_index)\n inout_rhs->min_index = in_lhs->min_index;\n }\n\n if (inout_rhs->max < in_lhs->max)\n {\n inout_rhs->max = in_lhs->max;\n inout_rhs->max_index = in_lhs->max_index;\n }\n else if (inout_rhs->max == in_lhs->max)\n { \/\/ choose lower cpu index when tied to make operator cumutative\n if (inout_rhs->max_index > in_lhs->max_index)\n inout_rhs->max_index = in_lhs->max_index;\n }\n }\n }\n\n\n\n MinMaxAvg\n min_max_avg(const double my_value,\n const MPI_Comm &mpi_communicator)\n {\n MinMaxAvg result;\n\n const unsigned int my_id\n = dealii::Utilities::MPI::this_mpi_process(mpi_communicator);\n const unsigned int numproc\n = dealii::Utilities::MPI::n_mpi_processes(mpi_communicator);\n\n MPI_Op op;\n int ierr = MPI_Op_create((MPI_User_function *)&max_reduce, true, &op);\n AssertThrow(ierr == MPI_SUCCESS, ExcInternalError());\n\n MinMaxAvg in;\n in.sum = in.min = in.max = my_value;\n in.min_index = in.max_index = my_id;\n\n MPI_Datatype type;\n int lengths[]={3,2};\n MPI_Aint displacements[]={0,offsetof(MinMaxAvg, min_index)};\n MPI_Datatype types[]={MPI_DOUBLE, MPI_INT};\n\n ierr = MPI_Type_struct(2, lengths, displacements, types, &type);\n AssertThrow(ierr == MPI_SUCCESS, ExcInternalError());\n\n ierr = MPI_Type_commit(&type);\n ierr = MPI_Allreduce (&in, &result, 1, type, op, mpi_communicator);\n AssertThrow(ierr == MPI_SUCCESS, ExcInternalError());\n\n ierr = MPI_Type_free (&type);\n AssertThrow(ierr == MPI_SUCCESS, ExcInternalError());\n\n ierr = MPI_Op_free(&op);\n AssertThrow(ierr == MPI_SUCCESS, ExcInternalError());\n\n result.avg = result.sum \/ numproc;\n\n return result;\n }\n\n#else\n\n unsigned int n_mpi_processes (const MPI_Comm &)\n {\n return 1;\n }\n\n\n\n unsigned int this_mpi_process (const MPI_Comm &)\n {\n return 0;\n }\n\n\n MPI_Comm duplicate_communicator (const MPI_Comm &mpi_communicator)\n {\n return mpi_communicator;\n }\n\n\n\n\n MinMaxAvg\n min_max_avg(const double my_value,\n const MPI_Comm &)\n {\n MinMaxAvg result;\n\n result.sum = my_value;\n result.avg = my_value;\n result.min = my_value;\n result.max = my_value;\n result.min_index = 0;\n result.max_index = 0;\n\n return result;\n }\n\n#endif\n\n\n\n\n MPI_InitFinalize::MPI_InitFinalize (int &argc,\n char** &argv)\n :\n owns_mpi (true)\n {\n static bool constructor_has_already_run = false;\n Assert (constructor_has_already_run == false,\n ExcMessage (\"You can only create a single object of this class \"\n \"in a program since it initializes the MPI system.\"));\n\n#ifdef DEAL_II_COMPILER_SUPPORTS_MPI\n \/\/ if we have PETSc, we will initialize it and let it handle MPI.\n \/\/ Otherwise, we will do it.\n#ifdef DEAL_II_USE_PETSC\n PetscInitialize(&argc, &argv, PETSC_NULL, PETSC_NULL);\n#else\n int MPI_has_been_started = 0;\n MPI_Initialized(&MPI_has_been_started);\n AssertThrow (MPI_has_been_started == 0,\n ExcMessage (\"MPI error. You can only start MPI once!\"));\n\n int mpi_err;\n mpi_err = MPI_Init (&argc, &argv);\n AssertThrow (mpi_err == 0,\n ExcMessage (\"MPI could not be initialized.\"));\n#endif\n#else\n \/\/ make sure the compiler doesn't warn\n \/\/ about these variables\n (void)argc;\n (void)argv;\n#endif\n\n constructor_has_already_run = true;\n }\n\n\n MPI_InitFinalize::~MPI_InitFinalize()\n {\n#ifdef DEAL_II_COMPILER_SUPPORTS_MPI\n\n \/\/ make memory pool release all\n \/\/ vectors that are no longer\n \/\/ used at this point. this is\n \/\/ relevant because the static\n \/\/ object destructors run for\n \/\/ these vectors at the end of\n \/\/ the program would run after\n \/\/ MPI_Finalize is called,\n \/\/ leading to errors\n \/\/\n# if defined(DEAL_II_USE_TRILINOS) && !defined(__APPLE__)\n \/\/ TODO: On Mac OS X, shared libs can\n \/\/ only depend on other libs listed\n \/\/ later on the command line. This\n \/\/ means that libbase can't depend on\n \/\/ liblac, and we can't destroy the\n \/\/ memory pool here as long as we have\n \/\/ separate libraries. Consequently,\n \/\/ the #ifdef above. Deal will then\n \/\/ just continue to seg fault upon\n \/\/ completion of main()\n GrowingVectorMemory<TrilinosWrappers::MPI::Vector>\n ::release_unused_memory ();\n GrowingVectorMemory<TrilinosWrappers::MPI::BlockVector>\n ::release_unused_memory ();\n# endif\n\n\t\t\t\t \/\/ Same for PETSc.\n#ifdef DEAL_II_USE_PETSC\n GrowingVectorMemory<PETScWrappers::MPI::Vector>\n ::release_unused_memory ();\n GrowingVectorMemory<PETScWrappers::MPI::BlockVector>\n ::release_unused_memory ();\n GrowingVectorMemory<PETScWrappers::Vector>\n ::release_unused_memory ();\n GrowingVectorMemory<PETScWrappers::BlockVector>\n ::release_unused_memory ();\n\n\t\t\t\t \/\/ now end PETSc.\n PetscFinalize();\n#else\n\n\n int mpi_err = 0;\n\n int MPI_has_been_started = 0;\n MPI_Initialized(&MPI_has_been_started);\n if (Utilities::System::program_uses_mpi() == true && owns_mpi == true &&\n MPI_has_been_started != 0)\n {\n if (std::uncaught_exception())\n {\n std::cerr << \"ERROR: Uncaught exception in MPI_InitFinalize on proc \"\n << this_mpi_process(MPI_COMM_WORLD)\n << \". Skipping MPI_Finalize() to avoid a deadlock.\"\n << std::endl;\n }\n else\n mpi_err = MPI_Finalize();\n }\n\n\n AssertThrow (mpi_err == 0,\n ExcMessage (\"An error occurred while calling MPI_Finalize()\"));\n#endif\n#endif\n }\n\n\n } \/\/ end of namespace MPI\n\n} \/\/ end of namespace Utilities\n\nDEAL_II_NAMESPACE_CLOSE\n<|endoftext|>"} {"text":"<commit_before>#include \"VoronoiCell.h\"\n\/\/#include \"Cognition\/Modules\/Modeling\/PathPlanner\/AStarSearchParameters.h\"\n\n\n<commit_msg>Deleted empty file to remove Linker Warning<commit_after><|endoftext|>"} {"text":"<commit_before>\/*\nCopyright 2017 creatorlxd\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\nhttp:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n#include \"stdafx.h\"\n#include \"..\/Include\/BoundingBox.h\" \n\nSpaceGameEngine::AxisAlignedBoundingBox::AxisAlignedBoundingBox()\n{\n\tm_MinPosition = XMFLOAT3(0, 0, 0);\n\tm_MaxPosition = XMFLOAT3(0, 0, 0);\n}\n\nSpaceGameEngine::AxisAlignedBoundingBox::AxisAlignedBoundingBox(const XMFLOAT3 & minl, const XMFLOAT3 & maxl)\n{\n\tm_MinPosition = minl;\n\tm_MaxPosition = maxl;\n}\n\nbool SpaceGameEngine::IfIntersect(const AxisAlignedBoundingBox & aabb1, const AxisAlignedBoundingBox & aabb2)\n{\n\tif (aabb1.m_MinPosition.x >= aabb2.m_MaxPosition.x || aabb1.m_MaxPosition.x <= aabb2.m_MinPosition.x)\n\t\treturn false;\n\tif (aabb1.m_MinPosition.y >= aabb2.m_MaxPosition.y || aabb1.m_MaxPosition.y <= aabb2.m_MinPosition.y)\n\t\treturn false;\n\tif (aabb1.m_MinPosition.z >= aabb2.m_MaxPosition.z || aabb1.m_MaxPosition.z <= aabb2.m_MinPosition.z)\n\t\treturn false;\n\treturn true;\n}\n\nbool SpaceGameEngine::IfInclude(const AxisAlignedBoundingBox & aabb, const XMFLOAT3 & position)\n{\n\tif (aabb.m_MinPosition.x > position.x || aabb.m_MaxPosition.x < position.x)\n\t\treturn false;\n\tif (aabb.m_MinPosition.y > position.y || aabb.m_MaxPosition.y < position.y)\n\t\treturn false;\n\tif (aabb.m_MinPosition.z > position.z || aabb.m_MaxPosition.z < position.z)\n\t\treturn false;\n\treturn true;\n}\n\nbool SpaceGameEngine::IfInclude(const AxisAlignedBoundingBox & aabb1, const AxisAlignedBoundingBox & aabb2)\n{\n\tif ((aabb1.m_MinPosition.x <= aabb2.m_MinPosition.x&&aabb1.m_MaxPosition.x >= aabb2.m_MaxPosition.x) &&\n\t\t(aabb1.m_MinPosition.y <= aabb2.m_MinPosition.y&&aabb1.m_MaxPosition.y >= aabb2.m_MaxPosition.y) &&\n\t\t(aabb1.m_MinPosition.z <= aabb2.m_MinPosition.z&&aabb1.m_MaxPosition.z >= aabb2.m_MaxPosition.z))\n\t\treturn true;\n\telse\n\t\treturn false;\n}\n\nSpaceGameEngine::AxisAlignedBoundingBox SpaceGameEngine::GetAxisAlignedBoundingBox(const Vector<XMFLOAT3>& points)\n{\n\tXMFLOAT3 minl((float)MaxIntValue,(float)MaxIntValue,(float)MaxIntValue), maxl(0.0f,0.0f,0.0f);\n\tfor (auto& i : points)\n\t{\n\t\tminl.x = min(minl.x, i.x);\n\t\tminl.y = min(minl.y, i.y);\n\t\tminl.z = min(minl.z, i.z);\n\t\tmaxl.x = max(maxl.x, i.x);\n\t\tmaxl.y = max(maxl.y, i.y);\n\t\tmaxl.z = max(maxl.z, i.z);\n\t}\n\treturn AxisAlignedBoundingBox(minl, maxl);\n}\n\nSpaceGameEngine::AxisAlignedBoundingBox SpaceGameEngine::GetAxisAlignedBoundingBox(const Vector<AxisAlignedBoundingBox>& aabbs)\n{\n\tXMFLOAT3 minl((float)MaxIntValue, (float)MaxIntValue, (float)MaxIntValue), maxl(0.0f, 0.0f, 0.0f);\n\tfor (auto i : aabbs)\n\t{\n\t\tminl.x = min(minl.x, i.m_MinPosition.x);\n\t\tminl.y = min(minl.y, i.m_MinPosition.y);\n\t\tminl.z = min(minl.z, i.m_MinPosition.z);\n\t\tmaxl.x = max(maxl.x, i.m_MaxPosition.x);\n\t\tmaxl.y = max(maxl.y, i.m_MaxPosition.y);\n\t\tmaxl.z = max(maxl.z, i.m_MaxPosition.z);\n\t}\n\treturn AxisAlignedBoundingBox(minl, maxl);\n}\n\nbool SpaceGameEngine::IfIntersectWithFrustum(const AxisAlignedBoundingBox & aabb)\n{\n\tXMFLOAT3 point[8];\n\tpoint[0] = XMFLOAT3(aabb.m_MinPosition.x, aabb.m_MaxPosition.y, aabb.m_MinPosition.z);\n\tpoint[1] = XMFLOAT3(aabb.m_MaxPosition.x, aabb.m_MaxPosition.y, aabb.m_MinPosition.z);\n\tpoint[2] = XMFLOAT3(aabb.m_MaxPosition.x, aabb.m_MinPosition.y, aabb.m_MinPosition.z);\n\tpoint[3] = XMFLOAT3(aabb.m_MinPosition);\n\tpoint[4] = XMFLOAT3(aabb.m_MinPosition.x, aabb.m_MaxPosition.y, aabb.m_MaxPosition.z);\n\tpoint[5] = XMFLOAT3(aabb.m_MaxPosition);\n\tpoint[6] = XMFLOAT3(aabb.m_MaxPosition.x, aabb.m_MinPosition.y, aabb.m_MaxPosition.z);\n\tpoint[7] = XMFLOAT3(aabb.m_MinPosition.x, aabb.m_MinPosition.y, aabb.m_MaxPosition.z);\n\t\n\tXMFLOAT3 point_after[8];\n\tbool if_front = true, if_behind = true;\n\tint flag_x = 0, flag_y = 0;\n\tint ans_x = 0, ans_y = 0;\n\tfor (int i = 0; i < 8; i++)\n\t{\n\t\tpoint_after[i] = TransformByViewProjectionMatrix(point[i]);\n\t\tif (point_after[i].z >= 0)\n\t\t\tif_front = false;\n\t\tif (point_after[i].z <= 1)\n\t\t\tif_behind = false;\n\t\tif (point_after[i].x >= -1.0f&&point_after[i].x <= 1.0f&&\n\t\t\tpoint_after[i].y >= -1.0f&&point_after[i].y <= 1.0f&&\n\t\t\tpoint_after[i].z >= 0.0f&&point_after[i].z <= 1.0f)\n\t\t\treturn true;\n\t\tif (flag_x == 0)\n\t\t\tflag_x = (point_after[i].x > 0 ? 1 : -1);\n\t\tif (flag_y == 0)\n\t\t\tflag_y = (point_after[i].y > 0 ? 1 : -1);\n\t\tif (flag_x*point_after[i].x == 1)\n\t\t\tans_x += 1;\n\t\tif (flag_y*point_after[i].y == 1)\n\t\t\tans_y += 1;\n\t}\n\tif (if_front || if_behind)\n\t\treturn false;\n\tif (ans_x == 8 || ans_y == 8)\n\t\treturn false;\n\treturn true;\n}\n<commit_msg>fix a bug<commit_after>\/*\nCopyright 2017 creatorlxd\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\nhttp:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n#include \"stdafx.h\"\n#include \"..\/Include\/BoundingBox.h\" \n\nSpaceGameEngine::AxisAlignedBoundingBox::AxisAlignedBoundingBox()\n{\n\tm_MinPosition = XMFLOAT3(0, 0, 0);\n\tm_MaxPosition = XMFLOAT3(0, 0, 0);\n}\n\nSpaceGameEngine::AxisAlignedBoundingBox::AxisAlignedBoundingBox(const XMFLOAT3 & minl, const XMFLOAT3 & maxl)\n{\n\tm_MinPosition = minl;\n\tm_MaxPosition = maxl;\n}\n\nbool SpaceGameEngine::IfIntersect(const AxisAlignedBoundingBox & aabb1, const AxisAlignedBoundingBox & aabb2)\n{\n\tif (aabb1.m_MinPosition.x >= aabb2.m_MaxPosition.x || aabb1.m_MaxPosition.x <= aabb2.m_MinPosition.x)\n\t\treturn false;\n\tif (aabb1.m_MinPosition.y >= aabb2.m_MaxPosition.y || aabb1.m_MaxPosition.y <= aabb2.m_MinPosition.y)\n\t\treturn false;\n\tif (aabb1.m_MinPosition.z >= aabb2.m_MaxPosition.z || aabb1.m_MaxPosition.z <= aabb2.m_MinPosition.z)\n\t\treturn false;\n\treturn true;\n}\n\nbool SpaceGameEngine::IfInclude(const AxisAlignedBoundingBox & aabb, const XMFLOAT3 & position)\n{\n\tif (aabb.m_MinPosition.x > position.x || aabb.m_MaxPosition.x < position.x)\n\t\treturn false;\n\tif (aabb.m_MinPosition.y > position.y || aabb.m_MaxPosition.y < position.y)\n\t\treturn false;\n\tif (aabb.m_MinPosition.z > position.z || aabb.m_MaxPosition.z < position.z)\n\t\treturn false;\n\treturn true;\n}\n\nbool SpaceGameEngine::IfInclude(const AxisAlignedBoundingBox & aabb1, const AxisAlignedBoundingBox & aabb2)\n{\n\tif ((aabb1.m_MinPosition.x <= aabb2.m_MinPosition.x&&aabb1.m_MaxPosition.x >= aabb2.m_MaxPosition.x) &&\n\t\t(aabb1.m_MinPosition.y <= aabb2.m_MinPosition.y&&aabb1.m_MaxPosition.y >= aabb2.m_MaxPosition.y) &&\n\t\t(aabb1.m_MinPosition.z <= aabb2.m_MinPosition.z&&aabb1.m_MaxPosition.z >= aabb2.m_MaxPosition.z))\n\t\treturn true;\n\telse\n\t\treturn false;\n}\n\nSpaceGameEngine::AxisAlignedBoundingBox SpaceGameEngine::GetAxisAlignedBoundingBox(const Vector<XMFLOAT3>& points)\n{\n\tXMFLOAT3 minl((float)MaxIntValue,(float)MaxIntValue,(float)MaxIntValue), maxl(0.0f,0.0f,0.0f);\n\tfor (auto& i : points)\n\t{\n\t\tminl.x = min(minl.x, i.x);\n\t\tminl.y = min(minl.y, i.y);\n\t\tminl.z = min(minl.z, i.z);\n\t\tmaxl.x = max(maxl.x, i.x);\n\t\tmaxl.y = max(maxl.y, i.y);\n\t\tmaxl.z = max(maxl.z, i.z);\n\t}\n\treturn AxisAlignedBoundingBox(minl, maxl);\n}\n\nSpaceGameEngine::AxisAlignedBoundingBox SpaceGameEngine::GetAxisAlignedBoundingBox(const Vector<AxisAlignedBoundingBox>& aabbs)\n{\n\tXMFLOAT3 minl((float)MaxIntValue, (float)MaxIntValue, (float)MaxIntValue), maxl(0.0f, 0.0f, 0.0f);\n\tfor (auto i : aabbs)\n\t{\n\t\tminl.x = min(minl.x, i.m_MinPosition.x);\n\t\tminl.y = min(minl.y, i.m_MinPosition.y);\n\t\tminl.z = min(minl.z, i.m_MinPosition.z);\n\t\tmaxl.x = max(maxl.x, i.m_MaxPosition.x);\n\t\tmaxl.y = max(maxl.y, i.m_MaxPosition.y);\n\t\tmaxl.z = max(maxl.z, i.m_MaxPosition.z);\n\t}\n\treturn AxisAlignedBoundingBox(minl, maxl);\n}\n\nbool SpaceGameEngine::IfIntersectWithFrustum(const AxisAlignedBoundingBox & aabb)\n{\n\tXMFLOAT3 point[8];\n\tpoint[0] = XMFLOAT3(aabb.m_MinPosition.x, aabb.m_MaxPosition.y, aabb.m_MinPosition.z);\n\tpoint[1] = XMFLOAT3(aabb.m_MaxPosition.x, aabb.m_MaxPosition.y, aabb.m_MinPosition.z);\n\tpoint[2] = XMFLOAT3(aabb.m_MaxPosition.x, aabb.m_MinPosition.y, aabb.m_MinPosition.z);\n\tpoint[3] = XMFLOAT3(aabb.m_MinPosition);\n\tpoint[4] = XMFLOAT3(aabb.m_MinPosition.x, aabb.m_MaxPosition.y, aabb.m_MaxPosition.z);\n\tpoint[5] = XMFLOAT3(aabb.m_MaxPosition);\n\tpoint[6] = XMFLOAT3(aabb.m_MaxPosition.x, aabb.m_MinPosition.y, aabb.m_MaxPosition.z);\n\tpoint[7] = XMFLOAT3(aabb.m_MinPosition.x, aabb.m_MinPosition.y, aabb.m_MaxPosition.z);\n\t\n\tXMFLOAT3 point_after[8];\n\tbool if_front = true, if_behind = true;\n\tint flag_x = 0, flag_y = 0;\n\tint ans_x = 0, ans_y = 0;\n\tfor (int i = 0; i < 8; i++)\n\t{\n\t\tpoint_after[i] = TransformByViewProjectionMatrix(point[i]);\n\t\tif (point_after[i].z >= 0)\n\t\t\tif_front = false;\n\t\tif (point_after[i].z <= 1)\n\t\t\tif_behind = false;\n\t\tif (point_after[i].x >= -1.0f&&point_after[i].x <= 1.0f&&\n\t\t\tpoint_after[i].y >= -1.0f&&point_after[i].y <= 1.0f&&\n\t\t\tpoint_after[i].z >= 0.0f&&point_after[i].z <= 1.0f)\n\t\t\treturn true;\n\t\tif (flag_x == 0)\n\t\t\tflag_x = (point_after[i].x > 0 ? 1 : -1);\n\t\tif (flag_y == 0)\n\t\t\tflag_y = (point_after[i].y > 0 ? 1 : -1);\n\t\tif (flag_x*(point_after[i].x > 0 ? 1 : -1) == 1)\n\t\t\tans_x += 1;\n\t\tif (flag_y*(point_after[i].y > 0 ? 1 : -1) == 1)\n\t\t\tans_y += 1;\n\t}\n\tif (if_front || if_behind)\n\t\treturn false;\n\tif (ans_x == 8 && ans_y == 8)\n\t\treturn false;\n\treturn true;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (C) 2014 Google Inc. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following disclaimer\n * in the documentation and\/or other materials provided with the\n * distribution.\n * * Neither the name of Google Inc. nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \"config.h\"\n#include \"core\/loader\/WorkerLoaderClientBridgeSyncHelper.h\"\n\n#include \"core\/workers\/WorkerGlobalScope.h\"\n#include \"core\/workers\/WorkerLoaderProxy.h\"\n#include \"platform\/network\/ResourceError.h\"\n#include \"platform\/network\/ResourceResponse.h\"\n#include \"public\/platform\/WebWaitableEvent.h\"\n#include \"wtf\/Functional.h\"\n#include \"wtf\/MainThread.h\"\n#include \"wtf\/OwnPtr.h\"\n\nnamespace blink {\n\nPassOwnPtr<WorkerLoaderClientBridgeSyncHelper> WorkerLoaderClientBridgeSyncHelper::create(ThreadableLoaderClient& client, PassOwnPtr<blink::WebWaitableEvent> event)\n{\n return adoptPtr(new WorkerLoaderClientBridgeSyncHelper(client, event));\n}\n\nWorkerLoaderClientBridgeSyncHelper::~WorkerLoaderClientBridgeSyncHelper()\n{\n MutexLocker lock(m_lock);\n ASSERT(isMainThread());\n for (size_t i = 0; i < m_receivedData.size(); ++i)\n delete m_receivedData[i];\n}\n\nvoid WorkerLoaderClientBridgeSyncHelper::run()\n{\n \/\/ This must be called only after m_event is signalled.\n MutexLocker lock(m_lock);\n ASSERT(m_done);\n for (size_t i = 0; i < m_clientTasks.size(); ++i)\n (*m_clientTasks[i])();\n}\n\nvoid WorkerLoaderClientBridgeSyncHelper::didSendData(unsigned long long bytesSent, unsigned long long totalBytesToBeSent)\n{\n MutexLocker lock(m_lock);\n ASSERT(isMainThread());\n m_clientTasks.append(bind(&ThreadableLoaderClient::didSendData, &m_client, bytesSent, totalBytesToBeSent));\n}\n\nstatic void didReceiveResponseAdapter(ThreadableLoaderClient* client, unsigned long identifier, PassOwnPtr<CrossThreadResourceResponseData> responseData, PassOwnPtr<WebDataConsumerHandle> handle)\n{\n OwnPtr<ResourceResponse> response(ResourceResponse::adopt(responseData));\n client->didReceiveResponse(identifier, *response, handle);\n}\n\nvoid WorkerLoaderClientBridgeSyncHelper::didReceiveResponse(unsigned long identifier, const ResourceResponse& response, PassOwnPtr<WebDataConsumerHandle> handle)\n{\n MutexLocker lock(m_lock);\n ASSERT(isMainThread());\n m_clientTasks.append(bind(&didReceiveResponseAdapter, &m_client, identifier, response.copyData(), handle));\n}\n\nvoid WorkerLoaderClientBridgeSyncHelper::didReceiveData(const char* data, unsigned dataLength)\n{\n MutexLocker lock(m_lock);\n ASSERT(isMainThread());\n Vector<char>* buffer = new Vector<char>(dataLength);\n memcpy(buffer->data(), data, dataLength);\n m_receivedData.append(buffer);\n m_clientTasks.append(bind(&ThreadableLoaderClient::didReceiveData, &m_client, static_cast<const char*>(buffer->data()), dataLength));\n}\n\nvoid WorkerLoaderClientBridgeSyncHelper::didDownloadData(int dataLength)\n{\n MutexLocker lock(m_lock);\n ASSERT(isMainThread());\n m_clientTasks.append(bind(&ThreadableLoaderClient::didDownloadData, &m_client, dataLength));\n}\n\nvoid WorkerLoaderClientBridgeSyncHelper::didReceiveCachedMetadata(const char* data, int dataLength)\n{\n MutexLocker lock(m_lock);\n ASSERT(isMainThread());\n Vector<char>* buffer = new Vector<char>(dataLength);\n memcpy(buffer->data(), data, dataLength);\n m_receivedData.append(buffer);\n m_clientTasks.append(bind(&ThreadableLoaderClient::didReceiveCachedMetadata, &m_client, static_cast<const char*>(buffer->data()), dataLength));\n}\n\nvoid WorkerLoaderClientBridgeSyncHelper::didFinishLoading(unsigned long identifier, double finishTime)\n{\n MutexLocker lock(m_lock);\n ASSERT(isMainThread());\n m_clientTasks.append(bind(&ThreadableLoaderClient::didFinishLoading, &m_client, identifier, finishTime));\n m_done = true;\n m_event->signal();\n}\n\nvoid WorkerLoaderClientBridgeSyncHelper::didFail(const ResourceError& error)\n{\n MutexLocker lock(m_lock);\n ASSERT(isMainThread());\n m_clientTasks.append(bind(&ThreadableLoaderClient::didFail, &m_client, error.copy()));\n m_done = true;\n m_event->signal();\n}\n\nvoid WorkerLoaderClientBridgeSyncHelper::didFailAccessControlCheck(const ResourceError& error)\n{\n MutexLocker lock(m_lock);\n ASSERT(isMainThread());\n m_clientTasks.append(bind(&ThreadableLoaderClient::didFailAccessControlCheck, &m_client, error.copy()));\n m_done = true;\n m_event->signal();\n}\n\nvoid WorkerLoaderClientBridgeSyncHelper::didFailRedirectCheck()\n{\n MutexLocker lock(m_lock);\n ASSERT(isMainThread());\n m_clientTasks.append(bind(&ThreadableLoaderClient::didFailRedirectCheck, &m_client));\n m_done = true;\n m_event->signal();\n}\n\nWorkerLoaderClientBridgeSyncHelper::WorkerLoaderClientBridgeSyncHelper(ThreadableLoaderClient& client, PassOwnPtr<blink::WebWaitableEvent> event)\n : m_done(false)\n , m_client(client)\n , m_event(event)\n{\n ASSERT(m_event);\n}\n\n} \/\/ namespace blink\n<commit_msg>Use threadSafeBind() in WorkerLoaderClientBridgeSyncHelper<commit_after>\/*\n * Copyright (C) 2014 Google Inc. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following disclaimer\n * in the documentation and\/or other materials provided with the\n * distribution.\n * * Neither the name of Google Inc. nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \"config.h\"\n#include \"core\/loader\/WorkerLoaderClientBridgeSyncHelper.h\"\n\n#include \"core\/workers\/WorkerGlobalScope.h\"\n#include \"core\/workers\/WorkerLoaderProxy.h\"\n#include \"platform\/ThreadSafeFunctional.h\"\n#include \"platform\/network\/ResourceError.h\"\n#include \"platform\/network\/ResourceResponse.h\"\n#include \"public\/platform\/WebWaitableEvent.h\"\n#include \"wtf\/MainThread.h\"\n#include \"wtf\/OwnPtr.h\"\n\nnamespace blink {\n\nPassOwnPtr<WorkerLoaderClientBridgeSyncHelper> WorkerLoaderClientBridgeSyncHelper::create(ThreadableLoaderClient& client, PassOwnPtr<blink::WebWaitableEvent> event)\n{\n return adoptPtr(new WorkerLoaderClientBridgeSyncHelper(client, event));\n}\n\nWorkerLoaderClientBridgeSyncHelper::~WorkerLoaderClientBridgeSyncHelper()\n{\n MutexLocker lock(m_lock);\n ASSERT(isMainThread());\n for (size_t i = 0; i < m_receivedData.size(); ++i)\n delete m_receivedData[i];\n}\n\nvoid WorkerLoaderClientBridgeSyncHelper::run()\n{\n \/\/ This must be called only after m_event is signalled.\n MutexLocker lock(m_lock);\n ASSERT(m_done);\n for (size_t i = 0; i < m_clientTasks.size(); ++i)\n (*m_clientTasks[i])();\n}\n\nvoid WorkerLoaderClientBridgeSyncHelper::didSendData(unsigned long long bytesSent, unsigned long long totalBytesToBeSent)\n{\n MutexLocker lock(m_lock);\n ASSERT(isMainThread());\n m_clientTasks.append(threadSafeBind(&ThreadableLoaderClient::didSendData, AllowCrossThreadAccess(&m_client), bytesSent, totalBytesToBeSent));\n}\n\nstatic void didReceiveResponseAdapter(ThreadableLoaderClient* client, unsigned long identifier, PassOwnPtr<CrossThreadResourceResponseData> responseData, PassOwnPtr<WebDataConsumerHandle> handle)\n{\n OwnPtr<ResourceResponse> response(ResourceResponse::adopt(responseData));\n client->didReceiveResponse(identifier, *response, handle);\n}\n\nvoid WorkerLoaderClientBridgeSyncHelper::didReceiveResponse(unsigned long identifier, const ResourceResponse& response, PassOwnPtr<WebDataConsumerHandle> handle)\n{\n MutexLocker lock(m_lock);\n ASSERT(isMainThread());\n m_clientTasks.append(threadSafeBind(&didReceiveResponseAdapter, AllowCrossThreadAccess(&m_client), identifier, response, handle));\n}\n\nvoid WorkerLoaderClientBridgeSyncHelper::didReceiveData(const char* data, unsigned dataLength)\n{\n MutexLocker lock(m_lock);\n ASSERT(isMainThread());\n Vector<char>* buffer = new Vector<char>(dataLength);\n memcpy(buffer->data(), data, dataLength);\n m_receivedData.append(buffer);\n m_clientTasks.append(threadSafeBind(&ThreadableLoaderClient::didReceiveData, AllowCrossThreadAccess(&m_client), AllowCrossThreadAccess(static_cast<const char*>(buffer->data())), dataLength));\n}\n\nvoid WorkerLoaderClientBridgeSyncHelper::didDownloadData(int dataLength)\n{\n MutexLocker lock(m_lock);\n ASSERT(isMainThread());\n m_clientTasks.append(threadSafeBind(&ThreadableLoaderClient::didDownloadData, AllowCrossThreadAccess(&m_client), dataLength));\n}\n\nvoid WorkerLoaderClientBridgeSyncHelper::didReceiveCachedMetadata(const char* data, int dataLength)\n{\n MutexLocker lock(m_lock);\n ASSERT(isMainThread());\n Vector<char>* buffer = new Vector<char>(dataLength);\n memcpy(buffer->data(), data, dataLength);\n m_receivedData.append(buffer);\n m_clientTasks.append(threadSafeBind(&ThreadableLoaderClient::didReceiveCachedMetadata, AllowCrossThreadAccess(&m_client), AllowCrossThreadAccess(static_cast<const char*>(buffer->data())), dataLength));\n}\n\nvoid WorkerLoaderClientBridgeSyncHelper::didFinishLoading(unsigned long identifier, double finishTime)\n{\n MutexLocker lock(m_lock);\n ASSERT(isMainThread());\n m_clientTasks.append(threadSafeBind(&ThreadableLoaderClient::didFinishLoading, AllowCrossThreadAccess(&m_client), identifier, finishTime));\n m_done = true;\n m_event->signal();\n}\n\nvoid WorkerLoaderClientBridgeSyncHelper::didFail(const ResourceError& error)\n{\n MutexLocker lock(m_lock);\n ASSERT(isMainThread());\n m_clientTasks.append(threadSafeBind(&ThreadableLoaderClient::didFail, AllowCrossThreadAccess(&m_client), error));\n m_done = true;\n m_event->signal();\n}\n\nvoid WorkerLoaderClientBridgeSyncHelper::didFailAccessControlCheck(const ResourceError& error)\n{\n MutexLocker lock(m_lock);\n ASSERT(isMainThread());\n m_clientTasks.append(threadSafeBind(&ThreadableLoaderClient::didFailAccessControlCheck, AllowCrossThreadAccess(&m_client), error));\n m_done = true;\n m_event->signal();\n}\n\nvoid WorkerLoaderClientBridgeSyncHelper::didFailRedirectCheck()\n{\n MutexLocker lock(m_lock);\n ASSERT(isMainThread());\n m_clientTasks.append(threadSafeBind(&ThreadableLoaderClient::didFailRedirectCheck, AllowCrossThreadAccess(&m_client)));\n m_done = true;\n m_event->signal();\n}\n\nWorkerLoaderClientBridgeSyncHelper::WorkerLoaderClientBridgeSyncHelper(ThreadableLoaderClient& client, PassOwnPtr<blink::WebWaitableEvent> event)\n : m_done(false)\n , m_client(client)\n , m_event(event)\n{\n ASSERT(m_event);\n}\n\n} \/\/ namespace blink\n<|endoftext|>"} {"text":"<commit_before>\/**\n* Copyright (C) 2013 kangliqiang ,kangliq@163.com\n*\n* Licensed under the Apache License, Version 2.0 (the \"License\");\n* you may not use this file except in compliance with the License.\n* You may obtain a copy of the License at\n*\n* http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n*\n* Unless required by applicable law or agreed to in writing, software\n* distributed under the License is distributed on an \"AS IS\" BASIS,\n* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n* See the License for the specific language governing permissions and\n* limitations under the License.\n*\/\n\n#include \"SocketUtil.h\"\n#include <stdlib.h>\n#include <assert.h>\n#include <string.h>\n#include <sstream>\n#include <vector>\n#include <iostream>\n\nint SocketInit()\n{\n#ifdef WIN32\n\n\tWSADATA wsaData;\n\tWORD versionRequested;\n\n\tversionRequested = MAKEWORD(2, 2);\n\n\tif (0 != WSAStartup(versionRequested, &wsaData))\n\t{\n\t\treturn -1;\n\t}\n\n#else\n\n\tsignal(SIGPIPE, SIG_IGN);\n\n#endif\n\n\treturn 0;\n}\n\nint MakeSocketNonblocking (SOCKET fd)\n{\n#ifdef WIN32\n\tunsigned long para = 1;\n\treturn ioctlsocket (fd,FIONBIO,¶);\n#else\n\tint flags = fcntl (fd, F_GETFL, 0);\n\tassert (flags != -1);\n\tflags = (flags | O_NONBLOCK);\n\treturn fcntl (fd, F_SETFL, flags);\n#endif\n}\n\nint SetTcpNoDelay(SOCKET fd)\n{\n\tint flag = 1;\n\treturn setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (const char*)&flag, sizeof(flag));\n}\n\nbool SplitURL(const std::string& serverURL, std::string &addr, short &nPort)\n{\n\tsize_t pos = serverURL.find(':');\n\tif (pos == std::string::npos)\n\t{\n\t\treturn false;\n\t}\n\n\taddr = serverURL.substr(0, pos);\n\tif (0 == addr.compare(\"localhost\"))\n\t{\n\t\taddr = \"127.0.0.1\";\n\t} else {\n\t\taddr = MixAll::filterIP(addr);\n\t}\n\n\tpos ++;\n\n\tstd::string port = serverURL.substr(pos, serverURL.length() - pos);\n\tnPort = atoi(port.c_str());\n\treturn true;\n}\n\nsockaddr string2SocketAddress(const std::string& addrString)\n{\n\tstd::string strAddr;\n\tshort port;\n\tSplitURL(addrString,strAddr,port);\n\n\tstruct sockaddr_in sa;\n\tsa.sin_family = AF_INET;\n\tsa.sin_port = htons(port);\n\n\tsa.sin_addr.s_addr = inet_addr(strAddr.c_str());\n\n\tsockaddr addr;\n\tmemcpy(&addr,&sa,sizeof(sockaddr));\n\n\treturn addr;\n}\n\nstd::string socketAddress2String(sockaddr addr)\n{\n\tsockaddr_in in;\n\tmemcpy(&in,&addr,sizeof(sockaddr));\n\n\treturn inet_ntoa(in.sin_addr);\n}\n\nvoid GetLocalAddrs(std::vector<unsigned int> &addrs)\n{\n\taddrs.clear();\n\n#ifdef WIN32\n\tWSADATA wsaData;\n\tint ret = WSAStartup(MAKEWORD(2, 2), &wsaData);\n\tif (ret != 0) {\n\t\treturn;\n\t}\n\n\tSOCKET sfd = socket(AF_INET, SOCK_DGRAM, 0);\n\n\tif(sfd != INVALID_SOCKET)\n\t{\n\t\tDWORD bytesRet = 0;\n\t\tchar * buffer;\n\t\tint bufSize = 1024;\n\t\tdo\n\t\t{\n\t\t\tbuffer = (char*)malloc(bufSize);\n\t\t\tif (WSAIoctl(sfd, SIO_GET_INTERFACE_LIST, NULL, 0, buffer, bufSize, &bytesRet, NULL, NULL) == SOCKET_ERROR)\n\t\t\t{\n\t\t\t\tif (WSAGetLastError() == WSAEFAULT)\n\t\t\t\t{\n\t\t\t\t\tbufSize <<= 1;\n\t\t\t\t\tfree(buffer);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tbytesRet = 0;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}while (true);\n\n\t\tint size = bytesRet \/ sizeof(INTERFACE_INFO);\n\t\tINTERFACE_INFO* iinfo = (INTERFACE_INFO*)buffer;\n\n\t\tfor (int i = 0; i < size; i++)\n\t\t{\n\t\t\tif (iinfo[i].iiAddress.AddressIn.sin_family == AF_INET)\n\t\t\t{\n\t\t\t\taddrs.push_back(ntohl(iinfo[i].iiAddress.AddressIn.sin_addr.s_addr));\n\t\t\t}\n\t\t}\n\n\t\tfree(buffer);\n\t\tbuffer = NULL;\n\t\tclosesocket(sfd);\n\t}\n#else\n\n\tstruct ifconf ifc;\n\tifc.ifc_buf = NULL;\n\tifc.ifc_len = 0;\n\n\tint sfd = socket(AF_INET, SOCK_DGRAM, 0);\n\tif(sfd != INVALID_SOCKET)\n\t{\n\t\tint ret = ioctl(sfd, SIOCGIFCONF, (char *)&ifc);\n\n\t\tif(ret != -1)\n\t\t{\n\t\t\tifc.ifc_req=(struct ifreq *)malloc(ifc.ifc_len);\n\t\t\tret = ioctl(sfd, SIOCGIFCONF, (char *)&ifc);\n\t\t\tif(ret != -1)\n\t\t\t{\n\t\t\t\tfor(int i=0; i<ifc.ifc_len\/sizeof(struct ifreq); i++)\n\t\t\t\t{\n\t\t\t\t\tstruct sockaddr* sa = (struct sockaddr *)&(ifc.ifc_req[i].ifr_addr);\n\t\t\t\t\tif (AF_INET==sa->sa_family)\n\t\t\t\t\t{\n\t\t\t\t\t\tunsigned int addr = ((struct sockaddr_in *)sa)->sin_addr.s_addr;\n\t\t\t\t\t\taddrs.push_back(htonl(addr));\n\t\t\t\t\t}\t\t\t\t\n\t\t\t\t}\t\t\t\n\t\t\t}\n\n\t\t\tfree(ifc.ifc_req);\n\t\t\tifc.ifc_req = NULL;\n\t\t}\n\n\t\tclose(sfd);\n\t}\n\n#endif\n\n\tif(addrs.empty())\n\t{\t\t\n\t\tchar hostname[1024];\n\n\t\tint ret = gethostname(hostname, sizeof(hostname));\n\t\tif (ret == 0)\n\t\t{\n\t\t\tstruct addrinfo *result = NULL;\n\t\t\tstruct addrinfo *ptr = NULL;\n\t\t\tstruct addrinfo hints;\n\n\t\t\tmemset(&hints, 0,sizeof(hints) );\n\t\t\thints.ai_family = AF_INET;\n\t\t\thints.ai_socktype = SOCK_STREAM;\n\t\t\thints.ai_protocol = IPPROTO_TCP;\n\n\t\t\tret = getaddrinfo(hostname, NULL, &hints, &result);\n\t\t\tif ( ret == 0 ) \n\t\t\t{\n\t\t\t\tfor(ptr=result; ptr != NULL ;ptr=ptr->ai_next) \n\t\t\t\t{\n\t\t\t\t\t\n\t\t\t\t\tstruct sockaddr_in *sockaddr_ipv4 = (struct sockaddr_in *) ptr->ai_addr;\n\t\t\t\t\taddrs.push_back(ntohl(sockaddr_ipv4->sin_addr.s_addr));\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tfreeaddrinfo(result);\n\t\t}\n\t}\n\n\tstd::vector<unsigned int>::iterator it = addrs.begin();\n\tfor (;it!=addrs.end();)\n\t{\n\t\tif (*it>= 0x7F000000U && *it < 0x80000000U)\n\t\t{\n\t\t\tit = addrs.erase(it);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tit++;\n\t\t}\n\t}\n\n\tif (addrs.empty())\n\t{\n\t\taddrs.push_back(INADDR_LOOPBACK);\n\t}\n\n#ifdef WIN32\n\t\tWSACleanup();\n#endif\n}\n\nstd::string getLocalAddress()\n{\n\tstd::vector<unsigned int> addrs;\n\tGetLocalAddrs(addrs);\n\tstruct in_addr addr;\n\taddr.s_addr=htonl(addrs[0]);\n\n\treturn inet_ntoa(addr);\n}\n\nstd::string getHostName(sockaddr addr)\n{\n\tsockaddr_in in;\n\tmemcpy(&in,&addr,sizeof(sockaddr));\n\t\n\tstruct hostent *remoteHost = gethostbyaddr((char*) &(in.sin_addr), 4, AF_INET);\n\tchar** alias = remoteHost->h_aliases;\n\tif (*alias!=0)\n\t{\n\t\treturn *alias;\n\t}\n\telse\n\t{\n\t\treturn inet_ntoa(in.sin_addr);\n\t}\n}\n\n\nunsigned long long swapll(unsigned long long v)\n{\n#ifdef ENDIANMODE_BIG\n\treturn v;\n#else\n\tunsigned long long ret = ((v << 56) \n\t\t\t\t\t\t\t\t| ((v & 0xff00) << 40)\n\t\t\t\t\t\t\t\t| ((v & 0xff0000) << 24)\n\t\t\t\t\t\t\t\t| ((v & 0xff000000) << 8)\n\t\t\t\t\t\t\t\t| ((v >> 8 ) & 0xff000000)\n\t\t\t\t\t\t\t\t| ((v >> 24 ) & 0xff0000)\n\t\t\t\t\t\t\t\t| ((v >> 40 ) & 0xff00)\n\t\t\t\t\t\t\t\t| (v >> 56 ));\n\n\treturn ret;\n#endif\n}\n\nunsigned long long h2nll(unsigned long long v)\n{\n\treturn swapll(v);\n}\n\nunsigned long long n2hll(unsigned long long v)\n{\n\treturn swapll(v);\n}\n\nstd::string socketAddress2IPPort( sockaddr addr )\n{\n\tsockaddr_in in;\n\tmemcpy(&in,&addr,sizeof(sockaddr));\n\n\tchar tmp[32];\n\tsprintf(tmp,\"%s:%d\",inet_ntoa(in.sin_addr),ntohs(in.sin_port));\n\n\tstd::string ipport = tmp;\n\treturn ipport;\n}\n\nvoid load_certificate(SSL_CTX* ctx, char* cacert, char* cakey, char* trustCALocation) {\n if (SSL_CTX_use_certificate_file(ctx, cacert, SSL_FILETYPE_PEM) <= 0) {\n ERR_print_errors_fp(stderr);\n abort();\n }\n\n if(SSL_CTX_use_PrivateKey_file(ctx, cakey, SSL_FILETYPE_PEM) <= 0) {\n ERR_print_errors_fp(stderr);\n abort();\n }\n\n if (SSL_CTX_check_private_key(ctx) <= 0) {\n fprintf(stderr, \"Private key does not match the public certificate\\n\");\n abort();\n }\n\n \/*\n * @param CAfile\n * A pointer to the name of the file that contains the certificates of the trusted CAs and CRLs.\n * The file must be in base64 privacy enhanced mail (PEM) format.\n * The value of this parameter can be NULL if the value of the CApath parameter is not NULL.\n * The maximum length is 255 characters.\n *\n * @param CApath\n * A pointer to the name of the directory that contains the certificates of the trusted CAs and CRLs.\n * The files in the directory must be in PEM format.\n * The value of this parameter can be NULL if the value of the CAfile parameter is not NULL.\n * The maximum length is 255 characters.\n *\/\n SSL_CTX_load_verify_locations(ctx, NULL, trustCALocation);\n SSL_CTX_set_verify_depth(ctx, 5);\n SSL_CTX_set_verify(ctx, SSL_VERIFY_NONE, NULL);\n\tLogger::get_logger()->info(\"Load Certificate Successfully\");\n}\n\nSSL_CTX* initializeSSL() {\n\tSSL_library_init();\n\tSSL_load_error_strings();\n\tERR_load_BIO_strings();\n\tOpenSSL_add_all_algorithms(); \/\/ load and register all encryption algorithms.\n\tSSL_CTX* ctx = SSL_CTX_new(SSLv23_method());\n load_certificate(ctx, \/\/SSL_CTX*\n \"\/dianyi\/config\/RocketMQ\/SSL\/client.pem\", \/\/ public CA certificate\n \"\/dianyi\/config\/RocketMQ\/SSL\/client.pkey\", \/\/ private CA key\n \"\/dianyi\/config\/RocketMQ\/SSL\/\" \/\/ trust CA certificates\n );\n\n\treturn ctx;\n}\n\nvoid destroySSL() {\n\tERR_free_strings();\n\tEVP_cleanup();\n}\n\nvoid show_certificate(SSL* ssl) {\n X509 *cert;\n char *line;\n cert = SSL_get_peer_certificate(ssl); \/* Get certificates (if available) *\/\n if ( cert != NULL ) {\n\t\tLogger::get_logger()->info(\"Server certificates:\");\n\t\tline = X509_NAME_oneline(X509_get_subject_name(cert), 0, 0);\n\t\tLogger::get_logger()->info(\"Subject: {}\", line);\n\t\tfree(line);\n line = X509_NAME_oneline(X509_get_issuer_name(cert), 0, 0);\n\t\tLogger::get_logger()->info(\"Issuer: {}\", line);\n free(line);\n X509_free(cert);\n } else {\n\t\tLogger::get_logger()->warn(\"No certificates.\");\n }\n}\n\nvoid shutdownSSL(SSL * ssl) {\n\tSSL_shutdown(ssl);\n\tSSL_free(ssl);\n}<commit_msg>fix a warning<commit_after>\/**\n* Copyright (C) 2013 kangliqiang ,kangliq@163.com\n*\n* Licensed under the Apache License, Version 2.0 (the \"License\");\n* you may not use this file except in compliance with the License.\n* You may obtain a copy of the License at\n*\n* http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n*\n* Unless required by applicable law or agreed to in writing, software\n* distributed under the License is distributed on an \"AS IS\" BASIS,\n* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n* See the License for the specific language governing permissions and\n* limitations under the License.\n*\/\n\n#include \"SocketUtil.h\"\n#include <stdlib.h>\n#include <assert.h>\n#include <string.h>\n#include <sstream>\n#include <vector>\n#include <iostream>\n\nint SocketInit()\n{\n#ifdef WIN32\n\n\tWSADATA wsaData;\n\tWORD versionRequested;\n\n\tversionRequested = MAKEWORD(2, 2);\n\n\tif (0 != WSAStartup(versionRequested, &wsaData))\n\t{\n\t\treturn -1;\n\t}\n\n#else\n\n\tsignal(SIGPIPE, SIG_IGN);\n\n#endif\n\n\treturn 0;\n}\n\nint MakeSocketNonblocking (SOCKET fd)\n{\n#ifdef WIN32\n\tunsigned long para = 1;\n\treturn ioctlsocket (fd,FIONBIO,¶);\n#else\n\tint flags = fcntl (fd, F_GETFL, 0);\n\tassert (flags != -1);\n\tflags = (flags | O_NONBLOCK);\n\treturn fcntl (fd, F_SETFL, flags);\n#endif\n}\n\nint SetTcpNoDelay(SOCKET fd)\n{\n\tint flag = 1;\n\treturn setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (const char*)&flag, sizeof(flag));\n}\n\nbool SplitURL(const std::string& serverURL, std::string &addr, short &nPort)\n{\n\tsize_t pos = serverURL.find(':');\n\tif (pos == std::string::npos)\n\t{\n\t\treturn false;\n\t}\n\n\taddr = serverURL.substr(0, pos);\n\tif (0 == addr.compare(\"localhost\"))\n\t{\n\t\taddr = \"127.0.0.1\";\n\t} else {\n\t\taddr = MixAll::filterIP(addr);\n\t}\n\n\tpos ++;\n\n\tstd::string port = serverURL.substr(pos, serverURL.length() - pos);\n\tnPort = atoi(port.c_str());\n\treturn true;\n}\n\nsockaddr string2SocketAddress(const std::string& addrString)\n{\n\tstd::string strAddr;\n\tshort port;\n\tSplitURL(addrString,strAddr,port);\n\n\tstruct sockaddr_in sa;\n\tsa.sin_family = AF_INET;\n\tsa.sin_port = htons(port);\n\n\tsa.sin_addr.s_addr = inet_addr(strAddr.c_str());\n\n\tsockaddr addr;\n\tmemcpy(&addr,&sa,sizeof(sockaddr));\n\n\treturn addr;\n}\n\nstd::string socketAddress2String(sockaddr addr)\n{\n\tsockaddr_in in;\n\tmemcpy(&in,&addr,sizeof(sockaddr));\n\n\treturn inet_ntoa(in.sin_addr);\n}\n\nvoid GetLocalAddrs(std::vector<unsigned int> &addrs)\n{\n\taddrs.clear();\n\n#ifdef WIN32\n\tWSADATA wsaData;\n\tint ret = WSAStartup(MAKEWORD(2, 2), &wsaData);\n\tif (ret != 0) {\n\t\treturn;\n\t}\n\n\tSOCKET sfd = socket(AF_INET, SOCK_DGRAM, 0);\n\n\tif(sfd != INVALID_SOCKET)\n\t{\n\t\tDWORD bytesRet = 0;\n\t\tchar * buffer;\n\t\tint bufSize = 1024;\n\t\tdo\n\t\t{\n\t\t\tbuffer = (char*)malloc(bufSize);\n\t\t\tif (WSAIoctl(sfd, SIO_GET_INTERFACE_LIST, NULL, 0, buffer, bufSize, &bytesRet, NULL, NULL) == SOCKET_ERROR)\n\t\t\t{\n\t\t\t\tif (WSAGetLastError() == WSAEFAULT)\n\t\t\t\t{\n\t\t\t\t\tbufSize <<= 1;\n\t\t\t\t\tfree(buffer);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tbytesRet = 0;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}while (true);\n\n\t\tint size = bytesRet \/ sizeof(INTERFACE_INFO);\n\t\tINTERFACE_INFO* iinfo = (INTERFACE_INFO*)buffer;\n\n\t\tfor (int i = 0; i < size; i++)\n\t\t{\n\t\t\tif (iinfo[i].iiAddress.AddressIn.sin_family == AF_INET)\n\t\t\t{\n\t\t\t\taddrs.push_back(ntohl(iinfo[i].iiAddress.AddressIn.sin_addr.s_addr));\n\t\t\t}\n\t\t}\n\n\t\tfree(buffer);\n\t\tbuffer = NULL;\n\t\tclosesocket(sfd);\n\t}\n#else\n\n\tstruct ifconf ifc;\n\tifc.ifc_buf = NULL;\n\tifc.ifc_len = 0;\n\n\tint sfd = socket(AF_INET, SOCK_DGRAM, 0);\n\tif(sfd != INVALID_SOCKET)\n\t{\n\t\tint ret = ioctl(sfd, SIOCGIFCONF, (char *)&ifc);\n\n\t\tif(ret != -1)\n\t\t{\n\t\t\tifc.ifc_req=(struct ifreq *)malloc(ifc.ifc_len);\n\t\t\tret = ioctl(sfd, SIOCGIFCONF, (char *)&ifc);\n\t\t\tif(ret != -1)\n\t\t\t{\n\t\t\t\tfor(int i=0; i<ifc.ifc_len\/sizeof(struct ifreq); i++)\n\t\t\t\t{\n\t\t\t\t\tstruct sockaddr* sa = (struct sockaddr *)&(ifc.ifc_req[i].ifr_addr);\n\t\t\t\t\tif (AF_INET==sa->sa_family)\n\t\t\t\t\t{\n\t\t\t\t\t\tunsigned int addr = ((struct sockaddr_in *)sa)->sin_addr.s_addr;\n\t\t\t\t\t\taddrs.push_back(htonl(addr));\n\t\t\t\t\t}\t\t\t\t\n\t\t\t\t}\t\t\t\n\t\t\t}\n\n\t\t\tfree(ifc.ifc_req);\n\t\t\tifc.ifc_req = NULL;\n\t\t}\n\n\t\tclose(sfd);\n\t}\n\n#endif\n\n\tif(addrs.empty())\n\t{\t\t\n\t\tchar hostname[1024];\n\n\t\tint ret = gethostname(hostname, sizeof(hostname));\n\t\tif (ret == 0)\n\t\t{\n\t\t\tstruct addrinfo *result = NULL;\n\t\t\tstruct addrinfo *ptr = NULL;\n\t\t\tstruct addrinfo hints;\n\n\t\t\tmemset(&hints, 0,sizeof(hints) );\n\t\t\thints.ai_family = AF_INET;\n\t\t\thints.ai_socktype = SOCK_STREAM;\n\t\t\thints.ai_protocol = IPPROTO_TCP;\n\n\t\t\tret = getaddrinfo(hostname, NULL, &hints, &result);\n\t\t\tif ( ret == 0 ) \n\t\t\t{\n\t\t\t\tfor(ptr=result; ptr != NULL ;ptr=ptr->ai_next) \n\t\t\t\t{\n\t\t\t\t\t\n\t\t\t\t\tstruct sockaddr_in *sockaddr_ipv4 = (struct sockaddr_in *) ptr->ai_addr;\n\t\t\t\t\taddrs.push_back(ntohl(sockaddr_ipv4->sin_addr.s_addr));\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tfreeaddrinfo(result);\n\t\t}\n\t}\n\n\tstd::vector<unsigned int>::iterator it = addrs.begin();\n\tfor (;it!=addrs.end();)\n\t{\n\t\tif (*it>= 0x7F000000U && *it < 0x80000000U)\n\t\t{\n\t\t\tit = addrs.erase(it);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tit++;\n\t\t}\n\t}\n\n\tif (addrs.empty())\n\t{\n\t\taddrs.push_back(INADDR_LOOPBACK);\n\t}\n\n#ifdef WIN32\n\t\tWSACleanup();\n#endif\n}\n\nstd::string getLocalAddress()\n{\n\tstd::vector<unsigned int> addrs;\n\tGetLocalAddrs(addrs);\n\tstruct in_addr addr;\n\taddr.s_addr=htonl(addrs[0]);\n\n\treturn inet_ntoa(addr);\n}\n\nstd::string getHostName(sockaddr addr)\n{\n\tsockaddr_in in;\n\tmemcpy(&in,&addr,sizeof(sockaddr));\n\t\n\tstruct hostent *remoteHost = gethostbyaddr((char*) &(in.sin_addr), 4, AF_INET);\n\tchar** alias = remoteHost->h_aliases;\n\tif (*alias!=0)\n\t{\n\t\treturn *alias;\n\t}\n\telse\n\t{\n\t\treturn inet_ntoa(in.sin_addr);\n\t}\n}\n\n\nunsigned long long swapll(unsigned long long v)\n{\n#ifdef ENDIANMODE_BIG\n\treturn v;\n#else\n\tunsigned long long ret = ((v << 56) \n\t\t\t\t\t\t\t\t| ((v & 0xff00) << 40)\n\t\t\t\t\t\t\t\t| ((v & 0xff0000) << 24)\n\t\t\t\t\t\t\t\t| ((v & 0xff000000) << 8)\n\t\t\t\t\t\t\t\t| ((v >> 8 ) & 0xff000000)\n\t\t\t\t\t\t\t\t| ((v >> 24 ) & 0xff0000)\n\t\t\t\t\t\t\t\t| ((v >> 40 ) & 0xff00)\n\t\t\t\t\t\t\t\t| (v >> 56 ));\n\n\treturn ret;\n#endif\n}\n\nunsigned long long h2nll(unsigned long long v)\n{\n\treturn swapll(v);\n}\n\nunsigned long long n2hll(unsigned long long v)\n{\n\treturn swapll(v);\n}\n\nstd::string socketAddress2IPPort( sockaddr addr )\n{\n\tsockaddr_in in;\n\tmemcpy(&in,&addr,sizeof(sockaddr));\n\n\tchar tmp[32];\n\tsprintf(tmp,\"%s:%d\",inet_ntoa(in.sin_addr),ntohs(in.sin_port));\n\n\tstd::string ipport = tmp;\n\treturn ipport;\n}\n\nvoid load_certificate(SSL_CTX* ctx, char const * cacert, char const * cakey, char const * trustCALocation) {\n if (SSL_CTX_use_certificate_file(ctx, cacert, SSL_FILETYPE_PEM) <= 0) {\n\t\tLogger::get_logger()->error(\"Failed to apply public certeificate\");\n abort();\n }\n\n if(SSL_CTX_use_PrivateKey_file(ctx, cakey, SSL_FILETYPE_PEM) <= 0) {\n\t\tLogger::get_logger()->error(\"Failed to apply private key.\");\n abort();\n }\n\n if (SSL_CTX_check_private_key(ctx) <= 0) {\n\t\tLogger::get_logger()->error(\"Private key does not match the public certificate.\");\n abort();\n }\n\n \/*\n * @param CAfile\n * A pointer to the name of the file that contains the certificates of the trusted CAs and CRLs.\n * The file must be in base64 privacy enhanced mail (PEM) format.\n * The value of this parameter can be NULL if the value of the CApath parameter is not NULL.\n * The maximum length is 255 characters.\n *\n * @param CApath\n * A pointer to the name of the directory that contains the certificates of the trusted CAs and CRLs.\n * The files in the directory must be in PEM format.\n * The value of this parameter can be NULL if the value of the CAfile parameter is not NULL.\n * The maximum length is 255 characters.\n *\/\n SSL_CTX_load_verify_locations(ctx, NULL, trustCALocation);\n SSL_CTX_set_verify_depth(ctx, 5);\n SSL_CTX_set_verify(ctx, SSL_VERIFY_NONE, NULL);\n\tLogger::get_logger()->info(\"Load Certificate Successfully\");\n}\n\nSSL_CTX* initializeSSL() {\n\tSSL_library_init();\n\tSSL_load_error_strings();\n\tERR_load_BIO_strings();\n\tOpenSSL_add_all_algorithms(); \/\/ load and register all encryption algorithms.\n\tSSL_CTX* ctx = SSL_CTX_new(SSLv23_method());\n\tchar const * client_certificate = \"\/dianyi\/config\/RocketMQ\/SSL\/client.pem\";\n\tchar const * client_private_key = \"\/dianyi\/config\/RocketMQ\/SSL\/client.pkey\";\n\tchar const * cacerts = \"\/dianyi\/config\/RocketMQ\/SSL\/\";\n\n load_certificate(ctx, \/\/SSL_CTX*\n\t\t\t\t\t client_certificate, \/\/ public CA certificate\n client_private_key, \/\/ private CA key\n cacerts \/\/ trust CA certificates\n\n );\n\n\treturn ctx;\n}\n\nvoid destroySSL() {\n\tERR_free_strings();\n\tEVP_cleanup();\n}\n\nvoid show_certificate(SSL* ssl) {\n X509 *cert;\n char *line;\n cert = SSL_get_peer_certificate(ssl); \/* Get certificates (if available) *\/\n if ( cert != NULL ) {\n\t\tLogger::get_logger()->info(\"Server certificates:\");\n\t\tline = X509_NAME_oneline(X509_get_subject_name(cert), 0, 0);\n\t\tLogger::get_logger()->info(\"Subject: {}\", line);\n\t\tfree(line);\n line = X509_NAME_oneline(X509_get_issuer_name(cert), 0, 0);\n\t\tLogger::get_logger()->info(\"Issuer: {}\", line);\n free(line);\n X509_free(cert);\n } else {\n\t\tLogger::get_logger()->warn(\"No certificates.\");\n }\n}\n\nvoid shutdownSSL(SSL * ssl) {\n\tSSL_shutdown(ssl);\n\tSSL_free(ssl);\n}<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: basicrange.hxx,v $\n *\n * $Revision: 1.6 $\n *\n * last change: $Author: thb $ $Date: 2004-03-15 14:27:35 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef _BGFX_RANGE_BASICRANGE_HXX\n#define _BGFX_RANGE_BASICRANGE_HXX\n\n#ifndef _SAL_TYPES_H_\n#include <sal\/types.h>\n#endif\n\n#ifndef _INC_FLOAT\n#include <float.h>\n#endif\n\n\nnamespace basegfx\n{\n template< typename T, typename Traits > class BasicRange\n {\n protected:\n T mnMinimum;\n T mnMaximum;\n\n public:\n BasicRange() :\n mnMinimum(Traits::initMin()),\n mnMaximum(Traits::initMax())\n {\n }\n\n BasicRange( T nValue ) :\n mnMinimum(nValue),\n mnMaximum(nValue)\n {\n }\n\n BasicRange(const BasicRange& rRange) :\n mnMinimum(rRange.mnMinimum),\n mnMaximum(rRange.mnMaximum)\n {\n }\n\n void reset()\n {\n mnMinimum = Traits::initMin();\n mnMaximum = Traits::initMax();\n }\n\n bool isEmpty() const\n {\n return Traits::initMin() == mnMinimum && Traits::initMax() == mnMaximum;\n }\n\n T getMinimum() const { return mnMinimum; }\n T getMaximum() const { return mnMaximum; }\n\n double getCenter() const\n {\n return ((mnMaximum + mnMinimum) \/ 2.0);\n }\n\n bool isInside(T nValue) const\n {\n return (nValue >= mnMinimum) && (nValue <= mnMaximum);\n }\n\n bool isInside(const BasicRange& rRange) const\n {\n return (rRange.mnMinimum >= mnMinimum) && (rRange.mnMaximum <= mnMaximum);\n }\n\n bool overlaps(const BasicRange& rRange) const\n {\n return !((rRange.mnMaximum < mnMinimum) || (rRange.mnMinimum > mnMaximum));\n }\n\n bool operator==( const BasicRange& rRange ) const\n {\n return (mnMinimum == rRange.mnMinimum && mnMaximum == rRange.mnMaximum);\n }\n\n bool operator!=( const BasicRange& rRange ) const\n {\n return (mnMinimum != rRange.mnMinimum || mnMaximum != rRange.mnMaximum);\n }\n\n void operator=(const BasicRange& rRange)\n {\n mnMinimum = rRange.mnMinimum;\n mnMaximum = rRange.mnMaximum;\n }\n\n void expand(T nValue)\n {\n if(nValue < mnMinimum)\n {\n mnMinimum = nValue;\n }\n\n if(nValue > mnMaximum)\n {\n mnMaximum = nValue;\n }\n }\n\n void expand(const BasicRange& rRange)\n {\n if(rRange.mnMinimum < mnMinimum)\n {\n mnMinimum = rRange.mnMinimum;\n }\n\n if(rRange.mnMaximum > mnMaximum)\n {\n mnMaximum = rRange.mnMaximum;\n }\n }\n\n void grow(T nValue)\n {\n bool bLessThanZero(nValue < 0);\n\n if(nValue > 0 || bLessThanZero)\n {\n mnMinimum -= nValue;\n mnMaximum += nValue;\n\n if(bLessThanZero)\n {\n \/\/ test if range did collapse\n if(mnMinimum > mnMaximum)\n {\n \/\/ if yes, collapse to center\n mnMinimum = mnMaximum = (mnMinimum + mnMaximum) \/ 2.0;\n }\n }\n }\n }\n\n typename Traits::DifferenceType getRange() const\n {\n return (mnMaximum - mnMinimum);\n }\n };\n\n \/\/ some pre-fabricated traits\n struct DoubleTraits\n {\n static double initMin() { return DBL_MAX; };\n static double initMax() { return DBL_MIN; };\n\n typedef double DifferenceType;\n };\n\n struct Int32Traits\n {\n static sal_Int32 initMin() { return 0x7FFFFFFFL; };\n static sal_Int32 initMax() { return 0x80000000UL; };\n\n typedef sal_Int64 DifferenceType;\n };\n\n} \/\/ end of namespace basegfx\n\n#endif \/* _BGFX_RANGE_BASICRANGE_HXX *\/\n<commit_msg>INTEGRATION: CWS aw019 (1.6.36); FILE MERGED 2004\/10\/06 11:14:08 aw 1.6.36.1: #i34831#<commit_after>\/*************************************************************************\n *\n * $RCSfile: basicrange.hxx,v $\n *\n * $Revision: 1.7 $\n *\n * last change: $Author: pjunck $ $Date: 2004-11-03 08:36:11 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef _BGFX_RANGE_BASICRANGE_HXX\n#define _BGFX_RANGE_BASICRANGE_HXX\n\n#ifndef _SAL_TYPES_H_\n#include <sal\/types.h>\n#endif\n\n#ifndef _INC_FLOAT\n#include <float.h>\n#endif\n\n\nnamespace basegfx\n{\n template< typename T, typename Traits > class BasicRange\n {\n protected:\n T mnMinimum;\n T mnMaximum;\n\n public:\n BasicRange() :\n mnMinimum(Traits::initMin()),\n mnMaximum(Traits::initMax())\n {\n }\n\n BasicRange( T nValue ) :\n mnMinimum(nValue),\n mnMaximum(nValue)\n {\n }\n\n BasicRange(const BasicRange& rRange) :\n mnMinimum(rRange.mnMinimum),\n mnMaximum(rRange.mnMaximum)\n {\n }\n\n void reset()\n {\n mnMinimum = Traits::initMin();\n mnMaximum = Traits::initMax();\n }\n\n bool isEmpty() const\n {\n return Traits::initMin() == mnMinimum && Traits::initMax() == mnMaximum;\n }\n\n T getMinimum() const { return mnMinimum; }\n T getMaximum() const { return mnMaximum; }\n\n double getCenter() const\n {\n return ((mnMaximum + mnMinimum) \/ 2.0);\n }\n\n bool isInside(T nValue) const\n {\n return (nValue >= mnMinimum) && (nValue <= mnMaximum);\n }\n\n bool isInside(const BasicRange& rRange) const\n {\n return (rRange.mnMinimum >= mnMinimum) && (rRange.mnMaximum <= mnMaximum);\n }\n\n bool overlaps(const BasicRange& rRange) const\n {\n return !((rRange.mnMaximum < mnMinimum) || (rRange.mnMinimum > mnMaximum));\n }\n\n bool operator==( const BasicRange& rRange ) const\n {\n return (mnMinimum == rRange.mnMinimum && mnMaximum == rRange.mnMaximum);\n }\n\n bool operator!=( const BasicRange& rRange ) const\n {\n return (mnMinimum != rRange.mnMinimum || mnMaximum != rRange.mnMaximum);\n }\n\n void operator=(const BasicRange& rRange)\n {\n mnMinimum = rRange.mnMinimum;\n mnMaximum = rRange.mnMaximum;\n }\n\n void expand(T nValue)\n {\n if(nValue < mnMinimum)\n {\n mnMinimum = nValue;\n }\n\n if(nValue > mnMaximum)\n {\n mnMaximum = nValue;\n }\n }\n\n void expand(const BasicRange& rRange)\n {\n if(rRange.mnMinimum < mnMinimum)\n {\n mnMinimum = rRange.mnMinimum;\n }\n\n if(rRange.mnMaximum > mnMaximum)\n {\n mnMaximum = rRange.mnMaximum;\n }\n }\n\n void grow(T nValue)\n {\n bool bLessThanZero(nValue < 0);\n\n if(nValue > 0 || bLessThanZero)\n {\n mnMinimum -= nValue;\n mnMaximum += nValue;\n\n if(bLessThanZero)\n {\n \/\/ test if range did collapse\n if(mnMinimum > mnMaximum)\n {\n \/\/ if yes, collapse to center\n mnMinimum = mnMaximum = (mnMinimum + mnMaximum) \/ 2;\n }\n }\n }\n }\n\n typename Traits::DifferenceType getRange() const\n {\n return (mnMaximum - mnMinimum);\n }\n };\n\n \/\/ some pre-fabricated traits\n struct DoubleTraits\n {\n static double initMin() { return DBL_MAX; };\n static double initMax() { return DBL_MIN; };\n\n typedef double DifferenceType;\n };\n\n struct Int32Traits\n {\n static sal_Int32 initMin() { return 0x7FFFFFFFL; };\n static sal_Int32 initMax() { return 0x80000000UL; };\n\n typedef sal_Int64 DifferenceType;\n };\n\n} \/\/ end of namespace basegfx\n\n#endif \/* _BGFX_RANGE_BASICRANGE_HXX *\/\n<|endoftext|>"} {"text":"<commit_before>#include \"athena\/CubeMesh.h\"\r\n#include \"athena\/GraphicDevice.h\"\r\n\r\nusing namespace Athena;\r\n\r\nstatic const float s_positions[24 * 3] =\r\n{\r\n\t\/\/Front\r\n\t-1, 1, -1,\r\n\t-1, -1, -1,\r\n\t 1, 1, -1,\r\n\t 1, -1, -1,\r\n\t \/\/Back\r\n\t 1, -1, 1,\r\n\t-1, -1, 1,\r\n\t 1, 1, 1,\r\n\t-1, 1, 1,\r\n\t \/\/Left\r\n\t-1, -1, 1,\r\n\t-1, -1, -1,\r\n\t-1, 1, 1,\r\n\t-1, 1, -1,\r\n\t \/\/Right\r\n\t 1, 1, -1,\r\n\t 1, -1, -1,\r\n\t 1, 1, 1,\r\n\t 1, -1, 1,\r\n\t\/\/Bottom\r\n\t 1, -1, -1,\r\n\t-1, -1, -1,\r\n\t 1, -1, 1,\r\n\t-1, -1, 1,\r\n\t\/\/Top\r\n\t-1, 1, 1,\r\n\t-1, 1, -1,\r\n\t 1, 1, 1,\r\n\t 1, 1, -1,\r\n};\r\n\r\nstatic const float s_texCoords[24 * 2] =\r\n{\r\n\t\/\/Front\r\n\t0, 0,\r\n\t0, 1,\r\n\t1, 0,\r\n\t1, 1,\r\n\t\/\/Back\r\n\t0, 1,\r\n\t1, 1,\r\n\t0, 0,\r\n\t1, 0,\r\n\t\/\/Left\r\n\t0, 1,\r\n\t1, 1,\r\n\t0, 0,\r\n\t1, 0,\r\n\t\/\/Right\r\n\t0, 0,\r\n\t0, 1,\r\n\t1, 0,\r\n\t1, 1,\r\n\t\/\/Bottom\r\n\t0, 1,\r\n\t1, 1,\r\n\t0, 0,\r\n\t1, 0,\r\n\t\/\/Top\r\n\t0, 0,\r\n\t0, 1,\r\n\t1, 0,\r\n\t1, 1,\r\n};\r\n\r\nCCubeMesh::CCubeMesh()\r\n{\r\n\tVERTEX_BUFFER_DESCRIPTOR bufferDesc = GenerateVertexBufferDescriptor(24, 36, \r\n\t\tVERTEX_BUFFER_HAS_POS | VERTEX_BUFFER_HAS_UV0);\r\n\tconst auto& posVertexItem = bufferDesc.GetVertexItem(VERTEX_ITEM_ID_POSITION);\r\n\tconst auto& uv0VertexItem = bufferDesc.GetVertexItem(VERTEX_ITEM_ID_UV0);\r\n\r\n\tm_primitiveType = PRIMITIVE_TRIANGLE_LIST;\r\n\tm_primitiveCount = 12;\r\n\tm_vertexBuffer = CGraphicDevice::GetInstance().CreateVertexBuffer(bufferDesc);\r\n\r\n\tuint8* vertices = reinterpret_cast<uint8*>(m_vertexBuffer->LockVertices());\r\n\tfor(unsigned int i = 0; i < 24; i++)\r\n\t{\r\n\t\t*reinterpret_cast<CVector3*>(vertices + posVertexItem->offset) = CVector3(&s_positions[i * 3]);\r\n\t\t*reinterpret_cast<CVector2*>(vertices + uv0VertexItem->offset) = CVector2(&s_texCoords[i * 2]);\r\n\t\tvertices += bufferDesc.GetVertexSize();\r\n\t}\r\n\tm_vertexBuffer->UnlockVertices();\r\n\r\n\tuint16* indices = m_vertexBuffer->LockIndices();\r\n\tfor(unsigned int i = 0; i < 6; i++)\r\n\t{\r\n\t\tindices[(i * 6) + 0] = (i * 4) + 1;\r\n\t\tindices[(i * 6) + 1] = (i * 4) + 0;\r\n\t\tindices[(i * 6) + 2] = (i * 4) + 2;\r\n\t\tindices[(i * 6) + 3] = (i * 4) + 1;\r\n\t\tindices[(i * 6) + 4] = (i * 4) + 2;\r\n\t\tindices[(i * 6) + 5] = (i * 4) + 3;\r\n\t}\r\n\tm_vertexBuffer->UnlockIndices();\r\n}\r\n\r\nCCubeMesh::~CCubeMesh()\r\n{\r\n\r\n}\r\n\r\nMeshPtr CCubeMesh::Create()\r\n{\r\n\treturn MeshPtr(new CCubeMesh());\r\n}\r\n<commit_msg>Simplified index generation in CubeMesh.<commit_after>#include \"athena\/CubeMesh.h\"\r\n#include \"athena\/GraphicDevice.h\"\r\n\r\nusing namespace Athena;\r\n\r\nstatic const float s_positions[24 * 3] =\r\n{\r\n\t\/\/Front\r\n\t-1, 1, -1,\r\n\t-1, -1, -1,\r\n\t 1, 1, -1,\r\n\t 1, -1, -1,\r\n\t \/\/Back\r\n\t 1, -1, 1,\r\n\t-1, -1, 1,\r\n\t 1, 1, 1,\r\n\t-1, 1, 1,\r\n\t \/\/Left\r\n\t-1, -1, 1,\r\n\t-1, -1, -1,\r\n\t-1, 1, 1,\r\n\t-1, 1, -1,\r\n\t \/\/Right\r\n\t 1, 1, -1,\r\n\t 1, -1, -1,\r\n\t 1, 1, 1,\r\n\t 1, -1, 1,\r\n\t\/\/Bottom\r\n\t 1, -1, -1,\r\n\t-1, -1, -1,\r\n\t 1, -1, 1,\r\n\t-1, -1, 1,\r\n\t\/\/Top\r\n\t-1, 1, 1,\r\n\t-1, 1, -1,\r\n\t 1, 1, 1,\r\n\t 1, 1, -1,\r\n};\r\n\r\nstatic const float s_texCoords[24 * 2] =\r\n{\r\n\t\/\/Front\r\n\t0, 0,\r\n\t0, 1,\r\n\t1, 0,\r\n\t1, 1,\r\n\t\/\/Back\r\n\t0, 1,\r\n\t1, 1,\r\n\t0, 0,\r\n\t1, 0,\r\n\t\/\/Left\r\n\t0, 1,\r\n\t1, 1,\r\n\t0, 0,\r\n\t1, 0,\r\n\t\/\/Right\r\n\t0, 0,\r\n\t0, 1,\r\n\t1, 0,\r\n\t1, 1,\r\n\t\/\/Bottom\r\n\t0, 1,\r\n\t1, 1,\r\n\t0, 0,\r\n\t1, 0,\r\n\t\/\/Top\r\n\t0, 0,\r\n\t0, 1,\r\n\t1, 0,\r\n\t1, 1,\r\n};\r\n\r\n#define GENERATE_FACE_INDICES(i) (i * 4) + 1, (i * 4) + 0, (i * 4) + 2, (i * 4) + 1, (i * 4) + 2, (i * 4) + 3\r\n\r\nstatic const uint16 s_indices[36] =\r\n{\r\n\tGENERATE_FACE_INDICES(0),\r\n\tGENERATE_FACE_INDICES(1),\r\n\tGENERATE_FACE_INDICES(2),\r\n\tGENERATE_FACE_INDICES(3),\r\n\tGENERATE_FACE_INDICES(4),\r\n\tGENERATE_FACE_INDICES(5)\r\n};\r\n\r\nCCubeMesh::CCubeMesh()\r\n{\r\n\tVERTEX_BUFFER_DESCRIPTOR bufferDesc = GenerateVertexBufferDescriptor(24, 36, \r\n\t\tVERTEX_BUFFER_HAS_POS | VERTEX_BUFFER_HAS_UV0);\r\n\tconst auto& posVertexItem = bufferDesc.GetVertexItem(VERTEX_ITEM_ID_POSITION);\r\n\tconst auto& uv0VertexItem = bufferDesc.GetVertexItem(VERTEX_ITEM_ID_UV0);\r\n\r\n\tm_primitiveType = PRIMITIVE_TRIANGLE_LIST;\r\n\tm_primitiveCount = 12;\r\n\tm_vertexBuffer = CGraphicDevice::GetInstance().CreateVertexBuffer(bufferDesc);\r\n\r\n\tuint8* vertices = reinterpret_cast<uint8*>(m_vertexBuffer->LockVertices());\r\n\tfor(unsigned int i = 0; i < 24; i++)\r\n\t{\r\n\t\t*reinterpret_cast<CVector3*>(vertices + posVertexItem->offset) = CVector3(&s_positions[i * 3]);\r\n\t\t*reinterpret_cast<CVector2*>(vertices + uv0VertexItem->offset) = CVector2(&s_texCoords[i * 2]);\r\n\t\tvertices += bufferDesc.GetVertexSize();\r\n\t}\r\n\tm_vertexBuffer->UnlockVertices();\r\n\r\n\tuint16* indices = m_vertexBuffer->LockIndices();\r\n\tmemcpy(indices, s_indices, sizeof(s_indices));\r\n\tm_vertexBuffer->UnlockIndices();\r\n}\r\n\r\nCCubeMesh::~CCubeMesh()\r\n{\r\n\r\n}\r\n\r\nMeshPtr CCubeMesh::Create()\r\n{\r\n\treturn MeshPtr(new CCubeMesh());\r\n}\r\n<|endoftext|>"} {"text":"<commit_before>#include <fstream>\n#include <string>\n\n#include <boost\/random.hpp>\n#include <boost\/generator_iterator.hpp>\n#include <random>\n\n#include \"midi_misc.h\"\n\nusing namespace std;\n\n\n\/* Ended up using boost::filesystem instead\n * This bool func is not in use\n *\/\nbool does_file_exist(string fileName)\n{\n ifstream infile(fileName);\n return infile.good();\n}\n\nint random_int(int min, int max) {\n\trandom_device rd;\t\t\/\/ I think I prefer seeding with random device vs ctime\n\tmt19937 rng(rd()); \t\t\/\/ seed with Mersenne-Twister engine VS ctime\n\tuniform_int_distribution<int> uni(min, max);\n\treturn uni(rng);\n}\n\n\/* Another way to implement random function\nvoid MIDI_Scale::seed_gen() {\n\tgen.seed(static_cast<unsigned int>(std::time(0)));\n}\n\nint MIDI_Scale::gen_rand_num() {\n\t\/\/ seed_gen();\n\tboost::uniform_int<> dist(1, 2);\n boost::variate_generator<boost::mt19937&, boost::uniform_int<> > num(gen, dist);\n return num();\n}\n*\/<commit_msg>Update midi_misc.cpp<commit_after>#include <fstream>\n#include <string>\n\n#include <boost\/random.hpp>\n#include <boost\/generator_iterator.hpp>\n#include <random>\n\n#include \"midi_misc.h\"\n\nusing namespace std;\n\n\n\/* Ended up using boost::filesystem instead\n * This bool func is not in use\n *\/\nbool does_file_exist(string fileName)\n{\n ifstream infile(fileName);\n return infile.good();\n}\n\nint random_int(int min, int max) {\n\trandom_device rd;\t\t\/\/ I think I prefer seeding with random device vs ctime\n\tmt19937 rng(rd()); \t\t\/\/ seed with Mersenne-Twister engine VS ctime\n\tuniform_int_distribution<int> uni(min, max);\n\treturn uni(rng);\n}\n\n\/* Another way to implement random function\nvoid MIDI_Scale::seed_gen() {\n\tgen.seed(static_cast<unsigned int>(std::time(0)));\n}\n\nint MIDI_Scale::gen_rand_num() {\n\t\/\/ seed_gen(); \/\/ put in main.cpp\n\tboost::uniform_int<> dist(1, 2);\n \tboost::variate_generator<boost::mt19937&, boost::uniform_int<> > num(gen, dist);\n \treturn num();\n}\n*\/\n<|endoftext|>"} {"text":"<commit_before><commit_msg>coverity#738656 Uninitialized scalar field<commit_after><|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: frm_module.hxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: rt $ $Date: 2005-09-08 22:56:59 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef FRM_MODULE_HXX\n#define FRM_MODULE_HXX\n\n#define FORMS_MODULE_INCLUDE_CONTEXT\n #define FORMS_MODULE_NAMESPACE frm\n #include \"forms_module.hxx\"\n#undef FORMS_MODULE_INCLUDE_CONTEXT\n\n#endif \/\/ FRM_MODULE_HXX\n\n<commit_msg>INTEGRATION: CWS changefileheader (1.3.244); FILE MERGED 2008\/03\/31 13:11:39 rt 1.3.244.1: #i87441# Change license header to LPGL v3.<commit_after>\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2008 by Sun Microsystems, Inc.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: frm_module.hxx,v $\n * $Revision: 1.4 $\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * <http:\/\/www.openoffice.org\/license.html>\n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n#ifndef FRM_MODULE_HXX\n#define FRM_MODULE_HXX\n\n#define FORMS_MODULE_INCLUDE_CONTEXT\n #define FORMS_MODULE_NAMESPACE frm\n #include \"forms_module.hxx\"\n#undef FORMS_MODULE_INCLUDE_CONTEXT\n\n#endif \/\/ FRM_MODULE_HXX\n\n<|endoftext|>"} {"text":"<commit_before>#include <glm\/glm.hpp>\n#include <glm\/gtc\/matrix_transform.hpp>\n#include <glm\/gtx\/transform.hpp>\n#include <glm\/gtx\/quaternion.hpp>\n#include <glm\/gtc\/quaternion.hpp>\n#include <glm\/gtx\/matrix_interpolation.hpp>\n\n#include <Utils\/Containers\/Vector.hpp>\n#include <map>\n#include <chrono>\n\n#include <Core\/Engine.hh>\n#include <Core\/SceneManager.hh>\n#include <Core\/Renderer.hh>\n\n\/\/ DEPENDENCIES\n#include <Context\/SdlContext.hh>\n#include <Core\/ConfigurationManager.hpp>\n#include <Physic\/BulletDynamicManager.hpp>\n#include <Core\/Timer.hh>\n#include <Utils\/PubSub.hpp>\n#include <Render\/GeometryManager.hh>\n#include <Utils\/PerformanceDebugger.hh>\n#include <Core\/AssetsManager.hpp>\n\n#include <Convertor\/SkeletonLoader.hpp>\n#include <Convertor\/AnimationsLoader.hpp>\n#include <Convertor\/MeshLoader.hpp>\n#include <Convertor\/MaterialConvertor.hpp>\n#include <Convertor\/ImageLoader.hpp>\n\n\/\/SKINNING\n#include <Skinning\/Animation.hpp>\n#include <Skinning\/AnimationChannel.hpp>\n#include <Skinning\/AnimationInstance.hpp>\n#include <Skinning\/AnimationKey.hpp>\n#include <Skinning\/Bone.hpp>\n#include <Skinning\/Skeleton.hpp>\n\n\nint\t\t\tmain(int ac, char **av)\n{\n\tstd::shared_ptr<Engine>\te = std::make_shared<Engine>();\n\n\t\/\/ Set Configurations\n\tauto config = e->setInstance<ConfigurationManager>(File(\"MyConfigurationFile.conf\"));\n\n\te->setInstance<PubSub::Manager>();\n\te->setInstance<SdlContext, IRenderContext>();\n\te->setInstance<Input>();\n\te->setInstance<Timer>();\n\te->setInstance<Renderer>();\n\te->setInstance<SceneManager>();\n\te->setInstance<AGE::AssetsManager>();\n\te->setInstance<PerformanceDebugger>();\n\/\/\tauto geometryManager = e->setInstance<gl::GeometryManager>();\n\n\t\/\/ init engine\n\tif (e->init(0, 800, 600, \"~AGE~ V0.0 Demo\") == false)\n\t\treturn (EXIT_FAILURE);\n\n\t\/\/ Set default window size\n\t\/\/ If config file has different value, it'll be changed automaticaly\n\tconfig->setConfiguration<glm::uvec2>(\"windowSize\", glm::uvec2(800, 600), [&e](const glm::uvec2 &v)\n\t{\n\t\te->getInstance<IRenderContext>()->setScreenSize(std::move(v));\n\t});\n\n\tconfig->loadFile();\n\n\t\/\/ launch engine\n\tif (e->start() == false)\n\t\treturn (EXIT_FAILURE);\n\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\/\/\/\/\/\n\t\/\/\n\n\t\/\/\/\/\/Convert fbx to AGE data structure\n\n\tbool isSkeleton = false;\n\tbool isAnimations = false;\n\tbool isMesh = false;\n\tbool isMaterial = false;\n\tbool isTexture = false;\n\tbool convert = true;\n\tif (convert)\n\t{\n\t\t\/\/AGE::AssetDataSet dataSet;\n\t\t\/\/dataSet.filePath = File(\"catwoman\/atk close front 6.fbx\");\n\t\t\/\/dataSet.skeletonName = \"catwoman\";\n\t\t\/\/dataSet.skinName = \"catwoman\";\n\t\t\/\/dataSet.materialName = \"catwoman\";\n\t\t\/\/dataSet.animationName = \"catwoman-roulade\";\t\t\n\n\t\t\/\/dataSet.serializedDirectory = std::tr2::sys::basic_directory_entry<std::tr2::sys::path>(\"..\/..\/Assets\/AGE-Assets-For-Test\/Serialized\");\n\t\t\/\/dataSet.rawDirectory = std::tr2::sys::basic_directory_entry<std::tr2::sys::path>(\"..\/..\/Assets\/Raw\");\n\n\t\t\/\/isMaterial = AGE::MaterialLoader::load(dataSet);\n\t\t\/\/isTexture = AGE::ImageLoader::load(dataSet);\n\t\t\/\/isSkeleton = AGE::SkeletonLoader::load(dataSet);\n\t\t\/\/isAnimations = AGE::AnimationsLoader::load(dataSet);\n\t\t\/\/isMesh = AGE::MeshLoader::load(dataSet);\n\n\t\t\/\/AGE::MaterialLoader::save(dataSet);\n\t\t\/\/AGE::ImageLoader::save(dataSet);\n\t\t\/\/AGE::SkeletonLoader::save(dataSet);\n\t\t\/\/AGE::AnimationsLoader::save(dataSet);\n\t\t\/\/AGE::MeshLoader::save(dataSet);\n\t}\n\t{\n\t\tAGE::AssetDataSet dataSet;\n\t\tdataSet.filePath = File(\"ball\/ball.obj\");\n\t\tdataSet.skinName = \"ball\";\n\t\tdataSet.materialName = \"ball\";\n\n\t\tdataSet.serializedDirectory = std::tr2::sys::basic_directory_entry<std::tr2::sys::path>(\"..\/..\/Assets\/AGE-Assets-For-Test\/Serialized\");\n\t\tdataSet.rawDirectory = std::tr2::sys::basic_directory_entry<std::tr2::sys::path>(\"..\/..\/Assets\/AGE-Assets-For-Test\/Raw\");\n\n\t\tAGE::MaterialLoader::load(dataSet);\n\t\tAGE::ImageLoader::load(dataSet);\n\t\tAGE::MeshLoader::load(dataSet);\n\n\t\tAGE::MaterialLoader::save(dataSet);\n\t\tAGE::ImageLoader::save(dataSet);\n\t\tAGE::MeshLoader::save(dataSet);\n\t}\n\t{\n\t\tAGE::AssetDataSet dataSet;\n\t\tdataSet.filePath = File(\"cube\/cube.obj\");\n\t\tdataSet.skinName = \"cube\";\n\t\tdataSet.materialName = \"cube\";\n\n\t\tdataSet.serializedDirectory = std::tr2::sys::basic_directory_entry<std::tr2::sys::path>(\"..\/..\/Assets\/AGE-Assets-For-Test\/Serialized\");\n\t\tdataSet.rawDirectory = std::tr2::sys::basic_directory_entry<std::tr2::sys::path>(\"..\/..\/Assets\/AGE-Assets-For-Test\/Raw\");\n\n\t\tAGE::MaterialLoader::load(dataSet);\n\t\tAGE::ImageLoader::load(dataSet);\n\t\tAGE::MeshLoader::load(dataSet);\n\n\t\tAGE::MaterialLoader::save(dataSet);\n\t\tAGE::ImageLoader::save(dataSet);\n\t\tAGE::MeshLoader::save(dataSet);\n\t}\n\/\/\n\/\/\t\/\/Load assets from serialized file\n\/\/\tauto assetsManager = e->getInstance<AGE::AssetsManager>();\n\/\/\n\/\/\tauto catwomanMesh = assetsManager->loadMesh(\"..\/..\/Assets\/NewSerialized\/catwoman\/catwoman.sage\"); \/\/ load mesh\n\/\/\tauto catwomanSkeleton = assetsManager->loadSkeleton(\"..\/..\/Assets\/NewSerialized\/catwoman\/catwoman.skage\"); \/\/ load skeleton\n\/\/\tstd::shared_ptr<AGE::Animation> catwomanRoulade = nullptr;\n\/\/\tif (isAnimations)\n\/\/\t\tcatwomanRoulade = assetsManager->loadAnimation(\"..\/..\/Assets\/NewSerialized\/catwoman\/catwoman-roulade.aage\"); \/\/ load animation\n\/\/\n\/\/ \tAGE::AnimationInstance catwomanAnimationInstance(catwomanSkeleton, catwomanRoulade);\n\/\/\n\/\/\t\/\/\n\/\/\t\/\/\/\/\/\n\/\/\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/\n\/\/\n\/\/\tauto shader = e->getInstance<Renderer>()->addShader(\"basic\",\n\/\/\t\t\".\/basic.vp\",\n\/\/\t\t\".\/basic.fp\");\n\/\/\tif (shader->getId() < 0)\n\/\/\t\treturn EXIT_FAILURE;\n\/\/\tshader->use();\n\/\/\n\/\/\n\/\/\n\/\/\t\/\/ Projection matrix : 45 Field of View, 4:3 ratio, display range : 0.1 unit <-> 100 units\n\/\/\tglm::mat4 Projection = glm::perspective(60.0f, 16.0f \/ 9.0f, 0.1f, 1000.0f);\n\/\/\t\/\/ Camera matrix\n\/\/\tfloat lookAtX = 0;\n\/\/\tfloat lookAtY = 0;\n\/\/\t\/\/ Model matrix : an identity matrix (model will be at the origin)\n\/\/\tglm::mat4 Model = glm::mat4(1.0f); \/\/ Changes for each model !\n\/\/\tModel = glm::scale(Model, glm::vec3(0.2f));\n\/\/\n\/\/\n\/\/\t\/\/ On enable la depth car par defaut elle est pas active\n\/\/\t\/\/ Conseil : la mettre dans son game engine\n\/\/\tglEnable(GL_DEPTH_TEST);\n\/\/\tglDisable(GL_CULL_FACE);\n\/\/\t\/\/ la depth de clear par defaut sera 1\n\/\/\tglClearDepth(1.0f);\n\/\/\t\/\/ la couleur de clear par defaut sera du noir\n\/\/\tglClearColor(0.2f, 0.2f, 0.2f, 1.0f);\n\/\/\n\/\/\tdo\n\/\/\t{\n\/\/\t\tauto time = e->getInstance<Timer>()->getElapsed();\n\/\/\t\tstatic float totalTime = 0.0f;\n\/\/\t\ttotalTime += time;\n\/\/\n\/\/\t\tglm::vec4 color;\n\/\/\t\tshader->use();\n\/\/\t\tglClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);\n\/\/\t\tcolor = glm::vec4(1, 0, 1, 1);\n\/\/\n\/\/\t\tif (e->getInstance<Input>()->getKey(SDLK_w))\n\/\/\t\t\tlookAtY += 1;\n\/\/\t\tif (e->getInstance<Input>()->getKey(SDLK_s))\n\/\/\t\t\tlookAtY -= 1;\n\/\/\t\tif (e->getInstance<Input>()->getKey(SDLK_a))\n\/\/\t\t\tlookAtX -= 1;\n\/\/\t\tif (e->getInstance<Input>()->getKey(SDLK_d))\n\/\/\t\t\tlookAtX += 1;\n\/\/\n\/\/\t\tglm::mat4 View = glm::lookAt(\n\/\/\t\t\tglm::vec3(lookAtX, lookAtY, 150), \/\/ Camera is at (4,3,3), in World Space\n\/\/\t\t\tglm::vec3(lookAtX, lookAtY, 0), \/\/ and looks at the origin\n\/\/\t\t\tglm::vec3(0, 1, 0) \/\/ Head is up (set to 0,-1,0 to look upside-down)\n\/\/\t\t\t);\n\/\/\n\/\/\t\tauto colorId = glGetUniformLocation(shader->getId(), \"color\");\n\/\/\t\tauto modelId = glGetUniformLocation(shader->getId(), \"model\");\n\/\/\t\tauto viewId = glGetUniformLocation(shader->getId(), \"view\");\n\/\/\t\tauto projectionId = glGetUniformLocation(shader->getId(), \"projection\");\n\/\/\n\/\/\t\tglUniform4fv(colorId, 1, &color[0]);\n\/\/\t\tglUniformMatrix4fv(modelId, 1, GL_FALSE, &Model[0][0]);\n\/\/\t\tglUniformMatrix4fv(viewId, 1, GL_FALSE, &View[0][0]);\n\/\/\t\tglUniformMatrix4fv(projectionId, 1, GL_FALSE, &Projection[0][0]);\n\/\/\n\/\/\/\/\t\tfor (auto i = 0; i < 500; ++i)\n\/\/\t\t\tcatwomanAnimationInstance.update(totalTime);\n\/\/\t\tcatwomanSkeleton->updateSkinning();\n\/\/\t\tglUniformMatrix4fv(glGetUniformLocation(shader->getId(), \"bones\"), catwomanAnimationInstance.transformations.size(), GL_FALSE, glm::value_ptr(catwomanAnimationInstance.transformations[0]));\n\/\/\n\/\/\t\tfor (unsigned int i = 0; i < catwomanMesh->subMeshs.size(); ++i)\n\/\/\t\t{\n\/\/\t\t\tgeometryManager->draw(GL_TRIANGLES, catwomanMesh->subMeshs[i].indices, catwomanMesh->subMeshs[i].vertices);\n\/\/\t\t}\n\/\/\t} while (e->update());\n\/\/\n\/\/\tconfig->saveToFile();\n\/\/\te->stop();\n\treturn EXIT_SUCCESS;\n}<commit_msg>clean assert-convert<commit_after>#include <glm\/glm.hpp>\n#include <glm\/gtc\/matrix_transform.hpp>\n#include <glm\/gtx\/transform.hpp>\n#include <glm\/gtx\/quaternion.hpp>\n#include <glm\/gtc\/quaternion.hpp>\n#include <glm\/gtx\/matrix_interpolation.hpp>\n\n#include <Utils\/Containers\/Vector.hpp>\n#include <map>\n#include <chrono>\n\n#include <Core\/Engine.hh>\n#include <Core\/SceneManager.hh>\n\n\/\/ DEPENDENCIES\n#include <Context\/SdlContext.hh>\n#include <Core\/ConfigurationManager.hpp>\n#include <Physic\/BulletDynamicManager.hpp>\n#include <Core\/Timer.hh>\n#include <Utils\/PubSub.hpp>\n#include <Render\/GeometryManager.hh>\n#include <Utils\/PerformanceDebugger.hh>\n#include <Core\/AssetsManager.hpp>\n\n#include <Convertor\/SkeletonLoader.hpp>\n#include <Convertor\/AnimationsLoader.hpp>\n#include <Convertor\/MeshLoader.hpp>\n#include <Convertor\/MaterialConvertor.hpp>\n#include <Convertor\/ImageLoader.hpp>\n\n\/\/SKINNING\n#include <Skinning\/Animation.hpp>\n#include <Skinning\/AnimationChannel.hpp>\n#include <Skinning\/AnimationInstance.hpp>\n#include <Skinning\/AnimationKey.hpp>\n#include <Skinning\/Bone.hpp>\n#include <Skinning\/Skeleton.hpp>\n\n\nint\t\t\tmain(int ac, char **av)\n{\n\t{\n\t\tAGE::AssetDataSet dataSet;\n\t\tdataSet.filePath = File(\"ball\/ball.obj\");\n\t\tdataSet.skinName = \"ball\";\n\t\tdataSet.materialName = \"ball\";\n\n\t\tdataSet.serializedDirectory = std::tr2::sys::basic_directory_entry<std::tr2::sys::path>(\"..\/..\/Assets\/AGE-Assets-For-Test\/Serialized\");\n\t\tdataSet.rawDirectory = std::tr2::sys::basic_directory_entry<std::tr2::sys::path>(\"..\/..\/Assets\/AGE-Assets-For-Test\/Raw\");\n\n\t\tAGE::MaterialLoader::load(dataSet);\n\t\tAGE::ImageLoader::load(dataSet);\n\t\tAGE::MeshLoader::load(dataSet);\n\n\t\tAGE::MaterialLoader::save(dataSet);\n\t\tAGE::ImageLoader::save(dataSet);\n\t\tAGE::MeshLoader::save(dataSet);\n\t}\n\t{\n\t\tAGE::AssetDataSet dataSet;\n\t\tdataSet.filePath = File(\"cube\/cube.obj\");\n\t\tdataSet.skinName = \"cube\";\n\t\tdataSet.materialName = \"cube\";\n\n\t\tdataSet.serializedDirectory = std::tr2::sys::basic_directory_entry<std::tr2::sys::path>(\"..\/..\/Assets\/AGE-Assets-For-Test\/Serialized\");\n\t\tdataSet.rawDirectory = std::tr2::sys::basic_directory_entry<std::tr2::sys::path>(\"..\/..\/Assets\/AGE-Assets-For-Test\/Raw\");\n\n\t\tAGE::MaterialLoader::load(dataSet);\n\t\tAGE::ImageLoader::load(dataSet);\n\t\tAGE::MeshLoader::load(dataSet);\n\n\t\tAGE::MaterialLoader::save(dataSet);\n\t\tAGE::ImageLoader::save(dataSet);\n\t\tAGE::MeshLoader::save(dataSet);\n\t}\n\treturn (0);\n}<|endoftext|>"} {"text":"<commit_before>\/*******************************************************\n * Copyright (c) 2014, ArrayFire\n * All rights reserved.\n *\n * This file is distributed under 3-clause BSD license.\n * The complete license agreement can be obtained at:\n * http:\/\/arrayfire.com\/licenses\/BSD-3-Clause\n ********************************************************\/\n\n#include <af\/array.h>\n#include <af\/dim4.hpp>\n#include <af\/defines.h>\n#include <Array.hpp>\n#include <diagonal.hpp>\n#include <math.hpp>\n#include <err_cpu.hpp>\n\nnamespace cpu\n{\n template<typename T>\n Array<T> diagCreate(const Array<T> &in, const int num)\n {\n int size = in.dims()[0] + std::abs(num);\n int batch = in.dims()[1];\n Array<T> out = createEmptyArray<T>(dim4(size, size, batch));\n\n const T *iptr = in.get();\n T *optr = out.get();\n\n for (int k = 0; k < batch; k++) {\n for (int j = 0; j < size; j++) {\n for (int i = 0; i < size; i++) {\n T val = scalar<T>(0);\n if (i == j - num) {\n val = (num > 0) ? iptr[i] : iptr[j];\n }\n optr[i + j * out.strides()[1]] = val;\n }\n }\n optr += out.strides()[2];\n iptr += in.strides()[1];\n }\n\n return out;\n }\n\n template<typename T>\n Array<T> diagExtract(const Array<T> &in, const int num)\n {\n const dim_t *idims = in.dims().get();\n dim_t size = std::max(idims[0], idims[1]) - std::abs(num);\n Array<T> out = createEmptyArray<T>(dim4(size, 1, idims[2], idims[3]));\n\n const dim_t *odims = out.dims().get();\n\n const int i_off = (num > 0) ? (num * in.strides()[1]) : (-num);\n\n for (int l = 0; l < (int)odims[3]; l++) {\n\n for (int k = 0; k < (int)odims[2]; k++) {\n const T *iptr = in.get() + l * in.strides()[3] + k * in.strides()[2] + i_off;\n T *optr = out.get() + l * out.strides()[3] + k * out.strides()[2];\n\n for (int i = 0; i < (int)odims[0]; i++) {\n T val = scalar<T>(0);\n if (i < idims[0] && i < idims[1]) val = iptr[i * in.strides()[1] + i];\n optr[i] = val;\n }\n }\n }\n\n return out;\n }\n\n#define INSTANTIATE_DIAGONAL(T) \\\n template Array<T> diagExtract<T> (const Array<T> &in, const int num); \\\n template Array<T> diagCreate <T> (const Array<T> &in, const int num);\n\n INSTANTIATE_DIAGONAL(float)\n INSTANTIATE_DIAGONAL(double)\n INSTANTIATE_DIAGONAL(cfloat)\n INSTANTIATE_DIAGONAL(cdouble)\n INSTANTIATE_DIAGONAL(int)\n INSTANTIATE_DIAGONAL(uint)\n INSTANTIATE_DIAGONAL(intl)\n INSTANTIATE_DIAGONAL(uintl)\n INSTANTIATE_DIAGONAL(char)\n INSTANTIATE_DIAGONAL(uchar)\n\n}\n<commit_msg>Async CPU diagonal<commit_after>\/*******************************************************\n * Copyright (c) 2014, ArrayFire\n * All rights reserved.\n *\n * This file is distributed under 3-clause BSD license.\n * The complete license agreement can be obtained at:\n * http:\/\/arrayfire.com\/licenses\/BSD-3-Clause\n ********************************************************\/\n\n#include <af\/array.h>\n#include <af\/dim4.hpp>\n#include <af\/defines.h>\n#include <Array.hpp>\n#include <diagonal.hpp>\n#include <math.hpp>\n#include <err_cpu.hpp>\n#include <platform.hpp>\n#include <async_queue.hpp>\n\nnamespace cpu\n{\n template<typename T>\n Array<T> diagCreate(const Array<T> &in, const int num)\n {\n int size = in.dims()[0] + std::abs(num);\n int batch = in.dims()[1];\n Array<T> out = createEmptyArray<T>(dim4(size, size, batch));\n\n auto func = [=] (Array<T> out, const Array<T> in) {\n const T *iptr = in.get();\n T *optr = out.get();\n\n for (int k = 0; k < batch; k++) {\n for (int j = 0; j < size; j++) {\n for (int i = 0; i < size; i++) {\n T val = scalar<T>(0);\n if (i == j - num) {\n val = (num > 0) ? iptr[i] : iptr[j];\n }\n optr[i + j * out.strides()[1]] = val;\n }\n }\n optr += out.strides()[2];\n iptr += in.strides()[1];\n }\n };\n getQueue().enqueue(func, out, in);\n\n return out;\n }\n\n template<typename T>\n Array<T> diagExtract(const Array<T> &in, const int num)\n {\n const dim_t *idims = in.dims().get();\n dim_t size = std::max(idims[0], idims[1]) - std::abs(num);\n Array<T> out = createEmptyArray<T>(dim4(size, 1, idims[2], idims[3]));\n\n auto func = [=] (Array<T> out, const Array<T> in) {\n const dim_t *odims = out.dims().get();\n\n const int i_off = (num > 0) ? (num * in.strides()[1]) : (-num);\n\n for (int l = 0; l < (int)odims[3]; l++) {\n\n for (int k = 0; k < (int)odims[2]; k++) {\n const T *iptr = in.get() + l * in.strides()[3] + k * in.strides()[2] + i_off;\n T *optr = out.get() + l * out.strides()[3] + k * out.strides()[2];\n\n for (int i = 0; i < (int)odims[0]; i++) {\n T val = scalar<T>(0);\n if (i < idims[0] && i < idims[1]) val = iptr[i * in.strides()[1] + i];\n optr[i] = val;\n }\n }\n }\n };\n\n getQueue().enqueue(func, out, in);\n\n return out;\n }\n\n#define INSTANTIATE_DIAGONAL(T) \\\n template Array<T> diagExtract<T> (const Array<T> &in, const int num); \\\n template Array<T> diagCreate <T> (const Array<T> &in, const int num);\n\n INSTANTIATE_DIAGONAL(float)\n INSTANTIATE_DIAGONAL(double)\n INSTANTIATE_DIAGONAL(cfloat)\n INSTANTIATE_DIAGONAL(cdouble)\n INSTANTIATE_DIAGONAL(int)\n INSTANTIATE_DIAGONAL(uint)\n INSTANTIATE_DIAGONAL(intl)\n INSTANTIATE_DIAGONAL(uintl)\n INSTANTIATE_DIAGONAL(char)\n INSTANTIATE_DIAGONAL(uchar)\n\n}\n<|endoftext|>"} {"text":"<commit_before>#pragma once\n#ifndef NIFTY_PYTHON_GRAPH_LIFTED_MULTICUT_LEARNABLE_LIFTED_MULTICUT_OBJECTIVE_NAME_HXX\n#define NIFTY_PYTHON_GRAPH_LIFTED_MULTICUT_LEARNABLE_LIFTED_MULTICUT_OBJECTIVE_NAME_HXX\n\n#include \"nifty\/graph\/optimization\/lifted_multicut\/learnable_lifted_multicut_objective.hxx\"\n#include \"nifty\/python\/graph\/graph_name.hxx\"\n\nnamespace nifty{\nnamespace graph{\nnamespace lifted_multicut{\n\n\n template<class OBJECTIVE>\n struct LiftedMulticutObjectiveName;\n\n\n\n\n\n template<class GRAPH>\n struct LiftedMulticutObjectiveName<LearnableLiftedMulticutObjective<GRAPH, float> >{\n static std::string name(){\n return std::string(\"LearnableLiftedMulticutObjective\") + GraphName<GRAPH>::name();\n }\n };\n\n}\n}\n}\n\n#endif \/* NIFTY_PYTHON_GRAPH_LIFTED_MULTICUT_LEARNABLE_LIFTED_MULTICUT_OBJECTIVE_NAME_HXX *\/\n<commit_msg>fixed template issue in glue<commit_after>#pragma once\n#ifndef NIFTY_PYTHON_GRAPH_LIFTED_MULTICUT_LEARNABLE_LIFTED_MULTICUT_OBJECTIVE_NAME_HXX\n#define NIFTY_PYTHON_GRAPH_LIFTED_MULTICUT_LEARNABLE_LIFTED_MULTICUT_OBJECTIVE_NAME_HXX\n\n#include \"nifty\/graph\/optimization\/lifted_multicut\/learnable_lifted_multicut_objective.hxx\"\n#include \"nifty\/python\/graph\/graph_name.hxx\"\n\nnamespace nifty{\nnamespace graph{\nnamespace lifted_multicut{\n\n\n template<class OBJECTIVE>\n struct LiftedMulticutObjectiveName;\n\n\n\n\n\n template<class GRAPH, class T>\n struct LiftedMulticutObjectiveName<LearnableLiftedMulticutObjective<GRAPH, T> >{\n static std::string name(){\n return std::string(\"LearnableLiftedMulticutObjective\") + GraphName<GRAPH>::name();\n }\n };\n\n}\n}\n}\n\n#endif \/* NIFTY_PYTHON_GRAPH_LIFTED_MULTICUT_LEARNABLE_LIFTED_MULTICUT_OBJECTIVE_NAME_HXX *\/\n<|endoftext|>"} {"text":"<commit_before>#include \"settings.h\"\n\n#include \"ui_settings.h\"\n\n#include <ui\/settings\/camerainfo.h>\n#include <ui\/settings\/microphoneinfo.h>\n#include <ui\/settings\/screeninfo.h>\n#include \"settingshelper.h\"\n\n#include \"settingskeys.h\"\n\n#include <common.h>\n\n#include <QScreen>\n\n\nconst QStringList neededSettings = {SettingsKey::localRealname,\n SettingsKey::localUsername,\n SettingsKey::sipServerAddress,\n SettingsKey::sipAutoConnect};\n\nSettings::Settings(QWidget *parent) :\n QDialog(parent),\n basicUI_(new Ui::BasicSettings),\n cam_(std::shared_ptr<CameraInfo> (new CameraInfo())),\n mic_(std::shared_ptr<MicrophoneInfo> (new MicrophoneInfo())),\n screen_(std::shared_ptr<ScreenInfo> (new ScreenInfo())),\n sipSettings_(this),\n videoSettings_(this, cam_),\n audioSettings_(this, mic_),\n settings_(settingsFile, settingsFileFormat)\n{}\n\n\nSettings::~Settings()\n{\n \/\/ I believe the UI:s are destroyed when parents are destroyed\n}\n\n\nvoid Settings::init()\n{ \n basicUI_->setupUi(this);\n\n \/\/ Checks that settings values are correct for the program to start. Also sets GUI.\n getSettings(false);\n\n int videoID = getDeviceID(basicUI_->videoDevice_combo, SettingsKey::videoDeviceID,\n SettingsKey::videoDevice);\n int audioIndex = getDeviceID(basicUI_->audioDevice_combo, SettingsKey::audioDeviceID,\n SettingsKey::audioDevice);\n\n audioSettings_.init(audioIndex);\n videoSettings_.init(videoID);\n sipSettings_.init();\n\n \/\/QObject::connect(basicUI_->save, &QPushButton::clicked, this, &Settings::on_ok_clicked);\n \/\/QObject::connect(basicUI_->close, &QPushButton::clicked, this, &Settings::on_cancel_clicked);\n\n QObject::connect(&videoSettings_, &VideoSettings::updateVideoSettings,\n this, &Settings::updateVideoSettings);\n QObject::connect(&videoSettings_, &VideoSettings::hidden, this, &Settings::show);\n\n QObject::connect(&audioSettings_, &AudioSettings::updateAudioSettings,\n this, &Settings::updateAudioSettings);\n QObject::connect(&audioSettings_, &AudioSettings::hidden, this, &Settings::show);\n\n QObject::connect(&sipSettings_, &SIPSettings::updateCallSettings,\n this, &Settings::updateCallSettings);\n QObject::connect(&sipSettings_, &SIPSettings::hidden,\n this, &Settings::show);\n\n QObject::connect(basicUI_->serverAddress_edit, &QLineEdit::textChanged,\n this, &Settings::changedSIPText);\n QObject::connect(basicUI_->username_edit, &QLineEdit::textChanged,\n this, &Settings::changedSIPText);\n\n QObject::connect(basicUI_->serverAddress_edit, &QLineEdit::textChanged,\n this, &Settings::uiChangedString);\n\n QObject::connect(basicUI_->name_edit, &QLineEdit::textChanged,\n this, &Settings::uiChangedString);\n\n QObject::connect(basicUI_->username_edit, &QLineEdit::textChanged,\n this, &Settings::uiChangedString);\n\n QObject::connect(basicUI_->auto_connect_box, &QCheckBox::stateChanged,\n this, &Settings::uiChangedBool);\n\n QObject::connect(basicUI_->videoDevice_combo, &QComboBox::currentTextChanged,\n this, &Settings::uiChangedString);\n QObject::connect(basicUI_->audioDevice_combo, &QComboBox::currentTextChanged,\n this, &Settings::uiChangedString);\n QObject::connect(basicUI_->screenDevice_combo, &QComboBox::currentTextChanged,\n this, &Settings::uiChangedString);\n\n \/\/ TODO: Also emit the position of closed window and move this setting there\n}\n\n\nvoid Settings::show()\n{\n printNormal(this, \"Opening settings\");\n \/\/ initialize everytime in case they have changed\n initDeviceSelector(basicUI_->videoDevice_combo, SettingsKey::videoDeviceID,\n SettingsKey::videoDevice, cam_);\n initDeviceSelector(basicUI_->audioDevice_combo, SettingsKey::audioDeviceID,\n SettingsKey::audioDevice, mic_);\n initDeviceSelector(basicUI_->screenDevice_combo, SettingsKey::userScreenID,\n SettingsKey::userScreen, screen_);\n\n QWidget::show();\n basicUI_->save->hide();\n}\n\n\nvoid Settings::setMicState(bool enabled)\n{\n if (enabled)\n {\n settings_.setValue(SettingsKey::micStatus, \"1\");\n }\n else\n {\n settings_.setValue(SettingsKey::micStatus, \"0\");\n }\n}\n\n\nvoid Settings::setCameraState(bool enabled)\n{\n if (enabled)\n {\n settings_.setValue(SettingsKey::cameraStatus, \"1\");\n }\n else\n {\n settings_.setValue(SettingsKey::cameraStatus, \"0\");\n }\n}\n\n\nvoid Settings::setScreenShareState(bool enabled)\n{\n if (enabled)\n {\n int screenIndex = getDeviceID(basicUI_->screenDevice_combo, SettingsKey::userScreenID,\n SettingsKey::userScreen);\n\n if (screenIndex < QGuiApplication::screens().size())\n {\n QScreen *screen = QGuiApplication::screens().at(screenIndex);\n\n if (screen != nullptr)\n {\n QSize resolution;\n resolution.setWidth(screen->size().width() - screen->size().width()%8);\n resolution.setHeight(screen->size().height() - screen->size().height()%8);\n\n settings_.setValue(SettingsKey::screenShareStatus, \"1\");\n settings_.setValue(SettingsKey::videoResultionWidth, resolution.width());\n settings_.setValue(SettingsKey::videoResultionHeight, resolution.height());\n settings_.setValue(SettingsKey::videoFramerate, \"5\");\n videoSettings_.setScreenShareState(enabled);\n\n printNormal(this, \"Enabled Screen sharing\", \"Screen resolution\",\n QString::number(resolution.width()) + \"x\" + QString::number(resolution.height()));\n }\n }\n }\n else\n {\n settings_.setValue(SettingsKey::screenShareStatus, \"0\");\n videoSettings_.setScreenShareState(enabled);\n videoSettings_.saveCameraCapabilities(getDeviceID(basicUI_->audioDevice_combo,\n SettingsKey::videoDeviceID,\n SettingsKey::videoDevice), !enabled);\n }\n}\n\n\nvoid Settings::uiChangedString(QString text)\n{\n Q_UNUSED(text);\n basicUI_->save->show();\n}\n\n\nvoid Settings::uiChangedBool(bool state)\n{\n Q_UNUSED(state);\n basicUI_->save->show();\n}\n\n\nvoid Settings::on_save_clicked()\n{\n printNormal(this, \"Saving settings\");\n \/\/ The UI values are saved to settings.\n saveSettings();\n setScreenShareState(settingEnabled(SettingsKey::screenShareStatus));\n\n emit updateCallSettings();\n emit updateVideoSettings();\n emit updateAudioSettings();\n\n basicUI_->save->hide();\n}\n\n\nvoid Settings::on_close_clicked()\n{\n printNormal(this, \"Closing Settings. Gettings settings from file.\");\n\n if (checkSettingsList(settings_, neededSettings))\n {\n \/\/ discard UI values and restore the settings from file\n getSettings(false);\n hide();\n }\n}\n\n\nvoid Settings::on_sip_settings_button_clicked()\n{\n saveSettings();\n hide();\n sipSettings_.show();\n}\n\n\nvoid Settings::on_video_settings_button_clicked()\n{\n saveSettings();\n hide();\n videoSettings_.show();\n}\n\n\nvoid Settings::on_audio_settings_button_clicked()\n{\n saveSettings();\n hide();\n audioSettings_.show();\n}\n\n\/\/ records the settings\nvoid Settings::saveSettings()\n{\n printNormal(this, \"Recording settings\");\n\n \/\/ Local settings\n saveTextValue(SettingsKey::localRealname, basicUI_->name_edit->text(), settings_);\n saveTextValue(SettingsKey::localUsername, basicUI_->username_edit->text(), settings_);\n saveTextValue(SettingsKey::sipServerAddress, basicUI_->serverAddress_edit->text(), settings_);\n\n saveCheckBox(SettingsKey::sipAutoConnect, basicUI_->auto_connect_box, settings_);\n\n saveDevice(basicUI_->videoDevice_combo, SettingsKey::videoDeviceID,\n SettingsKey::videoDevice, true);\n saveDevice(basicUI_->audioDevice_combo, SettingsKey::audioDeviceID,\n SettingsKey::audioDevice, false);\n saveDevice(basicUI_->screenDevice_combo, SettingsKey::userScreenID,\n SettingsKey::userScreen, false);\n}\n\n\n\/\/ restores recorded settings\nvoid Settings::getSettings(bool changedDevice)\n{\n initDeviceSelector(basicUI_->videoDevice_combo, SettingsKey::videoDeviceID,\n SettingsKey::videoDevice, cam_);\n initDeviceSelector(basicUI_->audioDevice_combo, SettingsKey::audioDeviceID,\n SettingsKey::audioDevice, mic_);\n initDeviceSelector(basicUI_->screenDevice_combo, SettingsKey::userScreenID,\n SettingsKey::userScreen, screen_);\n\n \/\/get values from QSettings\n if (checkSettingsList(settings_, neededSettings))\n {\n printNormal(this, \"Loading settings from file\", {\"File\"}, {settings_.fileName()});\n\n basicUI_->name_edit->setText (settings_.value(SettingsKey::localRealname).toString());\n basicUI_->username_edit->setText (settings_.value(SettingsKey::localUsername).toString());\n\n basicUI_->serverAddress_edit->setText(settings_.value(SettingsKey::sipServerAddress).toString());\n\n restoreCheckBox(SettingsKey::sipAutoConnect, basicUI_->auto_connect_box, settings_);\n\n \/\/ updates the sip text label\n changedSIPText(\"\");\n\n \/\/ set index for camera\n int videoIndex = getDeviceID(basicUI_->videoDevice_combo, SettingsKey::videoDeviceID,\n SettingsKey::videoDevice);\n if(changedDevice)\n {\n videoSettings_.changedDevice(videoIndex);\n }\n basicUI_->videoDevice_combo->setCurrentIndex(videoIndex);\n\n \/\/ set correct entry for microphone selector\n int audioIndex = getDeviceID(basicUI_->audioDevice_combo, SettingsKey::audioDeviceID,\n SettingsKey::audioDevice);\n if (basicUI_->audioDevice_combo->count() != 0)\n {\n if (audioIndex != -1)\n {\n basicUI_->audioDevice_combo->setCurrentIndex(audioIndex);\n }\n else\n {\n basicUI_->audioDevice_combo->setCurrentIndex(0);\n }\n }\n\n \/\/ set index for screen\n int screenIndex = getDeviceID(basicUI_->screenDevice_combo, SettingsKey::userScreenID,\n SettingsKey::userScreen);\n if (basicUI_->screenDevice_combo->count() != 0)\n {\n if (screenIndex != -1)\n {\n basicUI_->screenDevice_combo->setCurrentIndex(screenIndex);\n }\n else\n {\n basicUI_->screenDevice_combo->setCurrentIndex(0);\n }\n }\n }\n else\n {\n resetFaultySettings();\n }\n}\n\n\nvoid Settings::resetFaultySettings()\n{\n printWarning(this, \"Could not restore settings! Resetting settings from defaults.\");\n\n \/\/ record GUI settings in hope that they are correct ( is case by default )\n saveSettings();\n\n videoSettings_.resetSettings(getDeviceID(basicUI_->videoDevice_combo,\n SettingsKey::videoDeviceID,\n SettingsKey::videoDevice));\n\n audioSettings_.resetSettings(getDeviceID(basicUI_->audioDevice_combo,\n SettingsKey::audioDeviceID,\n SettingsKey::audioDevice));\n\n \/\/ we set the connecting to true at this point because we want two things:\n \/\/ 1) that Kvazzup doesn't connect to any server without user permission\n \/\/ 2) that connecting to server is default since it is the easiest way to use Kvazzup\n \/\/ These two conditions can only be achieved by modifying UI after settings have been saved\n basicUI_->auto_connect_box->setChecked(true);\n \n \/\/ Show resetted settings to user so she can fix them manually\n show();\n}\n\n\nvoid Settings::initDeviceSelector(QComboBox* deviceSelector,\n QString settingID,\n QString settingsDevice,\n std::shared_ptr<DeviceInfoInterface> interface)\n{\n deviceSelector->clear();\n QStringList devices = interface->getDeviceList();\n for(int i = 0; i < devices.size(); ++i)\n {\n deviceSelector->addItem( devices[i]);\n }\n int deviceIndex = getDeviceID(deviceSelector, settingID, settingsDevice);\n\n if(deviceIndex >= deviceSelector->count())\n {\n deviceSelector->setCurrentIndex(0);\n }\n else\n {\n deviceSelector->setCurrentIndex(deviceIndex);\n }\n\n \/\/printNormal(this, \"Added \" + QString::number(deviceSelector->count()) + \" devices to selector\",\n \/\/ {\"SettingsID\"}, {settingID});\n}\n\n\nint Settings::getDeviceID(QComboBox* deviceSelector, QString settingID,\n QString settingsDevice)\n{\n Q_ASSERT(deviceSelector);\n QString deviceName = settings_.value(settingsDevice).toString();\n\n int deviceIndex = deviceSelector->findText(deviceName);\n int deviceID = settings_.value(settingID).toInt();\n\n\/\/ printDebug(DEBUG_NORMAL, this, \"Getting device ID from selector list\",\n\/\/ {\"SettingsID\", \"DeviceName\", \"List Index\", \"Number of items\"},\n\/\/ {settingID, deviceName, QString::number(deviceIndex),\n\/\/ QString::number(deviceSelector->count())});\n\n \/\/ if the device exists in list\n if(deviceIndex != -1 && deviceSelector->count() != 0)\n {\n \/\/ if we have multiple devices with same name we use id\n if(deviceID != deviceIndex\n && deviceSelector->itemText(deviceID) == settings_.value(settingsDevice).toString())\n {\n return deviceID;\n }\n else\n {\n \/\/ the recorded info was false and our found device is chosen\n settings_.setValue(settingID, deviceIndex);\n return deviceIndex;\n }\n } \/\/ if there are devices available, use first\n else if(deviceSelector->count() != 0)\n {\n \/\/ could not find the device. Choosing first one\n settings_.setValue(settingID, 0);\n return 0;\n }\n\n \/\/ no devices attached\n return -1;\n}\n\n\nvoid Settings::saveDevice(QComboBox* deviceSelector, QString settingsID,\n QString settingsDevice, bool video)\n{\n int currentIndex = deviceSelector->currentIndex();\n if( currentIndex != -1)\n {\n if(deviceSelector->currentText() != settings_.value(settingsDevice))\n {\n settings_.setValue(settingsDevice, deviceSelector->currentText());\n \/\/ set capability to first\n\n if (video)\n {\n videoSettings_.changedDevice(currentIndex);\n }\n else\n {\n audioSettings_.changedDevice(currentIndex);\n }\n }\n else if(basicUI_->videoDevice_combo->currentIndex() != settings_.value(settingsID))\n {\n if (video)\n {\n videoSettings_.changedDevice(currentIndex);\n }\n else\n {\n audioSettings_.changedDevice(currentIndex);\n }\n }\n\n \/\/ record index in all cases\n settings_.setValue(settingsID, currentIndex);\n }\n}\n\n\nvoid Settings::changedSIPText(const QString &text)\n{\n Q_UNUSED(text);\n basicUI_->sipAddress->setText(\"sip:\" + basicUI_->username_edit->text()\n + \"@\" + basicUI_->serverAddress_edit->text());\n}\n\n\nvoid Settings::updateServerStatus(QString status)\n{\n basicUI_->status->setText(status);\n}\n<commit_msg>fix(Settings): Initialize camera and mic buttons when starting the first time<commit_after>#include \"settings.h\"\n\n#include \"ui_settings.h\"\n\n#include <ui\/settings\/camerainfo.h>\n#include <ui\/settings\/microphoneinfo.h>\n#include <ui\/settings\/screeninfo.h>\n#include \"settingshelper.h\"\n\n#include \"settingskeys.h\"\n\n#include <common.h>\n\n#include <QScreen>\n\n\nconst QStringList neededSettings = {SettingsKey::localRealname,\n SettingsKey::localUsername,\n SettingsKey::sipServerAddress,\n SettingsKey::sipAutoConnect};\n\nSettings::Settings(QWidget *parent) :\n QDialog(parent),\n basicUI_(new Ui::BasicSettings),\n cam_(std::shared_ptr<CameraInfo> (new CameraInfo())),\n mic_(std::shared_ptr<MicrophoneInfo> (new MicrophoneInfo())),\n screen_(std::shared_ptr<ScreenInfo> (new ScreenInfo())),\n sipSettings_(this),\n videoSettings_(this, cam_),\n audioSettings_(this, mic_),\n settings_(settingsFile, settingsFileFormat)\n{}\n\n\nSettings::~Settings()\n{\n \/\/ I believe the UI:s are destroyed when parents are destroyed\n}\n\n\nvoid Settings::init()\n{ \n basicUI_->setupUi(this);\n\n \/\/ Checks that settings values are correct for the program to start. Also sets GUI.\n getSettings(false);\n\n int videoID = getDeviceID(basicUI_->videoDevice_combo, SettingsKey::videoDeviceID,\n SettingsKey::videoDevice);\n int audioIndex = getDeviceID(basicUI_->audioDevice_combo, SettingsKey::audioDeviceID,\n SettingsKey::audioDevice);\n\n audioSettings_.init(audioIndex);\n videoSettings_.init(videoID);\n sipSettings_.init();\n\n \/\/QObject::connect(basicUI_->save, &QPushButton::clicked, this, &Settings::on_ok_clicked);\n \/\/QObject::connect(basicUI_->close, &QPushButton::clicked, this, &Settings::on_cancel_clicked);\n\n QObject::connect(&videoSettings_, &VideoSettings::updateVideoSettings,\n this, &Settings::updateVideoSettings);\n QObject::connect(&videoSettings_, &VideoSettings::hidden, this, &Settings::show);\n\n QObject::connect(&audioSettings_, &AudioSettings::updateAudioSettings,\n this, &Settings::updateAudioSettings);\n QObject::connect(&audioSettings_, &AudioSettings::hidden, this, &Settings::show);\n\n QObject::connect(&sipSettings_, &SIPSettings::updateCallSettings,\n this, &Settings::updateCallSettings);\n QObject::connect(&sipSettings_, &SIPSettings::hidden,\n this, &Settings::show);\n\n QObject::connect(basicUI_->serverAddress_edit, &QLineEdit::textChanged,\n this, &Settings::changedSIPText);\n QObject::connect(basicUI_->username_edit, &QLineEdit::textChanged,\n this, &Settings::changedSIPText);\n\n QObject::connect(basicUI_->serverAddress_edit, &QLineEdit::textChanged,\n this, &Settings::uiChangedString);\n\n QObject::connect(basicUI_->name_edit, &QLineEdit::textChanged,\n this, &Settings::uiChangedString);\n\n QObject::connect(basicUI_->username_edit, &QLineEdit::textChanged,\n this, &Settings::uiChangedString);\n\n QObject::connect(basicUI_->auto_connect_box, &QCheckBox::stateChanged,\n this, &Settings::uiChangedBool);\n\n QObject::connect(basicUI_->videoDevice_combo, &QComboBox::currentTextChanged,\n this, &Settings::uiChangedString);\n QObject::connect(basicUI_->audioDevice_combo, &QComboBox::currentTextChanged,\n this, &Settings::uiChangedString);\n QObject::connect(basicUI_->screenDevice_combo, &QComboBox::currentTextChanged,\n this, &Settings::uiChangedString);\n\n\n if (!settings_.value(SettingsKey::micStatus).isValid())\n {\n setMicState(true);\n }\n\n\n if (!settings_.value(SettingsKey::cameraStatus).isValid())\n {\n setCameraState(true);\n }\n\n \/\/ TODO: Also emit the position of closed window and move this setting there\n}\n\n\nvoid Settings::show()\n{\n printNormal(this, \"Opening settings\");\n \/\/ initialize everytime in case they have changed\n initDeviceSelector(basicUI_->videoDevice_combo, SettingsKey::videoDeviceID,\n SettingsKey::videoDevice, cam_);\n initDeviceSelector(basicUI_->audioDevice_combo, SettingsKey::audioDeviceID,\n SettingsKey::audioDevice, mic_);\n initDeviceSelector(basicUI_->screenDevice_combo, SettingsKey::userScreenID,\n SettingsKey::userScreen, screen_);\n\n QWidget::show();\n basicUI_->save->hide();\n}\n\n\nvoid Settings::setMicState(bool enabled)\n{\n if (enabled)\n {\n settings_.setValue(SettingsKey::micStatus, \"1\");\n }\n else\n {\n settings_.setValue(SettingsKey::micStatus, \"0\");\n }\n}\n\n\nvoid Settings::setCameraState(bool enabled)\n{\n if (enabled)\n {\n settings_.setValue(SettingsKey::cameraStatus, \"1\");\n }\n else\n {\n settings_.setValue(SettingsKey::cameraStatus, \"0\");\n }\n}\n\n\nvoid Settings::setScreenShareState(bool enabled)\n{\n if (enabled)\n {\n int screenIndex = getDeviceID(basicUI_->screenDevice_combo, SettingsKey::userScreenID,\n SettingsKey::userScreen);\n\n if (screenIndex < QGuiApplication::screens().size())\n {\n QScreen *screen = QGuiApplication::screens().at(screenIndex);\n\n if (screen != nullptr)\n {\n QSize resolution;\n resolution.setWidth(screen->size().width() - screen->size().width()%8);\n resolution.setHeight(screen->size().height() - screen->size().height()%8);\n\n settings_.setValue(SettingsKey::screenShareStatus, \"1\");\n settings_.setValue(SettingsKey::videoResultionWidth, resolution.width());\n settings_.setValue(SettingsKey::videoResultionHeight, resolution.height());\n settings_.setValue(SettingsKey::videoFramerate, \"5\");\n videoSettings_.setScreenShareState(enabled);\n\n printNormal(this, \"Enabled Screen sharing\", \"Screen resolution\",\n QString::number(resolution.width()) + \"x\" + QString::number(resolution.height()));\n }\n }\n }\n else\n {\n settings_.setValue(SettingsKey::screenShareStatus, \"0\");\n videoSettings_.setScreenShareState(enabled);\n videoSettings_.saveCameraCapabilities(getDeviceID(basicUI_->audioDevice_combo,\n SettingsKey::videoDeviceID,\n SettingsKey::videoDevice), !enabled);\n }\n}\n\n\nvoid Settings::uiChangedString(QString text)\n{\n Q_UNUSED(text);\n basicUI_->save->show();\n}\n\n\nvoid Settings::uiChangedBool(bool state)\n{\n Q_UNUSED(state);\n basicUI_->save->show();\n}\n\n\nvoid Settings::on_save_clicked()\n{\n printNormal(this, \"Saving settings\");\n \/\/ The UI values are saved to settings.\n saveSettings();\n setScreenShareState(settingEnabled(SettingsKey::screenShareStatus));\n\n emit updateCallSettings();\n emit updateVideoSettings();\n emit updateAudioSettings();\n\n basicUI_->save->hide();\n}\n\n\nvoid Settings::on_close_clicked()\n{\n printNormal(this, \"Closing Settings. Gettings settings from file.\");\n\n if (checkSettingsList(settings_, neededSettings))\n {\n \/\/ discard UI values and restore the settings from file\n getSettings(false);\n hide();\n }\n}\n\n\nvoid Settings::on_sip_settings_button_clicked()\n{\n saveSettings();\n hide();\n sipSettings_.show();\n}\n\n\nvoid Settings::on_video_settings_button_clicked()\n{\n saveSettings();\n hide();\n videoSettings_.show();\n}\n\n\nvoid Settings::on_audio_settings_button_clicked()\n{\n saveSettings();\n hide();\n audioSettings_.show();\n}\n\n\/\/ records the settings\nvoid Settings::saveSettings()\n{\n printNormal(this, \"Recording settings\");\n\n \/\/ Local settings\n saveTextValue(SettingsKey::localRealname, basicUI_->name_edit->text(), settings_);\n saveTextValue(SettingsKey::localUsername, basicUI_->username_edit->text(), settings_);\n saveTextValue(SettingsKey::sipServerAddress, basicUI_->serverAddress_edit->text(), settings_);\n\n saveCheckBox(SettingsKey::sipAutoConnect, basicUI_->auto_connect_box, settings_);\n\n saveDevice(basicUI_->videoDevice_combo, SettingsKey::videoDeviceID,\n SettingsKey::videoDevice, true);\n saveDevice(basicUI_->audioDevice_combo, SettingsKey::audioDeviceID,\n SettingsKey::audioDevice, false);\n saveDevice(basicUI_->screenDevice_combo, SettingsKey::userScreenID,\n SettingsKey::userScreen, false);\n}\n\n\n\/\/ restores recorded settings\nvoid Settings::getSettings(bool changedDevice)\n{\n initDeviceSelector(basicUI_->videoDevice_combo, SettingsKey::videoDeviceID,\n SettingsKey::videoDevice, cam_);\n initDeviceSelector(basicUI_->audioDevice_combo, SettingsKey::audioDeviceID,\n SettingsKey::audioDevice, mic_);\n initDeviceSelector(basicUI_->screenDevice_combo, SettingsKey::userScreenID,\n SettingsKey::userScreen, screen_);\n\n \/\/get values from QSettings\n if (checkSettingsList(settings_, neededSettings))\n {\n printNormal(this, \"Loading settings from file\", {\"File\"}, {settings_.fileName()});\n\n basicUI_->name_edit->setText (settings_.value(SettingsKey::localRealname).toString());\n basicUI_->username_edit->setText (settings_.value(SettingsKey::localUsername).toString());\n\n basicUI_->serverAddress_edit->setText(settings_.value(SettingsKey::sipServerAddress).toString());\n\n restoreCheckBox(SettingsKey::sipAutoConnect, basicUI_->auto_connect_box, settings_);\n\n \/\/ updates the sip text label\n changedSIPText(\"\");\n\n \/\/ set index for camera\n int videoIndex = getDeviceID(basicUI_->videoDevice_combo, SettingsKey::videoDeviceID,\n SettingsKey::videoDevice);\n if(changedDevice)\n {\n videoSettings_.changedDevice(videoIndex);\n }\n basicUI_->videoDevice_combo->setCurrentIndex(videoIndex);\n\n \/\/ set correct entry for microphone selector\n int audioIndex = getDeviceID(basicUI_->audioDevice_combo, SettingsKey::audioDeviceID,\n SettingsKey::audioDevice);\n if (basicUI_->audioDevice_combo->count() != 0)\n {\n if (audioIndex != -1)\n {\n basicUI_->audioDevice_combo->setCurrentIndex(audioIndex);\n }\n else\n {\n basicUI_->audioDevice_combo->setCurrentIndex(0);\n }\n }\n\n \/\/ set index for screen\n int screenIndex = getDeviceID(basicUI_->screenDevice_combo, SettingsKey::userScreenID,\n SettingsKey::userScreen);\n if (basicUI_->screenDevice_combo->count() != 0)\n {\n if (screenIndex != -1)\n {\n basicUI_->screenDevice_combo->setCurrentIndex(screenIndex);\n }\n else\n {\n basicUI_->screenDevice_combo->setCurrentIndex(0);\n }\n }\n }\n else\n {\n resetFaultySettings();\n }\n}\n\n\nvoid Settings::resetFaultySettings()\n{\n printWarning(this, \"Could not restore settings! Resetting settings from defaults.\");\n\n \/\/ record GUI settings in hope that they are correct ( is case by default )\n saveSettings();\n\n videoSettings_.resetSettings(getDeviceID(basicUI_->videoDevice_combo,\n SettingsKey::videoDeviceID,\n SettingsKey::videoDevice));\n\n audioSettings_.resetSettings(getDeviceID(basicUI_->audioDevice_combo,\n SettingsKey::audioDeviceID,\n SettingsKey::audioDevice));\n\n \/\/ we set the connecting to true at this point because we want two things:\n \/\/ 1) that Kvazzup doesn't connect to any server without user permission\n \/\/ 2) that connecting to server is default since it is the easiest way to use Kvazzup\n \/\/ These two conditions can only be achieved by modifying UI after settings have been saved\n basicUI_->auto_connect_box->setChecked(true);\n \n \/\/ Show resetted settings to user so she can fix them manually\n show();\n}\n\n\nvoid Settings::initDeviceSelector(QComboBox* deviceSelector,\n QString settingID,\n QString settingsDevice,\n std::shared_ptr<DeviceInfoInterface> interface)\n{\n deviceSelector->clear();\n QStringList devices = interface->getDeviceList();\n for(int i = 0; i < devices.size(); ++i)\n {\n deviceSelector->addItem( devices[i]);\n }\n int deviceIndex = getDeviceID(deviceSelector, settingID, settingsDevice);\n\n if(deviceIndex >= deviceSelector->count())\n {\n deviceSelector->setCurrentIndex(0);\n }\n else\n {\n deviceSelector->setCurrentIndex(deviceIndex);\n }\n\n \/\/printNormal(this, \"Added \" + QString::number(deviceSelector->count()) + \" devices to selector\",\n \/\/ {\"SettingsID\"}, {settingID});\n}\n\n\nint Settings::getDeviceID(QComboBox* deviceSelector, QString settingID,\n QString settingsDevice)\n{\n Q_ASSERT(deviceSelector);\n QString deviceName = settings_.value(settingsDevice).toString();\n\n int deviceIndex = deviceSelector->findText(deviceName);\n int deviceID = settings_.value(settingID).toInt();\n\n\/\/ printDebug(DEBUG_NORMAL, this, \"Getting device ID from selector list\",\n\/\/ {\"SettingsID\", \"DeviceName\", \"List Index\", \"Number of items\"},\n\/\/ {settingID, deviceName, QString::number(deviceIndex),\n\/\/ QString::number(deviceSelector->count())});\n\n \/\/ if the device exists in list\n if(deviceIndex != -1 && deviceSelector->count() != 0)\n {\n \/\/ if we have multiple devices with same name we use id\n if(deviceID != deviceIndex\n && deviceSelector->itemText(deviceID) == settings_.value(settingsDevice).toString())\n {\n return deviceID;\n }\n else\n {\n \/\/ the recorded info was false and our found device is chosen\n settings_.setValue(settingID, deviceIndex);\n return deviceIndex;\n }\n } \/\/ if there are devices available, use first\n else if(deviceSelector->count() != 0)\n {\n \/\/ could not find the device. Choosing first one\n settings_.setValue(settingID, 0);\n return 0;\n }\n\n \/\/ no devices attached\n return -1;\n}\n\n\nvoid Settings::saveDevice(QComboBox* deviceSelector, QString settingsID,\n QString settingsDevice, bool video)\n{\n int currentIndex = deviceSelector->currentIndex();\n if( currentIndex != -1)\n {\n if(deviceSelector->currentText() != settings_.value(settingsDevice))\n {\n settings_.setValue(settingsDevice, deviceSelector->currentText());\n \/\/ set capability to first\n\n if (video)\n {\n videoSettings_.changedDevice(currentIndex);\n }\n else\n {\n audioSettings_.changedDevice(currentIndex);\n }\n }\n else if(basicUI_->videoDevice_combo->currentIndex() != settings_.value(settingsID))\n {\n if (video)\n {\n videoSettings_.changedDevice(currentIndex);\n }\n else\n {\n audioSettings_.changedDevice(currentIndex);\n }\n }\n\n \/\/ record index in all cases\n settings_.setValue(settingsID, currentIndex);\n }\n}\n\n\nvoid Settings::changedSIPText(const QString &text)\n{\n Q_UNUSED(text);\n basicUI_->sipAddress->setText(\"sip:\" + basicUI_->username_edit->text()\n + \"@\" + basicUI_->serverAddress_edit->text());\n}\n\n\nvoid Settings::updateServerStatus(QString status)\n{\n basicUI_->status->setText(status);\n}\n<|endoftext|>"} {"text":"<commit_before>\/******************************************************************************\n * Copyright 2018 The Apollo Authors. All Rights Reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *****************************************************************************\/\n\n\/**\n * @file\n **\/\n\n#include \"modules\/planning\/scenarios\/stop_sign\/unprotected\/stage_pre_stop.h\"\n\n#include <algorithm>\n#include <utility>\n\n#include \"modules\/perception\/proto\/perception_obstacle.pb.h\"\n\n#include \"cyber\/common\/log.h\"\n#include \"modules\/common\/time\/time.h\"\n#include \"modules\/common\/vehicle_state\/vehicle_state_provider.h\"\n#include \"modules\/map\/pnc_map\/path.h\"\n#include \"modules\/planning\/common\/frame.h\"\n#include \"modules\/planning\/common\/planning_context.h\"\n#include \"modules\/planning\/scenarios\/util\/util.h\"\n#include \"modules\/planning\/tasks\/deciders\/decider_creep.h\"\n\nnamespace apollo {\nnamespace planning {\nnamespace scenario {\nnamespace stop_sign {\n\nusing common::TrajectoryPoint;\nusing common::time::Clock;\nusing hdmap::HDMapUtil;\nusing hdmap::LaneInfoConstPtr;\nusing hdmap::OverlapInfoConstPtr;\nusing perception::PerceptionObstacle;\n\nusing StopSignLaneVehicles =\n std::unordered_map<std::string, std::vector<std::string>>;\n\nStage::StageStatus StopSignUnprotectedStagePreStop::Process(\n const TrajectoryPoint& planning_init_point, Frame* frame) {\n ADEBUG << \"stage: PreStop\";\n CHECK_NOTNULL(frame);\n\n scenario_config_.CopyFrom(GetContext()->scenario_config);\n\n bool plan_ok = ExecuteTaskOnReferenceLine(planning_init_point, frame);\n if (!plan_ok) {\n AERROR << \"StopSignUnprotectedStagePreStop planning error\";\n }\n\n const auto& reference_line_info = frame->reference_line_info().front();\n\n \/\/ check if the stop_sign is still along reference_line\n std::string stop_sign_overlap_id =\n PlanningContext::GetScenarioInfo()->current_stop_sign_overlap.object_id;\n if (scenario::CheckStopSignDone(reference_line_info, stop_sign_overlap_id)) {\n return FinishScenario();\n }\n\n constexpr double kPassStopLineBuffer = 0.3; \/\/ unit: m\n const double adc_front_edge_s = reference_line_info.AdcSlBoundary().end_s();\n const double distance_adc_pass_stop_sign =\n adc_front_edge_s -\n PlanningContext::GetScenarioInfo()->current_stop_sign_overlap.start_s;\n if (distance_adc_pass_stop_sign <= kPassStopLineBuffer) {\n \/\/ not passed stop line, check valid stop\n if (CheckADCStop(reference_line_info)) {\n return FinishStage();\n }\n } else {\n \/\/ passed stop line\n return FinishStage();\n }\n\n \/\/ PRE-STOP\n const PathDecision& path_decision = reference_line_info.path_decision();\n auto& watch_vehicles = GetContext()->watch_vehicles;\n\n std::vector<std::string> watch_vehicle_ids;\n for (auto it = watch_vehicles.begin(); it != watch_vehicles.end(); ++it) {\n std::copy(it->second.begin(), it->second.end(),\n std::back_inserter(watch_vehicle_ids));\n\n \/\/ for debug string\n std::string associated_lane_id = it->first;\n std::string s;\n for (size_t i = 0; i < it->second.size(); ++i) {\n std::string vehicle_id = (it->second)[i];\n s = s.empty() ? vehicle_id : s + \",\" + vehicle_id;\n }\n ADEBUG << \"watch_vehicles: lane_id[\" << associated_lane_id << \"] vehicle[\"\n << s << \"]\";\n }\n\n \/\/ pass vehicles being watched to DECIDER_RULE_BASED_STOP task\n \/\/ for visualization\n PlanningContext::GetScenarioInfo()->stop_sign_wait_for_obstacles.clear();\n std::copy(\n watch_vehicle_ids.begin(), watch_vehicle_ids.end(),\n std::back_inserter(\n PlanningContext::GetScenarioInfo()->stop_sign_wait_for_obstacles));\n\n for (const auto* obstacle : path_decision.obstacles().Items()) {\n \/\/ add to watch_vehicles if adc is still proceeding to stop sign\n AddWatchVehicle(*obstacle, &watch_vehicles);\n }\n\n return Stage::RUNNING;\n}\n\n\/**\n * @brief: add a watch vehicle which arrives at stop sign ahead of adc\n *\/\nint StopSignUnprotectedStagePreStop::AddWatchVehicle(\n const Obstacle& obstacle, StopSignLaneVehicles* watch_vehicles) {\n CHECK_NOTNULL(watch_vehicles);\n\n const PerceptionObstacle& perception_obstacle = obstacle.Perception();\n const std::string& obstacle_id = std::to_string(perception_obstacle.id());\n PerceptionObstacle::Type obstacle_type = perception_obstacle.type();\n std::string obstacle_type_name = PerceptionObstacle_Type_Name(obstacle_type);\n\n \/\/ check type\n if (obstacle_type != PerceptionObstacle::UNKNOWN &&\n obstacle_type != PerceptionObstacle::UNKNOWN_MOVABLE &&\n obstacle_type != PerceptionObstacle::BICYCLE &&\n obstacle_type != PerceptionObstacle::VEHICLE) {\n ADEBUG << \"obstacle_id[\" << obstacle_id << \"] type[\" << obstacle_type_name\n << \"]. skip\";\n return 0;\n }\n\n auto point = common::util::MakePointENU(perception_obstacle.position().x(),\n perception_obstacle.position().y(),\n perception_obstacle.position().z());\n double obstacle_s = 0.0;\n double obstacle_l = 0.0;\n LaneInfoConstPtr obstacle_lane;\n if (HDMapUtil::BaseMap().GetNearestLaneWithHeading(\n point, 5.0, perception_obstacle.theta(), M_PI \/ 3.0, &obstacle_lane,\n &obstacle_s, &obstacle_l) != 0) {\n ADEBUG << \"obstacle_id[\" << obstacle_id << \"] type[\" << obstacle_type_name\n << \"]: Failed to find nearest lane from map for position: \"\n << point.DebugString()\n << \"; heading:\" << perception_obstacle.theta();\n return -1;\n }\n\n \/\/ check obstacle is on an associate lane guarded by stop sign\n std::string obstable_lane_id = obstacle_lane.get()->id().id();\n auto assoc_lane_it = std::find_if(\n GetContext()->associated_lanes.begin(),\n GetContext()->associated_lanes.end(),\n [&obstable_lane_id](\n std::pair<LaneInfoConstPtr, OverlapInfoConstPtr>& assc_lane) {\n return assc_lane.first.get()->id().id() == obstable_lane_id;\n });\n if (assoc_lane_it == GetContext()->associated_lanes.end()) {\n ADEBUG << \"obstacle_id[\" << obstacle_id << \"] type[\" << obstacle_type_name\n << \"] lane_id[\" << obstable_lane_id\n << \"] not associated with current stop_sign. skip\";\n return -1;\n }\n\n \/\/ check a valid stop for stop line of the stop_sign\n auto over_lap_info = assoc_lane_it->second.get()->GetObjectOverlapInfo(\n obstacle_lane.get()->id());\n if (over_lap_info == nullptr) {\n AERROR << \"can't find over_lap_info for id: \" << obstable_lane_id;\n return -1;\n }\n const double stop_line_s = over_lap_info->lane_overlap_info().start_s();\n const double obstacle_end_s = obstacle_s + perception_obstacle.length() \/ 2;\n const double distance_to_stop_line = stop_line_s - obstacle_end_s;\n\n if (distance_to_stop_line < 0 ||\n scenario_config_.watch_vehicle_max_valid_stop_distance()) {\n ADEBUG << \"obstacle_id[\" << obstacle_id << \"] type[\" << obstacle_type_name\n << \"] distance_to_stop_line[\" << distance_to_stop_line\n << \"]; stop_line_s\" << stop_line_s << \"]; obstacle_end_s[\"\n << obstacle_end_s\n << \"] too far from stop line or pass stop line. skip\";\n return -1;\n }\n\n \/\/ use a vector since motocycles\/bicycles can be more than one\n std::vector<std::string> vehicles =\n (*watch_vehicles)[obstacle_lane->id().id()];\n if (std::find(vehicles.begin(), vehicles.end(), obstacle_id) ==\n vehicles.end()) {\n ADEBUG << \"AddWatchVehicle: lane[\" << obstacle_lane->id().id()\n << \"] obstacle_id[\" << obstacle_id << \"]\";\n (*watch_vehicles)[obstacle_lane->id().id()].push_back(obstacle_id);\n }\n\n return 0;\n}\n\n\/**\n * @brief: check valid stop_sign stop\n *\/\nbool StopSignUnprotectedStagePreStop::CheckADCStop(\n const ReferenceLineInfo& reference_line_info) {\n const double adc_speed =\n common::VehicleStateProvider::Instance()->linear_velocity();\n if (adc_speed > scenario_config_.max_adc_stop_speed()) {\n ADEBUG << \"ADC not stopped: speed[\" << adc_speed << \"]\";\n return false;\n }\n\n \/\/ check stop close enough to stop line of the stop_sign\n const double adc_front_edge_s = reference_line_info.AdcSlBoundary().end_s();\n const double stop_line_start_s =\n PlanningContext::GetScenarioInfo()->current_stop_sign_overlap.start_s;\n const double distance_stop_line_to_adc_front_edge =\n stop_line_start_s - adc_front_edge_s;\n ADEBUG << \"distance_stop_line_to_adc_front_edge[\"\n << distance_stop_line_to_adc_front_edge\n << \"] stop_sign[\"\n << PlanningContext::GetScenarioInfo()->current_stop_sign_overlap.object_id\n << \"] stop_line_start_s[\" << stop_line_start_s\n << \"] adc_front_edge_s[\" << adc_front_edge_s << \"]\";\n\n if (distance_stop_line_to_adc_front_edge >\n scenario_config_.max_valid_stop_distance()) {\n ADEBUG << \"not a valid stop. too far from stop line.\";\n return false;\n }\n\n \/\/ TODO(all): check no BICYCLE in between.\n\n return true;\n}\n\nStage::StageStatus StopSignUnprotectedStagePreStop::FinishStage() {\n GetContext()->stop_start_time = Clock::NowInSeconds();\n next_stage_ = ScenarioConfig::STOP_SIGN_UNPROTECTED_STOP;\n\n return Stage::FINISHED;\n}\n\n} \/\/ namespace stop_sign\n} \/\/ namespace scenario\n} \/\/ namespace planning\n} \/\/ namespace apollo\n<commit_msg>planning: fix a bug in stop-sign scenario<commit_after>\/******************************************************************************\n * Copyright 2018 The Apollo Authors. All Rights Reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *****************************************************************************\/\n\n\/**\n * @file\n **\/\n\n#include \"modules\/planning\/scenarios\/stop_sign\/unprotected\/stage_pre_stop.h\"\n\n#include <algorithm>\n#include <utility>\n\n#include \"modules\/perception\/proto\/perception_obstacle.pb.h\"\n\n#include \"cyber\/common\/log.h\"\n#include \"modules\/common\/time\/time.h\"\n#include \"modules\/common\/vehicle_state\/vehicle_state_provider.h\"\n#include \"modules\/map\/pnc_map\/path.h\"\n#include \"modules\/planning\/common\/frame.h\"\n#include \"modules\/planning\/common\/planning_context.h\"\n#include \"modules\/planning\/scenarios\/util\/util.h\"\n#include \"modules\/planning\/tasks\/deciders\/decider_creep.h\"\n\nnamespace apollo {\nnamespace planning {\nnamespace scenario {\nnamespace stop_sign {\n\nusing common::TrajectoryPoint;\nusing common::time::Clock;\nusing hdmap::HDMapUtil;\nusing hdmap::LaneInfoConstPtr;\nusing hdmap::OverlapInfoConstPtr;\nusing perception::PerceptionObstacle;\n\nusing StopSignLaneVehicles =\n std::unordered_map<std::string, std::vector<std::string>>;\n\nStage::StageStatus StopSignUnprotectedStagePreStop::Process(\n const TrajectoryPoint& planning_init_point, Frame* frame) {\n ADEBUG << \"stage: PreStop\";\n CHECK_NOTNULL(frame);\n\n scenario_config_.CopyFrom(GetContext()->scenario_config);\n\n bool plan_ok = ExecuteTaskOnReferenceLine(planning_init_point, frame);\n if (!plan_ok) {\n AERROR << \"StopSignUnprotectedStagePreStop planning error\";\n }\n\n const auto& reference_line_info = frame->reference_line_info().front();\n\n \/\/ check if the stop_sign is still along reference_line\n std::string stop_sign_overlap_id =\n PlanningContext::GetScenarioInfo()->current_stop_sign_overlap.object_id;\n if (scenario::CheckStopSignDone(reference_line_info, stop_sign_overlap_id)) {\n return FinishScenario();\n }\n\n constexpr double kPassStopLineBuffer = 0.3; \/\/ unit: m\n const double adc_front_edge_s = reference_line_info.AdcSlBoundary().end_s();\n const double distance_adc_pass_stop_sign =\n adc_front_edge_s -\n PlanningContext::GetScenarioInfo()->current_stop_sign_overlap.start_s;\n if (distance_adc_pass_stop_sign <= kPassStopLineBuffer) {\n \/\/ not passed stop line, check valid stop\n if (CheckADCStop(reference_line_info)) {\n return FinishStage();\n }\n } else {\n \/\/ passed stop line\n return FinishStage();\n }\n\n \/\/ PRE-STOP\n const PathDecision& path_decision = reference_line_info.path_decision();\n auto& watch_vehicles = GetContext()->watch_vehicles;\n\n std::vector<std::string> watch_vehicle_ids;\n for (auto it = watch_vehicles.begin(); it != watch_vehicles.end(); ++it) {\n std::copy(it->second.begin(), it->second.end(),\n std::back_inserter(watch_vehicle_ids));\n\n \/\/ for debug string\n std::string associated_lane_id = it->first;\n std::string s;\n for (size_t i = 0; i < it->second.size(); ++i) {\n std::string vehicle_id = (it->second)[i];\n s = s.empty() ? vehicle_id : s + \",\" + vehicle_id;\n }\n ADEBUG << \"watch_vehicles: lane_id[\" << associated_lane_id << \"] vehicle[\"\n << s << \"]\";\n }\n\n \/\/ pass vehicles being watched to DECIDER_RULE_BASED_STOP task\n \/\/ for visualization\n PlanningContext::GetScenarioInfo()->stop_sign_wait_for_obstacles.clear();\n std::copy(\n watch_vehicle_ids.begin(), watch_vehicle_ids.end(),\n std::back_inserter(\n PlanningContext::GetScenarioInfo()->stop_sign_wait_for_obstacles));\n\n for (const auto* obstacle : path_decision.obstacles().Items()) {\n \/\/ add to watch_vehicles if adc is still proceeding to stop sign\n AddWatchVehicle(*obstacle, &watch_vehicles);\n }\n\n return Stage::RUNNING;\n}\n\n\/**\n * @brief: add a watch vehicle which arrives at stop sign ahead of adc\n *\/\nint StopSignUnprotectedStagePreStop::AddWatchVehicle(\n const Obstacle& obstacle, StopSignLaneVehicles* watch_vehicles) {\n CHECK_NOTNULL(watch_vehicles);\n\n const PerceptionObstacle& perception_obstacle = obstacle.Perception();\n const std::string& obstacle_id = std::to_string(perception_obstacle.id());\n PerceptionObstacle::Type obstacle_type = perception_obstacle.type();\n std::string obstacle_type_name = PerceptionObstacle_Type_Name(obstacle_type);\n\n \/\/ check type\n if (obstacle_type != PerceptionObstacle::UNKNOWN &&\n obstacle_type != PerceptionObstacle::UNKNOWN_MOVABLE &&\n obstacle_type != PerceptionObstacle::BICYCLE &&\n obstacle_type != PerceptionObstacle::VEHICLE) {\n ADEBUG << \"obstacle_id[\" << obstacle_id << \"] type[\" << obstacle_type_name\n << \"]. skip\";\n return 0;\n }\n\n auto point = common::util::MakePointENU(perception_obstacle.position().x(),\n perception_obstacle.position().y(),\n perception_obstacle.position().z());\n double obstacle_s = 0.0;\n double obstacle_l = 0.0;\n LaneInfoConstPtr obstacle_lane;\n if (HDMapUtil::BaseMap().GetNearestLaneWithHeading(\n point, 5.0, perception_obstacle.theta(), M_PI \/ 3.0, &obstacle_lane,\n &obstacle_s, &obstacle_l) != 0) {\n ADEBUG << \"obstacle_id[\" << obstacle_id << \"] type[\" << obstacle_type_name\n << \"]: Failed to find nearest lane from map for position: \"\n << point.DebugString()\n << \"; heading:\" << perception_obstacle.theta();\n return -1;\n }\n\n \/\/ check obstacle is on an associate lane guarded by stop sign\n std::string obstable_lane_id = obstacle_lane.get()->id().id();\n auto assoc_lane_it = std::find_if(\n GetContext()->associated_lanes.begin(),\n GetContext()->associated_lanes.end(),\n [&obstable_lane_id](\n std::pair<LaneInfoConstPtr, OverlapInfoConstPtr>& assc_lane) {\n return assc_lane.first.get()->id().id() == obstable_lane_id;\n });\n if (assoc_lane_it == GetContext()->associated_lanes.end()) {\n ADEBUG << \"obstacle_id[\" << obstacle_id << \"] type[\" << obstacle_type_name\n << \"] lane_id[\" << obstable_lane_id\n << \"] not associated with current stop_sign. skip\";\n return -1;\n }\n\n \/\/ check a valid stop for stop line of the stop_sign\n auto over_lap_info = assoc_lane_it->second.get()->GetObjectOverlapInfo(\n obstacle_lane.get()->id());\n if (over_lap_info == nullptr) {\n AERROR << \"can't find over_lap_info for id: \" << obstable_lane_id;\n return -1;\n }\n const double stop_line_s = over_lap_info->lane_overlap_info().start_s();\n const double obstacle_end_s = obstacle_s + perception_obstacle.length() \/ 2;\n const double distance_to_stop_line = stop_line_s - obstacle_end_s;\n\n if (distance_to_stop_line >\n scenario_config_.watch_vehicle_max_valid_stop_distance()) {\n ADEBUG << \"obstacle_id[\" << obstacle_id << \"] type[\" << obstacle_type_name\n << \"] distance_to_stop_line[\" << distance_to_stop_line\n << \"]; stop_line_s\" << stop_line_s << \"]; obstacle_end_s[\"\n << obstacle_end_s << \"] too far from stop line. skip\";\n return -1;\n }\n\n \/\/ use a vector since motocycles\/bicycles can be more than one\n std::vector<std::string> vehicles =\n (*watch_vehicles)[obstacle_lane->id().id()];\n if (std::find(vehicles.begin(), vehicles.end(), obstacle_id) ==\n vehicles.end()) {\n ADEBUG << \"AddWatchVehicle: lane[\" << obstacle_lane->id().id()\n << \"] obstacle_id[\" << obstacle_id << \"]\";\n (*watch_vehicles)[obstacle_lane->id().id()].push_back(obstacle_id);\n }\n\n return 0;\n}\n\n\/**\n * @brief: check valid stop_sign stop\n *\/\nbool StopSignUnprotectedStagePreStop::CheckADCStop(\n const ReferenceLineInfo& reference_line_info) {\n const double adc_speed =\n common::VehicleStateProvider::Instance()->linear_velocity();\n if (adc_speed > scenario_config_.max_adc_stop_speed()) {\n ADEBUG << \"ADC not stopped: speed[\" << adc_speed << \"]\";\n return false;\n }\n\n \/\/ check stop close enough to stop line of the stop_sign\n const double adc_front_edge_s = reference_line_info.AdcSlBoundary().end_s();\n const double stop_line_start_s =\n PlanningContext::GetScenarioInfo()->current_stop_sign_overlap.start_s;\n const double distance_stop_line_to_adc_front_edge =\n stop_line_start_s - adc_front_edge_s;\n ADEBUG << \"distance_stop_line_to_adc_front_edge[\"\n << distance_stop_line_to_adc_front_edge\n << \"] stop_sign[\"\n << PlanningContext::GetScenarioInfo()->current_stop_sign_overlap.object_id\n << \"] stop_line_start_s[\" << stop_line_start_s\n << \"] adc_front_edge_s[\" << adc_front_edge_s << \"]\";\n\n if (distance_stop_line_to_adc_front_edge >\n scenario_config_.max_valid_stop_distance()) {\n ADEBUG << \"not a valid stop. too far from stop line.\";\n return false;\n }\n\n \/\/ TODO(all): check no BICYCLE in between.\n\n return true;\n}\n\nStage::StageStatus StopSignUnprotectedStagePreStop::FinishStage() {\n GetContext()->stop_start_time = Clock::NowInSeconds();\n next_stage_ = ScenarioConfig::STOP_SIGN_UNPROTECTED_STOP;\n\n return Stage::FINISHED;\n}\n\n} \/\/ namespace stop_sign\n} \/\/ namespace scenario\n} \/\/ namespace planning\n} \/\/ namespace apollo\n<|endoftext|>"} {"text":"<commit_before>#include \"pch.h\"\r\n#include \"AudioDeviceManager.h\"\r\n\r\n#include \"DspMatrix.h\"\r\n\r\nnamespace SaneAudioRenderer\r\n{\r\n namespace\r\n {\r\n WAVEFORMATEX BuildWaveFormat(WORD formatTag, uint32_t formatBits, uint32_t rate, uint32_t channelCount)\r\n {\r\n WAVEFORMATEX format;\r\n\r\n format.wFormatTag = formatTag;\r\n format.nChannels = channelCount;\r\n format.nSamplesPerSec = rate;\r\n format.nAvgBytesPerSec = formatBits \/ 8 * channelCount * rate;\r\n format.nBlockAlign = formatBits \/ 8 * channelCount;\r\n format.wBitsPerSample = formatBits;\r\n format.cbSize = (formatTag == WAVE_FORMAT_EXTENSIBLE) ? 22 : 0;\r\n\r\n return format;\r\n }\r\n\r\n WAVEFORMATEXTENSIBLE BuildWaveFormatExt(GUID formatGuid, uint32_t formatBits, WORD formatExtProps,\r\n uint32_t rate, uint32_t channelCount, DWORD channelMask)\r\n {\r\n WAVEFORMATEXTENSIBLE format;\r\n\r\n format.Format = BuildWaveFormat(WAVE_FORMAT_EXTENSIBLE, formatBits, rate, channelCount);\r\n format.Samples.wValidBitsPerSample = formatExtProps;\r\n format.dwChannelMask = channelMask;\r\n format.SubFormat = formatGuid;\r\n\r\n return format;\r\n }\r\n\r\n template <typename T>\r\n void AppendPcmFormatPack(T& data, uint32_t rate, uint32_t channelCount, DWORD channelMask)\r\n {\r\n data.insert(data.cend(), {\r\n BuildWaveFormatExt(KSDATAFORMAT_SUBTYPE_IEEE_FLOAT, 32, 32, rate, channelCount, channelMask),\r\n BuildWaveFormatExt(KSDATAFORMAT_SUBTYPE_PCM, 32, 32, rate, channelCount, channelMask),\r\n BuildWaveFormatExt(KSDATAFORMAT_SUBTYPE_PCM, 24, 24, rate, channelCount, channelMask),\r\n BuildWaveFormatExt(KSDATAFORMAT_SUBTYPE_PCM, 32, 24, rate, channelCount, channelMask),\r\n BuildWaveFormatExt(KSDATAFORMAT_SUBTYPE_PCM, 16, 16, rate, channelCount, channelMask),\r\n });\r\n }\r\n\r\n UINT32 GetDevicePropertyUint(IPropertyStore* pStore, REFPROPERTYKEY key)\r\n {\r\n assert(pStore);\r\n\r\n PROPVARIANT prop;\r\n PropVariantInit(&prop);\r\n ThrowIfFailed(pStore->GetValue(key, &prop));\r\n assert(prop.vt == VT_UI4);\r\n UINT32 ret = prop.uintVal;\r\n PropVariantClear(&prop);\r\n\r\n return ret;\r\n }\r\n\r\n SharedString GetDevicePropertyString(IPropertyStore* pStore, REFPROPERTYKEY key)\r\n {\r\n assert(pStore);\r\n\r\n PROPVARIANT prop;\r\n PropVariantInit(&prop);\r\n ThrowIfFailed(pStore->GetValue(key, &prop));\r\n assert(prop.vt == VT_LPWSTR);\r\n auto ret = std::make_shared<std::wstring>(prop.pwszVal);\r\n PropVariantClear(&prop);\r\n\r\n return ret;\r\n }\r\n\r\n DWORD ShiftBackSide(DWORD mask)\r\n {\r\n return mask ^ (SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT |\r\n SPEAKER_SIDE_LEFT | SPEAKER_SIDE_RIGHT);\r\n }\r\n\r\n void CreateAudioClient(IMMDeviceEnumerator* pEnumerator, AudioDeviceBackend& backend)\r\n {\r\n assert(pEnumerator);\r\n\r\n IMMDevicePtr device;\r\n\r\n if (!backend.id || backend.id->empty())\r\n {\r\n ThrowIfFailed(pEnumerator->GetDefaultAudioEndpoint(eRender, eMultimedia, &device));\r\n\r\n LPWSTR pDeviceId = nullptr;\r\n ThrowIfFailed(device->GetId(&pDeviceId));\r\n std::unique_ptr<WCHAR, CoTaskMemFreeDeleter> holder(pDeviceId);\r\n backend.id = std::make_shared<std::wstring>(pDeviceId);\r\n }\r\n else\r\n {\r\n IMMDeviceCollectionPtr collection;\r\n ThrowIfFailed(pEnumerator->EnumAudioEndpoints(eRender, DEVICE_STATE_ACTIVE, &collection));\r\n\r\n UINT count = 0;\r\n ThrowIfFailed(collection->GetCount(&count));\r\n\r\n for (UINT i = 0; i < count; i++)\r\n {\r\n ThrowIfFailed(collection->Item(i, &device));\r\n\r\n LPWSTR pDeviceId = nullptr;\r\n ThrowIfFailed(device->GetId(&pDeviceId));\r\n std::unique_ptr<WCHAR, CoTaskMemFreeDeleter> holder(pDeviceId);\r\n\r\n if (*backend.id == pDeviceId)\r\n break;\r\n\r\n device = nullptr;\r\n }\r\n }\r\n\r\n if (!device)\r\n return;\r\n\r\n IPropertyStorePtr devicePropertyStore;\r\n ThrowIfFailed(device->OpenPropertyStore(STGM_READ, &devicePropertyStore));\r\n\r\n backend.adapterName = GetDevicePropertyString(devicePropertyStore, PKEY_DeviceInterface_FriendlyName);\r\n backend.endpointName = GetDevicePropertyString(devicePropertyStore, PKEY_Device_DeviceDesc);\r\n\r\n static const PROPERTYKEY formFactorKey = { \/\/ PKEY_AudioEndpoint_FormFactor\r\n {0x1da5d803, 0xd492, 0x4edd, {0x8c, 0x23, 0xe0, 0xc0, 0xff, 0xee, 0x7f, 0x0e}}, 0\r\n };\r\n backend.endpointFormFactor = GetDevicePropertyUint(devicePropertyStore, formFactorKey);\r\n\r\n ThrowIfFailed(device->Activate(__uuidof(IAudioClient),\r\n CLSCTX_INPROC_SERVER, nullptr, (void**)&backend.audioClient));\r\n }\r\n\r\n HRESULT CheckBitstreamFormat(IMMDeviceEnumerator* pEnumerator, SharedWaveFormat format, ISettings* pSettings)\r\n {\r\n assert(pEnumerator);\r\n assert(format);\r\n assert(pSettings);\r\n\r\n try\r\n {\r\n AudioDeviceBackend device = {};\r\n\r\n {\r\n LPWSTR pDeviceId = nullptr;\r\n ThrowIfFailed(pSettings->GetOuputDevice(&pDeviceId, nullptr, nullptr));\r\n std::unique_ptr<WCHAR, CoTaskMemFreeDeleter> holder(pDeviceId);\r\n\r\n device.id = std::make_shared<std::wstring>(pDeviceId);\r\n }\r\n\r\n CreateAudioClient(pEnumerator, device);\r\n\r\n if (!device.audioClient)\r\n return E_FAIL;\r\n\r\n return device.audioClient->IsFormatSupported(AUDCLNT_SHAREMODE_EXCLUSIVE, &(*format), nullptr);\r\n }\r\n catch (HRESULT ex)\r\n {\r\n return ex;\r\n }\r\n }\r\n\r\n HRESULT CreateAudioDeviceBackend(IMMDeviceEnumerator* pEnumerator,\r\n SharedWaveFormat format, bool realtime, ISettings* pSettings,\r\n std::shared_ptr<AudioDeviceBackend>& backend)\r\n {\r\n assert(pEnumerator);\r\n assert(format);\r\n assert(pSettings);\r\n\r\n try\r\n {\r\n backend = std::make_shared<AudioDeviceBackend>();\r\n\r\n {\r\n LPWSTR pDeviceId = nullptr;\r\n BOOL exclusive;\r\n UINT32 buffer;\r\n ThrowIfFailed(pSettings->GetOuputDevice(&pDeviceId, &exclusive, &buffer));\r\n std::unique_ptr<WCHAR, CoTaskMemFreeDeleter> holder(pDeviceId);\r\n\r\n backend->id = std::make_shared<std::wstring>(pDeviceId);\r\n backend->exclusive = !!exclusive;\r\n backend->realtime = realtime;\r\n backend->bufferDuration = buffer;\r\n }\r\n\r\n CreateAudioClient(pEnumerator, *backend);\r\n\r\n if (!backend->audioClient)\r\n return E_FAIL;\r\n\r\n WAVEFORMATEX* pFormat;\r\n ThrowIfFailed(backend->audioClient->GetMixFormat(&pFormat));\r\n SharedWaveFormat mixFormat(pFormat, CoTaskMemFreeDeleter());\r\n\r\n backend->bitstream = (DspFormatFromWaveFormat(*format) == DspFormat::Unknown);\r\n\r\n const auto inputRate = format->nSamplesPerSec;\r\n const auto inputChannels = format->nChannels;\r\n const auto inputMask = DspMatrix::GetChannelMask(*format);\r\n const auto mixRate = mixFormat->nSamplesPerSec;\r\n const auto mixChannels = mixFormat->nChannels;\r\n const auto mixMask = DspMatrix::GetChannelMask(*mixFormat);\r\n\r\n if (backend->bitstream)\r\n {\r\n \/\/ Exclusive bitstreaming.\r\n if (!backend->exclusive)\r\n return E_FAIL;\r\n\r\n backend->dspFormat = DspFormat::Unknown;\r\n backend->waveFormat = format;\r\n }\r\n else if (backend->exclusive)\r\n {\r\n \/\/ Exclusive.\r\n std::vector<WAVEFORMATEXTENSIBLE> priorities;\r\n\r\n if (backend->endpointFormFactor == DigitalAudioDisplayDevice)\r\n {\r\n AppendPcmFormatPack(priorities, inputRate, inputChannels, inputMask);\r\n AppendPcmFormatPack(priorities, mixRate, inputChannels, inputMask);\r\n\r\n \/\/ Shift between 5.1 with side channels and 5.1 with back channels.\r\n if (inputMask == KSAUDIO_SPEAKER_5POINT1 ||\r\n inputMask == ShiftBackSide(KSAUDIO_SPEAKER_5POINT1))\r\n {\r\n auto altMask = ShiftBackSide(inputMask);\r\n AppendPcmFormatPack(priorities, inputRate, inputChannels, altMask);\r\n AppendPcmFormatPack(priorities, mixRate, inputChannels, altMask);\r\n }\r\n }\r\n\r\n AppendPcmFormatPack(priorities, inputRate, mixChannels, mixMask);\r\n AppendPcmFormatPack(priorities, mixRate, mixChannels, mixMask);\r\n\r\n priorities.insert(priorities.cend(), {\r\n WAVEFORMATEXTENSIBLE{BuildWaveFormat(WAVE_FORMAT_PCM, 16, inputRate, mixChannels)},\r\n WAVEFORMATEXTENSIBLE{BuildWaveFormat(WAVE_FORMAT_PCM, 16, mixRate, mixChannels)}\r\n });\r\n\r\n for (const auto& f : priorities)\r\n {\r\n assert(DspFormatFromWaveFormat(f.Format) != DspFormat::Unknown);\r\n\r\n if (SUCCEEDED(backend->audioClient->IsFormatSupported(AUDCLNT_SHAREMODE_EXCLUSIVE,\r\n &f.Format, nullptr)))\r\n {\r\n backend->dspFormat = DspFormatFromWaveFormat(f.Format);\r\n backend->waveFormat = CopyWaveFormat(f.Format);\r\n break;\r\n }\r\n }\r\n }\r\n else\r\n {\r\n \/\/ Shared.\r\n backend->dspFormat = DspFormat::Float;\r\n backend->waveFormat = mixFormat;\r\n\r\n std::vector<WAVEFORMATEXTENSIBLE> priorities = {\r\n BuildWaveFormatExt(KSDATAFORMAT_SUBTYPE_IEEE_FLOAT, 32, 32,\r\n mixRate, inputChannels, inputMask),\r\n };\r\n\r\n \/\/ Shift between 5.1 with side channels and 5.1 with back channels.\r\n if (inputMask == KSAUDIO_SPEAKER_5POINT1 ||\r\n inputMask == ShiftBackSide(KSAUDIO_SPEAKER_5POINT1))\r\n {\r\n priorities.push_back(BuildWaveFormatExt(KSDATAFORMAT_SUBTYPE_IEEE_FLOAT, 32, 32,\r\n mixRate, inputChannels, ShiftBackSide(inputMask)));\r\n }\r\n\r\n for (const auto& f : priorities)\r\n {\r\n assert(DspFormatFromWaveFormat(f.Format) != DspFormat::Unknown);\r\n\r\n WAVEFORMATEX* pClosest;\r\n if (SUCCEEDED(backend->audioClient->IsFormatSupported(AUDCLNT_SHAREMODE_SHARED,\r\n &f.Format, &pClosest)))\r\n {\r\n if (pClosest)\r\n {\r\n CoTaskMemFree(pClosest);\r\n }\r\n else\r\n {\r\n backend->dspFormat = DspFormatFromWaveFormat(f.Format);\r\n backend->waveFormat = CopyWaveFormat(f.Format);\r\n break;\r\n }\r\n }\r\n }\r\n }\r\n\r\n ThrowIfFailed(backend->audioClient->Initialize(\r\n backend->exclusive ? AUDCLNT_SHAREMODE_EXCLUSIVE : AUDCLNT_SHAREMODE_SHARED,\r\n AUDCLNT_STREAMFLAGS_NOPERSIST,\r\n OneMillisecond * backend->bufferDuration,\r\n 0, &(*backend->waveFormat), nullptr));\r\n\r\n ThrowIfFailed(backend->audioClient->GetService(IID_PPV_ARGS(&backend->audioRenderClient)));\r\n\r\n ThrowIfFailed(backend->audioClient->GetService(IID_PPV_ARGS(&backend->audioClock)));\r\n\r\n ThrowIfFailed(backend->audioClient->GetStreamLatency(&backend->latency));\r\n\r\n return S_OK;\r\n }\r\n catch (std::bad_alloc&)\r\n {\r\n backend = nullptr;\r\n return E_OUTOFMEMORY;\r\n }\r\n catch (HRESULT ex)\r\n {\r\n backend = nullptr;\r\n return ex;\r\n }\r\n }\r\n }\r\n\r\n AudioDeviceNotificationClient::AudioDeviceNotificationClient(std::atomic<uint32_t>& defaultDeviceSerial)\r\n : CUnknown(\"SaneAudioRenderer::AudioDeviceNotificationClient\", nullptr)\r\n , m_defaultDeviceSerial(defaultDeviceSerial)\r\n {\r\n }\r\n\r\n STDMETHODIMP AudioDeviceNotificationClient::NonDelegatingQueryInterface(REFIID riid, void** ppv)\r\n {\r\n if (riid == __uuidof(IMMNotificationClient))\r\n return GetInterface(static_cast<IMMNotificationClient*>(this), ppv);\r\n\r\n return CUnknown::NonDelegatingQueryInterface(riid, ppv);\r\n }\r\n\r\n STDMETHODIMP AudioDeviceNotificationClient::OnDefaultDeviceChanged(EDataFlow flow, ERole role, LPCWSTR)\r\n {\r\n if (flow == eRender && role == eMultimedia)\r\n m_defaultDeviceSerial++;\r\n\r\n return S_OK;\r\n }\r\n\r\n AudioDeviceManager::AudioDeviceManager(HRESULT& result)\r\n {\r\n if (FAILED(result))\r\n return;\r\n\r\n try\r\n {\r\n if (static_cast<HANDLE>(m_wake) == NULL ||\r\n static_cast<HANDLE>(m_done) == NULL)\r\n {\r\n throw E_OUTOFMEMORY;\r\n }\r\n\r\n m_thread = std::thread(\r\n [this]\r\n {\r\n CoInitializeHelper coInitializeHelper(COINIT_MULTITHREADED);\r\n\r\n while (!m_exit)\r\n {\r\n m_wake.Wait();\r\n\r\n if (m_function)\r\n {\r\n m_result = m_function();\r\n m_function = nullptr;\r\n m_done.Set();\r\n }\r\n }\r\n }\r\n );\r\n\r\n {\r\n m_function = [&] { return CoCreateInstance(__uuidof(MMDeviceEnumerator), nullptr,\r\n CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&m_enumerator)); };\r\n m_wake.Set();\r\n m_done.Wait();\r\n ThrowIfFailed(m_result);\r\n assert(m_enumerator);\r\n }\r\n\r\n {\r\n auto pNotificationClient = new AudioDeviceNotificationClient(m_defaultDeviceSerial);\r\n\r\n pNotificationClient->NonDelegatingAddRef();\r\n\r\n ThrowIfFailed(pNotificationClient->NonDelegatingQueryInterface(IID_PPV_ARGS(&m_notificationClient)));\r\n\r\n pNotificationClient->NonDelegatingRelease();\r\n\r\n ThrowIfFailed(m_enumerator->RegisterEndpointNotificationCallback(m_notificationClient));\r\n }\r\n }\r\n catch (HRESULT ex)\r\n {\r\n result = ex;\r\n }\r\n catch (std::system_error&)\r\n {\r\n result = E_FAIL;\r\n }\r\n }\r\n\r\n AudioDeviceManager::~AudioDeviceManager()\r\n {\r\n if (m_enumerator && m_notificationClient)\r\n m_enumerator->UnregisterEndpointNotificationCallback(m_notificationClient);\r\n\r\n m_exit = true;\r\n m_wake.Set();\r\n\r\n if (m_thread.joinable())\r\n m_thread.join();\r\n }\r\n\r\n bool AudioDeviceManager::BitstreamFormatSupported(SharedWaveFormat format, ISettings* pSettings)\r\n {\r\n assert(format);\r\n assert(pSettings);\r\n\r\n m_function = [&] { return CheckBitstreamFormat(m_enumerator, format, pSettings); };\r\n m_wake.Set();\r\n m_done.Wait();\r\n\r\n return SUCCEEDED(m_result);\r\n }\r\n\r\n std::unique_ptr<AudioDevice> AudioDeviceManager::CreateDevice(SharedWaveFormat format, bool realtime,\r\n ISettings* pSettings)\r\n {\r\n assert(format);\r\n assert(pSettings);\r\n\r\n std::shared_ptr<AudioDeviceBackend> backend;\r\n\r\n m_function = [&] { return CreateAudioDeviceBackend(m_enumerator, format, realtime, pSettings, backend); };\r\n m_wake.Set();\r\n m_done.Wait();\r\n\r\n if (FAILED(m_result))\r\n return nullptr;\r\n\r\n try\r\n {\r\n return std::unique_ptr<AudioDevice>(new AudioDevice(backend));\r\n }\r\n catch (std::bad_alloc&)\r\n {\r\n return nullptr;\r\n }\r\n catch (std::system_error&)\r\n {\r\n return nullptr;\r\n }\r\n }\r\n\r\n std::unique_ptr<WCHAR, CoTaskMemFreeDeleter> AudioDeviceManager::GetDefaultDeviceId()\r\n {\r\n assert(m_enumerator);\r\n\r\n try\r\n {\r\n IMMDevicePtr device;\r\n ThrowIfFailed(m_enumerator->GetDefaultAudioEndpoint(eRender, eMultimedia, &device));\r\n\r\n LPWSTR pDeviceId = nullptr;\r\n ThrowIfFailed(device->GetId(&pDeviceId));\r\n return std::unique_ptr<WCHAR, CoTaskMemFreeDeleter>(pDeviceId);\r\n }\r\n catch (HRESULT)\r\n {\r\n return nullptr;\r\n }\r\n }\r\n}\r\n<commit_msg>Release all interfaces before releasing MTA<commit_after>#include \"pch.h\"\r\n#include \"AudioDeviceManager.h\"\r\n\r\n#include \"DspMatrix.h\"\r\n\r\nnamespace SaneAudioRenderer\r\n{\r\n namespace\r\n {\r\n WAVEFORMATEX BuildWaveFormat(WORD formatTag, uint32_t formatBits, uint32_t rate, uint32_t channelCount)\r\n {\r\n WAVEFORMATEX format;\r\n\r\n format.wFormatTag = formatTag;\r\n format.nChannels = channelCount;\r\n format.nSamplesPerSec = rate;\r\n format.nAvgBytesPerSec = formatBits \/ 8 * channelCount * rate;\r\n format.nBlockAlign = formatBits \/ 8 * channelCount;\r\n format.wBitsPerSample = formatBits;\r\n format.cbSize = (formatTag == WAVE_FORMAT_EXTENSIBLE) ? 22 : 0;\r\n\r\n return format;\r\n }\r\n\r\n WAVEFORMATEXTENSIBLE BuildWaveFormatExt(GUID formatGuid, uint32_t formatBits, WORD formatExtProps,\r\n uint32_t rate, uint32_t channelCount, DWORD channelMask)\r\n {\r\n WAVEFORMATEXTENSIBLE format;\r\n\r\n format.Format = BuildWaveFormat(WAVE_FORMAT_EXTENSIBLE, formatBits, rate, channelCount);\r\n format.Samples.wValidBitsPerSample = formatExtProps;\r\n format.dwChannelMask = channelMask;\r\n format.SubFormat = formatGuid;\r\n\r\n return format;\r\n }\r\n\r\n template <typename T>\r\n void AppendPcmFormatPack(T& data, uint32_t rate, uint32_t channelCount, DWORD channelMask)\r\n {\r\n data.insert(data.cend(), {\r\n BuildWaveFormatExt(KSDATAFORMAT_SUBTYPE_IEEE_FLOAT, 32, 32, rate, channelCount, channelMask),\r\n BuildWaveFormatExt(KSDATAFORMAT_SUBTYPE_PCM, 32, 32, rate, channelCount, channelMask),\r\n BuildWaveFormatExt(KSDATAFORMAT_SUBTYPE_PCM, 24, 24, rate, channelCount, channelMask),\r\n BuildWaveFormatExt(KSDATAFORMAT_SUBTYPE_PCM, 32, 24, rate, channelCount, channelMask),\r\n BuildWaveFormatExt(KSDATAFORMAT_SUBTYPE_PCM, 16, 16, rate, channelCount, channelMask),\r\n });\r\n }\r\n\r\n UINT32 GetDevicePropertyUint(IPropertyStore* pStore, REFPROPERTYKEY key)\r\n {\r\n assert(pStore);\r\n\r\n PROPVARIANT prop;\r\n PropVariantInit(&prop);\r\n ThrowIfFailed(pStore->GetValue(key, &prop));\r\n assert(prop.vt == VT_UI4);\r\n UINT32 ret = prop.uintVal;\r\n PropVariantClear(&prop);\r\n\r\n return ret;\r\n }\r\n\r\n SharedString GetDevicePropertyString(IPropertyStore* pStore, REFPROPERTYKEY key)\r\n {\r\n assert(pStore);\r\n\r\n PROPVARIANT prop;\r\n PropVariantInit(&prop);\r\n ThrowIfFailed(pStore->GetValue(key, &prop));\r\n assert(prop.vt == VT_LPWSTR);\r\n auto ret = std::make_shared<std::wstring>(prop.pwszVal);\r\n PropVariantClear(&prop);\r\n\r\n return ret;\r\n }\r\n\r\n DWORD ShiftBackSide(DWORD mask)\r\n {\r\n return mask ^ (SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT |\r\n SPEAKER_SIDE_LEFT | SPEAKER_SIDE_RIGHT);\r\n }\r\n\r\n void CreateAudioClient(IMMDeviceEnumerator* pEnumerator, AudioDeviceBackend& backend)\r\n {\r\n assert(pEnumerator);\r\n\r\n IMMDevicePtr device;\r\n\r\n if (!backend.id || backend.id->empty())\r\n {\r\n ThrowIfFailed(pEnumerator->GetDefaultAudioEndpoint(eRender, eMultimedia, &device));\r\n\r\n LPWSTR pDeviceId = nullptr;\r\n ThrowIfFailed(device->GetId(&pDeviceId));\r\n std::unique_ptr<WCHAR, CoTaskMemFreeDeleter> holder(pDeviceId);\r\n backend.id = std::make_shared<std::wstring>(pDeviceId);\r\n }\r\n else\r\n {\r\n IMMDeviceCollectionPtr collection;\r\n ThrowIfFailed(pEnumerator->EnumAudioEndpoints(eRender, DEVICE_STATE_ACTIVE, &collection));\r\n\r\n UINT count = 0;\r\n ThrowIfFailed(collection->GetCount(&count));\r\n\r\n for (UINT i = 0; i < count; i++)\r\n {\r\n ThrowIfFailed(collection->Item(i, &device));\r\n\r\n LPWSTR pDeviceId = nullptr;\r\n ThrowIfFailed(device->GetId(&pDeviceId));\r\n std::unique_ptr<WCHAR, CoTaskMemFreeDeleter> holder(pDeviceId);\r\n\r\n if (*backend.id == pDeviceId)\r\n break;\r\n\r\n device = nullptr;\r\n }\r\n }\r\n\r\n if (!device)\r\n return;\r\n\r\n IPropertyStorePtr devicePropertyStore;\r\n ThrowIfFailed(device->OpenPropertyStore(STGM_READ, &devicePropertyStore));\r\n\r\n backend.adapterName = GetDevicePropertyString(devicePropertyStore, PKEY_DeviceInterface_FriendlyName);\r\n backend.endpointName = GetDevicePropertyString(devicePropertyStore, PKEY_Device_DeviceDesc);\r\n\r\n static const PROPERTYKEY formFactorKey = { \/\/ PKEY_AudioEndpoint_FormFactor\r\n {0x1da5d803, 0xd492, 0x4edd, {0x8c, 0x23, 0xe0, 0xc0, 0xff, 0xee, 0x7f, 0x0e}}, 0\r\n };\r\n backend.endpointFormFactor = GetDevicePropertyUint(devicePropertyStore, formFactorKey);\r\n\r\n ThrowIfFailed(device->Activate(__uuidof(IAudioClient),\r\n CLSCTX_INPROC_SERVER, nullptr, (void**)&backend.audioClient));\r\n }\r\n\r\n HRESULT CheckBitstreamFormat(IMMDeviceEnumerator* pEnumerator, SharedWaveFormat format, ISettings* pSettings)\r\n {\r\n assert(pEnumerator);\r\n assert(format);\r\n assert(pSettings);\r\n\r\n try\r\n {\r\n AudioDeviceBackend device = {};\r\n\r\n {\r\n LPWSTR pDeviceId = nullptr;\r\n ThrowIfFailed(pSettings->GetOuputDevice(&pDeviceId, nullptr, nullptr));\r\n std::unique_ptr<WCHAR, CoTaskMemFreeDeleter> holder(pDeviceId);\r\n\r\n device.id = std::make_shared<std::wstring>(pDeviceId);\r\n }\r\n\r\n CreateAudioClient(pEnumerator, device);\r\n\r\n if (!device.audioClient)\r\n return E_FAIL;\r\n\r\n return device.audioClient->IsFormatSupported(AUDCLNT_SHAREMODE_EXCLUSIVE, &(*format), nullptr);\r\n }\r\n catch (HRESULT ex)\r\n {\r\n return ex;\r\n }\r\n }\r\n\r\n HRESULT CreateAudioDeviceBackend(IMMDeviceEnumerator* pEnumerator,\r\n SharedWaveFormat format, bool realtime, ISettings* pSettings,\r\n std::shared_ptr<AudioDeviceBackend>& backend)\r\n {\r\n assert(pEnumerator);\r\n assert(format);\r\n assert(pSettings);\r\n\r\n try\r\n {\r\n backend = std::make_shared<AudioDeviceBackend>();\r\n\r\n {\r\n LPWSTR pDeviceId = nullptr;\r\n BOOL exclusive;\r\n UINT32 buffer;\r\n ThrowIfFailed(pSettings->GetOuputDevice(&pDeviceId, &exclusive, &buffer));\r\n std::unique_ptr<WCHAR, CoTaskMemFreeDeleter> holder(pDeviceId);\r\n\r\n backend->id = std::make_shared<std::wstring>(pDeviceId);\r\n backend->exclusive = !!exclusive;\r\n backend->realtime = realtime;\r\n backend->bufferDuration = buffer;\r\n }\r\n\r\n CreateAudioClient(pEnumerator, *backend);\r\n\r\n if (!backend->audioClient)\r\n return E_FAIL;\r\n\r\n WAVEFORMATEX* pFormat;\r\n ThrowIfFailed(backend->audioClient->GetMixFormat(&pFormat));\r\n SharedWaveFormat mixFormat(pFormat, CoTaskMemFreeDeleter());\r\n\r\n backend->bitstream = (DspFormatFromWaveFormat(*format) == DspFormat::Unknown);\r\n\r\n const auto inputRate = format->nSamplesPerSec;\r\n const auto inputChannels = format->nChannels;\r\n const auto inputMask = DspMatrix::GetChannelMask(*format);\r\n const auto mixRate = mixFormat->nSamplesPerSec;\r\n const auto mixChannels = mixFormat->nChannels;\r\n const auto mixMask = DspMatrix::GetChannelMask(*mixFormat);\r\n\r\n if (backend->bitstream)\r\n {\r\n \/\/ Exclusive bitstreaming.\r\n if (!backend->exclusive)\r\n return E_FAIL;\r\n\r\n backend->dspFormat = DspFormat::Unknown;\r\n backend->waveFormat = format;\r\n }\r\n else if (backend->exclusive)\r\n {\r\n \/\/ Exclusive.\r\n std::vector<WAVEFORMATEXTENSIBLE> priorities;\r\n\r\n if (backend->endpointFormFactor == DigitalAudioDisplayDevice)\r\n {\r\n AppendPcmFormatPack(priorities, inputRate, inputChannels, inputMask);\r\n AppendPcmFormatPack(priorities, mixRate, inputChannels, inputMask);\r\n\r\n \/\/ Shift between 5.1 with side channels and 5.1 with back channels.\r\n if (inputMask == KSAUDIO_SPEAKER_5POINT1 ||\r\n inputMask == ShiftBackSide(KSAUDIO_SPEAKER_5POINT1))\r\n {\r\n auto altMask = ShiftBackSide(inputMask);\r\n AppendPcmFormatPack(priorities, inputRate, inputChannels, altMask);\r\n AppendPcmFormatPack(priorities, mixRate, inputChannels, altMask);\r\n }\r\n }\r\n\r\n AppendPcmFormatPack(priorities, inputRate, mixChannels, mixMask);\r\n AppendPcmFormatPack(priorities, mixRate, mixChannels, mixMask);\r\n\r\n priorities.insert(priorities.cend(), {\r\n WAVEFORMATEXTENSIBLE{BuildWaveFormat(WAVE_FORMAT_PCM, 16, inputRate, mixChannels)},\r\n WAVEFORMATEXTENSIBLE{BuildWaveFormat(WAVE_FORMAT_PCM, 16, mixRate, mixChannels)}\r\n });\r\n\r\n for (const auto& f : priorities)\r\n {\r\n assert(DspFormatFromWaveFormat(f.Format) != DspFormat::Unknown);\r\n\r\n if (SUCCEEDED(backend->audioClient->IsFormatSupported(AUDCLNT_SHAREMODE_EXCLUSIVE,\r\n &f.Format, nullptr)))\r\n {\r\n backend->dspFormat = DspFormatFromWaveFormat(f.Format);\r\n backend->waveFormat = CopyWaveFormat(f.Format);\r\n break;\r\n }\r\n }\r\n }\r\n else\r\n {\r\n \/\/ Shared.\r\n backend->dspFormat = DspFormat::Float;\r\n backend->waveFormat = mixFormat;\r\n\r\n std::vector<WAVEFORMATEXTENSIBLE> priorities = {\r\n BuildWaveFormatExt(KSDATAFORMAT_SUBTYPE_IEEE_FLOAT, 32, 32,\r\n mixRate, inputChannels, inputMask),\r\n };\r\n\r\n \/\/ Shift between 5.1 with side channels and 5.1 with back channels.\r\n if (inputMask == KSAUDIO_SPEAKER_5POINT1 ||\r\n inputMask == ShiftBackSide(KSAUDIO_SPEAKER_5POINT1))\r\n {\r\n priorities.push_back(BuildWaveFormatExt(KSDATAFORMAT_SUBTYPE_IEEE_FLOAT, 32, 32,\r\n mixRate, inputChannels, ShiftBackSide(inputMask)));\r\n }\r\n\r\n for (const auto& f : priorities)\r\n {\r\n assert(DspFormatFromWaveFormat(f.Format) != DspFormat::Unknown);\r\n\r\n WAVEFORMATEX* pClosest;\r\n if (SUCCEEDED(backend->audioClient->IsFormatSupported(AUDCLNT_SHAREMODE_SHARED,\r\n &f.Format, &pClosest)))\r\n {\r\n if (pClosest)\r\n {\r\n CoTaskMemFree(pClosest);\r\n }\r\n else\r\n {\r\n backend->dspFormat = DspFormatFromWaveFormat(f.Format);\r\n backend->waveFormat = CopyWaveFormat(f.Format);\r\n break;\r\n }\r\n }\r\n }\r\n }\r\n\r\n ThrowIfFailed(backend->audioClient->Initialize(\r\n backend->exclusive ? AUDCLNT_SHAREMODE_EXCLUSIVE : AUDCLNT_SHAREMODE_SHARED,\r\n AUDCLNT_STREAMFLAGS_NOPERSIST,\r\n OneMillisecond * backend->bufferDuration,\r\n 0, &(*backend->waveFormat), nullptr));\r\n\r\n ThrowIfFailed(backend->audioClient->GetService(IID_PPV_ARGS(&backend->audioRenderClient)));\r\n\r\n ThrowIfFailed(backend->audioClient->GetService(IID_PPV_ARGS(&backend->audioClock)));\r\n\r\n ThrowIfFailed(backend->audioClient->GetStreamLatency(&backend->latency));\r\n\r\n return S_OK;\r\n }\r\n catch (std::bad_alloc&)\r\n {\r\n backend = nullptr;\r\n return E_OUTOFMEMORY;\r\n }\r\n catch (HRESULT ex)\r\n {\r\n backend = nullptr;\r\n return ex;\r\n }\r\n }\r\n }\r\n\r\n AudioDeviceNotificationClient::AudioDeviceNotificationClient(std::atomic<uint32_t>& defaultDeviceSerial)\r\n : CUnknown(\"SaneAudioRenderer::AudioDeviceNotificationClient\", nullptr)\r\n , m_defaultDeviceSerial(defaultDeviceSerial)\r\n {\r\n }\r\n\r\n STDMETHODIMP AudioDeviceNotificationClient::NonDelegatingQueryInterface(REFIID riid, void** ppv)\r\n {\r\n if (riid == __uuidof(IMMNotificationClient))\r\n return GetInterface(static_cast<IMMNotificationClient*>(this), ppv);\r\n\r\n return CUnknown::NonDelegatingQueryInterface(riid, ppv);\r\n }\r\n\r\n STDMETHODIMP AudioDeviceNotificationClient::OnDefaultDeviceChanged(EDataFlow flow, ERole role, LPCWSTR)\r\n {\r\n if (flow == eRender && role == eMultimedia)\r\n m_defaultDeviceSerial++;\r\n\r\n return S_OK;\r\n }\r\n\r\n AudioDeviceManager::AudioDeviceManager(HRESULT& result)\r\n {\r\n if (FAILED(result))\r\n return;\r\n\r\n try\r\n {\r\n if (static_cast<HANDLE>(m_wake) == NULL ||\r\n static_cast<HANDLE>(m_done) == NULL)\r\n {\r\n throw E_OUTOFMEMORY;\r\n }\r\n\r\n m_thread = std::thread(\r\n [this]\r\n {\r\n CoInitializeHelper coInitializeHelper(COINIT_MULTITHREADED);\r\n\r\n while (!m_exit)\r\n {\r\n m_wake.Wait();\r\n\r\n if (m_function)\r\n {\r\n m_result = m_function();\r\n m_function = nullptr;\r\n m_done.Set();\r\n }\r\n }\r\n }\r\n );\r\n\r\n {\r\n m_function = [&] { return CoCreateInstance(__uuidof(MMDeviceEnumerator), nullptr,\r\n CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&m_enumerator)); };\r\n m_wake.Set();\r\n m_done.Wait();\r\n ThrowIfFailed(m_result);\r\n assert(m_enumerator);\r\n }\r\n\r\n {\r\n auto pNotificationClient = new AudioDeviceNotificationClient(m_defaultDeviceSerial);\r\n\r\n pNotificationClient->NonDelegatingAddRef();\r\n\r\n ThrowIfFailed(pNotificationClient->NonDelegatingQueryInterface(IID_PPV_ARGS(&m_notificationClient)));\r\n\r\n pNotificationClient->NonDelegatingRelease();\r\n\r\n ThrowIfFailed(m_enumerator->RegisterEndpointNotificationCallback(m_notificationClient));\r\n }\r\n }\r\n catch (HRESULT ex)\r\n {\r\n result = ex;\r\n }\r\n catch (std::system_error&)\r\n {\r\n result = E_FAIL;\r\n }\r\n }\r\n\r\n AudioDeviceManager::~AudioDeviceManager()\r\n {\r\n if (m_enumerator && m_notificationClient)\r\n m_enumerator->UnregisterEndpointNotificationCallback(m_notificationClient);\r\n\r\n m_enumerator = nullptr;\r\n\r\n m_exit = true;\r\n m_wake.Set();\r\n\r\n if (m_thread.joinable())\r\n m_thread.join();\r\n }\r\n\r\n bool AudioDeviceManager::BitstreamFormatSupported(SharedWaveFormat format, ISettings* pSettings)\r\n {\r\n assert(format);\r\n assert(pSettings);\r\n\r\n m_function = [&] { return CheckBitstreamFormat(m_enumerator, format, pSettings); };\r\n m_wake.Set();\r\n m_done.Wait();\r\n\r\n return SUCCEEDED(m_result);\r\n }\r\n\r\n std::unique_ptr<AudioDevice> AudioDeviceManager::CreateDevice(SharedWaveFormat format, bool realtime,\r\n ISettings* pSettings)\r\n {\r\n assert(format);\r\n assert(pSettings);\r\n\r\n std::shared_ptr<AudioDeviceBackend> backend;\r\n\r\n m_function = [&] { return CreateAudioDeviceBackend(m_enumerator, format, realtime, pSettings, backend); };\r\n m_wake.Set();\r\n m_done.Wait();\r\n\r\n if (FAILED(m_result))\r\n return nullptr;\r\n\r\n try\r\n {\r\n return std::unique_ptr<AudioDevice>(new AudioDevice(backend));\r\n }\r\n catch (std::bad_alloc&)\r\n {\r\n return nullptr;\r\n }\r\n catch (std::system_error&)\r\n {\r\n return nullptr;\r\n }\r\n }\r\n\r\n std::unique_ptr<WCHAR, CoTaskMemFreeDeleter> AudioDeviceManager::GetDefaultDeviceId()\r\n {\r\n assert(m_enumerator);\r\n\r\n try\r\n {\r\n IMMDevicePtr device;\r\n ThrowIfFailed(m_enumerator->GetDefaultAudioEndpoint(eRender, eMultimedia, &device));\r\n\r\n LPWSTR pDeviceId = nullptr;\r\n ThrowIfFailed(device->GetId(&pDeviceId));\r\n return std::unique_ptr<WCHAR, CoTaskMemFreeDeleter>(pDeviceId);\r\n }\r\n catch (HRESULT)\r\n {\r\n return nullptr;\r\n }\r\n }\r\n}\r\n<|endoftext|>"} {"text":"<commit_before>#include \"inverseIndexStorageBloomierFilter.h\"\n\nInverseIndexStorageBloomierFilter::InverseIndexStorageBloomierFilter(size_t pSizeOfInverseIndex, size_t pMaxBinSize) {\n\tmInverseIndex = new std::vector<BloomierFilter* > (pSizeOfInverseIndex);\n\tmMaxBinSize = pMaxBinSize;\n\tmM = 5000;\n\tmK = 5;\n\tmQ = 8;\n}\nInverseIndexStorageBloomierFilter::~InverseIndexStorageBloomierFilter() {\n\t\n}\nsize_t InverseIndexStorageBloomierFilter::size() {\n\treturn mInverseIndex->size();\n}\nvsize_t* InverseIndexStorageBloomierFilter::getElement(size_t pVectorId, size_t pHashValue) {\n return (*mInverseIndex)[pVectorId]->get(pHashValue); \n}\nvoid InverseIndexStorageBloomierFilter::insert(size_t pVectorId, size_t pHashValue, size_t pInstance) {\n if ((*mInverseIndex)[pVectorId] == NULL) {\n (*mInverseIndex)[pVectorId] = new BloomierFilter(mM, mK, mQ, 100);\n }\n (*mInverseIndex)[pVectorId]->set(pHashValue, pInstance);\n}<commit_msg>Added maxBinSize to bloomieFilter constructor<commit_after>#include \"inverseIndexStorageBloomierFilter.h\"\n\nInverseIndexStorageBloomierFilter::InverseIndexStorageBloomierFilter(size_t pSizeOfInverseIndex, size_t pMaxBinSize) {\n\tmInverseIndex = new std::vector<BloomierFilter* > (pSizeOfInverseIndex);\n\tmMaxBinSize = pMaxBinSize;\n\tmM = 10000;\n\tmK = 5;\n\tmQ = 8;\n}\nInverseIndexStorageBloomierFilter::~InverseIndexStorageBloomierFilter() {\n\t\n}\nsize_t InverseIndexStorageBloomierFilter::size() {\n\treturn mInverseIndex->size();\n}\nvsize_t* InverseIndexStorageBloomierFilter::getElement(size_t pVectorId, size_t pHashValue) {\n return (*mInverseIndex)[pVectorId]->get(pHashValue); \n}\nvoid InverseIndexStorageBloomierFilter::insert(size_t pVectorId, size_t pHashValue, size_t pInstance) {\n if ((*mInverseIndex)[pVectorId] == NULL) {\n (*mInverseIndex)[pVectorId] = new BloomierFilter(mM, mK, mQ, 100, mMaxBinSize);\n }\n (*mInverseIndex)[pVectorId]->set(pHashValue, pInstance);\n}<|endoftext|>"} {"text":"<commit_before>\/**\n * Copyright (c) 2015 - The CM Authors <legal@clickmatcher.com>\n * All Rights Reserved.\n *\n * This file is CONFIDENTIAL -- Distribution or duplication of this material or\n * the information contained herein is strictly forbidden unless prior written\n * permission is obtained.\n *\/\n#include \"AutoCompleteServlet.h\"\n#include \"CTRCounter.h\"\n#include \"fnord-base\/Language.h\"\n#include \"fnord-base\/wallclock.h\"\n#include \"fnord-base\/io\/fileutil.h\"\n\nusing namespace fnord;\n\nnamespace cm {\n\nAutoCompleteServlet::AutoCompleteServlet(\n RefPtr<fts::Analyzer> analyzer) :\n analyzer_(analyzer) {}\n\nvoid AutoCompleteServlet::addTermInfo(const String& term, const TermInfo& ti) {\n if (ti.score < 1000) return;\n term_info_.emplace(term, ti);\n}\n\nvoid AutoCompleteServlet::handleHTTPRequest(\n http::HTTPRequest* req,\n http::HTTPResponse* res) {\n URI uri(req->uri());\n ResultListType results;\n const auto& params = uri.queryParams();\n\n \/* arguments *\/\n String lang_str;\n if (!URI::getParam(params, \"lang\", &lang_str)) {\n res->addBody(\"error: missing ?lang=... parameter\");\n res->setStatus(http::kStatusBadRequest);\n return;\n }\n\n String qstr;\n if (!URI::getParam(params, \"q\", &qstr)) {\n res->addBody(\"error: missing ?q=... parameter\");\n res->setStatus(http::kStatusBadRequest);\n return;\n }\n\n Vector<String> terms;\n Vector<String> valid_terms;\n auto lang = languageFromString(lang_str);\n analyzer_->tokenize(lang, qstr, &terms);\n if (terms.size() == 0) {\n res->addBody(\"error: invalid ?q=... parameter\");\n res->setStatus(http::kStatusBadRequest);\n return;\n }\n\n for (const auto& t : terms) {\n if (term_info_.count(lang_str + \"~\" + t) > 0) {\n valid_terms.emplace_back(t);\n }\n }\n\n if (terms.size() == 1 || valid_terms.size() == 0) {\n suggestSingleTerm(lang, terms, &results);\n } else {\n suggestMultiTerm(lang, terms, valid_terms, &results);\n }\n\n if (results.size() == 0 && qstr.length() > 2) {\n suggestFuzzy(lang, terms, &results);\n }\n\n#ifndef FNORD_NODEBUG\n fnord::logDebug(\n \"cm.autocompleteserver\",\n \"suggest lang=$0 qstr=$1 terms=$2 valid_terms=$3 results=$4\",\n lang_str,\n qstr,\n inspect(terms),\n inspect(valid_terms),\n results.size());\n#endif\n\n \/* write response *\/\n res->setStatus(http::kStatusOK);\n res->addHeader(\"Content-Type\", \"application\/json; charset=utf-8\");\n json::JSONOutputStream json(res->getBodyOutputStream());\n\n json.beginObject();\n json.addObjectEntry(\"query\");\n json.addString(qstr);\n json.addComma();\n json.addObjectEntry(\"suggestions\");\n json.beginArray();\n\n for (int i = 0; i < results.size() && i < 12; ++i) {\n if (i > 0) {\n json.addComma();\n }\n json.beginObject();\n json.addObjectEntry(\"text\");\n json.addString(std::get<0>(results[i]));\n json.addComma();\n json.addObjectEntry(\"score\");\n json.addFloat(std::get<1>(results[i]));\n json.addComma();\n json.addObjectEntry(\"url\");\n json.addString(std::get<2>(results[i]));\n json.endObject();\n }\n\n json.endArray();\n json.endObject();\n}\n\nvoid AutoCompleteServlet::suggestSingleTerm(\n Language lang,\n Vector<String> terms,\n ResultListType* results) {\n auto prefix = languageToString(lang) + \"~\" + terms.back();\n terms.pop_back();\n String qstr_prefix;\n\n if (terms.size() > 0 ) {\n qstr_prefix += StringUtil::join(terms, \" \") + \" \";\n }\n\n Vector<Pair<String, double>> matches;\n double best_match = 0;\n\n for (auto iter = term_info_.lower_bound(prefix);\n iter != term_info_.end() && StringUtil::beginsWith(iter->first, prefix);\n ++iter) {\n matches.emplace_back(iter->first, iter->second.score);\n if (iter->second.score > best_match) {\n best_match = iter->second.score;\n }\n }\n\n std::sort(matches.begin(), matches.end(), [] (\n const Pair<String, double>& a,\n const Pair<String, double>& b) {\n return b.second < a.second;\n });\n\n if (matches.size() > 0) {\n const auto& best_match_ti = term_info_.find(matches[0].first);\n for (const auto& c : best_match_ti->second.top_categories) {\n if ((c.second \/ best_match_ti->second.top_categories[0].second) < 0.2) {\n break;\n }\n\n auto label = StringUtil::format(\n \"$0$1 in $2\",\n qstr_prefix,\n matches[0].first,\n c.first);\n\n results->emplace_back(label, c.second, \"\");\n }\n }\n\n for (int m = 0; m < matches.size(); ++m) {\n auto score = matches[m].second;\n\n if ((score \/ best_match) < 0.1) {\n break;\n }\n\n results->emplace_back(qstr_prefix + matches[m].first, score, \"\");\n }\n\n if (matches.size() > 1) {\n const auto& best_match_ti = term_info_.find(matches[0].first);\n\n for (const auto& r : best_match_ti->second.related_terms) {\n auto label = StringUtil::format(\n \"$0$1 $2\",\n qstr_prefix,\n matches[0].first,\n r.first);\n\n results->emplace_back(label, r.second, \"\");\n }\n }\n}\n\nvoid AutoCompleteServlet::suggestMultiTerm(\n Language lang,\n Vector<String> terms,\n const Vector<String>& valid_terms,\n ResultListType* results) {\n auto lang_str = fnord::languageToString(lang);\n auto last_term = terms.back();\n terms.pop_back();\n String qstr_prefix;\n\n if (terms.size() > 0 ) {\n qstr_prefix += StringUtil::join(terms, \" \") + \" \";\n }\n\n HashMap<String, double> matches_h;\n double best_match = 0;\n for (const auto& vt : valid_terms) {\n if (last_term == vt) {\n continue;\n }\n\n const auto& vtinfo = term_info_.find(lang_str + \"~\" + vt)->second;\n for (const auto& related : vtinfo.related_terms) {\n if (!StringUtil::beginsWith(related.first, last_term)) {\n continue;\n }\n\n matches_h[related.first] += related.second;\n\n if (matches_h[related.first] > best_match) {\n best_match = matches_h[related.first];\n }\n }\n }\n\n Vector<Pair<String, double>> matches;\n for (const auto& m : matches_h) {\n matches.emplace_back(m);\n }\n\n std::sort(matches.begin(), matches.end(), [] (\n const Pair<String, double>& a,\n const Pair<String, double>& b) {\n return b.second < a.second;\n });\n\n for (int m = 0; m < matches.size(); ++m) {\n auto score = matches[m].second;\n\n if ((score \/ best_match) < 0.1) {\n break;\n }\n\n results->emplace_back(qstr_prefix + matches[m].first, score, \"\");\n }\n\n matches_h.clear();\n matches.clear();\n best_match = 0;\n\n for (const auto& vt : valid_terms) {\n const auto& vtinfo = term_info_.find(lang_str + \"~\" + vt)->second;\n for (const auto& related : vtinfo.related_terms) {\n matches_h[related.first] += related.second;\n\n if (matches_h[related.first] > best_match) {\n best_match = matches_h[related.first];\n }\n }\n }\n\n for (const auto& m : matches_h) {\n matches.emplace_back(m);\n }\n\n std::sort(matches.begin(), matches.end(), [] (\n const Pair<String, double>& a,\n const Pair<String, double>& b) {\n return b.second < a.second;\n });\n\n for (int m = 0; m < matches.size(); ++m) {\n auto score = matches[m].second;\n\n if ((score \/ best_match) < 0.1) {\n break;\n }\n\n results->emplace_back(qstr_prefix + matches[m].first, score, \"\");\n }\n}\n\nvoid AutoCompleteServlet::suggestFuzzy(\n Language lang,\n Vector<String> terms,\n ResultListType* results) {\n results->emplace_back(\"here be dragons: fuzzy suggestion\", 1.0, \"\");\n}\n\n\n}\n<commit_msg>multi term cat suggestion<commit_after>\/**\n * Copyright (c) 2015 - The CM Authors <legal@clickmatcher.com>\n * All Rights Reserved.\n *\n * This file is CONFIDENTIAL -- Distribution or duplication of this material or\n * the information contained herein is strictly forbidden unless prior written\n * permission is obtained.\n *\/\n#include \"AutoCompleteServlet.h\"\n#include \"CTRCounter.h\"\n#include \"fnord-base\/Language.h\"\n#include \"fnord-base\/wallclock.h\"\n#include \"fnord-base\/io\/fileutil.h\"\n\nusing namespace fnord;\n\nnamespace cm {\n\nAutoCompleteServlet::AutoCompleteServlet(\n RefPtr<fts::Analyzer> analyzer) :\n analyzer_(analyzer) {}\n\nvoid AutoCompleteServlet::addTermInfo(const String& term, const TermInfo& ti) {\n if (ti.score < 1000) return;\n term_info_.emplace(term, ti);\n}\n\nvoid AutoCompleteServlet::handleHTTPRequest(\n http::HTTPRequest* req,\n http::HTTPResponse* res) {\n URI uri(req->uri());\n ResultListType results;\n const auto& params = uri.queryParams();\n\n \/* arguments *\/\n String lang_str;\n if (!URI::getParam(params, \"lang\", &lang_str)) {\n res->addBody(\"error: missing ?lang=... parameter\");\n res->setStatus(http::kStatusBadRequest);\n return;\n }\n\n String qstr;\n if (!URI::getParam(params, \"q\", &qstr)) {\n res->addBody(\"error: missing ?q=... parameter\");\n res->setStatus(http::kStatusBadRequest);\n return;\n }\n\n Vector<String> terms;\n Vector<String> valid_terms;\n auto lang = languageFromString(lang_str);\n analyzer_->tokenize(lang, qstr, &terms);\n if (terms.size() == 0) {\n res->addBody(\"error: invalid ?q=... parameter\");\n res->setStatus(http::kStatusBadRequest);\n return;\n }\n\n for (const auto& t : terms) {\n if (term_info_.count(lang_str + \"~\" + t) > 0) {\n valid_terms.emplace_back(t);\n }\n }\n\n if (terms.size() == 1 || valid_terms.size() == 0) {\n suggestSingleTerm(lang, terms, &results);\n } else {\n suggestMultiTerm(lang, terms, valid_terms, &results);\n }\n\n if (results.size() == 0 && qstr.length() > 2) {\n suggestFuzzy(lang, terms, &results);\n }\n\n#ifndef FNORD_NODEBUG\n fnord::logDebug(\n \"cm.autocompleteserver\",\n \"suggest lang=$0 qstr=$1 terms=$2 valid_terms=$3 results=$4\",\n lang_str,\n qstr,\n inspect(terms),\n inspect(valid_terms),\n results.size());\n#endif\n\n \/* write response *\/\n res->setStatus(http::kStatusOK);\n res->addHeader(\"Content-Type\", \"application\/json; charset=utf-8\");\n json::JSONOutputStream json(res->getBodyOutputStream());\n\n json.beginObject();\n json.addObjectEntry(\"query\");\n json.addString(qstr);\n json.addComma();\n json.addObjectEntry(\"suggestions\");\n json.beginArray();\n\n for (int i = 0; i < results.size() && i < 12; ++i) {\n if (i > 0) {\n json.addComma();\n }\n json.beginObject();\n json.addObjectEntry(\"text\");\n json.addString(std::get<0>(results[i]));\n json.addComma();\n json.addObjectEntry(\"score\");\n json.addFloat(std::get<1>(results[i]));\n json.addComma();\n json.addObjectEntry(\"url\");\n json.addString(std::get<2>(results[i]));\n json.endObject();\n }\n\n json.endArray();\n json.endObject();\n}\n\nvoid AutoCompleteServlet::suggestSingleTerm(\n Language lang,\n Vector<String> terms,\n ResultListType* results) {\n auto prefix = languageToString(lang) + \"~\" + terms.back();\n terms.pop_back();\n String qstr_prefix;\n\n if (terms.size() > 0 ) {\n qstr_prefix += StringUtil::join(terms, \" \") + \" \";\n }\n\n Vector<Pair<String, double>> matches;\n double best_match = 0;\n\n for (auto iter = term_info_.lower_bound(prefix);\n iter != term_info_.end() && StringUtil::beginsWith(iter->first, prefix);\n ++iter) {\n matches.emplace_back(iter->first, iter->second.score);\n if (iter->second.score > best_match) {\n best_match = iter->second.score;\n }\n }\n\n std::sort(matches.begin(), matches.end(), [] (\n const Pair<String, double>& a,\n const Pair<String, double>& b) {\n return b.second < a.second;\n });\n\n if (matches.size() > 0) {\n const auto& best_match_ti = term_info_.find(matches[0].first);\n for (const auto& c : best_match_ti->second.top_categories) {\n if ((c.second \/ best_match_ti->second.top_categories[0].second) < 0.2) {\n break;\n }\n\n auto label = StringUtil::format(\n \"$0$1 in $2\",\n qstr_prefix,\n matches[0].first,\n c.first);\n\n results->emplace_back(label, c.second, \"\");\n }\n }\n\n for (int m = 0; m < matches.size(); ++m) {\n auto score = matches[m].second;\n\n if ((score \/ best_match) < 0.1) {\n break;\n }\n\n results->emplace_back(qstr_prefix + matches[m].first, score, \"\");\n }\n\n if (matches.size() > 1) {\n const auto& best_match_ti = term_info_.find(matches[0].first);\n\n for (const auto& r : best_match_ti->second.related_terms) {\n auto label = StringUtil::format(\n \"$0$1 $2\",\n qstr_prefix,\n matches[0].first,\n r.first);\n\n results->emplace_back(label, r.second, \"\");\n }\n }\n}\n\nvoid AutoCompleteServlet::suggestMultiTerm(\n Language lang,\n Vector<String> terms,\n const Vector<String>& valid_terms,\n ResultListType* results) {\n auto lang_str = fnord::languageToString(lang);\n auto last_term = terms.back();\n terms.pop_back();\n String qstr_prefix;\n\n if (terms.size() > 0 ) {\n qstr_prefix += StringUtil::join(terms, \" \") + \" \";\n }\n\n HashMap<String, double> topcats_h;\n double best_topcat = 0;\n HashMap<String, double> matches_h;\n double best_match = 0;\n for (const auto& vt : valid_terms) {\n const auto& vtinfo = term_info_.find(lang_str + \"~\" + vt)->second;\n\n for (const auto& topcat : vtinfo.top_categories) {\n topcats_h[topcat.first] += topcat.second;\n topcats_h[topcat.first] *= 2;\n\n if (topcats_h[topcat.first] > best_topcat) {\n best_topcat = topcats_h[topcat.first];\n }\n }\n\n if (last_term != vt) {\n for (const auto& related : vtinfo.related_terms) {\n if (!StringUtil::beginsWith(related.first, last_term)) {\n continue;\n }\n\n matches_h[related.first] += related.second;\n\n if (matches_h[related.first] > best_match) {\n best_match = matches_h[related.first];\n }\n }\n }\n }\n\n Vector<Pair<String, double>> topcats;\n for (const auto& m : topcats_h) {\n topcats.emplace_back(m);\n }\n\n std::sort(topcats.begin(), topcats.end(), [] (\n const Pair<String, double>& a,\n const Pair<String, double>& b) {\n return b.second < a.second;\n });\n\n for (int m = 0; m < topcats.size() && m < 3; ++m) {\n auto score = topcats[m].second;\n\n if ((score \/ best_topcat) < 0.2) {\n break;\n }\n\n auto label = StringUtil::format(\n \"$0 in $1\",\n StringUtil::join(valid_terms, \" \"),\n topcats[m].first);\n\n results->emplace_back(label, score, \"\");\n }\n\n Vector<Pair<String, double>> matches;\n for (const auto& m : matches_h) {\n matches.emplace_back(m);\n }\n\n std::sort(matches.begin(), matches.end(), [] (\n const Pair<String, double>& a,\n const Pair<String, double>& b) {\n return b.second < a.second;\n });\n\n for (int m = 0; m < matches.size(); ++m) {\n auto score = matches[m].second;\n\n if ((score \/ best_match) < 0.1) {\n break;\n }\n\n results->emplace_back(qstr_prefix + matches[m].first, score, \"\");\n }\n\n matches_h.clear();\n matches.clear();\n best_match = 0;\n\n for (const auto& vt : valid_terms) {\n const auto& vtinfo = term_info_.find(lang_str + \"~\" + vt)->second;\n for (const auto& related : vtinfo.related_terms) {\n matches_h[related.first] += related.second;\n\n if (matches_h[related.first] > best_match) {\n best_match = matches_h[related.first];\n }\n }\n }\n\n for (const auto& m : matches_h) {\n matches.emplace_back(m);\n }\n\n std::sort(matches.begin(), matches.end(), [] (\n const Pair<String, double>& a,\n const Pair<String, double>& b) {\n return b.second < a.second;\n });\n\n for (int m = 0; m < matches.size(); ++m) {\n auto score = matches[m].second;\n\n if ((score \/ best_match) < 0.1) {\n break;\n }\n\n results->emplace_back(qstr_prefix + matches[m].first, score, \"\");\n }\n}\n\nvoid AutoCompleteServlet::suggestFuzzy(\n Language lang,\n Vector<String> terms,\n ResultListType* results) {\n results->emplace_back(\"here be dragons: fuzzy suggestion\", 1.0, \"\");\n}\n\n\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"pnlAPI.h\"\n#include \"wx\/wxprec.h\"\n#include \"lime\/LimeSuite.h\"\n#ifndef WX_PRECOMP\n#include <wx\/wx.h>\n#endif \/\/WX_PRECOMP\n#include <wx\/spinctrl.h>\n\n#include \"IConnection.h\"\n#include \"lms7suiteEvents.h\"\n#include \"pnlLimeNetMicro.h\"\n#include \"lms7suiteAppFrame.h\"\n\nusing namespace std;\nusing namespace lime;\n\nenum Buttons {\n btnInit,\n btnEnCh,\n btnSetRate,\n btnSetRateDir,\n btnSetFreq,\n btnSetAnt,\n btnSetGain,\n btnSetdB,\n btnSetTest,\n btnGetRate,\n btnGetFreq,\n btnGetAnt,\n btnGetGain,\n btnGetdB,\n btnGetTest,\n btn_COUNT\n};\n\nstatic const wxString test_signals[] = {\"None\", \"NCO CLK\/8\", \"NCO CLK\/4\", \"NCO CLK\/8 FS\", \"NCO CLK\/8 FS\", \"DC\"};\n\npnlAPI::pnlAPI(LMS7SuiteAppFrame* parent) :\n wxFrame(parent, wxID_ANY, \"API Calls\", wxDefaultPosition, wxDefaultSize, wxDEFAULT_DIALOG_STYLE | wxRESIZE_BORDER),\n lmsControl(nullptr),\n lmsAppFrame(parent)\n{\n SetBackgroundColour(wxSystemSettings::GetColour(wxSYS_COLOUR_BTNFACE));\n wxFlexGridSizer* mainSizer;\n runButtons.resize(btn_COUNT);\n mainSizer = new wxFlexGridSizer( 0, 3, 1, 1);\n mainSizer->AddGrowableCol( 2 );\n mainSizer->SetFlexibleDirection( wxBOTH );\n mainSizer->SetNonFlexibleGrowMode( wxFLEX_GROWMODE_SPECIFIED );\n\n auto dirChoice = [this](){\n auto choice = new wxChoice(this, wxID_ANY);\n choice->Append(\"RX\");\n choice->Append(\"TX\");\n choice->SetSelection(0);\n return choice;\n };\n\n auto functionEntry = [this, mainSizer](Buttons btn, wxString label, std::vector<wxWindow*>args){\n runButtons[btn] = new wxButton(this, wxID_ANY, wxT(\"Run\"), wxDefaultPosition, wxDefaultSize, 0);\n mainSizer->Add( runButtons[btn], 0, wxALL, 1 );\n mainSizer->Add(new wxStaticText(this, wxID_ANY, label), 0, wxALL|wxALIGN_CENTER_VERTICAL, 5);\n runButtons[btn]->Connect(wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( pnlAPI::OnRun), NULL, this );\n auto paramSizer = new wxFlexGridSizer( 1, 0, 5, 5);\n for (auto a : args)\n paramSizer->Add(a, 0, wxALL|wxALIGN_CENTER_VERTICAL, 1);\n mainSizer->Add(paramSizer, 0, wxALL, 1 );\n return paramSizer;\n };\n\n functionEntry(btnInit, _(\"LMS_Init\"), {new wxStaticText(this, wxID_ANY, _(\" \"))});\n\n enChDir = dirChoice();\n enChCh = new ChWxChoice(this);\n enChEn = new wxChoice(this, wxID_ANY);\n enChEn->Append(\"Disabled\");\n enChEn->SetSelection(enChEn->Append(\"Enabled\"));\n functionEntry(btnEnCh, _(\"LMS_EnableChannel\"), {enChDir, enChCh, enChEn});\n\n setRateRate = new wxTextCtrl(this, wxNewId(), _(\"10\"), wxDefaultPosition, wxSize(64, -1));\n setRateOv = new wxChoice(this, wxID_ANY);\n for (int i = 32; i; i \/= 2)\n setRateOv->Append(wxString::Format(_(\"%ix\"), i));\n setRateOv->SetSelection(setRateOv->Append(\"Auto\"));\n auto text = new wxStaticText(this, wxID_ANY, _(\"MSps oversampling:\"));\n functionEntry(btnSetRate, _(\"LMS_SetSampleRate\"), {setRateRate, text, setRateOv});\n\n setRateDirDir = dirChoice();\n setRateDirRate = new wxTextCtrl(this, wxNewId(), _(\"10\"), wxDefaultPosition, wxSize(64, -1));\n setRateDirOv = new wxChoice(this, wxID_ANY);\n for (int i = 32; i; i \/= 2)\n setRateDirOv->Append(wxString::Format(_(\"%ix\"), i));\n setRateDirOv->SetSelection(setRateDirOv->Append(\"Auto\"));\n text = new wxStaticText(this, wxID_ANY, _(\"MSps oversampling:\"));\n functionEntry(btnSetRateDir, _(\"LMS_SetSampleRateDir\"), {setRateDirRate, text, setRateDirOv, setRateDirDir});\n\n setFreqDir = dirChoice();\n setFreqCh = new ChWxChoice(this);\n setFreqFreq = new wxTextCtrl(this, wxNewId(), _(\"500\"), wxDefaultPosition, wxSize(80, -1));\n text = new wxStaticText(this, wxID_ANY, _(\"MHz\"));\n functionEntry(btnSetFreq, _(\"LMS_SetLOFrequency\"), {setFreqDir, setFreqCh, setFreqFreq, text});\n\n setAntDir = dirChoice();\n setAntDir->Connect(wxEVT_COMMAND_CHOICE_SELECTED, wxCommandEventHandler(pnlAPI::OnAntDir), NULL, this);\n setAntCh = new ChWxChoice(this);\n setAntAnt = new wxChoice(this, wxID_ANY);\n functionEntry(btnSetAnt, _(\"LMS_SetAntenna\"), {setAntDir, setAntCh, setAntAnt});\n\n setGainDir = dirChoice();\n setGainCh = new ChWxChoice(this);\n setGainGain = new wxTextCtrl(this, wxNewId(), _(\"0.7\"), wxDefaultPosition, wxSize(48, -1));\n functionEntry(btnSetGain, _(\"LMS_SetNormalizedGain\"), {setGainDir, setGainCh, setGainGain});\n\n setdBDir = dirChoice();\n setdBCh = new ChWxChoice(this);\n setdBGain = new wxSpinCtrl(this, wxNewId(), _(\"\"), wxDefaultPosition, wxSize(56, -1), wxSP_ARROW_KEYS, 0, 100, 50);\n text = new wxStaticText(this, wxID_ANY, _(\"dB\"));\n functionEntry(btnSetdB, _(\"LMS_SetGaindB\"), {setdBDir, setdBCh, setdBGain, text});\n\n setTestDir = dirChoice();\n setTestCh = new ChWxChoice(this);\n setTestSig = new wxChoice(this, wxID_ANY, wxDefaultPosition, wxDefaultSize, 6 , test_signals);\n setTestSig->SetSelection(0);\n setTestI = new wxSpinCtrl(this, wxNewId(), _(\"\"), wxDefaultPosition, wxSize(72, -1), wxSP_ARROW_KEYS, 0, 65535, 10000);\n setTestQ = new wxSpinCtrl(this, wxNewId(), _(\"\"), wxDefaultPosition, wxSize(72, -1), wxSP_ARROW_KEYS, 0, 65535, 10000);\n text = new wxStaticText(this, wxID_ANY, _(\"DC_I\"));\n auto text2 = new wxStaticText(this, wxID_ANY, _(\"DC_Q\"));\n functionEntry(btnSetTest, _(\"LMS_SetTestSignal\"), {setTestDir, setTestCh, setTestSig, text, setTestI, text2, setTestQ});\n\n getRateDir = dirChoice();\n getRateCh = new ChWxChoice(this);\n getRateResult = new wxStaticText(this, wxID_ANY, _(\"\"));\n functionEntry(btnGetRate, _(\"LMS_GetSampleRate\"), {getRateDir, getRateCh, getRateResult});\n\n getFreqDir = dirChoice();\n getFreqCh = new ChWxChoice(this);\n getFreqResult = new wxStaticText(this, wxID_ANY, _(\"\"));\n functionEntry(btnGetFreq, _(\"LMS_GetLOFrequency\"), {getFreqDir, getFreqCh, getFreqResult});\n\n getAntDir = dirChoice();\n getAntCh = new ChWxChoice(this);\n getAntResult = new wxStaticText(this, wxID_ANY, _(\"\"));\n functionEntry(btnGetAnt, _(\"LMS_GetAntenna\"), {getAntDir, getAntCh, getAntResult});\n\n getGainDir = dirChoice();\n getGainCh = new ChWxChoice(this);\n getGainResult = new wxStaticText(this, wxID_ANY, _(\"\"));\n functionEntry(btnGetGain, _(\"LMS_GetNormalizedGain\"), {getGainDir, getGainCh, getGainResult});\n\n getdBDir = dirChoice();\n getdBCh = new ChWxChoice(this);\n getdBResult = new wxStaticText(this, wxID_ANY, _(\"\"));\n functionEntry(btnGetdB, _(\"LMS_GetGaindB\"), {getdBDir, getdBCh, getdBResult});\n\n getTestDir = dirChoice();\n getTestCh = new ChWxChoice(this);\n getTestResult = new wxStaticText(this, wxID_ANY, _(\"\"));\n functionEntry(btnGetTest, _(\"LMS_GetTestSignal\"), {getTestDir, getTestCh, getTestResult});\n\n this->SetSizer( mainSizer );\n this->Layout();\n mainSizer->Fit( this );\n}\n\npnlAPI::~pnlAPI()\n{\n \/\/ Disconnect Events\n setAntDir->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( pnlAPI::OnAntDir ), NULL, this );\n for (auto btn : runButtons)\n btn->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( pnlAPI::OnRun ), NULL, this );\n}\n\nvoid pnlAPI::OnRun( wxCommandEvent& event )\n{\n auto obj = event.GetEventObject();\n if (obj == runButtons[btnInit])\n {\n LMS_Init(lmsControl);\n lmsAppFrame->UpdateVisiblePanel();\n }\n else if (obj == runButtons[btnEnCh])\n {\n LMS_EnableChannel(lmsControl, enChDir->GetSelection(), enChCh->GetSelection(), enChEn->GetSelection());\n lmsAppFrame->UpdateVisiblePanel();\n }\n else if (obj == runButtons[btnSetdB])\n {\n LMS_SetGaindB(lmsControl, setdBDir->GetSelection(), setdBCh->GetSelection(), setdBGain->GetValue());\n lmsAppFrame->UpdateVisiblePanel();\n }\n else if (obj == runButtons[btnSetTest])\n {\n LMS_SetTestSignal(lmsControl, setTestDir->GetSelection(), setTestCh->GetSelection(), lms_testsig_t(setTestSig->GetSelection()), setTestI->GetValue(), setTestQ->GetValue());\n lmsAppFrame->UpdateVisiblePanel();\n }\n else if (obj == runButtons[btnSetFreq])\n {\n double freq = 0;\n setFreqFreq->GetValue().ToDouble(&freq);\n LMS_SetLOFrequency(lmsControl, setFreqDir->GetSelection(), setFreqCh->GetSelection(), freq*1e6);\n lmsAppFrame->UpdateVisiblePanel();\n }\n else if (obj == runButtons[btnSetRate])\n {\n double freq = 0;\n setRateRate->GetValue().ToDouble(&freq);\n LMS_SetSampleRate(lmsControl, freq*1e6, 32>>setRateOv->GetSelection());\n lmsAppFrame->UpdateVisiblePanel();\n }\n else if (obj == runButtons[btnSetAnt])\n {\n double freq = 0;\n setRateRate->GetValue().ToDouble(&freq);\n LMS_SetAntenna(lmsControl, setAntDir->GetSelection(), setAntCh->GetSelection(), setAntAnt->GetSelection());\n lmsAppFrame->UpdateVisiblePanel();\n }\n else if (obj == runButtons[btnSetGain])\n {\n double gain = 0;\n setGainGain->GetValue().ToDouble(&gain);\n LMS_SetNormalizedGain(lmsControl, setGainDir->GetSelection(), setGainCh->GetSelection(), gain);\n lmsAppFrame->UpdateVisiblePanel();\n }\n else if (obj == runButtons[btnGetRate])\n {\n double host, rf;\n LMS_GetSampleRate(lmsControl, getRateDir->GetSelection(), getRateCh->GetSelection(), &host, &rf);\n getRateResult->SetLabel(wxString::Format(_(\"Sample Rate: %.6f MSps (RF: %.3f MSps)\"), host\/1e6, rf\/1e6));\n }\n else if (obj == runButtons[btnGetFreq])\n {\n double freq;\n LMS_GetLOFrequency(lmsControl, getFreqDir->GetSelection(), getFreqCh->GetSelection(), &freq);\n getFreqResult->SetLabel(wxString::Format(_(\"RF Frequency: %.6f MHz\"), freq\/1e6));\n }\n else if (obj == runButtons[btnGetAnt])\n {\n int index = LMS_GetAntenna(lmsControl, getAntDir->GetSelection(), getAntCh->GetSelection());\n if (index < 0)\n return;\n lms_name_t list[16];\n int cnt = LMS_GetAntennaList(lmsControl, getAntDir->GetSelection(), getAntCh->GetSelection(), list);\n if (index >= cnt)\n return;\n getAntResult->SetLabel(wxString::Format(_(\"%s\"), list[index]));\n }\n else if (obj == runButtons[btnGetGain])\n {\n double gain;\n LMS_GetNormalizedGain(lmsControl, getGainDir->GetSelection(), getGainCh->GetSelection(), &gain);\n getGainResult->SetLabel(wxString::Format(_(\"%.2f\"), gain));\n }\n else if (obj == runButtons[btnGetdB])\n {\n unsigned gain;\n LMS_GetGaindB(lmsControl, getdBDir->GetSelection(), getdBCh->GetSelection(), &gain);\n getdBResult->SetLabel(wxString::Format(_(\"%d dB\"), gain));\n }\n else if (obj == runButtons[btnGetTest])\n {\n lms_testsig_t sig = LMS_TESTSIG_NONE;\n LMS_GetTestSignal(lmsControl, getTestDir->GetSelection(), getTestCh->GetSelection(), &sig);\n getTestResult->SetLabel(wxString::Format(_(\"%s\"), test_signals[sig].c_str()));\n }\n\n}\n\nvoid pnlAPI::OnAntDir( wxCommandEvent& event )\n{\n lms_name_t list[16];\n int cnt = LMS_GetAntennaList(lmsControl, event.GetInt(), 0, list);\n setAntAnt->Clear();\n for (int i = 0; i < cnt; i++)\n setAntAnt->Append(list[i]);\n setAntAnt->SetSelection(0);\n}\n\nvoid pnlAPI::Initialize(lms_device_t* controlPort)\n{\n lmsControl = controlPort;\n\n if (lmsControl)\n {\n for (auto ctrl : chControls)\n ctrl->Clear();\n for (int i = 0; i< LMS_GetNumChannels(lmsControl, false); i++)\n {\n auto txt = wxString::Format(_(\"ch %i\"), i);\n for (auto ctrl : chControls)\n ctrl->Append(txt);\n }\n for (auto ctrl : chControls)\n ctrl->SetSelection(0);\n {\n wxCommandEvent evt;\n evt.SetInt(0);\n OnAntDir(evt);\n }\n }\n}\n\n<commit_msg>pnlAPI: fix missing handling for LMS_SetSampleRateDir button<commit_after>#include \"pnlAPI.h\"\n#include \"wx\/wxprec.h\"\n#include \"lime\/LimeSuite.h\"\n#ifndef WX_PRECOMP\n#include <wx\/wx.h>\n#endif \/\/WX_PRECOMP\n#include <wx\/spinctrl.h>\n\n#include \"IConnection.h\"\n#include \"lms7suiteEvents.h\"\n#include \"pnlLimeNetMicro.h\"\n#include \"lms7suiteAppFrame.h\"\n\nusing namespace std;\nusing namespace lime;\n\nenum Buttons {\n btnInit,\n btnEnCh,\n btnSetRate,\n btnSetRateDir,\n btnSetFreq,\n btnSetAnt,\n btnSetGain,\n btnSetdB,\n btnSetTest,\n btnGetRate,\n btnGetFreq,\n btnGetAnt,\n btnGetGain,\n btnGetdB,\n btnGetTest,\n btn_COUNT\n};\n\nstatic const wxString test_signals[] = {\"None\", \"NCO CLK\/8\", \"NCO CLK\/4\", \"NCO CLK\/8 FS\", \"NCO CLK\/8 FS\", \"DC\"};\n\npnlAPI::pnlAPI(LMS7SuiteAppFrame* parent) :\n wxFrame(parent, wxID_ANY, \"API Calls\", wxDefaultPosition, wxDefaultSize, wxDEFAULT_DIALOG_STYLE | wxRESIZE_BORDER),\n lmsControl(nullptr),\n lmsAppFrame(parent)\n{\n SetBackgroundColour(wxSystemSettings::GetColour(wxSYS_COLOUR_BTNFACE));\n wxFlexGridSizer* mainSizer;\n runButtons.resize(btn_COUNT);\n mainSizer = new wxFlexGridSizer( 0, 3, 1, 1);\n mainSizer->AddGrowableCol( 2 );\n mainSizer->SetFlexibleDirection( wxBOTH );\n mainSizer->SetNonFlexibleGrowMode( wxFLEX_GROWMODE_SPECIFIED );\n\n auto dirChoice = [this](){\n auto choice = new wxChoice(this, wxID_ANY);\n choice->Append(\"RX\");\n choice->Append(\"TX\");\n choice->SetSelection(0);\n return choice;\n };\n\n auto functionEntry = [this, mainSizer](Buttons btn, wxString label, std::vector<wxWindow*>args){\n runButtons[btn] = new wxButton(this, wxID_ANY, wxT(\"Run\"), wxDefaultPosition, wxDefaultSize, 0);\n mainSizer->Add( runButtons[btn], 0, wxALL, 1 );\n mainSizer->Add(new wxStaticText(this, wxID_ANY, label), 0, wxALL|wxALIGN_CENTER_VERTICAL, 5);\n runButtons[btn]->Connect(wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( pnlAPI::OnRun), NULL, this );\n auto paramSizer = new wxFlexGridSizer( 1, 0, 5, 5);\n for (auto a : args)\n paramSizer->Add(a, 0, wxALL|wxALIGN_CENTER_VERTICAL, 1);\n mainSizer->Add(paramSizer, 0, wxALL, 1 );\n return paramSizer;\n };\n\n functionEntry(btnInit, _(\"LMS_Init\"), {new wxStaticText(this, wxID_ANY, _(\" \"))});\n\n enChDir = dirChoice();\n enChCh = new ChWxChoice(this);\n enChEn = new wxChoice(this, wxID_ANY);\n enChEn->Append(\"Disabled\");\n enChEn->SetSelection(enChEn->Append(\"Enabled\"));\n functionEntry(btnEnCh, _(\"LMS_EnableChannel\"), {enChDir, enChCh, enChEn});\n\n setRateRate = new wxTextCtrl(this, wxNewId(), _(\"10\"), wxDefaultPosition, wxSize(64, -1));\n setRateOv = new wxChoice(this, wxID_ANY);\n for (int i = 32; i; i \/= 2)\n setRateOv->Append(wxString::Format(_(\"%ix\"), i));\n setRateOv->SetSelection(setRateOv->Append(\"Auto\"));\n auto text = new wxStaticText(this, wxID_ANY, _(\"MSps oversampling:\"));\n functionEntry(btnSetRate, _(\"LMS_SetSampleRate\"), {setRateRate, text, setRateOv});\n\n setRateDirDir = dirChoice();\n setRateDirRate = new wxTextCtrl(this, wxNewId(), _(\"10\"), wxDefaultPosition, wxSize(64, -1));\n setRateDirOv = new wxChoice(this, wxID_ANY);\n for (int i = 32; i; i \/= 2)\n setRateDirOv->Append(wxString::Format(_(\"%ix\"), i));\n setRateDirOv->SetSelection(setRateDirOv->Append(\"Auto\"));\n text = new wxStaticText(this, wxID_ANY, _(\"MSps oversampling:\"));\n functionEntry(btnSetRateDir, _(\"LMS_SetSampleRateDir\"), {setRateDirRate, text, setRateDirOv, setRateDirDir});\n\n setFreqDir = dirChoice();\n setFreqCh = new ChWxChoice(this);\n setFreqFreq = new wxTextCtrl(this, wxNewId(), _(\"500\"), wxDefaultPosition, wxSize(80, -1));\n text = new wxStaticText(this, wxID_ANY, _(\"MHz\"));\n functionEntry(btnSetFreq, _(\"LMS_SetLOFrequency\"), {setFreqDir, setFreqCh, setFreqFreq, text});\n\n setAntDir = dirChoice();\n setAntDir->Connect(wxEVT_COMMAND_CHOICE_SELECTED, wxCommandEventHandler(pnlAPI::OnAntDir), NULL, this);\n setAntCh = new ChWxChoice(this);\n setAntAnt = new wxChoice(this, wxID_ANY);\n functionEntry(btnSetAnt, _(\"LMS_SetAntenna\"), {setAntDir, setAntCh, setAntAnt});\n\n setGainDir = dirChoice();\n setGainCh = new ChWxChoice(this);\n setGainGain = new wxTextCtrl(this, wxNewId(), _(\"0.7\"), wxDefaultPosition, wxSize(48, -1));\n functionEntry(btnSetGain, _(\"LMS_SetNormalizedGain\"), {setGainDir, setGainCh, setGainGain});\n\n setdBDir = dirChoice();\n setdBCh = new ChWxChoice(this);\n setdBGain = new wxSpinCtrl(this, wxNewId(), _(\"\"), wxDefaultPosition, wxSize(56, -1), wxSP_ARROW_KEYS, 0, 100, 50);\n text = new wxStaticText(this, wxID_ANY, _(\"dB\"));\n functionEntry(btnSetdB, _(\"LMS_SetGaindB\"), {setdBDir, setdBCh, setdBGain, text});\n\n setTestDir = dirChoice();\n setTestCh = new ChWxChoice(this);\n setTestSig = new wxChoice(this, wxID_ANY, wxDefaultPosition, wxDefaultSize, 6 , test_signals);\n setTestSig->SetSelection(0);\n setTestI = new wxSpinCtrl(this, wxNewId(), _(\"\"), wxDefaultPosition, wxSize(72, -1), wxSP_ARROW_KEYS, 0, 65535, 10000);\n setTestQ = new wxSpinCtrl(this, wxNewId(), _(\"\"), wxDefaultPosition, wxSize(72, -1), wxSP_ARROW_KEYS, 0, 65535, 10000);\n text = new wxStaticText(this, wxID_ANY, _(\"DC_I\"));\n auto text2 = new wxStaticText(this, wxID_ANY, _(\"DC_Q\"));\n functionEntry(btnSetTest, _(\"LMS_SetTestSignal\"), {setTestDir, setTestCh, setTestSig, text, setTestI, text2, setTestQ});\n\n getRateDir = dirChoice();\n getRateCh = new ChWxChoice(this);\n getRateResult = new wxStaticText(this, wxID_ANY, _(\"\"));\n functionEntry(btnGetRate, _(\"LMS_GetSampleRate\"), {getRateDir, getRateCh, getRateResult});\n\n getFreqDir = dirChoice();\n getFreqCh = new ChWxChoice(this);\n getFreqResult = new wxStaticText(this, wxID_ANY, _(\"\"));\n functionEntry(btnGetFreq, _(\"LMS_GetLOFrequency\"), {getFreqDir, getFreqCh, getFreqResult});\n\n getAntDir = dirChoice();\n getAntCh = new ChWxChoice(this);\n getAntResult = new wxStaticText(this, wxID_ANY, _(\"\"));\n functionEntry(btnGetAnt, _(\"LMS_GetAntenna\"), {getAntDir, getAntCh, getAntResult});\n\n getGainDir = dirChoice();\n getGainCh = new ChWxChoice(this);\n getGainResult = new wxStaticText(this, wxID_ANY, _(\"\"));\n functionEntry(btnGetGain, _(\"LMS_GetNormalizedGain\"), {getGainDir, getGainCh, getGainResult});\n\n getdBDir = dirChoice();\n getdBCh = new ChWxChoice(this);\n getdBResult = new wxStaticText(this, wxID_ANY, _(\"\"));\n functionEntry(btnGetdB, _(\"LMS_GetGaindB\"), {getdBDir, getdBCh, getdBResult});\n\n getTestDir = dirChoice();\n getTestCh = new ChWxChoice(this);\n getTestResult = new wxStaticText(this, wxID_ANY, _(\"\"));\n functionEntry(btnGetTest, _(\"LMS_GetTestSignal\"), {getTestDir, getTestCh, getTestResult});\n\n this->SetSizer( mainSizer );\n this->Layout();\n mainSizer->Fit( this );\n}\n\npnlAPI::~pnlAPI()\n{\n \/\/ Disconnect Events\n setAntDir->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( pnlAPI::OnAntDir ), NULL, this );\n for (auto btn : runButtons)\n btn->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( pnlAPI::OnRun ), NULL, this );\n}\n\nvoid pnlAPI::OnRun( wxCommandEvent& event )\n{\n auto obj = event.GetEventObject();\n if (obj == runButtons[btnInit])\n {\n LMS_Init(lmsControl);\n lmsAppFrame->UpdateVisiblePanel();\n }\n else if (obj == runButtons[btnEnCh])\n {\n LMS_EnableChannel(lmsControl, enChDir->GetSelection(), enChCh->GetSelection(), enChEn->GetSelection());\n lmsAppFrame->UpdateVisiblePanel();\n }\n else if (obj == runButtons[btnSetdB])\n {\n LMS_SetGaindB(lmsControl, setdBDir->GetSelection(), setdBCh->GetSelection(), setdBGain->GetValue());\n lmsAppFrame->UpdateVisiblePanel();\n }\n else if (obj == runButtons[btnSetTest])\n {\n LMS_SetTestSignal(lmsControl, setTestDir->GetSelection(), setTestCh->GetSelection(), lms_testsig_t(setTestSig->GetSelection()), setTestI->GetValue(), setTestQ->GetValue());\n lmsAppFrame->UpdateVisiblePanel();\n }\n else if (obj == runButtons[btnSetFreq])\n {\n double freq = 0;\n setFreqFreq->GetValue().ToDouble(&freq);\n LMS_SetLOFrequency(lmsControl, setFreqDir->GetSelection(), setFreqCh->GetSelection(), freq*1e6);\n lmsAppFrame->UpdateVisiblePanel();\n }\n else if (obj == runButtons[btnSetRate])\n {\n double freq = 0;\n setRateRate->GetValue().ToDouble(&freq);\n LMS_SetSampleRate(lmsControl, freq*1e6, 32>>setRateOv->GetSelection());\n lmsAppFrame->UpdateVisiblePanel();\n }\n else if (obj == runButtons[btnSetRateDir])\n {\n double freq = 0;\n setRateDirRate->GetValue().ToDouble(&freq);\n LMS_SetSampleRateDir(lmsControl, setRateDirDir->GetSelection(), freq*1e6, 32>>setRateDirOv->GetSelection());\n lmsAppFrame->UpdateVisiblePanel();\n }\n else if (obj == runButtons[btnSetAnt])\n {\n double freq = 0;\n setRateRate->GetValue().ToDouble(&freq);\n LMS_SetAntenna(lmsControl, setAntDir->GetSelection(), setAntCh->GetSelection(), setAntAnt->GetSelection());\n lmsAppFrame->UpdateVisiblePanel();\n }\n else if (obj == runButtons[btnSetGain])\n {\n double gain = 0;\n setGainGain->GetValue().ToDouble(&gain);\n LMS_SetNormalizedGain(lmsControl, setGainDir->GetSelection(), setGainCh->GetSelection(), gain);\n lmsAppFrame->UpdateVisiblePanel();\n }\n else if (obj == runButtons[btnGetRate])\n {\n double host, rf;\n LMS_GetSampleRate(lmsControl, getRateDir->GetSelection(), getRateCh->GetSelection(), &host, &rf);\n getRateResult->SetLabel(wxString::Format(_(\"Sample Rate: %.6f MSps (RF: %.3f MSps)\"), host\/1e6, rf\/1e6));\n }\n else if (obj == runButtons[btnGetFreq])\n {\n double freq;\n LMS_GetLOFrequency(lmsControl, getFreqDir->GetSelection(), getFreqCh->GetSelection(), &freq);\n getFreqResult->SetLabel(wxString::Format(_(\"RF Frequency: %.6f MHz\"), freq\/1e6));\n }\n else if (obj == runButtons[btnGetAnt])\n {\n int index = LMS_GetAntenna(lmsControl, getAntDir->GetSelection(), getAntCh->GetSelection());\n if (index < 0)\n return;\n lms_name_t list[16];\n int cnt = LMS_GetAntennaList(lmsControl, getAntDir->GetSelection(), getAntCh->GetSelection(), list);\n if (index >= cnt)\n return;\n getAntResult->SetLabel(wxString::Format(_(\"%s\"), list[index]));\n }\n else if (obj == runButtons[btnGetGain])\n {\n double gain;\n LMS_GetNormalizedGain(lmsControl, getGainDir->GetSelection(), getGainCh->GetSelection(), &gain);\n getGainResult->SetLabel(wxString::Format(_(\"%.2f\"), gain));\n }\n else if (obj == runButtons[btnGetdB])\n {\n unsigned gain;\n LMS_GetGaindB(lmsControl, getdBDir->GetSelection(), getdBCh->GetSelection(), &gain);\n getdBResult->SetLabel(wxString::Format(_(\"%d dB\"), gain));\n }\n else if (obj == runButtons[btnGetTest])\n {\n lms_testsig_t sig = LMS_TESTSIG_NONE;\n LMS_GetTestSignal(lmsControl, getTestDir->GetSelection(), getTestCh->GetSelection(), &sig);\n getTestResult->SetLabel(wxString::Format(_(\"%s\"), test_signals[sig].c_str()));\n }\n\n}\n\nvoid pnlAPI::OnAntDir( wxCommandEvent& event )\n{\n lms_name_t list[16];\n int cnt = LMS_GetAntennaList(lmsControl, event.GetInt(), 0, list);\n setAntAnt->Clear();\n for (int i = 0; i < cnt; i++)\n setAntAnt->Append(list[i]);\n setAntAnt->SetSelection(0);\n}\n\nvoid pnlAPI::Initialize(lms_device_t* controlPort)\n{\n lmsControl = controlPort;\n\n if (lmsControl)\n {\n for (auto ctrl : chControls)\n ctrl->Clear();\n for (int i = 0; i< LMS_GetNumChannels(lmsControl, false); i++)\n {\n auto txt = wxString::Format(_(\"ch %i\"), i);\n for (auto ctrl : chControls)\n ctrl->Append(txt);\n }\n for (auto ctrl : chControls)\n ctrl->SetSelection(0);\n {\n wxCommandEvent evt;\n evt.SetInt(0);\n OnAntDir(evt);\n }\n }\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/**\n * Copyright (c) 2015 Damien Tardy-Panis\n *\n * This file is subject to the terms and conditions defined in\n * file 'LICENSE', which is part of this source code package.\n **\/\n\n#include \"Lunarbaboon.h\"\n\n#include <QDebug>\n#include <QRegularExpression>\n#include <QRegularExpressionMatch>\n\nLunarbaboon::Lunarbaboon(QObject *parent) :\n Comic(parent)\n{\n m_info.id = QString(\"lunarbaboon\");\n m_info.name = QString(\"Lunarbaboon\");\n m_info.color = QColor(205, 207, 206);\n m_info.authors = QStringList(\"Chris Grady\");\n m_info.homepage = QUrl(\"http:\/\/www.lunarbaboon.com\/\");\n m_info.country = QLocale::Canada;\n m_info.language = QLocale::English;\n m_info.startDate = QDate::fromString(\"2012-07-09\", Qt::ISODate);\n m_info.endDate = QDate::currentDate();\n m_info.stripSourceUrl = QUrl(\"http:\/\/www.lunarbaboon.com\/\");\n}\n\nQUrl Lunarbaboon::extractStripImageUrl(QByteArray data)\n{\n QString html(data);\n QRegularExpression reg(\"<img[^>]*src=\\\"(\/storage\/[^\\\"]*)\\\"\");\n QRegularExpressionMatch match = reg.match(html);\n\n if (!match.hasMatch()) {\n return QUrl();\n }\n\n QString src = match.captured(1);\n\n return QUrl(\"http:\/\/www.lunarbaboon.com\/\" + src);\n}\n<commit_msg>fix Lunarbaboon comic<commit_after>\/**\n * Copyright (c) 2015 Damien Tardy-Panis\n *\n * This file is subject to the terms and conditions defined in\n * file 'LICENSE', which is part of this source code package.\n **\/\n\n#include \"Lunarbaboon.h\"\n\n#include <QDebug>\n#include <QRegularExpression>\n#include <QRegularExpressionMatch>\n\nLunarbaboon::Lunarbaboon(QObject *parent) :\n Comic(parent)\n{\n m_info.id = QString(\"lunarbaboon\");\n m_info.name = QString(\"Lunarbaboon\");\n m_info.color = QColor(205, 207, 206);\n m_info.authors = QStringList(\"Chris Grady\");\n m_info.homepage = QUrl(\"http:\/\/www.lunarbaboon.com\/\");\n m_info.country = QLocale::Canada;\n m_info.language = QLocale::English;\n m_info.startDate = QDate::fromString(\"2012-07-09\", Qt::ISODate);\n m_info.endDate = QDate::currentDate();\n m_info.stripSourceUrl = QUrl(\"http:\/\/www.lunarbaboon.com\/\");\n}\n\nQUrl Lunarbaboon::extractStripImageUrl(QByteArray data)\n{\n QString html(data);\n QRegularExpression reg(\"<img[^>]*src=\\\"(\/storage\/[^\\\"]*)\\\"\");\n QRegularExpressionMatch match = reg.match(html);\n\n if (!match.hasMatch()) {\n return QUrl();\n }\n\n QString src = match.captured(1);\n\n return QUrl(\"http:\/\/www.lunarbaboon.com\" + src);\n}\n<|endoftext|>"} {"text":"<commit_before>#include <osg\/ArgumentParser>\n#include <osg\/ApplicationUsage>\n\n#include <osgDB\/ReadFile>\n#include <osgDB\/FileNameUtils>\n#include <osgDB\/fstream>\n\n#include <iostream>\n\n\/\/ Search in str for all occurences of spat and replace them with rpat.\nvoid searchAndReplace(std::string& str, const std::string& spat, const std::string& rpat)\n{\n std::string::size_type pos = 0;\n while ((pos = str.find(spat, pos)) != std::string::npos)\n {\n str.replace(pos, spat.length(), rpat);\n }\n}\n\nvoid writeShader(osg::Shader* shader, const std::string& cppFileName, const std::string& variableName)\n{\n osgDB::ofstream fout(cppFileName.c_str());\n if (!fout)\n {\n std::cout<<\"Error: could not open file `\"<<cppFileName<<\"` for writing.\"<<std::endl;\n }\n\n std::string shaderSource = shader->getShaderSource();\n searchAndReplace(shaderSource, \"\\r\\n\", \"\\n\");\n searchAndReplace(shaderSource, \"\\r\", \"\\n\");\n\n std::string variableString = std::string(\"char \")+variableName+std::string(\"[] = \");\n \n std::string::size_type startOfLine = 0;\n std::string::size_type endOfLine = shaderSource.find_first_of('\\n', startOfLine);\n \n if (endOfLine==std::string::npos) \n {\n fout<<variableString<<shaderSource<<\"\\\\n\\\";\"<<std::endl;\n }\n else\n {\n std::string padding(variableString.size(),' ');\n\n fout<<variableString<<\"\\\"\"<<shaderSource.substr(startOfLine,endOfLine-startOfLine)<<\"\\\\n\\\"\"<<std::endl;\n startOfLine = endOfLine+1;\n endOfLine = shaderSource.find_first_of('\\n', startOfLine);\n\n while (endOfLine != std::string::npos)\n {\n fout<<padding<<\"\\\"\"<<shaderSource.substr(startOfLine,endOfLine-startOfLine)<<\"\\\\n\\\"\"<<std::endl;\n startOfLine = endOfLine + 1;\n endOfLine = shaderSource.find_first_of('\\n', startOfLine);\n }\n fout<<padding<<\"\\\"\"<<shaderSource.substr(startOfLine,endOfLine-startOfLine)<<\"\\\\n\\\";\"<<std::endl;\n }\n std::cout<<\"Written shader to `\"<<cppFileName<<\"`\"<<std::endl;\n}\n\nint main( int argc, char **argv )\n{\n \/\/ use an ArgumentParser object to manage the program arguments.\n osg::ArgumentParser arguments(&argc,argv);\n \n \/\/ set up the usage document, in case we need to print out how to use this program.\n arguments.getApplicationUsage()->setApplicationName(arguments.getApplicationName());\n arguments.getApplicationUsage()->setDescription(arguments.getApplicationName()+\" is a utility for converting between various input and output databases formats.\");\n arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+\" [options] filename ...\");\n arguments.getApplicationUsage()->addCommandLineOption(\"--shader <filename>\",\"Shader file to create a .cpp file for.\");\n arguments.getApplicationUsage()->addCommandLineOption(\"-h or --help\",\"Display command line parameters\");\n\n \/\/ if user request help write it out to cout.\n if (arguments.read(\"-h\") || arguments.read(\"--help\"))\n { \n arguments.getApplicationUsage()->write(std::cout);\n return 1;\n }\n \n std::string filename;\n if (arguments.read(\"--shader\",filename))\n {\n osg::ref_ptr<osg::Shader> shader = osgDB::readShaderFile(filename);\n if (shader.valid())\n {\n std::string name = osgDB::getStrippedName(filename);\n std::string path = osgDB::getFilePath(filename);\n std::string invalidCharacters = \"-+\/\\\\*=(){}[]:;<>,.?@'~#`!\\\"\";\n std::string numbericCharacters = \"0123456789\";\n std::string::size_type pos = name.find_first_of(invalidCharacters);\n while (pos != std::string::npos)\n {\n name[pos] = '_';\n pos = name.find_first_of(invalidCharacters);\n }\n \n std::string ext = osgDB::getFileExtension(filename);\n std::string cppFileName = osgDB::concatPaths(path, name + \"_\" + ext + \".cpp\");\n std::string variableName = name + \"_\" + ext;\n writeShader(shader.get(), cppFileName, variableName);\n\n return 0;\n }\n else\n {\n std::cout<<\"Error: could not find file '\"<<filename<<\"'\"<<std::endl;\n return 1;\n }\n \n }\n\n std::cout<<\"No appropriate command line options used.\"<<std::endl;\n\n arguments.getApplicationUsage()->write(std::cout);\n return 1;\n}\n<commit_msg>From Wang Rui, \"A Chinese engineer (named Beilei Geng) reports a possible bug in the osg2cpp application to me today. The conversion result may become incorrect if there are quotation marks ( \" ) in the shader file, which will mostly appear in comment lines.<commit_after>#include <osg\/ArgumentParser>\n#include <osg\/ApplicationUsage>\n\n#include <osgDB\/ReadFile>\n#include <osgDB\/FileNameUtils>\n#include <osgDB\/fstream>\n\n#include <iostream>\n\n\/\/ Search in str for all occurences of spat and replace them with rpat.\nvoid searchAndReplace(std::string& str, const std::string& spat, const std::string& rpat)\n{\n std::string::size_type pos = 0;\n while ((pos = str.find(spat, pos)) != std::string::npos)\n {\n str.replace(pos, spat.length(), rpat);\n }\n}\n\nvoid writeShader(osg::Shader* shader, const std::string& cppFileName, const std::string& variableName)\n{\n osgDB::ofstream fout(cppFileName.c_str());\n if (!fout)\n {\n std::cout<<\"Error: could not open file `\"<<cppFileName<<\"` for writing.\"<<std::endl;\n }\n\n std::string shaderSource = shader->getShaderSource();\n searchAndReplace(shaderSource, \"\\r\\n\", \"\\n\");\n searchAndReplace(shaderSource, \"\\r\", \"\\n\");\n searchAndReplace(shaderSource, \"\\\"\", \"\\\\\\\"\");\n \n std::string variableString = std::string(\"char \")+variableName+std::string(\"[] = \");\n \n std::string::size_type startOfLine = 0;\n std::string::size_type endOfLine = shaderSource.find_first_of('\\n', startOfLine);\n \n if (endOfLine==std::string::npos) \n {\n fout<<variableString<<shaderSource<<\"\\\\n\\\";\"<<std::endl;\n }\n else\n {\n std::string padding(variableString.size(),' ');\n\n fout<<variableString<<\"\\\"\"<<shaderSource.substr(startOfLine,endOfLine-startOfLine)<<\"\\\\n\\\"\"<<std::endl;\n startOfLine = endOfLine+1;\n endOfLine = shaderSource.find_first_of('\\n', startOfLine);\n\n while (endOfLine != std::string::npos)\n {\n fout<<padding<<\"\\\"\"<<shaderSource.substr(startOfLine,endOfLine-startOfLine)<<\"\\\\n\\\"\"<<std::endl;\n startOfLine = endOfLine + 1;\n endOfLine = shaderSource.find_first_of('\\n', startOfLine);\n }\n fout<<padding<<\"\\\"\"<<shaderSource.substr(startOfLine,endOfLine-startOfLine)<<\"\\\\n\\\";\"<<std::endl;\n }\n std::cout<<\"Written shader to `\"<<cppFileName<<\"`\"<<std::endl;\n}\n\nint main( int argc, char **argv )\n{\n \/\/ use an ArgumentParser object to manage the program arguments.\n osg::ArgumentParser arguments(&argc,argv);\n \n \/\/ set up the usage document, in case we need to print out how to use this program.\n arguments.getApplicationUsage()->setApplicationName(arguments.getApplicationName());\n arguments.getApplicationUsage()->setDescription(arguments.getApplicationName()+\" is a utility for converting between various input and output databases formats.\");\n arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+\" [options] filename ...\");\n arguments.getApplicationUsage()->addCommandLineOption(\"--shader <filename>\",\"Shader file to create a .cpp file for.\");\n arguments.getApplicationUsage()->addCommandLineOption(\"-h or --help\",\"Display command line parameters\");\n\n \/\/ if user request help write it out to cout.\n if (arguments.read(\"-h\") || arguments.read(\"--help\"))\n { \n arguments.getApplicationUsage()->write(std::cout);\n return 1;\n }\n \n std::string filename;\n if (arguments.read(\"--shader\",filename))\n {\n osg::ref_ptr<osg::Shader> shader = osgDB::readShaderFile(filename);\n if (shader.valid())\n {\n std::string name = osgDB::getStrippedName(filename);\n std::string path = osgDB::getFilePath(filename);\n std::string invalidCharacters = \"-+\/\\\\*=(){}[]:;<>,.?@'~#`!\\\"\";\n std::string numbericCharacters = \"0123456789\";\n std::string::size_type pos = name.find_first_of(invalidCharacters);\n while (pos != std::string::npos)\n {\n name[pos] = '_';\n pos = name.find_first_of(invalidCharacters);\n }\n \n std::string ext = osgDB::getFileExtension(filename);\n std::string cppFileName = osgDB::concatPaths(path, name + \"_\" + ext + \".cpp\");\n std::string variableName = name + \"_\" + ext;\n writeShader(shader.get(), cppFileName, variableName);\n\n return 0;\n }\n else\n {\n std::cout<<\"Error: could not find file '\"<<filename<<\"'\"<<std::endl;\n return 1;\n }\n \n }\n\n std::cout<<\"No appropriate command line options used.\"<<std::endl;\n\n arguments.getApplicationUsage()->write(std::cout);\n return 1;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright lowRISC contributors.\n\/\/ Licensed under the Apache License, Version 2.0, see LICENSE for details.\n\/\/ SPDX-License-Identifier: Apache-2.0\n\n#include \"sv_scoped.h\"\n\n#include <cassert>\n#include <sstream>\n\n\/\/ Set scope by name, returning the old scope. If the name doesn't describe a\n\/\/ valid scope, throw an SVScoped::Error.\nstatic svScope SetAbsScope(const std::string &name) {\n svScope new_scope = svGetScopeFromName(name.c_str());\n if (!new_scope)\n throw SVScoped::Error(name);\n return svSetScope(new_scope);\n}\n\n\/\/ Resolve name to a scope, using the rules described in the comment above the\n\/\/ class in sv_scoped.h, and then set it. Returns the old scope.\nstatic svScope SetRelScope(const std::string &name) {\n \/\/ Absolute (or empty) names resolve to themselves\n if (name[0] != '.') {\n return SetAbsScope(name);\n }\n\n svScope prev_scope = svGetScope();\n\n \/\/ Special case: If name is \".\", it means to use the current scope. Rather\n \/\/ than changing scope, we can just return where we are going to stay.\n if (name == \".\")\n return prev_scope;\n\n \/\/ For anything else, count how many dots appear after the first one (so\n \/\/ ..foo gives an up_count of 1; ...bar gives an up_count of 2).\n size_t first_not_dot = name.find_first_not_of('.', 1);\n if (first_not_dot == std::string::npos) {\n \/\/ name looks like \"....\": that's fine, it just means to go up some number\n \/\/ of steps from the current position and not down again. Amend\n \/\/ first_not_dot to point at the '\\0'.\n first_not_dot = name.size();\n }\n size_t up_count = first_not_dot - 1;\n\n \/\/ Get the name of the current scope, so that we can perform surgery.\n std::string scope_name = svGetNameFromScope(prev_scope);\n\n \/\/ scope_name will look something like \"TOP.foo.bar\". Search up_count\n \/\/ dots from the end, setting last_dot to point at the last dot that should\n \/\/ appear in the resolved name.\n \/\/\n \/\/ If up_count is too large, behave like \"cd \/; cd ..\" and stop at the\n \/\/ left-most dot.\n size_t last_dot = scope_name.size();\n for (size_t i = 0; i < up_count; ++i) {\n \/\/ This shouldn't ever trigger (because it would mean scope_name was\n \/\/ either empty or started with a \".\"), but allowing it makes the code a\n \/\/ bit more uniform.\n if (last_dot == 0)\n break;\n\n size_t dot = scope_name.rfind('.', last_dot - 1);\n if (dot == std::string::npos)\n break;\n\n last_dot = dot;\n }\n\n \/\/ Delete everything from last_dot onwards. If we are actually pointing at a\n \/\/ dot, this will do something like \"TOP.foo.bar\" -> \"TOP.foo\". If up_count\n \/\/ was zero or there were no dots, last_dot will equal the size of the string\n \/\/ (which means, conveniently, that erase is a no-op).\n scope_name.erase(last_dot);\n\n \/\/ If first_not_dot points inside name (so name looked like \"..foo.bar\"\n \/\/ rather than \"...\"), subtract one to point at the last dot of the initial\n \/\/ segment (we know there is one because name[0] == '.') and then append\n \/\/ everything from there to scope_name. For example, if scope_name\n \/\/ was \"TOP.foo.bar.baz\" and name was \"..qux\", we will have just amended\n \/\/ scope_name to be \"TOP.foo.bar\". Now we want to add \".qux\".\n if (first_not_dot < name.size()) {\n scope_name.append(name, first_not_dot - 1);\n }\n\n return SetAbsScope(scope_name);\n}\n\nSVScoped::SVScoped(const std::string &name) : prev_scope_(SetRelScope(name)) {}\n\nSVScoped::Error::Error(const std::string &scope_name)\n : scope_name_(scope_name) {\n std::ostringstream oss;\n oss << \"No such SystemVerilog scope: `\" << scope_name << \"'.\";\n msg_ = oss.str();\n}\n<commit_msg>[otbn] Use relative scope names for OTBN scopes<commit_after>\/\/ Copyright lowRISC contributors.\n\/\/ Licensed under the Apache License, Version 2.0, see LICENSE for details.\n\/\/ SPDX-License-Identifier: Apache-2.0\n\n#include \"sv_scoped.h\"\n\n#include <cassert>\n#include <sstream>\n\n\/\/ Set scope by name, returning the old scope. If the name doesn't describe a\n\/\/ valid scope, throw an SVScoped::Error.\nstatic svScope SetAbsScope(const std::string &name) {\n svScope new_scope = svGetScopeFromName(name.c_str());\n if (!new_scope)\n throw SVScoped::Error(name);\n return svSetScope(new_scope);\n}\n\n\/\/ Resolve name to a scope, using the rules described in the comment above the\n\/\/ class in sv_scoped.h, and then set it. Returns the old scope.\nstatic svScope SetRelScope(const std::string &name) {\n \/\/ Absolute (or empty) names resolve to themselves\n if (name[0] != '.') {\n return SetAbsScope(name);\n }\n\n svScope prev_scope = svGetScope();\n\n \/\/ Special case: If name is \".\", it means to use the current scope. Rather\n \/\/ than changing scope, we can just return where we are going to stay.\n if (name == \".\")\n return prev_scope;\n\n \/\/ For anything else, count how many dots appear after the first one (so\n \/\/ ..foo gives an up_count of 1; ...bar gives an up_count of 2).\n size_t first_not_dot = name.find_first_not_of('.', 1);\n if (first_not_dot == std::string::npos) {\n \/\/ name looks like \"....\": that's fine, it just means to go up some number\n \/\/ of steps from the current position and not down again. Amend\n \/\/ first_not_dot to point at the '\\0'.\n first_not_dot = name.size();\n }\n size_t up_count = first_not_dot - 1;\n\n \/\/ Get the name of the current scope, so that we can perform surgery.\n std::string scope_name = svGetNameFromScope(prev_scope);\n\n \/\/ scope_name will look something like \"TOP.foo.bar\". Search up_count\n \/\/ dots from the end, setting last_dot to point at the last dot that should\n \/\/ appear in the resolved name.\n \/\/\n \/\/ If up_count is too large, behave like \"cd \/; cd ..\" and stop at the\n \/\/ left-most dot.\n size_t last_dot = scope_name.size();\n for (size_t i = 0; i < up_count; ++i) {\n \/\/ This shouldn't ever trigger (because it would mean scope_name was\n \/\/ either empty or started with a \".\"), but allowing it makes the code a\n \/\/ bit more uniform.\n if (last_dot == 0)\n break;\n\n size_t dot = scope_name.rfind('.', last_dot - 1);\n if (dot == std::string::npos)\n break;\n\n last_dot = dot;\n }\n\n \/\/ Delete everything from last_dot onwards. If we are actually pointing at a\n \/\/ dot, this will do something like \"TOP.foo.bar\" -> \"TOP.foo\". If up_count\n \/\/ was zero or there were no dots, last_dot will equal the size of the string\n \/\/ (which means, conveniently, that erase is a no-op).\n scope_name.erase(last_dot);\n\n \/\/ If first_not_dot points inside name (so name looked like \"..foo.bar\"\n \/\/ rather than \"...\"), subtract one to point at the last dot of the initial\n \/\/ segment (we know there is one because name[0] == '.') and then append\n \/\/ everything to scope_name starting from there. For example, if scope_name\n \/\/ was \"TOP.foo.bar.baz\" and name was \"..qux\", we will have just amended\n \/\/ scope_name to be \"TOP.foo.bar\". Now we want to add \".qux\".\n if (first_not_dot < name.size()) {\n scope_name.append(name, first_not_dot - 1, std::string::npos);\n }\n\n return SetAbsScope(scope_name);\n}\n\nSVScoped::SVScoped(const std::string &name) : prev_scope_(SetRelScope(name)) {}\n\nSVScoped::Error::Error(const std::string &scope_name)\n : scope_name_(scope_name) {\n std::ostringstream oss;\n oss << \"No such SystemVerilog scope: `\" << scope_name << \"'.\";\n msg_ = oss.str();\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Time: push: O(logn)\n\/\/ pop: O(logn)\n\/\/ popMax: O(logn)\n\/\/ top: O(1)\n\/\/ peekMax: O(1)\n\/\/ Space: O(n), n is the number of values in the current stack\n\nclass MaxStack {\npublic:\n \/** initialize your data structure here. *\/\n MaxStack() {\n \n }\n \n void push(int x) {\n const auto idx = idx_to_val_.empty() ? 0 : idx_to_val_.begin()->first + 1;\n idx_to_val_[idx] = x;\n val_to_idxs_[x].emplace_back(idx);\n }\n \n int pop() {\n const auto& it = idx_to_val_.begin();\n const auto val = it->second;\n remove(val);\n return val;\n }\n \n int top() {\n return idx_to_val_.begin()->second;\n }\n \n int peekMax() {\n return val_to_idxs_.begin()->first;\n }\n \n int popMax() {\n const auto& it = val_to_idxs_.begin();\n const auto val = it->first;\n remove(val);\n return val;\n }\n\nprivate:\n map<int, int, greater<int>> idx_to_val_;\n map<int, vector<int>, greater<int>> val_to_idxs_;\n \n void remove(const int val) {\n const auto idx = val_to_idxs_[val].back();\n val_to_idxs_[val].pop_back();\n if (val_to_idxs_[val].empty()) {\n val_to_idxs_.erase(val);\n }\n idx_to_val_.erase(idx);\n }\n};\n\n\/**\n * Your MaxStack object will be instantiated and called as such:\n * MaxStack obj = new MaxStack();\n * obj.push(x);\n * int param_2 = obj.pop();\n * int param_3 = obj.top();\n * int param_4 = obj.peekMax();\n * int param_5 = obj.popMax();\n *\/\n<commit_msg>Update max-stack.cpp<commit_after>\/\/ Time: push: O(logn)\n\/\/ pop: O(logn)\n\/\/ popMax: O(logn)\n\/\/ top: O(1)\n\/\/ peekMax: O(1)\n\/\/ Space: O(n), n is the number of values in the current stack\n\nclass MaxStack {\npublic:\n \/** initialize your data structure here. *\/\n MaxStack() {\n \n }\n \n void push(int x) {\n const auto idx = idx_to_val_.empty() ? 0 : idx_to_val_.begin()->first + 1;\n idx_to_val_[idx] = x;\n val_to_idxs_[x].emplace_back(idx);\n }\n \n int pop() {\n const auto val = idx_to_val_.begin()->second;\n remove(val);\n return val;\n }\n \n int top() {\n return idx_to_val_.begin()->second;\n }\n \n int peekMax() {\n return val_to_idxs_.begin()->first;\n }\n \n int popMax() {\n const auto val = val_to_idxs_.begin()->first;\n remove(val);\n return val;\n }\n\nprivate:\n map<int, int, greater<int>> idx_to_val_;\n map<int, vector<int>, greater<int>> val_to_idxs_;\n \n void remove(const int val) {\n const auto idx = val_to_idxs_[val].back();\n val_to_idxs_[val].pop_back();\n if (val_to_idxs_[val].empty()) {\n val_to_idxs_.erase(val);\n }\n idx_to_val_.erase(idx);\n }\n};\n\n\/**\n * Your MaxStack object will be instantiated and called as such:\n * MaxStack obj = new MaxStack();\n * obj.push(x);\n * int param_2 = obj.pop();\n * int param_3 = obj.top();\n * int param_4 = obj.peekMax();\n * int param_5 = obj.popMax();\n *\/\n<|endoftext|>"} {"text":"<commit_before>#include \"initOgre.h\"\n\n#include \"OgreConfigFile.h\"\n#include <OgreMeshSerializer.h>\n\n#ifdef OGRE_PLATFORM_LINUX\n#include <sys\/stat.h>\n#endif\n\ninitOgre::initOgre(){\n\t\tFrameListener = NULL;\n\t\tRoot = NULL;\n\t\tOverlaySystem = NULL;\n\n\t}\ninitOgre::~initOgre()\n{\n\t\/\/delete Root;\n}\n\nint initOgre::start(){\n\n\tOgre::String PluginName;\n\tOgre::String mResourcesCfg;\n\tmResourcesCfg = \"resources.cfg\";\n\n\tRoot = new Ogre::Root(\"\", mResourcesCfg, \"Generator.LOG\");\n\tOverlaySystem = new Ogre::OverlaySystem();\n\n\n#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32\n\tPluginName.append(\"RenderSystem_Direct3D9\");\n#else\n\t\/* Use Posix-function stat to check existence of a file.\n\t * This is needed because Ogre makes zero effort to find its own plugins. *\/\n\tstruct stat statBuf;\n\tOgre::String PluginFile[4];\n\n\tPluginFile[0].append(\"\/usr\/lib\/OGRE\/RenderSystem_GL.so\");\n\tPluginFile[1].append(\"\/usr\/lib\/local\/OGRE\/RenderSystem_GL.so\");\n\t\/\/ Ubuntu\n#ifdef __x86_64__\n\tPluginFile[2].append(\"\/usr\/lib\/x86_64-linux-gnu\/OGRE-\");\n\tPluginFile[3].append(\"\/usr\/lib64\/OGRE\/RenderSystem_GL.so\");\n#elif __i386__\n\tPluginFile[2].append(\"\/usr\/lib\/i386-linux-gnu\/OGRE-\");\n\tPluginFile[3].append(\"\/usr\/lib32\/OGRE\/RenderSystem_GL.so\");\n#endif\n\tPluginFile[2] += Ogre::StringConverter::toString(OGRE_VERSION_MAJOR) + \".\";\n\tPluginFile[2] += Ogre::StringConverter::toString(OGRE_VERSION_MINOR) + \".\";\n\tPluginFile[2] += Ogre::StringConverter::toString(OGRE_VERSION_PATCH);\n\tPluginFile[2] += \"\/RenderSystem_GL.so\";\n\n\tint i;\n\tfor(i=0; i < 4; i++)\n\t{\n\t\tif( stat(PluginFile[i].c_str(), &statBuf) == 0 )\n\t\t{\n\t\t\tPluginFile[i].resize(PluginFile[i].size()-3);\t\/\/ strip \".so\"\n\t\t\tPluginName.assign( PluginFile[i] );\n\t\t\tbreak;\t\t\t\t\t\t\t\t\t\t\t\/\/ Exit loop if file exists\n\t\t}\n\t}\n\tif(PluginName == \"\")\n\t\tOgre::LogManager::getSingleton().logMessage(Ogre::LML_CRITICAL, \"Could not find RenderSystem_GL.so!\");\n#endif\n\n\t\/\/ RenderSystem_GL_d if using Ogre debug mode\n\tif(OGRE_DEBUG_MODE)\n\t\tPluginName.append(\"_d\");\n\t\/\/ Loads renderer plugin\n\tRoot->loadPlugin(PluginName);\n\n\t\/\/Load information from resource.cfg file\n\tOgre::ConfigFile cf;\n\tcf.load(mResourcesCfg);\n\tOgre::String name, locType;\n\tOgre::ConfigFile::SectionIterator secIt = cf.getSectionIterator();\n\twhile (secIt.hasMoreElements()) {\n\t\tOgre::ConfigFile::SettingsMultiMap* settings = secIt.getNext();\n\t\tOgre::ConfigFile::SettingsMultiMap::iterator it;\n\t\tfor (it = settings->begin(); it != settings->end(); ++it) {\n\t\t\tlocType = it->first;\n\t\t\tname = it->second;\n\t\t\tOgre::ResourceGroupManager::getSingleton().addResourceLocation(name, locType, Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);\n\t\t}\n\n\t}\n\n\t\/\/Ogre::ResourceGroupManager::getSingleton().declareResource(\"ram.mesh\", \"Mesh\", Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, Ogre::NameValuePairList());\n\t\/\/Ogre::ResourceGroupManager::getSingleton().declareResource(\"char_ram_col.jpg\", \"Font\", Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, Ogre::NameValuePairList());\n\t\/\/\/\/Ogre::ResourceGroupManager::getSingleton().declareResource(\"char_ram_nor.png\", \"Font\", Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, Ogre::NameValuePairList());\n\t\/\/Ogre::ResourceGroupManager::getSingleton().declareResource(\"ram_skin.material\", \"Material\", Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, Ogre::NameValuePairList());\n\t\/\/Ogre::ResourceGroupManager::getSingleton().declareResource(\"ram_skin_eyelids.material\", \"Material\", Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, Ogre::NameValuePairList());\n\t\/\/Ogre::ResourceGroupManager::getSingleton().declareResource(\"ram_skin_eyes.material\", \"Material\", Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, Ogre::NameValuePairList());\n\t\/\/Ogre::ResourceGroupManager::getSingleton().declareResource(\"ram_skin_horns.material\", \"Material\", Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, Ogre::NameValuePairList());\n\n\t\/\/Ogre::ResourceGroupManager::getSingleton().declareResource(\"asteroid.mesh\", \"Mesh\", Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, Ogre::NameValuePairList());\n\t\/\/Ogre::ResourceGroupManager::getSingleton().declareResource(\"Material.001.material\", \"Material\", Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, Ogre::NameValuePairList());\n\t\/\/Ogre::ResourceGroupManager::getSingleton().declareResource(\"space rock tex 3.jpg\", \"Font\", Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, Ogre::NameValuePairList());\n\n\t\/\/Ogre::TextureManager::getSingleton().setDefaultNumMipmaps(5);\n\tOgre::ResourceGroupManager::getSingleton().initialiseAllResourceGroups();\n\t\/\/Ogre::ResourceGroupManager::getSingleton().initialiseResourceGroup(Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);\n\n\t\/\/ Check renderer availability\n\tconst Ogre::RenderSystemList& RenderSystemList = Root->getAvailableRenderers();\n\tif( RenderSystemList.size() == 0 )\n\t{\n\t\tOgre::LogManager::getSingleton().logMessage(\"Rendersystems not found.\");\n\t\treturn 1;\n\t}\n\tOgre::RenderSystem *RenderSystem = RenderSystemList[0];\n\tRoot->setRenderSystem(RenderSystem);\n\n\n\t\/\/ Do not create window automatically\n\tRoot->initialise(false);\n\n\tOgre::NameValuePairList renderParams;\n\n\trenderParams[\"FSAA\"] = \"0\";\n\trenderParams[\"vsync\"] = \"true\"; \/\/ Waits for vertical sync\n\n\t\/\/ Actual call to create window, bool value is fullscreen flag\n\tWindow = Root->createRenderWindow(\"My little planet\", 800, 600, false, &renderParams);\n\n\n\t\/\/ Start creating scene\n\tScene = Root->createSceneManager(Ogre::ST_GENERIC);\n\tRootSceneNode = Scene->getRootSceneNode();\n\n\tif(OverlaySystem)\n\t\tScene->addRenderQueueListener(OverlaySystem);\n\n\treturn 0;\n}\n\nvoid initOgre::CreateFrameListener(PSphere *pSphere){\n\n#if OGRE_PLATFORM == OGRE_PLATFORM_APPLE_IOS\n\tFrameListener= new GeneratorFrameListener(Window, Camera, true, true, true);\n#else\n\tFrameListener= new GeneratorFrameListener(Window, Camera,pSphere ,Scene , RootSceneNode ,CollisionDetectionManager);\n#endif\n\t\/\/FrameListener->showDebugOverlay(true);\n\tRoot->addFrameListener(FrameListener);\n}\n\nvoid initOgre::setSceneAndRun(PSphere *planet){\n\n\t\/\/ Create camera\n\tCamera = Scene->createCamera(\"VertCamera\");\n\n\t\/\/ Camera position\n\tCamera->setPosition(Ogre::Vector3(0,0,planet->getRadius()*2.65f));\n\tplanet->setObserverPosition(Camera->getPosition());\n\t\/\/ Camera looks toward origo\n\tCamera->lookAt(Ogre::Vector3(0,0,0));\n\n\t\/\/ Create viewport\n\tOgre::Viewport *vp = Window->addViewport(Camera);\n\tvp->setBackgroundColour(Ogre::ColourValue(0,0,0));\n\n\t\/\/ Draw distances\n\tCamera->setNearClipDistance(1.5f);\n\tCamera->setFarClipDistance(3000.0f); \/\/ note to self: do not set if using stencil shadows\n\n\t\/\/ Let there be light\n\tScene->setAmbientLight(Ogre::ColourValue(0.2f, 0.2f, 0.2f));\n\tOgre::Light *light = Scene->createLight( \"PointLight\" );\n\tlight->setDiffuseColour(1.0, 1.0, 1.0);\n\tlight->setSpecularColour(1.0, 1.0, 1.0);\n\tlight->setType(Ogre::Light::LT_POINT);\n\tlight->setPosition(200, 40, 150);\n\n\n\t\/\/ Draw a sphere\n\tplanet->loadToBuffers(\"CustomMesh\", \"sphereTex\");\n\n\t\/\/Export the shape in a mesh file before destroying it\n\t\/\/Ogre::MeshPtr mesh;\n\t\/\/mesh = planet->getMesh();\n\t\/\/Ogre::MeshSerializer ser;\n\t\/\/ser.exportMesh(mesh.getPointer(), \"C:\\\\Users\\\\giova\\\\Documents\\\\PlanetGenerator\\\\planet.mesh\", Ogre::MeshSerializer::ENDIAN_NATIVE);\n\n\n\t\/\/ Attach entitys to sceneNodes\n\tOgre::SceneNode *CameraNode = RootSceneNode->createChildSceneNode(\"DefaultCameraNode\");\n\tCameraNode->attachObject(Camera);\n\n\tOgre::Entity *entity1 = Scene->createEntity(\"CustomEntity\", \"CustomMesh\");\n\tOgre::SceneNode *sphere1 = Scene->getRootSceneNode()->createChildSceneNode(\"planetSphere\");\n\tsphere1->attachObject(entity1);\n\n\n\t\/\/planet->loadMeshFile(\"ram1.mesh\", \"LocalMesh\");\n\n\tplanet->attachMeshOnGround(sphere1, Scene, \"ram.mesh\", \"Ramiro\", 0.0, 270.0);\n\tplanet->attachMesh(sphere1, Scene, \"asteroid.mesh\", \"CK7\", 0.0, 180.0);\n\n\t\/\/ No need for this anymore\n\t\/\/Ogre::MeshManager::getSingleton().remove(\"CustomMesh\");\n\n\tOgre::MaterialPtr textureMap = Ogre::MaterialManager::getSingleton()\n\t\t\t.create(\"TextureObject\",Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);\n\ttextureMap->getTechnique(0)->getPass(0)->createTextureUnitState(\"sphereTex\");\n\ttextureMap->getTechnique(0)->getPass(0)->setSceneBlending(Ogre::SBT_TRANSPARENT_ALPHA);\n\n\t\/\/ Set texture for the sphere\n\tentity1->setMaterial(textureMap);\n\n\tsphere1->setOrientation(1.3003361e-01f, -1.5604560e-01f, -7.5052901e-01f, 6.2884596e-01f);\n\n\t\/\/Collision Manager\n\tCollisionDetectionManager = new CollisionManager(planet->getObjects(),Camera);\n\tplanet->setCollisionManager( CollisionDetectionManager );\n\n\t\/\/createFrameListener\n\tCreateFrameListener(planet);\n\n\t\/\/start Rendering\n\tRoot->startRendering();\n}\n\nvoid initOgre::cleanup(){\n\n\t\/\/ Clean up our mess before exiting\n\tOgre::MaterialManager::getSingleton().remove(\"TextureObject\");\n\tOgre::TextureManager::getSingleton().remove(\"sphereTex\");\n\tScene->destroyEntity(\"CustomEntity\");\n\tScene->destroySceneNode(\"planetSphere\");\n\tScene->destroySceneNode(\"DefaultCameraNode\");\n\tScene->destroyCamera(Camera);\n\tScene->destroyLight(\"PointLight\");\n\tOgre::Root::getSingleton().getRenderSystem()->destroyRenderWindow(\"My little planet\");\n\tScene->clearScene();\n\tRoot->destroySceneManager(Scene);\n\n\tRoot->shutdown();\n\t\n\tdelete FrameListener;\n\tFrameListener = NULL;\n\tdelete OverlaySystem;\n\tOverlaySystem = NULL;\n\tdelete Root;\n\tRoot = NULL;\n\n\t\/\/Ogre::LogManager::getSingleton().logMessage(\"Ogre is cleaned up\");\n}\n<commit_msg>Reorientate planet<commit_after>#include \"initOgre.h\"\n\n#include \"OgreConfigFile.h\"\n#include <OgreMeshSerializer.h>\n\n#ifdef OGRE_PLATFORM_LINUX\n#include <sys\/stat.h>\n#endif\n\ninitOgre::initOgre(){\n\t\tFrameListener = NULL;\n\t\tRoot = NULL;\n\t\tOverlaySystem = NULL;\n\n\t}\ninitOgre::~initOgre()\n{\n\t\/\/delete Root;\n}\n\nint initOgre::start(){\n\n\tOgre::String PluginName;\n\tOgre::String mResourcesCfg;\n\tmResourcesCfg = \"resources.cfg\";\n\n\tRoot = new Ogre::Root(\"\", mResourcesCfg, \"Generator.LOG\");\n\tOverlaySystem = new Ogre::OverlaySystem();\n\n\n#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32\n\tPluginName.append(\"RenderSystem_Direct3D9\");\n#else\n\t\/* Use Posix-function stat to check existence of a file.\n\t * This is needed because Ogre makes zero effort to find its own plugins. *\/\n\tstruct stat statBuf;\n\tOgre::String PluginFile[4];\n\n\tPluginFile[0].append(\"\/usr\/lib\/OGRE\/RenderSystem_GL.so\");\n\tPluginFile[1].append(\"\/usr\/lib\/local\/OGRE\/RenderSystem_GL.so\");\n\t\/\/ Ubuntu\n#ifdef __x86_64__\n\tPluginFile[2].append(\"\/usr\/lib\/x86_64-linux-gnu\/OGRE-\");\n\tPluginFile[3].append(\"\/usr\/lib64\/OGRE\/RenderSystem_GL.so\");\n#elif __i386__\n\tPluginFile[2].append(\"\/usr\/lib\/i386-linux-gnu\/OGRE-\");\n\tPluginFile[3].append(\"\/usr\/lib32\/OGRE\/RenderSystem_GL.so\");\n#endif\n\tPluginFile[2] += Ogre::StringConverter::toString(OGRE_VERSION_MAJOR) + \".\";\n\tPluginFile[2] += Ogre::StringConverter::toString(OGRE_VERSION_MINOR) + \".\";\n\tPluginFile[2] += Ogre::StringConverter::toString(OGRE_VERSION_PATCH);\n\tPluginFile[2] += \"\/RenderSystem_GL.so\";\n\n\tint i;\n\tfor(i=0; i < 4; i++)\n\t{\n\t\tif( stat(PluginFile[i].c_str(), &statBuf) == 0 )\n\t\t{\n\t\t\tPluginFile[i].resize(PluginFile[i].size()-3);\t\/\/ strip \".so\"\n\t\t\tPluginName.assign( PluginFile[i] );\n\t\t\tbreak;\t\t\t\t\t\t\t\t\t\t\t\/\/ Exit loop if file exists\n\t\t}\n\t}\n\tif(PluginName == \"\")\n\t\tOgre::LogManager::getSingleton().logMessage(Ogre::LML_CRITICAL, \"Could not find RenderSystem_GL.so!\");\n#endif\n\n\t\/\/ RenderSystem_GL_d if using Ogre debug mode\n\tif(OGRE_DEBUG_MODE)\n\t\tPluginName.append(\"_d\");\n\t\/\/ Loads renderer plugin\n\tRoot->loadPlugin(PluginName);\n\n\t\/\/Load information from resource.cfg file\n\tOgre::ConfigFile cf;\n\tcf.load(mResourcesCfg);\n\tOgre::String name, locType;\n\tOgre::ConfigFile::SectionIterator secIt = cf.getSectionIterator();\n\twhile (secIt.hasMoreElements()) {\n\t\tOgre::ConfigFile::SettingsMultiMap* settings = secIt.getNext();\n\t\tOgre::ConfigFile::SettingsMultiMap::iterator it;\n\t\tfor (it = settings->begin(); it != settings->end(); ++it) {\n\t\t\tlocType = it->first;\n\t\t\tname = it->second;\n\t\t\tOgre::ResourceGroupManager::getSingleton().addResourceLocation(name, locType, Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);\n\t\t}\n\n\t}\n\n\t\/\/Ogre::ResourceGroupManager::getSingleton().declareResource(\"ram.mesh\", \"Mesh\", Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, Ogre::NameValuePairList());\n\t\/\/Ogre::ResourceGroupManager::getSingleton().declareResource(\"char_ram_col.jpg\", \"Font\", Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, Ogre::NameValuePairList());\n\t\/\/\/\/Ogre::ResourceGroupManager::getSingleton().declareResource(\"char_ram_nor.png\", \"Font\", Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, Ogre::NameValuePairList());\n\t\/\/Ogre::ResourceGroupManager::getSingleton().declareResource(\"ram_skin.material\", \"Material\", Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, Ogre::NameValuePairList());\n\t\/\/Ogre::ResourceGroupManager::getSingleton().declareResource(\"ram_skin_eyelids.material\", \"Material\", Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, Ogre::NameValuePairList());\n\t\/\/Ogre::ResourceGroupManager::getSingleton().declareResource(\"ram_skin_eyes.material\", \"Material\", Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, Ogre::NameValuePairList());\n\t\/\/Ogre::ResourceGroupManager::getSingleton().declareResource(\"ram_skin_horns.material\", \"Material\", Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, Ogre::NameValuePairList());\n\n\t\/\/Ogre::ResourceGroupManager::getSingleton().declareResource(\"asteroid.mesh\", \"Mesh\", Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, Ogre::NameValuePairList());\n\t\/\/Ogre::ResourceGroupManager::getSingleton().declareResource(\"Material.001.material\", \"Material\", Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, Ogre::NameValuePairList());\n\t\/\/Ogre::ResourceGroupManager::getSingleton().declareResource(\"space rock tex 3.jpg\", \"Font\", Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, Ogre::NameValuePairList());\n\n\t\/\/Ogre::TextureManager::getSingleton().setDefaultNumMipmaps(5);\n\tOgre::ResourceGroupManager::getSingleton().initialiseAllResourceGroups();\n\t\/\/Ogre::ResourceGroupManager::getSingleton().initialiseResourceGroup(Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);\n\n\t\/\/ Check renderer availability\n\tconst Ogre::RenderSystemList& RenderSystemList = Root->getAvailableRenderers();\n\tif( RenderSystemList.size() == 0 )\n\t{\n\t\tOgre::LogManager::getSingleton().logMessage(\"Rendersystems not found.\");\n\t\treturn 1;\n\t}\n\tOgre::RenderSystem *RenderSystem = RenderSystemList[0];\n\tRoot->setRenderSystem(RenderSystem);\n\n\n\t\/\/ Do not create window automatically\n\tRoot->initialise(false);\n\n\tOgre::NameValuePairList renderParams;\n\n\trenderParams[\"FSAA\"] = \"0\";\n\trenderParams[\"vsync\"] = \"true\"; \/\/ Waits for vertical sync\n\n\t\/\/ Actual call to create window, bool value is fullscreen flag\n\tWindow = Root->createRenderWindow(\"My little planet\", 800, 600, false, &renderParams);\n\n\n\t\/\/ Start creating scene\n\tScene = Root->createSceneManager(Ogre::ST_GENERIC);\n\tRootSceneNode = Scene->getRootSceneNode();\n\n\tif(OverlaySystem)\n\t\tScene->addRenderQueueListener(OverlaySystem);\n\n\treturn 0;\n}\n\nvoid initOgre::CreateFrameListener(PSphere *pSphere){\n\n#if OGRE_PLATFORM == OGRE_PLATFORM_APPLE_IOS\n\tFrameListener= new GeneratorFrameListener(Window, Camera, true, true, true);\n#else\n\tFrameListener= new GeneratorFrameListener(Window, Camera,pSphere ,Scene , RootSceneNode ,CollisionDetectionManager);\n#endif\n\t\/\/FrameListener->showDebugOverlay(true);\n\tRoot->addFrameListener(FrameListener);\n}\n\nvoid initOgre::setSceneAndRun(PSphere *planet){\n\n\t\/\/ Create camera\n\tCamera = Scene->createCamera(\"VertCamera\");\n\n\t\/\/ Camera position\n\tCamera->setPosition(Ogre::Vector3(0,0,planet->getRadius()*2.65f));\n\tplanet->setObserverPosition(Camera->getPosition());\n\t\/\/ Camera looks toward origo\n\tCamera->lookAt(Ogre::Vector3(0,0,0));\n\n\t\/\/ Create viewport\n\tOgre::Viewport *vp = Window->addViewport(Camera);\n\tvp->setBackgroundColour(Ogre::ColourValue(0,0,0));\n\n\t\/\/ Draw distances\n\tCamera->setNearClipDistance(1.5f);\n\tCamera->setFarClipDistance(3000.0f); \/\/ note to self: do not set if using stencil shadows\n\n\t\/\/ Let there be light\n\tScene->setAmbientLight(Ogre::ColourValue(0.2f, 0.2f, 0.2f));\n\tOgre::Light *light = Scene->createLight( \"PointLight\" );\n\tlight->setDiffuseColour(1.0, 1.0, 1.0);\n\tlight->setSpecularColour(1.0, 1.0, 1.0);\n\tlight->setType(Ogre::Light::LT_POINT);\n\tlight->setPosition(200, 40, 150);\n\n\n\t\/\/ Draw a sphere\n\tplanet->loadToBuffers(\"CustomMesh\", \"sphereTex\");\n\n\t\/\/Export the shape in a mesh file before destroying it\n\t\/\/Ogre::MeshPtr mesh;\n\t\/\/mesh = planet->getMesh();\n\t\/\/Ogre::MeshSerializer ser;\n\t\/\/ser.exportMesh(mesh.getPointer(), \"C:\\\\Users\\\\giova\\\\Documents\\\\PlanetGenerator\\\\planet.mesh\", Ogre::MeshSerializer::ENDIAN_NATIVE);\n\n\n\t\/\/ Attach entitys to sceneNodes\n\tOgre::SceneNode *CameraNode = RootSceneNode->createChildSceneNode(\"DefaultCameraNode\");\n\tCameraNode->attachObject(Camera);\n\n\tOgre::Entity *entity1 = Scene->createEntity(\"CustomEntity\", \"CustomMesh\");\n\tOgre::SceneNode *sphere1 = Scene->getRootSceneNode()->createChildSceneNode(\"planetSphere\");\n\tsphere1->attachObject(entity1);\n\n\n\t\/\/planet->loadMeshFile(\"ram1.mesh\", \"LocalMesh\");\n\n\tplanet->attachMeshOnGround(sphere1, Scene, \"ram.mesh\", \"Ramiro\", 0.0, 270.0);\n\tplanet->attachMesh(sphere1, Scene, \"asteroid.mesh\", \"CK7\", 0.0, 180.0);\n\n\t\/\/ No need for this anymore\n\t\/\/Ogre::MeshManager::getSingleton().remove(\"CustomMesh\");\n\n\tOgre::MaterialPtr textureMap = Ogre::MaterialManager::getSingleton()\n\t\t\t.create(\"TextureObject\",Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);\n\ttextureMap->getTechnique(0)->getPass(0)->createTextureUnitState(\"sphereTex\");\n\ttextureMap->getTechnique(0)->getPass(0)->setSceneBlending(Ogre::SBT_TRANSPARENT_ALPHA);\n\n\t\/\/ Set texture for the sphere\n\tentity1->setMaterial(textureMap);\n\n\tsphere1->setOrientation(0.163149834f, -0.19578641f, -0.314332321f, -0.9144643269f);\n\n\t\/\/Collision Manager\n\tCollisionDetectionManager = new CollisionManager(planet->getObjects(),Camera);\n\tplanet->setCollisionManager( CollisionDetectionManager );\n\n\t\/\/createFrameListener\n\tCreateFrameListener(planet);\n\n\t\/\/start Rendering\n\tRoot->startRendering();\n}\n\nvoid initOgre::cleanup(){\n\n\t\/\/ Clean up our mess before exiting\n\tOgre::MaterialManager::getSingleton().remove(\"TextureObject\");\n\tOgre::TextureManager::getSingleton().remove(\"sphereTex\");\n\tScene->destroyEntity(\"CustomEntity\");\n\tScene->destroySceneNode(\"planetSphere\");\n\tScene->destroySceneNode(\"DefaultCameraNode\");\n\tScene->destroyCamera(Camera);\n\tScene->destroyLight(\"PointLight\");\n\tOgre::Root::getSingleton().getRenderSystem()->destroyRenderWindow(\"My little planet\");\n\tScene->clearScene();\n\tRoot->destroySceneManager(Scene);\n\n\tRoot->shutdown();\n\t\n\tdelete FrameListener;\n\tFrameListener = NULL;\n\tdelete OverlaySystem;\n\tOverlaySystem = NULL;\n\tdelete Root;\n\tRoot = NULL;\n\n\t\/\/Ogre::LogManager::getSingleton().logMessage(\"Ogre is cleaned up\");\n}\n<|endoftext|>"} {"text":"<commit_before>#include <mutex>\n#include <stdint.h>\n#include <iostream>\n#include <condition_variable>\n#include \"protocol.h\"\n#include \"RCSwitch.h\"\n\n\/\/ The RF device data pin\n#define RF_DEVICE_COMM_PIN 2\n\nstd::mutex m;\nstd::condition_variable cv;\n\nvoid transmissionHandler() {\n \/\/ A signal is being received, wake up program\n cv.notify_all();\n}\n\nint init(RCSwitch& rfSwitch, int pulseLength) {\n \/\/ Init wiring PI\n if(wiringPiSetup() == -1) {\n std::cerr << \"wiringPiSetup failed, exiting...\" << std::endl;\n return 1;\n }\n \/\/ Init RF Switch\n if (pulseLength != 0) rfSwitch.setPulseLength(pulseLength);\n rfSwitch.enableReceive(RF_DEVICE_COMM_PIN); \/\/ Receiver on interrupt 0 => that is pin #2\n std::cout << \"listening...\" << std::endl;\n rfSwitch.registerCustomInterruptHandler(transmissionHandler);\n}\n\nvoid processPacket(packet_s packet) {\n std::cout << \"sensor type: \" << (int) packet.stype <<\n \", sensor id: \" << (int) packet.sid <<\n \", message: \" << (int) packet.message << std::endl;\n\n}\n\nvoid receiveMessage(RCSwitch& rfSwitch) {\n bool receiving_first = true;\n uint64_t previous_value = 0;\n uint64_t value = 0;\n packet_t raw_packet = 0;\n while(1) {\n std::unique_lock<std::mutex> lk(m);\n cv.wait(lk);\n\n if (rfSwitch.available()) {\n value = rfSwitch.getReceivedValue();\n rfSwitch.resetAvailable();\n if (value == previous_value)\n continue; \/\/ If we receive the same value, this is just a repeat\n previous_value = value;\n raw_packet |= value;\n \/\/ If we are receiving the first part of the packet, shift the value by\n \/\/ 32 to let room for the second half\n if (receiving_first) {\n raw_packet <<= 32;\n receiving_first = false;\n } else {\n \/\/ We received the second part, process it\n packet_s packet;\n int ret = read_packet(raw_packet, &packet);\n if (ret == WRONG_MAGIC_ERROR) {\n std::cout << \"DEBUG: Wrong magic number, dismiss message\" << std::endl;\n continue;\n } else if (ret == PARITY_ERROR) {\n std::cerr << \"ERROR: Parity error in message, tread lightly\" << std::endl;\n }\n processPacket(packet);\n receiving_first = true;\n raw_packet = 0;\n value = 0;\n }\n }\n }\n}\n\nint main(int argc, char **argv) {\n RCSwitch rfSwitch;\n\n if (argv[1] != NULL) {\n int retcode = 0;\n if ((retcode = init(rfSwitch, atoi(argv[1]))) != 0);\n return retcode;\n }\n\n receiveMessage(rfSwitch);\n\n return 0;\n}\n\n\n<commit_msg>Couple of fix.<commit_after>#include <mutex>\n#include <stdint.h>\n#include <iostream>\n#include <condition_variable>\n#include \"protocol.h\"\n#include \"RCSwitch.h\"\n\n\/\/ The RF device data pin\n#define RF_DEVICE_COMM_PIN 27\n\nstd::mutex m;\nstd::condition_variable cv;\n\nvoid transmissionHandler() {\n \/\/ A signal is being received, wake up program\n cv.notify_all();\n}\n\nint init(RCSwitch& rfSwitch, int pulseLength) {\n \/\/ Init wiring PI\n if(wiringPiSetupSys() == -1) {\n std::cerr << \"wiringPiSetup failed, exiting...\" << std::endl;\n return 1;\n }\n \/\/ Init RF Switch\n if (pulseLength != 0) rfSwitch.setPulseLength(pulseLength);\n rfSwitch.enableReceive(RF_DEVICE_COMM_PIN); \/\/ Receiver on interrupt 0 => that is pin #2\n rfSwitch.registerCustomInterruptHandler(transmissionHandler);\n return 0;\n}\n\nvoid processPacket(packet_s packet) {\n std::cout << \"sensor type: \" << (int) packet.stype <<\n \", sensor id: \" << (int) packet.sid <<\n \", message: \" << (int) packet.message << std::endl;\n\n}\n\nvoid receiveMessage(RCSwitch& rfSwitch) {\n bool receiving_first = true;\n uint64_t previous_value = 0;\n uint64_t value = 0;\n packet_t raw_packet = 0;\n std::cout << \"listening...\" << std::endl;\n while(1) {\n std::unique_lock<std::mutex> lk(m);\n cv.wait(lk);\n\n if (rfSwitch.available()) {\n value = rfSwitch.getReceivedValue();\n \/\/ std::cout << value << std::endl;\n rfSwitch.resetAvailable();\n if (value == previous_value)\n continue; \/\/ If we receive the same value, this is just a repeat\n previous_value = value;\n raw_packet |= value;\n \/\/ If we are receiving the first part of the packet, shift the value by\n \/\/ 32 to let room for the second half\n if (receiving_first) {\n raw_packet <<= 32;\n receiving_first = false;\n } else {\n \/\/ We received the second part, process it\n packet_s packet;\n int ret = read_packet(raw_packet, &packet);\n if (ret == WRONG_MAGIC_ERROR) {\n std::cout << \"DEBUG: Wrong magic number, dismiss message\" << std::endl;\n continue;\n } else if (ret == PARITY_ERROR) {\n std::cerr << \"ERROR: Parity error in message, tread lightly\" << std::endl;\n }\n processPacket(packet);\n receiving_first = true;\n raw_packet = 0;\n value = 0;\n }\n }\n }\n}\n\nint main(int argc, char **argv) {\n RCSwitch rfSwitch;\n\n int retcode;\n if ((retcode = init(rfSwitch, 0)) != 0) {\n std::cout << \"Initialization failed with \" << retcode << std::endl;\n return retcode;\n }\n\n receiveMessage(rfSwitch);\n\n return 0;\n}\n\n\n<|endoftext|>"} {"text":"<commit_before>#pragma once\n\n#include <agency\/detail\/config.hpp>\n#include <agency\/detail\/index_cast.hpp>\n#include <agency\/detail\/shape_cast.hpp>\n#include <agency\/detail\/swap.hpp>\n#include <agency\/detail\/memory\/allocator_traits.hpp>\n#include <utility>\n#include <memory>\n\nnamespace agency\n{\nnamespace detail\n{\n\n\ntemplate<class T, class Shape = size_t, class Alloc = std::allocator<T>, class Index = Shape>\nclass array\n{\n public:\n using value_type = T;\n\n using allocator_type = typename std::allocator_traits<Alloc>::template rebind_alloc<value_type>;\n\n using pointer = typename std::allocator_traits<allocator_type>::pointer;\n\n using const_pointer = typename std::allocator_traits<allocator_type>::const_pointer;\n\n using shape_type = Shape;\n\n using index_type = Index;\n\n \/\/ note that array's constructors have __agency_hd_warning_disable__\n \/\/ because Alloc's constructors may not have __AGENCY_ANNOTATION\n\n __agency_hd_warning_disable__\n __AGENCY_ANNOTATION\n array() : alloc_{}, shape_{}, data_(nullptr) {}\n\n __agency_hd_warning_disable__\n __AGENCY_ANNOTATION\n explicit array(const shape_type& shape, const allocator_type& alloc = allocator_type())\n : alloc_(allocator_type()),\n shape_(shape),\n data_(allocate_and_construct_elements(alloc_, size()))\n {\n }\n\n __agency_hd_warning_disable__\n __AGENCY_ANNOTATION\n explicit array(const shape_type& shape, const T& val, const allocator_type& alloc = allocator_type())\n : alloc_(alloc),\n shape_(shape),\n data_(allocate_and_construct_elements(alloc_, size(), val))\n {\n }\n\n __agency_hd_warning_disable__\n template<class Iterator,\n class = typename std::enable_if<\n !std::is_convertible<Iterator,shape_type>::value\n >::type>\n __AGENCY_ANNOTATION\n array(Iterator first, Iterator last)\n : array(shape_cast<shape_type>(last - first))\n {\n for(auto result = begin(); result != end(); ++result, ++first)\n {\n *result = *first;\n }\n }\n\n __agency_hd_warning_disable__\n __AGENCY_ANNOTATION\n array(const array& other)\n : array(other.shape())\n {\n auto iter = other.begin();\n auto result = begin();\n\n for(; iter != other.end(); ++iter, ++result)\n {\n *result = *iter;\n }\n }\n\n __agency_hd_warning_disable__\n __AGENCY_ANNOTATION\n array(array&& other)\n : alloc_{}, shape_{}, data_{}\n {\n swap(other);\n }\n\n __AGENCY_ANNOTATION\n ~array()\n {\n clear();\n }\n\n __AGENCY_ANNOTATION\n array& operator=(const array& other)\n {\n \/\/ XXX this is not a very efficient implementation\n array tmp = other;\n swap(tmp);\n return *this;\n }\n\n __AGENCY_ANNOTATION\n array& operator=(array&& other)\n {\n swap(other);\n return *this;\n }\n\n __AGENCY_ANNOTATION\n void swap(array& other)\n {\n agency::detail::swap(shape_, other.shape_);\n agency::detail::swap(data_, other.data_);\n }\n\n __AGENCY_ANNOTATION\n value_type& operator[](index_type idx)\n {\n std::size_t idx_1d = agency::detail::index_cast<std::size_t>(idx, shape(), size());\n\n return data_[idx_1d];\n }\n\n __AGENCY_ANNOTATION\n shape_type shape() const\n {\n return shape_;\n }\n\n __AGENCY_ANNOTATION\n std::size_t size() const\n {\n return agency::detail::shape_cast<std::size_t>(shape_);\n }\n\n __AGENCY_ANNOTATION\n pointer data()\n {\n return data_;\n }\n\n __AGENCY_ANNOTATION\n const_pointer data() const\n {\n return data_;\n }\n\n __AGENCY_ANNOTATION\n pointer begin()\n {\n return data();\n }\n\n __AGENCY_ANNOTATION\n pointer end()\n {\n return begin() + size();\n }\n\n __AGENCY_ANNOTATION\n const_pointer begin() const\n {\n return data();\n }\n\n __AGENCY_ANNOTATION\n const_pointer cbegin() const\n {\n return begin();\n }\n\n __AGENCY_ANNOTATION\n const_pointer end() const\n {\n return begin() + size();\n }\n\n __AGENCY_ANNOTATION\n const_pointer cend() const\n {\n return end();\n }\n\n __agency_hd_warning_disable__\n __AGENCY_ANNOTATION\n void clear()\n {\n if(size())\n {\n \/\/ XXX should really destroy through the allocator\n for(auto& x : *this)\n {\n x.~value_type();\n }\n\n alloc_.deallocate(data_, size());\n\n shape_ = shape_type{};\n }\n }\n\n __agency_hd_warning_disable__\n template<class Range>\n __AGENCY_ANNOTATION\n bool operator==(const Range& rhs) const\n {\n auto i = begin();\n auto j = rhs.begin();\n\n for(; i != end(); ++i, ++j)\n {\n if(*i != *j)\n {\n return false;\n }\n }\n\n return true;\n }\n\n private:\n __agency_hd_warning_disable__\n template<class... Args>\n __AGENCY_ANNOTATION\n static pointer allocate_and_construct_elements(allocator_type& alloc, size_t size, Args&&... args)\n {\n pointer result = alloc.allocate(size);\n\n allocator_traits<allocator_type>::construct_each(alloc, result, result + size, std::forward<Args>(args)...);\n\n return result;\n }\n\n allocator_type alloc_;\n\n shape_type shape_;\n\n pointer data_;\n};\n\n\n} \/\/ end detail\n} \/\/ end agency\n\n<commit_msg>Add __agency_hd_warning_disable__ to array's destructor<commit_after>#pragma once\n\n#include <agency\/detail\/config.hpp>\n#include <agency\/detail\/index_cast.hpp>\n#include <agency\/detail\/shape_cast.hpp>\n#include <agency\/detail\/swap.hpp>\n#include <agency\/detail\/memory\/allocator_traits.hpp>\n#include <utility>\n#include <memory>\n\nnamespace agency\n{\nnamespace detail\n{\n\n\ntemplate<class T, class Shape = size_t, class Alloc = std::allocator<T>, class Index = Shape>\nclass array\n{\n public:\n using value_type = T;\n\n using allocator_type = typename std::allocator_traits<Alloc>::template rebind_alloc<value_type>;\n\n using pointer = typename std::allocator_traits<allocator_type>::pointer;\n\n using const_pointer = typename std::allocator_traits<allocator_type>::const_pointer;\n\n using shape_type = Shape;\n\n using index_type = Index;\n\n \/\/ note that array's constructors have __agency_hd_warning_disable__\n \/\/ because Alloc's constructors may not have __AGENCY_ANNOTATION\n\n __agency_hd_warning_disable__\n __AGENCY_ANNOTATION\n array() : alloc_{}, shape_{}, data_(nullptr) {}\n\n __agency_hd_warning_disable__\n __AGENCY_ANNOTATION\n explicit array(const shape_type& shape, const allocator_type& alloc = allocator_type())\n : alloc_(allocator_type()),\n shape_(shape),\n data_(allocate_and_construct_elements(alloc_, size()))\n {\n }\n\n __agency_hd_warning_disable__\n __AGENCY_ANNOTATION\n explicit array(const shape_type& shape, const T& val, const allocator_type& alloc = allocator_type())\n : alloc_(alloc),\n shape_(shape),\n data_(allocate_and_construct_elements(alloc_, size(), val))\n {\n }\n\n __agency_hd_warning_disable__\n template<class Iterator,\n class = typename std::enable_if<\n !std::is_convertible<Iterator,shape_type>::value\n >::type>\n __AGENCY_ANNOTATION\n array(Iterator first, Iterator last)\n : array(shape_cast<shape_type>(last - first))\n {\n for(auto result = begin(); result != end(); ++result, ++first)\n {\n *result = *first;\n }\n }\n\n __agency_hd_warning_disable__\n __AGENCY_ANNOTATION\n array(const array& other)\n : array(other.shape())\n {\n auto iter = other.begin();\n auto result = begin();\n\n for(; iter != other.end(); ++iter, ++result)\n {\n *result = *iter;\n }\n }\n\n __agency_hd_warning_disable__\n __AGENCY_ANNOTATION\n array(array&& other)\n : alloc_{}, shape_{}, data_{}\n {\n swap(other);\n }\n\n __agency_hd_warning_disable__\n __AGENCY_ANNOTATION\n ~array()\n {\n clear();\n }\n\n __AGENCY_ANNOTATION\n array& operator=(const array& other)\n {\n \/\/ XXX this is not a very efficient implementation\n array tmp = other;\n swap(tmp);\n return *this;\n }\n\n __AGENCY_ANNOTATION\n array& operator=(array&& other)\n {\n swap(other);\n return *this;\n }\n\n __AGENCY_ANNOTATION\n void swap(array& other)\n {\n agency::detail::swap(shape_, other.shape_);\n agency::detail::swap(data_, other.data_);\n }\n\n __AGENCY_ANNOTATION\n value_type& operator[](index_type idx)\n {\n std::size_t idx_1d = agency::detail::index_cast<std::size_t>(idx, shape(), size());\n\n return data_[idx_1d];\n }\n\n __AGENCY_ANNOTATION\n shape_type shape() const\n {\n return shape_;\n }\n\n __AGENCY_ANNOTATION\n std::size_t size() const\n {\n return agency::detail::shape_cast<std::size_t>(shape_);\n }\n\n __AGENCY_ANNOTATION\n pointer data()\n {\n return data_;\n }\n\n __AGENCY_ANNOTATION\n const_pointer data() const\n {\n return data_;\n }\n\n __AGENCY_ANNOTATION\n pointer begin()\n {\n return data();\n }\n\n __AGENCY_ANNOTATION\n pointer end()\n {\n return begin() + size();\n }\n\n __AGENCY_ANNOTATION\n const_pointer begin() const\n {\n return data();\n }\n\n __AGENCY_ANNOTATION\n const_pointer cbegin() const\n {\n return begin();\n }\n\n __AGENCY_ANNOTATION\n const_pointer end() const\n {\n return begin() + size();\n }\n\n __AGENCY_ANNOTATION\n const_pointer cend() const\n {\n return end();\n }\n\n __agency_hd_warning_disable__\n __AGENCY_ANNOTATION\n void clear()\n {\n if(size())\n {\n \/\/ XXX should really destroy through the allocator\n for(auto& x : *this)\n {\n x.~value_type();\n }\n\n alloc_.deallocate(data_, size());\n\n shape_ = shape_type{};\n }\n }\n\n __agency_hd_warning_disable__\n template<class Range>\n __AGENCY_ANNOTATION\n bool operator==(const Range& rhs) const\n {\n auto i = begin();\n auto j = rhs.begin();\n\n for(; i != end(); ++i, ++j)\n {\n if(*i != *j)\n {\n return false;\n }\n }\n\n return true;\n }\n\n private:\n __agency_hd_warning_disable__\n template<class... Args>\n __AGENCY_ANNOTATION\n static pointer allocate_and_construct_elements(allocator_type& alloc, size_t size, Args&&... args)\n {\n pointer result = alloc.allocate(size);\n\n allocator_traits<allocator_type>::construct_each(alloc, result, result + size, std::forward<Args>(args)...);\n\n return result;\n }\n\n allocator_type alloc_;\n\n shape_type shape_;\n\n pointer data_;\n};\n\n\n} \/\/ end detail\n} \/\/ end agency\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n * lanczosSO.hpp\n *\n * Created on: Mar 3, 2015\n * Author: hugo\n *\/\n\n#ifndef ALGORITHM_LANCZOSSO_HPP_\n#define ALGORITHM_LANCZOSSO_HPP_\n\n#include <string>\n\n#include \"..\/core\/matrix.hpp\"\n#include \"..\/Eigen\/Dense\"\n\nusing namespace std;\n\nnamespace mflash{\n\n\tclass LancsosSO{\n\t\t\tMatrix<float, EmptyType> *matrix;\n\t\t\tint iterations;\n\t\t\tint k;\n\n\t\tpublic:\n\t\t\tvoid run();\n\t};\n\n\tvoid LancsosSO::run(){\n\t\tstring path = mflash::get_parent_directory(matrix->get_file());\n\n\t\tconst int64 block_size = matrix->get_elements_by_block();\n\n\n\n\t}\n\n}\n\n#endif \/* ALGORITHM_LANCZOSSO_HPP_ *\/\n<commit_msg>Lanczos Implementation using double without rit vectors<commit_after>\/*\n * lanczosSO.hpp\n *\n * Created on: Mar 3, 2015\n * Author: hugo\n *\/\n\n#ifndef ALGORITHM_LANCZOSSO_HPP_\n#define ALGORITHM_LANCZOSSO_HPP_\n\n#include <string>\n#include <cmath>\n#include \"..\/core\/matrix.hpp\"\n#include \"..\/core\/primitivevector.hpp\"\n\n#include \"..\/Eigen\/Dense\"\n\n#include \"..\/log\/easylogging++.h\"\n\nusing namespace std;\n\nnamespace mflash{\n\n\tclass LanczosSO{\n\t\t\tPrimitiveMatrix<double, EmptyType> *matrix;\n\t\t\tint iterations;\n\t\t\tint k;\n\n\t\t\tEigen::Matrix build_tridiagonal_matrix(int m, double alpha [], double beta[]);\n\n\t\tpublic:\n\t\t\tvoid run();\n\t};\n\n\tvoid LanczosSO::run(){\n\t\tstring path = mflash::get_parent_directory(matrix->get_file()) + FILE_SEPARATOR;\n\t\tstring v_file = path + \"v.bin\";\n\t\t\/\/string v_tmp = path + FILE_SEPARATOR + \"tmp.bin\";\n\t\tstring r_file = path + \"r.bin\";\n\n\t\tconst int64 block_size = matrix->get_elements_by_block();\n\t\tconst int64 node_count = matrix->size();\n\n\t\tdouble epsilon = sqrt(1E-18);\n\t\tdouble beta[] = new double[iterations];\n\t\tdouble alpha[] = new double[iterations];\n\n\t\t\/\/orthogonal vectors v\n\t\tPrimitiveVector<double> *vectors[] = new PrimitiveVector<double>*[iterations];\n\t\tPrimitiveVector<double> v (v_file, node_count, block_size);\n\t\tPrimitiveVector<double> r (r_file, node_count, block_size);\n\n\t\tLOG (INFO) << \"1: initial values\";\n\t\tvectors[0] = new PrimitiveVector<double> ( path + \"v0\", node_count, block_size );\n\t\tvectors[0]->fill_random();\n\t\tvectors[0]->multiply(((double)1\/vectors[0]->pnorm(2)));\n\n\t\tfor (int i = 0; i < iterations; i++){\n\t\t\t\tLOG (INFO) << \"3: Find a new basis vector\";\n\t\t\t\tmatrix->multiply( *(vectors[i]), v);\n\n\t\t\t\tLOG (INFO) << \"4:\";\n\t\t\t\talpha[i] = vectors[i]->transpose().multiply(v);\n\n\t\t\t\tLOG (INFO) << \"5: v = v - beta[i-1]V[i-1] - alpha[i]V[i]\";\n\t\t\t\tif(i>0){\n\t\t\t\t\t\tv.linear_combination(3, new double[3]{1, -1*beta[i-1], -1*alpha[i]}, new PrimitiveVector<double>*[3]{&v, vectors[i-1], vectors[i]});\n\t\t\t\t}else{\n\t\t\t\t\t\tv.linear_combination(2, new double[2]{1, -1*alpha[i]}, new PrimitiveVector<double>*[2]{&v, vectors[i]});\n\t\t\t\t}\n\n\t\t\t\tLOG (INFO) << \"6: beta[i] = ||v||\";\n\t\t\t\tbeta[i] = v.pnorm(2);\n\n\t\t\t\tLOG (INFO) << \"7: build tri-diagonal matrix from alpha and beta\";\n\t\t\t\tEigen::Matrix<double, i+1, i+1> ti = build_tridiagonal_matrix(i+1, alpha, beta);\n\n\t\t\t\tLOG (INFO) << \"8: \";\n\t\t\t\tEigen::SelfAdjointEigenSolver<Eigen::Matrix<double,i+1,i+1> > eigensolver(ti);\n\t\t\t\tEigen::Matrix<double, i+1, 1> evalues = eigensolver.eigenvalues();\n\t\t\t\tEigen::Matrix<double, i+1, i+1> q = eigensolver.eigenvectors();\n\n\t\t\t\tLOG (INFO) << \"Iteration \" << i << \", EigenValues: \";\n\t\t\t\tLOG (INFO) << evalues;\n\n\t\t\t\tEigen::Matrix<double, i+1, 1> mtmp = alpha;\n\t\t\t\tLOG (INFO) << \"Alphas: \";\n\t\t\t\tLOG (INFO) << mtmp;\n\t\t\t\tmtmp = beta;\n\t\t\t\tLOG (INFO) << \"Betas: \";\n\t\t\t\tLOG (INFO) << mtmp;\n\n\t\t\t\t\/\/Max singular value\n\t\t\t\tdouble max_sv = abs((double)evalues[0]);\n\t\t\t\tfor (int i = 1; i <= i; i++){\n\t\t\t\t\t\tmax_sv = max(max_sv, abs((double)evalues[i]));\n\t\t\t\t}\n\t\t\t\tLOG (INFO) << \"Max Singular Value = \" << max_sv;\n\n\t\t\t\tbool so = false;\n\n\t\t\t\tLOG (INFO) << \"9: Reorthogonalization\";\n\t\t\t\tfor (int j = 0; j <= i; j++){\n\t\t\t\t\t\tif (beta[i] * abs((double) q[i][j]) <= epsilon * max_sv){\n\t\t\t\t\t\t\t LOG (INFO) << \"Reorthogonalization for ritz vector = \"<< j;\n\n\t\t\t\t\t\t\t double constants [] = new double[i+1];\n\t\t\t\t\t\t\t for ( int k = 0; k < i+1; k++ ){\n\t\t\t\t\t\t\t\t\t constants[k] = (double)q[k,j];\n\t\t\t\t\t\t\t }\n\t\t\t\t\t\t\t r.linear_combination(i+1, constants, vectors);\n\t\t\t\t\t\t\t \/\/-(r*v)\n\t\t\t\t\t\t\t double constant = -1 * r.transpose().multiply(v);\n\t\t\t\t\t\t\t \/\/v=v-(r*v)r\n\t\t\t\t\t\t\t v.linear_combination(2, new double[2]{1, constant}, new PrimitiveVector<double>*[2]{&v, &r});\n\t\t\t\t\t\t\t so = true;\n\t\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tLOG (INFO) << \"15:\";\n\t\t\t\tif ( so ){\n\t\t\t\t\t\tLOG (INFO) << \"16: Recompute normalization constant beta[\"<< i <<\"]\";\n\t\t\t\t\t\tbeta[i] = v.pnorm(2);\n\t\t\t\t}\n\n\t\t\t\tLOG (INFO) << \"18:\";\n\t\t\t\tif ( beta[i] == 0){\n\t\t\t\t\t\titerations = i+1;\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\tif ( i < iterations-1 ){\n\t\t\t\t\t\tLOG (INFO) << \"21: V[i+1] = v\/beta[i]\";\n\t\t\t\t\t\tvectors[i+1] = new PrimitiveVector(path + \"v\" + (i+1), node_count, block_size);\n\t\t\t\t\t\tv.multiply(1\/beta[i], *vectors[i+1]);\n\t\t\t\t}\n\t\t}\n\t\tLOG (INFO) << \"Creating EigenValues\";\n\t\tEigen::Matrix<double, iterations, iterations> ti = build_tridiagonal_matrix(iterations, alpha, beta);\n\t\tEigen::SelfAdjointEigenSolver<Eigen::Matrix<double,iterations,iterations> > eigensolver(ti);\n\t\tEigen::Matrix<double, iterations, 1> evalues = eigensolver.eigenvalues();\n\t\tEigen::Matrix<double, iterations, iterations> q = eigensolver.eigenvectors();\n\n\n\n\t\t\/\/int64 ids[] = new int64[topK];\n\n\t}\n\n\tEigen::Matrix LanczosSO::build_tridiagonal_matrix(int m, double alpha [], double beta[]){\n\n\t\tEigen::Matrix<double, m, m> matrix;\n\t\tmatrix.fill(0);\n\n\t\tmatrix[0][0] = alpha[0];\n\n\t\tif(m==1) return matrix;\n\n\t\tmatrix[0][1] = beta[0];\n\t\tmatrix[m-1][m-2] = beta[m-2];\n\t\tmatrix[m-1][m-1] = alpha[m-1];\n\n\t\tfor(int i=1; i<m-1; i++){\n\t\t\tmatrix[i][i] = \t\talpha[i];\n\t\t\tmatrix[i][i+1] = \tbeta[i];\n\t\t\tmatrix[i][i-1] =\tbeta[i-1];\n\t\t}\n\t\treturn matrix;\n\t}\n}\n\n#endif \/* ALGORITHM_LANCZOSSO_HPP_ *\/\n<|endoftext|>"} {"text":"<commit_before>\/*\nThis file is part of Bohrium and copyright (c) 2012 the Bohrium\nteam <http:\/\/www.bh107.org>.\n\nBohrium is free software: you can redistribute it and\/or modify\nit under the terms of the GNU Lesser General Public License as\npublished by the Free Software Foundation, either version 3\nof the License, or (at your option) any later version.\n\nBohrium is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU General Public License for more details.\n\nYou should have received a copy of the\nGNU Lesser General Public License along with Bohrium.\n\nIf not, see <http:\/\/www.gnu.org\/licenses\/>.\n*\/\n\n#pragma once\n\n#include <cstdint>\n#include <bhxx\/BhArray.hpp>\n#include <bhxx\/array_operations.hpp>\n\n\nnamespace bhxx {\n\n\/** Return a new empty array\n *\n * @tparam T The data type of the new array\n * @param shape The shape of the new array\n * @return The new array\n *\/\ntemplate<typename T>\nBhArray <T> empty(Shape shape) {\n return BhArray<T>{std::move(shape)};\n}\n\n\/** Return a new empty array that has the same shape as `ary`\n *\n * @tparam OutType The data type of the returned new array\n * @tparam InType The data type of the input array\n * @param ary The array to take the shape from\n * @return The new array\n *\/\ntemplate<typename OutType, typename InType>\nBhArray <OutType> empty_like(const bhxx::BhArray<InType> &ary) {\n return BhArray<OutType>{ary.shape()};\n}\n\n\/** Return a new array filled with zeros\n *\n * @tparam T The data type of the new array\n * @param shape The shape of the new array\n * @return The new array\n *\/\ntemplate<typename T>\nBhArray <T> zeros(Shape shape) {\n BhArray<T> ret{std::move(shape)};\n ret = T{0};\n return ret;\n}\n\n\/** Return evenly spaced values within a given interval.\n *\n * @tparam T Data type of the returned array\n * @param start Start of interval. The interval includes this value.\n * @param stop End of interval. The interval does not include this value.\n * @param step Spacing between values. For any output out, this is the distance between\n * two adjacent values, out[i+1] - out[i].\n * @return New 1D array\n *\/\ntemplate<typename T>\nBhArray <T> arange(int64_t start, int64_t stop, int64_t step);\n\n\/** Return evenly spaced values within a given interval using steps of 1.\n *\n * @tparam T Data type of the returned array\n * @param start Start of interval. The interval includes this value.\n * @param stop End of interval. The interval does not include this value.\n * @return New 1D array\n *\/\ntemplate<typename T>\nBhArray <T> arange(int64_t start, int64_t stop) {\n return arange<T>(start, stop, 1);\n}\n\n\/** Return evenly spaced values from 0 to `stop` using steps of 1.\n *\n * @tparam T Data type of the returned array\n * @param stop End of interval. The interval does not include this value.\n * @return New 1D array\n *\/\ntemplate<typename T>\nBhArray <T> arange(int64_t stop) {\n return arange<T>(0, stop, 1);\n}\n\n\/** Element-wise `static_cast`.\n *\n * @tparam OutType The data type of the returned array\n * @tparam InType The data type of the input array\n * @param ary Input array to cast\n * @return New array\n *\/\ntemplate<typename OutType, typename InType>\nBhArray <OutType> cast(const bhxx::BhArray<InType> &ary) {\n BhArray<OutType> ret = empty_like<OutType>(ary);\n bhxx::identity(ret, ary);\n return ret;\n}\n\n} \/\/ namespace bhxx\n<commit_msg>bhxx: implemented ones() and full()<commit_after>\/*\nThis file is part of Bohrium and copyright (c) 2012 the Bohrium\nteam <http:\/\/www.bh107.org>.\n\nBohrium is free software: you can redistribute it and\/or modify\nit under the terms of the GNU Lesser General Public License as\npublished by the Free Software Foundation, either version 3\nof the License, or (at your option) any later version.\n\nBohrium is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU General Public License for more details.\n\nYou should have received a copy of the\nGNU Lesser General Public License along with Bohrium.\n\nIf not, see <http:\/\/www.gnu.org\/licenses\/>.\n*\/\n\n#pragma once\n\n#include <cstdint>\n#include <bhxx\/BhArray.hpp>\n#include <bhxx\/array_operations.hpp>\n\n\nnamespace bhxx {\n\n\/** Return a new empty array\n *\n * @tparam T The data type of the new array\n * @param shape The shape of the new array\n * @return The new array\n *\/\ntemplate<typename T>\nBhArray <T> empty(Shape shape) {\n return BhArray<T>{std::move(shape)};\n}\n\n\/** Return a new empty array that has the same shape as `ary`\n *\n * @tparam OutType The data type of the returned new array\n * @tparam InType The data type of the input array\n * @param ary The array to take the shape from\n * @return The new array\n *\/\ntemplate<typename OutType, typename InType>\nBhArray <OutType> empty_like(const bhxx::BhArray<InType> &ary) {\n return BhArray<OutType>{ary.shape()};\n}\n\n\/** Return a new array filled with `value`\n *\n * @tparam T The data type of the new array\n * @param shape The shape of the new array\n * @param value The value to fill the new array with\n * @return The new array\n *\/\ntemplate<typename T>\nBhArray <T> full(Shape shape, T value) {\n BhArray<T> ret{std::move(shape)};\n ret = value;\n return ret;\n}\n\n\/** Return a new array filled with zeros\n *\n * @tparam T The data type of the new array\n * @param shape The shape of the new array\n * @return The new array\n *\/\ntemplate<typename T>\nBhArray <T> zeros(Shape shape) {\n return full(std::move(shape), T{0});\n}\n\n\/** Return a new array filled with ones\n *\n * @tparam T The data type of the new array\n * @param shape The shape of the new array\n * @return The new array\n *\/\ntemplate<typename T>\nBhArray <T> ones(Shape shape) {\n return full(std::move(shape), T{1});\n}\n\n\/** Return evenly spaced values within a given interval.\n *\n * @tparam T Data type of the returned array\n * @param start Start of interval. The interval includes this value.\n * @param stop End of interval. The interval does not include this value.\n * @param step Spacing between values. For any output out, this is the distance between\n * two adjacent values, out[i+1] - out[i].\n * @return New 1D array\n *\/\ntemplate<typename T>\nBhArray <T> arange(int64_t start, int64_t stop, int64_t step);\n\n\/** Return evenly spaced values within a given interval using steps of 1.\n *\n * @tparam T Data type of the returned array\n * @param start Start of interval. The interval includes this value.\n * @param stop End of interval. The interval does not include this value.\n * @return New 1D array\n *\/\ntemplate<typename T>\nBhArray <T> arange(int64_t start, int64_t stop) {\n return arange<T>(start, stop, 1);\n}\n\n\/** Return evenly spaced values from 0 to `stop` using steps of 1.\n *\n * @tparam T Data type of the returned array\n * @param stop End of interval. The interval does not include this value.\n * @return New 1D array\n *\/\ntemplate<typename T>\nBhArray <T> arange(int64_t stop) {\n return arange<T>(0, stop, 1);\n}\n\n\/** Element-wise `static_cast`.\n *\n * @tparam OutType The data type of the returned array\n * @tparam InType The data type of the input array\n * @param ary Input array to cast\n * @return New array\n *\/\ntemplate<typename OutType, typename InType>\nBhArray <OutType> cast(const bhxx::BhArray<InType> &ary) {\n BhArray<OutType> ret = empty_like<OutType>(ary);\n bhxx::identity(ret, ary);\n return ret;\n}\n\n} \/\/ namespace bhxx\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: urp_writer.cxx,v $\n *\n * $Revision: 1.12 $\n *\n * last change: $Author: vg $ $Date: 2003-04-15 16:29:18 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n#include <stdio.h>\n\n#ifndef _OSL_TIME_H_\n#include <osl\/time.h>\n#endif\n\n#include <osl\/mutex.hxx>\n#include <osl\/conditn.h>\n\n#include <typelib\/typedescription.h>\n\n#include <bridges\/remote\/connection.h>\n#include <bridges\/remote\/remote.hxx>\n\n#include <com\/sun\/star\/uno\/Sequence.hxx>\n\n#include <bridges\/remote\/counter.hxx>\n\n#include \"urp_writer.hxx\"\n#include \"urp_bridgeimpl.hxx\"\n#include \"urp_marshal.hxx\"\n#include \"urp_dispatch.hxx\"\n\n#if OSL_DEBUG_LEVEL > 1\nstatic MyCounter thisCounter( \"DEBUG : WriterThread\" );\n#endif\n\nusing namespace ::osl;\n\nnamespace bridges_urp {\n\nOWriterThread::OWriterThread( remote_Connection *pConnection, urp_BridgeImpl *pBridgeImpl,\n uno_Environment *pEnvRemote) :\n m_pConnection( pConnection ),\n m_bAbort( sal_False ),\n m_pBridgeImpl( pBridgeImpl ),\n m_pEnvRemote( pEnvRemote ),\n m_bInBlockingWait( sal_False ),\n m_bEnterBlockingWait( sal_False )\n\n{\n m_oslCondition = osl_createCondition();\n osl_resetCondition( m_oslCondition );\n m_pConnection->acquire( m_pConnection );\n\n#if OSL_DEBUG_LEVEL > 1\n thisCounter.acquire();\n#endif\n}\n\nOWriterThread::~OWriterThread()\n{\n osl_destroyCondition( m_oslCondition );\n m_pConnection->release( m_pConnection );\n#if OSL_DEBUG_LEVEL > 1\n thisCounter.release();\n#endif\n}\n\n\n\/\/ touch is called with locked m_marshalingMutex\nvoid OWriterThread::touch( sal_Bool bImmediately )\n{\n if( bImmediately || m_pBridgeImpl->m_blockMarshaler.getPos() > m_pBridgeImpl->m_properties.nFlushBlockSize )\n {\n write();\n }\n else\n {\n \/\/ wake the writer thread up\n if( m_bInBlockingWait )\n {\n m_bInBlockingWait = sal_False;\n osl_setCondition( m_oslCondition );\n }\n else\n {\n \/\/ ensure, that the writing thread does not enter blocking mode\n m_bEnterBlockingWait = sal_False;\n }\n }\n}\n\n\nvoid OWriterThread::abort()\n{\n MutexGuard guard( m_pBridgeImpl->m_marshalingMutex );\n\n m_bAbort = sal_True;\n m_bEnterBlockingWait = sal_False;\n if( m_bInBlockingWait )\n {\n m_bInBlockingWait = sal_False;\n osl_setCondition( m_oslCondition );\n }\n}\n\n\n\/\/ must be called with locked marshaling mutex\nvoid OWriterThread::write()\n{\n if( ! m_pBridgeImpl->m_blockMarshaler.empty() && ! m_bAbort )\n {\n m_pBridgeImpl->m_blockMarshaler.finish( m_pBridgeImpl->m_nMarshaledMessages);\n m_pBridgeImpl->m_nMarshaledMessages = 0;\n\n sal_Int32 nLength = m_pBridgeImpl->m_blockMarshaler.getSize();\n sal_Int8 *pBuf = m_pBridgeImpl->m_blockMarshaler.getBuffer();\n\n if( nLength != m_pConnection->write( m_pConnection, pBuf, nLength ))\n {\n m_pBridgeImpl->m_blockMarshaler.restart();\n return;\n }\n m_pConnection->flush( m_pConnection );\n m_pBridgeImpl->m_blockMarshaler.restart();\n }\n}\n\nvoid OWriterThread::sendEmptyMessage()\n{\n \/\/ must be called with locked marshaling mutex\n sal_Int32 a[2] = {0,0};\n if( m_pConnection )\n {\n m_pConnection->write( m_pConnection , (sal_Int8*) a , sizeof( sal_Int32) *2 );\n }\n}\n\nvoid OWriterThread::insertReleaseRemoteCall(\n rtl_uString *pOid,typelib_TypeDescriptionReference *pTypeRef)\n{\n {\n ::osl::MutexGuard guard( m_releaseCallMutex );\n\n struct RemoteReleaseCall call;\n call.sOid = pOid;\n call.typeInterface = pTypeRef;\n m_lstReleaseCalls.push_back( call );\n }\n {\n MutexGuard guard( m_pBridgeImpl->m_marshalingMutex );\n if( m_bInBlockingWait )\n {\n m_bInBlockingWait = sal_False;\n osl_setCondition( m_oslCondition );\n }\n else\n {\n \/\/ ensure, that the writing thread does not enter blocking mode\n m_bEnterBlockingWait = sal_False;\n }\n }\n}\n\n\/* The release calls for doubled interfaces\n *\n *\n ***\/\nvoid OWriterThread::executeReleaseRemoteCalls()\n{\n sal_Bool bFound = sal_True;\n ::std::list< struct RemoteReleaseCall > lstReleaseCalls;\n {\n ::osl::MutexGuard guard( m_releaseCallMutex );\n lstReleaseCalls.swap( m_lstReleaseCalls );\n }\n\n for( ::std::list< struct RemoteReleaseCall >::iterator ii = lstReleaseCalls.begin();\n ii != lstReleaseCalls.end();\n ++ ii )\n {\n struct RemoteReleaseCall &call = (*ii) ;\n\n typelib_TypeDescription *pInterfaceTypeDesc = 0;\n typelib_TypeDescription *pReleaseMethod = 0;\n\n call.typeInterface.getDescription( &pInterfaceTypeDesc );\n if( ! pInterfaceTypeDesc->bComplete )\n {\n typelib_typedescription_complete( &pInterfaceTypeDesc );\n }\n\n uno_Any any;\n uno_Any *pAny = &any;\n\n typelib_typedescriptionreference_getDescription(\n &pReleaseMethod ,\n ((typelib_InterfaceTypeDescription*)pInterfaceTypeDesc)->ppAllMembers[REMOTE_RELEASE_METHOD_INDEX] );\n\n urp_sendRequest( m_pEnvRemote , pReleaseMethod, call.sOid.pData,\n (typelib_InterfaceTypeDescription*) pInterfaceTypeDesc,\n 0, 0 , &pAny );\n\n typelib_typedescription_release( pReleaseMethod );\n typelib_typedescription_release( pInterfaceTypeDesc );\n }\n}\n\n\nvoid OWriterThread::run()\n{\n while( ! m_bAbort )\n {\n sal_Bool bWait;\n {\n MutexGuard guard( m_pBridgeImpl->m_marshalingMutex );\n bWait = m_bEnterBlockingWait;\n if( bWait )\n {\n osl_resetCondition( m_oslCondition );\n m_bInBlockingWait = sal_True;\n }\n m_bEnterBlockingWait = sal_True;\n }\n\n \/\/ wait for some notification\n if( bWait )\n osl_waitCondition( m_oslCondition , 0 );\n \/\/ (m_bInBlockingWait = sal_False was set by the activating thread)\n\n if( m_bAbort )\n break;\n\n \/\/ Wait for the timeout\n TimeValue value = { 0 , 1000 * m_pBridgeImpl->m_properties.nOnewayTimeoutMUSEC };\n osl_resetCondition( m_oslCondition );\n osl_waitCondition( m_oslCondition , &value );\n\n \/\/ check if there are some release calls to be sent ....\n executeReleaseRemoteCalls();\n\n {\n \/\/ write to the socket\n MutexGuard guard( m_pBridgeImpl->m_marshalingMutex );\n if( ! m_pBridgeImpl->m_blockMarshaler.empty() )\n {\n write();\n }\n }\n }\n}\n\n\n}\n\n<commit_msg>INTEGRATION: CWS ooo20040329 (1.12.90); FILE MERGED 2004\/03\/17 10:21:09 waratah 1.12.90.1: #i1858# alter the order of some definitions to fix some -Wall warnings<commit_after>\/*************************************************************************\n *\n * $RCSfile: urp_writer.cxx,v $\n *\n * $Revision: 1.13 $\n *\n * last change: $Author: svesik $ $Date: 2004-04-21 13:46:50 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n#include <stdio.h>\n#ifndef _OSL_TIME_H_\n#include <osl\/time.h>\n#endif\n\n#include <osl\/mutex.hxx>\n#include <osl\/conditn.h>\n\n#include <typelib\/typedescription.h>\n\n#include <bridges\/remote\/connection.h>\n#include <bridges\/remote\/remote.hxx>\n\n#include <com\/sun\/star\/uno\/Sequence.hxx>\n\n#include <bridges\/remote\/counter.hxx>\n\n#include \"urp_writer.hxx\"\n#include \"urp_bridgeimpl.hxx\"\n#include \"urp_marshal.hxx\"\n#include \"urp_dispatch.hxx\"\n\n#if OSL_DEBUG_LEVEL > 1\nstatic MyCounter thisCounter( \"DEBUG : WriterThread\" );\n#endif\n\nusing namespace ::osl;\n\nnamespace bridges_urp {\n\nOWriterThread::OWriterThread( remote_Connection *pConnection, urp_BridgeImpl *pBridgeImpl,\n uno_Environment *pEnvRemote) :\n m_bAbort( sal_False ),\n m_bInBlockingWait( sal_False ),\n m_bEnterBlockingWait( sal_False ),\n m_pConnection( pConnection ),\n m_pBridgeImpl( pBridgeImpl ),\n m_pEnvRemote( pEnvRemote )\n\n{\n m_oslCondition = osl_createCondition();\n osl_resetCondition( m_oslCondition );\n m_pConnection->acquire( m_pConnection );\n\n#if OSL_DEBUG_LEVEL > 1\n thisCounter.acquire();\n#endif\n}\n\nOWriterThread::~OWriterThread()\n{\n osl_destroyCondition( m_oslCondition );\n m_pConnection->release( m_pConnection );\n#if OSL_DEBUG_LEVEL > 1\n thisCounter.release();\n#endif\n}\n\n\n\/\/ touch is called with locked m_marshalingMutex\nvoid OWriterThread::touch( sal_Bool bImmediately )\n{\n if( bImmediately || m_pBridgeImpl->m_blockMarshaler.getPos() > m_pBridgeImpl->m_properties.nFlushBlockSize )\n {\n write();\n }\n else\n {\n \/\/ wake the writer thread up\n if( m_bInBlockingWait )\n {\n m_bInBlockingWait = sal_False;\n osl_setCondition( m_oslCondition );\n }\n else\n {\n \/\/ ensure, that the writing thread does not enter blocking mode\n m_bEnterBlockingWait = sal_False;\n }\n }\n}\n\n\nvoid OWriterThread::abort()\n{\n MutexGuard guard( m_pBridgeImpl->m_marshalingMutex );\n\n m_bAbort = sal_True;\n m_bEnterBlockingWait = sal_False;\n if( m_bInBlockingWait )\n {\n m_bInBlockingWait = sal_False;\n osl_setCondition( m_oslCondition );\n }\n}\n\n\n\/\/ must be called with locked marshaling mutex\nvoid OWriterThread::write()\n{\n if( ! m_pBridgeImpl->m_blockMarshaler.empty() && ! m_bAbort )\n {\n m_pBridgeImpl->m_blockMarshaler.finish( m_pBridgeImpl->m_nMarshaledMessages);\n m_pBridgeImpl->m_nMarshaledMessages = 0;\n\n sal_Int32 nLength = m_pBridgeImpl->m_blockMarshaler.getSize();\n sal_Int8 *pBuf = m_pBridgeImpl->m_blockMarshaler.getBuffer();\n\n if( nLength != m_pConnection->write( m_pConnection, pBuf, nLength ))\n {\n m_pBridgeImpl->m_blockMarshaler.restart();\n return;\n }\n m_pConnection->flush( m_pConnection );\n m_pBridgeImpl->m_blockMarshaler.restart();\n }\n}\n\nvoid OWriterThread::sendEmptyMessage()\n{\n \/\/ must be called with locked marshaling mutex\n sal_Int32 a[2] = {0,0};\n if( m_pConnection )\n {\n m_pConnection->write( m_pConnection , (sal_Int8*) a , sizeof( sal_Int32) *2 );\n }\n}\n\nvoid OWriterThread::insertReleaseRemoteCall(\n rtl_uString *pOid,typelib_TypeDescriptionReference *pTypeRef)\n{\n {\n ::osl::MutexGuard guard( m_releaseCallMutex );\n\n struct RemoteReleaseCall call;\n call.sOid = pOid;\n call.typeInterface = pTypeRef;\n m_lstReleaseCalls.push_back( call );\n }\n {\n MutexGuard guard( m_pBridgeImpl->m_marshalingMutex );\n if( m_bInBlockingWait )\n {\n m_bInBlockingWait = sal_False;\n osl_setCondition( m_oslCondition );\n }\n else\n {\n \/\/ ensure, that the writing thread does not enter blocking mode\n m_bEnterBlockingWait = sal_False;\n }\n }\n}\n\n\/* The release calls for doubled interfaces\n *\n *\n ***\/\nvoid OWriterThread::executeReleaseRemoteCalls()\n{\n ::std::list< struct RemoteReleaseCall > lstReleaseCalls;\n {\n ::osl::MutexGuard guard( m_releaseCallMutex );\n lstReleaseCalls.swap( m_lstReleaseCalls );\n }\n\n for( ::std::list< struct RemoteReleaseCall >::iterator ii = lstReleaseCalls.begin();\n ii != lstReleaseCalls.end();\n ++ ii )\n {\n struct RemoteReleaseCall &call = (*ii) ;\n\n typelib_TypeDescription *pInterfaceTypeDesc = 0;\n typelib_TypeDescription *pReleaseMethod = 0;\n\n call.typeInterface.getDescription( &pInterfaceTypeDesc );\n if( ! pInterfaceTypeDesc->bComplete )\n {\n typelib_typedescription_complete( &pInterfaceTypeDesc );\n }\n\n uno_Any any;\n uno_Any *pAny = &any;\n\n typelib_typedescriptionreference_getDescription(\n &pReleaseMethod ,\n ((typelib_InterfaceTypeDescription*)pInterfaceTypeDesc)->ppAllMembers[REMOTE_RELEASE_METHOD_INDEX] );\n\n urp_sendRequest( m_pEnvRemote , pReleaseMethod, call.sOid.pData,\n (typelib_InterfaceTypeDescription*) pInterfaceTypeDesc,\n 0, 0 , &pAny );\n\n typelib_typedescription_release( pReleaseMethod );\n typelib_typedescription_release( pInterfaceTypeDesc );\n }\n}\n\n\nvoid OWriterThread::run()\n{\n while( ! m_bAbort )\n {\n sal_Bool bWait;\n {\n MutexGuard guard( m_pBridgeImpl->m_marshalingMutex );\n bWait = m_bEnterBlockingWait;\n if( bWait )\n {\n osl_resetCondition( m_oslCondition );\n m_bInBlockingWait = sal_True;\n }\n m_bEnterBlockingWait = sal_True;\n }\n\n \/\/ wait for some notification\n if( bWait )\n osl_waitCondition( m_oslCondition , 0 );\n \/\/ (m_bInBlockingWait = sal_False was set by the activating thread)\n\n if( m_bAbort )\n break;\n\n \/\/ Wait for the timeout\n TimeValue value = { 0 , 1000 * m_pBridgeImpl->m_properties.nOnewayTimeoutMUSEC };\n osl_resetCondition( m_oslCondition );\n osl_waitCondition( m_oslCondition , &value );\n\n \/\/ check if there are some release calls to be sent ....\n executeReleaseRemoteCalls();\n\n {\n \/\/ write to the socket\n MutexGuard guard( m_pBridgeImpl->m_marshalingMutex );\n if( ! m_pBridgeImpl->m_blockMarshaler.empty() )\n {\n write();\n }\n }\n }\n}\n\n\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/*!\n * \\page batch_airinv_cpp Command-Line Utility to Demonstrate Typical AirInv Usage\n * \\code\n *\/\n\/\/ STL\n#include <cassert>\n#include <iostream>\n#include <sstream>\n#include <fstream>\n#include <string>\n\/\/ Boost (Extended STL)\n#include <boost\/program_options.hpp>\n#include <boost\/tokenizer.hpp>\n\/\/ StdAir\n#include <stdair\/basic\/BasLogParams.hpp>\n#include <stdair\/basic\/BasDBParams.hpp>\n#include <stdair\/service\/Logger.hpp>\n\/\/ AirInv\n#include <airinv\/AIRINV_Master_Service.hpp>\n#include <airinv\/config\/airinv-paths.hpp>\n\n\/\/ \/\/\/\/\/\/\/\/ Constants \/\/\/\/\/\/\n\/** Default name and location for the log file. *\/\nconst std::string K_AIRINV_DEFAULT_LOG_FILENAME (\"airinv.log\");\n\n\/** Default name and location for the (CSV) input files. *\/\nconst std::string K_AIRINV_DEFAULT_INVENTORY_FILENAME (STDAIR_SAMPLE_DIR\n \"\/invdump01.csv\");\n\/** Default name and location for the (CSV) input files. *\/\nconst std::string K_AIRINV_DEFAULT_SCHEDULE_FILENAME (STDAIR_SAMPLE_DIR\n \"\/schedule01.csv\");\n\/** Default name and location for the (CSV) input files. *\/\nconst std::string K_AIRINV_DEFAULT_OND_FILENAME (STDAIR_SAMPLE_DIR \"\/ond01.csv\");\n\n\/** Default segment-date key on which the sale should be made. *\/\nconst std::string K_AIRINV_DEFAULT_SEGMENT_DATE_KEY (\"SV\/5\/2010-03-11\/KBP.JFK\");\n\n\/** Default class code for which the sale should be made. *\/\nconst stdair::ClassCode_T K_AIRINV_DEFAULT_CLASS_CODE (\"Y\");\n\n\/** Default party size for the sale. *\/\nconst stdair::PartySize_T K_AIRINV_DEFAULT_PARTY_SIZE (2);\n\n\/** Default for the input type. It can be either built-in or provided by an\n input file. That latter must then be given with the -i option. *\/\nconst bool K_AIRINV_DEFAULT_BUILT_IN_INPUT = false;\n\n\/** Default for the input type. The BOM tree can be built from either an\n inventory dump or from a schedule file (and, potentially, an O&D list). *\/\nconst bool K_AIRINV_DEFAULT_FOR_SCHEDULE = false;\n\n\/** Early return status (so that it can be differentiated from an\n error). *\/\nconst int K_AIRINV_EARLY_RETURN_STATUS = 99;\n\n\/\/ \/\/\/\/\/\/\/\/\/ Parsing of Options & Configuration \/\/\/\/\/\/\/\/\/\n\/\/ A helper function to simplify the main part.\ntemplate<class T> std::ostream& operator<< (std::ostream& os,\n const std::vector<T>& v) {\n std::copy (v.begin(), v.end(), std::ostream_iterator<T> (std::cout, \" \")); \n return os;\n}\n\n\/** Read and parse the command line options. *\/\nint readConfiguration (int argc, char* argv[],\n bool& ioIsBuiltin, bool& ioIsForSchedule,\n stdair::Filename_T& ioInventoryFilename,\n stdair::Filename_T& ioScheduleInputFilename,\n stdair::Filename_T& ioODInputFilename,\n std::string& ioSegmentDateKey,\n stdair::ClassCode_T& ioClassCode,\n stdair::PartySize_T& ioPartySize,\n std::string& ioLogFilename) {\n \/\/ Default for the built-in input\n ioIsBuiltin = K_AIRINV_DEFAULT_BUILT_IN_INPUT;\n\n \/\/ Default for the inventory or schedule option\n ioIsForSchedule = K_AIRINV_DEFAULT_FOR_SCHEDULE;\n\n \/\/ Declare a group of options that will be allowed only on command line\n boost::program_options::options_description generic (\"Generic options\");\n generic.add_options()\n (\"prefix\", \"print installation prefix\")\n (\"version,v\", \"print version string\")\n (\"help,h\", \"produce help message\");\n \n \/\/ Declare a group of options that will be allowed both on command\n \/\/ line and in config file\n\n boost::program_options::options_description config (\"Configuration\");\n config.add_options()\n (\"builtin,b\",\n \"The sample BOM tree can be either built-in or parsed from an input file. That latter must then be given with the -i\/--inventory or -s\/--schedule option\")\n (\"for_schedule,f\",\n \"The BOM tree should be built from a schedule file (instead of from an inventory dump)\")\n (\"inventory,i\",\n boost::program_options::value< std::string >(&ioInventoryFilename)->default_value(K_AIRINV_DEFAULT_INVENTORY_FILENAME),\n \"(CVS) input file for the inventory\")\n (\"schedule,s\",\n boost::program_options::value< std::string >(&ioScheduleInputFilename)->default_value(K_AIRINV_DEFAULT_SCHEDULE_FILENAME),\n \"(CVS) input file for the schedule\")\n (\"ond,o\",\n boost::program_options::value< std::string >(&ioODInputFilename)->default_value(K_AIRINV_DEFAULT_OND_FILENAME),\n \"(CVS) input file for the O&D\")\n (\"segment_date_key,k\",\n boost::program_options::value< std::string >(&ioSegmentDateKey)->default_value(K_AIRINV_DEFAULT_SEGMENT_DATE_KEY),\n \"Segment-date key\")\n (\"class_code,c\",\n boost::program_options::value< stdair::ClassCode_T >(&ioClassCode)->default_value(K_AIRINV_DEFAULT_CLASS_CODE),\n \"Class code\")\n (\"party_size,p\",\n boost::program_options::value< stdair::PartySize_T >(&ioPartySize)->default_value(K_AIRINV_DEFAULT_PARTY_SIZE),\n \"Party size\")\n (\"log,l\",\n boost::program_options::value< std::string >(&ioLogFilename)->default_value(K_AIRINV_DEFAULT_LOG_FILENAME),\n \"Filename for the logs\")\n ;\n\n \/\/ Hidden options, will be allowed both on command line and\n \/\/ in config file, but will not be shown to the user.\n boost::program_options::options_description hidden (\"Hidden options\");\n hidden.add_options()\n (\"copyright\",\n boost::program_options::value< std::vector<std::string> >(),\n \"Show the copyright (license)\");\n \n boost::program_options::options_description cmdline_options;\n cmdline_options.add(generic).add(config).add(hidden);\n\n boost::program_options::options_description config_file_options;\n config_file_options.add(config).add(hidden);\n boost::program_options::options_description visible (\"Allowed options\");\n visible.add(generic).add(config);\n \n boost::program_options::positional_options_description p;\n p.add (\"copyright\", -1);\n \n boost::program_options::variables_map vm;\n boost::program_options::\n store (boost::program_options::command_line_parser (argc, argv).\n options (cmdline_options).positional(p).run(), vm);\n\n std::ifstream ifs (\"airinv.cfg\");\n boost::program_options::store (parse_config_file (ifs, config_file_options),\n vm);\n boost::program_options::notify (vm);\n \n if (vm.count (\"help\")) {\n std::cout << visible << std::endl;\n return K_AIRINV_EARLY_RETURN_STATUS;\n }\n\n if (vm.count (\"version\")) {\n std::cout << PACKAGE_NAME << \", version \" << PACKAGE_VERSION << std::endl;\n return K_AIRINV_EARLY_RETURN_STATUS;\n }\n\n if (vm.count (\"prefix\")) {\n std::cout << \"Installation prefix: \" << PREFIXDIR << std::endl;\n return K_AIRINV_EARLY_RETURN_STATUS;\n }\n\n if (vm.count (\"builtin\")) {\n ioIsBuiltin = true;\n }\n const std::string isBuiltinStr = (ioIsBuiltin == true)?\"yes\":\"no\";\n std::cout << \"The BOM should be built-in? \" << isBuiltinStr << std::endl;\n\n if (vm.count (\"for_schedule\")) {\n ioIsForSchedule = true;\n }\n const std::string isForScheduleStr = (ioIsForSchedule == true)?\"yes\":\"no\";\n std::cout << \"The BOM should be built from schedule? \" << isForScheduleStr\n << std::endl;\n\n if (ioIsBuiltin == false) {\n\n if (ioIsForSchedule == false) {\n \/\/ The BOM tree should be built from parsing an inventory dump\n if (vm.count (\"inventory\")) {\n ioInventoryFilename = vm[\"inventory\"].as< std::string >();\n std::cout << \"Input inventory filename is: \" << ioInventoryFilename\n << std::endl;\n\n } else {\n \/\/ The built-in option is not selected. However, no inventory dump\n \/\/ file is specified\n std::cerr << \"Either one among the -b\/--builtin, -i\/--inventory or \"\n << \" -f\/--for_schedule and -s\/--schedule options \"\n << \"must be specified\" << std::endl;\n }\n\n } else {\n \/\/ The BOM tree should be built from parsing a schedule (and O&D) file\n if (vm.count (\"schedule\")) {\n ioScheduleInputFilename = vm[\"schedule\"].as< std::string >();\n std::cout << \"Input schedule filename is: \" << ioScheduleInputFilename\n << std::endl;\n\n } else {\n \/\/ The built-in option is not selected. However, no schedule file\n \/\/ is specified\n std::cerr << \"Either one among the -b\/--builtin, -i\/--inventory or \"\n << \" -f\/--for_schedule and -s\/--schedule options \"\n << \"must be specified\" << std::endl;\n }\n\n if (vm.count (\"ond\")) {\n ioODInputFilename = vm[\"ond\"].as< std::string >();\n std::cout << \"Input O&D filename is: \" << ioODInputFilename << std::endl;\n }\n }\n }\n\n if (vm.count (\"log\")) {\n ioLogFilename = vm[\"log\"].as< std::string >();\n std::cout << \"Log filename is: \" << ioLogFilename << std::endl;\n }\n\n return 0;\n}\n\n\n\/\/ \/\/\/\/\/\/\/\/\/ M A I N \/\/\/\/\/\/\/\/\/\/\/\/\nint main (int argc, char* argv[]) {\n\n \/\/ State whether the BOM tree should be built-in or parsed from an\n \/\/ input file\n bool isBuiltin;\n bool isForSchedule;\n\n \/\/ Input file names\n stdair::Filename_T lInventoryFilename;\n stdair::Filename_T lScheduleInputFilename;\n stdair::Filename_T lODInputFilename;\n\n \/\/ Parameters for the sale\n std::string lSegmentDateKey;\n stdair::ClassCode_T lClassCode;\n stdair::PartySize_T lPartySize;\n\n \/\/ Output log File\n stdair::Filename_T lLogFilename;\n\n \/\/ Call the command-line option parser\n const int lOptionParserStatus =\n readConfiguration (argc, argv, isBuiltin, isForSchedule, lInventoryFilename,\n lScheduleInputFilename, lODInputFilename,\n lSegmentDateKey, lClassCode, lPartySize, lLogFilename);\n\n if (lOptionParserStatus == K_AIRINV_EARLY_RETURN_STATUS) {\n return 0;\n }\n\n \/\/ Set the log parameters\n std::ofstream logOutputFile;\n \/\/ Open and clean the log outputfile\n logOutputFile.open (lLogFilename.c_str());\n logOutputFile.clear();\n\n \/\/ Initialise the inventory service\n const stdair::BasLogParams lLogParams (stdair::LOG::DEBUG, logOutputFile);\n \n \/\/ Check wether or not a (CSV) input file should be read\n if (isBuiltin == true) {\n\n \/\/ Build the BOM tree from parsing an inventory dump file\n AIRINV::AIRINV_Master_Service airinvService (lLogParams);\n\n \/\/ DEBUG\n STDAIR_LOG_DEBUG (\"Welcome to airinv\");\n\n \/\/ Build the sample BOM tree for RMOL\n airinvService.buildSampleBom();\n\n \/\/ Make a booking\n const bool isSellSuccessful =\n airinvService.sell (lSegmentDateKey, lClassCode, lPartySize);\n\n \/\/ DEBUG\n STDAIR_LOG_DEBUG (\"Sale ('\" << lSegmentDateKey << \"', \" << lClassCode << \": \"\n << lPartySize << \") successful? \" << isSellSuccessful);\n\n \/\/ DEBUG: Display the whole BOM tree\n const std::string& lCSVDump = airinvService.csvDisplay();\n STDAIR_LOG_DEBUG (lCSVDump);\n\n } else {\n if (isForSchedule == true) {\n \/\/ Build the BOM tree from parsing a schedule file (and O&D list)\n AIRINV::AIRINV_Master_Service airinvService (lLogParams,\n lScheduleInputFilename,\n lODInputFilename);\n\n \/\/ DEBUG\n STDAIR_LOG_DEBUG (\"Welcome to airinv\");\n\n \/\/ Make a booking\n const bool isSellSuccessful =\n airinvService.sell (lSegmentDateKey, lClassCode, lPartySize);\n\n \/\/ DEBUG\n STDAIR_LOG_DEBUG(\"Sale ('\" << lSegmentDateKey << \"', \" << lClassCode<< \": \"\n << lPartySize << \") successful? \" << isSellSuccessful);\n\n \/\/ DEBUG: Display the whole BOM tree\n const std::string& lCSVDump = airinvService.csvDisplay();\n STDAIR_LOG_DEBUG (lCSVDump);\n\n } else {\n \/\/ Build the BOM tree from parsing an inventory dump file\n AIRINV::AIRINV_Master_Service airinvService (lLogParams,\n lInventoryFilename);\n\n \/\/ DEBUG\n STDAIR_LOG_DEBUG (\"Welcome to airinv\");\n\n \/\/ Make a booking\n const bool isSellSuccessful =\n airinvService.sell (lSegmentDateKey, lClassCode, lPartySize);\n\n \/\/ DEBUG\n STDAIR_LOG_DEBUG(\"Sale ('\" << lSegmentDateKey << \"', \" << lClassCode<< \": \"\n << lPartySize << \") successful? \" << isSellSuccessful);\n\n \/\/ DEBUG: Display the whole BOM tree\n const std::string& lCSVDump = airinvService.csvDisplay();\n STDAIR_LOG_DEBUG (lCSVDump);\n }\n }\n\n \/\/ Close the Log outputFile\n logOutputFile.close();\n\n \/*\n Note: as that program is not intended to be run on a server in\n production, it is better not to catch the exceptions. When it\n happens (that an exception is throwned), that way we get the\n call stack.\n *\/\n\n return 0;\t\n}\n<commit_msg>[AirInv][Dev] Fixed the default segment-date key for the AirInv batch.<commit_after>\/*!\n * \\page batch_airinv_cpp Command-Line Utility to Demonstrate Typical AirInv Usage\n * \\code\n *\/\n\/\/ STL\n#include <cassert>\n#include <iostream>\n#include <sstream>\n#include <fstream>\n#include <string>\n\/\/ Boost (Extended STL)\n#include <boost\/program_options.hpp>\n#include <boost\/tokenizer.hpp>\n\/\/ StdAir\n#include <stdair\/basic\/BasLogParams.hpp>\n#include <stdair\/basic\/BasDBParams.hpp>\n#include <stdair\/service\/Logger.hpp>\n\/\/ AirInv\n#include <airinv\/AIRINV_Master_Service.hpp>\n#include <airinv\/config\/airinv-paths.hpp>\n\n\/\/ \/\/\/\/\/\/\/\/ Constants \/\/\/\/\/\/\n\/** Default name and location for the log file. *\/\nconst std::string K_AIRINV_DEFAULT_LOG_FILENAME (\"airinv.log\");\n\n\/** Default name and location for the (CSV) input files. *\/\nconst std::string K_AIRINV_DEFAULT_INVENTORY_FILENAME (STDAIR_SAMPLE_DIR\n \"\/invdump01.csv\");\n\/** Default name and location for the (CSV) input files. *\/\nconst std::string K_AIRINV_DEFAULT_SCHEDULE_FILENAME (STDAIR_SAMPLE_DIR\n \"\/schedule01.csv\");\n\/** Default name and location for the (CSV) input files. *\/\nconst std::string K_AIRINV_DEFAULT_OND_FILENAME (STDAIR_SAMPLE_DIR \"\/ond01.csv\");\n\n\/** Default segment-date key on which the sale should be made. *\/\nconst std::string K_AIRINV_DEFAULT_SEGMENT_DATE_KEY (\"SV,5,2010-03-11,KBP,JFK\");\n\n\/** Default class code for which the sale should be made. *\/\nconst stdair::ClassCode_T K_AIRINV_DEFAULT_CLASS_CODE (\"Y\");\n\n\/** Default party size for the sale. *\/\nconst stdair::PartySize_T K_AIRINV_DEFAULT_PARTY_SIZE (2);\n\n\/** Default for the input type. It can be either built-in or provided by an\n input file. That latter must then be given with the -i option. *\/\nconst bool K_AIRINV_DEFAULT_BUILT_IN_INPUT = false;\n\n\/** Default for the input type. The BOM tree can be built from either an\n inventory dump or from a schedule file (and, potentially, an O&D list). *\/\nconst bool K_AIRINV_DEFAULT_FOR_SCHEDULE = false;\n\n\/** Early return status (so that it can be differentiated from an\n error). *\/\nconst int K_AIRINV_EARLY_RETURN_STATUS = 99;\n\n\/\/ \/\/\/\/\/\/\/\/\/ Parsing of Options & Configuration \/\/\/\/\/\/\/\/\/\n\/\/ A helper function to simplify the main part.\ntemplate<class T> std::ostream& operator<< (std::ostream& os,\n const std::vector<T>& v) {\n std::copy (v.begin(), v.end(), std::ostream_iterator<T> (std::cout, \" \")); \n return os;\n}\n\n\/** Read and parse the command line options. *\/\nint readConfiguration (int argc, char* argv[],\n bool& ioIsBuiltin, bool& ioIsForSchedule,\n stdair::Filename_T& ioInventoryFilename,\n stdair::Filename_T& ioScheduleInputFilename,\n stdair::Filename_T& ioODInputFilename,\n std::string& ioSegmentDateKey,\n stdair::ClassCode_T& ioClassCode,\n stdair::PartySize_T& ioPartySize,\n std::string& ioLogFilename) {\n \/\/ Default for the built-in input\n ioIsBuiltin = K_AIRINV_DEFAULT_BUILT_IN_INPUT;\n\n \/\/ Default for the inventory or schedule option\n ioIsForSchedule = K_AIRINV_DEFAULT_FOR_SCHEDULE;\n\n \/\/ Declare a group of options that will be allowed only on command line\n boost::program_options::options_description generic (\"Generic options\");\n generic.add_options()\n (\"prefix\", \"print installation prefix\")\n (\"version,v\", \"print version string\")\n (\"help,h\", \"produce help message\");\n \n \/\/ Declare a group of options that will be allowed both on command\n \/\/ line and in config file\n\n boost::program_options::options_description config (\"Configuration\");\n config.add_options()\n (\"builtin,b\",\n \"The sample BOM tree can be either built-in or parsed from an input file. That latter must then be given with the -i\/--inventory or -s\/--schedule option\")\n (\"for_schedule,f\",\n \"The BOM tree should be built from a schedule file (instead of from an inventory dump)\")\n (\"inventory,i\",\n boost::program_options::value< std::string >(&ioInventoryFilename)->default_value(K_AIRINV_DEFAULT_INVENTORY_FILENAME),\n \"(CVS) input file for the inventory\")\n (\"schedule,s\",\n boost::program_options::value< std::string >(&ioScheduleInputFilename)->default_value(K_AIRINV_DEFAULT_SCHEDULE_FILENAME),\n \"(CVS) input file for the schedule\")\n (\"ond,o\",\n boost::program_options::value< std::string >(&ioODInputFilename)->default_value(K_AIRINV_DEFAULT_OND_FILENAME),\n \"(CVS) input file for the O&D\")\n (\"segment_date_key,k\",\n boost::program_options::value< std::string >(&ioSegmentDateKey)->default_value(K_AIRINV_DEFAULT_SEGMENT_DATE_KEY),\n \"Segment-date key\")\n (\"class_code,c\",\n boost::program_options::value< stdair::ClassCode_T >(&ioClassCode)->default_value(K_AIRINV_DEFAULT_CLASS_CODE),\n \"Class code\")\n (\"party_size,p\",\n boost::program_options::value< stdair::PartySize_T >(&ioPartySize)->default_value(K_AIRINV_DEFAULT_PARTY_SIZE),\n \"Party size\")\n (\"log,l\",\n boost::program_options::value< std::string >(&ioLogFilename)->default_value(K_AIRINV_DEFAULT_LOG_FILENAME),\n \"Filename for the logs\")\n ;\n\n \/\/ Hidden options, will be allowed both on command line and\n \/\/ in config file, but will not be shown to the user.\n boost::program_options::options_description hidden (\"Hidden options\");\n hidden.add_options()\n (\"copyright\",\n boost::program_options::value< std::vector<std::string> >(),\n \"Show the copyright (license)\");\n \n boost::program_options::options_description cmdline_options;\n cmdline_options.add(generic).add(config).add(hidden);\n\n boost::program_options::options_description config_file_options;\n config_file_options.add(config).add(hidden);\n boost::program_options::options_description visible (\"Allowed options\");\n visible.add(generic).add(config);\n \n boost::program_options::positional_options_description p;\n p.add (\"copyright\", -1);\n \n boost::program_options::variables_map vm;\n boost::program_options::\n store (boost::program_options::command_line_parser (argc, argv).\n options (cmdline_options).positional(p).run(), vm);\n\n std::ifstream ifs (\"airinv.cfg\");\n boost::program_options::store (parse_config_file (ifs, config_file_options),\n vm);\n boost::program_options::notify (vm);\n \n if (vm.count (\"help\")) {\n std::cout << visible << std::endl;\n return K_AIRINV_EARLY_RETURN_STATUS;\n }\n\n if (vm.count (\"version\")) {\n std::cout << PACKAGE_NAME << \", version \" << PACKAGE_VERSION << std::endl;\n return K_AIRINV_EARLY_RETURN_STATUS;\n }\n\n if (vm.count (\"prefix\")) {\n std::cout << \"Installation prefix: \" << PREFIXDIR << std::endl;\n return K_AIRINV_EARLY_RETURN_STATUS;\n }\n\n if (vm.count (\"builtin\")) {\n ioIsBuiltin = true;\n }\n const std::string isBuiltinStr = (ioIsBuiltin == true)?\"yes\":\"no\";\n std::cout << \"The BOM should be built-in? \" << isBuiltinStr << std::endl;\n\n if (vm.count (\"for_schedule\")) {\n ioIsForSchedule = true;\n }\n const std::string isForScheduleStr = (ioIsForSchedule == true)?\"yes\":\"no\";\n std::cout << \"The BOM should be built from schedule? \" << isForScheduleStr\n << std::endl;\n\n if (ioIsBuiltin == false) {\n\n if (ioIsForSchedule == false) {\n \/\/ The BOM tree should be built from parsing an inventory dump\n if (vm.count (\"inventory\")) {\n ioInventoryFilename = vm[\"inventory\"].as< std::string >();\n std::cout << \"Input inventory filename is: \" << ioInventoryFilename\n << std::endl;\n\n } else {\n \/\/ The built-in option is not selected. However, no inventory dump\n \/\/ file is specified\n std::cerr << \"Either one among the -b\/--builtin, -i\/--inventory or \"\n << \" -f\/--for_schedule and -s\/--schedule options \"\n << \"must be specified\" << std::endl;\n }\n\n } else {\n \/\/ The BOM tree should be built from parsing a schedule (and O&D) file\n if (vm.count (\"schedule\")) {\n ioScheduleInputFilename = vm[\"schedule\"].as< std::string >();\n std::cout << \"Input schedule filename is: \" << ioScheduleInputFilename\n << std::endl;\n\n } else {\n \/\/ The built-in option is not selected. However, no schedule file\n \/\/ is specified\n std::cerr << \"Either one among the -b\/--builtin, -i\/--inventory or \"\n << \" -f\/--for_schedule and -s\/--schedule options \"\n << \"must be specified\" << std::endl;\n }\n\n if (vm.count (\"ond\")) {\n ioODInputFilename = vm[\"ond\"].as< std::string >();\n std::cout << \"Input O&D filename is: \" << ioODInputFilename << std::endl;\n }\n }\n }\n\n if (vm.count (\"log\")) {\n ioLogFilename = vm[\"log\"].as< std::string >();\n std::cout << \"Log filename is: \" << ioLogFilename << std::endl;\n }\n\n return 0;\n}\n\n\n\/\/ \/\/\/\/\/\/\/\/\/ M A I N \/\/\/\/\/\/\/\/\/\/\/\/\nint main (int argc, char* argv[]) {\n\n \/\/ State whether the BOM tree should be built-in or parsed from an\n \/\/ input file\n bool isBuiltin;\n bool isForSchedule;\n\n \/\/ Input file names\n stdair::Filename_T lInventoryFilename;\n stdair::Filename_T lScheduleInputFilename;\n stdair::Filename_T lODInputFilename;\n\n \/\/ Parameters for the sale\n std::string lSegmentDateKey;\n stdair::ClassCode_T lClassCode;\n stdair::PartySize_T lPartySize;\n\n \/\/ Output log File\n stdair::Filename_T lLogFilename;\n\n \/\/ Call the command-line option parser\n const int lOptionParserStatus =\n readConfiguration (argc, argv, isBuiltin, isForSchedule, lInventoryFilename,\n lScheduleInputFilename, lODInputFilename,\n lSegmentDateKey, lClassCode, lPartySize, lLogFilename);\n\n if (lOptionParserStatus == K_AIRINV_EARLY_RETURN_STATUS) {\n return 0;\n }\n\n \/\/ Set the log parameters\n std::ofstream logOutputFile;\n \/\/ Open and clean the log outputfile\n logOutputFile.open (lLogFilename.c_str());\n logOutputFile.clear();\n\n \/\/ Initialise the inventory service\n const stdair::BasLogParams lLogParams (stdair::LOG::DEBUG, logOutputFile);\n \n \/\/ Check wether or not a (CSV) input file should be read\n if (isBuiltin == true) {\n\n \/\/ Build the BOM tree from parsing an inventory dump file\n AIRINV::AIRINV_Master_Service airinvService (lLogParams);\n\n \/\/ DEBUG\n STDAIR_LOG_DEBUG (\"Welcome to airinv\");\n\n \/\/ Build the sample BOM tree for RMOL\n airinvService.buildSampleBom();\n\n \/\/ Make a booking\n const bool isSellSuccessful =\n airinvService.sell (lSegmentDateKey, lClassCode, lPartySize);\n\n \/\/ DEBUG\n STDAIR_LOG_DEBUG (\"Sale ('\" << lSegmentDateKey << \"', \" << lClassCode << \": \"\n << lPartySize << \") successful? \" << isSellSuccessful);\n\n \/\/ DEBUG: Display the whole BOM tree\n const std::string& lCSVDump = airinvService.csvDisplay();\n STDAIR_LOG_DEBUG (lCSVDump);\n\n } else {\n if (isForSchedule == true) {\n \/\/ Build the BOM tree from parsing a schedule file (and O&D list)\n AIRINV::AIRINV_Master_Service airinvService (lLogParams,\n lScheduleInputFilename,\n lODInputFilename);\n\n \/\/ DEBUG\n STDAIR_LOG_DEBUG (\"Welcome to airinv\");\n\n \/\/ Make a booking\n const bool isSellSuccessful =\n airinvService.sell (lSegmentDateKey, lClassCode, lPartySize);\n\n \/\/ DEBUG\n STDAIR_LOG_DEBUG(\"Sale ('\" << lSegmentDateKey << \"', \" << lClassCode<< \": \"\n << lPartySize << \") successful? \" << isSellSuccessful);\n\n \/\/ DEBUG: Display the whole BOM tree\n const std::string& lCSVDump = airinvService.csvDisplay();\n STDAIR_LOG_DEBUG (lCSVDump);\n\n } else {\n \/\/ Build the BOM tree from parsing an inventory dump file\n AIRINV::AIRINV_Master_Service airinvService (lLogParams,\n lInventoryFilename);\n\n \/\/ DEBUG\n STDAIR_LOG_DEBUG (\"Welcome to airinv\");\n\n \/\/ Make a booking\n const bool isSellSuccessful =\n airinvService.sell (lSegmentDateKey, lClassCode, lPartySize);\n\n \/\/ DEBUG\n STDAIR_LOG_DEBUG(\"Sale ('\" << lSegmentDateKey << \"', \" << lClassCode<< \": \"\n << lPartySize << \") successful? \" << isSellSuccessful);\n\n \/\/ DEBUG: Display the whole BOM tree\n const std::string& lCSVDump = airinvService.csvDisplay();\n STDAIR_LOG_DEBUG (lCSVDump);\n }\n }\n\n \/\/ Close the Log outputFile\n logOutputFile.close();\n\n \/*\n Note: as that program is not intended to be run on a server in\n production, it is better not to catch the exceptions. When it\n happens (that an exception is throwned), that way we get the\n call stack.\n *\/\n\n return 0;\t\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n Copyright (C) 2012 by Ivan Safrin\n \n Permission is hereby granted, free of charge, to any person obtaining a copy\n of this software and associated documentation files (the \"Software\"), to deal\n in the Software without restriction, including without limitation the rights\n to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n copies of the Software, and to permit persons to whom the Software is\n furnished to do so, subject to the following conditions:\n \n The above copyright notice and this permission notice shall be included in\n all copies or substantial portions of the Software.\n \n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n THE SOFTWARE.\n *\/\n\n#include \"PolycodeEditor.h\"\n\nextern PolycodeClipboard *globalClipboard;\n\nPolycodeEditorFactory::PolycodeEditorFactory() {\n\t\n}\n\nPolycodeEditorFactory::~PolycodeEditorFactory() {\n\t\n}\n\nbool PolycodeEditorFactory::canHandleExtension(String extension) {\n\tfor(int i=0; i < extensions.size(); i++) {\n\t\tif(extension == extensions[i])\n\t\t return true;\n\t}\n\treturn false;\n}\n\nvoid PolycodeEditor::setFilePath(String newPath) {\n\tfilePath = newPath;\n}\n\nPolycodeEditor::PolycodeEditor(bool _isReadOnly) : ScreenEntity(), ClipboardProvider() {\n\tthis->_isReadOnly = _isReadOnly;\n\tenableScissor = true;\t\n\tprocessInputEvents = true;\n\t_hasChanges = false;\n\n\tCore *core = CoreServices::getInstance()->getCore();\n\t\n\tcore->addEventListener(this, Core::EVENT_COPY);\n\tcore->addEventListener(this, Core::EVENT_PASTE);\n}\n\nvoid PolycodeEditor::setHasChanges(bool newVal) {\n\tif(_hasChanges != newVal) {\n\t\t_hasChanges = newVal;\t\n\t\tdispatchEvent(new Event(), Event::CHANGE_EVENT);\n\t}\n}\n\nvoid PolycodeEditor::handleEvent(Event *event) {\n\tif(event->getDispatcher() == CoreServices::getInstance()->getCore() && enabled) {\n\t\tswitch(event->getEventCode()) {\n\n\t\t\t\/\/ Only copypaste of more complex IDE entities is handled here.\n\t\t\t\/\/ Pure text copy\/paste is handled in:\n\t\t\t\/\/ Modules\/Contents\/UI\/Source\/PolyUITextInput.cpp\n\t\t\tcase Core::EVENT_COPY:\n\t\t\t{\n\t\t\t\tvoid *data = NULL;\n\t\t\t\tString dataType = Copy(&data);\n\t\t\t\tif(data) {\n\t\t\t\t\tglobalClipboard->setData(data, dataType, this);\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak;\n\t\t\tcase Core::EVENT_PASTE:\n\t\t\t{\n\t\t\t\tif(globalClipboard->getData()) {\n\t\t\t\t\tPaste(globalClipboard->getData(), globalClipboard->getType());\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t}\n}\n\nvoid PolycodeEditor::Resize(int x, int y) {\n\teditorSize = Vector2(x,y);\n\tVector2 pos = getScreenPosition();\n\tscissorBox.setRect(pos.x,pos.y, x, y);\t\n}\n\nPolycodeEditor::~PolycodeEditor() {\n\t\n}\n\n\n<commit_msg>Fixed copy\/paste crashing the IDE because of unremoved event listeners<commit_after>\/*\n Copyright (C) 2012 by Ivan Safrin\n \n Permission is hereby granted, free of charge, to any person obtaining a copy\n of this software and associated documentation files (the \"Software\"), to deal\n in the Software without restriction, including without limitation the rights\n to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n copies of the Software, and to permit persons to whom the Software is\n furnished to do so, subject to the following conditions:\n \n The above copyright notice and this permission notice shall be included in\n all copies or substantial portions of the Software.\n \n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n THE SOFTWARE.\n *\/\n\n#include \"PolycodeEditor.h\"\n\nextern PolycodeClipboard *globalClipboard;\n\nPolycodeEditorFactory::PolycodeEditorFactory() {\n\t\n}\n\nPolycodeEditorFactory::~PolycodeEditorFactory() {\n\t\n}\n\nbool PolycodeEditorFactory::canHandleExtension(String extension) {\n\tfor(int i=0; i < extensions.size(); i++) {\n\t\tif(extension == extensions[i])\n\t\t return true;\n\t}\n\treturn false;\n}\n\nvoid PolycodeEditor::setFilePath(String newPath) {\n\tfilePath = newPath;\n}\n\nPolycodeEditor::PolycodeEditor(bool _isReadOnly) : ScreenEntity(), ClipboardProvider() {\n\tthis->_isReadOnly = _isReadOnly;\n\tenableScissor = true;\t\n\tprocessInputEvents = true;\n\t_hasChanges = false;\n\n\tCore *core = CoreServices::getInstance()->getCore();\n\t\n\tcore->addEventListener(this, Core::EVENT_COPY);\n\tcore->addEventListener(this, Core::EVENT_PASTE);\n}\n\nvoid PolycodeEditor::setHasChanges(bool newVal) {\n\tif(_hasChanges != newVal) {\n\t\t_hasChanges = newVal;\t\n\t\tdispatchEvent(new Event(), Event::CHANGE_EVENT);\n\t}\n}\n\nvoid PolycodeEditor::handleEvent(Event *event) {\n\tif(event->getDispatcher() == CoreServices::getInstance()->getCore() && enabled) {\n\t\tswitch(event->getEventCode()) {\n\n\t\t\t\/\/ Only copypaste of more complex IDE entities is handled here.\n\t\t\t\/\/ Pure text copy\/paste is handled in:\n\t\t\t\/\/ Modules\/Contents\/UI\/Source\/PolyUITextInput.cpp\n\t\t\tcase Core::EVENT_COPY:\n\t\t\t{\n\t\t\t\tvoid *data = NULL;\n\t\t\t\tString dataType = Copy(&data);\n\t\t\t\tif(data) {\n\t\t\t\t\tglobalClipboard->setData(data, dataType, this);\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak;\n\t\t\tcase Core::EVENT_PASTE:\n\t\t\t{\n\t\t\t\tif(globalClipboard->getData()) {\n\t\t\t\t\tPaste(globalClipboard->getData(), globalClipboard->getType());\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t}\n}\n\nvoid PolycodeEditor::Resize(int x, int y) {\n\teditorSize = Vector2(x,y);\n\tVector2 pos = getScreenPosition();\n\tscissorBox.setRect(pos.x,pos.y, x, y);\t\n}\n\nPolycodeEditor::~PolycodeEditor() {\n\tCore *core = CoreServices::getInstance()->getCore();\n\tcore->removeAllHandlersForListener(this);\n}\n\n\n<|endoftext|>"} {"text":"<commit_before><commit_msg>Example of classes, enum, interface, abstract class, inheritance, polymorphism, access modifiers, memory management.<commit_after>\/\/ Author: http:\/\/lemming.life\n\/\/ Language: C++\n\/\/ Purpose: Example of object oriented programming using classes.\n\/\/ - C++ is C with classes.\n\/\/ - Classes enable \"encapsulation\", meaning everything needed for x is in one package\/class.\n\/\/ - Has clases, enum, interface, abstract class, inheritance, polymorphism, access modifiers, \n\n#include <iostream>\n#include <string>\nusing namespace std;\n\/\/using std::string;\n\nclass Simple {\n public:\n int x; \/\/ This is a public member variable\n void changeX(int newX) { x = newX; } \/\/ This is a public method\n};\n\nclass Simple2 {\n private:\n int x; \/\/ Essential, a private member is one that only the class can access\n public:\n void changeX(int newX) { x = newX; } \/\/ changeX is a public method, which can access that x\n};\n\n\n\/\/ An enum is a type that has constant members.\nenum Color { RED, GREEN, BLUE };\n\n\/\/ A simple structure for x and y values.\nstruct Position {\n int x;\n int y;\n\n string toString() {\n return \"x: \" + to_string(x) + \" y: \" + to_string(y);\n }\n};\n\n\/\/ An interface is a constract\n\/\/ - Those using the interface must implement the methods advertised.\nclass PositionInterface {\n virtual int getX() = 0;\n virtual int getY() = 0;\n virtual void changePosition(int, int) = 0;\n};\n\n\/\/ Shape is an abstract class\n\/\/ - Abstract classes cannot be instantiated, but those inheriting from can be instantiated.\n\/\/ - The setColor(Color aColor) = 0 makes this an \"abstract class\" in c++\nclass Shape : PositionInterface {\n private:\n Position position; \/\/ The shape has a position structure, it is private and thus only Shape can access\n protected:\n Color color; \/\/ Shape and child classes can access\n public:\n\n \/\/ This is a parameterized constructor\n Shape(int newX, int newY) {\n position.x = newX;\n position.y = newY;\n } \n\n \/\/ Implementation of the PositionInterface methods\n int getX() { return position.x; }\n int getY() { return position.y; }\n void changePosition(int newX, int newY) { position.x = newX; position.y = newY; }\n\n \/\/ Shape by itself doesn't have a color\n \/\/ but the inherited types may. So, we must\n \/\/ ensure that inherited classes implement.\n virtual Color getColor() { return color; } \/\/ virtual method, it can be called but must be done so explictly\n virtual void setColor(Color aColor) = 0; \/\/ A pure virtual method == the child must implement.\n\n virtual string toString() {\n string colorStr;\n\n \/\/ The getColor() method call will be the child one (Circle)\n \/\/ - Polymorphism is magic.\n switch(getColor()) {\n case RED: colorStr = \"Red\"; break;\n case GREEN: colorStr = \"Green\"; break;\n case BLUE: colorStr = \"Blue\"; break;\n default: colorStr = \"None\"; break;\n }\n return position.toString() + \" Color: \" + colorStr;\n }\n\n \/\/ Abstract classes must have virtual destructors\n virtual ~Shape() { }\n};\n\n\/\/ Circle inherits from Shape\n\/\/ - This is a is-a relationship. Circle \"is-a\" shape.\nclass Circle : public Shape {\n private:\n int radius;\n public:\n \/\/ A parameterized constructor that calls Shape constructor for the x and y positions.\n Circle(int newX, int newY, int newRadius) : Shape(newX, newY) {\n radius = newRadius;\n }\n\n Color getColor() {\n return Shape::getColor(); \/\/ Explicitly calling the abstract class getColor();\n }\n\n void setColor(Color aColor) {\n color = aColor; \/\/ Circle can access protected and public members\n }\n\n string toString() {\n return Shape::toString() + \" Radius: \" + to_string(radius);\n }\n\n ~Circle() {\n \/\/ This is the Circle destructor\n \/\/ then ~Shape destructor is called\n }\n};\n\nclass Square : public Shape {\n private:\n int width;\n int height;\n public:\n\n \/\/ Repeating ourselves is tedious...\n \/\/ Seeing repetition like this means that we should reconsider\n \/\/ how we have implemented. Perhaps it is the wrong approach.\n \/\/ One fix is to delegate this to Shape as a \"has-a\" relationship\n \/\/ in a similar way as we have done with a \"has-a\" position.\n Color getColor() { return color; }\n void setColor(Color aColor) { color = aColor; }\n\n\n string toString() {\n return Shape::toString() + \" Width: \" + to_string(width) + \" Height: \" + to_string(height);\n }\n\n Square(int newX, int newY, int newWidth, int newHeight) : Shape(newX, newY) {\n width = newWidth;\n height = newHeight;\n }\n ~Square() { }\n};\n\n\n\nint main() {\n \n Simple simple;\n simple.x = 5;\n cout << \"Simple x is \" << simple.x << '\\n'; \/\/ 5\n simple.changeX(10);\n cout << \"Simple x is \" << simple.x << '\\n'; \/\/ 10\n\n \/\/ Create an object.\n Circle* circle = new Circle(0, 0, 5);\n cout << circle->toString() << '\\n'; \/\/ Color not yet assigned. So output is x: 0 y: 0 Color: None Radius: 5\n circle->setColor(RED);\n cout << circle->toString() << '\\n'; \/\/ x: 0 y: 0 Color: Red Radius: 5\n delete circle; \/\/ Order of destructor call is from specific to base.\n\n \/\/ Imagine having a collection of Circles, then we have a collection of Squares.\n \/\/ Then we go through each collection, and call the toString() method of each element.\n \/\/ Wouldn't it be better if we had a single collection of Squares and Circles -- a collection of Shapes.\n \/\/ We can do this because Shape* is an abstract class and both Squares and Circles inherit from it.\n Shape* shapes[] = { new Circle(1, 2, 3), new Square(4, 5, 6, 7) }; \/\/ This may also be called \"program to an interface\"\n int length = 2;\n\n for(int i=0; i<length; ++i) {\n \/\/ Polymorphism: it knows which to call Circle::toString() or Square::toString()\n cout << shapes[i]->toString() << '\\n'; \n delete shapes[i]; \/\/ Delete the object. In C++ we must free memory manually.\n }\n\n return 0;\n}<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2013 Intel Corporation. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"cameo\/runtime\/app\/cameo_main_delegate.h\"\n#include \"content\/public\/app\/content_main.h\"\n\n#if defined(OS_WIN)\n#include \"content\/public\/app\/startup_helper_win.h\"\n#include \"sandbox\/win\/sandbox_types.h\"\n#endif\n\n#if defined(OS_WIN)\nint APIENTRY wWinMain(HINSTANCE instance, HINSTANCE, wchar_t*, int) {\n sandbox::SandboxInterfaceInfo sandbox_info = {0};\n content::InitializeSandboxInfo(&sandbox_info);\n cameo::CameoMainDelegate delegate;\n return content::ContentMain(instance, &sandbox_info, &delegate);\n}\n#elif defined(OS_LINUX)\nint main(int argc, const char** argv) {\n cameo::CameoMainDelegate delegate;\n return content::ContentMain(argc, argv, &delegate);\n}\n#else\n#error \"Unsupport platform.\"\n#endif\n<commit_msg>Fix wrongly changed include path when removing cameo\/src dir<commit_after>\/\/ Copyright (c) 2013 Intel Corporation. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"cameo\/runtime\/app\/cameo_main_delegate.h\"\n#include \"content\/public\/app\/content_main.h\"\n\n#if defined(OS_WIN)\n#include \"content\/public\/app\/startup_helper_win.h\"\n#include \"sandbox\/win\/src\/sandbox_types.h\"\n#endif\n\n#if defined(OS_WIN)\nint APIENTRY wWinMain(HINSTANCE instance, HINSTANCE, wchar_t*, int) {\n sandbox::SandboxInterfaceInfo sandbox_info = {0};\n content::InitializeSandboxInfo(&sandbox_info);\n cameo::CameoMainDelegate delegate;\n return content::ContentMain(instance, &sandbox_info, &delegate);\n}\n#elif defined(OS_LINUX)\nint main(int argc, const char** argv) {\n cameo::CameoMainDelegate delegate;\n return content::ContentMain(argc, argv, &delegate);\n}\n#else\n#error \"Unsupport platform.\"\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2009 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/renderer\/devtools_agent_filter.h\"\n\n#include \"base\/message_loop.h\"\n#include \"chrome\/common\/devtools_messages.h\"\n#include \"chrome\/common\/render_messages.h\"\n#include \"chrome\/renderer\/devtools_agent.h\"\n#include \"chrome\/renderer\/plugin_channel_host.h\"\n#include \"chrome\/renderer\/render_view.h\"\n#include \"third_party\/WebKit\/WebKit\/chromium\/public\/WebDevToolsAgent.h\"\n#include \"third_party\/WebKit\/WebKit\/chromium\/public\/WebDevToolsMessageData.h\"\n#include \"third_party\/WebKit\/WebKit\/chromium\/public\/WebString.h\"\n#include \"webkit\/glue\/devtools_message_data.h\"\n\nusing WebKit::WebDevToolsAgent;\nusing WebKit::WebDevToolsMessageData;\nusing WebKit::WebDevToolsMessageTransport;\nusing WebKit::WebString;\n\n\/\/ static\nvoid DevToolsAgentFilter::DispatchMessageLoop() {\n MessageLoop* current = MessageLoop::current();\n bool old_state = current->NestableTasksAllowed();\n current->SetNestableTasksAllowed(true);\n current->RunAllPending();\n current->SetNestableTasksAllowed(old_state);\n}\n\n\/\/ static\nIPC::Channel* DevToolsAgentFilter::channel_ = NULL;\n\/\/ static\nint DevToolsAgentFilter::current_routing_id_ = 0;\n\nDevToolsAgentFilter::DevToolsAgentFilter()\n : message_handled_(false) {\n WebDevToolsAgent::setMessageLoopDispatchHandler(\n &DevToolsAgentFilter::DispatchMessageLoop);\n}\n\nDevToolsAgentFilter::~DevToolsAgentFilter() {\n}\n\nbool DevToolsAgentFilter::OnMessageReceived(const IPC::Message& message) {\n \/\/ Dispatch debugger commands directly from IO.\n message_handled_ = true;\n current_routing_id_ = message.routing_id();\n IPC_BEGIN_MESSAGE_MAP(DevToolsAgentFilter, message)\n IPC_MESSAGE_HANDLER(DevToolsAgentMsg_DebuggerCommand, OnDebuggerCommand)\n IPC_MESSAGE_HANDLER(DevToolsAgentMsg_DebuggerPauseScript,\n OnDebuggerPauseScript)\n IPC_MESSAGE_HANDLER(DevToolsAgentMsg_RpcMessage, OnRpcMessage)\n IPC_MESSAGE_UNHANDLED(message_handled_ = false)\n IPC_END_MESSAGE_MAP()\n return message_handled_;\n}\n\nvoid DevToolsAgentFilter::OnDebuggerCommand(const std::string& command) {\n WebDevToolsAgent::executeDebuggerCommand(\n WebString::fromUTF8(command), current_routing_id_);\n}\n\nvoid DevToolsAgentFilter::OnDebuggerPauseScript() {\n WebDevToolsAgent::debuggerPauseScript();\n}\n\nnamespace {\n\nclass WebDevToolsMessageTransportImpl : public WebDevToolsMessageTransport {\n public:\n void sendMessageToFrontendOnIOThread(const WebDevToolsMessageData& data) {\n DevToolsAgentFilter::SendRpcMessage(DevToolsMessageData(data));\n }\n};\n\n} \/\/ namespace\n\nvoid DevToolsAgentFilter::OnRpcMessage(const DevToolsMessageData& data) {\n WebDevToolsMessageTransportImpl transport;\n message_handled_ = WebDevToolsAgent::dispatchMessageFromFrontendOnIOThread(\n &transport,\n data.ToWebDevToolsMessageData());\n}\n\n\/\/ static\nvoid DevToolsAgentFilter::SendRpcMessage(const DevToolsMessageData& data) {\n IPC::Message* m = new ViewHostMsg_ForwardToDevToolsClient(\n current_routing_id_,\n DevToolsClientMsg_RpcMessage(data));\n channel_->Send(m);\n}\n<commit_msg>Include WebDevToolsMessageTransport.h in devtools_agent_filter.cc<commit_after>\/\/ Copyright (c) 2009 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/renderer\/devtools_agent_filter.h\"\n\n#include \"base\/message_loop.h\"\n#include \"chrome\/common\/devtools_messages.h\"\n#include \"chrome\/common\/render_messages.h\"\n#include \"chrome\/renderer\/devtools_agent.h\"\n#include \"chrome\/renderer\/plugin_channel_host.h\"\n#include \"chrome\/renderer\/render_view.h\"\n#include \"third_party\/WebKit\/WebKit\/chromium\/public\/WebDevToolsAgent.h\"\n#include \"third_party\/WebKit\/WebKit\/chromium\/public\/WebDevToolsMessageData.h\"\n#include \"third_party\/WebKit\/WebKit\/chromium\/public\/WebDevToolsMessageTransport.h\"\n#include \"third_party\/WebKit\/WebKit\/chromium\/public\/WebString.h\"\n#include \"webkit\/glue\/devtools_message_data.h\"\n\nusing WebKit::WebDevToolsAgent;\nusing WebKit::WebDevToolsMessageData;\nusing WebKit::WebDevToolsMessageTransport;\nusing WebKit::WebString;\n\n\/\/ static\nvoid DevToolsAgentFilter::DispatchMessageLoop() {\n MessageLoop* current = MessageLoop::current();\n bool old_state = current->NestableTasksAllowed();\n current->SetNestableTasksAllowed(true);\n current->RunAllPending();\n current->SetNestableTasksAllowed(old_state);\n}\n\n\/\/ static\nIPC::Channel* DevToolsAgentFilter::channel_ = NULL;\n\/\/ static\nint DevToolsAgentFilter::current_routing_id_ = 0;\n\nDevToolsAgentFilter::DevToolsAgentFilter()\n : message_handled_(false) {\n WebDevToolsAgent::setMessageLoopDispatchHandler(\n &DevToolsAgentFilter::DispatchMessageLoop);\n}\n\nDevToolsAgentFilter::~DevToolsAgentFilter() {\n}\n\nbool DevToolsAgentFilter::OnMessageReceived(const IPC::Message& message) {\n \/\/ Dispatch debugger commands directly from IO.\n message_handled_ = true;\n current_routing_id_ = message.routing_id();\n IPC_BEGIN_MESSAGE_MAP(DevToolsAgentFilter, message)\n IPC_MESSAGE_HANDLER(DevToolsAgentMsg_DebuggerCommand, OnDebuggerCommand)\n IPC_MESSAGE_HANDLER(DevToolsAgentMsg_DebuggerPauseScript,\n OnDebuggerPauseScript)\n IPC_MESSAGE_HANDLER(DevToolsAgentMsg_RpcMessage, OnRpcMessage)\n IPC_MESSAGE_UNHANDLED(message_handled_ = false)\n IPC_END_MESSAGE_MAP()\n return message_handled_;\n}\n\nvoid DevToolsAgentFilter::OnDebuggerCommand(const std::string& command) {\n WebDevToolsAgent::executeDebuggerCommand(\n WebString::fromUTF8(command), current_routing_id_);\n}\n\nvoid DevToolsAgentFilter::OnDebuggerPauseScript() {\n WebDevToolsAgent::debuggerPauseScript();\n}\n\nnamespace {\n\nclass WebDevToolsMessageTransportImpl : public WebDevToolsMessageTransport {\n public:\n void sendMessageToFrontendOnIOThread(const WebDevToolsMessageData& data) {\n DevToolsAgentFilter::SendRpcMessage(DevToolsMessageData(data));\n }\n};\n\n} \/\/ namespace\n\nvoid DevToolsAgentFilter::OnRpcMessage(const DevToolsMessageData& data) {\n WebDevToolsMessageTransportImpl transport;\n message_handled_ = WebDevToolsAgent::dispatchMessageFromFrontendOnIOThread(\n &transport,\n data.ToWebDevToolsMessageData());\n}\n\n\/\/ static\nvoid DevToolsAgentFilter::SendRpcMessage(const DevToolsMessageData& data) {\n IPC::Message* m = new ViewHostMsg_ForwardToDevToolsClient(\n current_routing_id_,\n DevToolsClientMsg_RpcMessage(data));\n channel_->Send(m);\n}\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: accessibleselectionhelper.hxx,v $\n *\n * $Revision: 1.7 $\n *\n * last change: $Author: rt $ $Date: 2005-09-08 02:26:16 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef COMPHELPER_ACCESSIBLE_SELECTION_HELPER_HXX\n#define COMPHELPER_ACCESSIBLE_SELECTION_HELPER_HXX\n\n#ifndef _COMPHELPER_UNO3_HXX_\n#include <comphelper\/uno3.hxx>\n#endif\n#ifndef COMPHELPER_ACCESSIBLE_CONTEXT_HELPER_HXX\n#include <comphelper\/accessiblecomponenthelper.hxx>\n#endif\n#ifndef _CPPUHELPER_IMPLBASE1_HXX_\n#include <cppuhelper\/implbase1.hxx>\n#endif\n#ifndef _COMPHELPER_UNO3_HXX_\n#include <comphelper\/uno3.hxx>\n#endif\n\n#ifndef _COM_SUN_STAR_ACCESSIBILITY_XACCESSIBLESELECTION_HPP_\n#include <com\/sun\/star\/accessibility\/XAccessibleSelection.hpp>\n#endif\n#ifndef INCLUDED_COMPHELPERDLLAPI_H\n#include \"comphelper\/comphelperdllapi.h\"\n#endif\n\n#define ACCESSIBLE_SELECTION_CHILD_ALL ((sal_Int32)-1)\n#define ACCESSIBLE_SELECTION_CHILD_SELF ((sal_Int32)-2)\n\n\/\/.........................................................................\nnamespace comphelper\n{\n\/\/.........................................................................\n\n \/\/=====================================================================\n \/\/= OCommonAccessibleSelection\n \/\/=====================================================================\n \/** base class encapsulating common functionality for the helper classes implementing\n the XAccessibleSelection\n *\/\n class COMPHELPER_DLLPUBLIC OCommonAccessibleSelection\n {\n protected:\n\n OCommonAccessibleSelection();\n\n protected:\n\n \/\/ access to context - still waiting to be overwritten\n virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessibleContext >\n implGetAccessibleContext()\n throw ( ::com::sun::star::uno::RuntimeException ) = 0;\n\n \/\/ return if the specified child is visible => watch for special ChildIndexes (ACCESSIBLE_SELECTION_CHILD_xxx)\n virtual sal_Bool\n implIsSelected( sal_Int32 nAccessibleChildIndex )\n throw (::com::sun::star::uno::RuntimeException) = 0;\n\n \/\/ select the specified child => watch for special ChildIndexes (ACCESSIBLE_SELECTION_CHILD_xxx)\n virtual void\n implSelect( sal_Int32 nAccessibleChildIndex, sal_Bool bSelect )\n throw (::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::uno::RuntimeException) = 0;\n\n protected:\n\n \/** non-virtual versions of the methods which can be implemented using <method>implIsSelected<\/method> and <method>implSelect<\/method>\n *\/\n void SAL_CALL selectAccessibleChild( sal_Int32 nChildIndex ) throw (::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::uno::RuntimeException);\n sal_Bool SAL_CALL isAccessibleChildSelected( sal_Int32 nChildIndex ) throw (::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::uno::RuntimeException);\n void SAL_CALL clearAccessibleSelection( ) throw (::com::sun::star::uno::RuntimeException);\n void SAL_CALL selectAllAccessibleChildren( ) throw (::com::sun::star::uno::RuntimeException);\n sal_Int32 SAL_CALL getSelectedAccessibleChildCount( ) throw (::com::sun::star::uno::RuntimeException);\n ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible > SAL_CALL getSelectedAccessibleChild( sal_Int32 nSelectedChildIndex ) throw (::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::uno::RuntimeException);\n void SAL_CALL deselectAccessibleChild( sal_Int32 nSelectedChildIndex ) throw (::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::uno::RuntimeException);\n };\n\n \/\/=====================================================================\n \/\/= OAccessibleSelectionHelper\n \/\/=====================================================================\n\n typedef ::cppu::ImplHelper1< ::com::sun::star::accessibility::XAccessibleSelection > OAccessibleSelectionHelper_Base;\n\n \/** a helper class for implementing an AccessibleSelection which at the same time\n supports an XAccessibleSelection interface.\n *\/\n class COMPHELPER_DLLPUBLIC OAccessibleSelectionHelper : public OAccessibleComponentHelper,\n public OCommonAccessibleSelection,\n public OAccessibleSelectionHelper_Base\n {\n protected:\n\n OAccessibleSelectionHelper( );\n\n \/\/\/ see the respective base class ctor for an extensive comment on this, please\n OAccessibleSelectionHelper( IMutex* _pExternalLock );\n\n \/\/ return ourself here by default\n virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessibleContext > implGetAccessibleContext() throw ( ::com::sun::star::uno::RuntimeException );\n\n public:\n\n \/\/ XInterface\n DECLARE_XINTERFACE( )\n DECLARE_XTYPEPROVIDER( )\n\n \/\/ XAccessibleSelection - default implementations\n virtual void SAL_CALL selectAccessibleChild( sal_Int32 nChildIndex ) throw (::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::uno::RuntimeException);\n virtual sal_Bool SAL_CALL isAccessibleChildSelected( sal_Int32 nChildIndex ) throw (::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::uno::RuntimeException);\n virtual void SAL_CALL clearAccessibleSelection( ) throw (::com::sun::star::uno::RuntimeException);\n virtual void SAL_CALL selectAllAccessibleChildren( ) throw (::com::sun::star::uno::RuntimeException);\n virtual sal_Int32 SAL_CALL getSelectedAccessibleChildCount( ) throw (::com::sun::star::uno::RuntimeException);\n virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible > SAL_CALL getSelectedAccessibleChild( sal_Int32 nSelectedChildIndex ) throw (::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::uno::RuntimeException);\n virtual void SAL_CALL deselectAccessibleChild( sal_Int32 nSelectedChildIndex ) throw (::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::uno::RuntimeException);\n };\n\n\/\/.........................................................................\n} \/\/ namespace comphelper\n\/\/.........................................................................\n\n#endif \/\/ COMPHELPER_ACCESSIBLE_SELECTION_HELPER_HXX\n\n<commit_msg>INTEGRATION: CWS changefileheader (1.7.246); FILE MERGED 2008\/04\/01 15:05:17 thb 1.7.246.3: #i85898# Stripping all external header guards 2008\/04\/01 12:26:23 thb 1.7.246.2: #i85898# Stripping all external header guards 2008\/03\/31 12:19:27 rt 1.7.246.1: #i87441# Change license header to LPGL v3.<commit_after>\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2008 by Sun Microsystems, Inc.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: accessibleselectionhelper.hxx,v $\n * $Revision: 1.8 $\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * <http:\/\/www.openoffice.org\/license.html>\n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n#ifndef COMPHELPER_ACCESSIBLE_SELECTION_HELPER_HXX\n#define COMPHELPER_ACCESSIBLE_SELECTION_HELPER_HXX\n\n#include <comphelper\/uno3.hxx>\n#ifndef COMPHELPER_ACCESSIBLE_CONTEXT_HELPER_HXX\n#include <comphelper\/accessiblecomponenthelper.hxx>\n#endif\n#include <cppuhelper\/implbase1.hxx>\n#include <comphelper\/uno3.hxx>\n#include <com\/sun\/star\/accessibility\/XAccessibleSelection.hpp>\n#include \"comphelper\/comphelperdllapi.h\"\n\n#define ACCESSIBLE_SELECTION_CHILD_ALL ((sal_Int32)-1)\n#define ACCESSIBLE_SELECTION_CHILD_SELF ((sal_Int32)-2)\n\n\/\/.........................................................................\nnamespace comphelper\n{\n\/\/.........................................................................\n\n \/\/=====================================================================\n \/\/= OCommonAccessibleSelection\n \/\/=====================================================================\n \/** base class encapsulating common functionality for the helper classes implementing\n the XAccessibleSelection\n *\/\n class COMPHELPER_DLLPUBLIC OCommonAccessibleSelection\n {\n protected:\n\n OCommonAccessibleSelection();\n\n protected:\n\n \/\/ access to context - still waiting to be overwritten\n virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessibleContext >\n implGetAccessibleContext()\n throw ( ::com::sun::star::uno::RuntimeException ) = 0;\n\n \/\/ return if the specified child is visible => watch for special ChildIndexes (ACCESSIBLE_SELECTION_CHILD_xxx)\n virtual sal_Bool\n implIsSelected( sal_Int32 nAccessibleChildIndex )\n throw (::com::sun::star::uno::RuntimeException) = 0;\n\n \/\/ select the specified child => watch for special ChildIndexes (ACCESSIBLE_SELECTION_CHILD_xxx)\n virtual void\n implSelect( sal_Int32 nAccessibleChildIndex, sal_Bool bSelect )\n throw (::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::uno::RuntimeException) = 0;\n\n protected:\n\n \/** non-virtual versions of the methods which can be implemented using <method>implIsSelected<\/method> and <method>implSelect<\/method>\n *\/\n void SAL_CALL selectAccessibleChild( sal_Int32 nChildIndex ) throw (::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::uno::RuntimeException);\n sal_Bool SAL_CALL isAccessibleChildSelected( sal_Int32 nChildIndex ) throw (::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::uno::RuntimeException);\n void SAL_CALL clearAccessibleSelection( ) throw (::com::sun::star::uno::RuntimeException);\n void SAL_CALL selectAllAccessibleChildren( ) throw (::com::sun::star::uno::RuntimeException);\n sal_Int32 SAL_CALL getSelectedAccessibleChildCount( ) throw (::com::sun::star::uno::RuntimeException);\n ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible > SAL_CALL getSelectedAccessibleChild( sal_Int32 nSelectedChildIndex ) throw (::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::uno::RuntimeException);\n void SAL_CALL deselectAccessibleChild( sal_Int32 nSelectedChildIndex ) throw (::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::uno::RuntimeException);\n };\n\n \/\/=====================================================================\n \/\/= OAccessibleSelectionHelper\n \/\/=====================================================================\n\n typedef ::cppu::ImplHelper1< ::com::sun::star::accessibility::XAccessibleSelection > OAccessibleSelectionHelper_Base;\n\n \/** a helper class for implementing an AccessibleSelection which at the same time\n supports an XAccessibleSelection interface.\n *\/\n class COMPHELPER_DLLPUBLIC OAccessibleSelectionHelper : public OAccessibleComponentHelper,\n public OCommonAccessibleSelection,\n public OAccessibleSelectionHelper_Base\n {\n protected:\n\n OAccessibleSelectionHelper( );\n\n \/\/\/ see the respective base class ctor for an extensive comment on this, please\n OAccessibleSelectionHelper( IMutex* _pExternalLock );\n\n \/\/ return ourself here by default\n virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessibleContext > implGetAccessibleContext() throw ( ::com::sun::star::uno::RuntimeException );\n\n public:\n\n \/\/ XInterface\n DECLARE_XINTERFACE( )\n DECLARE_XTYPEPROVIDER( )\n\n \/\/ XAccessibleSelection - default implementations\n virtual void SAL_CALL selectAccessibleChild( sal_Int32 nChildIndex ) throw (::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::uno::RuntimeException);\n virtual sal_Bool SAL_CALL isAccessibleChildSelected( sal_Int32 nChildIndex ) throw (::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::uno::RuntimeException);\n virtual void SAL_CALL clearAccessibleSelection( ) throw (::com::sun::star::uno::RuntimeException);\n virtual void SAL_CALL selectAllAccessibleChildren( ) throw (::com::sun::star::uno::RuntimeException);\n virtual sal_Int32 SAL_CALL getSelectedAccessibleChildCount( ) throw (::com::sun::star::uno::RuntimeException);\n virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible > SAL_CALL getSelectedAccessibleChild( sal_Int32 nSelectedChildIndex ) throw (::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::uno::RuntimeException);\n virtual void SAL_CALL deselectAccessibleChild( sal_Int32 nSelectedChildIndex ) throw (::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::uno::RuntimeException);\n };\n\n\/\/.........................................................................\n} \/\/ namespace comphelper\n\/\/.........................................................................\n\n#endif \/\/ COMPHELPER_ACCESSIBLE_SELECTION_HELPER_HXX\n\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: BorderHandler.cxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: os $ $Date: 2007-05-03 06:25:37 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n#ifndef INCLUDED_BORDERHANDLER_HXX\n#include <BorderHandler.hxx>\n#endif\n#ifndef INCLUDED_DMAPPER_PROPERTYMAP_HXX\n#include <PropertyMap.hxx>\n#endif\n#ifndef INCLUDED_RESOURCESIDS\n#include <doctok\/resourceids.hxx>\n#endif\n#ifndef INCLUDED_DMAPPER_CONVERSIONHELPER_HXX\n#include <ConversionHelper.hxx>\n#endif\n#ifndef _COM_SUN_STAR_TABLE_BORDERLINE_HPP_\n#include <com\/sun\/star\/table\/BorderLine.hpp>\n#endif\n\nnamespace dmapper {\n\nusing namespace ::com::sun::star;\nusing namespace writerfilter;\n\/\/using namespace ::std;\n\n\/*-- 24.04.2007 09:06:35---------------------------------------------------\n\n -----------------------------------------------------------------------*\/\nBorderHandler::BorderHandler() :\n m_nCurrentBorderPosition( BORDER_TOP ),\n m_nLineWidth(0),\n m_nLineType(0),\n m_nLineColor(0),\n m_nLineDistance(0)\n{\n}\n\/*-- 24.04.2007 09:06:35---------------------------------------------------\n\n -----------------------------------------------------------------------*\/\nBorderHandler::~BorderHandler()\n{\n}\n\/*-- 24.04.2007 09:06:35---------------------------------------------------\n\n -----------------------------------------------------------------------*\/\nvoid BorderHandler::attribute(doctok::Id rName, doctok::Value & rVal)\n{\n sal_Int32 nIntValue = rVal.getInt();\n switch( rName )\n {\n case NS_rtf::LN_rgbrc:\n {\n doctok::Reference<Properties>::Pointer_t pProperties = rVal.getProperties();\n if( pProperties.get())\n {\n pProperties->resolve(*this);\n \/\/\n\/\/ table::BorderLine* pToFill = 0;\n\/\/ switch(m_nCurrentBorderPosition)\n\/\/ {\n\/\/ case BORDER_TOP:\n\/\/ pToFill = &m_aTableBorder.TopLine;\n\/\/ m_aTableBorder.IsTopLineValid = sal_True;\n\/\/ break;\n\/\/ case BORDER_LEFT:\n\/\/ pToFill = &m_aTableBorder.LeftLine;\n\/\/ m_aTableBorder.IsLeftLineValid = sal_True;\n\/\/ break;\n\/\/ case BORDER_BOTTOM:\n\/\/ pToFill = &m_aTableBorder.BottomLine;\n\/\/ m_aTableBorder.IsBottomLineValid = sal_True;;\n\/\/ break;\n\/\/ case BORDER_RIGHT:\n\/\/ pToFill = &m_aTableBorder.RightLine;\n\/\/ m_aTableBorder.IsRightLineValid = sal_True;\n\/\/ break;\n\/\/ case BORDER_HORIZONTAL:\n\/\/ pToFill = &m_aTableBorder.HorizontalLine;\n\/\/ m_aTableBorder.IsHorizontalLineValid = sal_True;;\n\/\/ break;\n\/\/ case BORDER_VERTICAL:\n\/\/ m_aTableBorder.IsVerticalLineValid = sal_True;;\n\/\/ default:\n\/\/ pToFill = &m_aTableBorder.VerticalLine; break;\n\/\/ }\n ConversionHelper::MakeBorderLine( m_nLineWidth, m_nLineType, m_nLineColor,\n m_aBorderLines[m_nCurrentBorderPosition] );\n OSL_ENSURE(m_nCurrentBorderPosition < BORDER_COUNT, \"too many border values\");\n ++m_nCurrentBorderPosition;\n }\n }\n break;\n case NS_rtf::LN_DPTLINEWIDTH: \/\/ 0x2871\n \/\/ width of a single line in 1\/8 pt, max of 32 pt -> twip * 5 \/ 2.\n m_nLineWidth = ConversionHelper::convertToMM100( nIntValue * 5 \/ 2 );\n break;\n case NS_rtf::LN_BRCTYPE: \/\/ 0x2872\n m_nLineType = nIntValue;\n break;\n case NS_rtf::LN_ICO: \/\/ 0x2873\n m_nLineColor = nIntValue;\n break;\n case NS_rtf::LN_DPTSPACE: \/\/ 0x2874\n m_nLineDistance = nIntValue;\n break;\n case NS_rtf::LN_FSHADOW: \/\/ 0x2875\n \/\/if 1 then line has shadow - unsupported\n case NS_rtf::LN_FFRAME: \/\/ 0x2876\n case NS_rtf::LN_UNUSED2_15: \/\/ 0x2877\n \/\/ ignored\n break;\n default:\n OSL_ASSERT(\"unknown attribute\");\n }\n}\n\/*-- 24.04.2007 09:06:35---------------------------------------------------\n\n -----------------------------------------------------------------------*\/\nvoid BorderHandler::sprm(doctok::Sprm & rSprm)\n{\n (void)rSprm;\n}\n\/*-- 24.04.2007 09:09:01---------------------------------------------------\n\n -----------------------------------------------------------------------*\/\nPropertyMapPtr BorderHandler::getProperties()\n{\n static const PropertyIds aPropNames[BORDER_COUNT] =\n {\n PROP_TOP_BORDER,\n PROP_LEFT_BORDER,\n PROP_BOTTOM_BORDER,\n PROP_RIGHT_BORDER,\n META_PROP_HORIZONTAL_BORDER,\n META_PROP_VERTICAL_BORDER\n };\n PropertyMapPtr pPropertyMap(new PropertyMap);\n for( sal_Int32 nProp = 0; nProp < BORDER_COUNT; ++nProp)\n pPropertyMap->Insert( aPropNames[nProp], uno::makeAny( m_aBorderLines[nProp] ) );\n return pPropertyMap;\n}\n} \/\/namespace dmapper\n<commit_msg>don't apply default borders<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: BorderHandler.cxx,v $\n *\n * $Revision: 1.4 $\n *\n * last change: $Author: os $ $Date: 2007-05-24 11:31:43 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n#ifndef INCLUDED_BORDERHANDLER_HXX\n#include <BorderHandler.hxx>\n#endif\n#ifndef INCLUDED_DMAPPER_PROPERTYMAP_HXX\n#include <PropertyMap.hxx>\n#endif\n#ifndef INCLUDED_RESOURCESIDS\n#include <doctok\/resourceids.hxx>\n#endif\n#ifndef INCLUDED_DMAPPER_CONVERSIONHELPER_HXX\n#include <ConversionHelper.hxx>\n#endif\n#ifndef _COM_SUN_STAR_TABLE_BORDERLINE_HPP_\n#include <com\/sun\/star\/table\/BorderLine.hpp>\n#endif\n\nnamespace dmapper {\n\nusing namespace ::com::sun::star;\nusing namespace writerfilter;\n\/\/using namespace ::std;\n\n\/*-- 24.04.2007 09:06:35---------------------------------------------------\n\n -----------------------------------------------------------------------*\/\nBorderHandler::BorderHandler() :\n m_nCurrentBorderPosition( BORDER_TOP ),\n m_nLineWidth(0),\n m_nLineType(0),\n m_nLineColor(0),\n m_nLineDistance(0)\n{\n}\n\/*-- 24.04.2007 09:06:35---------------------------------------------------\n\n -----------------------------------------------------------------------*\/\nBorderHandler::~BorderHandler()\n{\n}\n\/*-- 24.04.2007 09:06:35---------------------------------------------------\n\n -----------------------------------------------------------------------*\/\nvoid BorderHandler::attribute(doctok::Id rName, doctok::Value & rVal)\n{\n sal_Int32 nIntValue = rVal.getInt();\n switch( rName )\n {\n case NS_rtf::LN_rgbrc:\n {\n doctok::Reference<Properties>::Pointer_t pProperties = rVal.getProperties();\n if( pProperties.get())\n {\n pProperties->resolve(*this);\n \/\/\n\/\/ table::BorderLine* pToFill = 0;\n\/\/ switch(m_nCurrentBorderPosition)\n\/\/ {\n\/\/ case BORDER_TOP:\n\/\/ pToFill = &m_aTableBorder.TopLine;\n\/\/ m_aTableBorder.IsTopLineValid = sal_True;\n\/\/ break;\n\/\/ case BORDER_LEFT:\n\/\/ pToFill = &m_aTableBorder.LeftLine;\n\/\/ m_aTableBorder.IsLeftLineValid = sal_True;\n\/\/ break;\n\/\/ case BORDER_BOTTOM:\n\/\/ pToFill = &m_aTableBorder.BottomLine;\n\/\/ m_aTableBorder.IsBottomLineValid = sal_True;;\n\/\/ break;\n\/\/ case BORDER_RIGHT:\n\/\/ pToFill = &m_aTableBorder.RightLine;\n\/\/ m_aTableBorder.IsRightLineValid = sal_True;\n\/\/ break;\n\/\/ case BORDER_HORIZONTAL:\n\/\/ pToFill = &m_aTableBorder.HorizontalLine;\n\/\/ m_aTableBorder.IsHorizontalLineValid = sal_True;;\n\/\/ break;\n\/\/ case BORDER_VERTICAL:\n\/\/ m_aTableBorder.IsVerticalLineValid = sal_True;;\n\/\/ default:\n\/\/ pToFill = &m_aTableBorder.VerticalLine; break;\n\/\/ }\n ConversionHelper::MakeBorderLine( m_nLineWidth, m_nLineType, m_nLineColor,\n m_aBorderLines[m_nCurrentBorderPosition] );\n OSL_ENSURE(m_nCurrentBorderPosition < BORDER_COUNT, \"too many border values\");\n ++m_nCurrentBorderPosition;\n }\n }\n break;\n case NS_rtf::LN_DPTLINEWIDTH: \/\/ 0x2871\n \/\/ width of a single line in 1\/8 pt, max of 32 pt -> twip * 5 \/ 2.\n m_nLineWidth = ConversionHelper::convertToMM100( nIntValue * 5 \/ 2 );\n break;\n case NS_rtf::LN_BRCTYPE: \/\/ 0x2872\n m_nLineType = nIntValue;\n break;\n case NS_rtf::LN_ICO: \/\/ 0x2873\n m_nLineColor = nIntValue;\n break;\n case NS_rtf::LN_DPTSPACE: \/\/ 0x2874\n m_nLineDistance = nIntValue;\n break;\n case NS_rtf::LN_FSHADOW: \/\/ 0x2875\n \/\/if 1 then line has shadow - unsupported\n case NS_rtf::LN_FFRAME: \/\/ 0x2876\n case NS_rtf::LN_UNUSED2_15: \/\/ 0x2877\n \/\/ ignored\n break;\n default:\n OSL_ASSERT(\"unknown attribute\");\n }\n}\n\/*-- 24.04.2007 09:06:35---------------------------------------------------\n\n -----------------------------------------------------------------------*\/\nvoid BorderHandler::sprm(doctok::Sprm & rSprm)\n{\n (void)rSprm;\n}\n\/*-- 24.04.2007 09:09:01---------------------------------------------------\n\n -----------------------------------------------------------------------*\/\nPropertyMapPtr BorderHandler::getProperties()\n{\n static const PropertyIds aPropNames[BORDER_COUNT] =\n {\n PROP_TOP_BORDER,\n PROP_LEFT_BORDER,\n PROP_BOTTOM_BORDER,\n PROP_RIGHT_BORDER,\n META_PROP_HORIZONTAL_BORDER,\n META_PROP_VERTICAL_BORDER\n };\n PropertyMapPtr pPropertyMap(new PropertyMap);\n \/\/ don't fill in default properties\n if( m_nCurrentBorderPosition )\n {\n for( sal_Int32 nProp = 0; nProp < BORDER_COUNT; ++nProp)\n pPropertyMap->Insert( aPropNames[nProp], uno::makeAny( m_aBorderLines[nProp] ) );\n }\n return pPropertyMap;\n}\n} \/\/namespace dmapper\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (C) 2004-2011 See the AUTHORS file for details.\n *\n * This program is free software; you can redistribute it and\/or modify it\n * under the terms of the GNU General Public License version 2 as published\n * by the Free Software Foundation.\n *\/\n\n#define REQUIRESSL\n\n#include \"Modules.h\"\n#include \"User.h\"\n#include \"Listener.h\"\n#include \"znc.h\"\n\nclass CSSLClientCertMod : public CGlobalModule {\npublic:\n\tGLOBALMODCONSTRUCTOR(CSSLClientCertMod) {}\n\tvirtual ~CSSLClientCertMod() {}\n\n\tvirtual bool OnBoot() {\n\t\tconst vector<CListener*>& vListeners = CZNC::Get().GetListeners();\n\t\tvector<CListener*>::const_iterator it;\n\n\t\t\/\/ We need the SSL_VERIFY_PEER flag on all listeners, or else\n\t\t\/\/ the client doesn't send a ssl cert\n\t\tfor (it = vListeners.begin(); it != vListeners.end(); it++)\n\t\t\t(*it)->GetRealListener()->SetRequireClientCertFlags(SSL_VERIFY_PEER);\n\n\t\tMCString::iterator it1;\n\t\tfor (it1 = BeginNV(); it1 != EndNV(); it1++) {\n\t\t\tVCString vsKeys;\n\t\t\tVCString::iterator it2;\n\n\t\t\tif (CZNC::Get().FindUser(it1->first) == NULL) {\n\t\t\t\tDEBUG(\"Unknown user in saved data [\" + it1->first + \"]\");\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tit1->second.Split(\" \", vsKeys, false);\n\t\t\tfor (it2 = vsKeys.begin(); it2 != vsKeys.end(); it2++) {\n\t\t\t\tm_PubKeys[it1->first].insert(*it2);\n\t\t\t}\n\t\t}\n\n\t\treturn true;\n\t}\n\n\tvirtual void OnPostRehash() {\n\t\tOnBoot();\n\t}\n\n\tvirtual bool OnLoad(const CString& sArgs, CString& sMessage) {\n\t\tOnBoot();\n\n\t\treturn true;\n\t}\n\n\tbool Save() {\n\t\tMSCString::iterator it;\n\n\t\tClearNV(false);\n\t\tfor (it = m_PubKeys.begin(); it != m_PubKeys.end(); it++) {\n\t\t\tCString sVal;\n\t\t\tSCString::iterator it2;\n\t\t\tfor (it2 = it->second.begin(); it2 != it->second.end(); it2++) {\n\t\t\t\tsVal += *it2 + \" \";\n\t\t\t}\n\n\t\t\tif (!sVal.empty())\n\t\t\t\tSetNV(it->first, sVal, false);\n\t\t}\n\n\t\treturn SaveRegistry();\n\t}\n\n\tvirtual EModRet OnLoginAttempt(CSmartPtr<CAuthBase> Auth) {\n\t\tCString sUser = Auth->GetUsername();\n\t\tCsock *pSock = Auth->GetSocket();\n\t\tCUser *pUser = CZNC::Get().FindUser(sUser);\n\n\t\tif (pSock == NULL || pUser == NULL)\n\t\t\treturn CONTINUE;\n\n\t\tCString sPubKey = GetKey(pSock);\n\t\tDEBUG(\"User: \" << sUser << \" Key: \" << sPubKey);\n\n\t\tif (sPubKey.empty()) {\n\t\t\tDEBUG(\"Peer got no public key, ignoring\");\n\t\t\treturn CONTINUE;\n\t\t}\n\n\t\tMSCString::iterator it = m_PubKeys.find(sUser);\n\t\tif (it == m_PubKeys.end()) {\n\t\t\tDEBUG(\"No saved pubkeys for this client\");\n\t\t\treturn CONTINUE;\n\t\t}\n\n\t\tSCString::iterator it2 = it->second.find(sPubKey);\n\t\tif (it2 == it->second.end()) {\n\t\t\tDEBUG(\"Invalid pubkey\");\n\t\t\treturn CONTINUE;\n\t\t}\n\n\t\t\/\/ This client uses a valid pubkey for this user, let them in\n\t\tDEBUG(\"Accepted pubkey auth\");\n\t\tAuth->AcceptLogin(*pUser);\n\n\t\treturn HALT;\n\t}\n\n\tvirtual void OnModCommand(const CString& sCommand) {\n\t\tCString sCmd = sCommand.Token(0);\n\n\t\tif (sCmd.Equals(\"show\")) {\n\t\t\tCString sPubKey = GetKey(m_pClient);\n\t\t\tif (sPubKey.empty())\n\t\t\t\tPutModule(\"You are not connected with any valid public key\");\n\t\t\telse\n\t\t\t\tPutModule(\"Your current public key is: \" + sPubKey);\n\t\t} else if (sCmd.Equals(\"add\")) {\n\t\t\tCString sPubKey = GetKey(m_pClient);\n\t\t\tif (sPubKey.empty())\n\t\t\t\tPutModule(\"You are not connected with any valid public key\");\n\t\t\telse {\n\t\t\t\tpair<SCString::iterator, bool> res = m_PubKeys[m_pUser->GetUserName()].insert(sPubKey);\n\t\t\t\tif (res.second) {\n\t\t\t\t\tPutModule(\"Added your current public key to the list\");\n\t\t\t\t\tSave();\n\t\t\t\t} else\n\t\t\t\t\tPutModule(\"Your key was already added\");\n\t\t\t}\n\t\t} else if (sCmd.Equals(\"list\")) {\n\t\t\tCTable Table;\n\n\t\t\tTable.AddColumn(\"Id\");\n\t\t\tTable.AddColumn(\"Key\");\n\n\t\t\tMSCString::iterator it = m_PubKeys.find(m_pUser->GetUserName());\n\t\t\tif (it == m_PubKeys.end()) {\n\t\t\t\tPutModule(\"No keys set for your user\");\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tSCString::iterator it2;\n\t\t\tunsigned int id = 1;\n\t\t\tfor (it2 = it->second.begin(); it2 != it->second.end(); it2++) {\n\t\t\t\tTable.AddRow();\n\t\t\t\tTable.SetCell(\"Id\", CString(id++));\n\t\t\t\tTable.SetCell(\"Key\", *it2);\n\t\t\t}\n\n\t\t\tif (PutModule(Table) == 0)\n\t\t\t\t\/\/ This double check is necessary, because the\n\t\t\t\t\/\/ set could be empty.\n\t\t\t\tPutModule(\"No keys set for your user\");\n\t\t} else if (sCmd.Equals(\"del\") || sCmd.Equals(\"remove\")) {\n\t\t\tunsigned int id = sCommand.Token(1, true).ToUInt();\n\t\t\tMSCString::iterator it = m_PubKeys.find(m_pUser->GetUserName());\n\n\t\t\tif (it == m_PubKeys.end()) {\n\t\t\t\tPutModule(\"No keys set for your user\");\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (id == 0 || id > it->second.size()) {\n\t\t\t\tPutModule(\"Invalid #, check \\\"list\\\"\");\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tSCString::iterator it2 = it->second.begin();\n\t\t\twhile (id > 1) {\n\t\t\t\tit2++;\n\t\t\t\tid--;\n\t\t\t}\n\n\t\t\tit->second.erase(it2);\n\t\t\tif (it->second.size() == 0)\n\t\t\t\tm_PubKeys.erase(it);\n\t\t\tPutModule(\"Removed\");\n\n\t\t\tSave();\n\t\t} else {\n\t\t\tPutModule(\"Commands: show, list, add, del [no]\");\n\t\t}\n\t}\n\n\tCString GetKey(Csock *pSock) {\n\t\tCString sRes;\n\t\tint res = pSock->GetPeerFingerprint(sRes);\n\n\t\tDEBUG(\"GetKey() returned status \" << res << \" with key \" << sRes);\n\n\t\t\/\/ This is 'inspired' by charybdis' libratbox\n\t\tswitch (res) {\n\t\tcase X509_V_OK:\n\t\tcase X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN:\n\t\tcase X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE:\n\t\tcase X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT:\n\t\t\treturn sRes;\n\t\tdefault:\n\t\t\treturn \"\";\n\t\t}\n\t}\n\nprivate:\n\t\/\/ Maps user names to a list of allowed pubkeys\n\ttypedef map<CString, set<CString> > MSCString;\n\tMSCString m_PubKeys;\n};\n\nGLOBALMODULEDEFS(CSSLClientCertMod, \"Allow users to authenticate via SSL client certificates\")\n<commit_msg>Make certauth use the CModCommand API<commit_after>\/*\n * Copyright (C) 2004-2011 See the AUTHORS file for details.\n *\n * This program is free software; you can redistribute it and\/or modify it\n * under the terms of the GNU General Public License version 2 as published\n * by the Free Software Foundation.\n *\/\n\n#define REQUIRESSL\n\n#include \"Modules.h\"\n#include \"User.h\"\n#include \"Listener.h\"\n#include \"znc.h\"\n\nclass CSSLClientCertMod : public CGlobalModule {\npublic:\n\tGLOBALMODCONSTRUCTOR(CSSLClientCertMod) {\n\t\tAddHelpCommand();\n\t\tAddCommand(\"Add\", static_cast<CModCommand::ModCmdFunc>(&CSSLClientCertMod::HandleAddCommand));\n\t\tAddCommand(\"Del\", static_cast<CModCommand::ModCmdFunc>(&CSSLClientCertMod::HandleDelCommand),\n\t\t\t\"id\");\n\t\tAddCommand(\"List\", static_cast<CModCommand::ModCmdFunc>(&CSSLClientCertMod::HandleListCommand));\n\t\tAddCommand(\"Show\", static_cast<CModCommand::ModCmdFunc>(&CSSLClientCertMod::HandleShowCommand),\n\t\t\t\"\", \"Print your current key\");\n\t}\n\n\tvirtual ~CSSLClientCertMod() {}\n\n\tvirtual bool OnBoot() {\n\t\tconst vector<CListener*>& vListeners = CZNC::Get().GetListeners();\n\t\tvector<CListener*>::const_iterator it;\n\n\t\t\/\/ We need the SSL_VERIFY_PEER flag on all listeners, or else\n\t\t\/\/ the client doesn't send a ssl cert\n\t\tfor (it = vListeners.begin(); it != vListeners.end(); it++)\n\t\t\t(*it)->GetRealListener()->SetRequireClientCertFlags(SSL_VERIFY_PEER);\n\n\t\tMCString::iterator it1;\n\t\tfor (it1 = BeginNV(); it1 != EndNV(); it1++) {\n\t\t\tVCString vsKeys;\n\t\t\tVCString::iterator it2;\n\n\t\t\tif (CZNC::Get().FindUser(it1->first) == NULL) {\n\t\t\t\tDEBUG(\"Unknown user in saved data [\" + it1->first + \"]\");\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tit1->second.Split(\" \", vsKeys, false);\n\t\t\tfor (it2 = vsKeys.begin(); it2 != vsKeys.end(); it2++) {\n\t\t\t\tm_PubKeys[it1->first].insert(*it2);\n\t\t\t}\n\t\t}\n\n\t\treturn true;\n\t}\n\n\tvirtual void OnPostRehash() {\n\t\tOnBoot();\n\t}\n\n\tvirtual bool OnLoad(const CString& sArgs, CString& sMessage) {\n\t\tOnBoot();\n\n\t\treturn true;\n\t}\n\n\tbool Save() {\n\t\tMSCString::iterator it;\n\n\t\tClearNV(false);\n\t\tfor (it = m_PubKeys.begin(); it != m_PubKeys.end(); it++) {\n\t\t\tCString sVal;\n\t\t\tSCString::iterator it2;\n\t\t\tfor (it2 = it->second.begin(); it2 != it->second.end(); it2++) {\n\t\t\t\tsVal += *it2 + \" \";\n\t\t\t}\n\n\t\t\tif (!sVal.empty())\n\t\t\t\tSetNV(it->first, sVal, false);\n\t\t}\n\n\t\treturn SaveRegistry();\n\t}\n\n\tvirtual EModRet OnLoginAttempt(CSmartPtr<CAuthBase> Auth) {\n\t\tCString sUser = Auth->GetUsername();\n\t\tCsock *pSock = Auth->GetSocket();\n\t\tCUser *pUser = CZNC::Get().FindUser(sUser);\n\n\t\tif (pSock == NULL || pUser == NULL)\n\t\t\treturn CONTINUE;\n\n\t\tCString sPubKey = GetKey(pSock);\n\t\tDEBUG(\"User: \" << sUser << \" Key: \" << sPubKey);\n\n\t\tif (sPubKey.empty()) {\n\t\t\tDEBUG(\"Peer got no public key, ignoring\");\n\t\t\treturn CONTINUE;\n\t\t}\n\n\t\tMSCString::iterator it = m_PubKeys.find(sUser);\n\t\tif (it == m_PubKeys.end()) {\n\t\t\tDEBUG(\"No saved pubkeys for this client\");\n\t\t\treturn CONTINUE;\n\t\t}\n\n\t\tSCString::iterator it2 = it->second.find(sPubKey);\n\t\tif (it2 == it->second.end()) {\n\t\t\tDEBUG(\"Invalid pubkey\");\n\t\t\treturn CONTINUE;\n\t\t}\n\n\t\t\/\/ This client uses a valid pubkey for this user, let them in\n\t\tDEBUG(\"Accepted pubkey auth\");\n\t\tAuth->AcceptLogin(*pUser);\n\n\t\treturn HALT;\n\t}\n\n\tvoid HandleShowCommand(const CString& sLine) {\n\t\tCString sPubKey = GetKey(m_pClient);\n\n\t\tif (sPubKey.empty()) {\n\t\t\tPutModule(\"You are not connected with any valid public key\");\n\t\t} else {\n\t\t\tPutModule(\"Your current public key is: \" + sPubKey);\n\t\t}\n\t}\n\n\tvoid HandleAddCommand(const CString& sLine) {\n\t\tCString sPubKey = GetKey(m_pClient);\n\n\t\tif (sPubKey.empty()) {\n\t\t\tPutModule(\"You are not connected with any valid public key\");\n\t\t} else {\n\t\t\tpair<SCString::iterator, bool> res = m_PubKeys[m_pUser->GetUserName()].insert(sPubKey);\n\t\t\tif (res.second) {\n\t\t\t\tPutModule(\"Added your current public key to the list\");\n\t\t\t\tSave();\n\t\t\t} else {\n\t\t\t\tPutModule(\"Your key was already added\");\n\t\t\t}\n\t\t}\n\t}\n\n\tvoid HandleListCommand(const CString& sLine) {\n\t\tCTable Table;\n\n\t\tTable.AddColumn(\"Id\");\n\t\tTable.AddColumn(\"Key\");\n\n\t\tMSCString::iterator it = m_PubKeys.find(m_pUser->GetUserName());\n\t\tif (it == m_PubKeys.end()) {\n\t\t\tPutModule(\"No keys set for your user\");\n\t\t\treturn;\n\t\t}\n\n\t\tSCString::iterator it2;\n\t\tunsigned int id = 1;\n\t\tfor (it2 = it->second.begin(); it2 != it->second.end(); it2++) {\n\t\t\tTable.AddRow();\n\t\t\tTable.SetCell(\"Id\", CString(id++));\n\t\t\tTable.SetCell(\"Key\", *it2);\n\t\t}\n\n\t\tif (PutModule(Table) == 0) {\n\t\t\t\/\/ This double check is necessary, because the\n\t\t\t\/\/ set could be empty.\n\t\t\tPutModule(\"No keys set for your user\");\n\t\t}\n\t}\n\n\tvoid HandleDelCommand(const CString& sLine) {\n\t\tunsigned int id = sLine.Token(1, true).ToUInt();\n\t\tMSCString::iterator it = m_PubKeys.find(m_pUser->GetUserName());\n\n\t\tif (it == m_PubKeys.end()) {\n\t\t\tPutModule(\"No keys set for your user\");\n\t\t\treturn;\n\t\t}\n\n\t\tif (id == 0 || id > it->second.size()) {\n\t\t\tPutModule(\"Invalid #, check \\\"list\\\"\");\n\t\t\treturn;\n\t\t}\n\n\t\tSCString::iterator it2 = it->second.begin();\n\t\twhile (id > 1) {\n\t\t\tit2++;\n\t\t\tid--;\n\t\t}\n\n\t\tit->second.erase(it2);\n\t\tif (it->second.size() == 0)\n\t\t\tm_PubKeys.erase(it);\n\t\tPutModule(\"Removed\");\n\n\t\tSave();\n\t}\n\n\tCString GetKey(Csock *pSock) {\n\t\tCString sRes;\n\t\tint res = pSock->GetPeerFingerprint(sRes);\n\n\t\tDEBUG(\"GetKey() returned status \" << res << \" with key \" << sRes);\n\n\t\t\/\/ This is 'inspired' by charybdis' libratbox\n\t\tswitch (res) {\n\t\tcase X509_V_OK:\n\t\tcase X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN:\n\t\tcase X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE:\n\t\tcase X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT:\n\t\t\treturn sRes;\n\t\tdefault:\n\t\t\treturn \"\";\n\t\t}\n\t}\n\nprivate:\n\t\/\/ Maps user names to a list of allowed pubkeys\n\ttypedef map<CString, set<CString> > MSCString;\n\tMSCString m_PubKeys;\n};\n\nGLOBALMODULEDEFS(CSSLClientCertMod, \"Allow users to authenticate via SSL client certificates\")\n<|endoftext|>"} {"text":"<commit_before>\/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- *\/\n\/*\n * This file is part of the LibreOffice project.\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\n * This file incorporates work covered by the following license notice:\n *\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed\n * with this work for additional information regarding copyright\n * ownership. The ASF licenses this file to you under the Apache\n * License, Version 2.0 (the \"License\"); you may not use this file\n * except in compliance with the License. You may obtain a copy of\n * the License at http:\/\/www.apache.org\/licenses\/LICENSE-2.0 .\n *\/\n\n#ifndef INCLUDED_RTL_CHARACTER_HXX\n#define INCLUDED_RTL_CHARACTER_HXX\n\n#include \"sal\/config.h\"\n\n#include \"sal\/types.h\"\n\nnamespace rtl\n{\n\/** Check for ASCII character.\n\n @param nUtf32 Some UCS-4 character.\n\n @return True if nChar is a ASCII character (0x00--0x7F).\n\n @since LibreOffice 4.1\n *\/\ninline bool isAscii(sal_uInt32 nUtf32)\n{\n return nUtf32 <= 0x7F;\n}\n\n\/** Check for ASCII lower case character.\n\n @param nUtf32 Some UCS-4 character.\n\n @return True if nChar is a US-ASCII lower case alphabetic character\n (ASCII 'a'--'z').\n\n @since LibreOffice 4.1\n *\/\ninline bool isAsciiLowerCase(sal_uInt32 nUtf32)\n{\n return nUtf32 >= 'a' && nUtf32 <= 'z';\n}\n\n\/** Check for US-ASCII upper case character.\n\n @param nUtf32 Some UCS-4 character.\n\n @return True if nChar is a US-ASCII upper case alphabetic character\n (US-ASCII 'A'--'Z').\n\n @since LibreOffice 4.1\n *\/\ninline bool isAsciiUpperCase(sal_uInt32 nUtf32)\n{\n return nUtf32 >= 'A' && nUtf32 <= 'Z';\n}\n\n\/** Check for ASCII alphanumeric character.\n\n @param nUtf32 Some UCS-4 character.\n\n @return True if nUtf32 is a US-ASCII alphanumeric character\n (ASCII '0'--'9', 'A'--'Z' or 'a'--'z').\n\n @since LibreOffice 4.1\n *\/\ninline bool isAsciiAlpha(sal_uInt32 nUtf32)\n{\n return isAsciiLowerCase(nUtf32) || isAsciiUpperCase(nUtf32);\n}\n\n\/** Check for ASCII digit character.\n\n @param nUtf32 Some UCS-4 character.\n\n @return True if nChar is a ASCII (decimal) digit character\n (ASCII '0'--'9').\n\n @since LibreOffice 4.1\n *\/\ninline bool isAsciiDigit(sal_uInt32 nUtf32)\n{\n return nUtf32 >= '0' && nUtf32 <= '9';\n}\n\n\/** Check for US-ASCII alphanumeric character.\n\n @param nUtf32 Some UCS-4 character.\n\n @return True if nChar is a US-ASCII alphanumeric character (US-ASCII\n '0'--'9', 'A'--'Z' or 'a'--'z').\n\n @since LibreOffice 4.1\n *\/\ninline bool isAsciiAlphanumeric(sal_uInt32 nUtf32)\n{\n return isAsciiDigit(nUtf32) || isAsciiAlpha(nUtf32);\n}\n\n\/** Check for US-ASCII canonic hexadecimal digit character.\n\n @param nUtf32 Some UCS-4 character.\n\n @return True if nChar is a US-ASCII canonic (i.e., upper case)\n hexadecimal digit character (US-ASCII '0'--'9' or 'A'--'F').\n\n @since LibreOffice 4.1\n *\/\ninline bool isAsciiCanonicHexDigit(sal_uInt32 nUtf32)\n{\n return isAsciiDigit(nUtf32) || (nUtf32 >= 'A' && nUtf32 <= 'F');\n}\n\n\/** Check for US-ASCII hexadecimal digit character.\n\n @param nUtf32 Some UCS-4 character.\n\n @return True if nChar is a US-ASCII hexadecimal digit character (US-\n ASCII '0'--'9', 'A'--'F', 'a'--'f').\n\n @since LibreOffice 4.1\n *\/\ninline bool isAsciiHexDigit(sal_uInt32 nUtf32)\n{\n return isAsciiCanonicHexDigit(nUtf32) || (nUtf32 >= 'a' && nUtf32 <= 'f');\n}\n\n}\/\/rtl namespace\n\n#endif\n\n\/* vim:set shiftwidth=4 softtabstop=4 expandtab: *\/\n<commit_msg>Clean up documentation<commit_after>\/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- *\/\n\/*\n * This file is part of the LibreOffice project.\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\n * This file incorporates work covered by the following license notice:\n *\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed\n * with this work for additional information regarding copyright\n * ownership. The ASF licenses this file to you under the Apache\n * License, Version 2.0 (the \"License\"); you may not use this file\n * except in compliance with the License. You may obtain a copy of\n * the License at http:\/\/www.apache.org\/licenses\/LICENSE-2.0 .\n *\/\n\n#ifndef INCLUDED_RTL_CHARACTER_HXX\n#define INCLUDED_RTL_CHARACTER_HXX\n\n#include \"sal\/config.h\"\n\n#include \"sal\/types.h\"\n\nnamespace rtl\n{\n\/** Check for ASCII character.\n\n @param nUtf32 A Unicode scalar value (represented as a UTF-32 code unit).\n\n @return True if nChar is a ASCII character (0x00--0x7F).\n\n @since LibreOffice 4.1\n *\/\ninline bool isAscii(sal_uInt32 nUtf32)\n{\n return nUtf32 <= 0x7F;\n}\n\n\/** Check for ASCII lower case character.\n\n @param nUtf32 A Unicode scalar value (represented as a UTF-32 code unit).\n\n @return True if nChar is a US-ASCII lower case alphabetic character\n (ASCII 'a'--'z').\n\n @since LibreOffice 4.1\n *\/\ninline bool isAsciiLowerCase(sal_uInt32 nUtf32)\n{\n return nUtf32 >= 'a' && nUtf32 <= 'z';\n}\n\n\/** Check for US-ASCII upper case character.\n\n @param nUtf32 A Unicode scalar value (represented as a UTF-32 code unit).\n\n @return True if nChar is a US-ASCII upper case alphabetic character\n (US-ASCII 'A'--'Z').\n\n @since LibreOffice 4.1\n *\/\ninline bool isAsciiUpperCase(sal_uInt32 nUtf32)\n{\n return nUtf32 >= 'A' && nUtf32 <= 'Z';\n}\n\n\/** Check for ASCII alphanumeric character.\n\n @param nUtf32 A Unicode scalar value (represented as a UTF-32 code unit).\n\n @return True if nUtf32 is a US-ASCII alphanumeric character\n (ASCII '0'--'9', 'A'--'Z' or 'a'--'z').\n\n @since LibreOffice 4.1\n *\/\ninline bool isAsciiAlpha(sal_uInt32 nUtf32)\n{\n return isAsciiLowerCase(nUtf32) || isAsciiUpperCase(nUtf32);\n}\n\n\/** Check for ASCII digit character.\n\n @param nUtf32 A Unicode scalar value (represented as a UTF-32 code unit).\n\n @return True if nChar is a ASCII (decimal) digit character\n (ASCII '0'--'9').\n\n @since LibreOffice 4.1\n *\/\ninline bool isAsciiDigit(sal_uInt32 nUtf32)\n{\n return nUtf32 >= '0' && nUtf32 <= '9';\n}\n\n\/** Check for US-ASCII alphanumeric character.\n\n @param nUtf32 A Unicode scalar value (represented as a UTF-32 code unit).\n\n @return True if nChar is a US-ASCII alphanumeric character (US-ASCII\n '0'--'9', 'A'--'Z' or 'a'--'z').\n\n @since LibreOffice 4.1\n *\/\ninline bool isAsciiAlphanumeric(sal_uInt32 nUtf32)\n{\n return isAsciiDigit(nUtf32) || isAsciiAlpha(nUtf32);\n}\n\n\/** Check for US-ASCII canonic hexadecimal digit character.\n\n @param nUtf32 A Unicode scalar value (represented as a UTF-32 code unit).\n\n @return True if nChar is a US-ASCII canonic (i.e., upper case)\n hexadecimal digit character (US-ASCII '0'--'9' or 'A'--'F').\n\n @since LibreOffice 4.1\n *\/\ninline bool isAsciiCanonicHexDigit(sal_uInt32 nUtf32)\n{\n return isAsciiDigit(nUtf32) || (nUtf32 >= 'A' && nUtf32 <= 'F');\n}\n\n\/** Check for US-ASCII hexadecimal digit character.\n\n @param nUtf32 A Unicode scalar value (represented as a UTF-32 code unit).\n\n @return True if nChar is a US-ASCII hexadecimal digit character (US-\n ASCII '0'--'9', 'A'--'F', 'a'--'f').\n\n @since LibreOffice 4.1\n *\/\ninline bool isAsciiHexDigit(sal_uInt32 nUtf32)\n{\n return isAsciiCanonicHexDigit(nUtf32) || (nUtf32 >= 'a' && nUtf32 <= 'f');\n}\n\n}\/\/rtl namespace\n\n#endif\n\n\/* vim:set shiftwidth=4 softtabstop=4 expandtab: *\/\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2014-2020 The Dash Core developers\n\/\/ Distributed under the MIT\/X11 software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n\n#include <governance\/governanceclasses.h>\n#include <governance\/governancevalidators.h>\n#include <validation.h>\n#include <rpc\/server.h>\n#include <wallet\/rpcwallet.h>\n#include <wallet\/wallet.h>\n#include <rpc\/blockchain.h>\n#include <node\/context.h>\n\n\nUniValue VoteWithMasternodes(const std::map<uint256, CKey>& keys,\n const uint256& hash, vote_signal_enum_t eVoteSignal,\n vote_outcome_enum_t eVoteOutcome, CConnman& connman)\n{\n {\n LOCK(governance.cs);\n CGovernanceObject *pGovObj = governance.FindGovernanceObject(hash);\n if (!pGovObj) {\n throw JSONRPCError(RPC_INVALID_PARAMETER, \"Governance object not found\");\n }\n }\n\n int nSuccessful = 0;\n int nFailed = 0;\n CDeterministicMNList mnList;\n deterministicMNManager->GetListAtChainTip(mnList);\n\n UniValue resultsObj(UniValue::VOBJ);\n\n for (const auto& p : keys) {\n const auto& proTxHash = p.first;\n const auto& key = p.second;\n\n UniValue statusObj(UniValue::VOBJ);\n\n auto dmn = mnList.GetValidMN(proTxHash);\n if (!dmn) {\n nFailed++;\n statusObj.pushKV(\"result\", \"failed\");\n statusObj.pushKV(\"errorMessage\", \"Can't find masternode by proTxHash\");\n resultsObj.pushKV(proTxHash.ToString(), statusObj);\n continue;\n }\n\n CGovernanceVote vote(dmn->collateralOutpoint, hash, eVoteSignal, eVoteOutcome);\n if (!vote.Sign(key, key.GetPubKey().GetID())) {\n nFailed++;\n statusObj.pushKV(\"result\", \"failed\");\n statusObj.pushKV(\"errorMessage\", \"Failure to sign.\");\n resultsObj.pushKV(proTxHash.ToString(), statusObj);\n continue;\n }\n\n CGovernanceException exception;\n if (governance.ProcessVoteAndRelay(vote, exception, connman)) {\n nSuccessful++;\n statusObj.pushKV(\"result\", \"success\");\n } else {\n nFailed++;\n statusObj.pushKV(\"result\", \"failed\");\n statusObj.pushKV(\"errorMessage\", exception.GetMessage());\n }\n\n resultsObj.pushKV(proTxHash.ToString(), statusObj);\n }\n\n UniValue returnObj(UniValue::VOBJ);\n returnObj.pushKV(\"overall\", strprintf(\"Voted successfully %d time(s) and failed %d time(s).\", nSuccessful, nFailed));\n returnObj.pushKV(\"detail\", resultsObj);\n\n return returnObj;\n}\n\nstatic RPCHelpMan gobject_prepare()\n{\n return RPCHelpMan{\"gobject_prepare\",\n \"\\nPrepare governance object by signing and creating tx.\\n\",\n { \n {\"parentHash\", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, \"Hash of the parent object, \\\"0\\\" is root.\"},\n {\"revision\", RPCArg::Type::NUM, RPCArg::Optional::NO, \"Object revision in the system.\"}, \n {\"time\", RPCArg::Type::NUM, RPCArg::Optional::NO, \"Time this object was created.\"},\n {\"dataHex\", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, \"Data in hex string form.\"},\n {\"outputHash\", RPCArg::Type::STR_HEX, RPCArg::Optional::OMITTED, \"The single output to submit the proposal fee from.\"}, \n {\"outputIndex\", RPCArg::Type::NUM, RPCArg::Optional::OMITTED, \"The output index.\"}, \n },\n RPCResult{RPCResult::Type::STR_HEX, \"hash\", \"txid\"},\n RPCExamples{\n HelpExampleCli(\"gobject_prepare\", \"\")\n + HelpExampleRpc(\"gobject_prepare\", \"\")\n },\n [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue\n{\n std::shared_ptr<CWallet> const wallet = GetWalletForJSONRPCRequest(request);\n if (!wallet) return NullUniValue;\n CWallet* const pwallet = wallet.get();\n NodeContext& node = EnsureNodeContext(request.context);\n if(!node.connman)\n throw JSONRPCError(RPC_CLIENT_P2P_DISABLED, \"Error: Peer-to-peer functionality missing or disabled\");\n\n EnsureWalletIsUnlocked(pwallet);\n\n \/\/ ASSEMBLE NEW GOVERNANCE OBJECT FROM USER PARAMETERS\n\n uint256 hashParent;\n\n \/\/ -- attach to root node (root node doesn't really exist, but has a hash of zero)\n if (request.params[0].get_str() == \"0\") {\n hashParent = uint256();\n } else {\n hashParent = ParseHashV(request.params[0], \"feeTxid\");\n }\n\n int nRevision = request.params[1].get_int();\n int64_t nTime = request.params[2].get_int64();\n std::string strDataHex = request.params[3].get_str();\n\n \/\/ CREATE A NEW COLLATERAL TRANSACTION FOR THIS SPECIFIC OBJECT\n\n CGovernanceObject govobj(hashParent, nRevision, nTime, uint256(), strDataHex);\n\n \/\/ This command is dangerous because it consumes 150 SYS irreversibly.\n \/\/ If params are lost, it's very hard to bruteforce them and yet\n \/\/ users ignore all instructions on syshub etc. and do not save them...\n \/\/ Let's log them here and hope users do not mess with debug.log\n LogPrintf(\"gobject_prepare -- params: %s %s %s %s, data: %s, hash: %s\\n\",\n request.params[0].get_str(), request.params[1].get_str(),\n request.params[2].get_str(), request.params[3].get_str(),\n govobj.GetDataAsPlainString(), govobj.GetHash().ToString());\n\n if (govobj.GetObjectType() == GOVERNANCE_OBJECT_PROPOSAL) {\n CProposalValidator validator(strDataHex, false);\n if (!validator.Validate()) {\n throw JSONRPCError(RPC_INVALID_PARAMETER, \"Invalid proposal data, error messages:\" + validator.GetErrorMessages());\n }\n }\n\n if (govobj.GetObjectType() == GOVERNANCE_OBJECT_TRIGGER) {\n throw JSONRPCError(RPC_INVALID_PARAMETER, \"Trigger objects need not be prepared (however only masternodes can create them)\");\n }\n\n LOCK(pwallet->cs_wallet);\n\n std::string strError = \"\";\n if (!govobj.IsValidLocally(strError, false))\n throw JSONRPCError(RPC_INTERNAL_ERROR, \"Governance object is not valid - \" + govobj.GetHash().ToString() + \" - \" + strError);\n\n \/\/ If specified, spend this outpoint as the proposal fee\n COutPoint outpoint;\n outpoint.SetNull();\n if (!request.params[4].isNull() && !request.params[5].isNull()) {\n uint256 collateralHash = ParseHashV(request.params[4], \"outputHash\");\n int32_t collateralIndex = request.params[5].get_int();\n if (collateralHash.IsNull() || collateralIndex < 0) {\n throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, strprintf(\"invalid hash or index: %s-%d\", collateralHash.ToString(), collateralIndex));\n }\n outpoint = COutPoint(collateralHash, (uint32_t)collateralIndex);\n }\n\n CTransactionRef tx;\n if (!pwallet->GetBudgetSystemCollateralTX(tx, govobj.GetHash(), govobj.GetMinCollateralFee(), outpoint)) {\n std::string err = \"Error making collateral transaction for governance object. Please check your wallet balance and make sure your wallet is unlocked.\";\n if (!request.params[5].isNull() && !request.params[6].isNull()) {\n err += \"Please verify your specified output is valid and is enough for the combined proposal fee and transaction fee.\";\n }\n throw JSONRPCError(RPC_INTERNAL_ERROR, err);\n }\n\n \/\/ -- send the tx to the network\n mapValue_t mapValue;\n pwallet->CommitTransaction(tx, std::move(mapValue), {} \/* orderForm *\/);\n\n LogPrint(BCLog::GOBJECT, \"gobject_prepare -- GetDataAsPlainString = %s, hash = %s, txid = %s\\n\",\n govobj.GetDataAsPlainString(), govobj.GetHash().ToString(), tx->GetHash().ToString());\n\n return tx->GetHash().ToString();\n},\n };\n} \n\n\nstatic RPCHelpMan gobject_vote_many()\n{\n return RPCHelpMan{\"gobject_vote_many\",\n \"\\nVote on a governance object by all masternodes for which the voting key is present in the local wallet.\\n\",\n { \n {\"governanceHash\", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, \"Hash of the governance object.\"},\n {\"vote\", RPCArg::Type::STR, RPCArg::Optional::NO, \"Vote, possible values: [funding|valid|delete|endorsed].\"}, \n {\"voteOutome\", RPCArg::Type::STR, RPCArg::Optional::NO, \"Vote outcome, possible values: [yes|no|abstain].\"}, \n },\n RPCResult{RPCResult::Type::NONE, \"\", \"\"},\n RPCExamples{\n HelpExampleCli(\"gobject_vote_many\", \"\")\n + HelpExampleRpc(\"gobject_vote_many\", \"\")\n },\n [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue\n{\n std::shared_ptr<CWallet> const wallet = GetWalletForJSONRPCRequest(request);\n if (!wallet) return NullUniValue;\n CWallet* const pwallet = wallet.get();\n\n NodeContext& node = EnsureNodeContext(request.context);\n if(!node.connman)\n throw JSONRPCError(RPC_CLIENT_P2P_DISABLED, \"Error: Peer-to-peer functionality missing or disabled\");\n\n\n uint256 hash = ParseHashV(request.params[0], \"Object hash\");\n std::string strVoteSignal = request.params[1].get_str();\n std::string strVoteOutcome = request.params[2].get_str();\n\n vote_signal_enum_t eVoteSignal = CGovernanceVoting::ConvertVoteSignal(strVoteSignal);\n if (eVoteSignal == VOTE_SIGNAL_NONE) {\n throw JSONRPCError(RPC_INVALID_PARAMETER,\n \"Invalid vote signal. Please using one of the following: \"\n \"(funding|valid|delete|endorsed)\");\n }\n\n vote_outcome_enum_t eVoteOutcome = CGovernanceVoting::ConvertVoteOutcome(strVoteOutcome);\n if (eVoteOutcome == VOTE_OUTCOME_NONE) {\n throw JSONRPCError(RPC_INVALID_PARAMETER, \"Invalid vote outcome. Please use one of the following: 'yes', 'no' or 'abstain'\");\n }\n\n EnsureWalletIsUnlocked(pwallet);\n\n std::map<uint256, CKey> votingKeys;\n \/\/ Make sure the results are valid at least up to the most recent block\n \/\/ the user could have gotten from another RPC command prior to now\n pwallet->BlockUntilSyncedToCurrentChain();\n CDeterministicMNList mnList;\n deterministicMNManager->GetListAtChainTip(mnList);\n mnList.ForEachMN(true, [&](const CDeterministicMNCPtr& dmn) {\n LegacyScriptPubKeyMan& spk_man = EnsureLegacyScriptPubKeyMan(*pwallet);\n LOCK2(pwallet->cs_wallet, spk_man.cs_KeyStore);\n\n EnsureWalletIsUnlocked(pwallet);\n\n CKey key;\n if (spk_man.GetKey(dmn->pdmnState->keyIDVoting, key)) {\n votingKeys.emplace(dmn->proTxHash, key);\n }\n });\n\n return VoteWithMasternodes(votingKeys, hash, eVoteSignal, eVoteOutcome, *node.connman);\n},\n };\n} \n\nstatic RPCHelpMan gobject_vote_alias()\n{\n return RPCHelpMan{\"gobject_vote_alias\",\n \"\\nVote on a governance object by masternode's voting key (if present in local wallet).\\n\",\n { \n {\"governanceHash\", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, \"Hash of the governance object.\"},\n {\"vote\", RPCArg::Type::STR, RPCArg::Optional::NO, \"Vote, possible values: [funding|valid|delete|endorsed].\"}, \n {\"voteOutome\", RPCArg::Type::STR, RPCArg::Optional::NO, \"Vote outcome, possible values: [yes|no|abstain].\"}, \n {\"protxHash\", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, \"Masternode's proTxHash.\"}, \n },\n RPCResult{RPCResult::Type::NONE, \"\", \"\"},\n RPCExamples{\n HelpExampleCli(\"gobject_vote_alias\", \"\")\n + HelpExampleRpc(\"gobject_vote_alias\", \"\")\n },\n [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue\n{ \n std::shared_ptr<CWallet> const wallet = GetWalletForJSONRPCRequest(request);\n if (!wallet) return NullUniValue;\n CWallet* const pwallet = wallet.get();\n\n NodeContext& node = EnsureNodeContext(request.context);\n if(!node.connman)\n throw JSONRPCError(RPC_CLIENT_P2P_DISABLED, \"Error: Peer-to-peer functionality missing or disabled\");\n\n\n uint256 hash = ParseHashV(request.params[0], \"Object hash\");\n std::string strVoteSignal = request.params[1].get_str();\n std::string strVoteOutcome = request.params[2].get_str();\n\n vote_signal_enum_t eVoteSignal = CGovernanceVoting::ConvertVoteSignal(strVoteSignal);\n if (eVoteSignal == VOTE_SIGNAL_NONE) {\n throw JSONRPCError(RPC_INVALID_PARAMETER,\n \"Invalid vote signal. Please using one of the following: \"\n \"(funding|valid|delete|endorsed)\");\n }\n\n vote_outcome_enum_t eVoteOutcome = CGovernanceVoting::ConvertVoteOutcome(strVoteOutcome);\n if (eVoteOutcome == VOTE_OUTCOME_NONE) {\n throw JSONRPCError(RPC_INVALID_PARAMETER, \"Invalid vote outcome. Please use one of the following: 'yes', 'no' or 'abstain'\");\n }\n\n EnsureWalletIsUnlocked(pwallet);\n\n uint256 proTxHash = ParseHashV(request.params[3], \"protxHash\");\n CDeterministicMNList mnList;\n deterministicMNManager->GetListAtChainTip(mnList);\n auto dmn = mnList.GetValidMN(proTxHash);\n if (!dmn) {\n throw JSONRPCError(RPC_INVALID_PARAMETER, \"Invalid or unknown proTxHash\");\n }\n \/\/ Make sure the results are valid at least up to the most recent block\n \/\/ the user could have gotten from another RPC command prior to now\n pwallet->BlockUntilSyncedToCurrentChain();\n CKey key;\n {\n LegacyScriptPubKeyMan& spk_man = EnsureLegacyScriptPubKeyMan(*pwallet);\n LOCK2(pwallet->cs_wallet, spk_man.cs_KeyStore);\n\n \n if (!spk_man.GetKey(dmn->pdmnState->keyIDVoting, key)) {\n throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf(\"Private key for voting address %s not known by wallet\", EncodeDestination(WitnessV0KeyHash(dmn->pdmnState->keyIDVoting))));\n }\n }\n\n std::map<uint256, CKey> votingKeys;\n votingKeys.emplace(proTxHash, key);\n\n return VoteWithMasternodes(votingKeys, hash, eVoteSignal, eVoteOutcome, *node.connman);\n},\n };\n} \n\nSpan<const CRPCCommand> GetGovernanceWalletRPCCommands()\n{\n\/\/ clang-format off\nstatic const CRPCCommand commands[] =\n{ \/\/ category name actor (function) argNames\n\/\/ --------------------- ------------------------ ----------------------- ----------\n { \"governancewallet\", \"gobject_vote_alias\", &gobject_vote_alias, {\"governanceHash\",\"vote\",\"voteOutome\",\"protxHash\"} },\n { \"governancewallet\", \"gobject_vote_many\", &gobject_vote_many, {\"governanceHash\",\"vote\",\"voteOutome\"} },\n { \"governancewallet\", \"gobject_prepare\", &gobject_prepare, {\"parentHash\",\"revision\",\"time\",\"dataHex\",\"outputHash\",\"outputIndex\"} },\n\n};\n\/\/ clang-format on\n return MakeSpan(commands);\n}\n<commit_msg>fix gitian fail with govc exception<commit_after>\/\/ Copyright (c) 2014-2020 The Dash Core developers\n\/\/ Distributed under the MIT\/X11 software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include <governance\/governanceexceptions.h>\n#include <governance\/governanceclasses.h>\n#include <governance\/governancevalidators.h>\n#include <validation.h>\n#include <rpc\/server.h>\n#include <wallet\/rpcwallet.h>\n#include <wallet\/wallet.h>\n#include <rpc\/blockchain.h>\n#include <node\/context.h>\n\n\nUniValue VoteWithMasternodes(const std::map<uint256, CKey>& keys,\n const uint256& hash, vote_signal_enum_t eVoteSignal,\n vote_outcome_enum_t eVoteOutcome, CConnman& connman)\n{\n {\n LOCK(governance.cs);\n CGovernanceObject *pGovObj = governance.FindGovernanceObject(hash);\n if (!pGovObj) {\n throw JSONRPCError(RPC_INVALID_PARAMETER, \"Governance object not found\");\n }\n }\n\n int nSuccessful = 0;\n int nFailed = 0;\n CDeterministicMNList mnList;\n deterministicMNManager->GetListAtChainTip(mnList);\n\n UniValue resultsObj(UniValue::VOBJ);\n\n for (const auto& p : keys) {\n const auto& proTxHash = p.first;\n const auto& key = p.second;\n\n UniValue statusObj(UniValue::VOBJ);\n\n auto dmn = mnList.GetValidMN(proTxHash);\n if (!dmn) {\n nFailed++;\n statusObj.pushKV(\"result\", \"failed\");\n statusObj.pushKV(\"errorMessage\", \"Can't find masternode by proTxHash\");\n resultsObj.pushKV(proTxHash.ToString(), statusObj);\n continue;\n }\n\n CGovernanceVote vote(dmn->collateralOutpoint, hash, eVoteSignal, eVoteOutcome);\n if (!vote.Sign(key, key.GetPubKey().GetID())) {\n nFailed++;\n statusObj.pushKV(\"result\", \"failed\");\n statusObj.pushKV(\"errorMessage\", \"Failure to sign.\");\n resultsObj.pushKV(proTxHash.ToString(), statusObj);\n continue;\n }\n\n CGovernanceException exception;\n if (governance.ProcessVoteAndRelay(vote, exception, connman)) {\n nSuccessful++;\n statusObj.pushKV(\"result\", \"success\");\n } else {\n nFailed++;\n statusObj.pushKV(\"result\", \"failed\");\n statusObj.pushKV(\"errorMessage\", exception.GetMessage());\n }\n\n resultsObj.pushKV(proTxHash.ToString(), statusObj);\n }\n\n UniValue returnObj(UniValue::VOBJ);\n returnObj.pushKV(\"overall\", strprintf(\"Voted successfully %d time(s) and failed %d time(s).\", nSuccessful, nFailed));\n returnObj.pushKV(\"detail\", resultsObj);\n\n return returnObj;\n}\n\nstatic RPCHelpMan gobject_prepare()\n{\n return RPCHelpMan{\"gobject_prepare\",\n \"\\nPrepare governance object by signing and creating tx.\\n\",\n { \n {\"parentHash\", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, \"Hash of the parent object, \\\"0\\\" is root.\"},\n {\"revision\", RPCArg::Type::NUM, RPCArg::Optional::NO, \"Object revision in the system.\"}, \n {\"time\", RPCArg::Type::NUM, RPCArg::Optional::NO, \"Time this object was created.\"},\n {\"dataHex\", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, \"Data in hex string form.\"},\n {\"outputHash\", RPCArg::Type::STR_HEX, RPCArg::Optional::OMITTED, \"The single output to submit the proposal fee from.\"}, \n {\"outputIndex\", RPCArg::Type::NUM, RPCArg::Optional::OMITTED, \"The output index.\"}, \n },\n RPCResult{RPCResult::Type::STR_HEX, \"hash\", \"txid\"},\n RPCExamples{\n HelpExampleCli(\"gobject_prepare\", \"\")\n + HelpExampleRpc(\"gobject_prepare\", \"\")\n },\n [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue\n{\n std::shared_ptr<CWallet> const wallet = GetWalletForJSONRPCRequest(request);\n if (!wallet) return NullUniValue;\n CWallet* const pwallet = wallet.get();\n NodeContext& node = EnsureNodeContext(request.context);\n if(!node.connman)\n throw JSONRPCError(RPC_CLIENT_P2P_DISABLED, \"Error: Peer-to-peer functionality missing or disabled\");\n\n EnsureWalletIsUnlocked(pwallet);\n\n \/\/ ASSEMBLE NEW GOVERNANCE OBJECT FROM USER PARAMETERS\n\n uint256 hashParent;\n\n \/\/ -- attach to root node (root node doesn't really exist, but has a hash of zero)\n if (request.params[0].get_str() == \"0\") {\n hashParent = uint256();\n } else {\n hashParent = ParseHashV(request.params[0], \"feeTxid\");\n }\n\n int nRevision = request.params[1].get_int();\n int64_t nTime = request.params[2].get_int64();\n std::string strDataHex = request.params[3].get_str();\n\n \/\/ CREATE A NEW COLLATERAL TRANSACTION FOR THIS SPECIFIC OBJECT\n\n CGovernanceObject govobj(hashParent, nRevision, nTime, uint256(), strDataHex);\n\n \/\/ This command is dangerous because it consumes 150 SYS irreversibly.\n \/\/ If params are lost, it's very hard to bruteforce them and yet\n \/\/ users ignore all instructions on syshub etc. and do not save them...\n \/\/ Let's log them here and hope users do not mess with debug.log\n LogPrintf(\"gobject_prepare -- params: %s %s %s %s, data: %s, hash: %s\\n\",\n request.params[0].get_str(), request.params[1].get_str(),\n request.params[2].get_str(), request.params[3].get_str(),\n govobj.GetDataAsPlainString(), govobj.GetHash().ToString());\n\n if (govobj.GetObjectType() == GOVERNANCE_OBJECT_PROPOSAL) {\n CProposalValidator validator(strDataHex, false);\n if (!validator.Validate()) {\n throw JSONRPCError(RPC_INVALID_PARAMETER, \"Invalid proposal data, error messages:\" + validator.GetErrorMessages());\n }\n }\n\n if (govobj.GetObjectType() == GOVERNANCE_OBJECT_TRIGGER) {\n throw JSONRPCError(RPC_INVALID_PARAMETER, \"Trigger objects need not be prepared (however only masternodes can create them)\");\n }\n\n LOCK(pwallet->cs_wallet);\n\n std::string strError = \"\";\n if (!govobj.IsValidLocally(strError, false))\n throw JSONRPCError(RPC_INTERNAL_ERROR, \"Governance object is not valid - \" + govobj.GetHash().ToString() + \" - \" + strError);\n\n \/\/ If specified, spend this outpoint as the proposal fee\n COutPoint outpoint;\n outpoint.SetNull();\n if (!request.params[4].isNull() && !request.params[5].isNull()) {\n uint256 collateralHash = ParseHashV(request.params[4], \"outputHash\");\n int32_t collateralIndex = request.params[5].get_int();\n if (collateralHash.IsNull() || collateralIndex < 0) {\n throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, strprintf(\"invalid hash or index: %s-%d\", collateralHash.ToString(), collateralIndex));\n }\n outpoint = COutPoint(collateralHash, (uint32_t)collateralIndex);\n }\n\n CTransactionRef tx;\n if (!pwallet->GetBudgetSystemCollateralTX(tx, govobj.GetHash(), govobj.GetMinCollateralFee(), outpoint)) {\n std::string err = \"Error making collateral transaction for governance object. Please check your wallet balance and make sure your wallet is unlocked.\";\n if (!request.params[5].isNull() && !request.params[6].isNull()) {\n err += \"Please verify your specified output is valid and is enough for the combined proposal fee and transaction fee.\";\n }\n throw JSONRPCError(RPC_INTERNAL_ERROR, err);\n }\n\n \/\/ -- send the tx to the network\n mapValue_t mapValue;\n pwallet->CommitTransaction(tx, std::move(mapValue), {} \/* orderForm *\/);\n\n LogPrint(BCLog::GOBJECT, \"gobject_prepare -- GetDataAsPlainString = %s, hash = %s, txid = %s\\n\",\n govobj.GetDataAsPlainString(), govobj.GetHash().ToString(), tx->GetHash().ToString());\n\n return tx->GetHash().ToString();\n},\n };\n} \n\n\nstatic RPCHelpMan gobject_vote_many()\n{\n return RPCHelpMan{\"gobject_vote_many\",\n \"\\nVote on a governance object by all masternodes for which the voting key is present in the local wallet.\\n\",\n { \n {\"governanceHash\", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, \"Hash of the governance object.\"},\n {\"vote\", RPCArg::Type::STR, RPCArg::Optional::NO, \"Vote, possible values: [funding|valid|delete|endorsed].\"}, \n {\"voteOutome\", RPCArg::Type::STR, RPCArg::Optional::NO, \"Vote outcome, possible values: [yes|no|abstain].\"}, \n },\n RPCResult{RPCResult::Type::NONE, \"\", \"\"},\n RPCExamples{\n HelpExampleCli(\"gobject_vote_many\", \"\")\n + HelpExampleRpc(\"gobject_vote_many\", \"\")\n },\n [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue\n{\n std::shared_ptr<CWallet> const wallet = GetWalletForJSONRPCRequest(request);\n if (!wallet) return NullUniValue;\n CWallet* const pwallet = wallet.get();\n\n NodeContext& node = EnsureNodeContext(request.context);\n if(!node.connman)\n throw JSONRPCError(RPC_CLIENT_P2P_DISABLED, \"Error: Peer-to-peer functionality missing or disabled\");\n\n\n uint256 hash = ParseHashV(request.params[0], \"Object hash\");\n std::string strVoteSignal = request.params[1].get_str();\n std::string strVoteOutcome = request.params[2].get_str();\n\n vote_signal_enum_t eVoteSignal = CGovernanceVoting::ConvertVoteSignal(strVoteSignal);\n if (eVoteSignal == VOTE_SIGNAL_NONE) {\n throw JSONRPCError(RPC_INVALID_PARAMETER,\n \"Invalid vote signal. Please using one of the following: \"\n \"(funding|valid|delete|endorsed)\");\n }\n\n vote_outcome_enum_t eVoteOutcome = CGovernanceVoting::ConvertVoteOutcome(strVoteOutcome);\n if (eVoteOutcome == VOTE_OUTCOME_NONE) {\n throw JSONRPCError(RPC_INVALID_PARAMETER, \"Invalid vote outcome. Please use one of the following: 'yes', 'no' or 'abstain'\");\n }\n\n EnsureWalletIsUnlocked(pwallet);\n\n std::map<uint256, CKey> votingKeys;\n \/\/ Make sure the results are valid at least up to the most recent block\n \/\/ the user could have gotten from another RPC command prior to now\n pwallet->BlockUntilSyncedToCurrentChain();\n CDeterministicMNList mnList;\n deterministicMNManager->GetListAtChainTip(mnList);\n mnList.ForEachMN(true, [&](const CDeterministicMNCPtr& dmn) {\n LegacyScriptPubKeyMan& spk_man = EnsureLegacyScriptPubKeyMan(*pwallet);\n LOCK2(pwallet->cs_wallet, spk_man.cs_KeyStore);\n\n EnsureWalletIsUnlocked(pwallet);\n\n CKey key;\n if (spk_man.GetKey(dmn->pdmnState->keyIDVoting, key)) {\n votingKeys.emplace(dmn->proTxHash, key);\n }\n });\n\n return VoteWithMasternodes(votingKeys, hash, eVoteSignal, eVoteOutcome, *node.connman);\n},\n };\n} \n\nstatic RPCHelpMan gobject_vote_alias()\n{\n return RPCHelpMan{\"gobject_vote_alias\",\n \"\\nVote on a governance object by masternode's voting key (if present in local wallet).\\n\",\n { \n {\"governanceHash\", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, \"Hash of the governance object.\"},\n {\"vote\", RPCArg::Type::STR, RPCArg::Optional::NO, \"Vote, possible values: [funding|valid|delete|endorsed].\"}, \n {\"voteOutome\", RPCArg::Type::STR, RPCArg::Optional::NO, \"Vote outcome, possible values: [yes|no|abstain].\"}, \n {\"protxHash\", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, \"Masternode's proTxHash.\"}, \n },\n RPCResult{RPCResult::Type::NONE, \"\", \"\"},\n RPCExamples{\n HelpExampleCli(\"gobject_vote_alias\", \"\")\n + HelpExampleRpc(\"gobject_vote_alias\", \"\")\n },\n [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue\n{ \n std::shared_ptr<CWallet> const wallet = GetWalletForJSONRPCRequest(request);\n if (!wallet) return NullUniValue;\n CWallet* const pwallet = wallet.get();\n\n NodeContext& node = EnsureNodeContext(request.context);\n if(!node.connman)\n throw JSONRPCError(RPC_CLIENT_P2P_DISABLED, \"Error: Peer-to-peer functionality missing or disabled\");\n\n\n uint256 hash = ParseHashV(request.params[0], \"Object hash\");\n std::string strVoteSignal = request.params[1].get_str();\n std::string strVoteOutcome = request.params[2].get_str();\n\n vote_signal_enum_t eVoteSignal = CGovernanceVoting::ConvertVoteSignal(strVoteSignal);\n if (eVoteSignal == VOTE_SIGNAL_NONE) {\n throw JSONRPCError(RPC_INVALID_PARAMETER,\n \"Invalid vote signal. Please using one of the following: \"\n \"(funding|valid|delete|endorsed)\");\n }\n\n vote_outcome_enum_t eVoteOutcome = CGovernanceVoting::ConvertVoteOutcome(strVoteOutcome);\n if (eVoteOutcome == VOTE_OUTCOME_NONE) {\n throw JSONRPCError(RPC_INVALID_PARAMETER, \"Invalid vote outcome. Please use one of the following: 'yes', 'no' or 'abstain'\");\n }\n\n EnsureWalletIsUnlocked(pwallet);\n\n uint256 proTxHash = ParseHashV(request.params[3], \"protxHash\");\n CDeterministicMNList mnList;\n deterministicMNManager->GetListAtChainTip(mnList);\n auto dmn = mnList.GetValidMN(proTxHash);\n if (!dmn) {\n throw JSONRPCError(RPC_INVALID_PARAMETER, \"Invalid or unknown proTxHash\");\n }\n \/\/ Make sure the results are valid at least up to the most recent block\n \/\/ the user could have gotten from another RPC command prior to now\n pwallet->BlockUntilSyncedToCurrentChain();\n CKey key;\n {\n LegacyScriptPubKeyMan& spk_man = EnsureLegacyScriptPubKeyMan(*pwallet);\n LOCK2(pwallet->cs_wallet, spk_man.cs_KeyStore);\n\n \n if (!spk_man.GetKey(dmn->pdmnState->keyIDVoting, key)) {\n throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf(\"Private key for voting address %s not known by wallet\", EncodeDestination(WitnessV0KeyHash(dmn->pdmnState->keyIDVoting))));\n }\n }\n\n std::map<uint256, CKey> votingKeys;\n votingKeys.emplace(proTxHash, key);\n\n return VoteWithMasternodes(votingKeys, hash, eVoteSignal, eVoteOutcome, *node.connman);\n},\n };\n} \n\nSpan<const CRPCCommand> GetGovernanceWalletRPCCommands()\n{\n\/\/ clang-format off\nstatic const CRPCCommand commands[] =\n{ \/\/ category name actor (function) argNames\n\/\/ --------------------- ------------------------ ----------------------- ----------\n { \"governancewallet\", \"gobject_vote_alias\", &gobject_vote_alias, {\"governanceHash\",\"vote\",\"voteOutome\",\"protxHash\"} },\n { \"governancewallet\", \"gobject_vote_many\", &gobject_vote_many, {\"governanceHash\",\"vote\",\"voteOutome\"} },\n { \"governancewallet\", \"gobject_prepare\", &gobject_prepare, {\"parentHash\",\"revision\",\"time\",\"dataHex\",\"outputHash\",\"outputIndex\"} },\n\n};\n\/\/ clang-format on\n return MakeSpan(commands);\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"replayState.h\"\n\n#include <deque>\n#include <boost\/bind.hpp>\n#include <boost\/thread.hpp>\n\n#include \"libwatcher\/message.h\"\n#include \"serverConnection.h\"\n#include \"Assert.h\"\n#include \"database.h\"\n#include \"watcherd.h\"\n\nusing namespace util;\nusing namespace watcher;\nusing namespace watcher::event;\n\n\/\/< default value for number of events to prefetch from the database\nconst unsigned int DEFAULT_BUFFER_SIZE = 10U; \/* db rows *\/\nconst unsigned int DEFAULT_STEP = 250U \/* ms *\/;\n\n\/** Internal structure used for implementing the class. Used to avoid\n * dependencies for the user of the class. These would normally be private\n * members of ReplayState.\n *\/\nstruct ReplayState::impl {\n boost::weak_ptr<ServerConnection> conn;\n std::deque<MessagePtr> events;\n boost::asio::deadline_timer timer;\n Timestamp ts; \/\/ the current effective time\n Timestamp last_event; \/\/ timestamp of last event retrieved from db\n float speed; \/\/< playback speed\n unsigned int bufsiz; \/\/< number of database rows to prefetch\n Timestamp step;\n enum run_state { paused, running } state;\n\n \/*\n * Lock used for event queue. This is required due to the seek() member\n * function, which can be called from a different thread.\n *\/\n boost::mutex lock;\n\n impl(ServerConnectionPtr& ptr) :\n conn(ptr), timer(ptr->io_service()), ts(0), last_event(0), bufsiz(DEFAULT_BUFFER_SIZE),\n step(DEFAULT_STEP), state(paused)\n {\n TRACE_ENTER();\n TRACE_EXIT();\n }\n};\n\nReplayState::ReplayState(ServerConnectionPtr ptr, Timestamp t, float playback_speed) :\n impl_(new impl(ptr))\n{\n TRACE_ENTER();\n Assert<Bad_arg>(t >= 0);\n impl_->ts = t;\n impl_->last_event = t;\n\n speed(playback_speed);\n TRACE_EXIT();\n}\n\nTimestamp ReplayState::tell() const\n{\n TRACE_ENTER();\n TRACE_EXIT_RET(impl_->ts);\n return impl_->ts;\n}\n\nReplayState& ReplayState::pause()\n{\n TRACE_ENTER();\n LOG_DEBUG(\"cancelling timer\");\n impl_->timer.cancel();\n impl_->state = impl::paused;\n TRACE_EXIT();\n return *this;\n}\n\nReplayState& ReplayState::seek(Timestamp t)\n{\n TRACE_ENTER();\n\n impl::run_state oldstate;\n {\n boost::mutex::scoped_lock L(impl_->lock);\n oldstate = impl_->state;\n pause();\n impl_->events.clear();\n impl_->ts = t;\n if (t == -1)\n impl_->last_event = std::numeric_limits<Timestamp>::max();\n else\n impl_->last_event = t;\n }\n if (oldstate == impl::running)\n run();\n TRACE_EXIT();\n return *this;\n}\n\nReplayState& ReplayState::speed(float f)\n{\n TRACE_ENTER();\n Assert<Bad_arg>(f != 0);\n \/* If speed changes direction, need to clear the event list.\n * Check for sign change by noting that positive*negative==negative\n *\/\n if (impl_->speed * f < 0) {\n impl::run_state oldstate;\n {\n boost::mutex::scoped_lock L(impl_->lock);\n\n oldstate = impl_->state;\n pause();\n\n impl_->events.clear();\n\n \/*\n * Avoid setting .last_event when SpeedMessage is received\n * prior to the first StartMessage.\n *\/\n if (impl_->ts != 0 && impl_->ts != -1)\n impl_->last_event = impl_->ts;\n\n impl_->speed = f;\n }\n if (oldstate == impl::running)\n run();\n } else\n impl_->speed = f;\n LOG_DEBUG(\"ts=\" << impl_->ts << \" last_event=\" << impl_->last_event);\n TRACE_EXIT();\n return *this;\n}\n\nReplayState& ReplayState::buffer_size(unsigned int n)\n{\n TRACE_ENTER();\n Assert<Bad_arg>(n != 0);\n impl_->bufsiz = n;\n TRACE_EXIT();\n return *this;\n}\n\nReplayState& ReplayState::time_step(unsigned int n)\n{\n TRACE_ENTER();\n Assert<Bad_arg>(n != 0);\n impl_->step = n;\n TRACE_EXIT();\n return *this;\n}\n\n\/* function object for accepting events output from Database::getEvents() *\/\nstruct event_output {\n std::deque<MessagePtr>& q;\n event_output(std::deque<MessagePtr>& qq) : q(qq) {}\n void operator() (MessagePtr m) { q.push_back(m); }\n};\n\n\/** Schedule an asynchronous task to replay events from the database to a GUI\n * client. If the local cache of upcoming events is empty, prefetch a block of\n * events from the database.\n *\n * The code is written such that it will work when playing events forward or in\n * reverse.\n *\/\nvoid ReplayState::run()\n{\n TRACE_ENTER();\n boost::mutex::scoped_lock L(impl_->lock);\n\n if (impl_->events.empty()) {\n \/\/ queue is empty, pre-fetch more items from the DB\n\n boost::function<void(MessagePtr)> cb(event_output(impl_->events));\n LOG_DEBUG(\"fetching events \" << (impl_->speed > 0 ? \"> \" : \"< \") << impl_->last_event);\n get_db_handle().getEvents(cb,\n impl_->last_event,\n (impl_->speed >= 0) ? Database::forward : Database::reverse,\n impl_->bufsiz);\n\n if (!impl_->events.empty()) {\n \/* When starting to replay, assume that time T=0 is the time of the\n * first event in the stream.\n * T= -1 is EOF.\n * Convert to timestamp of first item in the returned events.\n *\n * When playing in reverse, the first item in the list is the last event in the database.\n *\/\n if (impl_->ts == 0 || impl_->ts == -1)\n impl_->ts = impl_->events.front()->timestamp;\n\n \/\/ save timestamp of last event retrieved to avoid duplication\n impl_->last_event = impl_->events.back()->timestamp;\n }\n }\n\n if (! impl_->events.empty()) {\n \/\/ time until next event\n Timestamp delta = impl_->events.front()->timestamp - impl_->ts;\n LOG_DEBUG(\"Next event in \" << delta << \" ms\");\n\n \/\/ update our notion of the current time after the timer expires\n impl_->ts = impl_->events.front()->timestamp;\n\n \/* Adjust for playback speed. Note that when playing events in reverse, both speed\n * delta will be negative, which will turn delta into a positive value for the\n * async_wait() call, which is exactly what is required. *\/\n delta \/= impl_->speed;\n\n impl_->timer.expires_from_now(boost::posix_time::millisec(delta));\n impl_->timer.async_wait(boost::bind(&ReplayState::timer_handler, shared_from_this(), boost::asio::placeholders::error));\n impl_->state = impl::running;\n } else {\n \/*\n * FIXME what should happen when the end of the event stream is reached?\n * One option would be to convert to live stream at this point.\n *\/\n impl_->state = impl::paused;\n }\n TRACE_EXIT();\n}\n\n\/** Replay events to a GUI client when a timer expires.\n *\n * The run() member function is reponsible for prefetching events from the\n * database and storing them in the class object. When a timer expires, run\n * through the locally stored events and send those that occurred within the\n * last time slice. The task is then rescheduled when the next most recent\n * event needs to be transmitted.\n *\/\nvoid ReplayState::timer_handler(const boost::system::error_code& ec)\n{\n TRACE_ENTER();\n if (ec == boost::asio::error::operation_aborted)\n LOG_DEBUG(\"timer was cancelled\");\n else if (impl_->state == impl::paused) {\n LOG_DEBUG(\"timer expired but state is paused!\");\n } else {\n std::vector<MessagePtr> msgs;\n {\n boost::mutex::scoped_lock L(impl_->lock);\n\n while (! impl_->events.empty()) {\n MessagePtr m = impl_->events.front();\n \/* Replay all events in the current time step. Use the absolute value\n * of the difference in order for forward and reverse replay to work\n * properly. *\/\n if (abs(m->timestamp - impl_->ts) >= impl_->step)\n break;\n msgs.push_back(m);\n impl_->events.pop_front();\n }\n }\n\n ServerConnectionPtr srv = impl_->conn.lock();\n if (srv) { \/* connection is still alive *\/\n srv->sendMessage(msgs);\n run(); \/\/ reschedule this task\n }\n }\n TRACE_EXIT();\n}\n\n\/* This is required to be defined, otherwise a the default dtor will cause a\n * compiler error due to use of scoped_ptr with an incomplete type.\n *\/\nReplayState::~ReplayState()\n{\n TRACE_ENTER();\n TRACE_EXIT();\n}\n\nfloat ReplayState::speed() const\n{\n return impl_->speed;\n}\n<commit_msg>add debug message when last row of db is fetched<commit_after>#include \"replayState.h\"\n\n#include <deque>\n#include <boost\/bind.hpp>\n#include <boost\/thread.hpp>\n\n#include \"libwatcher\/message.h\"\n#include \"serverConnection.h\"\n#include \"Assert.h\"\n#include \"database.h\"\n#include \"watcherd.h\"\n\nusing namespace util;\nusing namespace watcher;\nusing namespace watcher::event;\n\n\/\/< default value for number of events to prefetch from the database\nconst unsigned int DEFAULT_BUFFER_SIZE = 10U; \/* db rows *\/\nconst unsigned int DEFAULT_STEP = 250U \/* ms *\/;\n\n\/** Internal structure used for implementing the class. Used to avoid\n * dependencies for the user of the class. These would normally be private\n * members of ReplayState.\n *\/\nstruct ReplayState::impl {\n boost::weak_ptr<ServerConnection> conn;\n std::deque<MessagePtr> events;\n boost::asio::deadline_timer timer;\n Timestamp ts; \/\/ the current effective time\n Timestamp last_event; \/\/ timestamp of last event retrieved from db\n float speed; \/\/< playback speed\n unsigned int bufsiz; \/\/< number of database rows to prefetch\n Timestamp step;\n enum run_state { paused, running } state;\n\n \/*\n * Lock used for event queue. This is required due to the seek() member\n * function, which can be called from a different thread.\n *\/\n boost::mutex lock;\n\n impl(ServerConnectionPtr& ptr) :\n conn(ptr), timer(ptr->io_service()), ts(0), last_event(0), bufsiz(DEFAULT_BUFFER_SIZE),\n step(DEFAULT_STEP), state(paused)\n {\n TRACE_ENTER();\n TRACE_EXIT();\n }\n};\n\nReplayState::ReplayState(ServerConnectionPtr ptr, Timestamp t, float playback_speed) :\n impl_(new impl(ptr))\n{\n TRACE_ENTER();\n Assert<Bad_arg>(t >= 0);\n impl_->ts = t;\n impl_->last_event = t;\n\n speed(playback_speed);\n TRACE_EXIT();\n}\n\nTimestamp ReplayState::tell() const\n{\n TRACE_ENTER();\n TRACE_EXIT_RET(impl_->ts);\n return impl_->ts;\n}\n\nReplayState& ReplayState::pause()\n{\n TRACE_ENTER();\n LOG_DEBUG(\"cancelling timer\");\n impl_->timer.cancel();\n impl_->state = impl::paused;\n TRACE_EXIT();\n return *this;\n}\n\nReplayState& ReplayState::seek(Timestamp t)\n{\n TRACE_ENTER();\n\n impl::run_state oldstate;\n {\n boost::mutex::scoped_lock L(impl_->lock);\n oldstate = impl_->state;\n pause();\n impl_->events.clear();\n impl_->ts = t;\n if (t == -1)\n impl_->last_event = std::numeric_limits<Timestamp>::max();\n else\n impl_->last_event = t;\n }\n if (oldstate == impl::running)\n run();\n TRACE_EXIT();\n return *this;\n}\n\nReplayState& ReplayState::speed(float f)\n{\n TRACE_ENTER();\n Assert<Bad_arg>(f != 0);\n \/* If speed changes direction, need to clear the event list.\n * Check for sign change by noting that positive*negative==negative\n *\/\n if (impl_->speed * f < 0) {\n impl::run_state oldstate;\n {\n boost::mutex::scoped_lock L(impl_->lock);\n\n oldstate = impl_->state;\n pause();\n\n impl_->events.clear();\n\n \/*\n * Avoid setting .last_event when SpeedMessage is received\n * prior to the first StartMessage.\n *\/\n if (impl_->ts != 0 && impl_->ts != -1)\n impl_->last_event = impl_->ts;\n\n impl_->speed = f;\n }\n if (oldstate == impl::running)\n run();\n } else\n impl_->speed = f;\n LOG_DEBUG(\"ts=\" << impl_->ts << \" last_event=\" << impl_->last_event);\n TRACE_EXIT();\n return *this;\n}\n\nReplayState& ReplayState::buffer_size(unsigned int n)\n{\n TRACE_ENTER();\n Assert<Bad_arg>(n != 0);\n impl_->bufsiz = n;\n TRACE_EXIT();\n return *this;\n}\n\nReplayState& ReplayState::time_step(unsigned int n)\n{\n TRACE_ENTER();\n Assert<Bad_arg>(n != 0);\n impl_->step = n;\n TRACE_EXIT();\n return *this;\n}\n\n\/* function object for accepting events output from Database::getEvents() *\/\nstruct event_output {\n std::deque<MessagePtr>& q;\n event_output(std::deque<MessagePtr>& qq) : q(qq) {}\n void operator() (MessagePtr m) { q.push_back(m); }\n};\n\n\/** Schedule an asynchronous task to replay events from the database to a GUI\n * client. If the local cache of upcoming events is empty, prefetch a block of\n * events from the database.\n *\n * The code is written such that it will work when playing events forward or in\n * reverse.\n *\/\nvoid ReplayState::run()\n{\n TRACE_ENTER();\n boost::mutex::scoped_lock L(impl_->lock);\n\n if (impl_->events.empty()) {\n \/\/ queue is empty, pre-fetch more items from the DB\n\n boost::function<void(MessagePtr)> cb(event_output(impl_->events));\n LOG_DEBUG(\"fetching events \" << (impl_->speed > 0 ? \"> \" : \"< \") << impl_->last_event);\n get_db_handle().getEvents(cb,\n impl_->last_event,\n (impl_->speed >= 0) ? Database::forward : Database::reverse,\n impl_->bufsiz);\n\n if (!impl_->events.empty()) {\n \/* When starting to replay, assume that time T=0 is the time of the\n * first event in the stream.\n * T= -1 is EOF.\n * Convert to timestamp of first item in the returned events.\n *\n * When playing in reverse, the first item in the list is the last event in the database.\n *\/\n if (impl_->ts == 0 || impl_->ts == -1)\n impl_->ts = impl_->events.front()->timestamp;\n\n \/\/ save timestamp of last event retrieved to avoid duplication\n impl_->last_event = impl_->events.back()->timestamp;\n }\n }\n\n if (! impl_->events.empty()) {\n \/\/ time until next event\n Timestamp delta = impl_->events.front()->timestamp - impl_->ts;\n LOG_DEBUG(\"Next event in \" << delta << \" ms\");\n\n \/\/ update our notion of the current time after the timer expires\n impl_->ts = impl_->events.front()->timestamp;\n\n \/* Adjust for playback speed. Note that when playing events in reverse, both speed\n * delta will be negative, which will turn delta into a positive value for the\n * async_wait() call, which is exactly what is required. *\/\n delta \/= impl_->speed;\n\n impl_->timer.expires_from_now(boost::posix_time::millisec(delta));\n impl_->timer.async_wait(boost::bind(&ReplayState::timer_handler, shared_from_this(), boost::asio::placeholders::error));\n impl_->state = impl::running;\n } else {\n \/*\n * FIXME what should happen when the end of the event stream is reached?\n * One option would be to convert to live stream at this point.\n *\/\n LOG_DEBUG(\"reached end of database, pausing playback\");\n impl_->state = impl::paused;\n }\n TRACE_EXIT();\n}\n\n\/** Replay events to a GUI client when a timer expires.\n *\n * The run() member function is reponsible for prefetching events from the\n * database and storing them in the class object. When a timer expires, run\n * through the locally stored events and send those that occurred within the\n * last time slice. The task is then rescheduled when the next most recent\n * event needs to be transmitted.\n *\/\nvoid ReplayState::timer_handler(const boost::system::error_code& ec)\n{\n TRACE_ENTER();\n if (ec == boost::asio::error::operation_aborted)\n LOG_DEBUG(\"timer was cancelled\");\n else if (impl_->state == impl::paused) {\n LOG_DEBUG(\"timer expired but state is paused!\");\n } else {\n std::vector<MessagePtr> msgs;\n {\n boost::mutex::scoped_lock L(impl_->lock);\n\n while (! impl_->events.empty()) {\n MessagePtr m = impl_->events.front();\n \/* Replay all events in the current time step. Use the absolute value\n * of the difference in order for forward and reverse replay to work\n * properly. *\/\n if (abs(m->timestamp - impl_->ts) >= impl_->step)\n break;\n msgs.push_back(m);\n impl_->events.pop_front();\n }\n }\n\n ServerConnectionPtr srv = impl_->conn.lock();\n if (srv) { \/* connection is still alive *\/\n srv->sendMessage(msgs);\n run(); \/\/ reschedule this task\n }\n }\n TRACE_EXIT();\n}\n\n\/* This is required to be defined, otherwise a the default dtor will cause a\n * compiler error due to use of scoped_ptr with an incomplete type.\n *\/\nReplayState::~ReplayState()\n{\n TRACE_ENTER();\n TRACE_EXIT();\n}\n\nfloat ReplayState::speed() const\n{\n return impl_->speed;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2013 Plenluno All rights reserved.\n\n#include <gtest\/gtest.h>\n#include <libnode\/node.h>\n#include <libnode\/message_queue.h>\n\n#include <libj\/status.h>\n#include <libj\/thread.h>\n#include <libj\/console.h>\n\nnamespace libj {\nnamespace node {\n\nclass GTestMsgQueueOnMessage : LIBJ_JS_FUNCTION(GTestMsgQueueOnMessage)\n public:\n GTestMsgQueueOnMessage(\n MessageQueue::Ptr mq,\n UInt numPost)\n : count_(0)\n , numPost_(numPost)\n , msgQueue_(mq) {}\n\n UInt count() { return count_; }\n\n virtual Value operator()(JsArray::Ptr args) {\n console::log(args->get(0));\n count_++;\n if (count_ >= numPost_) msgQueue_->stop();\n return Status::OK;\n }\n\n private:\n UInt count_;\n UInt numPost_;\n MessageQueue::Ptr msgQueue_;\n};\n\nclass GTestMsgQueueNodeRun : LIBJ_JS_FUNCTION(GTestMsgQueueNodeRun)\n public:\n virtual Value operator()(JsArray::Ptr args) {\n node::run();\n return Status::OK;\n }\n};\n\nclass GTestMsgQueuePostMessage : LIBJ_JS_FUNCTION(GTestMsgQueuePostMessage)\n public:\n GTestMsgQueuePostMessage(\n MessageQueue::Ptr mq,\n UInt numPost)\n : numPost_(numPost)\n , msgQueue_(mq) {}\n\n virtual Value operator()(JsArray::Ptr args) {\n for (UInt i = 0; i < numPost_; i++) {\n msgQueue_->postMessage(i);\n }\n return Status::OK;\n }\n\n private:\n UInt numPost_;\n MessageQueue::Ptr msgQueue_;\n};\n\nstatic const UInt NUM_POSTS = 7;\nstatic const UInt NUM_THREADS = 5;\n\nTEST(GTestMessageQueue, TestPostMessageSameThread) {\n MessageQueue::Ptr mq = MessageQueue::create();\n mq->start();\n\n GTestMsgQueueOnMessage::Ptr onMessage(\n new GTestMsgQueueOnMessage(mq, NUM_POSTS));\n mq->on(MessageQueue::EVENT_MESSAGE, onMessage);\n\n for (UInt i = 0; i < NUM_POSTS; i++) {\n mq->postMessage(String::create(\"msg\"));\n }\n\n node::run();\n\n ASSERT_EQ(NUM_POSTS, onMessage->count());\n}\n\nTEST(GTestMessageQueue, TestPostMessageMultiThread) {\n MessageQueue::Ptr mq = MessageQueue::create();\n mq->start();\n\n GTestMsgQueueOnMessage::Ptr onMessage(\n new GTestMsgQueueOnMessage(mq, NUM_POSTS * NUM_THREADS));\n mq->on(MessageQueue::EVENT_MESSAGE, onMessage);\n\n Thread::Ptr nodeRun(Thread::create(\n Function::Ptr(new GTestMsgQueueNodeRun())));\n\n JsArray::Ptr threads = JsArray::create();\n for (Size i = 0; i < NUM_THREADS; i++) {\n threads->add(Thread::create(\n Function::Ptr(new GTestMsgQueuePostMessage(mq, NUM_POSTS))));\n }\n\n nodeRun->start();\n\n for (Size i = 0; i < NUM_THREADS; i++) {\n threads->getPtr<Thread>(i)->start();\n }\n\n nodeRun->join();\n\n for (Size i = 0; i < NUM_THREADS; i++) {\n threads->getPtr<Thread>(i)->join();\n }\n\n ASSERT_EQ(NUM_POSTS * NUM_THREADS, onMessage->count());\n}\n\n} \/\/ namespace node\n} \/\/ namespace libj\n<commit_msg>fix memory leaks<commit_after>\/\/ Copyright (c) 2013 Plenluno All rights reserved.\n\n#include <gtest\/gtest.h>\n#include <libnode\/node.h>\n#include <libnode\/message_queue.h>\n\n#include <libj\/status.h>\n#include <libj\/thread.h>\n\nnamespace libj {\nnamespace node {\n\nclass GTestMsgQueueOnMessage : LIBJ_JS_FUNCTION(GTestMsgQueueOnMessage)\n public:\n GTestMsgQueueOnMessage(\n MessageQueue::Ptr mq,\n UInt numPost)\n : count_(0)\n , numPost_(numPost)\n , msgQueue_(mq) {}\n\n UInt count() { return count_; }\n\n virtual Value operator()(JsArray::Ptr args) {\n count_++;\n if (count_ >= numPost_) {\n msgQueue_->stop();\n msgQueue_ = MessageQueue::null();\n }\n return Status::OK;\n }\n\n private:\n UInt count_;\n UInt numPost_;\n MessageQueue::Ptr msgQueue_;\n};\n\nclass GTestMsgQueueNodeRun : LIBJ_JS_FUNCTION(GTestMsgQueueNodeRun)\n public:\n virtual Value operator()(JsArray::Ptr args) {\n node::run();\n return Status::OK;\n }\n};\n\nclass GTestMsgQueuePostMessage : LIBJ_JS_FUNCTION(GTestMsgQueuePostMessage)\n public:\n GTestMsgQueuePostMessage(\n MessageQueue::Ptr mq,\n UInt numPost)\n : numPost_(numPost)\n , msgQueue_(mq) {}\n\n virtual Value operator()(JsArray::Ptr args) {\n for (UInt i = 0; i < numPost_; i++) {\n msgQueue_->postMessage(i);\n }\n return Status::OK;\n }\n\n private:\n UInt numPost_;\n MessageQueue::Ptr msgQueue_;\n};\n\nstatic const UInt NUM_POSTS = 7;\nstatic const UInt NUM_THREADS = 5;\n\nTEST(GTestMessageQueue, TestPostMessageSameThread) {\n MessageQueue::Ptr mq = MessageQueue::create();\n mq->start();\n\n GTestMsgQueueOnMessage::Ptr onMessage(\n new GTestMsgQueueOnMessage(mq, NUM_POSTS));\n mq->on(MessageQueue::EVENT_MESSAGE, onMessage);\n\n for (UInt i = 0; i < NUM_POSTS; i++) {\n mq->postMessage(String::create(\"msg\"));\n }\n\n node::run();\n\n ASSERT_EQ(NUM_POSTS, onMessage->count());\n}\n\nTEST(GTestMessageQueue, TestPostMessageMultiThread) {\n MessageQueue::Ptr mq = MessageQueue::create();\n mq->start();\n\n GTestMsgQueueOnMessage::Ptr onMessage(\n new GTestMsgQueueOnMessage(mq, NUM_POSTS * NUM_THREADS));\n mq->on(MessageQueue::EVENT_MESSAGE, onMessage);\n\n Thread::Ptr nodeRun(Thread::create(\n Function::Ptr(new GTestMsgQueueNodeRun())));\n\n JsArray::Ptr threads = JsArray::create();\n for (Size i = 0; i < NUM_THREADS; i++) {\n threads->add(Thread::create(\n Function::Ptr(new GTestMsgQueuePostMessage(mq, NUM_POSTS))));\n }\n\n nodeRun->start();\n\n for (Size i = 0; i < NUM_THREADS; i++) {\n threads->getPtr<Thread>(i)->start();\n }\n\n nodeRun->join();\n\n for (Size i = 0; i < NUM_THREADS; i++) {\n threads->getPtr<Thread>(i)->join();\n }\n\n ASSERT_EQ(NUM_POSTS * NUM_THREADS, onMessage->count());\n}\n\n} \/\/ namespace node\n} \/\/ namespace libj\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: embeddoc.hxx,v $\n *\n * $Revision: 1.11 $\n *\n * last change: $Author: rt $ $Date: 2005-09-08 18:55:53 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef _EMBEDDOC_HXX_\n#define _EMBEDDOC_HXX_\n#if defined(_MSC_VER) && (_MSC_VER >= 1300)\n#undef _DEBUG\n#endif\n\n#include \"common.h\"\n#include <oleidl.h>\n\n#include <hash_map>\n\n#ifndef _COM_SUN_STAR_UNO_REFERENCE_H_\n#include <com\/sun\/star\/uno\/Reference.h>\n#endif\n#ifndef _COM_SUN_STAR_UNO_SEQUENCE_H_\n#include <com\/sun\/star\/uno\/SEQUENCE.h>\n#endif\n\n#include \"docholder.hxx\"\n\ntypedef ::std::hash_map< DWORD, IAdviseSink* > AdviseSinkHashMap;\ntypedef ::std::hash_map< DWORD, IAdviseSink* >::iterator AdviseSinkHashMapIterator;\n\nclass GDIMetaFile;\nclass CIIAObj;\n\n\nclass EmbedDocument_Impl\n : public IPersistStorage,\n public IDataObject,\n public IOleObject,\n public IOleInPlaceObject,\n public IPersistFile,\n public IDispatch\n{\nprotected:\n ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >\n fillArgsForLoading_Impl( ::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream > xStream,\n DWORD nStreamMode,\n LPCOLESTR pFilePath = NULL );\n ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >\n fillArgsForStoring_Impl( ::com::sun::star::uno::Reference< ::com::sun::star::io::XOutputStream > xStream );\n\n HRESULT SaveTo_Impl( IStorage* pStg );\n\n sal_uInt64 getMetaFileHandle_Impl( sal_Bool isEnhMeta );\n\npublic:\n EmbedDocument_Impl( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& smgr,\n const GUID* guid );\n ~EmbedDocument_Impl();\n\n \/* IUnknown methods *\/\n STDMETHOD(QueryInterface)(REFIID riid, LPVOID FAR * ppvObj);\n STDMETHOD_(ULONG, AddRef)();\n STDMETHOD_(ULONG, Release)();\n\n \/* IPersistMethod *\/\n STDMETHOD(GetClassID)(CLSID *pClassID);\n\n \/* IPersistStorage methods *\/\n STDMETHOD(IsDirty) ();\n STDMETHOD(InitNew) ( IStorage *pStg );\n STDMETHOD(Load) ( IStorage* pStr );\n STDMETHOD(Save) ( IStorage *pStgSave, BOOL fSameAsLoad );\n STDMETHOD(SaveCompleted) ( IStorage *pStgNew );\n STDMETHOD(HandsOffStorage) (void);\n\n \/* IDataObject methods *\/\n STDMETHOD(GetData) ( FORMATETC * pFormatetc, STGMEDIUM * pMedium );\n STDMETHOD(GetDataHere) ( FORMATETC * pFormatetc, STGMEDIUM * pMedium );\n STDMETHOD(QueryGetData) ( FORMATETC * pFormatetc );\n STDMETHOD(GetCanonicalFormatEtc) ( FORMATETC * pFormatetcIn, FORMATETC * pFormatetcOut );\n STDMETHOD(SetData) ( FORMATETC * pFormatetc, STGMEDIUM * pMedium, BOOL fRelease );\n STDMETHOD(EnumFormatEtc) ( DWORD dwDirection, IEnumFORMATETC ** ppFormatetc );\n STDMETHOD(DAdvise) ( FORMATETC * pFormatetc, DWORD advf, IAdviseSink * pAdvSink, DWORD * pdwConnection );\n STDMETHOD(DUnadvise) ( DWORD dwConnection );\n STDMETHOD(EnumDAdvise) ( IEnumSTATDATA ** ppenumAdvise );\n\n \/* IOleObject methods *\/\n STDMETHOD(SetClientSite) ( IOleClientSite* pSite );\n STDMETHOD(GetClientSite) ( IOleClientSite** pSite );\n STDMETHOD(SetHostNames) ( LPCOLESTR szContainerApp, LPCOLESTR szContainerObj );\n STDMETHOD(Close) ( DWORD dwSaveOption);\n STDMETHOD(SetMoniker) ( DWORD dwWhichMoniker, IMoniker *pmk );\n STDMETHOD(GetMoniker) ( DWORD dwAssign, DWORD dwWhichMoniker, IMoniker **ppmk );\n STDMETHOD(InitFromData) ( IDataObject *pDataObject, BOOL fCreation, DWORD dwReserved );\n STDMETHOD(GetClipboardData) ( DWORD dwReserved, IDataObject **ppDataObject );\n STDMETHOD(DoVerb) ( LONG iVerb, LPMSG lpmsg, IOleClientSite *pActiveSite, LONG lindex, HWND hwndParent, LPCRECT lprcPosRect );\n STDMETHOD(EnumVerbs) ( IEnumOLEVERB **ppEnumOleVerb );\n STDMETHOD(Update) ();\n STDMETHOD(IsUpToDate) ();\n STDMETHOD(GetUserClassID) ( CLSID *pClsid );\n STDMETHOD(GetUserType) ( DWORD dwFormOfType, LPOLESTR *pszUserType );\n STDMETHOD(SetExtent) ( DWORD dwDrawAspect, SIZEL *psizel );\n STDMETHOD(GetExtent) ( DWORD dwDrawAspect, SIZEL *psizel );\n STDMETHOD(Advise) ( IAdviseSink *pAdvSink, DWORD *pdwConnection );\n STDMETHOD(Unadvise) ( DWORD dwConnection );\n STDMETHOD(EnumAdvise) ( IEnumSTATDATA **ppenumAdvise );\n STDMETHOD(GetMiscStatus) ( DWORD dwAspect, DWORD *pdwStatus );\n STDMETHOD(SetColorScheme) ( LOGPALETTE *pLogpal );\n\n \/* IOleInPlaceObject methods *\/\n STDMETHOD(GetWindow)(HWND *);\n STDMETHOD(ContextSensitiveHelp)(BOOL);\n STDMETHOD(InPlaceDeactivate)();\n STDMETHOD(UIDeactivate)();\n STDMETHOD(SetObjectRects)(LPCRECT, LPCRECT);\n STDMETHOD(ReactivateAndUndo)();\n\n \/* IPersistFile methods *\/\n STDMETHOD(Load) ( LPCOLESTR pszFileName, DWORD dwMode );\n STDMETHOD(Save) ( LPCOLESTR pszFileName, BOOL fRemember );\n STDMETHOD(SaveCompleted) ( LPCOLESTR pszFileName );\n STDMETHOD(GetCurFile) ( LPOLESTR *ppszFileName );\n\n \/* IDispatch methods *\/\n STDMETHOD(GetTypeInfoCount) ( unsigned int FAR* pctinfo );\n STDMETHOD(GetTypeInfo) ( unsigned int iTInfo, LCID lcid, ITypeInfo FAR* FAR* ppTInfo );\n STDMETHOD(GetIDsOfNames) ( REFIID riid, OLECHAR FAR* FAR* rgszNames, unsigned int cNames, LCID lcid, DISPID FAR* rgDispId );\n STDMETHOD(Invoke) ( DISPID dispIdMember, REFIID riid, LCID lcid, WORD wFlags, DISPPARAMS FAR* pDispParams, VARIANT FAR* pVarResult, EXCEPINFO FAR* pExcepInfo, unsigned int FAR* puArgErr );\n\n \/\/ c++ - methods\n\n void notify();\n HRESULT SaveObject();\n HRESULT ShowObject();\n GUID GetGUID() const { return m_guid; }\n\nprotected:\n oslInterlockedCount m_refCount;\n\n ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > m_xFactory;\n\n DocumentHolder* m_pDocHolder;\n ::rtl::OUString m_aFileName;\n\n CComPtr< IStorage > m_pMasterStorage;\n CComPtr< IStream > m_pOwnStream;\n CComPtr< IStream > m_pExtStream;\n GUID m_guid;\n\n sal_Bool m_bIsDirty;\n\n CComPtr< IOleClientSite > m_pClientSite;\n CComPtr< IDataAdviseHolder > m_pDAdviseHolder;\n\n AdviseSinkHashMap m_aAdviseHashMap;\n DWORD m_nAdviseNum;\n};\n\n#endif \/\/_EMBEDDOC_HXX_\n\n<commit_msg>INTEGRATION: CWS rtfpp2 (1.11.12); FILE MERGED 2006\/02\/06 16:30:48 mba 1.11.12.1: #128676#: superfluous notification of DataChanged after saving<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: embeddoc.hxx,v $\n *\n * $Revision: 1.12 $\n *\n * last change: $Author: rt $ $Date: 2006-02-09 13:37:27 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef _EMBEDDOC_HXX_\n#define _EMBEDDOC_HXX_\n#if defined(_MSC_VER) && (_MSC_VER >= 1300)\n#undef _DEBUG\n#endif\n\n#include \"common.h\"\n#include <oleidl.h>\n\n#include <hash_map>\n\n#ifndef _COM_SUN_STAR_UNO_REFERENCE_H_\n#include <com\/sun\/star\/uno\/Reference.h>\n#endif\n#ifndef _COM_SUN_STAR_UNO_SEQUENCE_H_\n#include <com\/sun\/star\/uno\/SEQUENCE.h>\n#endif\n\n#include \"docholder.hxx\"\n\ntypedef ::std::hash_map< DWORD, IAdviseSink* > AdviseSinkHashMap;\ntypedef ::std::hash_map< DWORD, IAdviseSink* >::iterator AdviseSinkHashMapIterator;\n\nclass GDIMetaFile;\nclass CIIAObj;\n\n\nclass EmbedDocument_Impl\n : public IPersistStorage,\n public IDataObject,\n public IOleObject,\n public IOleInPlaceObject,\n public IPersistFile,\n public IDispatch\n{\nprotected:\n ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >\n fillArgsForLoading_Impl( ::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream > xStream,\n DWORD nStreamMode,\n LPCOLESTR pFilePath = NULL );\n ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >\n fillArgsForStoring_Impl( ::com::sun::star::uno::Reference< ::com::sun::star::io::XOutputStream > xStream );\n\n HRESULT SaveTo_Impl( IStorage* pStg );\n\n sal_uInt64 getMetaFileHandle_Impl( sal_Bool isEnhMeta );\n\npublic:\n EmbedDocument_Impl( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& smgr,\n const GUID* guid );\n ~EmbedDocument_Impl();\n\n \/* IUnknown methods *\/\n STDMETHOD(QueryInterface)(REFIID riid, LPVOID FAR * ppvObj);\n STDMETHOD_(ULONG, AddRef)();\n STDMETHOD_(ULONG, Release)();\n\n \/* IPersistMethod *\/\n STDMETHOD(GetClassID)(CLSID *pClassID);\n\n \/* IPersistStorage methods *\/\n STDMETHOD(IsDirty) ();\n STDMETHOD(InitNew) ( IStorage *pStg );\n STDMETHOD(Load) ( IStorage* pStr );\n STDMETHOD(Save) ( IStorage *pStgSave, BOOL fSameAsLoad );\n STDMETHOD(SaveCompleted) ( IStorage *pStgNew );\n STDMETHOD(HandsOffStorage) (void);\n\n \/* IDataObject methods *\/\n STDMETHOD(GetData) ( FORMATETC * pFormatetc, STGMEDIUM * pMedium );\n STDMETHOD(GetDataHere) ( FORMATETC * pFormatetc, STGMEDIUM * pMedium );\n STDMETHOD(QueryGetData) ( FORMATETC * pFormatetc );\n STDMETHOD(GetCanonicalFormatEtc) ( FORMATETC * pFormatetcIn, FORMATETC * pFormatetcOut );\n STDMETHOD(SetData) ( FORMATETC * pFormatetc, STGMEDIUM * pMedium, BOOL fRelease );\n STDMETHOD(EnumFormatEtc) ( DWORD dwDirection, IEnumFORMATETC ** ppFormatetc );\n STDMETHOD(DAdvise) ( FORMATETC * pFormatetc, DWORD advf, IAdviseSink * pAdvSink, DWORD * pdwConnection );\n STDMETHOD(DUnadvise) ( DWORD dwConnection );\n STDMETHOD(EnumDAdvise) ( IEnumSTATDATA ** ppenumAdvise );\n\n \/* IOleObject methods *\/\n STDMETHOD(SetClientSite) ( IOleClientSite* pSite );\n STDMETHOD(GetClientSite) ( IOleClientSite** pSite );\n STDMETHOD(SetHostNames) ( LPCOLESTR szContainerApp, LPCOLESTR szContainerObj );\n STDMETHOD(Close) ( DWORD dwSaveOption);\n STDMETHOD(SetMoniker) ( DWORD dwWhichMoniker, IMoniker *pmk );\n STDMETHOD(GetMoniker) ( DWORD dwAssign, DWORD dwWhichMoniker, IMoniker **ppmk );\n STDMETHOD(InitFromData) ( IDataObject *pDataObject, BOOL fCreation, DWORD dwReserved );\n STDMETHOD(GetClipboardData) ( DWORD dwReserved, IDataObject **ppDataObject );\n STDMETHOD(DoVerb) ( LONG iVerb, LPMSG lpmsg, IOleClientSite *pActiveSite, LONG lindex, HWND hwndParent, LPCRECT lprcPosRect );\n STDMETHOD(EnumVerbs) ( IEnumOLEVERB **ppEnumOleVerb );\n STDMETHOD(Update) ();\n STDMETHOD(IsUpToDate) ();\n STDMETHOD(GetUserClassID) ( CLSID *pClsid );\n STDMETHOD(GetUserType) ( DWORD dwFormOfType, LPOLESTR *pszUserType );\n STDMETHOD(SetExtent) ( DWORD dwDrawAspect, SIZEL *psizel );\n STDMETHOD(GetExtent) ( DWORD dwDrawAspect, SIZEL *psizel );\n STDMETHOD(Advise) ( IAdviseSink *pAdvSink, DWORD *pdwConnection );\n STDMETHOD(Unadvise) ( DWORD dwConnection );\n STDMETHOD(EnumAdvise) ( IEnumSTATDATA **ppenumAdvise );\n STDMETHOD(GetMiscStatus) ( DWORD dwAspect, DWORD *pdwStatus );\n STDMETHOD(SetColorScheme) ( LOGPALETTE *pLogpal );\n\n \/* IOleInPlaceObject methods *\/\n STDMETHOD(GetWindow)(HWND *);\n STDMETHOD(ContextSensitiveHelp)(BOOL);\n STDMETHOD(InPlaceDeactivate)();\n STDMETHOD(UIDeactivate)();\n STDMETHOD(SetObjectRects)(LPCRECT, LPCRECT);\n STDMETHOD(ReactivateAndUndo)();\n\n \/* IPersistFile methods *\/\n STDMETHOD(Load) ( LPCOLESTR pszFileName, DWORD dwMode );\n STDMETHOD(Save) ( LPCOLESTR pszFileName, BOOL fRemember );\n STDMETHOD(SaveCompleted) ( LPCOLESTR pszFileName );\n STDMETHOD(GetCurFile) ( LPOLESTR *ppszFileName );\n\n \/* IDispatch methods *\/\n STDMETHOD(GetTypeInfoCount) ( unsigned int FAR* pctinfo );\n STDMETHOD(GetTypeInfo) ( unsigned int iTInfo, LCID lcid, ITypeInfo FAR* FAR* ppTInfo );\n STDMETHOD(GetIDsOfNames) ( REFIID riid, OLECHAR FAR* FAR* rgszNames, unsigned int cNames, LCID lcid, DISPID FAR* rgDispId );\n STDMETHOD(Invoke) ( DISPID dispIdMember, REFIID riid, LCID lcid, WORD wFlags, DISPPARAMS FAR* pDispParams, VARIANT FAR* pVarResult, EXCEPINFO FAR* pExcepInfo, unsigned int FAR* puArgErr );\n\n \/\/ c++ - methods\n\n void notify( bool bDataChanged = true );\n HRESULT SaveObject();\n HRESULT ShowObject();\n GUID GetGUID() const { return m_guid; }\n\nprotected:\n oslInterlockedCount m_refCount;\n\n ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > m_xFactory;\n\n DocumentHolder* m_pDocHolder;\n ::rtl::OUString m_aFileName;\n\n CComPtr< IStorage > m_pMasterStorage;\n CComPtr< IStream > m_pOwnStream;\n CComPtr< IStream > m_pExtStream;\n GUID m_guid;\n\n sal_Bool m_bIsDirty;\n\n CComPtr< IOleClientSite > m_pClientSite;\n CComPtr< IDataAdviseHolder > m_pDAdviseHolder;\n\n AdviseSinkHashMap m_aAdviseHashMap;\n DWORD m_nAdviseNum;\n};\n\n#endif \/\/_EMBEDDOC_HXX_\n\n<|endoftext|>"} {"text":"<commit_before>\/**\n * \\file Constants.hpp\n * \\brief Defines some useful constants used throughout graphics applications.\n * These are fully templated and default to float.\n *\/\n\n#ifndef ATLAS_INCLUDE_ATLAS_CORE_CONSTANTS_HPP\n#define ATLAS_INCLUDE_ATLAS_CORE_CONSTANTS_HPP\n\n#pragma once\n\n#include <limits>\n\nnamespace atlas\n{\n namespace core\n {\n \/**\n * Returns the defined epsilon value for that data type.\n * @tparam The numerical data type.\n *\/\n template <typename GenType = float>\n constexpr GenType epsilon()\n {\n return std::numeric_limits<GenType>::epsilon();\n }\n\n template <typename GenType = float>\n constexpr GenType negInfinity()\n {\n return std::numeric_limits<GenType>::lowest();\n }\n\n \/**\n * Returns the \"infinity\" (maximum value) that the specified data type\n * can represent.\n * @tparam The numerical data type.\n *\/\n template <typename GenType = float>\n constexpr GenType infinity()\n {\n return std::numeric_limits<GenType>::max();\n }\n }\n}\n\n#endif<commit_msg>[brief] Adds enable_if to infinity constants.<commit_after>\/**\n * \\file Constants.hpp\n * \\brief Defines some useful constants used throughout graphics applications.\n * These are fully templated and default to float.\n *\/\n\n#ifndef ATLAS_INCLUDE_ATLAS_CORE_CONSTANTS_HPP\n#define ATLAS_INCLUDE_ATLAS_CORE_CONSTANTS_HPP\n\n#pragma once\n\n#include <limits>\n\nnamespace atlas\n{\n namespace core\n {\n \/**\n * Returns the defined epsilon value for that data type.\n * @tparam The numerical data type.\n *\/\n template <typename GenType = float>\n constexpr GenType epsilon()\n {\n return std::numeric_limits<GenType>::epsilon();\n }\n\n \/**\n * Returns the \"infinity\" (maximum value) that the specified data type\n * can represent.\n * @tparam The numerical data type.\n *\/\n template <typename GenType = float>\n constexpr typename std::enable_if<\n std::numeric_limits<GenType>::has_infinity, GenType>::type\n infinity()\n {\n return std::numeric_limits<GenType>::infinity();\n }\n\n template <typename GenType = float>\n constexpr typename std::enable_if<\n std::numeric_limits<GenType>::has_infinity, GenType>::type\n negInfinity()\n {\n return GenType(-1) * infinity<GenType>();\n }\n }\n}\n\n#endif<|endoftext|>"} {"text":"<commit_before>\/\/=======================================================================\n\/\/ Copyright (c) 2014 Baptiste Wicht\n\/\/ Distributed under the terms of the MIT License.\n\/\/ (See accompanying file LICENSE or copy at\n\/\/ http:\/\/opensource.org\/licenses\/MIT)\n\/\/=======================================================================\n\n#ifndef DLL_CONV_RBM_MP_DESC_HPP\n#define DLL_CONV_RBM_MP_DESC_HPP\n\n#include \"base_conf.hpp\"\n#include \"contrastive_divergence.hpp\"\n#include \"watcher.hpp\"\n#include \"tmp.hpp\"\n\nnamespace dll {\n\n\/*!\n * \\brief Describe a Convolutional Restricted Boltzmann Machine with\n * Probabilistic Max Pooling layer.\n *\n * This struct should be used to define a RBM either as standalone or for a DBN.\n * Once configured, the ::rbm_t member returns the type of the configured RBM.\n *\/\ntemplate<std::size_t NV_T, std::size_t NH_T, std::size_t K_T, std::size_t C_T, typename... Parameters>\nstruct conv_rbm_mp_desc {\n static constexpr const std::size_t NV = NV_T;\n static constexpr const std::size_t NH = NH_T;\n static constexpr const std::size_t K = K_T;\n static constexpr const std::size_t C = C_T;\n\n static constexpr const bool Momentum = detail::is_present<momentum, Parameters...>::value;\n static constexpr const std::size_t BatchSize = detail::get_value<batch_size<1>, Parameters...>::value;\n static constexpr const unit_type visible_unit = detail::get_value<visible<unit_type::BINARY>, Parameters...>::value;\n static constexpr const unit_type hidden_unit = detail::get_value<hidden<unit_type::BINARY>, Parameters...>::value;\n static constexpr const unit_type PoolingUnit = detail::get_value<pooling_unit<unit_type::BINARY>, Parameters...>::value;\n static constexpr const decay_type Decay = detail::get_value<weight_decay<decay_type::NONE>, Parameters...>::value;\n static constexpr const bool Sparsity = detail::is_present<sparsity, Parameters...>::value;\n\n \/*! The type of the trainer to use to train the RBM *\/\n template <typename RBM>\n using trainer_t = typename detail::get_template_type<trainer<cd1_trainer_t>, Parameters...>::template type<RBM>;\n\n \/*! The type of the watched to use during training *\/\n template <typename RBM>\n using watcher_t = typename detail::get_template_type<watcher<default_rbm_watcher>, Parameters...>::template type<RBM>;\n\n \/*! The RBM type *\/\n using rbm_t = conv_rbm_mp<conv_rbm_mp_desc<NV_T, NH_T, K_T, C_T, Parameters...>>;\n\n \/\/Validate all parameters\n\n static_assert(NV > 0, \"A matrix of at least 1x1 is necessary for the visible units\");\n static_assert(NH > 0, \"A matrix of at least 1x1 is necessary for the hidden units\");\n static_assert(K > 0, \"At least one base is necessary\");\n static_assert(C > 0, \"At least one pooling group is necessary\");\n\n \/\/Make sure only valid types are passed to the configuration list\n static_assert(\n detail::is_valid<detail::tmp_list<\n momentum, batch_size_id, visible_id, hidden_id, pooling_unit_id,\n weight_decay_id, sparsity, trainer_id>\n , Parameters...>::value,\n \"Invalid parameters type\");\n\n static_assert(BatchSize > 0, \"Batch size must be at least 1\");\n\n static_assert(!Sparsity || (Sparsity && hidden_unit == unit_type::BINARY),\n \"Sparsity only works with binary hidden units\");\n};\n\n} \/\/end of dbn namespace\n\n#endif<commit_msg>Fix watcher parameters<commit_after>\/\/=======================================================================\n\/\/ Copyright (c) 2014 Baptiste Wicht\n\/\/ Distributed under the terms of the MIT License.\n\/\/ (See accompanying file LICENSE or copy at\n\/\/ http:\/\/opensource.org\/licenses\/MIT)\n\/\/=======================================================================\n\n#ifndef DLL_CONV_RBM_MP_DESC_HPP\n#define DLL_CONV_RBM_MP_DESC_HPP\n\n#include \"base_conf.hpp\"\n#include \"contrastive_divergence.hpp\"\n#include \"watcher.hpp\"\n#include \"tmp.hpp\"\n\nnamespace dll {\n\n\/*!\n * \\brief Describe a Convolutional Restricted Boltzmann Machine with\n * Probabilistic Max Pooling layer.\n *\n * This struct should be used to define a RBM either as standalone or for a DBN.\n * Once configured, the ::rbm_t member returns the type of the configured RBM.\n *\/\ntemplate<std::size_t NV_T, std::size_t NH_T, std::size_t K_T, std::size_t C_T, typename... Parameters>\nstruct conv_rbm_mp_desc {\n static constexpr const std::size_t NV = NV_T;\n static constexpr const std::size_t NH = NH_T;\n static constexpr const std::size_t K = K_T;\n static constexpr const std::size_t C = C_T;\n\n static constexpr const bool Momentum = detail::is_present<momentum, Parameters...>::value;\n static constexpr const std::size_t BatchSize = detail::get_value<batch_size<1>, Parameters...>::value;\n static constexpr const unit_type visible_unit = detail::get_value<visible<unit_type::BINARY>, Parameters...>::value;\n static constexpr const unit_type hidden_unit = detail::get_value<hidden<unit_type::BINARY>, Parameters...>::value;\n static constexpr const unit_type PoolingUnit = detail::get_value<pooling_unit<unit_type::BINARY>, Parameters...>::value;\n static constexpr const decay_type Decay = detail::get_value<weight_decay<decay_type::NONE>, Parameters...>::value;\n static constexpr const bool Sparsity = detail::is_present<sparsity, Parameters...>::value;\n\n \/*! The type of the trainer to use to train the RBM *\/\n template <typename RBM>\n using trainer_t = typename detail::get_template_type<trainer<cd1_trainer_t>, Parameters...>::template type<RBM>;\n\n \/*! The type of the watched to use during training *\/\n template <typename RBM>\n using watcher_t = typename detail::get_template_type<watcher<default_rbm_watcher>, Parameters...>::template type<RBM>;\n\n \/*! The RBM type *\/\n using rbm_t = conv_rbm_mp<conv_rbm_mp_desc<NV_T, NH_T, K_T, C_T, Parameters...>>;\n\n \/\/Validate all parameters\n\n static_assert(NV > 0, \"A matrix of at least 1x1 is necessary for the visible units\");\n static_assert(NH > 0, \"A matrix of at least 1x1 is necessary for the hidden units\");\n static_assert(K > 0, \"At least one base is necessary\");\n static_assert(C > 0, \"At least one pooling group is necessary\");\n\n \/\/Make sure only valid types are passed to the configuration list\n static_assert(\n detail::is_valid<detail::tmp_list<\n momentum, batch_size_id, visible_id, hidden_id, pooling_unit_id,\n weight_decay_id, sparsity, trainer_id, watcher_id>\n , Parameters...>::value,\n \"Invalid parameters type\");\n\n static_assert(BatchSize > 0, \"Batch size must be at least 1\");\n\n static_assert(!Sparsity || (Sparsity && hidden_unit == unit_type::BINARY),\n \"Sparsity only works with binary hidden units\");\n};\n\n} \/\/end of dbn namespace\n\n#endif<|endoftext|>"} {"text":"<commit_before>\/\/=======================================================================\n\/\/ Copyright (c) 2014-2016 Baptiste Wicht\n\/\/ Distributed under the terms of the MIT License.\n\/\/ (See accompanying file LICENSE or copy at\n\/\/ http:\/\/opensource.org\/licenses\/MIT)\n\/\/=======================================================================\n\n#pragma once\n\nnamespace etl {\n\n\/*!\n * \\brief Define traits to get vectorization information for types when no vector mode is available.\n *\/\ntemplate <typename T>\nstruct no_intrinsic_traits {\n static constexpr const bool vectorizable = false; \/\/\/< Boolean flag indicating if the type is vectorizable or not\n static constexpr const std::size_t size = 1; \/\/\/< Numbers of elements done at once\n static constexpr const std::size_t alignment = alignof(T); \/\/\/< Necessary number of bytes of alignment for this type\n\n using intrinsic_type = T;\n};\n\nstruct no_vec {\n template<typename T>\n using traits = no_intrinsic_traits<T>;\n\n template<typename T>\n using vec_type = typename traits<T>::intrinsic_type;\n\n template <typename F, typename M>\n static inline void storeu(F* \/*memory*\/, M \/*value*\/) {}\n\n template <typename F, typename M>\n static inline void store(F* \/*memory*\/, M \/*value*\/) {}\n\n template <typename F>\n static F load(const F* \/*memory*\/) {}\n\n template <typename F>\n static F loadu(const F* \/*memory*\/) {}\n\n template <typename F>\n static F set(F \/*value*\/) {}\n\n template <typename M>\n static M add(M \/*lhs*\/, M \/*rhs*\/) {}\n\n template <typename M>\n static M sub(M \/*lhs*\/, M \/*rhs*\/) {}\n\n template <typename M>\n static M mul(M \/*lhs*\/, M \/*rhs*\/) {}\n\n template <typename M>\n static M div(M \/*lhs*\/, M \/*rhs*\/) {}\n\n template <typename M>\n static M sqrt(M \/*value*\/) {}\n\n template <typename M>\n static M minus(M \/*value*\/) {}\n};\n\n} \/\/end of namespace etl\n<commit_msg>A bit of doc<commit_after>\/\/=======================================================================\n\/\/ Copyright (c) 2014-2016 Baptiste Wicht\n\/\/ Distributed under the terms of the MIT License.\n\/\/ (See accompanying file LICENSE or copy at\n\/\/ http:\/\/opensource.org\/licenses\/MIT)\n\/\/=======================================================================\n\n#pragma once\n\nnamespace etl {\n\n\/*!\n * \\brief Define traits to get vectorization information for types when no vector mode is available.\n *\/\ntemplate <typename T>\nstruct no_intrinsic_traits {\n static constexpr const bool vectorizable = false; \/\/\/< Boolean flag indicating if the type is vectorizable or not\n static constexpr const std::size_t size = 1; \/\/\/< Numbers of elements done at once\n static constexpr const std::size_t alignment = alignof(T); \/\/\/< Necessary number of bytes of alignment for this type\n\n using intrinsic_type = T;\n};\n\n\/*!\n * \\brief Vectorization support when no vectorization is enabled.\n *\n * This class is purely here to ensure compilation, it will never be called at runtime\n *\/\nstruct no_vec {\n \/*!\n * \\brief The traits for this vectorization implementation\n *\/\n template<typename T>\n using traits = no_intrinsic_traits<T>;\n\n \/*!\n * \\brief The vector type for this vectorization implementation\n *\/\n template<typename T>\n using vec_type = typename traits<T>::intrinsic_type;\n\n \/*!\n * \\brief Unaligned store value to memory\n * \\param memory The target memory\n * \\param value The value to store\n *\/\n template <typename F, typename M>\n static inline void storeu(F* memory, M value) {\n cpp_unused(memory);\n cpp_unused(value);\n }\n\n \/*!\n * \\brief Aligned store value to memory\n * \\param memory The target memory\n * \\param value The value to store\n *\/\n template <typename F, typename M>\n static inline void store(F* memory, M value) {\n cpp_unused(memory);\n cpp_unused(value);\n }\n\n \/*!\n * \\brief Aligned load a vector from memory\n * \\param memory The target memory\n * \\return Vector of values from memory\n *\/\n template <typename F>\n static F load(const F* memory) {\n cpp_unused(memory);\n }\n\n \/*!\n * \\brief Unaligned load a vector from memory\n * \\param memory The target memory\n * \\return Vector of values from memory\n *\/\n template <typename F>\n static F loadu(const F* memory) {\n cpp_unused(memory);\n }\n\n \/*!\n * \\brief Create a vector containing the given value\n * \\param value The value\n * \\return Vector of value\n *\/\n template <typename F>\n static F set(F value) {\n cpp_unused(value);\n }\n\n \/*!\n * \\brief Vector addition or lhs and rhs\n * \\param lhs The left hand side of the operation\n * \\param rhs The right hand side of the operation\n * \\return Vector of the results\n *\/\n template <typename M>\n static M add(M lhs, M rhs) {\n cpp_unused(lhs);\n cpp_unused(rhs);\n }\n\n \/*!\n * \\brief Vector subtraction or lhs and rhs\n * \\param lhs The left hand side of the operation\n * \\param rhs The right hand side of the operation\n * \\return Vector of the results\n *\/\n template <typename M>\n static M sub(M lhs, M rhs) {\n cpp_unused(lhs);\n cpp_unused(rhs);\n }\n\n \/*!\n * \\brief Vector multiplication or lhs and rhs\n * \\param lhs The left hand side of the operation\n * \\param rhs The right hand side of the operation\n * \\return Vector of the results\n *\/\n template <typename M>\n static M mul(M lhs, M rhs) {\n cpp_unused(lhs);\n cpp_unused(rhs);\n }\n\n \/*!\n * \\brief Vector division or lhs and rhs\n * \\param lhs The left hand side of the operation\n * \\param rhs The right hand side of the operation\n * \\return Vector of the results\n *\/\n template <typename M>\n static M div(M lhs, M rhs) {\n cpp_unused(lhs);\n cpp_unused(rhs);\n }\n\n \/*!\n * \\brief Vector square root\n * \\param value The input values\n * \\return The square root of the input values\n *\/\n template <typename M>\n static M sqrt(M value) {\n cpp_unused(value);\n }\n\n \/*!\n * \\brief Compute the negative value of the input\n * \\param value The input values\n * \\return The negative values of the input values\n *\/\n template <typename M>\n static M minus(M value) {\n cpp_unused(value);\n }\n};\n\n} \/\/end of namespace etl\n<|endoftext|>"} {"text":"<commit_before>\/*\n\nCopyright (c) 2009, Arvid Norberg\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in\n the documentation and\/or other materials provided with the distribution.\n * Neither the name of the author nor the names of its\n contributors may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#ifndef TORRENT_SOCKET_IO_HPP_INCLUDED\n#define TORRENT_SOCKET_IO_HPP_INCLUDED\n\n#include \"libtorrent\/socket.hpp\"\n#include \"libtorrent\/address.hpp\"\n#include \"libtorrent\/io.hpp\"\n#include \"libtorrent\/error_code.hpp\"\n#include \"libtorrent\/lazy_entry.hpp\"\n#include <string>\n\nnamespace libtorrent\n{\n\tTORRENT_EXPORT std::string print_address(address const& addr);\n\tTORRENT_EXPORT std::string print_endpoint(tcp::endpoint const& ep);\n\tTORRENT_EXPORT std::string print_endpoint(udp::endpoint const& ep);\n\n\tnamespace detail\n\t{\n\t\ttemplate<class OutIt>\n\t\tvoid write_address(address const& a, OutIt& out)\n\t\t{\n#if TORRENT_USE_IPV6\n\t\t\tif (a.is_v4())\n\t\t\t{\n#endif\n\t\t\t\twrite_uint32(a.to_v4().to_ulong(), out);\n#if TORRENT_USE_IPV6\n\t\t\t}\n\t\t\telse if (a.is_v6())\n\t\t\t{\n\t\t\t\taddress_v6::bytes_type bytes\n\t\t\t\t\t= a.to_v6().to_bytes();\n\t\t\t\tstd::copy(bytes.begin(), bytes.end(), out);\n\t\t\t}\n#endif\n\t\t}\n\n\t\ttemplate<class InIt>\n\t\taddress read_v4_address(InIt& in)\n\t\t{\n\t\t\tunsigned long ip = read_uint32(in);\n\t\t\treturn address_v4(ip);\n\t\t}\n\n#if TORRENT_USE_IPV6\n\t\ttemplate<class InIt>\n\t\taddress read_v6_address(InIt& in)\n\t\t{\n\t\t\ttypedef address_v6::bytes_type bytes_t;\n\t\t\tbytes_t bytes;\n\t\t\tfor (bytes_t::iterator i = bytes.begin()\n\t\t\t\t, end(bytes.end()); i != end; ++i)\n\t\t\t\t*i = read_uint8(in);\n\t\t\treturn address_v6(bytes);\n\t\t}\n#endif\n\n\t\ttemplate<class Endpoint, class OutIt>\n\t\tvoid write_endpoint(Endpoint const& e, OutIt& out)\n\t\t{\n\t\t\twrite_address(e.address(), out);\n\t\t\twrite_uint16(e.port(), out);\n\t\t}\n\n\t\ttemplate<class Endpoint, class InIt>\n\t\tEndpoint read_v4_endpoint(InIt& in)\n\t\t{\n\t\t\taddress addr = read_v4_address(in);\n\t\t\tint port = read_uint16(in);\n\t\t\treturn Endpoint(addr, port);\n\t\t}\n\n#if TORRENT_USE_IPV6\n\t\ttemplate<class Endpoint, class InIt>\n\t\tEndpoint read_v6_endpoint(InIt& in)\n\t\t{\n\t\t\taddress addr = read_v6_address(in);\n\t\t\tint port = read_uint16(in);\n\t\t\treturn Endpoint(addr, port);\n\t\t}\n#endif\n\n\t\ttemplate <class EndpointType>\n\t\tvoid read_endpoint_list(libtorrent::lazy_entry const* n, std::vector<EndpointType>& epl)\n\t\t{\n\t\t\tusing namespace libtorrent;\n\t\t\tif (n->type() != lazy_entry::list_t) return;\n\t\t\tfor (int i = 0; i < n->list_size(); ++i)\n\t\t\t{\n\t\t\t\tlazy_entry const* e = n->list_at(i);\n\t\t\t\tif (e->type() != lazy_entry::string_t) return;\n\t\t\t\tif (e->string_length() < 6) continue;\n\t\t\t\tchar const* in = e->string_ptr();\n\t\t\t\tif (e->string_length() == 6)\n\t\t\t\t\tepl.push_back(read_v4_endpoint<EndpointType>(in));\n#if TORRENT_USE_IPV6\n\t\t\t\telse if (e->string_length() == 18)\n\t\t\t\t\tepl.push_back(read_v6_endpoint<EndpointType>(in));\n#endif\n\t\t\t}\n\t\t}\n\n\t}\n\n\n}\n\n#endif\n\n<commit_msg>fixed bug in write_address<commit_after>\/*\n\nCopyright (c) 2009, Arvid Norberg\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in\n the documentation and\/or other materials provided with the distribution.\n * Neither the name of the author nor the names of its\n contributors may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#ifndef TORRENT_SOCKET_IO_HPP_INCLUDED\n#define TORRENT_SOCKET_IO_HPP_INCLUDED\n\n#include \"libtorrent\/socket.hpp\"\n#include \"libtorrent\/address.hpp\"\n#include \"libtorrent\/io.hpp\"\n#include \"libtorrent\/error_code.hpp\"\n#include \"libtorrent\/lazy_entry.hpp\"\n#include <string>\n\nnamespace libtorrent\n{\n\tTORRENT_EXPORT std::string print_address(address const& addr);\n\tTORRENT_EXPORT std::string print_endpoint(tcp::endpoint const& ep);\n\tTORRENT_EXPORT std::string print_endpoint(udp::endpoint const& ep);\n\n\tnamespace detail\n\t{\n\t\ttemplate<class OutIt>\n\t\tvoid write_address(address const& a, OutIt& out)\n\t\t{\n#if TORRENT_USE_IPV6\n\t\t\tif (a.is_v4())\n\t\t\t{\n#endif\n\t\t\t\twrite_uint32(a.to_v4().to_ulong(), out);\n#if TORRENT_USE_IPV6\n\t\t\t}\n\t\t\telse if (a.is_v6())\n\t\t\t{\n\t\t\t\ttypedef address_v6::bytes_type bytes_t;\n\t\t\t\tbytes_t bytes = a.to_v6().to_bytes();\n\t\t\t\tfor (bytes_t::iterator i = bytes.begin()\n\t\t\t\t\t, end(bytes.end()); i != end; ++i)\n\t\t\t\t\twrite_uint8(*i, out);\n\t\t\t}\n#endif\n\t\t}\n\n\t\ttemplate<class InIt>\n\t\taddress read_v4_address(InIt& in)\n\t\t{\n\t\t\tunsigned long ip = read_uint32(in);\n\t\t\treturn address_v4(ip);\n\t\t}\n\n#if TORRENT_USE_IPV6\n\t\ttemplate<class InIt>\n\t\taddress read_v6_address(InIt& in)\n\t\t{\n\t\t\ttypedef address_v6::bytes_type bytes_t;\n\t\t\tbytes_t bytes;\n\t\t\tfor (bytes_t::iterator i = bytes.begin()\n\t\t\t\t, end(bytes.end()); i != end; ++i)\n\t\t\t\t*i = read_uint8(in);\n\t\t\treturn address_v6(bytes);\n\t\t}\n#endif\n\n\t\ttemplate<class Endpoint, class OutIt>\n\t\tvoid write_endpoint(Endpoint const& e, OutIt& out)\n\t\t{\n\t\t\twrite_address(e.address(), out);\n\t\t\twrite_uint16(e.port(), out);\n\t\t}\n\n\t\ttemplate<class Endpoint, class InIt>\n\t\tEndpoint read_v4_endpoint(InIt& in)\n\t\t{\n\t\t\taddress addr = read_v4_address(in);\n\t\t\tint port = read_uint16(in);\n\t\t\treturn Endpoint(addr, port);\n\t\t}\n\n#if TORRENT_USE_IPV6\n\t\ttemplate<class Endpoint, class InIt>\n\t\tEndpoint read_v6_endpoint(InIt& in)\n\t\t{\n\t\t\taddress addr = read_v6_address(in);\n\t\t\tint port = read_uint16(in);\n\t\t\treturn Endpoint(addr, port);\n\t\t}\n#endif\n\n\t\ttemplate <class EndpointType>\n\t\tvoid read_endpoint_list(libtorrent::lazy_entry const* n, std::vector<EndpointType>& epl)\n\t\t{\n\t\t\tusing namespace libtorrent;\n\t\t\tif (n->type() != lazy_entry::list_t) return;\n\t\t\tfor (int i = 0; i < n->list_size(); ++i)\n\t\t\t{\n\t\t\t\tlazy_entry const* e = n->list_at(i);\n\t\t\t\tif (e->type() != lazy_entry::string_t) return;\n\t\t\t\tif (e->string_length() < 6) continue;\n\t\t\t\tchar const* in = e->string_ptr();\n\t\t\t\tif (e->string_length() == 6)\n\t\t\t\t\tepl.push_back(read_v4_endpoint<EndpointType>(in));\n#if TORRENT_USE_IPV6\n\t\t\t\telse if (e->string_length() == 18)\n\t\t\t\t\tepl.push_back(read_v6_endpoint<EndpointType>(in));\n#endif\n\t\t\t}\n\t\t}\n\n\t}\n\n\n}\n\n#endif\n\n<|endoftext|>"} {"text":"<commit_before>\/* This file is part of Zanshin\n\n Copyright 2014 Kevin Ottens <ervin@kde.org>\n\n This program is free software; you can redistribute it and\/or\n modify it under the terms of the GNU General Public License as\n published by the Free Software Foundation; either version 2 of\n the License or (at your option) version 3 or any later version\n accepted by the membership of KDE e.V. (or its successor approved\n by the membership of KDE e.V.), which shall act as a proxy\n defined in Section 14 of version 3 of the license.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with this program; if not, write to the Free Software\n Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,\n USA.\n*\/\n\n\n#include \"itemdelegate.h\"\n\n#include <QStyleOptionViewItemV4>\n\n#include \"domain\/note.h\"\n#include \"domain\/task.h\"\n#include \"presentation\/querytreemodelbase.h\"\n\nusing namespace Widgets;\n\nItemDelegate::ItemDelegate(QObject *parent)\n : QStyledItemDelegate(parent)\n{\n}\n\nQSize ItemDelegate::sizeHint(const QStyleOptionViewItem &option,\n const QModelIndex &index) const\n{\n \/\/ Make sure they all get the height needed for a check indicator\n QStyleOptionViewItemV4 opt = option;\n opt.features = QStyleOptionViewItemV4::HasCheckIndicator;\n QSize res = QStyledItemDelegate::sizeHint(opt, index);\n return res;\n}\n\nvoid ItemDelegate::paint(QPainter *painter,\n const QStyleOptionViewItem &option,\n const QModelIndex &index) const\n{\n QStyleOptionViewItemV4 opt = option;\n\n Domain::Task::Ptr task;\n Domain::Note::Ptr note;\n\n QVariant data = index.data(Presentation::QueryTreeModelBase::ObjectRole);\n auto artifact = data.value<Domain::Artifact::Ptr>();\n if (artifact) {\n task = artifact.dynamicCast<Domain::Task>();\n note = artifact.dynamicCast<Domain::Note>();\n } else {\n task = data.value<Domain::Task::Ptr>();\n note = data.value<Domain::Note::Ptr>();\n }\n\n if (task) {\n if (task->isDone()) {\n opt.font.setStrikeOut(true);\n } else {\n if (task->startDate().isValid()\n && task->startDate().date() <= QDate::currentDate()) {\n opt.font.setBold(true);\n }\n\n if (task->dueDate().isValid()) {\n if (task->dueDate().date() < QDate::currentDate()) {\n opt.font.setBold(true);\n opt.palette.setColor(QPalette::Text, QColor(Qt::red));\n opt.palette.setColor(QPalette::HighlightedText, QColor(Qt::red));\n\n } else if (task->dueDate().date() == QDate::currentDate()) {\n opt.font.setBold(true);\n opt.palette.setColor(QPalette::Text, QColor(\"orange\"));\n opt.palette.setColor(QPalette::HighlightedText, QColor(\"orange\"));\n }\n }\n }\n }\n\n if (note) {\n opt.features |= QStyleOptionViewItemV4::HasDecoration;\n opt.icon = QIcon::fromTheme(\"text-plain\");\n }\n\n QStyledItemDelegate::paint(painter, opt, index);\n}\n<commit_msg>Display delegated tasks differently<commit_after>\/* This file is part of Zanshin\n\n Copyright 2014 Kevin Ottens <ervin@kde.org>\n\n This program is free software; you can redistribute it and\/or\n modify it under the terms of the GNU General Public License as\n published by the Free Software Foundation; either version 2 of\n the License or (at your option) version 3 or any later version\n accepted by the membership of KDE e.V. (or its successor approved\n by the membership of KDE e.V.), which shall act as a proxy\n defined in Section 14 of version 3 of the license.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with this program; if not, write to the Free Software\n Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,\n USA.\n*\/\n\n\n#include \"itemdelegate.h\"\n\n#include <QApplication>\n#include <QStyleOptionViewItemV4>\n\n#include \"domain\/note.h\"\n#include \"domain\/task.h\"\n#include \"presentation\/querytreemodelbase.h\"\n\nusing namespace Widgets;\n\nItemDelegate::ItemDelegate(QObject *parent)\n : QStyledItemDelegate(parent)\n{\n}\n\nQSize ItemDelegate::sizeHint(const QStyleOptionViewItem &option,\n const QModelIndex &index) const\n{\n \/\/ Make sure they all get the height needed for a check indicator\n QStyleOptionViewItemV4 opt = option;\n opt.features = QStyleOptionViewItemV4::HasCheckIndicator;\n QSize res = QStyledItemDelegate::sizeHint(opt, index);\n return res;\n}\n\nvoid ItemDelegate::paint(QPainter *painter,\n const QStyleOptionViewItem &option,\n const QModelIndex &index) const\n{\n QStyleOptionViewItemV4 opt = option;\n initStyleOption(&opt, index);\n\n Domain::Task::Ptr task;\n Domain::Note::Ptr note;\n\n QVariant data = index.data(Presentation::QueryTreeModelBase::ObjectRole);\n auto artifact = data.value<Domain::Artifact::Ptr>();\n if (artifact) {\n task = artifact.dynamicCast<Domain::Task>();\n note = artifact.dynamicCast<Domain::Note>();\n } else {\n task = data.value<Domain::Task::Ptr>();\n note = data.value<Domain::Note::Ptr>();\n }\n\n if (task) {\n if (task->isDone()) {\n opt.font.setStrikeOut(true);\n } else {\n if (task->startDate().isValid()\n && task->startDate().date() <= QDate::currentDate()) {\n opt.font.setBold(true);\n }\n\n if (task->dueDate().isValid()) {\n if (task->dueDate().date() < QDate::currentDate()) {\n opt.font.setBold(true);\n opt.palette.setColor(QPalette::Text, QColor(Qt::red));\n opt.palette.setColor(QPalette::HighlightedText, QColor(Qt::red));\n\n } else if (task->dueDate().date() == QDate::currentDate()) {\n opt.font.setBold(true);\n opt.palette.setColor(QPalette::Text, QColor(\"orange\"));\n opt.palette.setColor(QPalette::HighlightedText, QColor(\"orange\"));\n }\n }\n }\n\n if (task->delegate().isValid()) {\n opt.text = QString(\"(%1) %2\").arg(task->delegate().display(), opt.text);\n opt.font.setItalic(true);\n }\n }\n\n if (note) {\n opt.features |= QStyleOptionViewItemV4::HasDecoration;\n opt.icon = QIcon::fromTheme(\"text-plain\");\n }\n\n const QWidget *widget = opt.widget;\n QStyle *style = widget ? widget->style() : QApplication::style();\n style->drawControl(QStyle::CE_ItemViewItem, &opt, painter, widget);\n}\n<|endoftext|>"} {"text":"<commit_before>#include <stdexcept>\n#include <unordered_map>\n\n#include \"windowsx.h\"\n\n#include \"windowswindow.hh\"\n#include \"windowsopenglcontext.hh\"\n#include \"system\/mousebutton.hh\"\n#include \"system\/keycode.hh\"\n\nstatic char appName[] = \"Test Application\";\n\nusing System::KeyCode;\n\nclass KeyMap : public std::unordered_map<WPARAM, System::KeyCode>\n{\npublic:\n KeyMap() : std::unordered_map<WPARAM, System::KeyCode>() {\n (*this)[VK_PRIOR] = KeyCode::KeyPageUp;\n (*this)[VK_NEXT] = KeyCode::KeyPageDown;\n (*this)[VK_END] = KeyCode::KeyEnd;\n (*this)[VK_HOME] = KeyCode::KeyHome;\n (*this)[VK_INSERT] = KeyCode::KeyInsert;\n (*this)[VK_DELETE] = KeyCode::KeyDelete;\n\n (*this)[VK_RIGHT] = KeyCode::KeyRightArrow;\n (*this)[VK_DOWN] = KeyCode::KeyDownArrow;\n (*this)[VK_LEFT] = KeyCode::KeyLeftArrow;\n (*this)[VK_UP] = KeyCode::KeyUpArrow;\n\n (*this)[VK_ESCAPE] = KeyCode::KeyEscape;\n (*this)[VK_TAB] = KeyCode::KeyTab;\n (*this)[VK_SHIFT] = KeyCode::KeyShift;\n (*this)[VK_MENU] = KeyCode::KeyAlt;\n (*this)[VK_CONTROL] = KeyCode::KeyControl;\n (*this)[VK_CAPITAL] = KeyCode::KeyCapsLock;\n\n (*this)[VK_RCONTROL] = KeyCode::KeyRightControl;\n (*this)[VK_LCONTROL] = KeyCode::KeyLeftControl;\n (*this)[VK_RSHIFT] = KeyCode::KeyRightShift;\n (*this)[VK_LSHIFT] = KeyCode::KeyLeftShift;\n\n (*this)[VK_BACK] = KeyCode::KeyBackspace;\n (*this)[VK_RETURN] = KeyCode::KeyEnter;\n (*this)[VK_SPACE] = KeyCode::KeySpace;\n\n (*this)[0x30] = KeyCode::Key0;\n (*this)[0x31] = KeyCode::Key1;\n (*this)[0x32] = KeyCode::Key2;\n (*this)[0x33] = KeyCode::Key3;\n (*this)[0x34] = KeyCode::Key4;\n (*this)[0x35] = KeyCode::Key5;\n (*this)[0x36] = KeyCode::Key6;\n (*this)[0x37] = KeyCode::Key7;\n (*this)[0x38] = KeyCode::Key8;\n (*this)[0x39] = KeyCode::Key9;\n\n (*this)[VK_NUMPAD0] = KeyCode::KeyNumpad0;\n (*this)[VK_NUMPAD1] = KeyCode::KeyNumpad1;\n (*this)[VK_NUMPAD2] = KeyCode::KeyNumpad2;\n (*this)[VK_NUMPAD3] = KeyCode::KeyNumpad3;\n (*this)[VK_NUMPAD4] = KeyCode::KeyNumpad4;\n (*this)[VK_NUMPAD5] = KeyCode::KeyNumpad5;\n (*this)[VK_NUMPAD6] = KeyCode::KeyNumpad6;\n (*this)[VK_NUMPAD7] = KeyCode::KeyNumpad7;\n (*this)[VK_NUMPAD8] = KeyCode::KeyNumpad8;\n (*this)[VK_NUMPAD9] = KeyCode::KeyNumpad9;\n\n (*this)[VK_MULTIPLY] = KeyCode::KeyMultiply;\n (*this)[VK_ADD] = KeyCode::KeyPlus;\n (*this)[VK_SUBTRACT] = KeyCode::KeyMinus;\n (*this)[VK_DIVIDE] = KeyCode::KeyDivide;\n (*this)[VK_DECIMAL] = KeyCode::KeyDecimal;\n\n (*this)[0x41] = KeyCode::KeyA;\n (*this)[0x42] = KeyCode::KeyB;\n (*this)[0x43] = KeyCode::KeyC;\n (*this)[0x44] = KeyCode::KeyD;\n (*this)[0x45] = KeyCode::KeyE;\n (*this)[0x46] = KeyCode::KeyF;\n (*this)[0x47] = KeyCode::KeyG;\n (*this)[0x48] = KeyCode::KeyH;\n (*this)[0x49] = KeyCode::KeyI;\n (*this)[0x4A] = KeyCode::KeyJ;\n (*this)[0x4B] = KeyCode::KeyK;\n (*this)[0x4C] = KeyCode::KeyL;\n (*this)[0x4D] = KeyCode::KeyM;\n (*this)[0x4E] = KeyCode::KeyN;\n (*this)[0x4F] = KeyCode::KeyO;\n (*this)[0x50] = KeyCode::KeyP;\n (*this)[0x51] = KeyCode::KeyQ;\n (*this)[0x52] = KeyCode::KeyR;\n (*this)[0x53] = KeyCode::KeyS;\n (*this)[0x54] = KeyCode::KeyT;\n (*this)[0x55] = KeyCode::KeyU;\n (*this)[0x56] = KeyCode::KeyV;\n (*this)[0x57] = KeyCode::KeyW;\n (*this)[0x59] = KeyCode::KeyY;\n (*this)[0x5A] = KeyCode::KeyZ;\n }\n};\n\nstatic KeyMap keyMap;\nstatic std::unordered_map<HWND, WindowsWindow*> windowMap;\n\nWindowsWindow::WindowsWindow(const char *windowName, Framework::ISystemWindowController *controller, HINSTANCE processInstance, int commandShow)\n : m_controller(controller), m_openGLContext(NULL)\n{\n m_windowHandle = WindowsWindow::makeWindow(windowName, processInstance, commandShow);\n windowMap[m_windowHandle] = this;\n\n ShowWindow(m_windowHandle, commandShow);\n UpdateWindow(m_windowHandle);\n\n unsigned int windowWidth, windowHeight;\n GetWindowSize(&windowWidth, &windowHeight);\n m_controller->OnWindowResize(windowWidth, windowHeight);\n}\n\nHWND WindowsWindow::makeWindow(const char *windowName, HINSTANCE processInstance, int commandShow)\n{\n WNDCLASSEX windowClass;\n\n windowClass.cbSize = sizeof(WNDCLASSEX);\n windowClass.style = CS_VREDRAW | CS_HREDRAW;\n windowClass.lpfnWndProc = WndProc;\n windowClass.cbClsExtra = 0;\n windowClass.cbWndExtra = 0;\n windowClass.hInstance = processInstance;\n windowClass.hIcon = LoadIcon(NULL, IDI_APPLICATION);\n windowClass.hIconSm = LoadIcon(NULL, IDI_APPLICATION);\n windowClass.hCursor = LoadCursor(NULL, IDC_ARROW);\n windowClass.hbrBackground = (HBRUSH) GetStockObject(BLACK_BRUSH);\n windowClass.lpszClassName = appName;\n windowClass.lpszMenuName = NULL;\n\n RegisterClassEx(&windowClass);\n\n return CreateWindow(appName, windowName, WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, NULL, NULL, processInstance, NULL);\n}\n\nWindowsWindow::~WindowsWindow()\n{\n if (m_openGLContext != NULL)\n delete m_openGLContext;\n\n windowMap[m_windowHandle] = NULL;\n}\n\nint WindowsWindow::DoMessageLoop()\n{\n MSG message;\n\n Ready();\n\n while (GetMessage(&message, NULL, 0, 0))\n {\n TranslateMessage(&message);\n DispatchMessage(&message);\n }\n\n return message.wParam;\n}\n\nSystem::OpenGLContext *WindowsWindow::getOrCreateOpenGLContext()\n{\n if (m_openGLContext == NULL)\n m_openGLContext = new WindowsOpenGLContext(m_windowHandle);\n\n return m_openGLContext;\n}\n\nvoid WindowsWindow::GetWindowSize(unsigned int *width, unsigned int *height)\n{\n RECT rect;\n\n GetClientRect(m_windowHandle, &rect);\n\n *width = rect.right - rect.left;\n *height = rect.bottom - rect.top;\n}\n\nbool WindowsWindow::SetMousePosition(unsigned int posX, unsigned int posY)\n{\n POINT point;\n\n point.x = posX;\n point.y = posY;\n\n bool success = ClientToScreen(m_windowHandle, &point) ? SetCursorPos(point.x, point.y) : false;\n if (success)\n m_controller->OnMouseMove(point.x, point.y);\n\n return success;\n}\n\nvoid WindowsWindow::Destroy()\n{\n SendNotifyMessage(m_windowHandle, WM_DESTROY, 0, 0);\n}\n\nvoid WindowsWindow::Close()\n{\n SendNotifyMessage(m_windowHandle, WM_CLOSE, 0, 0);\n}\n\nvoid WindowsWindow::Ready()\n{\n m_controller->OnWindowReady();\n}\n\nvoid WindowsWindow::onClose()\n{\n m_controller->OnWindowClose();\n}\n\nvoid WindowsWindow::KeyDown(WPARAM key)\n{\n m_controller->OnKeyDown(keyMap[key]);\n}\n\nvoid WindowsWindow::WindowResize(WPARAM wParam, LPARAM lParam)\n{\n m_controller->OnWindowResize(LOWORD(lParam), HIWORD(lParam));\n}\n\nvoid WindowsWindow::KeyUp(WPARAM key)\n{\n m_controller->OnKeyUp(keyMap[key]);\n}\n\nvoid WindowsWindow::MouseMove(WPARAM wParam, LPARAM lParam)\n{\n m_controller->OnMouseMove(GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam));\n}\n\nvoid WindowsWindow::LeftMouseButtonDown(WPARAM wParam, LPARAM lParam)\n{\n m_controller->OnMouseButtonDown(System::MouseButton::ButtonOne);\n}\n\nvoid WindowsWindow::RightMouseButtonDown(WPARAM wParam, LPARAM lParam)\n{\n m_controller->OnMouseButtonDown(System::MouseButton::ButtonTwo);\n}\n\nvoid WindowsWindow::LeftMouseButtonUp(WPARAM wParam, LPARAM lParam)\n{\n m_controller->OnMouseButtonUp(System::MouseButton::ButtonOne);\n}\n\nvoid WindowsWindow::RightMouseButtonUp(WPARAM wParam, LPARAM lParam)\n{\n m_controller->OnMouseButtonUp(System::MouseButton::ButtonTwo);\n}\n\nvoid WindowsWindow::MouseScrollWheel(WPARAM wParam, LPARAM lParam)\n{\n m_controller->OnMouseScroll(GET_WHEEL_DELTA_WPARAM(wParam) \/ WHEEL_DELTA);\n}\n\nLRESULT CALLBACK WindowsWindow::WndProc(HWND windowHandle, UINT message, WPARAM wparam, LPARAM lparam)\n{\n switch(message)\n {\n case WM_KEYDOWN:\n windowMap[windowHandle]->KeyDown(wparam);\n return 0;\n\n case WM_KEYUP:\n windowMap[windowHandle]->KeyUp(wparam);\n return 0;\n\n case WM_MOUSEMOVE:\n windowMap[windowHandle]->MouseMove(wparam, lparam);\n return 0;\n\n case WM_LBUTTONDOWN:\n windowMap[windowHandle]->LeftMouseButtonDown(wparam, lparam);\n return 0;\n\n case WM_LBUTTONUP:\n windowMap[windowHandle]->LeftMouseButtonUp(wparam, lparam);\n return 0;\n\n case WM_RBUTTONDOWN:\n windowMap[windowHandle]->RightMouseButtonDown(wparam, lparam);\n return 0;\n\n case WM_RBUTTONUP:\n windowMap[windowHandle]->RightMouseButtonUp(wparam, lparam);\n return 0;\n\n case WM_MOUSEWHEEL:\n windowMap[windowHandle]->MouseScrollWheel(wparam, lparam);\n return 0;\n\n case WM_SIZE:\n windowMap[windowHandle]->WindowResize(wparam, lparam);\n return 0;\n\n case WM_CLOSE:\n windowMap[windowHandle]->onClose();\n return 0;\n\n case WM_DESTROY:\n PostQuitMessage(0);\n windowMap[windowHandle] = NULL;\n return 0;\n\n default:\n return DefWindowProc(windowHandle, message, wparam, lparam);\n }\n}\n<commit_msg>Take advantage of some STL exception throwing<commit_after>#include <stdexcept>\n#include <unordered_map>\n\n#include \"windowsx.h\"\n\n#include \"windowswindow.hh\"\n#include \"windowsopenglcontext.hh\"\n#include \"system\/mousebutton.hh\"\n#include \"system\/keycode.hh\"\n\nstatic char appName[] = \"Test Application\";\n\nusing System::KeyCode;\n\nclass KeyMap : public std::unordered_map<WPARAM, System::KeyCode>\n{\npublic:\n KeyMap() : std::unordered_map<WPARAM, System::KeyCode>() {\n (*this)[VK_PRIOR] = KeyCode::KeyPageUp;\n (*this)[VK_NEXT] = KeyCode::KeyPageDown;\n (*this)[VK_END] = KeyCode::KeyEnd;\n (*this)[VK_HOME] = KeyCode::KeyHome;\n (*this)[VK_INSERT] = KeyCode::KeyInsert;\n (*this)[VK_DELETE] = KeyCode::KeyDelete;\n\n (*this)[VK_RIGHT] = KeyCode::KeyRightArrow;\n (*this)[VK_DOWN] = KeyCode::KeyDownArrow;\n (*this)[VK_LEFT] = KeyCode::KeyLeftArrow;\n (*this)[VK_UP] = KeyCode::KeyUpArrow;\n\n (*this)[VK_ESCAPE] = KeyCode::KeyEscape;\n (*this)[VK_TAB] = KeyCode::KeyTab;\n (*this)[VK_SHIFT] = KeyCode::KeyShift;\n (*this)[VK_MENU] = KeyCode::KeyAlt;\n (*this)[VK_CONTROL] = KeyCode::KeyControl;\n (*this)[VK_CAPITAL] = KeyCode::KeyCapsLock;\n\n (*this)[VK_RCONTROL] = KeyCode::KeyRightControl;\n (*this)[VK_LCONTROL] = KeyCode::KeyLeftControl;\n (*this)[VK_RSHIFT] = KeyCode::KeyRightShift;\n (*this)[VK_LSHIFT] = KeyCode::KeyLeftShift;\n\n (*this)[VK_BACK] = KeyCode::KeyBackspace;\n (*this)[VK_RETURN] = KeyCode::KeyEnter;\n (*this)[VK_SPACE] = KeyCode::KeySpace;\n\n (*this)[0x30] = KeyCode::Key0;\n (*this)[0x31] = KeyCode::Key1;\n (*this)[0x32] = KeyCode::Key2;\n (*this)[0x33] = KeyCode::Key3;\n (*this)[0x34] = KeyCode::Key4;\n (*this)[0x35] = KeyCode::Key5;\n (*this)[0x36] = KeyCode::Key6;\n (*this)[0x37] = KeyCode::Key7;\n (*this)[0x38] = KeyCode::Key8;\n (*this)[0x39] = KeyCode::Key9;\n\n (*this)[VK_NUMPAD0] = KeyCode::KeyNumpad0;\n (*this)[VK_NUMPAD1] = KeyCode::KeyNumpad1;\n (*this)[VK_NUMPAD2] = KeyCode::KeyNumpad2;\n (*this)[VK_NUMPAD3] = KeyCode::KeyNumpad3;\n (*this)[VK_NUMPAD4] = KeyCode::KeyNumpad4;\n (*this)[VK_NUMPAD5] = KeyCode::KeyNumpad5;\n (*this)[VK_NUMPAD6] = KeyCode::KeyNumpad6;\n (*this)[VK_NUMPAD7] = KeyCode::KeyNumpad7;\n (*this)[VK_NUMPAD8] = KeyCode::KeyNumpad8;\n (*this)[VK_NUMPAD9] = KeyCode::KeyNumpad9;\n\n (*this)[VK_MULTIPLY] = KeyCode::KeyMultiply;\n (*this)[VK_ADD] = KeyCode::KeyPlus;\n (*this)[VK_SUBTRACT] = KeyCode::KeyMinus;\n (*this)[VK_DIVIDE] = KeyCode::KeyDivide;\n (*this)[VK_DECIMAL] = KeyCode::KeyDecimal;\n\n (*this)[0x41] = KeyCode::KeyA;\n (*this)[0x42] = KeyCode::KeyB;\n (*this)[0x43] = KeyCode::KeyC;\n (*this)[0x44] = KeyCode::KeyD;\n (*this)[0x45] = KeyCode::KeyE;\n (*this)[0x46] = KeyCode::KeyF;\n (*this)[0x47] = KeyCode::KeyG;\n (*this)[0x48] = KeyCode::KeyH;\n (*this)[0x49] = KeyCode::KeyI;\n (*this)[0x4A] = KeyCode::KeyJ;\n (*this)[0x4B] = KeyCode::KeyK;\n (*this)[0x4C] = KeyCode::KeyL;\n (*this)[0x4D] = KeyCode::KeyM;\n (*this)[0x4E] = KeyCode::KeyN;\n (*this)[0x4F] = KeyCode::KeyO;\n (*this)[0x50] = KeyCode::KeyP;\n (*this)[0x51] = KeyCode::KeyQ;\n (*this)[0x52] = KeyCode::KeyR;\n (*this)[0x53] = KeyCode::KeyS;\n (*this)[0x54] = KeyCode::KeyT;\n (*this)[0x55] = KeyCode::KeyU;\n (*this)[0x56] = KeyCode::KeyV;\n (*this)[0x57] = KeyCode::KeyW;\n (*this)[0x59] = KeyCode::KeyY;\n (*this)[0x5A] = KeyCode::KeyZ;\n }\n};\n\nstatic KeyMap keyMap;\nstatic std::unordered_map<HWND, WindowsWindow*> windowMap;\n\nWindowsWindow::WindowsWindow(const char *windowName, Framework::ISystemWindowController *controller, HINSTANCE processInstance, int commandShow)\n : m_controller(controller), m_openGLContext(NULL)\n{\n m_windowHandle = WindowsWindow::makeWindow(windowName, processInstance, commandShow);\n windowMap[m_windowHandle] = this;\n\n ShowWindow(m_windowHandle, commandShow);\n UpdateWindow(m_windowHandle);\n\n unsigned int windowWidth, windowHeight;\n GetWindowSize(&windowWidth, &windowHeight);\n m_controller->OnWindowResize(windowWidth, windowHeight);\n}\n\nHWND WindowsWindow::makeWindow(const char *windowName, HINSTANCE processInstance, int commandShow)\n{\n WNDCLASSEX windowClass;\n\n windowClass.cbSize = sizeof(WNDCLASSEX);\n windowClass.style = CS_VREDRAW | CS_HREDRAW;\n windowClass.lpfnWndProc = WndProc;\n windowClass.cbClsExtra = 0;\n windowClass.cbWndExtra = 0;\n windowClass.hInstance = processInstance;\n windowClass.hIcon = LoadIcon(NULL, IDI_APPLICATION);\n windowClass.hIconSm = LoadIcon(NULL, IDI_APPLICATION);\n windowClass.hCursor = LoadCursor(NULL, IDC_ARROW);\n windowClass.hbrBackground = (HBRUSH) GetStockObject(BLACK_BRUSH);\n windowClass.lpszClassName = appName;\n windowClass.lpszMenuName = NULL;\n\n RegisterClassEx(&windowClass);\n\n return CreateWindow(appName, windowName, WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, NULL, NULL, processInstance, NULL);\n}\n\nWindowsWindow::~WindowsWindow()\n{\n if (m_openGLContext != NULL)\n delete m_openGLContext;\n\n windowMap[m_windowHandle] = NULL;\n}\n\nint WindowsWindow::DoMessageLoop()\n{\n MSG message;\n\n Ready();\n\n while (GetMessage(&message, NULL, 0, 0))\n {\n TranslateMessage(&message);\n DispatchMessage(&message);\n }\n\n return message.wParam;\n}\n\nSystem::OpenGLContext *WindowsWindow::getOrCreateOpenGLContext()\n{\n if (m_openGLContext == NULL)\n m_openGLContext = new WindowsOpenGLContext(m_windowHandle);\n\n return m_openGLContext;\n}\n\nvoid WindowsWindow::GetWindowSize(unsigned int *width, unsigned int *height)\n{\n RECT rect;\n\n GetClientRect(m_windowHandle, &rect);\n\n *width = rect.right - rect.left;\n *height = rect.bottom - rect.top;\n}\n\nbool WindowsWindow::SetMousePosition(unsigned int posX, unsigned int posY)\n{\n POINT point;\n\n point.x = posX;\n point.y = posY;\n\n bool success = ClientToScreen(m_windowHandle, &point) ? SetCursorPos(point.x, point.y) : false;\n if (success)\n m_controller->OnMouseMove(point.x, point.y);\n\n return success;\n}\n\nvoid WindowsWindow::Destroy()\n{\n SendNotifyMessage(m_windowHandle, WM_DESTROY, 0, 0);\n}\n\nvoid WindowsWindow::Close()\n{\n SendNotifyMessage(m_windowHandle, WM_CLOSE, 0, 0);\n}\n\nvoid WindowsWindow::Ready()\n{\n m_controller->OnWindowReady();\n}\n\nvoid WindowsWindow::onClose()\n{\n m_controller->OnWindowClose();\n}\n\nvoid WindowsWindow::KeyDown(WPARAM key)\n{\n m_controller->OnKeyDown(keyMap[key]);\n}\n\nvoid WindowsWindow::WindowResize(WPARAM wParam, LPARAM lParam)\n{\n m_controller->OnWindowResize(LOWORD(lParam), HIWORD(lParam));\n}\n\nvoid WindowsWindow::KeyUp(WPARAM key)\n{\n m_controller->OnKeyUp(keyMap[key]);\n}\n\nvoid WindowsWindow::MouseMove(WPARAM wParam, LPARAM lParam)\n{\n m_controller->OnMouseMove(GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam));\n}\n\nvoid WindowsWindow::LeftMouseButtonDown(WPARAM wParam, LPARAM lParam)\n{\n m_controller->OnMouseButtonDown(System::MouseButton::ButtonOne);\n}\n\nvoid WindowsWindow::RightMouseButtonDown(WPARAM wParam, LPARAM lParam)\n{\n m_controller->OnMouseButtonDown(System::MouseButton::ButtonTwo);\n}\n\nvoid WindowsWindow::LeftMouseButtonUp(WPARAM wParam, LPARAM lParam)\n{\n m_controller->OnMouseButtonUp(System::MouseButton::ButtonOne);\n}\n\nvoid WindowsWindow::RightMouseButtonUp(WPARAM wParam, LPARAM lParam)\n{\n m_controller->OnMouseButtonUp(System::MouseButton::ButtonTwo);\n}\n\nvoid WindowsWindow::MouseScrollWheel(WPARAM wParam, LPARAM lParam)\n{\n m_controller->OnMouseScroll(GET_WHEEL_DELTA_WPARAM(wParam) \/ WHEEL_DELTA);\n}\n\nLRESULT CALLBACK WindowsWindow::WndProc(HWND windowHandle, UINT message, WPARAM wparam, LPARAM lparam)\n{\n switch(message)\n {\n case WM_KEYDOWN:\n windowMap.at(windowHandle)->KeyDown(wparam);\n return 0;\n\n case WM_KEYUP:\n windowMap.at(windowHandle)->KeyUp(wparam);\n return 0;\n\n case WM_MOUSEMOVE:\n windowMap.at(windowHandle)->MouseMove(wparam, lparam);\n return 0;\n\n case WM_LBUTTONDOWN:\n windowMap.at(windowHandle)->LeftMouseButtonDown(wparam, lparam);\n return 0;\n\n case WM_LBUTTONUP:\n windowMap.at(windowHandle)->LeftMouseButtonUp(wparam, lparam);\n return 0;\n\n case WM_RBUTTONDOWN:\n windowMap.at(windowHandle)->RightMouseButtonDown(wparam, lparam);\n return 0;\n\n case WM_RBUTTONUP:\n windowMap.at(windowHandle)->RightMouseButtonUp(wparam, lparam);\n return 0;\n\n case WM_MOUSEWHEEL:\n windowMap.at(windowHandle)->MouseScrollWheel(wparam, lparam);\n return 0;\n\n case WM_SIZE:\n windowMap.at(windowHandle)->WindowResize(wparam, lparam);\n return 0;\n\n case WM_CLOSE:\n windowMap.at(windowHandle)->onClose();\n return 0;\n\n case WM_DESTROY:\n PostQuitMessage(0);\n windowMap.at(windowHandle) = NULL;\n return 0;\n\n default:\n return DefWindowProc(windowHandle, message, wparam, lparam);\n }\n}\n<|endoftext|>"} {"text":"<commit_before>#include <stdexcept>\n#include <unordered_map>\n\n#include \"windowsx.h\"\n\n#include \"windowswindow.hh\"\n#include \"windowsopenglcontext.hh\"\n#include \"system\/mousebutton.hh\"\n#include \"system\/keycode.hh\"\n\nstatic char appName[] = \"Test Application\";\n\nusing System::KeyCode;\n\nclass KeyMap : public std::unordered_map<WPARAM, System::KeyCode>\n{\npublic:\n KeyMap() : std::unordered_map<WPARAM, System::KeyCode>() {\n (*this)[VK_PRIOR] = KeyCode::KeyPageUp;\n (*this)[VK_NEXT] = KeyCode::KeyPageDown;\n (*this)[VK_END] = KeyCode::KeyEnd;\n (*this)[VK_HOME] = KeyCode::KeyHome;\n (*this)[VK_INSERT] = KeyCode::KeyInsert;\n (*this)[VK_DELETE] = KeyCode::KeyDelete;\n\n (*this)[VK_RIGHT] = KeyCode::KeyRightArrow;\n (*this)[VK_DOWN] = KeyCode::KeyDownArrow;\n (*this)[VK_LEFT] = KeyCode::KeyLeftArrow;\n (*this)[VK_UP] = KeyCode::KeyUpArrow;\n\n (*this)[VK_ESCAPE] = KeyCode::KeyEscape;\n (*this)[VK_TAB] = KeyCode::KeyTab;\n (*this)[VK_SHIFT] = KeyCode::KeyShift;\n (*this)[VK_MENU] = KeyCode::KeyAlt;\n (*this)[VK_CONTROL] = KeyCode::KeyControl;\n (*this)[VK_CAPITAL] = KeyCode::KeyCapsLock;\n\n (*this)[VK_RCONTROL] = KeyCode::KeyRightControl;\n (*this)[VK_LCONTROL] = KeyCode::KeyLeftControl;\n (*this)[VK_RSHIFT] = KeyCode::KeyRightShift;\n (*this)[VK_LSHIFT] = KeyCode::KeyLeftShift;\n\n (*this)[VK_BACK] = KeyCode::KeyBackspace;\n (*this)[VK_RETURN] = KeyCode::KeyEnter;\n (*this)[VK_SPACE] = KeyCode::KeySpace;\n\n (*this)[0x30] = KeyCode::Key0;\n (*this)[0x31] = KeyCode::Key1;\n (*this)[0x32] = KeyCode::Key2;\n (*this)[0x33] = KeyCode::Key3;\n (*this)[0x34] = KeyCode::Key4;\n (*this)[0x35] = KeyCode::Key5;\n (*this)[0x36] = KeyCode::Key6;\n (*this)[0x37] = KeyCode::Key7;\n (*this)[0x38] = KeyCode::Key8;\n (*this)[0x39] = KeyCode::Key9;\n\n (*this)[VK_NUMPAD0] = KeyCode::KeyNumpad0;\n (*this)[VK_NUMPAD1] = KeyCode::KeyNumpad1;\n (*this)[VK_NUMPAD2] = KeyCode::KeyNumpad2;\n (*this)[VK_NUMPAD3] = KeyCode::KeyNumpad3;\n (*this)[VK_NUMPAD4] = KeyCode::KeyNumpad4;\n (*this)[VK_NUMPAD5] = KeyCode::KeyNumpad5;\n (*this)[VK_NUMPAD6] = KeyCode::KeyNumpad6;\n (*this)[VK_NUMPAD7] = KeyCode::KeyNumpad7;\n (*this)[VK_NUMPAD8] = KeyCode::KeyNumpad8;\n (*this)[VK_NUMPAD9] = KeyCode::KeyNumpad9;\n\n (*this)[VK_MULTIPLY] = KeyCode::KeyMultiply;\n (*this)[VK_ADD] = KeyCode::KeyPlus;\n (*this)[VK_SUBTRACT] = KeyCode::KeyMinus;\n (*this)[VK_DIVIDE] = KeyCode::KeyDivide;\n (*this)[VK_DECIMAL] = KeyCode::KeyDecimal;\n\n (*this)[0x41] = KeyCode::KeyA;\n (*this)[0x42] = KeyCode::KeyB;\n (*this)[0x43] = KeyCode::KeyC;\n (*this)[0x44] = KeyCode::KeyD;\n (*this)[0x45] = KeyCode::KeyE;\n (*this)[0x46] = KeyCode::KeyF;\n (*this)[0x47] = KeyCode::KeyG;\n (*this)[0x48] = KeyCode::KeyH;\n (*this)[0x49] = KeyCode::KeyI;\n (*this)[0x4A] = KeyCode::KeyJ;\n (*this)[0x4B] = KeyCode::KeyK;\n (*this)[0x4C] = KeyCode::KeyL;\n (*this)[0x4D] = KeyCode::KeyM;\n (*this)[0x4E] = KeyCode::KeyN;\n (*this)[0x4F] = KeyCode::KeyO;\n (*this)[0x50] = KeyCode::KeyP;\n (*this)[0x51] = KeyCode::KeyQ;\n (*this)[0x52] = KeyCode::KeyR;\n (*this)[0x53] = KeyCode::KeyS;\n (*this)[0x54] = KeyCode::KeyT;\n (*this)[0x55] = KeyCode::KeyU;\n (*this)[0x56] = KeyCode::KeyV;\n (*this)[0x57] = KeyCode::KeyW;\n (*this)[0x59] = KeyCode::KeyY;\n (*this)[0x5A] = KeyCode::KeyZ;\n }\n};\n\nstatic KeyMap keyMap;\nstatic std::unordered_map<HWND, WindowsWindow*> windowMap;\n\nWindowsWindow::WindowsWindow(const char *windowName, Framework::ISystemWindowController *controller, HINSTANCE processInstance, int commandShow)\n : m_controller(controller), m_openGLContext(NULL)\n{\n m_windowHandle = WindowsWindow::makeWindow(windowName, processInstance, commandShow);\n windowMap[m_windowHandle] = this;\n\n ShowWindow(m_windowHandle, commandShow);\n UpdateWindow(m_windowHandle);\n\n unsigned int windowWidth, windowHeight;\n GetWindowSize(&windowWidth, &windowHeight);\n m_controller->OnWindowResize(windowWidth, windowHeight);\n}\n\nHWND WindowsWindow::makeWindow(const char *windowName, HINSTANCE processInstance, int commandShow)\n{\n WNDCLASSEX windowClass;\n\n windowClass.cbSize = sizeof(WNDCLASSEX);\n windowClass.style = CS_VREDRAW | CS_HREDRAW;\n windowClass.lpfnWndProc = WndProc;\n windowClass.cbClsExtra = 0;\n windowClass.cbWndExtra = 0;\n windowClass.hInstance = processInstance;\n windowClass.hIcon = LoadIcon(NULL, IDI_APPLICATION);\n windowClass.hIconSm = LoadIcon(NULL, IDI_APPLICATION);\n windowClass.hCursor = LoadCursor(NULL, IDC_ARROW);\n windowClass.hbrBackground = (HBRUSH) GetStockObject(BLACK_BRUSH);\n windowClass.lpszClassName = appName;\n windowClass.lpszMenuName = NULL;\n\n RegisterClassEx(&windowClass);\n\n return CreateWindow(appName, windowName, WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, NULL, NULL, processInstance, NULL);\n}\n\nWindowsWindow::~WindowsWindow()\n{\n if (m_openGLContext != NULL)\n delete m_openGLContext;\n\n windowMap[m_windowHandle] = NULL;\n}\n\nint WindowsWindow::DoMessageLoop()\n{\n MSG message;\n\n Ready();\n\n while (GetMessage(&message, NULL, 0, 0))\n {\n TranslateMessage(&message);\n DispatchMessage(&message);\n }\n\n return message.wParam;\n}\n\nSystem::OpenGLContext *WindowsWindow::getOrCreateOpenGLContext()\n{\n if (m_openGLContext == NULL)\n m_openGLContext = new WindowsOpenGLContext(m_windowHandle);\n\n return m_openGLContext;\n}\n\nvoid WindowsWindow::GetWindowSize(unsigned int *width, unsigned int *height)\n{\n RECT rect;\n\n GetClientRect(m_windowHandle, &rect);\n\n *width = rect.right - rect.left;\n *height = rect.bottom - rect.top;\n}\n\nbool WindowsWindow::SetMousePosition(unsigned int posX, unsigned int posY)\n{\n POINT point;\n\n point.x = posX;\n point.y = posY;\n\n bool success = ClientToScreen(m_windowHandle, &point) ? SetCursorPos(point.x, point.y) : false;\n if (success)\n m_controller->OnMouseMove(point.x, point.y);\n\n return success;\n}\n\nvoid WindowsWindow::Destroy()\n{\n SendNotifyMessage(m_windowHandle, WM_DESTROY, 0, 0);\n}\n\nvoid WindowsWindow::Close()\n{\n SendNotifyMessage(m_windowHandle, WM_CLOSE, 0, 0);\n}\n\nvoid WindowsWindow::Ready()\n{\n m_controller->OnWindowReady();\n}\n\nvoid WindowsWindow::onClose()\n{\n m_controller->OnWindowClose();\n}\n\nvoid WindowsWindow::KeyDown(WPARAM key)\n{\n m_controller->OnKeyDown(keyMap[key]);\n}\n\nvoid WindowsWindow::WindowResize(WPARAM wParam, LPARAM lParam)\n{\n m_controller->OnWindowResize(LOWORD(lParam), HIWORD(lParam));\n}\n\nvoid WindowsWindow::KeyUp(WPARAM key)\n{\n m_controller->OnKeyUp(keyMap[key]);\n}\n\nvoid WindowsWindow::MouseMove(WPARAM wParam, LPARAM lParam)\n{\n m_controller->OnMouseMove(GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam));\n}\n\nvoid WindowsWindow::LeftMouseButtonDown(WPARAM wParam, LPARAM lParam)\n{\n m_controller->OnMouseButtonDown(System::MouseButton::ButtonOne);\n}\n\nvoid WindowsWindow::RightMouseButtonDown(WPARAM wParam, LPARAM lParam)\n{\n m_controller->OnMouseButtonDown(System::MouseButton::ButtonTwo);\n}\n\nvoid WindowsWindow::LeftMouseButtonUp(WPARAM wParam, LPARAM lParam)\n{\n m_controller->OnMouseButtonUp(System::MouseButton::ButtonOne);\n}\n\nvoid WindowsWindow::RightMouseButtonUp(WPARAM wParam, LPARAM lParam)\n{\n m_controller->OnMouseButtonUp(System::MouseButton::ButtonTwo);\n}\n\nvoid WindowsWindow::MouseScrollWheel(WPARAM wParam, LPARAM lParam)\n{\n m_controller->OnMouseScroll(GET_WHEEL_DELTA_WPARAM(wParam) \/ WHEEL_DELTA);\n}\n\nLRESULT CALLBACK WindowsWindow::WndProc(HWND windowHandle, UINT message, WPARAM wparam, LPARAM lparam)\n{\n WindowsWindow *window;\n\n try\n {\n window = windowMap.at(windowHandle);\n }\n catch (std::out_of_range e)\n {\n return DefWindowProc(windowHandle, message, wparam, lparam);\n }\n\n switch(message)\n {\n case WM_KEYDOWN:\n window->KeyDown(wparam);\n return 0;\n\n case WM_KEYUP:\n window->KeyUp(wparam);\n return 0;\n\n case WM_MOUSEMOVE:\n window->MouseMove(wparam, lparam);\n return 0;\n\n case WM_LBUTTONDOWN:\n window->LeftMouseButtonDown(wparam, lparam);\n return 0;\n\n case WM_LBUTTONUP:\n window->LeftMouseButtonUp(wparam, lparam);\n return 0;\n\n case WM_RBUTTONDOWN:\n window->RightMouseButtonDown(wparam, lparam);\n return 0;\n\n case WM_RBUTTONUP:\n window->RightMouseButtonUp(wparam, lparam);\n return 0;\n\n case WM_MOUSEWHEEL:\n window->MouseScrollWheel(wparam, lparam);\n return 0;\n\n case WM_SIZE:\n window->WindowResize(wparam, lparam);\n return 0;\n\n case WM_CLOSE:\n window->onClose();\n return 0;\n\n case WM_DESTROY:\n PostQuitMessage(0);\n windowMap[windowHandle] = NULL;\n return 0;\n }\n\n return DefWindowProc(windowHandle, message, wparam, lparam);\n}\n<commit_msg>Add some beginnings for borderless fullscreen<commit_after>#include <stdexcept>\n#include <unordered_map>\n\n#include \"windowsx.h\"\n\n#include \"windowswindow.hh\"\n#include \"windowsopenglcontext.hh\"\n#include \"system\/mousebutton.hh\"\n#include \"system\/keycode.hh\"\n\nstatic char appName[] = \"Test Application\";\n\nusing System::KeyCode;\n\nclass KeyMap : public std::unordered_map<WPARAM, System::KeyCode>\n{\npublic:\n KeyMap() : std::unordered_map<WPARAM, System::KeyCode>() {\n (*this)[VK_PRIOR] = KeyCode::KeyPageUp;\n (*this)[VK_NEXT] = KeyCode::KeyPageDown;\n (*this)[VK_END] = KeyCode::KeyEnd;\n (*this)[VK_HOME] = KeyCode::KeyHome;\n (*this)[VK_INSERT] = KeyCode::KeyInsert;\n (*this)[VK_DELETE] = KeyCode::KeyDelete;\n\n (*this)[VK_RIGHT] = KeyCode::KeyRightArrow;\n (*this)[VK_DOWN] = KeyCode::KeyDownArrow;\n (*this)[VK_LEFT] = KeyCode::KeyLeftArrow;\n (*this)[VK_UP] = KeyCode::KeyUpArrow;\n\n (*this)[VK_ESCAPE] = KeyCode::KeyEscape;\n (*this)[VK_TAB] = KeyCode::KeyTab;\n (*this)[VK_SHIFT] = KeyCode::KeyShift;\n (*this)[VK_MENU] = KeyCode::KeyAlt;\n (*this)[VK_CONTROL] = KeyCode::KeyControl;\n (*this)[VK_CAPITAL] = KeyCode::KeyCapsLock;\n\n (*this)[VK_RCONTROL] = KeyCode::KeyRightControl;\n (*this)[VK_LCONTROL] = KeyCode::KeyLeftControl;\n (*this)[VK_RSHIFT] = KeyCode::KeyRightShift;\n (*this)[VK_LSHIFT] = KeyCode::KeyLeftShift;\n\n (*this)[VK_BACK] = KeyCode::KeyBackspace;\n (*this)[VK_RETURN] = KeyCode::KeyEnter;\n (*this)[VK_SPACE] = KeyCode::KeySpace;\n\n (*this)[0x30] = KeyCode::Key0;\n (*this)[0x31] = KeyCode::Key1;\n (*this)[0x32] = KeyCode::Key2;\n (*this)[0x33] = KeyCode::Key3;\n (*this)[0x34] = KeyCode::Key4;\n (*this)[0x35] = KeyCode::Key5;\n (*this)[0x36] = KeyCode::Key6;\n (*this)[0x37] = KeyCode::Key7;\n (*this)[0x38] = KeyCode::Key8;\n (*this)[0x39] = KeyCode::Key9;\n\n (*this)[VK_NUMPAD0] = KeyCode::KeyNumpad0;\n (*this)[VK_NUMPAD1] = KeyCode::KeyNumpad1;\n (*this)[VK_NUMPAD2] = KeyCode::KeyNumpad2;\n (*this)[VK_NUMPAD3] = KeyCode::KeyNumpad3;\n (*this)[VK_NUMPAD4] = KeyCode::KeyNumpad4;\n (*this)[VK_NUMPAD5] = KeyCode::KeyNumpad5;\n (*this)[VK_NUMPAD6] = KeyCode::KeyNumpad6;\n (*this)[VK_NUMPAD7] = KeyCode::KeyNumpad7;\n (*this)[VK_NUMPAD8] = KeyCode::KeyNumpad8;\n (*this)[VK_NUMPAD9] = KeyCode::KeyNumpad9;\n\n (*this)[VK_MULTIPLY] = KeyCode::KeyMultiply;\n (*this)[VK_ADD] = KeyCode::KeyPlus;\n (*this)[VK_SUBTRACT] = KeyCode::KeyMinus;\n (*this)[VK_DIVIDE] = KeyCode::KeyDivide;\n (*this)[VK_DECIMAL] = KeyCode::KeyDecimal;\n\n (*this)[0x41] = KeyCode::KeyA;\n (*this)[0x42] = KeyCode::KeyB;\n (*this)[0x43] = KeyCode::KeyC;\n (*this)[0x44] = KeyCode::KeyD;\n (*this)[0x45] = KeyCode::KeyE;\n (*this)[0x46] = KeyCode::KeyF;\n (*this)[0x47] = KeyCode::KeyG;\n (*this)[0x48] = KeyCode::KeyH;\n (*this)[0x49] = KeyCode::KeyI;\n (*this)[0x4A] = KeyCode::KeyJ;\n (*this)[0x4B] = KeyCode::KeyK;\n (*this)[0x4C] = KeyCode::KeyL;\n (*this)[0x4D] = KeyCode::KeyM;\n (*this)[0x4E] = KeyCode::KeyN;\n (*this)[0x4F] = KeyCode::KeyO;\n (*this)[0x50] = KeyCode::KeyP;\n (*this)[0x51] = KeyCode::KeyQ;\n (*this)[0x52] = KeyCode::KeyR;\n (*this)[0x53] = KeyCode::KeyS;\n (*this)[0x54] = KeyCode::KeyT;\n (*this)[0x55] = KeyCode::KeyU;\n (*this)[0x56] = KeyCode::KeyV;\n (*this)[0x57] = KeyCode::KeyW;\n (*this)[0x59] = KeyCode::KeyY;\n (*this)[0x5A] = KeyCode::KeyZ;\n }\n};\n\nstatic KeyMap keyMap;\nstatic std::unordered_map<HWND, WindowsWindow*> windowMap;\n\nWindowsWindow::WindowsWindow(const char *windowName, Framework::ISystemWindowController *controller, HINSTANCE processInstance, int commandShow)\n : m_controller(controller), m_openGLContext(NULL)\n{\n m_windowHandle = WindowsWindow::makeWindow(windowName, processInstance, commandShow);\n windowMap[m_windowHandle] = this;\n\n ShowWindow(m_windowHandle, commandShow);\n UpdateWindow(m_windowHandle);\n\n unsigned int windowWidth, windowHeight;\n GetWindowSize(&windowWidth, &windowHeight);\n m_controller->OnWindowResize(windowWidth, windowHeight);\n}\n\nHWND WindowsWindow::makeWindow(const char *windowName, HINSTANCE processInstance, int commandShow)\n{\n WNDCLASSEX windowClass;\n\n windowClass.cbSize = sizeof(WNDCLASSEX);\n windowClass.style = CS_VREDRAW | CS_HREDRAW;\n windowClass.lpfnWndProc = WndProc;\n windowClass.cbClsExtra = 0;\n windowClass.cbWndExtra = 0;\n windowClass.hInstance = processInstance;\n windowClass.hIcon = LoadIcon(NULL, IDI_APPLICATION);\n windowClass.hIconSm = LoadIcon(NULL, IDI_APPLICATION);\n windowClass.hCursor = LoadCursor(NULL, IDC_ARROW);\n windowClass.hbrBackground = (HBRUSH) GetStockObject(BLACK_BRUSH);\n windowClass.lpszClassName = appName;\n windowClass.lpszMenuName = NULL;\n\n RegisterClassEx(&windowClass);\n\n POINT point = {0, 0};\n HMONITOR hmon = MonitorFromPoint(point, MONITOR_DEFAULTTONEAREST);\n MONITORINFO mi = { sizeof(mi) };\n if (!GetMonitorInfo(hmon, &mi))\n return NULL;\n\n \/\/return CreateWindow(appName, windowName, WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, NULL, NULL, processInstance, NULL);\n return CreateWindow(appName, windowName, WS_POPUP,\n mi.rcMonitor.left, mi.rcMonitor.top,\n mi.rcMonitor.right - mi.rcMonitor.left, mi.rcMonitor.bottom - mi.rcMonitor.top,\n NULL, NULL, processInstance, NULL);\n}\n\nWindowsWindow::~WindowsWindow()\n{\n if (m_openGLContext != NULL)\n delete m_openGLContext;\n\n windowMap[m_windowHandle] = NULL;\n}\n\nint WindowsWindow::DoMessageLoop()\n{\n MSG message;\n\n Ready();\n\n while (GetMessage(&message, NULL, 0, 0))\n {\n TranslateMessage(&message);\n DispatchMessage(&message);\n }\n\n return message.wParam;\n}\n\nSystem::OpenGLContext *WindowsWindow::getOrCreateOpenGLContext()\n{\n if (m_openGLContext == NULL)\n m_openGLContext = new WindowsOpenGLContext(m_windowHandle);\n\n return m_openGLContext;\n}\n\nvoid WindowsWindow::GetWindowSize(unsigned int *width, unsigned int *height)\n{\n RECT rect;\n\n GetClientRect(m_windowHandle, &rect);\n\n *width = rect.right - rect.left;\n *height = rect.bottom - rect.top;\n}\n\nbool WindowsWindow::SetMousePosition(unsigned int posX, unsigned int posY)\n{\n POINT point;\n\n point.x = posX;\n point.y = posY;\n\n bool success = ClientToScreen(m_windowHandle, &point) ? SetCursorPos(point.x, point.y) : false;\n if (success)\n m_controller->OnMouseMove(point.x, point.y);\n\n return success;\n}\n\nvoid WindowsWindow::Destroy()\n{\n SendNotifyMessage(m_windowHandle, WM_DESTROY, 0, 0);\n}\n\nvoid WindowsWindow::Close()\n{\n SendNotifyMessage(m_windowHandle, WM_CLOSE, 0, 0);\n}\n\nvoid WindowsWindow::Ready()\n{\n m_controller->OnWindowReady();\n}\n\nvoid WindowsWindow::onClose()\n{\n m_controller->OnWindowClose();\n}\n\nvoid WindowsWindow::KeyDown(WPARAM key)\n{\n m_controller->OnKeyDown(keyMap[key]);\n}\n\nvoid WindowsWindow::WindowResize(WPARAM wParam, LPARAM lParam)\n{\n m_controller->OnWindowResize(LOWORD(lParam), HIWORD(lParam));\n}\n\nvoid WindowsWindow::KeyUp(WPARAM key)\n{\n m_controller->OnKeyUp(keyMap[key]);\n}\n\nvoid WindowsWindow::MouseMove(WPARAM wParam, LPARAM lParam)\n{\n m_controller->OnMouseMove(GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam));\n}\n\nvoid WindowsWindow::LeftMouseButtonDown(WPARAM wParam, LPARAM lParam)\n{\n m_controller->OnMouseButtonDown(System::MouseButton::ButtonOne);\n}\n\nvoid WindowsWindow::RightMouseButtonDown(WPARAM wParam, LPARAM lParam)\n{\n m_controller->OnMouseButtonDown(System::MouseButton::ButtonTwo);\n}\n\nvoid WindowsWindow::LeftMouseButtonUp(WPARAM wParam, LPARAM lParam)\n{\n m_controller->OnMouseButtonUp(System::MouseButton::ButtonOne);\n}\n\nvoid WindowsWindow::RightMouseButtonUp(WPARAM wParam, LPARAM lParam)\n{\n m_controller->OnMouseButtonUp(System::MouseButton::ButtonTwo);\n}\n\nvoid WindowsWindow::MouseScrollWheel(WPARAM wParam, LPARAM lParam)\n{\n m_controller->OnMouseScroll(GET_WHEEL_DELTA_WPARAM(wParam) \/ WHEEL_DELTA);\n}\n\nLRESULT CALLBACK WindowsWindow::WndProc(HWND windowHandle, UINT message, WPARAM wparam, LPARAM lparam)\n{\n WindowsWindow *window;\n\n try\n {\n window = windowMap.at(windowHandle);\n }\n catch (std::out_of_range e)\n {\n return DefWindowProc(windowHandle, message, wparam, lparam);\n }\n\n switch(message)\n {\n case WM_KEYDOWN:\n window->KeyDown(wparam);\n return 0;\n\n case WM_KEYUP:\n window->KeyUp(wparam);\n return 0;\n\n case WM_MOUSEMOVE:\n window->MouseMove(wparam, lparam);\n return 0;\n\n case WM_LBUTTONDOWN:\n window->LeftMouseButtonDown(wparam, lparam);\n return 0;\n\n case WM_LBUTTONUP:\n window->LeftMouseButtonUp(wparam, lparam);\n return 0;\n\n case WM_RBUTTONDOWN:\n window->RightMouseButtonDown(wparam, lparam);\n return 0;\n\n case WM_RBUTTONUP:\n window->RightMouseButtonUp(wparam, lparam);\n return 0;\n\n case WM_MOUSEWHEEL:\n window->MouseScrollWheel(wparam, lparam);\n return 0;\n\n case WM_SIZE:\n window->WindowResize(wparam, lparam);\n return 0;\n\n case WM_CLOSE:\n window->onClose();\n return 0;\n\n case WM_DESTROY:\n PostQuitMessage(0);\n windowMap[windowHandle] = NULL;\n return 0;\n }\n\n return DefWindowProc(windowHandle, message, wparam, lparam);\n}\n<|endoftext|>"} {"text":"<commit_before>#if !defined(h_3e645482_ae6a_43e5_8f81_abbc4200212d)\n#define h_3e645482_ae6a_43e5_8f81_abbc4200212d\n\n#include <map>\n#include <string>\n#include <sstream>\n#include <stdexcept>\n#include \"Portability.hh\"\n\nnamespace log4cpp\n{\n class FactoryParams;\n namespace details\n {\n class base_validator_data\n {\n public:\n base_validator_data(const char* tag, const FactoryParams* params) : tag_(tag), params_(params){}\n\n protected:\n const char* tag_;\n const FactoryParams* params_;\n\n template<typename T>\n void assign(const std::string& param_value, T& value) const\n {\n assign_impl(param_value, value);\n }\n\n template<typename T>\n void assign_impl(const std::string& param_value, T& value) const\n {\n std::stringstream s;\n s << param_value;\n s >> value;\n }\n\n void assign_impl(const std::string& param_value, std::string& value) const\n {\n value = param_value;\n }\n\n void throw_error(const char* param_name) const\n {\n std::stringstream s;\n s << \"Property '\" << param_name << \"' required to configure \" << tag_;\n throw std::runtime_error(s.str());\n }\n };\n\n class optional_params_validator;\n class required_params_validator : public base_validator_data\n {\n public:\n required_params_validator(const char* tag, const FactoryParams* params) : base_validator_data(tag, params) {}\n\n template<typename T>\n optional_params_validator optional(const char* param, T& value) const;\n \n template<typename T>\n const required_params_validator& operator()(const char* param, T& value) const;\n };\n \n class optional_params_validator : public base_validator_data\n {\n public:\n optional_params_validator(const char* tag, const FactoryParams* params) : base_validator_data(tag, params) {}\n\n template<typename T>\n required_params_validator required(const char* param, T& value) const { required_params_validator v(tag_, params_); v(param, value); return v; }\n\n template<typename T>\n const optional_params_validator& operator()(const char* param, T& value) const;\n };\n\n template<typename T>\n optional_params_validator required_params_validator::optional(const char* param, T& value) const { optional_params_validator v(tag_, params_); v(param, value); return v; }\n\n class parameter_validator : public base_validator_data\n {\n public:\n parameter_validator(const char* tag, const FactoryParams* params) : base_validator_data(tag, params) {}\n\n template<typename T>\n required_params_validator required(const char* param, T& value) const { required_params_validator v(tag_, params_); v(param, value); return v; }\n\n template<typename T>\n optional_params_validator optional(const char* param, T& value) const { optional_params_validator v(tag_, params_); v(param, value); return v; }\n };\n }\n\n class LOG4CPP_EXPORT FactoryParams\n {\n typedef std::map<std::string, std::string> storage_t;\n \n public:\n typedef storage_t::const_iterator const_iterator;\n\n const std::string& operator[](const std::string& v) const;\n std::string& operator[](const std::string& v) { return storage_[v]; }\n details::parameter_validator get_for(const char* tag) const { return details::parameter_validator(tag, this); }\n const_iterator find(const std::string& t) const;\n const_iterator begin() const { return storage_.begin(); }\n const_iterator end() const { return storage_.end(); }\n\n private:\n typedef std::map<std::string, std::string> storage_t;\n\n storage_t storage_;\n };\n\n namespace details\n {\n template<typename T>\n const required_params_validator& required_params_validator::operator()(const char* param, T& value) const\n {\n FactoryParams::const_iterator i = params_->find(param);\n if (i != params_->end())\n assign(i->second, value);\n else\n throw_error(param);\n\n return *this;\n }\n \n template<typename T>\n const optional_params_validator& optional_params_validator::operator()(const char* param, T& value) const\n {\n FactoryParams::const_iterator i = params_->find(param);\n if (i != params_->end())\n assign(i->second, value);\n\n return *this;\n }\n }\n}\n\n#endif \/\/ h_3e645482_ae6a_43e5_8f81_abbc4200212d\n<commit_msg>[bug] fixed build problem under linux<commit_after>#if !defined(h_3e645482_ae6a_43e5_8f81_abbc4200212d)\n#define h_3e645482_ae6a_43e5_8f81_abbc4200212d\n\n#include <map>\n#include <string>\n#include <sstream>\n#include <stdexcept>\n#include \"Portability.hh\"\n\nnamespace log4cpp\n{\n class FactoryParams;\n namespace details\n {\n class base_validator_data\n {\n public:\n base_validator_data(const char* tag, const FactoryParams* params) : tag_(tag), params_(params){}\n\n protected:\n const char* tag_;\n const FactoryParams* params_;\n\n template<typename T>\n void assign(const std::string& param_value, T& value) const\n {\n assign_impl(param_value, value);\n }\n\n template<typename T>\n void assign_impl(const std::string& param_value, T& value) const\n {\n std::stringstream s;\n s << param_value;\n s >> value;\n }\n\n void assign_impl(const std::string& param_value, std::string& value) const\n {\n value = param_value;\n }\n\n void throw_error(const char* param_name) const\n {\n std::stringstream s;\n s << \"Property '\" << param_name << \"' required to configure \" << tag_;\n throw std::runtime_error(s.str());\n }\n };\n\n class optional_params_validator;\n class required_params_validator : public base_validator_data\n {\n public:\n required_params_validator(const char* tag, const FactoryParams* params) : base_validator_data(tag, params) {}\n\n template<typename T>\n optional_params_validator optional(const char* param, T& value) const;\n \n template<typename T>\n const required_params_validator& operator()(const char* param, T& value) const;\n };\n \n class optional_params_validator : public base_validator_data\n {\n public:\n optional_params_validator(const char* tag, const FactoryParams* params) : base_validator_data(tag, params) {}\n\n template<typename T>\n required_params_validator required(const char* param, T& value) const { required_params_validator v(tag_, params_); v(param, value); return v; }\n\n template<typename T>\n const optional_params_validator& operator()(const char* param, T& value) const;\n };\n\n template<typename T>\n optional_params_validator required_params_validator::optional(const char* param, T& value) const { optional_params_validator v(tag_, params_); v(param, value); return v; }\n\n class parameter_validator : public base_validator_data\n {\n public:\n parameter_validator(const char* tag, const FactoryParams* params) : base_validator_data(tag, params) {}\n\n template<typename T>\n required_params_validator required(const char* param, T& value) const { required_params_validator v(tag_, params_); v(param, value); return v; }\n\n template<typename T>\n optional_params_validator optional(const char* param, T& value) const { optional_params_validator v(tag_, params_); v(param, value); return v; }\n };\n }\n\n class LOG4CPP_EXPORT FactoryParams\n {\n typedef std::map<std::string, std::string> storage_t;\n\t\t \n\t\t \t\t storage_t storage_;\n \n public:\n typedef storage_t::const_iterator const_iterator;\n\n const std::string& operator[](const std::string& v) const;\n std::string& operator[](const std::string& v) { return storage_[v]; }\n details::parameter_validator get_for(const char* tag) const { return details::parameter_validator(tag, this); }\n const_iterator find(const std::string& t) const;\n const_iterator begin() const { return storage_.begin(); }\n const_iterator end() const { return storage_.end(); }\n\n private:\n \/*typedef std::map<std::string, std::string> storage_t;\n\n storage_t storage_; *\/\n };\n\n namespace details\n {\n template<typename T>\n const required_params_validator& required_params_validator::operator()(const char* param, T& value) const\n {\n FactoryParams::const_iterator i = params_->find(param);\n if (i != params_->end())\n assign(i->second, value);\n else\n throw_error(param);\n\n return *this;\n }\n \n template<typename T>\n const optional_params_validator& optional_params_validator::operator()(const char* param, T& value) const\n {\n FactoryParams::const_iterator i = params_->find(param);\n if (i != params_->end())\n assign(i->second, value);\n\n return *this;\n }\n }\n}\n\n#endif \/\/ h_3e645482_ae6a_43e5_8f81_abbc4200212d\n<|endoftext|>"} {"text":"<commit_before>#include <memory>\n#include <string>\n#include <uv.h>\n#include <vector>\n\n#include \"..\/log.h\"\n#include \"..\/message.h\"\n#include \"..\/queue.h\"\n#include \"..\/result.h\"\n#include \"worker_platform.h\"\n#include \"worker_thread.h\"\n\nusing std::string;\nusing std::unique_ptr;\n\nWorkerThread::WorkerThread(uv_async_t *main_callback) :\n Thread(\"worker thread\", main_callback),\n platform{WorkerPlatform::for_worker(this)}\n{\n \/\/\n}\n\n\/\/ Definition must be here to see the full definition of WorkerPlatform.\nWorkerThread::~WorkerThread() = default;\n\nResult<> WorkerThread::wake()\n{\n if (!is_healthy()) return health_err_result();\n\n return platform->wake();\n}\n\nResult<> WorkerThread::body()\n{\n return platform->listen();\n}\n\nResult<Thread::CommandOutcome> WorkerThread::handle_add_command(const CommandPayload *payload)\n{\n Result<bool> r = platform->handle_add_command(\n payload->get_id(), payload->get_channel_id(), payload->get_root(), payload->get_recursive());\n if (r.is_error()) return r.propagate<CommandOutcome>();\n\n return ok_result(r.get_value() ? ACK : NOTHING);\n}\n\nResult<Thread::CommandOutcome> WorkerThread::handle_remove_command(const CommandPayload *payload)\n{\n Result<bool> r = platform->handle_remove_command(payload->get_id(), payload->get_channel_id());\n if (r.is_error()) return r.propagate<CommandOutcome>();\n\n return ok_result(r.get_value() ? ACK : NOTHING);\n}\n\nvoid WorkerThread::collect_status(Status &status)\n{\n status.worker_thread_state = state_name();\n status.worker_thread_ok = get_error();\n status.worker_in_size = get_in_queue_size();\n status.worker_in_ok = get_in_queue_error();\n status.worker_out_size = get_out_queue_size();\n status.worker_out_ok = get_out_queue_error();\n}\n<commit_msg>Tidy up Result<> returns<commit_after>#include <memory>\n#include <string>\n#include <uv.h>\n#include <vector>\n\n#include \"..\/log.h\"\n#include \"..\/message.h\"\n#include \"..\/queue.h\"\n#include \"..\/result.h\"\n#include \"worker_platform.h\"\n#include \"worker_thread.h\"\n\nusing std::string;\nusing std::unique_ptr;\n\nWorkerThread::WorkerThread(uv_async_t *main_callback) :\n Thread(\"worker thread\", main_callback),\n platform{WorkerPlatform::for_worker(this)}\n{\n \/\/\n}\n\n\/\/ Definition must be here to see the full definition of WorkerPlatform.\nWorkerThread::~WorkerThread() = default;\n\nResult<> WorkerThread::wake()\n{\n if (!is_healthy()) return health_err_result();\n\n return platform->wake();\n}\n\nResult<> WorkerThread::body()\n{\n return platform->listen();\n}\n\nResult<Thread::CommandOutcome> WorkerThread::handle_add_command(const CommandPayload *payload)\n{\n Result<bool> r = platform->handle_add_command(\n payload->get_id(), payload->get_channel_id(), payload->get_root(), payload->get_recursive());\n return r.propagate(r.get_value() ? ACK : NOTHING);\n}\n\nResult<Thread::CommandOutcome> WorkerThread::handle_remove_command(const CommandPayload *payload)\n{\n Result<bool> r = platform->handle_remove_command(payload->get_id(), payload->get_channel_id());\n return r.propagate(r.get_value() ? ACK : NOTHING);\n}\n\nvoid WorkerThread::collect_status(Status &status)\n{\n status.worker_thread_state = state_name();\n status.worker_thread_ok = get_error();\n status.worker_in_size = get_in_queue_size();\n status.worker_in_ok = get_in_queue_error();\n status.worker_out_size = get_out_queue_size();\n status.worker_out_ok = get_out_queue_error();\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2016 Yahoo Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.\n\/**\n * @author Peter Boros\n * @date 2004\/08\/20\n * @version $Id$\n * @file segmenter.cpp\n * @brief Query segmenter based on %FSA (%Finite %State %Automaton) (implementation)\n *\n *\/\n\n#ifdef HAVE_CONFIG_H\n#include \"config.h\"\n#endif\n\n#include \"segmenter.h\"\n\n\nnamespace fsa {\n\nSegmenter::Segments::Segments()\n : _text(), _segments(), _map(),\n _segmentation(Segmenter::SEGMENTATION_METHODS,NULL)\n{}\n\nSegmenter::Segments::~Segments()\n{\n clear();\n}\n\nvoid\nSegmenter::Segments::clear()\n{\n _segments.clear();\n _map.init(_text.size());\n initSingles();\n for(unsigned int i=0;i<SEGMENTATION_METHODS;i++){\n delete _segmentation[i];\n _segmentation[i] = nullptr;\n }\n}\n\n\/\/ {{{ Segmenter::Segments::initSingles\n\nvoid Segmenter::Segments::initSingles()\n{\n for(unsigned int i=0;i<_text.size();i++){\n if(!_map.isValid(i,i+1)){\n _map.set(i,i+1,_segments.size());\n _segments.push_back(Segment(i,i+1,0));\n }\n }\n}\n\n\n\/\/ }}}\n\/\/ {{{ Segmenter::Segments::buildSegmentation\n\nvoid Segmenter::Segments::buildSegmentation(Segmenter::SegmentationMethod method)\n{\n int i,j;\n int n_txt=(int)_text.size(), n_sgm=_segments.size();\n int id,bestid;\n int pos, next=n_txt;\n unsigned int maxsc,conn;\n int bestval,temp=0,bias;\n std::vector<int> nextid(n_sgm,-1);\n std::vector<unsigned int> maxScore(n_sgm,0);\n\n if(_segmentation[method]==NULL){\n _segmentation[method] = new Segmenter::Segmentation;\n }\n else {\n _segmentation[method]->clear();\n }\n\n bias=0;\n switch(method){\n case SEGMENTATION_WEIGHTED_BIAS100:\n bias+=50;\n case SEGMENTATION_WEIGHTED_BIAS50:\n bias+=30;\n case SEGMENTATION_WEIGHTED_BIAS20:\n bias+=10;\n case SEGMENTATION_WEIGHTED_BIAS10:\n bias+=10;\n case SEGMENTATION_WEIGHTED:\n bestid=-1;\n for(i=n_txt;i>=0;i--){\n bestid=-1;maxsc=0;\n for(j=i+1;j<=n_txt;j++){\n id=_map.get(i,j);\n if(id>=0 && maxScore[id]+1>maxsc) {\n bestid=id;\n maxsc=maxScore[id]+1;\n }\n }\n if(maxsc>0) maxsc--;\n for(j=0;j<i;j++){\n id=_map.get(j,i);\n if(id>=0){\n nextid[id] = bestid;\n conn = _segments[id].conn();\n if(i-j<=1){\n maxScore[id] = maxsc;\n }\n else if(bias>0){\n maxScore[id] = maxsc + ((100+(i-j-2)*bias)*conn)\/100;\n }\n else{\n maxScore[id] = maxsc + conn;\n }\n }\n }\n }\n id = bestid;\n while(id!=-1){\n _segmentation[method]->push_back(id);\n id=nextid[id];\n }\n break;\n case SEGMENTATION_LEFTMOST_LONGEST:\n case SEGMENTATION_LEFTMOST_WEIGHTED:\n pos = 0;\n while(pos<n_txt){\n bestid = -1; bestval = -1;\n for(i=pos+1;i<=n_txt;i++){\n id = _map.get(pos,i);\n if(id>=0 &&\n (method==SEGMENTATION_LEFTMOST_LONGEST ||\n (temp=(_segments[id].len()>1)?(int)_segments[id].conn():0)>bestval) ){\n bestid = id;\n bestval = temp;\n next = i;\n }\n }\n _segmentation[method]->push_back(bestid);\n pos=next;\n }\n break;\n case SEGMENTATION_RIGHTMOST_LONGEST:\n case SEGMENTATION_RIGHTMOST_WEIGHTED:\n pos = n_txt;\n while(pos>0){\n bestid = -1; bestval = -1;\n for(i=pos-1;i>=0;i--){\n id = _map.get(i,pos);\n if(id>=0 &&\n (method==SEGMENTATION_RIGHTMOST_LONGEST ||\n (temp=(_segments[id].len()>1)?(int)_segments[id].conn():0)>bestval) ){\n bestid = id;\n bestval = temp;\n next = i;\n }\n }\n _segmentation[method]->push_front(bestid);\n pos=next;\n }\n break;\n case SEGMENTATION_LONGEST_WEIGHTED:\n case SEGMENTATION_LONGEST_LEFTMOST:\n case SEGMENTATION_LONGEST_RIGHTMOST:\n case SEGMENTATION_WEIGHTED_LONGEST:\n case SEGMENTATION_WEIGHTED_LEFTMOST:\n case SEGMENTATION_WEIGHTED_RIGHTMOST:\n buildSegmentationRecursive(method,*_segmentation[method],0,n_txt);\n break;\n default:\n break;\n }\n}\n\n\/\/ }}}\n\/\/ {{{ Segmenter::Segments::buildSegmentationRecursive\n\nvoid Segmenter::Segments::buildSegmentationRecursive(Segmenter::SegmentationMethod method,\n Segmenter::Segmentation& segmentation,\n unsigned int beg,\n unsigned int end)\n{\n int bestid, bestval1, bestval2, temp;\n int i;\n\n \/\/ locate the best segment according to method\n bestid=-1;bestval1=-1;bestval2=-1;\n for(i=0;i<(int)_segments.size();i++){\n if(beg<=_segments[i].beg() && end>=_segments[i].end()){\n switch(method){\n case SEGMENTATION_LONGEST_WEIGHTED:\n if((int)_segments[i].len()>bestval1 ||\n ((int)_segments[i].len()==bestval1 && (int)_segments[i].conn()>bestval2) ){\n bestid=i;\n bestval1=_segments[i].len();\n bestval2=_segments[i].conn();\n }\n break;\n case SEGMENTATION_LONGEST_LEFTMOST:\n if((int)_segments[i].len()>bestval1 ||\n ((int)_segments[i].len()==bestval1 && (int)_segments[i].beg()<bestval2) ){\n bestid=i;\n bestval1=_segments[i].len();\n bestval2=_segments[i].beg();\n }\n break;\n case SEGMENTATION_LONGEST_RIGHTMOST:\n if((int)_segments[i].len()>bestval1 ||\n ((int)_segments[i].len()==bestval1 && (int)_segments[i].end()>bestval2) ){\n bestid=i;\n bestval1=_segments[i].len();\n bestval2=_segments[i].end();\n }\n break;\n case SEGMENTATION_WEIGHTED_LONGEST:\n temp = (_segments[i].len()>1)?(int)_segments[i].conn():0;\n if(temp>bestval1 ||\n (temp==bestval1 &&\n (int)_segments[i].len()>bestval2) ){\n bestid=i;\n bestval1=temp;\n bestval2=_segments[i].len();\n }\n break;\n case SEGMENTATION_WEIGHTED_LEFTMOST:\n temp = (_segments[i].len()>1)?(int)_segments[i].conn():0;\n if(temp>bestval1 ||\n (temp==bestval1 &&\n (int)_segments[i].beg()<bestval2) ){\n bestid=i;\n bestval1=temp;\n bestval2=_segments[i].beg();\n }\n break;\n case SEGMENTATION_WEIGHTED_RIGHTMOST:\n temp = (int)_segments[i].len()>1?(int)_segments[i].conn():0;\n if(temp>bestval1 ||\n (temp==bestval1 &&\n (int)_segments[i].end()>bestval2) ){\n bestid=i;\n bestval1=temp;\n bestval2=_segments[i].end();\n }\n break;\n default: \/\/ dummy defult pick first possible\n if(bestid<0){\n bestid=i;\n }\n break;\n }\n }\n }\n if(bestid<0) {\n return; \/\/ this should never happen, as all one-word segments are created\n }\n\n \/\/ check left side\n if(beg<_segments[bestid].beg()){\n buildSegmentationRecursive(method,segmentation,beg,_segments[bestid].beg());\n }\n\n \/\/ add segment\n segmentation.push_back(bestid);\n\n \/\/ check right side\n if(end>_segments[bestid].end()){\n buildSegmentationRecursive(method,segmentation,_segments[bestid].end(),end);\n }\n}\n\n\/\/ }}}\n\n\/\/ {{{ Segmenter::segment\n\nvoid Segmenter::segment(Segmenter::Segments &segments) const\n{\n segments.clear();\n _detector.detect(segments.getText(),segments);\n}\n\nvoid Segmenter::segment(const NGram &text, Segmenter::Segments &segments) const\n{\n segments.setText(text);\n _detector.detect(segments.getText(),segments);\n}\n\nvoid Segmenter::segment(const std::string &text, Segmenter::Segments &segments) const\n{\n\n segments.setText(text);\n _detector.detect(segments.getText(),segments);\n}\n\nvoid Segmenter::segment(const char *text, Segmenter::Segments &segments) const\n{\n segments.setText(text);\n _detector.detect(segments.getText(),segments);\n}\n\n\/\/ }}}\n\n} \/\/ namespace fsa\n<commit_msg>Unify indentation to existing style.<commit_after>\/\/ Copyright 2016 Yahoo Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.\n\/**\n * @author Peter Boros\n * @date 2004\/08\/20\n * @version $Id$\n * @file segmenter.cpp\n * @brief Query segmenter based on %FSA (%Finite %State %Automaton) (implementation)\n *\n *\/\n\n#ifdef HAVE_CONFIG_H\n#include \"config.h\"\n#endif\n\n#include \"segmenter.h\"\n\n\nnamespace fsa {\n\nSegmenter::Segments::Segments()\n : _text(), _segments(), _map(),\n _segmentation(Segmenter::SEGMENTATION_METHODS,NULL)\n{ }\n\nSegmenter::Segments::~Segments()\n{\n clear();\n}\n\nvoid\nSegmenter::Segments::clear()\n{\n _segments.clear();\n _map.init(_text.size());\n initSingles();\n for(unsigned int i=0;i<SEGMENTATION_METHODS;i++){\n delete _segmentation[i];\n _segmentation[i] = nullptr;\n }\n}\n\n\/\/ {{{ Segmenter::Segments::initSingles\n\nvoid Segmenter::Segments::initSingles()\n{\n for(unsigned int i=0;i<_text.size();i++){\n if(!_map.isValid(i,i+1)){\n _map.set(i,i+1,_segments.size());\n _segments.push_back(Segment(i,i+1,0));\n }\n }\n}\n\n\n\/\/ }}}\n\/\/ {{{ Segmenter::Segments::buildSegmentation\n\nvoid Segmenter::Segments::buildSegmentation(Segmenter::SegmentationMethod method)\n{\n int i,j;\n int n_txt=(int)_text.size(), n_sgm=_segments.size();\n int id,bestid;\n int pos, next=n_txt;\n unsigned int maxsc,conn;\n int bestval,temp=0,bias;\n std::vector<int> nextid(n_sgm,-1);\n std::vector<unsigned int> maxScore(n_sgm,0);\n\n if(_segmentation[method]==NULL){\n _segmentation[method] = new Segmenter::Segmentation;\n }\n else {\n _segmentation[method]->clear();\n }\n\n bias=0;\n switch(method){\n case SEGMENTATION_WEIGHTED_BIAS100:\n bias+=50;\n case SEGMENTATION_WEIGHTED_BIAS50:\n bias+=30;\n case SEGMENTATION_WEIGHTED_BIAS20:\n bias+=10;\n case SEGMENTATION_WEIGHTED_BIAS10:\n bias+=10;\n case SEGMENTATION_WEIGHTED:\n bestid=-1;\n for(i=n_txt;i>=0;i--){\n bestid=-1;maxsc=0;\n for(j=i+1;j<=n_txt;j++){\n id=_map.get(i,j);\n if(id>=0 && maxScore[id]+1>maxsc) {\n bestid=id;\n maxsc=maxScore[id]+1;\n }\n }\n if(maxsc>0) maxsc--;\n for(j=0;j<i;j++){\n id=_map.get(j,i);\n if(id>=0){\n nextid[id] = bestid;\n conn = _segments[id].conn();\n if(i-j<=1){\n maxScore[id] = maxsc;\n }\n else if(bias>0){\n maxScore[id] = maxsc + ((100+(i-j-2)*bias)*conn)\/100;\n }\n else{\n maxScore[id] = maxsc + conn;\n }\n }\n }\n }\n id = bestid;\n while(id!=-1){\n _segmentation[method]->push_back(id);\n id=nextid[id];\n }\n break;\n case SEGMENTATION_LEFTMOST_LONGEST:\n case SEGMENTATION_LEFTMOST_WEIGHTED:\n pos = 0;\n while(pos<n_txt){\n bestid = -1; bestval = -1;\n for(i=pos+1;i<=n_txt;i++){\n id = _map.get(pos,i);\n if(id>=0 &&\n (method==SEGMENTATION_LEFTMOST_LONGEST ||\n (temp=(_segments[id].len()>1)?(int)_segments[id].conn():0)>bestval) ){\n bestid = id;\n bestval = temp;\n next = i;\n }\n }\n _segmentation[method]->push_back(bestid);\n pos=next;\n }\n break;\n case SEGMENTATION_RIGHTMOST_LONGEST:\n case SEGMENTATION_RIGHTMOST_WEIGHTED:\n pos = n_txt;\n while(pos>0){\n bestid = -1; bestval = -1;\n for(i=pos-1;i>=0;i--){\n id = _map.get(i,pos);\n if(id>=0 &&\n (method==SEGMENTATION_RIGHTMOST_LONGEST ||\n (temp=(_segments[id].len()>1)?(int)_segments[id].conn():0)>bestval) ){\n bestid = id;\n bestval = temp;\n next = i;\n }\n }\n _segmentation[method]->push_front(bestid);\n pos=next;\n }\n break;\n case SEGMENTATION_LONGEST_WEIGHTED:\n case SEGMENTATION_LONGEST_LEFTMOST:\n case SEGMENTATION_LONGEST_RIGHTMOST:\n case SEGMENTATION_WEIGHTED_LONGEST:\n case SEGMENTATION_WEIGHTED_LEFTMOST:\n case SEGMENTATION_WEIGHTED_RIGHTMOST:\n buildSegmentationRecursive(method,*_segmentation[method],0,n_txt);\n break;\n default:\n break;\n }\n}\n\n\/\/ }}}\n\/\/ {{{ Segmenter::Segments::buildSegmentationRecursive\n\nvoid Segmenter::Segments::buildSegmentationRecursive(Segmenter::SegmentationMethod method,\n Segmenter::Segmentation& segmentation,\n unsigned int beg,\n unsigned int end)\n{\n int bestid, bestval1, bestval2, temp;\n int i;\n\n \/\/ locate the best segment according to method\n bestid=-1;bestval1=-1;bestval2=-1;\n for(i=0;i<(int)_segments.size();i++){\n if(beg<=_segments[i].beg() && end>=_segments[i].end()){\n switch(method){\n case SEGMENTATION_LONGEST_WEIGHTED:\n if((int)_segments[i].len()>bestval1 ||\n ((int)_segments[i].len()==bestval1 && (int)_segments[i].conn()>bestval2) ){\n bestid=i;\n bestval1=_segments[i].len();\n bestval2=_segments[i].conn();\n }\n break;\n case SEGMENTATION_LONGEST_LEFTMOST:\n if((int)_segments[i].len()>bestval1 ||\n ((int)_segments[i].len()==bestval1 && (int)_segments[i].beg()<bestval2) ){\n bestid=i;\n bestval1=_segments[i].len();\n bestval2=_segments[i].beg();\n }\n break;\n case SEGMENTATION_LONGEST_RIGHTMOST:\n if((int)_segments[i].len()>bestval1 ||\n ((int)_segments[i].len()==bestval1 && (int)_segments[i].end()>bestval2) ){\n bestid=i;\n bestval1=_segments[i].len();\n bestval2=_segments[i].end();\n }\n break;\n case SEGMENTATION_WEIGHTED_LONGEST:\n temp = (_segments[i].len()>1)?(int)_segments[i].conn():0;\n if(temp>bestval1 ||\n (temp==bestval1 &&\n (int)_segments[i].len()>bestval2) ){\n bestid=i;\n bestval1=temp;\n bestval2=_segments[i].len();\n }\n break;\n case SEGMENTATION_WEIGHTED_LEFTMOST:\n temp = (_segments[i].len()>1)?(int)_segments[i].conn():0;\n if(temp>bestval1 ||\n (temp==bestval1 &&\n (int)_segments[i].beg()<bestval2) ){\n bestid=i;\n bestval1=temp;\n bestval2=_segments[i].beg();\n }\n break;\n case SEGMENTATION_WEIGHTED_RIGHTMOST:\n temp = (int)_segments[i].len()>1?(int)_segments[i].conn():0;\n if(temp>bestval1 ||\n (temp==bestval1 &&\n (int)_segments[i].end()>bestval2) ){\n bestid=i;\n bestval1=temp;\n bestval2=_segments[i].end();\n }\n break;\n default: \/\/ dummy defult pick first possible\n if(bestid<0){\n bestid=i;\n }\n break;\n }\n }\n }\n if(bestid<0) {\n return; \/\/ this should never happen, as all one-word segments are created\n }\n\n \/\/ check left side\n if(beg<_segments[bestid].beg()){\n buildSegmentationRecursive(method,segmentation,beg,_segments[bestid].beg());\n }\n\n \/\/ add segment\n segmentation.push_back(bestid);\n\n \/\/ check right side\n if(end>_segments[bestid].end()){\n buildSegmentationRecursive(method,segmentation,_segments[bestid].end(),end);\n }\n}\n\n\/\/ }}}\n\n\/\/ {{{ Segmenter::segment\n\nvoid Segmenter::segment(Segmenter::Segments &segments) const\n{\n segments.clear();\n _detector.detect(segments.getText(),segments);\n}\n\nvoid Segmenter::segment(const NGram &text, Segmenter::Segments &segments) const\n{\n segments.setText(text);\n _detector.detect(segments.getText(),segments);\n}\n\nvoid Segmenter::segment(const std::string &text, Segmenter::Segments &segments) const\n{\n\n segments.setText(text);\n _detector.detect(segments.getText(),segments);\n}\n\nvoid Segmenter::segment(const char *text, Segmenter::Segments &segments) const\n{\n segments.setText(text);\n _detector.detect(segments.getText(),segments);\n}\n\n\/\/ }}}\n\n} \/\/ namespace fsa\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 2015, Nagoya University\n\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n *\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and\/or other materials provided with the distribution.\n *\n * * Neither the name of Autoware nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*\/\n\n#include \"lane_select_core.h\"\n\nnamespace lane_planner\n{\n\/\/ Constructor\nLaneSelectNode::LaneSelectNode()\n : private_nh_(\"~\")\n , num_of_lane_(-1)\n , num_of_closest_(-1)\n , change_flag_(ChangeFlag::unknown)\n , is_lane_array_subscribed_(false)\n , is_current_pose_subscribed_(false)\n , last_time_(ros::Time::now())\n{\n initParameter();\n initSubscriber();\n initPublisher();\n}\n\n\/\/ Destructor\nLaneSelectNode::~LaneSelectNode()\n{\n}\n\nvoid LaneSelectNode::initSubscriber()\n{\n \/\/ setup subscriber\n sub1_ = nh_.subscribe(\"traffic_waypoints_array\", 100, &LaneSelectNode::callbackFromLaneArray, this);\n sub2_ = nh_.subscribe(\"current_pose\", 100, &LaneSelectNode::callbackFromCurrentPose, this);\n}\n\nvoid LaneSelectNode::initPublisher()\n{\n \/\/ setup publisher\n pub_ = nh_.advertise<waypoint_follower::lane>(\"base_waypoints\", 10, true);\n}\n\nvoid LaneSelectNode::initParameter()\n{\n private_nh_.param<int32_t>(\"size_of_waypoints\", size_of_waypoints_, int32_t(30));\n private_nh_.param<int32_t>(\"lane_change_interval\",lane_change_interval_,int32_t(2));\n}\n\nvoid LaneSelectNode::publishLocalLane()\n{\n if (!is_current_pose_subscribed_ || !is_lane_array_subscribed_)\n {\n ROS_ERROR(\"Necessary topics are not subscribed yet.\");\n return;\n }\n\n if (num_of_lane_ == -1)\n num_of_lane_++;\n\n ros::Time current_time = ros::Time::now();\n double dt = (current_time -last_time_).toSec();\n ROS_INFO(\"dt: %lf\",dt);\n if (dt > 1.0 && (change_flag_ == ChangeFlag::right && num_of_lane_ < static_cast<int32_t>(lane_array_.lanes.size())))\n {\n num_of_lane_++;\n last_time_ = current_time;\n }\n\n if (dt > 1.0 && (change_flag_ == ChangeFlag::left && num_of_lane_ > 0))\n {\n num_of_lane_--;\n last_time_ = current_time;\n }\n\n waypoint_follower::lane local_lane;\n createLocalLane(&local_lane);\n pub_.publish(local_lane);\n\n \/\/if (current_lane.waypoints.at(num_of_closest_).change_flag == static_cast<ChangeFlagInteger>(ChangeFlag::right) &&\n \/\/ num_of_lane_ != lane_array_.size() - 1)\n \/\/{\n \/\/ num_of_lane_++;\n \/\/}\n\n is_current_pose_subscribed_ = false;\n}\n\nvoid LaneSelectNode::createLocalLane(waypoint_follower::lane *lane)\n{\n num_of_closest_ = getClosestWaypoint(lane_array_.lanes.at(num_of_lane_), current_pose_.pose);\n\n if (num_of_closest_ == -1)\n {\n ROS_ERROR(\"cannot get closest waypoint\");\n return;\n }\n\n \/\/ setup\n lane->header.stamp = ros::Time::now();\n lane->header.frame_id = \"map\";\n\n \/\/ push some waypoints\n for (auto i = 0; i < size_of_waypoints_; i++)\n {\n if(num_of_closest_ + i > static_cast<int32_t>(lane_array_.lanes.at(num_of_lane_).waypoints.size() -1) )\n break;\n\n lane->waypoints.push_back(lane_array_.lanes.at(num_of_lane_).waypoints.at(num_of_closest_ + i));\n\n }\n\n \/\/ push current_pose as first waypoint\n waypoint_follower::waypoint first_waypoint;\n first_waypoint = lane->waypoints.at(0);\n first_waypoint.pose.pose.position.x = current_pose_.pose.position.x;\n first_waypoint.pose.pose.position.y = current_pose_.pose.position.y;\n auto it = lane->waypoints.begin();\n lane->waypoints.insert(it,first_waypoint);\n change_flag_ = static_cast<ChangeFlag>(lane_array_.lanes.at(num_of_lane_).waypoints.at(num_of_closest_).change_flag);\n ROS_INFO(\"change_flag: %d\", static_cast<ChangeFlagInteger>(change_flag_));\n\n}\n\nvoid LaneSelectNode::callbackFromLaneArray(const waypoint_follower::LaneArrayConstPtr &msg)\n{\n lane_array_ = *msg;\n is_lane_array_subscribed_ = true;\n}\n\nvoid LaneSelectNode::callbackFromCurrentPose(const geometry_msgs::PoseStampedConstPtr &msg)\n{\n current_pose_ = *msg;\n is_current_pose_subscribed_ = true;\n publishLocalLane();\n}\n\n\/\/ get closest waypoint from current pose\n\/*int32_t getClosestWaypoint(const waypoint_follower::lane ¤t_path, const geometry_msgs::Pose ¤t_pose)\n{\n WayPoints wp;\n wp.setPath(current_path);\n\n if (wp.isEmpty())\n return -1;\n\n \/\/ search closest candidate within a certain meter\n double search_distance = 5.0;\n std::vector<int> waypoint_candidates;\n for (int i = 1; i < wp.getSize(); i++)\n {\n if (getPlaneDistance(wp.getWaypointPosition(i), current_pose.position) > search_distance)\n continue;\n\n if (!wp.isFront(i, current_pose))\n continue;\n\n double angle_threshold = 90;\n if (getRelativeAngle(wp.getWaypointPose(i), current_pose) > angle_threshold)\n continue;\n\n waypoint_candidates.push_back(i);\n }\n\n \/\/ get closest waypoint from candidates\n if (!waypoint_candidates.empty())\n {\n int waypoint_min = -1;\n double distance_min = DBL_MAX;\n for (auto el : waypoint_candidates)\n {\n \/\/ ROS_INFO(\"closest_candidates : %d\",el);\n double d = getPlaneDistance(wp.getWaypointPosition(el), current_pose.position);\n if (d < distance_min)\n {\n waypoint_min = el;\n distance_min = d;\n }\n }\n return waypoint_min;\n }\n else\n {\n ROS_INFO(\"no candidate. search closest waypoint from all waypoints...\");\n \/\/ if there is no candidate...\n int waypoint_min = -1;\n double distance_min = DBL_MAX;\n for (int i = 1; i < wp.getSize(); i++)\n {\n if (!wp.isFront(i, current_pose))\n continue;\n\n \/\/ if (!wp.isValid(i, current_pose))\n \/\/ continue;\n\n double d = getPlaneDistance(wp.getWaypointPosition(i), current_pose.position);\n if (d < distance_min)\n {\n waypoint_min = i;\n distance_min = d;\n }\n }\n return waypoint_min;\n }\n}*\/\n\n} \/\/ lane_planner\n<commit_msg>apply clang-format<commit_after>\/*\n * Copyright (c) 2015, Nagoya University\n\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n *\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and\/or other materials provided with the distribution.\n *\n * * Neither the name of Autoware nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*\/\n\n#include \"lane_select_core.h\"\n\nnamespace lane_planner\n{\n\/\/ Constructor\nLaneSelectNode::LaneSelectNode()\n : private_nh_(\"~\")\n , num_of_lane_(-1)\n , num_of_closest_(-1)\n , change_flag_(ChangeFlag::unknown)\n , is_lane_array_subscribed_(false)\n , is_current_pose_subscribed_(false)\n , last_time_(ros::Time::now())\n{\n initParameter();\n initSubscriber();\n initPublisher();\n}\n\n\/\/ Destructor\nLaneSelectNode::~LaneSelectNode()\n{\n}\n\nvoid LaneSelectNode::initSubscriber()\n{\n \/\/ setup subscriber\n sub1_ = nh_.subscribe(\"traffic_waypoints_array\", 100, &LaneSelectNode::callbackFromLaneArray, this);\n sub2_ = nh_.subscribe(\"current_pose\", 100, &LaneSelectNode::callbackFromCurrentPose, this);\n}\n\nvoid LaneSelectNode::initPublisher()\n{\n \/\/ setup publisher\n pub_ = nh_.advertise<waypoint_follower::lane>(\"base_waypoints\", 10, true);\n}\n\nvoid LaneSelectNode::initParameter()\n{\n private_nh_.param<int32_t>(\"size_of_waypoints\", size_of_waypoints_, int32_t(30));\n private_nh_.param<int32_t>(\"lane_change_interval\", lane_change_interval_, int32_t(2));\n}\n\nvoid LaneSelectNode::publishLocalLane()\n{\n if (!is_current_pose_subscribed_ || !is_lane_array_subscribed_)\n {\n ROS_ERROR(\"Necessary topics are not subscribed yet.\");\n return;\n }\n\n if (num_of_lane_ == -1)\n num_of_lane_++;\n\n ros::Time current_time = ros::Time::now();\n double dt = (current_time - last_time_).toSec();\n ROS_INFO(\"dt: %lf\", dt);\n if (dt > 1.0 && (change_flag_ == ChangeFlag::right && num_of_lane_ < static_cast<int32_t>(lane_array_.lanes.size())))\n {\n num_of_lane_++;\n last_time_ = current_time;\n }\n\n if (dt > 1.0 && (change_flag_ == ChangeFlag::left && num_of_lane_ > 0))\n {\n num_of_lane_--;\n last_time_ = current_time;\n }\n\n waypoint_follower::lane local_lane;\n createLocalLane(&local_lane);\n pub_.publish(local_lane);\n\n \/\/ if (current_lane.waypoints.at(num_of_closest_).change_flag == static_cast<ChangeFlagInteger>(ChangeFlag::right) &&\n \/\/ num_of_lane_ != lane_array_.size() - 1)\n \/\/{\n \/\/ num_of_lane_++;\n \/\/}\n\n is_current_pose_subscribed_ = false;\n}\n\nvoid LaneSelectNode::createLocalLane(waypoint_follower::lane *lane)\n{\n num_of_closest_ = getClosestWaypoint(lane_array_.lanes.at(num_of_lane_), current_pose_.pose);\n\n if (num_of_closest_ == -1)\n {\n ROS_ERROR(\"cannot get closest waypoint\");\n return;\n }\n\n \/\/ setup\n lane->header.stamp = ros::Time::now();\n lane->header.frame_id = \"map\";\n\n \/\/ push some waypoints\n for (auto i = 0; i < size_of_waypoints_; i++)\n {\n if (num_of_closest_ + i > static_cast<int32_t>(lane_array_.lanes.at(num_of_lane_).waypoints.size() - 1))\n break;\n\n lane->waypoints.push_back(lane_array_.lanes.at(num_of_lane_).waypoints.at(num_of_closest_ + i));\n }\n\n \/\/ push current_pose as first waypoint\n waypoint_follower::waypoint first_waypoint;\n first_waypoint = lane->waypoints.at(0);\n first_waypoint.pose.pose.position.x = current_pose_.pose.position.x;\n first_waypoint.pose.pose.position.y = current_pose_.pose.position.y;\n auto it = lane->waypoints.begin();\n lane->waypoints.insert(it, first_waypoint);\n change_flag_ = static_cast<ChangeFlag>(lane_array_.lanes.at(num_of_lane_).waypoints.at(num_of_closest_).change_flag);\n ROS_INFO(\"change_flag: %d\", static_cast<ChangeFlagInteger>(change_flag_));\n}\n\nvoid LaneSelectNode::callbackFromLaneArray(const waypoint_follower::LaneArrayConstPtr &msg)\n{\n lane_array_ = *msg;\n is_lane_array_subscribed_ = true;\n}\n\nvoid LaneSelectNode::callbackFromCurrentPose(const geometry_msgs::PoseStampedConstPtr &msg)\n{\n current_pose_ = *msg;\n is_current_pose_subscribed_ = true;\n publishLocalLane();\n}\n\n\/\/ get closest waypoint from current pose\n\/*int32_t getClosestWaypoint(const waypoint_follower::lane ¤t_path, const geometry_msgs::Pose ¤t_pose)\n{\n WayPoints wp;\n wp.setPath(current_path);\n\n if (wp.isEmpty())\n return -1;\n\n \/\/ search closest candidate within a certain meter\n double search_distance = 5.0;\n std::vector<int> waypoint_candidates;\n for (int i = 1; i < wp.getSize(); i++)\n {\n if (getPlaneDistance(wp.getWaypointPosition(i), current_pose.position) > search_distance)\n continue;\n\n if (!wp.isFront(i, current_pose))\n continue;\n\n double angle_threshold = 90;\n if (getRelativeAngle(wp.getWaypointPose(i), current_pose) > angle_threshold)\n continue;\n\n waypoint_candidates.push_back(i);\n }\n\n \/\/ get closest waypoint from candidates\n if (!waypoint_candidates.empty())\n {\n int waypoint_min = -1;\n double distance_min = DBL_MAX;\n for (auto el : waypoint_candidates)\n {\n \/\/ ROS_INFO(\"closest_candidates : %d\",el);\n double d = getPlaneDistance(wp.getWaypointPosition(el), current_pose.position);\n if (d < distance_min)\n {\n waypoint_min = el;\n distance_min = d;\n }\n }\n return waypoint_min;\n }\n else\n {\n ROS_INFO(\"no candidate. search closest waypoint from all waypoints...\");\n \/\/ if there is no candidate...\n int waypoint_min = -1;\n double distance_min = DBL_MAX;\n for (int i = 1; i < wp.getSize(); i++)\n {\n if (!wp.isFront(i, current_pose))\n continue;\n\n \/\/ if (!wp.isValid(i, current_pose))\n \/\/ continue;\n\n double d = getPlaneDistance(wp.getWaypointPosition(i), current_pose.position);\n if (d < distance_min)\n {\n waypoint_min = i;\n distance_min = d;\n }\n }\n return waypoint_min;\n }\n}*\/\n\n} \/\/ lane_planner\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * Copyright (c) 2011-2012 Kohei Yoshida\n *\n * Permission is hereby granted, free of charge, to any person\n * obtaining a copy of this software and associated documentation\n * files (the \"Software\"), to deal in the Software without\n * restriction, including without limitation the rights to use,\n * copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the\n * Software is furnished to do so, subject to the following\n * conditions:\n *\n * The above copyright notice and this permission notice shall be\n * included in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES\n * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,\n * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\n * OTHER DEALINGS IN THE SOFTWARE.\n *\n ************************************************************************\/\n\n#ifndef __MDDS_GRID_MAP_COLUMN_HPP__\n#define __MDDS_GRID_MAP_COLUMN_HPP__\n\n#include \"default_deleter.hpp\"\n#include \"compat\/unique_ptr.hpp\"\n#include \"global.hpp\"\n#include \"grid_map_types.hpp\"\n\n#include <vector>\n#include <algorithm>\n#include <cassert>\n\n#include <boost\/noncopyable.hpp>\n\nnamespace mdds { namespace __gridmap {\n\n\/**\n * Each column consists of a series of blocks, and each block stores a\n * series of non-empty cells of identical type.\n *\/\ntemplate<typename _Trait>\nclass column\n{\npublic:\n typedef size_t size_type;\n\n typedef typename mdds::gridmap::base_cell_block cell_block_type;\n typedef typename mdds::gridmap::cell_t cell_category_type;\n typedef typename _Trait::row_key_type row_key_type;\n\nprivate:\n typedef _Trait trait;\n\n typedef typename _Trait::cell_block_func cell_block_func;\n\n struct block : boost::noncopyable\n {\n size_type m_size;\n cell_block_type* mp_data;\n\n block();\n block(size_type _size);\n block(const block& other);\n ~block();\n };\n\npublic:\n column();\n column(size_type init_row_size);\n column(const column& other);\n ~column();\n\n template<typename _T>\n void set_cell(row_key_type row, const _T& cell);\n\n template<typename _T>\n void set_cells(row_key_type row, const _T& it_begin, const _T& it_end);\n\n template<typename _T>\n void insert_cells(row_key_type row, const _T& it_begin, const _T& it_end);\n\n template<typename _T>\n void get_cell(row_key_type row, _T& cell) const;\n\n template<typename _T>\n _T get_cell(row_key_type row) const;\n\n bool is_empty(row_key_type row) const;\n\n void set_empty(row_key_type start_row, row_key_type end_row);\n\n void erase(row_key_type start_row, row_key_type end_row);\n\n void insert_empty(row_key_type row, size_type length);\n\n void clear();\n\n size_type size() const;\n\n size_type block_size() const;\n\n bool empty() const;\n\n void resize(size_type new_size);\n\n void swap(column& other);\n\n bool operator== (const column& other) const;\n bool operator!= (const column& other) const;\n\n column& operator= (const column& other);\n\n template<typename _T>\n static gridmap::cell_t get_cell_type(const _T& cell);\n\nprivate:\n \/**\n * Check the row value to make sure it's within specified range, and\n * convert it to size_type for internal use.\n *\/\n size_type check_row_range(row_key_type row) const;\n\n void get_block_position(\n size_type row, size_type& start_row, size_type& block_index, size_type start_block=0, size_type start_block_row=0) const;\n\n template<typename _T>\n void create_new_block_with_new_cell(cell_block_type*& data, const _T& cell);\n\n template<typename _T>\n void set_cell_to_middle_of_block(\n size_type block_index, size_type pos_in_block, const _T& cell);\n\n template<typename _T>\n void append_cell_to_block(size_type block_index, const _T& cell);\n\n template<typename _T>\n void set_cell_impl(size_type row, const _T& cell);\n\n template<typename _T>\n void set_cell_to_empty_block(\n size_type block_index, size_type pos_in_block, const _T& cell);\n\n template<typename _T>\n void set_cell_to_block_of_size_one(\n size_type block_index, const _T& cell);\n\n template<typename _T>\n void set_cell_to_top_of_data_block(\n size_type block_index, const _T& cell);\n\n template<typename _T>\n void set_cell_to_bottom_of_data_block(\n size_type block_index, const _T& cell);\n\n void set_empty_in_single_block(\n size_type start_row, size_type end_row, size_type block_index, size_type start_row_in_block);\n\n void set_empty_in_multi_blocks(\n size_type start_row, size_type end_row,\n size_type block_index1, size_type start_row_in_block1,\n size_type block_index2, size_type start_row_in_block2);\n\n void erase_impl(size_type start_row, size_type end_row);\n\n void insert_empty_impl(size_type row, size_type length);\n\n template<typename _T>\n void set_cells_impl(size_type row, const _T& it_begin, const _T& it_end);\n\n template<typename _T>\n void insert_cells_impl(size_type row, const _T& it_begin, const _T& it_end);\n\n template<typename _T>\n void set_cells_to_single_block(\n size_type start_row, size_type end_row, size_type block_index,\n size_type start_row_in_block, const _T& it_begin, const _T& it_end);\n\n template<typename _T>\n void set_cells_to_multi_blocks(\n size_type start_row, size_type end_row,\n size_type block_index1, size_type start_row_in_block1,\n size_type block_index2, size_type start_row_in_block2,\n const _T& it_begin, const _T& it_end);\n\n\n template<typename _T>\n void set_cells_to_multi_blocks_block1_non_equal(\n size_type start_row, size_type end_row,\n size_type block_index1, size_type start_row_in_block1,\n size_type block_index2, size_type start_row_in_block2,\n const _T& it_begin, const _T& it_end);\n\n template<typename _T>\n void set_cells_to_multi_blocks_block1_non_empty(\n size_type start_row, size_type end_row,\n size_type block_index1, size_type start_row_in_block1,\n size_type block_index2, size_type start_row_in_block2,\n const _T& it_begin, const _T& it_end);\n\n template<typename _T>\n bool append_to_prev_block(\n size_type block_index, cell_category_type cat, size_type length,\n const _T& it_begin, const _T& it_end);\n\n template<typename _T>\n void insert_cells_to_middle(\n size_type row, size_type block_index, size_type start_row,\n const _T& it_begin, const _T& it_end);\n\nprivate:\n typedef std::vector<block*> blocks_type;\n blocks_type m_blocks;\n size_type m_cur_size;\n};\n\n}}\n\n#include \"grid_map_column_def.inl\"\n\n#endif\n<commit_msg>Method descriptions.<commit_after>\/*************************************************************************\n *\n * Copyright (c) 2011-2012 Kohei Yoshida\n *\n * Permission is hereby granted, free of charge, to any person\n * obtaining a copy of this software and associated documentation\n * files (the \"Software\"), to deal in the Software without\n * restriction, including without limitation the rights to use,\n * copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the\n * Software is furnished to do so, subject to the following\n * conditions:\n *\n * The above copyright notice and this permission notice shall be\n * included in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES\n * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,\n * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\n * OTHER DEALINGS IN THE SOFTWARE.\n *\n ************************************************************************\/\n\n#ifndef __MDDS_GRID_MAP_COLUMN_HPP__\n#define __MDDS_GRID_MAP_COLUMN_HPP__\n\n#include \"default_deleter.hpp\"\n#include \"compat\/unique_ptr.hpp\"\n#include \"global.hpp\"\n#include \"grid_map_types.hpp\"\n\n#include <vector>\n#include <algorithm>\n#include <cassert>\n\n#include <boost\/noncopyable.hpp>\n\nnamespace mdds { namespace __gridmap {\n\n\/**\n * Each column consists of a series of blocks, and each block stores a\n * series of non-empty cells of identical type.\n *\/\ntemplate<typename _Trait>\nclass column\n{\npublic:\n typedef size_t size_type;\n\n typedef typename mdds::gridmap::base_cell_block cell_block_type;\n typedef typename mdds::gridmap::cell_t cell_category_type;\n typedef typename _Trait::row_key_type row_key_type;\n\nprivate:\n typedef _Trait trait;\n\n typedef typename _Trait::cell_block_func cell_block_func;\n\n struct block : boost::noncopyable\n {\n size_type m_size;\n cell_block_type* mp_data;\n\n block();\n block(size_type _size);\n block(const block& other);\n ~block();\n };\n\npublic:\n column();\n column(size_type init_row_size);\n column(const column& other);\n ~column();\n\n \/**\n * Set a value of an arbitrary type to a specified row. The type of the\n * value is inferred from the value passed to this method. The new value\n * will overwrite an existing value at the specified row position if any.\n *\n * <p>The method will throw an <code>std::out_of_range<\/code> exception if\n * the specified row is outside the current container size.<\/p>\n *\n * <p>Calling this method will not change the size of the container.<\/p>\n *\n * @param row row to insert the value to.\n * @param cell value to insert.\n *\/\n template<typename _T>\n void set_cell(row_key_type row, const _T& cell);\n\n \/**\n * Set multiple cell values of identical type to a range of cells starting\n * at specified row. Any existing cell values will be overwritten by the\n * new values.\n *\n * <p>The method will throw an <code>std::out_of_range<\/code> exception if\n * the range of new values would fall outside the current container\n * size.<\/p>\n *\n * <p>Calling this method will not change the size of the container.<\/p>\n *\n * @param row position of the first value of the series of new values\n * being inserted.\n * @param it_begin iterator that points to the begin position of the\n * values being set.\n * @param it_end iterator that points to the end position of the values\n * being set.\n *\/\n template<typename _T>\n void set_cells(row_key_type row, const _T& it_begin, const _T& it_end);\n\n \/**\n * Insert multiple cell values of identical type to a specified row\n * position. Existing values that occur at or below the specified row\n * position will get shifted after the insertion. No existing values will\n * be overwritten by the inserted values.\n *\n * <p>The method will throw an <code>std::out_of_range<\/code> exception if\n * the specified row position is outside the current container size.<\/p>\n *\n * <p>Calling this method will increase the size of the container by\n * the length of the new values inserted.<\/p>\n *\n * @param row row position at which the new values are to be inserted.\n * @param it_begin iterator that points to the begin position of the\n * values being inserted.\n * @param it_end iterator that points to the end position of the values\n * being inserted.\n *\/\n template<typename _T>\n void insert_cells(row_key_type row, const _T& it_begin, const _T& it_end);\n\n template<typename _T>\n void get_cell(row_key_type row, _T& cell) const;\n\n template<typename _T>\n _T get_cell(row_key_type row) const;\n\n bool is_empty(row_key_type row) const;\n\n void set_empty(row_key_type start_row, row_key_type end_row);\n\n void erase(row_key_type start_row, row_key_type end_row);\n\n void insert_empty(row_key_type row, size_type length);\n\n void clear();\n\n size_type size() const;\n\n size_type block_size() const;\n\n bool empty() const;\n\n void resize(size_type new_size);\n\n void swap(column& other);\n\n bool operator== (const column& other) const;\n bool operator!= (const column& other) const;\n\n column& operator= (const column& other);\n\n template<typename _T>\n static gridmap::cell_t get_cell_type(const _T& cell);\n\nprivate:\n \/**\n * Check the row value to make sure it's within specified range, and\n * convert it to size_type for internal use.\n *\/\n size_type check_row_range(row_key_type row) const;\n\n void get_block_position(\n size_type row, size_type& start_row, size_type& block_index, size_type start_block=0, size_type start_block_row=0) const;\n\n template<typename _T>\n void create_new_block_with_new_cell(cell_block_type*& data, const _T& cell);\n\n template<typename _T>\n void set_cell_to_middle_of_block(\n size_type block_index, size_type pos_in_block, const _T& cell);\n\n template<typename _T>\n void append_cell_to_block(size_type block_index, const _T& cell);\n\n template<typename _T>\n void set_cell_impl(size_type row, const _T& cell);\n\n template<typename _T>\n void set_cell_to_empty_block(\n size_type block_index, size_type pos_in_block, const _T& cell);\n\n template<typename _T>\n void set_cell_to_block_of_size_one(\n size_type block_index, const _T& cell);\n\n template<typename _T>\n void set_cell_to_top_of_data_block(\n size_type block_index, const _T& cell);\n\n template<typename _T>\n void set_cell_to_bottom_of_data_block(\n size_type block_index, const _T& cell);\n\n void set_empty_in_single_block(\n size_type start_row, size_type end_row, size_type block_index, size_type start_row_in_block);\n\n void set_empty_in_multi_blocks(\n size_type start_row, size_type end_row,\n size_type block_index1, size_type start_row_in_block1,\n size_type block_index2, size_type start_row_in_block2);\n\n void erase_impl(size_type start_row, size_type end_row);\n\n void insert_empty_impl(size_type row, size_type length);\n\n template<typename _T>\n void set_cells_impl(size_type row, const _T& it_begin, const _T& it_end);\n\n template<typename _T>\n void insert_cells_impl(size_type row, const _T& it_begin, const _T& it_end);\n\n template<typename _T>\n void set_cells_to_single_block(\n size_type start_row, size_type end_row, size_type block_index,\n size_type start_row_in_block, const _T& it_begin, const _T& it_end);\n\n template<typename _T>\n void set_cells_to_multi_blocks(\n size_type start_row, size_type end_row,\n size_type block_index1, size_type start_row_in_block1,\n size_type block_index2, size_type start_row_in_block2,\n const _T& it_begin, const _T& it_end);\n\n template<typename _T>\n void set_cells_to_multi_blocks_block1_non_equal(\n size_type start_row, size_type end_row,\n size_type block_index1, size_type start_row_in_block1,\n size_type block_index2, size_type start_row_in_block2,\n const _T& it_begin, const _T& it_end);\n\n template<typename _T>\n void set_cells_to_multi_blocks_block1_non_empty(\n size_type start_row, size_type end_row,\n size_type block_index1, size_type start_row_in_block1,\n size_type block_index2, size_type start_row_in_block2,\n const _T& it_begin, const _T& it_end);\n\n template<typename _T>\n bool append_to_prev_block(\n size_type block_index, cell_category_type cat, size_type length,\n const _T& it_begin, const _T& it_end);\n\n template<typename _T>\n void insert_cells_to_middle(\n size_type row, size_type block_index, size_type start_row,\n const _T& it_begin, const _T& it_end);\n\nprivate:\n typedef std::vector<block*> blocks_type;\n blocks_type m_blocks;\n size_type m_cur_size;\n};\n\n}}\n\n#include \"grid_map_column_def.inl\"\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/*\n * GlobalHistogramBinarizer.cpp\n * zxing\n *\n * Created by Ralf Kistner on 16\/10\/2009.\n * Copyright 2008 ZXing authors All rights reserved.\n * Modified by Lukasz Warchol on 02\/02\/2010.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include <zxing\/common\/GlobalHistogramBinarizer.h>\n\n#include <zxing\/common\/IllegalArgumentException.h>\n\nnamespace zxing {\nusing namespace std;\n\nconst int LUMINANCE_BITS = 5;\nconst int LUMINANCE_SHIFT = 8 - LUMINANCE_BITS;\nconst int LUMINANCE_BUCKETS = 1 << LUMINANCE_BITS;\n\nGlobalHistogramBinarizer::GlobalHistogramBinarizer(Ref<LuminanceSource> source) :\n Binarizer(source), cached_matrix_(NULL), cached_row_(NULL), cached_row_num_(-1) {\n\n}\n\nGlobalHistogramBinarizer::~GlobalHistogramBinarizer() {\n}\n\n\nRef<BitArray> GlobalHistogramBinarizer::getBlackRow(int y, Ref<BitArray> row) {\n if (y == cached_row_num_) {\n return cached_row_;\n }\n\n vector<int> histogram(LUMINANCE_BUCKETS, 0);\n LuminanceSource& source = *getLuminanceSource();\n int width = source.getWidth();\n if (row == NULL || static_cast<int>(row->getSize()) < width) {\n row = new BitArray(width);\n } else {\n row->clear();\n }\n \n \/\/TODO(flyashi): cache this instead of allocating and deleting per row\n unsigned char* row_pixels = NULL;\n try {\n row_pixels = new unsigned char[width];\n getLuminanceSource()->getRow(y,row_pixels);\n for (int x = 0; x < width; x++) {\n histogram[row_pixels[x] >> LUMINANCE_SHIFT]++;\n }\n int blackPoint = estimate(histogram) << LUMINANCE_SHIFT;\n\n\n Ref<BitArray> array_ref(new BitArray(width));\n BitArray& array = *array_ref;\n\n int left = row_pixels[0];\n int center = row_pixels[1];\n for (int x = 1; x < width - 1; x++) {\n int right = row_pixels[x + 1];\n \/\/ A simple -1 4 -1 box filter with a weight of 2.\n int luminance = ((center << 2) - left - right) >> 1;\n if (luminance < blackPoint) {\n array.set(x);\n }\n left = center;\n center = right;\n }\n\n cached_row_ = array_ref;\n cached_row_num_ = y;\n delete [] row_pixels;\n return array_ref;\n } catch (IllegalArgumentException const& iae) {\n \/\/ Cache the fact that this row failed.\n cached_row_ = NULL;\n cached_row_num_ = y;\n delete [] row_pixels;\n throw iae;\n }\n}\n\nRef<BitMatrix> GlobalHistogramBinarizer::getBlackMatrix() {\n if (cached_matrix_ != NULL) {\n return cached_matrix_;\n }\n\n \/\/ Faster than working with the reference\n LuminanceSource& source = *getLuminanceSource();\n int width = source.getWidth();\n int height = source.getHeight();\n vector<int> histogram(LUMINANCE_BUCKETS, 0);\n\n \/\/ Quickly calculates the histogram by sampling four rows from the image.\n \/\/ This proved to be more robust on the blackbox tests than sampling a\n \/\/ diagonal as we used to do.\n unsigned char* row = new unsigned char[width];\n for (int y = 1; y < 5; y++) {\n int rownum = height * y \/ 5;\n int right = (width << 2) \/ 5;\n int sdf;\n getLuminanceSource()->getRow(rownum,row);\n for (int x = width \/ 5; x < right; x++) {\n histogram[row[x] >> LUMINANCE_SHIFT]++;\n sdf = histogram[row[x] >> LUMINANCE_SHIFT];\n }\n }\n\n int blackPoint = estimate(histogram) << LUMINANCE_SHIFT;\n\n Ref<BitMatrix> matrix_ref(new BitMatrix(width, height));\n BitMatrix& matrix = *matrix_ref;\n for (int y = 0; y < height; y++) {\n getLuminanceSource()->getRow(y,row);\n for (int x = 0; x < width; x++) {\n if (row[x] <= blackPoint)\n matrix.set(x, y);\n }\n }\n\n cached_matrix_ = matrix_ref;\n\n delete [] row;\n return matrix_ref;\n}\n\nint GlobalHistogramBinarizer::estimate(vector<int> &histogram) {\n int numBuckets = histogram.size();\n int maxBucketCount = 0;\n\n \/\/ Find tallest peak in histogram\n int firstPeak = 0;\n int firstPeakSize = 0;\n for (int i = 0; i < numBuckets; i++) {\n if (histogram[i] > firstPeakSize) {\n firstPeak = i;\n firstPeakSize = histogram[i];\n }\n if (histogram[i] > maxBucketCount) {\n maxBucketCount = histogram[i];\n }\n }\n\n \/\/ Find second-tallest peak -- well, another peak that is tall and not\n \/\/ so close to the first one\n int secondPeak = 0;\n int secondPeakScore = 0;\n for (int i = 0; i < numBuckets; i++) {\n int distanceToBiggest = i - firstPeak;\n \/\/ Encourage more distant second peaks by multiplying by square of distance\n int score = histogram[i] * distanceToBiggest * distanceToBiggest;\n if (score > secondPeakScore) {\n secondPeak = i;\n secondPeakScore = score;\n }\n }\n\n \/\/ Put firstPeak first\n if (firstPeak > secondPeak) {\n int temp = firstPeak;\n firstPeak = secondPeak;\n secondPeak = temp;\n }\n\n \/\/ Kind of arbitrary; if the two peaks are very close, then we figure there is\n \/\/ so little dynamic range in the image, that discriminating black and white\n \/\/ is too error-prone.\n \/\/ Decoding the image\/line is either pointless, or may in some cases lead to\n \/\/ a false positive for 1D formats, which are relatively lenient.\n \/\/ We arbitrarily say \"close\" is\n \/\/ \"<= 1\/16 of the total histogram buckets apart\"\n if (secondPeak - firstPeak <= numBuckets >> 4) {\n throw IllegalArgumentException(\"Too little dynamic range in luminance\");\n }\n\n \/\/ Find a valley between them that is low and closer to the white peak\n int bestValley = secondPeak - 1;\n int bestValleyScore = -1;\n for (int i = secondPeak - 1; i > firstPeak; i--) {\n int fromFirst = i - firstPeak;\n \/\/ Favor a \"valley\" that is not too close to either peak -- especially not\n \/\/ the black peak -- and that has a low value of course\n int score = fromFirst * fromFirst * (secondPeak - i) *\n (maxBucketCount - histogram[i]);\n if (score > bestValleyScore) {\n bestValley = i;\n bestValleyScore = score;\n }\n }\n\n return bestValley;\n}\n\nRef<Binarizer> GlobalHistogramBinarizer::createBinarizer(Ref<LuminanceSource> source) {\n return Ref<Binarizer> (new GlobalHistogramBinarizer(source));\n}\n\n} \/\/ namespace zxing\n\n<commit_msg>Slight refinement to last change - a cached row which failed should throw an exception, not return NULL.<commit_after>\/*\n * GlobalHistogramBinarizer.cpp\n * zxing\n *\n * Created by Ralf Kistner on 16\/10\/2009.\n * Copyright 2008 ZXing authors All rights reserved.\n * Modified by Lukasz Warchol on 02\/02\/2010.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include <zxing\/common\/GlobalHistogramBinarizer.h>\n\n#include <zxing\/common\/IllegalArgumentException.h>\n\nnamespace zxing {\nusing namespace std;\n\nconst int LUMINANCE_BITS = 5;\nconst int LUMINANCE_SHIFT = 8 - LUMINANCE_BITS;\nconst int LUMINANCE_BUCKETS = 1 << LUMINANCE_BITS;\n\nGlobalHistogramBinarizer::GlobalHistogramBinarizer(Ref<LuminanceSource> source) :\n Binarizer(source), cached_matrix_(NULL), cached_row_(NULL), cached_row_num_(-1) {\n\n}\n\nGlobalHistogramBinarizer::~GlobalHistogramBinarizer() {\n}\n\n\nRef<BitArray> GlobalHistogramBinarizer::getBlackRow(int y, Ref<BitArray> row) {\n if (y == cached_row_num_) {\n if (cached_row_ != NULL) {\n return cached_row_;\n } else {\n throw IllegalArgumentException(\"Too little dynamic range in luminance\");\n }\n }\n\n vector<int> histogram(LUMINANCE_BUCKETS, 0);\n LuminanceSource& source = *getLuminanceSource();\n int width = source.getWidth();\n if (row == NULL || static_cast<int>(row->getSize()) < width) {\n row = new BitArray(width);\n } else {\n row->clear();\n }\n \n \/\/TODO(flyashi): cache this instead of allocating and deleting per row\n unsigned char* row_pixels = NULL;\n try {\n row_pixels = new unsigned char[width];\n getLuminanceSource()->getRow(y,row_pixels);\n for (int x = 0; x < width; x++) {\n histogram[row_pixels[x] >> LUMINANCE_SHIFT]++;\n }\n int blackPoint = estimate(histogram) << LUMINANCE_SHIFT;\n\n\n Ref<BitArray> array_ref(new BitArray(width));\n BitArray& array = *array_ref;\n\n int left = row_pixels[0];\n int center = row_pixels[1];\n for (int x = 1; x < width - 1; x++) {\n int right = row_pixels[x + 1];\n \/\/ A simple -1 4 -1 box filter with a weight of 2.\n int luminance = ((center << 2) - left - right) >> 1;\n if (luminance < blackPoint) {\n array.set(x);\n }\n left = center;\n center = right;\n }\n\n cached_row_ = array_ref;\n cached_row_num_ = y;\n delete [] row_pixels;\n return array_ref;\n } catch (IllegalArgumentException const& iae) {\n \/\/ Cache the fact that this row failed.\n cached_row_ = NULL;\n cached_row_num_ = y;\n delete [] row_pixels;\n throw iae;\n }\n}\n\nRef<BitMatrix> GlobalHistogramBinarizer::getBlackMatrix() {\n if (cached_matrix_ != NULL) {\n return cached_matrix_;\n }\n\n \/\/ Faster than working with the reference\n LuminanceSource& source = *getLuminanceSource();\n int width = source.getWidth();\n int height = source.getHeight();\n vector<int> histogram(LUMINANCE_BUCKETS, 0);\n\n \/\/ Quickly calculates the histogram by sampling four rows from the image.\n \/\/ This proved to be more robust on the blackbox tests than sampling a\n \/\/ diagonal as we used to do.\n unsigned char* row = new unsigned char[width];\n for (int y = 1; y < 5; y++) {\n int rownum = height * y \/ 5;\n int right = (width << 2) \/ 5;\n int sdf;\n getLuminanceSource()->getRow(rownum,row);\n for (int x = width \/ 5; x < right; x++) {\n histogram[row[x] >> LUMINANCE_SHIFT]++;\n sdf = histogram[row[x] >> LUMINANCE_SHIFT];\n }\n }\n\n int blackPoint = estimate(histogram) << LUMINANCE_SHIFT;\n\n Ref<BitMatrix> matrix_ref(new BitMatrix(width, height));\n BitMatrix& matrix = *matrix_ref;\n for (int y = 0; y < height; y++) {\n getLuminanceSource()->getRow(y,row);\n for (int x = 0; x < width; x++) {\n if (row[x] <= blackPoint)\n matrix.set(x, y);\n }\n }\n\n cached_matrix_ = matrix_ref;\n\n delete [] row;\n return matrix_ref;\n}\n\nint GlobalHistogramBinarizer::estimate(vector<int> &histogram) {\n int numBuckets = histogram.size();\n int maxBucketCount = 0;\n\n \/\/ Find tallest peak in histogram\n int firstPeak = 0;\n int firstPeakSize = 0;\n for (int i = 0; i < numBuckets; i++) {\n if (histogram[i] > firstPeakSize) {\n firstPeak = i;\n firstPeakSize = histogram[i];\n }\n if (histogram[i] > maxBucketCount) {\n maxBucketCount = histogram[i];\n }\n }\n\n \/\/ Find second-tallest peak -- well, another peak that is tall and not\n \/\/ so close to the first one\n int secondPeak = 0;\n int secondPeakScore = 0;\n for (int i = 0; i < numBuckets; i++) {\n int distanceToBiggest = i - firstPeak;\n \/\/ Encourage more distant second peaks by multiplying by square of distance\n int score = histogram[i] * distanceToBiggest * distanceToBiggest;\n if (score > secondPeakScore) {\n secondPeak = i;\n secondPeakScore = score;\n }\n }\n\n \/\/ Put firstPeak first\n if (firstPeak > secondPeak) {\n int temp = firstPeak;\n firstPeak = secondPeak;\n secondPeak = temp;\n }\n\n \/\/ Kind of arbitrary; if the two peaks are very close, then we figure there is\n \/\/ so little dynamic range in the image, that discriminating black and white\n \/\/ is too error-prone.\n \/\/ Decoding the image\/line is either pointless, or may in some cases lead to\n \/\/ a false positive for 1D formats, which are relatively lenient.\n \/\/ We arbitrarily say \"close\" is\n \/\/ \"<= 1\/16 of the total histogram buckets apart\"\n if (secondPeak - firstPeak <= numBuckets >> 4) {\n throw IllegalArgumentException(\"Too little dynamic range in luminance\");\n }\n\n \/\/ Find a valley between them that is low and closer to the white peak\n int bestValley = secondPeak - 1;\n int bestValleyScore = -1;\n for (int i = secondPeak - 1; i > firstPeak; i--) {\n int fromFirst = i - firstPeak;\n \/\/ Favor a \"valley\" that is not too close to either peak -- especially not\n \/\/ the black peak -- and that has a low value of course\n int score = fromFirst * fromFirst * (secondPeak - i) *\n (maxBucketCount - histogram[i]);\n if (score > bestValleyScore) {\n bestValley = i;\n bestValleyScore = score;\n }\n }\n\n return bestValley;\n}\n\nRef<Binarizer> GlobalHistogramBinarizer::createBinarizer(Ref<LuminanceSource> source) {\n return Ref<Binarizer> (new GlobalHistogramBinarizer(source));\n}\n\n} \/\/ namespace zxing\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (C) 2010-2013 Joshua Boyce.\r\n\/\/ See the file COPYING for copying permission.\r\n\r\n#pragma once\r\n\r\n#include <array>\r\n#include <cstddef>\r\n#include <exception>\r\n#include <memory>\r\n#include <string>\r\n#include <type_traits>\r\n#include <vector>\r\n\r\n#include <windows.h>\r\n\r\n#include <hadesmem\/detail\/assert.hpp>\r\n#include <hadesmem\/detail\/protect_guard.hpp>\r\n#include <hadesmem\/detail\/query_region.hpp>\r\n#include <hadesmem\/detail\/read_impl.hpp>\r\n#include <hadesmem\/detail\/static_assert.hpp>\r\n#include <hadesmem\/detail\/type_traits.hpp>\r\n#include <hadesmem\/error.hpp>\r\n#include <hadesmem\/protect.hpp>\r\n\r\n\/\/ TODO: Support custom string, vector, etc types. Also support custom \r\n\/\/ allocators, traits, etc.\r\n\r\nnamespace hadesmem\r\n{\r\n \r\ntemplate <typename T>\r\ninline T Read(Process const& process, PVOID address)\r\n{\r\n HADESMEM_DETAIL_ASSERT(address != nullptr);\r\n \r\n return detail::ReadImpl<T>(process, address);\r\n}\r\n\r\ntemplate <typename T, std::size_t N>\r\ninline std::array<T, N> Read(Process const& process, PVOID address)\r\n{\r\n HADESMEM_DETAIL_STATIC_ASSERT(N != 0);\r\n\r\n HADESMEM_DETAIL_ASSERT(address != nullptr);\r\n\r\n return detail::ReadImpl<std::array<T, N>>(process, address);\r\n}\r\n\r\ntemplate <typename T, std::size_t N, typename OutputIterator>\r\ninline void Read(Process const& process, PVOID address, OutputIterator out)\r\n{\r\n \/\/ TODO: Iterator checks for type and category.\r\n\r\n HADESMEM_DETAIL_STATIC_ASSERT(N != 0);\r\n\r\n HADESMEM_DETAIL_ASSERT(address != nullptr);\r\n\r\n auto const data = detail::ReadImpl<std::array<T, N>>(process, address);\r\n std::copy(&data[0], &data[0] + N, out);\r\n}\r\n\r\ntemplate <typename T>\r\ninline std::vector<T> ReadVector(\r\n Process const& process, \r\n PVOID address, \r\n std::size_t count);\r\n\r\ntemplate <typename T, typename OutputIterator>\r\ninline void Read(\r\n Process const& process, \r\n PVOID address, \r\n std::size_t n, \r\n OutputIterator out)\r\n{\r\n HADESMEM_DETAIL_ASSERT(address != nullptr);\r\n HADESMEM_DETAIL_ASSERT(n != 0);\r\n\r\n auto const data = ReadVector<T>(process, address, n);\r\n std::copy(std::begin(data), std::end(data), out);\r\n}\r\n\r\n\/\/ TODO: Clean up this function.\r\ntemplate <typename T, typename OutputIterator>\r\nvoid ReadStringEx(\r\n Process const& process, \r\n PVOID address, \r\n OutputIterator data, \r\n std::size_t chunk_len)\r\n{\r\n HADESMEM_DETAIL_STATIC_ASSERT(detail::IsCharType<T>::value);\r\n\r\n HADESMEM_DETAIL_ASSERT(chunk_len != 0);\r\n \r\n \/\/ TODO: Iterator checks for type and category.\r\n\r\n for (;;)\r\n {\r\n detail::ProtectGuard protect_guard(process, address, \r\n detail::ProtectGuardType::kRead);\r\n\r\n MEMORY_BASIC_INFORMATION const mbi = detail::Query(process, address);\r\n PVOID const region_next = static_cast<PBYTE>(mbi.BaseAddress) + \r\n mbi.RegionSize;\r\n\r\n T* cur = static_cast<T*>(address);\r\n while (cur + 1 <= region_next)\r\n {\r\n std::size_t const len_to_end = \r\n reinterpret_cast<DWORD_PTR>(region_next) - \r\n reinterpret_cast<DWORD_PTR>(cur);\r\n std::size_t const buf_len_bytes = (std::min)(chunk_len * sizeof(T), \r\n len_to_end);\r\n std::size_t const buf_len = buf_len_bytes \/ sizeof(T);\r\n\r\n std::vector<T> buf(buf_len);\r\n detail::ReadUnchecked(process, cur, buf.data(), buf.size() * sizeof(T));\r\n\r\n auto const iter = std::find(std::begin(buf), std::end(buf), T());\r\n std::copy(std::begin(buf), iter, data);\r\n\r\n if (iter != std::end(buf))\r\n {\r\n protect_guard.Restore();\r\n return;\r\n }\r\n\r\n cur += buf_len;\r\n }\r\n\r\n address = region_next;\r\n\r\n protect_guard.Restore();\r\n }\r\n}\r\n\r\ntemplate <typename T, typename OutputIterator>\r\nvoid ReadString(\r\n Process const& process, \r\n PVOID address, \r\n OutputIterator data)\r\n{\r\n std::size_t const chunk_len = 128;\r\n return ReadStringEx<T>(process, address, data, chunk_len);\r\n}\r\n\r\n\/\/ TODO: Support containers with custom traits, allocators, etc.\r\ntemplate <typename T>\r\nstd::basic_string<T> ReadStringEx(\r\n Process const& process, \r\n PVOID address, \r\n std::size_t chunk_len)\r\n{\r\n std::basic_string<T> data;\r\n ReadStringEx<T>(process, address, std::back_inserter(data), chunk_len);\r\n return data;\r\n}\r\n\r\n\/\/ TODO: Support containers with custom traits, allocators, etc.\r\ntemplate <typename T>\r\nstd::basic_string<T> ReadString(Process const& process, PVOID address)\r\n{\r\n std::size_t const chunk_len = 128;\r\n return ReadStringEx<T>(process, address, chunk_len);\r\n}\r\n\r\n\/\/ TODO: Support containers with custom traits, allocators, etc.\r\ntemplate <typename T>\r\ninline std::vector<T> ReadVector(\r\n Process const& process, \r\n PVOID address, \r\n std::size_t count)\r\n{\r\n HADESMEM_DETAIL_STATIC_ASSERT(detail::IsTriviallyCopyable<T>::value);\r\n HADESMEM_DETAIL_STATIC_ASSERT(detail::IsDefaultConstructible<T>::value);\r\n \r\n HADESMEM_DETAIL_ASSERT(address != nullptr);\r\n HADESMEM_DETAIL_ASSERT(count != 0);\r\n \r\n std::vector<T> data(count);\r\n detail::ReadImpl(process, address, data.data(), sizeof(T) * count);\r\n return data;\r\n}\r\n\r\ntemplate <typename T, typename OutputIterator>\r\ninline void ReadVector(\r\n Process const& process, \r\n PVOID address, \r\n std::size_t count, \r\n OutputIterator out)\r\n{\r\n \/\/ TODO: Iterator checks for type and category.\r\n\r\n HADESMEM_DETAIL_STATIC_ASSERT(detail::IsTriviallyCopyable<T>::value);\r\n HADESMEM_DETAIL_STATIC_ASSERT(detail::IsDefaultConstructible<T>::value);\r\n \r\n HADESMEM_DETAIL_ASSERT(address != nullptr);\r\n HADESMEM_DETAIL_ASSERT(count != 0);\r\n\r\n std::vector<T> data = ReadVector<T>(process, address, count);\r\n std::copy(std::begin(data), std::end(data), out);\r\n}\r\n\r\n}\r\n<commit_msg>* Add iterator category checks.<commit_after>\/\/ Copyright (C) 2010-2013 Joshua Boyce.\r\n\/\/ See the file COPYING for copying permission.\r\n\r\n#pragma once\r\n\r\n#include <array>\r\n#include <cstddef>\r\n#include <exception>\r\n#include <iterator>\r\n#include <memory>\r\n#include <string>\r\n#include <type_traits>\r\n#include <vector>\r\n\r\n#include <windows.h>\r\n\r\n#include <hadesmem\/detail\/assert.hpp>\r\n#include <hadesmem\/detail\/protect_guard.hpp>\r\n#include <hadesmem\/detail\/query_region.hpp>\r\n#include <hadesmem\/detail\/read_impl.hpp>\r\n#include <hadesmem\/detail\/static_assert.hpp>\r\n#include <hadesmem\/detail\/type_traits.hpp>\r\n#include <hadesmem\/error.hpp>\r\n#include <hadesmem\/protect.hpp>\r\n\r\n\/\/ TODO: Support custom string, vector, etc types. Also support custom \r\n\/\/ allocators, traits, etc.\r\n\r\nnamespace hadesmem\r\n{\r\n \r\ntemplate <typename T>\r\ninline T Read(Process const& process, PVOID address)\r\n{\r\n HADESMEM_DETAIL_ASSERT(address != nullptr);\r\n \r\n return detail::ReadImpl<T>(process, address);\r\n}\r\n\r\ntemplate <typename T, std::size_t N>\r\ninline std::array<T, N> Read(Process const& process, PVOID address)\r\n{\r\n HADESMEM_DETAIL_STATIC_ASSERT(N != 0);\r\n\r\n HADESMEM_DETAIL_ASSERT(address != nullptr);\r\n\r\n return detail::ReadImpl<std::array<T, N>>(process, address);\r\n}\r\n\r\ntemplate <typename T, std::size_t N, typename OutputIterator>\r\ninline void Read(Process const& process, PVOID address, OutputIterator out)\r\n{\r\n HADESMEM_DETAIL_STATIC_ASSERT(std::is_same<std::output_iterator_tag, \r\n typename std::iterator_traits<OutputIterator>::iterator_category>::value);\r\n\r\n HADESMEM_DETAIL_STATIC_ASSERT(N != 0);\r\n\r\n HADESMEM_DETAIL_ASSERT(address != nullptr);\r\n\r\n auto const data = detail::ReadImpl<std::array<T, N>>(process, address);\r\n std::copy(&data[0], &data[0] + N, out);\r\n}\r\n\r\ntemplate <typename T>\r\ninline std::vector<T> ReadVector(\r\n Process const& process, \r\n PVOID address, \r\n std::size_t count);\r\n\r\ntemplate <typename T, typename OutputIterator>\r\ninline void Read(\r\n Process const& process, \r\n PVOID address, \r\n std::size_t n, \r\n OutputIterator out)\r\n{\r\n HADESMEM_DETAIL_ASSERT(address != nullptr);\r\n HADESMEM_DETAIL_ASSERT(n != 0);\r\n\r\n auto const data = ReadVector<T>(process, address, n);\r\n std::copy(std::begin(data), std::end(data), out);\r\n}\r\n\r\ntemplate <typename T, typename OutputIterator>\r\nvoid ReadStringEx(\r\n Process const& process, \r\n PVOID address, \r\n OutputIterator data, \r\n std::size_t chunk_len)\r\n{\r\n HADESMEM_DETAIL_STATIC_ASSERT(detail::IsCharType<T>::value);\r\n HADESMEM_DETAIL_STATIC_ASSERT(std::is_same<std::output_iterator_tag, \r\n typename std::iterator_traits<OutputIterator>::iterator_category>::value);\r\n\r\n HADESMEM_DETAIL_ASSERT(chunk_len != 0);\r\n\r\n for (;;)\r\n {\r\n detail::ProtectGuard protect_guard(process, address, \r\n detail::ProtectGuardType::kRead);\r\n\r\n MEMORY_BASIC_INFORMATION const mbi = detail::Query(process, address);\r\n PVOID const region_next = static_cast<PBYTE>(mbi.BaseAddress) + \r\n mbi.RegionSize;\r\n\r\n T* cur = static_cast<T*>(address);\r\n while (cur + 1 <= region_next)\r\n {\r\n std::size_t const len_to_end = \r\n reinterpret_cast<DWORD_PTR>(region_next) - \r\n reinterpret_cast<DWORD_PTR>(cur);\r\n std::size_t const buf_len_bytes = (std::min)(chunk_len * sizeof(T), \r\n len_to_end);\r\n std::size_t const buf_len = buf_len_bytes \/ sizeof(T);\r\n\r\n std::vector<T> buf(buf_len);\r\n detail::ReadUnchecked(process, cur, buf.data(), buf.size() * sizeof(T));\r\n\r\n auto const iter = std::find(std::begin(buf), std::end(buf), T());\r\n std::copy(std::begin(buf), iter, data);\r\n\r\n if (iter != std::end(buf))\r\n {\r\n protect_guard.Restore();\r\n return;\r\n }\r\n\r\n cur += buf_len;\r\n }\r\n\r\n address = region_next;\r\n\r\n protect_guard.Restore();\r\n }\r\n}\r\n\r\ntemplate <typename T, typename OutputIterator>\r\nvoid ReadString(\r\n Process const& process, \r\n PVOID address, \r\n OutputIterator data)\r\n{\r\n std::size_t const chunk_len = 128;\r\n return ReadStringEx<T>(process, address, data, chunk_len);\r\n}\r\n\r\n\/\/ TODO: Support containers with custom traits, allocators, etc.\r\ntemplate <typename T>\r\nstd::basic_string<T> ReadStringEx(\r\n Process const& process, \r\n PVOID address, \r\n std::size_t chunk_len)\r\n{\r\n std::basic_string<T> data;\r\n ReadStringEx<T>(process, address, std::back_inserter(data), chunk_len);\r\n return data;\r\n}\r\n\r\n\/\/ TODO: Support containers with custom traits, allocators, etc.\r\ntemplate <typename T>\r\nstd::basic_string<T> ReadString(Process const& process, PVOID address)\r\n{\r\n std::size_t const chunk_len = 128;\r\n return ReadStringEx<T>(process, address, chunk_len);\r\n}\r\n\r\n\/\/ TODO: Support containers with custom traits, allocators, etc.\r\ntemplate <typename T>\r\ninline std::vector<T> ReadVector(\r\n Process const& process, \r\n PVOID address, \r\n std::size_t count)\r\n{\r\n HADESMEM_DETAIL_STATIC_ASSERT(detail::IsTriviallyCopyable<T>::value);\r\n HADESMEM_DETAIL_STATIC_ASSERT(detail::IsDefaultConstructible<T>::value);\r\n \r\n HADESMEM_DETAIL_ASSERT(address != nullptr);\r\n HADESMEM_DETAIL_ASSERT(count != 0);\r\n \r\n std::vector<T> data(count);\r\n detail::ReadImpl(process, address, data.data(), sizeof(T) * count);\r\n return data;\r\n}\r\n\r\ntemplate <typename T, typename OutputIterator>\r\ninline void ReadVector(\r\n Process const& process, \r\n PVOID address, \r\n std::size_t count, \r\n OutputIterator out)\r\n{\r\n HADESMEM_DETAIL_STATIC_ASSERT(std::is_same<std::output_iterator_tag, \r\n typename std::iterator_traits<OutputIterator>::iterator_category>::value);\r\n HADESMEM_DETAIL_STATIC_ASSERT(detail::IsTriviallyCopyable<T>::value);\r\n HADESMEM_DETAIL_STATIC_ASSERT(detail::IsDefaultConstructible<T>::value);\r\n \r\n HADESMEM_DETAIL_ASSERT(address != nullptr);\r\n HADESMEM_DETAIL_ASSERT(count != 0);\r\n\r\n std::vector<T> data = ReadVector<T>(process, address, count);\r\n std::copy(std::begin(data), std::end(data), out);\r\n}\r\n\r\n}\r\n<|endoftext|>"} {"text":"<commit_before>#include <vector>\n\nnamespace data{\nextern std::vector< std::vector<size_t> > docs;\n}<commit_msg>Use namespace std to see if size_t will work<commit_after>#include <vector>\n\nusing namespace std;\n\nnamespace data{\nextern std::vector< std::vector<size_t> > docs;\n}<|endoftext|>"} {"text":"<commit_before>\/*\n * The MIT License (MIT)\n *\n * Copyright (c) 2017 Hidekazu Ikeno\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n *\/\n\n\/\/\/\n\/\/\/ \\file aak_reduction.hpp\n\/\/\/\n\/\/\/ Sparse approximation of exponential sum using AAK theory.\n\/\/\/\n\n#ifndef MXPFIT_AAK_REDUCTION_HPP\n#define MXPFIT_AAK_REDUCTION_HPP\n\n#include <algorithm>\n\n#include <mxpfit\/exponential_sum.hpp>\n#include <mxpfit\/quasi_cauchy_rrd.hpp>\n#include <mxpfit\/self_adjoint_coneigensolver.hpp>\n\nnamespace mxpfit\n{\n\nnamespace detail\n{\n} \/\/ namespace: detail\n\n\/\/\/\n\/\/\/ ### AAKReduction\n\/\/\/\n\/\/\/ \\brief Find a truncated exponential sum function with smaller number of\n\/\/\/ terms using AAK theory.\n\/\/\/\n\/\/\/ \\tparam T Scalar type of exponential sum function.\n\/\/\/\n\/\/\/ For a given exponential sum function\n\/\/\/ \\f[\n\/\/\/ f(t)=\\sum_{j=1}^{N} c_{j}^{} e^{-p_{j}^{} t}, \\quad\n\/\/\/ (\\mathrm{Re}(a_{j}) > 0).\n\/\/\/ \\f]\n\/\/\/\n\/\/\/ and prescribed accuracy \\f$\\epsilon > 0,\\f$ this class calculates truncated\n\/\/\/ exponential \\f$\\tilde{f}(t)\\f$ sum such that\n\/\/\/\n\/\/\/ \\f[\n\/\/\/ \\tilde{f}(t)=\\sum_{j=1}^{M} \\tilde{c}_{j}^{}e^{-\\tilde{p}_{j}^{} t}, \\quad\n\/\/\/ \\left| f(t)-\\tilde{f}(t) \\right| < \\epsilon,\n\/\/\/ \\f]\n\/\/\/\n\/\/\/\n\/\/\/ The signal \\f$\\boldsymbol{f}=(f_{k})_{k=0}^{\\infty}\\f$ sampled on\n\/\/\/ \\f$k=0,1,\\dots\\f$ are expressed as\n\/\/\/\n\/\/\/ \\f[\n\/\/\/ f_{k}:= f(k) = \\sum_{j=1}^{N} c_{j} z_{j}^{k}\n\/\/\/ \\f]\n\/\/\/\n\/\/\/ where \\f$z_{j}=e^{-p_{j}}\\in \\mathbb{D}:=\\{z \\in \\mathbb{C}:0<|z|<1\\}.\\f$\n\/\/\/ The problem to find truncated exponential sum can be recast to find a new\n\/\/\/ signal \\f$\\tilde{\\boldsymbol{f}},\\f$ a sparse approximation of signal\n\/\/\/ \\f$\\boldsymbol{f},\\f$ such that\n\/\/\/\n\/\/\/ \\f[\n\/\/\/ \\tilde{f}_{k}=\\sum_{j=1}^{M}\\tilde{c}_{j}^{} \\tilde{z}_{j}^{k}, \\quad\n\/\/\/ \\|\\boldsymbol{f}-\\tilde{\\boldsymbol{f}}\\|<\\epsilon. \\f$\n\/\/\/ \\f]\n\/\/\/\n\/\/\/ Then, the exponents of reduced exponential sum\n\/\/\/ \\f$\\tilde{f}(t)\\f$ are obtained as \\f$\\tilde{p}_{j}=\\tilde{z}_{j}.\\f$\n\/\/\/\n\/\/\/\n\/\/\/ #### References\n\/\/\/\n\/\/\/ 1. Gerlind Plonka and Vlada Pototskaia, \"Application of the AAK theory for\n\/\/\/ sparse approximation of exponential sums\", arXiv 1609.09603v1 (2016).\n\/\/\/ [URL: https:\/\/arxiv.org\/abs\/1609.09603v1]\n\/\/\/ 2. Gregory Beylkin and Lucas Monzón, \"On approximation of functions by\n\/\/\/ exponential sums\", Appl. Comput. Harmon. Anal. **19** (2005) 17-48.\n\/\/\/ [DOI: https:\/\/doi.org\/10.1016\/j.acha.2005.01.003]\n\/\/\/ 3. T. S. Haut and G. Beylkin, \"FAST AND ACCURATE CON-EIGENVALUE ALGORITHM\n\/\/\/ FOR OPTIMAL RATIONAL APPROXIMATIONS\", SIAM J. Matrix Anal. Appl. **33**\n\/\/\/ (2012) 1101-1125.\n\/\/\/ [DOI: https:\/\/doi.org\/10.1137\/110821901]\n\/\/\/ 4. Terry Haut, Gregory Beylkin, and Lucas Monzón, \"Solving Burgers’\n\/\/\/ equation using optimal rational approximations\", Appl. Comput. Harmon.\n\/\/\/ Anal. **34** (2013) 83-95.\n\/\/\/ [DOI: https:\/\/doi.org\/10.1016\/j.acha.2012.03.004]\n\/\/\/\ntemplate <typename T>\nclass AAKReduction\n{\npublic:\n using Scalar = T;\n using RealScalar = typename Eigen::NumTraits<Scalar>::Real;\n using ComplexScalar = std::complex<RealScalar>;\n using Index = Eigen::Index;\n\n using VectorType = Eigen::Matrix<Scalar, Eigen::Dynamic, 1>;\n using MatrixType = Eigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic>;\n using ResultType = ExponentialSum<Scalar>;\n\n \/\/\/\n \/\/\/ Compute truncated exponential sum \\f$ \\hat{f}(t) \\f$\n \/\/\/\n \/\/\/ \\tparam DerivedF type of exponential sum inheriting ExponentialSumBase\n \/\/\/\n \/\/\/ \\param[in] orig original exponential sum function, \\f$ f(t) \\f$\n \/\/\/ \\param[in] threshold prescribed accuracy \\f$0 < \\epsilon \\ll 1\\f$\n \/\/\/\n \/\/\/ \\return An instance of ExponentialSum represents \\f$\\hat{f}(t)\\f$\n \/\/\/\n template <typename DerivedF>\n ResultType compute(const ExponentialSumBase<DerivedF>& orig,\n RealScalar threshold);\n\nprivate:\n enum\n {\n IsComplex = Eigen::NumTraits<Scalar>::IsComplex,\n };\n\n using ConeigenSolverType = SelfAdjointConeigenSolver<Scalar>;\n using RRDType =\n QuasiCauchyRRD<Scalar, QuasiCauchyRRDFunctorLogPole<Scalar>>;\n};\n\ntemplate <typename T>\ntemplate <typename DerivedF>\ntypename AAKReduction<T>::ResultType\nAAKReduction<T>::compute(const ExponentialSumBase<DerivedF>& orig,\n RealScalar threshold)\n{\n static const auto eps = Eigen::NumTraits<RealScalar>::epsilon();\n using Eigen::numext::abs;\n using Eigen::numext::real;\n\n const Index n0 = orig.size();\n std::cout << \"*** order of original function: \" << n0 << std::endl;\n\n \/\/-------------------------------------------------------------------------\n \/\/ Solve con-eigenvalue problem of the Cauchy-like matrix \\f$C\\f$ with\n \/\/ elements\n \/\/\n \/\/ C(i,j)= sqrt(c[i]) * sqrt(conj(c[j])) \/ (1 - z[i] * conj(z[j]))\n \/\/\n \/\/ where z[i] = exp(-p[i]).\n \/\/-------------------------------------------------------------------------\n \/\/\n \/\/ Rewrite the matrix element C(i,j) as\n \/\/\n \/\/ a[i] * b[j]\n \/\/ C(i,j) = ----------------------\n \/\/ exp(x[i]) - exp(y[j])\n \/\/\n \/\/ where,\n \/\/\n \/\/ a[i] = sqrt(c[i]) \/ exp(-p[i])\n \/\/ b[j] = sqrt(conj(c[j]))\n \/\/ x[i] = p[i]\n \/\/ y[j] = -conj(p[j])\n \/\/\n VectorType b(orig.weights().conjugate().sqrt());\n VectorType a(b.array().conjugate() * orig.exponents().exp());\n VectorType x(orig.exponents());\n VectorType y(-orig.exponents().conjugate());\n \/\/\n \/\/ Compute partial Cholesky decomposition of matrix C, such that,\n \/\/\n \/\/ C = (P * L) * D^2 * (P * L)^H,\n \/\/\n \/\/ where\n \/\/\n \/\/ - L: (n, m) matrix\n \/\/ - D: (m, m) real diagonal matrix\n \/\/ - P: (n, n) permutation matrix\n \/\/\n \/\/\n RRDType rrd;\n\n rrd.setThreshold(threshold * threshold * eps);\n rrd.compute(a, b, x, y);\n\n std::cout << \"*** rank after quasi-Cauchy RRD: \" << rrd.rank() << std::endl;\n\n \/\/\n \/\/ Compute con-eigendecomposition\n \/\/\n \/\/ C = X D^2 X^H = U^C S U^T,\n \/\/\n \/\/ where\n \/\/\n \/\/ - `X = P * L`: Cholesky factor (n, k)\n \/\/ - `S`: (k, k) diagonal matrix. Diagonal elements `S(i,i)` are\n \/\/ con-eigenvalues sorted in decreasing order.\n \/\/ - `U`: (n, k) matrix. k-th column hold a con-eigenvector corresponding\n \/\/ to k-th con-eigenvalue. The columns of `U` are orthogonal in the\n \/\/ sense that `U^T * U = I`.\n \/\/\n ConeigenSolverType ceig;\n ceig.compute(rrd.matrixPL(), rrd.vectorD());\n \/\/\n \/\/ Determines the order of reduced system, \\f$ M \\f$ from the Hankel\n \/\/ singular values, which are corresponding to the con-eigenvalues of matrix\n \/\/ `C`.\n \/\/\n const auto& sigma = ceig.coneigenvalues();\n auto pos = std::upper_bound(\n sigma.data(), sigma.data() + sigma.size(), threshold,\n [&](RealScalar lhs, RealScalar rhs) { return lhs >= rhs; });\n const Index n1 = static_cast<Index>(pos - sigma.data());\n std::cout << \"*** order after reduction: \" << n1 << std::endl;\n\n if (n1 == Index())\n {\n return ResultType();\n }\n\n std::cout << \" sigma = \" << sigma(n1 - 1) << std::endl;\n\n \/\/-------------------------------------------------------------------------\n \/\/ Find the `n1` roots of rational function\n \/\/\n \/\/ n1 sqrt(alpha[i]) * conj(u[i])\n \/\/ v(eta) = Sum ---------------------------\n \/\/ i=1 1 - conj(z[i]) * eta\n \/\/\n \/\/ where eta is on the unit disk.\n \/\/-------------------------------------------------------------------------\n\n \/\/\n \/\/ Barycentric form of Lagrange interpolation\n \/\/\n \/\/ VectorType& tau = x;\n \/\/ std::sort(tau.data(), tau.data() + tau.size(),\n \/\/ [&](const Scalar& lhs, const Scalar& rhs) {\n \/\/ return real(lhs) > real(rhs);\n \/\/ });\n \/\/ VectorType& s = y;\n\n ResultType ret;\n\n return ret;\n}\n\n} \/\/ namespace: mxpfit\n\n#endif \/* MXPFIT_AAK_REDUCTION_HPP *\/\n<commit_msg>Add functions for continued fraction interpolation<commit_after>\/*\n * The MIT License (MIT)\n *\n * Copyright (c) 2017 Hidekazu Ikeno\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n *\/\n\n\/\/\/\n\/\/\/ \\file aak_reduction.hpp\n\/\/\/\n\/\/\/ Sparse approximation of exponential sum using AAK theory.\n\/\/\/\n\n#ifndef MXPFIT_AAK_REDUCTION_HPP\n#define MXPFIT_AAK_REDUCTION_HPP\n\n#include <algorithm>\n\n#include <mxpfit\/exponential_sum.hpp>\n#include <mxpfit\/quasi_cauchy_rrd.hpp>\n#include <mxpfit\/self_adjoint_coneigensolver.hpp>\n\nnamespace mxpfit\n{\n\nnamespace detail\n{\n\n\/\/\/\n\/\/\/ \\internal\n\/\/\/\n\/\/\/ Create a rational function \\f$ f(x)\\f$ in the continued fraction form from a\n\/\/\/ given finite set of points \\f$ x_{i} \\f$ and their function values\n\/\/\/ \\f$y_{i}.\\f$\n\/\/\/\n\/\/\/ \\f[\n\/\/\/ f(x)=\\cfrac{a_{0}}{1+a_{1}\\cfrac{x-x_{0}}{1+a_{2}\\cfrac{x-x_{1}}{1+\\cdots}}}\n\/\/\/ \\f]\n\/\/\/\n\/\/\/ \\param[in] x set of points\n\/\/\/ \\param[in] y function values at given points `x`. All elements of `y` should\n\/\/\/ not be zero.\n\/\/\/ \\param[out] a the coefficients of continued fraction interpolation\n\/\/\/\n\ntemplate <typename VecX, typename VecY, typename VecA>\nvoid continued_fraction_interpolation_coeffs(const VecX& x, const VecY& y,\n VecA& a)\n{\n using ResultType = typename VecY::Scalar;\n using Real = typename Eigen::NumTraits<ResultType>::Real;\n using Index = Eigen::Index;\n\n static const Real tiny = Eigen::NumTraits<Real>::min();\n\n const auto a0 = y[0];\n a[0] = a0;\n\n for (Index i = 1; i < x.size(); ++i)\n {\n auto v = a0 \/ y[i];\n const auto xi = x[i];\n for (Index j = 0; j < i - 1; ++j)\n {\n v -= Real(1);\n if (v == ResultType())\n {\n v = tiny;\n }\n v = (a[j + 1] * (xi - x[j])) \/ v;\n }\n v -= Real(1);\n if (v == ResultType())\n {\n v = tiny;\n }\n a[i] = (xi - x[i - 1]) \/ v;\n }\n}\n\n\/\/\n\/\/ Compute value of the continued fraction interpolation f(x) and its derivative\n\/\/ f'(x).\n\/\/\n\/\/ Let define R_{i}(x) recursively as\n\/\/\n\/\/ R_{n-1}(x) = a_{n-2} \/ [1 + a_{n-1} (x - x_{n-1})]\n\/\/ R_{i}(x) = a_{i-1} \/ [1 + (x - x_{i}) R_{i+1}(x)] (i=n-2,n-3,...1)\n\/\/\n\/\/ then\n\/\/\n\/\/ f(x) = a_{0} \/ [1 + (x - x_{0}) R_{1}(x)].\n\/\/\n\/\/ The derivative of f(x) becomes\n\/\/\n\/\/ f'(x) = -a_{0} \/ [1 + (x - x_{0}) R_{1}(x)]^2\n\/\/ * [R_{1}(x) + (x - x_{0}) R_{1}'(x)]\n\/\/\n\/\/ The derivative of R_{i}(x) can also evaluated recursively as\n\/\/\n\/\/ R_{i}'(x) = -a_{i-1} \/ [1 + (x - x_{i}) R_{i+1}(x)]^2\n\/\/ * [R_{i+1}(x) + (x - x_{i}) R_{i+1}'(x)]\n\/\/\n\/\/ with\n\/\/\n\/\/ R_{n-1}'(x) = -a_{n-2} a_{n-1} \/ [1 + a_{n-1}(x - x_{n-1})]^2\n\/\/\ntemplate <typename VecX, typename VecA>\nvoid continued_fraction_interpolation_eval_with_derivative(\n typename VecX::Scalar x, const VecX& xi, const VecA& ai)\n{\n using ResultType = typename VecA::Scalar;\n using Real = typename Eigen::NumTraits<ResultType>::Real;\n using Index = Eigen::Index;\n\n static const Real tiny = Eigen::NumTraits<Real>::min();\n constexpr const Real one = Real(1);\n\n const auto n = ai.size();\n\n auto d = one + ai[n - 1] * (x - xi[n - 1]);\n auto f = ai[n - 2] \/ d; \/\/ R_{n-1}(x)\n auto df = -ai[n - 1] * f \/ d; \/\/ R_{n-1}'(x)\n\n for (Index k = n - 2; k > 0; --k)\n {\n d = one + (x - xi[k]) * f;\n if (d == ResultType())\n {\n d = tiny;\n }\n const auto f_pre = f;\n\n f = ai[k - 1] \/ d;\n df = -f * (f_pre + (x - xi[k]) * df) \/ d;\n }\n\n \/\/ now f = f(x), df = f'(x)\n}\n\ntemplate <typename VecX, typename VecY, typename VecA>\nstruct continued_fraction_interpolation\n{\n using ArgumentType = typename VecX::Scalar;\n using ResultType = typename VecY::Scalar;\n using Index = Eigen::Index;\n\n continued_fraction_interpolation(const VecX& x, VecY& y, VecA& a)\n : m_x(x), m_y(y), m_a(a)\n {\n assert(m_x.size() == m_y.size());\n assert(m_a.size() == m_x.size());\n compute_coeffs();\n }\n\n ResultType operator()(ArgumentType x) const;\n\n ResultType derivative(ArgumentType x) const;\n\nprivate:\n void compute_coeffs();\n const VecX& m_x;\n VecY& m_y;\n VecA& m_a;\n};\n\ntemplate <typename VecX, typename VecY, typename VecA>\nvoid continued_fraction_interpolation<VecX, VecY, VecA>::compute_coeffs()\n{\n using Real = typename Eigen::NumTraits<ResultType>::Real;\n static const Real tiny = Eigen::NumTraits<Real>::min();\n\n m_a[0] = m_y[0];\n\n for (Index i = 1; i < m_x.size(); ++i)\n {\n const auto xi = m_x[i];\n ResultType v = m_a[0] \/ m_y[i];\n for (Index j = 0; j < i - 1; ++j)\n {\n v -= Real(1);\n if (v == ResultType())\n {\n v = tiny;\n }\n v = (m_a[j + 1] * (xi - m_x[j])) \/ v;\n }\n v -= Real(1);\n if (v == ResultType())\n {\n v = tiny;\n }\n m_a[i] = (xi - m_x[i - 1]) \/ v;\n }\n}\n\ntemplate <typename VecX, typename VecY, typename VecA>\ntypename VecY::Scalar continued_fraction_interpolation<VecX, VecY, VecA>::\noperator()(ArgumentType x) const\n{\n using Real = typename Eigen::NumTraits<ResultType>::Real;\n constexpr static const Real one = Real(1);\n\n ResultType u = one;\n\n for (Index k = m_a.size() - 1; k > 0; --k)\n {\n \/\/ TODO: Need zero check?\n u = one + m_a[k] * (x - m_x[k - 1]) \/ u;\n }\n\n return m_a[0] \/ u;\n}\n\ntemplate <typename VecX, typename VecY, typename VecA>\ntypename VecY::Scalar\ncontinued_fraction_interpolation<VecX, VecY, VecA>::derivative(\n ArgumentType x) const\n{\n using Real = typename Eigen::NumTraits<ResultType>::Real;\n constexpr static const Real one = Real(1);\n\n auto& u = m_y; \/\/ overwrite m_y\n ResultType u(u.size() - 1) = one;\n\n for (Index k = m_a.size() - 1; k > 0; --k)\n {\n \/\/ TODO: Need zero check?\n u = one + m_a[k] * (x - m_x[k - 1]) \/ u;\n }\n\n return m_a[0] \/ u;\n}\n\n} \/\/ namespace: detail\n\n\/\/\/\n\/\/\/ ### AAKReduction\n\/\/\/\n\/\/\/ \\brief Find a truncated exponential sum function with smaller number of\n\/\/\/ terms using AAK theory.\n\/\/\/\n\/\/\/ \\tparam T Scalar type of exponential sum function.\n\/\/\/\n\/\/\/ For a given exponential sum function\n\/\/\/ \\f[\n\/\/\/ f(t)=\\sum_{j=1}^{N} c_{j}^{} e^{-p_{j}^{} t}, \\quad\n\/\/\/ (\\mathrm{Re}(a_{j}) > 0).\n\/\/\/ \\f]\n\/\/\/\n\/\/\/ and prescribed accuracy \\f$\\epsilon > 0,\\f$ this class calculates truncated\n\/\/\/ exponential \\f$\\tilde{f}(t)\\f$ sum such that\n\/\/\/\n\/\/\/ \\f[\n\/\/\/ \\tilde{f}(t)=\\sum_{j=1}^{M} \\tilde{c}_{j}^{}e^{-\\tilde{p}_{j}^{} t}, \\quad\n\/\/\/ \\left| f(t)-\\tilde{f}(t) \\right| < \\epsilon,\n\/\/\/ \\f]\n\/\/\/\n\/\/\/\n\/\/\/ The signal \\f$\\boldsymbol{f}=(f_{k})_{k=0}^{\\infty}\\f$ sampled on\n\/\/\/ \\f$k=0,1,\\dots\\f$ are expressed as\n\/\/\/\n\/\/\/ \\f[\n\/\/\/ f_{k}:= f(k) = \\sum_{j=1}^{N} c_{j} z_{j}^{k}\n\/\/\/ \\f]\n\/\/\/\n\/\/\/ where \\f$z_{j}=e^{-p_{j}}\\in \\mathbb{D}:=\\{z \\in \\mathbb{C}:0<|z|<1\\}.\\f$\n\/\/\/ The problem to find truncated exponential sum can be recast to find a new\n\/\/\/ signal \\f$\\tilde{\\boldsymbol{f}},\\f$ a sparse approximation of signal\n\/\/\/ \\f$\\boldsymbol{f},\\f$ such that\n\/\/\/\n\/\/\/ \\f[\n\/\/\/ \\tilde{f}_{k}=\\sum_{j=1}^{M}\\tilde{c}_{j}^{} \\tilde{z}_{j}^{k}, \\quad\n\/\/\/ \\|\\boldsymbol{f}-\\tilde{\\boldsymbol{f}}\\|<\\epsilon. \\f$\n\/\/\/ \\f]\n\/\/\/\n\/\/\/ Then, the exponents of reduced exponential sum\n\/\/\/ \\f$\\tilde{f}(t)\\f$ are obtained as \\f$\\tilde{p}_{j}=\\tilde{z}_{j}.\\f$\n\/\/\/\n\/\/\/\n\/\/\/ #### References\n\/\/\/\n\/\/\/ 1. Gerlind Plonka and Vlada Pototskaia, \"Application of the AAK theory for\n\/\/\/ sparse approximation of exponential sums\", arXiv 1609.09603v1 (2016).\n\/\/\/ [URL: https:\/\/arxiv.org\/abs\/1609.09603v1]\n\/\/\/ 2. Gregory Beylkin and Lucas Monzón, \"On approximation of functions by\n\/\/\/ exponential sums\", Appl. Comput. Harmon. Anal. **19** (2005) 17-48.\n\/\/\/ [DOI: https:\/\/doi.org\/10.1016\/j.acha.2005.01.003]\n\/\/\/ 3. T. S. Haut and G. Beylkin, \"FAST AND ACCURATE CON-EIGENVALUE ALGORITHM\n\/\/\/ FOR OPTIMAL RATIONAL APPROXIMATIONS\", SIAM J. Matrix Anal. Appl. **33**\n\/\/\/ (2012) 1101-1125.\n\/\/\/ [DOI: https:\/\/doi.org\/10.1137\/110821901]\n\/\/\/ 4. Terry Haut, Gregory Beylkin, and Lucas Monzón, \"Solving Burgers’\n\/\/\/ equation using optimal rational approximations\", Appl. Comput. Harmon.\n\/\/\/ Anal. **34** (2013) 83-95.\n\/\/\/ [DOI: https:\/\/doi.org\/10.1016\/j.acha.2012.03.004]\n\/\/\/\ntemplate <typename T>\nclass AAKReduction\n{\npublic:\n using Scalar = T;\n using RealScalar = typename Eigen::NumTraits<Scalar>::Real;\n using ComplexScalar = std::complex<RealScalar>;\n using Index = Eigen::Index;\n\n using VectorType = Eigen::Matrix<Scalar, Eigen::Dynamic, 1>;\n using MatrixType = Eigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic>;\n using ResultType = ExponentialSum<Scalar>;\n\n \/\/\/\n \/\/\/ Compute truncated exponential sum \\f$ \\hat{f}(t) \\f$\n \/\/\/\n \/\/\/ \\tparam DerivedF type of exponential sum inheriting ExponentialSumBase\n \/\/\/\n \/\/\/ \\param[in] orig original exponential sum function, \\f$ f(t) \\f$\n \/\/\/ \\param[in] threshold prescribed accuracy \\f$0 < \\epsilon \\ll 1\\f$\n \/\/\/\n \/\/\/ \\return An instance of ExponentialSum represents \\f$\\hat{f}(t)\\f$\n \/\/\/\n template <typename DerivedF>\n ResultType compute(const ExponentialSumBase<DerivedF>& orig,\n RealScalar threshold);\n\nprivate:\n enum\n {\n IsComplex = Eigen::NumTraits<Scalar>::IsComplex,\n };\n\n using ConeigenSolverType = SelfAdjointConeigenSolver<Scalar>;\n using RRDType =\n QuasiCauchyRRD<Scalar, QuasiCauchyRRDFunctorLogPole<Scalar>>;\n};\n\ntemplate <typename T>\ntemplate <typename DerivedF>\ntypename AAKReduction<T>::ResultType\nAAKReduction<T>::compute(const ExponentialSumBase<DerivedF>& orig,\n RealScalar threshold)\n{\n static const auto eps = Eigen::NumTraits<RealScalar>::epsilon();\n using Eigen::numext::abs;\n using Eigen::numext::conj;\n using Eigen::numext::real;\n\n const Index n0 = orig.size();\n std::cout << \"*** order of original function: \" << n0 << std::endl;\n\n \/\/-------------------------------------------------------------------------\n \/\/ Solve con-eigenvalue problem of the Cauchy-like matrix \\f$C\\f$ with\n \/\/ elements\n \/\/\n \/\/ C(i,j)= sqrt(c[i]) * sqrt(conj(c[j])) \/ (1 - z[i] * conj(z[j]))\n \/\/\n \/\/ where z[i] = exp(-p[i]).\n \/\/-------------------------------------------------------------------------\n \/\/\n \/\/ Rewrite the matrix element C(i,j) as\n \/\/\n \/\/ a[i] * b[j]\n \/\/ C(i,j) = ----------------------\n \/\/ exp(x[i]) - exp(y[j])\n \/\/\n \/\/ where,\n \/\/\n \/\/ a[i] = sqrt(c[i]) \/ exp(-p[i])\n \/\/ b[j] = sqrt(conj(c[j]))\n \/\/ x[i] = log(z[i]) = p[i]\n \/\/ y[j] = log(1\/conj(z[i])) = -conj(p[j])\n \/\/\n VectorType b(orig.weights().conjugate().sqrt());\n VectorType a(b.array().conjugate() * orig.exponents().exp());\n VectorType x(orig.exponents());\n VectorType y(-orig.exponents().conjugate());\n \/\/\n \/\/ Compute partial Cholesky decomposition of matrix C, such that,\n \/\/\n \/\/ C = (P * L) * D^2 * (P * L)^H,\n \/\/\n \/\/ where\n \/\/\n \/\/ - L: (n, m) matrix\n \/\/ - D: (m, m) real diagonal matrix\n \/\/ - P: (n, n) permutation matrix\n \/\/\n \/\/\n RRDType rrd;\n\n rrd.setThreshold(threshold * threshold * eps);\n rrd.compute(a, b, x, y);\n\n std::cout << \"*** rank after quasi-Cauchy RRD: \" << rrd.rank() << std::endl;\n\n \/\/\n \/\/ Compute con-eigendecomposition\n \/\/\n \/\/ C = X D^2 X^H = U^C S U^T,\n \/\/\n \/\/ where\n \/\/\n \/\/ - `X = P * L`: Cholesky factor (n, k)\n \/\/ - `S`: (k, k) diagonal matrix. Diagonal elements `S(i,i)` are\n \/\/ con-eigenvalues sorted in decreasing order.\n \/\/ - `U`: (n, k) matrix. k-th column hold a con-eigenvector corresponding\n \/\/ to k-th con-eigenvalue. The columns of `U` are orthogonal in the\n \/\/ sense that `U^T * U = I`.\n \/\/\n ConeigenSolverType ceig;\n ceig.compute(rrd.matrixPL(), rrd.vectorD());\n \/\/\n \/\/ Determines the order of reduced system, \\f$ M \\f$ from the Hankel\n \/\/ singular values, which are corresponding to the con-eigenvalues of matrix\n \/\/ `C`.\n \/\/\n const auto& sigma = ceig.coneigenvalues();\n auto pos = std::upper_bound(\n sigma.data(), sigma.data() + sigma.size(), threshold,\n [&](RealScalar lhs, RealScalar rhs) { return lhs >= rhs; });\n const Index n1 = static_cast<Index>(pos - sigma.data());\n std::cout << \"*** order after reduction: \" << n1 << std::endl;\n\n if (n1 == Index())\n {\n return ResultType();\n }\n\n std::cout << \" sigma = \" << sigma(n1 - 1) << std::endl;\n\n \/\/-------------------------------------------------------------------------\n \/\/ Find the `n1` roots of rational function\n \/\/\n \/\/ n0 sqrt(alpha[i]) * conj(u[i])\n \/\/ v(eta) = Sum ---------------------------\n \/\/ i=1 1 - conj(z[i]) * eta\n \/\/\n \/\/ where eta is on the unit disk.\n \/\/-------------------------------------------------------------------------\n\n auto vec_u = ceig.coneigenvectors().col(n1 - 1);\n \/\/\n \/\/ Approximation of v(eta) by continued fraction as\n \/\/\n \/\/ v(eta) = a1 \/ (1+a2(eta-z1)\/(1+a3(eta-z2)\/(1+...)))\n \/\/\n\n a(0) = conj(vec_u(0)) \/ b(0);\n for (Index i = 1; i < n0; ++i)\n {\n\n auto t = a(0) * b(i) \/ conj(vec_u(i));\n for (Index j = 0; j < i; ++i)\n {\n }\n a(i) = t;\n }\n\n \/\/\n \/\/ Barycentric form of Lagrange interpolation\n \/\/\n \/\/ VectorType& tau = x;\n \/\/ std::sort(tau.data(), tau.data() + tau.size(),\n \/\/ [&](const Scalar& lhs, const Scalar& rhs) {\n \/\/ return real(lhs) > real(rhs);\n \/\/ });\n \/\/ VectorType& s = y;\n\n ResultType ret;\n\n return ret;\n}\n\n} \/\/ namespace: mxpfit\n\n#endif \/* MXPFIT_AAK_REDUCTION_HPP *\/\n<|endoftext|>"} {"text":"<commit_before>\/** Compiler deficiency workarounds for libpqxx clients.\n *\n * Copyright (c) 2002-2017, Jeroen T. Vermeulen.\n *\n * See COPYING for copyright license. If you did not receive a file called\n * COPYING with this source code, please notify the distributor of this mistake,\n * or contact the author.\n *\/\n#ifndef PQXX_H_COMPILER_PUBLIC\n#define PQXX_H_COMPILER_PUBLIC\n\n\/\/ Workarounds & definitions that need to be included even in library's headers\n#include \"pqxx\/config-public-compiler.h\"\n\n\/\/ Workarounds for SUN Workshop 6\n#if defined(__SUNPRO_CC)\n#define PQXX_PRIVATE __hidden\n#endif\t\/\/ __SUNPRO_CC\n\n\n#if defined(__GNUC__) && defined(PQXX_HAVE_GCC_CONST)\n#define PQXX_CONST __attribute__ ((const))\n#else\n#define PQXX_CONST\n#endif\n\n#if defined(PQXX_HAVE_DEPRECATED)\n#define PQXX_DEPRECATED [[deprecated]]\n#elif defined(__GNUC__) && defined(PQXX_HAVE_GCC_DEPRECATED)\n#define PQXX_DEPRECATED __attribute__ ((deprecated))\n#else\n#define PQXX_DEPRECATED\n#endif\n\n#if defined(__GNUC__) && defined(PQXX_HAVE_GCC_PURE)\n#define PQXX_PURE __attribute__ ((pure))\n#else\n#define PQXX_PURE\n#endif\n\n\n\/\/ Workarounds for Windows\n#ifdef _WIN32\n\n\/* For now, export DLL symbols if _DLL is defined. This is done automatically\n * by the compiler when linking to the dynamic version of the runtime library,\n * according to \"gzh\"\n *\/\n\/\/ TODO: Define custom macro to govern how libpqxx will be linked to client\n#if !defined(PQXX_LIBEXPORT) && defined(PQXX_SHARED)\n#define PQXX_LIBEXPORT __declspec(dllimport)\n#endif\t\/\/ !PQXX_LIBEXPORT && PQXX_SHARED\n\n\n\/\/ Workarounds for Microsoft Visual C++\n#ifdef _MSC_VER\n\n\/\/ Suppress vtables on abstract classes.\n#define PQXX_NOVTABLE __declspec(novtable)\n\n\/\/ Automatically link with the appropriate libpq (static or dynamic, debug or\n\/\/ release). The default is to use the release DLL. Define PQXX_PQ_STATIC to\n\/\/ link to a static version of libpq, and _DEBUG to link to a debug version.\n\/\/ The two may be combined.\n#if defined(PQXX_AUTOLINK)\n#if defined(PQXX_PQ_STATIC)\n#ifdef _DEBUG\n#pragma comment(lib, \"libpqd\")\n#else\n#pragma comment(lib, \"libpq\")\n#endif\n#else\n#ifdef _DEBUG\n#pragma comment(lib, \"libpqddll\")\n#else\n#pragma comment(lib, \"libpqdll\")\n#endif\n#endif\n#endif\n\n\/\/ If we're not compiling libpqxx itself, automatically link with the\n\/\/ appropriate libpqxx library. To link with the libpqxx DLL, define\n\/\/ PQXX_SHARED; the default is to link with the static library. A static link\n\/\/ is the recommended practice.\n\/\/\n\/\/ The preprocessor macro PQXX_INTERNAL is used to detect whether we\n\/\/ are compiling the libpqxx library itself. When you compile the library\n\/\/ yourself using your own project file, make sure to include this macro.\n#if defined(PQXX_AUTOLINK) && !defined(PQXX_INTERNAL)\n #ifdef PQXX_SHARED\n #ifdef _DEBUG\n #pragma comment(lib, \"libpqxxD\")\n #else\n #pragma comment(lib, \"libpqxx\")\n #endif\n #else \/\/ !PQXX_SHARED\n #ifdef _DEBUG\n #pragma comment(lib, \"libpqxx_staticD\")\n #else\n #pragma comment(lib, \"libpqxx_static\")\n #endif\n #endif\n#endif\n\n#endif\t\/\/ _MSC_VER\n#endif\t\/\/ _WIN32\n\n\n#ifndef PQXX_LIBEXPORT\n#define PQXX_LIBEXPORT\n#endif\n\n#ifndef PQXX_PRIVATE\n#define PQXX_PRIVATE\n#endif\n\n#ifndef PQXX_NOVTABLE\n#define PQXX_NOVTABLE\n#endif\n\n#endif\n<commit_msg>Document some macros.<commit_after>\/** Compiler deficiency workarounds for libpqxx clients.\n *\n * Copyright (c) 2002-2017, Jeroen T. Vermeulen.\n *\n * See COPYING for copyright license. If you did not receive a file called\n * COPYING with this source code, please notify the distributor of this mistake,\n * or contact the author.\n *\/\n#ifndef PQXX_H_COMPILER_PUBLIC\n#define PQXX_H_COMPILER_PUBLIC\n\n\/\/ Workarounds & definitions that need to be included even in library's headers\n#include \"pqxx\/config-public-compiler.h\"\n\n\/\/ Workarounds for SUN Workshop 6\n#if defined(__SUNPRO_CC)\n#define PQXX_PRIVATE __hidden\n#endif\t\/\/ __SUNPRO_CC\n\n\n#if defined(__GNUC__) && defined(PQXX_HAVE_GCC_CONST)\n\/\/\/ Declare function without effects and without reading anything but its args.\n#define PQXX_CONST __attribute__ ((const))\n#else\n#define PQXX_CONST\n#endif\n\n#if defined(PQXX_HAVE_DEPRECATED)\n\/\/\/ Mark an item as deprecated.\n#define PQXX_DEPRECATED [[deprecated]]\n#elif defined(__GNUC__) && defined(PQXX_HAVE_GCC_DEPRECATED)\n#define PQXX_DEPRECATED __attribute__ ((deprecated))\n#else\n#define PQXX_DEPRECATED\n#endif\n\n#if defined(__GNUC__) && defined(PQXX_HAVE_GCC_PURE)\n\/\/\/ Declare function \"pure\": no side effects, only reads globals and its args.\n#define PQXX_PURE __attribute__ ((pure))\n#else\n#define PQXX_PURE\n#endif\n\n\n\/\/ Workarounds for Windows\n#ifdef _WIN32\n\n\/* For now, export DLL symbols if _DLL is defined. This is done automatically\n * by the compiler when linking to the dynamic version of the runtime library,\n * according to \"gzh\"\n *\/\n\/\/ TODO: Define custom macro to govern how libpqxx will be linked to client\n#if !defined(PQXX_LIBEXPORT) && defined(PQXX_SHARED)\n#define PQXX_LIBEXPORT __declspec(dllimport)\n#endif\t\/\/ !PQXX_LIBEXPORT && PQXX_SHARED\n\n\n\/\/ Workarounds for Microsoft Visual C++\n#ifdef _MSC_VER\n\n\/\/ Suppress vtables on abstract classes.\n#define PQXX_NOVTABLE __declspec(novtable)\n\n\/\/ Automatically link with the appropriate libpq (static or dynamic, debug or\n\/\/ release). The default is to use the release DLL. Define PQXX_PQ_STATIC to\n\/\/ link to a static version of libpq, and _DEBUG to link to a debug version.\n\/\/ The two may be combined.\n#if defined(PQXX_AUTOLINK)\n#if defined(PQXX_PQ_STATIC)\n#ifdef _DEBUG\n#pragma comment(lib, \"libpqd\")\n#else\n#pragma comment(lib, \"libpq\")\n#endif\n#else\n#ifdef _DEBUG\n#pragma comment(lib, \"libpqddll\")\n#else\n#pragma comment(lib, \"libpqdll\")\n#endif\n#endif\n#endif\n\n\/\/ If we're not compiling libpqxx itself, automatically link with the\n\/\/ appropriate libpqxx library. To link with the libpqxx DLL, define\n\/\/ PQXX_SHARED; the default is to link with the static library. A static link\n\/\/ is the recommended practice.\n\/\/\n\/\/ The preprocessor macro PQXX_INTERNAL is used to detect whether we\n\/\/ are compiling the libpqxx library itself. When you compile the library\n\/\/ yourself using your own project file, make sure to include this macro.\n#if defined(PQXX_AUTOLINK) && !defined(PQXX_INTERNAL)\n #ifdef PQXX_SHARED\n #ifdef _DEBUG\n #pragma comment(lib, \"libpqxxD\")\n #else\n #pragma comment(lib, \"libpqxx\")\n #endif\n #else \/\/ !PQXX_SHARED\n #ifdef _DEBUG\n #pragma comment(lib, \"libpqxx_staticD\")\n #else\n #pragma comment(lib, \"libpqxx_static\")\n #endif\n #endif\n#endif\n\n#endif\t\/\/ _MSC_VER\n#endif\t\/\/ _WIN32\n\n\n#ifndef PQXX_LIBEXPORT\n#define PQXX_LIBEXPORT\n#endif\n\n#ifndef PQXX_PRIVATE\n#define PQXX_PRIVATE\n#endif\n\n#ifndef PQXX_NOVTABLE\n#define PQXX_NOVTABLE\n#endif\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>#ifndef IZENELIB_UTIL_SKETCH_FMSKETCH_H_\n#define IZENELIB_UTIL_SKETCH_FMSKETCH_H_\n\n#include \"ICardinality.hpp\"\n#include \"Level2Sketch.hpp\"\n#include <util\/hashFunction.h>\n#include <common\/type_defs.h>\n#include <vector>\n#include <stdint.h>\n#include <math.h>\n\n#define BITSET_SIZE 64\n\nNS_IZENELIB_UTIL_BEGIN\n\ntemplate <typename ElemType>\nclass FMSketch : public ICardinality<ElemType>\n{\npublic:\n typedef std::vector<std::bitset<BITSET_SIZE> > FMSketchT;\n typedef ElemType DataTypeT;\n typedef ICardinality<DataTypeT> BaseType;\n typedef FMSketch<DataTypeT> ThisType;\n typedef Level2Sketch<DataTypeT> Level2SketchT;\n\n FMSketch(uint64_t seed, int k)\n : seed_(seed), \n fm_k_((size_t)k)\n {\n sketch_.resize(fm_k_);\n level2sketches_.resize(fm_k_);\n for(size_t i = 0; i < (size_t)fm_k_; ++i)\n level2sketches_[i].resize(BITSET_SIZE);\n }\n\n size_t size() const\n {\n return sketch_.size();\n }\n\n void load(std::istream& is)\n {\n is.read((char*)&seed_, sizeof(seed_));\n is.read((char*)&fm_k_, sizeof(fm_k_));\n FMSketchT().swap(sketch_);\n sketch_.reserve(fm_k_);\n level2sketches_.resize(fm_k_);\n for(size_t i = 0; i < fm_k_; ++i)\n {\n char data[BITSET_SIZE + 1];\n is.read((char*)&data, BITSET_SIZE);\n data[BITSET_SIZE] = '\\0';\n sketch_.push_back(std::bitset<BITSET_SIZE>(std::string(data)));\n level2sketches_[i].load(is);\n }\n }\n\n void save(std::ostream& os) const\n {\n os.write((const char*)&seed_, sizeof(seed_));\n os.write((const char*)&fm_k_, sizeof(fm_k_));\n for(size_t i = 0; i < fm_k_; ++i)\n {\n os.write((const char*)sketch_[i].to_string().data(), BITSET_SIZE);\n level2sketches_[i].save(os);\n }\n }\n\n void updateSketch(const DataTypeT& data)\n {\n for(size_t i = 0; i < fm_k_; ++i)\n {\n uint64_t v = izenelib::util::MurmurHash64A(&data,\n sizeof(DataTypeT), seed_ + i);\n uint8_t lsb = LSB(v);\n sketch_[i].set(lsb);\n level2sketches_[i].updateBucket(lsb, data);\n }\n }\n\n size_t setUnionEstimator(const ThisType& src) const\n {\n double f = (1 + E) * fm_k_ \/ 8;\n size_t index = 0;\n size_t count = 0;\n while(index < BITSET_SIZE)\n {\n count = 0;\n for(size_t i = 0; i < fm_k_; ++i)\n {\n if(!level2sketches_[i].emptyBucket(index) ||\n !src.level2sketches_[i].emptyBucket(index))\n {\n count++;\n }\n }\n if(count <= f)\n break;\n else\n index++;\n }\n double p = count\/fm_k_;\n double R = pow(2, index + 1);\n return log(1 - p)\/log(1 - 1\/R);\n }\n\n size_t setIntersectEstimator(const ThisType& src) const\n {\n if(src.size() == 0 || size() == 0)\n return 0;\n\n assert(src.size() == size());\n size_t sum = 0;\n size_t count = 0;\n size_t union_card = setUnionEstimator(src);\n for(size_t i = 0; i < fm_k_; ++i)\n {\n size_t index = std::ceil(std::log(2*union_card\/(1 - E)));\n \/\/size_t index = std::ceil(std::log(2*union_card\/(level2sketches_.size()*(1 - E)*(1 - E))));\n if(index > BITSET_SIZE)\n continue;\n int atomic_estimate = level2sketches_[i].atomicIntersectEstimator(index, src.level2sketches_[i]);\n if(atomic_estimate != -1)\n {\n sum += atomic_estimate;\n count++;\n }\n }\n if(count == 0)\n return 0;\n return sum*union_card\/count;\n }\n\n size_t intersectCard(const BaseType* src) const\n {\n const ThisType* fm_src = dynamic_cast<const ThisType*>(src);\n if(fm_src == NULL)\n {\n throw -1;\n }\n\n return setIntersectEstimator(*fm_src);\n }\n\n size_t getCardinate() const\n {\n if(sketch_.empty())\n return 0;\n int sum = 0;\n for(size_t i = 0; i < fm_k_; ++i)\n {\n int leftmost_zero = BITSET_SIZE;\n for(int m = BITSET_SIZE - 1; m >= 0; --m)\n {\n if(!sketch_[i].test(m))\n leftmost_zero = m;\n }\n sum += leftmost_zero;\n }\n return 1.2928 * pow(2, sum\/fm_k_);\n }\n\n void unionSketch(const BaseType* src)\n {\n if(src->size() == 0)\n return;\n\n const ThisType* fm_src = dynamic_cast<const ThisType*>(src);\n if(fm_src == NULL)\n {\n throw -1;\n }\n if(sketch_.empty())\n {\n *this = *fm_src;\n return;\n }\n assert(src->size() == size());\n const FMSketchT& tmp_src = fm_src->sketch_;\n for(size_t i = 0; i < sketch_.size(); ++i)\n {\n sketch_[i] |= tmp_src[i];\n level2sketches_[i].unionLevel2Sketch(fm_src->level2sketches_[i]);\n }\n }\n\n static size_t setUnionEstimator(const std::vector<ThisType>& sketches)\n {\n if(sketches.empty())\n return 0;\n size_t fm_k = sketches[0].fm_k_;\n double f = (1 + E) * fm_k \/ 8;\n size_t index = 0;\n std::vector<Level2SketchT> tmp_level2sketches;\n tmp_level2sketches.resize(sketches.size());\n size_t count = 0;\n while(index < BITSET_SIZE)\n {\n count = 0;\n for(size_t i = 0; i < fm_k; ++i)\n {\n for(size_t j = 0; j < sketches.size(); ++j)\n {\n tmp_level2sketches[j] = sketches[j].level2sketches_[i];\n }\n if(atomicUnionBucketEstimator(index, tmp_level2sketches))\n {\n count++;\n }\n }\n if(count <= f)\n break;\n else\n index++;\n }\n double p = count\/fm_k;\n double R = pow(2, index + 1);\n return log(1 - p)\/log(1 - 1\/R);\n }\n\n static size_t setUnionWithIntersectEstimator(const std::vector<ThisType>& union_sketch,\n const std::vector<ThisType>& filter_sketch) \n {\n if(union_sketch.empty() || filter_sketch.empty())\n return 0;\n size_t sum = 0;\n size_t count = 0;\n size_t fm_k = union_sketch[0].fm_k_;\n std::vector<ThisType> all_sketches = union_sketch;\n all_sketches.insert(all_sketches.end(), filter_sketch.begin(), filter_sketch.end());\n size_t union_card = setUnionEstimator(all_sketches);\n\n std::vector<Level2SketchT> tmp_level2sketches;\n tmp_level2sketches.resize(union_sketch.size());\n std::vector<Level2SketchT> tmpfilter_level2sketches;\n tmpfilter_level2sketches.resize(filter_sketch.size());\n\n for(size_t i = 0; i < fm_k; ++i)\n {\n size_t index = std::ceil(std::log(2*union_card\/(1 - E)));\n \/\/size_t index = std::ceil(std::log(2*union_card\/(level2sketches_.size()*(1 - E)*(1 - E))));\n if(index > BITSET_SIZE)\n continue;\n for(size_t j = 0; j < union_sketch.size(); ++j)\n {\n tmp_level2sketches[j] = union_sketch[j].level2sketches_[i];\n }\n for(size_t j = 0; j < filter_sketch.size(); ++j)\n {\n tmpfilter_level2sketches[j] = filter_sketch[j].level2sketches_[i];\n }\n int atomic_estimate = atomicUnionWithIntersectBucketEstimator(index, tmp_level2sketches,\n tmpfilter_level2sketches);\n if(atomic_estimate != -1)\n {\n sum += atomic_estimate;\n count++;\n }\n }\n if(count == 0)\n return 0;\n return sum*union_card\/count;\n }\n\n\nprivate:\n inline uint8_t LSB(uint64_t v)\n {\n for(uint8_t i = 0; i < 64; ++i)\n {\n if((v & ((uint64_t)1 << i)) != 0)\n return i;\n }\n return 63;\n }\n\n \/\/ the bits used for bucket index.\n uint64_t seed_;\n size_t fm_k_;\n FMSketchT sketch_;\n std::vector<Level2SketchT> level2sketches_;\n static const double E = 0.618;\n};\n\nNS_IZENELIB_UTIL_END\n\n#endif\n<commit_msg>use the time-efficient synopse for fmsketch<commit_after>#ifndef IZENELIB_UTIL_SKETCH_FMSKETCH_H_\n#define IZENELIB_UTIL_SKETCH_FMSKETCH_H_\n\n#include \"ICardinality.hpp\"\n#include \"Level2Sketch.hpp\"\n#include <util\/hashFunction.h>\n#include <common\/type_defs.h>\n#include <vector>\n#include <stdint.h>\n#include <math.h>\n\n#define BITSET_SIZE 64\n\nNS_IZENELIB_UTIL_BEGIN\n\ntemplate <typename ElemType>\nclass FMSketch : public ICardinality<ElemType>\n{\npublic:\n typedef std::vector<std::bitset<BITSET_SIZE> > FMSketchT;\n typedef ElemType DataTypeT;\n typedef ICardinality<DataTypeT> BaseType;\n typedef FMSketch<DataTypeT> ThisType;\n typedef Level2Sketch<DataTypeT> Level2SketchT;\n\n FMSketch(uint64_t seed, int k)\n : seed_(seed), \n fm_k_((size_t)k)\n {\n sketch_.resize(fm_k_);\n level2sketches_.resize(fm_k_);\n for(size_t i = 0; i < (size_t)fm_k_; ++i)\n level2sketches_[i].resize(BITSET_SIZE);\n }\n\n size_t size() const\n {\n return sketch_.size();\n }\n\n void load(std::istream& is)\n {\n is.read((char*)&seed_, sizeof(seed_));\n is.read((char*)&fm_k_, sizeof(fm_k_));\n FMSketchT().swap(sketch_);\n sketch_.reserve(fm_k_);\n level2sketches_.resize(fm_k_);\n for(size_t i = 0; i < fm_k_; ++i)\n {\n char data[BITSET_SIZE + 1];\n is.read((char*)&data, BITSET_SIZE);\n data[BITSET_SIZE] = '\\0';\n sketch_.push_back(std::bitset<BITSET_SIZE>(std::string(data)));\n level2sketches_[i].load(is);\n }\n }\n\n void save(std::ostream& os) const\n {\n os.write((const char*)&seed_, sizeof(seed_));\n os.write((const char*)&fm_k_, sizeof(fm_k_));\n for(size_t i = 0; i < fm_k_; ++i)\n {\n os.write((const char*)sketch_[i].to_string().data(), BITSET_SIZE);\n level2sketches_[i].save(os);\n }\n }\n\n void updateSketch(const DataTypeT& data)\n {\n uint64_t v = izenelib::util::MurmurHash64A(&data,\n sizeof(DataTypeT), seed_);\n uint8_t lsb = LSB(v\/fm_k_);\n sketch_[v % fm_k_].set(lsb);\n level2sketches_[v % fm_k_].updateBucket(lsb, data);\n }\n\n size_t setUnionEstimator(const ThisType& src) const\n {\n double f = (1 + E) * (double)fm_k_ \/ 8;\n size_t index = 0;\n size_t count = 0;\n while(index < BITSET_SIZE)\n {\n count = 0;\n for(size_t i = 0; i < fm_k_; ++i)\n {\n if(!level2sketches_[i].emptyBucket(index) ||\n !src.level2sketches_[i].emptyBucket(index))\n {\n count++;\n }\n }\n if(count <= f)\n break;\n else\n index++;\n }\n double p = count\/(double)fm_k_;\n double R = pow(2, index + 1);\n return log(1 - p)\/log(1 - 1\/R) * fm_k_;\n }\n\n size_t setIntersectEstimator(const ThisType& src) const\n {\n if(src.size() == 0 || size() == 0)\n return 0;\n\n assert(src.size() == size());\n size_t sum = 0;\n size_t count = 0;\n size_t union_card = setUnionEstimator(src);\n for(size_t i = 0; i < fm_k_; ++i)\n {\n \/\/size_t index = std::ceil(std::log(2*union_card\/(1 - E)));\n size_t index = std::ceil(std::log(2 * (double)union_card \/ (fm_k_ * (1 - E) * (1 - E))));\n if(index > BITSET_SIZE)\n continue;\n int atomic_estimate = level2sketches_[i].atomicIntersectEstimator(index, src.level2sketches_[i]);\n if(atomic_estimate != -1)\n {\n sum += atomic_estimate;\n count++;\n }\n }\n if(count == 0)\n return 0;\n return sum*union_card\/count;\n }\n\n size_t intersectCard(const BaseType* src) const\n {\n const ThisType* fm_src = dynamic_cast<const ThisType*>(src);\n if(fm_src == NULL)\n {\n throw -1;\n }\n\n return setIntersectEstimator(*fm_src);\n }\n\n size_t getCardinate() const\n {\n if(sketch_.empty())\n return 0;\n int sum = 0;\n for(size_t i = 0; i < fm_k_; ++i)\n {\n int leftmost_zero = BITSET_SIZE;\n for(int m = BITSET_SIZE - 1; m >= 0; --m)\n {\n if(!sketch_[i].test(m))\n leftmost_zero = m;\n }\n sum += leftmost_zero;\n }\n return 1.2928 * pow(2, sum\/(double)fm_k_) * fm_k_;\n }\n\n void unionSketch(const BaseType* src)\n {\n if(src->size() == 0)\n return;\n\n const ThisType* fm_src = dynamic_cast<const ThisType*>(src);\n if(fm_src == NULL)\n {\n throw -1;\n }\n if(sketch_.empty())\n {\n *this = *fm_src;\n return;\n }\n assert(src->size() == size());\n const FMSketchT& tmp_src = fm_src->sketch_;\n for(size_t i = 0; i < sketch_.size(); ++i)\n {\n sketch_[i] |= tmp_src[i];\n level2sketches_[i].unionLevel2Sketch(fm_src->level2sketches_[i]);\n }\n }\n\n static size_t setUnionEstimator(const std::vector<ThisType>& sketches)\n {\n if(sketches.empty())\n return 0;\n size_t fm_k = sketches[0].fm_k_;\n double f = (1 + E) * (double)fm_k \/ 8;\n size_t index = 0;\n std::vector<Level2SketchT> tmp_level2sketches;\n tmp_level2sketches.resize(sketches.size());\n size_t count = 0;\n while(index < BITSET_SIZE)\n {\n count = 0;\n for(size_t i = 0; i < fm_k; ++i)\n {\n for(size_t j = 0; j < sketches.size(); ++j)\n {\n tmp_level2sketches[j] = sketches[j].level2sketches_[i];\n }\n if(atomicUnionBucketEstimator(index, tmp_level2sketches))\n {\n count++;\n }\n }\n if(count <= f)\n break;\n else\n index++;\n }\n double p = count\/(double)fm_k;\n double R = pow(2, index + 1);\n return log(1 - p)\/log(1 - 1\/R) * fm_k;\n }\n\n static size_t setUnionWithIntersectEstimator(const std::vector<ThisType>& union_sketch,\n const std::vector<ThisType>& filter_sketch) \n {\n if(union_sketch.empty() || filter_sketch.empty())\n return 0;\n size_t sum = 0;\n size_t count = 0;\n size_t fm_k = union_sketch[0].fm_k_;\n std::vector<ThisType> all_sketches = union_sketch;\n all_sketches.insert(all_sketches.end(), filter_sketch.begin(), filter_sketch.end());\n size_t union_card = setUnionEstimator(all_sketches);\n\n std::vector<Level2SketchT> tmp_level2sketches;\n tmp_level2sketches.resize(union_sketch.size());\n std::vector<Level2SketchT> tmpfilter_level2sketches;\n tmpfilter_level2sketches.resize(filter_sketch.size());\n\n for(size_t i = 0; i < fm_k; ++i)\n {\n \/\/size_t index = std::ceil(std::log(2*union_card\/(1 - E)));\n size_t index = std::ceil(std::log(2 * (double)union_card \/ ( fm_k * (1 - E) * (1 - E) )));\n if(index > BITSET_SIZE)\n continue;\n for(size_t j = 0; j < union_sketch.size(); ++j)\n {\n tmp_level2sketches[j] = union_sketch[j].level2sketches_[i];\n }\n for(size_t j = 0; j < filter_sketch.size(); ++j)\n {\n tmpfilter_level2sketches[j] = filter_sketch[j].level2sketches_[i];\n }\n int atomic_estimate = atomicUnionWithIntersectBucketEstimator(index, tmp_level2sketches,\n tmpfilter_level2sketches);\n if(atomic_estimate != -1)\n {\n sum += atomic_estimate;\n count++;\n }\n }\n if(count == 0)\n return 0;\n return sum*union_card\/count;\n }\n\n\nprivate:\n inline uint8_t LSB(uint64_t v)\n {\n for(uint8_t i = 0; i < 64; ++i)\n {\n if((v & ((uint64_t)1 << i)) != 0)\n return i;\n }\n return 63;\n }\n\n \/\/ the bits used for bucket index.\n uint64_t seed_;\n size_t fm_k_;\n FMSketchT sketch_;\n std::vector<Level2SketchT> level2sketches_;\n static const double E = 0.618;\n};\n\nNS_IZENELIB_UTIL_END\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (C) 2004-2016 ZNC, see the NOTICE file for details.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include <znc\/Modules.h>\n#include <znc\/User.h>\n\nclass CNickServ : public CModule {\n void DoNickCommand(const CString& sCmd, const CString& sNick) {\n MCString msValues;\n msValues[\"nickname\"] = sNick;\n msValues[\"password\"] = GetNV(\"Password\");\n PutIRC(CString::NamedFormat(GetNV(sCmd), msValues));\n }\n\n public:\n void SetCommand(const CString& sLine) {\n SetNV(\"Password\", sLine.Token(1, true));\n PutModule(\"Password set\");\n }\n\n void ClearCommand(const CString& sLine) { DelNV(\"Password\"); }\n\n void SetNSNameCommand(const CString& sLine) {\n SetNV(\"NickServName\", sLine.Token(1, true));\n PutModule(\"NickServ name set\");\n }\n\n void ClearNSNameCommand(const CString& sLine) { DelNV(\"NickServName\"); }\n\n void ViewCommandsCommand(const CString& sLine) {\n PutModule(\"IDENTIFY \" + GetNV(\"IdentifyCmd\"));\n }\n\n void SetCommandCommand(const CString& sLine) {\n CString sCmd = sLine.Token(1);\n CString sNewCmd = sLine.Token(2, true);\n if (sCmd.Equals(\"IDENTIFY\")) {\n SetNV(\"IdentifyCmd\", sNewCmd);\n } else {\n PutModule(\"No such editable command. See ViewCommands for list.\");\n return;\n }\n PutModule(\"Ok\");\n }\n\n MODCONSTRUCTOR(CNickServ) {\n AddHelpCommand();\n AddCommand(\"Set\",\n static_cast<CModCommand::ModCmdFunc>(&CNickServ::SetCommand),\n \"password\");\n AddCommand(\"Clear\", static_cast<CModCommand::ModCmdFunc>(\n &CNickServ::ClearCommand),\n \"\", \"Clear your nickserv password\");\n AddCommand(\"SetNSName\", static_cast<CModCommand::ModCmdFunc>(\n &CNickServ::SetNSNameCommand),\n \"nickname\",\n \"Set NickServ name (Useful on networks like EpiKnet, where \"\n \"NickServ is named Themis)\");\n AddCommand(\"ClearNSName\", static_cast<CModCommand::ModCmdFunc>(\n &CNickServ::ClearNSNameCommand),\n \"\", \"Reset NickServ name to default (NickServ)\");\n AddCommand(\"ViewCommands\", static_cast<CModCommand::ModCmdFunc>(\n &CNickServ::ViewCommandsCommand),\n \"\",\n \"Show patterns for lines, which are being sent to NickServ\");\n AddCommand(\"SetCommand\", static_cast<CModCommand::ModCmdFunc>(\n &CNickServ::SetCommandCommand),\n \"cmd new-pattern\", \"Set pattern for commands\");\n }\n\n ~CNickServ() override {}\n\n bool OnLoad(const CString& sArgs, CString& sMessage) override {\n if (!sArgs.empty() && sArgs != \"<hidden>\") {\n SetNV(\"Password\", sArgs);\n SetArgs(\"<hidden>\");\n }\n\n if (GetNV(\"IdentifyCmd\").empty()) {\n SetNV(\"IdentifyCmd\", \"NICKSERV IDENTIFY {password}\");\n }\n\n return true;\n }\n\n void HandleMessage(CNick& Nick, const CString& sMessage) {\n CString sNickServName = (!GetNV(\"NickServName\").empty())\n ? GetNV(\"NickServName\")\n : \"NickServ\";\n if (!GetNV(\"Password\").empty() && Nick.NickEquals(sNickServName) &&\n (sMessage.find(\"msg\") != CString::npos ||\n sMessage.find(\"authenticate\") != CString::npos ||\n sMessage.find(\"choose a different nickname\") != CString::npos ||\n sMessage.find(\"please choose a different nick\") != CString::npos ||\n sMessage.find(\"If this is your nick, identify yourself with\") !=\n CString::npos ||\n sMessage.find(\"If this is your nick, type\") != CString::npos ||\n sMessage.find(\"This is a registered nickname, please identify\") !=\n CString::npos ||\n sMessage.StripControls_n().find(\n \"type \/NickServ IDENTIFY password\") != CString::npos ||\n sMessage.StripControls_n().find(\n \"type \/msg NickServ IDENTIFY password\") != CString::npos) &&\n sMessage.AsUpper().find(\"IDENTIFY\") != CString::npos &&\n sMessage.find(\"help\") == CString::npos) {\n MCString msValues;\n msValues[\"password\"] = GetNV(\"Password\");\n PutIRC(CString::NamedFormat(GetNV(\"IdentifyCmd\"), msValues));\n }\n }\n\n EModRet OnPrivMsg(CNick& Nick, CString& sMessage) override {\n HandleMessage(Nick, sMessage);\n return CONTINUE;\n }\n\n EModRet OnPrivNotice(CNick& Nick, CString& sMessage) override {\n HandleMessage(Nick, sMessage);\n return CONTINUE;\n }\n};\n\ntemplate <>\nvoid TModInfo<CNickServ>(CModInfo& Info) {\n Info.SetWikiPage(\"nickserv\");\n Info.SetHasArgs(true);\n Info.SetArgsHelpText(\"Please enter your nickserv password.\");\n}\n\nNETWORKMODULEDEFS(CNickServ, \"Auths you with NickServ\")\n<commit_msg>nickserv: support messages from X3 services<commit_after>\/*\n * Copyright (C) 2004-2016 ZNC, see the NOTICE file for details.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include <znc\/Modules.h>\n#include <znc\/User.h>\n\nclass CNickServ : public CModule {\n void DoNickCommand(const CString& sCmd, const CString& sNick) {\n MCString msValues;\n msValues[\"nickname\"] = sNick;\n msValues[\"password\"] = GetNV(\"Password\");\n PutIRC(CString::NamedFormat(GetNV(sCmd), msValues));\n }\n\n public:\n void SetCommand(const CString& sLine) {\n SetNV(\"Password\", sLine.Token(1, true));\n PutModule(\"Password set\");\n }\n\n void ClearCommand(const CString& sLine) { DelNV(\"Password\"); }\n\n void SetNSNameCommand(const CString& sLine) {\n SetNV(\"NickServName\", sLine.Token(1, true));\n PutModule(\"NickServ name set\");\n }\n\n void ClearNSNameCommand(const CString& sLine) { DelNV(\"NickServName\"); }\n\n void ViewCommandsCommand(const CString& sLine) {\n PutModule(\"IDENTIFY \" + GetNV(\"IdentifyCmd\"));\n }\n\n void SetCommandCommand(const CString& sLine) {\n CString sCmd = sLine.Token(1);\n CString sNewCmd = sLine.Token(2, true);\n if (sCmd.Equals(\"IDENTIFY\")) {\n SetNV(\"IdentifyCmd\", sNewCmd);\n } else {\n PutModule(\"No such editable command. See ViewCommands for list.\");\n return;\n }\n PutModule(\"Ok\");\n }\n\n MODCONSTRUCTOR(CNickServ) {\n AddHelpCommand();\n AddCommand(\"Set\",\n static_cast<CModCommand::ModCmdFunc>(&CNickServ::SetCommand),\n \"password\");\n AddCommand(\"Clear\", static_cast<CModCommand::ModCmdFunc>(\n &CNickServ::ClearCommand),\n \"\", \"Clear your nickserv password\");\n AddCommand(\"SetNSName\", static_cast<CModCommand::ModCmdFunc>(\n &CNickServ::SetNSNameCommand),\n \"nickname\",\n \"Set NickServ name (Useful on networks like EpiKnet, where \"\n \"NickServ is named Themis)\");\n AddCommand(\"ClearNSName\", static_cast<CModCommand::ModCmdFunc>(\n &CNickServ::ClearNSNameCommand),\n \"\", \"Reset NickServ name to default (NickServ)\");\n AddCommand(\"ViewCommands\", static_cast<CModCommand::ModCmdFunc>(\n &CNickServ::ViewCommandsCommand),\n \"\",\n \"Show patterns for lines, which are being sent to NickServ\");\n AddCommand(\"SetCommand\", static_cast<CModCommand::ModCmdFunc>(\n &CNickServ::SetCommandCommand),\n \"cmd new-pattern\", \"Set pattern for commands\");\n }\n\n ~CNickServ() override {}\n\n bool OnLoad(const CString& sArgs, CString& sMessage) override {\n if (!sArgs.empty() && sArgs != \"<hidden>\") {\n SetNV(\"Password\", sArgs);\n SetArgs(\"<hidden>\");\n }\n\n if (GetNV(\"IdentifyCmd\").empty()) {\n SetNV(\"IdentifyCmd\", \"NICKSERV IDENTIFY {password}\");\n }\n\n return true;\n }\n\n void HandleMessage(CNick& Nick, const CString& sMessage) {\n CString sNickServName = (!GetNV(\"NickServName\").empty())\n ? GetNV(\"NickServName\")\n : \"NickServ\";\n if (!GetNV(\"Password\").empty() && Nick.NickEquals(sNickServName) &&\n (sMessage.find(\"msg\") != CString::npos ||\n sMessage.find(\"authenticate\") != CString::npos ||\n sMessage.find(\"choose a different nickname\") != CString::npos ||\n sMessage.find(\"please choose a different nick\") != CString::npos ||\n sMessage.find(\"If this is your nick, identify yourself with\") !=\n CString::npos ||\n sMessage.find(\"If this is your nick, type\") != CString::npos ||\n sMessage.find(\"This is a registered nickname, please identify\") !=\n CString::npos ||\n sMessage.find(\"is a registered nick - you must auth to account\") !=\n CString::npos ||\n sMessage.StripControls_n().find(\n \"type \/NickServ IDENTIFY password\") != CString::npos ||\n sMessage.StripControls_n().find(\n \"type \/msg NickServ IDENTIFY password\") != CString::npos) &&\n sMessage.AsUpper().find(\"IDENTIFY\") != CString::npos &&\n sMessage.find(\"help\") == CString::npos) {\n MCString msValues;\n msValues[\"password\"] = GetNV(\"Password\");\n PutIRC(CString::NamedFormat(GetNV(\"IdentifyCmd\"), msValues));\n }\n }\n\n EModRet OnPrivMsg(CNick& Nick, CString& sMessage) override {\n HandleMessage(Nick, sMessage);\n return CONTINUE;\n }\n\n EModRet OnPrivNotice(CNick& Nick, CString& sMessage) override {\n HandleMessage(Nick, sMessage);\n return CONTINUE;\n }\n};\n\ntemplate <>\nvoid TModInfo<CNickServ>(CModInfo& Info) {\n Info.SetWikiPage(\"nickserv\");\n Info.SetHasArgs(true);\n Info.SetArgsHelpText(\"Please enter your nickserv password.\");\n}\n\nNETWORKMODULEDEFS(CNickServ, \"Auths you with NickServ\")\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2015-2020 Elviss Strazdins. All rights reserved.\n\n#include <cstdlib>\n#include <system_error>\n\n#pragma push_macro(\"WIN32_LEAN_AND_MEAN\")\n#pragma push_macro(\"NOMINMAX\")\n#ifndef WIN32_LEAN_AND_MEAN\n# define WIN32_LEAN_AND_MEAN\n#endif\n#ifndef NOMINMAX\n# define NOMINMAX\n#endif\n#include <Windows.h>\n#include <shellapi.h>\n#pragma pop_macro(\"WIN32_LEAN_AND_MEAN\")\n#pragma pop_macro(\"NOMINMAX\")\n\n#include \"EngineWin.hpp\"\n#include \"NativeWindowWin.hpp\"\n#include \"ShellExecuteErrorCategory.hpp\"\n#include \"..\/..\/input\/windows\/InputSystemWin.hpp\"\n#include \"..\/..\/utils\/Log.hpp\"\n\nnamespace ouzel::core::windows\n{\n namespace\n {\n std::vector<std::string> parseArgs(int argc, LPWSTR* argv)\n {\n std::vector<std::string> result;\n if (argv)\n for (int i = 0; i < argc; ++i)\n {\n const int bufferSize = WideCharToMultiByte(CP_UTF8, 0, argv[i], -1, nullptr, 0, nullptr, nullptr);\n if (bufferSize == 0)\n throw std::system_error(GetLastError(), std::system_category(), \"Failed to convert wide char to UTF-8\");\n\n std::vector<char> buffer(bufferSize);\n if (WideCharToMultiByte(CP_UTF8, 0, argv[i], -1, buffer.data(), bufferSize, nullptr, nullptr) == 0)\n throw std::system_error(GetLastError(), std::system_category(), \"Failed to convert wide char to UTF-8\");\n\n result.push_back(buffer.data());\n }\n\n return result;\n }\n\n const ShellExecuteErrorCategory shellExecuteErrorCategory{};\n }\n\n Engine::Engine(int argc, LPWSTR* argv):\n core::Engine(parseArgs(argc, argv))\n {\n }\n\n static void translateMessage(HWND window, const std::set<HACCEL>& accelerators, MSG& message)\n {\n bool translate = true;\n\n for (HACCEL accelerator : accelerators)\n {\n if (TranslateAccelerator(window, accelerator, &message))\n translate = false;\n }\n\n if (translate)\n {\n TranslateMessage(&message);\n DispatchMessage(&message);\n }\n }\n\n void Engine::run()\n {\n init();\n start();\n\n auto inputWin = static_cast<input::windows::InputSystem*>(inputManager->getInputSystem());\n auto windowWin = static_cast<NativeWindow*>(window->getNativeWindow());\n\n MSG message;\n\n while (active)\n {\n if (!paused)\n {\n if (PeekMessage(&message, nullptr, 0, 0, PM_REMOVE))\n {\n translateMessage(windowWin->getNativeWindow(),\n windowWin->accelerators, message);\n\n if (message.message == WM_QUIT)\n {\n exit();\n break;\n }\n }\n }\n else\n {\n const BOOL ret = GetMessage(&message, nullptr, 0, 0);\n if (ret == -1)\n throw std::system_error(GetLastError(), std::system_category(), \"Failed to get message\");\n\n if (ret == 0)\n {\n exit();\n break;\n }\n else\n {\n translateMessage(windowWin->getNativeWindow(),\n windowWin->accelerators, message);\n }\n }\n\n inputWin->update();\n }\n\n exit();\n }\n\n void Engine::runOnMainThread(const std::function<void()>& func)\n {\n auto windowWin = static_cast<NativeWindow*>(window->getNativeWindow());\n\n std::unique_lock lock(executeMutex);\n executeQueue.push(func);\n lock.unlock();\n\n if (!PostMessage(windowWin->getNativeWindow(), WM_USER, 0, 0))\n throw std::system_error(GetLastError(), std::system_category(), \"Failed to post message\");\n\n }\n\n void Engine::executeAll()\n {\n std::function<void()> func;\n\n for (;;)\n {\n std::unique_lock lock(executeMutex);\n\n if (executeQueue.empty())\n break;\n\n func = std::move(executeQueue.front());\n executeQueue.pop();\n lock.unlock();\n\n if (func) func();\n }\n }\n\n void Engine::openUrl(const std::string& url)\n {\n const int buferSize = MultiByteToWideChar(CP_UTF8, 0, url.c_str(), -1, nullptr, 0);\n if (buferSize == 0)\n throw std::system_error(GetLastError(), std::system_category(), \"Failed to convert UTF-8 to wide char\");\n\n auto buffer = std::make_unique<WCHAR[]>(buferSize);\n if (MultiByteToWideChar(CP_UTF8, 0, url.c_str(), -1, buffer.get(), buferSize) == 0)\n throw std::system_error(GetLastError(), std::system_category(), \"Failed to convert UTF-8 to wide char\");\n\n \/\/ Result of the ShellExecuteW can be cast only to an int (https:\/\/docs.microsoft.com\/en-us\/windows\/desktop\/api\/shellapi\/nf-shellapi-shellexecutew)\n const auto result = ShellExecuteW(nullptr, L\"open\", buffer.get(), nullptr, nullptr, SW_SHOWNORMAL);\n int status;\n std::memcpy(&status, &result, sizeof(status));\n if (status <= 32)\n throw std::system_error(status, shellExecuteErrorCategory, \"Failed to execute open\");\n }\n}\n<commit_msg>Refactor the code<commit_after>\/\/ Copyright 2015-2020 Elviss Strazdins. All rights reserved.\n\n#include <cstdlib>\n#include <system_error>\n\n#pragma push_macro(\"WIN32_LEAN_AND_MEAN\")\n#pragma push_macro(\"NOMINMAX\")\n#ifndef WIN32_LEAN_AND_MEAN\n# define WIN32_LEAN_AND_MEAN\n#endif\n#ifndef NOMINMAX\n# define NOMINMAX\n#endif\n#include <Windows.h>\n#include <shellapi.h>\n#pragma pop_macro(\"WIN32_LEAN_AND_MEAN\")\n#pragma pop_macro(\"NOMINMAX\")\n\n#include \"EngineWin.hpp\"\n#include \"NativeWindowWin.hpp\"\n#include \"ShellExecuteErrorCategory.hpp\"\n#include \"..\/..\/input\/windows\/InputSystemWin.hpp\"\n#include \"..\/..\/utils\/Log.hpp\"\n\nnamespace ouzel::core::windows\n{\n namespace\n {\n std::vector<std::string> parseArgs(int argc, LPWSTR* argv)\n {\n std::vector<std::string> result;\n if (argv)\n for (int i = 0; i < argc; ++i)\n {\n const int bufferSize = WideCharToMultiByte(CP_UTF8, 0, argv[i], -1, nullptr, 0, nullptr, nullptr);\n if (bufferSize == 0)\n throw std::system_error(GetLastError(), std::system_category(), \"Failed to convert wide char to UTF-8\");\n\n std::vector<char> buffer(bufferSize);\n if (WideCharToMultiByte(CP_UTF8, 0, argv[i], -1, buffer.data(), bufferSize, nullptr, nullptr) == 0)\n throw std::system_error(GetLastError(), std::system_category(), \"Failed to convert wide char to UTF-8\");\n\n result.push_back(buffer.data());\n }\n\n return result;\n }\n\n const ShellExecuteErrorCategory shellExecuteErrorCategory{};\n }\n\n Engine::Engine(int argc, LPWSTR* argv):\n core::Engine(parseArgs(argc, argv))\n {\n }\n\n static void translateMessage(HWND window, const std::set<HACCEL>& accelerators, MSG& message)\n {\n bool translate = true;\n\n for (HACCEL accelerator : accelerators)\n if (TranslateAccelerator(window, accelerator, &message))\n translate = false;\n\n if (translate)\n {\n TranslateMessage(&message);\n DispatchMessage(&message);\n }\n }\n\n void Engine::run()\n {\n init();\n start();\n\n auto inputWin = static_cast<input::windows::InputSystem*>(inputManager->getInputSystem());\n auto windowWin = static_cast<NativeWindow*>(window->getNativeWindow());\n\n while (active)\n {\n if (!paused)\n {\n MSG message;\n if (PeekMessage(&message, nullptr, 0, 0, PM_REMOVE))\n {\n translateMessage(windowWin->getNativeWindow(),\n windowWin->accelerators, message);\n\n if (message.message == WM_QUIT)\n {\n exit();\n break;\n }\n }\n }\n else\n {\n MSG message;\n const BOOL ret = GetMessage(&message, nullptr, 0, 0);\n if (ret == -1)\n throw std::system_error(GetLastError(), std::system_category(), \"Failed to get message\");\n\n if (ret == 0)\n {\n exit();\n break;\n }\n else\n {\n translateMessage(windowWin->getNativeWindow(),\n windowWin->accelerators, message);\n }\n }\n\n inputWin->update();\n }\n\n exit();\n }\n\n void Engine::runOnMainThread(const std::function<void()>& func)\n {\n auto windowWin = static_cast<NativeWindow*>(window->getNativeWindow());\n\n std::unique_lock lock(executeMutex);\n executeQueue.push(func);\n lock.unlock();\n\n if (!PostMessage(windowWin->getNativeWindow(), WM_USER, 0, 0))\n throw std::system_error(GetLastError(), std::system_category(), \"Failed to post message\");\n\n }\n\n void Engine::executeAll()\n {\n std::function<void()> func;\n\n for (;;)\n {\n std::unique_lock lock(executeMutex);\n\n if (executeQueue.empty())\n break;\n\n func = std::move(executeQueue.front());\n executeQueue.pop();\n lock.unlock();\n\n if (func) func();\n }\n }\n\n void Engine::openUrl(const std::string& url)\n {\n const int buferSize = MultiByteToWideChar(CP_UTF8, 0, url.c_str(), -1, nullptr, 0);\n if (buferSize == 0)\n throw std::system_error(GetLastError(), std::system_category(), \"Failed to convert UTF-8 to wide char\");\n\n auto buffer = std::make_unique<WCHAR[]>(buferSize);\n if (MultiByteToWideChar(CP_UTF8, 0, url.c_str(), -1, buffer.get(), buferSize) == 0)\n throw std::system_error(GetLastError(), std::system_category(), \"Failed to convert UTF-8 to wide char\");\n\n \/\/ Result of the ShellExecuteW can be cast only to an int (https:\/\/docs.microsoft.com\/en-us\/windows\/desktop\/api\/shellapi\/nf-shellapi-shellexecutew)\n const auto result = ShellExecuteW(nullptr, L\"open\", buffer.get(), nullptr, nullptr, SW_SHOWNORMAL);\n int status;\n std::memcpy(&status, &result, sizeof(status));\n if (status <= 32)\n throw std::system_error(status, shellExecuteErrorCategory, \"Failed to execute open\");\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2013 Samplecount S.L.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#ifndef METHCLA_PLUGIN_HPP_INCLUDED\n#define METHCLA_PLUGIN_HPP_INCLUDED\n\n#include <methcla\/log.hpp>\n#include <methcla\/plugin.h>\n#include <oscpp\/server.hpp>\n\n#include <functional>\n#include <cstring>\n\n\/\/ NOTE: This API is unstable and subject to change!\n\nnamespace Methcla { namespace Plugin {\n\n template <class Synth> class World\n {\n const Methcla_World* m_context;\n\n public:\n World(const Methcla_World* context)\n : m_context(context)\n { }\n\n double sampleRate() const\n {\n return methcla_world_samplerate(m_context);\n }\n\n size_t blockSize() const\n {\n return methcla_world_block_size(m_context);\n }\n\n Methcla_Time currentTime() const\n {\n return methcla_world_current_time(m_context);\n }\n\n void* alloc(size_t size) const\n {\n return methcla_world_alloc(m_context, size);\n }\n\n void* allocAligned(size_t alignment, size_t size) const\n {\n return methcla_world_alloc_aligned(m_context, alignment, size);\n }\n\n void free(void* ptr)\n {\n methcla_world_free(m_context, ptr);\n }\n\n void performCommand(Methcla_HostPerformFunction perform, void* data)\n {\n methcla_world_perform_command(m_context, perform, data);\n }\n\n LogStream log(Methcla_LogLevel logLevel=kMethcla_LogInfo)\n {\n using namespace std::placeholders;\n return LogStream(std::bind(m_context->log_line, m_context, _1, _2), logLevel);\n }\n\n void synthRetain(Synth* synth) const\n {\n methcla_world_synth_retain(m_context, synth);\n }\n\n void synthRelease(Synth* synth) const\n {\n methcla_world_synth_release(m_context, synth);\n }\n\n void synthDone(Synth* synth) const\n {\n methcla_world_synth_done(m_context, synth);\n }\n };\n\n class HostContext\n {\n const Methcla_Host* m_context;\n\n public:\n HostContext(const Methcla_Host* context)\n : m_context(context)\n {}\n\n LogStream log(Methcla_LogLevel logLevel=kMethcla_LogInfo)\n {\n using namespace std::placeholders;\n return LogStream(std::bind(m_context->log_line, m_context, _1, _2), logLevel);\n }\n };\n\n class NoPorts\n {\n public:\n enum Port { };\n\n static size_t numPorts() { return 0; }\n\n static Methcla_PortDescriptor descriptor(Port)\n {\n Methcla_PortDescriptor result;\n std::memset(&result, 0, sizeof(result));\n return result;\n }\n };\n\n class PortDescriptor\n {\n public:\n static Methcla_PortDescriptor make(Methcla_PortDirection direction, Methcla_PortType type, Methcla_PortFlags flags=kMethcla_PortFlags)\n {\n Methcla_PortDescriptor pd;\n pd.direction = direction;\n pd.type = type;\n pd.flags = flags;\n return pd;\n }\n\n static Methcla_PortDescriptor audioInput(Methcla_PortFlags flags=kMethcla_PortFlags)\n {\n return make(kMethcla_Input, kMethcla_AudioPort, flags);\n }\n\n static Methcla_PortDescriptor audioOutput(Methcla_PortFlags flags=kMethcla_PortFlags)\n {\n return make(kMethcla_Output, kMethcla_AudioPort, flags);\n }\n\n static Methcla_PortDescriptor controlInput(Methcla_PortFlags flags=kMethcla_PortFlags)\n {\n return make(kMethcla_Input, kMethcla_ControlPort, flags);\n }\n\n static Methcla_PortDescriptor controlOutput(Methcla_PortFlags flags=kMethcla_PortFlags)\n {\n return make(kMethcla_Output, kMethcla_ControlPort, flags);\n }\n };\n\n template <class Options, class PortDescriptor> class StaticSynthOptions\n {\n public:\n typedef Options Type;\n\n static void\n configure( const void* tag_buffer\n , size_t tag_buffer_size\n , const void* arg_buffer\n , size_t arg_buffer_size\n , Methcla_SynthOptions* options )\n {\n OSCPP::Server::ArgStream args(\n OSCPP::ReadStream(tag_buffer, tag_buffer_size),\n OSCPP::ReadStream(arg_buffer, arg_buffer_size)\n );\n new (options) Type(args);\n }\n\n static bool\n port_descriptor( const Methcla_SynthOptions*\n , Methcla_PortCount index\n , Methcla_PortDescriptor* port )\n {\n if (index < PortDescriptor::numPorts())\n {\n *port = PortDescriptor::descriptor(static_cast<typename PortDescriptor::Port>(index));\n return true;\n }\n return false;\n }\n };\n\n namespace detail\n {\n template <class Synth, bool Condition>\n class IfSynthDefHasActivate\n {\n public:\n static inline void exec(const Methcla_World*, Synth*) { }\n };\n\n template <class Synth>\n class IfSynthDefHasActivate<Synth, true>\n {\n public:\n static inline void exec(const Methcla_World* context, Synth* synth)\n { synth->activate(World<Synth>(context)); }\n };\n\n template <class Synth, bool Condition>\n class IfSynthDefHasCleanup\n {\n public:\n static inline void exec(const Methcla_World*, Synth*) { }\n };\n\n template <class Synth>\n class IfSynthDefHasCleanup<Synth, true>\n {\n public:\n static inline void exec(const Methcla_World* context, Synth* synth)\n { synth->cleanup(World<Synth>(context)); }\n };\n } \/\/ namespace detail\n\n enum SynthDefFlags\n {\n kSynthDefDefaultFlags = 0x00,\n kSynthDefHasActivate = 0x01,\n kSynthDefHasCleanup = 0x02\n };\n\n template <class Synth, class Options, class PortDescriptor, SynthDefFlags Flags=kSynthDefDefaultFlags> class SynthDef\n {\n static void\n construct( const Methcla_World* context\n , const Methcla_SynthDef* synthDef\n , const Methcla_SynthOptions* options\n , Methcla_Synth* synth )\n {\n assert(context != nullptr);\n assert(options != nullptr);\n new (synth) Synth(World<Synth>(context), synthDef, *static_cast<const typename Options::Type*>(options));\n }\n\n static void\n connect( Methcla_Synth* synth\n , Methcla_PortCount port\n , void* data)\n {\n static_cast<Synth*>(synth)->connect(static_cast<typename PortDescriptor::Port>(port), data);\n }\n\n static void\n activate(const Methcla_World* context, Methcla_Synth* synth)\n {\n detail::IfSynthDefHasActivate<\n Synth,\n (Flags & kSynthDefHasActivate) == kSynthDefHasActivate\n >::exec(context, static_cast<Synth*>(synth));\n }\n\n static void\n process(const Methcla_World* context, Methcla_Synth* synth, size_t numFrames)\n {\n static_cast<Synth*>(synth)->process(World<Synth>(context), numFrames);\n }\n\n static void\n destroy(const Methcla_World* context, Methcla_Synth* synth)\n {\n \/\/ Call cleanup method\n detail::IfSynthDefHasActivate<\n Synth,\n (Flags & kSynthDefHasCleanup) == kSynthDefHasCleanup\n >::exec(context, static_cast<Synth*>(synth));\n \/\/ Call destructor\n static_cast<Synth*>(synth)->~Synth();\n }\n\n public:\n void operator()(const Methcla_Host* host, const char* uri)\n {\n static const Methcla_SynthDef kSynthDef =\n {\n uri,\n sizeof(Synth),\n sizeof(typename Options::Type),\n Options::configure,\n Options::port_descriptor,\n construct,\n connect,\n activate,\n process,\n destroy\n };\n methcla_host_register_synthdef(host, &kSynthDef);\n }\n };\n\n template <class Synth, class Options, class Ports, SynthDefFlags Flags=kSynthDefDefaultFlags>\n using StaticSynthDef\n = SynthDef<Synth, StaticSynthOptions<Options,Ports>, Ports, Flags>;\n} }\n\n#endif \/\/ METHCLA_PLUGIN_HPP_INCLUDED\n<commit_msg>Remove deprecated plugin interface methods<commit_after>\/\/ Copyright 2013 Samplecount S.L.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#ifndef METHCLA_PLUGIN_HPP_INCLUDED\n#define METHCLA_PLUGIN_HPP_INCLUDED\n\n#include <methcla\/log.hpp>\n#include <methcla\/plugin.h>\n#include <oscpp\/server.hpp>\n\n#include <functional>\n#include <cstring>\n\n\/\/ NOTE: This API is unstable and subject to change!\n\nnamespace Methcla { namespace Plugin {\n\n template <class Synth> class World\n {\n const Methcla_World* m_context;\n\n public:\n World(const Methcla_World* context)\n : m_context(context)\n { }\n\n double sampleRate() const\n {\n return methcla_world_samplerate(m_context);\n }\n\n size_t blockSize() const\n {\n return methcla_world_block_size(m_context);\n }\n\n Methcla_Time currentTime() const\n {\n return methcla_world_current_time(m_context);\n }\n\n void* alloc(size_t size) const\n {\n return methcla_world_alloc(m_context, size);\n }\n\n void* allocAligned(size_t alignment, size_t size) const\n {\n return methcla_world_alloc_aligned(m_context, alignment, size);\n }\n\n void free(void* ptr)\n {\n methcla_world_free(m_context, ptr);\n }\n\n void performCommand(Methcla_HostPerformFunction perform, void* data)\n {\n methcla_world_perform_command(m_context, perform, data);\n }\n\n LogStream log(Methcla_LogLevel logLevel=kMethcla_LogInfo)\n {\n using namespace std::placeholders;\n return LogStream(std::bind(m_context->log_line, m_context, _1, _2), logLevel);\n }\n\n void synthDone(Synth* synth) const\n {\n methcla_world_synth_done(m_context, synth);\n }\n };\n\n class HostContext\n {\n const Methcla_Host* m_context;\n\n public:\n HostContext(const Methcla_Host* context)\n : m_context(context)\n {}\n\n LogStream log(Methcla_LogLevel logLevel=kMethcla_LogInfo)\n {\n using namespace std::placeholders;\n return LogStream(std::bind(m_context->log_line, m_context, _1, _2), logLevel);\n }\n };\n\n class NoPorts\n {\n public:\n enum Port { };\n\n static size_t numPorts() { return 0; }\n\n static Methcla_PortDescriptor descriptor(Port)\n {\n Methcla_PortDescriptor result;\n std::memset(&result, 0, sizeof(result));\n return result;\n }\n };\n\n class PortDescriptor\n {\n public:\n static Methcla_PortDescriptor make(Methcla_PortDirection direction, Methcla_PortType type, Methcla_PortFlags flags=kMethcla_PortFlags)\n {\n Methcla_PortDescriptor pd;\n pd.direction = direction;\n pd.type = type;\n pd.flags = flags;\n return pd;\n }\n\n static Methcla_PortDescriptor audioInput(Methcla_PortFlags flags=kMethcla_PortFlags)\n {\n return make(kMethcla_Input, kMethcla_AudioPort, flags);\n }\n\n static Methcla_PortDescriptor audioOutput(Methcla_PortFlags flags=kMethcla_PortFlags)\n {\n return make(kMethcla_Output, kMethcla_AudioPort, flags);\n }\n\n static Methcla_PortDescriptor controlInput(Methcla_PortFlags flags=kMethcla_PortFlags)\n {\n return make(kMethcla_Input, kMethcla_ControlPort, flags);\n }\n\n static Methcla_PortDescriptor controlOutput(Methcla_PortFlags flags=kMethcla_PortFlags)\n {\n return make(kMethcla_Output, kMethcla_ControlPort, flags);\n }\n };\n\n template <class Options, class PortDescriptor> class StaticSynthOptions\n {\n public:\n typedef Options Type;\n\n static void\n configure( const void* tag_buffer\n , size_t tag_buffer_size\n , const void* arg_buffer\n , size_t arg_buffer_size\n , Methcla_SynthOptions* options )\n {\n OSCPP::Server::ArgStream args(\n OSCPP::ReadStream(tag_buffer, tag_buffer_size),\n OSCPP::ReadStream(arg_buffer, arg_buffer_size)\n );\n new (options) Type(args);\n }\n\n static bool\n port_descriptor( const Methcla_SynthOptions*\n , Methcla_PortCount index\n , Methcla_PortDescriptor* port )\n {\n if (index < PortDescriptor::numPorts())\n {\n *port = PortDescriptor::descriptor(static_cast<typename PortDescriptor::Port>(index));\n return true;\n }\n return false;\n }\n };\n\n namespace detail\n {\n template <class Synth, bool Condition>\n class IfSynthDefHasActivate\n {\n public:\n static inline void exec(const Methcla_World*, Synth*) { }\n };\n\n template <class Synth>\n class IfSynthDefHasActivate<Synth, true>\n {\n public:\n static inline void exec(const Methcla_World* context, Synth* synth)\n { synth->activate(World<Synth>(context)); }\n };\n\n template <class Synth, bool Condition>\n class IfSynthDefHasCleanup\n {\n public:\n static inline void exec(const Methcla_World*, Synth*) { }\n };\n\n template <class Synth>\n class IfSynthDefHasCleanup<Synth, true>\n {\n public:\n static inline void exec(const Methcla_World* context, Synth* synth)\n { synth->cleanup(World<Synth>(context)); }\n };\n } \/\/ namespace detail\n\n enum SynthDefFlags\n {\n kSynthDefDefaultFlags = 0x00,\n kSynthDefHasActivate = 0x01,\n kSynthDefHasCleanup = 0x02\n };\n\n template <class Synth, class Options, class PortDescriptor, SynthDefFlags Flags=kSynthDefDefaultFlags> class SynthDef\n {\n static void\n construct( const Methcla_World* context\n , const Methcla_SynthDef* synthDef\n , const Methcla_SynthOptions* options\n , Methcla_Synth* synth )\n {\n assert(context != nullptr);\n assert(options != nullptr);\n new (synth) Synth(World<Synth>(context), synthDef, *static_cast<const typename Options::Type*>(options));\n }\n\n static void\n connect( Methcla_Synth* synth\n , Methcla_PortCount port\n , void* data)\n {\n static_cast<Synth*>(synth)->connect(static_cast<typename PortDescriptor::Port>(port), data);\n }\n\n static void\n activate(const Methcla_World* context, Methcla_Synth* synth)\n {\n detail::IfSynthDefHasActivate<\n Synth,\n (Flags & kSynthDefHasActivate) == kSynthDefHasActivate\n >::exec(context, static_cast<Synth*>(synth));\n }\n\n static void\n process(const Methcla_World* context, Methcla_Synth* synth, size_t numFrames)\n {\n static_cast<Synth*>(synth)->process(World<Synth>(context), numFrames);\n }\n\n static void\n destroy(const Methcla_World* context, Methcla_Synth* synth)\n {\n \/\/ Call cleanup method\n detail::IfSynthDefHasActivate<\n Synth,\n (Flags & kSynthDefHasCleanup) == kSynthDefHasCleanup\n >::exec(context, static_cast<Synth*>(synth));\n \/\/ Call destructor\n static_cast<Synth*>(synth)->~Synth();\n }\n\n public:\n void operator()(const Methcla_Host* host, const char* uri)\n {\n static const Methcla_SynthDef kSynthDef =\n {\n uri,\n sizeof(Synth),\n sizeof(typename Options::Type),\n Options::configure,\n Options::port_descriptor,\n construct,\n connect,\n activate,\n process,\n destroy\n };\n methcla_host_register_synthdef(host, &kSynthDef);\n }\n };\n\n template <class Synth, class Options, class Ports, SynthDefFlags Flags=kSynthDefDefaultFlags>\n using StaticSynthDef\n = SynthDef<Synth, StaticSynthOptions<Options,Ports>, Ports, Flags>;\n} }\n\n#endif \/\/ METHCLA_PLUGIN_HPP_INCLUDED\n<|endoftext|>"} {"text":"<commit_before>\/*\r\n * Copyright (c) MZ3 Project Team All rights reserved.\r\n * Code licensed under the BSD License:\r\n * http:\/\/www.mz3.jp\/license.txt\r\n *\/\r\n#include \"stdafx.h\"\r\n#include \"MixiParserUtil.h\"\r\n\r\n\/\/\/ mixi pHTMLp[T\r\nnamespace mixi {\r\n\r\n\t\/**\r\n\t * ϊ(tEۂ𒊏oAmixi SetDate)\r\n\t *\r\n\t * @param line [in] ܂ޕB\r\n\t * F\"2006N1119 17:12\"\r\n\t * \"<span class=\"date\">2007N0705 21:55<\/span><\/dt>\"\r\n\t * \"<td>1008<\/td><\/tr>\"\r\n\t * \"1219927284\" (G|bN)\r\n\t * @param mixi [out] ͌ʂ SetDate ŕۑB\r\n\t *\/\r\n\tbool ParserUtil::ParseDate(LPCTSTR line, CMixiData& mixi)\r\n\t{\r\n\t\t\/\/ ėp `\r\n\t\tif (wcsstr(line, L\"\") != NULL) {\r\n\t\t\t\/\/ K\\̃RpC\r\n\t\t\tstatic MyRegex reg;\r\n\t\t\tif( !util::CompileRegex( reg, L\"([0-9]{2,4})?N?([0-9]{1,2}?)([0-9]{1,2})[^0-9]*([0-9]{1,2})?:??([0-9]{2})?\" ) ) {\r\n\t\t\t\treturn false;\r\n\t\t\t}\r\n\t\t\t\/\/ \r\n\t\t\tif( reg.exec(line) && reg.results.size() == 6 ) {\r\n\t\t\t\t\/\/ o\r\n\t\t\t\tint year = _wtoi( reg.results[1].str.c_str() );\r\n\t\t\t\tint month = _wtoi( reg.results[2].str.c_str() );\r\n\t\t\t\tint day = _wtoi( reg.results[3].str.c_str() );\r\n\t\t\t\tint hour = _wtoi( reg.results[4].str.c_str() );\r\n\t\t\t\tint minute = _wtoi( reg.results[5].str.c_str() );\r\n\t\t\t\t\/\/mixi.SetDate(year, month, day, hour, minute);\r\n\r\n\t\t\t\tif (year<1900) {\r\n\t\t\t\t\t\/\/ CTime year<1900 T|[gĂȂ̂ŁAƂēo^B\r\n\t\t\t\t\tCString s;\r\n\t\t\t\t\ts.Format(_T(\"%02d\/%02d %02d:%02d\"), month, day, hour, minute);\r\n\t\t\t\t\tmixi.SetDate( s );\r\n\t\t\t\t} else {\r\n\t\t\t\t\tmixi.SetDate( CTime(year, month, day, hour, minute, 0) );\r\n\t\t\t\t}\r\n\t\t\t\treturn true;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tCTime t;\r\n\t\tif (ParseDate(line, t)) {\r\n\t\t\t\/\/ ͐\r\n\t\t\tmixi.SetDate(t);\r\n\t\t\treturn true;\r\n\t\t}\r\n\r\n\t\tCString msg = L\"ɓtE‚܂ : [\";\r\n\t\tmsg += line;\r\n\t\tmsg += L\"]\";\r\n\t\tMZ3LOGGER_DEBUG( msg );\r\n\t\treturn false;\r\n\t}\r\n\r\n\r\n\tbool ParserUtil::ParseDate(LPCTSTR line, CTime& t_result)\r\n\t{\r\n\t\t\/\/ T1. RSS ` (YYYY-MM-DDT00:00:00Z)\r\n\t\t{\r\n\t\t\t\/\/ K\\̃RpC\r\n\t\t\tstatic MyRegex reg;\r\n\t\t\tif( !util::CompileRegex( reg, L\"([0-9]{4})-([0-9]{2})-([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})Z\" ) ) {\r\n\t\t\t\treturn false;\r\n\t\t\t}\r\n\t\t\t\/\/ \r\n\t\t\tif( reg.exec(line) && reg.results.size() == 7 ) {\r\n\t\t\t\t\/\/ o\r\n\t\t\t\tint year = _wtoi( reg.results[1].str.c_str() );\r\n\t\t\t\tint month = _wtoi( reg.results[2].str.c_str() );\r\n\t\t\t\tint day = _wtoi( reg.results[3].str.c_str() );\r\n\t\t\t\tint hour = _wtoi( reg.results[4].str.c_str() );\r\n\t\t\t\tint minute = _wtoi( reg.results[5].str.c_str() );\r\n\r\n\t\t\t\tCTime t(year, month, day, hour, minute, 0);\r\n\t\t\t\tt += CTimeSpan(0, 9, 0, 0);\r\n\r\n\t\t\t\tt_result = t;\r\n\t\t\t\t\/\/mixi.SetDate(t.GetYear(), t.GetMonth(), t.GetDay(), t.GetHour(), t.GetMinute());\r\n\t\t\t\treturn true;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t\/\/ T2. RSS ` (YYYY-MM-DDT00:00:00+09:00)\r\n\t\t{\r\n\t\t\t\/\/ K\\̃RpC\r\n\t\t\tstatic MyRegex reg;\r\n\t\t\tif( !util::CompileRegex( reg, L\"([0-9]{4})-([0-9]{2})-([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})\\\\+([0-9]{2}):([0-9]{2})\" ) ) {\r\n\t\t\t\treturn false;\r\n\t\t\t}\r\n\t\t\t\/\/ \r\n\t\t\tif( reg.exec(line) && reg.results.size() == 9 ) {\r\n\t\t\t\t\/\/ o\r\n\t\t\t\tint year = _wtoi( reg.results[1].str.c_str() );\r\n\t\t\t\tint month = _wtoi( reg.results[2].str.c_str() );\r\n\t\t\t\tint day = _wtoi( reg.results[3].str.c_str() );\r\n\t\t\t\tint hour = _wtoi( reg.results[4].str.c_str() );\r\n\t\t\t\tint minute = _wtoi( reg.results[5].str.c_str() );\r\n\r\n\t\t\t\tCTime t(year, month, day, hour, minute, 0);\r\n\/\/\t\t\t\tt += CTimeSpan(0, 9, 0, 0);\r\n\r\n\t\t\t\tt_result = t;\r\n\t\t\t\treturn true;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t\/\/ T3. RSS ` (Sun Dec 16 09:00:00 +0000 2007)\r\n\t\t\/\/ T3. RSS ` (Fri Dec 5 1:03:05 +0900 2008)\r\n\t\t{\r\n\t\t\t\/\/ K\\̃RpC\r\n\t\t\tstatic MyRegex reg;\r\n\t\t\tif( !util::CompileRegex( reg, L\"([a-zA-Z]{3}) ([a-zA-Z]{3}) ([0-9]{1,2}) ([0-9]{1,2}):([0-9]{2}):([0-9]{2}) \\\\+([0-9]{4}) ([0-9]{4})\" ) ) {\r\n\t\t\t\treturn false;\r\n\t\t\t}\r\n\t\t\t\/\/ \r\n\t\t\tif( reg.exec(line) && reg.results.size() == 9 ) {\r\n\t\t\t\t\/\/ o\r\n\r\n\t\t\t\t\/\/ N\r\n\t\t\t\tint year = _wtoi( reg.results[8].str.c_str() );\r\n\r\n\t\t\t\t\/\/ \r\n\t\t\t\tint month = ThreeCharMonthToInteger( reg.results[2].str.c_str() );\r\n\t\t\t\tint day = _wtoi( reg.results[3].str.c_str() );\r\n\t\t\t\tint hour = _wtoi( reg.results[4].str.c_str() );\r\n\t\t\t\tint minute = _wtoi( reg.results[5].str.c_str() );\r\n\t\t\t\tint sec = _wtoi( reg.results[6].str.c_str() );\r\n\r\n\t\t\t\tCTime t(year, month, day, hour, minute, sec);\r\n\r\n\t\t\t\tint diff = _wtoi( reg.results[7].str.c_str() );\r\n\t\t\t\tif (diff==0) {\r\n\t\t\t\t\tt += CTimeSpan(0, 9, 0, 0);\r\n\t\t\t\t}\r\n\t\t\t\tt_result = t;\r\n\t\t\t\treturn true;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t\/\/ T4. RSS 2.0 ` (Mon, 16 Dec 2007 09:00:00 +0900)\r\n\t\t\/\/ T4. RSS 2.0 ` (Mon, 16 Dec 2007 09:00:00 GMT)\r\n\t\t{\r\n\t\t\t\/\/ K\\̃RpC\r\n\t\t\tstatic MyRegex reg;\r\n\t\t\tif( !util::CompileRegex( reg, L\"([a-zA-Z]{3}), ([0-9]{2}) ([a-zA-Z]{3}) ([0-9]{4}) ([0-9]{2}):([0-9]{2}):([0-9]{2}) (.*)\" ) ) {\r\n\t\t\t\treturn false;\r\n\t\t\t}\r\n\t\t\t\/\/ \r\n\t\t\tif( reg.exec(line) && reg.results.size() == 9 ) {\r\n\t\t\t\t\/\/ o\r\n\r\n\t\t\t\t\/\/ N\r\n\t\t\t\tint year = _wtoi( reg.results[4].str.c_str() );\r\n\r\n\t\t\t\t\/\/ \r\n\t\t\t\tint month = ThreeCharMonthToInteger( reg.results[3].str.c_str() );\r\n\t\t\t\tint day = _wtoi( reg.results[2].str.c_str() );\r\n\t\t\t\tint hour = _wtoi( reg.results[5].str.c_str() );\r\n\t\t\t\tint minute = _wtoi( reg.results[6].str.c_str() );\r\n\t\t\t\tint sec = _wtoi( reg.results[7].str.c_str() );\r\n\t\t\t\tCTime t(year, month, day, hour, minute, sec);\r\n\r\n\t\t\t\t\/\/ ȈՎϊ\r\n\t\t\t\tconst std::wstring& time_diff = reg.results[8].str;\r\n\r\n\t\t\t\tif (time_diff==L\"GMT\") {\r\n\t\t\t\t\tt += CTimeSpan(0, 9, 0, 0);\r\n\t\t\t\t}\r\n\r\n\t\t\t\tt_result = t;\r\n\t\t\t\treturn true;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t\/\/ T5. epoch ` (1219927284)\r\n\t\t{\r\n\t\t\t\/\/ K\\̃RpC\r\n\t\t\tstatic MyRegex reg;\r\n\t\t\tif( !util::CompileRegex( reg, L\"^([0-9]*)$\" ) ) {\r\n\t\t\t\treturn false;\r\n\t\t\t}\r\n\t\t\t\/\/ \r\n\t\t\tif( reg.exec(line) && reg.results.size() == 2 ) {\r\n\t\t\t\t\/\/ o\r\n\r\n\t\t\t\tt_result = CTime(_wtoi(reg.results[1].str.c_str()));\r\n\r\n\t\t\t\treturn true;\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn false;\r\n\t}\r\n\r\n}\r\n<commit_msg><commit_after>\/*\r\n * Copyright (c) MZ3 Project Team All rights reserved.\r\n * Code licensed under the BSD License:\r\n * http:\/\/www.mz3.jp\/license.txt\r\n *\/\r\n#include \"stdafx.h\"\r\n#include \"MixiParserUtil.h\"\r\n\r\n\/\/\/ mixi pHTMLp[T\r\nnamespace mixi {\r\n\r\n\t\/**\r\n\t * ϊ(tEۂ𒊏oAmixi SetDate)\r\n\t *\r\n\t * @param line [in] ܂ޕB\r\n\t * F\"2006N1119 17:12\"\r\n\t * \"<span class=\"date\">2007N0705 21:55<\/span><\/dt>\"\r\n\t * \"<td>1008<\/td><\/tr>\"\r\n\t * \"1219927284\" (G|bN)\r\n\t * @param mixi [out] ͌ʂ SetDate ŕۑB\r\n\t *\/\r\n\tbool ParserUtil::ParseDate(LPCTSTR line, CMixiData& mixi)\r\n\t{\r\n\t\t\/\/ ėp `\r\n\t\tif (wcsstr(line, L\"\") != NULL) {\r\n\t\t\t\/\/ K\\̃RpC\r\n\t\t\tstatic MyRegex reg;\r\n\t\t\tif( !util::CompileRegex( reg, L\"([0-9]{2,4})?N?([0-9]{1,2}?)([0-9]{1,2})[^0-9]*([0-9]{1,2})?:??([0-9]{2})?\" ) ) {\r\n\t\t\t\treturn false;\r\n\t\t\t}\r\n\t\t\t\/\/ \r\n\t\t\tif( reg.exec(line) && reg.results.size() == 6 ) {\r\n\t\t\t\t\/\/ o\r\n\t\t\t\tint year = _wtoi( reg.results[1].str.c_str() );\r\n\t\t\t\tint month = _wtoi( reg.results[2].str.c_str() );\r\n\t\t\t\tint day = _wtoi( reg.results[3].str.c_str() );\r\n\t\t\t\tint hour = _wtoi( reg.results[4].str.c_str() );\r\n\t\t\t\tint minute = _wtoi( reg.results[5].str.c_str() );\r\n\t\t\t\t\/\/mixi.SetDate(year, month, day, hour, minute);\r\n\r\n\t\t\t\tif (year<1900) {\r\n\t\t\t\t\t\/\/ CTime year<1900 T|[gĂȂ̂ŁAƂēo^B\r\n\t\t\t\t\tCString s;\r\n\t\t\t\t\ts.Format(_T(\"%02d\/%02d %02d:%02d\"), month, day, hour, minute);\r\n\t\t\t\t\tmixi.SetDate( s );\r\n\t\t\t\t} else {\r\n\t\t\t\t\tmixi.SetDate( CTime(year, month, day, hour, minute, 0) );\r\n\t\t\t\t}\r\n\t\t\t\treturn true;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tCTime t;\r\n\t\tif (ParseDate(line, t)) {\r\n\t\t\t\/\/ ͐\r\n\t\t\tmixi.SetDate(t);\r\n\t\t\treturn true;\r\n\t\t}\r\n\r\n\t\tCString msg = L\"ɓtE‚܂ : [\";\r\n\t\tmsg += line;\r\n\t\tmsg += L\"]\";\r\n\t\tMZ3LOGGER_DEBUG( msg );\r\n\t\treturn false;\r\n\t}\r\n\r\n\r\n\tbool ParserUtil::ParseDate(LPCTSTR line, CTime& t_result)\r\n\t{\r\n\t\t\/\/ T1. RSS ` (YYYY-MM-DDT00:00:00Z)\r\n\t\t{\r\n\t\t\t\/\/ K\\̃RpC\r\n\t\t\tstatic MyRegex reg;\r\n\t\t\tif( !util::CompileRegex( reg, L\"([0-9]{4})-([0-9]{2})-([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})Z\" ) ) {\r\n\t\t\t\treturn false;\r\n\t\t\t}\r\n\t\t\t\/\/ \r\n\t\t\tif( reg.exec(line) && reg.results.size() == 7 ) {\r\n\t\t\t\t\/\/ o\r\n\t\t\t\tint year = _wtoi( reg.results[1].str.c_str() );\r\n\t\t\t\tint month = _wtoi( reg.results[2].str.c_str() );\r\n\t\t\t\tint day = _wtoi( reg.results[3].str.c_str() );\r\n\t\t\t\tint hour = _wtoi( reg.results[4].str.c_str() );\r\n\t\t\t\tint minute = _wtoi( reg.results[5].str.c_str() );\r\n\r\n\t\t\t\tCTime t(year, month, day, hour, minute, 0);\r\n\t\t\t\tt += CTimeSpan(0, 9, 0, 0);\r\n\r\n\t\t\t\tt_result = t;\r\n\t\t\t\t\/\/mixi.SetDate(t.GetYear(), t.GetMonth(), t.GetDay(), t.GetHour(), t.GetMinute());\r\n\t\t\t\treturn true;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t\/\/ T2. RSS ` (YYYY-MM-DDT00:00:00+09:00)\r\n\t\t{\r\n\t\t\t\/\/ K\\̃RpC\r\n\t\t\tstatic MyRegex reg;\r\n\t\t\tif( !util::CompileRegex( reg, L\"([0-9]{4})-([0-9]{2})-([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})\\\\+([0-9]{2}):([0-9]{2})\" ) ) {\r\n\t\t\t\treturn false;\r\n\t\t\t}\r\n\t\t\t\/\/ \r\n\t\t\tif( reg.exec(line) && reg.results.size() == 9 ) {\r\n\t\t\t\t\/\/ o\r\n\t\t\t\tint year = _wtoi( reg.results[1].str.c_str() );\r\n\t\t\t\tint month = _wtoi( reg.results[2].str.c_str() );\r\n\t\t\t\tint day = _wtoi( reg.results[3].str.c_str() );\r\n\t\t\t\tint hour = _wtoi( reg.results[4].str.c_str() );\r\n\t\t\t\tint minute = _wtoi( reg.results[5].str.c_str() );\r\n\r\n\t\t\t\tCTime t(year, month, day, hour, minute, 0);\r\n\/\/\t\t\t\tt += CTimeSpan(0, 9, 0, 0);\r\n\r\n\t\t\t\tt_result = t;\r\n\t\t\t\treturn true;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t\/\/ T3. RSS ` (Sun Dec 16 09:00:00 +0000 2007)\r\n\t\t\/\/ T3. RSS ` (Fri Dec 5 1:03:05 +0900 2008)\r\n\t\t{\r\n\t\t\t\/\/ K\\̃RpC\r\n\t\t\tstatic MyRegex reg;\r\n\t\t\tif( !util::CompileRegex( reg, L\"([a-zA-Z]{3}) ([a-zA-Z]{3}) ([0-9]{1,2}) ([0-9]{1,2}):([0-9]{2}):([0-9]{2}) \\\\+([0-9]{4}) ([0-9]{4})\" ) ) {\r\n\t\t\t\treturn false;\r\n\t\t\t}\r\n\t\t\t\/\/ \r\n\t\t\tif( reg.exec(line) && reg.results.size() == 9 ) {\r\n\t\t\t\t\/\/ o\r\n\r\n\t\t\t\t\/\/ N\r\n\t\t\t\tint year = _wtoi( reg.results[8].str.c_str() );\r\n\r\n\t\t\t\t\/\/ \r\n\t\t\t\tint month = ThreeCharMonthToInteger( reg.results[2].str.c_str() );\r\n\t\t\t\tint day = _wtoi( reg.results[3].str.c_str() );\r\n\t\t\t\tint hour = _wtoi( reg.results[4].str.c_str() );\r\n\t\t\t\tint minute = _wtoi( reg.results[5].str.c_str() );\r\n\t\t\t\tint sec = _wtoi( reg.results[6].str.c_str() );\r\n\r\n\t\t\t\tCTime t(year, month, day, hour, minute, sec);\r\n\r\n\t\t\t\tint diff = _wtoi( reg.results[7].str.c_str() );\r\n\t\t\t\tif (diff==0) {\r\n\t\t\t\t\tt += CTimeSpan(0, 9, 0, 0);\r\n\t\t\t\t}\r\n\t\t\t\tt_result = t;\r\n\t\t\t\treturn true;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t\/\/ T4. RSS 2.0 ` (Mon, 16 Dec 2007 09:00:00 +0900)\r\n\t\t\/\/ T4. RSS 2.0 ` (Mon, 16 Dec 2007 09:00:00 GMT)\r\n\t\t{\r\n\t\t\t\/\/ K\\̃RpC\r\n\t\t\tstatic MyRegex reg;\r\n\t\t\tif( !util::CompileRegex( reg, L\"([a-zA-Z]{3}), ([0-9]{2}) ([a-zA-Z]{3}) ([0-9]{4}) ([0-9]{2}):([0-9]{2}):([0-9]{2}) (.*)\" ) ) {\r\n\t\t\t\treturn false;\r\n\t\t\t}\r\n\t\t\t\/\/ \r\n\t\t\tif( reg.exec(line) && reg.results.size() == 9 ) {\r\n\t\t\t\t\/\/ o\r\n\r\n\t\t\t\t\/\/ N\r\n\t\t\t\tint year = _wtoi( reg.results[4].str.c_str() );\r\n\r\n\t\t\t\t\/\/ \r\n\t\t\t\tint month = ThreeCharMonthToInteger( reg.results[3].str.c_str() );\r\n\t\t\t\tint day = _wtoi( reg.results[2].str.c_str() );\r\n\t\t\t\tint hour = _wtoi( reg.results[5].str.c_str() );\r\n\t\t\t\tint minute = _wtoi( reg.results[6].str.c_str() );\r\n\t\t\t\tint sec = _wtoi( reg.results[7].str.c_str() );\r\n\t\t\t\tCTime t(year, month, day, hour, minute, sec);\r\n\r\n\t\t\t\t\/\/ ȈՎϊ\r\n\t\t\t\tconst std::wstring& time_diff = reg.results[8].str;\r\n\r\n\t\t\t\tif (time_diff==L\"GMT\") {\r\n\t\t\t\t\tt += CTimeSpan(0, 9, 0, 0);\r\n\t\t\t\t}\r\n\r\n\t\t\t\tt_result = t;\r\n\t\t\t\treturn true;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t\/\/ T5. epoch ` (1219927284)\r\n\t\t{\r\n\t\t\t\/\/ K\\̃RpC\r\n\t\t\tstatic MyRegex reg;\r\n\t\t\tif( !util::CompileRegex( reg, L\"^([0-9]*)$\" ) ) {\r\n\t\t\t\treturn false;\r\n\t\t\t}\r\n\t\t\t\/\/ \r\n\t\t\tif( reg.exec(line) && reg.results.size() == 2 ) {\r\n\t\t\t\t\/\/ o\r\n\r\n\t\t\t\tt_result = CTime(_wtoi(reg.results[1].str.c_str()));\r\n\r\n\t\t\t\treturn true;\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn false;\r\n\t}\r\n\r\n}\r\n<|endoftext|>"} {"text":"<commit_before>#include \"HalideRuntime.h\"\n#include \"HalideRuntimeCuda.h\"\n#include \"HalideRuntimeOpenGL.h\"\n#include \"HalideRuntimeOpenCL.h\"\n#include \"HalideRuntimeRenderscript.h\"\n#include \"runtime_internal.h\"\n\n\/\/ This runtime module will contain extern declarations of the Halide\n\/\/ API and the types it uses. It's useful for compiling modules that\n\/\/ use the API without including a copy of it (e.g. JIT, NoRuntime).\n\n\/\/ Can be generated via the following:\n\/\/ cat src\/runtime\/runtime_internal.h src\/runtime\/HalideRuntime*.h | grep \"^[^ ][^(]*halide_[^ ]*(\" | grep -v '#define' | sed \"s\/[^(]*halide\/halide\/\" | sed \"s\/(.*\/\/\" | sed \"s\/^h\/ \\(void *)\\&h\/\" | sed \"s\/$\/,\/\" | sort | uniq\n\nnamespace {\n__attribute__((used)) void *runtime_api_functions[] = {\n (void *)&halide_copy_to_device,\n (void *)&halide_copy_to_host,\n (void *)&halide_cuda_detach_device_ptr,\n (void *)&halide_cuda_device_interface,\n (void *)&halide_cuda_get_device_ptr,\n (void *)&halide_cuda_initialize_kernels,\n (void *)&halide_cuda_run,\n (void *)&halide_cuda_wrap_device_ptr,\n (void *)&halide_current_time_ns,\n (void *)&halide_debug_to_file,\n (void *)&halide_device_free,\n (void *)&halide_device_free_as_destructor,\n (void *)&halide_device_malloc,\n (void *)&halide_device_release,\n (void *)&halide_device_sync,\n (void *)&halide_do_par_for,\n (void *)&halide_double_to_string,\n (void *)&halide_enumerate_registered_filters,\n (void *)&halide_error,\n (void *)&halide_error_access_out_of_bounds,\n (void *)&halide_error_bad_elem_size,\n (void *)&halide_error_bounds_inference_call_failed,\n (void *)&halide_error_buffer_allocation_too_large,\n (void *)&halide_error_buffer_argument_is_null,\n (void *)&halide_error_buffer_extents_too_large,\n (void *)&halide_error_constraints_make_required_region_smaller,\n (void *)&halide_error_constraint_violated,\n (void *)&halide_error_debug_to_file_failed,\n (void *)&halide_error_explicit_bounds_too_small,\n (void *)&halide_error_extern_stage_failed,\n (void *)&halide_error_out_of_memory,\n (void *)&halide_error_param_too_large_f64,\n (void *)&halide_error_param_too_large_i64,\n (void *)&halide_error_param_too_large_u64,\n (void *)&halide_error_param_too_small_f64,\n (void *)&halide_error_param_too_small_i64,\n (void *)&halide_error_param_too_small_u64,\n (void *)&halide_free,\n (void *)&halide_get_gpu_device,\n (void *)&halide_get_library_symbol,\n (void *)&halide_get_symbol,\n (void *)&halide_get_trace_file,\n (void *)&halide_int64_to_string,\n (void *)&halide_load_library,\n (void *)&halide_malloc,\n (void *)&halide_memoization_cache_cleanup,\n (void *)&halide_memoization_cache_lookup,\n (void *)&halide_memoization_cache_set_size,\n (void *)&halide_memoization_cache_store,\n (void *)&halide_mutex_cleanup,\n (void *)&halide_mutex_lock,\n (void *)&halide_mutex_unlock,\n (void *)&halide_opencl_detach_cl_mem,\n (void *)&halide_opencl_device_interface,\n (void *)&halide_opencl_get_cl_mem,\n (void *)&halide_opencl_get_device_type,\n (void *)&halide_opencl_get_platform_name,\n (void *)&halide_opencl_initialize_kernels,\n (void *)&halide_opencl_run,\n (void *)&halide_opencl_set_device_type,\n (void *)&halide_opencl_set_platform_name,\n (void *)&halide_opencl_wrap_cl_mem,\n (void *)&halide_opengl_context_lost,\n (void *)&halide_opengl_create_context,\n (void *)&halide_opengl_detach_texture,\n (void *)&halide_opengl_device_interface,\n (void *)&halide_opengl_get_proc_address,\n (void *)&halide_opengl_get_texture,\n (void *)&halide_opengl_initialize_kernels,\n (void *)&halide_opengl_run,\n (void *)&halide_opengl_wrap_render_target,\n (void *)&halide_opengl_wrap_texture,\n (void *)&halide_pointer_to_string,\n (void *)&halide_print,\n (void *)&halide_release_jit_module,\n (void *)&halide_renderscript_device_interface,\n (void *)&halide_renderscript_initialize_kernels,\n (void *)&halide_renderscript_run,\n (void *)&halide_set_gpu_device,\n (void *)&halide_set_num_threads,\n (void *)&halide_set_trace_file,\n (void *)&halide_shutdown_thread_pool,\n (void *)&halide_shutdown_trace,\n (void *)&halide_start_clock,\n (void *)&halide_string_to_string,\n (void *)&halide_trace,\n (void *)&halide_uint64_to_string,\n (void *)&halide_use_jit_module\n};\n}\n<commit_msg>Add some more runtime functions to the runtime_api list<commit_after>#include \"HalideRuntime.h\"\n#include \"HalideRuntimeCuda.h\"\n#include \"HalideRuntimeOpenGL.h\"\n#include \"HalideRuntimeOpenCL.h\"\n#include \"HalideRuntimeRenderscript.h\"\n#include \"runtime_internal.h\"\n\n\/\/ This runtime module will contain extern declarations of the Halide\n\/\/ API and the types it uses. It's useful for compiling modules that\n\/\/ use the API without including a copy of it (e.g. JIT, NoRuntime).\n\n\/\/ Can be generated via the following:\n\/\/ cat src\/runtime\/runtime_internal.h src\/runtime\/HalideRuntime*.h | grep \"^[^ ][^(]*halide_[^ ]*(\" | grep -v '#define' | sed \"s\/[^(]*halide\/halide\/\" | sed \"s\/(.*\/\/\" | sed \"s\/^h\/ \\(void *)\\&h\/\" | sed \"s\/$\/,\/\" | sort | uniq\n\nnamespace {\n__attribute__((used)) void *runtime_api_functions[] = {\n (void *)&halide_copy_to_device,\n (void *)&halide_copy_to_host,\n (void *)&halide_cuda_detach_device_ptr,\n (void *)&halide_cuda_device_interface,\n (void *)&halide_cuda_get_device_ptr,\n (void *)&halide_cuda_initialize_kernels,\n (void *)&halide_cuda_run,\n (void *)&halide_cuda_wrap_device_ptr,\n (void *)&halide_current_time_ns,\n (void *)&halide_debug_to_file,\n (void *)&halide_device_free,\n (void *)&halide_device_free_as_destructor,\n (void *)&halide_device_malloc,\n (void *)&halide_device_release,\n (void *)&halide_device_sync,\n (void *)&halide_do_par_for,\n (void *)&halide_double_to_string,\n (void *)&halide_enumerate_registered_filters,\n (void *)&halide_error,\n (void *)&halide_error_access_out_of_bounds,\n (void *)&halide_error_bad_elem_size,\n (void *)&halide_error_bounds_inference_call_failed,\n (void *)&halide_error_buffer_allocation_too_large,\n (void *)&halide_error_buffer_argument_is_null,\n (void *)&halide_error_buffer_extents_too_large,\n (void *)&halide_error_constraints_make_required_region_smaller,\n (void *)&halide_error_constraint_violated,\n (void *)&halide_error_debug_to_file_failed,\n (void *)&halide_error_explicit_bounds_too_small,\n (void *)&halide_error_extern_stage_failed,\n (void *)&halide_error_out_of_memory,\n (void *)&halide_error_param_too_large_f64,\n (void *)&halide_error_param_too_large_i64,\n (void *)&halide_error_param_too_large_u64,\n (void *)&halide_error_param_too_small_f64,\n (void *)&halide_error_param_too_small_i64,\n (void *)&halide_error_param_too_small_u64,\n (void *)&halide_free,\n (void *)&halide_get_gpu_device,\n (void *)&halide_get_library_symbol,\n (void *)&halide_get_symbol,\n (void *)&halide_get_trace_file,\n (void *)&halide_int64_to_string,\n (void *)&halide_load_library,\n (void *)&halide_malloc,\n (void *)&halide_memoization_cache_cleanup,\n (void *)&halide_memoization_cache_lookup,\n (void *)&halide_memoization_cache_set_size,\n (void *)&halide_memoization_cache_store,\n (void *)&halide_mutex_cleanup,\n (void *)&halide_mutex_lock,\n (void *)&halide_mutex_unlock,\n (void *)&halide_opencl_detach_cl_mem,\n (void *)&halide_opencl_device_interface,\n (void *)&halide_opencl_get_cl_mem,\n (void *)&halide_opencl_get_device_type,\n (void *)&halide_opencl_get_platform_name,\n (void *)&halide_opencl_initialize_kernels,\n (void *)&halide_opencl_run,\n (void *)&halide_opencl_set_device_type,\n (void *)&halide_opencl_set_platform_name,\n (void *)&halide_opencl_wrap_cl_mem,\n (void *)&halide_opengl_context_lost,\n (void *)&halide_opengl_create_context,\n (void *)&halide_opengl_detach_texture,\n (void *)&halide_opengl_device_interface,\n (void *)&halide_opengl_get_proc_address,\n (void *)&halide_opengl_get_texture,\n (void *)&halide_opengl_initialize_kernels,\n (void *)&halide_opengl_run,\n (void *)&halide_opengl_wrap_render_target,\n (void *)&halide_opengl_wrap_texture,\n (void *)&halide_pointer_to_string,\n (void *)&halide_print,\n (void *)&halide_profiler_pipeline_start,\n (void *)&halide_profiler_get_state,\n (void *)&halide_profiler_reset,\n (void *)&halide_profiler_report,\n (void *)&halide_release_jit_module,\n (void *)&halide_renderscript_device_interface,\n (void *)&halide_renderscript_initialize_kernels,\n (void *)&halide_renderscript_run,\n (void *)&halide_set_gpu_device,\n (void *)&halide_set_num_threads,\n (void *)&halide_set_trace_file,\n (void *)&halide_shutdown_thread_pool,\n (void *)&halide_shutdown_trace,\n (void *)&halide_start_clock,\n (void *)&halide_string_to_string,\n (void *)&halide_trace,\n (void *)&halide_uint64_to_string,\n (void *)&halide_use_jit_module\n};\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright 2015 BrewPi\/Elco Jacobs.\n *\n * This file is part of BrewPi.\n *\n * BrewPi is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * BrewPi is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with BrewPi. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n\n\n\n#include \"Control.h\"\n\n#include <vector>\n#include \"Pid.h\"\n#include \"defaultDevices.h\"\n#include \"ActuatorInterfaces.h\"\n#include \"ActuatorPwm.h\"\n#include \"ActuatorTimeLimited.h\"\n#include \"TempSensor.h\"\n#include \"ActuatorSetPoint.h\"\n#include \"ActuatorMutexDriver.h\"\n#include \"ActuatorMutexGroup.h\"\n#include \"json_writer.h\"\n\nControl::Control()\n{\n \/\/ set up static devices for backwards compatibility with tempControl\n beer1Sensor = new TempSensor(defaultTempSensorBasic());\n beer1Sensor->setName(\"beer1\");\n beer2Sensor = new TempSensor(defaultTempSensorBasic());\n beer2Sensor->setName(\"beer2\");\n fridgeSensor = new TempSensor(defaultTempSensorBasic());\n fridgeSensor->setName(\"fridge\");\n\n mutex = new ActuatorMutexGroup();\n\n heater1Mutex = new ActuatorMutexDriver(defaultActuator(), mutex);\n heater1 = new ActuatorPwm(heater1Mutex, 4); \/\/ period 4s\n\n heater2Mutex = new ActuatorMutexDriver(defaultActuator(), mutex);\n heater2 = new ActuatorPwm(heater2Mutex, 4); \/\/ period 4s\n\n coolerTimeLimited = new ActuatorTimeLimited(defaultActuator(), 120, 180); \/\/ 2 min minOn time, 3 min minOff\n coolerMutex = new ActuatorMutexDriver(coolerTimeLimited, mutex);\n cooler = new ActuatorPwm(coolerMutex, 1200); \/\/ period 20 min\n\n beer1Set = new SetPointSimple();\n beer2Set = new SetPointSimple();\n fridgeSet = new SetPointSimple();\n\n fridgeSetPointActuator = new ActuatorSetPoint(fridgeSet, fridgeSensor, beer1Set);\n fridgeSetPointActuator->setMin(-10.0);\n fridgeSetPointActuator->setMax(10.0);\n\n heater1Pid = new Pid(fridgeSensor, heater1, fridgeSet);\n heater1Pid->setName(\"heater1\");\n\n coolerPid = new Pid(fridgeSensor, cooler, fridgeSet);\n coolerPid->setActuatorIsNegative(true);\n coolerPid->setName(\"cooler\");\n\n heater2Pid = new Pid(beer2Sensor, heater2, beer2Set);\n heater2Pid->setName(\"heater2\");\n\n beerToFridgePid = new Pid(beer1Sensor, fridgeSetPointActuator, beer1Set);\n beerToFridgePid->setName(\"beer2fridge\");\n\n pids.push_back(heater1Pid);\n pids.push_back(heater2Pid);\n pids.push_back(coolerPid);\n pids.push_back(beerToFridgePid);\n\n sensors.push_back(fridgeSensor);\n sensors.push_back(beer1Sensor);\n sensors.push_back(beer2Sensor);\n\n actuators.push_back(cooler);\n actuators.push_back(heater1);\n actuators.push_back(heater2);\n\n beer1SetNamed = new SetPointNamed(beer1Set);\n beer1SetNamed->setName(\"beer1set\");\n beer2SetNamed = new SetPointNamed(beer2Set);\n beer1SetNamed->setName(\"beer2set\");\n fridgeSetNamed = new SetPointNamed(fridgeSet);\n fridgeSetNamed->setName(\"fridgeset\");\n\n setpoints.push_back(beer1SetNamed);\n setpoints.push_back(beer2SetNamed);\n setpoints.push_back(fridgeSetNamed);\n\n mutex->setDeadTime(1800000); \/\/ 30 minutes\n}\n\nControl::~Control(){\n \/\/ in practice this is never used since the instance is global\n\n#if 0\n delete heater1Mutex;\n delete heater1;\n\n delete heater2Mutex;\n delete heater2;\n\n delete coolerTimeLimited;\n delete coolerMutex;\n delete cooler;\n\n delete fridgeSetPointActuator;\n\n delete beer1Set;\n delete beer2Set;\n delete fridgeSet;\n\n delete beer1SetNamed;\n delete beer2SetNamed;\n delete fridgeSetNamed;\n\n delete mutex;\n\n delete heater1Pid;\n delete heater2Pid;\n delete coolerPid;\n delete beerToFridgePid;\n\n pids.clear();\n sensors.clear();\n actuators.clear();\n#endif\n}\n\n\/\/ This update function should be called every second\nvoid Control::update(){\n updateSensors();\n updatePids();\n updateActuators();\n mutex->update();\n}\n\nvoid Control::updatePids(){\n for ( auto &pid : pids ) {\n pid->update();\n }\n}\n\n\/\/ The actuator update should be called often to generate the PWM signal\nvoid Control::updateSensors(){\n for ( auto &sensor : sensors ) {\n sensor->update();\n }\n}\n\nvoid Control::updateActuators(){\n for ( auto &actuator : actuators ) {\n actuator->update();\n }\n}\n\nvoid Control::serialize(JSON::Adapter& adapter){\n JSON::Class root(adapter, \"Control\");\n JSON_E(adapter, pids);\n JSON_E(adapter, sensors);\n JSON_E(adapter, actuators);\n JSON_T(adapter, setpoints);\n}\n\nControl control;\n<commit_msg>only use empty Control destructor when building for embedded<commit_after>\/*\n * Copyright 2015 BrewPi\/Elco Jacobs.\n *\n * This file is part of BrewPi.\n *\n * BrewPi is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * BrewPi is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with BrewPi. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n\n\n\n#include \"Control.h\"\n\n#include <vector>\n#include \"Pid.h\"\n#include \"defaultDevices.h\"\n#include \"ActuatorInterfaces.h\"\n#include \"ActuatorPwm.h\"\n#include \"ActuatorTimeLimited.h\"\n#include \"TempSensor.h\"\n#include \"ActuatorSetPoint.h\"\n#include \"ActuatorMutexDriver.h\"\n#include \"ActuatorMutexGroup.h\"\n#include \"json_writer.h\"\n\nControl::Control()\n{\n \/\/ set up static devices for backwards compatibility with tempControl\n beer1Sensor = new TempSensor(defaultTempSensorBasic());\n beer1Sensor->setName(\"beer1\");\n beer2Sensor = new TempSensor(defaultTempSensorBasic());\n beer2Sensor->setName(\"beer2\");\n fridgeSensor = new TempSensor(defaultTempSensorBasic());\n fridgeSensor->setName(\"fridge\");\n\n mutex = new ActuatorMutexGroup();\n\n heater1Mutex = new ActuatorMutexDriver(defaultActuator(), mutex);\n heater1 = new ActuatorPwm(heater1Mutex, 4); \/\/ period 4s\n\n heater2Mutex = new ActuatorMutexDriver(defaultActuator(), mutex);\n heater2 = new ActuatorPwm(heater2Mutex, 4); \/\/ period 4s\n\n coolerTimeLimited = new ActuatorTimeLimited(defaultActuator(), 120, 180); \/\/ 2 min minOn time, 3 min minOff\n coolerMutex = new ActuatorMutexDriver(coolerTimeLimited, mutex);\n cooler = new ActuatorPwm(coolerMutex, 1200); \/\/ period 20 min\n\n beer1Set = new SetPointSimple();\n beer2Set = new SetPointSimple();\n fridgeSet = new SetPointSimple();\n\n fridgeSetPointActuator = new ActuatorSetPoint(fridgeSet, fridgeSensor, beer1Set);\n fridgeSetPointActuator->setMin(-10.0);\n fridgeSetPointActuator->setMax(10.0);\n\n heater1Pid = new Pid(fridgeSensor, heater1, fridgeSet);\n heater1Pid->setName(\"heater1\");\n\n coolerPid = new Pid(fridgeSensor, cooler, fridgeSet);\n coolerPid->setActuatorIsNegative(true);\n coolerPid->setName(\"cooler\");\n\n heater2Pid = new Pid(beer2Sensor, heater2, beer2Set);\n heater2Pid->setName(\"heater2\");\n\n beerToFridgePid = new Pid(beer1Sensor, fridgeSetPointActuator, beer1Set);\n beerToFridgePid->setName(\"beer2fridge\");\n\n pids.push_back(heater1Pid);\n pids.push_back(heater2Pid);\n pids.push_back(coolerPid);\n pids.push_back(beerToFridgePid);\n\n sensors.push_back(fridgeSensor);\n sensors.push_back(beer1Sensor);\n sensors.push_back(beer2Sensor);\n\n actuators.push_back(cooler);\n actuators.push_back(heater1);\n actuators.push_back(heater2);\n\n beer1SetNamed = new SetPointNamed(beer1Set);\n beer1SetNamed->setName(\"beer1set\");\n beer2SetNamed = new SetPointNamed(beer2Set);\n beer1SetNamed->setName(\"beer2set\");\n fridgeSetNamed = new SetPointNamed(fridgeSet);\n fridgeSetNamed->setName(\"fridgeset\");\n\n setpoints.push_back(beer1SetNamed);\n setpoints.push_back(beer2SetNamed);\n setpoints.push_back(fridgeSetNamed);\n\n mutex->setDeadTime(1800000); \/\/ 30 minutes\n}\n\nControl::~Control(){\n#if defined(ARDUINO) || defined(SPARK)\n \/\/ global control object is static and never destroyed.\n \/\/ omit proper destructor to save space.\n#else\n delete heater1Mutex;\n delete heater1;\n\n delete heater2Mutex;\n delete heater2;\n\n delete coolerTimeLimited;\n delete coolerMutex;\n delete cooler;\n\n delete fridgeSetPointActuator;\n\n delete beer1Set;\n delete beer2Set;\n delete fridgeSet;\n\n delete beer1SetNamed;\n delete beer2SetNamed;\n delete fridgeSetNamed;\n\n delete mutex;\n\n delete heater1Pid;\n delete heater2Pid;\n delete coolerPid;\n delete beerToFridgePid;\n\n pids.clear();\n sensors.clear();\n actuators.clear();\n#endif\n}\n\n\/\/ This update function should be called every second\nvoid Control::update(){\n updateSensors();\n updatePids();\n updateActuators();\n mutex->update();\n}\n\nvoid Control::updatePids(){\n for ( auto &pid : pids ) {\n pid->update();\n }\n}\n\n\/\/ The actuator update should be called often to generate the PWM signal\nvoid Control::updateSensors(){\n for ( auto &sensor : sensors ) {\n sensor->update();\n }\n}\n\nvoid Control::updateActuators(){\n for ( auto &actuator : actuators ) {\n actuator->update();\n }\n}\n\nvoid Control::serialize(JSON::Adapter& adapter){\n JSON::Class root(adapter, \"Control\");\n JSON_E(adapter, pids);\n JSON_E(adapter, sensors);\n JSON_E(adapter, actuators);\n JSON_T(adapter, setpoints);\n}\n\nControl control;\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/external_tab_container.h\"\n\n#include \"app\/win_util.h\"\n#include \"base\/logging.h\"\n#include \"base\/win_util.h\"\n#include \"chrome\/browser\/automation\/automation_provider.h\"\n#include \"chrome\/browser\/browser.h\"\n#include \"chrome\/browser\/extensions\/extension_function_dispatcher.h\"\n#include \"chrome\/browser\/load_notification_details.h\"\n#include \"chrome\/browser\/profile.h\"\n#include \"chrome\/browser\/tab_contents\/provisional_load_details.h\"\n#include \"chrome\/browser\/tab_contents\/tab_contents.h\"\n#include \"chrome\/browser\/views\/tab_contents\/tab_contents_container.h\"\n#include \"chrome\/common\/chrome_constants.h\"\n#include \"chrome\/common\/notification_service.h\"\n#include \"chrome\/test\/automation\/automation_messages.h\"\n\nstatic const wchar_t kWindowObjectKey[] = L\"ChromeWindowObject\";\n\n\/\/ TODO(sanjeevr): The external_accel_table_ and external_accel_entry_count_\n\/\/ member variables are now obsolete and we don't use them.\n\/\/ We need to remove them.\nExternalTabContainer::ExternalTabContainer(\n AutomationProvider* automation)\n : automation_(automation),\n tab_contents_(NULL),\n external_accel_table_(NULL),\n external_accel_entry_count_(0),\n tab_contents_container_(NULL),\n tab_handle_(0),\n ignore_next_load_notification_(false) {\n}\n\nExternalTabContainer::~ExternalTabContainer() {\n Uninitialize(GetNativeView());\n}\n\nbool ExternalTabContainer::Init(Profile* profile,\n HWND parent,\n const gfx::Rect& bounds,\n DWORD style) {\n if (IsWindow()) {\n NOTREACHED();\n return false;\n }\n\n set_window_style(WS_POPUP);\n views::WidgetWin::Init(NULL, bounds, true);\n if (!IsWindow()) {\n NOTREACHED();\n return false;\n }\n\n \/\/ We don't ever remove the prop because the lifetime of this object\n \/\/ is the same as the lifetime of the window\n SetProp(GetNativeView(), kWindowObjectKey, this);\n\n views::FocusManager* focus_manager =\n views::FocusManager::GetFocusManager(GetNativeView());\n focus_manager->AddKeystrokeListener(this);\n\n tab_contents_ = new TabContents(profile, NULL, MSG_ROUTING_NONE, NULL);\n tab_contents_->set_delegate(this);\n tab_contents_->render_view_host()->AllowExternalHostBindings();\n\n \/\/ Create a TabContentsContainer to handle focus cycling using Tab and\n \/\/ Shift-Tab.\n tab_contents_container_ = new TabContentsContainer;\n SetContentsView(tab_contents_container_);\n\n \/\/ Note that SetTabContents must be called after AddChildView is called\n tab_contents_container_->ChangeTabContents(tab_contents_);\n\n NavigationController* controller = &tab_contents_->controller();\n registrar_.Add(this, NotificationType::NAV_ENTRY_COMMITTED,\n Source<NavigationController>(controller));\n registrar_.Add(this, NotificationType::FAIL_PROVISIONAL_LOAD_WITH_ERROR,\n Source<NavigationController>(controller));\n registrar_.Add(this, NotificationType::LOAD_STOP,\n Source<NavigationController>(controller));\n NotificationService::current()->Notify(\n NotificationType::EXTERNAL_TAB_CREATED,\n Source<NavigationController>(controller),\n NotificationService::NoDetails());\n\n \/\/ We need WS_POPUP to be on the window during initialization, but\n \/\/ once initialized we apply the requested style which may or may not\n \/\/ include the popup bit.\n \/\/ Note that it's important to do this before we call SetParent since\n \/\/ during the SetParent call we will otherwise get a WA_ACTIVATE call\n \/\/ that causes us to steal the current focus.\n SetWindowLong(GWL_STYLE, (GetWindowLong(GWL_STYLE) & ~WS_POPUP) | style);\n\n \/\/ Now apply the parenting and style\n if (parent)\n SetParent(GetNativeView(), parent);\n\n ::ShowWindow(tab_contents_->GetNativeView(), SW_SHOWNA);\n return true;\n}\n\nvoid ExternalTabContainer::SetAccelerators(HACCEL accel_table,\n int accel_table_entry_count) {\n external_accel_table_ = accel_table;\n external_accel_entry_count_ = accel_table_entry_count;\n}\n\nvoid ExternalTabContainer::ProcessUnhandledAccelerator(const MSG& msg) {\n \/\/ We just received an accelerator key that we had sent to external host\n \/\/ back. Since the external host was not interested in handling this, we\n \/\/ need to dispatch this message as if we had just peeked this out. (we\n \/\/ also need to call TranslateMessage to generate a WM_CHAR if needed).\n TranslateMessage(&msg);\n DispatchMessage(&msg);\n}\n\nvoid ExternalTabContainer::SetInitialFocus(bool reverse) {\n DCHECK(tab_contents_);\n if (tab_contents_) {\n static_cast<TabContents*>(tab_contents_)->Focus();\n static_cast<TabContents*>(tab_contents_)->SetInitialFocus(reverse);\n }\n}\n\n\/\/ static\nbool ExternalTabContainer::IsExternalTabContainer(HWND window) {\n if (GetProp(window, kWindowObjectKey) != NULL)\n return true;\n\n return false;\n}\n\n\/\/ static\nExternalTabContainer* ExternalTabContainer::GetContainerForTab(\n HWND tab_window) {\n HWND parent_window = ::GetParent(tab_window);\n if (!::IsWindow(parent_window)) {\n return NULL;\n }\n if (!IsExternalTabContainer(parent_window)) {\n return NULL;\n }\n ExternalTabContainer* container = reinterpret_cast<ExternalTabContainer*>(\n GetProp(parent_window, kWindowObjectKey));\n return container;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ ExternalTabContainer, TabContentsDelegate implementation:\n\nvoid ExternalTabContainer::OpenURLFromTab(TabContents* source,\n const GURL& url,\n const GURL& referrer,\n WindowOpenDisposition disposition,\n PageTransition::Type transition) {\n switch (disposition) {\n case CURRENT_TAB:\n case SINGLETON_TAB:\n case NEW_FOREGROUND_TAB:\n case NEW_BACKGROUND_TAB:\n case NEW_WINDOW:\n if (automation_) {\n automation_->Send(new AutomationMsg_OpenURL(0, tab_handle_,\n url, disposition));\n }\n break;\n default:\n break;\n }\n}\n\nvoid ExternalTabContainer::NavigationStateChanged(const TabContents* source,\n unsigned changed_flags) {\n if (automation_) {\n automation_->Send(new AutomationMsg_NavigationStateChanged(0, tab_handle_,\n changed_flags));\n }\n}\n\nvoid ExternalTabContainer::AddNewContents(TabContents* source,\n TabContents* new_contents,\n WindowOpenDisposition disposition,\n const gfx::Rect& initial_pos,\n bool user_gesture) {\n if (disposition == NEW_POPUP || disposition == NEW_WINDOW ||\n disposition == NEW_FOREGROUND_TAB || disposition == NEW_BACKGROUND_TAB) {\n Browser::BuildPopupWindowHelper(source, new_contents, initial_pos,\n Browser::TYPE_POPUP,\n tab_contents_->profile(), true);\n } else {\n NOTREACHED();\n }\n}\n\nvoid ExternalTabContainer::ActivateContents(TabContents* contents) {\n}\n\nvoid ExternalTabContainer::LoadingStateChanged(TabContents* source) {\n}\n\nvoid ExternalTabContainer::CloseContents(TabContents* source) {\n}\n\nvoid ExternalTabContainer::MoveContents(TabContents* source,\n const gfx::Rect& pos) {\n}\n\nbool ExternalTabContainer::IsPopup(TabContents* source) {\n return false;\n}\n\nvoid ExternalTabContainer::URLStarredChanged(TabContents* source,\n bool starred) {\n}\n\nvoid ExternalTabContainer::UpdateTargetURL(TabContents* source,\n const GURL& url) {\n if (automation_) {\n std::wstring url_string = CA2W(url.spec().c_str());\n automation_->Send(\n new AutomationMsg_UpdateTargetUrl(0, tab_handle_, url_string));\n }\n}\n\nvoid ExternalTabContainer::ContentsZoomChange(bool zoom_in) {\n}\n\nvoid ExternalTabContainer::ToolbarSizeChanged(TabContents* source,\n bool finished) {\n}\n\nvoid ExternalTabContainer::ForwardMessageToExternalHost(\n const std::string& message, const std::string& origin,\n const std::string& target) {\n if (automation_) {\n automation_->Send(\n new AutomationMsg_ForwardMessageToExternalHost(0, tab_handle_,\n message, origin, target));\n }\n}\n\nExtensionFunctionDispatcher* ExternalTabContainer::\n CreateExtensionFunctionDispatcher(RenderViewHost* render_view_host,\n const std::string& extension_id) {\n return new ExtensionFunctionDispatcher(render_view_host, NULL, extension_id);\n}\n\nbool ExternalTabContainer::TakeFocus(bool reverse) {\n if (automation_) {\n views::FocusManager* focus_manager =\n views::FocusManager::GetFocusManager(GetNativeView());\n DCHECK(focus_manager);\n if (focus_manager) {\n focus_manager->ClearFocus();\n automation_->Send(new AutomationMsg_TabbedOut(0, tab_handle_,\n win_util::IsShiftPressed()));\n }\n }\n\n return true;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ ExternalTabContainer, NotificationObserver implementation:\n\nvoid ExternalTabContainer::Observe(NotificationType type,\n const NotificationSource& source,\n const NotificationDetails& details) {\n if (!automation_)\n return;\n\n static const int kHttpClientErrorStart = 400;\n static const int kHttpServerErrorEnd = 510;\n\n switch (type.value) {\n case NotificationType::LOAD_STOP: {\n const LoadNotificationDetails* load =\n Details<LoadNotificationDetails>(details).ptr();\n if (load != NULL && PageTransition::IsMainFrame(load->origin())) {\n automation_->Send(new AutomationMsg_TabLoaded(0, tab_handle_,\n load->url()));\n }\n break;\n }\n case NotificationType::NAV_ENTRY_COMMITTED: {\n if (ignore_next_load_notification_) {\n ignore_next_load_notification_ = false;\n return;\n }\n\n const NavigationController::LoadCommittedDetails* commit =\n Details<NavigationController::LoadCommittedDetails>(details).ptr();\n\n if (commit->http_status_code >= kHttpClientErrorStart &&\n commit->http_status_code <= kHttpServerErrorEnd) {\n automation_->Send(new AutomationMsg_NavigationFailed(\n 0, tab_handle_, commit->http_status_code, commit->entry->url()));\n\n ignore_next_load_notification_ = true;\n } else {\n \/\/ When the previous entry index is invalid, it will be -1, which\n \/\/ will still make the computation come out right (navigating to the\n \/\/ 0th entry will be +1).\n automation_->Send(new AutomationMsg_DidNavigate(\n 0, tab_handle_, commit->type,\n commit->previous_entry_index -\n tab_contents_->controller().last_committed_entry_index(),\n commit->entry->url()));\n }\n break;\n }\n case NotificationType::FAIL_PROVISIONAL_LOAD_WITH_ERROR: {\n const ProvisionalLoadDetails* load_details =\n Details<ProvisionalLoadDetails>(details).ptr();\n automation_->Send(new AutomationMsg_NavigationFailed(\n 0, tab_handle_, load_details->error_code(), load_details->url()));\n\n ignore_next_load_notification_ = true;\n break;\n }\n default:\n NOTREACHED();\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ ExternalTabContainer, views::WidgetWin overrides:\n\nvoid ExternalTabContainer::OnDestroy() {\n Uninitialize(GetNativeView());\n WidgetWin::OnDestroy();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ ExternalTabContainer, views::KeystrokeListener implementation:\n\nbool ExternalTabContainer::ProcessKeyStroke(HWND window, UINT message,\n WPARAM wparam, LPARAM lparam) {\n if (!automation_) {\n return false;\n }\n if ((wparam == VK_TAB) && !win_util::IsCtrlPressed()) {\n \/\/ Tabs are handled separately (except if this is Ctrl-Tab or\n \/\/ Ctrl-Shift-Tab)\n return false;\n }\n\n unsigned int flags = HIWORD(lparam);\n bool alt = (flags & KF_ALTDOWN) != 0;\n if (!alt && (message == WM_SYSKEYUP || message == WM_KEYUP)) {\n \/\/ In case the Alt key is being released.\n alt = (wparam == VK_MENU);\n }\n\n if ((flags & KF_EXTENDED) || alt || (wparam >= VK_F1 && wparam <= VK_F24) ||\n wparam == VK_ESCAPE || wparam == VK_RETURN ||\n win_util::IsShiftPressed() || win_util::IsCtrlPressed()) {\n \/\/ If this is an extended key or if one or more of Alt, Shift and Control\n \/\/ are pressed, this might be an accelerator that the external host wants\n \/\/ to handle. If the host does not handle this accelerator, it will reflect\n \/\/ the accelerator back to us via the ProcessUnhandledAccelerator method.\n MSG msg = {0};\n msg.hwnd = window;\n msg.message = message;\n msg.wParam = wparam;\n msg.lParam = lparam;\n automation_->Send(new AutomationMsg_HandleAccelerator(0, tab_handle_, msg));\n return true;\n }\n\n return false;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ ExternalTabContainer, private:\n\nvoid ExternalTabContainer::Uninitialize(HWND window) {\n if (::IsWindow(window)) {\n views::FocusManager* focus_manager =\n views::FocusManager::GetFocusManager(window);\n if (focus_manager)\n focus_manager->RemoveKeystrokeListener(this);\n }\n\n if (tab_contents_) {\n NotificationService::current()->Notify(\n NotificationType::EXTERNAL_TAB_CLOSED,\n Source<NavigationController>(&tab_contents_->controller()),\n Details<ExternalTabContainer>(this));\n\n delete tab_contents_;\n tab_contents_ = NULL;\n }\n}\n\n<commit_msg>Rollin' back 17315. Looks to be breaking OpenPopupWindowWithPlugin in the UI Test on the builder.<commit_after>\/\/ Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/external_tab_container.h\"\n\n#include \"app\/win_util.h\"\n#include \"base\/logging.h\"\n#include \"base\/win_util.h\"\n#include \"chrome\/browser\/automation\/automation_provider.h\"\n#include \"chrome\/browser\/browser.h\"\n#include \"chrome\/browser\/extensions\/extension_function_dispatcher.h\"\n#include \"chrome\/browser\/load_notification_details.h\"\n#include \"chrome\/browser\/profile.h\"\n#include \"chrome\/browser\/tab_contents\/provisional_load_details.h\"\n#include \"chrome\/browser\/tab_contents\/tab_contents.h\"\n#include \"chrome\/browser\/views\/tab_contents\/tab_contents_container.h\"\n#include \"chrome\/common\/chrome_constants.h\"\n#include \"chrome\/common\/notification_service.h\"\n#include \"chrome\/test\/automation\/automation_messages.h\"\n\nstatic const wchar_t kWindowObjectKey[] = L\"ChromeWindowObject\";\n\n\/\/ TODO(sanjeevr): The external_accel_table_ and external_accel_entry_count_\n\/\/ member variables are now obsolete and we don't use them.\n\/\/ We need to remove them.\nExternalTabContainer::ExternalTabContainer(\n AutomationProvider* automation)\n : automation_(automation),\n tab_contents_(NULL),\n external_accel_table_(NULL),\n external_accel_entry_count_(0),\n tab_contents_container_(NULL),\n tab_handle_(0),\n ignore_next_load_notification_(false) {\n}\n\nExternalTabContainer::~ExternalTabContainer() {\n Uninitialize(GetNativeView());\n}\n\nbool ExternalTabContainer::Init(Profile* profile,\n HWND parent,\n const gfx::Rect& bounds,\n DWORD style) {\n if (IsWindow()) {\n NOTREACHED();\n return false;\n }\n\n set_window_style(WS_POPUP);\n views::WidgetWin::Init(NULL, bounds, true);\n if (!IsWindow()) {\n NOTREACHED();\n return false;\n }\n\n \/\/ We don't ever remove the prop because the lifetime of this object\n \/\/ is the same as the lifetime of the window\n SetProp(GetNativeView(), kWindowObjectKey, this);\n\n views::FocusManager* focus_manager =\n views::FocusManager::GetFocusManager(GetNativeView());\n focus_manager->AddKeystrokeListener(this);\n\n tab_contents_ = new TabContents(profile, NULL, MSG_ROUTING_NONE, NULL);\n tab_contents_->set_delegate(this);\n tab_contents_->render_view_host()->AllowExternalHostBindings();\n\n \/\/ Create a TabContentsContainer to handle focus cycling using Tab and\n \/\/ Shift-Tab.\n tab_contents_container_ = new TabContentsContainer;\n SetContentsView(tab_contents_container_);\n\n \/\/ Note that SetTabContents must be called after AddChildView is called\n tab_contents_container_->ChangeTabContents(tab_contents_);\n\n NavigationController* controller = &tab_contents_->controller();\n registrar_.Add(this, NotificationType::NAV_ENTRY_COMMITTED,\n Source<NavigationController>(controller));\n registrar_.Add(this, NotificationType::FAIL_PROVISIONAL_LOAD_WITH_ERROR,\n Source<NavigationController>(controller));\n registrar_.Add(this, NotificationType::LOAD_STOP,\n Source<NavigationController>(controller));\n NotificationService::current()->Notify(\n NotificationType::EXTERNAL_TAB_CREATED,\n Source<NavigationController>(controller),\n NotificationService::NoDetails());\n\n \/\/ We need WS_POPUP to be on the window during initialization, but\n \/\/ once initialized we apply the requested style which may or may not\n \/\/ include the popup bit.\n \/\/ Note that it's important to do this before we call SetParent since\n \/\/ during the SetParent call we will otherwise get a WA_ACTIVATE call\n \/\/ that causes us to steal the current focus.\n SetWindowLong(GWL_STYLE, (GetWindowLong(GWL_STYLE) & ~WS_POPUP) | style);\n\n \/\/ Now apply the parenting and style\n if (parent)\n SetParent(GetNativeView(), parent);\n\n ::ShowWindow(tab_contents_->GetNativeView(), SW_SHOWNA);\n return true;\n}\n\nvoid ExternalTabContainer::SetAccelerators(HACCEL accel_table,\n int accel_table_entry_count) {\n external_accel_table_ = accel_table;\n external_accel_entry_count_ = accel_table_entry_count;\n}\n\nvoid ExternalTabContainer::ProcessUnhandledAccelerator(const MSG& msg) {\n \/\/ We just received an accelerator key that we had sent to external host\n \/\/ back. Since the external host was not interested in handling this, we\n \/\/ need to dispatch this message as if we had just peeked this out. (we\n \/\/ also need to call TranslateMessage to generate a WM_CHAR if needed).\n TranslateMessage(&msg);\n DispatchMessage(&msg);\n}\n\nvoid ExternalTabContainer::SetInitialFocus(bool reverse) {\n DCHECK(tab_contents_);\n if (tab_contents_) {\n static_cast<TabContents*>(tab_contents_)->Focus();\n static_cast<TabContents*>(tab_contents_)->SetInitialFocus(reverse);\n }\n}\n\n\/\/ static\nbool ExternalTabContainer::IsExternalTabContainer(HWND window) {\n if (GetProp(window, kWindowObjectKey) != NULL)\n return true;\n \n return false;\n}\n\n\/\/ static\nExternalTabContainer* ExternalTabContainer::GetContainerForTab(\n HWND tab_window) {\n HWND parent_window = ::GetParent(tab_window);\n if (!::IsWindow(parent_window)) {\n return NULL;\n }\n if (!IsExternalTabContainer(parent_window)) {\n return NULL;\n }\n ExternalTabContainer* container = reinterpret_cast<ExternalTabContainer*>(\n GetProp(parent_window, kWindowObjectKey));\n return container;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ ExternalTabContainer, TabContentsDelegate implementation:\n\nvoid ExternalTabContainer::OpenURLFromTab(TabContents* source,\n const GURL& url,\n const GURL& referrer,\n WindowOpenDisposition disposition,\n PageTransition::Type transition) {\n switch (disposition) {\n case CURRENT_TAB:\n case SINGLETON_TAB:\n case NEW_FOREGROUND_TAB:\n case NEW_BACKGROUND_TAB:\n case NEW_WINDOW:\n if (automation_) {\n automation_->Send(new AutomationMsg_OpenURL(0, tab_handle_,\n url, disposition));\n }\n break;\n default:\n break;\n }\n}\n\nvoid ExternalTabContainer::NavigationStateChanged(const TabContents* source,\n unsigned changed_flags) {\n if (automation_) {\n automation_->Send(new AutomationMsg_NavigationStateChanged(0, tab_handle_,\n changed_flags));\n }\n}\n\nvoid ExternalTabContainer::AddNewContents(TabContents* source,\n TabContents* new_contents,\n WindowOpenDisposition disposition,\n const gfx::Rect& initial_pos,\n bool user_gesture) {\n if (disposition == NEW_POPUP || disposition == NEW_WINDOW) {\n Browser::BuildPopupWindowHelper(source, new_contents, initial_pos,\n Browser::TYPE_POPUP,\n tab_contents_->profile(), true);\n } else {\n NOTREACHED();\n }\n}\n\nvoid ExternalTabContainer::ActivateContents(TabContents* contents) {\n}\n\nvoid ExternalTabContainer::LoadingStateChanged(TabContents* source) {\n}\n\nvoid ExternalTabContainer::CloseContents(TabContents* source) {\n}\n\nvoid ExternalTabContainer::MoveContents(TabContents* source,\n const gfx::Rect& pos) {\n}\n\nbool ExternalTabContainer::IsPopup(TabContents* source) {\n return false;\n}\n\nvoid ExternalTabContainer::URLStarredChanged(TabContents* source,\n bool starred) {\n}\n\nvoid ExternalTabContainer::UpdateTargetURL(TabContents* source,\n const GURL& url) {\n if (automation_) {\n std::wstring url_string = CA2W(url.spec().c_str());\n automation_->Send(\n new AutomationMsg_UpdateTargetUrl(0, tab_handle_, url_string));\n }\n}\n\nvoid ExternalTabContainer::ContentsZoomChange(bool zoom_in) {\n}\n\nvoid ExternalTabContainer::ToolbarSizeChanged(TabContents* source,\n bool finished) {\n}\n\nvoid ExternalTabContainer::ForwardMessageToExternalHost(\n const std::string& message, const std::string& origin,\n const std::string& target) {\n if(automation_) {\n automation_->Send(\n new AutomationMsg_ForwardMessageToExternalHost(0, tab_handle_,\n message, origin, target));\n }\n}\n\nExtensionFunctionDispatcher* ExternalTabContainer::\n CreateExtensionFunctionDispatcher(RenderViewHost* render_view_host,\n const std::string& extension_id) {\n return new ExtensionFunctionDispatcher(render_view_host, NULL, extension_id);\n}\n\nbool ExternalTabContainer::TakeFocus(bool reverse) {\n if (automation_) {\n views::FocusManager* focus_manager =\n views::FocusManager::GetFocusManager(GetNativeView());\n DCHECK(focus_manager);\n if (focus_manager) {\n focus_manager->ClearFocus();\n automation_->Send(new AutomationMsg_TabbedOut(0, tab_handle_,\n win_util::IsShiftPressed()));\n }\n }\n\n return true;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ ExternalTabContainer, NotificationObserver implementation:\n\nvoid ExternalTabContainer::Observe(NotificationType type,\n const NotificationSource& source,\n const NotificationDetails& details) {\n if (!automation_)\n return;\n\n static const int kHttpClientErrorStart = 400;\n static const int kHttpServerErrorEnd = 510;\n\n switch (type.value) {\n case NotificationType::LOAD_STOP: {\n const LoadNotificationDetails* load =\n Details<LoadNotificationDetails>(details).ptr();\n if (load != NULL && PageTransition::IsMainFrame(load->origin())) {\n automation_->Send(new AutomationMsg_TabLoaded(0, tab_handle_,\n load->url()));\n }\n break;\n }\n case NotificationType::NAV_ENTRY_COMMITTED: {\n if (ignore_next_load_notification_) {\n ignore_next_load_notification_ = false;\n return;\n }\n\n const NavigationController::LoadCommittedDetails* commit =\n Details<NavigationController::LoadCommittedDetails>(details).ptr();\n\n if (commit->http_status_code >= kHttpClientErrorStart &&\n commit->http_status_code <= kHttpServerErrorEnd) {\n automation_->Send(new AutomationMsg_NavigationFailed(\n 0, tab_handle_, commit->http_status_code, commit->entry->url()));\n\n ignore_next_load_notification_ = true;\n } else {\n \/\/ When the previous entry index is invalid, it will be -1, which\n \/\/ will still make the computation come out right (navigating to the\n \/\/ 0th entry will be +1).\n automation_->Send(new AutomationMsg_DidNavigate(\n 0, tab_handle_, commit->type,\n commit->previous_entry_index -\n tab_contents_->controller().last_committed_entry_index(),\n commit->entry->url()));\n }\n break;\n }\n case NotificationType::FAIL_PROVISIONAL_LOAD_WITH_ERROR: {\n const ProvisionalLoadDetails* load_details =\n Details<ProvisionalLoadDetails>(details).ptr();\n automation_->Send(new AutomationMsg_NavigationFailed(\n 0, tab_handle_, load_details->error_code(), load_details->url()));\n\n ignore_next_load_notification_ = true;\n break;\n }\n default:\n NOTREACHED();\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ ExternalTabContainer, views::WidgetWin overrides:\n\nvoid ExternalTabContainer::OnDestroy() {\n Uninitialize(GetNativeView());\n WidgetWin::OnDestroy();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ ExternalTabContainer, views::KeystrokeListener implementation:\n\nbool ExternalTabContainer::ProcessKeyStroke(HWND window, UINT message,\n WPARAM wparam, LPARAM lparam) {\n if (!automation_) {\n return false;\n }\n if ((wparam == VK_TAB) && !win_util::IsCtrlPressed()) {\n \/\/ Tabs are handled separately (except if this is Ctrl-Tab or\n \/\/ Ctrl-Shift-Tab)\n return false;\n }\n\n unsigned int flags = HIWORD(lparam);\n bool alt = (flags & KF_ALTDOWN) != 0;\n if (!alt && (message == WM_SYSKEYUP || message == WM_KEYUP)) {\n \/\/ In case the Alt key is being released.\n alt = (wparam == VK_MENU);\n }\n\n if ((flags & KF_EXTENDED) || alt || (wparam >= VK_F1 && wparam <= VK_F24) ||\n wparam == VK_ESCAPE || wparam == VK_RETURN ||\n win_util::IsShiftPressed() || win_util::IsCtrlPressed()) {\n \/\/ If this is an extended key or if one or more of Alt, Shift and Control\n \/\/ are pressed, this might be an accelerator that the external host wants\n \/\/ to handle. If the host does not handle this accelerator, it will reflect\n \/\/ the accelerator back to us via the ProcessUnhandledAccelerator method.\n MSG msg = {0};\n msg.hwnd = window;\n msg.message = message;\n msg.wParam = wparam;\n msg.lParam = lparam;\n automation_->Send(new AutomationMsg_HandleAccelerator(0, tab_handle_, msg));\n return true;\n }\n\n return false;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ ExternalTabContainer, private:\n\nvoid ExternalTabContainer::Uninitialize(HWND window) {\n if (::IsWindow(window)) {\n views::FocusManager* focus_manager =\n views::FocusManager::GetFocusManager(window);\n if (focus_manager)\n focus_manager->RemoveKeystrokeListener(this);\n }\n\n if (tab_contents_) {\n NotificationService::current()->Notify(\n NotificationType::EXTERNAL_TAB_CLOSED,\n Source<NavigationController>(&tab_contents_->controller()),\n Details<ExternalTabContainer>(this));\n\n delete tab_contents_;\n tab_contents_ = NULL;\n }\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/history\/download_types.h\"\n\nDownloadCreateInfo::DownloadCreateInfo(const FilePath& path,\n const GURL& url,\n base::Time start_time,\n int64 received_bytes,\n int64 total_bytes,\n int32 state,\n int32 download_id)\n : path(path),\n url(url),\n path_uniquifier(0),\n start_time(start_time),\n received_bytes(received_bytes),\n total_bytes(total_bytes),\n state(state),\n download_id(download_id),\n child_id(-1),\n render_view_id(-1),\n request_id(-1),\n db_handle(0),\n prompt_user_for_save_location(false),\n is_dangerous(false),\n is_extension_install(false) {\n}\n\nDownloadCreateInfo::DownloadCreateInfo()\n : path_uniquifier(0),\n received_bytes(0),\n total_bytes(0),\n state(-1),\n download_id(-1),\n child_id(-1),\n render_view_id(-1),\n request_id(-1),\n db_handle(0),\n prompt_user_for_save_location(false),\n is_dangerous(false),\n is_extension_install(false) {\n}\n\nDownloadCreateInfo::~DownloadCreateInfo() {\n}\n<commit_msg>Removed download_types.cc; no longer used.<commit_after><|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.\n\n#include \"disk_mem_usage_sampler.h\"\n#include <vespa\/vespalib\/util\/timer.h>\n#include <vespa\/searchlib\/common\/lambdatask.h>\n#include <experimental\/filesystem>\n#include <unistd.h>\n\nusing search::makeLambdaTask;\n\nnamespace proton {\n\nDiskMemUsageSampler::DiskMemUsageSampler(const std::string &protonBaseDir,\n const std::string &vespaHomeDir,\n const Config &config)\n : _filter(config.hwInfo),\n _protonBaseDir(protonBaseDir),\n _vespaHomeDir(vespaHomeDir),\n _sampleInterval(60.0),\n _periodicTimer()\n{\n setConfig(config);\n}\n\nDiskMemUsageSampler::~DiskMemUsageSampler()\n{\n _periodicTimer.reset();\n}\n\nvoid\nDiskMemUsageSampler::setConfig(const Config &config)\n{\n _periodicTimer.reset();\n _filter.setConfig(config.filterConfig);\n _sampleInterval = config.sampleInterval;\n sampleUsage();\n _periodicTimer = std::make_unique<vespalib::Timer>();\n _periodicTimer->scheduleAtFixedRate(makeLambdaTask([this]()\n { sampleUsage(); }),\n _sampleInterval, _sampleInterval);\n}\n\nvoid\nDiskMemUsageSampler::sampleUsage()\n{\n sampleMemoryUsage();\n sampleDiskUsage();\n}\n\nnamespace {\n\nnamespace fs = std::experimental::filesystem;\n\nuint64_t\nsampleDiskUsageInDirectory(const fs::path &path)\n{\n uint64_t result = 0;\n for (const auto &elem : fs::recursive_directory_iterator(path,\n fs::directory_options::skip_permission_denied)) {\n if (fs::is_regular_file(elem.path()) && !fs::is_symlink(elem.path())) {\n result += fs::file_size(elem.path());\n }\n }\n return result;\n}\n\nuint64_t\nsampleDiskUsageOnFileSystem(const fs::path &path)\n{\n auto space_info = fs::space(path);\n return (space_info.capacity - space_info.available);\n}\n\n}\n\nvoid\nDiskMemUsageSampler::sampleDiskUsage()\n{\n bool slowDisk = _filter.getHwInfo().slowDisk();\n _filter.setDiskStats(slowDisk ? sampleDiskUsageOnFileSystem(_protonBaseDir) :\n sampleDiskUsageInDirectory(_vespaHomeDir));\n}\n\nvoid\nDiskMemUsageSampler::sampleMemoryUsage()\n{\n _filter.setMemoryStats(vespalib::ProcessMemoryStats::create());\n}\n\n} \/\/ namespace proton\n<commit_msg>Disable directory scan for now, it causes bad behavior when system believes disk is fast while it is a spinning disk.<commit_after>\/\/ Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.\n\n#include \"disk_mem_usage_sampler.h\"\n#include <vespa\/vespalib\/util\/timer.h>\n#include <vespa\/searchlib\/common\/lambdatask.h>\n#include <experimental\/filesystem>\n#include <unistd.h>\n\nusing search::makeLambdaTask;\n\nnamespace proton {\n\nDiskMemUsageSampler::DiskMemUsageSampler(const std::string &protonBaseDir,\n const std::string &vespaHomeDir,\n const Config &config)\n : _filter(config.hwInfo),\n _protonBaseDir(protonBaseDir),\n _vespaHomeDir(vespaHomeDir),\n _sampleInterval(60.0),\n _periodicTimer()\n{\n setConfig(config);\n}\n\nDiskMemUsageSampler::~DiskMemUsageSampler()\n{\n _periodicTimer.reset();\n}\n\nvoid\nDiskMemUsageSampler::setConfig(const Config &config)\n{\n _periodicTimer.reset();\n _filter.setConfig(config.filterConfig);\n _sampleInterval = config.sampleInterval;\n sampleUsage();\n _periodicTimer = std::make_unique<vespalib::Timer>();\n _periodicTimer->scheduleAtFixedRate(makeLambdaTask([this]()\n { sampleUsage(); }),\n _sampleInterval, _sampleInterval);\n}\n\nvoid\nDiskMemUsageSampler::sampleUsage()\n{\n sampleMemoryUsage();\n sampleDiskUsage();\n}\n\nnamespace {\n\nnamespace fs = std::experimental::filesystem;\n\nuint64_t\nsampleDiskUsageInDirectory(const fs::path &path)\n{\n uint64_t result = 0;\n for (const auto &elem : fs::recursive_directory_iterator(path,\n fs::directory_options::skip_permission_denied)) {\n if (fs::is_regular_file(elem.path()) && !fs::is_symlink(elem.path())) {\n result += fs::file_size(elem.path());\n }\n }\n return result;\n}\n\nuint64_t\nsampleDiskUsageOnFileSystem(const fs::path &path)\n{\n auto space_info = fs::space(path);\n return (space_info.capacity - space_info.available);\n}\n\n}\n\nvoid\nDiskMemUsageSampler::sampleDiskUsage()\n{\n bool slowDisk = _filter.getHwInfo().slowDisk() || true;\n _filter.setDiskStats(slowDisk ? sampleDiskUsageOnFileSystem(_protonBaseDir) :\n sampleDiskUsageInDirectory(_vespaHomeDir));\n}\n\nvoid\nDiskMemUsageSampler::sampleMemoryUsage()\n{\n _filter.setMemoryStats(vespalib::ProcessMemoryStats::create());\n}\n\n} \/\/ namespace proton\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2009 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/views\/panel_controller.h\"\n\n#include <gdk\/gdkx.h>\nextern \"C\" {\n#include <X11\/Xlib.h>\n}\n\n#include \"app\/resource_bundle.h\"\n#include \"base\/logging.h\"\n#include \"base\/singleton.h\"\n#include \"base\/scoped_ptr.h\"\n#include \"chrome\/browser\/browser.h\"\n#include \"chrome\/browser\/gtk\/browser_window_gtk.h\"\n#include \"chrome\/browser\/views\/tabs\/tab_overview_types.h\"\n#include \"chrome\/common\/x11_util.h\"\n#include \"grit\/app_resources.h\"\n#include \"grit\/generated_resources.h\"\n#include \"grit\/theme_resources.h\"\n#include \"views\/controls\/button\/image_button.h\"\n#include \"views\/controls\/label.h\"\n#include \"views\/event.h\"\n#include \"views\/view.h\"\n#include \"views\/widget\/widget_gtk.h\"\n\nstatic int close_button_width;\nstatic int close_button_height;\nstatic SkBitmap* close_button_n;\nstatic SkBitmap* close_button_h;\nstatic SkBitmap* close_button_p;\nstatic gfx::Font* title_font = NULL;\n\nnamespace {\n\nconst int kTitleWidth = 200;\nconst int kTitleHeight = 24;\nconst int kTitlePad = 8;\nconst int kButtonPad = 8;\n\nstatic bool resources_initialized;\nstatic void InitializeResources() {\n if (resources_initialized) {\n return;\n }\n\n resources_initialized = true;\n ResourceBundle& rb = ResourceBundle::GetSharedInstance();\n title_font = new gfx::Font(rb.GetFont(ResourceBundle::BaseFont));\n close_button_n = rb.GetBitmapNamed(IDR_TAB_CLOSE);\n close_button_h = rb.GetBitmapNamed(IDR_TAB_CLOSE_H);\n close_button_p = rb.GetBitmapNamed(IDR_TAB_CLOSE_P);\n close_button_width = close_button_n->width();\n close_button_height = close_button_n->height();\n}\n\n} \/\/ namespace\n\nPanelController::PanelController(BrowserWindowGtk* browser_window)\n : browser_window_(browser_window),\n panel_(browser_window->window()),\n panel_xid_(x11_util::GetX11WindowFromGtkWidget(GTK_WIDGET(panel_))),\n expanded_(true),\n mouse_down_(false),\n dragging_(false) {\n title_window_ = new views::WidgetGtk(views::WidgetGtk::TYPE_WINDOW);\n gfx::Rect title_bounds(\n 0, 0, browser_window->GetNormalBounds().width(), kTitleHeight);\n title_window_->Init(NULL, title_bounds);\n title_ = title_window_->GetNativeView();\n title_xid_ = x11_util::GetX11WindowFromGtkWidget(title_);\n\n TabOverviewTypes* tab_overview = TabOverviewTypes::instance();\n tab_overview->SetWindowType(\n title_,\n TabOverviewTypes::WINDOW_TYPE_CHROME_PANEL_TITLEBAR,\n NULL);\n std::vector<int> type_params;\n type_params.push_back(title_xid_);\n type_params.push_back(expanded_ ? 1 : 0);\n tab_overview->SetWindowType(\n GTK_WIDGET(panel_),\n TabOverviewTypes::WINDOW_TYPE_CHROME_PANEL,\n &type_params);\n\n g_signal_connect(\n panel_, \"client-event\", G_CALLBACK(OnPanelClientEvent), this);\n\n title_content_ = new TitleContentView(this);\n title_window_->SetContentsView(title_content_);\n title_window_->Show();\n}\n\nvoid PanelController::UpdateTitleBar() {\n title_content_->title_label()->SetText(\n browser_window_->browser()->GetCurrentPageTitle());\n}\n\nbool PanelController::TitleMousePressed(const views::MouseEvent& event) {\n if (!event.IsOnlyLeftMouseButton()) {\n return false;\n }\n gfx::Point abs_location = event.location();\n views::View::ConvertPointToScreen(title_content_, &abs_location);\n mouse_down_ = true;\n mouse_down_abs_x_ = abs_location.x();\n mouse_down_abs_y_ = abs_location.y();\n mouse_down_offset_x_ = event.x();\n mouse_down_offset_y_ = event.y();\n dragging_ = false;\n return true;\n}\n\nvoid PanelController::TitleMouseReleased(\n const views::MouseEvent& event, bool canceled) {\n if (!event.IsOnlyLeftMouseButton()) {\n return;\n }\n \/\/ Only handle clicks that started in our window.\n if (!mouse_down_) {\n return;\n }\n\n mouse_down_ = false;\n if (!dragging_) {\n TabOverviewTypes::Message msg(\n TabOverviewTypes::Message::WM_SET_PANEL_STATE);\n msg.set_param(0, panel_xid_);\n msg.set_param(1, expanded_ ? 0 : 1);\n TabOverviewTypes::instance()->SendMessage(msg);\n } else {\n TabOverviewTypes::Message msg(\n TabOverviewTypes::Message::WM_NOTIFY_PANEL_DRAG_COMPLETE);\n msg.set_param(0, panel_xid_);\n TabOverviewTypes::instance()->SendMessage(msg);\n dragging_ = false;\n }\n}\n\nbool PanelController::TitleMouseDragged(const views::MouseEvent& event) {\n if (!mouse_down_) {\n return false;\n }\n\n gfx::Point abs_location = event.location();\n views::View::ConvertPointToScreen(title_content_, &abs_location);\n if (!dragging_) {\n if (views::View::ExceededDragThreshold(\n abs_location.x() - mouse_down_abs_x_,\n abs_location.y() - mouse_down_abs_y_)) {\n dragging_ = true;\n }\n }\n if (dragging_) {\n TabOverviewTypes::Message msg(TabOverviewTypes::Message::WM_MOVE_PANEL);\n msg.set_param(0, panel_xid_);\n msg.set_param(1, abs_location.x() - mouse_down_offset_x_);\n msg.set_param(2, abs_location.y() - mouse_down_offset_y_);\n TabOverviewTypes::instance()->SendMessage(msg);\n }\n return true;\n}\n\n\/\/ static\nbool PanelController::OnPanelClientEvent(\n GtkWidget* widget,\n GdkEventClient* event,\n PanelController* panel_controller) {\n return panel_controller->PanelClientEvent(event);\n}\n\nbool PanelController::PanelClientEvent(GdkEventClient* event) {\n TabOverviewTypes::Message msg;\n TabOverviewTypes::instance()->DecodeMessage(*event, &msg);\n if (msg.type() == TabOverviewTypes::Message::CHROME_NOTIFY_PANEL_STATE) {\n expanded_ = msg.param(0);\n }\n return true;\n}\n\nvoid PanelController::Close() {\n title_window_->Close();\n}\n\nvoid PanelController::ButtonPressed(views::Button* sender) {\n if (sender == title_content_->close_button()) {\n browser_window_->Close();\n }\n}\n\nPanelController::TitleContentView::TitleContentView(\n PanelController* panel_controller)\n : panel_controller_(panel_controller) {\n InitializeResources();\n close_button_ = new views::ImageButton(panel_controller_);\n close_button_->SetImage(views::CustomButton::BS_NORMAL, close_button_n);\n close_button_->SetImage(views::CustomButton::BS_HOT, close_button_h);\n close_button_->SetImage(views::CustomButton::BS_PUSHED, close_button_p);\n AddChildView(close_button_);\n\n title_label_ = new views::Label(std::wstring(), *title_font);\n title_label_->SetHorizontalAlignment(views::Label::ALIGN_LEFT);\n AddChildView(title_label_);\n\n set_background(views::Background::CreateSolidBackground(0xdd, 0xdd, 0xdd, 1));\n}\n\nvoid PanelController::TitleContentView::Layout() {\n close_button_->SetBounds(\n bounds().width() - (close_button_width + kButtonPad),\n (bounds().height() - close_button_height) \/ 2,\n close_button_width,\n close_button_height);\n title_label_->SetBounds(\n kTitlePad,\n 0,\n bounds().width() - (kTitlePad + close_button_width + 2 * kButtonPad),\n bounds().height());\n}\n\nbool PanelController::TitleContentView::OnMousePressed(\n const views::MouseEvent& event) {\n return panel_controller_->TitleMousePressed(event);\n}\n\nvoid PanelController::TitleContentView::OnMouseReleased(\n const views::MouseEvent& event, bool canceled) {\n return panel_controller_->TitleMouseReleased(event, canceled);\n}\n\nbool PanelController::TitleContentView::OnMouseDragged(\n const views::MouseEvent& event) {\n return panel_controller_->TitleMouseDragged(event);\n}\n\n<commit_msg>Fixed compile breakage resulting from wstring to string16 change.<commit_after>\/\/ Copyright (c) 2009 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/views\/panel_controller.h\"\n\n#include <gdk\/gdkx.h>\nextern \"C\" {\n#include <X11\/Xlib.h>\n}\n\n#include \"app\/resource_bundle.h\"\n#include \"base\/logging.h\"\n#include \"base\/singleton.h\"\n#include \"base\/scoped_ptr.h\"\n#include \"base\/string_util.h\"\n#include \"chrome\/browser\/browser.h\"\n#include \"chrome\/browser\/gtk\/browser_window_gtk.h\"\n#include \"chrome\/browser\/views\/tabs\/tab_overview_types.h\"\n#include \"chrome\/common\/x11_util.h\"\n#include \"grit\/app_resources.h\"\n#include \"grit\/generated_resources.h\"\n#include \"grit\/theme_resources.h\"\n#include \"views\/controls\/button\/image_button.h\"\n#include \"views\/controls\/label.h\"\n#include \"views\/event.h\"\n#include \"views\/view.h\"\n#include \"views\/widget\/widget_gtk.h\"\n\nstatic int close_button_width;\nstatic int close_button_height;\nstatic SkBitmap* close_button_n;\nstatic SkBitmap* close_button_h;\nstatic SkBitmap* close_button_p;\nstatic gfx::Font* title_font = NULL;\n\nnamespace {\n\nconst int kTitleWidth = 200;\nconst int kTitleHeight = 24;\nconst int kTitlePad = 8;\nconst int kButtonPad = 8;\n\nstatic bool resources_initialized;\nstatic void InitializeResources() {\n if (resources_initialized) {\n return;\n }\n\n resources_initialized = true;\n ResourceBundle& rb = ResourceBundle::GetSharedInstance();\n title_font = new gfx::Font(rb.GetFont(ResourceBundle::BaseFont));\n close_button_n = rb.GetBitmapNamed(IDR_TAB_CLOSE);\n close_button_h = rb.GetBitmapNamed(IDR_TAB_CLOSE_H);\n close_button_p = rb.GetBitmapNamed(IDR_TAB_CLOSE_P);\n close_button_width = close_button_n->width();\n close_button_height = close_button_n->height();\n}\n\n} \/\/ namespace\n\nPanelController::PanelController(BrowserWindowGtk* browser_window)\n : browser_window_(browser_window),\n panel_(browser_window->window()),\n panel_xid_(x11_util::GetX11WindowFromGtkWidget(GTK_WIDGET(panel_))),\n expanded_(true),\n mouse_down_(false),\n dragging_(false) {\n title_window_ = new views::WidgetGtk(views::WidgetGtk::TYPE_WINDOW);\n gfx::Rect title_bounds(\n 0, 0, browser_window->GetNormalBounds().width(), kTitleHeight);\n title_window_->Init(NULL, title_bounds);\n title_ = title_window_->GetNativeView();\n title_xid_ = x11_util::GetX11WindowFromGtkWidget(title_);\n\n TabOverviewTypes* tab_overview = TabOverviewTypes::instance();\n tab_overview->SetWindowType(\n title_,\n TabOverviewTypes::WINDOW_TYPE_CHROME_PANEL_TITLEBAR,\n NULL);\n std::vector<int> type_params;\n type_params.push_back(title_xid_);\n type_params.push_back(expanded_ ? 1 : 0);\n tab_overview->SetWindowType(\n GTK_WIDGET(panel_),\n TabOverviewTypes::WINDOW_TYPE_CHROME_PANEL,\n &type_params);\n\n g_signal_connect(\n panel_, \"client-event\", G_CALLBACK(OnPanelClientEvent), this);\n\n title_content_ = new TitleContentView(this);\n title_window_->SetContentsView(title_content_);\n title_window_->Show();\n}\n\nvoid PanelController::UpdateTitleBar() {\n title_content_->title_label()->SetText(\n UTF16ToWideHack(browser_window_->browser()->GetCurrentPageTitle()));\n}\n\nbool PanelController::TitleMousePressed(const views::MouseEvent& event) {\n if (!event.IsOnlyLeftMouseButton()) {\n return false;\n }\n gfx::Point abs_location = event.location();\n views::View::ConvertPointToScreen(title_content_, &abs_location);\n mouse_down_ = true;\n mouse_down_abs_x_ = abs_location.x();\n mouse_down_abs_y_ = abs_location.y();\n mouse_down_offset_x_ = event.x();\n mouse_down_offset_y_ = event.y();\n dragging_ = false;\n return true;\n}\n\nvoid PanelController::TitleMouseReleased(\n const views::MouseEvent& event, bool canceled) {\n if (!event.IsOnlyLeftMouseButton()) {\n return;\n }\n \/\/ Only handle clicks that started in our window.\n if (!mouse_down_) {\n return;\n }\n\n mouse_down_ = false;\n if (!dragging_) {\n TabOverviewTypes::Message msg(\n TabOverviewTypes::Message::WM_SET_PANEL_STATE);\n msg.set_param(0, panel_xid_);\n msg.set_param(1, expanded_ ? 0 : 1);\n TabOverviewTypes::instance()->SendMessage(msg);\n } else {\n TabOverviewTypes::Message msg(\n TabOverviewTypes::Message::WM_NOTIFY_PANEL_DRAG_COMPLETE);\n msg.set_param(0, panel_xid_);\n TabOverviewTypes::instance()->SendMessage(msg);\n dragging_ = false;\n }\n}\n\nbool PanelController::TitleMouseDragged(const views::MouseEvent& event) {\n if (!mouse_down_) {\n return false;\n }\n\n gfx::Point abs_location = event.location();\n views::View::ConvertPointToScreen(title_content_, &abs_location);\n if (!dragging_) {\n if (views::View::ExceededDragThreshold(\n abs_location.x() - mouse_down_abs_x_,\n abs_location.y() - mouse_down_abs_y_)) {\n dragging_ = true;\n }\n }\n if (dragging_) {\n TabOverviewTypes::Message msg(TabOverviewTypes::Message::WM_MOVE_PANEL);\n msg.set_param(0, panel_xid_);\n msg.set_param(1, abs_location.x() - mouse_down_offset_x_);\n msg.set_param(2, abs_location.y() - mouse_down_offset_y_);\n TabOverviewTypes::instance()->SendMessage(msg);\n }\n return true;\n}\n\n\/\/ static\nbool PanelController::OnPanelClientEvent(\n GtkWidget* widget,\n GdkEventClient* event,\n PanelController* panel_controller) {\n return panel_controller->PanelClientEvent(event);\n}\n\nbool PanelController::PanelClientEvent(GdkEventClient* event) {\n TabOverviewTypes::Message msg;\n TabOverviewTypes::instance()->DecodeMessage(*event, &msg);\n if (msg.type() == TabOverviewTypes::Message::CHROME_NOTIFY_PANEL_STATE) {\n expanded_ = msg.param(0);\n }\n return true;\n}\n\nvoid PanelController::Close() {\n title_window_->Close();\n}\n\nvoid PanelController::ButtonPressed(views::Button* sender) {\n if (sender == title_content_->close_button()) {\n browser_window_->Close();\n }\n}\n\nPanelController::TitleContentView::TitleContentView(\n PanelController* panel_controller)\n : panel_controller_(panel_controller) {\n InitializeResources();\n close_button_ = new views::ImageButton(panel_controller_);\n close_button_->SetImage(views::CustomButton::BS_NORMAL, close_button_n);\n close_button_->SetImage(views::CustomButton::BS_HOT, close_button_h);\n close_button_->SetImage(views::CustomButton::BS_PUSHED, close_button_p);\n AddChildView(close_button_);\n\n title_label_ = new views::Label(std::wstring(), *title_font);\n title_label_->SetHorizontalAlignment(views::Label::ALIGN_LEFT);\n AddChildView(title_label_);\n\n set_background(views::Background::CreateSolidBackground(0xdd, 0xdd, 0xdd, 1));\n}\n\nvoid PanelController::TitleContentView::Layout() {\n close_button_->SetBounds(\n bounds().width() - (close_button_width + kButtonPad),\n (bounds().height() - close_button_height) \/ 2,\n close_button_width,\n close_button_height);\n title_label_->SetBounds(\n kTitlePad,\n 0,\n bounds().width() - (kTitlePad + close_button_width + 2 * kButtonPad),\n bounds().height());\n}\n\nbool PanelController::TitleContentView::OnMousePressed(\n const views::MouseEvent& event) {\n return panel_controller_->TitleMousePressed(event);\n}\n\nvoid PanelController::TitleContentView::OnMouseReleased(\n const views::MouseEvent& event, bool canceled) {\n return panel_controller_->TitleMouseReleased(event, canceled);\n}\n\nbool PanelController::TitleContentView::OnMouseDragged(\n const views::MouseEvent& event) {\n return panel_controller_->TitleMouseDragged(event);\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/\/------------------------------------------------------------------------------\n\/\/ Copyright (c) 2016 by contributors. All Rights Reserved.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/------------------------------------------------------------------------------\n\n\/*\nAuthor: Chao Ma (mctt90@gmail.com)\n\nThis file tests the FFMScore class.\n*\/\n\n#include \"gtest\/gtest.h\"\n\n#include \"src\/base\/common.h\"\n#include \"src\/data\/data_structure.h\"\n#include \"src\/data\/hyper_parameters.h\"\n\n#include \"src\/score\/score_function.h\"\n#include \"src\/score\/ffm_score.h\"\n\nnamespace xLearn {\n\nindex_t K = 24;\nindex_t Kfeat = 3;\nindex_t kfield = 3;\nindex_t kLength = Kfeat + 1 + Kfeat*kfield*K;\n\nTEST(FFM_TEST, calc_score) {\n SparseRow row(Kfeat+1, true);\n std::vector<real_t> w(kLength, 1.0);\n \/\/ Init SparseRow\n for (index_t i = 1; i <= Kfeat; ++i) {\n row.idx[i] = i;\n row.field[i] = i;\n row.X[i] = 2.0;\n }\n row.idx[0] = 0; \/\/ bias\n row.field[0] = 0;\n row.X[0] = 1.0;\n HyperParam hyper_param;\n hyper_param.num_feature = Kfeat;\n hyper_param.num_K = K;\n hyper_param.num_field = kfield;\n FFMScore score;\n score.Initialize(hyper_param);\n real_t val = score.CalcScore(&row, &w);\n \/\/ 7 + 24*4*3 = 295.0\n EXPECT_FLOAT_EQ(val, 295.0);\n}\n\nTEST(FFM_TEST, calc_grad) {\n \/\/ Reset hyper parameters\n K = 24;\n Kfeat = 100;\n kfield = 100;\n kLength = Kfeat + 1 + Kfeat*kfield*K;\n \/\/ Create SparseRow\n SparseRow row(Kfeat+1, true);\n for (index_t i = 0; i < Kfeat+1; ++i) {\n row.idx[i] = i;\n row.X[i] = 2.0;\n row.field[i] = i;\n }\n \/\/ Create model\n std::vector<real_t> w(kLength, 3.0);\n \/\/ Create updater\n Updater* updater = new Updater();\n HyperParam hyper_param;\n hyper_param.learning_rate = 0.1;\n updater->Initialize(hyper_param);\n \/\/ Create score function\n FFMScore score;\n hyper_param.num_feature = Kfeat;\n hyper_param.num_K = K;\n hyper_param.num_field = kfield;\n score.Initialize(hyper_param);\n score.CalcGrad(&row, w, 1.0, updater);\n \/\/ Test\n for (index_t i = 0; i < Kfeat+1; ++i) {\n EXPECT_FLOAT_EQ(w[i], 2.8);\n }\n for (index_t i = Kfeat+1; i < kLength; ++i) {\n if (w[i] != 3.0) {\n EXPECT_FLOAT_EQ(w[i], 1.8);\n }\n }\n \/\/ Test speed\n int line = 1000;\n for (int i = 0 ; i < line; ++i) {\n score.CalcGrad(&row, w, 1.0, updater);\n }\n}\n\n} \/\/ namespace xLearn\n<commit_msg>update<commit_after>\/\/------------------------------------------------------------------------------\n\/\/ Copyright (c) 2016 by contributors. All Rights Reserved.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/------------------------------------------------------------------------------\n\n\/*\nAuthor: Chao Ma (mctt90@gmail.com)\n\nThis file tests the FFMScore class.\n*\/\n\n#include \"gtest\/gtest.h\"\n\n#include \"src\/base\/common.h\"\n#include \"src\/data\/data_structure.h\"\n#include \"src\/data\/hyper_parameters.h\"\n\n#include \"src\/score\/score_function.h\"\n#include \"src\/score\/ffm_score.h\"\n\nnamespace xLearn {\n\nindex_t K = 24;\nindex_t Kfeat = 3;\nindex_t kfield = 3;\nindex_t kLength = Kfeat + 1 + Kfeat*kfield*K;\n\nTEST(FFM_TEST, calc_score) {\n SparseRow row(Kfeat+1, true);\n std::vector<real_t> w(kLength, 1.0);\n \/\/ Init SparseRow\n for (index_t i = 1; i <= Kfeat; ++i) {\n row.idx[i] = i;\n row.field[i] = i;\n row.X[i] = 2.0;\n }\n row.idx[0] = 0; \/\/ bias\n row.field[0] = 0;\n row.X[0] = 1.0;\n HyperParam hyper_param;\n hyper_param.num_feature = Kfeat;\n hyper_param.num_K = K;\n hyper_param.num_field = kfield;\n FFMScore score;\n score.Initialize(hyper_param);\n real_t val = score.CalcScore(&row, &w);\n \/\/ 7 + 24*4*3 = 295.0\n EXPECT_FLOAT_EQ(val, 295.0);\n}\n\nTEST(FFM_TEST, calc_grad) {\n \/\/ Reset hyper parameters\n K = 24;\n Kfeat = 100;\n kfield = 100;\n kLength = Kfeat + 1 + Kfeat*kfield*K;\n \/\/ Create SparseRow\n SparseRow row(Kfeat+1, true);\n for (index_t i = 0; i < Kfeat+1; ++i) {\n row.idx[i] = i;\n row.X[i] = 2.0;\n row.field[i] = i;\n }\n \/\/ Create model\n std::vector<real_t> w(kLength, 3.0);\n \/\/ Create updater\n Updater* updater = new Updater();\n HyperParam hyper_param;\n hyper_param.learning_rate = 0.1;\n updater->Initialize(hyper_param);\n \/\/ Create score function\n FFMScore score;\n hyper_param.num_feature = Kfeat;\n hyper_param.num_K = K;\n hyper_param.num_field = kfield;\n score.Initialize(hyper_param);\n score.CalcGrad(&row, w, 1.0, updater);\n \/\/ Test\n for (index_t i = 0; i < Kfeat+1; ++i) {\n EXPECT_FLOAT_EQ(w[i], 2.8);\n }\n for (index_t i = Kfeat+1; i < kLength; ++i) {\n if (w[i] != 3.0) {\n EXPECT_FLOAT_EQ(w[i], 1.8);\n }\n }\n}\n\n} \/\/ namespace xLearn\n<|endoftext|>"} {"text":"<commit_before>\/\/--------------------------------------------------------------------*- C++ -*-\n\/\/ CLING - the C++ LLVM-based InterpreterG :)\n\/\/ version: $Id$\n\/\/ author: Axel Naumann <axel@cern.ch>\n\/\/------------------------------------------------------------------------------\n\n#include \"cling\/Interpreter\/CIFactory.h\"\n\n#include \"ChainedConsumer.h\"\n\n#include \"clang\/AST\/ASTContext.h\"\n#include \"clang\/Basic\/TargetInfo.h\"\n#include \"clang\/Basic\/Version.h\"\n#include \"clang\/Frontend\/TextDiagnosticPrinter.h\"\n#include \"clang\/Lex\/Pragma.h\"\n#include \"clang\/Lex\/Preprocessor.h\"\n\n#include \"llvm\/LLVMContext.h\"\n#include \"llvm\/Target\/TargetOptions.h\"\n#include \"llvm\/Support\/TargetSelect.h\"\n#include \"llvm\/Support\/MemoryBuffer.h\"\n#include \"llvm\/Support\/Path.h\"\n\nusing namespace clang;\n\nnamespace cling {\n \/\/\n \/\/ Dummy function so we can use dladdr to find the executable path.\n \/\/\n void locate_cling_executable()\n {\n }\n\n CompilerInstance* CIFactory::createCI(llvm::StringRef code,\n int argc,\n const char* const *argv,\n const char* llvmdir) {\n return createCI(llvm::MemoryBuffer::getMemBuffer(code), 0, argc, argv, llvmdir);\n }\n\n \n CompilerInstance* CIFactory::createCI(llvm::MemoryBuffer* buffer, \n PragmaNamespace* Pragma, \n int argc, \n const char* const *argv,\n const char* llvmdir){\n \/\/ main's argv[0] is skipped!\n\n if (!Pragma) {\n Pragma = new PragmaNamespace(\"cling\");\n }\n\n \/\/ Create an instance builder, passing the llvmdir and arguments.\n \/\/\n \/\/ Initialize the llvm library.\n \/\/\n \/\/ If not set, exception handling will not be turned on\n llvm::JITExceptionHandling = true;\n llvm::InitializeNativeTarget();\n llvm::InitializeAllAsmPrinters();\n llvm::sys::Path resource_path;\n if (llvmdir) {\n resource_path = llvmdir;\n resource_path.appendComponent(\"lib\");\n resource_path.appendComponent(\"clang\");\n resource_path.appendComponent(CLANG_VERSION_STRING);\n } else {\n \/\/ FIXME: The first arg really does need to be argv[0] on FreeBSD.\n \/\/\n \/\/ Note: The second arg is not used for Apple, FreeBSD, Linux,\n \/\/ or cygwin, and can only be used on systems which support\n \/\/ the use of dladdr().\n \/\/\n \/\/ Note: On linux and cygwin this uses \/proc\/self\/exe to find the path.\n \/\/\n \/\/ Note: On Apple it uses _NSGetExecutablePath().\n \/\/\n \/\/ Note: On FreeBSD it uses getprogpath().\n \/\/\n \/\/ Note: Otherwise it uses dladdr().\n \/\/\n resource_path = CompilerInvocation::GetResourcesPath(\"cling\",\n (void*)(intptr_t) locate_cling_executable\n );\n }\n\n\n \/\/ Create and setup a compiler instance.\n CompilerInstance* CI = new CompilerInstance();\n {\n \/\/\n \/\/ Buffer the error messages while we process\n \/\/ the compiler options.\n \/\/\n\n \/\/ Needed when we call CreateFromArgs\n CI->createDiagnostics(0, 0);\n CompilerInvocation::CreateFromArgs\n (CI->getInvocation(), argv, argv + argc, CI->getDiagnostics());\n\n \/\/ Reset the diagnostics options that came from CreateFromArgs\n DiagnosticOptions& DiagOpts = CI->getDiagnosticOpts();\n DiagOpts.ShowColors = 1;\n DiagnosticConsumer* Client = new TextDiagnosticPrinter(llvm::errs(), DiagOpts);\n CI->createDiagnostics(0, 0, Client);\n\n \/\/ Set the language options, which cling needs\n SetClingCustomLangOpts(CI->getLangOpts());\n\n if (CI->getHeaderSearchOpts().UseBuiltinIncludes &&\n CI->getHeaderSearchOpts().ResourceDir.empty()) {\n CI->getHeaderSearchOpts().ResourceDir = resource_path.str();\n }\n CI->getInvocation().getPreprocessorOpts().addMacroDef(\"__CLING__\");\n if (CI->getDiagnostics().hasErrorOccurred()) {\n delete CI;\n CI = 0;\n return 0;\n }\n }\n CI->setTarget(TargetInfo::CreateTargetInfo(CI->getDiagnostics(),\n CI->getTargetOpts()));\n if (!CI->hasTarget()) {\n delete CI;\n CI = 0;\n return 0;\n }\n CI->getTarget().setForcedLangOptions(CI->getLangOpts());\n SetClingTargetLangOpts(CI->getLangOpts(), CI->getTarget());\n \n \/\/ Set up source and file managers\n CI->createFileManager();\n CI->createSourceManager(CI->getFileManager());\n \n \/\/ Set up the memory buffer\n if (buffer)\n CI->getSourceManager().createMainFileIDForMemBuffer(buffer);\n \n \/\/ Set up the preprocessor\n CI->createPreprocessor();\n Preprocessor& PP = CI->getPreprocessor();\n PP.AddPragmaHandler(Pragma);\n PP.getBuiltinInfo().InitializeBuiltins(PP.getIdentifierTable(),\n PP.getLangOptions());\n \/*NoBuiltins = *\/ \/\/true);\n \n \/\/ Set up the ASTContext\n ASTContext *Ctx = new ASTContext(CI->getLangOpts(),\n PP.getSourceManager(), &CI->getTarget(), PP.getIdentifierTable(),\n PP.getSelectorTable(), PP.getBuiltinInfo(), 0);\n CI->setASTContext(Ctx);\n \/\/CI->getSourceManager().clearIDTables(); \/\/do we really need it?\n \n \/\/ Set up the ASTConsumers\n CI->setASTConsumer(new ChainedConsumer());\n\n \/\/ Set up Sema\n CodeCompleteConsumer* CCC = 0;\n CI->createSema(TU_Prefix, CCC);\n\n \/\/ Set CodeGen options\n \/\/ CI->getCodeGenOpts().DebugInfo = 1; \/\/ want debug info\n \/\/ CI->getCodeGenOpts().EmitDeclMetadata = 1; \/\/ For unloading, for later\n CI->getCodeGenOpts().OptimizationLevel = 0; \/\/ see pure SSA, that come out\n assert((CI->getCodeGenOpts().VerifyModule = 1) && \"When asserts are on, let's also assert the module\");\n return CI;\n }\n\n void CIFactory::SetClingCustomLangOpts(LangOptions& Opts) {\n Opts.EmitAllDecls = 1;\n }\n\n void CIFactory::SetClingTargetLangOpts(LangOptions& Opts, \n const TargetInfo& Target) {\n if (Target.getTriple().getOS() == llvm::Triple::Win32) {\n Opts.MicrosoftExt = 1;\n Opts.MSCVersion = 1300;\n \/\/ Should fix http:\/\/llvm.org\/bugs\/show_bug.cgi?id=10528\n Opts.DelayedTemplateParsing = 1;\n }\n }\n} \/\/ end namespace\n<commit_msg>Typo<commit_after>\/\/--------------------------------------------------------------------*- C++ -*-\n\/\/ CLING - the C++ LLVM-based InterpreterG :)\n\/\/ version: $Id$\n\/\/ author: Axel Naumann <axel@cern.ch>\n\/\/------------------------------------------------------------------------------\n\n#include \"cling\/Interpreter\/CIFactory.h\"\n\n#include \"ChainedConsumer.h\"\n\n#include \"clang\/AST\/ASTContext.h\"\n#include \"clang\/Basic\/TargetInfo.h\"\n#include \"clang\/Basic\/Version.h\"\n#include \"clang\/Frontend\/TextDiagnosticPrinter.h\"\n#include \"clang\/Lex\/Pragma.h\"\n#include \"clang\/Lex\/Preprocessor.h\"\n\n#include \"llvm\/LLVMContext.h\"\n#include \"llvm\/Target\/TargetOptions.h\"\n#include \"llvm\/Support\/TargetSelect.h\"\n#include \"llvm\/Support\/MemoryBuffer.h\"\n#include \"llvm\/Support\/Path.h\"\n\nusing namespace clang;\n\nnamespace cling {\n \/\/\n \/\/ Dummy function so we can use dladdr to find the executable path.\n \/\/\n void locate_cling_executable()\n {\n }\n\n CompilerInstance* CIFactory::createCI(llvm::StringRef code,\n int argc,\n const char* const *argv,\n const char* llvmdir) {\n return createCI(llvm::MemoryBuffer::getMemBuffer(code), 0, argc, argv, llvmdir);\n }\n\n \n CompilerInstance* CIFactory::createCI(llvm::MemoryBuffer* buffer, \n PragmaNamespace* Pragma, \n int argc, \n const char* const *argv,\n const char* llvmdir){\n \/\/ main's argv[0] is skipped!\n\n if (!Pragma) {\n Pragma = new PragmaNamespace(\"cling\");\n }\n\n \/\/ Create an instance builder, passing the llvmdir and arguments.\n \/\/\n \/\/ Initialize the llvm library.\n \/\/\n \/\/ If not set, exception handling will not be turned on\n llvm::JITExceptionHandling = true;\n llvm::InitializeNativeTarget();\n llvm::InitializeAllAsmPrinters();\n llvm::sys::Path resource_path;\n if (llvmdir) {\n resource_path = llvmdir;\n resource_path.appendComponent(\"lib\");\n resource_path.appendComponent(\"clang\");\n resource_path.appendComponent(CLANG_VERSION_STRING);\n } else {\n \/\/ FIXME: The first arg really does need to be argv[0] on FreeBSD.\n \/\/\n \/\/ Note: The second arg is not used for Apple, FreeBSD, Linux,\n \/\/ or cygwin, and can only be used on systems which support\n \/\/ the use of dladdr().\n \/\/\n \/\/ Note: On linux and cygwin this uses \/proc\/self\/exe to find the path.\n \/\/\n \/\/ Note: On Apple it uses _NSGetExecutablePath().\n \/\/\n \/\/ Note: On FreeBSD it uses getprogpath().\n \/\/\n \/\/ Note: Otherwise it uses dladdr().\n \/\/\n resource_path = CompilerInvocation::GetResourcesPath(\"cling\",\n (void*)(intptr_t) locate_cling_executable\n );\n }\n\n\n \/\/ Create and setup a compiler instance.\n CompilerInstance* CI = new CompilerInstance();\n {\n \/\/\n \/\/ Buffer the error messages while we process\n \/\/ the compiler options.\n \/\/\n\n \/\/ Needed when we call CreateFromArgs\n CI->createDiagnostics(0, 0);\n CompilerInvocation::CreateFromArgs\n (CI->getInvocation(), argv, argv + argc, CI->getDiagnostics());\n\n \/\/ Reset the diagnostics options that came from CreateFromArgs\n DiagnosticOptions& DiagOpts = CI->getDiagnosticOpts();\n DiagOpts.ShowColors = 1;\n DiagnosticConsumer* Client = new TextDiagnosticPrinter(llvm::errs(), DiagOpts);\n CI->createDiagnostics(0, 0, Client);\n\n \/\/ Set the language options, which cling needs\n SetClingCustomLangOpts(CI->getLangOpts());\n\n if (CI->getHeaderSearchOpts().UseBuiltinIncludes &&\n CI->getHeaderSearchOpts().ResourceDir.empty()) {\n CI->getHeaderSearchOpts().ResourceDir = resource_path.str();\n }\n CI->getInvocation().getPreprocessorOpts().addMacroDef(\"__CLING__\");\n if (CI->getDiagnostics().hasErrorOccurred()) {\n delete CI;\n CI = 0;\n return 0;\n }\n }\n CI->setTarget(TargetInfo::CreateTargetInfo(CI->getDiagnostics(),\n CI->getTargetOpts()));\n if (!CI->hasTarget()) {\n delete CI;\n CI = 0;\n return 0;\n }\n CI->getTarget().setForcedLangOptions(CI->getLangOpts());\n SetClingTargetLangOpts(CI->getLangOpts(), CI->getTarget());\n \n \/\/ Set up source and file managers\n CI->createFileManager();\n CI->createSourceManager(CI->getFileManager());\n \n \/\/ Set up the memory buffer\n if (buffer)\n CI->getSourceManager().createMainFileIDForMemBuffer(buffer);\n \n \/\/ Set up the preprocessor\n CI->createPreprocessor();\n Preprocessor& PP = CI->getPreprocessor();\n PP.AddPragmaHandler(Pragma);\n PP.getBuiltinInfo().InitializeBuiltins(PP.getIdentifierTable(),\n PP.getLangOptions());\n \/*NoBuiltins = *\/ \/\/true);\n \n \/\/ Set up the ASTContext\n ASTContext *Ctx = new ASTContext(CI->getLangOpts(),\n PP.getSourceManager(), &CI->getTarget(), PP.getIdentifierTable(),\n PP.getSelectorTable(), PP.getBuiltinInfo(), 0);\n CI->setASTContext(Ctx);\n \/\/CI->getSourceManager().clearIDTables(); \/\/do we really need it?\n \n \/\/ Set up the ASTConsumers\n CI->setASTConsumer(new ChainedConsumer());\n\n \/\/ Set up Sema\n CodeCompleteConsumer* CCC = 0;\n CI->createSema(TU_Prefix, CCC);\n\n \/\/ Set CodeGen options\n \/\/ CI->getCodeGenOpts().DebugInfo = 1; \/\/ want debug info\n \/\/ CI->getCodeGenOpts().EmitDeclMetadata = 1; \/\/ For unloading, for later\n CI->getCodeGenOpts().OptimizationLevel = 0; \/\/ see pure SSA, that comes out\n assert((CI->getCodeGenOpts().VerifyModule = 1) && \"When asserts are on, let's also assert the module\");\n return CI;\n }\n\n void CIFactory::SetClingCustomLangOpts(LangOptions& Opts) {\n Opts.EmitAllDecls = 1;\n }\n\n void CIFactory::SetClingTargetLangOpts(LangOptions& Opts, \n const TargetInfo& Target) {\n if (Target.getTriple().getOS() == llvm::Triple::Win32) {\n Opts.MicrosoftExt = 1;\n Opts.MSCVersion = 1300;\n \/\/ Should fix http:\/\/llvm.org\/bugs\/show_bug.cgi?id=10528\n Opts.DelayedTemplateParsing = 1;\n }\n }\n} \/\/ end namespace\n<|endoftext|>"} {"text":"<commit_before><commit_msg>Adding face orientation heuristic<commit_after><|endoftext|>"} {"text":"<commit_before>\/\/===--- VirtualNearMissCheck.cpp - clang-tidy-----------------------------===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"VirtualNearMissCheck.h\"\n#include \"clang\/AST\/ASTContext.h\"\n#include \"clang\/AST\/CXXInheritance.h\"\n#include \"clang\/ASTMatchers\/ASTMatchFinder.h\"\n#include \"clang\/Lex\/Lexer.h\"\n\nusing namespace clang::ast_matchers;\n\nnamespace clang {\nnamespace tidy {\nnamespace misc {\n\nAST_MATCHER(CXXMethodDecl, isStatic) { return Node.isStatic(); }\n\nAST_MATCHER(CXXMethodDecl, isOverloadedOperator) {\n return Node.isOverloadedOperator();\n}\n\n\/\/\/ Finds out if the given method overrides some method.\nstatic bool isOverrideMethod(const CXXMethodDecl *MD) {\n return MD->size_overridden_methods() > 0 || MD->hasAttr<OverrideAttr>();\n}\n\n\/\/\/ Checks whether the return types are covariant, according to\n\/\/\/ C++[class.virtual]p7.\n\/\/\/\n\/\/\/ Similar with clang::Sema::CheckOverridingFunctionReturnType.\n\/\/\/ \\returns true if the return types of BaseMD and DerivedMD are covariant.\nstatic bool checkOverridingFunctionReturnType(const ASTContext *Context,\n const CXXMethodDecl *BaseMD,\n const CXXMethodDecl *DerivedMD) {\n QualType BaseReturnTy = BaseMD->getType()\n ->getAs<FunctionType>()\n ->getReturnType()\n .getCanonicalType();\n QualType DerivedReturnTy = DerivedMD->getType()\n ->getAs<FunctionType>()\n ->getReturnType()\n .getCanonicalType();\n\n if (DerivedReturnTy->isDependentType() || BaseReturnTy->isDependentType())\n return false;\n\n \/\/ Check if return types are identical.\n if (Context->hasSameType(DerivedReturnTy, BaseReturnTy))\n return true;\n\n \/\/\/ Check if the return types are covariant.\n\n \/\/ Both types must be pointers or references to classes.\n if (!(BaseReturnTy->isPointerType() && DerivedReturnTy->isPointerType()) &&\n !(BaseReturnTy->isReferenceType() && DerivedReturnTy->isReferenceType()))\n return false;\n\n \/\/\/ BTy is the class type in return type of BaseMD. For example,\n \/\/\/ B* Base::md()\n \/\/\/ While BRD is the declaration of B.\n QualType DTy = DerivedReturnTy->getPointeeType().getCanonicalType();\n QualType BTy = BaseReturnTy->getPointeeType().getCanonicalType();\n\n const CXXRecordDecl *DRD = DTy->getAsCXXRecordDecl();\n const CXXRecordDecl *BRD = BTy->getAsCXXRecordDecl();\n if (DRD == nullptr || BRD == nullptr)\n return false;\n\n if (!DRD->hasDefinition() || !BRD->hasDefinition())\n return false;\n\n if (DRD == BRD)\n return true;\n\n if (!Context->hasSameUnqualifiedType(DTy, BTy)) {\n \/\/ Begin checking whether the conversion from D to B is valid.\n CXXBasePaths Paths(\/*FindAmbiguities=*\/true, \/*RecordPaths=*\/true,\n \/*DetectVirtual=*\/false);\n\n \/\/ Check whether D is derived from B, and fill in a CXXBasePaths object.\n if (!DRD->isDerivedFrom(BRD, Paths))\n return false;\n\n \/\/ Check ambiguity.\n if (Paths.isAmbiguous(Context->getCanonicalType(BTy).getUnqualifiedType()))\n return false;\n\n \/\/ Check accessibility.\n \/\/ FIXME: We currently only support checking if B is accessible base class\n \/\/ of D, or D is the same class which DerivedMD is in.\n bool IsItself =\n DRD->getCanonicalDecl() == DerivedMD->getParent()->getCanonicalDecl();\n bool HasPublicAccess = false;\n for (const auto &Path : Paths) {\n if (Path.Access == AS_public)\n HasPublicAccess = true;\n }\n if (!HasPublicAccess && !IsItself)\n return false;\n \/\/ End checking conversion from D to B.\n }\n\n \/\/ Both pointers or references should have the same cv-qualification.\n if (DerivedReturnTy.getLocalCVRQualifiers() !=\n BaseReturnTy.getLocalCVRQualifiers())\n return false;\n\n \/\/ The class type D should have the same cv-qualification as or less\n \/\/ cv-qualification than the class type B.\n if (DTy.isMoreQualifiedThan(BTy))\n return false;\n\n return true;\n}\n\n\/\/\/ \\returns decayed type for arrays and functions.\nstatic QualType getDecayedType(QualType Type) {\n if (const auto *Decayed = Type->getAs<DecayedType>())\n return Decayed->getDecayedType();\n return Type;\n}\n\n\/\/\/ \\returns true if the param types are the same.\nstatic bool checkParamTypes(const CXXMethodDecl *BaseMD,\n const CXXMethodDecl *DerivedMD) {\n unsigned NumParamA = BaseMD->getNumParams();\n unsigned NumParamB = DerivedMD->getNumParams();\n if (NumParamA != NumParamB)\n return false;\n\n for (unsigned I = 0; I < NumParamA; I++) {\n if (getDecayedType(BaseMD->getParamDecl(I)->getType().getCanonicalType()) !=\n getDecayedType(\n DerivedMD->getParamDecl(I)->getType().getCanonicalType()))\n return false;\n }\n return true;\n}\n\n\/\/\/ \\returns true if derived method can override base method except for the\n\/\/\/ name.\nstatic bool checkOverrideWithoutName(const ASTContext *Context,\n const CXXMethodDecl *BaseMD,\n const CXXMethodDecl *DerivedMD) {\n if (BaseMD->isStatic() != DerivedMD->isStatic())\n return false;\n\n if (BaseMD->getType() == DerivedMD->getType())\n return true;\n\n \/\/ Now the function types are not identical. Then check if the return types\n \/\/ are covariant and if the param types are the same.\n if (!checkOverridingFunctionReturnType(Context, BaseMD, DerivedMD))\n return false;\n return checkParamTypes(BaseMD, DerivedMD);\n}\n\n\/\/\/ Check whether BaseMD overrides DerivedMD.\n\/\/\/\n\/\/\/ Prerequisite: the class which BaseMD is in should be a base class of that\n\/\/\/ DerivedMD is in.\nstatic bool checkOverrideByDerivedMethod(const CXXMethodDecl *BaseMD,\n const CXXMethodDecl *DerivedMD) {\n for (CXXMethodDecl::method_iterator I = DerivedMD->begin_overridden_methods(),\n E = DerivedMD->end_overridden_methods();\n I != E; ++I) {\n const CXXMethodDecl *OverriddenMD = *I;\n if (BaseMD->getCanonicalDecl() == OverriddenMD->getCanonicalDecl())\n return true;\n }\n\n return false;\n}\n\nbool VirtualNearMissCheck::isPossibleToBeOverridden(\n const CXXMethodDecl *BaseMD) {\n auto Iter = PossibleMap.find(BaseMD);\n if (Iter != PossibleMap.end())\n return Iter->second;\n\n bool IsPossible = !BaseMD->isImplicit() && !isa<CXXConstructorDecl>(BaseMD) &&\n !isa<CXXDestructorDecl>(BaseMD) && BaseMD->isVirtual() &&\n !BaseMD->isOverloadedOperator() &&\n !isa<CXXConversionDecl>(BaseMD);\n PossibleMap[BaseMD] = IsPossible;\n return IsPossible;\n}\n\nbool VirtualNearMissCheck::isOverriddenByDerivedClass(\n const CXXMethodDecl *BaseMD, const CXXRecordDecl *DerivedRD) {\n auto Key = std::make_pair(BaseMD, DerivedRD);\n auto Iter = OverriddenMap.find(Key);\n if (Iter != OverriddenMap.end())\n return Iter->second;\n\n bool IsOverridden = false;\n for (const CXXMethodDecl *DerivedMD : DerivedRD->methods()) {\n if (!isOverrideMethod(DerivedMD))\n continue;\n\n if (checkOverrideByDerivedMethod(BaseMD, DerivedMD)) {\n IsOverridden = true;\n break;\n }\n }\n OverriddenMap[Key] = IsOverridden;\n return IsOverridden;\n}\n\nvoid VirtualNearMissCheck::registerMatchers(MatchFinder *Finder) {\n if (!getLangOpts().CPlusPlus)\n return;\n\n Finder->addMatcher(\n cxxMethodDecl(\n unless(anyOf(isOverride(), isImplicit(), cxxConstructorDecl(),\n cxxDestructorDecl(), cxxConversionDecl(), isStatic(),\n isOverloadedOperator())))\n .bind(\"method\"),\n this);\n}\n\nvoid VirtualNearMissCheck::check(const MatchFinder::MatchResult &Result) {\n const auto *DerivedMD = Result.Nodes.getNodeAs<CXXMethodDecl>(\"method\");\n assert(DerivedMD);\n\n const ASTContext *Context = Result.Context;\n\n const auto *DerivedRD = DerivedMD->getParent()->getDefinition();\n assert(DerivedRD);\n\n for (const auto &BaseSpec : DerivedRD->bases()) {\n if (const auto *BaseRD = BaseSpec.getType()->getAsCXXRecordDecl()) {\n for (const auto *BaseMD : BaseRD->methods()) {\n if (!isPossibleToBeOverridden(BaseMD))\n continue;\n\n if (isOverriddenByDerivedClass(BaseMD, DerivedRD))\n continue;\n\n unsigned EditDistance =\n BaseMD->getName().edit_distance(DerivedMD->getName());\n if (EditDistance > 0 && EditDistance <= EditDistanceThreshold) {\n if (checkOverrideWithoutName(Context, BaseMD, DerivedMD)) {\n \/\/ A \"virtual near miss\" is found.\n auto Range = CharSourceRange::getTokenRange(\n SourceRange(DerivedMD->getLocation()));\n\n bool ApplyFix = !BaseMD->isTemplateInstantiation() &&\n !DerivedMD->isTemplateInstantiation();\n auto Diag =\n diag(DerivedMD->getLocStart(),\n \"method '%0' has a similar name and the same signature as \"\n \"virtual method '%1'; did you mean to override it?\")\n << DerivedMD->getQualifiedNameAsString()\n << BaseMD->getQualifiedNameAsString();\n if (ApplyFix)\n Diag << FixItHint::CreateReplacement(Range, BaseMD->getName());\n }\n }\n }\n }\n }\n}\n\n} \/\/ namespace misc\n} \/\/ namespace tidy\n} \/\/ namespace clang\n<commit_msg>[clang-tidy] Don't compute the edit distance if it's over the threshold.<commit_after>\/\/===--- VirtualNearMissCheck.cpp - clang-tidy-----------------------------===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"VirtualNearMissCheck.h\"\n#include \"clang\/AST\/ASTContext.h\"\n#include \"clang\/AST\/CXXInheritance.h\"\n#include \"clang\/ASTMatchers\/ASTMatchFinder.h\"\n#include \"clang\/Lex\/Lexer.h\"\n\nusing namespace clang::ast_matchers;\n\nnamespace clang {\nnamespace tidy {\nnamespace misc {\n\nAST_MATCHER(CXXMethodDecl, isStatic) { return Node.isStatic(); }\n\nAST_MATCHER(CXXMethodDecl, isOverloadedOperator) {\n return Node.isOverloadedOperator();\n}\n\n\/\/\/ Finds out if the given method overrides some method.\nstatic bool isOverrideMethod(const CXXMethodDecl *MD) {\n return MD->size_overridden_methods() > 0 || MD->hasAttr<OverrideAttr>();\n}\n\n\/\/\/ Checks whether the return types are covariant, according to\n\/\/\/ C++[class.virtual]p7.\n\/\/\/\n\/\/\/ Similar with clang::Sema::CheckOverridingFunctionReturnType.\n\/\/\/ \\returns true if the return types of BaseMD and DerivedMD are covariant.\nstatic bool checkOverridingFunctionReturnType(const ASTContext *Context,\n const CXXMethodDecl *BaseMD,\n const CXXMethodDecl *DerivedMD) {\n QualType BaseReturnTy = BaseMD->getType()\n ->getAs<FunctionType>()\n ->getReturnType()\n .getCanonicalType();\n QualType DerivedReturnTy = DerivedMD->getType()\n ->getAs<FunctionType>()\n ->getReturnType()\n .getCanonicalType();\n\n if (DerivedReturnTy->isDependentType() || BaseReturnTy->isDependentType())\n return false;\n\n \/\/ Check if return types are identical.\n if (Context->hasSameType(DerivedReturnTy, BaseReturnTy))\n return true;\n\n \/\/\/ Check if the return types are covariant.\n\n \/\/ Both types must be pointers or references to classes.\n if (!(BaseReturnTy->isPointerType() && DerivedReturnTy->isPointerType()) &&\n !(BaseReturnTy->isReferenceType() && DerivedReturnTy->isReferenceType()))\n return false;\n\n \/\/\/ BTy is the class type in return type of BaseMD. For example,\n \/\/\/ B* Base::md()\n \/\/\/ While BRD is the declaration of B.\n QualType DTy = DerivedReturnTy->getPointeeType().getCanonicalType();\n QualType BTy = BaseReturnTy->getPointeeType().getCanonicalType();\n\n const CXXRecordDecl *DRD = DTy->getAsCXXRecordDecl();\n const CXXRecordDecl *BRD = BTy->getAsCXXRecordDecl();\n if (DRD == nullptr || BRD == nullptr)\n return false;\n\n if (!DRD->hasDefinition() || !BRD->hasDefinition())\n return false;\n\n if (DRD == BRD)\n return true;\n\n if (!Context->hasSameUnqualifiedType(DTy, BTy)) {\n \/\/ Begin checking whether the conversion from D to B is valid.\n CXXBasePaths Paths(\/*FindAmbiguities=*\/true, \/*RecordPaths=*\/true,\n \/*DetectVirtual=*\/false);\n\n \/\/ Check whether D is derived from B, and fill in a CXXBasePaths object.\n if (!DRD->isDerivedFrom(BRD, Paths))\n return false;\n\n \/\/ Check ambiguity.\n if (Paths.isAmbiguous(Context->getCanonicalType(BTy).getUnqualifiedType()))\n return false;\n\n \/\/ Check accessibility.\n \/\/ FIXME: We currently only support checking if B is accessible base class\n \/\/ of D, or D is the same class which DerivedMD is in.\n bool IsItself =\n DRD->getCanonicalDecl() == DerivedMD->getParent()->getCanonicalDecl();\n bool HasPublicAccess = false;\n for (const auto &Path : Paths) {\n if (Path.Access == AS_public)\n HasPublicAccess = true;\n }\n if (!HasPublicAccess && !IsItself)\n return false;\n \/\/ End checking conversion from D to B.\n }\n\n \/\/ Both pointers or references should have the same cv-qualification.\n if (DerivedReturnTy.getLocalCVRQualifiers() !=\n BaseReturnTy.getLocalCVRQualifiers())\n return false;\n\n \/\/ The class type D should have the same cv-qualification as or less\n \/\/ cv-qualification than the class type B.\n if (DTy.isMoreQualifiedThan(BTy))\n return false;\n\n return true;\n}\n\n\/\/\/ \\returns decayed type for arrays and functions.\nstatic QualType getDecayedType(QualType Type) {\n if (const auto *Decayed = Type->getAs<DecayedType>())\n return Decayed->getDecayedType();\n return Type;\n}\n\n\/\/\/ \\returns true if the param types are the same.\nstatic bool checkParamTypes(const CXXMethodDecl *BaseMD,\n const CXXMethodDecl *DerivedMD) {\n unsigned NumParamA = BaseMD->getNumParams();\n unsigned NumParamB = DerivedMD->getNumParams();\n if (NumParamA != NumParamB)\n return false;\n\n for (unsigned I = 0; I < NumParamA; I++) {\n if (getDecayedType(BaseMD->getParamDecl(I)->getType().getCanonicalType()) !=\n getDecayedType(\n DerivedMD->getParamDecl(I)->getType().getCanonicalType()))\n return false;\n }\n return true;\n}\n\n\/\/\/ \\returns true if derived method can override base method except for the\n\/\/\/ name.\nstatic bool checkOverrideWithoutName(const ASTContext *Context,\n const CXXMethodDecl *BaseMD,\n const CXXMethodDecl *DerivedMD) {\n if (BaseMD->isStatic() != DerivedMD->isStatic())\n return false;\n\n if (BaseMD->getType() == DerivedMD->getType())\n return true;\n\n \/\/ Now the function types are not identical. Then check if the return types\n \/\/ are covariant and if the param types are the same.\n if (!checkOverridingFunctionReturnType(Context, BaseMD, DerivedMD))\n return false;\n return checkParamTypes(BaseMD, DerivedMD);\n}\n\n\/\/\/ Check whether BaseMD overrides DerivedMD.\n\/\/\/\n\/\/\/ Prerequisite: the class which BaseMD is in should be a base class of that\n\/\/\/ DerivedMD is in.\nstatic bool checkOverrideByDerivedMethod(const CXXMethodDecl *BaseMD,\n const CXXMethodDecl *DerivedMD) {\n for (CXXMethodDecl::method_iterator I = DerivedMD->begin_overridden_methods(),\n E = DerivedMD->end_overridden_methods();\n I != E; ++I) {\n const CXXMethodDecl *OverriddenMD = *I;\n if (BaseMD->getCanonicalDecl() == OverriddenMD->getCanonicalDecl())\n return true;\n }\n\n return false;\n}\n\nbool VirtualNearMissCheck::isPossibleToBeOverridden(\n const CXXMethodDecl *BaseMD) {\n auto Iter = PossibleMap.find(BaseMD);\n if (Iter != PossibleMap.end())\n return Iter->second;\n\n bool IsPossible = !BaseMD->isImplicit() && !isa<CXXConstructorDecl>(BaseMD) &&\n !isa<CXXDestructorDecl>(BaseMD) && BaseMD->isVirtual() &&\n !BaseMD->isOverloadedOperator() &&\n !isa<CXXConversionDecl>(BaseMD);\n PossibleMap[BaseMD] = IsPossible;\n return IsPossible;\n}\n\nbool VirtualNearMissCheck::isOverriddenByDerivedClass(\n const CXXMethodDecl *BaseMD, const CXXRecordDecl *DerivedRD) {\n auto Key = std::make_pair(BaseMD, DerivedRD);\n auto Iter = OverriddenMap.find(Key);\n if (Iter != OverriddenMap.end())\n return Iter->second;\n\n bool IsOverridden = false;\n for (const CXXMethodDecl *DerivedMD : DerivedRD->methods()) {\n if (!isOverrideMethod(DerivedMD))\n continue;\n\n if (checkOverrideByDerivedMethod(BaseMD, DerivedMD)) {\n IsOverridden = true;\n break;\n }\n }\n OverriddenMap[Key] = IsOverridden;\n return IsOverridden;\n}\n\nvoid VirtualNearMissCheck::registerMatchers(MatchFinder *Finder) {\n if (!getLangOpts().CPlusPlus)\n return;\n\n Finder->addMatcher(\n cxxMethodDecl(\n unless(anyOf(isOverride(), isImplicit(), cxxConstructorDecl(),\n cxxDestructorDecl(), cxxConversionDecl(), isStatic(),\n isOverloadedOperator())))\n .bind(\"method\"),\n this);\n}\n\nvoid VirtualNearMissCheck::check(const MatchFinder::MatchResult &Result) {\n const auto *DerivedMD = Result.Nodes.getNodeAs<CXXMethodDecl>(\"method\");\n assert(DerivedMD);\n\n const ASTContext *Context = Result.Context;\n\n const auto *DerivedRD = DerivedMD->getParent()->getDefinition();\n assert(DerivedRD);\n\n for (const auto &BaseSpec : DerivedRD->bases()) {\n if (const auto *BaseRD = BaseSpec.getType()->getAsCXXRecordDecl()) {\n for (const auto *BaseMD : BaseRD->methods()) {\n if (!isPossibleToBeOverridden(BaseMD))\n continue;\n\n if (isOverriddenByDerivedClass(BaseMD, DerivedRD))\n continue;\n\n unsigned EditDistance = BaseMD->getName().edit_distance(\n DerivedMD->getName(), EditDistanceThreshold);\n if (EditDistance > 0 && EditDistance <= EditDistanceThreshold) {\n if (checkOverrideWithoutName(Context, BaseMD, DerivedMD)) {\n \/\/ A \"virtual near miss\" is found.\n auto Range = CharSourceRange::getTokenRange(\n SourceRange(DerivedMD->getLocation()));\n\n bool ApplyFix = !BaseMD->isTemplateInstantiation() &&\n !DerivedMD->isTemplateInstantiation();\n auto Diag =\n diag(DerivedMD->getLocStart(),\n \"method '%0' has a similar name and the same signature as \"\n \"virtual method '%1'; did you mean to override it?\")\n << DerivedMD->getQualifiedNameAsString()\n << BaseMD->getQualifiedNameAsString();\n if (ApplyFix)\n Diag << FixItHint::CreateReplacement(Range, BaseMD->getName());\n }\n }\n }\n }\n }\n}\n\n} \/\/ namespace misc\n} \/\/ namespace tidy\n} \/\/ namespace clang\n<|endoftext|>"} {"text":"<commit_before><commit_msg>A number of error catches have been introduced. If the user specifies input that is not sensible (or possible), the program will exit.<commit_after><|endoftext|>"} {"text":"<commit_before><commit_msg>vg filter option fixes<commit_after><|endoftext|>"} {"text":"<commit_before><commit_msg>removed isdust<commit_after><|endoftext|>"} {"text":"<commit_before><commit_msg>Accidentally uncommented old code<commit_after><|endoftext|>"} {"text":"<commit_before>#include <allegro5\/allegro.h>\n#include <cstdio>\n#include <vector>\n\n#include \"renderer.h\"\n#include \"global_constants.h\"\n#include \"entity.h\"\n\nRenderer::Renderer() : spriteloader()\n{\n \/\/ Create a display\n display = al_create_display(WINDOW_WIDTH, WINDOW_HEIGHT);\n if(!display)\n {\n \/\/ FIXME: Make the error argument mean anything?\n fprintf(stderr, \"Fatal Error: Could not create display\\n\");\n throw -1;\n }\n\n background = al_create_bitmap(WINDOW_WIDTH, WINDOW_HEIGHT);\n midground = al_create_bitmap(WINDOW_WIDTH, WINDOW_HEIGHT);\n foreground = al_create_bitmap(WINDOW_WIDTH, WINDOW_HEIGHT);\n}\n\nRenderer::~Renderer()\n{\n \/\/ Cleanup\n al_destroy_display(display);\n}\n\nvoid Renderer::render(Gamestate *currentstate, PlayerPtr myself)\n{\n \/\/ Set camera\n Character *c = static_cast<Character*>(currentstate->get(currentstate->get(myself)->character));\n if (c != 0)\n {\n cam_x = c->x - WINDOW_WIDTH\/2.0;\n cam_y = c->y - WINDOW_HEIGHT\/2.0;\n }\n\n al_set_target_bitmap(background);\n al_clear_to_color(al_map_rgba(0, 0, 0, 0));\n al_set_target_bitmap(midground);\n al_clear_to_color(al_map_rgba(0, 0, 0, 0));\n al_set_target_bitmap(foreground);\n al_clear_to_color(al_map_rgba(0, 0, 0, 0));\n\n \/\/ Go through all objects and let them render themselves on the layers\n for (auto& e : currentstate->entitylist)\n {\n e.second->render(this);\n }\n\n \/\/ Set render target to be the display\n al_set_target_backbuffer(display);\n\n \/\/ Draw the map background first\n currentstate->currentmap->render(cam_x, cam_y);\n\n \/\/ Then draw each layer\n al_draw_bitmap(background, 0, 0, 0);\n al_draw_bitmap(midground, 0, 0, 0);\n al_draw_bitmap(foreground, 0, 0, 0);\n\n al_flip_display();\n}\n<commit_msg>Fixed out of map rendering glitches.<commit_after>#include <allegro5\/allegro.h>\n#include <cstdio>\n#include <vector>\n\n#include \"renderer.h\"\n#include \"global_constants.h\"\n#include \"entity.h\"\n\nRenderer::Renderer() : spriteloader()\n{\n \/\/ Create a display\n display = al_create_display(WINDOW_WIDTH, WINDOW_HEIGHT);\n if(!display)\n {\n \/\/ FIXME: Make the error argument mean anything?\n fprintf(stderr, \"Fatal Error: Could not create display\\n\");\n throw -1;\n }\n\n background = al_create_bitmap(WINDOW_WIDTH, WINDOW_HEIGHT);\n midground = al_create_bitmap(WINDOW_WIDTH, WINDOW_HEIGHT);\n foreground = al_create_bitmap(WINDOW_WIDTH, WINDOW_HEIGHT);\n}\n\nRenderer::~Renderer()\n{\n \/\/ Cleanup\n al_destroy_display(display);\n}\n\nvoid Renderer::render(Gamestate *currentstate, PlayerPtr myself)\n{\n \/\/ Set camera\n Character *c = static_cast<Character*>(currentstate->get(currentstate->get(myself)->character));\n if (c != 0)\n {\n cam_x = c->x - WINDOW_WIDTH\/2.0;\n cam_y = c->y - WINDOW_HEIGHT\/2.0;\n }\n\n al_set_target_bitmap(background);\n al_clear_to_color(al_map_rgba(0, 0, 0, 0));\n al_set_target_bitmap(midground);\n al_clear_to_color(al_map_rgba(0, 0, 0, 0));\n al_set_target_bitmap(foreground);\n al_clear_to_color(al_map_rgba(0, 0, 0, 0));\n\n \/\/ Go through all objects and let them render themselves on the layers\n for (auto& e : currentstate->entitylist)\n {\n e.second->render(this);\n }\n\n \/\/ Set render target to be the display\n al_set_target_backbuffer(display);\n\n \/\/ Clear black\n al_clear_to_color(al_map_rgba(0, 0, 0, 1));\n\n \/\/ Draw the map background first\n currentstate->currentmap->render(cam_x, cam_y);\n\n \/\/ Then draw each layer\n al_draw_bitmap(background, 0, 0, 0);\n al_draw_bitmap(midground, 0, 0, 0);\n al_draw_bitmap(foreground, 0, 0, 0);\n\n al_flip_display();\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"RapidExternalEvtGen.h\"\n\n#include <cstdlib>\n#include <fstream>\n#include <queue>\n\n#include \"TRandom.h\"\n#include \"TSystem.h\"\n\n#ifdef RAPID_EVTGEN\n#include \"EvtGen\/EvtGen.hh\"\n#include \"EvtGenBase\/EvtRandomEngine.hh\"\n#include \"EvtGenBase\/EvtAbsRadCorr.hh\"\n#include \"EvtGenBase\/EvtDecayBase.hh\"\n#include \"EvtGenBase\/EvtParticle.hh\"\n#include \"EvtGenBase\/EvtParticleFactory.hh\"\n#include \"EvtGenBase\/EvtPatches.hh\"\n#include \"EvtGenBase\/EvtPDL.hh\"\n#include \"EvtGenBase\/EvtMTRandomEngine.hh\"\n\n#include \"EvtGenExternal\/EvtExternalGenList.hh\"\n#endif\n\nbool RapidExternalEvtGen::decay(std::vector<RapidParticle*>& parts) {\n#ifdef RAPID_EVTGEN\n\tEvtParticle* theParent(0);\n\n\tif(parts.size() < 1) {\n\t\tstd::cout << \"WARNING in RapidExternalEvtGen::decay : There are no particles to decay.\" << std::endl;\n\t\treturn false;\n\t}\n\tEvtId theId = EvtPDL::evtIdFromLundKC(parts[0]->id());\n\n\t\/\/ Parent particle 4-momentum\n\tTLorentzVector pIn = parts[0]->getP();\n\tEvtVector4R pInit(pIn.E(),pIn.Px(),pIn.Py(),pIn.Pz());\n\n\ttheParent = EvtParticleFactory::particleFactory(theId, pInit);\n\tif (theParent->getSpinStates() == 3) {theParent->setVectorSpinDensity();}\n\n\t\/\/ Generate the event\n\tevtGen_->generateDecay(theParent);\n\n\t\/\/ Store particles to read in the order RapidSim stores them\n\tstd::queue<EvtParticle*> evtParts;\n\t\/\/ Also store the number of children expected for each of these particles so we can remove PHOTOS photons\n\tstd::queue<int> nExpectedChildren;\n\tevtParts.push(theParent);\n\tnExpectedChildren.push(parts[0]->nDaughters());\n\n\tEvtVector4R x4Evt;\n\tEvtVector4R p4Evt;\n\tTLorentzVector p4TLV;\n\n\tint iPart=1; \/\/ The momentum and origin vertex of the first particle are already set\n\n\twhile(!evtParts.empty()) {\n\t\tEvtParticle* theParticle = evtParts.front();\n\n\t\t\/\/ B0 and Bs may mix in EvtGen - RapidSim ignores this step and only records the second state\n\t\twhile(theParticle->getNDaug()==1) {\n\t\t\ttheParticle = theParticle->getDaug(0);\n\t\t}\n\n\t\tint nChildren = nExpectedChildren.front();\n\n\t\t\/\/ Loop over the daughter tracks\n\t\tfor (int iChild = 0; iChild < nChildren; ++iChild) {\n\t\t\tEvtParticle* child = theParticle->getDaug(iChild);\n\n\t\t\tif (child != 0) {\n\t\t\t\tp4Evt = child->getP4Lab();\n\t\t\t\tx4Evt = child->get4Pos();\n\t\t\t\tp4TLV.SetPxPyPzE(p4Evt.get(1),p4Evt.get(2),p4Evt.get(3),p4Evt.get(0));\n\t\t\t\tif(parts.size() < iPart+1u) {\n\t\t\t\t\tstd::cout << \"WARNING in RapidExternalEvtGen::decay : EvtGen has produced too many particles.\" << std::endl;\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t\tparts[iPart]->setP(p4TLV);\n\t\t\t\tparts[iPart]->getOriginVertex()->setXYZ(1e3*x4Evt.get(1),1e3*x4Evt.get(2),1e3*x4Evt.get(3));\n\t\t\t\tevtParts.push(child);\n\t\t\t\tnExpectedChildren.push(parts[iPart]->nDaughters());\n\t\t\t\t++iPart;\n\t\t\t}\n\t\t}\n\n\t\tdelete theParticle;\n\t\tevtParts.pop();\n\t\tnExpectedChildren.pop();\n\t}\n\n\treturn true;\n#else\n\tif(!suppressWarning_) {\n\t\tstd::cout << \"WARNING in RapidExternalEvtGen::decay : EvtGen extension not compiled. Will not use EvtGen to decay \" << parts[0]->name() << \".\" << std::endl;\n\t\tsuppressWarning_=true;\n\t}\n\n\treturn false;\n#endif\n}\n\nbool RapidExternalEvtGen::setup() {\n#ifdef RAPID_EVTGEN\n\tstd::cout << \"INFO in RapidExternalEvtGen::setup : Setting decay for external EvtGen generator.\" << std::endl;\n\tif(!evtGen_) setupGenerator();\n\tevtGen_->readUDecay(decFileName_.Data());\n\treturn true;\n#else\n\tstd::cout << \"WARNING in RapidExternalEvtGen::setup : EvtGen extension not compiled.\" << std::endl;\n\treturn false;\n#endif\n}\n\nbool RapidExternalEvtGen::setupGenerator() {\n#ifdef RAPID_EVTGEN\n\tstd::cout << \"INFO in RapidExternalEvtGen::setupGenerator : Setting up external EvtGen generator.\" << std::endl;\n\tEvtRandomEngine* randomEngine = 0;\n\tEvtAbsRadCorr* radCorrEngine = 0;\n\tstd::list<EvtDecayBase*> extraModels;\n\n\t\/\/ Define the random number generator\n\tuint seed = gRandom->GetSeed();\n\trandomEngine = new EvtMTRandomEngine(seed);\n\n\tbool useEvtGenRandom(false);\n\tEvtExternalGenList genList(true, \"\", \"gamma\", useEvtGenRandom);\n\tradCorrEngine = genList.getPhotosModel();\n\textraModels = genList.getListOfModels();\n\n\tTString evtPDLPath;\n\tevtPDLPath += getenv(\"EVTGEN_ROOT\");\n\tevtPDLPath += \"\/evt.pdl\";\n\n\tbool foundDec=false;\n\n\tTString decPath;\n\tdecPath += getenv(\"RAPIDSIM_CONFIG\");\n\tif(decPath!=\"\") {\n\t\tdecPath += \"\/config\/evtgen\/DECAY.DEC\";\n\t\tif(!gSystem->AccessPathName(decPath)) foundDec=true;\n\t}\n\n\t\/\/ We want to initialise EvtGen before we define our DEC file so we can use EvtPDL\n\t\/\/ To do this pass an empty DEC file as the main decay file and pass our file later as a user file\n\tif(!foundDec) {\n\t\tdecPath += getenv(\"RAPIDSIM_ROOT\");\n\t\tdecPath += \"\/config\/evtgen\/DECAY.DEC\";\n\t}\n\n\tevtGen_ = new EvtGen(decPath.Data(), evtPDLPath.Data(), randomEngine,\n\t\t\tradCorrEngine, &extraModels);\n\n\treturn true;\n#else\n\tstd::cout << \"WARNING in RapidExternalEvtGen::setup : EvtGen extension not compiled.\" << std::endl;\n\treturn false;\n#endif\n}\n\nvoid RapidExternalEvtGen::writeDecFile(TString fname, std::vector<RapidParticle*>& parts, bool usePhotos) {\n#ifdef RAPID_EVTGEN\n\tif(!evtGen_) setupGenerator();\n\n\tdecFileName_ = fname+\".DEC\";\n\tstd::cout << \"INFO in RapidExternalEvtGen::writeDecFile : Writing EvtGen DEC file : \" << decFileName_ << std::endl;\n\n\tstd::ofstream fout;\n\tfout.open(decFileName_, std::ofstream::out);\n\n\tif(usePhotos) {\n\t\tfout << \"yesPhotos\\n\" << std::endl;\n\t} else {\n\t\tfout << \"noPhotos\\n\" << std::endl;\n\t}\n\n\t\/\/ Loop over all particles and write out Decay rule for each\n\tfor(unsigned int iPart=0; iPart<parts.size(); ++iPart) {\n\t\tunsigned int nChildren = parts[iPart]->nDaughters();\n\t\tif(nChildren>0) {\n\t\t\tint id = parts[iPart]->id();\n\t\t\tfout << \"Decay \" << getEvtGenName(id) << \"\\n1.00\\t\";\n\t\t\tif ( !(parts[iPart]->evtGenDecayModel()).Contains(\"TAUOLA\") ) {\n\t\t\t\tfor(unsigned int iChild=0; iChild<nChildren; ++iChild) {\n\t\t\t\t\tfout << getEvtGenName(parts[iPart]->daughter(iChild)->id()) << \"\\t\";\n\t\t\t\t}\n\t\t\t}\n\t\t\tfout << parts[iPart]->evtGenDecayModel() << \";\" << std::endl;\n\t\t\tfout <<\"Enddecay\" << std::endl;\n\n\t\t\t\/\/ Workaround to deal with mixing of B0 and Bs\n\t\t\tif(TMath::Abs(id)==531||TMath::Abs(id)==511) fout <<\"CDecay \" << getEvtGenConjName(id) << std::endl << std::endl;\n\t\t}\n\t}\n\tfout <<\"End\\n\" << std::endl;\n\tfout.close();\n#else\n\tstd::cout << \"WARNING in RapidExternalEvtGen::writeDecFile : EvtGen extension not compiled. Cannot write DEC file \"\n\t\t << fname << \" for \" << parts.size() << \"particles with usePhotos=\" << usePhotos << \".\" << std::endl;\n#endif\n}\n\nTString RapidExternalEvtGen::getEvtGenName(int id) {\n#ifdef RAPID_EVTGEN\n\tEvtId evtId = EvtPDL::evtIdFromLundKC(id);\n\tTString name = EvtPDL::name(evtId);\n\treturn name;\n#else\n\tstd::cout << \"WARNING in RapidExternalEvtGen::getEvtGenName : EvtGen extension not compiled. Cannot lookup name for particle ID \" << id << \".\" << std::endl;\n\treturn \"\";\n#endif\n}\n\nTString RapidExternalEvtGen::getEvtGenConjName(int id) {\n#ifdef RAPID_EVTGEN\n\tEvtId evtId = EvtPDL::evtIdFromLundKC(id);\n\tEvtId evtConjId = EvtPDL::chargeConj(evtId);\n\tTString name = EvtPDL::name(evtConjId);\n\treturn name;\n#else\n\tstd::cout << \"WARNING in RapidExternalEvtGen::getEvtGenConjName : EvtGen extension not compiled. Cannot lookup conjugate name for particle ID \" << id << \".\" << std::endl;\n\treturn \"\";\n#endif\n}\n<commit_msg>Fix memory leak when using EvtGen with PHOTOS<commit_after>#include \"RapidExternalEvtGen.h\"\n\n#include <cstdlib>\n#include <fstream>\n#include <queue>\n\n#include \"TRandom.h\"\n#include \"TSystem.h\"\n\n#ifdef RAPID_EVTGEN\n#include \"EvtGen\/EvtGen.hh\"\n#include \"EvtGenBase\/EvtRandomEngine.hh\"\n#include \"EvtGenBase\/EvtAbsRadCorr.hh\"\n#include \"EvtGenBase\/EvtDecayBase.hh\"\n#include \"EvtGenBase\/EvtParticle.hh\"\n#include \"EvtGenBase\/EvtParticleFactory.hh\"\n#include \"EvtGenBase\/EvtPatches.hh\"\n#include \"EvtGenBase\/EvtPDL.hh\"\n#include \"EvtGenBase\/EvtMTRandomEngine.hh\"\n\n#include \"EvtGenExternal\/EvtExternalGenList.hh\"\n#endif\n\nbool RapidExternalEvtGen::decay(std::vector<RapidParticle*>& parts) {\n#ifdef RAPID_EVTGEN\n\tEvtParticle* theParent(0);\n\n\tif(parts.size() < 1) {\n\t\tstd::cout << \"WARNING in RapidExternalEvtGen::decay : There are no particles to decay.\" << std::endl;\n\t\treturn false;\n\t}\n\tEvtId theId = EvtPDL::evtIdFromLundKC(parts[0]->id());\n\n\t\/\/ Parent particle 4-momentum\n\tTLorentzVector pIn = parts[0]->getP();\n\tEvtVector4R pInit(pIn.E(),pIn.Px(),pIn.Py(),pIn.Pz());\n\n\ttheParent = EvtParticleFactory::particleFactory(theId, pInit);\n\tif (theParent->getSpinStates() == 3) {theParent->setVectorSpinDensity();}\n\n\t\/\/ Generate the event\n\tevtGen_->generateDecay(theParent);\n\n\t\/\/ Store particles to read in the order RapidSim stores them\n\tstd::queue<EvtParticle*> evtParts;\n\t\/\/ Also store the number of children expected for each of these particles so we can remove PHOTOS photons\n\tstd::queue<int> nExpectedChildren;\n\tevtParts.push(theParent);\n\tnExpectedChildren.push(parts[0]->nDaughters());\n\n\tEvtVector4R x4Evt;\n\tEvtVector4R p4Evt;\n\tTLorentzVector p4TLV;\n\n\tint iPart=1; \/\/ The momentum and origin vertex of the first particle are already set\n\n\twhile(!evtParts.empty()) {\n\t\tEvtParticle* theParticle = evtParts.front();\n\n\t\t\/\/ B0 and Bs may mix in EvtGen - RapidSim ignores this step and only records the second state\n\t\twhile(theParticle->getNDaug()==1) {\n\t\t\ttheParticle = theParticle->getDaug(0);\n\t\t}\n\n\t\tuint nChildren = nExpectedChildren.front();\n\n\t\t\/\/ Loop over the daughter tracks\n\t\tfor (uint iChild = 0; iChild < nChildren; ++iChild) {\n\t\t\tEvtParticle* child = theParticle->getDaug(iChild);\n\n\t\t\tif (child != 0) {\n\t\t\t\tp4Evt = child->getP4Lab();\n\t\t\t\tx4Evt = child->get4Pos();\n\t\t\t\tp4TLV.SetPxPyPzE(p4Evt.get(1),p4Evt.get(2),p4Evt.get(3),p4Evt.get(0));\n\t\t\t\tif(parts.size() < iPart+1u) {\n\t\t\t\t\tstd::cout << \"WARNING in RapidExternalEvtGen::decay : EvtGen has produced too many particles.\" << std::endl;\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t\tparts[iPart]->setP(p4TLV);\n\t\t\t\tparts[iPart]->getOriginVertex()->setXYZ(1e3*x4Evt.get(1),1e3*x4Evt.get(2),1e3*x4Evt.get(3));\n\t\t\t\tevtParts.push(child);\n\t\t\t\tnExpectedChildren.push(parts[iPart]->nDaughters());\n\t\t\t\t++iPart;\n\t\t\t}\n\t\t}\n\n\t\t\/\/ Clean up any PHOTOS photons\n\t\tfor (uint iChild = nChildren; iChild < theParticle->getNDaug(); ++iChild) {\n\t\t\tdelete theParticle->getDaug(iChild);\n\t\t}\n\t\tdelete theParticle;\n\t\tevtParts.pop();\n\t\tnExpectedChildren.pop();\n\t}\n\n\treturn true;\n#else\n\tif(!suppressWarning_) {\n\t\tstd::cout << \"WARNING in RapidExternalEvtGen::decay : EvtGen extension not compiled. Will not use EvtGen to decay \" << parts[0]->name() << \".\" << std::endl;\n\t\tsuppressWarning_=true;\n\t}\n\n\treturn false;\n#endif\n}\n\nbool RapidExternalEvtGen::setup() {\n#ifdef RAPID_EVTGEN\n\tstd::cout << \"INFO in RapidExternalEvtGen::setup : Setting decay for external EvtGen generator.\" << std::endl;\n\tif(!evtGen_) setupGenerator();\n\tevtGen_->readUDecay(decFileName_.Data());\n\treturn true;\n#else\n\tstd::cout << \"WARNING in RapidExternalEvtGen::setup : EvtGen extension not compiled.\" << std::endl;\n\treturn false;\n#endif\n}\n\nbool RapidExternalEvtGen::setupGenerator() {\n#ifdef RAPID_EVTGEN\n\tstd::cout << \"INFO in RapidExternalEvtGen::setupGenerator : Setting up external EvtGen generator.\" << std::endl;\n\tEvtRandomEngine* randomEngine = 0;\n\tEvtAbsRadCorr* radCorrEngine = 0;\n\tstd::list<EvtDecayBase*> extraModels;\n\n\t\/\/ Define the random number generator\n\tuint seed = gRandom->GetSeed();\n\trandomEngine = new EvtMTRandomEngine(seed);\n\n\tbool useEvtGenRandom(false);\n\tEvtExternalGenList genList(true, \"\", \"gamma\", useEvtGenRandom);\n\tradCorrEngine = genList.getPhotosModel();\n\textraModels = genList.getListOfModels();\n\n\tTString evtPDLPath;\n\tevtPDLPath += getenv(\"EVTGEN_ROOT\");\n\tevtPDLPath += \"\/evt.pdl\";\n\n\tbool foundDec=false;\n\n\tTString decPath;\n\tdecPath += getenv(\"RAPIDSIM_CONFIG\");\n\tif(decPath!=\"\") {\n\t\tdecPath += \"\/config\/evtgen\/DECAY.DEC\";\n\t\tif(!gSystem->AccessPathName(decPath)) foundDec=true;\n\t}\n\n\t\/\/ We want to initialise EvtGen before we define our DEC file so we can use EvtPDL\n\t\/\/ To do this pass an empty DEC file as the main decay file and pass our file later as a user file\n\tif(!foundDec) {\n\t\tdecPath += getenv(\"RAPIDSIM_ROOT\");\n\t\tdecPath += \"\/config\/evtgen\/DECAY.DEC\";\n\t}\n\n\tevtGen_ = new EvtGen(decPath.Data(), evtPDLPath.Data(), randomEngine,\n\t\t\tradCorrEngine, &extraModels);\n\n\treturn true;\n#else\n\tstd::cout << \"WARNING in RapidExternalEvtGen::setup : EvtGen extension not compiled.\" << std::endl;\n\treturn false;\n#endif\n}\n\nvoid RapidExternalEvtGen::writeDecFile(TString fname, std::vector<RapidParticle*>& parts, bool usePhotos) {\n#ifdef RAPID_EVTGEN\n\tif(!evtGen_) setupGenerator();\n\n\tdecFileName_ = fname+\".DEC\";\n\tstd::cout << \"INFO in RapidExternalEvtGen::writeDecFile : Writing EvtGen DEC file : \" << decFileName_ << std::endl;\n\n\tstd::ofstream fout;\n\tfout.open(decFileName_, std::ofstream::out);\n\n\tif(usePhotos) {\n\t\tfout << \"yesPhotos\\n\" << std::endl;\n\t} else {\n\t\tfout << \"noPhotos\\n\" << std::endl;\n\t}\n\n\t\/\/ Loop over all particles and write out Decay rule for each\n\tfor(unsigned int iPart=0; iPart<parts.size(); ++iPart) {\n\t\tunsigned int nChildren = parts[iPart]->nDaughters();\n\t\tif(nChildren>0) {\n\t\t\tint id = parts[iPart]->id();\n\t\t\tfout << \"Decay \" << getEvtGenName(id) << \"\\n1.00\\t\";\n\t\t\tif ( !(parts[iPart]->evtGenDecayModel()).Contains(\"TAUOLA\") ) {\n\t\t\t\tfor(unsigned int iChild=0; iChild<nChildren; ++iChild) {\n\t\t\t\t\tfout << getEvtGenName(parts[iPart]->daughter(iChild)->id()) << \"\\t\";\n\t\t\t\t}\n\t\t\t}\n\t\t\tfout << parts[iPart]->evtGenDecayModel() << \";\" << std::endl;\n\t\t\tfout <<\"Enddecay\" << std::endl;\n\n\t\t\t\/\/ Workaround to deal with mixing of B0 and Bs\n\t\t\tif(TMath::Abs(id)==531||TMath::Abs(id)==511) fout <<\"CDecay \" << getEvtGenConjName(id) << std::endl << std::endl;\n\t\t}\n\t}\n\tfout <<\"End\\n\" << std::endl;\n\tfout.close();\n#else\n\tstd::cout << \"WARNING in RapidExternalEvtGen::writeDecFile : EvtGen extension not compiled. Cannot write DEC file \"\n\t\t << fname << \" for \" << parts.size() << \"particles with usePhotos=\" << usePhotos << \".\" << std::endl;\n#endif\n}\n\nTString RapidExternalEvtGen::getEvtGenName(int id) {\n#ifdef RAPID_EVTGEN\n\tEvtId evtId = EvtPDL::evtIdFromLundKC(id);\n\tTString name = EvtPDL::name(evtId);\n\treturn name;\n#else\n\tstd::cout << \"WARNING in RapidExternalEvtGen::getEvtGenName : EvtGen extension not compiled. Cannot lookup name for particle ID \" << id << \".\" << std::endl;\n\treturn \"\";\n#endif\n}\n\nTString RapidExternalEvtGen::getEvtGenConjName(int id) {\n#ifdef RAPID_EVTGEN\n\tEvtId evtId = EvtPDL::evtIdFromLundKC(id);\n\tEvtId evtConjId = EvtPDL::chargeConj(evtId);\n\tTString name = EvtPDL::name(evtConjId);\n\treturn name;\n#else\n\tstd::cout << \"WARNING in RapidExternalEvtGen::getEvtGenConjName : EvtGen extension not compiled. Cannot lookup conjugate name for particle ID \" << id << \".\" << std::endl;\n\treturn \"\";\n#endif\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n\nCopyright (c) 2013, Arvid Norberg\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in\n the documentation and\/or other materials provided with the distribution.\n * Neither the name of the author nor the names of its\n contributors may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#include \"libtorrent\/resolver.hpp\"\n#include <boost\/bind.hpp>\n#include \"libtorrent\/debug.hpp\"\n\nnamespace libtorrent\n{\n\/\/ #error the first places to use this resolver is the http_connection\/http_tracker_connection and udp_tracker_connection. make sure to prefer cache on shutdown\n\n\tresolver::resolver(io_service& ios)\n\t\t: m_ios(ios)\n\t\t, m_resolver(ios)\n\t\t, m_max_size(700)\n\t\t, m_timeout(1200)\n\t{}\n\n\tvoid resolver::on_lookup(error_code const& ec, tcp::resolver::iterator i\n\t\t, resolver_interface::callback_t h, std::string hostname)\n\t{\n#if defined TORRENT_ASIO_DEBUGGING\n\t\tcomplete_async(\"resolver::on_lookup\");\n#endif\n\t\tif (ec)\n\t\t{\n\t\t\tstd::vector<address> empty;\n\t\t\th(ec, empty);\n\t\t\treturn;\n\t\t}\n\t\n\t\tdns_cache_entry& ce = m_cache[hostname];\n\t\ttime_t now = time(NULL);\n\t\tce.last_seen = now;\n\t\tce.addresses.clear();\n\t\twhile (i != tcp::resolver::iterator())\n\t\t{\n\t\t\tce.addresses.push_back(i->endpoint().address());\n\t\t\t++i;\n\t\t}\n\n\t\th(ec, ce.addresses);\n\n\t\t\/\/ if m_cache grows too big, weed out the\n\t\t\/\/ oldest entries\n\t\tif (m_cache.size() > m_max_size)\n\t\t{\n\t\t\tcache_t::iterator oldest = m_cache.begin();\n\t\t\tfor (cache_t::iterator i = m_cache.begin();\n\t\t\t\ti != m_cache.end(); ++i)\n\t\t\t{\n\t\t\t\tcache_t::iterator e = i;\n\t\t\t\t++i;\n\t\t\t\tif (i->second.last_seen < oldest->second.last_seen)\n\t\t\t\t\toldest = i;\n\t\t\t}\n\n\t\t\t\/\/ remove the oldest entry\n\t\t\tm_cache.erase(oldest);\n\t\t}\n\t}\n\t\n\n\tvoid resolver::async_resolve(std::string const& host, int flags\n\t\t, resolver_interface::callback_t const& h)\n\t{\n\t\tcache_t::iterator i = m_cache.find(host);\n\t\tif (i != m_cache.end())\n\t\t{\n\t\t\t\/\/ keep cache entries valid for m_timeout seconds\n\t\t\tif ((flags & resolver_interface::prefer_cache)\n\t\t\t\t|| i->second.last_seen + m_timeout >= time(NULL))\n\t\t\t{\n\t\t\t\terror_code ec;\n\t\t\t\tm_ios.post(boost::bind(h, ec, i->second.addresses));\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t\n\t\t\/\/ the port is ignored\n\t\ttcp::resolver::query q(host, \"80\");\n\n#if defined TORRENT_ASIO_DEBUGGING\n\t\tadd_outstanding_async(\"resolver::on_lookup\");\n#endif\n\t\tm_resolver.async_resolve(q, boost::bind(&resolver::on_lookup, this, _1, _2\n\t\t\t, h, host));\n\t}\n}\n\n<commit_msg>fix todo comment<commit_after>\/*\n\nCopyright (c) 2013, Arvid Norberg\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in\n the documentation and\/or other materials provided with the distribution.\n * Neither the name of the author nor the names of its\n contributors may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#include \"libtorrent\/resolver.hpp\"\n#include <boost\/bind.hpp>\n#include \"libtorrent\/debug.hpp\"\n\nnamespace libtorrent\n{\n\/\/ TODO: 3 the first places to use this resolver is the\n\/\/ http_connection\/http_tracker_connection and udp_tracker_connection.\n\/\/ make sure to prefer cache on shutdown\n\tresolver::resolver(io_service& ios)\n\t\t: m_ios(ios)\n\t\t, m_resolver(ios)\n\t\t, m_max_size(700)\n\t\t, m_timeout(1200)\n\t{}\n\n\tvoid resolver::on_lookup(error_code const& ec, tcp::resolver::iterator i\n\t\t, resolver_interface::callback_t h, std::string hostname)\n\t{\n#if defined TORRENT_ASIO_DEBUGGING\n\t\tcomplete_async(\"resolver::on_lookup\");\n#endif\n\t\tif (ec)\n\t\t{\n\t\t\tstd::vector<address> empty;\n\t\t\th(ec, empty);\n\t\t\treturn;\n\t\t}\n\t\n\t\tdns_cache_entry& ce = m_cache[hostname];\n\t\ttime_t now = time(NULL);\n\t\tce.last_seen = now;\n\t\tce.addresses.clear();\n\t\twhile (i != tcp::resolver::iterator())\n\t\t{\n\t\t\tce.addresses.push_back(i->endpoint().address());\n\t\t\t++i;\n\t\t}\n\n\t\th(ec, ce.addresses);\n\n\t\t\/\/ if m_cache grows too big, weed out the\n\t\t\/\/ oldest entries\n\t\tif (m_cache.size() > m_max_size)\n\t\t{\n\t\t\tcache_t::iterator oldest = m_cache.begin();\n\t\t\tfor (cache_t::iterator i = m_cache.begin();\n\t\t\t\ti != m_cache.end(); ++i)\n\t\t\t{\n\t\t\t\tcache_t::iterator e = i;\n\t\t\t\t++i;\n\t\t\t\tif (i->second.last_seen < oldest->second.last_seen)\n\t\t\t\t\toldest = i;\n\t\t\t}\n\n\t\t\t\/\/ remove the oldest entry\n\t\t\tm_cache.erase(oldest);\n\t\t}\n\t}\n\t\n\n\tvoid resolver::async_resolve(std::string const& host, int flags\n\t\t, resolver_interface::callback_t const& h)\n\t{\n\t\tcache_t::iterator i = m_cache.find(host);\n\t\tif (i != m_cache.end())\n\t\t{\n\t\t\t\/\/ keep cache entries valid for m_timeout seconds\n\t\t\tif ((flags & resolver_interface::prefer_cache)\n\t\t\t\t|| i->second.last_seen + m_timeout >= time(NULL))\n\t\t\t{\n\t\t\t\terror_code ec;\n\t\t\t\tm_ios.post(boost::bind(h, ec, i->second.addresses));\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t\n\t\t\/\/ the port is ignored\n\t\ttcp::resolver::query q(host, \"80\");\n\n#if defined TORRENT_ASIO_DEBUGGING\n\t\tadd_outstanding_async(\"resolver::on_lookup\");\n#endif\n\t\tm_resolver.async_resolve(q, boost::bind(&resolver::on_lookup, this, _1, _2\n\t\t\t, h, host));\n\t}\n}\n\n<|endoftext|>"} {"text":"<commit_before>#include \"zipper.h\"\n#include \"defs.h\"\n#include \"tools.h\"\n\n#include <fstream>\n#include <stdexcept>\n\nnamespace zipper {\n\n\tstruct Zipper::Impl\n\t{\n\t\tZipper& m_outer;\n\t\tzipFile m_zf;\n\t\tourmemory_t m_zipmem;\n\t\tzlib_filefunc_def m_filefunc;\n\n\t\tImpl(Zipper& outer) : m_outer(outer), m_zipmem(), m_filefunc()\n\t\t{\n\t\t\tm_zf = NULL;\n\t\t\t\/\/m_filefunc = { 0 };\n\t\t}\n\n\t\tbool initFile(const std::string& filename)\n\t\t{\n\t\t\t#ifdef USEWIN32IOAPI\n\t\t\t\tzlib_filefunc64_def ffunc = { 0 };\n\t\t\t#endif\n\n\t\t\tint mode = 0;\n\t\t\tint flags = Zipper::Append;\n\n\t\t\t\/* open the zip file for output *\/\n\t\t\tif (checkFileExists(filename))\n\t\t\t\tmode = (flags & Zipper::Overwrite) ? APPEND_STATUS_CREATE : APPEND_STATUS_ADDINZIP;\n\t\t\telse\n\t\t\t\tmode = APPEND_STATUS_CREATE;\n\n\t\t\t#ifdef USEWIN32IOAPI\n\t\t\t\tfill_win32_filefunc64A(&ffunc);\n\t\t\t\tm_zf = zipOpen2_64(filename.c_str(), mode, NULL, &ffunc);\n\t\t\t#else\n\t\t\t\tm_zf = zipOpen64(filename.c_str(), mode);\n\t\t\t#endif\n\n\t\t\treturn NULL != m_zf;\n\t\t}\n\n\t\tbool initWithStream(std::iostream& stream)\n\t\t{\n\t\t\tm_zipmem.grow = 1;\n\n\t\t\tstream.seekg(0, std::ios::end);\n\t\t\tsize_t size = (size_t)stream.tellg();\n\t\t\tstream.seekg(0);\n\n\t\t\tif (size > 0)\n\t\t\t{\n\t\t\t\tm_zipmem.base = new char[(size_t)size];\n\t\t\t\tstream.read(m_zipmem.base, size);\n\t\t\t}\n\n\t\t\tfill_memory_filefunc(&m_filefunc, &m_zipmem);\n\t\t\t\n\t\t\treturn initMemory(size > 0 ? APPEND_STATUS_CREATE : APPEND_STATUS_ADDINZIP, m_filefunc);\n\t\t}\n\n\t\tbool initWithVector(std::vector<unsigned char>& buffer)\n\t\t{\n\t\t\tm_zipmem.grow = 1;\n\n\t\t\tif (!buffer.empty())\n\t\t\t{\n\t\t\t\tm_zipmem.base = new char[buffer.size()];\n\t\t\t\tmemcpy(m_zipmem.base, (char*)buffer.data(), buffer.size());\n\t\t\t\tm_zipmem.size = (uLong)buffer.size();\n\t\t\t}\n\n\t\t\tfill_memory_filefunc(&m_filefunc, &m_zipmem);\n\n\t\t\treturn initMemory(buffer.empty() ? APPEND_STATUS_CREATE : APPEND_STATUS_ADDINZIP, m_filefunc);\n\t\t}\n\n\t\tbool initMemory(int mode, zlib_filefunc_def& filefunc)\n\t\t{\n\t\t\tm_zf = zipOpen3(\"__notused__\", mode, 0, 0, &filefunc);\n\t\t\treturn m_zf != NULL;\n\t\t}\n\n\t\tbool add(std::istream& input_stream, const std::string& nameInZip, const std::string& password, int flags)\n\t\t{\n\t\t\tif (!m_zf) return false;\n\n\t\t\tint compressLevel = 0;\n\t\t\tint zip64 = 0;\n\t\t\tint size_buf = WRITEBUFFERSIZE;\n\t\t\tint err = ZIP_OK;\n\t\t\tunsigned long crcFile = 0;\n\n\t\t\tzip_fileinfo zi = { 0 };\n\t\t\tsize_t size_read;\n\n\t\t\tstd::vector<char> buff;\n\t\t\tbuff.resize(size_buf);\n\n\t\t\tif (nameInZip.empty())\n\t\t\t\treturn false;\n\n\t\t\tif (flags & Zipper::Faster) compressLevel = 1;\n\t\t\tif (flags & Zipper::Better) compressLevel = 9;\n\n\t\t\tzip64 = (int)isLargeFile(input_stream);\n\t\t\tif (password.empty())\n\t\t\t\terr = zipOpenNewFileInZip64(m_zf,\n\t\t\t\t\tnameInZip.c_str(),\n\t\t\t\t\t&zi,\n\t\t\t\t\tNULL,\n\t\t\t\t\t0,\n\t\t\t\t\tNULL,\n\t\t\t\t\t0,\n\t\t\t\t\tNULL \/* comment*\/,\n\t\t\t\t\t(compressLevel != 0) ? Z_DEFLATED : 0,\n\t\t\t\t\tcompressLevel,\n\t\t\t\t\tzip64);\n\t\t\telse\n\t\t\t{\n\t\t\t\tgetFileCrc(input_stream, buff, crcFile);\n\t\t\t\terr = zipOpenNewFileInZip3_64(m_zf,\n\t\t\t\t\tnameInZip.c_str(),\n\t\t\t\t\t&zi,\n\t\t\t\t\tNULL,\n\t\t\t\t\t0,\n\t\t\t\t\tNULL,\n\t\t\t\t\t0,\n\t\t\t\t\tNULL \/* comment*\/,\n\t\t\t\t\t(compressLevel != 0) ? Z_DEFLATED : 0,\n\t\t\t\t\tcompressLevel,\n\t\t\t\t\t0,\n\t\t\t\t\t\/* -MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY, *\/\n\t\t\t\t\t-MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY,\n\t\t\t\t\tpassword.c_str(),\n\t\t\t\t\tcrcFile,\n\t\t\t\t\tzip64);\n\t\t\t}\n\n\t\t\tif (ZIP_OK == err)\n\t\t\t{\n\t\t\t\tdo {\n\t\t\t\t\terr = ZIP_OK;\n\t\t\t\t\tinput_stream.read(buff.data(), buff.size());\n\t\t\t\t\tsize_read = (size_t)input_stream.gcount();\n\t\t\t\t\tif (size_read < buff.size() && !input_stream.eof() && !input_stream.good())\n\t\t\t\t\t\terr = ZIP_ERRNO;\n\n\t\t\t\t\tif (size_read > 0)\n\t\t\t\t\t\terr = zipWriteInFileInZip(this->m_zf, buff.data(), (unsigned int)size_read);\n\n\t\t\t\t} while ((err == ZIP_OK) && (size_read>0));\n\t\t\t}\n\t\t\telse\n\t\t\t\tthrow EXCEPTION_CLASS((\"Error adding '\" + nameInZip + \"' to zip\").c_str());\n\n\t\t\tif (ZIP_OK == err)\n\t\t\t\terr = zipCloseFileInZip(this->m_zf);\n\n\t\t\treturn ZIP_OK == err;\n\t\t}\n\n\t\tvoid close()\n\t\t{\n\t\t\tif (m_zf)\n\t\t\t\tzipClose(m_zf, NULL);\n\n\t\t\tif (m_zipmem.base && m_zipmem.limit > 0)\n\t\t\t{\n\t\t\t\tif (m_outer.m_usingMemoryVector)\n\t\t\t\t{\n\t\t\t\t\tm_outer.m_vecbuffer.resize(m_zipmem.limit);\n\t\t\t\t\tm_outer.m_vecbuffer.assign(m_zipmem.base, m_zipmem.base + m_zipmem.limit);\n\t\t\t\t}\n\n\t\t\t\telse if (m_outer.m_usingStream)\n\t\t\t\t\tm_outer.m_obuffer.write(m_zipmem.base, m_zipmem.limit);\n\t\t\t}\n\n\t\t\tfree(m_zipmem.base);\n\t\t}\n\t};\n\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\tZipper::Zipper(const std::string& zipname)\n\t\t: m_obuffer(*(new std::stringstream())) \/\/not used but using local variable throws exception\n\t\t, m_vecbuffer(*(new std::vector<unsigned char>())) \/\/not used but using local variable throws exception\n\t\t, m_usingMemoryVector(false)\n\t\t, m_usingStream(false)\n\t\t, m_zipname(zipname)\n\t\t, m_impl(new Impl(*this))\n\t{\n\t\tif (!m_impl->initFile(zipname))\n\t\t\tthrow EXCEPTION_CLASS(\"Error creating zip in file!\");\n\n\t\tm_open = true;\n\t}\n\n\tZipper::Zipper(const std::string& zipname, const std::string& password)\n\t\t: m_obuffer(*(new std::stringstream())) \/\/not used but using local variable throws exception\n\t\t, m_vecbuffer(*(new std::vector<unsigned char>())) \/\/not used but using local variable throws exception\n\t\t, m_usingMemoryVector(false)\n\t\t, m_usingStream(false)\n\t\t, m_zipname(zipname)\n\t\t, m_password(password)\n\t\t, m_impl(new Impl(*this))\n\t{\n\t\tif (!m_impl->initFile(zipname))\n\t\t\tthrow EXCEPTION_CLASS(\"Error creating zip in file!\");\n\n\t\tm_open = true;\n\t}\n\n\tZipper::Zipper(std::iostream& buffer)\n\t\t: m_vecbuffer(*(new std::vector<unsigned char>())) \/\/not used but using local variable throws exception\n\t\t, m_obuffer(buffer)\n\t\t, m_usingMemoryVector(false)\n\t\t, m_usingStream(true)\n\t\t, m_impl(new Impl(*this))\n\t{\n\t\tif (!m_impl->initWithStream(m_obuffer))\n\t\t\tthrow EXCEPTION_CLASS(\"Error creating zip in memory!\");\n\n\t\tm_open = true;\n\t}\n\n\tZipper::Zipper(std::vector<unsigned char>& buffer)\n\t\t: m_vecbuffer(buffer)\n\t\t, m_obuffer(*(new std::stringstream())) \/\/not used but using local variable throws exception\n\t\t, m_usingMemoryVector(true)\n\t\t, m_usingStream(false)\n\t\t, m_impl(new Impl(*this))\n\t{\n\t\tif (!m_impl->initWithVector(m_vecbuffer))\n\t\t\tthrow EXCEPTION_CLASS(\"Error creating zip in memory!\");\n\n\t\tm_open = true;\n\t}\n\n\tZipper::~Zipper(void)\n\t{\n\t\tclose();\n\t}\n\n\tbool Zipper::add(std::istream& source, const std::string& nameInZip, zipFlags flags)\n\t{\n\t\treturn m_impl->add(source, nameInZip, \"\", flags);\n\t}\n\n\tbool Zipper::add(const std::string& fileOrFolderPath, zipFlags flags)\n\t{\n\t\tif (isDirectory(fileOrFolderPath))\n\t\t{\n\t\t\tstd::string folderName = fileNameFromPath(fileOrFolderPath);\n\t\t\tstd::vector<std::string> files = filesFromDirectory(fileOrFolderPath);\n\t\t\tstd::vector<std::string>::iterator it = files.begin();\n\t\t\tfor (; it != files.end(); ++it)\n\t\t\t{\n\t\t\t\tstd::ifstream input(it->c_str(), std::ios::binary);\n\t\t\t\tstd::string nameInZip = it->substr(it->find(folderName), it->size());\n\t\t\t\tadd(input, nameInZip, flags);\n\t\t\t\tinput.close();\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tstd::ifstream input(fileOrFolderPath.c_str(), std::ios::binary);\n\t\t\tadd(input, fileNameFromPath(fileOrFolderPath), flags);\n\t\t\tinput.close();\n\t\t}\n\n\t\treturn true;\n\t}\n\n\n\tvoid Zipper::open()\n\t{\n\t\tif (!m_open)\n\t\t{\n\t\t\tif (m_usingMemoryVector)\n\t\t\t{\n\t\t\t\tif (!m_impl->initWithVector(m_vecbuffer))\n\t\t\t\t\tthrow EXCEPTION_CLASS(\"Error opening zip memory!\");\n\t\t\t}\n\t\t\telse if (m_usingStream)\n\t\t\t{\n\t\t\t\tif (!m_impl->initWithStream(m_obuffer))\n\t\t\t\t\tthrow EXCEPTION_CLASS(\"Error opening zip memory!\");\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tif (!m_impl->initFile(m_zipname))\n\t\t\t\t\tthrow EXCEPTION_CLASS(\"Error opening zip file!\");\n\t\t\t}\n\n\t\t\tm_open = true;\n\t\t}\n\t}\n\n\tvoid Zipper::close()\n\t{\n\t\tif (m_open)\n\t\t{\n\t\t\tm_impl->close();\n\t\t\tm_open = false;\n\t\t}\n\t}\n}\n<commit_msg>if there is aaa\/bbb\/ccc\/aaa\/ path, the code will have problem<commit_after>#include \"zipper.h\"\n#include \"defs.h\"\n#include \"tools.h\"\n\n#include <fstream>\n#include <stdexcept>\n\nnamespace zipper {\n\n\tstruct Zipper::Impl\n\t{\n\t\tZipper& m_outer;\n\t\tzipFile m_zf;\n\t\tourmemory_t m_zipmem;\n\t\tzlib_filefunc_def m_filefunc;\n\n\t\tImpl(Zipper& outer) : m_outer(outer), m_zipmem(), m_filefunc()\n\t\t{\n\t\t\tm_zf = NULL;\n\t\t\t\/\/m_filefunc = { 0 };\n\t\t}\n\n\t\tbool initFile(const std::string& filename)\n\t\t{\n\t\t\t#ifdef USEWIN32IOAPI\n\t\t\t\tzlib_filefunc64_def ffunc = { 0 };\n\t\t\t#endif\n\n\t\t\tint mode = 0;\n\t\t\tint flags = Zipper::Append;\n\n\t\t\t\/* open the zip file for output *\/\n\t\t\tif (checkFileExists(filename))\n\t\t\t\tmode = (flags & Zipper::Overwrite) ? APPEND_STATUS_CREATE : APPEND_STATUS_ADDINZIP;\n\t\t\telse\n\t\t\t\tmode = APPEND_STATUS_CREATE;\n\n\t\t\t#ifdef USEWIN32IOAPI\n\t\t\t\tfill_win32_filefunc64A(&ffunc);\n\t\t\t\tm_zf = zipOpen2_64(filename.c_str(), mode, NULL, &ffunc);\n\t\t\t#else\n\t\t\t\tm_zf = zipOpen64(filename.c_str(), mode);\n\t\t\t#endif\n\n\t\t\treturn NULL != m_zf;\n\t\t}\n\n\t\tbool initWithStream(std::iostream& stream)\n\t\t{\n\t\t\tm_zipmem.grow = 1;\n\n\t\t\tstream.seekg(0, std::ios::end);\n\t\t\tsize_t size = (size_t)stream.tellg();\n\t\t\tstream.seekg(0);\n\n\t\t\tif (size > 0)\n\t\t\t{\n\t\t\t\tm_zipmem.base = new char[(size_t)size];\n\t\t\t\tstream.read(m_zipmem.base, size);\n\t\t\t}\n\n\t\t\tfill_memory_filefunc(&m_filefunc, &m_zipmem);\n\t\t\t\n\t\t\treturn initMemory(size > 0 ? APPEND_STATUS_CREATE : APPEND_STATUS_ADDINZIP, m_filefunc);\n\t\t}\n\n\t\tbool initWithVector(std::vector<unsigned char>& buffer)\n\t\t{\n\t\t\tm_zipmem.grow = 1;\n\n\t\t\tif (!buffer.empty())\n\t\t\t{\n\t\t\t\tm_zipmem.base = new char[buffer.size()];\n\t\t\t\tmemcpy(m_zipmem.base, (char*)buffer.data(), buffer.size());\n\t\t\t\tm_zipmem.size = (uLong)buffer.size();\n\t\t\t}\n\n\t\t\tfill_memory_filefunc(&m_filefunc, &m_zipmem);\n\n\t\t\treturn initMemory(buffer.empty() ? APPEND_STATUS_CREATE : APPEND_STATUS_ADDINZIP, m_filefunc);\n\t\t}\n\n\t\tbool initMemory(int mode, zlib_filefunc_def& filefunc)\n\t\t{\n\t\t\tm_zf = zipOpen3(\"__notused__\", mode, 0, 0, &filefunc);\n\t\t\treturn m_zf != NULL;\n\t\t}\n\n\t\tbool add(std::istream& input_stream, const std::string& nameInZip, const std::string& password, int flags)\n\t\t{\n\t\t\tif (!m_zf) return false;\n\n\t\t\tint compressLevel = 0;\n\t\t\tint zip64 = 0;\n\t\t\tint size_buf = WRITEBUFFERSIZE;\n\t\t\tint err = ZIP_OK;\n\t\t\tunsigned long crcFile = 0;\n\n\t\t\tzip_fileinfo zi = { 0 };\n\t\t\tsize_t size_read;\n\n\t\t\tstd::vector<char> buff;\n\t\t\tbuff.resize(size_buf);\n\n\t\t\tif (nameInZip.empty())\n\t\t\t\treturn false;\n\n\t\t\tif (flags & Zipper::Faster) compressLevel = 1;\n\t\t\tif (flags & Zipper::Better) compressLevel = 9;\n\n\t\t\tzip64 = (int)isLargeFile(input_stream);\n\t\t\tif (password.empty())\n\t\t\t\terr = zipOpenNewFileInZip64(m_zf,\n\t\t\t\t\tnameInZip.c_str(),\n\t\t\t\t\t&zi,\n\t\t\t\t\tNULL,\n\t\t\t\t\t0,\n\t\t\t\t\tNULL,\n\t\t\t\t\t0,\n\t\t\t\t\tNULL \/* comment*\/,\n\t\t\t\t\t(compressLevel != 0) ? Z_DEFLATED : 0,\n\t\t\t\t\tcompressLevel,\n\t\t\t\t\tzip64);\n\t\t\telse\n\t\t\t{\n\t\t\t\tgetFileCrc(input_stream, buff, crcFile);\n\t\t\t\terr = zipOpenNewFileInZip3_64(m_zf,\n\t\t\t\t\tnameInZip.c_str(),\n\t\t\t\t\t&zi,\n\t\t\t\t\tNULL,\n\t\t\t\t\t0,\n\t\t\t\t\tNULL,\n\t\t\t\t\t0,\n\t\t\t\t\tNULL \/* comment*\/,\n\t\t\t\t\t(compressLevel != 0) ? Z_DEFLATED : 0,\n\t\t\t\t\tcompressLevel,\n\t\t\t\t\t0,\n\t\t\t\t\t\/* -MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY, *\/\n\t\t\t\t\t-MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY,\n\t\t\t\t\tpassword.c_str(),\n\t\t\t\t\tcrcFile,\n\t\t\t\t\tzip64);\n\t\t\t}\n\n\t\t\tif (ZIP_OK == err)\n\t\t\t{\n\t\t\t\tdo {\n\t\t\t\t\terr = ZIP_OK;\n\t\t\t\t\tinput_stream.read(buff.data(), buff.size());\n\t\t\t\t\tsize_read = (size_t)input_stream.gcount();\n\t\t\t\t\tif (size_read < buff.size() && !input_stream.eof() && !input_stream.good())\n\t\t\t\t\t\terr = ZIP_ERRNO;\n\n\t\t\t\t\tif (size_read > 0)\n\t\t\t\t\t\terr = zipWriteInFileInZip(this->m_zf, buff.data(), (unsigned int)size_read);\n\n\t\t\t\t} while ((err == ZIP_OK) && (size_read>0));\n\t\t\t}\n\t\t\telse\n\t\t\t\tthrow EXCEPTION_CLASS((\"Error adding '\" + nameInZip + \"' to zip\").c_str());\n\n\t\t\tif (ZIP_OK == err)\n\t\t\t\terr = zipCloseFileInZip(this->m_zf);\n\n\t\t\treturn ZIP_OK == err;\n\t\t}\n\n\t\tvoid close()\n\t\t{\n\t\t\tif (m_zf)\n\t\t\t\tzipClose(m_zf, NULL);\n\n\t\t\tif (m_zipmem.base && m_zipmem.limit > 0)\n\t\t\t{\n\t\t\t\tif (m_outer.m_usingMemoryVector)\n\t\t\t\t{\n\t\t\t\t\tm_outer.m_vecbuffer.resize(m_zipmem.limit);\n\t\t\t\t\tm_outer.m_vecbuffer.assign(m_zipmem.base, m_zipmem.base + m_zipmem.limit);\n\t\t\t\t}\n\n\t\t\t\telse if (m_outer.m_usingStream)\n\t\t\t\t\tm_outer.m_obuffer.write(m_zipmem.base, m_zipmem.limit);\n\t\t\t}\n\n\t\t\tfree(m_zipmem.base);\n\t\t}\n\t};\n\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\tZipper::Zipper(const std::string& zipname)\n\t\t: m_obuffer(*(new std::stringstream())) \/\/not used but using local variable throws exception\n\t\t, m_vecbuffer(*(new std::vector<unsigned char>())) \/\/not used but using local variable throws exception\n\t\t, m_usingMemoryVector(false)\n\t\t, m_usingStream(false)\n\t\t, m_zipname(zipname)\n\t\t, m_impl(new Impl(*this))\n\t{\n\t\tif (!m_impl->initFile(zipname))\n\t\t\tthrow EXCEPTION_CLASS(\"Error creating zip in file!\");\n\n\t\tm_open = true;\n\t}\n\n\tZipper::Zipper(const std::string& zipname, const std::string& password)\n\t\t: m_obuffer(*(new std::stringstream())) \/\/not used but using local variable throws exception\n\t\t, m_vecbuffer(*(new std::vector<unsigned char>())) \/\/not used but using local variable throws exception\n\t\t, m_usingMemoryVector(false)\n\t\t, m_usingStream(false)\n\t\t, m_zipname(zipname)\n\t\t, m_password(password)\n\t\t, m_impl(new Impl(*this))\n\t{\n\t\tif (!m_impl->initFile(zipname))\n\t\t\tthrow EXCEPTION_CLASS(\"Error creating zip in file!\");\n\n\t\tm_open = true;\n\t}\n\n\tZipper::Zipper(std::iostream& buffer)\n\t\t: m_vecbuffer(*(new std::vector<unsigned char>())) \/\/not used but using local variable throws exception\n\t\t, m_obuffer(buffer)\n\t\t, m_usingMemoryVector(false)\n\t\t, m_usingStream(true)\n\t\t, m_impl(new Impl(*this))\n\t{\n\t\tif (!m_impl->initWithStream(m_obuffer))\n\t\t\tthrow EXCEPTION_CLASS(\"Error creating zip in memory!\");\n\n\t\tm_open = true;\n\t}\n\n\tZipper::Zipper(std::vector<unsigned char>& buffer)\n\t\t: m_vecbuffer(buffer)\n\t\t, m_obuffer(*(new std::stringstream())) \/\/not used but using local variable throws exception\n\t\t, m_usingMemoryVector(true)\n\t\t, m_usingStream(false)\n\t\t, m_impl(new Impl(*this))\n\t{\n\t\tif (!m_impl->initWithVector(m_vecbuffer))\n\t\t\tthrow EXCEPTION_CLASS(\"Error creating zip in memory!\");\n\n\t\tm_open = true;\n\t}\n\n\tZipper::~Zipper(void)\n\t{\n\t\tclose();\n\t}\n\n\tbool Zipper::add(std::istream& source, const std::string& nameInZip, zipFlags flags)\n\t{\n\t\treturn m_impl->add(source, nameInZip, \"\", flags);\n\t}\n\n\tbool Zipper::add(const std::string& fileOrFolderPath, zipFlags flags)\n\t{\n\t\tif (isDirectory(fileOrFolderPath))\n\t\t{\n\t\t\tstd::string folderName = fileNameFromPath(fileOrFolderPath);\n\t\t\tstd::vector<std::string> files = filesFromDirectory(fileOrFolderPath);\n\t\t\tstd::vector<std::string>::iterator it = files.begin();\n\t\t\tfor (; it != files.end(); ++it)\n\t\t\t{\n\t\t\t\tstd::ifstream input(it->c_str(), std::ios::binary);\n\t\t\t\tstd::string nameInZip = it->substr(it->rfind(folderName), it->size());\n\t\t\t\tadd(input, nameInZip, flags);\n\t\t\t\tinput.close();\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tstd::ifstream input(fileOrFolderPath.c_str(), std::ios::binary);\n\t\t\tadd(input, fileNameFromPath(fileOrFolderPath), flags);\n\t\t\tinput.close();\n\t\t}\n\n\t\treturn true;\n\t}\n\n\n\tvoid Zipper::open()\n\t{\n\t\tif (!m_open)\n\t\t{\n\t\t\tif (m_usingMemoryVector)\n\t\t\t{\n\t\t\t\tif (!m_impl->initWithVector(m_vecbuffer))\n\t\t\t\t\tthrow EXCEPTION_CLASS(\"Error opening zip memory!\");\n\t\t\t}\n\t\t\telse if (m_usingStream)\n\t\t\t{\n\t\t\t\tif (!m_impl->initWithStream(m_obuffer))\n\t\t\t\t\tthrow EXCEPTION_CLASS(\"Error opening zip memory!\");\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tif (!m_impl->initFile(m_zipname))\n\t\t\t\t\tthrow EXCEPTION_CLASS(\"Error opening zip file!\");\n\t\t\t}\n\n\t\t\tm_open = true;\n\t\t}\n\t}\n\n\tvoid Zipper::close()\n\t{\n\t\tif (m_open)\n\t\t{\n\t\t\tm_impl->close();\n\t\t\tm_open = false;\n\t\t}\n\t}\n}\n<|endoftext|>"} {"text":"<commit_before>\/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- *\/\n\/* libodfgen\n * Version: MPL 2.0 \/ LGPLv2.1+\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\n * Major Contributor(s):\n * Copyright (C) 2002-2003 William Lachance (wrlach@gmail.com)\n *\n * For minor contributions see the git repository.\n *\n * Alternatively, the contents of this file may be used under the terms\n * of the GNU Lesser General Public License Version 2.1 or later\n * (LGPLv2.1+), in which case the provisions of the LGPLv2.1+ are\n * applicable instead of those above.\n *\n * For further information visit http:\/\/libwpd.sourceforge.net\n *\/\n\n\/* \"This product is not manufactured, approved, or supported by\n * Corel Corporation or Corel Corporation Limited.\"\n *\/\n#include \"FilterInternal.hxx\"\n#include \"PageSpan.hxx\"\n#include \"DocumentElement.hxx\"\n\nPageSpan::PageSpan(const librevenge::RVNGPropertyList &xPropList) :\n\tmxPropList(xPropList),\n\tmpHeaderContent(0),\n\tmpFooterContent(0),\n\tmpHeaderLeftContent(0),\n\tmpFooterLeftContent(0),\n\tmpHeaderFirstContent(0),\n\tmpFooterFirstContent(0),\n\tmpHeaderLastContent(0),\n\tmpFooterLastContent(0)\n{\n}\n\nnamespace\n{\ntypedef std::vector<DocumentElement *>::iterator DEVIter;\n}\n\nPageSpan::~PageSpan()\n{\n\tif (mpHeaderContent)\n\t{\n\t\tfor (DEVIter iterHeaderContent = mpHeaderContent->begin();\n\t\t iterHeaderContent != mpHeaderContent->end();\n\t\t ++iterHeaderContent)\n\t\t\tdelete(*iterHeaderContent);\n\t\tdelete mpHeaderContent;\n\t}\n\n\tif (mpHeaderLeftContent)\n\t{\n\t\tfor (DEVIter iterHeaderLeftContent = mpHeaderLeftContent->begin();\n\t\t iterHeaderLeftContent != mpHeaderLeftContent->end();\n\t\t ++iterHeaderLeftContent)\n\t\t\tdelete(*iterHeaderLeftContent);\n\t\tdelete mpHeaderLeftContent;\n\t}\n\n\tif (mpHeaderFirstContent)\n\t{\n\t\tfor (DEVIter iterHeaderFirstContent = mpHeaderFirstContent->begin();\n\t\t iterHeaderFirstContent != mpHeaderFirstContent->end();\n\t\t ++iterHeaderFirstContent)\n\t\t\tdelete(*iterHeaderFirstContent);\n\t\tdelete mpHeaderFirstContent;\n\t}\n\n\tif (mpHeaderLastContent)\n\t{\n\t\tfor (DEVIter iterHeaderLastContent = mpHeaderLastContent->begin();\n\t\t iterHeaderLastContent != mpHeaderLastContent->end();\n\t\t ++iterHeaderLastContent)\n\t\t\tdelete(*iterHeaderLastContent);\n\t\tdelete mpHeaderLastContent;\n\t}\n\n\tif (mpFooterContent)\n\t{\n\t\tfor (DEVIter iterFooterContent = mpFooterContent->begin();\n\t\t iterFooterContent != mpFooterContent->end();\n\t\t ++iterFooterContent)\n\t\t\tdelete(*iterFooterContent);\n\t\tdelete mpFooterContent;\n\t}\n\n\tif (mpFooterLeftContent)\n\t{\n\t\tfor (DEVIter iterFooterLeftContent = mpFooterLeftContent->begin();\n\t\t iterFooterLeftContent != mpFooterLeftContent->end();\n\t\t ++iterFooterLeftContent)\n\t\t\tdelete(*iterFooterLeftContent);\n\t\tdelete mpFooterLeftContent;\n\t}\n\n\tif (mpFooterFirstContent)\n\t{\n\t\tfor (DEVIter iterFooterFirstContent = mpFooterFirstContent->begin();\n\t\t iterFooterFirstContent != mpFooterFirstContent->end();\n\t\t ++iterFooterFirstContent)\n\t\t\tdelete(*iterFooterFirstContent);\n\t\tdelete mpFooterFirstContent;\n\t}\n\n\tif (mpFooterLastContent)\n\t{\n\t\tfor (DEVIter iterFooterLastContent = mpFooterLastContent->begin();\n\t\t iterFooterLastContent != mpFooterLastContent->end();\n\t\t ++iterFooterLastContent)\n\t\t\tdelete(*iterFooterLastContent);\n\t\tdelete mpFooterLastContent;\n\t}\n}\n\nint PageSpan::getSpan() const\n{\n\tif (mxPropList[\"librevenge:num-pages\"])\n\t\treturn mxPropList[\"librevenge:num-pages\"]->getInt();\n\n\treturn 0; \/\/ should never happen\n}\n\nvoid PageSpan::setHeaderContent(std::vector<DocumentElement *> *pHeaderContent)\n{\n\tif (mpHeaderContent)\n\t{\n\t\tfor (DEVIter iterHeaderContent = mpHeaderContent->begin();\n\t\t iterHeaderContent != mpHeaderContent->end();\n\t\t ++iterHeaderContent)\n\t\t\tdelete(*iterHeaderContent);\n\t\tdelete mpHeaderContent;\n\t}\n\n\tmpHeaderContent = pHeaderContent;\n}\n\nvoid PageSpan::setFooterContent(std::vector<DocumentElement *> *pFooterContent)\n{\n\tif (mpFooterContent)\n\t{\n\t\tfor (DEVIter iterFooterContent = mpFooterContent->begin();\n\t\t iterFooterContent != mpFooterContent->end();\n\t\t ++iterFooterContent)\n\t\t\tdelete(*iterFooterContent);\n\t\tdelete mpFooterContent;\n\t}\n\n\tmpFooterContent = pFooterContent;\n}\n\nvoid PageSpan::setHeaderLeftContent(std::vector<DocumentElement *> *pHeaderContent)\n{\n\tif (mpHeaderLeftContent)\n\t{\n\t\tfor (DEVIter iterHeaderLeftContent = mpHeaderLeftContent->begin();\n\t\t iterHeaderLeftContent != mpHeaderLeftContent->end();\n\t\t ++iterHeaderLeftContent)\n\t\t\tdelete(*iterHeaderLeftContent);\n\t\tdelete mpHeaderLeftContent;\n\t}\n\n\tmpHeaderLeftContent = pHeaderContent;\n}\n\nvoid PageSpan::setFooterLeftContent(std::vector<DocumentElement *> *pFooterContent)\n{\n\tif (mpFooterLeftContent)\n\t{\n\t\tfor (DEVIter iterFooterLeftContent = mpFooterLeftContent->begin();\n\t\t iterFooterLeftContent != mpFooterLeftContent->end();\n\t\t ++iterFooterLeftContent)\n\t\t\tdelete(*iterFooterLeftContent);\n\t\tdelete mpFooterLeftContent;\n\t}\n\n\tmpFooterLeftContent = pFooterContent;\n}\n\nvoid PageSpan::setHeaderFirstContent(std::vector<DocumentElement *> *pHeaderContent)\n{\n\tif (mpHeaderFirstContent)\n\t{\n\t\tfor (DEVIter iterHeaderFirstContent = mpHeaderFirstContent->begin();\n\t\t iterHeaderFirstContent != mpHeaderFirstContent->end();\n\t\t ++iterHeaderFirstContent)\n\t\t\tdelete(*iterHeaderFirstContent);\n\t\tdelete mpHeaderFirstContent;\n\t}\n\n\tmpHeaderFirstContent = pHeaderContent;\n}\n\nvoid PageSpan::setFooterFirstContent(std::vector<DocumentElement *> *pFooterContent)\n{\n\tif (mpFooterFirstContent)\n\t{\n\t\tfor (DEVIter iterFooterFirstContent = mpFooterFirstContent->begin();\n\t\t iterFooterFirstContent != mpFooterFirstContent->end();\n\t\t ++iterFooterFirstContent)\n\t\t\tdelete(*iterFooterFirstContent);\n\t\tdelete mpFooterFirstContent;\n\t}\n\n\tmpFooterFirstContent = pFooterContent;\n}\n\nvoid PageSpan::setHeaderLastContent(std::vector<DocumentElement *> *pHeaderContent)\n{\n\tif (mpHeaderLastContent)\n\t{\n\t\tfor (DEVIter iterHeaderLastContent = mpHeaderLastContent->begin();\n\t\t iterHeaderLastContent != mpHeaderLastContent->end();\n\t\t ++iterHeaderLastContent)\n\t\t\tdelete(*iterHeaderLastContent);\n\t\tdelete mpHeaderLastContent;\n\t}\n\n\tmpHeaderLastContent = pHeaderContent;\n}\n\nvoid PageSpan::setFooterLastContent(std::vector<DocumentElement *> *pFooterContent)\n{\n\tif (mpFooterLastContent)\n\t{\n\t\tfor (DEVIter iterFooterLastContent = mpFooterLastContent->begin();\n\t\t iterFooterLastContent != mpFooterLastContent->end();\n\t\t ++iterFooterLastContent)\n\t\t\tdelete(*iterFooterLastContent);\n\t\tdelete mpFooterLastContent;\n\t}\n\n\tmpFooterLastContent = pFooterContent;\n}\n\nvoid PageSpan::writePageLayout(const int iNum, OdfDocumentHandler *pHandler) const\n{\n\tlibrevenge::RVNGPropertyList propList;\n\n\tlibrevenge::RVNGString sPageLayoutName;\n\tsPageLayoutName.sprintf(\"PM%i\", iNum+2);\n\tpropList.insert(\"style:name\", sPageLayoutName);\n\tpHandler->startElement(\"style:page-layout\", propList);\n\n\tlibrevenge::RVNGPropertyList tempPropList = mxPropList;\n\tif (!tempPropList[\"style:writing-mode\"])\n\t\ttempPropList.insert(\"style:writing-mode\", librevenge::RVNGString(\"lr-tb\"));\n\tif (!tempPropList[\"style:footnote-max-height\"])\n\t\ttempPropList.insert(\"style:footnote-max-height\", librevenge::RVNGString(\"0in\"));\n\tpHandler->startElement(\"style:page-layout-properties\", tempPropList);\n\n\tlibrevenge::RVNGPropertyList footnoteSepPropList;\n\tfootnoteSepPropList.insert(\"style:width\", librevenge::RVNGString(\"0.0071in\"));\n\tfootnoteSepPropList.insert(\"style:distance-before-sep\", librevenge::RVNGString(\"0.0398in\"));\n\tfootnoteSepPropList.insert(\"style:distance-after-sep\", librevenge::RVNGString(\"0.0398in\"));\n\tfootnoteSepPropList.insert(\"style:adjustment\", librevenge::RVNGString(\"left\"));\n\tfootnoteSepPropList.insert(\"style:rel-width\", librevenge::RVNGString(\"25%\"));\n\tfootnoteSepPropList.insert(\"style:color\", librevenge::RVNGString(\"#000000\"));\n\tpHandler->startElement(\"style:footnote-sep\", footnoteSepPropList);\n\n\tpHandler->endElement(\"style:footnote-sep\");\n\tpHandler->endElement(\"style:page-layout-properties\");\n\tpHandler->endElement(\"style:page-layout\");\n}\n\nvoid PageSpan::writeMasterPages(const int iStartingNum, const int iPageLayoutNum, const bool bLastPageSpan,\n OdfDocumentHandler *pHandler) const\n{\n\tint iSpan = 0;\n\t(bLastPageSpan) ? iSpan = 1 : iSpan = getSpan();\n\n\tfor (int i=iStartingNum; i<(iStartingNum+iSpan); ++i)\n\t{\n\t\tTagOpenElement masterPageOpen(\"style:master-page\");\n\t\tlibrevenge::RVNGString sMasterPageName, sMasterPageDisplayName;\n\t\tsMasterPageName.sprintf(\"Page_Style_%i\", i);\n\t\tsMasterPageDisplayName.sprintf(\"Page Style %i\", i);\n\t\tlibrevenge::RVNGString sPageLayoutName;\n\t\tlibrevenge::RVNGPropertyList propList;\n\t\tsPageLayoutName.sprintf(\"PM%i\", iPageLayoutNum+2);\n\t\tpropList.insert(\"style:name\", sMasterPageName);\n\t\tpropList.insert(\"style:display-name\", sMasterPageDisplayName);\n\t\tpropList.insert(\"style:page-layout-name\", sPageLayoutName);\n\t\tif (!bLastPageSpan)\n\t\t{\n\t\t\tlibrevenge::RVNGString sNextMasterPageName;\n\t\t\tsNextMasterPageName.sprintf(\"Page_Style_%i\", (i+1));\n\t\t\tpropList.insert(\"style:next-style-name\", sNextMasterPageName);\n\t\t}\n\t\tpHandler->startElement(\"style:master-page\", propList);\n\n\t\tif (mpHeaderContent)\n\t\t{\n\t\t\t_writeHeaderFooter(\"style:header\", *mpHeaderContent, pHandler);\n\t\t\tpHandler->endElement(\"style:header\");\n\t\t}\n\t\telse if (mpHeaderLeftContent || mpHeaderFirstContent || mpHeaderLastContent)\n\t\t{\n\t\t\tTagOpenElement(\"style:header\").write(pHandler);\n\t\t\tpHandler->endElement(\"style:header\");\n\t\t}\n\t\tif (mpHeaderLeftContent)\n\t\t{\n\t\t\t_writeHeaderFooter(\"style:header-left\", *mpHeaderLeftContent, pHandler);\n\t\t\tpHandler->endElement(\"style:header-left\");\n\t\t}\n\t\tif (mpHeaderFirstContent)\n\t\t{\n\t\t\t_writeHeaderFooter(\"style:header-first\", *mpHeaderFirstContent, pHandler);\n\t\t\tpHandler->endElement(\"style:header-first\");\n\t\t}\n\t\tif (mpHeaderLastContent)\n\t\t{\n\t\t\t_writeHeaderFooter(\"style:header-last\", *mpHeaderLastContent, pHandler);\n\t\t\tpHandler->endElement(\"style:header-last\");\n\t\t}\n\n\t\tif (mpFooterContent)\n\t\t{\n\t\t\t_writeHeaderFooter(\"style:footer\", *mpFooterContent, pHandler);\n\t\t\tpHandler->endElement(\"style:footer\");\n\t\t}\n\t\telse if (mpFooterLeftContent || mpFooterFirstContent || mpFooterLastContent)\n\t\t{\n\t\t\tTagOpenElement(\"style:footer\").write(pHandler);\n\t\t\tpHandler->endElement(\"style:footer\");\n\t\t}\n\t\tif (mpFooterLeftContent)\n\t\t{\n\t\t\t_writeHeaderFooter(\"style:footer-left\", *mpFooterLeftContent, pHandler);\n\t\t\tpHandler->endElement(\"style:footer-left\");\n\t\t}\n\t\tif (mpFooterFirstContent)\n\t\t{\n\t\t\t_writeHeaderFooter(\"style:footer-first\", *mpFooterFirstContent, pHandler);\n\t\t\tpHandler->endElement(\"style:footer-first\");\n\t\t}\n\t\tif (mpFooterLastContent)\n\t\t{\n\t\t\t_writeHeaderFooter(\"style:footer-last\", *mpFooterLastContent, pHandler);\n\t\t\tpHandler->endElement(\"style:footer-last\");\n\t\t}\n\n\t\tpHandler->endElement(\"style:master-page\");\n\t}\n}\n\nvoid PageSpan::_writeHeaderFooter(const char *headerFooterTagName,\n const std::vector<DocumentElement *> &headerFooterContent,\n OdfDocumentHandler *pHandler) const\n{\n\tTagOpenElement headerFooterOpen(headerFooterTagName);\n\theaderFooterOpen.write(pHandler);\n\tfor (std::vector<DocumentElement *>::const_iterator iter = headerFooterContent.begin();\n\t iter != headerFooterContent.end();\n\t ++iter)\n\t{\n\t\t(*iter)->write(pHandler);\n\t}\n}\n\n\/* vim:set shiftwidth=4 softtabstop=4 noexpandtab: *\/\n<commit_msg>LO does not support yet the header\/footer occurrence \"last\", so don't bother<commit_after>\/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- *\/\n\/* libodfgen\n * Version: MPL 2.0 \/ LGPLv2.1+\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\n * Major Contributor(s):\n * Copyright (C) 2002-2003 William Lachance (wrlach@gmail.com)\n *\n * For minor contributions see the git repository.\n *\n * Alternatively, the contents of this file may be used under the terms\n * of the GNU Lesser General Public License Version 2.1 or later\n * (LGPLv2.1+), in which case the provisions of the LGPLv2.1+ are\n * applicable instead of those above.\n *\n * For further information visit http:\/\/libwpd.sourceforge.net\n *\/\n\n\/* \"This product is not manufactured, approved, or supported by\n * Corel Corporation or Corel Corporation Limited.\"\n *\/\n#include \"FilterInternal.hxx\"\n#include \"PageSpan.hxx\"\n#include \"DocumentElement.hxx\"\n\nPageSpan::PageSpan(const librevenge::RVNGPropertyList &xPropList) :\n\tmxPropList(xPropList),\n\tmpHeaderContent(0),\n\tmpFooterContent(0),\n\tmpHeaderLeftContent(0),\n\tmpFooterLeftContent(0),\n\tmpHeaderFirstContent(0),\n\tmpFooterFirstContent(0),\n\tmpHeaderLastContent(0),\n\tmpFooterLastContent(0)\n{\n}\n\nnamespace\n{\ntypedef std::vector<DocumentElement *>::iterator DEVIter;\n}\n\nPageSpan::~PageSpan()\n{\n\tif (mpHeaderContent)\n\t{\n\t\tfor (DEVIter iterHeaderContent = mpHeaderContent->begin();\n\t\t iterHeaderContent != mpHeaderContent->end();\n\t\t ++iterHeaderContent)\n\t\t\tdelete(*iterHeaderContent);\n\t\tdelete mpHeaderContent;\n\t}\n\n\tif (mpHeaderLeftContent)\n\t{\n\t\tfor (DEVIter iterHeaderLeftContent = mpHeaderLeftContent->begin();\n\t\t iterHeaderLeftContent != mpHeaderLeftContent->end();\n\t\t ++iterHeaderLeftContent)\n\t\t\tdelete(*iterHeaderLeftContent);\n\t\tdelete mpHeaderLeftContent;\n\t}\n\n\tif (mpHeaderFirstContent)\n\t{\n\t\tfor (DEVIter iterHeaderFirstContent = mpHeaderFirstContent->begin();\n\t\t iterHeaderFirstContent != mpHeaderFirstContent->end();\n\t\t ++iterHeaderFirstContent)\n\t\t\tdelete(*iterHeaderFirstContent);\n\t\tdelete mpHeaderFirstContent;\n\t}\n\n\tif (mpHeaderLastContent)\n\t{\n\t\tfor (DEVIter iterHeaderLastContent = mpHeaderLastContent->begin();\n\t\t iterHeaderLastContent != mpHeaderLastContent->end();\n\t\t ++iterHeaderLastContent)\n\t\t\tdelete(*iterHeaderLastContent);\n\t\tdelete mpHeaderLastContent;\n\t}\n\n\tif (mpFooterContent)\n\t{\n\t\tfor (DEVIter iterFooterContent = mpFooterContent->begin();\n\t\t iterFooterContent != mpFooterContent->end();\n\t\t ++iterFooterContent)\n\t\t\tdelete(*iterFooterContent);\n\t\tdelete mpFooterContent;\n\t}\n\n\tif (mpFooterLeftContent)\n\t{\n\t\tfor (DEVIter iterFooterLeftContent = mpFooterLeftContent->begin();\n\t\t iterFooterLeftContent != mpFooterLeftContent->end();\n\t\t ++iterFooterLeftContent)\n\t\t\tdelete(*iterFooterLeftContent);\n\t\tdelete mpFooterLeftContent;\n\t}\n\n\tif (mpFooterFirstContent)\n\t{\n\t\tfor (DEVIter iterFooterFirstContent = mpFooterFirstContent->begin();\n\t\t iterFooterFirstContent != mpFooterFirstContent->end();\n\t\t ++iterFooterFirstContent)\n\t\t\tdelete(*iterFooterFirstContent);\n\t\tdelete mpFooterFirstContent;\n\t}\n\n\tif (mpFooterLastContent)\n\t{\n\t\tfor (DEVIter iterFooterLastContent = mpFooterLastContent->begin();\n\t\t iterFooterLastContent != mpFooterLastContent->end();\n\t\t ++iterFooterLastContent)\n\t\t\tdelete(*iterFooterLastContent);\n\t\tdelete mpFooterLastContent;\n\t}\n}\n\nint PageSpan::getSpan() const\n{\n\tif (mxPropList[\"librevenge:num-pages\"])\n\t\treturn mxPropList[\"librevenge:num-pages\"]->getInt();\n\n\treturn 0; \/\/ should never happen\n}\n\nvoid PageSpan::setHeaderContent(std::vector<DocumentElement *> *pHeaderContent)\n{\n\tif (mpHeaderContent)\n\t{\n\t\tfor (DEVIter iterHeaderContent = mpHeaderContent->begin();\n\t\t iterHeaderContent != mpHeaderContent->end();\n\t\t ++iterHeaderContent)\n\t\t\tdelete(*iterHeaderContent);\n\t\tdelete mpHeaderContent;\n\t}\n\n\tmpHeaderContent = pHeaderContent;\n}\n\nvoid PageSpan::setFooterContent(std::vector<DocumentElement *> *pFooterContent)\n{\n\tif (mpFooterContent)\n\t{\n\t\tfor (DEVIter iterFooterContent = mpFooterContent->begin();\n\t\t iterFooterContent != mpFooterContent->end();\n\t\t ++iterFooterContent)\n\t\t\tdelete(*iterFooterContent);\n\t\tdelete mpFooterContent;\n\t}\n\n\tmpFooterContent = pFooterContent;\n}\n\nvoid PageSpan::setHeaderLeftContent(std::vector<DocumentElement *> *pHeaderContent)\n{\n\tif (mpHeaderLeftContent)\n\t{\n\t\tfor (DEVIter iterHeaderLeftContent = mpHeaderLeftContent->begin();\n\t\t iterHeaderLeftContent != mpHeaderLeftContent->end();\n\t\t ++iterHeaderLeftContent)\n\t\t\tdelete(*iterHeaderLeftContent);\n\t\tdelete mpHeaderLeftContent;\n\t}\n\n\tmpHeaderLeftContent = pHeaderContent;\n}\n\nvoid PageSpan::setFooterLeftContent(std::vector<DocumentElement *> *pFooterContent)\n{\n\tif (mpFooterLeftContent)\n\t{\n\t\tfor (DEVIter iterFooterLeftContent = mpFooterLeftContent->begin();\n\t\t iterFooterLeftContent != mpFooterLeftContent->end();\n\t\t ++iterFooterLeftContent)\n\t\t\tdelete(*iterFooterLeftContent);\n\t\tdelete mpFooterLeftContent;\n\t}\n\n\tmpFooterLeftContent = pFooterContent;\n}\n\nvoid PageSpan::setHeaderFirstContent(std::vector<DocumentElement *> *pHeaderContent)\n{\n\tif (mpHeaderFirstContent)\n\t{\n\t\tfor (DEVIter iterHeaderFirstContent = mpHeaderFirstContent->begin();\n\t\t iterHeaderFirstContent != mpHeaderFirstContent->end();\n\t\t ++iterHeaderFirstContent)\n\t\t\tdelete(*iterHeaderFirstContent);\n\t\tdelete mpHeaderFirstContent;\n\t}\n\n\tmpHeaderFirstContent = pHeaderContent;\n}\n\nvoid PageSpan::setFooterFirstContent(std::vector<DocumentElement *> *pFooterContent)\n{\n\tif (mpFooterFirstContent)\n\t{\n\t\tfor (DEVIter iterFooterFirstContent = mpFooterFirstContent->begin();\n\t\t iterFooterFirstContent != mpFooterFirstContent->end();\n\t\t ++iterFooterFirstContent)\n\t\t\tdelete(*iterFooterFirstContent);\n\t\tdelete mpFooterFirstContent;\n\t}\n\n\tmpFooterFirstContent = pFooterContent;\n}\n\nvoid PageSpan::setHeaderLastContent(std::vector<DocumentElement *> *pHeaderContent)\n{\n\tif (mpHeaderLastContent)\n\t{\n\t\tfor (DEVIter iterHeaderLastContent = mpHeaderLastContent->begin();\n\t\t iterHeaderLastContent != mpHeaderLastContent->end();\n\t\t ++iterHeaderLastContent)\n\t\t\tdelete(*iterHeaderLastContent);\n\t\tdelete mpHeaderLastContent;\n\t}\n\n\tmpHeaderLastContent = pHeaderContent;\n}\n\nvoid PageSpan::setFooterLastContent(std::vector<DocumentElement *> *pFooterContent)\n{\n\tif (mpFooterLastContent)\n\t{\n\t\tfor (DEVIter iterFooterLastContent = mpFooterLastContent->begin();\n\t\t iterFooterLastContent != mpFooterLastContent->end();\n\t\t ++iterFooterLastContent)\n\t\t\tdelete(*iterFooterLastContent);\n\t\tdelete mpFooterLastContent;\n\t}\n\n\tmpFooterLastContent = pFooterContent;\n}\n\nvoid PageSpan::writePageLayout(const int iNum, OdfDocumentHandler *pHandler) const\n{\n\tlibrevenge::RVNGPropertyList propList;\n\n\tlibrevenge::RVNGString sPageLayoutName;\n\tsPageLayoutName.sprintf(\"PM%i\", iNum+2);\n\tpropList.insert(\"style:name\", sPageLayoutName);\n\tpHandler->startElement(\"style:page-layout\", propList);\n\n\tlibrevenge::RVNGPropertyList tempPropList = mxPropList;\n\tif (!tempPropList[\"style:writing-mode\"])\n\t\ttempPropList.insert(\"style:writing-mode\", librevenge::RVNGString(\"lr-tb\"));\n\tif (!tempPropList[\"style:footnote-max-height\"])\n\t\ttempPropList.insert(\"style:footnote-max-height\", librevenge::RVNGString(\"0in\"));\n\tpHandler->startElement(\"style:page-layout-properties\", tempPropList);\n\n\tlibrevenge::RVNGPropertyList footnoteSepPropList;\n\tfootnoteSepPropList.insert(\"style:width\", librevenge::RVNGString(\"0.0071in\"));\n\tfootnoteSepPropList.insert(\"style:distance-before-sep\", librevenge::RVNGString(\"0.0398in\"));\n\tfootnoteSepPropList.insert(\"style:distance-after-sep\", librevenge::RVNGString(\"0.0398in\"));\n\tfootnoteSepPropList.insert(\"style:adjustment\", librevenge::RVNGString(\"left\"));\n\tfootnoteSepPropList.insert(\"style:rel-width\", librevenge::RVNGString(\"25%\"));\n\tfootnoteSepPropList.insert(\"style:color\", librevenge::RVNGString(\"#000000\"));\n\tpHandler->startElement(\"style:footnote-sep\", footnoteSepPropList);\n\n\tpHandler->endElement(\"style:footnote-sep\");\n\tpHandler->endElement(\"style:page-layout-properties\");\n\tpHandler->endElement(\"style:page-layout\");\n}\n\nvoid PageSpan::writeMasterPages(const int iStartingNum, const int iPageLayoutNum, const bool bLastPageSpan,\n OdfDocumentHandler *pHandler) const\n{\n\tint iSpan = 0;\n\t(bLastPageSpan) ? iSpan = 1 : iSpan = getSpan();\n\n\tfor (int i=iStartingNum; i<(iStartingNum+iSpan); ++i)\n\t{\n\t\tTagOpenElement masterPageOpen(\"style:master-page\");\n\t\tlibrevenge::RVNGString sMasterPageName, sMasterPageDisplayName;\n\t\tsMasterPageName.sprintf(\"Page_Style_%i\", i);\n\t\tsMasterPageDisplayName.sprintf(\"Page Style %i\", i);\n\t\tlibrevenge::RVNGString sPageLayoutName;\n\t\tlibrevenge::RVNGPropertyList propList;\n\t\tsPageLayoutName.sprintf(\"PM%i\", iPageLayoutNum+2);\n\t\tpropList.insert(\"style:name\", sMasterPageName);\n\t\tpropList.insert(\"style:display-name\", sMasterPageDisplayName);\n\t\tpropList.insert(\"style:page-layout-name\", sPageLayoutName);\n\t\tif (!bLastPageSpan)\n\t\t{\n\t\t\tlibrevenge::RVNGString sNextMasterPageName;\n\t\t\tsNextMasterPageName.sprintf(\"Page_Style_%i\", (i+1));\n\t\t\tpropList.insert(\"style:next-style-name\", sNextMasterPageName);\n\t\t}\n\t\tpHandler->startElement(\"style:master-page\", propList);\n\n\t\tif (mpHeaderContent)\n\t\t{\n\t\t\t_writeHeaderFooter(\"style:header\", *mpHeaderContent, pHandler);\n\t\t\tpHandler->endElement(\"style:header\");\n\t\t}\n\t\telse if (mpHeaderLeftContent || mpHeaderFirstContent \/* || mpHeaderLastContent *\/)\n\t\t{\n\t\t\tTagOpenElement(\"style:header\").write(pHandler);\n\t\t\tpHandler->endElement(\"style:header\");\n\t\t}\n\t\tif (mpHeaderLeftContent)\n\t\t{\n\t\t\t_writeHeaderFooter(\"style:header-left\", *mpHeaderLeftContent, pHandler);\n\t\t\tpHandler->endElement(\"style:header-left\");\n\t\t}\n\t\tif (mpHeaderFirstContent)\n\t\t{\n\t\t\t_writeHeaderFooter(\"style:header-first\", *mpHeaderFirstContent, pHandler);\n\t\t\tpHandler->endElement(\"style:header-first\");\n\t\t}\n\t\t\/*\n\t\tif (mpHeaderLastContent)\n\t\t{\n\t\t\t_writeHeaderFooter(\"style:header-last\", *mpHeaderLastContent, pHandler);\n\t\t\tpHandler->endElement(\"style:header-last\");\n\t\t}\n\t\t*\/\n\n\t\tif (mpFooterContent)\n\t\t{\n\t\t\t_writeHeaderFooter(\"style:footer\", *mpFooterContent, pHandler);\n\t\t\tpHandler->endElement(\"style:footer\");\n\t\t}\n\t\telse if (mpFooterLeftContent || mpFooterFirstContent \/* || mpFooterLastContent *\/)\n\t\t{\n\t\t\tTagOpenElement(\"style:footer\").write(pHandler);\n\t\t\tpHandler->endElement(\"style:footer\");\n\t\t}\n\t\tif (mpFooterLeftContent)\n\t\t{\n\t\t\t_writeHeaderFooter(\"style:footer-left\", *mpFooterLeftContent, pHandler);\n\t\t\tpHandler->endElement(\"style:footer-left\");\n\t\t}\n\t\tif (mpFooterFirstContent)\n\t\t{\n\t\t\t_writeHeaderFooter(\"style:footer-first\", *mpFooterFirstContent, pHandler);\n\t\t\tpHandler->endElement(\"style:footer-first\");\n\t\t}\n\t\t\/*\n\t\tif (mpFooterLastContent)\n\t\t{\n\t\t\t_writeHeaderFooter(\"style:footer-last\", *mpFooterLastContent, pHandler);\n\t\t\tpHandler->endElement(\"style:footer-last\");\n\t\t}\n\t\t*\/\n\n\t\tpHandler->endElement(\"style:master-page\");\n\t}\n}\n\nvoid PageSpan::_writeHeaderFooter(const char *headerFooterTagName,\n const std::vector<DocumentElement *> &headerFooterContent,\n OdfDocumentHandler *pHandler) const\n{\n\tTagOpenElement headerFooterOpen(headerFooterTagName);\n\theaderFooterOpen.write(pHandler);\n\tfor (std::vector<DocumentElement *>::const_iterator iter = headerFooterContent.begin();\n\t iter != headerFooterContent.end();\n\t ++iter)\n\t{\n\t\t(*iter)->write(pHandler);\n\t}\n}\n\n\/* vim:set shiftwidth=4 softtabstop=4 noexpandtab: *\/\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2017 Netherlands Institute for Radio Astronomy (ASTRON)\n\/\/ Copyright 2017 Netherlands eScience Center\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include <ReadData.hpp>\n\nnamespace AstroData {\n\nRingBufferError::RingBufferError(const std::string & message) : message(message) {}\n\nRingBufferError::~RingBufferError() noexcept {}\n\nconst char * RingBufferError::what() const noexcept {\n return message.c_str();\n}\n\nvoid readZappedChannels(Observation & observation, const std::string & inputFilename, std::vector<unsigned int> & zappedChannels) {\n unsigned int nrChannels = 0;\n std::ifstream input;\n\n input.open(inputFilename);\n if ( !input ) {\n throw FileError(\"ERROR: impossible to open zapped channels file \\\"\" + inputFilename + \"\\\"\");\n }\n while ( !input.eof() ) {\n unsigned int channel = observation.getNrChannels();\n\n input >> channel;\n if ( channel < observation.getNrChannels() ) {\n zappedChannels[channel] = 1;\n nrChannels++;\n }\n }\n input.close();\n observation.setNrZappedChannels(nrChannels);\n}\n\nvoid readIntegrationSteps(const Observation & observation, const std::string & inputFilename, std::set<unsigned int> & integrationSteps) {\n std::ifstream input;\n\n input.open(inputFilename);\n if ( !input ) {\n throw FileError(\"ERROR: impossible to open integration steps file \\\"\" + inputFilename + \"\\\"\");\n }\n while ( !input.eof() ) {\n unsigned int step = observation.getNrSamplesPerBatch();\n\n input >> step;\n if ( step < observation.getNrSamplesPerBatch() ) {\n integrationSteps.insert(step);\n }\n }\n input.close();\n}\n\n#ifdef HAVE_PSRDADA\nvoid readPSRDADAHeader(Observation & observation, dada_hdu_t & ringBuffer) {\n \/\/ Staging variables for the header elements\n unsigned int uintValue = 0;\n float floatValue[2] = {0.0f, 0.0f};\n \/\/ Header string\n uint64_t headerBytes = 0;\n char * header = 0;\n\n header = ipcbuf_get_next_read(ringBuffer.header_block, &headerBytes);\n if ( (header == 0) || (headerBytes == 0 ) ) {\n throw RingBufferError(\"ERROR: impossible to read the PSRDADA header\");\n }\n ascii_header_get(header, \"SAMPLES_PER_BATCH\", \"%d\", &uintValue);\n observation.setNrSamplesPerBatch(uintValue);\n ascii_header_get(header, \"NCHAN\", \"%d\", &uintValue);\n ascii_header_get(header, \"MIN_FREQUENCY\", \"%f\", &floatValue[0]);\n ascii_header_get(header, \"CHANNEL_BANDWIDTH\", \"%f\", &floatValue[1]);\n observation.setFrequencyRange(1, uintValue, floatValue[0], floatValue[1]);\n ascii_header_get(header, \"TSAMP\", \"%f\", &floatValue[0]);\n observation.setSamplingTime(floatValue[0]);\n if ( ipcbuf_mark_cleared(ringBuffer.header_block) < 0 ) {\n throw RingBufferError(\"ERROR: impossible to mark the PSRDADA header as cleared\");\n }\n}\n#endif \/\/ HAVE_PSRDADA\n\n} \/\/ AstroData\n\n<commit_msg>Fixing a bug in which the number of subbands was not set when reading input from PSRDADA.<commit_after>\/\/ Copyright 2017 Netherlands Institute for Radio Astronomy (ASTRON)\n\/\/ Copyright 2017 Netherlands eScience Center\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include <ReadData.hpp>\n\nnamespace AstroData {\n\nRingBufferError::RingBufferError(const std::string & message) : message(message) {}\n\nRingBufferError::~RingBufferError() noexcept {}\n\nconst char * RingBufferError::what() const noexcept {\n return message.c_str();\n}\n\nvoid readZappedChannels(Observation & observation, const std::string & inputFilename, std::vector<unsigned int> & zappedChannels) {\n unsigned int nrChannels = 0;\n std::ifstream input;\n\n input.open(inputFilename);\n if ( !input ) {\n throw FileError(\"ERROR: impossible to open zapped channels file \\\"\" + inputFilename + \"\\\"\");\n }\n while ( !input.eof() ) {\n unsigned int channel = observation.getNrChannels();\n\n input >> channel;\n if ( channel < observation.getNrChannels() ) {\n zappedChannels[channel] = 1;\n nrChannels++;\n }\n }\n input.close();\n observation.setNrZappedChannels(nrChannels);\n}\n\nvoid readIntegrationSteps(const Observation & observation, const std::string & inputFilename, std::set<unsigned int> & integrationSteps) {\n std::ifstream input;\n\n input.open(inputFilename);\n if ( !input ) {\n throw FileError(\"ERROR: impossible to open integration steps file \\\"\" + inputFilename + \"\\\"\");\n }\n while ( !input.eof() ) {\n unsigned int step = observation.getNrSamplesPerBatch();\n\n input >> step;\n if ( step < observation.getNrSamplesPerBatch() ) {\n integrationSteps.insert(step);\n }\n }\n input.close();\n}\n\n#ifdef HAVE_PSRDADA\nvoid readPSRDADAHeader(Observation & observation, dada_hdu_t & ringBuffer) {\n \/\/ Staging variables for the header elements\n unsigned int uintValue = 0;\n float floatValue[2] = {0.0f, 0.0f};\n \/\/ Header string\n uint64_t headerBytes = 0;\n char * header = 0;\n\n header = ipcbuf_get_next_read(ringBuffer.header_block, &headerBytes);\n if ( (header == 0) || (headerBytes == 0 ) ) {\n throw RingBufferError(\"ERROR: impossible to read the PSRDADA header\");\n }\n ascii_header_get(header, \"SAMPLES_PER_BATCH\", \"%d\", &uintValue);\n observation.setNrSamplesPerBatch(uintValue);\n ascii_header_get(header, \"NCHAN\", \"%d\", &uintValue);\n ascii_header_get(header, \"MIN_FREQUENCY\", \"%f\", &floatValue[0]);\n ascii_header_get(header, \"CHANNEL_BANDWIDTH\", \"%f\", &floatValue[1]);\n observation.setFrequencyRange(observation.getNrSubbands(), uintValue, floatValue[0], floatValue[1]);\n ascii_header_get(header, \"TSAMP\", \"%f\", &floatValue[0]);\n observation.setSamplingTime(floatValue[0]);\n if ( ipcbuf_mark_cleared(ringBuffer.header_block) < 0 ) {\n throw RingBufferError(\"ERROR: impossible to mark the PSRDADA header as cleared\");\n }\n}\n#endif \/\/ HAVE_PSRDADA\n\n} \/\/ AstroData\n\n<|endoftext|>"} {"text":"<commit_before>#include \"Settings.h\"\n\n#include <QSettings>\n\n#include \"Autostart.h\"\n#include \"Hearthstone.h\"\n\n#include \"Updater.h\"\nextern Updater *gUpdater;\n\nDEFINE_SINGLETON_SCOPE( Settings );\n\n#define KEY_ACCOUNT_USERNAME \"username\"\n#define KEY_ACCOUNT_PASSWORD \"password\"\n#define KEY_WEBSERVICE_URL \"webserviceUrl\"\n#define KEY_UPLOAD_METADATA_ENABLED \"uploadMetadataEnabled\"\n#define KEY_HEARTHSTONE_DIRECTORY_PATH \"hearthstoneDirectoryPath\"\n#define KEY_OVERLAY_ENABLED \"overlayEnabled\"\n\nSettings::Settings() {\n}\n\nSettings::~Settings() {\n}\n\n\nQString Settings::AccountUsername() const {\n return QSettings().value( KEY_ACCOUNT_USERNAME ).toString();\n}\n\nQString Settings::AccountPassword() const {\n return QSettings().value( KEY_ACCOUNT_PASSWORD ).toString();\n}\n\nbool Settings::HasAccount() const {\n return !AccountUsername().isEmpty() && !AccountPassword().isEmpty();\n}\n\nvoid Settings::SetAccount( const QString& username, const QString& password ) {\n QSettings s;\n s.setValue( KEY_ACCOUNT_USERNAME, username );\n s.setValue( KEY_ACCOUNT_PASSWORD, password );\n\n emit AccountChanged( username, password );\n}\n\nQString Settings::WebserviceURL() const {\n return QSettings().value( KEY_WEBSERVICE_URL ).toString();\n}\n\nvoid Settings::SetWebserviceURL( const QString& webserviceUrl ) {\n QSettings s;\n s.setValue( KEY_WEBSERVICE_URL, webserviceUrl );\n\n emit WebserviceURLChanged( webserviceUrl );\n}\n\nbool Settings::Autostart() const {\n return ::Autostart().Active();\n}\n\nvoid Settings::SetAutostart( bool enabled ) {\n ::Autostart().SetActive( enabled );\n\n emit AutostartChanged( enabled );\n}\n\nbool Settings::AutoUpdateCheck() const {\n bool enabled = gUpdater && gUpdater->AutomaticallyChecksForUpdates();\n return enabled;\n}\n\nvoid Settings::SetAutoUpdateCheck( bool enabled ) {\n if( gUpdater ) {\n gUpdater->SetAutomaticallyChecksForUpdates( enabled );\n }\n\n emit AutoUpdateCheckChanged( enabled );\n}\n\nvoid Settings::CheckForUpdates() {\n if( gUpdater ) {\n gUpdater->CheckForUpdatesNow();\n }\n}\n\nbool Settings::UploadMetadataEnabled() const {\n return QSettings().value( KEY_UPLOAD_METADATA_ENABLED, false ).toBool();\n}\n\nvoid Settings::SetUploadMetadataEnabled( bool enabled ) {\n QSettings().setValue( KEY_UPLOAD_METADATA_ENABLED, enabled );\n\n emit UploadMetadataEnabledChanged( enabled );\n}\n\nbool Settings::OverlayEnabled() const {\n return QSettings().value( KEY_OVERLAY_ENABLED, true ).toBool();\n}\n\nvoid Settings::SetOverlayEnabled( bool enabled ) {\n QSettings().setValue( KEY_OVERLAY_ENABLED, enabled );\n emit OverlayEnabledChanged( enabled );\n}\n\nQString Settings::HearthstoneDirectoryPath() const {\n QString path = QSettings().value( KEY_HEARTHSTONE_DIRECTORY_PATH ).toString();\n if( path.isEmpty() ) {\n path = Hearthstone::Instance()->DetectHearthstonePath();\n }\n return path;\n}\n\nvoid Settings::SetHearthstoneDirectoryPath( const QString& path ) {\n QSettings s;\n s.setValue( KEY_HEARTHSTONE_DIRECTORY_PATH, path );\n\n emit HearthstoneDirectoryPathChanged( path );\n}\n<commit_msg>Only enable overlay by default for new users<commit_after>#include \"Settings.h\"\n\n#include <QSettings>\n\n#include \"Autostart.h\"\n#include \"Hearthstone.h\"\n\n#include \"Updater.h\"\nextern Updater *gUpdater;\n\nDEFINE_SINGLETON_SCOPE( Settings );\n\n#define KEY_ACCOUNT_USERNAME \"username\"\n#define KEY_ACCOUNT_PASSWORD \"password\"\n#define KEY_WEBSERVICE_URL \"webserviceUrl\"\n#define KEY_UPLOAD_METADATA_ENABLED \"uploadMetadataEnabled\"\n#define KEY_HEARTHSTONE_DIRECTORY_PATH \"hearthstoneDirectoryPath\"\n#define KEY_OVERLAY_ENABLED \"overlayEnabled\"\n\nSettings::Settings() {\n}\n\nSettings::~Settings() {\n}\n\n\nQString Settings::AccountUsername() const {\n return QSettings().value( KEY_ACCOUNT_USERNAME ).toString();\n}\n\nQString Settings::AccountPassword() const {\n return QSettings().value( KEY_ACCOUNT_PASSWORD ).toString();\n}\n\nbool Settings::HasAccount() const {\n return !AccountUsername().isEmpty() && !AccountPassword().isEmpty();\n}\n\nvoid Settings::SetAccount( const QString& username, const QString& password ) {\n QSettings s;\n s.setValue( KEY_ACCOUNT_USERNAME, username );\n s.setValue( KEY_ACCOUNT_PASSWORD, password );\n\n emit AccountChanged( username, password );\n}\n\nQString Settings::WebserviceURL() const {\n return QSettings().value( KEY_WEBSERVICE_URL ).toString();\n}\n\nvoid Settings::SetWebserviceURL( const QString& webserviceUrl ) {\n QSettings s;\n s.setValue( KEY_WEBSERVICE_URL, webserviceUrl );\n\n emit WebserviceURLChanged( webserviceUrl );\n}\n\nbool Settings::Autostart() const {\n return ::Autostart().Active();\n}\n\nvoid Settings::SetAutostart( bool enabled ) {\n ::Autostart().SetActive( enabled );\n\n emit AutostartChanged( enabled );\n}\n\nbool Settings::AutoUpdateCheck() const {\n bool enabled = gUpdater && gUpdater->AutomaticallyChecksForUpdates();\n return enabled;\n}\n\nvoid Settings::SetAutoUpdateCheck( bool enabled ) {\n if( gUpdater ) {\n gUpdater->SetAutomaticallyChecksForUpdates( enabled );\n }\n\n emit AutoUpdateCheckChanged( enabled );\n}\n\nvoid Settings::CheckForUpdates() {\n if( gUpdater ) {\n gUpdater->CheckForUpdatesNow();\n }\n}\n\nbool Settings::UploadMetadataEnabled() const {\n return QSettings().value( KEY_UPLOAD_METADATA_ENABLED, false ).toBool();\n}\n\nvoid Settings::SetUploadMetadataEnabled( bool enabled ) {\n QSettings().setValue( KEY_UPLOAD_METADATA_ENABLED, enabled );\n\n emit UploadMetadataEnabledChanged( enabled );\n}\n\nbool Settings::OverlayEnabled() const {\n \/\/ Enable overlay by default for new users, but not for existing ones\n bool defaultOverlayEnabled = HasAccount() ? false : true;\n return QSettings().value( KEY_OVERLAY_ENABLED, defaultOverlayEnabled ).toBool();\n}\n\nvoid Settings::SetOverlayEnabled( bool enabled ) {\n QSettings().setValue( KEY_OVERLAY_ENABLED, enabled );\n emit OverlayEnabledChanged( enabled );\n}\n\nQString Settings::HearthstoneDirectoryPath() const {\n QString path = QSettings().value( KEY_HEARTHSTONE_DIRECTORY_PATH ).toString();\n if( path.isEmpty() ) {\n path = Hearthstone::Instance()->DetectHearthstonePath();\n }\n return path;\n}\n\nvoid Settings::SetHearthstoneDirectoryPath( const QString& path ) {\n QSettings s;\n s.setValue( KEY_HEARTHSTONE_DIRECTORY_PATH, path );\n\n emit HearthstoneDirectoryPathChanged( path );\n}\n<|endoftext|>"} {"text":"<commit_before>#ifndef ITERBASE_HPP_\n#define ITERBASE_HPP_\n\n\n\/\/ This file consists of utilities used for the generic nature of the\n\/\/ iterable wrapper classes. As such, the contents of this file should be\n\/\/ considered UNDOCUMENTED and is subject to change without warning. This\n\/\/ also applies to the name of the file. No user code should include\n\/\/ this file directly.\n\n#include <utility>\n#include <tuple>\n#include <iterator>\n#include <functional>\n#include <memory>\n#include <type_traits>\n#include <cstddef>\n\nnamespace iter {\n\n \/\/ iterator_type<C> is the type of C's iterator\n template <typename Container>\n using iterator_type =\n decltype(std::begin(std::declval<Container&>()));\n\n \/\/ iterator_deref<C> is the type obtained by dereferencing an iterator\n \/\/ to an object of type C\n template <typename Container>\n using iterator_deref =\n decltype(*std::declval<iterator_type<Container>&>());\n\n \/\/ const_iteator_deref is the type obtained through dereferencing\n \/\/ a const iterator& (note: not a const_iterator). ie: the result\n \/\/ of Container::iterator::operator*() const\n template <typename Container>\n using const_iterator_deref =\n decltype(*std::declval<const iterator_type<Container>&>());\n\n\n template <typename Container>\n using iterator_traits_deref =\n std::remove_reference_t<iterator_deref<Container>>;\n\n \/\/ iterator_type<C> is the type of C's iterator\n template <typename Container>\n using reverse_iterator_type =\n decltype(std::declval<Container&>().rbegin());\n\n \/\/ iterator_deref<C> is the type obtained by dereferencing an iterator\n \/\/ to an object of type C\n template <typename Container>\n using reverse_iterator_deref =\n decltype(*std::declval<reverse_iterator_type<Container>&>());\n\n template <typename, typename =void>\n struct is_random_access_iter : std::false_type { };\n\n template <typename T>\n struct is_random_access_iter<T,\n std::enable_if_t<\n std::is_same<\n typename std::iterator_traits<T>::iterator_category,\n std::random_access_iterator_tag>::value\n >> : std::true_type { };\n\n template <typename T>\n using has_random_access_iter = is_random_access_iter<iterator_type<T>>;\n \/\/ because std::advance assumes a lot and is actually smart, I need a dumb\n\n \/\/ version that will work with most things\n template <typename InputIt, typename Distance =std::size_t>\n void dumb_advance(InputIt& iter, Distance distance=1) {\n for (Distance i(0); i < distance; ++i) {\n ++iter;\n }\n }\n\n template <typename Iter, typename Distance>\n void dumb_advance_impl(Iter& iter, const Iter& end,\n Distance distance, std::false_type) {\n for (Distance i(0); i < distance && iter != end; ++i) {\n ++iter;\n }\n }\n\n template <typename Iter, typename Distance>\n void dumb_advance_impl(Iter& iter, const Iter& end,\n Distance distance, std::true_type) {\n if (static_cast<Distance>(end - iter) < distance) {\n iter = end;\n } else {\n iter += distance;\n }\n }\n\n \/\/ iter will not be incremented past end\n template <typename Iter, typename Distance =std::size_t>\n void dumb_advance(Iter& iter, const Iter& end, Distance distance=1) {\n dumb_advance_impl(iter, end, distance, is_random_access_iter<Iter>{});\n }\n\n template <typename ForwardIt, typename Distance =std::size_t>\n ForwardIt dumb_next(ForwardIt it, Distance distance=1) {\n dumb_advance(it, distance);\n return it;\n }\n\n template <typename ForwardIt, typename Distance =std::size_t>\n ForwardIt dumb_next(\n ForwardIt it, const ForwardIt& end, Distance distance=1) {\n dumb_advance(it, end, distance);\n return it;\n }\n\n template <typename Container, typename Distance =std::size_t>\n Distance dumb_size(Container&& container) {\n Distance d{0};\n for (auto it = std::begin(container), end = std::end(container);\n it != end;\n ++it) {\n ++d;\n }\n return d;\n }\n\n\n template <typename... Ts>\n struct are_same : std::true_type { };\n\n template <typename T, typename U, typename... Ts>\n struct are_same<T, U, Ts...>\n : std::integral_constant<bool,\n std::is_same<T, U>::value && are_same<T, Ts...>::value> { };\n\n namespace detail {\n template <typename... Ts>\n std::tuple<iterator_type<Ts>...> iterator_tuple_type_helper(\n const std::tuple<Ts...>&);\n }\n \/\/ Given a tuple template argument, evaluates to a tuple of iterators\n \/\/ for the template argument's contained types.\n template <typename TupleType>\n using iterator_tuple_type =\n decltype(detail::iterator_tuple_type_helper(\n std::declval<TupleType>()));\n\n namespace detail {\n template <typename... Ts>\n std::tuple<iterator_deref<Ts>...> iterator_tuple_deref_helper(\n const std::tuple<Ts...>&);\n }\n\n \/\/ Given a tuple template argument, evaluates to a tuple of\n \/\/ what the iterators for the template argument's contained types\n \/\/ dereference to\n template <typename TupleType>\n using iterator_deref_tuple =\n decltype(detail::iterator_tuple_deref_helper(\n std::declval<TupleType>()));\n\n \/\/ ---- Tuple utilities ---- \/\/\n \n \/\/ function absorbing all arguments passed to it. used when\n \/\/ applying a function to a parameter pack but not passing the evaluated\n \/\/ results anywhere\n template <typename... Ts>\n void absorb(Ts&&...) { }\n\n namespace detail {\n template <typename Func, typename TupleType, std::size_t... Is>\n decltype(auto) call_with_tuple_impl(Func&& mf, TupleType&& tup,\n std::index_sequence<Is...>) {\n return mf(std::forward<\n std::tuple_element_t<\n Is, std::remove_reference_t<TupleType>>\n >(std::get<Is>(tup))...);\n }\n }\n\n \/\/ expand a TupleType into individual arguments when calling a Func\n template <typename Func, typename TupleType>\n decltype(auto) call_with_tuple(Func&& mf, TupleType&& tup) {\n constexpr auto TUP_SIZE = std::tuple_size<\n std::decay_t<TupleType>>::value;\n return detail::call_with_tuple_impl(\n std::forward<Func>(mf),\n std::forward<TupleType>(tup),\n std::make_index_sequence<TUP_SIZE>{});\n }\n\n \/\/ DerefHolder holds the value gotten from an iterator dereference\n \/\/ if the iterate dereferences to an lvalue references, a pointer to the\n \/\/ element is stored\n \/\/ if it does not, a value is stored instead\n \/\/ get() returns a reference to the held item in either case\n \/\/ pull() should be used when the item is being \"pulled out\" of the\n \/\/ DerefHolder. after pull() is called, neither it nor get() can be\n \/\/ safely called after\n \/\/ reset() replaces the currently held item and may be called after pull()\n\n template <typename T, typename =void>\n class DerefHolder {\n private:\n static_assert(!std::is_lvalue_reference<T>::value,\n \"Non-lvalue-ref specialization used for lvalue ref type\");\n \/\/ it could still be an rvalue reference\n using TPlain = std::remove_reference_t<T>;\n\n std::unique_ptr<TPlain> item_p;\n\n public:\n DerefHolder() = default;\n\n DerefHolder(const DerefHolder& other)\n : item_p{other.item_p ? new TPlain(*other.item_p) : nullptr}\n { }\n\n DerefHolder& operator=(const DerefHolder& other) {\n this->item_p.reset(other.item_p\n ? new TPlain(*other.item_p) : nullptr);\n return *this;\n }\n\n DerefHolder(DerefHolder&&) = default;\n DerefHolder& operator=(DerefHolder&&) = default;\n ~DerefHolder() = default;\n\n TPlain& get() {\n return *item_p;\n }\n\n T pull() {\n \/\/ NOTE should I reset the unique_ptr to nullptr here\n \/\/ since its held item is now invalid anyway?\n return std::move(*item_p);\n }\n\n void reset(T&& item) {\n item_p.reset(new TPlain(std::move(item)));\n }\n\n explicit operator bool() const {\n return this->item_p;\n }\n };\n\n\n \/\/ Specialization for when T is an lvalue ref. Keep this in mind\n \/\/ wherever a T appears.\n template <typename T>\n class DerefHolder<T,\n typename std::enable_if<std::is_lvalue_reference<T>::value>::type>\n {\n private:\n static_assert(std::is_lvalue_reference<T>::value,\n \"lvalue specialization handling non-lvalue-ref type\");\n\n std::remove_reference_t<T> *item_p =nullptr;\n public:\n DerefHolder() = default;\n\n T get() {\n return *this->item_p;\n }\n\n T pull() {\n return this->get();\n }\n\n void reset(T item) {\n this->item_p = &item;\n }\n\n explicit operator bool() const {\n return this->item_p != nullptr;\n }\n };\n\n template <typename T>\n struct type_is {\n using type = T;\n };\n\n \/\/ gcc CWG 1558\n template <typename...>\n struct void_t_help {\n using type = void;\n };\n template <typename... Ts>\n using void_t = typename void_t_help<Ts...>::type;\n}\n\n#endif\n<commit_msg>adds reverse iter aliases<commit_after>#ifndef ITERBASE_HPP_\n#define ITERBASE_HPP_\n\n\n\/\/ This file consists of utilities used for the generic nature of the\n\/\/ iterable wrapper classes. As such, the contents of this file should be\n\/\/ considered UNDOCUMENTED and is subject to change without warning. This\n\/\/ also applies to the name of the file. No user code should include\n\/\/ this file directly.\n\n#include <utility>\n#include <tuple>\n#include <iterator>\n#include <functional>\n#include <memory>\n#include <type_traits>\n#include <cstddef>\n\nnamespace iter {\n\n \/\/ iterator_type<C> is the type of C's iterator\n template <typename Container>\n using iterator_type =\n decltype(std::begin(std::declval<Container&>()));\n\n \/\/ iterator_deref<C> is the type obtained by dereferencing an iterator\n \/\/ to an object of type C\n template <typename Container>\n using iterator_deref =\n decltype(*std::declval<iterator_type<Container>&>());\n\n \/\/ const_iteator_deref is the type obtained through dereferencing\n \/\/ a const iterator& (note: not a const_iterator). ie: the result\n \/\/ of Container::iterator::operator*() const\n template <typename Container>\n using const_iterator_deref =\n decltype(*std::declval<const iterator_type<Container>&>());\n\n\n template <typename Container>\n using iterator_traits_deref =\n std::remove_reference_t<iterator_deref<Container>>;\n\n \/\/ iterator_type<C> is the type of C's iterator\n template <typename Container>\n using reverse_iterator_type =\n decltype(std::rbegin(std::declval<Container&>()));\n\n \/\/ iterator_deref<C> is the type obtained by dereferencing an iterator\n \/\/ to an object of type C\n template <typename Container>\n using reverse_iterator_deref =\n decltype(*std::declval<reverse_iterator_type<Container>&>());\n\n template <typename Container>\n using reverse_iterator_traits_deref =\n std::remove_reference_t<reverse_iterator_deref<Container>>;\n\n template <typename, typename =void>\n struct is_random_access_iter : std::false_type { };\n\n template <typename T>\n struct is_random_access_iter<T,\n std::enable_if_t<\n std::is_same<\n typename std::iterator_traits<T>::iterator_category,\n std::random_access_iterator_tag>::value\n >> : std::true_type { };\n\n template <typename T>\n using has_random_access_iter = is_random_access_iter<iterator_type<T>>;\n \/\/ because std::advance assumes a lot and is actually smart, I need a dumb\n\n \/\/ version that will work with most things\n template <typename InputIt, typename Distance =std::size_t>\n void dumb_advance(InputIt& iter, Distance distance=1) {\n for (Distance i(0); i < distance; ++i) {\n ++iter;\n }\n }\n\n template <typename Iter, typename Distance>\n void dumb_advance_impl(Iter& iter, const Iter& end,\n Distance distance, std::false_type) {\n for (Distance i(0); i < distance && iter != end; ++i) {\n ++iter;\n }\n }\n\n template <typename Iter, typename Distance>\n void dumb_advance_impl(Iter& iter, const Iter& end,\n Distance distance, std::true_type) {\n if (static_cast<Distance>(end - iter) < distance) {\n iter = end;\n } else {\n iter += distance;\n }\n }\n\n \/\/ iter will not be incremented past end\n template <typename Iter, typename Distance =std::size_t>\n void dumb_advance(Iter& iter, const Iter& end, Distance distance=1) {\n dumb_advance_impl(iter, end, distance, is_random_access_iter<Iter>{});\n }\n\n template <typename ForwardIt, typename Distance =std::size_t>\n ForwardIt dumb_next(ForwardIt it, Distance distance=1) {\n dumb_advance(it, distance);\n return it;\n }\n\n template <typename ForwardIt, typename Distance =std::size_t>\n ForwardIt dumb_next(\n ForwardIt it, const ForwardIt& end, Distance distance=1) {\n dumb_advance(it, end, distance);\n return it;\n }\n\n template <typename Container, typename Distance =std::size_t>\n Distance dumb_size(Container&& container) {\n Distance d{0};\n for (auto it = std::begin(container), end = std::end(container);\n it != end;\n ++it) {\n ++d;\n }\n return d;\n }\n\n\n template <typename... Ts>\n struct are_same : std::true_type { };\n\n template <typename T, typename U, typename... Ts>\n struct are_same<T, U, Ts...>\n : std::integral_constant<bool,\n std::is_same<T, U>::value && are_same<T, Ts...>::value> { };\n\n namespace detail {\n template <typename... Ts>\n std::tuple<iterator_type<Ts>...> iterator_tuple_type_helper(\n const std::tuple<Ts...>&);\n }\n \/\/ Given a tuple template argument, evaluates to a tuple of iterators\n \/\/ for the template argument's contained types.\n template <typename TupleType>\n using iterator_tuple_type =\n decltype(detail::iterator_tuple_type_helper(\n std::declval<TupleType>()));\n\n namespace detail {\n template <typename... Ts>\n std::tuple<iterator_deref<Ts>...> iterator_tuple_deref_helper(\n const std::tuple<Ts...>&);\n }\n\n \/\/ Given a tuple template argument, evaluates to a tuple of\n \/\/ what the iterators for the template argument's contained types\n \/\/ dereference to\n template <typename TupleType>\n using iterator_deref_tuple =\n decltype(detail::iterator_tuple_deref_helper(\n std::declval<TupleType>()));\n\n \/\/ ---- Tuple utilities ---- \/\/\n \n \/\/ function absorbing all arguments passed to it. used when\n \/\/ applying a function to a parameter pack but not passing the evaluated\n \/\/ results anywhere\n template <typename... Ts>\n void absorb(Ts&&...) { }\n\n namespace detail {\n template <typename Func, typename TupleType, std::size_t... Is>\n decltype(auto) call_with_tuple_impl(Func&& mf, TupleType&& tup,\n std::index_sequence<Is...>) {\n return mf(std::forward<\n std::tuple_element_t<\n Is, std::remove_reference_t<TupleType>>\n >(std::get<Is>(tup))...);\n }\n }\n\n \/\/ expand a TupleType into individual arguments when calling a Func\n template <typename Func, typename TupleType>\n decltype(auto) call_with_tuple(Func&& mf, TupleType&& tup) {\n constexpr auto TUP_SIZE = std::tuple_size<\n std::decay_t<TupleType>>::value;\n return detail::call_with_tuple_impl(\n std::forward<Func>(mf),\n std::forward<TupleType>(tup),\n std::make_index_sequence<TUP_SIZE>{});\n }\n\n \/\/ DerefHolder holds the value gotten from an iterator dereference\n \/\/ if the iterate dereferences to an lvalue references, a pointer to the\n \/\/ element is stored\n \/\/ if it does not, a value is stored instead\n \/\/ get() returns a reference to the held item in either case\n \/\/ pull() should be used when the item is being \"pulled out\" of the\n \/\/ DerefHolder. after pull() is called, neither it nor get() can be\n \/\/ safely called after\n \/\/ reset() replaces the currently held item and may be called after pull()\n\n template <typename T, typename =void>\n class DerefHolder {\n private:\n static_assert(!std::is_lvalue_reference<T>::value,\n \"Non-lvalue-ref specialization used for lvalue ref type\");\n \/\/ it could still be an rvalue reference\n using TPlain = std::remove_reference_t<T>;\n\n std::unique_ptr<TPlain> item_p;\n\n public:\n DerefHolder() = default;\n\n DerefHolder(const DerefHolder& other)\n : item_p{other.item_p ? new TPlain(*other.item_p) : nullptr}\n { }\n\n DerefHolder& operator=(const DerefHolder& other) {\n this->item_p.reset(other.item_p\n ? new TPlain(*other.item_p) : nullptr);\n return *this;\n }\n\n DerefHolder(DerefHolder&&) = default;\n DerefHolder& operator=(DerefHolder&&) = default;\n ~DerefHolder() = default;\n\n TPlain& get() {\n return *item_p;\n }\n\n T pull() {\n \/\/ NOTE should I reset the unique_ptr to nullptr here\n \/\/ since its held item is now invalid anyway?\n return std::move(*item_p);\n }\n\n void reset(T&& item) {\n item_p.reset(new TPlain(std::move(item)));\n }\n\n explicit operator bool() const {\n return this->item_p;\n }\n };\n\n\n \/\/ Specialization for when T is an lvalue ref. Keep this in mind\n \/\/ wherever a T appears.\n template <typename T>\n class DerefHolder<T,\n typename std::enable_if<std::is_lvalue_reference<T>::value>::type>\n {\n private:\n static_assert(std::is_lvalue_reference<T>::value,\n \"lvalue specialization handling non-lvalue-ref type\");\n\n std::remove_reference_t<T> *item_p =nullptr;\n public:\n DerefHolder() = default;\n\n T get() {\n return *this->item_p;\n }\n\n T pull() {\n return this->get();\n }\n\n void reset(T item) {\n this->item_p = &item;\n }\n\n explicit operator bool() const {\n return this->item_p != nullptr;\n }\n };\n\n template <typename T>\n struct type_is {\n using type = T;\n };\n\n \/\/ gcc CWG 1558\n template <typename...>\n struct void_t_help {\n using type = void;\n };\n template <typename... Ts>\n using void_t = typename void_t_help<Ts...>::type;\n}\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/*!\n * This file is part of CameraPlus.\n *\n * Copyright (C) 2012-2014 Mohammed Sameer <msameer@foolab.org>\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n *\/\n\n#include \"settings.h\"\n#include <QSettings>\n#include <QDir>\n#include \"devicesettings.h\"\n\n#define PATH QString(\"%1%2.config%2\/cameraplus.conf\").arg(QDir::homePath()).arg(QDir::separator())\n\n#define DEFAULT_MODE 1\n#define DEFAULT_USE_GPS true\n#define DEFAULT_USE_GEOTAGS true\n#define DEFAULT_SOUND_ENABLED true\n#define DEFAULT_SHOW_TOOL_BAR false\n#define DEFAULT_VIDEO_MUTE false\n#define DEFAULT_GRID_ENABLED false\n#define DEFAULT_FACE_DETECTION_ENABLED true\n#define DEFAULT_ZOOM_AS_SHUTTER false\n#define DEFAULT_PROXIMITY_AS_SHUTTER false\n#define DEFAULT_DEVICE 0\n#define DEFAULT_ENABLE_PREVIEW true\n#define DEFAULT_NIGHT_MODE false\n#define DEFAULT_PLUGIN \"org.foolab.cameraplus.image\"\n#define DEFAULT_CAPTURE_TIMER_DELAY 5\n\nSettings::Settings(QObject *parent) :\n QObject(parent),\n m_settings(new QSettings(PATH, QSettings::IniFormat, this)) {\n\n}\n\nSettings::~Settings() {\n delete m_settings; m_settings = 0;\n}\n\nint Settings::mode() const {\n return m_settings->value(\"camera\/mode\", DEFAULT_MODE).toInt();\n}\n\nvoid Settings::setMode(int mode) {\n if (mode != Settings::mode()) {\n m_settings->setValue(\"camera\/mode\", mode);\n\n emit modeChanged();\n }\n}\n\nQString Settings::creatorName() const {\n return m_settings->value(\"camera\/creatorName\").toString();\n}\n\nvoid Settings::setCreatorName(const QString& name) {\n if (name != creatorName()) {\n m_settings->setValue(\"camera\/creatorName\", name);\n\n emit creatorNameChanged();\n }\n}\n\nbool Settings::useGps() const {\n return m_settings->value(\"camera\/useGps\", DEFAULT_USE_GPS).toBool();\n}\n\nvoid Settings::setUseGps(bool enable) {\n if (enable != useGps()) {\n m_settings->setValue(\"camera\/useGps\", enable);\n\n emit useGpsChanged();\n }\n}\n\nbool Settings::useGeotags() const {\n return m_settings->value(\"camera\/useGeotags\", DEFAULT_USE_GEOTAGS).toBool();\n}\n\nvoid Settings::setUseGeotags(bool enable) {\n if (enable != useGeotags()) {\n m_settings->setValue(\"camera\/useGeotags\", enable);\n\n emit useGeotagsChanged();\n }\n}\n\nbool Settings::isSoundEnabled() const {\n return m_settings->value(\"camera\/soundEnabled\", DEFAULT_SOUND_ENABLED).toBool();\n}\n\nvoid Settings::setSoundEnabled(bool enabled) {\n if (isSoundEnabled() != enabled) {\n m_settings->setValue(\"camera\/soundEnabled\", enabled);\n emit soundEnabledChanged();\n }\n}\n\nbool Settings::isToolBarShown() const {\n return m_settings->value(\"camera\/showToolBar\", DEFAULT_SHOW_TOOL_BAR).toBool();\n}\n\nvoid Settings::setToolBarShown(bool shown) {\n if (isToolBarShown() != shown) {\n m_settings->setValue(\"camera\/showToolBar\", shown);\n\n emit toolBarShownChanged();\n }\n}\n\nbool Settings::isGridEnabled() const {\n return m_settings->value(\"camera\/gridEnabled\", DEFAULT_GRID_ENABLED).toBool();\n}\n\nvoid Settings::setGridEnabled(bool enabled) {\n if (enabled != isGridEnabled()) {\n m_settings->setValue(\"camera\/gridEnabled\", enabled);\n emit gridEnabledChanged();\n }\n}\n\nbool Settings::isFaceDetectionEnabled() const {\n return m_settings->value(\"image\/faceDetectionEnabled\", DEFAULT_FACE_DETECTION_ENABLED).toBool();\n}\n\nvoid Settings::setFaceDetectionEnabled(bool enabled) {\n if (isFaceDetectionEnabled() != enabled) {\n m_settings->setValue(\"image\/faceDetectionEnabled\", enabled);\n emit faceDetectionEnabledChanged();\n }\n}\n\nbool Settings::isZoomAsShutterEnabled() const {\n return m_settings->value(\"camera\/zoomAsShutter\", DEFAULT_ZOOM_AS_SHUTTER).toBool();\n}\n\nvoid Settings::setZoomAsShutterEnabled(bool enabled) {\n if (isZoomAsShutterEnabled() != enabled) {\n m_settings->setValue(\"camera\/zoomAsShutter\", enabled);\n\n emit zoomAsShutterChanged();\n }\n}\n\nbool Settings::isProximityAsShutterEnabled() const {\n return m_settings->value(\"camera\/proximityAsShutter\", DEFAULT_PROXIMITY_AS_SHUTTER).toBool();\n}\n\nvoid Settings::setProximityAsShutterEnabled(bool enabled) {\n if (isProximityAsShutterEnabled() != enabled) {\n m_settings->setValue(\"camera\/proximityAsShutter\", enabled);\n\n emit proximityAsShutterChanged();\n }\n}\n\nint Settings::device() const {\n return m_settings->value(\"camera\/device\", DEFAULT_DEVICE).toInt();\n}\n\nvoid Settings::setDevice(int device) {\n if (device != Settings::device()) {\n m_settings->setValue(\"camera\/device\", device);\n emit deviceChanged();\n }\n}\n\nQVariant Settings::value(const QString& key, const QVariant& defaultValue) const {\n return m_settings->value(key, defaultValue);\n}\n\nvoid Settings::setValue(const QString& key, const QVariant& value) {\n m_settings->setValue(key, value);\n}\n\nQString Settings::fileNamingStamp(const QString& id) const {\n QString key = QString(\"fileNaming\/%1\").arg(id);\n return m_settings->value(key).toString();\n}\n\nvoid Settings::setFileNamingStamp(const QString& id, const QString& stamp) {\n QString key = QString(\"fileNaming\/%1\").arg(id);\n m_settings->setValue(key, stamp);\n}\n\nint Settings::fileNamingCounter(const QString& id) const {\n QString key = QString(\"fileNaming\/%1\").arg(id);\n return m_settings->value(key).toInt();\n}\n\nvoid Settings::setFileNamingCounter(const QString& id, int counter) {\n QString key = QString(\"fileNaming\/%1\").arg(id);\n m_settings->setValue(key, counter);\n}\n\nbool Settings::isPreviewEnabled() const {\n return m_settings->value(\"camera\/enablePreview\", DEFAULT_ENABLE_PREVIEW).toBool();\n}\n\nvoid Settings::setPreviewEnabled(bool enabled) {\n if (enabled != isPreviewEnabled()) {\n m_settings->setValue(\"camera\/enablePreview\", enabled);\n\n emit previewEnabledChanged();\n }\n}\n\nbool Settings::isNightModeEnabled() const {\n return m_settings->value(\"camera\/nightMode\", DEFAULT_NIGHT_MODE).toBool();\n}\n\nvoid Settings::setNightModeEnabled(bool enabled) {\n if (isNightModeEnabled() != enabled) {\n m_settings->setValue(\"camera\/nightMode\", enabled);\n emit nightModeChanged();\n }\n}\n\nQString Settings::plugin() const {\n return m_settings->value(\"camera\/plugin\", DEFAULT_PLUGIN).toString();\n}\n\nvoid Settings::setPlugin(const QString& plugin) {\n if (Settings::plugin() != plugin) {\n m_settings->setValue(\"camera\/plugin\", plugin);\n emit pluginChanged();\n }\n}\n\nint Settings::captureTimerDelay() const {\n return m_settings->value(\"captureTimer\/delay\", DEFAULT_CAPTURE_TIMER_DELAY).toInt();\n}\n\nvoid Settings::setCaptureTimerDelay(int delay) {\n if (delay != captureTimerDelay()) {\n m_settings->setValue(\"captureTimer\/delay\", delay);\n emit captureTimerDelayChanged();\n }\n}\n<commit_msg>sailfish: adjust the settings path to be harbour compliant<commit_after>\/*!\n * This file is part of CameraPlus.\n *\n * Copyright (C) 2012-2014 Mohammed Sameer <msameer@foolab.org>\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n *\/\n\n#include \"settings.h\"\n#include <QSettings>\n#include <QDir>\n#include \"devicesettings.h\"\n\n#ifdef SAILFISH\n#define PATH QString(\"%1%2.config%2harbour-cameraplus%2harbour-cameraplus.conf\").arg(QDir::homePath()).arg(QDir::separator())\n#else\n#define PATH QString(\"%1%2.config%2cameraplus.conf\").arg(QDir::homePath()).arg(QDir::separator())\n#endif\n\n#define DEFAULT_MODE 1\n#define DEFAULT_USE_GPS true\n#define DEFAULT_USE_GEOTAGS true\n#define DEFAULT_SOUND_ENABLED true\n#define DEFAULT_SHOW_TOOL_BAR false\n#define DEFAULT_VIDEO_MUTE false\n#define DEFAULT_GRID_ENABLED false\n#define DEFAULT_FACE_DETECTION_ENABLED true\n#define DEFAULT_ZOOM_AS_SHUTTER false\n#define DEFAULT_PROXIMITY_AS_SHUTTER false\n#define DEFAULT_DEVICE 0\n#define DEFAULT_ENABLE_PREVIEW true\n#define DEFAULT_NIGHT_MODE false\n#define DEFAULT_PLUGIN \"org.foolab.cameraplus.image\"\n#define DEFAULT_CAPTURE_TIMER_DELAY 5\n\nSettings::Settings(QObject *parent) :\n QObject(parent),\n m_settings(new QSettings(PATH, QSettings::IniFormat, this)) {\n\n}\n\nSettings::~Settings() {\n delete m_settings; m_settings = 0;\n}\n\nint Settings::mode() const {\n return m_settings->value(\"camera\/mode\", DEFAULT_MODE).toInt();\n}\n\nvoid Settings::setMode(int mode) {\n if (mode != Settings::mode()) {\n m_settings->setValue(\"camera\/mode\", mode);\n\n emit modeChanged();\n }\n}\n\nQString Settings::creatorName() const {\n return m_settings->value(\"camera\/creatorName\").toString();\n}\n\nvoid Settings::setCreatorName(const QString& name) {\n if (name != creatorName()) {\n m_settings->setValue(\"camera\/creatorName\", name);\n\n emit creatorNameChanged();\n }\n}\n\nbool Settings::useGps() const {\n return m_settings->value(\"camera\/useGps\", DEFAULT_USE_GPS).toBool();\n}\n\nvoid Settings::setUseGps(bool enable) {\n if (enable != useGps()) {\n m_settings->setValue(\"camera\/useGps\", enable);\n\n emit useGpsChanged();\n }\n}\n\nbool Settings::useGeotags() const {\n return m_settings->value(\"camera\/useGeotags\", DEFAULT_USE_GEOTAGS).toBool();\n}\n\nvoid Settings::setUseGeotags(bool enable) {\n if (enable != useGeotags()) {\n m_settings->setValue(\"camera\/useGeotags\", enable);\n\n emit useGeotagsChanged();\n }\n}\n\nbool Settings::isSoundEnabled() const {\n return m_settings->value(\"camera\/soundEnabled\", DEFAULT_SOUND_ENABLED).toBool();\n}\n\nvoid Settings::setSoundEnabled(bool enabled) {\n if (isSoundEnabled() != enabled) {\n m_settings->setValue(\"camera\/soundEnabled\", enabled);\n emit soundEnabledChanged();\n }\n}\n\nbool Settings::isToolBarShown() const {\n return m_settings->value(\"camera\/showToolBar\", DEFAULT_SHOW_TOOL_BAR).toBool();\n}\n\nvoid Settings::setToolBarShown(bool shown) {\n if (isToolBarShown() != shown) {\n m_settings->setValue(\"camera\/showToolBar\", shown);\n\n emit toolBarShownChanged();\n }\n}\n\nbool Settings::isGridEnabled() const {\n return m_settings->value(\"camera\/gridEnabled\", DEFAULT_GRID_ENABLED).toBool();\n}\n\nvoid Settings::setGridEnabled(bool enabled) {\n if (enabled != isGridEnabled()) {\n m_settings->setValue(\"camera\/gridEnabled\", enabled);\n emit gridEnabledChanged();\n }\n}\n\nbool Settings::isFaceDetectionEnabled() const {\n return m_settings->value(\"image\/faceDetectionEnabled\", DEFAULT_FACE_DETECTION_ENABLED).toBool();\n}\n\nvoid Settings::setFaceDetectionEnabled(bool enabled) {\n if (isFaceDetectionEnabled() != enabled) {\n m_settings->setValue(\"image\/faceDetectionEnabled\", enabled);\n emit faceDetectionEnabledChanged();\n }\n}\n\nbool Settings::isZoomAsShutterEnabled() const {\n return m_settings->value(\"camera\/zoomAsShutter\", DEFAULT_ZOOM_AS_SHUTTER).toBool();\n}\n\nvoid Settings::setZoomAsShutterEnabled(bool enabled) {\n if (isZoomAsShutterEnabled() != enabled) {\n m_settings->setValue(\"camera\/zoomAsShutter\", enabled);\n\n emit zoomAsShutterChanged();\n }\n}\n\nbool Settings::isProximityAsShutterEnabled() const {\n return m_settings->value(\"camera\/proximityAsShutter\", DEFAULT_PROXIMITY_AS_SHUTTER).toBool();\n}\n\nvoid Settings::setProximityAsShutterEnabled(bool enabled) {\n if (isProximityAsShutterEnabled() != enabled) {\n m_settings->setValue(\"camera\/proximityAsShutter\", enabled);\n\n emit proximityAsShutterChanged();\n }\n}\n\nint Settings::device() const {\n return m_settings->value(\"camera\/device\", DEFAULT_DEVICE).toInt();\n}\n\nvoid Settings::setDevice(int device) {\n if (device != Settings::device()) {\n m_settings->setValue(\"camera\/device\", device);\n emit deviceChanged();\n }\n}\n\nQVariant Settings::value(const QString& key, const QVariant& defaultValue) const {\n return m_settings->value(key, defaultValue);\n}\n\nvoid Settings::setValue(const QString& key, const QVariant& value) {\n m_settings->setValue(key, value);\n}\n\nQString Settings::fileNamingStamp(const QString& id) const {\n QString key = QString(\"fileNaming\/%1\").arg(id);\n return m_settings->value(key).toString();\n}\n\nvoid Settings::setFileNamingStamp(const QString& id, const QString& stamp) {\n QString key = QString(\"fileNaming\/%1\").arg(id);\n m_settings->setValue(key, stamp);\n}\n\nint Settings::fileNamingCounter(const QString& id) const {\n QString key = QString(\"fileNaming\/%1\").arg(id);\n return m_settings->value(key).toInt();\n}\n\nvoid Settings::setFileNamingCounter(const QString& id, int counter) {\n QString key = QString(\"fileNaming\/%1\").arg(id);\n m_settings->setValue(key, counter);\n}\n\nbool Settings::isPreviewEnabled() const {\n return m_settings->value(\"camera\/enablePreview\", DEFAULT_ENABLE_PREVIEW).toBool();\n}\n\nvoid Settings::setPreviewEnabled(bool enabled) {\n if (enabled != isPreviewEnabled()) {\n m_settings->setValue(\"camera\/enablePreview\", enabled);\n\n emit previewEnabledChanged();\n }\n}\n\nbool Settings::isNightModeEnabled() const {\n return m_settings->value(\"camera\/nightMode\", DEFAULT_NIGHT_MODE).toBool();\n}\n\nvoid Settings::setNightModeEnabled(bool enabled) {\n if (isNightModeEnabled() != enabled) {\n m_settings->setValue(\"camera\/nightMode\", enabled);\n emit nightModeChanged();\n }\n}\n\nQString Settings::plugin() const {\n return m_settings->value(\"camera\/plugin\", DEFAULT_PLUGIN).toString();\n}\n\nvoid Settings::setPlugin(const QString& plugin) {\n if (Settings::plugin() != plugin) {\n m_settings->setValue(\"camera\/plugin\", plugin);\n emit pluginChanged();\n }\n}\n\nint Settings::captureTimerDelay() const {\n return m_settings->value(\"captureTimer\/delay\", DEFAULT_CAPTURE_TIMER_DELAY).toInt();\n}\n\nvoid Settings::setCaptureTimerDelay(int delay) {\n if (delay != captureTimerDelay()) {\n m_settings->setValue(\"captureTimer\/delay\", delay);\n emit captureTimerDelayChanged();\n }\n}\n<|endoftext|>"} {"text":"<commit_before>#include <cctype>\n#include <fstream>\n#include <stdio.h>\n#include <sstream> \/\/ ostringstream\n#include \"utils\/logoutput.h\"\n\n#include \"settings.h\"\n#include \"settingRegistry.h\"\n\n\/\/c++11 no longer defines M_PI, so add our own constant.\n#ifndef M_PI\n#define M_PI 3.14159265358979323846\n#endif\n\nSettingsBase::SettingsBase()\n: parent(NULL)\n{\n}\n\nSettingsBase::SettingsBase(SettingsBase* parent)\n: parent(parent)\n{\n}\n\nvoid SettingsBase::setSetting(std::string key, std::string value)\n{\n if (SettingRegistry::getInstance()->settingExists(key))\n {\n setting_values[key] = value;\n }\n else\n {\n cura::logError(\"Warning: setting an unregistered setting %s\\n\", key.c_str() );\n setting_values[key] = value; \/\/ Handy when programmers are in the process of introducing a new setting\n }\n}\n\nstd::string SettingsBase::getSettingString(std::string key)\n{\n if (setting_values.find(key) != setting_values.end())\n {\n return setting_values[key];\n }\n if (parent)\n {\n return parent->getSettingString(key);\n }\n \n if (SettingRegistry::getInstance()->settingExists(key))\n {\n setting_values[key] = SettingRegistry::getInstance()->getSettingConfig(key)->getDefaultValue();\n \/\/cura::logError(\"Using default for: %s = %s\\n\", key.c_str(), setting_values[key].c_str());\n }\n else\n {\n setting_values[key] = \"\";\n cura::logError(\"Unregistered setting %s\\n\", key.c_str());\n }\n return setting_values[key];\n}\n\nbool SettingsBase::hasSetting(std::string key)\n{\n if (setting_values.find(key) != setting_values.end())\n {\n return true;\n }\n if (parent)\n {\n return parent->hasSetting(key);\n }\n \n return false;\n}\n\nint SettingsBase::getSettingAsIndex(std::string key)\n{\n std::string value = getSettingString(key);\n return atoi(value.c_str());\n}\n\nint SettingsBase::getSettingAsCount(std::string key)\n{\n std::string value = getSettingString(key);\n return atoi(value.c_str());\n}\n\nint SettingsBase::getSettingInMicrons(std::string key)\n{\n std::string value = getSettingString(key);\n return atof(value.c_str()) * 1000.0;\n}\n\ndouble SettingsBase::getSettingInAngleRadians(std::string key)\n{\n std::string value = getSettingString(key);\n return atof(value.c_str()) \/ 180.0 * M_PI;\n}\n\nbool SettingsBase::getSettingBoolean(std::string key)\n{\n std::string value = getSettingString(key);\n if (value == \"on\")\n return true;\n if (value == \"yes\")\n return true;\n if (value == \"true\")\n return true;\n return atoi(value.c_str()) != 0;\n}\n\ndouble SettingsBase::getSettingInDegreeCelsius(std::string key)\n{\n std::string value = getSettingString(key);\n return atof(value.c_str());\n}\n\ndouble SettingsBase::getSettingInMillimetersPerSecond(std::string key)\n{\n std::string value = getSettingString(key);\n return std::max(1.0, atof(value.c_str()));\n}\n\ndouble SettingsBase::getSettingInPercentage(std::string key)\n{\n std::string value = getSettingString(key);\n return std::max(0.0, atof(value.c_str()));\n}\n\ndouble SettingsBase::getSettingInSeconds(std::string key)\n{\n std::string value = getSettingString(key);\n return std::max(0.0, atof(value.c_str()));\n}\n\nEGCodeFlavor SettingsBase::getSettingAsGCodeFlavor(std::string key)\n{\n std::string value = getSettingString(key);\n if (value == \"RepRap\")\n return GCODE_FLAVOR_REPRAP;\n else if (value == \"UltiGCode\")\n return GCODE_FLAVOR_ULTIGCODE;\n else if (value == \"Makerbot\")\n return GCODE_FLAVOR_MAKERBOT;\n else if (value == \"BFB\")\n return GCODE_FLAVOR_BFB;\n else if (value == \"MACH3\")\n return GCODE_FLAVOR_MACH3;\n else if (value == \"RepRap (Volumatric)\")\n return GCODE_FLAVOR_REPRAP_VOLUMATRIC;\n return GCODE_FLAVOR_REPRAP;\n}\n\nEFillMethod SettingsBase::getSettingAsFillMethod(std::string key)\n{\n std::string value = getSettingString(key);\n if (value == \"Lines\")\n return Fill_Lines;\n if (value == \"Grid\")\n return Fill_Grid;\n if (value == \"Triangles\")\n return Fill_Triangles;\n if (value == \"Concentric\")\n return Fill_Concentric;\n if (value == \"ZigZag\")\n return Fill_ZigZag;\n return Fill_None;\n}\n\nEPlatformAdhesion SettingsBase::getSettingAsPlatformAdhesion(std::string key)\n{\n std::string value = getSettingString(key);\n if (value == \"Brim\")\n return Adhesion_Brim;\n if (value == \"Raft\")\n return Adhesion_Raft;\n return Adhesion_None;\n}\n\nESupportType SettingsBase::getSettingAsSupportType(std::string key)\n{\n std::string value = getSettingString(key);\n if (value == \"Everywhere\")\n return Support_Everywhere;\n if (value == \"Touching Buildplate\")\n return Support_PlatformOnly;\n return Support_None;\n}\n<commit_msg>Fix support generation by making sure \"True\" is also recognised as true<commit_after>#include <cctype>\n#include <fstream>\n#include <stdio.h>\n#include <sstream> \/\/ ostringstream\n#include \"utils\/logoutput.h\"\n\n#include \"settings.h\"\n#include \"settingRegistry.h\"\n\n\/\/c++11 no longer defines M_PI, so add our own constant.\n#ifndef M_PI\n#define M_PI 3.14159265358979323846\n#endif\n\nSettingsBase::SettingsBase()\n: parent(NULL)\n{\n}\n\nSettingsBase::SettingsBase(SettingsBase* parent)\n: parent(parent)\n{\n}\n\nvoid SettingsBase::setSetting(std::string key, std::string value)\n{\n if (SettingRegistry::getInstance()->settingExists(key))\n {\n setting_values[key] = value;\n }\n else\n {\n cura::logError(\"Warning: setting an unregistered setting %s\\n\", key.c_str() );\n setting_values[key] = value; \/\/ Handy when programmers are in the process of introducing a new setting\n }\n}\n\nstd::string SettingsBase::getSettingString(std::string key)\n{\n if (setting_values.find(key) != setting_values.end())\n {\n return setting_values[key];\n }\n if (parent)\n {\n return parent->getSettingString(key);\n }\n \n if (SettingRegistry::getInstance()->settingExists(key))\n {\n setting_values[key] = SettingRegistry::getInstance()->getSettingConfig(key)->getDefaultValue();\n \/\/cura::logError(\"Using default for: %s = %s\\n\", key.c_str(), setting_values[key].c_str());\n }\n else\n {\n setting_values[key] = \"\";\n cura::logError(\"Unregistered setting %s\\n\", key.c_str());\n }\n return setting_values[key];\n}\n\nbool SettingsBase::hasSetting(std::string key)\n{\n if (setting_values.find(key) != setting_values.end())\n {\n return true;\n }\n if (parent)\n {\n return parent->hasSetting(key);\n }\n \n return false;\n}\n\nint SettingsBase::getSettingAsIndex(std::string key)\n{\n std::string value = getSettingString(key);\n return atoi(value.c_str());\n}\n\nint SettingsBase::getSettingAsCount(std::string key)\n{\n std::string value = getSettingString(key);\n return atoi(value.c_str());\n}\n\nint SettingsBase::getSettingInMicrons(std::string key)\n{\n std::string value = getSettingString(key);\n return atof(value.c_str()) * 1000.0;\n}\n\ndouble SettingsBase::getSettingInAngleRadians(std::string key)\n{\n std::string value = getSettingString(key);\n return atof(value.c_str()) \/ 180.0 * M_PI;\n}\n\nbool SettingsBase::getSettingBoolean(std::string key)\n{\n std::string value = getSettingString(key);\n if (value == \"on\")\n return true;\n if (value == \"yes\")\n return true;\n if (value == \"true\" or value == \"True\") \/\/Python uses \"True\"\n return true;\n return atoi(value.c_str()) != 0;\n}\n\ndouble SettingsBase::getSettingInDegreeCelsius(std::string key)\n{\n std::string value = getSettingString(key);\n return atof(value.c_str());\n}\n\ndouble SettingsBase::getSettingInMillimetersPerSecond(std::string key)\n{\n std::string value = getSettingString(key);\n return std::max(1.0, atof(value.c_str()));\n}\n\ndouble SettingsBase::getSettingInPercentage(std::string key)\n{\n std::string value = getSettingString(key);\n return std::max(0.0, atof(value.c_str()));\n}\n\ndouble SettingsBase::getSettingInSeconds(std::string key)\n{\n std::string value = getSettingString(key);\n return std::max(0.0, atof(value.c_str()));\n}\n\nEGCodeFlavor SettingsBase::getSettingAsGCodeFlavor(std::string key)\n{\n std::string value = getSettingString(key);\n if (value == \"RepRap\")\n return GCODE_FLAVOR_REPRAP;\n else if (value == \"UltiGCode\")\n return GCODE_FLAVOR_ULTIGCODE;\n else if (value == \"Makerbot\")\n return GCODE_FLAVOR_MAKERBOT;\n else if (value == \"BFB\")\n return GCODE_FLAVOR_BFB;\n else if (value == \"MACH3\")\n return GCODE_FLAVOR_MACH3;\n else if (value == \"RepRap (Volumatric)\")\n return GCODE_FLAVOR_REPRAP_VOLUMATRIC;\n return GCODE_FLAVOR_REPRAP;\n}\n\nEFillMethod SettingsBase::getSettingAsFillMethod(std::string key)\n{\n std::string value = getSettingString(key);\n if (value == \"Lines\")\n return Fill_Lines;\n if (value == \"Grid\")\n return Fill_Grid;\n if (value == \"Triangles\")\n return Fill_Triangles;\n if (value == \"Concentric\")\n return Fill_Concentric;\n if (value == \"ZigZag\")\n return Fill_ZigZag;\n return Fill_None;\n}\n\nEPlatformAdhesion SettingsBase::getSettingAsPlatformAdhesion(std::string key)\n{\n std::string value = getSettingString(key);\n if (value == \"Brim\")\n return Adhesion_Brim;\n if (value == \"Raft\")\n return Adhesion_Raft;\n return Adhesion_None;\n}\n\nESupportType SettingsBase::getSettingAsSupportType(std::string key)\n{\n std::string value = getSettingString(key);\n if (value == \"Everywhere\")\n return Support_Everywhere;\n if (value == \"Touching Buildplate\")\n return Support_PlatformOnly;\n return Support_None;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/\/\n\/\/\/ @file test.cpp\n\/\/\/ @brief bool soe::test(); runs sieving tests to ensure that\n\/\/\/ ParallelPrimeSieve objects produce correct results.\n\/\/\/\n\/\/\/ Copyright (C) 2013 Kim Walisch, <kim.walisch@gmail.com>\n\/\/\/\n\/\/\/ This file is distributed under the BSD License. See the COPYING\n\/\/\/ file in the top level directory.\n\/\/\/\n\n#include <primesieve\/soe\/ParallelPrimeSieve.h>\n\n#include <iostream>\n#include <iomanip>\n#include <exception>\n#include <stdexcept>\n#include <algorithm>\n#include <cstdlib>\n#include <ctime>\n#include <stdint.h>\n\nusing namespace std;\n\nnamespace soe {\n\n\/\/\/ Correct values to compare with test results\nconst unsigned int primeCounts[19] =\n{\n 4, \/\/ pi(10^1)\n 25, \/\/ pi(10^2)\n 168, \/\/ pi(10^3)\n 1229, \/\/ pi(10^4)\n 9592, \/\/ pi(10^5)\n 78498, \/\/ pi(10^6)\n 664579, \/\/ pi(10^7)\n 5761455, \/\/ pi(10^8)\n 50847534, \/\/ pi(10^9)\n 455052511, \/\/ pi(10^10)\n 155428406, \/\/ pi[10^12, 10^12+2^32]\n 143482916, \/\/ pi[10^13, 10^13+2^32]\n 133235063, \/\/ pi[10^14, 10^14+2^32]\n 124350420, \/\/ pi[10^15, 10^15+2^32]\n 116578809, \/\/ pi[10^16, 10^16+2^32]\n 109726486, \/\/ pi[10^17, 10^17+2^32]\n 103626726, \/\/ pi[10^18, 10^18+2^32]\n 98169972, \/\/ pi[10^19, 10^19+2^32]\n 2895317534U \/\/ pi[10^15, 10^15+10^11]\n};\n\n\/\/\/ Keeps the memory usage below 1GB\nconst int maxThreads[8] = { 32, 32, 32, 32, 32, 8, 4, 1 };\n\nuint64_t ipow(uint64_t x, int n)\n{\n uint64_t result = 1;\n while (n != 0)\n {\n if ((n & 1) != 0)\n {\n result *= x;\n n -= 1;\n }\n x *= x;\n n \/= 2;\n }\n return result;\n}\n\n\/\/\/ Get a random 64-bit integer < limit\nuint64_t getRand64(uint64_t limit)\n{\n uint64_t rand64 = 0;\n for (int i = 0; i < 4; i++)\n rand64 = rand() % (1 << 16) + (rand64 << (i * 16));\n return rand64 % limit;\n}\n\nvoid check(bool isCorrect)\n{\n cout << (isCorrect ? \"OK\" : \"ERROR\") << endl;\n if (!isCorrect)\n throw runtime_error(\"test failed!\");\n}\n\n\/\/\/ Count the primes up to 10^10\nvoid testPix()\n{\n cout << \"pi(x) : Prime-counting function test\" << endl;\n ParallelPrimeSieve pps;\n pps.setStart(0);\n pps.setStop(0);\n uint64_t primeCount = 0;\n\n \/\/ pi(x) with x = 10^i for i = 1 to 10\n for (int i = 1; i <= 10; i++)\n {\n primeCount += pps.countPrimes(pps.getStop() + 1, ipow(10, i));\n cout << \"pi(10^\" << i << (i < 10 ? \") = \" : \") = \") << setw(12) << primeCount;\n check(primeCount == primeCounts[i - 1]);\n }\n cout << endl;\n}\n\n\/\/\/ Count the primes within [10^i, 10^i+2^32] for i = 12 to 19\nvoid testBigPrimes()\n{\n ParallelPrimeSieve pps;\n pps.setFlags(pps.COUNT_PRIMES | pps.PRINT_STATUS);\n\n for (int i = 12; i <= 19; i++)\n {\n cout << \"Sieving the primes within [10^\" << i << \", 10^\" << i << \"+2^32]\" << endl;\n pps.setStart(ipow(10, i));\n pps.setStop(pps.getStart() + ipow(2, 32));\n pps.setNumThreads(min(pps.getNumThreads(), maxThreads[i - 12]));\n pps.sieve();\n cout << \"\\rPrime count: \" << setw(11) << pps.getPrimeCount();\n check(pps.getPrimeCount() == primeCounts[i - 2]);\n }\n cout << endl;\n}\n\n\/\/\/ Sieve about 200 small random intervals until the interval\n\/\/\/ [10^15, 10^15+10^11] has been completed.\n\/\/\/\nvoid testRandomIntervals()\n{\n cout << \"Sieving the primes within [10^15, 10^15+10^11] randomly\" << endl;\n uint64_t maxInterval = ipow(10, 9);\n uint64_t lowerBound = ipow(10, 15);\n uint64_t upperBound = lowerBound + ipow(10, 11);\n uint64_t primeCount = 0;\n srand(static_cast<unsigned int>(time(0)));\n ParallelPrimeSieve pps;\n pps.setStart(lowerBound - 1);\n pps.setStop(lowerBound - 1);\n\n while (pps.getStop() < upperBound)\n {\n pps.setStart(pps.getStop() + 1);\n pps.setStop(min(pps.getStart() + getRand64(maxInterval), upperBound));\n pps.setSieveSize(1 << (rand() % 12));\n pps.sieve();\n primeCount += pps.getPrimeCount();\n cout << \"\\rRemaining chunk: \"\n << \"\\rRemaining chunk: \"\n << upperBound - pps.getStop() << flush;\n }\n cout << endl << \"Prime count: \" << setw(11) << primeCount;\n check(primeCount == primeCounts[18]);\n cout << endl;\n}\n\n\/\/\/ Run various sieving tests to ensure that ParallelPrimeSieve\n\/\/\/ (and PrimeSieve) objects produce correct results.\n\/\/\/ The tests use up to 1 GB of memory and take about 3 minutes to\n\/\/\/ complete on a dual core CPU from 2011.\n\/\/\/ @return true If no error occurred else false.\n\/\/\/\nbool test()\n{\n cout << left;\n try\n {\n testPix();\n testBigPrimes();\n testRandomIntervals();\n }\n catch (exception& e)\n {\n cerr << endl << \"Error: \" << e.what() << endl;\n return false;\n }\n cout << \"All tests passed successfully!\" << endl;\n return true;\n}\n\n} \/\/ end namespace\n<commit_msg>Comment<commit_after>\/\/\/\n\/\/\/ @file test.cpp\n\/\/\/ @brief bool soe::test(); runs prime sieving tests to ensure that\n\/\/\/ ParallelPrimeSieve objects produce correct results.\n\/\/\/\n\/\/\/ Copyright (C) 2013 Kim Walisch, <kim.walisch@gmail.com>\n\/\/\/\n\/\/\/ This file is distributed under the BSD License. See the COPYING\n\/\/\/ file in the top level directory.\n\/\/\/\n\n#include <primesieve\/soe\/ParallelPrimeSieve.h>\n\n#include <iostream>\n#include <iomanip>\n#include <exception>\n#include <stdexcept>\n#include <algorithm>\n#include <cstdlib>\n#include <ctime>\n#include <stdint.h>\n\nusing namespace std;\n\nnamespace soe {\n\n\/\/\/ Correct values to compare with test results\nconst unsigned int primeCounts[19] =\n{\n 4, \/\/ pi(10^1)\n 25, \/\/ pi(10^2)\n 168, \/\/ pi(10^3)\n 1229, \/\/ pi(10^4)\n 9592, \/\/ pi(10^5)\n 78498, \/\/ pi(10^6)\n 664579, \/\/ pi(10^7)\n 5761455, \/\/ pi(10^8)\n 50847534, \/\/ pi(10^9)\n 455052511, \/\/ pi(10^10)\n 155428406, \/\/ pi[10^12, 10^12+2^32]\n 143482916, \/\/ pi[10^13, 10^13+2^32]\n 133235063, \/\/ pi[10^14, 10^14+2^32]\n 124350420, \/\/ pi[10^15, 10^15+2^32]\n 116578809, \/\/ pi[10^16, 10^16+2^32]\n 109726486, \/\/ pi[10^17, 10^17+2^32]\n 103626726, \/\/ pi[10^18, 10^18+2^32]\n 98169972, \/\/ pi[10^19, 10^19+2^32]\n 2895317534U \/\/ pi[10^15, 10^15+10^11]\n};\n\n\/\/\/ Keeps the memory usage below 1GB\nconst int maxThreads[8] = { 32, 32, 32, 32, 32, 8, 4, 1 };\n\nuint64_t ipow(uint64_t x, int n)\n{\n uint64_t result = 1;\n while (n != 0)\n {\n if ((n & 1) != 0)\n {\n result *= x;\n n -= 1;\n }\n x *= x;\n n \/= 2;\n }\n return result;\n}\n\n\/\/\/ Get a random 64-bit integer < limit\nuint64_t getRand64(uint64_t limit)\n{\n uint64_t rand64 = 0;\n for (int i = 0; i < 4; i++)\n rand64 = rand() % (1 << 16) + (rand64 << (i * 16));\n return rand64 % limit;\n}\n\nvoid check(bool isCorrect)\n{\n cout << (isCorrect ? \"OK\" : \"ERROR\") << endl;\n if (!isCorrect)\n throw runtime_error(\"test failed!\");\n}\n\n\/\/\/ Count the primes up to 10^10\nvoid testPix()\n{\n cout << \"pi(x) : Prime-counting function test\" << endl;\n ParallelPrimeSieve pps;\n pps.setStart(0);\n pps.setStop(0);\n uint64_t primeCount = 0;\n\n \/\/ pi(x) with x = 10^i for i = 1 to 10\n for (int i = 1; i <= 10; i++)\n {\n primeCount += pps.countPrimes(pps.getStop() + 1, ipow(10, i));\n cout << \"pi(10^\" << i << (i < 10 ? \") = \" : \") = \") << setw(12) << primeCount;\n check(primeCount == primeCounts[i - 1]);\n }\n cout << endl;\n}\n\n\/\/\/ Count the primes within [10^i, 10^i+2^32] for i = 12 to 19\nvoid testBigPrimes()\n{\n ParallelPrimeSieve pps;\n pps.setFlags(pps.COUNT_PRIMES | pps.PRINT_STATUS);\n\n for (int i = 12; i <= 19; i++)\n {\n cout << \"Sieving the primes within [10^\" << i << \", 10^\" << i << \"+2^32]\" << endl;\n pps.setStart(ipow(10, i));\n pps.setStop(pps.getStart() + ipow(2, 32));\n pps.setNumThreads(min(pps.getNumThreads(), maxThreads[i - 12]));\n pps.sieve();\n cout << \"\\rPrime count: \" << setw(11) << pps.getPrimeCount();\n check(pps.getPrimeCount() == primeCounts[i - 2]);\n }\n cout << endl;\n}\n\n\/\/\/ Sieve about 200 small random intervals until the interval\n\/\/\/ [10^15, 10^15+10^11] has been completed.\n\/\/\/\nvoid testRandomIntervals()\n{\n cout << \"Sieving the primes within [10^15, 10^15+10^11] randomly\" << endl;\n uint64_t maxInterval = ipow(10, 9);\n uint64_t lowerBound = ipow(10, 15);\n uint64_t upperBound = lowerBound + ipow(10, 11);\n uint64_t primeCount = 0;\n srand(static_cast<unsigned int>(time(0)));\n ParallelPrimeSieve pps;\n pps.setStart(lowerBound - 1);\n pps.setStop(lowerBound - 1);\n\n while (pps.getStop() < upperBound)\n {\n pps.setStart(pps.getStop() + 1);\n pps.setStop(min(pps.getStart() + getRand64(maxInterval), upperBound));\n pps.setSieveSize(1 << (rand() % 12));\n pps.sieve();\n primeCount += pps.getPrimeCount();\n cout << \"\\rRemaining chunk: \"\n << \"\\rRemaining chunk: \"\n << upperBound - pps.getStop() << flush;\n }\n cout << endl << \"Prime count: \" << setw(11) << primeCount;\n check(primeCount == primeCounts[18]);\n cout << endl;\n}\n\n\/\/\/ Run various sieving tests to ensure that ParallelPrimeSieve\n\/\/\/ (and PrimeSieve) objects produce correct results.\n\/\/\/ The tests use up to 1 gigabyte of memory and take about\n\/\/\/ 1 minute to complete on a quad core CPU from 2013.\n\/\/\/ @return true If no error occurred else false.\n\/\/\/\nbool test()\n{\n cout << left;\n try\n {\n testPix();\n testBigPrimes();\n testRandomIntervals();\n }\n catch (exception& e)\n {\n cerr << endl << \"Error: \" << e.what() << endl;\n return false;\n }\n cout << \"All tests passed successfully!\" << endl;\n return true;\n}\n\n} \/\/ end namespace\n<|endoftext|>"} {"text":"<commit_before>\/\/\/\\file sourcery.cpp\n\/\/\/Utility program used for c-string dumping files.\n#undef DEBUG\n#define DEBUG -1\n#include <stdint.h>\n#include <string.h>\n#include <unistd.h>\n#include <iomanip>\n#include <iostream>\n#include <fstream>\n#include <string>\n#include \"..\/lib\/url.h\"\n#include \"..\/lib\/url.cpp\"\n#include \"..\/lib\/encode.h\"\n#include \"..\/lib\/encode.cpp\"\n\nstd::string getContents(const char * fileName){\n std::ifstream inFile(fileName);\n std::string fullText;\n if (inFile){\n std::ostringstream contents;\n contents << inFile.rdbuf();\n inFile.close();\n return contents.str();\n }\n return \"\";\n}\n\n\nint main(int argc, char* argv[]){\n\n if (argc < 4) {\n std::cerr << \"Usage: \" << argv[0] << \" <inputFile> <variableName> <outputFile> [<splittext>]\" << std::endl;\n return 42;\n }\n const char * splitText = 0;\n if (argc >= 5){splitText = argv[4];}\n\n char workDir[512];\n getcwd(workDir, 512);\n HTTP::URL inUri(std::string(\"file:\/\/\") + workDir + \"\/\");\n inUri = inUri.link(argv[1]);\n\n \/\/Read the entire first argument into a string buffer\n std::string fullText = getContents(inUri.getFilePath().c_str());\n \n \/\/replace every <script src=\"*\"><\/script> with the contents of the file '*'\n while (fullText.find(\"<script src=\\\"\") != std::string::npos){\n size_t locStart = fullText.find(\"<script src=\\\"\");\n size_t locEnd = fullText.find(\"\\\"><\/script>\", locStart);\n \/\/Assume we should abort if the strlen of the filename is > 230 chars\n if (locEnd - locStart >= 230){break;}\n HTTP::URL fileName = inUri.link(fullText.substr(locStart+13, locEnd-locStart-13));\n std::string subText = getContents(fileName.getFilePath().c_str());\n fullText = fullText.substr(0, locStart) + \"<script>\" + subText + fullText.substr(locEnd+2);\n }\n\n \/\/replace every <link rel=\"stylesheet\" href=\"*\"> with the contents of the file '*'\n while (fullText.find(\"<link rel=\\\"stylesheet\\\" href=\\\"\") != std::string::npos){\n size_t locStart = fullText.find(\"<link rel=\\\"stylesheet\\\" href=\\\"\");\n size_t locEnd = fullText.find(\"\\\">\", locStart);\n \/\/Assume we should abort if the strlen of the filename is > 230 chars\n if (locEnd - locStart >= 230){break;}\n HTTP::URL fileName = inUri.link(fullText.substr(locStart+29, locEnd-locStart-29));\n std::string subText = getContents(fileName.getFilePath().c_str());\n fullText = fullText.substr(0, locStart) + \"<style>\" + subText + \"<\/style>\" + fullText.substr(locEnd+2);\n }\n\n size_t splitPoint = std::string::npos;\n size_t splitLen = 0;\n if (splitText){\n splitPoint = fullText.find(splitText);\n if (splitPoint != std::string::npos){\n splitLen = strlen(splitText);\n }\n }\n\n std::ofstream tmp(argv[3]);\n \/\/begin the first line\n if (!splitLen){\n tmp << \"const char *\" << argv[2] << \" = \" << std::endl << \" \\\"\";\n }else{\n tmp << \"const char *\" << argv[2] << \"_prefix = \" << std::endl << \" \\\"\";\n }\n uint32_t i = 0; \/\/Current line byte counter\n uint32_t total = 0; \/\/Finished lines so far byte counter\n bool sawQ = false;\n for (size_t pos = 0; pos < fullText.size(); ++pos){\n if (pos == splitPoint){\n tmp << \"\\\";\" << std::endl << \"uint32_t \" << argv[2] << \"_prefix_len = \" << i + total << \";\" << std::endl;\n tmp << \"const char *\" << argv[2] << \"_suffix = \" << std::endl << \" \\\"\";\n i = 0;\n total = 0;\n sawQ = false;\n pos += splitLen;\n }\n unsigned char thisChar = fullText.at(pos);\n switch (thisChar){\n \/\/Filter special characters.\n case '\\n': tmp << \"\\\\n\"; break;\n case '\\r': tmp << \"\\\\r\"; break;\n case '\\t': tmp << \"\\\\t\"; break;\n case '\\\\': tmp << \"\\\\\\\\\"; break;\n case '\\\"': tmp << \"\\\\\\\"\"; break;\n case '?':\n if (sawQ){tmp << \"\\\"\\\"\";}\n tmp << \"?\";\n sawQ = true;\n break;\n default:\n if (thisChar < 32 || thisChar > 126){\n \/\/Convert to octal.\n tmp << '\\\\' << std::oct << std::setw(3) << std::setfill('0') << (unsigned int)thisChar << std::dec;\n }else{\n tmp << thisChar;\n }\n sawQ = false;\n }\n ++i;\n \/\/ We print 80 bytes per line, regardless of special characters\n \/\/ (Mostly because calculating this correctly would double the lines of code for this utility -_-)\n if (i >= 80){\n tmp << \"\\\" \\\\\" << std::endl << \" \\\"\";\n total += i;\n i = 0;\n }\n }\n \/\/end the last line, plus length variable\n tmp << \"\\\";\" << std::endl << \"uint32_t \" << argv[2] << (splitLen?\"_suffix\":\"\") << \"_len = \" << i + total << \";\" << std::endl;\n tmp.close();\n return 0;\n}\n\n<commit_msg>Fixed sourcery compile<commit_after>\/\/\/\\file sourcery.cpp\n\/\/\/Utility program used for c-string dumping files.\n#undef DEBUG\n#define DEBUG -1\n#include <stdint.h>\n#include <string.h>\n#include <unistd.h>\n#include <iomanip>\n#include <iostream>\n#include <fstream>\n#include <sstream>\n#include <string>\n#include \"..\/lib\/url.h\"\n#include \"..\/lib\/url.cpp\"\n#include \"..\/lib\/encode.h\"\n#include \"..\/lib\/encode.cpp\"\n\nstd::string getContents(const char * fileName){\n std::ifstream inFile(fileName);\n std::string fullText;\n if (inFile){\n std::stringstream contents;\n contents << inFile.rdbuf();\n inFile.close();\n return contents.str();\n }\n return \"\";\n}\n\n\nint main(int argc, char* argv[]){\n\n if (argc < 4) {\n std::cerr << \"Usage: \" << argv[0] << \" <inputFile> <variableName> <outputFile> [<splittext>]\" << std::endl;\n return 42;\n }\n const char * splitText = 0;\n if (argc >= 5){splitText = argv[4];}\n\n char workDir[512];\n getcwd(workDir, 512);\n HTTP::URL inUri(std::string(\"file:\/\/\") + workDir + \"\/\");\n inUri = inUri.link(argv[1]);\n\n \/\/Read the entire first argument into a string buffer\n std::string fullText = getContents(inUri.getFilePath().c_str());\n \n \/\/replace every <script src=\"*\"><\/script> with the contents of the file '*'\n while (fullText.find(\"<script src=\\\"\") != std::string::npos){\n size_t locStart = fullText.find(\"<script src=\\\"\");\n size_t locEnd = fullText.find(\"\\\"><\/script>\", locStart);\n \/\/Assume we should abort if the strlen of the filename is > 230 chars\n if (locEnd - locStart >= 230){break;}\n HTTP::URL fileName = inUri.link(fullText.substr(locStart+13, locEnd-locStart-13));\n std::string subText = getContents(fileName.getFilePath().c_str());\n fullText = fullText.substr(0, locStart) + \"<script>\" + subText + fullText.substr(locEnd+2);\n }\n\n \/\/replace every <link rel=\"stylesheet\" href=\"*\"> with the contents of the file '*'\n while (fullText.find(\"<link rel=\\\"stylesheet\\\" href=\\\"\") != std::string::npos){\n size_t locStart = fullText.find(\"<link rel=\\\"stylesheet\\\" href=\\\"\");\n size_t locEnd = fullText.find(\"\\\">\", locStart);\n \/\/Assume we should abort if the strlen of the filename is > 230 chars\n if (locEnd - locStart >= 230){break;}\n HTTP::URL fileName = inUri.link(fullText.substr(locStart+29, locEnd-locStart-29));\n std::string subText = getContents(fileName.getFilePath().c_str());\n fullText = fullText.substr(0, locStart) + \"<style>\" + subText + \"<\/style>\" + fullText.substr(locEnd+2);\n }\n\n size_t splitPoint = std::string::npos;\n size_t splitLen = 0;\n if (splitText){\n splitPoint = fullText.find(splitText);\n if (splitPoint != std::string::npos){\n splitLen = strlen(splitText);\n }\n }\n\n std::ofstream tmp(argv[3]);\n \/\/begin the first line\n if (!splitLen){\n tmp << \"const char *\" << argv[2] << \" = \" << std::endl << \" \\\"\";\n }else{\n tmp << \"const char *\" << argv[2] << \"_prefix = \" << std::endl << \" \\\"\";\n }\n uint32_t i = 0; \/\/Current line byte counter\n uint32_t total = 0; \/\/Finished lines so far byte counter\n bool sawQ = false;\n for (size_t pos = 0; pos < fullText.size(); ++pos){\n if (pos == splitPoint){\n tmp << \"\\\";\" << std::endl << \"uint32_t \" << argv[2] << \"_prefix_len = \" << i + total << \";\" << std::endl;\n tmp << \"const char *\" << argv[2] << \"_suffix = \" << std::endl << \" \\\"\";\n i = 0;\n total = 0;\n sawQ = false;\n pos += splitLen;\n }\n unsigned char thisChar = fullText.at(pos);\n switch (thisChar){\n \/\/Filter special characters.\n case '\\n': tmp << \"\\\\n\"; break;\n case '\\r': tmp << \"\\\\r\"; break;\n case '\\t': tmp << \"\\\\t\"; break;\n case '\\\\': tmp << \"\\\\\\\\\"; break;\n case '\\\"': tmp << \"\\\\\\\"\"; break;\n case '?':\n if (sawQ){tmp << \"\\\"\\\"\";}\n tmp << \"?\";\n sawQ = true;\n break;\n default:\n if (thisChar < 32 || thisChar > 126){\n \/\/Convert to octal.\n tmp << '\\\\' << std::oct << std::setw(3) << std::setfill('0') << (unsigned int)thisChar << std::dec;\n }else{\n tmp << thisChar;\n }\n sawQ = false;\n }\n ++i;\n \/\/ We print 80 bytes per line, regardless of special characters\n \/\/ (Mostly because calculating this correctly would double the lines of code for this utility -_-)\n if (i >= 80){\n tmp << \"\\\" \\\\\" << std::endl << \" \\\"\";\n total += i;\n i = 0;\n }\n }\n \/\/end the last line, plus length variable\n tmp << \"\\\";\" << std::endl << \"uint32_t \" << argv[2] << (splitLen?\"_suffix\":\"\") << \"_len = \" << i + total << \";\" << std::endl;\n tmp.close();\n return 0;\n}\n\n<|endoftext|>"} {"text":"<commit_before>#include <ostream>\r\n#include <string>\r\n#include <cassert>\r\n\r\n#include \"card.h\"\r\n\r\nusing namespace DNRY;\r\n\r\nCards::Card::Card(const Suit& suit, const Value& value) {\r\n s = suit;\r\n v = value;\r\n}\r\n\r\nCards::Suit Cards::Card::suit() const {\r\n return s;\r\n}\r\n\r\nCards::Value Cards::Card::value() const {\r\n return v;\r\n}\r\n\r\nstd::string Cards::make_string(Suit s) {\r\n#ifdef _WIN32\r\n \/\/ workaround for VS2013's Windows-1252 code page format and lack\r\n \/\/ of u8 string literals \r\n const auto club = \"C\";\r\n const auto diamond = \"D\";\r\n const auto heart = \"H\";\r\n const auto spade = \"S\";\r\n#else\r\n const auto club = u8\"♣\";\r\n const auto diamond = u8\"♦\";\r\n const auto heart = u8\"♥\";\r\n const auto spade = u8\"♠\";\r\n#endif\r\n switch (s) {\r\n case Cards::Suit::club: {\r\n return std::string(club);\r\n }\r\n case Cards::Suit::diamond: {\r\n return std::string(diamond);\r\n }\r\n case Cards::Suit::heart: {\r\n return std::string(heart);\r\n }\r\n case Cards::Suit::spade: {\r\n return std::string(spade);\r\n }\r\n default: {\r\n assert(false);\r\n return \"\";\r\n }\r\n }\r\n}\r\n\r\nstd::string Cards::make_string(Value v) {\r\n switch (v) {\r\n case Cards::Value::ace:\r\n return \"A\";\r\n case Cards::Value::two:\r\n return \"2\";\r\n case Cards::Value::three:\r\n return \"3\";\r\n case Cards::Value::four:\r\n return \"4\";\r\n case Cards::Value::five:\r\n return \"5\";\r\n case Cards::Value::six:\r\n return \"6\";\r\n case Cards::Value::seven:\r\n return \"7\";\r\n case Cards::Value::eight:\r\n return \"8\";\r\n case Cards::Value::nine:\r\n return \"9\";\r\n case Cards::Value::ten:\r\n return \"10\";\r\n case Cards::Value::jack:\r\n return \"J\";\r\n case Cards::Value::queen:\r\n return \"Q\";\r\n case Cards::Value::king:\r\n return \"K\";\r\n default: {\r\n assert(false);\r\n return \"\";\r\n }\r\n }\r\n}\r\n\r\nstd::ostream& Cards::operator<<(std::ostream& os, const Cards::Card& c) {\r\n os << Cards::make_string(c.value()) << Cards::make_string(c.suit());\r\n return os;\r\n}\r\n<commit_msg>Add initializer list<commit_after>#include <ostream>\r\n#include <string>\r\n#include <cassert>\r\n\r\n#include \"card.h\"\r\n\r\nusing namespace DNRY;\r\n\r\nCards::Card::Card(const Suit& suit, const Value& value) : s{suit}, v{value} {}\r\n\r\nCards::Suit Cards::Card::suit() const {\r\n return s;\r\n}\r\n\r\nCards::Value Cards::Card::value() const {\r\n return v;\r\n}\r\n\r\nstd::string Cards::make_string(Suit s) {\r\n#ifdef _WIN32\r\n \/\/ workaround for VS2013's Windows-1252 code page format and lack\r\n \/\/ of u8 string literals \r\n const auto club = \"C\";\r\n const auto diamond = \"D\";\r\n const auto heart = \"H\";\r\n const auto spade = \"S\";\r\n#else\r\n const auto club = u8\"♣\";\r\n const auto diamond = u8\"♦\";\r\n const auto heart = u8\"♥\";\r\n const auto spade = u8\"♠\";\r\n#endif\r\n switch (s) {\r\n case Cards::Suit::club: {\r\n return std::string(club);\r\n }\r\n case Cards::Suit::diamond: {\r\n return std::string(diamond);\r\n }\r\n case Cards::Suit::heart: {\r\n return std::string(heart);\r\n }\r\n case Cards::Suit::spade: {\r\n return std::string(spade);\r\n }\r\n default: {\r\n assert(false);\r\n return \"\";\r\n }\r\n }\r\n}\r\n\r\nstd::string Cards::make_string(Value v) {\r\n switch (v) {\r\n case Cards::Value::ace:\r\n return \"A\";\r\n case Cards::Value::two:\r\n return \"2\";\r\n case Cards::Value::three:\r\n return \"3\";\r\n case Cards::Value::four:\r\n return \"4\";\r\n case Cards::Value::five:\r\n return \"5\";\r\n case Cards::Value::six:\r\n return \"6\";\r\n case Cards::Value::seven:\r\n return \"7\";\r\n case Cards::Value::eight:\r\n return \"8\";\r\n case Cards::Value::nine:\r\n return \"9\";\r\n case Cards::Value::ten:\r\n return \"10\";\r\n case Cards::Value::jack:\r\n return \"J\";\r\n case Cards::Value::queen:\r\n return \"Q\";\r\n case Cards::Value::king:\r\n return \"K\";\r\n default: {\r\n assert(false);\r\n return \"\";\r\n }\r\n }\r\n}\r\n\r\nstd::ostream& Cards::operator<<(std::ostream& os, const Cards::Card& c) {\r\n os << Cards::make_string(c.value()) << Cards::make_string(c.suit());\r\n return os;\r\n}\r\n<|endoftext|>"} {"text":"<commit_before>#include \"node_info.h\"\n\n#include <cstddef>\n#include <cstdlib>\n#include <cstring>\n\n#include \"sixtracklib\/common\/definitions.h\"\n#include \"sixtracklib\/common\/control\/definitions.h\"\n#include \"sixtracklib\/common\/control\/node_info.hpp\"\n\n\n#if !defined( _GPUCODE )\n\nnamespace st = SIXTRL_CXX_NAMESPACE;\n\nvoid NS(NodeInfo_delete)( ::NS(NodeInfoBase)* SIXTRL_RESTRICT node_info )\n{\n if( node_info != nullptr ) delete node_info;\n}\n\n\/* ------------------------------------------------------------------------- *\/\n\n::NS(NodeId) const* NS(NodeInfo_get_ptr_const_node_id)(\n SIXTRL_ARGPTR_DEC const ::NS(NodeInfoBase) *const SIXTRL_RESTRICT info )\n{\n return ( info != nullptr ) ? info->ptrNodeId() : nullptr;\n}\n\n::NS(NodeId)* NS(NodeInfo_get_ptr_node_id)(\n SIXTRL_ARGPTR_DEC ::NS(NodeInfoBase)* SIXTRL_RESTRICT info )\n{\n return ( info != nullptr ) ? info->ptrNodeId() : nullptr;\n}\n\n::NS(node_platform_id_t) NS(NodeInfo_get_platform_id)(\n SIXTRL_ARGPTR_DEC const ::NS(NodeInfoBase) *const SIXTRL_RESTRICT info )\n{\n return ( info != nullptr )\n ? info->platformId() : st::NODE_ILLEGAL_PATFORM_ID;\n}\n\nvoid NS(NodeInfo_set_platform_id)(\n SIXTRL_ARGPTR_DEC ::NS(NodeInfoBase)* SIXTRL_RESTRICT info,\n ::NS(node_platform_id_t) const platform_id )\n{\n if( info != nullptr ) info->setPlatformId( platform_id );\n}\n\n::NS(node_device_id_t) NS(NodeInfo_get_device_id)(\n SIXTRL_ARGPTR_DEC const ::NS(NodeInfoBase) *const SIXTRL_RESTRICT info )\n{\n return ( info != nullptr )\n ? info->deviceId() : st::NODE_ILLEGAL_DEVICE_ID;\n}\n\nvoid NS(NodeInfo_set_device_id)(\n SIXTRL_ARGPTR_DEC ::NS(NodeInfoBase)* SIXTRL_RESTRICT info,\n ::NS(node_device_id_t) const device_id )\n{\n if( info != nullptr ) info->setDeviceId( device_id );\n}\n\nbool NS(NodeInfo_has_node_index)(\n SIXTRL_ARGPTR_DEC const ::NS(NodeInfoBase) *const SIXTRL_RESTRICT info )\n{\n return ( ( info != nullptr ) && ( info->hasNodeIndex() ) );\n}\n\n::NS(node_index_t) NS(NodeInfo_get_node_index)(\n SIXTRL_ARGPTR_DEC const ::NS(NodeInfoBase) *const SIXTRL_RESTRICT info )\n{\n return ( info != nullptr )\n ? info->nodeIndex() : st::NODE_UNDEFINED_INDEX;\n}\n\nvoid NS(NodeInfo_set_node_index)(\n SIXTRL_ARGPTR_DEC ::NS(NodeInfoBase)* SIXTRL_RESTRICT info,\n ::NS(node_index_t) node_index )\n{\n if( info != nullptr ) info->setNodeIndex( node_index );\n}\n\nbool NS(NodeInfo_is_default_node)(\n SIXTRL_ARGPTR_DEC const ::NS(NodeInfoBase) *const SIXTRL_RESTRICT info )\n{\n return ( ( info != nullptr ) && ( info->isDefaultNode() ) );\n}\n\nbool NS(NodeInfo_is_selected_node)(\n SIXTRL_ARGPTR_DEC const ::NS(NodeInfoBase) *const SIXTRL_RESTRICT info )\n{\n return ( ( info != nullptr ) && ( info->isSelectedNode() ) );\n}\n\nvoid NS(NodeInfo_set_is_default_node)(\n SIXTRL_ARGPTR_DEC ::NS(NodeInfoBase)* SIXTRL_RESTRICT info,\n bool const is_default )\n{\n if( info != nullptr ) info->setIsDefaultNode( is_default );\n}\n\nvoid NS(NodeInfo_set_is_selected_node)(\n SIXTRL_ARGPTR_DEC ::NS(NodeInfoBase)* SIXTRL_RESTRICT info,\n bool const is_selected )\n{\n if( info != nullptr ) info->setIsSelectedNode( is_selected );\n}\n\n\/* ------------------------------------------------------------------------- *\/\n\n::NS(arch_id_t) NS(NodeInfo_get_arch_id)(\n SIXTRL_ARGPTR_DEC const ::NS(NodeInfoBase) *const SIXTRL_RESTRICT info )\n{\n return ( info != nullptr ) ? info->archId() : ::NS(ARCHITECTURE_ILLEGAL);\n}\n\nbool NS(NodeInfo_has_arch_string)(\n SIXTRL_ARGPTR_DEC const ::NS(NodeInfoBase) *const SIXTRL_RESTRICT info )\n{\n return ( ( info != nullptr ) && ( info->hasArchStr() ) );\n}\n\nchar const* NS(NodeInfo_get_arch_string)(\n SIXTRL_ARGPTR_DEC const ::NS(NodeInfoBase) *const SIXTRL_RESTRICT info )\n{\n return ( info != nullptr ) ? info->ptrArchStr() : nullptr;\n}\n\n\/* ------------------------------------------------------------------------- *\/\n\nbool NS(NodeInfo_has_platform_name)(\n SIXTRL_ARGPTR_DEC const ::NS(NodeInfoBase) *const SIXTRL_RESTRICT info )\n{\n return ( ( info != nullptr ) && ( info->hasPlatformName() ) );\n}\n\nchar const* NS(NodeInfo_get_platform_name)(\n SIXTRL_ARGPTR_DEC const ::NS(NodeInfoBase) *const SIXTRL_RESTRICT info )\n{\n return ( info != nullptr ) ? info->ptrPlatformNameStr() : nullptr;\n}\n\nvoid NS(NodeInfo_set_platform_name)(\n SIXTRL_ARGPTR_DEC ::NS(NodeInfoBase)* SIXTRL_RESTRICT info,\n SIXTRL_ARGPTR_DEC const char *const SIXTRL_RESTRICT platform_name )\n{\n if( info != nullptr ) info->setPlatformName( platform_name );\n}\n\nbool NS(NodeInfo_has_device_name)(\n SIXTRL_ARGPTR_DEC const ::NS(NodeInfoBase) *const SIXTRL_RESTRICT info )\n{\n return ( ( info != nullptr ) && ( info->hasDeviceName() ) );\n}\n\nchar const* NS(NodeInfo_get_device_name)(\n SIXTRL_ARGPTR_DEC const ::NS(NodeInfoBase) *const SIXTRL_RESTRICT info )\n{\n return ( info != nullptr ) ? info->ptrDeviceNameStr() : nullptr;\n}\n\nvoid NS(NodeInfo_set_device_name)(\n SIXTRL_ARGPTR_DEC ::NS(NodeInfoBase)* SIXTRL_RESTRICT info,\n SIXTRL_ARGPTR_DEC const char *const SIXTRL_RESTRICT device_name )\n{\n if( info != nullptr ) info->setDeviceName( device_name );\n}\n\nbool NS(NodeInfo_has_description)(\n SIXTRL_ARGPTR_DEC const ::NS(NodeInfoBase) *const SIXTRL_RESTRICT info )\n{\n return ( ( info != nullptr ) && ( info->hasDescription() ) );\n}\n\nchar const* NS(NodeInfo_get_description)(\n SIXTRL_ARGPTR_DEC const ::NS(NodeInfoBase) *const SIXTRL_RESTRICT info )\n{\n return ( info != nullptr ) ? info->ptrDescriptionStr() : nullptr;\n}\n\nvoid NS(NodeInfo_set_description)(\n SIXTRL_ARGPTR_DEC ::NS(NodeInfoBase)* SIXTRL_RESTRICT info,\n SIXTRL_ARGPTR_DEC const char *const SIXTRL_RESTRICT description )\n{\n if( info != nullptr ) info->setPlatformName( description );\n}\n\n\/* ------------------------------------------------------------------------- *\/\n\nvoid NS(NodeInfo_print)( SIXTRL_ARGPTR_DEC const ::NS(NodeInfoBase) *const\n SIXTRL_RESTRICT info, ::FILE* SIXTRL_RESTRICT output )\n{\n if( ( info != nullptr ) && ( output != nullptr ) )\n {\n info->print( output );\n }\n}\n\nvoid NS(NodeInfo_print_out)(\n SIXTRL_ARGPTR_DEC const ::NS(NodeInfoBase) *const SIXTRL_RESTRICT info )\n{\n if( info != nullptr ) info->printOut();\n}\n\n\n::NS(arch_size_t) NS(NodeInfo_get_required_output_str_length)(\n SIXTRL_ARGPTR_DEC const ::NS(NodeInfoBase) *const SIXTRL_RESTRICT info )\n{\n return ( info != nullptr ) \n ? info->requiredOutStringLength() : ::NS(arch_size_t){ 0 }; \n}\n\nSIXTRL_EXTERN SIXTRL_HOST_FN NS(arch_status_t)\nNS(NodeInfo_convert_to_string)(\n SIXTRL_ARGPTR_DEC const NS(NodeInfoBase) *const SIXTRL_RESTRICT info, \n NS(arch_size_t) const out_string_capacity,\n char* SIXTRL_RESTRICT out_string )\n{\n return ( info != nullptr ) \n ? info->toString( out_string_capacity, out_string ) \n : st::ARCH_STATUS_GENERAL_FAILURE; \n}\n\n#endif \/* !defined( _GPUCODE ) *\/\n\n\/* end: sixtracklib\/common\/control\/node_info_c99.cpp *\/\n<commit_msg>common: cosmetic changes<commit_after>#include \"node_info.h\"\n\n#include <cstddef>\n#include <cstdlib>\n#include <cstring>\n\n#include \"sixtracklib\/common\/definitions.h\"\n#include \"sixtracklib\/common\/control\/definitions.h\"\n#include \"sixtracklib\/common\/control\/node_info.hpp\"\n\n\n#if !defined( _GPUCODE )\n\nnamespace st = SIXTRL_CXX_NAMESPACE;\n\nvoid NS(NodeInfo_delete)( ::NS(NodeInfoBase)* SIXTRL_RESTRICT node_info )\n{\n if( node_info != nullptr ) delete node_info;\n}\n\n\/* ------------------------------------------------------------------------- *\/\n\n::NS(NodeId) const* NS(NodeInfo_get_ptr_const_node_id)(\n SIXTRL_ARGPTR_DEC const ::NS(NodeInfoBase) *const SIXTRL_RESTRICT info )\n{\n return ( info != nullptr ) ? info->ptrNodeId() : nullptr;\n}\n\n::NS(NodeId)* NS(NodeInfo_get_ptr_node_id)(\n SIXTRL_ARGPTR_DEC ::NS(NodeInfoBase)* SIXTRL_RESTRICT info )\n{\n return ( info != nullptr ) ? info->ptrNodeId() : nullptr;\n}\n\n::NS(node_platform_id_t) NS(NodeInfo_get_platform_id)(\n SIXTRL_ARGPTR_DEC const ::NS(NodeInfoBase) *const SIXTRL_RESTRICT info )\n{\n return ( info != nullptr )\n ? info->platformId() : st::NODE_ILLEGAL_PATFORM_ID;\n}\n\nvoid NS(NodeInfo_set_platform_id)(\n SIXTRL_ARGPTR_DEC ::NS(NodeInfoBase)* SIXTRL_RESTRICT info,\n ::NS(node_platform_id_t) const platform_id )\n{\n if( info != nullptr ) info->setPlatformId( platform_id );\n}\n\n::NS(node_device_id_t) NS(NodeInfo_get_device_id)(\n SIXTRL_ARGPTR_DEC const ::NS(NodeInfoBase) *const SIXTRL_RESTRICT info )\n{\n return ( info != nullptr )\n ? info->deviceId() : st::NODE_ILLEGAL_DEVICE_ID;\n}\n\nvoid NS(NodeInfo_set_device_id)(\n SIXTRL_ARGPTR_DEC ::NS(NodeInfoBase)* SIXTRL_RESTRICT info,\n ::NS(node_device_id_t) const device_id )\n{\n if( info != nullptr ) info->setDeviceId( device_id );\n}\n\nbool NS(NodeInfo_has_node_index)(\n SIXTRL_ARGPTR_DEC const ::NS(NodeInfoBase) *const SIXTRL_RESTRICT info )\n{\n return ( ( info != nullptr ) && ( info->hasNodeIndex() ) );\n}\n\n::NS(node_index_t) NS(NodeInfo_get_node_index)(\n SIXTRL_ARGPTR_DEC const ::NS(NodeInfoBase) *const SIXTRL_RESTRICT info )\n{\n return ( info != nullptr )\n ? info->nodeIndex() : st::NODE_UNDEFINED_INDEX;\n}\n\nvoid NS(NodeInfo_set_node_index)(\n SIXTRL_ARGPTR_DEC ::NS(NodeInfoBase)* SIXTRL_RESTRICT info,\n ::NS(node_index_t) node_index )\n{\n if( info != nullptr ) info->setNodeIndex( node_index );\n}\n\nbool NS(NodeInfo_is_default_node)(\n SIXTRL_ARGPTR_DEC const ::NS(NodeInfoBase) *const SIXTRL_RESTRICT info )\n{\n return ( ( info != nullptr ) && ( info->isDefaultNode() ) );\n}\n\nbool NS(NodeInfo_is_selected_node)(\n SIXTRL_ARGPTR_DEC const ::NS(NodeInfoBase) *const SIXTRL_RESTRICT info )\n{\n return ( ( info != nullptr ) && ( info->isSelectedNode() ) );\n}\n\nvoid NS(NodeInfo_set_is_default_node)(\n SIXTRL_ARGPTR_DEC ::NS(NodeInfoBase)* SIXTRL_RESTRICT info,\n bool const is_default )\n{\n if( info != nullptr ) info->setIsDefaultNode( is_default );\n}\n\nvoid NS(NodeInfo_set_is_selected_node)(\n SIXTRL_ARGPTR_DEC ::NS(NodeInfoBase)* SIXTRL_RESTRICT info,\n bool const is_selected )\n{\n if( info != nullptr ) info->setIsSelectedNode( is_selected );\n}\n\n\/* ------------------------------------------------------------------------- *\/\n\n::NS(arch_id_t) NS(NodeInfo_get_arch_id)(\n SIXTRL_ARGPTR_DEC const ::NS(NodeInfoBase) *const SIXTRL_RESTRICT info )\n{\n return ( info != nullptr ) ? info->archId() : st::ARCHITECTURE_ILLEGAL;\n}\n\nbool NS(NodeInfo_has_arch_string)(\n SIXTRL_ARGPTR_DEC const ::NS(NodeInfoBase) *const SIXTRL_RESTRICT info )\n{\n return ( ( info != nullptr ) && ( info->hasArchStr() ) );\n}\n\nchar const* NS(NodeInfo_get_arch_string)(\n SIXTRL_ARGPTR_DEC const ::NS(NodeInfoBase) *const SIXTRL_RESTRICT info )\n{\n return ( info != nullptr ) ? info->ptrArchStr() : nullptr;\n}\n\n\/* ------------------------------------------------------------------------- *\/\n\nbool NS(NodeInfo_has_platform_name)(\n SIXTRL_ARGPTR_DEC const ::NS(NodeInfoBase) *const SIXTRL_RESTRICT info )\n{\n return ( ( info != nullptr ) && ( info->hasPlatformName() ) );\n}\n\nchar const* NS(NodeInfo_get_platform_name)(\n SIXTRL_ARGPTR_DEC const ::NS(NodeInfoBase) *const SIXTRL_RESTRICT info )\n{\n return ( info != nullptr ) ? info->ptrPlatformNameStr() : nullptr;\n}\n\nvoid NS(NodeInfo_set_platform_name)(\n SIXTRL_ARGPTR_DEC ::NS(NodeInfoBase)* SIXTRL_RESTRICT info,\n SIXTRL_ARGPTR_DEC const char *const SIXTRL_RESTRICT platform_name )\n{\n if( info != nullptr ) info->setPlatformName( platform_name );\n}\n\nbool NS(NodeInfo_has_device_name)(\n SIXTRL_ARGPTR_DEC const ::NS(NodeInfoBase) *const SIXTRL_RESTRICT info )\n{\n return ( ( info != nullptr ) && ( info->hasDeviceName() ) );\n}\n\nchar const* NS(NodeInfo_get_device_name)(\n SIXTRL_ARGPTR_DEC const ::NS(NodeInfoBase) *const SIXTRL_RESTRICT info )\n{\n return ( info != nullptr ) ? info->ptrDeviceNameStr() : nullptr;\n}\n\nvoid NS(NodeInfo_set_device_name)(\n SIXTRL_ARGPTR_DEC ::NS(NodeInfoBase)* SIXTRL_RESTRICT info,\n SIXTRL_ARGPTR_DEC const char *const SIXTRL_RESTRICT device_name )\n{\n if( info != nullptr ) info->setDeviceName( device_name );\n}\n\nbool NS(NodeInfo_has_description)(\n SIXTRL_ARGPTR_DEC const ::NS(NodeInfoBase) *const SIXTRL_RESTRICT info )\n{\n return ( ( info != nullptr ) && ( info->hasDescription() ) );\n}\n\nchar const* NS(NodeInfo_get_description)(\n SIXTRL_ARGPTR_DEC const ::NS(NodeInfoBase) *const SIXTRL_RESTRICT info )\n{\n return ( info != nullptr ) ? info->ptrDescriptionStr() : nullptr;\n}\n\nvoid NS(NodeInfo_set_description)(\n SIXTRL_ARGPTR_DEC ::NS(NodeInfoBase)* SIXTRL_RESTRICT info,\n SIXTRL_ARGPTR_DEC const char *const SIXTRL_RESTRICT description )\n{\n if( info != nullptr ) info->setPlatformName( description );\n}\n\n\/* ------------------------------------------------------------------------- *\/\n\nvoid NS(NodeInfo_print)( SIXTRL_ARGPTR_DEC const ::NS(NodeInfoBase) *const\n SIXTRL_RESTRICT info, ::FILE* SIXTRL_RESTRICT output )\n{\n if( ( info != nullptr ) && ( output != nullptr ) )\n {\n info->print( output );\n }\n}\n\nvoid NS(NodeInfo_print_out)(\n SIXTRL_ARGPTR_DEC const ::NS(NodeInfoBase) *const SIXTRL_RESTRICT info )\n{\n if( info != nullptr ) info->printOut();\n}\n\n\n::NS(arch_size_t) NS(NodeInfo_get_required_output_str_length)(\n SIXTRL_ARGPTR_DEC const ::NS(NodeInfoBase) *const SIXTRL_RESTRICT info )\n{\n return ( info != nullptr )\n ? info->requiredOutStringLength() : ::NS(arch_size_t){ 0 };\n}\n\nSIXTRL_EXTERN SIXTRL_HOST_FN NS(arch_status_t)\nNS(NodeInfo_convert_to_string)(\n SIXTRL_ARGPTR_DEC const NS(NodeInfoBase) *const SIXTRL_RESTRICT info,\n NS(arch_size_t) const out_string_capacity,\n char* SIXTRL_RESTRICT out_string )\n{\n return ( info != nullptr )\n ? info->toString( out_string_capacity, out_string )\n : st::ARCH_STATUS_GENERAL_FAILURE;\n}\n\n#endif \/* !defined( _GPUCODE ) *\/\n\n\/* end: sixtracklib\/common\/control\/node_info_c99.cpp *\/\n<|endoftext|>"} {"text":"<commit_before>\/\/ This file is part of Poseidon.\n\/\/ Copyleft 2022, LH_Mouse. All wrongs reserved.\n\n#include \"..\/precompiled.ipp\"\n#include \"timer_driver.hpp\"\n#include \"async_logger.hpp\"\n#include \"..\/core\/abstract_timer.hpp\"\n#include \"..\/utils.hpp\"\n#include <time.h>\n\nnamespace poseidon {\nnamespace {\n\nstruct Queued_Timer\n {\n weak_ptr<Abstract_Timer> timer;\n uint64_t serial;\n int64_t next;\n int64_t period;\n };\n\nstruct Timer_Comparator\n {\n bool\n operator()(const Queued_Timer& lhs, const Queued_Timer& rhs) noexcept\n { return lhs.next > rhs.next; }\n\n bool\n operator()(const Queued_Timer& lhs, int64_t rhs) noexcept\n { return lhs.next > rhs; }\n\n bool\n operator()(int64_t lhs, const Queued_Timer& rhs) noexcept\n { return lhs > rhs.next; }\n }\n constexpr timer_comparator;\n\nint64_t\ndo_monotonic_now() noexcept\n {\n ::timespec ts;\n ::clock_gettime(CLOCK_MONOTONIC, &ts);\n return ts.tv_sec * 1000 + (uint32_t) ts.tv_nsec \/ 1000000U;\n }\n\n} \/\/ namespace\n\nPOSEIDON_HIDDEN_STRUCT(Timer_Driver, Queued_Timer);\n\nTimer_Driver::\nTimer_Driver()\n {\n \/\/ Generate a random serial.\n this->m_serial = (uint64_t) do_monotonic_now();\n }\n\nTimer_Driver::\n~Timer_Driver()\n {\n }\n\nvoid\nTimer_Driver::\nthread_loop()\n {\n \/\/ Await an element.\n plain_mutex::unique_lock lock(this->m_pq_mutex);\n while(this->m_pq.empty())\n this->m_pq_avail.wait(lock);\n\n const int64_t now = do_monotonic_now();\n int64_t delta = this->m_pq.front().next - now;\n if(delta > 0) {\n POSEIDON_LOG_TRACE((\"Timer driver waiting: $1 millisecond(s) remaining\"), delta);\n this->m_pq_avail.wait_for(lock, delta);\n return;\n }\n ::std::pop_heap(this->m_pq.begin(), this->m_pq.end(), timer_comparator);\n auto elem = ::std::move(this->m_pq.back());\n this->m_pq.pop_back();\n\n auto timer = elem.timer.lock();\n if(!timer)\n return;\n else if(elem.serial != timer->m_serial)\n return;\n\n if(elem.period != 0) {\n \/\/ Update the next time point and insert the timer back.\n elem.next += elem.period;\n this->m_pq.emplace_back(::std::move(elem));\n ::std::push_heap(this->m_pq.begin(), this->m_pq.end(), timer_comparator);\n }\n lock.unlock();\n\n \/\/ Execute it.\n \/\/ Exceptions are ignored.\n POSEIDON_LOG_TRACE((\"Executing timer `$1` (class `$2`)\"), timer, typeid(*timer));\n timer->m_async_state.store(async_state_running);\n timer->m_count.xadd(1);\n\n try {\n timer->do_abstract_timer_on_tick(now);\n }\n catch(exception& stdex) {\n POSEIDON_LOG_WARN((\n \"Timer error: $1\",\n \"[exception class `$2`]\",\n \"[timer class `$3`]\"),\n stdex.what(), typeid(stdex), typeid(*timer));\n }\n\n timer->m_async_state.store(async_state_suspended);\n }\n\nvoid\nTimer_Driver::\ninsert(const shared_ptr<Abstract_Timer>& timer, int64_t delay, int64_t period)\n {\n \/\/ Validate arguments.\n if(!timer)\n POSEIDON_THROW((\"Null timer pointer not valid\"));\n\n if(delay < 0)\n POSEIDON_THROW((\"Negative time delay not valid: $1\"), delay);\n\n if(delay > INT32_MAX)\n POSEIDON_THROW((\"Time delay too large: $1\"), delay);\n\n if(period < 0)\n POSEIDON_THROW((\"Negative timer period not valid: $1\"), period);\n\n if(period > INT32_MAX)\n POSEIDON_THROW((\"Timer period too large: $1\"), period);\n\n \/\/ Calculate the end time point.\n Queued_Timer elem;\n elem.timer = timer;\n elem.next = do_monotonic_now() + delay;\n elem.period = period;\n\n \/\/ Insert the timer.\n plain_mutex::unique_lock lock(this->m_pq_mutex);\n elem.serial = ++ this->m_serial;\n timer->m_serial = elem.serial;\n this->m_pq.emplace_back(::std::move(elem));\n ::std::push_heap(this->m_pq.begin(), this->m_pq.end(), timer_comparator);\n this->m_pq_avail.notify_one();\n }\n\n} \/\/ namespace poseidon\n<commit_msg>timer_driver: Add comments<commit_after>\/\/ This file is part of Poseidon.\n\/\/ Copyleft 2022, LH_Mouse. All wrongs reserved.\n\n#include \"..\/precompiled.ipp\"\n#include \"timer_driver.hpp\"\n#include \"async_logger.hpp\"\n#include \"..\/core\/abstract_timer.hpp\"\n#include \"..\/utils.hpp\"\n#include <time.h>\n\nnamespace poseidon {\nnamespace {\n\nstruct Queued_Timer\n {\n weak_ptr<Abstract_Timer> timer;\n uint64_t serial;\n int64_t next;\n int64_t period;\n };\n\nstruct Timer_Comparator\n {\n \/\/ We have to build a minheap here.\n bool\n operator()(const Queued_Timer& lhs, const Queued_Timer& rhs) noexcept\n { return lhs.next > rhs.next; }\n\n bool\n operator()(const Queued_Timer& lhs, int64_t rhs) noexcept\n { return lhs.next > rhs; }\n\n bool\n operator()(int64_t lhs, const Queued_Timer& rhs) noexcept\n { return lhs > rhs.next; }\n }\n constexpr timer_comparator;\n\nint64_t\ndo_monotonic_now() noexcept\n {\n ::timespec ts;\n ::clock_gettime(CLOCK_MONOTONIC, &ts);\n return ts.tv_sec * 1000 + (uint32_t) ts.tv_nsec \/ 1000000U;\n }\n\n} \/\/ namespace\n\nPOSEIDON_HIDDEN_STRUCT(Timer_Driver, Queued_Timer);\n\nTimer_Driver::\nTimer_Driver()\n {\n \/\/ Generate a random serial.\n this->m_serial = (uint64_t) do_monotonic_now();\n }\n\nTimer_Driver::\n~Timer_Driver()\n {\n }\n\nvoid\nTimer_Driver::\nthread_loop()\n {\n \/\/ Await an element.\n plain_mutex::unique_lock lock(this->m_pq_mutex);\n while(this->m_pq.empty())\n this->m_pq_avail.wait(lock);\n\n const int64_t now = do_monotonic_now();\n int64_t delta = this->m_pq.front().next - now;\n if(delta > 0) {\n POSEIDON_LOG_TRACE((\"Timer driver waiting: $1 millisecond(s) remaining\"), delta);\n this->m_pq_avail.wait_for(lock, delta);\n return;\n }\n ::std::pop_heap(this->m_pq.begin(), this->m_pq.end(), timer_comparator);\n auto elem = ::std::move(this->m_pq.back());\n this->m_pq.pop_back();\n\n auto timer = elem.timer.lock();\n if(!timer)\n return;\n else if(elem.serial != timer->m_serial)\n return;\n\n if(elem.period != 0) {\n \/\/ Update the next time point and insert the timer back.\n elem.next += elem.period;\n this->m_pq.emplace_back(::std::move(elem));\n ::std::push_heap(this->m_pq.begin(), this->m_pq.end(), timer_comparator);\n }\n lock.unlock();\n\n \/\/ Execute it.\n \/\/ Exceptions are ignored.\n POSEIDON_LOG_TRACE((\"Executing timer `$1` (class `$2`)\"), timer, typeid(*timer));\n timer->m_async_state.store(async_state_running);\n timer->m_count.xadd(1);\n\n try {\n timer->do_abstract_timer_on_tick(now);\n }\n catch(exception& stdex) {\n POSEIDON_LOG_WARN((\n \"Timer error: $1\",\n \"[exception class `$2`]\",\n \"[timer class `$3`]\"),\n stdex.what(), typeid(stdex), typeid(*timer));\n }\n\n timer->m_async_state.store(async_state_suspended);\n }\n\nvoid\nTimer_Driver::\ninsert(const shared_ptr<Abstract_Timer>& timer, int64_t delay, int64_t period)\n {\n \/\/ Validate arguments.\n if(!timer)\n POSEIDON_THROW((\"Null timer pointer not valid\"));\n\n if(delay < 0)\n POSEIDON_THROW((\"Negative time delay not valid: $1\"), delay);\n\n if(delay > INT32_MAX)\n POSEIDON_THROW((\"Time delay too large: $1\"), delay);\n\n if(period < 0)\n POSEIDON_THROW((\"Negative timer period not valid: $1\"), period);\n\n if(period > INT32_MAX)\n POSEIDON_THROW((\"Timer period too large: $1\"), period);\n\n \/\/ Calculate the end time point.\n Queued_Timer elem;\n elem.timer = timer;\n elem.next = do_monotonic_now() + delay;\n elem.period = period;\n\n \/\/ Insert the timer.\n plain_mutex::unique_lock lock(this->m_pq_mutex);\n elem.serial = ++ this->m_serial;\n timer->m_serial = elem.serial;\n this->m_pq.emplace_back(::std::move(elem));\n ::std::push_heap(this->m_pq.begin(), this->m_pq.end(), timer_comparator);\n this->m_pq_avail.notify_one();\n }\n\n} \/\/ namespace poseidon\n<|endoftext|>"} {"text":"<commit_before>\/**\n * Copyright 2011-2015 Quickstep Technologies LLC.\n * Copyright 2015-2016 Pivotal Software, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n **\/\n\n#ifndef QUICKSTEP_STORAGE_STORAGE_BLOCK_BASE_HPP_\n#define QUICKSTEP_STORAGE_STORAGE_BLOCK_BASE_HPP_\n\n#include <atomic>\n#include <cstddef>\n\n#include \"storage\/StorageBlockInfo.hpp\"\n#include \"utility\/Macros.hpp\"\n\n#include \"glog\/logging.h\"\n\nnamespace quickstep {\n\n\/**\n * @brief Abstract base class which encompasses functionality common to\n * StorageBlock and StorageBlob.\n **\/\nclass StorageBlockBase {\n public:\n \/**\n * @brief Virtual destructor.\n **\/\n virtual ~StorageBlockBase() {\n#ifdef QUICKSTEP_DEBUG\n CHECK_EQ(0, getRefCount())\n << \"Nonzero ref_count_ when deleting block (\"\n << BlockIdUtil::Domain(id_) << \", \"\n << BlockIdUtil::Counter(id_) << \")\";\n#endif\n }\n\n \/**\n * @brief Determine if this is a StorageBlob or StorageBlock.\n *\n * @return true if this is a StorageBlob, false if it is a StorageBlock.\n **\/\n virtual bool isBlob() const = 0;\n\n \/**\n * @brief Get this block's block_id.\n *\n * @return This block's ID.\n **\/\n inline block_id getID() const {\n return id_;\n }\n\n \/**\n * @brief Check whether this block is dirty (whether it has been changed\n * since being written to disk).\n *\n * @return Whether the block is dirty.\n **\/\n inline bool isDirty() const {\n return dirty_;\n }\n\n \/**\n * @brief Clear the dirty bit for this block, marking it as clean.\n **\/\n inline void markClean() {\n dirty_ = false;\n }\n\n#ifdef QUICKSTEP_DEBUG\n \/**\n * @brief Atomically increment the reference count for this StorageBlockBase.\n **\/\n void ref() const {\n ++ref_count_;\n }\n\n \/**\n * @brief Atomically decrement the reference count for this StorageBlockBase.\n **\/\n void unref() const {\n CHECK_GE(--ref_count_, 0)\n << \"unref() of block (\"\n << BlockIdUtil::Domain(id_) << \", \"\n << BlockIdUtil::Counter(id_) << \") \"\n << \"caused reference count to become negative.\";\n }\n\n \/**\n * @brief Atomically get the reference count of this block.\n * @return This block's reference count.\n **\/\n int getRefCount() const {\n return ref_count_.load();\n }\n#endif\n\n protected:\n StorageBlockBase(const block_id id,\n void *block_memory,\n const std::size_t block_memory_size)\n : id_(id),\n dirty_(false),\n block_memory_(block_memory),\n block_memory_size_(block_memory_size)\n#ifdef QUICKSTEP_DEBUG\n , ref_count_(0) \/\/ initialize the atomic using direct initialization\n#endif\n { \/\/ breaking the style guidelines to call atomic direct initialization only when compiled with QUICKSTEP_DEBUG defined\n }\n\n const block_id id_;\n bool dirty_;\n\n void *block_memory_;\n const std::size_t block_memory_size_;\n\n private:\n#ifdef QUICKSTEP_DEBUG\n mutable std::atomic_int ref_count_;\n#endif\n\n DISALLOW_COPY_AND_ASSIGN(StorageBlockBase);\n};\n\n} \/\/ namespace quickstep\n\n#endif \/\/ QUICKSTEP_STORAGE_STORAGE_BLOCK_BASE_HPP_\n<commit_msg>Send job back to Travis.<commit_after>\/**\n * Copyright 2011-2015 Quickstep Technologies LLC.\n * Copyright 2015-2016 Pivotal Software, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n **\/\n\n#ifndef QUICKSTEP_STORAGE_STORAGE_BLOCK_BASE_HPP_\n#define QUICKSTEP_STORAGE_STORAGE_BLOCK_BASE_HPP_\n\n#include <atomic>\n#include <cstddef>\n\n#include \"storage\/StorageBlockInfo.hpp\"\n#include \"utility\/Macros.hpp\"\n\n#include \"glog\/logging.h\"\n\nnamespace quickstep {\n\n\/**\n * @brief Abstract base class which encompasses functionality common to\n * StorageBlock and StorageBlob.\n **\/\nclass StorageBlockBase {\n public:\n \/**\n * @brief Virtual destructor.\n **\/\n virtual ~StorageBlockBase() {\n#ifdef QUICKSTEP_DEBUG\n CHECK_EQ(0, getRefCount())\n << \"Nonzero ref_count_ when deleting block (\"\n << BlockIdUtil::Domain(id_) << \", \"\n << BlockIdUtil::Counter(id_) << \")\";\n#endif\n }\n\n \/**\n * @brief Determine if this is a StorageBlob or StorageBlock.\n *\n * @return true if this is a StorageBlob, false if it is a StorageBlock.\n **\/\n virtual bool isBlob() const = 0;\n\n \/**\n * @brief Get this block's block_id.\n *\n * @return This block's ID.\n **\/\n inline block_id getID() const {\n return id_;\n }\n\n \/**\n * @brief Check whether this block is dirty (whether it has been changed\n * since being written to disk).\n *\n * @return Whether the block is dirty.\n **\/\n inline bool isDirty() const {\n return dirty_;\n }\n\n \/**\n * @brief Clear the dirty bit for this block, marking it as clean.\n **\/\n inline void markClean() {\n dirty_ = false;\n }\n\n#ifdef QUICKSTEP_DEBUG\n \/**\n * @brief Atomically increment the reference count for this StorageBlockBase.\n **\/\n void ref() const {\n ++ref_count_;\n }\n\n \/**\n * @brief Atomically decrement the reference count for this StorageBlockBase.\n **\/\n void unref() const {\n CHECK_GE(--ref_count_, 0)\n << \"unref() of block (\"\n << BlockIdUtil::Domain(id_) << \", \"\n << BlockIdUtil::Counter(id_) << \") \"\n << \"caused reference count to become negative.\";\n }\n\n \/**\n * @brief Atomically get the reference count of this block.\n * @return This block's reference count.\n **\/\n int getRefCount() const {\n return ref_count_.load();\n }\n#endif\n\n protected:\n StorageBlockBase(const block_id id,\n void *block_memory,\n const std::size_t block_memory_size)\n : id_(id),\n dirty_(false),\n block_memory_(block_memory),\n block_memory_size_(block_memory_size)\n#ifdef QUICKSTEP_DEBUG\n , ref_count_(0) \/\/ Initialize the atomic using direct initialization.\n#endif\n { \/\/ We are breaking the style guidelines to call direct initialization\n \/\/ on the atomic variable only when compiled with QUICKSTEP_DEBUG defined.\n }\n\n const block_id id_;\n bool dirty_;\n\n void *block_memory_;\n const std::size_t block_memory_size_;\n\n private:\n#ifdef QUICKSTEP_DEBUG\n mutable std::atomic_int ref_count_;\n#endif\n\n DISALLOW_COPY_AND_ASSIGN(StorageBlockBase);\n};\n\n} \/\/ namespace quickstep\n\n#endif \/\/ QUICKSTEP_STORAGE_STORAGE_BLOCK_BASE_HPP_\n<|endoftext|>"} {"text":"<commit_before>\n\/\/ External C++ \/ GLFW functionality for the 'util' module:\n\n\/\/ Namespace(s):\nnamespace external_util\n{\n\t\/\/ Functions:\n\tbool setClipboard(String input)\n\t{\n\t\tconst char* source = input.ToCString<char>();\n\t\t\n\t\t\/\/ Set the system's clipboard-string.\n\t\tglfwSetClipboardString(BBGlfwGame::GlfwGame()->GetGLFWwindow(), source);\n\t\t\n\t\t\/\/ Return the default response.\n\t\treturn true;\n\t}\n\t\n\tString getClipboard()\n\t{\n\t\t\/\/ Grab the current state of the clipboard.\n\t\tconst char* nativeString = glfwGetClipboardString(BBGlfwGame::GlfwGame()->GetGLFWwindow());\n\t\t\n\t\t\/\/ Convert the native clipboard-data into a Monkey 'String'.\n\t\treturn String(nativeString, strlen(nativeString));\n\t}\n\t\n\tbool clearClipboard()\n\t{\n\t\t\/\/ Attempt to clear the clipboard (For some reason, I can't just supply 'NULL').\n\t\tglfwSetClipboardString(BBGlfwGame::GlfwGame()->GetGLFWwindow(), \"\");\n\t\t\n\t\t\/\/ Return the default response.\n\t\treturn true;\n\t}\n}\n<commit_msg>Fixed a UTF8-related bug with 'SetClipboard'. Special thanks to sereschkin for spotting that.<commit_after>\n\/\/ External C++ \/ GLFW functionality for the 'util' module:\n\n\/\/ Namespace(s):\nnamespace external_util\n{\n\t\/\/ Functions:\n\tbool setClipboard(String input)\n\t{\n\t\t\/\/ Set the system's clipboard-string.\n\t\tglfwSetClipboardString(BBGlfwGame::GlfwGame()->GetGLFWwindow(), input.ToUtf8()); \/\/ input.ToCString<char>();\n\t\t\n\t\t\/\/ Return the default response.\n\t\treturn true;\n\t}\n\t\n\tString getClipboard()\n\t{\n\t\t\/\/ Grab the current state of the clipboard.\n\t\tconst char* nativeString = glfwGetClipboardString(BBGlfwGame::GlfwGame()->GetGLFWwindow());\n\t\t\n\t\t\/\/ Convert the native clipboard-data into a Monkey 'String'.\n\t\treturn String(nativeString, strlen(nativeString));\n\t}\n\t\n\tbool clearClipboard()\n\t{\n\t\t\/\/ Attempt to clear the clipboard (For some reason, I can't just supply 'NULL').\n\t\tglfwSetClipboardString(BBGlfwGame::GlfwGame()->GetGLFWwindow(), \"\");\n\t\t\n\t\t\/\/ Return the default response.\n\t\treturn true;\n\t}\n}\n<|endoftext|>"} {"text":"<commit_before>\/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- *\/\n\/* librevenge\n * Version: MPL 2.0 \/ LGPLv2.1+\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\n * Alternatively, the contents of this file may be used under the terms\n * of the GNU Lesser General Public License Version 2.1 or later\n * (LGPLv2.1+), in which case the provisions of the LGPLv2.1+ are\n * applicable instead of those above.\n *\/\n\n#ifndef RVNGSTRINGTEST_H\n#define RVNGSTRINGTEST_H\n\n#include <algorithm>\n#include <cstring>\n\n#include <cppunit\/TestFixture.h>\n#include <cppunit\/extensions\/HelperMacros.h>\n\n#include <librevenge\/librevenge.h>\n\n#include \"librevenge_internal.h\"\n\nnamespace test\n{\n\nusing librevenge::RVNGString;\n\nusing std::equal;\nusing std::size_t;\nusing std::strlen;\n\nnamespace\n{\n\nvoid implTestEscapeXML(const char *const input, const char *const expected)\n{\n\tconst size_t len = strlen(expected);\n\n\t\/\/ appending a C string\n\tRVNGString str;\n\tstr.appendEscapedXML(input);\n\tCPPUNIT_ASSERT_EQUAL(static_cast<unsigned long>(len), str.size());\n\tCPPUNIT_ASSERT_EQUAL(int(len), str.len());\n\tCPPUNIT_ASSERT(equal(expected, expected + len, str.cstr()));\n\n\t\/\/ appending a RVNGString\n\tRVNGString str2;\n\tstr2.appendEscapedXML(RVNGString(input));\n\tCPPUNIT_ASSERT_EQUAL(static_cast<unsigned long>(len), str2.size());\n\tCPPUNIT_ASSERT_EQUAL(int(len), str2.len());\n\tCPPUNIT_ASSERT(equal(expected, expected + len, str2.cstr()));\n}\n\n}\n\nclass RVNGStringTest : public CPPUNIT_NS::TestFixture\n{\npublic:\n\tvirtual void setUp();\n\tvirtual void tearDown();\n\nprivate:\n\tCPPUNIT_TEST_SUITE(RVNGStringTest);\n\tCPPUNIT_TEST(testConstruction);\n\tCPPUNIT_TEST(testAppend);\n\tCPPUNIT_TEST(testAppendEscapedXML);\n\tCPPUNIT_TEST(testClear);\n\tCPPUNIT_TEST_SUITE_END();\n\nprivate:\n\tvoid testConstruction();\n\tvoid testAppend();\n\tvoid testAppendEscapedXML();\n\tvoid testClear();\n};\n\nvoid RVNGStringTest::setUp()\n{\n}\n\nvoid RVNGStringTest::tearDown()\n{\n}\n\nvoid RVNGStringTest::testConstruction()\n{\n\t\/\/ default ctor creates empty string\n\tRVNGString empty;\n\tCPPUNIT_ASSERT_EQUAL(0ul, empty.size());\n\tCPPUNIT_ASSERT_EQUAL(0, empty.len());\n\n\t\/\/ construction from a C string\n\tconst char input[] = \"hello world\";\n\tconst size_t len = RVNG_NUM_ELEMENTS(input) - 1;\n\tRVNGString str(input);\n\tCPPUNIT_ASSERT_EQUAL(len, str.size());\n\tCPPUNIT_ASSERT_EQUAL(int(len), str.len());\n\tCPPUNIT_ASSERT(equal(input, input + len, str.cstr()));\n\n\t\/\/ copy construction\n\tRVNGString copy(str);\n\tCPPUNIT_ASSERT_EQUAL(len, copy.size());\n\tCPPUNIT_ASSERT_EQUAL(int(len), copy.len());\n\tCPPUNIT_ASSERT(equal(input, input + len, copy.cstr()));\n\n\t\/\/ assignment\n\tRVNGString assign;\n\tassign = str;\n\tCPPUNIT_ASSERT_EQUAL(len, assign.size());\n\tCPPUNIT_ASSERT_EQUAL(int(len), assign.len());\n\tCPPUNIT_ASSERT(equal(input, input + len, assign.cstr()));\n\n\t\/\/ assignment from C string\n\tRVNGString assign2;\n\tassign2 = input;\n\tCPPUNIT_ASSERT_EQUAL(len, assign.size());\n\tCPPUNIT_ASSERT_EQUAL(int(len), assign.len());\n\tCPPUNIT_ASSERT(equal(input, input + len, assign.cstr()));\n}\n\nvoid RVNGStringTest::testAppend()\n{\n\tconst char input[] = \"hello world\";\n\tconst size_t len = RVNG_NUM_ELEMENTS(input) - 1;\n\tRVNGString str;\n\n\t\/\/ appending a character\n\tstr.append('h');\n\tCPPUNIT_ASSERT_EQUAL(1ul, str.size());\n\tCPPUNIT_ASSERT_EQUAL(1, str.len());\n\tCPPUNIT_ASSERT_EQUAL('h', str.cstr()[0]);\n\n\tRVNGString str2;\n\t\/\/ appending a RVNGString\n\tstr2.append(str);\n\tCPPUNIT_ASSERT_EQUAL(1ul, str2.size());\n\tCPPUNIT_ASSERT_EQUAL(1, str2.len());\n\tCPPUNIT_ASSERT_EQUAL('h', str2.cstr()[0]);\n\n\t\/\/ appending a C string\n\tstr2.append(input + 1);\n\tCPPUNIT_ASSERT_EQUAL(len, str2.size());\n\tCPPUNIT_ASSERT_EQUAL(int(len), str2.len());\n\tCPPUNIT_ASSERT(equal(input, input + len, str2.cstr()));\n}\n\nvoid RVNGStringTest::testAppendEscapedXML()\n{\n\timplTestEscapeXML(\"hello world\", \"hello world\");\n\timplTestEscapeXML(\"<greetings who=\\\"world\\\" kind=\\'&hello;\\'>\", \"<greetings who="world" kind='&hello;'>\");\n}\n\nvoid RVNGStringTest::testClear()\n{\n\tRVNGString str;\n\t\/\/ clearing empty str does nothing\n\tstr.clear();\n\tCPPUNIT_ASSERT_EQUAL(0ul, str.size());\n\tCPPUNIT_ASSERT_EQUAL(0, str.len());\n\n\tstr.append('a');\n\tstr.clear();\n\tCPPUNIT_ASSERT_EQUAL(0ul, str.size());\n\tCPPUNIT_ASSERT_EQUAL(0, str.len());\n}\n\nCPPUNIT_TEST_SUITE_REGISTRATION(RVNGStringTest);\n\n}\n\n#endif \/\/ RVNGSTRINGTEST_H\n\n\/* vim:set shiftwidth=4 softtabstop=4 noexpandtab: *\/\n<commit_msg>test RVNGString::escapeXML too<commit_after>\/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- *\/\n\/* librevenge\n * Version: MPL 2.0 \/ LGPLv2.1+\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\n * Alternatively, the contents of this file may be used under the terms\n * of the GNU Lesser General Public License Version 2.1 or later\n * (LGPLv2.1+), in which case the provisions of the LGPLv2.1+ are\n * applicable instead of those above.\n *\/\n\n#ifndef RVNGSTRINGTEST_H\n#define RVNGSTRINGTEST_H\n\n#include <algorithm>\n#include <cstring>\n\n#include <cppunit\/TestFixture.h>\n#include <cppunit\/extensions\/HelperMacros.h>\n\n#include <librevenge\/librevenge.h>\n\n#include \"librevenge_internal.h\"\n\nnamespace test\n{\n\nusing librevenge::RVNGString;\n\nusing std::equal;\nusing std::size_t;\nusing std::strlen;\n\nnamespace\n{\n\nvoid implTestEscapeXML(const char *const input, const char *const expected)\n{\n\tconst size_t len = strlen(expected);\n\n\t{\n\t\t\/\/ appending a C string\n\t\tRVNGString str;\n\t\tstr.appendEscapedXML(input);\n\t\tCPPUNIT_ASSERT_EQUAL(static_cast<unsigned long>(len), str.size());\n\t\tCPPUNIT_ASSERT_EQUAL(int(len), str.len());\n\t\tCPPUNIT_ASSERT(equal(expected, expected + len, str.cstr()));\n\t}\n\n\t{\n\t\t\/\/ appending a RVNGString\n\t\tRVNGString str;\n\t\tstr.appendEscapedXML(RVNGString(input));\n\t\tCPPUNIT_ASSERT_EQUAL(static_cast<unsigned long>(len), str.size());\n\t\tCPPUNIT_ASSERT_EQUAL(int(len), str.len());\n\t\tCPPUNIT_ASSERT(equal(expected, expected + len, str.cstr()));\n\t}\n\n\t{\n\t\t\/\/ creating from a C string\n\t\tRVNGString str(RVNGString::escapeXML(input));\n\t\tCPPUNIT_ASSERT_EQUAL(static_cast<unsigned long>(len), str.size());\n\t\tCPPUNIT_ASSERT_EQUAL(int(len), str.len());\n\t\tCPPUNIT_ASSERT(equal(expected, expected + len, str.cstr()));\n\t}\n\n\t{\n\t\t\/\/ creating from a RVNGString\n\t\tRVNGString str(RVNGString::escapeXML(RVNGString(input)));\n\t\tCPPUNIT_ASSERT_EQUAL(static_cast<unsigned long>(len), str.size());\n\t\tCPPUNIT_ASSERT_EQUAL(int(len), str.len());\n\t\tCPPUNIT_ASSERT(equal(expected, expected + len, str.cstr()));\n\t}\n}\n\n}\n\nclass RVNGStringTest : public CPPUNIT_NS::TestFixture\n{\npublic:\n\tvirtual void setUp();\n\tvirtual void tearDown();\n\nprivate:\n\tCPPUNIT_TEST_SUITE(RVNGStringTest);\n\tCPPUNIT_TEST(testConstruction);\n\tCPPUNIT_TEST(testAppend);\n\tCPPUNIT_TEST(testAppendEscapedXML);\n\tCPPUNIT_TEST(testClear);\n\tCPPUNIT_TEST_SUITE_END();\n\nprivate:\n\tvoid testConstruction();\n\tvoid testAppend();\n\tvoid testAppendEscapedXML();\n\tvoid testClear();\n};\n\nvoid RVNGStringTest::setUp()\n{\n}\n\nvoid RVNGStringTest::tearDown()\n{\n}\n\nvoid RVNGStringTest::testConstruction()\n{\n\t\/\/ default ctor creates empty string\n\tRVNGString empty;\n\tCPPUNIT_ASSERT_EQUAL(0ul, empty.size());\n\tCPPUNIT_ASSERT_EQUAL(0, empty.len());\n\n\t\/\/ construction from a C string\n\tconst char input[] = \"hello world\";\n\tconst size_t len = RVNG_NUM_ELEMENTS(input) - 1;\n\tRVNGString str(input);\n\tCPPUNIT_ASSERT_EQUAL(len, str.size());\n\tCPPUNIT_ASSERT_EQUAL(int(len), str.len());\n\tCPPUNIT_ASSERT(equal(input, input + len, str.cstr()));\n\n\t\/\/ copy construction\n\tRVNGString copy(str);\n\tCPPUNIT_ASSERT_EQUAL(len, copy.size());\n\tCPPUNIT_ASSERT_EQUAL(int(len), copy.len());\n\tCPPUNIT_ASSERT(equal(input, input + len, copy.cstr()));\n\n\t\/\/ assignment\n\tRVNGString assign;\n\tassign = str;\n\tCPPUNIT_ASSERT_EQUAL(len, assign.size());\n\tCPPUNIT_ASSERT_EQUAL(int(len), assign.len());\n\tCPPUNIT_ASSERT(equal(input, input + len, assign.cstr()));\n\n\t\/\/ assignment from C string\n\tRVNGString assign2;\n\tassign2 = input;\n\tCPPUNIT_ASSERT_EQUAL(len, assign.size());\n\tCPPUNIT_ASSERT_EQUAL(int(len), assign.len());\n\tCPPUNIT_ASSERT(equal(input, input + len, assign.cstr()));\n}\n\nvoid RVNGStringTest::testAppend()\n{\n\tconst char input[] = \"hello world\";\n\tconst size_t len = RVNG_NUM_ELEMENTS(input) - 1;\n\tRVNGString str;\n\n\t\/\/ appending a character\n\tstr.append('h');\n\tCPPUNIT_ASSERT_EQUAL(1ul, str.size());\n\tCPPUNIT_ASSERT_EQUAL(1, str.len());\n\tCPPUNIT_ASSERT_EQUAL('h', str.cstr()[0]);\n\n\tRVNGString str2;\n\t\/\/ appending a RVNGString\n\tstr2.append(str);\n\tCPPUNIT_ASSERT_EQUAL(1ul, str2.size());\n\tCPPUNIT_ASSERT_EQUAL(1, str2.len());\n\tCPPUNIT_ASSERT_EQUAL('h', str2.cstr()[0]);\n\n\t\/\/ appending a C string\n\tstr2.append(input + 1);\n\tCPPUNIT_ASSERT_EQUAL(len, str2.size());\n\tCPPUNIT_ASSERT_EQUAL(int(len), str2.len());\n\tCPPUNIT_ASSERT(equal(input, input + len, str2.cstr()));\n}\n\nvoid RVNGStringTest::testAppendEscapedXML()\n{\n\timplTestEscapeXML(\"hello world\", \"hello world\");\n\timplTestEscapeXML(\"<greetings who=\\\"world\\\" kind=\\'&hello;\\'>\", \"<greetings who="world" kind='&hello;'>\");\n}\n\nvoid RVNGStringTest::testClear()\n{\n\tRVNGString str;\n\t\/\/ clearing empty str does nothing\n\tstr.clear();\n\tCPPUNIT_ASSERT_EQUAL(0ul, str.size());\n\tCPPUNIT_ASSERT_EQUAL(0, str.len());\n\n\tstr.append('a');\n\tstr.clear();\n\tCPPUNIT_ASSERT_EQUAL(0ul, str.size());\n\tCPPUNIT_ASSERT_EQUAL(0, str.len());\n}\n\nCPPUNIT_TEST_SUITE_REGISTRATION(RVNGStringTest);\n\n}\n\n#endif \/\/ RVNGSTRINGTEST_H\n\n\/* vim:set shiftwidth=4 softtabstop=4 noexpandtab: *\/\n<|endoftext|>"} {"text":"<commit_before>#include \"acmacs-base\/pybind11.hh\"\n#include \"acmacs-chart\/ace.hh\"\n#include \"variant-id.hh\"\n#include \"vaccines.hh\"\n#include \"hidb.hh\"\n#include \"hidb-export.hh\"\n\nusing namespace hidb;\n\n\/\/ ----------------------------------------------------------------------\n\nPYBIND11_PLUGIN(hidb_backend)\n{\n py::module m(\"hidb_backend\", \"HiDB access plugin\");\n\n \/\/ ----------------------------------------------------------------------\n \/\/ acmacs_chart_backend\n \/\/ ----------------------------------------------------------------------\n\n auto acmacs_chart_backend = py::module::import(\"acmacs_chart_backend\");\n class hidb_Antigen : public Antigen {};\n \/\/ using hidb_Antigen = Antigen;\n py::class_<hidb_Antigen>(m, \"Antigen\", acmacs_chart_backend.attr(\"Antigen\"));\n \/\/ m.attr(\"Antigen\") = acmacs_chart_backend.attr(\"Antigen\");\n \/\/ py::class_<Antigen>(m, \"Antigen\", acmacs_chart_backend.attr(\"Antigen\"));\n \/\/ py::class_<Serum>(m, \"Serum\", acmacs_chart_backend.attr(\"Serum\"));\n\n \/\/ ----------------------------------------------------------------------\n \/\/ Vaccines\n \/\/ ----------------------------------------------------------------------\n\n py::class_<Vaccines::HomologousSerum>(m, \"Vaccines_HomologousSerum\")\n .def_readonly(\"serum\", &Vaccines::HomologousSerum::serum)\n .def_readonly(\"serum_index\", &Vaccines::HomologousSerum::serum_index)\n .def_readonly(\"most_recent_table\", &Vaccines::HomologousSerum::most_recent_table_date)\n .def(\"number_of_tables\", &Vaccines::HomologousSerum::number_of_tables)\n ;\n\n py::class_<Vaccines::Entry>(m, \"Vaccines_Entry\")\n .def_readonly(\"antigen\", &Vaccines::Entry::antigen)\n .def_readonly(\"antigen_index\", &Vaccines::Entry::antigen_index)\n .def_readonly(\"homologous_sera\", &Vaccines::Entry::homologous_sera, py::return_value_policy::reference)\n ;\n\n py::class_<Vaccines>(m, \"Vaccines\")\n .def(\"report\", &Vaccines::report, py::arg(\"indent\") = 0)\n .def(\"egg\", &Vaccines::egg, py::arg(\"no\") = 0, py::return_value_policy::reference)\n .def(\"cell\", &Vaccines::cell, py::arg(\"no\") = 0, py::return_value_policy::reference)\n .def(\"reassortant\", &Vaccines::reassortant, py::arg(\"no\") = 0, py::return_value_policy::reference)\n .def(\"number_of_eggs\", &Vaccines::number_of_eggs)\n .def(\"number_of_cells\", &Vaccines::number_of_cells)\n .def(\"number_of_reassortants\", &Vaccines::number_of_reassortants)\n ;\n\n m.def(\"find_vaccines_in_chart\", &find_vaccines_in_chart, py::arg(\"name\"), py::arg(\"chart\"), py::arg(\"hidb\"));\n\n \/\/ ----------------------------------------------------------------------\n \/\/ HiDb\n \/\/ ----------------------------------------------------------------------\n\n py::class_<PerTable>(m, \"PerTable\")\n .def(\"table_id\", static_cast<const std::string (PerTable::*)() const>(&PerTable::table_id))\n ;\n\n py::class_<AntigenData>(m, \"AntigenData\")\n \/\/ .def(\"data\", py::overload_cast<>(&AntigenData::data))\n .def(\"data\", [](AntigenData& antigen_data) -> hidb_Antigen& { return static_cast<hidb_Antigen&>(antigen_data.data()); })\n .def(\"number_of_tables\", &AntigenData::number_of_tables)\n .def(\"most_recent_table\", &AntigenData::most_recent_table)\n .def(\"oldest_table\", &AntigenData::oldest_table)\n .def(\"date\", &AntigenData::date)\n .def(\"tables\", static_cast<const std::vector<PerTable>& (AntigenData::*)() const>(&AntigenData::per_table))\n ;\n\n py::class_<SerumData>(m, \"SerumData\")\n .def(\"data\", py::overload_cast<>(&SerumData::data))\n .def(\"number_of_tables\", &SerumData::number_of_tables)\n .def(\"most_recent_table\", &SerumData::most_recent_table)\n .def(\"oldest_table\", &SerumData::oldest_table)\n .def(\"tables\", static_cast<const std::vector<PerTable>& (SerumData::*)() const>(&SerumData::per_table))\n .def(\"homologous\", &SerumData::homologous)\n ;\n\n py::class_<AntigenRefs>(m, \"AntigenRefs\")\n .def(\"__len__\", [](const AntigenRefs& ar) { return ar.size(); })\n .def(\"__getitem__\", [](const AntigenRefs& ar, size_t i) { if (i >= ar.size()) throw py::index_error(); return ar[i]; }, py::return_value_policy::reference)\n .def(\"country\", &AntigenRefs::country, py::arg(\"country\"))\n .def(\"date_range\", &AntigenRefs::date_range, py::arg(\"begin\") = \"\", py::arg(\"end\") = \"\")\n ;\n\n \/\/ --------------------------------------------------\n \/\/ lambdas below are to avoid python GC affecting data\n\n auto pointer_to_copy = [](const std::vector<const AntigenData*>& source) -> std::vector<AntigenData> {\n std::vector<AntigenData> result;\n std::transform(source.begin(), source.end(), std::back_inserter(result), [](const auto& e) { return *e; });\n return result;\n };\n\n auto find_antigens_by_name = [&pointer_to_copy](const HiDb& aHiDb, std::string name) -> std::vector<AntigenData> {\n return pointer_to_copy(aHiDb.find_antigens_by_name(name));\n };\n\n auto find_antigens = [&pointer_to_copy](const HiDb& aHiDb, std::string name) -> std::vector<AntigenData> {\n return pointer_to_copy(aHiDb.find_antigens(name));\n };\n\n auto find_antigens_fuzzy = [&pointer_to_copy](const HiDb& aHiDb, std::string name) {\n return pointer_to_copy(aHiDb.find_antigens_fuzzy(name));\n };\n\n auto find_antigens_extra_fuzzy = [&pointer_to_copy](const HiDb& aHiDb, std::string name) {\n return pointer_to_copy(aHiDb.find_antigens_extra_fuzzy(name));\n };\n\n auto find_antigens_with_score = [](const HiDb& aHiDb, std::string name) {\n const auto source = aHiDb.find_antigens_with_score(name);\n std::vector<std::pair<AntigenData, size_t>> result;\n std::transform(source.begin(), source.end(), std::back_inserter(result), [](const auto& e) { return std::make_pair(*e.first, e.second); });\n return result;\n };\n\n auto find_antigens_by_cdcid = [&pointer_to_copy](const HiDb& aHiDb, std::string cdcid) -> std::vector<AntigenData> {\n return pointer_to_copy(aHiDb.find_antigens_by_cdcid(cdcid));\n };\n\n auto find_sera = [](const HiDb& aHiDb, std::string name) {\n const auto source = aHiDb.find_sera(name);\n std::vector<SerumData> result;\n std::transform(source.begin(), source.end(), std::back_inserter(result), [](const auto& e) { return *e; });\n return result;\n };\n\n auto find_homologous_sera = [](const HiDb& aHiDb, const AntigenData& aAntigen) {\n const auto source = aHiDb.find_homologous_sera(aAntigen);\n std::vector<SerumData> result;\n std::transform(source.begin(), source.end(), std::back_inserter(result), [](const auto& e) { return *e; });\n return result;\n };\n\n auto find_sera_with_score = [](const HiDb& aHiDb, std::string name) {\n const auto source = aHiDb.find_sera_with_score(name);\n std::vector<std::pair<SerumData, size_t>> result;\n std::transform(source.begin(), source.end(), std::back_inserter(result), [](const auto& e) { return std::make_pair(*e.first, e.second); });\n return result;\n };\n\n \/\/ --------------------------------------------------\n\n py::class_<HiDbStat>(m, \"HiDbStat\")\n .def(py::init<>())\n .def(\"compute_totals\", &HiDbStat::compute_totals)\n .def(\"as_dict\", [](HiDbStat& aStat) -> HiDbStatContainer& { return aStat; }, py::return_value_policy::reference)\n ;\n\n \/\/ --------------------------------------------------\n\n py::class_<HiDb>(m, \"HiDb\")\n .def(py::init<>())\n .def(\"add\", &HiDb::add, py::arg(\"chart\"))\n .def(\"export_to\", &HiDb::exportTo, py::arg(\"filename\"), py::arg(\"pretty\") = false)\n .def(\"import_from\", &HiDb::importFrom, py::arg(\"filename\"))\n .def(\"import_locdb\", &HiDb::importLocDb, py::arg(\"filename\"))\n\n .def(\"all_antigens\", &HiDb::all_antigens, py::return_value_policy::reference)\n .def(\"all_countries\", &HiDb::all_countries)\n .def(\"unrecognized_locations\", &HiDb::unrecognized_locations, py::doc(\"returns unrecognized locations found in all antigen\/serum names\"))\n\n .def(\"stat_antigens\", &HiDb::stat_antigens, py::arg(\"stat\"), py::arg(\"start_date\") = \"\", py::arg(\"end_date\") = \"\")\n .def(\"stat_sera\", &HiDb::stat_sera, py::arg(\"stat\"), py::arg(\"stat_unique\"), py::arg(\"start_date\") = \"\", py::arg(\"end_date\") = \"\")\n\n .def(\"list_antigen_names\", &HiDb::list_antigen_names, py::arg(\"lab\") = \"\", py::arg(\"full_name\") = false)\n .def(\"list_antigens\", &HiDb::list_antigens, py::arg(\"lab\"))\n .def(\"find_antigens\", find_antigens, py::arg(\"name\"))\n .def(\"find_antigens_fuzzy\", find_antigens_fuzzy, py::arg(\"name\"))\n .def(\"find_antigens_extra_fuzzy\", find_antigens_extra_fuzzy, py::arg(\"name\"))\n .def(\"find_antigens_with_score\", find_antigens_with_score, py::arg(\"name\"))\n .def(\"find_antigens_by_name\", find_antigens_by_name, py::arg(\"name\"))\n .def(\"find_antigens_by_cdcid\", find_antigens_by_cdcid, py::arg(\"cdcid\"))\n .def(\"list_serum_names\", &HiDb::list_serum_names, py::arg(\"lab\") = \"\", py::arg(\"full_name\") = false)\n .def(\"list_sera\", &HiDb::list_sera, py::arg(\"lab\"))\n .def(\"find_sera\", find_sera, py::arg(\"name\"))\n .def(\"find_homologous_sera\", find_homologous_sera, py::arg(\"antigen\"))\n .def(\"find_sera_with_score\", find_sera_with_score, py::arg(\"name\"))\n .def(\"find_homologous_antigens_for_sera_of_chart\", &HiDb::find_homologous_antigens_for_sera_of_chart, py::arg(\"chart\"))\n ;\n\n \/\/ ----------------------------------------------------------------------\n\n py::class_<hidb::HiDbSet>(m, \"HiDbSet\")\n .def(py::init<std::string>(), py::arg(\"hidb_dir\"))\n .def(\"get\", &hidb::HiDbSet::get, py::arg(\"virus_type\"), py::return_value_policy::reference)\n ;\n\n \/\/ ----------------------------------------------------------------------\n\n return m.ptr();\n}\n\n\/\/ ----------------------------------------------------------------------\n\/\/\/ Local Variables:\n\/\/\/ eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))\n\/\/\/ End:\n<commit_msg>figuring out how to use class from another python module<commit_after>#include \"acmacs-base\/pybind11.hh\"\n#include \"acmacs-chart\/ace.hh\"\n#include \"variant-id.hh\"\n#include \"vaccines.hh\"\n#include \"hidb.hh\"\n#include \"hidb-export.hh\"\n\nusing namespace hidb;\n\n\/\/ ----------------------------------------------------------------------\n\nPYBIND11_PLUGIN(hidb_backend)\n{\n py::module m(\"hidb_backend\", \"HiDB access plugin\");\n\n \/\/ ----------------------------------------------------------------------\n \/\/ acmacs_chart_backend\n \/\/ ----------------------------------------------------------------------\n\n auto acmacs_chart_backend = py::module::import(\"acmacs_chart_backend\");\n class hidb_Antigen : public Antigen {};\n py::class_<hidb_Antigen>(m, \"Antigen\", acmacs_chart_backend.attr(\"Antigen\"));\n class hidb_Serum : public Serum {};\n py::class_<hidb_Serum>(m, \"Serum\", acmacs_chart_backend.attr(\"Serum\"));\n\n \/\/ ----------------------------------------------------------------------\n \/\/ Vaccines\n \/\/ ----------------------------------------------------------------------\n\n py::class_<Vaccines::HomologousSerum>(m, \"Vaccines_HomologousSerum\")\n .def_readonly(\"serum\", &Vaccines::HomologousSerum::serum)\n .def_readonly(\"serum_index\", &Vaccines::HomologousSerum::serum_index)\n .def_readonly(\"most_recent_table\", &Vaccines::HomologousSerum::most_recent_table_date)\n .def(\"number_of_tables\", &Vaccines::HomologousSerum::number_of_tables)\n ;\n\n py::class_<Vaccines::Entry>(m, \"Vaccines_Entry\")\n .def_readonly(\"antigen\", &Vaccines::Entry::antigen)\n .def_readonly(\"antigen_index\", &Vaccines::Entry::antigen_index)\n .def_readonly(\"homologous_sera\", &Vaccines::Entry::homologous_sera, py::return_value_policy::reference)\n ;\n\n py::class_<Vaccines>(m, \"Vaccines\")\n .def(\"report\", &Vaccines::report, py::arg(\"indent\") = 0)\n .def(\"egg\", &Vaccines::egg, py::arg(\"no\") = 0, py::return_value_policy::reference)\n .def(\"cell\", &Vaccines::cell, py::arg(\"no\") = 0, py::return_value_policy::reference)\n .def(\"reassortant\", &Vaccines::reassortant, py::arg(\"no\") = 0, py::return_value_policy::reference)\n .def(\"number_of_eggs\", &Vaccines::number_of_eggs)\n .def(\"number_of_cells\", &Vaccines::number_of_cells)\n .def(\"number_of_reassortants\", &Vaccines::number_of_reassortants)\n ;\n\n m.def(\"find_vaccines_in_chart\", &find_vaccines_in_chart, py::arg(\"name\"), py::arg(\"chart\"), py::arg(\"hidb\"));\n\n \/\/ ----------------------------------------------------------------------\n \/\/ HiDb\n \/\/ ----------------------------------------------------------------------\n\n py::class_<PerTable>(m, \"PerTable\")\n .def(\"table_id\", static_cast<const std::string (PerTable::*)() const>(&PerTable::table_id))\n ;\n\n py::class_<AntigenData>(m, \"AntigenData\")\n \/\/ .def(\"data\", py::overload_cast<>(&AntigenData::data))\n .def(\"data\", [](AntigenData& antigen_data) -> hidb_Antigen& { return static_cast<hidb_Antigen&>(antigen_data.data()); })\n .def(\"number_of_tables\", &AntigenData::number_of_tables)\n .def(\"most_recent_table\", &AntigenData::most_recent_table)\n .def(\"oldest_table\", &AntigenData::oldest_table)\n .def(\"date\", &AntigenData::date)\n .def(\"tables\", static_cast<const std::vector<PerTable>& (AntigenData::*)() const>(&AntigenData::per_table))\n ;\n\n py::class_<SerumData>(m, \"SerumData\")\n \/\/.def(\"data\", py::overload_cast<>(&SerumData::data))\n .def(\"data\", [](SerumData& serum_data) -> hidb_Serum& { return static_cast<hidb_Serum&>(serum_data.data()); })\n .def(\"number_of_tables\", &SerumData::number_of_tables)\n .def(\"most_recent_table\", &SerumData::most_recent_table)\n .def(\"oldest_table\", &SerumData::oldest_table)\n .def(\"tables\", static_cast<const std::vector<PerTable>& (SerumData::*)() const>(&SerumData::per_table))\n .def(\"homologous\", &SerumData::homologous)\n ;\n\n py::class_<AntigenRefs>(m, \"AntigenRefs\")\n .def(\"__len__\", [](const AntigenRefs& ar) { return ar.size(); })\n .def(\"__getitem__\", [](const AntigenRefs& ar, size_t i) { if (i >= ar.size()) throw py::index_error(); return ar[i]; }, py::return_value_policy::reference)\n .def(\"country\", &AntigenRefs::country, py::arg(\"country\"))\n .def(\"date_range\", &AntigenRefs::date_range, py::arg(\"begin\") = \"\", py::arg(\"end\") = \"\")\n ;\n\n \/\/ --------------------------------------------------\n \/\/ lambdas below are to avoid python GC affecting data\n\n auto pointer_to_copy = [](const std::vector<const AntigenData*>& source) -> std::vector<AntigenData> {\n std::vector<AntigenData> result;\n std::transform(source.begin(), source.end(), std::back_inserter(result), [](const auto& e) { return *e; });\n return result;\n };\n\n auto find_antigens_by_name = [&pointer_to_copy](const HiDb& aHiDb, std::string name) -> std::vector<AntigenData> {\n return pointer_to_copy(aHiDb.find_antigens_by_name(name));\n };\n\n auto find_antigens = [&pointer_to_copy](const HiDb& aHiDb, std::string name) -> std::vector<AntigenData> {\n return pointer_to_copy(aHiDb.find_antigens(name));\n };\n\n auto find_antigens_fuzzy = [&pointer_to_copy](const HiDb& aHiDb, std::string name) {\n return pointer_to_copy(aHiDb.find_antigens_fuzzy(name));\n };\n\n auto find_antigens_extra_fuzzy = [&pointer_to_copy](const HiDb& aHiDb, std::string name) {\n return pointer_to_copy(aHiDb.find_antigens_extra_fuzzy(name));\n };\n\n auto find_antigens_with_score = [](const HiDb& aHiDb, std::string name) {\n const auto source = aHiDb.find_antigens_with_score(name);\n std::vector<std::pair<AntigenData, size_t>> result;\n std::transform(source.begin(), source.end(), std::back_inserter(result), [](const auto& e) { return std::make_pair(*e.first, e.second); });\n return result;\n };\n\n auto find_antigens_by_cdcid = [&pointer_to_copy](const HiDb& aHiDb, std::string cdcid) -> std::vector<AntigenData> {\n return pointer_to_copy(aHiDb.find_antigens_by_cdcid(cdcid));\n };\n\n auto find_sera = [](const HiDb& aHiDb, std::string name) {\n const auto source = aHiDb.find_sera(name);\n std::vector<SerumData> result;\n std::transform(source.begin(), source.end(), std::back_inserter(result), [](const auto& e) { return *e; });\n return result;\n };\n\n auto find_homologous_sera = [](const HiDb& aHiDb, const AntigenData& aAntigen) {\n const auto source = aHiDb.find_homologous_sera(aAntigen);\n std::vector<SerumData> result;\n std::transform(source.begin(), source.end(), std::back_inserter(result), [](const auto& e) { return *e; });\n return result;\n };\n\n auto find_sera_with_score = [](const HiDb& aHiDb, std::string name) {\n const auto source = aHiDb.find_sera_with_score(name);\n std::vector<std::pair<SerumData, size_t>> result;\n std::transform(source.begin(), source.end(), std::back_inserter(result), [](const auto& e) { return std::make_pair(*e.first, e.second); });\n return result;\n };\n\n \/\/ --------------------------------------------------\n\n py::class_<HiDbStat>(m, \"HiDbStat\")\n .def(py::init<>())\n .def(\"compute_totals\", &HiDbStat::compute_totals)\n .def(\"as_dict\", [](HiDbStat& aStat) -> HiDbStatContainer& { return aStat; }, py::return_value_policy::reference)\n ;\n\n \/\/ --------------------------------------------------\n\n py::class_<HiDb>(m, \"HiDb\")\n .def(py::init<>())\n .def(\"add\", &HiDb::add, py::arg(\"chart\"))\n .def(\"export_to\", &HiDb::exportTo, py::arg(\"filename\"), py::arg(\"pretty\") = false)\n .def(\"import_from\", &HiDb::importFrom, py::arg(\"filename\"))\n .def(\"import_locdb\", &HiDb::importLocDb, py::arg(\"filename\"))\n\n .def(\"all_antigens\", &HiDb::all_antigens, py::return_value_policy::reference)\n .def(\"all_countries\", &HiDb::all_countries)\n .def(\"unrecognized_locations\", &HiDb::unrecognized_locations, py::doc(\"returns unrecognized locations found in all antigen\/serum names\"))\n\n .def(\"stat_antigens\", &HiDb::stat_antigens, py::arg(\"stat\"), py::arg(\"start_date\") = \"\", py::arg(\"end_date\") = \"\")\n .def(\"stat_sera\", &HiDb::stat_sera, py::arg(\"stat\"), py::arg(\"stat_unique\"), py::arg(\"start_date\") = \"\", py::arg(\"end_date\") = \"\")\n\n .def(\"list_antigen_names\", &HiDb::list_antigen_names, py::arg(\"lab\") = \"\", py::arg(\"full_name\") = false)\n .def(\"list_antigens\", &HiDb::list_antigens, py::arg(\"lab\"))\n .def(\"find_antigens\", find_antigens, py::arg(\"name\"))\n .def(\"find_antigens_fuzzy\", find_antigens_fuzzy, py::arg(\"name\"))\n .def(\"find_antigens_extra_fuzzy\", find_antigens_extra_fuzzy, py::arg(\"name\"))\n .def(\"find_antigens_with_score\", find_antigens_with_score, py::arg(\"name\"))\n .def(\"find_antigens_by_name\", find_antigens_by_name, py::arg(\"name\"))\n .def(\"find_antigens_by_cdcid\", find_antigens_by_cdcid, py::arg(\"cdcid\"))\n .def(\"list_serum_names\", &HiDb::list_serum_names, py::arg(\"lab\") = \"\", py::arg(\"full_name\") = false)\n .def(\"list_sera\", &HiDb::list_sera, py::arg(\"lab\"))\n .def(\"find_sera\", find_sera, py::arg(\"name\"))\n .def(\"find_homologous_sera\", find_homologous_sera, py::arg(\"antigen\"))\n .def(\"find_sera_with_score\", find_sera_with_score, py::arg(\"name\"))\n .def(\"find_homologous_antigens_for_sera_of_chart\", &HiDb::find_homologous_antigens_for_sera_of_chart, py::arg(\"chart\"))\n ;\n\n \/\/ ----------------------------------------------------------------------\n\n py::class_<hidb::HiDbSet>(m, \"HiDbSet\")\n .def(py::init<std::string>(), py::arg(\"hidb_dir\"))\n .def(\"get\", &hidb::HiDbSet::get, py::arg(\"virus_type\"), py::return_value_policy::reference)\n ;\n\n \/\/ ----------------------------------------------------------------------\n\n return m.ptr();\n}\n\n\/\/ ----------------------------------------------------------------------\n\/\/\/ Local Variables:\n\/\/\/ eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))\n\/\/\/ End:\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2019 The SwiftShader Authors. All Rights Reserved.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \"Type.hpp\"\n#include \"Value.hpp\"\n#include \"Variable.hpp\"\n\nnamespace vk {\nnamespace dbg {\n\nconst FormatFlags FormatFlags::Default = {\n\t\"[\", \/\/ listPrefix\n\t\"]\", \/\/ listSuffix\n\t\", \", \/\/ listDelimiter\n\t\"\", \/\/ listIndent\n\t&FormatFlags::Default, \/\/ subListFmt\n};\n\nstd::string Value::string(const FormatFlags& fmt \/* = FormatFlags::Default *\/) const\n{\n\tswitch(type()->kind)\n\t{\n\tcase Kind::Bool:\n\t\treturn *reinterpret_cast<const bool*>(get()) ? \"true\" : \"false\";\n\tcase Kind::U8:\n\t\treturn std::to_string(*reinterpret_cast<const uint8_t*>(get()));\n\tcase Kind::S8:\n\t\treturn std::to_string(*reinterpret_cast<const int8_t*>(get()));\n\tcase Kind::U16:\n\t\treturn std::to_string(*reinterpret_cast<const uint16_t*>(get()));\n\tcase Kind::S16:\n\t\treturn std::to_string(*reinterpret_cast<const int16_t*>(get()));\n\tcase Kind::F32:\n\t\treturn std::to_string(*reinterpret_cast<const float*>(get()));\n\tcase Kind::U32:\n\t\treturn std::to_string(*reinterpret_cast<const uint32_t*>(get()));\n\tcase Kind::S32:\n\t\treturn std::to_string(*reinterpret_cast<const int32_t*>(get()));\n\tcase Kind::F64:\n\t\treturn std::to_string(*reinterpret_cast<const double*>(get()));\n\tcase Kind::U64:\n\t\treturn std::to_string(*reinterpret_cast<const uint64_t*>(get()));\n\tcase Kind::S64:\n\t\treturn std::to_string(*reinterpret_cast<const int64_t*>(get()));\n\tcase Kind::Ptr:\n\t\treturn std::to_string(reinterpret_cast<uintptr_t>(get()));\n\tcase Kind::VariableContainer:\n\t\tauto const* vc = static_cast<const VariableContainer*>(this);\n\t\tstd::string out = \"\";\n\t\tauto subfmt = *fmt.subListFmt;\n\t\tsubfmt.listIndent = fmt.listIndent + fmt.subListFmt->listIndent;\n\t\tbool first = true;\n\t\tvc->foreach(0, [&](const Variable& var) {\n\t\t\tif(!first) { out += fmt.listDelimiter; }\n\t\t\tfirst = false;\n\t\t\tout += fmt.listIndent;\n\t\t\tout += var.name;\n\t\t\tout += \": \";\n\t\t\tout += var.value->string(subfmt);\n\t\t});\n\t\treturn fmt.listPrefix + out + fmt.listSuffix;\n\t}\n\treturn \"\";\n}\n\n} \/\/ namespace dbg\n} \/\/ namespace vk<commit_msg>src\/Vulkan\/Debug: Add scope for case block<commit_after>\/\/ Copyright 2019 The SwiftShader Authors. All Rights Reserved.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \"Type.hpp\"\n#include \"Value.hpp\"\n#include \"Variable.hpp\"\n\nnamespace vk {\nnamespace dbg {\n\nconst FormatFlags FormatFlags::Default = {\n\t\"[\", \/\/ listPrefix\n\t\"]\", \/\/ listSuffix\n\t\", \", \/\/ listDelimiter\n\t\"\", \/\/ listIndent\n\t&FormatFlags::Default, \/\/ subListFmt\n};\n\nstd::string Value::string(const FormatFlags& fmt \/* = FormatFlags::Default *\/) const\n{\n\tswitch(type()->kind)\n\t{\n\tcase Kind::Bool:\n\t\treturn *reinterpret_cast<const bool*>(get()) ? \"true\" : \"false\";\n\tcase Kind::U8:\n\t\treturn std::to_string(*reinterpret_cast<const uint8_t*>(get()));\n\tcase Kind::S8:\n\t\treturn std::to_string(*reinterpret_cast<const int8_t*>(get()));\n\tcase Kind::U16:\n\t\treturn std::to_string(*reinterpret_cast<const uint16_t*>(get()));\n\tcase Kind::S16:\n\t\treturn std::to_string(*reinterpret_cast<const int16_t*>(get()));\n\tcase Kind::F32:\n\t\treturn std::to_string(*reinterpret_cast<const float*>(get()));\n\tcase Kind::U32:\n\t\treturn std::to_string(*reinterpret_cast<const uint32_t*>(get()));\n\tcase Kind::S32:\n\t\treturn std::to_string(*reinterpret_cast<const int32_t*>(get()));\n\tcase Kind::F64:\n\t\treturn std::to_string(*reinterpret_cast<const double*>(get()));\n\tcase Kind::U64:\n\t\treturn std::to_string(*reinterpret_cast<const uint64_t*>(get()));\n\tcase Kind::S64:\n\t\treturn std::to_string(*reinterpret_cast<const int64_t*>(get()));\n\tcase Kind::Ptr:\n\t\treturn std::to_string(reinterpret_cast<uintptr_t>(get()));\n\tcase Kind::VariableContainer:\n\t{\n\t\tauto const* vc = static_cast<const VariableContainer*>(this);\n\t\tstd::string out = \"\";\n\t\tauto subfmt = *fmt.subListFmt;\n\t\tsubfmt.listIndent = fmt.listIndent + fmt.subListFmt->listIndent;\n\t\tbool first = true;\n\t\tvc->foreach(0, [&](const Variable& var) {\n\t\t\tif(!first) { out += fmt.listDelimiter; }\n\t\t\tfirst = false;\n\t\t\tout += fmt.listIndent;\n\t\t\tout += var.name;\n\t\t\tout += \": \";\n\t\t\tout += var.value->string(subfmt);\n\t\t});\n\t\treturn fmt.listPrefix + out + fmt.listSuffix;\n\t}\n\t}\n\treturn \"\";\n}\n\n} \/\/ namespace dbg\n} \/\/ namespace vk<|endoftext|>"} {"text":"<commit_before><commit_msg>typo: referenzed -> referenced<commit_after><|endoftext|>"} {"text":"<commit_before>#include \"WavefrontObjLoader.h\"\n\n#include <cassert>\n#include <sstream>\n#include <iostream>\n#include <fstream>\n\n#include \"PlanarGraph.h\"\n#include \"..\/system\/StringUtils.h\"\n\n#include <glm\/glm.hpp>\n\nusing namespace std;\nusing namespace table;\n\nWavefrontObjLoader::WavefrontObjLoader() : FileTypeHandler(\"WaveFront object\", false) {\n addExtension(\"obj\");\n}\n\nstd::shared_ptr<Graph>\nWavefrontObjLoader::openGraph(const char * filename) {\n auto graph = std::make_shared<PlanarGraph>();\n graph->setHasSpatialData(true);\n \n ifstream in(filename, ios::in);\n if (!in) {\n cerr << \"Cannot open \" << filename << endl;\n return 0;\n }\n \n map<string, int> nodes;\n map<string, int> waiting_faces;\n\n vector<glm::vec3> vertices;\n vector<glm::vec2> uvs;\n vector<glm::vec3> normals;\n\n int region_id = graph->addRegion();\n \n string line;\n while (getline(in, line)) {\n if (line.substr(0,2) == \"v \") {\n istringstream s(line.substr(2));\n double x, y, z;\n s >> x >> y >> z;\n vertices.push_back(glm::vec3(x, y, z));\n } else if (line.substr(0, 3) == \"vn \") {\n istringstream s(line.substr(3));\n double x, y, z;\n s >> x;\n s >> y;\n s >> z;\n normals.push_back(glm::vec3(x, y, z));\n } else if (line.substr(0, 3) == \"vt \") {\n istringstream s(line.substr(3));\n double x, y;\n s >> x >> y;\n uvs.push_back(glm::vec2(x, y)); \n } else if (line.substr(0, 2) == \"f \") { \n int face_id = graph->addFace(region_id);\n vector<unsigned int> face_nodes;\n istringstream s(line.substr(2));\n for (unsigned int i = 0; i < 3; i++) {\n\tstring vs;\n\ts >> vs;\n\tvector<string> vd = StringUtils::split(vs, '\/');\n\tassert(vd.size() == 3);\n\tint vi = stoi(vd[0]) - 1, uvi = stoi(vd[1]) - 1, ni = stoi(vd[2]) - 1;\n\tassert(vi >= 0 && vi < vertices.size());\n\tconst glm::vec3 & v = vertices[vi];\n#if 0\n\tassert(uvi >= 0 && uvi < uvs.size());\n\tconst glm::vec2 & uv = uvs[uvi];\n#endif\n\tassert(ni >= 0 && ni < normals.size());\n\tconst glm::vec3 & normal = normals[ni];\n\tface_nodes.push_back(createNode(*graph, nodes, v.x, v.y, v.z,\n\t\t\t\t\tnormal.x, normal.y, normal.z));\n }\n assert(face_nodes.size() >= 3);\n for (int i = 0; i < (int)face_nodes.size(); i++) {\n\tint node1 = face_nodes[i], node2 = face_nodes[(i + 1) % face_nodes.size()];\n\tassert(node1 != node2);\n\tostringstream key1, key2;\n\tkey1 << node1 << \"\/\" << node2;\n\tmap<string, int>::iterator it = waiting_faces.find(key1.str());\n\tif (it != waiting_faces.end()) {\n\t graph->addEdge(node1, node2, face_id, it->second);\n\t} else {\n\t key2 << node2 << \"\/\" << node1;\n\t it = waiting_faces.find(key2.str());\n\t if (it != waiting_faces.end()) {\n\t graph->addEdge(node2, node1, it->second, face_id);\n\t } else {\n\t waiting_faces[key1.str()] = face_id;\n\t }\n\t}\n }\n } else if (line[0] == '#') {\n \/\/ comment\n } else {\n cerr << \"skipping row \" << line << endl;\n }\n }\n\n#if 0 \n normals.resize(mesh->vertices.size(), glm::vec3(0.0, 0.0, 0.0));\n for (int i = 0; i < elements.size(); i+=3) {\n GLushort ia = elements[i];\n GLushort ib = elements[i+1];\n GLushort ic = elements[i+2];\n glm::vec3 normal = glm::normalize(glm::cross( glm::vec3(vertices[ib]) - glm::vec3(vertices[ia]),\n\t\t\t\t\t\t glm::vec3(vertices[ic]) - glm::vec3(vertices[ia])));\n normals[ia] = normals[ib] = normals[ic] = normal;\n }\n#endif\n\n return graph;\n}\n<commit_msg>rename createNode to createNode3D<commit_after>#include \"WavefrontObjLoader.h\"\n\n#include <cassert>\n#include <sstream>\n#include <iostream>\n#include <fstream>\n\n#include \"PlanarGraph.h\"\n#include \"..\/system\/StringUtils.h\"\n\n#include <glm\/glm.hpp>\n\nusing namespace std;\nusing namespace table;\n\nWavefrontObjLoader::WavefrontObjLoader() : FileTypeHandler(\"WaveFront object\", false) {\n addExtension(\"obj\");\n}\n\nstd::shared_ptr<Graph>\nWavefrontObjLoader::openGraph(const char * filename) {\n auto graph = std::make_shared<PlanarGraph>();\n graph->setHasSpatialData(true);\n \n ifstream in(filename, ios::in);\n if (!in) {\n cerr << \"Cannot open \" << filename << endl;\n return 0;\n }\n \n map<string, int> nodes;\n map<string, int> waiting_faces;\n\n vector<glm::vec3> vertices;\n vector<glm::vec2> uvs;\n vector<glm::vec3> normals;\n\n int region_id = graph->addRegion();\n \n string line;\n while (getline(in, line)) {\n if (line.substr(0,2) == \"v \") {\n istringstream s(line.substr(2));\n double x, y, z;\n s >> x >> y >> z;\n vertices.push_back(glm::vec3(x, y, z));\n } else if (line.substr(0, 3) == \"vn \") {\n istringstream s(line.substr(3));\n double x, y, z;\n s >> x;\n s >> y;\n s >> z;\n normals.push_back(glm::vec3(x, y, z));\n } else if (line.substr(0, 3) == \"vt \") {\n istringstream s(line.substr(3));\n double x, y;\n s >> x >> y;\n uvs.push_back(glm::vec2(x, y)); \n } else if (line.substr(0, 2) == \"f \") { \n int face_id = graph->addFace(region_id);\n vector<unsigned int> face_nodes;\n istringstream s(line.substr(2));\n for (unsigned int i = 0; i < 3; i++) {\n\tstring vs;\n\ts >> vs;\n\tvector<string> vd = StringUtils::split(vs, '\/');\n\tassert(vd.size() == 3);\n\tint vi = stoi(vd[0]) - 1, uvi = stoi(vd[1]) - 1, ni = stoi(vd[2]) - 1;\n\tassert(vi >= 0 && vi < vertices.size());\n\tconst glm::vec3 & v = vertices[vi];\n#if 0\n\tassert(uvi >= 0 && uvi < uvs.size());\n\tconst glm::vec2 & uv = uvs[uvi];\n#endif\n\tassert(ni >= 0 && ni < normals.size());\n\tconst glm::vec3 & normal = normals[ni];\n\tface_nodes.push_back(createNode3D(*graph, nodes, v.x, v.y, v.z,\n\t\t\t\t\t normal.x, normal.y, normal.z));\n }\n assert(face_nodes.size() >= 3);\n for (int i = 0; i < (int)face_nodes.size(); i++) {\n\tint node1 = face_nodes[i], node2 = face_nodes[(i + 1) % face_nodes.size()];\n\tassert(node1 != node2);\n\tostringstream key1, key2;\n\tkey1 << node1 << \"\/\" << node2;\n\tmap<string, int>::iterator it = waiting_faces.find(key1.str());\n\tif (it != waiting_faces.end()) {\n\t graph->addEdge(node1, node2, face_id, it->second);\n\t} else {\n\t key2 << node2 << \"\/\" << node1;\n\t it = waiting_faces.find(key2.str());\n\t if (it != waiting_faces.end()) {\n\t graph->addEdge(node2, node1, it->second, face_id);\n\t } else {\n\t waiting_faces[key1.str()] = face_id;\n\t }\n\t}\n }\n } else if (line[0] == '#') {\n \/\/ comment\n } else {\n cerr << \"skipping row \" << line << endl;\n }\n }\n\n#if 0 \n normals.resize(mesh->vertices.size(), glm::vec3(0.0, 0.0, 0.0));\n for (int i = 0; i < elements.size(); i+=3) {\n GLushort ia = elements[i];\n GLushort ib = elements[i+1];\n GLushort ic = elements[i+2];\n glm::vec3 normal = glm::normalize(glm::cross( glm::vec3(vertices[ib]) - glm::vec3(vertices[ia]),\n\t\t\t\t\t\t glm::vec3(vertices[ic]) - glm::vec3(vertices[ia])));\n normals[ia] = normals[ib] = normals[ic] = normal;\n }\n#endif\n\n return graph;\n}\n<|endoftext|>"} {"text":"<commit_before>#include <stdexcept>\n\n#include <tightdb\/util\/thread.hpp>\n\n#if !defined _WIN32\n# include <unistd.h>\n#endif\n\n\/\/ \"Process shared mutexes\" are not officially supported on Android,\n\/\/ but they appear to work anyway.\n#if _POSIX_THREAD_PROCESS_SHARED > 0 || TIGHTDB_ANDROID\n# define TIGHTDB_HAVE_PTHREAD_PROCESS_SHARED\n#endif\n\n\/\/ Unfortunately Older Ubuntu releases such as 10.04 reports support\n\/\/ for robust mutexes by setting _POSIX_THREADS = 200809L and\n\/\/ _POSIX_THREAD_PROCESS_SHARED = 200809L even though they do not\n\/\/ provide pthread_mutex_consistent(). See also\n\/\/ http:\/\/www.gnu.org\/software\/gnulib\/manual\/gnulib.html#pthread_005fmutex_005fconsistent.\n\/\/ Support was added to glibc 2.12, so we disable for earlier versions\n\/\/ of glibs\n#ifdef TIGHTDB_HAVE_PTHREAD_PROCESS_SHARED\n# if !defined _WIN32 \/\/ 'robust' not supported by our windows pthreads port\n# if _POSIX_THREADS >= 200809L\n# ifdef __GNU_LIBRARY__\n# if __GLIBC__ >= 2 && __GLIBC_MINOR__ >= 12\n# define TIGHTDB_HAVE_ROBUST_PTHREAD_MUTEX\n# endif\n# else\n# define TIGHTDB_HAVE_ROBUST_PTHREAD_MUTEX\n# endif\n# endif\n# endif\n#endif\n\n\nusing namespace std;\nusing namespace tightdb;\nusing namespace tightdb::util;\n\n\nnamespace {\n\n\/\/ Valgrind can show still-reachable leaks for pthread_create() on many systems (AIX, Debian, etc) because\n\/\/ glibc declares a static memory pool for threads which are free'd by the OS on process termination. See\n\/\/ http:\/\/www.network-theory.co.uk\/docs\/valgrind\/valgrind_20.html under --run-libc-freeres=<yes|no>.\n\/\/ This can give false positives because of missing suppression, etc (not real leaks!). It's also a problem\n\/\/ on Windows, so we have written our own clean-up method for the Windows port.\n#if defined _WIN32 && defined TIGHTDB_DEBUG\nvoid free_threadpool();\n\nclass Initialization\n{\npublic:\n ~Initialization()\n {\n free_threadpool();\n }\n};\n\nInitialization initialization;\n\nvoid free_threadpool()\n{\n pthread_cleanup();\n}\n#endif\n\n} \/\/ anonymous namespace\n\n\nvoid Thread::join()\n{\n if (!m_joinable)\n throw runtime_error(\"Thread is not joinable\");\n void** value_ptr = 0; \/\/ Ignore return value\n int r = pthread_join(m_id, value_ptr);\n if (TIGHTDB_UNLIKELY(r != 0))\n join_failed(r); \/\/ Throws\n m_joinable = false;\n}\n\nTIGHTDB_NORETURN void Thread::create_failed(int)\n{\n throw runtime_error(\"pthread_create() failed\");\n}\n\nTIGHTDB_NORETURN void Thread::join_failed(int)\n{\n \/\/ It is intentional that the argument is ignored here.\n throw runtime_error(\"pthread_join() failed.\");\n}\n\nvoid Mutex::init_as_process_shared(bool robust_if_available)\n{\n#ifdef TIGHTDB_HAVE_PTHREAD_PROCESS_SHARED\n pthread_mutexattr_t attr;\n int r = pthread_mutexattr_init(&attr);\n if (TIGHTDB_UNLIKELY(r != 0))\n attr_init_failed(r);\n r = pthread_mutexattr_setpshared(&attr, PTHREAD_PROCESS_SHARED);\n TIGHTDB_ASSERT(r == 0);\n# ifdef TIGHTDB_HAVE_ROBUST_PTHREAD_MUTEX\n if (robust_if_available) {\n r = pthread_mutexattr_setrobust(&attr, PTHREAD_MUTEX_ROBUST);\n TIGHTDB_ASSERT(r == 0);\n }\n# else \/\/ !TIGHTDB_HAVE_ROBUST_PTHREAD_MUTEX\n static_cast<void>(robust_if_available);\n# endif\n r = pthread_mutex_init(&m_impl, &attr);\n int r2 = pthread_mutexattr_destroy(&attr);\n TIGHTDB_ASSERT(r2 == 0);\n static_cast<void>(r2);\n if (TIGHTDB_UNLIKELY(r != 0))\n init_failed(r);\n#else \/\/ !TIGHTDB_HAVE_PTHREAD_PROCESS_SHARED\n static_cast<void>(robust_if_available);\n throw runtime_error(\"No support for process-shared mutexes\");\n#endif\n}\n\nTIGHTDB_NORETURN void Mutex::init_failed(int err)\n{\n switch (err) {\n case ENOMEM:\n throw bad_alloc();\n default:\n throw runtime_error(\"pthread_mutex_init() failed\");\n }\n}\n\nTIGHTDB_NORETURN void Mutex::attr_init_failed(int err)\n{\n switch (err) {\n case ENOMEM:\n throw bad_alloc();\n default:\n throw runtime_error(\"pthread_mutexattr_init() failed\");\n }\n}\n\nTIGHTDB_NORETURN void Mutex::destroy_failed(int err) TIGHTDB_NOEXCEPT\n{\n if (err == EBUSY)\n TIGHTDB_TERMINATE(\"Destruction of mutex in use\");\n TIGHTDB_TERMINATE(\"pthread_mutex_destroy() failed\");\n}\n\n\nTIGHTDB_NORETURN void Mutex::lock_failed(int err) TIGHTDB_NOEXCEPT\n{\n if (err == EDEADLK)\n TIGHTDB_TERMINATE(\"Recursive locking of mutex\");\n TIGHTDB_TERMINATE(\"pthread_mutex_lock() failed\");\n}\n\n\nbool RobustMutex::is_robust_on_this_platform() TIGHTDB_NOEXCEPT\n{\n#ifdef TIGHTDB_HAVE_ROBUST_PTHREAD_MUTEX\n return true;\n#else\n return false;\n#endif\n}\n\nbool RobustMutex::low_level_lock()\n{\n int r = pthread_mutex_lock(&m_impl);\n if (TIGHTDB_LIKELY(r == 0))\n return true;\n#ifdef TIGHTDB_HAVE_ROBUST_PTHREAD_MUTEX\n if (r == EOWNERDEAD)\n return false;\n if (r == ENOTRECOVERABLE)\n throw NotRecoverable();\n#endif\n lock_failed(r);\n}\n\nvoid RobustMutex::mark_as_consistent() TIGHTDB_NOEXCEPT\n{\n#ifdef TIGHTDB_HAVE_ROBUST_PTHREAD_MUTEX\n int r = pthread_mutex_consistent(&m_impl);\n TIGHTDB_ASSERT(r == 0);\n static_cast<void>(r);\n#endif\n}\n\n\nCondVar::CondVar(process_shared_tag)\n{\n#ifdef TIGHTDB_HAVE_PTHREAD_PROCESS_SHARED\n pthread_condattr_t attr;\n int r = pthread_condattr_init(&attr);\n if (TIGHTDB_UNLIKELY(r != 0))\n attr_init_failed(r);\n r = pthread_condattr_setpshared(&attr, PTHREAD_PROCESS_SHARED);\n TIGHTDB_ASSERT(r == 0);\n r = pthread_cond_init(&m_impl, &attr);\n int r2 = pthread_condattr_destroy(&attr);\n TIGHTDB_ASSERT(r2 == 0);\n static_cast<void>(r2);\n if (TIGHTDB_UNLIKELY(r != 0))\n init_failed(r);\n#else \/\/ !TIGHTDB_HAVE_PTHREAD_PROCESS_SHARED\n throw runtime_error(\"No support for process-shared condition variables\");\n#endif\n}\n\nTIGHTDB_NORETURN void CondVar::init_failed(int err)\n{\n switch (err) {\n case ENOMEM:\n throw bad_alloc();\n default:\n throw runtime_error(\"pthread_cond_init() failed\");\n }\n}\n\nvoid CondVar::handle_wait_error(int err)\n{\n#ifdef TIGHTDB_HAVE_ROBUST_PTHREAD_MUTEX\n if (err == ENOTRECOVERABLE)\n throw RobustMutex::NotRecoverable();\n if (err == EOWNERDEAD)\n return;\n#endif\n TIGHTDB_TERMINATE(\"pthread_mutex_lock() failed\");\n}\n\nTIGHTDB_NORETURN void CondVar::attr_init_failed(int err)\n{\n switch (err) {\n case ENOMEM:\n throw bad_alloc();\n default:\n throw runtime_error(\"pthread_condattr_init() failed\");\n }\n}\n\nTIGHTDB_NORETURN void CondVar::destroy_failed(int err) TIGHTDB_NOEXCEPT\n{\n if (err == EBUSY)\n TIGHTDB_TERMINATE(\"Destruction of condition variable in use\");\n TIGHTDB_TERMINATE(\"pthread_cond_destroy() failed\");\n}\n<commit_msg>again...<commit_after>#include <stdexcept>\n\n#include <tightdb\/util\/thread.hpp>\n\n#if !defined _WIN32\n# include <unistd.h>\n#endif\n\n\/\/ \"Process shared mutexes\" are not officially supported on Android,\n\/\/ but they appear to work anyway.\n#if _POSIX_THREAD_PROCESS_SHARED > 0 || TIGHTDB_ANDROID\n# define TIGHTDB_HAVE_PTHREAD_PROCESS_SHARED\n#endif\n\n\/\/ Unfortunately Older Ubuntu releases such as 10.04 reports support\n\/\/ for robust mutexes by setting _POSIX_THREADS = 200809L and\n\/\/ _POSIX_THREAD_PROCESS_SHARED = 200809L even though they do not\n\/\/ provide pthread_mutex_consistent(). See also\n\/\/ http:\/\/www.gnu.org\/software\/gnulib\/manual\/gnulib.html#pthread_005fmutex_005fconsistent.\n\/\/ Support was added to glibc 2.12, so we disable for earlier versions\n\/\/ of glibs\n#ifdef TIGHTDB_HAVE_PTHREAD_PROCESS_SHARED\n# if !defined _WIN32 \/\/ 'robust' not supported by our windows pthreads port\n# if _POSIX_THREADS >= 200809L\n# ifdef __GNU_LIBRARY__\n# if __GLIBC__ >= 2 && __GLIBC_MINOR__ >= 12\n# define TIGHTDB_HAVE_ROBUST_PTHREAD_MUTEX\n# endif\n# else\n# define TIGHTDB_HAVE_ROBUST_PTHREAD_MUTEX\n# endif\n# endif\n# endif\n#endif\n\n\nusing namespace std;\nusing namespace tightdb;\nusing namespace tightdb::util;\n\n\nnamespace {\n\n\/\/ Valgrind can show still-reachable leaks for pthread_create() on many systems (AIX, Debian, etc) because\n\/\/ glibc declares a static memory pool for threads which are free'd by the OS on process termination. See\n\/\/ http:\/\/www.network-theory.co.uk\/docs\/valgrind\/valgrind_20.html under --run-libc-freeres=<yes|no>.\n\/\/ This can give false positives because of missing suppression, etc (not real leaks!). It's also a problem\n\/\/ on Windows, so we have written our own clean-up method for the Windows port.\n#if defined _WIN32 && defined TIGHTDB_DEBUG\nvoid free_threadpool();\n\nclass Initialization\n{\npublic:\n ~Initialization()\n {\n free_threadpool();\n }\n};\n\nInitialization initialization;\n\nvoid free_threadpool()\n{\n pthread_cleanup();\n}\n#endif\n\n} \/\/ anonymous namespace\n\n\nvoid Thread::join()\n{\n if (!m_joinable)\n throw runtime_error(\"Thread is not joinable\");\n void** value_ptr = 0; \/\/ Ignore return value\n int r = pthread_join(m_id, value_ptr);\n if (TIGHTDB_UNLIKELY(r != 0))\n join_failed(r); \/\/ Throws\n m_joinable = false;\n}\n\nTIGHTDB_NORETURN void Thread::create_failed(int)\n{\n throw runtime_error(\"pthread_create() failed\");\n}\n\nTIGHTDB_NORETURN void Thread::join_failed(int)\n{\n \/\/ It is intentional that the argument is ignored here.\n throw runtime_error(\"pthread_join() failed.\");\n}\n\nvoid Mutex::init_as_process_shared(bool robust_if_available)\n{\n#ifdef TIGHTDB_HAVE_PTHREAD_PROCESS_SHARED\n pthread_mutexattr_t attr;\n int r = pthread_mutexattr_init(&attr);\n if (TIGHTDB_UNLIKELY(r != 0))\n attr_init_failed(r);\n r = pthread_mutexattr_setpshared(&attr, PTHREAD_PROCESS_SHARED);\n TIGHTDB_ASSERT(r == 0);\n# ifdef TIGHTDB_HAVE_ROBUST_PTHREAD_MUTEX\n if (robust_if_available) {\n r = pthread_mutexattr_setrobust(&attr, PTHREAD_MUTEX_ROBUST);\n TIGHTDB_ASSERT(r == 0);\n }\n# else \/\/ !TIGHTDB_HAVE_ROBUST_PTHREAD_MUTEX\n static_cast<void>(robust_if_available);\n# endif\n r = pthread_mutex_init(&m_impl, &attr);\n int r2 = pthread_mutexattr_destroy(&attr);\n TIGHTDB_ASSERT(r2 == 0);\n static_cast<void>(r2);\n if (TIGHTDB_UNLIKELY(r != 0))\n init_failed(r);\n#else \/\/ !TIGHTDB_HAVE_PTHREAD_PROCESS_SHARED\n static_cast<void>(robust_if_available);\n throw runtime_error(\"No support for process-shared mutexes\");\n#endif\n}\n\nTIGHTDB_NORETURN void Mutex::init_failed(int err)\n{\n switch (err) {\n case ENOMEM:\n throw bad_alloc();\n default:\n throw runtime_error(\"pthread_mutex_init() failed\");\n }\n}\n\nTIGHTDB_NORETURN void Mutex::attr_init_failed(int err)\n{\n switch (err) {\n case ENOMEM:\n throw bad_alloc();\n default:\n throw runtime_error(\"pthread_mutexattr_init() failed\");\n }\n}\n\nTIGHTDB_NORETURN void Mutex::destroy_failed(int err) TIGHTDB_NOEXCEPT\n{\n if (err == EBUSY)\n TIGHTDB_TERMINATE(\"Destruction of mutex in use\");\n TIGHTDB_TERMINATE(\"pthread_mutex_destroy() failed\");\n}\n\n\nTIGHTDB_NORETURN void Mutex::lock_failed(int err) TIGHTDB_NOEXCEPT\n{\n if (err == EDEADLK)\n TIGHTDB_TERMINATE(\"Recursive locking of mutex\");\n TIGHTDB_TERMINATE(\"pthread_mutex_lock() failed\");\n}\n\n\nbool RobustMutex::is_robust_on_this_platform() TIGHTDB_NOEXCEPT\n{\n#ifdef TIGHTDB_HAVE_ROBUST_PTHREAD_MUTEX\n return true;\n#else\n return false;\n#endif\n}\n\nbool RobustMutex::low_level_lock()\n{\n int r = pthread_mutex_lock(&m_impl);\n if (TIGHTDB_LIKELY(r == 0))\n return true;\n#ifdef TIGHTDB_HAVE_ROBUST_PTHREAD_MUTEX\n if (r == EOWNERDEAD)\n return false;\n if (r == ENOTRECOVERABLE)\n throw NotRecoverable();\n#endif\n lock_failed(r);\n}\n\nvoid RobustMutex::mark_as_consistent() TIGHTDB_NOEXCEPT\n{\n#ifdef TIGHTDB_HAVE_ROBUST_PTHREAD_MUTEX\n int r = pthread_mutex_consistent(&m_impl);\n TIGHTDB_ASSERT(r == 0);\n static_cast<void>(r);\n#endif\n}\n\n\nCondVar::CondVar(process_shared_tag)\n{\n#ifdef TIGHTDB_HAVE_PTHREAD_PROCESS_SHARED\n pthread_condattr_t attr;\n int r = pthread_condattr_init(&attr);\n if (TIGHTDB_UNLIKELY(r != 0))\n attr_init_failed(r);\n r = pthread_condattr_setpshared(&attr, PTHREAD_PROCESS_SHARED);\n TIGHTDB_ASSERT(r == 0);\n r = pthread_cond_init(&m_impl, &attr);\n int r2 = pthread_condattr_destroy(&attr);\n TIGHTDB_ASSERT(r2 == 0);\n static_cast<void>(r2);\n if (TIGHTDB_UNLIKELY(r != 0))\n init_failed(r);\n#else \/\/ !TIGHTDB_HAVE_PTHREAD_PROCESS_SHARED\n throw runtime_error(\"No support for process-shared condition variables\");\n#endif\n}\n\nTIGHTDB_NORETURN void CondVar::init_failed(int err)\n{\n switch (err) {\n case ENOMEM:\n throw bad_alloc();\n default:\n throw runtime_error(\"pthread_cond_init() failed\");\n }\n}\n\nvoid CondVar::handle_wait_error(int err)\n{\n#ifdef TIGHTDB_HAVE_ROBUST_PTHREAD_MUTEX\n if (err == ENOTRECOVERABLE)\n throw RobustMutex::NotRecoverable();\n if (err == EOWNERDEAD)\n return;\n#else\n static_cast<void>(err);\n#endif\n TIGHTDB_TERMINATE(\"pthread_mutex_lock() failed\");\n}\n\nTIGHTDB_NORETURN void CondVar::attr_init_failed(int err)\n{\n switch (err) {\n case ENOMEM:\n throw bad_alloc();\n default:\n throw runtime_error(\"pthread_condattr_init() failed\");\n }\n}\n\nTIGHTDB_NORETURN void CondVar::destroy_failed(int err) TIGHTDB_NOEXCEPT\n{\n if (err == EBUSY)\n TIGHTDB_TERMINATE(\"Destruction of condition variable in use\");\n TIGHTDB_TERMINATE(\"pthread_cond_destroy() failed\");\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * The Apache Software License, Version 1.1\n *\n *\n * Copyright (c) 1999 The Apache Software Foundation. All rights \n * reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer. \n *\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in\n * the documentation and\/or other materials provided with the\n * distribution.\n *\n * 3. The end-user documentation included with the redistribution,\n * if any, must include the following acknowledgment: \n * \"This product includes software developed by the\n * Apache Software Foundation (http:\/\/www.apache.org\/).\"\n * Alternately, this acknowledgment may appear in the software itself,\n * if and wherever such third-party acknowledgments normally appear.\n *\n * 4. The names \"Xalan\" and \"Apache Software Foundation\" must\n * not be used to endorse or promote products derived from this\n * software without prior written permission. For written \n * permission, please contact apache@apache.org.\n *\n * 5. Products derived from this software may not be called \"Apache\",\n * nor may \"Apache\" appear in their name, without prior written\n * permission of the Apache Software Foundation.\n *\n * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED\n * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR\n * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF\n * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT\n * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n * ====================================================================\n *\n * This software consists of voluntary contributions made by many\n * individuals on behalf of the Apache Software Foundation and was\n * originally based on software copyright (c) 1999, International\n * Business Machines, Inc., http:\/\/www.ibm.com. For more\n * information on the Apache Software Foundation, please see\n * <http:\/\/www.apache.org\/>.\n *\/\n#if !defined(XPATHFACTORY_HEADER_GUARD_1357924680)\n#define XPATHFACTORY_HEADER_GUARD_1357924680\n\n\n\n\/\/ Base include file. Must be first.\n#include <XPath\/XPathDefinitions.hpp>\n\n\n\n#include <cassert>\n#include <functional>\n\n\n\nclass XPath;\n\n\n\nclass XALAN_XPATH_EXPORT XPathFactory\n{\npublic:\n\n\texplicit\n\tXPathFactory();\n\n\tvirtual\n\t~XPathFactory();\n\n\t\/**\n\t * Return an XPath to the factory.\n\t * \n\t * @param theXPath The XPath to be returned\n\t * @return true if the object belongs to the factory, false if not.\n\t *\/\n\tbool\n\treturnObject(const XPath*\ttheXPath)\n\t{\n\t\treturn doReturnObject(theXPath);\n\t}\n\n\t\/**\n\t * Reset the instance. This invalidates all existing instances created\n\t * with this XPathFactory.\n\t *\/\n\tvirtual void\n\treset() = 0;\n\n\t\/**\n\t * Create an XPath. The XPath instance is owned by the factory, and should\n\t * not be deleted. The factory will manage the lifetime.\n\t *\n\t * @param fOptimize true to optimize management of objects\n\t *\/\n\tvirtual XPath*\n\tcreate(bool\t\tfOptimize = true) = 0;\n\nprotected:\n\n\tvirtual bool\n\tdoReturnObject(\n\t\t\tconst XPath*\ttheXPath,\n\t\t\tbool\t\t\tfInReset = false) = 0;\n\n\t\/**\n\t *\n\t * A functor for use with stl algorithms.\n\t *\n\t *\/\n#if defined(XALAN_NO_NAMESPACES)\n\tstruct ProtectedDeleteXPathFunctor : public unary_function<const XPath*, void>\n#else\n\tstruct ProtectedDeleteXPathFunctor : public std::unary_function<const XPath*, void>\n#endif\n\t{\n\tpublic:\n\n\t\tProtectedDeleteXPathFunctor(\n\t\t\tXPathFactory&\t\ttheFactoryInstance,\n\t\t\tbool\t\t\t\tfInReset) :\n\t\t\tm_factoryInstance(theFactoryInstance),\n\t\t\tm_fInReset(fInReset)\n\t\t{\n\t\t}\n\n\t\tresult_type\n\t\toperator()(argument_type\ttheXPath) const\n\t\t{\n\t\t\tm_factoryInstance.doReturnObject(theXPath,\n\t\t\t\t\t\t\t\t\t\t\t m_fInReset);\n\t\t}\n\n\tprivate:\n\n\t\tXPathFactory&\t\tm_factoryInstance;\n\n\t\tconst bool\t\t\tm_fInReset;\n\t};\n\n\tfriend struct ProtectedDeleteXPathFunctor;\n\n};\n\n\n\n\/**\n * Manages the lifetime of an XPath instance.\n *\/\nclass XPathGuard\n{\npublic:\n\n\t\/**\n\t * Construct an XPathGuard instance from a factory object and an XPath.\n\t * \n\t * @param theFactory object that manages lifetime of XPaths\n\t * @param theXPath pointer to XPath managed\n\t *\/\n\tXPathGuard(\n\t\t\tXPathFactory&\ttheFactory,\n\t\t\tXPath*\t\t\ttheXPath) :\n\t\tm_factory(&theFactory),\n\t\tm_object(theXPath)\n\t{\n\t}\n\n\t\/\/ Note that copy construction transfers ownership, just\n\t\/\/ as std::auto_ptr.\n\tXPathGuard(XPathGuard&\ttheRHS)\n\t{\n\t\t\/\/ Release the current object...\n\t\trelease();\n\n\t\t\/\/ Copy the factory and object pointers...\n\t\tm_factory = theRHS.m_factory;\n\t\tm_object = theRHS.m_object;\n\n\t\t\/\/ The source object no longer points to\n\t\t\/\/ the object...\n\t\ttheRHS.m_factory = 0;\n\t\ttheRHS.m_object = 0;\n\t}\n\n\t~XPathGuard()\n\t{\n\t\treset();\n\t}\n\n\t\/**\n\t * Retrieve the object pointer (must not be null)\n\t * \n\t * @return pointer to XPath\n\t *\/\n\tXPath*\n\toperator->() const\n\t{\n\t\tassert(m_object != 0);\n\n\t\treturn m_object;\n\t}\n\n\t\/**\n\t * Retrieve the object pointer (may be null)\n\t * \n\t * @return pointer to XPath\n\t *\/\n\tXPath*\n\tget() const\n\t{\n\t\treturn m_object;\n\t}\n\n\t\/**\n\t * Return the referenced object to the factory and set pointers to null.\n\t *\/\n\tvoid\n\treset()\n\t{\n\t\tif (m_object != 0)\n\t\t{\n\t\t\tassert(m_factory != 0);\n\n\t\t\tm_factory->returnObject(m_object);\n\n\t\t\tm_object = 0;\n\t\t}\n\n\t\tm_factory = 0;\n\t}\n\n\t\/**\n\t * Transfers ownership of XPath to caller\n\t * \n\t * @return pointer to XPath\n\t *\/\n\tXPath*\n\trelease()\n\t{\n\t\tXPath* const\ttheTemp = m_object;\n\n\t\tm_object = 0;\n\n\t\treturn theTemp;\n\t}\n\nprivate:\n\n\tXPathGuard&\n\toperator=(const XPathGuard&);\n\n\tbool\n\toperator==(const XPathGuard&) const;\n\n\n\t\/\/ Data members...\n\tXPathFactory*\t\tm_factory;\n XPath*\t\t\tm_object;\n};\n\n#endif\t\/\/ XPATHFACTORY_HEADER_GUARD_1357924680\n<commit_msg>Added delete functor.<commit_after>\/*\n * The Apache Software License, Version 1.1\n *\n *\n * Copyright (c) 1999 The Apache Software Foundation. All rights \n * reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer. \n *\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in\n * the documentation and\/or other materials provided with the\n * distribution.\n *\n * 3. The end-user documentation included with the redistribution,\n * if any, must include the following acknowledgment: \n * \"This product includes software developed by the\n * Apache Software Foundation (http:\/\/www.apache.org\/).\"\n * Alternately, this acknowledgment may appear in the software itself,\n * if and wherever such third-party acknowledgments normally appear.\n *\n * 4. The names \"Xalan\" and \"Apache Software Foundation\" must\n * not be used to endorse or promote products derived from this\n * software without prior written permission. For written \n * permission, please contact apache@apache.org.\n *\n * 5. Products derived from this software may not be called \"Apache\",\n * nor may \"Apache\" appear in their name, without prior written\n * permission of the Apache Software Foundation.\n *\n * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED\n * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR\n * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF\n * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT\n * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n * ====================================================================\n *\n * This software consists of voluntary contributions made by many\n * individuals on behalf of the Apache Software Foundation and was\n * originally based on software copyright (c) 1999, International\n * Business Machines, Inc., http:\/\/www.ibm.com. For more\n * information on the Apache Software Foundation, please see\n * <http:\/\/www.apache.org\/>.\n *\/\n#if !defined(XPATHFACTORY_HEADER_GUARD_1357924680)\n#define XPATHFACTORY_HEADER_GUARD_1357924680\n\n\n\n\/\/ Base include file. Must be first.\n#include <XPath\/XPathDefinitions.hpp>\n\n\n\n#include <cassert>\n#include <functional>\n\n\n\nclass XPath;\n\n\n\nclass XALAN_XPATH_EXPORT XPathFactory\n{\npublic:\n\n\texplicit\n\tXPathFactory();\n\n\tvirtual\n\t~XPathFactory();\n\n\t\/**\n\t * Return an XPath to the factory.\n\t * \n\t * @param theXPath The XPath to be returned\n\t * @return true if the object belongs to the factory, false if not.\n\t *\/\n\tbool\n\treturnObject(const XPath*\ttheXPath)\n\t{\n\t\treturn doReturnObject(theXPath);\n\t}\n\n\t\/**\n\t * Reset the instance. This invalidates all existing instances created\n\t * with this XPathFactory.\n\t *\/\n\tvirtual void\n\treset() = 0;\n\n\t\/**\n\t * Create an XPath. The XPath instance is owned by the factory, and should\n\t * not be deleted. The factory will manage the lifetime.\n\t *\n\t * @param fOptimize true to optimize management of objects\n\t *\/\n\tvirtual XPath*\n\tcreate(bool\t\tfOptimize = true) = 0;\n\n\t\/**\n\t *\n\t * A functor for use with stl algorithms.\n\t *\n\t *\/\n#if defined(XALAN_NO_NAMESPACES)\n\tstruct DeleteXPathFunctor : public unary_function<const XPath*, void>\n#else\n\tstruct DeleteXPathFunctor : public std::unary_function<const XPath*, void>\n#endif\n\t{\n\tpublic:\n\n\t\tDeleteXPathFunctor(\n\t\t\tXPathFactory&\t\ttheFactoryInstance) :\n\t\t\tm_factoryInstance(theFactoryInstance)\n\t\t{\n\t\t}\n\n\t\tresult_type\n\t\toperator()(argument_type\ttheXPath) const\n\t\t{\n\t\t\tm_factoryInstance.doReturnObject(theXPath,\n\t\t\t\t\t\t\t\t\t\t\t false);\n\t\t}\n\n\tprivate:\n\n\t\tXPathFactory&\t\tm_factoryInstance;\n\t};\n\n\tfriend struct DeleteXPathFunctor;\n\nprotected:\n\n\tvirtual bool\n\tdoReturnObject(\n\t\t\tconst XPath*\ttheXPath,\n\t\t\tbool\t\t\tfInReset = false) = 0;\n\n\t\/**\n\t *\n\t * A functor for use with stl algorithms.\n\t *\n\t *\/\n#if defined(XALAN_NO_NAMESPACES)\n\tstruct ProtectedDeleteXPathFunctor : public unary_function<const XPath*, void>\n#else\n\tstruct ProtectedDeleteXPathFunctor : public std::unary_function<const XPath*, void>\n#endif\n\t{\n\tpublic:\n\n\t\tProtectedDeleteXPathFunctor(\n\t\t\tXPathFactory&\t\ttheFactoryInstance,\n\t\t\tbool\t\t\t\tfInReset) :\n\t\t\tm_factoryInstance(theFactoryInstance),\n\t\t\tm_fInReset(fInReset)\n\t\t{\n\t\t}\n\n\t\tresult_type\n\t\toperator()(argument_type\ttheXPath) const\n\t\t{\n\t\t\tm_factoryInstance.doReturnObject(theXPath,\n\t\t\t\t\t\t\t\t\t\t\t m_fInReset);\n\t\t}\n\n\tprivate:\n\n\t\tXPathFactory&\t\tm_factoryInstance;\n\n\t\tconst bool\t\t\tm_fInReset;\n\t};\n\n\tfriend struct ProtectedDeleteXPathFunctor;\n};\n\n\n\n\/**\n * Manages the lifetime of an XPath instance.\n *\/\nclass XPathGuard\n{\npublic:\n\n\t\/**\n\t * Construct an XPathGuard instance from a factory object and an XPath.\n\t * \n\t * @param theFactory object that manages lifetime of XPaths\n\t * @param theXPath pointer to XPath managed\n\t *\/\n\tXPathGuard(\n\t\t\tXPathFactory&\ttheFactory,\n\t\t\tXPath*\t\t\ttheXPath) :\n\t\tm_factory(&theFactory),\n\t\tm_object(theXPath)\n\t{\n\t}\n\n\t\/\/ Note that copy construction transfers ownership, just\n\t\/\/ as std::auto_ptr.\n\tXPathGuard(XPathGuard&\ttheRHS)\n\t{\n\t\t\/\/ Release the current object...\n\t\trelease();\n\n\t\t\/\/ Copy the factory and object pointers...\n\t\tm_factory = theRHS.m_factory;\n\t\tm_object = theRHS.m_object;\n\n\t\t\/\/ The source object no longer points to\n\t\t\/\/ the object...\n\t\ttheRHS.m_factory = 0;\n\t\ttheRHS.m_object = 0;\n\t}\n\n\t~XPathGuard()\n\t{\n\t\treset();\n\t}\n\n\t\/**\n\t * Retrieve the object pointer (must not be null)\n\t * \n\t * @return pointer to XPath\n\t *\/\n\tXPath*\n\toperator->() const\n\t{\n\t\tassert(m_object != 0);\n\n\t\treturn m_object;\n\t}\n\n\t\/**\n\t * Retrieve the object pointer (may be null)\n\t * \n\t * @return pointer to XPath\n\t *\/\n\tXPath*\n\tget() const\n\t{\n\t\treturn m_object;\n\t}\n\n\t\/**\n\t * Return the referenced object to the factory and set pointers to null.\n\t *\/\n\tvoid\n\treset()\n\t{\n\t\tif (m_object != 0)\n\t\t{\n\t\t\tassert(m_factory != 0);\n\n\t\t\tm_factory->returnObject(m_object);\n\n\t\t\tm_object = 0;\n\t\t}\n\n\t\tm_factory = 0;\n\t}\n\n\t\/**\n\t * Transfers ownership of XPath to caller\n\t * \n\t * @return pointer to XPath\n\t *\/\n\tXPath*\n\trelease()\n\t{\n\t\tXPath* const\ttheTemp = m_object;\n\n\t\tm_object = 0;\n\n\t\treturn theTemp;\n\t}\n\nprivate:\n\n\tXPathGuard&\n\toperator=(const XPathGuard&);\n\n\tbool\n\toperator==(const XPathGuard&) const;\n\n\n\t\/\/ Data members...\n\tXPathFactory*\t\tm_factory;\n XPath*\t\t\tm_object;\n};\n\n#endif\t\/\/ XPATHFACTORY_HEADER_GUARD_1357924680\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n#include <fstream>\n#include <sstream>\n#include <string>\n#include <vector>\n#include <map>\n#include \"options.h\"\n\ntypedef std::map<std::string, uint64_t> dict_t;\n\nuint64_t dict_load(const char *dict_file, dict_t &dict) {\n\tuint64_t max = 0;\n\tif (dict_file) {\n\t\tstd::ifstream dict_fs(dict_file);\n\t\tif(dict_fs) {\n\t\t\tstd::string line;\n\t\t\twhile (getline(dict_fs, line)) {\n\t\t\t\tstd::stringstream ss(line);\n\t\t\t\tstd::string token;\n\t\t\t\tuint64_t id;\n\t\t\t\tss >> token;\n\t\t\t\tss >> id;\n\t\t\t\tdict[token] = id;\n\t\t\t\tif (id > max) max = id;\n\t\t\t}\n\t\t\tdict_fs.close();\n\t\t\tmax++;\n\t\t}\n\t}\n\treturn max;\n}\n\nvoid dict_store(const char *dict_file, dict_t &dict) {\n\tif (dict_file) {\n\t\tstd::ofstream dict_fs(dict_file);\n\t\tif(dict_fs) {\n\t\t\tfor (auto elem: dict) {\n\t\t\t\tdict_fs << elem.first << \" \" << elem.second << std::endl;\n\t\t\t}\n\t\t\tdict_fs.close();\n\t\t}\n\t}\n}\n\nvoid permutate(dict_t &dict, uint64_t &id, char seperator) {\n\tstd::string line;\n\twhile (getline(std::cin, line)) {\n\t\tstd::stringstream ss(line);\n\t\tstd::string token;\n\t\twhile (getline(ss, token, seperator)) {\n\t\t\tauto itr = dict.find(token);\n\t\t\tif (itr == dict.end()) dict[token] = id++;\n\t\t\tstd::cout << dict[token] << \" \";\n\t\t}\n\t\tstd::cout << std::endl;\n\t}\n}\n\nint main (int argc, char* argv[]) {\n\tusing namespace std;\n\tusing namespace opt;\n\n\tif (chkOption(argv, argv + argc, \"-h\")) {\n\t\tcout << \"labeler [options]\" << endl\n\t\t\t<< \" -h:\\t ask for help\" << endl\n\t\t\t<< \" -d:\\t dictionary\" << endl\n\t\t\t<< \" -s:\\t seperator\" << endl;\n\t\treturn 0;\n\t}\n\n\tchar* dict_file = getOption(argv, argv + argc, \"-d\");\n\tchar* seperator = getOption(argv, argv + argc, \"-s\");\n\n\tdict_t dict;\n\tuint64_t id = dict_load(dict_file, dict);\n\n\tchar s = seperator ? seperator[0] : ' ';\n\tpermutate(dict, id, s);\n\n\tdict_store(dict_file, dict);\n\n\treturn 0;\n}\n<commit_msg>permutate on file<commit_after>#include <iostream>\n#include <fstream>\n#include <sstream>\n#include <string>\n#include <vector>\n#include <map>\n#include \"options.h\"\n\ntypedef std::map<std::string, uint64_t> dict_t;\n\nuint64_t dict_load(const char *dict_file, dict_t &dict) {\n\tuint64_t max = 0;\n\tif (dict_file) {\n\t\tstd::ifstream dict_fs(dict_file);\n\t\tif(dict_fs) {\n\t\t\tstd::string line;\n\t\t\twhile (getline(dict_fs, line)) {\n\t\t\t\tstd::stringstream ss(line);\n\t\t\t\tstd::string token;\n\t\t\t\tuint64_t id;\n\t\t\t\tss >> token;\n\t\t\t\tss >> id;\n\t\t\t\tdict[token] = id;\n\t\t\t\tif (id > max) max = id;\n\t\t\t}\n\t\t\tdict_fs.close();\n\t\t\tmax++;\n\t\t}\n\t}\n\treturn max;\n}\n\nvoid dict_store(const char *dict_file, dict_t &dict) {\n\tif (dict_file) {\n\t\tstd::ofstream dict_fs(dict_file);\n\t\tif(dict_fs) {\n\t\t\tfor (auto elem: dict) {\n\t\t\t\tdict_fs << elem.first << \" \" << elem.second << std::endl;\n\t\t\t}\n\t\t\tdict_fs.close();\n\t\t}\n\t}\n}\n\nvoid permutate(dict_t &dict, uint64_t &id, char seperator) {\n\tstd::string line;\n\twhile (getline(std::cin, line)) {\n\t\tstd::stringstream ss(line);\n\t\tstd::string token;\n\t\twhile (getline(ss, token, seperator)) {\n\t\t\tauto itr = dict.find(token);\n\t\t\tif (itr == dict.end()) dict[token] = id++;\n\t\t\tstd::cout << dict[token] << \" \";\n\t\t}\n\t\tstd::cout << std::endl;\n\t}\n}\n\nvoid permutate(const char *input_file, dict_t &dict, uint64_t &id, char seperator) {\n\tif (input_file) {\n\t\tstd::string output_file(input_file); output_file += \"-mapped\";\n\t\tstd::ifstream ifs(input_file);\n\t\tstd::ofstream ofs(output_file);\n\t\tif(ifs && ofs) {\n\t\t\tstd::string line;\n\t\t\twhile (getline(ifs, line)) {\n\t\t\t\tstd::stringstream ss(line);\n\t\t\t\tstd::string token;\n\t\t\t\twhile (getline(ss, token, seperator)) {\n\t\t\t\t\tauto itr = dict.find(token);\n\t\t\t\t\tif (itr == dict.end()) dict[token] = id++;\n\t\t\t\t\tofs << dict[token] << \" \";\n\t\t\t\t}\n\t\t\t\tofs << std::endl;\n\t\t\t}\n\t\t}\n\t\tofs.close();\n\t\tifs.close();\n\t}\n}\n\nint main(int argc, char* argv[]) {\n\tusing namespace std;\n\tusing namespace opt;\n\n\tif (chkOption(argv, argv + argc, \"-h\")) {\n\t\tcout << \"labeler [options]\" << endl\n\t\t\t<< \" -h:\\t ask for help\" << endl\n\t\t\t<< \" -d:\\t dictionary\" << endl\n\t\t\t<< \" -s:\\t seperator\" << endl\n\t\t\t<< \" -i:\\t input file\" << endl;\n\t\treturn 0;\n\t}\n\n\tchar* dict_file = getOption(argv, argv + argc, \"-d\");\n\tchar* seperator = getOption(argv, argv + argc, \"-s\");\n\tchar* input_file = getOption(argv, argv + argc, \"-i\");\n\n\tdict_t dict;\n\tuint64_t id = dict_load(dict_file, dict);\n\n\tchar s = seperator ? seperator[0] : ' ';\n\tif (input_file) permutate(input_file, dict, id, s); else permutate(dict, id, s);\n\n\tdict_store(dict_file, dict);\n\n\treturn 0;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"Crypto.h\"\r\n\r\n#include <QTimer>\r\n#include \"GlobalPasswordDialog.h\"\r\n\r\n#define CRYPTOPP_DEFAULT_NO_DLL\r\n#include <cryptopp\/dll.h>\r\n#include <cryptopp\/sha.h>\r\n#include <cryptopp\/base64.h>\r\n#include <cryptopp\/twofish.h>\r\n\r\nconst unsigned int YAPS_KEY_SIZE = CryptoPP::SHA256::DIGESTSIZE;\r\ntypedef byte Key[YAPS_KEY_SIZE];\r\n\r\nvolatile int g_volatileInt = '0';\r\n\r\nstatic int volatileInt()\r\n{\r\n if (++g_volatileInt > '9')\r\n g_volatileInt = '0';\r\n return g_volatileInt;\r\n}\r\n\r\nstatic void eraseKey(Key& key)\r\n{\r\n memset((void*)&key[0], volatileInt(), YAPS_KEY_SIZE);\r\n}\r\n\r\ntemplate<typename StringType>\r\nstatic void eraseString(StringType& s)\r\n{\r\n for (int i = 0, imax = s.size(); i < imax; i++)\r\n s[i] = volatileInt();\r\n s.clear();\r\n}\r\n\r\nstatic void makeKeyFromPassword(const QString& password, Key& key)\r\n{\r\n QByteArray passwordUtf8 = password.toUtf8();\r\n CryptoPP::SHA256 hash;\r\n hash.CalculateDigest(key, (const byte*)passwordUtf8.data(), passwordUtf8.size());\r\n}\r\n\r\nstatic void twofishEncrypt(const QString& input, QString& output, const Key& key)\r\n{\r\n std::string inputStd = input.toStdString();\r\n std::string outputStd;\r\n\r\n byte iv[CryptoPP::Twofish::BLOCKSIZE];\r\n memset(iv, 0x01, CryptoPP::Twofish::BLOCKSIZE);\r\n\r\n CryptoPP::CFB_Mode<CryptoPP::Twofish>::Encryption cipher(key, YAPS_KEY_SIZE, iv);\r\n CryptoPP::StringSource(inputStd, true,\r\n new CryptoPP::StreamTransformationFilter(cipher,\r\n new CryptoPP::Base64Encoder(\r\n new CryptoPP::StringSink(outputStd), false\r\n ) \/\/ Base64Encoder\r\n ) \/\/ StreamTransformationFilter\r\n ); \/\/ StringSource\r\n\r\n eraseString(output);\r\n output = std::move(QString::fromStdString(outputStd));\r\n eraseString(inputStd);\r\n eraseString(outputStd);\r\n}\r\n\r\nstatic void twofishDecrypt(const QString& input, QString& output, const Key& key)\r\n{\r\n std::string inputStd = input.toStdString();\r\n std::string outputStd;\r\n\r\n byte iv[CryptoPP::Twofish::BLOCKSIZE];\r\n memset(iv, 0x01, CryptoPP::Twofish::BLOCKSIZE);\r\n\r\n CryptoPP::CFB_Mode<CryptoPP::Twofish>::Decryption cipher(key, YAPS_KEY_SIZE, iv);\r\n CryptoPP::StringSource(inputStd, true,\r\n new CryptoPP::Base64Decoder(\r\n new CryptoPP::StreamTransformationFilter(cipher,\r\n new CryptoPP::StringSink(outputStd)\r\n ) \/\/ StreamTransformationFilter\r\n ) \/\/ Base64Decoder\r\n ); \/\/ StringSource\r\n\r\n eraseString(output);\r\n output = std::move(QString::fromStdString(outputStd));\r\n eraseString(inputStd);\r\n eraseString(outputStd);\r\n}\r\n\r\n\/\/static void testTwofish(const QString& password, const QString& message)\r\n\/\/{\r\n\/\/ Key key, key2;\r\n\/\/ makeKeyFromPassword(password, key);\r\n\/\/ memcpy(key2, key, sizeof(key));\r\n\/\/ QString encrypted, decrypted;\r\n\/\/ twofishEncrypt(message, encrypted, key);\r\n\/\/ twofishDecrypt(encrypted, decrypted, key2);\r\n\/\/ qDebug() << message;\r\n\/\/ qDebug() << encrypted;\r\n\/\/ qDebug() << decrypted;\r\n\/\/}\r\n\r\nstatic void generateRandomPassword(QString& password, int length)\r\n{\r\n \/\/ Generate a random block\r\n CryptoPP::AutoSeededRandomPool randomPool;\r\n CryptoPP::SecByteBlock block(length * 3);\r\n randomPool.GenerateBlock(block, block.size());\r\n\r\n \/\/ make password using base64\r\n std::string output;\r\n CryptoPP::Base64Encoder base64(new CryptoPP::StringSink(output), false);\r\n base64.Put(block, block.size());\r\n base64.MessageEnd();\r\n\r\n password = std::move(QString::fromStdString(output));\r\n eraseString(output);\r\n password.replace('+', '-');\r\n password.replace('\/', '_');\r\n}\r\n\r\nCrypto& Crypto::privateInstance()\r\n{\r\n static Crypto single;\r\n return single;\r\n}\r\n\r\nCrypto::CryptoPointer Crypto::instance()\r\n{\r\n auto& single = privateInstance();\r\n\r\n if (!single.refreshPassword())\r\n return CryptoPointer(nullptr, Crypto::unlockCrypto);\r\n\r\n return CryptoPointer(&single, Crypto::unlockCrypto);\r\n}\r\n\r\nCrypto::Crypto()\r\n{\r\n m_clearTimer = new QTimer(this);\r\n m_clearTimer->setSingleShot(true);\r\n connect(m_clearTimer, SIGNAL(timeout()), this, SLOT(clear()));\r\n}\r\n\r\nvoid Crypto::encrypt(QString& text)\r\n{\r\n Key key;\r\n makeKeyFromPassword(m_globalPassword, key);\r\n twofishEncrypt(text, text, key);\r\n eraseKey(key);\r\n}\r\n\r\nvoid Crypto::decrypt(const QString& input, QString& output)\r\n{\r\n Key key;\r\n makeKeyFromPassword(m_globalPassword, key);\r\n twofishDecrypt(input, output, key);\r\n eraseKey(key);\r\n}\r\n\r\nvoid Crypto::erase(QString& stringToErase)\r\n{\r\n eraseString(stringToErase);\r\n}\r\n\r\nvoid Crypto::generatePassword(QString& password, int length)\r\n{\r\n if (length <= 0)\r\n password.clear();\r\n else\r\n generateRandomPassword(password, length);\r\n}\r\n\r\nbool Crypto::refreshPassword()\r\n{\r\n if (m_globalPassword.isEmpty()) {\r\n GlobalPasswordDialog(m_globalPassword).exec();\r\n if (m_globalPassword.isEmpty())\r\n return false;\r\n }\r\n\r\n m_clearTimer->start(300000);\r\n emit globalPasswordRefreshed();\r\n return true;\r\n}\r\n\r\nvoid Crypto::lock()\r\n{\r\n m_locked = true;\r\n}\r\n\r\nvoid Crypto::unlock()\r\n{\r\n m_locked = false;\r\n}\r\n\r\nvoid Crypto::unlockCrypto(Crypto* crypto)\r\n{\r\n if (crypto)\r\n crypto->unlock();\r\n}\r\n\r\nvoid Crypto::clear()\r\n{\r\n if (m_locked) {\r\n m_clearTimer->start(100);\r\n } else if (!m_globalPassword.isEmpty()) {\r\n m_clearTimer->stop();\r\n eraseString(m_globalPassword);\r\n emit globalPasswordExpired();\r\n }\r\n}\r\n\r\nvoid Crypto::clearGlobalPassword()\r\n{\r\n privateInstance().clear();\r\n}\r\n<commit_msg>concatenate passwords with random noise to improve cipher strength<commit_after>#include \"Crypto.h\"\r\n\r\n#include <QTimer>\r\n#include \"GlobalPasswordDialog.h\"\r\n\r\n#define CRYPTOPP_DEFAULT_NO_DLL\r\n#include <cryptopp\/dll.h>\r\n#include <cryptopp\/sha.h>\r\n#include <cryptopp\/base64.h>\r\n#include <cryptopp\/twofish.h>\r\n\r\nconst unsigned int YAPS_KEY_SIZE = CryptoPP::SHA256::DIGESTSIZE;\r\nconst unsigned int YAPS_NOISE_SIZE = 4096;\r\ntypedef byte Key[YAPS_KEY_SIZE];\r\n\r\nvolatile int g_volatileInt = '0';\r\n\r\nstatic int volatileInt()\r\n{\r\n if (++g_volatileInt > '9')\r\n g_volatileInt = '0';\r\n return g_volatileInt;\r\n}\r\n\r\nstatic void eraseKey(Key& key)\r\n{\r\n memset((void*)&key[0], volatileInt(), YAPS_KEY_SIZE);\r\n}\r\n\r\ntemplate<typename StringType>\r\nstatic void eraseString(StringType& s)\r\n{\r\n for (int i = 0, imax = s.size(); i < imax; i++)\r\n s[i] = volatileInt();\r\n s.clear();\r\n}\r\n\r\nstatic void makeKeyFromPassword(const QString& password, Key& key)\r\n{\r\n QByteArray passwordUtf8 = password.toUtf8();\r\n CryptoPP::SHA256 hash;\r\n hash.CalculateDigest(key, (const byte*)passwordUtf8.data(), passwordUtf8.size());\r\n}\r\n\r\nstatic void surroundWithNoise(std::string& s, size_t outputSize)\r\n{\r\n if (s.size() + 1 >= outputSize)\r\n return;\r\n size_t freeSpace = outputSize - s.size();\r\n\r\n \/\/ generate random noise\r\n std::string buffer(outputSize, '\\0');\r\n CryptoPP::AutoSeededRandomPool randomPool;\r\n randomPool.GenerateBlock((byte*)&buffer[0], outputSize);\r\n \/\/ replace all zero bytes\r\n for (size_t i = 0; i < outputSize; ++i) {\r\n while (buffer[i] == '\\0')\r\n buffer[i] = (char)randomPool.GenerateByte();\r\n }\r\n\r\n \/\/ find random position for string 's'\r\n size_t randomNumber;\r\n randomPool.GenerateBlock((byte*)&randomNumber, sizeof(randomNumber));\r\n size_t right = randomNumber % (freeSpace - 1) + 1;\r\n size_t left = freeSpace - right;\r\n\r\n \/\/ copy s into buffer and put zero delimiters\r\n memcpy(&buffer[left], &s[0], s.size());\r\n buffer[outputSize - right] = '\\0';\r\n if (left > 0)\r\n buffer[left - 1] = '\\0';\r\n\r\n \/\/ replace s by buffer and erase original string\r\n buffer.swap(s);\r\n eraseString(buffer);\r\n}\r\n\r\nstatic void cleanStringFromNoise(std::string& s)\r\n{\r\n size_t right = s.find_last_of('\\0');\r\n if (right == std::string::npos || right == 0)\r\n return;\r\n\r\n size_t left = s.find_last_of('\\0', right - 1);\r\n if (left == std::string::npos)\r\n left = 0;\r\n\r\n if (right == left + 1)\r\n return;\r\n\r\n std::string buffer = s.substr(left + 1, right - left - 1);\r\n buffer.swap(s);\r\n eraseString(buffer);\r\n}\r\n\r\nstatic void twofishEncrypt(const QString& input, QString& output, const Key& key)\r\n{\r\n std::string inputStd = input.toStdString();\r\n surroundWithNoise(inputStd, YAPS_NOISE_SIZE);\r\n std::string outputStd;\r\n\r\n byte iv[CryptoPP::Twofish::BLOCKSIZE];\r\n memset(iv, 0x01, CryptoPP::Twofish::BLOCKSIZE);\r\n\r\n CryptoPP::CFB_Mode<CryptoPP::Twofish>::Encryption cipher(key, YAPS_KEY_SIZE, iv);\r\n CryptoPP::StringSource(inputStd, true,\r\n new CryptoPP::StreamTransformationFilter(cipher,\r\n new CryptoPP::Base64Encoder(\r\n new CryptoPP::StringSink(outputStd), false\r\n ) \/\/ Base64Encoder\r\n ) \/\/ StreamTransformationFilter\r\n ); \/\/ StringSource\r\n\r\n eraseString(output);\r\n output = std::move(QString::fromStdString(outputStd));\r\n eraseString(inputStd);\r\n eraseString(outputStd);\r\n}\r\n\r\nstatic void twofishDecrypt(const QString& input, QString& output, const Key& key)\r\n{\r\n std::string inputStd = input.toStdString();\r\n std::string outputStd;\r\n\r\n byte iv[CryptoPP::Twofish::BLOCKSIZE];\r\n memset(iv, 0x01, CryptoPP::Twofish::BLOCKSIZE);\r\n\r\n CryptoPP::CFB_Mode<CryptoPP::Twofish>::Decryption cipher(key, YAPS_KEY_SIZE, iv);\r\n CryptoPP::StringSource(inputStd, true,\r\n new CryptoPP::Base64Decoder(\r\n new CryptoPP::StreamTransformationFilter(cipher,\r\n new CryptoPP::StringSink(outputStd)\r\n ) \/\/ StreamTransformationFilter\r\n ) \/\/ Base64Decoder\r\n ); \/\/ StringSource\r\n\r\n cleanStringFromNoise(outputStd);\r\n eraseString(output);\r\n output = std::move(QString::fromStdString(outputStd));\r\n eraseString(inputStd);\r\n eraseString(outputStd);\r\n}\r\n\r\n\/\/static void testTwofish(const QString& password, const QString& message)\r\n\/\/{\r\n\/\/ Key key, key2;\r\n\/\/ makeKeyFromPassword(password, key);\r\n\/\/ memcpy(key2, key, sizeof(key));\r\n\/\/ QString encrypted, decrypted;\r\n\/\/ twofishEncrypt(message, encrypted, key);\r\n\/\/ twofishDecrypt(encrypted, decrypted, key2);\r\n\/\/ qDebug() << message;\r\n\/\/ qDebug() << encrypted;\r\n\/\/ qDebug() << decrypted;\r\n\/\/}\r\n\r\nstatic void generateRandomPassword(QString& password, int length)\r\n{\r\n \/\/ Generate a random block\r\n CryptoPP::AutoSeededRandomPool randomPool;\r\n CryptoPP::SecByteBlock block(length * 3);\r\n randomPool.GenerateBlock(block, block.size());\r\n\r\n \/\/ make password using base64\r\n std::string output;\r\n CryptoPP::Base64Encoder base64(new CryptoPP::StringSink(output), false);\r\n base64.Put(block, block.size());\r\n base64.MessageEnd();\r\n\r\n password = std::move(QString::fromStdString(output));\r\n eraseString(output);\r\n password.replace('+', '-');\r\n password.replace('\/', '_');\r\n}\r\n\r\nCrypto& Crypto::privateInstance()\r\n{\r\n static Crypto single;\r\n return single;\r\n}\r\n\r\nCrypto::CryptoPointer Crypto::instance()\r\n{\r\n auto& single = privateInstance();\r\n\r\n if (!single.refreshPassword())\r\n return CryptoPointer(nullptr, Crypto::unlockCrypto);\r\n\r\n return CryptoPointer(&single, Crypto::unlockCrypto);\r\n}\r\n\r\nCrypto::Crypto()\r\n{\r\n m_clearTimer = new QTimer(this);\r\n m_clearTimer->setSingleShot(true);\r\n connect(m_clearTimer, SIGNAL(timeout()), this, SLOT(clear()));\r\n}\r\n\r\nvoid Crypto::encrypt(QString& text)\r\n{\r\n Key key;\r\n makeKeyFromPassword(m_globalPassword, key);\r\n twofishEncrypt(text, text, key);\r\n eraseKey(key);\r\n}\r\n\r\nvoid Crypto::decrypt(const QString& input, QString& output)\r\n{\r\n Key key;\r\n makeKeyFromPassword(m_globalPassword, key);\r\n twofishDecrypt(input, output, key);\r\n eraseKey(key);\r\n}\r\n\r\nvoid Crypto::erase(QString& stringToErase)\r\n{\r\n eraseString(stringToErase);\r\n}\r\n\r\nvoid Crypto::generatePassword(QString& password, int length)\r\n{\r\n if (length <= 0)\r\n password.clear();\r\n else\r\n generateRandomPassword(password, length);\r\n}\r\n\r\nbool Crypto::refreshPassword()\r\n{\r\n if (m_globalPassword.isEmpty()) {\r\n GlobalPasswordDialog(m_globalPassword).exec();\r\n if (m_globalPassword.isEmpty())\r\n return false;\r\n }\r\n\r\n m_clearTimer->start(300000);\r\n emit globalPasswordRefreshed();\r\n return true;\r\n}\r\n\r\nvoid Crypto::lock()\r\n{\r\n m_locked = true;\r\n}\r\n\r\nvoid Crypto::unlock()\r\n{\r\n m_locked = false;\r\n}\r\n\r\nvoid Crypto::unlockCrypto(Crypto* crypto)\r\n{\r\n if (crypto)\r\n crypto->unlock();\r\n}\r\n\r\nvoid Crypto::clear()\r\n{\r\n if (m_locked) {\r\n m_clearTimer->start(100);\r\n } else if (!m_globalPassword.isEmpty()) {\r\n m_clearTimer->stop();\r\n eraseString(m_globalPassword);\r\n emit globalPasswordExpired();\r\n }\r\n}\r\n\r\nvoid Crypto::clearGlobalPassword()\r\n{\r\n privateInstance().clear();\r\n}\r\n<|endoftext|>"} {"text":"<commit_before>#include <QSettings>\n\n#include \"QGCSettingsWidget.h\"\n#include \"MainWindow.h\"\n#include \"ui_QGCSettingsWidget.h\"\n\n#include \"LinkManager.h\"\n#include \"MAVLinkProtocol.h\"\n#include \"MAVLinkSettingsWidget.h\"\n#include \"GAudioOutput.h\"\n\n\/\/, Qt::WindowFlags flags\n\nQGCSettingsWidget::QGCSettingsWidget(QWidget *parent, Qt::WindowFlags flags) :\n QDialog(parent, flags),\n mainWindow((MainWindow*)parent),\n ui(new Ui::QGCSettingsWidget)\n{\n ui->setupUi(this);\n\n \/\/ Center the window on the screen.\n QRect position = frameGeometry();\n position.moveCenter(QDesktopWidget().availableGeometry().center());\n move(position.topLeft());\n\n \/\/ Add all protocols\n QList<ProtocolInterface*> protocols = LinkManager::instance()->getProtocols();\n foreach (ProtocolInterface* protocol, protocols) {\n MAVLinkProtocol* mavlink = dynamic_cast<MAVLinkProtocol*>(protocol);\n if (mavlink) {\n MAVLinkSettingsWidget* msettings = new MAVLinkSettingsWidget(mavlink, this);\n ui->tabWidget->addTab(msettings, \"MAVLink\");\n }\n }\n\n this->window()->setWindowTitle(tr(\"QGroundControl Settings\"));\n\n \/\/ Settings reset\n connect(ui->resetSettingsButton, SIGNAL(clicked()), this, SLOT(resetSettings()));\n\n \/\/ Audio preferences\n ui->audioMuteCheckBox->setChecked(GAudioOutput::instance()->isMuted());\n connect(ui->audioMuteCheckBox, SIGNAL(toggled(bool)), GAudioOutput::instance(), SLOT(mute(bool)));\n connect(GAudioOutput::instance(), SIGNAL(mutedChanged(bool)), ui->audioMuteCheckBox, SLOT(setChecked(bool)));\n\n \/\/ Reconnect\n ui->reconnectCheckBox->setChecked(mainWindow->autoReconnectEnabled());\n connect(ui->reconnectCheckBox, SIGNAL(clicked(bool)), mainWindow, SLOT(enableAutoReconnect(bool)));\n\n \/\/ Low power mode\n ui->lowPowerCheckBox->setChecked(mainWindow->lowPowerModeEnabled());\n connect(ui->lowPowerCheckBox, SIGNAL(clicked(bool)), mainWindow, SLOT(enableLowPowerMode(bool)));\n\n \/\/ Dock widget title bars\n ui->titleBarCheckBox->setChecked(mainWindow->dockWidgetTitleBarsEnabled());\n connect(ui->titleBarCheckBox,SIGNAL(clicked(bool)),mainWindow,SLOT(enableDockWidgetTitleBars(bool)));\n\n \/\/ Custom mode\n\n ui->customModeComboBox->addItem(tr(\"Default: Generic MAVLink and serial links\"), MainWindow::CUSTOM_MODE_NONE);\n ui->customModeComboBox->addItem(tr(\"Wifi: Generic MAVLink, wifi or serial links\"), MainWindow::CUSTOM_MODE_WIFI);\n ui->customModeComboBox->addItem(tr(\"PX4: Optimized for PX4 Autopilot Users\"), MainWindow::CUSTOM_MODE_PX4);\n ui->customModeComboBox->addItem(tr(\"APM: Optimized for ArduPilot Users\"), MainWindow::CUSTOM_MODE_APM);\n\n ui->customModeComboBox->setCurrentIndex(ui->customModeComboBox->findData(mainWindow->getCustomMode()));\n connect(ui->customModeComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(selectCustomMode(int)));\n\n \/\/ Intialize the style UI to the proper values obtained from the MainWindow.\n MainWindow::QGC_MAINWINDOW_STYLE style = mainWindow->getStyle();\n ui->styleChooser->setCurrentIndex(style);\n if (style == MainWindow::QGC_MAINWINDOW_STYLE_DARK)\n {\n ui->styleSheetFile->setText(mainWindow->getDarkStyleSheet());\n }\n else\n {\n ui->styleSheetFile->setText(mainWindow->getLightStyleSheet());\n }\n\n \/\/ And then connect all the signals for the UI for changing styles.\n connect(ui->styleChooser, SIGNAL(currentIndexChanged(int)), this, SLOT(styleChanged(int)));\n connect(ui->styleCustomButton, SIGNAL(clicked()), this, SLOT(selectStylesheet()));\n connect(ui->styleDefaultButton, SIGNAL(clicked()), this, SLOT(setDefaultStyle()));\n connect(ui->styleSheetFile, SIGNAL(editingFinished()), this, SLOT(lineEditFinished()));\n\n \/\/ Close \/ destroy\n connect(ui->buttonBox, SIGNAL(accepted()), this, SLOT(deleteLater()));\n}\n\nQGCSettingsWidget::~QGCSettingsWidget()\n{\n delete ui;\n}\n\nvoid QGCSettingsWidget::selectStylesheet()\n{\n \/\/ Let user select style sheet. The root directory for the file picker is the user's home directory if they haven't loaded a custom style.\n \/\/ Otherwise it defaults to the directory of that custom file.\n QString findDir;\n QString oldStylesheet(ui->styleSheetFile->text());\n QFile styleSheet(oldStylesheet);\n if (styleSheet.exists() && oldStylesheet[0] != ':')\n {\n findDir = styleSheet.fileName();\n }\n else\n {\n findDir = QDir::homePath();\n }\n\n \/\/ Prompt the user to select a new style sheet. Do nothing if they cancel.\n QString newStyleFileName = QFileDialog::getOpenFileName(this, tr(\"Specify stylesheet\"), findDir, tr(\"CSS Stylesheet (*.css);;\"));\n if (newStyleFileName.isNull()) {\n return;\n }\n\n \/\/ Load the new style sheet if a valid one was selected, notifying the user\n \/\/ of an error if necessary.\n QFile newStyleFile(newStyleFileName);\n if (!newStyleFile.exists() || !updateStyle(newStyleFileName))\n {\n QMessageBox msgBox;\n msgBox.setIcon(QMessageBox::Information);\n msgBox.setText(tr(\"QGroundControl did not load a new style\"));\n msgBox.setInformativeText(tr(\"Stylesheet file %1 was not readable\").arg(newStyleFileName));\n msgBox.setStandardButtons(QMessageBox::Ok);\n msgBox.setDefaultButton(QMessageBox::Ok);\n msgBox.exec();\n }\n \/\/ And update the UI as needed.\n else\n {\n ui->styleSheetFile->setText(newStyleFileName);\n }\n}\n\nbool QGCSettingsWidget::updateStyle(QString style)\n{\n switch (ui->styleChooser->currentIndex())\n {\n case 0:\n return mainWindow->loadStyle(MainWindow::QGC_MAINWINDOW_STYLE_DARK, style);\n case 1:\n return mainWindow->loadStyle(MainWindow::QGC_MAINWINDOW_STYLE_LIGHT, style);\n default:\n return false;\n }\n}\n\nvoid QGCSettingsWidget::lineEditFinished()\n{\n QString newStyleFileName(ui->styleSheetFile->text());\n QFile newStyleFile(newStyleFileName);\n if (!newStyleFile.exists() || !updateStyle(newStyleFileName))\n {\n QMessageBox msgBox;\n msgBox.setIcon(QMessageBox::Information);\n msgBox.setText(tr(\"QGroundControl did not load a new style\"));\n msgBox.setInformativeText(tr(\"Stylesheet file %1 was not readable\").arg(newStyleFileName));\n msgBox.setStandardButtons(QMessageBox::Ok);\n msgBox.setDefaultButton(QMessageBox::Ok);\n msgBox.exec();\n }\n}\n\nvoid QGCSettingsWidget::styleChanged(int index)\n{\n if (index == 1)\n {\n ui->styleSheetFile->setText(mainWindow->getLightStyleSheet());\n mainWindow->loadStyle(MainWindow::QGC_MAINWINDOW_STYLE_LIGHT, mainWindow->getLightStyleSheet());\n }\n else\n {\n ui->styleSheetFile->setText(mainWindow->getDarkStyleSheet());\n mainWindow->loadStyle(MainWindow::QGC_MAINWINDOW_STYLE_DARK, mainWindow->getDarkStyleSheet());\n }\n}\n\nvoid QGCSettingsWidget::setDefaultStyle()\n{\n if (ui->styleChooser->currentIndex() == 1)\n {\n ui->styleSheetFile->setText(MainWindow::defaultLightStyle);\n mainWindow->loadStyle(MainWindow::QGC_MAINWINDOW_STYLE_LIGHT, MainWindow::defaultLightStyle);\n }\n else\n {\n ui->styleSheetFile->setText(MainWindow::defaultDarkStyle);\n mainWindow->loadStyle(MainWindow::QGC_MAINWINDOW_STYLE_DARK, MainWindow::defaultDarkStyle);\n }\n}\n\nvoid QGCSettingsWidget::selectCustomMode(int mode)\n{\n MainWindow::instance()->setCustomMode(static_cast<enum MainWindow::CUSTOM_MODE>(ui->customModeComboBox->itemData(mode).toInt()));\n MainWindow::instance()->showInfoMessage(tr(\"Please restart QGroundControl\"), tr(\"The optimization selection was changed. The application needs to be closed and restarted to put all optimizations into effect.\"));\n}\n\nvoid QGCSettingsWidget::resetSettings()\n{\n QSettings settings;\n settings.sync();\n settings.clear();\n \/\/ Write current application version\n settings.setValue(\"QGC_APPLICATION_VERSION\", QGC_APPLICATION_VERSION);\n settings.sync();\n}\n<commit_msg>QDesktopWidget() doesn't work in Qt5, use QApplication::desktop() instead.<commit_after>#include <QSettings>\n\n#include \"QGCSettingsWidget.h\"\n#include \"MainWindow.h\"\n#include \"ui_QGCSettingsWidget.h\"\n\n#include \"LinkManager.h\"\n#include \"MAVLinkProtocol.h\"\n#include \"MAVLinkSettingsWidget.h\"\n#include \"GAudioOutput.h\"\n\n\/\/, Qt::WindowFlags flags\n\nQGCSettingsWidget::QGCSettingsWidget(QWidget *parent, Qt::WindowFlags flags) :\n QDialog(parent, flags),\n mainWindow((MainWindow*)parent),\n ui(new Ui::QGCSettingsWidget)\n{\n ui->setupUi(this);\n\n \/\/ Center the window on the screen.\n QRect position = frameGeometry();\n position.moveCenter(QApplication::desktop()->availableGeometry().center());\n move(position.topLeft());\n\n \/\/ Add all protocols\n QList<ProtocolInterface*> protocols = LinkManager::instance()->getProtocols();\n foreach (ProtocolInterface* protocol, protocols) {\n MAVLinkProtocol* mavlink = dynamic_cast<MAVLinkProtocol*>(protocol);\n if (mavlink) {\n MAVLinkSettingsWidget* msettings = new MAVLinkSettingsWidget(mavlink, this);\n ui->tabWidget->addTab(msettings, \"MAVLink\");\n }\n }\n\n this->window()->setWindowTitle(tr(\"QGroundControl Settings\"));\n\n \/\/ Settings reset\n connect(ui->resetSettingsButton, SIGNAL(clicked()), this, SLOT(resetSettings()));\n\n \/\/ Audio preferences\n ui->audioMuteCheckBox->setChecked(GAudioOutput::instance()->isMuted());\n connect(ui->audioMuteCheckBox, SIGNAL(toggled(bool)), GAudioOutput::instance(), SLOT(mute(bool)));\n connect(GAudioOutput::instance(), SIGNAL(mutedChanged(bool)), ui->audioMuteCheckBox, SLOT(setChecked(bool)));\n\n \/\/ Reconnect\n ui->reconnectCheckBox->setChecked(mainWindow->autoReconnectEnabled());\n connect(ui->reconnectCheckBox, SIGNAL(clicked(bool)), mainWindow, SLOT(enableAutoReconnect(bool)));\n\n \/\/ Low power mode\n ui->lowPowerCheckBox->setChecked(mainWindow->lowPowerModeEnabled());\n connect(ui->lowPowerCheckBox, SIGNAL(clicked(bool)), mainWindow, SLOT(enableLowPowerMode(bool)));\n\n \/\/ Dock widget title bars\n ui->titleBarCheckBox->setChecked(mainWindow->dockWidgetTitleBarsEnabled());\n connect(ui->titleBarCheckBox,SIGNAL(clicked(bool)),mainWindow,SLOT(enableDockWidgetTitleBars(bool)));\n\n \/\/ Custom mode\n\n ui->customModeComboBox->addItem(tr(\"Default: Generic MAVLink and serial links\"), MainWindow::CUSTOM_MODE_NONE);\n ui->customModeComboBox->addItem(tr(\"Wifi: Generic MAVLink, wifi or serial links\"), MainWindow::CUSTOM_MODE_WIFI);\n ui->customModeComboBox->addItem(tr(\"PX4: Optimized for PX4 Autopilot Users\"), MainWindow::CUSTOM_MODE_PX4);\n ui->customModeComboBox->addItem(tr(\"APM: Optimized for ArduPilot Users\"), MainWindow::CUSTOM_MODE_APM);\n\n ui->customModeComboBox->setCurrentIndex(ui->customModeComboBox->findData(mainWindow->getCustomMode()));\n connect(ui->customModeComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(selectCustomMode(int)));\n\n \/\/ Intialize the style UI to the proper values obtained from the MainWindow.\n MainWindow::QGC_MAINWINDOW_STYLE style = mainWindow->getStyle();\n ui->styleChooser->setCurrentIndex(style);\n if (style == MainWindow::QGC_MAINWINDOW_STYLE_DARK)\n {\n ui->styleSheetFile->setText(mainWindow->getDarkStyleSheet());\n }\n else\n {\n ui->styleSheetFile->setText(mainWindow->getLightStyleSheet());\n }\n\n \/\/ And then connect all the signals for the UI for changing styles.\n connect(ui->styleChooser, SIGNAL(currentIndexChanged(int)), this, SLOT(styleChanged(int)));\n connect(ui->styleCustomButton, SIGNAL(clicked()), this, SLOT(selectStylesheet()));\n connect(ui->styleDefaultButton, SIGNAL(clicked()), this, SLOT(setDefaultStyle()));\n connect(ui->styleSheetFile, SIGNAL(editingFinished()), this, SLOT(lineEditFinished()));\n\n \/\/ Close \/ destroy\n connect(ui->buttonBox, SIGNAL(accepted()), this, SLOT(deleteLater()));\n}\n\nQGCSettingsWidget::~QGCSettingsWidget()\n{\n delete ui;\n}\n\nvoid QGCSettingsWidget::selectStylesheet()\n{\n \/\/ Let user select style sheet. The root directory for the file picker is the user's home directory if they haven't loaded a custom style.\n \/\/ Otherwise it defaults to the directory of that custom file.\n QString findDir;\n QString oldStylesheet(ui->styleSheetFile->text());\n QFile styleSheet(oldStylesheet);\n if (styleSheet.exists() && oldStylesheet[0] != ':')\n {\n findDir = styleSheet.fileName();\n }\n else\n {\n findDir = QDir::homePath();\n }\n\n \/\/ Prompt the user to select a new style sheet. Do nothing if they cancel.\n QString newStyleFileName = QFileDialog::getOpenFileName(this, tr(\"Specify stylesheet\"), findDir, tr(\"CSS Stylesheet (*.css);;\"));\n if (newStyleFileName.isNull()) {\n return;\n }\n\n \/\/ Load the new style sheet if a valid one was selected, notifying the user\n \/\/ of an error if necessary.\n QFile newStyleFile(newStyleFileName);\n if (!newStyleFile.exists() || !updateStyle(newStyleFileName))\n {\n QMessageBox msgBox;\n msgBox.setIcon(QMessageBox::Information);\n msgBox.setText(tr(\"QGroundControl did not load a new style\"));\n msgBox.setInformativeText(tr(\"Stylesheet file %1 was not readable\").arg(newStyleFileName));\n msgBox.setStandardButtons(QMessageBox::Ok);\n msgBox.setDefaultButton(QMessageBox::Ok);\n msgBox.exec();\n }\n \/\/ And update the UI as needed.\n else\n {\n ui->styleSheetFile->setText(newStyleFileName);\n }\n}\n\nbool QGCSettingsWidget::updateStyle(QString style)\n{\n switch (ui->styleChooser->currentIndex())\n {\n case 0:\n return mainWindow->loadStyle(MainWindow::QGC_MAINWINDOW_STYLE_DARK, style);\n case 1:\n return mainWindow->loadStyle(MainWindow::QGC_MAINWINDOW_STYLE_LIGHT, style);\n default:\n return false;\n }\n}\n\nvoid QGCSettingsWidget::lineEditFinished()\n{\n QString newStyleFileName(ui->styleSheetFile->text());\n QFile newStyleFile(newStyleFileName);\n if (!newStyleFile.exists() || !updateStyle(newStyleFileName))\n {\n QMessageBox msgBox;\n msgBox.setIcon(QMessageBox::Information);\n msgBox.setText(tr(\"QGroundControl did not load a new style\"));\n msgBox.setInformativeText(tr(\"Stylesheet file %1 was not readable\").arg(newStyleFileName));\n msgBox.setStandardButtons(QMessageBox::Ok);\n msgBox.setDefaultButton(QMessageBox::Ok);\n msgBox.exec();\n }\n}\n\nvoid QGCSettingsWidget::styleChanged(int index)\n{\n if (index == 1)\n {\n ui->styleSheetFile->setText(mainWindow->getLightStyleSheet());\n mainWindow->loadStyle(MainWindow::QGC_MAINWINDOW_STYLE_LIGHT, mainWindow->getLightStyleSheet());\n }\n else\n {\n ui->styleSheetFile->setText(mainWindow->getDarkStyleSheet());\n mainWindow->loadStyle(MainWindow::QGC_MAINWINDOW_STYLE_DARK, mainWindow->getDarkStyleSheet());\n }\n}\n\nvoid QGCSettingsWidget::setDefaultStyle()\n{\n if (ui->styleChooser->currentIndex() == 1)\n {\n ui->styleSheetFile->setText(MainWindow::defaultLightStyle);\n mainWindow->loadStyle(MainWindow::QGC_MAINWINDOW_STYLE_LIGHT, MainWindow::defaultLightStyle);\n }\n else\n {\n ui->styleSheetFile->setText(MainWindow::defaultDarkStyle);\n mainWindow->loadStyle(MainWindow::QGC_MAINWINDOW_STYLE_DARK, MainWindow::defaultDarkStyle);\n }\n}\n\nvoid QGCSettingsWidget::selectCustomMode(int mode)\n{\n MainWindow::instance()->setCustomMode(static_cast<enum MainWindow::CUSTOM_MODE>(ui->customModeComboBox->itemData(mode).toInt()));\n MainWindow::instance()->showInfoMessage(tr(\"Please restart QGroundControl\"), tr(\"The optimization selection was changed. The application needs to be closed and restarted to put all optimizations into effect.\"));\n}\n\nvoid QGCSettingsWidget::resetSettings()\n{\n QSettings settings;\n settings.sync();\n settings.clear();\n \/\/ Write current application version\n settings.setValue(\"QGC_APPLICATION_VERSION\", QGC_APPLICATION_VERSION);\n settings.sync();\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ -*- Mode: C++; tab-width: 2; -*-\n\/\/ vi: set ts=2:\n\/\/\n\n\/* CrystalGenerator.C\n* 2012 Stefan Nickels \n*\/\n\n\/\/ ----------------------------------------------------\n\/\/ $Maintainer: Stefan Nickels $\n\/\/ $Authors: Stefan Nickels $\n\/\/ ----------------------------------------------------\n\n#include <BALL\/XRAY\/crystalGenerator.h>\n#include <BALL\/XRAY\/crystalInfo.h>\n#include <BALL\/FORMAT\/PDBFile.h>\n#include <BALL\/KERNEL\/system.h>\n#include <BALL\/FORMAT\/commandlineParser.h>\n#include <BALL\/FORMAT\/parameters.h>\n#include <BALL\/FORMAT\/parameterSection.h>\n#include <BALL\/SYSTEM\/path.h>\n\n#include \"version.h\"\n\nusing namespace std;\nusing namespace BALL;\n\nint main(int argc, char* argv[])\n{\n\t\/\/ instantiate CommandlineParser object supplying\n\t\/\/ - tool name\n\t\/\/ - short description\n\t\/\/ - version string\n\t\/\/ - build date\n\t\/\/ - category\n\tCommandlineParser parpars(\"X-Ray CrystalGenerator\", \"creates crystals\", \"VERSION\", String(__DATE__), \"Structure Creation\");\n\t\n parpars.registerParameter(\"i\", \"input pdb file\", INFILE, true);\n\tparpars.registerParameter(\"o\", \"output pdb file\", OUTFILE, true);\n\n \/\/ the space group\n\tparpars.registerParameter(\"sg\", \"space group symbol in Herman-Mauguin notation\", STRING, true);\n \n\tCrystalGenerator generator;\n\t\n\t\/\/ Fill the space group symbol list\n\tgenerator.getSpaceGroupFilename();\n\tPath path;\n\tString filename = generator.getSpaceGroupFilename();\n\tString filepath = path.find(filename);\n\tif (filepath == \"\")\n\t{\n\t\t\tthrow Exception::FileNotFound(__FILE__, __LINE__, filename);\n\t}\n\n\tParameters* param = new Parameters(filepath);\n\tif (!param->isValid()) return false;\n\n\tParameterSection* pms = new ParameterSection();\n\tpms->extractSection(*param, \"SpacegroupList\");\t\n\tif (!pms->isValid()) return false;\n\t\n\tdelete param;\n\t\t\t\n\tlist<String> space_groups;\n\tfor (Position i = 0; i < pms->getNumberOfKeys(); i++)\n\t{\n\t\tspace_groups.push_back(pms->getValue(i,0).c_str());\n\t}\n\t\n\tdelete pms;\n\t\t\t\t\t\n\tparpars.setParameterRestrictions(\"sg\", space_groups);\n\t\n \/\/ the cell axes\n parpars.registerParameter(\"axis_a\", \"cell axis a\", DOUBLE, false);\n\t\/\/parpars.setParameterRestrictions(\"axis_a\", 0, 100);\n\tparpars.registerParameter(\"axis_b\", \"cell axis b\", DOUBLE, false);\n\t\/\/parpars.setParameterRestrictions(\"axis_b\", 0, 100);\n\tparpars.registerParameter(\"axis_c\", \"cell axis c\", DOUBLE, false);\n\t\/\/parpars.setParameterRestrictions(\"axis_c\", 0, 100);\n \n \/\/ the cell angles\n\tparpars.registerParameter(\"angle_alpha\", \"cell angle alpha\", DOUBLE, false);\n\tparpars.setParameterRestrictions(\"angle_alpha\", 0., 359.);\n\tparpars.registerParameter(\"angle_beta\", \"cell angle beta\", DOUBLE, false);\n\tparpars.setParameterRestrictions(\"angle_beta\", 0., 359.);\n\tparpars.registerParameter(\"angle_gamma\", \"cell angle gamma\", DOUBLE, false);\n\tparpars.setParameterRestrictions(\"angle_gamma\", 0., 359.);\n\t\n \/\/ the unit cell indices to create\n parpars.registerParameter(\"from_uc_a\", \"from unit cell index a\", INT, true);\n\tparpars.setParameterRestrictions(\"from_uc_a\", 0, 9);\n\tparpars.registerParameter(\"from_uc_b\", \"from unit cell index b\", INT, true);\n\tparpars.setParameterRestrictions(\"from_uc_b\", 0, 9);\n\tparpars.registerParameter(\"from_uc_c\", \"from unit cell index c\", INT, true);\n\tparpars.setParameterRestrictions(\"from_uc_c\", 0, 9);\n\tparpars.registerParameter(\"to_uc_a\", \"to unit cell index a\", INT, true);\n\tparpars.setParameterRestrictions(\"from_uc_a\", 0, 9);\n\tparpars.registerParameter(\"to_uc_b\", \"to unit cell index b\", INT, true);\n\tparpars.setParameterRestrictions(\"from_uc_b\", 0, 9);\n\tparpars.registerParameter(\"to_uc_c\", \"to unit cell index c\", INT, true);\n\tparpars.setParameterRestrictions(\"from_uc_c\", 0, 9);\n \n String man = \"TODO: Manual\";\n\tparpars.setToolManual(man);\n\t\n parpars.setSupportedFormats(\"i\",\"pdb\");\n parpars.setSupportedFormats(\"o\",\"pdb\");\n\n\tparpars.parse(argc, argv);\n \n PDBFile file;\n file.open(parpars.get(\"i\"));\n System system;\n file >> system;\n\n generator.setSystem(&system);\n\n boost::shared_ptr<CrystalInfo> ci_ptr(new CrystalInfo());\n ci_ptr->setSpaceGroup(parpars.get(\"sg\"));\n\tci_ptr->setCellEdgeLengthA(parpars.get(\"axis_a\").toDouble());\n\tci_ptr->setCellEdgeLengthB(parpars.get(\"axis_b\").toDouble());\n\tci_ptr->setCellEdgeLengthC(parpars.get(\"axis_c\").toDouble());\n\tci_ptr->setCellAngleAlpha(Angle(parpars.get(\"angle_alpha\").toDouble(), false));\n\tci_ptr->setCellAngleBeta(Angle(parpars.get(\"angle_beta\").toDouble(), false));\n\t\n ci_ptr->setCellAngleGamma(Angle(parpars.get(\"angle_gamma\").toDouble(), false));\n \n\tgenerator.setCrystalInfo(ci_ptr);\n\t\n\tSystem* output = 0;\n\tstd::list<System*> crystal = generator.generatePacking(parpars.get(\"from_uc_a\").toInt(), parpars.get(\"to_uc_a\").toInt(),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t parpars.get(\"from_uc_b\").toInt(), parpars.get(\"to_uc_b\").toInt(),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t parpars.get(\"from_uc_c\").toInt(), parpars.get(\"to_uc_c\").toInt());\n\toutput = new System();\n\toutput->setName(system.getName());\n\tstd::list<System*>::iterator it_c = crystal.begin();\t\n\n\tfor(;it_c != crystal.end(); it_c++)\n\t{\n\t\toutput->spliceAfter(**it_c);\n\t}\n\n\tPDBFile outfile(parpars.get(\"o\"), ios::out); \n\toutfile << *output;\n\toutfile.close();\n\n\tLog << \"seems to be done.\" << endl;\n\n}\n\n<commit_msg>Fixed CrystalGenerator tool for Galaxy<commit_after>\/\/ -*- Mode: C++; tab-width: 2; -*-\n\/\/ vi: set ts=2:\n\/\/\n\n\/* CrystalGenerator.C\n* 2012 Stefan Nickels \n*\/\n\n\/\/ ----------------------------------------------------\n\/\/ $Maintainer: Stefan Nickels $\n\/\/ $Authors: Stefan Nickels $\n\/\/ ----------------------------------------------------\n\n#include <BALL\/XRAY\/crystalGenerator.h>\n#include <BALL\/XRAY\/crystalInfo.h>\n#include <BALL\/FORMAT\/PDBFile.h>\n#include <BALL\/KERNEL\/system.h>\n#include <BALL\/FORMAT\/commandlineParser.h>\n#include <BALL\/FORMAT\/parameters.h>\n#include <BALL\/FORMAT\/parameterSection.h>\n#include <BALL\/SYSTEM\/path.h>\n\n#include \"version.h\"\n\nusing namespace std;\nusing namespace BALL;\n\nint main(int argc, char* argv[])\n{\n\t\/\/ instantiate CommandlineParser object supplying\n\t\/\/ - tool name\n\t\/\/ - short description\n\t\/\/ - version string\n\t\/\/ - build date\n\t\/\/ - category\n\tCommandlineParser parpars(\"CrystalGenerator\", \"creates crystals\", \"VERSION\", String(__DATE__), \"Structure Creation\");\n\t\n parpars.registerParameter(\"i\", \"input pdb file\", INFILE, true);\n\tparpars.registerParameter(\"o\", \"output pdb file\", OUTFILE, true);\n\n \/\/ the space group\n\tparpars.registerParameter(\"sg\", \"space group symbol in Herman-Mauguin notation\", STRING, true);\n \n\tCrystalGenerator generator;\n\t\n\t\/\/ Fill the space group symbol list\n\tgenerator.getSpaceGroupFilename();\n\tPath path;\n\tString filename = generator.getSpaceGroupFilename();\n\tString filepath = path.find(filename);\n\tif (filepath == \"\")\n\t{\n\t\t\tthrow Exception::FileNotFound(__FILE__, __LINE__, filename);\n\t}\n\n\tParameters* param = new Parameters(filepath);\n\tif (!param->isValid()) return false;\n\n\tParameterSection* pms = new ParameterSection();\n\tpms->extractSection(*param, \"SpacegroupList\");\t\n\tif (!pms->isValid()) return false;\n\t\n\tdelete param;\n\t\t\t\n\tlist<String> space_groups;\n\tfor (Position i = 0; i < pms->getNumberOfKeys(); i++)\n\t{\n\t\tspace_groups.push_back(pms->getValue(i,0).c_str());\n\t}\n\t\n\tdelete pms;\n\t\t\t\t\t\n\tparpars.setParameterRestrictions(\"sg\", space_groups);\n\t\n \/\/ the cell axes\n parpars.registerParameter(\"axis_a\", \"cell axis a\", DOUBLE, false);\n\t\/\/parpars.setParameterRestrictions(\"axis_a\", 0, 100);\n\tparpars.registerParameter(\"axis_b\", \"cell axis b\", DOUBLE, false);\n\t\/\/parpars.setParameterRestrictions(\"axis_b\", 0, 100);\n\tparpars.registerParameter(\"axis_c\", \"cell axis c\", DOUBLE, false);\n\t\/\/parpars.setParameterRestrictions(\"axis_c\", 0, 100);\n \n \/\/ the cell angles\n\tparpars.registerParameter(\"angle_alpha\", \"cell angle alpha\", DOUBLE, false);\n\tparpars.setParameterRestrictions(\"angle_alpha\", 0., 359.);\n\tparpars.registerParameter(\"angle_beta\", \"cell angle beta\", DOUBLE, false);\n\tparpars.setParameterRestrictions(\"angle_beta\", 0., 359.);\n\tparpars.registerParameter(\"angle_gamma\", \"cell angle gamma\", DOUBLE, false);\n\tparpars.setParameterRestrictions(\"angle_gamma\", 0., 359.);\n\t\n \/\/ the unit cell indices to create\n parpars.registerParameter(\"from_uc_a\", \"from unit cell index a\", INT, true);\n\tparpars.setParameterRestrictions(\"from_uc_a\", 0, 9);\n\tparpars.registerParameter(\"from_uc_b\", \"from unit cell index b\", INT, true);\n\tparpars.setParameterRestrictions(\"from_uc_b\", 0, 9);\n\tparpars.registerParameter(\"from_uc_c\", \"from unit cell index c\", INT, true);\n\tparpars.setParameterRestrictions(\"from_uc_c\", 0, 9);\n\tparpars.registerParameter(\"to_uc_a\", \"to unit cell index a\", INT, true);\n\tparpars.setParameterRestrictions(\"from_uc_a\", 0, 9);\n\tparpars.registerParameter(\"to_uc_b\", \"to unit cell index b\", INT, true);\n\tparpars.setParameterRestrictions(\"from_uc_b\", 0, 9);\n\tparpars.registerParameter(\"to_uc_c\", \"to unit cell index c\", INT, true);\n\tparpars.setParameterRestrictions(\"from_uc_c\", 0, 9);\n \n String man = \"TODO: Manual\";\n\tparpars.setToolManual(man);\n\t\n parpars.setSupportedFormats(\"i\",\"pdb\");\n parpars.setSupportedFormats(\"o\",\"pdb\");\n\n\tparpars.parse(argc, argv);\n \n PDBFile file;\n file.open(parpars.get(\"i\"));\n System system;\n file >> system;\n\n generator.setSystem(&system);\n\n boost::shared_ptr<CrystalInfo> ci_ptr(new CrystalInfo());\n ci_ptr->setSpaceGroup(parpars.get(\"sg\"));\n\tci_ptr->setCellEdgeLengthA(parpars.get(\"axis_a\").toDouble());\n\tci_ptr->setCellEdgeLengthB(parpars.get(\"axis_b\").toDouble());\n\tci_ptr->setCellEdgeLengthC(parpars.get(\"axis_c\").toDouble());\n\tci_ptr->setCellAngleAlpha(Angle(parpars.get(\"angle_alpha\").toDouble(), false));\n\tci_ptr->setCellAngleBeta(Angle(parpars.get(\"angle_beta\").toDouble(), false));\n\t\n ci_ptr->setCellAngleGamma(Angle(parpars.get(\"angle_gamma\").toDouble(), false));\n \n\tgenerator.setCrystalInfo(ci_ptr);\n\t\n\tSystem* output = 0;\n\tstd::list<System*> crystal = generator.generatePacking(parpars.get(\"from_uc_a\").toInt(), parpars.get(\"to_uc_a\").toInt(),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t parpars.get(\"from_uc_b\").toInt(), parpars.get(\"to_uc_b\").toInt(),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t parpars.get(\"from_uc_c\").toInt(), parpars.get(\"to_uc_c\").toInt());\n\toutput = new System();\n\toutput->setName(system.getName());\n\tstd::list<System*>::iterator it_c = crystal.begin();\t\n\n\tfor(;it_c != crystal.end(); it_c++)\n\t{\n\t\toutput->spliceAfter(**it_c);\n\t}\n\n\tPDBFile outfile(parpars.get(\"o\"), ios::out); \n\toutfile << *output;\n\toutfile.close();\n\n\tLog << \"seems to be done.\" << endl;\n\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/* Copyright © 2001-2015, Canal TP and\/or its affiliates. All rights reserved.\n \nThis file is part of Navitia,\n the software to build cool stuff with public transport.\n \nHope you'll enjoy and contribute to this project,\n powered by Canal TP (www.canaltp.fr).\nHelp us simplify mobility and open public transport:\n a non ending quest to the responsive locomotion way of traveling!\n \nLICENCE: This program is free software; you can redistribute it and\/or modify\nit under the terms of the GNU Affero General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n \nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU Affero General Public License for more details.\n \nYou should have received a copy of the GNU Affero General Public License\nalong with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n \nStay tuned using\ntwitter @navitia \nIRC #navitia on freenode\nhttps:\/\/groups.google.com\/d\/forum\/navitia\nwww.navitia.io\n*\/\n\n#include \"journey_pattern_container.h\"\n#include \"type\/pt_data.h\"\n#include <type_traits>\n\nnamespace navitia { namespace routing {\n\nnamespace nt = navitia::type;\n\ntemplate<> std::vector<const nt::DiscreteVehicleJourney*>&\nJourneyPattern::get_vjs<nt::DiscreteVehicleJourney>() {\n return discrete_vjs;\n}\ntemplate<> std::vector<const nt::FrequencyVehicleJourney*>&\nJourneyPattern::get_vjs<nt::FrequencyVehicleJourney>() {\n return freq_vjs;\n}\n\nvoid JourneyPatternContainer::load(const nt::PT_Data& pt_data) {\n map.clear();\n jps.clear();\n jpps.clear();\n jps_from_route.assign(pt_data.routes);\n jp_from_vj.assign(pt_data.vehicle_journeys);\n for (const auto* jp: pt_data.journey_patterns) {\n for (const auto& vj: jp->discrete_vehicle_journey_list) { add_vj(*vj); }\n for (const auto& vj: jp->frequency_vehicle_journey_list) { add_vj(*vj); }\n }\n}\n\nconst JppIdx& JourneyPatternContainer::get_jpp(const type::StopTime& st) const {\n const auto& jp = get(jp_from_vj[VjIdx(*st.vehicle_journey)]);\n return jp.jpps.at(st.journey_pattern_point->order);\n}\n\n\ntemplate<typename VJ>\nJourneyPatternContainer::JpKey JourneyPatternContainer::make_key(const VJ& vj) {\n JourneyPatternContainer::JpKey key;\n key.route_idx = RouteIdx(*vj.journey_pattern->route);\n key.is_freq = std::is_same<VJ, nt::FrequencyVehicleJourney>::value;\n for (const auto& st: vj.stop_time_list) {\n key.jpp_keys.emplace_back(SpIdx(*st.journey_pattern_point->stop_point),\n st.local_traffic_zone,\n st.properties);\n }\n return key;\n}\n\nstatic bool st_are_equals(const nt::VehicleJourney& vj1, const nt::VehicleJourney& vj2) {\n for (auto it1 = vj1.stop_time_list.begin(), it2 = vj2.stop_time_list.begin();\n it1 != vj1.stop_time_list.end() && it2 != vj2.stop_time_list.end();\n ++it1, ++it2) {\n if (it1->arrival_time != it2->arrival_time || it1->departure_time != it2->departure_time) {\n return false;\n }\n }\n return true;\n}\n\ntemplate<typename VJ> static bool\novertake(const VJ& vj, const std::vector<const VJ*> vjs) {\n if (vj.stop_time_list.empty()) { return false; }\n for (const VJ* cur_vj: vjs) {\n assert(vj.stop_time_list.size() == cur_vj->stop_time_list.size());\n\n \/\/ if the validity patterns do not overlap, it can't overtake\n if ((vj.validity_pattern->days & cur_vj->validity_pattern->days).none() &&\n (vj.adapted_validity_pattern->days & cur_vj->adapted_validity_pattern->days).none()) {\n continue;\n }\n\n \/\/ if the stop times are the same, they don't overtake\n if (st_are_equals(vj, *cur_vj)) { continue; }\n\n const bool vj_is_first =\n vj.stop_time_list.front().departure_time < cur_vj->stop_time_list.front().departure_time;\n const VJ& vj1 = vj_is_first ? vj : *cur_vj;\n const VJ& vj2 = vj_is_first ? *cur_vj : vj;\n for (auto it1 = vj1.stop_time_list.begin(), it2 = vj2.stop_time_list.begin();\n it1 != vj1.stop_time_list.end() && it2 != vj2.stop_time_list.end();\n ++it1, ++it2) {\n if (it1->arrival_time >= it2->arrival_time ||\n it1->departure_time >= it2->departure_time) {\n return true;\n } \n }\n }\n return false;\n}\n\ntemplate<typename VJ>\nvoid JourneyPatternContainer::add_vj(const VJ& vj) {\n \/\/ Get the existing jps according to the key.\n const auto key = make_key(vj);\n auto& jps = map[key];\n\n \/\/ The vj must not overtake the other vj in its jp, thus searching\n \/\/ for one satisfying jp.\n for (auto& jp_idx: jps) {\n auto& jp = get_mut(jp_idx);\n auto& vjs = jp.template get_vjs<VJ>();\n if (! overtake(vj, vjs)) {\n \/\/ Great, found a valid jp, inserting and stopping\n vjs.push_back(&vj);\n jp_from_vj[VjIdx(vj)] = jp_idx;\n return;\n }\n }\n\n \/\/ We did not find a jp, creating a new one.\n const auto jp_idx = make_jp(key);\n jps.push_back(jp_idx);\n jps_from_route[key.route_idx].push_back(jp_idx);\n get_mut(jp_idx).template get_vjs<VJ>().push_back(&vj);\n jp_from_vj[VjIdx(vj)] = jp_idx;\n}\n\nJpIdx JourneyPatternContainer::make_jp(const JpKey& key) {\n const auto jp_idx = JpIdx(jps.size());\n jps.emplace_back();\n auto& jp = jps.back();\n jp.route_idx = key.route_idx;\n uint16_t order = 0;\n for (const auto& jpp_key: key.jpp_keys) {\n jp.jpps.push_back(make_jpp(jp_idx, jpp_key.sp_idx, order++));\n }\n return jp_idx;\n}\n\nJppIdx JourneyPatternContainer::make_jpp(const JpIdx& jp_idx, const SpIdx& sp_idx, uint16_t order) {\n const auto idx = JppIdx(jpps.size());\n jpps.push_back({jp_idx, sp_idx, order});\n return idx;\n}\n\nJourneyPattern& JourneyPatternContainer::get_mut(const JpIdx& idx) {\n assert(idx.val < jps.size());\n return jps[idx.val];\n}\n\n\n}}\/\/ namespace navitia::routing\n<commit_msg>routing: fix after rebase<commit_after>\/* Copyright © 2001-2015, Canal TP and\/or its affiliates. All rights reserved.\n \nThis file is part of Navitia,\n the software to build cool stuff with public transport.\n \nHope you'll enjoy and contribute to this project,\n powered by Canal TP (www.canaltp.fr).\nHelp us simplify mobility and open public transport:\n a non ending quest to the responsive locomotion way of traveling!\n \nLICENCE: This program is free software; you can redistribute it and\/or modify\nit under the terms of the GNU Affero General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n \nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU Affero General Public License for more details.\n \nYou should have received a copy of the GNU Affero General Public License\nalong with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n \nStay tuned using\ntwitter @navitia \nIRC #navitia on freenode\nhttps:\/\/groups.google.com\/d\/forum\/navitia\nwww.navitia.io\n*\/\n\n#include \"journey_pattern_container.h\"\n#include \"type\/pt_data.h\"\n#include <type_traits>\n#include <boost\/algorithm\/cxx11\/all_of.hpp>\n\nnamespace navitia { namespace routing {\n\nnamespace nt = navitia::type;\n\ntemplate<> std::vector<const nt::DiscreteVehicleJourney*>&\nJourneyPattern::get_vjs<nt::DiscreteVehicleJourney>() {\n return discrete_vjs;\n}\ntemplate<> std::vector<const nt::FrequencyVehicleJourney*>&\nJourneyPattern::get_vjs<nt::FrequencyVehicleJourney>() {\n return freq_vjs;\n}\n\nvoid JourneyPatternContainer::load(const nt::PT_Data& pt_data) {\n map.clear();\n jps.clear();\n jpps.clear();\n jps_from_route.assign(pt_data.routes);\n jp_from_vj.assign(pt_data.vehicle_journeys);\n for (const auto* jp: pt_data.journey_patterns) {\n for (const auto& vj: jp->discrete_vehicle_journey_list) { add_vj(*vj); }\n for (const auto& vj: jp->frequency_vehicle_journey_list) { add_vj(*vj); }\n }\n}\n\nconst JppIdx& JourneyPatternContainer::get_jpp(const type::StopTime& st) const {\n const auto& jp = get(jp_from_vj[VjIdx(*st.vehicle_journey)]);\n return jp.jpps.at(st.journey_pattern_point->order);\n}\n\n\ntemplate<typename VJ>\nJourneyPatternContainer::JpKey JourneyPatternContainer::make_key(const VJ& vj) {\n JourneyPatternContainer::JpKey key;\n key.route_idx = RouteIdx(*vj.journey_pattern->route);\n key.is_freq = std::is_same<VJ, nt::FrequencyVehicleJourney>::value;\n for (const auto& st: vj.stop_time_list) {\n key.jpp_keys.emplace_back(SpIdx(*st.journey_pattern_point->stop_point),\n st.local_traffic_zone,\n st.properties);\n }\n return key;\n}\n\nstatic bool st_are_equals(const nt::VehicleJourney& vj1, const nt::VehicleJourney& vj2) {\n for (auto it1 = vj1.stop_time_list.begin(), it2 = vj2.stop_time_list.begin();\n it1 != vj1.stop_time_list.end() && it2 != vj2.stop_time_list.end();\n ++it1, ++it2) {\n if (it1->arrival_time != it2->arrival_time || it1->departure_time != it2->departure_time) {\n return false;\n }\n }\n return true;\n}\n\ntemplate<typename VJ> static bool\novertake(const VJ& vj, const std::vector<const VJ*> vjs) {\n if (vj.stop_time_list.empty()) { return false; }\n for (const VJ* cur_vj: vjs) {\n assert(vj.stop_time_list.size() == cur_vj->stop_time_list.size());\n\n \/\/ if the validity patterns do not overlap, it can't overtake\n const auto levels = {nt::RTLevel::Theoric, nt::RTLevel::Adapted, nt::RTLevel::RealTime};\n const bool dont_overlap = boost::algorithm::all_of(levels, [&](nt::RTLevel lvl) {\n if (vj.validity_patterns[lvl] == nullptr) { return true; }\n if (cur_vj->validity_patterns[lvl] == nullptr) { return true; }\n return (vj.validity_patterns[lvl]->days & cur_vj->validity_patterns[lvl]->days).none();\n });\n if (dont_overlap) { continue; }\n\n \/\/ if the stop times are the same, they don't overtake\n if (st_are_equals(vj, *cur_vj)) { continue; }\n\n const bool vj_is_first =\n vj.stop_time_list.front().departure_time < cur_vj->stop_time_list.front().departure_time;\n const VJ& vj1 = vj_is_first ? vj : *cur_vj;\n const VJ& vj2 = vj_is_first ? *cur_vj : vj;\n for (auto it1 = vj1.stop_time_list.begin(), it2 = vj2.stop_time_list.begin();\n it1 != vj1.stop_time_list.end() && it2 != vj2.stop_time_list.end();\n ++it1, ++it2) {\n if (it1->arrival_time >= it2->arrival_time ||\n it1->departure_time >= it2->departure_time) {\n return true;\n } \n }\n }\n return false;\n}\n\ntemplate<typename VJ>\nvoid JourneyPatternContainer::add_vj(const VJ& vj) {\n \/\/ Get the existing jps according to the key.\n const auto key = make_key(vj);\n auto& jps = map[key];\n\n \/\/ The vj must not overtake the other vj in its jp, thus searching\n \/\/ for one satisfying jp.\n for (auto& jp_idx: jps) {\n auto& jp = get_mut(jp_idx);\n auto& vjs = jp.template get_vjs<VJ>();\n if (! overtake(vj, vjs)) {\n \/\/ Great, found a valid jp, inserting and stopping\n vjs.push_back(&vj);\n jp_from_vj[VjIdx(vj)] = jp_idx;\n return;\n }\n }\n\n \/\/ We did not find a jp, creating a new one.\n const auto jp_idx = make_jp(key);\n jps.push_back(jp_idx);\n jps_from_route[key.route_idx].push_back(jp_idx);\n get_mut(jp_idx).template get_vjs<VJ>().push_back(&vj);\n jp_from_vj[VjIdx(vj)] = jp_idx;\n}\n\nJpIdx JourneyPatternContainer::make_jp(const JpKey& key) {\n const auto jp_idx = JpIdx(jps.size());\n jps.emplace_back();\n auto& jp = jps.back();\n jp.route_idx = key.route_idx;\n uint16_t order = 0;\n for (const auto& jpp_key: key.jpp_keys) {\n jp.jpps.push_back(make_jpp(jp_idx, jpp_key.sp_idx, order++));\n }\n return jp_idx;\n}\n\nJppIdx JourneyPatternContainer::make_jpp(const JpIdx& jp_idx, const SpIdx& sp_idx, uint16_t order) {\n const auto idx = JppIdx(jpps.size());\n jpps.push_back({jp_idx, sp_idx, order});\n return idx;\n}\n\nJourneyPattern& JourneyPatternContainer::get_mut(const JpIdx& idx) {\n assert(idx.val < jps.size());\n return jps[idx.val];\n}\n\n\n}}\/\/ namespace navitia::routing\n<|endoftext|>"} {"text":"<commit_before>\/*ckwg +5\n * Copyright 2011-2012 by Kitware, Inc. All Rights Reserved. Please refer to\n * KITWARE_LICENSE.TXT for licensing information, or contact General Counsel,\n * Kitware, Inc., 28 Corporate Drive, Clifton Park, NY 12065.\n *\/\n\n#include \"edge.h\"\n#include \"edge_exception.h\"\n\n#include \"stamp.h\"\n#include \"types.h\"\n\n#include <boost\/thread\/condition_variable.hpp>\n#include <boost\/thread\/locks.hpp>\n#include <boost\/thread\/mutex.hpp>\n#include <boost\/weak_ptr.hpp>\n\n#include <queue>\n\n\/**\n * \\file edge.cxx\n *\n * \\brief Implementation of the \\link vistk::edge edge\\endlink class.\n *\/\n\nnamespace vistk\n{\n\nconfig::key_t const edge::config_dependency = config::key_t(\"_dependency\");\nconfig::key_t const edge::config_capacity = config::key_t(\"capacity\");\n\nclass edge::priv\n{\n public:\n priv(bool depends_, size_t capacity_);\n ~priv();\n\n typedef boost::weak_ptr<process> process_ref_t;\n\n bool has_data() const;\n bool full_of_data() const;\n void complete_check() const;\n\n bool const depends;\n size_t const capacity;\n bool downstream_complete;\n\n process_ref_t upstream;\n process_ref_t downstream;\n\n std::queue<edge_datum_t> q;\n\n boost::condition_variable cond_have_data;\n boost::condition_variable cond_have_space;\n\n mutable boost::mutex mutex;\n mutable boost::mutex complete_mutex;\n};\n\nedge\n::edge(config_t const& config)\n{\n if (!config)\n {\n throw null_edge_config_exception();\n }\n\n bool const depends = config->get_value<bool>(config_dependency, true);\n size_t const capacity = config->get_value<size_t>(config_capacity, 0);\n\n d.reset(new priv(depends, capacity));\n}\n\nedge\n::~edge()\n{\n}\n\nbool\nedge\n::makes_dependency() const\n{\n return d->depends;\n}\n\nbool\nedge\n::has_data() const\n{\n boost::mutex::scoped_lock const lock(d->mutex);\n\n (void)lock;\n\n return d->has_data();\n}\n\nbool\nedge\n::full_of_data() const\n{\n boost::mutex::scoped_lock const lock(d->mutex);\n\n (void)lock;\n\n return d->full_of_data();\n}\n\nsize_t\nedge\n::datum_count() const\n{\n boost::mutex::scoped_lock const lock(d->mutex);\n\n (void)lock;\n\n return d->q.size();\n}\n\nvoid\nedge\n::push_datum(edge_datum_t const& datum)\n{\n {\n boost::mutex::scoped_lock const lock(d->complete_mutex);\n\n (void)lock;\n\n if (d->downstream_complete)\n {\n return;\n }\n }\n\n {\n boost::mutex::scoped_lock lock(d->mutex);\n\n while (d->full_of_data())\n {\n d->cond_have_space.wait(lock);\n }\n\n d->q.push(datum);\n }\n\n d->cond_have_data.notify_one();\n}\n\nedge_datum_t\nedge\n::get_datum()\n{\n d->complete_check();\n\n edge_datum_t dat;\n\n {\n boost::mutex::scoped_lock lock(d->mutex);\n\n while (!d->has_data())\n {\n d->cond_have_data.wait(lock);\n }\n\n dat = d->q.front();\n\n d->q.pop();\n }\n\n d->cond_have_space.notify_one();\n\n return dat;\n}\n\nedge_datum_t\nedge\n::peek_datum()\n{\n d->complete_check();\n\n boost::mutex::scoped_lock lock(d->mutex);\n\n while (!d->has_data())\n {\n d->cond_have_data.wait(lock);\n }\n\n return d->q.front();\n}\n\nvoid\nedge\n::pop_datum()\n{\n d->complete_check();\n\n boost::mutex::scoped_lock lock(d->mutex);\n\n while (!d->has_data())\n {\n d->cond_have_data.wait(lock);\n }\n\n d->q.pop();\n\n d->cond_have_space.notify_one();\n}\n\nvoid\nedge\n::mark_downstream_as_complete()\n{\n boost::mutex::scoped_lock complete_lock(d->complete_mutex);\n\n (void)complete_lock;\n\n d->downstream_complete = true;\n\n boost::mutex::scoped_lock const lock(d->mutex);\n\n (void)lock;\n\n while (d->q.size())\n {\n d->q.pop();\n }\n}\n\nbool\nedge\n::is_downstream_complete() const\n{\n boost::mutex::scoped_lock const lock(d->complete_mutex);\n\n (void)lock;\n\n return d->downstream_complete;\n}\n\nvoid\nedge\n::set_upstream_process(process_t process)\n{\n if (!process)\n {\n throw null_process_connection_exception();\n }\n\n if (!d->upstream.expired())\n {\n process_t const up = d->upstream.lock();\n\n throw input_already_connected_exception(up->name(), process->name());\n }\n\n d->upstream = process;\n}\n\nvoid\nedge\n::set_downstream_process(process_t process)\n{\n if (!process)\n {\n throw null_process_connection_exception();\n }\n\n if (!d->downstream.expired())\n {\n process_t const down = d->downstream.lock();\n\n throw output_already_connected_exception(down->name(), process->name());\n }\n\n d->downstream = process;\n}\n\nbool\noperator == (edge_datum_t const& a, edge_datum_t const& b)\n{\n return (( a.get<0>() == b.get<0>()) &&\n (*a.get<1>() == *b.get<1>()));\n}\n\nedge::priv\n::priv(bool depends_, size_t capacity_)\n : depends(depends_)\n , capacity(capacity_)\n , downstream_complete(false)\n{\n}\n\nedge::priv\n::~priv()\n{\n}\n\nbool\nedge::priv\n::has_data() const\n{\n return (q.size() != 0);\n}\n\nbool\nedge::priv\n::full_of_data() const\n{\n if (!capacity)\n {\n return false;\n }\n\n return (q.size() == capacity);\n}\n\nvoid\nedge::priv\n::complete_check() const\n{\n boost::mutex::scoped_lock const lock(complete_mutex);\n\n (void)lock;\n\n if (downstream_complete)\n {\n throw datum_requested_after_complete();\n }\n}\n\n}\n<commit_msg>Narrow the scope of the lock<commit_after>\/*ckwg +5\n * Copyright 2011-2012 by Kitware, Inc. All Rights Reserved. Please refer to\n * KITWARE_LICENSE.TXT for licensing information, or contact General Counsel,\n * Kitware, Inc., 28 Corporate Drive, Clifton Park, NY 12065.\n *\/\n\n#include \"edge.h\"\n#include \"edge_exception.h\"\n\n#include \"stamp.h\"\n#include \"types.h\"\n\n#include <boost\/thread\/condition_variable.hpp>\n#include <boost\/thread\/locks.hpp>\n#include <boost\/thread\/mutex.hpp>\n#include <boost\/weak_ptr.hpp>\n\n#include <queue>\n\n\/**\n * \\file edge.cxx\n *\n * \\brief Implementation of the \\link vistk::edge edge\\endlink class.\n *\/\n\nnamespace vistk\n{\n\nconfig::key_t const edge::config_dependency = config::key_t(\"_dependency\");\nconfig::key_t const edge::config_capacity = config::key_t(\"capacity\");\n\nclass edge::priv\n{\n public:\n priv(bool depends_, size_t capacity_);\n ~priv();\n\n typedef boost::weak_ptr<process> process_ref_t;\n\n bool has_data() const;\n bool full_of_data() const;\n void complete_check() const;\n\n bool const depends;\n size_t const capacity;\n bool downstream_complete;\n\n process_ref_t upstream;\n process_ref_t downstream;\n\n std::queue<edge_datum_t> q;\n\n boost::condition_variable cond_have_data;\n boost::condition_variable cond_have_space;\n\n mutable boost::mutex mutex;\n mutable boost::mutex complete_mutex;\n};\n\nedge\n::edge(config_t const& config)\n{\n if (!config)\n {\n throw null_edge_config_exception();\n }\n\n bool const depends = config->get_value<bool>(config_dependency, true);\n size_t const capacity = config->get_value<size_t>(config_capacity, 0);\n\n d.reset(new priv(depends, capacity));\n}\n\nedge\n::~edge()\n{\n}\n\nbool\nedge\n::makes_dependency() const\n{\n return d->depends;\n}\n\nbool\nedge\n::has_data() const\n{\n boost::mutex::scoped_lock const lock(d->mutex);\n\n (void)lock;\n\n return d->has_data();\n}\n\nbool\nedge\n::full_of_data() const\n{\n boost::mutex::scoped_lock const lock(d->mutex);\n\n (void)lock;\n\n return d->full_of_data();\n}\n\nsize_t\nedge\n::datum_count() const\n{\n boost::mutex::scoped_lock const lock(d->mutex);\n\n (void)lock;\n\n return d->q.size();\n}\n\nvoid\nedge\n::push_datum(edge_datum_t const& datum)\n{\n {\n boost::mutex::scoped_lock const lock(d->complete_mutex);\n\n (void)lock;\n\n if (d->downstream_complete)\n {\n return;\n }\n }\n\n {\n boost::mutex::scoped_lock lock(d->mutex);\n\n while (d->full_of_data())\n {\n d->cond_have_space.wait(lock);\n }\n\n d->q.push(datum);\n }\n\n d->cond_have_data.notify_one();\n}\n\nedge_datum_t\nedge\n::get_datum()\n{\n d->complete_check();\n\n edge_datum_t dat;\n\n {\n boost::mutex::scoped_lock lock(d->mutex);\n\n while (!d->has_data())\n {\n d->cond_have_data.wait(lock);\n }\n\n dat = d->q.front();\n\n d->q.pop();\n }\n\n d->cond_have_space.notify_one();\n\n return dat;\n}\n\nedge_datum_t\nedge\n::peek_datum()\n{\n d->complete_check();\n\n boost::mutex::scoped_lock lock(d->mutex);\n\n while (!d->has_data())\n {\n d->cond_have_data.wait(lock);\n }\n\n return d->q.front();\n}\n\nvoid\nedge\n::pop_datum()\n{\n d->complete_check();\n\n {\n boost::mutex::scoped_lock lock(d->mutex);\n\n while (!d->has_data())\n {\n d->cond_have_data.wait(lock);\n }\n\n d->q.pop();\n }\n\n d->cond_have_space.notify_one();\n}\n\nvoid\nedge\n::mark_downstream_as_complete()\n{\n boost::mutex::scoped_lock complete_lock(d->complete_mutex);\n\n (void)complete_lock;\n\n d->downstream_complete = true;\n\n boost::mutex::scoped_lock const lock(d->mutex);\n\n (void)lock;\n\n while (d->q.size())\n {\n d->q.pop();\n }\n}\n\nbool\nedge\n::is_downstream_complete() const\n{\n boost::mutex::scoped_lock const lock(d->complete_mutex);\n\n (void)lock;\n\n return d->downstream_complete;\n}\n\nvoid\nedge\n::set_upstream_process(process_t process)\n{\n if (!process)\n {\n throw null_process_connection_exception();\n }\n\n if (!d->upstream.expired())\n {\n process_t const up = d->upstream.lock();\n\n throw input_already_connected_exception(up->name(), process->name());\n }\n\n d->upstream = process;\n}\n\nvoid\nedge\n::set_downstream_process(process_t process)\n{\n if (!process)\n {\n throw null_process_connection_exception();\n }\n\n if (!d->downstream.expired())\n {\n process_t const down = d->downstream.lock();\n\n throw output_already_connected_exception(down->name(), process->name());\n }\n\n d->downstream = process;\n}\n\nbool\noperator == (edge_datum_t const& a, edge_datum_t const& b)\n{\n return (( a.get<0>() == b.get<0>()) &&\n (*a.get<1>() == *b.get<1>()));\n}\n\nedge::priv\n::priv(bool depends_, size_t capacity_)\n : depends(depends_)\n , capacity(capacity_)\n , downstream_complete(false)\n{\n}\n\nedge::priv\n::~priv()\n{\n}\n\nbool\nedge::priv\n::has_data() const\n{\n return (q.size() != 0);\n}\n\nbool\nedge::priv\n::full_of_data() const\n{\n if (!capacity)\n {\n return false;\n }\n\n return (q.size() == capacity);\n}\n\nvoid\nedge::priv\n::complete_check() const\n{\n boost::mutex::scoped_lock const lock(complete_mutex);\n\n (void)lock;\n\n if (downstream_complete)\n {\n throw datum_requested_after_complete();\n }\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/**************************************************************************\n**\n** This file is part of Qt Creator\n**\n** Copyright (c) 2009 Nokia Corporation and\/or its subsidiary(-ies).\n**\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n** Commercial Usage\n**\n** Licensees holding valid Qt Commercial licenses may use this file in\n** accordance with the Qt Commercial License Agreement provided with the\n** Software or, alternatively, in accordance with the terms contained in\n** a written agreement between you and Nokia.\n**\n** GNU Lesser General Public License Usage\n**\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** If you are unsure which license is appropriate for your use, please\n** contact the sales department at http:\/\/qt.nokia.com\/contact.\n**\n**************************************************************************\/\n\n#include \"s60devicerunconfigurationwidget.h\"\n#include \"s60devicerunconfiguration.h\"\n#include \"s60runconfigbluetoothstarter.h\"\n#include \"bluetoothlistener_gui.h\"\n#include \"s60manager.h\"\n#include \"launcher.h\"\n#include \"bluetoothlistener.h\"\n#include \"bluetoothlistener_gui.h\"\n#include \"serialdevicelister.h\"\n\n#include <utils\/detailswidget.h>\n#include <utils\/qtcassert.h>\n#include <utils\/pathchooser.h>\n\n#include <QtCore\/QTimer>\n#include <QtGui\/QRadioButton>\n#include <QtGui\/QLabel>\n#include <QtGui\/QLineEdit>\n#include <QtGui\/QComboBox>\n#include <QtGui\/QVBoxLayout>\n#include <QtGui\/QHBoxLayout>\n#include <QtGui\/QFormLayout>\n#include <QtGui\/QToolButton>\n#include <QtGui\/QStyle>\n#include <QtGui\/QApplication>\n#include <QtGui\/QSpacerItem>\n\nQ_DECLARE_METATYPE(Qt4ProjectManager::Internal::CommunicationDevice)\n\nnamespace Qt4ProjectManager {\nnamespace Internal {\n\nS60DeviceRunConfigurationWidget::S60DeviceRunConfigurationWidget(\n S60DeviceRunConfiguration *runConfiguration,\n QWidget *parent)\n : QWidget(parent),\n m_runConfiguration(runConfiguration),\n m_detailsWidget(new Utils::DetailsWidget),\n m_serialPortsCombo(new QComboBox),\n m_nameLineEdit(new QLineEdit(m_runConfiguration->name())),\n m_sisxFileLabel(new QLabel(m_runConfiguration->basePackageFilePath() + QLatin1String(\".sisx\"))),\n m_deviceInfoButton(new QToolButton),\n m_deviceInfoDescriptionLabel(new QLabel(tr(\"Device:\"))),\n m_deviceInfoLabel(new QLabel),\n m_infoTimeOutTimer(0)\n{\n QVBoxLayout *mainBoxLayout = new QVBoxLayout();\n mainBoxLayout->setMargin(0);\n setLayout(mainBoxLayout);\n mainBoxLayout->addWidget(m_detailsWidget);\n QWidget *detailsContainer = new QWidget;\n m_detailsWidget->setWidget(detailsContainer);\n\n QVBoxLayout *detailsBoxLayout = new QVBoxLayout();\n detailsBoxLayout->setMargin(0);\n detailsContainer->setLayout(detailsBoxLayout);\n\n QFormLayout *formLayout = new QFormLayout();\n formLayout->setMargin(0);\n detailsBoxLayout->addLayout(formLayout);\n \/\/ Name control\n QLabel *nameLabel = new QLabel(tr(\"Name:\"));\n nameLabel->setBuddy(m_nameLineEdit);\n formLayout->addRow(nameLabel, m_nameLineEdit);\n formLayout->addRow(tr(\"Install File:\"), m_sisxFileLabel);\n\n updateSerialDevices(); \n connect(S60Manager::instance()->serialDeviceLister(), SIGNAL(updated()),\n this, SLOT(updateSerialDevices()));\n \/\/ Serial devices control\n connect(m_serialPortsCombo, SIGNAL(activated(int)), this, SLOT(setSerialPort(int)));\n QHBoxLayout *serialPortHBoxLayout = new QHBoxLayout;\n serialPortHBoxLayout->addWidget(m_serialPortsCombo);\n serialPortHBoxLayout->addSpacerItem(new QSpacerItem(0, 0, QSizePolicy::MinimumExpanding, QSizePolicy::Ignored));\n\n formLayout->addRow(tr(\"Device on Serial Port:\"), serialPortHBoxLayout);\n\n \/\/ Device Info with button. Widgets are enabled in above call to updateSerialDevices()\n QHBoxLayout *infoHBoxLayout = new QHBoxLayout;\n m_deviceInfoLabel->setWordWrap(true);\n infoHBoxLayout->addWidget(m_deviceInfoLabel);\n infoHBoxLayout->addSpacerItem(new QSpacerItem(0, 0, QSizePolicy::MinimumExpanding, QSizePolicy::Ignored));\n infoHBoxLayout->addWidget(m_deviceInfoButton);\n m_deviceInfoButton->setIcon(qApp->style()->standardIcon(QStyle::SP_MessageBoxInformation));\n m_deviceInfoButton->setToolTip(tr(\"Queries the device for information\"));\n connect(m_deviceInfoButton, SIGNAL(clicked()), this, SLOT(updateDeviceInfo()));\n formLayout->addRow(m_deviceInfoDescriptionLabel, infoHBoxLayout);\n\n \/\/ Signature\/certificate stuff.\n QWidget *signatureWidget = new QWidget();\n QVBoxLayout *layout = new QVBoxLayout();\n signatureWidget->setLayout(layout);\n detailsBoxLayout->addWidget(signatureWidget);\n QRadioButton *selfSign = new QRadioButton(tr(\"Self-signed certificate\"));\n QHBoxLayout *customHBox = new QHBoxLayout();\n customHBox->setMargin(0);\n QVBoxLayout *radioLayout = new QVBoxLayout();\n QRadioButton *customSignature = new QRadioButton();\n radioLayout->addWidget(customSignature);\n radioLayout->addStretch(10);\n customHBox->addLayout(radioLayout);\n QFormLayout *customLayout = new QFormLayout();\n customLayout->setMargin(0);\n customLayout->setLabelAlignment(Qt::AlignRight);\n Utils::PathChooser *signaturePath = new Utils::PathChooser();\n signaturePath->setExpectedKind(Utils::PathChooser::File);\n signaturePath->setPromptDialogTitle(tr(\"Choose certificate file (.cer)\"));\n customLayout->addRow(new QLabel(tr(\"Custom certificate:\")), signaturePath);\n Utils::PathChooser *keyPath = new Utils::PathChooser();\n keyPath->setExpectedKind(Utils::PathChooser::File);\n keyPath->setPromptDialogTitle(tr(\"Choose key file (.key \/ .pem)\"));\n customLayout->addRow(new QLabel(tr(\"Key file:\")), keyPath);\n customHBox->addLayout(customLayout);\n customHBox->addStretch(10);\n layout->addWidget(selfSign);\n layout->addLayout(customHBox);\n layout->addStretch(10);\n\n switch (m_runConfiguration->signingMode()) {\n case S60DeviceRunConfiguration::SignSelf:\n selfSign->setChecked(true);\n break;\n case S60DeviceRunConfiguration::SignCustom:\n customSignature->setChecked(true);\n break;\n }\n\n signaturePath->setPath(m_runConfiguration->customSignaturePath());\n keyPath->setPath(m_runConfiguration->customKeyPath());\n\n connect(m_nameLineEdit, SIGNAL(textEdited(QString)),\n this, SLOT(nameEdited(QString)));\n connect(m_runConfiguration, SIGNAL(targetInformationChanged()),\n this, SLOT(updateTargetInformation()));\n connect(selfSign, SIGNAL(toggled(bool)), this, SLOT(selfSignToggled(bool)));\n connect(customSignature, SIGNAL(toggled(bool)), this, SLOT(customSignatureToggled(bool)));\n connect(signaturePath, SIGNAL(changed(QString)), this, SLOT(signaturePathChanged(QString)));\n connect(keyPath, SIGNAL(changed(QString)), this, SLOT(keyPathChanged(QString)));\n updateSummary();\n}\n\nvoid S60DeviceRunConfigurationWidget::updateSerialDevices()\n{\n m_serialPortsCombo->clear();\n clearDeviceInfo();\n const QString previousRunConfigurationPortName = m_runConfiguration->serialPortName();\n const QList<CommunicationDevice> devices = S60Manager::instance()->serialDeviceLister()->communicationDevices();\n int newIndex = -1;\n for (int i = 0; i < devices.size(); ++i) {\n const CommunicationDevice &device = devices.at(i);\n m_serialPortsCombo->addItem(device.friendlyName, qVariantFromValue(device));\n if (device.portName == previousRunConfigurationPortName)\n newIndex = i;\n }\n \/\/ Set new index: prefer to keep old or set to 0, if available.\n if (newIndex == -1 && !devices.empty())\n newIndex = 0;\n m_serialPortsCombo->setCurrentIndex(newIndex);\n if (newIndex == -1) {\n m_deviceInfoButton->setEnabled(false);\n m_runConfiguration->setSerialPortName(QString());\n } else {\n m_deviceInfoButton->setEnabled(true);\n const QString newPortName = device(newIndex).portName;\n if (newPortName != previousRunConfigurationPortName)\n m_runConfiguration->setSerialPortName(newPortName);\n }\n}\n\nCommunicationDevice S60DeviceRunConfigurationWidget::device(int i) const\n{\n if (i >= 0) {\n const QVariant data = m_serialPortsCombo->itemData(i);\n if (qVariantCanConvert<Qt4ProjectManager::Internal::CommunicationDevice>(data))\n return qVariantValue<Qt4ProjectManager::Internal::CommunicationDevice>(data);\n }\n return CommunicationDevice(SerialPortCommunication);\n}\n\nCommunicationDevice S60DeviceRunConfigurationWidget::currentDevice() const\n{\n return device(m_serialPortsCombo->currentIndex());\n}\n\nvoid S60DeviceRunConfigurationWidget::nameEdited(const QString &text)\n{\n m_runConfiguration->setName(text);\n}\n\nvoid S60DeviceRunConfigurationWidget::updateTargetInformation()\n{\n m_sisxFileLabel->setText(m_runConfiguration->basePackageFilePath() + QLatin1String(\".sisx\"));\n}\n\nvoid S60DeviceRunConfigurationWidget::setSerialPort(int index)\n{\n const CommunicationDevice d = device(index);\n m_runConfiguration->setSerialPortName(d.portName);\n m_runConfiguration->setCommunicationType(d.type);\n m_deviceInfoButton->setEnabled(index >= 0);\n clearDeviceInfo();\n updateSummary();\n}\n\nvoid S60DeviceRunConfigurationWidget::selfSignToggled(bool toggle)\n{\n if (toggle)\n m_runConfiguration->setSigningMode(S60DeviceRunConfiguration::SignSelf);\n updateSummary();\n}\n\nvoid S60DeviceRunConfigurationWidget::customSignatureToggled(bool toggle)\n{\n if (toggle)\n m_runConfiguration->setSigningMode(S60DeviceRunConfiguration::SignCustom);\n updateSummary();\n}\n\nvoid S60DeviceRunConfigurationWidget::signaturePathChanged(const QString &path)\n{\n m_runConfiguration->setCustomSignaturePath(path);\n updateSummary();\n}\n\nvoid S60DeviceRunConfigurationWidget::keyPathChanged(const QString &path)\n{\n m_runConfiguration->setCustomKeyPath(path);\n updateSummary();\n}\n\nvoid S60DeviceRunConfigurationWidget::updateSummary()\n{\n \/\/: Summary text of S60 device run configuration\n const QString device = m_serialPortsCombo->currentIndex() != -1 ?\n m_serialPortsCombo->currentText() :\n tr(\"<No Device>\");\n const QString signature = m_runConfiguration->signingMode() == S60DeviceRunConfiguration::SignCustom ?\n tr(\"(custom certificate)\") :\n tr(\"(self-signed certificate)\"); \n m_detailsWidget->setSummaryText(tr(\"Summary: Run on '%1' %2\").arg(device, signature));\n}\n\nvoid S60DeviceRunConfigurationWidget::clearDeviceInfo()\n{\n \/\/ Restore text & color\n m_deviceInfoLabel->clear();\n m_deviceInfoLabel->setStyleSheet(QString());\n}\n\nvoid S60DeviceRunConfigurationWidget::setDeviceInfoLabel(const QString &message, bool isError)\n{\n m_deviceInfoLabel->setStyleSheet(isError ?\n QString(QLatin1String(\"background-color: red;\")) :\n QString());\n m_deviceInfoLabel->setText(message);\n m_deviceInfoLabel->adjustSize();\n}\n\nvoid S60DeviceRunConfigurationWidget::updateDeviceInfo()\n{\n QString message;\n setDeviceInfoLabel(tr(\"Connecting...\"));\n const bool ok = getDeviceInfo(&message);\n setDeviceInfoLabel(message, !ok);\n}\n\nbool S60DeviceRunConfigurationWidget::getDeviceInfo(QString *message)\n{\n message->clear();\n \/\/ Do a launcher run with the ping protocol. Instantiate launcher on heap\n \/\/ as not to introduce delays when destructing a device with timeout\n trk::Launcher *launcher = new trk::Launcher(trk::Launcher::ActionPingOnly, QSharedPointer<trk::TrkDevice>(), this);\n const CommunicationDevice commDev = currentDevice();\n launcher->setSerialFrame(commDev.type == SerialPortCommunication);\n launcher->setTrkServerName(commDev.portName);\n \/\/ Prompt the user to start\n if (commDev.type == BlueToothCommunication) {\n S60RunConfigBluetoothStarter starter(launcher->trkDevice());\n starter.setDevice(launcher->trkServerName());\n const trk::StartBluetoothGuiResult src = trk::startBluetoothGui(starter, this, message);\n switch (src) {\n case trk::BluetoothGuiConnected:\n break;\n case trk::BluetoothGuiCanceled:\n launcher->deleteLater();\n return true;\n case trk::BluetoothGuiError:\n launcher->deleteLater();\n return false;\n };\n }\n if (!launcher->startServer(message)) {\n launcher->deleteLater();\n return false;\n }\n \/\/ Set up event loop in the foreground with a timer to quit in case of timeout.\n QEventLoop eventLoop;\n if (!m_infoTimeOutTimer) {\n m_infoTimeOutTimer = new QTimer(this);\n m_infoTimeOutTimer->setInterval(3000);\n m_infoTimeOutTimer->setSingleShot(true);\n }\n connect(m_infoTimeOutTimer, SIGNAL(timeout()), &eventLoop, SLOT(quit()));\n connect(launcher, SIGNAL(finished()), &eventLoop, SLOT(quit()));\n \/\/ Go!\n QApplication::setOverrideCursor(Qt::BusyCursor);\n m_infoTimeOutTimer->start();\n eventLoop.exec(QEventLoop::ExcludeUserInputEvents);\n m_infoTimeOutTimer->disconnect();\n QApplication::restoreOverrideCursor();\n \/\/ Anything received?\n *message = launcher->deviceDescription();\n launcher->deleteLater();\n if (message->isEmpty()) {\n *message = tr(\"A timeout occurred while querying the device. Check whether Trk is running\");\n return false;\n }\n return true;\n}\n\n} \/\/ namespace Internal\n} \/\/ namespace Qt4ProjectManager\n<commit_msg>S60: Fix the run configuration status label<commit_after>\/**************************************************************************\n**\n** This file is part of Qt Creator\n**\n** Copyright (c) 2009 Nokia Corporation and\/or its subsidiary(-ies).\n**\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n** Commercial Usage\n**\n** Licensees holding valid Qt Commercial licenses may use this file in\n** accordance with the Qt Commercial License Agreement provided with the\n** Software or, alternatively, in accordance with the terms contained in\n** a written agreement between you and Nokia.\n**\n** GNU Lesser General Public License Usage\n**\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** If you are unsure which license is appropriate for your use, please\n** contact the sales department at http:\/\/qt.nokia.com\/contact.\n**\n**************************************************************************\/\n\n#include \"s60devicerunconfigurationwidget.h\"\n#include \"s60devicerunconfiguration.h\"\n#include \"s60runconfigbluetoothstarter.h\"\n#include \"bluetoothlistener_gui.h\"\n#include \"s60manager.h\"\n#include \"launcher.h\"\n#include \"bluetoothlistener.h\"\n#include \"bluetoothlistener_gui.h\"\n#include \"serialdevicelister.h\"\n\n#include <utils\/detailswidget.h>\n#include <utils\/qtcassert.h>\n#include <utils\/pathchooser.h>\n\n#include <QtCore\/QTimer>\n#include <QtGui\/QRadioButton>\n#include <QtGui\/QLabel>\n#include <QtGui\/QLineEdit>\n#include <QtGui\/QComboBox>\n#include <QtGui\/QVBoxLayout>\n#include <QtGui\/QHBoxLayout>\n#include <QtGui\/QFormLayout>\n#include <QtGui\/QToolButton>\n#include <QtGui\/QStyle>\n#include <QtGui\/QApplication>\n#include <QtGui\/QSpacerItem>\n\nQ_DECLARE_METATYPE(Qt4ProjectManager::Internal::CommunicationDevice)\n\nnamespace Qt4ProjectManager {\nnamespace Internal {\n\nS60DeviceRunConfigurationWidget::S60DeviceRunConfigurationWidget(\n S60DeviceRunConfiguration *runConfiguration,\n QWidget *parent)\n : QWidget(parent),\n m_runConfiguration(runConfiguration),\n m_detailsWidget(new Utils::DetailsWidget),\n m_serialPortsCombo(new QComboBox),\n m_nameLineEdit(new QLineEdit(m_runConfiguration->name())),\n m_sisxFileLabel(new QLabel(m_runConfiguration->basePackageFilePath() + QLatin1String(\".sisx\"))),\n m_deviceInfoButton(new QToolButton),\n m_deviceInfoDescriptionLabel(new QLabel(tr(\"Device:\"))),\n m_deviceInfoLabel(new QLabel),\n m_infoTimeOutTimer(0)\n{\n QVBoxLayout *mainBoxLayout = new QVBoxLayout();\n mainBoxLayout->setMargin(0);\n setLayout(mainBoxLayout);\n mainBoxLayout->addWidget(m_detailsWidget);\n QWidget *detailsContainer = new QWidget;\n m_detailsWidget->setWidget(detailsContainer);\n\n QVBoxLayout *detailsBoxLayout = new QVBoxLayout();\n detailsBoxLayout->setMargin(0);\n detailsContainer->setLayout(detailsBoxLayout);\n\n QFormLayout *formLayout = new QFormLayout();\n formLayout->setMargin(0);\n detailsBoxLayout->addLayout(formLayout);\n \/\/ Name control\n QLabel *nameLabel = new QLabel(tr(\"Name:\"));\n nameLabel->setBuddy(m_nameLineEdit);\n formLayout->addRow(nameLabel, m_nameLineEdit);\n formLayout->addRow(tr(\"Install File:\"), m_sisxFileLabel);\n\n updateSerialDevices(); \n connect(S60Manager::instance()->serialDeviceLister(), SIGNAL(updated()),\n this, SLOT(updateSerialDevices()));\n \/\/ Serial devices control\n connect(m_serialPortsCombo, SIGNAL(activated(int)), this, SLOT(setSerialPort(int)));\n QHBoxLayout *serialPortHBoxLayout = new QHBoxLayout;\n serialPortHBoxLayout->addWidget(m_serialPortsCombo);\n serialPortHBoxLayout->addSpacerItem(new QSpacerItem(0, 0, QSizePolicy::MinimumExpanding, QSizePolicy::Ignored));\n\n formLayout->addRow(tr(\"Device on Serial Port:\"), serialPortHBoxLayout);\n\n \/\/ Device Info with button. Widgets are enabled in above call to updateSerialDevices()\n QHBoxLayout *infoHBoxLayout = new QHBoxLayout;\n m_deviceInfoLabel->setWordWrap(true);\n m_deviceInfoLabel->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Preferred);\n infoHBoxLayout->addWidget(m_deviceInfoLabel);\n infoHBoxLayout->addWidget(m_deviceInfoButton);\n m_deviceInfoButton->setIcon(qApp->style()->standardIcon(QStyle::SP_MessageBoxInformation));\n m_deviceInfoButton->setToolTip(tr(\"Queries the device for information\"));\n connect(m_deviceInfoButton, SIGNAL(clicked()), this, SLOT(updateDeviceInfo()));\n formLayout->addRow(m_deviceInfoDescriptionLabel, infoHBoxLayout);\n\n \/\/ Signature\/certificate stuff.\n QWidget *signatureWidget = new QWidget();\n QVBoxLayout *layout = new QVBoxLayout();\n signatureWidget->setLayout(layout);\n detailsBoxLayout->addWidget(signatureWidget);\n QRadioButton *selfSign = new QRadioButton(tr(\"Self-signed certificate\"));\n QHBoxLayout *customHBox = new QHBoxLayout();\n customHBox->setMargin(0);\n QVBoxLayout *radioLayout = new QVBoxLayout();\n QRadioButton *customSignature = new QRadioButton();\n radioLayout->addWidget(customSignature);\n radioLayout->addStretch(10);\n customHBox->addLayout(radioLayout);\n QFormLayout *customLayout = new QFormLayout();\n customLayout->setMargin(0);\n customLayout->setLabelAlignment(Qt::AlignRight);\n Utils::PathChooser *signaturePath = new Utils::PathChooser();\n signaturePath->setExpectedKind(Utils::PathChooser::File);\n signaturePath->setPromptDialogTitle(tr(\"Choose certificate file (.cer)\"));\n customLayout->addRow(new QLabel(tr(\"Custom certificate:\")), signaturePath);\n Utils::PathChooser *keyPath = new Utils::PathChooser();\n keyPath->setExpectedKind(Utils::PathChooser::File);\n keyPath->setPromptDialogTitle(tr(\"Choose key file (.key \/ .pem)\"));\n customLayout->addRow(new QLabel(tr(\"Key file:\")), keyPath);\n customHBox->addLayout(customLayout);\n customHBox->addStretch(10);\n layout->addWidget(selfSign);\n layout->addLayout(customHBox);\n layout->addStretch(10);\n\n switch (m_runConfiguration->signingMode()) {\n case S60DeviceRunConfiguration::SignSelf:\n selfSign->setChecked(true);\n break;\n case S60DeviceRunConfiguration::SignCustom:\n customSignature->setChecked(true);\n break;\n }\n\n signaturePath->setPath(m_runConfiguration->customSignaturePath());\n keyPath->setPath(m_runConfiguration->customKeyPath());\n\n connect(m_nameLineEdit, SIGNAL(textEdited(QString)),\n this, SLOT(nameEdited(QString)));\n connect(m_runConfiguration, SIGNAL(targetInformationChanged()),\n this, SLOT(updateTargetInformation()));\n connect(selfSign, SIGNAL(toggled(bool)), this, SLOT(selfSignToggled(bool)));\n connect(customSignature, SIGNAL(toggled(bool)), this, SLOT(customSignatureToggled(bool)));\n connect(signaturePath, SIGNAL(changed(QString)), this, SLOT(signaturePathChanged(QString)));\n connect(keyPath, SIGNAL(changed(QString)), this, SLOT(keyPathChanged(QString)));\n updateSummary();\n}\n\nvoid S60DeviceRunConfigurationWidget::updateSerialDevices()\n{\n m_serialPortsCombo->clear();\n clearDeviceInfo();\n const QString previousRunConfigurationPortName = m_runConfiguration->serialPortName();\n const QList<CommunicationDevice> devices = S60Manager::instance()->serialDeviceLister()->communicationDevices();\n int newIndex = -1;\n for (int i = 0; i < devices.size(); ++i) {\n const CommunicationDevice &device = devices.at(i);\n m_serialPortsCombo->addItem(device.friendlyName, qVariantFromValue(device));\n if (device.portName == previousRunConfigurationPortName)\n newIndex = i;\n }\n \/\/ Set new index: prefer to keep old or set to 0, if available.\n if (newIndex == -1 && !devices.empty())\n newIndex = 0;\n m_serialPortsCombo->setCurrentIndex(newIndex);\n if (newIndex == -1) {\n m_deviceInfoButton->setEnabled(false);\n m_runConfiguration->setSerialPortName(QString());\n } else {\n m_deviceInfoButton->setEnabled(true);\n const QString newPortName = device(newIndex).portName;\n if (newPortName != previousRunConfigurationPortName)\n m_runConfiguration->setSerialPortName(newPortName);\n }\n}\n\nCommunicationDevice S60DeviceRunConfigurationWidget::device(int i) const\n{\n if (i >= 0) {\n const QVariant data = m_serialPortsCombo->itemData(i);\n if (qVariantCanConvert<Qt4ProjectManager::Internal::CommunicationDevice>(data))\n return qVariantValue<Qt4ProjectManager::Internal::CommunicationDevice>(data);\n }\n return CommunicationDevice(SerialPortCommunication);\n}\n\nCommunicationDevice S60DeviceRunConfigurationWidget::currentDevice() const\n{\n return device(m_serialPortsCombo->currentIndex());\n}\n\nvoid S60DeviceRunConfigurationWidget::nameEdited(const QString &text)\n{\n m_runConfiguration->setName(text);\n}\n\nvoid S60DeviceRunConfigurationWidget::updateTargetInformation()\n{\n m_sisxFileLabel->setText(m_runConfiguration->basePackageFilePath() + QLatin1String(\".sisx\"));\n}\n\nvoid S60DeviceRunConfigurationWidget::setSerialPort(int index)\n{\n const CommunicationDevice d = device(index);\n m_runConfiguration->setSerialPortName(d.portName);\n m_runConfiguration->setCommunicationType(d.type);\n m_deviceInfoButton->setEnabled(index >= 0);\n clearDeviceInfo();\n updateSummary();\n}\n\nvoid S60DeviceRunConfigurationWidget::selfSignToggled(bool toggle)\n{\n if (toggle)\n m_runConfiguration->setSigningMode(S60DeviceRunConfiguration::SignSelf);\n updateSummary();\n}\n\nvoid S60DeviceRunConfigurationWidget::customSignatureToggled(bool toggle)\n{\n if (toggle)\n m_runConfiguration->setSigningMode(S60DeviceRunConfiguration::SignCustom);\n updateSummary();\n}\n\nvoid S60DeviceRunConfigurationWidget::signaturePathChanged(const QString &path)\n{\n m_runConfiguration->setCustomSignaturePath(path);\n updateSummary();\n}\n\nvoid S60DeviceRunConfigurationWidget::keyPathChanged(const QString &path)\n{\n m_runConfiguration->setCustomKeyPath(path);\n updateSummary();\n}\n\nvoid S60DeviceRunConfigurationWidget::updateSummary()\n{\n \/\/: Summary text of S60 device run configuration\n const QString device = m_serialPortsCombo->currentIndex() != -1 ?\n m_serialPortsCombo->currentText() :\n tr(\"<No Device>\");\n const QString signature = m_runConfiguration->signingMode() == S60DeviceRunConfiguration::SignCustom ?\n tr(\"(custom certificate)\") :\n tr(\"(self-signed certificate)\"); \n m_detailsWidget->setSummaryText(tr(\"Summary: Run on '%1' %2\").arg(device, signature));\n}\n\nvoid S60DeviceRunConfigurationWidget::clearDeviceInfo()\n{\n \/\/ Restore text & color\n m_deviceInfoLabel->clear();\n m_deviceInfoLabel->setStyleSheet(QString());\n}\n\nvoid S60DeviceRunConfigurationWidget::setDeviceInfoLabel(const QString &message, bool isError)\n{\n m_deviceInfoLabel->setStyleSheet(isError ?\n QString(QLatin1String(\"background-color: red;\")) :\n QString());\n m_deviceInfoLabel->setText(message);\n m_deviceInfoLabel->adjustSize();\n}\n\nvoid S60DeviceRunConfigurationWidget::updateDeviceInfo()\n{\n QString message;\n setDeviceInfoLabel(tr(\"Connecting...\"));\n const bool ok = getDeviceInfo(&message);\n setDeviceInfoLabel(message, !ok);\n}\n\nbool S60DeviceRunConfigurationWidget::getDeviceInfo(QString *message)\n{\n message->clear();\n \/\/ Do a launcher run with the ping protocol. Instantiate launcher on heap\n \/\/ as not to introduce delays when destructing a device with timeout\n trk::Launcher *launcher = new trk::Launcher(trk::Launcher::ActionPingOnly, QSharedPointer<trk::TrkDevice>(), this);\n const CommunicationDevice commDev = currentDevice();\n launcher->setSerialFrame(commDev.type == SerialPortCommunication);\n launcher->setTrkServerName(commDev.portName);\n \/\/ Prompt the user to start\n if (commDev.type == BlueToothCommunication) {\n S60RunConfigBluetoothStarter starter(launcher->trkDevice());\n starter.setDevice(launcher->trkServerName());\n const trk::StartBluetoothGuiResult src = trk::startBluetoothGui(starter, this, message);\n switch (src) {\n case trk::BluetoothGuiConnected:\n break;\n case trk::BluetoothGuiCanceled:\n launcher->deleteLater();\n return true;\n case trk::BluetoothGuiError:\n launcher->deleteLater();\n return false;\n };\n }\n if (!launcher->startServer(message)) {\n launcher->deleteLater();\n return false;\n }\n \/\/ Set up event loop in the foreground with a timer to quit in case of timeout.\n QEventLoop eventLoop;\n if (!m_infoTimeOutTimer) {\n m_infoTimeOutTimer = new QTimer(this);\n m_infoTimeOutTimer->setInterval(3000);\n m_infoTimeOutTimer->setSingleShot(true);\n }\n connect(m_infoTimeOutTimer, SIGNAL(timeout()), &eventLoop, SLOT(quit()));\n connect(launcher, SIGNAL(finished()), &eventLoop, SLOT(quit()));\n \/\/ Go!\n QApplication::setOverrideCursor(Qt::BusyCursor);\n m_infoTimeOutTimer->start();\n eventLoop.exec(QEventLoop::ExcludeUserInputEvents);\n m_infoTimeOutTimer->disconnect();\n QApplication::restoreOverrideCursor();\n \/\/ Anything received?\n *message = launcher->deviceDescription();\n launcher->deleteLater();\n if (message->isEmpty()) {\n *message = tr(\"A timeout occurred while querying the device. Check whether Trk is running\");\n return false;\n }\n return true;\n}\n\n} \/\/ namespace Internal\n} \/\/ namespace Qt4ProjectManager\n<|endoftext|>"} {"text":"<commit_before>#include \"TelegramServer.hpp\"\n\n#include <QLoggingCategory>\n#include <QTcpServer>\n#include <QTcpSocket>\n\n#include \"ApiUtils.hpp\"\n#include \"TelegramServerUser.hpp\"\n#include \"RemoteClientConnection.hpp\"\n#include \"RemoteServerConnection.hpp\"\n#include \"Session.hpp\"\n\n#include \"CServerTcpTransport.hpp\"\n\n\/\/ Generated RPC Operation Factory includes\n#include \"AccountOperationFactory.hpp\"\n#include \"AuthOperationFactory.hpp\"\n#include \"BotsOperationFactory.hpp\"\n#include \"ChannelsOperationFactory.hpp\"\n#include \"ContactsOperationFactory.hpp\"\n#include \"HelpOperationFactory.hpp\"\n#include \"LangpackOperationFactory.hpp\"\n#include \"MessagesOperationFactory.hpp\"\n#include \"PaymentsOperationFactory.hpp\"\n#include \"PhoneOperationFactory.hpp\"\n#include \"PhotosOperationFactory.hpp\"\n#include \"StickersOperationFactory.hpp\"\n#include \"UpdatesOperationFactory.hpp\"\n#include \"UploadOperationFactory.hpp\"\n#include \"UsersOperationFactory.hpp\"\n\/\/ End of generated RPC Operation Factory includes\n\n#include \"ServerMessageData.hpp\"\n#include \"ServerRpcLayer.hpp\"\n#include \"ServerUtils.hpp\"\n#include \"Storage.hpp\"\n#include \"Debug.hpp\"\n\nQ_LOGGING_CATEGORY(loggingCategoryServer, \"telegram.server.main\", QtInfoMsg)\nQ_LOGGING_CATEGORY(loggingCategoryServerApi, \"telegram.server.api\", QtWarningMsg)\n\nnamespace Telegram {\n\nnamespace Server {\n\nServer::Server(QObject *parent) :\n QObject(parent)\n{\n m_rpcOperationFactories = {\n \/\/ Generated RPC Operation Factory initialization\n new AccountOperationFactory(),\n new AuthOperationFactory(),\n new BotsOperationFactory(),\n new ChannelsOperationFactory(),\n new ContactsOperationFactory(),\n new HelpOperationFactory(),\n new LangpackOperationFactory(),\n new MessagesOperationFactory(),\n new PaymentsOperationFactory(),\n new PhoneOperationFactory(),\n new PhotosOperationFactory(),\n new StickersOperationFactory(),\n new UpdatesOperationFactory(),\n new UploadOperationFactory(),\n new UsersOperationFactory(),\n \/\/ End of generated RPC Operation Factory initialization\n };\n m_serverSocket = new QTcpServer(this);\n connect(m_serverSocket, &QTcpServer::newConnection, this, &Server::onNewConnection);\n}\n\nvoid Server::setDcOption(const DcOption &option)\n{\n m_dcOption = option;\n}\n\nvoid Server::setServerPrivateRsaKey(const Telegram::RsaKey &key)\n{\n m_key = key;\n}\n\nbool Server::start()\n{\n if (!m_serverSocket->listen(QHostAddress(m_dcOption.address), m_dcOption.port)) {\n qCCritical(loggingCategoryServer).noquote().nospace() << \"Unable to listen port \" << m_dcOption.port\n << \" (\" << m_serverSocket->serverError() << \")\";\n return false;\n }\n qCInfo(loggingCategoryServer).nospace().noquote() << this << \" start server (DC \" << m_dcOption.id << \") \"\n << \"on \" << m_dcOption.address << \":\" << m_dcOption.port\n << \"; Key:\" << hex << showbase << m_key.fingerprint;\n return true;\n}\n\nvoid Server::stop()\n{\n qCInfo(loggingCategoryServer).nospace().noquote() << this << \" stop server (DC \" << m_dcOption.id << \") \"\n << \"on \" << m_dcOption.address << \":\" << m_dcOption.port;\n if (m_serverSocket) {\n m_serverSocket->close();\n }\n\n \/\/ Connections removed from the set on disconnected.\n \/\/ Copy connections to a variable to iterate over a constant container instead of\n \/\/ (virtually) simultanously mutated member variable.\n QSet<RemoteClientConnection*> activeConnections = m_activeConnections;\n for (RemoteClientConnection *client : activeConnections) {\n client->transport()->disconnectFromHost();\n }\n}\n\nvoid Server::loadData()\n{\n const int number = 10;\n for (int i = 0; i < number; ++i) {\n LocalUser *newUser = new LocalUser();\n newUser->setPhoneNumber(QStringLiteral(\"%1\").arg(i, 6, 10, QLatin1Char('0')));\n insertUser(newUser);\n }\n}\n\nvoid Server::setServerConfiguration(const DcConfiguration &config)\n{\n m_dcConfiguration = config;\n}\n\nvoid Server::addServerConnection(RemoteServerConnection *remoteServer)\n{\n m_remoteServers.insert(remoteServer);\n}\n\nquint32 Server::getDcIdForUserIdentifier(const QString &phoneNumber)\n{\n if (m_phoneToUserId.contains(phoneNumber)) {\n return m_dcOption.id;\n }\n return 0;\n}\n\nvoid Server::setAuthorizationProvider(Authorization::Provider *provider)\n{\n m_authProvider = provider;\n}\n\nvoid Server::setStorage(Storage *storage)\n{\n m_storage = storage;\n}\n\nvoid Server::onNewConnection()\n{\n QTcpSocket *socket = m_serverSocket->nextPendingConnection();\n if (!socket) {\n qCDebug(loggingCategoryServer) << \"expected pending connection does not exist\";\n return;\n }\n qCInfo(loggingCategoryServer) << this << \"An incoming connection from\" << socket->peerAddress().toString();\n TcpTransport *transport = new TcpTransport(socket, this);\n socket->setParent(transport);\n RemoteClientConnection *client = new RemoteClientConnection(this);\n connect(client, &BaseConnection::statusChanged, this, &Server::onClientConnectionStatusChanged);\n client->setServerRsaKey(m_key);\n client->setTransport(transport);\n client->setServerApi(this);\n client->setRpcFactories(m_rpcOperationFactories);\n\n m_activeConnections.insert(client);\n}\n\nvoid Server::onClientConnectionStatusChanged()\n{\n RemoteClientConnection *client = qobject_cast<RemoteClientConnection*>(sender());\n if (client->status() == RemoteClientConnection::Status::HasDhKey) {\n if (!client->session()) {\n qCDebug(loggingCategoryServer) << Q_FUNC_INFO << \"Connected a client with a new auth key\"\n << \"from\" << client->transport()->remoteAddress();\n }\n } else if (client->status() == RemoteClientConnection::Status::Disconnected) {\n if (client->session()) {\n qCInfo(loggingCategoryServer) << this << __func__ << \"Disconnected a client with session id\"\n << hex << showbase << client->session()->id()\n << \"from\" << client->transport()->remoteAddress();\n client->session()->setConnection(nullptr);\n } else {\n qCInfo(loggingCategoryServer) << this << __func__ << \"Disconnected a client without a session\"\n << \"from\" << client->transport()->remoteAddress();\n }\n \/\/ TODO: Initiate session cleanup after session expiration time out\n m_activeConnections.remove(client);\n client->deleteLater();\n }\n}\n\nPeer Server::getPeer(const TLInputPeer &peer, const LocalUser *applicant) const\n{\n switch (peer.tlType) {\n case TLValue::InputPeerEmpty:\n return Peer();\n case TLValue::InputPeerSelf:\n return Peer::fromUserId(applicant->id());\n case TLValue::InputPeerChat:\n return Peer::fromChatId(peer.chatId);\n case TLValue::InputPeerUser:\n return Peer::fromUserId(peer.userId);\n case TLValue::InputPeerChannel:\n return Peer::fromChannelId(peer.channelId);\n default:\n qCWarning(loggingCategoryServerApi) << this << __func__ << \"Invalid input peer type\" << peer.tlType;\n return Peer();\n };\n}\n\nMessageRecipient *Server::getRecipient(const Peer &peer, const LocalUser *applicant) const\n{\n Q_UNUSED(applicant)\n switch (peer.type) {\n case Telegram::Peer::User:\n return getUser(peer.id);\n case Telegram::Peer::Chat:\n \/\/ recipient = api()->getChannel(arguments.peer.groupId, arguments.peer.accessHash);\n break;\n case Telegram::Peer::Channel:\n \/\/recipient = api()->getChannel(arguments.peer.channelId, arguments.peer.accessHash);\n break;\n }\n return nullptr;\n}\n\nLocalUser *Server::getUser(const QString &identifier) const\n{\n quint32 id = m_phoneToUserId.value(identifier);\n if (!id) {\n return nullptr;\n }\n return m_users.value(id);\n}\n\nLocalUser *Server::getUser(quint32 userId) const\n{\n return m_users.value(userId);\n}\n\nAbstractUser *Server::getUser(const TLInputUser &inputUser, LocalUser *self) const\n{\n switch (inputUser.tlType) {\n case TLValue::InputUserSelf:\n return self;\n case TLValue::InputUser:\n return tryAccessUser(inputUser.userId, inputUser.accessHash, self);\n case TLValue::InputUserEmpty:\n return nullptr;\n default:\n return nullptr;\n }\n}\n\nAbstractUser *Server::tryAccessUser(quint32 userId, quint64 accessHash, LocalUser *applicant) const\n{\n AbstractUser *u = getAbstractUser(userId);\n \/\/ TODO: Check access hash\n return u;\n}\n\nLocalUser *Server::addUser(const QString &identifier)\n{\n qCDebug(loggingCategoryServerApi) << Q_FUNC_INFO << identifier;\n LocalUser *user = new LocalUser();\n user->setPhoneNumber(identifier);\n user->setDcId(dcId());\n insertUser(user);\n return user;\n}\n\nSession *Server::createSession(quint64 authId, const QByteArray &authKey, const QString &address)\n{\n Session *session = new Session();\n session->authId = authId;\n session->authKey = authKey;\n session->ip = address;\n m_authIdToSession.insert(authId, session);\n return session;\n}\n\nSession *Server::getSessionByAuthId(quint64 authKeyId) const\n{\n return m_authIdToSession.value(authKeyId);\n}\n\nvoid Server::bindUserSession(LocalUser *user, Session *session)\n{\n user->addSession(session);\n}\n\nvoid Server::queueUpdates(const QVector<UpdateNotification> ¬ifications)\n{\n for (const UpdateNotification ¬ification : notifications) {\n LocalUser *recipient = getUser(notification.userId);\n if (!recipient) {\n qWarning() << Q_FUNC_INFO << \"Invalid user!\" << notification.userId;\n }\n\n TLUpdates updates;\n updates.tlType = TLValue::Updates;\n updates.date = notification.date;\n\n QSet<Peer> interestingPeers;\n switch (notification.type) {\n case UpdateNotification::Type::NewMessage: {\n TLUpdate update;\n update.tlType = TLValue::UpdateNewMessage;\n\n const quint64 globalMessageId = recipient->getPostBox()->getMessageGlobalId(notification.messageId);\n const MessageData *messageData = storage()->getMessage(globalMessageId);\n\n if (!messageData) {\n qWarning() << Q_FUNC_INFO << \"no message\";\n continue;\n }\n Utils::setupTLMessage(&update.message, messageData, notification.messageId, recipient);\n update.pts = notification.pts;\n update.ptsCount = 1;\n\n interestingPeers.insert(messageData->toPeer());\n if (update.message.fromId) {\n interestingPeers.insert(Peer::fromUserId(update.message.fromId));\n }\n\n updates.seq = 0; \/\/ ??\n updates.updates = { update };\n }\n break;\n case UpdateNotification::Type::Invalid:\n break;\n }\n\n Utils::setupTLPeers(&updates, interestingPeers, this, recipient);\n for (Session *session : recipient->activeSessions()) {\n if (session == notification.excludeSession) {\n continue;\n }\n session->rpcLayer()->sendUpdates(updates);\n }\n }\n}\n\nvoid Server::insertUser(LocalUser *user)\n{\n qCDebug(loggingCategoryServerApi) << Q_FUNC_INFO << user << user->phoneNumber() << user->id();\n m_users.insert(user->id(), user);\n m_phoneToUserId.insert(user->phoneNumber(), user->id());\n for (Session *session : user->sessions()) {\n m_authIdToSession.insert(session->authId, session);\n }\n}\n\nPhoneStatus Server::getPhoneStatus(const QString &identifier) const\n{\n PhoneStatus result;\n AbstractUser *user = getAbstractUser(identifier);\n if (user) {\n result.online = user->isOnline();\n result.dcId = user->dcId();\n }\n return result;\n}\n\nPasswordInfo Server::getPassword(const QString &identifier)\n{\n PasswordInfo result;\n LocalUser *user = getUser(identifier);\n if (user && user->hasPassword()) {\n result.currentSalt = user->passwordSalt();\n result.hint = user->passwordHint();\n }\n return result;\n}\n\nbool Server::checkPassword(const QString &identifier, const QByteArray &hash)\n{\n LocalUser *user = getUser(identifier);\n if (user && user->hasPassword()) {\n return user->passwordHash() == hash;\n }\n return false;\n\n}\n\nbool Server::identifierIsValid(const QString &identifier) const\n{\n const bool result = identifier.length() > 4;\n qCDebug(loggingCategoryServerApi) << \"identifierIsValid(\" << identifier << \"):\" << result;\n return result;\n}\n\nQString Server::normalizeIdentifier(const QString &identifier) const\n{\n if (identifier.startsWith(QLatin1Char('+'))) {\n return identifier.mid(1);\n }\n return identifier;\n}\n\nAbstractUser *Server::getAbstractUser(quint32 userId) const\n{\n AbstractUser *user = getUser(userId);\n if (!user) {\n user = getRemoteUser(userId);\n }\n return user;\n}\n\nAbstractUser *Server::getAbstractUser(const QString &identifier) const\n{\n AbstractUser *user = getUser(identifier);\n if (!user) {\n user = getRemoteUser(identifier);\n }\n return user;\n}\n\nAbstractUser *Server::getRemoteUser(quint32 userId) const\n{\n for (RemoteServerConnection *remoteServer : m_remoteServers) {\n AbstractUser *u = remoteServer->api()->getUser(userId);\n if (u) {\n return u;\n }\n }\n return nullptr;\n}\n\nAbstractUser *Server::getRemoteUser(const QString &identifier) const\n{\n for (RemoteServerConnection *remoteServer : m_remoteServers) {\n AbstractUser *u = remoteServer->api()->getUser(identifier);\n if (u) {\n return u;\n }\n }\n return nullptr;\n}\n\n} \/\/ Server namespace\n\n} \/\/ Telegram namespace\n<commit_msg>Server: Implement ReadHistory{In,Out}box update<commit_after>#include \"TelegramServer.hpp\"\n\n#include <QLoggingCategory>\n#include <QTcpServer>\n#include <QTcpSocket>\n\n#include \"ApiUtils.hpp\"\n#include \"TelegramServerUser.hpp\"\n#include \"RemoteClientConnection.hpp\"\n#include \"RemoteServerConnection.hpp\"\n#include \"Session.hpp\"\n\n#include \"CServerTcpTransport.hpp\"\n\n\/\/ Generated RPC Operation Factory includes\n#include \"AccountOperationFactory.hpp\"\n#include \"AuthOperationFactory.hpp\"\n#include \"BotsOperationFactory.hpp\"\n#include \"ChannelsOperationFactory.hpp\"\n#include \"ContactsOperationFactory.hpp\"\n#include \"HelpOperationFactory.hpp\"\n#include \"LangpackOperationFactory.hpp\"\n#include \"MessagesOperationFactory.hpp\"\n#include \"PaymentsOperationFactory.hpp\"\n#include \"PhoneOperationFactory.hpp\"\n#include \"PhotosOperationFactory.hpp\"\n#include \"StickersOperationFactory.hpp\"\n#include \"UpdatesOperationFactory.hpp\"\n#include \"UploadOperationFactory.hpp\"\n#include \"UsersOperationFactory.hpp\"\n\/\/ End of generated RPC Operation Factory includes\n\n#include \"ServerMessageData.hpp\"\n#include \"ServerRpcLayer.hpp\"\n#include \"ServerUtils.hpp\"\n#include \"Storage.hpp\"\n#include \"Debug.hpp\"\n\nQ_LOGGING_CATEGORY(loggingCategoryServer, \"telegram.server.main\", QtInfoMsg)\nQ_LOGGING_CATEGORY(loggingCategoryServerApi, \"telegram.server.api\", QtWarningMsg)\n\nnamespace Telegram {\n\nnamespace Server {\n\nServer::Server(QObject *parent) :\n QObject(parent)\n{\n m_rpcOperationFactories = {\n \/\/ Generated RPC Operation Factory initialization\n new AccountOperationFactory(),\n new AuthOperationFactory(),\n new BotsOperationFactory(),\n new ChannelsOperationFactory(),\n new ContactsOperationFactory(),\n new HelpOperationFactory(),\n new LangpackOperationFactory(),\n new MessagesOperationFactory(),\n new PaymentsOperationFactory(),\n new PhoneOperationFactory(),\n new PhotosOperationFactory(),\n new StickersOperationFactory(),\n new UpdatesOperationFactory(),\n new UploadOperationFactory(),\n new UsersOperationFactory(),\n \/\/ End of generated RPC Operation Factory initialization\n };\n m_serverSocket = new QTcpServer(this);\n connect(m_serverSocket, &QTcpServer::newConnection, this, &Server::onNewConnection);\n}\n\nvoid Server::setDcOption(const DcOption &option)\n{\n m_dcOption = option;\n}\n\nvoid Server::setServerPrivateRsaKey(const Telegram::RsaKey &key)\n{\n m_key = key;\n}\n\nbool Server::start()\n{\n if (!m_serverSocket->listen(QHostAddress(m_dcOption.address), m_dcOption.port)) {\n qCCritical(loggingCategoryServer).noquote().nospace() << \"Unable to listen port \" << m_dcOption.port\n << \" (\" << m_serverSocket->serverError() << \")\";\n return false;\n }\n qCInfo(loggingCategoryServer).nospace().noquote() << this << \" start server (DC \" << m_dcOption.id << \") \"\n << \"on \" << m_dcOption.address << \":\" << m_dcOption.port\n << \"; Key:\" << hex << showbase << m_key.fingerprint;\n return true;\n}\n\nvoid Server::stop()\n{\n qCInfo(loggingCategoryServer).nospace().noquote() << this << \" stop server (DC \" << m_dcOption.id << \") \"\n << \"on \" << m_dcOption.address << \":\" << m_dcOption.port;\n if (m_serverSocket) {\n m_serverSocket->close();\n }\n\n \/\/ Connections removed from the set on disconnected.\n \/\/ Copy connections to a variable to iterate over a constant container instead of\n \/\/ (virtually) simultanously mutated member variable.\n QSet<RemoteClientConnection*> activeConnections = m_activeConnections;\n for (RemoteClientConnection *client : activeConnections) {\n client->transport()->disconnectFromHost();\n }\n}\n\nvoid Server::loadData()\n{\n const int number = 10;\n for (int i = 0; i < number; ++i) {\n LocalUser *newUser = new LocalUser();\n newUser->setPhoneNumber(QStringLiteral(\"%1\").arg(i, 6, 10, QLatin1Char('0')));\n insertUser(newUser);\n }\n}\n\nvoid Server::setServerConfiguration(const DcConfiguration &config)\n{\n m_dcConfiguration = config;\n}\n\nvoid Server::addServerConnection(RemoteServerConnection *remoteServer)\n{\n m_remoteServers.insert(remoteServer);\n}\n\nquint32 Server::getDcIdForUserIdentifier(const QString &phoneNumber)\n{\n if (m_phoneToUserId.contains(phoneNumber)) {\n return m_dcOption.id;\n }\n return 0;\n}\n\nvoid Server::setAuthorizationProvider(Authorization::Provider *provider)\n{\n m_authProvider = provider;\n}\n\nvoid Server::setStorage(Storage *storage)\n{\n m_storage = storage;\n}\n\nvoid Server::onNewConnection()\n{\n QTcpSocket *socket = m_serverSocket->nextPendingConnection();\n if (!socket) {\n qCDebug(loggingCategoryServer) << \"expected pending connection does not exist\";\n return;\n }\n qCInfo(loggingCategoryServer) << this << \"An incoming connection from\" << socket->peerAddress().toString();\n TcpTransport *transport = new TcpTransport(socket, this);\n socket->setParent(transport);\n RemoteClientConnection *client = new RemoteClientConnection(this);\n connect(client, &BaseConnection::statusChanged, this, &Server::onClientConnectionStatusChanged);\n client->setServerRsaKey(m_key);\n client->setTransport(transport);\n client->setServerApi(this);\n client->setRpcFactories(m_rpcOperationFactories);\n\n m_activeConnections.insert(client);\n}\n\nvoid Server::onClientConnectionStatusChanged()\n{\n RemoteClientConnection *client = qobject_cast<RemoteClientConnection*>(sender());\n if (client->status() == RemoteClientConnection::Status::HasDhKey) {\n if (!client->session()) {\n qCDebug(loggingCategoryServer) << Q_FUNC_INFO << \"Connected a client with a new auth key\"\n << \"from\" << client->transport()->remoteAddress();\n }\n } else if (client->status() == RemoteClientConnection::Status::Disconnected) {\n if (client->session()) {\n qCInfo(loggingCategoryServer) << this << __func__ << \"Disconnected a client with session id\"\n << hex << showbase << client->session()->id()\n << \"from\" << client->transport()->remoteAddress();\n client->session()->setConnection(nullptr);\n } else {\n qCInfo(loggingCategoryServer) << this << __func__ << \"Disconnected a client without a session\"\n << \"from\" << client->transport()->remoteAddress();\n }\n \/\/ TODO: Initiate session cleanup after session expiration time out\n m_activeConnections.remove(client);\n client->deleteLater();\n }\n}\n\nPeer Server::getPeer(const TLInputPeer &peer, const LocalUser *applicant) const\n{\n switch (peer.tlType) {\n case TLValue::InputPeerEmpty:\n return Peer();\n case TLValue::InputPeerSelf:\n return Peer::fromUserId(applicant->id());\n case TLValue::InputPeerChat:\n return Peer::fromChatId(peer.chatId);\n case TLValue::InputPeerUser:\n return Peer::fromUserId(peer.userId);\n case TLValue::InputPeerChannel:\n return Peer::fromChannelId(peer.channelId);\n default:\n qCWarning(loggingCategoryServerApi) << this << __func__ << \"Invalid input peer type\" << peer.tlType;\n return Peer();\n };\n}\n\nMessageRecipient *Server::getRecipient(const Peer &peer, const LocalUser *applicant) const\n{\n Q_UNUSED(applicant)\n switch (peer.type) {\n case Telegram::Peer::User:\n return getUser(peer.id);\n case Telegram::Peer::Chat:\n \/\/ recipient = api()->getChannel(arguments.peer.groupId, arguments.peer.accessHash);\n break;\n case Telegram::Peer::Channel:\n \/\/recipient = api()->getChannel(arguments.peer.channelId, arguments.peer.accessHash);\n break;\n }\n return nullptr;\n}\n\nLocalUser *Server::getUser(const QString &identifier) const\n{\n quint32 id = m_phoneToUserId.value(identifier);\n if (!id) {\n return nullptr;\n }\n return m_users.value(id);\n}\n\nLocalUser *Server::getUser(quint32 userId) const\n{\n return m_users.value(userId);\n}\n\nAbstractUser *Server::getUser(const TLInputUser &inputUser, LocalUser *self) const\n{\n switch (inputUser.tlType) {\n case TLValue::InputUserSelf:\n return self;\n case TLValue::InputUser:\n return tryAccessUser(inputUser.userId, inputUser.accessHash, self);\n case TLValue::InputUserEmpty:\n return nullptr;\n default:\n return nullptr;\n }\n}\n\nAbstractUser *Server::tryAccessUser(quint32 userId, quint64 accessHash, LocalUser *applicant) const\n{\n AbstractUser *u = getAbstractUser(userId);\n \/\/ TODO: Check access hash\n return u;\n}\n\nLocalUser *Server::addUser(const QString &identifier)\n{\n qCDebug(loggingCategoryServerApi) << Q_FUNC_INFO << identifier;\n LocalUser *user = new LocalUser();\n user->setPhoneNumber(identifier);\n user->setDcId(dcId());\n insertUser(user);\n return user;\n}\n\nSession *Server::createSession(quint64 authId, const QByteArray &authKey, const QString &address)\n{\n Session *session = new Session();\n session->authId = authId;\n session->authKey = authKey;\n session->ip = address;\n m_authIdToSession.insert(authId, session);\n return session;\n}\n\nSession *Server::getSessionByAuthId(quint64 authKeyId) const\n{\n return m_authIdToSession.value(authKeyId);\n}\n\nvoid Server::bindUserSession(LocalUser *user, Session *session)\n{\n user->addSession(session);\n}\n\nvoid Server::queueUpdates(const QVector<UpdateNotification> ¬ifications)\n{\n for (const UpdateNotification ¬ification : notifications) {\n LocalUser *recipient = getUser(notification.userId);\n if (!recipient) {\n qWarning() << Q_FUNC_INFO << \"Invalid user!\" << notification.userId;\n }\n\n TLUpdates updates;\n updates.tlType = TLValue::Updates;\n updates.date = notification.date;\n\n QSet<Peer> interestingPeers;\n switch (notification.type) {\n case UpdateNotification::Type::NewMessage: {\n TLUpdate update;\n update.tlType = TLValue::UpdateNewMessage;\n\n const quint64 globalMessageId = recipient->getPostBox()->getMessageGlobalId(notification.messageId);\n const MessageData *messageData = storage()->getMessage(globalMessageId);\n\n if (!messageData) {\n qWarning() << Q_FUNC_INFO << \"no message\";\n continue;\n }\n Utils::setupTLMessage(&update.message, messageData, notification.messageId, recipient);\n update.pts = notification.pts;\n update.ptsCount = 1;\n\n interestingPeers.insert(messageData->toPeer());\n if (update.message.fromId) {\n interestingPeers.insert(Peer::fromUserId(update.message.fromId));\n }\n\n updates.seq = 0; \/\/ ??\n updates.updates = { update };\n }\n break;\n case UpdateNotification::Type::ReadInbox:\n case UpdateNotification::Type::ReadOutbox:\n {\n TLUpdate update;\n update.tlType = notification.type == UpdateNotification::Type::ReadInbox\n ? TLValue::UpdateReadHistoryInbox\n : TLValue::UpdateReadHistoryOutbox;\n update.pts = notification.pts;\n update.ptsCount = 1;\n update.peer = Telegram::Utils::toTLPeer(notification.dialogPeer);\n update.maxId = notification.messageId;\n\n updates.seq = 0; \/\/ ??\n updates.updates = { update };\n }\n break;\n case UpdateNotification::Type::Invalid:\n break;\n }\n\n Utils::setupTLPeers(&updates, interestingPeers, this, recipient);\n for (Session *session : recipient->activeSessions()) {\n if (session == notification.excludeSession) {\n continue;\n }\n session->rpcLayer()->sendUpdates(updates);\n }\n }\n}\n\nvoid Server::insertUser(LocalUser *user)\n{\n qCDebug(loggingCategoryServerApi) << Q_FUNC_INFO << user << user->phoneNumber() << user->id();\n m_users.insert(user->id(), user);\n m_phoneToUserId.insert(user->phoneNumber(), user->id());\n for (Session *session : user->sessions()) {\n m_authIdToSession.insert(session->authId, session);\n }\n}\n\nPhoneStatus Server::getPhoneStatus(const QString &identifier) const\n{\n PhoneStatus result;\n AbstractUser *user = getAbstractUser(identifier);\n if (user) {\n result.online = user->isOnline();\n result.dcId = user->dcId();\n }\n return result;\n}\n\nPasswordInfo Server::getPassword(const QString &identifier)\n{\n PasswordInfo result;\n LocalUser *user = getUser(identifier);\n if (user && user->hasPassword()) {\n result.currentSalt = user->passwordSalt();\n result.hint = user->passwordHint();\n }\n return result;\n}\n\nbool Server::checkPassword(const QString &identifier, const QByteArray &hash)\n{\n LocalUser *user = getUser(identifier);\n if (user && user->hasPassword()) {\n return user->passwordHash() == hash;\n }\n return false;\n\n}\n\nbool Server::identifierIsValid(const QString &identifier) const\n{\n const bool result = identifier.length() > 4;\n qCDebug(loggingCategoryServerApi) << \"identifierIsValid(\" << identifier << \"):\" << result;\n return result;\n}\n\nQString Server::normalizeIdentifier(const QString &identifier) const\n{\n if (identifier.startsWith(QLatin1Char('+'))) {\n return identifier.mid(1);\n }\n return identifier;\n}\n\nAbstractUser *Server::getAbstractUser(quint32 userId) const\n{\n AbstractUser *user = getUser(userId);\n if (!user) {\n user = getRemoteUser(userId);\n }\n return user;\n}\n\nAbstractUser *Server::getAbstractUser(const QString &identifier) const\n{\n AbstractUser *user = getUser(identifier);\n if (!user) {\n user = getRemoteUser(identifier);\n }\n return user;\n}\n\nAbstractUser *Server::getRemoteUser(quint32 userId) const\n{\n for (RemoteServerConnection *remoteServer : m_remoteServers) {\n AbstractUser *u = remoteServer->api()->getUser(userId);\n if (u) {\n return u;\n }\n }\n return nullptr;\n}\n\nAbstractUser *Server::getRemoteUser(const QString &identifier) const\n{\n for (RemoteServerConnection *remoteServer : m_remoteServers) {\n AbstractUser *u = remoteServer->api()->getUser(identifier);\n if (u) {\n return u;\n }\n }\n return nullptr;\n}\n\n} \/\/ Server namespace\n\n} \/\/ Telegram namespace\n<|endoftext|>"} {"text":"<commit_before>#include \"atoms_md.h\"\n#include \"xmath.h\"\n\/*--------------------------------------------\n \n --------------------------------------------*\/\nAtomsMD::AtomsMD(MPI_Comm& world):\nAtoms(world),\nS_pe{DESIG2(__dim__,__dim__,NAN)},\npe(NAN)\n{\n elem=new Vec<elem_type>(this,1,\"elem\");\n x_d=new Vec<type0>(this,__dim__,\"x_d\");\n x_d->empty(0.0);\n}\n\/*--------------------------------------------\n \n --------------------------------------------*\/\nAtomsMD::~AtomsMD()\n{\n delete x_d;\n delete elem;\n}\n\/*--------------------------------------------\n \n --------------------------------------------*\/\nAtomsMD& AtomsMD::operator=(const Atoms& r)\n{\n elements=r.elements;\n comm=r.comm;\n natms_lcl=r.natms_lcl;\n natms_ph=r.natms_ph;\n natms=r.natms;\n step=r.step;\n \n max_cut=r.max_cut;\n kB=r.kB;\n hP=r.hP;\n \n vol=r.vol;\n memcpy(depth_inv,r.depth_inv,__dim__*sizeof(type0));\n memcpy(__h,r.__h,__nvoigt__*sizeof(type0));\n memcpy(__b,r.__b,__nvoigt__*sizeof(type0));\n memcpy(&H[0][0],&r.H[0][0],__dim__*__dim__*sizeof(type0));\n memcpy(&B[0][0],&r.B[0][0],__dim__*__dim__*sizeof(type0));\n \n for(int i=0;i<nvecs;i++)\n if(!vecs[i]->is_empty())\n vecs[i]->resize(natms_lcl);\n memcpy(x->begin(),r.x->begin(),natms_lcl*__dim__*sizeof(type0));\n memcpy(id->begin(),r.id->begin(),natms_lcl*sizeof(unsigned int));\n return* this;\n}\n\/*--------------------------------------------\n x2s\n --------------------------------------------*\/\nvoid AtomsMD::x_d2s_d_dump()\n{\n Algebra::X2S_NOCORR<__dim__>(__b,natms,x_d->begin_dump());\n}\n\/*--------------------------------------------\n \n --------------------------------------------*\/\n#include \"random.h\"\n#include \"elements.h\"\n#include \"xmath.h\"\nvoid AtomsMD::create_T(type0 T,int seed)\n{\n x_d->fill();\n Random rand(seed+comm_rank);\n type0* __x_d=x_d->begin();\n type0* m=elements.masses;\n elem_type* __elem=elem->begin();\n type0 fac;\n if(!x_dof->is_empty())\n {\n bool* __dof=x_dof->begin();\n for(int i=0;i<natms_lcl;i++)\n {\n fac=sqrt(kB*T\/m[*__elem]);\n Algebra::Do<__dim__>::func([&fac,&rand,&__x_d,__dof,this](const int i){if(__dof[i]) __x_d[i]=rand.gaussian()*fac;});\n __x_d+=__dim__;\n __dof+=__dim__;\n ++__elem;\n }\n }\n else\n {\n for(int i=0;i<natms_lcl;i++)\n {\n fac=sqrt(kB*T\/m[*__elem]);\n Algebra::Do<__dim__>::func([&fac,&rand,&__x_d,this](const int i){__x_d[i]=rand.gaussian()*fac;});\n __x_d+=__dim__;\n ++__elem;\n }\n }\n}\n\/*--------------------------------------------\n \n --------------------------------------------*\/\nvoid AtomsMD::DO(PyObject* op)\n{ \n class Func_x\n {\n public:\n void operator()(type0*,type0*)\n {};\n };\n Func_x func_x;\n VecPy<type0,Func_x> x_vec_py(x,func_x);\n \n class Func_x_d\n {\n public:\n void operator()(type0*,type0*)\n {};\n };\n Func_x_d func_x_d;\n VecPy<type0,Func_x_d> x_d_vec_py(x_d,func_x_d);\n \n \n class Func_id\n {\n public:\n void operator()(unsigned int* old_val,unsigned int* new_val)\n {\n if(*old_val!=*new_val)\n throw std::string(\"id of atoms cannot be changed\");\n };\n };\n Func_id func_id;\n VecPy<unsigned int,Func_id> id_vec_py(id,func_id);\n \n \n \n class Func_elem\n {\n public:\n elem_type nelem;\n Func_elem(elem_type __nelem):nelem(__nelem){}\n void operator()(elem_type* old_val,elem_type* new_val)\n {\n if(*new_val>=nelem)\n throw std::string(\"elem of atoms should be less than \")+Print::to_string(static_cast<int>(nelem));\n };\n };\n Func_elem func_elem(elements.__nelems);\n VecPy<elem_type,Func_elem> elem_vec_py(elem,func_elem);\n \n \n \n class Func_dof\n {\n public:\n void operator()(bool*,bool*)\n {\n };\n };\n Func_dof func_dof;\n VecPy<bool,Func_dof> dof_vec_py(x_dof,func_dof);\n try\n {\n VecPyFunc::Do(this,op,id_vec_py,x_vec_py,x_d_vec_py,elem_vec_py,dof_vec_py);\n }\n catch(std::string& err_msg)\n {\n throw err_msg;\n }\n \n if(x_vec_py.inc) this->reset_domain();\n \n}\n\/*------------------------------------------------------------------------------------------------------------------------------------\n \n ------------------------------------------------------------------------------------------------------------------------------------*\/\n#include \"ff_styles.h\"\n#include \"import_styles.h\"\nPyObject* AtomsMD::__new__(PyTypeObject* type,PyObject* args,PyObject* kwds)\n{\n Object* __self=reinterpret_cast<Object*>(type->tp_alloc(type,0));\n PyObject* self=reinterpret_cast<PyObject*>(__self);\n return self;\n}\n\/*--------------------------------------------\n \n --------------------------------------------*\/\nint AtomsMD::__init__(PyObject* self,PyObject* args,PyObject* kwds)\n{\n FuncAPI<> func(\"__init__\");\n if(func(args,kwds)==-1) return -1;\n Object* __self=reinterpret_cast<Object*>(self);\n __self->atoms=NULL;\n __self->ff=NULL;\n return 0;\n}\n\/*--------------------------------------------\n \n --------------------------------------------*\/\nPyObject* AtomsMD::__alloc__(PyTypeObject* type,Py_ssize_t)\n{\n Object* __self=new Object;\n Py_TYPE(__self)=type;\n Py_REFCNT(__self)=1;\n __self->atoms=NULL;\n __self->ff=NULL;\n return reinterpret_cast<PyObject*>(__self);\n}\n\/*--------------------------------------------\n \n --------------------------------------------*\/\nvoid AtomsMD::__dealloc__(PyObject* self)\n{\n Object* __self=reinterpret_cast<Object*>(self);\n delete __self->ff;\n delete __self->atoms;\n delete __self;\n}\n\/*--------------------------------------------*\/\nPyTypeObject AtomsMD::TypeObject ={PyObject_HEAD_INIT(NULL)};\n\/*--------------------------------------------*\/\nint AtomsMD::setup_tp()\n{\n TypeObject.tp_name=\"mapp.md.atoms\";\n TypeObject.tp_doc=\"container class\";\n \n TypeObject.tp_flags=Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE;\n TypeObject.tp_basicsize=sizeof(Object);\n \n TypeObject.tp_new=__new__;\n TypeObject.tp_init=__init__;\n TypeObject.tp_alloc=__alloc__;\n TypeObject.tp_dealloc=__dealloc__;\n \n setup_tp_getset();\n TypeObject.tp_getset=getset;\n setup_tp_methods();\n TypeObject.tp_methods=methods;\n \n int ichk=PyType_Ready(&TypeObject);\n if(ichk<0) return ichk;\n Py_INCREF(&TypeObject);\n return ichk;\n}\n\/*--------------------------------------------*\/\nPyGetSetDef AtomsMD::getset[]=EmptyPyGetSetDef(15);\n\/*--------------------------------------------*\/\nvoid AtomsMD::setup_tp_getset()\n{\n getset_step(getset[0]);\n getset_hP(getset[1]);\n getset_kB(getset[2]);\n getset_H(getset[3]);\n getset_B(getset[4]);\n getset_vol(getset[5]);\n getset_elems(getset[6]);\n getset_skin(getset[7]);\n getset_comm_rank(getset[8]);\n getset_comm_size(getset[9]);\n getset_comm_coords(getset[10]);\n getset_comm_dims(getset[11]);\n getset_pe(getset[12]);\n getset_S_pe(getset[13]);\n}\n\/*--------------------------------------------\n \n --------------------------------------------*\/\nvoid AtomsMD::getset_S_pe(PyGetSetDef& getset)\n{\n getset.name=(char*)\"S_pe\";\n getset.doc=(char*)R\"---(\n (double) potential energy stress\n \n Potential energy part of virial stress\n )---\";\n getset.get=[](PyObject* self,void*)->PyObject*\n {\n return var<type0[__dim__][__dim__]>::build(reinterpret_cast<Object*>(self)->atoms->S_pe);\n };\n getset.set=[](PyObject* self,PyObject* val,void*)->int\n {\n PyErr_SetString(PyExc_TypeError,\"readonly attribute\");\n return -1;\n };\n}\n\/*--------------------------------------------\n \n --------------------------------------------*\/\nvoid AtomsMD::getset_pe(PyGetSetDef& getset)\n{\n getset.name=(char*)\"pe\";\n getset.doc=(char*)R\"---(\n (double) potential energy\n \n Potential energy\n )---\";\n getset.get=[](PyObject* self,void*)->PyObject*\n {\n return var<type0>::build(reinterpret_cast<Object*>(self)->atoms->pe);\n };\n getset.set=[](PyObject* self,PyObject* val,void*)->int\n {\n PyErr_SetString(PyExc_TypeError,\"readonly attribute\");\n return -1;\n };\n}\n\/*--------------------------------------------*\/\n#ifdef POTFIT\nPyMethodDef AtomsMD::methods[]=EmptyPyMethodDef(16);\n#else\nPyMethodDef AtomsMD::methods[]=EmptyPyMethodDef(13);\n#endif\n\/*--------------------------------------------*\/\nvoid AtomsMD::setup_tp_methods()\n{\n ml_do(methods[0]);\n ml_mul(methods[1]);\n ml_strain(methods[2]);\n ml_create_temp(methods[3]);\n ml_add_elem(methods[4]);\n ForceFieldLJ::ml_new(methods[5]);\n ForceFieldEAM::ml_new(methods[6],methods[7],methods[8]);\n ForceFieldFS::ml_new(methods[9]);\n ForceFieldEAMFunc::ml_new(methods[10]);\n ImportCFGMD::ml_import(methods[11]);\n#ifdef POTFIT\n ForceFieldEAMFit::ml_new(methods[12]);\n ForceFieldEAMFitO::ml_new(methods[13]);\n ForceFieldEAMPotFitAckOgata::ml_new(methods[14]);\n#endif\n}\n\/*--------------------------------------------\n \n --------------------------------------------*\/\nvoid AtomsMD::ml_create_temp(PyMethodDef& tp_method)\n{\n tp_method.ml_flags=METH_VARARGS | METH_KEYWORDS;\n tp_method.ml_name=\"create_temp\";\n tp_method.ml_meth=(PyCFunction)(PyCFunctionWithKeywords)(\n [](PyObject* self,PyObject* args,PyObject* kwds)->PyObject*\n {\n FuncAPI<type0,int> f(\"create_temp\",{\"temp\",\"seed\"});\n f.logics<0>()[0]=VLogics(\"gt\",0.0);\n f.logics<1>()[0]=VLogics(\"gt\",0);\n if(f(args,kwds)) return NULL;\n \n AtomsMD::Object* __self=reinterpret_cast<AtomsMD::Object*>(self);\n __self->atoms->create_T(f.val<0>(),f.val<1>());\n Py_RETURN_NONE;\n });\n tp_method.ml_doc=R\"---(\n create_temp(temp,seed)\n \n Create a random velcity field\n \n Parameters\n ----------\n temp : double\n Temperature\n seed : int\n random seed\n \n Returns\n -------\n None\n \n )---\";\n}\n\/*--------------------------------------------\n \n --------------------------------------------*\/\nvoid AtomsMD::ml_add_elem(PyMethodDef& tp_method)\n{\n tp_method.ml_flags=METH_VARARGS | METH_KEYWORDS;\n tp_method.ml_name=\"add_elem\";\n tp_method.ml_meth=(PyCFunction)(PyCFunctionWithKeywords)(\n [](PyObject* self,PyObject* args,PyObject* kwds)->PyObject*\n {\n FuncAPI<std::string,type0> f(\"add_elem\",{\"elem\",\"mass\"});\n f.logics<1>()[0]=VLogics(\"gt\",0.0);\n if(f(args,kwds)) return NULL;\n \n AtomsMD::Object* __self=reinterpret_cast<AtomsMD::Object*>(self);\n __self->atoms->elements.add_type(f.val<1>(),f.val<0>().c_str());\n \n Py_RETURN_NONE;\n });\n tp_method.ml_doc=R\"---(\n add_elem(elem,mass)\n \n Add a new element to the system\n \n Parameters\n ----------\n elem : string\n New element\n seed : double\n Mass of the element\n \n Returns\n -------\n None\n \n )---\";\n}\n\n<commit_msg>nothing important<commit_after>#include \"atoms_md.h\"\n#include \"xmath.h\"\n\/*--------------------------------------------\n \n --------------------------------------------*\/\nAtomsMD::AtomsMD(MPI_Comm& world):\nAtoms(world),\nS_pe{DESIG2(__dim__,__dim__,NAN)},\npe(NAN)\n{\n elem=new Vec<elem_type>(this,1,\"elem\");\n x_d=new Vec<type0>(this,__dim__,\"x_d\");\n x_d->empty(0.0);\n}\n\/*--------------------------------------------\n \n --------------------------------------------*\/\nAtomsMD::~AtomsMD()\n{\n delete x_d;\n delete elem;\n}\n\/*--------------------------------------------\n \n --------------------------------------------*\/\nAtomsMD& AtomsMD::operator=(const Atoms& r)\n{\n elements=r.elements;\n comm=r.comm;\n natms_lcl=r.natms_lcl;\n natms_ph=r.natms_ph;\n natms=r.natms;\n step=r.step;\n \n max_cut=r.max_cut;\n kB=r.kB;\n hP=r.hP;\n \n vol=r.vol;\n memcpy(depth_inv,r.depth_inv,__dim__*sizeof(type0));\n memcpy(__h,r.__h,__nvoigt__*sizeof(type0));\n memcpy(__b,r.__b,__nvoigt__*sizeof(type0));\n memcpy(&H[0][0],&r.H[0][0],__dim__*__dim__*sizeof(type0));\n memcpy(&B[0][0],&r.B[0][0],__dim__*__dim__*sizeof(type0));\n \n for(int i=0;i<nvecs;i++)\n if(!vecs[i]->is_empty())\n vecs[i]->resize(natms_lcl);\n memcpy(x->begin(),r.x->begin(),natms_lcl*__dim__*sizeof(type0));\n memcpy(id->begin(),r.id->begin(),natms_lcl*sizeof(unsigned int));\n return* this;\n}\n\/*--------------------------------------------\n x2s\n --------------------------------------------*\/\nvoid AtomsMD::x_d2s_d_dump()\n{\n Algebra::X2S_NOCORR<__dim__>(__b,natms,x_d->begin_dump());\n}\n\/*--------------------------------------------\n \n --------------------------------------------*\/\n#include \"random.h\"\n#include \"elements.h\"\n#include \"xmath.h\"\nvoid AtomsMD::create_T(type0 T,int seed)\n{\n x_d->fill();\n Random rand(seed+comm_rank);\n type0* __x_d=x_d->begin();\n type0* m=elements.masses;\n elem_type* __elem=elem->begin();\n type0 fac;\n if(!x_dof->is_empty())\n {\n bool* __dof=x_dof->begin();\n for(int i=0;i<natms_lcl;i++)\n {\n fac=sqrt(kB*T\/m[*__elem]);\n Algebra::Do<__dim__>::func([&fac,&rand,&__x_d,__dof,this](const int i){if(__dof[i]) __x_d[i]=rand.gaussian()*fac;});\n __x_d+=__dim__;\n __dof+=__dim__;\n ++__elem;\n }\n }\n else\n {\n for(int i=0;i<natms_lcl;i++)\n {\n fac=sqrt(kB*T\/m[*__elem]);\n Algebra::Do<__dim__>::func([&fac,&rand,&__x_d,this](const int i){__x_d[i]=rand.gaussian()*fac;});\n __x_d+=__dim__;\n ++__elem;\n }\n }\n}\n\/*--------------------------------------------\n \n --------------------------------------------*\/\nvoid AtomsMD::DO(PyObject* op)\n{ \n class Func_x\n {\n public:\n void operator()(type0*,type0*)\n {};\n };\n Func_x func_x;\n VecPy<type0,Func_x> x_vec_py(x,func_x);\n \n class Func_x_d\n {\n public:\n void operator()(type0*,type0*)\n {};\n };\n Func_x_d func_x_d;\n VecPy<type0,Func_x_d> x_d_vec_py(x_d,func_x_d);\n \n \n class Func_id\n {\n public:\n void operator()(unsigned int* old_val,unsigned int* new_val)\n {\n if(*old_val!=*new_val)\n throw std::string(\"id of atoms cannot be changed\");\n };\n };\n Func_id func_id;\n VecPy<unsigned int,Func_id> id_vec_py(id,func_id);\n \n \n \n class Func_elem\n {\n public:\n elem_type nelem;\n Func_elem(elem_type __nelem):nelem(__nelem){}\n void operator()(elem_type* old_val,elem_type* new_val)\n {\n if(*new_val>=nelem)\n throw std::string(\"elem of atoms should be less than \")+Print::to_string(static_cast<int>(nelem));\n };\n };\n Func_elem func_elem(elements.__nelems);\n VecPy<elem_type,Func_elem> elem_vec_py(elem,func_elem);\n \n \n \n class Func_dof\n {\n public:\n void operator()(bool*,bool*)\n {\n };\n };\n Func_dof func_dof;\n VecPy<bool,Func_dof> dof_vec_py(x_dof,func_dof);\n try\n {\n VecPyFunc::Do(this,op,id_vec_py,x_vec_py,x_d_vec_py,elem_vec_py,dof_vec_py);\n }\n catch(std::string& err_msg)\n {\n throw err_msg;\n }\n \n if(x_vec_py.inc) this->reset_domain();\n \n}\n\/*------------------------------------------------------------------------------------------------------------------------------------\n \n ------------------------------------------------------------------------------------------------------------------------------------*\/\n#include \"ff_styles.h\"\n#include \"import_styles.h\"\nPyObject* AtomsMD::__new__(PyTypeObject* type,PyObject* args,PyObject* kwds)\n{\n Object* __self=reinterpret_cast<Object*>(type->tp_alloc(type,0));\n PyObject* self=reinterpret_cast<PyObject*>(__self);\n return self;\n}\n\/*--------------------------------------------\n \n --------------------------------------------*\/\nint AtomsMD::__init__(PyObject* self,PyObject* args,PyObject* kwds)\n{\n FuncAPI<> func(\"__init__\");\n if(func(args,kwds)==-1) return -1;\n Object* __self=reinterpret_cast<Object*>(self);\n __self->atoms=NULL;\n __self->ff=NULL;\n return 0;\n}\n\/*--------------------------------------------\n \n --------------------------------------------*\/\nPyObject* AtomsMD::__alloc__(PyTypeObject* type,Py_ssize_t)\n{\n Object* __self=new Object;\n Py_TYPE(__self)=type;\n Py_REFCNT(__self)=1;\n __self->atoms=NULL;\n __self->ff=NULL;\n return reinterpret_cast<PyObject*>(__self);\n}\n\/*--------------------------------------------\n \n --------------------------------------------*\/\nvoid AtomsMD::__dealloc__(PyObject* self)\n{\n Object* __self=reinterpret_cast<Object*>(self);\n delete __self->ff;\n delete __self->atoms;\n delete __self;\n}\n\/*--------------------------------------------*\/\nPyTypeObject AtomsMD::TypeObject ={PyObject_HEAD_INIT(NULL)};\n\/*--------------------------------------------*\/\nint AtomsMD::setup_tp()\n{\n TypeObject.tp_name=\"mapp.md.atoms\";\n TypeObject.tp_doc=\"container class\";\n \n TypeObject.tp_flags=Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE;\n TypeObject.tp_basicsize=sizeof(Object);\n \n TypeObject.tp_new=__new__;\n TypeObject.tp_init=__init__;\n TypeObject.tp_alloc=__alloc__;\n TypeObject.tp_dealloc=__dealloc__;\n \n setup_tp_getset();\n TypeObject.tp_getset=getset;\n setup_tp_methods();\n TypeObject.tp_methods=methods;\n \n int ichk=PyType_Ready(&TypeObject);\n if(ichk<0) return ichk;\n Py_INCREF(&TypeObject);\n return ichk;\n}\n\/*--------------------------------------------*\/\nPyGetSetDef AtomsMD::getset[]=EmptyPyGetSetDef(15);\n\/*--------------------------------------------*\/\nvoid AtomsMD::setup_tp_getset()\n{\n getset_step(getset[0]);\n getset_hP(getset[1]);\n getset_kB(getset[2]);\n getset_H(getset[3]);\n getset_B(getset[4]);\n getset_vol(getset[5]);\n getset_elems(getset[6]);\n getset_skin(getset[7]);\n getset_comm_rank(getset[8]);\n getset_comm_size(getset[9]);\n getset_comm_coords(getset[10]);\n getset_comm_dims(getset[11]);\n getset_pe(getset[12]);\n getset_S_pe(getset[13]);\n}\n\/*--------------------------------------------\n \n --------------------------------------------*\/\nvoid AtomsMD::getset_S_pe(PyGetSetDef& getset)\n{\n getset.name=(char*)\"S_pe\";\n getset.doc=(char*)R\"---(\n (double) potential energy stress\n \n Potential energy part of virial stress\n )---\";\n getset.get=[](PyObject* self,void*)->PyObject*\n {\n return var<type0[__dim__][__dim__]>::build(reinterpret_cast<Object*>(self)->atoms->S_pe);\n };\n getset.set=[](PyObject* self,PyObject* val,void*)->int\n {\n PyErr_SetString(PyExc_TypeError,\"readonly attribute\");\n return -1;\n };\n}\n\/*--------------------------------------------\n \n --------------------------------------------*\/\nvoid AtomsMD::getset_pe(PyGetSetDef& getset)\n{\n getset.name=(char*)\"pe\";\n getset.doc=(char*)R\"---(\n (double) potential energy\n \n Potential energy\n )---\";\n getset.get=[](PyObject* self,void*)->PyObject*\n {\n return var<type0>::build(reinterpret_cast<Object*>(self)->atoms->pe);\n };\n getset.set=[](PyObject* self,PyObject* val,void*)->int\n {\n PyErr_SetString(PyExc_TypeError,\"readonly attribute\");\n return -1;\n };\n}\n\/*--------------------------------------------*\/\n#ifdef POTFIT\nPyMethodDef AtomsMD::methods[]=EmptyPyMethodDef(16);\n#else\nPyMethodDef AtomsMD::methods[]=EmptyPyMethodDef(13);\n#endif\n\/*--------------------------------------------*\/\nvoid AtomsMD::setup_tp_methods()\n{\n ml_do(methods[0]);\n ml_mul(methods[1]);\n ml_strain(methods[2]);\n ml_create_temp(methods[3]);\n ml_add_elem(methods[4]);\n ForceFieldLJ::ml_new(methods[5]);\n ForceFieldEAM::ml_new(methods[6],methods[7],methods[8]);\n ForceFieldFS::ml_new(methods[9]);\n ForceFieldEAMFunc::ml_new(methods[10]);\n ImportCFGMD::ml_import(methods[11]);\n#ifdef POTFIT\n ForceFieldEAMFit::ml_new(methods[12]);\n ForceFieldEAMFitO::ml_new(methods[13]);\n ForceFieldEAMPotFitAckOgata::ml_new(methods[14]);\n#endif\n}\n\/*--------------------------------------------\n \n --------------------------------------------*\/\nvoid AtomsMD::ml_create_temp(PyMethodDef& tp_method)\n{\n tp_method.ml_flags=METH_VARARGS | METH_KEYWORDS;\n tp_method.ml_name=\"create_temp\";\n tp_method.ml_meth=(PyCFunction)(PyCFunctionWithKeywords)(\n [](PyObject* self,PyObject* args,PyObject* kwds)->PyObject*\n {\n AtomsMD::Object* __self=reinterpret_cast<AtomsMD::Object*>(self);\n if(std::isnan(__self->atoms->kB))\n {\n PyErr_SetString(PyExc_TypeError,\"boltzmann constant should be set prior to create_temp\");\n return NULL;\n }\n \n FuncAPI<type0,int> f(\"create_temp\",{\"temp\",\"seed\"});\n f.logics<0>()[0]=VLogics(\"gt\",0.0);\n f.logics<1>()[0]=VLogics(\"gt\",0);\n if(f(args,kwds)) return NULL;\n \n __self->atoms->create_T(f.val<0>(),f.val<1>());\n Py_RETURN_NONE;\n });\n tp_method.ml_doc=R\"---(\n create_temp(temp,seed)\n \n Create a random velcity field\n \n Parameters\n ----------\n temp : double\n Temperature\n seed : int\n random seed\n \n Returns\n -------\n None\n \n )---\";\n}\n\/*--------------------------------------------\n \n --------------------------------------------*\/\nvoid AtomsMD::ml_add_elem(PyMethodDef& tp_method)\n{\n tp_method.ml_flags=METH_VARARGS | METH_KEYWORDS;\n tp_method.ml_name=\"add_elem\";\n tp_method.ml_meth=(PyCFunction)(PyCFunctionWithKeywords)(\n [](PyObject* self,PyObject* args,PyObject* kwds)->PyObject*\n {\n FuncAPI<std::string,type0> f(\"add_elem\",{\"elem\",\"mass\"});\n f.logics<1>()[0]=VLogics(\"gt\",0.0);\n if(f(args,kwds)) return NULL;\n \n AtomsMD::Object* __self=reinterpret_cast<AtomsMD::Object*>(self);\n __self->atoms->elements.add_type(f.val<1>(),f.val<0>().c_str());\n \n Py_RETURN_NONE;\n });\n tp_method.ml_doc=R\"---(\n add_elem(elem,mass)\n \n Add a new element to the system\n \n Parameters\n ----------\n elem : string\n New element\n seed : double\n Mass of the element\n \n Returns\n -------\n None\n \n )---\";\n}\n\n<|endoftext|>"} {"text":"<commit_before>#pragma once\n\n#include <geneial\/core\/operations\/coupling\/SimpleCouplingOperation.h>\n\ngeneial_private_namespace(geneial)\n{\ngeneial_private_namespace(operation)\n{\ngeneial_private_namespace(coupling)\n{\nusing ::geneial::population::Population;\nusing ::geneial::operation::crossover::BaseCrossoverOperation;\nusing ::geneial::operation::selection::BaseSelectionOperation;\nusing ::geneial::population::management::BaseManager;\n\ngeneial_export_namespace\n{\n\ntemplate<typename FITNESS_TYPE>\ntypename BaseCouplingOperation<FITNESS_TYPE>::offspring_result_set SimpleCouplingOperation<FITNESS_TYPE>::doCopulate(\n const typename BaseSelectionOperation<FITNESS_TYPE>::selection_result_set &mating_pool,\n const BaseCrossoverOperation<FITNESS_TYPE> &crossoverOperation, BaseManager<FITNESS_TYPE> &manager)\n{\n\n typedef typename BaseCouplingOperation<FITNESS_TYPE>::offspring_result_set offspring_container;\n typedef typename BaseCrossoverOperation<FITNESS_TYPE>::crossover_result_set children_container;\n typedef typename BaseSelectionOperation<FITNESS_TYPE>::selection_result_set mating_container;\n typedef typename BaseChromosome<FITNESS_TYPE>::ptr chrom_ptr;\n\n unsigned int offspring_left = this->getSettings().getNumberOfOffspring();\n\n offspring_container offspring; \/\/A small container for all the little children :-)\n offspring.reserve(offspring_left);\n\n\n assert(mating_pool.size() > 1);\n \/\/iterate over mating candidates and create a pairwise mapping.\n \/**\n * Example getNumberOfOffspring: 8, #mating_pool = 5\n *\n * Parent1 \\\/ Child1\n * Parent2 \/\\ Child2\n *\n * Parent3 \\\/ Child3\n * Parent4 \/\\ Child4\n *\n * Parent5 \\\/ Child5\n * Parent1 \/\\ Child6\n *\n * Parent2 \\\/ Child7\n * Parent3 \/\n *\/\n for (typename mating_container::const_iterator it = mating_pool.begin(); offspring_left > 0;)\n {\n \/\/TODO (bewo) REFACTOR: research cyclic iterators to avoid all those ugly case distinctions\n chrom_ptr parent1(*it);\n it++;\n \/\/wrap around if necessary\n if (it == mating_pool.end())\n {\n it = mating_pool.begin();\n }\n\n chrom_ptr parent2(*it);\n it++;\n if (it == mating_pool.end())\n {\n it = mating_pool.begin();\n }\n\n const children_container children(crossoverOperation.doCrossover(parent1, parent2));\n offspring_left -= this->copyUnlessMaximumReached(offspring,children,offspring_left);\n\n if (offspring_left > 0 && !crossoverOperation.isSymmetric())\n {\n const children_container assymetricChildren(crossoverOperation.doCrossover(parent2, parent1));\n offspring_left -= this->copyUnlessMaximumReached(offspring,assymetricChildren,offspring_left);\n }\n }\n\n return offspring;\n}\n\n} \/* geneial_export_namespace *\/\n} \/* private namespace coupling *\/\n} \/* private namespace operation *\/\n} \/* private namespace geneial *\/\n\n<commit_msg>Update SimpleCouplingOperation.hpp<commit_after>#pragma once\n\n#include <geneial\/core\/operations\/coupling\/SimpleCouplingOperation.h>\n\ngeneial_private_namespace(geneial)\n{\ngeneial_private_namespace(operation)\n{\ngeneial_private_namespace(coupling)\n{\nusing ::geneial::population::Population;\nusing ::geneial::operation::crossover::BaseCrossoverOperation;\nusing ::geneial::operation::selection::BaseSelectionOperation;\nusing ::geneial::population::management::BaseManager;\n\ngeneial_export_namespace\n{\n\ntemplate<typename FITNESS_TYPE>\ntypename BaseCouplingOperation<FITNESS_TYPE>::offspring_result_set SimpleCouplingOperation<FITNESS_TYPE>::doCopulate(\n const typename BaseSelectionOperation<FITNESS_TYPE>::selection_result_set &mating_pool,\n const BaseCrossoverOperation<FITNESS_TYPE> &crossoverOperation, BaseManager<FITNESS_TYPE> &manager)\n{\n\n typedef typename BaseCouplingOperation<FITNESS_TYPE>::offspring_result_set offspring_container;\n typedef typename BaseCrossoverOperation<FITNESS_TYPE>::crossover_result_set children_container;\n typedef typename BaseSelectionOperation<FITNESS_TYPE>::selection_result_set mating_container;\n typedef typename BaseChromosome<FITNESS_TYPE>::ptr chrom_ptr;\n\n unsigned int offspring_left = this->getSettings().getNumberOfOffspring();\n\n offspring_container offspring; \/\/A small container for all the little children :-)\n offspring.reserve(offspring_left);\n\n\n assert(mating_pool.size() > 1);\n \/\/iterate over mating candidates and create a pairwise mapping.\n \/**\n * Example getNumberOfOffspring: 7, #mating_pool = 5\n *\n * Parent1 \\\/ Child1\n * Parent2 \/\\ Child2\n *\n * Parent3 \\\/ Child3\n * Parent4 \/\\ Child4\n *\n * Parent5 \\\/ Child5\n * Parent1 \/\\ Child6\n *\n * Parent2 \\\/ Child7\n * Parent3 \/\n *\/\n for (typename mating_container::const_iterator it = mating_pool.begin(); offspring_left > 0;)\n {\n \/\/TODO (bewo) REFACTOR: research cyclic iterators to avoid all those ugly case distinctions\n chrom_ptr parent1(*it);\n it++;\n \/\/wrap around if necessary\n if (it == mating_pool.end())\n {\n it = mating_pool.begin();\n }\n\n chrom_ptr parent2(*it);\n it++;\n if (it == mating_pool.end())\n {\n it = mating_pool.begin();\n }\n\n const children_container children(crossoverOperation.doCrossover(parent1, parent2));\n offspring_left -= this->copyUnlessMaximumReached(offspring,children,offspring_left);\n\n if (offspring_left > 0 && !crossoverOperation.isSymmetric())\n {\n const children_container assymetricChildren(crossoverOperation.doCrossover(parent2, parent1));\n offspring_left -= this->copyUnlessMaximumReached(offspring,assymetricChildren,offspring_left);\n }\n }\n\n return offspring;\n}\n\n} \/* geneial_export_namespace *\/\n} \/* private namespace coupling *\/\n} \/* private namespace operation *\/\n} \/* private namespace geneial *\/\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ Author: Hong Jiang <hong@hjiang.net>\n\n#include \"jsonxx.h\"\n\n#include <cctype>\n#include <iostream>\n#include <sstream>\n\nnamespace jsonxx {\n\n\/\/ Try to consume characters from the input stream and match the\n\/\/ pattern string.\nbool match(const char* pattern, std::istream& input) {\n input >> std::ws;\n const char* cur(pattern);\n char ch(0);\n while(input && !input.eof() && *cur != 0) {\n input.get(ch);\n if (ch != *cur) {\n input.putback(ch);\n return false;\n } else {\n cur++;\n }\n }\n return *cur == 0;\n}\n\nbool parse_string(std::istream& input, std::string* value) {\n if (!match(\"\\\"\", input)) {\n return false;\n }\n char ch;\n while(!input.eof() && input.good()) {\n input.get(ch);\n if (ch == '\"') {\n break;\n }\n if (ch == '\\\\') {\n input.get(ch);\n switch(ch) {\n case '\"':\n case '\\\\':\n case '\/':\n value->push_back(ch);\n break;\n case 'b':\n value->push_back('\\b');\n break;\n case 'f':\n value->push_back('\\f');\n break;\n case 'n':\n value->push_back('\\n');\n break;\n case 'r':\n value->push_back('\\r');\n break;\n case 't':\n value->push_back('\\t');\n break;\n default:\n value->push_back('\\\\');\n value->push_back(ch);\n break;\n }\n } else {\n value->push_back(ch);\n }\n }\n if (input && ch == '\"') {\n return true;\n } else {\n return false;\n }\n}\n\nbool parse_bool(std::istream& input, bool* value) {\n if (match(\"true\", input)) {\n *value = true;\n return true;\n }\n if (match(\"false\", input)) {\n *value = false;\n return true;\n }\n return false;\n}\n\nbool parse_null(std::istream& input) {\n if (match(\"null\", input)) {\n return true;\n }\n return false;\n}\n\nbool parse_number(std::istream& input, long* value) {\n input >> std::ws;\n char ch;\n std::string value_str;\n int sign = 1;\n if (match(\"-\", input)) {\n sign = -1;\n } else {\n match(\"+\", input);\n }\n while(input && !input.eof()) {\n input.get(ch);\n if (!isdigit(ch)) {\n input.putback(ch);\n break;\n }\n value_str.push_back(ch);\n }\n if (value_str.size() > 0) {\n std::istringstream(value_str) >> *value;\n return true;\n } else {\n return false;\n }\n}\n\nObject::Object() : value_map_() {}\n\nObject::~Object() {\n std::map<std::string, Value*>::iterator i;\n for (i = value_map_.begin(); i != value_map_.end(); ++i) {\n delete i->second;\n }\n}\n\nbool Object::parse(std::istream& input) {\n if (!match(\"{\", input)) {\n return false;\n }\n\n do {\n std::string key;\n if (!parse_string(input, &key)) {\n return false;\n }\n if (!match(\":\", input)) {\n return false;\n }\n Value* v = new Value();\n if (!v->parse(input)) {\n delete v;\n break;\n }\n value_map_[key] = v;\n } while (match(\",\", input));\n\n if (!match(\"}\", input)) {\n return false;\n }\n return true;\n}\n\nValue::Value() : type_(INVALID_) {}\n\nValue::~Value() {\n if (type_ == STRING_) {\n delete string_value_;\n }\n if (type_ == OBJECT_) {\n delete object_value_;\n }\n if (type_ == ARRAY_) {\n delete array_value_;\n }\n}\n\nbool Value::parse(std::istream& input) {\n std::string string_value;\n if (parse_string(input, &string_value)) {\n string_value_ = new std::string();\n string_value_->swap(string_value);\n type_ = STRING_;\n return true;\n }\n if (parse_number(input, &integer_value_)) {\n type_ = INTEGER_;\n return true;\n }\n\n if (parse_bool(input, &bool_value_)) {\n type_ = BOOL_;\n return true;\n }\n if (parse_null(input)) {\n type_ = NULL_;\n return true;\n }\n if (input.peek() == '[') {\n array_value_ = new Array();\n if (array_value_->parse(input)) {\n type_ = ARRAY_;\n return true;\n }\n delete array_value_;\n }\n object_value_ = new Object();\n if (object_value_->parse(input)) {\n type_ = OBJECT_;\n return true;\n }\n delete object_value_;\n return false;\n}\n\nArray::Array() : values_() {}\n\nArray::~Array() {\n for (unsigned int i = 0; i < values_.size(); ++i) {\n delete values_[i];\n }\n}\n\nbool Array::parse(std::istream& input) {\n if (!match(\"[\", input)) {\n return false;\n }\n\n do {\n Value* v = new Value();\n if (!v->parse(input)) {\n delete v;\n break;\n }\n values_.push_back(v);\n } while (match(\",\", input));\n\n if (!match(\"]\", input)) {\n return false;\n }\n return true;\n}\n\nstatic std::ostream& stream_string(std::ostream& stream,\n const std::string& string) {\n stream << '\"';\n for (std::string::const_iterator i = string.begin(),\n e = string.end(); i != e; ++i) {\n if (*i == '\"' || *i == '\\\\') {\n stream << '\\\\' << *i;\n } else {\n stream << *i;\n }\n }\n stream << '\"';\n return stream;\n}\n\n} \/\/ namespace jsonxx\n\nstd::ostream& operator<<(std::ostream& stream, const jsonxx::Value& v) {\n if (v.is<long>()) {\n return stream << v.get<long>();\n } else if (v.is<std::string>()) {\n return jsonxx::stream_string(stream, v.get<std::string>());\n } else if (v.is<bool>()) {\n if (v.get<bool>()) {\n return stream << \"true\";\n } else {\n return stream << \"false\";\n }\n } else if (v.is<jsonxx::Value::Null>()) {\n return stream << \"null\";\n } else if (v.is<jsonxx::Object>()) {\n return stream << v.get<jsonxx::Object>();\n } else if (v.is<jsonxx::Array>()){\n return stream << v.get<jsonxx::Array>();\n }\n \/\/ Shouldn't reach here.\n return stream;\n}\n\nstd::ostream& operator<<(std::ostream& stream, const jsonxx::Array& v) {\n stream << \"[\";\n const std::vector<jsonxx::Value*>& values(v.values());\n for (unsigned int i = 0; i < values.size()-1; ++i) {\n stream << *(values[i]) << \", \";\n }\n return stream << *(values[values.size()-1]) << \"]\";\n}\n\nstd::ostream& operator<<(std::ostream& stream, const jsonxx::Object& v) {\n stream << \"{\";\n const std::map<std::string, jsonxx::Value*>& kv(v.kv_map());\n for (std::map<std::string, jsonxx::Value*>::const_iterator i = kv.begin();\n i != kv.end(); \/**\/) {\n jsonxx::stream_string(stream, i->first);\n stream << \": \" << *(i->second);\n ++i;\n if ( i != kv.end()) {\n stream << \", \";\n }\n }\n return stream << \"}\";\n}\n<commit_msg>[performance] improve number parsing speed<commit_after>\/\/ Author: Hong Jiang <hong@hjiang.net>\n\n#include \"jsonxx.h\"\n\n#include <cctype>\n#include <iostream>\n#include <sstream>\n\nnamespace jsonxx {\n\n\/\/ Try to consume characters from the input stream and match the\n\/\/ pattern string.\nbool match(const char* pattern, std::istream& input) {\n input >> std::ws;\n const char* cur(pattern);\n char ch(0);\n while(input && !input.eof() && *cur != 0) {\n input.get(ch);\n if (ch != *cur) {\n input.putback(ch);\n return false;\n } else {\n cur++;\n }\n }\n return *cur == 0;\n}\n\nbool parse_string(std::istream& input, std::string* value) {\n if (!match(\"\\\"\", input)) {\n return false;\n }\n char ch;\n while(!input.eof() && input.good()) {\n input.get(ch);\n if (ch == '\"') {\n break;\n }\n if (ch == '\\\\') {\n input.get(ch);\n switch(ch) {\n case '\"':\n case '\\\\':\n case '\/':\n value->push_back(ch);\n break;\n case 'b':\n value->push_back('\\b');\n break;\n case 'f':\n value->push_back('\\f');\n break;\n case 'n':\n value->push_back('\\n');\n break;\n case 'r':\n value->push_back('\\r');\n break;\n case 't':\n value->push_back('\\t');\n break;\n default:\n value->push_back('\\\\');\n value->push_back(ch);\n break;\n }\n } else {\n value->push_back(ch);\n }\n }\n if (input && ch == '\"') {\n return true;\n } else {\n return false;\n }\n}\n\nbool parse_bool(std::istream& input, bool* value) {\n if (match(\"true\", input)) {\n *value = true;\n return true;\n }\n if (match(\"false\", input)) {\n *value = false;\n return true;\n }\n return false;\n}\n\nbool parse_null(std::istream& input) {\n if (match(\"null\", input)) {\n return true;\n }\n return false;\n}\n\nbool parse_number(std::istream& input, long* value) {\n input >> std::ws;\n input >> *value;\n if (input.fail()) {\n input.clear();\n return false;\n }\n return true;\n}\n\nObject::Object() : value_map_() {}\n\nObject::~Object() {\n std::map<std::string, Value*>::iterator i;\n for (i = value_map_.begin(); i != value_map_.end(); ++i) {\n delete i->second;\n }\n}\n\nbool Object::parse(std::istream& input) {\n if (!match(\"{\", input)) {\n return false;\n }\n\n do {\n std::string key;\n if (!parse_string(input, &key)) {\n return false;\n }\n if (!match(\":\", input)) {\n return false;\n }\n Value* v = new Value();\n if (!v->parse(input)) {\n delete v;\n break;\n }\n value_map_[key] = v;\n } while (match(\",\", input));\n\n if (!match(\"}\", input)) {\n return false;\n }\n return true;\n}\n\nValue::Value() : type_(INVALID_) {}\n\nValue::~Value() {\n if (type_ == STRING_) {\n delete string_value_;\n }\n if (type_ == OBJECT_) {\n delete object_value_;\n }\n if (type_ == ARRAY_) {\n delete array_value_;\n }\n}\n\nbool Value::parse(std::istream& input) {\n std::string string_value;\n if (parse_string(input, &string_value)) {\n string_value_ = new std::string();\n string_value_->swap(string_value);\n type_ = STRING_;\n return true;\n }\n if (parse_number(input, &integer_value_)) {\n type_ = INTEGER_;\n return true;\n }\n\n if (parse_bool(input, &bool_value_)) {\n type_ = BOOL_;\n return true;\n }\n if (parse_null(input)) {\n type_ = NULL_;\n return true;\n }\n if (input.peek() == '[') {\n array_value_ = new Array();\n if (array_value_->parse(input)) {\n type_ = ARRAY_;\n return true;\n }\n delete array_value_;\n }\n object_value_ = new Object();\n if (object_value_->parse(input)) {\n type_ = OBJECT_;\n return true;\n }\n delete object_value_;\n return false;\n}\n\nArray::Array() : values_() {}\n\nArray::~Array() {\n for (unsigned int i = 0; i < values_.size(); ++i) {\n delete values_[i];\n }\n}\n\nbool Array::parse(std::istream& input) {\n if (!match(\"[\", input)) {\n return false;\n }\n\n do {\n Value* v = new Value();\n if (!v->parse(input)) {\n delete v;\n break;\n }\n values_.push_back(v);\n } while (match(\",\", input));\n\n if (!match(\"]\", input)) {\n return false;\n }\n return true;\n}\n\nstatic std::ostream& stream_string(std::ostream& stream,\n const std::string& string) {\n stream << '\"';\n for (std::string::const_iterator i = string.begin(),\n e = string.end(); i != e; ++i) {\n if (*i == '\"' || *i == '\\\\') {\n stream << '\\\\' << *i;\n } else {\n stream << *i;\n }\n }\n stream << '\"';\n return stream;\n}\n\n} \/\/ namespace jsonxx\n\nstd::ostream& operator<<(std::ostream& stream, const jsonxx::Value& v) {\n if (v.is<long>()) {\n return stream << v.get<long>();\n } else if (v.is<std::string>()) {\n return jsonxx::stream_string(stream, v.get<std::string>());\n } else if (v.is<bool>()) {\n if (v.get<bool>()) {\n return stream << \"true\";\n } else {\n return stream << \"false\";\n }\n } else if (v.is<jsonxx::Value::Null>()) {\n return stream << \"null\";\n } else if (v.is<jsonxx::Object>()) {\n return stream << v.get<jsonxx::Object>();\n } else if (v.is<jsonxx::Array>()){\n return stream << v.get<jsonxx::Array>();\n }\n \/\/ Shouldn't reach here.\n return stream;\n}\n\nstd::ostream& operator<<(std::ostream& stream, const jsonxx::Array& v) {\n stream << \"[\";\n const std::vector<jsonxx::Value*>& values(v.values());\n for (unsigned int i = 0; i < values.size()-1; ++i) {\n stream << *(values[i]) << \", \";\n }\n return stream << *(values[values.size()-1]) << \"]\";\n}\n\nstd::ostream& operator<<(std::ostream& stream, const jsonxx::Object& v) {\n stream << \"{\";\n const std::map<std::string, jsonxx::Value*>& kv(v.kv_map());\n for (std::map<std::string, jsonxx::Value*>::const_iterator i = kv.begin();\n i != kv.end(); \/**\/) {\n jsonxx::stream_string(stream, i->first);\n stream << \": \" << *(i->second);\n ++i;\n if ( i != kv.end()) {\n stream << \", \";\n }\n }\n return stream << \"}\";\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/---------------------------------------------------------------------------\/\/\n\/\/!\n\/\/! \\file tstSubshellIncoherentPhotonScatteringDistribution.cpp\n\/\/! \\author Alex Robinson\n\/\/! \\brier Subshell incoherent photon scattering distribution unit tests\n\/\/!\n\/\/---------------------------------------------------------------------------\/\/\n\n\/\/ Std Lib Includes\n#include <iostream>\n#include <limits>\n \n\/\/ Trilinos Includes\n#include <Teuchos_UnitTestHarness.hpp>\n#include <Teuchos_RCP.hpp>\n#include <Teuchos_VerboseObject.hpp>\n#include <Teuchos_Array.hpp>\n\n\/\/ FRENSIE Includes\n#include \"MonteCarlo_UnitTestHarnessExtensions.hpp\"\n#include \"MonteCarlo_SubshellIncoherentPhotonScatteringDistribution.hpp\"\n#include \"MonteCarlo_SubshellType.hpp\"\n#include \"Data_ElectronPhotonRelaxationDataContainer.hpp\"\n#include \"Utility_TabularDistribution.hpp\"\n#include \"Utility_RandomNumberGenerator.hpp\"\n#include \"Utility_DirectionHelpers.hpp\"\n\n\/\/---------------------------------------------------------------------------\/\/\n\/\/ Testing Variables\n\/\/---------------------------------------------------------------------------\/\/\n\nTeuchos::RCP<MonteCarlo::PhotonScatteringDistribution>\n distribution;\n\n\/\/---------------------------------------------------------------------------\/\/\n\/\/ Tests.\n\/\/---------------------------------------------------------------------------\/\/\n\/\/ Check that the subshell can be returned\nTEUCHOS_UNIT_TEST( SubshellIncoherentPhotonScatteringDistribution,\n\t\t getSubshell )\n{\n Teuchos::RCP<MonteCarlo::SubshellIncoherentPhotonScatteringDistribution>\n derived_dist = Teuchos::rcp_dynamic_cast<MonteCarlo::SubshellIncoherentPhotonScatteringDistribution>( distribution );\n\n TEST_EQUALITY_CONST( derived_dist->getSubshell(), MonteCarlo::K_SUBSHELL);\n}\n\n\/\/---------------------------------------------------------------------------\/\/\n\/\/ Check that the binding energy can be returned\nTEUCHOS_UNIT_TEST( SubshellIncoherentPhotonScatteringDistribution,\n\t\t getBindingEnergy )\n{\n Teuchos::RCP<MonteCarlo::SubshellIncoherentPhotonScatteringDistribution>\n derived_dist = Teuchos::rcp_dynamic_cast<MonteCarlo::SubshellIncoherentPhotonScatteringDistribution>( distribution );\n\n TEST_EQUALITY_CONST( derived_dist->getBindingEnergy(), \n\t\t 8.82899999999999935e-02 );\n}\n\n\/\/---------------------------------------------------------------------------\/\/\n\/\/ Check that a photon can be scattered incoherently without Doppler broadening\nTEUCHOS_UNIT_TEST( SubshellIncoherentPhotonScatteringDistribution,\n\t\t scatterPhoton )\n{\n MonteCarlo::ParticleBank bank;\n \n MonteCarlo::PhotonState photon( 0 );\n photon.setEnergy( 20.0 );\n photon.setDirection( 0.0, 0.0, 1.0 );\n \n MonteCarlo::SubshellType shell_of_interaction;\n\n \/\/ Set up the random number stream\n std::vector<double> fake_stream( 4 );\n fake_stream[0] = 0.001; \/\/ sample from first term of koblinger's method\n fake_stream[1] = 0.5; \/\/ x = 40.13902672495315, mu = 0.0\n fake_stream[2] = 1.0-1e-15; \/\/ accept x in occupation number rejection loop\n fake_stream[3] = 0.5; \/\/ azimuthal_angle = pi\n\n Utility::RandomNumberGenerator::setFakeStream( fake_stream );\n\n distribution->scatterPhoton( photon,\n\t\t\t bank,\n\t\t\t shell_of_interaction);\n\n Utility::RandomNumberGenerator::unsetFakeStream();\n\n TEST_EQUALITY_CONST( bank.size(), 1 );\n TEST_EQUALITY_CONST( bank.top()->getParticleType(), MonteCarlo::ELECTRON );\n TEST_FLOATING_EQUALITY( bank.top()->getEnergy(), \n\t\t\t 19.50173181484825,\n\t\t\t 1e-15 );\n TEST_FLOATING_EQUALITY( bank.top()->getZDirection(), \n\t\t\t 0.9996898054103247, \n\t\t\t 1e-15 );\n TEST_FLOATING_EQUALITY( bank.top()->getYDirection(), \n\t\t\t -0.024905681252821114, \n\t\t\t 1e-12 );\n UTILITY_TEST_FLOATING_EQUALITY( bank.top()->getXDirection(), 0.0, 1e-15 );\n TEST_FLOATING_EQUALITY( photon.getEnergy(), 0.4982681851517501, 1e-15 );\n UTILITY_TEST_FLOATING_EQUALITY( photon.getZDirection(), 0.0, 1e-15 );\n TEST_FLOATING_EQUALITY( photon.getYDirection(), 1.0, 1e-15 );\n UTILITY_TEST_FLOATING_EQUALITY( photon.getXDirection(), 0.0, 1e-15 );\n TEST_EQUALITY_CONST( shell_of_interaction, MonteCarlo::K_SUBSHELL );\n}\n\n\/\/---------------------------------------------------------------------------\/\/\n\/\/ Custom main function\n\/\/---------------------------------------------------------------------------\/\/\nint main( int argc, char** argv )\n{\n std::string test_native_file_name;\n\n Teuchos::CommandLineProcessor& clp = Teuchos::UnitTestRepository::getCLP();\n\n clp.setOption( \"test_native_file\",\n\t\t &test_native_file_name,\n\t\t \"Test Native file name\" );\n\n const Teuchos::RCP<Teuchos::FancyOStream> out = \n Teuchos::VerboseObjectBase::getDefaultOStream();\n\n Teuchos::CommandLineProcessor::EParseCommandLineReturn parse_return = \n clp.parse(argc,argv);\n\n if ( parse_return != Teuchos::CommandLineProcessor::PARSE_SUCCESSFUL ) \n {\n *out << \"\\nEnd Result: TEST FAILED\" << std::endl;\n return parse_return;\n }\n\n {\n \/\/ Create the native data file container\n Data::ElectronPhotonRelaxationDataContainer \n data_container( test_native_file_name );\n \n \/\/ Extract the Compton profile and occupation number for the first subshell\n const std::vector<double>& compton_profile_grid_s1 = \n data_container.getComptonProfileMomentumGrid( 1 );\n \n const std::vector<double>& compton_profile_s1 = \n data_container.getComptonProfile( 1 );\n \n const std::vector<double>& occupation_number_grid_s1 = \n data_container.getOccupationNumberMomentumGrid( 1 );\n \n const std::vector<double>& occupation_number_s1 = \n data_container.getOccupationNumber( 1 );\n \n \/\/ Create the Compton profile and occupation number distributions\n Teuchos::RCP<const Utility::TabularOneDDistribution> compton_profile_s1_dist(\n\t\t\t new Utility::TabularDistribution<Utility::LinLin>( \n\t\t\t\t\t\t compton_profile_grid_s1,\n\t\t\t\t\t\t compton_profile_s1 ) );\n\n Teuchos::RCP<const Utility::OneDDistribution> occupation_number_s1_dist(\n\t\t\t new Utility::TabularDistribution<Utility::LinLin>(\n\t\t\t\t\t\t occupation_number_grid_s1,\n\t\t\t\t\t\t occupation_number_s1 ) );\n\n \/\/ Create the subshell incoherent distributions\n distribution.reset(\n\t\tnew MonteCarlo::SubshellIncoherentPhotonScatteringDistribution(\n\t\t\t MonteCarlo::convertENDFDesignatorToSubshellEnum( 1 ),\n\t\t\t data_container.getSubshellOccupancy( 1 ),\n\t\t\t data_container.getSubshellBindingEnergy( 1 ),\n\t\t\t occupation_number_s1_dist,\n\t\t\t 3.0 ) );\n }\n\n \/\/ Initialize the random number generator\n Utility::RandomNumberGenerator::createStreams();\n \n \/\/ Run the unit tests\n Teuchos::GlobalMPISession mpiSession( &argc, &argv );\n\n const bool success = Teuchos::UnitTestRepository::runUnitTests( *out );\n\n if (success)\n *out << \"\\nEnd Result: TEST PASSED\" << std::endl;\n else\n *out << \"\\nEnd Result: TEST FAILED\" << std::endl;\n\n clp.printFinalTimerSummary(out.ptr());\n\n return (success ? 0 : 1); \n}\n\n\/\/---------------------------------------------------------------------------\/\/\n\/\/ end tstSubshellIncoherentPhotonScatteringDistribution.cpp\n\/\/---------------------------------------------------------------------------\/\/\n<commit_msg>Added tests to the subshell incoherent photon scattering distribution.<commit_after>\/\/---------------------------------------------------------------------------\/\/\n\/\/!\n\/\/! \\file tstSubshellIncoherentPhotonScatteringDistribution.cpp\n\/\/! \\author Alex Robinson\n\/\/! \\brier Subshell incoherent photon scattering distribution unit tests\n\/\/!\n\/\/---------------------------------------------------------------------------\/\/\n\n\/\/ Std Lib Includes\n#include <iostream>\n#include <limits>\n \n\/\/ Trilinos Includes\n#include <Teuchos_UnitTestHarness.hpp>\n#include <Teuchos_RCP.hpp>\n#include <Teuchos_VerboseObject.hpp>\n#include <Teuchos_Array.hpp>\n\n\/\/ FRENSIE Includes\n#include \"MonteCarlo_UnitTestHarnessExtensions.hpp\"\n#include \"MonteCarlo_SubshellIncoherentPhotonScatteringDistribution.hpp\"\n#include \"MonteCarlo_SubshellType.hpp\"\n#include \"Data_ElectronPhotonRelaxationDataContainer.hpp\"\n#include \"Utility_TabularDistribution.hpp\"\n#include \"Utility_RandomNumberGenerator.hpp\"\n#include \"Utility_DirectionHelpers.hpp\"\n\n\/\/---------------------------------------------------------------------------\/\/\n\/\/ Testing Variables\n\/\/---------------------------------------------------------------------------\/\/\n\nTeuchos::RCP<MonteCarlo::PhotonScatteringDistribution>\n distribution;\n\n\/\/---------------------------------------------------------------------------\/\/\n\/\/ Tests.\n\/\/---------------------------------------------------------------------------\/\/\n\/\/ Check that the distribution can be evaluated\nTEUCHOS_UNIT_TEST( SubshellIncoherentPhotonScatteringDistribution,\n\t\t evaluate )\n{\n double dist_value = distribution->evaluate(\n\t\t\t Utility::PhysicalConstants::electron_rest_mass_energy,\n\t\t\t 1.0 );\n \n TEST_FLOATING_EQUALITY( dist_value, 0.0, 1e-15 );\n\n dist_value = distribution->evaluate( \n\t\t\t Utility::PhysicalConstants::electron_rest_mass_energy,\n\t\t\t -1.0 );\n \n TEST_FLOATING_EQUALITY( dist_value, 0.18204031443868224, 1e-6 );\n\n dist_value = distribution->evaluate( 1.0, 1.0 );\n \n TEST_FLOATING_EQUALITY( dist_value, 0.0, 1e-15 );\n \n dist_value = distribution->evaluate( 1.0, 0.0 );\n\n TEST_FLOATING_EQUALITY( dist_value, 0.1309675807668618, 1e-15 );\n\n dist_value = distribution->evaluate( 1.0, -1.0 );\n\n TEST_FLOATING_EQUALITY( dist_value, 0.10574024270641422, 1e-15 );\t\n}\n\n\/\/---------------------------------------------------------------------------\/\/\n\/\/ Check that the distribution pdf can be evaluated\nTEUCHOS_UNIT_TEST( SubshellIncoherentPhotonScatteringDistribution,\n\t\t evaluatePDF )\n{\n double pdf_value = distribution->evaluatePDF( \n\t\t\t Utility::PhysicalConstants::electron_rest_mass_energy,\n\t\t\t 1.0 );\n \n TEST_FLOATING_EQUALITY( pdf_value, 0.0, 1e-15 );\n\n pdf_value = distribution->evaluatePDF( \n\t\t\t Utility::PhysicalConstants::electron_rest_mass_energy,\n\t\t\t -1.0 );\n \n TEST_FLOATING_EQUALITY( pdf_value, 0.23410347913716015, 1e-6 );\n\n pdf_value = distribution->evaluatePDF( 1.0, 1.0 );\n\n TEST_FLOATING_EQUALITY( pdf_value, 0.0, 1e-15 );\n\n pdf_value = distribution->evaluatePDF( 1.0, 0.0 );\n\n TEST_FLOATING_EQUALITY( pdf_value, 0.18052763492462426, 1e-15 );\n\n pdf_value = distribution->evaluatePDF( 1.0, -1.0 );\n\n TEST_FLOATING_EQUALITY( pdf_value, 0.14575390199904137, 1e-15 );\n}\n\n\/\/---------------------------------------------------------------------------\/\/\n\/\/ Check that the integrated cross section can be evaluated\nTEUCHOS_UNIT_TEST( SubshellIncoherentPhotonScatteringDistribution,\n\t\t evaluateIntegratedCrossSection )\n{\n double cross_section = distribution->evaluateIntegratedCrossSection( \n\t\t\t Utility::PhysicalConstants::electron_rest_mass_energy,\n\t\t\t 1e-3 );\n \n TEST_FLOATING_EQUALITY( cross_section, 0.777606189833794259, 1e-15 );\n\n cross_section = distribution->evaluateIntegratedCrossSection( 1.0, 1e-3 );\n \n TEST_FLOATING_EQUALITY( cross_section, 0.725471093783202292, 1e-15 );\n\n cross_section = distribution->evaluateIntegratedCrossSection( 20.0, 1e-3 );\n \n TEST_FLOATING_EQUALITY( cross_section, 0.120620123031366933, 1e-15 );\n}\n\n\/\/---------------------------------------------------------------------------\/\/\n\/\/ Check that the subshell can be returned\nTEUCHOS_UNIT_TEST( SubshellIncoherentPhotonScatteringDistribution,\n\t\t getSubshell )\n{\n Teuchos::RCP<MonteCarlo::SubshellIncoherentPhotonScatteringDistribution>\n derived_dist = Teuchos::rcp_dynamic_cast<MonteCarlo::SubshellIncoherentPhotonScatteringDistribution>( distribution );\n\n TEST_EQUALITY_CONST( derived_dist->getSubshell(), MonteCarlo::K_SUBSHELL);\n}\n\n\/\/---------------------------------------------------------------------------\/\/\n\/\/ Check that the binding energy can be returned\nTEUCHOS_UNIT_TEST( SubshellIncoherentPhotonScatteringDistribution,\n\t\t getBindingEnergy )\n{\n Teuchos::RCP<MonteCarlo::SubshellIncoherentPhotonScatteringDistribution>\n derived_dist = Teuchos::rcp_dynamic_cast<MonteCarlo::SubshellIncoherentPhotonScatteringDistribution>( distribution );\n\n TEST_EQUALITY_CONST( derived_dist->getBindingEnergy(), \n\t\t 8.82899999999999935e-02 );\n}\n\n\/\/---------------------------------------------------------------------------\/\/\n\/\/ Check that a photon can be scattered incoherently without Doppler broadening\nTEUCHOS_UNIT_TEST( SubshellIncoherentPhotonScatteringDistribution,\n\t\t scatterPhoton )\n{\n MonteCarlo::ParticleBank bank;\n \n MonteCarlo::PhotonState photon( 0 );\n photon.setEnergy( 20.0 );\n photon.setDirection( 0.0, 0.0, 1.0 );\n \n MonteCarlo::SubshellType shell_of_interaction;\n\n \/\/ Set up the random number stream\n std::vector<double> fake_stream( 4 );\n fake_stream[0] = 0.001; \/\/ sample from first term of koblinger's method\n fake_stream[1] = 0.5; \/\/ x = 40.13902672495315, mu = 0.0\n fake_stream[2] = 1.0-1e-15; \/\/ accept x in occupation number rejection loop\n fake_stream[3] = 0.5; \/\/ azimuthal_angle = pi\n\n Utility::RandomNumberGenerator::setFakeStream( fake_stream );\n\n distribution->scatterPhoton( photon,\n\t\t\t bank,\n\t\t\t shell_of_interaction);\n\n Utility::RandomNumberGenerator::unsetFakeStream();\n\n TEST_EQUALITY_CONST( bank.size(), 1 );\n TEST_EQUALITY_CONST( bank.top()->getParticleType(), MonteCarlo::ELECTRON );\n TEST_FLOATING_EQUALITY( bank.top()->getEnergy(), \n\t\t\t 19.50173181484825,\n\t\t\t 1e-15 );\n TEST_FLOATING_EQUALITY( bank.top()->getZDirection(), \n\t\t\t 0.9996898054103247, \n\t\t\t 1e-15 );\n TEST_FLOATING_EQUALITY( bank.top()->getYDirection(), \n\t\t\t -0.024905681252821114, \n\t\t\t 1e-12 );\n UTILITY_TEST_FLOATING_EQUALITY( bank.top()->getXDirection(), 0.0, 1e-15 );\n TEST_FLOATING_EQUALITY( photon.getEnergy(), 0.4982681851517501, 1e-15 );\n UTILITY_TEST_FLOATING_EQUALITY( photon.getZDirection(), 0.0, 1e-15 );\n TEST_FLOATING_EQUALITY( photon.getYDirection(), 1.0, 1e-15 );\n UTILITY_TEST_FLOATING_EQUALITY( photon.getXDirection(), 0.0, 1e-15 );\n TEST_EQUALITY_CONST( shell_of_interaction, MonteCarlo::K_SUBSHELL );\n}\n\n\/\/---------------------------------------------------------------------------\/\/\n\/\/ Custom main function\n\/\/---------------------------------------------------------------------------\/\/\nint main( int argc, char** argv )\n{\n std::string test_native_file_name;\n\n Teuchos::CommandLineProcessor& clp = Teuchos::UnitTestRepository::getCLP();\n\n clp.setOption( \"test_native_file\",\n\t\t &test_native_file_name,\n\t\t \"Test Native file name\" );\n\n const Teuchos::RCP<Teuchos::FancyOStream> out = \n Teuchos::VerboseObjectBase::getDefaultOStream();\n\n Teuchos::CommandLineProcessor::EParseCommandLineReturn parse_return = \n clp.parse(argc,argv);\n\n if ( parse_return != Teuchos::CommandLineProcessor::PARSE_SUCCESSFUL ) \n {\n *out << \"\\nEnd Result: TEST FAILED\" << std::endl;\n return parse_return;\n }\n\n {\n \/\/ Create the native data file container\n Data::ElectronPhotonRelaxationDataContainer \n data_container( test_native_file_name );\n \n \/\/ Extract the occupation number for the first subshell\n const std::vector<double>& occupation_number_grid_s1 = \n data_container.getOccupationNumberMomentumGrid( 1 );\n \n const std::vector<double>& occupation_number_s1 = \n data_container.getOccupationNumber( 1 );\n\n for( unsigned i = 0; i < occupation_number_grid_s1.size(); ++i )\n {\n std::cout << occupation_number_grid_s1[i] << \" \"\n\t\t<< occupation_number_s1[i] << std::endl;\n }\n \n \/\/ Create the occupation number distributions\n Teuchos::RCP<const Utility::OneDDistribution> occupation_number_s1_dist(\n\t\t\t new Utility::TabularDistribution<Utility::LinLin>(\n\t\t\t\t\t\t occupation_number_grid_s1,\n\t\t\t\t\t\t occupation_number_s1 ) );\n\n \/\/ Create the subshell incoherent distributions\n distribution.reset(\n\t\tnew MonteCarlo::SubshellIncoherentPhotonScatteringDistribution(\n\t\t\t MonteCarlo::convertENDFDesignatorToSubshellEnum( 1 ),\n\t\t\t data_container.getSubshellOccupancy( 1 ),\n\t\t\t data_container.getSubshellBindingEnergy( 1 ),\n\t\t\t occupation_number_s1_dist,\n\t\t\t 3.0 ) );\n }\n\n \/\/ Initialize the random number generator\n Utility::RandomNumberGenerator::createStreams();\n \n \/\/ Run the unit tests\n Teuchos::GlobalMPISession mpiSession( &argc, &argv );\n\n const bool success = Teuchos::UnitTestRepository::runUnitTests( *out );\n\n if (success)\n *out << \"\\nEnd Result: TEST PASSED\" << std::endl;\n else\n *out << \"\\nEnd Result: TEST FAILED\" << std::endl;\n\n clp.printFinalTimerSummary(out.ptr());\n\n return (success ? 0 : 1); \n}\n\n\/\/---------------------------------------------------------------------------\/\/\n\/\/ end tstSubshellIncoherentPhotonScatteringDistribution.cpp\n\/\/---------------------------------------------------------------------------\/\/\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 2007 The Hewlett-Packard Development Company\n * All rights reserved.\n *\n * Redistribution and use of this software in source and binary forms,\n * with or without modification, are permitted provided that the\n * following conditions are met:\n *\n * The software must be used only for Non-Commercial Use which means any\n * use which is NOT directed to receiving any direct monetary\n * compensation for, or commercial advantage from such use. Illustrative\n * examples of non-commercial use are academic research, personal study,\n * teaching, education and corporate research & development.\n * Illustrative examples of commercial use are distributing products for\n * commercial advantage and providing services using the software for\n * commercial advantage.\n *\n * If you wish to use this software or functionality therein that may be\n * covered by patents for commercial use, please contact:\n * Director of Intellectual Property Licensing\n * Office of Strategy and Technology\n * Hewlett-Packard Company\n * 1501 Page Mill Road\n * Palo Alto, California 94304\n *\n * Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer. Redistributions\n * in binary form must reproduce the above copyright notice, this list of\n * conditions and the following disclaimer in the documentation and\/or\n * other materials provided with the distribution. Neither the name of\n * the COPYRIGHT HOLDER(s), HEWLETT-PACKARD COMPANY, nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission. No right of\n * sublicense is granted herewith. Derivatives of the software and\n * output created using the software may be prepared, but only for\n * Non-Commercial Uses. Derivatives of the software may be shared with\n * others provided: (i) the others agree to abide by the list of\n * conditions herein which includes the Non-Commercial Use restrictions;\n * and (ii) such Derivatives of the software include the above copyright\n * notice to acknowledge the contribution from this software where\n * applicable, this list of conditions and the disclaimer below.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n * Authors: Gabe Black\n *\/\n\n#include \"arch\/x86\/predecoder.hh\"\n#include \"base\/misc.hh\"\n#include \"base\/trace.hh\"\n#include \"sim\/host.hh\"\n\nnamespace X86ISA\n{\n void Predecoder::reset()\n {\n origPC = basePC + offset;\n DPRINTF(Predecoder, \"Setting origPC to %#x\\n\", origPC);\n emi.rex = 0;\n emi.legacy = 0;\n emi.opcode.num = 0;\n\n immediateCollected = 0;\n emi.immediate = 0;\n emi.displacement = 0;\n\n emi.modRM = 0;\n emi.sib = 0;\n emi.mode = 0;\n }\n\n void Predecoder::process()\n {\n \/\/This function drives the predecoder state machine.\n\n \/\/Some sanity checks. You shouldn't try to process more bytes if\n \/\/there aren't any, and you shouldn't overwrite an already\n \/\/predecoder ExtMachInst.\n assert(!outOfBytes);\n assert(!emiIsReady);\n\n \/\/While there's still something to do...\n while(!emiIsReady && !outOfBytes)\n {\n uint8_t nextByte = getNextByte();\n switch(state)\n {\n case ResetState:\n reset();\n state = PrefixState;\n case PrefixState:\n state = doPrefixState(nextByte);\n break;\n case OpcodeState:\n state = doOpcodeState(nextByte);\n break;\n case ModRMState:\n state = doModRMState(nextByte);\n break;\n case SIBState:\n state = doSIBState(nextByte);\n break;\n case DisplacementState:\n state = doDisplacementState();\n break;\n case ImmediateState:\n state = doImmediateState();\n break;\n case ErrorState:\n panic(\"Went to the error state in the predecoder.\\n\");\n default:\n panic(\"Unrecognized state! %d\\n\", state);\n }\n }\n }\n\n \/\/Either get a prefix and record it in the ExtMachInst, or send the\n \/\/state machine on to get the opcode(s).\n Predecoder::State Predecoder::doPrefixState(uint8_t nextByte)\n {\n uint8_t prefix = Prefixes[nextByte];\n State nextState = PrefixState;\n if(prefix)\n consumeByte();\n switch(prefix)\n {\n \/\/Operand size override prefixes\n case OperandSizeOverride:\n DPRINTF(Predecoder, \"Found operand size override prefix.\\n\");\n emi.legacy.op = true;\n break;\n case AddressSizeOverride:\n DPRINTF(Predecoder, \"Found address size override prefix.\\n\");\n emi.legacy.addr = true;\n break;\n \/\/Segment override prefixes\n case CSOverride:\n case DSOverride:\n case ESOverride:\n case FSOverride:\n case GSOverride:\n case SSOverride:\n DPRINTF(Predecoder, \"Found segment override.\\n\");\n emi.legacy.seg = prefix;\n break;\n case Lock:\n DPRINTF(Predecoder, \"Found lock prefix.\\n\");\n emi.legacy.lock = true;\n break;\n case Rep:\n DPRINTF(Predecoder, \"Found rep prefix.\\n\");\n emi.legacy.rep = true;\n break;\n case Repne:\n DPRINTF(Predecoder, \"Found repne prefix.\\n\");\n emi.legacy.repne = true;\n break;\n case RexPrefix:\n DPRINTF(Predecoder, \"Found Rex prefix %#x.\\n\", nextByte);\n emi.rex = nextByte;\n break;\n case 0:\n nextState = OpcodeState;\n break;\n default:\n panic(\"Unrecognized prefix %#x\\n\", nextByte);\n }\n return nextState;\n }\n\n \/\/Load all the opcodes (currently up to 2) and then figure out\n \/\/what immediate and\/or ModRM is needed.\n Predecoder::State Predecoder::doOpcodeState(uint8_t nextByte)\n {\n State nextState = ErrorState;\n emi.opcode.num++;\n \/\/We can't handle 3+ byte opcodes right now\n assert(emi.opcode.num < 3);\n consumeByte();\n if(emi.opcode.num == 1 && nextByte == 0x0f)\n {\n nextState = OpcodeState;\n DPRINTF(Predecoder, \"Found two byte opcode.\\n\");\n emi.opcode.prefixA = nextByte;\n }\n else if(emi.opcode.num == 2 &&\n (nextByte == 0x0f ||\n (nextByte & 0xf8) == 0x38))\n {\n panic(\"Three byte opcodes aren't yet supported!\\n\");\n nextState = OpcodeState;\n DPRINTF(Predecoder, \"Found three byte opcode.\\n\");\n emi.opcode.prefixB = nextByte;\n }\n else\n {\n DPRINTF(Predecoder, \"Found opcode %#x.\\n\", nextByte);\n emi.opcode.op = nextByte;\n\n \/\/Figure out the effective operand size. This can be overriden to\n \/\/a fixed value at the decoder level.\n int logOpSize;\n if(\/*FIXME long mode*\/1)\n {\n if(emi.rex.w)\n logOpSize = 3; \/\/ 64 bit operand size\n else if(emi.legacy.op)\n logOpSize = 1; \/\/ 16 bit operand size\n else\n logOpSize = 2; \/\/ 32 bit operand size\n }\n else if(\/*FIXME default 32*\/1)\n {\n if(emi.legacy.op)\n logOpSize = 1; \/\/ 16 bit operand size\n else\n logOpSize = 2; \/\/ 32 bit operand size\n }\n else \/\/ 16 bit default operand size\n {\n if(emi.legacy.op)\n logOpSize = 2; \/\/ 32 bit operand size\n else\n logOpSize = 1; \/\/ 16 bit operand size\n }\n\n \/\/Set the actual op size\n emi.opSize = 1 << logOpSize;\n\n \/\/Figure out the effective address size. This can be overriden to\n \/\/a fixed value at the decoder level.\n int logAddrSize;\n if(\/*FIXME 64-bit mode*\/1)\n {\n if(emi.legacy.addr)\n logAddrSize = 2; \/\/ 32 bit address size\n else\n logAddrSize = 3; \/\/ 64 bit address size\n }\n else if(\/*FIXME default 32*\/1)\n {\n if(emi.legacy.addr)\n logAddrSize = 1; \/\/ 16 bit address size\n else\n logAddrSize = 2; \/\/ 32 bit address size\n }\n else \/\/ 16 bit default operand size\n {\n if(emi.legacy.addr)\n logAddrSize = 2; \/\/ 32 bit address size\n else\n logAddrSize = 1; \/\/ 16 bit address size\n }\n\n \/\/Set the actual address size\n emi.addrSize = 1 << logAddrSize;\n\n \/\/Figure out how big of an immediate we'll retreive based\n \/\/on the opcode.\n int immType = ImmediateType[emi.opcode.num - 1][nextByte];\n immediateSize = SizeTypeToSize[logOpSize - 1][immType];\n\n \/\/Determine what to expect next\n if (UsesModRM[emi.opcode.num - 1][nextByte]) {\n nextState = ModRMState;\n } else {\n if(immediateSize) {\n nextState = ImmediateState;\n } else {\n emiIsReady = true;\n nextState = ResetState;\n }\n }\n }\n return nextState;\n }\n\n \/\/Get the ModRM byte and determine what displacement, if any, there is.\n \/\/Also determine whether or not to get the SIB byte, displacement, or\n \/\/immediate next.\n Predecoder::State Predecoder::doModRMState(uint8_t nextByte)\n {\n State nextState = ErrorState;\n ModRM modRM;\n modRM = nextByte;\n DPRINTF(Predecoder, \"Found modrm byte %#x.\\n\", nextByte);\n if (0) {\/\/FIXME in 16 bit mode\n \/\/figure out 16 bit displacement size\n if(modRM.mod == 0 && modRM.rm == 6 || modRM.mod == 2)\n displacementSize = 2;\n else if(modRM.mod == 1)\n displacementSize = 1;\n else\n displacementSize = 0;\n } else {\n \/\/figure out 32\/64 bit displacement size\n if(modRM.mod == 0 && modRM.rm == 5 || modRM.mod == 2)\n displacementSize = 4;\n else if(modRM.mod == 1)\n displacementSize = 1;\n else\n displacementSize = 0;\n }\n \/\/If there's an SIB, get that next.\n \/\/There is no SIB in 16 bit mode.\n if(modRM.rm == 4 && modRM.mod != 3) {\n \/\/ && in 32\/64 bit mode)\n nextState = SIBState;\n } else if(displacementSize) {\n nextState = DisplacementState;\n } else if(immediateSize) {\n nextState = ImmediateState;\n } else {\n emiIsReady = true;\n nextState = ResetState;\n }\n \/\/The ModRM byte is consumed no matter what\n consumeByte();\n emi.modRM = modRM;\n return nextState;\n }\n\n \/\/Get the SIB byte. We don't do anything with it at this point, other\n \/\/than storing it in the ExtMachInst. Determine if we need to get a\n \/\/displacement or immediate next.\n Predecoder::State Predecoder::doSIBState(uint8_t nextByte)\n {\n State nextState = ErrorState;\n emi.sib = nextByte;\n DPRINTF(Predecoder, \"Found SIB byte %#x.\\n\", nextByte);\n consumeByte();\n if(emi.modRM.mod == 0 && emi.sib.base == 5)\n displacementSize = 4;\n if(displacementSize) {\n nextState = DisplacementState;\n } else if(immediateSize) {\n nextState = ImmediateState;\n } else {\n emiIsReady = true;\n nextState = ResetState;\n }\n return nextState;\n }\n\n \/\/Gather up the displacement, or at least as much of it\n \/\/as we can get.\n Predecoder::State Predecoder::doDisplacementState()\n {\n State nextState = ErrorState;\n\n getImmediate(immediateCollected,\n emi.displacement,\n displacementSize);\n\n DPRINTF(Predecoder, \"Collecting %d byte displacement, got %d bytes.\\n\",\n displacementSize, immediateCollected);\n\n if(displacementSize == immediateCollected) {\n \/\/Reset this for other immediates.\n immediateCollected = 0;\n \/\/Sign extend the displacement\n switch(displacementSize)\n {\n case 1:\n emi.displacement = sext<8>(emi.displacement);\n break;\n case 2:\n emi.displacement = sext<16>(emi.displacement);\n break;\n case 4:\n emi.displacement = sext<32>(emi.displacement);\n break;\n default:\n panic(\"Undefined displacement size!\\n\");\n }\n DPRINTF(Predecoder, \"Collected displacement %#x.\\n\",\n emi.displacement);\n if(immediateSize) {\n nextState = ImmediateState;\n } else {\n emiIsReady = true;\n nextState = ResetState;\n }\n }\n else\n nextState = DisplacementState;\n return nextState;\n }\n\n \/\/Gather up the immediate, or at least as much of it\n \/\/as we can get\n Predecoder::State Predecoder::doImmediateState()\n {\n State nextState = ErrorState;\n\n getImmediate(immediateCollected,\n emi.immediate,\n immediateSize);\n\n DPRINTF(Predecoder, \"Collecting %d byte immediate, got %d bytes.\\n\",\n immediateSize, immediateCollected);\n\n if(immediateSize == immediateCollected)\n {\n \/\/Reset this for other immediates.\n immediateCollected = 0;\n\n \/\/XXX Warning! The following is an observed pattern and might\n \/\/not always be true!\n\n \/\/Instructions which use 64 bit operands but 32 bit immediates\n \/\/need to have the immediate sign extended to 64 bits.\n \/\/Instructions which use true 64 bit immediates won't be\n \/\/affected, and instructions that use true 32 bit immediates\n \/\/won't notice.\n switch(immediateSize)\n {\n case 4:\n emi.immediate = sext<32>(emi.immediate);\n break;\n case 1:\n emi.immediate = sext<8>(emi.immediate);\n }\n\n DPRINTF(Predecoder, \"Collected immediate %#x.\\n\",\n emi.immediate);\n emiIsReady = true;\n nextState = ResetState;\n }\n else\n nextState = ImmediateState;\n return nextState;\n }\n}\n<commit_msg>Add a special case for \"test\" which needs an immediate even though everything else with it's opcode doesn't. Also made some spacing consistent.<commit_after>\/*\n * Copyright (c) 2007 The Hewlett-Packard Development Company\n * All rights reserved.\n *\n * Redistribution and use of this software in source and binary forms,\n * with or without modification, are permitted provided that the\n * following conditions are met:\n *\n * The software must be used only for Non-Commercial Use which means any\n * use which is NOT directed to receiving any direct monetary\n * compensation for, or commercial advantage from such use. Illustrative\n * examples of non-commercial use are academic research, personal study,\n * teaching, education and corporate research & development.\n * Illustrative examples of commercial use are distributing products for\n * commercial advantage and providing services using the software for\n * commercial advantage.\n *\n * If you wish to use this software or functionality therein that may be\n * covered by patents for commercial use, please contact:\n * Director of Intellectual Property Licensing\n * Office of Strategy and Technology\n * Hewlett-Packard Company\n * 1501 Page Mill Road\n * Palo Alto, California 94304\n *\n * Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer. Redistributions\n * in binary form must reproduce the above copyright notice, this list of\n * conditions and the following disclaimer in the documentation and\/or\n * other materials provided with the distribution. Neither the name of\n * the COPYRIGHT HOLDER(s), HEWLETT-PACKARD COMPANY, nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission. No right of\n * sublicense is granted herewith. Derivatives of the software and\n * output created using the software may be prepared, but only for\n * Non-Commercial Uses. Derivatives of the software may be shared with\n * others provided: (i) the others agree to abide by the list of\n * conditions herein which includes the Non-Commercial Use restrictions;\n * and (ii) such Derivatives of the software include the above copyright\n * notice to acknowledge the contribution from this software where\n * applicable, this list of conditions and the disclaimer below.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n * Authors: Gabe Black\n *\/\n\n#include \"arch\/x86\/predecoder.hh\"\n#include \"base\/misc.hh\"\n#include \"base\/trace.hh\"\n#include \"sim\/host.hh\"\n\nnamespace X86ISA\n{\n void Predecoder::reset()\n {\n origPC = basePC + offset;\n DPRINTF(Predecoder, \"Setting origPC to %#x\\n\", origPC);\n emi.rex = 0;\n emi.legacy = 0;\n emi.opcode.num = 0;\n\n immediateCollected = 0;\n emi.immediate = 0;\n emi.displacement = 0;\n\n emi.modRM = 0;\n emi.sib = 0;\n emi.mode = 0;\n }\n\n void Predecoder::process()\n {\n \/\/This function drives the predecoder state machine.\n\n \/\/Some sanity checks. You shouldn't try to process more bytes if\n \/\/there aren't any, and you shouldn't overwrite an already\n \/\/predecoder ExtMachInst.\n assert(!outOfBytes);\n assert(!emiIsReady);\n\n \/\/While there's still something to do...\n while(!emiIsReady && !outOfBytes)\n {\n uint8_t nextByte = getNextByte();\n switch(state)\n {\n case ResetState:\n reset();\n state = PrefixState;\n case PrefixState:\n state = doPrefixState(nextByte);\n break;\n case OpcodeState:\n state = doOpcodeState(nextByte);\n break;\n case ModRMState:\n state = doModRMState(nextByte);\n break;\n case SIBState:\n state = doSIBState(nextByte);\n break;\n case DisplacementState:\n state = doDisplacementState();\n break;\n case ImmediateState:\n state = doImmediateState();\n break;\n case ErrorState:\n panic(\"Went to the error state in the predecoder.\\n\");\n default:\n panic(\"Unrecognized state! %d\\n\", state);\n }\n }\n }\n\n \/\/Either get a prefix and record it in the ExtMachInst, or send the\n \/\/state machine on to get the opcode(s).\n Predecoder::State Predecoder::doPrefixState(uint8_t nextByte)\n {\n uint8_t prefix = Prefixes[nextByte];\n State nextState = PrefixState;\n if(prefix)\n consumeByte();\n switch(prefix)\n {\n \/\/Operand size override prefixes\n case OperandSizeOverride:\n DPRINTF(Predecoder, \"Found operand size override prefix.\\n\");\n emi.legacy.op = true;\n break;\n case AddressSizeOverride:\n DPRINTF(Predecoder, \"Found address size override prefix.\\n\");\n emi.legacy.addr = true;\n break;\n \/\/Segment override prefixes\n case CSOverride:\n case DSOverride:\n case ESOverride:\n case FSOverride:\n case GSOverride:\n case SSOverride:\n DPRINTF(Predecoder, \"Found segment override.\\n\");\n emi.legacy.seg = prefix;\n break;\n case Lock:\n DPRINTF(Predecoder, \"Found lock prefix.\\n\");\n emi.legacy.lock = true;\n break;\n case Rep:\n DPRINTF(Predecoder, \"Found rep prefix.\\n\");\n emi.legacy.rep = true;\n break;\n case Repne:\n DPRINTF(Predecoder, \"Found repne prefix.\\n\");\n emi.legacy.repne = true;\n break;\n case RexPrefix:\n DPRINTF(Predecoder, \"Found Rex prefix %#x.\\n\", nextByte);\n emi.rex = nextByte;\n break;\n case 0:\n nextState = OpcodeState;\n break;\n default:\n panic(\"Unrecognized prefix %#x\\n\", nextByte);\n }\n return nextState;\n }\n\n \/\/Load all the opcodes (currently up to 2) and then figure out\n \/\/what immediate and\/or ModRM is needed.\n Predecoder::State Predecoder::doOpcodeState(uint8_t nextByte)\n {\n State nextState = ErrorState;\n emi.opcode.num++;\n \/\/We can't handle 3+ byte opcodes right now\n assert(emi.opcode.num < 3);\n consumeByte();\n if(emi.opcode.num == 1 && nextByte == 0x0f)\n {\n nextState = OpcodeState;\n DPRINTF(Predecoder, \"Found two byte opcode.\\n\");\n emi.opcode.prefixA = nextByte;\n }\n else if(emi.opcode.num == 2 &&\n (nextByte == 0x0f ||\n (nextByte & 0xf8) == 0x38))\n {\n panic(\"Three byte opcodes aren't yet supported!\\n\");\n nextState = OpcodeState;\n DPRINTF(Predecoder, \"Found three byte opcode.\\n\");\n emi.opcode.prefixB = nextByte;\n }\n else\n {\n DPRINTF(Predecoder, \"Found opcode %#x.\\n\", nextByte);\n emi.opcode.op = nextByte;\n\n \/\/Figure out the effective operand size. This can be overriden to\n \/\/a fixed value at the decoder level.\n int logOpSize;\n if(\/*FIXME long mode*\/1)\n {\n if(emi.rex.w)\n logOpSize = 3; \/\/ 64 bit operand size\n else if(emi.legacy.op)\n logOpSize = 1; \/\/ 16 bit operand size\n else\n logOpSize = 2; \/\/ 32 bit operand size\n }\n else if(\/*FIXME default 32*\/1)\n {\n if(emi.legacy.op)\n logOpSize = 1; \/\/ 16 bit operand size\n else\n logOpSize = 2; \/\/ 32 bit operand size\n }\n else \/\/ 16 bit default operand size\n {\n if(emi.legacy.op)\n logOpSize = 2; \/\/ 32 bit operand size\n else\n logOpSize = 1; \/\/ 16 bit operand size\n }\n\n \/\/Set the actual op size\n emi.opSize = 1 << logOpSize;\n\n \/\/Figure out the effective address size. This can be overriden to\n \/\/a fixed value at the decoder level.\n int logAddrSize;\n if(\/*FIXME 64-bit mode*\/1)\n {\n if(emi.legacy.addr)\n logAddrSize = 2; \/\/ 32 bit address size\n else\n logAddrSize = 3; \/\/ 64 bit address size\n }\n else if(\/*FIXME default 32*\/1)\n {\n if(emi.legacy.addr)\n logAddrSize = 1; \/\/ 16 bit address size\n else\n logAddrSize = 2; \/\/ 32 bit address size\n }\n else \/\/ 16 bit default operand size\n {\n if(emi.legacy.addr)\n logAddrSize = 2; \/\/ 32 bit address size\n else\n logAddrSize = 1; \/\/ 16 bit address size\n }\n\n \/\/Set the actual address size\n emi.addrSize = 1 << logAddrSize;\n\n \/\/Figure out how big of an immediate we'll retreive based\n \/\/on the opcode.\n int immType = ImmediateType[emi.opcode.num - 1][nextByte];\n immediateSize = SizeTypeToSize[logOpSize - 1][immType];\n\n \/\/Determine what to expect next\n if (UsesModRM[emi.opcode.num - 1][nextByte]) {\n nextState = ModRMState;\n } else {\n if(immediateSize) {\n nextState = ImmediateState;\n } else {\n emiIsReady = true;\n nextState = ResetState;\n }\n }\n }\n return nextState;\n }\n\n \/\/Get the ModRM byte and determine what displacement, if any, there is.\n \/\/Also determine whether or not to get the SIB byte, displacement, or\n \/\/immediate next.\n Predecoder::State Predecoder::doModRMState(uint8_t nextByte)\n {\n State nextState = ErrorState;\n ModRM modRM;\n modRM = nextByte;\n DPRINTF(Predecoder, \"Found modrm byte %#x.\\n\", nextByte);\n if (0) {\/\/FIXME in 16 bit mode\n \/\/figure out 16 bit displacement size\n if(modRM.mod == 0 && modRM.rm == 6 || modRM.mod == 2)\n displacementSize = 2;\n else if(modRM.mod == 1)\n displacementSize = 1;\n else\n displacementSize = 0;\n } else {\n \/\/figure out 32\/64 bit displacement size\n if(modRM.mod == 0 && modRM.rm == 5 || modRM.mod == 2)\n displacementSize = 4;\n else if(modRM.mod == 1)\n displacementSize = 1;\n else\n displacementSize = 0;\n }\n\n \/\/ The \"test\" instruction in group 3 needs an immediate, even though\n \/\/ the other instructions with the same actual opcode don't.\n if (emi.opcode.num == 1 && (modRM.reg & 0x6) == 0) {\n if (emi.opcode.op == 0xF6)\n immediateSize = 1;\n else if (emi.opcode.op == 0xF7)\n immediateSize = (emi.opSize == 8) ? 4 : emi.opSize;\n }\n\n \/\/If there's an SIB, get that next.\n \/\/There is no SIB in 16 bit mode.\n if (modRM.rm == 4 && modRM.mod != 3) {\n \/\/ && in 32\/64 bit mode)\n nextState = SIBState;\n } else if(displacementSize) {\n nextState = DisplacementState;\n } else if(immediateSize) {\n nextState = ImmediateState;\n } else {\n emiIsReady = true;\n nextState = ResetState;\n }\n \/\/The ModRM byte is consumed no matter what\n consumeByte();\n emi.modRM = modRM;\n return nextState;\n }\n\n \/\/Get the SIB byte. We don't do anything with it at this point, other\n \/\/than storing it in the ExtMachInst. Determine if we need to get a\n \/\/displacement or immediate next.\n Predecoder::State Predecoder::doSIBState(uint8_t nextByte)\n {\n State nextState = ErrorState;\n emi.sib = nextByte;\n DPRINTF(Predecoder, \"Found SIB byte %#x.\\n\", nextByte);\n consumeByte();\n if (emi.modRM.mod == 0 && emi.sib.base == 5)\n displacementSize = 4;\n if (displacementSize) {\n nextState = DisplacementState;\n } else if(immediateSize) {\n nextState = ImmediateState;\n } else {\n emiIsReady = true;\n nextState = ResetState;\n }\n return nextState;\n }\n\n \/\/Gather up the displacement, or at least as much of it\n \/\/as we can get.\n Predecoder::State Predecoder::doDisplacementState()\n {\n State nextState = ErrorState;\n\n getImmediate(immediateCollected,\n emi.displacement,\n displacementSize);\n\n DPRINTF(Predecoder, \"Collecting %d byte displacement, got %d bytes.\\n\",\n displacementSize, immediateCollected);\n\n if(displacementSize == immediateCollected) {\n \/\/Reset this for other immediates.\n immediateCollected = 0;\n \/\/Sign extend the displacement\n switch(displacementSize)\n {\n case 1:\n emi.displacement = sext<8>(emi.displacement);\n break;\n case 2:\n emi.displacement = sext<16>(emi.displacement);\n break;\n case 4:\n emi.displacement = sext<32>(emi.displacement);\n break;\n default:\n panic(\"Undefined displacement size!\\n\");\n }\n DPRINTF(Predecoder, \"Collected displacement %#x.\\n\",\n emi.displacement);\n if(immediateSize) {\n nextState = ImmediateState;\n } else {\n emiIsReady = true;\n nextState = ResetState;\n }\n }\n else\n nextState = DisplacementState;\n return nextState;\n }\n\n \/\/Gather up the immediate, or at least as much of it\n \/\/as we can get\n Predecoder::State Predecoder::doImmediateState()\n {\n State nextState = ErrorState;\n\n getImmediate(immediateCollected,\n emi.immediate,\n immediateSize);\n\n DPRINTF(Predecoder, \"Collecting %d byte immediate, got %d bytes.\\n\",\n immediateSize, immediateCollected);\n\n if(immediateSize == immediateCollected)\n {\n \/\/Reset this for other immediates.\n immediateCollected = 0;\n\n \/\/XXX Warning! The following is an observed pattern and might\n \/\/not always be true!\n\n \/\/Instructions which use 64 bit operands but 32 bit immediates\n \/\/need to have the immediate sign extended to 64 bits.\n \/\/Instructions which use true 64 bit immediates won't be\n \/\/affected, and instructions that use true 32 bit immediates\n \/\/won't notice.\n switch(immediateSize)\n {\n case 4:\n emi.immediate = sext<32>(emi.immediate);\n break;\n case 1:\n emi.immediate = sext<8>(emi.immediate);\n }\n\n DPRINTF(Predecoder, \"Collected immediate %#x.\\n\",\n emi.immediate);\n emiIsReady = true;\n nextState = ResetState;\n }\n else\n nextState = ImmediateState;\n return nextState;\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 2007 The Hewlett-Packard Development Company\n * All rights reserved.\n *\n * Redistribution and use of this software in source and binary forms,\n * with or without modification, are permitted provided that the\n * following conditions are met:\n *\n * The software must be used only for Non-Commercial Use which means any\n * use which is NOT directed to receiving any direct monetary\n * compensation for, or commercial advantage from such use. Illustrative\n * examples of non-commercial use are academic research, personal study,\n * teaching, education and corporate research & development.\n * Illustrative examples of commercial use are distributing products for\n * commercial advantage and providing services using the software for\n * commercial advantage.\n *\n * If you wish to use this software or functionality therein that may be\n * covered by patents for commercial use, please contact:\n * Director of Intellectual Property Licensing\n * Office of Strategy and Technology\n * Hewlett-Packard Company\n * 1501 Page Mill Road\n * Palo Alto, California 94304\n *\n * Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer. Redistributions\n * in binary form must reproduce the above copyright notice, this list of\n * conditions and the following disclaimer in the documentation and\/or\n * other materials provided with the distribution. Neither the name of\n * the COPYRIGHT HOLDER(s), HEWLETT-PACKARD COMPANY, nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission. No right of\n * sublicense is granted herewith. Derivatives of the software and\n * output created using the software may be prepared, but only for\n * Non-Commercial Uses. Derivatives of the software may be shared with\n * others provided: (i) the others agree to abide by the list of\n * conditions herein which includes the Non-Commercial Use restrictions;\n * and (ii) such Derivatives of the software include the above copyright\n * notice to acknowledge the contribution from this software where\n * applicable, this list of conditions and the disclaimer below.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n * Authors: Gabe Black\n *\/\n\n#ifndef __ARCH_X86_X86TRAITS_HH__\n#define __ARCH_X86_X86TRAITS_HH__\n\nnamespace X86ISA\n{\n \/\/XXX This will definitely need to be something larger in the future.\n const int NumMicroIntRegs = 0;\n\n const int NumMMXRegs = 8;\n const int NumXMMRegs = 16;\n}\n\n#endif \/\/__ARCH_X86_X86TRAITS_HH__\n<commit_msg>Add in some microregs.<commit_after>\/*\n * Copyright (c) 2007 The Hewlett-Packard Development Company\n * All rights reserved.\n *\n * Redistribution and use of this software in source and binary forms,\n * with or without modification, are permitted provided that the\n * following conditions are met:\n *\n * The software must be used only for Non-Commercial Use which means any\n * use which is NOT directed to receiving any direct monetary\n * compensation for, or commercial advantage from such use. Illustrative\n * examples of non-commercial use are academic research, personal study,\n * teaching, education and corporate research & development.\n * Illustrative examples of commercial use are distributing products for\n * commercial advantage and providing services using the software for\n * commercial advantage.\n *\n * If you wish to use this software or functionality therein that may be\n * covered by patents for commercial use, please contact:\n * Director of Intellectual Property Licensing\n * Office of Strategy and Technology\n * Hewlett-Packard Company\n * 1501 Page Mill Road\n * Palo Alto, California 94304\n *\n * Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer. Redistributions\n * in binary form must reproduce the above copyright notice, this list of\n * conditions and the following disclaimer in the documentation and\/or\n * other materials provided with the distribution. Neither the name of\n * the COPYRIGHT HOLDER(s), HEWLETT-PACKARD COMPANY, nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission. No right of\n * sublicense is granted herewith. Derivatives of the software and\n * output created using the software may be prepared, but only for\n * Non-Commercial Uses. Derivatives of the software may be shared with\n * others provided: (i) the others agree to abide by the list of\n * conditions herein which includes the Non-Commercial Use restrictions;\n * and (ii) such Derivatives of the software include the above copyright\n * notice to acknowledge the contribution from this software where\n * applicable, this list of conditions and the disclaimer below.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n * Authors: Gabe Black\n *\/\n\n#ifndef __ARCH_X86_X86TRAITS_HH__\n#define __ARCH_X86_X86TRAITS_HH__\n\nnamespace X86ISA\n{\n const int NumMicroIntRegs = 16;\n\n const int NumMMXRegs = 8;\n const int NumXMMRegs = 16;\n}\n\n#endif \/\/__ARCH_X86_X86TRAITS_HH__\n<|endoftext|>"} {"text":"<commit_before>\/\/ [AsmJit]\n\/\/ Complete x86\/x64 JIT and Remote Assembler for C++.\n\/\/\n\/\/ [License]\n\/\/ Zlib - See LICENSE.md file in the package.\n\n\/\/ [Export]\n#define ASMJIT_EXPORTS\n\n\/\/ [Dependencies - AsmJit]\n#include \"..\/base\/intutil.h\"\n#include \"..\/base\/logger.h\"\n#include \"..\/base\/string.h\"\n\n\/\/ [Dependencies - C]\n#include <stdarg.h>\n\n\/\/ [Api-Begin]\n#include \"..\/apibegin.h\"\n\nnamespace asmjit {\n\n\/\/ ============================================================================\n\/\/ [asmjit::BaseLogger - Construction \/ Destruction]\n\/\/ ============================================================================\n\nBaseLogger::BaseLogger() {\n _options = 0;\n ::memset(_indentation, 0, ASMJIT_ARRAY_SIZE(_indentation));\n}\n\nBaseLogger::~BaseLogger() {}\n\n\/\/ ============================================================================\n\/\/ [asmjit::BaseLogger - Logging]\n\/\/ ============================================================================\n\nvoid BaseLogger::logFormat(uint32_t style, const char* fmt, ...) {\n char buf[1024];\n size_t len;\n\n va_list ap;\n va_start(ap, fmt);\n len = vsnprintf(buf, 1023, fmt, ap);\n va_end(ap);\n\n logString(style, buf, len);\n}\n\nvoid BaseLogger::logBinary(uint32_t style, const void* data, size_t size) {\n static const char prefix[] = \".data \";\n static const char hex[16] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };\n\n const uint8_t* s = static_cast<const uint8_t*>(data);\n size_t i = size;\n\n char buffer[128];\n ::memcpy(buffer, prefix, ASMJIT_ARRAY_SIZE(prefix) - 1);\n\n while (i) {\n uint32_t n = static_cast<uint32_t>(IntUtil::iMax<size_t>(i, 16));\n char* p = buffer + ASMJIT_ARRAY_SIZE(prefix) - 1;\n\n i -= n;\n do {\n uint32_t c = s[0];\n\n p[0] = hex[c >> 4];\n p[1] = hex[c & 15];\n\n p += 2;\n s += 1;\n } while (--n);\n\n *p++ = '\\n';\n logString(style, buffer, (size_t)(p - buffer));\n }\n}\n\n\/\/ ============================================================================\n\/\/ [asmjit::BaseLogger - LogBinary]\n\/\/ ============================================================================\n\nvoid BaseLogger::setOption(uint32_t id, bool value) {\n if (id >= kLoggerOptionCount)\n return;\n\n uint32_t mask = 1 << id;\n\n if (value)\n _options |= mask;\n else\n _options &= ~mask;\n}\n\n\/\/ ============================================================================\n\/\/ [asmjit::BaseLogger - Indentation]\n\/\/ ============================================================================\n\nvoid BaseLogger::setIndentation(const char* indentation) {\n ::memset(_indentation, 0, ASMJIT_ARRAY_SIZE(_indentation));\n if (!indentation)\n return;\n\n size_t length = StringUtil::nlen(indentation, ASMJIT_ARRAY_SIZE(_indentation) - 1);\n ::memcpy(_indentation, indentation, length);\n}\n\n\/\/ ============================================================================\n\/\/ [asmjit::FileLogger - Construction \/ Destruction]\n\/\/ ============================================================================\n\nFileLogger::FileLogger(FILE* stream) : _stream(NULL) {\n setStream(stream);\n}\n\nFileLogger::~FileLogger() {}\n\n\/\/ ============================================================================\n\/\/ [asmjit::FileLogger - Accessors]\n\/\/ ============================================================================\n\n\/\/! @brief Set file stream.\nvoid FileLogger::setStream(FILE* stream) {\n _stream = stream;\n}\n\n\/\/ ============================================================================\n\/\/ [asmjit::FileLogger - Logging]\n\/\/ ============================================================================\n\nvoid FileLogger::logString(uint32_t style, const char* buf, size_t len) {\n if (!_stream)\n return;\n\n if (len == kInvalidIndex)\n len = strlen(buf);\n\n fwrite(buf, 1, len, _stream);\n}\n\n\/\/ ============================================================================\n\/\/ [asmjit::StringLogger - Construction \/ Destruction]\n\/\/ ============================================================================\n\nStringLogger::StringLogger() {}\nStringLogger::~StringLogger() {}\n\n\/\/ ============================================================================\n\/\/ [asmjit::StringLogger - Logging]\n\/\/ ============================================================================\n\nvoid StringLogger::logString(uint32_t style, const char* buf, size_t len) {\n _stringBuilder.appendString(buf, len);\n}\n\n} \/\/ asmjit namespace\n\n\/\/ [Api-End]\n#include \"..\/apiend.h\"\n<commit_msg>Fixed logger bug when showing embed data.<commit_after>\/\/ [AsmJit]\n\/\/ Complete x86\/x64 JIT and Remote Assembler for C++.\n\/\/\n\/\/ [License]\n\/\/ Zlib - See LICENSE.md file in the package.\n\n\/\/ [Export]\n#define ASMJIT_EXPORTS\n\n\/\/ [Dependencies - AsmJit]\n#include \"..\/base\/intutil.h\"\n#include \"..\/base\/logger.h\"\n#include \"..\/base\/string.h\"\n\n\/\/ [Dependencies - C]\n#include <stdarg.h>\n\n\/\/ [Api-Begin]\n#include \"..\/apibegin.h\"\n\nnamespace asmjit {\n\n\/\/ ============================================================================\n\/\/ [asmjit::BaseLogger - Construction \/ Destruction]\n\/\/ ============================================================================\n\nBaseLogger::BaseLogger() {\n _options = 0;\n ::memset(_indentation, 0, ASMJIT_ARRAY_SIZE(_indentation));\n}\n\nBaseLogger::~BaseLogger() {}\n\n\/\/ ============================================================================\n\/\/ [asmjit::BaseLogger - Logging]\n\/\/ ============================================================================\n\nvoid BaseLogger::logFormat(uint32_t style, const char* fmt, ...) {\n char buf[1024];\n size_t len;\n\n va_list ap;\n va_start(ap, fmt);\n len = vsnprintf(buf, 1023, fmt, ap);\n va_end(ap);\n\n logString(style, buf, len);\n}\n\nvoid BaseLogger::logBinary(uint32_t style, const void* data, size_t size) {\n static const char prefix[] = \".data \";\n static const char hex[16] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };\n\n const uint8_t* s = static_cast<const uint8_t*>(data);\n size_t i = size;\n\n char buffer[128];\n ::memcpy(buffer, prefix, ASMJIT_ARRAY_SIZE(prefix) - 1);\n\n while (i) {\n uint32_t n = static_cast<uint32_t>(IntUtil::iMin<size_t>(i, 16));\n char* p = buffer + ASMJIT_ARRAY_SIZE(prefix) - 1;\n\n i -= n;\n do {\n uint32_t c = s[0];\n\n p[0] = hex[c >> 4];\n p[1] = hex[c & 15];\n\n p += 2;\n s += 1;\n } while (--n);\n\n *p++ = '\\n';\n logString(style, buffer, (size_t)(p - buffer));\n }\n}\n\n\/\/ ============================================================================\n\/\/ [asmjit::BaseLogger - LogBinary]\n\/\/ ============================================================================\n\nvoid BaseLogger::setOption(uint32_t id, bool value) {\n if (id >= kLoggerOptionCount)\n return;\n\n uint32_t mask = 1 << id;\n\n if (value)\n _options |= mask;\n else\n _options &= ~mask;\n}\n\n\/\/ ============================================================================\n\/\/ [asmjit::BaseLogger - Indentation]\n\/\/ ============================================================================\n\nvoid BaseLogger::setIndentation(const char* indentation) {\n ::memset(_indentation, 0, ASMJIT_ARRAY_SIZE(_indentation));\n if (!indentation)\n return;\n\n size_t length = StringUtil::nlen(indentation, ASMJIT_ARRAY_SIZE(_indentation) - 1);\n ::memcpy(_indentation, indentation, length);\n}\n\n\/\/ ============================================================================\n\/\/ [asmjit::FileLogger - Construction \/ Destruction]\n\/\/ ============================================================================\n\nFileLogger::FileLogger(FILE* stream) : _stream(NULL) {\n setStream(stream);\n}\n\nFileLogger::~FileLogger() {}\n\n\/\/ ============================================================================\n\/\/ [asmjit::FileLogger - Accessors]\n\/\/ ============================================================================\n\n\/\/! @brief Set file stream.\nvoid FileLogger::setStream(FILE* stream) {\n _stream = stream;\n}\n\n\/\/ ============================================================================\n\/\/ [asmjit::FileLogger - Logging]\n\/\/ ============================================================================\n\nvoid FileLogger::logString(uint32_t style, const char* buf, size_t len) {\n if (!_stream)\n return;\n\n if (len == kInvalidIndex)\n len = strlen(buf);\n\n fwrite(buf, 1, len, _stream);\n}\n\n\/\/ ============================================================================\n\/\/ [asmjit::StringLogger - Construction \/ Destruction]\n\/\/ ============================================================================\n\nStringLogger::StringLogger() {}\nStringLogger::~StringLogger() {}\n\n\/\/ ============================================================================\n\/\/ [asmjit::StringLogger - Logging]\n\/\/ ============================================================================\n\nvoid StringLogger::logString(uint32_t style, const char* buf, size_t len) {\n _stringBuilder.appendString(buf, len);\n}\n\n} \/\/ asmjit namespace\n\n\/\/ [Api-End]\n#include \"..\/apiend.h\"\n<|endoftext|>"} {"text":"<commit_before>#ifndef RADIUMENGINE_INTERPOLATION_HPP\n#define RADIUMENGINE_INTERPOLATION_HPP\n\n#include <Core\/Math\/LinearAlgebra.hpp>\n#include <Engine\/Assets\/FileData.hpp>\n\nnamespace Ra {\nnamespace Core {\n\ninline void interpolate( const Core::Vector3& v0, const Core::Vector3& v1, const Scalar t, Core::Vector3& result ) {\n result = ( ( t * v0 ) + ( ( 1.0 - t ) * v1 ) );\n}\n\ninline void interpolate( const Core::Quaternion& q0, const Core::Quaternion& q1, const Scalar t, Core::Quaternion& result ) {\n result = q0.slerp( t, q1 );\n}\n\ninline void interpolate( const Core::Transform& T0, const Core::Transform& T1, const Scalar t, Core::Transform& result ) {\n Core::Quaternion q0 = Core::Quaternion( T0.rotation() );\n Core::Quaternion q1 = Core::Quaternion( T1.rotation() );\n Core::Quaternion q = q0.slerp( t, q1 );\n Core::Vector3 tr = ( ( t * T0.translation() ) + ( ( 1.0 - t ) * T1.translation() ) );\n result.linear() = q.toRotationMatrix();\n result.translation() = tr;\n}\n\n} \/\/ namespace Core\n} \/\/ namespace Ra\n\n#endif \/\/ RADIUMENGINE_INTERPOLATION_HPP\n<commit_msg>Interpolation functions maintenability improved<commit_after>#ifndef RADIUMENGINE_INTERPOLATION_HPP\n#define RADIUMENGINE_INTERPOLATION_HPP\n\n#include <Core\/Math\/LinearAlgebra.hpp>\n\/\/#include <Engine\/Assets\/FileData.hpp>\n\nnamespace Ra {\nnamespace Core {\n\ninline void interpolate( const Core::Vector3& v0, const Core::Vector3& v1, const Scalar t, Core::Vector3& result ) {\n result = ( ( ( 1.0 - t ) * v0 ) + ( t * v1 ) );\n}\n\ninline void interpolate( const Core::Quaternion& q0, const Core::Quaternion& q1, const Scalar t, Core::Quaternion& result ) {\n result = q0.slerp( t, q1 );\n}\n\ninline void interpolate( const Core::Transform& T0, const Core::Transform& T1, const Scalar t, Core::Transform& result ) {\n Core::Quaternion q;\n Core::Vector3 tr;\n interpolate( Core::Quaternion( T0.rotation() ),\n Core::Quaternion( T1.rotation() ),\n t,\n q );\n interpolate( T0.translation(),\n T1.translation(),\n t,\n tr );\n result.linear() = q.toRotationMatrix();\n result.translation() = tr;\n}\n\n} \/\/ namespace Core\n} \/\/ namespace Ra\n\n#endif \/\/ RADIUMENGINE_INTERPOLATION_HPP\n<|endoftext|>"} {"text":"<commit_before>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Copyright (c) 2016, Image Engine Design Inc. All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are\n\/\/ met:\n\/\/\n\/\/ * Redistributions of source code must retain the above\n\/\/ copyright notice, this list of conditions and the following\n\/\/ disclaimer.\n\/\/\n\/\/ * Redistributions in binary form must reproduce the above\n\/\/ copyright notice, this list of conditions and the following\n\/\/ disclaimer in the documentation and\/or other materials provided with\n\/\/ the distribution.\n\/\/\n\/\/ * Neither the name of John Haddon nor the names of\n\/\/ any other contributors to this software may be used to endorse or\n\/\/ promote products derived from this software without specific prior\n\/\/ written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS\n\/\/ IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,\n\/\/ THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n\/\/ PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR\n\/\/ CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n\/\/ EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n\/\/ PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n\/\/ PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n\/\/ LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n\/\/ NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n\/\/ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"Gaffer\/StringPlug.h\"\n\n#include \"GafferScene\/Private\/IECoreScenePreview\/Renderer.h\"\n\n#include \"GafferArnold\/InteractiveArnoldRender.h\"\n\nusing namespace GafferScene;\nusing namespace GafferArnold;\n\nIE_CORE_DEFINERUNTIMETYPED( InteractiveArnoldRender );\n\nInteractiveArnoldRender::InteractiveArnoldRender( const std::string &name )\n\t:\tInteractiveRender( \"IECoreArnold::Renderer\", name )\n{\n}\n\nInteractiveArnoldRender::~InteractiveArnoldRender()\n{\n}\n<commit_msg>InteractiveArnoldRender : Remove unnecessary includes.<commit_after>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Copyright (c) 2016, Image Engine Design Inc. All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are\n\/\/ met:\n\/\/\n\/\/ * Redistributions of source code must retain the above\n\/\/ copyright notice, this list of conditions and the following\n\/\/ disclaimer.\n\/\/\n\/\/ * Redistributions in binary form must reproduce the above\n\/\/ copyright notice, this list of conditions and the following\n\/\/ disclaimer in the documentation and\/or other materials provided with\n\/\/ the distribution.\n\/\/\n\/\/ * Neither the name of John Haddon nor the names of\n\/\/ any other contributors to this software may be used to endorse or\n\/\/ promote products derived from this software without specific prior\n\/\/ written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS\n\/\/ IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,\n\/\/ THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n\/\/ PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR\n\/\/ CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n\/\/ EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n\/\/ PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n\/\/ PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n\/\/ LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n\/\/ NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n\/\/ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"GafferArnold\/InteractiveArnoldRender.h\"\n\nusing namespace GafferScene;\nusing namespace GafferArnold;\n\nIE_CORE_DEFINERUNTIMETYPED( InteractiveArnoldRender );\n\nInteractiveArnoldRender::InteractiveArnoldRender( const std::string &name )\n\t:\tInteractiveRender( \"IECoreArnold::Renderer\", name )\n{\n}\n\nInteractiveArnoldRender::~InteractiveArnoldRender()\n{\n}\n<|endoftext|>"} {"text":"<commit_before>#include <Arduino.h>\n#include <stdint.h>\n\n#include \"receiver_driver.h\"\n\n\n#define SPI_ADDRESS_SYNTH_A 0x01\n\n\nvoid ReceiverDriver::init(\n uint8_t spiClockPin,\n uint8_t spiDataPin,\n uint8_t spiSelectPin\n) {\n this->spiClockPin = spiClockPin;\n this->spiDataPin = spiDataPin;\n this->spiSelectPin = spiSelectPin;\n}\n\nvoid ReceiverDriver::setSynthRegisterB(uint32_t data) {\n this->sendRegister(SPI_ADDRESS_SYNTH_A, data);\n}\n\n\nvoid ReceiverDriver::sendRegister(uint8_t address, uint32_t data) {\n this->sendSlaveSelect(LOW);\n\n this->sendBits(address, 4);\n this->sendBit(HIGH); \/\/ Enable write.\n\n this->sendBits(data, 20);\n\n \/\/ Finished clocking data in\n this->sendSlaveSelect(HIGH);\n digitalWrite(this->spiSelectPin, LOW);\n digitalWrite(this->spiClockPin, LOW);\n digitalWrite(this->spiDataPin, LOW);\n}\n\nvoid ReceiverDriver::sendBits(uint32_t bits, uint8_t count) {\n for (uint8_t i = 0; i < count; i++) {\n this->sendBit(bits & 0x1);\n bits >>= 1;\n }\n}\n\nvoid ReceiverDriver::sendBit(uint8_t value) {\n digitalWrite(this->spiClockPin, LOW);\n delayMicroseconds(1);\n\n digitalWrite(this->spiDataPin, value);\n delayMicroseconds(1);\n digitalWrite(this->spiClockPin, HIGH);\n delayMicroseconds(1);\n\n digitalWrite(this->spiClockPin, LOW);\n delayMicroseconds(1);\n}\n\nvoid ReceiverDriver::sendSlaveSelect(uint8_t value) {\n digitalWrite(this->spiSelectPin, value);\n delayMicroseconds(1);\n}\n<commit_msg>Attempt at fixing multiple device select<commit_after>#include <Arduino.h>\n#include <stdint.h>\n\n#include \"receiver_driver.h\"\n\n\n#define SPI_ADDRESS_SYNTH_B 0x01\n\n\nvoid ReceiverDriver::init(\n uint8_t spiClockPin,\n uint8_t spiDataPin,\n uint8_t spiSelectPin\n) {\n this->spiClockPin = spiClockPin;\n this->spiDataPin = spiDataPin;\n this->spiSelectPin = spiSelectPin;\n}\n\nvoid ReceiverDriver::setSynthRegisterB(uint32_t data) {\n this->sendRegister(SPI_ADDRESS_SYNTH_B, data);\n}\n\n\nvoid ReceiverDriver::sendRegister(uint8_t address, uint32_t data) {\n this->sendSlaveSelect(LOW);\n\n this->sendBits(address, 4);\n this->sendBit(HIGH); \/\/ Enable write.\n\n this->sendBits(data, 20);\n\n \/\/ Finished clocking data in\n this->sendSlaveSelect(HIGH);\n digitalWrite(this->spiClockPin, LOW);\n digitalWrite(this->spiDataPin, LOW);\n delayMicroseconds(1);\n}\n\nvoid ReceiverDriver::sendBits(uint32_t bits, uint8_t count) {\n for (uint8_t i = 0; i < count; i++) {\n this->sendBit(bits & 0x1);\n bits >>= 1;\n }\n}\n\nvoid ReceiverDriver::sendBit(uint8_t value) {\n digitalWrite(this->spiClockPin, LOW);\n delayMicroseconds(1);\n\n digitalWrite(this->spiDataPin, value);\n delayMicroseconds(1);\n digitalWrite(this->spiClockPin, HIGH);\n delayMicroseconds(1);\n\n digitalWrite(this->spiClockPin, LOW);\n delayMicroseconds(1);\n}\n\nvoid ReceiverDriver::sendSlaveSelect(uint8_t value) {\n digitalWrite(this->spiSelectPin, value);\n delayMicroseconds(1);\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ -*- Mode: C++; tab-width: 2; -*-\n\/\/ vi: set ts=2:\n\/\/\n\/\/ $Id: rtti.C,v 1.14 2003\/08\/26 09:17:44 oliver Exp $\n\/\/\n\n#include <BALL\/COMMON\/global.h>\n#include <BALL\/COMMON\/rtti.h>\n\n#include <typeinfo>\n#include <ctype.h>\n\n\n\/\/ Nasty hacks to demangle the stupid name mangling schemes \n\/\/ of diverse compilers.\n\n\/\/ GNU g++:\n\/\/ Starting V3.0 we use __cxa_demangle to demangle the names,\n\/\/ which is declared in <cxxabi.h>.\n#ifdef BALL_COMPILER_GXX\n#\tif (BALL_COMPILER_VERSION_MAJOR > 2)\n\t\t#include <cxxabi.h>\n#\tendif\n#endif\n\n#ifdef BALL_COMPILER_INTEL\n\t\/\/ Declare the __cxa_demangle method for Intel's C++ compiler.\n\t\/\/ Intel does not provide the cxxabi.h header G++ provides, so \n\t\/\/ this hack is somewhat rough.\n\tnamespace abi\n\t{\n\t\textern \"C\" char* __cxa_demangle(const char*, char*, unsigned int*, int*);\n\t}\n#endif\n\nnamespace BALL \n{\n\n\tstring streamClassName(const std::type_info& t)\n\t{\n#if (defined(BALL_COMPILER_GXX) || defined(BALL_COMPILER_INTEL))\n #if (BALL_COMPILER_VERSION_MAJOR < 3)\n\t\t\tstring s(t.name());\n s = GNUDemangling::demangle(s);\n #else\n\t\t\tchar buf[BALL_MAX_LINE_LENGTH];\n\t\t\tstd::size_t length = BALL_MAX_LINE_LENGTH - 1;\n\t\t\tint status = 0;\n string s(\"_Z\");\n s += t.name();\n char* name = abi::__cxa_demangle(s.c_str(), buf, &length, &status);\n if (name != 0)\n {\n s = name;\n\t\t\t}\n #endif \n#else\n\t\tstring s(t.name());\n\t\t#ifdef BALL_COMPILER_MSVC\n\t\t\t\/\/ MSVC prefixes all class names with \"class \" -- delete it!\n\t\t\twhile (s.find(\"class \") != string::npos) \n\t\t\t\ts.erase(s.find(\"class \"), 6);\n\t\t#endif\n\t\t\n\t\t\n#endif\n\n\n\t\tfor (unsigned int i = 0; i < s.size(); i++)\n\t\t{\n\t\t\tif (s[i] == ' ')\n\t\t\t{\n\t\t\t\ts[i] = '_';\n\t\t\t}\n\t\t}\n\n\t\tif (string(s, 0, 6) == \"const_\")\n\t\t{\n\t\t\ts.erase(0, 6);\n\t\t}\n\n\t\treturn s;\n\t}\n \n#ifdef BALL_COMPILER_GXX\n#\tif (BALL_COMPILER_VERSION_MAJOR < 3)\n\n\tnamespace GNUDemangling \n\t{\n\n\t\tstring decode_mangling(string& s)\n\t\t{\n\t\t\tstring tmp;\n\t\t\tint i,len;\n\n\t\t\tif (s.size() == 0)\n\t\t\t\treturn \"\";\n\n\t\t\tif (!isdigit(s[0]))\n\t\t\t{ \/\/ decode GNU shortcuts for built-in types\n\t\t\t\tchar c = s[0];\n\t\t\t\ts.erase(0, 1);\n\t\t\t\tswitch (c)\n\t\t\t\t{\n\t\t\t\t\tcase 'Q': \/\/ start of class name\n\t\t\t\t\t\tlen = atoi(string(s,1,1).c_str());\n\t\t\t\t\t\ts.erase(0, 1);\n\t\t\t\t\t\tfor (i = 0; i < len; i++)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\ttmp.append(decode_mangling(s));\n\t\t\t\t\t\t\ttmp.append(\"::\");\n\t\t\t\t\t\t}\n\t\t\t\t\t\ttmp.erase(tmp.end() - 2, tmp.end());\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 'Z': \/\/ template parameter\n\t\t\t\t\t\treturn decode_mangling(s);\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase 'i':\n\t\t\t\t\t\treturn \"int\";\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase 'l':\n\t\t\t\t\t\treturn \"long\";\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase 's':\n\t\t\t\t\t\treturn \"short\";\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase 'c':\n\t\t\t\t\t\treturn \"char\";\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase 'x':\n\t\t\t\t\t\treturn \"long long\";\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase 'f':\n\t\t\t\t\t\treturn \"float\";\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase 'd':\n\t\t\t\t\t\treturn \"double\";\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase 'b':\n\t\t\t\t\t\treturn \"bool\";\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase 'w':\n\t\t\t\t\t\treturn \"wchar_t\";\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase 'U': \/\/ unsigned variants\n\t\t\t\t\t\ttmp = \"unsigned \";\n\t\t\t\t\t\ttmp.append(decode_mangling(s));\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase 'C': \/\/ const\n\t\t\t\t\t\ttmp = \"const \";\n\t\t\t\t\t\ttmp.append(decode_mangling(s));\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase 'P': \/\/ pointer\n\t\t\t\t\t\ttmp = decode_mangling(s);\n\t\t\t\t\t\ttmp.append(\"*\");\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase 'R': \/\/ reference\n\t\t\t\t\t\ttmp = decode_mangling(s);\n\t\t\t\t\t\ttmp.append(\"&\");\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase 't':\n\t\t\t\t\t\ttmp = decode_mangling(s);\n\t\t\t\t\t\ttmp.append(\"<\");\n\t\t\t\t\t\n\t\t\t\t\t\tlen = atoi(string(1, s[0]).c_str());\n\t\t\t\t\t\ts.erase(0,1);\n\t\t\t\t\t\tfor (i = 0; i < len; i++)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\ttmp.append(decode_mangling(s));\n\t\t\t\t\t\t\ttmp.append(\",\");\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\/\/ remove last ','\n\t\t\t\t\t\ttmp.erase(tmp.end() - 1, tmp.end());\n\t\t\t\t\t\ttmp.append(\">\");\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tdefault:\n\t\t\t\t\t\ttmp = \"?\";\n\t\t\t\t}\n\t\t\t\treturn tmp;\n\t\t\t} \n\t\t\telse \n\t\t\t{\n\t\t\t\ti = s.find_first_not_of(\"0123456789\");\n\t\t\t\tlen = atol(string(s, 0, i).c_str());\n\t\t\t\tif (len == 0)\n\t\t\t\t{\n\t\t\t\t\ts.erase(0,1);\n\t\t\t\t\t\t\n\t\t\t\t\tif (s.size() > 0)\n\t\t\t\t\t{\n\t\t\t\t\t\treturn decode_mangling(s);\n\t\t\t\t\t}\n\t\t\t\t\telse \n\t\t\t\t\t{\n\t\t\t\t\t\treturn \"\";\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse \n\t\t\t\t{\n\t\t\t\t\tstring h(s, i, len);\n\t\t\t\t\ts.erase(0, i + len);\n\t\t\t\t\n\t\t\t\t\treturn h;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tstring demangle(string s)\n\t\t{\n\t\t\tstring tmp = decode_mangling(s);\n\n\t\t\twhile (tmp[tmp.size() - 1] == ':')\n\t\t\t{\n\t\t\t\ttmp.erase(tmp.end() - 1, tmp.end());\n\t\t\t}\n\n\t\t\twhile (tmp[0] == ':')\n\t\t\t{\n\t\t\t\ttmp.erase(0, 1);\n\t\t\t}\n\n\t\t\treturn tmp;\n\t\t}\n\n\t} \/\/ namespace GNUDemangling \n\n#\tendif \/\/ (BALL_COMPILER_VERSION_MAJOR < 3)\n#endif \/\/ BALL_COMPILER_GXX\n\n} \/\/ namespace BALL\n\n<commit_msg>Fixed a bug in RTTI on 64 bit machines.<commit_after>\/\/ -*- Mode: C++; tab-width: 2; -*-\n\/\/ vi: set ts=2:\n\/\/\n\/\/ $Id: rtti.C,v 1.14 2003\/08\/26 09:17:44 oliver Exp $\n\/\/\n\n#include <BALL\/COMMON\/global.h>\n#include <BALL\/COMMON\/rtti.h>\n\n#include <typeinfo>\n#include <ctype.h>\n\n\n\/\/ Nasty hacks to demangle the stupid name mangling schemes \n\/\/ of diverse compilers.\n\n\/\/ GNU g++:\n\/\/ Starting V3.0 we use __cxa_demangle to demangle the names,\n\/\/ which is declared in <cxxabi.h>.\n#ifdef BALL_COMPILER_GXX\n#\tif (BALL_COMPILER_VERSION_MAJOR > 2)\n\t\t#include <cxxabi.h>\n#\tendif\n#endif\n\n#ifdef BALL_COMPILER_INTEL\n\t\/\/ Declare the __cxa_demangle method for Intel's C++ compiler.\n\t\/\/ Intel does not provide the cxxabi.h header G++ provides, so \n\t\/\/ this hack is somewhat rough.\n\tnamespace abi\n\t{\n\t\textern \"C\" char* __cxa_demangle(const char*, char*, unsigned int*, int*);\n\t}\n#endif\n\nnamespace BALL \n{\n\n\tstring streamClassName(const std::type_info& t)\n\t{\n#if (defined(BALL_COMPILER_GXX) || defined(BALL_COMPILER_INTEL))\n #if (BALL_COMPILER_VERSION_MAJOR < 3)\n\t\t\tstring s(t.name());\n s = GNUDemangling::demangle(s);\n #else\n\t\t\tchar buf[BALL_MAX_LINE_LENGTH];\n\t\t\tunsigned int length = BALL_MAX_LINE_LENGTH - 1;\n\t\t\tint status = 0;\n string s(\"_Z\");\n s += t.name();\n char* name = abi::__cxa_demangle(s.c_str(), buf, &length, &status);\n if (name != 0)\n {\n s = name;\n\t\t\t}\n #endif \n#else\n\t\tstring s(t.name());\n\t\t#ifdef BALL_COMPILER_MSVC\n\t\t\t\/\/ MSVC prefixes all class names with \"class \" -- delete it!\n\t\t\twhile (s.find(\"class \") != string::npos) \n\t\t\t\ts.erase(s.find(\"class \"), 6);\n\t\t#endif\n\t\t\n\t\t\n#endif\n\n\n\t\tfor (unsigned int i = 0; i < s.size(); i++)\n\t\t{\n\t\t\tif (s[i] == ' ')\n\t\t\t{\n\t\t\t\ts[i] = '_';\n\t\t\t}\n\t\t}\n\n\t\tif (string(s, 0, 6) == \"const_\")\n\t\t{\n\t\t\ts.erase(0, 6);\n\t\t}\n\n\t\treturn s;\n\t}\n \n#ifdef BALL_COMPILER_GXX\n#\tif (BALL_COMPILER_VERSION_MAJOR < 3)\n\n\tnamespace GNUDemangling \n\t{\n\n\t\tstring decode_mangling(string& s)\n\t\t{\n\t\t\tstring tmp;\n\t\t\tint i,len;\n\n\t\t\tif (s.size() == 0)\n\t\t\t\treturn \"\";\n\n\t\t\tif (!isdigit(s[0]))\n\t\t\t{ \/\/ decode GNU shortcuts for built-in types\n\t\t\t\tchar c = s[0];\n\t\t\t\ts.erase(0, 1);\n\t\t\t\tswitch (c)\n\t\t\t\t{\n\t\t\t\t\tcase 'Q': \/\/ start of class name\n\t\t\t\t\t\tlen = atoi(string(s,1,1).c_str());\n\t\t\t\t\t\ts.erase(0, 1);\n\t\t\t\t\t\tfor (i = 0; i < len; i++)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\ttmp.append(decode_mangling(s));\n\t\t\t\t\t\t\ttmp.append(\"::\");\n\t\t\t\t\t\t}\n\t\t\t\t\t\ttmp.erase(tmp.end() - 2, tmp.end());\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 'Z': \/\/ template parameter\n\t\t\t\t\t\treturn decode_mangling(s);\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase 'i':\n\t\t\t\t\t\treturn \"int\";\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase 'l':\n\t\t\t\t\t\treturn \"long\";\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase 's':\n\t\t\t\t\t\treturn \"short\";\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase 'c':\n\t\t\t\t\t\treturn \"char\";\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase 'x':\n\t\t\t\t\t\treturn \"long long\";\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase 'f':\n\t\t\t\t\t\treturn \"float\";\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase 'd':\n\t\t\t\t\t\treturn \"double\";\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase 'b':\n\t\t\t\t\t\treturn \"bool\";\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase 'w':\n\t\t\t\t\t\treturn \"wchar_t\";\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase 'U': \/\/ unsigned variants\n\t\t\t\t\t\ttmp = \"unsigned \";\n\t\t\t\t\t\ttmp.append(decode_mangling(s));\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase 'C': \/\/ const\n\t\t\t\t\t\ttmp = \"const \";\n\t\t\t\t\t\ttmp.append(decode_mangling(s));\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase 'P': \/\/ pointer\n\t\t\t\t\t\ttmp = decode_mangling(s);\n\t\t\t\t\t\ttmp.append(\"*\");\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase 'R': \/\/ reference\n\t\t\t\t\t\ttmp = decode_mangling(s);\n\t\t\t\t\t\ttmp.append(\"&\");\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase 't':\n\t\t\t\t\t\ttmp = decode_mangling(s);\n\t\t\t\t\t\ttmp.append(\"<\");\n\t\t\t\t\t\n\t\t\t\t\t\tlen = atoi(string(1, s[0]).c_str());\n\t\t\t\t\t\ts.erase(0,1);\n\t\t\t\t\t\tfor (i = 0; i < len; i++)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\ttmp.append(decode_mangling(s));\n\t\t\t\t\t\t\ttmp.append(\",\");\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\/\/ remove last ','\n\t\t\t\t\t\ttmp.erase(tmp.end() - 1, tmp.end());\n\t\t\t\t\t\ttmp.append(\">\");\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tdefault:\n\t\t\t\t\t\ttmp = \"?\";\n\t\t\t\t}\n\t\t\t\treturn tmp;\n\t\t\t} \n\t\t\telse \n\t\t\t{\n\t\t\t\ti = s.find_first_not_of(\"0123456789\");\n\t\t\t\tlen = atol(string(s, 0, i).c_str());\n\t\t\t\tif (len == 0)\n\t\t\t\t{\n\t\t\t\t\ts.erase(0,1);\n\t\t\t\t\t\t\n\t\t\t\t\tif (s.size() > 0)\n\t\t\t\t\t{\n\t\t\t\t\t\treturn decode_mangling(s);\n\t\t\t\t\t}\n\t\t\t\t\telse \n\t\t\t\t\t{\n\t\t\t\t\t\treturn \"\";\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse \n\t\t\t\t{\n\t\t\t\t\tstring h(s, i, len);\n\t\t\t\t\ts.erase(0, i + len);\n\t\t\t\t\n\t\t\t\t\treturn h;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tstring demangle(string s)\n\t\t{\n\t\t\tstring tmp = decode_mangling(s);\n\n\t\t\twhile (tmp[tmp.size() - 1] == ':')\n\t\t\t{\n\t\t\t\ttmp.erase(tmp.end() - 1, tmp.end());\n\t\t\t}\n\n\t\t\twhile (tmp[0] == ':')\n\t\t\t{\n\t\t\t\ttmp.erase(0, 1);\n\t\t\t}\n\n\t\t\treturn tmp;\n\t\t}\n\n\t} \/\/ namespace GNUDemangling \n\n#\tendif \/\/ (BALL_COMPILER_VERSION_MAJOR < 3)\n#endif \/\/ BALL_COMPILER_GXX\n\n} \/\/ namespace BALL\n\n<|endoftext|>"} {"text":"<commit_before><commit_msg>coverity#738907 Uninitialized scalar field<commit_after><|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: frmpage.hxx,v $\n *\n * $Revision: 1.20 $\n *\n * last change: $Author: vg $ $Date: 2007-10-22 15:18:58 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef _FRMPAGE_HXX\n#define _FRMPAGE_HXX\n\n#ifndef _FIXED_HXX \/\/autogen\n#include <vcl\/fixed.hxx>\n#endif\n#ifndef _BUTTON_HXX \/\/autogen\n#include <vcl\/button.hxx>\n#endif\n#ifndef _LSTBOX_HXX \/\/autogen\n#include <vcl\/lstbox.hxx>\n#endif\n#ifndef _FIELD_HXX \/\/autogen\n#include <vcl\/field.hxx>\n#endif\n#ifndef _SFXTABDLG_HXX \/\/autogen\n#include <sfx2\/tabdlg.hxx>\n#endif\n#ifndef _SVXSWFRAMEPOSSTRINGS_HXX\n#include <svx\/swframeposstrings.hxx>\n#endif\n\n#ifndef _SWTYPES_HXX\n#include <swtypes.hxx>\n#endif\n#ifndef _BMPWIN_HXX\n#include <bmpwin.hxx>\n#endif\n#ifndef _SVXSWFRAMEEXAMPLE_HXX\n#include <svx\/swframeexample.hxx>\n#endif\n#ifndef _PRCNTFLD_HXX\n#include <prcntfld.hxx>\n#endif\n#ifndef _GLOBALS_HRC\n#include <globals.hrc>\n#endif\n\n\nnamespace sfx2{class FileDialogHelper;}\nclass SwWrtShell;\nstruct FrmMap;\n\/\/ OD 12.11.2003 #i22341#\nstruct SwPosition;\n\n\/*--------------------------------------------------------------------\n Beschreibung: Rahmendialog\n --------------------------------------------------------------------*\/\n\nclass SwFrmPage: public SfxTabPage\n{\n \/\/ Size\n FixedText aWidthFT;\n FixedText aWidthAutoFT;\n PercentField aWidthED;\n CheckBox aRelWidthCB;\n CheckBox aAutoWidthCB;\n FixedText aHeightFT;\n FixedText aHeightAutoFT;\n PercentField aHeightED;\n CheckBox aRelHeightCB;\n CheckBox aAutoHeightCB;\n CheckBox aFixedRatioCB;\n PushButton aRealSizeBT;\n FixedLine aSizeFL;\n\n \/\/ Anker\n FixedLine aTypeFL;\n FixedLine aTypeSepFL;\n RadioButton aAnchorAtPageRB;\n RadioButton aAnchorAtParaRB;\n RadioButton aAnchorAtCharRB;\n RadioButton aAnchorAsCharRB;\n RadioButton aAnchorAtFrameRB;\n\n \/\/ Position\n FixedText aHorizontalFT;\n ListBox aHorizontalDLB;\n FixedText aAtHorzPosFT;\n MetricField aAtHorzPosED;\n FixedText aHoriRelationFT;\n ListBox aHoriRelationLB;\n CheckBox aMirrorPagesCB;\n FixedText aVerticalFT;\n ListBox aVerticalDLB;\n FixedText aAtVertPosFT;\n MetricField aAtVertPosED;\n FixedText aVertRelationFT;\n ListBox aVertRelationLB;\n \/\/ OD 02.10.2003 #i18732# - check box for new option 'FollowTextFlow'\n CheckBox aFollowTextFlowCB;\n FixedLine aPositionFL;\n\n \/\/ Example\n SvxSwFrameExample aExampleWN;\n\n \/\/'string provider'\n SvxSwFramePosString aFramePosString;\n\n BOOL bAtHorzPosModified;\n BOOL bAtVertPosModified;\n\n BOOL bFormat;\n BOOL bNew;\n BOOL bNoModifyHdl;\n BOOL bVerticalChanged; \/\/check done whether frame is in vertical environment\n BOOL bIsVerticalFrame; \/\/current frame is in vertical environment - strings are exchanged\n BOOL bIsInRightToLeft; \/\/ current frame is in right-to-left environment - strings are exchanged\n BOOL bHtmlMode;\n USHORT nHtmlMode;\n USHORT nDlgType;\n Size aGrfSize;\n Size aWrap;\n SwTwips nUpperBorder;\n SwTwips nLowerBorder;\n double fWidthHeightRatio; \/\/width-to-height ratio to support the KeepRatio button\n\n \/\/ OD 12.11.2003 #i22341# - keep content position of character for\n \/\/ to character anchored objects.\n const SwPosition* mpToCharCntntPos;\n\n \/\/ Die alten Ausrichtungen\n short nOldH;\n short nOldHRel;\n short nOldV;\n short nOldVRel;\n\n FrmMap* pVMap;\n FrmMap* pHMap;\n\n virtual void ActivatePage(const SfxItemSet& rSet);\n virtual int DeactivatePage(SfxItemSet *pSet);\n\n\n DECL_LINK( RangeModifyHdl, Edit * );\n DECL_LINK( AnchorTypeHdl, RadioButton * );\n DECL_LINK( PosHdl, ListBox * );\n DECL_LINK( RelHdl, ListBox * );\n void InitPos(RndStdIds eId, USHORT nH, USHORT nHRel,\n USHORT nV, USHORT nVRel,\n long nX, long nY);\n\n DECL_LINK( RealSizeHdl, Button * );\n DECL_LINK( RelSizeClickHdl, CheckBox * );\n DECL_LINK( MirrorHdl, CheckBox * );\n\n DECL_LINK( AutoWidthClickHdl, void* );\n DECL_LINK( AutoHeightClickHdl, void* );\n\n \/\/ Beispiel aktualisieren\n void UpdateExample();\n DECL_LINK( ModifyHdl, Edit * );\n\n void Init(const SfxItemSet& rSet, BOOL bReset = FALSE);\n \/\/ OD 12.11.2003 #i22341# - adjustment to handle maps, that are ambigous\n \/\/ in the alignment.\n USHORT FillPosLB( const FrmMap* _pMap,\n const USHORT _nAlign,\n const USHORT _nRel,\n ListBox& _rLB );\n \/\/ OD 14.11.2003 #i22341# - adjustment to handle maps, that are ambigous\n \/\/ in their string entries.\n ULONG FillRelLB( const FrmMap* _pMap,\n const USHORT _nLBSelPos,\n const USHORT _nAlign,\n USHORT _nRel,\n ListBox& _rLB,\n FixedText& _rFT );\n USHORT GetMapPos( const FrmMap *pMap, ListBox &rAlignLB );\n short GetAlignment(FrmMap *pMap, USHORT nMapPos, ListBox &rAlignLB, ListBox &rRelationLB);\n short GetRelation(FrmMap *pMap, ListBox &rRelationLB);\n RndStdIds GetAnchor();\n\n void EnableGraficMode( void ); \/\/ hides auto check boxes and re-org controls for \"Real Size\" button\n\n SwFrmPage(Window *pParent, const SfxItemSet &rSet);\n ~SwFrmPage();\n\n using TabPage::ActivatePage;\n using TabPage::DeactivatePage;\n\npublic:\n\n static SfxTabPage *Create(Window *pParent, const SfxItemSet &rSet);\n static USHORT* GetRanges();\n\n virtual BOOL FillItemSet(SfxItemSet &rSet);\n virtual void Reset(const SfxItemSet &rSet);\n\n void SetNewFrame(BOOL bNewFrame) { bNew = bNewFrame; }\n void SetFormatUsed(BOOL bFmt);\n void SetFrmType(USHORT nType) { nDlgType = nType; }\n inline BOOL IsInGraficMode( void ) { return nDlgType == DLG_FRM_GRF || nDlgType == DLG_FRM_OLE; }\n};\n\nclass SwGrfExtPage: public SfxTabPage\n{\n \/\/ Spiegeln\n FixedLine aMirrorFL;\n CheckBox aMirrorVertBox;\n CheckBox aMirrorHorzBox;\n RadioButton aAllPagesRB;\n RadioButton aLeftPagesRB;\n RadioButton aRightPagesRB;\n BmpWindow aBmpWin;\n\n FixedLine aConnectFL;\n FixedText aConnectFT;\n Edit aConnectED;\n PushButton aBrowseBT;\n\n String aFilterName;\n String aGrfName, aNewGrfName;\n\n ::sfx2::FileDialogHelper* pGrfDlg;\n\n BOOL bHtmlMode;\n\n \/\/ Handler fuer Spiegeln\n DECL_LINK( MirrorHdl, CheckBox * );\n DECL_LINK( BrowseHdl, Button * );\n\n virtual void ActivatePage(const SfxItemSet& rSet);\n SwGrfExtPage(Window *pParent, const SfxItemSet &rSet);\n ~SwGrfExtPage();\n\n using TabPage::ActivatePage;\n using TabPage::DeactivatePage;\n\npublic:\n\n static SfxTabPage *Create(Window *pParent, const SfxItemSet &rSet);\n\n virtual BOOL FillItemSet(SfxItemSet &rSet);\n virtual void Reset(const SfxItemSet &rSet);\n virtual int DeactivatePage(SfxItemSet *pSet);\n};\n\n\nclass SwFrmURLPage : public SfxTabPage\n{\n \/\/Hyperlink\n FixedLine aHyperLinkFL;\n FixedText aURLFT;\n Edit aURLED;\n PushButton aSearchPB;\n FixedText aNameFT;\n Edit aNameED;\n FixedText aFrameFT;\n ComboBox aFrameCB;\n\n \/\/Image map\n FixedLine aImageFL;\n CheckBox aServerCB;\n CheckBox aClientCB;\n\n DECL_LINK( InsertFileHdl, PushButton * );\n\n\n SwFrmURLPage(Window *pParent, const SfxItemSet &rSet);\n ~SwFrmURLPage();\n\n using TabPage::ActivatePage;\n using TabPage::DeactivatePage;\n\npublic:\n\n static SfxTabPage *Create(Window *pParent, const SfxItemSet &rSet);\n\n virtual BOOL FillItemSet(SfxItemSet &rSet);\n virtual void Reset(const SfxItemSet &rSet);\n};\n\n\/*-----------------13.11.96 12.59-------------------\n\n--------------------------------------------------*\/\n\nclass SwFrmAddPage : public SfxTabPage\n{\n FixedText aNameFT;\n Edit aNameED;\n FixedText aAltNameFT;\n Edit aAltNameED;\n FixedText aPrevFT;\n ListBox aPrevLB;\n FixedText aNextFT;\n ListBox aNextLB;\n FixedLine aNamesFL;\n\n CheckBox aProtectContentCB;\n CheckBox aProtectFrameCB;\n CheckBox aProtectSizeCB;\n FixedLine aProtectFL;\n\n CheckBox aEditInReadonlyCB;\n CheckBox aPrintFrameCB;\n FixedText aTextFlowFT;\n ListBox aTextFlowLB;\n\n FixedLine aExtFL;\n\n SwWrtShell* pWrtSh;\n\n USHORT nDlgType;\n BOOL bHtmlMode;\n BOOL bFormat;\n BOOL bNew;\n\n DECL_LINK(EditModifyHdl, Edit*);\n DECL_LINK(ChainModifyHdl, ListBox*);\n\n SwFrmAddPage(Window *pParent, const SfxItemSet &rSet);\n ~SwFrmAddPage();\n\npublic:\n\n static SfxTabPage* Create(Window *pParent, const SfxItemSet &rSet);\n static USHORT* GetRanges();\n\n virtual BOOL FillItemSet(SfxItemSet &rSet);\n virtual void Reset(const SfxItemSet &rSet);\n\n void SetFormatUsed(BOOL bFmt);\n void SetFrmType(USHORT nType) { nDlgType = nType; }\n void SetNewFrame(BOOL bNewFrame) { bNew = bNewFrame; }\n void SetShell(SwWrtShell* pSh) { pWrtSh = pSh; }\n\n};\n\n#endif \/\/ _FRMPAGE_HXX\n<commit_msg>INTEGRATION: CWS changefileheader (1.20.214); FILE MERGED 2008\/04\/01 15:59:12 thb 1.20.214.3: #i85898# Stripping all external header guards 2008\/04\/01 12:55:27 thb 1.20.214.2: #i85898# Stripping all external header guards 2008\/03\/31 16:58:31 rt 1.20.214.1: #i87441# Change license header to LPGL v3.<commit_after>\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2008 by Sun Microsystems, Inc.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: frmpage.hxx,v $\n * $Revision: 1.21 $\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * <http:\/\/www.openoffice.org\/license.html>\n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n#ifndef _FRMPAGE_HXX\n#define _FRMPAGE_HXX\n\n#ifndef _FIXED_HXX \/\/autogen\n#include <vcl\/fixed.hxx>\n#endif\n#ifndef _BUTTON_HXX \/\/autogen\n#include <vcl\/button.hxx>\n#endif\n#ifndef _LSTBOX_HXX \/\/autogen\n#include <vcl\/lstbox.hxx>\n#endif\n#ifndef _FIELD_HXX \/\/autogen\n#include <vcl\/field.hxx>\n#endif\n#include <sfx2\/tabdlg.hxx>\n#include <svx\/swframeposstrings.hxx>\n#include <swtypes.hxx>\n#include <bmpwin.hxx>\n#include <svx\/swframeexample.hxx>\n#include <prcntfld.hxx>\n#ifndef _GLOBALS_HRC\n#include <globals.hrc>\n#endif\n\n\nnamespace sfx2{class FileDialogHelper;}\nclass SwWrtShell;\nstruct FrmMap;\n\/\/ OD 12.11.2003 #i22341#\nstruct SwPosition;\n\n\/*--------------------------------------------------------------------\n Beschreibung: Rahmendialog\n --------------------------------------------------------------------*\/\n\nclass SwFrmPage: public SfxTabPage\n{\n \/\/ Size\n FixedText aWidthFT;\n FixedText aWidthAutoFT;\n PercentField aWidthED;\n CheckBox aRelWidthCB;\n CheckBox aAutoWidthCB;\n FixedText aHeightFT;\n FixedText aHeightAutoFT;\n PercentField aHeightED;\n CheckBox aRelHeightCB;\n CheckBox aAutoHeightCB;\n CheckBox aFixedRatioCB;\n PushButton aRealSizeBT;\n FixedLine aSizeFL;\n\n \/\/ Anker\n FixedLine aTypeFL;\n FixedLine aTypeSepFL;\n RadioButton aAnchorAtPageRB;\n RadioButton aAnchorAtParaRB;\n RadioButton aAnchorAtCharRB;\n RadioButton aAnchorAsCharRB;\n RadioButton aAnchorAtFrameRB;\n\n \/\/ Position\n FixedText aHorizontalFT;\n ListBox aHorizontalDLB;\n FixedText aAtHorzPosFT;\n MetricField aAtHorzPosED;\n FixedText aHoriRelationFT;\n ListBox aHoriRelationLB;\n CheckBox aMirrorPagesCB;\n FixedText aVerticalFT;\n ListBox aVerticalDLB;\n FixedText aAtVertPosFT;\n MetricField aAtVertPosED;\n FixedText aVertRelationFT;\n ListBox aVertRelationLB;\n \/\/ OD 02.10.2003 #i18732# - check box for new option 'FollowTextFlow'\n CheckBox aFollowTextFlowCB;\n FixedLine aPositionFL;\n\n \/\/ Example\n SvxSwFrameExample aExampleWN;\n\n \/\/'string provider'\n SvxSwFramePosString aFramePosString;\n\n BOOL bAtHorzPosModified;\n BOOL bAtVertPosModified;\n\n BOOL bFormat;\n BOOL bNew;\n BOOL bNoModifyHdl;\n BOOL bVerticalChanged; \/\/check done whether frame is in vertical environment\n BOOL bIsVerticalFrame; \/\/current frame is in vertical environment - strings are exchanged\n BOOL bIsInRightToLeft; \/\/ current frame is in right-to-left environment - strings are exchanged\n BOOL bHtmlMode;\n USHORT nHtmlMode;\n USHORT nDlgType;\n Size aGrfSize;\n Size aWrap;\n SwTwips nUpperBorder;\n SwTwips nLowerBorder;\n double fWidthHeightRatio; \/\/width-to-height ratio to support the KeepRatio button\n\n \/\/ OD 12.11.2003 #i22341# - keep content position of character for\n \/\/ to character anchored objects.\n const SwPosition* mpToCharCntntPos;\n\n \/\/ Die alten Ausrichtungen\n short nOldH;\n short nOldHRel;\n short nOldV;\n short nOldVRel;\n\n FrmMap* pVMap;\n FrmMap* pHMap;\n\n virtual void ActivatePage(const SfxItemSet& rSet);\n virtual int DeactivatePage(SfxItemSet *pSet);\n\n\n DECL_LINK( RangeModifyHdl, Edit * );\n DECL_LINK( AnchorTypeHdl, RadioButton * );\n DECL_LINK( PosHdl, ListBox * );\n DECL_LINK( RelHdl, ListBox * );\n void InitPos(RndStdIds eId, USHORT nH, USHORT nHRel,\n USHORT nV, USHORT nVRel,\n long nX, long nY);\n\n DECL_LINK( RealSizeHdl, Button * );\n DECL_LINK( RelSizeClickHdl, CheckBox * );\n DECL_LINK( MirrorHdl, CheckBox * );\n\n DECL_LINK( AutoWidthClickHdl, void* );\n DECL_LINK( AutoHeightClickHdl, void* );\n\n \/\/ Beispiel aktualisieren\n void UpdateExample();\n DECL_LINK( ModifyHdl, Edit * );\n\n void Init(const SfxItemSet& rSet, BOOL bReset = FALSE);\n \/\/ OD 12.11.2003 #i22341# - adjustment to handle maps, that are ambigous\n \/\/ in the alignment.\n USHORT FillPosLB( const FrmMap* _pMap,\n const USHORT _nAlign,\n const USHORT _nRel,\n ListBox& _rLB );\n \/\/ OD 14.11.2003 #i22341# - adjustment to handle maps, that are ambigous\n \/\/ in their string entries.\n ULONG FillRelLB( const FrmMap* _pMap,\n const USHORT _nLBSelPos,\n const USHORT _nAlign,\n USHORT _nRel,\n ListBox& _rLB,\n FixedText& _rFT );\n USHORT GetMapPos( const FrmMap *pMap, ListBox &rAlignLB );\n short GetAlignment(FrmMap *pMap, USHORT nMapPos, ListBox &rAlignLB, ListBox &rRelationLB);\n short GetRelation(FrmMap *pMap, ListBox &rRelationLB);\n RndStdIds GetAnchor();\n\n void EnableGraficMode( void ); \/\/ hides auto check boxes and re-org controls for \"Real Size\" button\n\n SwFrmPage(Window *pParent, const SfxItemSet &rSet);\n ~SwFrmPage();\n\n using TabPage::ActivatePage;\n using TabPage::DeactivatePage;\n\npublic:\n\n static SfxTabPage *Create(Window *pParent, const SfxItemSet &rSet);\n static USHORT* GetRanges();\n\n virtual BOOL FillItemSet(SfxItemSet &rSet);\n virtual void Reset(const SfxItemSet &rSet);\n\n void SetNewFrame(BOOL bNewFrame) { bNew = bNewFrame; }\n void SetFormatUsed(BOOL bFmt);\n void SetFrmType(USHORT nType) { nDlgType = nType; }\n inline BOOL IsInGraficMode( void ) { return nDlgType == DLG_FRM_GRF || nDlgType == DLG_FRM_OLE; }\n};\n\nclass SwGrfExtPage: public SfxTabPage\n{\n \/\/ Spiegeln\n FixedLine aMirrorFL;\n CheckBox aMirrorVertBox;\n CheckBox aMirrorHorzBox;\n RadioButton aAllPagesRB;\n RadioButton aLeftPagesRB;\n RadioButton aRightPagesRB;\n BmpWindow aBmpWin;\n\n FixedLine aConnectFL;\n FixedText aConnectFT;\n Edit aConnectED;\n PushButton aBrowseBT;\n\n String aFilterName;\n String aGrfName, aNewGrfName;\n\n ::sfx2::FileDialogHelper* pGrfDlg;\n\n BOOL bHtmlMode;\n\n \/\/ Handler fuer Spiegeln\n DECL_LINK( MirrorHdl, CheckBox * );\n DECL_LINK( BrowseHdl, Button * );\n\n virtual void ActivatePage(const SfxItemSet& rSet);\n SwGrfExtPage(Window *pParent, const SfxItemSet &rSet);\n ~SwGrfExtPage();\n\n using TabPage::ActivatePage;\n using TabPage::DeactivatePage;\n\npublic:\n\n static SfxTabPage *Create(Window *pParent, const SfxItemSet &rSet);\n\n virtual BOOL FillItemSet(SfxItemSet &rSet);\n virtual void Reset(const SfxItemSet &rSet);\n virtual int DeactivatePage(SfxItemSet *pSet);\n};\n\n\nclass SwFrmURLPage : public SfxTabPage\n{\n \/\/Hyperlink\n FixedLine aHyperLinkFL;\n FixedText aURLFT;\n Edit aURLED;\n PushButton aSearchPB;\n FixedText aNameFT;\n Edit aNameED;\n FixedText aFrameFT;\n ComboBox aFrameCB;\n\n \/\/Image map\n FixedLine aImageFL;\n CheckBox aServerCB;\n CheckBox aClientCB;\n\n DECL_LINK( InsertFileHdl, PushButton * );\n\n\n SwFrmURLPage(Window *pParent, const SfxItemSet &rSet);\n ~SwFrmURLPage();\n\n using TabPage::ActivatePage;\n using TabPage::DeactivatePage;\n\npublic:\n\n static SfxTabPage *Create(Window *pParent, const SfxItemSet &rSet);\n\n virtual BOOL FillItemSet(SfxItemSet &rSet);\n virtual void Reset(const SfxItemSet &rSet);\n};\n\n\/*-----------------13.11.96 12.59-------------------\n\n--------------------------------------------------*\/\n\nclass SwFrmAddPage : public SfxTabPage\n{\n FixedText aNameFT;\n Edit aNameED;\n FixedText aAltNameFT;\n Edit aAltNameED;\n FixedText aPrevFT;\n ListBox aPrevLB;\n FixedText aNextFT;\n ListBox aNextLB;\n FixedLine aNamesFL;\n\n CheckBox aProtectContentCB;\n CheckBox aProtectFrameCB;\n CheckBox aProtectSizeCB;\n FixedLine aProtectFL;\n\n CheckBox aEditInReadonlyCB;\n CheckBox aPrintFrameCB;\n FixedText aTextFlowFT;\n ListBox aTextFlowLB;\n\n FixedLine aExtFL;\n\n SwWrtShell* pWrtSh;\n\n USHORT nDlgType;\n BOOL bHtmlMode;\n BOOL bFormat;\n BOOL bNew;\n\n DECL_LINK(EditModifyHdl, Edit*);\n DECL_LINK(ChainModifyHdl, ListBox*);\n\n SwFrmAddPage(Window *pParent, const SfxItemSet &rSet);\n ~SwFrmAddPage();\n\npublic:\n\n static SfxTabPage* Create(Window *pParent, const SfxItemSet &rSet);\n static USHORT* GetRanges();\n\n virtual BOOL FillItemSet(SfxItemSet &rSet);\n virtual void Reset(const SfxItemSet &rSet);\n\n void SetFormatUsed(BOOL bFmt);\n void SetFrmType(USHORT nType) { nDlgType = nType; }\n void SetNewFrame(BOOL bNewFrame) { bNew = bNewFrame; }\n void SetShell(SwWrtShell* pSh) { pWrtSh = pSh; }\n\n};\n\n#endif \/\/ _FRMPAGE_HXX\n<|endoftext|>"} {"text":"<commit_before>#include <string.h>\n#include <iostream>\n#include <fstream>\n#include <stdlib.h>\n#include <stdio.h>\n#include <sstream>\n#include <sys\/stat.h>\n#include <time.h>\n\n#include \"SuMo.h\"\n#include \"Timer.h\"\n\n\/* specific to file *\/\nconst int NUM_ARGS = 4;\nconst char* filename = \"logData\";\nconst char* description = \"log data from DAQ\";\nusing namespace std;\n\/********************\/\n\n\/* subtract pedestal values on-line *\/\nstatic bool PED_SUBTRCT = false; \n\nstatic int LIMIT_READOUT_RATE = 10000;\nstatic int NUM_SEQ_TIMEOUTS = 100;\nconst float MAX_INT_TIMER = 600.; \/\/ 10 minutes\n\/* note: usb timeout defined in include\/stdUSB.h *\/\n\nbool overwriteExistingFile = false;\n\nbool fileExists(const std::string& filename);\n\nint main(int argc, char* argv[]){\n if(argc == 2 && std::string(argv[1]) == \"-h\"){\n cout << endl;\n cout << filename << \" :: \" << description << endl;\n cout << filename << \" :: takes \" << NUM_ARGS-1 << \" arguments\" << endl;\n return 1; \n }\n else if(argc > NUM_ARGS+1 || argc < NUM_ARGS){\n cout << \"error: too many number of arguments\" << endl;\n return -1;\n }\n else{\n int num_checks = 5; \n int num_events = 100;\n int acq_rate = 10000;\n SuMo command;\n char log_data_filename[100];\n \n strcpy(log_data_filename, argv[1]);\n num_events = atoi(argv[2]);\n int trig_mode = atoi(argv[3]);\n \n if(command.check_active_boards(num_checks))\n return 1;\n\n command.log_data(log_data_filename, num_events, trig_mode, acq_rate);\n \n return 0;\n }\n}\n\nint SuMo::log_data(const char* log_filename, unsigned int NUM_READS, int trig_mode, int acq_rate){\n bool convert_to_voltage;\n int sample, check_event, asic_baseline[psecSampleCells], count = 0, psec_cnt = 0, numTimeouts = 0, last_k;\n float _now_, t = 0.;\n char logDataFilename[300];\n Timer timer = Timer(); \n time_t now;\n\n \/* handle filename *\/\n \/\/ 'scalar' mode\n ofstream rate_fs;\n if(trig_mode == 2){\n char logRateFilename[300];\n sprintf(logRateFilename, \"%s.acdc.rate\", log_filename);\n rate_fs.open(logRateFilename, ios::trunc);\n }\n \n \/\/ full waveform, standard mode\n sprintf(logDataFilename, \"%s.acdc.dat\", log_filename);\n string temp;\n while(fileExists(logDataFilename)){\n cout << \"file already exists, try new filename: (or enter to overwrite \/ ctrl-C to quit): \";\n getline(cin, temp);\n if(temp.empty()) break;\n sprintf(logDataFilename, \"%s.acdc.dat\", temp.c_str());\n }\n \n ofstream ofs;\n ofs.open(logDataFilename, ios::trunc);\n\n \/* read all front end cards *\/\n bool all[numFrontBoards];\n for(int i=0;i<numFrontBoards; i++) all[i] = true;\n\n \/* setup some things *\/\n if(trig_mode==1) {\n set_usb_read_mode(24);\n if(mode==USB2x) set_usb_read_mode_slaveDevice(24);\n }\n else {\n if(mode==USB2x) set_usb_read_mode_slaveDevice(16);\n set_usb_read_mode(16), dump_data();\n } \n \n load_ped();\n \/* save pedestal data to file header for reference, easy access *\/\n \/* zero pad to match data format *\/\n for(int i=0; i < psecSampleCells; i++){\n \n ofs << i << \" \" << 0 << \" \";\n for(int board=0; board<numFrontBoards; board++){\n if(DC_ACTIVE[board]){\n\tfor(int channel=0; channel < AC_CHANNELS; channel++) ofs << PED_DATA[board][channel][i]<< \" \"; \n\tofs << 0 << \" \";\n }\n }\n ofs << endl;\n }\n\n \/* cpu time zero *\/\n \/\/t0 = time(NULL);\n timer.start();\n\n for(int k=0;k<NUM_READS; k++){\n \/* unix timestamp *\/\n time(&now);\n \/* rough cpu timing in seconds since readout start time*\/\n t = timer.stop(); \n if(t > MAX_INT_TIMER) {\n cout << endl << \"readout timed out at \" << t << \"on event \" << k << endl;\n break;\n }\n \/*set read mode to NULL *\/\n set_usb_read_mode(16);\n if(mode==USB2x) set_usb_read_mode_slaveDevice(16);\n \/*reset last event on firmware *\/\n manage_cc_fifo(1);\n if(mode==USB2x) manage_cc_fifo_slaveDevice(1);\n\n \/*send trigger over software if not looking externally *\/\n if(trig_mode==1){ \n reset_self_trigger(15, 0), set_usb_read_mode(7);\n if(mode == USB2x) reset_self_trigger(15, 1), set_usb_read_mode_slaveDevice(7);\n usleep(acq_rate+LIMIT_READOUT_RATE);\n set_usb_read_mode(0);\n if(mode == USB2x) set_usb_read_mode_slaveDevice(0);\n }\n else{\n \/\/ 'rate-only' mode, only pull data every second\n if(trig_mode == 2){\n\tusleep(3e6);\n }\n \n software_trigger((unsigned int)15);\n if(mode == USB2x) software_trigger_slaveDevice((unsigned int)15);\n usleep(LIMIT_READOUT_RATE); \/* somewhat arbitrary hard-coded rate limitation *\/\n \n }\n\n \/* show event number at terminal *\/\n if((k+1) % 2 == 0 || k==0){\n cout << \"Readout: \" << k+1 << \" of \" << NUM_READS << \" :: @time \"<< t << \" sec \\r\";\n cout.flush();\n } \n \/**************************************\/\n \/*Do bulk read on all front-end cards *\/ \n int numBoards = read_AC(1, all, false);\n \/**************************************\/\n \/* handle timeouts or lack of data *\/\n int numBoardsTimedout = 0;\n for(int i=0; i<numFrontBoards; i++) numBoardsTimedout = numBoardsTimedout + (int)BOARDS_TIMEOUT[i];\n \/\/ timeout on all boards\n if( numBoards == 0 ){\n ofs << k << \" \" << 0xFF << \" \" << endl;\n\n k = k-1; \/\/repeat event\n continue;\t\n \n }\n \/*\n int numBoardsTimedout = 0;\n for(int i=0; i<numFrontBoards; i++) numBoardsTimedout = numBoardsTimedout + (int)BOARDS_TIMEOUT[i];\n if(numBoards == 0 || numBoardsTimedout > 0){\n \/\/ check for number of timeouts in a row \n numTimeouts++; \n \/\/ handle if too many timeouts: \n if(numTimeouts > NUM_SEQ_TIMEOUTS){\n\tcout << endl << \"error: too many timeouts in a row\" << endl; \n\treturn -1;\n }\n k = k-1;\n continue; \n }\n else numTimeouts = 0; \n *\/\n\n \/* form data for filesave *\/\n for(int targetAC = 0; targetAC < numFrontBoards; targetAC++){ \n if(BOARDS_READOUT[targetAC] && numBoards > 0){\n\tpsec_cnt = 0;\n\t\/*assign meta data *\/\n\tget_AC_info(false, targetAC);\n\tform_meta_data(targetAC, k, t, now);\n\n\tcheck_event = 0;\n\n\tfor(int i = 0; i < AC_CHANNELS; i++){\n\t if(i>0 && i % 6 == 0) psec_cnt ++;\n\n\t for(int j = 0; j < psecSampleCells; j++){\n\t sample = adcDat[targetAC]->AC_RAW_DATA[psec_cnt][i%6*256+j];\n\t if(PED_SUBTRCT) sample -= PED_DATA[targetAC][i][j]; \n\t \n\t adcDat[targetAC]->Data[i][j] = sample;\n\t }\n\t} \n\t\/* wraparound_correction, if desired: *\/\n\tint baseline[psecSampleCells];\n\tunwrap_baseline(baseline, 2); \n\tfor (int j = 0; j < psecSampleCells; j++) asic_baseline[j] = baseline[j];\n }\n \/\/if timeout on only some, but not all boards\n else if( numBoards > 0 && BOARDS_TIMEOUT[targetAC] ){\n\tfor(int i = 0; i < AC_CHANNELS; i++){\n\t if(i>0 && i % 6 == 0) psec_cnt ++;\n\n\t for(int j = 0; j < psecSampleCells; j++){\n\t sample = 0xFF; \n\t adcDat[targetAC]->Data[i][j] = sample;\n\t }\n\t} \n }\n }\n\t\n for(int i=0; i < psecSampleCells; i++){\n\n ofs << i << \" \" << asic_baseline[i] << \" \";\n for(int board=0; board<numFrontBoards; board++)\n\tif(BOARDS_READOUT[board])\n\t for(int channel=0; channel < AC_CHANNELS+1; channel++) ofs << std::dec << adcDat[board]->Data[channel][i] << \" \";\n else if(BOARDS_TIMEOUT[board])\n \t for(int channel=0; channel < AC_CHANNELS+1; channel++) ofs << std::dec << adcDat[board]->Data[channel][i] << \" \";\n\n ofs <<endl;\n } \n \n if(trig_mode == 2){\n for(int board=0; board<numFrontBoards; board++){\n\tif(BOARDS_READOUT[board]){\n\n\t rate_fs << k << \"\\t\" << board << \"\\t\" << t << \"\\t\";\n\n\t for(int channel=0; channel < AC_CHANNELS; channel++) rate_fs << adcDat[board]->self_trig_scalar[channel] << \"\\t\";\n\t \n\t rate_fs << endl;\n\t}\n }\n }\n last_k = k;\n }\n \n cout << \"Readout: \" << last_k+1<< \" of \" << NUM_READS << \" :: @time \" <<t<< \" sec...........\\r\", usleep(100000),cout.flush();\n cout << \"Readout: \" << last_k+1 << \" of \" << NUM_READS << \" :: @time \" <<t<< \" sec...........finished logging\\r\",cout.flush();\n\n manage_cc_fifo(1);\n \/* add whitespace to end of file *\/\n ofs <<endl<<endl;\n ofs.close();\n\n if(trig_mode == 2) rate_fs.close();\n\n set_usb_read_mode(16); \/\/turn off trigger, if on\n dump_data();\n \n cout << endl;\n cout << \"Data saved in file: \" << logDataFilename << endl << \"*****\" << endl;\n return 0;\n}\n\nbool fileExists(const string& filename)\n{\n struct stat buf;\n if (stat(filename.c_str(), &buf) != -1)\n {\n return true;\n }\n return false;\n}\n\nvoid SuMo::form_meta_data(int Address, int count, double cpuTime, time_t now)\n{\n int i = Address;\n adcDat[i]->Data[AC_CHANNELS][0] = count;\n adcDat[i]->Data[AC_CHANNELS][1] = Address;\n adcDat[i]->Data[AC_CHANNELS][2] = adcDat[i]->CC_EVENT_COUNT;\n adcDat[i]->Data[AC_CHANNELS][3] = adcDat[i]->CC_BIN_COUNT; \n adcDat[i]->Data[AC_CHANNELS][4] = adcDat[i]->timestamp_hi;\n adcDat[i]->Data[AC_CHANNELS][5] = adcDat[i]->timestamp_mid;\n adcDat[i]->Data[AC_CHANNELS][6] = adcDat[i]->timestamp_lo;\n \n adcDat[i]->Data[AC_CHANNELS][7] = adcDat[i]->CC_TIMESTAMP_HI;\n adcDat[i]->Data[AC_CHANNELS][8] = adcDat[i]->CC_TIMESTAMP_MID;\n adcDat[i]->Data[AC_CHANNELS][9] = adcDat[i]->CC_TIMESTAMP_LO;\n\n adcDat[i]->Data[AC_CHANNELS][10] = adcDat[i]->bin_count_rise;\n adcDat[i]->Data[AC_CHANNELS][11] = adcDat[i]->bin_count_fall;\n adcDat[i]->Data[AC_CHANNELS][12] = adcDat[i]->self_trig_settings; \n adcDat[i]->Data[AC_CHANNELS][13] = adcDat[i]->event_count;\n adcDat[i]->Data[AC_CHANNELS][14] = adcDat[i]->reg_self_trig[0];\n adcDat[i]->Data[AC_CHANNELS][15] = adcDat[i]->reg_self_trig[1]; \n adcDat[i]->Data[AC_CHANNELS][16] = adcDat[i]->reg_self_trig[2];\n adcDat[i]->Data[AC_CHANNELS][17] = adcDat[i]->reg_self_trig[3]; \n adcDat[i]->Data[AC_CHANNELS][18] = adcDat[i]->self_trig_mask; \n adcDat[i]->Data[AC_CHANNELS][19] = adcDat[i]->last_ac_instruct; \n adcDat[i]->Data[AC_CHANNELS][20] = adcDat[i]->last_last_ac_instruct;\n adcDat[i]->Data[AC_CHANNELS][21] = adcDat[i]->trig_en; \n adcDat[i]->Data[AC_CHANNELS][22] = adcDat[i]->trig_wait_for_sys; \n adcDat[i]->Data[AC_CHANNELS][23] = adcDat[i]->trig_rate_only; \n adcDat[i]->Data[AC_CHANNELS][24] = adcDat[i]->trig_sign; \n\n \/*fill slots 25-39 *\/\n for(int j=0; j<numChipsOnBoard; j++){\n adcDat[i]->Data[AC_CHANNELS][j+25] = adcDat[i]->ro_cnt[j]; \n adcDat[i]->Data[AC_CHANNELS][j+25+numChipsOnBoard] = adcDat[i]->vbias[j]; \n adcDat[i]->Data[AC_CHANNELS][j+25+2*numChipsOnBoard] = adcDat[i]->trigger_threshold[j]; \n }\n \/*fill slots 40-69 *\/\n for(int j=0; j<AC_CHANNELS; j++){\n adcDat[i]->Data[AC_CHANNELS][j+40] = adcDat[i]->self_trig_scalar[j];\n }\n adcDat[i]->Data[AC_CHANNELS][70] = cpuTime;\n adcDat[i]->Data[AC_CHANNELS][71] = now;\n adcDat[i]->Data[AC_CHANNELS][72] = WRAP_CONSTANT; \n\n}\n\n\n\n<commit_msg>modify logData to handle low rates and timeouts<commit_after>#include <string.h>\n#include <iostream>\n#include <fstream>\n#include <stdlib.h>\n#include <stdio.h>\n#include <sstream>\n#include <sys\/stat.h>\n#include <time.h>\n\n#include \"SuMo.h\"\n#include \"Timer.h\"\n\n\/* specific to file *\/\nconst int NUM_ARGS = 4;\nconst char* filename = \"logData\";\nconst char* description = \"log data from DAQ\";\nusing namespace std;\n\/********************\/\n\n\/* subtract pedestal values on-line *\/\nstatic bool PED_SUBTRCT = false; \n\nstatic int LIMIT_READOUT_RATE = 10000;\nstatic int NUM_SEQ_TIMEOUTS = 100;\nconst float MAX_INT_TIMER = 100.; \n\/* note: usb timeout defined in include\/stdUSB.h *\/\n\nbool overwriteExistingFile = false;\n\nbool fileExists(const std::string& filename);\n\nint main(int argc, char* argv[]){\n if(argc == 2 && std::string(argv[1]) == \"-h\"){\n cout << endl;\n cout << filename << \" :: \" << description << endl;\n cout << filename << \" :: takes \" << NUM_ARGS-1 << \" arguments\" << endl;\n return 1; \n }\n else if(argc > NUM_ARGS+1 || argc < NUM_ARGS){\n cout << \"error: too many number of arguments\" << endl;\n return -1;\n }\n else{\n int num_checks = 5; \n int num_events = 100;\n int acq_rate = 10000;\n SuMo command;\n char log_data_filename[100];\n \n strcpy(log_data_filename, argv[1]);\n num_events = atoi(argv[2]);\n int trig_mode = atoi(argv[3]);\n \n if(command.check_active_boards(num_checks))\n return 1;\n\n command.log_data(log_data_filename, num_events, trig_mode, acq_rate);\n \n return 0;\n }\n}\n\nint SuMo::log_data(const char* log_filename, unsigned int NUM_READS, int trig_mode, int acq_rate){\n bool convert_to_voltage;\n int sample, check_event, asic_baseline[psecSampleCells], count = 0, psec_cnt = 0, numTimeouts = 0, last_k;\n float _now_, t = 0.;\n char logDataFilename[300];\n Timer timer = Timer(); \n time_t now;\n\n \/* handle filename *\/\n \/\/ 'scalar' mode\n ofstream rate_fs;\n if(trig_mode == 2){\n char logRateFilename[300];\n sprintf(logRateFilename, \"%s.acdc.rate\", log_filename);\n rate_fs.open(logRateFilename, ios::trunc);\n }\n \n \/\/ full waveform, standard mode\n sprintf(logDataFilename, \"%s.acdc.dat\", log_filename);\n string temp;\n while(fileExists(logDataFilename)){\n cout << \"file already exists, try new filename: (or enter to overwrite \/ ctrl-C to quit): \";\n getline(cin, temp);\n if(temp.empty()) break;\n sprintf(logDataFilename, \"%s.acdc.dat\", temp.c_str());\n }\n \n ofstream ofs;\n ofs.open(logDataFilename, ios::trunc);\n\n \/* read all front end cards *\/\n bool all[numFrontBoards];\n for(int i=0;i<numFrontBoards; i++) all[i] = true;\n\n \/* setup some things *\/\n if(trig_mode==1) {\n set_usb_read_mode(24);\n if(mode==USB2x) set_usb_read_mode_slaveDevice(24);\n }\n else {\n if(mode==USB2x) set_usb_read_mode_slaveDevice(16);\n set_usb_read_mode(16), dump_data();\n } \n \n load_ped();\n \/* save pedestal data to file header for reference, easy access *\/\n \/* zero pad to match data format *\/\n for(int i=0; i < psecSampleCells; i++){\n \n ofs << i << \" \" << 0 << \" \";\n for(int board=0; board<numFrontBoards; board++){\n if(DC_ACTIVE[board]){\n\tfor(int channel=0; channel < AC_CHANNELS; channel++) ofs << PED_DATA[board][channel][i]<< \" \"; \n\tofs << 0 << \" \";\n }\n }\n ofs << endl;\n }\n\n \/* cpu time zero *\/\n \/\/t0 = time(NULL);\n timer.start();\n\n for(int k=0;k<NUM_READS; k++){\n \/* unix timestamp *\/\n time(&now);\n \/* rough cpu timing in seconds since readout start time*\/\n t = timer.stop(); \n if(t > MAX_INT_TIMER) {\n cout << endl << \"readout timed out at \" << t << \"on event \" << k << endl;\n break;\n }\n \/*set read mode to NULL *\/\n set_usb_read_mode(16);\n if(mode==USB2x) set_usb_read_mode_slaveDevice(16);\n \/*reset last event on firmware *\/\n manage_cc_fifo(1);\n if(mode==USB2x) manage_cc_fifo_slaveDevice(1);\n\n \/*send trigger over software if not looking externally *\/\n if(trig_mode==1){ \n if(mode == USB2x) reset_self_trigger(15, 1);\n reset_self_trigger(15, 0);\n\n if(mode == USB2x) set_usb_read_mode_slaveDevice(7);\n set_usb_read_mode(7);\n\n usleep(acq_rate+LIMIT_READOUT_RATE); \/\/acq rate limit\n \n if(mode == USB2x) set_usb_read_mode_slaveDevice(0); \n set_usb_read_mode(0);\n }\n else{\n \/\/ 'rate-only' mode, only pull data every second\n if(trig_mode == 2){\n\tusleep(3e6);\n }\n \n software_trigger((unsigned int)15);\n if(mode == USB2x) software_trigger_slaveDevice((unsigned int)15);\n usleep(LIMIT_READOUT_RATE); \/* somewhat arbitrary hard-coded rate limitation *\/\n \n }\n\n \/* show event number at terminal *\/\n if((k+1) % 2 == 0 || k==0){\n cout << \"Readout: \" << k+1 << \" of \" << NUM_READS << \" :: @time \"<< t << \" sec \\r\";\n cout.flush();\n } \n \/**************************************\/\n \/*Do bulk read on all front-end cards *\/ \n int numBoards = read_AC(1, all, false);\n \/**************************************\/\n \n \/* handle timeouts or lack of data *\/\n int numBoardsTimedout = 0;\n for(int i=0; i<numFrontBoards; i++) numBoardsTimedout = numBoardsTimedout + (int)BOARDS_TIMEOUT[i];\n \/\/ timeout on all boards\n if( numBoards == 0 ){\n \/\/ofs << k << \" \" << 0xFF << \" \" << endl;\n k = k-1; \/\/repeat event\n continue;\t\n \n }\n \/*\n int numBoardsTimedout = 0;\n for(int i=0; i<numFrontBoards; i++) numBoardsTimedout = numBoardsTimedout + (int)BOARDS_TIMEOUT[i];\n if(numBoards == 0 || numBoardsTimedout > 0){\n \/\/ check for number of timeouts in a row \n numTimeouts++; \n \/\/ handle if too many timeouts: \n if(numTimeouts > NUM_SEQ_TIMEOUTS){\n\tcout << endl << \"error: too many timeouts in a row\" << endl; \n\treturn -1;\n }\n k = k-1;\n continue; \n }\n else numTimeouts = 0; \n *\/\n\n \/* form data for filesave *\/\n for(int targetAC = 0; targetAC < numFrontBoards; targetAC++){ \n if(BOARDS_READOUT[targetAC] && numBoards > 0){\n\tpsec_cnt = 0;\n\t\/*assign meta data *\/\n\tget_AC_info(false, targetAC);\n\tform_meta_data(targetAC, k, t, now);\n\n\tcheck_event = 0;\n\n\tfor(int i = 0; i < AC_CHANNELS; i++){\n\t if(i>0 && i % 6 == 0) psec_cnt ++;\n\n\t for(int j = 0; j < psecSampleCells; j++){\n\t sample = adcDat[targetAC]->AC_RAW_DATA[psec_cnt][i%6*256+j];\n\t if(PED_SUBTRCT) sample -= PED_DATA[targetAC][i][j]; \n\t \n\t adcDat[targetAC]->Data[i][j] = sample;\n\t }\n\t} \n\t\/* wraparound_correction, if desired: *\/\n\tint baseline[psecSampleCells];\n\tunwrap_baseline(baseline, 2); \n\tfor (int j = 0; j < psecSampleCells; j++) asic_baseline[j] = baseline[j];\n }\n \/\/if timeout on only some, but not all boards\n else if( numBoards > 0 && BOARDS_TIMEOUT[targetAC] ){\n\tfor(int i = 0; i < AC_CHANNELS; i++){\n\t if(i>0 && i % 6 == 0) psec_cnt ++;\n\n\t for(int j = 0; j < psecSampleCells; j++){\n\t sample = 0xFF; \n\t adcDat[targetAC]->Data[i][j] = sample;\n\t }\n\t} \n }\n }\n\t\n for(int i=0; i < psecSampleCells; i++){\n\n ofs << i << \" \" << asic_baseline[i] << \" \";\n for(int board=0; board<numFrontBoards; board++)\n\tif(BOARDS_READOUT[board])\n\t for(int channel=0; channel < AC_CHANNELS+1; channel++) ofs << std::dec << adcDat[board]->Data[channel][i] << \" \";\n else if(BOARDS_TIMEOUT[board])\n \t for(int channel=0; channel < AC_CHANNELS+1; channel++) ofs << std::dec << adcDat[board]->Data[channel][i] << \" \";\n\n ofs <<endl;\n } \n \n if(trig_mode == 2){\n for(int board=0; board<numFrontBoards; board++){\n\tif(BOARDS_READOUT[board]){\n\n\t rate_fs << k << \"\\t\" << board << \"\\t\" << t << \"\\t\";\n\n\t for(int channel=0; channel < AC_CHANNELS; channel++) rate_fs << adcDat[board]->self_trig_scalar[channel] << \"\\t\";\n\t \n\t rate_fs << endl;\n\t}\n }\n }\n last_k = k;\n }\n \n cout << \"Readout: \" << last_k+1<< \" of \" << NUM_READS << \" :: @time \" <<t<< \" sec...........\\r\", usleep(100000),cout.flush();\n cout << \"Readout: \" << last_k+1 << \" of \" << NUM_READS << \" :: @time \" <<t<< \" sec...........finished logging\\r\",cout.flush();\n\n manage_cc_fifo(1);\n \/* add whitespace to end of file *\/\n ofs <<endl<<endl;\n ofs.close();\n\n if(trig_mode == 2) rate_fs.close();\n\n set_usb_read_mode(16); \/\/turn off trigger, if on\n dump_data();\n \n cout << endl;\n cout << \"Data saved in file: \" << logDataFilename << endl << \"*****\" << endl;\n return 0;\n}\n\nbool fileExists(const string& filename)\n{\n struct stat buf;\n if (stat(filename.c_str(), &buf) != -1)\n {\n return true;\n }\n return false;\n}\n\nvoid SuMo::form_meta_data(int Address, int count, double cpuTime, time_t now)\n{\n int i = Address;\n adcDat[i]->Data[AC_CHANNELS][0] = count;\n adcDat[i]->Data[AC_CHANNELS][1] = Address;\n adcDat[i]->Data[AC_CHANNELS][2] = adcDat[i]->CC_EVENT_COUNT;\n adcDat[i]->Data[AC_CHANNELS][3] = adcDat[i]->CC_BIN_COUNT; \n adcDat[i]->Data[AC_CHANNELS][4] = adcDat[i]->timestamp_hi;\n adcDat[i]->Data[AC_CHANNELS][5] = adcDat[i]->timestamp_mid;\n adcDat[i]->Data[AC_CHANNELS][6] = adcDat[i]->timestamp_lo;\n \n adcDat[i]->Data[AC_CHANNELS][7] = adcDat[i]->CC_TIMESTAMP_HI;\n adcDat[i]->Data[AC_CHANNELS][8] = adcDat[i]->CC_TIMESTAMP_MID;\n adcDat[i]->Data[AC_CHANNELS][9] = adcDat[i]->CC_TIMESTAMP_LO;\n\n adcDat[i]->Data[AC_CHANNELS][10] = adcDat[i]->bin_count_rise;\n adcDat[i]->Data[AC_CHANNELS][11] = adcDat[i]->bin_count_fall;\n adcDat[i]->Data[AC_CHANNELS][12] = adcDat[i]->self_trig_settings; \n adcDat[i]->Data[AC_CHANNELS][13] = adcDat[i]->event_count;\n adcDat[i]->Data[AC_CHANNELS][14] = adcDat[i]->reg_self_trig[0];\n adcDat[i]->Data[AC_CHANNELS][15] = adcDat[i]->reg_self_trig[1]; \n adcDat[i]->Data[AC_CHANNELS][16] = adcDat[i]->reg_self_trig[2];\n adcDat[i]->Data[AC_CHANNELS][17] = adcDat[i]->reg_self_trig[3]; \n adcDat[i]->Data[AC_CHANNELS][18] = adcDat[i]->self_trig_mask; \n adcDat[i]->Data[AC_CHANNELS][19] = adcDat[i]->last_ac_instruct; \n adcDat[i]->Data[AC_CHANNELS][20] = adcDat[i]->last_last_ac_instruct;\n adcDat[i]->Data[AC_CHANNELS][21] = adcDat[i]->trig_en; \n adcDat[i]->Data[AC_CHANNELS][22] = adcDat[i]->trig_wait_for_sys; \n adcDat[i]->Data[AC_CHANNELS][23] = adcDat[i]->trig_rate_only; \n adcDat[i]->Data[AC_CHANNELS][24] = adcDat[i]->trig_sign; \n\n \/*fill slots 25-39 *\/\n for(int j=0; j<numChipsOnBoard; j++){\n adcDat[i]->Data[AC_CHANNELS][j+25] = adcDat[i]->ro_cnt[j]; \n adcDat[i]->Data[AC_CHANNELS][j+25+numChipsOnBoard] = adcDat[i]->vbias[j]; \n adcDat[i]->Data[AC_CHANNELS][j+25+2*numChipsOnBoard] = adcDat[i]->trigger_threshold[j]; \n }\n \/*fill slots 40-69 *\/\n for(int j=0; j<AC_CHANNELS; j++){\n adcDat[i]->Data[AC_CHANNELS][j+40] = adcDat[i]->self_trig_scalar[j];\n }\n adcDat[i]->Data[AC_CHANNELS][70] = cpuTime;\n adcDat[i]->Data[AC_CHANNELS][71] = now;\n adcDat[i]->Data[AC_CHANNELS][72] = WRAP_CONSTANT; \n\n}\n\n\n\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: usrpref.hxx,v $\n *\n * $Revision: 1.12 $\n *\n * last change: $Author: hr $ $Date: 2007-09-27 12:13:49 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n#ifndef _USRPREF_HXX\n#define _USRPREF_HXX\n\n\n\n#ifndef _UTL_CONFIGITEM_HXX_\n#include <unotools\/configitem.hxx>\n#endif\n#ifndef _FLDUPDE_HXX\n#include <fldupde.hxx>\n#endif\n#include \"viewopt.hxx\"\n\n#ifndef _VCL_FLDUNIT_HXX\n#include <vcl\/fldunit.hxx>\n#endif\n\n\/* -----------------------------28.09.00 09:45--------------------------------\n\n ---------------------------------------------------------------------------*\/\nclass SwMasterUsrPref;\nclass SwContentViewConfig : public utl::ConfigItem\n{\n SwMasterUsrPref& rParent;\n BOOL bWeb;\n\n com::sun::star::uno::Sequence<rtl::OUString> GetPropertyNames();\n public:\n SwContentViewConfig(BOOL bWeb, SwMasterUsrPref& rParent);\n ~SwContentViewConfig();\n\n \/\/ utl::ConfigItem\n virtual void Notify( const com::sun::star::uno::Sequence< rtl::OUString > &rPropertyNames );\n virtual void Commit();\n\n void Load();\n void SetModified(){ConfigItem::SetModified();}\n};\n\/* -----------------------------28.09.00 09:45--------------------------------\n\n ---------------------------------------------------------------------------*\/\nclass SwLayoutViewConfig : public utl::ConfigItem\n{\n SwMasterUsrPref& rParent;\n BOOL bWeb;\n\n com::sun::star::uno::Sequence<rtl::OUString> GetPropertyNames();\n public:\n SwLayoutViewConfig(BOOL bWeb, SwMasterUsrPref& rParent);\n ~SwLayoutViewConfig();\n\n virtual void Commit();\n void Load();\n void SetModified(){ConfigItem::SetModified();}\n};\n\/* -----------------------------19.01.01 13:06--------------------------------\n\n ---------------------------------------------------------------------------*\/\nclass SwGridConfig : public utl::ConfigItem\n{\n SwMasterUsrPref& rParent;\n BOOL bWeb;\n\n com::sun::star::uno::Sequence<rtl::OUString> GetPropertyNames();\n public:\n SwGridConfig(BOOL bWeb, SwMasterUsrPref& rParent);\n ~SwGridConfig();\n\n virtual void Commit();\n void Load();\n void SetModified(){ConfigItem::SetModified();}\n};\n\/* -----------------------------19.01.01 13:06--------------------------------\n\n ---------------------------------------------------------------------------*\/\nclass SwCursorConfig : public utl::ConfigItem\n{\n SwMasterUsrPref& rParent;\n\n com::sun::star::uno::Sequence<rtl::OUString> GetPropertyNames();\n public:\n SwCursorConfig(SwMasterUsrPref& rParent);\n ~SwCursorConfig();\n\n virtual void Commit();\n void Load();\n void SetModified(){ConfigItem::SetModified();}\n};\n\/* -----------------------------28.09.00 09:45--------------------------------\n\n ---------------------------------------------------------------------------*\/\nclass SwWebColorConfig : public utl::ConfigItem\n{\n SwMasterUsrPref& rParent;\n com::sun::star::uno::Sequence<rtl::OUString> aPropNames;\n\n public:\n SwWebColorConfig(SwMasterUsrPref& rParent);\n ~SwWebColorConfig();\n\n virtual void Commit();\n void Load();\n void SetModified(){ConfigItem::SetModified();}\n};\n\/* -----------------------------28.09.00 09:45--------------------------------\n\n ---------------------------------------------------------------------------*\/\nclass SwMasterUsrPref : public SwViewOption\n{\n friend class SwContentViewConfig;\n friend class SwLayoutViewConfig;\n friend class SwGridConfig;\n friend class SwCursorConfig;\n friend class SwWebColorConfig;\n\n SwContentViewConfig aContentConfig;\n SwLayoutViewConfig aLayoutConfig;\n SwGridConfig aGridConfig;\n SwCursorConfig aCursorConfig;\n SwWebColorConfig* pWebColorConfig;\n\n SwFldUpdateFlags eFldUpdateFlags; \/\/udpate of fields and charts\n sal_Int32 nLinkUpdateMode;\n FieldUnit eUserMetric;\n FieldUnit eHScrollMetric;\n sal_Bool bIsHScrollMetricSet;\n FieldUnit eVScrollMetric;\n sal_Bool bIsVScrollMetricSet;\n\n\n sal_Int32 nDefTab; \/\/default tab stop distance\n\npublic:\n SwMasterUsrPref(BOOL bWeb);\n ~SwMasterUsrPref();\n\n void SetUsrPref(const SwViewOption &rCopy);\n\n void Commit()\n {\n aContentConfig.Commit();\n aLayoutConfig.Commit();\n aGridConfig.Commit();\n aCursorConfig.Commit();\n if(pWebColorConfig)\n pWebColorConfig->Commit();\n }\n void SetModified()\n {\n aContentConfig.SetModified();\n aLayoutConfig.SetModified();\n aGridConfig.SetModified();\n aCursorConfig.SetModified();\n if(pWebColorConfig)\n pWebColorConfig->SetModified();\n }\n\n void SetUpdateLinkMode(sal_Int32 nSet, sal_Bool bNoModify = sal_False)\n {\n nLinkUpdateMode = nSet;\n if(!bNoModify)\n aContentConfig.SetModified();\n }\n sal_Int32 GetUpdateLinkMode() const {return nLinkUpdateMode; }\n\n void SetUpdateFields(BOOL bSet, sal_Bool bNoModify = sal_False)\n {\n if(bSet && eFldUpdateFlags == AUTOUPD_OFF)\n {\n eFldUpdateFlags = AUTOUPD_FIELD_ONLY;\n if(!bNoModify)\n aContentConfig.SetModified();\n }\n else if(!bSet)\n {\n eFldUpdateFlags = AUTOUPD_OFF;\n if(!bNoModify)\n aContentConfig.SetModified();\n }\n };\n sal_Bool IsUpdateFields()const {return eFldUpdateFlags != AUTOUPD_OFF; }\n\n SwFldUpdateFlags GetFldUpdateFlags()const {return eFldUpdateFlags;}\n void SetFldUpdateFlags(SwFldUpdateFlags eSet, sal_Bool bNoModify = sal_False)\n {\n eFldUpdateFlags = eSet;\n if(!bNoModify)\n aContentConfig.SetModified();\n }\n\n void SetUpdateCharts(BOOL bSet, sal_Bool bNoModify = sal_False)\n {\n if(bSet)\n {\n eFldUpdateFlags = AUTOUPD_FIELD_AND_CHARTS;\n if(!bNoModify)\n aContentConfig.SetModified();\n }\n else if(eFldUpdateFlags == AUTOUPD_FIELD_AND_CHARTS)\n {\n eFldUpdateFlags = AUTOUPD_FIELD_ONLY;\n if(!bNoModify)\n aContentConfig.SetModified();\n }\n };\n sal_Bool IsUpdateCharts()const {return eFldUpdateFlags == AUTOUPD_FIELD_AND_CHARTS; }\n\n FieldUnit GetMetric() const { return eUserMetric;}\n void SetMetric(FieldUnit eSet, sal_Bool bNoModify = sal_False)\n {\n eUserMetric = eSet;\n if(!bNoModify)\n aLayoutConfig.SetModified();\n }\n\n sal_Bool IsHScrollMetric()const {return bIsHScrollMetricSet;}\n FieldUnit GetHScrollMetric() const { return bIsHScrollMetricSet ? eHScrollMetric : eUserMetric;}\n void SetHScrollMetric(FieldUnit eSet, sal_Bool bNoModify = sal_False)\n {\n eHScrollMetric = eSet; bIsHScrollMetricSet = sal_True;\n if(!bNoModify)\n aLayoutConfig.SetModified();\n }\n\n sal_Bool IsVScrollMetric()const {return bIsVScrollMetricSet;}\n FieldUnit GetVScrollMetric() const { return bIsVScrollMetricSet ? eVScrollMetric : eUserMetric;}\n void SetVScrollMetric(FieldUnit eSet, sal_Bool bNoModify = sal_False)\n {\n eVScrollMetric = eSet; bIsVScrollMetricSet = sal_True;\n if(!bNoModify)\n aLayoutConfig.SetModified();\n }\n\n sal_Int32 GetDefTab() const { return nDefTab;}\n void SetDefTab( sal_Int32 nSet, sal_Bool bNoModify = sal_False )\n {\n nDefTab = nSet;\n if(!bNoModify)\n aLayoutConfig.SetModified();\n }\n\n};\n\n#endif\n\n<commit_msg>INTEGRATION: CWS os103 (1.11.116); FILE MERGED 2007\/10\/01 07:04:54 os 1.11.116.2: RESYNC: (1.11-1.12); FILE MERGED 2007\/09\/05 12:22:31 os 1.11.116.1: #81258# SwMasterUsrPref members reordered<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: usrpref.hxx,v $\n *\n * $Revision: 1.13 $\n *\n * last change: $Author: rt $ $Date: 2007-11-06 16:26:43 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n#ifndef _USRPREF_HXX\n#define _USRPREF_HXX\n\n\n\n#ifndef _UTL_CONFIGITEM_HXX_\n#include <unotools\/configitem.hxx>\n#endif\n#ifndef _FLDUPDE_HXX\n#include <fldupde.hxx>\n#endif\n#include \"viewopt.hxx\"\n\n#ifndef _VCL_FLDUNIT_HXX\n#include <vcl\/fldunit.hxx>\n#endif\n\n\/* -----------------------------28.09.00 09:45--------------------------------\n\n ---------------------------------------------------------------------------*\/\nclass SwMasterUsrPref;\nclass SwContentViewConfig : public utl::ConfigItem\n{\n SwMasterUsrPref& rParent;\n BOOL bWeb;\n\n com::sun::star::uno::Sequence<rtl::OUString> GetPropertyNames();\n public:\n SwContentViewConfig(BOOL bWeb, SwMasterUsrPref& rParent);\n ~SwContentViewConfig();\n\n \/\/ utl::ConfigItem\n virtual void Notify( const com::sun::star::uno::Sequence< rtl::OUString > &rPropertyNames );\n virtual void Commit();\n\n void Load();\n void SetModified(){ConfigItem::SetModified();}\n};\n\/* -----------------------------28.09.00 09:45--------------------------------\n\n ---------------------------------------------------------------------------*\/\nclass SwLayoutViewConfig : public utl::ConfigItem\n{\n SwMasterUsrPref& rParent;\n BOOL bWeb;\n\n com::sun::star::uno::Sequence<rtl::OUString> GetPropertyNames();\n public:\n SwLayoutViewConfig(BOOL bWeb, SwMasterUsrPref& rParent);\n ~SwLayoutViewConfig();\n\n virtual void Commit();\n void Load();\n void SetModified(){ConfigItem::SetModified();}\n};\n\/* -----------------------------19.01.01 13:06--------------------------------\n\n ---------------------------------------------------------------------------*\/\nclass SwGridConfig : public utl::ConfigItem\n{\n SwMasterUsrPref& rParent;\n BOOL bWeb;\n\n com::sun::star::uno::Sequence<rtl::OUString> GetPropertyNames();\n public:\n SwGridConfig(BOOL bWeb, SwMasterUsrPref& rParent);\n ~SwGridConfig();\n\n virtual void Commit();\n void Load();\n void SetModified(){ConfigItem::SetModified();}\n};\n\/* -----------------------------19.01.01 13:06--------------------------------\n\n ---------------------------------------------------------------------------*\/\nclass SwCursorConfig : public utl::ConfigItem\n{\n SwMasterUsrPref& rParent;\n\n com::sun::star::uno::Sequence<rtl::OUString> GetPropertyNames();\n public:\n SwCursorConfig(SwMasterUsrPref& rParent);\n ~SwCursorConfig();\n\n virtual void Commit();\n void Load();\n void SetModified(){ConfigItem::SetModified();}\n};\n\/* -----------------------------28.09.00 09:45--------------------------------\n\n ---------------------------------------------------------------------------*\/\nclass SwWebColorConfig : public utl::ConfigItem\n{\n SwMasterUsrPref& rParent;\n com::sun::star::uno::Sequence<rtl::OUString> aPropNames;\n\n public:\n SwWebColorConfig(SwMasterUsrPref& rParent);\n ~SwWebColorConfig();\n\n virtual void Commit();\n void Load();\n void SetModified(){ConfigItem::SetModified();}\n};\n\/* -----------------------------28.09.00 09:45--------------------------------\n\n ---------------------------------------------------------------------------*\/\nclass SwMasterUsrPref : public SwViewOption\n{\n friend class SwContentViewConfig;\n friend class SwLayoutViewConfig;\n friend class SwGridConfig;\n friend class SwCursorConfig;\n friend class SwWebColorConfig;\n\n SwFldUpdateFlags eFldUpdateFlags; \/\/udpate of fields and charts\n sal_Int32 nLinkUpdateMode;\n FieldUnit eUserMetric;\n FieldUnit eHScrollMetric;\n sal_Bool bIsHScrollMetricSet;\n FieldUnit eVScrollMetric;\n sal_Bool bIsVScrollMetricSet;\n\n sal_Int32 nDefTab; \/\/default tab stop distance\n\n SwContentViewConfig aContentConfig;\n SwLayoutViewConfig aLayoutConfig;\n SwGridConfig aGridConfig;\n SwCursorConfig aCursorConfig;\n SwWebColorConfig* pWebColorConfig;\n\npublic:\n SwMasterUsrPref(BOOL bWeb);\n ~SwMasterUsrPref();\n\n void SetUsrPref(const SwViewOption &rCopy);\n\n void Commit()\n {\n aContentConfig.Commit();\n aLayoutConfig.Commit();\n aGridConfig.Commit();\n aCursorConfig.Commit();\n if(pWebColorConfig)\n pWebColorConfig->Commit();\n }\n void SetModified()\n {\n aContentConfig.SetModified();\n aLayoutConfig.SetModified();\n aGridConfig.SetModified();\n aCursorConfig.SetModified();\n if(pWebColorConfig)\n pWebColorConfig->SetModified();\n }\n\n void SetUpdateLinkMode(sal_Int32 nSet, sal_Bool bNoModify = sal_False)\n {\n nLinkUpdateMode = nSet;\n if(!bNoModify)\n aContentConfig.SetModified();\n }\n sal_Int32 GetUpdateLinkMode() const {return nLinkUpdateMode; }\n\n void SetUpdateFields(BOOL bSet, sal_Bool bNoModify = sal_False)\n {\n if(bSet && eFldUpdateFlags == AUTOUPD_OFF)\n {\n eFldUpdateFlags = AUTOUPD_FIELD_ONLY;\n if(!bNoModify)\n aContentConfig.SetModified();\n }\n else if(!bSet)\n {\n eFldUpdateFlags = AUTOUPD_OFF;\n if(!bNoModify)\n aContentConfig.SetModified();\n }\n };\n sal_Bool IsUpdateFields()const {return eFldUpdateFlags != AUTOUPD_OFF; }\n\n SwFldUpdateFlags GetFldUpdateFlags()const {return eFldUpdateFlags;}\n void SetFldUpdateFlags(SwFldUpdateFlags eSet, sal_Bool bNoModify = sal_False)\n {\n eFldUpdateFlags = eSet;\n if(!bNoModify)\n aContentConfig.SetModified();\n }\n\n void SetUpdateCharts(BOOL bSet, sal_Bool bNoModify = sal_False)\n {\n if(bSet)\n {\n eFldUpdateFlags = AUTOUPD_FIELD_AND_CHARTS;\n if(!bNoModify)\n aContentConfig.SetModified();\n }\n else if(eFldUpdateFlags == AUTOUPD_FIELD_AND_CHARTS)\n {\n eFldUpdateFlags = AUTOUPD_FIELD_ONLY;\n if(!bNoModify)\n aContentConfig.SetModified();\n }\n };\n sal_Bool IsUpdateCharts()const {return eFldUpdateFlags == AUTOUPD_FIELD_AND_CHARTS; }\n\n FieldUnit GetMetric() const { return eUserMetric;}\n void SetMetric(FieldUnit eSet, sal_Bool bNoModify = sal_False)\n {\n eUserMetric = eSet;\n if(!bNoModify)\n aLayoutConfig.SetModified();\n }\n\n sal_Bool IsHScrollMetric()const {return bIsHScrollMetricSet;}\n FieldUnit GetHScrollMetric() const { return bIsHScrollMetricSet ? eHScrollMetric : eUserMetric;}\n void SetHScrollMetric(FieldUnit eSet, sal_Bool bNoModify = sal_False)\n {\n eHScrollMetric = eSet; bIsHScrollMetricSet = sal_True;\n if(!bNoModify)\n aLayoutConfig.SetModified();\n }\n\n sal_Bool IsVScrollMetric()const {return bIsVScrollMetricSet;}\n FieldUnit GetVScrollMetric() const { return bIsVScrollMetricSet ? eVScrollMetric : eUserMetric;}\n void SetVScrollMetric(FieldUnit eSet, sal_Bool bNoModify = sal_False)\n {\n eVScrollMetric = eSet; bIsVScrollMetricSet = sal_True;\n if(!bNoModify)\n aLayoutConfig.SetModified();\n }\n\n sal_Int32 GetDefTab() const { return nDefTab;}\n void SetDefTab( sal_Int32 nSet, sal_Bool bNoModify = sal_False )\n {\n nDefTab = nSet;\n if(!bNoModify)\n aLayoutConfig.SetModified();\n }\n\n};\n\n#endif\n\n<|endoftext|>"} {"text":"<commit_before>#include \"core.h\"\n\nconst uint8_t PROGMEM lcdBootProgram[] = {\n 0xAE, \/\/ Display Off\n 0XD5, \/\/ Set Display Clock Divisor v\n 0xF0, \/\/ 0x80 is default\n 0xA8, \/\/ Set Multiplex Ratio v\n 0x3F,\n 0xD3, \/\/ Set Display Offset v\n 0x00,\n 0x40, \/\/ Set Start Line (0)\n 0x8D, \/\/ Charge Pump Setting v\n 0x14, \/\/ Enable\n \/\/ running this next pair twice?\n 0x20, \/\/ Set Memory Mode v\n 0x00, \/\/ Horizontal Addressing\n 0xA1, \/\/ Set Segment Re-map (A0) | (b0001)\n 0xC8, \/\/ Set COM Output Scan Direction\n 0xDA, \/\/ Set COM Pins v\n 0x12,\n 0x81, \/\/ Set Contrast v\n 0xCF,\n 0xD9, \/\/ Set Precharge\n 0xF1,\n 0xDB, \/\/ Set VCom Detect\n 0x40,\n 0xA4, \/\/ Entire Display ON\n 0xA6, \/\/ Set normal\/inverse display\n 0xAF, \/\/ Display On\n\n 0x20, \/\/ set display mode\n 0x00, \/\/ horizontal addressing mode\n\n 0x21, \/\/ set col address\n 0x00,\n COLUMN_ADDRESS_END,\n\n 0x22, \/\/ set page address\n 0x00,\n PAGE_ADDRESS_END\n};\n\n\nArduboyCore::ArduboyCore() {}\n\n\/\/ meant to be overridden by subclasses\nvoid ArduboyCore::setup()\n{\n boot();\n}\n\nvoid ArduboyCore::boot()\n{\n #if F_CPU == 8000000L\n slowCPU();\n #endif\n\n SPI.begin();\n bootPins();\n bootLCD();\n\n #ifdef SAFE_MODE\n if (getInput() == (LEFT_BUTTON | UP_BUTTON))\n safeMode();\n #endif\n\n saveMuchPower();\n}\n\n#if F_CPU == 8000000L\n\/\/ if we're compiling for 8Mhz we need to slow the CPU down because the\n\/\/ hardware clock on the Arduboy is 16MHz\nvoid ArduboyCore::slowCPU()\n{\n uint8_t oldSREG = SREG;\n cli(); \/\/ suspend interrupts\n CLKPR = _BV(CLKPCE); \/\/ allow reprogramming clock\n CLKPR = 1; \/\/ set clock divisor to 2 (0b0001)\n SREG = oldSREG; \/\/ restore interrupts\n}\n#endif\n\nvoid ArduboyCore::bootPins()\n{\n \/\/ OLED SPI\n pinMode(DC, OUTPUT);\n pinMode(CS, OUTPUT);\n pinMode(RST, OUTPUT);\n digitalWrite(RST, HIGH);\n delay(1); \/\/ VDD (3.3V) goes high at start, lets just chill for a ms\n digitalWrite(RST, LOW); \/\/ bring reset low\n delay(10); \/\/ wait 10ms\n digitalWrite(RST, HIGH); \/\/ bring out of reset\n\n \/\/ Buttons\n pinMode(PIN_LEFT_BUTTON, INPUT_PULLUP);\n pinMode(PIN_RIGHT_BUTTON, INPUT_PULLUP);\n pinMode(PIN_UP_BUTTON, INPUT_PULLUP);\n pinMode(PIN_DOWN_BUTTON, INPUT_PULLUP);\n pinMode(PIN_A_BUTTON, INPUT_PULLUP);\n pinMode(PIN_B_BUTTON, INPUT_PULLUP);\n\n}\n\nvoid ArduboyCore::bootLCD()\n{\n \/\/ setup the ports we need to talk to the OLED\n csport = portOutputRegister(digitalPinToPort(CS));\n cspinmask = digitalPinToBitMask(CS);\n dcport = portOutputRegister(digitalPinToPort(DC));\n dcpinmask = digitalPinToBitMask(DC);\n\n LCDCommandMode();\n for (int8_t i=0; i < sizeof(lcdBootProgram); i++) {\n SPI.transfer(pgm_read_byte(lcdBootProgram + i));\n }\n LCDDataMode();\n}\n\nvoid ArduboyCore::LCDDataMode()\n{\n *dcport |= dcpinmask;\n *csport &= ~cspinmask;\n}\n\nvoid ArduboyCore::LCDCommandMode()\n{\n *csport |= cspinmask; \/\/ why are we doing this twice?\n *csport |= cspinmask;\n *dcport &= ~dcpinmask;\n *csport &= ~cspinmask;\n}\n\n\n\n\/\/ Safe Mode is engaged by holding down both the LEFT button and UP button\n\/\/ when plugging the device into USB. It puts your device into a tight\n\/\/ loop and allows it to be reprogrammed even if you have uploaded a very\n\/\/ broken sketch that interferes with the normal USB triggered auto-reboot\n\/\/ functionality of the device.\nvoid ArduboyCore::safeMode()\n{\n blank(); \/\/ too avoid random gibberish\n while (true) {\n asm volatile(\"nop \\n\");\n }\n}\n\n\n\/* Power Management *\/\n\nvoid ArduboyCore::idle()\n{\n set_sleep_mode(SLEEP_MODE_IDLE);\n sleep_mode();\n}\n\nvoid ArduboyCore::saveMuchPower()\n{\n power_adc_disable();\n power_usart0_disable();\n power_twi_disable();\n \/\/ timer 0 is for millis()\n \/\/ timers 1 and 3 are for music and sounds\n power_timer2_disable();\n power_usart1_disable();\n \/\/ we need USB, for now (to allow triggered reboots to reprogram)\n \/\/ power_usb_disable()\n}\n\nuint8_t ArduboyCore::width() { return WIDTH; }\n\nuint8_t ArduboyCore::height() { return HEIGHT; }\n\n\n\/* Drawing *\/\n\nvoid ArduboyCore::paint8Pixels(uint8_t pixels)\n{\n SPI.transfer(pixels);\n}\n\nvoid ArduboyCore::paintScreen(const unsigned char *image)\n{\n for (int i = 0; i < (HEIGHT*WIDTH)\/8; i++)\n {\n SPI.transfer(pgm_read_byte(image + i));\n }\n}\n\nvoid ArduboyCore::paintScreen(unsigned char image[])\n{\n for (int i = 0; i < (HEIGHT*WIDTH)\/8; i++)\n {\n SPI.transfer(image[i]);\n }\n}\n\nvoid ArduboyCore::blank()\n{\n for (int i = 0; i < (HEIGHT*WIDTH)\/8; i++)\n SPI.transfer(0x00);\n}\n\n\n\/* Buttons *\/\n\nuint8_t ArduboyCore::getInput()\n{\n \/\/ using ports here is ~100 bytes smaller than digitalRead()\n #ifdef DEVKIT\n \/\/ down, left, up\n uint8_t buttons = ((~PINB) & B01110000);\n \/\/ right button\n buttons = buttons | (((~PINC) & B01000000) >> 4);\n \/\/ A and B\n buttons = buttons | (((~PINF) & B11000000) >> 6);\n #endif\n\n \/\/ b0dlu0rab - see button defines in Arduboy.h\n return buttons;\n}\n<commit_msg>hand optimized paintScreen from memory buffer<commit_after>#include \"core.h\"\n\nconst uint8_t PROGMEM lcdBootProgram[] = {\n 0xAE, \/\/ Display Off\n 0XD5, \/\/ Set Display Clock Divisor v\n 0xF0, \/\/ 0x80 is default\n 0xA8, \/\/ Set Multiplex Ratio v\n 0x3F,\n 0xD3, \/\/ Set Display Offset v\n 0x00,\n 0x40, \/\/ Set Start Line (0)\n 0x8D, \/\/ Charge Pump Setting v\n 0x14, \/\/ Enable\n \/\/ running this next pair twice?\n 0x20, \/\/ Set Memory Mode v\n 0x00, \/\/ Horizontal Addressing\n 0xA1, \/\/ Set Segment Re-map (A0) | (b0001)\n 0xC8, \/\/ Set COM Output Scan Direction\n 0xDA, \/\/ Set COM Pins v\n 0x12,\n 0x81, \/\/ Set Contrast v\n 0xCF,\n 0xD9, \/\/ Set Precharge\n 0xF1,\n 0xDB, \/\/ Set VCom Detect\n 0x40,\n 0xA4, \/\/ Entire Display ON\n 0xA6, \/\/ Set normal\/inverse display\n 0xAF, \/\/ Display On\n\n 0x20, \/\/ set display mode\n 0x00, \/\/ horizontal addressing mode\n\n 0x21, \/\/ set col address\n 0x00,\n COLUMN_ADDRESS_END,\n\n 0x22, \/\/ set page address\n 0x00,\n PAGE_ADDRESS_END\n};\n\n\nArduboyCore::ArduboyCore() {}\n\n\/\/ meant to be overridden by subclasses\nvoid ArduboyCore::setup()\n{\n boot();\n}\n\nvoid ArduboyCore::boot()\n{\n #if F_CPU == 8000000L\n slowCPU();\n #endif\n\n SPI.begin();\n bootPins();\n bootLCD();\n\n #ifdef SAFE_MODE\n if (getInput() == (LEFT_BUTTON | UP_BUTTON))\n safeMode();\n #endif\n\n saveMuchPower();\n}\n\n#if F_CPU == 8000000L\n\/\/ if we're compiling for 8Mhz we need to slow the CPU down because the\n\/\/ hardware clock on the Arduboy is 16MHz\nvoid ArduboyCore::slowCPU()\n{\n uint8_t oldSREG = SREG;\n cli(); \/\/ suspend interrupts\n CLKPR = _BV(CLKPCE); \/\/ allow reprogramming clock\n CLKPR = 1; \/\/ set clock divisor to 2 (0b0001)\n SREG = oldSREG; \/\/ restore interrupts\n}\n#endif\n\nvoid ArduboyCore::bootPins()\n{\n \/\/ OLED SPI\n pinMode(DC, OUTPUT);\n pinMode(CS, OUTPUT);\n pinMode(RST, OUTPUT);\n digitalWrite(RST, HIGH);\n delay(1); \/\/ VDD (3.3V) goes high at start, lets just chill for a ms\n digitalWrite(RST, LOW); \/\/ bring reset low\n delay(10); \/\/ wait 10ms\n digitalWrite(RST, HIGH); \/\/ bring out of reset\n\n \/\/ Buttons\n pinMode(PIN_LEFT_BUTTON, INPUT_PULLUP);\n pinMode(PIN_RIGHT_BUTTON, INPUT_PULLUP);\n pinMode(PIN_UP_BUTTON, INPUT_PULLUP);\n pinMode(PIN_DOWN_BUTTON, INPUT_PULLUP);\n pinMode(PIN_A_BUTTON, INPUT_PULLUP);\n pinMode(PIN_B_BUTTON, INPUT_PULLUP);\n\n}\n\nvoid ArduboyCore::bootLCD()\n{\n \/\/ setup the ports we need to talk to the OLED\n csport = portOutputRegister(digitalPinToPort(CS));\n cspinmask = digitalPinToBitMask(CS);\n dcport = portOutputRegister(digitalPinToPort(DC));\n dcpinmask = digitalPinToBitMask(DC);\n\n LCDCommandMode();\n for (int8_t i=0; i < sizeof(lcdBootProgram); i++) {\n SPI.transfer(pgm_read_byte(lcdBootProgram + i));\n }\n LCDDataMode();\n}\n\nvoid ArduboyCore::LCDDataMode()\n{\n *dcport |= dcpinmask;\n *csport &= ~cspinmask;\n}\n\nvoid ArduboyCore::LCDCommandMode()\n{\n *csport |= cspinmask; \/\/ why are we doing this twice?\n *csport |= cspinmask;\n *dcport &= ~dcpinmask;\n *csport &= ~cspinmask;\n}\n\n\n\n\/\/ Safe Mode is engaged by holding down both the LEFT button and UP button\n\/\/ when plugging the device into USB. It puts your device into a tight\n\/\/ loop and allows it to be reprogrammed even if you have uploaded a very\n\/\/ broken sketch that interferes with the normal USB triggered auto-reboot\n\/\/ functionality of the device.\nvoid ArduboyCore::safeMode()\n{\n blank(); \/\/ too avoid random gibberish\n while (true) {\n asm volatile(\"nop \\n\");\n }\n}\n\n\n\/* Power Management *\/\n\nvoid ArduboyCore::idle()\n{\n set_sleep_mode(SLEEP_MODE_IDLE);\n sleep_mode();\n}\n\nvoid ArduboyCore::saveMuchPower()\n{\n power_adc_disable();\n power_usart0_disable();\n power_twi_disable();\n \/\/ timer 0 is for millis()\n \/\/ timers 1 and 3 are for music and sounds\n power_timer2_disable();\n power_usart1_disable();\n \/\/ we need USB, for now (to allow triggered reboots to reprogram)\n \/\/ power_usb_disable()\n}\n\nuint8_t ArduboyCore::width() { return WIDTH; }\n\nuint8_t ArduboyCore::height() { return HEIGHT; }\n\n\n\/* Drawing *\/\n\nvoid ArduboyCore::paint8Pixels(uint8_t pixels)\n{\n SPI.transfer(pixels);\n}\n\nvoid ArduboyCore::paintScreen(const unsigned char *image)\n{\n for (int i = 0; i < (HEIGHT*WIDTH)\/8; i++)\n {\n SPI.transfer(pgm_read_byte(image + i));\n }\n}\n\n\/\/ paint from a memory buffer, this should be FAST as it's likely what\n\/\/ will be used by any buffer based subclass\nvoid ArduboyCore::paintScreen(unsigned char image[])\n{\n for (int i = 0; i < (HEIGHT*WIDTH)\/8; i++)\n {\n \/\/ SPI.transfer(image[i]);\n\n \/\/ we need to burn 18 cycles between sets of SPDR\n \/\/ 4 clock cycles\n SPDR = image[i];\n \/\/ 7 clock cycles\n asm volatile(\n \"mul __zero_reg__, __zero_reg__ \\n\" \/\/ 2 cycles\n \"mul __zero_reg__, __zero_reg__ \\n\" \/\/ 2 cycles\n \"mul __zero_reg__, __zero_reg__ \\n\" \/\/ 2 cycles\n );\n }\n}\n\nvoid ArduboyCore::blank()\n{\n for (int i = 0; i < (HEIGHT*WIDTH)\/8; i++)\n SPI.transfer(0x00);\n}\n\n\n\/* Buttons *\/\n\nuint8_t ArduboyCore::getInput()\n{\n \/\/ using ports here is ~100 bytes smaller than digitalRead()\n #ifdef DEVKIT\n \/\/ down, left, up\n uint8_t buttons = ((~PINB) & B01110000);\n \/\/ right button\n buttons = buttons | (((~PINC) & B01000000) >> 4);\n \/\/ A and B\n buttons = buttons | (((~PINF) & B11000000) >> 6);\n #endif\n\n \/\/ b0dlu0rab - see button defines in Arduboy.h\n return buttons;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/\/\n\/\/\/ @file\n\/\/\/ @copyright Copyright (C) 2017-2018, Jonathan Bryan Schmalhofer\n\/\/\/\n\/\/\/ @brief AirSimToRos Implementation\n\/\/\/\n\n#include \"js_airsim_to_ros_library\/airsim_to_ros_class.h\"\n\nnamespace js_airsim_to_ros_library\n{\n\nAirSimToRosClass::AirSimToRosClass(std::string const& addr)\n : zmq_context_(1)\n , zmq_subscriber_(zmq_context_, ZMQ_SUB)\n{\n zmq_subscriber_.setsockopt(ZMQ_IDENTITY, \"AirSimToRosSubscriber\", 5);\n zmq_subscriber_.setsockopt(ZMQ_SUBSCRIBE, \"\", 0);\n zmq_subscriber_.setsockopt(ZMQ_RCVTIMEO, 5000);\n zmq_subscriber_.connect(addr);\n \n \/\/ Header\n header_seq_ = 0;\n header_stamp_sec_ = 0;\n header_stamp_nsec_ = 0;\n header_frame_id_ = \"\";\n \/\/ Left\n left_height_ = 0;\n left_width_ = 0;\n left_encoding_ = \"\";\n left_is_bigendian_ = 0;\n left_step_ = 0;\n left_data_ = NULL;\n left_data_size_ = 0;\n \/\/ Right\n right_height_ = 0;\n right_width_ = 0;\n right_encoding_ = \"\";\n right_is_bigendian_ = 0;\n right_step_ = 0;\n right_data_ = NULL;\n right_data_size_ = 0;\n \n \/\/ Pose.position\n pose_position_x_ = 0;\n pose_position_y_ = 0;\n pose_position_z_ = 0;\n \/\/ Pose.orientation\n pose_orientation_roll_ = 0;\n pose_orientation_pitch_ = 0;\n pose_orientation_yaw_ = 0;\n}\n\nvoid AirSimToRosClass::Connect(std::string const& addr)\n{\n\tzmq_subscriber_.connect(addr);\n}\n \nAirSimToRosClass::~AirSimToRosClass()\n{\n free(left_data_);\n free(right_data_);\n}\n\nint8_t AirSimToRosClass::ReceivedMessage()\n{\n zmq::message_t zmq_received_message;\n zmq_subscriber_.recv(&zmq_received_message);\n\n flatbuffers::FlatBufferBuilder fbb;\n airsim_to_ros::StereoImagePoseBuilder builder(fbb);\n\n \/\/ Verify the message contents are trustworthy.\n flatbuffers::Verifier verifier((const unsigned char *)zmq_received_message.data(),\n zmq_received_message.size());\n int8_t return_value = 0;\n\n\n if (zmq_received_message.size() > 0)\n {\n \/\/ Make sure the message has valid data.\n if (airsim_to_ros::VerifyStereoImagePoseBuffer(verifier))\n {\n auto flatbuffer_rcvd = airsim_to_ros::GetStereoImagePose(zmq_received_message.data());\n\n \/\/ Header\n header_seq_ = flatbuffer_rcvd->header()->seq();\n header_stamp_sec_ = flatbuffer_rcvd->header()->stamp()->sec();\n header_stamp_nsec_ = flatbuffer_rcvd->header()->stamp()->nsec();\n header_frame_id_ = flatbuffer_rcvd->header()->frame_id()->c_str();\n \/\/ Left\n left_height_ = flatbuffer_rcvd->left()->height();\n left_width_ = flatbuffer_rcvd->left()->width();\n left_encoding_ = flatbuffer_rcvd->left()->encoding()->c_str();\n left_is_bigendian_ = flatbuffer_rcvd->left()->is_bigendian();\n left_step_ = flatbuffer_rcvd->left()->step();\n left_data_ = (std::uint8_t*)realloc(left_data_, left_step_ * left_height_);\/\/zmq_received_message.size());\n left_data_size_ = left_step_ * left_height_;\n memcpy(left_data_, flatbuffer_rcvd->left()->data(), left_data_size_);\n \/\/ Right\n right_height_ = flatbuffer_rcvd->right()->height();\n right_width_ = flatbuffer_rcvd->right()->width();\n right_encoding_ = flatbuffer_rcvd->right()->encoding()->c_str();\n right_is_bigendian_ = flatbuffer_rcvd->right()->is_bigendian();\n right_step_ = flatbuffer_rcvd->right()->step();\n right_data_ = (std::uint8_t*)realloc(right_data_, right_step_ * right_height_);\/\/zmq_received_message.size());\n right_data_size_ = right_step_ * right_height_;\n memcpy(right_data_, flatbuffer_rcvd->right()->data(), right_data_size_);\n \n \/\/ position\n pose_position_x_ = flatbuffer_rcvd->pose()->position()->x();\n pose_position_y_ = flatbuffer_rcvd->pose()->position()->y();\n pose_position_z_ = flatbuffer_rcvd->pose()->position()->z();\n \/\/ orientation\n pose_orientation_roll_ = flatbuffer_rcvd->pose()->orientation()->roll();\n pose_orientation_pitch_ = flatbuffer_rcvd->pose()->orientation()->pitch();\n pose_orientation_yaw_ = flatbuffer_rcvd->pose()->orientation()->yaw();\n return_value = 1;\n }\n else\n {\n return_value = -1;\n }\n }\n\n return return_value;\n}\n \nuint32_t AirSimToRosClass::GetHeaderSeq()\n{\n return header_seq_;\n}\n \nuint32_t AirSimToRosClass::GetHeaderStampSec()\n{\n return header_stamp_sec_;\n}\n\nuint32_t AirSimToRosClass::GetHeaderStampNsec()\n{\n return header_stamp_nsec_;\n}\n\nstd::string AirSimToRosClass::GetHeaderFrameid()\n{\n return header_frame_id_;\n}\n\nuint32_t AirSimToRosClass::GetLeftHeight()\n{\n return left_height_;\n}\n\nuint32_t AirSimToRosClass::GetLeftWidth()\n{\n return left_width_;\n}\n\nstd::string AirSimToRosClass::GetLeftEncoding()\n{\n return left_encoding_;\n}\n\nuint8_t AirSimToRosClass::GetLeftIsBigendian()\n{\n return left_is_bigendian_;\n}\n\nuint32_t AirSimToRosClass::GetLeftStep()\n{\n return left_step_;\n}\n\nstd::uint8_t* AirSimToRosClass::GetLeftData()\n{\n return left_data_;\n}\n \nsize_t AirSimToRosClass::GetLeftDataSize()\n{\n return left_data_size_;\n}\n\nuint32_t AirSimToRosClass::GetRightHeight()\n{\n return right_height_;\n}\n\nuint32_t AirSimToRosClass::GetRightWidth()\n{\n return right_width_;\n}\n\nstd::string AirSimToRosClass::GetRightEncoding()\n{\n return right_encoding_;\n}\n\nuint8_t AirSimToRosClass::GetRightIsBigendian()\n{\n return right_is_bigendian_;\n}\n\nuint32_t AirSimToRosClass::GetRightStep()\n{\n return right_step_;\n}\n\nstd::uint8_t* AirSimToRosClass::GetRightData()\n{\n return right_data_;\n}\n \nsize_t AirSimToRosClass::GetRightDataSize()\n{\n return right_data_size_;\n}\n\ndouble AirSimToRosClass::GetPosePositionX()\n{\n return pose_position_x_;\n}\n\ndouble AirSimToRosClass::GetPosePositionY()\n{\n return pose_position_y_;\n}\n\ndouble AirSimToRosClass::GetPosePositionZ()\n{\n return pose_position_z_;\n}\n\ndouble AirSimToRosClass::GetPoseOrientationRoll()\n{\n return pose_orientation_roll_;\n}\n\ndouble AirSimToRosClass::GetPoseOrientationPitch()\n{\n return pose_orientation_pitch_;\n}\n\ndouble AirSimToRosClass::GetPoseOrientationYaw()\n{\n return pose_orientation_yaw_;\n}\n} \/\/ namespace js_airsim_to_ros_library\n\n<commit_msg>removed those behated tabs<commit_after>\/\/\/\n\/\/\/ @file\n\/\/\/ @copyright Copyright (C) 2017-2018, Jonathan Bryan Schmalhofer\n\/\/\/\n\/\/\/ @brief AirSimToRos Implementation\n\/\/\/\n\n#include \"js_airsim_to_ros_library\/airsim_to_ros_class.h\"\n\nnamespace js_airsim_to_ros_library\n{\n\nAirSimToRosClass::AirSimToRosClass(std::string const& addr)\n : zmq_context_(1)\n , zmq_subscriber_(zmq_context_, ZMQ_SUB)\n{\n zmq_subscriber_.setsockopt(ZMQ_IDENTITY, \"AirSimToRosSubscriber\", 5);\n zmq_subscriber_.setsockopt(ZMQ_SUBSCRIBE, \"\", 0);\n zmq_subscriber_.setsockopt(ZMQ_RCVTIMEO, 5000);\n zmq_subscriber_.connect(addr);\n \n \/\/ Header\n header_seq_ = 0;\n header_stamp_sec_ = 0;\n header_stamp_nsec_ = 0;\n header_frame_id_ = \"\";\n \/\/ Left\n left_height_ = 0;\n left_width_ = 0;\n left_encoding_ = \"\";\n left_is_bigendian_ = 0;\n left_step_ = 0;\n left_data_ = NULL;\n left_data_size_ = 0;\n \/\/ Right\n right_height_ = 0;\n right_width_ = 0;\n right_encoding_ = \"\";\n right_is_bigendian_ = 0;\n right_step_ = 0;\n right_data_ = NULL;\n right_data_size_ = 0;\n \n \/\/ Pose.position\n pose_position_x_ = 0;\n pose_position_y_ = 0;\n pose_position_z_ = 0;\n \/\/ Pose.orientation\n pose_orientation_roll_ = 0;\n pose_orientation_pitch_ = 0;\n pose_orientation_yaw_ = 0;\n}\n\nvoid AirSimToRosClass::Connect(std::string const& addr)\n{\n zmq_subscriber_.connect(addr);\n}\n \nAirSimToRosClass::~AirSimToRosClass()\n{\n free(left_data_);\n free(right_data_);\n}\n\nint8_t AirSimToRosClass::ReceivedMessage()\n{\n zmq::message_t zmq_received_message;\n zmq_subscriber_.recv(&zmq_received_message);\n\n flatbuffers::FlatBufferBuilder fbb;\n airsim_to_ros::StereoImagePoseBuilder builder(fbb);\n\n \/\/ Verify the message contents are trustworthy.\n flatbuffers::Verifier verifier((const unsigned char *)zmq_received_message.data(),\n zmq_received_message.size());\n int8_t return_value = 0;\n\n\n if (zmq_received_message.size() > 0)\n {\n \/\/ Make sure the message has valid data.\n if (airsim_to_ros::VerifyStereoImagePoseBuffer(verifier))\n {\n auto flatbuffer_rcvd = airsim_to_ros::GetStereoImagePose(zmq_received_message.data());\n\n \/\/ Header\n header_seq_ = flatbuffer_rcvd->header()->seq();\n header_stamp_sec_ = flatbuffer_rcvd->header()->stamp()->sec();\n header_stamp_nsec_ = flatbuffer_rcvd->header()->stamp()->nsec();\n header_frame_id_ = flatbuffer_rcvd->header()->frame_id()->c_str();\n \/\/ Left\n left_height_ = flatbuffer_rcvd->left()->height();\n left_width_ = flatbuffer_rcvd->left()->width();\n left_encoding_ = flatbuffer_rcvd->left()->encoding()->c_str();\n left_is_bigendian_ = flatbuffer_rcvd->left()->is_bigendian();\n left_step_ = flatbuffer_rcvd->left()->step();\n left_data_ = (std::uint8_t*)realloc(left_data_, left_step_ * left_height_);\/\/zmq_received_message.size());\n left_data_size_ = left_step_ * left_height_;\n memcpy(left_data_, flatbuffer_rcvd->left()->data(), left_data_size_);\n \/\/ Right\n right_height_ = flatbuffer_rcvd->right()->height();\n right_width_ = flatbuffer_rcvd->right()->width();\n right_encoding_ = flatbuffer_rcvd->right()->encoding()->c_str();\n right_is_bigendian_ = flatbuffer_rcvd->right()->is_bigendian();\n right_step_ = flatbuffer_rcvd->right()->step();\n right_data_ = (std::uint8_t*)realloc(right_data_, right_step_ * right_height_);\/\/zmq_received_message.size());\n right_data_size_ = right_step_ * right_height_;\n memcpy(right_data_, flatbuffer_rcvd->right()->data(), right_data_size_);\n \n \/\/ position\n pose_position_x_ = flatbuffer_rcvd->pose()->position()->x();\n pose_position_y_ = flatbuffer_rcvd->pose()->position()->y();\n pose_position_z_ = flatbuffer_rcvd->pose()->position()->z();\n \/\/ orientation\n pose_orientation_roll_ = flatbuffer_rcvd->pose()->orientation()->roll();\n pose_orientation_pitch_ = flatbuffer_rcvd->pose()->orientation()->pitch();\n pose_orientation_yaw_ = flatbuffer_rcvd->pose()->orientation()->yaw();\n return_value = 1;\n }\n else\n {\n return_value = -1;\n }\n }\n\n return return_value;\n}\n \nuint32_t AirSimToRosClass::GetHeaderSeq()\n{\n return header_seq_;\n}\n \nuint32_t AirSimToRosClass::GetHeaderStampSec()\n{\n return header_stamp_sec_;\n}\n\nuint32_t AirSimToRosClass::GetHeaderStampNsec()\n{\n return header_stamp_nsec_;\n}\n\nstd::string AirSimToRosClass::GetHeaderFrameid()\n{\n return header_frame_id_;\n}\n\nuint32_t AirSimToRosClass::GetLeftHeight()\n{\n return left_height_;\n}\n\nuint32_t AirSimToRosClass::GetLeftWidth()\n{\n return left_width_;\n}\n\nstd::string AirSimToRosClass::GetLeftEncoding()\n{\n return left_encoding_;\n}\n\nuint8_t AirSimToRosClass::GetLeftIsBigendian()\n{\n return left_is_bigendian_;\n}\n\nuint32_t AirSimToRosClass::GetLeftStep()\n{\n return left_step_;\n}\n\nstd::uint8_t* AirSimToRosClass::GetLeftData()\n{\n return left_data_;\n}\n \nsize_t AirSimToRosClass::GetLeftDataSize()\n{\n return left_data_size_;\n}\n\nuint32_t AirSimToRosClass::GetRightHeight()\n{\n return right_height_;\n}\n\nuint32_t AirSimToRosClass::GetRightWidth()\n{\n return right_width_;\n}\n\nstd::string AirSimToRosClass::GetRightEncoding()\n{\n return right_encoding_;\n}\n\nuint8_t AirSimToRosClass::GetRightIsBigendian()\n{\n return right_is_bigendian_;\n}\n\nuint32_t AirSimToRosClass::GetRightStep()\n{\n return right_step_;\n}\n\nstd::uint8_t* AirSimToRosClass::GetRightData()\n{\n return right_data_;\n}\n \nsize_t AirSimToRosClass::GetRightDataSize()\n{\n return right_data_size_;\n}\n\ndouble AirSimToRosClass::GetPosePositionX()\n{\n return pose_position_x_;\n}\n\ndouble AirSimToRosClass::GetPosePositionY()\n{\n return pose_position_y_;\n}\n\ndouble AirSimToRosClass::GetPosePositionZ()\n{\n return pose_position_z_;\n}\n\ndouble AirSimToRosClass::GetPoseOrientationRoll()\n{\n return pose_orientation_roll_;\n}\n\ndouble AirSimToRosClass::GetPoseOrientationPitch()\n{\n return pose_orientation_pitch_;\n}\n\ndouble AirSimToRosClass::GetPoseOrientationYaw()\n{\n return pose_orientation_yaw_;\n}\n} \/\/ namespace js_airsim_to_ros_library\n\n<|endoftext|>"} {"text":"<commit_before>\r\n#include \"gtest\/gtest.h\"\r\n#include <alcommon-ng\/serialization\/serialization.h>\r\n#include <boost\/timer.hpp>\r\n#include <string>\r\n\r\nusing namespace AL::Serialization;\r\nint numMessages = 1000;\r\n\r\nTEST(SerializationTest, TextSerializationSimpleTypes)\r\n{\r\n \/\/ float three = 3.0f;\r\n std::string text = \"three\";\r\n std::string str;\r\n\r\n \/\/ text\r\n str = serialize(3, TEXT);\r\n int str_int = deserialize<int>(str, TEXT);\r\n EXPECT_EQ(3, str_int);\r\n\r\n str = serialize(3.0f, TEXT);\r\n float str_float = deserialize<float>(str, TEXT);\r\n EXPECT_EQ(3.0f, str_float);\r\n\r\n str = serialize(text, TEXT);\r\n std::string str_str = deserialize<std::string>(str, TEXT);\r\n EXPECT_EQ(text, str_str);\r\n}\r\n\r\nTEST(SerializationTest, XmlSerializationSimpleTypes)\r\n{\r\n std::string text = \"three\";\r\n std::string str;\r\n\r\n \/\/ xml\r\n str = serialize(3, XML);\r\n int xml_int = deserialize<int>(str, XML);\r\n EXPECT_EQ(3, xml_int);\r\n\r\n str = serialize(3.0f, XML);\r\n float xml_float = deserialize<float>(str, XML);\r\n EXPECT_EQ(3.0f, xml_float);\r\n\r\n str = serialize(text, XML);\r\n std::string xml_str = deserialize<std::string>(str, XML);\r\n EXPECT_EQ(text, xml_str);\r\n}\r\n\r\n\r\nTEST(SerializationTest, BinarySerializationSimpleTypes)\r\n{\r\n std::string text = \"three\";\r\n std::string str;\r\n\r\n \/\/ bin\r\n str = serialize(3, BINARY);\r\n int bin_int = deserialize<int>(str, BINARY);\r\n EXPECT_EQ(3, bin_int);\r\n\r\n str = serialize(3.0f, BINARY);\r\n float bin_float = deserialize<float>(str, BINARY);\r\n EXPECT_EQ(3.0f, bin_float);\r\n\r\n str = serialize(text, BINARY);\r\n std::string bin_str = deserialize<std::string>(str, BINARY);\r\n EXPECT_EQ(text, bin_str);\r\n\r\n}\r\n\r\n\r\nTEST(SerializationTest, DefaultSerializationSimpleTypes)\r\n{\r\n std::string text = \"three\";\r\n std::string str;\r\n\r\n \/\/ auto binary\r\n str = serialize(3);\r\n int aut_int = deserialize<int>(str);\r\n EXPECT_EQ(3, aut_int);\r\n\r\n str = serialize(3.0f);\r\n float aut_float = deserialize<float>(str);\r\n EXPECT_EQ(3.0f, aut_float);\r\n\r\n str = serialize(text);\r\n std::string aut_str = deserialize<std::string>(str);\r\n EXPECT_EQ(text, aut_str);\r\n\r\n}\r\n\r\n\r\nTEST(SerializationTest, BinaryToPtrSerializationSimpleTypes)\r\n{\r\n std::string text = \"three\";\r\n std::string str;\r\n\r\n \/\/ to ptr\r\n str = serialize(3);\r\n boost::shared_ptr<int> ptr_int = deserializeToPtr<int>(str);\r\n EXPECT_EQ(3, *ptr_int.get());\r\n\r\n str = serialize(3.0f);\r\n boost::shared_ptr<float> ptr_float = deserializeToPtr<float>(str);\r\n EXPECT_EQ(3.0f, *ptr_float.get());\r\n\r\n str = serialize(text);\r\n boost::shared_ptr<std::string> ptr_str = deserializeToPtr<std::string>(str);\r\n EXPECT_EQ(text, *ptr_str.get());\r\n\r\n \/\/ from ptr\r\n}\r\n\r\n\r\nvoid testSerialization_StringBufferSizes(AL::Serialization::SERIALIZATION_TYPE type, int numMessages) {\r\n\r\n std::cout << \"Bytes, msg\/s, MB\/s\" << std::endl;\r\n \/\/ loop message sizes 2^i bytes\r\n for (unsigned int i=1; i < 15; i++) {\r\n\r\n char character = 'A';\r\n unsigned int numBytes = (unsigned int)pow(2.0f,(int)i);\r\n std::string request = std::string(numBytes, character);\r\n\r\n boost::timer t;\r\n double elapsed;\r\n t.restart();\r\n\r\n for (int loop = 0; loop < numMessages; loop++) {\r\n \/\/ Serialize\r\n std::string reply = AL::Serialization::serialize(request, type);\r\n }\r\n\r\n elapsed = t.elapsed();\r\n float msgPs = 1.0f \/ ((float)elapsed \/ (1.0f * numMessages) );\r\n float mgbPs = (msgPs * numBytes) \/ (1024 * 1024.0f);\r\n std::cout << numBytes << \", \" << msgPs << \", \" << mgbPs << std::endl;\r\n }\r\n}\r\n\r\nvoid testDeSerialization_StringBufferSizes(AL::Serialization::SERIALIZATION_TYPE type, int numMessages) {\r\n\r\n std::cout << \"Bytes, msg\/s, MB\/s\" << std::endl;\r\n \/\/ loop message sizes 2^i bytes\r\n for (unsigned int i=1; i < 15; i++) {\r\n\r\n char character = 'A';\r\n unsigned int numBytes = (unsigned int)pow(2.0f,(int)i);\r\n std::string request = std::string(numBytes, character);\r\n\r\n boost::timer t;\r\n double elapsed;\r\n std::string buffer = AL::Serialization::serialize(request, type);\r\n\r\n t.restart();\r\n\r\n for (int loop = 0; loop < numMessages; loop++) {\r\n \/\/ Serialize\r\n std::string reply = AL::Serialization::deserialize<std::string>(buffer, type);\r\n }\r\n\r\n elapsed = t.elapsed();\r\n float msgPs = 1.0f \/ ((float)elapsed \/ (1.0f * numMessages) );\r\n float mgbPs = (msgPs * numBytes) \/ (1024 * 1024.0f);\r\n std::cout << numBytes << \", \" << msgPs << \", \" << mgbPs << std::endl;\r\n }\r\n}\r\n\r\nTEST(SerializationPerformance, binary) {\r\n \/\/int numMessages = 10000;\r\n std::cout << \" BINARY Serialization \" << numMessages << std::endl; \r\n testSerialization_StringBufferSizes(BINARY, numMessages);\r\n std::cout << \" BINARY DeSerialization \" << numMessages << std::endl; \r\n testDeSerialization_StringBufferSizes(BINARY, numMessages);\r\n}\r\n\r\nTEST(SerializationPerformance, text) {\r\n \/\/int numMessages = 10000;\r\n\r\n std::cout << \" TEXT Serialization \" << numMessages << std::endl;\r\n testSerialization_StringBufferSizes(TEXT, numMessages);\r\n std::cout << \" TEXT DeSerialization \" << numMessages << std::endl;\r\n testDeSerialization_StringBufferSizes(TEXT, numMessages);\r\n}\r\n\r\nTEST(SerializationPerformance, xml) {\r\n \/\/int numMessages = 10000;\r\n\r\n std::cout << \" XML Serialization \" << numMessages << std::endl; \r\n testSerialization_StringBufferSizes(XML, numMessages);\r\n std::cout << \" XML DeSerialization \" << numMessages << std::endl; \r\n testDeSerialization_StringBufferSizes(XML, numMessages);\r\n\r\n}<commit_msg>Added vector float tests<commit_after>\r\n#include \"gtest\/gtest.h\"\r\n#include <alcommon-ng\/serialization\/serialization.h>\r\n#include <boost\/timer.hpp>\r\n#include <string>\r\n\r\nusing namespace AL::Serialization;\r\nint numMessages = 1000;\r\n\r\nTEST(SerializationTest, TextSerializationSimpleTypes)\r\n{\r\n \/\/ float three = 3.0f;\r\n std::string text = \"three\";\r\n std::string str;\r\n\r\n \/\/ text\r\n str = serialize(3, TEXT);\r\n int str_int = deserialize<int>(str, TEXT);\r\n EXPECT_EQ(3, str_int);\r\n\r\n str = serialize(3.0f, TEXT);\r\n float str_float = deserialize<float>(str, TEXT);\r\n EXPECT_EQ(3.0f, str_float);\r\n\r\n str = serialize(text, TEXT);\r\n std::string str_str = deserialize<std::string>(str, TEXT);\r\n EXPECT_EQ(text, str_str);\r\n\r\n std::vector<float> floats;\r\n floats.assign(26,1.1028284f);\r\n str = serialize(floats, TEXT);\r\n std::vector<float> rep = deserialize<std::vector<float> >(str, TEXT);\r\n for (unsigned int i = 0; i < floats.size(); ++i) {\r\n EXPECT_EQ(floats[i], rep[i]);\r\n }\r\n}\r\n\r\nTEST(SerializationTest, XmlSerializationSimpleTypes)\r\n{\r\n std::string text = \"three\";\r\n std::string str;\r\n\r\n \/\/ xml\r\n str = serialize(3, XML);\r\n int xml_int = deserialize<int>(str, XML);\r\n EXPECT_EQ(3, xml_int);\r\n\r\n str = serialize(3.0f, XML);\r\n float xml_float = deserialize<float>(str, XML);\r\n EXPECT_EQ(3.0f, xml_float);\r\n\r\n str = serialize(text, XML);\r\n std::string xml_str = deserialize<std::string>(str, XML);\r\n EXPECT_EQ(text, xml_str);\r\n\r\n std::vector<float> floats;\r\n floats.assign(26,1.1028284f);\r\n str = serialize(floats, XML);\r\n std::vector<float> rep = deserialize<std::vector<float> >(str, XML);\r\n for (unsigned int i = 0; i < floats.size(); ++i) {\r\n EXPECT_EQ(floats[i], rep[i]);\r\n }\r\n}\r\n\r\n\r\nTEST(SerializationTest, BinarySerializationSimpleTypes)\r\n{\r\n std::string text = \"three\";\r\n std::string str;\r\n\r\n \/\/ bin\r\n str = serialize(3, BINARY);\r\n int bin_int = deserialize<int>(str, BINARY);\r\n EXPECT_EQ(3, bin_int);\r\n\r\n str = serialize(3.0f, BINARY);\r\n float bin_float = deserialize<float>(str, BINARY);\r\n EXPECT_EQ(3.0f, bin_float);\r\n\r\n str = serialize(text, BINARY);\r\n std::string bin_str = deserialize<std::string>(str, BINARY);\r\n EXPECT_EQ(text, bin_str);\r\n\r\n std::vector<float> floats;\r\n floats.assign(26,1.1028284f);\r\n str = serialize(floats, BINARY);\r\n std::vector<float> rep = deserialize<std::vector<float> >(str, BINARY);\r\n for (unsigned int i = 0; i < floats.size(); ++i) {\r\n EXPECT_EQ(floats[i], rep[i]);\r\n }\r\n\r\n}\r\n\r\n\r\nTEST(SerializationTest, DefaultSerializationSimpleTypes)\r\n{\r\n std::string text = \"three\";\r\n std::string str;\r\n\r\n \/\/ auto binary\r\n str = serialize(3);\r\n int aut_int = deserialize<int>(str);\r\n EXPECT_EQ(3, aut_int);\r\n\r\n str = serialize(3.0f);\r\n float aut_float = deserialize<float>(str);\r\n EXPECT_EQ(3.0f, aut_float);\r\n\r\n str = serialize(text);\r\n std::string aut_str = deserialize<std::string>(str);\r\n EXPECT_EQ(text, aut_str);\r\n\r\n}\r\n\r\n\r\nTEST(SerializationTest, BinaryToPtrSerializationSimpleTypes)\r\n{\r\n std::string text = \"three\";\r\n std::string str;\r\n\r\n \/\/ to ptr\r\n str = serialize(3);\r\n boost::shared_ptr<int> ptr_int = deserializeToPtr<int>(str);\r\n EXPECT_EQ(3, *ptr_int.get());\r\n\r\n str = serialize(3.0f);\r\n boost::shared_ptr<float> ptr_float = deserializeToPtr<float>(str);\r\n EXPECT_EQ(3.0f, *ptr_float.get());\r\n\r\n str = serialize(text);\r\n boost::shared_ptr<std::string> ptr_str = deserializeToPtr<std::string>(str);\r\n EXPECT_EQ(text, *ptr_str.get());\r\n\r\n \/\/ from ptr\r\n}\r\n\r\n\r\nvoid testSerialization_StringBufferSizes(AL::Serialization::SERIALIZATION_TYPE type, int numMessages) {\r\n\r\n std::cout << \"Bytes, msg\/s, MB\/s\" << std::endl;\r\n \/\/ loop message sizes 2^i bytes\r\n for (unsigned int i=1; i < 21; i++) {\r\n\r\n char character = 'A';\r\n unsigned int numBytes = (unsigned int)pow(2.0f,(int)i);\r\n std::string request = std::string(numBytes, character);\r\n\r\n boost::timer t;\r\n double elapsed;\r\n t.restart();\r\n\r\n for (int loop = 0; loop < numMessages; loop++) {\r\n \/\/ Serialize\r\n std::string reply = AL::Serialization::serialize(request, type);\r\n }\r\n\r\n elapsed = t.elapsed();\r\n float msgPs = 1.0f \/ ((float)elapsed \/ (1.0f * numMessages) );\r\n float mgbPs = (msgPs * numBytes) \/ (1024 * 1024.0f);\r\n std::cout << numBytes << \", \" << msgPs << \", \" << mgbPs << std::endl;\r\n }\r\n}\r\n\r\nvoid testDeSerialization_StringBufferSizes(AL::Serialization::SERIALIZATION_TYPE type, int numMessages) {\r\n\r\n std::cout << \"Bytes, msg\/s, MB\/s\" << std::endl;\r\n \/\/ loop message sizes 2^i bytes\r\n for (unsigned int i=1; i < 21; i++) {\r\n\r\n char character = 'A';\r\n unsigned int numBytes = (unsigned int)pow(2.0f,(int)i);\r\n std::string request = std::string(numBytes, character);\r\n\r\n boost::timer t;\r\n double elapsed;\r\n std::string buffer = AL::Serialization::serialize(request, type);\r\n\r\n t.restart();\r\n\r\n for (int loop = 0; loop < numMessages; loop++) {\r\n \/\/ Serialize\r\n std::string reply = AL::Serialization::deserialize<std::string>(buffer, type);\r\n }\r\n\r\n elapsed = t.elapsed();\r\n float msgPs = 1.0f \/ ((float)elapsed \/ (1.0f * numMessages) );\r\n float mgbPs = (msgPs * numBytes) \/ (1024 * 1024.0f);\r\n std::cout << numBytes << \", \" << msgPs << \", \" << mgbPs << std::endl;\r\n }\r\n}\r\n\r\nTEST(SerializationPerformance, DISABLED_binary) {\r\n \/\/int numMessages = 10000;\r\n std::cout << \" BINARY Serialization \" << numMessages << std::endl; \r\n testSerialization_StringBufferSizes(BINARY, numMessages);\r\n std::cout << \" BINARY DeSerialization \" << numMessages << std::endl; \r\n testDeSerialization_StringBufferSizes(BINARY, numMessages);\r\n}\r\n\r\nTEST(SerializationPerformance, DISABLED_text) {\r\n \/\/int numMessages = 10000;\r\n\r\n std::cout << \" TEXT Serialization \" << numMessages << std::endl;\r\n testSerialization_StringBufferSizes(TEXT, numMessages);\r\n std::cout << \" TEXT DeSerialization \" << numMessages << std::endl;\r\n testDeSerialization_StringBufferSizes(TEXT, numMessages);\r\n}\r\n\r\nTEST(SerializationPerformance, DISABLED_xml) {\r\n \/\/int numMessages = 10000;\r\n\r\n std::cout << \" XML Serialization \" << numMessages << std::endl; \r\n testSerialization_StringBufferSizes(XML, numMessages);\r\n std::cout << \" XML DeSerialization \" << numMessages << std::endl; \r\n testDeSerialization_StringBufferSizes(XML, numMessages);\r\n\r\n}\r\nvoid testSerialization_vectorfloat(AL::Serialization::SERIALIZATION_TYPE type, int numMessages) {\r\n std::string str;\r\n std::vector<float> floats;\r\n floats.assign(26,1.1028284f);\r\n\r\n int numBytes = sizeof(float) * 26;\r\n \r\n \/\/std::cout << \"Vector<float> binary: \" << numMessages << std::endl;\r\n \/\/std::cout << \"Bytes, msg\/s, MB\/s\" << std::endl;\r\n boost::timer t;\r\n\r\n for( int i=0; i< numMessages; i++) {\r\n \r\n str = serialize(floats, type);\r\n std::vector<float> rep = deserialize<std::vector<float> >(str, type);\r\n }\r\n\r\n double elapsed = t.elapsed();\r\n float msgPs = 1.0f \/ ((float)elapsed \/ (1.0f * numMessages) );\r\n float mgbPs = (msgPs * numBytes) \/ (1024 * 1024.0f);\r\n \/\/std::cout << numBytes << \", \" << msgPs << \", \" << mgbPs << std::endl;\r\n}\r\n\r\nTEST(SerializationPerformance, vectorfloatBinary) {\r\n int numMessages = 1000;\r\n testSerialization_vectorfloat(BINARY,numMessages);\r\n}\r\n\r\nTEST(SerializationPerformance, vectorfloatText) {\r\n int numMessages = 1000;\r\n testSerialization_vectorfloat(TEXT,numMessages);\r\n}\r\n\r\nTEST(SerializationPerformance, vectorfloatXML) {\r\n int numMessages = 1000;\r\n testSerialization_vectorfloat(XML,numMessages);\r\n}\r\n<|endoftext|>"} {"text":"<commit_before>\/**\n * \\file\n * Copyright 2015 Benjamin Worpitz\n *\n * This file is part of alpaka.\n *\n * alpaka is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * alpaka is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public License\n * along with alpaka.\n * If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n\n\/\/ \\Hack: Boost.MPL defines BOOST_MPL_CFG_GPU_ENABLED to __host__ __device__ if nvcc is used.\n\/\/ BOOST_AUTO_TEST_CASE_TEMPLATE and its internals are not GPU enabled but is using boost::mpl::for_each internally.\n\/\/ For each template parameter this leads to:\n\/\/ \/home\/travis\/build\/boost\/boost\/mpl\/for_each.hpp(78): warning: calling a __host__ function from a __host__ __device__ function is not allowed\n\/\/ because boost::mpl::for_each has the BOOST_MPL_CFG_GPU_ENABLED attribute but the test internals are pure host methods.\n\/\/ Because we do not use MPL within GPU code here, we can disable the MPL GPU support.\n#define BOOST_MPL_CFG_GPU_ENABLED\n\n#include <alpaka\/alpaka.hpp>\n#include <alpaka\/test\/acc\/Acc.hpp> \/\/ alpaka::test::acc::TestAccs\n#include <alpaka\/test\/stream\/Stream.hpp> \/\/ alpaka::test::stream::DefaultStream\n#include <alpaka\/test\/KernelExecutionFixture.hpp> \/\/ alpaka::test::KernelExecutionFixture\n\n#include <boost\/test\/unit_test.hpp>\n\n\/\/#############################################################################\n\/\/!\n\/\/#############################################################################\nclass BlockSharedMemDyn\n{\npublic:\n \/\/-----------------------------------------------------------------------------\n \/\/!\n \/\/-----------------------------------------------------------------------------\n ALPAKA_NO_HOST_ACC_WARNING\n template<\n typename TAcc>\n ALPAKA_FN_ACC auto operator()(\n TAcc const & acc) const\n -> void\n {\n \/\/ Assure that the pointer is non null.\n auto && a = alpaka::block::shared::dyn::getMem<std::uint32_t>(acc);\n BOOST_REQUIRE_NE(static_cast<std::uint32_t *>(nullptr), a);\n\n \/\/ Each call should return the same pointer ...\n auto && b = alpaka::block::shared::dyn::getMem<std::uint32_t>(acc);\n BOOST_REQUIRE_EQUAL(a, b);\n\n \/\/ ... even for different types.\n auto && c = alpaka::block::shared::dyn::getMem<float>(acc);\n BOOST_REQUIRE_EQUAL(a, reinterpret_cast<std::uint32_t *>(c));\n }\n};\n\nnamespace alpaka\n{\n namespace kernel\n {\n namespace traits\n {\n \/\/#############################################################################\n \/\/! The trait for getting the size of the block shared dynamic memory for a kernel.\n \/\/#############################################################################\n template<\n typename TAcc>\n struct BlockSharedMemDynSizeBytes<\n BlockSharedMemDyn,\n TAcc>\n {\n \/\/-----------------------------------------------------------------------------\n \/\/! \\return The size of the shared memory allocated for a block.\n \/\/-----------------------------------------------------------------------------\n template<\n typename TVec>\n ALPAKA_FN_HOST static auto getBlockSharedMemDynSizeBytes(\n BlockSharedMemDyn const & blockSharedMemDyn,\n TVec const & blockThreadExtent,\n TVec const & threadElemExtent)\n -> size::Size<TAcc>\n {\n boost::ignore_unused(blockSharedMemDyn);\n return sizeof(std::uint32_t) * blockThreadExtent.prod() * threadElemExtent.prod();\n }\n };\n }\n }\n}\n\nBOOST_AUTO_TEST_SUITE(blockSharedMemDyn)\n\n\/\/-----------------------------------------------------------------------------\n\/\/\n\/\/-----------------------------------------------------------------------------\nBOOST_AUTO_TEST_CASE_TEMPLATE(\n sameNonNullAdress,\n TAcc,\n alpaka::test::acc::TestAccs)\n{\n using Dim = alpaka::dim::Dim<TAcc>;\n using Size = alpaka::size::Size<TAcc>;\n\n alpaka::test::KernelExecutionFixture<TAcc> fixture(\n alpaka::Vec<Dim, Size>::ones());\n\n BlockSharedMemDyn kernel;\n\n BOOST_REQUIRE_EQUAL(\n true,\n fixture(\n kernel));\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n<commit_msg>unify test kernel names<commit_after>\/**\n * \\file\n * Copyright 2015 Benjamin Worpitz\n *\n * This file is part of alpaka.\n *\n * alpaka is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * alpaka is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public License\n * along with alpaka.\n * If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n\n\/\/ \\Hack: Boost.MPL defines BOOST_MPL_CFG_GPU_ENABLED to __host__ __device__ if nvcc is used.\n\/\/ BOOST_AUTO_TEST_CASE_TEMPLATE and its internals are not GPU enabled but is using boost::mpl::for_each internally.\n\/\/ For each template parameter this leads to:\n\/\/ \/home\/travis\/build\/boost\/boost\/mpl\/for_each.hpp(78): warning: calling a __host__ function from a __host__ __device__ function is not allowed\n\/\/ because boost::mpl::for_each has the BOOST_MPL_CFG_GPU_ENABLED attribute but the test internals are pure host methods.\n\/\/ Because we do not use MPL within GPU code here, we can disable the MPL GPU support.\n#define BOOST_MPL_CFG_GPU_ENABLED\n\n#include <alpaka\/alpaka.hpp>\n#include <alpaka\/test\/acc\/Acc.hpp> \/\/ alpaka::test::acc::TestAccs\n#include <alpaka\/test\/stream\/Stream.hpp> \/\/ alpaka::test::stream::DefaultStream\n#include <alpaka\/test\/KernelExecutionFixture.hpp> \/\/ alpaka::test::KernelExecutionFixture\n\n#include <boost\/test\/unit_test.hpp>\n\n\/\/#############################################################################\n\/\/!\n\/\/#############################################################################\nclass BlockSharedMemDynTestKernel\n{\npublic:\n \/\/-----------------------------------------------------------------------------\n \/\/!\n \/\/-----------------------------------------------------------------------------\n ALPAKA_NO_HOST_ACC_WARNING\n template<\n typename TAcc>\n ALPAKA_FN_ACC auto operator()(\n TAcc const & acc) const\n -> void\n {\n \/\/ Assure that the pointer is non null.\n auto && a = alpaka::block::shared::dyn::getMem<std::uint32_t>(acc);\n BOOST_REQUIRE_NE(static_cast<std::uint32_t *>(nullptr), a);\n\n \/\/ Each call should return the same pointer ...\n auto && b = alpaka::block::shared::dyn::getMem<std::uint32_t>(acc);\n BOOST_REQUIRE_EQUAL(a, b);\n\n \/\/ ... even for different types.\n auto && c = alpaka::block::shared::dyn::getMem<float>(acc);\n BOOST_REQUIRE_EQUAL(a, reinterpret_cast<std::uint32_t *>(c));\n }\n};\n\nnamespace alpaka\n{\n namespace kernel\n {\n namespace traits\n {\n \/\/#############################################################################\n \/\/! The trait for getting the size of the block shared dynamic memory for a kernel.\n \/\/#############################################################################\n template<\n typename TAcc>\n struct BlockSharedMemDynSizeBytes<\n BlockSharedMemDynTestKernel,\n TAcc>\n {\n \/\/-----------------------------------------------------------------------------\n \/\/! \\return The size of the shared memory allocated for a block.\n \/\/-----------------------------------------------------------------------------\n template<\n typename TVec>\n ALPAKA_FN_HOST static auto getBlockSharedMemDynSizeBytes(\n BlockSharedMemDynTestKernel const & blockSharedMemDyn,\n TVec const & blockThreadExtent,\n TVec const & threadElemExtent)\n -> size::Size<TAcc>\n {\n boost::ignore_unused(blockSharedMemDyn);\n return sizeof(std::uint32_t) * blockThreadExtent.prod() * threadElemExtent.prod();\n }\n };\n }\n }\n}\n\nBOOST_AUTO_TEST_SUITE(blockSharedMemDyn)\n\n\/\/-----------------------------------------------------------------------------\n\/\/\n\/\/-----------------------------------------------------------------------------\nBOOST_AUTO_TEST_CASE_TEMPLATE(\n sameNonNullAdress,\n TAcc,\n alpaka::test::acc::TestAccs)\n{\n using Dim = alpaka::dim::Dim<TAcc>;\n using Size = alpaka::size::Size<TAcc>;\n\n alpaka::test::KernelExecutionFixture<TAcc> fixture(\n alpaka::Vec<Dim, Size>::ones());\n\n BlockSharedMemDynTestKernel kernel;\n\n BOOST_REQUIRE_EQUAL(\n true,\n fixture(\n kernel));\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n<|endoftext|>"} {"text":"<commit_before>#include <stan\/math\/prim\/scal.hpp>\n#include <test\/unit\/math\/prim\/scal\/prob\/util.hpp>\n#include <boost\/random\/mersenne_twister.hpp>\n#include <boost\/math\/distributions.hpp>\n#include <gtest\/gtest.h>\n\nTEST(ProbDistributionsVonMises, error_check) {\n boost::random::mt19937 rng;\n EXPECT_NO_THROW(stan::math::von_mises_rng(1.0, 2.0, rng));\n EXPECT_NO_THROW(stan::math::von_mises_rng(1.0, 0.0, rng));\n\n EXPECT_THROW(\n stan::math::von_mises_rng(stan::math::negative_infinity(), 2.0, rng),\n std::domain_error);\n EXPECT_THROW(\n stan::math::von_mises_rng(1, stan::math::positive_infinity(), rng),\n std::domain_error);\n EXPECT_THROW(stan::math::von_mises_rng(1, -3, rng), std::domain_error);\n EXPECT_NO_THROW(stan::math::von_mises_rng(2, 1, rng));\n}\n\nTEST(ProbDistributionsVonMises, chiSquareGoodnessFitTest1) {\n boost::random::mt19937 rng;\n int N = 10000;\n int K = 80;\n boost::math::chi_squared mydist(K - 1);\n\n double loc[]\n = {1.589032, 1.835082, 1.977091, 2.078807, 2.158994, 2.225759, 2.283346,\n 2.334261, 2.380107, 2.421973, 2.460635, 2.496664, 2.530492, 2.562457,\n 2.592827, 2.621819, 2.649609, 2.676346, 2.702153, 2.727137, 2.751389,\n 2.774988, 2.798002, 2.820493, 2.842515, 2.864116, 2.885340, 2.906227,\n 2.926814, 2.947132, 2.967214, 2.987089, 3.006782, 3.026321, 3.045728,\n 3.065028, 3.084243, 3.103394, 3.122504, 3.141593, 3.160681, 3.179791,\n 3.198942, 3.218157, 3.237457, 3.256865, 3.276403, 3.296097, 3.315971,\n 3.336053, 3.356372, 3.376958, 3.397845, 3.419069, 3.440671, 3.462693,\n 3.485184, 3.508198, 3.531796, 3.556048, 3.581032, 3.606840, 3.633576,\n 3.661367, 3.690358, 3.720728, 3.752694, 3.786522, 3.822550, 3.861212,\n 3.903079, 3.948925, 3.999839, 4.057427, 4.124191, 4.204379, 4.306094,\n 4.448103, 4.694153};\n for (int i = 0; i < K - 1; i++)\n loc[i] = loc[i] - stan::math::pi();\n\n int count = 0;\n int bin[K];\n double expect[K];\n for (int i = 0; i < K; i++) {\n bin[i] = 0;\n expect[i] = N \/ K;\n }\n\n while (count < N) {\n double a = stan::math::von_mises_rng(0, 3.0, rng);\n int i = 0;\n while (i < K - 1 && a > loc[i])\n ++i;\n ++bin[i];\n count++;\n }\n\n double chi = 0;\n\n for (int j = 0; j < K; j++) {\n chi += ((bin[j] - expect[j]) * (bin[j] - expect[j]) \/ expect[j]);\n }\n\n EXPECT_LT(chi, quantile(complement(mydist, 1e-6)));\n}\n\nTEST(ProbDistributionsVonMises, chiSquareGoodnessFitTest2) {\n boost::random::mt19937 rng;\n int N = 10000;\n int K = 80;\n boost::math::chi_squared mydist(K - 1);\n\n double loc[]\n = {1.5890, 1.8351, 1.9771, 2.0788, 2.1590, 2.2258, 2.2833, 2.3343, 2.3801,\n 2.4220, 2.4606, 2.4967, 2.5305, 2.5625, 2.5928, 2.6218, 2.6496, 2.6763,\n 2.7022, 2.7271, 2.7514, 2.7750, 2.7980, 2.8205, 2.8425, 2.8641, 2.8853,\n 2.9062, 2.9268, 2.9471, 2.9672, 2.9871, 3.0068, 3.0263, 3.0457, 3.0650,\n 3.0842, 3.1034, 3.1225, 3.1416, 3.1607, 3.1798, 3.1989, 3.2182, 3.2375,\n 3.2569, 3.2764, 3.2961, 3.3160, 3.3361, 3.3564, 3.3770, 3.3978, 3.4191,\n 3.4407, 3.4627, 3.4852, 3.5082, 3.5318, 3.5560, 3.5810, 3.6068, 3.6336,\n 3.6614, 3.6904, 3.7207, 3.7527, 3.7865, 3.8226, 3.8612, 3.9031, 3.9489,\n 3.9998, 4.0574, 4.1242, 4.2044, 4.3061, 4.4481, 4.6942};\n\n int count = 0;\n int bin[K];\n double expect[K];\n for (int i = 0; i < K; i++) {\n bin[i] = 0;\n expect[i] = N \/ K;\n }\n\n while (count < N) {\n double a = stan::math::von_mises_rng(11 * 3.14, 3.0, rng);\n int i = 0;\n while (i < K - 1 && a > loc[i])\n ++i;\n ++bin[i];\n count++;\n }\n\n double chi = 0;\n\n for (int j = 0; j < K; j++) {\n chi += ((bin[j] - expect[j]) * (bin[j] - expect[j]) \/ expect[j]);\n }\n\n EXPECT_LT(chi, quantile(complement(mydist, 1e-6)));\n}\n\nTEST(ProbDistributionsVonMises, chiSquareGoodnessFitTest3) {\n boost::random::mt19937 rng;\n int N = 10000;\n int K = 80;\n boost::math::chi_squared mydist(K - 1);\n\n double loc[] = {\n -0.552560, -0.306511, -0.164502, -0.062786, 0.017401, 0.084166, 0.141753,\n 0.192668, 0.238514, 0.280381, 0.319043, 0.355071, 0.388899, 0.420864,\n 0.451235, 0.480226, 0.508016, 0.534753, 0.560560, 0.585545, 0.609796,\n 0.633395, 0.656409, 0.678900, 0.700922, 0.722523, 0.743748, 0.764635,\n 0.785221, 0.805540, 0.825622, 0.845496, 0.865190, 0.884728, 0.904136,\n 0.923435, 0.942650, 0.961802, 0.980911, 1.000000, 1.019089, 1.038198,\n 1.057350, 1.076565, 1.095864, 1.115272, 1.134810, 1.154504, 1.174378,\n 1.194460, 1.214779, 1.235365, 1.256252, 1.277477, 1.299078, 1.321100,\n 1.343591, 1.366605, 1.390204, 1.414455, 1.439440, 1.465247, 1.491984,\n 1.519774, 1.548765, 1.579136, 1.611101, 1.644929, 1.680957, 1.719619,\n 1.761486, 1.807332, 1.858247, 1.915834, 1.982599, 2.062786, 2.164502,\n 2.306511, 2.552560};\n int count = 0;\n int bin[K];\n double expect[K];\n for (int i = 0; i < K; i++) {\n bin[i] = 0;\n expect[i] = N \/ K;\n }\n\n while (count < N) {\n double a = stan::math::von_mises_rng(-17.85, 3.0, rng);\n int i = 0;\n while (i < K - 1 && a > loc[i])\n ++i;\n ++bin[i];\n count++;\n }\n\n double chi = 0;\n\n for (int j = 0; j < K; j++) {\n chi += ((bin[j] - expect[j]) * (bin[j] - expect[j]) \/ expect[j]);\n }\n\n EXPECT_LT(chi, quantile(complement(mydist, 1e-6)));\n}\n\nTEST(ProbDistributionsVonMises, chiSquareGoodnessFitTest4) {\n boost::random::mt19937 rng;\n int N = 10000;\n int K = stan::math::round(2 * std::pow(N, 0.4));\n\n std::vector<double> samples;\n for (int i = 0; i < N; ++i) {\n samples.push_back(stan::math::von_mises_rng(stan::math::pi(), 0.0, rng));\n }\n\n std::vector<double> quantiles;\n for (int i = 1; i <= K; ++i) {\n double frac = static_cast<double>(i) * stan::math::TWO_PI \/ K;\n quantiles.push_back(0.0 + frac);\n }\n\n assert_matches_quantiles(samples, quantiles, 1e-6);\n}\n<commit_msg>Fix cpplint<commit_after>#include <stan\/math\/prim\/scal.hpp>\n#include <test\/unit\/math\/prim\/scal\/prob\/util.hpp>\n#include <boost\/random\/mersenne_twister.hpp>\n#include <boost\/math\/distributions.hpp>\n#include <gtest\/gtest.h>\n#include <vector>\n\nTEST(ProbDistributionsVonMises, error_check) {\n boost::random::mt19937 rng;\n EXPECT_NO_THROW(stan::math::von_mises_rng(1.0, 2.0, rng));\n EXPECT_NO_THROW(stan::math::von_mises_rng(1.0, 0.0, rng));\n\n EXPECT_THROW(\n stan::math::von_mises_rng(stan::math::negative_infinity(), 2.0, rng),\n std::domain_error);\n EXPECT_THROW(\n stan::math::von_mises_rng(1, stan::math::positive_infinity(), rng),\n std::domain_error);\n EXPECT_THROW(stan::math::von_mises_rng(1, -3, rng), std::domain_error);\n EXPECT_NO_THROW(stan::math::von_mises_rng(2, 1, rng));\n}\n\nTEST(ProbDistributionsVonMises, chiSquareGoodnessFitTest1) {\n boost::random::mt19937 rng;\n int N = 10000;\n int K = 80;\n boost::math::chi_squared mydist(K - 1);\n\n double loc[]\n = {1.589032, 1.835082, 1.977091, 2.078807, 2.158994, 2.225759, 2.283346,\n 2.334261, 2.380107, 2.421973, 2.460635, 2.496664, 2.530492, 2.562457,\n 2.592827, 2.621819, 2.649609, 2.676346, 2.702153, 2.727137, 2.751389,\n 2.774988, 2.798002, 2.820493, 2.842515, 2.864116, 2.885340, 2.906227,\n 2.926814, 2.947132, 2.967214, 2.987089, 3.006782, 3.026321, 3.045728,\n 3.065028, 3.084243, 3.103394, 3.122504, 3.141593, 3.160681, 3.179791,\n 3.198942, 3.218157, 3.237457, 3.256865, 3.276403, 3.296097, 3.315971,\n 3.336053, 3.356372, 3.376958, 3.397845, 3.419069, 3.440671, 3.462693,\n 3.485184, 3.508198, 3.531796, 3.556048, 3.581032, 3.606840, 3.633576,\n 3.661367, 3.690358, 3.720728, 3.752694, 3.786522, 3.822550, 3.861212,\n 3.903079, 3.948925, 3.999839, 4.057427, 4.124191, 4.204379, 4.306094,\n 4.448103, 4.694153};\n for (int i = 0; i < K - 1; i++)\n loc[i] = loc[i] - stan::math::pi();\n\n int count = 0;\n int bin[K];\n double expect[K];\n for (int i = 0; i < K; i++) {\n bin[i] = 0;\n expect[i] = N \/ K;\n }\n\n while (count < N) {\n double a = stan::math::von_mises_rng(0, 3.0, rng);\n int i = 0;\n while (i < K - 1 && a > loc[i])\n ++i;\n ++bin[i];\n count++;\n }\n\n double chi = 0;\n\n for (int j = 0; j < K; j++) {\n chi += ((bin[j] - expect[j]) * (bin[j] - expect[j]) \/ expect[j]);\n }\n\n EXPECT_LT(chi, quantile(complement(mydist, 1e-6)));\n}\n\nTEST(ProbDistributionsVonMises, chiSquareGoodnessFitTest2) {\n boost::random::mt19937 rng;\n int N = 10000;\n int K = 80;\n boost::math::chi_squared mydist(K - 1);\n\n double loc[]\n = {1.5890, 1.8351, 1.9771, 2.0788, 2.1590, 2.2258, 2.2833, 2.3343, 2.3801,\n 2.4220, 2.4606, 2.4967, 2.5305, 2.5625, 2.5928, 2.6218, 2.6496, 2.6763,\n 2.7022, 2.7271, 2.7514, 2.7750, 2.7980, 2.8205, 2.8425, 2.8641, 2.8853,\n 2.9062, 2.9268, 2.9471, 2.9672, 2.9871, 3.0068, 3.0263, 3.0457, 3.0650,\n 3.0842, 3.1034, 3.1225, 3.1416, 3.1607, 3.1798, 3.1989, 3.2182, 3.2375,\n 3.2569, 3.2764, 3.2961, 3.3160, 3.3361, 3.3564, 3.3770, 3.3978, 3.4191,\n 3.4407, 3.4627, 3.4852, 3.5082, 3.5318, 3.5560, 3.5810, 3.6068, 3.6336,\n 3.6614, 3.6904, 3.7207, 3.7527, 3.7865, 3.8226, 3.8612, 3.9031, 3.9489,\n 3.9998, 4.0574, 4.1242, 4.2044, 4.3061, 4.4481, 4.6942};\n\n int count = 0;\n int bin[K];\n double expect[K];\n for (int i = 0; i < K; i++) {\n bin[i] = 0;\n expect[i] = N \/ K;\n }\n\n while (count < N) {\n double a = stan::math::von_mises_rng(11 * 3.14, 3.0, rng);\n int i = 0;\n while (i < K - 1 && a > loc[i])\n ++i;\n ++bin[i];\n count++;\n }\n\n double chi = 0;\n\n for (int j = 0; j < K; j++) {\n chi += ((bin[j] - expect[j]) * (bin[j] - expect[j]) \/ expect[j]);\n }\n\n EXPECT_LT(chi, quantile(complement(mydist, 1e-6)));\n}\n\nTEST(ProbDistributionsVonMises, chiSquareGoodnessFitTest3) {\n boost::random::mt19937 rng;\n int N = 10000;\n int K = 80;\n boost::math::chi_squared mydist(K - 1);\n\n double loc[] = {\n -0.552560, -0.306511, -0.164502, -0.062786, 0.017401, 0.084166, 0.141753,\n 0.192668, 0.238514, 0.280381, 0.319043, 0.355071, 0.388899, 0.420864,\n 0.451235, 0.480226, 0.508016, 0.534753, 0.560560, 0.585545, 0.609796,\n 0.633395, 0.656409, 0.678900, 0.700922, 0.722523, 0.743748, 0.764635,\n 0.785221, 0.805540, 0.825622, 0.845496, 0.865190, 0.884728, 0.904136,\n 0.923435, 0.942650, 0.961802, 0.980911, 1.000000, 1.019089, 1.038198,\n 1.057350, 1.076565, 1.095864, 1.115272, 1.134810, 1.154504, 1.174378,\n 1.194460, 1.214779, 1.235365, 1.256252, 1.277477, 1.299078, 1.321100,\n 1.343591, 1.366605, 1.390204, 1.414455, 1.439440, 1.465247, 1.491984,\n 1.519774, 1.548765, 1.579136, 1.611101, 1.644929, 1.680957, 1.719619,\n 1.761486, 1.807332, 1.858247, 1.915834, 1.982599, 2.062786, 2.164502,\n 2.306511, 2.552560};\n int count = 0;\n int bin[K];\n double expect[K];\n for (int i = 0; i < K; i++) {\n bin[i] = 0;\n expect[i] = N \/ K;\n }\n\n while (count < N) {\n double a = stan::math::von_mises_rng(-17.85, 3.0, rng);\n int i = 0;\n while (i < K - 1 && a > loc[i])\n ++i;\n ++bin[i];\n count++;\n }\n\n double chi = 0;\n\n for (int j = 0; j < K; j++) {\n chi += ((bin[j] - expect[j]) * (bin[j] - expect[j]) \/ expect[j]);\n }\n\n EXPECT_LT(chi, quantile(complement(mydist, 1e-6)));\n}\n\nTEST(ProbDistributionsVonMises, chiSquareGoodnessFitTest4) {\n boost::random::mt19937 rng;\n int N = 10000;\n int K = stan::math::round(2 * std::pow(N, 0.4));\n\n std::vector<double> samples;\n for (int i = 0; i < N; ++i) {\n samples.push_back(stan::math::von_mises_rng(stan::math::pi(), 0.0, rng));\n }\n\n std::vector<double> quantiles;\n for (int i = 1; i <= K; ++i) {\n double frac = static_cast<double>(i) * stan::math::TWO_PI \/ K;\n quantiles.push_back(0.0 + frac);\n }\n\n assert_matches_quantiles(samples, quantiles, 1e-6);\n}\n<|endoftext|>"} {"text":"<commit_before><commit_msg>error C2666: 'operator ==' : 2 overloads have similar conversions<commit_after><|endoftext|>"} {"text":"<commit_before>\/*\n This file is part of Kontact.\n\n Copyright (c) 2004 Tobias Koenig <tokoe@kde.org>\n adapted for karm 2005 by Thorsten Staerk <kde@staerk.de>\n karm renamed to ktimetracker 2007-2008\n\n This program is free software; you can redistribute it and\/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation; either version 2 of the License, or\n (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License along\n with this program; if not, write to the Free Software Foundation, Inc.,\n 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n\n As a special exception, permission is given to link this program\n with any edition of Qt, and distribute the resulting executable,\n without including the source code for Qt in the source distribution.\n*\/\n\n#include \"ktimetracker_plugin.h\"\n#include \"ktimetrackerinterface.h\"\n\n#include <ktimetrackerpart.h>\n\n#include <kontactinterfaces\/core.h>\n#include <kontactinterfaces\/plugin.h>\n\n#include <kactioncollection.h>\n#include <kcmdlineargs.h>\n#include <kgenericfactory.h>\n#include <kicon.h>\n#include <kparts\/componentfactory.h>\n\nEXPORT_KONTACT_PLUGIN( ktimetrackerplugin, ktimetracker )\n\nktimetrackerplugin::ktimetrackerplugin( Kontact::Core *core, const QVariantList & )\n : Kontact::Plugin( core, core, \"ktimetracker\" ), mInterface( 0 )\n{\n setComponentData( KontactPluginFactory::componentData() );\n\n KAction *action = new KAction( KIcon( \"ktimetracker\" ), i18n( \"New Task\" ), this );\n actionCollection()->addAction( \"new_task\", action );\n action->setShortcut( QKeySequence( Qt::CTRL + Qt::SHIFT + Qt::Key_W ) );\n connect( action, SIGNAL(triggered(bool)), SLOT(newTask()) );\n insertNewAction( action );\n\n mUniqueAppWatcher = new Kontact::UniqueAppWatcher(\n new Kontact::UniqueAppHandlerFactory<KtimetrackerUniqueAppHandler>(), this );\n}\n\nktimetrackerplugin::~ktimetrackerplugin()\n{\n}\n\nbool ktimetrackerplugin::isRunningStandalone()\n{\n return mUniqueAppWatcher->isRunningStandalone();\n}\n\nQStringList ktimetrackerplugin::invisibleToolbarActions() const\n{\n return QStringList() << \"new_task\" << \"new_sub_task\" ;\n}\n\nKParts::ReadOnlyPart *ktimetrackerplugin::createPart()\n{\n KParts::ReadOnlyPart *part = loadPart();\n if ( !part ) return 0;\n\n mInterface = new OrgKdeKtimetrackerKtimetrackerInterface(\n \"org.kde.ktimetracker\", \"\/KTimeTracker\", QDBusConnection::sessionBus() );\n\n return part;\n}\n\nOrgKdeKtimetrackerKtimetrackerInterface *ktimetrackerplugin::interface()\n{\n if ( !mInterface ) part();\n Q_ASSERT( mInterface );\n return mInterface;\n}\n\nQStringList ktimetrackerplugin::configModules() const\n{\n QStringList modules;\n modules << \"PIM\/ktimetrackerconfig.desktop\";\n return modules;\n}\n\nvoid ktimetrackerplugin::newTask()\n{\n core()->selectPlugin( this );\n interface()->newTask();\n}\n\nvoid KtimetrackerUniqueAppHandler::loadCommandLineOptions()\n{\n \/\/ TODO: handle command line options\n KCmdLineArgs::addCmdLineOptions( KCmdLineOptions() );\n}\n\nint KtimetrackerUniqueAppHandler::newInstance()\n{\n kDebug();\n \/\/ Ensure part is loaded\n (void)plugin()->part();\n return Kontact::UniqueAppHandler::newInstance();\n}\n\n#include \"ktimetracker_plugin.moc\"\n\n<commit_msg>Fix mem leak<commit_after>\/*\n This file is part of Kontact.\n\n Copyright (c) 2004 Tobias Koenig <tokoe@kde.org>\n adapted for karm 2005 by Thorsten Staerk <kde@staerk.de>\n karm renamed to ktimetracker 2007-2008\n\n This program is free software; you can redistribute it and\/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation; either version 2 of the License, or\n (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License along\n with this program; if not, write to the Free Software Foundation, Inc.,\n 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n\n As a special exception, permission is given to link this program\n with any edition of Qt, and distribute the resulting executable,\n without including the source code for Qt in the source distribution.\n*\/\n\n#include \"ktimetracker_plugin.h\"\n#include \"ktimetrackerinterface.h\"\n\n#include <ktimetrackerpart.h>\n\n#include <kontactinterfaces\/core.h>\n#include <kontactinterfaces\/plugin.h>\n\n#include <kactioncollection.h>\n#include <kcmdlineargs.h>\n#include <kgenericfactory.h>\n#include <kicon.h>\n#include <kparts\/componentfactory.h>\n\nEXPORT_KONTACT_PLUGIN( ktimetrackerplugin, ktimetracker )\n\nktimetrackerplugin::ktimetrackerplugin( Kontact::Core *core, const QVariantList & )\n : Kontact::Plugin( core, core, \"ktimetracker\" ), mInterface( 0 )\n{\n setComponentData( KontactPluginFactory::componentData() );\n\n KAction *action = new KAction( KIcon( \"ktimetracker\" ), i18n( \"New Task\" ), this );\n actionCollection()->addAction( \"new_task\", action );\n action->setShortcut( QKeySequence( Qt::CTRL + Qt::SHIFT + Qt::Key_W ) );\n connect( action, SIGNAL(triggered(bool)), SLOT(newTask()) );\n insertNewAction( action );\n\n mUniqueAppWatcher = new Kontact::UniqueAppWatcher(\n new Kontact::UniqueAppHandlerFactory<KtimetrackerUniqueAppHandler>(), this );\n}\n\nktimetrackerplugin::~ktimetrackerplugin()\n{\n delete mInterface;\n}\n\nbool ktimetrackerplugin::isRunningStandalone()\n{\n return mUniqueAppWatcher->isRunningStandalone();\n}\n\nQStringList ktimetrackerplugin::invisibleToolbarActions() const\n{\n return QStringList() << \"new_task\" << \"new_sub_task\" ;\n}\n\nKParts::ReadOnlyPart *ktimetrackerplugin::createPart()\n{\n KParts::ReadOnlyPart *part = loadPart();\n if ( !part ) return 0;\n\n mInterface = new OrgKdeKtimetrackerKtimetrackerInterface(\n \"org.kde.ktimetracker\", \"\/KTimeTracker\", QDBusConnection::sessionBus() );\n\n return part;\n}\n\nOrgKdeKtimetrackerKtimetrackerInterface *ktimetrackerplugin::interface()\n{\n if ( !mInterface ) part();\n Q_ASSERT( mInterface );\n return mInterface;\n}\n\nQStringList ktimetrackerplugin::configModules() const\n{\n QStringList modules;\n modules << \"PIM\/ktimetrackerconfig.desktop\";\n return modules;\n}\n\nvoid ktimetrackerplugin::newTask()\n{\n core()->selectPlugin( this );\n interface()->newTask();\n}\n\nvoid KtimetrackerUniqueAppHandler::loadCommandLineOptions()\n{\n \/\/ TODO: handle command line options\n KCmdLineArgs::addCmdLineOptions( KCmdLineOptions() );\n}\n\nint KtimetrackerUniqueAppHandler::newInstance()\n{\n kDebug();\n \/\/ Ensure part is loaded\n (void)plugin()->part();\n return Kontact::UniqueAppHandler::newInstance();\n}\n\n#include \"ktimetracker_plugin.moc\"\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2009-2010 Satoshi Nakamoto\n\/\/ Copyright (c) 2009-2013 The Bitcoin developers\n\/\/ Distributed under the MIT\/X11 software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \"rpcserver.h\"\n#include \"rpcclient.h\"\n#include \"init.h\"\n#include \"main.h\"\n#include \"noui.h\"\n#include \"ui_interface.h\"\n#include \"util.h\"\n\n#include <boost\/algorithm\/string\/predicate.hpp>\n#include <boost\/filesystem.hpp>\n\n\/* Introduction text for doxygen: *\/\n\n\/*! \\mainpage Developer documentation\n *\n * \\section intro_sec Introduction\n *\n * This is the developer documentation of the reference client for an experimental new digital currency called Bitcoin (http:\/\/www.bitcoin.org\/),\n * which enables instant payments to anyone, anywhere in the world. Bitcoin uses peer-to-peer technology to operate\n * with no central authority: managing transactions and issuing money are carried out collectively by the network.\n *\n * The software is a community-driven open source project, released under the MIT license.\n *\n * \\section Navigation\n * Use the buttons <code>Namespaces<\/code>, <code>Classes<\/code> or <code>Files<\/code> at the top of the page to start navigating the code.\n *\/\n\nstatic bool fDaemon;\n\nvoid DetectShutdownThread(boost::thread_group* threadGroup)\n{\n bool fShutdown = ShutdownRequested();\n \/\/ Tell the main threads to shutdown.\n while (!fShutdown)\n {\n MilliSleep(200);\n fShutdown = ShutdownRequested();\n }\n if (threadGroup)\n {\n threadGroup->interrupt_all();\n threadGroup->join_all();\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Start\n\/\/\nbool AppInit(int argc, char* argv[])\n{\n boost::thread_group threadGroup;\n boost::thread* detectShutdownThread = NULL;\n\n bool fRet = false;\n try\n {\n \/\/\n \/\/ Parameters\n \/\/\n \/\/ If Qt is used, parameters\/bitcoin.conf are parsed in qt\/bitcoin.cpp's main()\n ParseParameters(argc, argv);\n if (!boost::filesystem::is_directory(GetDataDir(false)))\n {\n fprintf(stderr, \"Error: Specified data directory \\\"%s\\\" does not exist.\\n\", mapArgs[\"-datadir\"].c_str());\n return false;\n }\n try\n {\n ReadConfigFile(mapArgs, mapMultiArgs);\n } catch(std::exception &e) {\n fprintf(stderr,\"Error reading configuration file: %s\\n\", e.what());\n return false;\n }\n \/\/ Check for -testnet or -regtest parameter (TestNet() calls are only valid after this clause)\n if (!SelectParamsFromCommandLine()) {\n fprintf(stderr, \"Error: Invalid combination of -regtest and -testnet.\\n\");\n return false;\n }\n\n if (mapArgs.count(\"-?\") || mapArgs.count(\"--help\"))\n {\n \/\/ First part of help message is specific to bitcoind \/ RPC client\n std::string strUsage = _(\"Reddcoin Core Daemon\") + \" \" + _(\"version\") + \" \" + FormatFullVersion() + \"\\n\\n\" +\n _(\"Usage:\") + \"\\n\" +\n \" reddcoind [options] \" + _(\"Start Reddcoin Core Daemon\") + \"\\n\" +\n _(\"Usage (deprecated, use reddcoin-cli):\") + \"\\n\" +\n \" reddcoind [options] <command> [params] \" + _(\"Send command to Reddcoin Core\") + \"\\n\" +\n \" reddcoind [options] help \" + _(\"List commands\") + \"\\n\" +\n \" reddcoind [options] help <command> \" + _(\"Get help for a command\") + \"\\n\";\n\n strUsage += \"\\n\" + HelpMessage(HMM_BITCOIND);\n strUsage += \"\\n\" + HelpMessageCli(false);\n\n fprintf(stdout, \"%s\", strUsage.c_str());\n return false;\n }\n\n \/\/ Command-line RPC\n bool fCommandLine = false;\n for (int i = 1; i < argc; i++)\n if (!IsSwitchChar(argv[i][0]) && !boost::algorithm::istarts_with(argv[i], \"bitcoin:\"))\n fCommandLine = true;\n\n if (fCommandLine)\n {\n int ret = CommandLineRPC(argc, argv);\n exit(ret);\n }\n#ifndef WIN32\n fDaemon = GetBoolArg(\"-daemon\", false);\n if (fDaemon)\n {\n fprintf(stdout, \"Bitcoin server starting\\n\");\n\n \/\/ Daemonize\n pid_t pid = fork();\n if (pid < 0)\n {\n fprintf(stderr, \"Error: fork() returned %d errno %d\\n\", pid, errno);\n return false;\n }\n if (pid > 0) \/\/ Parent process, pid is child process id\n {\n CreatePidFile(GetPidFile(), pid);\n return true;\n }\n \/\/ Child process falls through to rest of initialization\n\n pid_t sid = setsid();\n if (sid < 0)\n fprintf(stderr, \"Error: setsid() returned %d errno %d\\n\", sid, errno);\n }\n#endif\n SoftSetBoolArg(\"-server\", true);\n\n detectShutdownThread = new boost::thread(boost::bind(&DetectShutdownThread, &threadGroup));\n fRet = AppInit2(threadGroup);\n }\n catch (std::exception& e) {\n PrintExceptionContinue(&e, \"AppInit()\");\n } catch (...) {\n PrintExceptionContinue(NULL, \"AppInit()\");\n }\n\n if (!fRet)\n {\n if (detectShutdownThread)\n detectShutdownThread->interrupt();\n\n threadGroup.interrupt_all();\n \/\/ threadGroup.join_all(); was left out intentionally here, because we didn't re-test all of\n \/\/ the startup-failure cases to make sure they don't result in a hang due to some\n \/\/ thread-blocking-waiting-for-another-thread-during-startup case\n }\n\n if (detectShutdownThread)\n {\n detectShutdownThread->join();\n delete detectShutdownThread;\n detectShutdownThread = NULL;\n }\n Shutdown();\n\n return fRet;\n}\n\nint main(int argc, char* argv[])\n{\n SetupEnvironment();\n\n bool fRet = false;\n\n \/\/ Connect bitcoind signal handlers\n noui_connect();\n\n fRet = AppInit(argc, argv);\n\n if (fRet && fDaemon)\n return 0;\n\n return (fRet ? 0 : 1);\n}\n<commit_msg>Update bitcoind.cpp<commit_after>\/\/ Copyright (c) 2009-2010 Satoshi Nakamoto\n\/\/ Copyright (c) 2009-2013 The Bitcoin developers\n\/\/ Distributed under the MIT\/X11 software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \"rpcserver.h\"\n#include \"rpcclient.h\"\n#include \"init.h\"\n#include \"main.h\"\n#include \"noui.h\"\n#include \"ui_interface.h\"\n#include \"util.h\"\n\n#include <boost\/algorithm\/string\/predicate.hpp>\n#include <boost\/filesystem.hpp>\n\n\/* Introduction text for doxygen: *\/\n\n\/*! \\mainpage Developer documentation\n *\n * \\section intro_sec Introduction\n *\n * This is the developer documentation of the reference client for an experimental new digital currency called Bitcoin (http:\/\/www.bitcoin.org\/),\n * which enables instant payments to anyone, anywhere in the world. Bitcoin uses peer-to-peer technology to operate\n * with no central authority: managing transactions and issuing money are carried out collectively by the network.\n *\n * The software is a community-driven open source project, released under the MIT license.\n *\n * \\section Navigation\n * Use the buttons <code>Namespaces<\/code>, <code>Classes<\/code> or <code>Files<\/code> at the top of the page to start navigating the code.\n *\/\n\nstatic bool fDaemon;\n\nvoid DetectShutdownThread(boost::thread_group* threadGroup)\n{\n bool fShutdown = ShutdownRequested();\n \/\/ Tell the main threads to shutdown.\n while (!fShutdown)\n {\n MilliSleep(200);\n fShutdown = ShutdownRequested();\n }\n if (threadGroup)\n {\n threadGroup->interrupt_all();\n threadGroup->join_all();\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Start\n\/\/\nbool AppInit(int argc, char* argv[])\n{\n boost::thread_group threadGroup;\n boost::thread* detectShutdownThread = NULL;\n\n bool fRet = false;\n try\n {\n \/\/\n \/\/ Parameters\n \/\/\n \/\/ If Qt is used, parameters\/bitcoin.conf are parsed in qt\/bitcoin.cpp's main()\n ParseParameters(argc, argv);\n if (!boost::filesystem::is_directory(GetDataDir(false)))\n {\n fprintf(stderr, \"Error: Specified data directory \\\"%s\\\" does not exist.\\n\", mapArgs[\"-datadir\"].c_str());\n return false;\n }\n try\n {\n ReadConfigFile(mapArgs, mapMultiArgs);\n } catch(std::exception &e) {\n fprintf(stderr,\"Error reading configuration file: %s\\n\", e.what());\n return false;\n }\n \/\/ Check for -testnet or -regtest parameter (TestNet() calls are only valid after this clause)\n if (!SelectParamsFromCommandLine()) {\n fprintf(stderr, \"Error: Invalid combination of -regtest and -testnet.\\n\");\n return false;\n }\n\n if (mapArgs.count(\"-?\") || mapArgs.count(\"--help\"))\n {\n \/\/ First part of help message is specific to bitcoind \/ RPC client\n std::string strUsage = _(\"Reddcoin Core Daemon\") + \" \" + _(\"version\") + \" \" + FormatFullVersion() + \"\\n\\n\" +\n _(\"Usage:\") + \"\\n\" +\n \" reddcoind [options] \" + _(\"Start Reddcoin Core Daemon\") + \"\\n\" +\n _(\"Usage (deprecated, use reddcoin-cli):\") + \"\\n\" +\n \" reddcoind [options] <command> [params] \" + _(\"Send command to Reddcoin Core\") + \"\\n\" +\n \" reddcoind [options] help \" + _(\"List commands\") + \"\\n\" +\n \" reddcoind [options] help <command> \" + _(\"Get help for a command\") + \"\\n\";\n\n strUsage += \"\\n\" + HelpMessage(HMM_BITCOIND);\n strUsage += \"\\n\" + HelpMessageCli(false);\n\n fprintf(stdout, \"%s\", strUsage.c_str());\n return false;\n }\n\n \/\/ Command-line RPC\n bool fCommandLine = false;\n for (int i = 1; i < argc; i++)\n if (!IsSwitchChar(argv[i][0]) && !boost::algorithm::istarts_with(argv[i], \"bitcoin:\"))\n fCommandLine = true;\n\n if (fCommandLine)\n {\n int ret = CommandLineRPC(argc, argv);\n exit(ret);\n }\n#ifndef WIN32\n fDaemon = GetBoolArg(\"-daemon\", false);\n if (fDaemon)\n {\n fprintf(stdout, \"Reddcoin server starting\\n\");\n\n \/\/ Daemonize\n pid_t pid = fork();\n if (pid < 0)\n {\n fprintf(stderr, \"Error: fork() returned %d errno %d\\n\", pid, errno);\n return false;\n }\n if (pid > 0) \/\/ Parent process, pid is child process id\n {\n CreatePidFile(GetPidFile(), pid);\n return true;\n }\n \/\/ Child process falls through to rest of initialization\n\n pid_t sid = setsid();\n if (sid < 0)\n fprintf(stderr, \"Error: setsid() returned %d errno %d\\n\", sid, errno);\n }\n#endif\n SoftSetBoolArg(\"-server\", true);\n\n detectShutdownThread = new boost::thread(boost::bind(&DetectShutdownThread, &threadGroup));\n fRet = AppInit2(threadGroup);\n }\n catch (std::exception& e) {\n PrintExceptionContinue(&e, \"AppInit()\");\n } catch (...) {\n PrintExceptionContinue(NULL, \"AppInit()\");\n }\n\n if (!fRet)\n {\n if (detectShutdownThread)\n detectShutdownThread->interrupt();\n\n threadGroup.interrupt_all();\n \/\/ threadGroup.join_all(); was left out intentionally here, because we didn't re-test all of\n \/\/ the startup-failure cases to make sure they don't result in a hang due to some\n \/\/ thread-blocking-waiting-for-another-thread-during-startup case\n }\n\n if (detectShutdownThread)\n {\n detectShutdownThread->join();\n delete detectShutdownThread;\n detectShutdownThread = NULL;\n }\n Shutdown();\n\n return fRet;\n}\n\nint main(int argc, char* argv[])\n{\n SetupEnvironment();\n\n bool fRet = false;\n\n \/\/ Connect bitcoind signal handlers\n noui_connect();\n\n fRet = AppInit(argc, argv);\n\n if (fRet && fDaemon)\n return 0;\n\n return (fRet ? 0 : 1);\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"bitstream.h\"\n\n#include <complex>\n\n#include \"wdsp\/wdsp.h\"\n\n#include \"filters.h\"\n\n#define FS 250000.0\n#define FC_0 57000.0\n#define IBUFLEN 4096\n#define OBUFLEN 128\n#define BITBUFLEN 1024\n\nnamespace redsea {\n\nint sign(double a) {\n return (a >= 0 ? 1 : 0);\n}\n\nBitStream::BitStream() : tot_errs_(2), reading_frame_(0), counter_(0), fsc_(FC_0), bit_buffer_(BITBUFLEN), mixer_phi_(0), clock_offset_(0), is_eof_(false), subcarr_lopass_fir_(wdsp::FIR(4000.0 \/ FS, 127)), subcarr_baseband_(IBUFLEN) {\n\n}\n\nvoid BitStream::deltaBit(int b) {\n bit_buffer_.append(b ^ dbit_);\n dbit_ = b;\n}\n\nvoid BitStream::biphase(double acc) {\n\n if (sign(acc) != sign(prev_acc_)) {\n tot_errs_[counter_ % 2] ++;\n }\n\n if (counter_ % 2 == reading_frame_) {\n deltaBit(sign(acc + prev_acc_));\n }\n if (counter_ == 0) {\n if (tot_errs_[1 - reading_frame_] < tot_errs_[reading_frame_]) {\n reading_frame_ = 1 - reading_frame_;\n }\n tot_errs_[0] = 0;\n tot_errs_[1] = 0;\n }\n\n prev_acc_ = acc;\n counter_ = (counter_ + 1) % 800;\n}\n\n\nvoid BitStream::demodulateMoreBits() {\n\n int16_t sample[IBUFLEN];\n int bytesread = fread(sample, sizeof(int16_t), IBUFLEN, stdin);\n if (bytesread < IBUFLEN) {\n is_eof_ = true;\n return;\n }\n\n for (int i = 0; i < bytesread; i++) {\n\n \/* Subcarrier downmix & phase recovery *\/\n\n mixer_phi_ += 2 * M_PI * fsc_ * (1.0\/FS);\n subcarr_baseband_.appendOverlapFiltered(wdsp::mix(sample[i] \/ 32768.0, mixer_phi_),\n subcarr_lopass_fir_);\n\n double pll_beta = 2e-3;\n\n std::complex<double> sc_sample = subcarr_baseband_.getNext();\n\n double phi1 = arg(sc_sample);\n if (phi1 >= M_PI_2) {\n phi1 -= M_PI;\n } else if (phi1 <= -M_PI_2) {\n phi1 += M_PI;\n }\n\n mixer_phi_ -= pll_beta * phi1;\n fsc_ -= .5 * pll_beta * phi1;\n\n \/* 1187.5 Hz clock *\/\n\n double clock_phi = mixer_phi_ \/ 48.0 + clock_offset_;\n double lo_clock = (fmod(clock_phi, 2*M_PI) < M_PI ? 1 : -1);\n\n \/* Clock phase recovery *\/\n\n if (sign(prev_bb_) != sign(real(sc_sample))) {\n double d_cphi = fmod(clock_phi, M_PI);\n if (d_cphi >= M_PI_2) d_cphi -= M_PI;\n clock_offset_ -= 0.005 * d_cphi;\n }\n\n \/* Decimate band-limited signal *\/\n if (numsamples_ % 8 == 0) {\n\n \/* biphase symbol integrate & dump *\/\n acc_ += real(sc_sample) * lo_clock;\n\n if (sign(lo_clock) != sign(prevclock_)) {\n biphase(acc_);\n acc_ = 0;\n }\n\n prevclock_ = lo_clock;\n }\n\n numsamples_ ++;\n\n prev_bb_ = real(sc_sample);\n\n }\n\n}\n\nint BitStream::getNextBit() {\n while (bit_buffer_.getFillCount() < 1 && !isEOF())\n demodulateMoreBits();\n\n int result = bit_buffer_.getNext();\n \/\/printf(\"read %d, write %d, fill count %d\\n\",bit_buffer_read_ptr_, bit_buffer_write_ptr_, bit_buffer_fill_count_);\n return result;\n}\n\nbool BitStream::isEOF() const {\n return is_eof_;\n}\n\n} \/\/ namespace redsea\n<commit_msg>move some code to low-throughput side<commit_after>#include \"bitstream.h\"\n\n#include <complex>\n\n#include \"wdsp\/wdsp.h\"\n\n#include \"filters.h\"\n\n#define FS 250000.0\n#define FC_0 57000.0\n#define IBUFLEN 4096\n#define OBUFLEN 128\n#define BITBUFLEN 1024\n\nnamespace redsea {\n\nint sign(double a) {\n return (a >= 0 ? 1 : 0);\n}\n\nBitStream::BitStream() : tot_errs_(2), reading_frame_(0), counter_(0), fsc_(FC_0), bit_buffer_(BITBUFLEN), mixer_phi_(0), clock_offset_(0), is_eof_(false), subcarr_lopass_fir_(wdsp::FIR(4000.0 \/ FS, 127)), subcarr_baseband_(IBUFLEN) {\n\n}\n\nvoid BitStream::deltaBit(int b) {\n bit_buffer_.append(b ^ dbit_);\n dbit_ = b;\n}\n\nvoid BitStream::biphase(double acc) {\n\n if (sign(acc) != sign(prev_acc_)) {\n tot_errs_[counter_ % 2] ++;\n }\n\n if (counter_ % 2 == reading_frame_) {\n deltaBit(sign(acc + prev_acc_));\n }\n if (counter_ == 0) {\n if (tot_errs_[1 - reading_frame_] < tot_errs_[reading_frame_]) {\n reading_frame_ = 1 - reading_frame_;\n }\n tot_errs_[0] = 0;\n tot_errs_[1] = 0;\n }\n\n prev_acc_ = acc;\n counter_ = (counter_ + 1) % 800;\n}\n\n\nvoid BitStream::demodulateMoreBits() {\n\n int16_t sample[IBUFLEN];\n int bytesread = fread(sample, sizeof(int16_t), IBUFLEN, stdin);\n if (bytesread < IBUFLEN) {\n is_eof_ = true;\n return;\n }\n\n for (int i = 0; i < bytesread; i++) {\n\n \/* Subcarrier downmix & phase recovery *\/\n\n mixer_phi_ += 2 * M_PI * fsc_ * (1.0\/FS);\n subcarr_baseband_.appendOverlapFiltered(wdsp::mix(sample[i] \/ 32768.0,\n mixer_phi_), subcarr_lopass_fir_);\n\n double pll_beta = 16e-3;\n\n \/* Decimate band-limited signal *\/\n if (numsamples_ % 8 == 0) {\n\n std::complex<double> sc_sample = subcarr_baseband_.at(0);\n subcarr_baseband_.forward(8);\n\n double phi1 = arg(sc_sample);\n if (phi1 >= M_PI_2) {\n phi1 -= M_PI;\n } else if (phi1 <= -M_PI_2) {\n phi1 += M_PI;\n }\n\n mixer_phi_ -= pll_beta * phi1;\n fsc_ -= .5 * pll_beta * phi1;\n\n \/* 1187.5 Hz clock *\/\n\n double clock_phi = mixer_phi_ \/ 48.0 + clock_offset_;\n double lo_clock = (fmod(clock_phi, 2*M_PI) < M_PI ? 1 : -1);\n\n \/* Clock phase recovery *\/\n\n if (sign(prev_bb_) != sign(real(sc_sample))) {\n double d_cphi = fmod(clock_phi, M_PI);\n if (d_cphi >= M_PI_2) d_cphi -= M_PI;\n clock_offset_ -= 0.005 * d_cphi;\n }\n\n \/* biphase symbol integrate & dump *\/\n acc_ += real(sc_sample) * lo_clock;\n\n if (sign(lo_clock) != sign(prevclock_)) {\n biphase(acc_);\n acc_ = 0;\n }\n\n prevclock_ = lo_clock;\n prev_bb_ = real(sc_sample);\n }\n\n numsamples_ ++;\n\n }\n\n}\n\nint BitStream::getNextBit() {\n while (bit_buffer_.getFillCount() < 1 && !isEOF())\n demodulateMoreBits();\n\n int result = bit_buffer_.getNext();\n \/\/printf(\"read %d, write %d, fill count %d\\n\",bit_buffer_read_ptr_, bit_buffer_write_ptr_, bit_buffer_fill_count_);\n return result;\n}\n\nbool BitStream::isEOF() const {\n return is_eof_;\n}\n\n} \/\/ namespace redsea\n<|endoftext|>"} {"text":"<commit_before>\/****************************************************************************\n**\n** Copyright (c) 2008-2009 Nokia Corporation and\/or its subsidiary(-ies).\n**\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n** This file is part of the Qt Mobility Components.\n**\n** $QT_BEGIN_LICENSE:LGPL$\n** No Commercial Usage\n** This file contains pre-release code and may not be distributed.\n** You may use this file in accordance with the terms and conditions\n** contained in the Technology Preview License Agreement accompanying\n** this package.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Nokia gives you certain\n** additional rights. These rights are described in the Nokia Qt LGPL\n** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this\n** package.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at http:\/\/qt.nokia.com\/contact.\n** $QT_END_LICENSE$\n**\n****************************************************************************\/\n\n#include <QtTest\/QtTest>\n#include <QDebug>\n#include \"qmediaplaylist.h\"\n\nclass tst_QMediaPlaylist : public QObject\n{\n Q_OBJECT\npublic slots:\n void init();\n void cleanup();\n\nprivate slots:\n void construction();\n void append();\n void currentItem();\n};\n\nvoid tst_QMediaPlaylist::init()\n{\n}\n\nvoid tst_QMediaPlaylist::cleanup()\n{\n}\n\nvoid tst_QMediaPlaylist::construction()\n{\n QMediaPlaylist playlist;\n QCOMPARE(playlist.size(), 0);\n QVERIFY(playlist.isEmpty());\n}\n\nvoid tst_QMediaPlaylist::append()\n{\n QMediaPlaylist playlist;\n QVERIFY(!playlist.isReadOnly());\n\n QMediaSource source1(QUrl(QLatin1String(\"file:\/\/\/1\")));\n playlist.appendItem(source1);\n QCOMPARE(playlist.size(), 1);\n QCOMPARE(playlist.media(0), source1);\n\n QMediaSource source2(QUrl(QLatin1String(\"file:\/\/\/2\")));\n playlist.appendItem(source2);\n QCOMPARE(playlist.size(), 2);\n QCOMPARE(playlist.media(1), source2);\n}\n\nvoid tst_QMediaPlaylist::currentItem()\n{\n QMediaPlaylist playlist;\n\n QMediaSource source1(QUrl(QLatin1String(\"file:\/\/\/1\")));\n playlist.appendItem(source1);\n\n QMediaSource source2(QUrl(QLatin1String(\"file:\/\/\/2\")));\n playlist.appendItem(source2);\n\n QCOMPARE(playlist.currentPosition(), -1);\n QCOMPARE(playlist.currentMedia(), QMediaSource());\n\n QCOMPARE(playlist.nextPosition(), 0);\n QCOMPARE(playlist.nextPosition(2), 1);\n QCOMPARE(playlist.previousPosition(), -1);\n QCOMPARE(playlist.previousPosition(2), -1);\n\n playlist.setCurrentPosition(0);\n QCOMPARE(playlist.currentPosition(), 0);\n QCOMPARE(playlist.currentMedia(), source1);\n\n QCOMPARE(playlist.nextPosition(), 1);\n QCOMPARE(playlist.nextPosition(2), -1);\n QCOMPARE(playlist.previousPosition(), -1);\n QCOMPARE(playlist.previousPosition(2), -1);\n\n playlist.setCurrentPosition(1);\n QCOMPARE(playlist.currentPosition(), 1);\n QCOMPARE(playlist.currentMedia(), source2);\n\n playlist.setCurrentPosition(2); \/\/warning is expected\n QCOMPARE(playlist.currentPosition(), 1);\n QCOMPARE(playlist.currentMedia(), source2);\n\n QCOMPARE(playlist.nextPosition(), -1);\n QCOMPARE(playlist.nextPosition(2), -1);\n QCOMPARE(playlist.previousPosition(), 0);\n QCOMPARE(playlist.previousPosition(2), -1);\n}\n\nQTEST_MAIN(tst_QMediaPlaylist)\n#include \"tst_qmediaplaylist.moc\"\n\n<commit_msg>added more qmediaplaylist related tests<commit_after>\/****************************************************************************\n**\n** Copyright (c) 2008-2009 Nokia Corporation and\/or its subsidiary(-ies).\n**\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n** This file is part of the Qt Mobility Components.\n**\n** $QT_BEGIN_LICENSE:LGPL$\n** No Commercial Usage\n** This file contains pre-release code and may not be distributed.\n** You may use this file in accordance with the terms and conditions\n** contained in the Technology Preview License Agreement accompanying\n** this package.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Nokia gives you certain\n** additional rights. These rights are described in the Nokia Qt LGPL\n** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this\n** package.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at http:\/\/qt.nokia.com\/contact.\n** $QT_END_LICENSE$\n**\n****************************************************************************\/\n\n#include <QtTest\/QtTest>\n#include <QDebug>\n#include \"qmediaplaylist.h\"\n\nclass tst_QMediaPlaylist : public QObject\n{\n Q_OBJECT\npublic slots:\n void init();\n void cleanup();\n void initTestCase();\n\nprivate slots:\n void construction();\n void append();\n void insert();\n void clear();\n void removeItems();\n void currentItem();\n void saveAndLoad();\n\nprivate:\n QMediaSource source1;\n QMediaSource source2;\n QMediaSource source3;\n};\n\nvoid tst_QMediaPlaylist::init()\n{\n}\n\nvoid tst_QMediaPlaylist::initTestCase()\n{\n source1 = QMediaSource(QUrl(QLatin1String(\"file:\/\/\/1\")));\n source2 = QMediaSource(QUrl(QLatin1String(\"file:\/\/\/2\")));\n source3 = QMediaSource(QUrl(QLatin1String(\"file:\/\/\/3\")));\n}\n\nvoid tst_QMediaPlaylist::cleanup()\n{\n}\n\nvoid tst_QMediaPlaylist::construction()\n{\n QMediaPlaylist playlist;\n QCOMPARE(playlist.size(), 0);\n QVERIFY(playlist.isEmpty());\n}\n\nvoid tst_QMediaPlaylist::append()\n{\n QMediaPlaylist playlist;\n QVERIFY(!playlist.isReadOnly());\n\n playlist.appendItem(source1);\n QCOMPARE(playlist.size(), 1);\n QCOMPARE(playlist.media(0), source1);\n\n playlist.appendItem(source2);\n QCOMPARE(playlist.size(), 2);\n QCOMPARE(playlist.media(1), source2);\n}\n\nvoid tst_QMediaPlaylist::insert()\n{\n QMediaPlaylist playlist;\n QVERIFY(!playlist.isReadOnly());\n\n playlist.appendItem(source1);\n QCOMPARE(playlist.size(), 1);\n QCOMPARE(playlist.media(0), source1);\n\n playlist.appendItem(source2);\n QCOMPARE(playlist.size(), 2);\n QCOMPARE(playlist.media(1), source2);\n\n QSignalSpy aboutToBeInsertedSignalSpy(&playlist, SIGNAL(itemsAboutToBeInserted(int,int)));\n QSignalSpy insertedSignalSpy(&playlist, SIGNAL(itemsInserted(int,int)));\n\n playlist.insertItem(1, source3);\n QCOMPARE(playlist.size(), 3);\n QCOMPARE(playlist.media(0), source1);\n QCOMPARE(playlist.media(1), source3);\n QCOMPARE(playlist.media(2), source2);\n\n QCOMPARE(aboutToBeInsertedSignalSpy.count(), 1);\n QCOMPARE(aboutToBeInsertedSignalSpy.first()[0].toInt(), 1);\n QCOMPARE(aboutToBeInsertedSignalSpy.first()[1].toInt(), 1);\n\n QCOMPARE(insertedSignalSpy.count(), 1);\n QCOMPARE(insertedSignalSpy.first()[0].toInt(), 1);\n QCOMPARE(insertedSignalSpy.first()[1].toInt(), 1);\n}\n\n\nvoid tst_QMediaPlaylist::currentItem()\n{\n QMediaPlaylist playlist;\n playlist.appendItem(source1);\n playlist.appendItem(source2);\n\n QCOMPARE(playlist.currentPosition(), -1);\n QCOMPARE(playlist.currentMedia(), QMediaSource());\n\n QCOMPARE(playlist.nextPosition(), 0);\n QCOMPARE(playlist.nextPosition(2), 1);\n QCOMPARE(playlist.previousPosition(), -1);\n QCOMPARE(playlist.previousPosition(2), -1);\n\n playlist.setCurrentPosition(0);\n QCOMPARE(playlist.currentPosition(), 0);\n QCOMPARE(playlist.currentMedia(), source1);\n\n QCOMPARE(playlist.nextPosition(), 1);\n QCOMPARE(playlist.nextPosition(2), -1);\n QCOMPARE(playlist.previousPosition(), -1);\n QCOMPARE(playlist.previousPosition(2), -1);\n\n playlist.setCurrentPosition(1);\n QCOMPARE(playlist.currentPosition(), 1);\n QCOMPARE(playlist.currentMedia(), source2);\n\n playlist.setCurrentPosition(2); \/\/warning is expected\n QCOMPARE(playlist.currentPosition(), 1);\n QCOMPARE(playlist.currentMedia(), source2);\n\n QCOMPARE(playlist.nextPosition(), -1);\n QCOMPARE(playlist.nextPosition(2), -1);\n QCOMPARE(playlist.previousPosition(), 0);\n QCOMPARE(playlist.previousPosition(2), -1);\n}\n\nvoid tst_QMediaPlaylist::clear()\n{\n QMediaPlaylist playlist;\n playlist.appendItem(source1);\n playlist.appendItem(source2);\n\n playlist.clear();\n QVERIFY(playlist.isEmpty());\n QCOMPARE(playlist.size(), 0);\n}\n\nvoid tst_QMediaPlaylist::removeItems()\n{\n QMediaPlaylist playlist;\n playlist.appendItem(source1);\n playlist.appendItem(source2);\n playlist.appendItem(source3);\n\n QSignalSpy aboutToBeRemovedSignalSpy(&playlist, SIGNAL(itemsAboutToBeRemoved(int,int)));\n QSignalSpy removedSignalSpy(&playlist, SIGNAL(itemsRemoved(int,int)));\n playlist.removeItem(1);\n QCOMPARE(playlist.size(), 2);\n QCOMPARE(playlist.media(1), source3);\n\n QCOMPARE(aboutToBeRemovedSignalSpy.count(), 1);\n QCOMPARE(aboutToBeRemovedSignalSpy.first()[0].toInt(), 1);\n QCOMPARE(aboutToBeRemovedSignalSpy.first()[1].toInt(), 1);\n\n QCOMPARE(removedSignalSpy.count(), 1);\n QCOMPARE(removedSignalSpy.first()[0].toInt(), 1);\n QCOMPARE(removedSignalSpy.first()[1].toInt(), 1);\n\n aboutToBeRemovedSignalSpy.clear();\n removedSignalSpy.clear();\n\n playlist.removeItems(0,1);\n QVERIFY(playlist.isEmpty());\n\n QCOMPARE(aboutToBeRemovedSignalSpy.count(), 1);\n QCOMPARE(aboutToBeRemovedSignalSpy.first()[0].toInt(), 0);\n QCOMPARE(aboutToBeRemovedSignalSpy.first()[1].toInt(), 1);\n\n QCOMPARE(removedSignalSpy.count(), 1);\n QCOMPARE(removedSignalSpy.first()[0].toInt(), 0);\n QCOMPARE(removedSignalSpy.first()[1].toInt(), 1);\n\n\n playlist.appendItem(source1);\n playlist.appendItem(source2);\n playlist.appendItem(source3);\n\n playlist.removeItems(0,1);\n QCOMPARE(playlist.size(), 1);\n QCOMPARE(playlist.media(0), source3);\n}\n\nvoid tst_QMediaPlaylist::saveAndLoad()\n{\n \/*\n QMediaPlaylist playlist;\n playlist.appendItem(source1);\n playlist.appendItem(source2);\n playlist.appendItem(source3);\n\n QBuffer buffer;\n buffer.open(QBuffer::ReadWrite);\n\n bool res = playlist.save(&buffer, \"m3u\");\n\n QVERIFY(res);\n QVERIFY(buffer.pos() > 0);\n buffer.seek(0);\n\n QMediaPlaylist playlist2;\n res = playlist2.load(&buffer, \"m3u\");\n QVERIFY(res);\n QCOMPARE(playlist.size(), playlist2.size());\n QCOMPARE(playlist.media(0), playlist2.media(0));\n *\/\n}\n\nQTEST_MAIN(tst_QMediaPlaylist)\n#include \"tst_qmediaplaylist.moc\"\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2014, Facebook, Inc. All rights reserved.\n\/\/ This source code is licensed under the BSD-style license found in the\n\/\/ LICENSE file in the root directory of this source tree. An additional grant\n\/\/ of patent rights can be found in the PATENTS file in the same directory.\n\/\/\n\/\/ Copyright (c) 2011 The LevelDB Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file. See the AUTHORS file for names of contributors.\n\n#ifndef ROCKSDB_LITE\n#include \"table\/cuckoo_table_reader.h\"\n\n#include <algorithm>\n#include <limits>\n#include <string>\n#include <utility>\n#include <vector>\n#include \"rocksdb\/iterator.h\"\n#include \"rocksdb\/table.h\"\n#include \"table\/meta_blocks.h\"\n#include \"table\/cuckoo_table_factory.h\"\n#include \"table\/get_context.h\"\n#include \"util\/arena.h\"\n#include \"util\/coding.h\"\n\nnamespace rocksdb {\nnamespace {\nconst uint64_t CACHE_LINE_MASK = ~((uint64_t)CACHE_LINE_SIZE - 1);\nconst uint32_t kInvalidIndex = std::numeric_limits<uint32_t>::max();\n}\n\nextern const uint64_t kCuckooTableMagicNumber;\n\nCuckooTableReader::CuckooTableReader(\n const ImmutableCFOptions& ioptions,\n std::unique_ptr<RandomAccessFile>&& file,\n uint64_t file_size,\n const Comparator* comparator,\n uint64_t (*get_slice_hash)(const Slice&, uint32_t, uint64_t))\n : file_(std::move(file)),\n ucomp_(comparator),\n get_slice_hash_(get_slice_hash) {\n if (!ioptions.allow_mmap_reads) {\n status_ = Status::InvalidArgument(\"File is not mmaped\");\n }\n TableProperties* props = nullptr;\n status_ = ReadTableProperties(file_.get(), file_size, kCuckooTableMagicNumber,\n ioptions.env, ioptions.info_log, &props);\n if (!status_.ok()) {\n return;\n }\n table_props_.reset(props);\n auto& user_props = props->user_collected_properties;\n auto hash_funs = user_props.find(CuckooTablePropertyNames::kNumHashFunc);\n if (hash_funs == user_props.end()) {\n status_ = Status::Corruption(\"Number of hash functions not found\");\n return;\n }\n num_hash_func_ = *reinterpret_cast<const uint32_t*>(hash_funs->second.data());\n auto unused_key = user_props.find(CuckooTablePropertyNames::kEmptyKey);\n if (unused_key == user_props.end()) {\n status_ = Status::Corruption(\"Empty bucket value not found\");\n return;\n }\n unused_key_ = unused_key->second;\n\n key_length_ = props->fixed_key_len;\n auto user_key_len = user_props.find(CuckooTablePropertyNames::kUserKeyLength);\n if (user_key_len == user_props.end()) {\n status_ = Status::Corruption(\"User key length not found\");\n return;\n }\n user_key_length_ = *reinterpret_cast<const uint32_t*>(\n user_key_len->second.data());\n\n auto value_length = user_props.find(CuckooTablePropertyNames::kValueLength);\n if (value_length == user_props.end()) {\n status_ = Status::Corruption(\"Value length not found\");\n return;\n }\n value_length_ = *reinterpret_cast<const uint32_t*>(\n value_length->second.data());\n bucket_length_ = key_length_ + value_length_;\n\n auto hash_table_size = user_props.find(\n CuckooTablePropertyNames::kHashTableSize);\n if (hash_table_size == user_props.end()) {\n status_ = Status::Corruption(\"Hash table size not found\");\n return;\n }\n table_size_ = *reinterpret_cast<const uint64_t*>(\n hash_table_size->second.data());\n\n auto is_last_level = user_props.find(CuckooTablePropertyNames::kIsLastLevel);\n if (is_last_level == user_props.end()) {\n status_ = Status::Corruption(\"Is last level not found\");\n return;\n }\n is_last_level_ = *reinterpret_cast<const bool*>(is_last_level->second.data());\n\n auto identity_as_first_hash = user_props.find(\n CuckooTablePropertyNames::kIdentityAsFirstHash);\n if (identity_as_first_hash == user_props.end()) {\n status_ = Status::Corruption(\"identity as first hash not found\");\n return;\n }\n identity_as_first_hash_ = *reinterpret_cast<const bool*>(\n identity_as_first_hash->second.data());\n\n auto use_module_hash = user_props.find(\n CuckooTablePropertyNames::kUseModuleHash);\n if (use_module_hash == user_props.end()) {\n status_ = Status::Corruption(\"hash type is not found\");\n return;\n }\n use_module_hash_ = *reinterpret_cast<const bool*>(\n use_module_hash->second.data());\n auto cuckoo_block_size = user_props.find(\n CuckooTablePropertyNames::kCuckooBlockSize);\n if (cuckoo_block_size == user_props.end()) {\n status_ = Status::Corruption(\"Cuckoo block size not found\");\n return;\n }\n cuckoo_block_size_ = *reinterpret_cast<const uint32_t*>(\n cuckoo_block_size->second.data());\n cuckoo_block_bytes_minus_one_ = cuckoo_block_size_ * bucket_length_ - 1;\n status_ = file_->Read(0, file_size, &file_data_, nullptr);\n}\n\nStatus CuckooTableReader::Get(const ReadOptions& readOptions, const Slice& key,\n GetContext* get_context) {\n assert(key.size() == key_length_ + (is_last_level_ ? 8 : 0));\n Slice user_key = ExtractUserKey(key);\n for (uint32_t hash_cnt = 0; hash_cnt < num_hash_func_; ++hash_cnt) {\n uint64_t offset = bucket_length_ * CuckooHash(\n user_key, hash_cnt, use_module_hash_, table_size_,\n identity_as_first_hash_, get_slice_hash_);\n const char* bucket = &file_data_.data()[offset];\n for (uint32_t block_idx = 0; block_idx < cuckoo_block_size_;\n ++block_idx, bucket += bucket_length_) {\n if (ucomp_->Compare(Slice(unused_key_.data(), user_key.size()),\n Slice(bucket, user_key.size())) == 0) {\n return Status::OK();\n }\n \/\/ Here, we compare only the user key part as we support only one entry\n \/\/ per user key and we don't support sanpshot.\n if (ucomp_->Compare(user_key, Slice(bucket, user_key.size())) == 0) {\n Slice value(bucket + key_length_, value_length_);\n if (is_last_level_) {\n get_context->SaveValue(value);\n } else {\n Slice full_key(bucket, key_length_);\n ParsedInternalKey found_ikey;\n ParseInternalKey(full_key, &found_ikey);\n get_context->SaveValue(found_ikey, value);\n }\n \/\/ We don't support merge operations. So, we return here.\n return Status::OK();\n }\n }\n }\n return Status::OK();\n}\n\nvoid CuckooTableReader::Prepare(const Slice& key) {\n \/\/ Prefetch the first Cuckoo Block.\n Slice user_key = ExtractUserKey(key);\n uint64_t addr = reinterpret_cast<uint64_t>(file_data_.data()) +\n bucket_length_ * CuckooHash(user_key, 0, use_module_hash_, table_size_,\n identity_as_first_hash_, nullptr);\n uint64_t end_addr = addr + cuckoo_block_bytes_minus_one_;\n for (addr &= CACHE_LINE_MASK; addr < end_addr; addr += CACHE_LINE_SIZE) {\n PREFETCH(reinterpret_cast<const char*>(addr), 0, 3);\n }\n}\n\nclass CuckooTableIterator : public Iterator {\n public:\n explicit CuckooTableIterator(CuckooTableReader* reader);\n ~CuckooTableIterator() {}\n bool Valid() const override;\n void SeekToFirst() override;\n void SeekToLast() override;\n void Seek(const Slice& target) override;\n void Next() override;\n void Prev() override;\n Slice key() const override;\n Slice value() const override;\n Status status() const override { return status_; }\n void InitIfNeeded();\n\n private:\n struct BucketComparator {\n BucketComparator(const Slice& file_data, const Comparator* ucomp,\n uint32_t bucket_len, uint32_t user_key_len,\n const Slice target = Slice())\n : file_data_(file_data),\n ucomp_(ucomp),\n bucket_len_(bucket_len),\n user_key_len_(user_key_len),\n target_(target) {}\n bool operator()(const uint32_t first, const uint32_t second) const {\n const char* first_bucket =\n (first == kInvalidIndex) ? target_.data() :\n &file_data_.data()[first * bucket_len_];\n const char* second_bucket =\n (second == kInvalidIndex) ? target_.data() :\n &file_data_.data()[second * bucket_len_];\n return ucomp_->Compare(Slice(first_bucket, user_key_len_),\n Slice(second_bucket, user_key_len_)) < 0;\n }\n private:\n const Slice file_data_;\n const Comparator* ucomp_;\n const uint32_t bucket_len_;\n const uint32_t user_key_len_;\n const Slice target_;\n };\n\n const BucketComparator bucket_comparator_;\n void PrepareKVAtCurrIdx();\n CuckooTableReader* reader_;\n bool initialized_;\n Status status_;\n \/\/ Contains a map of keys to bucket_id sorted in key order.\n std::vector<uint32_t> sorted_bucket_ids_;\n \/\/ We assume that the number of items can be stored in uint32 (4 Billion).\n uint32_t curr_key_idx_;\n Slice curr_value_;\n IterKey curr_key_;\n \/\/ No copying allowed\n CuckooTableIterator(const CuckooTableIterator&) = delete;\n void operator=(const Iterator&) = delete;\n};\n\nCuckooTableIterator::CuckooTableIterator(CuckooTableReader* reader)\n : bucket_comparator_(reader->file_data_, reader->ucomp_,\n reader->bucket_length_, reader->user_key_length_),\n reader_(reader),\n initialized_(false),\n curr_key_idx_(kInvalidIndex) {\n sorted_bucket_ids_.clear();\n curr_value_.clear();\n curr_key_.Clear();\n}\n\nvoid CuckooTableIterator::InitIfNeeded() {\n if (initialized_) {\n return;\n }\n sorted_bucket_ids_.reserve(reader_->GetTableProperties()->num_entries);\n uint64_t num_buckets = reader_->table_size_ + reader_->cuckoo_block_size_ - 1;\n assert(num_buckets < kInvalidIndex);\n const char* bucket = reader_->file_data_.data();\n for (uint32_t bucket_id = 0; bucket_id < num_buckets; ++bucket_id) {\n if (Slice(bucket, reader_->key_length_) != Slice(reader_->unused_key_)) {\n sorted_bucket_ids_.push_back(bucket_id);\n }\n bucket += reader_->bucket_length_;\n }\n assert(sorted_bucket_ids_.size() ==\n reader_->GetTableProperties()->num_entries);\n std::sort(sorted_bucket_ids_.begin(), sorted_bucket_ids_.end(),\n bucket_comparator_);\n curr_key_idx_ = kInvalidIndex;\n initialized_ = true;\n}\n\nvoid CuckooTableIterator::SeekToFirst() {\n InitIfNeeded();\n curr_key_idx_ = 0;\n PrepareKVAtCurrIdx();\n}\n\nvoid CuckooTableIterator::SeekToLast() {\n InitIfNeeded();\n curr_key_idx_ = sorted_bucket_ids_.size() - 1;\n PrepareKVAtCurrIdx();\n}\n\nvoid CuckooTableIterator::Seek(const Slice& target) {\n InitIfNeeded();\n const BucketComparator seek_comparator(\n reader_->file_data_, reader_->ucomp_,\n reader_->bucket_length_, reader_->user_key_length_,\n ExtractUserKey(target));\n auto seek_it = std::lower_bound(sorted_bucket_ids_.begin(),\n sorted_bucket_ids_.end(),\n kInvalidIndex,\n seek_comparator);\n curr_key_idx_ = std::distance(sorted_bucket_ids_.begin(), seek_it);\n PrepareKVAtCurrIdx();\n}\n\nbool CuckooTableIterator::Valid() const {\n return curr_key_idx_ < sorted_bucket_ids_.size();\n}\n\nvoid CuckooTableIterator::PrepareKVAtCurrIdx() {\n if (!Valid()) {\n curr_value_.clear();\n curr_key_.Clear();\n return;\n }\n uint32_t id = sorted_bucket_ids_[curr_key_idx_];\n const char* offset = reader_->file_data_.data() +\n id * reader_->bucket_length_;\n if (reader_->is_last_level_) {\n \/\/ Always return internal key.\n curr_key_.SetInternalKey(Slice(offset, reader_->user_key_length_),\n 0, kTypeValue);\n } else {\n curr_key_.SetKey(Slice(offset, reader_->key_length_));\n }\n curr_value_ = Slice(offset + reader_->key_length_, reader_->value_length_);\n}\n\nvoid CuckooTableIterator::Next() {\n if (!Valid()) {\n curr_value_.clear();\n curr_key_.Clear();\n return;\n }\n ++curr_key_idx_;\n PrepareKVAtCurrIdx();\n}\n\nvoid CuckooTableIterator::Prev() {\n if (curr_key_idx_ == 0) {\n curr_key_idx_ = sorted_bucket_ids_.size();\n }\n if (!Valid()) {\n curr_value_.clear();\n curr_key_.Clear();\n return;\n }\n --curr_key_idx_;\n PrepareKVAtCurrIdx();\n}\n\nSlice CuckooTableIterator::key() const {\n assert(Valid());\n return curr_key_.GetKey();\n}\n\nSlice CuckooTableIterator::value() const {\n assert(Valid());\n return curr_value_;\n}\n\nextern Iterator* NewErrorIterator(const Status& status, Arena* arena);\n\nIterator* CuckooTableReader::NewIterator(\n const ReadOptions& read_options, Arena* arena) {\n if (!status().ok()) {\n return NewErrorIterator(\n Status::Corruption(\"CuckooTableReader status is not okay.\"), arena);\n }\n if (read_options.total_order_seek) {\n return NewErrorIterator(\n Status::InvalidArgument(\"total_order_seek is not supported.\"), arena);\n }\n CuckooTableIterator* iter;\n if (arena == nullptr) {\n iter = new CuckooTableIterator(this);\n } else {\n auto iter_mem = arena->AllocateAligned(sizeof(CuckooTableIterator));\n iter = new (iter_mem) CuckooTableIterator(this);\n }\n return iter;\n}\n\nsize_t CuckooTableReader::ApproximateMemoryUsage() const { return 0; }\n\n} \/\/ namespace rocksdb\n#endif\n<commit_msg>table\/cuckoo_table_reader.cc: pass func parameter by reference<commit_after>\/\/ Copyright (c) 2014, Facebook, Inc. All rights reserved.\n\/\/ This source code is licensed under the BSD-style license found in the\n\/\/ LICENSE file in the root directory of this source tree. An additional grant\n\/\/ of patent rights can be found in the PATENTS file in the same directory.\n\/\/\n\/\/ Copyright (c) 2011 The LevelDB Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file. See the AUTHORS file for names of contributors.\n\n#ifndef ROCKSDB_LITE\n#include \"table\/cuckoo_table_reader.h\"\n\n#include <algorithm>\n#include <limits>\n#include <string>\n#include <utility>\n#include <vector>\n#include \"rocksdb\/iterator.h\"\n#include \"rocksdb\/table.h\"\n#include \"table\/meta_blocks.h\"\n#include \"table\/cuckoo_table_factory.h\"\n#include \"table\/get_context.h\"\n#include \"util\/arena.h\"\n#include \"util\/coding.h\"\n\nnamespace rocksdb {\nnamespace {\nconst uint64_t CACHE_LINE_MASK = ~((uint64_t)CACHE_LINE_SIZE - 1);\nconst uint32_t kInvalidIndex = std::numeric_limits<uint32_t>::max();\n}\n\nextern const uint64_t kCuckooTableMagicNumber;\n\nCuckooTableReader::CuckooTableReader(\n const ImmutableCFOptions& ioptions,\n std::unique_ptr<RandomAccessFile>&& file,\n uint64_t file_size,\n const Comparator* comparator,\n uint64_t (*get_slice_hash)(const Slice&, uint32_t, uint64_t))\n : file_(std::move(file)),\n ucomp_(comparator),\n get_slice_hash_(get_slice_hash) {\n if (!ioptions.allow_mmap_reads) {\n status_ = Status::InvalidArgument(\"File is not mmaped\");\n }\n TableProperties* props = nullptr;\n status_ = ReadTableProperties(file_.get(), file_size, kCuckooTableMagicNumber,\n ioptions.env, ioptions.info_log, &props);\n if (!status_.ok()) {\n return;\n }\n table_props_.reset(props);\n auto& user_props = props->user_collected_properties;\n auto hash_funs = user_props.find(CuckooTablePropertyNames::kNumHashFunc);\n if (hash_funs == user_props.end()) {\n status_ = Status::Corruption(\"Number of hash functions not found\");\n return;\n }\n num_hash_func_ = *reinterpret_cast<const uint32_t*>(hash_funs->second.data());\n auto unused_key = user_props.find(CuckooTablePropertyNames::kEmptyKey);\n if (unused_key == user_props.end()) {\n status_ = Status::Corruption(\"Empty bucket value not found\");\n return;\n }\n unused_key_ = unused_key->second;\n\n key_length_ = props->fixed_key_len;\n auto user_key_len = user_props.find(CuckooTablePropertyNames::kUserKeyLength);\n if (user_key_len == user_props.end()) {\n status_ = Status::Corruption(\"User key length not found\");\n return;\n }\n user_key_length_ = *reinterpret_cast<const uint32_t*>(\n user_key_len->second.data());\n\n auto value_length = user_props.find(CuckooTablePropertyNames::kValueLength);\n if (value_length == user_props.end()) {\n status_ = Status::Corruption(\"Value length not found\");\n return;\n }\n value_length_ = *reinterpret_cast<const uint32_t*>(\n value_length->second.data());\n bucket_length_ = key_length_ + value_length_;\n\n auto hash_table_size = user_props.find(\n CuckooTablePropertyNames::kHashTableSize);\n if (hash_table_size == user_props.end()) {\n status_ = Status::Corruption(\"Hash table size not found\");\n return;\n }\n table_size_ = *reinterpret_cast<const uint64_t*>(\n hash_table_size->second.data());\n\n auto is_last_level = user_props.find(CuckooTablePropertyNames::kIsLastLevel);\n if (is_last_level == user_props.end()) {\n status_ = Status::Corruption(\"Is last level not found\");\n return;\n }\n is_last_level_ = *reinterpret_cast<const bool*>(is_last_level->second.data());\n\n auto identity_as_first_hash = user_props.find(\n CuckooTablePropertyNames::kIdentityAsFirstHash);\n if (identity_as_first_hash == user_props.end()) {\n status_ = Status::Corruption(\"identity as first hash not found\");\n return;\n }\n identity_as_first_hash_ = *reinterpret_cast<const bool*>(\n identity_as_first_hash->second.data());\n\n auto use_module_hash = user_props.find(\n CuckooTablePropertyNames::kUseModuleHash);\n if (use_module_hash == user_props.end()) {\n status_ = Status::Corruption(\"hash type is not found\");\n return;\n }\n use_module_hash_ = *reinterpret_cast<const bool*>(\n use_module_hash->second.data());\n auto cuckoo_block_size = user_props.find(\n CuckooTablePropertyNames::kCuckooBlockSize);\n if (cuckoo_block_size == user_props.end()) {\n status_ = Status::Corruption(\"Cuckoo block size not found\");\n return;\n }\n cuckoo_block_size_ = *reinterpret_cast<const uint32_t*>(\n cuckoo_block_size->second.data());\n cuckoo_block_bytes_minus_one_ = cuckoo_block_size_ * bucket_length_ - 1;\n status_ = file_->Read(0, file_size, &file_data_, nullptr);\n}\n\nStatus CuckooTableReader::Get(const ReadOptions& readOptions, const Slice& key,\n GetContext* get_context) {\n assert(key.size() == key_length_ + (is_last_level_ ? 8 : 0));\n Slice user_key = ExtractUserKey(key);\n for (uint32_t hash_cnt = 0; hash_cnt < num_hash_func_; ++hash_cnt) {\n uint64_t offset = bucket_length_ * CuckooHash(\n user_key, hash_cnt, use_module_hash_, table_size_,\n identity_as_first_hash_, get_slice_hash_);\n const char* bucket = &file_data_.data()[offset];\n for (uint32_t block_idx = 0; block_idx < cuckoo_block_size_;\n ++block_idx, bucket += bucket_length_) {\n if (ucomp_->Compare(Slice(unused_key_.data(), user_key.size()),\n Slice(bucket, user_key.size())) == 0) {\n return Status::OK();\n }\n \/\/ Here, we compare only the user key part as we support only one entry\n \/\/ per user key and we don't support sanpshot.\n if (ucomp_->Compare(user_key, Slice(bucket, user_key.size())) == 0) {\n Slice value(bucket + key_length_, value_length_);\n if (is_last_level_) {\n get_context->SaveValue(value);\n } else {\n Slice full_key(bucket, key_length_);\n ParsedInternalKey found_ikey;\n ParseInternalKey(full_key, &found_ikey);\n get_context->SaveValue(found_ikey, value);\n }\n \/\/ We don't support merge operations. So, we return here.\n return Status::OK();\n }\n }\n }\n return Status::OK();\n}\n\nvoid CuckooTableReader::Prepare(const Slice& key) {\n \/\/ Prefetch the first Cuckoo Block.\n Slice user_key = ExtractUserKey(key);\n uint64_t addr = reinterpret_cast<uint64_t>(file_data_.data()) +\n bucket_length_ * CuckooHash(user_key, 0, use_module_hash_, table_size_,\n identity_as_first_hash_, nullptr);\n uint64_t end_addr = addr + cuckoo_block_bytes_minus_one_;\n for (addr &= CACHE_LINE_MASK; addr < end_addr; addr += CACHE_LINE_SIZE) {\n PREFETCH(reinterpret_cast<const char*>(addr), 0, 3);\n }\n}\n\nclass CuckooTableIterator : public Iterator {\n public:\n explicit CuckooTableIterator(CuckooTableReader* reader);\n ~CuckooTableIterator() {}\n bool Valid() const override;\n void SeekToFirst() override;\n void SeekToLast() override;\n void Seek(const Slice& target) override;\n void Next() override;\n void Prev() override;\n Slice key() const override;\n Slice value() const override;\n Status status() const override { return status_; }\n void InitIfNeeded();\n\n private:\n struct BucketComparator {\n BucketComparator(const Slice& file_data, const Comparator* ucomp,\n uint32_t bucket_len, uint32_t user_key_len,\n const Slice& target = Slice())\n : file_data_(file_data),\n ucomp_(ucomp),\n bucket_len_(bucket_len),\n user_key_len_(user_key_len),\n target_(target) {}\n bool operator()(const uint32_t first, const uint32_t second) const {\n const char* first_bucket =\n (first == kInvalidIndex) ? target_.data() :\n &file_data_.data()[first * bucket_len_];\n const char* second_bucket =\n (second == kInvalidIndex) ? target_.data() :\n &file_data_.data()[second * bucket_len_];\n return ucomp_->Compare(Slice(first_bucket, user_key_len_),\n Slice(second_bucket, user_key_len_)) < 0;\n }\n private:\n const Slice file_data_;\n const Comparator* ucomp_;\n const uint32_t bucket_len_;\n const uint32_t user_key_len_;\n const Slice target_;\n };\n\n const BucketComparator bucket_comparator_;\n void PrepareKVAtCurrIdx();\n CuckooTableReader* reader_;\n bool initialized_;\n Status status_;\n \/\/ Contains a map of keys to bucket_id sorted in key order.\n std::vector<uint32_t> sorted_bucket_ids_;\n \/\/ We assume that the number of items can be stored in uint32 (4 Billion).\n uint32_t curr_key_idx_;\n Slice curr_value_;\n IterKey curr_key_;\n \/\/ No copying allowed\n CuckooTableIterator(const CuckooTableIterator&) = delete;\n void operator=(const Iterator&) = delete;\n};\n\nCuckooTableIterator::CuckooTableIterator(CuckooTableReader* reader)\n : bucket_comparator_(reader->file_data_, reader->ucomp_,\n reader->bucket_length_, reader->user_key_length_),\n reader_(reader),\n initialized_(false),\n curr_key_idx_(kInvalidIndex) {\n sorted_bucket_ids_.clear();\n curr_value_.clear();\n curr_key_.Clear();\n}\n\nvoid CuckooTableIterator::InitIfNeeded() {\n if (initialized_) {\n return;\n }\n sorted_bucket_ids_.reserve(reader_->GetTableProperties()->num_entries);\n uint64_t num_buckets = reader_->table_size_ + reader_->cuckoo_block_size_ - 1;\n assert(num_buckets < kInvalidIndex);\n const char* bucket = reader_->file_data_.data();\n for (uint32_t bucket_id = 0; bucket_id < num_buckets; ++bucket_id) {\n if (Slice(bucket, reader_->key_length_) != Slice(reader_->unused_key_)) {\n sorted_bucket_ids_.push_back(bucket_id);\n }\n bucket += reader_->bucket_length_;\n }\n assert(sorted_bucket_ids_.size() ==\n reader_->GetTableProperties()->num_entries);\n std::sort(sorted_bucket_ids_.begin(), sorted_bucket_ids_.end(),\n bucket_comparator_);\n curr_key_idx_ = kInvalidIndex;\n initialized_ = true;\n}\n\nvoid CuckooTableIterator::SeekToFirst() {\n InitIfNeeded();\n curr_key_idx_ = 0;\n PrepareKVAtCurrIdx();\n}\n\nvoid CuckooTableIterator::SeekToLast() {\n InitIfNeeded();\n curr_key_idx_ = sorted_bucket_ids_.size() - 1;\n PrepareKVAtCurrIdx();\n}\n\nvoid CuckooTableIterator::Seek(const Slice& target) {\n InitIfNeeded();\n const BucketComparator seek_comparator(\n reader_->file_data_, reader_->ucomp_,\n reader_->bucket_length_, reader_->user_key_length_,\n ExtractUserKey(target));\n auto seek_it = std::lower_bound(sorted_bucket_ids_.begin(),\n sorted_bucket_ids_.end(),\n kInvalidIndex,\n seek_comparator);\n curr_key_idx_ = std::distance(sorted_bucket_ids_.begin(), seek_it);\n PrepareKVAtCurrIdx();\n}\n\nbool CuckooTableIterator::Valid() const {\n return curr_key_idx_ < sorted_bucket_ids_.size();\n}\n\nvoid CuckooTableIterator::PrepareKVAtCurrIdx() {\n if (!Valid()) {\n curr_value_.clear();\n curr_key_.Clear();\n return;\n }\n uint32_t id = sorted_bucket_ids_[curr_key_idx_];\n const char* offset = reader_->file_data_.data() +\n id * reader_->bucket_length_;\n if (reader_->is_last_level_) {\n \/\/ Always return internal key.\n curr_key_.SetInternalKey(Slice(offset, reader_->user_key_length_),\n 0, kTypeValue);\n } else {\n curr_key_.SetKey(Slice(offset, reader_->key_length_));\n }\n curr_value_ = Slice(offset + reader_->key_length_, reader_->value_length_);\n}\n\nvoid CuckooTableIterator::Next() {\n if (!Valid()) {\n curr_value_.clear();\n curr_key_.Clear();\n return;\n }\n ++curr_key_idx_;\n PrepareKVAtCurrIdx();\n}\n\nvoid CuckooTableIterator::Prev() {\n if (curr_key_idx_ == 0) {\n curr_key_idx_ = sorted_bucket_ids_.size();\n }\n if (!Valid()) {\n curr_value_.clear();\n curr_key_.Clear();\n return;\n }\n --curr_key_idx_;\n PrepareKVAtCurrIdx();\n}\n\nSlice CuckooTableIterator::key() const {\n assert(Valid());\n return curr_key_.GetKey();\n}\n\nSlice CuckooTableIterator::value() const {\n assert(Valid());\n return curr_value_;\n}\n\nextern Iterator* NewErrorIterator(const Status& status, Arena* arena);\n\nIterator* CuckooTableReader::NewIterator(\n const ReadOptions& read_options, Arena* arena) {\n if (!status().ok()) {\n return NewErrorIterator(\n Status::Corruption(\"CuckooTableReader status is not okay.\"), arena);\n }\n if (read_options.total_order_seek) {\n return NewErrorIterator(\n Status::InvalidArgument(\"total_order_seek is not supported.\"), arena);\n }\n CuckooTableIterator* iter;\n if (arena == nullptr) {\n iter = new CuckooTableIterator(this);\n } else {\n auto iter_mem = arena->AllocateAligned(sizeof(CuckooTableIterator));\n iter = new (iter_mem) CuckooTableIterator(this);\n }\n return iter;\n}\n\nsize_t CuckooTableReader::ApproximateMemoryUsage() const { return 0; }\n\n} \/\/ namespace rocksdb\n#endif\n<|endoftext|>"} {"text":"<commit_before>#include \"mikemap.h\"\r\n#include <stdio.h>\r\n\/\/#include <string.h>\r\n\/\/#include <stdlib.h>\r\n\r\n\/\/#define TEST_MIKEMAP\r\n\r\n#ifdef TEST_MIKEMAP\r\n#include <assert.h>\r\n\r\n#define DEFAULT_TEST_VALUE 99\r\nusing namespace mikemap;\r\n\r\nint main(int argc, char *argv[])\r\n{\r\n MikeMap mm;\r\n char input[] = \"[100,1,101,0,10,0,9,0,14,0,11,0,15,0]\";\r\n MAP_KEY_TYPE key = DEFAULT_TEST_VALUE;\r\n MAP_VALUE_TYPE value = DEFAULT_TEST_VALUE;\r\n int converted = 0;\r\n\r\n assert(mm.get_len() == 0);\r\n for (int i = 0; i < MAX_MAP_LEN - 4; i++)\r\n mm.set(i, i);\r\n assert(mm.get_len() == MAX_MAP_LEN - 4);\r\n mm.del(1);\r\n assert(mm.get_len() == MAX_MAP_LEN - 5);\r\n assert(mm.get(4) == 4);\r\n assert(mm.has(1) == false);\r\n assert(mm.has(2) == true);\r\n mm.get_at(MAX_MAP_LEN + 4, &key, &value);\r\n assert(key == DEFAULT_TEST_VALUE);\r\n assert(value == DEFAULT_TEST_VALUE);\r\n mm.get_at(3, &key, &value);\r\n assert(key == 4);\r\n assert(value == 4);\r\n mm.clear();\r\n key = DEFAULT_TEST_VALUE;\r\n value = DEFAULT_TEST_VALUE;\r\n assert(mm.get_len() == 0);\r\n for (int i = 0; i < MAX_MAP_LEN - 4; i++)\r\n mm.set(i, i);\r\n assert(mm.get_len() == MAX_MAP_LEN - 4);\r\n mm.del(1);\r\n assert(mm.get_len() == MAX_MAP_LEN - 5);\r\n assert(mm.get(4) == 4);\r\n assert(mm.get(10) == 10);\r\n assert(mm.has(1) == false);\r\n assert(mm.has(2) == true);\r\n mm.get_at(MAX_MAP_LEN + 4, &key, &value);\r\n assert(key == DEFAULT_TEST_VALUE);\r\n assert(value == DEFAULT_TEST_VALUE);\r\n mm.get_at(3, &key, &value);\r\n assert(key == 4);\r\n assert(value == 4);\r\n mm.del(2);\r\n mm.del(5);\r\n mm.set(2, 20);\r\n assert(mm.has(2) == true);\r\n assert(mm.get_len() == MAX_MAP_LEN - 6);\r\n mm.get_at(MAX_MAP_LEN - 7, &key, &value);\r\n assert(key == 2);\r\n assert(value == 20);\r\n assert(mm.has(5) == false);\r\n mm.clear();\r\n assert(mm.from_string(input, &converted) == 0);\r\n assert(converted == 14);\r\n mm.get_at(0, &key, &value);\r\n printf(\"k0: %d v0: %d\\n\", key, value);\r\n assert(key == 100);\r\n assert(value == 1);\r\n mm.get_at(4, &key, &value);\r\n assert(key == 14);\r\n assert(value == 0);\r\n}\r\n#endif\r\n\r\nnamespace mikemap\r\n{\r\n\r\n MikeMap::MikeMap()\r\n {\r\n this->mikemap_len = 0;\r\n }\r\n\r\n void MikeMap::set(MAP_KEY_TYPE key, MAP_VALUE_TYPE value)\r\n {\r\n for (unsigned int i = 0; i < mikemap_len; i++)\r\n {\r\n if (mikemap_keys[i] == key)\r\n {\r\n mikemap_values[i] = value;\r\n return;\r\n }\r\n }\r\n if (mikemap_len == MAX_MAP_LEN)\r\n return;\r\n mikemap_keys[mikemap_len] = key;\r\n mikemap_values[mikemap_len] = value;\r\n mikemap_len++;\r\n }\r\n\r\n bool MikeMap::has(MAP_KEY_TYPE key) const\r\n {\r\n for (unsigned int i = 0; i < mikemap_len; i++)\r\n {\r\n if (mikemap_keys[i] == key)\r\n {\r\n return true;\r\n }\r\n }\r\n return false;\r\n }\r\n\r\n MAP_VALUE_TYPE MikeMap::get(MAP_KEY_TYPE key) const\r\n {\r\n for (unsigned int i = 0; i < mikemap_len; i++)\r\n {\r\n if (mikemap_keys[i] == key)\r\n {\r\n return mikemap_values[i];\r\n }\r\n }\r\n return 0;\r\n }\r\n\r\n void MikeMap::to_string(char *ptr)\r\n {\r\n int offset = 0;\r\n for (unsigned int i = 0; i < mikemap_len; i++)\r\n {\r\n if (i > 0)\r\n {\r\n ptr[offset] = ',';\r\n offset++;\r\n }\r\n offset += sprintf(&ptr[offset], \"%d\", mikemap_keys[i]);\r\n ptr[offset] = ',';\r\n offset++;\r\n offset += sprintf(&ptr[offset], \"%d\", mikemap_values[i]);\r\n }\r\n }\r\n\r\n int MikeMap::to_int(const char *data, int len)\r\n {\r\n int val = 0;\r\n while (len)\r\n {\r\n int new_val = ((int)*data - (int)'0');\r\n val = val * 10 + new_val;\r\n len--;\r\n data++;\r\n }\r\n#ifdef TEST_MIKEMAP\r\n printf(\"val: %d\\n\", val);\r\n#endif\r\n return val;\r\n }\r\n\r\n int MikeMap::from_string(const char *data_start, int *converted)\r\n {\r\n const char *data_ptr = data_start;\r\n\r\n this->clear();\r\n \/\/ the map is supposed to start with \"[\"\r\n if (*data_ptr != '[')\r\n return MM_ERR_WRONG_START;\r\n data_ptr++;\r\n\r\n while (1)\r\n {\r\n int len_key = 0;\r\n const char *key_start = data_ptr;\r\n {\r\n while (len_key < MAX_SINGLE_DATA_LEN && *data_ptr != ',' && *data_ptr != ']')\r\n {\r\n if (*data_ptr < '0' || *data_ptr > '9')\r\n return MM_ERR_NO_DIGIT;\r\n len_key++;\r\n data_ptr++;\r\n }\r\n if (len_key == 0 || len_key == MAX_SINGLE_DATA_LEN)\r\n return MM_ERR_ZERO_MAX_LEN_KEY;\r\n if (*data_ptr == ']')\r\n return MM_ERR_MISSING_VAL;\r\n }\r\n int k = this->to_int(key_start, len_key);\r\n (*converted)++;\r\n data_ptr++;\r\n int len_val = 0;\r\n const char *val_start = data_ptr;\r\n {\r\n while (len_val < MAX_SINGLE_DATA_LEN && *data_ptr != ',' && *data_ptr != ']')\r\n {\r\n if (*data_ptr < '0' || *data_ptr > '9')\r\n return MM_ERR_NO_DIGIT;\r\n len_val++;\r\n data_ptr++;\r\n }\r\n if (len_val == 0 || len_val == MAX_SINGLE_DATA_LEN)\r\n return MM_ERR_ZERO_MAX_LEN_VAL;\r\n }\r\n int v = this->to_int(val_start, len_val);\r\n (*converted)++;\r\n this->set(k, v);\r\n if (*data_ptr == ']')\r\n break;\r\n else\r\n data_ptr++;\r\n }\r\n\r\n return MM_OK;\r\n }\r\n\r\n void MikeMap::del(MAP_KEY_TYPE key)\r\n {\r\n for (unsigned int i = 0; i < mikemap_len; i++)\r\n {\r\n if (mikemap_keys[i] == key)\r\n {\r\n for (unsigned int si = i; si < (mikemap_len - 1); si++)\r\n {\r\n mikemap_keys[si] = mikemap_keys[si + 1];\r\n mikemap_values[si] = mikemap_values[si + 1];\r\n }\r\n mikemap_keys[mikemap_len] = 0;\r\n mikemap_values[mikemap_len] = 0;\r\n mikemap_len--;\r\n return;\r\n }\r\n }\r\n }\r\n\r\n unsigned int MikeMap::get_len() const\r\n {\r\n return mikemap_len;\r\n }\r\n\r\n void MikeMap::clear()\r\n {\r\n mikemap_len = 0;\r\n }\r\n\r\n void MikeMap::get_at(unsigned int at, MAP_KEY_TYPE *key, MAP_VALUE_TYPE *value) const\r\n {\r\n if (at < mikemap_len)\r\n {\r\n *key = mikemap_keys[at];\r\n *value = mikemap_values[at];\r\n }\r\n }\r\n}<commit_msg>tried to fix what looks like unsigned 32 bit thing, did not work<commit_after>#include \"mikemap.h\"\r\n#include <stdio.h>\r\n\/\/#include <string.h>\r\n\/\/#include <stdlib.h>\r\n\r\n\/\/#define TEST_MIKEMAP\r\n\r\n#ifdef TEST_MIKEMAP\r\n#include <assert.h>\r\n\r\n#define DEFAULT_TEST_VALUE 99\r\nusing namespace mikemap;\r\n\r\nint main(int argc, char *argv[])\r\n{\r\n MikeMap mm;\r\n char input[] = \"[100,1,101,0,10,0,9,0,14,0,11,0,15,0]\";\r\n MAP_KEY_TYPE key = DEFAULT_TEST_VALUE;\r\n MAP_VALUE_TYPE value = DEFAULT_TEST_VALUE;\r\n int converted = 0;\r\n\r\n assert(mm.get_len() == 0);\r\n for (int i = 0; i < MAX_MAP_LEN - 4; i++)\r\n mm.set(i, i);\r\n assert(mm.get_len() == MAX_MAP_LEN - 4);\r\n mm.del(1);\r\n assert(mm.get_len() == MAX_MAP_LEN - 5);\r\n assert(mm.get(4) == 4);\r\n assert(mm.has(1) == false);\r\n assert(mm.has(2) == true);\r\n mm.get_at(MAX_MAP_LEN + 4, &key, &value);\r\n assert(key == DEFAULT_TEST_VALUE);\r\n assert(value == DEFAULT_TEST_VALUE);\r\n mm.get_at(3, &key, &value);\r\n assert(key == 4);\r\n assert(value == 4);\r\n mm.clear();\r\n key = DEFAULT_TEST_VALUE;\r\n value = DEFAULT_TEST_VALUE;\r\n assert(mm.get_len() == 0);\r\n for (int i = 0; i < MAX_MAP_LEN - 4; i++)\r\n mm.set(i, i);\r\n assert(mm.get_len() == MAX_MAP_LEN - 4);\r\n mm.del(1);\r\n assert(mm.get_len() == MAX_MAP_LEN - 5);\r\n assert(mm.get(4) == 4);\r\n assert(mm.get(10) == 10);\r\n assert(mm.has(1) == false);\r\n assert(mm.has(2) == true);\r\n mm.get_at(MAX_MAP_LEN + 4, &key, &value);\r\n assert(key == DEFAULT_TEST_VALUE);\r\n assert(value == DEFAULT_TEST_VALUE);\r\n mm.get_at(3, &key, &value);\r\n assert(key == 4);\r\n assert(value == 4);\r\n mm.del(2);\r\n mm.del(5);\r\n mm.set(2, 20);\r\n assert(mm.has(2) == true);\r\n assert(mm.get_len() == MAX_MAP_LEN - 6);\r\n mm.get_at(MAX_MAP_LEN - 7, &key, &value);\r\n assert(key == 2);\r\n assert(value == 20);\r\n assert(mm.has(5) == false);\r\n mm.clear();\r\n assert(mm.from_string(input, &converted) == 0);\r\n assert(converted == 14);\r\n mm.get_at(0, &key, &value);\r\n printf(\"k0: %d v0: %d\\n\", key, value);\r\n assert(key == 100);\r\n assert(value == 1);\r\n mm.get_at(4, &key, &value);\r\n assert(key == 14);\r\n assert(value == 0);\r\n}\r\n#endif\r\n\r\nnamespace mikemap\r\n{\r\n\r\n MikeMap::MikeMap()\r\n {\r\n this->mikemap_len = 0;\r\n }\r\n\r\n void MikeMap::set(MAP_KEY_TYPE key, MAP_VALUE_TYPE value)\r\n {\r\n for (unsigned int i = 0; i < mikemap_len; i++)\r\n {\r\n if (mikemap_keys[i] == key)\r\n {\r\n mikemap_values[i] = value;\r\n return;\r\n }\r\n }\r\n if (mikemap_len == MAX_MAP_LEN)\r\n return;\r\n mikemap_keys[mikemap_len] = key;\r\n mikemap_values[mikemap_len] = value;\r\n mikemap_len++;\r\n }\r\n\r\n bool MikeMap::has(MAP_KEY_TYPE key) const\r\n {\r\n for (unsigned int i = 0; i < mikemap_len; i++)\r\n {\r\n if (mikemap_keys[i] == key)\r\n {\r\n return true;\r\n }\r\n }\r\n return false;\r\n }\r\n\r\n MAP_VALUE_TYPE MikeMap::get(MAP_KEY_TYPE key) const\r\n {\r\n for (unsigned int i = 0; i < mikemap_len; i++)\r\n {\r\n if (mikemap_keys[i] == key)\r\n {\r\n return mikemap_values[i];\r\n }\r\n }\r\n return 0;\r\n }\r\n\r\n void MikeMap::to_string(char *ptr)\r\n {\r\n int offset = 0;\r\n for (unsigned int i = 0; i < mikemap_len; i++)\r\n {\r\n if (i > 0)\r\n {\r\n ptr[offset] = ',';\r\n offset++;\r\n }\r\n offset += sprintf(&ptr[offset], \"%d\", mikemap_keys[i]);\r\n ptr[offset] = ',';\r\n offset++;\r\n offset += sprintf(&ptr[offset], \"%d\", mikemap_values[i]);\r\n }\r\n }\r\n\r\n int MikeMap::to_int(const char *data, int len)\r\n {\r\n long int val = 0;\r\n while (len)\r\n {\r\n long int new_val = ((int)*data - (int)'0');\r\n val = val * 10 + new_val;\r\n len--;\r\n data++;\r\n }\r\n#ifdef TEST_MIKEMAP\r\n printf(\"val: %d\\n\", val);\r\n#endif\r\n return val;\r\n }\r\n\r\n int MikeMap::from_string(const char *data_start, int *converted)\r\n {\r\n const char *data_ptr = data_start;\r\n\r\n this->clear();\r\n \/\/ the map is supposed to start with \"[\"\r\n if (*data_ptr != '[')\r\n return MM_ERR_WRONG_START;\r\n data_ptr++;\r\n\r\n while (1)\r\n {\r\n int len_key = 0;\r\n const char *key_start = data_ptr;\r\n {\r\n while (len_key < MAX_SINGLE_DATA_LEN && *data_ptr != ',' && *data_ptr != ']')\r\n {\r\n if (*data_ptr < '0' || *data_ptr > '9')\r\n return MM_ERR_NO_DIGIT;\r\n len_key++;\r\n data_ptr++;\r\n }\r\n if (len_key == 0 || len_key == MAX_SINGLE_DATA_LEN)\r\n return MM_ERR_ZERO_MAX_LEN_KEY;\r\n if (*data_ptr == ']')\r\n return MM_ERR_MISSING_VAL;\r\n }\r\n int k = this->to_int(key_start, len_key);\r\n (*converted)++;\r\n data_ptr++;\r\n int len_val = 0;\r\n const char *val_start = data_ptr;\r\n {\r\n while (len_val < MAX_SINGLE_DATA_LEN && *data_ptr != ',' && *data_ptr != ']')\r\n {\r\n if (*data_ptr < '0' || *data_ptr > '9')\r\n return MM_ERR_NO_DIGIT;\r\n len_val++;\r\n data_ptr++;\r\n }\r\n if (len_val == 0 || len_val == MAX_SINGLE_DATA_LEN)\r\n return MM_ERR_ZERO_MAX_LEN_VAL;\r\n }\r\n int v = this->to_int(val_start, len_val);\r\n (*converted)++;\r\n this->set(k, v);\r\n if (*data_ptr == ']')\r\n break;\r\n else\r\n data_ptr++;\r\n }\r\n\r\n return MM_OK;\r\n }\r\n\r\n void MikeMap::del(MAP_KEY_TYPE key)\r\n {\r\n for (unsigned int i = 0; i < mikemap_len; i++)\r\n {\r\n if (mikemap_keys[i] == key)\r\n {\r\n for (unsigned int si = i; si < (mikemap_len - 1); si++)\r\n {\r\n mikemap_keys[si] = mikemap_keys[si + 1];\r\n mikemap_values[si] = mikemap_values[si + 1];\r\n }\r\n mikemap_keys[mikemap_len] = 0;\r\n mikemap_values[mikemap_len] = 0;\r\n mikemap_len--;\r\n return;\r\n }\r\n }\r\n }\r\n\r\n unsigned int MikeMap::get_len() const\r\n {\r\n return mikemap_len;\r\n }\r\n\r\n void MikeMap::clear()\r\n {\r\n mikemap_len = 0;\r\n }\r\n\r\n void MikeMap::get_at(unsigned int at, MAP_KEY_TYPE *key, MAP_VALUE_TYPE *value) const\r\n {\r\n if (at < mikemap_len)\r\n {\r\n *key = mikemap_keys[at];\r\n *value = mikemap_values[at];\r\n }\r\n }\r\n}<|endoftext|>"} {"text":"<commit_before>#include \"miomain.h\"\n#include \"config\/configuration.h\"\n#include \"devicedetection.h\"\n#include \"sysex\/midi.h\"\n#include \"sysex\/retcommandlist.h\"\n#include \"ui_miomain.h\"\n#include \"widgets\/centralwidget.h\"\n#include \"widgets\/deviceinfowidget.h\"\n#include \"widgets\/multiinfowidget.h\"\n#include \"widgets\/portswidget.h\"\n\n#include <QCloseEvent>\n#include <QDesktopWidget>\n#include <QMessageBox>\n#include <QPixmap>\n#include <QSignalMapper>\n#include <QStyle>\n#include <QTimer>\n#include <QToolButton>\n#include <QtDebug>\n\nMioMain::MioMain(QWidget *parent) : QMainWindow(parent), ui(new Ui::MioMain) {\n ui->setupUi(this);\n\tsetDockOptions(QMainWindow::AnimatedDocks | QMainWindow::ForceTabbedDocks |\n QMainWindow::VerticalTabs);\n\t\/*QPixmap *pm = new QPixmap(\"\/develop\/mioconfig\/graphik\/restore.svg\");\n\tpm->save(\"\/develop\/mioconfig\/graphik\/restore.xpm\", \"xpm\");\n\tpm->load(\"\/develop\/mioconfig\/graphik\/SaveToDevice.svg\");\n\tpm->save(\"\/develop\/mioconfig\/graphik\/SaveToDevice.xpm\", \"xpm\");*\/\n readSettings();\n if (readDevicesFromSettings())\n openDefaultDevice();\n else\n QTimer::singleShot(100, this, SLOT(openDetectionWindow()));\n}\n\nMioMain::~MioMain() {\n if (deviceDetectionWindow)\n delete deviceDetectionWindow;\n delete ui;\n}\n\nvoid MioMain::openDefaultDevice() {\n writeDevicesToSettings();\n long defaultDeviceSN = Configuration::getInstance().getDefaultDevice();\n Device *d = Configuration::getInstance().getDevices()->at(defaultDeviceSN);\n addDevicesToSelectionMenu(defaultDeviceSN);\n openDeviceGUI(d);\n}\n\nvoid MioMain::addDevicesToSelectionMenu(long defaultDeviceSN) {\n QSignalMapper *signalMapper = new QSignalMapper();\n Devices *devices = Configuration::getInstance().getDevices();\n QActionGroup *devicesGroup = new QActionGroup(this);\n devicesGroup->setExclusive(true);\n for (Devices::iterator it = devices->begin(); it != devices->end(); ++it) {\n Device *d = it->second;\n QAction *a =\n ui->menuSelect->addAction(QString::fromStdString(d->getDeviceName()));\n a->setCheckable(true);\n devicesGroup->addAction(a);\n connect(a, SIGNAL(triggered()), signalMapper, SLOT(map()));\n signalMapper->setMapping(a, new DeviceMenuMapper(d));\n if (it->first == defaultDeviceSN)\n a->setChecked(true);\n }\n connect(signalMapper, SIGNAL(mapped(QObject *)), this,\n SLOT(openDeviceGUI(QObject *)));\n}\n\nvoid MioMain::openDeviceGUI(QObject *o) {\n DeviceMenuMapper *m = (DeviceMenuMapper *)o;\n#ifdef __MIO_DEBUG__\n std::cout << \"open device GUI: \" << m->device->getDeviceName() << std::endl;\n#endif \/\/__MIO_DEBUG__\n openDeviceGUI(m->device);\n}\n\nvoid MioMain::addDock(QDockWidget *dockWidget, Qt::DockWidgetArea area) {\n if (MultiInfoWidget *miw = dynamic_cast<MultiInfoWidget *>(dockWidget)) {\n miw->createInfoSections();\n }\n switch (area) {\n case Qt::NoDockWidgetArea:\n setCentralWidget(dockWidget);\n break;\n case Qt::LeftDockWidgetArea:\n this->addDockWidget(Qt::LeftDockWidgetArea, dockWidget);\n break;\n default:\n break;\n }\n std::vector<QDockWidget *> v = dockWidgetAreas[area];\n if (v.size() > 0) {\n tabifyDockWidget(v[v.size() - 1], dockWidget);\n }\n dockWidgetAreas[area].push_back(dockWidget);\n}\n\nvoid MioMain::clearDocWidgets() {\n\tremoveToolBar(toolBar);\n\tdelete toolBar;\n\ttoolBar = 0;\n for (std::map<Qt::DockWidgetArea, std::vector<QDockWidget *>>::iterator it =\n dockWidgetAreas.begin();\n it != dockWidgetAreas.end(); ++it) {\n std::vector<QDockWidget *> v = it->second;\n for (unsigned int j = 0; j < v.size(); j++) {\n QWidget *w = v.at(j);\n delete w;\n }\n v.clear();\n }\n dockWidgetAreas.clear();\n}\n\nvoid MioMain::replacePanel(QWidget *w) {\n CentralWidget *cw = (CentralWidget *)centralWidget();\n cw->replacePanel(w);\n}\n\nvoid MioMain::addDeviceToolButtons() {\n\tBYTE_VECTOR *saveRestoreList = this->currentDevice->saveRestoreList;\n\tfor (unsigned int i = 0; i < saveRestoreList->size(); ++i) {\n\t\tswitch ((SaveRestore::SaveResstoreId)(*saveRestoreList)[i]) {\n\t\tcase SaveRestore::SAVE_TO_DEVICE: {\n\t\t\tQToolButton *btn = new QToolButton();\n\t\t\tbtn->setToolButtonStyle(Qt::ToolButtonIconOnly);\n\t\t\tbtn->setText(\"Save\");\n\t\t\tbtn->setToolTip(tr(\"Save current settings to device\"));\n\t\t\ttoolBar->addWidget(btn);\n\t\t\tbtn->setIcon(QIcon(\":\/pixmaps\/saveto\"));\n\t\t\tconnect(btn, SIGNAL(pressed()), this, SLOT(storeToDevice()));\n\t\t} break;\n\t\tcase SaveRestore::RESTORE_FROM_DEVICE: {\n\t\t\tQToolButton *btn = new QToolButton();\n\t\t\tbtn->setToolButtonStyle(Qt::ToolButtonIconOnly);\n\t\t\tbtn->setText(\"Restore\");\n\t\t\tbtn->setToolTip(tr(\"Restore settings from device\"));\n\t\t\ttoolBar->addWidget(btn);\n\t\t\tbtn->setIcon(QIcon(\":\/pixmaps\/readfrom\"));\n\t\t\tconnect(btn, SIGNAL(pressed()), this, SLOT(restoreFromDevice()));\n\t\t} break;\n\t\tcase SaveRestore::SET_TO_FACTORY_DEFAULT: {\n\t\t\tQToolButton *btn = new QToolButton();\n\t\t\tbtn->setToolButtonStyle(Qt::ToolButtonIconOnly);\n\t\t\tbtn->setText(\"Fact\");\n\t\t\tbtn->setToolTip(tr(\"Reset settings to factory default\"));\n\t\t\ttoolBar->addWidget(btn);\n\t\t\tbtn->setIcon(QIcon(\":\/pixmaps\/restore\"));\n\t\t\tconnect(btn, SIGNAL(pressed()), this, SLOT(resetToFactoryDefaults()));\n\t\t} break;\n\t\tdefault:\n\t\t\tbreak;\n\t\t}\n\t}\n}\n\nvoid MioMain::openDeviceGUI(Device *d) {\n clearDocWidgets();\n\ttoolBar = new QToolBar(tr(\"Device Actions\"), this);\n\ttoolBar->setObjectName(\"DeviceActions\");\n\tthis->addToolBar(toolBar);\n\n\tthis->currentDevice = d;\n\td->connect();\n RetCommandList *c = d->getCommands();\n if (c == 0) {\n \/\/ TODO throw error\n exit(2);\n }\n setWindowTitle(this->title + QString(\": \") +\n QString::fromStdString(d->getDeviceName()));\n CentralWidget *centralWidget = new CentralWidget(this, d);\n this->addDock(centralWidget);\n\n DeviceInfoWidget *deviceInfoWidget =\n new DeviceInfoWidget(this, d, d->getDeviceInfo());\n this->addDock(deviceInfoWidget, Qt::LeftDockWidgetArea);\n\n PortsWidget *portsWidget = new PortsWidget(this, d);\n this->addDock(portsWidget, Qt::LeftDockWidgetArea);\n\n\taddDeviceToolButtons();\n\n QSettings *settings = Configuration::getInstance().getSettings();\n settings->beginGroup(\"MainWindow\");\n restoreGeometry(settings->value(\"geometry\").toByteArray());\n settings->endGroup();\n settings->beginGroup(\"Docks\");\n \/\/ restoreState(settings->value(\"DockWindows\").toByteArray());\n settings->endGroup();\n deviceInfoWidget->show();\n\tdeviceInfoWidget->raise();\n}\n\nvoid MioMain::storeToDevice() {\n\tQMessageBox msgBox;\n\tmsgBox.setText(tr(\"Store current setings to device?\"));\n\tmsgBox.setStandardButtons(QMessageBox::Ok | QMessageBox::Cancel);\n\tmsgBox.setDefaultButton(QMessageBox::Save);\n\tint ret = msgBox.exec();\n\tif (ret == QMessageBox::Ok)\n\t\tsaveRestore(SaveRestore::SAVE_TO_DEVICE);\n}\n\nvoid MioMain::restoreFromDevice() {\n\tQMessageBox msgBox;\n\tmsgBox.setText(tr(\"Read all settings from device?\"));\n\tmsgBox.setStandardButtons(QMessageBox::Ok | QMessageBox::Cancel);\n\tmsgBox.setDefaultButton(QMessageBox::Save);\n\tint ret = msgBox.exec();\n\tif (ret == QMessageBox::Ok) {\n\t\tsaveRestore(SaveRestore::RESTORE_FROM_DEVICE);\n\t\tcurrentDevice->disconnect();\n\t\topenDeviceGUI(this->currentDevice);\n\t}\n}\n\nvoid MioMain::resetToFactoryDefaults() {\n\tQMessageBox msgBox;\n\tmsgBox.setText(tr(\"Reset all settings to factory default?\"));\n\tmsgBox.setStandardButtons(QMessageBox::Ok | QMessageBox::Cancel);\n\tmsgBox.setDefaultButton(QMessageBox::Save);\n\tint ret = msgBox.exec();\n\tif (ret == QMessageBox::Ok) {\n\t\tsaveRestore(SaveRestore::SET_TO_FACTORY_DEFAULT);\n\t\tcurrentDevice->disconnect();\n\t\topenDeviceGUI(this->currentDevice);\n\t}\n}\n\nvoid MioMain::saveRestore(SaveRestore::SaveResstoreId saveRestoreId) {\n\tSaveRestore *saveRestore = new SaveRestore(currentDevice);\n\tsaveRestore->setSaveRestoreId(saveRestoreId);\n\tsaveRestore->execute();\n}\n\nvoid MioMain::closeEvent(QCloseEvent *event) {\n writeSettings();\n event->accept();\n}\n\nvoid MioMain::openDetectionWindow() {\n deviceDetectionWindow = new DeviceDetection(this);\n deviceDetectionWindow->exec();\n}\n\nvoid MioMain::writeSettings() {\n QSettings *settings = Configuration::getInstance().getSettings();\n settings->beginGroup(\"MainWindow\");\n settings->setValue(\"geometry\", saveGeometry());\n settings->setValue(\"size\", size());\n settings->setValue(\"pos\", pos());\n settings->endGroup();\n settings->beginGroup(\"Docks\");\n settings->setValue(\"DockWindows\", saveState());\n settings->endGroup();\n}\n\nvoid MioMain::writeDevicesToSettings() {\n QSettings *settings = Configuration::getInstance().getSettings();\n Devices *devices = Configuration::getInstance().getDevices();\n settings->remove(\"Devices\");\n settings->beginWriteArray(\"Devices\");\n int i = 0;\n for (Devices::iterator it = devices->begin(); it != devices->end(); ++it) {\n settings->setArrayIndex(i);\n Device *d = it->second;\n settings->setValue(\"Device Name\",\n QString::fromStdString(d->getDeviceName()));\n settings->setValue(\"Serial Number\",\n (qlonglong)(d->getSerialNumber()->getLongValue()));\n settings->setValue(\"Input Port\", d->getInPortNumer());\n settings->setValue(\"Output Port\", d->getOutPortNumer());\n settings->setValue(\"Product Id\",\n (qlonglong)d->getProductId()->getLongValue());\n#ifdef __MIO_SIMULATE__\n if (d->getSimulate()) {\n settings->setValue(\"Simulate\", true);\n settings->setValue(\"Model Name\",\n QString::fromStdString(d->getModelName()));\n }\n#endif\n ++i;\n }\n settings->endArray();\n}\n\nvoid MioMain::connectSlots() {\n \/\/ connect(this->)\n}\n\nvoid MioMain::readSettings() {\n this->title = windowTitle();\n QSettings *settings = Configuration::getInstance().getSettings();\n settings->beginGroup(\"MainWindow\");\n resize(settings->value(\"size\", QSize(400, 400)).toSize());\n move(settings->value(\"pos\", QPoint(200, 200)).toPoint());\n settings->endGroup();\n}\n\nbool MioMain::readDevicesFromSettings() {\n Devices *devices = Configuration::getInstance().getDevices();\n devices->clear();\n QSettings *settings = Configuration::getInstance().getSettings();\n int size = settings->beginReadArray(\"Devices\");\n if (size == 0)\n return false;\n for (int i = 0; i < size; ++i) {\n Device *device = 0;\n settings->setArrayIndex(i);\n int productId = settings->value(\"Product Id\").toInt();\n long serialNumber =\n (qlonglong)settings->value(\"Serial Number\").toLongLong();\n int inputPort = (qlonglong)settings->value(\"Input Port\").toInt();\n int outputPort = (qlonglong)settings->value(\"Output Port\").toInt();\n bool simulate = settings->value(\"Simulate\").toBool();\n#ifdef __MIO_SIMULATE__\n if (simulate) {\n std::string modelName =\n settings->value(\"Model Name\").toString().toStdString();\n std::string deviceName =\n settings->value(\"Device Name\").toString().toStdString();\n device = new Device(inputPort, outputPort, serialNumber, productId,\n modelName, deviceName);\n } else {\n device = new Device(inputPort, outputPort, serialNumber, productId);\n }\n#else\n if (!simulate)\n device = new Device(inputPort, outputPort, serialNumber, productId);\n#endif\n if (device && device->queryDeviceInfo())\n devices->insert(std::pair<long, Device *>(serialNumber, device));\n }\n settings->endArray();\n if (devices->size() == 0)\n return false;\n return true;\n}\nvoid MioMain::on_actionQuit_triggered() { close(); }\n<commit_msg>unsuccessful try to get the device back, after restoring fro device memory<commit_after>#include \"miomain.h\"\n#include \"config\/configuration.h\"\n#include \"devicedetection.h\"\n#include \"sysex\/midi.h\"\n#include \"sysex\/retcommandlist.h\"\n#include \"ui_miomain.h\"\n#include \"widgets\/centralwidget.h\"\n#include \"widgets\/deviceinfowidget.h\"\n#include \"widgets\/multiinfowidget.h\"\n#include \"widgets\/portswidget.h\"\n\n#include <QCloseEvent>\n#include <QDesktopWidget>\n#include <QMessageBox>\n#include <QPixmap>\n#include <QSignalMapper>\n#include <QStyle>\n#include <QTimer>\n#include <QToolButton>\n#include <QtDebug>\n\nMioMain::MioMain(QWidget *parent) : QMainWindow(parent), ui(new Ui::MioMain) {\n ui->setupUi(this);\n\tsetDockOptions(QMainWindow::AnimatedDocks | QMainWindow::ForceTabbedDocks |\n QMainWindow::VerticalTabs);\n\t\/*QPixmap *pm = new QPixmap(\"\/develop\/mioconfig\/graphik\/restore.svg\");\n\tpm->save(\"\/develop\/mioconfig\/graphik\/restore.xpm\", \"xpm\");\n\tpm->load(\"\/develop\/mioconfig\/graphik\/SaveToDevice.svg\");\n\tpm->save(\"\/develop\/mioconfig\/graphik\/SaveToDevice.xpm\", \"xpm\");*\/\n readSettings();\n if (readDevicesFromSettings())\n openDefaultDevice();\n else\n QTimer::singleShot(100, this, SLOT(openDetectionWindow()));\n}\n\nMioMain::~MioMain() {\n if (deviceDetectionWindow)\n delete deviceDetectionWindow;\n delete ui;\n}\n\nvoid MioMain::openDefaultDevice() {\n writeDevicesToSettings();\n long defaultDeviceSN = Configuration::getInstance().getDefaultDevice();\n Device *d = Configuration::getInstance().getDevices()->at(defaultDeviceSN);\n addDevicesToSelectionMenu(defaultDeviceSN);\n openDeviceGUI(d);\n}\n\nvoid MioMain::addDevicesToSelectionMenu(long defaultDeviceSN) {\n QSignalMapper *signalMapper = new QSignalMapper();\n Devices *devices = Configuration::getInstance().getDevices();\n QActionGroup *devicesGroup = new QActionGroup(this);\n devicesGroup->setExclusive(true);\n for (Devices::iterator it = devices->begin(); it != devices->end(); ++it) {\n Device *d = it->second;\n QAction *a =\n ui->menuSelect->addAction(QString::fromStdString(d->getDeviceName()));\n a->setCheckable(true);\n devicesGroup->addAction(a);\n connect(a, SIGNAL(triggered()), signalMapper, SLOT(map()));\n signalMapper->setMapping(a, new DeviceMenuMapper(d));\n if (it->first == defaultDeviceSN)\n a->setChecked(true);\n }\n connect(signalMapper, SIGNAL(mapped(QObject *)), this,\n SLOT(openDeviceGUI(QObject *)));\n}\n\nvoid MioMain::openDeviceGUI(QObject *o) {\n DeviceMenuMapper *m = (DeviceMenuMapper *)o;\n#ifdef __MIO_DEBUG__\n std::cout << \"open device GUI: \" << m->device->getDeviceName() << std::endl;\n#endif \/\/__MIO_DEBUG__\n openDeviceGUI(m->device);\n}\n\nvoid MioMain::addDock(QDockWidget *dockWidget, Qt::DockWidgetArea area) {\n if (MultiInfoWidget *miw = dynamic_cast<MultiInfoWidget *>(dockWidget)) {\n miw->createInfoSections();\n }\n switch (area) {\n case Qt::NoDockWidgetArea:\n setCentralWidget(dockWidget);\n break;\n case Qt::LeftDockWidgetArea:\n this->addDockWidget(Qt::LeftDockWidgetArea, dockWidget);\n break;\n default:\n break;\n }\n std::vector<QDockWidget *> v = dockWidgetAreas[area];\n if (v.size() > 0) {\n tabifyDockWidget(v[v.size() - 1], dockWidget);\n }\n dockWidgetAreas[area].push_back(dockWidget);\n}\n\nvoid MioMain::clearDocWidgets() {\n\tremoveToolBar(toolBar);\n\tdelete toolBar;\n\ttoolBar = 0;\n for (std::map<Qt::DockWidgetArea, std::vector<QDockWidget *>>::iterator it =\n dockWidgetAreas.begin();\n it != dockWidgetAreas.end(); ++it) {\n std::vector<QDockWidget *> v = it->second;\n for (unsigned int j = 0; j < v.size(); j++) {\n QWidget *w = v.at(j);\n delete w;\n }\n v.clear();\n }\n dockWidgetAreas.clear();\n}\n\nvoid MioMain::replacePanel(QWidget *w) {\n CentralWidget *cw = (CentralWidget *)centralWidget();\n cw->replacePanel(w);\n}\n\nvoid MioMain::addDeviceToolButtons() {\n\tBYTE_VECTOR *saveRestoreList = this->currentDevice->saveRestoreList;\n\tfor (unsigned int i = 0; i < saveRestoreList->size(); ++i) {\n\t\tswitch ((SaveRestore::SaveResstoreId)(*saveRestoreList)[i]) {\n\t\tcase SaveRestore::SAVE_TO_DEVICE: {\n\t\t\tQToolButton *btn = new QToolButton();\n\t\t\tbtn->setToolButtonStyle(Qt::ToolButtonIconOnly);\n\t\t\tbtn->setText(\"Save\");\n\t\t\tbtn->setToolTip(tr(\"Save current settings to device\"));\n\t\t\ttoolBar->addWidget(btn);\n\t\t\tbtn->setIcon(QIcon(\":\/pixmaps\/saveto\"));\n\t\t\tconnect(btn, SIGNAL(pressed()), this, SLOT(storeToDevice()));\n\t\t} break;\n\t\tcase SaveRestore::RESTORE_FROM_DEVICE: {\n\t\t\tQToolButton *btn = new QToolButton();\n\t\t\tbtn->setToolButtonStyle(Qt::ToolButtonIconOnly);\n\t\t\tbtn->setText(\"Restore\");\n\t\t\tbtn->setToolTip(tr(\"Restore settings from device\"));\n\t\t\ttoolBar->addWidget(btn);\n\t\t\tbtn->setIcon(QIcon(\":\/pixmaps\/readfrom\"));\n\t\t\tconnect(btn, SIGNAL(pressed()), this, SLOT(restoreFromDevice()));\n\t\t} break;\n\t\tcase SaveRestore::SET_TO_FACTORY_DEFAULT: {\n\t\t\tQToolButton *btn = new QToolButton();\n\t\t\tbtn->setToolButtonStyle(Qt::ToolButtonIconOnly);\n\t\t\tbtn->setText(\"Fact\");\n\t\t\tbtn->setToolTip(tr(\"Reset settings to factory default\"));\n\t\t\ttoolBar->addWidget(btn);\n\t\t\tbtn->setIcon(QIcon(\":\/pixmaps\/restore\"));\n\t\t\tconnect(btn, SIGNAL(pressed()), this, SLOT(resetToFactoryDefaults()));\n\t\t} break;\n\t\tdefault:\n\t\t\tbreak;\n\t\t}\n\t}\n}\n\nvoid MioMain::openDeviceGUI(Device *d) {\n clearDocWidgets();\n\ttoolBar = new QToolBar(tr(\"Device Actions\"), this);\n\ttoolBar->setObjectName(\"DeviceActions\");\n\tthis->addToolBar(toolBar);\n\n\tthis->currentDevice = d;\n\td->connect();\n RetCommandList *c = d->getCommands();\n if (c == 0) {\n \/\/ TODO throw error\n exit(2);\n }\n setWindowTitle(this->title + QString(\": \") +\n QString::fromStdString(d->getDeviceName()));\n CentralWidget *centralWidget = new CentralWidget(this, d);\n this->addDock(centralWidget);\n\n DeviceInfoWidget *deviceInfoWidget =\n new DeviceInfoWidget(this, d, d->getDeviceInfo());\n this->addDock(deviceInfoWidget, Qt::LeftDockWidgetArea);\n\n PortsWidget *portsWidget = new PortsWidget(this, d);\n this->addDock(portsWidget, Qt::LeftDockWidgetArea);\n\n\taddDeviceToolButtons();\n\n QSettings *settings = Configuration::getInstance().getSettings();\n settings->beginGroup(\"MainWindow\");\n restoreGeometry(settings->value(\"geometry\").toByteArray());\n settings->endGroup();\n settings->beginGroup(\"Docks\");\n \/\/ restoreState(settings->value(\"DockWindows\").toByteArray());\n settings->endGroup();\n deviceInfoWidget->show();\n\tdeviceInfoWidget->raise();\n}\n\nvoid MioMain::storeToDevice() {\n\tQMessageBox msgBox;\n\tmsgBox.setText(tr(\"Store current setings to device?\"));\n\tmsgBox.setStandardButtons(QMessageBox::Ok | QMessageBox::Cancel);\n\tmsgBox.setDefaultButton(QMessageBox::Save);\n\tint ret = msgBox.exec();\n\tif (ret == QMessageBox::Ok)\n\t\tsaveRestore(SaveRestore::SAVE_TO_DEVICE);\n}\n\nvoid MioMain::restoreFromDevice() {\n\tQMessageBox msgBox;\n\tmsgBox.setText(tr(\"Read all settings from device?\"));\n\tmsgBox.setStandardButtons(QMessageBox::Ok | QMessageBox::Cancel);\n\tmsgBox.setDefaultButton(QMessageBox::Save);\n\tint ret = msgBox.exec();\n\tif (ret == QMessageBox::Ok) {\n\t\tsaveRestore(SaveRestore::RESTORE_FROM_DEVICE);\n\t\tcurrentDevice->disconnect();\n\t\tSLEEP(5000);\n\t\tbool valid = false;\n\t\tfor (int i = 0; i < 10; ++i) {\n\t\t\tcurrentDevice->connect();\n\t\t\tvalid = currentDevice->isDeviceValid();\n\t\t\tif (valid) {\n\t\t\t\tcurrentDevice->getDeviceInfo();\n\t\t\t\topenDeviceGUI(currentDevice);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif (!valid)\n\t\t\texit(-1);\n\t}\n}\n\nvoid MioMain::resetToFactoryDefaults() {\n\tQMessageBox msgBox;\n\tmsgBox.setText(tr(\"Reset all settings to factory default?\"));\n\tmsgBox.setStandardButtons(QMessageBox::Ok | QMessageBox::Cancel);\n\tmsgBox.setDefaultButton(QMessageBox::Save);\n\tint ret = msgBox.exec();\n\tif (ret == QMessageBox::Ok) {\n\t\tsaveRestore(SaveRestore::SET_TO_FACTORY_DEFAULT);\n\t\tcurrentDevice->disconnect();\n\t\topenDeviceGUI(this->currentDevice);\n\t}\n}\n\nvoid MioMain::saveRestore(SaveRestore::SaveResstoreId saveRestoreId) {\n\tSaveRestore *saveRestore = new SaveRestore(currentDevice);\n\tsaveRestore->setSaveRestoreId(saveRestoreId);\n\tsaveRestore->execute();\n}\n\nvoid MioMain::closeEvent(QCloseEvent *event) {\n writeSettings();\n event->accept();\n}\n\nvoid MioMain::openDetectionWindow() {\n deviceDetectionWindow = new DeviceDetection(this);\n deviceDetectionWindow->exec();\n}\n\nvoid MioMain::writeSettings() {\n QSettings *settings = Configuration::getInstance().getSettings();\n settings->beginGroup(\"MainWindow\");\n settings->setValue(\"geometry\", saveGeometry());\n settings->setValue(\"size\", size());\n settings->setValue(\"pos\", pos());\n settings->endGroup();\n settings->beginGroup(\"Docks\");\n settings->setValue(\"DockWindows\", saveState());\n settings->endGroup();\n}\n\nvoid MioMain::writeDevicesToSettings() {\n QSettings *settings = Configuration::getInstance().getSettings();\n Devices *devices = Configuration::getInstance().getDevices();\n settings->remove(\"Devices\");\n settings->beginWriteArray(\"Devices\");\n int i = 0;\n for (Devices::iterator it = devices->begin(); it != devices->end(); ++it) {\n settings->setArrayIndex(i);\n Device *d = it->second;\n settings->setValue(\"Device Name\",\n QString::fromStdString(d->getDeviceName()));\n settings->setValue(\"Serial Number\",\n (qlonglong)(d->getSerialNumber()->getLongValue()));\n settings->setValue(\"Input Port\", d->getInPortNumer());\n settings->setValue(\"Output Port\", d->getOutPortNumer());\n settings->setValue(\"Product Id\",\n (qlonglong)d->getProductId()->getLongValue());\n#ifdef __MIO_SIMULATE__\n if (d->getSimulate()) {\n settings->setValue(\"Simulate\", true);\n settings->setValue(\"Model Name\",\n QString::fromStdString(d->getModelName()));\n }\n#endif\n ++i;\n }\n settings->endArray();\n}\n\nvoid MioMain::connectSlots() {\n \/\/ connect(this->)\n}\n\nvoid MioMain::readSettings() {\n this->title = windowTitle();\n QSettings *settings = Configuration::getInstance().getSettings();\n settings->beginGroup(\"MainWindow\");\n resize(settings->value(\"size\", QSize(400, 400)).toSize());\n move(settings->value(\"pos\", QPoint(200, 200)).toPoint());\n settings->endGroup();\n}\n\nbool MioMain::readDevicesFromSettings() {\n Devices *devices = Configuration::getInstance().getDevices();\n devices->clear();\n QSettings *settings = Configuration::getInstance().getSettings();\n int size = settings->beginReadArray(\"Devices\");\n if (size == 0)\n return false;\n for (int i = 0; i < size; ++i) {\n Device *device = 0;\n settings->setArrayIndex(i);\n int productId = settings->value(\"Product Id\").toInt();\n long serialNumber =\n (qlonglong)settings->value(\"Serial Number\").toLongLong();\n int inputPort = (qlonglong)settings->value(\"Input Port\").toInt();\n int outputPort = (qlonglong)settings->value(\"Output Port\").toInt();\n bool simulate = settings->value(\"Simulate\").toBool();\n#ifdef __MIO_SIMULATE__\n if (simulate) {\n std::string modelName =\n settings->value(\"Model Name\").toString().toStdString();\n std::string deviceName =\n settings->value(\"Device Name\").toString().toStdString();\n device = new Device(inputPort, outputPort, serialNumber, productId,\n modelName, deviceName);\n } else {\n device = new Device(inputPort, outputPort, serialNumber, productId);\n }\n#else\n if (!simulate)\n device = new Device(inputPort, outputPort, serialNumber, productId);\n#endif\n if (device && device->queryDeviceInfo())\n devices->insert(std::pair<long, Device *>(serialNumber, device));\n }\n settings->endArray();\n if (devices->size() == 0)\n return false;\n return true;\n}\nvoid MioMain::on_actionQuit_triggered() { close(); }\n<|endoftext|>"} {"text":"<commit_before>\/\/===- CorrelatedValuePropagation.cpp - Propagate CFG-derived info --------===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This file implements the Correlated Value Propagation pass.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#define DEBUG_TYPE \"correlated-value-propagation\"\n#include \"llvm\/Transforms\/Scalar.h\"\n#include \"llvm\/Function.h\"\n#include \"llvm\/Instructions.h\"\n#include \"llvm\/Pass.h\"\n#include \"llvm\/Analysis\/LazyValueInfo.h\"\n#include \"llvm\/Support\/CFG.h\"\n#include \"llvm\/Transforms\/Utils\/Local.h\"\n#include \"llvm\/ADT\/DepthFirstIterator.h\"\n#include \"llvm\/ADT\/Statistic.h\"\nusing namespace llvm;\n\nSTATISTIC(NumPhis, \"Number of phis propagated\");\nSTATISTIC(NumSelects, \"Number of selects propagated\");\nSTATISTIC(NumMemAccess, \"Number of memory access targets propagated\");\nSTATISTIC(NumCmps, \"Number of comparisons propagated\");\n\nnamespace {\n class CorrelatedValuePropagation : public FunctionPass {\n LazyValueInfo *LVI;\n \n bool processSelect(SelectInst *SI);\n bool processPHI(PHINode *P);\n bool processMemAccess(Instruction *I);\n bool processCmp(CmpInst *C);\n \n public:\n static char ID;\n CorrelatedValuePropagation(): FunctionPass(ID) {\n initializeCorrelatedValuePropagationPass(*PassRegistry::getPassRegistry());\n }\n \n bool runOnFunction(Function &F);\n \n virtual void getAnalysisUsage(AnalysisUsage &AU) const {\n AU.addRequired<LazyValueInfo>();\n }\n };\n}\n\nchar CorrelatedValuePropagation::ID = 0;\nINITIALIZE_PASS_BEGIN(CorrelatedValuePropagation, \"correlated-propagation\",\n \"Value Propagation\", false, false)\nINITIALIZE_PASS_DEPENDENCY(LazyValueInfo)\nINITIALIZE_PASS_END(CorrelatedValuePropagation, \"correlated-propagation\",\n \"Value Propagation\", false, false)\n\n\/\/ Public interface to the Value Propagation pass\nPass *llvm::createCorrelatedValuePropagationPass() {\n return new CorrelatedValuePropagation();\n}\n\nbool CorrelatedValuePropagation::processSelect(SelectInst *S) {\n if (S->getType()->isVectorTy()) return false;\n if (isa<Constant>(S->getOperand(0))) return false;\n \n Constant *C = LVI->getConstant(S->getOperand(0), S->getParent());\n if (!C) return false;\n \n ConstantInt *CI = dyn_cast<ConstantInt>(C);\n if (!CI) return false;\n \n S->replaceAllUsesWith(S->getOperand(CI->isOne() ? 1 : 2));\n S->eraseFromParent();\n\n ++NumSelects;\n \n return true;\n}\n\nbool CorrelatedValuePropagation::processPHI(PHINode *P) {\n bool Changed = false;\n \n BasicBlock *BB = P->getParent();\n for (unsigned i = 0, e = P->getNumIncomingValues(); i < e; ++i) {\n Value *Incoming = P->getIncomingValue(i);\n if (isa<Constant>(Incoming)) continue;\n \n Constant *C = LVI->getConstantOnEdge(P->getIncomingValue(i),\n P->getIncomingBlock(i),\n BB);\n if (!C) continue;\n \n P->setIncomingValue(i, C);\n Changed = true;\n }\n \n if (Value *ConstVal = P->hasConstantValue()) {\n P->replaceAllUsesWith(ConstVal);\n P->eraseFromParent();\n Changed = true;\n }\n \n ++NumPhis;\n \n return Changed;\n}\n\nbool CorrelatedValuePropagation::processMemAccess(Instruction *I) {\n Value *Pointer = 0;\n if (LoadInst *L = dyn_cast<LoadInst>(I))\n Pointer = L->getPointerOperand();\n else\n Pointer = cast<StoreInst>(I)->getPointerOperand();\n \n if (isa<Constant>(Pointer)) return false;\n \n Constant *C = LVI->getConstant(Pointer, I->getParent());\n if (!C) return false;\n \n ++NumMemAccess;\n I->replaceUsesOfWith(Pointer, C);\n return true;\n}\n\n\/\/\/ processCmp - If the value of this comparison could be determined locally,\n\/\/\/ constant propagation would already have figured it out. Instead, walk\n\/\/\/ the predecessors and statically evaluate the comparison based on information\n\/\/\/ available on that edge. If a given static evaluation is true on ALL\n\/\/\/ incoming edges, then it's true universally and we can simplify the compare.\nbool CorrelatedValuePropagation::processCmp(CmpInst *C) {\n Value *Op0 = C->getOperand(0);\n if (isa<Instruction>(Op0) &&\n cast<Instruction>(Op0)->getParent() == C->getParent())\n return false;\n \n Constant *Op1 = dyn_cast<Constant>(C->getOperand(1));\n if (!Op1) return false;\n \n pred_iterator PI = pred_begin(C->getParent()), PE = pred_end(C->getParent());\n if (PI == PE) return false;\n \n LazyValueInfo::Tristate Result = LVI->getPredicateOnEdge(C->getPredicate(), \n C->getOperand(0), Op1, *PI, C->getParent());\n if (Result == LazyValueInfo::Unknown) return false;\n\n ++PI;\n while (PI != PE) {\n LazyValueInfo::Tristate Res = LVI->getPredicateOnEdge(C->getPredicate(), \n C->getOperand(0), Op1, *PI, C->getParent());\n if (Res != Result) return false;\n ++PI;\n }\n \n ++NumCmps;\n \n if (Result == LazyValueInfo::True)\n C->replaceAllUsesWith(ConstantInt::getTrue(C->getContext()));\n else\n C->replaceAllUsesWith(ConstantInt::getFalse(C->getContext()));\n \n C->eraseFromParent();\n\n return true;\n}\n\nbool CorrelatedValuePropagation::runOnFunction(Function &F) {\n LVI = &getAnalysis<LazyValueInfo>();\n \n bool FnChanged = false;\n \n \/\/ Perform a depth-first walk of the CFG so that we don't waste time\n \/\/ optimizing unreachable blocks.\n for (df_iterator<BasicBlock*> FI = df_begin(&F.getEntryBlock()),\n FE = df_end(&F.getEntryBlock()); FI != FE; ++FI) {\n bool BBChanged = false;\n for (BasicBlock::iterator BI = FI->begin(), BE = FI->end(); BI != BE; ) {\n Instruction *II = BI++;\n switch (II->getOpcode()) {\n case Instruction::Select:\n BBChanged |= processSelect(cast<SelectInst>(II));\n break;\n case Instruction::PHI:\n BBChanged |= processPHI(cast<PHINode>(II));\n break;\n case Instruction::ICmp:\n case Instruction::FCmp:\n BBChanged |= processCmp(cast<CmpInst>(II));\n break;\n case Instruction::Load:\n case Instruction::Store:\n BBChanged |= processMemAccess(II);\n break;\n }\n }\n \n \/\/ Propagating correlated values might leave cruft around.\n \/\/ Try to clean it up before we continue.\n if (BBChanged)\n SimplifyInstructionsInBlock(*FI);\n \n FnChanged |= BBChanged;\n }\n \n return FnChanged;\n}\n<commit_msg>Give up on doing in-line instruction simplification during correlated value propagation. Instruction simplification needs to be guaranteed never to be run on an unreachable block. However, earlier block simplifications may have changed the CFG to make block that were reachable when we began our iteration unreachable by the time we try to simplify them. (Note that this also means that our depth-first iterators were potentially being invalidated).<commit_after>\/\/===- CorrelatedValuePropagation.cpp - Propagate CFG-derived info --------===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This file implements the Correlated Value Propagation pass.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#define DEBUG_TYPE \"correlated-value-propagation\"\n#include \"llvm\/Transforms\/Scalar.h\"\n#include \"llvm\/Function.h\"\n#include \"llvm\/Instructions.h\"\n#include \"llvm\/Pass.h\"\n#include \"llvm\/Analysis\/LazyValueInfo.h\"\n#include \"llvm\/Support\/CFG.h\"\n#include \"llvm\/Transforms\/Utils\/Local.h\"\n#include \"llvm\/ADT\/Statistic.h\"\nusing namespace llvm;\n\nSTATISTIC(NumPhis, \"Number of phis propagated\");\nSTATISTIC(NumSelects, \"Number of selects propagated\");\nSTATISTIC(NumMemAccess, \"Number of memory access targets propagated\");\nSTATISTIC(NumCmps, \"Number of comparisons propagated\");\n\nnamespace {\n class CorrelatedValuePropagation : public FunctionPass {\n LazyValueInfo *LVI;\n \n bool processSelect(SelectInst *SI);\n bool processPHI(PHINode *P);\n bool processMemAccess(Instruction *I);\n bool processCmp(CmpInst *C);\n \n public:\n static char ID;\n CorrelatedValuePropagation(): FunctionPass(ID) {\n initializeCorrelatedValuePropagationPass(*PassRegistry::getPassRegistry());\n }\n \n bool runOnFunction(Function &F);\n \n virtual void getAnalysisUsage(AnalysisUsage &AU) const {\n AU.addRequired<LazyValueInfo>();\n }\n };\n}\n\nchar CorrelatedValuePropagation::ID = 0;\nINITIALIZE_PASS_BEGIN(CorrelatedValuePropagation, \"correlated-propagation\",\n \"Value Propagation\", false, false)\nINITIALIZE_PASS_DEPENDENCY(LazyValueInfo)\nINITIALIZE_PASS_END(CorrelatedValuePropagation, \"correlated-propagation\",\n \"Value Propagation\", false, false)\n\n\/\/ Public interface to the Value Propagation pass\nPass *llvm::createCorrelatedValuePropagationPass() {\n return new CorrelatedValuePropagation();\n}\n\nbool CorrelatedValuePropagation::processSelect(SelectInst *S) {\n if (S->getType()->isVectorTy()) return false;\n if (isa<Constant>(S->getOperand(0))) return false;\n \n Constant *C = LVI->getConstant(S->getOperand(0), S->getParent());\n if (!C) return false;\n \n ConstantInt *CI = dyn_cast<ConstantInt>(C);\n if (!CI) return false;\n \n S->replaceAllUsesWith(S->getOperand(CI->isOne() ? 1 : 2));\n S->eraseFromParent();\n\n ++NumSelects;\n \n return true;\n}\n\nbool CorrelatedValuePropagation::processPHI(PHINode *P) {\n bool Changed = false;\n \n BasicBlock *BB = P->getParent();\n for (unsigned i = 0, e = P->getNumIncomingValues(); i < e; ++i) {\n Value *Incoming = P->getIncomingValue(i);\n if (isa<Constant>(Incoming)) continue;\n \n Constant *C = LVI->getConstantOnEdge(P->getIncomingValue(i),\n P->getIncomingBlock(i),\n BB);\n if (!C) continue;\n \n P->setIncomingValue(i, C);\n Changed = true;\n }\n \n if (Value *ConstVal = P->hasConstantValue()) {\n P->replaceAllUsesWith(ConstVal);\n P->eraseFromParent();\n Changed = true;\n }\n \n ++NumPhis;\n \n return Changed;\n}\n\nbool CorrelatedValuePropagation::processMemAccess(Instruction *I) {\n Value *Pointer = 0;\n if (LoadInst *L = dyn_cast<LoadInst>(I))\n Pointer = L->getPointerOperand();\n else\n Pointer = cast<StoreInst>(I)->getPointerOperand();\n \n if (isa<Constant>(Pointer)) return false;\n \n Constant *C = LVI->getConstant(Pointer, I->getParent());\n if (!C) return false;\n \n ++NumMemAccess;\n I->replaceUsesOfWith(Pointer, C);\n return true;\n}\n\n\/\/\/ processCmp - If the value of this comparison could be determined locally,\n\/\/\/ constant propagation would already have figured it out. Instead, walk\n\/\/\/ the predecessors and statically evaluate the comparison based on information\n\/\/\/ available on that edge. If a given static evaluation is true on ALL\n\/\/\/ incoming edges, then it's true universally and we can simplify the compare.\nbool CorrelatedValuePropagation::processCmp(CmpInst *C) {\n Value *Op0 = C->getOperand(0);\n if (isa<Instruction>(Op0) &&\n cast<Instruction>(Op0)->getParent() == C->getParent())\n return false;\n \n Constant *Op1 = dyn_cast<Constant>(C->getOperand(1));\n if (!Op1) return false;\n \n pred_iterator PI = pred_begin(C->getParent()), PE = pred_end(C->getParent());\n if (PI == PE) return false;\n \n LazyValueInfo::Tristate Result = LVI->getPredicateOnEdge(C->getPredicate(), \n C->getOperand(0), Op1, *PI, C->getParent());\n if (Result == LazyValueInfo::Unknown) return false;\n\n ++PI;\n while (PI != PE) {\n LazyValueInfo::Tristate Res = LVI->getPredicateOnEdge(C->getPredicate(), \n C->getOperand(0), Op1, *PI, C->getParent());\n if (Res != Result) return false;\n ++PI;\n }\n \n ++NumCmps;\n \n if (Result == LazyValueInfo::True)\n C->replaceAllUsesWith(ConstantInt::getTrue(C->getContext()));\n else\n C->replaceAllUsesWith(ConstantInt::getFalse(C->getContext()));\n \n C->eraseFromParent();\n\n return true;\n}\n\nbool CorrelatedValuePropagation::runOnFunction(Function &F) {\n LVI = &getAnalysis<LazyValueInfo>();\n \n bool FnChanged = false;\n \n for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) {\n bool BBChanged = false;\n for (BasicBlock::iterator BI = FI->begin(), BE = FI->end(); BI != BE; ) {\n Instruction *II = BI++;\n switch (II->getOpcode()) {\n case Instruction::Select:\n BBChanged |= processSelect(cast<SelectInst>(II));\n break;\n case Instruction::PHI:\n BBChanged |= processPHI(cast<PHINode>(II));\n break;\n case Instruction::ICmp:\n case Instruction::FCmp:\n BBChanged |= processCmp(cast<CmpInst>(II));\n break;\n case Instruction::Load:\n case Instruction::Store:\n BBChanged |= processMemAccess(II);\n break;\n }\n }\n \n FnChanged |= BBChanged;\n }\n \n return FnChanged;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2009 Minor Gordon.\r\n\/\/ This source comes from the XtreemFS project. It is licensed under the GPLv2 (see COPYING for terms and conditions).\r\n\r\n#include \"org\/xtreemfs\/client\/proxy.h\"\r\n#include \"policy_container.h\"\r\n#include \"platform_exception_event.h\"\r\nusing namespace org::xtreemfs::client;\r\n\r\n#include \"org\/xtreemfs\/interfaces\/constants.h\"\r\n\r\n#include <algorithm>\r\n\r\n#ifdef _WIN32\r\n#include \"yield\/platform\/windows.h\"\r\n#define ETIMEDOUT WSAETIMEDOUT\r\n#else\r\n#include <errno.h>\r\n#endif\r\n\r\n\r\nProxy::Proxy( const YIELD::URI& uri, uint16_t default_oncrpc_port )\r\n : uri( uri )\r\n{\r\n ssl_context = NULL;\r\n log = NULL;\r\n init( default_oncrpc_port );\r\n}\r\n\r\nProxy::Proxy( const YIELD::URI& uri, YIELD::Log& log, uint16_t default_oncrpc_port )\r\n : uri( uri ), log( &log )\r\n{\r\n ssl_context = NULL;\r\n init( default_oncrpc_port );\r\n}\r\n\r\nProxy::Proxy( const YIELD::URI& uri, YIELD::SSLContext& ssl_context, uint16_t default_oncrpcs_port )\r\n: uri( uri ), ssl_context( &ssl_context )\r\n{\r\n log = NULL;\r\n init( default_oncrpcs_port );\r\n}\r\n\r\nProxy::Proxy( const YIELD::URI& uri, YIELD::SSLContext& ssl_context, YIELD::Log& log, uint16_t default_oncrpcs_port )\r\n: uri( uri ), ssl_context( &ssl_context ), log( &log )\r\n{\r\n init( default_oncrpcs_port );\r\n}\r\n\r\nvoid Proxy::init( uint16_t default_port )\r\n{\r\n peer_sockaddr = this->uri;\r\n\r\n if ( this->uri.get_port() == 0 )\r\n this->uri.set_port( default_port );\r\n\r\n policies = new PolicyContainer;\r\n\r\n flags = PROXY_DEFAULT_FLAGS;\r\n reconnect_tries_max = PROXY_DEFAULT_RECONNECT_TRIES_MAX;\r\n operation_timeout_ms = PROXY_DEFAULT_OPERATION_TIMEOUT_MS;\r\n\r\n conn = NULL;\r\n\r\n org::xtreemfs::interfaces::Exceptions().registerObjectFactories( object_factories );\r\n}\r\n\r\nProxy::~Proxy()\r\n{\r\n delete policies;\r\n delete conn;\r\n YIELD::Object::decRef( ssl_context );\r\n YIELD::Object::decRef( log );\r\n}\r\n\r\nvoid Proxy::handleEvent( YIELD::Event& ev )\r\n{\r\n switch ( ev.get_type_id() )\r\n {\r\n case YIELD_OBJECT_TYPE_ID( YIELD::StageStartupEvent ):\r\n case YIELD_OBJECT_TYPE_ID( YIELD::StageShutdownEvent ): YIELD::Object::decRef( ev ); break;\r\n\r\n default:\r\n {\r\n switch ( ev.get_general_type() )\r\n {\r\n case YIELD::Object::REQUEST:\r\n {\r\n YIELD::Request& req = static_cast<YIELD::Request&>( ev );\r\n if ( ( flags & PROXY_FLAG_PRINT_OPERATIONS ) == PROXY_FLAG_PRINT_OPERATIONS )\r\n {\r\n YIELD::PrettyPrintOutputStream pretty_print_output_stream( std::cout );\r\n pretty_print_output_stream.writeObject( YIELD::PrettyPrintOutputStream::Declaration( req.get_type_name() ), req );\r\n }\r\n\r\n try\r\n {\r\n org::xtreemfs::interfaces::UserCredentials user_credentials;\r\n policies->getCurrentUserCredentials( user_credentials );\r\n YIELD::ONCRPCRequest oncrpc_req( YIELD::Object::incRef( req ), object_factories, org::xtreemfs::interfaces::ONCRPC_AUTH_FLAVOR, &user_credentials );\r\n\r\n uint8_t reconnect_tries_left = reconnect_tries_max;\r\n if ( conn == NULL )\r\n reconnect_tries_left = reconnect( reconnect_tries_left );\r\n\r\n uint64_t remaining_operation_timeout_ms = operation_timeout_ms;\r\n if ( operation_timeout_ms == static_cast<uint64_t>( -1 ) || ssl_context != NULL )\r\n conn->setBlocking();\r\n else\r\n conn->setBlocking();\r\n\r\n bool have_written = false;\r\n\r\n for ( ;; )\r\n { \r\n if ( !have_written )\r\n {\r\n if ( oncrpc_req.serialize( *conn ) )\r\n {\r\n have_written = true;\r\n continue;\r\n }\r\n }\r\n else\r\n {\r\n if ( oncrpc_req.deserialize( *conn ) )\r\n {\r\n req.respond( static_cast<YIELD::Event&>( YIELD::Object::incRef( *oncrpc_req.getInBody() ) ) );\r\n YIELD::Object::decRef( req );\r\n return;\r\n }\r\n }\r\n\r\n if ( YIELD::Socket::WOULDBLOCK() )\r\n {\r\n if ( remaining_operation_timeout_ms > 0 )\r\n {\r\n fd_event_queue.toggleSocketEvent( *conn, conn, have_written, !have_written );\r\n double start_epoch_time_ms = YIELD::Time::getCurrentUnixTimeMS();\r\n YIELD::FDEvent* fd_event = static_cast<YIELD::FDEvent*>( fd_event_queue.timed_dequeue( static_cast<YIELD::timeout_ns_t>( remaining_operation_timeout_ms ) * NS_IN_MS ) );\r\n if ( fd_event )\r\n {\r\n if ( fd_event->error_code == 0 )\r\n remaining_operation_timeout_ms -= std::min( static_cast<uint64_t>( YIELD::Time::getCurrentUnixTimeMS() - start_epoch_time_ms ), remaining_operation_timeout_ms );\r\n else\r\n reconnect_tries_left = reconnect( reconnect_tries_left );\r\n }\r\n else\r\n throwExceptionEvent( new PlatformExceptionEvent( ETIMEDOUT ) );\r\n }\r\n else\r\n throwExceptionEvent( new PlatformExceptionEvent( ETIMEDOUT ) );\r\n }\r\n else\r\n reconnect_tries_left = reconnect( reconnect_tries_left );\r\n }\r\n }\r\n catch ( YIELD::ExceptionEvent* exc_ev )\r\n {\r\n req.respond( *exc_ev );\r\n YIELD::Object::decRef( req );\r\n }\r\n }\r\n break;\r\n\r\n default: YIELD::DebugBreak(); break;\r\n }\r\n }\r\n break;\r\n }\r\n}\r\n\r\nuint8_t Proxy::reconnect( uint8_t reconnect_tries_left )\r\n{\r\n if ( conn != NULL ) \/\/ This is a reconnect, not the first connect\r\n {\r\n fd_event_queue.detachSocket( *conn, conn );\r\n conn->close();\r\n delete conn;\r\n conn = NULL;\r\n }\r\n\r\n while( reconnect_tries_left == static_cast<uint8_t>( -1 ) ||\r\n --reconnect_tries_left > 0 )\r\n {\r\n \/\/ Create the conn object based on the URI type\r\n if ( ssl_context == NULL )\r\n conn = new YIELD::TCPSocket;\r\n else\r\n conn = new YIELD::SSLSocket( *ssl_context );\r\n\r\n \/\/ Attach the socket to the fd_event_queue even if we're doing a blocking connect, in case a later read\/write is non-blocking\r\n fd_event_queue.attachSocket( *conn, conn, false, false ); \/\/ Attach without read or write notifications enabled\r\n\r\n \/\/ Now try the actual connect\r\n if ( operation_timeout_ms == static_cast<uint64_t>( -1 ) || ssl_context != NULL ) \/\/ Blocking\r\n {\r\n conn->setBlocking();\r\n if ( conn->connect( peer_sockaddr ) )\r\n return reconnect_tries_left;\r\n }\r\n else \/\/ Non-blocking\/timed\r\n {\r\n uint64_t remaining_operation_timeout_ms = operation_timeout_ms;\r\n conn->setNonBlocking();\r\n\r\n if ( conn->connect( peer_sockaddr ) )\r\n break;\r\n else if ( YIELD::Socket::WOULDBLOCK() )\r\n {\r\n fd_event_queue.toggleSocketEvent( *conn, conn, false, true ); \/\/ Write readiness = the connect() operation is complete\r\n double start_epoch_time_ms = YIELD::Time::getCurrentUnixTimeMS();\r\n YIELD::FDEvent* fd_event = static_cast<YIELD::FDEvent*>( fd_event_queue.timed_dequeue( static_cast<YIELD::timeout_ns_t>( remaining_operation_timeout_ms ) * NS_IN_MS ) );\r\n if ( fd_event && fd_event->error_code == 0 && conn->connect( peer_sockaddr ) )\r\n {\r\n fd_event_queue.toggleSocketEvent( *conn, conn, false, false );\r\n return reconnect_tries_left;\r\n }\r\n else\r\n {\r\n remaining_operation_timeout_ms -= std::min( static_cast<uint64_t>( YIELD::Time::getCurrentUnixTimeMS() - start_epoch_time_ms ), remaining_operation_timeout_ms );\r\n if ( remaining_operation_timeout_ms == 0 ) { reconnect_tries_left = 0; break; }\r\n }\r\n }\r\n }\r\n\r\n \/\/ Clear the connection state for the next try\r\n fd_event_queue.detachSocket( *conn, conn );\r\n conn->close();\r\n delete conn;\r\n conn = NULL;\r\n }\r\n\r\n unsigned long error_code = YIELD::PlatformException::errno_();\r\n if ( error_code == 0 )\r\n error_code = ETIMEDOUT;\r\n throw new PlatformExceptionEvent( error_code );\r\n}\r\n\r\nvoid Proxy::throwExceptionEvent( YIELD::ExceptionEvent* exc_ev )\r\n{\r\n if ( conn )\r\n {\r\n fd_event_queue.detachSocket( *conn, conn );\r\n conn->close();\r\n delete conn;\r\n conn = NULL;\r\n }\r\n\r\n throw exc_ev;\r\n}\r\n<commit_msg>client: Proxy: small bug fix<commit_after>\/\/ Copyright 2009 Minor Gordon.\r\n\/\/ This source comes from the XtreemFS project. It is licensed under the GPLv2 (see COPYING for terms and conditions).\r\n\r\n#include \"org\/xtreemfs\/client\/proxy.h\"\r\n#include \"policy_container.h\"\r\n#include \"platform_exception_event.h\"\r\nusing namespace org::xtreemfs::client;\r\n\r\n#include \"org\/xtreemfs\/interfaces\/constants.h\"\r\n\r\n#include <algorithm>\r\n\r\n#ifdef _WIN32\r\n#include \"yield\/platform\/windows.h\"\r\n#define ETIMEDOUT WSAETIMEDOUT\r\n#else\r\n#include <errno.h>\r\n#endif\r\n\r\n\r\nProxy::Proxy( const YIELD::URI& uri, uint16_t default_oncrpc_port )\r\n : uri( uri )\r\n{\r\n ssl_context = NULL;\r\n log = NULL;\r\n init( default_oncrpc_port );\r\n}\r\n\r\nProxy::Proxy( const YIELD::URI& uri, YIELD::Log& log, uint16_t default_oncrpc_port )\r\n : uri( uri ), log( &log )\r\n{\r\n ssl_context = NULL;\r\n init( default_oncrpc_port );\r\n}\r\n\r\nProxy::Proxy( const YIELD::URI& uri, YIELD::SSLContext& ssl_context, uint16_t default_oncrpcs_port )\r\n: uri( uri ), ssl_context( &ssl_context )\r\n{\r\n log = NULL;\r\n init( default_oncrpcs_port );\r\n}\r\n\r\nProxy::Proxy( const YIELD::URI& uri, YIELD::SSLContext& ssl_context, YIELD::Log& log, uint16_t default_oncrpcs_port )\r\n: uri( uri ), ssl_context( &ssl_context ), log( &log )\r\n{\r\n init( default_oncrpcs_port );\r\n}\r\n\r\nvoid Proxy::init( uint16_t default_port )\r\n{\r\n if ( this->uri.get_port() == 0 )\r\n this->uri.set_port( default_port );\r\n\r\n peer_sockaddr = this->uri;\r\n\r\n policies = new PolicyContainer;\r\n\r\n flags = PROXY_DEFAULT_FLAGS;\r\n reconnect_tries_max = PROXY_DEFAULT_RECONNECT_TRIES_MAX;\r\n operation_timeout_ms = PROXY_DEFAULT_OPERATION_TIMEOUT_MS;\r\n\r\n conn = NULL;\r\n\r\n org::xtreemfs::interfaces::Exceptions().registerObjectFactories( object_factories );\r\n}\r\n\r\nProxy::~Proxy()\r\n{\r\n delete policies;\r\n delete conn;\r\n YIELD::Object::decRef( ssl_context );\r\n YIELD::Object::decRef( log );\r\n}\r\n\r\nvoid Proxy::handleEvent( YIELD::Event& ev )\r\n{\r\n switch ( ev.get_type_id() )\r\n {\r\n case YIELD_OBJECT_TYPE_ID( YIELD::StageStartupEvent ):\r\n case YIELD_OBJECT_TYPE_ID( YIELD::StageShutdownEvent ): YIELD::Object::decRef( ev ); break;\r\n\r\n default:\r\n {\r\n switch ( ev.get_general_type() )\r\n {\r\n case YIELD::Object::REQUEST:\r\n {\r\n YIELD::Request& req = static_cast<YIELD::Request&>( ev );\r\n if ( ( flags & PROXY_FLAG_PRINT_OPERATIONS ) == PROXY_FLAG_PRINT_OPERATIONS )\r\n {\r\n YIELD::PrettyPrintOutputStream pretty_print_output_stream( std::cout );\r\n pretty_print_output_stream.writeObject( YIELD::PrettyPrintOutputStream::Declaration( req.get_type_name() ), req );\r\n }\r\n\r\n try\r\n {\r\n org::xtreemfs::interfaces::UserCredentials user_credentials;\r\n policies->getCurrentUserCredentials( user_credentials );\r\n YIELD::ONCRPCRequest oncrpc_req( YIELD::Object::incRef( req ), object_factories, org::xtreemfs::interfaces::ONCRPC_AUTH_FLAVOR, &user_credentials );\r\n\r\n uint8_t reconnect_tries_left = reconnect_tries_max;\r\n if ( conn == NULL )\r\n reconnect_tries_left = reconnect( reconnect_tries_left );\r\n\r\n uint64_t remaining_operation_timeout_ms = operation_timeout_ms;\r\n if ( operation_timeout_ms == static_cast<uint64_t>( -1 ) || ssl_context != NULL )\r\n conn->setBlocking();\r\n else\r\n conn->setBlocking();\r\n\r\n bool have_written = false;\r\n\r\n for ( ;; )\r\n { \r\n if ( !have_written )\r\n {\r\n if ( oncrpc_req.serialize( *conn ) )\r\n {\r\n have_written = true;\r\n continue;\r\n }\r\n }\r\n else\r\n {\r\n if ( oncrpc_req.deserialize( *conn ) )\r\n {\r\n req.respond( static_cast<YIELD::Event&>( YIELD::Object::incRef( *oncrpc_req.getInBody() ) ) );\r\n YIELD::Object::decRef( req );\r\n return;\r\n }\r\n }\r\n\r\n if ( YIELD::Socket::WOULDBLOCK() )\r\n {\r\n if ( remaining_operation_timeout_ms > 0 )\r\n {\r\n fd_event_queue.toggleSocketEvent( *conn, conn, have_written, !have_written );\r\n double start_epoch_time_ms = YIELD::Time::getCurrentUnixTimeMS();\r\n YIELD::FDEvent* fd_event = static_cast<YIELD::FDEvent*>( fd_event_queue.timed_dequeue( static_cast<YIELD::timeout_ns_t>( remaining_operation_timeout_ms ) * NS_IN_MS ) );\r\n if ( fd_event )\r\n {\r\n if ( fd_event->error_code == 0 )\r\n remaining_operation_timeout_ms -= std::min( static_cast<uint64_t>( YIELD::Time::getCurrentUnixTimeMS() - start_epoch_time_ms ), remaining_operation_timeout_ms );\r\n else\r\n reconnect_tries_left = reconnect( reconnect_tries_left );\r\n }\r\n else\r\n throwExceptionEvent( new PlatformExceptionEvent( ETIMEDOUT ) );\r\n }\r\n else\r\n throwExceptionEvent( new PlatformExceptionEvent( ETIMEDOUT ) );\r\n }\r\n else\r\n reconnect_tries_left = reconnect( reconnect_tries_left );\r\n }\r\n }\r\n catch ( YIELD::ExceptionEvent* exc_ev )\r\n {\r\n req.respond( *exc_ev );\r\n YIELD::Object::decRef( req );\r\n }\r\n }\r\n break;\r\n\r\n default: YIELD::DebugBreak(); break;\r\n }\r\n }\r\n break;\r\n }\r\n}\r\n\r\nuint8_t Proxy::reconnect( uint8_t reconnect_tries_left )\r\n{\r\n if ( conn != NULL ) \/\/ This is a reconnect, not the first connect\r\n {\r\n fd_event_queue.detachSocket( *conn, conn );\r\n conn->close();\r\n delete conn;\r\n conn = NULL;\r\n }\r\n\r\n while( reconnect_tries_left == static_cast<uint8_t>( -1 ) ||\r\n --reconnect_tries_left > 0 )\r\n {\r\n \/\/ Create the conn object based on the URI type\r\n if ( ssl_context == NULL )\r\n conn = new YIELD::TCPSocket;\r\n else\r\n conn = new YIELD::SSLSocket( *ssl_context );\r\n\r\n \/\/ Attach the socket to the fd_event_queue even if we're doing a blocking connect, in case a later read\/write is non-blocking\r\n fd_event_queue.attachSocket( *conn, conn, false, false ); \/\/ Attach without read or write notifications enabled\r\n\r\n \/\/ Now try the actual connect\r\n if ( operation_timeout_ms == static_cast<uint64_t>( -1 ) || ssl_context != NULL ) \/\/ Blocking\r\n {\r\n conn->setBlocking();\r\n if ( conn->connect( peer_sockaddr ) )\r\n return reconnect_tries_left;\r\n }\r\n else \/\/ Non-blocking\/timed\r\n {\r\n uint64_t remaining_operation_timeout_ms = operation_timeout_ms;\r\n conn->setNonBlocking();\r\n\r\n if ( conn->connect( peer_sockaddr ) )\r\n break;\r\n else if ( YIELD::Socket::WOULDBLOCK() )\r\n {\r\n fd_event_queue.toggleSocketEvent( *conn, conn, false, true ); \/\/ Write readiness = the connect() operation is complete\r\n double start_epoch_time_ms = YIELD::Time::getCurrentUnixTimeMS();\r\n YIELD::FDEvent* fd_event = static_cast<YIELD::FDEvent*>( fd_event_queue.timed_dequeue( static_cast<YIELD::timeout_ns_t>( remaining_operation_timeout_ms ) * NS_IN_MS ) );\r\n if ( fd_event && fd_event->error_code == 0 && conn->connect( peer_sockaddr ) )\r\n {\r\n fd_event_queue.toggleSocketEvent( *conn, conn, false, false );\r\n return reconnect_tries_left;\r\n }\r\n else\r\n {\r\n remaining_operation_timeout_ms -= std::min( static_cast<uint64_t>( YIELD::Time::getCurrentUnixTimeMS() - start_epoch_time_ms ), remaining_operation_timeout_ms );\r\n if ( remaining_operation_timeout_ms == 0 ) { reconnect_tries_left = 0; break; }\r\n }\r\n }\r\n }\r\n\r\n \/\/ Clear the connection state for the next try\r\n fd_event_queue.detachSocket( *conn, conn );\r\n conn->close();\r\n delete conn;\r\n conn = NULL;\r\n }\r\n\r\n unsigned long error_code = YIELD::PlatformException::errno_();\r\n if ( error_code == 0 )\r\n error_code = ETIMEDOUT;\r\n throw new PlatformExceptionEvent( error_code );\r\n}\r\n\r\nvoid Proxy::throwExceptionEvent( YIELD::ExceptionEvent* exc_ev )\r\n{\r\n if ( conn )\r\n {\r\n fd_event_queue.detachSocket( *conn, conn );\r\n conn->close();\r\n delete conn;\r\n conn = NULL;\r\n }\r\n\r\n throw exc_ev;\r\n}\r\n<|endoftext|>"} {"text":"<commit_before>#pragma once\n\n#include <iostream>\n#include <cmath>\n\n\/\/ ----------------------------------------------------------------------\n\nnamespace acmacs\n{\n constexpr double sqr(double value) { return value * value; }\n\n class LineDefinedByEquation\n {\n public:\n LineDefinedByEquation() = default;\n LineDefinedByEquation(double slope, double intercept) : slope_{slope}, intercept_{intercept} {}\n\n constexpr double slope() const { return slope_; }\n constexpr double intercept() const { return intercept_; }\n\n template <typename V> double distance_with_direction(const V& vect) const\n {\n return (slope() * vect[0] - vect[1] + intercept()) \/ std::sqrt(sqr(slope()) + 1);\n }\n\n template <typename V> double distance_to(const V& vect) const { return std::abs(distance_with_direction(vect)); }\n\n template <typename V> V project_on(const V& source) const\n {\n return source;\n }\n\n private:\n double slope_ = 1;\n double intercept_ = 0;\n\n }; \/\/ class LineDefinedByEquation\n\n inline std::ostream& operator<<(std::ostream& out, const LineDefinedByEquation& line) { return out << \"Line(slope:\" << line.slope() << \", intercept:\" << line.intercept() << ')'; }\n\n} \/\/ namespace acmacs\n\n\/\/ ----------------------------------------------------------------------\n\/\/\/ Local Variables:\n\/\/\/ eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))\n\/\/\/ End:\n<commit_msg>acmacs::LineDefinedByEquation::project_on()<commit_after>#pragma once\n\n#include <iostream>\n#include <cmath>\n\n\/\/ ----------------------------------------------------------------------\n\nnamespace acmacs\n{\n constexpr double sqr(double value) { return value * value; }\n\n class LineDefinedByEquation\n {\n public:\n LineDefinedByEquation() = default;\n LineDefinedByEquation(double slope, double intercept) : slope_{slope}, intercept_{intercept} {}\n\n constexpr double slope() const { return slope_; }\n constexpr double intercept() const { return intercept_; }\n\n \/\/ https:\/\/en.wikipedia.org\/wiki\/Distance_from_a_point_to_a_line\n template <typename V> double distance_with_direction(const V& vect) const\n {\n return (slope() * vect[0] - vect[1] + intercept()) \/ std::sqrt(a2b2());\n }\n\n template <typename V> double distance_to(const V& vect) const { return std::abs(distance_with_direction(vect)); }\n\n template <typename V> V project_on(const V& source) const\n {\n return {(source[0] + slope() * source[1] - slope() * intercept()) \/ a2b2(),\n (slope() * (source[0] + slope() * source[1]) + intercept()) \/ a2b2()};\n }\n\n private:\n double slope_ = 1;\n double intercept_ = 0;\n\n constexpr double a2b2() const { return sqr(slope()) + 1; }\n\n }; \/\/ class LineDefinedByEquation\n\n inline std::ostream& operator<<(std::ostream& out, const LineDefinedByEquation& line) { return out << \"Line(slope:\" << line.slope() << \", intercept:\" << line.intercept() << ')'; }\n\n} \/\/ namespace acmacs\n\n\/\/ ----------------------------------------------------------------------\n\/\/\/ Local Variables:\n\/\/\/ eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))\n\/\/\/ End:\n<|endoftext|>"} {"text":"<commit_before>#include <stdio.h>\n#include <stdlib.h>\n#include <signal.h>\n#include <unistd.h>\n#include <string.h>\n#include <time.h>\n#include <pthread.h>\n#include <sys\/time.h>\n\n#include <boost\/unordered_map.hpp>\n\n#include \"SignalRoutine.h\"\n#include \"..\/Log.h\"\n#include \"..\/Cache.h\"\n\n\/*\n * Define log types\n * l_ means local log types, each thread has a log\n * g_ means global log types, each shared variable has a log\n * r -> read \n * w -> write\n * l -> lock\n * m -> mutex init\n * f -> fork\n *\/\ntypedef struct {\n \/\/ <long\/void *> sizeof pointer usually equals to sizeof long\n LastOnePredictorLog<long> VAL_LOG; \n \/\/ <int>, -1 is the place holder, means the read operation reads\n \/\/ the local value\n LastOnePredictorLog<int> VER_LOG; \n} l_rlog_t;\n\ntypedef VLastOnePredictorLog l_wlog_t;\n\ntypedef LastOnePredictorLog<pthread_t> g_llog_t;\n\ntypedef LastOnePredictorLog<pthread_t> g_mlog_t;\n\ntypedef LastOnePredictorLog<pthread_t> g_flog_t;\n\ntypedef struct {\n void* address;\n size_t range;\n} mem_t;\n\ntypedef struct {\n std::vector<mem_t *> ADDRESS_LOG;\n VLastOnePredictorLog BIRTHDAY_LOG;\n} l_addmap_t;\n\n\/*\n * Define local log keys\n *\/\nstatic pthread_key_t rlog_key;\nstatic pthread_key_t wlog_key;\nstatic pthread_key_t cache_key;\nstatic pthread_key_t birthday_key;\nstatic pthread_key_t address_birthday_map_key;\n\n\/*\n * Define global log variables, each shared var has one\n *\/\nstatic std::vector<g_llog_t *> llogs; \/\/ <g_llog_t *> size is not fixed, and should be determined at runtime\nstatic g_flog_t flog;\nstatic g_mlog_t mlog;\n\n\/*\n * write versions, each shared var has a version\n *\/\nstatic unsigned* write_versions;\n\n\/*\n * locks for synchronization, each shared var has one\n *\/\nstatic pthread_mutex_t* locks;\nstatic pthread_mutex_t fork_lock = PTHREAD_MUTEX_INITIALIZER;\nstatic pthread_mutex_t mutex_init_lock = PTHREAD_MUTEX_INITIALIZER;\n\n\/*\n * mutex_t-> mutex_id hashmap\n * pthread_t -> thread_id hashmap\n *\/\nstatic unsigned mutex_id = 0;\nstatic boost::unordered_map<pthread_mutex_t *, unsigned> mutex_ht;\nstatic boost::unordered_map<pthread_t, unsigned> thread_ht;\nstatic boost::unordered_map<pthread_t, l_rlog_t*> rlogs;\nstatic boost::unordered_map<pthread_t, l_wlog_t*> wlogs;\nstatic boost::unordered_map<pthread_t, l_addmap_t*> addlogs;\n\n\/*\n * start to record?\n *\/\nstatic bool start = false;\n\n\/*\n * number of shared variables\n *\/\nstatic unsigned num_shared_vars = 0;\n\n#ifdef NO_TIME_CMD\nstatic struct timeval tpstart, tpend;\n#endif\n\nstatic inline void lock(unsigned svId) {\n pthread_mutex_lock(&locks[svId]);\n}\n\nstatic inline void unlock(unsigned svId) {\n pthread_mutex_unlock(&locks[svId]);\n}\n\nstatic inline void forkLock() {\n pthread_mutex_lock(&fork_lock);\n}\n\nstatic inline void forkUnlock() {\n pthread_mutex_unlock(&fork_lock);\n}\n\nstatic inline void mutexInitLock() {\n pthread_mutex_lock(&mutex_init_lock);\n}\n\nstatic inline void mutexInitUnlock() {\n pthread_mutex_unlock(&mutex_init_lock);\n}\n\n\/* delete logs\n *\/\nvoid close_read_log(void* log) {\n pthread_t tid = pthread_self();\n rlogs[tid] = (l_rlog_t*) log;\n}\n\nvoid close_write_log(void* log) {\n pthread_t tid = pthread_self();\n wlogs[tid] = (l_wlog_t*) log;\n}\n\nvoid close_map_log(void* log) {\n pthread_t tid = pthread_self();\n addlogs[tid] = (l_addmap_t*) log;\n}\n\nvoid close_cache(void* log) {\n delete (Cache*) log;\n}\n\nextern \"C\" {\n\n void OnInit(unsigned svsNum) {\n printf(\"OnInit-Record\\n\");\n num_shared_vars = svsNum;\n initializeSigRoutine();\n\n pthread_key_create(&rlog_key, close_read_log);\n pthread_key_create(&wlog_key, close_write_log);\n pthread_key_create(&address_birthday_map_key, close_map_log);\n pthread_key_create(&birthday_key, NULL);\n pthread_key_create(&cache_key, close_cache);\n\n write_versions = new unsigned[svsNum];\n memset(write_versions, 0, sizeof (unsigned) * svsNum);\n locks = new pthread_mutex_t[svsNum];\n\n for (unsigned i = 0; i < svsNum; i++) {\n pthread_mutex_init(&locks[i], NULL);\n }\n\n \/\/ main thread.\n pthread_t tid = pthread_self();\n thread_ht[tid] = thread_ht.size();\n\n#ifdef NO_TIME_CMD\n gettimeofday(&tpstart, NULL);\n#endif\n }\n\n void OnExit() {\n start = false;\n\n#ifdef NO_TIME_CMD\n gettimeofday(&tpend, NULL);\n double timeuse = 1000000 * (tpend.tv_sec - tpstart.tv_sec) + tpend.tv_usec - tpstart.tv_usec;\n timeuse \/= 1000;\n printf(\"processor time is %lf ms\\n\", timeuse);\n#endif\n printf(\"OnExit-Record\\n\");\n\n \/\/ dump, delete\/free is not needed, because program will exit.\n {\/\/flog\n flog.dumpWithValueUnsignedMap(\"fork.dat\", \"wb\", thread_ht);\n }\n\n {\n \/\/mlog, llogs\n mlog.dumpWithValueUnsignedMap(\"mutex.dat\", \"wb\", thread_ht);\n for (unsigned i = 0; i < llogs.size(); i++) {\n g_llog_t * llog = llogs[i];\n llog->dumpWithValueUnsignedMap(\"mutex.dat\", \"ab\", thread_ht);\n }\n }\n\n {\/\/rlog\n bool created = false;\n boost::unordered_map<pthread_t, l_rlog_t*>::iterator rit = rlogs.begin();\n while (rit != rlogs.end()) {\n l_rlog_t* rlog = rit->second;\n unsigned _tid = thread_ht[rit->first];\n for (unsigned i = 0; i < num_shared_vars; i++) {\n if (!created) {\n rlog[i].VAL_LOG.dumpWithUnsigned(\"read.dat\", \"wb\", _tid);\n rlog[i].VER_LOG.dumpWithUnsigned(\"read.dat\", \"ab\", _tid);\n\n created = true;\n } else {\n rlog[i].VAL_LOG.dumpWithUnsigned(\"read.dat\", \"ab\", _tid);\n rlog[i].VER_LOG.dumpWithUnsigned(\"read.dat\", \"ab\", _tid);\n }\n }\n\n rit++;\n }\n }\n {\/\/wlog\n bool created = false;\n boost::unordered_map<pthread_t, l_wlog_t*>::iterator wit = wlogs.begin();\n while (wit != wlogs.end()) {\n l_wlog_t* wlog = wit->second;\n unsigned _tid = thread_ht[wit->first];\n for (unsigned i = 0; i < num_shared_vars; i++) {\n if (!created) {\n wlog->dumpWithUnsigned(\"write.dat\", \"wb\", _tid);\n\n created = true;\n } else {\n wlog->dumpWithUnsigned(\"write.dat\", \"ab\", _tid);\n }\n }\n\n wit++;\n }\n }\n {\/\/address birthday map\n bool created = false;\n boost::unordered_map<pthread_t, l_addmap_t*>::iterator it = addlogs.begin();\n while (it != addlogs.end()) {\n unsigned _tid = thread_ht[it->first];\n l_addmap_t * addmap = it->second;\n\n FILE * fout = NULL;\n if (!created) {\n fout = fopen(\"addressmap.dat\", \"wb\");\n created = true;\n } else {\n fout = fopen(\"addressmap.dat\", \"ab\");\n }\n\n unsigned size = addmap->ADDRESS_LOG.size();\n fwrite(&size, sizeof (unsigned), 1, fout);\n fwrite(&_tid, sizeof (unsigned), 1, fout);\n for (unsigned i = 0; i < size; i++) {\n mem_t * m = addmap->ADDRESS_LOG[i];\n fwrite(&m->address, sizeof (void*), 1, fout);\n fwrite(&m->range, sizeof (size_t), 1, fout);\n }\n fclose(fout);\n\n addmap->BIRTHDAY_LOG.dump(\"addressmap.dat\", \"ab\");\n\n it++;\n }\n }\n }\n\n void OnAddressInit(void* value, size_t size, size_t n) {\n if (!start) {\n return;\n }\n\n l_addmap_t * mlog = (l_addmap_t*) pthread_getspecific(address_birthday_map_key);\n if (mlog == NULL) {\n mlog = new l_addmap_t;\n pthread_setspecific(address_birthday_map_key, mlog);\n }\n\n size_t * counter = (size_t *) pthread_getspecific(birthday_key);\n if (counter == NULL) {\n counter = new size_t;\n (*counter) = 0;\n }\n\n size_t c = *counter;\n mem_t * m = new mem_t;\n m->address = value;\n m->range = size*n;\n mlog->ADDRESS_LOG.push_back(m);\n mlog->BIRTHDAY_LOG.logValue(c++);\n (*counter) = c;\n }\n\n void OnLoad(int svId, long address, long value, int debug) {\n if (!start) {\n return;\n }\n\n#ifdef DEBUG\n printf(\"OnLoad\\n\");\n#endif\n \/\/ using thread_key to tell whether log has been established\n \/\/ if so, use it, otherwise, new one\n l_rlog_t * rlog = (l_rlog_t*) pthread_getspecific(rlog_key);\n if (rlog == NULL) {\n rlog = new l_rlog_t[num_shared_vars];\n pthread_setspecific(rlog_key, rlog);\n }\n\n Cache* cache = (Cache*) pthread_getspecific(cache_key);\n if (cache != NULL && cache->query(address, value)) {\n rlog[svId].VER_LOG.logValue(write_versions[svId]);\n } else {\n rlog[svId].VAL_LOG.logValue(value);\n rlog[svId].VER_LOG.logValue(-1);\n }\n }\n\n unsigned OnPreStore(int svId, int debug) {\n if (!start) {\n return 0;\n }\n\n lock(svId);\n#ifdef DEBUG\n printf(\"OnPreStore: %d [%d]\\n\", svId, debug);\n#endif\n unsigned version = write_versions[svId];\n write_versions[svId] = version + 1;\n\n return version;\n }\n\n void OnStore(int svId, unsigned version, long address, long value, int debug) {\n if (!start) {\n return;\n }\n#ifdef DEBUG\n printf(\"OnStore\\n\");\n#endif\n unlock(svId);\n\n l_wlog_t * wlog = (l_wlog_t*) pthread_getspecific(wlog_key);\n if (wlog == NULL) {\n wlog = new l_wlog_t[num_shared_vars];\n pthread_setspecific(wlog_key, wlog);\n }\n wlog[svId].logValue(version);\n\n Cache* cache = (Cache*) pthread_getspecific(cache_key);\n if (cache == NULL) {\n cache = new Cache;\n }\n\n cache->add(address, value);\n }\n\n void OnLock(pthread_mutex_t* mutex_ptr) {\n if (!start) {\n return;\n }\n\n \/\/ if map does not contain it, it must be a bug\n \/\/ because lock and init have a race.\n if (!mutex_ht.count(mutex_ptr)) {\n fprintf(stderr, \"ERROR: program bug!\\n\");\n OnExit();\n exit(1);\n }\n\n \/\/ here, the same address mutex_ptr is impossible to init a new lock\n \/\/ because the lock has been locked\n \/\/ therefore mutex_ht[mutex_ptr] is safe\n g_llog_t* llog = llogs[mutex_ht[mutex_ptr]];\n llog->logValue(pthread_self()); \/\/ exchange to _tid at last\n\n#ifdef DEBUG\n printf(\"OnLock --> t%d\\n\", thread_ht[tid]);\n#endif\n }\n\n void OnWait(pthread_cond_t* cond_ptr, pthread_mutex_t* mutex_ptr) {\n if (!start) {\n return;\n }\n#ifdef DEBUG\n printf(\"OnWait\\n\");\n#endif\n\n if (!mutex_ht.count(mutex_ptr)) {\n fprintf(stderr, \"ERROR: program bug!\\n\");\n OnExit();\n exit(1);\n }\n g_llog_t* llog = llogs[mutex_ht[mutex_ptr]];\n llog->logValue(pthread_self());\n }\n\n void OnPreMutexInit(bool race) {\n if (start && race) {\n mutexInitLock();\n }\n }\n\n void OnMutexInit(pthread_mutex_t* mutex_ptr, bool race) {\n \/\/ if mutex_ht contains mutex_ptr, it means that the original one may be\n \/\/ destroyed; No matther mutex_ht contains it or not, it is a new lock\n mutex_ht[mutex_ptr] = mutex_id++;\n g_llog_t * llog = new g_llog_t;\n llogs.push_back(llog);\n\n\n if (start && race) {\n pthread_t tid = pthread_self();\n mlog.logValue(tid);\n\n mutexInitUnlock();\n }\n }\n\n void OnPreFork(bool race) {\n if (!start) {\n start = true;\n }\n#ifdef DEBUG\n printf(\"OnPreFork\\n\");\n#endif\n if (race) forkLock();\n }\n\n void OnFork(pthread_t* forked_tid_ptr, bool race) {\n if (!start) {\n return;\n }\n\n#ifdef DEBUG\n printf(\"OnFork\\n\");\n#endif\n\n pthread_t ftid = *(forked_tid_ptr);\n if (!thread_ht.count(ftid)) {\n thread_ht[ftid] = thread_ht.size();\n }\n\n if (race) {\n pthread_t tid = pthread_self();\n flog.logValue(tid);\n\n forkUnlock();\n }\n }\n\n\n}\n\n\/* ************************************************************************\n * Signal Process\n * ************************************************************************\/\n\nvoid sigroutine(int dunno) {\n printSigInformation(dunno);\n\n OnExit();\n exit(dunno);\n}\n<commit_msg>comments<commit_after>#include <stdio.h>\n#include <stdlib.h>\n#include <signal.h>\n#include <unistd.h>\n#include <string.h>\n#include <time.h>\n#include <pthread.h>\n#include <sys\/time.h>\n\n#include <boost\/unordered_map.hpp>\n\n#include \"SignalRoutine.h\"\n#include \"..\/Log.h\"\n#include \"..\/Cache.h\"\n\n\/*\n * Define log types\n * l_ means local log types, each thread has a log\n * g_ means global log types, each shared variable has a log\n * r -> read \n * w -> write\n * l -> lock\n * m -> mutex init\n * f -> fork\n *\/\ntypedef struct {\n \/\/ <long\/void *> sizeof pointer usually equals to sizeof long\n LastOnePredictorLog<long> VAL_LOG; \n \/\/ <int>, -1 is the place holder, means the read operation reads\n \/\/ the local value\n LastOnePredictorLog<int> VER_LOG; \n} l_rlog_t;\n\ntypedef VLastOnePredictorLog l_wlog_t;\n\ntypedef LastOnePredictorLog<pthread_t> g_llog_t;\n\ntypedef LastOnePredictorLog<pthread_t> g_mlog_t;\n\ntypedef LastOnePredictorLog<pthread_t> g_flog_t;\n\ntypedef struct {\n void* address;\n size_t range;\n} mem_t;\n\ntypedef struct {\n std::vector<mem_t *> ADDRESS_LOG;\n VLastOnePredictorLog BIRTHDAY_LOG;\n} l_addmap_t;\n\n\/*\n * Define local log keys\n *\/\nstatic pthread_key_t rlog_key;\nstatic pthread_key_t wlog_key;\nstatic pthread_key_t cache_key;\nstatic pthread_key_t birthday_key;\nstatic pthread_key_t address_birthday_map_key;\n\n\/*\n * Define global log variables, each shared var has one\n *\/\nstatic std::vector<g_llog_t *> llogs; \/\/ <g_llog_t *> size is not fixed, and should be determined at runtime\nstatic g_flog_t flog;\nstatic g_mlog_t mlog;\n\n\/*\n * write versions, each shared var has a version\n *\/\nstatic unsigned* write_versions;\n\n\/*\n * locks for synchronization, each shared var has one\n *\/\nstatic pthread_mutex_t* locks;\nstatic pthread_mutex_t fork_lock = PTHREAD_MUTEX_INITIALIZER;\nstatic pthread_mutex_t mutex_init_lock = PTHREAD_MUTEX_INITIALIZER;\n\n\/*\n * mutex_t-> mutex_id hashmap\n * pthread_t -> thread_id hashmap\n *\/\nstatic unsigned mutex_id = 0;\nstatic boost::unordered_map<pthread_mutex_t *, unsigned> mutex_ht;\nstatic boost::unordered_map<pthread_t, unsigned> thread_ht;\nstatic boost::unordered_map<pthread_t, l_rlog_t*> rlogs;\nstatic boost::unordered_map<pthread_t, l_wlog_t*> wlogs;\nstatic boost::unordered_map<pthread_t, l_addmap_t*> addlogs;\n\n\/*\n * start to record?\n *\/\nstatic bool start = false;\n\n\/*\n * number of shared variables\n *\/\nstatic unsigned num_shared_vars = 0;\n\n#ifdef NO_TIME_CMD\nstatic struct timeval tpstart, tpend;\n#endif\n\nstatic inline void lock(unsigned svId) {\n pthread_mutex_lock(&locks[svId]);\n}\n\nstatic inline void unlock(unsigned svId) {\n pthread_mutex_unlock(&locks[svId]);\n}\n\nstatic inline void forkLock() {\n pthread_mutex_lock(&fork_lock);\n}\n\nstatic inline void forkUnlock() {\n pthread_mutex_unlock(&fork_lock);\n}\n\nstatic inline void mutexInitLock() {\n pthread_mutex_lock(&mutex_init_lock);\n}\n\nstatic inline void mutexInitUnlock() {\n pthread_mutex_unlock(&mutex_init_lock);\n}\n\n\/* we do not dump logs here, because it is time consuming\n * we store them in a global map, dump them at last\n * \n * in practice, we can dump them here to avoid memory leak\n *\/\nvoid close_read_log(void* log) {\n pthread_t tid = pthread_self();\n rlogs[tid] = (l_rlog_t*) log;\n}\n\nvoid close_write_log(void* log) {\n pthread_t tid = pthread_self();\n wlogs[tid] = (l_wlog_t*) log;\n}\n\nvoid close_map_log(void* log) {\n pthread_t tid = pthread_self();\n addlogs[tid] = (l_addmap_t*) log;\n}\n\nvoid close_cache(void* log) {\n delete (Cache*) log;\n}\n\nextern \"C\" {\n\n void OnInit(unsigned svsNum) {\n printf(\"OnInit-Record\\n\");\n num_shared_vars = svsNum;\n initializeSigRoutine();\n\n pthread_key_create(&rlog_key, close_read_log);\n pthread_key_create(&wlog_key, close_write_log);\n pthread_key_create(&address_birthday_map_key, close_map_log);\n pthread_key_create(&birthday_key, NULL);\n pthread_key_create(&cache_key, close_cache);\n\n write_versions = new unsigned[svsNum];\n memset(write_versions, 0, sizeof (unsigned) * svsNum);\n locks = new pthread_mutex_t[svsNum];\n\n for (unsigned i = 0; i < svsNum; i++) {\n pthread_mutex_init(&locks[i], NULL);\n }\n\n \/\/ main thread.\n pthread_t tid = pthread_self();\n thread_ht[tid] = thread_ht.size();\n\n#ifdef NO_TIME_CMD\n gettimeofday(&tpstart, NULL);\n#endif\n }\n\n void OnExit() {\n start = false;\n\n#ifdef NO_TIME_CMD\n gettimeofday(&tpend, NULL);\n double timeuse = 1000000 * (tpend.tv_sec - tpstart.tv_sec) + tpend.tv_usec - tpstart.tv_usec;\n timeuse \/= 1000;\n printf(\"processor time is %lf ms\\n\", timeuse);\n#endif\n printf(\"OnExit-Record\\n\");\n\n \/\/ dump, delete\/free is not needed, because program will exit.\n {\/\/flog\n flog.dumpWithValueUnsignedMap(\"fork.dat\", \"wb\", thread_ht);\n }\n\n {\n \/\/mlog, llogs\n mlog.dumpWithValueUnsignedMap(\"mutex.dat\", \"wb\", thread_ht);\n for (unsigned i = 0; i < llogs.size(); i++) {\n g_llog_t * llog = llogs[i];\n llog->dumpWithValueUnsignedMap(\"mutex.dat\", \"ab\", thread_ht);\n }\n }\n\n {\/\/rlog\n bool created = false;\n boost::unordered_map<pthread_t, l_rlog_t*>::iterator rit = rlogs.begin();\n while (rit != rlogs.end()) {\n l_rlog_t* rlog = rit->second;\n unsigned _tid = thread_ht[rit->first];\n for (unsigned i = 0; i < num_shared_vars; i++) {\n if (!created) {\n rlog[i].VAL_LOG.dumpWithUnsigned(\"read.dat\", \"wb\", _tid);\n rlog[i].VER_LOG.dumpWithUnsigned(\"read.dat\", \"ab\", _tid);\n\n created = true;\n } else {\n rlog[i].VAL_LOG.dumpWithUnsigned(\"read.dat\", \"ab\", _tid);\n rlog[i].VER_LOG.dumpWithUnsigned(\"read.dat\", \"ab\", _tid);\n }\n }\n\n rit++;\n }\n }\n {\/\/wlog\n bool created = false;\n boost::unordered_map<pthread_t, l_wlog_t*>::iterator wit = wlogs.begin();\n while (wit != wlogs.end()) {\n l_wlog_t* wlog = wit->second;\n unsigned _tid = thread_ht[wit->first];\n for (unsigned i = 0; i < num_shared_vars; i++) {\n if (!created) {\n wlog->dumpWithUnsigned(\"write.dat\", \"wb\", _tid);\n\n created = true;\n } else {\n wlog->dumpWithUnsigned(\"write.dat\", \"ab\", _tid);\n }\n }\n\n wit++;\n }\n }\n {\/\/address birthday map\n bool created = false;\n boost::unordered_map<pthread_t, l_addmap_t*>::iterator it = addlogs.begin();\n while (it != addlogs.end()) {\n unsigned _tid = thread_ht[it->first];\n l_addmap_t * addmap = it->second;\n\n FILE * fout = NULL;\n if (!created) {\n fout = fopen(\"addressmap.dat\", \"wb\");\n created = true;\n } else {\n fout = fopen(\"addressmap.dat\", \"ab\");\n }\n\n unsigned size = addmap->ADDRESS_LOG.size();\n fwrite(&size, sizeof (unsigned), 1, fout);\n fwrite(&_tid, sizeof (unsigned), 1, fout);\n for (unsigned i = 0; i < size; i++) {\n mem_t * m = addmap->ADDRESS_LOG[i];\n fwrite(&m->address, sizeof (void*), 1, fout);\n fwrite(&m->range, sizeof (size_t), 1, fout);\n }\n fclose(fout);\n\n addmap->BIRTHDAY_LOG.dump(\"addressmap.dat\", \"ab\");\n\n it++;\n }\n }\n }\n\n void OnAddressInit(void* value, size_t size, size_t n) {\n if (!start) {\n return;\n }\n\n l_addmap_t * mlog = (l_addmap_t*) pthread_getspecific(address_birthday_map_key);\n if (mlog == NULL) {\n mlog = new l_addmap_t;\n pthread_setspecific(address_birthday_map_key, mlog);\n }\n\n size_t * counter = (size_t *) pthread_getspecific(birthday_key);\n if (counter == NULL) {\n counter = new size_t;\n (*counter) = 0;\n }\n\n size_t c = *counter;\n mem_t * m = new mem_t;\n m->address = value;\n m->range = size*n;\n mlog->ADDRESS_LOG.push_back(m);\n mlog->BIRTHDAY_LOG.logValue(c++);\n (*counter) = c;\n }\n\n void OnLoad(int svId, long address, long value, int debug) {\n if (!start) {\n return;\n }\n\n#ifdef DEBUG\n printf(\"OnLoad\\n\");\n#endif\n \/\/ using thread_key to tell whether log has been established\n \/\/ if so, use it, otherwise, new one\n l_rlog_t * rlog = (l_rlog_t*) pthread_getspecific(rlog_key);\n if (rlog == NULL) {\n rlog = new l_rlog_t[num_shared_vars];\n pthread_setspecific(rlog_key, rlog);\n }\n\n Cache* cache = (Cache*) pthread_getspecific(cache_key);\n if (cache != NULL && cache->query(address, value)) {\n rlog[svId].VER_LOG.logValue(write_versions[svId]);\n } else {\n rlog[svId].VAL_LOG.logValue(value);\n rlog[svId].VER_LOG.logValue(-1);\n }\n }\n\n unsigned OnPreStore(int svId, int debug) {\n if (!start) {\n return 0;\n }\n\n lock(svId);\n#ifdef DEBUG\n printf(\"OnPreStore: %d [%d]\\n\", svId, debug);\n#endif\n unsigned version = write_versions[svId];\n write_versions[svId] = version + 1;\n\n return version;\n }\n\n void OnStore(int svId, unsigned version, long address, long value, int debug) {\n if (!start) {\n return;\n }\n#ifdef DEBUG\n printf(\"OnStore\\n\");\n#endif\n unlock(svId);\n\n l_wlog_t * wlog = (l_wlog_t*) pthread_getspecific(wlog_key);\n if (wlog == NULL) {\n wlog = new l_wlog_t[num_shared_vars];\n pthread_setspecific(wlog_key, wlog);\n }\n wlog[svId].logValue(version);\n\n Cache* cache = (Cache*) pthread_getspecific(cache_key);\n if (cache == NULL) {\n cache = new Cache;\n }\n\n cache->add(address, value);\n }\n\n void OnLock(pthread_mutex_t* mutex_ptr) {\n if (!start) {\n return;\n }\n\n \/\/ if map does not contain it, it must be a bug\n \/\/ because lock and init have a race.\n if (!mutex_ht.count(mutex_ptr)) {\n fprintf(stderr, \"ERROR: program bug!\\n\");\n OnExit();\n exit(1);\n }\n\n \/\/ here, the same address mutex_ptr is impossible to init a new lock\n \/\/ because the lock has been locked\n \/\/ therefore mutex_ht[mutex_ptr] is safe\n g_llog_t* llog = llogs[mutex_ht[mutex_ptr]];\n llog->logValue(pthread_self()); \/\/ exchange to _tid at last\n\n#ifdef DEBUG\n printf(\"OnLock --> t%d\\n\", thread_ht[tid]);\n#endif\n }\n\n void OnWait(pthread_cond_t* cond_ptr, pthread_mutex_t* mutex_ptr) {\n if (!start) {\n return;\n }\n#ifdef DEBUG\n printf(\"OnWait\\n\");\n#endif\n\n if (!mutex_ht.count(mutex_ptr)) {\n fprintf(stderr, \"ERROR: program bug!\\n\");\n OnExit();\n exit(1);\n }\n g_llog_t* llog = llogs[mutex_ht[mutex_ptr]];\n llog->logValue(pthread_self());\n }\n\n void OnPreMutexInit(bool race) {\n if (start && race) {\n mutexInitLock();\n }\n }\n\n void OnMutexInit(pthread_mutex_t* mutex_ptr, bool race) {\n \/\/ if mutex_ht contains mutex_ptr, it means that the original one may be\n \/\/ destroyed; No matther mutex_ht contains it or not, it is a new lock\n mutex_ht[mutex_ptr] = mutex_id++;\n g_llog_t * llog = new g_llog_t;\n llogs.push_back(llog);\n\n\n if (start && race) {\n pthread_t tid = pthread_self();\n mlog.logValue(tid);\n\n mutexInitUnlock();\n }\n }\n\n void OnPreFork(bool race) {\n if (!start) {\n start = true;\n }\n#ifdef DEBUG\n printf(\"OnPreFork\\n\");\n#endif\n if (race) forkLock();\n }\n\n void OnFork(pthread_t* forked_tid_ptr, bool race) {\n if (!start) {\n return;\n }\n\n#ifdef DEBUG\n printf(\"OnFork\\n\");\n#endif\n\n pthread_t ftid = *(forked_tid_ptr);\n if (!thread_ht.count(ftid)) {\n thread_ht[ftid] = thread_ht.size();\n }\n\n if (race) {\n pthread_t tid = pthread_self();\n flog.logValue(tid);\n\n forkUnlock();\n }\n }\n\n\n}\n\n\/* ************************************************************************\n * Signal Process\n * ************************************************************************\/\n\nvoid sigroutine(int dunno) {\n printSigInformation(dunno);\n\n OnExit();\n exit(dunno);\n}\n<|endoftext|>"} {"text":"<commit_before>#include <thread>\n#include <renderer.hpp>\n#include <fensterchen.hpp>\n\nint main(int argc, char* argv[])\n{\n unsigned const width = 600;\n unsigned const height = 600;\n std::string const filename = \".\/checkerboard.ppm\";\n\n Renderer app(width, height, filename);\n\n std::thread thr([&app]() { app.render(); });\n\n Window win(glm::ivec2(width,height));\n\n while (!win.shouldClose()) {\n if (win.isKeyPressed(GLFW_KEY_ESCAPE)) {\n win.stop();\n }\n\n glDrawPixels( width, height, GL_RGB, GL_FLOAT\n , app.colorbuffer().data());\n\n win.update();\n }\n\n thr.join();\n\n return 0;\n}\n<commit_msg>raytracer.cpp fixed<commit_after>#include <thread>\n#include <renderer.hpp>\n#include <fensterchen.hpp>\n\nint main(int argc, char* argv[])\n{\n Scene scene;\n unsigned const width = 600;\n unsigned const height = 600;\n std::string const filename = \".\/checkerboard.ppm\";\n\n Renderer app(scene, width, height, filename);\n\n std::thread thr([&app]() { app.render(); });\n\n Window win(glm::ivec2(width,height));\n\n while (!win.shouldClose()) {\n if (win.isKeyPressed(GLFW_KEY_ESCAPE)) {\n win.stop();\n }\n\n glDrawPixels( width, height, GL_RGB, GL_FLOAT\n , app.colorbuffer().data());\n\n win.update();\n }\n\n thr.join();\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: XMLEmbeddedObjectImportContext.hxx,v $\n *\n * $Revision: 1.1 $\n *\n * last change: $Author: mib $ $Date: 2001-05-09 12:06:23 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef _XMLOFF_XMLEMBEDDEDOBJECTIMPORTCONTEXT_HXX\n#define _XMLOFF_XMLEMBEDDEDOBJECTIMPORTCONTEXT_HXX\n\n#ifndef _COM_SUN_STAR_XML_SAX_XDOCUMENTHANDLER_HPP_\n#include <com\/sun\/star\/xml\/sax\/XDocumentHandler.hpp>\n#endif\n\n#ifndef _XMLOFF_XMLICTXT_HXX\n#include \"xmlictxt.hxx\"\n#endif\n\nnamespace com { namespace sun { namespace star { namespace lang {\n class XComponent; } } } }\n\nclass XMLEmbeddedObjectImportContext : public SvXMLImportContext\n{\n ::com::sun::star::uno::Reference<\n ::com::sun::star::xml::sax::XDocumentHandler > xHandler;\n\n ::rtl::OUString sFilterService;\n\npublic:\n TYPEINFO();\n\n const ::rtl::OUString& GetFilterServiceName() const { return sFilterService; }\n\n XMLEmbeddedObjectImportContext( SvXMLImport& rImport, USHORT nPrfx,\n const ::rtl::OUString& rLName,\n const ::com::sun::star::uno::Reference<\n ::com::sun::star::xml::sax::XAttributeList >& xAttrList );\n\n virtual ~XMLEmbeddedObjectImportContext();\n\n virtual SvXMLImportContext *CreateChildContext( USHORT nPrefix,\n const ::rtl::OUString& rLocalName,\n const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList >& xAttrList );\n\n virtual void StartElement( const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList >& xAttrList );\n\n virtual void EndElement();\n\n virtual void Characters( const ::rtl::OUString& rChars );\n\n sal_Bool SetComponent(\n ::com::sun::star::uno::Reference<\n ::com::sun::star::lang::XComponent >& rComp );\n\n};\n\n#endif \/\/ _XMLOFF_XMLEMBEDDEDOBJECTIMPORTCONTEXT_HXX\n\n<commit_msg>#100592# added OUString sCLSID and interfaces<commit_after>\/*************************************************************************\n *\n * $RCSfile: XMLEmbeddedObjectImportContext.hxx,v $\n *\n * $Revision: 1.2 $\n *\n * last change: $Author: aw $ $Date: 2002-06-27 11:04:33 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef _XMLOFF_XMLEMBEDDEDOBJECTIMPORTCONTEXT_HXX\n#define _XMLOFF_XMLEMBEDDEDOBJECTIMPORTCONTEXT_HXX\n\n#ifndef _COM_SUN_STAR_XML_SAX_XDOCUMENTHANDLER_HPP_\n#include <com\/sun\/star\/xml\/sax\/XDocumentHandler.hpp>\n#endif\n\n#ifndef _XMLOFF_XMLICTXT_HXX\n#include \"xmlictxt.hxx\"\n#endif\n\nnamespace com { namespace sun { namespace star { namespace lang {\n class XComponent; } } } }\n\nclass XMLEmbeddedObjectImportContext : public SvXMLImportContext\n{\n ::com::sun::star::uno::Reference<\n ::com::sun::star::xml::sax::XDocumentHandler > xHandler;\n\n ::rtl::OUString sFilterService;\n \/\/ #100592#\n ::rtl::OUString sCLSID;\n\npublic:\n TYPEINFO();\n\n const ::rtl::OUString& GetFilterServiceName() const { return sFilterService; }\n \/\/ #100592#\n const ::rtl::OUString& GetFilterCLSID() const { return sCLSID; }\n\n XMLEmbeddedObjectImportContext( SvXMLImport& rImport, USHORT nPrfx,\n const ::rtl::OUString& rLName,\n const ::com::sun::star::uno::Reference<\n ::com::sun::star::xml::sax::XAttributeList >& xAttrList );\n\n virtual ~XMLEmbeddedObjectImportContext();\n\n virtual SvXMLImportContext *CreateChildContext( USHORT nPrefix,\n const ::rtl::OUString& rLocalName,\n const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList >& xAttrList );\n\n virtual void StartElement( const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList >& xAttrList );\n\n virtual void EndElement();\n\n virtual void Characters( const ::rtl::OUString& rChars );\n\n sal_Bool SetComponent(\n ::com::sun::star::uno::Reference<\n ::com::sun::star::lang::XComponent >& rComp );\n\n};\n\n#endif \/\/ _XMLOFF_XMLEMBEDDEDOBJECTIMPORTCONTEXT_HXX\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2018 The clvk authors.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#pragma once\n\n#include <cstring>\n\n#include <atomic>\n#include <chrono>\n#include <condition_variable>\n#include <deque>\n#include <list>\n#include <mutex>\n#include <string>\n#include <thread>\n#include <unordered_map>\n#include <vector>\n\n#include <vulkan\/vulkan.h>\n\n#include \"cl_headers.hpp\"\n#include \"device.hpp\"\n#include \"utils.hpp\"\n\nstruct refcounted {\n\n refcounted() : m_refcount(1) { }\n\n virtual ~refcounted() = default;\n\n void retain() {\n unsigned int refcount = m_refcount.fetch_add(1);\n cvk_debug_fn(\"obj = %p, refcount now %u\", this, refcount + 1);\n }\n\n void release() {\n unsigned int refcount = m_refcount.fetch_sub(1);\n cvk_debug_fn(\"obj = %p, refcount now %u\", this, refcount - 1);\n\n if (refcount == 1) {\n delete this;\n }\n }\n\n unsigned int refcount() const {\n return m_refcount.load();\n }\n\nprivate:\n std::atomic<unsigned int> m_refcount;\n};\n\ntemplate<typename T>\nstruct refcounted_holder {\n\n refcounted_holder() : m_refcounted(nullptr) {}\n\n refcounted_holder(T *refcounted) : m_refcounted(refcounted) {\n if (m_refcounted != nullptr) {\n m_refcounted->retain();\n }\n }\n\n refcounted_holder(const refcounted_holder &other) :\n m_refcounted(other.m_refcounted) {\n if (m_refcounted != nullptr) {\n m_refcounted->retain();\n }\n }\n\n refcounted_holder(const refcounted_holder &&other) = delete;\n\n ~refcounted_holder() {\n if (m_refcounted != nullptr) {\n m_refcounted->release();\n }\n }\n\n T* operator->() const {\n return m_refcounted;\n }\n\n operator T*() const {\n return m_refcounted;\n }\n\n refcounted_holder& operator=(const refcounted_holder& ) = delete;\n refcounted_holder& operator=(const refcounted_holder&&) = delete;\n\n void reset(T* refc) {\n if (m_refcounted != nullptr) {\n m_refcounted->release();\n }\n m_refcounted = refc;\n if (m_refcounted != nullptr) {\n m_refcounted->retain();\n }\n }\n\nprivate:\n T *m_refcounted;\n};\n\ntypedef struct _cl_context : public refcounted {\n\n _cl_context(cvk_device *device, const cl_context_properties* props)\n : m_device(device) {\n\n if (props) {\n while (*props) {\n \/\/ Save name\n m_properties.push_back(*props);\n \/\/ Save value\n m_properties.push_back(*(props+1));\n props += 2;\n }\n m_properties.push_back(*props);\n }\n }\n\n virtual ~_cl_context() {}\n\n const std::vector<cl_context_properties>& properties() const {\n return m_properties;\n }\n\n cvk_device* device() const { return m_device; }\n unsigned num_devices() const { return 1u; }\n\nprivate:\n cvk_device *m_device;\n std::vector<cl_context_properties> m_properties;\n\n} cvk_context;\n\nstruct api_object : public refcounted {\n\n api_object(cvk_context *context) : m_context(context) {\n m_context->retain();\n }\n ~api_object() {\n m_context->release();\n }\n\n cvk_context* context() const { return m_context; }\n\nprotected:\n cvk_context *m_context;\n};\n\n<commit_msg>Use refcounted_holder to manage context refcounting in api_object<commit_after>\/\/ Copyright 2018 The clvk authors.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#pragma once\n\n#include <cstring>\n\n#include <atomic>\n#include <chrono>\n#include <condition_variable>\n#include <deque>\n#include <list>\n#include <mutex>\n#include <string>\n#include <thread>\n#include <unordered_map>\n#include <vector>\n\n#include <vulkan\/vulkan.h>\n\n#include \"cl_headers.hpp\"\n#include \"device.hpp\"\n#include \"utils.hpp\"\n\nstruct refcounted {\n\n refcounted() : m_refcount(1) { }\n\n virtual ~refcounted() = default;\n\n void retain() {\n unsigned int refcount = m_refcount.fetch_add(1);\n cvk_debug_fn(\"obj = %p, refcount now %u\", this, refcount + 1);\n }\n\n void release() {\n unsigned int refcount = m_refcount.fetch_sub(1);\n cvk_debug_fn(\"obj = %p, refcount now %u\", this, refcount - 1);\n\n if (refcount == 1) {\n delete this;\n }\n }\n\n unsigned int refcount() const {\n return m_refcount.load();\n }\n\nprivate:\n std::atomic<unsigned int> m_refcount;\n};\n\ntemplate<typename T>\nstruct refcounted_holder {\n\n refcounted_holder() : m_refcounted(nullptr) {}\n\n refcounted_holder(T *refcounted) : m_refcounted(refcounted) {\n if (m_refcounted != nullptr) {\n m_refcounted->retain();\n }\n }\n\n refcounted_holder(const refcounted_holder &other) :\n m_refcounted(other.m_refcounted) {\n if (m_refcounted != nullptr) {\n m_refcounted->retain();\n }\n }\n\n refcounted_holder(const refcounted_holder &&other) = delete;\n\n ~refcounted_holder() {\n if (m_refcounted != nullptr) {\n m_refcounted->release();\n }\n }\n\n T* operator->() const {\n return m_refcounted;\n }\n\n operator T*() const {\n return m_refcounted;\n }\n\n refcounted_holder& operator=(const refcounted_holder& ) = delete;\n refcounted_holder& operator=(const refcounted_holder&&) = delete;\n\n void reset(T* refc) {\n if (m_refcounted != nullptr) {\n m_refcounted->release();\n }\n m_refcounted = refc;\n if (m_refcounted != nullptr) {\n m_refcounted->retain();\n }\n }\n\nprivate:\n T *m_refcounted;\n};\n\ntypedef struct _cl_context : public refcounted {\n\n _cl_context(cvk_device *device, const cl_context_properties* props)\n : m_device(device) {\n\n if (props) {\n while (*props) {\n \/\/ Save name\n m_properties.push_back(*props);\n \/\/ Save value\n m_properties.push_back(*(props+1));\n props += 2;\n }\n m_properties.push_back(*props);\n }\n }\n\n virtual ~_cl_context() {}\n\n const std::vector<cl_context_properties>& properties() const {\n return m_properties;\n }\n\n cvk_device* device() const { return m_device; }\n unsigned num_devices() const { return 1u; }\n\nprivate:\n cvk_device *m_device;\n std::vector<cl_context_properties> m_properties;\n\n} cvk_context;\n\nusing cvk_context_holder = refcounted_holder<cvk_context>;\n\nstruct api_object : public refcounted {\n\n api_object(cvk_context *context) : m_context(context) {}\n cvk_context* context() const { return m_context; }\n\nprotected:\n cvk_context_holder m_context;\n};\n\n<|endoftext|>"} {"text":"<commit_before>\/**************************************************************************\n* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *\n* *\n* Author: The ALICE Off-line Project. *\n* Contributors are mentioned in the code where appropriate. *\n* *\n* Permission to use, copy, modify and distribute this software and its *\n* documentation strictly for non-commercial purposes is hereby granted *\n* without fee, provided that the above copyright notice appears in all *\n* copies and that both the copyright notice and this permission notice *\n* appear in the supporting documentation. The authors make no claims *\n* about the suitability of this software for any purpose. It is *\n* provided \"as is\" without express or implied warranty. *\n**************************************************************************\/\n\n\/\/ $Id$\n\n#include \"AliMUONClusterFinderSimpleFit.h\"\n\n#include \"AliLog.h\"\n#include \"AliMpDEManager.h\"\n#include \"AliMpStationType.h\"\n#include \"AliMUONCluster.h\"\n#include \"AliMUONConstants.h\"\n#include \"AliMUONDigit.h\"\n#include \"AliMUONMathieson.h\"\n#include \"AliMUONPad.h\"\n#include \"AliMUONClusterFinderCOG.h\"\n#include \"AliMpArea.h\"\n#include \"TClonesArray.h\"\n#include \"TObjArray.h\"\n#include \"TVector2.h\"\n#include \"TVirtualFitter.h\"\n#include \"TF1.h\"\n\n\/\/\/ \\class AliMUONClusterFinderSimpleFit\n\/\/\/\n\/\/\/ Basic cluster finder \n\/\/\/ \n\/\/\/ We simply use AliMUONPreClusterFinder to get basic cluster,\n\/\/\/ and then we try to fit the charge repartition using a Mathieson\n\/\/\/ distribution, varying the position.\n\/\/\/\n\/\/\/ FIXME: this one is still at the developping stage...\n\/\/\/\n\/\/\/ \\author Laurent Aphecetche\n\n\/\/\/ \\nocond CLASSIMP\nClassImp(AliMUONClusterFinderSimpleFit)\n\/\/\/ \\endcond\n\nnamespace\n{\n \/\/___________________________________________________________________________\n void \n FitFunction(Int_t& \/*notused*\/, Double_t* \/*notused*\/, \n Double_t& f, Double_t* par, \n Int_t \/*notused*\/)\n {\n \/\/\/ Chi2 Function to minimize: Mathieson charge distribution in 2 dimensions\n \n TObjArray* userObjects = static_cast<TObjArray*>(TVirtualFitter::GetFitter()->GetObjectFit());\n \n AliMUONCluster* cluster = static_cast<AliMUONCluster*>(userObjects->At(0));\n AliMUONMathieson* mathieson = static_cast<AliMUONMathieson*>(userObjects->At(1));\n \n f = 0.0;\n Float_t qTot = cluster->Charge();\n Float_t chargeCorrel[] = { cluster->Charge(0)\/qTot, cluster->Charge(1)\/qTot };\n \n for ( Int_t i = 0 ; i < cluster->Multiplicity(); ++i )\n {\n AliMUONPad* pad = cluster->Pad(i);\n \/\/ skip pads w\/ saturation or other problem(s)\n if ( pad->Status() ) continue; \n TVector2 lowerLeft = TVector2(par[0],par[1]) - pad->Position() - pad->Dimensions();\n TVector2 upperRight(lowerLeft + pad->Dimensions()*2.0);\n Float_t estimatedCharge = \n qTot*mathieson->IntXY(lowerLeft.X(),lowerLeft.Y(),\n upperRight.X(),upperRight.Y());\n estimatedCharge *= chargeCorrel[pad->Cathode()];\n Float_t actualCharge = pad->Charge();\n \n Float_t delta = (estimatedCharge - actualCharge);\n \n f += delta*delta\/qTot; \n } \n }\n}\n\n\/\/_____________________________________________________________________________\nAliMUONClusterFinderSimpleFit::AliMUONClusterFinderSimpleFit()\n: AliMUONVClusterFinder(),\nfClusterFinder(0x0),\nfMathieson(0x0)\n{\n \/\/\/ ctor\n}\n\n\/\/_____________________________________________________________________________\nAliMUONClusterFinderSimpleFit::~AliMUONClusterFinderSimpleFit()\n{\n \/\/\/ dtor\n delete fClusterFinder;\n delete fMathieson;\n}\n\n\/\/_____________________________________________________________________________\nBool_t \nAliMUONClusterFinderSimpleFit::Prepare(const AliMpVSegmentation* segmentations[2],\n TClonesArray* digits[2])\n{\n \/\/\/ Prepare for clustering\n\n \/\/ FIXME: should we get the Mathieson from elsewhere ?\n \n \/\/ Find out the DetElemId\n Int_t detElemId(-1);\n \n for ( Int_t i = 0; i < 2; ++i )\n {\n AliMUONDigit* d = static_cast<AliMUONDigit*>(digits[i]->First());\n if (d)\n {\n detElemId = d->DetElemId();\n break;\n }\n }\n \n if ( detElemId < 0 )\n {\n AliWarning(\"Could not find DE. Probably no digits at all ?\");\n return kFALSE;\n }\n \n AliMp::StationType stationType = AliMpDEManager::GetStationType(detElemId);\n \n Float_t kx3 = AliMUONConstants::SqrtKx3();\n Float_t ky3 = AliMUONConstants::SqrtKy3();\n Float_t pitch = AliMUONConstants::Pitch();\n \n if ( stationType == AliMp::kStation1 )\n {\n kx3 = AliMUONConstants::SqrtKx3St1();\n ky3 = AliMUONConstants::SqrtKy3St1();\n pitch = AliMUONConstants::PitchSt1();\n }\n \n delete fMathieson;\n fMathieson = new AliMUONMathieson;\n \n fMathieson->SetPitch(pitch);\n fMathieson->SetSqrtKx3AndDeriveKx2Kx4(kx3);\n fMathieson->SetSqrtKy3AndDeriveKy2Ky4(ky3);\n\n delete fClusterFinder;\n fClusterFinder = new AliMUONClusterFinderCOG;\n return fClusterFinder->Prepare(segmentations,digits);\n}\n\n\/\/_____________________________________________________________________________\nAliMUONCluster* \nAliMUONClusterFinderSimpleFit::NextCluster()\n{\n \/\/\/ Returns next cluster\n \n if ( !fClusterFinder ) return 0x0;\n AliMUONCluster* cluster = fClusterFinder->NextCluster();\n if ( cluster )\n {\n ComputePosition(*cluster);\n\n if ( cluster->Charge() < 7 )\n {\n \/\/ skip that one\n return NextCluster();\n } \n }\n return cluster;\n}\n\n\/\/_____________________________________________________________________________\nvoid \nAliMUONClusterFinderSimpleFit::ComputePosition(AliMUONCluster& cluster)\n{\n \/\/\/ Compute the position of the given cluster, by fitting a Mathieson\n \/\/\/ charge distribution to it\n \n TVirtualFitter* fitter = TVirtualFitter::Fitter(0,2);\n fitter->SetFCN(FitFunction);\n\n if ( cluster.Multiplicity() < 3 ) return;\n \n \/\/ We try a Mathieson fit, starting\n \/\/ with the center-of-gravity estimate as a first guess\n \/\/ for the cluster center.\n \n Double_t xCOG = cluster.Position().X();\n Double_t yCOG = cluster.Position().Y();\n \n Float_t stepX = 0.01; \/\/ cm\n Float_t stepY = 0.01; \/\/ cm\n \n Double_t arg(1);\/\/0);\n \n fitter->ExecuteCommand(\"SET PRINT\",&arg,1); \/\/ disable printout\n \n fitter->SetParameter(0,\"cluster X position\",xCOG,stepX,0,0);\n fitter->SetParameter(1,\"cluster Y position\",yCOG,stepY,0,0);\n\/\/ fitter->SetParameter(2,\"charge ratio\",1.0,0.01,0.1,10);\n \n TObjArray userObjects;\n \n userObjects.Add(&cluster);\n userObjects.Add(fMathieson);\n \n\/\/ fitter->SetUserFunc(&userObjects);\n fitter->SetObjectFit(&userObjects);\n \n fitter->ExecuteCommand(\"MIGRAD\",0,0);\n \n Double_t results[] = { fitter->GetParameter(0),\n fitter->GetParameter(1) };\n \n Double_t errors[] = { fitter->GetParError(0),\n fitter->GetParError(1) };\n \n cluster.SetPosition(TVector2(results[0],results[1]),\n TVector2(errors[0],errors[1]));\n \n TF1* func = static_cast<TF1*>(fitter->GetUserFunc());\n Double_t chi2 = 0;\n if ( func ) chi2 = func->GetChisquare();\n \n AliDebug(1,Form(\"Cluster fitted to (x,y)=(%e,%e) (xerr,yerr)=(%e,%e) chi2=%e\",\n results[0],results[1],\n errors[0],errors[1],chi2));\n\/\/ cluster.SetChi2(chi2\/fitter->GetNumberFreeParameters());\n}\n\n\n\n<commit_msg>Should now work almost correctly...(Laurent)<commit_after>\/**************************************************************************\n* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *\n* *\n* Author: The ALICE Off-line Project. *\n* Contributors are mentioned in the code where appropriate. *\n* *\n* Permission to use, copy, modify and distribute this software and its *\n* documentation strictly for non-commercial purposes is hereby granted *\n* without fee, provided that the above copyright notice appears in all *\n* copies and that both the copyright notice and this permission notice *\n* appear in the supporting documentation. The authors make no claims *\n* about the suitability of this software for any purpose. It is *\n* provided \"as is\" without express or implied warranty. *\n**************************************************************************\/\n\n\/\/ $Id$\n\n#include \"AliMUONClusterFinderSimpleFit.h\"\n\n#include \"AliLog.h\"\n#include \"AliMpDEManager.h\"\n#include \"AliMpStationType.h\"\n#include \"AliMUONCluster.h\"\n#include \"AliMUONConstants.h\"\n#include \"AliMUONDigit.h\"\n#include \"AliMUONMathieson.h\"\n#include \"AliMUONPad.h\"\n#include \"AliMUONClusterFinderCOG.h\"\n#include \"AliMpArea.h\"\n#include \"TClonesArray.h\"\n#include \"TObjArray.h\"\n#include \"TVector2.h\"\n#include \"TVirtualFitter.h\"\n#include \"TF1.h\"\n\n\/\/\/ \\class AliMUONClusterFinderSimpleFit\n\/\/\/\n\/\/\/ Basic cluster finder \n\/\/\/ \n\/\/\/ We simply use AliMUONPreClusterFinder to get basic cluster,\n\/\/\/ and then we try to fit the charge repartition using a Mathieson\n\/\/\/ distribution, varying the position.\n\/\/\/\n\/\/\/ FIXME: this one is still at the developping stage...\n\/\/\/\n\/\/\/ \\author Laurent Aphecetche\n\n\/\/\/ \\nocond CLASSIMP\nClassImp(AliMUONClusterFinderSimpleFit)\n\/\/\/ \\endcond\n\nnamespace\n{\n \/\/___________________________________________________________________________\n void \n FitFunction(Int_t& \/*notused*\/, Double_t* \/*notused*\/, \n Double_t& f, Double_t* par, \n Int_t \/*notused*\/)\n {\n \/\/\/ Chi2 Function to minimize: Mathieson charge distribution in 2 dimensions\n \n TObjArray* userObjects = static_cast<TObjArray*>(TVirtualFitter::GetFitter()->GetObjectFit());\n \n AliMUONCluster* cluster = static_cast<AliMUONCluster*>(userObjects->At(0));\n AliMUONMathieson* mathieson = static_cast<AliMUONMathieson*>(userObjects->At(1));\n \n f = 0.0;\n Float_t qTot = cluster->Charge();\n\/\/ Float_t chargeCorrel[] = { cluster->Charge(0)\/qTot, cluster->Charge(1)\/qTot };\n\/\/ Float_t qRatio[] = { 1.0\/par[2], par[2] };\n \n for ( Int_t i = 0 ; i < cluster->Multiplicity(); ++i )\n {\n AliMUONPad* pad = cluster->Pad(i);\n \/\/ skip pads w\/ saturation or other problem(s)\n if ( pad->Status() ) continue; \n TVector2 lowerLeft = TVector2(par[0],par[1]) - pad->Position() - pad->Dimensions();\n TVector2 upperRight(lowerLeft + pad->Dimensions()*2.0);\n Float_t estimatedCharge = mathieson->IntXY(lowerLeft.X(),lowerLeft.Y(),\n upperRight.X(),upperRight.Y());\n\/\/ estimatedCharge *= 2\/(1+qRatio[pad->Cathode()]);\n Float_t actualCharge = pad->Charge()\/qTot;\n \n Float_t delta = (estimatedCharge - actualCharge);\n \n f += delta*delta; \n } \n }\n}\n\n\/\/_____________________________________________________________________________\nAliMUONClusterFinderSimpleFit::AliMUONClusterFinderSimpleFit()\n: AliMUONVClusterFinder(),\nfClusterFinder(0x0),\nfMathieson(0x0)\n{\n \/\/\/ ctor\n}\n\n\/\/_____________________________________________________________________________\nAliMUONClusterFinderSimpleFit::~AliMUONClusterFinderSimpleFit()\n{\n \/\/\/ dtor\n delete fClusterFinder;\n delete fMathieson;\n}\n\n\/\/_____________________________________________________________________________\nBool_t \nAliMUONClusterFinderSimpleFit::Prepare(const AliMpVSegmentation* segmentations[2],\n TClonesArray* digits[2])\n{\n \/\/\/ Prepare for clustering\n\n \/\/ FIXME: should we get the Mathieson from elsewhere ?\n \n \/\/ Find out the DetElemId\n Int_t detElemId(-1);\n \n for ( Int_t i = 0; i < 2; ++i )\n {\n AliMUONDigit* d = static_cast<AliMUONDigit*>(digits[i]->First());\n if (d)\n {\n detElemId = d->DetElemId();\n break;\n }\n }\n \n if ( detElemId < 0 )\n {\n AliWarning(\"Could not find DE. Probably no digits at all ?\");\n return kFALSE;\n }\n \n AliMp::StationType stationType = AliMpDEManager::GetStationType(detElemId);\n \n Float_t kx3 = AliMUONConstants::SqrtKx3();\n Float_t ky3 = AliMUONConstants::SqrtKy3();\n Float_t pitch = AliMUONConstants::Pitch();\n \n if ( stationType == AliMp::kStation1 )\n {\n kx3 = AliMUONConstants::SqrtKx3St1();\n ky3 = AliMUONConstants::SqrtKy3St1();\n pitch = AliMUONConstants::PitchSt1();\n }\n \n delete fMathieson;\n fMathieson = new AliMUONMathieson;\n \n fMathieson->SetPitch(pitch);\n fMathieson->SetSqrtKx3AndDeriveKx2Kx4(kx3);\n fMathieson->SetSqrtKy3AndDeriveKy2Ky4(ky3);\n\n delete fClusterFinder;\n fClusterFinder = new AliMUONClusterFinderCOG;\n return fClusterFinder->Prepare(segmentations,digits);\n}\n\n\/\/_____________________________________________________________________________\nAliMUONCluster* \nAliMUONClusterFinderSimpleFit::NextCluster()\n{\n \/\/\/ Returns next cluster\n \n if ( !fClusterFinder ) return 0x0;\n AliMUONCluster* cluster = fClusterFinder->NextCluster();\n if ( cluster )\n {\n ComputePosition(*cluster);\n\n if ( cluster->Charge() < 7 )\n {\n \/\/ skip that one\n return NextCluster();\n } \n }\n return cluster;\n}\n\n\/\/_____________________________________________________________________________\nvoid \nAliMUONClusterFinderSimpleFit::ComputePosition(AliMUONCluster& cluster)\n{\n \/\/\/ Compute the position of the given cluster, by fitting a Mathieson\n \/\/\/ charge distribution to it\n \n TVirtualFitter* fitter = TVirtualFitter::Fitter(0,2);\n fitter->SetFCN(FitFunction);\n\n if ( cluster.Multiplicity() < 3 ) return;\n \n \/\/ We try a Mathieson fit, starting\n \/\/ with the center-of-gravity estimate as a first guess\n \/\/ for the cluster center.\n \n Double_t xCOG = cluster.Position().X();\n Double_t yCOG = cluster.Position().Y();\n \n Float_t stepX = 0.01; \/\/ cm\n Float_t stepY = 0.01; \/\/ cm\n \n Double_t arg(-1); \/\/ disable printout\n \n fitter->ExecuteCommand(\"SET PRINT\",&arg,1);\n \n fitter->SetParameter(0,\"cluster X position\",xCOG,stepX,0,0);\n fitter->SetParameter(1,\"cluster Y position\",yCOG,stepY,0,0);\n \n TObjArray userObjects;\n \n userObjects.Add(&cluster);\n userObjects.Add(fMathieson);\n \n fitter->SetObjectFit(&userObjects);\n \n Int_t val = fitter->ExecuteCommand(\"MIGRAD\",0,0);\n AliDebug(1,Form(\"ExecuteCommand returned value=%d\",val));\n if ( val ) \n {\n \/\/ fit failed. Using COG results, with big errors\n AliWarning(\"Fit failed. Using COG results for cluster=\");\n StdoutToAliWarning(cluster.Print());\n cluster.SetPosition(TVector2(xCOG,yCOG),TVector2(TMath::Abs(xCOG),TMath::Abs(yCOG)));\n cluster.SetChi2(1E3);\n }\n \n Double_t results[] = { fitter->GetParameter(0),\n fitter->GetParameter(1) };\n \n Double_t errors[] = { fitter->GetParError(0),\n fitter->GetParError(1) };\n \n cluster.SetPosition(TVector2(results[0],results[1]),\n TVector2(errors[0],errors[1]));\n \n Double_t amin, edm, errdef;\n Int_t nvpar, nparx;\n \n fitter->GetStats(amin, edm, errdef, nvpar, nparx);\n\n Double_t chi2 = amin;\n \n AliDebug(1,Form(\"Cluster fitted to (x,y)=(%e,%e) (xerr,yerr)=(%e,%e) \\n chi2=%e ndf=%d\",\n results[0],results[1],\n errors[0],errors[1],chi2,fitter->GetNumberFreeParameters()));\n cluster.SetChi2(chi2);\n}\n\n\n\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: XMLPropertyBackpatcher.cxx,v $\n *\n * $Revision: 1.2 $\n *\n * last change: $Author: dvo $ $Date: 2000-09-28 18:27:13 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_\n#include <com\/sun\/star\/beans\/XPropertySet.hpp>\n#endif\n\n#ifndef _COM_SUN_STAR_UNO_REFERENCE_H_\n#include <com\/sun\/star\/uno\/Reference.h>\n#endif\n\n#ifndef _RTL_USTRING\n#include <rtl\/ustring>\n#endif\n\n#ifndef _TOOLS_DEBUG_HXX\n#include <tools\/debug.hxx>\n#endif\n\n#ifndef _XMLOFF_XMLPROPERTYBACKPATCHER_HXX\n#include \"XMLPropertyBackpatcher.hxx\"\n#endif\n\n\nusing ::rtl::OUString;\nusing ::std::vector;\nusing ::std::map;\nusing ::com::sun::star::uno::Reference;\nusing ::com::sun::star::uno::Any;\nusing ::com::sun::star::beans::XPropertySet;\n\n\ntemplate<class A>\nXMLPropertyBackpatcher<A>::XMLPropertyBackpatcher(\n const ::rtl::OUString& sPropName) :\n sPropertyName(sPropName),\n bDefaultHandling(sal_False),\n bPreserveProperty(sal_False),\n sPreservePropertyName()\n{\n}\n\ntemplate<class A>\nXMLPropertyBackpatcher<A>::XMLPropertyBackpatcher(\n const OUString& sPropName,\n const OUString& sPreserveName,\n sal_Bool bDefault,\n A aDef) :\n sPropertyName(sPropName),\n bDefaultHandling(bDefault),\n aDefault(aDef),\n sPreservePropertyName(sPreserveName),\n bPreserveProperty(sPreserveName.getLength()>0)\n{\n}\n\ntemplate<class A>\nXMLPropertyBackpatcher<A>::XMLPropertyBackpatcher(\n const sal_Char* pPropName) :\n sPropertyName(),\n bDefaultHandling(sal_False),\n bPreserveProperty(sal_False),\n sPreservePropertyName()\n{\n DBG_ASSERT(pPropName != NULL, \"need property name\");\n sPropertyName = OUString::createFromAscii(pPropName);\n}\n\ntemplate<class A>\nXMLPropertyBackpatcher<A>::XMLPropertyBackpatcher(\n const sal_Char* pPropName,\n const sal_Char* pPreservePropName,\n sal_Bool bDefault,\n A aDef) :\n sPropertyName(),\n sPreservePropertyName(),\n bDefaultHandling(bDefault),\n bPreserveProperty(pPreservePropName != NULL),\n aDefault(aDef)\n{\n DBG_ASSERT(pPropName != NULL, \"need property name\");\n sPropertyName = OUString::createFromAscii(pPropName);\n if (pPreservePropName != NULL)\n {\n sPreservePropertyName = OUString::createFromAscii(pPreservePropName);\n }\n}\n\ntemplate<class A>\nXMLPropertyBackpatcher<A>::~XMLPropertyBackpatcher()\n{\n SetDefault();\n}\n\n\ntemplate<class A>\nvoid XMLPropertyBackpatcher<A>::ResolveId(\n const OUString& sName,\n A aValue)\n{\n \/\/ insert ID into ID map\n aIDMap[sName] = aValue;\n\n \/\/ backpatch old references, if backpatch list exists\n if (aBackpatchListMap.count(sName))\n {\n \/\/ aah, we have a backpatch list!\n BackpatchListType* pList =\n (BackpatchListType*)aBackpatchListMap[sName];\n\n \/\/ a) remove list from list map\n aBackpatchListMap.erase(sName);\n\n \/\/ b) for every item, set SequenceNumber\n \/\/ (and preserve Property, if appropriate)\n Any aAny;\n aAny <<= aValue;\n if (bPreserveProperty)\n {\n \/\/ preserve version\n for(BackpatchListType::iterator aIter = pList->begin();\n aIter != pList->end();\n aIter++)\n {\n Reference<XPropertySet> xProp = (*aIter);\n Any aPres = xProp->getPropertyValue(sPreservePropertyName);\n xProp->setPropertyValue(sPropertyName, aAny);\n xProp->setPropertyValue(sPreservePropertyName, aPres);\n }\n }\n else\n {\n \/\/ without preserve\n for(BackpatchListType::iterator aIter = pList->begin();\n aIter != pList->end();\n aIter++)\n {\n (*aIter)->setPropertyValue(sPropertyName, aAny);\n }\n }\n\n \/\/ c) delete list\n delete pList;\n }\n \/\/ else: no backpatch list -> then we're finished\n}\n\ntemplate<class A>\nvoid XMLPropertyBackpatcher<A>::SetProperty(\n const Reference<XPropertySet> & xPropSet,\n const OUString& sName)\n{\n Reference<XPropertySet> xNonConstPropSet(xPropSet);\n SetProperty(xNonConstPropSet, sName);\n}\n\ntemplate<class A>\nvoid XMLPropertyBackpatcher<A>::SetProperty(\n Reference<XPropertySet> & xPropSet,\n const OUString& sName)\n{\n if (aIDMap.count(sName))\n {\n \/\/ we know this ID -> set property\n Any aAny;\n aAny <<= aIDMap[sName];\n xPropSet->setPropertyValue(sPropertyName, aAny);\n }\n else\n {\n \/\/ ID unknown -> into backpatch list for later fixup\n if (! aBackpatchListMap.count(sName))\n {\n \/\/ create backpatch list for this name\n BackpatchListType* pTmp = new BackpatchListType() ;\n aBackpatchListMap[sName] = (void*)pTmp;\n }\n\n \/\/ insert footnote\n ((BackpatchListType*)aBackpatchListMap[sName])->push_back(xPropSet);\n }\n}\n\ntemplate<class A>\nvoid XMLPropertyBackpatcher<A>::SetDefault()\n{\n if (bDefaultHandling)\n {\n \/\/ not implemented yet\n }\n}\n\n\/\/ force instantiation of templates\ntemplate XMLPropertyBackpatcher<sal_Int16>;\ntemplate XMLPropertyBackpatcher<OUString>;\n<commit_msg>- fixed: wrong syntax for explicit template instantiation<commit_after>\/*************************************************************************\n *\n * $RCSfile: XMLPropertyBackpatcher.cxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: dvo $ $Date: 2000-10-04 21:16:49 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_\n#include <com\/sun\/star\/beans\/XPropertySet.hpp>\n#endif\n\n#ifndef _COM_SUN_STAR_UNO_REFERENCE_H_\n#include <com\/sun\/star\/uno\/Reference.h>\n#endif\n\n#ifndef _RTL_USTRING\n#include <rtl\/ustring>\n#endif\n\n#ifndef _TOOLS_DEBUG_HXX\n#include <tools\/debug.hxx>\n#endif\n\n#ifndef _XMLOFF_XMLPROPERTYBACKPATCHER_HXX\n#include \"XMLPropertyBackpatcher.hxx\"\n#endif\n\n\nusing ::rtl::OUString;\nusing ::std::vector;\nusing ::std::map;\nusing ::com::sun::star::uno::Reference;\nusing ::com::sun::star::uno::Any;\nusing ::com::sun::star::beans::XPropertySet;\n\n\ntemplate<class A>\nXMLPropertyBackpatcher<A>::XMLPropertyBackpatcher(\n const ::rtl::OUString& sPropName) :\n sPropertyName(sPropName),\n bDefaultHandling(sal_False),\n bPreserveProperty(sal_False),\n sPreservePropertyName()\n{\n}\n\ntemplate<class A>\nXMLPropertyBackpatcher<A>::XMLPropertyBackpatcher(\n const OUString& sPropName,\n const OUString& sPreserveName,\n sal_Bool bDefault,\n A aDef) :\n sPropertyName(sPropName),\n bDefaultHandling(bDefault),\n aDefault(aDef),\n sPreservePropertyName(sPreserveName),\n bPreserveProperty(sPreserveName.getLength()>0)\n{\n}\n\ntemplate<class A>\nXMLPropertyBackpatcher<A>::XMLPropertyBackpatcher(\n const sal_Char* pPropName) :\n sPropertyName(),\n bDefaultHandling(sal_False),\n bPreserveProperty(sal_False),\n sPreservePropertyName()\n{\n DBG_ASSERT(pPropName != NULL, \"need property name\");\n sPropertyName = OUString::createFromAscii(pPropName);\n}\n\ntemplate<class A>\nXMLPropertyBackpatcher<A>::XMLPropertyBackpatcher(\n const sal_Char* pPropName,\n const sal_Char* pPreservePropName,\n sal_Bool bDefault,\n A aDef) :\n sPropertyName(),\n sPreservePropertyName(),\n bDefaultHandling(bDefault),\n bPreserveProperty(pPreservePropName != NULL),\n aDefault(aDef)\n{\n DBG_ASSERT(pPropName != NULL, \"need property name\");\n sPropertyName = OUString::createFromAscii(pPropName);\n if (pPreservePropName != NULL)\n {\n sPreservePropertyName = OUString::createFromAscii(pPreservePropName);\n }\n}\n\ntemplate<class A>\nXMLPropertyBackpatcher<A>::~XMLPropertyBackpatcher()\n{\n SetDefault();\n}\n\n\ntemplate<class A>\nvoid XMLPropertyBackpatcher<A>::ResolveId(\n const OUString& sName,\n A aValue)\n{\n \/\/ insert ID into ID map\n aIDMap[sName] = aValue;\n\n \/\/ backpatch old references, if backpatch list exists\n if (aBackpatchListMap.count(sName))\n {\n \/\/ aah, we have a backpatch list!\n BackpatchListType* pList =\n (BackpatchListType*)aBackpatchListMap[sName];\n\n \/\/ a) remove list from list map\n aBackpatchListMap.erase(sName);\n\n \/\/ b) for every item, set SequenceNumber\n \/\/ (and preserve Property, if appropriate)\n Any aAny;\n aAny <<= aValue;\n if (bPreserveProperty)\n {\n \/\/ preserve version\n for(BackpatchListType::iterator aIter = pList->begin();\n aIter != pList->end();\n aIter++)\n {\n Reference<XPropertySet> xProp = (*aIter);\n Any aPres = xProp->getPropertyValue(sPreservePropertyName);\n xProp->setPropertyValue(sPropertyName, aAny);\n xProp->setPropertyValue(sPreservePropertyName, aPres);\n }\n }\n else\n {\n \/\/ without preserve\n for(BackpatchListType::iterator aIter = pList->begin();\n aIter != pList->end();\n aIter++)\n {\n (*aIter)->setPropertyValue(sPropertyName, aAny);\n }\n }\n\n \/\/ c) delete list\n delete pList;\n }\n \/\/ else: no backpatch list -> then we're finished\n}\n\ntemplate<class A>\nvoid XMLPropertyBackpatcher<A>::SetProperty(\n const Reference<XPropertySet> & xPropSet,\n const OUString& sName)\n{\n Reference<XPropertySet> xNonConstPropSet(xPropSet);\n SetProperty(xNonConstPropSet, sName);\n}\n\ntemplate<class A>\nvoid XMLPropertyBackpatcher<A>::SetProperty(\n Reference<XPropertySet> & xPropSet,\n const OUString& sName)\n{\n if (aIDMap.count(sName))\n {\n \/\/ we know this ID -> set property\n Any aAny;\n aAny <<= aIDMap[sName];\n xPropSet->setPropertyValue(sPropertyName, aAny);\n }\n else\n {\n \/\/ ID unknown -> into backpatch list for later fixup\n if (! aBackpatchListMap.count(sName))\n {\n \/\/ create backpatch list for this name\n BackpatchListType* pTmp = new BackpatchListType() ;\n aBackpatchListMap[sName] = (void*)pTmp;\n }\n\n \/\/ insert footnote\n ((BackpatchListType*)aBackpatchListMap[sName])->push_back(xPropSet);\n }\n}\n\ntemplate<class A>\nvoid XMLPropertyBackpatcher<A>::SetDefault()\n{\n if (bDefaultHandling)\n {\n \/\/ not implemented yet\n }\n}\n\n\/\/ force instantiation of templates\ntemplate class XMLPropertyBackpatcher<sal_Int16>;\ntemplate class XMLPropertyBackpatcher<OUString>;\n\n<|endoftext|>"} {"text":"<commit_before>#include <maya\/MFnMesh.h>\n#include <maya\/MFnMeshData.h>\n#include <maya\/MEulerRotation.h>\n#include <maya\/MQuaternion.h>\n#include <maya\/MFnArrayAttrsData.h>\n#include <maya\/MArrayDataBuilder.h>\n\n#include \"Asset.h\"\n#include \"AssetNode.h\"\n#include \"OutputInstancerObject.h\"\n#include \"util.h\"\n\nOutputInstancerObject::OutputInstancerObject(\n int assetId,\n int objectId,\n Asset* objectControl\n ) :\n OutputObject(\n assetId,\n objectId,\n objectControl\n ),\n myGeoInfo(HAPI_GeoInfo_Create())\n{\n \/\/update();\n}\n\nOutputInstancerObject::~OutputInstancerObject() {}\n\nOutputObject::ObjectType\nOutputInstancerObject::type()\n{\n return OutputObject::OBJECT_TYPE_INSTANCER;\n}\n\nMStringArray\nOutputInstancerObject::getAttributeStringData(HAPI_AttributeOwner owner, MString name)\n{\n return Util::getAttributeStringData(myAssetId, myObjectId, 0, 0, owner, name);\n}\n\nvoid\nOutputInstancerObject::update()\n{\n try\n {\n HAPI_Result hstat = HAPI_RESULT_SUCCESS;\n hstat = HAPI_GetGeoInfo(myAssetId, myObjectId, 0, &myGeoInfo);\n Util::checkHAPIStatus(hstat);\n }\n catch (HAPIError& e)\n {\n cerr << e.what() << endl;\n return;\n }\n\n if(myNeverBuilt || myGeoInfo.hasGeoChanged)\n {\n \/\/ clear the arrays\n myInstancedObjectNames.clear();\n myInstancedObjectIndices.clear();\n myUniqueInstObjNames.clear();\n myHoudiniInstanceAttribute.clear();\n myHoudiniNameAttribute.clear();\n\n try\n {\n if(myGeoInfo.partCount <= 0)\n return;\n\n HAPI_Result hstat = HAPI_RESULT_SUCCESS;\n hstat = HAPI_GetPartInfo(myAssetId, myObjectId, 0, 0, &myPartInfo);\n Util::checkHAPIStatus(hstat);\n }\n catch (HAPIError& e)\n {\n cerr << e.what() << endl;\n }\n\n if(myObjectInfo.objectToInstanceId >= 0)\n {\n myInstancedObjectIndices = MIntArray(myPartInfo.pointCount, 0);\n return;\n }\n\n \/\/ fill array of size pointCount of instanced names\n MStringArray instanceAttrs = getAttributeStringData(HAPI_ATTROWNER_POINT, \"instance\");\n for(unsigned int i=0; i<instanceAttrs.length(); i++)\n {\n MStringArray splitObjName;\n instanceAttrs[i].split('\/', splitObjName);\n myInstancedObjectNames.append(splitObjName[splitObjName.length()-1]);\n myHoudiniInstanceAttribute.append(instanceAttrs[i]);\n }\n\n MStringArray nameAttrs = getAttributeStringData(HAPI_ATTROWNER_POINT, \"name\");\n for(unsigned int ii = 0; ii < nameAttrs.length(); ii++)\n {\n myHoudiniNameAttribute.append(nameAttrs[ii]);\n }\n\n \/\/ get a list of unique instanced names, and compute the object indices that would\n \/\/ be passed to Maya instancer\n for(unsigned int i = 0; i< myInstancedObjectNames.length(); ++i)\n {\n bool duplicate = false;\n unsigned int j = 0;\n for(; j< myUniqueInstObjNames.length(); ++j)\n {\n if(myUniqueInstObjNames[j] == myInstancedObjectNames[i])\n {\n duplicate = true;\n break;\n }\n }\n if(!duplicate)\n myUniqueInstObjNames.append(myInstancedObjectNames[i]);\n myInstancedObjectIndices.append((int) j);\n }\n\n \/\/ Workaround a crash where we can't determine the object to instance.\n if(!myInstancedObjectNames.length())\n {\n myInstancedObjectIndices = MIntArray(myPartInfo.pointCount, -1);\n }\n }\n}\n\nMIntArray\nOutputInstancerObject::getInstancedObjIds()\n{\n MIntArray ret;\n if(myObjectInfo.objectToInstanceId >= 0)\n ret.append(myObjectInfo.objectToInstanceId);\n return ret;\n}\n\nMStringArray\nOutputInstancerObject::getUniqueInstObjNames()\n{\n return myUniqueInstObjNames;\n}\n\nMStatus\n\/\/OutputInstancerObject::compute(const MPlug& plug, MDataBlock& data)\nOutputInstancerObject::compute(\n MDataHandle& handle,\n bool &needToSyncOutputs\n )\n{\n update();\n\n if(myGeoInfo.partCount <= 0)\n return MS::kFailure;\n\n if(myNeverBuilt || myGeoInfo.hasGeoChanged)\n {\n MDataHandle instancerDataHandle = handle.child(AssetNode::outputInstancerData);\n MArrayDataHandle instancedObjectNamesHandle = handle.child(AssetNode::outputInstancedObjectNames);\n MArrayDataHandle houdiniInstanceAttributeHandle = handle.child(AssetNode::outputHoudiniInstanceAttribute);\n MArrayDataHandle houdiniNameAttributeHandle = handle.child(AssetNode::outputHoudiniNameAttribute);\n MArrayDataHandle instanceTransformHandle = handle.child(AssetNode::outputInstanceTransform);\n\n \/\/MDataHandle instHandle = data.outputValue(instancerDataPlug);\n MFnArrayAttrsData fnAAD;\n MObject instOutput = fnAAD.create();\n MVectorArray positions = fnAAD.vectorArray(\"position\");\n MVectorArray rotations = fnAAD.vectorArray(\"rotation\");\n MVectorArray scales = fnAAD.vectorArray(\"scale\");\n MIntArray objectIndices = fnAAD.intArray(\"objectIndex\");\n\n unsigned int size = myPartInfo.pointCount;\n HAPI_Transform * instTransforms = new HAPI_Transform[size];\n HAPI_GetInstanceTransforms(myAssetId, myObjectInfo.id, 0, HAPI_SRT, instTransforms, 0, size);\n\n MArrayDataBuilder houdiniInstanceAttributeBuilder = houdiniInstanceAttributeHandle.builder();\n MArrayDataBuilder houdiniNameAttributeBuilder = houdiniNameAttributeHandle.builder();\n MArrayDataBuilder instanceTransformBuilder = instanceTransformHandle.builder();\n\n for(unsigned int j=0; j<size; j++)\n {\n HAPI_Transform it = instTransforms[j];\n MVector p(it.position[0], it.position[1], it.position[2]);\n MVector r = MQuaternion(it.rotationQuaternion[0],\n it.rotationQuaternion[1], it.rotationQuaternion[2],\n it.rotationQuaternion[3]).asEulerRotation().asVector();\n MVector s(it.scale[0], it.scale[1], it.scale[2]);\n\n int objIndex = myInstancedObjectIndices[j];\n\n positions.append(p);\n rotations.append(r);\n scales.append(s);\n objectIndices.append(objIndex);\n\n if(myHoudiniInstanceAttribute.length() == size)\n {\n MDataHandle intanceAttributeHandle = houdiniInstanceAttributeBuilder.addElement(j);\n intanceAttributeHandle.set(myHoudiniInstanceAttribute[j]);\n }\n\n if(myHoudiniNameAttribute.length() == size)\n {\n MDataHandle nameAttributeHandle = houdiniNameAttributeBuilder.addElement(j);\n nameAttributeHandle.set(myHoudiniNameAttribute[j]);\n }\n\n MDataHandle transformHandle = instanceTransformBuilder.addElement(j);\n MDataHandle translateHandle = transformHandle.child(AssetNode::outputInstanceTranslate);\n MDataHandle rotateHandle = transformHandle.child(AssetNode::outputInstanceRotate);\n MDataHandle scaleHandle = transformHandle.child(AssetNode::outputInstanceScale);\n\n MDataHandle txHandle = translateHandle.child(AssetNode::outputInstanceTranslateX);\n txHandle.set(p.x);\n MDataHandle tyHandle = translateHandle.child(AssetNode::outputInstanceTranslateY);\n tyHandle.set(p.y);\n MDataHandle tzHandle = translateHandle.child(AssetNode::outputInstanceTranslateZ);\n tzHandle.set(p.z);\n\n MDataHandle rxHandle = rotateHandle.child(AssetNode::outputInstanceRotateX);\n rxHandle.set(r.x);\n MDataHandle ryHandle = rotateHandle.child(AssetNode::outputInstanceRotateY);\n ryHandle.set(r.y);\n MDataHandle rzHandle = rotateHandle.child(AssetNode::outputInstanceRotateZ);\n rzHandle.set(r.z);\n\n MDataHandle sxHandle = scaleHandle.child(AssetNode::outputInstanceScaleX);\n sxHandle.set(s.x);\n MDataHandle syHandle = scaleHandle.child(AssetNode::outputInstanceScaleY);\n syHandle.set(s.y);\n MDataHandle szHandle = scaleHandle.child(AssetNode::outputInstanceScaleZ);\n szHandle.set(s.z);\n }\n\n houdiniInstanceAttributeHandle.set(houdiniInstanceAttributeBuilder);\n houdiniInstanceAttributeHandle.setAllClean();\n\n houdiniNameAttributeHandle.set(houdiniNameAttributeBuilder);\n houdiniNameAttributeHandle.setAllClean();\n\n instanceTransformHandle.set(instanceTransformBuilder);\n instanceTransformHandle.setAllClean();\n\n delete[] instTransforms;\n\n instancerDataHandle.set(instOutput);\n\n MArrayDataBuilder builder = instancedObjectNamesHandle.builder();\n if(myObjectInfo.objectToInstanceId >= 0)\n {\n \/\/ instancing a single object\n OutputObject* objToInstance = myObjectControl->findObjectById(myObjectInfo.objectToInstanceId);\n MString name = objToInstance->getName();\n\n MDataHandle h = builder.addElement(0);\n h.set(name);\n } else\n {\n \/\/ instancing multiple objects\n for(unsigned int i=0; i< myUniqueInstObjNames.length(); i++)\n {\n MDataHandle h = builder.addElement(i);\n h.set(myUniqueInstObjNames[i]);\n }\n\n \/\/ clean up extra elements\n int builderSizeCheck = builder.elementCount();\n if(builderSizeCheck > (int) myUniqueInstObjNames.length())\n {\n for(int i= myUniqueInstObjNames.length(); i<builderSizeCheck; i++)\n {\n builder.removeElement(i);\n }\n }\n }\n instancedObjectNamesHandle.set(builder);\n instancedObjectNamesHandle.setAllClean();\n\n handle.setClean();\n instancerDataHandle.setClean();\n \/\/data.setClean(plug);\n \/\/data.setClean(instancerDataPlug);\n\n myNeverBuilt = false;\n }\n\n return MS::kSuccess;\n}\n<commit_msg>Use HAPI_GetObjects to get instance object name<commit_after>#include <maya\/MFnMesh.h>\n#include <maya\/MFnMeshData.h>\n#include <maya\/MEulerRotation.h>\n#include <maya\/MQuaternion.h>\n#include <maya\/MFnArrayAttrsData.h>\n#include <maya\/MArrayDataBuilder.h>\n\n#include \"Asset.h\"\n#include \"AssetNode.h\"\n#include \"OutputInstancerObject.h\"\n#include \"util.h\"\n\nOutputInstancerObject::OutputInstancerObject(\n int assetId,\n int objectId,\n Asset* objectControl\n ) :\n OutputObject(\n assetId,\n objectId,\n objectControl\n ),\n myGeoInfo(HAPI_GeoInfo_Create())\n{\n \/\/update();\n}\n\nOutputInstancerObject::~OutputInstancerObject() {}\n\nOutputObject::ObjectType\nOutputInstancerObject::type()\n{\n return OutputObject::OBJECT_TYPE_INSTANCER;\n}\n\nMStringArray\nOutputInstancerObject::getAttributeStringData(HAPI_AttributeOwner owner, MString name)\n{\n return Util::getAttributeStringData(myAssetId, myObjectId, 0, 0, owner, name);\n}\n\nvoid\nOutputInstancerObject::update()\n{\n try\n {\n HAPI_Result hstat = HAPI_RESULT_SUCCESS;\n hstat = HAPI_GetGeoInfo(myAssetId, myObjectId, 0, &myGeoInfo);\n Util::checkHAPIStatus(hstat);\n }\n catch (HAPIError& e)\n {\n cerr << e.what() << endl;\n return;\n }\n\n if(myNeverBuilt || myGeoInfo.hasGeoChanged)\n {\n \/\/ clear the arrays\n myInstancedObjectNames.clear();\n myInstancedObjectIndices.clear();\n myUniqueInstObjNames.clear();\n myHoudiniInstanceAttribute.clear();\n myHoudiniNameAttribute.clear();\n\n try\n {\n if(myGeoInfo.partCount <= 0)\n return;\n\n HAPI_Result hstat = HAPI_RESULT_SUCCESS;\n hstat = HAPI_GetPartInfo(myAssetId, myObjectId, 0, 0, &myPartInfo);\n Util::checkHAPIStatus(hstat);\n }\n catch (HAPIError& e)\n {\n cerr << e.what() << endl;\n }\n\n if(myObjectInfo.objectToInstanceId >= 0)\n {\n myInstancedObjectIndices = MIntArray(myPartInfo.pointCount, 0);\n return;\n }\n\n \/\/ fill array of size pointCount of instanced names\n MStringArray instanceAttrs = getAttributeStringData(HAPI_ATTROWNER_POINT, \"instance\");\n for(unsigned int i=0; i<instanceAttrs.length(); i++)\n {\n MStringArray splitObjName;\n instanceAttrs[i].split('\/', splitObjName);\n myInstancedObjectNames.append(splitObjName[splitObjName.length()-1]);\n myHoudiniInstanceAttribute.append(instanceAttrs[i]);\n }\n\n MStringArray nameAttrs = getAttributeStringData(HAPI_ATTROWNER_POINT, \"name\");\n for(unsigned int ii = 0; ii < nameAttrs.length(); ii++)\n {\n myHoudiniNameAttribute.append(nameAttrs[ii]);\n }\n\n \/\/ get a list of unique instanced names, and compute the object indices that would\n \/\/ be passed to Maya instancer\n for(unsigned int i = 0; i< myInstancedObjectNames.length(); ++i)\n {\n bool duplicate = false;\n unsigned int j = 0;\n for(; j< myUniqueInstObjNames.length(); ++j)\n {\n if(myUniqueInstObjNames[j] == myInstancedObjectNames[i])\n {\n duplicate = true;\n break;\n }\n }\n if(!duplicate)\n myUniqueInstObjNames.append(myInstancedObjectNames[i]);\n myInstancedObjectIndices.append((int) j);\n }\n\n \/\/ Workaround a crash where we can't determine the object to instance.\n if(!myInstancedObjectNames.length())\n {\n myInstancedObjectIndices = MIntArray(myPartInfo.pointCount, -1);\n }\n }\n}\n\nMIntArray\nOutputInstancerObject::getInstancedObjIds()\n{\n MIntArray ret;\n if(myObjectInfo.objectToInstanceId >= 0)\n ret.append(myObjectInfo.objectToInstanceId);\n return ret;\n}\n\nMStringArray\nOutputInstancerObject::getUniqueInstObjNames()\n{\n return myUniqueInstObjNames;\n}\n\nMStatus\n\/\/OutputInstancerObject::compute(const MPlug& plug, MDataBlock& data)\nOutputInstancerObject::compute(\n MDataHandle& handle,\n bool &needToSyncOutputs\n )\n{\n update();\n\n if(myGeoInfo.partCount <= 0)\n return MS::kFailure;\n\n if(myNeverBuilt || myGeoInfo.hasGeoChanged)\n {\n MDataHandle instancerDataHandle = handle.child(AssetNode::outputInstancerData);\n MArrayDataHandle instancedObjectNamesHandle = handle.child(AssetNode::outputInstancedObjectNames);\n MArrayDataHandle houdiniInstanceAttributeHandle = handle.child(AssetNode::outputHoudiniInstanceAttribute);\n MArrayDataHandle houdiniNameAttributeHandle = handle.child(AssetNode::outputHoudiniNameAttribute);\n MArrayDataHandle instanceTransformHandle = handle.child(AssetNode::outputInstanceTransform);\n\n \/\/MDataHandle instHandle = data.outputValue(instancerDataPlug);\n MFnArrayAttrsData fnAAD;\n MObject instOutput = fnAAD.create();\n MVectorArray positions = fnAAD.vectorArray(\"position\");\n MVectorArray rotations = fnAAD.vectorArray(\"rotation\");\n MVectorArray scales = fnAAD.vectorArray(\"scale\");\n MIntArray objectIndices = fnAAD.intArray(\"objectIndex\");\n\n unsigned int size = myPartInfo.pointCount;\n HAPI_Transform * instTransforms = new HAPI_Transform[size];\n HAPI_GetInstanceTransforms(myAssetId, myObjectInfo.id, 0, HAPI_SRT, instTransforms, 0, size);\n\n MArrayDataBuilder houdiniInstanceAttributeBuilder = houdiniInstanceAttributeHandle.builder();\n MArrayDataBuilder houdiniNameAttributeBuilder = houdiniNameAttributeHandle.builder();\n MArrayDataBuilder instanceTransformBuilder = instanceTransformHandle.builder();\n\n for(unsigned int j=0; j<size; j++)\n {\n HAPI_Transform it = instTransforms[j];\n MVector p(it.position[0], it.position[1], it.position[2]);\n MVector r = MQuaternion(it.rotationQuaternion[0],\n it.rotationQuaternion[1], it.rotationQuaternion[2],\n it.rotationQuaternion[3]).asEulerRotation().asVector();\n MVector s(it.scale[0], it.scale[1], it.scale[2]);\n\n int objIndex = myInstancedObjectIndices[j];\n\n positions.append(p);\n rotations.append(r);\n scales.append(s);\n objectIndices.append(objIndex);\n\n if(myHoudiniInstanceAttribute.length() == size)\n {\n MDataHandle intanceAttributeHandle = houdiniInstanceAttributeBuilder.addElement(j);\n intanceAttributeHandle.set(myHoudiniInstanceAttribute[j]);\n }\n\n if(myHoudiniNameAttribute.length() == size)\n {\n MDataHandle nameAttributeHandle = houdiniNameAttributeBuilder.addElement(j);\n nameAttributeHandle.set(myHoudiniNameAttribute[j]);\n }\n\n MDataHandle transformHandle = instanceTransformBuilder.addElement(j);\n MDataHandle translateHandle = transformHandle.child(AssetNode::outputInstanceTranslate);\n MDataHandle rotateHandle = transformHandle.child(AssetNode::outputInstanceRotate);\n MDataHandle scaleHandle = transformHandle.child(AssetNode::outputInstanceScale);\n\n MDataHandle txHandle = translateHandle.child(AssetNode::outputInstanceTranslateX);\n txHandle.set(p.x);\n MDataHandle tyHandle = translateHandle.child(AssetNode::outputInstanceTranslateY);\n tyHandle.set(p.y);\n MDataHandle tzHandle = translateHandle.child(AssetNode::outputInstanceTranslateZ);\n tzHandle.set(p.z);\n\n MDataHandle rxHandle = rotateHandle.child(AssetNode::outputInstanceRotateX);\n rxHandle.set(r.x);\n MDataHandle ryHandle = rotateHandle.child(AssetNode::outputInstanceRotateY);\n ryHandle.set(r.y);\n MDataHandle rzHandle = rotateHandle.child(AssetNode::outputInstanceRotateZ);\n rzHandle.set(r.z);\n\n MDataHandle sxHandle = scaleHandle.child(AssetNode::outputInstanceScaleX);\n sxHandle.set(s.x);\n MDataHandle syHandle = scaleHandle.child(AssetNode::outputInstanceScaleY);\n syHandle.set(s.y);\n MDataHandle szHandle = scaleHandle.child(AssetNode::outputInstanceScaleZ);\n szHandle.set(s.z);\n }\n\n houdiniInstanceAttributeHandle.set(houdiniInstanceAttributeBuilder);\n houdiniInstanceAttributeHandle.setAllClean();\n\n houdiniNameAttributeHandle.set(houdiniNameAttributeBuilder);\n houdiniNameAttributeHandle.setAllClean();\n\n instanceTransformHandle.set(instanceTransformBuilder);\n instanceTransformHandle.setAllClean();\n\n delete[] instTransforms;\n\n instancerDataHandle.set(instOutput);\n\n MArrayDataBuilder builder = instancedObjectNamesHandle.builder();\n if(myObjectInfo.objectToInstanceId >= 0)\n {\n \/\/ instancing a single object\n HAPI_ObjectInfo instanceObjectInfo;\n HAPI_GetObjects(\n myAssetId,\n &instanceObjectInfo,\n myObjectInfo.objectToInstanceId, 1\n );\n MString name = Util::getString(instanceObjectInfo.nameSH);\n\n MDataHandle h = builder.addElement(0);\n h.set(name);\n } else\n {\n \/\/ instancing multiple objects\n for(unsigned int i=0; i< myUniqueInstObjNames.length(); i++)\n {\n MDataHandle h = builder.addElement(i);\n h.set(myUniqueInstObjNames[i]);\n }\n\n \/\/ clean up extra elements\n int builderSizeCheck = builder.elementCount();\n if(builderSizeCheck > (int) myUniqueInstObjNames.length())\n {\n for(int i= myUniqueInstObjNames.length(); i<builderSizeCheck; i++)\n {\n builder.removeElement(i);\n }\n }\n }\n instancedObjectNamesHandle.set(builder);\n instancedObjectNamesHandle.setAllClean();\n\n handle.setClean();\n instancerDataHandle.setClean();\n \/\/data.setClean(plug);\n \/\/data.setClean(instancerDataPlug);\n\n myNeverBuilt = false;\n }\n\n return MS::kSuccess;\n}\n<|endoftext|>"} {"text":"<commit_before>\/**\n * \\file dog_box_approx.cpp\n *\n * Difference of Gaussians approximated using box filters\n * - convert RGB image to V or HSV\n * - compute first box filter\n * - compute x-y overlapped summed area table\n * - compute two different box filters using different box radii\n * - apply 2nd order x box filter on each output\n * - apply 2nd order y box filter on each output\n * - compute the difference between the two in the finite difference operator\n *\/\n\n#include <iostream>\n#include <Halide.h>\n\n#include \"recfilter.h\"\n#include \"iir_coeff.h\"\n\nusing namespace Halide;\n\n\/\/ Difference operator to compute 1D x double box filter from second order intergal image\nExpr diff_op_x(Func F, Expr x, Expr y, int w, int h, int B, int channel);\n\n\/\/ Difference operator to compute 1D y double box filter from second order intergal image\nExpr diff_op_y(Func F, Expr x, Expr y, int w, int h, int B, int channel);\n\n\/\/ Difference operator to compute 2D xy single box filter from summed area table\nExpr diff_op_xy(Func F, Expr x, Expr y, int w, int h, int B);\n\n\nint main(int argc, char** argv) {\n Arguments args(argc, argv);\n\n bool nosched = args.noschedule;\n int iter = args.iterations;\n int tile_width = args.block;\n int width = args.width;\n int height = args.width;\n\n int sigma1 = 1.0f;\n int sigma2 = 2.0f;\n\n \/\/ box filter radii for approximating Gaussians of given sigma with 3 iterations\n int B1 = gaussian_box_filter(sigma1, 3);\n int B2 = gaussian_box_filter(sigma2, 3);\n\n Image<int16_t> image = generate_random_image<int16_t>(width,height);\n\n \/\/ pad the image with zeros at borders\n int pad = std::max(3*B1+3, 3*B2+3);\n for (int k=0; k<image.channels(); k++) {\n for (int i=0; i<image.width(); i++) {\n for (int j=0; j<image.height(); j++) {\n if (i<pad || i>width-pad || j<pad || j>height-pad) {\n image(i,j,k) = 0.0f;\n }\n }\n }\n }\n\n RecFilterDim x(\"x\", width);\n RecFilterDim y(\"y\", height);\n\n \/\/ Compute V of HSV from RGB input\n RecFilter V(\"V\");\n \/\/ V(x,y) = Cast::make(type_of<float>(), max(image(x,y,0), max(image(x,y,1),image(x,y,2))));\n V(x,y) = Internal::Cast::make(type_of<float>(), image(x,y));\n\n \/\/ summed table from V channel\n RecFilter SAT(\"SAT\");\n SAT(x,y) = V.as_func()(x,y);\n SAT.add_filter(+x, {1.0f, 1.0f});\n SAT.add_filter(+y, {1.0f, 1.0f});\n\n \/\/ copmute 1 iteration of box filters from this result\n RecFilter Box1(\"Box1\");\n Box1(x,y) = Tuple(diff_op_xy(SAT.as_func(), x, y, width, height, B1), diff_op_xy(SAT.as_func(), x, y, width, height, B2));\n\n \/\/ compute 2nd order x box filter, calculate the 2nd order intergal image first on both outputs\n RecFilter SAT2x(\"SAT2x\");\n SAT2x(x,y) = Tuple(Box1.as_func()(x,y)[0], Box1.as_func()(x,y)[1]);\n SAT2x.add_filter(+x, {1.0f, 2.0f, -1.0f});\n\n \/\/ complete the 2nd order x box filter by difference operator\n RecFilter Box2x(\"Box2x\");\n Box2x(x,y) = Tuple(diff_op_x(SAT2x.as_func(), x, y, width, height, B1, 0), diff_op_x(SAT2x.as_func(), x, y, width, height, B2, 1));\n\n \/\/ compute 2nd order y box filter, calculate the 2nd order intergal image first on both outputs\n RecFilter SAT2y(\"SAT2y\");\n SAT2y(x,y) = Tuple(Box2x.as_func()(x,y)[0], Box2x.as_func()(x,y)[1]);\n SAT2y.add_filter(+y, {1.0f, 2.0f, -1.0f});\n\n \/\/ complete 2nd order y box filter, subtract the result and take square as final result\n RecFilter DoG(\"DoG\");\n DoG(x,y) = diff_op_y(SAT2y.as_func(), x, y, width, height, B1, 0) - diff_op_y(SAT2y.as_func(), x, y, width, height, B2, 1);\n\n\n \/\/ -------------------------------------------------------------------------\n \/\/ tile all the intgral image functions\n\n SAT.split_all_dimensions(tile_width);\n SAT2x.split_all_dimensions(tile_width);\n SAT2y.split_all_dimensions(tile_width);\n\n\n \/\/ -------------------------------------------------------------------------\n \/\/ schedules\n\n \/\/ Identical schedules for the three pointwise operations\n \/\/ these are not recursive filters, so it is just easier to\n \/\/ write schedule for them using Halide API\n\n Var xo(\"xo\"), xi(\"xi\"), xii(\"xii\"), u(x.var());\n Var yo(\"yo\"), yi(\"yi\"), yii(\"yii\"), v(y.var());\n\n Box1.as_func().compute_root()\n .split (u, xo, xi, tile_width)\n .split (v, yo, yi, tile_width)\n .split (yi,yi, yii,8)\n .unroll (yii)\n .reorder(yii,xi,yi,xo,yo)\n .gpu (xo,yo,xi,yi);\n\n Box2x.as_func().compute_root()\n .split (u, xo, xi, tile_width)\n .split (v, yo, yi, tile_width)\n .split (yi,yi, yii, 8)\n .unroll (yii)\n .reorder(yii,xi,yi,xo,yo)\n .gpu (xo,yo,xi,yi);\n\n DoG.as_func().compute_root()\n .split (u, xo, xi, tile_width)\n .split (v, yo, yi, tile_width)\n .split (yi,yi, yii,8)\n .unroll (yii)\n .reorder(yii,xi,yi,xo,yo)\n .gpu (xo,yo,xi,yi);\n\n \/\/ automatic schedules for recursive filter pipelines\n if (!nosched) {\n SAT .gpu_auto_schedule(128);\n SAT2x.gpu_auto_schedule(128);\n SAT2y.gpu_auto_schedule(128);\n }\n else {\n\n \/\/ euivalnet manual schedules\n\n int ws = 32;\n int unroll_w = ws\/4;\n int intra_tiles_per_warp = ws\/2;\n int inter_tiles_per_warp = 4;\n\n \/\/ first box filter\n {\n RecFilter F = SAT;\n\n F.intra_schedule(1).compute_locally()\n .reorder_storage(F.inner(), F.outer())\n .unroll (F.inner_scan())\n .split (F.inner(1), unroll_w)\n .unroll (F.inner(1).split_var())\n .reorder (F.inner_scan(), F.inner(1).split_var(), F.inner(), F.outer())\n .gpu_threads (F.inner(0), F.inner(1))\n .gpu_blocks (F.outer(0), F.outer(1));\n\n F.intra_schedule(2).compute_locally()\n .unroll (F.inner_scan())\n .split (F.outer(0), intra_tiles_per_warp)\n .reorder (F.inner(), F.inner_scan(), F.tail(), F.outer(0).split_var(), F.outer())\n .fuse (F.tail(), F.inner(0))\n .gpu_threads(F.tail(), F.outer(0).split_var())\n .gpu_blocks (F.outer(0), F.outer(1));\n\n F.inter_schedule().compute_globally()\n .reorder_storage(F.inner(), F.tail(), F.outer())\n .unroll (F.outer_scan())\n .split (F.outer(0), inter_tiles_per_warp)\n .reorder (F.outer_scan(), F.tail(), F.outer(0).split_var(), F.inner(), F.outer())\n .gpu_threads (F.inner(0), F.outer(0).split_var())\n .gpu_blocks (F.outer(0));\n\n }\n\n\n \/\/ second order 2 box filter along x\n {\n RecFilter sat_x = SAT2x;\n\n sat_x.intra_schedule().compute_locally()\n .split (sat_x.full(0), ws, sat_x.inner())\n .split (sat_x.inner(1), unroll_w)\n .unroll (sat_x.inner(1).split_var())\n .unroll (sat_x.inner_scan())\n .reorder (sat_x.inner_scan(), sat_x.inner(1).split_var(), sat_x.tail(), sat_x.inner(), sat_x.outer(), sat_x.full())\n .gpu_threads(sat_x.inner(0), sat_x.inner(1))\n .gpu_blocks (sat_x.outer(0), sat_x.full(0));\n\n sat_x.inter_schedule().compute_globally()\n .reorder_storage(sat_x.full(0), sat_x.tail(), sat_x.outer(0))\n .split (sat_x.full(0), ws, sat_x.inner())\n .unroll (sat_x.outer_scan())\n .split (sat_x.full(0), inter_tiles_per_warp)\n .reorder (sat_x.outer_scan(), sat_x.tail(), sat_x.full(0).split_var(), sat_x.inner(), sat_x.full(0))\n .gpu_threads (sat_x.inner(0), sat_x.full(0).split_var())\n .gpu_blocks (sat_x.full(0));\n }\n\n \/\/ slightly different schedule for y IIR filter\n {\n RecFilter sat_y = SAT2y;\n\n sat_y.intra_schedule().compute_locally()\n .reorder_storage(sat_y.full(0), sat_y.inner(), sat_y.outer(0))\n .split (sat_y.full(0), ws)\n .split (sat_y.inner(0), unroll_w)\n .unroll (sat_y.inner(0).split_var())\n .unroll (sat_y.inner_scan())\n .reorder (sat_y.inner_scan(), sat_y.inner(0).split_var(), sat_y.inner(0), sat_y.full(0).split_var(), sat_y.full(0), sat_y.outer(0))\n .gpu_threads(sat_y.full(0).split_var(), sat_y.inner(0))\n .gpu_blocks (sat_y.full(0), sat_y.outer(0));\n\n sat_y.inter_schedule().compute_globally()\n .reorder_storage(sat_y.full(0), sat_y.tail(), sat_y.outer(0))\n .split (sat_y.full(0), ws, sat_y.inner())\n .unroll (sat_y.outer_scan())\n .split (sat_y.full(0), inter_tiles_per_warp)\n .reorder (sat_y.outer_scan(), sat_y.tail(), sat_y.full(0).split_var(), sat_y.inner(), sat_y.full(0))\n .gpu_threads (sat_y.inner(0), sat_y.full(0).split_var())\n .gpu_blocks (sat_y.full(0));\n }\n }\n\n DoG.profile(iter);\n\n return 0;\n}\n\n\nExpr diff_op_x(Func F, Expr x, Expr y, int w, int h, int B, int c) {\n Expr e = (F(min(x+B,w-1), y)[c] - 2.0f*F(max(x-1,0), y)[c] + F(max(x-2*B-2,0), y)[c]) \/ float(2*B+1);\n return e;\n}\n\nExpr diff_op_y(Func F, Expr x, Expr y, int w, int h, int B, int c) {\n Expr e = (F(x, min(y+B,h-1))[c] - 2.0f*F(x, max(y-1,0))[c] + F(x, max(y-2*B-2,0))[c]) \/ float(2*B+1);\n return e;\n}\n\n\n\/\/ Difference operator to compute 2D xy single box filter from summed area table\nExpr diff_op_xy(Func F, Expr x, Expr y, int w, int h, int B) {\n Expr e =(1.0f * F(clamp(x+B+0, 0, w-1), clamp(y+B+0, 0, h-1)) +\n -1.0f * F(clamp(x+B+0, 0, w-1), clamp(y-B-1, 0, h-1)) +\n 1.0f * F(clamp(x-B-1, 0, w-1), clamp(y-B-1, 0, h-1)) +\n -1.0f * F(clamp(x-B-1, 0, w-1), clamp(y+B+0, 0, h-1))) \/ std::pow(2*B+1,2);\n return e;\n}\n<commit_msg>Code cleanup in difference of gaussian<commit_after>\/**\n * \\file diff_gauss.cpp\n *\n * Difference of Gaussians approximated using box filters\n * - convert RGB image to V or HSV\n * - compute first box filter\n * - compute x-y overlapped summed area table\n * - compute two different box filters using different box radii\n * - apply 2nd order x box filter on each output\n * - apply 2nd order y box filter on each output\n * - compute the difference between the two in the finite difference operator\n *\n * \\todo imporve numerical stability by dividing the image by 2r before computing\n * and integral image instead of computing the integral image and then dividing\n * during finite differencing\n *\/\n\n#include <iostream>\n#include <Halide.h>\n\n#include <recfilter.h>\n#include <iir_coeff.h>\n\nusing namespace Halide;\n\n\/\/\/ Difference operator to compute 1D x double box filter from 2nd order intergal image\nExpr diff_op_x(Func F, Expr x, Expr y, int w, int h, int B, int channel);\n\n\/\/\/ Difference operator to compute 1D y double box filter from 2nd order intergal image\nExpr diff_op_y(Func F, Expr x, Expr y, int w, int h, int B, int channel);\n\n\/\/\/ Difference operator to compute 2D xy single box filter from summed area table\nExpr diff_op_xy(Func F, Expr x, Expr y, int w, int h, int B);\n\n\/\/\/ Manual schedule for difference of Gaussians, this is not used in the benchmark\n\/\/\/ and only illustrates what the automatic scheduler does under the hood, these can\n\/\/\/ used instead of the auto schedules\nvoid manual_schedules(void);\n\nint main(int argc, char** argv) {\n Arguments args(argc, argv);\n\n int iter = args.iterations;\n int tile_width = args.block;\n int width = args.width;\n int height = args.width;\n\n \/\/ box filter radii for approximating Gaussians of given sigma with 3 iterations\n int sigma1 = 1.0f;\n int sigma2 = 2.0f;\n int B1 = gaussian_box_filter(sigma1, 3);\n int B2 = gaussian_box_filter(sigma2, 3);\n\n Image<int16_t> image = generate_random_image<int16_t>(width,height);\n\n \/\/ pad the image with zeros at borders\n int pad = std::max(3*B1+3, 3*B2+3);\n for (int k=0; k<image.channels(); k++) {\n for (int i=0; i<image.width(); i++) {\n for (int j=0; j<image.height(); j++) {\n if (i<pad || i>width-pad || j<pad || j>height-pad) {\n image(i,j,k) = 0.0f;\n }\n }\n }\n }\n\n RecFilterDim x(\"x\", width);\n RecFilterDim y(\"y\", height);\n\n \/\/ Compute V of HSV from RGB input\n RecFilter V(\"V\");\n \/\/ V(x,y) = Cast::make(type_of<float>(), max(image(x,y,0), max(image(x,y,1),image(x,y,2))));\n V(x,y) = Internal::Cast::make(type_of<float>(), image(x,y));\n\n \/\/ summed table from V channel\n RecFilter SAT(\"SAT\");\n SAT(x,y) = V.as_func()(x,y);\n SAT.add_filter(+x, {1.0f, 1.0f});\n SAT.add_filter(+y, {1.0f, 1.0f});\n\n \/\/ compute 1 iteration of box filters from this result\n RecFilter Box1(\"Box1\");\n Box1(x,y) = Tuple(diff_op_xy(SAT.as_func(), x, y, width, height, B1), diff_op_xy(SAT.as_func(), x, y, width, height, B2));\n\n \/\/ compute 2nd order x box filter, calculate the 2nd order intergal image first on both outputs\n RecFilter SAT2x(\"SAT2x\");\n SAT2x(x,y) = Tuple(Box1.as_func()(x,y)[0], Box1.as_func()(x,y)[1]);\n SAT2x.add_filter(+x, {1.0f, 2.0f, -1.0f});\n\n \/\/ complete the 2nd order x box filter by difference operator\n RecFilter Box2x(\"Box2x\");\n Box2x(x,y) = Tuple(diff_op_x(SAT2x.as_func(), x, y, width, height, B1, 0), diff_op_x(SAT2x.as_func(), x, y, width, height, B2, 1));\n\n \/\/ compute 2nd order y box filter, calculate the 2nd order intergal image first on both outputs\n RecFilter SAT2y(\"SAT2y\");\n SAT2y(x,y) = Tuple(Box2x.as_func()(x,y)[0], Box2x.as_func()(x,y)[1]);\n SAT2y.add_filter(+y, {1.0f, 2.0f, -1.0f});\n\n \/\/ complete 2nd order y box filter, subtract the result and take square as final result\n RecFilter DoG(\"DoG\");\n DoG(x,y) = diff_op_y(SAT2y.as_func(), x, y, width, height, B1, 0) - diff_op_y(SAT2y.as_func(), x, y, width, height, B2, 1);\n\n\n \/\/ -------------------------------------------------------------------------\n \/\/ tile all the intgral image functions\n\n SAT .split_all_dimensions(tile_width);\n SAT2x.split_all_dimensions(tile_width);\n SAT2y.split_all_dimensions(tile_width);\n\n \/\/ -------------------------------------------------------------------------\n \/\/ schedules\n\n SAT .gpu_auto_schedule(128);\n SAT2x.gpu_auto_schedule(128);\n SAT2y.gpu_auto_schedule(128);\n\n Box1 .gpu_auto_schedule(128, tile_width);\n Box2x.gpu_auto_schedule(128, tile_width);\n DoG .gpu_auto_schedule(128, tile_width);\n\n \/\/ -------------------------------------------------------------------------\n \/\/ compile and profile\n DoG.profile(iter);\n\n return EXIT_SUCCESS;\n}\n\nExpr diff_op_x(Func F, Expr x, Expr y, int w, int h, int B, int c) {\n Expr e = (F(min(x+B,w-1), y)[c] - 2.0f*F(max(x-1,0), y)[c] + F(max(x-2*B-2,0), y)[c]) \/ float(2*B+1);\n return e;\n}\n\nExpr diff_op_y(Func F, Expr x, Expr y, int w, int h, int B, int c) {\n Expr e = (F(x, min(y+B,h-1))[c] - 2.0f*F(x, max(y-1,0))[c] + F(x, max(y-2*B-2,0))[c]) \/ float(2*B+1);\n return e;\n}\n\n\n\/\/ Difference operator to compute 2D xy single box filter from summed area table\nExpr diff_op_xy(Func F, Expr x, Expr y, int w, int h, int B) {\n Expr e =(1.0f * F(clamp(x+B+0, 0, w-1), clamp(y+B+0, 0, h-1)) +\n -1.0f * F(clamp(x+B+0, 0, w-1), clamp(y-B-1, 0, h-1)) +\n 1.0f * F(clamp(x-B-1, 0, w-1), clamp(y-B-1, 0, h-1)) +\n -1.0f * F(clamp(x-B-1, 0, w-1), clamp(y+B+0, 0, h-1))) \/ std::pow(2*B+1,2);\n return e;\n}\n\n\nvoid manual_schedules(void) {\n int ws = 32;\n int unroll_w = ws\/4;\n int intra_tiles_per_warp = ws\/2;\n int inter_tiles_per_warp = 4;\n\n Var xo(\"xo\"), xi(\"xi\"), xii(\"xii\"), u(x.var());\n Var yo(\"yo\"), yi(\"yi\"), yii(\"yii\"), v(y.var());\n\n \/\/ first box filter\n {\n RecFilter F = SAT;\n\n F.intra_schedule(1).compute_locally()\n .reorder_storage(F.inner(), F.outer())\n .unroll (F.inner_scan())\n .split (F.inner(1), unroll_w)\n .unroll (F.inner(1).split_var())\n .reorder (F.inner_scan(), F.inner(1).split_var(), F.inner(), F.outer())\n .gpu_threads (F.inner(0), F.inner(1))\n .gpu_blocks (F.outer(0), F.outer(1));\n\n F.intra_schedule(2).compute_locally()\n .unroll (F.inner_scan())\n .split (F.outer(0), intra_tiles_per_warp)\n .reorder (F.inner(), F.inner_scan(), F.tail(), F.outer(0).split_var(), F.outer())\n .fuse (F.tail(), F.inner(0))\n .gpu_threads(F.tail(), F.outer(0).split_var())\n .gpu_blocks (F.outer(0), F.outer(1));\n\n F.inter_schedule().compute_globally()\n .reorder_storage(F.inner(), F.tail(), F.outer())\n .unroll (F.outer_scan())\n .split (F.outer(0), inter_tiles_per_warp)\n .reorder (F.outer_scan(), F.tail(), F.outer(0).split_var(), F.inner(), F.outer())\n .gpu_threads (F.inner(0), F.outer(0).split_var())\n .gpu_blocks (F.outer(0));\n }\n\n\n \/\/ second order 2 box filter along x\n {\n RecFilter sat_x = SAT2x;\n\n sat_x.intra_schedule().compute_locally()\n .split (sat_x.full(0), ws, sat_x.inner())\n .split (sat_x.inner(1), unroll_w)\n .unroll (sat_x.inner(1).split_var())\n .unroll (sat_x.inner_scan())\n .reorder (sat_x.inner_scan(), sat_x.inner(1).split_var(), sat_x.tail(), sat_x.inner(), sat_x.outer(), sat_x.full())\n .gpu_threads(sat_x.inner(0), sat_x.inner(1))\n .gpu_blocks (sat_x.outer(0), sat_x.full(0));\n\n sat_x.inter_schedule().compute_globally()\n .reorder_storage(sat_x.full(0), sat_x.tail(), sat_x.outer(0))\n .split (sat_x.full(0), ws, sat_x.inner())\n .unroll (sat_x.outer_scan())\n .split (sat_x.full(0), inter_tiles_per_warp)\n .reorder (sat_x.outer_scan(), sat_x.tail(), sat_x.full(0).split_var(), sat_x.inner(), sat_x.full(0))\n .gpu_threads (sat_x.inner(0), sat_x.full(0).split_var())\n .gpu_blocks (sat_x.full(0));\n }\n\n \/\/ slightly different schedule for y IIR filter\n {\n RecFilter sat_y = SAT2y;\n\n sat_y.intra_schedule().compute_locally()\n .reorder_storage(sat_y.full(0), sat_y.inner(), sat_y.outer(0))\n .split (sat_y.full(0), ws)\n .split (sat_y.inner(0), unroll_w)\n .unroll (sat_y.inner(0).split_var())\n .unroll (sat_y.inner_scan())\n .reorder (sat_y.inner_scan(), sat_y.inner(0).split_var(), sat_y.inner(0), sat_y.full(0).split_var(), sat_y.full(0), sat_y.outer(0))\n .gpu_threads(sat_y.full(0).split_var(), sat_y.inner(0))\n .gpu_blocks (sat_y.full(0), sat_y.outer(0));\n\n sat_y.inter_schedule().compute_globally()\n .reorder_storage(sat_y.full(0), sat_y.tail(), sat_y.outer(0))\n .split (sat_y.full(0), ws, sat_y.inner())\n .unroll (sat_y.outer_scan())\n .split (sat_y.full(0), inter_tiles_per_warp)\n .reorder (sat_y.outer_scan(), sat_y.tail(), sat_y.full(0).split_var(), sat_y.inner(), sat_y.full(0))\n .gpu_threads (sat_y.inner(0), sat_y.full(0).split_var())\n .gpu_blocks (sat_y.full(0));\n }\n\n {\n Box1.as_func().compute_root()\n .split (u, xo, xi, tile_width)\n .split (v, yo, yi, tile_width)\n .split (yi,yi, yii,8)\n .unroll (yii)\n .reorder(yii,xi,yi,xo,yo)\n .gpu (xo,yo,xi,yi);\n\n Box2x.as_func().compute_root()\n .split (u, xo, xi, tile_width)\n .split (v, yo, yi, tile_width)\n .split (yi,yi, yii, 8)\n .unroll (yii)\n .reorder(yii,xi,yi,xo,yo)\n .gpu (xo,yo,xi,yi);\n\n DoG.as_func().compute_root()\n .split (u, xo, xi, tile_width)\n .split (v, yo, yi, tile_width)\n .split (yi,yi, yii,8)\n .unroll (yii)\n .reorder(yii,xi,yi,xo,yo)\n .gpu (xo,yo,xi,yi);\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (C) 2016 ScyllaDB\n *\/\n\n\/*\n * This file is part of Scylla.\n *\n * Scylla is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * Scylla is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with Scylla. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n\n#pragma once\n\n#include <chrono>\n#include <unordered_map>\n#include <boost\/intrusive\/list.hpp>\n#include <boost\/intrusive\/unordered_set.hpp>\n\n#include <seastar\/core\/timer.hh>\n#include <seastar\/core\/gate.hh>\n\n#include \"utils\/exceptions.hh\"\n\nnamespace bi = boost::intrusive;\n\nnamespace utils {\n\/\/ Simple variant of the \"LoadingCache\" used for permissions in origin.\n\ntypedef lowres_clock loading_cache_clock_type;\ntypedef bi::list_base_hook<bi::link_mode<bi::auto_unlink>> auto_unlink_list_hook;\n\ntemplate<typename Tp, typename Key, typename Hash, typename EqualPred>\nclass timestamped_val : public auto_unlink_list_hook, public bi::unordered_set_base_hook<bi::store_hash<true>> {\npublic:\n typedef bi::list<timestamped_val, bi::constant_time_size<false>> lru_list_type;\n typedef Key key_type;\n typedef Tp value_type;\n\nprivate:\n std::experimental::optional<Tp> _opt_value;\n loading_cache_clock_type::time_point _loaded;\n loading_cache_clock_type::time_point _last_read;\n lru_list_type& _lru_list; \/\/\/ MRU item is at the front, LRU - at the back\n Key _key;\n\npublic:\n struct key_eq {\n bool operator()(const Key& k, const timestamped_val& c) const {\n return EqualPred()(k, c.key());\n }\n\n bool operator()(const timestamped_val& c, const Key& k) const {\n return EqualPred()(c.key(), k);\n }\n };\n\n timestamped_val(lru_list_type& lru_list, const Key& key)\n : _loaded(loading_cache_clock_type::now())\n , _last_read(_loaded)\n , _lru_list(lru_list)\n , _key(key) {}\n\n timestamped_val(lru_list_type& lru_list, Key&& key)\n : _loaded(loading_cache_clock_type::now())\n , _last_read(_loaded)\n , _lru_list(lru_list)\n , _key(std::move(key)) {}\n\n timestamped_val(const timestamped_val&) = default;\n timestamped_val(timestamped_val&&) = default;\n\n \/\/ Make sure copy\/move-assignments don't go through the template below\n timestamped_val& operator=(const timestamped_val&) = default;\n timestamped_val& operator=(timestamped_val&) = default;\n timestamped_val& operator=(timestamped_val&&) = default;\n\n template <typename U>\n timestamped_val& operator=(U&& new_val) {\n _opt_value = std::forward<U>(new_val);\n _loaded = loading_cache_clock_type::now();\n return *this;\n }\n\n const Tp& value() {\n _last_read = loading_cache_clock_type::now();\n touch();\n return _opt_value.value();\n }\n\n explicit operator bool() const noexcept {\n return bool(_opt_value);\n }\n\n loading_cache_clock_type::time_point last_read() const noexcept {\n return _last_read;\n }\n\n loading_cache_clock_type::time_point loaded() const noexcept {\n return _loaded;\n }\n\n const Key& key() const {\n return _key;\n }\n\n friend bool operator==(const timestamped_val& a, const timestamped_val& b){\n return EqualPred()(a.key(), b.key());\n }\n\n friend std::size_t hash_value(const timestamped_val& v) {\n return Hash()(v.key());\n }\n\nprivate:\n \/\/\/ Set this item as the most recently used item.\n \/\/\/ The MRU item is going to be at the front of the _lru_list, the LRU item - at the back.\n void touch() noexcept {\n auto_unlink_list_hook::unlink();\n _lru_list.push_front(*this);\n }\n};\n\nclass shared_mutex {\nprivate:\n lw_shared_ptr<semaphore> _mutex_ptr;\n\npublic:\n shared_mutex() : _mutex_ptr(make_lw_shared<semaphore>(1)) {}\n semaphore& get() const noexcept {\n return *_mutex_ptr;\n }\n};\n\ntemplate<typename Key,\n typename Tp,\n typename Hash = std::hash<Key>,\n typename EqualPred = std::equal_to<Key>,\n typename Alloc = std::allocator<timestamped_val<Tp, Key, Hash, EqualPred>>,\n typename SharedMutexMapAlloc = std::allocator<std::pair<const Key, shared_mutex>>>\nclass loading_cache {\nprivate:\n typedef timestamped_val<Tp, Key, Hash, EqualPred> ts_value_type;\n typedef bi::unordered_set<ts_value_type, bi::power_2_buckets<true>, bi::compare_hash<true>> set_type;\n typedef std::unordered_map<Key, shared_mutex, Hash, EqualPred, SharedMutexMapAlloc> write_mutex_map_type;\n typedef typename ts_value_type::lru_list_type lru_list_type;\n typedef typename set_type::bucket_traits bi_set_bucket_traits;\n\n static constexpr int initial_num_buckets = 256;\n static constexpr int max_num_buckets = 1024 * 1024;\n\npublic:\n typedef Tp value_type;\n typedef Key key_type;\n typedef typename set_type::iterator iterator;\n\n template<typename Func>\n loading_cache(size_t max_size, std::chrono::milliseconds expiry, std::chrono::milliseconds refresh, logging::logger& logger, Func&& load)\n : _buckets(initial_num_buckets)\n , _set(bi_set_bucket_traits(_buckets.data(), _buckets.size()))\n , _max_size(max_size)\n , _expiry(expiry)\n , _refresh(refresh)\n , _logger(logger)\n , _load(std::forward<Func>(load)) {\n\n \/\/ If expiration period is zero - caching is disabled\n if (!caching_enabled()) {\n return;\n }\n\n \/\/ Sanity check: if expiration period is given then non-zero refresh period and maximal size are required\n if (_refresh == std::chrono::milliseconds(0) || _max_size == 0) {\n throw exceptions::configuration_exception(\"loading_cache: caching is enabled but refresh period and\/or max_size are zero\");\n }\n\n _timer_period = std::min(_expiry, _refresh);\n _timer.set_callback([this] { on_timer(); });\n _timer.arm(_timer_period);\n }\n\n ~loading_cache() {\n _set.clear_and_dispose([] (ts_value_type* ptr) { loading_cache::destroy_ts_value(ptr); });\n }\n\n future<Tp> get(const Key& k) {\n \/\/ If caching is disabled - always load in the foreground\n if (!caching_enabled()) {\n return _load(k);\n }\n\n \/\/ If the key is not in the cache yet, then find_or_create() is going to\n \/\/ create a new uninitialized value in the map. If the value is already\n \/\/ in the cache (the fast path) simply return the value. Otherwise, take\n \/\/ the mutex and try to load the value (the slow path).\n iterator ts_value_it = find_or_create(k);\n if (*ts_value_it) {\n return make_ready_future<Tp>(ts_value_it->value());\n } else {\n return slow_load(k);\n }\n }\n\n future<> stop() {\n return _timer_reads_gate.close().finally([this] { _timer.cancel(); });\n }\n\nprivate:\n bool caching_enabled() const {\n return _expiry != std::chrono::milliseconds(0);\n }\n\n \/\/\/ Look for the entry with the given key. It it doesn't exist - create a new one and add it to the _set.\n \/\/\/\n \/\/\/ \\param k The key to look for\n \/\/\/\n \/\/\/ \\return An iterator to the value with the given key (always dirrerent from _set.end())\n template <typename KeyType>\n iterator find_or_create(KeyType&& k) {\n iterator i = _set.find(k, Hash(), typename ts_value_type::key_eq());\n if (i == _set.end()) {\n ts_value_type* new_ts_val = Alloc().allocate(1);\n new(new_ts_val) ts_value_type(_lru_list, std::forward<KeyType>(k));\n auto p = _set.insert(*new_ts_val);\n i = p.first;\n }\n\n return i;\n }\n\n static void destroy_ts_value(ts_value_type* val) {\n val->~ts_value_type();\n Alloc().deallocate(val, 1);\n }\n\n future<Tp> slow_load(const Key& k) {\n \/\/ If the key is not in the cache yet, then _write_mutex_map[k] is going\n \/\/ to create a new value with the initialized mutex. The mutex is going\n \/\/ to serialize the producers and only the first one is going to\n \/\/ actually issue a load operation and initialize the value with the\n \/\/ received result. The rest are going to see (and read) the initialized\n \/\/ value when they enter the critical section.\n shared_mutex sm = _write_mutex_map[k];\n return with_semaphore(sm.get(), 1, [this, k] {\n iterator ts_value_it = find_or_create(k);\n if (*ts_value_it) {\n return make_ready_future<Tp>(ts_value_it->value());\n }\n _logger.trace(\"{}: storing the value for the first time\", k);\n return _load(k).then([this, k] (Tp t) {\n \/\/ we have to \"re-read\" the _set here because the value may have been evicted by now\n iterator ts_value_it = find_or_create(std::move(k));\n *ts_value_it = std::move(t);\n return make_ready_future<Tp>(ts_value_it->value());\n });\n }).finally([sm] {});\n }\n\n future<> reload(ts_value_type& ts_val) {\n return _load(ts_val.key()).then_wrapped([this, &ts_val] (auto&& f) {\n \/\/ The exceptions are related to the load operation itself.\n \/\/ We should ignore them for the background reads - if\n \/\/ they persist the value will age and will be reloaded in\n \/\/ the forground. If the foreground READ fails the error\n \/\/ will be propagated up to the user and will fail the\n \/\/ corresponding query.\n try {\n ts_val = f.get0();\n } catch (std::exception& e) {\n _logger.debug(\"{}: reload failed: {}\", ts_val.key(), e.what());\n } catch (...) {\n _logger.debug(\"{}: reload failed: unknown error\", ts_val.key());\n }\n });\n }\n\n void erase(iterator it) {\n _set.erase_and_dispose(it, [] (ts_value_type* ptr) { loading_cache::destroy_ts_value(ptr); });\n \/\/ no need to delete the item from _lru_list - it's auto-deleted\n }\n\n void drop_expired() {\n auto now = loading_cache_clock_type::now();\n _lru_list.remove_and_dispose_if([now, this] (const ts_value_type& v) {\n using namespace std::chrono;\n \/\/ An entry should be discarded if it hasn't been reloaded for too long or nobody cares about it anymore\n auto since_last_read = now - v.last_read();\n auto since_loaded = now - v.loaded();\n if (_expiry < since_last_read || _expiry < since_loaded) {\n _logger.trace(\"drop_expired(): {}: dropping the entry: _expiry {}, ms passed since: loaded {} last_read {}\", v.key(), _expiry.count(), duration_cast<milliseconds>(since_loaded).count(), duration_cast<milliseconds>(since_last_read).count());\n return true;\n }\n return false;\n }, [this] (ts_value_type* p) {\n erase(_set.iterator_to(*p));\n });\n }\n\n \/\/ Shrink the cache to the _max_size discarding the least recently used items\n void shrink() {\n if (_set.size() > _max_size) {\n auto num_items_to_erase = _set.size() - _max_size;\n for (size_t i = 0; i < num_items_to_erase; ++i) {\n using namespace std::chrono;\n ts_value_type& ts_val = *_lru_list.rbegin();\n _logger.trace(\"shrink(): {}: dropping the entry: ms since last_read {}\", ts_val.key(), duration_cast<milliseconds>(loading_cache_clock_type::now() - ts_val.last_read()).count());\n erase(_set.iterator_to(ts_val));\n }\n }\n }\n\n void rehash() {\n size_t new_buckets_count = 0;\n\n \/\/ Don't grow or shrink too fast even if there is a steep drop\/growth in the number of elements in the set.\n \/\/ Exponential growth\/backoff should be good enough.\n \/\/\n \/\/ Try to keep the load factor between 0.25 and 1.0.\n if (_set.size() < _current_buckets_count \/ 4) {\n new_buckets_count = _current_buckets_count \/ 4;\n } else if (_set.size() > _current_buckets_count) {\n new_buckets_count = _current_buckets_count * 2;\n }\n\n if (new_buckets_count < initial_num_buckets || new_buckets_count > max_num_buckets) {\n return;\n }\n\n std::vector<typename set_type::bucket_type> new_buckets(new_buckets_count);\n _set.rehash(bi_set_bucket_traits(new_buckets.data(), new_buckets.size()));\n _logger.trace(\"rehash(): buckets count changed: {} -> {}\", _current_buckets_count, new_buckets_count);\n\n _buckets.swap(new_buckets);\n _current_buckets_count = new_buckets_count;\n }\n\n void on_timer() {\n _logger.trace(\"on_timer(): start\");\n\n auto timer_start_tp = loading_cache_clock_type::now();\n\n \/\/ Clear all cached mutexes\n _write_mutex_map.clear();\n\n \/\/ Clean up items that were not touched for the whole _expiry period.\n drop_expired();\n\n \/\/ Remove the least recently used items if map is too big.\n shrink();\n\n \/\/ check if rehashing is needed and do it if it is.\n rehash();\n\n \/\/ Reload all those which vlaue needs to be reloaded.\n with_gate(_timer_reads_gate, [this, timer_start_tp] {\n return parallel_for_each(_set.begin(), _set.end(), [this, curr_time = timer_start_tp] (auto& ts_val) {\n _logger.trace(\"on_timer(): {}: checking the value age\", ts_val.key());\n if (ts_val && ts_val.loaded() + _refresh < curr_time) {\n _logger.trace(\"on_timer(): {}: reloading the value\", ts_val.key());\n return this->reload(ts_val);\n }\n return now();\n }).finally([this, timer_start_tp] {\n _logger.trace(\"on_timer(): rearming\");\n _timer.arm(timer_start_tp + _timer_period);\n });\n });\n }\n\n std::vector<typename set_type::bucket_type> _buckets;\n size_t _current_buckets_count = initial_num_buckets;\n set_type _set;\n write_mutex_map_type _write_mutex_map;\n lru_list_type _lru_list;\n size_t _max_size;\n std::chrono::milliseconds _expiry;\n std::chrono::milliseconds _refresh;\n loading_cache_clock_type::duration _timer_period;\n logging::logger& _logger;\n std::function<future<Tp>(const Key&)> _load;\n timer<loading_cache_clock_type> _timer;\n seastar::gate _timer_reads_gate;\n};\n\n}\n\n<commit_msg>utils::loading_cache: rework on top of utils::loading_shared_values<commit_after>\/*\n * Copyright (C) 2016 ScyllaDB\n *\/\n\n\/*\n * This file is part of Scylla.\n *\n * Scylla is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * Scylla is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with Scylla. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n\n#pragma once\n\n#include <chrono>\n#include <unordered_map>\n#include <boost\/intrusive\/list.hpp>\n#include <boost\/intrusive\/unordered_set.hpp>\n\n#include <seastar\/core\/timer.hh>\n#include <seastar\/core\/gate.hh>\n\n#include \"exceptions\/exceptions.hh\"\n#include \"utils\/loading_shared_values.hh\"\n#include \"log.hh\"\n\nnamespace bi = boost::intrusive;\n\nnamespace utils {\n\nusing loading_cache_clock_type = seastar::lowres_clock;\nusing auto_unlink_list_hook = bi::list_base_hook<bi::link_mode<bi::auto_unlink>>;\n\ntemplate<typename Tp, typename Key, typename Hash, typename EqualPred, typename LoadingSharedValuesStats>\nclass timestamped_val {\npublic:\n using value_type = Tp;\n using loading_values_type = typename utils::loading_shared_values<Key, timestamped_val, Hash, EqualPred, LoadingSharedValuesStats, 256>;\n class lru_entry;\n\nprivate:\n value_type _value;\n loading_cache_clock_type::time_point _loaded;\n loading_cache_clock_type::time_point _last_read;\n lru_entry* _lru_entry_ptr = nullptr; \/\/\/ MRU item is at the front, LRU - at the back\n\npublic:\n timestamped_val(value_type val)\n : _value(std::move(val))\n , _loaded(loading_cache_clock_type::now())\n , _last_read(_loaded)\n {}\n timestamped_val(timestamped_val&&) = default;\n\n timestamped_val& operator=(value_type new_val) {\n assert(_lru_entry_ptr);\n\n _value = std::move(new_val);\n _loaded = loading_cache_clock_type::now();\n return *this;\n }\n\n value_type& value() noexcept {\n touch();\n return _value;\n }\n\n loading_cache_clock_type::time_point last_read() const noexcept {\n return _last_read;\n }\n\n loading_cache_clock_type::time_point loaded() const noexcept {\n return _loaded;\n }\n\n bool ready() const noexcept {\n return _lru_entry_ptr;\n }\n\nprivate:\n void touch() noexcept {\n assert(_lru_entry_ptr);\n _last_read = loading_cache_clock_type::now();\n _lru_entry_ptr->touch();\n }\n\n void set_anchor_back_reference(lru_entry* lru_entry_ptr) noexcept {\n _lru_entry_ptr = lru_entry_ptr;\n }\n};\n\n\/\/\/ \\brief This is and LRU list entry which is also an anchor for a loading_cache value.\ntemplate<typename Tp, typename Key, typename Hash, typename EqualPred, typename LoadingSharedValuesStats>\nclass timestamped_val<Tp, Key, Hash, EqualPred, LoadingSharedValuesStats>::lru_entry : public auto_unlink_list_hook {\nprivate:\n using ts_value_type = timestamped_val<Tp, Key, Hash, EqualPred, LoadingSharedValuesStats>;\n using loading_values_type = typename ts_value_type::loading_values_type;\n\npublic:\n using lru_list_type = bi::list<lru_entry, bi::constant_time_size<false>>;\n using timestamped_val_ptr = typename loading_values_type::entry_ptr;\n\nprivate:\n timestamped_val_ptr _ts_val_ptr;\n lru_list_type& _lru_list;\n\npublic:\n lru_entry(timestamped_val_ptr ts_val, lru_list_type& lru_list)\n : _ts_val_ptr(std::move(ts_val))\n , _lru_list(lru_list)\n {\n _ts_val_ptr->set_anchor_back_reference(this);\n }\n\n ~lru_entry() {\n _ts_val_ptr->set_anchor_back_reference(nullptr);\n }\n\n \/\/\/ Set this item as the most recently used item.\n \/\/\/ The MRU item is going to be at the front of the _lru_list, the LRU item - at the back.\n void touch() noexcept {\n auto_unlink_list_hook::unlink();\n _lru_list.push_front(*this);\n }\n\n const Key& key() const noexcept {\n return loading_values_type::to_key(_ts_val_ptr);\n }\n\n timestamped_val& timestamped_value() noexcept { return *_ts_val_ptr; }\n const timestamped_val& timestamped_value() const noexcept { return *_ts_val_ptr; }\n timestamped_val_ptr timestamped_value_ptr() noexcept { return _ts_val_ptr; }\n};\n\nenum class loading_cache_reload_enabled { no, yes };\n\ntemplate<typename Key,\n typename Tp,\n typename Hash = std::hash<Key>,\n typename EqualPred = std::equal_to<Key>,\n typename LoadingSharedValuesStats = utils::do_nothing_loading_shared_values_stats,\n typename Alloc = std::allocator<typename timestamped_val<Tp, Key, Hash, EqualPred, LoadingSharedValuesStats>::lru_entry>>\nclass loading_cache {\nprivate:\n using ts_value_type = timestamped_val<Tp, Key, Hash, EqualPred, LoadingSharedValuesStats>;\n using loading_values_type = typename ts_value_type::loading_values_type;\n using timestamped_val_ptr = typename loading_values_type::entry_ptr;\n using ts_value_lru_entry = typename ts_value_type::lru_entry;\n using set_iterator = typename loading_values_type::iterator;\n using lru_list_type = typename ts_value_lru_entry::lru_list_type;\n\npublic:\n using value_type = Tp;\n using key_type = Key;\n\n\n template<typename Func>\n loading_cache(size_t max_size, std::chrono::milliseconds expiry, std::chrono::milliseconds refresh, logging::logger& logger, Func&& load)\n : _max_size(max_size)\n , _expiry(expiry)\n , _refresh(refresh)\n , _logger(logger)\n , _load(std::forward<Func>(load)) {\n\n \/\/ If expiration period is zero - caching is disabled\n if (!caching_enabled()) {\n return;\n }\n\n \/\/ Sanity check: if expiration period is given then non-zero refresh period and maximal size are required\n if (_refresh == std::chrono::milliseconds(0) || _max_size == 0) {\n throw exceptions::configuration_exception(\"loading_cache: caching is enabled but refresh period and\/or max_size are zero\");\n }\n\n _timer_period = std::min(_expiry, _refresh);\n _timer.set_callback([this] { on_timer(); });\n _timer.arm(_timer_period);\n }\n\n ~loading_cache() {\n _lru_list.erase_and_dispose(_lru_list.begin(), _lru_list.end(), [] (ts_value_lru_entry* ptr) { loading_cache::destroy_ts_value(ptr); });\n }\n\n future<Tp> get(const Key& k) {\n \/\/ If caching is disabled - always load in the foreground\n if (!caching_enabled()) {\n return _load(k);\n }\n\n return _loading_values.get_or_load(k, [this] (const Key& k) {\n return _load(k).then([this] (value_type val) {\n return ts_value_type(std::move(val));\n });\n }).then([this, k] (timestamped_val_ptr ts_val_ptr) {\n \/\/ check again since it could have already been inserted and initialized\n if (!ts_val_ptr->ready()) {\n _logger.trace(\"{}: storing the value for the first time\", k);\n\n ts_value_lru_entry* new_lru_entry = Alloc().allocate(1);\n new(new_lru_entry) ts_value_lru_entry(std::move(ts_val_ptr), _lru_list);\n\n \/\/ This will \"touch\" the entry and add it to the LRU list.\n return make_ready_future<Tp>(new_lru_entry->timestamped_value_ptr()->value());\n }\n\n return make_ready_future<Tp>(ts_val_ptr->value());\n });\n }\n\n future<> stop() {\n return _timer_reads_gate.close().finally([this] { _timer.cancel(); });\n }\n\nprivate:\n set_iterator set_find(const Key& k) noexcept {\n set_iterator it = _loading_values.find(k);\n set_iterator end_it = set_end();\n\n if (it == end_it || !it->ready()) {\n return end_it;\n }\n return it;\n }\n\n set_iterator set_end() noexcept {\n return _loading_values.end();\n }\n\n set_iterator set_begin() noexcept {\n return _loading_values.begin();\n }\n\n bool caching_enabled() const {\n return _expiry != std::chrono::milliseconds(0);\n }\n\n static void destroy_ts_value(ts_value_lru_entry* val) {\n val->~ts_value_lru_entry();\n Alloc().deallocate(val, 1);\n }\n\n future<> reload(ts_value_lru_entry& lru_entry) {\n return _load(lru_entry.key()).then_wrapped([this, key = lru_entry.key()] (auto&& f) mutable {\n \/\/ if the entry has been evicted by now - simply end here\n set_iterator it = set_find(key);\n if (it == set_end()) {\n _logger.trace(\"{}: entry was dropped during the reload\", key);\n return make_ready_future<>();\n }\n\n \/\/ The exceptions are related to the load operation itself.\n \/\/ We should ignore them for the background reads - if\n \/\/ they persist the value will age and will be reloaded in\n \/\/ the forground. If the foreground READ fails the error\n \/\/ will be propagated up to the user and will fail the\n \/\/ corresponding query.\n try {\n *it = f.get0();\n } catch (std::exception& e) {\n _logger.debug(\"{}: reload failed: {}\", key, e.what());\n } catch (...) {\n _logger.debug(\"{}: reload failed: unknown error\", key);\n }\n\n return make_ready_future<>();\n });\n }\n\n void drop_expired() {\n auto now = loading_cache_clock_type::now();\n _lru_list.remove_and_dispose_if([now, this] (const ts_value_lru_entry& lru_entry) {\n using namespace std::chrono;\n \/\/ An entry should be discarded if it hasn't been reloaded for too long or nobody cares about it anymore\n const ts_value_type& v = lru_entry.timestamped_value();\n auto since_last_read = now - v.last_read();\n auto since_loaded = now - v.loaded();\n if (_expiry < since_last_read || _expiry < since_loaded) {\n _logger.trace(\"drop_expired(): {}: dropping the entry: _expiry {}, ms passed since: loaded {} last_read {}\", lru_entry.key(), _expiry.count(), duration_cast<milliseconds>(since_loaded).count(), duration_cast<milliseconds>(since_last_read).count());\n return true;\n }\n return false;\n }, [this] (ts_value_lru_entry* p) {\n loading_cache::destroy_ts_value(p);\n });\n }\n\n \/\/ Shrink the cache to the _max_size discarding the least recently used items\n void shrink() {\n if (_loading_values.size() > _max_size) {\n auto num_items_to_erase = _loading_values.size() - _max_size;\n for (size_t i = 0; i < num_items_to_erase; ++i) {\n using namespace std::chrono;\n auto it = _lru_list.rbegin();\n \/\/ This may happen if there are pending insertions into the loading_shared_values that hasn't been yet finalized.\n \/\/ In this case the number of elements in the _lru_list will be less than the _loading_values.size().\n if (_lru_list.rbegin() == _lru_list.rend()) {\n return;\n }\n ts_value_lru_entry& lru_entry = *it;\n _logger.trace(\"shrink(): {}: dropping the entry: ms since last_read {}\", lru_entry.key(), duration_cast<milliseconds>(loading_cache_clock_type::now() - lru_entry.timestamped_value().last_read()).count());\n loading_cache::destroy_ts_value(&lru_entry);\n }\n }\n }\n\n \/\/ Try to bring the load factors of the _loading_values into a known range.\n void periodic_rehash() noexcept {\n try {\n _loading_values.rehash();\n } catch (...) {\n \/\/ if rehashing fails - continue with the current buckets array\n }\n }\n\n void on_timer() {\n _logger.trace(\"on_timer(): start\");\n\n \/\/ Clean up items that were not touched for the whole _expiry period.\n drop_expired();\n\n \/\/ Remove the least recently used items if map is too big.\n shrink();\n\n \/\/ check if rehashing is needed and do it if it is.\n periodic_rehash();\n\n \/\/ Reload all those which vlaue needs to be reloaded.\n with_gate(_timer_reads_gate, [this] {\n return parallel_for_each(_lru_list.begin(), _lru_list.end(), [this] (ts_value_lru_entry& lru_entry) {\n _logger.trace(\"on_timer(): {}: checking the value age\", lru_entry.key());\n if (lru_entry.timestamped_value().loaded() + _refresh < loading_cache_clock_type::now()) {\n _logger.trace(\"on_timer(): {}: reloading the value\", lru_entry.key());\n return this->reload(lru_entry);\n }\n return now();\n }).finally([this] {\n _logger.trace(\"on_timer(): rearming\");\n _timer.arm(loading_cache_clock_type::now() + _timer_period);\n });\n });\n }\n\n loading_values_type _loading_values;\n lru_list_type _lru_list;\n size_t _max_size = 0;\n std::chrono::milliseconds _expiry;\n std::chrono::milliseconds _refresh;\n loading_cache_clock_type::duration _timer_period;\n logging::logger& _logger;\n std::function<future<Tp>(const Key&)> _load;\n timer<loading_cache_clock_type> _timer;\n seastar::gate _timer_reads_gate;\n};\n\n}\n\n<|endoftext|>"} {"text":"<commit_before>\n\/*\n * Copyright (C) 2015 ScyllaDB\n *\/\n\n\/*\n * This file is part of Scylla.\n *\n * Scylla is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * Scylla is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with Scylla. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n\n#pragma once\n\n#include <stdint.h>\n#include <memory>\n#include \"bytes.hh\"\n#include \"utils\/allocation_strategy.hh\"\n#include <seastar\/core\/unaligned.hh>\n#include <unordered_map>\n#include <type_traits>\n\nstruct blob_storage {\n struct [[gnu::packed]] ref_type {\n blob_storage* ptr;\n\n ref_type() {}\n ref_type(blob_storage* ptr) : ptr(ptr) {}\n operator blob_storage*() const { return ptr; }\n blob_storage* operator->() const { return ptr; }\n blob_storage& operator*() const { return *ptr; }\n };\n using size_type = uint32_t;\n using char_type = bytes_view::value_type;\n\n ref_type* backref;\n size_type size;\n size_type frag_size;\n ref_type next;\n char_type data[];\n\n blob_storage(ref_type* backref, size_type size, size_type frag_size) noexcept\n : backref(backref)\n , size(size)\n , frag_size(frag_size)\n , next(nullptr)\n {\n *backref = this;\n }\n\n blob_storage(blob_storage&& o) noexcept\n : backref(o.backref)\n , size(o.size)\n , frag_size(o.frag_size)\n , next(o.next)\n {\n *backref = this;\n o.next = nullptr;\n if (next) {\n next->backref = &next;\n }\n memcpy(data, o.data, frag_size);\n }\n} __attribute__((packed));\n\n\/\/ A managed version of \"bytes\" (can be used with LSA).\nclass managed_bytes {\n struct linearization_context {\n unsigned _nesting = 0;\n \/\/ Map from first blob_storage address to linearized version\n \/\/ We use the blob_storage address to be insentive to moving\n \/\/ a managed_bytes object.\n std::unordered_map<const blob_storage*, std::unique_ptr<bytes_view::value_type[]>> _state;\n void enter() {\n ++_nesting;\n }\n void leave() {\n if (!--_nesting) {\n _state.clear();\n }\n }\n void forget(const blob_storage* p) noexcept;\n };\n static thread_local linearization_context _linearization_context;\npublic:\n struct linearization_context_guard {\n linearization_context_guard() {\n _linearization_context.enter();\n }\n ~linearization_context_guard() {\n _linearization_context.leave();\n }\n };\nprivate:\n static constexpr size_t max_inline_size = 15;\n struct small_blob {\n bytes_view::value_type data[max_inline_size];\n int8_t size; \/\/ -1 -> use blob_storage\n };\n union u {\n u() {}\n ~u() {}\n blob_storage::ref_type ptr;\n small_blob small;\n } _u;\n static_assert(sizeof(small_blob) > sizeof(blob_storage*), \"inline size too small\");\nprivate:\n bool external() const {\n return _u.small.size < 0;\n }\n size_t max_seg(allocation_strategy& alctr) {\n return alctr.preferred_max_contiguous_allocation() - sizeof(blob_storage);\n }\n void free_chain(blob_storage* p) noexcept {\n if (p->next && _linearization_context._nesting) {\n _linearization_context.forget(p);\n }\n auto& alctr = current_allocator();\n while (p) {\n auto n = p->next;\n alctr.destroy(p);\n p = n;\n }\n }\n const bytes_view::value_type* read_linearize() const {\n if (!external()) {\n return _u.small.data;\n } else if (!_u.ptr->next) {\n return _u.ptr->data;\n } else {\n return do_linearize();\n }\n }\n bytes_view::value_type& value_at_index(blob_storage::size_type index) {\n if (!external()) {\n return _u.small.data[index];\n }\n blob_storage* a = _u.ptr;\n while (index >= a->frag_size) {\n index -= a->frag_size;\n a = a->next;\n }\n return a->data[index];\n }\n const bytes_view::value_type* do_linearize() const;\npublic:\n using size_type = blob_storage::size_type;\n struct initialized_later {};\n\n managed_bytes() {\n _u.small.size = 0;\n }\n\n managed_bytes(const blob_storage::char_type* ptr, size_type size)\n : managed_bytes(bytes_view(ptr, size)) {}\n\n managed_bytes(const bytes& b) : managed_bytes(static_cast<bytes_view>(b)) {}\n\n managed_bytes(initialized_later, size_type size) {\n if (size <= max_inline_size) {\n _u.small.size = size;\n } else {\n _u.small.size = -1;\n auto& alctr = current_allocator();\n auto maxseg = max_seg(alctr);\n auto now = std::min(size_t(size), maxseg);\n void* p = alctr.alloc(&standard_migrator<blob_storage>::object,\n sizeof(blob_storage) + now, alignof(blob_storage));\n auto first = new (p) blob_storage(&_u.ptr, size, now);\n auto last = first;\n size -= now;\n try {\n while (size) {\n auto now = std::min(size_t(size), maxseg);\n void* p = alctr.alloc(&standard_migrator<blob_storage>::object,\n sizeof(blob_storage) + now, alignof(blob_storage));\n last = new (p) blob_storage(&last->next, 0, now);\n size -= now;\n }\n } catch (...) {\n free_chain(first);\n throw;\n }\n }\n }\n\n managed_bytes(bytes_view v) : managed_bytes(initialized_later(), v.size()) {\n if (!external()) {\n std::copy(v.begin(), v.end(), _u.small.data);\n return;\n }\n auto p = v.data();\n auto s = v.size();\n auto b = _u.ptr;\n while (s) {\n memcpy(b->data, p, b->frag_size);\n p += b->frag_size;\n s -= b->frag_size;\n b = b->next;\n }\n assert(!b);\n }\n\n managed_bytes(std::initializer_list<bytes::value_type> b) : managed_bytes(b.begin(), b.size()) {}\n\n ~managed_bytes() noexcept {\n if (external()) {\n free_chain(_u.ptr);\n }\n }\n\n managed_bytes(const managed_bytes& o) : managed_bytes(initialized_later(), o.size()) {\n if (!external()) {\n memcpy(data(), o.data(), size());\n return;\n }\n auto s = size();\n const blob_storage::ref_type* next_src = &o._u.ptr;\n blob_storage* blob_src = nullptr;\n size_type size_src = 0;\n size_type offs_src = 0;\n blob_storage::ref_type* next_dst = &_u.ptr;\n blob_storage* blob_dst = nullptr;\n size_type size_dst = 0;\n size_type offs_dst = 0;\n while (s) {\n if (!size_src) {\n blob_src = *next_src;\n next_src = &blob_src->next;\n size_src = blob_src->frag_size;\n offs_src = 0;\n }\n if (!size_dst) {\n blob_dst = *next_dst;\n next_dst = &blob_dst->next;\n size_dst = blob_dst->frag_size;\n offs_dst = 0;\n }\n auto now = std::min(size_src, size_dst);\n memcpy(blob_dst->data + offs_dst, blob_src->data + offs_src, now);\n s -= now;\n offs_src += now; size_src -= now;\n offs_dst += now; size_dst -= now;\n }\n assert(size_src == 0 && size_dst == 0);\n }\n\n managed_bytes(managed_bytes&& o) noexcept\n : _u(o._u)\n {\n if (external()) {\n if (_u.ptr) {\n _u.ptr->backref = &_u.ptr;\n }\n }\n o._u.small.size = 0;\n }\n\n managed_bytes& operator=(managed_bytes&& o) noexcept {\n if (this != &o) {\n this->~managed_bytes();\n new (this) managed_bytes(std::move(o));\n }\n return *this;\n }\n\n managed_bytes& operator=(const managed_bytes& o) {\n if (this != &o) {\n managed_bytes tmp(o);\n this->~managed_bytes();\n new (this) managed_bytes(std::move(tmp));\n }\n return *this;\n }\n\n bool operator==(const managed_bytes& o) const {\n if (size() != o.size()) {\n return false;\n }\n if (!external()) {\n return bytes_view(*this) == bytes_view(o);\n } else {\n auto a = _u.ptr;\n auto a_data = a->data;\n auto a_remain = a->frag_size;\n a = a->next;\n auto b = o._u.ptr;\n auto b_data = b->data;\n auto b_remain = b->frag_size;\n b = b->next;\n while (a_remain || b_remain) {\n auto now = std::min(a_remain, b_remain);\n if (bytes_view(a_data, now) != bytes_view(b_data, now)) {\n return false;\n }\n a_data += now;\n a_remain -= now;\n if (!a_remain && a) {\n a_data = a->data;\n a_remain = a->frag_size;\n a = a->next;\n }\n b_data += now;\n b_remain -= now;\n if (!b_remain && b) {\n b_data = b->data;\n b_remain = b->frag_size;\n b = b->next;\n }\n }\n return true;\n }\n }\n\n bool operator!=(const managed_bytes& o) const {\n return !(*this == o);\n }\n\n operator bytes_view() const {\n return { data(), size() };\n }\n\n bool is_fragmented() const {\n return external() && _u.ptr->next;\n }\n\n operator bytes_mutable_view() {\n assert(!is_fragmented());\n return { data(), size() };\n };\n\n bytes_view::value_type& operator[](size_type index) {\n return value_at_index(index);\n }\n\n const bytes_view::value_type& operator[](size_type index) const {\n return const_cast<const bytes_view::value_type&>(\n const_cast<managed_bytes*>(this)->value_at_index(index));\n }\n\n size_type size() const {\n if (external()) {\n return _u.ptr->size;\n } else {\n return _u.small.size;\n }\n }\n\n const blob_storage::char_type* begin() const {\n return data();\n }\n\n const blob_storage::char_type* end() const {\n return data() + size();\n }\n\n blob_storage::char_type* begin() {\n return data();\n }\n\n blob_storage::char_type* end() {\n return data() + size();\n }\n\n bool empty() const {\n return _u.small.size == 0;\n }\n\n blob_storage::char_type* data() {\n if (external()) {\n assert(!_u.ptr->next); \/\/ must be linearized\n return _u.ptr->data;\n } else {\n return _u.small.data;\n }\n }\n\n const blob_storage::char_type* data() const {\n return read_linearize();\n }\n\n \/\/ Returns the amount of external memory used.\n size_t external_memory_usage() const {\n if (external()) {\n size_t mem = 0;\n blob_storage* blob = _u.ptr;\n while (blob) {\n mem += blob->frag_size + sizeof(blob_storage);\n blob = blob->next;\n }\n return mem;\n }\n return 0;\n }\n\n template <typename Func>\n friend std::result_of_t<Func()> with_linearized_managed_bytes(Func&& func);\n};\n\n\/\/ Run func() while ensuring that reads of managed_bytes objects are\n\/\/ temporarlily linearized\ntemplate <typename Func>\ninline\nstd::result_of_t<Func()>\nwith_linearized_managed_bytes(Func&& func) {\n managed_bytes::linearization_context_guard g;\n return func();\n}\n\nnamespace std {\n\ntemplate <>\nstruct hash<managed_bytes> {\n size_t operator()(const managed_bytes& v) const {\n return hash<bytes_view>()(v);\n }\n};\n\n}\n\n\/\/ blob_storage is a variable-size type\ninline\nsize_t\nsize_for_allocation_strategy(const blob_storage& bs) {\n return sizeof(bs) + bs.frag_size;\n}\n<commit_msg>managed_bytes: Declare copy constructor as allocation point<commit_after>\n\/*\n * Copyright (C) 2015 ScyllaDB\n *\/\n\n\/*\n * This file is part of Scylla.\n *\n * Scylla is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * Scylla is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with Scylla. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n\n#pragma once\n\n#include <stdint.h>\n#include <memory>\n#include \"bytes.hh\"\n#include \"utils\/allocation_strategy.hh\"\n#include <seastar\/core\/unaligned.hh>\n#include <seastar\/util\/alloc_failure_injector.hh>\n#include <unordered_map>\n#include <type_traits>\n\nstruct blob_storage {\n struct [[gnu::packed]] ref_type {\n blob_storage* ptr;\n\n ref_type() {}\n ref_type(blob_storage* ptr) : ptr(ptr) {}\n operator blob_storage*() const { return ptr; }\n blob_storage* operator->() const { return ptr; }\n blob_storage& operator*() const { return *ptr; }\n };\n using size_type = uint32_t;\n using char_type = bytes_view::value_type;\n\n ref_type* backref;\n size_type size;\n size_type frag_size;\n ref_type next;\n char_type data[];\n\n blob_storage(ref_type* backref, size_type size, size_type frag_size) noexcept\n : backref(backref)\n , size(size)\n , frag_size(frag_size)\n , next(nullptr)\n {\n *backref = this;\n }\n\n blob_storage(blob_storage&& o) noexcept\n : backref(o.backref)\n , size(o.size)\n , frag_size(o.frag_size)\n , next(o.next)\n {\n *backref = this;\n o.next = nullptr;\n if (next) {\n next->backref = &next;\n }\n memcpy(data, o.data, frag_size);\n }\n} __attribute__((packed));\n\n\/\/ A managed version of \"bytes\" (can be used with LSA).\nclass managed_bytes {\n struct linearization_context {\n unsigned _nesting = 0;\n \/\/ Map from first blob_storage address to linearized version\n \/\/ We use the blob_storage address to be insentive to moving\n \/\/ a managed_bytes object.\n std::unordered_map<const blob_storage*, std::unique_ptr<bytes_view::value_type[]>> _state;\n void enter() {\n ++_nesting;\n }\n void leave() {\n if (!--_nesting) {\n _state.clear();\n }\n }\n void forget(const blob_storage* p) noexcept;\n };\n static thread_local linearization_context _linearization_context;\npublic:\n struct linearization_context_guard {\n linearization_context_guard() {\n _linearization_context.enter();\n }\n ~linearization_context_guard() {\n _linearization_context.leave();\n }\n };\nprivate:\n static constexpr size_t max_inline_size = 15;\n struct small_blob {\n bytes_view::value_type data[max_inline_size];\n int8_t size; \/\/ -1 -> use blob_storage\n };\n union u {\n u() {}\n ~u() {}\n blob_storage::ref_type ptr;\n small_blob small;\n } _u;\n static_assert(sizeof(small_blob) > sizeof(blob_storage*), \"inline size too small\");\nprivate:\n bool external() const {\n return _u.small.size < 0;\n }\n size_t max_seg(allocation_strategy& alctr) {\n return alctr.preferred_max_contiguous_allocation() - sizeof(blob_storage);\n }\n void free_chain(blob_storage* p) noexcept {\n if (p->next && _linearization_context._nesting) {\n _linearization_context.forget(p);\n }\n auto& alctr = current_allocator();\n while (p) {\n auto n = p->next;\n alctr.destroy(p);\n p = n;\n }\n }\n const bytes_view::value_type* read_linearize() const {\n if (!external()) {\n return _u.small.data;\n } else if (!_u.ptr->next) {\n return _u.ptr->data;\n } else {\n return do_linearize();\n }\n }\n bytes_view::value_type& value_at_index(blob_storage::size_type index) {\n if (!external()) {\n return _u.small.data[index];\n }\n blob_storage* a = _u.ptr;\n while (index >= a->frag_size) {\n index -= a->frag_size;\n a = a->next;\n }\n return a->data[index];\n }\n const bytes_view::value_type* do_linearize() const;\npublic:\n using size_type = blob_storage::size_type;\n struct initialized_later {};\n\n managed_bytes() {\n _u.small.size = 0;\n }\n\n managed_bytes(const blob_storage::char_type* ptr, size_type size)\n : managed_bytes(bytes_view(ptr, size)) {}\n\n managed_bytes(const bytes& b) : managed_bytes(static_cast<bytes_view>(b)) {}\n\n managed_bytes(initialized_later, size_type size) {\n memory::on_alloc_point();\n if (size <= max_inline_size) {\n _u.small.size = size;\n } else {\n _u.small.size = -1;\n auto& alctr = current_allocator();\n auto maxseg = max_seg(alctr);\n auto now = std::min(size_t(size), maxseg);\n void* p = alctr.alloc(&standard_migrator<blob_storage>::object,\n sizeof(blob_storage) + now, alignof(blob_storage));\n auto first = new (p) blob_storage(&_u.ptr, size, now);\n auto last = first;\n size -= now;\n try {\n while (size) {\n auto now = std::min(size_t(size), maxseg);\n void* p = alctr.alloc(&standard_migrator<blob_storage>::object,\n sizeof(blob_storage) + now, alignof(blob_storage));\n last = new (p) blob_storage(&last->next, 0, now);\n size -= now;\n }\n } catch (...) {\n free_chain(first);\n throw;\n }\n }\n }\n\n managed_bytes(bytes_view v) : managed_bytes(initialized_later(), v.size()) {\n if (!external()) {\n std::copy(v.begin(), v.end(), _u.small.data);\n return;\n }\n auto p = v.data();\n auto s = v.size();\n auto b = _u.ptr;\n while (s) {\n memcpy(b->data, p, b->frag_size);\n p += b->frag_size;\n s -= b->frag_size;\n b = b->next;\n }\n assert(!b);\n }\n\n managed_bytes(std::initializer_list<bytes::value_type> b) : managed_bytes(b.begin(), b.size()) {}\n\n ~managed_bytes() noexcept {\n if (external()) {\n free_chain(_u.ptr);\n }\n }\n\n managed_bytes(const managed_bytes& o) : managed_bytes(initialized_later(), o.size()) {\n if (!external()) {\n memcpy(data(), o.data(), size());\n return;\n }\n auto s = size();\n const blob_storage::ref_type* next_src = &o._u.ptr;\n blob_storage* blob_src = nullptr;\n size_type size_src = 0;\n size_type offs_src = 0;\n blob_storage::ref_type* next_dst = &_u.ptr;\n blob_storage* blob_dst = nullptr;\n size_type size_dst = 0;\n size_type offs_dst = 0;\n while (s) {\n if (!size_src) {\n blob_src = *next_src;\n next_src = &blob_src->next;\n size_src = blob_src->frag_size;\n offs_src = 0;\n }\n if (!size_dst) {\n blob_dst = *next_dst;\n next_dst = &blob_dst->next;\n size_dst = blob_dst->frag_size;\n offs_dst = 0;\n }\n auto now = std::min(size_src, size_dst);\n memcpy(blob_dst->data + offs_dst, blob_src->data + offs_src, now);\n s -= now;\n offs_src += now; size_src -= now;\n offs_dst += now; size_dst -= now;\n }\n assert(size_src == 0 && size_dst == 0);\n }\n\n managed_bytes(managed_bytes&& o) noexcept\n : _u(o._u)\n {\n if (external()) {\n if (_u.ptr) {\n _u.ptr->backref = &_u.ptr;\n }\n }\n o._u.small.size = 0;\n }\n\n managed_bytes& operator=(managed_bytes&& o) noexcept {\n if (this != &o) {\n this->~managed_bytes();\n new (this) managed_bytes(std::move(o));\n }\n return *this;\n }\n\n managed_bytes& operator=(const managed_bytes& o) {\n if (this != &o) {\n managed_bytes tmp(o);\n this->~managed_bytes();\n new (this) managed_bytes(std::move(tmp));\n }\n return *this;\n }\n\n bool operator==(const managed_bytes& o) const {\n if (size() != o.size()) {\n return false;\n }\n if (!external()) {\n return bytes_view(*this) == bytes_view(o);\n } else {\n auto a = _u.ptr;\n auto a_data = a->data;\n auto a_remain = a->frag_size;\n a = a->next;\n auto b = o._u.ptr;\n auto b_data = b->data;\n auto b_remain = b->frag_size;\n b = b->next;\n while (a_remain || b_remain) {\n auto now = std::min(a_remain, b_remain);\n if (bytes_view(a_data, now) != bytes_view(b_data, now)) {\n return false;\n }\n a_data += now;\n a_remain -= now;\n if (!a_remain && a) {\n a_data = a->data;\n a_remain = a->frag_size;\n a = a->next;\n }\n b_data += now;\n b_remain -= now;\n if (!b_remain && b) {\n b_data = b->data;\n b_remain = b->frag_size;\n b = b->next;\n }\n }\n return true;\n }\n }\n\n bool operator!=(const managed_bytes& o) const {\n return !(*this == o);\n }\n\n operator bytes_view() const {\n return { data(), size() };\n }\n\n bool is_fragmented() const {\n return external() && _u.ptr->next;\n }\n\n operator bytes_mutable_view() {\n assert(!is_fragmented());\n return { data(), size() };\n };\n\n bytes_view::value_type& operator[](size_type index) {\n return value_at_index(index);\n }\n\n const bytes_view::value_type& operator[](size_type index) const {\n return const_cast<const bytes_view::value_type&>(\n const_cast<managed_bytes*>(this)->value_at_index(index));\n }\n\n size_type size() const {\n if (external()) {\n return _u.ptr->size;\n } else {\n return _u.small.size;\n }\n }\n\n const blob_storage::char_type* begin() const {\n return data();\n }\n\n const blob_storage::char_type* end() const {\n return data() + size();\n }\n\n blob_storage::char_type* begin() {\n return data();\n }\n\n blob_storage::char_type* end() {\n return data() + size();\n }\n\n bool empty() const {\n return _u.small.size == 0;\n }\n\n blob_storage::char_type* data() {\n if (external()) {\n assert(!_u.ptr->next); \/\/ must be linearized\n return _u.ptr->data;\n } else {\n return _u.small.data;\n }\n }\n\n const blob_storage::char_type* data() const {\n return read_linearize();\n }\n\n \/\/ Returns the amount of external memory used.\n size_t external_memory_usage() const {\n if (external()) {\n size_t mem = 0;\n blob_storage* blob = _u.ptr;\n while (blob) {\n mem += blob->frag_size + sizeof(blob_storage);\n blob = blob->next;\n }\n return mem;\n }\n return 0;\n }\n\n template <typename Func>\n friend std::result_of_t<Func()> with_linearized_managed_bytes(Func&& func);\n};\n\n\/\/ Run func() while ensuring that reads of managed_bytes objects are\n\/\/ temporarlily linearized\ntemplate <typename Func>\ninline\nstd::result_of_t<Func()>\nwith_linearized_managed_bytes(Func&& func) {\n managed_bytes::linearization_context_guard g;\n return func();\n}\n\nnamespace std {\n\ntemplate <>\nstruct hash<managed_bytes> {\n size_t operator()(const managed_bytes& v) const {\n return hash<bytes_view>()(v);\n }\n};\n\n}\n\n\/\/ blob_storage is a variable-size type\ninline\nsize_t\nsize_for_allocation_strategy(const blob_storage& bs) {\n return sizeof(bs) + bs.frag_size;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/! @Alan\n\/\/! Exercise 10.12:\n\/\/! Write a function named compareIsbn that compares the isbn() members of two Sales_data objects.\n\/\/! Use that function to sort a vector that holds Sales_data objects.\n\/\/!\n\n#include <iostream>\n#include <string>\n#include <vector>\n#include <algorithm>\n#include <numeric>\n#include \"..\/ch07\/ex7_26.h\" \/\/ Sales_data class.\n\ninline bool \ncompareIsbn(const Sales_data &sd1, const Sales_data &sd2)\n{\n return sd1.isbn().size() < sd2.isbn().size();\n}\n\nint main()\n{\n Sales_data d1(\"aa\"), d2(\"aaaa\"), d3(\"aaa\"), d4(\"z\"), d5(\"aaaaz\");\n std::vector<Sales_data> v{d1, d2, d3, d4, d5};\n\n \/\/! @note the elements the iterators pointing to\n \/\/! must match the parameters of the predicate.\n std::sort(v.begin(), v.end(), compareIsbn);\n\n for(const auto &element : v)\n std::cout << element.isbn() << \" \";\n std::cout << std::endl;\n\n return 0;\n}\n<commit_msg>Update ex10_12.cpp<commit_after>\/\/! @Yue Wang\n\/\/! Exercise 10.12:\n\/\/! Write a function named compareIsbn that compares the isbn() members of two Sales_data objects.\n\/\/! Use that function to sort a vector that holds Sales_data objects.\n\/\/!\n\n#include <iostream>\n#include <string>\n#include <vector>\n#include <algorithm>\n#include <numeric>\n#include \"..\/ch07\/ex7_26.h\" \/\/ Sales_data class.\n\ninline bool compareIsbn(const Sales_data &sd1, const Sales_data &sd2)\n{\n return sd1.isbn().size() < sd2.isbn().size();\n}\n\nint main()\n{\n Sales_data d1(\"aa\"), d2(\"aaaa\"), d3(\"aaa\"), d4(\"z\"), d5(\"aaaaz\");\n std::vector<Sales_data> v{d1, d2, d3, d4, d5};\n\n \/\/! @note the elements the iterators pointing to\n \/\/! must match the parameters of the predicate.\n std::sort(v.begin(), v.end(), compareIsbn);\n\n for(const auto &element : v)\n std::cout << element.isbn() << \" \";\n std::cout << std::endl;\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ ex11_31.cpp\n\/\/ Exercise 11.31\n\/\/\n\/\/ Created by pezy on 12\/17\/14.\n\/\/ Copyright (c) 2014 pezy. All rights reserved.\n\/\/\n\/\/ Write a program that defines a multimap of authors and their works.\n\/\/ Use **find** to find **an element** in the multimap and erase that element.\n\/\/ Be sure your program works correctly if the element you look for is not in\n\/\/ the map.\n\n#include <iostream>\n#include <map>\n#include <string>\n\nusing namespace std;\n\nint main()\n{\n multimap<string, string> authors={{\"alan\", \"DMA\"}, {\"pezy\", \"LeetCode\"}, {\"alan\", \"CLRS\"}, {\"wang\", \"FTP\"}, {\"pezy\", \"CP5\"}, {\"wang\", \"CPP-Concurrency\"}};\n \/\/ want to delete an element that author is Alan, work is CP5\n string author=\"pezy\";\n string work=\"CP5\";\n\n auto found=authors.find(author);\n auto cnt=authors.count(author);\n\n while(cnt)\n {\n if(found->second==work)\n {\n authors.erase(found);\n break;\n }\n ++found;\n --cnt;\n }\n\n for(const auto &author:authors)\n cout<<author.first<<\" \"<<author.second<<endl;\n}\n<commit_msg>Update ex11_31.cpp<commit_after>\/\/\n\/\/ ex11_31.cpp\n\/\/ Exercise 11.31\n\/\/\n\/\/ Created by pezy on 12\/17\/14.\n\/\/ Copyright (c) 2014 pezy. All rights reserved.\n\/\/\n\/\/ Write a program that defines a multimap of authors and their works.\n\/\/ Use **find** to find **an element** in the multimap and erase that element.\n\/\/ Be sure your program works correctly if the element you look for is not in\n\/\/ the map.\n\n#include <iostream>\n#include <map>\n#include <string>\n\nusing namespace std;\n\nint main()\n{\n multimap<string, string> authors={{\"alan\", \"DMA\"}, {\"pezy\", \"LeetCode\"}, {\"alan\", \"CLRS\"}, {\"wang\", \"FTP\"}, {\"pezy\", \"CP5\"}, {\"wang\", \"CPP-Concurrency\"}};\n \/\/ want to delete an element that author is pezy, work is CP5\n string author=\"pezy\";\n string work=\"CP5\";\n\n auto found=authors.find(author);\n auto cnt=authors.count(author);\n\n while(cnt)\n {\n if(found->second==work)\n {\n authors.erase(found);\n break;\n }\n ++found;\n --cnt;\n }\n\n for(const auto &author:authors)\n cout<<author.first<<\" \"<<author.second<<endl;\n}\n<|endoftext|>"} {"text":"<commit_before>#include <osg\/LOD>\n\n#include <algorithm>\n\nusing namespace osg;\n\nLOD::LOD(const LOD& lod,const CopyOp& copyop):\n Group(lod,copyop),\n _centerMode(lod._centerMode),\n _userDefinedCenter(lod._userDefinedCenter),\n _rangeList(lod._rangeList)\n{\n}\n\n\nvoid LOD::traverse(NodeVisitor& nv)\n{\n switch(nv.getTraversalMode())\n {\n case(NodeVisitor::TRAVERSE_ALL_CHILDREN):\n std::for_each(_children.begin(),_children.end(),NodeAcceptOp(nv));\n break;\n case(NodeVisitor::TRAVERSE_ACTIVE_CHILDREN):\n {\n float distance = nv.getDistanceToEyePoint(getCenter(),true);\n unsigned int numChildren = _children.size();\n if (_rangeList.size()<numChildren) numChildren=_rangeList.size();\n \n for(unsigned int i=0;i<numChildren;++i)\n { \n if (_rangeList[i].first<=distance && distance<_rangeList[i].second)\n {\n _children[i]->accept(nv);\n }\n }\n break;\n }\n default:\n break;\n }\n}\n\nbool LOD::addChild( Node *child )\n{\n float maxRange = 0.0f;\n if (!_rangeList.empty()) maxRange=_rangeList.back().second;\n return addChild(child,maxRange,maxRange);\n}\n\nbool LOD::addChild(Node *child, float min, float max)\n{\n if (Group::addChild(child))\n {\n if (_children.size()>_rangeList.size()) _rangeList.resize(_children.size(),MinMaxPair(min,min));\n _rangeList[_children.size()-1].first = min;\n _rangeList[_children.size()-1].second = max;\n return true;\n }\n return false;\n}\n\nbool LOD::removeChild( Node *child )\n{\n \/\/ find the child's position.\n unsigned int pos=findChildNo(child);\n if (pos==_children.size()) return false;\n \n _rangeList.erase(_rangeList.begin()+pos);\n \n return Group::removeChild(child); \n}\n\nvoid LOD::setRange(unsigned int childNo, float min,float max)\n{\n if (childNo>=_rangeList.size()) _rangeList.resize(childNo+1,MinMaxPair(min,min));\n _rangeList[childNo].first=min;\n _rangeList[childNo].second=max;\n}\n<commit_msg>Fixed bug in osg::LOD::addChild() which was forcing all ranges to be identical values.<commit_after>#include <osg\/LOD>\n\n#include <algorithm>\n\nusing namespace osg;\n\nLOD::LOD(const LOD& lod,const CopyOp& copyop):\n Group(lod,copyop),\n _centerMode(lod._centerMode),\n _userDefinedCenter(lod._userDefinedCenter),\n _rangeList(lod._rangeList)\n{\n}\n\n\nvoid LOD::traverse(NodeVisitor& nv)\n{\n switch(nv.getTraversalMode())\n {\n case(NodeVisitor::TRAVERSE_ALL_CHILDREN):\n std::for_each(_children.begin(),_children.end(),NodeAcceptOp(nv));\n break;\n case(NodeVisitor::TRAVERSE_ACTIVE_CHILDREN):\n {\n float distance = nv.getDistanceToEyePoint(getCenter(),true);\n unsigned int numChildren = _children.size();\n if (_rangeList.size()<numChildren) numChildren=_rangeList.size();\n \n for(unsigned int i=0;i<numChildren;++i)\n { \n if (_rangeList[i].first<=distance && distance<_rangeList[i].second)\n {\n _children[i]->accept(nv);\n }\n }\n break;\n }\n default:\n break;\n }\n}\n\nbool LOD::addChild( Node *child )\n{\n if (Group::addChild(child))\n {\n float maxRange = 0.0f;\n if (!_rangeList.empty()) maxRange=_rangeList.back().second;\n\n if (_children.size()>_rangeList.size()) _rangeList.resize(_children.size(),MinMaxPair(maxRange,maxRange));\n\n return true;\n }\n return false;\n}\n\nbool LOD::addChild(Node *child, float min, float max)\n{\n if (Group::addChild(child))\n {\n if (_children.size()>_rangeList.size()) _rangeList.resize(_children.size(),MinMaxPair(min,min));\n _rangeList[_children.size()-1].first = min;\n _rangeList[_children.size()-1].second = max;\n return true;\n }\n return false;\n}\n\nbool LOD::removeChild( Node *child )\n{\n \/\/ find the child's position.\n unsigned int pos=findChildNo(child);\n if (pos==_children.size()) return false;\n \n _rangeList.erase(_rangeList.begin()+pos);\n \n return Group::removeChild(child); \n}\n\nvoid LOD::setRange(unsigned int childNo, float min,float max)\n{\n if (childNo>=_rangeList.size()) _rangeList.resize(childNo+1,MinMaxPair(min,min));\n _rangeList[childNo].first=min;\n _rangeList[childNo].second=max;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ ex12_14.cpp\n\/\/ Exercise 12.14\n\/\/\n\/\/ Created by pezy on 12\/22\/14.\n\/\/ Copyright (c) 2014 pezy. All rights reserved.\n\/\/\n\/\/ Write your own version of a function that uses a shared_ptr to manage a\n\/\/ connection.\n\n#include <iostream>\n#include <string>\n#include <memory>\n\nstruct connection {\n std::string ip;\n int port;\n connection(std::string ip_, int port_) : ip(ip_), port(port_) {}\n};\nstruct destination {\n std::string ip;\n int port;\n destination(std::string ip_, int port_) : ip(ip_), port(port_) {}\n};\n\nconnection connect(destination* pDest)\n{\n std::shared_ptr<connection> pConn(new connection(pDest->ip, pDest->port));\n std::cout << \"creating connection(\" << pConn.use_count() << \")\"\n << std::endl;\n return *pConn;\n}\n\nvoid disconnect(connection pConn)\n{\n std::cout << \"connection close(\" << pConn.ip << \":\" << pConn.port << \")\"\n << std::endl;\n}\n\nvoid end_connection(connection* pConn)\n{\n disconnect(*pConn);\n}\n\nvoid f(destination& d)\n{\n connection conn = connect(&d);\n std::shared_ptr<connection> p(&conn, end_connection);\n std::cout << \"connecting now(\" << p.use_count() << \")\" << std::endl;\n}\n\nint main()\n{\n destination dest(\"202.118.176.67\", 3316);\n f(dest);\n}<commit_msg>Update ex12_14.cpp<commit_after>\/\/\n\/\/ ex12_14.cpp\n\/\/ Exercise 12.14\n\/\/\n\/\/ Created by pezy on 12\/22\/14.\n\/\/ Copyright (c) 2014 pezy. All rights reserved.\n\/\/\n\/\/ Write your own version of a function that uses a shared_ptr to manage a\n\/\/ connection.\n\n#include <iostream>\n#include <memory>\n#include <string>\n\nusing namespace std;\n\nstruct destination {\n string ip;\n int port;\n destination(string ip_, int port_):ip(ip_), port(port_) {}\n};\n\nstruct connection {\n string ip;\n int port;\n connection(string ip_, int port_):ip(ip_), port(port_) {}\n};\n\nconnection connect(destination *pDest)\n{\n shared_ptr<connection> pConn(new connection(pDest->ip, pDest->port));\n cout<<\"creating connection(\"<<pConn.use_count()<<\")\"<<endl;\n return *pConn;\n}\n\nvoid disconnect(connection pConn)\n{\n cout<<\"connection close(\"<<pConn.ip<<\":\"<<pConn.port<<\")\"<<endl;\n}\n\nvoid end_connection(connection *pConn)\n{\n disconnect(*pConn);\n}\n\nvoid f(destination &d)\n{\n connection conn=connect(&d);\n shared_ptr<connection> p(&conn, end_connection);\n cout<<\"connecting now(\"<<p.use_count()<<\")\"<<endl;\n}\n\nint main()\n{\n destination dest(\"202.118.176.67\", 3316);\n f(dest);\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * nextpnr -- Next Generation Place and Route\n *\n * Copyright (C) 2018 Miodrag Milanovic <miodrag@symbioticeda.com>\n * Copyright (C) 2018 Serge Bazanski <q3k@symbioticeda.com>\n *\n * Permission to use, copy, modify, and\/or distribute this software for any\n * purpose with or without fee is hereby granted, provided that the above\n * copyright notice and this permission notice appear in all copies.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n *\n *\/\n\n#include \"treemodel.h\"\n#include \"log.h\"\n\nNEXTPNR_NAMESPACE_BEGIN\n\nnamespace TreeModel {\n\n\n\/\/ converts 'aa123bb432' -> ['aa', '123', 'bb', '432']\nstd::vector<QString> IdStringList::alphaNumSplit(const QString &str)\n{\n std::vector<QString> res;\n QString current_part;\n\n bool number = true;\n for (const auto c : str) {\n if (current_part.size() == 0 && res.size() == 0) {\n current_part.push_back(c);\n number = c.isNumber();\n continue;\n }\n\n if (number != c.isNumber()) {\n number = c.isNumber();\n res.push_back(current_part);\n current_part.clear();\n }\n\n current_part.push_back(c);\n }\n \n res.push_back(current_part);\n\n return res;\n}\n\nvoid IdStringList::updateElements(Context *ctx, std::vector<IdString> elements)\n{\n bool changed = false;\n\n \/\/ For any elements that are not yet in managed_, created them.\n std::unordered_set<IdString> element_set;\n for (auto elem : elements) {\n element_set.insert(elem);\n auto existing = managed_.find(elem);\n if (existing == managed_.end()) {\n auto item = new IdStringItem(ctx, elem, this, child_type_);\n managed_.emplace(elem, std::unique_ptr<IdStringItem>(item));\n changed = true;\n }\n }\n \n \/\/ For any elements that are in managed_ but not in new, delete them.\n for (auto &pair : managed_) {\n if (element_set.count(pair.first) != 0) {\n continue;\n }\n managed_.erase(pair.first);\n changed = true;\n }\n\n \/\/ Return early if there are no changes.\n if (!changed)\n return;\n\n \/\/ Rebuild children list.\n children_.clear();\n for (auto &pair : managed_) {\n if (element_set.count(pair.first) != 0) {\n children_.push_back(pair.second.get());\n }\n }\n\n \/\/ Sort new children\n qSort(children_.begin(), children_.end(), [&](const Item *a, const Item *b){\n auto parts_a = alphaNumSplit(a->name());\n auto parts_b = alphaNumSplit(b->name());\n\n \/\/ Short-circuit for different part count.\n if (parts_a.size() != parts_b.size()) {\n return parts_a.size() < parts_b.size();\n }\n\n for (size_t i = 0; i < parts_a.size(); i++) {\n auto &part_a = parts_a.at(i);\n auto &part_b = parts_b.at(i);\n \n bool a_is_number, b_is_number;\n int a_number = part_a.toInt(&a_is_number);\n int b_number = part_b.toInt(&b_is_number);\n\n \/\/ If both parts are numbers, compare numerically.\n \/\/ If they're equal, continue to next part.\n if (a_is_number && b_is_number) {\n if (a_number != b_number) {\n return a_number < b_number;\n } else {\n continue;\n }\n }\n\n \/\/ For different alpha\/nonalpha types, make numeric parts appear\n \/\/ first.\n if (a_is_number != b_is_number) {\n return a_is_number;\n }\n\n \/\/ If both parts are numbers, compare lexically.\n \/\/ If they're equal, continue to next part.\n if (part_a == part_b) {\n continue;\n }\n return part_a < part_b;\n }\n\n \/\/ Same string.\n return true;\n });\n}\n\nvoid IdStringList::search(QList<Item*> &results, QString text, int limit)\n{\n for (const auto &child : children_) {\n if (limit != -1 && results.size() > limit)\n return;\n\n if (child->name().contains(text))\n results.push_back(child);\n }\n}\n\n\nModel::Model(QObject *parent) :\n QAbstractItemModel(parent),\n root_(new Item(\"Elements\", nullptr)) {}\n\nModel::~Model() {}\n\nvoid Model::loadContext(Context *ctx)\n{\n if (!ctx)\n return;\n ctx_ = ctx;\n\n beginResetModel();\n\n \/\/ Currently we lack an API to get a proper hierarchy of bels\/pip\/wires\n \/\/ cross-arch. So we only do this for ICE40 by querying the ChipDB\n \/\/ directly.\n \/\/ TODO(q3k): once AnyId and the tree API land in Arch, move this over.\n#ifdef ARCH_ICE40\n {\n std::map<std::pair<int, int>, std::vector<BelId>> belMap;\n for (auto bel : ctx->getBels()) {\n auto loc = ctx->getBelLocation(bel);\n belMap[std::pair<int, int>(loc.x, loc.y)].push_back(bel);\n }\n auto belGetter = [](Context *ctx, BelId id) { return ctx->getBelName(id); };\n bel_root_ = std::unique_ptr<BelXYRoot>(new BelXYRoot(ctx, \"Bels\", root_.get(), belMap, belGetter, ElementType::BEL));\n\n std::map<std::pair<int, int>, std::vector<WireId>> wireMap;\n for (int i = 0; i < ctx->chip_info->num_wires; i++) {\n const auto wire = &ctx->chip_info->wire_data[i];\n WireId wireid;\n wireid.index = i;\n wireMap[std::pair<int, int>(wire->x, wire->y)].push_back(wireid);\n }\n auto wireGetter = [](Context *ctx, WireId id) { return ctx->getWireName(id); };\n wire_root_ = std::unique_ptr<WireXYRoot>(new WireXYRoot(ctx, \"Wires\", root_.get(), wireMap, wireGetter, ElementType::WIRE));\n\n std::map<std::pair<int, int>, std::vector<PipId>> pipMap;\n for (int i = 0; i < ctx->chip_info->num_pips; i++) {\n const auto pip = &ctx->chip_info->pip_data[i];\n PipId pipid;\n pipid.index = i;\n pipMap[std::pair<int, int>(pip->x, pip->y)].push_back(pipid);\n }\n printf(\"generating pip static tree...\\n\");\n auto pipGetter = [](Context *ctx, PipId id) { return ctx->getPipName(id); };\n pip_root_ = std::unique_ptr<PipXYRoot>(new PipXYRoot(ctx, \"Pips\", root_.get(), pipMap, pipGetter, ElementType::PIP));\n }\n#endif\n\n cell_root_ = std::unique_ptr<IdStringList>(new IdStringList(QString(\"Cells\"), root_.get(), ElementType::CELL));\n net_root_ = std::unique_ptr<IdStringList>(new IdStringList(QString(\"Nets\"), root_.get(), ElementType::NET));\n\n endResetModel();\n\n updateCellsNets(ctx);\n}\n\nvoid Model::updateCellsNets(Context *ctx)\n{\n if (!ctx)\n return;\n\n beginResetModel();\n\n std::vector<IdString> cells;\n for (auto &pair : ctx->cells) {\n cells.push_back(pair.first);\n }\n cell_root_->updateElements(ctx, cells);\n\n std::vector<IdString> nets;\n for (auto &pair : ctx->nets) {\n nets.push_back(pair.first);\n }\n net_root_->updateElements(ctx, nets);\n\n endResetModel();\n}\n\nint Model::rowCount(const QModelIndex &parent) const { return nodeFromIndex(parent)->count(); }\n\nint Model::columnCount(const QModelIndex &parent) const { return 1; }\n\nQModelIndex Model::index(int row, int column, const QModelIndex &parent) const\n{\n Item *node = nodeFromIndex(parent);\n if (row >= node->count())\n return QModelIndex();\n\n return createIndex(row, column, node->child(row));\n}\n\nQModelIndex Model::parent(const QModelIndex &child) const\n{\n Item *parent = nodeFromIndex(child)->parent();\n if (parent == root_.get())\n return QModelIndex();\n Item *node = parent->parent();\n return createIndex(node->indexOf(parent), 0, parent);\n}\n\nQVariant Model::data(const QModelIndex &index, int role) const\n{\n if (index.column() != 0)\n return QVariant();\n if (role != Qt::DisplayRole)\n return QVariant();\n Item *node = nodeFromIndex(index);\n return node->name();\n}\n\nQVariant Model::headerData(int section, Qt::Orientation orientation, int role) const\n{\n Q_UNUSED(section);\n if (orientation == Qt::Horizontal && role == Qt::DisplayRole)\n return QString(\"Items\");\n\n return QVariant();\n}\n\nItem *Model::nodeFromIndex(const QModelIndex &idx) const\n{\n if (idx.isValid())\n return (Item *)idx.internalPointer();\n return root_.get();\n}\n\nQt::ItemFlags Model::flags(const QModelIndex &index) const\n{\n Item *node = nodeFromIndex(index);\n return Qt::ItemIsEnabled | (node->type() != ElementType::NONE ? Qt::ItemIsSelectable : Qt::NoItemFlags);\n}\n\n\nvoid Model::fetchMore(const QModelIndex &parent)\n{\n if (ctx_ == nullptr)\n return;\n\n std::lock_guard<std::mutex> lock_ui(ctx_->ui_mutex);\n std::lock_guard<std::mutex> lock(ctx_->mutex);\n\n nodeFromIndex(parent)->fetchMore();\n}\n\nbool Model::canFetchMore(const QModelIndex &parent) const\n{\n return nodeFromIndex(parent)->canFetchMore();\n}\n\nQList<QModelIndex> Model::search(QString text)\n{\n const int limit = 500;\n QList<Item*> list;\n cell_root_->search(list, text, limit);\n net_root_->search(list, text, limit);\n bel_root_->search(list, text, limit);\n wire_root_->search(list, text, limit);\n pip_root_->search(list, text, limit);\n\n QList<QModelIndex> res;\n for (auto i : list) {\n res.push_back(indexFromNode(i));\n }\n return res;\n}\n\n}; \/\/ namespace TreeModel\n\nNEXTPNR_NAMESPACE_END\n<commit_msg>gui: cosmetics<commit_after>\/*\n * nextpnr -- Next Generation Place and Route\n *\n * Copyright (C) 2018 Miodrag Milanovic <miodrag@symbioticeda.com>\n * Copyright (C) 2018 Serge Bazanski <q3k@symbioticeda.com>\n *\n * Permission to use, copy, modify, and\/or distribute this software for any\n * purpose with or without fee is hereby granted, provided that the above\n * copyright notice and this permission notice appear in all copies.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n *\n *\/\n\n#include \"treemodel.h\"\n#include \"log.h\"\n\nNEXTPNR_NAMESPACE_BEGIN\n\nnamespace TreeModel {\n\n\n\/\/ converts 'aa123bb432' -> ['aa', '123', 'bb', '432']\nstd::vector<QString> IdStringList::alphaNumSplit(const QString &str)\n{\n std::vector<QString> res;\n QString current_part;\n\n bool number = true;\n for (const auto c : str) {\n if (current_part.size() == 0 && res.size() == 0) {\n current_part.push_back(c);\n number = c.isNumber();\n continue;\n }\n\n if (number != c.isNumber()) {\n number = c.isNumber();\n res.push_back(current_part);\n current_part.clear();\n }\n\n current_part.push_back(c);\n }\n \n res.push_back(current_part);\n\n return res;\n}\n\nvoid IdStringList::updateElements(Context *ctx, std::vector<IdString> elements)\n{\n bool changed = false;\n\n \/\/ For any elements that are not yet in managed_, created them.\n std::unordered_set<IdString> element_set;\n for (auto elem : elements) {\n element_set.insert(elem);\n auto existing = managed_.find(elem);\n if (existing == managed_.end()) {\n auto item = new IdStringItem(ctx, elem, this, child_type_);\n managed_.emplace(elem, std::unique_ptr<IdStringItem>(item));\n changed = true;\n }\n }\n \n \/\/ For any elements that are in managed_ but not in new, delete them.\n for (auto &pair : managed_) {\n if (element_set.count(pair.first) != 0) {\n continue;\n }\n managed_.erase(pair.first);\n changed = true;\n }\n\n \/\/ Return early if there are no changes.\n if (!changed)\n return;\n\n \/\/ Rebuild children list.\n children_.clear();\n for (auto &pair : managed_) {\n if (element_set.count(pair.first) != 0) {\n children_.push_back(pair.second.get());\n }\n }\n\n \/\/ Sort new children\n qSort(children_.begin(), children_.end(), [&](const Item *a, const Item *b){\n auto parts_a = alphaNumSplit(a->name());\n auto parts_b = alphaNumSplit(b->name());\n\n \/\/ Short-circuit for different part count.\n if (parts_a.size() != parts_b.size()) {\n return parts_a.size() < parts_b.size();\n }\n\n for (size_t i = 0; i < parts_a.size(); i++) {\n auto &part_a = parts_a.at(i);\n auto &part_b = parts_b.at(i);\n \n bool a_is_number, b_is_number;\n int a_number = part_a.toInt(&a_is_number);\n int b_number = part_b.toInt(&b_is_number);\n\n \/\/ If both parts are numbers, compare numerically.\n \/\/ If they're equal, continue to next part.\n if (a_is_number && b_is_number) {\n if (a_number != b_number) {\n return a_number < b_number;\n } else {\n continue;\n }\n }\n\n \/\/ For different alpha\/nonalpha types, make numeric parts appear\n \/\/ first.\n if (a_is_number != b_is_number) {\n return a_is_number;\n }\n\n \/\/ If both parts are numbers, compare lexically.\n \/\/ If they're equal, continue to next part.\n if (part_a == part_b) {\n continue;\n }\n return part_a < part_b;\n }\n\n \/\/ Same string.\n return true;\n });\n}\n\nvoid IdStringList::search(QList<Item*> &results, QString text, int limit)\n{\n for (const auto &child : children_) {\n if (limit != -1 && results.size() > limit)\n return;\n\n if (child->name().contains(text))\n results.push_back(child);\n }\n}\n\n\nModel::Model(QObject *parent) :\n QAbstractItemModel(parent),\n root_(new Item(\"Elements\", nullptr)) {}\n\nModel::~Model() {}\n\nvoid Model::loadContext(Context *ctx)\n{\n if (!ctx)\n return;\n ctx_ = ctx;\n\n beginResetModel();\n\n \/\/ Currently we lack an API to get a proper hierarchy of bels\/pip\/wires\n \/\/ cross-arch. So we only do this for ICE40 by querying the ChipDB\n \/\/ directly.\n \/\/ TODO(q3k): once AnyId and the tree API land in Arch, move this over.\n#ifdef ARCH_ICE40\n {\n std::map<std::pair<int, int>, std::vector<BelId>> belMap;\n for (auto bel : ctx->getBels()) {\n auto loc = ctx->getBelLocation(bel);\n belMap[std::pair<int, int>(loc.x, loc.y)].push_back(bel);\n }\n auto belGetter = [](Context *ctx, BelId id) { return ctx->getBelName(id); };\n bel_root_ = std::unique_ptr<BelXYRoot>(new BelXYRoot(ctx, \"Bels\", root_.get(), belMap, belGetter, ElementType::BEL));\n\n std::map<std::pair<int, int>, std::vector<WireId>> wireMap;\n for (int i = 0; i < ctx->chip_info->num_wires; i++) {\n const auto wire = &ctx->chip_info->wire_data[i];\n WireId wireid;\n wireid.index = i;\n wireMap[std::pair<int, int>(wire->x, wire->y)].push_back(wireid);\n }\n auto wireGetter = [](Context *ctx, WireId id) { return ctx->getWireName(id); };\n wire_root_ = std::unique_ptr<WireXYRoot>(new WireXYRoot(ctx, \"Wires\", root_.get(), wireMap, wireGetter, ElementType::WIRE));\n\n std::map<std::pair<int, int>, std::vector<PipId>> pipMap;\n for (int i = 0; i < ctx->chip_info->num_pips; i++) {\n const auto pip = &ctx->chip_info->pip_data[i];\n PipId pipid;\n pipid.index = i;\n pipMap[std::pair<int, int>(pip->x, pip->y)].push_back(pipid);\n }\n auto pipGetter = [](Context *ctx, PipId id) { return ctx->getPipName(id); };\n pip_root_ = std::unique_ptr<PipXYRoot>(new PipXYRoot(ctx, \"Pips\", root_.get(), pipMap, pipGetter, ElementType::PIP));\n }\n#endif\n\n cell_root_ = std::unique_ptr<IdStringList>(new IdStringList(QString(\"Cells\"), root_.get(), ElementType::CELL));\n net_root_ = std::unique_ptr<IdStringList>(new IdStringList(QString(\"Nets\"), root_.get(), ElementType::NET));\n\n endResetModel();\n\n updateCellsNets(ctx);\n}\n\nvoid Model::updateCellsNets(Context *ctx)\n{\n if (!ctx)\n return;\n\n beginResetModel();\n\n std::vector<IdString> cells;\n for (auto &pair : ctx->cells) {\n cells.push_back(pair.first);\n }\n cell_root_->updateElements(ctx, cells);\n\n std::vector<IdString> nets;\n for (auto &pair : ctx->nets) {\n nets.push_back(pair.first);\n }\n net_root_->updateElements(ctx, nets);\n\n endResetModel();\n}\n\nint Model::rowCount(const QModelIndex &parent) const { return nodeFromIndex(parent)->count(); }\n\nint Model::columnCount(const QModelIndex &parent) const { return 1; }\n\nQModelIndex Model::index(int row, int column, const QModelIndex &parent) const\n{\n Item *node = nodeFromIndex(parent);\n if (row >= node->count())\n return QModelIndex();\n\n return createIndex(row, column, node->child(row));\n}\n\nQModelIndex Model::parent(const QModelIndex &child) const\n{\n Item *parent = nodeFromIndex(child)->parent();\n if (parent == root_.get())\n return QModelIndex();\n Item *node = parent->parent();\n return createIndex(node->indexOf(parent), 0, parent);\n}\n\nQVariant Model::data(const QModelIndex &index, int role) const\n{\n if (index.column() != 0)\n return QVariant();\n if (role != Qt::DisplayRole)\n return QVariant();\n Item *node = nodeFromIndex(index);\n return node->name();\n}\n\nQVariant Model::headerData(int section, Qt::Orientation orientation, int role) const\n{\n Q_UNUSED(section);\n if (orientation == Qt::Horizontal && role == Qt::DisplayRole)\n return QString(\"Items\");\n\n return QVariant();\n}\n\nItem *Model::nodeFromIndex(const QModelIndex &idx) const\n{\n if (idx.isValid())\n return (Item *)idx.internalPointer();\n return root_.get();\n}\n\nQt::ItemFlags Model::flags(const QModelIndex &index) const\n{\n Item *node = nodeFromIndex(index);\n return Qt::ItemIsEnabled | (node->type() != ElementType::NONE ? Qt::ItemIsSelectable : Qt::NoItemFlags);\n}\n\n\nvoid Model::fetchMore(const QModelIndex &parent)\n{\n if (ctx_ == nullptr)\n return;\n\n std::lock_guard<std::mutex> lock_ui(ctx_->ui_mutex);\n std::lock_guard<std::mutex> lock(ctx_->mutex);\n\n nodeFromIndex(parent)->fetchMore();\n}\n\nbool Model::canFetchMore(const QModelIndex &parent) const\n{\n return nodeFromIndex(parent)->canFetchMore();\n}\n\nQList<QModelIndex> Model::search(QString text)\n{\n const int limit = 500;\n QList<Item*> list;\n cell_root_->search(list, text, limit);\n net_root_->search(list, text, limit);\n bel_root_->search(list, text, limit);\n wire_root_->search(list, text, limit);\n pip_root_->search(list, text, limit);\n\n QList<QModelIndex> res;\n for (auto i : list) {\n res.push_back(indexFromNode(i));\n }\n return res;\n}\n\n}; \/\/ namespace TreeModel\n\nNEXTPNR_NAMESPACE_END\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (C) 2015 ScyllaDB\n *\/\n\n\/*\n * This file is part of Scylla.\n *\n * Scylla is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * Scylla is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with Scylla. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n\n#include \"compaction_manager.hh\"\n#include \"sstables\/compaction_manager.hh\"\n#include \"api\/api-doc\/compaction_manager.json.hh\"\n#include \"db\/system_keyspace.hh\"\n#include \"column_family.hh\"\n#include <utility>\n\nnamespace api {\n\nnamespace cm = httpd::compaction_manager_json;\nusing namespace json;\n\nstatic future<json::json_return_type> get_cm_stats(http_context& ctx,\n int64_t compaction_manager::stats::*f) {\n return ctx.db.map_reduce0([f](database& db) {\n return db.get_compaction_manager().get_stats().*f;\n }, int64_t(0), std::plus<int64_t>()).then([](const int64_t& res) {\n return make_ready_future<json::json_return_type>(res);\n });\n}\nstatic std::unordered_map<std::pair<sstring, sstring>, uint64_t, utils::tuple_hash> sum_pending_tasks(std::unordered_map<std::pair<sstring, sstring>, uint64_t, utils::tuple_hash>&& a,\n const std::unordered_map<std::pair<sstring, sstring>, uint64_t, utils::tuple_hash>& b) {\n for (auto&& i : b) {\n if (i.second) {\n a[i.first] += i.second;\n }\n }\n return std::move(a);\n}\n\n\nvoid set_compaction_manager(http_context& ctx, routes& r) {\n cm::get_compactions.set(r, [&ctx] (std::unique_ptr<request> req) {\n return ctx.db.map_reduce0([](database& db) {\n std::vector<cm::summary> summaries;\n const compaction_manager& cm = db.get_compaction_manager();\n\n for (const auto& c : cm.get_compactions()) {\n cm::summary s;\n s.ks = c->ks_name;\n s.cf = c->cf_name;\n s.unit = \"keys\";\n s.task_type = sstables::compaction_name(c->type);\n s.completed = c->total_keys_written;\n s.total = c->total_partitions;\n summaries.push_back(std::move(s));\n }\n return summaries;\n }, std::vector<cm::summary>(), concat<cm::summary>).then([](const std::vector<cm::summary>& res) {\n return make_ready_future<json::json_return_type>(res);\n });\n });\n\n cm::get_pending_tasks_by_table.set(r, [&ctx] (std::unique_ptr<request> req) {\n return ctx.db.map_reduce0([&ctx](database& db) {\n std::unordered_map<std::pair<sstring, sstring>, uint64_t, utils::tuple_hash> tasks;\n return do_for_each(db.get_column_families(), [&tasks](const std::pair<utils::UUID, seastar::lw_shared_ptr<table>>& i) {\n table& cf = *i.second.get();\n tasks[std::make_pair(cf.schema()->ks_name(), cf.schema()->cf_name())] = cf.get_compaction_strategy().estimated_pending_compactions(cf);\n return make_ready_future<>();\n }).then([&tasks] {\n return tasks;\n });\n }, std::unordered_map<std::pair<sstring, sstring>, uint64_t, utils::tuple_hash>(), sum_pending_tasks).then(\n [](const std::unordered_map<std::pair<sstring, sstring>, uint64_t, utils::tuple_hash>& task_map) {\n std::vector<cm::pending_compaction> res;\n res.reserve(task_map.size());\n for (auto i : task_map) {\n cm::pending_compaction task;\n task.ks = i.first.first;\n task.cf = i.first.second;\n task.task = i.second;\n res.emplace_back(std::move(task));\n }\n return make_ready_future<json::json_return_type>(res);\n });\n });\n\n cm::force_user_defined_compaction.set(r, [] (std::unique_ptr<request> req) {\n \/\/TBD\n \/\/ FIXME\n warn(unimplemented::cause::API);\n return make_ready_future<json::json_return_type>(json_void());\n });\n\n cm::stop_compaction.set(r, [&ctx] (std::unique_ptr<request> req) {\n auto type = req->get_query_param(\"type\");\n return ctx.db.invoke_on_all([type] (database& db) {\n auto& cm = db.get_compaction_manager();\n cm.stop_compaction(type);\n }).then([] {\n return make_ready_future<json::json_return_type>(json_void());\n });\n });\n\n cm::get_pending_tasks.set(r, [&ctx] (std::unique_ptr<request> req) {\n return map_reduce_cf(ctx, int64_t(0), [](column_family& cf) {\n return cf.get_compaction_strategy().estimated_pending_compactions(cf);\n }, std::plus<int64_t>());\n });\n\n cm::get_completed_tasks.set(r, [&ctx] (std::unique_ptr<request> req) {\n return get_cm_stats(ctx, &compaction_manager::stats::completed_tasks);\n });\n\n cm::get_total_compactions_completed.set(r, [] (std::unique_ptr<request> req) {\n \/\/ FIXME\n \/\/ We are currently dont have an API for compaction\n \/\/ so returning a 0 as the number of total compaction is ok\n return make_ready_future<json::json_return_type>(0);\n });\n\n cm::get_bytes_compacted.set(r, [] (std::unique_ptr<request> req) {\n \/\/TBD\n \/\/ FIXME\n warn(unimplemented::cause::API);\n return make_ready_future<json::json_return_type>(0);\n });\n\n cm::get_compaction_history.set(r, [] (std::unique_ptr<request> req) {\n std::function<future<>(output_stream<char>&&)> f = [](output_stream<char>&& s) {\n return do_with(output_stream<char>(std::move(s)), true, [] (output_stream<char>& s, bool& first){\n return s.write(\"[\").then([&s, &first] {\n return db::system_keyspace::get_compaction_history([&s, &first](const db::system_keyspace::compaction_history_entry& entry) mutable {\n cm::history h;\n h.id = entry.id.to_sstring();\n h.ks = std::move(entry.ks);\n h.cf = std::move(entry.cf);\n h.compacted_at = entry.compacted_at;\n h.bytes_in = entry.bytes_in;\n h.bytes_out = entry.bytes_out;\n for (auto it : entry.rows_merged) {\n httpd::compaction_manager_json::row_merged e;\n e.key = it.first;\n e.value = it.second;\n h.rows_merged.push(std::move(e));\n }\n auto fut = first ? make_ready_future<>() : s.write(\", \");\n first = false;\n return fut.then([&s, h = std::move(h)] {\n return formatter::write(s, h);\n });\n }).then([&s] {\n return s.write(\"]\").then([&s] {\n return s.close();\n });\n });\n });\n });\n };\n return make_ready_future<json::json_return_type>(std::move(f));\n });\n\n cm::get_compaction_info.set(r, [] (std::unique_ptr<request> req) {\n \/\/TBD\n \/\/ FIXME\n warn(unimplemented::cause::API);\n std::vector<cm::compaction_info> res;\n return make_ready_future<json::json_return_type>(res);\n });\n\n}\n\n}\n\n<commit_msg>api\/compaction_manager: do not hold map on the stack<commit_after>\/*\n * Copyright (C) 2015 ScyllaDB\n *\/\n\n\/*\n * This file is part of Scylla.\n *\n * Scylla is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * Scylla is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with Scylla. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n\n#include \"compaction_manager.hh\"\n#include \"sstables\/compaction_manager.hh\"\n#include \"api\/api-doc\/compaction_manager.json.hh\"\n#include \"db\/system_keyspace.hh\"\n#include \"column_family.hh\"\n#include <utility>\n\nnamespace api {\n\nnamespace cm = httpd::compaction_manager_json;\nusing namespace json;\n\nstatic future<json::json_return_type> get_cm_stats(http_context& ctx,\n int64_t compaction_manager::stats::*f) {\n return ctx.db.map_reduce0([f](database& db) {\n return db.get_compaction_manager().get_stats().*f;\n }, int64_t(0), std::plus<int64_t>()).then([](const int64_t& res) {\n return make_ready_future<json::json_return_type>(res);\n });\n}\nstatic std::unordered_map<std::pair<sstring, sstring>, uint64_t, utils::tuple_hash> sum_pending_tasks(std::unordered_map<std::pair<sstring, sstring>, uint64_t, utils::tuple_hash>&& a,\n const std::unordered_map<std::pair<sstring, sstring>, uint64_t, utils::tuple_hash>& b) {\n for (auto&& i : b) {\n if (i.second) {\n a[i.first] += i.second;\n }\n }\n return std::move(a);\n}\n\n\nvoid set_compaction_manager(http_context& ctx, routes& r) {\n cm::get_compactions.set(r, [&ctx] (std::unique_ptr<request> req) {\n return ctx.db.map_reduce0([](database& db) {\n std::vector<cm::summary> summaries;\n const compaction_manager& cm = db.get_compaction_manager();\n\n for (const auto& c : cm.get_compactions()) {\n cm::summary s;\n s.ks = c->ks_name;\n s.cf = c->cf_name;\n s.unit = \"keys\";\n s.task_type = sstables::compaction_name(c->type);\n s.completed = c->total_keys_written;\n s.total = c->total_partitions;\n summaries.push_back(std::move(s));\n }\n return summaries;\n }, std::vector<cm::summary>(), concat<cm::summary>).then([](const std::vector<cm::summary>& res) {\n return make_ready_future<json::json_return_type>(res);\n });\n });\n\n cm::get_pending_tasks_by_table.set(r, [&ctx] (std::unique_ptr<request> req) {\n return ctx.db.map_reduce0([&ctx](database& db) {\n return do_with(std::unordered_map<std::pair<sstring, sstring>, uint64_t, utils::tuple_hash>(), [&ctx, &db](std::unordered_map<std::pair<sstring, sstring>, uint64_t, utils::tuple_hash>& tasks) {\n return do_for_each(db.get_column_families(), [&tasks](const std::pair<utils::UUID, seastar::lw_shared_ptr<table>>& i) {\n table& cf = *i.second.get();\n tasks[std::make_pair(cf.schema()->ks_name(), cf.schema()->cf_name())] = cf.get_compaction_strategy().estimated_pending_compactions(cf);\n return make_ready_future<>();\n }).then([&tasks] {\n return std::move(tasks);\n });\n });\n }, std::unordered_map<std::pair<sstring, sstring>, uint64_t, utils::tuple_hash>(), sum_pending_tasks).then(\n [](const std::unordered_map<std::pair<sstring, sstring>, uint64_t, utils::tuple_hash>& task_map) {\n std::vector<cm::pending_compaction> res;\n res.reserve(task_map.size());\n for (auto i : task_map) {\n cm::pending_compaction task;\n task.ks = i.first.first;\n task.cf = i.first.second;\n task.task = i.second;\n res.emplace_back(std::move(task));\n }\n return make_ready_future<json::json_return_type>(res);\n });\n });\n\n cm::force_user_defined_compaction.set(r, [] (std::unique_ptr<request> req) {\n \/\/TBD\n \/\/ FIXME\n warn(unimplemented::cause::API);\n return make_ready_future<json::json_return_type>(json_void());\n });\n\n cm::stop_compaction.set(r, [&ctx] (std::unique_ptr<request> req) {\n auto type = req->get_query_param(\"type\");\n return ctx.db.invoke_on_all([type] (database& db) {\n auto& cm = db.get_compaction_manager();\n cm.stop_compaction(type);\n }).then([] {\n return make_ready_future<json::json_return_type>(json_void());\n });\n });\n\n cm::get_pending_tasks.set(r, [&ctx] (std::unique_ptr<request> req) {\n return map_reduce_cf(ctx, int64_t(0), [](column_family& cf) {\n return cf.get_compaction_strategy().estimated_pending_compactions(cf);\n }, std::plus<int64_t>());\n });\n\n cm::get_completed_tasks.set(r, [&ctx] (std::unique_ptr<request> req) {\n return get_cm_stats(ctx, &compaction_manager::stats::completed_tasks);\n });\n\n cm::get_total_compactions_completed.set(r, [] (std::unique_ptr<request> req) {\n \/\/ FIXME\n \/\/ We are currently dont have an API for compaction\n \/\/ so returning a 0 as the number of total compaction is ok\n return make_ready_future<json::json_return_type>(0);\n });\n\n cm::get_bytes_compacted.set(r, [] (std::unique_ptr<request> req) {\n \/\/TBD\n \/\/ FIXME\n warn(unimplemented::cause::API);\n return make_ready_future<json::json_return_type>(0);\n });\n\n cm::get_compaction_history.set(r, [] (std::unique_ptr<request> req) {\n std::function<future<>(output_stream<char>&&)> f = [](output_stream<char>&& s) {\n return do_with(output_stream<char>(std::move(s)), true, [] (output_stream<char>& s, bool& first){\n return s.write(\"[\").then([&s, &first] {\n return db::system_keyspace::get_compaction_history([&s, &first](const db::system_keyspace::compaction_history_entry& entry) mutable {\n cm::history h;\n h.id = entry.id.to_sstring();\n h.ks = std::move(entry.ks);\n h.cf = std::move(entry.cf);\n h.compacted_at = entry.compacted_at;\n h.bytes_in = entry.bytes_in;\n h.bytes_out = entry.bytes_out;\n for (auto it : entry.rows_merged) {\n httpd::compaction_manager_json::row_merged e;\n e.key = it.first;\n e.value = it.second;\n h.rows_merged.push(std::move(e));\n }\n auto fut = first ? make_ready_future<>() : s.write(\", \");\n first = false;\n return fut.then([&s, h = std::move(h)] {\n return formatter::write(s, h);\n });\n }).then([&s] {\n return s.write(\"]\").then([&s] {\n return s.close();\n });\n });\n });\n });\n };\n return make_ready_future<json::json_return_type>(std::move(f));\n });\n\n cm::get_compaction_info.set(r, [] (std::unique_ptr<request> req) {\n \/\/TBD\n \/\/ FIXME\n warn(unimplemented::cause::API);\n std::vector<cm::compaction_info> res;\n return make_ready_future<json::json_return_type>(res);\n });\n\n}\n\n}\n\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n#include \"SdlApplication.h\"\n#include \"vgl.h\"\n#include \"LoadShaders.h\"\n\nenum VAO_IDs { Triangles, NumVAOs };\nenum Buffer_IDs { ArrayBuffer, NumBuffers };\nenum Attrib_IDs { vPosition = 0 };\n\nGLuint VAOs[NumVAOs];\nGLuint Buffers[NumBuffers];\n\nconst GLuint NumVertices = 6;\n\n\nclass MyApplication: public SdlApplication {\npublic:\n\/\/ MyApplication();\n int init(int width, int height);\n void Render();\n};\n\n\/\/ MyApplication::MyApplication()\n\/\/ : SdlApplication()\n\/\/ {\n\/\/ }\n\nint MyApplication::init(int width, int height)\n{\n int retval = SdlApplication::init(width, height);\n\n glGenVertexArrays(NumVAOs, VAOs);\n glBindVertexArray(VAOs[Triangles]);\n GLfloat vertices[NumVertices][2] = {\n { -0.90, -0.90 }, \/\/ Triangle 1\n { 0.85, -0.90 },\n { -0.90, 0.85 },\n { 0.90, -0.85 }, \/\/ Triangle 2\n { 0.90, 0.90 },\n { -0.85, 0.90 },\n };\n glGenBuffers(NumBuffers, Buffers);\n glBindBuffer(GL_ARRAY_BUFFER, Buffers[ArrayBuffer]);\n glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);\n\n ShaderInfo shaders[] = {\n { GL_VERTEX_SHADER, \"triangles.vert\" },\n { GL_FRAGMENT_SHADER, \"triangles.frag\" },\n { GL_NONE, NULL}\n };\n GLuint program = LoadShaders(shaders);\n glUseProgram(program);\n glVertexAttribPointer(vPosition, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));\n glEnableVertexAttribArray(vPosition);\n \n return retval;\n}\n\n\nvoid MyApplication::Render()\n{\n \/* This makes our buffer swap syncronized with the monitor's vertical refresh *\/\n SDL_GL_SetSwapInterval(1);\n \n glClear(GL_COLOR_BUFFER_BIT);\n glBindVertexArray(VAOs[Triangles]);\n glDrawArrays(GL_TRIANGLES, 0, NumVertices);\n glFlush();\n \n \/* Swap our back buffer to the front *\/\n SDL_GL_SwapWindow(win);\n}\n\n\n\n\nint main(int argc, char* argv[])\n{\n\tMyApplication app;\n\treturn app.run(640, 480);\n}\n\n<commit_msg>Removed commented out unnecessary mess<commit_after>#include <iostream>\n#include \"SdlApplication.h\"\n#include \"vgl.h\"\n#include \"LoadShaders.h\"\n\nenum VAO_IDs { Triangles, NumVAOs };\nenum Buffer_IDs { ArrayBuffer, NumBuffers };\nenum Attrib_IDs { vPosition = 0 };\n\nGLuint VAOs[NumVAOs];\nGLuint Buffers[NumBuffers];\n\nconst GLuint NumVertices = 6;\n\n\nclass MyApplication: public SdlApplication {\npublic:\n int init(int width, int height);\n void Render();\n};\n\nint MyApplication::init(int width, int height)\n{\n int retval = SdlApplication::init(width, height);\n\n glGenVertexArrays(NumVAOs, VAOs);\n glBindVertexArray(VAOs[Triangles]);\n GLfloat vertices[NumVertices][2] = {\n { -0.90, -0.90 }, \/\/ Triangle 1\n { 0.85, -0.90 },\n { -0.90, 0.85 },\n { 0.90, -0.85 }, \/\/ Triangle 2\n { 0.90, 0.90 },\n { -0.85, 0.90 },\n };\n glGenBuffers(NumBuffers, Buffers);\n glBindBuffer(GL_ARRAY_BUFFER, Buffers[ArrayBuffer]);\n glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);\n\n ShaderInfo shaders[] = {\n { GL_VERTEX_SHADER, \"triangles.vert\" },\n { GL_FRAGMENT_SHADER, \"triangles.frag\" },\n { GL_NONE, NULL}\n };\n GLuint program = LoadShaders(shaders);\n glUseProgram(program);\n glVertexAttribPointer(vPosition, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));\n glEnableVertexAttribArray(vPosition);\n \n return retval;\n}\n\n\nvoid MyApplication::Render()\n{\n \/* This makes our buffer swap syncronized with the monitor's vertical refresh *\/\n SDL_GL_SetSwapInterval(1);\n \n glClear(GL_COLOR_BUFFER_BIT);\n glBindVertexArray(VAOs[Triangles]);\n glDrawArrays(GL_TRIANGLES, 0, NumVertices);\n glFlush();\n \n \/* Swap our back buffer to the front *\/\n SDL_GL_SwapWindow(win);\n}\n\n\n\n\nint main(int argc, char* argv[])\n{\n\tMyApplication app;\n\treturn app.run(640, 480);\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/*=========================================================================\n *\n * Copyright Insight Software Consortium\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0.txt\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *=========================================================================*\/\n#include \"itkCommand.h\"\n\nnamespace itk\n{\n Command::Command() = default;\n\n Command::~Command() = default;\n\n CStyleCommand::CStyleCommand()\n\n {}\n\n CStyleCommand::~CStyleCommand()\n {\n if ( m_ClientDataDeleteCallback )\n {\n m_ClientDataDeleteCallback(m_ClientData);\n }\n }\n\n void CStyleCommand::SetClientData(void *cd)\n {\n m_ClientData = cd;\n }\n void CStyleCommand::SetCallback(FunctionPointer f)\n {\n m_Callback = f;\n }\n void CStyleCommand::SetConstCallback(ConstFunctionPointer f)\n {\n m_ConstCallback = f;\n }\n void CStyleCommand::SetClientDataDeleteCallback(DeleteDataFunctionPointer f)\n {\n m_ClientDataDeleteCallback = f;\n }\n\n void CStyleCommand::Execute(Object *caller, const EventObject & event)\n {\n if ( m_Callback )\n {\n m_Callback(caller, event, m_ClientData);\n }\n }\n\n void CStyleCommand::Execute(const Object *caller, const EventObject & event)\n {\n if ( m_ConstCallback )\n {\n m_ConstCallback(caller, event, m_ClientData);\n }\n }\n}\n<commit_msg>STYLE: Use = default for trivial constructors<commit_after>\/*=========================================================================\n *\n * Copyright Insight Software Consortium\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0.txt\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *=========================================================================*\/\n#include \"itkCommand.h\"\n\nnamespace itk\n{\n Command::Command() = default;\n\n Command::~Command() = default;\n\n CStyleCommand::CStyleCommand() = default;\n\n CStyleCommand::~CStyleCommand()\n {\n if ( m_ClientDataDeleteCallback )\n {\n m_ClientDataDeleteCallback(m_ClientData);\n }\n }\n\n void CStyleCommand::SetClientData(void *cd)\n {\n m_ClientData = cd;\n }\n void CStyleCommand::SetCallback(FunctionPointer f)\n {\n m_Callback = f;\n }\n void CStyleCommand::SetConstCallback(ConstFunctionPointer f)\n {\n m_ConstCallback = f;\n }\n void CStyleCommand::SetClientDataDeleteCallback(DeleteDataFunctionPointer f)\n {\n m_ClientDataDeleteCallback = f;\n }\n\n void CStyleCommand::Execute(Object *caller, const EventObject & event)\n {\n if ( m_Callback )\n {\n m_Callback(caller, event, m_ClientData);\n }\n }\n\n void CStyleCommand::Execute(const Object *caller, const EventObject & event)\n {\n if ( m_ConstCallback )\n {\n m_ConstCallback(caller, event, m_ClientData);\n }\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 2016 Jari Saukkonen\n *\n * Permission is hereby granted, free of charge, to any person obtaining\n * a copy of this software and associated documentation files (the\n * \"Software\"), to deal in the Software without restriction, including\n * without limitation the rights to use, copy, modify, merge, publish,\n * distribute, sublicense, and\/or sell copies of the Software, and to\n * permit persons to whom the Software is furnished to do so, subject to\n * the following conditions:\n *\n * The above copyright notice and this permission notice shall be included\n * in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\n * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\n * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n *\/\n\n#include \"PowerConsumptionLog.h\"\n\nPowerConsumptionLog::PowerConsumptionLog() :\n m_pos(0),\n m_windowPos(0),\n m_overloadThreshold(5000) {\n memset(&m_data[0], 0, 16);\n memset(&m_window[0], 0, 16);\n}\n\nvoid PowerConsumptionLog::measure(unsigned int milliAmps) {\n m_window[m_windowPos++ & 0xF] = milliAmps;\n}\n\nvoid PowerConsumptionLog::appendCurrentMeasurement() {\n unsigned int avg = 0;\n for (int i = 1; i <= 10; i++) {\n avg += m_window[(m_windowPos-i) & 0xF];\n }\n m_data[m_pos++ & 0xF] = avg\/10;\n}\n\nbool PowerConsumptionLog::isOverload(unsigned int threshold) const {\n for (int i = 1; i <= 5; i++) {\n if (m_data[(m_pos-i) % 0xF] < threshold) {\n return false;\n }\n }\n return true;\n}\n\nvoid PowerConsumptionLog::report(NMEASerial& serial) {\n String message = \"POWER,\";\n for (int i = 1; i <= 10; i++) {\n message += String(m_data[(m_pos-i) % 0xF]) + \",\";\n }\n serial.print(message.substring(0, message.length()-1));\n}\n<commit_msg>Make overload condition more sensitive<commit_after>\/*\n * Copyright (c) 2016 Jari Saukkonen\n *\n * Permission is hereby granted, free of charge, to any person obtaining\n * a copy of this software and associated documentation files (the\n * \"Software\"), to deal in the Software without restriction, including\n * without limitation the rights to use, copy, modify, merge, publish,\n * distribute, sublicense, and\/or sell copies of the Software, and to\n * permit persons to whom the Software is furnished to do so, subject to\n * the following conditions:\n *\n * The above copyright notice and this permission notice shall be included\n * in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\n * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\n * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n *\/\n\n#include \"PowerConsumptionLog.h\"\n\nPowerConsumptionLog::PowerConsumptionLog() :\n m_pos(0),\n m_windowPos(0),\n m_overloadThreshold(5000) {\n memset(&m_data[0], 0, 16);\n memset(&m_window[0], 0, 16);\n}\n\nvoid PowerConsumptionLog::measure(unsigned int milliAmps) {\n m_window[m_windowPos++ & 0xF] = milliAmps;\n}\n\nvoid PowerConsumptionLog::appendCurrentMeasurement() {\n unsigned int avg = 0;\n for (int i = 1; i <= 10; i++) {\n avg += m_window[(m_windowPos-i) & 0xF];\n }\n m_data[m_pos++ & 0xF] = avg\/10;\n}\n\nbool PowerConsumptionLog::isOverload(unsigned int threshold) const {\n for (int i = 1; i <= 3; i++) {\n if (m_data[(m_pos-i) % 0xF] < threshold) {\n return false;\n }\n }\n return true;\n}\n\nvoid PowerConsumptionLog::report(NMEASerial& serial) {\n String message = \"POWER,\";\n for (int i = 1; i <= 10; i++) {\n message += String(m_data[(m_pos-i) % 0xF]) + \",\";\n }\n serial.print(message.substring(0, message.length()-1));\n}\n<|endoftext|>"} {"text":"<commit_before>#pragma once\n\n#include <DirectXMath.h>\n#include <typeinfo>\n\nnamespace dx\n{\n struct UpdateArgs;\n class Game;\n class ComponentBase;\n\n inline constexpr std::uint32_t kMaxComponentCount = 8;\n\n template<typename T>\n struct is_unique_ptr : std::false_type\n {};\n\n template<typename T, typename D>\n struct is_unique_ptr<std::unique_ptr<T, D>> : std::true_type\n {};\n\n class Object final\n {\n public:\n template<typename... ComponentsT>\n Object(std::unique_ptr<ComponentsT>... components)\n {\n AddComponents(std::move(components)...);\n }\n\n template<typename... ComponentsT, typename = std::enable_if_t<std::conjunction_v<\n std::negation<std::disjunction<is_unique_ptr<ComponentsT>,\n std::is_same<std::decay_t<ComponentsT>, Object>>>...>>>\n Object(ComponentsT&&... components)\n {\n AddComponents(std::make_unique<std::decay_t<ComponentsT>>(std::forward<ComponentsT>(components))...);\n }\n\n template<typename T>\n T* GetComponent() const\n {\n return dynamic_cast<T*>(GetComponent(typeid(T)));\n }\n\n ComponentBase* GetComponent(const std::type_info& type) const;\n\n template<typename T>\n T& AddComponent(std::unique_ptr<T> component)\n {\n auto& ret = *component;\n AddComponentInternal(std::move(component));\n return ret;\n }\n\n template<typename... Args>\n void AddComponents(std::unique_ptr<Args>... components)\n {\n m_components.reserve(sizeof...(components));\n (AddComponentInternal(std::move(components)), ...);\n }\n\n private:\n void AddComponentInternal(std::unique_ptr<ComponentBase> component);\n\n boost::container::static_vector<std::unique_ptr<ComponentBase>, kMaxComponentCount>\n m_components;\n };\n}<commit_msg>decay<commit_after>#pragma once\n\n#include <DirectXMath.h>\n#include <typeinfo>\n\nnamespace dx\n{\n struct UpdateArgs;\n class Game;\n class ComponentBase;\n\n inline constexpr std::uint32_t kMaxComponentCount = 8;\n\n template<typename T>\n struct is_unique_ptr : std::false_type\n {};\n\n template<typename T, typename D>\n struct is_unique_ptr<std::unique_ptr<T, D>> : std::true_type\n {};\n\n class Object final\n {\n public:\n template<typename... ComponentsT>\n Object(std::unique_ptr<ComponentsT>... components)\n {\n AddComponents(std::move(components)...);\n }\n\n template<typename... ComponentsT, typename = std::enable_if_t<std::conjunction_v<\n std::negation<std::disjunction<is_unique_ptr<std::decay_t<ComponentsT>>,\n std::is_same<std::decay_t<ComponentsT>, Object>>>...>>>\n Object(ComponentsT&&... components)\n {\n AddComponents(std::make_unique<std::decay_t<ComponentsT>>(std::forward<ComponentsT>(components))...);\n }\n\n template<typename T>\n T* GetComponent() const\n {\n return dynamic_cast<T*>(GetComponent(typeid(T)));\n }\n\n ComponentBase* GetComponent(const std::type_info& type) const;\n\n template<typename T>\n T& AddComponent(std::unique_ptr<T> component)\n {\n auto& ret = *component;\n AddComponentInternal(std::move(component));\n return ret;\n }\n\n template<typename T, typename... Args,\n typename =\n std::enable_if_t <\n !std::disjunction_v<is_unique_ptr<std::decay_t<Args>>...>>>\n T& AddComponent(Args&&... args)\n {\n return AddComponent<T>(std::make_unique<T>(std::forward<Args>(args)...));\n }\n\n template<typename... Args>\n void AddComponents(std::unique_ptr<Args>... components)\n {\n m_components.reserve(sizeof...(components));\n (AddComponentInternal(std::move(components)), ...);\n }\n\n private:\n void AddComponentInternal(std::unique_ptr<ComponentBase> component);\n\n boost::container::static_vector<std::unique_ptr<ComponentBase>, kMaxComponentCount>\n m_components;\n };\n}<|endoftext|>"} {"text":"<commit_before>\/**\n * Non-metric Space Library\n *\n * Main developers: Bilegsaikhan Naidan, Leonid Boytsov, Yury Malkov, Ben Frederickson, David Novak\n *\n * For the complete list of contributors and further details see:\n * https:\/\/github.com\/searchivarius\/NonMetricSpaceLib\n *\n * Copyright (c) 2013-2018\n *\n * This code is released under the\n * Apache License Version 2.0 http:\/\/www.apache.org\/licenses\/.\n *\n *\/\n#include <iostream>\n#include <string>\n\n#include \"space.h\"\n#include \"params.h\"\n#include \"init.h\"\n#include \"report_intr_dim.h\"\n#include \"spacefactory.h\"\n#include \"cmd_options.h\"\n#include \"my_isnan_isinf.h\"\n\nusing namespace similarity;\nusing namespace std;\n\nconst unsigned defaultSampleQty = 1000000;\n\ntemplate <typename dist_t>\nvoid ComputeMuDeffect(const Space<dist_t>& space,\n const ObjectVector& dataset,\n double & dleft, double & dright,\n size_t SampleQty = 1000000) {\n dleft = dright = -1;\n for (size_t n = 0; n < SampleQty; ++n) {\n size_t r1 = RandomInt() % dataset.size();\n size_t r2 = RandomInt() % dataset.size();\n size_t r3 = RandomInt() % dataset.size();\n CHECK(r1 < dataset.size());\n CHECK(r2 < dataset.size());\n CHECK(r3 < dataset.size());\n const Object* q = dataset[r1];\n const Object* a = dataset[r2];\n const Object* b = dataset[r3];\n {\n dist_t d1 = space.IndexTimeDistance(q, a);\n dist_t d2 = space.IndexTimeDistance(q, b);\n dist_t d3 = space.IndexTimeDistance(a, b);\n if (my_isnan(d1) || my_isnan(d2) || my_isnan(d3)) {\n throw runtime_error(\"!!! Bug: a distance returned NAN!\");\n }\n if (d3 != 0) {\n dright = max(dright, (double)fabs(double(d1)-double(d2))\/double(d3));\n }\n }\n {\n dist_t d1 = space.IndexTimeDistance(a, q);\n dist_t d2 = space.IndexTimeDistance(b, q);\n dist_t d3 = space.IndexTimeDistance(b, a);\n if (my_isnan(d1) || my_isnan(d2) || my_isnan(d3)) {\n throw runtime_error(\"!!! Bug: a distance returned NAN!\");\n }\n if (d3 != 0) {\n dleft = max(dleft, (double)fabs(double(d1)-double(d2))\/double(d3));\n }\n }\n }\n}\n\ntemplate <typename dist_t>\nvoid TestSpace(\n string spaceDesc,\n string dataFile,\n bool compMuDeffect,\n unsigned maxNumData,\n unsigned sampleQty,\n string sampleFile\n ) {\n string spaceType;\n vector<string> vSpaceArgs;\n\n ParseSpaceArg(spaceDesc, spaceType, vSpaceArgs);\n AnyParams spaceParams({AnyParams(vSpaceArgs)});\n\n unique_ptr<Space<dist_t>> space(SpaceFactoryRegistry<dist_t>::\n Instance().CreateSpace(spaceType, spaceParams));\n\n ObjectVector data;\n vector<string> tmp;\n unique_ptr<DataFileInputState> inpState(space->ReadDataset(data, tmp, dataFile, maxNumData));\n space->UpdateParamsFromFile(*inpState);\n vector<double> dist;\n\n \/\/ Prints the report\n ReportIntrinsicDimensionality(\"********\", *space, data, dist, sampleQty);\n if (!sampleFile.empty()) {\n ofstream of(sampleFile);\n CHECK_MSG(of, \"Cannot open for writing file: \" + sampleFile);\n of.exceptions ( std::ifstream::failbit | std::ifstream::badbit );\n \n for (size_t i = 0; i < dist.size(); ++i) {\n if (i) of << \"\\t\";\n of << dist[i];\n } \n of << std::endl;\n }\n if (compMuDeffect) {\n double dleft, dright;\n ComputeMuDeffect<dist_t>(\n *space,\n data,\n dleft, dright,\n sampleQty\n );\n LOG(LIB_INFO) << \"### left mu-defect. : \" << dleft << \" right mu-defect. :\" << dright;\n }\n}\n\nint main(int argc, char* argv[]) {\n string spaceDesc, distType;\n string dataFile;\n string sampleFile;\n unsigned maxNumData;\n unsigned sampleQty;\n bool compMuDeffect;\n\n CmdOptions cmd_options;\n\n cmd_options.Add(new CmdParam(\"spaceType,s\", \"space type, e.g., l1, l2, lp:p=0.5\",\n &spaceDesc, true));\n cmd_options.Add(new CmdParam(\"distType\", \"distance value type: int, float, double\",\n &distType, false, DIST_TYPE_FLOAT));\n cmd_options.Add(new CmdParam(\"dataFile,i\", \"input data file\",\n &dataFile, true));\n cmd_options.Add(new CmdParam(\"maxNumData\", \"if non-zero, only the first maxNumData elements are used\",\n &maxNumData, false, 0));\n cmd_options.Add(new CmdParam(\"sampleQty\", \"a number of samples (a sample is a pair of data points)\",\n &sampleQty, false, defaultSampleQty));\n cmd_options.Add(new CmdParam(\"muDeffect,m\", \"estimate the left and the right mu deffectiveness\",\n &compMuDeffect, false, false));\n cmd_options.Add(new CmdParam(\"sampleFile\", \"optional output sample file\",\n &sampleFile, false, \"\"));\n\n try {\n cmd_options.Parse(argc, argv);\n\n if (!DoesFileExist(dataFile)) {\n PREPARE_RUNTIME_ERR(err) << \"data file \" << dataFile << \" doesn't exist\";\n THROW_RUNTIME_ERR(err);\n }\n\n initLibrary(0, LIB_LOGSTDERR);\n\n if (DIST_TYPE_INT == distType) {\n TestSpace<int>(\n spaceDesc,\n dataFile,\n compMuDeffect,\n maxNumData,\n sampleQty,\n sampleFile\n );\n } else if (DIST_TYPE_FLOAT == distType) {\n TestSpace<float>(\n spaceDesc,\n dataFile,\n compMuDeffect,\n maxNumData,\n sampleQty,\n sampleFile\n );\n } else if (DIST_TYPE_DOUBLE == distType) {\n TestSpace<double>(\n spaceDesc,\n dataFile,\n compMuDeffect,\n maxNumData,\n sampleQty,\n sampleFile\n );\n }\n\n } catch (const CmdParserException& e) {\n cmd_options.ToString();\n std::cout.flush();\n LOG(LIB_FATAL) << e.what();\n } catch (const exception& e) {\n cmd_options.ToString();\n std::cout.flush();\n LOG(LIB_FATAL) << e.what();\n }\n\n return 0;\n}\n<commit_msg>tiny fix in report_intr_dim output format.<commit_after>\/**\n * Non-metric Space Library\n *\n * Main developers: Bilegsaikhan Naidan, Leonid Boytsov, Yury Malkov, Ben Frederickson, David Novak\n *\n * For the complete list of contributors and further details see:\n * https:\/\/github.com\/searchivarius\/NonMetricSpaceLib\n *\n * Copyright (c) 2013-2018\n *\n * This code is released under the\n * Apache License Version 2.0 http:\/\/www.apache.org\/licenses\/.\n *\n *\/\n#include <iostream>\n#include <string>\n\n#include \"space.h\"\n#include \"params.h\"\n#include \"init.h\"\n#include \"report_intr_dim.h\"\n#include \"spacefactory.h\"\n#include \"cmd_options.h\"\n#include \"my_isnan_isinf.h\"\n\nusing namespace similarity;\nusing namespace std;\n\nconst unsigned defaultSampleQty = 1000000;\n\ntemplate <typename dist_t>\nvoid ComputeMuDeffect(const Space<dist_t>& space,\n const ObjectVector& dataset,\n double & dleft, double & dright,\n size_t SampleQty = 1000000) {\n dleft = dright = -1;\n for (size_t n = 0; n < SampleQty; ++n) {\n size_t r1 = RandomInt() % dataset.size();\n size_t r2 = RandomInt() % dataset.size();\n size_t r3 = RandomInt() % dataset.size();\n CHECK(r1 < dataset.size());\n CHECK(r2 < dataset.size());\n CHECK(r3 < dataset.size());\n const Object* q = dataset[r1];\n const Object* a = dataset[r2];\n const Object* b = dataset[r3];\n {\n dist_t d1 = space.IndexTimeDistance(q, a);\n dist_t d2 = space.IndexTimeDistance(q, b);\n dist_t d3 = space.IndexTimeDistance(a, b);\n if (my_isnan(d1) || my_isnan(d2) || my_isnan(d3)) {\n throw runtime_error(\"!!! Bug: a distance returned NAN!\");\n }\n if (d3 != 0) {\n dright = max(dright, (double)fabs(double(d1)-double(d2))\/double(d3));\n }\n }\n {\n dist_t d1 = space.IndexTimeDistance(a, q);\n dist_t d2 = space.IndexTimeDistance(b, q);\n dist_t d3 = space.IndexTimeDistance(b, a);\n if (my_isnan(d1) || my_isnan(d2) || my_isnan(d3)) {\n throw runtime_error(\"!!! Bug: a distance returned NAN!\");\n }\n if (d3 != 0) {\n dleft = max(dleft, (double)fabs(double(d1)-double(d2))\/double(d3));\n }\n }\n }\n}\n\ntemplate <typename dist_t>\nvoid TestSpace(\n string spaceDesc,\n string dataFile,\n bool compMuDeffect,\n unsigned maxNumData,\n unsigned sampleQty,\n string sampleFile\n ) {\n string spaceType;\n vector<string> vSpaceArgs;\n\n ParseSpaceArg(spaceDesc, spaceType, vSpaceArgs);\n AnyParams spaceParams({AnyParams(vSpaceArgs)});\n\n unique_ptr<Space<dist_t>> space(SpaceFactoryRegistry<dist_t>::\n Instance().CreateSpace(spaceType, spaceParams));\n\n ObjectVector data;\n vector<string> tmp;\n unique_ptr<DataFileInputState> inpState(space->ReadDataset(data, tmp, dataFile, maxNumData));\n space->UpdateParamsFromFile(*inpState);\n vector<double> dist;\n\n \/\/ Prints the report\n ReportIntrinsicDimensionality(\"********\", *space, data, dist, sampleQty);\n if (!sampleFile.empty()) {\n ofstream of(sampleFile);\n CHECK_MSG(of, \"Cannot open for writing file: \" + sampleFile);\n of.exceptions ( std::ifstream::failbit | std::ifstream::badbit );\n \n for (size_t i = 0; i < dist.size(); ++i) {\n if (i) of << \",\";\n of << dist[i];\n } \n of << std::endl;\n }\n if (compMuDeffect) {\n double dleft, dright;\n ComputeMuDeffect<dist_t>(\n *space,\n data,\n dleft, dright,\n sampleQty\n );\n LOG(LIB_INFO) << \"### left mu-defect. : \" << dleft << \" right mu-defect. :\" << dright;\n }\n}\n\nint main(int argc, char* argv[]) {\n string spaceDesc, distType;\n string dataFile;\n string sampleFile;\n unsigned maxNumData;\n unsigned sampleQty;\n bool compMuDeffect;\n\n CmdOptions cmd_options;\n\n cmd_options.Add(new CmdParam(\"spaceType,s\", \"space type, e.g., l1, l2, lp:p=0.5\",\n &spaceDesc, true));\n cmd_options.Add(new CmdParam(\"distType\", \"distance value type: int, float, double\",\n &distType, false, DIST_TYPE_FLOAT));\n cmd_options.Add(new CmdParam(\"dataFile,i\", \"input data file\",\n &dataFile, true));\n cmd_options.Add(new CmdParam(\"maxNumData\", \"if non-zero, only the first maxNumData elements are used\",\n &maxNumData, false, 0));\n cmd_options.Add(new CmdParam(\"sampleQty\", \"a number of samples (a sample is a pair of data points)\",\n &sampleQty, false, defaultSampleQty));\n cmd_options.Add(new CmdParam(\"muDeffect,m\", \"estimate the left and the right mu deffectiveness\",\n &compMuDeffect, false, false));\n cmd_options.Add(new CmdParam(\"sampleFile\", \"optional output sample file\",\n &sampleFile, false, \"\"));\n\n try {\n cmd_options.Parse(argc, argv);\n\n if (!DoesFileExist(dataFile)) {\n PREPARE_RUNTIME_ERR(err) << \"data file \" << dataFile << \" doesn't exist\";\n THROW_RUNTIME_ERR(err);\n }\n\n initLibrary(0, LIB_LOGSTDERR);\n\n if (DIST_TYPE_INT == distType) {\n TestSpace<int>(\n spaceDesc,\n dataFile,\n compMuDeffect,\n maxNumData,\n sampleQty,\n sampleFile\n );\n } else if (DIST_TYPE_FLOAT == distType) {\n TestSpace<float>(\n spaceDesc,\n dataFile,\n compMuDeffect,\n maxNumData,\n sampleQty,\n sampleFile\n );\n } else if (DIST_TYPE_DOUBLE == distType) {\n TestSpace<double>(\n spaceDesc,\n dataFile,\n compMuDeffect,\n maxNumData,\n sampleQty,\n sampleFile\n );\n }\n\n } catch (const CmdParserException& e) {\n cmd_options.ToString();\n std::cout.flush();\n LOG(LIB_FATAL) << e.what();\n } catch (const exception& e) {\n cmd_options.ToString();\n std::cout.flush();\n LOG(LIB_FATAL) << e.what();\n }\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>#include <qstringlist.h>\n#include <QEvent>\n\n#include \"dbus_service.h\"\n#include \"defines.h\"\n#include \"QsLog.h\"\n\nDBusService::DBusService(const QString &serviceName, QObject *parent) :\n\tQObject(parent),\n\tmDbusServiceName(serviceName),\n\tmServiceType(getDeviceType(serviceName)),\n\tmConnected(true),\n\tmDeviceInstance(serviceName, \"\/DeviceInstance\", DBUS_CONNECTION)\n{\n\tmDeviceInstance.getValue();\n\tQLOG_INFO() << \"[DBusService] DeviceInstance of \" << serviceName << \"=\" << mDeviceInstance.getValue().toInt() << \"with type\" << mServiceType;\n}\n\nQString DBusService::getDeviceType(const QString &name)\n{\n\tQStringList elements = name.split(\".\");\n\tif (elements.count() < 3)\n\t\treturn \"Unkown\";\n\n\treturn elements[2];\n}\n\nvoid DBusService::setDeviceType(const QString &name)\n{\n\tmServiceType = getDeviceType(name);\n}\n\nvoid DBusService::registerObjects(const QStringList &pathList)\n{\n\tforeach(const QString &path, pathList)\n\t\tregisterObject(path);\n}\n\nvoid DBusService::registerObject(const QString &path)\n{\n\tQLOG_INFO() << \"[DBusService] registerObject \" << mDbusServiceName << path;\n\tBusItemCons * busitem = new BusItemCons(mDbusServiceName, path, DBUS_CONNECTION);\n\tmBusItems.insert(path, busitem);\n}\n\nQVariant DBusService::getValue(const QString path)\n{\n\tif (mBusItems.contains(path)) {\n\t\treturn mBusItems.value(path)->getValue();\n\t} else\n\t\treturn QVariant();\n}\n\nbool DBusService::setValue(const QString path, const QVariant value)\n{\n\tif (mBusItems.contains(path)) {\n\t\tQLOG_TRACE() << \"[DBusService] Set value\" << path << value.toString();\n\t\treturn mBusItems.value(path)->setValue(value) == 0 ? true : false;\n\t} else\n\t\treturn false;\n}\n<commit_msg>dbus_service: removed trace log<commit_after>#include <qstringlist.h>\n#include <QEvent>\n\n#include \"dbus_service.h\"\n#include \"defines.h\"\n#include \"QsLog.h\"\n\nDBusService::DBusService(const QString &serviceName, QObject *parent) :\n\tQObject(parent),\n\tmDbusServiceName(serviceName),\n\tmServiceType(getDeviceType(serviceName)),\n\tmConnected(true),\n\tmDeviceInstance(serviceName, \"\/DeviceInstance\", DBUS_CONNECTION)\n{\n\tmDeviceInstance.getValue();\n\tQLOG_INFO() << \"[DBusService] DeviceInstance of \" << serviceName << \"=\" << mDeviceInstance.getValue().toInt() << \"with type\" << mServiceType;\n}\n\nQString DBusService::getDeviceType(const QString &name)\n{\n\tQStringList elements = name.split(\".\");\n\tif (elements.count() < 3)\n\t\treturn \"Unkown\";\n\n\treturn elements[2];\n}\n\nvoid DBusService::setDeviceType(const QString &name)\n{\n\tmServiceType = getDeviceType(name);\n}\n\nvoid DBusService::registerObjects(const QStringList &pathList)\n{\n\tforeach(const QString &path, pathList)\n\t\tregisterObject(path);\n}\n\nvoid DBusService::registerObject(const QString &path)\n{\n\tQLOG_INFO() << \"[DBusService] registerObject \" << mDbusServiceName << path;\n\tBusItemCons * busitem = new BusItemCons(mDbusServiceName, path, DBUS_CONNECTION);\n\tmBusItems.insert(path, busitem);\n}\n\nQVariant DBusService::getValue(const QString path)\n{\n\tif (mBusItems.contains(path)) {\n\t\treturn mBusItems.value(path)->getValue();\n\t} else\n\t\treturn QVariant();\n}\n\nbool DBusService::setValue(const QString path, const QVariant value)\n{\n\tif (mBusItems.contains(path))\n\t\treturn mBusItems.value(path)->setValue(value) == 0 ? true : false;\n\telse\n\t\treturn false;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ @(#)root\/eve:$Id$\n\/\/ Author: Timur Pocheptsov\n\n\/*************************************************************************\n * Copyright (C) 1995-2007, Rene Brun and Fons Rademakers. *\n * All rights reserved. *\n * *\n * For the licensing terms see $ROOTSYS\/LICENSE. *\n * For the list of contributors see $ROOTSYS\/README\/CREDITS. *\n *************************************************************************\/\n#include \"TGLPlotCamera.h\"\n#include \"TGLIncludes.h\"\n#include \"TVirtualGL.h\"\n\n\/\/______________________________________________________________________________\n\/\/\n\/\/ Camera for TGLPlotPainter and sub-classes.\n\nClassImp(TGLPlotCamera);\n\n\/\/______________________________________________________________________________\nTGLPlotCamera::TGLPlotCamera() :\n fZoom(1.), fShift(1.5), fCenter(),\n fVpChanged(kFALSE)\n{\n \/\/Construct camera for plot painters.\n fOrthoBox[0] = 1.;\n fOrthoBox[1] = 1.;\n fOrthoBox[2] = -100.;\n fOrthoBox[3] = 100.;\n}\n\n\/\/______________________________________________________________________________\nvoid TGLPlotCamera::SetViewport(const TGLRect &vp)\n{\n \/\/Setup viewport, if it was changed, plus reset arcball.\n \n if (vp.Width() != fViewport.Width() || vp.Height() != fViewport.Height() ||\n vp.X() != fViewport.X() || vp.Y() != fViewport.Y())\n {\n fVpChanged = kTRUE;\n fArcBall.SetBounds(vp.Width(), vp.Height());\n fViewport = vp;\n \n } else\n fVpChanged = kFALSE;\n}\n\n\/\/______________________________________________________________________________\nvoid TGLPlotCamera::SetViewVolume(const TGLVertex3 *\/*box*\/)\n{\n \/\/'box' is the TGLPlotPainter's back box's coordinates.\n\/* fCenter[0] = (box[0].X() + box[1].X()) \/ 2;\n fCenter[1] = (box[0].Y() + box[2].Y()) \/ 2;\n fCenter[2] = (box[0].Z() + box[4].Z()) \/ 2;\n const Double_t maxDim = box[1].X() - box[0].X();\n fOrthoBox[0] = maxDim;\n fOrthoBox[1] = maxDim;\n fOrthoBox[2] = -100 * maxDim;\/\/100?\n fOrthoBox[3] = 100 * maxDim;\n fShift = maxDim * 1.5;*\/\n}\n\n\/\/______________________________________________________________________________\nvoid TGLPlotCamera::StartRotation(Int_t px, Int_t py)\n{\n \/\/User clicks somewhere (px, py).\n fArcBall.Click(TPoint(px, py));\n}\n\n\/\/______________________________________________________________________________\nvoid TGLPlotCamera::RotateCamera(Int_t px, Int_t py)\n{\n \/\/Mouse movement.\n fArcBall.Drag(TPoint(px, py));\n}\n\n\/\/______________________________________________________________________________\nvoid TGLPlotCamera::StartPan(Int_t px, Int_t py)\n{\n \/\/User clicks somewhere (px, py).\n fMousePos.fX = px;\n fMousePos.fY = fViewport.Height() - py;\n}\n\n\/\/______________________________________________________________________________\nvoid TGLPlotCamera::Pan(Int_t px, Int_t py)\n{\n \/\/Pan camera.\n py = fViewport.Height() - py;\n \/\/Extract gl matrices.\n Double_t mv[16] = {0.};\n glGetDoublev(GL_MODELVIEW_MATRIX, mv);\n Double_t pr[16] = {0.};\n glGetDoublev(GL_PROJECTION_MATRIX, pr);\n Int_t vp[] = {0, 0, fViewport.Width(), fViewport.Height()};\n \/\/Adjust pan vector.\n TGLVertex3 start, end;\n gluUnProject(fMousePos.fX, fMousePos.fY, 1., mv, pr, vp, &start.X(), &start.Y(), &start.Z());\n gluUnProject(px, py, 1., mv, pr, vp, &end.X(), &end.Y(), &end.Z());\n fTruck += (start - end) \/= 2.;\n fMousePos.fX = px;\n fMousePos.fY = py;\n}\n\n\/\/______________________________________________________________________________\nvoid TGLPlotCamera::SetCamera()const\n{\n \/\/Viewport and projection.\n glViewport(fViewport.X(), fViewport.Y(), fViewport.Width(), fViewport.Height());\n\n glMatrixMode(GL_PROJECTION);\n glLoadIdentity();\n glOrtho(\n -fOrthoBox[0] * fZoom,\n fOrthoBox[0] * fZoom,\n -fOrthoBox[1] * fZoom,\n fOrthoBox[1] * fZoom,\n fOrthoBox[2],\n fOrthoBox[3]\n );\n\n glMatrixMode(GL_MODELVIEW);\n glLoadIdentity();\n}\n\n\/\/______________________________________________________________________________\nvoid TGLPlotCamera::Apply(Double_t phi, Double_t theta)const\n{\n \/\/Applies rotations and translations before drawing\n glTranslated(0., 0., -fShift);\n glMultMatrixd(fArcBall.GetRotMatrix());\n glRotated(theta - 90., 1., 0., 0.);\n glRotated(phi, 0., 0., 1.);\n glTranslated(-fTruck[0], -fTruck[1], -fTruck[2]);\n\/\/ glTranslated(-fCenter[0], -fCenter[1], -fCenter[2]);\n}\n\n\/\/______________________________________________________________________________\nInt_t TGLPlotCamera::GetX()const\n{\n \/\/viewport[0]\n return fViewport.X();\n}\n\n\/\/______________________________________________________________________________\nInt_t TGLPlotCamera::GetY()const\n{\n \/\/viewport[1]\n return fViewport.Y();\n}\n\n\/\/______________________________________________________________________________\nInt_t TGLPlotCamera::GetWidth()const\n{\n \/\/viewport[2]\n return Int_t(fViewport.Width());\n}\n\n\/\/______________________________________________________________________________\nInt_t TGLPlotCamera::GetHeight()const\n{\n \/\/viewport[3]\n return Int_t(fViewport.Height());\n}\n\n\/\/______________________________________________________________________________\nvoid TGLPlotCamera::ZoomIn()\n{\n \/\/Zoom in.\n fZoom \/= 1.2;\n}\n\n\/\/______________________________________________________________________________\nvoid TGLPlotCamera::ZoomOut()\n{\n \/\/Zoom out.\n fZoom *= 1.2;\n}\n<commit_msg>Fix a compilation warning on Windows<commit_after>\/\/ @(#)root\/eve:$Id$\n\/\/ Author: Timur Pocheptsov\n\n\/*************************************************************************\n * Copyright (C) 1995-2007, Rene Brun and Fons Rademakers. *\n * All rights reserved. *\n * *\n * For the licensing terms see $ROOTSYS\/LICENSE. *\n * For the list of contributors see $ROOTSYS\/README\/CREDITS. *\n *************************************************************************\/\n#include \"TGLPlotCamera.h\"\n#include \"TGLIncludes.h\"\n#include \"TVirtualGL.h\"\n\n\/\/______________________________________________________________________________\n\/\/\n\/\/ Camera for TGLPlotPainter and sub-classes.\n\nClassImp(TGLPlotCamera);\n\n\/\/______________________________________________________________________________\nTGLPlotCamera::TGLPlotCamera() :\n fZoom(1.), fShift(1.5), fCenter(),\n fVpChanged(kFALSE)\n{\n \/\/Construct camera for plot painters.\n fOrthoBox[0] = 1.;\n fOrthoBox[1] = 1.;\n fOrthoBox[2] = -100.;\n fOrthoBox[3] = 100.;\n}\n\n\/\/______________________________________________________________________________\nvoid TGLPlotCamera::SetViewport(const TGLRect &vp)\n{\n \/\/Setup viewport, if it was changed, plus reset arcball.\n \n if (vp.Width() != fViewport.Width() || vp.Height() != fViewport.Height() ||\n vp.X() != fViewport.X() || vp.Y() != fViewport.Y())\n {\n fVpChanged = kTRUE;\n fArcBall.SetBounds(vp.Width(), vp.Height());\n fViewport = vp;\n \n } else\n fVpChanged = kFALSE;\n}\n\n\/\/______________________________________________________________________________\nvoid TGLPlotCamera::SetViewVolume(const TGLVertex3* \/* box *\/)\n{\n \/\/'box' is the TGLPlotPainter's back box's coordinates.\n\/* fCenter[0] = (box[0].X() + box[1].X()) \/ 2;\n fCenter[1] = (box[0].Y() + box[2].Y()) \/ 2;\n fCenter[2] = (box[0].Z() + box[4].Z()) \/ 2;\n const Double_t maxDim = box[1].X() - box[0].X();\n fOrthoBox[0] = maxDim;\n fOrthoBox[1] = maxDim;\n fOrthoBox[2] = -100 * maxDim;\/\/100?\n fOrthoBox[3] = 100 * maxDim;\n fShift = maxDim * 1.5;*\/\n}\n\n\/\/______________________________________________________________________________\nvoid TGLPlotCamera::StartRotation(Int_t px, Int_t py)\n{\n \/\/User clicks somewhere (px, py).\n fArcBall.Click(TPoint(px, py));\n}\n\n\/\/______________________________________________________________________________\nvoid TGLPlotCamera::RotateCamera(Int_t px, Int_t py)\n{\n \/\/Mouse movement.\n fArcBall.Drag(TPoint(px, py));\n}\n\n\/\/______________________________________________________________________________\nvoid TGLPlotCamera::StartPan(Int_t px, Int_t py)\n{\n \/\/User clicks somewhere (px, py).\n fMousePos.fX = px;\n fMousePos.fY = fViewport.Height() - py;\n}\n\n\/\/______________________________________________________________________________\nvoid TGLPlotCamera::Pan(Int_t px, Int_t py)\n{\n \/\/Pan camera.\n py = fViewport.Height() - py;\n \/\/Extract gl matrices.\n Double_t mv[16] = {0.};\n glGetDoublev(GL_MODELVIEW_MATRIX, mv);\n Double_t pr[16] = {0.};\n glGetDoublev(GL_PROJECTION_MATRIX, pr);\n Int_t vp[] = {0, 0, fViewport.Width(), fViewport.Height()};\n \/\/Adjust pan vector.\n TGLVertex3 start, end;\n gluUnProject(fMousePos.fX, fMousePos.fY, 1., mv, pr, vp, &start.X(), &start.Y(), &start.Z());\n gluUnProject(px, py, 1., mv, pr, vp, &end.X(), &end.Y(), &end.Z());\n fTruck += (start - end) \/= 2.;\n fMousePos.fX = px;\n fMousePos.fY = py;\n}\n\n\/\/______________________________________________________________________________\nvoid TGLPlotCamera::SetCamera()const\n{\n \/\/Viewport and projection.\n glViewport(fViewport.X(), fViewport.Y(), fViewport.Width(), fViewport.Height());\n\n glMatrixMode(GL_PROJECTION);\n glLoadIdentity();\n glOrtho(\n -fOrthoBox[0] * fZoom,\n fOrthoBox[0] * fZoom,\n -fOrthoBox[1] * fZoom,\n fOrthoBox[1] * fZoom,\n fOrthoBox[2],\n fOrthoBox[3]\n );\n\n glMatrixMode(GL_MODELVIEW);\n glLoadIdentity();\n}\n\n\/\/______________________________________________________________________________\nvoid TGLPlotCamera::Apply(Double_t phi, Double_t theta)const\n{\n \/\/Applies rotations and translations before drawing\n glTranslated(0., 0., -fShift);\n glMultMatrixd(fArcBall.GetRotMatrix());\n glRotated(theta - 90., 1., 0., 0.);\n glRotated(phi, 0., 0., 1.);\n glTranslated(-fTruck[0], -fTruck[1], -fTruck[2]);\n\/\/ glTranslated(-fCenter[0], -fCenter[1], -fCenter[2]);\n}\n\n\/\/______________________________________________________________________________\nInt_t TGLPlotCamera::GetX()const\n{\n \/\/viewport[0]\n return fViewport.X();\n}\n\n\/\/______________________________________________________________________________\nInt_t TGLPlotCamera::GetY()const\n{\n \/\/viewport[1]\n return fViewport.Y();\n}\n\n\/\/______________________________________________________________________________\nInt_t TGLPlotCamera::GetWidth()const\n{\n \/\/viewport[2]\n return Int_t(fViewport.Width());\n}\n\n\/\/______________________________________________________________________________\nInt_t TGLPlotCamera::GetHeight()const\n{\n \/\/viewport[3]\n return Int_t(fViewport.Height());\n}\n\n\/\/______________________________________________________________________________\nvoid TGLPlotCamera::ZoomIn()\n{\n \/\/Zoom in.\n fZoom \/= 1.2;\n}\n\n\/\/______________________________________________________________________________\nvoid TGLPlotCamera::ZoomOut()\n{\n \/\/Zoom out.\n fZoom *= 1.2;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * libcpu: x86_disasm.cpp\n *\n * disassembler\n *\/\n\n#include <stdlib.h>\n#include <stdio.h>\n\n#include \"libcpu.h\"\n#include \"x86_isa.h\"\n#include \"x86_decode.h\"\n\nstatic const char* mnemo[] = {\n#define DECLARE_INSTR(name,str) str,\n#include \"x86_instr.h\"\n#undef DECLARE_INSTR\n};\n\nstatic const char *to_mnemonic(struct x86_instr *instr)\n{\n\treturn mnemo[instr->type];\n}\n\nstatic const char *byte_reg_names[] = {\n\t\"%al\",\n\t\"%cl\",\n\t\"%dl\",\n\t\"%bl\",\n\t\"%ah\",\n\t\"%ch\",\n\t\"%dh\",\n\t\"%bh\",\n};\n\nstatic const char *word_reg_names[] = {\n\t\"%ax\",\n\t\"%cx\",\n\t\"%dx\",\n\t\"%bx\",\n\t\"%sp\",\n\t\"%bp\",\n\t\"%si\",\n\t\"%di\",\n};\n\nstatic const char *seg_reg_names[] = {\n\t\"%es\",\n\t\"%cs\",\n\t\"%ss\",\n\t\"%ds\",\n};\n\nstatic const char *mem_byte_reg_names[] = {\n\t\"%bx,%si\",\n\t\"%bx,%di\",\n\t\"%bp,%si\",\n\t\"%bp,%di\",\n\t\"%si\",\n\t\"%di\",\n\tNULL,\n\t\"%bx\",\n};\n\nstatic const char *seg_override_names[] = {\n\t\"\",\n\t\"%es:\",\n\t\"%cs:\",\n\t\"%ss:\",\n\t\"%ds:\",\n};\n\nstatic const char *lock_names[] = {\n\t\"\",\n\t\"lock \",\n};\n\nstatic const char *prefix_names[] = {\n\t\"\",\n\t\"repnz \",\n\t\"rep \",\n};\n\nstatic const char *sign_to_str(int n)\n{\n\tif (n >= 0)\n\t\treturn \"\";\n\n\treturn \"-\";\n}\n\nstatic const char *to_reg_name(struct x86_instr *instr, int reg_num)\n{\n\tif (instr->flags & WIDTH_BYTE)\n\t\treturn byte_reg_names[reg_num];\n\n\treturn word_reg_names[reg_num];\n}\n\n\nstatic const char *to_seg_reg_name(struct x86_instr *instr, int reg_num)\n{\n\treturn seg_reg_names[reg_num];\n}\n\nstatic int\nprint_operand(addr_t pc, char *operands, size_t size, struct x86_instr *instr, struct x86_operand *operand)\n{\n\tint ret = 0;\n\n\tswitch (operand->type) {\n\tcase OP_IMM:\n\t\tret = snprintf(operands, size, \"$0x%x\", operand->imm);\n\t\tbreak;\n\tcase OP_REL:\n\t\tret = snprintf(operands, size, \"%x\", (unsigned int)((long)pc + instr->nr_bytes + operand->rel));\n\t\tbreak;\n\tcase OP_REG:\n\t\tret = snprintf(operands, size, \"%s\", to_reg_name(instr, operand->reg));\n\t\tbreak;\n\tcase OP_SEG_REG:\n\t\tret = snprintf(operands, size, \"%s\", to_seg_reg_name(instr, operand->reg));\n\t\tbreak;\n\tcase OP_MEM:\n\t\tret = snprintf(operands, size, \"%s%x\", sign_to_str(operand->disp), abs(operand->disp));\n\t\tbreak;\n\tcase OP_MEM_DISP:\n\t\tret = snprintf(operands, size, \"%s%s0x%x(%s)\", seg_override_names[instr->seg_override], sign_to_str(operand->disp), abs(operand->disp), mem_byte_reg_names[operand->reg]);\n\t\tbreak;\n\t}\n\treturn ret;\n}\n\nint\narch_8086_disasm_instr(cpu_t *cpu, addr_t pc, char *line, unsigned int max_line)\n{\n\tstruct x86_instr instr;\n\tchar operands[32];\n\tint len = 0;\n\n\tif (arch_8086_decode_instr(&instr, cpu->RAM, pc) != 0) {\n\t\tfprintf(stderr, \"error: unable to decode opcode %x\\n\", instr.opcode);\n\t\texit(1);\n\t}\n\n\toperands[0] = '\\0';\n\n\t\/* AT&T syntax operands *\/\n\tif (!(instr.flags & SRC_NONE))\n\t\tlen += print_operand(pc, operands+len, sizeof(operands)-len, &instr, &instr.src);\n\n\tif (!(instr.flags & SRC_NONE) && !(instr.flags & DST_NONE))\n\t\tlen += snprintf(operands+len, sizeof(operands)-len, \",\");\n\n\tif (!(instr.flags & DST_NONE))\n\t\tlen += print_operand(pc, operands+len, sizeof(operands)-len, &instr, &instr.dst);\n\n snprintf(line, max_line, \"%s%s%s\\t%s\", lock_names[instr.lock_prefix], prefix_names[instr.rep_prefix], to_mnemonic(&instr), operands);\n\n return arch_8086_instr_length(&instr);\n}\n<commit_msg>x86: Fix disasm hexadecimal prints<commit_after>\/*\n * libcpu: x86_disasm.cpp\n *\n * disassembler\n *\/\n\n#include <stdlib.h>\n#include <stdio.h>\n\n#include \"libcpu.h\"\n#include \"x86_isa.h\"\n#include \"x86_decode.h\"\n\nstatic const char* mnemo[] = {\n#define DECLARE_INSTR(name,str) str,\n#include \"x86_instr.h\"\n#undef DECLARE_INSTR\n};\n\nstatic const char *to_mnemonic(struct x86_instr *instr)\n{\n\treturn mnemo[instr->type];\n}\n\nstatic const char *byte_reg_names[] = {\n\t\"%al\",\n\t\"%cl\",\n\t\"%dl\",\n\t\"%bl\",\n\t\"%ah\",\n\t\"%ch\",\n\t\"%dh\",\n\t\"%bh\",\n};\n\nstatic const char *word_reg_names[] = {\n\t\"%ax\",\n\t\"%cx\",\n\t\"%dx\",\n\t\"%bx\",\n\t\"%sp\",\n\t\"%bp\",\n\t\"%si\",\n\t\"%di\",\n};\n\nstatic const char *seg_reg_names[] = {\n\t\"%es\",\n\t\"%cs\",\n\t\"%ss\",\n\t\"%ds\",\n};\n\nstatic const char *mem_byte_reg_names[] = {\n\t\"%bx,%si\",\n\t\"%bx,%di\",\n\t\"%bp,%si\",\n\t\"%bp,%di\",\n\t\"%si\",\n\t\"%di\",\n\tNULL,\n\t\"%bx\",\n};\n\nstatic const char *seg_override_names[] = {\n\t\"\",\n\t\"%es:\",\n\t\"%cs:\",\n\t\"%ss:\",\n\t\"%ds:\",\n};\n\nstatic const char *lock_names[] = {\n\t\"\",\n\t\"lock \",\n};\n\nstatic const char *prefix_names[] = {\n\t\"\",\n\t\"repnz \",\n\t\"rep \",\n};\n\nstatic const char *sign_to_str(int n)\n{\n\tif (n >= 0)\n\t\treturn \"\";\n\n\treturn \"-\";\n}\n\nstatic const char *to_reg_name(struct x86_instr *instr, int reg_num)\n{\n\tif (instr->flags & WIDTH_BYTE)\n\t\treturn byte_reg_names[reg_num];\n\n\treturn word_reg_names[reg_num];\n}\n\n\nstatic const char *to_seg_reg_name(struct x86_instr *instr, int reg_num)\n{\n\treturn seg_reg_names[reg_num];\n}\n\nstatic int\nprint_operand(addr_t pc, char *operands, size_t size, struct x86_instr *instr, struct x86_operand *operand)\n{\n\tint ret = 0;\n\n\tswitch (operand->type) {\n\tcase OP_IMM:\n\t\tret = snprintf(operands, size, \"$0x%x\", operand->imm);\n\t\tbreak;\n\tcase OP_REL:\n\t\tret = snprintf(operands, size, \"0x%x\", (unsigned int)((long)pc + instr->nr_bytes + operand->rel));\n\t\tbreak;\n\tcase OP_REG:\n\t\tret = snprintf(operands, size, \"%s\", to_reg_name(instr, operand->reg));\n\t\tbreak;\n\tcase OP_SEG_REG:\n\t\tret = snprintf(operands, size, \"%s\", to_seg_reg_name(instr, operand->reg));\n\t\tbreak;\n\tcase OP_MEM:\n\t\tret = snprintf(operands, size, \"%s0x%x\", sign_to_str(operand->disp), abs(operand->disp));\n\t\tbreak;\n\tcase OP_MEM_DISP:\n\t\tret = snprintf(operands, size, \"%s%s0x%x(%s)\", seg_override_names[instr->seg_override], sign_to_str(operand->disp), abs(operand->disp), mem_byte_reg_names[operand->reg]);\n\t\tbreak;\n\t}\n\treturn ret;\n}\n\nint\narch_8086_disasm_instr(cpu_t *cpu, addr_t pc, char *line, unsigned int max_line)\n{\n\tstruct x86_instr instr;\n\tchar operands[32];\n\tint len = 0;\n\n\tif (arch_8086_decode_instr(&instr, cpu->RAM, pc) != 0) {\n\t\tfprintf(stderr, \"error: unable to decode opcode %x\\n\", instr.opcode);\n\t\texit(1);\n\t}\n\n\toperands[0] = '\\0';\n\n\t\/* AT&T syntax operands *\/\n\tif (!(instr.flags & SRC_NONE))\n\t\tlen += print_operand(pc, operands+len, sizeof(operands)-len, &instr, &instr.src);\n\n\tif (!(instr.flags & SRC_NONE) && !(instr.flags & DST_NONE))\n\t\tlen += snprintf(operands+len, sizeof(operands)-len, \",\");\n\n\tif (!(instr.flags & DST_NONE))\n\t\tlen += print_operand(pc, operands+len, sizeof(operands)-len, &instr, &instr.dst);\n\n snprintf(line, max_line, \"%s%s%s\\t%s\", lock_names[instr.lock_prefix], prefix_names[instr.rep_prefix], to_mnemonic(&instr), operands);\n\n return arch_8086_instr_length(&instr);\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Silly subclass of CTreeCtrl just to implement Drag&Drop.\n *\n * Based on MFC sample code from CMNCTRL1\n *\/\n\n\n#include \"stdafx.h\"\n#include \"MyTreeCtrl.h\"\n#include \"DboxMain.h\"\n#include \"corelib\/ItemData.h\"\n#include \"corelib\/MyString.h\"\n\n#ifdef _DEBUG\n#define new DEBUG_NEW\n#undef THIS_FILE\nstatic char THIS_FILE[] = __FILE__;\n#endif\n\nstatic const TCHAR GROUP_SEP = TCHAR('.');\n\nCMyTreeCtrl::CMyTreeCtrl() : m_bDragging(false), m_pimagelist(NULL)\n{\n}\n\nCMyTreeCtrl::~CMyTreeCtrl()\n{\n delete m_pimagelist;\n}\n\n\nBEGIN_MESSAGE_MAP(CMyTreeCtrl, CTreeCtrl)\n\t\/\/{{AFX_MSG_MAP(CMyTreeCtrl)\n\tON_NOTIFY_REFLECT(TVN_ENDLABELEDIT, OnEndLabelEdit)\n\tON_NOTIFY_REFLECT(TVN_BEGINDRAG, OnBeginDrag)\n\tON_NOTIFY_REFLECT(TVN_BEGINRDRAG, OnBeginDrag)\n\tON_WM_MOUSEMOVE()\n\tON_WM_DESTROY()\n\tON_WM_LBUTTONUP()\n\t\/\/}}AFX_MSG_MAP\nEND_MESSAGE_MAP()\n\nvoid CMyTreeCtrl::OnDestroy()\n{\n CImageList *pimagelist;\n\n pimagelist = GetImageList(TVSIL_NORMAL);\n if (pimagelist != NULL) {\n pimagelist->DeleteImageList();\n delete pimagelist;\n }\n}\n\nvoid CMyTreeCtrl::SetNewStyle(long lStyleMask, BOOL bSetBits)\n{\n long lStyleOld;\n\n lStyleOld = GetWindowLong(m_hWnd, GWL_STYLE);\n lStyleOld &= ~lStyleMask;\n if (bSetBits)\n lStyleOld |= lStyleMask;\n\n SetWindowLong(m_hWnd, GWL_STYLE, lStyleOld);\n SetWindowPos(NULL, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER);\n}\n\nvoid CMyTreeCtrl::UpdateLeafsGroup(HTREEITEM hItem, CString prefix)\n{\n if (IsLeafNode(hItem)) {\n DWORD itemData = GetItemData(hItem);\n ASSERT(itemData != NULL);\n CItemData *ci = (CItemData *)itemData;\n ci->SetGroup(CMyString(prefix));\n } else { \/\/ update prefix with current group name and recurse\n if (!prefix.IsEmpty())\n prefix += GROUP_SEP;\n prefix += GetItemText(hItem);\n HTREEITEM child;\n for(child = GetChildItem(hItem); child != NULL; child = GetNextSiblingItem(child)) {\n UpdateLeafsGroup(child, prefix);\n }\n }\n}\n\nvoid CMyTreeCtrl::OnEndLabelEdit(LPNMHDR pnmhdr, LRESULT *pLResult)\n{\n TV_DISPINFO *ptvinfo;\n\n ptvinfo = (TV_DISPINFO *)pnmhdr;\n if (ptvinfo->item.pszText != NULL) {\n ptvinfo->item.mask = TVIF_TEXT;\n SetItem(&ptvinfo->item);\n HTREEITEM ti = ptvinfo->item.hItem;\n if (IsLeafNode(ptvinfo->item.hItem)) {\n \/\/ Update leaf's title\n DWORD itemData = GetItemData(ti);\n ASSERT(itemData != NULL);\n CItemData *ci = (CItemData *)itemData;\n ci->SetTitle(ptvinfo->item.pszText);\n DboxMain *parent = (DboxMain *)GetParent();\n \/\/ update corresponding List text\n DisplayInfo *di = (DisplayInfo *)ci->GetDisplayInfo();\n ASSERT(di != NULL);\n int lindex = di->list_index;\n parent->UpdateListItemTitle(lindex, ptvinfo->item.pszText);\n \/\/ Mark database as modified\n parent->SetChanged(true);\n } else {\n \/\/ Update all leaf chldren with new path element\n \/\/ prefix is path up to and NOT including renamed node\n CString prefix;\n HTREEITEM parent, current = ti;\n do {\n\tparent = GetParentItem(current);\n\tif (parent == NULL) {\n\t break;\n\t}\n\tcurrent = parent;\n\tif (!prefix.IsEmpty())\n\t prefix = GROUP_SEP + prefix;\n\tprefix = GetItemText(current) + prefix;\n } while (1);\n UpdateLeafsGroup(ti, prefix);\n }\n }\n *pLResult = TRUE;\n}\n\nvoid CMyTreeCtrl::OnMouseMove(UINT nFlags, CPoint point)\n{\n HTREEITEM hitem;\n UINT flags;\n\n if (m_bDragging) {\n ASSERT(m_pimagelist != NULL);\n m_pimagelist->DragMove(point);\n if ((hitem = HitTest(point, &flags)) != NULL) {\n m_pimagelist->DragLeave(this);\n SelectDropTarget(hitem);\n m_hitemDrop = hitem;\n m_pimagelist->DragEnter(this, point);\n }\n }\n\n CTreeCtrl::OnMouseMove(nFlags, point);\n}\n\nbool CMyTreeCtrl::IsChildNodeOf(HTREEITEM hitemChild, HTREEITEM hitemSuspectedParent)\n{\n do {\n if (hitemChild == hitemSuspectedParent)\n break;\n } while ((hitemChild = GetParentItem(hitemChild)) != NULL);\n\n return (hitemChild != NULL);\n}\n\nbool CMyTreeCtrl::IsLeafNode(HTREEITEM hItem)\n{\n \/\/ ItemHasChildren() won't work in the general case\n BOOL status;\n int i, dummy;\n status = GetItemImage(hItem, i, dummy);\n ASSERT(status);\n return (i == LEAF);\n}\n\nvoid CMyTreeCtrl::DeleteWithParents(HTREEITEM hItem)\n{\n \/\/ We don't want nodes that have no children to remain\n HTREEITEM p;\n do {\n p = GetParentItem(hItem);\n DeleteItem(hItem);\n if (ItemHasChildren(p))\n break;\n hItem = p;\n } while (p != TVI_ROOT);\n}\n\nCString CMyTreeCtrl::GetGroup(HTREEITEM hItem)\n{\n CString retval;\n CString nodeText;\n while (hItem != NULL) {\n nodeText = GetItemText(hItem);\n if (!retval.IsEmpty())\n nodeText += GROUP_SEP;\n retval = nodeText + retval;\n hItem = GetParentItem(hItem);\n }\n return retval;\n}\n\n\nstatic CMyString GetPathElem(CMyString &path)\n{\n \/\/ Get first path element and chop it off, i.e., if\n \/\/ path = \"a.b.c.d\"\n \/\/ will return \"a\" and path will be \"b.c.d\"\n \/\/ (assuming GROUP_SEP is '.')\n\n CMyString retval;\n int N = path.Find(GROUP_SEP);\n if (N == -1) {\n retval = path;\n path = _T(\"\");\n } else {\n const int Len = path.GetLength();\n retval = CMyString(path.Left(N));\n path = CMyString(path.Right(Len - N - 1));\n }\n return retval;\n}\n\nstatic bool ExistsInTree(CTreeCtrl &Tree, HTREEITEM node,\n\t\t\t const CMyString &s, HTREEITEM &si)\n{\n \/\/ returns true iff s is a direct descendant of node\n HTREEITEM ti = Tree.GetChildItem(node);\n \n while (ti != NULL) {\n const CMyString itemText = Tree.GetItemText(ti);\n if (itemText == s) {\n si = ti;\n return true;\n }\n ti = Tree.GetNextItem(ti, TVGN_NEXT);\n }\n return false;\n}\n\nHTREEITEM CMyTreeCtrl::AddGroup(const CString &group)\n{\n \/\/ Add a group at the end of path\n HTREEITEM ti = TVI_ROOT;\n HTREEITEM si;\n if (!group.IsEmpty()) {\n CMyString path = group;\n CMyString s;\n do {\n s = GetPathElem(path);\n if (!ExistsInTree(*this, ti, s, si)) {\n\tti = InsertItem(s, ti, TVI_SORT);\n\tSetItemImage(ti, CMyTreeCtrl::NODE, CMyTreeCtrl::NODE);\n } else\n\tti = si;\n } while (!path.IsEmpty());\n }\n return ti;\n}\n\nbool CMyTreeCtrl::TransferItem(HTREEITEM hitemDrag, HTREEITEM hitemDrop)\n{\n TV_INSERTSTRUCT tvstruct;\n TCHAR sztBuffer[128];\n HTREEITEM hNewItem, hFirstChild;\n DWORD itemData = GetItemData(hitemDrag);\n\n \/\/ avoid an infinite recursion\n tvstruct.item.hItem = hitemDrag;\n tvstruct.item.cchTextMax = sizeof(sztBuffer)\/sizeof(TCHAR) - 1;\n tvstruct.item.pszText = sztBuffer;\n tvstruct.item.mask = (TVIF_CHILDREN | TVIF_HANDLE | TVIF_IMAGE\n\t\t\t| TVIF_SELECTEDIMAGE | TVIF_TEXT);\n GetItem(&tvstruct.item); \/\/ get information of the dragged element\n tvstruct.hParent = hitemDrop;\n tvstruct.hInsertAfter = TVI_SORT;\n tvstruct.item.mask = TVIF_IMAGE | TVIF_SELECTEDIMAGE | TVIF_TEXT;\n hNewItem = InsertItem(&tvstruct);\n if (itemData != 0) { \/\/ Non-NULL itemData implies Leaf\n CItemData *ci = (CItemData *)itemData;\n \/\/ Update Group\n CMyString path, elem;\n HTREEITEM p, q = hNewItem;\n do {\n p = GetParentItem(q);\n if (p != NULL) {\n\telem = CMyString(GetItemText(p));\n\tif (!path.IsEmpty())\n\t elem += GROUP_SEP;\n\tpath = elem + path;\n\tq = p;\n } else\n\tbreak;\n } while (1);\n ci->SetGroup(path);\n \/\/ Mark database as modified!\n ((DboxMain *)GetParent())->SetChanged(true);\n \/\/ Update DisplayInfo record associated with ItemData\n DisplayInfo *di = (DisplayInfo *)ci->GetDisplayInfo();\n ASSERT(di != NULL);\n di->tree_item = hNewItem;\n }\n SetItemData(hNewItem, itemData);\n\n while ((hFirstChild = GetChildItem(hitemDrag)) != NULL) {\n TransferItem(hFirstChild, hNewItem); \/\/ recursively transfer all the items\n DeleteItem(hFirstChild);\n }\n return true;\n}\n\nvoid CMyTreeCtrl::OnButtonUp()\n{\n if (m_bDragging) {\n ASSERT(m_pimagelist != NULL);\n m_pimagelist->DragLeave(this);\n m_pimagelist->EndDrag();\n delete m_pimagelist;\n m_pimagelist = NULL;\n HTREEITEM parent = GetParentItem(m_hitemDrag);\n\n if (m_hitemDrag != m_hitemDrop &&\n\t!IsLeafNode(m_hitemDrop) &&\n\t!IsChildNodeOf(m_hitemDrop, m_hitemDrag) &&\n\tparent != m_hitemDrop) {\n TransferItem(m_hitemDrag, m_hitemDrop);\n DeleteItem(m_hitemDrag);\n while (parent != NULL && !ItemHasChildren(parent)) {\n\tHTREEITEM grandParent = GetParentItem(parent);\n\tDeleteItem(parent);\n\tparent = grandParent;\n }\n } else\n MessageBeep(0);\n\n ReleaseCapture();\n m_bDragging = FALSE;\n SelectDropTarget(NULL);\n }\n}\n\nvoid CMyTreeCtrl::OnLButtonUp(UINT nFlags, CPoint point)\n{\n OnButtonUp();\n CTreeCtrl::OnLButtonUp(nFlags, point);\n}\n\n\nvoid CMyTreeCtrl::OnBeginDrag(LPNMHDR , LRESULT *)\n{\n CPoint ptAction;\n UINT nFlags;\n\n GetCursorPos(&ptAction);\n ScreenToClient(&ptAction);\n ASSERT(!m_bDragging);\n m_bDragging = TRUE;\n m_hitemDrag = HitTest(ptAction, &nFlags);\n m_hitemDrop = NULL;\n\n ASSERT(m_pimagelist == NULL);\n m_pimagelist = CreateDragImage(m_hitemDrag);\n m_pimagelist->DragShowNolock(TRUE);\n m_pimagelist->SetDragCursorImage(0, CPoint(0, 0));\n m_pimagelist->BeginDrag(0, CPoint(0,0));\n m_pimagelist->DragMove(ptAction);\n m_pimagelist->DragEnter(this, ptAction);\n SetCapture();\n}\n<commit_msg>Removed annoying beep, resort after online edit.<commit_after>\/*\n * Silly subclass of CTreeCtrl just to implement Drag&Drop.\n *\n * Based on MFC sample code from CMNCTRL1\n *\/\n\n\n#include \"stdafx.h\"\n#include \"MyTreeCtrl.h\"\n#include \"DboxMain.h\"\n#include \"corelib\/ItemData.h\"\n#include \"corelib\/MyString.h\"\n\n#ifdef _DEBUG\n#define new DEBUG_NEW\n#undef THIS_FILE\nstatic char THIS_FILE[] = __FILE__;\n#endif\n\nstatic const TCHAR GROUP_SEP = TCHAR('.');\n\nCMyTreeCtrl::CMyTreeCtrl() : m_bDragging(false), m_pimagelist(NULL)\n{\n}\n\nCMyTreeCtrl::~CMyTreeCtrl()\n{\n delete m_pimagelist;\n}\n\n\nBEGIN_MESSAGE_MAP(CMyTreeCtrl, CTreeCtrl)\n\t\/\/{{AFX_MSG_MAP(CMyTreeCtrl)\n\tON_NOTIFY_REFLECT(TVN_ENDLABELEDIT, OnEndLabelEdit)\n\tON_NOTIFY_REFLECT(TVN_BEGINDRAG, OnBeginDrag)\n\tON_WM_MOUSEMOVE()\n\tON_WM_DESTROY()\n\tON_WM_LBUTTONUP()\n\t\/\/}}AFX_MSG_MAP\nEND_MESSAGE_MAP()\n\nvoid CMyTreeCtrl::OnDestroy()\n{\n CImageList *pimagelist;\n\n pimagelist = GetImageList(TVSIL_NORMAL);\n if (pimagelist != NULL) {\n pimagelist->DeleteImageList();\n delete pimagelist;\n }\n}\n\nvoid CMyTreeCtrl::SetNewStyle(long lStyleMask, BOOL bSetBits)\n{\n long lStyleOld;\n\n lStyleOld = GetWindowLong(m_hWnd, GWL_STYLE);\n lStyleOld &= ~lStyleMask;\n if (bSetBits)\n lStyleOld |= lStyleMask;\n\n SetWindowLong(m_hWnd, GWL_STYLE, lStyleOld);\n SetWindowPos(NULL, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER);\n}\n\nvoid CMyTreeCtrl::UpdateLeafsGroup(HTREEITEM hItem, CString prefix)\n{\n \/\/ Starting with hItem, update the Group field of all of hItem's\n \/\/ children. Called after a label has been edited.\n if (IsLeafNode(hItem)) {\n DWORD itemData = GetItemData(hItem);\n ASSERT(itemData != NULL);\n CItemData *ci = (CItemData *)itemData;\n ci->SetGroup(CMyString(prefix));\n } else { \/\/ update prefix with current group name and recurse\n if (!prefix.IsEmpty())\n prefix += GROUP_SEP;\n prefix += GetItemText(hItem);\n HTREEITEM child;\n for(child = GetChildItem(hItem); child != NULL; child = GetNextSiblingItem(child)) {\n UpdateLeafsGroup(child, prefix);\n }\n }\n}\n\nvoid CMyTreeCtrl::OnEndLabelEdit(LPNMHDR pnmhdr, LRESULT *pLResult)\n{\n TV_DISPINFO *ptvinfo = (TV_DISPINFO *)pnmhdr;\n\n if (ptvinfo->item.pszText != NULL) {\n DboxMain *parent = (DboxMain *)GetParent();\n ptvinfo->item.mask = TVIF_TEXT;\n SetItem(&ptvinfo->item);\n HTREEITEM ti = ptvinfo->item.hItem;\n if (IsLeafNode(ptvinfo->item.hItem)) {\n \/\/ Update leaf's title\n DWORD itemData = GetItemData(ti);\n ASSERT(itemData != NULL);\n CItemData *ci = (CItemData *)itemData;\n ci->SetTitle(ptvinfo->item.pszText);\n \/\/ update corresponding List text\n DisplayInfo *di = (DisplayInfo *)ci->GetDisplayInfo();\n ASSERT(di != NULL);\n int lindex = di->list_index;\n parent->UpdateListItemTitle(lindex, ptvinfo->item.pszText);\n } else {\n \/\/ Update all leaf chldren with new path element\n \/\/ prefix is path up to and NOT including renamed node\n CString prefix;\n HTREEITEM parent, current = ti;\n do {\n\tparent = GetParentItem(current);\n\tif (parent == NULL) {\n\t break;\n\t}\n\tcurrent = parent;\n\tif (!prefix.IsEmpty())\n\t prefix = GROUP_SEP + prefix;\n\tprefix = GetItemText(current) + prefix;\n } while (1);\n UpdateLeafsGroup(ti, prefix);\n }\n \/\/ Mark database as modified\n parent->SetChanged(true);\n SortChildren(GetParentItem(ti));\n }\n *pLResult = TRUE;\n}\n\nvoid CMyTreeCtrl::OnMouseMove(UINT nFlags, CPoint point)\n{\n HTREEITEM hitem;\n UINT flags;\n\n if (m_bDragging) {\n ASSERT(m_pimagelist != NULL);\n m_pimagelist->DragMove(point);\n if ((hitem = HitTest(point, &flags)) != NULL) {\n m_pimagelist->DragLeave(this);\n SelectDropTarget(hitem);\n m_hitemDrop = hitem;\n m_pimagelist->DragEnter(this, point);\n }\n }\n CTreeCtrl::OnMouseMove(nFlags, point);\n}\n\nbool CMyTreeCtrl::IsChildNodeOf(HTREEITEM hitemChild, HTREEITEM hitemSuspectedParent)\n{\n do {\n if (hitemChild == hitemSuspectedParent)\n break;\n } while ((hitemChild = GetParentItem(hitemChild)) != NULL);\n\n return (hitemChild != NULL);\n}\n\nbool CMyTreeCtrl::IsLeafNode(HTREEITEM hItem)\n{\n \/\/ ItemHasChildren() won't work in the general case\n BOOL status;\n int i, dummy;\n status = GetItemImage(hItem, i, dummy);\n ASSERT(status);\n return (i == LEAF);\n}\n\nvoid CMyTreeCtrl::DeleteWithParents(HTREEITEM hItem)\n{\n \/\/ We don't want nodes that have no children to remain\n HTREEITEM p;\n do {\n p = GetParentItem(hItem);\n DeleteItem(hItem);\n if (ItemHasChildren(p))\n break;\n hItem = p;\n } while (p != TVI_ROOT);\n}\n\nCString CMyTreeCtrl::GetGroup(HTREEITEM hItem)\n{\n CString retval;\n CString nodeText;\n while (hItem != NULL) {\n nodeText = GetItemText(hItem);\n if (!retval.IsEmpty())\n nodeText += GROUP_SEP;\n retval = nodeText + retval;\n hItem = GetParentItem(hItem);\n }\n return retval;\n}\n\n\nstatic CMyString GetPathElem(CMyString &path)\n{\n \/\/ Get first path element and chop it off, i.e., if\n \/\/ path = \"a.b.c.d\"\n \/\/ will return \"a\" and path will be \"b.c.d\"\n \/\/ (assuming GROUP_SEP is '.')\n\n CMyString retval;\n int N = path.Find(GROUP_SEP);\n if (N == -1) {\n retval = path;\n path = _T(\"\");\n } else {\n const int Len = path.GetLength();\n retval = CMyString(path.Left(N));\n path = CMyString(path.Right(Len - N - 1));\n }\n return retval;\n}\n\nstatic bool ExistsInTree(CTreeCtrl &Tree, HTREEITEM node,\n\t\t\t const CMyString &s, HTREEITEM &si)\n{\n \/\/ returns true iff s is a direct descendant of node\n HTREEITEM ti = Tree.GetChildItem(node);\n \n while (ti != NULL) {\n const CMyString itemText = Tree.GetItemText(ti);\n if (itemText == s) {\n si = ti;\n return true;\n }\n ti = Tree.GetNextItem(ti, TVGN_NEXT);\n }\n return false;\n}\n\nHTREEITEM CMyTreeCtrl::AddGroup(const CString &group)\n{\n \/\/ Add a group at the end of path\n HTREEITEM ti = TVI_ROOT;\n HTREEITEM si;\n if (!group.IsEmpty()) {\n CMyString path = group;\n CMyString s;\n do {\n s = GetPathElem(path);\n if (!ExistsInTree(*this, ti, s, si)) {\n\tti = InsertItem(s, ti, TVI_SORT);\n\tSetItemImage(ti, CMyTreeCtrl::NODE, CMyTreeCtrl::NODE);\n } else\n\tti = si;\n } while (!path.IsEmpty());\n }\n return ti;\n}\n\nbool CMyTreeCtrl::TransferItem(HTREEITEM hitemDrag, HTREEITEM hitemDrop)\n{\n TV_INSERTSTRUCT tvstruct;\n TCHAR sztBuffer[128];\n HTREEITEM hNewItem, hFirstChild;\n DWORD itemData = GetItemData(hitemDrag);\n\n \/\/ avoid an infinite recursion\n tvstruct.item.hItem = hitemDrag;\n tvstruct.item.cchTextMax = sizeof(sztBuffer)\/sizeof(TCHAR) - 1;\n tvstruct.item.pszText = sztBuffer;\n tvstruct.item.mask = (TVIF_CHILDREN | TVIF_HANDLE | TVIF_IMAGE\n\t\t\t| TVIF_SELECTEDIMAGE | TVIF_TEXT);\n GetItem(&tvstruct.item); \/\/ get information of the dragged element\n tvstruct.hParent = hitemDrop;\n tvstruct.hInsertAfter = TVI_SORT;\n tvstruct.item.mask = TVIF_IMAGE | TVIF_SELECTEDIMAGE | TVIF_TEXT;\n hNewItem = InsertItem(&tvstruct);\n if (itemData != 0) { \/\/ Non-NULL itemData implies Leaf\n CItemData *ci = (CItemData *)itemData;\n \/\/ Update Group\n CMyString path, elem;\n HTREEITEM p, q = hNewItem;\n do {\n p = GetParentItem(q);\n if (p != NULL) {\n\telem = CMyString(GetItemText(p));\n\tif (!path.IsEmpty())\n\t elem += GROUP_SEP;\n\tpath = elem + path;\n\tq = p;\n } else\n\tbreak;\n } while (1);\n ci->SetGroup(path);\n \/\/ Mark database as modified!\n ((DboxMain *)GetParent())->SetChanged(true);\n \/\/ Update DisplayInfo record associated with ItemData\n DisplayInfo *di = (DisplayInfo *)ci->GetDisplayInfo();\n ASSERT(di != NULL);\n di->tree_item = hNewItem;\n }\n SetItemData(hNewItem, itemData);\n\n while ((hFirstChild = GetChildItem(hitemDrag)) != NULL) {\n TransferItem(hFirstChild, hNewItem); \/\/ recursively transfer all the items\n DeleteItem(hFirstChild);\n }\n return true;\n}\n\nvoid CMyTreeCtrl::OnButtonUp()\n{\n if (m_bDragging) {\n ASSERT(m_pimagelist != NULL);\n m_pimagelist->DragLeave(this);\n m_pimagelist->EndDrag();\n delete m_pimagelist;\n m_pimagelist = NULL;\n HTREEITEM parent = GetParentItem(m_hitemDrag);\n\n if (m_hitemDrag != m_hitemDrop &&\n\t!IsLeafNode(m_hitemDrop) &&\n\t!IsChildNodeOf(m_hitemDrop, m_hitemDrag) &&\n\tparent != m_hitemDrop) {\n TransferItem(m_hitemDrag, m_hitemDrop);\n DeleteItem(m_hitemDrag);\n while (parent != NULL && !ItemHasChildren(parent)) {\n\tHTREEITEM grandParent = GetParentItem(parent);\n\tDeleteItem(parent);\n\tparent = grandParent;\n }\n }\n ReleaseCapture();\n m_bDragging = FALSE;\n SelectDropTarget(NULL);\n }\n}\n\nvoid CMyTreeCtrl::OnLButtonUp(UINT nFlags, CPoint point)\n{\n OnButtonUp();\n CTreeCtrl::OnLButtonUp(nFlags, point);\n}\n\n\nvoid CMyTreeCtrl::OnBeginDrag(LPNMHDR , LRESULT *)\n{\n CPoint ptAction;\n UINT nFlags;\n\n GetCursorPos(&ptAction);\n ScreenToClient(&ptAction);\n ASSERT(!m_bDragging);\n m_bDragging = TRUE;\n m_hitemDrag = HitTest(ptAction, &nFlags);\n m_hitemDrop = NULL;\n\n ASSERT(m_pimagelist == NULL);\n m_pimagelist = CreateDragImage(m_hitemDrag);\n m_pimagelist->DragShowNolock(TRUE);\n m_pimagelist->SetDragCursorImage(0, CPoint(0, 0));\n m_pimagelist->BeginDrag(0, CPoint(0,0));\n m_pimagelist->DragMove(ptAction);\n m_pimagelist->DragEnter(this, ptAction);\n SetCapture();\n}\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n#include <map>\n#include <string>\n#include <iterator>\n#include <vector>\nusing namespace std;\n\nunsigned int M;\nstring morse_string;\nstring morse_table[] = {\".-\", \"-...\", \"-.-.\", \"-..\", \".\", \"..-.\", \"--.\", \"....\", \"..\", \".---\", \"-.-\", \".-..\", \"--\", \"-.\", \"---\", \".--.\", \"--.-\", \".-.\", \"...\", \"-\", \"..-\", \"...-\", \".--\", \"-..-\", \"-.--\", \"--..\"};\n\nint matches(unsigned int start, vector<int> &x, map<string, int> &dictionary) {\n\tif (start == morse_string.size())\n\t\treturn 1;\n\tif (x[start] != -1)\n\t\treturn x[start];\n\t\n\tint ret = 0;\n\tmap<string, int>::iterator it;\n\tstring substring;\n\tfor (unsigned int i = 0 ; i < M && start+i < morse_string.size() ; i++) {\n\t\tsubstring += morse_string[start+i];\n\t\tif ((it = dictionary.find(substring)) != dictionary.end())\n\t\t\tret += it->second*matches(start+i+1, x, dictionary);\n\t}\n\n\tx[start] = ret;\n\treturn ret;\n}\n\nstring encode_morse(const string s) {\n\tstring ret = \"\";\n\tfor (char c:s)\n\t\tret += morse_table[c-'A'];\n\tif (ret.size() > M)\n\t\tM = ret.size();\n\treturn ret;\n}\n\nint main() {\n\tint T, N;\n\tstring tmp;\n\tmap<string, int>::iterator it;\n\tcin >> T;\n\t\n\twhile (T--) {\n\t\tM = 0;\n\t\tvector<int> x(1000, -1);\n\t\tmap<string, int> dictionary;\n\t\tmorse_string = \"\";\n\t\tcin >> morse_string;\n\t\tcin >> N;\n\t\tfor (int j = 0 ; j < N ; j++) {\n\t\t\tcin >> tmp;\n\t\t\ttmp = encode_morse(tmp);\n\t\t\tif ((it = dictionary.find(tmp)) == dictionary.end())\n\t\t\t\tdictionary[tmp] = 1;\n\t\t\telse\n\t\t\t\tdictionary[tmp]++;\n\t\t}\n\t\t\n\t\tcout << matches(0, x, dictionary) << endl;\n\t\t\n\t\tif (T) {\n\t\t\tcout << endl;\n\t\t\tfor (int j = 0 ; j < 1000 ; j++)\n\t\t\t\tx[j] = -1;\n\t\t}\n\t}\n\treturn 0;\n}\n<commit_msg>Morse Multiple Matches<commit_after><|endoftext|>"} {"text":"<commit_before>\/\/ from execute.cpp\nvoid DrawASCII(LWR& lwr) {\n string ascii_filename;\n fprintf(stdout, \"What ASCII photo would you like me to draw?\\n> \");\n cin >> ascii_filename;\n lwr.DrawASCIIPhoto(ASCII_PATH + ascii_filename + TXT);\n}\n\n\/\/ from LWR\n \/\/ Just for fun draw a file containing ASCII characters\n int DrawASCIIPhoto(std::string path_to_ascii_file = \"\",\n double speed_percent = 100.0);\n\n\/\/ from utils\nnamespace AsciiArt {\n int Generate2DVectorFromASCIIFile(std::string ascii_file,\n std::vector<std::vector<char>>& ascii_img,\n std::unordered_map<char, std::string> character_set,\n std::vector<char>& char_appearance);\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/ ASCII \/\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/ This comes from the thesis and thus needs to be heavily modified.\n\n\n\/\/ .png or .jpg photo should first be converted into an ASCII photo.\n\/*\nint LWR::DrawASCIIPhoto(string path_to_ascii_file,\n double speed_percent) {\n vector<vector<char>> ascii_img;\n vector<cart_motion*> character_motion_paths;\n unordered_map<char, int> character_freq;\n unsigned int err_val = 0;\n\n if (path_to_ascii_file != \"\") {\n \/\/ read ASCII photo from file into 2D vector.\n Generate2DVectorFromASCIIFile(path_to_ascii_file, ascii_img,\n character_freq);\n\n int img_width = ascii_img.at(0).size();\n int img_height = ascii_img.size();\n LWRLogParser log_parser = LWRLogParser();\n\n \/\/ load motion profiles for all characters in ascii drawing\n \/\/ from motion normalized log files\n for (const auto &myPair : character_freq) {\n string log_file = KUKA_LOG_DIR;\n log_file += myPair.first;\n log_file += \"_standardized\";\n log_file += KUKA_LOG_EXTENSION;\n log_parser.SetLogFile(log_file);\n\n character_motion_paths.push_back(new cart_motion());\n\n \/\/ parse log file and generate motion to repeat\n err_val = log_parser.ParseMotion(NULL, character_motion_paths.back());\n if (err_val != EOK) {\n printf(\"ERROR, could not parse input file\");\n \/\/ add deleting\n \/\/ delete &cart_path;\n return ERROR_INVALID_INPUT_FILE;\n }\n }\n\n }\n else {\n \/\/ keyboard input script\n }\n return 1;\n}\n*\/\nint LWR::DrawASCIIPhoto(string path_to_ascii_file,\n double speed_percent) {\n \/\/ assume standardized character recording files have been created\n\n \/\/ start with map character -> filename\n string standardized_file_path = \"C:\\\\Users\\\\HMMS\\\\Documents\\\\GitHub\\\\Thesis\\\\KUKA LWR\\\\logs\\\\standardized_char_set\\\\\";\n string standardized_file_extension = \".dat\";\n static unordered_map<char, string> char_filename_map = {\n { '$', \"$\" }, { ' ', \"space\" }, { '+', \"+\" }, { '7', \"7\" }, { '8', \"8\" },\n { ':', \"colon\" }, { '=', \"equal\" }, { '?', \"question\" }, { 'D', \"D\" },\n { 'I', \"I\" }, { 'M', \"M\" }, { 'N', \"N\" }, { 'O', \"O\" }, { 'Z', \"Z\" },\n { '~', \"tilde\" }, { '\\n', \"newline\" }, {'\\b', \"newline_left\"}\n };\n \/\/ reserve for char order and appearance in ASCII file\n vector<char> char_appearance;\n \/\/float start[3] = { -0.7, 0.4, -0.0145 };\n float start[3] = { -0.70f, 0.0f, 0.200f }; \/\/ draw on table\n int column = 0;\n int row = 0;\n\n \/\/ create 2D character array for ascii art photo\n \/\/ get mapping in order of what characters are in the file\n vector<vector<char>> ascii_img;\n AsciiArt::Generate2DVectorFromASCIIFile(path_to_ascii_file, ascii_img, char_filename_map, char_appearance);\n\n \/\/ artificially add \\n and \\b to appearance\n char_appearance.push_back('\\n');\n \/\/char_appearance.push_back('\\b');\n\n \/\/ map character to open file stream (hardcore)\n \/*\n unordered_map<char, ifstream> char_files;\n for (int i = 0; i < char_appearance.size(); ++i) {\n char_files[i] = ifstream(char_filename_map[char_appearance[i]]);\n }\n *\/\n\n \/\/ load header information\n \/\/ assume char width, height, pose all the same for all standards\n int char_width;\n int char_height;\n float pose_rotation_matrix[9] = { 0, 0, 0, 0, 0, 0, 0, 0, 0 };\n Logging::Logger log;\n log.SetInputFile(standardized_file_path + char_appearance[0] + standardized_file_extension);\n log.ReadHeader();\n \/\/LWRLogParser log_parser = LWRLogParser(standardized_file_path + char_appearance[0] + standardized_file_extension);\n \/\/log_parser.ParseHeader();\n\n \/\/ get char width, char height, rotation matrix\n log.GetCharacterWidth(char_width);\n log.GetCharacterHeight(char_height);\n log.GetPoseRotationMatrix(pose_rotation_matrix);\n\n \/\/ load entire path for each used character\n \/\/ maps 'char' -> vector<float[3]> e.g. '$' -> [[1,2,3], [1,2,4], [1,2,2] ...\n unordered_map<char, vector<vector<float>>> char_path_map;\n for (unsigned int i = 0; i < char_appearance.size(); ++i) {\n char current_char = char_appearance[i];\n ifstream char_file = ifstream(standardized_file_path + char_filename_map[current_char] + standardized_file_extension);\n \/\/ add new entry to map for char\n char_path_map[current_char] = vector<vector<float>>();\n \/\/ read path\n log.ReadStandardizedCharacterPath(&char_file, char_path_map[current_char]);\n }\n\n \/\/ set rotation matrix in commanded pose\n \/\/ same rotation matrix is used for all points\n \/\/ limited scope\n {\n int i = 0;\n int j = 0;\n for (i; i < NUMBER_OF_FRAME_ELEMENTS; ++i) {\n pose_cmd[i] = pose_rotation_matrix[j++];\n if ((i + 1) % 4 == 0) {\n i++;\n }\n }\n }\n \n \/\/ get starting position\n char tmp = ascii_img[0][0];\n vector<float> starting_xyz = char_path_map[tmp][0];\n pose_cmd[3] = starting_xyz[0];\n pose_cmd[7] = starting_xyz[1];\n pose_cmd[11] = starting_xyz[2];\n \/\/ add starting position offset\n\n \/\/ move to starting position\n int err_val = EOK;\n printf(\"MOVING to starting position.\\n\");\n \n \/\/err_val = MoveToJointPosition({-0.669f, 43.977f, 0.690f, -101.919f, -0.207f, -55.887f, -0.368f});\n \/\/err_val = MoveToCartesianPose(pose_cmd);\n \/\/if (err_val != EOK) {\n \/\/ fri_->printf(\"ERROR, cannot move robot to position\\n\");\n \/\/}\n \/\/else {\n \/\/ printf(\"MOVED to starting position\\n\");\n \/\/}\n \/\/ start cartesian impedance control mode\n err_val = StartCartesianImpedanceControlMode(CARTESIAN_STIFFNESS_HIGH, CARTESIAN_DAMPING_LOW, CARTESIAN_TORQUE_NONE);\n if (err_val != EOK) {\n printf(\"ERROR, could not start robot in CartImpedanceControlMode\");\n return err_val;\n }\n\n ofstream output(\"C:\\\\Users\\\\HMMS\\\\Documents\\\\GitHub\\\\Thesis\\\\KUKA LWR\\\\misc\\\\ascii_art_path.txt\");\n\n \/\/ loop over char in 2D ascii art array\n\n \/\/ for this printer pattern add:\n \/\/ new line at end to even line numbers\n \/\/ inv(space), new line to the start odd line numbers\n \/*\n for (int i = 0; i < ascii_img.size(); ++i) {\n if (i % 2 == 0) {\n ascii_img[i].push_back('\\n');\n }\n else {\n ascii_img[i].insert(ascii_img[i].begin(), '\\b');\n }\n }\n *\/\n row = 0;\n for (auto ascii_row : ascii_img) {\n column = 0;\n if ((row % 2) == 1) { \/\/ odd == right to left\n\n for (column = ascii_row.size() - 1; column >= 0; column--) {\n char ascii_character = ascii_row[column];\n printf(\"%c\", ascii_character);\n \/\/output << ascii_character << \"\\n\";\n auto path = char_path_map[ascii_character];\n for (int elem = path.size() -1 ; elem >= 0; elem--) {\n \/\/printf(\"%d\/%d\\n\", path.size()-1-elem, path.size());\n \/\/ wait one KRC iteration cycle\n fri_->WaitForKRCTick();\n\n \/\/ check for connection issues\n \n if (!fri_->IsMachineOK()) {\n fprintf(stderr, \"ERROR, the machine is not ready anymore.\\n\");\n err_val = Errors::ERROR_MACHINE_NOT_OKAY;\n break;\n }\n \n\n \/\/ set commanded pose displacements to standardized path value\n \/\/ rotations will never change and are set origionally\n pose_cmd[3] = path[elem][0];\n pose_cmd[7] = path[elem][1];\n pose_cmd[11] = path[elem][2];\n\n \/\/ add starting point\n pose_cmd[3] += start[0];\n pose_cmd[7] += start[1];\n pose_cmd[11] += start[2];\n\n \/\/ add position x y global offset\n pose_cmd[3] += (float)(column*char_width) \/ 1000.0f; \/\/ mm to m\n pose_cmd[7] -= (float)(row*char_height) \/ 1000.0f;\n\n fri_->SetCommandedCartPose(pose_cmd);\n \/\/printf(\"%.5f, %.5f, %.5f\\n\", pose_cmd[3], pose_cmd[7], pose_cmd[11]);\n output << pose_cmd[3] << \"\\t\" << pose_cmd[7] << \"\\t\" << pose_cmd[11] << \"\\n\";\n }\n }\n printf(\"\\n\");\n }\n else { \/\/ forward\n for (column = 0; column < static_cast<int>(ascii_row.size()); ++column) {\n char ascii_character = ascii_row[column];\n printf(\"%c\", ascii_character);\n \/\/output << ascii_character << \"\\n\";\n auto path = char_path_map[ascii_character];\n\n for (unsigned int elem = 0; elem < path.size(); ++elem) {\n \/\/printf(\"%d\/%d\\n\", elem, path.size()-1);\n \/\/ wait one KRC iteration cycle\n fri_->WaitForKRCTick();\n\n \/\/ check for connection issues\n \n if (!fri_->IsMachineOK()) {\n fprintf(stderr, \"ERROR, the machine is not ready anymore.\\n\");\n err_val = Errors::ERROR_MACHINE_NOT_OKAY;\n break;\n }\n \n\n \/\/ set commanded pose displacements to standardized path value\n \/\/ rotations will never change and are set origionally\n pose_cmd[3] = path[elem][0];\n pose_cmd[7] = path[elem][1];\n pose_cmd[11] = path[elem][2];\n\n \/\/ add starting point\n pose_cmd[3] += start[0];\n pose_cmd[7] += start[1];\n pose_cmd[11] += start[2];\n\n \/\/ add position x y global offset\n pose_cmd[3] += (float)(column*char_width) \/ 1000.0f; \/\/ mm to m\n pose_cmd[7] -= (float)(row*char_height) \/ 1000.0f;\n\n fri_->SetCommandedCartPose(pose_cmd);\n \/\/printf(\"%.5f, %.5f, %.5f\\n\", pose_cmd[3], pose_cmd[7], pose_cmd[11]);\n output << pose_cmd[3] << \"\\t\" << pose_cmd[7] << \"\\t\" << pose_cmd[11] << \"\\n\";\n }\n }\n printf(\"\\n\");\n }\n \/\/ add new line\n auto path = char_path_map['\\n'];\n column < 0 ? column++ : column-- ;\n for (unsigned int elem = 0; elem < path.size(); ++elem) {\n \/\/printf(\"%d\/%d\\n\", elem, path.size() - 1);\n \/\/ wait one KRC iteration cycle\n fri_->WaitForKRCTick();\n\n \/\/ check for connection issues\n\n if (!fri_->IsMachineOK()) {\n fprintf(stderr, \"ERROR, the machine is not ready anymore.\\n\");\n err_val = Errors::ERROR_MACHINE_NOT_OKAY;\n break;\n }\n\n \/\/ set commanded pose displacements to standardized path value\n \/\/ rotations will never change and are set origionally\n pose_cmd[3] = path[elem][0];\n pose_cmd[7] = path[elem][1];\n pose_cmd[11] = path[elem][2];\n\n \/\/ add starting point\n pose_cmd[3] += start[0];\n pose_cmd[7] += start[1];\n pose_cmd[11] += start[2];\n\n \/\/ add position x y global offset\n pose_cmd[3] += (float)(column*char_width) \/ 1000.0f; \/\/ mm to m\n pose_cmd[7] -= (float)(row*char_height) \/ 1000.0f;\n\n fri_->SetCommandedCartPose(pose_cmd);\n \/\/printf(\"%.5f, %.5f, %.5f\\n\", pose_cmd[3], pose_cmd[7], pose_cmd[11]);\n output << pose_cmd[3] << \"\\t\" << pose_cmd[7] << \"\\t\" << pose_cmd[11] << \"\\n\";\n }\n\n row++;\n }\n\n \/\/ stop\n fri_->StopRobot();\n return EOK;\n}<commit_msg>Generate ascii art file<commit_after>\/\/ from execute.cpp\nvoid DrawASCII(LWR& lwr) {\n string ascii_filename;\n fprintf(stdout, \"What ASCII photo would you like me to draw?\\n> \");\n cin >> ascii_filename;\n lwr.DrawASCIIPhoto(ASCII_PATH + ascii_filename + TXT);\n}\n\n\/\/ from LWR\n \/\/ Just for fun draw a file containing ASCII characters\n int DrawASCIIPhoto(std::string path_to_ascii_file = \"\",\n double speed_percent = 100.0);\n\n\/\/ from utils\nnamespace AsciiArt {\n int Generate2DVectorFromASCIIFile(std::string ascii_file,\n std::vector<std::vector<char>>& ascii_img,\n std::unordered_map<char, std::string> character_set,\n std::vector<char>& char_appearance);\n};\n\nnamespace AsciiArt {\n int Generate2DVectorFromASCIIFile(string ascii_file,\n vector<vector<char>>& ascii_img,\n unordered_map<char, string> character_set,\n vector<char>& char_appearance) {\n\n ifstream ss_ascii_file(ascii_file);\n if (!ss_ascii_file.is_open()) {\n printf(\"Unable to open ASCII file\");\n return ERROR_FILE_NOT_FOUND;\n }\n\n string line;\n int row = 0;\n while (getline(ss_ascii_file, line)) {\n ascii_img.push_back(vector<char>()); \/\/ row vector columns set to line size\n for (unsigned int i = 0; i<line.length(); i++) {\n ascii_img[row].push_back(line.at(i)); \/\/ set character\n if (character_set.erase(line[i]) == 1) { \/\/ just removed from map\n char_appearance.push_back(line.at(i));\n }\n }\n row++;\n }\n return SUCCESS;\n }\n}\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/ ASCII \/\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/ This comes from the thesis and thus needs to be heavily modified.\n\n\n\/\/ .png or .jpg photo should first be converted into an ASCII photo.\n\/*\nint LWR::DrawASCIIPhoto(string path_to_ascii_file,\n double speed_percent) {\n vector<vector<char>> ascii_img;\n vector<cart_motion*> character_motion_paths;\n unordered_map<char, int> character_freq;\n unsigned int err_val = 0;\n\n if (path_to_ascii_file != \"\") {\n \/\/ read ASCII photo from file into 2D vector.\n Generate2DVectorFromASCIIFile(path_to_ascii_file, ascii_img,\n character_freq);\n\n int img_width = ascii_img.at(0).size();\n int img_height = ascii_img.size();\n LWRLogParser log_parser = LWRLogParser();\n\n \/\/ load motion profiles for all characters in ascii drawing\n \/\/ from motion normalized log files\n for (const auto &myPair : character_freq) {\n string log_file = KUKA_LOG_DIR;\n log_file += myPair.first;\n log_file += \"_standardized\";\n log_file += KUKA_LOG_EXTENSION;\n log_parser.SetLogFile(log_file);\n\n character_motion_paths.push_back(new cart_motion());\n\n \/\/ parse log file and generate motion to repeat\n err_val = log_parser.ParseMotion(NULL, character_motion_paths.back());\n if (err_val != EOK) {\n printf(\"ERROR, could not parse input file\");\n \/\/ add deleting\n \/\/ delete &cart_path;\n return ERROR_INVALID_INPUT_FILE;\n }\n }\n\n }\n else {\n \/\/ keyboard input script\n }\n return 1;\n}\n*\/\nint LWR::DrawASCIIPhoto(string path_to_ascii_file,\n double speed_percent) {\n \/\/ assume standardized character recording files have been created\n\n \/\/ start with map character -> filename\n string standardized_file_path = \"C:\\\\Users\\\\HMMS\\\\Documents\\\\GitHub\\\\Thesis\\\\KUKA LWR\\\\logs\\\\standardized_char_set\\\\\";\n string standardized_file_extension = \".dat\";\n static unordered_map<char, string> char_filename_map = {\n { '$', \"$\" }, { ' ', \"space\" }, { '+', \"+\" }, { '7', \"7\" }, { '8', \"8\" },\n { ':', \"colon\" }, { '=', \"equal\" }, { '?', \"question\" }, { 'D', \"D\" },\n { 'I', \"I\" }, { 'M', \"M\" }, { 'N', \"N\" }, { 'O', \"O\" }, { 'Z', \"Z\" },\n { '~', \"tilde\" }, { '\\n', \"newline\" }, {'\\b', \"newline_left\"}\n };\n \/\/ reserve for char order and appearance in ASCII file\n vector<char> char_appearance;\n \/\/float start[3] = { -0.7, 0.4, -0.0145 };\n float start[3] = { -0.70f, 0.0f, 0.200f }; \/\/ draw on table\n int column = 0;\n int row = 0;\n\n \/\/ create 2D character array for ascii art photo\n \/\/ get mapping in order of what characters are in the file\n vector<vector<char>> ascii_img;\n AsciiArt::Generate2DVectorFromASCIIFile(path_to_ascii_file, ascii_img, char_filename_map, char_appearance);\n\n \/\/ artificially add \\n and \\b to appearance\n char_appearance.push_back('\\n');\n \/\/char_appearance.push_back('\\b');\n\n \/\/ map character to open file stream (hardcore)\n \/*\n unordered_map<char, ifstream> char_files;\n for (int i = 0; i < char_appearance.size(); ++i) {\n char_files[i] = ifstream(char_filename_map[char_appearance[i]]);\n }\n *\/\n\n \/\/ load header information\n \/\/ assume char width, height, pose all the same for all standards\n int char_width;\n int char_height;\n float pose_rotation_matrix[9] = { 0, 0, 0, 0, 0, 0, 0, 0, 0 };\n Logging::Logger log;\n log.SetInputFile(standardized_file_path + char_appearance[0] + standardized_file_extension);\n log.ReadHeader();\n \/\/LWRLogParser log_parser = LWRLogParser(standardized_file_path + char_appearance[0] + standardized_file_extension);\n \/\/log_parser.ParseHeader();\n\n \/\/ get char width, char height, rotation matrix\n log.GetCharacterWidth(char_width);\n log.GetCharacterHeight(char_height);\n log.GetPoseRotationMatrix(pose_rotation_matrix);\n\n \/\/ load entire path for each used character\n \/\/ maps 'char' -> vector<float[3]> e.g. '$' -> [[1,2,3], [1,2,4], [1,2,2] ...\n unordered_map<char, vector<vector<float>>> char_path_map;\n for (unsigned int i = 0; i < char_appearance.size(); ++i) {\n char current_char = char_appearance[i];\n ifstream char_file = ifstream(standardized_file_path + char_filename_map[current_char] + standardized_file_extension);\n \/\/ add new entry to map for char\n char_path_map[current_char] = vector<vector<float>>();\n \/\/ read path\n log.ReadStandardizedCharacterPath(&char_file, char_path_map[current_char]);\n }\n\n \/\/ set rotation matrix in commanded pose\n \/\/ same rotation matrix is used for all points\n \/\/ limited scope\n {\n int i = 0;\n int j = 0;\n for (i; i < NUMBER_OF_FRAME_ELEMENTS; ++i) {\n pose_cmd[i] = pose_rotation_matrix[j++];\n if ((i + 1) % 4 == 0) {\n i++;\n }\n }\n }\n \n \/\/ get starting position\n char tmp = ascii_img[0][0];\n vector<float> starting_xyz = char_path_map[tmp][0];\n pose_cmd[3] = starting_xyz[0];\n pose_cmd[7] = starting_xyz[1];\n pose_cmd[11] = starting_xyz[2];\n \/\/ add starting position offset\n\n \/\/ move to starting position\n int err_val = EOK;\n printf(\"MOVING to starting position.\\n\");\n \n \/\/err_val = MoveToJointPosition({-0.669f, 43.977f, 0.690f, -101.919f, -0.207f, -55.887f, -0.368f});\n \/\/err_val = MoveToCartesianPose(pose_cmd);\n \/\/if (err_val != EOK) {\n \/\/ fri_->printf(\"ERROR, cannot move robot to position\\n\");\n \/\/}\n \/\/else {\n \/\/ printf(\"MOVED to starting position\\n\");\n \/\/}\n \/\/ start cartesian impedance control mode\n err_val = StartCartesianImpedanceControlMode(CARTESIAN_STIFFNESS_HIGH, CARTESIAN_DAMPING_LOW, CARTESIAN_TORQUE_NONE);\n if (err_val != EOK) {\n printf(\"ERROR, could not start robot in CartImpedanceControlMode\");\n return err_val;\n }\n\n ofstream output(\"C:\\\\Users\\\\HMMS\\\\Documents\\\\GitHub\\\\Thesis\\\\KUKA LWR\\\\misc\\\\ascii_art_path.txt\");\n\n \/\/ loop over char in 2D ascii art array\n\n \/\/ for this printer pattern add:\n \/\/ new line at end to even line numbers\n \/\/ inv(space), new line to the start odd line numbers\n \/*\n for (int i = 0; i < ascii_img.size(); ++i) {\n if (i % 2 == 0) {\n ascii_img[i].push_back('\\n');\n }\n else {\n ascii_img[i].insert(ascii_img[i].begin(), '\\b');\n }\n }\n *\/\n row = 0;\n for (auto ascii_row : ascii_img) {\n column = 0;\n if ((row % 2) == 1) { \/\/ odd == right to left\n\n for (column = ascii_row.size() - 1; column >= 0; column--) {\n char ascii_character = ascii_row[column];\n printf(\"%c\", ascii_character);\n \/\/output << ascii_character << \"\\n\";\n auto path = char_path_map[ascii_character];\n for (int elem = path.size() -1 ; elem >= 0; elem--) {\n \/\/printf(\"%d\/%d\\n\", path.size()-1-elem, path.size());\n \/\/ wait one KRC iteration cycle\n fri_->WaitForKRCTick();\n\n \/\/ check for connection issues\n \n if (!fri_->IsMachineOK()) {\n fprintf(stderr, \"ERROR, the machine is not ready anymore.\\n\");\n err_val = Errors::ERROR_MACHINE_NOT_OKAY;\n break;\n }\n \n\n \/\/ set commanded pose displacements to standardized path value\n \/\/ rotations will never change and are set origionally\n pose_cmd[3] = path[elem][0];\n pose_cmd[7] = path[elem][1];\n pose_cmd[11] = path[elem][2];\n\n \/\/ add starting point\n pose_cmd[3] += start[0];\n pose_cmd[7] += start[1];\n pose_cmd[11] += start[2];\n\n \/\/ add position x y global offset\n pose_cmd[3] += (float)(column*char_width) \/ 1000.0f; \/\/ mm to m\n pose_cmd[7] -= (float)(row*char_height) \/ 1000.0f;\n\n fri_->SetCommandedCartPose(pose_cmd);\n \/\/printf(\"%.5f, %.5f, %.5f\\n\", pose_cmd[3], pose_cmd[7], pose_cmd[11]);\n output << pose_cmd[3] << \"\\t\" << pose_cmd[7] << \"\\t\" << pose_cmd[11] << \"\\n\";\n }\n }\n printf(\"\\n\");\n }\n else { \/\/ forward\n for (column = 0; column < static_cast<int>(ascii_row.size()); ++column) {\n char ascii_character = ascii_row[column];\n printf(\"%c\", ascii_character);\n \/\/output << ascii_character << \"\\n\";\n auto path = char_path_map[ascii_character];\n\n for (unsigned int elem = 0; elem < path.size(); ++elem) {\n \/\/printf(\"%d\/%d\\n\", elem, path.size()-1);\n \/\/ wait one KRC iteration cycle\n fri_->WaitForKRCTick();\n\n \/\/ check for connection issues\n \n if (!fri_->IsMachineOK()) {\n fprintf(stderr, \"ERROR, the machine is not ready anymore.\\n\");\n err_val = Errors::ERROR_MACHINE_NOT_OKAY;\n break;\n }\n \n\n \/\/ set commanded pose displacements to standardized path value\n \/\/ rotations will never change and are set origionally\n pose_cmd[3] = path[elem][0];\n pose_cmd[7] = path[elem][1];\n pose_cmd[11] = path[elem][2];\n\n \/\/ add starting point\n pose_cmd[3] += start[0];\n pose_cmd[7] += start[1];\n pose_cmd[11] += start[2];\n\n \/\/ add position x y global offset\n pose_cmd[3] += (float)(column*char_width) \/ 1000.0f; \/\/ mm to m\n pose_cmd[7] -= (float)(row*char_height) \/ 1000.0f;\n\n fri_->SetCommandedCartPose(pose_cmd);\n \/\/printf(\"%.5f, %.5f, %.5f\\n\", pose_cmd[3], pose_cmd[7], pose_cmd[11]);\n output << pose_cmd[3] << \"\\t\" << pose_cmd[7] << \"\\t\" << pose_cmd[11] << \"\\n\";\n }\n }\n printf(\"\\n\");\n }\n \/\/ add new line\n auto path = char_path_map['\\n'];\n column < 0 ? column++ : column-- ;\n for (unsigned int elem = 0; elem < path.size(); ++elem) {\n \/\/printf(\"%d\/%d\\n\", elem, path.size() - 1);\n \/\/ wait one KRC iteration cycle\n fri_->WaitForKRCTick();\n\n \/\/ check for connection issues\n\n if (!fri_->IsMachineOK()) {\n fprintf(stderr, \"ERROR, the machine is not ready anymore.\\n\");\n err_val = Errors::ERROR_MACHINE_NOT_OKAY;\n break;\n }\n\n \/\/ set commanded pose displacements to standardized path value\n \/\/ rotations will never change and are set origionally\n pose_cmd[3] = path[elem][0];\n pose_cmd[7] = path[elem][1];\n pose_cmd[11] = path[elem][2];\n\n \/\/ add starting point\n pose_cmd[3] += start[0];\n pose_cmd[7] += start[1];\n pose_cmd[11] += start[2];\n\n \/\/ add position x y global offset\n pose_cmd[3] += (float)(column*char_width) \/ 1000.0f; \/\/ mm to m\n pose_cmd[7] -= (float)(row*char_height) \/ 1000.0f;\n\n fri_->SetCommandedCartPose(pose_cmd);\n \/\/printf(\"%.5f, %.5f, %.5f\\n\", pose_cmd[3], pose_cmd[7], pose_cmd[11]);\n output << pose_cmd[3] << \"\\t\" << pose_cmd[7] << \"\\t\" << pose_cmd[11] << \"\\n\";\n }\n\n row++;\n }\n\n \/\/ stop\n fri_->StopRobot();\n return EOK;\n}<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 2005, Peter Sommerlad and IFS Institute for Software at HSR Rapperswil, Switzerland\n * All rights reserved.\n *\n * This library\/application is free software; you can redistribute and\/or modify it under the terms of\n * the license that is included with this library\/application in the file license.txt.\n *\/\n\n\/\/--- interface include --------------------------------------------------------\n#include \"LFListenerPoolTest.h\"\n\n\/\/--- module under test --------------------------------------------------------\n#include \"LFListenerPool.h\"\n\n\/\/--- test modules used --------------------------------------------------------\n#include \"TestSuite.h\"\n\n\/\/--- standard modules used ----------------------------------------------------\n#include \"Socket.h\"\n#include \"WPMStatHandler.h\"\n#include \"RequestProcessor.h\"\n\n\/\/--- TestRequestReactor ----\n\/\/:test driver for lf pool testing\nclass TestProcessor: public RequestProcessor\n{\npublic:\n\tTestProcessor(LFListenerPoolTest *);\n\t~TestProcessor();\n\tvoid ProcessRequest(Context &ctx);\n\nprotected:\n\tLFListenerPoolTest *fTest;\n};\n\nTestProcessor::TestProcessor(LFListenerPoolTest *test)\n\t: RequestProcessor(\"TestProcessor\")\n\t, fTest(test)\n{\n\tStartTrace(TestProcessor.Ctor);\n}\n\nTestProcessor::~TestProcessor()\n{\n\tStartTrace(TestProcessor.Dtor);\n}\n\nvoid TestProcessor::ProcessRequest(Context &ctx)\n{\n\tStartTrace(TestProcessor.ProcessRequest);\n\tfTest->EventProcessed(ctx.GetSocket());\n}\n\n\/\/---- LFListenerPoolTest ----------------------------------------------------------------\nLFListenerPoolTest::LFListenerPoolTest(TString tstrName)\n\t: TestCaseType(tstrName)\n{\n\tStartTrace(LFListenerPoolTest.LFListenerPoolTest);\n}\n\nLFListenerPoolTest::~LFListenerPoolTest()\n{\n\tStartTrace(LFListenerPoolTest.Dtor);\n}\n\nvoid LFListenerPoolTest::setUp ()\n{\n\tStartTrace(LFListenerPoolTest.setUp);\n\tt_assert(GetConfig().IsDefined(\"Modules\"));\n}\n\nvoid LFListenerPoolTest::NoReactorTest()\n{\n\tStartTrace(LFListenerPoolTest.NoReactorTest);\n\tLFListenerPool lfp(0);\n\n\tTrace(\"ip:\" << GetConfig()[\"Testhost\"][\"ip\"].AsString() << \" : port:\" << GetConfig()[\"Testhost\"][\"port\"].AsLong());\n\tAcceptor ac1(GetConfig()[\"Testhost\"][\"ip\"].AsString(), GetConfig()[\"Testhost\"][\"port\"].AsLong(), 5, 0);\n\tAnything lfpConfig;\n\tlfpConfig[String(\"Accept\") << GetConfig()[\"Testhost\"][\"port\"].AsString()] = (IFAObject *)&ac1;\n\tif ( t_assertm( !lfp.Init(2, lfpConfig, true), \"no reactor is configured; init should fail\")) {\n\t\tt_assertm(lfp.GetPoolSize() == 0, \"expected no threads in pool\");\n\t\tt_assertm(lfp.Start(true, 1000, 10) == -1, \"expected Start to fail\");\n\t}\n}\n\nvoid LFListenerPoolTest::NoFactoryTest()\n{\n\tStartTrace(LFListenerPoolTest.NoFactoryTest);\n\tconst long cNumOfThreads = 2;\n\tLFListenerPool lfp(new RequestReactor(new TestProcessor(this), new WPMStatHandler(cNumOfThreads)));\n\n\tAnything lfpConfig;\n\tlfpConfig.Append(\"TCP4343\");\n\tif (t_assertm(!lfp.Init(cNumOfThreads, lfpConfig, true), \"expected initialization to fail; no valid factory\")) {\n\t\tt_assertm(lfp.GetPoolSize() == 0, \"expected no threads in pool\");\n\t\tt_assertm(lfp.Start(true, 1000, 10) == -1, \"expected Start to fail\");\n\t}\n}\n\nvoid LFListenerPoolTest::InvalidAcceptorTest()\n{\n\tStartTrace(LFListenerPoolTest.InvalidAcceptorTest);\n\tconst long cNumOfThreads = 2;\n\tLFListenerPool lfp(new RequestReactor(new TestProcessor(this), new WPMStatHandler(cNumOfThreads)));\n\n\tAnything lfpConfig;\n\tlfpConfig.Append(\"Fake\");\n\tif (t_assertm(!lfp.Init(cNumOfThreads, lfpConfig, true), \"expected initialization to fail; acceptor is not valid\")) {\n\t\tt_assertm(lfp.GetPoolSize() == 0, \"expected no threads in pool\");\n\t\tt_assertm(lfp.Start(true, 1000, 10) == -1, \"expected Start to fail\");\n\t}\n}\n\nvoid LFListenerPoolTest::InvalidReactorTest()\n{\n\tStartTrace(LFListenerPoolTest.InvalidReactorTest);\n\tconst long cNumOfThreads = 2;\n\tLFListenerPool lfp(new RequestReactor(0, 0));\n\n\tAnything lfpConfig;\n\tlfpConfig.Append(\"TCP5010\");\n\tif (t_assertm(!lfp.Init(cNumOfThreads, lfpConfig, true), \"expected initialization to fail; reactor is not valid\")) {\n\t\tt_assertm(lfp.GetPoolSize() == 0, \"expected no threads in pool\");\n\t\tt_assertm(lfp.Start(true, 1000, 10) == -1, \"expected Start to fail\");\n\t}\n}\n\nvoid LFListenerPoolTest::OneAcceptorTest()\n{\n\tStartTrace(LFListenerPoolTest.OneAcceptorTest);\n\tconst long cNumOfThreads = 2;\n\tLFListenerPool lfp(new RequestReactor(new TestProcessor(this), new WPMStatHandler(cNumOfThreads)));\n\n\tAnything lfpConfig;\n\tlfpConfig.Append(\"TCP5010\");\n\tif (t_assertm(lfp.Init(cNumOfThreads, lfpConfig, true), \"expected initialization to succeed; are factories present?\")) {\n\t\tif (t_assert(lfp.Start(true, 1000, 10) == 0 )) {\n\t\t\tProcessOneEvent();\n\t\t\tlfp.RequestTermination();\n\t\t\tt_assertm(lfp.Join() == 0, \"expected Join to succeed\");\n\t\t}\n\t}\n}\n\nvoid LFListenerPoolTest::TwoAcceptorsTest()\n{\n\tStartTrace(LFListenerPoolTest.TwoAcceptorsTest);\n\tconst long cNumOfThreads = 3;\n\tLFListenerPool lfp(new RequestReactor(new TestProcessor(this), new WPMStatHandler(cNumOfThreads)));\n\n\tAnything lfpConfig;\n\tlfpConfig.Append(\"TCP5010\");\n\tlfpConfig.Append(\"TCP5011\");\n\tif (t_assertm(lfp.Init(cNumOfThreads, lfpConfig, true), \"expected initialization to succeed; are factories present?\")) {\n\t\tif (t_assert(lfp.Start(true, 1000, 10) == 0 )) {\n\t\t\tProcessTwoEvents();\n\t\t\tlfp.RequestTermination();\n\t\t\tt_assertm(lfp.Join() == 0, \"expected Join to succeed\");\n\t\t}\n\t}\n}\n\nvoid LFListenerPoolTest::ManyAcceptorsTest()\n{\n\tStartTrace(LeaderFollowerPoolTest.ManyAcceptorsTest);\n\t{\n\t\tconst long cNumOfThreads = 0;\n\t\tLFListenerPool lfp(new RequestReactor(new TestProcessor(this), new WPMStatHandler(cNumOfThreads)));\n\n\t\tAnything lfpConfig;\n\t\tlfpConfig.Append(\"TCP5010\");\n\t\tlfpConfig.Append(\"TCP5011\");\n\t\tlfpConfig.Append(\"TCP5012\");\n\n\t\tif (t_assertm(!lfp.Init(cNumOfThreads, lfpConfig, true), \"should not allow LFPool to run without threads\")) {\n\t\t\tt_assertm(lfp.GetPoolSize() == 0, \"expected no threads in pool\");\n\t\t\tt_assertm(lfp.Start(true, 1000, 10) == -1, \"expected Start to fail\");\n\n\t\t}\n\t}\n\t{\n\t\tconst long cNumOfThreads = 1;\n\t\tLFListenerPool lfp(new RequestReactor(new TestProcessor(this), new WPMStatHandler(cNumOfThreads)));\n\n\t\tAnything lfpConfig;\n\t\tlfpConfig.Append(\"TCP5010\");\n\t\tlfpConfig.Append(\"TCP5011\");\n\t\tlfpConfig.Append(\"TCP5012\");\n\n\t\tif (t_assertm(lfp.Init(cNumOfThreads, lfpConfig, true), \"some port maybe already bound\")) {\n\t\t\tif (t_assert(lfp.Start(false, 1000, 10) == 0 )) {\n\t\t\t\tProcessManyEvents();\n\t\t\t\tlfp.RequestTermination();\n\t\t\t\tt_assertm(lfp.Join() == 0, \"expected Join to succeed\");\n\t\t\t}\n\t\t}\n\t}\n\t{\n\t\tconst long cNumOfThreads = 2;\n\t\tLFListenerPool lfp(new RequestReactor(new TestProcessor(this), new WPMStatHandler(cNumOfThreads)));\n\n\t\tAnything lfpConfig;\n\t\tlfpConfig.Append(\"TCP5010\");\n\t\tlfpConfig.Append(\"TCP5011\");\n\t\tlfpConfig.Append(\"TCP5012\");\n\n\t\tif (t_assertm(lfp.Init(cNumOfThreads, lfpConfig, true), \"some port maybe already bound\")) {\n\t\t\tif (t_assert(lfp.Start(false, 1000, 10) == 0 )) {\n\t\t\t\tProcessManyEvents();\n\t\t\t\tlfp.RequestTermination();\n\t\t\t\tt_assertm(lfp.Join() == 0, \"expected Join to succeed\");\n\t\t\t}\n\t\t}\n\t}\n\t{\n\t\tconst long cNumOfThreads = 3;\n\t\tLFListenerPool lfp(new RequestReactor(new TestProcessor(this), new WPMStatHandler(cNumOfThreads)));\n\n\t\tAnything lfpConfig;\n\t\tlfpConfig.Append(\"TCP5010\");\n\t\tlfpConfig.Append(\"TCP5011\");\n\t\tlfpConfig.Append(\"TCP5012\");\n\n\t\tif (t_assertm(lfp.Init(cNumOfThreads, lfpConfig, true), \"some port maybe already bound\")) {\n\t\t\tif (t_assert(lfp.Start(false, 1000, 10) == 0 )) {\n\t\t\t\tProcessManyEvents();\n\t\t\t\tlfp.RequestTermination();\n\t\t\t\tt_assertm(lfp.Join() == 0, \"expected Join to succeed\");\n\t\t\t}\n\t\t}\n\t}\n\t{\n\t\tconst long cNumOfThreads = 4;\n\t\tLFListenerPool lfp(new RequestReactor(new TestProcessor(this), new WPMStatHandler(cNumOfThreads)));\n\n\t\tAnything lfpConfig;\n\t\tlfpConfig.Append(\"TCP5010\");\n\t\tlfpConfig.Append(\"TCP5011\");\n\t\tlfpConfig.Append(\"TCP5012\");\n\n\t\tif (t_assertm(lfp.Init(cNumOfThreads, lfpConfig, true), \"some port maybe already bound\")) {\n\t\t\tif (t_assert(lfp.Start(true, 1000, 10) == 0 )) {\n\t\t\t\tProcessManyEvents();\n\t\t\t\tlfp.RequestTermination();\n\t\t\t\tt_assertm(lfp.Join() == 0, \"expected Join to succeed\");\n\t\t\t}\n\t\t}\n\t}\n}\n\nbool LFListenerPoolTest::EventProcessed(Socket *socket)\n{\n\tStartTrace(LFListenerPoolTest.EventProcessed);\n\tif (t_assert(socket != NULL)) {\n\t\tString request;\n\t\t(*socket->GetStream()) >> request;\n\t\tassertEqual(\"hallo\", request);\n\t\t(*socket->GetStream()) << \"HostReply\" << endl;\n\t\treturn true;\n\t}\n\treturn false;\n}\n\nvoid LFListenerPoolTest::ProcessOneEvent()\n{\n\tStartTrace(LeaderFollowerPoolTest.ProcessOneEvent);\n\tConnector c1(GetConfig()[\"Testhost\"][\"ip\"].AsString(), GetConfig()[\"TCP5010\"][\"Port\"].AsLong());\n\tString reply1;\n\n\tif ( t_assert(c1.GetStream() != NULL) ) {\n\t\t(*c1.GetStream()) << \"hallo\" << endl;\n\t\tt_assert(!!(*c1.GetStream()));\n\t\t(*c1.GetStream()) >> reply1;\n\t\tt_assert(!!(*c1.GetStream()));\n\n\t\tassertEqual(\"HostReply\", reply1);\n\t}\n}\n\nvoid LFListenerPoolTest::ProcessManyEvents()\n{\n\tStartTrace(LeaderFollowerPoolTest.ProcessManyEvents);\n\tConnector c1(GetConfig()[\"Testhost\"][\"ip\"].AsString(), GetConfig()[\"TCP5010\"][\"Port\"].AsLong());\n\tConnector c2(GetConfig()[\"Testhost\"][\"ip\"].AsString(), GetConfig()[\"TCP5011\"][\"Port\"].AsLong());\n\tConnector c3(GetConfig()[\"Testhost\"][\"ip\"].AsString(), GetConfig()[\"TCP5012\"][\"Port\"].AsLong());\n\tString reply1;\n\tString reply2;\n\tString reply3;\n\n\tif (t_assert(c1.GetStream() != NULL) && t_assert(c2.GetStream() != NULL) && t_assert(c3.GetStream() != NULL)) {\n\t\t(*c1.GetStream()) << \"hallo\" << endl;\n\t\t(*c2.GetStream()) << \"hallo\" << endl;\n\t\t(*c3.GetStream()) << \"hallo\" << endl;\n\t\tt_assert(!!(*c1.GetStream()));\n\t\tt_assert(!!(*c2.GetStream()));\n\t\tt_assert(!!(*c3.GetStream()));\n\t\t(*c1.GetStream()) >> reply1;\n\t\t(*c2.GetStream()) >> reply2;\n\t\t(*c3.GetStream()) >> reply3;\n\t\tt_assert(!!(*c1.GetStream()));\n\t\tt_assert(!!(*c2.GetStream()));\n\t\tt_assert(!!(*c3.GetStream()));\n\n\t\tassertEqual(\"HostReply\", reply1);\n\t\tassertEqual(\"HostReply\", reply2);\n\t\tassertEqual(\"HostReply\", reply3);\n\t}\n}\n\nvoid LFListenerPoolTest::ProcessTwoEvents()\n{\n\tStartTrace(LeaderFollowerPoolTest.ProcessTwoEvents);\n\tConnector c1(GetConfig()[\"Testhost\"][\"ip\"].AsString(), GetConfig()[\"TCP5010\"][\"Port\"].AsLong());\n\tConnector c2(GetConfig()[\"Testhost\"][\"ip\"].AsString(), GetConfig()[\"TCP5011\"][\"Port\"].AsLong());\n\tString reply1;\n\tString reply2;\n\n\tif (t_assert(c1.GetStream() != NULL) && t_assert(c2.GetStream() != NULL)) {\n\t\t(*c1.GetStream()) << \"hallo\" << endl;\n\t\t(*c2.GetStream()) << \"hallo\" << endl;\n\t\tt_assert(!!(*c1.GetStream()));\n\t\tt_assert(!!(*c2.GetStream()));\n\t\t(*c1.GetStream()) >> reply1;\n\t\t(*c2.GetStream()) >> reply2;\n\t\tt_assert(!!(*c1.GetStream()));\n\t\tt_assert(!!(*c2.GetStream()));\n\n\t\tassertEqual(\"HostReply\", reply1);\n\t\tassertEqual(\"HostReply\", reply2);\n\t}\n}\n\n\/\/ builds up a suite of testcases, add a line for each testmethod\nTest *LFListenerPoolTest::suite ()\n{\n\tStartTrace(LFListenerPoolTest.suite);\n\tTestSuite *testSuite = new TestSuite;\n\n\tADD_CASE(testSuite, LFListenerPoolTest, NoReactorTest);\n\tADD_CASE(testSuite, LFListenerPoolTest, NoFactoryTest);\n\tADD_CASE(testSuite, LFListenerPoolTest, OneAcceptorTest);\n\tADD_CASE(testSuite, LFListenerPoolTest, TwoAcceptorsTest);\n\tADD_CASE(testSuite, LFListenerPoolTest, ManyAcceptorsTest);\n\tADD_CASE(testSuite, LFListenerPoolTest, InvalidAcceptorTest);\n\tADD_CASE(testSuite, LFListenerPoolTest, InvalidReactorTest);\n\n\treturn testSuite;\n}\n<commit_msg>adjusted PoolAllocator params according to real memory usage<commit_after>\/*\n * Copyright (c) 2005, Peter Sommerlad and IFS Institute for Software at HSR Rapperswil, Switzerland\n * All rights reserved.\n *\n * This library\/application is free software; you can redistribute and\/or modify it under the terms of\n * the license that is included with this library\/application in the file license.txt.\n *\/\n\n\/\/--- interface include --------------------------------------------------------\n#include \"LFListenerPoolTest.h\"\n\n\/\/--- module under test --------------------------------------------------------\n#include \"LFListenerPool.h\"\n\n\/\/--- test modules used --------------------------------------------------------\n#include \"TestSuite.h\"\n\n\/\/--- standard modules used ----------------------------------------------------\n#include \"Socket.h\"\n#include \"WPMStatHandler.h\"\n#include \"RequestProcessor.h\"\n\n\/\/--- TestRequestReactor ----\n\/\/:test driver for lf pool testing\nclass TestProcessor: public RequestProcessor\n{\npublic:\n\tTestProcessor(LFListenerPoolTest *);\n\t~TestProcessor();\n\tvoid ProcessRequest(Context &ctx);\n\nprotected:\n\tLFListenerPoolTest *fTest;\n};\n\nTestProcessor::TestProcessor(LFListenerPoolTest *test)\n\t: RequestProcessor(\"TestProcessor\")\n\t, fTest(test)\n{\n\tStartTrace(TestProcessor.Ctor);\n}\n\nTestProcessor::~TestProcessor()\n{\n\tStartTrace(TestProcessor.Dtor);\n}\n\nvoid TestProcessor::ProcessRequest(Context &ctx)\n{\n\tStartTrace(TestProcessor.ProcessRequest);\n\tfTest->EventProcessed(ctx.GetSocket());\n}\n\n\/\/---- LFListenerPoolTest ----------------------------------------------------------------\nLFListenerPoolTest::LFListenerPoolTest(TString tstrName)\n\t: TestCaseType(tstrName)\n{\n\tStartTrace(LFListenerPoolTest.LFListenerPoolTest);\n}\n\nLFListenerPoolTest::~LFListenerPoolTest()\n{\n\tStartTrace(LFListenerPoolTest.Dtor);\n}\n\nvoid LFListenerPoolTest::setUp ()\n{\n\tStartTrace(LFListenerPoolTest.setUp);\n\tt_assert(GetConfig().IsDefined(\"Modules\"));\n}\n\nvoid LFListenerPoolTest::NoReactorTest()\n{\n\tStartTrace(LFListenerPoolTest.NoReactorTest);\n\tLFListenerPool lfp(0);\n\n\tTrace(\"ip:\" << GetConfig()[\"Testhost\"][\"ip\"].AsString() << \" : port:\" << GetConfig()[\"Testhost\"][\"port\"].AsLong());\n\tAcceptor ac1(GetConfig()[\"Testhost\"][\"ip\"].AsString(), GetConfig()[\"Testhost\"][\"port\"].AsLong(), 5, 0);\n\tAnything lfpConfig;\n\tlfpConfig[String(\"Accept\") << GetConfig()[\"Testhost\"][\"port\"].AsString()] = (IFAObject *)&ac1;\n\tif ( t_assertm( !lfp.Init(2, lfpConfig, true), \"no reactor is configured; init should fail\")) {\n\t\tt_assertm(lfp.GetPoolSize() == 0, \"expected no threads in pool\");\n\t\tt_assertm(lfp.Start(true, 1000, 11) == -1, \"expected Start to fail\");\n\t}\n}\n\nvoid LFListenerPoolTest::NoFactoryTest()\n{\n\tStartTrace(LFListenerPoolTest.NoFactoryTest);\n\tconst long cNumOfThreads = 2;\n\tLFListenerPool lfp(new RequestReactor(new TestProcessor(this), new WPMStatHandler(cNumOfThreads)));\n\n\tAnything lfpConfig;\n\tlfpConfig.Append(\"TCP4343\");\n\tif (t_assertm(!lfp.Init(cNumOfThreads, lfpConfig, true), \"expected initialization to fail; no valid factory\")) {\n\t\tt_assertm(lfp.GetPoolSize() == 0, \"expected no threads in pool\");\n\t\tt_assertm(lfp.Start(true, 1000, 11) == -1, \"expected Start to fail\");\n\t}\n}\n\nvoid LFListenerPoolTest::InvalidAcceptorTest()\n{\n\tStartTrace(LFListenerPoolTest.InvalidAcceptorTest);\n\tconst long cNumOfThreads = 2;\n\tLFListenerPool lfp(new RequestReactor(new TestProcessor(this), new WPMStatHandler(cNumOfThreads)));\n\n\tAnything lfpConfig;\n\tlfpConfig.Append(\"Fake\");\n\tif (t_assertm(!lfp.Init(cNumOfThreads, lfpConfig, true), \"expected initialization to fail; acceptor is not valid\")) {\n\t\tt_assertm(lfp.GetPoolSize() == 0, \"expected no threads in pool\");\n\t\tt_assertm(lfp.Start(true, 1000, 11) == -1, \"expected Start to fail\");\n\t}\n}\n\nvoid LFListenerPoolTest::InvalidReactorTest()\n{\n\tStartTrace(LFListenerPoolTest.InvalidReactorTest);\n\tconst long cNumOfThreads = 2;\n\tLFListenerPool lfp(new RequestReactor(0, 0));\n\n\tAnything lfpConfig;\n\tlfpConfig.Append(\"TCP5010\");\n\tif (t_assertm(!lfp.Init(cNumOfThreads, lfpConfig, true), \"expected initialization to fail; reactor is not valid\")) {\n\t\tt_assertm(lfp.GetPoolSize() == 0, \"expected no threads in pool\");\n\t\tt_assertm(lfp.Start(true, 1000, 11) == -1, \"expected Start to fail\");\n\t}\n}\n\nvoid LFListenerPoolTest::OneAcceptorTest()\n{\n\tStartTrace(LFListenerPoolTest.OneAcceptorTest);\n\tconst long cNumOfThreads = 2;\n\tLFListenerPool lfp(new RequestReactor(new TestProcessor(this), new WPMStatHandler(cNumOfThreads)));\n\n\tAnything lfpConfig;\n\tlfpConfig.Append(\"TCP5010\");\n\tif (t_assertm(lfp.Init(cNumOfThreads, lfpConfig, true), \"expected initialization to succeed; are factories present?\")) {\n\t\tif (t_assert(lfp.Start(true, 1000, 11) == 0 )) {\n\t\t\tProcessOneEvent();\n\t\t\tlfp.RequestTermination();\n\t\t\tt_assertm(lfp.Join() == 0, \"expected Join to succeed\");\n\t\t}\n\t}\n}\n\nvoid LFListenerPoolTest::TwoAcceptorsTest()\n{\n\tStartTrace(LFListenerPoolTest.TwoAcceptorsTest);\n\tconst long cNumOfThreads = 3;\n\tLFListenerPool lfp(new RequestReactor(new TestProcessor(this), new WPMStatHandler(cNumOfThreads)));\n\n\tAnything lfpConfig;\n\tlfpConfig.Append(\"TCP5010\");\n\tlfpConfig.Append(\"TCP5011\");\n\tif (t_assertm(lfp.Init(cNumOfThreads, lfpConfig, true), \"expected initialization to succeed; are factories present?\")) {\n\t\tif (t_assert(lfp.Start(true, 1000, 11) == 0 )) {\n\t\t\tProcessTwoEvents();\n\t\t\tlfp.RequestTermination();\n\t\t\tt_assertm(lfp.Join() == 0, \"expected Join to succeed\");\n\t\t}\n\t}\n}\n\nvoid LFListenerPoolTest::ManyAcceptorsTest()\n{\n\tStartTrace(LeaderFollowerPoolTest.ManyAcceptorsTest);\n\t{\n\t\tconst long cNumOfThreads = 0;\n\t\tLFListenerPool lfp(new RequestReactor(new TestProcessor(this), new WPMStatHandler(cNumOfThreads)));\n\n\t\tAnything lfpConfig;\n\t\tlfpConfig.Append(\"TCP5010\");\n\t\tlfpConfig.Append(\"TCP5011\");\n\t\tlfpConfig.Append(\"TCP5012\");\n\n\t\tif (t_assertm(!lfp.Init(cNumOfThreads, lfpConfig, true), \"should not allow LFPool to run without threads\")) {\n\t\t\tt_assertm(lfp.GetPoolSize() == 0, \"expected no threads in pool\");\n\t\t\tt_assertm(lfp.Start(true, 1000, 11) == -1, \"expected Start to fail\");\n\n\t\t}\n\t}\n\t{\n\t\tconst long cNumOfThreads = 1;\n\t\tLFListenerPool lfp(new RequestReactor(new TestProcessor(this), new WPMStatHandler(cNumOfThreads)));\n\n\t\tAnything lfpConfig;\n\t\tlfpConfig.Append(\"TCP5010\");\n\t\tlfpConfig.Append(\"TCP5011\");\n\t\tlfpConfig.Append(\"TCP5012\");\n\n\t\tif (t_assertm(lfp.Init(cNumOfThreads, lfpConfig, true), \"some port maybe already bound\")) {\n\t\t\tif (t_assert(lfp.Start(false, 1000, 10) == 0 )) {\n\t\t\t\tProcessManyEvents();\n\t\t\t\tlfp.RequestTermination();\n\t\t\t\tt_assertm(lfp.Join() == 0, \"expected Join to succeed\");\n\t\t\t}\n\t\t}\n\t}\n\t{\n\t\tconst long cNumOfThreads = 2;\n\t\tLFListenerPool lfp(new RequestReactor(new TestProcessor(this), new WPMStatHandler(cNumOfThreads)));\n\n\t\tAnything lfpConfig;\n\t\tlfpConfig.Append(\"TCP5010\");\n\t\tlfpConfig.Append(\"TCP5011\");\n\t\tlfpConfig.Append(\"TCP5012\");\n\n\t\tif (t_assertm(lfp.Init(cNumOfThreads, lfpConfig, true), \"some port maybe already bound\")) {\n\t\t\tif (t_assert(lfp.Start(false, 1000, 10) == 0 )) {\n\t\t\t\tProcessManyEvents();\n\t\t\t\tlfp.RequestTermination();\n\t\t\t\tt_assertm(lfp.Join() == 0, \"expected Join to succeed\");\n\t\t\t}\n\t\t}\n\t}\n\t{\n\t\tconst long cNumOfThreads = 3;\n\t\tLFListenerPool lfp(new RequestReactor(new TestProcessor(this), new WPMStatHandler(cNumOfThreads)));\n\n\t\tAnything lfpConfig;\n\t\tlfpConfig.Append(\"TCP5010\");\n\t\tlfpConfig.Append(\"TCP5011\");\n\t\tlfpConfig.Append(\"TCP5012\");\n\n\t\tif (t_assertm(lfp.Init(cNumOfThreads, lfpConfig, true), \"some port maybe already bound\")) {\n\t\t\tif (t_assert(lfp.Start(false, 1000, 10) == 0 )) {\n\t\t\t\tProcessManyEvents();\n\t\t\t\tlfp.RequestTermination();\n\t\t\t\tt_assertm(lfp.Join() == 0, \"expected Join to succeed\");\n\t\t\t}\n\t\t}\n\t}\n\t{\n\t\tconst long cNumOfThreads = 4;\n\t\tLFListenerPool lfp(new RequestReactor(new TestProcessor(this), new WPMStatHandler(cNumOfThreads)));\n\n\t\tAnything lfpConfig;\n\t\tlfpConfig.Append(\"TCP5010\");\n\t\tlfpConfig.Append(\"TCP5011\");\n\t\tlfpConfig.Append(\"TCP5012\");\n\n\t\tif (t_assertm(lfp.Init(cNumOfThreads, lfpConfig, true), \"some port maybe already bound\")) {\n\t\t\tif (t_assert(lfp.Start(true, 1000, 11) == 0 )) {\n\t\t\t\tProcessManyEvents();\n\t\t\t\tlfp.RequestTermination();\n\t\t\t\tt_assertm(lfp.Join() == 0, \"expected Join to succeed\");\n\t\t\t}\n\t\t}\n\t}\n}\n\nbool LFListenerPoolTest::EventProcessed(Socket *socket)\n{\n\tStartTrace(LFListenerPoolTest.EventProcessed);\n\tif (t_assert(socket != NULL)) {\n\t\tString request;\n\t\t(*socket->GetStream()) >> request;\n\t\tassertEqual(\"hallo\", request);\n\t\t(*socket->GetStream()) << \"HostReply\" << endl;\n\t\treturn true;\n\t}\n\treturn false;\n}\n\nvoid LFListenerPoolTest::ProcessOneEvent()\n{\n\tStartTrace(LeaderFollowerPoolTest.ProcessOneEvent);\n\tConnector c1(GetConfig()[\"Testhost\"][\"ip\"].AsString(), GetConfig()[\"TCP5010\"][\"Port\"].AsLong());\n\tString reply1;\n\n\tif ( t_assert(c1.GetStream() != NULL) ) {\n\t\t(*c1.GetStream()) << \"hallo\" << endl;\n\t\tt_assert(!!(*c1.GetStream()));\n\t\t(*c1.GetStream()) >> reply1;\n\t\tt_assert(!!(*c1.GetStream()));\n\n\t\tassertEqual(\"HostReply\", reply1);\n\t}\n}\n\nvoid LFListenerPoolTest::ProcessManyEvents()\n{\n\tStartTrace(LeaderFollowerPoolTest.ProcessManyEvents);\n\tConnector c1(GetConfig()[\"Testhost\"][\"ip\"].AsString(), GetConfig()[\"TCP5010\"][\"Port\"].AsLong());\n\tConnector c2(GetConfig()[\"Testhost\"][\"ip\"].AsString(), GetConfig()[\"TCP5011\"][\"Port\"].AsLong());\n\tConnector c3(GetConfig()[\"Testhost\"][\"ip\"].AsString(), GetConfig()[\"TCP5012\"][\"Port\"].AsLong());\n\tString reply1;\n\tString reply2;\n\tString reply3;\n\n\tif (t_assert(c1.GetStream() != NULL) && t_assert(c2.GetStream() != NULL) && t_assert(c3.GetStream() != NULL)) {\n\t\t(*c1.GetStream()) << \"hallo\" << endl;\n\t\t(*c2.GetStream()) << \"hallo\" << endl;\n\t\t(*c3.GetStream()) << \"hallo\" << endl;\n\t\tt_assert(!!(*c1.GetStream()));\n\t\tt_assert(!!(*c2.GetStream()));\n\t\tt_assert(!!(*c3.GetStream()));\n\t\t(*c1.GetStream()) >> reply1;\n\t\t(*c2.GetStream()) >> reply2;\n\t\t(*c3.GetStream()) >> reply3;\n\t\tt_assert(!!(*c1.GetStream()));\n\t\tt_assert(!!(*c2.GetStream()));\n\t\tt_assert(!!(*c3.GetStream()));\n\n\t\tassertEqual(\"HostReply\", reply1);\n\t\tassertEqual(\"HostReply\", reply2);\n\t\tassertEqual(\"HostReply\", reply3);\n\t}\n}\n\nvoid LFListenerPoolTest::ProcessTwoEvents()\n{\n\tStartTrace(LeaderFollowerPoolTest.ProcessTwoEvents);\n\tConnector c1(GetConfig()[\"Testhost\"][\"ip\"].AsString(), GetConfig()[\"TCP5010\"][\"Port\"].AsLong());\n\tConnector c2(GetConfig()[\"Testhost\"][\"ip\"].AsString(), GetConfig()[\"TCP5011\"][\"Port\"].AsLong());\n\tString reply1;\n\tString reply2;\n\n\tif (t_assert(c1.GetStream() != NULL) && t_assert(c2.GetStream() != NULL)) {\n\t\t(*c1.GetStream()) << \"hallo\" << endl;\n\t\t(*c2.GetStream()) << \"hallo\" << endl;\n\t\tt_assert(!!(*c1.GetStream()));\n\t\tt_assert(!!(*c2.GetStream()));\n\t\t(*c1.GetStream()) >> reply1;\n\t\t(*c2.GetStream()) >> reply2;\n\t\tt_assert(!!(*c1.GetStream()));\n\t\tt_assert(!!(*c2.GetStream()));\n\n\t\tassertEqual(\"HostReply\", reply1);\n\t\tassertEqual(\"HostReply\", reply2);\n\t}\n}\n\n\/\/ builds up a suite of testcases, add a line for each testmethod\nTest *LFListenerPoolTest::suite ()\n{\n\tStartTrace(LFListenerPoolTest.suite);\n\tTestSuite *testSuite = new TestSuite;\n\n\tADD_CASE(testSuite, LFListenerPoolTest, NoReactorTest);\n\tADD_CASE(testSuite, LFListenerPoolTest, NoFactoryTest);\n\tADD_CASE(testSuite, LFListenerPoolTest, OneAcceptorTest);\n\tADD_CASE(testSuite, LFListenerPoolTest, TwoAcceptorsTest);\n\tADD_CASE(testSuite, LFListenerPoolTest, ManyAcceptorsTest);\n\tADD_CASE(testSuite, LFListenerPoolTest, InvalidAcceptorTest);\n\tADD_CASE(testSuite, LFListenerPoolTest, InvalidReactorTest);\n\n\treturn testSuite;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ cocTimer.h\n\/\/ Created by Lukasz Karluk on 10\/10\/2015.\n\/\/ http:\/\/codeoncanvas.cc\n\/\/\n\n#include \"cocSwipe.h\"\n\nnamespace coc {\n\nusing namespace std;\nusing namespace glm;\n\n\/\/--------------------------------------------------------------\nSwipe::Swipe() {\n\n swipePixelDistanceThreshold = 50;\n swipePixelVelocityThreshold = 100;\n \n reset();\n}\n\nSwipe::~Swipe() {\n \/\/\n}\n\nvoid Swipe::setSwipeArea(const coc::Rect & rect) {\n swipeArea = rect;\n}\n\nvoid Swipe::setSwipeArea(float x, float y, float w, float h) {\n swipeArea.setX(x);\n swipeArea.setY(y);\n swipeArea.setW(w);\n swipeArea.setH(h);\n}\n\nvoid Swipe::setSwipePixelDistanceThreshold(float value) {\n swipePixelDistanceThreshold = value;\n}\n\nvoid Swipe::setSwipePixelVelocityThreshold(float value) {\n swipePixelVelocityThreshold = value;\n}\n\n\/\/--------------------------------------------------------------\nvoid Swipe::update(double _optionalTimeElapsedSinceLastUpdateInSeconds) {\n\n bGestureFoundNew = false; \/\/ clear on every new frame.\n\n \/\/----------------------------------------------------------\n bool bSwipeStopped = false;\n if(points.size() > 0) {\n const SwipePoint & pointLast = points[points.size()-1];\n bSwipeStopped = (pointLast.type == SwipePoint::TypeUp);\n if(bSwipeStopped == true) {\n bool bDownNew = false;\n for(int i=0; i<pointsNew.size(); i++) {\n const SwipePoint & pointNew = pointsNew[i];\n if(pointNew.type == SwipePoint::TypeDown) {\n bDownNew = true;\n break;\n }\n }\n if(bDownNew == true) {\n bSwipeStopped = false;\n reset();\n }\n }\n }\n \n if(bSwipeStopped == true) {\n return;\n }\n\n bool bSwipeStarted = true;\n bSwipeStarted = bSwipeStarted && (points.size() > 0);\n \n bool bSwipeStartedNow = true;\n bSwipeStartedNow = bSwipeStartedNow && (bSwipeStarted == false);\n bSwipeStartedNow = bSwipeStartedNow && (pointsNew.size() > 0);\n if(bSwipeStartedNow == true) {\n bSwipeStartedNow = bSwipeStartedNow && (pointsNew[0].type == SwipePoint::TypeDown);\n }\n \n bool bUpdate = false;\n bUpdate = bUpdate || (bSwipeStarted == true);\n bUpdate = bUpdate || (bSwipeStartedNow == true);\n if(bUpdate == false) {\n return;\n }\n \n double timeElapsedSinceLastUpdateInSeconds = _optionalTimeElapsedSinceLastUpdateInSeconds;\n if(timeElapsedSinceLastUpdateInSeconds < 0.0) {\n timeElapsedSinceLastUpdateInSeconds = coc::getTimeElapsedSinceLastFrame();\n }\n \n if(bSwipeStartedNow == true) {\n swipeTime = 0;\n } else {\n swipeTime += timeElapsedSinceLastUpdateInSeconds;\n }\n \n if(pointsNew.size() == 0) {\n return;\n }\n \n \/\/----------------------------------------------------------\n bool bFound = false;\n SwipePoint pointNew;\n \n if(bSwipeStartedNow == true) {\n\n \/\/ look for touch down.\n\n for(int i=0; i<pointsNew.size(); i++) {\n if(pointsNew[i].type == SwipePoint::TypeDown) {\n pointNew = pointsNew[i];\n bFound = true;\n break;\n }\n }\n \n } else {\n \n \/\/ look for touch up first.\n \n for(int i=pointsNew.size()-1; i>=0; i--) {\n if(pointsNew[i].type == SwipePoint::TypeUp) {\n \n bool bSame = false;\n if(points.size() > 0) {\n const SwipePoint & pointLast = points[points.size()-1];\n bSame = true;\n bSame = bSame && ((int)pointsNew[i].position.x == (int)pointLast.position.x);\n bSame = bSame && ((int)pointsNew[i].position.y == (int)pointLast.position.y);\n }\n if(bSame == true) {\n \/\/ remove last move point and replace with up point.\n points.erase(points.begin() + points.size()-1);\n }\n \n pointNew = pointsNew[i];\n bFound = true;\n break;\n }\n }\n \n \/\/ look for touch moved first.\n \n if(bFound == false) {\n for(int i=pointsNew.size()-1; i>=0; i--) {\n if(pointsNew[i].type == SwipePoint::TypeMoved) {\n \n bool bSame = false;\n if(points.size() > 0) {\n const SwipePoint & pointLast = points[points.size()-1];\n bSame = true;\n bSame = bSame && ((int)pointsNew[i].position.x == (int)pointLast.position.x);\n bSame = bSame && ((int)pointsNew[i].position.y == (int)pointLast.position.y);\n }\n if(bSame == true) {\n continue;\n }\n \n pointNew = pointsNew[i];\n bFound = true;\n break;\n }\n }\n }\n }\n \n pointsNew.clear();\n \n if(bFound == false) {\n return;\n }\n \n points.push_back(pointNew);\n SwipePoint & point = points.back();\n point.time = swipeTime;\n \n if(points.size() > 1) {\n \n const SwipePoint & pointLast = points[points.size()-2];\n point.velocity = (point.position - pointLast.position) \/ (point.time - pointLast.time);\n point.velocityScale = length(point.velocity) \/ swipePixelVelocityThreshold;\n \n point.angleDeg = coc::angleClockwise(point.velocity);\n point.angleDeg = (point.angleDeg \/ (float)PI) * 180.0;\n }\n \n \/\/----------------------------------------------------------\n if(gestureStartIndex == -1) {\n gestureStartIndex = points.size() - 1;\n }\n \n SwipePoint gesturePointStart;\n SwipeDirection gestureDirectionStart;\n \n for(int i=gestureStartIndex; i<points.size(); i++) {\n if(i == gestureStartIndex) {\n gesturePointStart = points[i];\n gestureDirectionStart = getDirectionFromAngle(gesturePointStart.angleDeg);\n }\n \n const SwipePoint & gesturePoint = points[i];\n if(gesturePoint.velocityScale < 1.0) {\n gestureDirection = SwipeDirectionUndefined;\n gestureStartIndex = -1;\n break;\n }\n \n SwipeDirection gestureDirectionNew = getDirectionFromAngle(gesturePoint.angleDeg);\n if(gestureDirectionNew != gestureDirectionStart) {\n gestureDirection = SwipeDirectionUndefined;\n gestureStartIndex = -1;\n break;\n }\n \n float dist = distance(gesturePoint.position, gesturePointStart.position);\n if(dist >= swipePixelDistanceThreshold) {\n bGestureFoundNew = gestureDirection != gestureDirectionNew;\n gestureDirection = gestureDirectionNew;\n }\n }\n}\n\nvoid Swipe::reset() {\n \n points.clear();\n swipeTime = 0;\n \n gestureDirection = SwipeDirectionUndefined;\n gestureStartIndex = -1;\n}\n\n\/\/--------------------------------------------------------------\nvoid Swipe::pointDown(float x, float y) {\n pointNew(x, y, SwipePoint::TypeDown);\n}\n\nvoid Swipe::pointMoved(float x, float y) {\n pointNew(x, y, SwipePoint::TypeMoved);\n}\n\nvoid Swipe::pointUp(float x, float y) {\n pointNew(x, y, SwipePoint::TypeUp);\n}\n\nvoid Swipe::pointNew(float x, float y, SwipePoint::Type type) {\n pointsNew.push_back(SwipePoint());\n SwipePoint & point = pointsNew.back();\n point.position = vec2(x, y);\n point.type = type;\n}\n\n\/\/--------------------------------------------------------------\nbool Swipe::hasFoundSwipeGesture() const {\n return bGestureFoundNew;\n}\n\nSwipeDirection Swipe::getSwipeGestureDirection() const {\n return gestureDirection;\n}\n\nconst std::vector<SwipePoint> & Swipe::getPoints() const {\n return points;\n}\n\nfloat Swipe::getSwipeTime() const {\n return swipeTime;\n}\n\n\/\/--------------------------------------------------------------\nSwipeDirection Swipe::getDirectionFromAngle(float angleDeg) const {\n SwipeDirection dir;\n if((angleDeg > 315 && angleDeg <= 360) || (angleDeg >= 0 && angleDeg <= 45)) {\n dir = SwipeDirectionUp;\n } else if(angleDeg > 45 && angleDeg <= 135) {\n dir = SwipeDirectionRight;\n } else if(angleDeg > 135 && angleDeg <= 225) {\n dir = SwipeDirectionDown;\n } else if(angleDeg > 225 && angleDeg <= 315) {\n dir = SwipeDirectionLeft;\n }\n return dir;\n}\n\n}<commit_msg>PI fix<commit_after>\/\/\n\/\/ cocTimer.h\n\/\/ Created by Lukasz Karluk on 10\/10\/2015.\n\/\/ http:\/\/codeoncanvas.cc\n\/\/\n\n#include \"cocSwipe.h\"\n\nnamespace coc {\n\nusing namespace std;\nusing namespace glm;\n\n\/\/--------------------------------------------------------------\nSwipe::Swipe() {\n\n swipePixelDistanceThreshold = 50;\n swipePixelVelocityThreshold = 100;\n \n reset();\n}\n\nSwipe::~Swipe() {\n \/\/\n}\n\nvoid Swipe::setSwipeArea(const coc::Rect & rect) {\n swipeArea = rect;\n}\n\nvoid Swipe::setSwipeArea(float x, float y, float w, float h) {\n swipeArea.setX(x);\n swipeArea.setY(y);\n swipeArea.setW(w);\n swipeArea.setH(h);\n}\n\nvoid Swipe::setSwipePixelDistanceThreshold(float value) {\n swipePixelDistanceThreshold = value;\n}\n\nvoid Swipe::setSwipePixelVelocityThreshold(float value) {\n swipePixelVelocityThreshold = value;\n}\n\n\/\/--------------------------------------------------------------\nvoid Swipe::update(double _optionalTimeElapsedSinceLastUpdateInSeconds) {\n\n bGestureFoundNew = false; \/\/ clear on every new frame.\n\n \/\/----------------------------------------------------------\n bool bSwipeStopped = false;\n if(points.size() > 0) {\n const SwipePoint & pointLast = points[points.size()-1];\n bSwipeStopped = (pointLast.type == SwipePoint::TypeUp);\n if(bSwipeStopped == true) {\n bool bDownNew = false;\n for(int i=0; i<pointsNew.size(); i++) {\n const SwipePoint & pointNew = pointsNew[i];\n if(pointNew.type == SwipePoint::TypeDown) {\n bDownNew = true;\n break;\n }\n }\n if(bDownNew == true) {\n bSwipeStopped = false;\n reset();\n }\n }\n }\n \n if(bSwipeStopped == true) {\n return;\n }\n\n bool bSwipeStarted = true;\n bSwipeStarted = bSwipeStarted && (points.size() > 0);\n \n bool bSwipeStartedNow = true;\n bSwipeStartedNow = bSwipeStartedNow && (bSwipeStarted == false);\n bSwipeStartedNow = bSwipeStartedNow && (pointsNew.size() > 0);\n if(bSwipeStartedNow == true) {\n bSwipeStartedNow = bSwipeStartedNow && (pointsNew[0].type == SwipePoint::TypeDown);\n }\n \n bool bUpdate = false;\n bUpdate = bUpdate || (bSwipeStarted == true);\n bUpdate = bUpdate || (bSwipeStartedNow == true);\n if(bUpdate == false) {\n return;\n }\n \n double timeElapsedSinceLastUpdateInSeconds = _optionalTimeElapsedSinceLastUpdateInSeconds;\n if(timeElapsedSinceLastUpdateInSeconds < 0.0) {\n timeElapsedSinceLastUpdateInSeconds = coc::getTimeElapsedSinceLastFrame();\n }\n \n if(bSwipeStartedNow == true) {\n swipeTime = 0;\n } else {\n swipeTime += timeElapsedSinceLastUpdateInSeconds;\n }\n \n if(pointsNew.size() == 0) {\n return;\n }\n \n \/\/----------------------------------------------------------\n bool bFound = false;\n SwipePoint pointNew;\n \n if(bSwipeStartedNow == true) {\n\n \/\/ look for touch down.\n\n for(int i=0; i<pointsNew.size(); i++) {\n if(pointsNew[i].type == SwipePoint::TypeDown) {\n pointNew = pointsNew[i];\n bFound = true;\n break;\n }\n }\n \n } else {\n \n \/\/ look for touch up first.\n \n for(int i=pointsNew.size()-1; i>=0; i--) {\n if(pointsNew[i].type == SwipePoint::TypeUp) {\n \n bool bSame = false;\n if(points.size() > 0) {\n const SwipePoint & pointLast = points[points.size()-1];\n bSame = true;\n bSame = bSame && ((int)pointsNew[i].position.x == (int)pointLast.position.x);\n bSame = bSame && ((int)pointsNew[i].position.y == (int)pointLast.position.y);\n }\n if(bSame == true) {\n \/\/ remove last move point and replace with up point.\n points.erase(points.begin() + points.size()-1);\n }\n \n pointNew = pointsNew[i];\n bFound = true;\n break;\n }\n }\n \n \/\/ look for touch moved first.\n \n if(bFound == false) {\n for(int i=pointsNew.size()-1; i>=0; i--) {\n if(pointsNew[i].type == SwipePoint::TypeMoved) {\n \n bool bSame = false;\n if(points.size() > 0) {\n const SwipePoint & pointLast = points[points.size()-1];\n bSame = true;\n bSame = bSame && ((int)pointsNew[i].position.x == (int)pointLast.position.x);\n bSame = bSame && ((int)pointsNew[i].position.y == (int)pointLast.position.y);\n }\n if(bSame == true) {\n continue;\n }\n \n pointNew = pointsNew[i];\n bFound = true;\n break;\n }\n }\n }\n }\n \n pointsNew.clear();\n \n if(bFound == false) {\n return;\n }\n \n points.push_back(pointNew);\n SwipePoint & point = points.back();\n point.time = swipeTime;\n \n if(points.size() > 1) {\n \n const SwipePoint & pointLast = points[points.size()-2];\n point.velocity = (point.position - pointLast.position) \/ (point.time - pointLast.time);\n point.velocityScale = length(point.velocity) \/ swipePixelVelocityThreshold;\n \n point.angleDeg = coc::angleClockwise(point.velocity);\n point.angleDeg = (point.angleDeg \/ (float)M_PI) * 180.0;\n }\n \n \/\/----------------------------------------------------------\n if(gestureStartIndex == -1) {\n gestureStartIndex = points.size() - 1;\n }\n \n SwipePoint gesturePointStart;\n SwipeDirection gestureDirectionStart;\n \n for(int i=gestureStartIndex; i<points.size(); i++) {\n if(i == gestureStartIndex) {\n gesturePointStart = points[i];\n gestureDirectionStart = getDirectionFromAngle(gesturePointStart.angleDeg);\n }\n \n const SwipePoint & gesturePoint = points[i];\n if(gesturePoint.velocityScale < 1.0) {\n gestureDirection = SwipeDirectionUndefined;\n gestureStartIndex = -1;\n break;\n }\n \n SwipeDirection gestureDirectionNew = getDirectionFromAngle(gesturePoint.angleDeg);\n if(gestureDirectionNew != gestureDirectionStart) {\n gestureDirection = SwipeDirectionUndefined;\n gestureStartIndex = -1;\n break;\n }\n \n float dist = distance(gesturePoint.position, gesturePointStart.position);\n if(dist >= swipePixelDistanceThreshold) {\n bGestureFoundNew = gestureDirection != gestureDirectionNew;\n gestureDirection = gestureDirectionNew;\n }\n }\n}\n\nvoid Swipe::reset() {\n \n points.clear();\n swipeTime = 0;\n \n gestureDirection = SwipeDirectionUndefined;\n gestureStartIndex = -1;\n}\n\n\/\/--------------------------------------------------------------\nvoid Swipe::pointDown(float x, float y) {\n pointNew(x, y, SwipePoint::TypeDown);\n}\n\nvoid Swipe::pointMoved(float x, float y) {\n pointNew(x, y, SwipePoint::TypeMoved);\n}\n\nvoid Swipe::pointUp(float x, float y) {\n pointNew(x, y, SwipePoint::TypeUp);\n}\n\nvoid Swipe::pointNew(float x, float y, SwipePoint::Type type) {\n pointsNew.push_back(SwipePoint());\n SwipePoint & point = pointsNew.back();\n point.position = vec2(x, y);\n point.type = type;\n}\n\n\/\/--------------------------------------------------------------\nbool Swipe::hasFoundSwipeGesture() const {\n return bGestureFoundNew;\n}\n\nSwipeDirection Swipe::getSwipeGestureDirection() const {\n return gestureDirection;\n}\n\nconst std::vector<SwipePoint> & Swipe::getPoints() const {\n return points;\n}\n\nfloat Swipe::getSwipeTime() const {\n return swipeTime;\n}\n\n\/\/--------------------------------------------------------------\nSwipeDirection Swipe::getDirectionFromAngle(float angleDeg) const {\n SwipeDirection dir;\n if((angleDeg > 315 && angleDeg <= 360) || (angleDeg >= 0 && angleDeg <= 45)) {\n dir = SwipeDirectionUp;\n } else if(angleDeg > 45 && angleDeg <= 135) {\n dir = SwipeDirectionRight;\n } else if(angleDeg > 135 && angleDeg <= 225) {\n dir = SwipeDirectionDown;\n } else if(angleDeg > 225 && angleDeg <= 315) {\n dir = SwipeDirectionLeft;\n }\n return dir;\n}\n\n}<|endoftext|>"} {"text":"<commit_before><commit_msg>`yli::load::load_symbiosis`: edit `std::cerr` error output.<commit_after><|endoftext|>"} {"text":"<commit_before>#include <cmath>\n#include <cstdio>\n#include <fstream>\n#include <iostream>\n#include <sstream>\n#include <vector>\n#include \"TCanvas.h\"\n#include \"TFile.h\"\n#include \"TH2.h\"\n#include \"TStyle.h\"\n\nint main(int argc, char** argv) {\n \/\/ Set ROOT params\n gStyle->SetOptStat(0);\n gStyle->SetNumberContours(999);\n\n bool print_help = false;\n int return_code = 0;\n if(argc == 1) {\n print_help = true;\n return_code = 1;\n }\n\n \/\/ Read parameters\n std::string file_name;\n std::string output_file_name;\n std::string plane = \"yz\";\n int slice_index = 0;\n bool flag_cut = false;\n int slice_cut = 0;\n int xdiv = 100;\n int ydiv = 100;\n int zdiv = 100;\n for(int i = 1; i < argc; i++) {\n if(strcmp(argv[i], \"-h\") == 0) {\n print_help = true;\n } else if(strcmp(argv[i], \"-f\") == 0 && (i + 1 < argc)) {\n file_name = std::string(argv[++i]);\n } else if(strcmp(argv[i], \"-o\") == 0 && (i + 1 < argc)) {\n output_file_name = std::string(argv[++i]);\n } else if(strcmp(argv[i], \"-p\") == 0 && (i + 1 < argc)) {\n plane = std::string(argv[++i]);\n } else if(strcmp(argv[i], \"-c\") == 0 && (i + 1 < argc)) {\n slice_cut = std::atoi(argv[++i]);\n flag_cut = true;\n } else if(strcmp(argv[i], \"-x\") == 0 && (i + 1 < argc)) {\n xdiv = std::atoi(argv[++i]);\n } else if(strcmp(argv[i], \"-y\") == 0 && (i + 1 < argc)) {\n ydiv = std::atoi(argv[++i]);\n } else if(strcmp(argv[i], \"-z\") == 0 && (i + 1 < argc)) {\n zdiv = std::atoi(argv[++i]);\n } else {\n std::cout << \"Unrecognized command line argument or missing value\\\"\" << argv[i] << std::endl;\n print_help = true;\n return_code = 1;\n }\n }\n\n if(file_name.empty()) {\n print_help = true;\n return_code = 1;\n }\n\n if(print_help) {\n std::cerr << \"Usage: .\/tcad_dfise_reader -f <file_name> [<options>]\" << std::endl;\n std::cout << \"\\t -f <file_name> init file name\" << std::endl;\n std::cout << \"\\t -o <output_file_name> name of the file to output (default is efield.png)\" << std::endl;\n std::cout << \"\\t -p <plane> plane to be ploted. xy, yz or zx (default is yz)\" << std::endl;\n std::cout << \"\\t -c <cut> projection height index (default is mesh_pitch \/ 2)\" << std::endl;\n std::cout << \"\\t -x <mesh x_pitch> plot regular mesh X binning (default is 100)\" << std::endl;\n std::cout << \"\\t -y <mesh_y_pitch> plot regular mesh Y binning (default is 100)\" << std::endl;\n std::cout << \"\\t -z <mesh_z_pitch> plot regular mesh Z binning (default is 100)\" << std::endl;\n return return_code;\n }\n\n \/\/ Read file\n std::cout << \"Reading file: \" << file_name;\n\n size_t firstindex = file_name.find_last_of(\"_\");\n size_t lastindex = file_name.find(\".\");\n output_file_name = file_name.substr(0, lastindex);\n output_file_name += \".png\";\n\n std::string observable = file_name.substr(firstindex + 1, lastindex - (firstindex + 1));\n\n std::ifstream input_file;\n input_file.open(file_name);\n if(input_file.is_open() != false) {\n std::cout << \" OK\" << std::endl;\n } else {\n std::cout << \" FAILED\" << std::endl;\n return 1;\n }\n\n \/\/ Find plotting indices\n int x_bin = 0;\n int y_bin = 0;\n int x_bin_index = 0;\n int y_bin_index = 0;\n if(strcmp(plane.c_str(), \"xy\") == 0) {\n x_bin = xdiv;\n y_bin = ydiv;\n if(!flag_cut) {\n slice_cut = zdiv \/ 2;\n }\n x_bin_index = 0;\n y_bin_index = 1;\n slice_index = 2;\n }\n if(strcmp(plane.c_str(), \"yz\") == 0) {\n x_bin = ydiv;\n y_bin = zdiv;\n if(!flag_cut) {\n slice_cut = xdiv \/ 2;\n }\n x_bin_index = 1;\n y_bin_index = 2;\n slice_index = 0;\n }\n if(strcmp(plane.c_str(), \"zx\") == 0) {\n x_bin = zdiv;\n y_bin = xdiv;\n if(!flag_cut) {\n slice_cut = ydiv \/ 2;\n }\n x_bin_index = 2;\n y_bin_index = 0;\n slice_index = 1;\n }\n\n \/\/ Create and fill histogram\n auto efield_map =\n new TH2D(Form(\"%s\", observable.c_str()), Form(\"%s\", observable.c_str()), x_bin, 0, x_bin, y_bin, 0, y_bin);\n auto exfield_map = new TH2D(Form(\"%s X component\", observable.c_str()),\n Form(\"%s X component\", observable.c_str()),\n x_bin,\n 0,\n x_bin,\n y_bin,\n 0,\n y_bin);\n auto eyfield_map = new TH2D(Form(\"%s Y component\", observable.c_str()),\n Form(\"%s Y component\", observable.c_str()),\n x_bin,\n 0,\n x_bin,\n y_bin,\n 0,\n y_bin);\n auto ezfield_map = new TH2D(Form(\"%s Z component\", observable.c_str()),\n Form(\"%s Z component\", observable.c_str()),\n x_bin,\n 0,\n x_bin,\n y_bin,\n 0,\n y_bin);\n auto c1 = new TCanvas();\n\n double dummy;\n double vector[6];\n int line = 1;\n std::string file_line;\n while(getline(input_file, file_line)) {\n int p = 0;\n if(line < 7) {\n line++;\n continue;\n }\n std::stringstream mystream(file_line);\n while(mystream >> dummy) {\n vector[p] = dummy;\n p++;\n }\n if(vector[slice_index] == slice_cut) {\n efield_map->Fill(\n vector[x_bin_index], vector[y_bin_index], sqrt(pow(vector[3], 2) + pow(vector[4], 2) + pow(vector[5], 2)));\n exfield_map->Fill(vector[x_bin_index], vector[y_bin_index], vector[3]);\n eyfield_map->Fill(vector[x_bin_index], vector[y_bin_index], vector[4]);\n ezfield_map->Fill(vector[x_bin_index], vector[y_bin_index], vector[5]);\n }\n line++;\n }\n std::string root_file_name = file_name.substr(0, lastindex);\n root_file_name += \"_Interpolation_plots.root\";\n auto* tf = new TFile(root_file_name.c_str(), \"RECREATE\");\n exfield_map->Write(Form(\"%s X component\", observable.c_str()));\n eyfield_map->Write(Form(\"%s Y component\", observable.c_str()));\n ezfield_map->Write(Form(\"%s Z component\", observable.c_str()));\n efield_map->Write(Form(\"%s Norm\", observable.c_str()));\n c1->cd();\n efield_map->Draw(\"colz\");\n c1->SaveAs(output_file_name.c_str());\n tf->Close();\n return 0;\n}\n<commit_msg>small CI fix<commit_after>#include <cmath>\n#include <cstdio>\n#include <fstream>\n#include <iostream>\n#include <sstream>\n#include <vector>\n#include \"TCanvas.h\"\n#include \"TFile.h\"\n#include \"TH2.h\"\n#include \"TStyle.h\"\n\nint main(int argc, char** argv) {\n \/\/ Set ROOT params\n gStyle->SetOptStat(0);\n gStyle->SetNumberContours(999);\n\n bool print_help = false;\n int return_code = 0;\n if(argc == 1) {\n print_help = true;\n return_code = 1;\n }\n\n \/\/ Read parameters\n std::string file_name;\n std::string output_file_name;\n std::string plane = \"yz\";\n int slice_index = 0;\n bool flag_cut = false;\n int slice_cut = 0;\n int xdiv = 100;\n int ydiv = 100;\n int zdiv = 100;\n for(int i = 1; i < argc; i++) {\n if(strcmp(argv[i], \"-h\") == 0) {\n print_help = true;\n } else if(strcmp(argv[i], \"-f\") == 0 && (i + 1 < argc)) {\n file_name = std::string(argv[++i]);\n } else if(strcmp(argv[i], \"-o\") == 0 && (i + 1 < argc)) {\n output_file_name = std::string(argv[++i]);\n } else if(strcmp(argv[i], \"-p\") == 0 && (i + 1 < argc)) {\n plane = std::string(argv[++i]);\n } else if(strcmp(argv[i], \"-c\") == 0 && (i + 1 < argc)) {\n slice_cut = std::atoi(argv[++i]);\n flag_cut = true;\n } else if(strcmp(argv[i], \"-x\") == 0 && (i + 1 < argc)) {\n xdiv = std::atoi(argv[++i]);\n } else if(strcmp(argv[i], \"-y\") == 0 && (i + 1 < argc)) {\n ydiv = std::atoi(argv[++i]);\n } else if(strcmp(argv[i], \"-z\") == 0 && (i + 1 < argc)) {\n zdiv = std::atoi(argv[++i]);\n } else {\n std::cout << \"Unrecognized command line argument or missing value\\\"\" << argv[i] << std::endl;\n print_help = true;\n return_code = 1;\n }\n }\n\n if(file_name.empty()) {\n print_help = true;\n return_code = 1;\n }\n\n if(print_help) {\n std::cerr << \"Usage: .\/tcad_dfise_reader -f <file_name> [<options>]\" << std::endl;\n std::cout << \"\\t -f <file_name> init file name\" << std::endl;\n std::cout << \"\\t -o <output_file_name> name of the file to output (default is efield.png)\" << std::endl;\n std::cout << \"\\t -p <plane> plane to be ploted. xy, yz or zx (default is yz)\" << std::endl;\n std::cout << \"\\t -c <cut> projection height index (default is mesh_pitch \/ 2)\" << std::endl;\n std::cout << \"\\t -x <mesh x_pitch> plot regular mesh X binning (default is 100)\" << std::endl;\n std::cout << \"\\t -y <mesh_y_pitch> plot regular mesh Y binning (default is 100)\" << std::endl;\n std::cout << \"\\t -z <mesh_z_pitch> plot regular mesh Z binning (default is 100)\" << std::endl;\n return return_code;\n }\n\n \/\/ Read file\n std::cout << \"Reading file: \" << file_name;\n\n size_t firstindex = file_name.find_last_of('_');\n size_t lastindex = file_name.find('.');\n output_file_name = file_name.substr(0, lastindex);\n output_file_name += \".png\";\n\n std::string observable = file_name.substr(firstindex + 1, lastindex - (firstindex + 1));\n\n std::ifstream input_file;\n input_file.open(file_name);\n if(input_file.is_open() != false) {\n std::cout << \" OK\" << std::endl;\n } else {\n std::cout << \" FAILED\" << std::endl;\n return 1;\n }\n\n \/\/ Find plotting indices\n int x_bin = 0;\n int y_bin = 0;\n int x_bin_index = 0;\n int y_bin_index = 0;\n if(strcmp(plane.c_str(), \"xy\") == 0) {\n x_bin = xdiv;\n y_bin = ydiv;\n if(!flag_cut) {\n slice_cut = zdiv \/ 2;\n }\n x_bin_index = 0;\n y_bin_index = 1;\n slice_index = 2;\n }\n if(strcmp(plane.c_str(), \"yz\") == 0) {\n x_bin = ydiv;\n y_bin = zdiv;\n if(!flag_cut) {\n slice_cut = xdiv \/ 2;\n }\n x_bin_index = 1;\n y_bin_index = 2;\n slice_index = 0;\n }\n if(strcmp(plane.c_str(), \"zx\") == 0) {\n x_bin = zdiv;\n y_bin = xdiv;\n if(!flag_cut) {\n slice_cut = ydiv \/ 2;\n }\n x_bin_index = 2;\n y_bin_index = 0;\n slice_index = 1;\n }\n\n \/\/ Create and fill histogram\n auto efield_map =\n new TH2D(Form(\"%s\", observable.c_str()), Form(\"%s\", observable.c_str()), x_bin, 0, x_bin, y_bin, 0, y_bin);\n auto exfield_map = new TH2D(Form(\"%s X component\", observable.c_str()),\n Form(\"%s X component\", observable.c_str()),\n x_bin,\n 0,\n x_bin,\n y_bin,\n 0,\n y_bin);\n auto eyfield_map = new TH2D(Form(\"%s Y component\", observable.c_str()),\n Form(\"%s Y component\", observable.c_str()),\n x_bin,\n 0,\n x_bin,\n y_bin,\n 0,\n y_bin);\n auto ezfield_map = new TH2D(Form(\"%s Z component\", observable.c_str()),\n Form(\"%s Z component\", observable.c_str()),\n x_bin,\n 0,\n x_bin,\n y_bin,\n 0,\n y_bin);\n auto c1 = new TCanvas();\n\n double dummy;\n double vector[6];\n int line = 1;\n std::string file_line;\n while(getline(input_file, file_line)) {\n int p = 0;\n if(line < 7) {\n line++;\n continue;\n }\n std::stringstream mystream(file_line);\n while(mystream >> dummy) {\n vector[p] = dummy;\n p++;\n }\n if(vector[slice_index] == slice_cut) {\n efield_map->Fill(\n vector[x_bin_index], vector[y_bin_index], sqrt(pow(vector[3], 2) + pow(vector[4], 2) + pow(vector[5], 2)));\n exfield_map->Fill(vector[x_bin_index], vector[y_bin_index], vector[3]);\n eyfield_map->Fill(vector[x_bin_index], vector[y_bin_index], vector[4]);\n ezfield_map->Fill(vector[x_bin_index], vector[y_bin_index], vector[5]);\n }\n line++;\n }\n std::string root_file_name = file_name.substr(0, lastindex);\n root_file_name += \"_Interpolation_plots.root\";\n auto* tf = new TFile(root_file_name.c_str(), \"RECREATE\");\n exfield_map->Write(Form(\"%s X component\", observable.c_str()));\n eyfield_map->Write(Form(\"%s Y component\", observable.c_str()));\n ezfield_map->Write(Form(\"%s Z component\", observable.c_str()));\n efield_map->Write(Form(\"%s Norm\", observable.c_str()));\n c1->cd();\n efield_map->Draw(\"colz\");\n c1->SaveAs(output_file_name.c_str());\n tf->Close();\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: bibmod.cxx,v $\n *\n * $Revision: 1.10 $\n *\n * last change: $Author: rt $ $Date: 2007-04-26 08:05:22 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_extensions.hxx\"\n\n\n#include <tools\/resmgr.hxx>\n#ifndef _URLOBJ_HXX\n#include <tools\/urlobj.hxx>\n#endif\n#ifndef SVTOOLS_URIHELPER_HXX\n#include <svtools\/urihelper.hxx>\n#endif\n\n#ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_\n#include <com\/sun\/star\/container\/XNameAccess.hpp>\n#endif\n#ifndef _COM_SUN_STAR_UTIL_XLOCALIZEDALIASES_HPP_\n#include <com\/sun\/star\/util\/XLocalizedAliases.hpp>\n#endif\n#ifndef _COM_SUN_STAR_LANG_XLOCALIZABLE_HPP_\n#include <com\/sun\/star\/lang\/XLocalizable.hpp>\n#endif\n\n#ifndef _TOOLS_DEBUG_HXX\n#include <tools\/debug.hxx>\n#endif\n\n#include \"bibmod.hxx\"\n#include \"bibresid.hxx\"\n#include \"datman.hxx\"\n#include \"bibconfig.hxx\"\nstatic PtrBibModul pBibModul=NULL;\nstatic sal_uInt32 nBibModulCount=0;\n\n#ifndef _UCBHELPER_CONTENT_HXX\n#include <ucbhelper\/content.hxx>\n#endif\n\nusing namespace ::rtl;\nusing namespace ::com::sun::star;\nusing namespace ::com::sun::star::uno;\nusing namespace ::com::sun::star::util;\nusing namespace ::com::sun::star::lang;\nusing namespace ::com::sun::star::ucb;\n\n#define C2U(cChar) OUString::createFromAscii(cChar)\n#define C2S(cChar) String::CreateFromAscii(cChar)\n\nHdlBibModul OpenBibModul()\n{\n if(pBibModul==NULL)\n {\n pBibModul=new BibModul();\n }\n nBibModulCount++;\n return &pBibModul;\n}\n\nvoid CloseBibModul(HdlBibModul ppBibModul)\n{\n nBibModulCount--;\n if(nBibModulCount==0 && ppBibModul!=NULL)\n {\n delete pBibModul;\n pBibModul=NULL;\n }\n}\n\nBibResId::BibResId( sal_uInt16 nId ) :\n ResId( nId, *pBibModul->GetResMgr() )\n{\n}\nBibConfig* BibModul::pBibConfig = 0;\nBibModul::BibModul()\n{\n pResMgr = ResMgr::CreateResMgr( \"bib\" MAKE_NUMSTR(SUPD) );\n}\n\nBibModul::~BibModul()\n{\n delete pResMgr;\n delete pBibConfig;\n pBibConfig = 0;\n}\n\nBibDataManager* BibModul::createDataManager()\n{\n return new BibDataManager();\n}\n\/\/-----------------------------------------------------------------------------\nBibConfig* BibModul::GetConfig()\n{\n if(! pBibConfig)\n pBibConfig = new BibConfig;\n return pBibConfig;\n}\n\n\n\/\/ PropertyNames\n#define STATIC_USTRING(a,b) rtl::OUString a(b)\nSTATIC_USTRING(FM_PROP_LABEL,C2U(\"Label\"));\nSTATIC_USTRING(FM_PROP_CONTROLSOURCE,C2U(\"DataField\"));\nSTATIC_USTRING(FM_PROP_NAME,C2U(\"Name\"));\nSTATIC_USTRING(FM_PROP_FORMATKEY,C2U(\"FormatKey\"));\n#ifdef TF_SDBAPI\n#else \/\/ !TF_SDBAPI\nSTATIC_USTRING(FM_PROP_EDITMODE,C2U(\"RecordMode\"));\nSTATIC_USTRING(FM_PROP_CURSORSOURCETYPE,C2U(\"DataSelectionType\"));\nSTATIC_USTRING(FM_PROP_CURSORSOURCE,C2U(\"DataSelection\"));\nSTATIC_USTRING(FM_PROP_DATASOURCE, C2U(\"DataSource\"));\n#endif \/\/ !TF_SDBAPI\nSTATIC_USTRING(FM_PROP_VALUE,C2U(\"Value\"));\nSTATIC_USTRING(FM_PROP_TEXT,C2U(\"Text\"));\n<commit_msg>INTEGRATION: CWS supdremove02 (1.10.142); FILE MERGED 2008\/01\/31 13:46:32 rt 1.10.142.1: #i85482# Remove UPD from resource name.<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: bibmod.cxx,v $\n *\n * $Revision: 1.11 $\n *\n * last change: $Author: obo $ $Date: 2008-02-25 15:32:21 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_extensions.hxx\"\n\n\n#include <tools\/resmgr.hxx>\n#ifndef _URLOBJ_HXX\n#include <tools\/urlobj.hxx>\n#endif\n#ifndef SVTOOLS_URIHELPER_HXX\n#include <svtools\/urihelper.hxx>\n#endif\n\n#ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_\n#include <com\/sun\/star\/container\/XNameAccess.hpp>\n#endif\n#ifndef _COM_SUN_STAR_UTIL_XLOCALIZEDALIASES_HPP_\n#include <com\/sun\/star\/util\/XLocalizedAliases.hpp>\n#endif\n#ifndef _COM_SUN_STAR_LANG_XLOCALIZABLE_HPP_\n#include <com\/sun\/star\/lang\/XLocalizable.hpp>\n#endif\n\n#ifndef _TOOLS_DEBUG_HXX\n#include <tools\/debug.hxx>\n#endif\n\n#include \"bibmod.hxx\"\n#include \"bibresid.hxx\"\n#include \"datman.hxx\"\n#include \"bibconfig.hxx\"\nstatic PtrBibModul pBibModul=NULL;\nstatic sal_uInt32 nBibModulCount=0;\n\n#ifndef _UCBHELPER_CONTENT_HXX\n#include <ucbhelper\/content.hxx>\n#endif\n\nusing namespace ::rtl;\nusing namespace ::com::sun::star;\nusing namespace ::com::sun::star::uno;\nusing namespace ::com::sun::star::util;\nusing namespace ::com::sun::star::lang;\nusing namespace ::com::sun::star::ucb;\n\n#define C2U(cChar) OUString::createFromAscii(cChar)\n#define C2S(cChar) String::CreateFromAscii(cChar)\n\nHdlBibModul OpenBibModul()\n{\n if(pBibModul==NULL)\n {\n pBibModul=new BibModul();\n }\n nBibModulCount++;\n return &pBibModul;\n}\n\nvoid CloseBibModul(HdlBibModul ppBibModul)\n{\n nBibModulCount--;\n if(nBibModulCount==0 && ppBibModul!=NULL)\n {\n delete pBibModul;\n pBibModul=NULL;\n }\n}\n\nBibResId::BibResId( sal_uInt16 nId ) :\n ResId( nId, *pBibModul->GetResMgr() )\n{\n}\nBibConfig* BibModul::pBibConfig = 0;\nBibModul::BibModul()\n{\n pResMgr = ResMgr::CreateResMgr( \"bib\" );\n}\n\nBibModul::~BibModul()\n{\n delete pResMgr;\n delete pBibConfig;\n pBibConfig = 0;\n}\n\nBibDataManager* BibModul::createDataManager()\n{\n return new BibDataManager();\n}\n\/\/-----------------------------------------------------------------------------\nBibConfig* BibModul::GetConfig()\n{\n if(! pBibConfig)\n pBibConfig = new BibConfig;\n return pBibConfig;\n}\n\n\n\/\/ PropertyNames\n#define STATIC_USTRING(a,b) rtl::OUString a(b)\nSTATIC_USTRING(FM_PROP_LABEL,C2U(\"Label\"));\nSTATIC_USTRING(FM_PROP_CONTROLSOURCE,C2U(\"DataField\"));\nSTATIC_USTRING(FM_PROP_NAME,C2U(\"Name\"));\nSTATIC_USTRING(FM_PROP_FORMATKEY,C2U(\"FormatKey\"));\n#ifdef TF_SDBAPI\n#else \/\/ !TF_SDBAPI\nSTATIC_USTRING(FM_PROP_EDITMODE,C2U(\"RecordMode\"));\nSTATIC_USTRING(FM_PROP_CURSORSOURCETYPE,C2U(\"DataSelectionType\"));\nSTATIC_USTRING(FM_PROP_CURSORSOURCE,C2U(\"DataSelection\"));\nSTATIC_USTRING(FM_PROP_DATASOURCE, C2U(\"DataSource\"));\n#endif \/\/ !TF_SDBAPI\nSTATIC_USTRING(FM_PROP_VALUE,C2U(\"Value\"));\nSTATIC_USTRING(FM_PROP_TEXT,C2U(\"Text\"));\n<|endoftext|>"} {"text":"<commit_before><commit_msg>Treat \"Ascender Sans\" and \"Ascender Serif\" as equivalent to \"Arial\" and \"Times New Roman\" as Liberation Sans\/Serif are.<commit_after><|endoftext|>"} {"text":"<commit_before>#include \"codecmanager.h\"\n#include \"ui_codecmanager.h\"\n\nCodecManager::CodecManager(QWidget *parent, QString encoder)\n : QWidget(parent), ui(new Ui::CodecManager),\n streamingParameters(new QMap<QString, QString>), layoutCounter(0) {\n ui->setupUi(this);\n\n streamingParameters->insert(\"c:v\", encoder);\n addParameter(\"FPS\", \"r\", \"\");\n addParameter(\"Bitrate\", \"b:v\", \"\");\n addParameter(\"Minrate\", \"minrate\", \"\");\n addParameter(\"Maxrate\", \"maxrate\", \"\");\n addParameter(\"Buffer size\", \"bufsize\", \"\");\n addParameter(\"Aspect ratio\", \"aspect\", \"\");\n addParameter(\"Qscale\", \"qscale:v\", \"\");\n addParameter(\"Costant Rate Factor\", \"crf\", \"\");\n}\n\nCodecManager::~CodecManager() { delete ui; }\n\nQMap<QString, QString> *CodecManager::getStreamingParameters() {\n QMap<QString, QString> *parameters(streamingParameters);\n \/\/ Add final parameters\n parameters->insert(\"f\", \"matroska\");\n parameters->insert(\"an\", \"\");\n return parameters;\n}\n\nvoid CodecManager::addParameter(QString label, QString parameter,\n QString value) {\n \/\/ Create a new layout for the parameter\n QVBoxLayout *layout = new QVBoxLayout(this);\n\n \/\/ Add a QLabel\n QLabel *labelWidget = new QLabel(label, this);\n layout->addWidget(labelWidget);\n\n \/\/ Add a QLineEdit\n QLineEdit *lineEdit = new QLineEdit(value, this);\n layout->addWidget(lineEdit);\n\n \/\/ Make the form interactive\n streamingParameters->insert(parameter, value);\n connect(lineEdit, &QLineEdit::editingFinished, [=] {\n QString newValue = lineEdit->text();\n if (newValue != streamingParameters->value(parameter)) {\n streamingParameters->insert(parameter, newValue);\n emit parametersChanged();\n }\n });\n\n insertParameter(layout);\n}\n\nvoid CodecManager::addParameter(QString label, QString parameter,\n QList<QString> values) {\n \/\/ Create a new layout for the parameter\n QVBoxLayout *layout = new QVBoxLayout(this);\n\n \/\/ Add a QLabel\n QLabel *labelWidget = new QLabel(label, this);\n layout->addWidget(labelWidget);\n\n \/\/ Add a QComboBox\n QComboBox *comboBox = new QComboBox(this);\n comboBox->insertItems(0, values);\n layout->addWidget(comboBox);\n\n \/\/ Make the form interactive\n streamingParameters->insert(parameter, values[0]);\n connect(comboBox, &QComboBox::currentTextChanged,\n [=](const QString &newValue) {\n if (newValue != streamingParameters->value(parameter)) {\n streamingParameters->insert(parameter, newValue);\n emit parametersChanged();\n }\n });\n\n insertParameter(layout);\n}\n\nvoid CodecManager::insertParameter(QLayout *layout) {\n \/\/ Calculate position\n int row = layoutCounter \/ 7;\n int column = layoutCounter % 7;\n\n \/\/ Insert the layout\n ui->mainLayout->addLayout(layout, row, column);\n layoutCounter++;\n}\n<commit_msg>Do not add parent objects to layout elements (that was a bug)<commit_after>#include \"codecmanager.h\"\n#include \"ui_codecmanager.h\"\n\nCodecManager::CodecManager(QWidget *parent, QString encoder)\n : QWidget(parent), ui(new Ui::CodecManager),\n streamingParameters(new QMap<QString, QString>), layoutCounter(0) {\n ui->setupUi(this);\n\n streamingParameters->insert(\"c:v\", encoder);\n addParameter(\"FPS\", \"r\", \"\");\n addParameter(\"Bitrate\", \"b:v\", \"\");\n addParameter(\"Minrate\", \"minrate\", \"\");\n addParameter(\"Maxrate\", \"maxrate\", \"\");\n addParameter(\"Buffer size\", \"bufsize\", \"\");\n addParameter(\"Aspect ratio\", \"aspect\", \"\");\n addParameter(\"Qscale\", \"qscale:v\", \"\");\n addParameter(\"Costant Rate Factor\", \"crf\", \"\");\n}\n\nCodecManager::~CodecManager() { delete ui; }\n\nQMap<QString, QString> *CodecManager::getStreamingParameters() {\n QMap<QString, QString> *parameters(streamingParameters);\n \/\/ Add final parameters\n parameters->insert(\"f\", \"matroska\");\n parameters->insert(\"an\", \"\");\n return parameters;\n}\n\nvoid CodecManager::addParameter(QString label, QString parameter,\n QString value) {\n \/\/ Create a new layout for the parameter\n QVBoxLayout *layout = new QVBoxLayout();\n\n \/\/ Add a QLabel\n QLabel *labelWidget = new QLabel(label, this);\n layout->addWidget(labelWidget);\n\n \/\/ Add a QLineEdit\n QLineEdit *lineEdit = new QLineEdit(value, this);\n layout->addWidget(lineEdit);\n\n \/\/ Make the form interactive\n streamingParameters->insert(parameter, value);\n connect(lineEdit, &QLineEdit::editingFinished, [=] {\n QString newValue = lineEdit->text();\n if (newValue != streamingParameters->value(parameter)) {\n streamingParameters->insert(parameter, newValue);\n emit parametersChanged();\n }\n });\n\n insertParameter(layout);\n}\n\nvoid CodecManager::addParameter(QString label, QString parameter,\n QList<QString> values) {\n \/\/ Create a new layout for the parameter\n QVBoxLayout *layout = new QVBoxLayout();\n\n \/\/ Add a QLabel\n QLabel *labelWidget = new QLabel(label, this);\n layout->addWidget(labelWidget);\n\n \/\/ Add a QComboBox\n QComboBox *comboBox = new QComboBox(this);\n comboBox->insertItems(0, values);\n layout->addWidget(comboBox);\n\n \/\/ Make the form interactive\n streamingParameters->insert(parameter, values[0]);\n connect(comboBox, &QComboBox::currentTextChanged,\n [=](const QString &newValue) {\n if (newValue != streamingParameters->value(parameter)) {\n streamingParameters->insert(parameter, newValue);\n emit parametersChanged();\n }\n });\n\n insertParameter(layout);\n}\n\nvoid CodecManager::insertParameter(QLayout *layout) {\n \/\/ Calculate position\n int row = layoutCounter \/ 7;\n int column = layoutCounter % 7;\n\n \/\/ Insert the layout\n ui->mainLayout->addLayout(layout, row, column);\n layoutCounter++;\n}\n<|endoftext|>"} {"text":"<commit_before>\n\/*\n * Copyright 2011 Google Inc.\n *\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n *\/\n#include \"SkBenchmark.h\"\n#include \"SkCanvas.h\"\n#include \"SkFontHost.h\"\n#include \"SkPaint.h\"\n#include \"SkRandom.h\"\n#include \"SkSfntUtils.h\"\n#include \"SkString.h\"\n#include \"SkTemplates.h\"\n\n\/* Some considerations for performance:\n short -vs- long strings (measuring overhead)\n tiny -vs- large pointsize (measure blit -vs- overhead)\n 1 -vs- many point sizes (measure cache lookup)\n normal -vs- subpixel -vs- lineartext (minor)\n force purge after each draw to measure scaler\n textencoding?\n text -vs- postext - pathtext\n *\/\nclass TextBench : public SkBenchmark {\n SkPaint fPaint;\n int fCount;\n SkPoint* fPos;\n SkString fText;\n SkString fName;\n enum { N = 600 };\npublic:\n TextBench(void* param, const char text[], int ps, bool linearText,\n bool posText, SkColor color = SK_ColorBLACK) : INHERITED(param) {\n fText.set(text);\n\n fPaint.setAntiAlias(true);\n fPaint.setTextSize(SkIntToScalar(ps));\n fPaint.setLinearText(linearText);\n fPaint.setColor(color);\n\n if (posText) {\n SkAutoTArray<SkScalar> storage(fText.size());\n SkScalar* widths = storage.get();\n fCount = fPaint.getTextWidths(fText.c_str(), fText.size(), widths);\n fPos = new SkPoint[fCount];\n SkScalar x = 0;\n for (int i = 0; i < fCount; i++) {\n fPos[i].set(x, 0);\n x += widths[i];\n }\n } else {\n fCount = 0;\n fPos = NULL;\n }\n }\n\n virtual ~TextBench() {\n delete[] fPos;\n }\n\nprotected:\n virtual const char* onGetName() {\n fName.printf(\"text_%g\", SkScalarToFloat(fPaint.getTextSize()));\n if (fPaint.isLinearText()) {\n fName.append(\"_linear\");\n }\n if (fPos) {\n fName.append(\"_pos\");\n }\n\n if (SK_ColorBLACK != fPaint.getColor()) {\n fName.appendf(\"_%02X\", fPaint.getAlpha());\n }\n return fName.c_str();\n }\n\n virtual void onDraw(SkCanvas* canvas) {\n const SkIPoint dim = this->getSize();\n SkRandom rand;\n\n SkPaint paint(fPaint);\n this->setupPaint(&paint);\n paint.setColor(fPaint.getColor()); \/\/ need our specified color\n\n const SkScalar x0 = SkIntToScalar(-10);\n const SkScalar y0 = SkIntToScalar(-10);\n\n for (int i = 0; i < N; i++) {\n SkScalar x = x0 + rand.nextUScalar1() * dim.fX;\n SkScalar y = y0 + rand.nextUScalar1() * dim.fY;\n if (fPos) {\n canvas->save(SkCanvas::kMatrix_SaveFlag);\n canvas->translate(x, y);\n canvas->drawPosText(fText.c_str(), fText.size(), fPos, paint);\n canvas->restore();\n } else {\n canvas->drawText(fText.c_str(), fText.size(), x, y, paint);\n }\n }\n }\n\nprivate:\n typedef SkBenchmark INHERITED;\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#define STR \"Hamburgefons\"\n#define SMALL 9\n#define BIG 48\n\nstatic SkBenchmark* Fact0(void* p) { return new TextBench(p, STR, SMALL, false, false); }\nstatic SkBenchmark* Fact01(void* p) { return new TextBench(p, STR, SMALL, false, false, 0xFFFF0000); }\nstatic SkBenchmark* Fact02(void* p) { return new TextBench(p, STR, SMALL, false, false, 0x88FF0000); }\n\nstatic SkBenchmark* Fact1(void* p) { return new TextBench(p, STR, SMALL, false, true); }\nstatic SkBenchmark* Fact2(void* p) { return new TextBench(p, STR, SMALL, true, false); }\nstatic SkBenchmark* Fact3(void* p) { return new TextBench(p, STR, SMALL, true, true); }\n\nstatic SkBenchmark* Fact4(void* p) { return new TextBench(p, STR, BIG, false, false); }\nstatic SkBenchmark* Fact41(void* p) { return new TextBench(p, STR, BIG, false, false, 0xFFFF0000); }\nstatic SkBenchmark* Fact42(void* p) { return new TextBench(p, STR, BIG, false, false, 0x88FF0000); }\n\nstatic SkBenchmark* Fact5(void* p) { return new TextBench(p, STR, BIG, false, true); }\nstatic SkBenchmark* Fact6(void* p) { return new TextBench(p, STR, BIG, true, false); }\nstatic SkBenchmark* Fact7(void* p) { return new TextBench(p, STR, BIG, true, true); }\n\nstatic BenchRegistry gReg0(Fact0);\nstatic BenchRegistry gReg01(Fact01);\nstatic BenchRegistry gReg02(Fact02);\nstatic BenchRegistry gReg1(Fact1);\nstatic BenchRegistry gReg2(Fact2);\nstatic BenchRegistry gReg3(Fact3);\nstatic BenchRegistry gReg4(Fact4);\nstatic BenchRegistry gReg41(Fact41);\nstatic BenchRegistry gReg42(Fact42);\nstatic BenchRegistry gReg5(Fact5);\nstatic BenchRegistry gReg6(Fact6);\nstatic BenchRegistry gReg7(Fact7);\n\n<commit_msg>change text bench to measure text blit speed<commit_after>\n\/*\n * Copyright 2011 Google Inc.\n *\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n *\/\n#include \"SkBenchmark.h\"\n#include \"SkCanvas.h\"\n#include \"SkFontHost.h\"\n#include \"SkPaint.h\"\n#include \"SkRandom.h\"\n#include \"SkSfntUtils.h\"\n#include \"SkString.h\"\n#include \"SkTemplates.h\"\n\nenum FontQuality {\n kBW,\n kAA,\n kLCD\n};\n\nstatic const char* fontQualityName(const SkPaint& paint) {\n if (!paint.isAntiAlias()) {\n return \"BW\";\n }\n if (paint.isLCDRenderText()) {\n return \"LCD\";\n }\n return \"AA\";\n}\n\n\/* Some considerations for performance:\n short -vs- long strings (measuring overhead)\n tiny -vs- large pointsize (measure blit -vs- overhead)\n 1 -vs- many point sizes (measure cache lookup)\n normal -vs- subpixel -vs- lineartext (minor)\n force purge after each draw to measure scaler\n textencoding?\n text -vs- postext - pathtext\n *\/\nclass TextBench : public SkBenchmark {\n SkPaint fPaint;\n SkString fText;\n SkString fName;\n FontQuality fFQ;\n enum { N = 800 };\npublic:\n TextBench(void* param, const char text[], int ps,\n SkColor color, FontQuality fq) : INHERITED(param) {\n fFQ = fq;\n fText.set(text);\n\n fPaint.setAntiAlias(kBW != fq);\n fPaint.setLCDRenderText(kLCD == fq);\n fPaint.setTextSize(SkIntToScalar(ps));\n fPaint.setColor(color);\n }\n\nprotected:\n virtual const char* onGetName() {\n fName.printf(\"text_%g\", SkScalarToFloat(fPaint.getTextSize()));\n fName.appendf(\"_%s\", fontQualityName(fPaint));\n if (SK_ColorBLACK != fPaint.getColor()) {\n fName.appendf(\"_%02X\", fPaint.getAlpha());\n } else {\n fName.appendf(\"_BK\");\n }\n return fName.c_str();\n }\n\n virtual void onDraw(SkCanvas* canvas) {\n const SkIPoint dim = this->getSize();\n SkRandom rand;\n\n SkPaint paint(fPaint);\n this->setupPaint(&paint);\n \/\/ explicitly need these\n paint.setColor(fPaint.getColor());\n paint.setAntiAlias(kBW != fFQ);\n paint.setLCDRenderText(kLCD == fFQ);\n\n const SkScalar x0 = SkIntToScalar(-10);\n const SkScalar y0 = SkIntToScalar(-10);\n\n for (int i = 0; i < N; i++) {\n SkScalar x = x0 + rand.nextUScalar1() * dim.fX;\n SkScalar y = y0 + rand.nextUScalar1() * dim.fY;\n canvas->drawText(fText.c_str(), fText.size(), x, y, paint);\n }\n }\n\nprivate:\n typedef SkBenchmark INHERITED;\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#define STR \"Hamburgefons\"\n\nstatic SkBenchmark* Fact01(void* p) { return new TextBench(p, STR, 16, 0xFF000000, kBW); }\nstatic SkBenchmark* Fact02(void* p) { return new TextBench(p, STR, 16, 0xFFFF0000, kBW); }\nstatic SkBenchmark* Fact03(void* p) { return new TextBench(p, STR, 16, 0x88FF0000, kBW); }\n\nstatic SkBenchmark* Fact11(void* p) { return new TextBench(p, STR, 16, 0xFF000000, kAA); }\nstatic SkBenchmark* Fact12(void* p) { return new TextBench(p, STR, 16, 0xFFFF0000, kAA); }\nstatic SkBenchmark* Fact13(void* p) { return new TextBench(p, STR, 16, 0x88FF0000, kAA); }\n\nstatic SkBenchmark* Fact21(void* p) { return new TextBench(p, STR, 16, 0xFF000000, kLCD); }\nstatic SkBenchmark* Fact22(void* p) { return new TextBench(p, STR, 16, 0xFFFF0000, kLCD); }\nstatic SkBenchmark* Fact23(void* p) { return new TextBench(p, STR, 16, 0x88FF0000, kLCD); }\n\nstatic BenchRegistry gReg01(Fact01);\nstatic BenchRegistry gReg02(Fact02);\nstatic BenchRegistry gReg03(Fact03);\n\nstatic BenchRegistry gReg11(Fact11);\nstatic BenchRegistry gReg12(Fact12);\nstatic BenchRegistry gReg13(Fact13);\n\nstatic BenchRegistry gReg21(Fact21);\nstatic BenchRegistry gReg22(Fact22);\nstatic BenchRegistry gReg23(Fact23);\n\n<|endoftext|>"} {"text":"<commit_before>#include <benchmark\/benchmark.h>\n\n#include <blackhole\/attribute.hpp>\n\n#include \"mod.hpp\"\n\nnamespace blackhole {\nnamespace benchmark {\n\nstatic void view_ctor_get_int64(::benchmark::State& state) {\n while (state.KeepRunning()) {\n blackhole::attribute::view_t v(42);\n blackhole::attribute::get<std::int64_t>(v);\n }\n\n state.SetItemsProcessed(state.iterations());\n}\n\nstatic void from_owned(::benchmark::State& state) {\n blackhole::attribute::value_t owned(42);\n\n while (state.KeepRunning()) {\n blackhole::attribute::view_t view(owned);\n ::benchmark::DoNotOptimize(view);\n }\n\n state.SetItemsProcessed(state.iterations());\n}\n\nNBENCHMARK(\"attribute.view_t[ctor + get<i64>]\", view_ctor_get_int64);\nNBENCHMARK(\"attribute.view_t[ctor + from owned]\", from_owned);\n\n} \/\/ namespace benchmark\n} \/\/ namespace blackhole\n<commit_msg>feat(bench): measure different values<commit_after>#include <benchmark\/benchmark.h>\n\n#include <blackhole\/attribute.hpp>\n\n#include \"mod.hpp\"\n\nnamespace blackhole {\nnamespace benchmark {\n\nstatic void view_ctor_get_int64(::benchmark::State& state) {\n while (state.KeepRunning()) {\n blackhole::attribute::view_t v(42);\n blackhole::attribute::get<std::int64_t>(v);\n }\n\n state.SetItemsProcessed(state.iterations());\n}\n\nstatic void from_owned(::benchmark::State& state) {\n blackhole::attribute::value_t owned(42);\n\n while (state.KeepRunning()) {\n blackhole::attribute::view_t view(owned);\n ::benchmark::DoNotOptimize(view);\n }\n\n state.SetItemsProcessed(state.iterations());\n}\n\nstatic void from_owned_string(::benchmark::State& state) {\n blackhole::attribute::value_t owned(\"le message\");\n\n while (state.KeepRunning()) {\n blackhole::attribute::view_t view(owned);\n ::benchmark::DoNotOptimize(view);\n }\n\n state.SetItemsProcessed(state.iterations());\n}\n\nNBENCHMARK(\"attribute.view_t[ctor + get<i64>]\", view_ctor_get_int64);\nNBENCHMARK(\"attribute.view_t[ctor + from owned]\", from_owned);\nNBENCHMARK(\"attribute.view_t[ctor + from owned string]\", from_owned_string);\n\n} \/\/ namespace benchmark\n} \/\/ namespace blackhole\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (C) 2018 The Android Open Source Project\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"perfetto\/ext\/base\/watchdog.h\"\n\n#if PERFETTO_BUILDFLAG(PERFETTO_WATCHDOG)\n\n#include <fcntl.h>\n#include <inttypes.h>\n#include <signal.h>\n#include <stdint.h>\n\n#include <fstream>\n#include <thread>\n\n#include \"perfetto\/base\/build_config.h\"\n#include \"perfetto\/base\/logging.h\"\n#include \"perfetto\/base\/thread_utils.h\"\n#include \"perfetto\/ext\/base\/scoped_file.h\"\n\nnamespace perfetto {\nnamespace base {\n\nnamespace {\n\nconstexpr uint32_t kDefaultPollingInterval = 30 * 1000;\n\nbool IsMultipleOf(uint32_t number, uint32_t divisor) {\n return number >= divisor && number % divisor == 0;\n}\n\ndouble MeanForArray(const uint64_t array[], size_t size) {\n uint64_t total = 0;\n for (size_t i = 0; i < size; i++) {\n total += array[i];\n }\n return total \/ size;\n}\n\n} \/\/ namespace\n\nWatchdog::Watchdog(uint32_t polling_interval_ms)\n : polling_interval_ms_(polling_interval_ms) {}\n\nWatchdog::~Watchdog() {\n if (!thread_.joinable()) {\n PERFETTO_DCHECK(!enabled_);\n return;\n }\n PERFETTO_DCHECK(enabled_);\n enabled_ = false;\n exit_signal_.notify_one();\n thread_.join();\n}\n\nWatchdog* Watchdog::GetInstance() {\n static Watchdog* watchdog = new Watchdog(kDefaultPollingInterval);\n return watchdog;\n}\n\nWatchdog::Timer Watchdog::CreateFatalTimer(uint32_t ms) {\n if (!enabled_.load(std::memory_order_relaxed))\n return Watchdog::Timer(0);\n\n return Watchdog::Timer(ms);\n}\n\nvoid Watchdog::Start() {\n std::lock_guard<std::mutex> guard(mutex_);\n if (thread_.joinable()) {\n PERFETTO_DCHECK(enabled_);\n } else {\n PERFETTO_DCHECK(!enabled_);\n\n#if PERFETTO_BUILDFLAG(PERFETTO_OS_LINUX) || \\\n PERFETTO_BUILDFLAG(PERFETTO_OS_ANDROID)\n \/\/ Kick the thread to start running but only on Android or Linux.\n enabled_ = true;\n thread_ = std::thread(&Watchdog::ThreadMain, this);\n#endif\n }\n}\n\nvoid Watchdog::SetMemoryLimit(uint64_t bytes, uint32_t window_ms) {\n \/\/ Update the fields under the lock.\n std::lock_guard<std::mutex> guard(mutex_);\n\n PERFETTO_CHECK(IsMultipleOf(window_ms, polling_interval_ms_) || bytes == 0);\n\n size_t size = bytes == 0 ? 0 : window_ms \/ polling_interval_ms_ + 1;\n memory_window_bytes_.Reset(size);\n memory_limit_bytes_ = bytes;\n}\n\nvoid Watchdog::SetCpuLimit(uint32_t percentage, uint32_t window_ms) {\n std::lock_guard<std::mutex> guard(mutex_);\n\n PERFETTO_CHECK(percentage <= 100);\n PERFETTO_CHECK(IsMultipleOf(window_ms, polling_interval_ms_) ||\n percentage == 0);\n\n size_t size = percentage == 0 ? 0 : window_ms \/ polling_interval_ms_ + 1;\n cpu_window_time_ticks_.Reset(size);\n cpu_limit_percentage_ = percentage;\n}\n\nvoid Watchdog::ThreadMain() {\n base::ScopedFile stat_fd(base::OpenFile(\"\/proc\/self\/stat\", O_RDONLY));\n if (!stat_fd) {\n PERFETTO_ELOG(\"Failed to open stat file to enforce resource limits.\");\n return;\n }\n\n std::unique_lock<std::mutex> guard(mutex_);\n for (;;) {\n exit_signal_.wait_for(guard,\n std::chrono::milliseconds(polling_interval_ms_));\n if (!enabled_)\n return;\n\n lseek(stat_fd.get(), 0, SEEK_SET);\n\n char c[512];\n if (read(stat_fd.get(), c, sizeof(c)) < 0) {\n PERFETTO_ELOG(\"Failed to read stat file to enforce resource limits.\");\n return;\n }\n c[sizeof(c) - 1] = '\\0';\n\n unsigned long int utime = 0l;\n unsigned long int stime = 0l;\n long int rss_pages = -1l;\n PERFETTO_CHECK(\n sscanf(c,\n \"%*d %*s %*c %*d %*d %*d %*d %*d %*u %*u %*u %*u %*u %lu\"\n \"%lu %*d %*d %*d %*d %*d %*d %*u %*u %ld\",\n &utime, &stime, &rss_pages) == 3);\n\n uint64_t cpu_time = utime + stime;\n uint64_t rss_bytes = static_cast<uint64_t>(rss_pages) * base::kPageSize;\n\n CheckMemory(rss_bytes);\n CheckCpu(cpu_time);\n }\n}\n\nvoid Watchdog::CheckMemory(uint64_t rss_bytes) {\n if (memory_limit_bytes_ == 0)\n return;\n\n \/\/ Add the current stat value to the ring buffer and check that the mean\n \/\/ remains under our threshold.\n if (memory_window_bytes_.Push(rss_bytes)) {\n if (memory_window_bytes_.Mean() > memory_limit_bytes_) {\n PERFETTO_ELOG(\n \"Memory watchdog trigger. Memory window of %f bytes is above the \"\n \"%\" PRIu64 \" bytes limit.\",\n memory_window_bytes_.Mean(), memory_limit_bytes_);\n kill(getpid(), SIGABRT);\n }\n }\n}\n\nvoid Watchdog::CheckCpu(uint64_t cpu_time) {\n if (cpu_limit_percentage_ == 0)\n return;\n\n \/\/ Add the cpu time to the ring buffer.\n if (cpu_window_time_ticks_.Push(cpu_time)) {\n \/\/ Compute the percentage over the whole window and check that it remains\n \/\/ under the threshold.\n uint64_t difference_ticks = cpu_window_time_ticks_.NewestWhenFull() -\n cpu_window_time_ticks_.OldestWhenFull();\n double window_interval_ticks =\n (static_cast<double>(WindowTimeForRingBuffer(cpu_window_time_ticks_)) \/\n 1000.0) *\n sysconf(_SC_CLK_TCK);\n double percentage = static_cast<double>(difference_ticks) \/\n static_cast<double>(window_interval_ticks) * 100;\n if (percentage > cpu_limit_percentage_) {\n PERFETTO_ELOG(\"CPU watchdog trigger. %f%% CPU use is above the %\" PRIu32\n \"%% CPU limit.\",\n percentage, cpu_limit_percentage_);\n kill(getpid(), SIGABRT);\n }\n }\n}\n\nuint32_t Watchdog::WindowTimeForRingBuffer(const WindowedInterval& window) {\n return static_cast<uint32_t>(window.size() - 1) * polling_interval_ms_;\n}\n\nbool Watchdog::WindowedInterval::Push(uint64_t sample) {\n \/\/ Add the sample to the current position in the ring buffer.\n buffer_[position_] = sample;\n\n \/\/ Update the position with next one circularily.\n position_ = (position_ + 1) % size_;\n\n \/\/ Set the filled flag the first time we wrap.\n filled_ = filled_ || position_ == 0;\n return filled_;\n}\n\ndouble Watchdog::WindowedInterval::Mean() const {\n return MeanForArray(buffer_.get(), size_);\n}\n\nvoid Watchdog::WindowedInterval::Clear() {\n position_ = 0;\n buffer_.reset(new uint64_t[size_]());\n}\n\nvoid Watchdog::WindowedInterval::Reset(size_t new_size) {\n position_ = 0;\n size_ = new_size;\n buffer_.reset(new_size == 0 ? nullptr : new uint64_t[new_size]());\n}\n\nWatchdog::Timer::Timer(uint32_t ms) {\n if (!ms)\n return; \/\/ No-op timer created when the watchdog is disabled.\n\n struct sigevent sev = {};\n sev.sigev_notify = SIGEV_THREAD_ID;\n sev._sigev_un._tid = base::GetThreadId();\n sev.sigev_signo = SIGABRT;\n PERFETTO_CHECK(timer_create(CLOCK_MONOTONIC, &sev, &timerid_) != -1);\n struct itimerspec its = {};\n its.it_value.tv_sec = ms \/ 1000;\n its.it_value.tv_nsec = 1000000L * (ms % 1000);\n PERFETTO_CHECK(timer_settime(timerid_, 0, &its, nullptr) != -1);\n}\n\nWatchdog::Timer::~Timer() {\n if (timerid_ != nullptr) {\n timer_delete(timerid_);\n }\n}\n\nWatchdog::Timer::Timer(Timer&& other) noexcept {\n timerid_ = other.timerid_;\n other.timerid_ = nullptr;\n}\n\n} \/\/ namespace base\n} \/\/ namespace perfetto\n\n#endif \/\/ PERFETTO_BUILDFLAG(PERFETTO_WATCHDOG)\n<commit_msg>Fix precision errors by explicit casting<commit_after>\/*\n * Copyright (C) 2018 The Android Open Source Project\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"perfetto\/ext\/base\/watchdog.h\"\n\n#if PERFETTO_BUILDFLAG(PERFETTO_WATCHDOG)\n\n#include <fcntl.h>\n#include <inttypes.h>\n#include <signal.h>\n#include <stdint.h>\n\n#include <fstream>\n#include <thread>\n\n#include \"perfetto\/base\/build_config.h\"\n#include \"perfetto\/base\/logging.h\"\n#include \"perfetto\/base\/thread_utils.h\"\n#include \"perfetto\/ext\/base\/scoped_file.h\"\n\nnamespace perfetto {\nnamespace base {\n\nnamespace {\n\nconstexpr uint32_t kDefaultPollingInterval = 30 * 1000;\n\nbool IsMultipleOf(uint32_t number, uint32_t divisor) {\n return number >= divisor && number % divisor == 0;\n}\n\ndouble MeanForArray(const uint64_t array[], size_t size) {\n uint64_t total = 0;\n for (size_t i = 0; i < size; i++) {\n total += array[i];\n }\n return static_cast<double>(total \/ size);\n\n}\n\n} \/\/ namespace\n\nWatchdog::Watchdog(uint32_t polling_interval_ms)\n : polling_interval_ms_(polling_interval_ms) {}\n\nWatchdog::~Watchdog() {\n if (!thread_.joinable()) {\n PERFETTO_DCHECK(!enabled_);\n return;\n }\n PERFETTO_DCHECK(enabled_);\n enabled_ = false;\n exit_signal_.notify_one();\n thread_.join();\n}\n\nWatchdog* Watchdog::GetInstance() {\n static Watchdog* watchdog = new Watchdog(kDefaultPollingInterval);\n return watchdog;\n}\n\nWatchdog::Timer Watchdog::CreateFatalTimer(uint32_t ms) {\n if (!enabled_.load(std::memory_order_relaxed))\n return Watchdog::Timer(0);\n\n return Watchdog::Timer(ms);\n}\n\nvoid Watchdog::Start() {\n std::lock_guard<std::mutex> guard(mutex_);\n if (thread_.joinable()) {\n PERFETTO_DCHECK(enabled_);\n } else {\n PERFETTO_DCHECK(!enabled_);\n\n#if PERFETTO_BUILDFLAG(PERFETTO_OS_LINUX) || \\\n PERFETTO_BUILDFLAG(PERFETTO_OS_ANDROID)\n \/\/ Kick the thread to start running but only on Android or Linux.\n enabled_ = true;\n thread_ = std::thread(&Watchdog::ThreadMain, this);\n#endif\n }\n}\n\nvoid Watchdog::SetMemoryLimit(uint64_t bytes, uint32_t window_ms) {\n \/\/ Update the fields under the lock.\n std::lock_guard<std::mutex> guard(mutex_);\n\n PERFETTO_CHECK(IsMultipleOf(window_ms, polling_interval_ms_) || bytes == 0);\n\n size_t size = bytes == 0 ? 0 : window_ms \/ polling_interval_ms_ + 1;\n memory_window_bytes_.Reset(size);\n memory_limit_bytes_ = bytes;\n}\n\nvoid Watchdog::SetCpuLimit(uint32_t percentage, uint32_t window_ms) {\n std::lock_guard<std::mutex> guard(mutex_);\n\n PERFETTO_CHECK(percentage <= 100);\n PERFETTO_CHECK(IsMultipleOf(window_ms, polling_interval_ms_) ||\n percentage == 0);\n\n size_t size = percentage == 0 ? 0 : window_ms \/ polling_interval_ms_ + 1;\n cpu_window_time_ticks_.Reset(size);\n cpu_limit_percentage_ = percentage;\n}\n\nvoid Watchdog::ThreadMain() {\n base::ScopedFile stat_fd(base::OpenFile(\"\/proc\/self\/stat\", O_RDONLY));\n if (!stat_fd) {\n PERFETTO_ELOG(\"Failed to open stat file to enforce resource limits.\");\n return;\n }\n\n std::unique_lock<std::mutex> guard(mutex_);\n for (;;) {\n exit_signal_.wait_for(guard,\n std::chrono::milliseconds(polling_interval_ms_));\n if (!enabled_)\n return;\n\n lseek(stat_fd.get(), 0, SEEK_SET);\n\n char c[512];\n if (read(stat_fd.get(), c, sizeof(c)) < 0) {\n PERFETTO_ELOG(\"Failed to read stat file to enforce resource limits.\");\n return;\n }\n c[sizeof(c) - 1] = '\\0';\n\n unsigned long int utime = 0l;\n unsigned long int stime = 0l;\n long int rss_pages = -1l;\n PERFETTO_CHECK(\n sscanf(c,\n \"%*d %*s %*c %*d %*d %*d %*d %*d %*u %*u %*u %*u %*u %lu\"\n \"%lu %*d %*d %*d %*d %*d %*d %*u %*u %ld\",\n &utime, &stime, &rss_pages) == 3);\n\n uint64_t cpu_time = utime + stime;\n uint64_t rss_bytes = static_cast<uint64_t>(rss_pages) * base::kPageSize;\n\n CheckMemory(rss_bytes);\n CheckCpu(cpu_time);\n }\n}\n\nvoid Watchdog::CheckMemory(uint64_t rss_bytes) {\n if (memory_limit_bytes_ == 0)\n return;\n\n \/\/ Add the current stat value to the ring buffer and check that the mean\n \/\/ remains under our threshold.\n if (memory_window_bytes_.Push(rss_bytes)) {\n if (memory_window_bytes_.Mean() > static_cast<double>(memory_limit_bytes_)) {\n PERFETTO_ELOG(\n \"Memory watchdog trigger. Memory window of %f bytes is above the \"\n \"%\" PRIu64 \" bytes limit.\",\n memory_window_bytes_.Mean(), memory_limit_bytes_);\n kill(getpid(), SIGABRT);\n }\n }\n}\n\nvoid Watchdog::CheckCpu(uint64_t cpu_time) {\n if (cpu_limit_percentage_ == 0)\n return;\n\n \/\/ Add the cpu time to the ring buffer.\n if (cpu_window_time_ticks_.Push(cpu_time)) {\n \/\/ Compute the percentage over the whole window and check that it remains\n \/\/ under the threshold.\n uint64_t difference_ticks = cpu_window_time_ticks_.NewestWhenFull() -\n cpu_window_time_ticks_.OldestWhenFull();\n double window_interval_ticks =\n (static_cast<double>(WindowTimeForRingBuffer(cpu_window_time_ticks_)) \/\n 1000.0) *\n static_cast<double>(sysconf(_SC_CLK_TCK));\n double percentage = static_cast<double>(difference_ticks) \/\n static_cast<double>(window_interval_ticks) * 100;\n if (percentage > cpu_limit_percentage_) {\n PERFETTO_ELOG(\"CPU watchdog trigger. %f%% CPU use is above the %\" PRIu32\n \"%% CPU limit.\",\n percentage, cpu_limit_percentage_);\n kill(getpid(), SIGABRT);\n }\n }\n}\n\nuint32_t Watchdog::WindowTimeForRingBuffer(const WindowedInterval& window) {\n return static_cast<uint32_t>(window.size() - 1) * polling_interval_ms_;\n}\n\nbool Watchdog::WindowedInterval::Push(uint64_t sample) {\n \/\/ Add the sample to the current position in the ring buffer.\n buffer_[position_] = sample;\n\n \/\/ Update the position with next one circularily.\n position_ = (position_ + 1) % size_;\n\n \/\/ Set the filled flag the first time we wrap.\n filled_ = filled_ || position_ == 0;\n return filled_;\n}\n\ndouble Watchdog::WindowedInterval::Mean() const {\n return MeanForArray(buffer_.get(), size_);\n}\n\nvoid Watchdog::WindowedInterval::Clear() {\n position_ = 0;\n buffer_.reset(new uint64_t[size_]());\n}\n\nvoid Watchdog::WindowedInterval::Reset(size_t new_size) {\n position_ = 0;\n size_ = new_size;\n buffer_.reset(new_size == 0 ? nullptr : new uint64_t[new_size]());\n}\n\nWatchdog::Timer::Timer(uint32_t ms) {\n if (!ms)\n return; \/\/ No-op timer created when the watchdog is disabled.\n\n struct sigevent sev = {};\n sev.sigev_notify = SIGEV_THREAD_ID;\n sev._sigev_un._tid = base::GetThreadId();\n sev.sigev_signo = SIGABRT;\n PERFETTO_CHECK(timer_create(CLOCK_MONOTONIC, &sev, &timerid_) != -1);\n struct itimerspec its = {};\n its.it_value.tv_sec = ms \/ 1000;\n its.it_value.tv_nsec = 1000000L * (ms % 1000);\n PERFETTO_CHECK(timer_settime(timerid_, 0, &its, nullptr) != -1);\n}\n\nWatchdog::Timer::~Timer() {\n if (timerid_ != nullptr) {\n timer_delete(timerid_);\n }\n}\n\nWatchdog::Timer::Timer(Timer&& other) noexcept {\n timerid_ = other.timerid_;\n other.timerid_ = nullptr;\n}\n\n} \/\/ namespace base\n} \/\/ namespace perfetto\n\n#endif \/\/ PERFETTO_BUILDFLAG(PERFETTO_WATCHDOG)\n<|endoftext|>"} {"text":"<commit_before>#include \"lua_class.h\"\n#include \"..\/table\/table.h\"\n#include \"..\/util\/string_enum.h\"\n\nnamespace saki\n{\n\n\n\nbool isValidSuitStr(const std::string &s)\n{\n return s.size() == 1 && T34::isValidSuit(s[0]);\n}\n\nstd::string toLower(const char *s)\n{\n std::string res(s);\n std::for_each(res.begin(), res.end(), [](char &c) {\n c = static_cast<char>(std::tolower(c));\n });\n return res;\n}\n\nstd::pair<Mount::Exit, bool> parseMountExit(const std::string &s)\n{\n std::pair<Mount::Exit, bool> res;\n\n res.second = true;\n if (s == \"pii\")\n res.first = Mount::Exit::PII;\n else if (s == \"rinshan\")\n res.first = Mount::Exit::RINSHAN;\n else if (s == \"dorahyou\")\n res.first = Mount::Exit::DORAHYOU;\n else if (s == \"urahyou\")\n res.first = Mount::Exit::URAHYOU;\n else\n res.second = false;\n\n return res;\n}\n\ntemplate<typename Class, typename Ret, typename... Args>\nclass AsTable\n{\npublic:\n using Method = Ret (Class::*)(Args...) const;\n using Table = sol::as_table_t<sol::meta::unqualified_t<Ret>>;\n\n explicit AsTable(Method method)\n : mMethod(method)\n {\n }\n\n Table operator()(Class &thiz, Args... args)\n {\n return sol::as_table((thiz.*mMethod)(args...));\n }\n\nprivate:\n Method mMethod;\n};\n\nvoid setupLuaClasses(const sol::environment &env, LuaUserErrorHandler &error)\n{\n setupLuaTile(env, error);\n setupLuaWho(env);\n setupLuaMeld(env, error);\n setupLuaExist(env, error);\n setupLuaMount(env, error);\n setupLuaTileCount(env, error);\n setupLuaHand(env);\n setupLuaGame(env);\n}\n\nvoid setupLuaTile(sol::environment env, LuaUserErrorHandler &error)\n{\n env.new_usertype<T34>(\n \"T34\",\n sol::meta_function::construct, sol::factories(\n [&error](int ti) {\n if (ti < 0 || ti >= 34) {\n error.handleUserError(\"invalid T34 id\");\n return T34();\n }\n\n return T34(ti);\n },\n [&error](const std::string s) {\n static const std::array<std::string, 34> dict {\n \"1m\", \"2m\", \"3m\", \"4m\", \"5m\", \"6m\", \"7m\", \"8m\", \"9m\",\n \"1p\", \"2p\", \"3p\", \"4p\", \"5p\", \"6p\", \"7p\", \"8p\", \"9p\",\n \"1s\", \"2s\", \"3s\", \"4s\", \"5s\", \"6s\", \"7s\", \"8s\", \"9s\",\n \"1f\", \"2f\", \"3f\", \"4f\", \"1y\", \"2y\", \"3y\"\n };\n\n auto it = std::find(dict.begin(), dict.end(), s);\n if (it == dict.end()) {\n error.handleUserError(\"invalid T34 string\");\n return T34();\n }\n\n return T34(static_cast<int>(it - dict.begin()));\n }\n ),\n \"id34\", &T34::id34,\n \"suit\", [](T34 t) { return T34::charOf(t.suit()); },\n \"val\", &T34::val,\n \"str34\", &T34::str34,\n \"isyakuhai\", &T34::isYakuhai,\n sol::meta_function::to_string, &T34::str34,\n \"all\", sol::var(std::vector<T34>(tiles34::ALL34.begin(), tiles34::ALL34.end()))\n );\n\n env.new_usertype<T37>(\n \"T37\",\n sol::meta_function::construct, sol::factories(\n [&error](int ti) {\n if (ti < 0 || ti >= 34) {\n error.handleUserError(\"invalid T34 id\");\n return T37();\n }\n\n return T37(ti);\n },\n [&error](const std::string s) {\n if (!T37::isValidStr(s.c_str())) {\n error.handleUserError(\"invalid T37 suit\");\n return T37();\n }\n return T37(s.c_str());\n }\n ),\n \"isaka5\", &T37::isAka5,\n \"str37\", &T37::str37,\n sol::meta_function::to_string, &T37::str37,\n sol::base_classes, sol::bases<T34>()\n );\n}\n\nvoid setupLuaWho(sol::environment env)\n{\n env.new_usertype<Who>(\n \"Who\",\n \"right\", &Who::right,\n \"cross\", &Who::cross,\n \"left\", &Who::left,\n sol::meta_function::to_string, &Who::index,\n sol::meta_function::equal_to, &Who::operator==\n );\n}\n\nvoid setupLuaMeld(sol::environment env, LuaUserErrorHandler &error)\n{\n env.new_usertype<M37>(\n \"M37\",\n \"type\", [](const M37 &m) {\n return toLower(util::stringOf(m.type()));\n },\n sol::meta_function::index, [&error](const M37 &m, int index) {\n int zeroIndex = index - 1;\n int size = static_cast<int>(m.tiles().size());\n if (zeroIndex < 0 || zeroIndex > size) {\n error.handleUserError(\"invalid meld index\");\n return T37();\n }\n\n return m[index];\n }\n );\n}\n\nvoid setupLuaExist(sol::environment env, LuaUserErrorHandler &error)\n{\n (void) error;\n env.new_usertype<Exist>(\n \"Exist\",\n \"incmk\", sol::overload(\n [](Exist &exist, T34 t, int delta) {\n exist.incMk(t, delta);\n },\n [](Exist &exist, const T37 &t, int delta) {\n exist.incMk(t, delta);\n }\n )\n );\n}\n\nvoid setupLuaMount(sol::environment env, LuaUserErrorHandler &error)\n{\n env.new_usertype<Mount>(\n \"Mount\",\n \"remainpii\", &Mount::remainPii,\n \"remainrinshan\", &Mount::remainRinshan,\n \"remaina\", sol::overload(\n [](Mount &mount, T34 t) {\n mount.remainA(t);\n },\n [](Mount &mount, const T37 &t) {\n mount.remainA(t);\n }\n ),\n \"getdrids\", AsTable(&Mount::getDrids),\n \"geturids\", AsTable(&Mount::getUrids),\n \"lighta\", sol::overload(\n [](Mount &mount, T34 t, int mk, bool rin) {\n mount.lightA(t, mk, rin);\n },\n [](Mount &mount, T34 t, int mk) {\n mount.lightA(t, mk);\n }\n ),\n \"lightb\", sol::overload(\n [](Mount &mount, T34 t, int mk, bool rin) {\n mount.lightB(t, mk, rin);\n },\n [](Mount &mount, T34 t, int mk) {\n mount.lightB(t, mk);\n }\n ),\n \"incmk\", sol::overload(\n [&error](Mount &mount, std::string exit, size_t pos, T34 t, int delta, bool bSpace) {\n auto [e, ok] = parseMountExit(exit);\n if (!ok) {\n error.handleUserError(\"invalid mount exit\");\n return;\n }\n mount.incMk(e, pos, t, delta, bSpace);\n },\n [&error](Mount &mount, std::string exit, size_t pos, const T37 &t, int delta, bool bSpace) {\n auto [e, ok] = parseMountExit(exit);\n if (!ok) {\n error.handleUserError(\"invalid mount exit\");\n return;\n }\n mount.incMk(e, pos, t, delta, bSpace);\n }\n ),\n \"loadb\", &Mount::loadB\n );\n}\n\nvoid setupLuaTileCount(sol::environment env, LuaUserErrorHandler &error)\n{\n env.new_usertype<TileCount>(\n \"Tilecount\",\n \"ct\", sol::overload(\n [](const TileCount &tc, T34 t) {\n return tc.ct(t);\n },\n [&error](const TileCount &tc, std::string suit) {\n if (!isValidSuitStr(suit)) {\n error.handleUserError(\"invalid suit\");\n return 0;\n }\n\n return tc.ct(T34::suitOf(suit[0]));\n }\n )\n );\n}\n\nvoid setupLuaHand(sol::environment env)\n{\n env.new_usertype<Hand>(\n \"Hand\",\n \"closed\", &Hand::closed,\n \"ct\", &Hand::ct,\n \"ctaka5\", &Hand::ctAka5,\n \"ready\", &Hand::ready,\n \"step\", &Hand::step,\n \"step4\", &Hand::step4,\n \"step7\", &Hand::step7,\n \"step13\", &Hand::step13,\n \"effa\", AsTable(&Hand::effA),\n \"effa4\", AsTable(&Hand::effA4),\n \"ismenzen\", &Hand::isMenzen,\n \"barks\", AsTable(&Hand::barks),\n \"canchii\", &Hand::canChii,\n \"canchiiasleft\", &Hand::canChiiAsLeft,\n \"canchiiasmiddle\", &Hand::canChiiAsMiddle,\n \"canchiiasright\", &Hand::canChiiAsRight,\n \"canpon\", &Hand::canPon,\n \"candaiminkan\", &Hand::canDaiminkan,\n sol::meta_function::modulus, sol::overload(\n [](const util::Stactor<T37, 5> &ids, const Hand &hand) {\n return ids % hand;\n },\n [](T34 indic, const Hand &hand) {\n return indic % hand;\n }\n )\n );\n}\n\nvoid setupLuaGame(sol::environment env)\n{\n env.new_usertype<Table>(\n \"Game\",\n \"gethand\", &Table::getHand,\n \"getround\", &Table::getRound,\n \"getextraround\", &Table::getExtraRound,\n \"getdealer\", &Table::getDealer,\n \"getselfwind\", &Table::getSelfWind,\n \"getroundwind\", &Table::getRoundWind,\n \"getriver\", AsTable(&Table::getRiver),\n \"riichiestablished\", &Table::riichiEstablished\n );\n}\n\nsol::table toLuaTable(sol::environment env, const TableEvent &event)\n{\n using TE = TableEvent;\n\n sol::table args = env.create();\n\n switch (event.type()) {\n case TE::Type::TABLE_STARTED:\n args[\"seed\"] = event.as<TE::TableStarted>().seed;\n break;\n case TE::Type::FIRST_DEALER_CHOSEN:\n args[\"who\"] = event.as<TE::FirstDealerChosen>().who;\n break;\n case TE::Type::ROUND_STARTED: {\n const auto &a = event.as<TE::RoundStarted>();\n args[\"round\"] = a.round;\n args[\"extraround\"] = a.extraRound;\n args[\"dealer\"] = a.dealer;\n args[\"alllast\"] = a.allLast;\n args[\"deposit\"] = a.deposit;\n args[\"seed\"] = a.seed;\n break;\n }\n case TE::Type::DICED: {\n const auto &a = event.as<TE::Diced>();\n args[\"die1\"] = a.die1;\n args[\"die2\"] = a.die2;\n break;\n }\n case TE::Type::DRAWN:\n args[\"who\"] = event.as<TE::Drawn>().who;\n break;\n case TE::Type::DISCARDED:\n args[\"spin\"] = event.as<TE::Discarded>().spin;\n break;\n case TE::Type::RIICHI_CALLED:\n args[\"who\"] = event.as<TE::RiichiCalled>().who;\n break;\n case TE::Type::RIICHI_ESTABLISHED:\n args[\"who\"] = event.as<TE::RiichiEstablished>().who;\n break;\n case TE::Type::BARKED: {\n const auto &a = event.as<TE::Barked>();\n args[\"who\"] = a.who;\n args[\"bark\"] = a.bark;\n args[\"spin\"] = a.spin;\n break;\n }\n case TE::Type::ROUND_ENDED: {\n const auto &a = event.as<TE::RoundEnded>();\n args[\"result\"] = util::stringOf(a.result);\n args[\"openers\"] = a.openers;\n args[\"gunner\"] = a.gunner;\n args[\"forms\"] = a.forms;\n break;\n }\n case TE::Type::TABLE_ENDED: {\n const auto &a = event.as<TE::TableEnded>();\n args[\"ranks\"] = a.ranks;\n args[\"scores\"] = a.scores;\n break;\n }\n case TE::Type::POPPED_UP:\n args[\"who\"] = event.as<TE::PoppedUp>().who;\n break;\n default:\n break;\n }\n\n return env.create_with(\n \"type\", util::stringOf(event.type()),\n \"args\", args\n );\n}\n\n\n\n} \/\/ namespace saki\n<commit_msg>add several T34, T37, M37, Who lua api<commit_after>#include \"lua_class.h\"\n#include \"..\/table\/table.h\"\n#include \"..\/util\/string_enum.h\"\n\nnamespace saki\n{\n\n\n\nbool isValidSuitStr(const std::string &s)\n{\n return s.size() == 1 && T34::isValidSuit(s[0]);\n}\n\nstd::string toLower(const char *s)\n{\n std::string res(s);\n std::for_each(res.begin(), res.end(), [](char &c) {\n c = static_cast<char>(std::tolower(c));\n });\n return res;\n}\n\nstd::pair<Mount::Exit, bool> parseMountExit(const std::string &s)\n{\n std::pair<Mount::Exit, bool> res;\n\n res.second = true;\n if (s == \"pii\")\n res.first = Mount::Exit::PII;\n else if (s == \"rinshan\")\n res.first = Mount::Exit::RINSHAN;\n else if (s == \"dorahyou\")\n res.first = Mount::Exit::DORAHYOU;\n else if (s == \"urahyou\")\n res.first = Mount::Exit::URAHYOU;\n else\n res.second = false;\n\n return res;\n}\n\ntemplate<typename Class, typename Ret, typename... Args>\nclass AsTable\n{\npublic:\n using Method = Ret (Class::*)(Args...) const;\n using Table = sol::as_table_t<sol::meta::unqualified_t<Ret>>;\n\n explicit AsTable(Method method)\n : mMethod(method)\n {\n }\n\n Table operator()(Class &thiz, Args... args)\n {\n return sol::as_table((thiz.*mMethod)(args...));\n }\n\nprivate:\n Method mMethod;\n};\n\nvoid setupLuaClasses(const sol::environment &env, LuaUserErrorHandler &error)\n{\n setupLuaTile(env, error);\n setupLuaWho(env);\n setupLuaMeld(env, error);\n setupLuaExist(env, error);\n setupLuaMount(env, error);\n setupLuaTileCount(env, error);\n setupLuaHand(env);\n setupLuaGame(env);\n}\n\nvoid setupLuaTile(sol::environment env, LuaUserErrorHandler &error)\n{\n env.new_usertype<T34>(\n \"T34\",\n sol::meta_function::construct, sol::factories(\n [&error](int ti) {\n if (ti < 0 || ti >= 34) {\n error.handleUserError(\"invalid T34 id\");\n return T34();\n }\n\n return T34(ti);\n },\n [&error](const std::string s) {\n static const std::array<std::string, 34> dict {\n \"1m\", \"2m\", \"3m\", \"4m\", \"5m\", \"6m\", \"7m\", \"8m\", \"9m\",\n \"1p\", \"2p\", \"3p\", \"4p\", \"5p\", \"6p\", \"7p\", \"8p\", \"9p\",\n \"1s\", \"2s\", \"3s\", \"4s\", \"5s\", \"6s\", \"7s\", \"8s\", \"9s\",\n \"1f\", \"2f\", \"3f\", \"4f\", \"1y\", \"2y\", \"3y\"\n };\n\n auto it = std::find(dict.begin(), dict.end(), s);\n if (it == dict.end()) {\n error.handleUserError(\"invalid T34 string\");\n return T34();\n }\n\n return T34(static_cast<int>(it - dict.begin()));\n }\n ),\n \"id34\", &T34::id34,\n \"suit\", [](T34 t) { return T34::charOf(t.suit()); },\n \"val\", &T34::val,\n \"str34\", &T34::str34,\n \"isz\", &T34::isZ,\n \"isnum\", &T34::isNum,\n \"isnum19\", &T34::isNum19,\n \"isyao\", &T34::isYao,\n \"isyakuhai\", &T34::isYakuhai,\n \"dora\", &T34::dora,\n \"indicator\", &T34::indicator,\n sol::meta_function::to_string, &T34::str34,\n sol::meta_function::equal_to, &T34::operator==,\n sol::meta_function::less_than, &T34::operator<,\n sol::meta_function::modulus, &T34::operator%,\n \"all\", sol::var(std::vector<T34>(tiles34::ALL34.begin(), tiles34::ALL34.end()))\n );\n\n env.new_usertype<T37>(\n \"T37\",\n sol::meta_function::construct, sol::factories(\n [&error](int ti) {\n if (ti < 0 || ti >= 34) {\n error.handleUserError(\"invalid T34 id\");\n return T37();\n }\n\n return T37(ti);\n },\n [&error](const std::string s) {\n if (!T37::isValidStr(s.c_str())) {\n error.handleUserError(\"invalid T37 suit\");\n return T37();\n }\n return T37(s.c_str());\n }\n ),\n \"isaka5\", &T37::isAka5,\n \"lookssame\", &T37::looksSame,\n \"str37\", &T37::str37,\n sol::meta_function::to_string, &T37::str37,\n sol::base_classes, sol::bases<T34>()\n );\n}\n\nvoid setupLuaWho(sol::environment env)\n{\n env.new_usertype<Who>(\n \"Who\",\n \"right\", &Who::right,\n \"cross\", &Who::cross,\n \"left\", &Who::left,\n \"bydice\", &Who::byDice,\n \"byturn\", &Who::byTurn,\n \"looksat\", &Who::looksAt,\n \"turnfrom\", &Who::turnFrom,\n \"index\", [](Who w) { return w.index() + 1; },\n sol::meta_function::to_string, [](Who w) { return w.index() + 1; },\n sol::meta_function::equal_to, &Who::operator==\n );\n}\n\nvoid setupLuaMeld(sol::environment env, LuaUserErrorHandler &error)\n{\n env.new_usertype<M37>(\n \"M37\",\n \"type\", [](const M37 &m) {\n return toLower(util::stringOf(m.type()));\n },\n \"has\", &M37::has,\n sol::meta_function::index, [&error](const M37 &m, int index) {\n int zeroIndex = index - 1;\n int size = static_cast<int>(m.tiles().size());\n if (zeroIndex < 0 || zeroIndex > size) {\n error.handleUserError(\"invalid meld index\");\n return T37();\n }\n\n return m[index];\n }\n );\n}\n\nvoid setupLuaExist(sol::environment env, LuaUserErrorHandler &error)\n{\n (void) error;\n env.new_usertype<Exist>(\n \"Exist\",\n \"incmk\", sol::overload(\n [](Exist &exist, T34 t, int delta) {\n exist.incMk(t, delta);\n },\n [](Exist &exist, const T37 &t, int delta) {\n exist.incMk(t, delta);\n }\n )\n );\n}\n\nvoid setupLuaMount(sol::environment env, LuaUserErrorHandler &error)\n{\n env.new_usertype<Mount>(\n \"Mount\",\n \"remainpii\", &Mount::remainPii,\n \"remainrinshan\", &Mount::remainRinshan,\n \"remaina\", sol::overload(\n [](Mount &mount, T34 t) {\n mount.remainA(t);\n },\n [](Mount &mount, const T37 &t) {\n mount.remainA(t);\n }\n ),\n \"getdrids\", AsTable(&Mount::getDrids),\n \"geturids\", AsTable(&Mount::getUrids),\n \"lighta\", sol::overload(\n [](Mount &mount, T34 t, int mk, bool rin) {\n mount.lightA(t, mk, rin);\n },\n [](Mount &mount, T34 t, int mk) {\n mount.lightA(t, mk);\n }\n ),\n \"lightb\", sol::overload(\n [](Mount &mount, T34 t, int mk, bool rin) {\n mount.lightB(t, mk, rin);\n },\n [](Mount &mount, T34 t, int mk) {\n mount.lightB(t, mk);\n }\n ),\n \"incmk\", sol::overload(\n [&error](Mount &mount, std::string exit, size_t pos, T34 t, int delta, bool bSpace) {\n auto [e, ok] = parseMountExit(exit);\n if (!ok) {\n error.handleUserError(\"invalid mount exit\");\n return;\n }\n mount.incMk(e, pos, t, delta, bSpace);\n },\n [&error](Mount &mount, std::string exit, size_t pos, const T37 &t, int delta, bool bSpace) {\n auto [e, ok] = parseMountExit(exit);\n if (!ok) {\n error.handleUserError(\"invalid mount exit\");\n return;\n }\n mount.incMk(e, pos, t, delta, bSpace);\n }\n ),\n \"loadb\", &Mount::loadB\n );\n}\n\nvoid setupLuaTileCount(sol::environment env, LuaUserErrorHandler &error)\n{\n env.new_usertype<TileCount>(\n \"Tilecount\",\n \"ct\", sol::overload(\n [](const TileCount &tc, T34 t) {\n return tc.ct(t);\n },\n [&error](const TileCount &tc, std::string suit) {\n if (!isValidSuitStr(suit)) {\n error.handleUserError(\"invalid suit\");\n return 0;\n }\n\n return tc.ct(T34::suitOf(suit[0]));\n }\n )\n );\n}\n\nvoid setupLuaHand(sol::environment env)\n{\n env.new_usertype<Hand>(\n \"Hand\",\n \"closed\", &Hand::closed,\n \"ct\", &Hand::ct,\n \"ctaka5\", &Hand::ctAka5,\n \"ready\", &Hand::ready,\n \"step\", &Hand::step,\n \"step4\", &Hand::step4,\n \"step7\", &Hand::step7,\n \"step13\", &Hand::step13,\n \"effa\", AsTable(&Hand::effA),\n \"effa4\", AsTable(&Hand::effA4),\n \"ismenzen\", &Hand::isMenzen,\n \"barks\", AsTable(&Hand::barks),\n \"canchii\", &Hand::canChii,\n \"canchiiasleft\", &Hand::canChiiAsLeft,\n \"canchiiasmiddle\", &Hand::canChiiAsMiddle,\n \"canchiiasright\", &Hand::canChiiAsRight,\n \"canpon\", &Hand::canPon,\n \"candaiminkan\", &Hand::canDaiminkan,\n sol::meta_function::modulus, sol::overload(\n [](const util::Stactor<T37, 5> &ids, const Hand &hand) {\n return ids % hand;\n },\n [](T34 indic, const Hand &hand) {\n return indic % hand;\n }\n )\n );\n}\n\nvoid setupLuaGame(sol::environment env)\n{\n env.new_usertype<Table>(\n \"Game\",\n \"gethand\", &Table::getHand,\n \"getround\", &Table::getRound,\n \"getextraround\", &Table::getExtraRound,\n \"getdealer\", &Table::getDealer,\n \"getselfwind\", &Table::getSelfWind,\n \"getroundwind\", &Table::getRoundWind,\n \"getriver\", AsTable(&Table::getRiver),\n \"riichiestablished\", &Table::riichiEstablished\n );\n}\n\nsol::table toLuaTable(sol::environment env, const TableEvent &event)\n{\n using TE = TableEvent;\n\n sol::table args = env.create();\n\n switch (event.type()) {\n case TE::Type::TABLE_STARTED:\n args[\"seed\"] = event.as<TE::TableStarted>().seed;\n break;\n case TE::Type::FIRST_DEALER_CHOSEN:\n args[\"who\"] = event.as<TE::FirstDealerChosen>().who;\n break;\n case TE::Type::ROUND_STARTED: {\n const auto &a = event.as<TE::RoundStarted>();\n args[\"round\"] = a.round;\n args[\"extraround\"] = a.extraRound;\n args[\"dealer\"] = a.dealer;\n args[\"alllast\"] = a.allLast;\n args[\"deposit\"] = a.deposit;\n args[\"seed\"] = a.seed;\n break;\n }\n case TE::Type::DICED: {\n const auto &a = event.as<TE::Diced>();\n args[\"die1\"] = a.die1;\n args[\"die2\"] = a.die2;\n break;\n }\n case TE::Type::DRAWN:\n args[\"who\"] = event.as<TE::Drawn>().who;\n break;\n case TE::Type::DISCARDED:\n args[\"spin\"] = event.as<TE::Discarded>().spin;\n break;\n case TE::Type::RIICHI_CALLED:\n args[\"who\"] = event.as<TE::RiichiCalled>().who;\n break;\n case TE::Type::RIICHI_ESTABLISHED:\n args[\"who\"] = event.as<TE::RiichiEstablished>().who;\n break;\n case TE::Type::BARKED: {\n const auto &a = event.as<TE::Barked>();\n args[\"who\"] = a.who;\n args[\"bark\"] = a.bark;\n args[\"spin\"] = a.spin;\n break;\n }\n case TE::Type::ROUND_ENDED: {\n const auto &a = event.as<TE::RoundEnded>();\n args[\"result\"] = util::stringOf(a.result);\n args[\"openers\"] = a.openers;\n args[\"gunner\"] = a.gunner;\n args[\"forms\"] = a.forms;\n break;\n }\n case TE::Type::TABLE_ENDED: {\n const auto &a = event.as<TE::TableEnded>();\n args[\"ranks\"] = a.ranks;\n args[\"scores\"] = a.scores;\n break;\n }\n case TE::Type::POPPED_UP:\n args[\"who\"] = event.as<TE::PoppedUp>().who;\n break;\n default:\n break;\n }\n\n return env.create_with(\n \"type\", util::stringOf(event.type()),\n \"args\", args\n );\n}\n\n\n\n} \/\/ namespace saki\n<|endoftext|>"} {"text":"<commit_before>#include <benchmark\/benchmark.h>\n#include <iostream>\n#include <boost\/optional\/optional.hpp>\n\nnamespace\n{\n struct TestReporter : benchmark::BenchmarkReporter\n {\n boost::optional<bool> ok;\n benchmark::ConsoleReporter display;\n\n bool ReportContext(const Context &context) override\n {\n return display.ReportContext(context);\n }\n\n void ReportRuns(const std::vector<Run> &report) override\n {\n for (const Run &run : report)\n {\n if (run.benchmark_name == \"MediumRequestAndResponseOverInProcessPipe\/4k\")\n {\n \/\/ These values should be about right for the super slow processors on travis-ci.\n const double required_bytes =\n#ifdef NDEBUG\n 1200000\n#else\n 26000\n#endif\n ;\n if (run.bytes_per_second >= required_bytes)\n {\n if (run.bytes_per_second < (required_bytes * 2))\n {\n ok = true;\n }\n else\n {\n std::cerr << run.benchmark_name\n << \" is much faster than required which is suspicious: \" << run.bytes_per_second\n << \" bytes\/s (\" << required_bytes << \" required)\\n\";\n ok = false;\n }\n }\n else\n {\n std::cerr << run.benchmark_name << \" is too slow: \" << run.bytes_per_second << \" bytes\/s (\"\n << required_bytes << \" required)\\n\";\n ok = false;\n }\n }\n }\n return display.ReportRuns(report);\n }\n };\n}\n\nint main(int argc, char **argv)\n{\n benchmark::Initialize(&argc, argv);\n TestReporter reporter;\n benchmark::RunSpecifiedBenchmarks(&reporter);\n if (!reporter.ok)\n {\n std::cerr << \"At least one of the required test benchmarks did not run\\n\";\n return 1;\n }\n return (*reporter.ok ? 0 : 1);\n}\n<commit_msg>benchmark: debug is even slower now<commit_after>#include <benchmark\/benchmark.h>\n#include <iostream>\n#include <boost\/optional\/optional.hpp>\n\nnamespace\n{\n struct TestReporter : benchmark::BenchmarkReporter\n {\n boost::optional<bool> ok;\n benchmark::ConsoleReporter display;\n\n bool ReportContext(const Context &context) override\n {\n return display.ReportContext(context);\n }\n\n void ReportRuns(const std::vector<Run> &report) override\n {\n for (const Run &run : report)\n {\n if (run.benchmark_name == \"MediumRequestAndResponseOverInProcessPipe\/4k\")\n {\n \/\/ These values should be about right for the super slow processors on travis-ci.\n const double required_bytes =\n#ifdef NDEBUG\n 1200000\n#else\n 19500\n#endif\n ;\n if (run.bytes_per_second >= required_bytes)\n {\n if (run.bytes_per_second < (required_bytes * 2))\n {\n ok = true;\n }\n else\n {\n std::cerr << run.benchmark_name\n << \" is much faster than required which is suspicious: \" << run.bytes_per_second\n << \" bytes\/s (\" << required_bytes << \" required)\\n\";\n ok = false;\n }\n }\n else\n {\n std::cerr << run.benchmark_name << \" is too slow: \" << run.bytes_per_second << \" bytes\/s (\"\n << required_bytes << \" required)\\n\";\n ok = false;\n }\n }\n }\n return display.ReportRuns(report);\n }\n };\n}\n\nint main(int argc, char **argv)\n{\n benchmark::Initialize(&argc, argv);\n TestReporter reporter;\n benchmark::RunSpecifiedBenchmarks(&reporter);\n if (!reporter.ok)\n {\n std::cerr << \"At least one of the required test benchmarks did not run\\n\";\n return 1;\n }\n return (*reporter.ok ? 0 : 1);\n}\n<|endoftext|>"} {"text":"<commit_before>\/**\n * \\file\n * \\brief Implementation of RCC-related functions for STM32F1\n *\n * \\author Copyright (C) 2016 Kamil Szczygiel http:\/\/www.distortec.com http:\/\/www.freddiechopin.info\n *\n * \\par License\n * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not\n * distributed with this file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\/\n\n#include \"distortos\/chip\/STM32F1-RCC.hpp\"\n\n#include \"distortos\/chip\/STM32F1-RCC-bits.h\"\n\n#include \"distortos\/chip\/CMSIS-proxy.h\"\n\n#include <array>\n\n#include <cerrno>\n\nnamespace distortos\n{\n\nnamespace chip\n{\n\nnamespace\n{\n\n\/*---------------------------------------------------------------------------------------------------------------------+\n| local functions\n+---------------------------------------------------------------------------------------------------------------------*\/\n\n\/**\n * \\brief Configures PREDIV1 or PREDIV2 division factor.\n *\n * \\param [in] prediv2 selects whether PREDIV1 (false) or PREDIV2 (true) will be configured\n * \\param [in] prediv is the PREDIV1 or PREDIV2 division factor, [minPrediv; maxPrediv]\n *\n * \\return 0 on success, error code otherwise:\n * - EINVAL - \\a prediv value is invalid;\n *\/\n\nint configurePrediv(const bool prediv2, const uint8_t prediv)\n{\n\tif (prediv < minPrediv || prediv > maxPrediv)\n\t\treturn EINVAL;\n\n#if defined(CONFIG_CHIP_STM32F100)\n\tstatic_cast<void>(prediv2);\t\/\/ suppress warning\n\tRCC->CFGR2 = (RCC->CFGR2 & ~RCC_CFGR2_PREDIV1) | (prediv << RCC_CFGR2_PREDIV1_bit);\n#elif defined(CONFIG_CHIP_STM32F105) || defined(CONFIG_CHIP_STM32F107)\n\tRCC->CFGR2 = (RCC->CFGR2 & ~(prediv2 == true ? RCC_CFGR2_PREDIV2 : RCC_CFGR2_PREDIV1)) |\n\t\t\t(prediv << (prediv2 == true ? RCC_CFGR2_PREDIV2_bit : RCC_CFGR2_PREDIV1_bit));\n#else\t\/\/ !defined(CONFIG_CHIP_STM32F100) && !defined(CONFIG_CHIP_STM32F105) && !defined(CONFIG_CHIP_STM32F107)\n\tstatic_cast<void>(prediv2);\t\/\/ suppress warning\n\tRCC_CFGR_PLLXTPRE_bb = prediv == 2;\n#endif\t\/\/ !defined(CONFIG_CHIP_STM32F100) && !defined(CONFIG_CHIP_STM32F105) && !defined(CONFIG_CHIP_STM32F107)\n\treturn 0;\n}\n\n#if defined(CONFIG_CHIP_STM32F105) || defined(CONFIG_CHIP_STM32F107)\n\n\/**\n * \\brief Enables PLL2 or PLL3.\n *\n * Enables PLL2 or PLL3 using selected parameters and waits until it is stable.\n *\n * \\warning Before changing configuration of PLL2 make sure that it is not used in any way (as source of main PLL).\n * Before changing configuration of PLL3 make sure that it is not used in any way (as source of peripheral clocks).\n *\n * \\param [in] pll3 selects whether PLL2 (false) or PLL3 (true) will be configured\n * \\param [in] pll23Mul is the PLL2MUL value for PLL2 or PLL3MUL value for PLL3, [minPll23Mul; maxPll23Mul] and\n * {pll23Mul16, pll23Mul20}\n *\n * \\return 0 on success, error code otherwise:\n * - EINVAL - \\a pll23Mul value is invalid;\n *\/\n\nint enablePll23(const bool pll3, const uint8_t pll23Mul)\n{\n\tif ((pll23Mul < minPll23Mul || pll23Mul > maxPll23Mul) && pll23Mul != pll23Mul16 && pll23Mul != pll23Mul20)\n\t\treturn EINVAL;\n\n\tconst auto convertedPll23Mul = pll23Mul - 2 <= 0xf ? pll23Mul - 2 : 0xf;\n\tRCC->CFGR2 = (RCC->CFGR2 & ~(pll3 == true ? RCC_CFGR2_PLL3MUL : RCC_CFGR2_PLL2MUL)) |\n\t\t\t(convertedPll23Mul << (pll3 == true ? RCC_CFGR2_PLL3MUL_bit : RCC_CFGR2_PLL2MUL_bit));\n\t(pll3 == true ? RCC_CR_PLL3ON_bb : RCC_CR_PLL2ON_bb) = 1;\n\twhile ((pll3 == true ? RCC_CR_PLL3RDY_bb : RCC_CR_PLL2RDY_bb) == 0);\t\/\/ wait until PLL is stable\n\treturn 0;\n}\n\n#endif\t\/\/ defined(CONFIG_CHIP_STM32F105) || defined(CONFIG_CHIP_STM32F107)\n\n}\t\/\/ namespace\n\n\/*---------------------------------------------------------------------------------------------------------------------+\n| global functions\n+---------------------------------------------------------------------------------------------------------------------*\/\n\nint configureAhbClockDivider(const uint16_t hpre)\n{\n\tstatic const std::pair<decltype(hpre), decltype(RCC_CFGR_HPRE_DIV1)> associations[]\n\t{\n\t\t{hpreDiv1, RCC_CFGR_HPRE_DIV1},\n\t\t{hpreDiv2, RCC_CFGR_HPRE_DIV2},\n\t\t{hpreDiv4, RCC_CFGR_HPRE_DIV4},\n\t\t{hpreDiv8, RCC_CFGR_HPRE_DIV8},\n\t\t{hpreDiv16, RCC_CFGR_HPRE_DIV16},\n\t\t{hpreDiv64, RCC_CFGR_HPRE_DIV64},\n\t\t{hpreDiv128, RCC_CFGR_HPRE_DIV128},\n\t\t{hpreDiv256, RCC_CFGR_HPRE_DIV256},\n\t\t{hpreDiv512, RCC_CFGR_HPRE_DIV512},\n\t};\n\n\tfor (auto& association : associations)\n\t\tif (association.first == hpre)\n\t\t{\n\t\t\tRCC->CFGR = (RCC->CFGR & ~RCC_CFGR_HPRE) | association.second;\n\t\t\treturn 0;\n\t\t}\n\n\treturn EINVAL;\n}\n\nint configureApbClockDivider(const bool ppre2, const uint8_t ppre)\n{\n\tstatic const std::pair<decltype(ppre), std::array<decltype(RCC_CFGR_PPRE1_DIV1), 2>> associations[]\n\t{\n\t\t{ppreDiv1, {RCC_CFGR_PPRE1_DIV1, RCC_CFGR_PPRE2_DIV1}},\n\t\t{ppreDiv2, {RCC_CFGR_PPRE1_DIV2, RCC_CFGR_PPRE2_DIV2}},\n\t\t{ppreDiv4, {RCC_CFGR_PPRE1_DIV4, RCC_CFGR_PPRE2_DIV4}},\n\t\t{ppreDiv8, {RCC_CFGR_PPRE1_DIV8, RCC_CFGR_PPRE2_DIV8}},\n\t\t{ppreDiv16, {RCC_CFGR_PPRE1_DIV16, RCC_CFGR_PPRE2_DIV16}},\n\t};\n\n\tfor (auto& association : associations)\n\t\tif (association.first == ppre)\n\t\t{\n\t\t\tstatic const decltype(RCC_CFGR_PPRE1) masks[] {RCC_CFGR_PPRE1, RCC_CFGR_PPRE2};\n\t\t\tRCC->CFGR = (RCC->CFGR & ~masks[ppre2]) | association.second[ppre2];\n\t\t\treturn 0;\n\t\t}\n\n\treturn EINVAL;\n}\n\nint configurePrediv1(const uint8_t prediv1)\n{\n\treturn configurePrediv(false, prediv1);\n}\n\n#if defined(CONFIG_CHIP_STM32F105) || defined(CONFIG_CHIP_STM32F107)\n\nvoid configurePrediv1ClockSource(const bool pll2)\n{\n\tRCC_CFGR2_PREDIV1SRC_bb = pll2;\n}\n\nint configurePrediv2(const uint8_t prediv2)\n{\n\treturn configurePrediv(true, prediv2);\n}\n\n#endif\t\/\/ defined(CONFIG_CHIP_STM32F105) || defined(CONFIG_CHIP_STM32F107)\n\nvoid enableHse(const bool bypass)\n{\n\tRCC_CR_HSEBYP_bb = bypass;\n\tRCC_CR_HSEON_bb = 1;\n\twhile (RCC_CR_HSERDY_bb == 0);\t\/\/ wait until HSE oscillator is stable\n}\n\nint enablePll(const bool prediv1, const uint8_t pllmul)\n{\n#if defined(CONFIG_CHIP_STM32F105) || defined(CONFIG_CHIP_STM32F107)\n\n\tif ((pllmul < minPllmul || pllmul > maxPllmul) && pllmul != pllmul6_5)\n\t\treturn EINVAL;\n\n#else\t\/\/ !defined(CONFIG_CHIP_STM32F105) && !defined(CONFIG_CHIP_STM32F107)\n\n\tif (pllmul < minPllmul || pllmul > maxPllmul)\n\t\treturn EINVAL;\n\n#endif\t\/\/ !defined(CONFIG_CHIP_STM32F105) && !defined(CONFIG_CHIP_STM32F107)\n\n\tRCC->CFGR = (RCC->CFGR & ~(RCC_CFGR_PLLMULL | RCC_CFGR_PLLSRC)) | ((pllmul - 2) << RCC_CFGR_PLLMUL_bit) |\n\t\t\t(prediv1 << RCC_CFGR_PLLSRC_bit);\n\tRCC_CR_PLLON_bb = 1;\n\twhile (RCC_CR_PLLRDY_bb == 0);\t\/\/ wait until PLL is stable\n\treturn 0;\n}\n\n#if defined(CONFIG_CHIP_STM32F105) || defined(CONFIG_CHIP_STM32F107)\n\nint enablePll2(const uint8_t pll2Mul)\n{\n\treturn enablePll23(false, pll2Mul);\n}\n\nint enablePll3(const uint8_t pll3Mul)\n{\n\treturn enablePll23(true, pll3Mul);\n}\n\n#endif\t\/\/ defined(CONFIG_CHIP_STM32F105) || defined(CONFIG_CHIP_STM32F107)\n\nvoid disableHse()\n{\n\tRCC_CR_HSEON_bb = 0;\n}\n\nvoid disablePll()\n{\n\tRCC_CR_PLLON_bb = 0;\n}\n\n#if defined(CONFIG_CHIP_STM32F105) || defined(CONFIG_CHIP_STM32F107)\n\nvoid disablePll2()\n{\n\tRCC_CR_PLL2ON_bb = 0;\n}\n\nvoid disablePll3()\n{\n\tRCC_CR_PLL3ON_bb = 0;\n}\n\n#endif\t\/\/ defined(CONFIG_CHIP_STM32F105) || defined(CONFIG_CHIP_STM32F107)\n\nvoid switchSystemClock(const SystemClockSource source)\n{\n\tconst auto sourceValue = static_cast<uint32_t>(source);\n\tRCC->CFGR = (RCC->CFGR & ~RCC_CFGR_SW) | (sourceValue << RCC_CFGR_SW_bit);\n\twhile ((RCC->CFGR & RCC_CFGR_SWS) != sourceValue << RCC_CFGR_SWS_bit);\n}\n\n}\t\/\/ namespace chip\n\n}\t\/\/ namespace distortos\n<commit_msg>Fix PREDIVx configuration for STM32F1<commit_after>\/**\n * \\file\n * \\brief Implementation of RCC-related functions for STM32F1\n *\n * \\author Copyright (C) 2016 Kamil Szczygiel http:\/\/www.distortec.com http:\/\/www.freddiechopin.info\n *\n * \\par License\n * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not\n * distributed with this file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\/\n\n#include \"distortos\/chip\/STM32F1-RCC.hpp\"\n\n#include \"distortos\/chip\/STM32F1-RCC-bits.h\"\n\n#include \"distortos\/chip\/CMSIS-proxy.h\"\n\n#include <array>\n\n#include <cerrno>\n\nnamespace distortos\n{\n\nnamespace chip\n{\n\nnamespace\n{\n\n\/*---------------------------------------------------------------------------------------------------------------------+\n| local functions\n+---------------------------------------------------------------------------------------------------------------------*\/\n\n\/**\n * \\brief Configures PREDIV1 or PREDIV2 division factor.\n *\n * \\param [in] prediv2 selects whether PREDIV1 (false) or PREDIV2 (true) will be configured\n * \\param [in] prediv is the PREDIV1 or PREDIV2 division factor, [minPrediv; maxPrediv]\n *\n * \\return 0 on success, error code otherwise:\n * - EINVAL - \\a prediv value is invalid;\n *\/\n\nint configurePrediv(const bool prediv2, const uint8_t prediv)\n{\n\tif (prediv < minPrediv || prediv > maxPrediv)\n\t\treturn EINVAL;\n\n#if defined(CONFIG_CHIP_STM32F100)\n\tstatic_cast<void>(prediv2);\t\/\/ suppress warning\n\tRCC->CFGR2 = (RCC->CFGR2 & ~RCC_CFGR2_PREDIV1) | ((prediv - 1) << RCC_CFGR2_PREDIV1_bit);\n#elif defined(CONFIG_CHIP_STM32F105) || defined(CONFIG_CHIP_STM32F107)\n\tRCC->CFGR2 = (RCC->CFGR2 & ~(prediv2 == true ? RCC_CFGR2_PREDIV2 : RCC_CFGR2_PREDIV1)) |\n\t\t\t((prediv - 1) << (prediv2 == true ? RCC_CFGR2_PREDIV2_bit : RCC_CFGR2_PREDIV1_bit));\n#else\t\/\/ !defined(CONFIG_CHIP_STM32F100) && !defined(CONFIG_CHIP_STM32F105) && !defined(CONFIG_CHIP_STM32F107)\n\tstatic_cast<void>(prediv2);\t\/\/ suppress warning\n\tRCC_CFGR_PLLXTPRE_bb = prediv == 2;\n#endif\t\/\/ !defined(CONFIG_CHIP_STM32F100) && !defined(CONFIG_CHIP_STM32F105) && !defined(CONFIG_CHIP_STM32F107)\n\treturn 0;\n}\n\n#if defined(CONFIG_CHIP_STM32F105) || defined(CONFIG_CHIP_STM32F107)\n\n\/**\n * \\brief Enables PLL2 or PLL3.\n *\n * Enables PLL2 or PLL3 using selected parameters and waits until it is stable.\n *\n * \\warning Before changing configuration of PLL2 make sure that it is not used in any way (as source of main PLL).\n * Before changing configuration of PLL3 make sure that it is not used in any way (as source of peripheral clocks).\n *\n * \\param [in] pll3 selects whether PLL2 (false) or PLL3 (true) will be configured\n * \\param [in] pll23Mul is the PLL2MUL value for PLL2 or PLL3MUL value for PLL3, [minPll23Mul; maxPll23Mul] and\n * {pll23Mul16, pll23Mul20}\n *\n * \\return 0 on success, error code otherwise:\n * - EINVAL - \\a pll23Mul value is invalid;\n *\/\n\nint enablePll23(const bool pll3, const uint8_t pll23Mul)\n{\n\tif ((pll23Mul < minPll23Mul || pll23Mul > maxPll23Mul) && pll23Mul != pll23Mul16 && pll23Mul != pll23Mul20)\n\t\treturn EINVAL;\n\n\tconst auto convertedPll23Mul = pll23Mul - 2 <= 0xf ? pll23Mul - 2 : 0xf;\n\tRCC->CFGR2 = (RCC->CFGR2 & ~(pll3 == true ? RCC_CFGR2_PLL3MUL : RCC_CFGR2_PLL2MUL)) |\n\t\t\t(convertedPll23Mul << (pll3 == true ? RCC_CFGR2_PLL3MUL_bit : RCC_CFGR2_PLL2MUL_bit));\n\t(pll3 == true ? RCC_CR_PLL3ON_bb : RCC_CR_PLL2ON_bb) = 1;\n\twhile ((pll3 == true ? RCC_CR_PLL3RDY_bb : RCC_CR_PLL2RDY_bb) == 0);\t\/\/ wait until PLL is stable\n\treturn 0;\n}\n\n#endif\t\/\/ defined(CONFIG_CHIP_STM32F105) || defined(CONFIG_CHIP_STM32F107)\n\n}\t\/\/ namespace\n\n\/*---------------------------------------------------------------------------------------------------------------------+\n| global functions\n+---------------------------------------------------------------------------------------------------------------------*\/\n\nint configureAhbClockDivider(const uint16_t hpre)\n{\n\tstatic const std::pair<decltype(hpre), decltype(RCC_CFGR_HPRE_DIV1)> associations[]\n\t{\n\t\t{hpreDiv1, RCC_CFGR_HPRE_DIV1},\n\t\t{hpreDiv2, RCC_CFGR_HPRE_DIV2},\n\t\t{hpreDiv4, RCC_CFGR_HPRE_DIV4},\n\t\t{hpreDiv8, RCC_CFGR_HPRE_DIV8},\n\t\t{hpreDiv16, RCC_CFGR_HPRE_DIV16},\n\t\t{hpreDiv64, RCC_CFGR_HPRE_DIV64},\n\t\t{hpreDiv128, RCC_CFGR_HPRE_DIV128},\n\t\t{hpreDiv256, RCC_CFGR_HPRE_DIV256},\n\t\t{hpreDiv512, RCC_CFGR_HPRE_DIV512},\n\t};\n\n\tfor (auto& association : associations)\n\t\tif (association.first == hpre)\n\t\t{\n\t\t\tRCC->CFGR = (RCC->CFGR & ~RCC_CFGR_HPRE) | association.second;\n\t\t\treturn 0;\n\t\t}\n\n\treturn EINVAL;\n}\n\nint configureApbClockDivider(const bool ppre2, const uint8_t ppre)\n{\n\tstatic const std::pair<decltype(ppre), std::array<decltype(RCC_CFGR_PPRE1_DIV1), 2>> associations[]\n\t{\n\t\t{ppreDiv1, {RCC_CFGR_PPRE1_DIV1, RCC_CFGR_PPRE2_DIV1}},\n\t\t{ppreDiv2, {RCC_CFGR_PPRE1_DIV2, RCC_CFGR_PPRE2_DIV2}},\n\t\t{ppreDiv4, {RCC_CFGR_PPRE1_DIV4, RCC_CFGR_PPRE2_DIV4}},\n\t\t{ppreDiv8, {RCC_CFGR_PPRE1_DIV8, RCC_CFGR_PPRE2_DIV8}},\n\t\t{ppreDiv16, {RCC_CFGR_PPRE1_DIV16, RCC_CFGR_PPRE2_DIV16}},\n\t};\n\n\tfor (auto& association : associations)\n\t\tif (association.first == ppre)\n\t\t{\n\t\t\tstatic const decltype(RCC_CFGR_PPRE1) masks[] {RCC_CFGR_PPRE1, RCC_CFGR_PPRE2};\n\t\t\tRCC->CFGR = (RCC->CFGR & ~masks[ppre2]) | association.second[ppre2];\n\t\t\treturn 0;\n\t\t}\n\n\treturn EINVAL;\n}\n\nint configurePrediv1(const uint8_t prediv1)\n{\n\treturn configurePrediv(false, prediv1);\n}\n\n#if defined(CONFIG_CHIP_STM32F105) || defined(CONFIG_CHIP_STM32F107)\n\nvoid configurePrediv1ClockSource(const bool pll2)\n{\n\tRCC_CFGR2_PREDIV1SRC_bb = pll2;\n}\n\nint configurePrediv2(const uint8_t prediv2)\n{\n\treturn configurePrediv(true, prediv2);\n}\n\n#endif\t\/\/ defined(CONFIG_CHIP_STM32F105) || defined(CONFIG_CHIP_STM32F107)\n\nvoid enableHse(const bool bypass)\n{\n\tRCC_CR_HSEBYP_bb = bypass;\n\tRCC_CR_HSEON_bb = 1;\n\twhile (RCC_CR_HSERDY_bb == 0);\t\/\/ wait until HSE oscillator is stable\n}\n\nint enablePll(const bool prediv1, const uint8_t pllmul)\n{\n#if defined(CONFIG_CHIP_STM32F105) || defined(CONFIG_CHIP_STM32F107)\n\n\tif ((pllmul < minPllmul || pllmul > maxPllmul) && pllmul != pllmul6_5)\n\t\treturn EINVAL;\n\n#else\t\/\/ !defined(CONFIG_CHIP_STM32F105) && !defined(CONFIG_CHIP_STM32F107)\n\n\tif (pllmul < minPllmul || pllmul > maxPllmul)\n\t\treturn EINVAL;\n\n#endif\t\/\/ !defined(CONFIG_CHIP_STM32F105) && !defined(CONFIG_CHIP_STM32F107)\n\n\tRCC->CFGR = (RCC->CFGR & ~(RCC_CFGR_PLLMULL | RCC_CFGR_PLLSRC)) | ((pllmul - 2) << RCC_CFGR_PLLMUL_bit) |\n\t\t\t(prediv1 << RCC_CFGR_PLLSRC_bit);\n\tRCC_CR_PLLON_bb = 1;\n\twhile (RCC_CR_PLLRDY_bb == 0);\t\/\/ wait until PLL is stable\n\treturn 0;\n}\n\n#if defined(CONFIG_CHIP_STM32F105) || defined(CONFIG_CHIP_STM32F107)\n\nint enablePll2(const uint8_t pll2Mul)\n{\n\treturn enablePll23(false, pll2Mul);\n}\n\nint enablePll3(const uint8_t pll3Mul)\n{\n\treturn enablePll23(true, pll3Mul);\n}\n\n#endif\t\/\/ defined(CONFIG_CHIP_STM32F105) || defined(CONFIG_CHIP_STM32F107)\n\nvoid disableHse()\n{\n\tRCC_CR_HSEON_bb = 0;\n}\n\nvoid disablePll()\n{\n\tRCC_CR_PLLON_bb = 0;\n}\n\n#if defined(CONFIG_CHIP_STM32F105) || defined(CONFIG_CHIP_STM32F107)\n\nvoid disablePll2()\n{\n\tRCC_CR_PLL2ON_bb = 0;\n}\n\nvoid disablePll3()\n{\n\tRCC_CR_PLL3ON_bb = 0;\n}\n\n#endif\t\/\/ defined(CONFIG_CHIP_STM32F105) || defined(CONFIG_CHIP_STM32F107)\n\nvoid switchSystemClock(const SystemClockSource source)\n{\n\tconst auto sourceValue = static_cast<uint32_t>(source);\n\tRCC->CFGR = (RCC->CFGR & ~RCC_CFGR_SW) | (sourceValue << RCC_CFGR_SW_bit);\n\twhile ((RCC->CFGR & RCC_CFGR_SWS) != sourceValue << RCC_CFGR_SWS_bit);\n}\n\n}\t\/\/ namespace chip\n\n}\t\/\/ namespace distortos\n<|endoftext|>"} {"text":"<commit_before>#include \"tour_processor.h\"\n#include \"b5m_types.h\"\n#include \"b5m_helper.h\"\n#include \"scd_doc_processor.h\"\n#include <boost\/algorithm\/string.hpp>\n#include <glog\/logging.h>\n#include <common\/ScdParser.h>\n#include <document-manager\/ScdDocument.h>\n#include <assert.h>\n\n\/\/#define TOUR_DEBUG\n\nusing namespace sf1r;\n\nTourProcessor::TourProcessor()\n{\n}\n\nTourProcessor::~TourProcessor()\n{\n}\n\nbool TourProcessor::Generate(const std::string& scd_path, const std::string& mdb_instance)\n{\n\t\/\/scan all the *.scd\n m_ = mdb_instance;\n ScdDocProcessor::ProcessorType p = boost::bind(&TourProcessor::Insert_, this, _1);\n int thread_num = 1;\n ScdDocProcessor sd_processor(p, thread_num);\n sd_processor.AddInput(scd_path);\n sd_processor.Process();\n Finish_();\n\treturn true;\n}\n\nvoid TourProcessor::Insert_(ScdDocument& doc)\n{\n\tstd::string sdays;\n\tstd::string price;\n\tBufferValueItem value;\n doc.getString(SCD_FROM_CITY, value.from);\n doc.getString(SCD_TO_CITY, value.to);\n\tdoc.getString(SCD_PRICE,price);\n doc.getString(SCD_TIME_PLAN, sdays);\n value.days = ParseDays_(sdays);\n value.doc = doc;\n value.price = 0.0;\n try {\n value.price = boost::lexical_cast<double>(price);\n }\n catch(std::exception& ex)\n {\n std::cerr<<\"parse tour price error for \"<< price<<std::endl;\n }\n value.bcluster = true;\n if(value.days.second==0||value.price==0.0||value.from.empty()||value.to.empty()) value.bcluster = false;\n \n\t\/\/generate union key by to_city\n\tUnionBufferKey union_key;\n\tGenerateUnionKey(union_key,value.from,value.to);\n\t\/\/BufferKey key(value.from, value.to);\n boost::unique_lock<boost::mutex> lock(mutex_);\n buffer_[union_key].push_back(value);\n}\n\nstd::pair<uint32_t, uint32_t> TourProcessor::ParseDays_(const std::string& sdays) const\n{\n \/\/find \"天\" Ps:4-7天\/8天\n std::pair<uint32_t, uint32_t> r(0,0);\n\tsize_t pos = sdays.find(\"天\");\n\tif(pos == std::string::npos)\n\t{\n\t\tpos = sdays.length();\n\t}\n\t\n\tstd::string tmp_days = sdays.substr(0,pos);\n\t\/\/find '-'\n\tpos = tmp_days.find('-');\n\tif(pos == std::string::npos)\n\t{\n\t\tr.first = atoi(tmp_days.c_str());\n\t\tr.second = r.first;\n\t}\n\telse\n\t{\n\t\tint min_days = atoi(tmp_days.substr(0,pos).c_str());\n\t\tint max_days = atoi(tmp_days.substr(pos+1).c_str());\n\t\tr.first = min_days;\n\t\tr.second = max_days;\n\t}\n\treturn r;\n}\n\nvoid TourProcessor::GenerateUnionKey(UnionBufferKey& union_key,\n\t\t\t\t\t\t\t\t\t const std::string& from_city,\n\t\t\t\t\t\t\t\t\t const std::string& to_city)const\n{\n\tstd::vector<std::string> union_to_city;\n\tboost::split(union_to_city,to_city,boost::is_any_of(\",\"));\n\n\tif(union_to_city.size() == 0)\n\t{\n\t\tunion_key.push_back(std::make_pair(from_city,\"\"));\n\t\treturn;\n\t}\n\n\tfor(size_t i = 0;i<union_to_city.size();i++)\n\t{\n\t\t\/\/ps:from city:上海 to city:上海,马累,马尔代夫 \n\t\t\/\/so we should remove key pair(上海,上海)\n\t\tif(union_to_city[i].empty()) continue;\n\t\tif(union_to_city.size() >= 2)\n\t\t{\n\t\t\tif(from_city == union_to_city[i]) continue;\n\t\t}\n\t\tunion_key.push_back(std::make_pair(from_city,union_to_city[i]));\n\t}\n\n\tif(union_key.size()==0)\n\t{\n\t\tunion_key.push_back(std::make_pair(from_city,from_city));\n\t}\n\n\t\/\/sort key vector\n\tstd::sort(union_key.union_key_.begin(),union_key.union_key_.end());\n}\n\nvoid TourProcessor::Finish_()\n{\n LOG(INFO)<<\"buffer size \"<<buffer_.size()<<std::endl;\n std::string odir = m_+\"\/b5mo\";\n std::string pdir = m_+\"\/b5mp\";\n boost::filesystem::create_directories(odir);\n boost::filesystem::create_directories(pdir);\n ScdWriter owriter(odir, UPDATE_SCD);\n ScdWriter pwriter(pdir, UPDATE_SCD);\n for(Buffer::iterator it = buffer_.begin();it!=buffer_.end();++it)\n {\n const UnionBufferKey& key = it->first;\n BufferValue& value = it->second;\n#ifdef TOUR_DEBUG\n\t LOG(INFO) << \"1---->processing:\"; \t\n\t\tfor(size_t i = 0; i<key.size();i++)\n\t\t{\n\t\t\tLOG(INFO) << key[i].first << \",\" << key[i].second << \"\t\";\n\t\t}\n\t\tLOG(INFO) << value.size() << std::endl;\n#endif\n std::sort(value.begin(), value.end());\n std::vector<Group> groups;\n for(uint32_t i=0;i<value.size();i++)\n {\n const BufferValueItem& vi = value[i];\n#ifdef TOUR_DEBUG\n LOG(INFO)<<\"find value item \"<<vi.from<<\",\"<<vi.to<<\",[\"<<vi.days.first<<\",\"<<vi.days.second<<\"],\"<<vi.price<<\",\"<<vi.bcluster<<std::endl;\n#endif\n Group* find_group = NULL;\n for(uint32_t j=0;j<groups.size();j++)\n {\n Group& g = groups[j];\n if(!g.front().bcluster) continue;\n \/\/compare vi with g;\n std::pair<uint32_t, uint32_t> g_mindays = g.front().days;\n if(vi.days.first>g_mindays.second&&vi.days.first-g_mindays.second>1) continue;\n \/\/if(vi.days-g_mindays>1) continue;\n \/\/double avg_price = 0.0;\n \/\/for(uint32_t k=0;k<g.size();k++)\n \/\/{\n \/\/ avg_price += g[k].price;\n \/\/}\n \/\/avg_price\/=g.size();\n \/\/double p_ratio = std::max(vi.price, avg_price)\/std::min(vi.price, avg_price);\n \/\/if(p_ratio>1.5) continue;\n find_group = &g;\n }\n\n if(find_group==NULL)\n {\n Group g;\n g.push_back(vi);\n groups.push_back(g);\n#ifdef TOUR_DEBUG\n LOG(INFO)<<\"create new group\"<<std::endl;\n#endif\n }\n else\n {\n find_group->push_back(vi);\n }\n }\n for(uint32_t i=0;i<groups.size();i++)\n {\n Group& g = groups[i];\n std::string pid;\n g.front().doc.getString(\"DOCID\", pid);\n for(uint32_t j=0;j<g.size();j++)\n {\n BufferValueItem& vi = g[j];\n vi.doc.property(\"uuid\") = str_to_propstr(pid);\n owriter.Append(vi.doc);\n }\n Document pdoc;\n GenP_(g, pdoc);\n pwriter.Append(pdoc);\n }\n }\n owriter.Close();\n pwriter.Close();\n}\n\nvoid TourProcessor::GenP_(Group& g, Document& doc) const\n{\n\tassert(g.size() >= 1);\n\tdoc = g[0].doc;\n\tdoc.eraseProperty(\"uuid\");\n\tstd::string price;\n\tstd::string p_docid;\n Set source_set;\n\tdouble min_price = g[0].price;\n\tdouble max_price = g[0].price;\n\t\/\/get first doc uuid as pid\n\tg[0].doc.getString(SCD_UUID,p_docid);\n\t\/\/set docid default use first docid\n\tdoc.property(SCD_DOC_ID) = str_to_propstr(p_docid);\n\tfor(std::size_t i=0;i<g.size();i++)\n\t{\n\t\tScdDocument& doc_ref = g[i].doc;\n\t\t\/\/get source list\n std::string source;\n\t\tdoc_ref.getString(SCD_SOURCE,source);\n\t\tif(!source.empty()) source_set.insert(source); \n\t\t\/\/get price range\n\t\tmin_price = std::min(min_price,g[i].price);\n\t\tmax_price = std::max(max_price,g[i].price);\n\t\t\/\/maybe some other rules TODO........\n\t}\n\n\t\/\/generate p <source>\n std::string source;\n\tfor(Set::const_iterator it = source_set.begin();it!=source_set.end();++it)\n\t{\n\t if(!source.empty()) source+=\",\";\n\t\tsource += *it;\n\t}\n\tdoc.property(SCD_SOURCE)=str_to_propstr(source);\n\n\t\/\/generate p <price>\n\tstd::stringstream ss;\n\tif(min_price < max_price)\n\t{\n\t\tss << min_price << '-'<< max_price;\n\t}\n\telse\n\t{\n\t\tassert(min_price == max_price);\n\t\tss << min_price;\n\t}\n\tss >> price;\n\tdoc.property(SCD_PRICE) = str_to_propstr(price);\n\tdoc.property(\"itemcount\") = (int64_t)(g.size());\n\t\/\/may have other attribute to set property todo......\n\t\/\/\n\t\/\/\n}\n<commit_msg>fix bug:split() generate messy code<commit_after>#include \"tour_processor.h\"\n#include \"b5m_types.h\"\n#include \"b5m_helper.h\"\n#include \"scd_doc_processor.h\"\n#include <boost\/algorithm\/string.hpp>\n#include <glog\/logging.h>\n#include <common\/ScdParser.h>\n#include <document-manager\/ScdDocument.h>\n#include <assert.h>\n\n\/\/#define TOUR_DEBUG\n\nusing namespace sf1r;\n\nTourProcessor::TourProcessor()\n{\n}\n\nTourProcessor::~TourProcessor()\n{\n}\n\nbool TourProcessor::Generate(const std::string& scd_path, const std::string& mdb_instance)\n{\n\t\/\/scan all the *.scd\n m_ = mdb_instance;\n ScdDocProcessor::ProcessorType p = boost::bind(&TourProcessor::Insert_, this, _1);\n int thread_num = 1;\n ScdDocProcessor sd_processor(p, thread_num);\n sd_processor.AddInput(scd_path);\n sd_processor.Process();\n Finish_();\n\treturn true;\n}\n\nvoid TourProcessor::Insert_(ScdDocument& doc)\n{\n\tstd::string sdays;\n\tstd::string price;\n\tBufferValueItem value;\n doc.getString(SCD_FROM_CITY, value.from);\n doc.getString(SCD_TO_CITY, value.to);\n\tdoc.getString(SCD_PRICE,price);\n doc.getString(SCD_TIME_PLAN, sdays);\n value.days = ParseDays_(sdays);\n value.doc = doc;\n value.price = 0.0;\n try {\n value.price = boost::lexical_cast<double>(price);\n }\n catch(std::exception& ex)\n {\n std::cerr<<\"parse tour price error for \"<< price<<std::endl;\n }\n value.bcluster = true;\n if(value.days.second==0||value.price==0.0||value.from.empty()||value.to.empty()) value.bcluster = false;\n \n\t\/\/generate union key by to_city\n\tUnionBufferKey union_key;\n\tGenerateUnionKey(union_key,value.from,value.to);\n\t\/\/BufferKey key(value.from, value.to);\n boost::unique_lock<boost::mutex> lock(mutex_);\n buffer_[union_key].push_back(value);\n}\n\nstd::pair<uint32_t, uint32_t> TourProcessor::ParseDays_(const std::string& sdays) const\n{\n \/\/find \"天\" Ps:4-7天\/8天\n std::pair<uint32_t, uint32_t> r(0,0);\n\tsize_t pos = sdays.find(\"天\");\n\tif(pos == std::string::npos)\n\t{\n\t\tpos = sdays.length();\n\t}\n\t\n\tstd::string tmp_days = sdays.substr(0,pos);\n\t\/\/find '-'\n\tpos = tmp_days.find('-');\n\tif(pos == std::string::npos)\n\t{\n\t\tr.first = atoi(tmp_days.c_str());\n\t\tr.second = r.first;\n\t}\n\telse\n\t{\n\t\tint min_days = atoi(tmp_days.substr(0,pos).c_str());\n\t\tint max_days = atoi(tmp_days.substr(pos+1).c_str());\n\t\tr.first = min_days;\n\t\tr.second = max_days;\n\t}\n\treturn r;\n}\n\nvoid TourProcessor::GenerateUnionKey(UnionBufferKey& union_key,\n\t\t\t\t\t\t\t\t\t const std::string& from_city,\n\t\t\t\t\t\t\t\t\t const std::string& to_city)const\n{\n\tstd::vector<std::string> union_to_city;\n\tboost::split(union_to_city,to_city,boost::is_any_of(\",\"));\n\n\tif(union_to_city.size() == 0)\n\t{\n\t\tunion_key.push_back(std::make_pair(from_city,\"\"));\n\t\treturn;\n\t}\n\n\tfor(size_t i = 0;i<union_to_city.size();i++)\n\t{\n\t\t\/\/ps:from city:上海 to city:上海,马累,马尔代夫 \n\t\t\/\/so we should remove key pair(上海,上海)\n\t\tif(union_to_city[i].empty()) continue;\n\t\tif(union_to_city.size() >= 2)\n\t\t{\n\t\t\tif(from_city == union_to_city[i]) continue;\n\t\t}\n\t\tunion_key.push_back(std::make_pair(from_city,union_to_city[i]));\n\t}\n\n\tif(union_key.size()==0)\n\t{\n\t\tunion_key.push_back(std::make_pair(from_city,from_city));\n\t}\n\n\t\/\/sort key vector\n\tstd::sort(union_key.union_key_.begin(),union_key.union_key_.end());\n}\n\nvoid TourProcessor::Finish_()\n{\n LOG(INFO)<<\"buffer size \"<<buffer_.size()<<std::endl;\n std::string odir = m_+\"\/b5mo\";\n std::string pdir = m_+\"\/b5mp\";\n boost::filesystem::create_directories(odir);\n boost::filesystem::create_directories(pdir);\n\tScdWriter owriter(odir, UPDATE_SCD);\n ScdWriter pwriter(pdir, UPDATE_SCD);\n for(Buffer::iterator it = buffer_.begin();it!=buffer_.end();++it)\n {\n const UnionBufferKey& key = it->first;\n BufferValue& value = it->second;\n#ifdef TOUR_DEBUG\n\t\tLOG(INFO) << \"1---->processing:\";\n\t\tfor(size_t i = 0; i<key.union_key_.size();i++)\n\t\t{\n\t\t\tLOG(INFO) << key.union_key_[i].first << \",\" << key.union_key_[i].second << \"\t\";\n\t\t}\n\t\tLOG(INFO) << \"aggregate count:\" << value.size();\n#endif\n std::sort(value.begin(), value.end());\n std::vector<Group> groups;\n for(uint32_t i=0;i<value.size();i++)\n {\n const BufferValueItem& vi = value[i];\n#ifdef TOUR_DEBUG\n LOG(INFO)<<\"find value item \"<<vi.from<<\",\"<<vi.to<<\",[\"<<vi.days.first<<\",\"<<vi.days.second<<\"],\"<<vi.price<<\",\"<<vi.bcluster<<std::endl;\n#endif\n Group* find_group = NULL;\n for(uint32_t j=0;j<groups.size();j++)\n {\n Group& g = groups[j];\n if(!g.front().bcluster) continue;\n \/\/compare vi with g;\n std::pair<uint32_t, uint32_t> g_mindays = g.front().days;\n if(vi.days.first>g_mindays.second&&vi.days.first-g_mindays.second>1) continue;\n \/\/if(vi.days-g_mindays>1) continue;\n \/\/double avg_price = 0.0;\n \/\/for(uint32_t k=0;k<g.size();k++)\n \/\/{\n \/\/ avg_price += g[k].price;\n \/\/}\n \/\/avg_price\/=g.size();\n \/\/double p_ratio = std::max(vi.price, avg_price)\/std::min(vi.price, avg_price);\n \/\/if(p_ratio>1.5) continue;\n find_group = &g;\n }\n\n if(find_group==NULL)\n {\n Group g;\n g.push_back(vi);\n groups.push_back(g);\n#ifdef TOUR_DEBUG\n LOG(INFO)<<\"create new group\"<<std::endl;\n#endif\n }\n else\n {\n find_group->push_back(vi);\n }\n }\n for(uint32_t i=0;i<groups.size();i++)\n {\n Group& g = groups[i];\n std::string pid;\n g.front().doc.getString(\"DOCID\", pid);\n for(uint32_t j=0;j<g.size();j++)\n {\n BufferValueItem& vi = g[j];\n vi.doc.property(\"uuid\") = str_to_propstr(pid);\n owriter.Append(vi.doc);\n }\n Document pdoc;\n GenP_(g, pdoc);\n pwriter.Append(pdoc);\n }\n }\n owriter.Close();\n pwriter.Close();\n}\n\nvoid TourProcessor::GenP_(Group& g, Document& doc) const\n{\n\tassert(g.size() >= 1);\n\tdoc = g[0].doc;\n\tdoc.eraseProperty(\"uuid\");\n\tstd::string price;\n\tstd::string p_docid;\n Set source_set;\n\tdouble min_price = g[0].price;\n\tdouble max_price = g[0].price;\n\t\/\/get first doc uuid as pid\n\tg[0].doc.getString(SCD_UUID,p_docid);\n\t\/\/set docid default use first docid\n\tdoc.property(SCD_DOC_ID) = str_to_propstr(p_docid);\n\tfor(std::size_t i=0;i<g.size();i++)\n\t{\n\t\tScdDocument& doc_ref = g[i].doc;\n\t\t\/\/get source list\n std::string source;\n\t\tdoc_ref.getString(SCD_SOURCE,source);\n\t\tif(!source.empty()) source_set.insert(source); \n\t\t\/\/get price range\n\t\tmin_price = std::min(min_price,g[i].price);\n\t\tmax_price = std::max(max_price,g[i].price);\n\t\t\/\/maybe some other rules TODO........\n\t}\n\n\t\/\/generate p <source>\n std::string source;\n\tfor(Set::const_iterator it = source_set.begin();it!=source_set.end();++it)\n\t{\n\t if(!source.empty()) source+=\",\";\n\t\tsource += *it;\n\t}\n\tdoc.property(SCD_SOURCE)=str_to_propstr(source);\n\n\t\/\/generate p <price>\n\tstd::stringstream ss;\n\tif(min_price < max_price)\n\t{\n\t\tss << min_price << '-'<< max_price;\n\t}\n\telse\n\t{\n\t\tassert(min_price == max_price);\n\t\tss << min_price;\n\t}\n\tss >> price;\n\tdoc.property(SCD_PRICE) = str_to_propstr(price);\n\tdoc.property(\"itemcount\") = (int64_t)(g.size());\n\t\/\/may have other attribute to set property todo......\n\t\/\/\n\t\/\/\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/\r\n\/\/ PROJECT: Aspia Remote Desktop\r\n\/\/ FILE: host\/host_session_file_transfer.cc\r\n\/\/ LICENSE: Mozilla Public License Version 2.0\r\n\/\/ PROGRAMMERS: Dmitry Chapyshev (dmitry@aspia.ru)\r\n\/\/\r\n\r\n#include \"host\/host_session_file_transfer.h\"\r\n#include \"base\/files\/file_helpers.h\"\r\n#include \"base\/files\/file_util.h\"\r\n#include \"ipc\/pipe_channel_proxy.h\"\r\n#include \"protocol\/message_serialization.h\"\r\n#include \"protocol\/filesystem.h\"\r\n#include \"proto\/auth_session.pb.h\"\r\n\r\nnamespace aspia {\r\n\r\nvoid HostSessionFileTransfer::Run(const std::wstring& channel_id)\r\n{\r\n status_dialog_ = std::make_unique<FileStatusDialog>();\r\n\r\n ipc_channel_ = PipeChannel::CreateClient(channel_id);\r\n if (ipc_channel_)\r\n {\r\n ipc_channel_proxy_ = ipc_channel_->pipe_channel_proxy();\r\n\r\n uint32_t user_data = GetCurrentProcessId();\r\n\r\n PipeChannel::DisconnectHandler disconnect_handler =\r\n std::bind(&HostSessionFileTransfer::OnIpcChannelDisconnect, this);\r\n\r\n if (ipc_channel_->Connect(user_data, std::move(disconnect_handler)))\r\n {\r\n OnIpcChannelConnect(user_data);\r\n status_dialog_->WaitForClose();\r\n }\r\n\r\n ipc_channel_.reset();\r\n }\r\n\r\n status_dialog_.reset();\r\n}\r\n\r\nvoid HostSessionFileTransfer::OnIpcChannelConnect(uint32_t user_data)\r\n{\r\n \/\/ The server sends the session type in user_data.\r\n proto::SessionType session_type =\r\n static_cast<proto::SessionType>(user_data);\r\n\r\n if (session_type != proto::SESSION_TYPE_FILE_TRANSFER)\r\n {\r\n LOG(FATAL) << \"Invalid session type passed: \" << session_type;\r\n return;\r\n }\r\n\r\n status_dialog_->OnSessionStarted();\r\n\r\n ipc_channel_proxy_->Receive(std::bind(\r\n &HostSessionFileTransfer::OnIpcChannelMessage, this, std::placeholders::_1));\r\n}\r\n\r\nvoid HostSessionFileTransfer::OnIpcChannelDisconnect()\r\n{\r\n status_dialog_->OnSessionTerminated();\r\n}\r\n\r\nvoid HostSessionFileTransfer::OnIpcChannelMessage(const IOBuffer& buffer)\r\n{\r\n proto::file_transfer::ClientToHost message;\r\n\r\n if (!ParseMessage(buffer, message))\r\n {\r\n ipc_channel_proxy_->Disconnect();\r\n return;\r\n }\r\n\r\n if (message.has_drive_list_request())\r\n {\r\n ReadDriveListRequest();\r\n }\r\n else if (message.has_file_list_request())\r\n {\r\n ReadFileListRequest(message.file_list_request());\r\n }\r\n else if (message.has_directory_size_request())\r\n {\r\n ReadDirectorySizeRequest(message.directory_size_request());\r\n }\r\n else if (message.has_create_directory_request())\r\n {\r\n ReadCreateDirectoryRequest(message.create_directory_request());\r\n }\r\n else if (message.has_rename_request())\r\n {\r\n ReadRenameRequest(message.rename_request());\r\n }\r\n else if (message.has_remove_request())\r\n {\r\n ReadRemoveRequest(message.remove_request());\r\n }\r\n else if (message.has_file_upload_request())\r\n {\r\n ReadFileUploadRequest(message.file_upload_request());\r\n }\r\n else if (message.has_file_packet())\r\n {\r\n if (!ReadFilePacket(message.file_packet()))\r\n ipc_channel_proxy_->Disconnect();\r\n }\r\n else if (message.has_file_download_request())\r\n {\r\n ReadFileDownloadRequest(message.file_download_request());\r\n }\r\n else if (message.has_file_packet_request())\r\n {\r\n if (!ReadFilePacketRequest())\r\n ipc_channel_proxy_->Disconnect();\r\n }\r\n else\r\n {\r\n LOG(ERROR) << \"Unknown message from client\";\r\n ipc_channel_proxy_->Disconnect();\r\n }\r\n}\r\n\r\nvoid HostSessionFileTransfer::SendReply(const proto::file_transfer::HostToClient& reply)\r\n{\r\n ipc_channel_proxy_->Send(\r\n SerializeMessage<IOBuffer>(reply),\r\n std::bind(&HostSessionFileTransfer::OnReplySended, this));\r\n}\r\n\r\nvoid HostSessionFileTransfer::OnReplySended()\r\n{\r\n \/\/ Receive next request.\r\n ipc_channel_proxy_->Receive(std::bind(\r\n &HostSessionFileTransfer::OnIpcChannelMessage, this, std::placeholders::_1));\r\n}\r\n\r\nvoid HostSessionFileTransfer::ReadDriveListRequest()\r\n{\r\n proto::file_transfer::HostToClient reply;\r\n reply.set_status(ExecuteDriveListRequest(reply.mutable_drive_list()));\r\n\r\n if (reply.status() == proto::REQUEST_STATUS_SUCCESS)\r\n {\r\n status_dialog_->OnDriveListRequest();\r\n }\r\n\r\n SendReply(reply);\r\n}\r\n\r\nvoid HostSessionFileTransfer::ReadFileListRequest(const proto::FileListRequest& request)\r\n{\r\n proto::file_transfer::HostToClient reply;\r\n\r\n FilePath path = std::experimental::filesystem::u8path(request.path());\r\n\r\n reply.set_status(ExecuteFileListRequest(path, reply.mutable_file_list()));\r\n\r\n if (reply.status() == proto::REQUEST_STATUS_SUCCESS)\r\n {\r\n status_dialog_->OnFileListRequest(path);\r\n }\r\n\r\n SendReply(reply);\r\n}\r\n\r\nvoid HostSessionFileTransfer::ReadCreateDirectoryRequest(\r\n const proto::CreateDirectoryRequest& request)\r\n{\r\n proto::file_transfer::HostToClient reply;\r\n\r\n FilePath path = std::experimental::filesystem::u8path(request.path());\r\n\r\n reply.set_status(ExecuteCreateDirectoryRequest(path));\r\n\r\n if (reply.status() == proto::REQUEST_STATUS_SUCCESS)\r\n {\r\n status_dialog_->OnCreateDirectoryRequest(path);\r\n }\r\n\r\n SendReply(reply);\r\n}\r\n\r\nvoid HostSessionFileTransfer::ReadDirectorySizeRequest(const proto::DirectorySizeRequest& request)\r\n{\r\n proto::file_transfer::HostToClient reply;\r\n\r\n FilePath path = std::experimental::filesystem::u8path(request.path());\r\n\r\n uint64_t directory_size = 0;\r\n\r\n reply.set_status(ExecuteDirectorySizeRequest(path, directory_size));\r\n reply.mutable_directory_size()->set_size(directory_size);\r\n\r\n SendReply(reply);\r\n}\r\n\r\nvoid HostSessionFileTransfer::ReadRenameRequest(const proto::RenameRequest& request)\r\n{\r\n proto::file_transfer::HostToClient reply;\r\n\r\n FilePath old_name = std::experimental::filesystem::u8path(request.old_name());\r\n FilePath new_name = std::experimental::filesystem::u8path(request.new_name());\r\n\r\n reply.set_status(ExecuteRenameRequest(old_name, new_name));\r\n\r\n if (reply.status() == proto::REQUEST_STATUS_SUCCESS)\r\n {\r\n status_dialog_->OnRenameRequest(old_name, new_name);\r\n }\r\n\r\n SendReply(reply);\r\n}\r\n\r\nvoid HostSessionFileTransfer::ReadRemoveRequest(const proto::RemoveRequest& request)\r\n{\r\n proto::file_transfer::HostToClient reply;\r\n\r\n FilePath path = std::experimental::filesystem::u8path(request.path());\r\n\r\n reply.set_status(ExecuteRemoveRequest(path));\r\n\r\n if (reply.status() == proto::REQUEST_STATUS_SUCCESS)\r\n {\r\n status_dialog_->OnRemoveRequest(path);\r\n }\r\n\r\n SendReply(reply);\r\n}\r\n\r\nvoid HostSessionFileTransfer::ReadFileUploadRequest(const proto::FileUploadRequest& request)\r\n{\r\n proto::file_transfer::HostToClient reply;\r\n\r\n FilePath file_path = std::experimental::filesystem::u8path(request.file_path());\r\n\r\n do\r\n {\r\n if (!IsValidPathName(file_path))\r\n {\r\n reply.set_status(proto::REQUEST_STATUS_INVALID_PATH_NAME);\r\n break;\r\n }\r\n\r\n if (!request.overwrite())\r\n {\r\n if (PathExists(file_path))\r\n {\r\n reply.set_status(proto::REQUEST_STATUS_PATH_ALREADY_EXISTS);\r\n break;\r\n }\r\n }\r\n\r\n file_depacketizer_ = FileDepacketizer::Create(file_path, request.overwrite());\r\n if (!file_depacketizer_)\r\n {\r\n reply.set_status(proto::REQUEST_STATUS_FILE_CREATE_ERROR);\r\n break;\r\n }\r\n\r\n reply.set_status(proto::REQUEST_STATUS_SUCCESS);\r\n }\r\n while (false);\r\n\r\n if (reply.status() == proto::REQUEST_STATUS_SUCCESS)\r\n {\r\n status_dialog_->OnFileUploadRequest(file_path);\r\n }\r\n\r\n SendReply(reply);\r\n}\r\n\r\nbool HostSessionFileTransfer::ReadFilePacket(const proto::FilePacket& file_packet)\r\n{\r\n if (!file_depacketizer_)\r\n {\r\n LOG(ERROR) << \"Unexpected file packet\";\r\n return false;\r\n }\r\n\r\n proto::file_transfer::HostToClient reply;\r\n\r\n if (!file_depacketizer_->ReadNextPacket(file_packet))\r\n {\r\n reply.set_status(proto::REQUEST_STATUS_FILE_WRITE_ERROR);\r\n }\r\n else\r\n {\r\n reply.set_status(proto::REQUEST_STATUS_SUCCESS);\r\n }\r\n\r\n if (file_packet.flags() & proto::FilePacket::LAST_PACKET)\r\n {\r\n file_depacketizer_.reset();\r\n }\r\n\r\n SendReply(reply);\r\n return true;\r\n}\r\n\r\nvoid HostSessionFileTransfer::ReadFileDownloadRequest(const proto::FileDownloadRequest& request)\r\n{\r\n proto::file_transfer::HostToClient reply;\r\n\r\n FilePath file_path = std::experimental::filesystem::u8path(request.file_path());\r\n\r\n if (!IsValidPathName(file_path))\r\n {\r\n reply.set_status(proto::REQUEST_STATUS_INVALID_PATH_NAME);\r\n }\r\n else\r\n {\r\n file_packetizer_ = FilePacketizer::Create(file_path);\r\n if (!file_packetizer_)\r\n {\r\n reply.set_status(proto::REQUEST_STATUS_FILE_OPEN_ERROR);\r\n }\r\n else\r\n {\r\n reply.set_status(proto::REQUEST_STATUS_SUCCESS);\r\n }\r\n }\r\n\r\n SendReply(reply);\r\n}\r\n\r\nbool HostSessionFileTransfer::ReadFilePacketRequest()\r\n{\r\n if (!file_packetizer_)\r\n {\r\n LOG(ERROR) << \"Unexpected download data request\";\r\n return false;\r\n }\r\n\r\n proto::file_transfer::HostToClient reply;\r\n\r\n std::unique_ptr<proto::FilePacket> packet = file_packetizer_->CreateNextPacket();\r\n if (!packet)\r\n {\r\n reply.set_status(proto::REQUEST_STATUS_FILE_READ_ERROR);\r\n }\r\n else\r\n {\r\n if (packet->flags() & proto::FilePacket::LAST_PACKET)\r\n {\r\n file_packetizer_.reset();\r\n }\r\n\r\n reply.set_status(proto::REQUEST_STATUS_SUCCESS);\r\n reply.set_allocated_file_packet(packet.release());\r\n }\r\n\r\n SendReply(reply);\r\n return true;\r\n}\r\n\r\n} \/\/ namespace aspia\r\n<commit_msg>- Using Process class to get process id.<commit_after>\/\/\r\n\/\/ PROJECT: Aspia Remote Desktop\r\n\/\/ FILE: host\/host_session_file_transfer.cc\r\n\/\/ LICENSE: Mozilla Public License Version 2.0\r\n\/\/ PROGRAMMERS: Dmitry Chapyshev (dmitry@aspia.ru)\r\n\/\/\r\n\r\n#include \"host\/host_session_file_transfer.h\"\r\n#include \"base\/files\/file_helpers.h\"\r\n#include \"base\/files\/file_util.h\"\r\n#include \"base\/process\/process.h\"\r\n#include \"ipc\/pipe_channel_proxy.h\"\r\n#include \"protocol\/message_serialization.h\"\r\n#include \"protocol\/filesystem.h\"\r\n#include \"proto\/auth_session.pb.h\"\r\n\r\nnamespace aspia {\r\n\r\nvoid HostSessionFileTransfer::Run(const std::wstring& channel_id)\r\n{\r\n status_dialog_ = std::make_unique<FileStatusDialog>();\r\n\r\n ipc_channel_ = PipeChannel::CreateClient(channel_id);\r\n if (ipc_channel_)\r\n {\r\n ipc_channel_proxy_ = ipc_channel_->pipe_channel_proxy();\r\n\r\n uint32_t user_data = Process::Current().Pid();\r\n\r\n PipeChannel::DisconnectHandler disconnect_handler =\r\n std::bind(&HostSessionFileTransfer::OnIpcChannelDisconnect, this);\r\n\r\n if (ipc_channel_->Connect(user_data, std::move(disconnect_handler)))\r\n {\r\n OnIpcChannelConnect(user_data);\r\n status_dialog_->WaitForClose();\r\n }\r\n\r\n ipc_channel_.reset();\r\n }\r\n\r\n status_dialog_.reset();\r\n}\r\n\r\nvoid HostSessionFileTransfer::OnIpcChannelConnect(uint32_t user_data)\r\n{\r\n \/\/ The server sends the session type in user_data.\r\n proto::SessionType session_type =\r\n static_cast<proto::SessionType>(user_data);\r\n\r\n if (session_type != proto::SESSION_TYPE_FILE_TRANSFER)\r\n {\r\n LOG(FATAL) << \"Invalid session type passed: \" << session_type;\r\n return;\r\n }\r\n\r\n status_dialog_->OnSessionStarted();\r\n\r\n ipc_channel_proxy_->Receive(std::bind(\r\n &HostSessionFileTransfer::OnIpcChannelMessage, this, std::placeholders::_1));\r\n}\r\n\r\nvoid HostSessionFileTransfer::OnIpcChannelDisconnect()\r\n{\r\n status_dialog_->OnSessionTerminated();\r\n}\r\n\r\nvoid HostSessionFileTransfer::OnIpcChannelMessage(const IOBuffer& buffer)\r\n{\r\n proto::file_transfer::ClientToHost message;\r\n\r\n if (!ParseMessage(buffer, message))\r\n {\r\n ipc_channel_proxy_->Disconnect();\r\n return;\r\n }\r\n\r\n if (message.has_drive_list_request())\r\n {\r\n ReadDriveListRequest();\r\n }\r\n else if (message.has_file_list_request())\r\n {\r\n ReadFileListRequest(message.file_list_request());\r\n }\r\n else if (message.has_directory_size_request())\r\n {\r\n ReadDirectorySizeRequest(message.directory_size_request());\r\n }\r\n else if (message.has_create_directory_request())\r\n {\r\n ReadCreateDirectoryRequest(message.create_directory_request());\r\n }\r\n else if (message.has_rename_request())\r\n {\r\n ReadRenameRequest(message.rename_request());\r\n }\r\n else if (message.has_remove_request())\r\n {\r\n ReadRemoveRequest(message.remove_request());\r\n }\r\n else if (message.has_file_upload_request())\r\n {\r\n ReadFileUploadRequest(message.file_upload_request());\r\n }\r\n else if (message.has_file_packet())\r\n {\r\n if (!ReadFilePacket(message.file_packet()))\r\n ipc_channel_proxy_->Disconnect();\r\n }\r\n else if (message.has_file_download_request())\r\n {\r\n ReadFileDownloadRequest(message.file_download_request());\r\n }\r\n else if (message.has_file_packet_request())\r\n {\r\n if (!ReadFilePacketRequest())\r\n ipc_channel_proxy_->Disconnect();\r\n }\r\n else\r\n {\r\n LOG(ERROR) << \"Unknown message from client\";\r\n ipc_channel_proxy_->Disconnect();\r\n }\r\n}\r\n\r\nvoid HostSessionFileTransfer::SendReply(const proto::file_transfer::HostToClient& reply)\r\n{\r\n ipc_channel_proxy_->Send(\r\n SerializeMessage<IOBuffer>(reply),\r\n std::bind(&HostSessionFileTransfer::OnReplySended, this));\r\n}\r\n\r\nvoid HostSessionFileTransfer::OnReplySended()\r\n{\r\n \/\/ Receive next request.\r\n ipc_channel_proxy_->Receive(std::bind(\r\n &HostSessionFileTransfer::OnIpcChannelMessage, this, std::placeholders::_1));\r\n}\r\n\r\nvoid HostSessionFileTransfer::ReadDriveListRequest()\r\n{\r\n proto::file_transfer::HostToClient reply;\r\n reply.set_status(ExecuteDriveListRequest(reply.mutable_drive_list()));\r\n\r\n if (reply.status() == proto::REQUEST_STATUS_SUCCESS)\r\n {\r\n status_dialog_->OnDriveListRequest();\r\n }\r\n\r\n SendReply(reply);\r\n}\r\n\r\nvoid HostSessionFileTransfer::ReadFileListRequest(const proto::FileListRequest& request)\r\n{\r\n proto::file_transfer::HostToClient reply;\r\n\r\n FilePath path = std::experimental::filesystem::u8path(request.path());\r\n\r\n reply.set_status(ExecuteFileListRequest(path, reply.mutable_file_list()));\r\n\r\n if (reply.status() == proto::REQUEST_STATUS_SUCCESS)\r\n {\r\n status_dialog_->OnFileListRequest(path);\r\n }\r\n\r\n SendReply(reply);\r\n}\r\n\r\nvoid HostSessionFileTransfer::ReadCreateDirectoryRequest(\r\n const proto::CreateDirectoryRequest& request)\r\n{\r\n proto::file_transfer::HostToClient reply;\r\n\r\n FilePath path = std::experimental::filesystem::u8path(request.path());\r\n\r\n reply.set_status(ExecuteCreateDirectoryRequest(path));\r\n\r\n if (reply.status() == proto::REQUEST_STATUS_SUCCESS)\r\n {\r\n status_dialog_->OnCreateDirectoryRequest(path);\r\n }\r\n\r\n SendReply(reply);\r\n}\r\n\r\nvoid HostSessionFileTransfer::ReadDirectorySizeRequest(const proto::DirectorySizeRequest& request)\r\n{\r\n proto::file_transfer::HostToClient reply;\r\n\r\n FilePath path = std::experimental::filesystem::u8path(request.path());\r\n\r\n uint64_t directory_size = 0;\r\n\r\n reply.set_status(ExecuteDirectorySizeRequest(path, directory_size));\r\n reply.mutable_directory_size()->set_size(directory_size);\r\n\r\n SendReply(reply);\r\n}\r\n\r\nvoid HostSessionFileTransfer::ReadRenameRequest(const proto::RenameRequest& request)\r\n{\r\n proto::file_transfer::HostToClient reply;\r\n\r\n FilePath old_name = std::experimental::filesystem::u8path(request.old_name());\r\n FilePath new_name = std::experimental::filesystem::u8path(request.new_name());\r\n\r\n reply.set_status(ExecuteRenameRequest(old_name, new_name));\r\n\r\n if (reply.status() == proto::REQUEST_STATUS_SUCCESS)\r\n {\r\n status_dialog_->OnRenameRequest(old_name, new_name);\r\n }\r\n\r\n SendReply(reply);\r\n}\r\n\r\nvoid HostSessionFileTransfer::ReadRemoveRequest(const proto::RemoveRequest& request)\r\n{\r\n proto::file_transfer::HostToClient reply;\r\n\r\n FilePath path = std::experimental::filesystem::u8path(request.path());\r\n\r\n reply.set_status(ExecuteRemoveRequest(path));\r\n\r\n if (reply.status() == proto::REQUEST_STATUS_SUCCESS)\r\n {\r\n status_dialog_->OnRemoveRequest(path);\r\n }\r\n\r\n SendReply(reply);\r\n}\r\n\r\nvoid HostSessionFileTransfer::ReadFileUploadRequest(const proto::FileUploadRequest& request)\r\n{\r\n proto::file_transfer::HostToClient reply;\r\n\r\n FilePath file_path = std::experimental::filesystem::u8path(request.file_path());\r\n\r\n do\r\n {\r\n if (!IsValidPathName(file_path))\r\n {\r\n reply.set_status(proto::REQUEST_STATUS_INVALID_PATH_NAME);\r\n break;\r\n }\r\n\r\n if (!request.overwrite())\r\n {\r\n if (PathExists(file_path))\r\n {\r\n reply.set_status(proto::REQUEST_STATUS_PATH_ALREADY_EXISTS);\r\n break;\r\n }\r\n }\r\n\r\n file_depacketizer_ = FileDepacketizer::Create(file_path, request.overwrite());\r\n if (!file_depacketizer_)\r\n {\r\n reply.set_status(proto::REQUEST_STATUS_FILE_CREATE_ERROR);\r\n break;\r\n }\r\n\r\n reply.set_status(proto::REQUEST_STATUS_SUCCESS);\r\n }\r\n while (false);\r\n\r\n if (reply.status() == proto::REQUEST_STATUS_SUCCESS)\r\n {\r\n status_dialog_->OnFileUploadRequest(file_path);\r\n }\r\n\r\n SendReply(reply);\r\n}\r\n\r\nbool HostSessionFileTransfer::ReadFilePacket(const proto::FilePacket& file_packet)\r\n{\r\n if (!file_depacketizer_)\r\n {\r\n LOG(ERROR) << \"Unexpected file packet\";\r\n return false;\r\n }\r\n\r\n proto::file_transfer::HostToClient reply;\r\n\r\n if (!file_depacketizer_->ReadNextPacket(file_packet))\r\n {\r\n reply.set_status(proto::REQUEST_STATUS_FILE_WRITE_ERROR);\r\n }\r\n else\r\n {\r\n reply.set_status(proto::REQUEST_STATUS_SUCCESS);\r\n }\r\n\r\n if (file_packet.flags() & proto::FilePacket::LAST_PACKET)\r\n {\r\n file_depacketizer_.reset();\r\n }\r\n\r\n SendReply(reply);\r\n return true;\r\n}\r\n\r\nvoid HostSessionFileTransfer::ReadFileDownloadRequest(const proto::FileDownloadRequest& request)\r\n{\r\n proto::file_transfer::HostToClient reply;\r\n\r\n FilePath file_path = std::experimental::filesystem::u8path(request.file_path());\r\n\r\n if (!IsValidPathName(file_path))\r\n {\r\n reply.set_status(proto::REQUEST_STATUS_INVALID_PATH_NAME);\r\n }\r\n else\r\n {\r\n file_packetizer_ = FilePacketizer::Create(file_path);\r\n if (!file_packetizer_)\r\n {\r\n reply.set_status(proto::REQUEST_STATUS_FILE_OPEN_ERROR);\r\n }\r\n else\r\n {\r\n reply.set_status(proto::REQUEST_STATUS_SUCCESS);\r\n }\r\n }\r\n\r\n SendReply(reply);\r\n}\r\n\r\nbool HostSessionFileTransfer::ReadFilePacketRequest()\r\n{\r\n if (!file_packetizer_)\r\n {\r\n LOG(ERROR) << \"Unexpected download data request\";\r\n return false;\r\n }\r\n\r\n proto::file_transfer::HostToClient reply;\r\n\r\n std::unique_ptr<proto::FilePacket> packet = file_packetizer_->CreateNextPacket();\r\n if (!packet)\r\n {\r\n reply.set_status(proto::REQUEST_STATUS_FILE_READ_ERROR);\r\n }\r\n else\r\n {\r\n if (packet->flags() & proto::FilePacket::LAST_PACKET)\r\n {\r\n file_packetizer_.reset();\r\n }\r\n\r\n reply.set_status(proto::REQUEST_STATUS_SUCCESS);\r\n reply.set_allocated_file_packet(packet.release());\r\n }\r\n\r\n SendReply(reply);\r\n return true;\r\n}\r\n\r\n} \/\/ namespace aspia\r\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2016, Joseph Mirabel\n\/\/ Authors: Joseph Mirabel (joseph.mirabel@laas.fr)\n\/\/\n\/\/ This file is part of hpp-pinocchio.\n\/\/ hpp-pinocchio is free software: you can redistribute it\n\/\/ and\/or modify it under the terms of the GNU Lesser General Public\n\/\/ License as published by the Free Software Foundation, either version\n\/\/ 3 of the License, or (at your option) any later version.\n\/\/\n\/\/ hpp-pinocchio is distributed in the hope that it will be\n\/\/ useful, but WITHOUT ANY WARRANTY; without even the implied warranty\n\/\/ of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ General Lesser Public License for more details. You should have\n\/\/ received a copy of the GNU Lesser General Public License along with\n\/\/ hpp-pinocchio. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n\n#include <hpp\/pinocchio\/urdf\/util.hh>\n\n#include <urdf_parser\/urdf_parser.h>\n\n#include <hpp\/fcl\/mesh_loader\/loader.h>\n\n#include <pinocchio\/parsers\/utils.hpp>\n#include <pinocchio\/parsers\/urdf.hpp>\n#include <pinocchio\/multibody\/geometry.hpp>\n#include <pinocchio\/algorithm\/geometry.hpp>\n#include <pinocchio\/parsers\/srdf.hpp>\n\n#include <hpp\/util\/debug.hh>\n\n#include <hpp\/pinocchio\/joint.hh>\n#include <hpp\/pinocchio\/joint-collection.hh>\n#include <hpp\/pinocchio\/device.hh>\n#include <hpp\/pinocchio\/humanoid-robot.hh>\n\nnamespace hpp {\n namespace pinocchio {\n namespace urdf {\n namespace {\n#ifdef HPP_DEBUG\n const bool verbose = true;\n#else\n const bool verbose = false;\n#endif\n\n JointPtr_t findSpecialJoint (const HumanoidRobotPtr_t& robot, const std::string& linkName)\n {\n return robot->getJointByBodyName (linkName);\n }\n\n void setSpecialJoints (const HumanoidRobotPtr_t& robot, std::string prefix)\n {\n if (!prefix.empty() && *prefix.rbegin() != '\/') prefix += \"\/\";\n try {\n robot->waist (robot->getJointByName(prefix + \"root_joint\"));\n } catch (const std::exception&) {\n hppDout (notice, \"No waist joint found\");\n }\n try {\n robot->chest (findSpecialJoint (robot, prefix + \"chest\"));\n } catch (const std::exception&) {\n hppDout (notice, \"No chest joint found\");\n }\n try {\n robot->leftWrist (findSpecialJoint (robot, prefix + \"l_wrist\"));\n } catch (const std::exception&) {\n hppDout (notice, \"No left wrist joint found\");\n }\n try {\n robot->rightWrist (findSpecialJoint (robot, prefix + \"r_wrist\"));\n } catch (const std::exception&) {\n hppDout (notice, \"No right wrist joint found\");\n }\n try {\n robot->leftAnkle (findSpecialJoint (robot, prefix + \"l_ankle\"));\n } catch (const std::exception&) {\n hppDout (notice, \"No left ankle joint found\");\n }\n try {\n robot->rightAnkle (findSpecialJoint (robot, prefix + \"r_ankle\"));\n } catch (const std::exception&) {\n hppDout (notice, \"No right ankle joint found\");\n }\n try {\n robot->gazeJoint (findSpecialJoint (robot, prefix + \"gaze\"));\n } catch (const std::exception&) {\n hppDout (notice, \"No gaze joint found\");\n }\n }\n\n void fillGaze (const HumanoidRobotPtr_t robot)\n {\n vector3_t dir, origin;\n \/\/ Gaze direction is defined by the gaze joint local\n \/\/ orientation.\n dir[0] = 1;\n dir[1] = 0;\n dir[2] = 0;\n \/\/ Gaze position should is defined by the gaze joint local\n \/\/ origin.\n origin[0] = 0;\n origin[1] = 0;\n origin[2] = 0;\n robot->gaze (dir, origin);\n }\n\n JointModelVariant buildJoint (const std::string& type)\n {\n if (type == \"freeflyer\") return JointCollection::JointModelFreeFlyer();\n else if (type == \"planar\") return JointCollection::JointModelPlanar();\n else if (type == \"prismatic_x\") return JointCollection::JointModelPX();\n else if (type == \"prismatic_y\") return JointCollection::JointModelPY();\n else if (type == \"translation3d\") return JointCollection::JointModelTranslation();\n else throw std::invalid_argument\n (\"Root joint type \\\"\" + type + \"\\\" is currently not available.\");\n }\n\n void setPrefix (const std::string& prefix,\n Model& model, GeomModel& geomModel,\n const JointIndex& idFirstJoint,\n const FrameIndex& idFirstFrame)\n {\n for (JointIndex i = idFirstJoint; i < model.joints.size(); ++i) {\n model.names[i] = prefix + model.names[i];\n }\n for (FrameIndex i = idFirstFrame; i < model.frames.size(); ++i) {\n ::pinocchio::Frame& f = model.frames[i];\n f.name = prefix + f.name;\n }\n BOOST_FOREACH(::pinocchio::GeometryObject& go, geomModel.geometryObjects) {\n go.name = prefix + go.name;\n }\n }\n\n void setRootJointBounds(Model& model,\n const JointIndex& rtIdx,\n const std::string& rootType)\n {\n value_type b = std::numeric_limits<value_type>::infinity();\n if (rootType == \"freeflyer\") {\n const std::size_t idx = model.joints[rtIdx].idx_q();\n model.upperPositionLimit.segment<3>(idx).setConstant(+b);\n model.lowerPositionLimit.segment<3>(idx).setConstant(-b);\n \/\/ Quaternion bounds\n b = 1.01;\n const size_type quat_idx = idx + 3;\n model.upperPositionLimit.segment<4>(quat_idx).setConstant(+b);\n model.lowerPositionLimit.segment<4>(quat_idx).setConstant(-b);\n } else if (rootType == \"planar\") {\n const std::size_t idx = model.joints[rtIdx].idx_q();\n model.upperPositionLimit.segment<2>(idx).setConstant(+b);\n model.lowerPositionLimit.segment<2>(idx).setConstant(-b);\n \/\/ Unit complex bounds\n b = 1.01;\n const size_type cplx_idx = idx + 2;\n model.upperPositionLimit.segment<2>(cplx_idx).setConstant(+b);\n model.lowerPositionLimit.segment<2>(cplx_idx).setConstant(-b);\n }\n }\n\n std::string makeModelPath (const std::string& package,\n const std::string& type,\n const std::string& modelName,\n const std::string& suffix = \"\")\n {\n std::stringstream ss;\n ss << \"package:\/\/\" << package << \"\/\" << type << \"\/\" << modelName << suffix << \".\" << type;\n return ss.str();\n }\n\n template <bool XmlString>\n void _removeCollisionPairs (\n const Model& model,\n GeomModel& geomModel,\n const std::string& srdf,\n bool verbose)\n {\n ::pinocchio::srdf::removeCollisionPairsFromXML\n (model, geomModel, srdf, verbose);\n }\n\n template <>\n void _removeCollisionPairs<false> (\n const Model& model,\n GeomModel& geomModel,\n const std::string& srdf,\n bool verbose)\n {\n ::pinocchio::srdf::removeCollisionPairs\n (model, geomModel, srdf, verbose);\n }\n\n template <bool srdfAsXmlString>\n void _loadModel (const DevicePtr_t& robot,\n const JointIndex& baseJoint,\n std::string prefix,\n const std::string& rootType,\n const ::urdf::ModelInterfaceSharedPtr urdfTree,\n const std::istream& urdfStream,\n const std::string& srdf)\n {\n if (!urdfTree)\n throw std::invalid_argument (\"Failed to parse URDF. Use check_urdf command to know what's wrong.\");\n if (baseJoint != 0)\n throw std::invalid_argument (\"Only appending robots at the world is supported.\");\n\n Model& model = robot->model();\n const JointIndex idFirstJoint = model.joints.size();\n const FrameIndex idFirstFrame = model.frames.size();\n if (rootType == \"anchor\")\n ::pinocchio::urdf::buildModel(urdfTree, model, verbose);\n else\n ::pinocchio::urdf::buildModel(urdfTree, buildJoint(rootType), model, verbose);\n robot->createData();\n\n hppDout (notice, \"Finished parsing URDF file.\");\n\n GeomModel geomModel;\n\n std::vector<std::string> baseDirs = ::pinocchio::rosPaths();\n fcl::MeshLoaderPtr loader (new fcl::CachedMeshLoader);\n ::pinocchio::urdf::buildGeom(model, urdfStream, ::pinocchio::COLLISION, geomModel, baseDirs, loader);\n geomModel.addAllCollisionPairs();\n\n if (!srdf.empty()) {\n _removeCollisionPairs<srdfAsXmlString>\n (model, geomModel, srdf, verbose);\n if(!srdfAsXmlString)\n se3::srdf::getNeutralConfigurationFromSrdf(model,srdf);\n else{\n hppDout(warning,\"Neutral configuration won't be extracted from SRDF string.\");\n \/\/TODO : A method getNeutralConfigurationFromSrdfString must be added in Pinocchio,\n \/\/ similarly to removeCollisionPairsFromSrdf \/ removeCollisionPairsFromSrdfString\n }\n }\n\n if (!prefix.empty()) {\n if (*prefix.rbegin() != '\/') prefix += \"\/\";\n setPrefix(prefix, model, geomModel, idFirstJoint, idFirstFrame);\n }\n\n \/\/ Update root joint bounds\n assert((rootType == \"anchor\")\n || (model.names[idFirstJoint] == prefix + \"root_joint\"));\n setRootJointBounds(model, idFirstJoint, rootType);\n\n ::pinocchio::appendGeometryModel(robot->geomModel(), geomModel);\n robot->createGeomData();\n\n hppDout (notice, \"Finished parsing SRDF file.\");\n }\n\n }\n\n void loadRobotModel (const DevicePtr_t& robot,\n\t\t\t const std::string& rootJointType,\n\t\t\t const std::string& package,\n\t\t\t const std::string& modelName,\n\t\t\t const std::string& urdfSuffix,\n const std::string& srdfSuffix)\n {\n loadModel (robot, 0, \"\", rootJointType,\n makeModelPath(package, \"urdf\", modelName, urdfSuffix),\n makeModelPath(package, \"srdf\", modelName, srdfSuffix));\n }\n\n void loadRobotModel (const DevicePtr_t& robot,\n const JointIndex& baseJoint,\n\t\t\t const std::string& prefix,\n\t\t\t const std::string& rootJointType,\n\t\t\t const std::string& package,\n\t\t\t const std::string& modelName,\n\t\t\t const std::string& urdfSuffix,\n const std::string& srdfSuffix)\n {\n loadModel (robot, baseJoint, \n (prefix.empty() ? \"\" : prefix + \"\/\"),\n rootJointType,\n makeModelPath(package, \"urdf\", modelName, urdfSuffix),\n makeModelPath(package, \"srdf\", modelName, srdfSuffix));\n }\n\n void setupHumanoidRobot (const HumanoidRobotPtr_t& robot,\n const std::string& prefix)\n {\n\t\/\/ Look for special joints and attach them to the model.\n\tsetSpecialJoints (robot, prefix);\n\t\/\/ Fill gaze position and direction.\n\tfillGaze (robot);\n }\n\n void loadUrdfModel (const DevicePtr_t& robot,\n const JointIndex& baseJoint,\n const std::string& prefix,\n\t\t\t const std::string& rootJointType,\n\t\t\t const std::string& package,\n\t\t\t const std::string& filename)\n {\n loadModel (robot, baseJoint,\n (prefix.empty() ? \"\" : prefix + \"\/\"),\n rootJointType,\n makeModelPath(package, \"urdf\", filename), \"\");\n }\n\n void loadUrdfModel (const DevicePtr_t& robot,\n\t\t\t const std::string& rootType,\n\t\t\t const std::string& package,\n\t\t\t const std::string& filename)\n {\n loadModel (robot, 0, \"\", rootType,\n makeModelPath(package, \"urdf\", filename), \"\");\n }\n\n void loadModel (const DevicePtr_t& robot,\n const JointIndex& baseJoint,\n const std::string& prefix,\n const std::string& rootType,\n const std::string& urdfPath,\n const std::string& srdfPath)\n {\n std::vector<std::string> baseDirs = ::pinocchio::rosPaths();\n\n std::string urdfFileName = ::pinocchio::retrieveResourcePath(urdfPath, baseDirs);\n if (urdfFileName == \"\") {\n throw std::invalid_argument (std::string (\"Unable to retrieve \") +\n urdfPath);\n }\n\n std::string srdfFileName;\n if (!srdfPath.empty()) {\n srdfFileName = ::pinocchio::retrieveResourcePath(srdfPath, baseDirs);\n if (srdfFileName == \"\") {\n throw std::invalid_argument (std::string (\"Unable to retrieve \") +\n srdfPath);\n }\n }\n\n ::urdf::ModelInterfaceSharedPtr urdfTree = ::urdf::parseURDFFile(urdfFileName);\n std::ifstream urdfStream (urdfFileName.c_str());\n _loadModel <false> (robot, baseJoint, prefix, rootType,\n urdfTree, urdfStream, srdfFileName);\n }\n\n void loadModelFromString (const DevicePtr_t& robot,\n const JointIndex& baseJoint,\n const std::string& prefix,\n const std::string& rootType,\n const std::string& urdfString,\n const std::string& srdfString)\n {\n ::urdf::ModelInterfaceSharedPtr urdfTree = ::urdf::parseURDF(urdfString);\n std::istringstream urdfStream (urdfString);\n _loadModel <true> (robot, baseJoint, prefix, rootType,\n urdfTree, urdfStream, srdfString);\n }\n } \/\/ end of namespace urdf.\n } \/\/ end of namespace pinocchio.\n} \/\/ end of namespace hpp.\n<commit_msg>Update to Pinocchio v2<commit_after>\/\/ Copyright (c) 2016, Joseph Mirabel\n\/\/ Authors: Joseph Mirabel (joseph.mirabel@laas.fr)\n\/\/\n\/\/ This file is part of hpp-pinocchio.\n\/\/ hpp-pinocchio is free software: you can redistribute it\n\/\/ and\/or modify it under the terms of the GNU Lesser General Public\n\/\/ License as published by the Free Software Foundation, either version\n\/\/ 3 of the License, or (at your option) any later version.\n\/\/\n\/\/ hpp-pinocchio is distributed in the hope that it will be\n\/\/ useful, but WITHOUT ANY WARRANTY; without even the implied warranty\n\/\/ of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ General Lesser Public License for more details. You should have\n\/\/ received a copy of the GNU Lesser General Public License along with\n\/\/ hpp-pinocchio. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n\n#include <hpp\/pinocchio\/urdf\/util.hh>\n\n#include <urdf_parser\/urdf_parser.h>\n\n#include <hpp\/fcl\/mesh_loader\/loader.h>\n\n#include <pinocchio\/parsers\/utils.hpp>\n#include <pinocchio\/parsers\/urdf.hpp>\n#include <pinocchio\/multibody\/geometry.hpp>\n#include <pinocchio\/algorithm\/geometry.hpp>\n#include <pinocchio\/parsers\/srdf.hpp>\n\n#include <hpp\/util\/debug.hh>\n\n#include <hpp\/pinocchio\/joint.hh>\n#include <hpp\/pinocchio\/joint-collection.hh>\n#include <hpp\/pinocchio\/device.hh>\n#include <hpp\/pinocchio\/humanoid-robot.hh>\n\nnamespace hpp {\n namespace pinocchio {\n namespace urdf {\n namespace {\n#ifdef HPP_DEBUG\n const bool verbose = true;\n#else\n const bool verbose = false;\n#endif\n\n JointPtr_t findSpecialJoint (const HumanoidRobotPtr_t& robot, const std::string& linkName)\n {\n return robot->getJointByBodyName (linkName);\n }\n\n void setSpecialJoints (const HumanoidRobotPtr_t& robot, std::string prefix)\n {\n if (!prefix.empty() && *prefix.rbegin() != '\/') prefix += \"\/\";\n try {\n robot->waist (robot->getJointByName(prefix + \"root_joint\"));\n } catch (const std::exception&) {\n hppDout (notice, \"No waist joint found\");\n }\n try {\n robot->chest (findSpecialJoint (robot, prefix + \"chest\"));\n } catch (const std::exception&) {\n hppDout (notice, \"No chest joint found\");\n }\n try {\n robot->leftWrist (findSpecialJoint (robot, prefix + \"l_wrist\"));\n } catch (const std::exception&) {\n hppDout (notice, \"No left wrist joint found\");\n }\n try {\n robot->rightWrist (findSpecialJoint (robot, prefix + \"r_wrist\"));\n } catch (const std::exception&) {\n hppDout (notice, \"No right wrist joint found\");\n }\n try {\n robot->leftAnkle (findSpecialJoint (robot, prefix + \"l_ankle\"));\n } catch (const std::exception&) {\n hppDout (notice, \"No left ankle joint found\");\n }\n try {\n robot->rightAnkle (findSpecialJoint (robot, prefix + \"r_ankle\"));\n } catch (const std::exception&) {\n hppDout (notice, \"No right ankle joint found\");\n }\n try {\n robot->gazeJoint (findSpecialJoint (robot, prefix + \"gaze\"));\n } catch (const std::exception&) {\n hppDout (notice, \"No gaze joint found\");\n }\n }\n\n void fillGaze (const HumanoidRobotPtr_t robot)\n {\n vector3_t dir, origin;\n \/\/ Gaze direction is defined by the gaze joint local\n \/\/ orientation.\n dir[0] = 1;\n dir[1] = 0;\n dir[2] = 0;\n \/\/ Gaze position should is defined by the gaze joint local\n \/\/ origin.\n origin[0] = 0;\n origin[1] = 0;\n origin[2] = 0;\n robot->gaze (dir, origin);\n }\n\n JointModelVariant buildJoint (const std::string& type)\n {\n if (type == \"freeflyer\") return JointCollection::JointModelFreeFlyer();\n else if (type == \"planar\") return JointCollection::JointModelPlanar();\n else if (type == \"prismatic_x\") return JointCollection::JointModelPX();\n else if (type == \"prismatic_y\") return JointCollection::JointModelPY();\n else if (type == \"translation3d\") return JointCollection::JointModelTranslation();\n else throw std::invalid_argument\n (\"Root joint type \\\"\" + type + \"\\\" is currently not available.\");\n }\n\n void setPrefix (const std::string& prefix,\n Model& model, GeomModel& geomModel,\n const JointIndex& idFirstJoint,\n const FrameIndex& idFirstFrame)\n {\n for (JointIndex i = idFirstJoint; i < model.joints.size(); ++i) {\n model.names[i] = prefix + model.names[i];\n }\n for (FrameIndex i = idFirstFrame; i < model.frames.size(); ++i) {\n ::pinocchio::Frame& f = model.frames[i];\n f.name = prefix + f.name;\n }\n BOOST_FOREACH(::pinocchio::GeometryObject& go, geomModel.geometryObjects) {\n go.name = prefix + go.name;\n }\n }\n\n void setRootJointBounds(Model& model,\n const JointIndex& rtIdx,\n const std::string& rootType)\n {\n value_type b = std::numeric_limits<value_type>::infinity();\n if (rootType == \"freeflyer\") {\n const std::size_t idx = model.joints[rtIdx].idx_q();\n model.upperPositionLimit.segment<3>(idx).setConstant(+b);\n model.lowerPositionLimit.segment<3>(idx).setConstant(-b);\n \/\/ Quaternion bounds\n b = 1.01;\n const size_type quat_idx = idx + 3;\n model.upperPositionLimit.segment<4>(quat_idx).setConstant(+b);\n model.lowerPositionLimit.segment<4>(quat_idx).setConstant(-b);\n } else if (rootType == \"planar\") {\n const std::size_t idx = model.joints[rtIdx].idx_q();\n model.upperPositionLimit.segment<2>(idx).setConstant(+b);\n model.lowerPositionLimit.segment<2>(idx).setConstant(-b);\n \/\/ Unit complex bounds\n b = 1.01;\n const size_type cplx_idx = idx + 2;\n model.upperPositionLimit.segment<2>(cplx_idx).setConstant(+b);\n model.lowerPositionLimit.segment<2>(cplx_idx).setConstant(-b);\n }\n }\n\n std::string makeModelPath (const std::string& package,\n const std::string& type,\n const std::string& modelName,\n const std::string& suffix = \"\")\n {\n std::stringstream ss;\n ss << \"package:\/\/\" << package << \"\/\" << type << \"\/\" << modelName << suffix << \".\" << type;\n return ss.str();\n }\n\n template <bool XmlString>\n void _removeCollisionPairs (\n const Model& model,\n GeomModel& geomModel,\n const std::string& srdf,\n bool verbose)\n {\n ::pinocchio::srdf::removeCollisionPairsFromXML\n (model, geomModel, srdf, verbose);\n }\n\n template <>\n void _removeCollisionPairs<false> (\n const Model& model,\n GeomModel& geomModel,\n const std::string& srdf,\n bool verbose)\n {\n ::pinocchio::srdf::removeCollisionPairs\n (model, geomModel, srdf, verbose);\n }\n\n template <bool srdfAsXmlString>\n void _loadModel (const DevicePtr_t& robot,\n const JointIndex& baseJoint,\n std::string prefix,\n const std::string& rootType,\n const ::urdf::ModelInterfaceSharedPtr urdfTree,\n const std::istream& urdfStream,\n const std::string& srdf)\n {\n if (!urdfTree)\n throw std::invalid_argument (\"Failed to parse URDF. Use check_urdf command to know what's wrong.\");\n if (baseJoint != 0)\n throw std::invalid_argument (\"Only appending robots at the world is supported.\");\n\n Model& model = robot->model();\n const JointIndex idFirstJoint = model.joints.size();\n const FrameIndex idFirstFrame = model.frames.size();\n if (rootType == \"anchor\")\n ::pinocchio::urdf::buildModel(urdfTree, model, verbose);\n else\n ::pinocchio::urdf::buildModel(urdfTree, buildJoint(rootType), model, verbose);\n robot->createData();\n\n hppDout (notice, \"Finished parsing URDF file.\");\n\n GeomModel geomModel;\n\n std::vector<std::string> baseDirs = ::pinocchio::rosPaths();\n fcl::MeshLoaderPtr loader (new fcl::CachedMeshLoader);\n ::pinocchio::urdf::buildGeom(model, urdfStream, ::pinocchio::COLLISION, geomModel, baseDirs, loader);\n geomModel.addAllCollisionPairs();\n\n if (!srdf.empty()) {\n _removeCollisionPairs<srdfAsXmlString>\n (model, geomModel, srdf, verbose);\n if(!srdfAsXmlString)\n ::pinocchio::srdf::getNeutralConfiguration(model,srdf);\n else{\n hppDout(warning,\"Neutral configuration won't be extracted from SRDF string.\");\n \/\/TODO : A method getNeutralConfigurationFromSrdfString must be added in Pinocchio,\n \/\/ similarly to removeCollisionPairsFromSrdf \/ removeCollisionPairsFromSrdfString\n }\n }\n\n if (!prefix.empty()) {\n if (*prefix.rbegin() != '\/') prefix += \"\/\";\n setPrefix(prefix, model, geomModel, idFirstJoint, idFirstFrame);\n }\n\n \/\/ Update root joint bounds\n assert((rootType == \"anchor\")\n || (model.names[idFirstJoint] == prefix + \"root_joint\"));\n setRootJointBounds(model, idFirstJoint, rootType);\n\n ::pinocchio::appendGeometryModel(robot->geomModel(), geomModel);\n robot->createGeomData();\n\n hppDout (notice, \"Finished parsing SRDF file.\");\n }\n\n }\n\n void loadRobotModel (const DevicePtr_t& robot,\n\t\t\t const std::string& rootJointType,\n\t\t\t const std::string& package,\n\t\t\t const std::string& modelName,\n\t\t\t const std::string& urdfSuffix,\n const std::string& srdfSuffix)\n {\n loadModel (robot, 0, \"\", rootJointType,\n makeModelPath(package, \"urdf\", modelName, urdfSuffix),\n makeModelPath(package, \"srdf\", modelName, srdfSuffix));\n }\n\n void loadRobotModel (const DevicePtr_t& robot,\n const JointIndex& baseJoint,\n\t\t\t const std::string& prefix,\n\t\t\t const std::string& rootJointType,\n\t\t\t const std::string& package,\n\t\t\t const std::string& modelName,\n\t\t\t const std::string& urdfSuffix,\n const std::string& srdfSuffix)\n {\n loadModel (robot, baseJoint, \n (prefix.empty() ? \"\" : prefix + \"\/\"),\n rootJointType,\n makeModelPath(package, \"urdf\", modelName, urdfSuffix),\n makeModelPath(package, \"srdf\", modelName, srdfSuffix));\n }\n\n void setupHumanoidRobot (const HumanoidRobotPtr_t& robot,\n const std::string& prefix)\n {\n\t\/\/ Look for special joints and attach them to the model.\n\tsetSpecialJoints (robot, prefix);\n\t\/\/ Fill gaze position and direction.\n\tfillGaze (robot);\n }\n\n void loadUrdfModel (const DevicePtr_t& robot,\n const JointIndex& baseJoint,\n const std::string& prefix,\n\t\t\t const std::string& rootJointType,\n\t\t\t const std::string& package,\n\t\t\t const std::string& filename)\n {\n loadModel (robot, baseJoint,\n (prefix.empty() ? \"\" : prefix + \"\/\"),\n rootJointType,\n makeModelPath(package, \"urdf\", filename), \"\");\n }\n\n void loadUrdfModel (const DevicePtr_t& robot,\n\t\t\t const std::string& rootType,\n\t\t\t const std::string& package,\n\t\t\t const std::string& filename)\n {\n loadModel (robot, 0, \"\", rootType,\n makeModelPath(package, \"urdf\", filename), \"\");\n }\n\n void loadModel (const DevicePtr_t& robot,\n const JointIndex& baseJoint,\n const std::string& prefix,\n const std::string& rootType,\n const std::string& urdfPath,\n const std::string& srdfPath)\n {\n std::vector<std::string> baseDirs = ::pinocchio::rosPaths();\n\n std::string urdfFileName = ::pinocchio::retrieveResourcePath(urdfPath, baseDirs);\n if (urdfFileName == \"\") {\n throw std::invalid_argument (std::string (\"Unable to retrieve \") +\n urdfPath);\n }\n\n std::string srdfFileName;\n if (!srdfPath.empty()) {\n srdfFileName = ::pinocchio::retrieveResourcePath(srdfPath, baseDirs);\n if (srdfFileName == \"\") {\n throw std::invalid_argument (std::string (\"Unable to retrieve \") +\n srdfPath);\n }\n }\n\n ::urdf::ModelInterfaceSharedPtr urdfTree = ::urdf::parseURDFFile(urdfFileName);\n std::ifstream urdfStream (urdfFileName.c_str());\n _loadModel <false> (robot, baseJoint, prefix, rootType,\n urdfTree, urdfStream, srdfFileName);\n }\n\n void loadModelFromString (const DevicePtr_t& robot,\n const JointIndex& baseJoint,\n const std::string& prefix,\n const std::string& rootType,\n const std::string& urdfString,\n const std::string& srdfString)\n {\n ::urdf::ModelInterfaceSharedPtr urdfTree = ::urdf::parseURDF(urdfString);\n std::istringstream urdfStream (urdfString);\n _loadModel <true> (robot, baseJoint, prefix, rootType,\n urdfTree, urdfStream, srdfString);\n }\n } \/\/ end of namespace urdf.\n } \/\/ end of namespace pinocchio.\n} \/\/ end of namespace hpp.\n<|endoftext|>"} {"text":"<commit_before>#include \"util.h\"\n\n#include \"function_traits.h\"\n\n#include \"catch.h\"\n\n#include <limits>\n#include <regex>\n\nTEST_CASE(\"PrettyPrintNumBytes\") {\n using T = function_traits<decltype(PrettyPrintNumBytes)>::argument<0>::type;\n constexpr T K = 1 << 10, M = 1 << 20, G = 1 << 30;\n\n \/\/ show exact numbers up to 1 KiB\n REQUIRE(PrettyPrintNumBytes(0) == \"0 B\");\n REQUIRE(PrettyPrintNumBytes(1) == \"1 B\");\n REQUIRE(PrettyPrintNumBytes(2) == \"2 B\");\n REQUIRE(PrettyPrintNumBytes(K - 1) == \"1023 B\");\n REQUIRE(PrettyPrintNumBytes(K ) == \"1 KiB\");\n REQUIRE(PrettyPrintNumBytes(K + 1) == \"1 KiB\");\n\n \/\/ round up to 2 KiB starting at 1.5 KiB\n REQUIRE(PrettyPrintNumBytes(K + 511) == \"1 KiB\");\n REQUIRE(PrettyPrintNumBytes(K + 512) == \"2 KiB\");\n REQUIRE(PrettyPrintNumBytes(K + 513) == \"2 KiB\");\n\n \/\/ round up to 3 KiB starting at 2.5 KiB\n REQUIRE(PrettyPrintNumBytes(2*K + 511) == \"2 KiB\");\n REQUIRE(PrettyPrintNumBytes(2*K + 512) == \"3 KiB\");\n REQUIRE(PrettyPrintNumBytes(2*K + 513) == \"3 KiB\");\n\n \/\/ round up to 1 MiB starting at 1023.5 KiB\n REQUIRE(PrettyPrintNumBytes(M - 513) == \"1023 KiB\");\n REQUIRE(PrettyPrintNumBytes(M - 512) == \"1 MiB\");\n REQUIRE(PrettyPrintNumBytes(M - 511) == \"1 MiB\");\n\n \/\/ round up to 2 MiB starting at 1.5 MiB\n REQUIRE(PrettyPrintNumBytes(M + 512*K - 1) == \"1 MiB\");\n REQUIRE(PrettyPrintNumBytes(M + 512*K ) == \"2 MiB\");\n REQUIRE(PrettyPrintNumBytes(M + 512*K + 1) == \"2 MiB\");\n\n \/\/ round up to 3 MiB starting at 2.5 MiB\n REQUIRE(PrettyPrintNumBytes(2*M + 512*K - 1) == \"2 MiB\");\n REQUIRE(PrettyPrintNumBytes(2*M + 512*K ) == \"3 MiB\");\n REQUIRE(PrettyPrintNumBytes(2*M + 512*K + 1) == \"3 MiB\");\n\n \/\/ round up to 1 GiB starting at 1023.5 MiB\n REQUIRE(PrettyPrintNumBytes(G - 512*K - 1) == \"1023 MiB\");\n REQUIRE(PrettyPrintNumBytes(G - 512*K ) == \"1 GiB\");\n REQUIRE(PrettyPrintNumBytes(G - 512*K + 1) == \"1 GiB\");\n\n constexpr T Max = std::numeric_limits<T>::max();\n REQUIRE(std::regex_match(PrettyPrintNumBytes(Max), std::regex(\"\\\\d+ EiB\")));\n}\n<commit_msg>don't assume ULLONG_MAX is > 2^60<commit_after>#include \"util.h\"\n\n#include \"function_traits.h\"\n\n#include \"catch.h\"\n\n#include <limits>\n#include <regex>\n\nTEST_CASE(\"PrettyPrintNumBytes\") {\n using T = function_traits<decltype(PrettyPrintNumBytes)>::argument<0>::type;\n constexpr T K = 1 << 10, M = 1 << 20, G = 1 << 30;\n\n \/\/ show exact numbers up to 1 KiB\n REQUIRE(PrettyPrintNumBytes(0) == \"0 B\");\n REQUIRE(PrettyPrintNumBytes(1) == \"1 B\");\n REQUIRE(PrettyPrintNumBytes(2) == \"2 B\");\n REQUIRE(PrettyPrintNumBytes(K - 1) == \"1023 B\");\n REQUIRE(PrettyPrintNumBytes(K ) == \"1 KiB\");\n REQUIRE(PrettyPrintNumBytes(K + 1) == \"1 KiB\");\n\n \/\/ round up to 2 KiB starting at 1.5 KiB\n REQUIRE(PrettyPrintNumBytes(K + 511) == \"1 KiB\");\n REQUIRE(PrettyPrintNumBytes(K + 512) == \"2 KiB\");\n REQUIRE(PrettyPrintNumBytes(K + 513) == \"2 KiB\");\n\n \/\/ round up to 3 KiB starting at 2.5 KiB\n REQUIRE(PrettyPrintNumBytes(2*K + 511) == \"2 KiB\");\n REQUIRE(PrettyPrintNumBytes(2*K + 512) == \"3 KiB\");\n REQUIRE(PrettyPrintNumBytes(2*K + 513) == \"3 KiB\");\n\n \/\/ round up to 1 MiB starting at 1023.5 KiB\n REQUIRE(PrettyPrintNumBytes(M - 513) == \"1023 KiB\");\n REQUIRE(PrettyPrintNumBytes(M - 512) == \"1 MiB\");\n REQUIRE(PrettyPrintNumBytes(M - 511) == \"1 MiB\");\n\n \/\/ round up to 2 MiB starting at 1.5 MiB\n REQUIRE(PrettyPrintNumBytes(M + 512*K - 1) == \"1 MiB\");\n REQUIRE(PrettyPrintNumBytes(M + 512*K ) == \"2 MiB\");\n REQUIRE(PrettyPrintNumBytes(M + 512*K + 1) == \"2 MiB\");\n\n \/\/ round up to 3 MiB starting at 2.5 MiB\n REQUIRE(PrettyPrintNumBytes(2*M + 512*K - 1) == \"2 MiB\");\n REQUIRE(PrettyPrintNumBytes(2*M + 512*K ) == \"3 MiB\");\n REQUIRE(PrettyPrintNumBytes(2*M + 512*K + 1) == \"3 MiB\");\n\n \/\/ round up to 1 GiB starting at 1023.5 MiB\n REQUIRE(PrettyPrintNumBytes(G - 512*K - 1) == \"1023 MiB\");\n REQUIRE(PrettyPrintNumBytes(G - 512*K ) == \"1 GiB\");\n REQUIRE(PrettyPrintNumBytes(G - 512*K + 1) == \"1 GiB\");\n\n constexpr T Max = std::numeric_limits<T>::max();\n REQUIRE(std::regex_match(PrettyPrintNumBytes(Max), std::regex(\"\\\\d+ [A-Z]iB\")));\n}\n<|endoftext|>"} {"text":"<commit_before>\/**********************************************************************\n * $Id$\n *\n * GEOS - Geometry Engine Open Source\n * http:\/\/geos.refractions.net\n *\n * Copyright (C) 2001-2002 Vivid Solutions Inc.\n *\n * This is free software; you can redistribute and\/or modify it under\n * the terms of the GNU Lesser General Public Licence as published\n * by the Free Software Foundation. \n * See the COPYING file for more information.\n *\n **********************************************************************\n * $Log$\n * Revision 1.12 2004\/05\/05 13:08:01 strk\n * Leaks fixed, explicit allocations\/deallocations reduced.\n *\n * Revision 1.11 2004\/05\/05 10:54:48 strk\n * Removed some private static heap explicit allocation, less cleanup done by\n * the unloader.\n *\n * Revision 1.10 2004\/05\/03 22:56:44 strk\n * leaks fixed, exception specification omitted.\n *\n * Revision 1.9 2004\/05\/03 17:15:38 strk\n * leaks on exception fixed.\n *\n * Revision 1.8 2004\/05\/03 10:43:43 strk\n * Exception specification considered harmful - left as comment.\n *\n * Revision 1.7 2004\/04\/30 09:15:28 strk\n * Enlarged exception specifications to allow for AssertionFailedException.\n * Added missing initializers.\n *\n * Revision 1.6 2004\/04\/23 00:02:18 strk\n * const-correctness changes\n *\n * Revision 1.5 2004\/04\/20 10:58:04 strk\n * More memory leaks removed.\n *\n * Revision 1.4 2004\/04\/19 15:14:46 strk\n * Added missing virtual destructor in SpatialIndex class.\n * Memory leaks fixes. Const and throw specifications added.\n *\n * Revision 1.3 2004\/04\/19 12:51:01 strk\n * Memory leaks fixes. Throw specifications added.\n *\n * Revision 1.2 2004\/04\/14 08:38:52 strk\n * BufferBuilder constructor missed to initialize workingPrecisionModel\n *\n * Revision 1.1 2004\/04\/10 08:40:01 ybychkov\n * \"operation\/buffer\" upgraded to JTS 1.4\n *\n *\n **********************************************************************\/\n\n\n#include \"..\/..\/headers\/opBuffer.h\"\n\nnamespace geos {\n\n\/**\n* Compute the change in depth as an edge is crossed from R to L\n*\/\nint BufferBuilder::depthDelta(Label *label) {\n\tint lLoc=label->getLocation(0, Position::LEFT);\n\tint rLoc=label->getLocation(0, Position::RIGHT);\n\tif (lLoc== Location::INTERIOR && rLoc== Location::EXTERIOR)\n\t\treturn 1;\n\telse if (lLoc== Location::EXTERIOR && rLoc== Location::INTERIOR)\n\t\treturn -1;\n\treturn 0;\n}\n\nCGAlgorithms BufferBuilder::cga=RobustCGAlgorithms();\n\n\/**\n* Creates a new BufferBuilder\n*\/\nBufferBuilder::BufferBuilder() {\n\tworkingPrecisionModel=NULL;\n\tgraph=new PlanarGraph(new OverlayNodeFactory());\n\tquadrantSegments=OffsetCurveBuilder::DEFAULT_QUADRANT_SEGMENTS;\n\tendCapStyle=BufferOp::CAP_ROUND;\n\tedgeList=new EdgeList();\n}\n\nBufferBuilder::~BufferBuilder() {\n\tdelete edgeList;\n\tdelete graph;\n}\n\n\/**\n* Sets the number of segments used to approximate a angle fillet\n*\n* @param quadrantSegments the number of segments in a fillet for a quadrant\n*\/\nvoid BufferBuilder::setQuadrantSegments(int nQuadrantSegments){\n\tquadrantSegments=nQuadrantSegments;\n}\n\n\/**\n* Sets the precision model to use during the curve computation and noding,\n* if it is different to the precision model of the Geometry->\n* If the precision model is less than the precision of the Geometry precision model,\n* the Geometry must have previously been rounded to that precision->\n*\n* @param pm the precision model to use\n*\/\nvoid BufferBuilder::setWorkingPrecisionModel(PrecisionModel *pm){\n\tworkingPrecisionModel=pm;\n}\n\nvoid BufferBuilder::setEndCapStyle(int nEndCapStyle){\n\tendCapStyle=nEndCapStyle;\n}\n\nGeometry*\nBufferBuilder::buffer(Geometry *g, double distance)\n\t\/\/ throw(GEOSException *)\n{\n\tconst PrecisionModel *precisionModel=workingPrecisionModel;\n\tif (precisionModel==NULL)\n\t\tprecisionModel=g->getPrecisionModel();\n\n\t\/\/ factory must be the same as the one used by the input\n\tgeomFact=g->getFactory();\n\tOffsetCurveBuilder curveBuilder=OffsetCurveBuilder(precisionModel, quadrantSegments);\n\tcurveBuilder.setEndCapStyle(endCapStyle);\n\tOffsetCurveSetBuilder curveSetBuilder=OffsetCurveSetBuilder(g, distance, &curveBuilder);\n\tvector<SegmentString*> *bufferSegStrList=curveSetBuilder.getCurves();\n\t\/\/ short-circuit test\n\tif ((int)bufferSegStrList->size()<=0) {\n\t\tGeometry *emptyGeom=geomFact->createGeometryCollection(new vector<Geometry*>());\n\t\treturn emptyGeom;\n\t}\n\n\tcomputeNodedEdges(bufferSegStrList, precisionModel);\n\n\tGeometry* resultGeom=NULL;\n\tvector<Geometry*> *resultPolyList=NULL;\n\tvector<BufferSubgraph*> *subgraphList=NULL;\n\ttry {\n\t\tgraph->addEdges(edgeList->getEdges());\n\t\tsubgraphList=createSubgraphs(graph);\n\t\tPolygonBuilder polyBuilder=PolygonBuilder(geomFact,&cga);\n\t\tbuildSubgraphs(subgraphList, &polyBuilder);\n\t\tresultPolyList=polyBuilder.getPolygons();\n\t\tresultGeom=geomFact->buildGeometry(resultPolyList);\n\t} catch (GEOSException *exc) {\n\t\tfor (int i=0; i<subgraphList->size(); i++)\n\t\t\tdelete (*subgraphList)[i];\n\t\tdelete subgraphList;\n\t\tdelete resultPolyList;\n\t\tthrow;\n\t} \n\tfor (int i=0; i<subgraphList->size(); i++)\n\t\tdelete (*subgraphList)[i];\n\tdelete subgraphList;\n\tdelete resultPolyList;\n\treturn resultGeom;\n}\n\nvoid\nBufferBuilder::computeNodedEdges(vector<SegmentString*> *bufferSegStrList, const PrecisionModel *precisionModel)\n\t\/\/ throw(GEOSException *)\n{\n\t\/\/BufferCurveGraphNoder noder=new BufferCurveGraphNoder(geomFact->getPrecisionModel());\n\tIteratedNoder noder=IteratedNoder(precisionModel);\n\tvector<SegmentString*> *nodedSegStrings = NULL;\n\t\n\ttry \n\t{\n\t\tnodedSegStrings=noder.node(bufferSegStrList);\n\n\t\t\/\/ DEBUGGING ONLY\n\t\t\/\/BufferDebug->saveEdges(nodedEdges, \"run\" + BufferDebug->runCount + \"_nodedEdges\");\n\t\tfor (int i=0;i<(int)nodedSegStrings->size();i++) {\n\t\t\tSegmentString *segStr=(*nodedSegStrings)[i];\n\t\t\tLabel *oldLabel=(Label*) segStr->getContext();\n\t\t\tEdge *edge=new Edge((CoordinateList*) segStr->getCoordinates(), new Label(oldLabel));\n\t\t\tinsertEdge(edge);\n\t\t}\n\t\t\/\/saveEdges(edgeList->getEdges(), \"run\" + runCount + \"_collapsedEdges\");\n\t} catch (...) {\n\t\tdelete nodedSegStrings;\n\t\tthrow;\n\t} \n\tdelete nodedSegStrings;\n}\n\n\n\/**\n* Inserted edges are checked to see if an identical edge already exists->\n* If so, the edge is not inserted, but its label is merged\n* with the existing edge->\n*\/\nvoid BufferBuilder::insertEdge(Edge *e){\n\t\/\/<FIX> MD 8 Oct 03 speed up identical edge lookup\n\t\/\/ fast lookup\n\tEdge *existingEdge=edgeList->findEqualEdge(e);\n\t\/\/ If an identical edge already exists, simply update its label\n\tif (existingEdge != NULL) {\n\t\tLabel *existingLabel=existingEdge->getLabel();\n\t\tLabel *labelToMerge=e->getLabel();\n\t\t\/\/ check if new edge is in reverse direction to existing edge\n\t\t\/\/ if so, must flip the label before merging it\n\t\tif (! existingEdge->isPointwiseEqual(e)) {\n\t\t\tlabelToMerge=new Label(e->getLabel());\n\t\t\tlabelToMerge->flip();\n\t\t}\n\t\texistingLabel->merge(labelToMerge);\n\t\t\/\/ compute new depth delta of sum of edges\n\t\tint mergeDelta=depthDelta(labelToMerge);\n\t\tint existingDelta=existingEdge->getDepthDelta();\n\t\tint newDelta=existingDelta + mergeDelta;\n\t\texistingEdge->setDepthDelta(newDelta);\n\t\tdelete e;\n\t} else { \/\/ no matching existing edge was found\n\t\t\/\/ add this new edge to the list of edges in this graph\n\t\t\/\/e->setName(name + edges->size());\n\t\tedgeList->add(e);\n\t\te->setDepthDelta(depthDelta(e->getLabel()));\n\t}\n}\n\nbool BufferSubgraphGT(BufferSubgraph *first, BufferSubgraph *second) {\n\tif (first->compareTo(second)>=0)\n\t\treturn true;\n\telse\n\t\treturn false;\n}\n\nvector<BufferSubgraph*>*\nBufferBuilder::createSubgraphs(PlanarGraph *graph)\n{\n\tvector<BufferSubgraph*> *subgraphList=new vector<BufferSubgraph*>();\n\tvector<Node*> *n=graph->getNodes();\n\tfor (int i=0;i<(int)n->size();i++) {\n\t\tNode *node=(*n)[i];\n\t\tif (!node->isVisited()) {\n\t\t\tBufferSubgraph *subgraph=new BufferSubgraph(&cga);\n\t\t\tsubgraph->create(node);\n\t\t\tsubgraphList->push_back(subgraph);\n\t\t}\n\t}\n\tdelete n;\n\t\/**\n\t* Sort the subgraphs in descending order of their rightmost coordinate->\n\t* This ensures that when the Polygons for the subgraphs are built,\n\t* subgraphs for shells will have been built before the subgraphs for\n\t* any holes they contain->\n\t*\/\n\tsort(subgraphList->begin(),subgraphList->end(),BufferSubgraphGT);\n\treturn subgraphList;\n}\n\n\/**\n* Completes the building of the input subgraphs by depth-labelling them,\n* and adds them to the PolygonBuilder->\n* The subgraph list must be sorted in rightmost-coordinate order->\n*\n* @param subgraphList the subgraphs to build\n* @param polyBuilder the PolygonBuilder which will build the final polygons\n*\/\nvoid\nBufferBuilder::buildSubgraphs(vector<BufferSubgraph*> *subgraphList,PolygonBuilder *polyBuilder)\n{\n\tvector<BufferSubgraph*> *processedGraphs=new vector<BufferSubgraph*>();\n\ttry {\n\t\tfor (int i=0;i<(int)subgraphList->size();i++) {\n\t\t\tBufferSubgraph *subgraph=(*subgraphList)[i];\n\t\t\tCoordinate *p=subgraph->getRightmostCoordinate();\n\t\t\tSubgraphDepthLocater locater=SubgraphDepthLocater(processedGraphs);\n\t\t\tint outsideDepth=locater.getDepth(*p);\n\t\t\tsubgraph->computeDepth(outsideDepth);\n\t\t\tsubgraph->findResultEdges();\n\t\t\tprocessedGraphs->push_back(subgraph);\n\t\t\tpolyBuilder->add(subgraph->getDirectedEdges(), subgraph->getNodes());\n\t\t}\n\t} catch (...) {\n\t\tdelete processedGraphs;\n\t\tthrow;\n\t}\n\tdelete processedGraphs;\n}\n}\n<commit_msg>Avoid use of copy c'tors on local objects initializzation<commit_after>\/**********************************************************************\n * $Id$\n *\n * GEOS - Geometry Engine Open Source\n * http:\/\/geos.refractions.net\n *\n * Copyright (C) 2001-2002 Vivid Solutions Inc.\n *\n * This is free software; you can redistribute and\/or modify it under\n * the terms of the GNU Lesser General Public Licence as published\n * by the Free Software Foundation. \n * See the COPYING file for more information.\n *\n **********************************************************************\n * $Log$\n * Revision 1.13 2004\/05\/05 16:36:46 strk\n * Avoid use of copy c'tors on local objects initializzation\n *\n * Revision 1.12 2004\/05\/05 13:08:01 strk\n * Leaks fixed, explicit allocations\/deallocations reduced.\n *\n * Revision 1.11 2004\/05\/05 10:54:48 strk\n * Removed some private static heap explicit allocation, less cleanup done by\n * the unloader.\n *\n * Revision 1.10 2004\/05\/03 22:56:44 strk\n * leaks fixed, exception specification omitted.\n *\n * Revision 1.9 2004\/05\/03 17:15:38 strk\n * leaks on exception fixed.\n *\n * Revision 1.8 2004\/05\/03 10:43:43 strk\n * Exception specification considered harmful - left as comment.\n *\n * Revision 1.7 2004\/04\/30 09:15:28 strk\n * Enlarged exception specifications to allow for AssertionFailedException.\n * Added missing initializers.\n *\n * Revision 1.6 2004\/04\/23 00:02:18 strk\n * const-correctness changes\n *\n * Revision 1.5 2004\/04\/20 10:58:04 strk\n * More memory leaks removed.\n *\n * Revision 1.4 2004\/04\/19 15:14:46 strk\n * Added missing virtual destructor in SpatialIndex class.\n * Memory leaks fixes. Const and throw specifications added.\n *\n * Revision 1.3 2004\/04\/19 12:51:01 strk\n * Memory leaks fixes. Throw specifications added.\n *\n * Revision 1.2 2004\/04\/14 08:38:52 strk\n * BufferBuilder constructor missed to initialize workingPrecisionModel\n *\n * Revision 1.1 2004\/04\/10 08:40:01 ybychkov\n * \"operation\/buffer\" upgraded to JTS 1.4\n *\n *\n **********************************************************************\/\n\n\n#include \"..\/..\/headers\/opBuffer.h\"\n\nnamespace geos {\n\n\/**\n* Compute the change in depth as an edge is crossed from R to L\n*\/\nint BufferBuilder::depthDelta(Label *label) {\n\tint lLoc=label->getLocation(0, Position::LEFT);\n\tint rLoc=label->getLocation(0, Position::RIGHT);\n\tif (lLoc== Location::INTERIOR && rLoc== Location::EXTERIOR)\n\t\treturn 1;\n\telse if (lLoc== Location::EXTERIOR && rLoc== Location::INTERIOR)\n\t\treturn -1;\n\treturn 0;\n}\n\nCGAlgorithms BufferBuilder::cga=RobustCGAlgorithms();\n\n\/**\n* Creates a new BufferBuilder\n*\/\nBufferBuilder::BufferBuilder() {\n\tworkingPrecisionModel=NULL;\n\tgraph=new PlanarGraph(new OverlayNodeFactory());\n\tquadrantSegments=OffsetCurveBuilder::DEFAULT_QUADRANT_SEGMENTS;\n\tendCapStyle=BufferOp::CAP_ROUND;\n\tedgeList=new EdgeList();\n}\n\nBufferBuilder::~BufferBuilder() {\n\tdelete edgeList;\n\tdelete graph;\n}\n\n\/**\n* Sets the number of segments used to approximate a angle fillet\n*\n* @param quadrantSegments the number of segments in a fillet for a quadrant\n*\/\nvoid BufferBuilder::setQuadrantSegments(int nQuadrantSegments){\n\tquadrantSegments=nQuadrantSegments;\n}\n\n\/**\n* Sets the precision model to use during the curve computation and noding,\n* if it is different to the precision model of the Geometry->\n* If the precision model is less than the precision of the Geometry precision model,\n* the Geometry must have previously been rounded to that precision->\n*\n* @param pm the precision model to use\n*\/\nvoid BufferBuilder::setWorkingPrecisionModel(PrecisionModel *pm){\n\tworkingPrecisionModel=pm;\n}\n\nvoid BufferBuilder::setEndCapStyle(int nEndCapStyle){\n\tendCapStyle=nEndCapStyle;\n}\n\nGeometry*\nBufferBuilder::buffer(Geometry *g, double distance)\n\t\/\/ throw(GEOSException *)\n{\n\tconst PrecisionModel *precisionModel=workingPrecisionModel;\n\tif (precisionModel==NULL)\n\t\tprecisionModel=g->getPrecisionModel();\n\n\t\/\/ factory must be the same as the one used by the input\n\tgeomFact=g->getFactory();\n\tOffsetCurveBuilder curveBuilder(precisionModel, quadrantSegments);\n\tcurveBuilder.setEndCapStyle(endCapStyle);\n\tOffsetCurveSetBuilder curveSetBuilder(g, distance, &curveBuilder);\n\tvector<SegmentString*> *bufferSegStrList=curveSetBuilder.getCurves();\n\t\/\/ short-circuit test\n\tif ((int)bufferSegStrList->size()<=0) {\n\t\tGeometry *emptyGeom=geomFact->createGeometryCollection(new vector<Geometry*>());\n\t\treturn emptyGeom;\n\t}\n\n\tcomputeNodedEdges(bufferSegStrList, precisionModel);\n\n\tGeometry* resultGeom=NULL;\n\tvector<Geometry*> *resultPolyList=NULL;\n\tvector<BufferSubgraph*> *subgraphList=NULL;\n\ttry {\n\t\tgraph->addEdges(edgeList->getEdges());\n\t\tsubgraphList=createSubgraphs(graph);\n\t\tPolygonBuilder polyBuilder(geomFact,&cga);\n\t\tbuildSubgraphs(subgraphList, &polyBuilder);\n\t\tresultPolyList=polyBuilder.getPolygons();\n\t\tresultGeom=geomFact->buildGeometry(resultPolyList);\n\t} catch (GEOSException *exc) {\n\t\tfor (int i=0; i<subgraphList->size(); i++)\n\t\t\tdelete (*subgraphList)[i];\n\t\tdelete subgraphList;\n\t\tdelete resultPolyList;\n\t\tthrow;\n\t} \n\tfor (int i=0; i<subgraphList->size(); i++)\n\t\tdelete (*subgraphList)[i];\n\tdelete subgraphList;\n\tdelete resultPolyList;\n\treturn resultGeom;\n}\n\nvoid\nBufferBuilder::computeNodedEdges(vector<SegmentString*> *bufferSegStrList, const PrecisionModel *precisionModel)\n\t\/\/ throw(GEOSException *)\n{\n\t\/\/BufferCurveGraphNoder noder=new BufferCurveGraphNoder(geomFact->getPrecisionModel());\n\tIteratedNoder noder(precisionModel);\n\tvector<SegmentString*> *nodedSegStrings = NULL;\n\t\n\ttry \n\t{\n\t\tnodedSegStrings=noder.node(bufferSegStrList);\n\n\t\t\/\/ DEBUGGING ONLY\n\t\t\/\/BufferDebug->saveEdges(nodedEdges, \"run\" + BufferDebug->runCount + \"_nodedEdges\");\n\t\tfor (int i=0;i<(int)nodedSegStrings->size();i++) {\n\t\t\tSegmentString *segStr=(*nodedSegStrings)[i];\n\t\t\tLabel *oldLabel=(Label*) segStr->getContext();\n\t\t\tEdge *edge=new Edge((CoordinateList*) segStr->getCoordinates(), new Label(oldLabel));\n\t\t\tinsertEdge(edge);\n\t\t}\n\t\t\/\/saveEdges(edgeList->getEdges(), \"run\" + runCount + \"_collapsedEdges\");\n\t} catch (...) {\n\t\tdelete nodedSegStrings;\n\t\tthrow;\n\t} \n\tdelete nodedSegStrings;\n}\n\n\n\/**\n* Inserted edges are checked to see if an identical edge already exists->\n* If so, the edge is not inserted, but its label is merged\n* with the existing edge->\n*\/\nvoid BufferBuilder::insertEdge(Edge *e){\n\t\/\/<FIX> MD 8 Oct 03 speed up identical edge lookup\n\t\/\/ fast lookup\n\tEdge *existingEdge=edgeList->findEqualEdge(e);\n\t\/\/ If an identical edge already exists, simply update its label\n\tif (existingEdge != NULL) {\n\t\tLabel *existingLabel=existingEdge->getLabel();\n\t\tLabel *labelToMerge=e->getLabel();\n\t\t\/\/ check if new edge is in reverse direction to existing edge\n\t\t\/\/ if so, must flip the label before merging it\n\t\tif (! existingEdge->isPointwiseEqual(e)) {\n\t\t\tlabelToMerge=new Label(e->getLabel());\n\t\t\tlabelToMerge->flip();\n\t\t}\n\t\texistingLabel->merge(labelToMerge);\n\t\t\/\/ compute new depth delta of sum of edges\n\t\tint mergeDelta=depthDelta(labelToMerge);\n\t\tint existingDelta=existingEdge->getDepthDelta();\n\t\tint newDelta=existingDelta + mergeDelta;\n\t\texistingEdge->setDepthDelta(newDelta);\n\t\tdelete e;\n\t} else { \/\/ no matching existing edge was found\n\t\t\/\/ add this new edge to the list of edges in this graph\n\t\t\/\/e->setName(name + edges->size());\n\t\tedgeList->add(e);\n\t\te->setDepthDelta(depthDelta(e->getLabel()));\n\t}\n}\n\nbool BufferSubgraphGT(BufferSubgraph *first, BufferSubgraph *second) {\n\tif (first->compareTo(second)>=0)\n\t\treturn true;\n\telse\n\t\treturn false;\n}\n\nvector<BufferSubgraph*>*\nBufferBuilder::createSubgraphs(PlanarGraph *graph)\n{\n\tvector<BufferSubgraph*> *subgraphList=new vector<BufferSubgraph*>();\n\tvector<Node*> *n=graph->getNodes();\n\tfor (int i=0;i<(int)n->size();i++) {\n\t\tNode *node=(*n)[i];\n\t\tif (!node->isVisited()) {\n\t\t\tBufferSubgraph *subgraph=new BufferSubgraph(&cga);\n\t\t\tsubgraph->create(node);\n\t\t\tsubgraphList->push_back(subgraph);\n\t\t}\n\t}\n\tdelete n;\n\t\/**\n\t* Sort the subgraphs in descending order of their rightmost coordinate->\n\t* This ensures that when the Polygons for the subgraphs are built,\n\t* subgraphs for shells will have been built before the subgraphs for\n\t* any holes they contain->\n\t*\/\n\tsort(subgraphList->begin(),subgraphList->end(),BufferSubgraphGT);\n\treturn subgraphList;\n}\n\n\/**\n* Completes the building of the input subgraphs by depth-labelling them,\n* and adds them to the PolygonBuilder->\n* The subgraph list must be sorted in rightmost-coordinate order->\n*\n* @param subgraphList the subgraphs to build\n* @param polyBuilder the PolygonBuilder which will build the final polygons\n*\/\nvoid\nBufferBuilder::buildSubgraphs(vector<BufferSubgraph*> *subgraphList,PolygonBuilder *polyBuilder)\n{\n\tvector<BufferSubgraph*> *processedGraphs=new vector<BufferSubgraph*>();\n\ttry {\n\t\tfor (int i=0;i<(int)subgraphList->size();i++) {\n\t\t\tBufferSubgraph *subgraph=(*subgraphList)[i];\n\t\t\tCoordinate *p=subgraph->getRightmostCoordinate();\n\t\t\tSubgraphDepthLocater locater=SubgraphDepthLocater(processedGraphs);\n\t\t\tint outsideDepth=locater.getDepth(*p);\n\t\t\tsubgraph->computeDepth(outsideDepth);\n\t\t\tsubgraph->findResultEdges();\n\t\t\tprocessedGraphs->push_back(subgraph);\n\t\t\tpolyBuilder->add(subgraph->getDirectedEdges(), subgraph->getNodes());\n\t\t}\n\t} catch (...) {\n\t\tdelete processedGraphs;\n\t\tthrow;\n\t}\n\tdelete processedGraphs;\n}\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2009-2010 Satoshi Nakamoto\n\/\/ Copyright (c) 2009-2014 The Bitcoin developers\n\/\/ Copyright (c) 2016-2019 The PIVX developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#if defined(HAVE_CONFIG_H)\n#include \"config\/pivx-config.h\"\n#endif\n\n#include \"tinyformat.h\"\n#include \"utiltime.h\"\n\n#include <boost\/date_time\/posix_time\/posix_time.hpp>\n#include <boost\/thread.hpp>\n\n\nstatic int64_t nMockTime = 0; \/\/! For unit testing\n\nint64_t GetTime()\n{\n if (nMockTime) return nMockTime;\n\n return time(NULL);\n}\n\nvoid SetMockTime(int64_t nMockTimeIn)\n{\n nMockTime = nMockTimeIn;\n}\n\nint64_t GetTimeMillis()\n{\n return (boost::posix_time::ptime(boost::posix_time::microsec_clock::universal_time()) -\n boost::posix_time::ptime(boost::gregorian::date(1970, 1, 1)))\n .total_milliseconds();\n}\n\nint64_t GetTimeMicros()\n{\n return (boost::posix_time::ptime(boost::posix_time::microsec_clock::universal_time()) -\n boost::posix_time::ptime(boost::gregorian::date(1970, 1, 1)))\n .total_microseconds();\n}\n\nvoid MilliSleep(int64_t n)\n{\n boost::this_thread::sleep_for(boost::chrono::milliseconds(n));\n}\n\nstd::string DateTimeStrFormat(const char* pszFormat, int64_t nTime)\n{\n \/\/ std::locale takes ownership of the pointer\n std::locale loc(std::locale::classic(), new boost::posix_time::time_facet(pszFormat));\n std::stringstream ss;\n ss.imbue(loc);\n ss << boost::posix_time::from_time_t(nTime);\n return ss.str();\n}\n\nstd::string DurationToDHMS(int64_t nDurationTime)\n{\n int seconds = nDurationTime % 60;\n nDurationTime \/= 60;\n int minutes = nDurationTime % 60;\n nDurationTime \/= 60;\n int hours = nDurationTime % 24;\n int days = nDurationTime \/ 24;\n if (days)\n return strprintf(\"%dd %02dh:%02dm:%02ds\", days, hours, minutes, seconds);\n if (hours)\n return strprintf(\"%02dh:%02dm:%02ds\", hours, minutes, seconds);\n return strprintf(\"%02dm:%02ds\", minutes, seconds);\n}\n<commit_msg>fix tsan: utiltime race on nMockTime<commit_after>\/\/ Copyright (c) 2009-2010 Satoshi Nakamoto\n\/\/ Copyright (c) 2009-2014 The Bitcoin developers\n\/\/ Copyright (c) 2016-2019 The PIVX developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#if defined(HAVE_CONFIG_H)\n#include \"config\/pivx-config.h\"\n#endif\n\n#include \"tinyformat.h\"\n#include \"utiltime.h\"\n\n#include <atomic>\n\n#include <boost\/date_time\/posix_time\/posix_time.hpp>\n#include <boost\/thread.hpp>\n\n\nstatic std::atomic<int64_t> nMockTime(0); \/\/!< For unit testing\n\n\nint64_t GetTime()\n{\n int64_t mocktime = nMockTime.load(std::memory_order_relaxed);\n if (mocktime) return mocktime;\n\n time_t now = time(nullptr);\n assert(now > 0);\n return now;\n}\n\nvoid SetMockTime(int64_t nMockTimeIn)\n{\n nMockTime.store(nMockTimeIn, std::memory_order_relaxed);\n}\n\nint64_t GetTimeMillis()\n{\n int64_t now = (boost::posix_time::microsec_clock::universal_time() -\n boost::posix_time::ptime(boost::gregorian::date(1970,1,1))).total_milliseconds();\n assert(now > 0);\n return now;\n}\n\nint64_t GetTimeMicros()\n{\n int64_t now = (boost::posix_time::microsec_clock::universal_time() -\n boost::posix_time::ptime(boost::gregorian::date(1970,1,1))).total_microseconds();\n assert(now > 0);\n return now;\n}\n\nvoid MilliSleep(int64_t n)\n{\n boost::this_thread::sleep_for(boost::chrono::milliseconds(n));\n}\n\nstd::string DateTimeStrFormat(const char* pszFormat, int64_t nTime)\n{\n \/\/ std::locale takes ownership of the pointer\n std::locale loc(std::locale::classic(), new boost::posix_time::time_facet(pszFormat));\n std::stringstream ss;\n ss.imbue(loc);\n ss << boost::posix_time::from_time_t(nTime);\n return ss.str();\n}\n\nstd::string DurationToDHMS(int64_t nDurationTime)\n{\n int seconds = nDurationTime % 60;\n nDurationTime \/= 60;\n int minutes = nDurationTime % 60;\n nDurationTime \/= 60;\n int hours = nDurationTime % 24;\n int days = nDurationTime \/ 24;\n if (days)\n return strprintf(\"%dd %02dh:%02dm:%02ds\", days, hours, minutes, seconds);\n if (hours)\n return strprintf(\"%02dh:%02dm:%02ds\", hours, minutes, seconds);\n return strprintf(\"%02dm:%02ds\", minutes, seconds);\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2009-2010 Satoshi Nakamoto\n\/\/ Copyright (c) 2009-2014 The Bitcoin Core developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#if defined(HAVE_CONFIG_H)\n#include \"config\/bitcoin-config.h\"\n#endif\n\n#include \"utiltime.h\"\n\n#include <boost\/date_time\/posix_time\/posix_time.hpp>\n#include <boost\/thread.hpp>\n\nusing namespace std;\n\nstatic int64_t nMockTime = 0; \/\/! For unit testing\n\nint64_t GetTime()\n{\n if (nMockTime) return nMockTime;\n\n return time(NULL);\n}\n\nvoid SetMockTime(int64_t nMockTimeIn)\n{\n nMockTime = nMockTimeIn;\n}\n\nint64_t GetTimeMillis()\n{\n return (boost::posix_time::microsec_clock::universal_time() -\n boost::posix_time::ptime(boost::gregorian::date(1970,1,1))).total_milliseconds();\n}\n\nint64_t GetTimeMicros()\n{\n return (boost::posix_time::microsec_clock::universal_time() -\n boost::posix_time::ptime(boost::gregorian::date(1970,1,1))).total_microseconds();\n}\n\n\/** Return a time useful for the debug log *\/\nint64_t GetLogTimeMicros()\n{\n if (nMockTime) return nMockTime*1000000;\n\n return GetTimeMicros();\n}\n\nvoid MilliSleep(int64_t n)\n{\n\n\/**\n * Boost's sleep_for was uninterruptable when backed by nanosleep from 1.50\n * until fixed in 1.52. Use the deprecated sleep method for the broken case.\n * See: https:\/\/svn.boost.org\/trac\/boost\/ticket\/7238\n *\/\n#if defined(HAVE_WORKING_BOOST_SLEEP_FOR)\n boost::this_thread::sleep_for(boost::chrono::milliseconds(n));\n#elif defined(HAVE_WORKING_BOOST_SLEEP)\n boost::this_thread::sleep(boost::posix_time::milliseconds(n));\n#else\n\/\/should never get here\n#error missing boost sleep implementation\n#endif\n}\n\nstd::string DateTimeStrFormat(const char* pszFormat, int64_t nTime)\n{\n \/\/ std::locale takes ownership of the pointer\n std::locale loc(std::locale::classic(), new boost::posix_time::time_facet(pszFormat));\n std::stringstream ss;\n ss.imbue(loc);\n ss << boost::posix_time::from_time_t(nTime);\n return ss.str();\n}\n<commit_msg>Assert now > 0 in GetTime GetTimeMillis GetTimeMicros<commit_after>\/\/ Copyright (c) 2009-2010 Satoshi Nakamoto\n\/\/ Copyright (c) 2009-2014 The Bitcoin Core developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#if defined(HAVE_CONFIG_H)\n#include \"config\/bitcoin-config.h\"\n#endif\n\n#include \"utiltime.h\"\n\n#include <boost\/date_time\/posix_time\/posix_time.hpp>\n#include <boost\/thread.hpp>\n\nusing namespace std;\n\nstatic int64_t nMockTime = 0; \/\/! For unit testing\n\nint64_t GetTime()\n{\n if (nMockTime) return nMockTime;\n\n time_t now = time(NULL);\n assert(now > 0);\n return now;\n}\n\nvoid SetMockTime(int64_t nMockTimeIn)\n{\n nMockTime = nMockTimeIn;\n}\n\nint64_t GetTimeMillis()\n{\n int64_t now = (boost::posix_time::microsec_clock::universal_time() -\n boost::posix_time::ptime(boost::gregorian::date(1970,1,1))).total_milliseconds();\n assert(now > 0);\n return now;\n}\n\nint64_t GetTimeMicros()\n{\n int64_t now = (boost::posix_time::microsec_clock::universal_time() -\n boost::posix_time::ptime(boost::gregorian::date(1970,1,1))).total_microseconds();\n assert(now > 0);\n return now;\n}\n\n\/** Return a time useful for the debug log *\/\nint64_t GetLogTimeMicros()\n{\n if (nMockTime) return nMockTime*1000000;\n\n return GetTimeMicros();\n}\n\nvoid MilliSleep(int64_t n)\n{\n\n\/**\n * Boost's sleep_for was uninterruptable when backed by nanosleep from 1.50\n * until fixed in 1.52. Use the deprecated sleep method for the broken case.\n * See: https:\/\/svn.boost.org\/trac\/boost\/ticket\/7238\n *\/\n#if defined(HAVE_WORKING_BOOST_SLEEP_FOR)\n boost::this_thread::sleep_for(boost::chrono::milliseconds(n));\n#elif defined(HAVE_WORKING_BOOST_SLEEP)\n boost::this_thread::sleep(boost::posix_time::milliseconds(n));\n#else\n\/\/should never get here\n#error missing boost sleep implementation\n#endif\n}\n\nstd::string DateTimeStrFormat(const char* pszFormat, int64_t nTime)\n{\n \/\/ std::locale takes ownership of the pointer\n std::locale loc(std::locale::classic(), new boost::posix_time::time_facet(pszFormat));\n std::stringstream ss;\n ss.imbue(loc);\n ss << boost::posix_time::from_time_t(nTime);\n return ss.str();\n}\n<|endoftext|>"} {"text":"<commit_before>\/* bzflag\n * Copyright (c) 1993 - 2005 Tim Riker\n *\n * This package is free software; you can redistribute it and\/or\n * modify it under the terms of the license found in the file\n * named COPYING that should have accompanied this file.\n *\n * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR\n * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED\n * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.\n *\/\n\n\/* interface header *\/\n#include \"EffectsMenu.h\"\n\n\/* system implementation headers *\/\n#include <string>\n#include <vector>\n\n\/* common implementation headers *\/\n#include \"BundleMgr.h\"\n#include \"BZDBCache.h\"\n#include \"TextUtils.h\"\n#include \"FontManager.h\"\n#include \"SceneRenderer.h\"\n\n\/* local implementation headers *\/\n#include \"MainMenu.h\"\n#include \"MainWindow.h\"\n#include \"TrackMarks.h\"\n#include \"HUDDialogStack.h\"\n#include \"HUDuiControl.h\"\n#include \"HUDuiList.h\"\n#include \"HUDuiLabel.h\"\n\n\nEffectsMenu::EffectsMenu()\n{\n \/\/ add controls\n std::vector<HUDuiControl*>& list = getControls();\n\n \/\/ cache font face ID\n int fontFace = MainMenu::getFontFace();\n\n \/\/ the menu label\n HUDuiLabel* label = new HUDuiLabel;\n label->setFontFace(fontFace);\n label->setString(\"Effects Settings\");\n list.push_back(label);\n\n \/\/ the menu options\n HUDuiList* option;\n std::vector<std::string>* options;\n\n \/\/ Rain Scale\n option = new HUDuiList;\n option->setFontFace(MainMenu::getFontFace());\n option->setLabel(\"Rain:\");\n option->setCallback(callback, (void*)\"r\");\n options = &option->getList();\n options->push_back(std::string(\"Off\"));\n option->createSlider(10);\n option->update();\n list.push_back(option);\n\n \/\/ The Mirror\n option = new HUDuiList;\n option->setFontFace(fontFace);\n option->setLabel(\"Mirror:\");\n option->setCallback(callback, (void*)\"m\");\n options = &option->getList();\n options->push_back(std::string(\"Off\"));\n options->push_back(std::string(\"On\"));\n option->update();\n list.push_back(option);\n\n \/\/ Animated Treads\n option = new HUDuiList;\n option->setFontFace(fontFace);\n option->setLabel(\"Animated Treads:\");\n option->setCallback(callback, (void*)\"a\");\n options = &option->getList();\n options->push_back(std::string(\"Off\"));\n options->push_back(std::string(\"On\"));\n option->update();\n list.push_back(option);\n\n \/\/ Display Treads\n option = new HUDuiList;\n option->setFontFace(fontFace);\n option->setLabel(\"Display Treads:\");\n option->setCallback(callback, (void*)\"T\");\n options = &option->getList();\n options->push_back(std::string(\"Off\"));\n options->push_back(std::string(\"On\"));\n option->update();\n list.push_back(option);\n\n \/\/ Track Mark Fading Scale\n option = new HUDuiList;\n option->setFontFace(MainMenu::getFontFace());\n option->setLabel(\"Track Marks :\");\n option->setCallback(callback, (void*)\"t\");\n options = &option->getList();\n options->push_back(std::string(\"Off\"));\n option->createSlider(10);\n option->update();\n list.push_back(option);\n\n \/\/ Track Mark Culling Type\n option = new HUDuiList;\n option->setFontFace(MainMenu::getFontFace());\n option->setLabel(\"Track Mark Culling:\");\n option->setCallback(callback, (void*)\"c\");\n options = &option->getList();\n options->push_back(std::string(\"None\"));\n options->push_back(std::string(\"Fast\"));\n options->push_back(std::string(\"Best\"));\n option->update();\n list.push_back(option);\n\n initNavigation(list, 1, list.size() - 1);\n}\n\n\nEffectsMenu::~EffectsMenu()\n{\n}\n\n\nvoid EffectsMenu::execute()\n{\n}\n\n\nvoid EffectsMenu::resize(int width, int height)\n{\n HUDDialog::resize(width, height);\n\n \/\/ use a big font for title, smaller font for the rest\n const float titleFontSize = (float)height \/ 15.0f;\n const float fontSize = (float)height \/ 45.0f;\n FontManager &fm = FontManager::instance();\n\n \/\/ reposition title\n std::vector<HUDuiControl*>& list = getControls();\n HUDuiLabel* title = (HUDuiLabel*)list[0];\n title->setFontSize(titleFontSize);\n const float titleWidth =\n fm.getStrLength(MainMenu::getFontFace(), titleFontSize, title->getString());\n const float titleHeight =\n fm.getStrHeight(MainMenu::getFontFace(), titleFontSize, \" \");\n float x = 0.5f * ((float)width - titleWidth);\n float y = (float)height - titleHeight;\n title->setPosition(x, y);\n\n \/\/ reposition options\n x = 0.5f * (float)width;\n y -= 0.6f * titleHeight;\n const float h = fm.getStrHeight(MainMenu::getFontFace(), fontSize, \" \");\n const int count = list.size();\n int i;\n for (i = 1; i < count; i++) {\n list[i]->setFontSize(fontSize);\n list[i]->setPosition(x, y);\n y -= 1.0f * h;\n }\n\n \/\/ load current settings\n i = 1;\n ((HUDuiList*)list[i++])->setIndex(int((BZDB.eval(\"userRainScale\") * 10.0f) + 0.5f));\n ((HUDuiList*)list[i++])->setIndex(BZDB.isTrue(\"userMirror\") ? 1 : 0);\n ((HUDuiList*)list[i++])->setIndex(BZDB.isTrue(\"animatedTreads\") ? 1 : 0);\n ((HUDuiList*)list[i++])->setIndex(BZDB.isTrue(\"showTreads\") ? 1 : 0);\n ((HUDuiList*)list[i++])->setIndex(int((TrackMarks::getUserFade() * 10.0f) + 0.5f));\n TrackMarks::AirCullStyle style = TrackMarks::getAirCulling();\n if (style == TrackMarks::NoAirCull) {\n ((HUDuiList*)list[i++])->setIndex(0);\n } else if (style != TrackMarks::FullAirCull) {\n ((HUDuiList*)list[i++])->setIndex(1);\n } else {\n ((HUDuiList*)list[i++])->setIndex(2);\n }\n}\n\n\nvoid EffectsMenu::callback(HUDuiControl* w, void* data)\n{\n HUDuiList* list = (HUDuiList*)w;\n\n switch (((const char*)data)[0]) {\n case 'r': {\n int scale = list->getIndex();\n BZDB.setFloat(\"userRainScale\", float(scale) \/ 10.0f);\n break;\n }\n case 'm': {\n BZDB.set(\"userMirror\", list->getIndex() ? \"1\" : \"0\");\n break;\n }\n case 'a': {\n BZDB.set(\"animatedTreads\", list->getIndex() ? \"1\" : \"0\");\n RENDERER.setRebuildTanks();\n break;\n }\n case 'T': {\n BZDB.set(\"showTreads\", list->getIndex() ? \"1\" : \"0\");\n break;\n }\n case 't': {\n int fade = list->getIndex();\n TrackMarks::setUserFade(float(fade) \/ 10.0f);\n break;\n }\n case 'c': {\n int culling = list->getIndex();\n if (culling <= 0) {\n\tTrackMarks::setAirCulling(TrackMarks::NoAirCull);\n } else if (culling == 1) {\n\tTrackMarks::setAirCulling(TrackMarks::InitAirCull);\n } else {\n\tTrackMarks::setAirCulling(TrackMarks::FullAirCull);\n }\n break;\n }\n }\n}\n\n\n\/\/ Local Variables: ***\n\/\/ mode: C++ ***\n\/\/ tab-width: 8 ***\n\/\/ c-basic-offset: 2 ***\n\/\/ indent-tabs-mode: t ***\n\/\/ End: ***\n\/\/ ex: shiftwidth=2 tabstop=8\n<commit_msg>breakup the Effects menu a little<commit_after>\/* bzflag\n * Copyright (c) 1993 - 2005 Tim Riker\n *\n * This package is free software; you can redistribute it and\/or\n * modify it under the terms of the license found in the file\n * named COPYING that should have accompanied this file.\n *\n * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR\n * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED\n * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.\n *\/\n\n\/* interface header *\/\n#include \"EffectsMenu.h\"\n\n\/* system implementation headers *\/\n#include <string>\n#include <vector>\n\n\/* common implementation headers *\/\n#include \"BundleMgr.h\"\n#include \"BZDBCache.h\"\n#include \"TextUtils.h\"\n#include \"FontManager.h\"\n#include \"SceneRenderer.h\"\n\n\/* local implementation headers *\/\n#include \"MainMenu.h\"\n#include \"MainWindow.h\"\n#include \"TrackMarks.h\"\n#include \"HUDDialogStack.h\"\n#include \"HUDuiControl.h\"\n#include \"HUDuiList.h\"\n#include \"HUDuiLabel.h\"\n\n\nEffectsMenu::EffectsMenu()\n{\n \/\/ add controls\n std::vector<HUDuiControl*>& list = getControls();\n\n \/\/ cache font face ID\n int fontFace = MainMenu::getFontFace();\n\n \/\/ the menu label\n HUDuiLabel* label = new HUDuiLabel;\n label->setFontFace(fontFace);\n label->setString(\"Effects Settings\");\n list.push_back(label);\n\n \/\/ the menu options\n HUDuiList* option;\n std::vector<std::string>* options;\n\n \/\/ Rain Scale\n option = new HUDuiList;\n option->setFontFace(MainMenu::getFontFace());\n option->setLabel(\"Rain:\");\n option->setCallback(callback, (void*)\"r\");\n options = &option->getList();\n options->push_back(std::string(\"Off\"));\n option->createSlider(10);\n option->update();\n list.push_back(option);\n\n \/\/ The Mirror\n option = new HUDuiList;\n option->setFontFace(fontFace);\n option->setLabel(\"Mirror:\");\n option->setCallback(callback, (void*)\"m\");\n options = &option->getList();\n options->push_back(std::string(\"Off\"));\n options->push_back(std::string(\"On\"));\n option->update();\n list.push_back(option);\n\n \/\/ Display Treads\n option = new HUDuiList;\n option->setFontFace(fontFace);\n option->setLabel(\"Display Treads:\");\n option->setCallback(callback, (void*)\"T\");\n options = &option->getList();\n options->push_back(std::string(\"Off\"));\n options->push_back(std::string(\"On\"));\n option->update();\n list.push_back(option);\n\n \/\/ Animated Treads\n option = new HUDuiList;\n option->setFontFace(fontFace);\n option->setLabel(\"Animated Treads:\");\n option->setCallback(callback, (void*)\"a\");\n options = &option->getList();\n options->push_back(std::string(\"Off\"));\n options->push_back(std::string(\"On\"));\n option->update();\n list.push_back(option);\n\n \/\/ Track Mark Fading Scale\n option = new HUDuiList;\n option->setFontFace(MainMenu::getFontFace());\n option->setLabel(\"Track Marks :\");\n option->setCallback(callback, (void*)\"t\");\n options = &option->getList();\n options->push_back(std::string(\"Off\"));\n option->createSlider(10);\n option->update();\n list.push_back(option);\n\n \/\/ Track Mark Culling Type\n option = new HUDuiList;\n option->setFontFace(MainMenu::getFontFace());\n option->setLabel(\"Track Mark Culling:\");\n option->setCallback(callback, (void*)\"c\");\n options = &option->getList();\n options->push_back(std::string(\"None\"));\n options->push_back(std::string(\"Fast\"));\n options->push_back(std::string(\"Best\"));\n option->update();\n list.push_back(option);\n\n initNavigation(list, 1, list.size() - 1);\n}\n\n\nEffectsMenu::~EffectsMenu()\n{\n}\n\n\nvoid EffectsMenu::execute()\n{\n}\n\n\nvoid EffectsMenu::resize(int width, int height)\n{\n HUDDialog::resize(width, height);\n\n \/\/ use a big font for title, smaller font for the rest\n const float titleFontSize = (float)height \/ 15.0f;\n const float fontSize = (float)height \/ 45.0f;\n FontManager &fm = FontManager::instance();\n\n \/\/ reposition title\n std::vector<HUDuiControl*>& list = getControls();\n HUDuiLabel* title = (HUDuiLabel*)list[0];\n title->setFontSize(titleFontSize);\n const float titleWidth =\n fm.getStrLength(MainMenu::getFontFace(), titleFontSize, title->getString());\n const float titleHeight =\n fm.getStrHeight(MainMenu::getFontFace(), titleFontSize, \" \");\n float x = 0.5f * ((float)width - titleWidth);\n float y = (float)height - titleHeight;\n title->setPosition(x, y);\n\n \/\/ reposition options\n x = 0.5f * (float)width;\n y -= 0.6f * titleHeight;\n const float h = fm.getStrHeight(MainMenu::getFontFace(), fontSize, \" \");\n const int count = list.size();\n int i;\n for (i = 1; i < count; i++) {\n list[i]->setFontSize(fontSize);\n list[i]->setPosition(x, y);\n if ((i == 2) || (i == 4)) {\n y -= 1.75f * h;\n } else {\n y -= 1.0f * h;\n }\n }\n\n \/\/ load current settings\n i = 1;\n ((HUDuiList*)list[i++])->setIndex(int((BZDB.eval(\"userRainScale\") * 10.0f) + 0.5f));\n ((HUDuiList*)list[i++])->setIndex(BZDB.isTrue(\"userMirror\") ? 1 : 0);\n ((HUDuiList*)list[i++])->setIndex(BZDB.isTrue(\"showTreads\") ? 1 : 0);\n ((HUDuiList*)list[i++])->setIndex(BZDB.isTrue(\"animatedTreads\") ? 1 : 0);\n ((HUDuiList*)list[i++])->setIndex(int((TrackMarks::getUserFade() * 10.0f) + 0.5f));\n TrackMarks::AirCullStyle style = TrackMarks::getAirCulling();\n if (style == TrackMarks::NoAirCull) {\n ((HUDuiList*)list[i++])->setIndex(0);\n } else if (style != TrackMarks::FullAirCull) {\n ((HUDuiList*)list[i++])->setIndex(1);\n } else {\n ((HUDuiList*)list[i++])->setIndex(2);\n }\n}\n\n\nvoid EffectsMenu::callback(HUDuiControl* w, void* data)\n{\n HUDuiList* list = (HUDuiList*)w;\n\n switch (((const char*)data)[0]) {\n case 'r': {\n int scale = list->getIndex();\n BZDB.setFloat(\"userRainScale\", float(scale) \/ 10.0f);\n break;\n }\n case 'm': {\n BZDB.set(\"userMirror\", list->getIndex() ? \"1\" : \"0\");\n break;\n }\n case 'T': {\n BZDB.set(\"showTreads\", list->getIndex() ? \"1\" : \"0\");\n break;\n }\n case 'a': {\n BZDB.set(\"animatedTreads\", list->getIndex() ? \"1\" : \"0\");\n RENDERER.setRebuildTanks();\n break;\n }\n case 't': {\n int fade = list->getIndex();\n TrackMarks::setUserFade(float(fade) \/ 10.0f);\n break;\n }\n case 'c': {\n int culling = list->getIndex();\n if (culling <= 0) {\n\tTrackMarks::setAirCulling(TrackMarks::NoAirCull);\n } else if (culling == 1) {\n\tTrackMarks::setAirCulling(TrackMarks::InitAirCull);\n } else {\n\tTrackMarks::setAirCulling(TrackMarks::FullAirCull);\n }\n break;\n }\n }\n}\n\n\n\/\/ Local Variables: ***\n\/\/ mode: C++ ***\n\/\/ tab-width: 8 ***\n\/\/ c-basic-offset: 2 ***\n\/\/ indent-tabs-mode: t ***\n\/\/ End: ***\n\/\/ ex: shiftwidth=2 tabstop=8\n<|endoftext|>"} {"text":"<commit_before>#include <stdio.h>\n#include <stdlib.h>\n#include <strings.h>\n\n\/\/#include \"notas.h\"\n\n#define N 0x100\n\nstruct TStack{\n struct TAlumno *data[N];\n int cima;\n};\n\nvoid push(struct TStack *pila, struct TAlumno *al){}\nstruct TAlumno *pop(struct TStack *pila){}\n\nint main(int argc, char *argv[]){\n\n struct TAlumno *alumno;\n struct TStack pila;\n pila.cima = 0;\n\n alumno = (struct TAlumno *) malloc(sizeof (struct TAlumno));\n pila.data[0] = alumno;\n pila.cima++;\n\n return EXIT_SUCCESS;\n}\n<commit_msg>struct<commit_after>#include <stdio.h>\n#include <stdlib.h>\n#include <strings.h>\n\n\/\/#include \"notas.h\"\n\/\/hacer una pila que empuje alumnos o lo que queramos.\n\n#define N 0x100\n\nstruct TStack{\n struct TAlumno *reg[1000*N];\n struct TAlumno *data[N];\n int cima;\n};\n\nvoid push(struct TStack *pila, struct TAlumno *al){}\nstruct TAlumno *pop(struct TStack *pila){}\n\nint main(int argc, char *argv[]){\n\n struct TAlumno *alumno;\n struct TStack pila;\n pila.cima = 0;\n\n alumno = (struct TAlumno *) malloc(sizeof (struct TAlumno));\n pila.data[0] = alumno;\n pila.cima++;\n\n return EXIT_SUCCESS;\n}\n<|endoftext|>"} {"text":"<commit_before>#include <stdio.h> \n#include <stdlib.h>\n#include <iostream>\n#include \"SDL.h\"\n#include \"SDL_image.h\"\n\nbool done;\nint board[3][3];\nint player, winner;\nint winXSize = 300;\nint winYSize = 300;\nSDL_Texture* textureSheet[2];\t\t\/\/ Array with the textures\nSDL_Window* window;\t\t\t\t\/\/ The window\nSDL_Renderer* renderer;\t\t\t\t\/\/ The renderer\n\nvoid ApplySurface(int x, int y, SDL_Texture *tex, SDL_Renderer *rend) { \/\/ Parameters, x and y, define position in the projected window.\n\tSDL_Rect pos;\n pos.x = x;\n pos.y = y;\n\tSDL_QueryTexture(tex, NULL, NULL, &pos.w, &pos.h); \/\/ Setup ups the image and shows it.\n SDL_RenderCopy(rend, tex, NULL, &pos);\n}\n\nSDL_Texture* loadImage(char* _file) { \/\/ Returns a pointer to the texture.\n\tSDL_Texture* tex = nullptr;\n\ttex = IMG_LoadTexture(renderer, _file);\n if (tex == nullptr) { \/\/ Checks the pointer and print error.\n\t\tprintf(\"Failed to load image: %s %s\\n\", _file, IMG_GetError());\n\t\tgetchar();\n\t}\n return tex;\n}\n\nbool InitSDL() {\n\n\tif (SDL_Init(SDL_INIT_EVERYTHING) == -1){\n\t\treturn false;\n\t}\n\n\t\/\/ Creating the window\n\twindow = SDL_CreateWindow(\"Tick Tack Toe\", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, winXSize, winYSize, NULL);\n if (window == nullptr){\n\t\treturn false;\n }\n\n\t\/\/ Creating the renderer\n\trenderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);\n if (renderer == nullptr){\n\t\treturn false;\n }\n\n\t\/\/ Loads all the pictures.\n\ttextureSheet[0] = loadImage(\"blank.png\");\n\ttextureSheet[1] = loadImage(\"O.png\");\n\ttextureSheet[2] = loadImage(\"X.png\");\n\n\t\/\/ Everything went ok\n\treturn true;\n}\n\nvoid select(int &X, int &Y) { \/\/ Retrieves the clicked position and prepares it for usage.\n\n\tbool click = false;\n\tSDL_Event _event;\n\n\twhile (click == false){\n\t\twhile (SDL_PollEvent(&_event)) {\n\t\t\n\t\t\t\/\/ Get the mouse position on click.\n\t\t\tif (_event.type == SDL_MOUSEBUTTONDOWN && _event.button.button == SDL_BUTTON_LEFT){\n\t\t\t\tSDL_GetMouseState(&Y, &X);\n\t\t\t\tX = X\/100;\tY = Y\/100;\n\t\t\t\tclick = true;\n\t\t\t}\n\t\t\t\/\/ On closing the window, exit.\n\t\t\tif (_event.type == SDL_QUIT){\n\t\t\t\texit(0);\n\t\t\t}\n\t\t}\n\t}\n}\n\nvoid Draw(int _x, int _y, int _i) {\n\t\/\/ Draws to back buffer\n\tApplySurface(_x, _y, textureSheet[_i], renderer);\n}\n\nint X(int pos) {\n\treturn pos % 3;\n}\n \nint Y(int pos) {\n\treturn pos \/ 3;\n}\n\nvoid set(int pos, int who) {\n\tboard[Y(pos)][X(pos)] = who;\n}\n\nvoid set(int posX, int posY, int who) {\n\tboard[posY][posX] = who;\n}\n \nvoid unset(int pos) {\n\tboard[Y(pos)][X(pos)] = -1;\n}\n\nvoid unset(int posX, int posY) {\n\tboard[posY][posX] = -1;\n}\n\nvoid printIntro() {\n\tprintf(\" _____ _ _____ _____ \\n\");\n\tprintf(\"|_ _(_) |_ _| |_ _| \\n\");\n\tprintf(\" | | _ ___ ______| | __ _ ___ ______| | ___ ___ \\n\");\n\tprintf(\" | | | |\/ __|______| |\/ _` |\/ __|______| |\/ _ \\\\ \/ _ \\\\\\n\");\n\tprintf(\" | | | | (__ | | (_| | (__ | | (_) | __\/\\n\");\n\tprintf(\" \\\\_\/ |_|\\\\___| \\\\_\/\\\\__,_|\\\\___| \\\\_\/\\\\___\/ \\\\___|\\n\");\n\tprintf(\" \\n\");\n}\n\nvoid setup() { \/\/ Prepares the board and set ups the order of plays for the algorithm.\n\tprintf(\"Input starting player(0 = AI first, 1 = Human first): \"); \/\/ 0 = Ai first, 1 = Human first.\n\tscanf_s(\"%d\", &player); \n\tif (player != 0) {\n\t\tplayer = 1;\n\t}\n\n\tint i, j;\n\tfor (i = 0; i < 3; i++) { \n\t\tfor (j = 0; j < 3; j++) {\n\n\t\t\tboard[i][j] = -1;\n\t\t}\n\t}\n\tdone = false;\n\t\n\tprintf(\"\\n\\tStart Game...\\n\\n\\n\");\n}\n \nvoid printBoard() { \/\/ Prints the image related to the value in the array.\n\n\tint i, j;\n\tSDL_RenderClear(renderer); \/\/ Clears the screen before projecting images.\n\tfor (i = 0; i < 3; i++) {\n\t\tfor (j = 0; j < 3; j++) {\n\t\t\tDraw(i * 100, j * 100, board[i][j]+1); \/\/ Draws the designated image.\n\t\t}\n\t}\n\tSDL_RenderPresent(renderer); \/\/ Renders the prepared images.\n}\n \nint checkGame() {\n\tint i, j;\n\n\t\/\/ Checking if the game is won Vertically\n\tfor (i = 0; i < 3; i++) {\n\t\tint fl = board[i][0];\n\t\tfor (j = 1; j < 3; j++) {\n\t\t\tif (board[i][j] != fl) {\n\t\t\t\tfl = -1;\n\t\t\t}\n\t\t}\n\t\tif (fl == -1) {\n\t\t\tcontinue;\n\t\t}\n\t\twinner = fl;\n\t\treturn 1;\n\t}\n \n\t\/\/ Check if the game is won Horizontal\n\tfor (i = 0; i < 3; i++) {\n\t\tint fl = board[0][i];\n\t\tfor (j = 1; j < 3; j++) {\n\t\t\tif (board[j][i] != fl) {\n\t\t\t\tfl = -1;\n\t\t\t}\n\t\t}\n\t\tif (fl == -1) {\n\t\t\tcontinue;\n\t\t}\n\t\twinner = fl;\n\t\treturn 1;\n\t}\n\t\n\t\/\/ Checking the game for diagonal winning\n\tif (board[0][0] == board[1][1] && board[2][2] == board[1][1] && board[0][0] != -1) {\n\t\twinner = board[0][0];\n\t\treturn 1;\n\t} \n\tif (board[0][2] == board[1][1] && board[2][0] == board[1][1] && board[1][1] != -1) {\n\t\twinner = board[1][1];\n\t\treturn 1;\n\t}\n \n\t\/\/ If there is a free spot left\n\tfor (i = 0; i < 3; i++) {\n\t\tfor (j = 0; j < 3; j++) {\n\t\t\tif (board[i][j] == -1) {\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t}\n\t}\n\twinner = -1;\n\treturn 1;\n}\n \nint testGame() {\n\tint i, j;\n\n\t\/\/ Checks if there is 3 in a row Vertically, and returns the winner if it's not empty\n\tfor (i = 0; i < 3; i++) {\n\t\tint fl = board[i][0];\n\t\tfor (j = 1; j < 3; j++) {\n\t\t\tif (board[i][j] != fl) {\n\t\t\t\tfl = -1;\n\t\t\t}\n\t\t}\n\t\tif (fl == -1) {\n\t\t\tcontinue;\n\t\t}\n\treturn fl;\n\t}\n \n\t\/\/ Checks if there is 3 in a row Horizontally, and returns the winner if it's not empty\n\tfor (i = 0; i < 3; i++) {\n\n\t\tint fl = board[0][i];\n\t\tfor (j = 1; j < 3; j++) {\n\t\t\tif (board[j][i] != fl) {\n\t\t\t\tfl = -1;\n\t\t\t}\n\t\t}\n\t\tif (fl == -1) {\n\t\t\tcontinue;\n\t\t}\n\treturn fl;\n\t}\n \n\t\/\/ Returns the winner if there is 3 in a row diagonally\n\tif (board[0][0] == board[1][1] && board[2][2] == board[1][1] && board[0][0] != -1) {\n\t\treturn board[0][0];\n\t}\n\tif (board[0][2] == board[1][1] && board[2][0] == board[1][1] && board[1][1] != -1) {\n\t\treturn board[1][1];\n\t}\n\n\t\n\t\/\/ Returns 2 if there is a free square\n\tfor (i = 0; i < 3; i++) {\n\t\tfor (j = 0; j < 3; j++) {\n\t\t\tif (board[i][j] == -1){\n\t\t\t\treturn 2;\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/ Otherwise returns -1\n\treturn -1;\n}\n \nvoid playerPlay() {\n\n\t\/\/ Print the board\n\tprintBoard();\n\t\/\/ Register the spot to play in.\n\tint x; int y;\n\tdo{\n\t\tprintf(\"Click on a free square to play in.\\n\");\n\t\tselect(x, y);\n\t}while (board[y][x] != -1);\n\n\t\/\/ Change the selected square\n\tset(x, y, player);\n\tprintf(\"Played in: %d %d\\n\", x, y);\n}\n \nint AlphaBetaNegamax(int who, int &move, int a, int b) {\n\t\n\tint D = testGame(); \/\/ Checks the state of the game.\n\t\n\t\/\/ If the game have ended.\n\tif (D != 2) {\n\n\t\t\/\/ Returns a score, 0 = draw, 1 = wictory, -1 = lose\n\t\tif (D == -1) {\n\t\t\treturn 0;\n\t\t} else if (D == who) {\n\t\t\treturn 1;\n\t\t} else {\n\t\t\treturn -1;\n\t\t}\n\t}\n\n\t\/\/ If the game haven't ended.\n\tint i, flag = 0;\n\n\t\/\/ Iterate trough all the possible moves, if they're possible\n\tfor (i = 0; i < 9; i++) {\n\t\tif (board[Y(i)][X(i)] == -1) {\n\n\t\t\t\/\/ Tries a move\n\t\t\tset(i, who);\n\t\t\tint tmp;\n\t\t\tint score = -AlphaBetaNegamax(1 - who, tmp, -b, -a); \/\/ Recursive tries next move until a score is returned.\n\t\t\t\n\t\t\t\/\/ Undo the move\n\t\t\tunset(i);\n\n\t\t\t\/\/ If the result is victory or better\n\t\t\tif (score >= b) {\n\t\t\t\tmove = i;\n\t\t\t\treturn score;\n\t\t\t}\n\t\t\t\/\/ Finds the best possible solution that's not a victory.\n\t\t\tif (score > a || (score == a && flag == 0)) {\n\t\t\t\tmove = i;\n\t\t\t\ta = score;\n\t\t\t\tflag = 1;\n\t\t\t}\n\t\t}\n\t}\n\treturn a;\n}\n \nvoid aiPlay() { \/\/ Ai calculates his move and plays.\n int bx = 0;\n AlphaBetaNegamax(player, bx, -1, 1); \/\/ Calculates optimal move. Maximizes own score, minimazes human score.\n set(bx, player); \/\/ Sets the Ai's move.\n printf(\"Played in: %d %d\\n\", X(bx), Y(bx));\n}\n \nvoid play() {\n\n\t\/\/ It is the players turn\n\tif (player == 1) {\n\t\tplayerPlay();\n\t} else { \/\/ Its the AI's turn\n\t\taiPlay();\n\t}\n}\n \nvoid printOutro() {\n\t\/\/ Prints the winner of the game.\n\tif( winner == 2) {\n\t\tprintf(\"Game Winner: AI\");\n\t} else {\n\t\tprintf(\"Game Winner: Player\");\n\t}\n}\n\nint main(int argc, char* argv[]) {\n\t\/\/ Initiates SDL\n\tif(!InitSDL()) {\n\t\tprintf(\"Error!\");\n\t\treturn 0;\n\t}\n\t\n\t\/\/ Play game!\n\tbool restart;\n\tdo{\n\t\t\/\/ Initiates game\n\t\tprintIntro();\n\t\tsetup();\n\n\t\t\/\/ While game is still playing\n\t\twhile (!done) {\n\t\t\tplay();\n\t\t\tplayer = 1 - player;\n\t\t\tif (checkGame()) {\n\n\t\t\t\tdone = true;\n\t\t\t}\n\t\t\tprintBoard();\n\t\t}\n\n\t\t\/\/ After game have ended, print winner and ask for restart.\n\t\tprintOutro();\n\t\tchar holder;\n\t\tprintf(\"\\nDo you want to try again? Y\/N \");\n\t\tscanf_s(\" %c\", &holder, 1);\n\n\t\t\/\/ If yes, set the restart bool.\n\t\tif(toupper(holder) != 'Y') {\n\t\t\trestart = false;\n\t\t} else {\n\t\t\trestart = true;\n\t\t\tsystem(\"CLS\");\n\t\t}\n\t} while (restart);\n\treturn 0;\n}\n<commit_msg>Added some error outputs<commit_after>\/\/ STD\n#include <stdio.h> \n#include <stdlib.h>\n#include <iostream>\n\/\/ SDL\n#include \"SDL.h\"\n#include \"SDL_image.h\"\n\nbool done;\nint board[3][3];\nint player, winner;\nint winXSize = 300;\nint winYSize = 300;\nSDL_Texture* textureSheet[2];\t\t\/\/ Array with the textures\nSDL_Window* window;\t\t\t\t\/\/ The window\nSDL_Renderer* renderer;\t\t\t\t\/\/ The renderer\n\nvoid ApplySurface(int x, int y, SDL_Texture *tex, SDL_Renderer *rend) { \/\/ Parameters, x and y, define position in the projected window.\n\tSDL_Rect pos;\n pos.x = x;\n pos.y = y;\n\tSDL_QueryTexture(tex, NULL, NULL, &pos.w, &pos.h); \/\/ Setup ups the image and shows it.\n SDL_RenderCopy(rend, tex, NULL, &pos);\n}\n\nSDL_Texture* loadImage(char* _file) { \/\/ Returns a pointer to the texture.\n\tSDL_Texture* tex = nullptr;\n\ttex = IMG_LoadTexture(renderer, _file);\n if (tex == nullptr) { \/\/ Checks the pointer and print error.\n\t\tprintf(\"Failed to load image: %s %s\\n\", _file, IMG_GetError());\n\t\tgetchar();\n\t}\n return tex;\n}\n\nbool InitSDL() {\n\n\tif (SDL_Init(SDL_INIT_EVERYTHING) == -1){\n\t\treturn false;\n\t}\n\n\t\/\/ Creating the window\n\twindow = SDL_CreateWindow(\"Tick Tack Toe\", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, winXSize, winYSize, NULL);\n if (window == nullptr){\n\t\tprintf(\"Something went wrong, with making the window for SDL\");\n\t\tgetchar();\n\t\treturn false;\n }\n\n\t\/\/ Creating the renderer\n\trenderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);\n if (renderer == nullptr){\n\t\tprintf(\"Something went wrong, with making the renderer for SDL\");\n\t\tgetchar();\n\t\treturn false;\n }\n\n\t\/\/ Loads all the pictures.\n\ttextureSheet[0] = loadImage(\"blank.png\");\n\ttextureSheet[1] = loadImage(\"O.png\");\n\ttextureSheet[2] = loadImage(\"X.png\");\n\n\t\/\/ Everything went ok\n\treturn true;\n}\n\nvoid select(int &X, int &Y) { \/\/ Retrieves the clicked position and prepares it for usage.\n\n\tbool click = false;\n\tSDL_Event _event;\n\n\twhile (click == false){\n\t\twhile (SDL_PollEvent(&_event)) {\n\t\t\n\t\t\t\/\/ Get the mouse position on click.\n\t\t\tif (_event.type == SDL_MOUSEBUTTONDOWN && _event.button.button == SDL_BUTTON_LEFT){\n\t\t\t\tSDL_GetMouseState(&Y, &X);\n\t\t\t\tX = X\/100;\tY = Y\/100;\n\t\t\t\tclick = true;\n\t\t\t}\n\t\t\t\/\/ On closing the window, exit.\n\t\t\tif (_event.type == SDL_QUIT){\n\t\t\t\texit(0);\n\t\t\t}\n\t\t}\n\t}\n}\n\nvoid Draw(int _x, int _y, int _i) {\n\t\/\/ Draws to back buffer\n\tApplySurface(_x, _y, textureSheet[_i], renderer);\n}\n\nint X(int pos) {\n\treturn pos % 3;\n}\n \nint Y(int pos) {\n\treturn pos \/ 3;\n}\n\nvoid set(int pos, int who) {\n\tboard[Y(pos)][X(pos)] = who;\n}\n\nvoid set(int posX, int posY, int who) {\n\tboard[posY][posX] = who;\n}\n \nvoid unset(int pos) {\n\tboard[Y(pos)][X(pos)] = -1;\n}\n\nvoid unset(int posX, int posY) {\n\tboard[posY][posX] = -1;\n}\n\nvoid printIntro() {\n\tprintf(\" _____ _ _____ _____ \\n\");\n\tprintf(\"|_ _(_) |_ _| |_ _| \\n\");\n\tprintf(\" | | _ ___ ______| | __ _ ___ ______| | ___ ___ \\n\");\n\tprintf(\" | | | |\/ __|______| |\/ _` |\/ __|______| |\/ _ \\\\ \/ _ \\\\\\n\");\n\tprintf(\" | | | | (__ | | (_| | (__ | | (_) | __\/\\n\");\n\tprintf(\" \\\\_\/ |_|\\\\___| \\\\_\/\\\\__,_|\\\\___| \\\\_\/\\\\___\/ \\\\___|\\n\");\n\tprintf(\" \\n\");\n}\n\nvoid setup() { \/\/ Prepares the board and set ups the order of plays for the algorithm.\n\tprintf(\"Input starting player(0 = AI first, 1 = Human first): \"); \/\/ 0 = Ai first, 1 = Human first.\n\tscanf_s(\"%d\", &player); \n\tif (player != 0) {\n\t\tplayer = 1;\n\t}\n\n\tint i, j;\n\tfor (i = 0; i < 3; i++) { \n\t\tfor (j = 0; j < 3; j++) {\n\n\t\t\tboard[i][j] = -1;\n\t\t}\n\t}\n\tdone = false;\n\t\n\tprintf(\"\\n\\tStart Game...\\n\\n\\n\");\n}\n \nvoid printBoard() { \/\/ Prints the image related to the value in the array.\n\n\tint i, j;\n\tSDL_RenderClear(renderer); \/\/ Clears the screen before projecting images.\n\tfor (i = 0; i < 3; i++) {\n\t\tfor (j = 0; j < 3; j++) {\n\t\t\tDraw(i * 100, j * 100, board[i][j]+1); \/\/ Draws the designated image.\n\t\t}\n\t}\n\tSDL_RenderPresent(renderer); \/\/ Renders the prepared images.\n}\n \nint checkGame() {\n\tint i, j;\n\n\t\/\/ Checking if the game is won Vertically\n\tfor (i = 0; i < 3; i++) {\n\t\tint fl = board[i][0];\n\t\tfor (j = 1; j < 3; j++) {\n\t\t\tif (board[i][j] != fl) {\n\t\t\t\tfl = -1;\n\t\t\t}\n\t\t}\n\t\tif (fl == -1) {\n\t\t\tcontinue;\n\t\t}\n\t\twinner = fl;\n\t\treturn 1;\n\t}\n \n\t\/\/ Check if the game is won Horizontal\n\tfor (i = 0; i < 3; i++) {\n\t\tint fl = board[0][i];\n\t\tfor (j = 1; j < 3; j++) {\n\t\t\tif (board[j][i] != fl) {\n\t\t\t\tfl = -1;\n\t\t\t}\n\t\t}\n\t\tif (fl == -1) {\n\t\t\tcontinue;\n\t\t}\n\t\twinner = fl;\n\t\treturn 1;\n\t}\n\t\n\t\/\/ Checking the game for diagonal winning\n\tif (board[0][0] == board[1][1] && board[2][2] == board[1][1] && board[0][0] != -1) {\n\t\twinner = board[0][0];\n\t\treturn 1;\n\t} \n\tif (board[0][2] == board[1][1] && board[2][0] == board[1][1] && board[1][1] != -1) {\n\t\twinner = board[1][1];\n\t\treturn 1;\n\t}\n \n\t\/\/ If there is a free spot left\n\tfor (i = 0; i < 3; i++) {\n\t\tfor (j = 0; j < 3; j++) {\n\t\t\tif (board[i][j] == -1) {\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t}\n\t}\n\twinner = -1;\n\treturn 1;\n}\n \nint testGame() {\n\tint i, j;\n\n\t\/\/ Checks if there is 3 in a row Vertically, and returns the winner if it's not empty\n\tfor (i = 0; i < 3; i++) {\n\t\tint fl = board[i][0];\n\t\tfor (j = 1; j < 3; j++) {\n\t\t\tif (board[i][j] != fl) {\n\t\t\t\tfl = -1;\n\t\t\t}\n\t\t}\n\t\tif (fl == -1) {\n\t\t\tcontinue;\n\t\t}\n\treturn fl;\n\t}\n \n\t\/\/ Checks if there is 3 in a row Horizontally, and returns the winner if it's not empty\n\tfor (i = 0; i < 3; i++) {\n\n\t\tint fl = board[0][i];\n\t\tfor (j = 1; j < 3; j++) {\n\t\t\tif (board[j][i] != fl) {\n\t\t\t\tfl = -1;\n\t\t\t}\n\t\t}\n\t\tif (fl == -1) {\n\t\t\tcontinue;\n\t\t}\n\treturn fl;\n\t}\n \n\t\/\/ Returns the winner if there is 3 in a row diagonally\n\tif (board[0][0] == board[1][1] && board[2][2] == board[1][1] && board[0][0] != -1) {\n\t\treturn board[0][0];\n\t}\n\tif (board[0][2] == board[1][1] && board[2][0] == board[1][1] && board[1][1] != -1) {\n\t\treturn board[1][1];\n\t}\n\n\t\n\t\/\/ Returns 2 if there is a free square\n\tfor (i = 0; i < 3; i++) {\n\t\tfor (j = 0; j < 3; j++) {\n\t\t\tif (board[i][j] == -1){\n\t\t\t\treturn 2;\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/ Otherwise returns -1\n\treturn -1;\n}\n \nvoid playerPlay() {\n\n\t\/\/ Print the board\n\tprintBoard();\n\t\/\/ Register the spot to play in.\n\tint x; int y;\n\tdo{\n\t\tprintf(\"Click on a free square to play in.\\n\");\n\t\tselect(x, y);\n\t}while (board[y][x] != -1);\n\n\t\/\/ Change the selected square\n\tset(x, y, player);\n\tprintf(\"Played in: %d %d\\n\", x, y);\n}\n \nint AlphaBetaNegamax(int who, int &move, int a, int b) {\n\t\n\tint D = testGame(); \/\/ Checks the state of the game.\n\t\n\t\/\/ If the game have ended.\n\tif (D != 2) {\n\n\t\t\/\/ Returns a score, 0 = draw, 1 = wictory, -1 = lose\n\t\tif (D == -1) {\n\t\t\treturn 0;\n\t\t} else if (D == who) {\n\t\t\treturn 1;\n\t\t} else {\n\t\t\treturn -1;\n\t\t}\n\t}\n\n\t\/\/ If the game haven't ended.\n\tint i, flag = 0;\n\n\t\/\/ Iterate trough all the possible moves, if they're possible\n\tfor (i = 0; i < 9; i++) {\n\t\tif (board[Y(i)][X(i)] == -1) {\n\n\t\t\t\/\/ Tries a move\n\t\t\tset(i, who);\n\t\t\tint tmp;\n\t\t\tint score = -AlphaBetaNegamax(1 - who, tmp, -b, -a); \/\/ Recursive tries next move until a score is returned.\n\t\t\t\n\t\t\t\/\/ Undo the move\n\t\t\tunset(i);\n\n\t\t\t\/\/ If the result is victory or better\n\t\t\tif (score >= b) {\n\t\t\t\tmove = i;\n\t\t\t\treturn score;\n\t\t\t}\n\t\t\t\/\/ Finds the best possible solution that's not a victory.\n\t\t\tif (score > a || (score == a && flag == 0)) {\n\t\t\t\tmove = i;\n\t\t\t\ta = score;\n\t\t\t\tflag = 1;\n\t\t\t}\n\t\t}\n\t}\n\treturn a;\n}\n \nvoid aiPlay() { \/\/ Ai calculates his move and plays.\n int bx = 0;\n AlphaBetaNegamax(player, bx, -1, 1); \/\/ Calculates optimal move. Maximizes own score, minimazes human score.\n set(bx, player); \/\/ Sets the Ai's move.\n printf(\"Played in: %d %d\\n\", X(bx), Y(bx));\n}\n \nvoid play() {\n\n\t\/\/ It is the players turn\n\tif (player == 1) {\n\t\tplayerPlay();\n\t} else { \/\/ Its the AI's turn\n\t\taiPlay();\n\t}\n}\n \nvoid printOutro() {\n\t\/\/ Prints the winner of the game.\n\tif( winner == 2) {\n\t\tprintf(\"Game Winner: AI\");\n\t} else {\n\t\tprintf(\"Game Winner: Player\");\n\t}\n}\n\nint main(int argc, char* argv[]) {\n\t\/\/ Initiates SDL\n\tif(!InitSDL()) {\n\t\tprintf(\"Error!\");\n\t\treturn 0;\n\t}\n\t\n\t\/\/ Play game!\n\tbool restart;\n\tdo{\n\t\t\/\/ Initiates game\n\t\tprintIntro();\n\t\tsetup();\n\n\t\t\/\/ While game is still playing\n\t\twhile (!done) {\n\t\t\tplay();\n\t\t\tplayer = 1 - player;\n\t\t\tif (checkGame()) {\n\n\t\t\t\tdone = true;\n\t\t\t}\n\t\t\tprintBoard();\n\t\t}\n\n\t\t\/\/ After game have ended, print winner and ask for restart.\n\t\tprintOutro();\n\t\tchar holder;\n\t\tprintf(\"\\nDo you want to try again? Y\/N \");\n\t\tscanf_s(\" %c\", &holder, 1);\n\n\t\t\/\/ If yes, set the restart bool.\n\t\tif(toupper(holder) != 'Y') {\n\t\t\trestart = false;\n\t\t} else {\n\t\t\trestart = true;\n\t\t\tsystem(\"CLS\");\n\t\t}\n\t} while (restart);\n\treturn 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/=====================================================================\/\/\n\/*! @file\n @brief ファースト・サンプル(LED 点滅) @n\n\t\t\tRX64M, RX71M, RX72M: @n\n\t\t\t\t\t12MHz のベースクロックを使用する @n\n\t\t\t    P07 ピンにLEDを接続する @n\n\t\t\tRX65N (Renesas Envision kit RX65N): @n\n\t\t\t\t\t12MHz のベースクロックを使用する @n\n\t\t\t    P70 に接続された LED を利用する @n\n\t\t\tRX63T @n\n\t\t\t\t\t12MHz のベースクロックを使用する @n\n\t\t\t\t\tPB7 に接続された LED を利用する @n\n\t\t\tRX24T: @n\n\t\t\t\t\t10MHz のベースクロックを使用する @n\n\t\t\t    P00 ピンにLEDを接続する @n\n\t\t\tRX66T: @n\n\t\t\t\t\t10MHz のベースクロックを使用する @n\n\t\t\t    P00 ピンにLEDを接続する\n @author 平松邦仁 (hira@rvf-rc45.net)\n\t@copyright\tCopyright (C) 2018 Kunihito Hiramatsu @n\n\t\t\t\tReleased under the MIT license @n\n\t\t\t\thttps:\/\/github.com\/hirakuni45\/RX\/blob\/master\/LICENSE\n*\/\n\/\/=====================================================================\/\/\n#include \"common\/renesas.hpp\"\n\n#include \"common\/fixed_fifo.hpp\"\n#include \"common\/sci_io.hpp\"\n#include \"common\/cmt_io.hpp\"\n\n#include \"common\/format.hpp\"\n#include \"common\/input.hpp\"\n\n#include \"FreeRTOS.h\"\n#include \"task.h\"\n\n#ifdef SIG_RX64M\n\/\/ RX64Mで、GR-KAEDE の場合有効にする\n#define GR_KAEDE\n#endif\n\nnamespace {\n\n\/\/\/ ベースクリスタルの定義\n\/\/\/ LED 接続ポートの定義\n#if defined(SIG_RX71M)\n\ttypedef device::system_io<12000000> SYSTEM_IO;\n\ttypedef device::PORT<device::PORT0, device::bitpos::B7> LED;\n\ttypedef device::SCI1 SCI_CH;\n\tstatic const char* system_str_ = { \"RX71M\" };\n#elif defined(SIG_RX72M)\n\ttypedef device::system_io<12000000> SYSTEM_IO;\n\ttypedef device::PORT<device::PORT0, device::bitpos::B7> LED;\n\ttypedef device::SCI1 SCI_CH;\n\tstatic const char* system_str_ = { \"RX72M\" };\n#elif defined(SIG_RX64M)\n\ttypedef device::system_io<12000000> SYSTEM_IO;\n#ifdef GR_KAEDE\n\ttypedef device::PORT<device::PORTC, device::bitpos::B1> LED;\n\ttypedef device::PORT<device::PORTC, device::bitpos::B0> LED2;\n\ttypedef device::SCI7 SCI_CH;\n\tstatic const char* system_str_ = { \"GR-KAEDE\" };\n#else\n\ttypedef device::PORT<device::PORT0, device::bitpos::B7> LED;\n\ttypedef device::SCI1 SCI_CH;\n\tstatic const char* system_str_ = { \"RX64M\" };\n#endif\n#elif defined(SIG_RX65N)\n\ttypedef device::system_io<12000000> SYSTEM_IO;\n\ttypedef device::PORT<device::PORT7, device::bitpos::B0> LED;\n\ttypedef device::SCI9 SCI_CH;\n\tstatic const char* system_str_ = { \"RX65N\" };\n#elif defined(SIG_RX63T)\n\ttypedef device::system_io<12000000> SYSTEM_IO;\n\ttypedef device::PORT<device::PORTB, device::bitpos::B7> LED;\n\ttypedef device::SCI1 SCI_CH;\n\tstatic const char* system_str_ = { \"RX63T\" };\n#elif defined(SIG_RX24T)\n\ttypedef device::system_io<10000000> SYSTEM_IO;\n\ttypedef device::PORT<device::PORT0, device::bitpos::B0> LED;\n\ttypedef device::SCI1 SCI_CH;\n\tstatic const char* system_str_ = { \"RX24T\" };\n#elif defined(SIG_RX66T)\n\ttypedef device::system_io<10000000, 160000000> SYSTEM_IO;\n\ttypedef device::PORT<device::PORT0, device::bitpos::B0> LED;\n\ttypedef device::SCI1 SCI_CH;\n\tstatic const char* system_str_ = { \"RX66T\" };\n#endif\n\n\ttypedef device::cmt_io<device::CMT0> CMT;\n\tCMT\t\t\tcmt_;\n\n\ttypedef utils::fixed_fifo<char, 512> RXB; \/\/ RX (RECV) バッファの定義\n\ttypedef utils::fixed_fifo<char, 256> TXB; \/\/ TX (SEND) バッファの定義\n\n\ttypedef device::sci_io<SCI_CH, RXB, TXB> SCI;\n\tSCI\t\t\tsci_;\n}\n\nextern \"C\" {\n\n\t\/\/ syscalls.c から呼ばれる、標準出力(stdout, stderr)\n\tvoid sci_putch(char ch)\n\t{\n\t \tvolatile static bool lock_ = false;\n\t\twhile(lock_) ;\n\t\tlock_ = true;\n\t\tsci_.putch(ch);\n\t\tlock_ = false;\n\t}\n\n\n\tvoid sci_puts(const char* str)\n\t{\n\t\tvolatile static bool lock_ = false;\n\t\twhile(lock_) ;\n\t\tlock_ = true;\n\t\tsci_.puts(str);\n\t\tlock_ = false;\n\t}\n\n\n\t\/\/ syscalls.c から呼ばれる、標準入力(stdin)\n\tchar sci_getch(void)\n\t{\n\t\tvolatile static bool lock_ = false;\n\t\twhile(lock_) ;\n\t\tlock_ = true;\n\t\tauto ch = sci_.getch();\n\t\tlock_ = false;\n\t\treturn ch;\n\t}\n\n\n\tuint16_t sci_length()\n\t{\n\t\treturn sci_.recv_length();\n\t}\n\n\n\tvoid vApplicationMallocFailedHook(void)\n\t{\n\t\t\/* Called if a call to pvPortMalloc() fails because there is insufficient\n\t\tfree memory available in the FreeRTOS heap. pvPortMalloc() is called\n\t\tinternally by FreeRTOS API functions that create tasks, queues, software\n\t\ttimers, and semaphores. The size of the FreeRTOS heap is set by the\n\t\tconfigTOTAL_HEAP_SIZE configuration constant in FreeRTOSConfig.h. *\/\n\t\ttaskDISABLE_INTERRUPTS();\n\t\tfor( ;; );\n\t}\n\n\n\tvoid vApplicationStackOverflowHook(TaskHandle_t pxTask, char *pcTaskName)\n\t{\n\t\t( void ) pcTaskName;\n\t\t( void ) pxTask;\n\n\t\t\/* Run time stack overflow checking is performed if\n\t\tconfigCHECK_FOR_STACK_OVERFLOW is defined to 1 or 2. This hook\n\t\tfunction is called if a stack overflow is detected. *\/\n\t\ttaskDISABLE_INTERRUPTS();\n\t\tfor( ;; );\n\t}\n\n\n\tvoid vApplicationIdleHook(void)\n\t{\n\/\/\/\t\tvolatile size_t xFreeHeapSpace;\n\n\t\t\/* This is just a trivial example of an idle hook. It is called on each\n\t\tcycle of the idle task. It must *NOT* attempt to block. In this case the\n\t\tidle task just queries the amount of FreeRTOS heap that remains. See the\n\t\tmemory management section on the http:\/\/www.FreeRTOS.org web site for memory\n\t\tmanagement options. If there is a lot of heap memory free then the\n\t\tconfigTOTAL_HEAP_SIZE value in FreeRTOSConfig.h can be reduced to free up\n\t\tRAM. *\/\n\/\/\/\t\txFreeHeapSpace = xPortGetFreeHeapSize();\n\n\t\t\/* Remove compiler warning about xFreeHeapSpace being set but never used. *\/\n\/\/\/\t\t( void ) xFreeHeapSpace;\n\t}\n\n\n\tvoid vApplicationTickHook(void)\n\t{\n\t}\n\n\n\tvoid vAssertCalled(void)\n\t{\n\t\tvolatile unsigned long ul = 0;\n\n\t\ttaskENTER_CRITICAL();\n\t\t{\n\t\t\t\/* Use the debugger to set ul to a non-zero value in order to step out\n\t\t\tof this function to determine why it was called. *\/\n\t\t\twhile( ul == 0 )\n\t\t\t{\n\t\t\t\tportNOP();\n\t\t\t}\n\t\t}\n\t\ttaskEXIT_CRITICAL();\n\t}\n\n\textern void vTickISR(void);\n\textern void vSoftwareInterruptISR(void);\n\n\tvoid vApplicationSetupTimerInterrupt(void)\n\t{\n\t\tuint8_t intr = configKERNEL_INTERRUPT_PRIORITY;\n\t\tcmt_.start(configTICK_RATE_HZ, intr, vTickISR);\n\n\t\tdevice::icu_mgr::set_task(device::ICU::VECTOR::SWINT, vSoftwareInterruptISR);\n\t\tdevice::icu_mgr::set_level(device::ICU::VECTOR::SWINT, configKERNEL_INTERRUPT_PRIORITY);\n\t}\n};\n\n\nnamespace {\n\n\tvoid vTask1(void *pvParameters)\n\t{\n\t\tuint32_t loop = 0;\n\t\tuint32_t cnt = 0;\n\t\twhile(1) {\n\t\t\tvTaskEnterCritical();\n\t\t\tLED::P = !LED::P();\n\t\t\tvTaskExitCritical();\n\t\t\tvTaskDelay(500 \/ portTICK_PERIOD_MS);\n\t\t\t++loop;\n\t\t\tif(loop >= 10) {\n\t\t\t\tloop = 0;\n\t\t\t\tutils::format(\"Task1: %u\\n\") % cnt;\n\t\t\t\t++cnt;\n\t\t\t}\n\t\t}\n\t}\n\n\n\tvoid vTask2(void *pvParameters)\n\t{\n\t\tuint32_t loop = 0;\n\t\tuint32_t cnt = 0;\n\t\twhile(1) {\n\t\t\tvTaskEnterCritical();\n#ifdef GR_KAEDE\n\t\t\tLED2::P = !LED2::P();\n#else\n\t\t\tLED::P = !LED::P();\n#endif\n\t\t\tvTaskExitCritical();\n\t\t\tvTaskDelay(100 \/ portTICK_PERIOD_MS);\n\t\t\t++loop;\n\t\t\tif(loop >= 12) {\n\t\t\t\tloop = 0;\n\t\t\t\tutils::format(\"Task2: %u\\n\") % cnt;\n\t\t\t\t++cnt;\n\t\t\t}\n\t\t}\n\t}\n\n\n\tvoid vTask3(void *pvParameters)\n\t{\n\t\tuint32_t cnt = 0;\n\t\twhile(1) {\n\t\t\tutils::format(\"Task3: %u\\n\") % cnt;\n\t\t\t++cnt;\n\t\t\tvTaskDelay(1000 \/ portTICK_PERIOD_MS);\n\t\t}\n\t}\n}\n\n\nint main(int argc, char** argv);\n\nint main(int argc, char** argv)\n{\n\tSYSTEM_IO::setup_system_clock();\n\n\tLED::OUTPUT(); \/\/ LED ポートを出力に設定\n\tLED::P = 1;\t\t\/\/ Off\n#ifdef GR_KAEDE\n\tLED2::OUTPUT();\n\tLED2::P = 1;\n#endif\n\n\t{ \/\/ SCI の開始\n\t\tuint8_t intr = 2; \/\/ 割り込みレベル\n\t\tuint32_t baud = 115200; \/\/ ボーレート\n\t\tsci_.start(baud, intr);\n\t}\n\n\tauto clk = F_ICLK \/ 1000000;\n\tutils::format(\"Start FreeRTOS sample for '%s' %d[MHz]\\n\") % system_str_ % clk;\n\n\t{\n\t\tuint32_t stack_size = 512;\n\t\tvoid* param = nullptr;\n\t\tuint32_t prio = 1;\n\t\txTaskCreate(vTask1, \"Task1\", stack_size, param, prio, nullptr);\n\t\txTaskCreate(vTask2, \"Task2\", stack_size, param, prio, nullptr);\n\t\txTaskCreate(vTask3, \"Task3\", stack_size, param, prio, nullptr);\n\t}\n\n\tvTaskStartScheduler();\n\n\t\/\/ タスクスケジューラーが正常なら実行されない\n\twhile(1) {\n\t\tutils::delay::milli_second(250);\n\t\tLED::P = !LED::P();\n\t\tutils::delay::milli_second(250);\n\t\tLED::P = !LED::P();\n\t}\n}\n<commit_msg>Update: cleanup<commit_after>\/\/=====================================================================\/\/\n\/*! @file\n @brief FreeRTOS Simple Sample(Flash LED, Output SCI) @n\n\t\t\tRX64M, RX71M, RX72M: @n\n\t\t\t\t\t12MHz のベースクロックを使用する @n\n\t\t\t    P07 ピンにLEDを接続する @n\n\t\t\tRX65N (Renesas Envision kit RX65N): @n\n\t\t\t\t\t12MHz のベースクロックを使用する @n\n\t\t\t    P70 に接続された LED を利用する @n\n\t\t\tRX63T @n\n\t\t\t\t\t12MHz のベースクロックを使用する @n\n\t\t\t\t\tPB7 に接続された LED を利用する @n\n\t\t\tRX24T: @n\n\t\t\t\t\t10MHz のベースクロックを使用する @n\n\t\t\t    P00 ピンにLEDを接続する @n\n\t\t\tRX66T: @n\n\t\t\t\t\t10MHz のベースクロックを使用する @n\n\t\t\t    P00 ピンにLEDを接続する\n @author 平松邦仁 (hira@rvf-rc45.net)\n\t@copyright\tCopyright (C) 2018 Kunihito Hiramatsu @n\n\t\t\t\tReleased under the MIT license @n\n\t\t\t\thttps:\/\/github.com\/hirakuni45\/RX\/blob\/master\/LICENSE\n*\/\n\/\/=====================================================================\/\/\n#include \"common\/renesas.hpp\"\n\n#include \"common\/fixed_fifo.hpp\"\n#include \"common\/sci_io.hpp\"\n#include \"common\/cmt_io.hpp\"\n\n#include \"common\/format.hpp\"\n#include \"common\/input.hpp\"\n\n#include \"FreeRTOS.h\"\n#include \"task.h\"\n\n#ifdef SIG_RX64M\n\/\/ RX64Mで、GR-KAEDE の場合有効にする\n\/\/ #define GR_KAEDE\n#endif\n\nnamespace {\n\n\/\/\/ ベースクリスタルの定義\n\/\/\/ LED 接続ポートの定義\n#if defined(SIG_RX71M)\n\ttypedef device::system_io<12000000> SYSTEM_IO;\n\ttypedef device::PORT<device::PORT0, device::bitpos::B7> LED;\n\ttypedef device::SCI1 SCI_CH;\n\tstatic const char* system_str_ = { \"RX71M\" };\n#elif defined(SIG_RX72M)\n\ttypedef device::system_io<12000000> SYSTEM_IO;\n\ttypedef device::PORT<device::PORT0, device::bitpos::B7> LED;\n\ttypedef device::SCI1 SCI_CH;\n\tstatic const char* system_str_ = { \"RX72M\" };\n#elif defined(SIG_RX64M)\n\ttypedef device::system_io<12000000> SYSTEM_IO;\n#ifdef GR_KAEDE\n\ttypedef device::PORT<device::PORTC, device::bitpos::B1> LED;\n\ttypedef device::PORT<device::PORTC, device::bitpos::B0> LED2;\n\ttypedef device::SCI7 SCI_CH;\n\tstatic const char* system_str_ = { \"GR-KAEDE\" };\n#else\n\ttypedef device::PORT<device::PORT0, device::bitpos::B7> LED;\n\ttypedef device::SCI1 SCI_CH;\n\tstatic const char* system_str_ = { \"RX64M\" };\n#endif\n#elif defined(SIG_RX65N)\n\ttypedef device::system_io<12000000> SYSTEM_IO;\n\ttypedef device::PORT<device::PORT7, device::bitpos::B0> LED;\n\ttypedef device::SCI9 SCI_CH;\n\tstatic const char* system_str_ = { \"RX65N\" };\n#elif defined(SIG_RX63T)\n\ttypedef device::system_io<12000000> SYSTEM_IO;\n\ttypedef device::PORT<device::PORTB, device::bitpos::B7> LED;\n\ttypedef device::SCI1 SCI_CH;\n\tstatic const char* system_str_ = { \"RX63T\" };\n#elif defined(SIG_RX24T)\n\ttypedef device::system_io<10000000> SYSTEM_IO;\n\ttypedef device::PORT<device::PORT0, device::bitpos::B0> LED;\n\ttypedef device::SCI1 SCI_CH;\n\tstatic const char* system_str_ = { \"RX24T\" };\n#elif defined(SIG_RX66T)\n\ttypedef device::system_io<10000000, 160000000> SYSTEM_IO;\n\ttypedef device::PORT<device::PORT0, device::bitpos::B0> LED;\n\ttypedef device::SCI1 SCI_CH;\n\tstatic const char* system_str_ = { \"RX66T\" };\n#endif\n\n\ttypedef device::cmt_io<device::CMT0> CMT;\n\tCMT\t\t\tcmt_;\n\n\ttypedef utils::fixed_fifo<char, 512> RXB; \/\/ RX (RECV) バッファの定義\n\ttypedef utils::fixed_fifo<char, 256> TXB; \/\/ TX (SEND) バッファの定義\n\n\ttypedef device::sci_io<SCI_CH, RXB, TXB> SCI;\n\tSCI\t\t\tsci_;\n}\n\nextern \"C\" {\n\n\t\/\/ syscalls.c から呼ばれる、標準出力(stdout, stderr)\n\tvoid sci_putch(char ch)\n\t{\n\t\tstatic volatile bool lock_ = false;\n\t\twhile(lock_) ;\n\t\tlock_ = true;\n\t\tsci_.putch(ch);\n\t\tlock_ = false;\n\t}\n\n\n\tvoid sci_puts(const char* str)\n\t{\n\t\tstatic volatile bool lock_ = false;\n\t\twhile(lock_) ;\n\t\tlock_ = true;\n\t\tsci_.puts(str);\n\t\tlock_ = false;\n\t}\n\n\n\t\/\/ syscalls.c から呼ばれる、標準入力(stdin)\n\tchar sci_getch(void)\n\t{\n\t\tstatic volatile bool lock_ = false;\n\t\twhile(lock_) ;\n\t\tlock_ = true;\n\t\tauto ch = sci_.getch();\n\t\tlock_ = false;\n\t\treturn ch;\n\t}\n\n\n\tuint16_t sci_length()\n\t{\n\t\treturn sci_.recv_length();\n\t}\n\n\n\tvoid vApplicationMallocFailedHook(void)\n\t{\n\t\t\/* Called if a call to pvPortMalloc() fails because there is insufficient\n\t\tfree memory available in the FreeRTOS heap. pvPortMalloc() is called\n\t\tinternally by FreeRTOS API functions that create tasks, queues, software\n\t\ttimers, and semaphores. The size of the FreeRTOS heap is set by the\n\t\tconfigTOTAL_HEAP_SIZE configuration constant in FreeRTOSConfig.h. *\/\n\t\ttaskDISABLE_INTERRUPTS();\n\t\tfor( ;; );\n\t}\n\n\n\tvoid vApplicationStackOverflowHook(TaskHandle_t pxTask, char *pcTaskName)\n\t{\n\t\t( void ) pcTaskName;\n\t\t( void ) pxTask;\n\n\t\t\/* Run time stack overflow checking is performed if\n\t\tconfigCHECK_FOR_STACK_OVERFLOW is defined to 1 or 2. This hook\n\t\tfunction is called if a stack overflow is detected. *\/\n\t\ttaskDISABLE_INTERRUPTS();\n\t\tfor( ;; );\n\t}\n\n\n\tvoid vApplicationIdleHook(void)\n\t{\n\/\/\/\t\tvolatile size_t xFreeHeapSpace;\n\n\t\t\/* This is just a trivial example of an idle hook. It is called on each\n\t\tcycle of the idle task. It must *NOT* attempt to block. In this case the\n\t\tidle task just queries the amount of FreeRTOS heap that remains. See the\n\t\tmemory management section on the http:\/\/www.FreeRTOS.org web site for memory\n\t\tmanagement options. If there is a lot of heap memory free then the\n\t\tconfigTOTAL_HEAP_SIZE value in FreeRTOSConfig.h can be reduced to free up\n\t\tRAM. *\/\n\/\/\/\t\txFreeHeapSpace = xPortGetFreeHeapSize();\n\n\t\t\/* Remove compiler warning about xFreeHeapSpace being set but never used. *\/\n\/\/\/\t\t( void ) xFreeHeapSpace;\n\t}\n\n\n\tvoid vApplicationTickHook(void)\n\t{\n\t}\n\n\n\tvoid vAssertCalled(void)\n\t{\n\t\tvolatile unsigned long ul = 0;\n\n\t\ttaskENTER_CRITICAL();\n\t\t{\n\t\t\t\/* Use the debugger to set ul to a non-zero value in order to step out\n\t\t\tof this function to determine why it was called. *\/\n\t\t\twhile( ul == 0 )\n\t\t\t{\n\t\t\t\tportNOP();\n\t\t\t}\n\t\t}\n\t\ttaskEXIT_CRITICAL();\n\t}\n\n\textern void vTickISR(void);\n\textern void vSoftwareInterruptISR(void);\n\n\tvoid vApplicationSetupTimerInterrupt(void)\n\t{\n\t\tuint8_t intr = configKERNEL_INTERRUPT_PRIORITY;\n\t\tcmt_.start(configTICK_RATE_HZ, intr, vTickISR);\n\n\t\tdevice::icu_mgr::set_task(device::ICU::VECTOR::SWINT, vSoftwareInterruptISR);\n\t\tdevice::icu_mgr::set_level(device::ICU::VECTOR::SWINT, configKERNEL_INTERRUPT_PRIORITY);\n\t}\n};\n\n\nnamespace {\n\n\tvoid vTask1(void *pvParameters)\n\t{\n\t\tuint32_t loop = 0;\n\t\tuint32_t cnt = 0;\n\t\twhile(1) {\n\t\t\tvTaskEnterCritical();\n\t\t\tLED::P = !LED::P();\n\t\t\tvTaskExitCritical();\n\t\t\tvTaskDelay(500 \/ portTICK_PERIOD_MS);\n\t\t\t++loop;\n\t\t\tif(loop >= 10) {\n\t\t\t\tloop = 0;\n\t\t\t\tutils::format(\"Task1: %u\\n\") % cnt;\n\t\t\t\t++cnt;\n\t\t\t}\n\t\t}\n\t}\n\n\n\tvoid vTask2(void *pvParameters)\n\t{\n\t\tuint32_t loop = 0;\n\t\tuint32_t cnt = 0;\n\t\twhile(1) {\n\t\t\tvTaskEnterCritical();\n#ifdef GR_KAEDE\n\t\t\tLED2::P = !LED2::P();\n#else\n\t\t\tLED::P = !LED::P();\n#endif\n\t\t\tvTaskExitCritical();\n\t\t\tvTaskDelay(100 \/ portTICK_PERIOD_MS);\n\t\t\t++loop;\n\t\t\tif(loop >= 12) {\n\t\t\t\tloop = 0;\n\t\t\t\tutils::format(\"Task2: %u\\n\") % cnt;\n\t\t\t\t++cnt;\n\t\t\t}\n\t\t}\n\t}\n\n\n\tvoid vTask3(void *pvParameters)\n\t{\n\t\tuint32_t cnt = 0;\n\t\twhile(1) {\n\t\t\tutils::format(\"Task3: %u\\n\") % cnt;\n\t\t\t++cnt;\n\t\t\tvTaskDelay(1000 \/ portTICK_PERIOD_MS);\n\t\t}\n\t}\n}\n\n\nint main(int argc, char** argv);\n\nint main(int argc, char** argv)\n{\n\tSYSTEM_IO::setup_system_clock();\n\n\tLED::OUTPUT(); \/\/ LED ポートを出力に設定\n\tLED::P = 1;\t\t\/\/ Off\n#ifdef GR_KAEDE\n\tLED2::OUTPUT();\n\tLED2::P = 1;\n#endif\n\n\t{ \/\/ SCI の開始\n\t\tuint8_t intr = 2; \/\/ 割り込みレベル\n\t\tuint32_t baud = 115200; \/\/ ボーレート\n\t\tsci_.start(baud, intr);\n\t}\n\n\tauto clk = F_ICLK \/ 1000000;\n\tutils::format(\"Start FreeRTOS sample for '%s' %d[MHz]\\n\") % system_str_ % clk;\n\n\t{\n\t\tuint32_t stack_size = 512;\n\t\tvoid* param = nullptr;\n\t\tuint32_t prio = 1;\n\t\txTaskCreate(vTask1, \"Task1\", stack_size, param, prio, nullptr);\n\t\txTaskCreate(vTask2, \"Task2\", stack_size, param, prio, nullptr);\n\t\txTaskCreate(vTask3, \"Task3\", stack_size, param, prio, nullptr);\n\t}\n\n\tvTaskStartScheduler();\n\n\t\/\/ タスクスケジューラーが正常なら実行されない\n\twhile(1) {\n\t\tutils::delay::milli_second(250);\n\t\tLED::P = !LED::P();\n\t\tutils::delay::milli_second(250);\n\t\tLED::P = !LED::P();\n\t}\n}\n<|endoftext|>"} {"text":"<commit_before>#ifndef SILICIUM_STEADY_CLOCK_HPP\n#define SILICIUM_STEADY_CLOCK_HPP\n\n#include <silicium\/config.hpp>\n#include <boost\/chrono\/system_clocks.hpp>\n#include <chrono>\n\nnamespace Si\n{\n#if defined(BOOST_CHRONO_HAS_STEADY_CLOCK)\n#define SILICIUM_HAS_STEADY_CLOCK 1\n\tusing boost::chrono::steady_clock;\n\tnamespace chrono = boost::chrono;\n#elif !SILICIUM_GCC46\n#define SILICIUM_HAS_STEADY_CLOCK 1\n\tusing std::chrono::steady_clock;\n\tnamespace chrono = std::chrono;\n#else\n#define SILICIUM_HAS_STEADY_CLOCK 0\n\tnamespace chrono = boost::chrono;\n#endif\n\n#if SILICIUM_HAS_STEADY_CLOCK\n\ttypedef steady_clock steady_clock_if_available;\n#else\n\ttypedef boost::chrono::system_clock steady_clock_if_available;\n#endif\n}\n\n#endif\n<commit_msg>detect boost::chrono::steady_clock correctly<commit_after>#ifndef SILICIUM_STEADY_CLOCK_HPP\n#define SILICIUM_STEADY_CLOCK_HPP\n\n#include <silicium\/config.hpp>\n#include <boost\/chrono\/system_clocks.hpp>\n#include <chrono>\n\nnamespace Si\n{\n#if defined(BOOST_CHRONO_HAS_CLOCK_STEADY)\n#define SILICIUM_HAS_STEADY_CLOCK 1\n\tusing boost::chrono::steady_clock;\n\tnamespace chrono = boost::chrono;\n#elif !SILICIUM_GCC46\n#define SILICIUM_HAS_STEADY_CLOCK 1\n\tusing std::chrono::steady_clock;\n\tnamespace chrono = std::chrono;\n#else\n#define SILICIUM_HAS_STEADY_CLOCK 0\n\tnamespace chrono = boost::chrono;\n#endif\n\n#if SILICIUM_HAS_STEADY_CLOCK\n\ttypedef steady_clock steady_clock_if_available;\n#else\n\ttypedef boost::chrono::system_clock steady_clock_if_available;\n#endif\n}\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>#include \"testApp.h\"\n\n#include \"ofxAlembic.h\"\n\nofEasyCam cam;\n\nofxAlembic::Reader abc;\n\n\/\/--------------------------------------------------------------\nvoid testApp::setup()\n{\n\tofSetVerticalSync(true);\n\tofSetFrameRate(60);\n\tofBackground(0);\n\t\n\tstring path = \"sample.abc\";\n\t\n\t{\n\t\tofxAlembic::Writer writer;\n\t\t\n\t\tif (writer.open(path, 30)) \/\/ export at 30fps\n\t\t{\n\t\t\tfor (int f = 0; f < 60; f++)\n\t\t\t{\n\t\t\t\t\/\/ points\n\t\t\t\t{\n\t\t\t\t\tvector<ofVec3f> points;\n\t\t\t\t\t\n\t\t\t\t\tfor (int i = 0; i < 10; i++)\n\t\t\t\t\t{\n\t\t\t\t\t\tofVec3f p;\n\t\t\t\t\t\tp.x = ofRandom(-300, 300);\n\t\t\t\t\t\tp.y = ofRandom(-300, 300);\n\t\t\t\t\t\tp.z = ofRandom(-300, 300);\n\t\t\t\t\t\tpoints.push_back(p);\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\twriter.addPoints(\"\/points\", points);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t\/\/ curves\n\t\t\t\t{\n\t\t\t\t\tvector<ofPolyline> curves;\n\t\t\t\t\t\n\t\t\t\t\tfor (int i = 0; i < 10; i++)\n\t\t\t\t\t{\n\t\t\t\t\t\tofPolyline poly;\n\t\t\t\t\t\t\n\t\t\t\t\t\tfor (int n = 0; n < 100; n++)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tofVec3f v;\n\t\t\t\t\t\t\tv.x = ofSignedNoise(1, 0, 0, n * 0.01 + f * 10 + i) * 300;\n\t\t\t\t\t\t\tv.y = ofSignedNoise(0, 1, 0, n * 0.01 + f * 10 + i) * 300;\n\t\t\t\t\t\t\tv.z = ofSignedNoise(0, 0, 1, n * 0.01 + f * 10 + i) * 300;\n\t\t\t\t\t\t\tpoly.addVertex(v);\n\t\t\t\t\t\t}\n\t\t\t\t\t\t\n\t\t\t\t\t\tcurves.push_back(poly);\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\twriter.addCurves(\"\/curves\", curves);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t\/\/ mesh\n\t\t\t\t{\n\t\t\t\t\tofMesh mesh;\n\t\t\t\t\t\n\t\t\t\t\tint num = ofRandom(1, 10) * 3;\n\t\t\t\t\t\n\t\t\t\t\tfor (int i = 0; i < num; i++)\n\t\t\t\t\t{\n\t\t\t\t\t\tofVec3f p;\n\t\t\t\t\t\tp.x = ofRandom(-300, 300);\n\t\t\t\t\t\tp.y = ofRandom(-300, 300);\n\t\t\t\t\t\tp.z = ofRandom(-300, 300);\n\t\t\t\t\t\tmesh.addVertex(p);\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\twriter.addPolyMesh(\"\/polymesh\", mesh);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t\n\tabc.open(path);\n\t\n\tabc.dumpNames();\n}\n\nvoid testApp::exit()\n{\n\tabc.close();\n}\n\n\/\/--------------------------------------------------------------\nvoid testApp::update()\n{\n\tfloat t = fmodf(ofGetElapsedTimef(), abc.getMaxTime());\n\tabc.setTime(t);\n}\n\n\/\/--------------------------------------------------------------\nvoid testApp::draw()\n{\n\tcam.begin();\n\n\tglPointSize(4);\n\t\n\t{\n\t\tofMesh mesh;\n\t\tabc.get(\"\/polymesh\", mesh);\n\t\t\n\t\tofSetColor(255, 0, 0);\n\t\tmesh.draw();\n\t}\n\n\t{\n\t\tvector<ofVec3f> points;\n\t\tabc.get(\"\/points\", points);\n\t\t\n\t\tofSetColor(0, 255, 0);\n\t\tglBegin(GL_POINTS);\n\t\tfor (int i = 0; i < points.size(); i++)\n\t\t\tglVertex3fv(points[i].getPtr());\n\t\tglEnd();\n\t}\n\n\t{\n\t\tvector<ofPolyline> curves;\n\t\tabc.get(\"\/curves\", curves);\n\t\t\n\t\tofSetColor(0, 0, 255);\n\t\tfor (int i = 0; i < curves.size(); i++)\n\t\t\tcurves[i].draw();\n\t}\n\n\t\/\/ or simply, abc.draw();\n\t\n\tcam.end();\n\t\n\tofSetColor(255);\n\t\n\tofDrawBitmapString(ofToString(abc.getTime()) + \"\/\" + ofToString(abc.getMaxTime()), 10, 20);\n}\n\n\/\/--------------------------------------------------------------\nvoid testApp::keyPressed(int key)\n{\n\t\n}\n\n\/\/--------------------------------------------------------------\nvoid testApp::keyReleased(int key)\n{\n\n}\n\n\/\/--------------------------------------------------------------\nvoid testApp::mouseMoved(int x, int y)\n{\n\n}\n\n\/\/--------------------------------------------------------------\nvoid testApp::mouseDragged(int x, int y, int button)\n{\n\n}\n\n\/\/--------------------------------------------------------------\nvoid testApp::mousePressed(int x, int y, int button)\n{\n\n}\n\n\/\/--------------------------------------------------------------\nvoid testApp::mouseReleased(int x, int y, int button)\n{\n\n}\n\n\/\/--------------------------------------------------------------\nvoid testApp::windowResized(int w, int h)\n{\n\n}\n\n\/\/--------------------------------------------------------------\nvoid testApp::gotMessage(ofMessage msg)\n{\n\n}\n\n\/\/--------------------------------------------------------------\nvoid testApp::dragEvent(ofDragInfo dragInfo)\n{\n\n}<commit_msg>Add XForm export example<commit_after>#include \"testApp.h\"\n\n#include \"ofxAlembic.h\"\n\nofEasyCam cam;\n\nofxAlembic::Reader abc;\n\n\/\/--------------------------------------------------------------\nvoid testApp::setup()\n{\n\tofSetVerticalSync(true);\n\tofSetFrameRate(60);\n\tofBackground(0);\n\t\n\tstring path = \"sample.abc\";\n\t\n\t{\n\t\tofxAlembic::Writer writer;\n\t\t\n\t\tif (writer.open(path, 30)) \/\/ export at 30fps\n\t\t{\n\t\t\tfor (int f = 0; f < 60; f++)\n\t\t\t{\n\t\t\t\t\/\/ points\n\t\t\t\t{\n\t\t\t\t\tvector<ofVec3f> points;\n\t\t\t\t\t\n\t\t\t\t\tfor (int i = 0; i < 10; i++)\n\t\t\t\t\t{\n\t\t\t\t\t\tofVec3f p;\n\t\t\t\t\t\tp.x = ofRandom(-300, 300);\n\t\t\t\t\t\tp.y = ofRandom(-300, 300);\n\t\t\t\t\t\tp.z = ofRandom(-300, 300);\n\t\t\t\t\t\tpoints.push_back(p);\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\twriter.addPoints(\"\/points\", points);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t\/\/ curves\n\t\t\t\t{\n\t\t\t\t\tvector<ofPolyline> curves;\n\t\t\t\t\t\n\t\t\t\t\tfor (int i = 0; i < 10; i++)\n\t\t\t\t\t{\n\t\t\t\t\t\tofPolyline poly;\n\t\t\t\t\t\t\n\t\t\t\t\t\tfor (int n = 0; n < 100; n++)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tofVec3f v;\n\t\t\t\t\t\t\tv.x = ofSignedNoise(1, 0, 0, n * 0.01 + f * 10 + i) * 300;\n\t\t\t\t\t\t\tv.y = ofSignedNoise(0, 1, 0, n * 0.01 + f * 10 + i) * 300;\n\t\t\t\t\t\t\tv.z = ofSignedNoise(0, 0, 1, n * 0.01 + f * 10 + i) * 300;\n\t\t\t\t\t\t\tpoly.addVertex(v);\n\t\t\t\t\t\t}\n\t\t\t\t\t\t\n\t\t\t\t\t\tcurves.push_back(poly);\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\twriter.addCurves(\"\/curves\", curves);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t\/\/ mesh\n\t\t\t\t{\n\t\t\t\t\tofMesh mesh;\n\t\t\t\t\t\n\t\t\t\t\tint num = ofRandom(1, 10) * 3;\n\t\t\t\t\t\n\t\t\t\t\tfor (int i = 0; i < num; i++)\n\t\t\t\t\t{\n\t\t\t\t\t\tofVec3f p;\n\t\t\t\t\t\tp.x = ofRandom(-300, 300);\n\t\t\t\t\t\tp.y = ofRandom(-300, 300);\n\t\t\t\t\t\tp.z = ofRandom(-300, 300);\n\t\t\t\t\t\tmesh.addVertex(p);\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\twriter.addPolyMesh(\"\/polymesh\", mesh);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t\/\/ mesh with xform\n\t\t\t\t{\n\t\t\t\t\tofMatrix4x4 mat;\n\t\t\t\t\tmat.glRotate(f * 5, 0, 1, 0);\n\t\t\t\t\twriter.addXform(\"\/box\", mat);\n\t\t\t\t\t\n\t\t\t\t\tif (f == 0)\n\t\t\t\t\t{\n\t\t\t\t\t\t\/\/ write only first frame\n\t\t\t\t\t\t\n\t\t\t\t\t\tofBoxPrimitive box;\n\t\t\t\t\t\tbox.set(100);\n\t\t\t\t\t\twriter.addPolyMesh(\"\/box\/boxShape\", box.getMesh());\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t\n\tabc.open(path);\n\t\n\tabc.dumpNames();\n}\n\nvoid testApp::exit()\n{\n\tabc.close();\n}\n\n\/\/--------------------------------------------------------------\nvoid testApp::update()\n{\n\tfloat t = fmodf(ofGetElapsedTimef(), abc.getMaxTime());\n\tabc.setTime(t);\n}\n\n\/\/--------------------------------------------------------------\nvoid testApp::draw()\n{\n\tcam.begin();\n\n\tglPointSize(4);\n\t\n\t{\n\t\tofMesh mesh;\n\t\tabc.get(\"\/polymesh\", mesh);\n\t\t\n\t\tofSetColor(255, 0, 0);\n\t\tmesh.draw();\n\t}\n\n\t{\n\t\tvector<ofVec3f> points;\n\t\tabc.get(\"\/points\", points);\n\t\t\n\t\tofSetColor(0, 255, 0);\n\t\tglBegin(GL_POINTS);\n\t\tfor (int i = 0; i < points.size(); i++)\n\t\t\tglVertex3fv(points[i].getPtr());\n\t\tglEnd();\n\t}\n\n\t{\n\t\tvector<ofPolyline> curves;\n\t\tabc.get(\"\/curves\", curves);\n\t\t\n\t\tofSetColor(0, 0, 255);\n\t\tfor (int i = 0; i < curves.size(); i++)\n\t\t\tcurves[i].draw();\n\t}\n\n\t{\n\t\tofSetColor(255, 255, 0);\n\t\tabc.get(\"\/box\")->draw(); \/\/ draw box with xform\n\t}\n\n\t\/\/ or simply, abc.draw();\n\t\n\tcam.end();\n\t\n\tofSetColor(255);\n\t\n\tofDrawBitmapString(ofToString(abc.getTime()) + \"\/\" + ofToString(abc.getMaxTime()), 10, 20);\n}\n\n\/\/--------------------------------------------------------------\nvoid testApp::keyPressed(int key)\n{\n\t\n}\n\n\/\/--------------------------------------------------------------\nvoid testApp::keyReleased(int key)\n{\n\n}\n\n\/\/--------------------------------------------------------------\nvoid testApp::mouseMoved(int x, int y)\n{\n\n}\n\n\/\/--------------------------------------------------------------\nvoid testApp::mouseDragged(int x, int y, int button)\n{\n\n}\n\n\/\/--------------------------------------------------------------\nvoid testApp::mousePressed(int x, int y, int button)\n{\n\n}\n\n\/\/--------------------------------------------------------------\nvoid testApp::mouseReleased(int x, int y, int button)\n{\n\n}\n\n\/\/--------------------------------------------------------------\nvoid testApp::windowResized(int w, int h)\n{\n\n}\n\n\/\/--------------------------------------------------------------\nvoid testApp::gotMessage(ofMessage msg)\n{\n\n}\n\n\/\/--------------------------------------------------------------\nvoid testApp::dragEvent(ofDragInfo dragInfo)\n{\n\n}<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2016 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"ozone\/ui\/desktop_aura\/desktop_factory_ozone_wayland.h\"\n\n#include \"ozone\/ui\/desktop_aura\/desktop_screen_wayland.h\"\n#include \"ozone\/ui\/desktop_aura\/desktop_window_tree_host_ozone.cc\"\n\nnamespace views {\n\nDesktopWindowTreeHost* DesktopFactoryOzoneWayland::CreateWindowTreeHost(\n internal::NativeWidgetDelegate* native_widget_delegate,\n DesktopNativeWidgetAura* desktop_native_widget_aura) {\n return new DesktopWindowTreeHostOzone(native_widget_delegate,\n desktop_native_widget_aura);\n}\n\ngfx::Screen* DesktopFactoryOzoneWayland::CreateDesktopScreen() {\n return new DesktopScreenWayland;\n}\n\nDesktopFactoryOzone* CreateDesktopFactoryOzoneWayland() {\n return new DesktopFactoryOzoneWayland;\n}\n\n} \/\/ namespace views\n<commit_msg>Fix multiple definition link error<commit_after>\/\/ Copyright 2016 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"ozone\/ui\/desktop_aura\/desktop_factory_ozone_wayland.h\"\n\n#include \"ozone\/ui\/desktop_aura\/desktop_screen_wayland.h\"\n#include \"ozone\/ui\/desktop_aura\/desktop_window_tree_host_ozone.h\"\n\nnamespace views {\n\nDesktopWindowTreeHost* DesktopFactoryOzoneWayland::CreateWindowTreeHost(\n internal::NativeWidgetDelegate* native_widget_delegate,\n DesktopNativeWidgetAura* desktop_native_widget_aura) {\n return new DesktopWindowTreeHostOzone(native_widget_delegate,\n desktop_native_widget_aura);\n}\n\ngfx::Screen* DesktopFactoryOzoneWayland::CreateDesktopScreen() {\n return new DesktopScreenWayland;\n}\n\nDesktopFactoryOzone* CreateDesktopFactoryOzoneWayland() {\n return new DesktopFactoryOzoneWayland;\n}\n\n} \/\/ namespace views\n<|endoftext|>"} {"text":"<commit_before>\/*\n * OgreBitesConfigDialog.cpp\n *\n * Created on: 06.12.2016\n * Author: pavel\n *\/\n\n#include \"OgreBitesConfigDialog.h\"\n#include \"OgreConfigDialogImp.h\"\n\nnamespace OgreBites {\n Ogre::ConfigDialog* getNativeConfigDialog() {\n#if OGRE_PLATFORM == OGRE_PLATFORM_LINUX || OGRE_PLATFORM == OGRE_PLATFORM_WIN32 || OGRE_PLATFORM == OGRE_PLATFORM_APPLE\n static ConfigDialog dialog;\n return &dialog;\n#else\n return NULL;\n#endif\n }\n} \/* namespace OgreBites *\/\n<commit_msg>Bites: disable ConfigDialog on MinGW until we have resolved #1064<commit_after>\/*\n * OgreBitesConfigDialog.cpp\n *\n * Created on: 06.12.2016\n * Author: pavel\n *\/\n\n#include \"OgreBitesConfigDialog.h\"\n#include \"OgreConfigDialogImp.h\"\n\nnamespace OgreBites {\n Ogre::ConfigDialog* getNativeConfigDialog() {\n#if OGRE_PLATFORM == OGRE_PLATFORM_LINUX || (OGRE_PLATFORM == OGRE_PLATFORM_WIN32 && !defined(__MINGW32__)) || OGRE_PLATFORM == OGRE_PLATFORM_APPLE\n static ConfigDialog dialog;\n return &dialog;\n#else\n return NULL;\n#endif\n }\n} \/* namespace OgreBites *\/\n<|endoftext|>"} {"text":"<commit_before>\/\/==============================================================================\r\n\/\/ Single cell simulation view graph panel widget\r\n\/\/==============================================================================\r\n\r\n#include \"singlecellsimulationviewgraphpanelplotwidget.h\"\r\n#include \"singlecellsimulationviewgraphpanelwidget.h\"\r\n\r\n\/\/==============================================================================\r\n\r\n#include <QHBoxLayout>\r\n#include <QMouseEvent>\r\n\r\n\/\/==============================================================================\r\n\r\n#include \"qwt_plot_curve.h\"\r\n\r\n\/\/==============================================================================\r\n\r\n#include \"ui_singlecellsimulationviewgraphpanelwidget.h\"\r\n\r\n\/\/==============================================================================\r\n\r\nnamespace OpenCOR {\r\nnamespace SingleCellSimulationView {\r\n\r\n\/\/==============================================================================\r\n\r\nSingleCellSimulationViewGraphPanelWidget::SingleCellSimulationViewGraphPanelWidget(QWidget *pParent) :\r\n Widget(pParent),\r\n mGui(new Ui::SingleCellSimulationViewGraphPanelWidget),\r\n mActive(false)\r\n{\r\n \/\/ Set up the GUI\r\n\r\n mGui->setupUi(this);\r\n\r\n \/\/ Create, customise and add an inactive marker to our layout\r\n\r\n static const int MarkerWidth = 3;\r\n\r\n mMarker = new QFrame(this);\r\n\r\n mMarker->setFrameShape(QFrame::VLine);\r\n mMarker->setLineWidth(MarkerWidth);\r\n mMarker->setMinimumWidth(MarkerWidth);\r\n\r\n setActive(false);\r\n\r\n mGui->layout->addWidget(mMarker);\r\n\r\n \/\/ Create and add a plot widget to our layout\r\n\r\n mPlot = new SingleCellSimulationViewGraphPanelPlotWidget(this);\r\n\r\n mGui->layout->addWidget(mPlot);\r\n\r\n \/\/ Allow the graph panel to be of any vertical size\r\n\r\n setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Ignored);\r\n}\r\n\r\n\/\/==============================================================================\r\n\r\nSingleCellSimulationViewGraphPanelWidget::~SingleCellSimulationViewGraphPanelWidget()\r\n{\r\n \/\/ Delete the GUI\r\n\r\n delete mGui;\r\n}\r\n\r\n\/\/==============================================================================\r\n\r\nvoid SingleCellSimulationViewGraphPanelWidget::changeEvent(QEvent *pEvent)\r\n{\r\n \/\/ Default handling of the event\r\n\r\n Widget::changeEvent(pEvent);\r\n\r\n \/\/ Check whether the palette has changed and if so then update the colour\r\n \/\/ used to highlight the active graph panel\r\n\r\n if (pEvent->type() == QEvent::PaletteChange)\r\n updateMarkerColor();\r\n}\r\n\r\n\/\/==============================================================================\r\n\r\nvoid SingleCellSimulationViewGraphPanelWidget::mousePressEvent(QMouseEvent *pEvent)\r\n{\r\n \/\/ Default handling of the event\r\n\r\n QWidget::mousePressEvent(pEvent);\r\n\r\n \/\/ Activate\/inactivate the graph panel\r\n \/\/ Note: we do it through setActive() because we want the graph panel to let\r\n \/\/ people know that our active state has changed...\r\n\r\n setActive(true);\r\n}\r\n\r\n\/\/==============================================================================\r\n\r\nSingleCellSimulationViewGraphPanelPlotWidget * SingleCellSimulationViewGraphPanelWidget::plot()\r\n{\r\n \/\/ Return the pointer to our plot widget\r\n\r\n return mPlot;\r\n}\r\n\r\n\/\/==============================================================================\r\n\r\nbool SingleCellSimulationViewGraphPanelWidget::isActive() const\r\n{\r\n \/\/ Return whether the graph panel as active\r\n\r\n return mActive;\r\n}\r\n\r\n\/\/==============================================================================\r\n\r\nvoid SingleCellSimulationViewGraphPanelWidget::updateMarkerColor()\r\n{\r\n \/\/ Update the marker's colour based on whether the graph panel is active\r\n\r\n QPalette newPalette = palette();\r\n\r\n newPalette.setColor(QPalette::WindowText,\r\n mActive?\r\n CommonWidget::highlightColor():\r\n CommonWidget::windowColor());\r\n\r\n mMarker->setPalette(newPalette);\r\n}\r\n\r\n\/\/==============================================================================\r\n\r\nvoid SingleCellSimulationViewGraphPanelWidget::setActive(const bool &pActive)\r\n{\r\n if (pActive == mActive)\r\n return;\r\n\r\n \/\/ Set the graph panel's active state\r\n\r\n mActive = pActive;\r\n\r\n \/\/ Update the marker's colour\r\n\r\n updateMarkerColor();\r\n\r\n \/\/ Let people know if the graph panel has been activated or inactivated\r\n\r\n if (pActive)\r\n emit activated(this);\r\n else\r\n emit inactivated(this);\r\n}\r\n\r\n\/\/==============================================================================\r\n\r\n} \/\/ namespace SingleCellSimulationView\r\n} \/\/ namespace OpenCOR\r\n\r\n\/\/==============================================================================\r\n\/\/ End of file\r\n\/\/==============================================================================\r\n<commit_msg>Temporarily removed the marker in our graph panel (#112).<commit_after>\/\/==============================================================================\r\n\/\/ Single cell simulation view graph panel widget\r\n\/\/==============================================================================\r\n\r\n#include \"singlecellsimulationviewgraphpanelplotwidget.h\"\r\n#include \"singlecellsimulationviewgraphpanelwidget.h\"\r\n\r\n\/\/==============================================================================\r\n\r\n#include <QHBoxLayout>\r\n#include <QMouseEvent>\r\n\r\n\/\/==============================================================================\r\n\r\n#include \"qwt_plot_curve.h\"\r\n\r\n\/\/==============================================================================\r\n\r\n#include \"ui_singlecellsimulationviewgraphpanelwidget.h\"\r\n\r\n\/\/==============================================================================\r\n\r\nnamespace OpenCOR {\r\nnamespace SingleCellSimulationView {\r\n\r\n\/\/==============================================================================\r\n\r\nSingleCellSimulationViewGraphPanelWidget::SingleCellSimulationViewGraphPanelWidget(QWidget *pParent) :\r\n Widget(pParent),\r\n mGui(new Ui::SingleCellSimulationViewGraphPanelWidget),\r\n mActive(false)\r\n{\r\n \/\/ Set up the GUI\r\n\r\n mGui->setupUi(this);\r\n\r\n \/\/ Create, customise and add an inactive marker to our layout\r\n\r\n static const int MarkerWidth = 3;\r\n\r\n mMarker = new QFrame(this);\r\n\r\n mMarker->setFrameShape(QFrame::VLine);\r\n mMarker->setLineWidth(MarkerWidth);\r\n mMarker->setMinimumWidth(MarkerWidth);\r\n\r\n setActive(false);\r\n\r\n\/\/ mGui->layout->addWidget(mMarker);\r\n\/\/---GRY--- THIS IS TEMPORARY, I.E. WHILE WE SUPPORT ONLY ONE GRAPH PANEL...\r\n\r\n \/\/ Create and add a plot widget to our layout\r\n\r\n mPlot = new SingleCellSimulationViewGraphPanelPlotWidget(this);\r\n\r\n mGui->layout->addWidget(mPlot);\r\n\r\n \/\/ Allow the graph panel to be of any vertical size\r\n\r\n setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Ignored);\r\n}\r\n\r\n\/\/==============================================================================\r\n\r\nSingleCellSimulationViewGraphPanelWidget::~SingleCellSimulationViewGraphPanelWidget()\r\n{\r\n \/\/ Delete the GUI\r\n\r\n delete mGui;\r\n}\r\n\r\n\/\/==============================================================================\r\n\r\nvoid SingleCellSimulationViewGraphPanelWidget::changeEvent(QEvent *pEvent)\r\n{\r\n \/\/ Default handling of the event\r\n\r\n Widget::changeEvent(pEvent);\r\n\r\n \/\/ Check whether the palette has changed and if so then update the colour\r\n \/\/ used to highlight the active graph panel\r\n\r\n if (pEvent->type() == QEvent::PaletteChange)\r\n updateMarkerColor();\r\n}\r\n\r\n\/\/==============================================================================\r\n\r\nvoid SingleCellSimulationViewGraphPanelWidget::mousePressEvent(QMouseEvent *pEvent)\r\n{\r\n \/\/ Default handling of the event\r\n\r\n QWidget::mousePressEvent(pEvent);\r\n\r\n \/\/ Activate\/inactivate the graph panel\r\n \/\/ Note: we do it through setActive() because we want the graph panel to let\r\n \/\/ people know that our active state has changed...\r\n\r\n setActive(true);\r\n}\r\n\r\n\/\/==============================================================================\r\n\r\nSingleCellSimulationViewGraphPanelPlotWidget * SingleCellSimulationViewGraphPanelWidget::plot()\r\n{\r\n \/\/ Return the pointer to our plot widget\r\n\r\n return mPlot;\r\n}\r\n\r\n\/\/==============================================================================\r\n\r\nbool SingleCellSimulationViewGraphPanelWidget::isActive() const\r\n{\r\n \/\/ Return whether the graph panel as active\r\n\r\n return mActive;\r\n}\r\n\r\n\/\/==============================================================================\r\n\r\nvoid SingleCellSimulationViewGraphPanelWidget::updateMarkerColor()\r\n{\r\n \/\/ Update the marker's colour based on whether the graph panel is active\r\n\r\n QPalette newPalette = palette();\r\n\r\n newPalette.setColor(QPalette::WindowText,\r\n mActive?\r\n CommonWidget::highlightColor():\r\n CommonWidget::windowColor());\r\n\r\n mMarker->setPalette(newPalette);\r\n}\r\n\r\n\/\/==============================================================================\r\n\r\nvoid SingleCellSimulationViewGraphPanelWidget::setActive(const bool &pActive)\r\n{\r\n if (pActive == mActive)\r\n return;\r\n\r\n \/\/ Set the graph panel's active state\r\n\r\n mActive = pActive;\r\n\r\n \/\/ Update the marker's colour\r\n\r\n updateMarkerColor();\r\n\r\n \/\/ Let people know if the graph panel has been activated or inactivated\r\n\r\n if (pActive)\r\n emit activated(this);\r\n else\r\n emit inactivated(this);\r\n}\r\n\r\n\/\/==============================================================================\r\n\r\n} \/\/ namespace SingleCellSimulationView\r\n} \/\/ namespace OpenCOR\r\n\r\n\/\/==============================================================================\r\n\/\/ End of file\r\n\/\/==============================================================================\r\n<|endoftext|>"} {"text":"<commit_before>#include \"aiplayer.h\"\n#include \"game.h\"\n\n#include <iostream>\n\n\n\n\n\nAIPlayer::AIPlayer()\n{\n \/\/ int *tmp = new int[4];\n \/\/ tmp[0] = 1;\n \/\/ tmp[1] = 2;\n \/\/ tmp[2] = 3;\n \/\/ tmp[3] = 4;\n\n \/\/ int **out = calculateOrderPermutations(tmp, 4);\n\n \/\/ for (int i = 0; i < calculateNumberOfOrderPermutations(4); i++)\n \/\/ {\n \/\/ for (int j = 0; j < 4; j++)\n \/\/ {\n \/\/ std::cout << out[i][j] << \" \";\n \/\/ }\n \/\/ std::cout << \"\\n\";\n \/\/ }\n}\n\nbool AIPlayer::playRound(int grid[GAME_BOARD_GRID_SIZE][GAME_BOARD_GRID_SIZE],\n int piece[NUMBER_OF_PIECES_PER_ROUND],\n int x[NUMBER_OF_PIECES_PER_ROUND],\n int y[NUMBER_OF_PIECES_PER_ROUND])\n{\n\n int numberOfPermutations = calculateNumberOfOrderPermutations(NUMBER_OF_PIECES_PER_ROUND);\n int **permutations = calculateOrderPermutations(piece, NUMBER_OF_PIECES_PER_ROUND);\n\n std::vector<int*> permutationsVector = std::vector<int*>();\n\n for (int i = 0; i < numberOfPermutations; i++)\n {\n bool inAlready = false;\n for (size_t j = 0; j < permutationsVector.size(); j++)\n {\n if (permutationsVector.at(j) == permutations[i])\n {\n inAlready = true;\n break;\n }\n\n inAlready = true;\n for (int k = 0; k < NUMBER_OF_PIECES_PER_ROUND; k++)\n {\n if (permutations[i][k] != permutationsVector.at(j)[k])\n {\n inAlready = false;\n break;\n }\n }\n\n if (inAlready)\n {\n break;\n }\n }\n\n if (!inAlready)\n {\n permutationsVector.push_back(permutations[i]);\n }\n }\n\n delete [] permutations;\n\n std::vector<Move*> *moves = new std::vector<Move*>();\n\n for (size_t i = 0; i < permutationsVector.size(); i++)\n {\n calculateMoves(permutationsVector.at(i), grid, moves);\n delete [] permutationsVector.at(i);\n }\n\n\n\n if (moves->size() == 0)\n {\n delete moves;\n std::cout << \"No Moves \\n\";\n return false;\n }\n\n std::cout << \"Number of Moves: \" << moves->size() << \"\\n\";\n\n int bestMoveScore = 0;\n int bestMoveIndex = 0;\n for (size_t m = 0; m < moves->size(); m++)\n {\n evaluateMove(moves->at(m));\n\n if (moves->at(m)->moveScore > bestMoveScore)\n {\n bestMoveIndex = m;\n }\n }\n\n for (int i = 0; i < NUMBER_OF_PIECES_PER_ROUND; i++)\n {\n piece[i] = moves->at(bestMoveIndex)->piece[i];\n \/\/ piece[i] = 16;\/\/moves->at(bestMoveIndex)->piece[i];\n x[i] = moves->at(bestMoveIndex)->x[i];\n y[i] = moves->at(bestMoveIndex)->y[i];\n }\n\n\n\n\n for (size_t m = 0; m < moves->size(); m++)\n {\n for (int i = 0; i < GAME_BOARD_GRID_SIZE; i++)\n {\n delete [] moves->at(m)->grid[i];\n }\n delete [] moves->at(m)->grid;\n delete moves->at(m);\n }\n\n delete moves;\n return true;\n}\n\n\nint AIPlayer::processGrid(int **grid)\n{\n\n int linesCleared = 0;\n\n bool rowsToClear[GAME_BOARD_GRID_SIZE];\n bool columnsToClear[GAME_BOARD_GRID_SIZE];\n\n for (int i = 0; i < GAME_BOARD_GRID_SIZE; i++)\n {\n bool didFindHole = false;\n\n for (int j = 0; j < GAME_BOARD_GRID_SIZE; j++)\n {\n if (grid[i][j] == 0)\n {\n didFindHole = true;\n break;\n }\n }\n\n rowsToClear[i] = !didFindHole;\n }\n\n for (int i = 0; i < GAME_BOARD_GRID_SIZE; i++)\n {\n bool didFindHole = false;\n\n for (int j = 0; j < GAME_BOARD_GRID_SIZE; j++)\n {\n if (grid[j][i] == 0)\n {\n didFindHole = true;\n break;\n }\n }\n\n columnsToClear[i] = !didFindHole;\n }\n\n for (int i = 0; i < GAME_BOARD_GRID_SIZE; i++)\n {\n if (!rowsToClear[i])\n {\n continue;\n }\n\n linesCleared++;\n\n for (int j = 0; j < GAME_BOARD_GRID_SIZE; j++)\n {\n grid[i][j] = 0;\n }\n }\n\n for (int i = 0; i < GAME_BOARD_GRID_SIZE; i++)\n {\n if (!columnsToClear[i])\n {\n continue;\n }\n linesCleared++;\n\n for (int j = 0; j < GAME_BOARD_GRID_SIZE; j++)\n {\n grid[j][i] = 0;\n }\n }\n\n return linesCleared;\n}\n\nvoid AIPlayer::calculateMoves(int pieces[NUMBER_OF_PIECES_PER_ROUND], int origGrid[GAME_BOARD_GRID_SIZE][GAME_BOARD_GRID_SIZE], std::vector<Move*> *moves)\n{\n\n \/\/ Make an initial empty move\n Move *initMove = new Move();\n\n \/\/ Clear everything\n initMove->moveScore = 0;\n initMove->numberOfLinesCleared = 0;\n initMove->grid = new int*[GAME_BOARD_GRID_SIZE];\n\n for (int i = 0; i < NUMBER_OF_PIECES_PER_ROUND; i++)\n {\n initMove->piece[i] = pieces[i];\n }\n\n\n for (int j = 0; j < GAME_BOARD_GRID_SIZE; j++)\n {\n \/\/ Allocate memory\n initMove->grid[j] = new int[GAME_BOARD_GRID_SIZE];\n\n \/\/ Copy into the new array;\n for (int t = 0; t < GAME_BOARD_GRID_SIZE; t++)\n {\n initMove->grid[j][t] = origGrid[j][t];\n }\n }\n\n\n std::vector<Move*> moveTmp = std::vector<Move*>();\n moveTmp.push_back(initMove);\n\n\n \/\/ Do all additional pieces\n for (int i = 0; i < NUMBER_OF_PIECES_PER_ROUND; i++)\n {\n std::vector<Move*> movetmpOrig = std::vector<Move*>(moveTmp);\n moveTmp.clear();\n\n \/\/ Get the piece data\n int pWidth = 0;\n int pHeight = 0;\n int pGrid[5][5];\n\n \/\/ Get the piece data\n Game::getGridForPiece(pieces[i], pWidth, pHeight, pGrid);\n\n for (size_t m = 0; m < movetmpOrig.size(); m++)\n {\n Move *currentMove = movetmpOrig.at(m);\n for (int piecePlacementX = 0; piecePlacementX < (GAME_BOARD_GRID_SIZE - pWidth + 1); piecePlacementX++)\n {\n for (int piecePlacementY = 0; piecePlacementY < (GAME_BOARD_GRID_SIZE - pHeight + 1); piecePlacementY++)\n {\n bool isValidMove = true;\n\n \/\/ Check if it is a valid move\n for (int pX = 0; pX < pWidth; pX++)\n {\n for (int pY = 0; pY < pHeight; pY++)\n {\n if (currentMove->grid[piecePlacementY + pY][piecePlacementX + pX] == 1)\n {\n isValidMove = false;\n break;\n }\n }\n\n if (!isValidMove)\n {\n break;\n }\n }\n\n if (!isValidMove)\n {\n continue;\n }\n\n Move *newMove = new Move(*currentMove);\n\n for (int pI = 0; pI < NUMBER_OF_PIECES_PER_ROUND; pI++)\n {\n newMove->piece[pI] = currentMove->piece[pI];\n }\n\n newMove->numberOfLinesCleared = currentMove->numberOfLinesCleared;\n newMove->x[i] = piecePlacementX;\n newMove->y[i] = piecePlacementY;\n\n newMove->grid = new int*[GAME_BOARD_GRID_SIZE];\n\n for (int j = 0; j < GAME_BOARD_GRID_SIZE; j++)\n {\n \/\/ Allocate memory\n newMove->grid[j] = new int[GAME_BOARD_GRID_SIZE];\n\n \/\/ Copy into the new array;\n for (int t = 0; t < GAME_BOARD_GRID_SIZE; t++)\n {\n newMove->grid[j][t] = currentMove->grid[j][t];\n }\n }\n\n \/\/ Place the piece since valid\n for (int pX = 0; pX < pWidth; pX++)\n {\n for (int pY = 0; pY < pHeight; pY++)\n {\n newMove->grid[piecePlacementY + pY][piecePlacementX + pX] += pGrid[pY][pX];\n }\n }\n\n newMove->numberOfLinesCleared += processGrid(newMove->grid);\n\n moveTmp.push_back(newMove);\n }\n }\n\n for (int g = 0; g < GAME_BOARD_GRID_SIZE; g++)\n {\n delete [] currentMove->grid[g];\n }\n delete [] currentMove->grid;\n delete movetmpOrig.at(m);\n }\n }\n\n\n\n for (size_t m = 0; m < moveTmp.size(); m++)\n {\n moves->push_back(moveTmp.at(m));\n }\n\n moveTmp.clear();\n\n}\n\nvoid AIPlayer::evaluateMove(Move *m)\n{\n\n m->moveScore = m->numberOfLinesCleared;\n\n \/\/ int numberOfHoles = 0;\n \/\/ int numberOfFreeLines = 0;\n\n\n \/\/ for (int x = 0; x < GAME_BOARD_GRID_SIZE; x++)\n \/\/ {\n \/\/ for (int y = 0; y < GAME_BOARD_GRID_SIZE; y++)\n \/\/ {\n\n \/\/ }\n \/\/ }\n}\n\n\n\n\nint AIPlayer::calculateNumberOfOrderPermutations(int c)\n{\n int fact = 1;\n for (int i = c; i > 0; i--)\n {\n fact *= i;\n }\n\n return fact;\n}\n\n\nint** AIPlayer::calculateOrderPermutations(int *p, int count)\n{\n if (count == 1)\n {\n int **ret = new int*[1];\n ret[0] = new int[1];\n ret[0][0] = p[0];\n return ret;\n }\n\n int lowerPermNum = calculateNumberOfOrderPermutations(count - 1);\n\n int **ret = new int*[lowerPermNum * count];\n\n int permPos = 0;\n for (int i = 0; i < count; i++)\n {\n int *par = new int[count - 1];\n int c = 0;\n for (int j = 0; j < count; j++)\n {\n if (j == i)\n {\n continue;\n }\n par[c] = p[j];\n c++;\n }\n\n int **lowerPerms = calculateOrderPermutations(par, count - 1);\n delete [] par;\n\n\n for (int j = 0; j < lowerPermNum; j++)\n {\n ret[permPos] = new int[count];\n\n for (int t = 0; t < count - 1; t++)\n {\n ret[permPos][t] = lowerPerms[j][t];\n }\n\n ret[permPos][count - 1] = p[i];\n permPos++;\n\n delete [] lowerPerms[j];\n }\n\n delete [] lowerPerms;\n }\n\n return ret;\n}<commit_msg>Added AI logic<commit_after>#include \"aiplayer.h\"\n#include \"game.h\"\n\n#include <iostream>\n\n\n\n\n\nAIPlayer::AIPlayer()\n{\n \/\/ int *tmp = new int[4];\n \/\/ tmp[0] = 1;\n \/\/ tmp[1] = 2;\n \/\/ tmp[2] = 3;\n \/\/ tmp[3] = 4;\n\n \/\/ int **out = calculateOrderPermutations(tmp, 4);\n\n \/\/ for (int i = 0; i < calculateNumberOfOrderPermutations(4); i++)\n \/\/ {\n \/\/ for (int j = 0; j < 4; j++)\n \/\/ {\n \/\/ std::cout << out[i][j] << \" \";\n \/\/ }\n \/\/ std::cout << \"\\n\";\n \/\/ }\n}\n\nbool AIPlayer::playRound(int grid[GAME_BOARD_GRID_SIZE][GAME_BOARD_GRID_SIZE],\n int piece[NUMBER_OF_PIECES_PER_ROUND],\n int x[NUMBER_OF_PIECES_PER_ROUND],\n int y[NUMBER_OF_PIECES_PER_ROUND])\n{\n\n int numberOfPermutations = calculateNumberOfOrderPermutations(NUMBER_OF_PIECES_PER_ROUND);\n int **permutations = calculateOrderPermutations(piece, NUMBER_OF_PIECES_PER_ROUND);\n\n std::vector<int*> permutationsVector = std::vector<int*>();\n\n for (int i = 0; i < numberOfPermutations; i++)\n {\n bool inAlready = false;\n for (size_t j = 0; j < permutationsVector.size(); j++)\n {\n if (permutationsVector.at(j) == permutations[i])\n {\n inAlready = true;\n break;\n }\n\n inAlready = true;\n for (int k = 0; k < NUMBER_OF_PIECES_PER_ROUND; k++)\n {\n if (permutations[i][k] != permutationsVector.at(j)[k])\n {\n inAlready = false;\n break;\n }\n }\n\n if (inAlready)\n {\n break;\n }\n }\n\n if (!inAlready)\n {\n permutationsVector.push_back(permutations[i]);\n }\n }\n\n delete [] permutations;\n\n std::vector<Move*> *moves = new std::vector<Move*>();\n\n for (size_t i = 0; i < permutationsVector.size(); i++)\n {\n calculateMoves(permutationsVector.at(i), grid, moves);\n delete [] permutationsVector.at(i);\n }\n\n if (moves->size() == 0)\n {\n delete moves;\n std::cout << \"No Moves \\n\";\n return false;\n }\n\n std::cout << \"Number of Moves: \" << moves->size() << \"\\n\";\n\n int bestMoveScore = 0;\n int bestMoveIndex = 0;\n for (size_t m = 0; m < moves->size(); m++)\n {\n evaluateMove(moves->at(m));\n\n if (moves->at(m)->moveScore > bestMoveScore)\n {\n bestMoveIndex = m;\n }\n }\n\n for (int i = 0; i < NUMBER_OF_PIECES_PER_ROUND; i++)\n {\n piece[i] = moves->at(bestMoveIndex)->piece[i];\n x[i] = moves->at(bestMoveIndex)->x[i];\n y[i] = moves->at(bestMoveIndex)->y[i];\n }\n\n\n\n\n for (size_t m = 0; m < moves->size(); m++)\n {\n for (int i = 0; i < GAME_BOARD_GRID_SIZE; i++)\n {\n delete [] moves->at(m)->grid[i];\n }\n delete [] moves->at(m)->grid;\n delete moves->at(m);\n }\n\n delete moves;\n return true;\n}\n\n\nint AIPlayer::processGrid(int **grid)\n{\n\n int linesCleared = 0;\n\n bool rowsToClear[GAME_BOARD_GRID_SIZE];\n bool columnsToClear[GAME_BOARD_GRID_SIZE];\n\n for (int i = 0; i < GAME_BOARD_GRID_SIZE; i++)\n {\n bool didFindHole = false;\n\n for (int j = 0; j < GAME_BOARD_GRID_SIZE; j++)\n {\n if (grid[i][j] == 0)\n {\n didFindHole = true;\n break;\n }\n }\n\n rowsToClear[i] = !didFindHole;\n }\n\n for (int i = 0; i < GAME_BOARD_GRID_SIZE; i++)\n {\n bool didFindHole = false;\n\n for (int j = 0; j < GAME_BOARD_GRID_SIZE; j++)\n {\n if (grid[j][i] == 0)\n {\n didFindHole = true;\n break;\n }\n }\n\n columnsToClear[i] = !didFindHole;\n }\n\n for (int i = 0; i < GAME_BOARD_GRID_SIZE; i++)\n {\n if (!rowsToClear[i])\n {\n continue;\n }\n\n linesCleared++;\n\n for (int j = 0; j < GAME_BOARD_GRID_SIZE; j++)\n {\n grid[i][j] = 0;\n }\n }\n\n for (int i = 0; i < GAME_BOARD_GRID_SIZE; i++)\n {\n if (!columnsToClear[i])\n {\n continue;\n }\n linesCleared++;\n\n for (int j = 0; j < GAME_BOARD_GRID_SIZE; j++)\n {\n grid[j][i] = 0;\n }\n }\n\n return linesCleared;\n}\n\nvoid AIPlayer::calculateMoves(int pieces[NUMBER_OF_PIECES_PER_ROUND], int origGrid[GAME_BOARD_GRID_SIZE][GAME_BOARD_GRID_SIZE], std::vector<Move*> *moves)\n{\n\n \/\/ Make an initial empty move\n Move *initMove = new Move();\n\n \/\/ Clear everything\n initMove->moveScore = 0;\n initMove->numberOfLinesCleared = 0;\n initMove->grid = new int*[GAME_BOARD_GRID_SIZE];\n\n for (int i = 0; i < NUMBER_OF_PIECES_PER_ROUND; i++)\n {\n initMove->piece[i] = pieces[i];\n }\n\n\n for (int j = 0; j < GAME_BOARD_GRID_SIZE; j++)\n {\n \/\/ Allocate memory\n initMove->grid[j] = new int[GAME_BOARD_GRID_SIZE];\n\n \/\/ Copy into the new array;\n for (int t = 0; t < GAME_BOARD_GRID_SIZE; t++)\n {\n initMove->grid[j][t] = origGrid[j][t];\n }\n }\n\n\n std::vector<Move*> *moveTmp = new std::vector<Move*>();\n moveTmp->push_back(initMove);\n\n\n \/\/ Do all additional pieces\n for (int i = 0; i < NUMBER_OF_PIECES_PER_ROUND; i++)\n {\n std::vector<Move*> *movetmpOrig = moveTmp;\n moveTmp = new std::vector<Move*>();\n\n \/\/ Get the piece data\n int pWidth = 0;\n int pHeight = 0;\n int pGrid[5][5];\n\n \/\/ Get the piece data\n Game::getGridForPiece(pieces[i], pWidth, pHeight, pGrid);\n\n for (size_t m = 0; m < movetmpOrig->size(); m++)\n {\n Move *currentMove = movetmpOrig->at(m);\n for (int piecePlacementX = 0; piecePlacementX < (GAME_BOARD_GRID_SIZE - pWidth + 1); piecePlacementX++)\n {\n for (int piecePlacementY = 0; piecePlacementY < (GAME_BOARD_GRID_SIZE - pHeight + 1); piecePlacementY++)\n {\n bool isValidMove = true;\n\n \/\/ Check if it is a valid move\n for (int pX = 0; pX < pWidth; pX++)\n {\n for (int pY = 0; pY < pHeight; pY++)\n {\n if (currentMove->grid[piecePlacementY + pY][piecePlacementX + pX] == 1)\n {\n isValidMove = false;\n break;\n }\n }\n\n if (!isValidMove)\n {\n break;\n }\n }\n\n if (!isValidMove)\n {\n continue;\n }\n\n Move *newMove = new Move(*currentMove);\n\n for (int pI = 0; pI < NUMBER_OF_PIECES_PER_ROUND; pI++)\n {\n newMove->piece[pI] = currentMove->piece[pI];\n }\n\n newMove->numberOfLinesCleared = currentMove->numberOfLinesCleared;\n newMove->x[i] = piecePlacementX;\n newMove->y[i] = piecePlacementY;\n\n newMove->grid = new int*[GAME_BOARD_GRID_SIZE];\n\n for (int j = 0; j < GAME_BOARD_GRID_SIZE; j++)\n {\n \/\/ Allocate memory\n newMove->grid[j] = new int[GAME_BOARD_GRID_SIZE];\n\n \/\/ Copy into the new array;\n for (int t = 0; t < GAME_BOARD_GRID_SIZE; t++)\n {\n newMove->grid[j][t] = currentMove->grid[j][t];\n }\n }\n\n \/\/ Place the piece since valid\n for (int pX = 0; pX < pWidth; pX++)\n {\n for (int pY = 0; pY < pHeight; pY++)\n {\n newMove->grid[piecePlacementY + pY][piecePlacementX + pX] += pGrid[pY][pX];\n }\n }\n\n newMove->numberOfLinesCleared += processGrid(newMove->grid);\n\n moveTmp->push_back(newMove);\n }\n }\n\n for (int g = 0; g < GAME_BOARD_GRID_SIZE; g++)\n {\n delete [] currentMove->grid[g];\n }\n delete [] currentMove->grid;\n delete movetmpOrig.at(m);\n }\n\n delete movetmpOrig;\n }\n\n\n\n for (size_t m = 0; m < moveTmp->size(); m++)\n {\n moves->push_back(moveTmp->at(m));\n }\n\n delete moveTmp;\n moveTmp->clear();\n\n}\n\nvoid AIPlayer::evaluateMove(Move *m)\n{\n\n m->moveScore = m->numberOfLinesCleared;\n\n \/\/ int numberOfHoles = 0;\n \/\/ int numberOfFreeLines = 0;\n\n\n \/\/ for (int x = 0; x < GAME_BOARD_GRID_SIZE; x++)\n \/\/ {\n \/\/ for (int y = 0; y < GAME_BOARD_GRID_SIZE; y++)\n \/\/ {\n\n \/\/ }\n \/\/ }\n}\n\n\n\n\nint AIPlayer::calculateNumberOfOrderPermutations(int c)\n{\n int fact = 1;\n for (int i = c; i > 0; i--)\n {\n fact *= i;\n }\n\n return fact;\n}\n\n\nint** AIPlayer::calculateOrderPermutations(int *p, int count)\n{\n if (count == 1)\n {\n int **ret = new int*[1];\n ret[0] = new int[1];\n ret[0][0] = p[0];\n return ret;\n }\n\n int lowerPermNum = calculateNumberOfOrderPermutations(count - 1);\n\n int **ret = new int*[lowerPermNum * count];\n\n int permPos = 0;\n for (int i = 0; i < count; i++)\n {\n int *par = new int[count - 1];\n int c = 0;\n for (int j = 0; j < count; j++)\n {\n if (j == i)\n {\n continue;\n }\n par[c] = p[j];\n c++;\n }\n\n int **lowerPerms = calculateOrderPermutations(par, count - 1);\n delete [] par;\n\n\n for (int j = 0; j < lowerPermNum; j++)\n {\n ret[permPos] = new int[count];\n\n for (int t = 0; t < count - 1; t++)\n {\n ret[permPos][t] = lowerPerms[j][t];\n }\n\n ret[permPos][count - 1] = p[i];\n permPos++;\n\n delete [] lowerPerms[j];\n }\n\n delete [] lowerPerms;\n }\n\n return ret;\n}<|endoftext|>"} {"text":"<commit_before>#include \"RandomWorld.hpp\"\n#include \"..\/Simulator.hpp\"\n#include \"..\/agent\/Ant.hpp\"\n#include \"..\/gui\/GuiEventManager.hpp\"\n#include \"..\/sim\/nav\/Node.hpp\"\n#include \"..\/sim\/nav\/Edge.hpp\"\n#include \"..\/sim\/agent\/Ant.hpp\"\n#include \"..\/sim\/worldobject\/AntFoodPile.hpp\"\n#include \"..\/sim\/worldobject\/SolidObject.hpp\"\n#include \"..\/sim\/worldobject\/AntHome.hpp\"\n#include \"..\/util\/Random.hpp\"\n\n#include <vector>\n#include <memory>\n#include <cassert>\n\n\/\/ Christopher D. Canfield\n\/\/ November 2013\n\/\/ RandomWorld.cpp\n\nusing cdc::RandomWorld;\nusing cdc::GuiEventManager;\nusing cdc::Node;\nusing cdc::Edge;\nusing cdc::GridLocation;\nusing cdc::AntFoodPile;\nusing cdc::AntHome;\nusing cdc::Random;\nusing cdc::SolidObject;\nusing cdc::Ant;\n\nusing namespace sf;\nusing namespace std;\n\n\/\/ Creates the world's navigation graph.\nvoid createNavGraph(vector<Node>& navGraph);\n\n\/\/ Adds food piles to the world.\nvoid addFood(vector<Node>& navGraph, vector<Node*>& occupiedAreas, vector<AntFoodPile>& antFoodPiles);\n\n\/\/ Adds obstructions to the world.\nvoid addObstructions(vector<Node>& navGraph, vector<Node*>& occupiedAreas, vector<Sprite>& obstructions);\n\n\/\/ Adds the ant hill to the world.\n\/\/ Returns the ant hill location within the nav graph.\nint addAntHill(vector<Node>& navGraph, vector<Node*>& occupiedAreas, vector<AntHome>& antHills);\n\n\/\/ Adds a random number of ants to the world.\nvoid addAnts(vector<Node>& navGraph, AntHome& antHill, GuiEventManager& eventManager, vector<Ant>& ants);\n\n\/\/ Finds an unoccupied location between the min and max node (inclusive).\n\/\/ Returns the index of the node within the nav graph.\nint findValidLocation(vector<Node>& navGraph, vector<Node*>& occupiedAreas, int minAllowedNode, int maxAllowedNode, Random& rand);\n\n\/\/ Returns true if the node is occupied, or false if not.\nbool isOccupied(vector<Node*> occupiedAreas, Node& location);\n\n\n\/\/ TODO: the size of the world should be accessible outside of the class,\n\/\/ or the size should be passed into the world.\nconst int nav_graph_rows = 30;\nconst int nav_graph_columns = 30;\n\nconst int side_offset = 50;\nconst int node_offset = 100;\n\n\nRandomWorld::RandomWorld(GuiEventManager& eventManager) :\n\teventManager(eventManager)\n{\n}\n\nRandomWorld::~RandomWorld()\n{\n}\n\n\nvoid RandomWorld::create(GuiEventManager& eventManager)\n{\n\tcreateNavGraph(navGraph);\n\tvector<Node*> offLimitAreas;\n\n\taddFood(navGraph, offLimitAreas, antFoodPiles);\n\taddObstructions(navGraph, offLimitAreas, obstructions);\n\tint antHillLocation = addAntHill(navGraph, offLimitAreas, antHills);\n\taddAnts(navGraph, antHills[0], eventManager, ants);\n}\n\n\nvoid createNavGraph(vector<Node>& navGraph)\n{\n\tnavGraph.reserve(nav_graph_rows * nav_graph_rows);\n\n\tfor (int row = 0; row < nav_graph_rows; ++row)\n\t{\n\t\tfor (int column = 0; column < nav_graph_columns; ++column)\n\t\t{\n\t\t\tint pixelX = side_offset + (column * node_offset);\n\t\t\tint pixelY = side_offset + (row * node_offset);\n\t\t\tnavGraph.push_back(Node(GridLocation(row, column), pixelX, pixelY));\n\t\t}\n\t}\n\n\tfor (int row = 0; row < nav_graph_rows; ++row)\n\t{\n\t\tfor (int column = 0; column < nav_graph_columns; ++column)\n\t\t{\n\t\t\tauto& startNode = navGraph[(row * nav_graph_columns) + column];\n\t\t\t\/\/ Add up connection.\n\t\t\tif (row > 0)\n\t\t\t{\n\t\t\t\tauto& endNode = navGraph[(row - 1) * nav_graph_columns + column];\n\t\t\t\tauto edge = make_shared<Edge>(startNode, endNode, 1);\n\t\t\t\tif (!startNode.edgeExists(edge))\n\t\t\t\t{\n\t\t\t\t\tstartNode.addEdge(edge);\n\t\t\t\t}\n\t\t\t}\n\t\t\t\/\/ Add down connection.\n\t\t\tif (row < nav_graph_columns - 1)\n\t\t\t{\n\t\t\t\tauto& endNode = navGraph[(row + 1) * nav_graph_columns + column];\n\t\t\t\tauto edge = make_shared<Edge>(startNode, endNode, 1);\n\t\t\t\tif (!startNode.edgeExists(edge))\n\t\t\t\t{\n\t\t\t\t\tstartNode.addEdge(edge);\n\t\t\t\t}\n\t\t\t}\n\t\t\t\/\/ Add left connection.\n\t\t\tif (column > 0)\n\t\t\t{\n\t\t\t\tauto& endNode = navGraph[row * nav_graph_columns + column - 1];\n\t\t\t\tauto edge = make_shared<Edge>(startNode, endNode, 1);\n\t\t\t\tif (!startNode.edgeExists(edge))\n\t\t\t\t{\n\t\t\t\t\tstartNode.addEdge(edge);\n\t\t\t\t}\n\t\t\t}\n\t\t\t\/\/ Add right connection.\n\t\t\tif (column < nav_graph_columns - 1)\n\t\t\t{\n\t\t\t\tauto& endNode = navGraph[row * nav_graph_columns + column + 1];\n\t\t\t\tauto edge = make_shared<Edge>(startNode, endNode, 1);\n\t\t\t\tif (!startNode.edgeExists(edge))\n\t\t\t\t{\n\t\t\t\t\tstartNode.addEdge(edge);\n\t\t\t\t}\n\t\t\t}\n\t\t\t\/\/ Add diagonal connection 1.\n\n\t\t\t\/\/ Add diagonal connection 2.\n\t\t}\n\t}\n}\n\nvoid addFood(vector<Node>& navGraph, vector<Node*>& occupiedAreas, vector<AntFoodPile>& antFoodPiles)\n{\n\tRandom rand;\n\n\t\/\/ Add between 3 and 10 piles of food.\n\tconst int minFoodPiles = 3;\n\tconst int maxFoodPiles = 10;\n\n\tint foodPileCount = rand.getInteger(minFoodPiles, maxFoodPiles);\n\tfor (int i = 0; i < maxFoodPiles; ++i)\n\t{\n\t\tint nodeLocation = findValidLocation(navGraph, occupiedAreas, 0, navGraph.size(), rand);\n\t\tint foodInPile = rand.getInteger(50, 750);\n\t\tantFoodPiles.push_back(AntFoodPile(foodInPile, navGraph[nodeLocation]));\n\t\toccupiedAreas.push_back(&navGraph[nodeLocation]);\n\t}\n}\n\nvoid addObstructions(vector<Node>& navGraph, vector<Node*>& occupiedAreas, vector<Sprite>& obstructions)\n{\n\tRandom rand;\n\n\t\/\/ Add between 10 and 20 obstructions.\n\tconst int maxObstructions = 20;\n\tconst int minObstructions = 10;\n\n\tint obstructionCount = rand.getInteger(minObstructions, maxObstructions);\n\tfor (int i = 0; i < maxObstructions; ++i)\n\t{\n\t\tint nodeLocation = findValidLocation(navGraph, occupiedAreas, 0, navGraph.size(), rand);\n\t\tauto rock = SolidObject::createRock(navGraph, navGraph[nodeLocation].getPixelX(), navGraph[nodeLocation].getPixelY());\n\t\tobstructions.push_back(rock);\n\t\toccupiedAreas.push_back(&navGraph[nodeLocation]);\n\t}\n}\n\nint addAntHill(vector<Node>& navGraph, vector<Node*>& occupiedAreas, vector<AntHome>& antHills)\n{\n\tRandom rand;\n\n\t\/\/ Ant hill can be in any node within the first three rows.\n\tint antHillLocation = rand.getInteger(0, 3 * nav_graph_columns);\n\tint nodeLocation = findValidLocation(navGraph, occupiedAreas, 0, 3 * nav_graph_columns, rand);\n\t\n\tantHills.push_back(AntHome(navGraph[antHillLocation], navGraph));\n\toccupiedAreas.push_back(&navGraph[antHillLocation]);\n\treturn antHillLocation;\n}\n\nvoid addAnts(vector<Node>& navGraph, AntHome& antHill, GuiEventManager& eventManager, vector<Ant>& ants)\n{\n\tRandom rand;\n\n\tconst int minAnts = 30;\n\tconst int maxAnts = 60;\n\n\tint antCount = rand.getInteger(minAnts, maxAnts);\n\tfor (int i = 0; i < antCount; ++i)\n\t{\n\t\tants.push_back(Ant(eventManager, antHill, antHill.getNavGraphHelper(), antHill.getNode()));\n\t}\n}\n\nint findValidLocation(vector<Node>& navGraph, vector<Node*>& occupiedAreas, int minAllowedNode, int maxAllowedNode, Random& rand)\n{\n\tbool validLocationFound = false;\n\twhile (!validLocationFound)\n\t{\n\t\tint nodeLocation = rand.getInteger(minAllowedNode, maxAllowedNode);\n\t\tif (!isOccupied(occupiedAreas, navGraph[nodeLocation]))\n\t\t{\n\t\t\treturn nodeLocation;\n\t\t}\n\t}\n\treturn -1;\n}\n\nbool isOccupied(vector<Node*> occupiedAreas, Node& location)\n{\n\tfor (auto& occupied : occupiedAreas)\n\t{\n\t\tif (occupied == &location)\n\t\t{\n\t\t\treturn true;\n\t\t}\n\t}\n\treturn false;\n}<commit_msg>Added diagonal edges to nodes<commit_after>#include \"RandomWorld.hpp\"\n#include \"..\/Simulator.hpp\"\n#include \"..\/agent\/Ant.hpp\"\n#include \"..\/gui\/GuiEventManager.hpp\"\n#include \"..\/sim\/nav\/Node.hpp\"\n#include \"..\/sim\/nav\/Edge.hpp\"\n#include \"..\/sim\/agent\/Ant.hpp\"\n#include \"..\/sim\/worldobject\/AntFoodPile.hpp\"\n#include \"..\/sim\/worldobject\/SolidObject.hpp\"\n#include \"..\/sim\/worldobject\/AntHome.hpp\"\n#include \"..\/util\/Random.hpp\"\n\n#include <vector>\n#include <memory>\n#include <cassert>\n\n\/\/ Christopher D. Canfield\n\/\/ November 2013\n\/\/ RandomWorld.cpp\n\nusing cdc::RandomWorld;\nusing cdc::GuiEventManager;\nusing cdc::Node;\nusing cdc::Edge;\nusing cdc::GridLocation;\nusing cdc::AntFoodPile;\nusing cdc::AntHome;\nusing cdc::Random;\nusing cdc::SolidObject;\nusing cdc::Ant;\n\nusing namespace sf;\nusing namespace std;\n\n\/\/ Creates the world's navigation graph.\nvoid createNavGraph(vector<Node>& navGraph);\n\n\/\/ Adds food piles to the world.\nvoid addFood(vector<Node>& navGraph, vector<Node*>& occupiedAreas, vector<AntFoodPile>& antFoodPiles);\n\n\/\/ Adds obstructions to the world.\nvoid addObstructions(vector<Node>& navGraph, vector<Node*>& occupiedAreas, vector<Sprite>& obstructions);\n\n\/\/ Adds the ant hill to the world.\n\/\/ Returns the ant hill location within the nav graph.\nint addAntHill(vector<Node>& navGraph, vector<Node*>& occupiedAreas, vector<AntHome>& antHills);\n\n\/\/ Adds a random number of ants to the world.\nvoid addAnts(vector<Node>& navGraph, AntHome& antHill, GuiEventManager& eventManager, vector<Ant>& ants);\n\n\/\/ Finds an unoccupied location between the min and max node (inclusive).\n\/\/ Returns the index of the node within the nav graph.\nint findValidLocation(vector<Node>& navGraph, vector<Node*>& occupiedAreas, int minAllowedNode, int maxAllowedNode, Random& rand);\n\n\/\/ Returns true if the node is occupied, or false if not.\nbool isOccupied(vector<Node*> occupiedAreas, Node& location);\n\n\n\/\/ TODO: the size of the world should be accessible outside of the class,\n\/\/ or the size should be passed into the world.\nconst int nav_graph_rows = 30;\nconst int nav_graph_columns = 30;\n\nconst int side_offset = 50;\nconst int node_offset = 100;\n\n\nRandomWorld::RandomWorld(GuiEventManager& eventManager) :\n\teventManager(eventManager)\n{\n}\n\nRandomWorld::~RandomWorld()\n{\n}\n\n\nvoid RandomWorld::create(GuiEventManager& eventManager)\n{\n\tcreateNavGraph(navGraph);\n\tvector<Node*> offLimitAreas;\n\n\taddFood(navGraph, offLimitAreas, antFoodPiles);\n\taddObstructions(navGraph, offLimitAreas, obstructions);\n\tint antHillLocation = addAntHill(navGraph, offLimitAreas, antHills);\n\taddAnts(navGraph, antHills[0], eventManager, ants);\n}\n\n\nvoid createNavGraph(vector<Node>& navGraph)\n{\n\tnavGraph.reserve(nav_graph_rows * nav_graph_rows);\n\tvector<vector<Node*>> navGraphEdgeHelper(nav_graph_rows, vector<Node*>(nav_graph_columns, nullptr));\n\n\tfor (int row = 0; row < nav_graph_rows; ++row)\n\t{\n\t\tfor (int column = 0; column < nav_graph_columns; ++column)\n\t\t{\n\t\t\tint pixelX = side_offset + (column * node_offset);\n\t\t\tint pixelY = side_offset + (row * node_offset);\n\t\t\tnavGraph.push_back(Node(GridLocation(row, column), pixelX, pixelY));\n\t\t\tnavGraphEdgeHelper[row][column] = &navGraph.back();\n\t\t}\n\t}\n\n\tfor (int row = 0; row < nav_graph_rows; ++row)\n\t{\n\t\tfor (int column = 0; column < nav_graph_columns; ++column)\n\t\t{\n\t\t\tauto& startNode = *navGraphEdgeHelper[row][column];\n\t\t\t\/\/ Add up connection.\n\t\t\tif (row > 0)\n\t\t\t{\n\t\t\t\tauto& endNode = *navGraphEdgeHelper[row - 1][column];\n\t\t\t\tauto edge = make_shared<Edge>(startNode, endNode, 1);\n\t\t\t\tif (!startNode.edgeExists(edge))\n\t\t\t\t{\n\t\t\t\t\tstartNode.addEdge(edge);\n\t\t\t\t}\n\t\t\t}\n\t\t\t\/\/ Add down connection.\n\t\t\tif (row < nav_graph_columns - 1)\n\t\t\t{\n\t\t\t\tauto& endNode = *navGraphEdgeHelper[row + 1][column];\n\t\t\t\tauto edge = make_shared<Edge>(startNode, endNode, 1);\n\t\t\t\tif (!startNode.edgeExists(edge))\n\t\t\t\t{\n\t\t\t\t\tstartNode.addEdge(edge);\n\t\t\t\t}\n\t\t\t}\n\t\t\t\/\/ Add left connection.\n\t\t\tif (column > 0)\n\t\t\t{\n\t\t\t\tauto& endNode = *navGraphEdgeHelper[row][column - 1];\n\t\t\t\tauto edge = make_shared<Edge>(startNode, endNode, 1);\n\t\t\t\tif (!startNode.edgeExists(edge))\n\t\t\t\t{\n\t\t\t\t\tstartNode.addEdge(edge);\n\t\t\t\t}\n\t\t\t}\n\t\t\t\/\/ Add right connection.\n\t\t\tif (column < nav_graph_columns - 1)\n\t\t\t{\n\t\t\t\tauto& endNode = *navGraphEdgeHelper[row][column + 1];\n\t\t\t\tauto edge = make_shared<Edge>(startNode, endNode, 1);\n\t\t\t\tif (!startNode.edgeExists(edge))\n\t\t\t\t{\n\t\t\t\t\tstartNode.addEdge(edge);\n\t\t\t\t}\n\t\t\t}\n\t\t\t\/\/ Add diagonal connections\n\t\t\tif (row > 0 && row < (nav_graph_rows - 1) && column > 0 && column < (nav_graph_columns - 1))\n\t\t\t{\n\t\t\t\tauto& diagonal1Node = *navGraphEdgeHelper[row + 1][column - 1];\n\t\t\t\tauto edge1 = make_shared<Edge>(startNode, diagonal1Node, 1);\n\t\t\t\t\n\t\t\t\tauto& diagonal2Node = *navGraphEdgeHelper[row + 1][column + 1];\n\t\t\t\tauto edge2 = make_shared<Edge>(startNode, diagonal2Node, 1);\n\n\t\t\t\tauto& diagonal3Node = *navGraphEdgeHelper[row - 1][column - 1];\n\t\t\t\tauto edge3 = make_shared<Edge>(startNode, diagonal3Node, 1);\n\n\t\t\t\tauto& diagonal4Node = *navGraphEdgeHelper[row - 1][column + 1];\n\t\t\t\tauto edge4 = make_shared<Edge>(startNode, diagonal4Node, 1);\n\n\t\t\t\tif (!startNode.edgeExists(edge1))\n\t\t\t\t{\n\t\t\t\t\tstartNode.addEdge(edge1);\n\t\t\t\t}\n\t\t\t\telse if (!startNode.edgeExists(edge2))\n\t\t\t\t{\n\t\t\t\t\tstartNode.addEdge(edge2);\n\t\t\t\t}\n\t\t\t\telse if (!startNode.edgeExists(edge3))\n\t\t\t\t{\n\t\t\t\t\tstartNode.addEdge(edge3);\n\t\t\t\t}\n\t\t\t\telse if (!startNode.edgeExists(edge4))\n\t\t\t\t{\n\t\t\t\t\tstartNode.addEdge(edge4);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\nvoid addFood(vector<Node>& navGraph, vector<Node*>& occupiedAreas, vector<AntFoodPile>& antFoodPiles)\n{\n\tRandom rand;\n\n\t\/\/ Add between 3 and 10 piles of food.\n\tconst int minFoodPiles = 3;\n\tconst int maxFoodPiles = 10;\n\n\tint foodPileCount = rand.getInteger(minFoodPiles, maxFoodPiles);\n\tfor (int i = 0; i < maxFoodPiles; ++i)\n\t{\n\t\tint nodeLocation = findValidLocation(navGraph, occupiedAreas, 0, navGraph.size(), rand);\n\t\tint foodInPile = rand.getInteger(50, 750);\n\t\tantFoodPiles.push_back(AntFoodPile(foodInPile, navGraph[nodeLocation]));\n\t\toccupiedAreas.push_back(&navGraph[nodeLocation]);\n\t}\n}\n\nvoid addObstructions(vector<Node>& navGraph, vector<Node*>& occupiedAreas, vector<Sprite>& obstructions)\n{\n\tRandom rand;\n\n\t\/\/ Add between 10 and 20 obstructions.\n\tconst int maxObstructions = 20;\n\tconst int minObstructions = 10;\n\n\tint obstructionCount = rand.getInteger(minObstructions, maxObstructions);\n\tfor (int i = 0; i < maxObstructions; ++i)\n\t{\n\t\tint nodeLocation = findValidLocation(navGraph, occupiedAreas, 0, navGraph.size(), rand);\n\t\tauto rock = SolidObject::createRock(navGraph, navGraph[nodeLocation].getPixelX(), navGraph[nodeLocation].getPixelY());\n\t\tobstructions.push_back(rock);\n\t\toccupiedAreas.push_back(&navGraph[nodeLocation]);\n\t}\n}\n\nint addAntHill(vector<Node>& navGraph, vector<Node*>& occupiedAreas, vector<AntHome>& antHills)\n{\n\tRandom rand;\n\n\t\/\/ Ant hill can be in any node within the first three rows.\n\tint antHillLocation = rand.getInteger(0, 3 * nav_graph_columns);\n\tint nodeLocation = findValidLocation(navGraph, occupiedAreas, 0, 3 * nav_graph_columns, rand);\n\t\n\tantHills.push_back(AntHome(navGraph[antHillLocation], navGraph));\n\toccupiedAreas.push_back(&navGraph[antHillLocation]);\n\treturn antHillLocation;\n}\n\nvoid addAnts(vector<Node>& navGraph, AntHome& antHill, GuiEventManager& eventManager, vector<Ant>& ants)\n{\n\tRandom rand;\n\n\tconst int minAnts = 30;\n\tconst int maxAnts = 60;\n\n\tint antCount = rand.getInteger(minAnts, maxAnts);\n\tfor (int i = 0; i < antCount; ++i)\n\t{\n\t\tants.push_back(Ant(eventManager, antHill, antHill.getNavGraphHelper(), antHill.getNode()));\n\t}\n}\n\nint findValidLocation(vector<Node>& navGraph, vector<Node*>& occupiedAreas, int minAllowedNode, int maxAllowedNode, Random& rand)\n{\n\tbool validLocationFound = false;\n\twhile (!validLocationFound)\n\t{\n\t\tint nodeLocation = rand.getInteger(minAllowedNode, maxAllowedNode);\n\t\tif (!isOccupied(occupiedAreas, navGraph[nodeLocation]))\n\t\t{\n\t\t\treturn nodeLocation;\n\t\t}\n\t}\n\treturn -1;\n}\n\nbool isOccupied(vector<Node*> occupiedAreas, Node& location)\n{\n\tfor (auto& occupied : occupiedAreas)\n\t{\n\t\tif (occupied == &location)\n\t\t{\n\t\t\treturn true;\n\t\t}\n\t}\n\treturn false;\n}<|endoftext|>"} {"text":"<commit_before>#include <jni.h>\n#include <stdlib.h>\n#include <time.h>\n#include <locale.h>\n\n#include <mpv\/client.h>\n#include <mpv\/opengl_cb.h>\n\n#include <EGL\/egl.h>\n\n#include \"main.h\"\n\nextern \"C\" {\n JNIEXPORT void JNICALL Java_is_xyz_mpv_MPVLib_init(JNIEnv* env, jobject obj);\n JNIEXPORT void JNICALL Java_is_xyz_mpv_MPVLib_resize(JNIEnv* env, jobject obj, jint width, jint height);\n JNIEXPORT void JNICALL Java_is_xyz_mpv_MPVLib_step(JNIEnv* env, jobject obj);\n};\n\n\nstatic void die(const char *msg)\n{\n ALOGE(\"%s\", msg);\n exit(1);\n}\n\nstatic void *get_proc_address_mpv(void *fn_ctx, const char *name)\n{\n return (void*)eglGetProcAddress(name);\n}\n\nmpv_handle *mpv;\nmpv_opengl_cb_context *mpv_gl;\n\nJNIEXPORT void JNICALL\nJava_is_xyz_mpv_MPVLib_init(JNIEnv* env, jobject obj) {\n ALOGE(\"init\");\n\n setlocale(LC_NUMERIC, \"C\");\n\n mpv = mpv_create();\n if (!mpv)\n die(\"context init failed\");\n\n int res;\n int terminal = 1;\n res = mpv_set_option(mpv, \"terminal\", MPV_FORMAT_FLAG, &terminal);\n ALOGE(\"mpv_set_option terminal ret %d\", res);\n res = mpv_set_option_string(mpv, \"msg-level\", \"all=v\");\n ALOGE(\"mpv_set_option_string msg-level ret %d\", res);\n\n if (mpv_initialize(mpv) < 0)\n die(\"mpv init failed\");\n mpv_gl = (mpv_opengl_cb_context*)mpv_get_sub_api(mpv, MPV_SUB_API_OPENGL_CB);\n if (!mpv_gl)\n die(\"failed to create mpv GL API handle\");\n\n if (mpv_opengl_cb_init_gl(mpv_gl, NULL, get_proc_address_mpv, NULL) < 0)\n die(\"failed to initialize mpv GL context\");\n\n if (mpv_set_option_string(mpv, \"vo\", \"opengl-cb\") < 0)\n die(\"failed to set VO\");\n if (mpv_set_option_string(mpv, \"ao\", \"null\") < 0)\n die(\"failed to set AO\");\n\n const char *cmd[] = {\"loadfile\", \"\/sdcard1\/1.mp4\", NULL};\n res = mpv_command(mpv, cmd);\n ALOGE(\"mpv_command returns %d\", res);\n}\n\nJNIEXPORT void JNICALL\nJava_is_xyz_mpv_MPVLib_resize(JNIEnv* env, jobject obj, jint width, jint height) {\n}\n\nJNIEXPORT void JNICALL\nJava_is_xyz_mpv_MPVLib_step(JNIEnv* env, jobject obj) {\n mpv_opengl_cb_draw(mpv_gl, 0, 1000, -1000);\n}\n<commit_msg>ao=openal<commit_after>#include <jni.h>\n#include <stdlib.h>\n#include <time.h>\n#include <locale.h>\n\n#include <mpv\/client.h>\n#include <mpv\/opengl_cb.h>\n\n#include <EGL\/egl.h>\n\n#include \"main.h\"\n\nextern \"C\" {\n JNIEXPORT void JNICALL Java_is_xyz_mpv_MPVLib_init(JNIEnv* env, jobject obj);\n JNIEXPORT void JNICALL Java_is_xyz_mpv_MPVLib_resize(JNIEnv* env, jobject obj, jint width, jint height);\n JNIEXPORT void JNICALL Java_is_xyz_mpv_MPVLib_step(JNIEnv* env, jobject obj);\n};\n\n\nstatic void die(const char *msg)\n{\n ALOGE(\"%s\", msg);\n exit(1);\n}\n\nstatic void *get_proc_address_mpv(void *fn_ctx, const char *name)\n{\n return (void*)eglGetProcAddress(name);\n}\n\nmpv_handle *mpv;\nmpv_opengl_cb_context *mpv_gl;\n\nJNIEXPORT void JNICALL\nJava_is_xyz_mpv_MPVLib_init(JNIEnv* env, jobject obj) {\n ALOGE(\"init\");\n\n setlocale(LC_NUMERIC, \"C\");\n\n mpv = mpv_create();\n if (!mpv)\n die(\"context init failed\");\n\n int res;\n int terminal = 1;\n res = mpv_set_option(mpv, \"terminal\", MPV_FORMAT_FLAG, &terminal);\n ALOGE(\"mpv_set_option terminal ret %d\", res);\n res = mpv_set_option_string(mpv, \"msg-level\", \"all=v\");\n ALOGE(\"mpv_set_option_string msg-level ret %d\", res);\n\n if (mpv_initialize(mpv) < 0)\n die(\"mpv init failed\");\n mpv_gl = (mpv_opengl_cb_context*)mpv_get_sub_api(mpv, MPV_SUB_API_OPENGL_CB);\n if (!mpv_gl)\n die(\"failed to create mpv GL API handle\");\n\n if (mpv_opengl_cb_init_gl(mpv_gl, NULL, get_proc_address_mpv, NULL) < 0)\n die(\"failed to initialize mpv GL context\");\n\n if (mpv_set_option_string(mpv, \"vo\", \"opengl-cb\") < 0)\n die(\"failed to set VO\");\n if (mpv_set_option_string(mpv, \"ao\", \"openal\") < 0)\n die(\"failed to set AO\");\n\n const char *cmd[] = {\"loadfile\", \"\/sdcard1\/1.mp4\", NULL};\n res = mpv_command(mpv, cmd);\n ALOGE(\"mpv_command returns %d\", res);\n}\n\nJNIEXPORT void JNICALL\nJava_is_xyz_mpv_MPVLib_resize(JNIEnv* env, jobject obj, jint width, jint height) {\n}\n\nJNIEXPORT void JNICALL\nJava_is_xyz_mpv_MPVLib_step(JNIEnv* env, jobject obj) {\n mpv_opengl_cb_draw(mpv_gl, 0, 1000, -1000);\n}\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: ary.hxx,v $\n *\n * $Revision: 1.5 $\n *\n * last change: $Author: hr $ $Date: 2007-11-02 14:36:51 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef ARY_ARY_HXX\n#define ARY_ARY_HXX\n\n\n\/\/ USED SERVICES\n \/\/ BASE CLASSES\n \/\/ OTHER\n\nnamespace ary\n{\nnamespace idl\n{\n class Gate;\n}\n\nnamespace cpp\n{\n class Gate;\n}\n}\n\n\n\nnamespace ary\n{\n\n\/** Starting point for all work with the\n Autodoc Sourcecode Repository.\n\n Create and destroy the repository and\n give access to the \"Gates\" for different tasks.\n\n @collab ::ary::cpp::Gate\n @collab ::ary::idl::Gate\n*\/\n\nclass Repository\n{\n public:\n \/\/ LIFECYCLE\n virtual ~Repository() {}\n static DYN Repository &\n Create_();\n \/\/ INQUIRY\n virtual const String &\n Title() const = 0;\n virtual const ::ary::cpp::Gate &\n Gate_Cpp() const = 0;\n virtual const ::ary::idl::Gate &\n Gate_Idl() const = 0;\n \/\/ ACCESS\n virtual ::ary::cpp::Gate &\n Gate_Cpp() = 0;\n virtual ::ary::idl::Gate &\n Gate_Idl() = 0;\n virtual void Set_Title(\n const String & i_sName ) = 0;\n};\n\n\n\n} \/\/ namespace ary\n#endif\n<commit_msg>INTEGRATION: CWS changefileheader (1.5.22); FILE MERGED 2008\/03\/28 16:00:56 rt 1.5.22.1: #i87441# Change license header to LPGL v3.<commit_after>\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2008 by Sun Microsystems, Inc.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: ary.hxx,v $\n * $Revision: 1.6 $\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * <http:\/\/www.openoffice.org\/license.html>\n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n#ifndef ARY_ARY_HXX\n#define ARY_ARY_HXX\n\n\n\/\/ USED SERVICES\n \/\/ BASE CLASSES\n \/\/ OTHER\n\nnamespace ary\n{\nnamespace idl\n{\n class Gate;\n}\n\nnamespace cpp\n{\n class Gate;\n}\n}\n\n\n\nnamespace ary\n{\n\n\/** Starting point for all work with the\n Autodoc Sourcecode Repository.\n\n Create and destroy the repository and\n give access to the \"Gates\" for different tasks.\n\n @collab ::ary::cpp::Gate\n @collab ::ary::idl::Gate\n*\/\n\nclass Repository\n{\n public:\n \/\/ LIFECYCLE\n virtual ~Repository() {}\n static DYN Repository &\n Create_();\n \/\/ INQUIRY\n virtual const String &\n Title() const = 0;\n virtual const ::ary::cpp::Gate &\n Gate_Cpp() const = 0;\n virtual const ::ary::idl::Gate &\n Gate_Idl() const = 0;\n \/\/ ACCESS\n virtual ::ary::cpp::Gate &\n Gate_Cpp() = 0;\n virtual ::ary::idl::Gate &\n Gate_Idl() = 0;\n virtual void Set_Title(\n const String & i_sName ) = 0;\n};\n\n\n\n} \/\/ namespace ary\n#endif\n<|endoftext|>"} {"text":"<commit_before>#include \"StdAfx.h\"\r\n#include \"Rw2Decoder.h\"\r\n\r\n\/*\r\n RawSpeed - RAW file decoder.\r\n\r\n Copyright (C) 2009 Klaus Post\r\n\r\n This library is free software; you can redistribute it and\/or\r\n modify it under the terms of the GNU Lesser General Public\r\n License as published by the Free Software Foundation; either\r\n version 2 of the License, or (at your option) any later version.\r\n\r\n This library is distributed in the hope that it will be useful,\r\n but WITHOUT ANY WARRANTY; without even the implied warranty of\r\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\r\n Lesser General Public License for more details.\r\n\r\n You should have received a copy of the GNU Lesser General Public\r\n License along with this library; if not, write to the Free Software\r\n Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\r\n\r\n http:\/\/www.klauspost.com\r\n*\/\r\nnamespace RawSpeed {\r\n\r\nRw2Decoder::Rw2Decoder(TiffIFD *rootIFD, FileMap* file) :\r\n RawDecoder(file), mRootIFD(rootIFD), input_start(0) {\r\n decoderVersion = 1;\r\n}\r\nRw2Decoder::~Rw2Decoder(void) {\r\n if (input_start)\r\n delete input_start;\r\n input_start = 0;\r\n if (mRootIFD)\r\n delete mRootIFD;\r\n mRootIFD = NULL;\r\n}\r\n\r\nRawImage Rw2Decoder::decodeRawInternal() {\r\n\r\n vector<TiffIFD*> data = mRootIFD->getIFDsWithTag(PANASONIC_STRIPOFFSET);\r\n\r\n bool isOldPanasonic = FALSE;\r\n\r\n if (data.empty()) {\r\n if (!mRootIFD->hasEntryRecursive(STRIPOFFSETS))\r\n ThrowRDE(\"RW2 Decoder: No image data found\");\r\n isOldPanasonic = TRUE;\r\n data = mRootIFD->getIFDsWithTag(STRIPOFFSETS);\r\n }\r\n\r\n TiffIFD* raw = data[0];\r\n uint32 height = raw->getEntry((TiffTag)3)->getShort();\r\n uint32 width = raw->getEntry((TiffTag)2)->getShort();\r\n\r\n if (isOldPanasonic) {\r\n ThrowRDE(\"Cannot decode old-style Panasonic RAW files\");\r\n TiffEntry *offsets = raw->getEntry(STRIPOFFSETS);\r\n TiffEntry *counts = raw->getEntry(STRIPBYTECOUNTS);\r\n\r\n if (offsets->count != 1) {\r\n ThrowRDE(\"RW2 Decoder: Multiple Strips found: %u\", offsets->count);\r\n }\r\n int off = offsets->getInt();\r\n if (!mFile->isValid(off))\r\n ThrowRDE(\"Panasonic RAW Decoder: Invalid image data offset, cannot decode.\");\r\n\r\n int count = counts->getInt();\r\n if (count != (int)(width*height*2))\r\n ThrowRDE(\"Panasonic RAW Decoder: Byte count is wrong.\");\r\n\r\n if (!mFile->isValid(off+count))\r\n ThrowRDE(\"Panasonic RAW Decoder: Invalid image data offset, cannot decode.\");\r\n \r\n mRaw->dim = iPoint2D(width, height);\r\n mRaw->createData();\r\n ByteStream input_start(mFile->getData(off), mFile->getSize() - off);\r\n iPoint2D pos(0, 0);\r\n readUncompressedRaw(input_start, mRaw->dim,pos, width*2, 16, BitOrder_Plain);\r\n\r\n } else {\r\n\r\n mRaw->dim = iPoint2D(width, height);\r\n mRaw->createData();\r\n TiffEntry *offsets = raw->getEntry(PANASONIC_STRIPOFFSET);\r\n\r\n if (offsets->count != 1) {\r\n ThrowRDE(\"RW2 Decoder: Multiple Strips found: %u\", offsets->count);\r\n }\r\n\r\n load_flags = 0x2008;\r\n int off = offsets->getInt();\r\n\r\n if (!mFile->isValid(off))\r\n ThrowRDE(\"RW2 Decoder: Invalid image data offset, cannot decode.\");\r\n\r\n input_start = new ByteStream(mFile->getData(off), mFile->getSize() - off);\r\n DecodeRw2();\r\n }\r\n return mRaw;\r\n}\r\n\r\nvoid Rw2Decoder::DecodeRw2() {\r\n startThreads();\r\n}\r\n\r\nvoid Rw2Decoder::decodeThreaded(RawDecoderThread * t) {\r\n int x, i, j, sh = 0, pred[2], nonz[2];\r\n int w = mRaw->dim.x \/ 14;\r\n uint32 y;\r\n\r\n bool zero_is_bad = false;\r\n map<string,string>::iterator zero_hint = hints.find(\"zero_is_bad\");\r\n if (zero_hint != hints.end())\r\n zero_is_bad = true;\r\n\r\n \/* 9 + 1\/7 bits per pixel *\/\r\n int skip = w * 14 * t->start_y * 9;\r\n skip += w * 2 * t->start_y;\r\n skip \/= 8;\r\n\r\n PanaBitpump bits(new ByteStream(input_start));\r\n bits.load_flags = load_flags;\r\n bits.skipBytes(skip);\r\n\r\n vector<uint32> zero_pos;\r\n for (y = t->start_y; y < t->end_y; y++) {\r\n ushort16* dest = (ushort16*)mRaw->getData(0, y);\r\n for (x = 0; x < w; x++) {\r\n pred[0] = pred[1] = nonz[0] = nonz[1] = 0;\r\n int u = 0;\r\n for (i = 0; i < 14; i++) {\r\n \/\/ Even pixels\r\n if (u == 2)\r\n {\r\n sh = 4 >> (3 - bits.getBits(2));\r\n u = -1;\r\n }\r\n if (nonz[0]) {\r\n if ((j = bits.getBits(8))) {\r\n if ((pred[0] -= 0x80 << sh) < 0 || sh == 4)\r\n pred[0] &= ~(-1 << sh);\r\n pred[0] += j << sh;\r\n }\r\n } else if ((nonz[0] = bits.getBits(8)) || i > 11)\r\n pred[0] = nonz[0] << 4 | bits.getBits(4);\r\n *dest++ = pred[0];\r\n if (zero_is_bad && 0 == pred[0])\r\n zero_pos.push_back((y<<16) | (x*14+i));\r\n\r\n \/\/ Odd pixels\r\n i++;\r\n u++;\r\n if (u == 2)\r\n {\r\n sh = 4 >> (3 - bits.getBits(2));\r\n u = -1;\r\n }\r\n if (nonz[1]) {\r\n if ((j = bits.getBits(8))) {\r\n if ((pred[1] -= 0x80 << sh) < 0 || sh == 4)\r\n pred[1] &= ~(-1 << sh);\r\n pred[1] += j << sh;\r\n }\r\n } else if ((nonz[1] = bits.getBits(8)) || i > 11)\r\n pred[1] = nonz[1] << 4 | bits.getBits(4);\r\n *dest++ = pred[1];\r\n if (zero_is_bad && 0 == pred[1])\r\n zero_pos.push_back((y<<16) | (x*14+i));\r\n u++;\r\n }\r\n }\r\n }\r\n if (zero_is_bad && !zero_pos.empty()) {\r\n pthread_mutex_lock(&mRaw->mBadPixelMutex);\r\n mRaw->mBadPixelPositions.insert(mRaw->mBadPixelPositions.end(), zero_pos.begin(), zero_pos.end());\r\n pthread_mutex_unlock(&mRaw->mBadPixelMutex);\r\n }\r\n}\r\n\r\nvoid Rw2Decoder::checkSupportInternal(CameraMetaData *meta) {\r\n vector<TiffIFD*> data = mRootIFD->getIFDsWithTag(MODEL);\r\n if (data.empty())\r\n ThrowRDE(\"RW2 Support check: Model name found\");\r\n\r\n string make = data[0]->getEntry(MAKE)->getString();\r\n string model = data[0]->getEntry(MODEL)->getString();\r\n if (!this->checkCameraSupported(meta, make, model, guessMode()))\r\n this->checkCameraSupported(meta, make, model, \"\");\r\n}\r\n\r\nvoid Rw2Decoder::decodeMetaDataInternal(CameraMetaData *meta) {\r\n mRaw->cfa.setCFA(CFA_BLUE, CFA_GREEN, CFA_GREEN2, CFA_RED);\r\n vector<TiffIFD*> data = mRootIFD->getIFDsWithTag(MODEL);\r\n\r\n if (data.empty())\r\n ThrowRDE(\"RW2 Meta Decoder: Model name not found\");\r\n if (!data[0]->hasEntry(MAKE))\r\n ThrowRDE(\"RW2 Support: Make name not found\");\r\n\r\n string make = data[0]->getEntry(MAKE)->getString();\r\n string model = data[0]->getEntry(MODEL)->getString();\r\n string mode = guessMode();\r\n int iso = 0;\r\n if (mRootIFD->hasEntryRecursive(PANASONIC_ISO_SPEED))\r\n iso = mRootIFD->getEntryRecursive(PANASONIC_ISO_SPEED)->getInt();\r\n\r\n if (this->checkCameraSupported(meta, make, model, mode)) {\r\n setMetaData(meta, make, model, mode, iso);\r\n } else {\r\n mRaw->mode = mode;\r\n _RPT1(0, \"Mode not found in DB: %s\", mode.c_str());\r\n setMetaData(meta, make, model, \"\", iso);\r\n }\r\n}\r\n\r\n\r\n\r\nstd::string Rw2Decoder::guessMode() {\r\n float ratio = 3.0f \/ 2.0f; \/\/ Default\r\n\r\n if (!mRaw->isAllocated())\r\n return \"\";\r\n\r\n ratio = (float)mRaw->dim.x \/ (float)mRaw->dim.y;\r\n\r\n float min_diff = fabs(ratio - 16.0f \/ 9.0f);\r\n std::string closest_match = \"16:9\";\r\n\r\n float t = fabs(ratio - 3.0f \/ 2.0f);\r\n if (t < min_diff) {\r\n closest_match = \"3:2\";\r\n min_diff = t;\r\n }\r\n\r\n t = fabs(ratio - 4.0f \/ 3.0f);\r\n if (t < min_diff) {\r\n closest_match = \"4:3\";\r\n min_diff = t;\r\n }\r\n\r\n t = fabs(ratio - 1.0f);\r\n if (t < min_diff) {\r\n closest_match = \"1:1\";\r\n min_diff = t;\r\n }\r\n _RPT1(0, \"Mode guess: '%s'\\n\", closest_match.c_str());\r\n return closest_match;\r\n}\r\n\r\n\r\nPanaBitpump::PanaBitpump(ByteStream* _input) : input(_input), vbits(0) {\r\n}\r\n\r\nPanaBitpump::~PanaBitpump() {\r\n if (input)\r\n delete input;\r\n input = 0;\r\n}\r\n\r\nvoid PanaBitpump::skipBytes(int bytes) {\r\n int blocks = (bytes \/ 0x4000) * 0x4000;\r\n input->skipBytes(blocks);\r\n for (int i = blocks; i < bytes; i++)\r\n getBits(8);\r\n}\r\n\r\nuint32 PanaBitpump::getBits(int nbits) {\r\n int byte;\r\n\r\n if (!vbits) {\r\n \/* On truncated files this routine will just return just for the truncated\r\n * part of the file. Since there is no chance of affecting output buffer\r\n * size we allow the decoder to decode this\r\n *\/\r\n if (input->getRemainSize() < 0x4000 - load_flags) {\r\n memcpy(buf + load_flags, input->getData(), input->getRemainSize());\r\n input->skipBytes(input->getRemainSize());\r\n } else {\r\n memcpy(buf + load_flags, input->getData(), 0x4000 - load_flags);\r\n input->skipBytes(0x4000 - load_flags);\r\n if (input->getRemainSize() < load_flags) {\r\n memcpy(buf, input->getData(), input->getRemainSize());\r\n input->skipBytes(input->getRemainSize());\r\n } else {\r\n memcpy(buf, input->getData(), load_flags);\r\n input->skipBytes(load_flags);\r\n }\r\n }\r\n }\r\n vbits = (vbits - nbits) & 0x1ffff;\r\n byte = vbits >> 3 ^ 0x3ff0;\r\n return (buf[byte] | buf[byte+1] << 8) >> (vbits & 7) & ~(-1 << nbits);\r\n}\r\n\r\n} \/\/ namespace RawSpeed\r\n<commit_msg>Read blacklevels from Panasonic metadata.<commit_after>#include \"StdAfx.h\"\r\n#include \"Rw2Decoder.h\"\r\n\r\n\/*\r\n RawSpeed - RAW file decoder.\r\n\r\n Copyright (C) 2009 Klaus Post\r\n\r\n This library is free software; you can redistribute it and\/or\r\n modify it under the terms of the GNU Lesser General Public\r\n License as published by the Free Software Foundation; either\r\n version 2 of the License, or (at your option) any later version.\r\n\r\n This library is distributed in the hope that it will be useful,\r\n but WITHOUT ANY WARRANTY; without even the implied warranty of\r\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\r\n Lesser General Public License for more details.\r\n\r\n You should have received a copy of the GNU Lesser General Public\r\n License along with this library; if not, write to the Free Software\r\n Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\r\n\r\n http:\/\/www.klauspost.com\r\n*\/\r\nnamespace RawSpeed {\r\n\r\nRw2Decoder::Rw2Decoder(TiffIFD *rootIFD, FileMap* file) :\r\n RawDecoder(file), mRootIFD(rootIFD), input_start(0) {\r\n decoderVersion = 1;\r\n}\r\nRw2Decoder::~Rw2Decoder(void) {\r\n if (input_start)\r\n delete input_start;\r\n input_start = 0;\r\n if (mRootIFD)\r\n delete mRootIFD;\r\n mRootIFD = NULL;\r\n}\r\n\r\nRawImage Rw2Decoder::decodeRawInternal() {\r\n\r\n vector<TiffIFD*> data = mRootIFD->getIFDsWithTag(PANASONIC_STRIPOFFSET);\r\n\r\n bool isOldPanasonic = FALSE;\r\n\r\n if (data.empty()) {\r\n if (!mRootIFD->hasEntryRecursive(STRIPOFFSETS))\r\n ThrowRDE(\"RW2 Decoder: No image data found\");\r\n isOldPanasonic = TRUE;\r\n data = mRootIFD->getIFDsWithTag(STRIPOFFSETS);\r\n }\r\n\r\n TiffIFD* raw = data[0];\r\n uint32 height = raw->getEntry((TiffTag)3)->getShort();\r\n uint32 width = raw->getEntry((TiffTag)2)->getShort();\r\n\r\n if (isOldPanasonic) {\r\n ThrowRDE(\"Cannot decode old-style Panasonic RAW files\");\r\n TiffEntry *offsets = raw->getEntry(STRIPOFFSETS);\r\n TiffEntry *counts = raw->getEntry(STRIPBYTECOUNTS);\r\n\r\n if (offsets->count != 1) {\r\n ThrowRDE(\"RW2 Decoder: Multiple Strips found: %u\", offsets->count);\r\n }\r\n int off = offsets->getInt();\r\n if (!mFile->isValid(off))\r\n ThrowRDE(\"Panasonic RAW Decoder: Invalid image data offset, cannot decode.\");\r\n\r\n int count = counts->getInt();\r\n if (count != (int)(width*height*2))\r\n ThrowRDE(\"Panasonic RAW Decoder: Byte count is wrong.\");\r\n\r\n if (!mFile->isValid(off+count))\r\n ThrowRDE(\"Panasonic RAW Decoder: Invalid image data offset, cannot decode.\");\r\n \r\n mRaw->dim = iPoint2D(width, height);\r\n mRaw->createData();\r\n ByteStream input_start(mFile->getData(off), mFile->getSize() - off);\r\n iPoint2D pos(0, 0);\r\n readUncompressedRaw(input_start, mRaw->dim,pos, width*2, 16, BitOrder_Plain);\r\n\r\n } else {\r\n\r\n mRaw->dim = iPoint2D(width, height);\r\n mRaw->createData();\r\n TiffEntry *offsets = raw->getEntry(PANASONIC_STRIPOFFSET);\r\n\r\n if (offsets->count != 1) {\r\n ThrowRDE(\"RW2 Decoder: Multiple Strips found: %u\", offsets->count);\r\n }\r\n\r\n load_flags = 0x2008;\r\n int off = offsets->getInt();\r\n\r\n if (!mFile->isValid(off))\r\n ThrowRDE(\"RW2 Decoder: Invalid image data offset, cannot decode.\");\r\n\r\n input_start = new ByteStream(mFile->getData(off), mFile->getSize() - off);\r\n DecodeRw2();\r\n }\r\n \/\/ Read blacklevels\r\n if (raw->hasEntry((TiffTag)0x1c) && raw->hasEntry((TiffTag)0x1d) && raw->hasEntry((TiffTag)0x1e)) {\r\n mRaw->blackLevelSeparate[0] = raw->getEntry((TiffTag)0x1c)->getInt() + 15;\r\n mRaw->blackLevelSeparate[1] = mRaw->blackLevelSeparate[2] = raw->getEntry((TiffTag)0x1d)->getInt() + 15;\r\n mRaw->blackLevelSeparate[3] = raw->getEntry((TiffTag)0x1e)->getInt() + 15;\r\n }\r\n return mRaw;\r\n}\r\n\r\nvoid Rw2Decoder::DecodeRw2() {\r\n startThreads();\r\n}\r\n\r\nvoid Rw2Decoder::decodeThreaded(RawDecoderThread * t) {\r\n int x, i, j, sh = 0, pred[2], nonz[2];\r\n int w = mRaw->dim.x \/ 14;\r\n uint32 y;\r\n\r\n bool zero_is_bad = false;\r\n map<string,string>::iterator zero_hint = hints.find(\"zero_is_bad\");\r\n if (zero_hint != hints.end())\r\n zero_is_bad = true;\r\n\r\n \/* 9 + 1\/7 bits per pixel *\/\r\n int skip = w * 14 * t->start_y * 9;\r\n skip += w * 2 * t->start_y;\r\n skip \/= 8;\r\n\r\n PanaBitpump bits(new ByteStream(input_start));\r\n bits.load_flags = load_flags;\r\n bits.skipBytes(skip);\r\n\r\n vector<uint32> zero_pos;\r\n for (y = t->start_y; y < t->end_y; y++) {\r\n ushort16* dest = (ushort16*)mRaw->getData(0, y);\r\n for (x = 0; x < w; x++) {\r\n pred[0] = pred[1] = nonz[0] = nonz[1] = 0;\r\n int u = 0;\r\n for (i = 0; i < 14; i++) {\r\n \/\/ Even pixels\r\n if (u == 2)\r\n {\r\n sh = 4 >> (3 - bits.getBits(2));\r\n u = -1;\r\n }\r\n if (nonz[0]) {\r\n if ((j = bits.getBits(8))) {\r\n if ((pred[0] -= 0x80 << sh) < 0 || sh == 4)\r\n pred[0] &= ~(-1 << sh);\r\n pred[0] += j << sh;\r\n }\r\n } else if ((nonz[0] = bits.getBits(8)) || i > 11)\r\n pred[0] = nonz[0] << 4 | bits.getBits(4);\r\n *dest++ = pred[0];\r\n if (zero_is_bad && 0 == pred[0])\r\n zero_pos.push_back((y<<16) | (x*14+i));\r\n\r\n \/\/ Odd pixels\r\n i++;\r\n u++;\r\n if (u == 2)\r\n {\r\n sh = 4 >> (3 - bits.getBits(2));\r\n u = -1;\r\n }\r\n if (nonz[1]) {\r\n if ((j = bits.getBits(8))) {\r\n if ((pred[1] -= 0x80 << sh) < 0 || sh == 4)\r\n pred[1] &= ~(-1 << sh);\r\n pred[1] += j << sh;\r\n }\r\n } else if ((nonz[1] = bits.getBits(8)) || i > 11)\r\n pred[1] = nonz[1] << 4 | bits.getBits(4);\r\n *dest++ = pred[1];\r\n if (zero_is_bad && 0 == pred[1])\r\n zero_pos.push_back((y<<16) | (x*14+i));\r\n u++;\r\n }\r\n }\r\n }\r\n if (zero_is_bad && !zero_pos.empty()) {\r\n pthread_mutex_lock(&mRaw->mBadPixelMutex);\r\n mRaw->mBadPixelPositions.insert(mRaw->mBadPixelPositions.end(), zero_pos.begin(), zero_pos.end());\r\n pthread_mutex_unlock(&mRaw->mBadPixelMutex);\r\n }\r\n}\r\n\r\nvoid Rw2Decoder::checkSupportInternal(CameraMetaData *meta) {\r\n vector<TiffIFD*> data = mRootIFD->getIFDsWithTag(MODEL);\r\n if (data.empty())\r\n ThrowRDE(\"RW2 Support check: Model name found\");\r\n\r\n string make = data[0]->getEntry(MAKE)->getString();\r\n string model = data[0]->getEntry(MODEL)->getString();\r\n if (!this->checkCameraSupported(meta, make, model, guessMode()))\r\n this->checkCameraSupported(meta, make, model, \"\");\r\n}\r\n\r\nvoid Rw2Decoder::decodeMetaDataInternal(CameraMetaData *meta) {\r\n mRaw->cfa.setCFA(CFA_BLUE, CFA_GREEN, CFA_GREEN2, CFA_RED);\r\n vector<TiffIFD*> data = mRootIFD->getIFDsWithTag(MODEL);\r\n\r\n if (data.empty())\r\n ThrowRDE(\"RW2 Meta Decoder: Model name not found\");\r\n if (!data[0]->hasEntry(MAKE))\r\n ThrowRDE(\"RW2 Support: Make name not found\");\r\n\r\n string make = data[0]->getEntry(MAKE)->getString();\r\n string model = data[0]->getEntry(MODEL)->getString();\r\n string mode = guessMode();\r\n int iso = 0;\r\n if (mRootIFD->hasEntryRecursive(PANASONIC_ISO_SPEED))\r\n iso = mRootIFD->getEntryRecursive(PANASONIC_ISO_SPEED)->getInt();\r\n\r\n if (this->checkCameraSupported(meta, make, model, mode)) {\r\n setMetaData(meta, make, model, mode, iso);\r\n } else {\r\n mRaw->mode = mode;\r\n _RPT1(0, \"Mode not found in DB: %s\", mode.c_str());\r\n setMetaData(meta, make, model, \"\", iso);\r\n }\r\n}\r\n\r\n\r\n\r\nstd::string Rw2Decoder::guessMode() {\r\n float ratio = 3.0f \/ 2.0f; \/\/ Default\r\n\r\n if (!mRaw->isAllocated())\r\n return \"\";\r\n\r\n ratio = (float)mRaw->dim.x \/ (float)mRaw->dim.y;\r\n\r\n float min_diff = fabs(ratio - 16.0f \/ 9.0f);\r\n std::string closest_match = \"16:9\";\r\n\r\n float t = fabs(ratio - 3.0f \/ 2.0f);\r\n if (t < min_diff) {\r\n closest_match = \"3:2\";\r\n min_diff = t;\r\n }\r\n\r\n t = fabs(ratio - 4.0f \/ 3.0f);\r\n if (t < min_diff) {\r\n closest_match = \"4:3\";\r\n min_diff = t;\r\n }\r\n\r\n t = fabs(ratio - 1.0f);\r\n if (t < min_diff) {\r\n closest_match = \"1:1\";\r\n min_diff = t;\r\n }\r\n _RPT1(0, \"Mode guess: '%s'\\n\", closest_match.c_str());\r\n return closest_match;\r\n}\r\n\r\n\r\nPanaBitpump::PanaBitpump(ByteStream* _input) : input(_input), vbits(0) {\r\n}\r\n\r\nPanaBitpump::~PanaBitpump() {\r\n if (input)\r\n delete input;\r\n input = 0;\r\n}\r\n\r\nvoid PanaBitpump::skipBytes(int bytes) {\r\n int blocks = (bytes \/ 0x4000) * 0x4000;\r\n input->skipBytes(blocks);\r\n for (int i = blocks; i < bytes; i++)\r\n getBits(8);\r\n}\r\n\r\nuint32 PanaBitpump::getBits(int nbits) {\r\n int byte;\r\n\r\n if (!vbits) {\r\n \/* On truncated files this routine will just return just for the truncated\r\n * part of the file. Since there is no chance of affecting output buffer\r\n * size we allow the decoder to decode this\r\n *\/\r\n if (input->getRemainSize() < 0x4000 - load_flags) {\r\n memcpy(buf + load_flags, input->getData(), input->getRemainSize());\r\n input->skipBytes(input->getRemainSize());\r\n } else {\r\n memcpy(buf + load_flags, input->getData(), 0x4000 - load_flags);\r\n input->skipBytes(0x4000 - load_flags);\r\n if (input->getRemainSize() < load_flags) {\r\n memcpy(buf, input->getData(), input->getRemainSize());\r\n input->skipBytes(input->getRemainSize());\r\n } else {\r\n memcpy(buf, input->getData(), load_flags);\r\n input->skipBytes(load_flags);\r\n }\r\n }\r\n }\r\n vbits = (vbits - nbits) & 0x1ffff;\r\n byte = vbits >> 3 ^ 0x3ff0;\r\n return (buf[byte] | buf[byte+1] << 8) >> (vbits & 7) & ~(-1 << nbits);\r\n}\r\n\r\n} \/\/ namespace RawSpeed\r\n<|endoftext|>"} {"text":"<commit_before>\/*\nCopyright (c) 2012-2015 The SSDB Authors. All rights reserved.\nUse of this source code is governed by a BSD-style license that can be\nfound in the LICENSE file.\n*\/\n#include <stdio.h>\n#include <stdlib.h>\n#include <string>\n#include <vector>\n#include \"split.h\"\n\nvoid welcome(){\n\tprintf(\"ssdb-split - Split ssdb-server\\n\");\n\tprintf(\"Copyright (c) 2012-2015 ssdb.io\\n\");\n\tprintf(\"\\n\");\n}\n\nvoid usage(int argc, char **argv){\n\tprintf(\"Usage:\\n\");\n\tprintf(\" %sr\\n\", argv[0]);\n\tprintf(\"\\n\");\n\tprintf(\"Options:\\n\");\n\tprintf(\" xx - \\n\");\n}\n\nint main(int argc, char **argv){\n\twelcome();\n\t\n\tint ret;\n\tSplit split;\n\tret = split.init(\"127.0.0.1\", 9000, \"127.0.0.1\", 8888, \"127.0.0.1\", 8889);\n\tif(ret == -1){\n\t\tfprintf(stderr, \"%d error!\\n\", __LINE__);\n\t\texit(1);\n\t}\n\t\n\tint64_t src_dbsize;\n\tssdb::Status s;\n\ts = split.src_client->dbsize(&src_dbsize);\n\tif(!s.ok()){\n\t\tfprintf(stderr, \"%d error!\\n\", __LINE__);\n\t\texit(1);\n\t}\n\t\n\tprintf(\"src dbsize: %lld\\n\", src_dbsize);\n\t\n\tint64_t total_moved = 0;\n\tstd::string min_key;\n\tstd::string max_key;\n\twhile(1){\n\t\tint64_t size = split.move_some();\n\t\tif(size == -1){\n\t\t\tfprintf(stderr, \"error!\\n\");\n\t\t\texit(1);\n\t\t}\n\t\tif(size == 0){\n\t\t\tfprintf(stderr, \"no data to move, end.\\n\");\n\t\t\tsplit.finish();\n\t\t\tbreak;\n\t\t}\n\t\ttotal_moved += size;\n\t\t\n\t\tint64_t src_dbsize_new;\n\t\tssdb::Status s;\n\t\ts = split.src_client->dbsize(&src_dbsize_new);\n\t\tif(!s.ok()){\n\t\t\tfprintf(stderr, \"error!\\n\");\n\t\t\texit(1);\n\t\t}\n\n\t\tprintf(\"moved: %lld, src_dbsize_old: %lld, src_dbsize_new: %lld\\n\", total_moved\/1024, src_dbsize\/1024, src_dbsize_new\/1024);\n\t\t\n\t\tif(total_moved > src_dbsize\/2 || (src_dbsize_new - src_dbsize) > src_dbsize\/10){\n\t\t\tfprintf(stderr, \"split end.\\n\");\n\t\t\tsplit.finish();\n\t\t\tbreak;\n\t\t}\n\t\t\n\t\tgetchar();\n\t}\n\t\n\treturn 0;\n}\n\n<commit_msg>update<commit_after>\/*\nCopyright (c) 2012-2015 The SSDB Authors. All rights reserved.\nUse of this source code is governed by a BSD-style license that can be\nfound in the LICENSE file.\n*\/\n#include <stdio.h>\n#include <stdlib.h>\n#include <string>\n#include <vector>\n#include \"split.h\"\n\nvoid welcome(){\n\tprintf(\"ssdb-split - Split ssdb-server\\n\");\n\tprintf(\"Copyright (c) 2012-2015 ssdb.io\\n\");\n\tprintf(\"\\n\");\n}\n\nvoid usage(int argc, char **argv){\n\tprintf(\"Usage:\\n\");\n\tprintf(\" %sr\\n\", argv[0]);\n\tprintf(\"\\n\");\n\tprintf(\"Options:\\n\");\n\tprintf(\" xx - \\n\");\n}\n\nint main(int argc, char **argv){\n\twelcome();\n\t\n\tint ret;\n\tSplit split;\n\tret = split.init(\"127.0.0.1\", 9000, \"127.0.0.1\", 8888, \"127.0.0.1\", 8889);\n\tif(ret == -1){\n\t\tfprintf(stderr, \"%d error!\\n\", __LINE__);\n\t\texit(1);\n\t}\n\t\n\tssdb::Status s;\n\tint64_t src_dbsize;\n\ts = split.src_client->dbsize(&src_dbsize);\n\tif(!s.ok()){\n\t\tfprintf(stderr, \"%d error!\\n\", __LINE__);\n\t\texit(1);\n\t}\n\t\n\tprintf(\"src dbsize: %lld\\n\", src_dbsize);\n\t\n\tint64_t total_moved = 0;\n\tstd::string min_key;\n\tstd::string max_key;\n\twhile(1){\n\t\tint64_t size = split.move_some();\n\t\tif(size == -1){\n\t\t\tfprintf(stderr, \"error!\\n\");\n\t\t\texit(1);\n\t\t}\n\t\tif(size == 0){\n\t\t\tfprintf(stderr, \"no data to move, end.\\n\");\n\t\t\tsplit.finish();\n\t\t\tbreak;\n\t\t}\n\t\ttotal_moved += size;\n\t\t\n\t\tint64_t src_dbsize_new;\n\t\ts = split.src_client->dbsize(&src_dbsize_new);\n\t\tif(!s.ok()){\n\t\t\tfprintf(stderr, \"error!\\n\");\n\t\t\texit(1);\n\t\t}\n\t\t\n\t\tint64_t dst_dbsize_new;\n\t\ts = split.dst_client->dbsize(&dst_dbsize_new);\n\t\tif(!s.ok()){\n\t\t\tfprintf(stderr, \"error!\\n\");\n\t\t\texit(1);\n\t\t}\n\n\t\tprintf(\"moved: %lld, src_dbsize_old: %lld, src_dbsize_new: %lld, dst_dbsize_new: %lld\\n\",\n\t\t\ttotal_moved\/1024, src_dbsize\/1024, src_dbsize_new\/1024, dst_dbsize_new\/1024);\n\t\t\n\t\tif(total_moved > src_dbsize\/2 || dst_dbsize_new > src_dbsize\/2 || (src_dbsize_new - src_dbsize) > src_dbsize\/10){\n\t\t\tfprintf(stderr, \"split end.\\n\");\n\t\t\tsplit.finish();\n\t\t\tbreak;\n\t\t}\n\t\t\n\t\tgetchar();\n\t}\n\t\n\treturn 0;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ ======================================================================== \/\/\n\/\/ Copyright 2009-2016 Intel Corporation \/\/\n\/\/ \/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\"); \/\/\n\/\/ you may not use this file except in compliance with the License. \/\/\n\/\/ You may obtain a copy of the License at \/\/\n\/\/ \/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0 \/\/\n\/\/ \/\/\n\/\/ Unless required by applicable law or agreed to in writing, software \/\/\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS, \/\/\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. \/\/\n\/\/ See the License for the specific language governing permissions and \/\/\n\/\/ limitations under the License. \/\/\n\/\/ ======================================================================== \/\/\n\n#include \"taskschedulerinternal.h\"\n#include \"..\/math\/math.h\"\n#include \"..\/sys\/sysinfo.h\"\n#include <algorithm>\n\nnamespace embree\n{\n size_t TaskScheduler::g_numThreads = 0;\n __thread TaskScheduler* TaskScheduler::g_instance = nullptr;\n __thread TaskScheduler::Thread* TaskScheduler::thread_local_thread = nullptr;\n TaskScheduler::ThreadPool* TaskScheduler::threadPool = nullptr;\n\n template<typename Predicate, typename Body>\n __forceinline void TaskScheduler::steal_loop(Thread& thread, const Predicate& pred, const Body& body)\n {\n while (true)\n {\n \/*! some rounds that yield *\/\n for (size_t i=0; i<32; i++)\n {\n \/*! some spinning rounds *\/\n const size_t threadCount = thread.threadCount();\n for (size_t j=0; j<1024; j+=threadCount)\n {\n if (!pred()) return;\n if (thread.scheduler->steal_from_other_threads(thread)) {\n i=j=0;\n body();\n }\n }\n yield();\n }\n }\n }\n\n \/*! run this task *\/\n __dllexport void TaskScheduler::Task::run (Thread& thread) \/\/ FIXME: avoid as many __dllexports as possible\n {\n \/* try to run if not already stolen *\/\n if (try_switch_state(INITIALIZED,DONE))\n {\n Task* prevTask = thread.task; \n thread.task = this;\n try {\n if (thread.scheduler->cancellingException == nullptr)\n closure->execute();\n } catch (...) {\n if (thread.scheduler->cancellingException == nullptr)\n thread.scheduler->cancellingException = std::current_exception();\n }\n thread.task = prevTask;\n add_dependencies(-1);\n }\n \n \/* steal until all dependencies have completed *\/\n steal_loop(thread,\n [&] () { return dependencies>0; },\n [&] () { while (thread.tasks.execute_local(thread,this)); });\n\n \/* now signal our parent task that we are finished *\/\n if (parent) \n parent->add_dependencies(-1);\n }\n\n __dllexport bool TaskScheduler::TaskQueue::execute_local(Thread& thread, Task* parent)\n {\n \/* stop if we run out of local tasks or reach the waiting task *\/\n if (right == 0 || &tasks[right-1] == parent)\n return false;\n \n \/* execute task *\/\n size_t oldRight = right;\n tasks[right-1].run(thread);\n if (right != oldRight) {\n THROW_RUNTIME_ERROR(\"you have to wait for spawned subtasks\");\n }\n \n \/* pop task and closure from stack *\/\n right--;\n if (tasks[right].stackPtr != size_t(-1))\n stackPtr = tasks[right].stackPtr;\n \n \/* also move left pointer *\/\n if (left >= right) left.store(right.load());\n \n return right != 0;\n }\n \n bool TaskScheduler::TaskQueue::steal(Thread& thread) \n {\n size_t l = left;\n if (l < right) \n l = left++;\n else \n return false;\n \n if (!tasks[l].try_steal(thread.tasks.tasks[thread.tasks.right]))\n return false;\n \n thread.tasks.right++;\n return true;\n }\n \n \/* we steal from the left *\/\n size_t TaskScheduler::TaskQueue::getTaskSizeAtLeft() \n {\t\n if (left >= right) return 0;\n return tasks[left].N;\n }\n\n static MutexSys g_mutex;\n static BarrierSys g_barrier(2);\n\n void threadPoolFunction(std::pair<TaskScheduler::ThreadPool*,size_t>* pair)\n {\n TaskScheduler::ThreadPool* pool = pair->first;\n size_t threadIndex = pair->second;\n g_barrier.wait();\n pool->thread_loop(threadIndex);\n }\n\n TaskScheduler::ThreadPool::ThreadPool(bool set_affinity)\n : numThreads(0), numThreadsRunning(0), set_affinity(set_affinity), running(false) {}\n\n __dllexport void TaskScheduler::ThreadPool::startThreads()\n {\n if (running) return;\n setNumThreads(numThreads,true);\n }\n\n void TaskScheduler::ThreadPool::setNumThreads(size_t newNumThreads, bool startThreads)\n {\n Lock<MutexSys> lock(g_mutex);\n \n if (newNumThreads == 0)\n newNumThreads = getNumberOfLogicalThreads();\n\n numThreads = newNumThreads;\n if (!startThreads && !running) return;\n running = true;\n size_t numThreadsActive = numThreadsRunning;\n\n mutex.lock();\n numThreadsRunning = newNumThreads;\n mutex.unlock();\n condition.notify_all();\n\n \/* start new threads *\/\n for (size_t t=numThreadsActive; t<numThreads; t++) \n {\n if (t == 0) continue;\n auto pair = std::make_pair(this,t);\n threads.push_back(createThread((thread_func)threadPoolFunction,&pair,4*1024*1024,set_affinity ? t : -1));\n g_barrier.wait();\n }\n\n \/* stop some threads if we reduce the number of threads *\/\n for (ssize_t t=numThreadsActive-1; t>=ssize_t(numThreadsRunning); t--) {\n if (t == 0) continue;\n embree::join(threads.back());\n threads.pop_back();\n }\n }\n\n TaskScheduler::ThreadPool::~ThreadPool()\n {\n \/* leave all taskschedulers *\/\n mutex.lock();\n numThreadsRunning = 0;\n mutex.unlock();\n condition.notify_all();\n\n \/* wait for threads to terminate *\/\n for (size_t i=0; i<threads.size(); i++) \n embree::join(threads[i]);\n }\n\n __dllexport void TaskScheduler::ThreadPool::add(const Ref<TaskScheduler>& scheduler)\n {\n mutex.lock();\n schedulers.push_back(scheduler);\n mutex.unlock();\n condition.notify_all();\n }\n\n __dllexport void TaskScheduler::ThreadPool::remove(const Ref<TaskScheduler>& scheduler)\n {\n Lock<MutexSys> lock(mutex);\n for (std::list<Ref<TaskScheduler> >::iterator it = schedulers.begin(); it != schedulers.end(); it++) {\n if (scheduler == *it) {\n schedulers.erase(it);\n return;\n }\n }\n }\n\n void TaskScheduler::ThreadPool::thread_loop(size_t globalThreadIndex)\n {\n while (globalThreadIndex < numThreadsRunning)\n {\n Ref<TaskScheduler> scheduler = NULL;\n ssize_t threadIndex = -1;\n {\n Lock<MutexSys> lock(mutex);\n condition.wait(mutex, [&] () { return globalThreadIndex >= numThreadsRunning || !schedulers.empty(); });\n if (globalThreadIndex >= numThreadsRunning) break;\n scheduler = schedulers.front();\n threadIndex = scheduler->allocThreadIndex();\n }\n scheduler->thread_loop(threadIndex);\n }\n }\n \n TaskScheduler::TaskScheduler()\n : threadCounter(0), anyTasksRunning(0), hasRootTask(false) \n {\n threadLocal.resize(2*getNumberOfLogicalThreads()); \/\/ FIXME: this has to be 2x as in the join mode the worker threads also join\n for (size_t i=0; i<threadLocal.size(); i++)\n threadLocal[i].store(nullptr);\n }\n \n TaskScheduler::~TaskScheduler() \n {\n assert(threadCounter == 0);\n }\n\n __dllexport size_t TaskScheduler::threadIndex() \n {\n Thread* thread = TaskScheduler::thread();\n if (thread) return thread->threadIndex;\n else return 0;\n }\n\n __dllexport size_t TaskScheduler::threadCount() {\n return threadPool->size();\n }\n\n __dllexport TaskScheduler* TaskScheduler::instance() \n {\n if (g_instance == NULL) {\n g_instance = new TaskScheduler;\n g_instance->refInc();\n }\n return g_instance;\n }\n\n void TaskScheduler::create(size_t numThreads, bool set_affinity)\n {\n if (!threadPool) threadPool = new TaskScheduler::ThreadPool(set_affinity);\n threadPool->setNumThreads(numThreads,false);\n }\n\n void TaskScheduler::destroy() {\n delete threadPool; threadPool = nullptr;\n }\n\n __dllexport ssize_t TaskScheduler::allocThreadIndex()\n {\n size_t threadIndex = threadCounter++;\n assert(threadIndex < threadLocal.size());\n return threadIndex;\n }\n\n void TaskScheduler::join()\n {\n mutex.lock();\n size_t threadIndex = allocThreadIndex();\n condition.wait(mutex, [&] () { return hasRootTask.load(); });\n mutex.unlock();\n std::exception_ptr except = thread_loop(threadIndex);\n if (except != nullptr) std::rethrow_exception(except);\n }\n\n void TaskScheduler::reset() {\n hasRootTask = false;\n }\n\n void TaskScheduler::wait_for_threads(size_t threadCount)\n {\n while (threadCounter < threadCount-1)\n __pause_cpu();\n }\n\n __dllexport TaskScheduler::Thread* TaskScheduler::thread() {\n return thread_local_thread;\n }\n\n __dllexport TaskScheduler::Thread* TaskScheduler::swapThread(Thread* thread) \n {\n Thread* old = thread_local_thread;\n thread_local_thread = thread;\n return old;\n }\n\n __dllexport bool TaskScheduler::wait() \n {\n Thread* thread = TaskScheduler::thread();\n if (thread == nullptr) return true;\n while (thread->tasks.execute_local(*thread,thread->task)) {};\n return thread->scheduler->cancellingException == nullptr;\n }\n\n std::exception_ptr TaskScheduler::thread_loop(size_t threadIndex)\n {\n \/* allocate thread structure *\/\n std::unique_ptr<Thread> mthread(new Thread(threadIndex,this)); \/\/ too large for stack allocation\n Thread& thread = *mthread;\n threadLocal[threadIndex].store(&thread);\n Thread* oldThread = swapThread(&thread);\n\n \/* main thread loop *\/\n while (anyTasksRunning)\n {\n steal_loop(thread,\n [&] () { return anyTasksRunning > 0; },\n [&] () { \n anyTasksRunning++;\n while (thread.tasks.execute_local(thread,nullptr));\n anyTasksRunning--;\n });\n }\n threadLocal[threadIndex].store(nullptr);\n swapThread(oldThread);\n\n \/* remember exception to throw *\/\n std::exception_ptr except = nullptr;\n if (cancellingException != nullptr) except = cancellingException;\n\n \/* wait for all threads to terminate *\/\n threadCounter--;\n#if defined(__WIN32__)\n\tsize_t loopIndex = 1;\n#endif\n#define LOOP_YIELD_THRESHOLD 4096\n\twhile (threadCounter > 0) {\n#if defined(__WIN32__)\n\t\tif ((loopIndex % LOOP_YIELD_THRESHOLD) == 0)\n\t\t\tyield();\n\t\telse\n\t\t\t_mm_pause(); \n#endif\t\t\n\t loopIndex++;\n\t}\n return except;\n }\n\n bool TaskScheduler::steal_from_other_threads(Thread& thread)\n {\n const size_t threadIndex = thread.threadIndex;\n const size_t threadCount = this->threadCounter;\n\n for (size_t i=1; i<threadCount; i++) \n {\n __pause_cpu(32);\n size_t otherThreadIndex = threadIndex+i;\n if (otherThreadIndex >= threadCount) otherThreadIndex -= threadCount;\n\n Thread* othread = threadLocal[otherThreadIndex].load();\n if (!othread)\n continue;\n\n if (othread->tasks.steal(thread)) \n return true; \n }\n\n return false;\n }\n\n __dllexport void TaskScheduler::startThreads() {\n threadPool->startThreads();\n }\n\n __dllexport void TaskScheduler::addScheduler(const Ref<TaskScheduler>& scheduler) {\n threadPool->add(scheduler);\n }\n\n __dllexport void TaskScheduler::removeScheduler(const Ref<TaskScheduler>& scheduler) {\n threadPool->remove(scheduler);\n }\n}\n<commit_msg>compile fix<commit_after>\/\/ ======================================================================== \/\/\n\/\/ Copyright 2009-2016 Intel Corporation \/\/\n\/\/ \/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\"); \/\/\n\/\/ you may not use this file except in compliance with the License. \/\/\n\/\/ You may obtain a copy of the License at \/\/\n\/\/ \/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0 \/\/\n\/\/ \/\/\n\/\/ Unless required by applicable law or agreed to in writing, software \/\/\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS, \/\/\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. \/\/\n\/\/ See the License for the specific language governing permissions and \/\/\n\/\/ limitations under the License. \/\/\n\/\/ ======================================================================== \/\/\n\n#include \"taskschedulerinternal.h\"\n#include \"..\/math\/math.h\"\n#include \"..\/sys\/sysinfo.h\"\n#include <algorithm>\n\nnamespace embree\n{\n size_t TaskScheduler::g_numThreads = 0;\n __thread TaskScheduler* TaskScheduler::g_instance = nullptr;\n __thread TaskScheduler::Thread* TaskScheduler::thread_local_thread = nullptr;\n TaskScheduler::ThreadPool* TaskScheduler::threadPool = nullptr;\n\n template<typename Predicate, typename Body>\n __forceinline void TaskScheduler::steal_loop(Thread& thread, const Predicate& pred, const Body& body)\n {\n while (true)\n {\n \/*! some rounds that yield *\/\n for (size_t i=0; i<32; i++)\n {\n \/*! some spinning rounds *\/\n const size_t threadCount = thread.threadCount();\n for (size_t j=0; j<1024; j+=threadCount)\n {\n if (!pred()) return;\n if (thread.scheduler->steal_from_other_threads(thread)) {\n i=j=0;\n body();\n }\n }\n yield();\n }\n }\n }\n\n \/*! run this task *\/\n __dllexport void TaskScheduler::Task::run (Thread& thread) \/\/ FIXME: avoid as many __dllexports as possible\n {\n \/* try to run if not already stolen *\/\n if (try_switch_state(INITIALIZED,DONE))\n {\n Task* prevTask = thread.task; \n thread.task = this;\n try {\n if (thread.scheduler->cancellingException == nullptr)\n closure->execute();\n } catch (...) {\n if (thread.scheduler->cancellingException == nullptr)\n thread.scheduler->cancellingException = std::current_exception();\n }\n thread.task = prevTask;\n add_dependencies(-1);\n }\n \n \/* steal until all dependencies have completed *\/\n steal_loop(thread,\n [&] () { return dependencies>0; },\n [&] () { while (thread.tasks.execute_local(thread,this)); });\n\n \/* now signal our parent task that we are finished *\/\n if (parent) \n parent->add_dependencies(-1);\n }\n\n __dllexport bool TaskScheduler::TaskQueue::execute_local(Thread& thread, Task* parent)\n {\n \/* stop if we run out of local tasks or reach the waiting task *\/\n if (right == 0 || &tasks[right-1] == parent)\n return false;\n \n \/* execute task *\/\n size_t oldRight = right;\n tasks[right-1].run(thread);\n if (right != oldRight) {\n THROW_RUNTIME_ERROR(\"you have to wait for spawned subtasks\");\n }\n \n \/* pop task and closure from stack *\/\n right--;\n if (tasks[right].stackPtr != size_t(-1))\n stackPtr = tasks[right].stackPtr;\n \n \/* also move left pointer *\/\n if (left >= right) left.store(right.load());\n \n return right != 0;\n }\n \n bool TaskScheduler::TaskQueue::steal(Thread& thread) \n {\n size_t l = left;\n if (l < right) \n l = left++;\n else \n return false;\n \n if (!tasks[l].try_steal(thread.tasks.tasks[thread.tasks.right]))\n return false;\n \n thread.tasks.right++;\n return true;\n }\n \n \/* we steal from the left *\/\n size_t TaskScheduler::TaskQueue::getTaskSizeAtLeft() \n {\t\n if (left >= right) return 0;\n return tasks[left].N;\n }\n\n static MutexSys g_mutex;\n static BarrierSys g_barrier(2);\n\n void threadPoolFunction(std::pair<TaskScheduler::ThreadPool*,size_t>* pair)\n {\n TaskScheduler::ThreadPool* pool = pair->first;\n size_t threadIndex = pair->second;\n g_barrier.wait();\n pool->thread_loop(threadIndex);\n }\n\n TaskScheduler::ThreadPool::ThreadPool(bool set_affinity)\n : numThreads(0), numThreadsRunning(0), set_affinity(set_affinity), running(false) {}\n\n __dllexport void TaskScheduler::ThreadPool::startThreads()\n {\n if (running) return;\n setNumThreads(numThreads,true);\n }\n\n void TaskScheduler::ThreadPool::setNumThreads(size_t newNumThreads, bool startThreads)\n {\n Lock<MutexSys> lock(g_mutex);\n \n if (newNumThreads == 0)\n newNumThreads = getNumberOfLogicalThreads();\n\n numThreads = newNumThreads;\n if (!startThreads && !running) return;\n running = true;\n size_t numThreadsActive = numThreadsRunning;\n\n mutex.lock();\n numThreadsRunning = newNumThreads;\n mutex.unlock();\n condition.notify_all();\n\n \/* start new threads *\/\n for (size_t t=numThreadsActive; t<numThreads; t++) \n {\n if (t == 0) continue;\n auto pair = std::make_pair(this,t);\n threads.push_back(createThread((thread_func)threadPoolFunction,&pair,4*1024*1024,set_affinity ? t : -1));\n g_barrier.wait();\n }\n\n \/* stop some threads if we reduce the number of threads *\/\n for (ssize_t t=numThreadsActive-1; t>=ssize_t(numThreadsRunning); t--) {\n if (t == 0) continue;\n embree::join(threads.back());\n threads.pop_back();\n }\n }\n\n TaskScheduler::ThreadPool::~ThreadPool()\n {\n \/* leave all taskschedulers *\/\n mutex.lock();\n numThreadsRunning = 0;\n mutex.unlock();\n condition.notify_all();\n\n \/* wait for threads to terminate *\/\n for (size_t i=0; i<threads.size(); i++) \n embree::join(threads[i]);\n }\n\n __dllexport void TaskScheduler::ThreadPool::add(const Ref<TaskScheduler>& scheduler)\n {\n mutex.lock();\n schedulers.push_back(scheduler);\n mutex.unlock();\n condition.notify_all();\n }\n\n __dllexport void TaskScheduler::ThreadPool::remove(const Ref<TaskScheduler>& scheduler)\n {\n Lock<MutexSys> lock(mutex);\n for (std::list<Ref<TaskScheduler> >::iterator it = schedulers.begin(); it != schedulers.end(); it++) {\n if (scheduler == *it) {\n schedulers.erase(it);\n return;\n }\n }\n }\n\n void TaskScheduler::ThreadPool::thread_loop(size_t globalThreadIndex)\n {\n while (globalThreadIndex < numThreadsRunning)\n {\n Ref<TaskScheduler> scheduler = NULL;\n ssize_t threadIndex = -1;\n {\n Lock<MutexSys> lock(mutex);\n condition.wait(mutex, [&] () { return globalThreadIndex >= numThreadsRunning || !schedulers.empty(); });\n if (globalThreadIndex >= numThreadsRunning) break;\n scheduler = schedulers.front();\n threadIndex = scheduler->allocThreadIndex();\n }\n scheduler->thread_loop(threadIndex);\n }\n }\n \n TaskScheduler::TaskScheduler()\n : threadCounter(0), anyTasksRunning(0), hasRootTask(false) \n {\n threadLocal.resize(2*getNumberOfLogicalThreads()); \/\/ FIXME: this has to be 2x as in the join mode the worker threads also join\n for (size_t i=0; i<threadLocal.size(); i++)\n threadLocal[i].store(nullptr);\n }\n \n TaskScheduler::~TaskScheduler() \n {\n assert(threadCounter == 0);\n }\n\n __dllexport size_t TaskScheduler::threadIndex() \n {\n Thread* thread = TaskScheduler::thread();\n if (thread) return thread->threadIndex;\n else return 0;\n }\n\n __dllexport size_t TaskScheduler::threadCount() {\n return threadPool->size();\n }\n\n __dllexport TaskScheduler* TaskScheduler::instance() \n {\n if (g_instance == NULL) {\n g_instance = new TaskScheduler;\n g_instance->refInc();\n }\n return g_instance;\n }\n\n void TaskScheduler::create(size_t numThreads, bool set_affinity)\n {\n if (!threadPool) threadPool = new TaskScheduler::ThreadPool(set_affinity);\n threadPool->setNumThreads(numThreads,false);\n }\n\n void TaskScheduler::destroy() {\n delete threadPool; threadPool = nullptr;\n }\n\n __dllexport ssize_t TaskScheduler::allocThreadIndex()\n {\n size_t threadIndex = threadCounter++;\n assert(threadIndex < threadLocal.size());\n return threadIndex;\n }\n\n void TaskScheduler::join()\n {\n mutex.lock();\n size_t threadIndex = allocThreadIndex();\n condition.wait(mutex, [&] () { return hasRootTask.load(); });\n mutex.unlock();\n std::exception_ptr except = thread_loop(threadIndex);\n if (except != nullptr) std::rethrow_exception(except);\n }\n\n void TaskScheduler::reset() {\n hasRootTask = false;\n }\n\n void TaskScheduler::wait_for_threads(size_t threadCount)\n {\n while (threadCounter < threadCount-1)\n __pause_cpu();\n }\n\n __dllexport TaskScheduler::Thread* TaskScheduler::thread() {\n return thread_local_thread;\n }\n\n __dllexport TaskScheduler::Thread* TaskScheduler::swapThread(Thread* thread) \n {\n Thread* old = thread_local_thread;\n thread_local_thread = thread;\n return old;\n }\n\n __dllexport bool TaskScheduler::wait() \n {\n Thread* thread = TaskScheduler::thread();\n if (thread == nullptr) return true;\n while (thread->tasks.execute_local(*thread,thread->task)) {};\n return thread->scheduler->cancellingException == nullptr;\n }\n\n std::exception_ptr TaskScheduler::thread_loop(size_t threadIndex)\n {\n \/* allocate thread structure *\/\n std::unique_ptr<Thread> mthread(new Thread(threadIndex,this)); \/\/ too large for stack allocation\n Thread& thread = *mthread;\n threadLocal[threadIndex].store(&thread);\n Thread* oldThread = swapThread(&thread);\n\n \/* main thread loop *\/\n while (anyTasksRunning)\n {\n steal_loop(thread,\n [&] () { return anyTasksRunning > 0; },\n [&] () { \n anyTasksRunning++;\n while (thread.tasks.execute_local(thread,nullptr));\n anyTasksRunning--;\n });\n }\n threadLocal[threadIndex].store(nullptr);\n swapThread(oldThread);\n\n \/* remember exception to throw *\/\n std::exception_ptr except = nullptr;\n if (cancellingException != nullptr) except = cancellingException;\n\n \/* wait for all threads to terminate *\/\n threadCounter--;\n#if defined(__WIN32__)\n\tsize_t loopIndex = 1;\n#endif\n#define LOOP_YIELD_THRESHOLD 4096\n\twhile (threadCounter > 0) {\n#if defined(__WIN32__)\n if ((loopIndex % LOOP_YIELD_THRESHOLD) == 0)\n yield();\n else\n _mm_pause(); \n\t loopIndex++;\n#else\n yield();\n#endif\t\t\n\t}\n return except;\n }\n\n bool TaskScheduler::steal_from_other_threads(Thread& thread)\n {\n const size_t threadIndex = thread.threadIndex;\n const size_t threadCount = this->threadCounter;\n\n for (size_t i=1; i<threadCount; i++) \n {\n __pause_cpu(32);\n size_t otherThreadIndex = threadIndex+i;\n if (otherThreadIndex >= threadCount) otherThreadIndex -= threadCount;\n\n Thread* othread = threadLocal[otherThreadIndex].load();\n if (!othread)\n continue;\n\n if (othread->tasks.steal(thread)) \n return true; \n }\n\n return false;\n }\n\n __dllexport void TaskScheduler::startThreads() {\n threadPool->startThreads();\n }\n\n __dllexport void TaskScheduler::addScheduler(const Ref<TaskScheduler>& scheduler) {\n threadPool->add(scheduler);\n }\n\n __dllexport void TaskScheduler::removeScheduler(const Ref<TaskScheduler>& scheduler) {\n threadPool->remove(scheduler);\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/**\n * Copyright (c) 2015 - The CM Authors <legal@clickmatcher.com>\n * All Rights Reserved.\n *\n * This file is CONFIDENTIAL -- Distribution or duplication of this material or\n * the information contained herein is strictly forbidden unless prior written\n * permission is obtained.\n *\/\n#include <stdlib.h>\n#include <unistd.h>\n#include <signal.h>\n#include \"fnord-base\/io\/filerepository.h\"\n#include \"fnord-base\/io\/fileutil.h\"\n#include \"fnord-base\/application.h\"\n#include \"fnord-base\/logging.h\"\n#include \"fnord-base\/random.h\"\n#include \"fnord-base\/thread\/eventloop.h\"\n#include \"fnord-base\/thread\/threadpool.h\"\n#include \"fnord-base\/thread\/queue.h\"\n#include \"fnord-base\/wallclock.h\"\n#include \"fnord-base\/cli\/flagparser.h\"\n#include \"fnord-eventdb\/TableRepository.h\"\n#include \"fnord-eventdb\/LogTableTail.h\"\n#include \"fnord-msg\/MessageEncoder.h\"\n#include \"fnord-msg\/MessagePrinter.h\"\n#include \"logjoin\/LogJoinBackfill.h\"\n#include \"IndexReader.h\"\n\n#include \"common.h\"\n#include \"schemas.h\"\n\nusing namespace cm;\nusing namespace fnord;\n\nfnord::thread::EventLoop ev;\nstd::atomic<bool> cm_logjoin_shutdown;\n\nvoid quit(int n) {\n cm_logjoin_shutdown = true;\n}\n\nstruct BackfillData {\n Option<String> shop_name;\n Option<String> shop_id;\n Option<uint64_t> category1;\n Option<uint64_t> category2;\n Option<uint64_t> category3;\n};\n\nint main(int argc, const char** argv) {\n fnord::Application::init();\n fnord::Application::logToStderr();\n\n cm_logjoin_shutdown = false;\n struct sigaction sa;\n memset(&sa, 0, sizeof(struct sigaction));\n sa.sa_handler = quit;\n sigaction(SIGTERM, &sa, NULL);\n sigaction(SIGQUIT, &sa, NULL);\n sigaction(SIGINT, &sa, NULL);\n\n fnord::cli::FlagParser flags;\n\n flags.defineFlag(\n \"datadir\",\n cli::FlagParser::T_STRING,\n true,\n NULL,\n NULL,\n \"datadir\",\n \"<path>\");\n\n flags.defineFlag(\n \"feedserver_addr\",\n fnord::cli::FlagParser::T_STRING,\n false,\n NULL,\n \"http:\/\/localhost:8000\",\n \"feedserver addr\",\n \"<addr>\");\n\n flags.defineFlag(\n \"batch_size\",\n fnord::cli::FlagParser::T_INTEGER,\n false,\n NULL,\n \"2048\",\n \"batch_size\",\n \"<num>\");\n\n flags.defineFlag(\n \"worker_threads\",\n fnord::cli::FlagParser::T_INTEGER,\n false,\n NULL,\n \"4\",\n \"threads\",\n \"<num>\");\n\n flags.defineFlag(\n \"upload_threads\",\n fnord::cli::FlagParser::T_INTEGER,\n false,\n NULL,\n \"1\",\n \"threads\",\n \"<num>\");\n\n flags.defineFlag(\n \"no_dryrun\",\n fnord::cli::FlagParser::T_SWITCH,\n false,\n NULL,\n NULL,\n \"no dryrun\",\n \"<bool>\");\n\n flags.defineFlag(\n \"index\",\n cli::FlagParser::T_STRING,\n false,\n NULL,\n NULL,\n \"index directory\",\n \"<path>\");\n\n flags.defineFlag(\n \"replica\",\n cli::FlagParser::T_STRING,\n true,\n NULL,\n NULL,\n \"replica id\",\n \"<id>\");\n\n flags.defineFlag(\n \"no_dryrun\",\n fnord::cli::FlagParser::T_SWITCH,\n false,\n NULL,\n NULL,\n \"no dryrun\",\n \"<bool>\");\n\n flags.defineFlag(\n \"loglevel\",\n fnord::cli::FlagParser::T_STRING,\n false,\n NULL,\n \"INFO\",\n \"loglevel\",\n \"<level>\");\n\n flags.parseArgv(argc, argv);\n\n Logger::get()->setMinimumLogLevel(\n strToLogLevel(flags.getString(\"loglevel\")));\n\n\n \/* args *\/\n auto index_path = flags.getString(\"index\");\n auto batch_size = flags.getInt(\"batch_size\");\n auto datadir = flags.getString(\"datadir\");\n auto dry_run = !flags.isSet(\"no_dryrun\");\n if (!FileUtil::isDirectory(datadir)) {\n RAISEF(kIOError, \"no such directory: $0\", datadir);\n }\n\n URI target_uri(\"http:\/\/localhost:8000\/eventdb\/insert?table=joined_sessions-dawanda\");\n\n\n \/* event loop, http *\/\n http::HTTPConnectionPool http(&ev);\n auto evloop_thread = std::thread([] {\n ev.run();\n });\n\n\n \/* open index *\/\n auto index = cm::IndexReader::openIndex(index_path);\n\n\n \/* open table *\/\n auto schema = joinedSessionsSchema();\n auto table = eventdb::TableReader::open(\n \"dawanda_joined_sessions\",\n flags.getString(\"replica\"),\n datadir,\n schema);\n\n\n auto queries_fid = schema.id(\"queries\");\n auto queryitems_fid = schema.id(\"queries.items\");\n auto qi_id_fid = schema.id(\"queries.items.item_id\");\n auto qi_sid_fid = schema.id(\"queries.items.shop_id\");\n auto qi_sname_fid = schema.id(\"queries.items.shop_name\");\n auto qi_c1_fid = schema.id(\"queries.items.category1\");\n auto qi_c2_fid = schema.id(\"queries.items.category2\");\n auto qi_c3_fid = schema.id(\"queries.items.category3\");\n\n HashMap<String, BackfillData> cache;\n\n \/* backfill fn *\/\n auto get_backfill_data = [&cache, &index] (const String& item_id) -> BackfillData {\n auto cached = cache.find(item_id);\n if (!(cached == cache.end())) {\n return cached->second;\n }\n\n BackfillData data;\n\n DocID docid { .docid = item_id };\n data.shop_id = index->docIndex()->getField(docid, \"shop_id\");\n data.shop_name = index->docIndex()->getField(docid, \"shop_name\");\n\n auto category1 = index->docIndex()->getField(docid, \"category1\");\n if (!category1.isEmpty()) {\n data.category1 = Some((uint64_t) std::stoull(category1.get()));\n }\n\n auto category2 = index->docIndex()->getField(docid, \"category2\");\n if (!category2.isEmpty()) {\n data.category2 = Some((uint64_t) std::stoull(category2.get()));\n }\n\n auto category3 = index->docIndex()->getField(docid, \"category3\");\n if (!category3.isEmpty()) {\n data.category3 = Some((uint64_t) std::stoull(category3.get()));\n }\n\n cache[item_id] = data;\n return data;\n };\n\n auto backfill_fn = [\n &schema,\n &queries_fid,\n &queryitems_fid,\n &qi_id_fid,\n &qi_sid_fid,\n &qi_sname_fid,\n &qi_c1_fid,\n &qi_c2_fid,\n &qi_c3_fid,\n &get_backfill_data\n ] (msg::MessageObject* record) {\n auto msg = msg::MessagePrinter::print(*record, schema);\n\n for (auto& q : record->asObject()) {\n if (q.id != queries_fid) {\n continue;\n }\n\n for (auto& qi : q.asObject()) {\n if (qi.id != queryitems_fid) {\n continue;\n }\n\n String item_id;\n for (auto cur = qi.asObject().begin(); cur != qi.asObject().end(); ) {\n auto id = cur->id;\n\n if (id == qi_id_fid) {\n item_id = cur->asString();\n ++cur;\n } else if (\n id == qi_sid_fid ||\n id == qi_sname_fid ||\n id == qi_c1_fid ||\n id == qi_c2_fid ||\n id == qi_c3_fid) {\n cur = qi.asObject().erase(cur);\n } else {\n ++cur;\n }\n }\n\n auto bdata = get_backfill_data(item_id);\n\n if (!bdata.shop_id.isEmpty()) {\n qi.addChild(qi_sid_fid, bdata.shop_id.get());\n }\n\n if (!bdata.shop_name.isEmpty()) {\n qi.addChild(qi_sname_fid, bdata.shop_name.get());\n }\n\n if (!bdata.category1.isEmpty()) {\n qi.addChild(qi_c1_fid, bdata.category1.get());\n }\n\n if (!bdata.category2.isEmpty()) {\n qi.addChild(qi_c2_fid, bdata.category2.get());\n }\n\n if (!bdata.category3.isEmpty()) {\n qi.addChild(qi_c3_fid, bdata.category3.get());\n }\n }\n }\n\n fnord::iputs(\"backfill: $0\", msg);\n };\n\n\n \/* run backfill *\/\n cm::LogJoinBackfill backfill(\n table,\n backfill_fn,\n \"\/tmp\/logjoin-backfill-state\",\n dry_run,\n target_uri,\n &http);\n\n backfill.start();\n\n while (backfill.process(batch_size)) {\n if (cm_logjoin_shutdown.load()) {\n break;\n }\n }\n\n backfill.shutdown();\n ev.shutdown();\n evloop_thread.join();\n\n return 0;\n}\n\n<commit_msg>print backfilled record<commit_after>\/**\n * Copyright (c) 2015 - The CM Authors <legal@clickmatcher.com>\n * All Rights Reserved.\n *\n * This file is CONFIDENTIAL -- Distribution or duplication of this material or\n * the information contained herein is strictly forbidden unless prior written\n * permission is obtained.\n *\/\n#include <stdlib.h>\n#include <unistd.h>\n#include <signal.h>\n#include \"fnord-base\/io\/filerepository.h\"\n#include \"fnord-base\/io\/fileutil.h\"\n#include \"fnord-base\/application.h\"\n#include \"fnord-base\/logging.h\"\n#include \"fnord-base\/random.h\"\n#include \"fnord-base\/thread\/eventloop.h\"\n#include \"fnord-base\/thread\/threadpool.h\"\n#include \"fnord-base\/thread\/queue.h\"\n#include \"fnord-base\/wallclock.h\"\n#include \"fnord-base\/cli\/flagparser.h\"\n#include \"fnord-eventdb\/TableRepository.h\"\n#include \"fnord-eventdb\/LogTableTail.h\"\n#include \"fnord-msg\/MessageEncoder.h\"\n#include \"fnord-msg\/MessagePrinter.h\"\n#include \"logjoin\/LogJoinBackfill.h\"\n#include \"IndexReader.h\"\n\n#include \"common.h\"\n#include \"schemas.h\"\n\nusing namespace cm;\nusing namespace fnord;\n\nfnord::thread::EventLoop ev;\nstd::atomic<bool> cm_logjoin_shutdown;\n\nvoid quit(int n) {\n cm_logjoin_shutdown = true;\n}\n\nstruct BackfillData {\n Option<String> shop_name;\n Option<String> shop_id;\n Option<uint64_t> category1;\n Option<uint64_t> category2;\n Option<uint64_t> category3;\n};\n\nint main(int argc, const char** argv) {\n fnord::Application::init();\n fnord::Application::logToStderr();\n\n cm_logjoin_shutdown = false;\n struct sigaction sa;\n memset(&sa, 0, sizeof(struct sigaction));\n sa.sa_handler = quit;\n sigaction(SIGTERM, &sa, NULL);\n sigaction(SIGQUIT, &sa, NULL);\n sigaction(SIGINT, &sa, NULL);\n\n fnord::cli::FlagParser flags;\n\n flags.defineFlag(\n \"datadir\",\n cli::FlagParser::T_STRING,\n true,\n NULL,\n NULL,\n \"datadir\",\n \"<path>\");\n\n flags.defineFlag(\n \"feedserver_addr\",\n fnord::cli::FlagParser::T_STRING,\n false,\n NULL,\n \"http:\/\/localhost:8000\",\n \"feedserver addr\",\n \"<addr>\");\n\n flags.defineFlag(\n \"batch_size\",\n fnord::cli::FlagParser::T_INTEGER,\n false,\n NULL,\n \"2048\",\n \"batch_size\",\n \"<num>\");\n\n flags.defineFlag(\n \"worker_threads\",\n fnord::cli::FlagParser::T_INTEGER,\n false,\n NULL,\n \"4\",\n \"threads\",\n \"<num>\");\n\n flags.defineFlag(\n \"upload_threads\",\n fnord::cli::FlagParser::T_INTEGER,\n false,\n NULL,\n \"1\",\n \"threads\",\n \"<num>\");\n\n flags.defineFlag(\n \"no_dryrun\",\n fnord::cli::FlagParser::T_SWITCH,\n false,\n NULL,\n NULL,\n \"no dryrun\",\n \"<bool>\");\n\n flags.defineFlag(\n \"index\",\n cli::FlagParser::T_STRING,\n false,\n NULL,\n NULL,\n \"index directory\",\n \"<path>\");\n\n flags.defineFlag(\n \"replica\",\n cli::FlagParser::T_STRING,\n true,\n NULL,\n NULL,\n \"replica id\",\n \"<id>\");\n\n flags.defineFlag(\n \"no_dryrun\",\n fnord::cli::FlagParser::T_SWITCH,\n false,\n NULL,\n NULL,\n \"no dryrun\",\n \"<bool>\");\n\n flags.defineFlag(\n \"loglevel\",\n fnord::cli::FlagParser::T_STRING,\n false,\n NULL,\n \"INFO\",\n \"loglevel\",\n \"<level>\");\n\n flags.parseArgv(argc, argv);\n\n Logger::get()->setMinimumLogLevel(\n strToLogLevel(flags.getString(\"loglevel\")));\n\n\n \/* args *\/\n auto index_path = flags.getString(\"index\");\n auto batch_size = flags.getInt(\"batch_size\");\n auto datadir = flags.getString(\"datadir\");\n auto dry_run = !flags.isSet(\"no_dryrun\");\n if (!FileUtil::isDirectory(datadir)) {\n RAISEF(kIOError, \"no such directory: $0\", datadir);\n }\n\n URI target_uri(\"http:\/\/localhost:8000\/eventdb\/insert?table=joined_sessions-dawanda\");\n\n\n \/* event loop, http *\/\n http::HTTPConnectionPool http(&ev);\n auto evloop_thread = std::thread([] {\n ev.run();\n });\n\n\n \/* open index *\/\n auto index = cm::IndexReader::openIndex(index_path);\n\n\n \/* open table *\/\n auto schema = joinedSessionsSchema();\n auto table = eventdb::TableReader::open(\n \"dawanda_joined_sessions\",\n flags.getString(\"replica\"),\n datadir,\n schema);\n\n\n auto queries_fid = schema.id(\"queries\");\n auto queryitems_fid = schema.id(\"queries.items\");\n auto qi_id_fid = schema.id(\"queries.items.item_id\");\n auto qi_sid_fid = schema.id(\"queries.items.shop_id\");\n auto qi_sname_fid = schema.id(\"queries.items.shop_name\");\n auto qi_c1_fid = schema.id(\"queries.items.category1\");\n auto qi_c2_fid = schema.id(\"queries.items.category2\");\n auto qi_c3_fid = schema.id(\"queries.items.category3\");\n\n HashMap<String, BackfillData> cache;\n\n \/* backfill fn *\/\n auto get_backfill_data = [&cache, &index] (const String& item_id) -> BackfillData {\n auto cached = cache.find(item_id);\n if (!(cached == cache.end())) {\n return cached->second;\n }\n\n BackfillData data;\n\n DocID docid { .docid = item_id };\n data.shop_id = index->docIndex()->getField(docid, \"shop_id\");\n data.shop_name = index->docIndex()->getField(docid, \"shop_name\");\n\n auto category1 = index->docIndex()->getField(docid, \"category1\");\n if (!category1.isEmpty()) {\n data.category1 = Some((uint64_t) std::stoull(category1.get()));\n }\n\n auto category2 = index->docIndex()->getField(docid, \"category2\");\n if (!category2.isEmpty()) {\n data.category2 = Some((uint64_t) std::stoull(category2.get()));\n }\n\n auto category3 = index->docIndex()->getField(docid, \"category3\");\n if (!category3.isEmpty()) {\n data.category3 = Some((uint64_t) std::stoull(category3.get()));\n }\n\n cache[item_id] = data;\n return data;\n };\n\n auto backfill_fn = [\n &schema,\n &queries_fid,\n &queryitems_fid,\n &qi_id_fid,\n &qi_sid_fid,\n &qi_sname_fid,\n &qi_c1_fid,\n &qi_c2_fid,\n &qi_c3_fid,\n &get_backfill_data\n ] (msg::MessageObject* record) {\n for (auto& q : record->asObject()) {\n if (q.id != queries_fid) {\n continue;\n }\n\n for (auto& qi : q.asObject()) {\n if (qi.id != queryitems_fid) {\n continue;\n }\n\n String item_id;\n for (auto cur = qi.asObject().begin(); cur != qi.asObject().end(); ) {\n auto id = cur->id;\n\n if (id == qi_id_fid) {\n item_id = cur->asString();\n ++cur;\n } else if (\n id == qi_sid_fid ||\n id == qi_sname_fid ||\n id == qi_c1_fid ||\n id == qi_c2_fid ||\n id == qi_c3_fid) {\n cur = qi.asObject().erase(cur);\n } else {\n ++cur;\n }\n }\n\n auto bdata = get_backfill_data(item_id);\n\n if (!bdata.shop_id.isEmpty()) {\n qi.addChild(qi_sid_fid, bdata.shop_id.get());\n }\n\n if (!bdata.shop_name.isEmpty()) {\n qi.addChild(qi_sname_fid, bdata.shop_name.get());\n }\n\n if (!bdata.category1.isEmpty()) {\n qi.addChild(qi_c1_fid, bdata.category1.get());\n }\n\n if (!bdata.category2.isEmpty()) {\n qi.addChild(qi_c2_fid, bdata.category2.get());\n }\n\n if (!bdata.category3.isEmpty()) {\n qi.addChild(qi_c3_fid, bdata.category3.get());\n }\n }\n }\n\n auto msg = msg::MessagePrinter::print(*record, schema);\n fnord::iputs(\"backfill: $0\", msg);\n };\n\n\n \/* run backfill *\/\n cm::LogJoinBackfill backfill(\n table,\n backfill_fn,\n \"\/tmp\/logjoin-backfill-state\",\n dry_run,\n target_uri,\n &http);\n\n backfill.start();\n\n while (backfill.process(batch_size)) {\n if (cm_logjoin_shutdown.load()) {\n break;\n }\n }\n\n backfill.shutdown();\n ev.shutdown();\n evloop_thread.join();\n\n return 0;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: storagehelper.cxx,v $\n *\n * $Revision: 1.2 $\n *\n * last change: $Author: kz $ $Date: 2004-10-04 21:07:02 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef _COM_SUN_STAR_EMBED_ELEMENTMODES_HPP_\n#include <com\/sun\/star\/embed\/ElementModes.hpp>\n#endif\n#ifndef _COM_SUN_STAR_EMBED_XENCRYPTIONPROTECTEDSOURCE_HPP_\n#include <com\/sun\/star\/embed\/XEncryptionProtectedSource.hpp>\n#endif\n\n#ifndef _COM_SUN_STAR_UCB_XSIMPLEFILEACCESS_HPP_\n#include <com\/sun\/star\/ucb\/XSimpleFileAccess.hpp>\n#endif\n\n#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_\n#include <com\/sun\/star\/beans\/XPropertySet.hpp>\n#endif\n\n#include <comphelper\/fileformat.h>\n#include <comphelper\/storagehelper.hxx>\n#include <comphelper\/processfactory.hxx>\n\nusing namespace ::com::sun::star;\n\nnamespace comphelper {\n\n\/\/ ----------------------------------------------------------------------\nuno::Reference< lang::XSingleServiceFactory > OStorageHelper::GetStorageFactory(\n const uno::Reference< lang::XMultiServiceFactory >& xSF )\n throw ( uno::Exception )\n{\n uno::Reference< lang::XMultiServiceFactory > xFactory = xSF.is() ? xSF : ::comphelper::getProcessServiceFactory();\n if ( !xFactory.is() )\n throw uno::RuntimeException();\n\n uno::Reference < lang::XSingleServiceFactory > xStorageFactory(\n xFactory->createInstance ( ::rtl::OUString::createFromAscii( \"com.sun.star.embed.StorageFactory\" ) ),\n uno::UNO_QUERY );\n\n if ( !xStorageFactory.is() )\n throw uno::RuntimeException();\n\n return xStorageFactory;\n}\n\n\/\/ ----------------------------------------------------------------------\nuno::Reference< embed::XStorage > OStorageHelper::GetTemporaryStorage(\n const uno::Reference< lang::XMultiServiceFactory >& xFactory )\n throw ( uno::Exception )\n{\n uno::Reference< embed::XStorage > xTempStorage( GetStorageFactory( xFactory )->createInstance(),\n uno::UNO_QUERY );\n if ( !xTempStorage.is() )\n throw uno::RuntimeException();\n\n return xTempStorage;\n}\n\n\/\/ ----------------------------------------------------------------------\nuno::Reference< embed::XStorage > OStorageHelper::GetStorageFromURL(\n const ::rtl::OUString& aURL,\n sal_Int32 nStorageMode,\n const uno::Reference< lang::XMultiServiceFactory >& xFactory )\n throw ( uno::Exception )\n{\n uno::Sequence< uno::Any > aArgs( 2 );\n aArgs[0] <<= aURL;\n aArgs[1] <<= nStorageMode;\n\n uno::Reference< embed::XStorage > xTempStorage( GetStorageFactory( xFactory )->createInstanceWithArguments( aArgs ),\n uno::UNO_QUERY );\n if ( !xTempStorage.is() )\n throw uno::RuntimeException();\n\n return xTempStorage;\n}\n\n\/\/ ----------------------------------------------------------------------\nuno::Reference< embed::XStorage > OStorageHelper::GetStorageFromInputStream(\n const uno::Reference < io::XInputStream >& xStream,\n const uno::Reference< lang::XMultiServiceFactory >& xFactory )\n throw ( uno::Exception )\n{\n uno::Sequence< uno::Any > aArgs( 2 );\n aArgs[0] <<= xStream;\n aArgs[1] <<= embed::ElementModes::READ;\n\n uno::Reference< embed::XStorage > xTempStorage( GetStorageFactory( xFactory )->createInstanceWithArguments( aArgs ),\n uno::UNO_QUERY );\n if ( !xTempStorage.is() )\n throw uno::RuntimeException();\n\n return xTempStorage;\n}\n\n\/\/ ----------------------------------------------------------------------\nuno::Reference< embed::XStorage > OStorageHelper::GetStorageFromStream(\n const uno::Reference < io::XStream >& xStream,\n sal_Int32 nStorageMode,\n const uno::Reference< lang::XMultiServiceFactory >& xFactory )\n throw ( uno::Exception )\n{\n uno::Sequence< uno::Any > aArgs( 2 );\n aArgs[0] <<= xStream;\n aArgs[1] <<= nStorageMode;\n\n uno::Reference< embed::XStorage > xTempStorage( GetStorageFactory( xFactory )->createInstanceWithArguments( aArgs ),\n uno::UNO_QUERY );\n if ( !xTempStorage.is() )\n throw uno::RuntimeException();\n\n return xTempStorage;\n}\n\n\/\/ ----------------------------------------------------------------------\nvoid OStorageHelper::CopyInputToOutput(\n const uno::Reference< io::XInputStream >& xInput,\n const uno::Reference< io::XOutputStream >& xOutput )\n throw ( uno::Exception )\n{\n static const sal_Int32 nConstBufferSize = 32000;\n\n sal_Int32 nRead;\n uno::Sequence < sal_Int8 > aSequence ( nConstBufferSize );\n\n do\n {\n nRead = xInput->readBytes ( aSequence, nConstBufferSize );\n if ( nRead < nConstBufferSize )\n {\n uno::Sequence < sal_Int8 > aTempBuf ( aSequence.getConstArray(), nRead );\n xOutput->writeBytes ( aTempBuf );\n }\n else\n xOutput->writeBytes ( aSequence );\n }\n while ( nRead == nConstBufferSize );\n}\n\n\/\/ ----------------------------------------------------------------------\nuno::Reference< io::XInputStream > OStorageHelper::GetInputStreamFromURL(\n const ::rtl::OUString& aURL,\n const uno::Reference< lang::XMultiServiceFactory >& xSF )\n throw ( uno::Exception )\n{\n uno::Reference< lang::XMultiServiceFactory > xFactory = xSF.is() ? xSF : ::comphelper::getProcessServiceFactory();\n if ( !xFactory.is() )\n throw uno::RuntimeException();\n\n uno::Reference < ::com::sun::star::ucb::XSimpleFileAccess > xTempAccess(\n xFactory->createInstance ( ::rtl::OUString::createFromAscii( \"com.sun.star.ucb.SimpleFileAccess\" ) ),\n uno::UNO_QUERY );\n\n if ( !xTempAccess.is() )\n throw uno::RuntimeException();\n\n uno::Reference< io::XInputStream > xInputStream = xTempAccess->openFileRead( aURL );\n if ( !xInputStream.is() )\n throw uno::RuntimeException();\n\n return xInputStream;\n}\n\n\/\/ ----------------------------------------------------------------------\nvoid OStorageHelper::SetCommonStoragePassword(\n const uno::Reference< embed::XStorage >& xStorage,\n const ::rtl::OUString& aPass )\n throw ( uno::Exception )\n{\n uno::Reference< embed::XEncryptionProtectedSource > xEncrSet( xStorage, uno::UNO_QUERY );\n if ( !xEncrSet.is() )\n throw io::IOException(); \/\/ TODO\n\n xEncrSet->setEncryptionPassword( aPass );\n}\n\n\/\/ ----------------------------------------------------------------------\nsal_Int32 OStorageHelper::GetXStorageFormat(\n const uno::Reference< embed::XStorage >& xStorage )\n throw ( uno::Exception )\n{\n uno::Reference< beans::XPropertySet > xStorProps( xStorage, uno::UNO_QUERY_THROW );\n\n ::rtl::OUString aMediaType;\n xStorProps->getPropertyValue( ::rtl::OUString::createFromAscii( \"MediaType\" ) ) >>= aMediaType;\n\n sal_Int32 nResult = 0;\n\n \/\/ TODO\/LATER: the filter configuration could be used to detect it later, or batter a special service\n if ( aMediaType.equalsIgnoreAsciiCase( ::rtl::OUString::createFromAscii( \"application\/vnd.sun.xml.writer\" ) )\n || aMediaType.equalsIgnoreAsciiCase( ::rtl::OUString::createFromAscii( \"application\/vnd.sun.xml.writer.web\" ) )\n || aMediaType.equalsIgnoreAsciiCase( ::rtl::OUString::createFromAscii( \"application\/vnd.sun.xml.writer.global\" ) )\n || aMediaType.equalsIgnoreAsciiCase( ::rtl::OUString::createFromAscii( \"application\/vnd.sun.xml.draw\" ) )\n || aMediaType.equalsIgnoreAsciiCase( ::rtl::OUString::createFromAscii( \"application\/vnd.sun.xml.impress\" ) )\n || aMediaType.equalsIgnoreAsciiCase( ::rtl::OUString::createFromAscii( \"application\/vnd.sun.xml.calc\" ) )\n || aMediaType.equalsIgnoreAsciiCase( ::rtl::OUString::createFromAscii( \"application\/vnd.sun.xml.chart\" ) )\n || aMediaType.equalsIgnoreAsciiCase( ::rtl::OUString::createFromAscii( \"application\/vnd.sun.xml.math\" ) ) )\n {\n nResult = SOFFICE_FILEFORMAT_60;\n }\n else if ( aMediaType.equalsIgnoreAsciiCase( ::rtl::OUString::createFromAscii( \"application\/x-vnd.oasis.openoffice.text\" ) )\n || aMediaType.equalsIgnoreAsciiCase( ::rtl::OUString::createFromAscii( \"application\/x-vnd.oasis.openoffice.text-web\" ) )\n || aMediaType.equalsIgnoreAsciiCase( ::rtl::OUString::createFromAscii( \"application\/x-vnd.oasis.openoffice.text-global\" ) )\n || aMediaType.equalsIgnoreAsciiCase( ::rtl::OUString::createFromAscii( \"application\/x-vnd.oasis.openoffice.drawing\" ) )\n || aMediaType.equalsIgnoreAsciiCase( ::rtl::OUString::createFromAscii( \"application\/x-vnd.oasis.openoffice.presentation\" ) )\n || aMediaType.equalsIgnoreAsciiCase( ::rtl::OUString::createFromAscii( \"application\/x-vnd.oasis.openoffice.spreadsheet\" ) )\n || aMediaType.equalsIgnoreAsciiCase( ::rtl::OUString::createFromAscii( \"application\/x-vnd.oasis.openoffice.chart\" ) )\n || aMediaType.equalsIgnoreAsciiCase( ::rtl::OUString::createFromAscii( \"application\/x-vnd.oasis.openoffice.math\" ) ) )\n {\n nResult = SOFFICE_FILEFORMAT_8;\n }\n else\n throw uno::Exception();\n\n return nResult;\n}\n\n}\n\n<commit_msg>INTEGRATION: CWS fwkp2fix02 (1.2.34); FILE MERGED 2004\/11\/12 12:14:17 mba 1.2.34.1: #i36981#: math objects couldn't be loaded<commit_after>\/*************************************************************************\n *\n * $RCSfile: storagehelper.cxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: obo $ $Date: 2004-11-17 15:36:09 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef _COM_SUN_STAR_EMBED_ELEMENTMODES_HPP_\n#include <com\/sun\/star\/embed\/ElementModes.hpp>\n#endif\n#ifndef _COM_SUN_STAR_EMBED_XENCRYPTIONPROTECTEDSOURCE_HPP_\n#include <com\/sun\/star\/embed\/XEncryptionProtectedSource.hpp>\n#endif\n\n#ifndef _COM_SUN_STAR_UCB_XSIMPLEFILEACCESS_HPP_\n#include <com\/sun\/star\/ucb\/XSimpleFileAccess.hpp>\n#endif\n\n#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_\n#include <com\/sun\/star\/beans\/XPropertySet.hpp>\n#endif\n\n#include <comphelper\/fileformat.h>\n#include <comphelper\/storagehelper.hxx>\n#include <comphelper\/processfactory.hxx>\n\nusing namespace ::com::sun::star;\n\nnamespace comphelper {\n\n\/\/ ----------------------------------------------------------------------\nuno::Reference< lang::XSingleServiceFactory > OStorageHelper::GetStorageFactory(\n const uno::Reference< lang::XMultiServiceFactory >& xSF )\n throw ( uno::Exception )\n{\n uno::Reference< lang::XMultiServiceFactory > xFactory = xSF.is() ? xSF : ::comphelper::getProcessServiceFactory();\n if ( !xFactory.is() )\n throw uno::RuntimeException();\n\n uno::Reference < lang::XSingleServiceFactory > xStorageFactory(\n xFactory->createInstance ( ::rtl::OUString::createFromAscii( \"com.sun.star.embed.StorageFactory\" ) ),\n uno::UNO_QUERY );\n\n if ( !xStorageFactory.is() )\n throw uno::RuntimeException();\n\n return xStorageFactory;\n}\n\n\/\/ ----------------------------------------------------------------------\nuno::Reference< embed::XStorage > OStorageHelper::GetTemporaryStorage(\n const uno::Reference< lang::XMultiServiceFactory >& xFactory )\n throw ( uno::Exception )\n{\n uno::Reference< embed::XStorage > xTempStorage( GetStorageFactory( xFactory )->createInstance(),\n uno::UNO_QUERY );\n if ( !xTempStorage.is() )\n throw uno::RuntimeException();\n\n return xTempStorage;\n}\n\n\/\/ ----------------------------------------------------------------------\nuno::Reference< embed::XStorage > OStorageHelper::GetStorageFromURL(\n const ::rtl::OUString& aURL,\n sal_Int32 nStorageMode,\n const uno::Reference< lang::XMultiServiceFactory >& xFactory )\n throw ( uno::Exception )\n{\n uno::Sequence< uno::Any > aArgs( 2 );\n aArgs[0] <<= aURL;\n aArgs[1] <<= nStorageMode;\n\n uno::Reference< embed::XStorage > xTempStorage( GetStorageFactory( xFactory )->createInstanceWithArguments( aArgs ),\n uno::UNO_QUERY );\n if ( !xTempStorage.is() )\n throw uno::RuntimeException();\n\n return xTempStorage;\n}\n\n\/\/ ----------------------------------------------------------------------\nuno::Reference< embed::XStorage > OStorageHelper::GetStorageFromInputStream(\n const uno::Reference < io::XInputStream >& xStream,\n const uno::Reference< lang::XMultiServiceFactory >& xFactory )\n throw ( uno::Exception )\n{\n uno::Sequence< uno::Any > aArgs( 2 );\n aArgs[0] <<= xStream;\n aArgs[1] <<= embed::ElementModes::READ;\n\n uno::Reference< embed::XStorage > xTempStorage( GetStorageFactory( xFactory )->createInstanceWithArguments( aArgs ),\n uno::UNO_QUERY );\n if ( !xTempStorage.is() )\n throw uno::RuntimeException();\n\n return xTempStorage;\n}\n\n\/\/ ----------------------------------------------------------------------\nuno::Reference< embed::XStorage > OStorageHelper::GetStorageFromStream(\n const uno::Reference < io::XStream >& xStream,\n sal_Int32 nStorageMode,\n const uno::Reference< lang::XMultiServiceFactory >& xFactory )\n throw ( uno::Exception )\n{\n uno::Sequence< uno::Any > aArgs( 2 );\n aArgs[0] <<= xStream;\n aArgs[1] <<= nStorageMode;\n\n uno::Reference< embed::XStorage > xTempStorage( GetStorageFactory( xFactory )->createInstanceWithArguments( aArgs ),\n uno::UNO_QUERY );\n if ( !xTempStorage.is() )\n throw uno::RuntimeException();\n\n return xTempStorage;\n}\n\n\/\/ ----------------------------------------------------------------------\nvoid OStorageHelper::CopyInputToOutput(\n const uno::Reference< io::XInputStream >& xInput,\n const uno::Reference< io::XOutputStream >& xOutput )\n throw ( uno::Exception )\n{\n static const sal_Int32 nConstBufferSize = 32000;\n\n sal_Int32 nRead;\n uno::Sequence < sal_Int8 > aSequence ( nConstBufferSize );\n\n do\n {\n nRead = xInput->readBytes ( aSequence, nConstBufferSize );\n if ( nRead < nConstBufferSize )\n {\n uno::Sequence < sal_Int8 > aTempBuf ( aSequence.getConstArray(), nRead );\n xOutput->writeBytes ( aTempBuf );\n }\n else\n xOutput->writeBytes ( aSequence );\n }\n while ( nRead == nConstBufferSize );\n}\n\n\/\/ ----------------------------------------------------------------------\nuno::Reference< io::XInputStream > OStorageHelper::GetInputStreamFromURL(\n const ::rtl::OUString& aURL,\n const uno::Reference< lang::XMultiServiceFactory >& xSF )\n throw ( uno::Exception )\n{\n uno::Reference< lang::XMultiServiceFactory > xFactory = xSF.is() ? xSF : ::comphelper::getProcessServiceFactory();\n if ( !xFactory.is() )\n throw uno::RuntimeException();\n\n uno::Reference < ::com::sun::star::ucb::XSimpleFileAccess > xTempAccess(\n xFactory->createInstance ( ::rtl::OUString::createFromAscii( \"com.sun.star.ucb.SimpleFileAccess\" ) ),\n uno::UNO_QUERY );\n\n if ( !xTempAccess.is() )\n throw uno::RuntimeException();\n\n uno::Reference< io::XInputStream > xInputStream = xTempAccess->openFileRead( aURL );\n if ( !xInputStream.is() )\n throw uno::RuntimeException();\n\n return xInputStream;\n}\n\n\/\/ ----------------------------------------------------------------------\nvoid OStorageHelper::SetCommonStoragePassword(\n const uno::Reference< embed::XStorage >& xStorage,\n const ::rtl::OUString& aPass )\n throw ( uno::Exception )\n{\n uno::Reference< embed::XEncryptionProtectedSource > xEncrSet( xStorage, uno::UNO_QUERY );\n if ( !xEncrSet.is() )\n throw io::IOException(); \/\/ TODO\n\n xEncrSet->setEncryptionPassword( aPass );\n}\n\n\/\/ ----------------------------------------------------------------------\nsal_Int32 OStorageHelper::GetXStorageFormat(\n const uno::Reference< embed::XStorage >& xStorage )\n throw ( uno::Exception )\n{\n uno::Reference< beans::XPropertySet > xStorProps( xStorage, uno::UNO_QUERY_THROW );\n\n ::rtl::OUString aMediaType;\n xStorProps->getPropertyValue( ::rtl::OUString::createFromAscii( \"MediaType\" ) ) >>= aMediaType;\n\n sal_Int32 nResult = 0;\n\n \/\/ TODO\/LATER: the filter configuration could be used to detect it later, or batter a special service\n if ( aMediaType.equalsIgnoreAsciiCase( ::rtl::OUString::createFromAscii( \"application\/vnd.sun.xml.writer\" ) )\n || aMediaType.equalsIgnoreAsciiCase( ::rtl::OUString::createFromAscii( \"application\/vnd.sun.xml.writer.web\" ) )\n || aMediaType.equalsIgnoreAsciiCase( ::rtl::OUString::createFromAscii( \"application\/vnd.sun.xml.writer.global\" ) )\n || aMediaType.equalsIgnoreAsciiCase( ::rtl::OUString::createFromAscii( \"application\/vnd.sun.xml.draw\" ) )\n || aMediaType.equalsIgnoreAsciiCase( ::rtl::OUString::createFromAscii( \"application\/vnd.sun.xml.impress\" ) )\n || aMediaType.equalsIgnoreAsciiCase( ::rtl::OUString::createFromAscii( \"application\/vnd.sun.xml.calc\" ) )\n || aMediaType.equalsIgnoreAsciiCase( ::rtl::OUString::createFromAscii( \"application\/vnd.sun.xml.chart\" ) )\n || aMediaType.equalsIgnoreAsciiCase( ::rtl::OUString::createFromAscii( \"application\/vnd.sun.xml.math\" ) ) )\n {\n nResult = SOFFICE_FILEFORMAT_60;\n }\n else if ( aMediaType.equalsIgnoreAsciiCase( ::rtl::OUString::createFromAscii( \"application\/x-vnd.oasis.openoffice.text\" ) )\n || aMediaType.equalsIgnoreAsciiCase( ::rtl::OUString::createFromAscii( \"application\/x-vnd.oasis.openoffice.text-web\" ) )\n || aMediaType.equalsIgnoreAsciiCase( ::rtl::OUString::createFromAscii( \"application\/x-vnd.oasis.openoffice.text-global\" ) )\n || aMediaType.equalsIgnoreAsciiCase( ::rtl::OUString::createFromAscii( \"application\/x-vnd.oasis.openoffice.drawing\" ) )\n || aMediaType.equalsIgnoreAsciiCase( ::rtl::OUString::createFromAscii( \"application\/x-vnd.oasis.openoffice.presentation\" ) )\n || aMediaType.equalsIgnoreAsciiCase( ::rtl::OUString::createFromAscii( \"application\/x-vnd.oasis.openoffice.spreadsheet\" ) )\n || aMediaType.equalsIgnoreAsciiCase( ::rtl::OUString::createFromAscii( \"application\/x-vnd.oasis.openoffice.chart\" ) )\n || aMediaType.equalsIgnoreAsciiCase( ::rtl::OUString::createFromAscii( \"application\/x-vnd.oasis.openoffice.formula\" ) ) )\n {\n nResult = SOFFICE_FILEFORMAT_8;\n }\n else\n throw uno::Exception();\n\n return nResult;\n}\n\n}\n\n<|endoftext|>"} {"text":"<commit_before>#include \"compiler.hh\"\n#include \"tools.hh\"\n\n#include <iostream>\n\nusing namespace nolang;\n\nCompiler::Compiler() :\n m_parameters(false)\n{\n}\n\nImport *Compiler::addImportIdentifierSub(Import *imp, const std::string &cnts)\n{\n if (imp == nullptr) imp = new Import(cnts);\n else imp->addSub(cnts);\n return imp;\n}\n\nImport *Compiler::addImportIdentifierAs(Import *imp, const std::string &cnts)\n{\n if (imp == nullptr) imp = new Import(cnts);\n else imp->addAs(cnts);\n return imp;\n}\n\nvoid Compiler::iterateTree(mpc_ast_t *tree, std::function<void(mpc_ast_t *)> closure) {\n for (int c = 0; c < tree->children_num; ++c)\n closure(tree->children[c]);\n}\n\nbool Compiler::expect(mpc_ast_t *tree, std::string key, std::string val) const\n{\n std::string tag = tree->tag;\n\n if (tag.find(key) == std::string::npos) return false;\n if (!val.empty() && tree->contents != val) return false;\n\n return true;\n}\n\nImport *Compiler::addImportAs(mpc_ast_t *tree)\n{\n Import *imp = nullptr;\n\n iterateTree(tree, [&] (mpc_ast_t *item) {\n if (expect(item, \"identifier\"))\n imp = addImportIdentifierSub(imp, item->contents);\n });\n\n return imp;\n}\n\nvoid Compiler::addImport(mpc_ast_t *tree)\n{\n Import *imp = nullptr;\n\n iterateTree(tree, [&] (mpc_ast_t *item) {\n if (expect(item, \"identifier\"))\n imp = addImportIdentifierAs(imp, item->contents);\n else if (expect(item, \"namespacedef\"))\n imp = addImportAs(item);\n });\n if (imp) m_imports.push_back(imp);\n}\n\nvoid Compiler::printError(std::string message, mpc_ast_t *item)\n{\n std::cerr << \"** ERROR: \" << message << \": \" << item->tag << \": '\" << item->contents << \"'\\n\";\n}\n\nvoid Compiler::addConstAssignment(mpc_ast_t *item)\n{\n PureMethod tmp;\n Assignment *assignment = parseAssignment(item, &tmp);\n if (assignment && tmp.variables().size() == 1)\n m_consts.push_back(new Const(tmp.variables()[0], assignment));\n else printError(\"Invalid const\", item);\n}\n\nvoid Compiler::addConst(mpc_ast_t *tree)\n{\n bool wait_const = true;\n iterateTree(tree, [&] (mpc_ast_t *item) {\n if (expect(item, \"string\", \"const\"))\n wait_const = false;\n else if (!wait_const & expect(item, \"assignment\"))\n addConstAssignment(item);\n else printError(\"Unknown node in const defination\", item);\n });\n}\n\nNamespaceDef *Compiler::parseNamespaceDefStrings(mpc_ast_t *tree)\n{\n NamespaceDef *def = new NamespaceDef();\n std::vector<std::string> res;\n bool cast = false;\n\n iterateTree(tree, [&] (mpc_ast_t *item) {\n std::string cnts = item->contents;\n if (expect(item, \"identifier\")) {\n if (cast) def->setCast(cnts);\n else res.push_back(cnts);\n } else if (cnts == \"::\") {\n cast = true;\n } else if (cnts == \".\") { \/\/ FIXME\n } else printError(\"Unknown node in namespace defination\", item);\n });\n if (!res.empty()) def->setValues(res);\n return def;\n}\n\nNamespaceDef *Compiler::parseNamespaceDef(mpc_ast_t *tree)\n{\n NamespaceDef *res = parseNamespaceDefStrings(tree);\n if (!res->isValid()) {\n delete res;\n return nullptr;\n }\n return res;\n}\n\nMethodCall *Compiler::parseMethodCall(mpc_ast_t *tree)\n{\n MethodCall *mcall = new MethodCall();\n\n bool wait_ns = true;\n bool wait_call_end = false;\n\n iterateTree(tree, [&] (mpc_ast_t *item) {\n if (wait_ns && expect(item, \"identifier\")) {\n mcall->setNamespace(new NamespaceDef(item->contents));\n wait_ns = false;\n } else if (wait_ns && expect(item, \"namespacedef\")) {\n mcall->setNamespace(parseNamespaceDef(item));\n wait_ns = false;\n } else if (!wait_call_end && expect(item, \"char\", \"(\"))\n wait_call_end = true;\n else if (wait_call_end && expect(item, \"char\", \")\"))\n wait_call_end = false;\n else if (wait_call_end)\n mcall->addParameter(codegen(item));\n else printError(\"Unknown node in method call\", item);\n });\n\n return mcall;\n}\n\nTypeIdent *Compiler::parseTypeIdent(mpc_ast_t *tree, PureMethod *m)\n{\n std::string name;\n std::string type;\n bool wait_colon = true;\n iterateTree(tree, [&] (mpc_ast_t *item) {\n if (expect(item, \"identifier\")) {\n if (wait_colon) name += item->contents;\n else type += item->contents;\n }\n else if (wait_colon && expect(item, \"char\", \":\"))\n wait_colon = false;\n });\n m_last_indent = name;\n return new TypeIdent(name, type);\n}\n\nAssignment *Compiler::parseAssignmentTypeIdent(mpc_ast_t *item, PureMethod *m)\n{\n TypeIdent *ident = parseTypeIdent(item, m);\n if (m) m->addVariable(ident);\n else delete ident;\n return new Assignment(m_last_indent);\n}\n\nAssignment *Compiler::parseAssignment(mpc_ast_t *tree, PureMethod *m)\n{\n bool wait_for_ident = true;\n bool wait_for_assign = false;\n#if 0\n std::cout << \"\/*\\n\";\n mpc_ast_print(tree);\n std::cout << \"*\/\\n\";\n#endif\n Assignment *ass = nullptr;\n iterateTree(tree, [&] (mpc_ast_t *item) {\n if (wait_for_ident && expect(item, \"typeident\")) {\n ass = parseAssignmentTypeIdent(item, m);\n wait_for_ident = false;\n wait_for_assign = true;\n } else if (wait_for_ident && expect(item, \"namespacedef\")) {\n NamespaceDef *def = parseNamespaceDef(item);\n if (def == nullptr) {\n throw std::string(\"Invalid NamespaceDef in assignment\");\n }\n wait_for_ident = false;\n wait_for_assign = true;\n ass = new Assignment(def);\n } else if (wait_for_assign && expect(item, \"char\", \"=\")) {\n wait_for_assign = false;\n } else if (!wait_for_ident && !wait_for_assign) {\n \/\/ Now need to parse statements\/expr...\n std::vector<Statement*> stmt = codegen(item, m);\n ass->addStatements(stmt);\n } else printError(\"Unknown node in assignment\", item);\n });\n\n return ass;\n}\n\nvoid Compiler::parseStruct(mpc_ast_t *tree)\n{\n Struct *s = nullptr;\n\n iterateTree(tree, [&] (mpc_ast_t *item) {\n if (!s && expect(item, \"identifier\"))\n s = new Struct(item->contents);\n else if (s && expect(item, \"typeident\"))\n s->addData(parseTypeIdent(item, nullptr));\n else printError(\"Unknown node in struct\", item);\n });\n m_structs.push_back(s);\n}\n\nstd::vector<Statement*> Compiler::codegenRecurse(mpc_ast_t *tree, PureMethod *m, int level)\n{\n std::vector<Statement*> rdata;\n iterateTree(tree, [&] (mpc_ast_t *item) {\n std::vector<Statement*> st = codegen(item, m, level);\n for (auto s : st) {\n if (s->type() == \"EOS\") {\n rdata.push_back(s);\n m_blocks.push_back(rdata);\n rdata = std::vector<Statement*>();\n } else {\n rdata.push_back(s);\n }\n }\n });\n return rdata;\n}\n\nstd::vector<Statement*> Compiler::codegen(mpc_ast_t *tree, PureMethod *m, int level)\n{\n std::vector<Statement*> rdata;\n\n std::string tag = tree->tag;\n std::string cnts = tree->contents;\n bool recurse = true;\n\n if (tag == \">\") {\n \/\/std::cout << \"ROOT\\n\";\n } else if (expect(tree, \"comment\")) {\n \/\/ Ignore comments\n recurse = false;\n } else if (expect(tree, \"methoddef\")) {\n \/\/ New method\n parseMethod(tree, level);\n recurse = false;\n level = 0;\n } else if (expect(tree, \"struct\")) {\n parseStruct(tree);\n recurse = false;\n } else if (expect(tree, \"indent\")) {\n int new_level = cnts.length();\n if (new_level != level) {\n if (m && !m_blocks.empty()) {\n m->addBlock(m_blocks);\n m_blocks = std::vector<std::vector<Statement*>>();\n }\n }\n \/\/ SKIP and recurse\n } else if (expect(tree, \"methodcall\")) {\n rdata.push_back(parseMethodCall(tree));\n recurse = false;\n } else if (expect(tree, \"assignment\")) {\n rdata.push_back(parseAssignment(tree, m));\n recurse = false;\n } else if (expect(tree, \"number\")) {\n rdata.push_back(new NumberValue(cnts));\n } else if (expect(tree, \"termop\")) {\n rdata.push_back(new Op(cnts));\n } else if (expect(tree, \"factorop\")) {\n rdata.push_back(new Op(cnts));\n } else if (expect(tree, \"string\")) {\n rdata.push_back(new StringValue(cnts));\n } else if (expect(tree, \"typeident\")) {\n TypeIdent *ident = parseTypeIdent(tree, m);\n if (m_parameters) {\n rdata.push_back(ident);\n } else if (m != nullptr) {\n m->addVariable(ident);\n } else {\n rdata.push_back(ident);\n }\n recurse = false;\n } else if (expect(tree, \"namespacedef\")) {\n if (cnts == \"false\" || cnts == \"true\") {\n rdata.push_back(new Boolean(cnts));\n } else {\n NamespaceDef *def = parseNamespaceDef(tree);\n if (def != nullptr) {\n rdata.push_back(def);\n } else if (!cnts.empty()) {\n rdata.push_back(new Identifier(cnts));\n }\n }\n recurse = false;\n } else if (expect(tree, \"identifier\")) {\n \/\/ FIXME Some idenfiers are special\/reserved words\n if (cnts == \"false\" || cnts == \"true\") {\n rdata.push_back(new Boolean(cnts));\n } else {\n rdata.push_back(new Identifier(cnts));\n }\n } else if (expect(tree, \"import\")) {\n addImport(tree);\n recurse = false;\n } else if (expect(tree, \"const\")) {\n addConst(tree);\n recurse = false;\n } else if (expect(tree, \"newline\")) {\n rdata.push_back(new EOS());\n } else if (expect(tree, \"comparator\")) {\n rdata.push_back(new Comparator(cnts));\n } else if (expect(tree, \"char\", \"(\") || expect(tree, \"char\", \")\")) {\n rdata.push_back(new Braces(cnts));\n } else if (expect(tree, \"ows\") || expect(tree, \"ws\")) {\n } else printError(\"Unknown node in statement\", tree);\n\n if (recurse)\n rdata = applyToVector<Statement*>(rdata, codegenRecurse(tree, m, level));\n\n return rdata;\n}\n\nvoid Compiler::parseParamDef(mpc_ast_t *tree, PureMethod *m, int level)\n{\n int numparams = 0;\n for (int c = 0; c < tree->children_num; ++c) {\n std::string tag = tree->children[c]->tag;\n std::string cnts = tree->children[c]->contents;\n if (expect(tree->children[c], \"typeident\")) {\n m_parameters = true;\n auto res = codegen(tree->children[c], m, level + 1);\n m_parameters = false;\n for (auto r: res ){\n if (r->type() == \"TypeIdent\") {\n m->addParameter(static_cast<TypeIdent*>(r));\n } else {\n throw std::string(\"Invalid parameter definition: \" + r->code());\n }\n }\n } else if (expect(tree->children[c], \"char\") && cnts == \",\") {\n \/\/ FIXME?\n numparams += 1;\n } else {\n std::cerr << \"** ERROR: Unknown node in parameter: \" << tag << \": '\" << cnts << \"'\\n\";\n }\n }\n}\n\nvoid Compiler::parseArgs(mpc_ast_t *tree, PureMethod *m, int level)\n{\n int open = 0;\n for (int c = 0; c < tree->children_num; ++c) {\n std::string cnts = tree->children[c]->contents;\n if (expect(tree->children[c], \"char\")) {\n if (cnts == \"(\") open++;\n else if (cnts == \")\") open--;\n else {\n throw std::string(\"Unexpected char: \" + cnts);\n }\n } else if (open > 0 && expect(tree->children[c], \"paramdef\")) {\n parseParamDef(tree->children[c], m, level + 1);\n } else {\n std::string tag = tree->children[c]->tag;\n std::cerr << \"** ERROR: Unknown node in arguments: \" << tag << \": '\" << cnts << \"'\\n\";\n }\n }\n}\n\nvoid Compiler::parseMethodRet(mpc_ast_t *tree, PureMethod *m, int level)\n{\n auto r = codegen(tree, m, level);\n\n if (r.size() > 1) {\n throw std::string(\"Expected one return type, got \" + std::to_string(r.size()) + \" for '\" + m->name() + \"'\");\n }\n\n if (r.size() == 1) {\n if (r[0]->type() != \"Identifier\") {\n throw std::string(\"Expected identifier as return type, got \" + r[0]->type() + \" for '\" + m->name() + \"'\");\n }\n m->setReturnType(TypeDef(r[0]->code()));\n }\n}\n\nvoid Compiler::parseMethod(mpc_ast_t *tree, int level)\n{\n PureMethod *m = new PureMethod();\n bool waitName = true;\n bool waitBody = false;\n for (int c = 0; c < tree->children_num; ++c) {\n std::string tag = tree->children[c]->tag;\n std::string cnts = tree->children[c]->contents;\n if (waitName && tag.find(\"pure\") != std::string::npos) {\n m->setPure();\n } else if (waitName && tag.find(\"identifier\") != std::string::npos) {\n m->setName(cnts);\n waitName = false;\n } else if (!waitName && expect(tree->children[c], \"args\")) {\n parseArgs(tree->children[c], m, level + 1);\n } else if (!waitName && expect(tree->children[c], \"methodret\")) {\n parseMethodRet(tree->children[c], m, level + 1);\n } else if (tag.find(\"ows\") != std::string::npos) {\n \/\/ Optional whitespace\n } else if (!waitBody && tag.find(\"string\") != std::string::npos && cnts == \"=>\") {\n \/\/ Body should follow\n waitBody = true;\n } else if (waitBody && tag.find(\"body\") != std::string::npos) {\n m->setBody(codegen(tree->children[c], m, level));\n if (!m_blocks.empty()) {\n m->addBlock(m_blocks);\n \/\/m_blocks = std::vector<std::string>();\n m_blocks = std::vector<std::vector<Statement*>>();\n }\n } else if (tag.find(\"newline\") != std::string::npos || tag.find(\"ws\") != std::string::npos) {\n \/\/} else if (cnts.length() == 0) {\n \/\/ SKIP\n } else {\n std::cerr << \"** ERROR: Unknown node in method: \" << tag << \": '\" << cnts << \"'\\n\";\n }\n }\n m_methods[m->name()] = m;\n}\n<commit_msg>Refactor argument and parameter parsing<commit_after>#include \"compiler.hh\"\n#include \"tools.hh\"\n\n#include <iostream>\n\nusing namespace nolang;\n\nCompiler::Compiler() :\n m_parameters(false)\n{\n}\n\nImport *Compiler::addImportIdentifierSub(Import *imp, const std::string &cnts)\n{\n if (imp == nullptr) imp = new Import(cnts);\n else imp->addSub(cnts);\n return imp;\n}\n\nImport *Compiler::addImportIdentifierAs(Import *imp, const std::string &cnts)\n{\n if (imp == nullptr) imp = new Import(cnts);\n else imp->addAs(cnts);\n return imp;\n}\n\nvoid Compiler::iterateTree(mpc_ast_t *tree, std::function<void(mpc_ast_t *)> closure) {\n for (int c = 0; c < tree->children_num; ++c)\n closure(tree->children[c]);\n}\n\nbool Compiler::expect(mpc_ast_t *tree, std::string key, std::string val) const\n{\n std::string tag = tree->tag;\n\n if (tag.find(key) == std::string::npos) return false;\n if (!val.empty() && tree->contents != val) return false;\n\n return true;\n}\n\nImport *Compiler::addImportAs(mpc_ast_t *tree)\n{\n Import *imp = nullptr;\n\n iterateTree(tree, [&] (mpc_ast_t *item) {\n if (expect(item, \"identifier\"))\n imp = addImportIdentifierSub(imp, item->contents);\n });\n\n return imp;\n}\n\nvoid Compiler::addImport(mpc_ast_t *tree)\n{\n Import *imp = nullptr;\n\n iterateTree(tree, [&] (mpc_ast_t *item) {\n if (expect(item, \"identifier\"))\n imp = addImportIdentifierAs(imp, item->contents);\n else if (expect(item, \"namespacedef\"))\n imp = addImportAs(item);\n });\n if (imp) m_imports.push_back(imp);\n}\n\nvoid Compiler::printError(std::string message, mpc_ast_t *item)\n{\n std::cerr << \"** ERROR: \" << message << \": \" << item->tag << \": '\" << item->contents << \"'\\n\";\n}\n\nvoid Compiler::addConstAssignment(mpc_ast_t *item)\n{\n PureMethod tmp;\n Assignment *assignment = parseAssignment(item, &tmp);\n if (assignment && tmp.variables().size() == 1)\n m_consts.push_back(new Const(tmp.variables()[0], assignment));\n else printError(\"Invalid const\", item);\n}\n\nvoid Compiler::addConst(mpc_ast_t *tree)\n{\n bool wait_const = true;\n iterateTree(tree, [&] (mpc_ast_t *item) {\n if (expect(item, \"string\", \"const\"))\n wait_const = false;\n else if (!wait_const & expect(item, \"assignment\"))\n addConstAssignment(item);\n else printError(\"Unknown node in const defination\", item);\n });\n}\n\nNamespaceDef *Compiler::parseNamespaceDefStrings(mpc_ast_t *tree)\n{\n NamespaceDef *def = new NamespaceDef();\n std::vector<std::string> res;\n bool cast = false;\n\n iterateTree(tree, [&] (mpc_ast_t *item) {\n std::string cnts = item->contents;\n if (expect(item, \"identifier\")) {\n if (cast) def->setCast(cnts);\n else res.push_back(cnts);\n } else if (cnts == \"::\") {\n cast = true;\n } else if (cnts == \".\") { \/\/ FIXME\n } else printError(\"Unknown node in namespace defination\", item);\n });\n if (!res.empty()) def->setValues(res);\n return def;\n}\n\nNamespaceDef *Compiler::parseNamespaceDef(mpc_ast_t *tree)\n{\n NamespaceDef *res = parseNamespaceDefStrings(tree);\n if (!res->isValid()) {\n delete res;\n return nullptr;\n }\n return res;\n}\n\nMethodCall *Compiler::parseMethodCall(mpc_ast_t *tree)\n{\n MethodCall *mcall = new MethodCall();\n\n bool wait_ns = true;\n bool wait_call_end = false;\n\n iterateTree(tree, [&] (mpc_ast_t *item) {\n if (wait_ns && expect(item, \"identifier\")) {\n mcall->setNamespace(new NamespaceDef(item->contents));\n wait_ns = false;\n } else if (wait_ns && expect(item, \"namespacedef\")) {\n mcall->setNamespace(parseNamespaceDef(item));\n wait_ns = false;\n } else if (!wait_call_end && expect(item, \"char\", \"(\"))\n wait_call_end = true;\n else if (wait_call_end && expect(item, \"char\", \")\"))\n wait_call_end = false;\n else if (wait_call_end)\n mcall->addParameter(codegen(item));\n else printError(\"Unknown node in method call\", item);\n });\n\n return mcall;\n}\n\nTypeIdent *Compiler::parseTypeIdent(mpc_ast_t *tree, PureMethod *m)\n{\n std::string name;\n std::string type;\n bool wait_colon = true;\n iterateTree(tree, [&] (mpc_ast_t *item) {\n if (expect(item, \"identifier\")) {\n if (wait_colon) name += item->contents;\n else type += item->contents;\n }\n else if (wait_colon && expect(item, \"char\", \":\"))\n wait_colon = false;\n });\n m_last_indent = name;\n return new TypeIdent(name, type);\n}\n\nAssignment *Compiler::parseAssignmentTypeIdent(mpc_ast_t *item, PureMethod *m)\n{\n TypeIdent *ident = parseTypeIdent(item, m);\n if (m) m->addVariable(ident);\n else delete ident;\n return new Assignment(m_last_indent);\n}\n\nAssignment *Compiler::parseAssignment(mpc_ast_t *tree, PureMethod *m)\n{\n bool wait_for_ident = true;\n bool wait_for_assign = false;\n#if 0\n std::cout << \"\/*\\n\";\n mpc_ast_print(tree);\n std::cout << \"*\/\\n\";\n#endif\n Assignment *ass = nullptr;\n iterateTree(tree, [&] (mpc_ast_t *item) {\n if (wait_for_ident && expect(item, \"typeident\")) {\n ass = parseAssignmentTypeIdent(item, m);\n wait_for_ident = false;\n wait_for_assign = true;\n } else if (wait_for_ident && expect(item, \"namespacedef\")) {\n NamespaceDef *def = parseNamespaceDef(item);\n if (def == nullptr) {\n throw std::string(\"Invalid NamespaceDef in assignment\");\n }\n wait_for_ident = false;\n wait_for_assign = true;\n ass = new Assignment(def);\n } else if (wait_for_assign && expect(item, \"char\", \"=\")) {\n wait_for_assign = false;\n } else if (!wait_for_ident && !wait_for_assign) {\n \/\/ Now need to parse statements\/expr...\n std::vector<Statement*> stmt = codegen(item, m);\n ass->addStatements(stmt);\n } else printError(\"Unknown node in assignment\", item);\n });\n\n return ass;\n}\n\nvoid Compiler::parseStruct(mpc_ast_t *tree)\n{\n Struct *s = nullptr;\n\n iterateTree(tree, [&] (mpc_ast_t *item) {\n if (!s && expect(item, \"identifier\"))\n s = new Struct(item->contents);\n else if (s && expect(item, \"typeident\"))\n s->addData(parseTypeIdent(item, nullptr));\n else printError(\"Unknown node in struct\", item);\n });\n m_structs.push_back(s);\n}\n\nstd::vector<Statement*> Compiler::codegenRecurse(mpc_ast_t *tree, PureMethod *m, int level)\n{\n std::vector<Statement*> rdata;\n iterateTree(tree, [&] (mpc_ast_t *item) {\n std::vector<Statement*> st = codegen(item, m, level);\n for (auto s : st) {\n if (s->type() == \"EOS\") {\n rdata.push_back(s);\n m_blocks.push_back(rdata);\n rdata = std::vector<Statement*>();\n } else {\n rdata.push_back(s);\n }\n }\n });\n return rdata;\n}\n\nstd::vector<Statement*> Compiler::codegen(mpc_ast_t *tree, PureMethod *m, int level)\n{\n std::vector<Statement*> rdata;\n\n std::string tag = tree->tag;\n std::string cnts = tree->contents;\n bool recurse = true;\n\n if (tag == \">\") {\n \/\/std::cout << \"ROOT\\n\";\n } else if (expect(tree, \"comment\")) {\n \/\/ Ignore comments\n recurse = false;\n } else if (expect(tree, \"methoddef\")) {\n \/\/ New method\n parseMethod(tree, level);\n recurse = false;\n level = 0;\n } else if (expect(tree, \"struct\")) {\n parseStruct(tree);\n recurse = false;\n } else if (expect(tree, \"indent\")) {\n int new_level = cnts.length();\n if (new_level != level) {\n if (m && !m_blocks.empty()) {\n m->addBlock(m_blocks);\n m_blocks = std::vector<std::vector<Statement*>>();\n }\n }\n \/\/ SKIP and recurse\n } else if (expect(tree, \"methodcall\")) {\n rdata.push_back(parseMethodCall(tree));\n recurse = false;\n } else if (expect(tree, \"assignment\")) {\n rdata.push_back(parseAssignment(tree, m));\n recurse = false;\n } else if (expect(tree, \"number\")) {\n rdata.push_back(new NumberValue(cnts));\n } else if (expect(tree, \"termop\")) {\n rdata.push_back(new Op(cnts));\n } else if (expect(tree, \"factorop\")) {\n rdata.push_back(new Op(cnts));\n } else if (expect(tree, \"string\")) {\n rdata.push_back(new StringValue(cnts));\n } else if (expect(tree, \"typeident\")) {\n TypeIdent *ident = parseTypeIdent(tree, m);\n if (m_parameters) {\n rdata.push_back(ident);\n } else if (m != nullptr) {\n m->addVariable(ident);\n } else {\n rdata.push_back(ident);\n }\n recurse = false;\n } else if (expect(tree, \"namespacedef\")) {\n if (cnts == \"false\" || cnts == \"true\") {\n rdata.push_back(new Boolean(cnts));\n } else {\n NamespaceDef *def = parseNamespaceDef(tree);\n if (def != nullptr) {\n rdata.push_back(def);\n } else if (!cnts.empty()) {\n rdata.push_back(new Identifier(cnts));\n }\n }\n recurse = false;\n } else if (expect(tree, \"identifier\")) {\n \/\/ FIXME Some idenfiers are special\/reserved words\n if (cnts == \"false\" || cnts == \"true\") {\n rdata.push_back(new Boolean(cnts));\n } else {\n rdata.push_back(new Identifier(cnts));\n }\n } else if (expect(tree, \"import\")) {\n addImport(tree);\n recurse = false;\n } else if (expect(tree, \"const\")) {\n addConst(tree);\n recurse = false;\n } else if (expect(tree, \"newline\")) {\n rdata.push_back(new EOS());\n } else if (expect(tree, \"comparator\")) {\n rdata.push_back(new Comparator(cnts));\n } else if (expect(tree, \"char\", \"(\") || expect(tree, \"char\", \")\")) {\n rdata.push_back(new Braces(cnts));\n } else if (expect(tree, \"ows\") || expect(tree, \"ws\")) {\n } else printError(\"Unknown node in statement\", tree);\n\n if (recurse)\n rdata = applyToVector<Statement*>(rdata, codegenRecurse(tree, m, level));\n\n return rdata;\n}\n\nvoid Compiler::parseParamDef(mpc_ast_t *tree, PureMethod *m, int level)\n{\n iterateTree(tree, [&] (mpc_ast_t *item) {\n std::string cnts = item->contents;\n if (expect(item, \"typeident\")) {\n m_parameters = true;\n auto res = codegen(item, m, level + 1);\n m_parameters = false;\n for (auto r : res){\n if (r->type() == \"TypeIdent\")\n m->addParameter(static_cast<TypeIdent*>(r));\n else\n throw std::string(\"Invalid parameter definition: \" + r->code());\n }\n } else if (expect(item, \"char\") && cnts == \",\") {\n \/\/ FIXME Can ',' separate in params something else than next param?\n } else printError(\"Unknown node in parameter\", item);\n });\n}\n\nvoid Compiler::parseArgs(mpc_ast_t *tree, PureMethod *m, int level)\n{\n int open = 0;\n iterateTree(tree, [&] (mpc_ast_t *item) {\n if (expect(item, \"char\")) {\n std::string cnts = item->contents;\n if (cnts == \"(\") open++;\n else if (cnts == \")\") open--;\n else {\n throw std::string(\"Unexpected char: \" + cnts);\n }\n } else if (open > 0 && expect(item, \"paramdef\"))\n parseParamDef(item, m, level + 1);\n else printError(\"Unknown node in arguments\", item);\n });\n}\n\nvoid Compiler::parseMethodRet(mpc_ast_t *tree, PureMethod *m, int level)\n{\n auto r = codegen(tree, m, level);\n\n if (r.size() > 1) {\n throw std::string(\"Expected one return type, got \" + std::to_string(r.size()) + \" for '\" + m->name() + \"'\");\n }\n\n if (r.size() == 1) {\n if (r[0]->type() != \"Identifier\") {\n throw std::string(\"Expected identifier as return type, got \" + r[0]->type() + \" for '\" + m->name() + \"'\");\n }\n m->setReturnType(TypeDef(r[0]->code()));\n }\n}\n\nvoid Compiler::parseMethod(mpc_ast_t *tree, int level)\n{\n PureMethod *m = new PureMethod();\n bool waitName = true;\n bool waitBody = false;\n for (int c = 0; c < tree->children_num; ++c) {\n std::string tag = tree->children[c]->tag;\n std::string cnts = tree->children[c]->contents;\n if (waitName && tag.find(\"pure\") != std::string::npos) {\n m->setPure();\n } else if (waitName && tag.find(\"identifier\") != std::string::npos) {\n m->setName(cnts);\n waitName = false;\n } else if (!waitName && expect(tree->children[c], \"args\")) {\n parseArgs(tree->children[c], m, level + 1);\n } else if (!waitName && expect(tree->children[c], \"methodret\")) {\n parseMethodRet(tree->children[c], m, level + 1);\n } else if (tag.find(\"ows\") != std::string::npos) {\n \/\/ Optional whitespace\n } else if (!waitBody && tag.find(\"string\") != std::string::npos && cnts == \"=>\") {\n \/\/ Body should follow\n waitBody = true;\n } else if (waitBody && tag.find(\"body\") != std::string::npos) {\n m->setBody(codegen(tree->children[c], m, level));\n if (!m_blocks.empty()) {\n m->addBlock(m_blocks);\n \/\/m_blocks = std::vector<std::string>();\n m_blocks = std::vector<std::vector<Statement*>>();\n }\n } else if (tag.find(\"newline\") != std::string::npos || tag.find(\"ws\") != std::string::npos) {\n \/\/} else if (cnts.length() == 0) {\n \/\/ SKIP\n } else {\n std::cerr << \"** ERROR: Unknown node in method: \" << tag << \": '\" << cnts << \"'\\n\";\n }\n }\n m_methods[m->name()] = m;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 2017, Rauli Laine\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * 1. Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\/\n#include <plorth\/context.hpp>\n#include <plorth\/value-word.hpp>\n\nnamespace plorth\n{\n using source_iterator = unistring::const_iterator;\n\n static bool skip_whitespace(source_iterator&, const source_iterator&);\n static ref<value> compile_value(context*,\n source_iterator&,\n const source_iterator&);\n\n ref<quote> context::compile(const unistring& source)\n {\n std::vector<ref<class value>> values;\n ref<class value> value;\n auto it = std::begin(source);\n const auto end = std::end(source);\n\n while (it != end)\n {\n if (skip_whitespace(it, end))\n {\n break;\n }\n else if (!(value = compile_value(this, it, end)))\n {\n return ref<quote>();\n }\n values.push_back(value);\n }\n\n return m_runtime->compiled_quote(values);\n }\n\n \/**\n * Skips whitespace and comments from source code.\n *\n * \\return True if end of input has been reached, false otherwise.\n *\/\n static bool skip_whitespace(source_iterator& it, const source_iterator& end)\n {\n while (it != end)\n {\n \/\/ Skip line comments.\n if (*it == '#')\n {\n while (++it != end)\n {\n if (*it == '\\n' || *it == '\\r')\n {\n break;\n }\n }\n }\n else if (!std::isspace(*it))\n {\n return false;\n } else {\n ++it;\n }\n }\n\n return true;\n }\n\n static bool compile_escape_sequence(context* ctx,\n source_iterator& it,\n const source_iterator& end,\n unistring& buffer)\n {\n if (it >= end)\n {\n ctx->error(\n error::code_syntax,\n U\"Unexpected end of input; Missing escape sequence.\"\n );\n\n return false;\n }\n\n switch (*it++)\n {\n case 'b':\n buffer.append(1, 010);\n break;\n\n case 't':\n buffer.append(1, 011);\n break;\n\n case 'n':\n buffer.append(1, 012);\n break;\n\n case 'f':\n buffer.append(1, 014);\n break;\n\n case 'r':\n buffer.append(1, 015);\n break;\n\n case '\"':\n case '\\'':\n case '\\\\':\n case '\/':\n buffer.append(1, *(it - 1));\n break;\n\n case 'u':\n {\n unichar result = 0;\n\n for (int i = 0; i < 4; ++i)\n {\n if (it >= end)\n {\n ctx->error(\n error::code_syntax,\n U\"Unterminated escape sequence.\"\n );\n\n return false;\n }\n else if (!std::isxdigit(*it))\n {\n ctx->error(\n error::code_syntax,\n U\"Illegal Unicode hex escape sequence.\"\n );\n\n return false;\n }\n\n if (*it >= 'A' && *it <= 'F')\n {\n result = result * 16 + (*it++ - 'A' + 10);\n }\n else if (*it >= 'a' && *it <= 'f')\n {\n result = result * 16 + (*it++ - 'a' + 10);\n } else {\n result = result * 16 + (*it++ - '0');\n }\n }\n\n if (!unichar_validate(result))\n {\n ctx->error(\n error::code_syntax,\n U\"Illegal Unicode hex escape sequence.\"\n );\n\n return false;\n }\n\n buffer.append(1, result);\n }\n break;\n\n default:\n ctx->error(\n error::code_syntax,\n U\"Illegal escape sequence in string literal.\"\n );\n\n return false;\n }\n\n return true;\n }\n\n static ref<string> compile_string(context* ctx,\n source_iterator& it,\n const source_iterator& end)\n {\n unichar separator;\n unistring buffer;\n\n if (skip_whitespace(it, end))\n {\n ctx->error(\n error::code_syntax,\n U\"Unexpected end of input; Missing string.\"\n );\n\n return ref<string>();\n }\n\n if (*it != '\"' && *it != '\\'')\n {\n ctx->error(\n error::code_syntax,\n U\"Unexpected input; Missing string.\"\n );\n\n return ref<string>();\n }\n\n separator = *it++;\n\n for (;;)\n {\n if (it >= end)\n {\n ctx->error(\n error::code_syntax,\n unistring(U\"Unterminated string; Missing `\") + separator + U\"'\"\n );\n\n return ref<string>();\n }\n else if (*it == separator)\n {\n ++it;\n break;\n }\n else if (*it != '\\\\')\n {\n buffer.append(1, *it++);\n }\n else if (!compile_escape_sequence(ctx, ++it, end, buffer))\n {\n return ref<string>();\n }\n }\n\n return ctx->runtime()->string(buffer);\n }\n\n static ref<quote> compile_quote(context* ctx,\n source_iterator& it,\n const source_iterator& end)\n {\n std::vector<ref<value>> values;\n\n if (skip_whitespace(it, end))\n {\n ctx->error(\n error::code_syntax,\n U\"Unexpected end of input; Missing quote.\"\n );\n\n return ref<quote>();\n }\n\n if (*it != '(')\n {\n ctx->error(\n error::code_syntax,\n U\"Unexpected input; Missing quote.\"\n );\n\n return ref<quote>();\n }\n\n ++it;\n\n for (;;)\n {\n if (skip_whitespace(it, end))\n {\n ctx->error(error::code_syntax, U\"Unterminated quote; Missing `)'.\");\n\n return ref<quote>();\n }\n else if (*it == ')')\n {\n ++it;\n break;\n } else {\n const auto value = compile_value(ctx, it, end);\n\n if (!value)\n {\n return ref<quote>();\n }\n values.push_back(value);\n }\n }\n\n return ctx->runtime()->compiled_quote(values);\n }\n\n static ref<array> compile_array(context* ctx,\n source_iterator& it,\n const source_iterator& end)\n {\n std::vector<ref<value>> elements;\n\n if (skip_whitespace(it, end))\n {\n ctx->error(\n error::code_syntax,\n U\"Unexpected end of input; Missing array.\"\n );\n\n return ref<array>();\n }\n\n if (*it != '[')\n {\n ctx->error(\n error::code_syntax,\n U\"Unexpected input; Missing array.\"\n );\n\n return ref<array>();\n }\n\n ++it;\n\n for (;;)\n {\n if (skip_whitespace(it, end))\n {\n ctx->error(\n error::code_syntax,\n U\"Unterminated array; Missing `]'.\"\n );\n\n return ref<array>();\n }\n else if (*it == ']')\n {\n ++it;\n break;\n } else {\n const auto value = compile_value(ctx, it, end);\n\n if (!value)\n {\n return ref<array>();\n }\n elements.push_back(value);\n if (skip_whitespace(it, end) || (*it != ',' && *it != ']'))\n {\n ctx->error(\n error::code_syntax,\n U\"Unterminated array; Missing `]'.\"\n );\n\n return ref<array>();\n }\n else if (*it == ',')\n {\n ++it;\n }\n }\n }\n\n return ctx->runtime()->array(elements.data(), elements.size());\n }\n\n static ref<object> compile_object(context* ctx,\n source_iterator& it,\n const source_iterator& end)\n {\n object::container_type properties;\n\n if (skip_whitespace(it, end))\n {\n ctx->error(\n error::code_syntax,\n U\"Unexpected end of input; Missing object.\"\n );\n\n return ref<object>();\n }\n\n if (*it != '{')\n {\n ctx->error(\n error::code_syntax,\n U\"Unexpected input; Missing object.\"\n );\n\n return ref<object>();\n }\n\n ++it;\n\n for (;;)\n {\n if (skip_whitespace(it, end))\n {\n ctx->error(\n error::code_syntax,\n U\"Unterminated object; Missing `}'.\"\n );\n\n return ref<object>();\n }\n else if (*it == '}')\n {\n ++it;\n break;\n } else {\n ref<string> key;\n ref<class value> value;\n\n if (!(key = compile_string(ctx, it, end)))\n {\n return ref<object>();\n }\n\n if (skip_whitespace(it, end))\n {\n ctx->error(\n error::code_syntax,\n U\"Unterminated object; Missing `}'.\"\n );\n\n return ref<object>();\n }\n\n if (*it != ':')\n {\n ctx->error(\n error::code_syntax,\n U\"Missing `:' after property key.\"\n );\n\n return ref<object>();\n }\n\n if (!(value = compile_value(ctx, ++it, end)))\n {\n return ref<object>();\n }\n\n properties[key->to_string()] = value;\n\n if (skip_whitespace(it, end) || (*it != ',' && *it != '}'))\n {\n ctx->error(\n error::code_syntax,\n U\"Unterminated object; Missing `}'.\"\n );\n\n return ref<object>();\n }\n else if (*it == ',')\n {\n ++it;\n }\n }\n }\n\n return ctx->runtime()->value<object>(properties);\n }\n\n static ref<symbol> compile_symbol(context* ctx,\n source_iterator& it,\n const source_iterator& end)\n {\n unistring buffer;\n\n if (skip_whitespace(it, end))\n {\n ctx->error(\n error::code_syntax,\n U\"Unexpected end of input; Missing symbol.\"\n );\n\n return ref<symbol>();\n }\n\n if (!unichar_isword(*it))\n {\n ctx->error(\n error::code_syntax,\n U\"Unexpected input; Missing symbol.\"\n );\n\n return ref<symbol>();\n }\n\n buffer.append(1, *it++);\n while (it != end && unichar_isword(*it))\n {\n buffer.append(1, *it++);\n }\n\n return ctx->runtime()->value<symbol>(buffer);\n }\n\n static ref<word> compile_word(context* ctx,\n source_iterator& it,\n const source_iterator& end)\n {\n const auto& runtime = ctx->runtime();\n ref<class symbol> symbol;\n std::vector<ref<value>> values;\n\n if (skip_whitespace(it, end))\n {\n ctx->error(\n error::code_syntax,\n U\"Unexpected end of input; Missing word.\"\n );\n\n return ref<word>();\n }\n\n if (*it != ':')\n {\n ctx->error(\n error::code_syntax,\n U\"Unexpected input; Missing word.\"\n );\n\n return ref<word>();\n }\n\n ++it;\n\n if (!(symbol = compile_symbol(ctx, it, end)))\n {\n return ref<word>();\n }\n\n for (;;)\n {\n if (skip_whitespace(it, end))\n {\n ctx->error(error::code_syntax, U\"Unterminated word; Missing `;'.\");\n\n return ref<word>();\n }\n else if (*it == ';')\n {\n ++it;\n break;\n } else {\n const auto value = compile_value(ctx, it, end);\n\n if (!value)\n {\n return ref<word>();\n }\n values.push_back(value);\n }\n }\n\n return runtime->value<word>(symbol, runtime->compiled_quote(values));\n }\n\n static ref<value> compile_value(context* ctx,\n source_iterator& it,\n const source_iterator& end)\n {\n if (skip_whitespace(it, end))\n {\n ctx->error(\n error::code_syntax,\n U\"Unexpected end of input; Missing value.\"\n );\n\n return ref<value>();\n }\n switch (*it)\n {\n case '\"':\n case '\\'':\n return compile_string(ctx, it, end);\n\n case '(':\n return compile_quote(ctx, it, end);\n\n case '[':\n return compile_array(ctx, it, end);\n\n case '{':\n return compile_object(ctx, it, end);\n\n case ':':\n return compile_word(ctx, it, end);\n\n default:\n return compile_symbol(ctx, it, end);\n }\n }\n\n #if 0\n ref<quote> context::compile(const unistring& source)\n {\n std::vector<token> tokens;\n auto it = std::begin(source);\n const auto end = std::end(source);\n unistring buffer;\n\n while (it != end)\n {\n unichar c = *it++;\n\nretry_switch:\n if (!unichar_isword(c))\n {\n error(error::code_syntax, U\"Unexpected input.\");\n\n return ref<quote>();\n }\n\n buffer.assign(1, c);\n\n while (it != end)\n {\n if (!unichar_isword(c = *it++))\n {\n tokens.push_back(token(token::type_word, buffer));\n goto retry_switch;\n }\n buffer.append(1, c);\n }\n\n tokens.push_back(token(token::type_word, buffer));\n }\n\n return m_runtime->compiled_quote(tokens);\n }\n\n static bool compile_string_literal(context* ctx,\n const unichar separator,\n unistring::const_iterator& it,\n const unistring::const_iterator& end,\n std::vector<token>& tokens,\n unistring& buffer)\n {\n buffer.clear();\n for (;;)\n {\n unichar c;\n\n if (it >= end)\n {\n ctx->error(error::code_syntax, U\"Unterminated string literal.\");\n\n return false;\n }\n\n if ((c = *it++) == separator)\n {\n tokens.push_back(token(token::type_string, buffer));\n\n return true;\n }\n else if (c != '\\\\')\n {\n buffer.append(1, c);\n continue;\n }\n\n if (it >= end)\n {\n ctx->error(error::code_syntax, U\"Unterminated string literal.\");\n\n return false;\n }\n\n switch (c = *it++)\n {\n }\n }\n }\n #endif\n}\n<commit_msg>Remove code that has been commented out<commit_after>\/*\n * Copyright (c) 2017, Rauli Laine\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * 1. Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\/\n#include <plorth\/context.hpp>\n#include <plorth\/value-word.hpp>\n\nnamespace plorth\n{\n using source_iterator = unistring::const_iterator;\n\n static bool skip_whitespace(source_iterator&, const source_iterator&);\n static ref<value> compile_value(context*,\n source_iterator&,\n const source_iterator&);\n\n ref<quote> context::compile(const unistring& source)\n {\n std::vector<ref<class value>> values;\n ref<class value> value;\n auto it = std::begin(source);\n const auto end = std::end(source);\n\n while (it != end)\n {\n if (skip_whitespace(it, end))\n {\n break;\n }\n else if (!(value = compile_value(this, it, end)))\n {\n return ref<quote>();\n }\n values.push_back(value);\n }\n\n return m_runtime->compiled_quote(values);\n }\n\n \/**\n * Skips whitespace and comments from source code.\n *\n * \\return True if end of input has been reached, false otherwise.\n *\/\n static bool skip_whitespace(source_iterator& it, const source_iterator& end)\n {\n while (it != end)\n {\n \/\/ Skip line comments.\n if (*it == '#')\n {\n while (++it != end)\n {\n if (*it == '\\n' || *it == '\\r')\n {\n break;\n }\n }\n }\n else if (!std::isspace(*it))\n {\n return false;\n } else {\n ++it;\n }\n }\n\n return true;\n }\n\n static bool compile_escape_sequence(context* ctx,\n source_iterator& it,\n const source_iterator& end,\n unistring& buffer)\n {\n if (it >= end)\n {\n ctx->error(\n error::code_syntax,\n U\"Unexpected end of input; Missing escape sequence.\"\n );\n\n return false;\n }\n\n switch (*it++)\n {\n case 'b':\n buffer.append(1, 010);\n break;\n\n case 't':\n buffer.append(1, 011);\n break;\n\n case 'n':\n buffer.append(1, 012);\n break;\n\n case 'f':\n buffer.append(1, 014);\n break;\n\n case 'r':\n buffer.append(1, 015);\n break;\n\n case '\"':\n case '\\'':\n case '\\\\':\n case '\/':\n buffer.append(1, *(it - 1));\n break;\n\n case 'u':\n {\n unichar result = 0;\n\n for (int i = 0; i < 4; ++i)\n {\n if (it >= end)\n {\n ctx->error(\n error::code_syntax,\n U\"Unterminated escape sequence.\"\n );\n\n return false;\n }\n else if (!std::isxdigit(*it))\n {\n ctx->error(\n error::code_syntax,\n U\"Illegal Unicode hex escape sequence.\"\n );\n\n return false;\n }\n\n if (*it >= 'A' && *it <= 'F')\n {\n result = result * 16 + (*it++ - 'A' + 10);\n }\n else if (*it >= 'a' && *it <= 'f')\n {\n result = result * 16 + (*it++ - 'a' + 10);\n } else {\n result = result * 16 + (*it++ - '0');\n }\n }\n\n if (!unichar_validate(result))\n {\n ctx->error(\n error::code_syntax,\n U\"Illegal Unicode hex escape sequence.\"\n );\n\n return false;\n }\n\n buffer.append(1, result);\n }\n break;\n\n default:\n ctx->error(\n error::code_syntax,\n U\"Illegal escape sequence in string literal.\"\n );\n\n return false;\n }\n\n return true;\n }\n\n static ref<string> compile_string(context* ctx,\n source_iterator& it,\n const source_iterator& end)\n {\n unichar separator;\n unistring buffer;\n\n if (skip_whitespace(it, end))\n {\n ctx->error(\n error::code_syntax,\n U\"Unexpected end of input; Missing string.\"\n );\n\n return ref<string>();\n }\n\n if (*it != '\"' && *it != '\\'')\n {\n ctx->error(\n error::code_syntax,\n U\"Unexpected input; Missing string.\"\n );\n\n return ref<string>();\n }\n\n separator = *it++;\n\n for (;;)\n {\n if (it >= end)\n {\n ctx->error(\n error::code_syntax,\n unistring(U\"Unterminated string; Missing `\") + separator + U\"'\"\n );\n\n return ref<string>();\n }\n else if (*it == separator)\n {\n ++it;\n break;\n }\n else if (*it != '\\\\')\n {\n buffer.append(1, *it++);\n }\n else if (!compile_escape_sequence(ctx, ++it, end, buffer))\n {\n return ref<string>();\n }\n }\n\n return ctx->runtime()->string(buffer);\n }\n\n static ref<quote> compile_quote(context* ctx,\n source_iterator& it,\n const source_iterator& end)\n {\n std::vector<ref<value>> values;\n\n if (skip_whitespace(it, end))\n {\n ctx->error(\n error::code_syntax,\n U\"Unexpected end of input; Missing quote.\"\n );\n\n return ref<quote>();\n }\n\n if (*it != '(')\n {\n ctx->error(\n error::code_syntax,\n U\"Unexpected input; Missing quote.\"\n );\n\n return ref<quote>();\n }\n\n ++it;\n\n for (;;)\n {\n if (skip_whitespace(it, end))\n {\n ctx->error(error::code_syntax, U\"Unterminated quote; Missing `)'.\");\n\n return ref<quote>();\n }\n else if (*it == ')')\n {\n ++it;\n break;\n } else {\n const auto value = compile_value(ctx, it, end);\n\n if (!value)\n {\n return ref<quote>();\n }\n values.push_back(value);\n }\n }\n\n return ctx->runtime()->compiled_quote(values);\n }\n\n static ref<array> compile_array(context* ctx,\n source_iterator& it,\n const source_iterator& end)\n {\n std::vector<ref<value>> elements;\n\n if (skip_whitespace(it, end))\n {\n ctx->error(\n error::code_syntax,\n U\"Unexpected end of input; Missing array.\"\n );\n\n return ref<array>();\n }\n\n if (*it != '[')\n {\n ctx->error(\n error::code_syntax,\n U\"Unexpected input; Missing array.\"\n );\n\n return ref<array>();\n }\n\n ++it;\n\n for (;;)\n {\n if (skip_whitespace(it, end))\n {\n ctx->error(\n error::code_syntax,\n U\"Unterminated array; Missing `]'.\"\n );\n\n return ref<array>();\n }\n else if (*it == ']')\n {\n ++it;\n break;\n } else {\n const auto value = compile_value(ctx, it, end);\n\n if (!value)\n {\n return ref<array>();\n }\n elements.push_back(value);\n if (skip_whitespace(it, end) || (*it != ',' && *it != ']'))\n {\n ctx->error(\n error::code_syntax,\n U\"Unterminated array; Missing `]'.\"\n );\n\n return ref<array>();\n }\n else if (*it == ',')\n {\n ++it;\n }\n }\n }\n\n return ctx->runtime()->array(elements.data(), elements.size());\n }\n\n static ref<object> compile_object(context* ctx,\n source_iterator& it,\n const source_iterator& end)\n {\n object::container_type properties;\n\n if (skip_whitespace(it, end))\n {\n ctx->error(\n error::code_syntax,\n U\"Unexpected end of input; Missing object.\"\n );\n\n return ref<object>();\n }\n\n if (*it != '{')\n {\n ctx->error(\n error::code_syntax,\n U\"Unexpected input; Missing object.\"\n );\n\n return ref<object>();\n }\n\n ++it;\n\n for (;;)\n {\n if (skip_whitespace(it, end))\n {\n ctx->error(\n error::code_syntax,\n U\"Unterminated object; Missing `}'.\"\n );\n\n return ref<object>();\n }\n else if (*it == '}')\n {\n ++it;\n break;\n } else {\n ref<string> key;\n ref<class value> value;\n\n if (!(key = compile_string(ctx, it, end)))\n {\n return ref<object>();\n }\n\n if (skip_whitespace(it, end))\n {\n ctx->error(\n error::code_syntax,\n U\"Unterminated object; Missing `}'.\"\n );\n\n return ref<object>();\n }\n\n if (*it != ':')\n {\n ctx->error(\n error::code_syntax,\n U\"Missing `:' after property key.\"\n );\n\n return ref<object>();\n }\n\n if (!(value = compile_value(ctx, ++it, end)))\n {\n return ref<object>();\n }\n\n properties[key->to_string()] = value;\n\n if (skip_whitespace(it, end) || (*it != ',' && *it != '}'))\n {\n ctx->error(\n error::code_syntax,\n U\"Unterminated object; Missing `}'.\"\n );\n\n return ref<object>();\n }\n else if (*it == ',')\n {\n ++it;\n }\n }\n }\n\n return ctx->runtime()->value<object>(properties);\n }\n\n static ref<symbol> compile_symbol(context* ctx,\n source_iterator& it,\n const source_iterator& end)\n {\n unistring buffer;\n\n if (skip_whitespace(it, end))\n {\n ctx->error(\n error::code_syntax,\n U\"Unexpected end of input; Missing symbol.\"\n );\n\n return ref<symbol>();\n }\n\n if (!unichar_isword(*it))\n {\n ctx->error(\n error::code_syntax,\n U\"Unexpected input; Missing symbol.\"\n );\n\n return ref<symbol>();\n }\n\n buffer.append(1, *it++);\n while (it != end && unichar_isword(*it))\n {\n buffer.append(1, *it++);\n }\n\n return ctx->runtime()->value<symbol>(buffer);\n }\n\n static ref<word> compile_word(context* ctx,\n source_iterator& it,\n const source_iterator& end)\n {\n const auto& runtime = ctx->runtime();\n ref<class symbol> symbol;\n std::vector<ref<value>> values;\n\n if (skip_whitespace(it, end))\n {\n ctx->error(\n error::code_syntax,\n U\"Unexpected end of input; Missing word.\"\n );\n\n return ref<word>();\n }\n\n if (*it != ':')\n {\n ctx->error(\n error::code_syntax,\n U\"Unexpected input; Missing word.\"\n );\n\n return ref<word>();\n }\n\n ++it;\n\n if (!(symbol = compile_symbol(ctx, it, end)))\n {\n return ref<word>();\n }\n\n for (;;)\n {\n if (skip_whitespace(it, end))\n {\n ctx->error(error::code_syntax, U\"Unterminated word; Missing `;'.\");\n\n return ref<word>();\n }\n else if (*it == ';')\n {\n ++it;\n break;\n } else {\n const auto value = compile_value(ctx, it, end);\n\n if (!value)\n {\n return ref<word>();\n }\n values.push_back(value);\n }\n }\n\n return runtime->value<word>(symbol, runtime->compiled_quote(values));\n }\n\n static ref<value> compile_value(context* ctx,\n source_iterator& it,\n const source_iterator& end)\n {\n if (skip_whitespace(it, end))\n {\n ctx->error(\n error::code_syntax,\n U\"Unexpected end of input; Missing value.\"\n );\n\n return ref<value>();\n }\n switch (*it)\n {\n case '\"':\n case '\\'':\n return compile_string(ctx, it, end);\n\n case '(':\n return compile_quote(ctx, it, end);\n\n case '[':\n return compile_array(ctx, it, end);\n\n case '{':\n return compile_object(ctx, it, end);\n\n case ':':\n return compile_word(ctx, it, end);\n\n default:\n return compile_symbol(ctx, it, end);\n }\n }\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"JEBString\/CodePoints\/CodePointString.hpp\"\n\n#include \"JEBString\/Unicode\/CaseInsensitive.hpp\"\n#include \"JEBString\/Unicode\/UnicodePredicates.hpp\"\n\nnamespace JEBString { namespace EncodedStrings {\n\nusing CodePoints::makeForwardIterator;\nusing CodePoints::makeReverseIterator;\n\ntemplate <typename It1, typename Enc1, typename It2, typename Enc2>\nint32_t caseInsensitiveCompare(EncodedRange<It1, Enc1> str,\n EncodedRange<It2, Enc2> cmp)\n{\n return caseInsensitiveCompare(makeForwardIterator(str),\n makeForwardIterator(cmp));\n}\n\ntemplate <typename It1, typename Enc1, typename It2, typename Enc2>\nbool caseInsensitiveEqual(EncodedRange<It1, Enc1> str,\n EncodedRange<It2, Enc2> cmp)\n{\n return caseInsensitiveEqual(makeForwardIterator(str),\n makeForwardIterator(cmp));\n}\n\ntemplate <typename It1, typename Enc1, typename It2, typename Enc2>\nbool caseInsensitiveLess(EncodedRange<It1, Enc1> str,\n EncodedRange<It2, Enc2> cmp)\n{\n return caseInsensitiveLess(makeForwardIterator(str),\n makeForwardIterator(cmp));\n}\n\ntemplate <typename It, typename Enc>\nbool contains(EncodedRange<It, Enc> str, uint32_t chr)\n{\n auto it = makeForwardIterator(str);\n return advanceUntil(it, [=](uint32_t c){return c == chr;});\n}\n\ntemplate <typename InpIt, typename Enc1, typename OutIt, typename Enc2>\nvoid copy(EncodedRange<InpIt, Enc1> src, Encoder<OutIt, Enc2> dst)\n{\n if (src.encoding().encoding == dst.encoding().encoding)\n std::copy(begin(src), end(src), dst.iterator());\n else\n copy(makeForwardIterator(src), dst);\n}\n\ntemplate <typename It1, typename Enc1, typename It2, typename Enc2>\nbool endsWith(EncodedRange<It1, Enc1> str, EncodedRange<It2, Enc2> cmp,\n FindFlags_t flags \/*= FindFlags::Defaults*\/)\n{\n return startsWith(makeReverseIterator(str), makeReverseIterator(cmp),\n flags);\n}\n\ntemplate <typename It1, typename Enc1, typename It2, typename Enc2>\nEncodedRange<It1, Enc1> find(EncodedRange<It1, Enc1> str,\n EncodedRange<It2, Enc2> cmp,\n FindFlags_t flags \/*= FindFlags::Defaults*\/)\n{\n auto it = makeForwardIterator(str);\n return makeEncodedRange(CodePoints::find(\n it, makeForwardIterator(cmp), flags));\n}\n\ntemplate <typename It1, typename Enc1, typename It2, typename Enc2>\nEncodedRange<It1, Enc1> findNext(EncodedRange<It1, Enc1>& str,\n EncodedRange<It2, Enc2> cmp,\n FindFlags_t flags \/*= FindFlags::Defaults*\/)\n{\n auto it = makeForwardIterator(str);\n auto result = makeEncodedRange(CodePoints::find(\n it, makeForwardIterator(cmp), flags));\n str.setBegin(end(result));\n return result;\n}\n\ntemplate <typename It, typename Enc, typename UnaryFunc>\nvoid forEachCodePoint(EncodedRange<It, Enc> str, UnaryFunc func)\n{\n auto it = makeForwardIterator(str);\n uint32_t c;\n while (it.next(c))\n func(c);\n}\n\ntemplate <typename It, typename Enc, typename UnaryFunc>\nEncodedRange<It, Enc> forEachLine(\n EncodedRange<It, Enc> str, UnaryFunc tokenFunc,\n size_t maxParts \/*= 0*\/,\n SplitFlags_t flags \/*= SplitFlags::Defaults*\/)\n{\n return makeEncodedRange(forEachLine(\n makeForwardIterator(str), tokenFunc, maxParts, flags));\n}\n\ntemplate <typename It, typename Enc, typename UnaryFunc>\nvoid forEachLower(EncodedRange<It, Enc> str, UnaryFunc func)\n{\n forEachCodePoint(str, [&](uint32_t c){func(Unicode::lower(c));});\n}\n\ntemplate <typename It, typename Enc, typename UnaryFunc>\nvoid forEachTitle(EncodedRange<It, Enc> str, UnaryFunc func)\n{\n bool capNext = true;\n auto it = makeForwardIterator(str);\n uint32_t c;\n while (it.next(c))\n {\n if (!Unicode::isCasedLetter(c))\n {\n func(c);\n capNext = !Unicode::isLetter(c);\n }\n else if (capNext)\n {\n func(Unicode::title(c));\n capNext = false;\n }\n else\n {\n func(Unicode::lower(c));\n }\n }\n}\n\ntemplate <typename It, typename Enc, typename UnaryPred,\n typename UnaryFunc>\nEncodedRange<It, Enc> forEachToken(\n EncodedRange<It, Enc> str, UnaryPred delimiterPred,\n UnaryFunc tokenFunc,\n size_t maxParts \/*= 0*\/,\n SplitFlags_t flags \/*= SplitFlags::Defaults*\/)\n{\n return makeEncodedRange(forEachToken(\n makeForwardIterator(str), delimiterPred,\n tokenFunc, maxParts, flags));\n}\n\ntemplate <typename It1, typename Enc1, typename It2, typename Enc2,\n typename UnaryFunc>\nEncodedRange<It1, Enc1> forEachToken(\n EncodedRange<It1, Enc1> str, EncodedRange<It2, Enc2> delimiter,\n UnaryFunc tokenFunc,\n size_t maxParts \/*= 0*\/,\n SplitFlags_t flags \/*= SplitFlags::Defaults*\/)\n{\n return makeEncodedRange(forEachToken(\n makeForwardIterator(str), makeForwardIterator(delimiter),\n tokenFunc, maxParts, flags));\n}\n\ntemplate <typename It, typename Enc, typename UnaryFunc>\nvoid forEachUpper(EncodedRange<It, Enc> str, UnaryFunc func)\n{\n forEachCodePoint(str, [&](uint32_t c){func(Unicode::upper(c));});\n}\n\ntemplate <typename It, typename Enc>\nbool isAlphaNumeric(EncodedRange<It, Enc> str)\n{\n auto it = makeForwardIterator(str);\n return !empty(str) && advanceWhile(it, Unicode::isAlphaNumeric);\n}\n\ntemplate <typename It, typename Enc>\nEncodedRange<It, Enc> nextLine(EncodedRange<It, Enc>& str)\n{\n auto it = makeForwardIterator(str);\n auto line = makeEncodedRange(nextLine(it));\n it.setBegin(begin(it));\n return line;\n}\n\ntemplate <typename It, typename Enc, typename UnaryPred>\nEncodedRange<It, Enc> nextToken(EncodedRange<It, Enc>& str, UnaryPred pred)\n{\n auto it = makeForwardIterator(str);\n auto token = makeEncodedRange(nextToken(it, pred));\n str.setBegin(end(it));\n return token;\n}\n\ntemplate <typename It, typename Enc>\nIt nthCharacter(EncodedRange<It, Enc> str, ptrdiff_t n)\n{\n if (n >= 0)\n {\n auto it = makeForwardIterator(str);\n advanceCharacters(it, n);\n return begin(it);\n }\n else\n {\n auto it = makeReverseIterator(str);\n advanceCharacters(it, -n);\n return end(it);\n }\n}\n\ntemplate <typename It, typename Enc, typename UnaryPred>\nEncodedRange<It, Enc> prevToken(EncodedRange<It, Enc>& str, UnaryPred pred)\n{\n auto it = makeReverseIterator(str);\n auto token = makeEncodedRange(nextToken(it, pred));\n str.setEnd(end(it));\n return token;\n}\n\ntemplate <typename String, typename It1, typename Enc1,\n typename It2, typename Enc2, typename It3, typename Enc3>\nString& replace(String& dst,\n EncodedRange<It1, Enc1> str,\n EncodedRange<It2, Enc2> cmp,\n EncodedRange<It3, Enc3> subst,\n size_t max \/*= 0*\/,\n FindFlags_t flags \/*= FindFlags::Defaults*\/)\n{\n auto first = begin(str);\n auto match = findNext(str, cmp, flags);\n while (!empty(match))\n {\n dst.insert(end(dst), first, begin(match));\n dst.insert(end(dst), begin(subst), end(subst));\n first = begin(str);\n if (--max == 0)\n break;\n match = findNext(str, cmp, flags);\n }\n dst.insert(end(dst), first, end(str));\n return dst;\n}\n\ntemplate <typename InpIt, typename Enc1, typename OutIt, typename Enc2>\nvoid reverse(EncodedRange<InpIt, Enc1> src, Encoder<OutIt, Enc2> dst)\n{\n auto it = makeReverseIterator(src);\n while (advanceCharacter(it))\n {\n src.setBegin(end(it));\n copy(src, dst);\n src.setEnd(src.begin());\n }\n}\n\ntemplate <typename It1, typename Enc1, typename It2, typename Enc2>\nbool startsWith(EncodedRange<It1, Enc1> str, EncodedRange<It2, Enc2> cmp,\n FindFlags_t flags \/*= FindFlags::Defaults*\/)\n{\n return startsWith(makeForwardIterator(str),\n makeForwardIterator(cmp),\n flags);\n}\n\ntemplate <typename It, typename Enc>\nsize_t stringLength(EncodedRange<It, Enc> str)\n{\n auto it = makeForwardIterator(str);\n return advanceCharacters(it, std::numeric_limits<ptrdiff_t>::max());\n}\n\ntemplate <typename It, typename Enc>\nEncodedRange<It, Enc> substring(\n EncodedRange<It, Enc> str,\n ptrdiff_t first,\n ptrdiff_t last \/*= std::numeric_limits<long>::max()*\/)\n{\n if (0 <= first)\n {\n str.setBegin(nthCharacter(str, first));\n if (last < 0)\n str.setEnd(nthCharacter(str, last));\n else if (first <= last)\n str.setEnd(nthCharacter(str, last - first));\n else\n str.setEnd(str.begin());\n }\n else if (0 <= last)\n {\n auto newBegin = nthCharacter(str, first);\n if (std::distance(begin(str), newBegin) <= last)\n str.setEnd(nthCharacter(str, last));\n else\n str.setEnd(newBegin);\n str.setBegin(newBegin);\n }\n else\n {\n str.setEnd(nthCharacter(str, last));\n if (first < last)\n str.setBegin(nthCharacter(str, first - last));\n else\n str.setBegin(str.end());\n }\n return str;\n}\n\ntemplate <typename It, typename Enc, typename UnaryPred>\nEncodedRange<It, Enc> trim(EncodedRange<It, Enc> str, UnaryPred trimChar)\n{\n return trimBack(trimFront(str, trimChar), trimChar);\n}\n\n\ntemplate <typename It, typename Enc, typename UnaryPred>\nEncodedRange<It, Enc> trimFront(EncodedRange<It, Enc> str,\n UnaryPred trimChar)\n{\n auto first = makeForwardIterator(str);\n advanceWhile(first, trimChar);\n return makeEncodedRange(first);\n}\n\ntemplate <typename It, typename Enc, typename UnaryPred>\nEncodedRange<It, Enc> trimBack(EncodedRange<It, Enc> str,\n UnaryPred trimChar)\n{\n auto last = makeReverseIterator(str);\n advanceWhile(last, trimChar);\n return makeEncodedRange(last);\n}\n\n}}\n<commit_msg>Added missing include.<commit_after>#include \"JEBString\/CodePoints\/CodePointAlgorithms.hpp\"\n#include \"JEBString\/CodePoints\/CodePointString.hpp\"\n#include \"JEBString\/Unicode\/CaseInsensitive.hpp\"\n#include \"JEBString\/Unicode\/UnicodePredicates.hpp\"\n\nnamespace JEBString { namespace EncodedStrings {\n\nusing CodePoints::makeForwardIterator;\nusing CodePoints::makeReverseIterator;\n\ntemplate <typename It1, typename Enc1, typename It2, typename Enc2>\nint32_t caseInsensitiveCompare(EncodedRange<It1, Enc1> str,\n EncodedRange<It2, Enc2> cmp)\n{\n return caseInsensitiveCompare(makeForwardIterator(str),\n makeForwardIterator(cmp));\n}\n\ntemplate <typename It1, typename Enc1, typename It2, typename Enc2>\nbool caseInsensitiveEqual(EncodedRange<It1, Enc1> str,\n EncodedRange<It2, Enc2> cmp)\n{\n return caseInsensitiveEqual(makeForwardIterator(str),\n makeForwardIterator(cmp));\n}\n\ntemplate <typename It1, typename Enc1, typename It2, typename Enc2>\nbool caseInsensitiveLess(EncodedRange<It1, Enc1> str,\n EncodedRange<It2, Enc2> cmp)\n{\n return caseInsensitiveLess(makeForwardIterator(str),\n makeForwardIterator(cmp));\n}\n\ntemplate <typename It, typename Enc>\nbool contains(EncodedRange<It, Enc> str, uint32_t chr)\n{\n auto it = makeForwardIterator(str);\n return CodePoints::advanceUntil(it, [=](uint32_t c){return c == chr;});\n}\n\ntemplate <typename InpIt, typename Enc1, typename OutIt, typename Enc2>\nvoid copy(EncodedRange<InpIt, Enc1> src, Encoder<OutIt, Enc2> dst)\n{\n if (src.encoding().encoding == dst.encoding().encoding)\n std::copy(begin(src), end(src), dst.iterator());\n else\n copy(makeForwardIterator(src), dst);\n}\n\ntemplate <typename It1, typename Enc1, typename It2, typename Enc2>\nbool endsWith(EncodedRange<It1, Enc1> str, EncodedRange<It2, Enc2> cmp,\n FindFlags_t flags \/*= FindFlags::Defaults*\/)\n{\n return startsWith(makeReverseIterator(str), makeReverseIterator(cmp),\n flags);\n}\n\ntemplate <typename It1, typename Enc1, typename It2, typename Enc2>\nEncodedRange<It1, Enc1> find(EncodedRange<It1, Enc1> str,\n EncodedRange<It2, Enc2> cmp,\n FindFlags_t flags \/*= FindFlags::Defaults*\/)\n{\n auto it = makeForwardIterator(str);\n return makeEncodedRange(CodePoints::find(\n it, makeForwardIterator(cmp), flags));\n}\n\ntemplate <typename It1, typename Enc1, typename It2, typename Enc2>\nEncodedRange<It1, Enc1> findNext(EncodedRange<It1, Enc1>& str,\n EncodedRange<It2, Enc2> cmp,\n FindFlags_t flags \/*= FindFlags::Defaults*\/)\n{\n auto it = makeForwardIterator(str);\n auto result = makeEncodedRange(CodePoints::find(\n it, makeForwardIterator(cmp), flags));\n str.setBegin(end(result));\n return result;\n}\n\ntemplate <typename It, typename Enc, typename UnaryFunc>\nvoid forEachCodePoint(EncodedRange<It, Enc> str, UnaryFunc func)\n{\n auto it = makeForwardIterator(str);\n uint32_t c;\n while (it.next(c))\n func(c);\n}\n\ntemplate <typename It, typename Enc, typename UnaryFunc>\nEncodedRange<It, Enc> forEachLine(\n EncodedRange<It, Enc> str, UnaryFunc tokenFunc,\n size_t maxParts \/*= 0*\/,\n SplitFlags_t flags \/*= SplitFlags::Defaults*\/)\n{\n return makeEncodedRange(forEachLine(\n makeForwardIterator(str), tokenFunc, maxParts, flags));\n}\n\ntemplate <typename It, typename Enc, typename UnaryFunc>\nvoid forEachLower(EncodedRange<It, Enc> str, UnaryFunc func)\n{\n forEachCodePoint(str, [&](uint32_t c){func(Unicode::lower(c));});\n}\n\ntemplate <typename It, typename Enc, typename UnaryFunc>\nvoid forEachTitle(EncodedRange<It, Enc> str, UnaryFunc func)\n{\n bool capNext = true;\n auto it = makeForwardIterator(str);\n uint32_t c;\n while (it.next(c))\n {\n if (!Unicode::isCasedLetter(c))\n {\n func(c);\n capNext = !Unicode::isLetter(c);\n }\n else if (capNext)\n {\n func(Unicode::title(c));\n capNext = false;\n }\n else\n {\n func(Unicode::lower(c));\n }\n }\n}\n\ntemplate <typename It, typename Enc, typename UnaryPred,\n typename UnaryFunc>\nEncodedRange<It, Enc> forEachToken(\n EncodedRange<It, Enc> str, UnaryPred delimiterPred,\n UnaryFunc tokenFunc,\n size_t maxParts \/*= 0*\/,\n SplitFlags_t flags \/*= SplitFlags::Defaults*\/)\n{\n return makeEncodedRange(forEachToken(\n makeForwardIterator(str), delimiterPred,\n tokenFunc, maxParts, flags));\n}\n\ntemplate <typename It1, typename Enc1, typename It2, typename Enc2,\n typename UnaryFunc>\nEncodedRange<It1, Enc1> forEachToken(\n EncodedRange<It1, Enc1> str, EncodedRange<It2, Enc2> delimiter,\n UnaryFunc tokenFunc,\n size_t maxParts \/*= 0*\/,\n SplitFlags_t flags \/*= SplitFlags::Defaults*\/)\n{\n return makeEncodedRange(forEachToken(\n makeForwardIterator(str), makeForwardIterator(delimiter),\n tokenFunc, maxParts, flags));\n}\n\ntemplate <typename It, typename Enc, typename UnaryFunc>\nvoid forEachUpper(EncodedRange<It, Enc> str, UnaryFunc func)\n{\n forEachCodePoint(str, [&](uint32_t c){func(Unicode::upper(c));});\n}\n\ntemplate <typename It, typename Enc>\nbool isAlphaNumeric(EncodedRange<It, Enc> str)\n{\n auto it = makeForwardIterator(str);\n return !empty(str) && advanceWhile(it, Unicode::isAlphaNumeric);\n}\n\ntemplate <typename It, typename Enc>\nEncodedRange<It, Enc> nextLine(EncodedRange<It, Enc>& str)\n{\n auto it = makeForwardIterator(str);\n auto line = makeEncodedRange(nextLine(it));\n it.setBegin(begin(it));\n return line;\n}\n\ntemplate <typename It, typename Enc, typename UnaryPred>\nEncodedRange<It, Enc> nextToken(EncodedRange<It, Enc>& str, UnaryPred pred)\n{\n auto it = makeForwardIterator(str);\n auto token = makeEncodedRange(nextToken(it, pred));\n str.setBegin(end(it));\n return token;\n}\n\ntemplate <typename It, typename Enc>\nIt nthCharacter(EncodedRange<It, Enc> str, ptrdiff_t n)\n{\n if (n >= 0)\n {\n auto it = makeForwardIterator(str);\n advanceCharacters(it, n);\n return begin(it);\n }\n else\n {\n auto it = makeReverseIterator(str);\n advanceCharacters(it, -n);\n return end(it);\n }\n}\n\ntemplate <typename It, typename Enc, typename UnaryPred>\nEncodedRange<It, Enc> prevToken(EncodedRange<It, Enc>& str, UnaryPred pred)\n{\n auto it = makeReverseIterator(str);\n auto token = makeEncodedRange(nextToken(it, pred));\n str.setEnd(end(it));\n return token;\n}\n\ntemplate <typename String, typename It1, typename Enc1,\n typename It2, typename Enc2, typename It3, typename Enc3>\nString& replace(String& dst,\n EncodedRange<It1, Enc1> str,\n EncodedRange<It2, Enc2> cmp,\n EncodedRange<It3, Enc3> subst,\n size_t max \/*= 0*\/,\n FindFlags_t flags \/*= FindFlags::Defaults*\/)\n{\n auto first = begin(str);\n auto match = findNext(str, cmp, flags);\n while (!empty(match))\n {\n dst.insert(end(dst), first, begin(match));\n dst.insert(end(dst), begin(subst), end(subst));\n first = begin(str);\n if (--max == 0)\n break;\n match = findNext(str, cmp, flags);\n }\n dst.insert(end(dst), first, end(str));\n return dst;\n}\n\ntemplate <typename InpIt, typename Enc1, typename OutIt, typename Enc2>\nvoid reverse(EncodedRange<InpIt, Enc1> src, Encoder<OutIt, Enc2> dst)\n{\n auto it = makeReverseIterator(src);\n while (advanceCharacter(it))\n {\n src.setBegin(end(it));\n copy(src, dst);\n src.setEnd(src.begin());\n }\n}\n\ntemplate <typename It1, typename Enc1, typename It2, typename Enc2>\nbool startsWith(EncodedRange<It1, Enc1> str, EncodedRange<It2, Enc2> cmp,\n FindFlags_t flags \/*= FindFlags::Defaults*\/)\n{\n return startsWith(makeForwardIterator(str),\n makeForwardIterator(cmp),\n flags);\n}\n\ntemplate <typename It, typename Enc>\nsize_t stringLength(EncodedRange<It, Enc> str)\n{\n auto it = makeForwardIterator(str);\n return advanceCharacters(it, std::numeric_limits<ptrdiff_t>::max());\n}\n\ntemplate <typename It, typename Enc>\nEncodedRange<It, Enc> substring(\n EncodedRange<It, Enc> str,\n ptrdiff_t first,\n ptrdiff_t last \/*= std::numeric_limits<long>::max()*\/)\n{\n if (0 <= first)\n {\n str.setBegin(nthCharacter(str, first));\n if (last < 0)\n str.setEnd(nthCharacter(str, last));\n else if (first <= last)\n str.setEnd(nthCharacter(str, last - first));\n else\n str.setEnd(str.begin());\n }\n else if (0 <= last)\n {\n auto newBegin = nthCharacter(str, first);\n if (std::distance(begin(str), newBegin) <= last)\n str.setEnd(nthCharacter(str, last));\n else\n str.setEnd(newBegin);\n str.setBegin(newBegin);\n }\n else\n {\n str.setEnd(nthCharacter(str, last));\n if (first < last)\n str.setBegin(nthCharacter(str, first - last));\n else\n str.setBegin(str.end());\n }\n return str;\n}\n\ntemplate <typename It, typename Enc, typename UnaryPred>\nEncodedRange<It, Enc> trim(EncodedRange<It, Enc> str, UnaryPred trimChar)\n{\n return trimBack(trimFront(str, trimChar), trimChar);\n}\n\n\ntemplate <typename It, typename Enc, typename UnaryPred>\nEncodedRange<It, Enc> trimFront(EncodedRange<It, Enc> str,\n UnaryPred trimChar)\n{\n auto first = makeForwardIterator(str);\n advanceWhile(first, trimChar);\n return makeEncodedRange(first);\n}\n\ntemplate <typename It, typename Enc, typename UnaryPred>\nEncodedRange<It, Enc> trimBack(EncodedRange<It, Enc> str,\n UnaryPred trimChar)\n{\n auto last = makeReverseIterator(str);\n advanceWhile(last, trimChar);\n return makeEncodedRange(last);\n}\n\n}}\n<|endoftext|>"} {"text":"<commit_before>\/***********************************************************************************************************************\n**\n** Copyright (c) 2011, 2015 ETH Zurich\n** All rights reserved.\n**\n** Redistribution and use in source and binary forms, with or without modification, are permitted provided that the\n** following conditions are met:\n**\n** * Redistributions of source code must retain the above copyright notice, this list of conditions and the following\n** disclaimer.\n** * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the\n** following disclaimer in the documentation and\/or other materials provided with the distribution.\n** * Neither the name of the ETH Zurich nor the names of its contributors may be used to endorse or promote products\n** derived from this software without specific prior written permission.\n**\n**\n** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES,\n** INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n** SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n**\n***********************************************************************************************************************\/\n\n#include \"Commit.h\"\n\nnamespace FilePersistence {\n\nSignature::Signature()\n{\n\tdateTime_ = QDateTime::currentDateTimeUtc();\n\ttimeZone_ = QTimeZone{QTimeZone::systemTimeZoneId()};\n}\n\nCommitFile::CommitFile(){}\n\nCommitFile::CommitFile(QString relativePath, qint64 size, std::unique_ptr<char[]> content)\n\t: relativePath_{relativePath}, size_{size}, content_{std::move(content)}\n{}\n\nCommitFile::CommitFile(QString relativePath, qint64 size, std::unique_ptr<char[], CommitFileContentDeleter> content)\n\t: relativePath_{relativePath}, size_{size}, contentWithDeleter_{std::move(content)}\n{}\n\nconst char* CommitFile::content() const\n{\n\tQ_ASSERT((content_ && !contentWithDeleter_) || (!content_ && contentWithDeleter_));\n\tif (content_)\n\t\treturn content_.get();\n\telse\n\t\treturn contentWithDeleter_.get();\n}\n\nCommit::Commit() {}\n\nCommit::~Commit()\n{\n\tfor (auto file : files_.values())\n\t\tSAFE_DELETE(file);\n}\n\nvoid Commit::addFile(QString relativePath, qint64 size, std::unique_ptr<char[]> content)\n{\n\tfiles_.insert(relativePath, new CommitFile{relativePath, size, std::move(content)});\n}\n\nvoid Commit::addFile(QString relativePath, qint64 size, std::unique_ptr<char[], CommitFileContentDeleter> content)\n{\n\tfiles_.insert(relativePath, new CommitFile{relativePath, size, std::move(content)});\n}\n\nbool Commit::getFileContent(QString fileName, const char*& content, int& contentSize, bool exactFileNameMatching) const\n{\n\tQHash<QString, CommitFile*>::const_iterator iter;\n\n\t\/\/ name of file must match fileName exactly\n\tif (exactFileNameMatching)\n\t\titer = files_.find(fileName);\n\t\/\/ name of file must contain fileName\n\telse\n\t{\n\t\titer = files_.constBegin();\n\t\twhile (iter != files_.constEnd())\n\t\t{\n\t\t\tQFileInfo fileInfo{iter.key()};\n\t\t\tif ((fileName.startsWith(\"{\") && fileInfo.fileName().contains(fileName))|| fileInfo.fileName() == fileName)\n\t\t\t\tbreak;\n\t\t\titer++;\n\t\t}\n\t}\n\n\tif (iter != files_.constEnd())\n\t{\n\t\tcontentSize = iter.value()->size_;\n\t\tcontent = iter.value()->content();\n\t\treturn true;\n\t}\n\telse\n\t\treturn false;\n}\n\n}\n<commit_msg>Add isDir check<commit_after>\/***********************************************************************************************************************\n**\n** Copyright (c) 2011, 2015 ETH Zurich\n** All rights reserved.\n**\n** Redistribution and use in source and binary forms, with or without modification, are permitted provided that the\n** following conditions are met:\n**\n** * Redistributions of source code must retain the above copyright notice, this list of conditions and the following\n** disclaimer.\n** * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the\n** following disclaimer in the documentation and\/or other materials provided with the distribution.\n** * Neither the name of the ETH Zurich nor the names of its contributors may be used to endorse or promote products\n** derived from this software without specific prior written permission.\n**\n**\n** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES,\n** INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n** SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n**\n***********************************************************************************************************************\/\n\n#include \"Commit.h\"\n\nnamespace FilePersistence {\n\nSignature::Signature()\n{\n\tdateTime_ = QDateTime::currentDateTimeUtc();\n\ttimeZone_ = QTimeZone{QTimeZone::systemTimeZoneId()};\n}\n\nCommitFile::CommitFile(){}\n\nCommitFile::CommitFile(QString relativePath, qint64 size, std::unique_ptr<char[]> content)\n\t: relativePath_{relativePath}, size_{size}, content_{std::move(content)}\n{}\n\nCommitFile::CommitFile(QString relativePath, qint64 size, std::unique_ptr<char[], CommitFileContentDeleter> content)\n\t: relativePath_{relativePath}, size_{size}, contentWithDeleter_{std::move(content)}\n{}\n\nconst char* CommitFile::content() const\n{\n\tQ_ASSERT((content_ && !contentWithDeleter_) || (!content_ && contentWithDeleter_));\n\tif (content_)\n\t\treturn content_.get();\n\telse\n\t\treturn contentWithDeleter_.get();\n}\n\nCommit::Commit() {}\n\nCommit::~Commit()\n{\n\tfor (auto file : files_.values())\n\t\tSAFE_DELETE(file);\n}\n\nvoid Commit::addFile(QString relativePath, qint64 size, std::unique_ptr<char[]> content)\n{\n\tfiles_.insert(relativePath, new CommitFile{relativePath, size, std::move(content)});\n}\n\nvoid Commit::addFile(QString relativePath, qint64 size, std::unique_ptr<char[], CommitFileContentDeleter> content)\n{\n\tfiles_.insert(relativePath, new CommitFile{relativePath, size, std::move(content)});\n}\n\nbool Commit::getFileContent(QString fileName, const char*& content, int& contentSize, bool exactFileNameMatching) const\n{\n\tQHash<QString, CommitFile*>::const_iterator iter;\n\n\t\/\/ name of file must match fileName exactly\n\tif (exactFileNameMatching)\n\t\titer = files_.find(fileName);\n\t\/\/ name of file must contain fileName\n\telse\n\t{\n\t\titer = files_.constBegin();\n\t\twhile (iter != files_.constEnd())\n\t\t{\n\t\t\tQFileInfo fileInfo{iter.key()};\n\t\t\tif (!fileInfo.isDir() &&\n\t\t\t\t ((fileName.startsWith(\"{\") && fileInfo.fileName().contains(fileName))\n\t\t\t\t || fileInfo.fileName() == fileName))\n\t\t\t\tbreak;\n\t\t\titer++;\n\t\t}\n\t}\n\n\tif (iter != files_.constEnd())\n\t{\n\t\tcontentSize = iter.value()->size_;\n\t\tcontent = iter.value()->content();\n\t\treturn true;\n\t}\n\telse\n\t\treturn false;\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"PortalGame.h\"\n#include \"PhysicsController.h\"\n#include \"Sphere.h\"\n#include \"PhysicsCamera.h\"\n#include \"Box.h\"\n#include \"Cylinder.h\"\n#include \"Steerable3DController.h\"\n#include \"Ground.h\"\n#include \"Content.h\"\n#include <btBulletDynamicsCommon.h>\n#include <gtc\/quaternion.hpp>\n#include <gtx\/quaternion.hpp>\n#include <gtx\/euler_angles.hpp>\n#include <gtx\/norm.hpp>\n#include \"VectorDrawer.h\"\n\nusing namespace BGE;\n\n\nPortalGame::PortalGame(void)\n{\n\tphysicsFactory = NULL;\n\tdynamicsWorld = NULL;\n\tbroadphase = NULL;\n\tdispatcher = NULL;\n\tsolver = NULL;\n\tfullscreen = false;\n}\n\n\nPortalGame::~PortalGame(void)\n{\n}\n\n\nstd::shared_ptr<GameComponent> station;\n\/\/float theta = 0.0f;\n\nbool PortalGame::Initialise() \n{\n\triftEnabled = false;\n\t\/\/ Set up the collision configuration and dispatcher\n collisionConfiguration = new btDefaultCollisionConfiguration();\n dispatcher = new btCollisionDispatcher(collisionConfiguration);\n \n \/\/ The world.\n\tbtVector3 worldMin(-1000,-1000,-1000);\n\tbtVector3 worldMax(1000,1000,1000);\n\tbroadphase = new btAxisSweep3(worldMin,worldMax);\n\tsolver = new btSequentialImpulseConstraintSolver();\n\tdynamicsWorld = new btDiscreteDynamicsWorld(dispatcher,broadphase,solver,collisionConfiguration);\n dynamicsWorld->setGravity(btVector3(0,-9,0));\n\n\twidth = 800;\n\theight = 600;\n\n\tphysicsFactory = make_shared<PhysicsFactory>(dynamicsWorld);\n\n\tphysicsFactory->CreateGroundPhysics();\n\tphysicsFactory->CreateCameraPhysics();\n\n\t\/\/std::shared_ptr<GameComponent> box = make_shared<Box>(1, 1, 1);\n\t\/\/box->position = glm::vec3(0, 5, -20);\n\t\/\/Attach(box);\n\n\t\/\/non kinematic cyl\n\t\/\/ Stands for Box Objects \n\tshared_ptr<PhysicsController> colCyl_01 = physicsFactory->CreateCylinder(0.5,5, glm::vec3(5, 0, 0), glm::quat()); \n\t\/\/colCyl_01->tag=\"colObject_01\";\n\tshared_ptr<PhysicsController> colBox_01 = physicsFactory->CreateBox(1,1,1, glm::vec3(5, 7, 0), glm::quat()); \n\tcolBox_01->tag=\"colObject2\"; \n\n\tshared_ptr<PhysicsController> colCyl_02 = physicsFactory->CreateCylinder(0.5,8, glm::vec3(12, 0, 0), glm::quat());\n\n\tshared_ptr<PhysicsController> colBox_02 = physicsFactory->CreateBox(1,1,1, glm::vec3(12, 10, 0), glm::quat()); \n\tcolBox_02->tag=\"colObject2\"; \n\n\tshared_ptr<PhysicsController> colCyl_03 = physicsFactory->CreateCylinder(0.5,10, glm::vec3(18, 0, 0), glm::quat()); \n\tshared_ptr<PhysicsController> colBox_03 = physicsFactory->CreateBox(1,1,1, glm::vec3(18, 12, 0), glm::quat()); \n\tcolBox_03->tag=\"colObject2\"; \n \n \t\/\/box for collision\n\tshared_ptr<PhysicsController> colBox = physicsFactory->CreateBox(1,1,1, glm::vec3(5, 0, 0), glm::quat()); \n\t\/*shared_ptr<PhysicsController> colBox = physicsFactory->CreateBox(1,1,1, glm::vec3(5, 10, 0), glm::quat()); \n \tcolBox->tag=\"colObject2\"; \n+\t*\/\n\n\t\/\/ Ball to throw at Boxes\n\tshared_ptr<PhysicsController> colBall_01 = physicsFactory->CreateSphere(0.5,glm::vec3(5, 0, 10),glm::quat());\n\tcolBall_01->tag=\"colObject1\";\n\n\n\n\n\n\t\/\/physicsFactory->CreateWall(glm::vec3(-20,0,20), 50, 10);\n\n\t \/\/Now some constraints\n\t\/*shared_ptr<PhysicsController> box1 = physicsFactory->CreateBox(1,1,4, glm::vec3(5, 5, 0), glm::quat()); \n\tshared_ptr<PhysicsController> box2 = physicsFactory->CreateBox(1,1,4, glm::vec3(5, 5, 5), glm::quat()); *\/\n\t\/\/shared_ptr<PhysicsController> cap1 = physicsFactory->CreateCapsule(1,1, glm::vec3(5, 50, 5), glm::quat()); \n\t\/\/cap1->scale = glm::vec3(0.001,0.001,0.001);\n\n\t \/\/A hinge\n\t\/\/btHingeConstraint * hinge = new btHingeConstraint(*box1->rigidBody, *box2->rigidBody, btVector3(0,0,2.5f),btVector3(0,0,-2.5f), btVector3(0,1,0), btVector3(0,1,0), true);\n\t\/\/dynamicsWorld->addConstraint(hinge);\n\n\t\/\/box1 = physicsFactory->CreateBox(1,1,4, glm::vec3(10, 5, 0), glm::quat()); \n\t\/\/box2 = physicsFactory->CreateBox(1,1,4, glm::vec3(10, 5, 5), glm::quat());\n\t\/\/cap1 = physicsFactory->CreateCapsule(5,5, glm::vec3(5, 5, 5), glm::quat());\n\n\n\n\n\n\n\t\/\/physicsFactory->CreateCylinder(10, 3, glm::vec3(0, 20, 0), glm::quat());\n\n\t\/\/\/*std::shared_ptr<GameComponent> ship = make_shared<GameComponent>();\n\t\/\/ship->ambient = glm::vec3(0.2f, 0.2, 0.2f);\n\t\/\/ship->specular = glm::vec3(1.2f, 1.2f, 1.2f);\n\t\/\/std::shared_ptr<Model> model = Content::LoadModel(\"cobramk3\", glm::rotate(glm::mat4(1), 180.0f, GameComponent::basisUp));\t\n\t\/\/std::shared_ptr<GameComponent> steerable = make_shared<Steerable3DController>(model);\n\t\/\/steerable->position = glm::vec3(20, 5, -20);\n\t\/\/std::shared_ptr<VectorDrawer> vectorDrawer = make_shared<VectorDrawer>();\n\t\/\/vectorDrawer->scale = glm::vec3(5,5,10);\n\t\/\/ship->Attach(steerable);\n\t\/\/ship->Attach(model);\n\t\/\/ship->Attach(vectorDrawer);\n\t\/\/Attach(ship);*\/\n\n\t\/\/\/\/ Create a hierarchy\n\t\/\/station = make_shared<GameComponent>();\n\t\/\/station->worldMode = world_modes::from_self;\n\t\/\/station->ambient = glm::vec3(0.2f, 0.2, 0.2f);\n\t\/\/station->specular = glm::vec3(0,0,0);\n\t\/\/station->scale = glm::vec3(2,2,2);\n\t\/\/std::shared_ptr<Model> cmodel = Content::LoadModel(\"coriolis\", glm::rotate(glm::mat4(1), 90.0f, GameComponent::basisUp));\t\n\t\/\/station->Attach(cmodel);\n\t\/\/station->Attach(make_shared<VectorDrawer>(glm::vec3(7,7,7)));\n\t\/\/station->position = glm::vec3(40, 5, -20);\n\t\/\/Attach(station);\n\n\t\/\/\/\/ Add a child to the station and update by including the parent's world transform\n\t\/\/std::shared_ptr<GameComponent> ship1 = make_shared<GameComponent>();\n\t\/\/ship1->worldMode = world_modes::from_self_with_parent;\n\t\/\/ship1->ambient = glm::vec3(0.2f, 0.2, 0.2f);\n\t\/\/ship1->specular = glm::vec3(1.2f, 1.2f, 1.2f);\n\t\/\/std::shared_ptr<Model> ana = Content::LoadModel(\"anaconda\", glm::rotate(glm::mat4(1), 180.0f, GameComponent::basisUp));\t\n\t\/\/ship1->Attach(ana);\n\t\/\/ship1->position = glm::vec3(0, 0, -10);\n\t\/\/station->Attach(ship1);\n\n\t\n\t\/\/physicsFactory->CreateVehicle(glm::vec3(0,10,-30));\n\n\t\/\/ Create Inca Pyramid\n\t\/\/position(), baseWidth, blockHeight, blockWidth, blockDepth\n \/\/physicsFactory->CreateIncaPyramid(glm::vec3(20,0,-20), 6, 1.5, 1.5, 1.5);\n\n\t\/\/Create Rag Doll\n\t\/\/physicsFactory->CreateRagDoll(glm::vec3(25,0,-50));\n\n\n\tif (!Game::Initialise()) {\n\t\treturn false;\n\t}\n\n\tcamera->GetController()->position = glm::vec3(0,10, 0);\n\n\n\treturn true;\n}\n\n\nvoid BGE::PortalGame::Update(float timeDelta)\n{\n\tdynamicsWorld->stepSimulation(timeDelta,100);\n\t\/\/station->Yaw(timeDelta * 20.0f);\n\n\t\/\/collision detection check\n\t int numManifolds = dynamicsWorld->getDispatcher()->getNumManifolds();\n for (int i=0;i<numManifolds;i++)\n {\n btPersistentManifold* contactManifold = dynamicsWorld->getDispatcher()->getManifoldByIndexInternal(i);\n btCollisionObject* obA = (btCollisionObject*)(contactManifold->getBody0());\n\t\t\t\tbtCollisionObject* obB = (btCollisionObject*)(contactManifold->getBody1());\n\t\t\t\t\/\/ btCollisionObject* obA = (btCollisionObject*)(contactManifold->colCyl = physicsFactory->CreateCylinder(2,1, glm::vec3(5, 0, -10), glm::quat()); );\n\t\t\t\t\/\/btCollisionObject* obB = (btCollisionObject*)(contactManifold->colBox = physicsFactory->CreateBox(1,1,1, glm::vec3(5, 0, 0), glm::quat()); );\n PhysicsController * pcA = reinterpret_cast<PhysicsController*>(obA->getUserPointer());\n PhysicsController * pcB = reinterpret_cast<PhysicsController*>(obB->getUserPointer());\n\n int numContacts = contactManifold->getNumContacts();\n if (numContacts > 0)\n {\n if ((pcA != nullptr) && (pcB != nullptr))\n {\n\t\t\t\t\t\t\t\/\/PrintText(\"Collision between \" + pcA->tag + \" and \" + pcB->tag);\n\t\t\t\t\t\t\tif (pcA->tag == \"colObject1\" && pcB->tag == \"colObject2\")\n {\n\t\t\t\t\t\t\t\t PrintText(\"Collision between \" + pcA->tag + \" and \" + pcB->tag);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\/*if (pcB->tag == \"colObject1\" && pcA->tag == \"colObject2\")\n {\n\t\t\t\t\t\t\t\t PrintText(\"Collision between \" + pcA->tag + \" and \" + pcB->tag);\n\t\t\t\t\t\t\t}*\/\n }\n }\n }\n\n\tGame::Update(timeDelta);\n\n\n}\n\nvoid BGE::PortalGame::Cleanup()\n{\n\tGame::Cleanup();\n}\n<commit_msg>Walls (again)<commit_after>#include \"PortalGame.h\"\n#include \"PhysicsController.h\"\n#include \"Sphere.h\"\n#include \"PhysicsCamera.h\"\n#include \"Box.h\"\n#include \"Cylinder.h\"\n#include \"Steerable3DController.h\"\n#include \"Ground.h\"\n#include \"Content.h\"\n#include <btBulletDynamicsCommon.h>\n#include <gtc\/quaternion.hpp>\n#include <gtx\/quaternion.hpp>\n#include <gtx\/euler_angles.hpp>\n#include <gtx\/norm.hpp>\n#include \"VectorDrawer.h\"\n\nusing namespace BGE;\n\n\nPortalGame::PortalGame(void)\n{\n\tphysicsFactory = NULL;\n\tdynamicsWorld = NULL;\n\tbroadphase = NULL;\n\tdispatcher = NULL;\n\tsolver = NULL;\n\tfullscreen = false;\n}\n\n\nPortalGame::~PortalGame(void)\n{\n}\n\n\nstd::shared_ptr<GameComponent> station;\n\/\/float theta = 0.0f;\n\nbool PortalGame::Initialise() \n{\n\triftEnabled = false;\n\t\/\/ Set up the collision configuration and dispatcher\n collisionConfiguration = new btDefaultCollisionConfiguration();\n dispatcher = new btCollisionDispatcher(collisionConfiguration);\n \n \/\/ The world.\n\tbtVector3 worldMin(-1000,-1000,-1000);\n\tbtVector3 worldMax(1000,1000,1000);\n\tbroadphase = new btAxisSweep3(worldMin,worldMax);\n\tsolver = new btSequentialImpulseConstraintSolver();\n\tdynamicsWorld = new btDiscreteDynamicsWorld(dispatcher,broadphase,solver,collisionConfiguration);\n dynamicsWorld->setGravity(btVector3(0,-9,0));\n\n\twidth = 800;\n\theight = 600;\n\n\tphysicsFactory = make_shared<PhysicsFactory>(dynamicsWorld);\n\n\tphysicsFactory->CreateGroundPhysics();\n\tphysicsFactory->CreateCameraPhysics();\n\n\t\/\/std::shared_ptr<GameComponent> box = make_shared<Box>(1, 1, 1);\n\t\/\/box->position = glm::vec3(0, 5, -20);\n\t\/\/Attach(box);\n\n\t\/\/non kinematic cyl\n\t\/\/ Stands for Box Objects \n\tshared_ptr<PhysicsController> colCyl_01 = physicsFactory->CreateCylinder(0.5,5, glm::vec3(5, 0, 0), glm::quat()); \n\t\/\/colCyl_01->tag=\"colObject_01\";\n\tshared_ptr<PhysicsController> colBox_01 = physicsFactory->CreateBox(1,1,1, glm::vec3(5, 7, 0), glm::quat()); \n\tcolBox_01->tag=\"colObject2\"; \n\n\tshared_ptr<PhysicsController> colCyl_02 = physicsFactory->CreateCylinder(0.5,8, glm::vec3(12, 0, 0), glm::quat());\n\n\tshared_ptr<PhysicsController> colBox_02 = physicsFactory->CreateBox(1,1,1, glm::vec3(12, 10, 0), glm::quat()); \n\tcolBox_02->tag=\"colObject2\"; \n\n\tshared_ptr<PhysicsController> colCyl_03 = physicsFactory->CreateCylinder(0.5,10, glm::vec3(18, 0, 0), glm::quat()); \n\tshared_ptr<PhysicsController> colBox_03 = physicsFactory->CreateBox(1,1,1, glm::vec3(18, 12, 0), glm::quat()); \n\tcolBox_03->tag=\"colObject2\"; \n \n \t\/\/box for collision\n\tshared_ptr<PhysicsController> colBox = physicsFactory->CreateBox(1,1,1, glm::vec3(5, 0, 0), glm::quat()); \n\t\/*shared_ptr<PhysicsController> colBox = physicsFactory->CreateBox(1,1,1, glm::vec3(5, 10, 0), glm::quat()); \n \tcolBox->tag=\"colObject2\"; \n+\t*\/\n\n\t\/\/ Ball to throw at Boxes\n\tshared_ptr<PhysicsController> colBall_01 = physicsFactory->CreateSphere(0.5,glm::vec3(5, 0, 10),glm::quat());\n\tcolBall_01->tag=\"colObject1\";\n\n\n\t\/\/create walls for games\n\t\/\/left wall for box 1\n\tshared_ptr<PhysicsController> leftWall1 = physicsFactory->CreateBox(0.5,10,15, glm::vec3(-10, 0, -20), glm::quat()); \n\tleftWall1->diffuse = glm::vec3(1,0,1);\n\t\/\/leftWall1\n\n\t\/\/right wall for box 1\n\tshared_ptr<PhysicsController> rightWall1 = physicsFactory->CreateBox(0.5,10,15, glm::vec3(-2, 0, -20), glm::quat()); \n\trightWall1->diffuse = glm::vec3(1,0,1);\t\n\n\t\/\/top wall for box 1\n\tshared_ptr<PhysicsController> topWall1 = physicsFactory->CreateBox(15,0.5,15, glm::vec3(-4, 0, -20), glm::quat()); \n\ttopWall1->diffuse = glm::vec3(1,0,1);\t\n\n\n\t\/\/physicsFactory->CreateWall(glm::vec3(-20,0,20), 50, 10);\n\n\t \/\/Now some constraints\n\t\/*shared_ptr<PhysicsController> box1 = physicsFactory->CreateBox(1,1,4, glm::vec3(5, 5, 0), glm::quat()); \n\tshared_ptr<PhysicsController> box2 = physicsFactory->CreateBox(1,1,4, glm::vec3(5, 5, 5), glm::quat()); *\/\n\t\/\/shared_ptr<PhysicsController> cap1 = physicsFactory->CreateCapsule(1,1, glm::vec3(5, 50, 5), glm::quat()); \n\t\/\/cap1->scale = glm::vec3(0.001,0.001,0.001);\n\n\t \/\/A hinge\n\t\/\/btHingeConstraint * hinge = new btHingeConstraint(*box1->rigidBody, *box2->rigidBody, btVector3(0,0,2.5f),btVector3(0,0,-2.5f), btVector3(0,1,0), btVector3(0,1,0), true);\n\t\/\/dynamicsWorld->addConstraint(hinge);\n\n\t\/\/box1 = physicsFactory->CreateBox(1,1,4, glm::vec3(10, 5, 0), glm::quat()); \n\t\/\/box2 = physicsFactory->CreateBox(1,1,4, glm::vec3(10, 5, 5), glm::quat());\n\t\/\/cap1 = physicsFactory->CreateCapsule(5,5, glm::vec3(5, 5, 5), glm::quat());\n\n\n\n\n\n\n\t\/\/physicsFactory->CreateCylinder(10, 3, glm::vec3(0, 20, 0), glm::quat());\n\n\t\/\/\/*std::shared_ptr<GameComponent> ship = make_shared<GameComponent>();\n\t\/\/ship->ambient = glm::vec3(0.2f, 0.2, 0.2f);\n\t\/\/ship->specular = glm::vec3(1.2f, 1.2f, 1.2f);\n\t\/\/std::shared_ptr<Model> model = Content::LoadModel(\"cobramk3\", glm::rotate(glm::mat4(1), 180.0f, GameComponent::basisUp));\t\n\t\/\/std::shared_ptr<GameComponent> steerable = make_shared<Steerable3DController>(model);\n\t\/\/steerable->position = glm::vec3(20, 5, -20);\n\t\/\/std::shared_ptr<VectorDrawer> vectorDrawer = make_shared<VectorDrawer>();\n\t\/\/vectorDrawer->scale = glm::vec3(5,5,10);\n\t\/\/ship->Attach(steerable);\n\t\/\/ship->Attach(model);\n\t\/\/ship->Attach(vectorDrawer);\n\t\/\/Attach(ship);*\/\n\n\t\/\/\/\/ Create a hierarchy\n\t\/\/station = make_shared<GameComponent>();\n\t\/\/station->worldMode = world_modes::from_self;\n\t\/\/station->ambient = glm::vec3(0.2f, 0.2, 0.2f);\n\t\/\/station->specular = glm::vec3(0,0,0);\n\t\/\/station->scale = glm::vec3(2,2,2);\n\t\/\/std::shared_ptr<Model> cmodel = Content::LoadModel(\"coriolis\", glm::rotate(glm::mat4(1), 90.0f, GameComponent::basisUp));\t\n\t\/\/station->Attach(cmodel);\n\t\/\/station->Attach(make_shared<VectorDrawer>(glm::vec3(7,7,7)));\n\t\/\/station->position = glm::vec3(40, 5, -20);\n\t\/\/Attach(station);\n\n\t\/\/\/\/ Add a child to the station and update by including the parent's world transform\n\t\/\/std::shared_ptr<GameComponent> ship1 = make_shared<GameComponent>();\n\t\/\/ship1->worldMode = world_modes::from_self_with_parent;\n\t\/\/ship1->ambient = glm::vec3(0.2f, 0.2, 0.2f);\n\t\/\/ship1->specular = glm::vec3(1.2f, 1.2f, 1.2f);\n\t\/\/std::shared_ptr<Model> ana = Content::LoadModel(\"anaconda\", glm::rotate(glm::mat4(1), 180.0f, GameComponent::basisUp));\t\n\t\/\/ship1->Attach(ana);\n\t\/\/ship1->position = glm::vec3(0, 0, -10);\n\t\/\/station->Attach(ship1);\n\n\t\n\t\/\/physicsFactory->CreateVehicle(glm::vec3(0,10,-30));\n\n\t\/\/ Create Inca Pyramid\n\t\/\/position(), baseWidth, blockHeight, blockWidth, blockDepth\n \/\/physicsFactory->CreateIncaPyramid(glm::vec3(20,0,-20), 6, 1.5, 1.5, 1.5);\n\n\t\/\/Create Rag Doll\n\t\/\/physicsFactory->CreateRagDoll(glm::vec3(25,0,-50));\n\n\n\tif (!Game::Initialise()) {\n\t\treturn false;\n\t}\n\n\tcamera->GetController()->position = glm::vec3(0,10, 0);\n\n\n\treturn true;\n}\n\n\nvoid BGE::PortalGame::Update(float timeDelta)\n{\n\tdynamicsWorld->stepSimulation(timeDelta,100);\n\t\/\/station->Yaw(timeDelta * 20.0f);\n\n\t\/\/collision detection check\n\t int numManifolds = dynamicsWorld->getDispatcher()->getNumManifolds();\n for (int i=0;i<numManifolds;i++)\n {\n btPersistentManifold* contactManifold = dynamicsWorld->getDispatcher()->getManifoldByIndexInternal(i);\n btCollisionObject* obA = (btCollisionObject*)(contactManifold->getBody0());\n\t\t\t\tbtCollisionObject* obB = (btCollisionObject*)(contactManifold->getBody1());\n\t\t\t\t\/\/ btCollisionObject* obA = (btCollisionObject*)(contactManifold->colCyl = physicsFactory->CreateCylinder(2,1, glm::vec3(5, 0, -10), glm::quat()); );\n\t\t\t\t\/\/btCollisionObject* obB = (btCollisionObject*)(contactManifold->colBox = physicsFactory->CreateBox(1,1,1, glm::vec3(5, 0, 0), glm::quat()); );\n PhysicsController * pcA = reinterpret_cast<PhysicsController*>(obA->getUserPointer());\n PhysicsController * pcB = reinterpret_cast<PhysicsController*>(obB->getUserPointer());\n\n int numContacts = contactManifold->getNumContacts();\n if (numContacts > 0)\n {\n if ((pcA != nullptr) && (pcB != nullptr))\n {\n\t\t\t\t\t\t\t\/\/PrintText(\"Collision between \" + pcA->tag + \" and \" + pcB->tag);\n\t\t\t\t\t\t\tif (pcA->tag == \"colObject1\" && pcB->tag == \"colObject2\")\n {\n\t\t\t\t\t\t\t\t PrintText(\"Collision between \" + pcA->tag + \" and \" + pcB->tag);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\/*if (pcB->tag == \"colObject1\" && pcA->tag == \"colObject2\")\n {\n\t\t\t\t\t\t\t\t PrintText(\"Collision between \" + pcA->tag + \" and \" + pcB->tag);\n\t\t\t\t\t\t\t}*\/\n }\n }\n }\n\n\tGame::Update(timeDelta);\n\n\n}\n\nvoid BGE::PortalGame::Cleanup()\n{\n\tGame::Cleanup();\n}\n<|endoftext|>"} {"text":"<commit_before>\/* \n *\tfilter≈\n *\tExternal object for Max\/Lydbaer\n *\tCopyright © 2008 by Timothy Place\n * \n *\tLicense: This code is licensed under the terms of the GNU LGPL\n *\thttp:\/\/www.gnu.org\/licenses\/lgpl.html \n *\/\n\n#include \"maxMulticore.h\"\n#define thisTTClass TTFilter\n\n\n\n\/\/ For the filter≈ object, we wish to create our own class, \n\/\/ which then encapsulates the various filters available in TTBlue.\n\nclass TTFilter : public TTAudioObject {\nprotected:\n\tTTAudioObjectPtr\tactualFilterObject;\t\t\/\/\/< The actual filter object that this object is currently wrapping\n\tTTFloat64\t\t\tfrequency;\t\t\t\t\/\/\/< The center or cutoff frequency of the filter\n\tTTFloat64\t\t\tq;\t\t\t\t\t\t\/\/\/< The width of the filter\n\tTTSymbolPtr\t\t\ttype;\t\t\t\t\t\/\/\/< The name of the current filter type\n\t\npublic:\n\t\n\t\/\/ Constructor\n\tTTFilter(TTUInt16 newMaxNumChannels)\n\t\t: TTAudioObject(\"filter\", newMaxNumChannels), actualFilterObject(NULL)\n\t{\n\t\tregisterAttributeWithSetter(frequency, kTypeFloat64);\n\t\tregisterAttributeWithSetter(q, kTypeFloat64);\n\t\tregisterAttributeWithSetter(type, kTypeSymbol);\n\t\t\n\t\tregisterMessageWithArgument(getTypes);\n\t\tregisterMessageSimple(clear);\n\n\t\tregisterMessageWithArgument(updateMaxNumChannels);\n\t\tregisterMessageSimple(updateSr);\n\t\t\n\t\tsetAttributeValue(TT(\"maxNumChannels\"), newMaxNumChannels);\n\t\tsetAttributeValue(TT(\"type\"), TT(\"lowpass.1\"));\n\t\tsetAttributeValue(TT(\"frequency\"), 1000.0);\n\t\tsetAttributeValue(TT(\"q\"), 1.0);\n\t\tsetProcessMethod(processAudio);\n\t}\n\t\n\t\/\/ Destructor\n\tvirtual ~TTFilter()\n\t{\n\t\t;\n\t}\n\t\n\t\n\tTTErr setfrequency(const TTValue& newValue)\n\t{\t\n\t\tfrequency = newValue;\n\t\treturn actualFilterObject->setAttributeValue(TT(\"frequency\"), frequency);\n\t}\n\t\t\n\tTTErr setq(const TTValue& newValue)\n\t{\t\n\t\tq = newValue;\n\t\treturn actualFilterObject->setAttributeValue(TT(\"q\"), q);\n\t}\n\t\t\n\tTTErr settype(const TTValue& newValue)\n\t{\t\n\t\tTTSymbolPtr newType = newValue;\n\t\tTTErr\t\terr = kTTErrNone;\n\t\t\n\t\t\/\/ if the type didn't change, then don't change the filter\n\t\tif(newType == type)\n\t\t\treturn kTTErrNone;\n\t\t\n\t\ttype = newType;\n\t\terr = TTObjectInstantiate(type, &actualFilterObject, maxNumChannels);\t\t\t\n\t\tif(!err){\n\t\t\t\/\/ Now that we have our new filter, update it with the current state of the wrapper:\n\t\t\tactualFilterObject->setAttributeValue(TT(\"frequency\"), frequency);\n\t\t\terr = actualFilterObject->setAttributeValue(TT(\"q\"), q);\n\t\t\tif(err == kTTErrInvalidAttribute)\n\t\t\t\terr = actualFilterObject->setAttributeValue(TT(\"resonance\"), q);\n\t\t\tactualFilterObject->setAttributeValue(TT(\"bypass\"), this->attrBypass);\n\t\t\tactualFilterObject->setAttributeValue(TT(\"sr\"), sr);\n\t\t}\n\t\treturn err;\n\t}\n\t\t\n\t\n\tTTErr getTypes(TTValue& listOfFilterTypesToReturn)\n\t{\n\t\treturn TTGetRegisteredClassNamesForTags(listOfFilterTypesToReturn, TT(\"filter\"));\n\t}\n\t\n\t\n\tTTErr clear()\n\t{\n\t\treturn actualFilterObject->sendMessage(TT(\"clear\"));\n\t}\n\t\n\t\n\tTTErr updateMaxNumChannels(const TTValue& oldMaxNumChannels)\n\t{\n\t\tif(actualFilterObject)\n\t\t\treturn actualFilterObject->setAttributeValue(kTTSym_maxNumChannels, maxNumChannels);\n\t\telse\n\t\t\treturn kTTErrNone;\n\t}\n\t\n\t\n\tTTErr updateSr()\n\t{\n\t\treturn actualFilterObject->setAttributeValue(kTTSym_sr, sr);\n\t}\n\n\t\n\tTTErr processAudio(TTAudioSignalArrayPtr inputs, TTAudioSignalArrayPtr outputs)\n\t{\n\t\treturn actualFilterObject->process(inputs, outputs);\n\t}\n\t\n};\n\n\n\n\/\/ Because we have created this overdriveExtended class outside of the main TTBlue framework, \n\/\/ we have to define our own factory method that is used to create a new instance of our object.\n\nTTObjectPtr instantiateTTFilter(TTSymbolPtr className, TTValue& arguments)\n{\n\treturn new TTFilter(arguments);\n}\n\n\n\nint main(void)\n{\n\tTTMulticoreInit();\n\n\t\/\/ First, we have to register our custom subclass with the TTBlue framework.\n\tTTClassRegister(TT(\"filter\"), \"audio, processor, effect, lydbaer\", &instantiateTTFilter);\n\t\/\/ Then we are able to wrap it as a Max class.\n\treturn wrapAsMaxbaer(TT(\"filter\"), \"filter≈\", NULL);\n}\n\n<commit_msg>filter≈ object is now compiling properly<commit_after>\/* \n *\tfilter≈\n *\tExternal object for Max\/Lydbaer\n *\tCopyright © 2008 by Timothy Place\n * \n *\tLicense: This code is licensed under the terms of the GNU LGPL\n *\thttp:\/\/www.gnu.org\/licenses\/lgpl.html \n *\/\n\n#include \"maxMulticore.h\"\n\n#define thisTTClass\t\t\tTTFilter\n#define thisTTClassName\t\t\"filter\"\n#define thisTTClassTags\t\t\"audio, processor, filter, multicore\"\n\n\n\n\/\/ For the filter≈ object, we wish to create our own class, \n\/\/ which then encapsulates the various filters available in TTBlue.\n\nTTAUDIOCLASS(TTFilter)\n\nprotected:\n\tTTAudioObjectPtr\tactualFilterObject;\t\t\/\/\/< The actual filter object that this object is currently wrapping\n\tTTFloat64\t\t\tfrequency;\t\t\t\t\/\/\/< The center or cutoff frequency of the filter\n\tTTFloat64\t\t\tq;\t\t\t\t\t\t\/\/\/< The width of the filter\n\tTTSymbolPtr\t\t\ttype;\t\t\t\t\t\/\/\/< The name of the current filter type\n\t\npublic:\n\t\t\n\tTTErr setfrequency(const TTValue& newValue)\n\t{\t\n\t\tfrequency = newValue;\n\t\treturn actualFilterObject->setAttributeValue(TT(\"frequency\"), frequency);\n\t}\n\t\t\n\tTTErr setq(const TTValue& newValue)\n\t{\t\n\t\tq = newValue;\n\t\treturn actualFilterObject->setAttributeValue(TT(\"q\"), q);\n\t}\n\t\t\n\tTTErr settype(const TTValue& newValue)\n\t{\t\n\t\tTTSymbolPtr newType = newValue;\n\t\tTTErr\t\terr = kTTErrNone;\n\t\t\n\t\t\/\/ if the type didn't change, then don't change the filter\n\t\tif(newType == type)\n\t\t\treturn kTTErrNone;\n\t\t\n\t\ttype = newType;\n\t\terr = TTObjectInstantiate(type, &actualFilterObject, maxNumChannels);\t\t\t\n\t\tif(!err){\n\t\t\t\/\/ Now that we have our new filter, update it with the current state of the wrapper:\n\t\t\tactualFilterObject->setAttributeValue(TT(\"frequency\"), frequency);\n\t\t\terr = actualFilterObject->setAttributeValue(TT(\"q\"), q);\n\t\t\tif(err == kTTErrInvalidAttribute)\n\t\t\t\terr = actualFilterObject->setAttributeValue(TT(\"resonance\"), q);\n\t\t\tactualFilterObject->setAttributeValue(TT(\"bypass\"), this->attrBypass);\n\t\t\tactualFilterObject->setAttributeValue(TT(\"sr\"), sr);\n\t\t}\n\t\treturn err;\n\t}\n\t\t\n\t\n\tTTErr getTypes(TTValue& listOfFilterTypesToReturn)\n\t{\n\t\treturn TTGetRegisteredClassNamesForTags(listOfFilterTypesToReturn, TT(\"filter\"));\n\t}\n\t\n\t\n\tTTErr clear()\n\t{\n\t\treturn actualFilterObject->sendMessage(TT(\"clear\"));\n\t}\n\t\n\t\n\tTTErr updateMaxNumChannels(const TTValue& oldMaxNumChannels)\n\t{\n\t\tif(actualFilterObject)\n\t\t\treturn actualFilterObject->setAttributeValue(kTTSym_maxNumChannels, maxNumChannels);\n\t\telse\n\t\t\treturn kTTErrNone;\n\t}\n\t\n\t\n\tTTErr updateSr()\n\t{\n\t\treturn actualFilterObject->setAttributeValue(kTTSym_sr, sr);\n\t}\n\n\t\n\tTTErr processAudio(TTAudioSignalArrayPtr inputs, TTAudioSignalArrayPtr outputs)\n\t{\n\t\treturn actualFilterObject->process(inputs, outputs);\n\t}\n\t\n};\n\n\nTT_AUDIO_CONSTRUCTOR_EXPORT,\n\tactualFilterObject(NULL)\n{\n\tregisterAttributeWithSetter(frequency, kTypeFloat64);\n\tregisterAttributeWithSetter(q, kTypeFloat64);\n\tregisterAttributeWithSetter(type, kTypeSymbol);\n\t\n\tregisterMessageWithArgument(getTypes);\n\tregisterMessageSimple(clear);\n\t\n\tregisterMessageWithArgument(updateMaxNumChannels);\n\tregisterMessageSimple(updateSr);\n\t\n\tsetAttributeValue(TT(\"maxNumChannels\"), arguments);\n\tsetAttributeValue(TT(\"type\"), TT(\"lowpass.1\"));\n\tsetAttributeValue(TT(\"frequency\"), 1000.0);\n\tsetAttributeValue(TT(\"q\"), 1.0);\n\tsetProcessMethod(processAudio);\n}\n\n\n\/\/ Destructor\nTTFilter::~TTFilter()\n{\n\t;\n}\n\n\n\/*******************************************************************************\/\n\nint main(void)\n{\n\tTTMulticoreInit();\n\n\t\/\/ First, we have to register our custom subclass with the Jamoma Foundation runtime.\n\tTTFilter::registerClass();\n\t\n\t\/\/ Then we are able to wrap it as a Max class.\n\treturn wrapAsMaxbaer(TT(\"filter\"), \"filter≈\", NULL);\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright 2019-2020 Diligent Graphics LLC\n * Copyright 2015-2019 Egor Yusov\n * \n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * \n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n * In no event and under no legal theory, whether in tort (including negligence), \n * contract, or otherwise, unless required by applicable law (such as deliberate \n * and grossly negligent acts) or agreed to in writing, shall any Contributor be\n * liable for any damages, including any direct, indirect, special, incidental, \n * or consequential damages of any character arising as a result of this License or \n * out of the use or inability to use the software (including but not limited to damages \n * for loss of goodwill, work stoppage, computer failure or malfunction, or any and \n * all other commercial damages or losses), even if such Contributor has been advised \n * of the possibility of such damages.\n *\/\n\n#include \"pch.h\"\n\n#include \"FBOCache.hpp\"\n#include \"RenderDeviceGLImpl.hpp\"\n#include \"TextureBaseGL.hpp\"\n#include \"GLContextState.hpp\"\n\nnamespace Diligent\n{\n\nbool FBOCache::FBOCacheKey::operator==(const FBOCacheKey& Key) const\n{\n if (Hash != 0 && Key.Hash != 0 && Hash != Key.Hash)\n return false;\n\n if (NumRenderTargets != Key.NumRenderTargets)\n return false;\n for (Uint32 rt = 0; rt < NumRenderTargets; ++rt)\n {\n if (RTIds[rt] != Key.RTIds[rt])\n return false;\n if (RTIds[rt])\n {\n if (!(RTVDescs[rt] == Key.RTVDescs[rt]))\n return false;\n }\n }\n if (DSId != Key.DSId)\n return false;\n if (DSId)\n {\n if (!(DSVDesc == Key.DSVDesc))\n return false;\n }\n return true;\n}\n\nstd::size_t FBOCache::FBOCacheKeyHashFunc::operator()(const FBOCacheKey& Key) const\n{\n if (Key.Hash == 0)\n {\n std::hash<TextureViewDesc> TexViewDescHasher;\n Key.Hash = 0;\n HashCombine(Key.Hash, Key.NumRenderTargets);\n for (Uint32 rt = 0; rt < Key.NumRenderTargets; ++rt)\n {\n HashCombine(Key.Hash, Key.RTIds[rt]);\n if (Key.RTIds[rt])\n HashCombine(Key.Hash, TexViewDescHasher(Key.RTVDescs[rt]));\n }\n HashCombine(Key.Hash, Key.DSId);\n if (Key.DSId)\n HashCombine(Key.Hash, TexViewDescHasher(Key.DSVDesc));\n }\n return Key.Hash;\n}\n\n\nFBOCache::FBOCache()\n{\n m_Cache.max_load_factor(0.5f);\n m_TexIdToKey.max_load_factor(0.5f);\n}\n\nFBOCache::~FBOCache()\n{\n VERIFY(m_Cache.empty(), \"FBO cache is not empty. Are there any unreleased objects?\");\n VERIFY(m_TexIdToKey.empty(), \"TexIdToKey cache is not empty.\");\n}\n\nvoid FBOCache::OnReleaseTexture(ITexture* pTexture)\n{\n ThreadingTools::LockHelper CacheLock(m_CacheLockFlag);\n\n auto* pTexGL = ValidatedCast<TextureBaseGL>(pTexture);\n \/\/ Find all FBOs that this texture used in\n auto EqualRange = m_TexIdToKey.equal_range(pTexGL->GetUniqueID());\n for (auto It = EqualRange.first; It != EqualRange.second; ++It)\n {\n m_Cache.erase(It->second);\n }\n m_TexIdToKey.erase(EqualRange.first, EqualRange.second);\n}\n\nconst GLObjectWrappers::GLFrameBufferObj& FBOCache::GetFBO(Uint32 NumRenderTargets,\n TextureViewGLImpl* ppRTVs[],\n TextureViewGLImpl* pDSV,\n GLContextState& ContextState)\n{\n \/\/ Pop null render targets from the end of the list\n while (NumRenderTargets > 0 && ppRTVs[NumRenderTargets - 1] == nullptr)\n --NumRenderTargets;\n\n VERIFY(NumRenderTargets != 0 || pDSV != nullptr, \"At least one render target or a depth-stencil buffer must be provided\");\n\n \/\/ Lock the cache\n ThreadingTools::LockHelper CacheLock(m_CacheLockFlag);\n\n \/\/ Construct the key\n FBOCacheKey Key;\n VERIFY(NumRenderTargets < MAX_RENDER_TARGETS, \"Too many render targets are being set\");\n NumRenderTargets = std::min(NumRenderTargets, MAX_RENDER_TARGETS);\n Key.NumRenderTargets = NumRenderTargets;\n for (Uint32 rt = 0; rt < NumRenderTargets; ++rt)\n {\n auto* pRTView = ppRTVs[rt];\n if (pRTView == nullptr)\n continue;\n\n auto* pColorTexGL = pRTView->GetTexture<TextureBaseGL>();\n pColorTexGL->TextureMemoryBarrier(\n GL_FRAMEBUFFER_BARRIER_BIT, \/\/ Reads and writes via framebuffer object attachments after the\n \/\/ barrier will reflect data written by shaders prior to the barrier.\n \/\/ Additionally, framebuffer writes issued after the barrier will wait\n \/\/ on the completion of all shader writes issued prior to the barrier.\n ContextState);\n\n Key.RTIds[rt] = pColorTexGL->GetUniqueID();\n Key.RTVDescs[rt] = pRTView->GetDesc();\n }\n\n if (pDSV)\n {\n auto* pDepthTexGL = pDSV->GetTexture<TextureBaseGL>();\n pDepthTexGL->TextureMemoryBarrier(GL_FRAMEBUFFER_BARRIER_BIT, ContextState);\n Key.DSId = pDepthTexGL->GetUniqueID();\n Key.DSVDesc = pDSV->GetDesc();\n }\n\n \/\/ Try to find FBO in the map\n auto It = m_Cache.find(Key);\n if (It != m_Cache.end())\n {\n return It->second;\n }\n else\n {\n \/\/ Create a new FBO\n GLObjectWrappers::GLFrameBufferObj NewFBO(true);\n\n ContextState.BindFBO(NewFBO);\n\n \/\/ Initialize the FBO\n for (Uint32 rt = 0; rt < NumRenderTargets; ++rt)\n {\n if (auto* pRTView = ppRTVs[rt])\n {\n const auto& RTVDesc = pRTView->GetDesc();\n auto* pColorTexGL = pRTView->GetTexture<TextureBaseGL>();\n pColorTexGL->AttachToFramebuffer(RTVDesc, GL_COLOR_ATTACHMENT0 + rt);\n }\n }\n\n if (pDSV != nullptr)\n {\n const auto& DSVDesc = pDSV->GetDesc();\n auto* pDepthTexGL = pDSV->GetTexture<TextureBaseGL>();\n GLenum AttachmentPoint = 0;\n if (DSVDesc.Format == TEX_FORMAT_D32_FLOAT ||\n DSVDesc.Format == TEX_FORMAT_D16_UNORM)\n {\n#ifdef DILIGENT_DEBUG\n {\n const auto GLTexFmt = pDepthTexGL->GetGLTexFormat();\n VERIFY(GLTexFmt == GL_DEPTH_COMPONENT32F || GLTexFmt == GL_DEPTH_COMPONENT16,\n \"Inappropriate internal texture format (\", GLTexFmt,\n \") for depth attachment. GL_DEPTH_COMPONENT32F or GL_DEPTH_COMPONENT16 is expected\");\n }\n#endif\n AttachmentPoint = GL_DEPTH_ATTACHMENT;\n }\n else if (DSVDesc.Format == TEX_FORMAT_D32_FLOAT_S8X24_UINT ||\n DSVDesc.Format == TEX_FORMAT_D24_UNORM_S8_UINT)\n {\n#ifdef DILIGENT_DEBUG\n {\n const auto GLTexFmt = pDepthTexGL->GetGLTexFormat();\n VERIFY(GLTexFmt == GL_DEPTH24_STENCIL8 || GLTexFmt == GL_DEPTH32F_STENCIL8,\n \"Inappropriate internal texture format (\", GLTexFmt,\n \") for depth-stencil attachment. GL_DEPTH24_STENCIL8 or GL_DEPTH32F_STENCIL8 is expected\");\n }\n#endif\n AttachmentPoint = GL_DEPTH_STENCIL_ATTACHMENT;\n }\n else\n {\n UNEXPECTED(GetTextureFormatAttribs(DSVDesc.Format).Name, \" is not valid depth-stencil view format\");\n }\n pDepthTexGL->AttachToFramebuffer(DSVDesc, AttachmentPoint);\n }\n\n \/\/ We now need to set mapping between shader outputs and\n \/\/ color attachments. This largely redundant step is performed\n \/\/ by glDrawBuffers()\n \/\/ clang-format off\n static const GLenum DrawBuffers[] = \n { \n GL_COLOR_ATTACHMENT0, \n GL_COLOR_ATTACHMENT1, \n GL_COLOR_ATTACHMENT2, \n GL_COLOR_ATTACHMENT3,\n GL_COLOR_ATTACHMENT4,\n GL_COLOR_ATTACHMENT5,\n GL_COLOR_ATTACHMENT6,\n GL_COLOR_ATTACHMENT7,\n GL_COLOR_ATTACHMENT8,\n GL_COLOR_ATTACHMENT9,\n GL_COLOR_ATTACHMENT10,\n GL_COLOR_ATTACHMENT11,\n GL_COLOR_ATTACHMENT12,\n GL_COLOR_ATTACHMENT13,\n GL_COLOR_ATTACHMENT14,\n GL_COLOR_ATTACHMENT15\n };\n \/\/ clang-format on\n\n \/\/ The state set by glDrawBuffers() is part of the state of the framebuffer.\n \/\/ So it can be set up once and left it set.\n glDrawBuffers(NumRenderTargets, DrawBuffers);\n CHECK_GL_ERROR(\"Failed to set draw buffers via glDrawBuffers()\");\n\n GLenum Status = glCheckFramebufferStatus(GL_FRAMEBUFFER);\n if (Status != GL_FRAMEBUFFER_COMPLETE)\n {\n const Char* StatusString = \"Unknown\";\n switch (Status)\n {\n \/\/ clang-format off\n case GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT: StatusString = \"GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT\"; break;\n case GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT: StatusString = \"GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT\"; break;\n case GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER: StatusString = \"GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER\"; break;\n case GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER: StatusString = \"GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER\"; break;\n case GL_FRAMEBUFFER_UNSUPPORTED: StatusString = \"GL_FRAMEBUFFER_UNSUPPORTED\"; break;\n case GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE: StatusString = \"GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE\"; break;\n case GL_FRAMEBUFFER_INCOMPLETE_LAYER_TARGETS: StatusString = \"GL_FRAMEBUFFER_INCOMPLETE_LAYER_TARGETS\"; break;\n \/\/ clang-format on\n }\n LOG_ERROR(\"Framebuffer is incomplete. FB status: \", StatusString);\n UNEXPECTED(\"Framebuffer is incomplete\");\n }\n\n auto NewElems = m_Cache.emplace(std::make_pair(Key, std::move(NewFBO)));\n \/\/ New element must be actually inserted\n VERIFY(NewElems.second, \"New element was not inserted\");\n if (Key.DSId != 0)\n m_TexIdToKey.insert(std::make_pair(Key.DSId, Key));\n for (Uint32 rt = 0; rt < NumRenderTargets; ++rt)\n {\n if (Key.RTIds[rt] != 0)\n m_TexIdToKey.insert(std::make_pair(Key.RTIds[rt], Key));\n }\n\n return NewElems.first->second;\n }\n}\n\n} \/\/ namespace Diligent\n<commit_msg>The 'Key.Hash' variable was assigned the same value. ``` if (Key.Hash == 0){ Key.Hash = 0; } ```<commit_after>\/*\n * Copyright 2019-2020 Diligent Graphics LLC\n * Copyright 2015-2019 Egor Yusov\n * \n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * \n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n * In no event and under no legal theory, whether in tort (including negligence), \n * contract, or otherwise, unless required by applicable law (such as deliberate \n * and grossly negligent acts) or agreed to in writing, shall any Contributor be\n * liable for any damages, including any direct, indirect, special, incidental, \n * or consequential damages of any character arising as a result of this License or \n * out of the use or inability to use the software (including but not limited to damages \n * for loss of goodwill, work stoppage, computer failure or malfunction, or any and \n * all other commercial damages or losses), even if such Contributor has been advised \n * of the possibility of such damages.\n *\/\n\n#include \"pch.h\"\n\n#include \"FBOCache.hpp\"\n#include \"RenderDeviceGLImpl.hpp\"\n#include \"TextureBaseGL.hpp\"\n#include \"GLContextState.hpp\"\n\nnamespace Diligent\n{\n\nbool FBOCache::FBOCacheKey::operator==(const FBOCacheKey& Key) const\n{\n if (Hash != 0 && Key.Hash != 0 && Hash != Key.Hash)\n return false;\n\n if (NumRenderTargets != Key.NumRenderTargets)\n return false;\n for (Uint32 rt = 0; rt < NumRenderTargets; ++rt)\n {\n if (RTIds[rt] != Key.RTIds[rt])\n return false;\n if (RTIds[rt])\n {\n if (!(RTVDescs[rt] == Key.RTVDescs[rt]))\n return false;\n }\n }\n if (DSId != Key.DSId)\n return false;\n if (DSId)\n {\n if (!(DSVDesc == Key.DSVDesc))\n return false;\n }\n return true;\n}\n\nstd::size_t FBOCache::FBOCacheKeyHashFunc::operator()(const FBOCacheKey& Key) const\n{\n if (Key.Hash == 0)\n {\n std::hash<TextureViewDesc> TexViewDescHasher;\n HashCombine(Key.Hash, Key.NumRenderTargets);\n for (Uint32 rt = 0; rt < Key.NumRenderTargets; ++rt)\n {\n HashCombine(Key.Hash, Key.RTIds[rt]);\n if (Key.RTIds[rt])\n HashCombine(Key.Hash, TexViewDescHasher(Key.RTVDescs[rt]));\n }\n HashCombine(Key.Hash, Key.DSId);\n if (Key.DSId)\n HashCombine(Key.Hash, TexViewDescHasher(Key.DSVDesc));\n }\n return Key.Hash;\n}\n\n\nFBOCache::FBOCache()\n{\n m_Cache.max_load_factor(0.5f);\n m_TexIdToKey.max_load_factor(0.5f);\n}\n\nFBOCache::~FBOCache()\n{\n VERIFY(m_Cache.empty(), \"FBO cache is not empty. Are there any unreleased objects?\");\n VERIFY(m_TexIdToKey.empty(), \"TexIdToKey cache is not empty.\");\n}\n\nvoid FBOCache::OnReleaseTexture(ITexture* pTexture)\n{\n ThreadingTools::LockHelper CacheLock(m_CacheLockFlag);\n\n auto* pTexGL = ValidatedCast<TextureBaseGL>(pTexture);\n \/\/ Find all FBOs that this texture used in\n auto EqualRange = m_TexIdToKey.equal_range(pTexGL->GetUniqueID());\n for (auto It = EqualRange.first; It != EqualRange.second; ++It)\n {\n m_Cache.erase(It->second);\n }\n m_TexIdToKey.erase(EqualRange.first, EqualRange.second);\n}\n\nconst GLObjectWrappers::GLFrameBufferObj& FBOCache::GetFBO(Uint32 NumRenderTargets,\n TextureViewGLImpl* ppRTVs[],\n TextureViewGLImpl* pDSV,\n GLContextState& ContextState)\n{\n \/\/ Pop null render targets from the end of the list\n while (NumRenderTargets > 0 && ppRTVs[NumRenderTargets - 1] == nullptr)\n --NumRenderTargets;\n\n VERIFY(NumRenderTargets != 0 || pDSV != nullptr, \"At least one render target or a depth-stencil buffer must be provided\");\n\n \/\/ Lock the cache\n ThreadingTools::LockHelper CacheLock(m_CacheLockFlag);\n\n \/\/ Construct the key\n FBOCacheKey Key;\n VERIFY(NumRenderTargets < MAX_RENDER_TARGETS, \"Too many render targets are being set\");\n NumRenderTargets = std::min(NumRenderTargets, MAX_RENDER_TARGETS);\n Key.NumRenderTargets = NumRenderTargets;\n for (Uint32 rt = 0; rt < NumRenderTargets; ++rt)\n {\n auto* pRTView = ppRTVs[rt];\n if (pRTView == nullptr)\n continue;\n\n auto* pColorTexGL = pRTView->GetTexture<TextureBaseGL>();\n pColorTexGL->TextureMemoryBarrier(\n GL_FRAMEBUFFER_BARRIER_BIT, \/\/ Reads and writes via framebuffer object attachments after the\n \/\/ barrier will reflect data written by shaders prior to the barrier.\n \/\/ Additionally, framebuffer writes issued after the barrier will wait\n \/\/ on the completion of all shader writes issued prior to the barrier.\n ContextState);\n\n Key.RTIds[rt] = pColorTexGL->GetUniqueID();\n Key.RTVDescs[rt] = pRTView->GetDesc();\n }\n\n if (pDSV)\n {\n auto* pDepthTexGL = pDSV->GetTexture<TextureBaseGL>();\n pDepthTexGL->TextureMemoryBarrier(GL_FRAMEBUFFER_BARRIER_BIT, ContextState);\n Key.DSId = pDepthTexGL->GetUniqueID();\n Key.DSVDesc = pDSV->GetDesc();\n }\n\n \/\/ Try to find FBO in the map\n auto It = m_Cache.find(Key);\n if (It != m_Cache.end())\n {\n return It->second;\n }\n else\n {\n \/\/ Create a new FBO\n GLObjectWrappers::GLFrameBufferObj NewFBO(true);\n\n ContextState.BindFBO(NewFBO);\n\n \/\/ Initialize the FBO\n for (Uint32 rt = 0; rt < NumRenderTargets; ++rt)\n {\n if (auto* pRTView = ppRTVs[rt])\n {\n const auto& RTVDesc = pRTView->GetDesc();\n auto* pColorTexGL = pRTView->GetTexture<TextureBaseGL>();\n pColorTexGL->AttachToFramebuffer(RTVDesc, GL_COLOR_ATTACHMENT0 + rt);\n }\n }\n\n if (pDSV != nullptr)\n {\n const auto& DSVDesc = pDSV->GetDesc();\n auto* pDepthTexGL = pDSV->GetTexture<TextureBaseGL>();\n GLenum AttachmentPoint = 0;\n if (DSVDesc.Format == TEX_FORMAT_D32_FLOAT ||\n DSVDesc.Format == TEX_FORMAT_D16_UNORM)\n {\n#ifdef DILIGENT_DEBUG\n {\n const auto GLTexFmt = pDepthTexGL->GetGLTexFormat();\n VERIFY(GLTexFmt == GL_DEPTH_COMPONENT32F || GLTexFmt == GL_DEPTH_COMPONENT16,\n \"Inappropriate internal texture format (\", GLTexFmt,\n \") for depth attachment. GL_DEPTH_COMPONENT32F or GL_DEPTH_COMPONENT16 is expected\");\n }\n#endif\n AttachmentPoint = GL_DEPTH_ATTACHMENT;\n }\n else if (DSVDesc.Format == TEX_FORMAT_D32_FLOAT_S8X24_UINT ||\n DSVDesc.Format == TEX_FORMAT_D24_UNORM_S8_UINT)\n {\n#ifdef DILIGENT_DEBUG\n {\n const auto GLTexFmt = pDepthTexGL->GetGLTexFormat();\n VERIFY(GLTexFmt == GL_DEPTH24_STENCIL8 || GLTexFmt == GL_DEPTH32F_STENCIL8,\n \"Inappropriate internal texture format (\", GLTexFmt,\n \") for depth-stencil attachment. GL_DEPTH24_STENCIL8 or GL_DEPTH32F_STENCIL8 is expected\");\n }\n#endif\n AttachmentPoint = GL_DEPTH_STENCIL_ATTACHMENT;\n }\n else\n {\n UNEXPECTED(GetTextureFormatAttribs(DSVDesc.Format).Name, \" is not valid depth-stencil view format\");\n }\n pDepthTexGL->AttachToFramebuffer(DSVDesc, AttachmentPoint);\n }\n\n \/\/ We now need to set mapping between shader outputs and\n \/\/ color attachments. This largely redundant step is performed\n \/\/ by glDrawBuffers()\n \/\/ clang-format off\n static const GLenum DrawBuffers[] = \n { \n GL_COLOR_ATTACHMENT0, \n GL_COLOR_ATTACHMENT1, \n GL_COLOR_ATTACHMENT2, \n GL_COLOR_ATTACHMENT3,\n GL_COLOR_ATTACHMENT4,\n GL_COLOR_ATTACHMENT5,\n GL_COLOR_ATTACHMENT6,\n GL_COLOR_ATTACHMENT7,\n GL_COLOR_ATTACHMENT8,\n GL_COLOR_ATTACHMENT9,\n GL_COLOR_ATTACHMENT10,\n GL_COLOR_ATTACHMENT11,\n GL_COLOR_ATTACHMENT12,\n GL_COLOR_ATTACHMENT13,\n GL_COLOR_ATTACHMENT14,\n GL_COLOR_ATTACHMENT15\n };\n \/\/ clang-format on\n\n \/\/ The state set by glDrawBuffers() is part of the state of the framebuffer.\n \/\/ So it can be set up once and left it set.\n glDrawBuffers(NumRenderTargets, DrawBuffers);\n CHECK_GL_ERROR(\"Failed to set draw buffers via glDrawBuffers()\");\n\n GLenum Status = glCheckFramebufferStatus(GL_FRAMEBUFFER);\n if (Status != GL_FRAMEBUFFER_COMPLETE)\n {\n const Char* StatusString = \"Unknown\";\n switch (Status)\n {\n \/\/ clang-format off\n case GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT: StatusString = \"GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT\"; break;\n case GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT: StatusString = \"GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT\"; break;\n case GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER: StatusString = \"GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER\"; break;\n case GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER: StatusString = \"GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER\"; break;\n case GL_FRAMEBUFFER_UNSUPPORTED: StatusString = \"GL_FRAMEBUFFER_UNSUPPORTED\"; break;\n case GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE: StatusString = \"GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE\"; break;\n case GL_FRAMEBUFFER_INCOMPLETE_LAYER_TARGETS: StatusString = \"GL_FRAMEBUFFER_INCOMPLETE_LAYER_TARGETS\"; break;\n \/\/ clang-format on\n }\n LOG_ERROR(\"Framebuffer is incomplete. FB status: \", StatusString);\n UNEXPECTED(\"Framebuffer is incomplete\");\n }\n\n auto NewElems = m_Cache.emplace(std::make_pair(Key, std::move(NewFBO)));\n \/\/ New element must be actually inserted\n VERIFY(NewElems.second, \"New element was not inserted\");\n if (Key.DSId != 0)\n m_TexIdToKey.insert(std::make_pair(Key.DSId, Key));\n for (Uint32 rt = 0; rt < NumRenderTargets; ++rt)\n {\n if (Key.RTIds[rt] != 0)\n m_TexIdToKey.insert(std::make_pair(Key.RTIds[rt], Key));\n }\n\n return NewElems.first->second;\n }\n}\n\n} \/\/ namespace Diligent\n<|endoftext|>"} {"text":"<commit_before>\/*=========================================================================\n *\n * Copyright NumFOCUS\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0.txt\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *=========================================================================*\/\n\n#include <iostream>\n#include \"itkObject.h\"\n\n#include \"itkCommand.h\"\n#include \"itkTestingMacros.h\"\n\n\n\/\/\n\/\/ This test is for testing the Command Observer functionality of the\n\/\/ itk::Object class.\n\/\/\n\n\nnamespace\n{\n\nunsigned int onAnyCount = 0;\n\nvoid\nonAny(itk::Object *, const itk::EventObject &, void *)\n{\n ++onAnyCount;\n}\n\nvoid\nonAnyInvokeUser(itk::Object * o, const itk::EventObject &, void *)\n{\n static bool invoke = true;\n if (invoke)\n {\n invoke = false;\n o->InvokeEvent(itk::UserEvent());\n invoke = true;\n }\n}\n\nvoid\nonAnyConst(const itk::Object *, const itk::EventObject &, void *)\n{\n ++onAnyCount;\n}\n\nvoid\nonAnyThrow(itk::Object *, const itk::EventObject &, void *)\n{\n throw;\n}\n\nvoid\nonUserRemove(itk::Object * o, const itk::EventObject &, void * data)\n{\n unsigned long idToRemove = *static_cast<unsigned long *>(data);\n o->RemoveObserver(idToRemove);\n}\n\nint\ntestDeleteObserverDuringEvent()\n{\n itk::Object::Pointer o = itk::Object::New();\n\n\n unsigned long idToRemove;\n\n itk::CStyleCommand::Pointer removeCmd = itk::CStyleCommand::New();\n removeCmd->SetCallback(onUserRemove);\n removeCmd->SetObjectName(\"Remove Command\");\n\n itk::CStyleCommand::Pointer cmd = itk::CStyleCommand::New();\n cmd->SetCallback(onAny);\n cmd->SetObjectName(\"Any Command 1\");\n\n \/\/ Add Order 1\n o->AddObserver(itk::UserEvent(), removeCmd);\n idToRemove = o->AddObserver(itk::AnyEvent(), cmd);\n o->AddObserver(itk::AnyEvent(), cmd);\n removeCmd->SetClientData(&idToRemove);\n\n onAnyCount = 0;\n o->InvokeEvent(itk::AnyEvent());\n ITK_TEST_EXPECT_TRUE(onAnyCount == 2);\n\n onAnyCount = 0;\n o->InvokeEvent(itk::UserEvent());\n ITK_TEST_EXPECT_TRUE(onAnyCount == 1);\n\n\n onAnyCount = 0;\n o->InvokeEvent(itk::AnyEvent());\n ITK_TEST_EXPECT_TRUE(onAnyCount == 1);\n\n o->RemoveAllObservers();\n\n \/\/ Add Order 2\n idToRemove = o->AddObserver(itk::AnyEvent(), cmd);\n o->AddObserver(itk::UserEvent(), removeCmd);\n o->AddObserver(itk::AnyEvent(), cmd);\n removeCmd->SetClientData(&idToRemove);\n\n onAnyCount = 0;\n o->InvokeEvent(itk::AnyEvent());\n ITK_TEST_EXPECT_TRUE(onAnyCount == 2);\n\n onAnyCount = 0;\n o->InvokeEvent(itk::UserEvent());\n ITK_TEST_EXPECT_TRUE(onAnyCount == 2);\n\n\n onAnyCount = 0;\n o->InvokeEvent(itk::AnyEvent());\n ITK_TEST_EXPECT_TRUE(onAnyCount == 1);\n\n o->RemoveAllObservers();\n\n \/\/ Add Order 3\n idToRemove = o->AddObserver(itk::AnyEvent(), cmd);\n o->AddObserver(itk::AnyEvent(), cmd);\n o->AddObserver(itk::UserEvent(), removeCmd);\n removeCmd->SetClientData(&idToRemove);\n\n onAnyCount = 0;\n o->InvokeEvent(itk::AnyEvent());\n ITK_TEST_EXPECT_TRUE(onAnyCount == 2);\n\n onAnyCount = 0;\n o->InvokeEvent(itk::UserEvent());\n ITK_TEST_EXPECT_TRUE(onAnyCount == 2);\n\n\n onAnyCount = 0;\n o->InvokeEvent(itk::AnyEvent());\n ITK_TEST_EXPECT_TRUE(onAnyCount == 1);\n\n o->RemoveAllObservers();\n\n \/\/ Add Order 4\n o->AddObserver(itk::AnyEvent(), cmd);\n o->AddObserver(itk::UserEvent(), removeCmd);\n idToRemove = o->AddObserver(itk::AnyEvent(), cmd);\n removeCmd->SetClientData(&idToRemove);\n\n onAnyCount = 0;\n o->InvokeEvent(itk::AnyEvent());\n ITK_TEST_EXPECT_TRUE(onAnyCount == 2);\n\n onAnyCount = 0;\n o->InvokeEvent(itk::UserEvent());\n ITK_TEST_EXPECT_TRUE(onAnyCount == 1);\n\n\n onAnyCount = 0;\n o->InvokeEvent(itk::AnyEvent());\n ITK_TEST_EXPECT_TRUE(onAnyCount == 1);\n\n o->RemoveAllObservers();\n\n\n return EXIT_SUCCESS;\n}\n\n\nint\ntestCommandConstObject()\n{\n\n itk::Object::Pointer o = itk::Object::New();\n itk::Object::ConstPointer co = o;\n\n itk::CStyleCommand::Pointer cmd = itk::CStyleCommand::New();\n cmd->SetConstCallback(onAnyConst);\n cmd->SetObjectName(\"Any Command 1\");\n\n itk::CStyleCommand::Pointer removeCmd = itk::CStyleCommand::New();\n removeCmd->SetCallback(onUserRemove);\n removeCmd->SetObjectName(\"Remove Command\");\n\n co->AddObserver(itk::AnyEvent(), cmd);\n ITK_TEST_EXPECT_TRUE(co->HasObserver(itk::AnyEvent()));\n\n \/\/ the constant command doesn't get executed from the non-const\n \/\/ invocation\n onAnyCount = 0;\n o->InvokeEvent(itk::AnyEvent());\n ITK_TEST_EXPECT_TRUE(onAnyCount == 0);\n\n onAnyCount = 0;\n co->InvokeEvent(itk::AnyEvent());\n ITK_TEST_EXPECT_TRUE(onAnyCount == 1);\n\n return EXIT_SUCCESS;\n}\n\n\nint\ntestCommandRecursiveObject()\n{\n \/\/ this test has an command invoking another event, while removing a\n \/\/ a Command.\n \/\/ This is a super-mean test that is not likely to really be used.\n\n itk::Object::Pointer o = itk::Object::New();\n itk::Object::ConstPointer co = o;\n\n unsigned long idToRemove;\n\n itk::CStyleCommand::Pointer cmd = itk::CStyleCommand::New();\n cmd->SetCallback(onAny);\n cmd->SetObjectName(\"Any Command 1\");\n\n itk::CStyleCommand::Pointer removeCmd = itk::CStyleCommand::New();\n removeCmd->SetCallback(onUserRemove);\n removeCmd->SetObjectName(\"Remove Command\");\n\n itk::CStyleCommand::Pointer cmdInvoke = itk::CStyleCommand::New();\n cmdInvoke->SetCallback(onAnyInvokeUser);\n cmdInvoke->SetObjectName(\"Any Invoke User\");\n\n \/\/ On 1 Remove 1\n idToRemove = o->AddObserver(itk::AnyEvent(), cmdInvoke);\n o->AddObserver(itk::UserEvent(), removeCmd);\n o->AddObserver(itk::AnyEvent(), cmd);\n removeCmd->SetClientData(&idToRemove);\n\n onAnyCount = 0;\n o->InvokeEvent(itk::AnyEvent());\n ITK_TEST_EXPECT_TRUE(onAnyCount == 2);\n\n o->RemoveAllObservers();\n\n \/\/ On 1 Remove 2\n o->AddObserver(itk::AnyEvent(), cmdInvoke);\n idToRemove = o->AddObserver(itk::UserEvent(), removeCmd);\n o->AddObserver(itk::AnyEvent(), cmd);\n removeCmd->SetClientData(&idToRemove);\n\n onAnyCount = 0;\n o->InvokeEvent(itk::AnyEvent());\n ITK_TEST_EXPECT_TRUE(onAnyCount == 2);\n\n o->RemoveAllObservers();\n\n \/\/ On 1 Remove 3\n o->AddObserver(itk::AnyEvent(), cmdInvoke);\n o->AddObserver(itk::UserEvent(), removeCmd);\n idToRemove = o->AddObserver(itk::AnyEvent(), cmd);\n removeCmd->SetClientData(&idToRemove);\n\n onAnyCount = 0;\n o->InvokeEvent(itk::AnyEvent());\n ITK_TEST_EXPECT_TRUE(onAnyCount == 0);\n\n return EXIT_SUCCESS;\n}\n\n\nbool\ntestDeleteEventThrow()\n{\n \/\/ check the case where an exception in thrown in the DeleteEvent\n itk::Object::Pointer o = itk::Object::New();\n\n itk::CStyleCommand::Pointer cmd = itk::CStyleCommand::New();\n cmd->SetCallback(onAnyThrow);\n\n o->AddObserver(itk::DeleteEvent(), cmd);\n return EXIT_SUCCESS;\n}\n\nint\ntestLambdaCommand()\n{\n \/\/ check the case where an exception in thrown in the DeleteEvent\n itk::Object::Pointer o = itk::Object::New();\n\n int cnt = 0;\n o->AddObserver(itk::AnyEvent(), [&cnt](const itk::EventObject &) { ++cnt; });\n\n auto & objRef = *o.GetPointer();\n o->AddObserver(itk::AnyEvent(), [&objRef](const itk::EventObject & event) {\n std::cout << \"Object: \" << objRef.GetNameOfClass() << \" Event: \" << event << std::endl;\n });\n\n o->InvokeEvent(itk::AnyEvent());\n\n ITK_TEST_EXPECT_EQUAL(1, cnt);\n\n return EXIT_SUCCESS;\n}\n\n\n} \/\/ end namespace\n\n\nint\nitkCommandObserverObjectTest(int, char *[])\n{\n bool ret = true;\n\n ret &= (testDeleteObserverDuringEvent() == EXIT_SUCCESS);\n ret &= (testCommandConstObject() == EXIT_SUCCESS);\n ret &= (testCommandRecursiveObject() == EXIT_SUCCESS);\n ret &= (testDeleteEventThrow() == EXIT_SUCCESS);\n ret &= (testLambdaCommand() == EXIT_SUCCESS);\n\n return ret ? EXIT_SUCCESS : EXIT_FAILURE;\n}\n<commit_msg>BUG: ASAN identified use after delete bug<commit_after>\/*=========================================================================\n *\n * Copyright NumFOCUS\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0.txt\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *=========================================================================*\/\n\n#include <iostream>\n#include \"itkObject.h\"\n\n#include \"itkCommand.h\"\n#include \"itkTestingMacros.h\"\n\n\n\/\/\n\/\/ This test is for testing the Command Observer functionality of the\n\/\/ itk::Object class.\n\/\/\n\n\nnamespace\n{\n\nunsigned int onAnyCount = 0;\n\nvoid\nonAny(itk::Object *, const itk::EventObject &, void *)\n{\n ++onAnyCount;\n}\n\nvoid\nonAnyInvokeUser(itk::Object * o, const itk::EventObject &, void *)\n{\n static bool invoke = true;\n if (invoke)\n {\n invoke = false;\n o->InvokeEvent(itk::UserEvent());\n invoke = true;\n }\n}\n\nvoid\nonAnyConst(const itk::Object *, const itk::EventObject &, void *)\n{\n ++onAnyCount;\n}\n\nvoid\nonAnyThrow(itk::Object *, const itk::EventObject &, void *)\n{\n throw;\n}\n\nvoid\nonUserRemove(itk::Object * o, const itk::EventObject &, void * data)\n{\n unsigned long idToRemove = *static_cast<unsigned long *>(data);\n o->RemoveObserver(idToRemove);\n}\n\nint\ntestDeleteObserverDuringEvent()\n{\n itk::Object::Pointer o = itk::Object::New();\n\n\n unsigned long idToRemove;\n\n itk::CStyleCommand::Pointer removeCmd = itk::CStyleCommand::New();\n removeCmd->SetCallback(onUserRemove);\n removeCmd->SetObjectName(\"Remove Command\");\n\n itk::CStyleCommand::Pointer cmd = itk::CStyleCommand::New();\n cmd->SetCallback(onAny);\n cmd->SetObjectName(\"Any Command 1\");\n\n \/\/ Add Order 1\n o->AddObserver(itk::UserEvent(), removeCmd);\n idToRemove = o->AddObserver(itk::AnyEvent(), cmd);\n o->AddObserver(itk::AnyEvent(), cmd);\n removeCmd->SetClientData(&idToRemove);\n\n onAnyCount = 0;\n o->InvokeEvent(itk::AnyEvent());\n ITK_TEST_EXPECT_TRUE(onAnyCount == 2);\n\n onAnyCount = 0;\n o->InvokeEvent(itk::UserEvent());\n ITK_TEST_EXPECT_TRUE(onAnyCount == 1);\n\n\n onAnyCount = 0;\n o->InvokeEvent(itk::AnyEvent());\n ITK_TEST_EXPECT_TRUE(onAnyCount == 1);\n\n o->RemoveAllObservers();\n\n \/\/ Add Order 2\n idToRemove = o->AddObserver(itk::AnyEvent(), cmd);\n o->AddObserver(itk::UserEvent(), removeCmd);\n o->AddObserver(itk::AnyEvent(), cmd);\n removeCmd->SetClientData(&idToRemove);\n\n onAnyCount = 0;\n o->InvokeEvent(itk::AnyEvent());\n ITK_TEST_EXPECT_TRUE(onAnyCount == 2);\n\n onAnyCount = 0;\n o->InvokeEvent(itk::UserEvent());\n ITK_TEST_EXPECT_TRUE(onAnyCount == 2);\n\n\n onAnyCount = 0;\n o->InvokeEvent(itk::AnyEvent());\n ITK_TEST_EXPECT_TRUE(onAnyCount == 1);\n\n o->RemoveAllObservers();\n\n \/\/ Add Order 3\n idToRemove = o->AddObserver(itk::AnyEvent(), cmd);\n o->AddObserver(itk::AnyEvent(), cmd);\n o->AddObserver(itk::UserEvent(), removeCmd);\n removeCmd->SetClientData(&idToRemove);\n\n onAnyCount = 0;\n o->InvokeEvent(itk::AnyEvent());\n ITK_TEST_EXPECT_TRUE(onAnyCount == 2);\n\n onAnyCount = 0;\n o->InvokeEvent(itk::UserEvent());\n ITK_TEST_EXPECT_TRUE(onAnyCount == 2);\n\n\n onAnyCount = 0;\n o->InvokeEvent(itk::AnyEvent());\n ITK_TEST_EXPECT_TRUE(onAnyCount == 1);\n\n o->RemoveAllObservers();\n\n \/\/ Add Order 4\n o->AddObserver(itk::AnyEvent(), cmd);\n o->AddObserver(itk::UserEvent(), removeCmd);\n idToRemove = o->AddObserver(itk::AnyEvent(), cmd);\n removeCmd->SetClientData(&idToRemove);\n\n onAnyCount = 0;\n o->InvokeEvent(itk::AnyEvent());\n ITK_TEST_EXPECT_TRUE(onAnyCount == 2);\n\n onAnyCount = 0;\n o->InvokeEvent(itk::UserEvent());\n ITK_TEST_EXPECT_TRUE(onAnyCount == 1);\n\n\n onAnyCount = 0;\n o->InvokeEvent(itk::AnyEvent());\n ITK_TEST_EXPECT_TRUE(onAnyCount == 1);\n\n o->RemoveAllObservers();\n\n\n return EXIT_SUCCESS;\n}\n\n\nint\ntestCommandConstObject()\n{\n\n itk::Object::Pointer o = itk::Object::New();\n itk::Object::ConstPointer co = o;\n\n itk::CStyleCommand::Pointer cmd = itk::CStyleCommand::New();\n cmd->SetConstCallback(onAnyConst);\n cmd->SetObjectName(\"Any Command 1\");\n\n itk::CStyleCommand::Pointer removeCmd = itk::CStyleCommand::New();\n removeCmd->SetCallback(onUserRemove);\n removeCmd->SetObjectName(\"Remove Command\");\n\n co->AddObserver(itk::AnyEvent(), cmd);\n ITK_TEST_EXPECT_TRUE(co->HasObserver(itk::AnyEvent()));\n\n \/\/ the constant command doesn't get executed from the non-const\n \/\/ invocation\n onAnyCount = 0;\n o->InvokeEvent(itk::AnyEvent());\n ITK_TEST_EXPECT_TRUE(onAnyCount == 0);\n\n onAnyCount = 0;\n co->InvokeEvent(itk::AnyEvent());\n ITK_TEST_EXPECT_TRUE(onAnyCount == 1);\n\n return EXIT_SUCCESS;\n}\n\n\nint\ntestCommandRecursiveObject()\n{\n \/\/ this test has an command invoking another event, while removing a\n \/\/ a Command.\n \/\/ This is a super-mean test that is not likely to really be used.\n\n itk::Object::Pointer o = itk::Object::New();\n itk::Object::ConstPointer co = o;\n\n unsigned long idToRemove;\n\n itk::CStyleCommand::Pointer cmd = itk::CStyleCommand::New();\n cmd->SetCallback(onAny);\n cmd->SetObjectName(\"Any Command 1\");\n\n itk::CStyleCommand::Pointer removeCmd = itk::CStyleCommand::New();\n removeCmd->SetCallback(onUserRemove);\n removeCmd->SetObjectName(\"Remove Command\");\n\n itk::CStyleCommand::Pointer cmdInvoke = itk::CStyleCommand::New();\n cmdInvoke->SetCallback(onAnyInvokeUser);\n cmdInvoke->SetObjectName(\"Any Invoke User\");\n\n \/\/ On 1 Remove 1\n idToRemove = o->AddObserver(itk::AnyEvent(), cmdInvoke);\n o->AddObserver(itk::UserEvent(), removeCmd);\n o->AddObserver(itk::AnyEvent(), cmd);\n removeCmd->SetClientData(&idToRemove);\n\n onAnyCount = 0;\n o->InvokeEvent(itk::AnyEvent());\n ITK_TEST_EXPECT_TRUE(onAnyCount == 2);\n\n o->RemoveAllObservers();\n\n \/\/ On 1 Remove 2\n o->AddObserver(itk::AnyEvent(), cmdInvoke);\n idToRemove = o->AddObserver(itk::UserEvent(), removeCmd);\n o->AddObserver(itk::AnyEvent(), cmd);\n removeCmd->SetClientData(&idToRemove);\n\n onAnyCount = 0;\n o->InvokeEvent(itk::AnyEvent());\n ITK_TEST_EXPECT_TRUE(onAnyCount == 2);\n\n o->RemoveAllObservers();\n\n \/\/ On 1 Remove 3\n o->AddObserver(itk::AnyEvent(), cmdInvoke);\n o->AddObserver(itk::UserEvent(), removeCmd);\n idToRemove = o->AddObserver(itk::AnyEvent(), cmd);\n removeCmd->SetClientData(&idToRemove);\n\n onAnyCount = 0;\n o->InvokeEvent(itk::AnyEvent());\n ITK_TEST_EXPECT_TRUE(onAnyCount == 0);\n\n return EXIT_SUCCESS;\n}\n\n\nbool\ntestDeleteEventThrow()\n{\n \/\/ check the case where an exception in thrown in the DeleteEvent\n itk::Object::Pointer o = itk::Object::New();\n\n itk::CStyleCommand::Pointer cmd = itk::CStyleCommand::New();\n cmd->SetCallback(onAnyThrow);\n\n o->AddObserver(itk::DeleteEvent(), cmd);\n return EXIT_SUCCESS;\n}\n\nint\ntestLambdaCommand()\n{\n \/\/ NOTE: cnt needs to be defined BEFORE \"o\" because it MUST exist when the \"DeleteEvent()\" is causes the\n \/\/ FIRST OBSERVER LAMBDA to be called. If 'cnt' is defined after 'o' then when the scope\n \/\/ ends, 'cnt' is deleted first, followed by deleting 'o' which tries to increment 'cnt' when\n \/\/ the 'DeleteEvent' tries to be processed.\n int cnt = 0;\n int name_of_class_cnt = 0;\n\n {\n \/\/ check the case where an exception in thrown in the DeleteEvent\n itk::Object::Pointer o = itk::Object::New();\n \/*----- FIRST OBSERVER LAMBDA *\/\n o->AddObserver(itk::AnyEvent(), [&cnt](const itk::EventObject &) { ++cnt; });\n\n auto & objRef = *o.GetPointer();\n \/*----- SECOND OBSERVER LAMBDA *\/\n o->AddObserver(itk::AnyEvent(), [&objRef, &name_of_class_cnt](const itk::EventObject & event) {\n ++name_of_class_cnt;\n std::cout << \"Ivocation # \" << name_of_class_cnt << \"\\nObject: \" << objRef.GetNameOfClass() << \" Event: \" << event\n << std::endl;\n });\n\n o->InvokeEvent(itk::AnyEvent());\n ITK_TEST_EXPECT_EQUAL(1, cnt);\n ITK_TEST_EXPECT_EQUAL(1, name_of_class_cnt);\n\n } \/\/ A DeleteEvent is called here! as object \"o\" is deleted\n ITK_TEST_EXPECT_EQUAL(2, cnt); \/\/ Verify that cnt really was incremented during DeleteEvent!\n ITK_TEST_EXPECT_EQUAL(2, name_of_class_cnt);\n return EXIT_SUCCESS;\n}\n\n\n} \/\/ end namespace\n\n\nint\nitkCommandObserverObjectTest(int, char *[])\n{\n bool ret = true;\n\n ret &= (testDeleteObserverDuringEvent() == EXIT_SUCCESS);\n ret &= (testCommandConstObject() == EXIT_SUCCESS);\n ret &= (testCommandRecursiveObject() == EXIT_SUCCESS);\n ret &= (testDeleteEventThrow() == EXIT_SUCCESS);\n ret &= (testLambdaCommand() == EXIT_SUCCESS);\n\n return ret ? EXIT_SUCCESS : EXIT_FAILURE;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*===================================================================\n\nThe Medical Imaging Interaction Toolkit (MITK)\n\nCopyright (c) German Cancer Research Center,\nDivision of Medical and Biological Informatics.\nAll rights reserved.\n\nThis software is distributed WITHOUT ANY WARRANTY; without\neven the implied warranty of MERCHANTABILITY or FITNESS FOR\nA PARTICULAR PURPOSE.\n\nSee LICENSE.txt or http:\/\/www.mitk.org for details.\n\n===================================================================*\/\n\n#include \"QmitkNavigationToolCreationWidget.h\"\n\n\/\/mitk headers\n#include \"mitkTrackingTypes.h\"\n#include <mitkSTLFileReader.h>\n#include <mitkSurface.h>\n#include \"mitkNavigationData.h\"\n#include \"mitkRenderingManager.h\"\n\n\/\/qt headers\n#include <qfiledialog.h>\n#include <qmessagebox.h>\n#include <QDialog>\n\n\/\/poco headers\n#include <Poco\/Path.h>\n\n\/\/ vtk\n#include <vtkSphereSource.h>\n#include \"vtkConeSource.h\"\n\nconst std::string QmitkNavigationToolCreationWidget::VIEW_ID = \"org.mitk.views.navigationtoolcreationwizardwidget\";\n\nQmitkNavigationToolCreationWidget::QmitkNavigationToolCreationWidget(QWidget* parent, Qt::WindowFlags f)\n: QWidget(parent, f)\n{\n m_Controls = NULL;\n m_AdvancedWidget = new QmitkNavigationToolCreationAdvancedWidget(this);\n m_AdvancedWidget->setWindowFlags(Qt::Tool | Qt::WindowStaysOnTopHint);\n m_AdvancedWidget->setWindowTitle(\"Tool Creation Advanced Options\");\n m_AdvancedWidget->setModal(false);\n CreateQtPartControl(this);\n CreateConnections();\n}\n\nQmitkNavigationToolCreationWidget::~QmitkNavigationToolCreationWidget()\n{\n delete m_AdvancedWidget;\n}\n\nvoid QmitkNavigationToolCreationWidget::CreateQtPartControl(QWidget *parent)\n{\n if (!m_Controls)\n {\n \/\/ create GUI widgets\n m_Controls = new Ui::QmitkNavigationToolCreationWidgetControls;\n m_Controls->setupUi(parent);\n }\n}\n\nvoid QmitkNavigationToolCreationWidget::CreateConnections()\n{\n if ( m_Controls )\n {\n connect( (QObject*)(m_Controls->m_cancel), SIGNAL(clicked()), this, SLOT(OnCancel()) );\n connect( (QObject*)(m_Controls->m_finished), SIGNAL(clicked()), this, SLOT(OnFinished()) );\n connect( (QObject*)(m_Controls->m_LoadSurface), SIGNAL(clicked()), this, SLOT(OnLoadSurface()) );\n connect( (QObject*)(m_Controls->m_LoadCalibrationFile), SIGNAL(clicked()), this, SLOT(OnLoadCalibrationFile()) );\n connect( (QObject*)(m_Controls->m_ShowAdvancedOptionsPB), SIGNAL(toggled(bool)), this, SLOT(OnShowAdvancedOptions(bool)) );\n connect( (QObject*)(m_AdvancedWidget), SIGNAL(DialogCloseRequested()), this, SLOT(OnProcessDialogCloseRequest()) );\n connect( (QObject*)(m_AdvancedWidget), SIGNAL(RetrieveDataForManualToolTipManipulation()), this, SLOT(OnRetrieveDataForManualTooltipManipulation()) );\n }\n}\n\nvoid QmitkNavigationToolCreationWidget::Initialize(mitk::DataStorage* dataStorage, std::string supposedIdentifier, std::string supposedName)\n{\n m_DataStorage = dataStorage;\n\n \/\/initialize UI components\n m_Controls->m_SurfaceChooser->SetDataStorage(m_DataStorage);\n m_Controls->m_SurfaceChooser->SetAutoSelectNewItems(true);\n m_Controls->m_SurfaceChooser->SetPredicate(mitk::NodePredicateDataType::New(\"Surface\"));\n\n \/\/set default data\n m_Controls->m_ToolNameEdit->setText(supposedName.c_str());\n m_Controls->m_CalibrationFileName->setText(\"none\");\n m_Controls->m_Surface_Use_Sphere->setChecked(true);\n m_AdvancedWidget->SetDataStorage(m_DataStorage);\n\n}\n\nvoid QmitkNavigationToolCreationWidget::SetTrackingDeviceType(mitk::TrackingDeviceType type, bool changeable)\n{\n switch(type)\n {\n case mitk::NDIAurora:\n m_Controls->m_TrackingDeviceTypeChooser->setCurrentIndex(0);break;\n case mitk::NDIPolaris:\n m_Controls->m_TrackingDeviceTypeChooser->setCurrentIndex(1);break;\n case mitk::ClaronMicron:\n m_Controls->m_TrackingDeviceTypeChooser->setCurrentIndex(2);break;\n default:\n m_Controls->m_TrackingDeviceTypeChooser->setCurrentIndex(0);\n }\n m_Controls->m_TrackingDeviceTypeChooser->setEnabled(changeable);\n}\n\nmitk::NavigationTool::Pointer QmitkNavigationToolCreationWidget::GetCreatedTool()\n{\n return m_CreatedTool;\n}\n\n\/\/##################################################################################\n\/\/############################## slots ############################\n\/\/##################################################################################\n\nvoid QmitkNavigationToolCreationWidget::OnFinished()\n{\n \/\/here we create a new tool\n m_CreatedTool = mitk::NavigationTool::New();\n\n \/\/create DataNode...\n mitk::DataNode::Pointer newNode = mitk::DataNode::New();\n if(m_Controls->m_Surface_Use_Sphere->isChecked())\n {\n \/\/create small sphere and use it as surface\n mitk::Surface::Pointer mySphere = mitk::Surface::New();\n vtkConeSource *vtkData = vtkConeSource::New();\n vtkData->SetAngle(5.0);\n vtkData->SetResolution(50);\n vtkData->SetHeight(6.0f);\n vtkData->SetRadius(2.0f);\n vtkData->SetCenter(0.0, 0.0, 0.0);\n vtkData->Update();\n mySphere->SetVtkPolyData(vtkData->GetOutput());\n vtkData->Delete();\n newNode->SetData(mySphere);\n }\n else\n {\n newNode->SetData(m_Controls->m_SurfaceChooser->GetSelectedNode()->GetData());\n }\n newNode->SetName(m_Controls->m_ToolNameEdit->text().toLatin1());\n\n m_CreatedTool->SetDataNode(newNode);\n\n \/\/fill NavigationTool object\n m_CreatedTool->SetCalibrationFile(m_Controls->m_CalibrationFileName->text().toAscii().data());\n m_CreatedTool->SetIdentifier(m_Controls->m_IdentifierEdit->text().toAscii().data());\n m_CreatedTool->SetSerialNumber(m_Controls->m_SerialNumberEdit->text().toAscii().data());\n\n \/\/Tracking Device\n if (m_Controls->m_TrackingDeviceTypeChooser->currentText()==\"NDI Aurora\") m_CreatedTool->SetTrackingDeviceType(mitk::NDIAurora);\n else if (m_Controls->m_TrackingDeviceTypeChooser->currentText()==\"NDI Polaris\") m_CreatedTool->SetTrackingDeviceType(mitk::NDIPolaris);\n else if (m_Controls->m_TrackingDeviceTypeChooser->currentText()==\"Claron Technology Micron Tracker\") m_CreatedTool->SetTrackingDeviceType(mitk::ClaronMicron);\n else m_CreatedTool->SetTrackingDeviceType(mitk::TrackingSystemNotSpecified);\n\n \/\/ToolType\n if (m_Controls->m_ToolTypeChooser->currentText()==\"Instrument\") m_CreatedTool->SetType(mitk::NavigationTool::Instrument);\n else if (m_Controls->m_ToolTypeChooser->currentText()==\"Fiducial\") m_CreatedTool->SetType(mitk::NavigationTool::Fiducial);\n else if (m_Controls->m_ToolTypeChooser->currentText()==\"Skinmarker\") m_CreatedTool->SetType(mitk::NavigationTool::Skinmarker);\n else m_CreatedTool->SetType(mitk::NavigationTool::Unknown);\n\n mitk::NavigationData::Pointer tempND = mitk::NavigationData::New(m_AdvancedWidget->GetManipulatedToolTip());\n m_CreatedTool->SetToolTipOrientation(tempND->GetOrientation());\n m_CreatedTool->SetToolTipPosition(tempND->GetPosition());\n\n emit NavigationToolFinished();\n}\n\nvoid QmitkNavigationToolCreationWidget::OnCancel()\n{\n m_CreatedTool = NULL;\n\n emit Canceled();\n}\n\nvoid QmitkNavigationToolCreationWidget::OnLoadSurface()\n{\n std::string filename = QFileDialog::getOpenFileName(NULL,tr(\"Open Surface\"), \"\/\", \"*.stl\").toLatin1().data();\n mitk::STLFileReader::Pointer stlReader = mitk::STLFileReader::New();\n try\n {\n stlReader->SetFileName( filename.c_str() );\n stlReader->Update();\n }\n catch (...)\n {\n }\n\n if ( stlReader->GetOutput() == NULL );\n else\n {\n mitk::DataNode::Pointer newNode = mitk::DataNode::New();\n newNode->SetName(filename);\n newNode->SetData(stlReader->GetOutput());\n m_DataStorage->Add(newNode);\n }\n}\n\nvoid QmitkNavigationToolCreationWidget::OnLoadCalibrationFile()\n{\n m_Controls->m_CalibrationFileName->setText(QFileDialog::getOpenFileName(NULL,tr(\"Open Calibration File\"), \"\/\", \"*.*\"));\n}\n\nvoid QmitkNavigationToolCreationWidget::SetDefaultData(mitk::NavigationTool::Pointer DefaultTool)\n{\n m_Controls->m_ToolNameEdit->setText(QString(DefaultTool->GetDataNode()->GetName().c_str()));\n m_Controls->m_IdentifierEdit->setText(QString(DefaultTool->GetIdentifier().c_str()));\n m_Controls->m_SerialNumberEdit->setText(QString(DefaultTool->GetSerialNumber().c_str()));\n m_AdvancedWidget->SetDefaultTooltip( DefaultTool->GetToolTipTransform() );\n switch(DefaultTool->GetTrackingDeviceType())\n {\n case mitk::NDIAurora:\n m_Controls->m_TrackingDeviceTypeChooser->setCurrentIndex(0);break;\n case mitk::NDIPolaris:\n m_Controls->m_TrackingDeviceTypeChooser->setCurrentIndex(1);break;\n case mitk::ClaronMicron:\n m_Controls->m_TrackingDeviceTypeChooser->setCurrentIndex(2);break;\n default:\n m_Controls->m_TrackingDeviceTypeChooser->setCurrentIndex(0);\n }\n m_Controls->m_CalibrationFileName->setText(QString(DefaultTool->GetCalibrationFile().c_str()));\n m_Controls->m_Surface_Use_Other->setChecked(true);\n switch(DefaultTool->GetType())\n {\n case mitk::NavigationTool::Instrument:\n m_Controls->m_ToolTypeChooser->setCurrentIndex(0); break;\n case mitk::NavigationTool::Fiducial:\n m_Controls->m_ToolTypeChooser->setCurrentIndex(1); break;\n case mitk::NavigationTool::Skinmarker:\n m_Controls->m_ToolTypeChooser->setCurrentIndex(2); break;\n case mitk::NavigationTool::Unknown:\n m_Controls->m_ToolTypeChooser->setCurrentIndex(3); break;\n }\n\n m_Controls->m_SurfaceChooser->SetSelectedNode(DefaultTool->GetDataNode());\n\n}\n\n\n\n\/\/##################################################################################\n\/\/############################## internal help methods #############################\n\/\/##################################################################################\nvoid QmitkNavigationToolCreationWidget::MessageBox(std::string s)\n{\n QMessageBox msgBox;\n msgBox.setText(s.c_str());\n msgBox.exec();\n}\n\nvoid QmitkNavigationToolCreationWidget::OnShowAdvancedOptions(bool state)\n{\n if(state)\n {\n m_AdvancedWidget->show();\n m_AdvancedWidget->SetDefaultTooltip(m_AdvancedWidget->GetManipulatedToolTip()); \/\/use the last one, if there is one\n m_AdvancedWidget->ReInitialize();\n\n \/\/ reinit the views with the new nodes\n mitk::DataStorage::SetOfObjects::ConstPointer rs = m_DataStorage->GetAll();\n mitk::TimeGeometry::Pointer bounds = m_DataStorage->ComputeBoundingGeometry3D(rs, \"visible\"); \/\/ initialize the views to the bounding geometry\n mitk::RenderingManager::GetInstance()->InitializeViews(bounds);\n }\n else\n {\n m_AdvancedWidget->hide();\n }\n}\n\nvoid QmitkNavigationToolCreationWidget::OnProcessDialogCloseRequest()\n{\n m_AdvancedWidget->hide();\n m_Controls->m_ShowAdvancedOptionsPB->setChecked(false);\n}\n\nvoid QmitkNavigationToolCreationWidget::OnRetrieveDataForManualTooltipManipulation()\n{\n if(m_Controls->m_Surface_Use_Sphere->isChecked())\n {\n m_AdvancedWidget->SetToolTipSurface(true);\n }\n else\n {\n m_AdvancedWidget->SetToolTipSurface(false,\n dynamic_cast<mitk::DataNode*>(m_Controls->m_SurfaceChooser->GetSelectedNode().GetPointer()));\n }\n}\n<commit_msg>Filter extended to work on linux, too.<commit_after>\/*===================================================================\n\nThe Medical Imaging Interaction Toolkit (MITK)\n\nCopyright (c) German Cancer Research Center,\nDivision of Medical and Biological Informatics.\nAll rights reserved.\n\nThis software is distributed WITHOUT ANY WARRANTY; without\neven the implied warranty of MERCHANTABILITY or FITNESS FOR\nA PARTICULAR PURPOSE.\n\nSee LICENSE.txt or http:\/\/www.mitk.org for details.\n\n===================================================================*\/\n\n#include \"QmitkNavigationToolCreationWidget.h\"\n\n\/\/mitk headers\n#include \"mitkTrackingTypes.h\"\n#include <mitkSTLFileReader.h>\n#include <mitkSurface.h>\n#include \"mitkNavigationData.h\"\n#include \"mitkRenderingManager.h\"\n\n\/\/qt headers\n#include <qfiledialog.h>\n#include <qmessagebox.h>\n#include <QDialog>\n\n\/\/poco headers\n#include <Poco\/Path.h>\n\n\/\/ vtk\n#include <vtkSphereSource.h>\n#include \"vtkConeSource.h\"\n\nconst std::string QmitkNavigationToolCreationWidget::VIEW_ID = \"org.mitk.views.navigationtoolcreationwizardwidget\";\n\nQmitkNavigationToolCreationWidget::QmitkNavigationToolCreationWidget(QWidget* parent, Qt::WindowFlags f)\n: QWidget(parent, f)\n{\n m_Controls = NULL;\n m_AdvancedWidget = new QmitkNavigationToolCreationAdvancedWidget(this);\n m_AdvancedWidget->setWindowFlags(Qt::Tool | Qt::WindowStaysOnTopHint);\n m_AdvancedWidget->setWindowTitle(\"Tool Creation Advanced Options\");\n m_AdvancedWidget->setModal(false);\n CreateQtPartControl(this);\n CreateConnections();\n}\n\nQmitkNavigationToolCreationWidget::~QmitkNavigationToolCreationWidget()\n{\n delete m_AdvancedWidget;\n}\n\nvoid QmitkNavigationToolCreationWidget::CreateQtPartControl(QWidget *parent)\n{\n if (!m_Controls)\n {\n \/\/ create GUI widgets\n m_Controls = new Ui::QmitkNavigationToolCreationWidgetControls;\n m_Controls->setupUi(parent);\n }\n}\n\nvoid QmitkNavigationToolCreationWidget::CreateConnections()\n{\n if ( m_Controls )\n {\n connect( (QObject*)(m_Controls->m_cancel), SIGNAL(clicked()), this, SLOT(OnCancel()) );\n connect( (QObject*)(m_Controls->m_finished), SIGNAL(clicked()), this, SLOT(OnFinished()) );\n connect( (QObject*)(m_Controls->m_LoadSurface), SIGNAL(clicked()), this, SLOT(OnLoadSurface()) );\n connect( (QObject*)(m_Controls->m_LoadCalibrationFile), SIGNAL(clicked()), this, SLOT(OnLoadCalibrationFile()) );\n connect( (QObject*)(m_Controls->m_ShowAdvancedOptionsPB), SIGNAL(toggled(bool)), this, SLOT(OnShowAdvancedOptions(bool)) );\n connect( (QObject*)(m_AdvancedWidget), SIGNAL(DialogCloseRequested()), this, SLOT(OnProcessDialogCloseRequest()) );\n connect( (QObject*)(m_AdvancedWidget), SIGNAL(RetrieveDataForManualToolTipManipulation()), this, SLOT(OnRetrieveDataForManualTooltipManipulation()) );\n }\n}\n\nvoid QmitkNavigationToolCreationWidget::Initialize(mitk::DataStorage* dataStorage, std::string supposedIdentifier, std::string supposedName)\n{\n m_DataStorage = dataStorage;\n\n \/\/initialize UI components\n m_Controls->m_SurfaceChooser->SetDataStorage(m_DataStorage);\n m_Controls->m_SurfaceChooser->SetAutoSelectNewItems(true);\n m_Controls->m_SurfaceChooser->SetPredicate(mitk::NodePredicateDataType::New(\"Surface\"));\n\n \/\/set default data\n m_Controls->m_ToolNameEdit->setText(supposedName.c_str());\n m_Controls->m_CalibrationFileName->setText(\"none\");\n m_Controls->m_Surface_Use_Sphere->setChecked(true);\n m_AdvancedWidget->SetDataStorage(m_DataStorage);\n\n}\n\nvoid QmitkNavigationToolCreationWidget::SetTrackingDeviceType(mitk::TrackingDeviceType type, bool changeable)\n{\n switch(type)\n {\n case mitk::NDIAurora:\n m_Controls->m_TrackingDeviceTypeChooser->setCurrentIndex(0);break;\n case mitk::NDIPolaris:\n m_Controls->m_TrackingDeviceTypeChooser->setCurrentIndex(1);break;\n case mitk::ClaronMicron:\n m_Controls->m_TrackingDeviceTypeChooser->setCurrentIndex(2);break;\n default:\n m_Controls->m_TrackingDeviceTypeChooser->setCurrentIndex(0);\n }\n m_Controls->m_TrackingDeviceTypeChooser->setEnabled(changeable);\n}\n\nmitk::NavigationTool::Pointer QmitkNavigationToolCreationWidget::GetCreatedTool()\n{\n return m_CreatedTool;\n}\n\n\/\/##################################################################################\n\/\/############################## slots ############################\n\/\/##################################################################################\n\nvoid QmitkNavigationToolCreationWidget::OnFinished()\n{\n \/\/here we create a new tool\n m_CreatedTool = mitk::NavigationTool::New();\n\n \/\/create DataNode...\n mitk::DataNode::Pointer newNode = mitk::DataNode::New();\n if(m_Controls->m_Surface_Use_Sphere->isChecked())\n {\n \/\/create small sphere and use it as surface\n mitk::Surface::Pointer mySphere = mitk::Surface::New();\n vtkConeSource *vtkData = vtkConeSource::New();\n vtkData->SetAngle(5.0);\n vtkData->SetResolution(50);\n vtkData->SetHeight(6.0f);\n vtkData->SetRadius(2.0f);\n vtkData->SetCenter(0.0, 0.0, 0.0);\n vtkData->Update();\n mySphere->SetVtkPolyData(vtkData->GetOutput());\n vtkData->Delete();\n newNode->SetData(mySphere);\n }\n else\n {\n newNode->SetData(m_Controls->m_SurfaceChooser->GetSelectedNode()->GetData());\n }\n newNode->SetName(m_Controls->m_ToolNameEdit->text().toLatin1());\n\n m_CreatedTool->SetDataNode(newNode);\n\n \/\/fill NavigationTool object\n m_CreatedTool->SetCalibrationFile(m_Controls->m_CalibrationFileName->text().toAscii().data());\n m_CreatedTool->SetIdentifier(m_Controls->m_IdentifierEdit->text().toAscii().data());\n m_CreatedTool->SetSerialNumber(m_Controls->m_SerialNumberEdit->text().toAscii().data());\n\n \/\/Tracking Device\n if (m_Controls->m_TrackingDeviceTypeChooser->currentText()==\"NDI Aurora\") m_CreatedTool->SetTrackingDeviceType(mitk::NDIAurora);\n else if (m_Controls->m_TrackingDeviceTypeChooser->currentText()==\"NDI Polaris\") m_CreatedTool->SetTrackingDeviceType(mitk::NDIPolaris);\n else if (m_Controls->m_TrackingDeviceTypeChooser->currentText()==\"Claron Technology Micron Tracker\") m_CreatedTool->SetTrackingDeviceType(mitk::ClaronMicron);\n else m_CreatedTool->SetTrackingDeviceType(mitk::TrackingSystemNotSpecified);\n\n \/\/ToolType\n if (m_Controls->m_ToolTypeChooser->currentText()==\"Instrument\") m_CreatedTool->SetType(mitk::NavigationTool::Instrument);\n else if (m_Controls->m_ToolTypeChooser->currentText()==\"Fiducial\") m_CreatedTool->SetType(mitk::NavigationTool::Fiducial);\n else if (m_Controls->m_ToolTypeChooser->currentText()==\"Skinmarker\") m_CreatedTool->SetType(mitk::NavigationTool::Skinmarker);\n else m_CreatedTool->SetType(mitk::NavigationTool::Unknown);\n\n mitk::NavigationData::Pointer tempND = mitk::NavigationData::New(m_AdvancedWidget->GetManipulatedToolTip());\n m_CreatedTool->SetToolTipOrientation(tempND->GetOrientation());\n m_CreatedTool->SetToolTipPosition(tempND->GetPosition());\n\n emit NavigationToolFinished();\n}\n\nvoid QmitkNavigationToolCreationWidget::OnCancel()\n{\n m_CreatedTool = NULL;\n\n emit Canceled();\n}\n\nvoid QmitkNavigationToolCreationWidget::OnLoadSurface()\n{\n std::string filename = QFileDialog::getOpenFileName(NULL,tr(\"Open Surface\"), \"\/\", tr(\"STL (*.stl)\")).toLatin1().data();\n mitk::STLFileReader::Pointer stlReader = mitk::STLFileReader::New();\n try\n {\n stlReader->SetFileName( filename.c_str() );\n stlReader->Update();\n }\n catch (...)\n {\n }\n\n if ( stlReader->GetOutput() == NULL );\n else\n {\n mitk::DataNode::Pointer newNode = mitk::DataNode::New();\n newNode->SetName(filename);\n newNode->SetData(stlReader->GetOutput());\n m_DataStorage->Add(newNode);\n }\n}\n\nvoid QmitkNavigationToolCreationWidget::OnLoadCalibrationFile()\n{\n m_Controls->m_CalibrationFileName->setText(QFileDialog::getOpenFileName(NULL,tr(\"Open Calibration File\"), \"\/\", \"*.*\"));\n}\n\nvoid QmitkNavigationToolCreationWidget::SetDefaultData(mitk::NavigationTool::Pointer DefaultTool)\n{\n m_Controls->m_ToolNameEdit->setText(QString(DefaultTool->GetDataNode()->GetName().c_str()));\n m_Controls->m_IdentifierEdit->setText(QString(DefaultTool->GetIdentifier().c_str()));\n m_Controls->m_SerialNumberEdit->setText(QString(DefaultTool->GetSerialNumber().c_str()));\n m_AdvancedWidget->SetDefaultTooltip( DefaultTool->GetToolTipTransform() );\n switch(DefaultTool->GetTrackingDeviceType())\n {\n case mitk::NDIAurora:\n m_Controls->m_TrackingDeviceTypeChooser->setCurrentIndex(0);break;\n case mitk::NDIPolaris:\n m_Controls->m_TrackingDeviceTypeChooser->setCurrentIndex(1);break;\n case mitk::ClaronMicron:\n m_Controls->m_TrackingDeviceTypeChooser->setCurrentIndex(2);break;\n default:\n m_Controls->m_TrackingDeviceTypeChooser->setCurrentIndex(0);\n }\n m_Controls->m_CalibrationFileName->setText(QString(DefaultTool->GetCalibrationFile().c_str()));\n m_Controls->m_Surface_Use_Other->setChecked(true);\n switch(DefaultTool->GetType())\n {\n case mitk::NavigationTool::Instrument:\n m_Controls->m_ToolTypeChooser->setCurrentIndex(0); break;\n case mitk::NavigationTool::Fiducial:\n m_Controls->m_ToolTypeChooser->setCurrentIndex(1); break;\n case mitk::NavigationTool::Skinmarker:\n m_Controls->m_ToolTypeChooser->setCurrentIndex(2); break;\n case mitk::NavigationTool::Unknown:\n m_Controls->m_ToolTypeChooser->setCurrentIndex(3); break;\n }\n\n m_Controls->m_SurfaceChooser->SetSelectedNode(DefaultTool->GetDataNode());\n\n}\n\n\n\n\/\/##################################################################################\n\/\/############################## internal help methods #############################\n\/\/##################################################################################\nvoid QmitkNavigationToolCreationWidget::MessageBox(std::string s)\n{\n QMessageBox msgBox;\n msgBox.setText(s.c_str());\n msgBox.exec();\n}\n\nvoid QmitkNavigationToolCreationWidget::OnShowAdvancedOptions(bool state)\n{\n if(state)\n {\n m_AdvancedWidget->show();\n m_AdvancedWidget->SetDefaultTooltip(m_AdvancedWidget->GetManipulatedToolTip()); \/\/use the last one, if there is one\n m_AdvancedWidget->ReInitialize();\n\n \/\/ reinit the views with the new nodes\n mitk::DataStorage::SetOfObjects::ConstPointer rs = m_DataStorage->GetAll();\n mitk::TimeGeometry::Pointer bounds = m_DataStorage->ComputeBoundingGeometry3D(rs, \"visible\"); \/\/ initialize the views to the bounding geometry\n mitk::RenderingManager::GetInstance()->InitializeViews(bounds);\n }\n else\n {\n m_AdvancedWidget->hide();\n }\n}\n\nvoid QmitkNavigationToolCreationWidget::OnProcessDialogCloseRequest()\n{\n m_AdvancedWidget->hide();\n m_Controls->m_ShowAdvancedOptionsPB->setChecked(false);\n}\n\nvoid QmitkNavigationToolCreationWidget::OnRetrieveDataForManualTooltipManipulation()\n{\n if(m_Controls->m_Surface_Use_Sphere->isChecked())\n {\n m_AdvancedWidget->SetToolTipSurface(true);\n }\n else\n {\n m_AdvancedWidget->SetToolTipSurface(false,\n dynamic_cast<mitk::DataNode*>(m_Controls->m_SurfaceChooser->GetSelectedNode().GetPointer()));\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2015 Project Vogue. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include <algorithm>\n#include <sstream>\n#include <string>\n#include <utility>\n#include <vector>\n\n#include \"elang\/lir\/testing\/lir_test.h\"\n\n#include \"base\/logging.h\"\n#include \"elang\/lir\/transforms\/parallel_copy_expander.h\"\n\nnamespace elang {\nnamespace lir {\nnamespace {\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ LirParallelCopyExpanderTest\n\/\/\nclass LirParallelCopyExpanderTest : public testing::LirTest {\n protected:\n typedef std::pair<Value, Value> Task;\n\n LirParallelCopyExpanderTest() = default;\n ~LirParallelCopyExpanderTest() = default;\n\n static Value int32_type() {\n return Value(Value::Type::Integer, ValueSize::Size32);\n }\n\n static Value physical(int data) {\n return Value(Value::Type::Integer, ValueSize::Size32,\n Value::Kind::PhysicalRegister, data);\n }\n\n static Value stack_slot(int data) {\n return Value(Value::Type::Integer, ValueSize::Size32,\n Value::Kind::StackSlot, data);\n }\n\n void Expand(const std::vector<Task>& tasks, base::StringPiece expected);\n void ExpandWithScratch(const std::vector<Task>& tasks,\n Value scratch,\n base::StringPiece expected);\n void ExpandWithScratch2(const std::vector<Task>& tasks,\n Value scratch1,\n Value scratch2,\n base::StringPiece expected);\n\n private:\n DISALLOW_COPY_AND_ASSIGN(LirParallelCopyExpanderTest);\n};\n\nvoid LirParallelCopyExpanderTest::Expand(const std::vector<Task>& tasks,\n base::StringPiece expected) {\n ExpandWithScratch2(tasks, Value(), Value(), expected);\n}\n\nvoid LirParallelCopyExpanderTest::ExpandWithScratch(\n const std::vector<Task>& tasks,\n Value scratch1,\n base::StringPiece expected) {\n ExpandWithScratch2(tasks, scratch1, Value(), expected);\n}\n\nvoid LirParallelCopyExpanderTest::ExpandWithScratch2(\n const std::vector<Task>& original_tasks,\n Value scratch1,\n Value scratch2,\n base::StringPiece expected) {\n auto tasks = original_tasks;\n DCHECK(!tasks.empty());\n for (auto count = 0u; count < tasks.size(); ++count) {\n ParallelCopyExpander expander(factory(), int32_type());\n for (auto task : tasks)\n expander.AddTask(task.first, task.second);\n if (scratch1.is_physical())\n expander.AddScratch(scratch1);\n if (scratch2.is_physical())\n expander.AddScratch(scratch2);\n\n std::stringstream ostream;\n for (auto const instr : expander.Expand())\n ostream << PrintAsGeneric(instr) << std::endl;\n EXPECT_EQ(expected, ostream.str());\n\n std::rotate(tasks.begin(), tasks.begin() + 1, tasks.end());\n }\n}\n\n\/\/ Test cases...\n\nTEST_F(LirParallelCopyExpanderTest, AutoScratchByImmediate) {\n Expand(\n {\n std::make_pair(stack_slot(0), stack_slot(2)),\n std::make_pair(stack_slot(1), physical(0)),\n std::make_pair(physical(1), Value::SmallInt32(42)),\n },\n \"mov sp[1] = R0\\n\"\n \"mov R1 = sp[2]\\n\"\n \"mov sp[0] = R1\\n\"\n \"mov R1 = #42\\n\");\n}\n\nTEST_F(LirParallelCopyExpanderTest, AutoScratchByMemory) {\n Expand(\n {\n std::make_pair(stack_slot(0), stack_slot(2)),\n std::make_pair(stack_slot(1), physical(0)),\n std::make_pair(physical(1), stack_slot(2)),\n },\n \"mov sp[1] = R0\\n\"\n \"mov R1 = sp[2]\\n\"\n \"mov sp[0] = R1\\n\");\n}\n\nTEST_F(LirParallelCopyExpanderTest, AutoScratchByMemory2) {\n Expand(\n {\n std::make_pair(stack_slot(0), stack_slot(2)),\n std::make_pair(stack_slot(1), physical(0)),\n std::make_pair(physical(1), stack_slot(3)),\n },\n \"mov sp[1] = R0\\n\"\n \"mov R1 = sp[2]\\n\"\n \"mov sp[0] = R1\\n\"\n \"mov R1 = sp[3]\\n\");\n}\n\nTEST_F(LirParallelCopyExpanderTest, Basic) {\n Expand(\n {\n std::make_pair(physical(0), physical(1)),\n std::make_pair(physical(2), physical(1)),\n std::make_pair(physical(4), physical(3)),\n },\n \"mov R0 = R1\\n\"\n \"mov R2 = R1\\n\"\n \"mov R4 = R3\\n\");\n}\n\nTEST_F(LirParallelCopyExpanderTest, MemorySwap) {\n ExpandWithScratch2(\n {\n std::make_pair(stack_slot(0), stack_slot(1)),\n std::make_pair(stack_slot(1), stack_slot(0)),\n },\n physical(2), physical(3),\n \"mov R3 = sp[1]\\n\"\n \"mov R2 = sp[0]\\n\"\n \"mov sp[0] = R3\\n\"\n \"mov sp[1] = R2\\n\");\n}\n\n\/\/ memory swap requires 2 scratch register\nTEST_F(LirParallelCopyExpanderTest, MemorySwapNoScratch) {\n Expand(\n {\n std::make_pair(stack_slot(0), stack_slot(1)),\n std::make_pair(stack_slot(1), stack_slot(0)),\n },\n \"\");\n}\n\n\/\/ memory swap requires 2 scratch register\nTEST_F(LirParallelCopyExpanderTest, MemorySwapOneScratch) {\n Expand(\n {\n std::make_pair(stack_slot(0), stack_slot(1)),\n std::make_pair(stack_slot(1), stack_slot(0)),\n },\n \"\");\n}\n\nTEST_F(LirParallelCopyExpanderTest, PhysicalToMemory) {\n Expand(\n {\n std::make_pair(stack_slot(0), physical(0)),\n std::make_pair(stack_slot(1), physical(1)),\n },\n \"mov sp[0] = R0\\n\"\n \"mov sp[1] = R1\\n\");\n}\n\nTEST_F(LirParallelCopyExpanderTest, Rotate) {\n Expand(\n {\n std::make_pair(physical(0), physical(1)),\n std::make_pair(physical(1), physical(2)),\n std::make_pair(physical(2), physical(0)),\n },\n \"pcopy R0, R1 = R1, R0\\n\"\n \"pcopy R1, R2 = R2, R1\\n\");\n}\n\nTEST_F(LirParallelCopyExpanderTest, RotateMemory) {\n ExpandWithScratch2(\n {\n std::make_pair(stack_slot(0), stack_slot(1)),\n std::make_pair(stack_slot(1), stack_slot(2)),\n std::make_pair(stack_slot(2), stack_slot(0)),\n },\n physical(4), physical(5),\n \"mov R5 = sp[1]\\n\"\n \"mov R4 = sp[0]\\n\"\n \"mov sp[0] = R5\\n\"\n \"mov R5 = sp[2]\\n\"\n \"mov sp[1] = R5\\n\"\n \"mov sp[2] = R4\\n\");\n}\n\nTEST_F(LirParallelCopyExpanderTest, RotateMemoryAndPhysical) {\n ExpandWithScratch(\n {\n std::make_pair(physical(0), physical(1)),\n std::make_pair(physical(1), stack_slot(2)),\n std::make_pair(stack_slot(2), physical(0)),\n },\n physical(2),\n \"mov R2 = sp[2]\\n\"\n \"mov sp[2] = R0\\n\"\n \"mov R0 = R1\\n\"\n \"mov R1 = R2\\n\");\n}\n\nTEST_F(LirParallelCopyExpanderTest, Swap) {\n Expand(\n {\n std::make_pair(physical(0), physical(1)),\n std::make_pair(physical(1), physical(0)),\n },\n \"pcopy R0, R1 = R1, R0\\n\");\n}\n\n} \/\/ namespace\n} \/\/ namespace lir\n} \/\/ namespace elang\n<commit_msg>elang\/lir\/transforms: Use permutation rather than rotation for test case in |LirParallelCopyExpanderTest|.<commit_after>\/\/ Copyright 2015 Project Vogue. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include <algorithm>\n#include <sstream>\n#include <string>\n#include <utility>\n#include <vector>\n\n#include \"elang\/lir\/testing\/lir_test.h\"\n\n#include \"base\/logging.h\"\n#include \"elang\/lir\/transforms\/parallel_copy_expander.h\"\n\nnamespace elang {\nnamespace lir {\nnamespace {\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ LirParallelCopyExpanderTest\n\/\/\nclass LirParallelCopyExpanderTest : public testing::LirTest {\n protected:\n typedef std::pair<Value, Value> Task;\n\n LirParallelCopyExpanderTest() = default;\n ~LirParallelCopyExpanderTest() = default;\n\n static Value int32_type() {\n return Value(Value::Type::Integer, ValueSize::Size32);\n }\n\n static Value physical(int data) {\n return Value(Value::Type::Integer, ValueSize::Size32,\n Value::Kind::PhysicalRegister, data);\n }\n\n static Value stack_slot(int data) {\n return Value(Value::Type::Integer, ValueSize::Size32,\n Value::Kind::StackSlot, data);\n }\n\n void Expand(const std::vector<Task>& tasks, base::StringPiece expected);\n void ExpandWithScratch(const std::vector<Task>& tasks,\n Value scratch,\n base::StringPiece expected);\n void ExpandWithScratch2(const std::vector<Task>& tasks,\n Value scratch1,\n Value scratch2,\n base::StringPiece expected);\n\n private:\n DISALLOW_COPY_AND_ASSIGN(LirParallelCopyExpanderTest);\n};\n\nvoid LirParallelCopyExpanderTest::Expand(const std::vector<Task>& tasks,\n base::StringPiece expected) {\n ExpandWithScratch2(tasks, Value(), Value(), expected);\n}\n\nvoid LirParallelCopyExpanderTest::ExpandWithScratch(\n const std::vector<Task>& tasks,\n Value scratch1,\n base::StringPiece expected) {\n ExpandWithScratch2(tasks, scratch1, Value(), expected);\n}\n\nvoid LirParallelCopyExpanderTest::ExpandWithScratch2(\n const std::vector<Task>& original_tasks,\n Value scratch1,\n Value scratch2,\n base::StringPiece expected) {\n DCHECK(!original_tasks.empty());\n std::vector<int> indexes(original_tasks.size());\n for (auto index = 0u; index < indexes.size(); ++index)\n indexes[index] = index;\n do {\n ParallelCopyExpander expander(factory(), int32_type());\n std::vector<Task> tasks(indexes.size());\n tasks.resize(0);\n for (auto const index : indexes)\n tasks.push_back(original_tasks[index]);\n for (auto task : tasks)\n expander.AddTask(task.first, task.second);\n if (scratch1.is_physical())\n expander.AddScratch(scratch1);\n if (scratch2.is_physical())\n expander.AddScratch(scratch2);\n\n std::stringstream ostream;\n for (auto const instr : expander.Expand())\n ostream << PrintAsGeneric(instr) << std::endl;\n EXPECT_EQ(expected, ostream.str());\n\n std::rotate(tasks.begin(), tasks.begin() + 1, tasks.end());\n } while (std::next_permutation(indexes.begin(), indexes.end()));\n}\n\n\/\/ Test cases...\n\nTEST_F(LirParallelCopyExpanderTest, AutoScratchByImmediate) {\n Expand(\n {\n std::make_pair(stack_slot(0), stack_slot(2)),\n std::make_pair(stack_slot(1), physical(0)),\n std::make_pair(physical(1), Value::SmallInt32(42)),\n },\n \"mov sp[1] = R0\\n\"\n \"mov R1 = sp[2]\\n\"\n \"mov sp[0] = R1\\n\"\n \"mov R1 = #42\\n\");\n}\n\nTEST_F(LirParallelCopyExpanderTest, AutoScratchByMemory) {\n Expand(\n {\n std::make_pair(stack_slot(0), stack_slot(2)),\n std::make_pair(stack_slot(1), physical(0)),\n std::make_pair(physical(1), stack_slot(2)),\n },\n \"mov sp[1] = R0\\n\"\n \"mov R1 = sp[2]\\n\"\n \"mov sp[0] = R1\\n\");\n}\n\nTEST_F(LirParallelCopyExpanderTest, AutoScratchByMemory2) {\n Expand(\n {\n std::make_pair(stack_slot(0), stack_slot(2)),\n std::make_pair(stack_slot(1), physical(0)),\n std::make_pair(physical(1), stack_slot(3)),\n },\n \"mov sp[1] = R0\\n\"\n \"mov R1 = sp[2]\\n\"\n \"mov sp[0] = R1\\n\"\n \"mov R1 = sp[3]\\n\");\n}\n\nTEST_F(LirParallelCopyExpanderTest, Basic) {\n Expand(\n {\n std::make_pair(physical(0), physical(1)),\n std::make_pair(physical(2), physical(1)),\n std::make_pair(physical(4), physical(3)),\n },\n \"mov R0 = R1\\n\"\n \"mov R2 = R1\\n\"\n \"mov R4 = R3\\n\");\n}\n\nTEST_F(LirParallelCopyExpanderTest, MemorySwap) {\n ExpandWithScratch2(\n {\n std::make_pair(stack_slot(0), stack_slot(1)),\n std::make_pair(stack_slot(1), stack_slot(0)),\n },\n physical(2), physical(3),\n \"mov R3 = sp[1]\\n\"\n \"mov R2 = sp[0]\\n\"\n \"mov sp[0] = R3\\n\"\n \"mov sp[1] = R2\\n\");\n}\n\n\/\/ memory swap requires 2 scratch register\nTEST_F(LirParallelCopyExpanderTest, MemorySwapNoScratch) {\n Expand(\n {\n std::make_pair(stack_slot(0), stack_slot(1)),\n std::make_pair(stack_slot(1), stack_slot(0)),\n },\n \"\");\n}\n\n\/\/ memory swap requires 2 scratch register\nTEST_F(LirParallelCopyExpanderTest, MemorySwapOneScratch) {\n Expand(\n {\n std::make_pair(stack_slot(0), stack_slot(1)),\n std::make_pair(stack_slot(1), stack_slot(0)),\n },\n \"\");\n}\n\nTEST_F(LirParallelCopyExpanderTest, PhysicalToMemory) {\n Expand(\n {\n std::make_pair(stack_slot(0), physical(0)),\n std::make_pair(stack_slot(1), physical(1)),\n },\n \"mov sp[0] = R0\\n\"\n \"mov sp[1] = R1\\n\");\n}\n\nTEST_F(LirParallelCopyExpanderTest, Rotate) {\n Expand(\n {\n std::make_pair(physical(0), physical(1)),\n std::make_pair(physical(1), physical(2)),\n std::make_pair(physical(2), physical(0)),\n },\n \"pcopy R0, R1 = R1, R0\\n\"\n \"pcopy R1, R2 = R2, R1\\n\");\n}\n\nTEST_F(LirParallelCopyExpanderTest, RotateMemory) {\n ExpandWithScratch2(\n {\n std::make_pair(stack_slot(0), stack_slot(1)),\n std::make_pair(stack_slot(1), stack_slot(2)),\n std::make_pair(stack_slot(2), stack_slot(0)),\n },\n physical(4), physical(5),\n \"mov R5 = sp[1]\\n\"\n \"mov R4 = sp[0]\\n\"\n \"mov sp[0] = R5\\n\"\n \"mov R5 = sp[2]\\n\"\n \"mov sp[1] = R5\\n\"\n \"mov sp[2] = R4\\n\");\n}\n\nTEST_F(LirParallelCopyExpanderTest, RotateMemoryAndPhysical) {\n ExpandWithScratch(\n {\n std::make_pair(physical(0), physical(1)),\n std::make_pair(physical(1), stack_slot(2)),\n std::make_pair(stack_slot(2), physical(0)),\n },\n physical(2),\n \"mov R2 = sp[2]\\n\"\n \"mov sp[2] = R0\\n\"\n \"mov R0 = R1\\n\"\n \"mov R1 = R2\\n\");\n}\n\nTEST_F(LirParallelCopyExpanderTest, Swap) {\n Expand(\n {\n std::make_pair(physical(0), physical(1)),\n std::make_pair(physical(1), physical(0)),\n },\n \"pcopy R0, R1 = R1, R0\\n\");\n}\n\n} \/\/ namespace\n} \/\/ namespace lir\n} \/\/ namespace elang\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 2014 Samsung Electronics Co., Ltd.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *\/\n\/\/------------------------------------------------------------------------------\n\/\/\n\/\/ Run a json script layout file\n\/\/\n\/\/ - watches an named file and reloads actor tree if the file changes\n\/\/ ie run\n\/\/ builder-run layout.json\n\/\/\n\/\/ and edit layout.json in a text editor saving to trigger the reload\n\/\/\n\/\/------------------------------------------------------------------------------\n\n#include <dali\/dali.h>\n#include <dali-toolkit\/dali-toolkit.h>\n#include <dali-toolkit\/public-api\/builder\/builder.h>\n#include <dali-toolkit\/public-api\/builder\/tree-node.h>\n#include <map>\n#include <string>\n#include <fstream>\n#include <streambuf>\n#include <boost\/scoped_ptr.hpp>\n\n\/\/#include <boost\/regex.hpp>\n#include \"sys\/stat.h\"\n#include <ctime>\n\n#include <dali\/integration-api\/debug.h>\n\n#define TOKEN_STRING(x) #x\n\nusing namespace Dali;\nusing namespace Dali::Toolkit;\n\nnamespace\n{\n\nstd::string JSON_BROKEN(\" \\\n{ \\\n 'stage': \\\n [ \\\n { \\\n 'type':'TextActor', \\\n 'size': [50,50,1], \\\n 'parent-origin': 'CENTER', \\\n 'text':'COULD NOT LOAD JSON FILE' \\\n } \\\n ] \\\n} \\\n\");\n\nstd::string ReplaceQuotes(const std::string &single_quoted)\n{\n std::string s(single_quoted);\n\n \/\/ wrong as no embedded quote but had regex link problems\n std::replace(s.begin(), s.end(), '\\'', '\"');\n\n return s;\n}\n\n} \/\/ anon namespace\n\n\n\/\/------------------------------------------------------------------------------\n\/\/\n\/\/\n\/\/\n\/\/------------------------------------------------------------------------------\nclass FileWatcher\n{\npublic:\n FileWatcher(void);\n ~FileWatcher(void);\n explicit FileWatcher(const std::string &fn) { SetFilename(fn) ; };\n\n void SetFilename(const std::string &fn);\n std::string GetFilename();\n\n bool FileHasChanged(void);\n std::string GetFileContents(void) { return GetFileContents(mstringPath) ; };\n\nprivate:\n \/\/ compiler does\n \/\/ FileWatcher(const FileWatcher&);\n \/\/ FileWatcher &operator=(const FileWatcher &);\n\n std::time_t mLastTime;\n std::string mstringPath;\n\n std::string GetFileContents(const std::string &fn)\n {\n std::ifstream t(fn.c_str());\n return std::string((std::istreambuf_iterator<char>(t)), std::istreambuf_iterator<char>());\n };\n};\n\nFileWatcher::FileWatcher(void) : mLastTime(0)\n{\n}\n\nbool FileWatcher::FileHasChanged(void)\n{\n struct stat buf;\n\n if(0 != stat(mstringPath.c_str(), &buf))\n {\n DALI_LOG_WARNING(\"File does not exist '%s'\\n\", mstringPath.c_str());\n return false;\n }\n else\n {\n if(buf.st_mtime > mLastTime)\n {\n mLastTime = buf.st_mtime;\n return true;\n }\n else\n {\n mLastTime = buf.st_mtime;\n return false;\n }\n }\n\n return false;\n}\n\nFileWatcher::~FileWatcher()\n{\n}\n\nvoid FileWatcher::SetFilename(const std::string &fn)\n{\n mstringPath = fn;\n}\n\nstd::string FileWatcher::GetFilename(void)\n{\n return mstringPath;\n}\n\n\n\/\/------------------------------------------------------------------------------\n\/\/\n\/\/\n\/\/\n\/\/------------------------------------------------------------------------------\nclass ExampleApp : public ConnectionTracker\n{\npublic:\n ExampleApp(Application &app) : mApp(app)\n {\n app.InitSignal().Connect(this, &ExampleApp::Create);\n\n }\n\n ~ExampleApp() {}\n\npublic:\n void SetJSONFilename(std::string const &fn) { fw.SetFilename(fn) ; };\n\n void Create(Application& app)\n {\n mTimer = Timer::New( 500 ); \/\/ ms\n mTimer.TickSignal().Connect( this, &ExampleApp::OnTimer);\n mTimer.Start();\n\n \/\/ Connect to key events in order to exit\n Stage::GetCurrent().KeyEventSignal().Connect(this, &ExampleApp::OnKeyEvent);\n }\n\nprivate:\n Application& mApp;\n Layer mRootLayer;\n\n FileWatcher fw;\n Timer mTimer;\n\n void ReloadJsonFile(Builder& builder, Layer& layer)\n {\n Stage stage = Stage::GetCurrent();\n\n builder = Builder::New();\n\n PropertyValueMap defaultDirs;\n defaultDirs[ TOKEN_STRING(DALI_IMAGE_DIR) ] = DALI_IMAGE_DIR;\n defaultDirs[ TOKEN_STRING(DALI_MODEL_DIR) ] = DALI_MODEL_DIR;\n defaultDirs[ TOKEN_STRING(DALI_SCRIPT_DIR) ] = DALI_SCRIPT_DIR;\n\n builder.AddConstants( defaultDirs );\n\n if(!layer)\n {\n layer = Layer::New();\n layer.SetParentOrigin(ParentOrigin::CENTER);\n layer.SetAnchorPoint(AnchorPoint::CENTER);\n layer.SetSize( stage.GetRootLayer().GetCurrentSize() );\n stage.GetRootLayer().Add(layer);\n\n \/\/ render tasks may have been setup last load so remove them\n RenderTaskList taskList = stage.GetRenderTaskList();\n if( taskList.GetTaskCount() > 1 )\n {\n typedef std::vector<RenderTask> Collection;\n typedef Collection::iterator ColIter;\n Collection tasks;\n\n for(unsigned int i = 1; i < taskList.GetTaskCount(); ++i)\n {\n tasks.push_back( taskList.GetTask(i) );\n }\n\n for(ColIter iter = tasks.begin(); iter != tasks.end(); ++iter)\n {\n taskList.RemoveTask(*iter);\n }\n\n RenderTask defaultTask = taskList.GetTask(0);\n defaultTask.SetSourceActor( stage.GetRootLayer() );\n defaultTask.SetTargetFrameBuffer( FrameBufferImage() );\n }\n }\n\n unsigned int numChildren = layer.GetChildCount();\n\n for(unsigned int i=0; i<numChildren; ++i)\n {\n layer.Remove( layer.GetChildAt(0) );\n }\n\n std::string data(fw.GetFileContents());\n\n try\n {\n builder.LoadFromString(data);\n }\n catch(...)\n {\n builder.LoadFromString(ReplaceQuotes(JSON_BROKEN));\n }\n\n builder.AddActors( layer );\n\n }\n\n\n bool OnTimer(void)\n {\n if(fw.FileHasChanged())\n {\n ReloadJsonFile( mBuilder, mRootLayer );\n }\n\n return true;\n }\n\n \/\/ Process Key events to Quit on back-key\n void OnKeyEvent( const KeyEvent& event )\n {\n if( event.state == KeyEvent::Down )\n {\n if( IsKey( event, Dali::DALI_KEY_ESCAPE ) || IsKey( event, Dali::DALI_KEY_BACK ) )\n {\n Application::Get().Quit();\n }\n }\n }\n\n Builder mBuilder;\n};\n\n\/\/------------------------------------------------------------------------------\n\/\/\n\/\/\n\/\/\n\/\/------------------------------------------------------------------------------\nint main(int argc, char **argv)\n{\n Application dali_app = Application::New(&argc, &argv);\n\n ExampleApp app(dali_app);\n\n\n if(argc > 1)\n {\n std::cout << \"Loading file:\" << argc << \" \" << argv[1] << std::endl;\n app.SetJSONFilename(argv[1]);\n }\n else\n {\n DALI_ASSERT_ALWAYS(!\"Specify JSON file on command line\\n\");\n }\n\n dali_app.MainLoop();\n\n return 0;\n}\n<commit_msg>(Builder) Stop using Application::Get()<commit_after>\/*\n * Copyright (c) 2014 Samsung Electronics Co., Ltd.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *\/\n\/\/------------------------------------------------------------------------------\n\/\/\n\/\/ Run a json script layout file\n\/\/\n\/\/ - watches an named file and reloads actor tree if the file changes\n\/\/ ie run\n\/\/ builder-run layout.json\n\/\/\n\/\/ and edit layout.json in a text editor saving to trigger the reload\n\/\/\n\/\/------------------------------------------------------------------------------\n\n#include <dali\/dali.h>\n#include <dali-toolkit\/dali-toolkit.h>\n#include <dali-toolkit\/public-api\/builder\/builder.h>\n#include <dali-toolkit\/public-api\/builder\/tree-node.h>\n#include <map>\n#include <string>\n#include <fstream>\n#include <streambuf>\n#include <boost\/scoped_ptr.hpp>\n\n\/\/#include <boost\/regex.hpp>\n#include \"sys\/stat.h\"\n#include <ctime>\n\n#include <dali\/integration-api\/debug.h>\n\n#define TOKEN_STRING(x) #x\n\nusing namespace Dali;\nusing namespace Dali::Toolkit;\n\nnamespace\n{\n\nstd::string JSON_BROKEN(\" \\\n{ \\\n 'stage': \\\n [ \\\n { \\\n 'type':'TextActor', \\\n 'size': [50,50,1], \\\n 'parent-origin': 'CENTER', \\\n 'text':'COULD NOT LOAD JSON FILE' \\\n } \\\n ] \\\n} \\\n\");\n\nstd::string ReplaceQuotes(const std::string &single_quoted)\n{\n std::string s(single_quoted);\n\n \/\/ wrong as no embedded quote but had regex link problems\n std::replace(s.begin(), s.end(), '\\'', '\"');\n\n return s;\n}\n\n} \/\/ anon namespace\n\n\n\/\/------------------------------------------------------------------------------\n\/\/\n\/\/\n\/\/\n\/\/------------------------------------------------------------------------------\nclass FileWatcher\n{\npublic:\n FileWatcher(void);\n ~FileWatcher(void);\n explicit FileWatcher(const std::string &fn) { SetFilename(fn) ; };\n\n void SetFilename(const std::string &fn);\n std::string GetFilename();\n\n bool FileHasChanged(void);\n std::string GetFileContents(void) { return GetFileContents(mstringPath) ; };\n\nprivate:\n \/\/ compiler does\n \/\/ FileWatcher(const FileWatcher&);\n \/\/ FileWatcher &operator=(const FileWatcher &);\n\n std::time_t mLastTime;\n std::string mstringPath;\n\n std::string GetFileContents(const std::string &fn)\n {\n std::ifstream t(fn.c_str());\n return std::string((std::istreambuf_iterator<char>(t)), std::istreambuf_iterator<char>());\n };\n};\n\nFileWatcher::FileWatcher(void) : mLastTime(0)\n{\n}\n\nbool FileWatcher::FileHasChanged(void)\n{\n struct stat buf;\n\n if(0 != stat(mstringPath.c_str(), &buf))\n {\n DALI_LOG_WARNING(\"File does not exist '%s'\\n\", mstringPath.c_str());\n return false;\n }\n else\n {\n if(buf.st_mtime > mLastTime)\n {\n mLastTime = buf.st_mtime;\n return true;\n }\n else\n {\n mLastTime = buf.st_mtime;\n return false;\n }\n }\n\n return false;\n}\n\nFileWatcher::~FileWatcher()\n{\n}\n\nvoid FileWatcher::SetFilename(const std::string &fn)\n{\n mstringPath = fn;\n}\n\nstd::string FileWatcher::GetFilename(void)\n{\n return mstringPath;\n}\n\n\n\/\/------------------------------------------------------------------------------\n\/\/\n\/\/\n\/\/\n\/\/------------------------------------------------------------------------------\nclass ExampleApp : public ConnectionTracker\n{\npublic:\n ExampleApp(Application &app) : mApp(app)\n {\n app.InitSignal().Connect(this, &ExampleApp::Create);\n\n }\n\n ~ExampleApp() {}\n\npublic:\n void SetJSONFilename(std::string const &fn) { fw.SetFilename(fn) ; };\n\n void Create(Application& app)\n {\n mTimer = Timer::New( 500 ); \/\/ ms\n mTimer.TickSignal().Connect( this, &ExampleApp::OnTimer);\n mTimer.Start();\n\n \/\/ Connect to key events in order to exit\n Stage::GetCurrent().KeyEventSignal().Connect(this, &ExampleApp::OnKeyEvent);\n }\n\nprivate:\n Application& mApp;\n Layer mRootLayer;\n\n FileWatcher fw;\n Timer mTimer;\n\n void ReloadJsonFile(Builder& builder, Layer& layer)\n {\n Stage stage = Stage::GetCurrent();\n\n builder = Builder::New();\n\n PropertyValueMap defaultDirs;\n defaultDirs[ TOKEN_STRING(DALI_IMAGE_DIR) ] = DALI_IMAGE_DIR;\n defaultDirs[ TOKEN_STRING(DALI_MODEL_DIR) ] = DALI_MODEL_DIR;\n defaultDirs[ TOKEN_STRING(DALI_SCRIPT_DIR) ] = DALI_SCRIPT_DIR;\n\n builder.AddConstants( defaultDirs );\n\n if(!layer)\n {\n layer = Layer::New();\n layer.SetParentOrigin(ParentOrigin::CENTER);\n layer.SetAnchorPoint(AnchorPoint::CENTER);\n layer.SetSize( stage.GetRootLayer().GetCurrentSize() );\n stage.GetRootLayer().Add(layer);\n\n \/\/ render tasks may have been setup last load so remove them\n RenderTaskList taskList = stage.GetRenderTaskList();\n if( taskList.GetTaskCount() > 1 )\n {\n typedef std::vector<RenderTask> Collection;\n typedef Collection::iterator ColIter;\n Collection tasks;\n\n for(unsigned int i = 1; i < taskList.GetTaskCount(); ++i)\n {\n tasks.push_back( taskList.GetTask(i) );\n }\n\n for(ColIter iter = tasks.begin(); iter != tasks.end(); ++iter)\n {\n taskList.RemoveTask(*iter);\n }\n\n RenderTask defaultTask = taskList.GetTask(0);\n defaultTask.SetSourceActor( stage.GetRootLayer() );\n defaultTask.SetTargetFrameBuffer( FrameBufferImage() );\n }\n }\n\n unsigned int numChildren = layer.GetChildCount();\n\n for(unsigned int i=0; i<numChildren; ++i)\n {\n layer.Remove( layer.GetChildAt(0) );\n }\n\n std::string data(fw.GetFileContents());\n\n try\n {\n builder.LoadFromString(data);\n }\n catch(...)\n {\n builder.LoadFromString(ReplaceQuotes(JSON_BROKEN));\n }\n\n builder.AddActors( layer );\n\n }\n\n\n bool OnTimer(void)\n {\n if(fw.FileHasChanged())\n {\n ReloadJsonFile( mBuilder, mRootLayer );\n }\n\n return true;\n }\n\n \/\/ Process Key events to Quit on back-key\n void OnKeyEvent( const KeyEvent& event )\n {\n if( event.state == KeyEvent::Down )\n {\n if( IsKey( event, Dali::DALI_KEY_ESCAPE ) || IsKey( event, Dali::DALI_KEY_BACK ) )\n {\n mApp.Quit();\n }\n }\n }\n\n Builder mBuilder;\n};\n\n\/\/------------------------------------------------------------------------------\n\/\/\n\/\/\n\/\/\n\/\/------------------------------------------------------------------------------\nint main(int argc, char **argv)\n{\n Application dali_app = Application::New(&argc, &argv);\n\n ExampleApp app(dali_app);\n\n\n if(argc > 1)\n {\n std::cout << \"Loading file:\" << argc << \" \" << argv[1] << std::endl;\n app.SetJSONFilename(argv[1]);\n }\n else\n {\n DALI_ASSERT_ALWAYS(!\"Specify JSON file on command line\\n\");\n }\n\n dali_app.MainLoop();\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\n\/*\n * CodeQuery\n * Copyright (C) 2013 ruben2020 https:\/\/github.com\/ruben2020\/\n * \n * This program is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n * \n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n * \n *\/\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <memory>\n#include \"small_lib.h\"\n#include \"optlist.h\"\n#include \"sqlquery.h\"\n#include \"swver.h\"\n\n\nvoid printhelp(const char* str)\n{\n\tprintf(\"Usage: %s [-s <sqdbfile> [-p n] [-t x] -[e|f] ] [-d] [-v] [-h]\\n\\n\", str);\n\tprintf(\"options:\\n\");\n\tprintf(\" -s : CodeQuery sqlite3 db file path\\n\");\n\tprintf(\" -p n : parameter is a number denoted by n\\n\");\n\tprintf(\" default n = 1 (Symbol)\\n\");\n\tprintf(\" -t x : search term without spaces\\n\");\n\tprintf(\" if Exact Match is switched off, wild card\\n\");\n\tprintf(\" searches are possible. Use * and ?\\n\");\n\tprintf(\" -e : Exact Match switched ON \\n\");\n\tprintf(\" Case-sensitive\\n\");\n\tprintf(\" -f : Exact Match switched OFF (fuzzy search)\\n\");\n\tprintf(\" Case-insensitive with wild card search\\n\");\n\tprintf(\" -d : debug\\n\");\n\tprintf(\" -v : version\\n\");\n\tprintf(\" -h : help\\n\\n\");\n\tprintf(\"The combinations possible are -s -t -e, -s -t -f\\n\");\n\tprintf(\"The additional optional arguments are -d\\n\\n\");\n\tprintf(\"The possible values for n are:\\n\");\n\tprintf(\" 1: Symbol (default)\\n\");\n\tprintf(\" 2: Function or macro\\n\");\n\tprintf(\" 3: Class or struct\\n\");\n\tprintf(\" 4: Files including this file\\n\");\n\tprintf(\" 5: Full file path\\n\");\n\tprintf(\" 6: Functions calling this function\\n\");\n\tprintf(\" 7: Functions called by this function\\n\");\n\tprintf(\" 8: Members and methods of this class\\n\");\n\tprintf(\" 9: Class which owns this member or method\\n\");\n\tprintf(\" 10: Children of this class (inheritance)\\n\");\n\tprintf(\" 11: Parent of this class (inheritance)\\n\\n\");\n\tprintf(\"Example:\\n%s -s myproject.db -p 5 -t read*file -f\\n\\n\", str);\n\n}\n\nvoid printlicense(void)\n{\n\tprintf(CODEQUERY_SW_VERSION);\n\tprintf(\"\\n\");\n\tprintf(CODEQUERY_SW_LICENSE);\n}\n\nbool fileexists(const char* fn)\n{\n\tbool retval;\n\tFILE *fp;\n\tfp = fopen(fn, \"r\");\n\tretval = (fp != NULL);\n\tif (retval) fclose(fp);\n\treturn retval;\n}\n\nvoid process_argwithopt(option_t* thisOpt, bool& err, tStr& fnstr, bool filemustexist)\n{\n\tif (thisOpt->argument != NULL)\n\t{\n\t\tfnstr = thisOpt->argument;\n\t\tif (filemustexist && (fileexists(fnstr.c_str()) == false))\n\t\t{\n\t\t\tprintf(\"Error: File %s doesn't exist.\\n\", fnstr.c_str());\n\t\t\terr = true;\n\t\t}\n\t}\n\telse\n\t{\n\t\tprintf(\"Error: -%c used without file option.\\n\", thisOpt->option);\n\t\terr = true;\n\t}\n}\n\nint process_query(tStr sqfn, tStr term, tStr param, bool exact, bool debug)\n{\n\tif ((sqfn.empty())||(term.empty())||(param.empty())) return 1;\n\tint retVal = 0;\n\tstd::auto_ptr<sqlquery> sq(new sqlquery);\n\tsqlquery::en_filereadstatus filestatus = sq->open_dbfile(sqfn);\n\tswitch (filestatus)\n\t{\n\t\tcase sqlquery::sqlfileOK:\n\t\t\tbreak;\n\t\tcase sqlquery::sqlfileOPENERROR:\n\t\t\tprintf(\"Error: File %s open error!\\n\", sqfn.c_str());\n\t\t\treturn 1;\n\t\tcase sqlquery::sqlfileNOTCORRECTDB:\n\t\t\tprintf(\"Error: File %s does not have correct database format!\\n\", sqfn.c_str());\n\t\t\treturn 1;\n\t\tcase sqlquery::sqlfileINCORRECTVER:\n\t\t\tprintf(\"Error: File %s has an unsupported database version number!\\n\", sqfn.c_str());\n\t\t\treturn 1;\n\t\tcase sqlquery::sqlfileUNKNOWNERROR:\n\t\t\tprintf(\"Error: Unknown Error!\\n\");\n\t\t\treturn 1;\n\t}\n\tint intParam = atoi(param.c_str()) - 1;\n\tif ((intParam < 0) || (intParam > 10))\n\t{\n\t\tprintf(\"Error: Parameter is out of range!\\n\");\n\t\treturn 1;\t\n\t}\n\tsqlqueryresultlist resultlst;\n\tresultlst = sq->search(term, (sqlquery::en_queryType) intParam, exact);\n\tif (resultlst.result_type == sqlqueryresultlist::sqlresultERROR)\n\t{\n\t\tprintf(\"Error: SQL Error! %s!\\n\", resultlst.sqlerrmsg.c_str());\n\t\treturn 1;\t\n\t}\n\tfor(std::vector<sqlqueryresult>::iterator it = resultlst.resultlist.begin();\n\t\tit != resultlst.resultlist.end(); it++)\n\t{\n\t\tswitch(resultlst.result_type)\n\t\t{\n\t\t\tcase sqlqueryresultlist::sqlresultFULL:\n\t\t\t\tprintf(\"%s\\t%s:%s\\t%s\\n\", it->symname.c_str(), \n\t\t\t\tit->filename.c_str(), it->linenum.c_str(), it->linetext.c_str());\n\t\t\t\tbreak;\t\n\t\t\tcase sqlqueryresultlist::sqlresultFILE_LINE:\n\t\t\t\tprintf(\"%s:%s\\t%s\\n\", it->filename.c_str(), it->linenum.c_str(),\n\t\t\t\t it->linetext.c_str());\n\t\t\t\tbreak;\t\n\t\t\tcase sqlqueryresultlist::sqlresultFILE_ONLY:\n\t\t\t\tprintf(\"%s\\n\", it->filepath.c_str());\n\t\t\t\tbreak;\t\n\t\t}\n\t}\n\treturn retVal;\n}\n\nint main(int argc, char *argv[])\n{\n option_t *optList=NULL, *thisOpt=NULL;\n bool bSqlite, bParam, bTerm, bExact, bDebug, bVersion, bHelp, bError;\n int countExact = 0;\n\tbSqlite = false;\n\tbParam = false;\n\tbTerm = false;\n\tbExact = false;\n\tbDebug = false;\n\tbVersion = false;\n\tbHelp = (argc <= 1);\n\tbError = false;\n\ttStr sqfn, param = \"1\", term;\n\n \/* get list of command line options and their arguments *\/\n optList = GetOptList(argc, argv, (char*)\"s:p:t:efdvh\");\n\n \/* display results of parsing *\/\n while (optList != NULL)\n {\n thisOpt = optList;\n optList = optList->next;\n\t\t\n\t\tswitch(thisOpt->option)\n\t\t{\n\t\t\tcase 'v':\n\t\t\t\tbVersion = true;\n\t\t\t\tbreak;\n\t\t\tcase 'h':\n\t\t\t\tbHelp = true;\n\t\t\t\tbreak;\n\t\t\tcase 'e':\n\t\t\t\tbExact = true;\n\t\t\t\tcountExact++;\n\t\t\t\tbError = bError || (countExact > 1);\n\t\t\t\tbreak;\n\t\t\tcase 'f':\n\t\t\t\tbExact = false;\n\t\t\t\tcountExact++;\n\t\t\t\tbError = bError || (countExact > 1);\n\t\t\t\tbreak;\n\t\t\tcase 's':\n\t\t\t\tbSqlite = true;\n\t\t\t\tprocess_argwithopt(thisOpt, bError, sqfn, true);\n\t\t\t\tbreak;\n\t\t\tcase 'p':\n\t\t\t\tbParam = true;\n\t\t\t\tparam = thisOpt->argument;\n\t\t\t\tbreak;\n\t\t\tcase 't':\n\t\t\t\tbTerm = true;\n\t\t\t\tterm = thisOpt->argument;\n\t\t\t\tbreak;\n\t\t\tcase 'd':\n\t\t\t\tbDebug = true;\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tbreak;\n\t\t}\n free(thisOpt); \/* done with this item, free it *\/\n }\n\tif (bVersion)\n\t{\n\t\tprintlicense();\n\t\treturn 0;\n\t}\n\tif (bHelp || bError)\n\t{\n\t\tprinthelp(extract_filename(argv[0]));\n\t\treturn (bError ? 1 : 0);\n\t}\n\tif (!bSqlite)\n\t{\n\t\tprintf(\"Error: -s is required.\\n\");\n\t\tbError = true;\n\t}\n\tif (!bTerm)\n\t{\n\t\tprintf(\"Error: -t is required.\\n\");\n\t\tbError = true;\n\t}\n\tif (bError)\n\t{\n\t\tprinthelp(extract_filename(argv[0]));\n\t\treturn 1;\n\t}\n\tif (bSqlite && bTerm)\n\t{\n\t\tbError = process_query(sqfn, term, param, bExact, bDebug);\n\t}\n\tif (bError)\n\t{\n\t\tprinthelp(extract_filename(argv[0]));\n\t}\n\treturn bError;\n}\n\n<commit_msg>updated CLI<commit_after>\n\/*\n * CodeQuery\n * Copyright (C) 2013 ruben2020 https:\/\/github.com\/ruben2020\/\n * \n * This program is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n * \n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n * \n *\/\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <memory>\n#include \"small_lib.h\"\n#include \"optlist.h\"\n#include \"sqlquery.h\"\n#include \"swver.h\"\n\n\nvoid printhelp(const char* str)\n{\n\tprintf(\"Usage: %s [-s <sqdbfile> [-p <n>] [-t <term>] -[e|f] ] [-d] [-v] [-h]\\n\\n\", str);\n\tprintf(\"options:\\n\");\n\tprintf(\" -s : CodeQuery sqlite3 db file path\\n\");\n\tprintf(\" -p : parameter is a number denoted by n\\n\");\n\tprintf(\" default n = 1 (Symbol)\\n\");\n\tprintf(\" -t : search term without spaces\\n\");\n\tprintf(\" if Exact Match is switched off, wild card\\n\");\n\tprintf(\" searches are possible. Use * and ?\\n\");\n\tprintf(\" -e : Exact Match switched ON \\n\");\n\tprintf(\" Case-sensitive\\n\");\n\tprintf(\" -f : Exact Match switched OFF (fuzzy search)\\n\");\n\tprintf(\" Case-insensitive with wild card search\\n\");\n\tprintf(\" -d : debug\\n\");\n\tprintf(\" -v : version\\n\");\n\tprintf(\" -h : help\\n\\n\");\n\tprintf(\"The combinations possible are -s -t -e, -s -t -f\\n\");\n\tprintf(\"The additional optional arguments are -d\\n\\n\");\n\tprintf(\"The possible values for n are:\\n\");\n\tprintf(\" 1: Symbol (default)\\n\");\n\tprintf(\" 2: Function or macro\\n\");\n\tprintf(\" 3: Class or struct\\n\");\n\tprintf(\" 4: Files including this file\\n\");\n\tprintf(\" 5: Full file path\\n\");\n\tprintf(\" 6: Functions calling this function\\n\");\n\tprintf(\" 7: Functions called by this function\\n\");\n\tprintf(\" 8: Members and methods of this class\\n\");\n\tprintf(\" 9: Class which owns this member or method\\n\");\n\tprintf(\" 10: Children of this class (inheritance)\\n\");\n\tprintf(\" 11: Parent of this class (inheritance)\\n\\n\");\n\tprintf(\"Example:\\n%s -s myproject.db -p 6 -t read*file -f\\n\\n\", str);\n\n}\n\nvoid printlicense(void)\n{\n\tprintf(CODEQUERY_SW_VERSION);\n\tprintf(\"\\n\");\n\tprintf(CODEQUERY_SW_LICENSE);\n}\n\nbool fileexists(const char* fn)\n{\n\tbool retval;\n\tFILE *fp;\n\tfp = fopen(fn, \"r\");\n\tretval = (fp != NULL);\n\tif (retval) fclose(fp);\n\treturn retval;\n}\n\nvoid process_argwithopt(option_t* thisOpt, bool& err, tStr& fnstr, bool filemustexist)\n{\n\tif (thisOpt->argument != NULL)\n\t{\n\t\tfnstr = thisOpt->argument;\n\t\tif (filemustexist && (fileexists(fnstr.c_str()) == false))\n\t\t{\n\t\t\tprintf(\"Error: File %s doesn't exist.\\n\", fnstr.c_str());\n\t\t\terr = true;\n\t\t}\n\t}\n\telse\n\t{\n\t\tprintf(\"Error: -%c used without file option.\\n\", thisOpt->option);\n\t\terr = true;\n\t}\n}\n\nint process_query(tStr sqfn, tStr term, tStr param, bool exact, bool debug)\n{\n\tif ((sqfn.empty())||(term.empty())||(param.empty())) return 1;\n\tint retVal = 0;\n\tstd::auto_ptr<sqlquery> sq(new sqlquery);\n\tsqlquery::en_filereadstatus filestatus = sq->open_dbfile(sqfn);\n\tswitch (filestatus)\n\t{\n\t\tcase sqlquery::sqlfileOK:\n\t\t\tbreak;\n\t\tcase sqlquery::sqlfileOPENERROR:\n\t\t\tprintf(\"Error: File %s open error!\\n\", sqfn.c_str());\n\t\t\treturn 1;\n\t\tcase sqlquery::sqlfileNOTCORRECTDB:\n\t\t\tprintf(\"Error: File %s does not have correct database format!\\n\", sqfn.c_str());\n\t\t\treturn 1;\n\t\tcase sqlquery::sqlfileINCORRECTVER:\n\t\t\tprintf(\"Error: File %s has an unsupported database version number!\\n\", sqfn.c_str());\n\t\t\treturn 1;\n\t\tcase sqlquery::sqlfileUNKNOWNERROR:\n\t\t\tprintf(\"Error: Unknown Error!\\n\");\n\t\t\treturn 1;\n\t}\n\tint intParam = atoi(param.c_str()) - 1;\n\tif ((intParam < 0) || (intParam > 10))\n\t{\n\t\tprintf(\"Error: Parameter is out of range!\\n\");\n\t\treturn 1;\t\n\t}\n\tsqlqueryresultlist resultlst;\n\tresultlst = sq->search(term, (sqlquery::en_queryType) intParam, exact);\n\tif (resultlst.result_type == sqlqueryresultlist::sqlresultERROR)\n\t{\n\t\tprintf(\"Error: SQL Error! %s!\\n\", resultlst.sqlerrmsg.c_str());\n\t\treturn 1;\t\n\t}\n\tfor(std::vector<sqlqueryresult>::iterator it = resultlst.resultlist.begin();\n\t\tit != resultlst.resultlist.end(); it++)\n\t{\n\t\tswitch(resultlst.result_type)\n\t\t{\n\t\t\tcase sqlqueryresultlist::sqlresultFULL:\n\t\t\t\tprintf(\"%s\\t%s:%s\\t%s\\n\", it->symname.c_str(), \n\t\t\t\tit->filename.c_str(), it->linenum.c_str(), it->linetext.c_str());\n\t\t\t\tbreak;\t\n\t\t\tcase sqlqueryresultlist::sqlresultFILE_LINE:\n\t\t\t\tprintf(\"%s:%s\\t%s\\n\", it->filename.c_str(), it->linenum.c_str(),\n\t\t\t\t it->linetext.c_str());\n\t\t\t\tbreak;\t\n\t\t\tcase sqlqueryresultlist::sqlresultFILE_ONLY:\n\t\t\t\tprintf(\"%s\\n\", it->filepath.c_str());\n\t\t\t\tbreak;\t\n\t\t}\n\t}\n\treturn retVal;\n}\n\nint main(int argc, char *argv[])\n{\n option_t *optList=NULL, *thisOpt=NULL;\n bool bSqlite, bParam, bTerm, bExact, bDebug, bVersion, bHelp, bError;\n int countExact = 0;\n\tbSqlite = false;\n\tbParam = false;\n\tbTerm = false;\n\tbExact = false;\n\tbDebug = false;\n\tbVersion = false;\n\tbHelp = (argc <= 1);\n\tbError = false;\n\ttStr sqfn, param = \"1\", term;\n\n \/* get list of command line options and their arguments *\/\n optList = GetOptList(argc, argv, (char*)\"s:p:t:efdvh\");\n\n \/* display results of parsing *\/\n while (optList != NULL)\n {\n thisOpt = optList;\n optList = optList->next;\n\t\t\n\t\tswitch(thisOpt->option)\n\t\t{\n\t\t\tcase 'v':\n\t\t\t\tbVersion = true;\n\t\t\t\tbreak;\n\t\t\tcase 'h':\n\t\t\t\tbHelp = true;\n\t\t\t\tbreak;\n\t\t\tcase 'e':\n\t\t\t\tbExact = true;\n\t\t\t\tcountExact++;\n\t\t\t\tbError = bError || (countExact > 1);\n\t\t\t\tif (countExact > 1) printf(\"Error: either -e or -f but not both!\\n\");\n\t\t\t\tbreak;\n\t\t\tcase 'f':\n\t\t\t\tbExact = false;\n\t\t\t\tcountExact++;\n\t\t\t\tbError = bError || (countExact > 1);\n\t\t\t\tif (countExact > 1) printf(\"Error: either -e or -f but not both!\\n\");\n\t\t\t\tbreak;\n\t\t\tcase 's':\n\t\t\t\tbSqlite = true;\n\t\t\t\tprocess_argwithopt(thisOpt, bError, sqfn, true);\n\t\t\t\tbreak;\n\t\t\tcase 'p':\n\t\t\t\tbParam = true;\n\t\t\t\tparam = thisOpt->argument;\n\t\t\t\tbreak;\n\t\t\tcase 't':\n\t\t\t\tbTerm = true;\n\t\t\t\tterm = thisOpt->argument;\n\t\t\t\tbreak;\n\t\t\tcase 'd':\n\t\t\t\tbDebug = true;\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tbreak;\n\t\t}\n free(thisOpt); \/* done with this item, free it *\/\n }\n\tif (bVersion)\n\t{\n\t\tprintlicense();\n\t\treturn 0;\n\t}\n\tif (bHelp || bError)\n\t{\n\t\tprinthelp(extract_filename(argv[0]));\n\t\treturn (bError ? 1 : 0);\n\t}\n\tif (!bSqlite)\n\t{\n\t\tprintf(\"Error: -s is required.\\n\");\n\t\tbError = true;\n\t}\n\tif (!bTerm)\n\t{\n\t\tprintf(\"Error: -t is required.\\n\");\n\t\tbError = true;\n\t}\n\tif (bError)\n\t{\n\t\tprinthelp(extract_filename(argv[0]));\n\t\treturn 1;\n\t}\n\tif (bSqlite && bTerm)\n\t{\n\t\tbError = process_query(sqfn, term, param, bExact, bDebug);\n\t}\n\tif (bError)\n\t{\n\t\tprinthelp(extract_filename(argv[0]));\n\t}\n\treturn bError;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\n\/\/ Qt includes\n#include <QtGlobal>\n#include <QStringList>\n#include <QRegExp>\n\n\/\/ Visomics includes\n#include \"voUtils.h\"\n\n\/\/ VTK includes\n#include <vtkDoubleArray.h>\n#include <vtkIntArray.h>\n#include <vtkNew.h>\n#include <vtkSmartPointer.h>\n#include <vtkStringArray.h>\n#include <vtkTable.h>\n#include <vtkVariantArray.h>\n\n#include <QDebug>\n\nnamespace\n{\n\/\/----------------------------------------------------------------------------\ntemplate<typename ArrayType, typename ValueType>\nbool transposeColumn(vtkTable* srcTable, vtkTable* destTable, int columnId, bool useVariant = false)\n{\n if (!srcTable || !destTable)\n {\n return false;\n }\n if (columnId < 0 || columnId >= srcTable->GetNumberOfColumns())\n {\n return false;\n }\n vtkAbstractArray * column = srcTable->GetColumn(columnId);\n ArrayType * typeColumn = ArrayType::SafeDownCast(column);\n if (!typeColumn && !useVariant)\n {\n return false;\n }\n\n for (int rid = 0; rid < column->GetNumberOfTuples() * column->GetNumberOfComponents(); ++rid)\n {\n vtkSmartPointer<ArrayType> transposedColumn;\n if (columnId == 0)\n {\n transposedColumn = vtkSmartPointer<ArrayType>::New();\n transposedColumn->SetNumberOfValues(srcTable->GetNumberOfColumns());\n destTable->AddColumn(transposedColumn);\n }\n else\n {\n transposedColumn = ArrayType::SafeDownCast(destTable->GetColumn(rid));\n }\n Q_ASSERT(transposedColumn);\n if (!useVariant)\n {\n ValueType value = typeColumn->GetValue(rid);\n transposedColumn->SetValue(columnId, value);\n }\n else\n {\n vtkVariant value = column->GetVariantValue(rid);\n transposedColumn->SetVariantValue(columnId, value);\n }\n }\n return true;\n}\n}\n\n\/\/----------------------------------------------------------------------------\nbool voUtils::transposeTable(vtkTable* srcTable, vtkTable* destTable)\n{\n if (!srcTable)\n {\n return false;\n }\n\n if (!destTable)\n {\n return false;\n }\n\n if (srcTable->GetNumberOfColumns() == 0)\n {\n return true;\n }\n\n bool useVariant = false;\n vtkAbstractArray * firstColumn = srcTable->GetColumn(0);\n for (int cid = 1; cid < srcTable->GetNumberOfColumns(); ++cid)\n {\n if (qstrcmp(firstColumn->GetClassName(), srcTable->GetColumn(cid)->GetClassName()) != 0)\n {\n useVariant = true;\n break;\n }\n }\n\n for(int cid = 0; cid < srcTable->GetNumberOfColumns(); ++cid)\n {\n if (!useVariant)\n {\n if (!transposeColumn<vtkDoubleArray, double>(srcTable, destTable, cid))\n {\n if (!transposeColumn<vtkIntArray, int>(srcTable, destTable, cid))\n {\n if (!transposeColumn<vtkStringArray, vtkStdString>(srcTable, destTable, cid))\n {\n if (!transposeColumn<vtkVariantArray, vtkVariant>(srcTable, destTable, cid))\n {\n return false;\n }\n }\n }\n }\n }\n else\n {\n if (!transposeColumn<vtkVariantArray, vtkVariant>(srcTable, destTable, cid, useVariant))\n {\n return false;\n }\n }\n }\n\n return true;\n}\n\n\/\/----------------------------------------------------------------------------\nbool voUtils::transposeTable(vtkTable* table)\n{\n vtkNew<vtkTable> transposedTable;\n bool success = voUtils::transposeTable(table, transposedTable.GetPointer());\n if (!success)\n {\n return false;\n }\n table->ShallowCopy(transposedTable.GetPointer());\n return true;\n}\n\n\/\/----------------------------------------------------------------------------\nbool voUtils::insertColumnIntoTable(vtkTable * table, int position, vtkAbstractArray * columnToInsert)\n{\n if (!table)\n {\n return false;\n }\n if (!columnToInsert)\n {\n return false;\n }\n if (table->GetNumberOfRows() != columnToInsert->GetNumberOfComponents() * columnToInsert->GetNumberOfTuples())\n {\n return false;\n }\n if (position < 0)\n {\n position = 0;\n }\n if (position > table->GetNumberOfColumns())\n {\n position = table->GetNumberOfColumns();\n }\n\n vtkNew<vtkTable> updatedTable;\n for (int cid = 0; cid < table->GetNumberOfColumns(); ++cid)\n {\n vtkAbstractArray * column = table->GetColumn(cid);\n Q_ASSERT(column);\n if (cid == position)\n {\n updatedTable->AddColumn(columnToInsert);\n }\n updatedTable->AddColumn(column);\n }\n if (position == table->GetNumberOfColumns())\n {\n updatedTable->AddColumn(columnToInsert);\n }\n table->ShallowCopy(updatedTable.GetPointer());\n return true;\n}\n\n\/\/----------------------------------------------------------------------------\nvoid voUtils::setTableColumnNames(vtkTable * table, vtkStringArray * columnNames)\n{\n if (!table)\n {\n return;\n }\n if (!columnNames)\n {\n return;\n }\n\n for (int cid = 0; cid < table->GetNumberOfColumns() && cid < columnNames->GetNumberOfValues(); ++cid)\n {\n vtkAbstractArray * column = table->GetColumn(cid);\n Q_ASSERT(column);\n column->SetName(columnNames->GetValue(cid));\n }\n}\n\n\/\/----------------------------------------------------------------------------\nbool voUtils::parseRangeString(const QString& rangeString, QList<int>& rangeList, bool alpha)\n{\n if(!rangeList.empty())\n {\n return false;\n }\n\n if(rangeString.isEmpty())\n {\n return true;\n }\n\n \/\/ Validate - checks for form, not semantics\n QRegExp validRegEx;\n if (!alpha) \/\/ Numbers\n {\n validRegEx.setPattern(\"^(\\\\d+[-,])*\\\\d+$\");\n }\n else \/\/ Letters\n {\n validRegEx.setPattern(\"^([A-Z]+[-,])*[A-Z]+$\");\n validRegEx.setCaseSensitivity(Qt::CaseInsensitive);\n }\n QString scratchString(rangeString);\n scratchString.replace(\" \", \"\");\n if(!validRegEx.exactMatch(scratchString))\n {\n return false;\n }\n\n \/\/ Parse\n QStringList rangeStringList = scratchString.split(\",\");\n rangeStringList.removeDuplicates();\n\n QRegExp rangeRegEx;\n if (!alpha)\n {\n rangeRegEx.setPattern(\"^(\\\\d+)-(\\\\d+)$\");\n }\n else\n {\n rangeRegEx.setPattern(\"^([A-Z]+)-([A-Z]+)$\");\n rangeRegEx.setCaseSensitivity(Qt::CaseInsensitive);\n }\n foreach(const QString& subStr, rangeStringList)\n {\n if(rangeRegEx.indexIn(subStr) != -1)\n {\n int subBegin;\n int subEnd;\n if (!alpha)\n {\n subBegin = rangeRegEx.cap(1).toInt() - 1;\n subEnd = rangeRegEx.cap(2).toInt() - 1;\n }\n else\n {\n subBegin = voUtils::counterAlphaToInt(rangeRegEx.cap(1));\n subEnd = voUtils::counterAlphaToInt(rangeRegEx.cap(2));\n }\n for(int subCtr = subBegin; subCtr <= subEnd; subCtr++)\n {\n rangeList.push_back(subCtr);\n }\n }\n else\n {\n if (!alpha)\n {\n rangeList.push_back(subStr.toInt() - 1);\n }\n else\n {\n rangeList.push_back(voUtils::counterAlphaToInt(subStr));\n }\n }\n }\n\n rangeList = rangeList.toSet().toList(); \/\/ Remove duplicates\n qSort(rangeList);\n\n return true;\n}\n\n\/\/----------------------------------------------------------------------------\nQString voUtils::counterIntToAlpha(int intVal)\n{\n if (intVal < 0)\n {\n return QString();\n }\n else if (intVal < 26)\n {\n return QString(QChar('A' + intVal));\n }\n else\n {\n return voUtils::counterIntToAlpha((intVal \/ 26) - 1) + voUtils::counterIntToAlpha(intVal % 26);\n }\n}\n\n\/\/----------------------------------------------------------------------------\nint voUtils::counterAlphaToInt(const QString& alphaVal)\n{\n if (alphaVal.length() < 1)\n {\n return -1;\n }\n else if (alphaVal.length() == 1)\n {\n return static_cast<int>(alphaVal.toUpper().at(0).toLatin1() - 'A');\n }\n else\n {\n return (voUtils::counterAlphaToInt(alphaVal.mid(0, alphaVal.length()-1)) + 1) * 26\n + voUtils::counterAlphaToInt(alphaVal.mid(alphaVal.length()-1));\n }\n}\n\n<commit_msg>voUtils - Remove unused header<commit_after>\n\/\/ Qt includes\n#include <QtGlobal>\n#include <QStringList>\n#include <QRegExp>\n#include <QSet>\n\n\/\/ Visomics includes\n#include \"voUtils.h\"\n\n\/\/ VTK includes\n#include <vtkDoubleArray.h>\n#include <vtkIntArray.h>\n#include <vtkNew.h>\n#include <vtkSmartPointer.h>\n#include <vtkStringArray.h>\n#include <vtkTable.h>\n#include <vtkVariantArray.h>\n\nnamespace\n{\n\/\/----------------------------------------------------------------------------\ntemplate<typename ArrayType, typename ValueType>\nbool transposeColumn(vtkTable* srcTable, vtkTable* destTable, int columnId, bool useVariant = false)\n{\n if (!srcTable || !destTable)\n {\n return false;\n }\n if (columnId < 0 || columnId >= srcTable->GetNumberOfColumns())\n {\n return false;\n }\n vtkAbstractArray * column = srcTable->GetColumn(columnId);\n ArrayType * typeColumn = ArrayType::SafeDownCast(column);\n if (!typeColumn && !useVariant)\n {\n return false;\n }\n\n for (int rid = 0; rid < column->GetNumberOfTuples() * column->GetNumberOfComponents(); ++rid)\n {\n vtkSmartPointer<ArrayType> transposedColumn;\n if (columnId == 0)\n {\n transposedColumn = vtkSmartPointer<ArrayType>::New();\n transposedColumn->SetNumberOfValues(srcTable->GetNumberOfColumns());\n destTable->AddColumn(transposedColumn);\n }\n else\n {\n transposedColumn = ArrayType::SafeDownCast(destTable->GetColumn(rid));\n }\n Q_ASSERT(transposedColumn);\n if (!useVariant)\n {\n ValueType value = typeColumn->GetValue(rid);\n transposedColumn->SetValue(columnId, value);\n }\n else\n {\n vtkVariant value = column->GetVariantValue(rid);\n transposedColumn->SetVariantValue(columnId, value);\n }\n }\n return true;\n}\n}\n\n\/\/----------------------------------------------------------------------------\nbool voUtils::transposeTable(vtkTable* srcTable, vtkTable* destTable)\n{\n if (!srcTable)\n {\n return false;\n }\n\n if (!destTable)\n {\n return false;\n }\n\n if (srcTable->GetNumberOfColumns() == 0)\n {\n return true;\n }\n\n bool useVariant = false;\n vtkAbstractArray * firstColumn = srcTable->GetColumn(0);\n for (int cid = 1; cid < srcTable->GetNumberOfColumns(); ++cid)\n {\n if (qstrcmp(firstColumn->GetClassName(), srcTable->GetColumn(cid)->GetClassName()) != 0)\n {\n useVariant = true;\n break;\n }\n }\n\n for(int cid = 0; cid < srcTable->GetNumberOfColumns(); ++cid)\n {\n if (!useVariant)\n {\n if (!transposeColumn<vtkDoubleArray, double>(srcTable, destTable, cid))\n {\n if (!transposeColumn<vtkIntArray, int>(srcTable, destTable, cid))\n {\n if (!transposeColumn<vtkStringArray, vtkStdString>(srcTable, destTable, cid))\n {\n if (!transposeColumn<vtkVariantArray, vtkVariant>(srcTable, destTable, cid))\n {\n return false;\n }\n }\n }\n }\n }\n else\n {\n if (!transposeColumn<vtkVariantArray, vtkVariant>(srcTable, destTable, cid, useVariant))\n {\n return false;\n }\n }\n }\n\n return true;\n}\n\n\/\/----------------------------------------------------------------------------\nbool voUtils::transposeTable(vtkTable* table)\n{\n vtkNew<vtkTable> transposedTable;\n bool success = voUtils::transposeTable(table, transposedTable.GetPointer());\n if (!success)\n {\n return false;\n }\n table->ShallowCopy(transposedTable.GetPointer());\n return true;\n}\n\n\/\/----------------------------------------------------------------------------\nbool voUtils::insertColumnIntoTable(vtkTable * table, int position, vtkAbstractArray * columnToInsert)\n{\n if (!table)\n {\n return false;\n }\n if (!columnToInsert)\n {\n return false;\n }\n if (table->GetNumberOfRows() != columnToInsert->GetNumberOfComponents() * columnToInsert->GetNumberOfTuples())\n {\n return false;\n }\n if (position < 0)\n {\n position = 0;\n }\n if (position > table->GetNumberOfColumns())\n {\n position = table->GetNumberOfColumns();\n }\n\n vtkNew<vtkTable> updatedTable;\n for (int cid = 0; cid < table->GetNumberOfColumns(); ++cid)\n {\n vtkAbstractArray * column = table->GetColumn(cid);\n Q_ASSERT(column);\n if (cid == position)\n {\n updatedTable->AddColumn(columnToInsert);\n }\n updatedTable->AddColumn(column);\n }\n if (position == table->GetNumberOfColumns())\n {\n updatedTable->AddColumn(columnToInsert);\n }\n table->ShallowCopy(updatedTable.GetPointer());\n return true;\n}\n\n\/\/----------------------------------------------------------------------------\nvoid voUtils::setTableColumnNames(vtkTable * table, vtkStringArray * columnNames)\n{\n if (!table)\n {\n return;\n }\n if (!columnNames)\n {\n return;\n }\n\n for (int cid = 0; cid < table->GetNumberOfColumns() && cid < columnNames->GetNumberOfValues(); ++cid)\n {\n vtkAbstractArray * column = table->GetColumn(cid);\n Q_ASSERT(column);\n column->SetName(columnNames->GetValue(cid));\n }\n}\n\n\/\/----------------------------------------------------------------------------\nbool voUtils::parseRangeString(const QString& rangeString, QList<int>& rangeList, bool alpha)\n{\n if(!rangeList.empty())\n {\n return false;\n }\n\n if(rangeString.isEmpty())\n {\n return true;\n }\n\n \/\/ Validate - checks for form, not semantics\n QRegExp validRegEx;\n if (!alpha) \/\/ Numbers\n {\n validRegEx.setPattern(\"^(\\\\d+[-,])*\\\\d+$\");\n }\n else \/\/ Letters\n {\n validRegEx.setPattern(\"^([A-Z]+[-,])*[A-Z]+$\");\n validRegEx.setCaseSensitivity(Qt::CaseInsensitive);\n }\n QString scratchString(rangeString);\n scratchString.replace(\" \", \"\");\n if(!validRegEx.exactMatch(scratchString))\n {\n return false;\n }\n\n \/\/ Parse\n QStringList rangeStringList = scratchString.split(\",\");\n rangeStringList.removeDuplicates();\n\n QRegExp rangeRegEx;\n if (!alpha)\n {\n rangeRegEx.setPattern(\"^(\\\\d+)-(\\\\d+)$\");\n }\n else\n {\n rangeRegEx.setPattern(\"^([A-Z]+)-([A-Z]+)$\");\n rangeRegEx.setCaseSensitivity(Qt::CaseInsensitive);\n }\n foreach(const QString& subStr, rangeStringList)\n {\n if(rangeRegEx.indexIn(subStr) != -1)\n {\n int subBegin;\n int subEnd;\n if (!alpha)\n {\n subBegin = rangeRegEx.cap(1).toInt() - 1;\n subEnd = rangeRegEx.cap(2).toInt() - 1;\n }\n else\n {\n subBegin = voUtils::counterAlphaToInt(rangeRegEx.cap(1));\n subEnd = voUtils::counterAlphaToInt(rangeRegEx.cap(2));\n }\n for(int subCtr = subBegin; subCtr <= subEnd; subCtr++)\n {\n rangeList.push_back(subCtr);\n }\n }\n else\n {\n if (!alpha)\n {\n rangeList.push_back(subStr.toInt() - 1);\n }\n else\n {\n rangeList.push_back(voUtils::counterAlphaToInt(subStr));\n }\n }\n }\n\n rangeList = rangeList.toSet().toList(); \/\/ Remove duplicates\n qSort(rangeList);\n\n return true;\n}\n\n\/\/----------------------------------------------------------------------------\nQString voUtils::counterIntToAlpha(int intVal)\n{\n if (intVal < 0)\n {\n return QString();\n }\n else if (intVal < 26)\n {\n return QString(QChar('A' + intVal));\n }\n else\n {\n return voUtils::counterIntToAlpha((intVal \/ 26) - 1) + voUtils::counterIntToAlpha(intVal % 26);\n }\n}\n\n\/\/----------------------------------------------------------------------------\nint voUtils::counterAlphaToInt(const QString& alphaVal)\n{\n if (alphaVal.length() < 1)\n {\n return -1;\n }\n else if (alphaVal.length() == 1)\n {\n return static_cast<int>(alphaVal.toUpper().at(0).toLatin1() - 'A');\n }\n else\n {\n return (voUtils::counterAlphaToInt(alphaVal.mid(0, alphaVal.length()-1)) + 1) * 26\n + voUtils::counterAlphaToInt(alphaVal.mid(alphaVal.length()-1));\n }\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright 2016-2020 Christian Lockley\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n * not use this file except in compliance with the License. You may obtain\n * a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n * implied. See the License for the specific language governing\n * permissions and limitations under the License.\n *\/\n#include \"watchdogd.hpp\"\n#include \"linux.hpp\"\n#include \"watchdog.hpp\"\n#include \"logutils.hpp\"\n\nint Watchdog::Ping()\n{\n\tint tmp = 0;\n\n\tif (ioctl(fd, WDIOC_KEEPALIVE, &tmp) == 0) {\n\t\treturn 0;\n\t}\n\n\tioctl(fd, WDIOC_SETTIMEOUT, &timeout);\n\n\tif (ioctl(fd, WDIOC_KEEPALIVE, &tmp) == 0) {\n\t\treturn 0;\n\t}\n\n\tLogmsg(LOG_ERR, \"WDIOC_KEEPALIVE ioctl failed: %s\", MyStrerror(errno));\n\n\treturn -1;\n}\n\nint Watchdog::Close()\n{\n\tif (fd == -1) {\n\t\treturn 0;\n\t}\n\n\tif (write(fd, \"V\", strlen(\"V\")) < 0) {\n\t\tLogmsg(LOG_CRIT, \"write to watchdog device failed: %s\",\n\t\t MyStrerror(errno));\n\t\tclose(fd);\n\t\tLogmsg(LOG_CRIT, \"unable to close watchdog device\");\n\t\treturn -1;\n\t} else {\n\t\tclose(fd);\n\t}\n\n\treturn 0;\n}\n\nbool Watchdog::CanMagicClose()\n{\n\tstruct watchdog_info watchDogInfo = {0};\n\n\tif (ioctl(fd, WDIOC_GETSUPPORT, &watchDogInfo) < 0) {\n\t\tLogmsg(LOG_ERR, \"%s\", MyStrerror(errno));\n\t\treturn false;\n\t}\n\tif (strcmp((const char*)GetIdentity(),\"iamt_wdt\") == 0) {\n\t\treturn true; \/\/iamt_wdt is broken\n\t}\n\treturn (WDIOF_MAGICCLOSE & watchDogInfo.options);\n}\n\nbool Watchdog::PrintWdtInfo()\n{\n\tstruct watchdog_info watchDogInfo;\n\n\tif (ioctl(fd, WDIOC_GETSUPPORT, &watchDogInfo) < 0) {\n\t\tLogmsg(LOG_ERR, \"%s\", MyStrerror(errno));\n\t} else {\n\t\tif (strcasecmp((const char*)watchDogInfo.identity, \"software watchdog\") != 0) {\n\t\t\tLogmsg(LOG_DEBUG, \"Hardware watchdog '%s', version %u\",\n\t\t\t watchDogInfo.identity, watchDogInfo.firmware_version);\n\t\t} else {\n\t\t\tLogmsg(LOG_DEBUG, \"%s, version %u\",\n\t\t\t watchDogInfo.identity, watchDogInfo.firmware_version);\n\t\t}\n\t\tdev dev;\n\t\tGetDeviceMajorMinor(&dev, (char*)path);\n\t\tLogmsg(LOG_DEBUG, \"Device: %s Major: %li Minor: %li\", path, dev.major, dev.minor);\n\t\treturn true;\n\t}\n\n\treturn false;\n}\n\nunsigned char * Watchdog::GetIdentity()\n{\n\tstatic struct watchdog_info watchDogInfo;\n\n\tthis->Ping();\n\n\tif (ioctl(fd, WDIOC_GETSUPPORT, &watchDogInfo) < 0) {\n\t\tLogmsg(LOG_ERR, \"%s\", MyStrerror(errno));\n\t\treturn NULL;\n\t}\n\n\treturn watchDogInfo.identity;\n}\n\nint Watchdog::Open(const char *const path)\n{\n\tif (path == NULL) {\n\t\treturn -1;\n\t}\n\n\tfd = open(path, O_WRONLY | O_CLOEXEC);\n\n\tif (fd == -1) {\n\n\t\tLogmsg(LOG_ERR,\n\t\t \"unable to open watchdog device: %s\", MyStrerror(errno));\n\t\treturn -1;\n\t}\n\n\tif (this->Ping() != 0) {\n\t\tClose();\n\t\treturn -1;\n\t}\n\n\tif (CanMagicClose() == false) {\n\t\tLogmsg(LOG_ALERT,\n\t\t \"watchdog device does not support magic close char\");\n\t}\n\n\tstrcpy((char *)this->path, path);\n\n\treturn 0;\n}\n\nint Watchdog::GetOptimalPingInterval()\n{\n\tint timeout = 0;\n\n\tif (ioctl(fd, WDIOC_GETTIMEOUT, &timeout) < 0) {\n\t\treturn 1;\n\t}\n\n\ttimeout \/= 2;\n\n\tif (timeout < 1)\n\t\treturn 1;\n\n\treturn timeout;\n}\n\nint Watchdog::Disable()\n{\n\tint options = WDIOS_DISABLECARD;\n\tif (ioctl(fd, WDIOC_SETOPTIONS, &options) < 0) {\n\t\tLogmsg(LOG_CRIT, \"WDIOS_DISABLECARD ioctl failed: %s\",\n\t\t MyStrerror(errno));\n\t\treturn -1;\n\t}\n\n\treturn 0;\n}\n\nint Watchdog::Enable()\n{\n\tint options = WDIOS_ENABLECARD;\n\tif (ioctl(fd, WDIOC_SETOPTIONS, &options) < 0) {\n\t\tLogmsg(LOG_CRIT, \"WDIOS_ENABLECARD ioctl failed: %s\",\n\t\t MyStrerror(errno));\n\t\treturn -1;\n\t}\n\n\treturn 0;\n}\n\nint Watchdog::ConfigureWatchdogTimeout(int timeout)\n{\n\tstruct watchdog_info watchDogInfo;\n\n\tif (timeout <= 0)\n\t\treturn 0;\n\n\tif (Disable() < 0) {\n\t\treturn -1;\n\t}\n\n\tif (ioctl(fd, WDIOC_GETSUPPORT, &watchDogInfo) < 0) {\n\t\tLogmsg(LOG_CRIT, \"WDIOC_GETSUPPORT ioctl failed: %s\",\n\t\t MyStrerror(errno));\n\t\treturn -1;\n\t}\n\n\tif (!(watchDogInfo.options & WDIOF_SETTIMEOUT)) {\n\t\treturn -1;\n\t}\n\n\tint oldTimeout = timeout;\n\n\tif (ioctl(fd, WDIOC_SETTIMEOUT, &timeout) < 0) {\n\t\tthis->timeout = GetOptimalPingInterval();\n\n\t\tfprintf(stderr, \"watchdogd: unable to set WDT timeout\\n\");\n\t\tfprintf(stderr, \"using default: %i\", this->timeout);\n\n\t\tif (Enable() < 0) {\n\t\t\treturn -1;\n\t\t}\n\n\t\treturn Ping();\n\t}\n\n\tif (timeout != oldTimeout) {\n\t\tfprintf(stderr, \"watchdogd: Actual WDT timeout: %i seconds\\n\",\n\t\t\ttimeout);\n\t\tfprintf(stderr,\n\t\t\t\"watchdogd: Timeout specified in the configuration file: %i\\n\",\n\t\t\toldTimeout);\n\t}\n\n\tthis->timeout = timeout;\n\n\tif (Enable() < 0) {\n\t\treturn -1;\n\t}\n\n\treturn Ping();\n}\n\nlong unsigned Watchdog::GetStatus()\n{\n\tlong unsigned status = 0;\n\n\tioctl(fd, WDIOC_GETBOOTSTATUS, &status);\n\n\treturn status;\n}\n\nlong Watchdog::GetFirmwareVersion()\n{\n\tstruct watchdog_info watchDogInfo = {0};\n\n\tioctl(fd, WDIOC_GETSUPPORT, &watchDogInfo);\n\n\treturn watchDogInfo.firmware_version;\n}\n\nlong Watchdog::GetTimeleft()\n{\n\tint timeleft = 0;\n\n\tif (ioctl(fd, WDIOC_GETTIMELEFT, &timeleft) < 0) {\n\t\treturn -1;\n\t}\n\n\treturn timeleft;\n}\n\nint Watchdog::GetRawTimeout()\n{\n\tint timeout = 0;\n\tioctl(fd, WDIOC_GETTIMEOUT, &timeout);\n\treturn timeout;\n}\n\nbool Watchdog::CheckWatchdogTimeout(int timeout)\n{\n\tif (timeout <= this->timeout) {\n\t\treturn false;\n\t}\n\treturn true;\n}\n<commit_msg>ensure timeout is not 0<commit_after>\/*\n * Copyright 2016-2020 Christian Lockley\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n * not use this file except in compliance with the License. You may obtain\n * a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n * implied. See the License for the specific language governing\n * permissions and limitations under the License.\n *\/\n#include \"watchdogd.hpp\"\n#include \"linux.hpp\"\n#include \"watchdog.hpp\"\n#include \"logutils.hpp\"\n\nint Watchdog::Ping()\n{\n\tint tmp = 0;\n\n\tif (ioctl(fd, WDIOC_KEEPALIVE, &tmp) == 0) {\n\t\treturn 0;\n\t}\n\n\tioctl(fd, WDIOC_SETTIMEOUT, &timeout);\n\n\tif (ioctl(fd, WDIOC_KEEPALIVE, &tmp) == 0) {\n\t\treturn 0;\n\t}\n\n\tLogmsg(LOG_ERR, \"WDIOC_KEEPALIVE ioctl failed: %s\", MyStrerror(errno));\n\n\treturn -1;\n}\n\nint Watchdog::Close()\n{\n\tif (fd == -1) {\n\t\treturn 0;\n\t}\n\n\tif (write(fd, \"V\", strlen(\"V\")) < 0) {\n\t\tLogmsg(LOG_CRIT, \"write to watchdog device failed: %s\",\n\t\t MyStrerror(errno));\n\t\tclose(fd);\n\t\tLogmsg(LOG_CRIT, \"unable to close watchdog device\");\n\t\treturn -1;\n\t} else {\n\t\tclose(fd);\n\t}\n\n\treturn 0;\n}\n\nbool Watchdog::CanMagicClose()\n{\n\tstruct watchdog_info watchDogInfo = {0};\n\n\tif (ioctl(fd, WDIOC_GETSUPPORT, &watchDogInfo) < 0) {\n\t\tLogmsg(LOG_ERR, \"%s\", MyStrerror(errno));\n\t\treturn false;\n\t}\n\tif (strcmp((const char*)GetIdentity(),\"iamt_wdt\") == 0) {\n\t\treturn true; \/\/iamt_wdt is broken\n\t}\n\treturn (WDIOF_MAGICCLOSE & watchDogInfo.options);\n}\n\nbool Watchdog::PrintWdtInfo()\n{\n\tstruct watchdog_info watchDogInfo;\n\n\tif (ioctl(fd, WDIOC_GETSUPPORT, &watchDogInfo) < 0) {\n\t\tLogmsg(LOG_ERR, \"%s\", MyStrerror(errno));\n\t} else {\n\t\tif (strcasecmp((const char*)watchDogInfo.identity, \"software watchdog\") != 0) {\n\t\t\tLogmsg(LOG_DEBUG, \"Hardware watchdog '%s', version %u\",\n\t\t\t watchDogInfo.identity, watchDogInfo.firmware_version);\n\t\t} else {\n\t\t\tLogmsg(LOG_DEBUG, \"%s, version %u\",\n\t\t\t watchDogInfo.identity, watchDogInfo.firmware_version);\n\t\t}\n\t\tdev dev;\n\t\tGetDeviceMajorMinor(&dev, (char*)path);\n\t\tLogmsg(LOG_DEBUG, \"Device: %s Major: %li Minor: %li\", path, dev.major, dev.minor);\n\t\treturn true;\n\t}\n\n\treturn false;\n}\n\nunsigned char * Watchdog::GetIdentity()\n{\n\tstatic struct watchdog_info watchDogInfo;\n\n\tthis->Ping();\n\n\tif (ioctl(fd, WDIOC_GETSUPPORT, &watchDogInfo) < 0) {\n\t\tLogmsg(LOG_ERR, \"%s\", MyStrerror(errno));\n\t\treturn NULL;\n\t}\n\n\treturn watchDogInfo.identity;\n}\n\nint Watchdog::Open(const char *const path)\n{\n\tif (path == NULL) {\n\t\treturn -1;\n\t}\n\n\tfd = open(path, O_WRONLY | O_CLOEXEC);\n\n\tif (fd == -1) {\n\n\t\tLogmsg(LOG_ERR,\n\t\t \"unable to open watchdog device: %s\", MyStrerror(errno));\n\t\treturn -1;\n\t}\n\n\tif (this->Ping() != 0) {\n\t\tClose();\n\t\treturn -1;\n\t}\n\n\tif (CanMagicClose() == false) {\n\t\tLogmsg(LOG_ALERT,\n\t\t \"watchdog device does not support magic close char\");\n\t}\n\n\tstrcpy((char *)this->path, path);\n\n\treturn 0;\n}\n\nint Watchdog::GetOptimalPingInterval()\n{\n\tint timeout = 0;\n\n\tif (ioctl(fd, WDIOC_GETTIMEOUT, &timeout) < 0) {\n\t\treturn 1;\n\t}\n\n\ttimeout \/= 2;\n\n\tif (timeout < 1 || timeout == 0)\n\t\treturn 1;\n\n\treturn timeout;\n}\n\nint Watchdog::Disable()\n{\n\tint options = WDIOS_DISABLECARD;\n\tif (ioctl(fd, WDIOC_SETOPTIONS, &options) < 0) {\n\t\tLogmsg(LOG_CRIT, \"WDIOS_DISABLECARD ioctl failed: %s\",\n\t\t MyStrerror(errno));\n\t\treturn -1;\n\t}\n\n\treturn 0;\n}\n\nint Watchdog::Enable()\n{\n\tint options = WDIOS_ENABLECARD;\n\tif (ioctl(fd, WDIOC_SETOPTIONS, &options) < 0) {\n\t\tLogmsg(LOG_CRIT, \"WDIOS_ENABLECARD ioctl failed: %s\",\n\t\t MyStrerror(errno));\n\t\treturn -1;\n\t}\n\n\treturn 0;\n}\n\nint Watchdog::ConfigureWatchdogTimeout(int timeout)\n{\n\tstruct watchdog_info watchDogInfo;\n\n\tif (timeout <= 0)\n\t\treturn 0;\n\n\tif (Disable() < 0) {\n\t\treturn -1;\n\t}\n\n\tif (ioctl(fd, WDIOC_GETSUPPORT, &watchDogInfo) < 0) {\n\t\tLogmsg(LOG_CRIT, \"WDIOC_GETSUPPORT ioctl failed: %s\",\n\t\t MyStrerror(errno));\n\t\treturn -1;\n\t}\n\n\tif (!(watchDogInfo.options & WDIOF_SETTIMEOUT)) {\n\t\treturn -1;\n\t}\n\n\tint oldTimeout = timeout;\n\n\tif (ioctl(fd, WDIOC_SETTIMEOUT, &timeout) < 0) {\n\t\tthis->timeout = GetOptimalPingInterval();\n\n\t\tfprintf(stderr, \"watchdogd: unable to set WDT timeout\\n\");\n\t\tfprintf(stderr, \"using default: %i\", this->timeout);\n\n\t\tif (Enable() < 0) {\n\t\t\treturn -1;\n\t\t}\n\n\t\treturn Ping();\n\t}\n\n\tif (timeout != oldTimeout) {\n\t\tfprintf(stderr, \"watchdogd: Actual WDT timeout: %i seconds\\n\",\n\t\t\ttimeout);\n\t\tfprintf(stderr,\n\t\t\t\"watchdogd: Timeout specified in the configuration file: %i\\n\",\n\t\t\toldTimeout);\n\t}\n\n\tthis->timeout = timeout;\n\n\tif (Enable() < 0) {\n\t\treturn -1;\n\t}\n\n\treturn Ping();\n}\n\nlong unsigned Watchdog::GetStatus()\n{\n\tlong unsigned status = 0;\n\n\tioctl(fd, WDIOC_GETBOOTSTATUS, &status);\n\n\treturn status;\n}\n\nlong Watchdog::GetFirmwareVersion()\n{\n\tstruct watchdog_info watchDogInfo = {0};\n\n\tioctl(fd, WDIOC_GETSUPPORT, &watchDogInfo);\n\n\treturn watchDogInfo.firmware_version;\n}\n\nlong Watchdog::GetTimeleft()\n{\n\tint timeleft = 0;\n\n\tif (ioctl(fd, WDIOC_GETTIMELEFT, &timeleft) < 0) {\n\t\treturn -1;\n\t}\n\n\treturn timeleft;\n}\n\nint Watchdog::GetRawTimeout()\n{\n\tint timeout = 0;\n\tioctl(fd, WDIOC_GETTIMEOUT, &timeout);\n\treturn timeout;\n}\n\nbool Watchdog::CheckWatchdogTimeout(int timeout)\n{\n\tif (timeout <= this->timeout) {\n\t\treturn false;\n\t}\n\treturn true;\n}\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n#include <vector>\n#include <fstream>\n#include <string>\n#include <algorithm>\n\n#include <boost\/lexical_cast.hpp>\n\n#include \"Point.hpp\"\n#include \"Function.hpp\"\n#include \"SymbolicRegressionSolver.hpp\"\n#include \"Config.hpp\"\n\n\/\/#define VERBOSE_LOG\n\nint amountOfSimulationsToPerform = 1;\nSymbolicRegressionSolver::Config config{};\nFunction fn{parse(\"+ 1 x\").statement, \"x\"};\nint initialPoint = -10;\nint endPoint = 10;\nint stepSize = 2;\n\nstd::istream& operator>>(std::istream& is, SymbolicRegressionSolver::Config& config);\nstd::ostream& operator<<(std::ostream& os, const SymbolicRegressionSolver::Config& config);\n\nvoid parseArguments(int argc, char *argv[]);\nvoid printValidFlags()\n{\n std::cout << \"-c <configuration-file> (TODO)\\n\";\n std::cout << \"-f <function>\\n\";\n std::cout << \"-i <initial-point>\\n\";\n std::cout << \"-e <end-point>\\n\";\n std::cout << \"-s <step size>\\n\";\n std::cout << \"-r <amount of times to redo simulation>\\n\";\n}\n\nvoid performSimulation(const PointList& points);\n\nint main(int argc, char *argv[])\n{\n parseArguments(argc, argv);\n\n#ifdef VERBOSE_LOG\n std::clog << \"function: \" << fn << '\\n';\n std::clog << \"initial point: \" << initialPoint << '\\n';\n std::clog << \"end point: \" << endPoint << '\\n';\n std::clog << \"step size: \" << stepSize << '\\n';\n#endif \/\/ VERBOSE_LOG\n\n std::vector<Point> points;\n points.reserve((endPoint - initialPoint)\/stepSize);\n\n VariableMap map;\n for(int i = initialPoint; i <= endPoint; i += stepSize)\n {\n points.emplace_back(i, fn(map, i));\n }\n\n for(int i = 0; i < amountOfSimulationsToPerform; ++i)\n {\n performSimulation(points);\n }\n\n return 0;\n}\n\nvoid performSimulation(const PointList& points)\n{\n SymbolicRegressionSolver solver(config, points);\n auto solutions = solver.solve();\n\n if(!solver.foundSolution())\n {\n\/\/ std::cout << \"No solution!\\n\";\n return;\n }\n\n for(size_t i = 0; i < solutions.size(); ++i)\n {\n auto& solution = solutions[i];\n std::cout << solver.currentGeneration() << \",\";\n\/\/ std::cout << i + 1 << \",\";\n std::cout << solution.fitnessLevel << \",\";\n std::cout << solution.mutated << \",\"; \n std::cout << solution.mated << '\\n';\n\n#ifdef VERBOSE_LOG\n std::cout << \"solution \" << i + 1 << \":\\n\";\n std::cout << \"\\tfunction: \" << solution.function << '\\n';\n std::cout << \"\\tfitness: \" << solution.fitnessLevel << '\\n';\n std::cout << \"\\tmutated?: \" << std::boolalpha << solution.mutated << '\\n';\n std::cout << \"\\tmated?: \" << solution.mated << '\\n';\n#endif \/\/VERBOSE_LOG\n }\n}\n\nvoid parseArguments(int argc, char *argv[])\n{\n for(int i = 1; i < argc; ++i)\n {\n auto command = argv[i];\n auto commandSize = strlen(command);\n if(command[0] != '-')\n {\n std::cout << \"Invalid format: \" << command << \".\\n\";\n std::cout << \"Flags must be prefixed with \\\"-\\\" (without quotes).\\n\";\n std::exit(-2);\n break;\n }\n\n if(commandSize == 1 || commandSize > 2)\n {\n std::cout << \"Invalid flag: \\\"\" << command << \"\\\"\\n\";\n printValidFlags();\n std::exit(-5);\n }\n\n if(i + 1 >= argc)\n {\n std::cout << \"please provide info with a flag...\\n\";\n printValidFlags();\n std::exit(-6);\n }\n\n switch(command[1])\n {\n \/\/ assign function\n case 'f':\n {\n std::string functionAsString;\n for(int j = i + 1; j < argc && argv[j][0] != '-'; ++j, ++i)\n {\n functionAsString += argv[j];\n }\n fn = functionAsString;\n }\n break;\n case 'i':\n {\n std::string str = argv[++i];\n initialPoint = boost::lexical_cast<int>(str);\n }\n break;\n case 'e':\n {\n std::string str = argv[++i];\n endPoint = boost::lexical_cast<int>(str);\n }\n break;\n case 's':\n {\n std::string str = argv[++i];\n stepSize = boost::lexical_cast<int>(str);\n }\n break;\n case 'r':\n {\n std::string str = argv[++i];\n amountOfSimulationsToPerform = boost::lexical_cast<int>(str);\n }\n break;\n case 'c':\n {\n try \n {\n std::string filepath = argv[++i];\n std::ifstream file;\n file.exceptions(std::ifstream::failbit | std::ifstream::badbit);\n file.open(filepath);\n file >> config; \/\/ read the config\n\n \/*\n std::cout << \"Loaded config:\\n\";\n std::cout << config << std::endl;\n *\/\n } \n catch(boost::bad_lexical_cast& e)\n {\n std::cerr << e.what();\n std::exit(5);\n }\n catch(std::exception& e)\n {\n std::cerr << e.what();\n std::exit(6);\n }\n }\n break;\n default:\n std::cout << \"Invalid flag\\n\";\n printValidFlags();\n std::exit(-4);\n break;\n }\n }\n}\n\nnamespace \n{\nstd::string obtainValue(const std::string& line)\n{\n return std::string(line.begin() + line.find_last_of('=') + 1, line.end());\n}\n\ntemplate <class T>\nvoid read(std::string& buffer, std::istream& is, T& value)\n{\n std::getline(is, buffer);\n auto stringValue = obtainValue(buffer);\n stringValue.erase(std::remove_if(stringValue.begin(), stringValue.end(), [](char c) { return std::isspace(c); }), stringValue.end());\n value = boost::lexical_cast<T>(stringValue);\n}\n}\n\nstd::ostream& operator<<(std::ostream& os, const SymbolicRegressionSolver::Config::NearestNeighbourOption& n)\n{\n static constexpr const char* STRINGS[] = { \"Always Use\", \"Never Use\", \"Random\" };\n return os << STRINGS[static_cast<size_t>(n)];\n}\n\nstd::ostream& operator<<(std::ostream& os, const SymbolicRegressionSolver::Config::PopulationRefillOption& p)\n{\n static constexpr const char* STRINGS[] = { \"Refill\", \"Duplicate\", \"Throw Away\" };\n return os << STRINGS[static_cast<size_t>(p)];\n}\n\nstd::ostream& operator<<(std::ostream& os, const SymbolicRegressionSolver::Config& config)\n{\n os << \"initial population = \" << config.initialPopulation << '\\n';\n os << \"max generations = \" << config.maxGenerations << '\\n';\n os << \"initial max depth = \" << config.initialMaxDepth << '\\n';\n os << \"max solution depth = \" << config.maxSolutionDepth << '\\n';\n os << \"keep percent = \" << config.keepPercentage << '\\n';\n os << \"mutation percent = \" << config.mutationPercent << '\\n';\n os << \"mate percent = \" << config.matePercent << '\\n';\n os << \"min constant = \" << config.constantDist.a() << '\\n';\n os << \"max constant = \" << config.constantDist.b() << '\\n';\n os << \"solution criteria = \" << config.solutionCriterea << '\\n';\n os << \"chance to change const = \" << config.chanceToChangeConstant << '\\n';\n os << \"chance to change var = \" << config.chanceToChangeVar << '\\n';\n os << \"nearest neighbour opt = \" << config.nearestNeighbourOption << '\\n';\n os << \"chance to use nearest neighbour = \" << config.chanceToUseNearestNeighbour << '\\n';\n os << \"step size = \" << config.stepSize << '\\n';\n os << \"pop refill opt = \" << config.populationRefillOption << '\\n';\n return os;\n}\n\nstd::istream& operator>>(std::istream& is, SymbolicRegressionSolver::Config& config)\n{\n std::string buffer;\n\n read(buffer, is, config.initialPopulation);\n read(buffer, is, config.maxGenerations);\n read(buffer, is, config.initialMaxDepth);\n read(buffer, is, config.maxSolutionDepth);\n read(buffer, is, config.keepPercentage);\n read(buffer, is, config.mutationPercent);\n read(buffer, is, config.matePercent);\n\n\n \/\/ have to do this separately for const dist\n int a, b;\n read(buffer, is, a);\n read(buffer, is, b);\n\n config.constantDist = decltype(config.constantDist){a, b};\n\n read(buffer, is, config.solutionCriterea);\n read(buffer, is, config.chanceToChangeConstant);\n read(buffer, is, config.chanceToChangeVar);\n \n int nearestNeighbour = 0;\n read(buffer, is, nearestNeighbour);\n config.nearestNeighbourOption = static_cast<decltype(config.nearestNeighbourOption)>(nearestNeighbour);\n\n read(buffer, is, config.chanceToUseNearestNeighbour);\n read(buffer, is, config.stepSize);\n \n int refillOption = 0;\n read(buffer, is, refillOption);\n config.populationRefillOption = static_cast<decltype(config.populationRefillOption)>(refillOption);\n \n return is;\n}\n<commit_msg>Fixed segfault in CLI<commit_after>#include <iostream>\n#include <vector>\n#include <fstream>\n#include <string>\n#include <algorithm>\n\n#include <boost\/lexical_cast.hpp>\n\n#include \"Point.hpp\"\n#include \"Function.hpp\"\n#include \"SymbolicRegressionSolver.hpp\"\n#include \"Config.hpp\"\n\n\/\/#define VERBOSE_LOG\n\nint amountOfSimulationsToPerform = 1;\nSymbolicRegressionSolver::Config config{};\nFunction fn{parse(\"+ 1 x\").statement, \"x\"};\nint initialPoint = -10;\nint endPoint = 10;\nint stepSize = 2;\n\nstd::istream& operator>>(std::istream& is, SymbolicRegressionSolver::Config& config);\nstd::ostream& operator<<(std::ostream& os, const SymbolicRegressionSolver::Config& config);\n\nvoid parseArguments(int argc, char *argv[]);\nvoid printValidFlags()\n{\n std::cout << \"-c <configuration-file> (TODO)\\n\";\n std::cout << \"-f <function>\\n\";\n std::cout << \"-i <initial-point>\\n\";\n std::cout << \"-e <end-point>\\n\";\n std::cout << \"-s <step size>\\n\";\n std::cout << \"-r <amount of times to redo simulation>\\n\";\n}\n\nvoid performSimulation(const PointList& points);\n\nint main(int argc, char *argv[])\n{\n parseArguments(argc, argv);\n\n#ifdef VERBOSE_LOG\n std::clog << \"function: \" << fn << '\\n';\n std::clog << \"initial point: \" << initialPoint << '\\n';\n std::clog << \"end point: \" << endPoint << '\\n';\n std::clog << \"step size: \" << stepSize << '\\n';\n#endif \/\/ VERBOSE_LOG\n\n std::vector<Point> points;\n points.reserve((endPoint - initialPoint)\/stepSize);\n\n VariableMap map;\n for(int i = initialPoint; i <= endPoint; i += stepSize)\n {\n points.emplace_back(i, fn(map, i));\n }\n\n for(int i = 0; i < amountOfSimulationsToPerform; ++i)\n {\n performSimulation(points);\n }\n\n return 0;\n}\n\nvoid performSimulation(const PointList& points)\n{\n SymbolicRegressionSolver solver(config, points);\n auto solutions = solver.solve();\n\n if(!solver.foundSolution())\n {\n\/\/ std::cout << \"No solution!\\n\";\n return;\n }\n\n for(size_t i = 0; i < solutions.size(); ++i)\n {\n auto& solution = solutions[i];\n std::cout << solver.currentGeneration() << \",\";\n\/\/ std::cout << i + 1 << \",\";\n std::cout << solution.fitnessLevel << \",\";\n std::cout << solution.mutated << \",\"; \n std::cout << solution.mated << '\\n';\n\n#ifdef VERBOSE_LOG\n std::cout << \"solution \" << i + 1 << \":\\n\";\n std::cout << \"\\tfunction: \" << solution.function << '\\n';\n std::cout << \"\\tfitness: \" << solution.fitnessLevel << '\\n';\n std::cout << \"\\tmutated?: \" << std::boolalpha << solution.mutated << '\\n';\n std::cout << \"\\tmated?: \" << solution.mated << '\\n';\n#endif \/\/VERBOSE_LOG\n }\n}\n\nvoid parseArguments(int argc, char *argv[])\n{\n for(int i = 1; i < argc; ++i)\n {\n auto command = argv[i];\n auto commandSize = strlen(command);\n if(command[0] != '-')\n {\n std::cout << \"Invalid format: \" << command << \".\\n\";\n std::cout << \"Flags must be prefixed with \\\"-\\\" (without quotes).\\n\";\n std::exit(-2);\n break;\n }\n\n if(commandSize == 1 || commandSize > 2)\n {\n std::cout << \"Invalid flag: \\\"\" << command << \"\\\"\\n\";\n printValidFlags();\n std::exit(-5);\n }\n\n if(i + 1 >= argc)\n {\n std::cout << \"please provide info with a flag...\\n\";\n printValidFlags();\n std::exit(-6);\n }\n\n switch(command[1])\n {\n \/\/ assign function\n case 'f':\n {\n std::string functionAsString;\n for(int j = i + 1; j < argc && argv[j][0] != '-'; ++j, ++i)\n {\n functionAsString += argv[j];\n }\n fn = functionAsString;\n fn = parse(functionAsString).statement;\n }\n break;\n case 'i':\n {\n std::string str = argv[++i];\n initialPoint = boost::lexical_cast<int>(str);\n }\n break;\n case 'e':\n {\n std::string str = argv[++i];\n endPoint = boost::lexical_cast<int>(str);\n }\n break;\n case 's':\n {\n std::string str = argv[++i];\n stepSize = boost::lexical_cast<int>(str);\n }\n break;\n case 'r':\n {\n std::string str = argv[++i];\n amountOfSimulationsToPerform = boost::lexical_cast<int>(str);\n }\n break;\n case 'c':\n {\n try \n {\n std::string filepath = argv[++i];\n std::ifstream file;\n file.exceptions(std::ifstream::failbit | std::ifstream::badbit);\n file.open(filepath);\n file >> config; \/\/ read the config\n\n \/*\n std::cout << \"Loaded config:\\n\";\n std::cout << config << std::endl;\n *\/\n } \n catch(boost::bad_lexical_cast& e)\n {\n std::cerr << e.what();\n std::exit(5);\n }\n catch(std::exception& e)\n {\n std::cerr << e.what();\n std::exit(6);\n }\n }\n break;\n default:\n std::cout << \"Invalid flag\\n\";\n printValidFlags();\n std::exit(-4);\n break;\n }\n }\n}\n\nnamespace \n{\nstd::string obtainValue(const std::string& line)\n{\n return std::string(line.begin() + line.find_last_of('=') + 1, line.end());\n}\n\ntemplate <class T>\nvoid read(std::string& buffer, std::istream& is, T& value)\n{\n std::getline(is, buffer);\n auto stringValue = obtainValue(buffer);\n stringValue.erase(std::remove_if(stringValue.begin(), stringValue.end(), [](char c) { return std::isspace(c); }), stringValue.end());\n value = boost::lexical_cast<T>(stringValue);\n}\n}\n\nstd::ostream& operator<<(std::ostream& os, const SymbolicRegressionSolver::Config::NearestNeighbourOption& n)\n{\n static constexpr const char* STRINGS[] = { \"Always Use\", \"Never Use\", \"Random\" };\n return os << STRINGS[static_cast<size_t>(n)];\n}\n\nstd::ostream& operator<<(std::ostream& os, const SymbolicRegressionSolver::Config::PopulationRefillOption& p)\n{\n static constexpr const char* STRINGS[] = { \"Refill\", \"Duplicate\", \"Throw Away\" };\n return os << STRINGS[static_cast<size_t>(p)];\n}\n\nstd::ostream& operator<<(std::ostream& os, const SymbolicRegressionSolver::Config& config)\n{\n os << \"initial population = \" << config.initialPopulation << '\\n';\n os << \"max generations = \" << config.maxGenerations << '\\n';\n os << \"initial max depth = \" << config.initialMaxDepth << '\\n';\n os << \"max solution depth = \" << config.maxSolutionDepth << '\\n';\n os << \"keep percent = \" << config.keepPercentage << '\\n';\n os << \"mutation percent = \" << config.mutationPercent << '\\n';\n os << \"mate percent = \" << config.matePercent << '\\n';\n os << \"min constant = \" << config.constantDist.a() << '\\n';\n os << \"max constant = \" << config.constantDist.b() << '\\n';\n os << \"solution criteria = \" << config.solutionCriterea << '\\n';\n os << \"chance to change const = \" << config.chanceToChangeConstant << '\\n';\n os << \"chance to change var = \" << config.chanceToChangeVar << '\\n';\n os << \"nearest neighbour opt = \" << config.nearestNeighbourOption << '\\n';\n os << \"chance to use nearest neighbour = \" << config.chanceToUseNearestNeighbour << '\\n';\n os << \"step size = \" << config.stepSize << '\\n';\n os << \"pop refill opt = \" << config.populationRefillOption << '\\n';\n return os;\n}\n\nstd::istream& operator>>(std::istream& is, SymbolicRegressionSolver::Config& config)\n{\n std::string buffer;\n\n read(buffer, is, config.initialPopulation);\n read(buffer, is, config.maxGenerations);\n read(buffer, is, config.initialMaxDepth);\n read(buffer, is, config.maxSolutionDepth);\n read(buffer, is, config.keepPercentage);\n read(buffer, is, config.mutationPercent);\n read(buffer, is, config.matePercent);\n\n\n \/\/ have to do this separately for const dist\n int a, b;\n read(buffer, is, a);\n read(buffer, is, b);\n\n config.constantDist = decltype(config.constantDist){a, b};\n\n read(buffer, is, config.solutionCriterea);\n read(buffer, is, config.chanceToChangeConstant);\n read(buffer, is, config.chanceToChangeVar);\n \n int nearestNeighbour = 0;\n read(buffer, is, nearestNeighbour);\n config.nearestNeighbourOption = static_cast<decltype(config.nearestNeighbourOption)>(nearestNeighbour);\n\n read(buffer, is, config.chanceToUseNearestNeighbour);\n read(buffer, is, config.stepSize);\n \n int refillOption = 0;\n read(buffer, is, refillOption);\n config.populationRefillOption = static_cast<decltype(config.populationRefillOption)>(refillOption);\n \n return is;\n}\n<|endoftext|>"} {"text":"<commit_before><commit_msg>prob2 fast algo<commit_after><|endoftext|>"} {"text":"<commit_before>\/* bzflag\n * Copyright (c) 1993 - 2005 Tim Riker\n *\n * This package is free software; you can redistribute it and\/or\n * modify it under the terms of the license found in the file\n * named COPYING that should have accompanied this file.\n *\n * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR\n * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED\n * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.\n *\/\n\n\/\/ class interface header\n#include \"cURLManager.h\"\n\n\/\/ common implementation headers\n#include \"bzfio.h\"\n\nbool cURLManager::inited = false;\nCURLM *cURLManager::multiHandle = NULL;\nstd::map<CURL*,\n\t cURLManager*> cURLManager::cURLMap;\n\ncURLManager::cURLManager()\n{\n CURLcode result;\n\n theData = NULL;\n theLen = 0;\n errorCode = CURLE_OK;\n added = false;\n\n if (!inited)\n setup();\n\n easyHandle = curl_easy_init();\n if (!easyHandle) {\n DEBUG1(\"Something wrong with CURL\\n\");\n return;\n }\n#if LIBCURL_VERSION_NUM >= 0x070a00\n result = curl_easy_setopt(easyHandle, CURLOPT_NOSIGNAL, true);\n if (result != CURLE_OK) {\n errorCode = result;\n DEBUG1(\"CURLOPT_NOSIGNAL error: %d\\n\", result);\n }\n#endif\n\n result = curl_easy_setopt(easyHandle, CURLOPT_WRITEFUNCTION,\n\t\t\t cURLManager::writeFunction);\n if (result != CURLE_OK)\n DEBUG1(\"CURLOPT_WRITEFUNCTION error: %d\\n\", result);\n\n result = curl_easy_setopt(easyHandle, CURLOPT_WRITEDATA, this);\n if (result != CURLE_OK)\n DEBUG1(\"CURLOPT_WRITEDATA error: %d\\n\", result);\n\n}\n\ncURLManager::~cURLManager()\n{\n if (added)\n removeHandle();\n curl_easy_cleanup(easyHandle);\n free(theData);\n}\n\nvoid cURLManager::setup()\n{\n CURLcode result;\n\n DEBUG1(\"LIBCURL: %s\\n\", curl_version());\n#if LIBCURL_VERSION_NUM >= 0x070a00\n if ((result = curl_global_init(CURL_GLOBAL_NOTHING)))\n DEBUG1(\"cURL Global init Error: %d\\n\", result);\n#endif\n multiHandle = curl_multi_init();\n if (!multiHandle)\n DEBUG1(\"Unexpected error creating multi handle from libcurl \\n\");\n inited = true;\n}\n\nsize_t cURLManager::writeFunction(void *ptr, size_t size, size_t nmemb,\n\t\t\t\t void *stream)\n{\n int len = size * nmemb;\n ((cURLManager*)stream)->collectData((char*)ptr, len);\n return len;\n}\n\nvoid cURLManager::setTimeout(long timeout)\n{\n CURLcode result;\n\n result = curl_easy_setopt(easyHandle, CURLOPT_TIMEOUT, timeout);\n if (result != CURLE_OK) {\n errorCode = result;\n DEBUG1(\"CURLOPT_TIMEOUT error: %d\\n\", result);\n }\n}\n\nvoid cURLManager::setNoBody()\n{\n CURLcode result;\n long nobody = 1;\n\n result = curl_easy_setopt(easyHandle, CURLOPT_NOBODY, nobody);\n if (result != CURLE_OK) {\n errorCode = result;\n DEBUG1(\"CURLOPT_NOBODY error: %d\\n\", result);\n }\n}\n\nvoid cURLManager::setGetMode()\n{\n CURLcode result;\n long get = 1;\n\n result = curl_easy_setopt(easyHandle, CURLOPT_HTTPGET, get);\n if (result != CURLE_OK) {\n errorCode = result;\n DEBUG1(\"CURLOPT_GET error: %d\\n\", result);\n }\n}\n\nvoid cURLManager::setURL(std::string url)\n{\n CURLcode result;\n\n if (url == \"\")\n result = curl_easy_setopt(easyHandle, CURLOPT_URL, NULL);\n else\n result = curl_easy_setopt(easyHandle, CURLOPT_URL, url.c_str());\n if (result != CURLE_OK) {\n errorCode = result;\n DEBUG1(\"CURLOPT_URL error: %d\\n\", result);\n }\n}\n\nvoid cURLManager::setProgressFunction(curl_progress_callback func, void* data)\n{\n CURLcode result;\n if (func != NULL) {\n result = curl_easy_setopt(easyHandle, CURLOPT_PROGRESSFUNCTION, func);\n if (result == CURLE_OK)\n result = curl_easy_setopt(easyHandle, CURLOPT_PROGRESSDATA, data);\n if (result == CURLE_OK)\n result = curl_easy_setopt(easyHandle, CURLOPT_NOPROGRESS, 0);\n } else {\n result = curl_easy_setopt(easyHandle, CURLOPT_NOPROGRESS, 1);\n }\n if (result != CURLE_OK) {\n errorCode = result;\n DEBUG1(\"CURLOPT_SET_PROGRESS error: %d\\n\", result);\n }\n}\n\nvoid cURLManager::setRequestFileTime(bool request)\n{\n CURLcode result;\n long requestFileTime = request ? 1 : 0;\n result = curl_easy_setopt(easyHandle, CURLOPT_FILETIME, requestFileTime);\n if (result != CURLE_OK) {\n errorCode = result;\n DEBUG1(\"CURLOPT_FILETIME error: %d\\n\", result);\n }\n}\n\nvoid cURLManager::addHandle()\n{\n CURLMcode result = curl_multi_add_handle(multiHandle, easyHandle);\n if (result != CURLM_OK)\n DEBUG1(\"Error while adding easy handle from libcurl; Error: %d\\n\", result);\n cURLMap[easyHandle] = this;\n added = true;\n}\n\nvoid cURLManager::removeHandle()\n{\n if (!added)\n return;\n cURLMap.erase(easyHandle);\n CURLMcode result = curl_multi_remove_handle(multiHandle, easyHandle);\n if (result != CURLM_OK)\n DEBUG1(\"Error while removing easy handle from libcurl; Error: %d\\n\", result);\n added = false;\n}\n\nvoid cURLManager::finalization(char *, unsigned int, bool)\n{\n}\n\nvoid cURLManager::collectData(char* ptr, int len)\n{\n unsigned char *newData = (unsigned char *)realloc(theData, theLen + len);\n if (!newData) {\n DEBUG1(\"memory exhausted\\n\");\n } else {\n memcpy(newData + theLen, ptr, len);\n theLen += len;\n theData = newData;\n }\n}\n\nint cURLManager::perform()\n{\n if (!inited)\n setup();\n\n int activeTransfers = 0;\n CURLMcode result;\n while (true) {\n result = curl_multi_perform(multiHandle, &activeTransfers);\n if (result != CURLM_CALL_MULTI_PERFORM)\n break;\n }\n if (result != CURLM_OK)\n DEBUG1(\"Error while doing multi_perform from libcurl; Error: %d\\n\", result);\n\n int msgs_in_queue;\n CURLMsg *pendingMsg;\n CURL *easy;\n\n\n while (true) {\n pendingMsg = curl_multi_info_read(multiHandle, &msgs_in_queue);\n if (!pendingMsg)\n break;\n\n easy = pendingMsg->easy_handle;\n\n cURLMap[easy]->infoComplete(pendingMsg->data.result);\n\n if (msgs_in_queue <= 0)\n break;\n }\n\n return activeTransfers;\n}\n\nvoid cURLManager::infoComplete(CURLcode result)\n{\n if (result != CURLE_OK)\n DEBUG1(\"File transfer terminated with error from libcurl; Error: %d\\n\", result);\n finalization((char *)theData, theLen, result == CURLE_OK);\n free(theData);\n removeHandle();\n theData = NULL;\n theLen = 0;\n}\n\nbool cURLManager::getFileTime(time_t &t)\n{\n long filetime;\n CURLcode result;\n result = curl_easy_getinfo(easyHandle, CURLINFO_FILETIME, &filetime);\n if (result) {\n DEBUG1(\"CURLINFO_FILETIME error: %d\\n\", result);\n return false;\n }\n t = (time_t)filetime;\n return true;\n}\n\n\/\/ Local Variables: ***\n\/\/ mode:C++ ***\n\/\/ tab-width: 8 ***\n\/\/ c-basic-offset: 2 ***\n\/\/ indent-tabs-mode: t ***\n\/\/ End: ***\n\/\/ ex: shiftwidth=2 tabstop=8\n<commit_msg>Stay in the notify table until destroyed. Avoid some SEGV<commit_after>\/* bzflag\n * Copyright (c) 1993 - 2005 Tim Riker\n *\n * This package is free software; you can redistribute it and\/or\n * modify it under the terms of the license found in the file\n * named COPYING that should have accompanied this file.\n *\n * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR\n * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED\n * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.\n *\/\n\n\/\/ class interface header\n#include \"cURLManager.h\"\n\n\/\/ common implementation headers\n#include \"bzfio.h\"\n\nbool cURLManager::inited = false;\nCURLM *cURLManager::multiHandle = NULL;\nstd::map<CURL*,\n\t cURLManager*> cURLManager::cURLMap;\n\ncURLManager::cURLManager()\n{\n CURLcode result;\n\n theData = NULL;\n theLen = 0;\n errorCode = CURLE_OK;\n added = false;\n\n if (!inited)\n setup();\n\n easyHandle = curl_easy_init();\n if (!easyHandle) {\n DEBUG1(\"Something wrong with CURL\\n\");\n return;\n }\n#if LIBCURL_VERSION_NUM >= 0x070a00\n result = curl_easy_setopt(easyHandle, CURLOPT_NOSIGNAL, true);\n if (result != CURLE_OK) {\n errorCode = result;\n DEBUG1(\"CURLOPT_NOSIGNAL error: %d\\n\", result);\n }\n#endif\n\n result = curl_easy_setopt(easyHandle, CURLOPT_WRITEFUNCTION,\n\t\t\t cURLManager::writeFunction);\n if (result != CURLE_OK)\n DEBUG1(\"CURLOPT_WRITEFUNCTION error: %d\\n\", result);\n\n result = curl_easy_setopt(easyHandle, CURLOPT_WRITEDATA, this);\n if (result != CURLE_OK)\n DEBUG1(\"CURLOPT_WRITEDATA error: %d\\n\", result);\n\n cURLMap[easyHandle] = this;\n}\n\ncURLManager::~cURLManager()\n{\n if (added)\n removeHandle();\n cURLMap.erase(easyHandle);\n curl_easy_cleanup(easyHandle);\n free(theData);\n}\n\nvoid cURLManager::setup()\n{\n CURLcode result;\n\n DEBUG1(\"LIBCURL: %s\\n\", curl_version());\n#if LIBCURL_VERSION_NUM >= 0x070a00\n if ((result = curl_global_init(CURL_GLOBAL_NOTHING)))\n DEBUG1(\"cURL Global init Error: %d\\n\", result);\n#endif\n multiHandle = curl_multi_init();\n if (!multiHandle)\n DEBUG1(\"Unexpected error creating multi handle from libcurl \\n\");\n inited = true;\n}\n\nsize_t cURLManager::writeFunction(void *ptr, size_t size, size_t nmemb,\n\t\t\t\t void *stream)\n{\n int len = size * nmemb;\n ((cURLManager*)stream)->collectData((char*)ptr, len);\n return len;\n}\n\nvoid cURLManager::setTimeout(long timeout)\n{\n CURLcode result;\n\n result = curl_easy_setopt(easyHandle, CURLOPT_TIMEOUT, timeout);\n if (result != CURLE_OK) {\n errorCode = result;\n DEBUG1(\"CURLOPT_TIMEOUT error: %d\\n\", result);\n }\n}\n\nvoid cURLManager::setNoBody()\n{\n CURLcode result;\n long nobody = 1;\n\n result = curl_easy_setopt(easyHandle, CURLOPT_NOBODY, nobody);\n if (result != CURLE_OK) {\n errorCode = result;\n DEBUG1(\"CURLOPT_NOBODY error: %d\\n\", result);\n }\n}\n\nvoid cURLManager::setGetMode()\n{\n CURLcode result;\n long get = 1;\n\n result = curl_easy_setopt(easyHandle, CURLOPT_HTTPGET, get);\n if (result != CURLE_OK) {\n errorCode = result;\n DEBUG1(\"CURLOPT_GET error: %d\\n\", result);\n }\n}\n\nvoid cURLManager::setURL(std::string url)\n{\n CURLcode result;\n\n if (url == \"\")\n result = curl_easy_setopt(easyHandle, CURLOPT_URL, NULL);\n else\n result = curl_easy_setopt(easyHandle, CURLOPT_URL, url.c_str());\n if (result != CURLE_OK) {\n errorCode = result;\n DEBUG1(\"CURLOPT_URL error: %d\\n\", result);\n }\n}\n\nvoid cURLManager::setProgressFunction(curl_progress_callback func, void* data)\n{\n CURLcode result;\n if (func != NULL) {\n result = curl_easy_setopt(easyHandle, CURLOPT_PROGRESSFUNCTION, func);\n if (result == CURLE_OK)\n result = curl_easy_setopt(easyHandle, CURLOPT_PROGRESSDATA, data);\n if (result == CURLE_OK)\n result = curl_easy_setopt(easyHandle, CURLOPT_NOPROGRESS, 0);\n } else {\n result = curl_easy_setopt(easyHandle, CURLOPT_NOPROGRESS, 1);\n }\n if (result != CURLE_OK) {\n errorCode = result;\n DEBUG1(\"CURLOPT_SET_PROGRESS error: %d\\n\", result);\n }\n}\n\nvoid cURLManager::setRequestFileTime(bool request)\n{\n CURLcode result;\n long requestFileTime = request ? 1 : 0;\n result = curl_easy_setopt(easyHandle, CURLOPT_FILETIME, requestFileTime);\n if (result != CURLE_OK) {\n errorCode = result;\n DEBUG1(\"CURLOPT_FILETIME error: %d\\n\", result);\n }\n}\n\nvoid cURLManager::addHandle()\n{\n CURLMcode result = curl_multi_add_handle(multiHandle, easyHandle);\n if (result != CURLM_OK)\n DEBUG1(\"Error while adding easy handle from libcurl; Error: %d\\n\", result);\n added = true;\n}\n\nvoid cURLManager::removeHandle()\n{\n if (!added)\n return;\n CURLMcode result = curl_multi_remove_handle(multiHandle, easyHandle);\n if (result != CURLM_OK)\n DEBUG1(\"Error while removing easy handle from libcurl; Error: %d\\n\", result);\n added = false;\n}\n\nvoid cURLManager::finalization(char *, unsigned int, bool)\n{\n}\n\nvoid cURLManager::collectData(char* ptr, int len)\n{\n unsigned char *newData = (unsigned char *)realloc(theData, theLen + len);\n if (!newData) {\n DEBUG1(\"memory exhausted\\n\");\n } else {\n memcpy(newData + theLen, ptr, len);\n theLen += len;\n theData = newData;\n }\n}\n\nint cURLManager::perform()\n{\n if (!inited)\n setup();\n\n int activeTransfers = 0;\n CURLMcode result;\n while (true) {\n result = curl_multi_perform(multiHandle, &activeTransfers);\n if (result != CURLM_CALL_MULTI_PERFORM)\n break;\n }\n if (result != CURLM_OK)\n DEBUG1(\"Error while doing multi_perform from libcurl; Error: %d\\n\", result);\n\n int msgs_in_queue;\n CURLMsg *pendingMsg;\n CURL *easy;\n\n\n while (true) {\n pendingMsg = curl_multi_info_read(multiHandle, &msgs_in_queue);\n if (!pendingMsg)\n break;\n\n easy = pendingMsg->easy_handle;\n\n cURLMap[easy]->infoComplete(pendingMsg->data.result);\n\n if (msgs_in_queue <= 0)\n break;\n }\n\n return activeTransfers;\n}\n\nvoid cURLManager::infoComplete(CURLcode result)\n{\n if (result != CURLE_OK)\n DEBUG1(\"File transfer terminated with error from libcurl; Error: %d\\n\", result);\n finalization((char *)theData, theLen, result == CURLE_OK);\n free(theData);\n removeHandle();\n theData = NULL;\n theLen = 0;\n}\n\nbool cURLManager::getFileTime(time_t &t)\n{\n long filetime;\n CURLcode result;\n result = curl_easy_getinfo(easyHandle, CURLINFO_FILETIME, &filetime);\n if (result) {\n DEBUG1(\"CURLINFO_FILETIME error: %d\\n\", result);\n return false;\n }\n t = (time_t)filetime;\n return true;\n}\n\n\/\/ Local Variables: ***\n\/\/ mode:C++ ***\n\/\/ tab-width: 8 ***\n\/\/ c-basic-offset: 2 ***\n\/\/ indent-tabs-mode: t ***\n\/\/ End: ***\n\/\/ ex: shiftwidth=2 tabstop=8\n<|endoftext|>"} {"text":"<commit_before>\n#include \"Block.h\"\n\nnamespace common {\nnamespace entity {\n\nBlock::Block(QPoint position) :\n Entity(position, true, true, \"res\/block.png\") {\n\n}\n\nvoid Block::Update(std::weak_ptr<GameEngine> game_engine, int t) {\n (void) game_engine;\n (void) t;\n}\n\nvoid Block::HitByFire(std::weak_ptr<GameEngine> game_engine) {\n \/* Called when entity is hit by fire. *\/\n \/\/ TODO : add bonus creation\n (void) game_engine;\n should_be_removed_ = true;\n}\n\nvoid Block::Serialize(QDataStream& stream) const {\n SerializeBaseEntity(stream, EntityId::kBlockId); \/\/othing else to do\n}\n\nbool Block::operator==(const Block& other) const {\n return Entity::operator==(other);\n}\n\n\n}\n}\n<commit_msg>Typo.<commit_after>\n#include \"Block.h\"\n\nnamespace common {\nnamespace entity {\n\nBlock::Block(QPoint position) :\n Entity(position, true, true, \"res\/block.png\") {\n\n}\n\nvoid Block::Update(std::weak_ptr<GameEngine> game_engine, int t) {\n (void) game_engine;\n (void) t;\n}\n\nvoid Block::HitByFire(std::weak_ptr<GameEngine> game_engine) {\n \/* Called when entity is hit by fire. *\/\n \/\/ TODO : add bonus creation\n (void) game_engine;\n should_be_removed_ = true;\n}\n\nvoid Block::Serialize(QDataStream& stream) const {\n SerializeBaseEntity(stream, EntityId::kBlockId); \/\/nothing else to do\n}\n\nbool Block::operator==(const Block& other) const {\n return Entity::operator==(other);\n}\n\n\n}\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ This file is a part of the IncludeOS unikernel - www.includeos.org\n\/\/\n\/\/ Copyright 2015 Oslo and Akershus University College of Applied Sciences\n\/\/ and Alfred Bratterud\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include <os>\n#include <net\/inet4>\n#include <net\/dhcp\/dh4client.hpp>\n#include <math.h> \/\/ rand()\n#include <sstream>\n\n\/\/ An IP-stack object\nstd::unique_ptr<net::Inet4<VirtioNet> > inet;\n\nusing namespace std::chrono;\n\nstd::string HTML_RESPONSE() {\n int color = rand();\n std::stringstream stream;\n\n \/* HTML Fonts *\/\n std::string ubuntu_medium = \"font-family: \\'Ubuntu\\', sans-serif; font-weight: 500; \";\n std::string ubuntu_normal = \"font-family: \\'Ubuntu\\', sans-serif; font-weight: 400; \";\n std::string ubuntu_light = \"font-family: \\'Ubuntu\\', sans-serif; font-weight: 300; \";\n\n \/* HTML *\/\n stream << \"<html><head>\"\n << \"<link href='https:\/\/fonts.googleapis.com\/css?family=Ubuntu:500,300' rel='stylesheet' type='text\/css'>\"\n << \"<\/head><body>\"\n << \"<h1 style= \\\"color: \" << \"#\" << std::hex << (color >> 8) << \"\\\">\"\n << \"<span style=\\\"\"+ubuntu_medium+\"\\\">Include<\/span><span style=\\\"\"+ubuntu_light+\"\\\">OS<\/span> <\/h1>\"\n << \"<h2>Now speaks TCP!<\/h2>\"\n \/\/ .... generate more dynamic content\n << \"<p> ...and can improvise http. With limitations of course, but it's been easier than expected so far <\/p>\"\n << \"<footer><hr \/> © 2015, Oslo and Akershus University College of Applied Sciences <\/footer>\"\n << \"<\/body><\/html>\\n\";\n\n std::string html = stream.str();\n\n std::string header=\"HTTP\/1.1 200 OK \\n \" \\\n \"Date: Mon, 01 Jan 1970 00:00:01 GMT \\n\" \\\n \"Server: IncludeOS prototype 4.0 \\n\" \\\n \"Last-Modified: Wed, 08 Jan 2003 23:11:55 GMT \\n\" \\\n \"Content-Type: text\/html; charset=UTF-8 \\n\" \\\n \"Content-Length: \"+std::to_string(html.size())+\"\\n\" \\\n \"Accept-Ranges: bytes\\n\" \\\n \"Connection: close\\n\\n\";\n return header + html;\n}\n\nconst std::string NOT_FOUND = \"HTTP\/1.1 404 Not Found \\n Connection: close\\n\\n\";\n\nvoid Service::start() {\n \/\/ Assign a driver (VirtioNet) to a network interface (eth0)\n \/\/ @note: We could determine the appropirate driver dynamically, but then we'd\n \/\/ have to include all the drivers into the image, which we want to avoid.\n hw::Nic<VirtioNet>& eth0 = hw::Dev::eth<0,VirtioNet>();\n\n \/\/ Bring up a network stack, attached to the nic\n \/\/ @note : No parameters after 'nic' means we'll use DHCP for IP config.\n inet = std::make_unique<net::Inet4<VirtioNet> >(eth0);\n\n \/\/ Static IP configuration, until we (possibly) get DHCP\n \/\/ @note : Mostly to get a robust demo service that it works with and without DHCP\n inet->network_config( { 10,0,0,42 }, \/\/ IP\n { 255,255,255,0 }, \/\/ Netmask\n { 10,0,0,1 }, \/\/ Gateway\n { 8,8,8,8 } ); \/\/ DNS\n\n srand(OS::cycles_since_boot());\n\n \/\/ Set up a TCP server on port 80\n auto& server = inet->tcp().bind(80);\n\n hw::PIT::instance().onRepeatedTimeout(30s, []{\n printf(\"<Service> TCP STATUS:\\n%s \\n\", inet->tcp().status().c_str());\n });\n\n \/\/ Add a TCP connection handler - here a hardcoded HTTP-service\n server.onAccept([] (auto conn) -> bool {\n printf(\"<Service> @onAccept - Connection attempt from: %s \\n\",\n conn->to_string().c_str());\n return true; \/\/ allow all connections\n\n }).onConnect([] (auto conn) {\n printf(\"<Service> @onConnect - Connection successfully established.\\n\");\n \/\/ read async with a buffer size of 1024 bytes\n \/\/ define what to do when data is read\n conn->read(1024, [conn](net::TCP::buffer_t buf, size_t n) {\n \/\/ create string from buffer\n std::string data { (char*)buf.get(), n };\n printf(\"<Service> @read:\\n%s\\n\", data.c_str());\n\n if (data.find(\"GET \/ \") != std::string::npos) {\n\n \/\/ create response\n std::string response = HTML_RESPONSE();\n \/\/ write the data from the string with the strings size\n conn->write(response.data(), response.size(), [](size_t n) {\n printf(\"<Service> @write: %u bytes written\\n\", n);\n });\n }\n else {\n conn->write(NOT_FOUND.data(), NOT_FOUND.size());\n }\n });\n\n }).onDisconnect([](auto conn, auto reason) {\n printf(\"<Service> @onDisconnect - Reason: %s \\n\", reason.to_string().c_str());\n conn->close();\n }).onPacketReceived([](auto, auto packet) {\n printf(\"@Packet: %s\\n\", packet->to_string().c_str());\n });\n\n printf(\"*** TEST SERVICE STARTED *** \\n\");\n}\n<commit_msg>examples: added more debug on demo<commit_after>\/\/ This file is a part of the IncludeOS unikernel - www.includeos.org\n\/\/\n\/\/ Copyright 2015 Oslo and Akershus University College of Applied Sciences\n\/\/ and Alfred Bratterud\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include <os>\n#include <net\/inet4>\n#include <net\/dhcp\/dh4client.hpp>\n#include <math.h> \/\/ rand()\n#include <sstream>\n\n\/\/ An IP-stack object\nstd::unique_ptr<net::Inet4<VirtioNet> > inet;\n\nusing namespace std::chrono;\n\nstd::string HTML_RESPONSE() {\n int color = rand();\n std::stringstream stream;\n\n \/* HTML Fonts *\/\n std::string ubuntu_medium = \"font-family: \\'Ubuntu\\', sans-serif; font-weight: 500; \";\n std::string ubuntu_normal = \"font-family: \\'Ubuntu\\', sans-serif; font-weight: 400; \";\n std::string ubuntu_light = \"font-family: \\'Ubuntu\\', sans-serif; font-weight: 300; \";\n\n \/* HTML *\/\n stream << \"<html><head>\"\n << \"<link href='https:\/\/fonts.googleapis.com\/css?family=Ubuntu:500,300' rel='stylesheet' type='text\/css'>\"\n << \"<\/head><body>\"\n << \"<h1 style= \\\"color: \" << \"#\" << std::hex << (color >> 8) << \"\\\">\"\n << \"<span style=\\\"\"+ubuntu_medium+\"\\\">Include<\/span><span style=\\\"\"+ubuntu_light+\"\\\">OS<\/span> <\/h1>\"\n << \"<h2>Now speaks TCP!<\/h2>\"\n \/\/ .... generate more dynamic content\n << \"<p> ...and can improvise http. With limitations of course, but it's been easier than expected so far <\/p>\"\n << \"<footer><hr \/> © 2015, Oslo and Akershus University College of Applied Sciences <\/footer>\"\n << \"<\/body><\/html>\\n\";\n\n std::string html = stream.str();\n\n std::string header=\"HTTP\/1.1 200 OK \\n \" \\\n \"Date: Mon, 01 Jan 1970 00:00:01 GMT \\n\" \\\n \"Server: IncludeOS prototype 4.0 \\n\" \\\n \"Last-Modified: Wed, 08 Jan 2003 23:11:55 GMT \\n\" \\\n \"Content-Type: text\/html; charset=UTF-8 \\n\" \\\n \"Content-Length: \"+std::to_string(html.size())+\"\\n\" \\\n \"Accept-Ranges: bytes\\n\" \\\n \"Connection: close\\n\\n\";\n return header + html;\n}\n\nconst std::string NOT_FOUND = \"HTTP\/1.1 404 Not Found \\nConnection: close\\n\\n\";\n\nvoid Service::start() {\n \/\/ Assign a driver (VirtioNet) to a network interface (eth0)\n \/\/ @note: We could determine the appropirate driver dynamically, but then we'd\n \/\/ have to include all the drivers into the image, which we want to avoid.\n hw::Nic<VirtioNet>& eth0 = hw::Dev::eth<0,VirtioNet>();\n\n \/\/ Bring up a network stack, attached to the nic\n \/\/ @note : No parameters after 'nic' means we'll use DHCP for IP config.\n inet = std::make_unique<net::Inet4<VirtioNet> >(eth0);\n\n \/\/ Static IP configuration, until we (possibly) get DHCP\n \/\/ @note : Mostly to get a robust demo service that it works with and without DHCP\n inet->network_config( { 10,0,0,42 }, \/\/ IP\n { 255,255,255,0 }, \/\/ Netmask\n { 10,0,0,1 }, \/\/ Gateway\n { 8,8,8,8 } ); \/\/ DNS\n\n srand(OS::cycles_since_boot());\n\n \/\/ Set up a TCP server on port 80\n auto& server = inet->tcp().bind(80);\n\n hw::PIT::instance().on_repeated_timeout(30s, []{\n printf(\"<Service> TCP STATUS:\\n%s \\n\", inet->tcp().status().c_str());\n });\n\n \/\/ Add a TCP connection handler - here a hardcoded HTTP-service\n server.onAccept([] (auto conn) -> bool {\n printf(\"<Service> @onAccept - Connection attempt from: %s \\n\",\n conn->to_string().c_str());\n return true; \/\/ allow all connections\n\n })\n .onConnect([] (auto conn) {\n printf(\"<Service> @onConnect - Connection successfully established.\\n\");\n \/\/ read async with a buffer size of 1024 bytes\n \/\/ define what to do when data is read\n conn->read(1024, [conn](net::TCP::buffer_t buf, size_t n) {\n \/\/ create string from buffer\n std::string data { (char*)buf.get(), n };\n printf(\"<Service> @read:\\n%s\\n\", data.c_str());\n\n if (data.find(\"GET \/ \") != std::string::npos) {\n\n \/\/ create response\n std::string response = HTML_RESPONSE();\n \/\/ write the data from the string with the strings size\n conn->write(response.data(), response.size(), [](size_t n) {\n printf(\"<Service> @write: %u bytes written\\n\", n);\n });\n }\n else {\n conn->write(NOT_FOUND.data(), NOT_FOUND.size());\n }\n });\n\n })\n .onDisconnect([](auto conn, auto reason) {\n printf(\"<Service> @onDisconnect - Reason: %s \\n\", reason.to_string().c_str());\n conn->close();\n })\n .onPacketReceived([](auto, auto packet) {\n printf(\"@Packet: %s\\n\", packet->to_string().c_str());\n })\n .onError([](auto, auto err) {\n printf(\"<Service> @onError - %s\\n\", err.what());\n });\n\n printf(\"*** TEST SERVICE STARTED *** \\n\");\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (C) 2017 ScyllaDB\n *\/\n\n\/*\n * This file is part of Scylla.\n *\n * Scylla is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * Scylla is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with Scylla. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n\n#pragma once\n\n#include \"types.hh\"\n#include \"bytes.hh\"\n\n#include <optional>\n#include <variant>\n\n#include <seastar\/util\/variant_utils.hh>\n\n#include \"utils\/fragmented_temporary_buffer.hh\"\n\nnamespace cql3 {\n\nstruct null_value {\n};\n\nstruct unset_value {\n};\n\nclass raw_value;\n\/\/\/ \\brief View to a raw CQL protocol value.\n\/\/\/\n\/\/\/ \\see raw_value\nstruct raw_value_view {\n std::variant<fragmented_temporary_buffer::view, null_value, unset_value> _data;\n \/\/ Temporary storage is only useful if a raw_value_view needs to be instantiated\n \/\/ with a value which lifetime is bounded only to the view itself.\n \/\/ This hack is introduced in order to avoid storing temporary storage\n \/\/ in an external container, which may cause memory leaking problems.\n \/\/ This pointer is disengaged for regular raw_value_view instances.\n \/\/ Data is stored in a shared pointer for two reasons:\n \/\/ - pointers are cheap to copy\n \/\/ - it makes the view keep its semantics - it's safe to copy a view multiple times\n \/\/ and all copies still refer to the same underlying data.\n lw_shared_ptr<bytes> _temporary_storage = nullptr;\n\n raw_value_view(null_value&& data)\n : _data{std::move(data)}\n {}\n raw_value_view(unset_value&& data)\n : _data{std::move(data)}\n {}\n raw_value_view(fragmented_temporary_buffer::view data)\n : _data{data}\n {}\n \/\/ This constructor is only used by make_temporary() and it acquires ownership\n \/\/ of the given buffer. The view created that way refers to its own temporary storage.\n explicit raw_value_view(bytes&& temporary_storage);\npublic:\n static raw_value_view make_null() {\n return raw_value_view{std::move(null_value{})};\n }\n static raw_value_view make_unset_value() {\n return raw_value_view{std::move(unset_value{})};\n }\n static raw_value_view make_value(fragmented_temporary_buffer::view view) {\n return raw_value_view{view};\n }\n static raw_value_view make_temporary(raw_value&& value);\n bool is_null() const {\n return std::holds_alternative<null_value>(_data);\n }\n bool is_unset_value() const {\n return std::holds_alternative<unset_value>(_data);\n }\n bool is_value() const {\n return std::holds_alternative<fragmented_temporary_buffer::view>(_data);\n }\n std::optional<fragmented_temporary_buffer::view> data() const {\n if (auto pdata = std::get_if<fragmented_temporary_buffer::view>(&_data)) {\n return *pdata;\n }\n return {};\n }\n explicit operator bool() const {\n return is_value();\n }\n const fragmented_temporary_buffer::view* operator->() const {\n return &std::get<fragmented_temporary_buffer::view>(_data);\n }\n const fragmented_temporary_buffer::view& operator*() const {\n return std::get<fragmented_temporary_buffer::view>(_data);\n }\n\n bool operator==(const raw_value_view& other) const {\n if (_data.index() != other._data.index()) {\n return false;\n }\n if (is_value() && **this != *other) {\n return false;\n }\n return true;\n }\n bool operator!=(const raw_value_view& other) const {\n return !(*this == other);\n }\n\n friend std::ostream& operator<<(std::ostream& os, const raw_value_view& value);\n};\n\n\/\/\/ \\brief Raw CQL protocol value.\n\/\/\/\n\/\/\/ The `raw_value` type represents an uninterpreted value from the CQL wire\n\/\/\/ protocol. A raw value can hold either a null value, an unset value, or a byte\n\/\/\/ blob that represents the value.\nclass raw_value {\n std::variant<bytes, null_value, unset_value> _data;\n\n raw_value(null_value&& data)\n : _data{std::move(data)}\n {}\n raw_value(unset_value&& data)\n : _data{std::move(data)}\n {}\n raw_value(bytes&& data)\n : _data{std::move(data)}\n {}\n raw_value(const bytes& data)\n : _data{data}\n {}\npublic:\n static raw_value make_null() {\n return raw_value{std::move(null_value{})};\n }\n static raw_value make_unset_value() {\n return raw_value{std::move(unset_value{})};\n }\n static raw_value make_value(const raw_value_view& view);\n static raw_value make_value(bytes&& bytes) {\n return raw_value{std::move(bytes)};\n }\n static raw_value make_value(const bytes& bytes) {\n return raw_value{bytes};\n }\n static raw_value make_value(const bytes_opt& bytes) {\n if (bytes) {\n return make_value(*bytes);\n }\n return make_null();\n }\n bool is_null() const {\n return std::holds_alternative<null_value>(_data);\n }\n bool is_unset_value() const {\n return std::holds_alternative<unset_value>(_data);\n }\n bool is_value() const {\n return std::holds_alternative<bytes>(_data);\n }\n bytes_opt data() const {\n if (auto pdata = std::get_if<bytes>(&_data)) {\n return *pdata;\n }\n return {};\n }\n explicit operator bool() const {\n return is_value();\n }\n const bytes* operator->() const {\n return &std::get<bytes>(_data);\n }\n const bytes& operator*() const {\n return std::get<bytes>(_data);\n }\n bytes&& extract_value() && {\n auto b = std::get_if<bytes>(&_data);\n assert(b);\n return std::move(*b);\n }\n raw_value_view to_view() const;\n};\n\n}\n\ninline bytes to_bytes(const cql3::raw_value_view& view)\n{\n return linearized(*view);\n}\n\ninline bytes_opt to_bytes_opt(const cql3::raw_value_view& view) {\n auto buffer_view = view.data();\n if (buffer_view) {\n return bytes_opt(linearized(*buffer_view));\n }\n return bytes_opt();\n}\n\ninline bytes_opt to_bytes_opt(const cql3::raw_value& value) {\n return to_bytes_opt(value.to_view());\n}\n<commit_msg>cql3: values: add an internals-independent API to raw_value_view<commit_after>\/*\n * Copyright (C) 2017 ScyllaDB\n *\/\n\n\/*\n * This file is part of Scylla.\n *\n * Scylla is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * Scylla is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with Scylla. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n\n#pragma once\n\n#include \"types.hh\"\n#include \"types\/collection.hh\"\n#include \"bytes.hh\"\n\n#include <optional>\n#include <variant>\n\n#include <seastar\/util\/variant_utils.hh>\n\n#include \"utils\/fragmented_temporary_buffer.hh\"\n\nnamespace cql3 {\n\nstruct null_value {\n};\n\nstruct unset_value {\n};\n\nclass raw_value;\n\/\/\/ \\brief View to a raw CQL protocol value.\n\/\/\/\n\/\/\/ \\see raw_value\nstruct raw_value_view {\n std::variant<fragmented_temporary_buffer::view, null_value, unset_value> _data;\n \/\/ Temporary storage is only useful if a raw_value_view needs to be instantiated\n \/\/ with a value which lifetime is bounded only to the view itself.\n \/\/ This hack is introduced in order to avoid storing temporary storage\n \/\/ in an external container, which may cause memory leaking problems.\n \/\/ This pointer is disengaged for regular raw_value_view instances.\n \/\/ Data is stored in a shared pointer for two reasons:\n \/\/ - pointers are cheap to copy\n \/\/ - it makes the view keep its semantics - it's safe to copy a view multiple times\n \/\/ and all copies still refer to the same underlying data.\n lw_shared_ptr<bytes> _temporary_storage = nullptr;\n\n raw_value_view(null_value&& data)\n : _data{std::move(data)}\n {}\n raw_value_view(unset_value&& data)\n : _data{std::move(data)}\n {}\n raw_value_view(fragmented_temporary_buffer::view data)\n : _data{data}\n {}\n \/\/ This constructor is only used by make_temporary() and it acquires ownership\n \/\/ of the given buffer. The view created that way refers to its own temporary storage.\n explicit raw_value_view(bytes&& temporary_storage);\npublic:\n static raw_value_view make_null() {\n return raw_value_view{std::move(null_value{})};\n }\n static raw_value_view make_unset_value() {\n return raw_value_view{std::move(unset_value{})};\n }\n static raw_value_view make_value(fragmented_temporary_buffer::view view) {\n return raw_value_view{view};\n }\n static raw_value_view make_value(bytes_view view) {\n return raw_value_view{fragmented_temporary_buffer::view(view)};\n }\n static raw_value_view make_temporary(raw_value&& value);\n bool is_null() const {\n return std::holds_alternative<null_value>(_data);\n }\n bool is_unset_value() const {\n return std::holds_alternative<unset_value>(_data);\n }\n bool is_value() const {\n return std::holds_alternative<fragmented_temporary_buffer::view>(_data);\n }\n std::optional<fragmented_temporary_buffer::view> data() const {\n if (auto pdata = std::get_if<fragmented_temporary_buffer::view>(&_data)) {\n return *pdata;\n }\n return {};\n }\n explicit operator bool() const {\n return is_value();\n }\n const fragmented_temporary_buffer::view* operator->() const {\n return &std::get<fragmented_temporary_buffer::view>(_data);\n }\n const fragmented_temporary_buffer::view& operator*() const {\n return std::get<fragmented_temporary_buffer::view>(_data);\n }\n\n bool operator==(const raw_value_view& other) const {\n if (_data.index() != other._data.index()) {\n return false;\n }\n if (is_value() && **this != *other) {\n return false;\n }\n return true;\n }\n bool operator!=(const raw_value_view& other) const {\n return !(*this == other);\n }\n\n template <typename Func>\n requires std::invocable<Func, const managed_bytes_view&> && std::invocable<Func, const fragmented_temporary_buffer::view&>\n decltype(auto) with_value(Func f) const {\n return f(std::get<fragmented_temporary_buffer::view>(_data));\n }\n\n template <typename Func>\n requires std::invocable<Func, bytes_view>\n decltype(auto) with_linearized(Func f) const {\n return with_value([&] (const FragmentedView auto& v) {\n return ::with_linearized(v, std::forward<Func>(f));\n });\n }\n\n size_t size_bytes() const {\n return with_value([&] (const FragmentedView auto& v) {\n return v.size_bytes();\n });\n }\n\n template <typename ValueType>\n ValueType deserialize(const abstract_type& t) const {\n return value_cast<ValueType>(with_value([&] (const FragmentedView auto& v) { return t.deserialize(v); }));\n }\n\n template <typename ValueType>\n ValueType deserialize(const collection_type_impl& t, cql_serialization_format sf) const {\n return value_cast<ValueType>(with_value([&] (const FragmentedView auto& v) { return t.deserialize(v, sf); }));\n }\n\n void validate(const abstract_type& t, cql_serialization_format sf) const {\n return with_value([&] (const FragmentedView auto& v) { return t.validate(v, sf); });\n }\n\n template <typename ValueType>\n ValueType validate_and_deserialize(const collection_type_impl& t, cql_serialization_format sf) const {\n return with_value([&] (const FragmentedView auto& v) {\n t.validate(v, sf);\n return value_cast<ValueType>(t.deserialize(v, sf));\n });\n }\n\n template <typename ValueType>\n ValueType validate_and_deserialize(const abstract_type& t, cql_serialization_format sf) const {\n return with_value([&] (const FragmentedView auto& v) {\n t.validate(v, sf);\n return value_cast<ValueType>(t.deserialize(v));\n });\n }\n\n friend std::ostream& operator<<(std::ostream& os, const raw_value_view& value);\n};\n\n\/\/\/ \\brief Raw CQL protocol value.\n\/\/\/\n\/\/\/ The `raw_value` type represents an uninterpreted value from the CQL wire\n\/\/\/ protocol. A raw value can hold either a null value, an unset value, or a byte\n\/\/\/ blob that represents the value.\nclass raw_value {\n std::variant<bytes, null_value, unset_value> _data;\n\n raw_value(null_value&& data)\n : _data{std::move(data)}\n {}\n raw_value(unset_value&& data)\n : _data{std::move(data)}\n {}\n raw_value(bytes&& data)\n : _data{std::move(data)}\n {}\n raw_value(const bytes& data)\n : _data{data}\n {}\npublic:\n static raw_value make_null() {\n return raw_value{std::move(null_value{})};\n }\n static raw_value make_unset_value() {\n return raw_value{std::move(unset_value{})};\n }\n static raw_value make_value(const raw_value_view& view);\n static raw_value make_value(bytes&& bytes) {\n return raw_value{std::move(bytes)};\n }\n static raw_value make_value(const bytes& bytes) {\n return raw_value{bytes};\n }\n static raw_value make_value(const bytes_opt& bytes) {\n if (bytes) {\n return make_value(*bytes);\n }\n return make_null();\n }\n bool is_null() const {\n return std::holds_alternative<null_value>(_data);\n }\n bool is_unset_value() const {\n return std::holds_alternative<unset_value>(_data);\n }\n bool is_value() const {\n return std::holds_alternative<bytes>(_data);\n }\n bytes_opt data() const {\n if (auto pdata = std::get_if<bytes>(&_data)) {\n return *pdata;\n }\n return {};\n }\n explicit operator bool() const {\n return is_value();\n }\n const bytes* operator->() const {\n return &std::get<bytes>(_data);\n }\n const bytes& operator*() const {\n return std::get<bytes>(_data);\n }\n bytes&& extract_value() && {\n auto b = std::get_if<bytes>(&_data);\n assert(b);\n return std::move(*b);\n }\n bytes to_bytes() && {\n return std::move(std::get<bytes>(_data));\n }\n raw_value_view to_view() const;\n};\n\n}\n\ninline bytes to_bytes(const cql3::raw_value_view& view)\n{\n return linearized(*view);\n}\n\ninline bytes_opt to_bytes_opt(const cql3::raw_value_view& view) {\n auto buffer_view = view.data();\n if (buffer_view) {\n return bytes_opt(linearized(*buffer_view));\n }\n return bytes_opt();\n}\n\ninline bytes_opt to_bytes_opt(const cql3::raw_value& value) {\n return to_bytes_opt(value.to_view());\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ Copyright (c) 2002-2010 The ANGLE Project Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\/\/\n\n#include \"compiler\/PoolAlloc.h\"\n\n#ifndef _MSC_VER\n#include <stdint.h>\n#endif\n#include <stdio.h>\n\n#include \"compiler\/InitializeGlobals.h\"\n#include \"compiler\/osinclude.h\"\n\nOS_TLSIndex PoolIndex = OS_INVALID_TLS_INDEX;\n\nvoid InitializeGlobalPools()\n{\n TThreadGlobalPools* globalPools= static_cast<TThreadGlobalPools*>(OS_GetTLSValue(PoolIndex)); \n if (globalPools)\n return;\n\n TThreadGlobalPools* threadData = new TThreadGlobalPools();\n threadData->globalPoolAllocator = 0;\n\n OS_SetTLSValue(PoolIndex, threadData);\n}\n\nvoid FreeGlobalPools()\n{\n \/\/ Release the allocated memory for this thread.\n TThreadGlobalPools* globalPools= static_cast<TThreadGlobalPools*>(OS_GetTLSValue(PoolIndex)); \n if (!globalPools)\n return;\n \n delete globalPools;\n}\n\nbool InitializePoolIndex()\n{\n \/\/ Allocate a TLS index.\n if ((PoolIndex = OS_AllocTLSIndex()) == OS_INVALID_TLS_INDEX)\n return false;\n\n return true;\n}\n\nvoid FreePoolIndex()\n{\n \/\/ Release the TLS index.\n OS_FreeTLSIndex(PoolIndex);\n}\n\nTPoolAllocator& GetGlobalPoolAllocator()\n{\n TThreadGlobalPools* threadData = static_cast<TThreadGlobalPools*>(OS_GetTLSValue(PoolIndex));\n\n return *threadData->globalPoolAllocator;\n}\n\nvoid SetGlobalPoolAllocator(TPoolAllocator* poolAllocator)\n{\n TThreadGlobalPools* threadData = static_cast<TThreadGlobalPools*>(OS_GetTLSValue(PoolIndex));\n\n threadData->globalPoolAllocator = poolAllocator;\n}\n\n\/\/\n\/\/ Implement the functionality of the TPoolAllocator class, which\n\/\/ is documented in PoolAlloc.h.\n\/\/\nTPoolAllocator::TPoolAllocator(int growthIncrement, int allocationAlignment) : \n pageSize(growthIncrement),\n alignment(allocationAlignment),\n freeList(0),\n inUseList(0),\n numCalls(0),\n totalBytes(0)\n{\n \/\/\n \/\/ Don't allow page sizes we know are smaller than all common\n \/\/ OS page sizes.\n \/\/\n if (pageSize < 4*1024)\n pageSize = 4*1024;\n\n \/\/\n \/\/ A large currentPageOffset indicates a new page needs to\n \/\/ be obtained to allocate memory.\n \/\/\n currentPageOffset = pageSize;\n\n \/\/\n \/\/ Adjust alignment to be at least pointer aligned and\n \/\/ power of 2.\n \/\/\n size_t minAlign = sizeof(void*);\n alignment &= ~(minAlign - 1);\n if (alignment < minAlign)\n alignment = minAlign;\n size_t a = 1;\n while (a < alignment)\n a <<= 1;\n alignment = a;\n alignmentMask = a - 1;\n\n \/\/\n \/\/ Align header skip\n \/\/\n headerSkip = minAlign;\n if (headerSkip < sizeof(tHeader)) {\n headerSkip = (sizeof(tHeader) + alignmentMask) & ~alignmentMask;\n }\n}\n\nTPoolAllocator::~TPoolAllocator()\n{\n while (inUseList) {\n tHeader* next = inUseList->nextPage;\n inUseList->~tHeader();\n delete [] reinterpret_cast<char*>(inUseList);\n inUseList = next;\n }\n\n \/\/ We should not check the guard blocks\n \/\/ here, because we did it already when the block was\n \/\/ placed into the free list.\n \/\/\n while (freeList) {\n tHeader* next = freeList->nextPage;\n delete [] reinterpret_cast<char*>(freeList);\n freeList = next;\n }\n}\n\n\/\/ Support MSVC++ 6.0\nconst unsigned char TAllocation::guardBlockBeginVal = 0xfb;\nconst unsigned char TAllocation::guardBlockEndVal = 0xfe;\nconst unsigned char TAllocation::userDataFill = 0xcd;\n\n#ifdef GUARD_BLOCKS\n const size_t TAllocation::guardBlockSize = 16;\n#else\n const size_t TAllocation::guardBlockSize = 0;\n#endif\n\n\/\/\n\/\/ Check a single guard block for damage\n\/\/\nvoid TAllocation::checkGuardBlock(unsigned char* blockMem, unsigned char val, const char* locText) const\n{\n#ifdef GUARD_BLOCKS\n for (size_t x = 0; x < guardBlockSize; x++) {\n if (blockMem[x] != val) {\n char assertMsg[80];\n\n \/\/ We don't print the assert message. It's here just to be helpful.\n sprintf(assertMsg, \"PoolAlloc: Damage %s %Iu byte allocation at 0x%p\\n\",\n locText, size, data());\n assert(0 && \"PoolAlloc: Damage in guard block\");\n }\n }\n#endif\n}\n\n\nvoid TPoolAllocator::push()\n{\n tAllocState state = { currentPageOffset, inUseList };\n\n stack.push_back(state);\n \n \/\/\n \/\/ Indicate there is no current page to allocate from.\n \/\/\n currentPageOffset = pageSize;\n}\n\n\/\/\n\/\/ Do a mass-deallocation of all the individual allocations\n\/\/ that have occurred since the last push(), or since the\n\/\/ last pop(), or since the object's creation.\n\/\/\n\/\/ The deallocated pages are saved for future allocations.\n\/\/\nvoid TPoolAllocator::pop()\n{\n if (stack.size() < 1)\n return;\n\n tHeader* page = stack.back().page;\n currentPageOffset = stack.back().offset;\n\n while (inUseList != page) {\n \/\/ invoke destructor to free allocation list\n inUseList->~tHeader();\n \n tHeader* nextInUse = inUseList->nextPage;\n if (inUseList->pageCount > 1)\n delete [] reinterpret_cast<char*>(inUseList);\n else {\n inUseList->nextPage = freeList;\n freeList = inUseList;\n }\n inUseList = nextInUse;\n }\n\n stack.pop_back();\n}\n\n\/\/\n\/\/ Do a mass-deallocation of all the individual allocations\n\/\/ that have occurred.\n\/\/\nvoid TPoolAllocator::popAll()\n{\n while (stack.size() > 0)\n pop();\n}\n\nvoid* TPoolAllocator::allocate(size_t numBytes)\n{\n \/\/ If we are using guard blocks, all allocations are bracketed by\n \/\/ them: [guardblock][allocation][guardblock]. numBytes is how\n \/\/ much memory the caller asked for. allocationSize is the total\n \/\/ size including guard blocks. In release build,\n \/\/ guardBlockSize=0 and this all gets optimized away.\n size_t allocationSize = TAllocation::allocationSize(numBytes);\n \n \/\/\n \/\/ Just keep some interesting statistics.\n \/\/\n ++numCalls;\n totalBytes += numBytes;\n\n \/\/\n \/\/ Do the allocation, most likely case first, for efficiency.\n \/\/ This step could be moved to be inline sometime.\n \/\/\n if (currentPageOffset + allocationSize <= pageSize) {\n \/\/\n \/\/ Safe to allocate from currentPageOffset.\n \/\/\n unsigned char* memory = reinterpret_cast<unsigned char *>(inUseList) + currentPageOffset;\n currentPageOffset += allocationSize;\n currentPageOffset = (currentPageOffset + alignmentMask) & ~alignmentMask;\n\n return initializeAllocation(inUseList, memory, numBytes);\n }\n\n if (allocationSize + headerSkip > pageSize) {\n \/\/\n \/\/ Do a multi-page allocation. Don't mix these with the others.\n \/\/ The OS is efficient and allocating and free-ing multiple pages.\n \/\/\n size_t numBytesToAlloc = allocationSize + headerSkip;\n tHeader* memory = reinterpret_cast<tHeader*>(::new char[numBytesToAlloc]);\n if (memory == 0)\n return 0;\n\n \/\/ Use placement-new to initialize header\n new(memory) tHeader(inUseList, (numBytesToAlloc + pageSize - 1) \/ pageSize);\n inUseList = memory;\n\n currentPageOffset = pageSize; \/\/ make next allocation come from a new page\n\n \/\/ No guard blocks for multi-page allocations (yet)\n return reinterpret_cast<void*>(reinterpret_cast<uintptr_t>(memory) + headerSkip);\n }\n\n \/\/\n \/\/ Need a simple page to allocate from.\n \/\/\n tHeader* memory;\n if (freeList) {\n memory = freeList;\n freeList = freeList->nextPage;\n } else {\n memory = reinterpret_cast<tHeader*>(::new char[pageSize]);\n if (memory == 0)\n return 0;\n }\n\n \/\/ Use placement-new to initialize header\n new(memory) tHeader(inUseList, 1);\n inUseList = memory;\n \n unsigned char* ret = reinterpret_cast<unsigned char *>(inUseList) + headerSkip;\n currentPageOffset = (headerSkip + allocationSize + alignmentMask) & ~alignmentMask;\n\n return initializeAllocation(inUseList, ret, numBytes);\n}\n\n\n\/\/\n\/\/ Check all allocations in a list for damage by calling check on each.\n\/\/\nvoid TAllocation::checkAllocList() const\n{\n for (const TAllocation* alloc = this; alloc != 0; alloc = alloc->prevAlloc)\n alloc->check();\n}\n<commit_msg>Fix printf format specifier in PoolAlloc.cpp.<commit_after>\/\/\n\/\/ Copyright (c) 2002-2010 The ANGLE Project Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\/\/\n\n#include \"compiler\/PoolAlloc.h\"\n\n#ifndef _MSC_VER\n#include <stdint.h>\n#endif\n#include <stdio.h>\n\n#include \"compiler\/InitializeGlobals.h\"\n#include \"compiler\/osinclude.h\"\n\nOS_TLSIndex PoolIndex = OS_INVALID_TLS_INDEX;\n\nvoid InitializeGlobalPools()\n{\n TThreadGlobalPools* globalPools= static_cast<TThreadGlobalPools*>(OS_GetTLSValue(PoolIndex)); \n if (globalPools)\n return;\n\n TThreadGlobalPools* threadData = new TThreadGlobalPools();\n threadData->globalPoolAllocator = 0;\n\n OS_SetTLSValue(PoolIndex, threadData);\n}\n\nvoid FreeGlobalPools()\n{\n \/\/ Release the allocated memory for this thread.\n TThreadGlobalPools* globalPools= static_cast<TThreadGlobalPools*>(OS_GetTLSValue(PoolIndex)); \n if (!globalPools)\n return;\n \n delete globalPools;\n}\n\nbool InitializePoolIndex()\n{\n \/\/ Allocate a TLS index.\n if ((PoolIndex = OS_AllocTLSIndex()) == OS_INVALID_TLS_INDEX)\n return false;\n\n return true;\n}\n\nvoid FreePoolIndex()\n{\n \/\/ Release the TLS index.\n OS_FreeTLSIndex(PoolIndex);\n}\n\nTPoolAllocator& GetGlobalPoolAllocator()\n{\n TThreadGlobalPools* threadData = static_cast<TThreadGlobalPools*>(OS_GetTLSValue(PoolIndex));\n\n return *threadData->globalPoolAllocator;\n}\n\nvoid SetGlobalPoolAllocator(TPoolAllocator* poolAllocator)\n{\n TThreadGlobalPools* threadData = static_cast<TThreadGlobalPools*>(OS_GetTLSValue(PoolIndex));\n\n threadData->globalPoolAllocator = poolAllocator;\n}\n\n\/\/\n\/\/ Implement the functionality of the TPoolAllocator class, which\n\/\/ is documented in PoolAlloc.h.\n\/\/\nTPoolAllocator::TPoolAllocator(int growthIncrement, int allocationAlignment) : \n pageSize(growthIncrement),\n alignment(allocationAlignment),\n freeList(0),\n inUseList(0),\n numCalls(0),\n totalBytes(0)\n{\n \/\/\n \/\/ Don't allow page sizes we know are smaller than all common\n \/\/ OS page sizes.\n \/\/\n if (pageSize < 4*1024)\n pageSize = 4*1024;\n\n \/\/\n \/\/ A large currentPageOffset indicates a new page needs to\n \/\/ be obtained to allocate memory.\n \/\/\n currentPageOffset = pageSize;\n\n \/\/\n \/\/ Adjust alignment to be at least pointer aligned and\n \/\/ power of 2.\n \/\/\n size_t minAlign = sizeof(void*);\n alignment &= ~(minAlign - 1);\n if (alignment < minAlign)\n alignment = minAlign;\n size_t a = 1;\n while (a < alignment)\n a <<= 1;\n alignment = a;\n alignmentMask = a - 1;\n\n \/\/\n \/\/ Align header skip\n \/\/\n headerSkip = minAlign;\n if (headerSkip < sizeof(tHeader)) {\n headerSkip = (sizeof(tHeader) + alignmentMask) & ~alignmentMask;\n }\n}\n\nTPoolAllocator::~TPoolAllocator()\n{\n while (inUseList) {\n tHeader* next = inUseList->nextPage;\n inUseList->~tHeader();\n delete [] reinterpret_cast<char*>(inUseList);\n inUseList = next;\n }\n\n \/\/ We should not check the guard blocks\n \/\/ here, because we did it already when the block was\n \/\/ placed into the free list.\n \/\/\n while (freeList) {\n tHeader* next = freeList->nextPage;\n delete [] reinterpret_cast<char*>(freeList);\n freeList = next;\n }\n}\n\n\/\/ Support MSVC++ 6.0\nconst unsigned char TAllocation::guardBlockBeginVal = 0xfb;\nconst unsigned char TAllocation::guardBlockEndVal = 0xfe;\nconst unsigned char TAllocation::userDataFill = 0xcd;\n\n#ifdef GUARD_BLOCKS\n const size_t TAllocation::guardBlockSize = 16;\n#else\n const size_t TAllocation::guardBlockSize = 0;\n#endif\n\n\/\/\n\/\/ Check a single guard block for damage\n\/\/\nvoid TAllocation::checkGuardBlock(unsigned char* blockMem, unsigned char val, const char* locText) const\n{\n#ifdef GUARD_BLOCKS\n for (size_t x = 0; x < guardBlockSize; x++) {\n if (blockMem[x] != val) {\n char assertMsg[80];\n\n \/\/ We don't print the assert message. It's here just to be helpful.\n#if defined(_MSC_VER)\n sprintf(assertMsg, \"PoolAlloc: Damage %s %Iu byte allocation at 0x%p\\n\",\n locText, size, data());\n#else\n sprintf(assertMsg, \"PoolAlloc: Damage %s %z byte allocation at 0x%p\\n\",\n locText, size, data());\n#endif\n assert(0 && \"PoolAlloc: Damage in guard block\");\n }\n }\n#endif\n}\n\n\nvoid TPoolAllocator::push()\n{\n tAllocState state = { currentPageOffset, inUseList };\n\n stack.push_back(state);\n \n \/\/\n \/\/ Indicate there is no current page to allocate from.\n \/\/\n currentPageOffset = pageSize;\n}\n\n\/\/\n\/\/ Do a mass-deallocation of all the individual allocations\n\/\/ that have occurred since the last push(), or since the\n\/\/ last pop(), or since the object's creation.\n\/\/\n\/\/ The deallocated pages are saved for future allocations.\n\/\/\nvoid TPoolAllocator::pop()\n{\n if (stack.size() < 1)\n return;\n\n tHeader* page = stack.back().page;\n currentPageOffset = stack.back().offset;\n\n while (inUseList != page) {\n \/\/ invoke destructor to free allocation list\n inUseList->~tHeader();\n \n tHeader* nextInUse = inUseList->nextPage;\n if (inUseList->pageCount > 1)\n delete [] reinterpret_cast<char*>(inUseList);\n else {\n inUseList->nextPage = freeList;\n freeList = inUseList;\n }\n inUseList = nextInUse;\n }\n\n stack.pop_back();\n}\n\n\/\/\n\/\/ Do a mass-deallocation of all the individual allocations\n\/\/ that have occurred.\n\/\/\nvoid TPoolAllocator::popAll()\n{\n while (stack.size() > 0)\n pop();\n}\n\nvoid* TPoolAllocator::allocate(size_t numBytes)\n{\n \/\/ If we are using guard blocks, all allocations are bracketed by\n \/\/ them: [guardblock][allocation][guardblock]. numBytes is how\n \/\/ much memory the caller asked for. allocationSize is the total\n \/\/ size including guard blocks. In release build,\n \/\/ guardBlockSize=0 and this all gets optimized away.\n size_t allocationSize = TAllocation::allocationSize(numBytes);\n \n \/\/\n \/\/ Just keep some interesting statistics.\n \/\/\n ++numCalls;\n totalBytes += numBytes;\n\n \/\/\n \/\/ Do the allocation, most likely case first, for efficiency.\n \/\/ This step could be moved to be inline sometime.\n \/\/\n if (currentPageOffset + allocationSize <= pageSize) {\n \/\/\n \/\/ Safe to allocate from currentPageOffset.\n \/\/\n unsigned char* memory = reinterpret_cast<unsigned char *>(inUseList) + currentPageOffset;\n currentPageOffset += allocationSize;\n currentPageOffset = (currentPageOffset + alignmentMask) & ~alignmentMask;\n\n return initializeAllocation(inUseList, memory, numBytes);\n }\n\n if (allocationSize + headerSkip > pageSize) {\n \/\/\n \/\/ Do a multi-page allocation. Don't mix these with the others.\n \/\/ The OS is efficient and allocating and free-ing multiple pages.\n \/\/\n size_t numBytesToAlloc = allocationSize + headerSkip;\n tHeader* memory = reinterpret_cast<tHeader*>(::new char[numBytesToAlloc]);\n if (memory == 0)\n return 0;\n\n \/\/ Use placement-new to initialize header\n new(memory) tHeader(inUseList, (numBytesToAlloc + pageSize - 1) \/ pageSize);\n inUseList = memory;\n\n currentPageOffset = pageSize; \/\/ make next allocation come from a new page\n\n \/\/ No guard blocks for multi-page allocations (yet)\n return reinterpret_cast<void*>(reinterpret_cast<uintptr_t>(memory) + headerSkip);\n }\n\n \/\/\n \/\/ Need a simple page to allocate from.\n \/\/\n tHeader* memory;\n if (freeList) {\n memory = freeList;\n freeList = freeList->nextPage;\n } else {\n memory = reinterpret_cast<tHeader*>(::new char[pageSize]);\n if (memory == 0)\n return 0;\n }\n\n \/\/ Use placement-new to initialize header\n new(memory) tHeader(inUseList, 1);\n inUseList = memory;\n \n unsigned char* ret = reinterpret_cast<unsigned char *>(inUseList) + headerSkip;\n currentPageOffset = (headerSkip + allocationSize + alignmentMask) & ~alignmentMask;\n\n return initializeAllocation(inUseList, ret, numBytes);\n}\n\n\n\/\/\n\/\/ Check all allocations in a list for damage by calling check on each.\n\/\/\nvoid TAllocation::checkAllocList() const\n{\n for (const TAllocation* alloc = this; alloc != 0; alloc = alloc->prevAlloc)\n alloc->check();\n}\n<|endoftext|>"} {"text":"<commit_before>#include <openlane\/component_provider.h>\n#include <openlane\/module.h>\n#include <iostream>\n#include <string>\n\ntypedef uint32_t (*ComponentFn)(void *ctx);\nComponentFn LCT;\n\nnamespace openlane {\n\nstd::string MakeModuleName(const char* name) {\n std::string module(\"lib\");\n module.append(name);\n module.append(\".so\");\n return module;\n}\n\nstd::string MakeConfigName(const char* name) {\n std::string config(name);\n config.append(\".xml\");\n return config;\n}\n\n\nComponentProvider::ComponentProvider() :\n xml_parser(this)\n{\n}\n\nComponentProvider::~ComponentProvider() {\n ComponentReverseIterator b = modules.rbegin();\n ComponentReverseIterator e = modules.rend();\n\n for(;b != e; ++b) {\n ErrorCode res = (*b)->GetSymbol(\"UnloadComponent\", LCT);\n if (Ok == res)\n LCT(this); \/\/ FIXME\n }\n}\n\nErrorCode ComponentProvider::LoadComponent(const char* filename) {\n\n ErrorCode res = Ok;\n try\n {\n DynamicLibraryPtr module(new DynamicLibrary);\n res = module->Load(filename);\n std::cout << \"LoadComponent\\tLoad(\" << filename << \")=\" << res << std::endl;\n\n if (Ok == res)\n res = module->GetSymbol(\"LoadComponent\", LCT);\n\n if (Ok == res)\n if (LCT(this) == 0) res = Ok; \/\/ FIXME\n\n if (Ok == res)\n modules.push_back(module);\n }\n catch(const std::bad_alloc&)\n {\n res = NoMemory;\n }\n\n return res;\n}\n\nErrorCode ComponentProvider::Initialize(const char* filename) {\n configs.push_back(std::string(filename));\n std::cout << \"ComponentProvider::Initialize\\tname1=\" << *configs.begin() << std::endl;\n\n while(!configs.empty()) {\n std::cout << \"ComponentProvider::Initialize\\tname=\" << *configs.begin() << std::endl;\n LoadConfig(configs.begin()->c_str());\n configs.erase(configs.begin());\n }\n return Ok;\n}\n\nErrorCode ComponentProvider::LoadConfig(const char* filename) {\n if (!filename)\n return InvalidArgument;\n\n ErrorCode result = xml_parser.Parse(filename);\n if (result != Ok)\n return result;\n\n return Ok;\n}\n\nErrorCode ComponentProvider::RegisterComponent(uint32_t id, CreateComponentFn fun) {\n std::cout << \"ComponentProvider::RegisterComponent\\tid=\" << id << std::endl;\n dic[id] = fun;\n return Ok;\n}\n\nErrorCode ComponentProvider::UnregisterComponent(uint32_t id) {\n std::cout << \"ComponentProvider::UnregisterComponent\\tid=\" << id << std::endl;\n return Ok;\n}\n\nvoid ComponentProvider::OnLoadComponent(const char* name) {\n std::string module_name = MakeModuleName(name);\n std::cout << \"ComponentProvider::OnLoadComponent\\tname=\" << module_name << std::endl;\n LoadComponent(module_name.c_str());\n}\n \nvoid ComponentProvider::OnLoadConfig(const char* name) {\n std::string config_name = MakeConfigName(name);\n std::cout << \"ComponentProvider::OnLoadConfig\\tname=\" << config_name << std::endl;\n \/\/LoadConfig(config_name.c_str());\n configs.push_back(config_name);\n}\n \n} \/* openlane *\/\n<commit_msg>Fix logging<commit_after>#include <openlane\/component_provider.h>\n#include <openlane\/module.h>\n#include <iostream>\n#include <string>\n\nnamespace {\ntypedef uint32_t (*ComponentFn)(void *ctx);\nComponentFn LCT;\n}\n\nnamespace openlane {\n\nstd::string MakeModuleName(const char* name) {\n std::string module(\"lib\");\n module.append(name);\n module.append(\".so\");\n return module;\n}\n\nstd::string MakeConfigName(const char* name) {\n std::string config(name);\n config.append(\".xml\");\n return config;\n}\n\n\nComponentProvider::ComponentProvider() :\n xml_parser(this)\n{\n}\n\nComponentProvider::~ComponentProvider() {\n ComponentReverseIterator b = modules.rbegin();\n ComponentReverseIterator e = modules.rend();\n\n for(;b != e; ++b) {\n ErrorCode res = (*b)->GetSymbol(\"UnloadComponent\", LCT);\n if (Ok == res)\n LCT(this); \/\/ FIXME\n }\n}\n\nErrorCode ComponentProvider::LoadComponent(const char* filename) {\n\n ErrorCode res = Ok;\n try\n {\n DynamicLibraryPtr module(new DynamicLibrary);\n res = module->Load(filename);\n std::cout << \"component_provider\\tLoad component \" << filename << \", result=\" << res << std::endl;\n\n if (Ok == res)\n res = module->GetSymbol(\"LoadComponent\", LCT);\n\n if (Ok == res)\n if (LCT(this) == 0) res = Ok; \/\/ FIXME\n\n if (Ok == res)\n modules.push_back(module);\n }\n catch(const std::bad_alloc&)\n {\n res = NoMemory;\n }\n\n return res;\n}\n\nErrorCode ComponentProvider::Initialize(const char* filename) {\n std::cout << \"component_provider\\tInitialize\" << std::endl;\n configs.push_back(std::string(filename));\n\n while(!configs.empty()) {\n LoadConfig(configs.begin()->c_str());\n configs.erase(configs.begin());\n }\n return Ok;\n}\n\nErrorCode ComponentProvider::LoadConfig(const char* filename) {\n if (!filename)\n return InvalidArgument;\n\n std::cout << \"component_provider\\tParse config, name=\" << filename << std::endl;\n ErrorCode result = xml_parser.Parse(filename);\n if (result != Ok)\n return result;\n\n return Ok;\n}\n\nErrorCode ComponentProvider::RegisterComponent(uint32_t id, CreateComponentFn fun) {\n std::cout << \"component_provider\\tRegisterComponent id=\" << id << std::endl;\n dic[id] = fun;\n return Ok;\n}\n\nErrorCode ComponentProvider::UnregisterComponent(uint32_t id) {\n std::cout << \"component_provider\\tUnregisterComponent id=\" << id << std::endl;\n return Ok;\n}\n\nvoid ComponentProvider::OnLoadComponent(const char* name) {\n std::string module_name = MakeModuleName(name);\n LoadComponent(module_name.c_str());\n}\n \nvoid ComponentProvider::OnLoadConfig(const char* name) {\n std::string config_name = MakeConfigName(name);\n configs.push_back(config_name);\n}\n \n} \/* openlane *\/\n<|endoftext|>"} {"text":"<commit_before>\/\/ This file is part of the \"x0\" project, http:\/\/github.com\/christianparpart\/x0>\n\/\/ (c) 2009-2017 Christian Parpart <christian@parpart.family>\n\/\/\n\/\/ Licensed under the MIT License (the \"License\"); you may not use this\n\/\/ file except in compliance with the License. You may obtain a copy of\n\/\/ the License at: http:\/\/opensource.org\/licenses\/MIT\n\n#include <xzero\/http\/client\/HttpClient.h>\n#include <xzero\/http\/HttpRequest.h>\n#include <xzero\/http\/HeaderFieldList.h>\n#include <xzero\/net\/TcpEndPoint.h>\n#include <xzero\/executor\/PosixScheduler.h>\n#include <xzero\/net\/DnsClient.h>\n#include <xzero\/io\/FileUtil.h>\n#include <xzero\/Application.h>\n#include <xzero\/RuntimeError.h>\n#include <xzero\/Uri.h>\n#include <xzero\/Flags.h>\n#include <xzero\/logging.h>\n#include <unordered_map>\n#include \"sysconfig.h\"\n#include <iostream>\n#include <unistd.h>\n\n\/\/ #define PACKAGE_VERSION X0_VERSION\n#define PACKAGE_HOMEPAGE_URL \"https:\/\/xzero.io\"\n\n#define VERBOSE(msg...) logInfo(\"xurl\", msg)\n#define DEBUG(msg...) logDebug(\"xurl\", msg)\n#define TRACE(msg...) logTrace(\"xurl\", msg)\n\nusing namespace xzero;\nusing namespace xzero::http;\nusing namespace xzero::http::client;\n\nusing xzero::http::HttpRequestInfo;\nusing xzero::http::HttpVersion;\nusing xzero::http::HeaderField;\n\nclass ServicePortMapping { \/\/ {{{\n public:\n ServicePortMapping();\n\n void loadFile(const std::string& path = \"\/etc\/services\");\n void loadContent(const std::string& content);\n\n int tcp(const std::string& name);\n int udp(const std::string& name);\n\n private:\n std::unordered_map<std::string, int> tcp_;\n std::unordered_map<std::string, int> udp_;\n};\n\nServicePortMapping::ServicePortMapping()\n : tcp_() {\n tcp_[\"http\"] = 80;\n tcp_[\"https\"] = 443;\n}\n\nint ServicePortMapping::tcp(const std::string& name) {\n auto i = tcp_.find(name);\n if (i != tcp_.end())\n return i->second;\n\n RAISE(RuntimeError, \"Unknown service '%s'\", name.c_str());\n}\n\/\/ }}}\n\nclass TerminalLogTarget : public ::xzero::LogTarget { \/\/ {{{\n public:\n void log(LogLevel level,\n const std::string& component,\n const std::string& message) override;\n};\n\nvoid TerminalLogTarget::log(LogLevel level,\n const std::string& component,\n const std::string& message) {\n if (component == \"xurl\") {\n printf(\"%s\\n\", message.c_str());\n } else {\n printf(\"[%s] %s\\n\", component.c_str(), message.c_str());\n }\n}\n\/\/ }}}\n\nclass XUrl {\n public:\n XUrl();\n\n int run(int argc, const char* argv[]);\n\n private:\n void addRequestHeader(const std::string& value);\n Uri makeUri(const std::string& url);\n IPAddress getIPAddress(const std::string& host);\n int getPort(const Uri& uri);\n void query(const Uri& uri);\n\n private:\n PosixScheduler scheduler_;\n Flags flags_;\n DnsClient dns_;\n Duration connectTimeout_;\n Duration readTimeout_;\n Duration writeTimeout_;\n TerminalLogTarget logTarget_;\n http::HeaderFieldList requestHeaders_;\n};\n\nXUrl::XUrl()\n : scheduler_(CatchAndLogExceptionHandler(\"xurl\")),\n flags_(),\n dns_(),\n connectTimeout_(4_seconds),\n readTimeout_(60_seconds),\n writeTimeout_(10_seconds),\n logTarget_(),\n requestHeaders_()\n{\n Application::init();\n \/\/Application::logToStderr(LogLevel::Info);\n Logger::get()->addTarget(&logTarget_);\n\n requestHeaders_.push_back(\"User-Agent\", \"xurl\/\" PACKAGE_VERSION);\n\n flags_.defineBool(\"help\", 'h', \"Prints this help.\");\n flags_.defineBool(\"head\", 'I', \"Performs a HEAD request.\");\n flags_.defineBool(\"verbose\", 'v', \"Be verbose (log level: info)\");\n flags_.defineString(\"output\", 'o', \"PATH\", \"Write response body to given file.\");\n flags_.defineString(\"log-level\", 'L', \"STRING\", \"Log level.\", \"warning\");\n flags_.defineString(\"method\", 'X', \"METHOD\", \"HTTP method\", \"GET\");\n flags_.defineNumber(\"connect-timeout\", 0, \"MS\", \"TCP connect() timeout\", 10_seconds .milliseconds());\n flags_.defineString(\"upload-file\", 'T', \"PATH\", \"Uploads given file.\", \"\");\n flags_.defineString(\"header\", 'H', \"HEADER\", \"Adds a custom request header\",\n None(),\n std::bind(&XUrl::addRequestHeader, this, std::placeholders::_1));\n flags_.defineBool(\"ipv4\", '4', \"Favor IPv4 for TCP\/IP communication.\");\n flags_.defineBool(\"ipv6\", '6', \"Favor IPv6 for TCP\/IP communication.\");\n flags_.enableParameters(\"URL\", \"URL to query\");\n}\n\nvoid XUrl::addRequestHeader(const std::string& field) {\n requestHeaders_.push_back(HeaderField::parse(field));\n}\n\nint XUrl::run(int argc, const char* argv[]) {\n std::error_code ec = flags_.parse(argc, argv);\n if (ec) {\n fprintf(stderr, \"Failed to parse flags. %s\\n\", ec.message().c_str());\n return 1;\n }\n\n if (flags_.isSet(\"log-level\"))\n Logger::get()->setMinimumLogLevel(make_loglevel(flags_.getString(\"log-level\")));\n\n if (flags_.getBool(\"verbose\"))\n Logger::get()->setMinimumLogLevel(make_loglevel(\"info\"));\n\n if (flags_.getBool(\"help\")) {\n std::cerr\n << \"xurl: Xzero HTTP Client \" PACKAGE_VERSION\n << \" [\" PACKAGE_HOMEPAGE_URL \"]\" << std::endl\n << \"Copyright (c) 2009-2017 by Christian Parpart <christian@parpart.family>\" << std::endl\n << std::endl\n << \"Usage: xurl [options ...]\" << std::endl\n << std::endl\n << \"Options:\" << std::endl\n << flags_.helpText() << std::endl;\n return 0;\n }\n\n if (flags_.parameters().empty()) {\n logError(\"xurl\", \"No URL given.\");\n return 1;\n }\n\n if (flags_.parameters().size() != 1) {\n logError(\"xurl\", \"Too many URLs given.\");\n return 1;\n }\n\n Uri uri = makeUri(flags_.parameters()[0]);\n query(uri);\n\n return 0;\n}\n\nUri XUrl::makeUri(const std::string& url) {\n Uri uri(url);\n\n if (uri.path() == \"\")\n uri.setPath(\"\/\");\n\n return uri;\n}\n\nIPAddress XUrl::getIPAddress(const std::string& host) {\n std::vector<IPAddress> ipaddresses = dns_.ipv4(host);\n if (ipaddresses.empty())\n RAISE(RuntimeError, \"Could not resolve %s.\", host.c_str());\n\n return ipaddresses.front();\n}\n\nint XUrl::getPort(const Uri& uri) {\n if (uri.port())\n return uri.port();\n\n return ServicePortMapping().tcp(uri.scheme());\n}\n\nvoid XUrl::query(const Uri& uri) {\n IPAddress ipaddr = getIPAddress(uri.host());\n int port = getPort(uri);\n InetAddress inetAddr(ipaddr, port);\n Duration keepAlive = 8_seconds;\n\n logDebug(\"xurl\", \"inet addr: $0, uri: $1\", inetAddr, uri.toString());\n\n std::string method = flags_.getString(\"method\");\n\n if (flags_.getBool(\"head\")) {\n method = \"HEAD\";\n }\n\n HugeBuffer body;\n if (!flags_.getString(\"upload-file\").empty()) {\n method = \"PUT\";\n body = FileUtil::read(flags_.getString(\"upload-file\"));\n }\n\n requestHeaders_.overwrite(\"Host\", uri.hostAndPort());\n\n HttpRequest req(HttpVersion::VERSION_1_1,\n method,\n uri.pathAndQuery(),\n requestHeaders_,\n uri.scheme() == \"https\",\n std::move(body));\n req.setScheme(uri.scheme());\n\n VERBOSE(\"> $0 $1 HTTP\/$2\", req.unparsedMethod(),\n req.unparsedUri(),\n req.version());\n\n for (const HeaderField& field: req.headers())\n if (field.name()[0] != ':')\n VERBOSE(\"> $0: $1\", field.name(), field.value());\n\n VERBOSE(\">\");\n\n HttpClient httpClient(&scheduler_, inetAddr,\n connectTimeout_, readTimeout_, writeTimeout_,\n keepAlive);\n\n Future<HttpClient::Response> f = httpClient.send(req);\n\n f.onSuccess([](HttpClient::Response& response) {\n VERBOSE(\"< HTTP\/$0 $1 $2\", response.version(),\n (int) response.status(),\n response.reason());\n\n for (const HeaderField& field: response.headers())\n VERBOSE(\"< $0: $1\", field.name(), field.value());\n\n VERBOSE(\"<\");\n\n const BufferRef& content = response.content().getBuffer();\n write(STDOUT_FILENO, content.data(), content.size());\n });\n\n f.onFailure([](std::error_code ec) {\n logError(\"xurl\", \"connect() failed. $0\", ec.message());\n });\n\n scheduler_.runLoop();\n}\n\nint main(int argc, const char* argv[]) {\n XUrl app;\n return app.run(argc, argv);\n}\n<commit_msg>[xurl] small refactors<commit_after>\/\/ This file is part of the \"x0\" project, http:\/\/github.com\/christianparpart\/x0>\n\/\/ (c) 2009-2017 Christian Parpart <christian@parpart.family>\n\/\/\n\/\/ Licensed under the MIT License (the \"License\"); you may not use this\n\/\/ file except in compliance with the License. You may obtain a copy of\n\/\/ the License at: http:\/\/opensource.org\/licenses\/MIT\n\n#include <xzero\/http\/client\/HttpClient.h>\n#include <xzero\/http\/HttpRequest.h>\n#include <xzero\/http\/HeaderFieldList.h>\n#include <xzero\/net\/TcpEndPoint.h>\n#include <xzero\/executor\/PosixScheduler.h>\n#include <xzero\/net\/DnsClient.h>\n#include <xzero\/io\/FileUtil.h>\n#include <xzero\/Application.h>\n#include <xzero\/RuntimeError.h>\n#include <xzero\/Uri.h>\n#include <xzero\/Flags.h>\n#include <xzero\/logging.h>\n#include <unordered_map>\n#include \"sysconfig.h\"\n#include <iostream>\n#include <unistd.h>\n\n\/\/ #define PACKAGE_VERSION X0_VERSION\n#define PACKAGE_HOMEPAGE_URL \"https:\/\/xzero.io\"\n\n#define VERBOSE(msg...) logInfo(\"xurl\", msg)\n#define DEBUG(msg...) logDebug(\"xurl\", msg)\n#define TRACE(msg...) logTrace(\"xurl\", msg)\n\nusing namespace xzero;\nusing namespace xzero::http;\nusing namespace xzero::http::client;\n\nusing xzero::http::HttpRequestInfo;\nusing xzero::http::HttpVersion;\nusing xzero::http::HeaderField;\n\nclass ServicePortMapping { \/\/ {{{\n public:\n ServicePortMapping();\n\n void loadFile(const std::string& path = \"\/etc\/services\");\n void loadContent(const std::string& content);\n\n int tcp(const std::string& name);\n int udp(const std::string& name);\n\n private:\n std::unordered_map<std::string, int> tcp_;\n std::unordered_map<std::string, int> udp_;\n};\n\nServicePortMapping::ServicePortMapping()\n : tcp_() {\n tcp_[\"http\"] = 80;\n tcp_[\"https\"] = 443;\n}\n\nint ServicePortMapping::tcp(const std::string& name) {\n auto i = tcp_.find(name);\n if (i != tcp_.end())\n return i->second;\n\n RAISE(RuntimeError, \"Unknown service '%s'\", name.c_str());\n}\n\/\/ }}}\n\nclass XurlLogTarget : public ::xzero::LogTarget { \/\/ {{{\n public:\n void log(LogLevel level,\n const std::string& component,\n const std::string& message) override;\n};\n\nvoid XurlLogTarget::log(LogLevel level,\n const std::string& component,\n const std::string& message) {\n if (component == \"xurl\") {\n printf(\"%s\\n\", message.c_str());\n } else {\n printf(\"[%s] %s\\n\", component.c_str(), message.c_str());\n }\n}\n\/\/ }}}\n\nclass XUrl {\n public:\n XUrl();\n\n int run(int argc, const char* argv[]);\n\n private:\n void addRequestHeader(const std::string& value);\n Uri makeUri(const std::string& url);\n IPAddress getIPAddress(const std::string& host);\n int getPort(const Uri& uri);\n void query(const Uri& uri);\n\n private:\n PosixScheduler scheduler_;\n Flags flags_;\n DnsClient dns_;\n Duration connectTimeout_;\n Duration readTimeout_;\n Duration writeTimeout_;\n XurlLogTarget logTarget_;\n http::HeaderFieldList requestHeaders_;\n};\n\nXUrl::XUrl()\n : scheduler_(CatchAndLogExceptionHandler(\"xurl\")),\n flags_(),\n dns_(),\n connectTimeout_(4_seconds),\n readTimeout_(60_seconds),\n writeTimeout_(10_seconds),\n logTarget_(),\n requestHeaders_()\n{\n Application::init();\n \/\/Application::logToStderr(LogLevel::Info);\n Logger::get()->addTarget(&logTarget_);\n\n requestHeaders_.push_back(\"User-Agent\", \"xurl\/\" PACKAGE_VERSION);\n\n flags_.defineBool(\"help\", 'h', \"Prints this help.\");\n flags_.defineBool(\"head\", 'I', \"Performs a HEAD request.\");\n flags_.defineBool(\"verbose\", 'v', \"Be verbose (log level: info)\");\n flags_.defineString(\"output\", 'o', \"PATH\", \"Write response body to given file.\");\n flags_.defineString(\"log-level\", 'L', \"STRING\", \"Log level.\", \"warning\");\n flags_.defineString(\"method\", 'X', \"METHOD\", \"HTTP method\", \"GET\");\n flags_.defineNumber(\"connect-timeout\", 0, \"MS\", \"TCP connect() timeout\", 10_seconds .milliseconds());\n flags_.defineString(\"upload-file\", 'T', \"PATH\", \"Uploads given file.\", \"\");\n flags_.defineString(\"header\", 'H', \"HEADER\", \"Adds a custom request header\",\n None(),\n std::bind(&XUrl::addRequestHeader, this, std::placeholders::_1));\n flags_.defineBool(\"ipv4\", '4', \"Favor IPv4 for TCP\/IP communication.\");\n flags_.defineBool(\"ipv6\", '6', \"Favor IPv6 for TCP\/IP communication.\");\n flags_.enableParameters(\"URL\", \"URL to query\");\n}\n\nvoid XUrl::addRequestHeader(const std::string& field) {\n requestHeaders_.push_back(HeaderField::parse(field));\n}\n\nint XUrl::run(int argc, const char* argv[]) {\n std::error_code ec = flags_.parse(argc, argv);\n if (ec) {\n fprintf(stderr, \"Failed to parse flags. %s\\n\", ec.message().c_str());\n return 1;\n }\n\n if (flags_.isSet(\"log-level\"))\n Logger::get()->setMinimumLogLevel(make_loglevel(flags_.getString(\"log-level\")));\n\n if (flags_.getBool(\"verbose\"))\n Logger::get()->setMinimumLogLevel(make_loglevel(\"info\"));\n\n if (flags_.getBool(\"help\")) {\n std::cerr\n << \"xurl: Xzero HTTP Client \" PACKAGE_VERSION\n << \" [\" PACKAGE_HOMEPAGE_URL \"]\" << std::endl\n << \"Copyright (c) 2009-2017 by Christian Parpart <christian@parpart.family>\" << std::endl\n << std::endl\n << \"Usage: xurl [options ...]\" << std::endl\n << std::endl\n << \"Options:\" << std::endl\n << flags_.helpText() << std::endl;\n return 0;\n }\n\n if (flags_.parameters().empty()) {\n logError(\"xurl\", \"No URL given.\");\n return 1;\n }\n\n if (flags_.parameters().size() != 1) {\n logError(\"xurl\", \"Too many URLs given.\");\n return 1;\n }\n\n query(makeUri(flags_.parameters()[0]));\n\n return 0;\n}\n\nUri XUrl::makeUri(const std::string& url) {\n Uri uri(url);\n\n if (uri.path() == \"\")\n uri.setPath(\"\/\");\n\n return uri;\n}\n\nIPAddress XUrl::getIPAddress(const std::string& host) {\n std::vector<IPAddress> ipaddresses = dns_.ipv4(host);\n if (ipaddresses.empty())\n RAISE(RuntimeError, \"Could not resolve %s.\", host.c_str());\n\n return ipaddresses.front();\n}\n\nint XUrl::getPort(const Uri& uri) {\n if (uri.port())\n return uri.port();\n\n return ServicePortMapping().tcp(uri.scheme());\n}\n\nvoid XUrl::query(const Uri& uri) {\n IPAddress ipaddr = getIPAddress(uri.host());\n int port = getPort(uri);\n InetAddress inetAddr(ipaddr, port);\n Duration keepAlive = 8_seconds;\n\n std::string method = flags_.getString(\"method\");\n\n if (flags_.getBool(\"head\")) {\n method = \"HEAD\";\n }\n\n HugeBuffer body;\n if (!flags_.getString(\"upload-file\").empty()) {\n method = \"PUT\";\n body = FileUtil::read(flags_.getString(\"upload-file\"));\n }\n\n requestHeaders_.overwrite(\"Host\", uri.hostAndPort());\n\n HttpRequest req(HttpVersion::VERSION_1_1,\n method,\n uri.pathAndQuery(),\n requestHeaders_,\n uri.scheme() == \"https\",\n std::move(body));\n req.setScheme(uri.scheme());\n\n VERBOSE(\"* connecting to $0\", inetAddr);\n\n VERBOSE(\"> $0 $1 HTTP\/$2\", req.unparsedMethod(),\n req.unparsedUri(),\n req.version());\n\n for (const HeaderField& field: req.headers())\n if (field.name()[0] != ':')\n VERBOSE(\"> $0: $1\", field.name(), field.value());\n\n VERBOSE(\">\");\n\n HttpClient httpClient(&scheduler_, inetAddr,\n connectTimeout_, readTimeout_, writeTimeout_,\n keepAlive);\n\n Future<HttpClient::Response> f = httpClient.send(req);\n\n f.onSuccess([](HttpClient::Response& response) {\n VERBOSE(\"< HTTP\/$0 $1 $2\", response.version(),\n (int) response.status(),\n response.reason());\n\n for (const HeaderField& field: response.headers())\n VERBOSE(\"< $0: $1\", field.name(), field.value());\n\n VERBOSE(\"<\");\n\n const BufferRef& content = response.content().getBuffer();\n write(STDOUT_FILENO, content.data(), content.size());\n });\n\n f.onFailure([](std::error_code ec) {\n logError(\"xurl\", \"connect() failed. $0\", ec.message());\n });\n\n scheduler_.runLoop();\n}\n\nint main(int argc, const char* argv[]) {\n XUrl app;\n return app.run(argc, argv);\n}\n<|endoftext|>"} {"text":"<commit_before><commit_msg>A triple drift<commit_after><|endoftext|>"} {"text":"<commit_before>\/*\n Copyright 2012 Joe Hermaszewski. All rights reserved.\n\n Redistribution and use in source and binary forms, with or without\n modification, are permitted provided that the following conditions are met:\n\n 1. Redistributions of source code must retain the above copyright notice,\n this list of conditions and the following disclaimer.\n\n 2. Redistributions in binary form must reproduce the above copyright notice,\n this list of conditions and the following disclaimer in the documentation\n and\/or other materials provided with the distribution.\n\n THIS SOFTWARE IS PROVIDED BY JOE HERMASZEWSKI \"AS IS\" AND ANY EXPRESS OR\n IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\n MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO\n EVENT SHALL JOE HERMASZEWSKI OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF\n THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n The views and conclusions contained in the software and documentation are\n those of the authors and should not be interpreted as representing official\n policies, either expressed or implied, of Joe Hermaszewski.\n*\/\n\n#include \"statement.hpp\"\n\n#include <cassert>\n#include <memory>\n\n#include <compiler\/casting.hpp>\n#include <compiler\/parser.hpp>\n#include <compiler\/tokens\/statements\/compound_statement.hpp>\n#include <compiler\/tokens\/token.hpp>\n\nnamespace JoeLang\n{\nnamespace Compiler\n{\n\n\/\/------------------------------------------------------------------------------\n\/\/ Statement\n\/\/------------------------------------------------------------------------------\n\nStatement::Statement( TokenTy sub_class_id )\n :Token( sub_class_id )\n{\n}\n\nStatement::~Statement()\n{\n}\n\nvoid Statement::Print( int depth ) const\n{\n}\n\nbool Statement::Parse( Parser& parser, Statement_up& token )\n{\n \/\/ Try and parse any kind of statement\n std::unique_ptr<Token> t;\n if( !parser.ExpectAnyOf< CompoundStatement >( t ) )\n return false;\n\n assert( isa<Statement>( t ) && \"Statement parsed a non-statement\" );\n token.reset( static_cast<Statement*>( t.release() ) );\n return true;\n}\n\nbool Statement::classof( const Token* d )\n{\n return d->GetSubClassID() >= TokenTy::Statement_Start &&\n d->GetSubClassID() <= TokenTy::Statement_End;\n}\n\nbool Statement::classof( const Statement* d )\n{\n \/\/ A Statement is always a Statement\n return true;\n}\n\n} \/\/ namespace Compiler\n} \/\/ namespace JoeLang\n<commit_msg>[+] Parsing Return statements<commit_after>\/*\n Copyright 2012 Joe Hermaszewski. All rights reserved.\n\n Redistribution and use in source and binary forms, with or without\n modification, are permitted provided that the following conditions are met:\n\n 1. Redistributions of source code must retain the above copyright notice,\n this list of conditions and the following disclaimer.\n\n 2. Redistributions in binary form must reproduce the above copyright notice,\n this list of conditions and the following disclaimer in the documentation\n and\/or other materials provided with the distribution.\n\n THIS SOFTWARE IS PROVIDED BY JOE HERMASZEWSKI \"AS IS\" AND ANY EXPRESS OR\n IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\n MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO\n EVENT SHALL JOE HERMASZEWSKI OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF\n THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n The views and conclusions contained in the software and documentation are\n those of the authors and should not be interpreted as representing official\n policies, either expressed or implied, of Joe Hermaszewski.\n*\/\n\n#include \"statement.hpp\"\n\n#include <cassert>\n#include <memory>\n\n#include <compiler\/casting.hpp>\n#include <compiler\/parser.hpp>\n#include <compiler\/tokens\/statements\/compound_statement.hpp>\n#include <compiler\/tokens\/statements\/return_statement.hpp>\n#include <compiler\/tokens\/token.hpp>\n\nnamespace JoeLang\n{\nnamespace Compiler\n{\n\n\/\/------------------------------------------------------------------------------\n\/\/ Statement\n\/\/------------------------------------------------------------------------------\n\nStatement::Statement( TokenTy sub_class_id )\n :Token( sub_class_id )\n{\n}\n\nStatement::~Statement()\n{\n}\n\nvoid Statement::Print( int depth ) const\n{\n}\n\nbool Statement::Parse( Parser& parser, Statement_up& token )\n{\n \/\/ Try and parse any kind of statement\n std::unique_ptr<Token> t;\n if( !parser.ExpectAnyOf< CompoundStatement,\n ReturnStatement >( t ) )\n return false;\n\n assert( isa<Statement>( t ) && \"Statement parsed a non-statement\" );\n token.reset( static_cast<Statement*>( t.release() ) );\n return true;\n}\n\nbool Statement::classof( const Token* d )\n{\n return d->GetSubClassID() >= TokenTy::Statement_Start &&\n d->GetSubClassID() <= TokenTy::Statement_End;\n}\n\nbool Statement::classof( const Statement* d )\n{\n \/\/ A Statement is always a Statement\n return true;\n}\n\n} \/\/ namespace Compiler\n} \/\/ namespace JoeLang\n<|endoftext|>"} {"text":"<commit_before><commit_msg>Kart shouldn't fly through colliders now<commit_after><|endoftext|>"} {"text":"<commit_before>\/**\n * @file\n * @author Mamadou Babaei <info@babaei.net>\n * @version 0.1.0\n *\n * @section LICENSE\n *\n * (The MIT License)\n *\n * Copyright (c) 2016 - 2020 Mamadou Babaei\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n *\n * @section DESCRIPTION\n *\n * A (a)synchronous thread-safe mail class with a built-in queue system.\n *\/\n\n\n#include <chrono>\n#include <queue>\n#include <boost\/bind.hpp>\n#include <boost\/chrono\/chrono.hpp>\n#include <boost\/exception\/diagnostic_information.hpp>\n#include <boost\/filesystem.hpp>\n#include <boost\/thread\/lock_guard.hpp>\n#include <boost\/thread\/mutex.hpp>\n#include <boost\/thread\/thread.hpp>\n#if defined ( _WIN32 )\n#include <vmime\/platforms\/windows\/windowsHandler.hpp>\n#else\n#include <vmime\/platforms\/posix\/posixHandler.hpp>\n#include <vmime\/vmime.hpp>\n#endif \/\/ defined (_WIN32 )\n#include \"make_unique.hpp\"\n#include \"Log.hpp\"\n#include \"Mail.hpp\"\n#include \"Utility.hpp\"\n\n#define WORKER_THREAD_STOP_IDLE_MILLISECONDS 10000.0\n#define UNKNOWN_ERROR \"Unknown error!\"\n\nusing namespace std;\nusing namespace boost;\nusing namespace CoreLib;\n\nstruct Mail::Impl\n{\npublic:\n static std::queue<Mail *> MailQueue;\n static std::queue<Mail::SendCallback> MailCallbackQueue;\n static bool WorkerThreadIsRunning;\n static boost::mutex MailMutex;\n static boost::mutex WorkerMutex;\n static std::unique_ptr<boost::thread> WorkerThread;\n\npublic:\n static void DoWork();\n\npublic:\n std::string From;\n std::string To;\n std::string Subject;\n std::string Body;\n std::vector<std::string> Attachments;\n\n bool DeleteLater;\n\npublic:\n Impl();\n ~Impl();\n};\n\nstd::queue<Mail *> Mail::Impl::MailQueue;\nstd::queue<Mail::SendCallback> Mail::Impl::MailCallbackQueue;\nbool Mail::Impl::WorkerThreadIsRunning = false;\nboost::mutex Mail::Impl::MailMutex;\nboost::mutex Mail::Impl::WorkerMutex;\nstd::unique_ptr<boost::thread> Mail::Impl::WorkerThread;\n\nvoid Mail::Impl::DoWork()\n{\n LOG_INFO(\"Mail worker thread started\");\n\n try {\n auto lastJobTime = std::chrono::high_resolution_clock::now();\n\n bool isMailQueueEmpty = false;\n Mail *mail = nullptr;\n Mail::SendCallback callback = nullptr;\n\n for (;;) {\n boost::this_thread::interruption_point();\n\n {\n boost::lock_guard<boost::mutex> lock(WorkerMutex);\n (void)lock;\n\n if (!WorkerThreadIsRunning)\n break;\n }\n\n boost::this_thread::disable_interruption di;\n\n {\n boost::lock_guard<boost::mutex> lock(MailMutex);\n (void)lock;\n\n isMailQueueEmpty = !(MailQueue.size() > 0);\n\n if (!isMailQueueEmpty) {\n mail = MailQueue.front();\n callback = MailCallbackQueue.front();\n }\n }\n\n if (!isMailQueueEmpty) {\n string error;\n bool rc = mail->Send(error);\n if (callback != nullptr) {\n callback(rc, error);\n }\n\n {\n boost::lock_guard<boost::mutex> lock(MailMutex);\n (void)lock;\n\n MailQueue.pop();\n MailCallbackQueue.pop();\n }\n\n if (mail->GetDeleteLater()) {\n delete mail;\n }\n\n lastJobTime = std::chrono::high_resolution_clock::now();\n }\n\n boost::this_thread::restore_interruption ri(di);\n (void)ri;\n boost::this_thread::interruption_point();\n\n boost::this_thread::sleep_for(boost::chrono::nanoseconds(1));\n\n if (isMailQueueEmpty) {\n if ((std::chrono::duration<double, std::milli>(\n std::chrono::high_resolution_clock::now() - lastJobTime)).count() \/\/ elapsed in milliseconds\n > WORKER_THREAD_STOP_IDLE_MILLISECONDS) {\n {\n boost::lock_guard<boost::mutex> lock(WorkerMutex);\n (void)lock;\n\n WorkerThreadIsRunning = false;\n break;\n }\n }\n }\n }\n }\n\n catch (boost::exception &ex) {\n LOG_ERROR(boost::diagnostic_information(ex));\n }\n\n catch (std::exception &ex) {\n LOG_ERROR(ex.what());\n }\n\n catch (...) {\n LOG_ERROR(UNKNOWN_ERROR);\n }\n\n LOG_INFO(\"Mail worker thread stopped\");\n}\n\nMail::Mail()\n : m_pimpl(std::make_shared<Mail::Impl>())\n{\n\n}\n\nMail::Mail(const std::string &from, const std::string &to,\n const std::string &subject, const std::string &body,\n const std::vector<std::string> &attachments)\n : m_pimpl(std::make_shared<Mail::Impl>())\n{\n m_pimpl->From = from;\n m_pimpl->To = to;\n m_pimpl->Subject = subject;\n m_pimpl->Body = body;\n SetAttachments(attachments);\n}\n\nMail::~Mail() = default;\n\nstd::string Mail::GetFrom()\n{\n return m_pimpl->From;\n}\n\nstd::string Mail::GetTo()\n{\n return m_pimpl->To;\n}\n\nstd::string Mail::GetSubject()\n{\n return m_pimpl->Subject;\n}\n\nstd::string Mail::GetBody()\n{\n return m_pimpl->Body;\n}\n\nconst std::vector<std::string> &Mail::GetAttachments()\n{\n return m_pimpl->Attachments;\n}\n\nvoid Mail::SetFrom(const std::string &from)\n{\n m_pimpl->From = from;\n}\n\nvoid Mail::SetTo(const std::string &to)\n{\n m_pimpl->To = to;\n}\n\nvoid Mail::SetSubject(const std::string &subject)\n{\n m_pimpl->Subject = subject;\n}\n\nvoid Mail::SetBody(const std::string &body)\n{\n m_pimpl->Body = body;\n}\n\nvoid Mail::SetAttachments(const std::vector<std::string> &attachments)\n{\n m_pimpl->Attachments.clear();\n for (auto a : attachments) {\n m_pimpl->Attachments.push_back(a);\n }\n}\n\nbool Mail::GetDeleteLater() const\n{\n return m_pimpl->DeleteLater;\n}\n\nvoid Mail::SetDeleteLater(const bool del) const\n{\n m_pimpl->DeleteLater = del;\n}\n\nbool Mail::Send() const\n{\n string err;\n return Send(err);\n}\n\nbool Mail::Send(std::string &out_error) const\n{\n try {\n#if defined (_WIN32)\n vmime::platform::setHandler<vmime::platforms::windows::windowsHandler>();\n#else\n vmime::platform::setHandler<vmime::platforms::posix::posixHandler>();\n#endif \/* defined (_WIN32) *\/\n\n vmime::messageBuilder mb;\n\n mb.setExpeditor(vmime::mailbox(m_pimpl->From));\n mb.getRecipients().appendAddress(vmime::make_shared<vmime::mailbox>(m_pimpl->To));\n\n mb.setSubject(*vmime::text::newFromString(m_pimpl->Subject, vmime::charsets::UTF_8));\n\n mb.constructTextPart(vmime::mediaType(vmime::mediaTypes::TEXT, vmime::mediaTypes::TEXT_HTML));\n mb.getTextPart()->setCharset(vmime::charsets::UTF_8);\n mb.getTextPart()->setText(vmime::make_shared<vmime::stringContentHandler>(m_pimpl->Body));\n\n if (m_pimpl->Attachments.size() > 0) {\n for (auto a : m_pimpl->Attachments) {\n vmime::shared_ptr <vmime::attachment> att = vmime::make_shared <vmime::fileAttachment>\n (a, vmime::mediaType(\"application\/octet-stream\"),\n vmime::text(filesystem::path(a).stem().string()));\n mb.appendAttachment(att);\n }\n }\n\n vmime::shared_ptr<vmime::message> msg = mb.construct();\n\n vmime::utility::url url(\"smtp:\/\/localhost\");\n#if VMIME_API_MODE == VMIME_LEGACY_API\n vmime::shared_ptr<vmime::net::session> sess = vmime::make_shared<vmime::net::session>();\n#else\n vmime::shared_ptr<vmime::net::session> sess = vmime::net::session::create();\n#endif \/\/ VMIME_API_MODE == VMIME_LEGACY_API\n vmime::shared_ptr<vmime::net::transport> tr = sess->getTransport(url);\n\n tr->connect();\n tr->send(msg);\n tr->disconnect();\n\n return true;\n }\n\n catch (vmime::exception &ex) {\n out_error.assign(ex.what());\n }\n\n catch(std::exception &ex) {\n out_error.assign(ex.what());\n }\n\n catch (...) {\n out_error.assign(UNKNOWN_ERROR);\n }\n\n return false;\n}\n\nvoid Mail::SendAsync(const SendCallback callback)\n{\n try {\n {\n boost::lock_guard<boost::mutex> lock(Impl::MailMutex);\n (void)lock;\n\n Impl::MailQueue.push(this);\n Impl::MailCallbackQueue.push(callback);\n }\n\n {\n boost::lock_guard<boost::mutex> lock(Impl::WorkerMutex);\n (void)lock;\n\n if (!Impl::WorkerThreadIsRunning) {\n Impl::WorkerThreadIsRunning = true;\n\n Impl::WorkerThread = make_unique<boost::thread>(Mail::Impl::DoWork);\n Impl::WorkerThread->detach();\n }\n }\n }\n\n catch (boost::exception &ex) {\n LOG_ERROR(boost::diagnostic_information(ex));\n }\n\n catch (std::exception &ex) {\n LOG_ERROR(ex.what());\n }\n\n catch (...) {\n LOG_ERROR(UNKNOWN_ERROR);\n }\n}\n\nMail::Impl::Impl()\n : DeleteLater(false)\n{\n\n}\n\nMail::Impl::~Impl() = default;\n<commit_msg>add boost prefix to filesystem in order to avoid build issues in c++17 mode on clang<commit_after>\/**\n * @file\n * @author Mamadou Babaei <info@babaei.net>\n * @version 0.1.0\n *\n * @section LICENSE\n *\n * (The MIT License)\n *\n * Copyright (c) 2016 - 2020 Mamadou Babaei\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n *\n * @section DESCRIPTION\n *\n * A (a)synchronous thread-safe mail class with a built-in queue system.\n *\/\n\n\n#include <chrono>\n#include <queue>\n#include <boost\/bind.hpp>\n#include <boost\/chrono\/chrono.hpp>\n#include <boost\/exception\/diagnostic_information.hpp>\n#include <boost\/filesystem.hpp>\n#include <boost\/thread\/lock_guard.hpp>\n#include <boost\/thread\/mutex.hpp>\n#include <boost\/thread\/thread.hpp>\n#if defined ( _WIN32 )\n#include <vmime\/platforms\/windows\/windowsHandler.hpp>\n#else\n#include <vmime\/platforms\/posix\/posixHandler.hpp>\n#include <vmime\/vmime.hpp>\n#endif \/\/ defined (_WIN32 )\n#include \"make_unique.hpp\"\n#include \"Log.hpp\"\n#include \"Mail.hpp\"\n#include \"Utility.hpp\"\n\n#define WORKER_THREAD_STOP_IDLE_MILLISECONDS 10000.0\n#define UNKNOWN_ERROR \"Unknown error!\"\n\nusing namespace std;\nusing namespace boost;\nusing namespace CoreLib;\n\nstruct Mail::Impl\n{\npublic:\n static std::queue<Mail *> MailQueue;\n static std::queue<Mail::SendCallback> MailCallbackQueue;\n static bool WorkerThreadIsRunning;\n static boost::mutex MailMutex;\n static boost::mutex WorkerMutex;\n static std::unique_ptr<boost::thread> WorkerThread;\n\npublic:\n static void DoWork();\n\npublic:\n std::string From;\n std::string To;\n std::string Subject;\n std::string Body;\n std::vector<std::string> Attachments;\n\n bool DeleteLater;\n\npublic:\n Impl();\n ~Impl();\n};\n\nstd::queue<Mail *> Mail::Impl::MailQueue;\nstd::queue<Mail::SendCallback> Mail::Impl::MailCallbackQueue;\nbool Mail::Impl::WorkerThreadIsRunning = false;\nboost::mutex Mail::Impl::MailMutex;\nboost::mutex Mail::Impl::WorkerMutex;\nstd::unique_ptr<boost::thread> Mail::Impl::WorkerThread;\n\nvoid Mail::Impl::DoWork()\n{\n LOG_INFO(\"Mail worker thread started\");\n\n try {\n auto lastJobTime = std::chrono::high_resolution_clock::now();\n\n bool isMailQueueEmpty = false;\n Mail *mail = nullptr;\n Mail::SendCallback callback = nullptr;\n\n for (;;) {\n boost::this_thread::interruption_point();\n\n {\n boost::lock_guard<boost::mutex> lock(WorkerMutex);\n (void)lock;\n\n if (!WorkerThreadIsRunning)\n break;\n }\n\n boost::this_thread::disable_interruption di;\n\n {\n boost::lock_guard<boost::mutex> lock(MailMutex);\n (void)lock;\n\n isMailQueueEmpty = !(MailQueue.size() > 0);\n\n if (!isMailQueueEmpty) {\n mail = MailQueue.front();\n callback = MailCallbackQueue.front();\n }\n }\n\n if (!isMailQueueEmpty) {\n string error;\n bool rc = mail->Send(error);\n if (callback != nullptr) {\n callback(rc, error);\n }\n\n {\n boost::lock_guard<boost::mutex> lock(MailMutex);\n (void)lock;\n\n MailQueue.pop();\n MailCallbackQueue.pop();\n }\n\n if (mail->GetDeleteLater()) {\n delete mail;\n }\n\n lastJobTime = std::chrono::high_resolution_clock::now();\n }\n\n boost::this_thread::restore_interruption ri(di);\n (void)ri;\n boost::this_thread::interruption_point();\n\n boost::this_thread::sleep_for(boost::chrono::nanoseconds(1));\n\n if (isMailQueueEmpty) {\n if ((std::chrono::duration<double, std::milli>(\n std::chrono::high_resolution_clock::now() - lastJobTime)).count() \/\/ elapsed in milliseconds\n > WORKER_THREAD_STOP_IDLE_MILLISECONDS) {\n {\n boost::lock_guard<boost::mutex> lock(WorkerMutex);\n (void)lock;\n\n WorkerThreadIsRunning = false;\n break;\n }\n }\n }\n }\n }\n\n catch (boost::exception &ex) {\n LOG_ERROR(boost::diagnostic_information(ex));\n }\n\n catch (std::exception &ex) {\n LOG_ERROR(ex.what());\n }\n\n catch (...) {\n LOG_ERROR(UNKNOWN_ERROR);\n }\n\n LOG_INFO(\"Mail worker thread stopped\");\n}\n\nMail::Mail()\n : m_pimpl(std::make_shared<Mail::Impl>())\n{\n\n}\n\nMail::Mail(const std::string &from, const std::string &to,\n const std::string &subject, const std::string &body,\n const std::vector<std::string> &attachments)\n : m_pimpl(std::make_shared<Mail::Impl>())\n{\n m_pimpl->From = from;\n m_pimpl->To = to;\n m_pimpl->Subject = subject;\n m_pimpl->Body = body;\n SetAttachments(attachments);\n}\n\nMail::~Mail() = default;\n\nstd::string Mail::GetFrom()\n{\n return m_pimpl->From;\n}\n\nstd::string Mail::GetTo()\n{\n return m_pimpl->To;\n}\n\nstd::string Mail::GetSubject()\n{\n return m_pimpl->Subject;\n}\n\nstd::string Mail::GetBody()\n{\n return m_pimpl->Body;\n}\n\nconst std::vector<std::string> &Mail::GetAttachments()\n{\n return m_pimpl->Attachments;\n}\n\nvoid Mail::SetFrom(const std::string &from)\n{\n m_pimpl->From = from;\n}\n\nvoid Mail::SetTo(const std::string &to)\n{\n m_pimpl->To = to;\n}\n\nvoid Mail::SetSubject(const std::string &subject)\n{\n m_pimpl->Subject = subject;\n}\n\nvoid Mail::SetBody(const std::string &body)\n{\n m_pimpl->Body = body;\n}\n\nvoid Mail::SetAttachments(const std::vector<std::string> &attachments)\n{\n m_pimpl->Attachments.clear();\n for (auto a : attachments) {\n m_pimpl->Attachments.push_back(a);\n }\n}\n\nbool Mail::GetDeleteLater() const\n{\n return m_pimpl->DeleteLater;\n}\n\nvoid Mail::SetDeleteLater(const bool del) const\n{\n m_pimpl->DeleteLater = del;\n}\n\nbool Mail::Send() const\n{\n string err;\n return Send(err);\n}\n\nbool Mail::Send(std::string &out_error) const\n{\n try {\n#if defined (_WIN32)\n vmime::platform::setHandler<vmime::platforms::windows::windowsHandler>();\n#else\n vmime::platform::setHandler<vmime::platforms::posix::posixHandler>();\n#endif \/* defined (_WIN32) *\/\n\n vmime::messageBuilder mb;\n\n mb.setExpeditor(vmime::mailbox(m_pimpl->From));\n mb.getRecipients().appendAddress(vmime::make_shared<vmime::mailbox>(m_pimpl->To));\n\n mb.setSubject(*vmime::text::newFromString(m_pimpl->Subject, vmime::charsets::UTF_8));\n\n mb.constructTextPart(vmime::mediaType(vmime::mediaTypes::TEXT, vmime::mediaTypes::TEXT_HTML));\n mb.getTextPart()->setCharset(vmime::charsets::UTF_8);\n mb.getTextPart()->setText(vmime::make_shared<vmime::stringContentHandler>(m_pimpl->Body));\n\n if (m_pimpl->Attachments.size() > 0) {\n for (auto a : m_pimpl->Attachments) {\n vmime::shared_ptr <vmime::attachment> att = vmime::make_shared <vmime::fileAttachment>\n (a, vmime::mediaType(\"application\/octet-stream\"),\n vmime::text(boost::filesystem::path(a).stem().string()));\n mb.appendAttachment(att);\n }\n }\n\n vmime::shared_ptr<vmime::message> msg = mb.construct();\n\n vmime::utility::url url(\"smtp:\/\/localhost\");\n#if VMIME_API_MODE == VMIME_LEGACY_API\n vmime::shared_ptr<vmime::net::session> sess = vmime::make_shared<vmime::net::session>();\n#else\n vmime::shared_ptr<vmime::net::session> sess = vmime::net::session::create();\n#endif \/\/ VMIME_API_MODE == VMIME_LEGACY_API\n vmime::shared_ptr<vmime::net::transport> tr = sess->getTransport(url);\n\n tr->connect();\n tr->send(msg);\n tr->disconnect();\n\n return true;\n }\n\n catch (vmime::exception &ex) {\n out_error.assign(ex.what());\n }\n\n catch(std::exception &ex) {\n out_error.assign(ex.what());\n }\n\n catch (...) {\n out_error.assign(UNKNOWN_ERROR);\n }\n\n return false;\n}\n\nvoid Mail::SendAsync(const SendCallback callback)\n{\n try {\n {\n boost::lock_guard<boost::mutex> lock(Impl::MailMutex);\n (void)lock;\n\n Impl::MailQueue.push(this);\n Impl::MailCallbackQueue.push(callback);\n }\n\n {\n boost::lock_guard<boost::mutex> lock(Impl::WorkerMutex);\n (void)lock;\n\n if (!Impl::WorkerThreadIsRunning) {\n Impl::WorkerThreadIsRunning = true;\n\n Impl::WorkerThread = make_unique<boost::thread>(Mail::Impl::DoWork);\n Impl::WorkerThread->detach();\n }\n }\n }\n\n catch (boost::exception &ex) {\n LOG_ERROR(boost::diagnostic_information(ex));\n }\n\n catch (std::exception &ex) {\n LOG_ERROR(ex.what());\n }\n\n catch (...) {\n LOG_ERROR(UNKNOWN_ERROR);\n }\n}\n\nMail::Impl::Impl()\n : DeleteLater(false)\n{\n\n}\n\nMail::Impl::~Impl() = default;\n<|endoftext|>"} {"text":"<commit_before>\/**\n * @file Cosa\/Periodic.hh\n * @version 1.0\n *\n * @section License\n * Copyright (C) 2012, Mikael Patel\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n * \n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n * \n * You should have received a copy of the GNU Lesser General\n * Public License along with this library; if not, write to the\n * Free Software Foundation, Inc., 59 Temple Place, Suite 330,\n * Boston, MA 02111-1307 USA\n *\n * @section Description\n * Periodic function handler. Syntactic sugar for watchdog timeout\n * event handlers. Subclass and implement the virtual method run()\n * as the function to be executed periodically.\n *\n * @section Limitations\n * Avoid setting period to the same value in the run method as this\n * will force the function to be executed twice in the same time frame. \n *\n * @section See Also\n * For details on time period handling see Watchdog.hh. This execution\n * pattern is also available in the FSM (Finite State Machine) class.\n * See FSM.hh.\n *\n * This file is part of the Arduino Che Cosa project.\n *\/\n\n#ifndef __COSA_PERIODIC_HH__\n#define __COSA_PERIODIC_HH__\n\n#include \"Cosa\/Types.h\"\n#include \"Cosa\/Linkage.hh\"\n#include \"Cosa\/Watchdog.hh\"\n\nclass Periodic : public Link {\nprivate:\n \/**\n * @override\n * Periodic event handler; dispatch the run() function on\n * timeout events.\n * @param[in] type the type of event.\n * @param[in] value the event value.\n *\/\n virtual void on_event(uint8_t type, uint16_t value)\n {\n if (type != Event::TIMEOUT_TYPE) return;\n run();\n }\n\npublic:\n \/**\n * Construct a periodic function handler. \n * @param[in] ms period of timeout.\n *\/\n Periodic(uint16_t ms) : \n Link()\n {\n set_period(ms);\n }\n\n \/**\n * Set timeout period.\n * @param[in] ms period of timeout.\n *\/\n void set_period(uint16_t ms)\n {\n Watchdog::attach(this, ms);\n }\n\n \/**\n * The default null function. \n *\/\n virtual void run() {}\n};\n\n#endif\n<commit_msg>Making Periodic an abstract class.<commit_after>\/**\n * @file Cosa\/Periodic.hh\n * @version 1.0\n *\n * @section License\n * Copyright (C) 2012-2013, Mikael Patel\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n * \n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n * \n * You should have received a copy of the GNU Lesser General\n * Public License along with this library; if not, write to the\n * Free Software Foundation, Inc., 59 Temple Place, Suite 330,\n * Boston, MA 02111-1307 USA\n *\n * @section Description\n * Periodic function handler. Syntactic sugar for watchdog timeout\n * event handlers. Subclass and implement the virtual method run()\n * as the function to be executed periodically.\n *\n * @section Limitations\n * Avoid setting period to the same value in the run method as this\n * will force the function to be executed twice in the same time frame. \n *\n * @section See Also\n * For details on time period handling see Watchdog.hh. This execution\n * pattern is also available in the FSM (Finite State Machine) class.\n * See FSM.hh.\n *\n * This file is part of the Arduino Che Cosa project.\n *\/\n\n#ifndef __COSA_PERIODIC_HH__\n#define __COSA_PERIODIC_HH__\n\n#include \"Cosa\/Types.h\"\n#include \"Cosa\/Linkage.hh\"\n#include \"Cosa\/Watchdog.hh\"\n\nclass Periodic : public Link {\nprivate:\n \/**\n * @override\n * Periodic event handler; dispatch the run() function on\n * timeout events.\n * @param[in] type the type of event.\n * @param[in] value the event value.\n *\/\n virtual void on_event(uint8_t type, uint16_t value)\n {\n if (type != Event::TIMEOUT_TYPE) return;\n run();\n }\n\npublic:\n \/**\n * Construct a periodic function handler. \n * @param[in] ms period of timeout.\n *\/\n Periodic(uint16_t ms) : \n Link()\n {\n set_period(ms);\n }\n\n \/**\n * Set timeout period.\n * @param[in] ms period of timeout.\n *\/\n void set_period(uint16_t ms)\n {\n Watchdog::attach(this, ms);\n }\n\n \/**\n * The default null function. \n *\/\n virtual void run() = 0;\n};\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2014 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/chromeos\/app_mode\/kiosk_mode_idle_app_name_notification.h\"\n\n#include \"base\/bind.h\"\n#include \"base\/command_line.h\"\n#include \"base\/logging.h\"\n#include \"chrome\/browser\/chromeos\/ui\/idle_app_name_notification_view.h\"\n#include \"chrome\/browser\/extensions\/extension_service.h\"\n#include \"chrome\/browser\/profiles\/profile_manager.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chromeos\/dbus\/dbus_thread_manager.h\"\n#include \"components\/user_manager\/user_manager.h\"\n#include \"extensions\/browser\/extension_system.h\"\n#include \"ui\/base\/user_activity\/user_activity_detector.h\"\n\nnamespace chromeos {\n\nnamespace {\n\n\/\/ The timeout in ms before the message shows up.\nconst int kIdleAppNameNotificationTimeoutMs = 2 * 60 * 1000;\n\n\/\/ The duration of visibility for the message.\nconst int kMessageVisibilityTimeMs = 3000;\n\n\/\/ The anomation time to show \/ hide the message.\nconst int kMessageAnimationTimeMs = 200;\n\n\/\/ Our global instance of the Kiosk mode message.\nKioskModeIdleAppNameNotification* g_kiosk_mode_idle_app_message = NULL;\n\n} \/\/ namespace\n\n\/\/ static\nvoid KioskModeIdleAppNameNotification::Initialize() {\n DCHECK(!g_kiosk_mode_idle_app_message);\n g_kiosk_mode_idle_app_message = new KioskModeIdleAppNameNotification();\n}\n\n\/\/ static\nvoid KioskModeIdleAppNameNotification::Shutdown() {\n if (g_kiosk_mode_idle_app_message) {\n delete g_kiosk_mode_idle_app_message;\n g_kiosk_mode_idle_app_message = NULL;\n }\n}\n\nKioskModeIdleAppNameNotification::KioskModeIdleAppNameNotification()\n : show_notification_upon_next_user_activity_(false) {\n \/\/ Note: The timeout is currently fixed. If that changes we need to check if\n \/\/ the KioskModeSettings were already initialized.\n Setup();\n}\n\nKioskModeIdleAppNameNotification::~KioskModeIdleAppNameNotification() {\n ui::UserActivityDetector* user_activity_detector =\n ui::UserActivityDetector::Get();\n if (user_activity_detector && user_activity_detector->HasObserver(this)) {\n user_activity_detector->RemoveObserver(this);\n \/\/ At this time the DBusThreadManager might already be gone.\n if (chromeos::DBusThreadManager::IsInitialized())\n chromeos::DBusThreadManager::Get()->GetPowerManagerClient(\n )->RemoveObserver(this);\n }\n}\n\nvoid KioskModeIdleAppNameNotification::Setup() {\n DCHECK(user_manager::UserManager::Get()->IsUserLoggedIn());\n Start();\n}\n\nvoid KioskModeIdleAppNameNotification::OnUserActivity(const ui::Event* event) {\n if (show_notification_upon_next_user_activity_) {\n base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();\n const std::string app_id =\n command_line->GetSwitchValueASCII(::switches::kAppId);\n Profile* profile = ProfileManager::GetActiveUserProfile();\n notification_.reset(\n new IdleAppNameNotificationView(\n kMessageVisibilityTimeMs,\n kMessageAnimationTimeMs,\n extensions::ExtensionSystem::Get(profile\n )->extension_service()->GetInstalledExtension(app_id)));\n show_notification_upon_next_user_activity_ = false;\n }\n ResetTimer();\n}\n\nvoid KioskModeIdleAppNameNotification::SuspendDone(\n const base::TimeDelta& sleep_duration) {\n \/\/ When we come back from a system resume we stop the timer and show the\n \/\/ message.\n timer_.Stop();\n OnTimeout();\n}\n\nvoid KioskModeIdleAppNameNotification::Start() {\n if (!ui::UserActivityDetector::Get()->HasObserver(this)) {\n ui::UserActivityDetector::Get()->AddObserver(this);\n chromeos::DBusThreadManager::Get()->GetPowerManagerClient()->AddObserver(\n this);\n }\n ResetTimer();\n}\n\nvoid KioskModeIdleAppNameNotification::ResetTimer() {\n if (timer_.IsRunning()) {\n timer_.Reset();\n } else {\n \/\/ OneShotTimer destroys the posted task after running it, so Reset()\n \/\/ isn't safe to call on a timer that's already fired.\n timer_.Start(\n FROM_HERE,\n base::TimeDelta::FromMilliseconds(kIdleAppNameNotificationTimeoutMs),\n base::Bind(&KioskModeIdleAppNameNotification::OnTimeout,\n base::Unretained(this)));\n }\n}\n\nvoid KioskModeIdleAppNameNotification::OnTimeout() {\n show_notification_upon_next_user_activity_ = true;\n}\n\n} \/\/ namespace chromeos\n<commit_msg>Disable return from idle notification on external displays and increase the idle timeout to 20 minutes.<commit_after>\/\/ Copyright 2014 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/chromeos\/app_mode\/kiosk_mode_idle_app_name_notification.h\"\n\n#include \"ash\/shell.h\"\n#include \"base\/bind.h\"\n#include \"base\/command_line.h\"\n#include \"base\/logging.h\"\n#include \"chrome\/browser\/chromeos\/ui\/idle_app_name_notification_view.h\"\n#include \"chrome\/browser\/extensions\/extension_service.h\"\n#include \"chrome\/browser\/profiles\/profile_manager.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chromeos\/dbus\/dbus_thread_manager.h\"\n#include \"components\/user_manager\/user_manager.h\"\n#include \"extensions\/browser\/extension_system.h\"\n#include \"ui\/base\/user_activity\/user_activity_detector.h\"\n#include \"ui\/gfx\/display.h\"\n#include \"ui\/gfx\/screen.h\"\n\nnamespace chromeos {\n\nnamespace {\n\n\/\/ The timeout in ms before the message shows up.\nconst int kIdleAppNameNotificationTimeoutMs = 20 * 60 * 1000;\n\n\/\/ The duration of visibility for the message.\nconst int kMessageVisibilityTimeMs = 3000;\n\n\/\/ The anomation time to show \/ hide the message.\nconst int kMessageAnimationTimeMs = 200;\n\n\/\/ Our global instance of the Kiosk mode message.\nKioskModeIdleAppNameNotification* g_kiosk_mode_idle_app_message = NULL;\n\n} \/\/ namespace\n\n\/\/ static\nvoid KioskModeIdleAppNameNotification::Initialize() {\n DCHECK(!g_kiosk_mode_idle_app_message);\n g_kiosk_mode_idle_app_message = new KioskModeIdleAppNameNotification();\n}\n\n\/\/ static\nvoid KioskModeIdleAppNameNotification::Shutdown() {\n if (g_kiosk_mode_idle_app_message) {\n delete g_kiosk_mode_idle_app_message;\n g_kiosk_mode_idle_app_message = NULL;\n }\n}\n\nKioskModeIdleAppNameNotification::KioskModeIdleAppNameNotification()\n : show_notification_upon_next_user_activity_(false) {\n \/\/ Note: The timeout is currently fixed. If that changes we need to check if\n \/\/ the KioskModeSettings were already initialized.\n Setup();\n}\n\nKioskModeIdleAppNameNotification::~KioskModeIdleAppNameNotification() {\n ui::UserActivityDetector* user_activity_detector =\n ui::UserActivityDetector::Get();\n if (user_activity_detector && user_activity_detector->HasObserver(this)) {\n user_activity_detector->RemoveObserver(this);\n \/\/ At this time the DBusThreadManager might already be gone.\n if (chromeos::DBusThreadManager::IsInitialized())\n chromeos::DBusThreadManager::Get()->GetPowerManagerClient(\n )->RemoveObserver(this);\n }\n}\n\nvoid KioskModeIdleAppNameNotification::Setup() {\n DCHECK(user_manager::UserManager::Get()->IsUserLoggedIn());\n Start();\n}\n\nvoid KioskModeIdleAppNameNotification::OnUserActivity(const ui::Event* event) {\n if (show_notification_upon_next_user_activity_) {\n gfx::Display display = ash::Shell::GetScreen()->GetPrimaryDisplay();\n \/\/ Display the notification only on internal display.\n if (display.IsInternal()) {\n base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();\n const std::string app_id =\n command_line->GetSwitchValueASCII(::switches::kAppId);\n Profile* profile = ProfileManager::GetActiveUserProfile();\n notification_.reset(\n new IdleAppNameNotificationView(\n kMessageVisibilityTimeMs,\n kMessageAnimationTimeMs,\n extensions::ExtensionSystem::Get(profile\n )->extension_service()->GetInstalledExtension(app_id)));\n }\n show_notification_upon_next_user_activity_ = false;\n }\n ResetTimer();\n}\n\nvoid KioskModeIdleAppNameNotification::SuspendDone(\n const base::TimeDelta& sleep_duration) {\n \/\/ When we come back from a system resume we stop the timer and show the\n \/\/ message.\n timer_.Stop();\n OnTimeout();\n}\n\nvoid KioskModeIdleAppNameNotification::Start() {\n if (!ui::UserActivityDetector::Get()->HasObserver(this)) {\n ui::UserActivityDetector::Get()->AddObserver(this);\n chromeos::DBusThreadManager::Get()->GetPowerManagerClient()->AddObserver(\n this);\n }\n ResetTimer();\n}\n\nvoid KioskModeIdleAppNameNotification::ResetTimer() {\n if (timer_.IsRunning()) {\n timer_.Reset();\n } else {\n \/\/ OneShotTimer destroys the posted task after running it, so Reset()\n \/\/ isn't safe to call on a timer that's already fired.\n timer_.Start(\n FROM_HERE,\n base::TimeDelta::FromMilliseconds(kIdleAppNameNotificationTimeoutMs),\n base::Bind(&KioskModeIdleAppNameNotification::OnTimeout,\n base::Unretained(this)));\n }\n}\n\nvoid KioskModeIdleAppNameNotification::OnTimeout() {\n show_notification_upon_next_user_activity_ = true;\n}\n\n} \/\/ namespace chromeos\n<|endoftext|>"} {"text":"<commit_before>\/* IBM_PROLOG_BEGIN_TAG *\/\n\/* This is an automatically generated prolog. *\/\n\/* *\/\n\/* $Source: src\/import\/chips\/p9\/procedures\/hwp\/cache\/p9_hcd_cache_stopclocks.H $ *\/\n\/* *\/\n\/* OpenPOWER HostBoot Project *\/\n\/* *\/\n\/* Contributors Listed Below - COPYRIGHT 2015,2019 *\/\n\/* [+] International Business Machines Corp. *\/\n\/* *\/\n\/* *\/\n\/* Licensed under the Apache License, Version 2.0 (the \"License\"); *\/\n\/* you may not use this file except in compliance with the License. *\/\n\/* You may obtain a copy of the License at *\/\n\/* *\/\n\/* http:\/\/www.apache.org\/licenses\/LICENSE-2.0 *\/\n\/* *\/\n\/* Unless required by applicable law or agreed to in writing, software *\/\n\/* distributed under the License is distributed on an \"AS IS\" BASIS, *\/\n\/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or *\/\n\/* implied. See the License for the specific language governing *\/\n\/* permissions and limitations under the License. *\/\n\/* *\/\n\/* IBM_PROLOG_END_TAG *\/\n\/\/\/\n\/\/\/ @file p9_hcd_cache_stopclocks.H\n\/\/\/ @brief Quad Clock Stop\n\/\/\/\n\n\/\/ *HWP HWP Owner : David Du <daviddu@us.ibm.com>\n\/\/ *HWP Backup HWP Owner : Greg Still <stillgs@us.ibm.com>\n\/\/ *HWP FW Owner : Sangeetha T S <sangeet2@in.ibm.com>\n\/\/ *HWP Team : PM\n\/\/ *HWP Consumed by : HB:PERV\n\/\/ *HWP Level : 2\n\n#ifndef __P9_HCD_CACHE_STOPCLOCKS_H__\n#define __P9_HCD_CACHE_STOPCLOCKS_H__\n\n#include <fapi2.H>\n#include <p9_hcd_common.H>\n\n\/\/\/ @typedef p9_hcd_cache_stopclocks_FP_t\n\/\/\/ function pointer typedef definition for HWP call support\ntypedef fapi2::ReturnCode (*p9_hcd_cache_stopclocks_FP_t) (\n const fapi2::Target<fapi2::TARGET_TYPE_EQ>&,\n const p9hcd::P9_HCD_CLK_CTRL_CONSTANTS,\n const p9hcd::P9_HCD_EX_CTRL_CONSTANTS,\n const bool);\n\nextern \"C\"\n{\n\n\/\/\/ @brief Quad Clock Stop\n\/\/\/ @param [in] i_target TARGET_TYPE_EQ target\n\/\/\/ @param [in] i_select_regions select clk regions on stopclocks\n\/\/\/ @param [in] i_select_ex select ex's on stopclocks\n\/\/\/ @param [in] i_sync_stop_quad_clk to stop CACHE & CORE chiplet clocks synchronously\n\/\/\/ @return FAPI2_RC_SUCCESS if success, else error code\n fapi2::ReturnCode\n p9_hcd_cache_stopclocks(\n const fapi2::Target<fapi2::TARGET_TYPE_EQ>& i_target,\n const p9hcd::P9_HCD_CLK_CTRL_CONSTANTS i_select_regions,\n const p9hcd::P9_HCD_EX_CTRL_CONSTANTS i_select_ex,\n const bool i_sync_stop_quad_clk = false);\n\n}\n\n#endif \/\/ __P9_HCD_CACHE_STOPCLOCKS_H__\n<commit_msg>L3 Update - p9_hcd_cache_stopclocks HWP<commit_after>\/* IBM_PROLOG_BEGIN_TAG *\/\n\/* This is an automatically generated prolog. *\/\n\/* *\/\n\/* $Source: src\/import\/chips\/p9\/procedures\/hwp\/cache\/p9_hcd_cache_stopclocks.H $ *\/\n\/* *\/\n\/* OpenPOWER HostBoot Project *\/\n\/* *\/\n\/* Contributors Listed Below - COPYRIGHT 2015,2019 *\/\n\/* [+] International Business Machines Corp. *\/\n\/* *\/\n\/* *\/\n\/* Licensed under the Apache License, Version 2.0 (the \"License\"); *\/\n\/* you may not use this file except in compliance with the License. *\/\n\/* You may obtain a copy of the License at *\/\n\/* *\/\n\/* http:\/\/www.apache.org\/licenses\/LICENSE-2.0 *\/\n\/* *\/\n\/* Unless required by applicable law or agreed to in writing, software *\/\n\/* distributed under the License is distributed on an \"AS IS\" BASIS, *\/\n\/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or *\/\n\/* implied. See the License for the specific language governing *\/\n\/* permissions and limitations under the License. *\/\n\/* *\/\n\/* IBM_PROLOG_END_TAG *\/\n\/\/\/\n\/\/\/ @file p9_hcd_cache_stopclocks.H\n\/\/\/ @brief Quad Clock Stop\n\/\/\/\n\n\/\/ *HWP HWP Owner : David Du <daviddu@us.ibm.com>\n\/\/ *HWP Backup HWP Owner : Greg Still <stillgs@us.ibm.com>\n\/\/ *HWP FW Owner : Amit Tendolkar <amit.tendolkar@in.ibm.com>\n\/\/ *HWP Team : PM\n\/\/ *HWP Consumed by : HB:PERV\n\/\/ *HWP Level : 3\n\n#ifndef __P9_HCD_CACHE_STOPCLOCKS_H__\n#define __P9_HCD_CACHE_STOPCLOCKS_H__\n\n#include <fapi2.H>\n#include <p9_hcd_common.H>\n\n\/\/\/ @typedef p9_hcd_cache_stopclocks_FP_t\n\/\/\/ function pointer typedef definition for HWP call support\ntypedef fapi2::ReturnCode (*p9_hcd_cache_stopclocks_FP_t) (\n const fapi2::Target<fapi2::TARGET_TYPE_EQ>&,\n const p9hcd::P9_HCD_CLK_CTRL_CONSTANTS,\n const p9hcd::P9_HCD_EX_CTRL_CONSTANTS,\n const bool);\n\nextern \"C\"\n{\n\n\/\/\/ @brief Quad Clock Stop\n\/\/\/ @param [in] i_target TARGET_TYPE_EQ target\n\/\/\/ @param [in] i_select_regions select clk regions on stopclocks\n\/\/\/ @param [in] i_select_ex select ex's on stopclocks\n\/\/\/ @param [in] i_sync_stop_quad_clk to stop CACHE & CORE chiplet clocks synchronously\n\/\/\/ @return FAPI2_RC_SUCCESS if success, else error code\n fapi2::ReturnCode\n p9_hcd_cache_stopclocks(\n const fapi2::Target<fapi2::TARGET_TYPE_EQ>& i_target,\n const p9hcd::P9_HCD_CLK_CTRL_CONSTANTS i_select_regions,\n const p9hcd::P9_HCD_EX_CTRL_CONSTANTS i_select_ex,\n const bool i_sync_stop_quad_clk = false);\n\n}\n\n#endif \/\/ __P9_HCD_CACHE_STOPCLOCKS_H__\n<|endoftext|>"} {"text":"<commit_before>\/*-------------------------------------------------------------------------\n * drawElements Quality Program Tester Core\n * ----------------------------------------\n *\n * Copyright 2014 The Android Open Source Project\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *\/\/*!\n * \\file\n * \\brief X11 Platform.\n *\/\/*--------------------------------------------------------------------*\/\n\n#include \"tcuX11Platform.hpp\"\n\n#include \"deUniquePtr.hpp\"\n#include \"gluPlatform.hpp\"\n#include \"vkPlatform.hpp\"\n#include \"tcuX11.hpp\"\n#include \"tcuFunctionLibrary.hpp\"\n#include \"deMemory.h\"\n\n#if defined (DEQP_SUPPORT_GLX)\n#\tinclude \"tcuX11GlxPlatform.hpp\"\n#endif\n#if defined (DEQP_SUPPORT_EGL)\n#\tinclude \"tcuX11EglPlatform.hpp\"\n#endif\n\n#include <sys\/utsname.h>\n\nnamespace tcu\n{\nnamespace x11\n{\n\nclass X11GLPlatform : public glu::Platform\n{\npublic:\n\tvoid\t\tregisterFactory\t(de::MovePtr<glu::ContextFactory> factory)\n\t{\n\t\tm_contextFactoryRegistry.registerFactory(factory.release());\n\t}\n};\n\nclass VulkanLibrary : public vk::Library\n{\npublic:\n\tVulkanLibrary (void)\n\t\t: m_library\t(\"libvulkan.so.1\")\n\t\t, m_driver\t(m_library)\n\t{\n\t}\n\n\tconst vk::PlatformInterface& getPlatformInterface (void) const\n\t{\n\t\treturn m_driver;\n\t}\n\nprivate:\n\tconst tcu::DynamicFunctionLibrary\tm_library;\n\tconst vk::PlatformDriver\t\t\tm_driver;\n};\n\nclass X11VulkanPlatform : public vk::Platform\n{\npublic:\n\tvk::Library* createLibrary (void) const\n\t{\n\t\treturn new VulkanLibrary();\n\t}\n\n\tvoid describePlatform (std::ostream& dst) const\n\t{\n\t\tutsname\t\tsysInfo;\n\n\t\tdeMemset(&sysInfo, 0, sizeof(sysInfo));\n\n\t\tif (uname(&sysInfo) != 0)\n\t\t\tthrow std::runtime_error(\"uname() failed\");\n\n\t\tdst << \"OS: \" << sysInfo.sysname << \" \" << sysInfo.release << \" \" << sysInfo.version << \"\\n\";\n\t\tdst << \"CPU: \" << sysInfo.machine << \"\\n\";\n\t}\n\n\tvoid getMemoryLimits (vk::PlatformMemoryLimits& limits) const\n\t{\n\t\tlimits.totalSystemMemory\t\t\t\t\t= 256*1024*1024;\n\t\tlimits.totalDeviceLocalMemory\t\t\t\t= 128*1024*1024;\n\t\tlimits.deviceMemoryAllocationGranularity\t= 64*1024;\n\t\tlimits.devicePageSize\t\t\t\t\t\t= 4096;\n\t\tlimits.devicePageTableEntrySize\t\t\t\t= 8;\n\t\tlimits.devicePageTableHierarchyLevels\t\t= 3;\n\t}\n};\n\nclass X11Platform : public tcu::Platform\n{\npublic:\n\t\t\t\t\t\t\tX11Platform\t\t\t(void);\n\tbool\t\t\t\t\tprocessEvents\t\t(void) { return !m_eventState.getQuitFlag(); }\n\tconst glu::Platform&\tgetGLPlatform\t\t(void) const { return m_glPlatform; }\n\n#if defined (DEQP_SUPPORT_EGL)\n\tconst eglu::Platform&\tgetEGLPlatform\t\t(void) const { return m_eglPlatform; }\n#endif \/\/ DEQP_SUPPORT_EGL\n\n\tconst vk::Platform&\t\tgetVulkanPlatform\t(void) const { return m_vkPlatform; }\n\nprivate:\n\tEventState\t\t\t\tm_eventState;\n#if defined (DEQP_SUPPORT_EGL)\n\tx11::egl::Platform\t\tm_eglPlatform;\n#endif \/\/ DEQP_SPPORT_EGL\n\tX11GLPlatform\t\t\tm_glPlatform;\n\tX11VulkanPlatform\t\tm_vkPlatform;\n};\n\nX11Platform::X11Platform (void)\n#if defined (DEQP_SUPPORT_EGL)\n\t: m_eglPlatform\t(m_eventState)\n#endif \/\/ DEQP_SUPPORT_EGL\n{\n#if defined (DEQP_SUPPORT_GLX)\n\tm_glPlatform.registerFactory(glx::createContextFactory(m_eventState));\n#endif \/\/ DEQP_SUPPORT_GLX\n#if defined (DEQP_SUPPORT_EGL)\n\tm_glPlatform.registerFactory(m_eglPlatform.createContextFactory());\n#endif \/\/ DEQP_SUPPORT_EGL\n}\n\n} \/\/ x11\n} \/\/ tcu\n\ntcu::Platform* createPlatform (void)\n{\n\treturn new tcu::x11::X11Platform();\n}\n<commit_msg>x11: Call XInitThreads() am: 5d11c9d2c0 am: 0fe4efcfa8 am: 8c04df2e48 am: c6bf22467b<commit_after>\/*-------------------------------------------------------------------------\n * drawElements Quality Program Tester Core\n * ----------------------------------------\n *\n * Copyright 2014 The Android Open Source Project\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *\/\/*!\n * \\file\n * \\brief X11 Platform.\n *\/\/*--------------------------------------------------------------------*\/\n\n#include \"tcuX11Platform.hpp\"\n\n#include \"deUniquePtr.hpp\"\n#include \"gluPlatform.hpp\"\n#include \"vkPlatform.hpp\"\n#include \"tcuX11.hpp\"\n#include \"tcuFunctionLibrary.hpp\"\n#include \"deMemory.h\"\n\n#if defined (DEQP_SUPPORT_GLX)\n#\tinclude \"tcuX11GlxPlatform.hpp\"\n#endif\n#if defined (DEQP_SUPPORT_EGL)\n#\tinclude \"tcuX11EglPlatform.hpp\"\n#endif\n\n#include <sys\/utsname.h>\n\nnamespace tcu\n{\nnamespace x11\n{\n\nclass X11GLPlatform : public glu::Platform\n{\npublic:\n\tvoid\t\tregisterFactory\t(de::MovePtr<glu::ContextFactory> factory)\n\t{\n\t\tm_contextFactoryRegistry.registerFactory(factory.release());\n\t}\n};\n\nclass VulkanLibrary : public vk::Library\n{\npublic:\n\tVulkanLibrary (void)\n\t\t: m_library\t(\"libvulkan.so.1\")\n\t\t, m_driver\t(m_library)\n\t{\n\t}\n\n\tconst vk::PlatformInterface& getPlatformInterface (void) const\n\t{\n\t\treturn m_driver;\n\t}\n\nprivate:\n\tconst tcu::DynamicFunctionLibrary\tm_library;\n\tconst vk::PlatformDriver\t\t\tm_driver;\n};\n\nclass X11VulkanPlatform : public vk::Platform\n{\npublic:\n\tvk::Library* createLibrary (void) const\n\t{\n\t\treturn new VulkanLibrary();\n\t}\n\n\tvoid describePlatform (std::ostream& dst) const\n\t{\n\t\tutsname\t\tsysInfo;\n\n\t\tdeMemset(&sysInfo, 0, sizeof(sysInfo));\n\n\t\tif (uname(&sysInfo) != 0)\n\t\t\tthrow std::runtime_error(\"uname() failed\");\n\n\t\tdst << \"OS: \" << sysInfo.sysname << \" \" << sysInfo.release << \" \" << sysInfo.version << \"\\n\";\n\t\tdst << \"CPU: \" << sysInfo.machine << \"\\n\";\n\t}\n\n\tvoid getMemoryLimits (vk::PlatformMemoryLimits& limits) const\n\t{\n\t\tlimits.totalSystemMemory\t\t\t\t\t= 256*1024*1024;\n\t\tlimits.totalDeviceLocalMemory\t\t\t\t= 128*1024*1024;\n\t\tlimits.deviceMemoryAllocationGranularity\t= 64*1024;\n\t\tlimits.devicePageSize\t\t\t\t\t\t= 4096;\n\t\tlimits.devicePageTableEntrySize\t\t\t\t= 8;\n\t\tlimits.devicePageTableHierarchyLevels\t\t= 3;\n\t}\n};\n\nclass X11Platform : public tcu::Platform\n{\npublic:\n\t\t\t\t\t\t\tX11Platform\t\t\t(void);\n\tbool\t\t\t\t\tprocessEvents\t\t(void) { return !m_eventState.getQuitFlag(); }\n\tconst glu::Platform&\tgetGLPlatform\t\t(void) const { return m_glPlatform; }\n\n#if defined (DEQP_SUPPORT_EGL)\n\tconst eglu::Platform&\tgetEGLPlatform\t\t(void) const { return m_eglPlatform; }\n#endif \/\/ DEQP_SUPPORT_EGL\n\n\tconst vk::Platform&\t\tgetVulkanPlatform\t(void) const { return m_vkPlatform; }\n\nprivate:\n\tEventState\t\t\t\tm_eventState;\n#if defined (DEQP_SUPPORT_EGL)\n\tx11::egl::Platform\t\tm_eglPlatform;\n#endif \/\/ DEQP_SPPORT_EGL\n\tX11GLPlatform\t\t\tm_glPlatform;\n\tX11VulkanPlatform\t\tm_vkPlatform;\n};\n\nX11Platform::X11Platform (void)\n#if defined (DEQP_SUPPORT_EGL)\n\t: m_eglPlatform\t(m_eventState)\n#endif \/\/ DEQP_SUPPORT_EGL\n{\n#if defined (DEQP_SUPPORT_GLX)\n\tm_glPlatform.registerFactory(glx::createContextFactory(m_eventState));\n#endif \/\/ DEQP_SUPPORT_GLX\n#if defined (DEQP_SUPPORT_EGL)\n\tm_glPlatform.registerFactory(m_eglPlatform.createContextFactory());\n#endif \/\/ DEQP_SUPPORT_EGL\n}\n\n} \/\/ x11\n} \/\/ tcu\n\ntcu::Platform* createPlatform (void)\n{\n\t\/\/ From man:XinitThreads(3):\n\t\/\/\n\t\/\/ The XInitThreads function initializes Xlib support for concurrent\n\t\/\/ threads. This function must be the first Xlib function\n\t\/\/ a multi-threaded program calls, and it must complete before any other\n\t\/\/ Xlib call is made.\n\tDE_CHECK_RUNTIME_ERR(XInitThreads() != 0);\n\n\treturn new tcu::x11::X11Platform();\n}\n<|endoftext|>"} {"text":"<commit_before>\/*=========================================================================\n\n Program: Visualization Toolkit\n Module: vtkFrustumCoverageCuller.cxx\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n\nCopyright (c) 1993-2001 Ken Martin, Will Schroeder, Bill Lorensen \nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n * Redistributions of source code must retain the above copyright notice,\n this list of conditions and the following disclaimer.\n\n * Redistributions in binary form must reproduce the above copyright notice,\n this list of conditions and the following disclaimer in the documentation\n and\/or other materials provided with the distribution.\n\n * Neither name of Ken Martin, Will Schroeder, or Bill Lorensen nor the names\n of any contributors may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\n * Modified source versions must be plainly marked as such, and must not be\n misrepresented as being the original software.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS''\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE FOR\nANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\nDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\nSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\nCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\nOR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n=========================================================================*\/\n#include \"vtkFrustumCoverageCuller.h\"\n#include \"vtkProp.h\"\n#include \"vtkRenderer.h\"\n#include \"vtkObjectFactory.h\"\n\n\n\n\/\/------------------------------------------------------------------------------\nvtkFrustumCoverageCuller* vtkFrustumCoverageCuller::New()\n{\n \/\/ First try to create the object from the vtkObjectFactory\n vtkObject* ret = vtkObjectFactory::CreateInstance(\"vtkFrustumCoverageCuller\");\n if(ret)\n {\n return (vtkFrustumCoverageCuller*)ret;\n }\n \/\/ If the factory was unable to create the object, then create it here.\n return new vtkFrustumCoverageCuller;\n}\n\n\n\n\n\/\/ Create a frustum coverage culler with default values\nvtkFrustumCoverageCuller::vtkFrustumCoverageCuller()\n{\n this->MinimumCoverage = 0.0001;\n this->MaximumCoverage = 1.0;\n this->SortingStyle = VTK_CULLER_SORT_NONE;\n}\n\n\/\/ The coverage is computed for each prop, and a resulting allocated\n\/\/ render time is computed. This is multiplied by the current allocated\n\/\/ render time of the prop. After this, props with no allocated time are\n\/\/ removed from the list (and the list length is shortened) to make sure\n\/\/ that they are not considered again by another culler or for rendering.\nfloat vtkFrustumCoverageCuller::Cull( vtkRenderer *ren, \n\t\t\t\t vtkProp **propList,\n\t\t\t\t int& listLength,\n\t\t\t\t int& initialized )\n{\n vtkProp *prop;\n float total_time;\n float *bounds, center[3];\n float radius = 0.0;\n float planes[24], d;\n float coverage, screen_bounds[4];\n float previous_time;\n int i, propLoop;\n float full_w, full_h, part_w, part_h;\n float *allocatedTimeList;\n float *distanceList;\n int index1, index2;\n float tmp;\n float aspect[2];\n\n \/\/ We will create a center distance entry for each prop in the list\n \/\/ If SortingStyle is set to BackToFront or FrontToBack we will then\n \/\/ sort the props that have a non-zero AllocatedRenderTime by their\n \/\/ center distance\n distanceList = new float[listLength];\n\n \/\/ We will return the total time of all props. This is used for\n \/\/ normalization.\n total_time = 0;\n\n ren->GetAspect( aspect );\n \/\/ Get the view frustum planes from the active camera\n ren->GetActiveCamera()->GetFrustumPlanes( (aspect[0] \/ aspect[1]), planes );\n\n \/\/ Keep a list of allocated times to help with sorting \/ removing\n \/\/ props later\n allocatedTimeList = new float[listLength];\n\n \/\/ For each prop, compute coverage\n for ( propLoop = 0; propLoop < listLength; propLoop++ )\n {\n \/\/ Get the prop out of the list\n prop = propList[propLoop];\n\n \/\/ If allocated render time has not been initialized yet (if this\n \/\/ is the first culler, it hasn't) then the previous time is set\n \/\/ to 0.0\n if ( !initialized )\n {\n previous_time = 1.0;\n }\n else\n {\n previous_time = prop->GetRenderTimeMultiplier();\n }\n\n \/\/ Get the bounds of the prop and compute an enclosing sphere\n bounds = prop->GetBounds();\n\n \/\/ We start with a coverage of 1.0 and set it to zero if the prop\n \/\/ is culled during the plane tests\n coverage = 1.0;\n \/\/ make sure the bounds are defined - they won't be for a 2D prop which\n \/\/ means that they will never be culled. Maybe this should be changed in\n \/\/ the future?\n if (bounds)\n {\n \/\/ a duff dataset like a polydata with no cells will have bad bounds\n if ((bounds[0] == -VTK_LARGE_FLOAT) || (bounds[0] == VTK_LARGE_FLOAT))\n {\n\t coverage = 0.0;\n\t i = 7;\n }\n else\n {\n center[0] = (bounds[0] + bounds[1]) \/ 2.0;\n center[1] = (bounds[2] + bounds[3]) \/ 2.0;\n center[2] = (bounds[4] + bounds[5]) \/ 2.0;\n radius = 0.5 * sqrt( (double)\n\t\t\t ( bounds[1] - bounds[0] ) *\n\t\t\t ( bounds[1] - bounds[0] ) +\n\t\t\t ( bounds[3] - bounds[2] ) *\n\t\t\t ( bounds[3] - bounds[2] ) +\n\t\t\t ( bounds[5] - bounds[4] ) *\n\t\t\t ( bounds[5] - bounds[4] ) );\n for ( i = 0; i < 6; i++ )\n {\n \/\/ Compute how far the center of the sphere is from this plane\n d =\n planes[i*4 + 0] * center[0] +\n planes[i*4 + 1] * center[1] +\n planes[i*4 + 2] * center[2] +\n planes[i*4 + 3];\n \/\/ If d < -radius the prop is not within the view frustum\n\t if ( d < -radius )\n\t {\n\t coverage = 0.0;\n\t i = 7;\n\t }\n \/\/ The first four planes are the ones bounding the edges of the\n \/\/ view plane (the last two are the near and far planes) The\n \/\/ distance from the edge of the sphere to these planes is stored\n \/\/ to compute coverage.\n if ( i < 4 )\n {\n screen_bounds[i] = d - radius;\n }\n\t \/\/ The fifth plane is the near plane - use the distance to\n \/\/ the center (d) as the value to sort by\n\t if ( i == 4 )\n\t {\n\t distanceList[propLoop] = d;\n\t }\n }\n }\n \/\/ If the prop wasn't culled during the plane tests...\n if ( coverage > 0.0 )\n\t {\n \/\/ Compute the width and height of this slice through the\n \/\/ view frustum that contains the center of the sphere\n\t full_w = screen_bounds[0] + screen_bounds[1] + 2.0 * radius;\n\t full_h = screen_bounds[2] + screen_bounds[3] + 2.0 * radius;\n \/\/ Subtract from the full width to get the width of the square\n \/\/ enclosing the circle slice from the sphere in the plane\n \/\/ through the center of the sphere. If the screen bounds for\n \/\/ the left and right planes (0,1) are greater than zero, then\n \/\/ the edge of the sphere was a positive distance away from the\n \/\/ plane, so there is a gap between the edge of the plane and\n \/\/ the edge of the box.\n part_w = full_w;\n if ( screen_bounds[0] > 0.0 )\n {\n part_w -= screen_bounds[0];\n }\n if ( screen_bounds[1] > 0.0 )\n {\n part_w -= screen_bounds[1];\n }\n \/\/ Do the same thing for the height with the top and bottom\n \/\/ planes (2,3).\n part_h = full_h;\n if ( screen_bounds[2] > 0.0 )\n {\n part_h -= screen_bounds[2];\n }\n if ( screen_bounds[3] > 0.0 )\n {\n part_h -= screen_bounds[3];\n }\n\n \/\/ Compute the fraction of coverage\n coverage = (part_w * part_h) \/ (full_w * full_h);\n \/\/ Convert this to an allocated render time - coverage less than\n \/\/ the minumum result in 0.0 time, greater than the maximum result in\n \/\/ 1.0 time, and in between a linear ramp is used\n if ( coverage < this->MinimumCoverage )\n {\n coverage = 0;\n }\n else if ( coverage > this->MaximumCoverage )\n {\n coverage = 1.0;\n }\n else\n {\n coverage = (coverage-this->MinimumCoverage) \/\n this->MaximumCoverage;\n }\n }\n }\n \/\/ This is a 2D prop - keep them at the beginning of the list in the same\n \/\/ order they came in (by giving them all the same distance) and set\n \/\/ the coverage to something small so that they won't get much\n \/\/ allocated render time (because they aren't LOD it doesn't matter,\n \/\/ and they generally do draw fast so you don't want to take too much\n \/\/ time away from the 3D prop because you added a title to your\n \/\/ window for example) They are put at the beginning of the list so\n \/\/ that when sorted back to front they will be rendered last.\n else\n {\n distanceList[propLoop] = -VTK_LARGE_FLOAT;\n coverage = 0.001;\n }\n \/\/ Multiply the new allocated time by the previous allocated time\n coverage *= previous_time;\n prop->SetRenderTimeMultiplier( coverage );\n\n \/\/ Save this in our array of allocated times which matches the\n \/\/ prop array. Also save the center distance\n allocatedTimeList[propLoop] = coverage;\n\n \/\/ Add the time for this prop to the total time\n total_time += coverage;\n }\n\n \/\/ Now traverse the list from the beginning, swapping any zero entries back\n \/\/ in the list, while preserving the order of the non-zero entries. This\n \/\/ requires two indices for the two items we are comparing at any step.\n \/\/ The second index always moves back by one, but the first index moves back\n \/\/ by one only when it is pointing to something that has a non-zero value.\n index1 = 0;\n for ( index2 = 1; index2 < listLength; index2++ )\n {\n if ( allocatedTimeList[index1] == 0.0 )\n {\n if ( allocatedTimeList[index2] != 0.0 )\n {\n allocatedTimeList[index1] = allocatedTimeList[index2];\n distanceList[index1] = distanceList[index2];\n propList[index1] = propList[index2];\n propList[index2] = NULL;\n allocatedTimeList[index2] = 0.0;\n distanceList[index2] = 0.0;\n }\n else\n {\n propList[index1] = propList[index2] = NULL;\n allocatedTimeList[index1] = allocatedTimeList[index2] = 0.0;\n distanceList[index1] = distanceList[index2] = 0.0;\n }\n }\n if ( allocatedTimeList[index1] != 0.0 )\n {\n index1++;\n }\n }\n\n \/\/ Compute the new list length - index1 is always pointing to the\n \/\/ first 0.0 entry or the last entry if none were zero (in which case\n \/\/ we won't change the list length)\n listLength = (allocatedTimeList[index1] == 0.0)?(index1):listLength;\n\n \/\/ Now reorder the list if sorting is on\n \/\/ Do it by a simple bubble sort - there probably aren't that\n \/\/ many props....\n\n if ( this->SortingStyle == VTK_CULLER_SORT_FRONT_TO_BACK )\n {\n for ( propLoop = 1; propLoop < listLength; propLoop++ )\n {\n index1 = propLoop;\n while ( (index1 - 1) >= 0 &&\n distanceList[index1] < distanceList[index1-1] )\n {\n tmp = distanceList[index1-1];\n distanceList[index1-1] = distanceList[index1];\n distanceList[index1] = tmp;\n prop = propList[index1-1];\n propList[index1-1] = propList[index1];\n propList[index1] = prop;\n index1--;\n }\n }\n }\n if ( this->SortingStyle == VTK_CULLER_SORT_BACK_TO_FRONT )\n {\n for ( propLoop = 1; propLoop < listLength; propLoop++ )\n {\n index1 = propLoop;\n while ( (index1 - 1) >= 0 &&\n distanceList[index1] > distanceList[index1-1] )\n {\n tmp = distanceList[index1-1];\n distanceList[index1-1] = distanceList[index1];\n distanceList[index1] = tmp;\n prop = propList[index1-1];\n propList[index1-1] = propList[index1];\n propList[index1] = prop;\n index1--;\n }\n }\n }\n \/\/ The allocated render times are now initialized\n initialized = 1;\n delete [] allocatedTimeList;\n delete [] distanceList;\n return total_time;\n}\n\n\/\/ Description:\n\/\/ Return the sorting style as a descriptive character string.\nconst char *vtkFrustumCoverageCuller::GetSortingStyleAsString(void)\n{\n if( this->SortingStyle == VTK_CULLER_SORT_NONE )\n {\n return \"None\";\n }\n if( this->SortingStyle == VTK_CULLER_SORT_FRONT_TO_BACK )\n {\n return \"Front To Back\";\n }\n if( this->SortingStyle == VTK_CULLER_SORT_BACK_TO_FRONT )\n {\n return \"Back To Front\";\n }\n else\n {\n return \"Unknown\";\n }\n}\n\nvoid vtkFrustumCoverageCuller::PrintSelf(ostream& os, vtkIndent indent)\n{\n this->vtkCuller::PrintSelf(os,indent);\n\n os << indent << \"Minimum Coverage: \" \n << this->MinimumCoverage << endl;\n\n os << indent << \"Maximum Coverage: \" \n << this->MaximumCoverage << endl;\n\n os << indent << \"Sorting Style: \"\n << this->GetSortingStyleAsString() << endl;\n\n}\n<commit_msg>ERR: Divide by zero when zooming lots<commit_after>\/*=========================================================================\n\n Program: Visualization Toolkit\n Module: vtkFrustumCoverageCuller.cxx\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n\nCopyright (c) 1993-2001 Ken Martin, Will Schroeder, Bill Lorensen \nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n * Redistributions of source code must retain the above copyright notice,\n this list of conditions and the following disclaimer.\n\n * Redistributions in binary form must reproduce the above copyright notice,\n this list of conditions and the following disclaimer in the documentation\n and\/or other materials provided with the distribution.\n\n * Neither name of Ken Martin, Will Schroeder, or Bill Lorensen nor the names\n of any contributors may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\n * Modified source versions must be plainly marked as such, and must not be\n misrepresented as being the original software.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS''\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE FOR\nANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\nDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\nSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\nCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\nOR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n=========================================================================*\/\n#include \"vtkFrustumCoverageCuller.h\"\n#include \"vtkProp.h\"\n#include \"vtkRenderer.h\"\n#include \"vtkObjectFactory.h\"\n\n\n\n\/\/------------------------------------------------------------------------------\nvtkFrustumCoverageCuller* vtkFrustumCoverageCuller::New()\n{\n \/\/ First try to create the object from the vtkObjectFactory\n vtkObject* ret = vtkObjectFactory::CreateInstance(\"vtkFrustumCoverageCuller\");\n if(ret)\n {\n return (vtkFrustumCoverageCuller*)ret;\n }\n \/\/ If the factory was unable to create the object, then create it here.\n return new vtkFrustumCoverageCuller;\n}\n\n\n\n\n\/\/ Create a frustum coverage culler with default values\nvtkFrustumCoverageCuller::vtkFrustumCoverageCuller()\n{\n this->MinimumCoverage = 0.0001;\n this->MaximumCoverage = 1.0;\n this->SortingStyle = VTK_CULLER_SORT_NONE;\n}\n\n\/\/ The coverage is computed for each prop, and a resulting allocated\n\/\/ render time is computed. This is multiplied by the current allocated\n\/\/ render time of the prop. After this, props with no allocated time are\n\/\/ removed from the list (and the list length is shortened) to make sure\n\/\/ that they are not considered again by another culler or for rendering.\nfloat vtkFrustumCoverageCuller::Cull( vtkRenderer *ren, \n\t\t\t\t vtkProp **propList,\n\t\t\t\t int& listLength,\n\t\t\t\t int& initialized )\n{\n vtkProp *prop;\n float total_time;\n float *bounds, center[3];\n float radius = 0.0;\n float planes[24], d;\n float coverage, screen_bounds[4];\n float previous_time;\n int i, propLoop;\n float full_w, full_h, part_w, part_h;\n float *allocatedTimeList;\n float *distanceList;\n int index1, index2;\n float tmp;\n float aspect[2];\n\n \/\/ We will create a center distance entry for each prop in the list\n \/\/ If SortingStyle is set to BackToFront or FrontToBack we will then\n \/\/ sort the props that have a non-zero AllocatedRenderTime by their\n \/\/ center distance\n distanceList = new float[listLength];\n\n \/\/ We will return the total time of all props. This is used for\n \/\/ normalization.\n total_time = 0;\n\n ren->GetAspect( aspect );\n \/\/ Get the view frustum planes from the active camera\n ren->GetActiveCamera()->GetFrustumPlanes( (aspect[0] \/ aspect[1]), planes );\n\n \/\/ Keep a list of allocated times to help with sorting \/ removing\n \/\/ props later\n allocatedTimeList = new float[listLength];\n\n \/\/ For each prop, compute coverage\n for ( propLoop = 0; propLoop < listLength; propLoop++ )\n {\n \/\/ Get the prop out of the list\n prop = propList[propLoop];\n\n \/\/ If allocated render time has not been initialized yet (if this\n \/\/ is the first culler, it hasn't) then the previous time is set\n \/\/ to 0.0\n if ( !initialized )\n {\n previous_time = 1.0;\n }\n else\n {\n previous_time = prop->GetRenderTimeMultiplier();\n }\n\n \/\/ Get the bounds of the prop and compute an enclosing sphere\n bounds = prop->GetBounds();\n\n \/\/ We start with a coverage of 1.0 and set it to zero if the prop\n \/\/ is culled during the plane tests\n coverage = 1.0;\n \/\/ make sure the bounds are defined - they won't be for a 2D prop which\n \/\/ means that they will never be culled. Maybe this should be changed in\n \/\/ the future?\n if (bounds)\n {\n \/\/ a duff dataset like a polydata with no cells will have bad bounds\n if ((bounds[0] == -VTK_LARGE_FLOAT) || (bounds[0] == VTK_LARGE_FLOAT))\n {\n\t coverage = 0.0;\n\t i = 7;\n }\n else\n {\n center[0] = (bounds[0] + bounds[1]) \/ 2.0;\n center[1] = (bounds[2] + bounds[3]) \/ 2.0;\n center[2] = (bounds[4] + bounds[5]) \/ 2.0;\n radius = 0.5 * sqrt( (double)\n\t\t\t ( bounds[1] - bounds[0] ) *\n\t\t\t ( bounds[1] - bounds[0] ) +\n\t\t\t ( bounds[3] - bounds[2] ) *\n\t\t\t ( bounds[3] - bounds[2] ) +\n\t\t\t ( bounds[5] - bounds[4] ) *\n\t\t\t ( bounds[5] - bounds[4] ) );\n for ( i = 0; i < 6; i++ )\n {\n \/\/ Compute how far the center of the sphere is from this plane\n d =\n planes[i*4 + 0] * center[0] +\n planes[i*4 + 1] * center[1] +\n planes[i*4 + 2] * center[2] +\n planes[i*4 + 3];\n \/\/ If d < -radius the prop is not within the view frustum\n\t if ( d < -radius )\n\t {\n\t coverage = 0.0;\n\t i = 7;\n\t }\n \/\/ The first four planes are the ones bounding the edges of the\n \/\/ view plane (the last two are the near and far planes) The\n \/\/ distance from the edge of the sphere to these planes is stored\n \/\/ to compute coverage.\n if ( i < 4 )\n {\n screen_bounds[i] = d - radius;\n }\n\t \/\/ The fifth plane is the near plane - use the distance to\n \/\/ the center (d) as the value to sort by\n\t if ( i == 4 )\n\t {\n\t distanceList[propLoop] = d;\n\t }\n }\n }\n \/\/ If the prop wasn't culled during the plane tests...\n if ( coverage > 0.0 )\n\t {\n \/\/ Compute the width and height of this slice through the\n \/\/ view frustum that contains the center of the sphere\n\t full_w = screen_bounds[0] + screen_bounds[1] + 2.0 * radius;\n\t full_h = screen_bounds[2] + screen_bounds[3] + 2.0 * radius;\n \/\/ Subtract from the full width to get the width of the square\n \/\/ enclosing the circle slice from the sphere in the plane\n \/\/ through the center of the sphere. If the screen bounds for\n \/\/ the left and right planes (0,1) are greater than zero, then\n \/\/ the edge of the sphere was a positive distance away from the\n \/\/ plane, so there is a gap between the edge of the plane and\n \/\/ the edge of the box.\n part_w = full_w;\n if ( screen_bounds[0] > 0.0 )\n {\n part_w -= screen_bounds[0];\n }\n if ( screen_bounds[1] > 0.0 )\n {\n part_w -= screen_bounds[1];\n }\n \/\/ Do the same thing for the height with the top and bottom\n \/\/ planes (2,3).\n part_h = full_h;\n if ( screen_bounds[2] > 0.0 )\n {\n part_h -= screen_bounds[2];\n }\n if ( screen_bounds[3] > 0.0 )\n {\n part_h -= screen_bounds[3];\n }\n\n \/\/ Compute the fraction of coverage\n if ((full_w * full_h)!=0.0)\n {\n coverage = (part_w * part_h) \/ (full_w * full_h);\n }\n else\n {\n coverage = 0;\n }\n \/\/ Convert this to an allocated render time - coverage less than\n \/\/ the minumum result in 0.0 time, greater than the maximum result in\n \/\/ 1.0 time, and in between a linear ramp is used\n if ( coverage < this->MinimumCoverage )\n {\n coverage = 0;\n }\n else if ( coverage > this->MaximumCoverage )\n {\n coverage = 1.0;\n }\n else\n {\n coverage = (coverage-this->MinimumCoverage) \/\n this->MaximumCoverage;\n }\n }\n }\n \/\/ This is a 2D prop - keep them at the beginning of the list in the same\n \/\/ order they came in (by giving them all the same distance) and set\n \/\/ the coverage to something small so that they won't get much\n \/\/ allocated render time (because they aren't LOD it doesn't matter,\n \/\/ and they generally do draw fast so you don't want to take too much\n \/\/ time away from the 3D prop because you added a title to your\n \/\/ window for example) They are put at the beginning of the list so\n \/\/ that when sorted back to front they will be rendered last.\n else\n {\n distanceList[propLoop] = -VTK_LARGE_FLOAT;\n coverage = 0.001;\n }\n \/\/ Multiply the new allocated time by the previous allocated time\n coverage *= previous_time;\n prop->SetRenderTimeMultiplier( coverage );\n\n \/\/ Save this in our array of allocated times which matches the\n \/\/ prop array. Also save the center distance\n allocatedTimeList[propLoop] = coverage;\n\n \/\/ Add the time for this prop to the total time\n total_time += coverage;\n }\n\n \/\/ Now traverse the list from the beginning, swapping any zero entries back\n \/\/ in the list, while preserving the order of the non-zero entries. This\n \/\/ requires two indices for the two items we are comparing at any step.\n \/\/ The second index always moves back by one, but the first index moves back\n \/\/ by one only when it is pointing to something that has a non-zero value.\n index1 = 0;\n for ( index2 = 1; index2 < listLength; index2++ )\n {\n if ( allocatedTimeList[index1] == 0.0 )\n {\n if ( allocatedTimeList[index2] != 0.0 )\n {\n allocatedTimeList[index1] = allocatedTimeList[index2];\n distanceList[index1] = distanceList[index2];\n propList[index1] = propList[index2];\n propList[index2] = NULL;\n allocatedTimeList[index2] = 0.0;\n distanceList[index2] = 0.0;\n }\n else\n {\n propList[index1] = propList[index2] = NULL;\n allocatedTimeList[index1] = allocatedTimeList[index2] = 0.0;\n distanceList[index1] = distanceList[index2] = 0.0;\n }\n }\n if ( allocatedTimeList[index1] != 0.0 )\n {\n index1++;\n }\n }\n\n \/\/ Compute the new list length - index1 is always pointing to the\n \/\/ first 0.0 entry or the last entry if none were zero (in which case\n \/\/ we won't change the list length)\n listLength = (allocatedTimeList[index1] == 0.0)?(index1):listLength;\n\n \/\/ Now reorder the list if sorting is on\n \/\/ Do it by a simple bubble sort - there probably aren't that\n \/\/ many props....\n\n if ( this->SortingStyle == VTK_CULLER_SORT_FRONT_TO_BACK )\n {\n for ( propLoop = 1; propLoop < listLength; propLoop++ )\n {\n index1 = propLoop;\n while ( (index1 - 1) >= 0 &&\n distanceList[index1] < distanceList[index1-1] )\n {\n tmp = distanceList[index1-1];\n distanceList[index1-1] = distanceList[index1];\n distanceList[index1] = tmp;\n prop = propList[index1-1];\n propList[index1-1] = propList[index1];\n propList[index1] = prop;\n index1--;\n }\n }\n }\n if ( this->SortingStyle == VTK_CULLER_SORT_BACK_TO_FRONT )\n {\n for ( propLoop = 1; propLoop < listLength; propLoop++ )\n {\n index1 = propLoop;\n while ( (index1 - 1) >= 0 &&\n distanceList[index1] > distanceList[index1-1] )\n {\n tmp = distanceList[index1-1];\n distanceList[index1-1] = distanceList[index1];\n distanceList[index1] = tmp;\n prop = propList[index1-1];\n propList[index1-1] = propList[index1];\n propList[index1] = prop;\n index1--;\n }\n }\n }\n \/\/ The allocated render times are now initialized\n initialized = 1;\n delete [] allocatedTimeList;\n delete [] distanceList;\n return total_time;\n}\n\n\/\/ Description:\n\/\/ Return the sorting style as a descriptive character string.\nconst char *vtkFrustumCoverageCuller::GetSortingStyleAsString(void)\n{\n if( this->SortingStyle == VTK_CULLER_SORT_NONE )\n {\n return \"None\";\n }\n if( this->SortingStyle == VTK_CULLER_SORT_FRONT_TO_BACK )\n {\n return \"Front To Back\";\n }\n if( this->SortingStyle == VTK_CULLER_SORT_BACK_TO_FRONT )\n {\n return \"Back To Front\";\n }\n else\n {\n return \"Unknown\";\n }\n}\n\nvoid vtkFrustumCoverageCuller::PrintSelf(ostream& os, vtkIndent indent)\n{\n this->vtkCuller::PrintSelf(os,indent);\n\n os << indent << \"Minimum Coverage: \" \n << this->MinimumCoverage << endl;\n\n os << indent << \"Maximum Coverage: \" \n << this->MaximumCoverage << endl;\n\n os << indent << \"Sorting Style: \"\n << this->GetSortingStyleAsString() << endl;\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright 2011-2013 Blender Foundation\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License\n *\/\n\n#include <stdio.h>\n\n#include \"buffers.h\"\n#include \"camera.h\"\n#include \"device.h\"\n#include \"scene.h\"\n#include \"session.h\"\n\n#include \"util_args.h\"\n#include \"util_foreach.h\"\n#include \"util_function.h\"\n#include \"util_path.h\"\n#include \"util_progress.h\"\n#include \"util_string.h\"\n#include \"util_time.h\"\n#include \"util_transform.h\"\n\n#ifdef WITH_CYCLES_STANDALONE_GUI\n#include \"util_view.h\"\n#endif\n\n#include \"cycles_xml.h\"\n\nCCL_NAMESPACE_BEGIN\n\nstruct Options {\n\tSession *session;\n\tScene *scene;\n\tstring filepath;\n\tint width, height;\n\tSceneParams scene_params;\n\tSessionParams session_params;\n\tbool quiet;\n\tbool show_help, interactive, pause;\n} options;\n\nstatic void session_print(const string& str)\n{\n\t\/* print with carriage return to overwrite previous *\/\n\tprintf(\"\\r%s\", str.c_str());\n\n\t\/* add spaces to overwrite longer previous print *\/\n\tstatic int maxlen = 0;\n\tint len = str.size();\n\tmaxlen = max(len, maxlen);\n\n\tfor(int i = len; i < maxlen; i++)\n\t\tprintf(\" \");\n\n\t\/* flush because we don't write an end of line *\/\n\tfflush(stdout);\n}\n\nstatic void session_print_status()\n{\n\tint sample, tile;\n\tdouble total_time, sample_time;\n\tstring status, substatus;\n\n\t\/* get status *\/\n\tsample = options.session->progress.get_sample();\n\toptions.session->progress.get_tile(tile, total_time, sample_time);\n\toptions.session->progress.get_status(status, substatus);\n\n\tif(substatus != \"\")\n\t\tstatus += \": \" + substatus;\n\n\t\/* print status *\/\n\tstatus = string_printf(\"Sample %d %s\", sample, status.c_str());\n\tsession_print(status);\n}\n\nstatic BufferParams& session_buffer_params()\n{\n\tstatic BufferParams buffer_params;\n\tbuffer_params.width = options.width;\n\tbuffer_params.height = options.height;\n\tbuffer_params.full_width = options.width;\n\tbuffer_params.full_height = options.height;\n\n\treturn buffer_params;\n}\n\nstatic void session_init()\n{\n\toptions.session = new Session(options.session_params);\n\toptions.session->reset(session_buffer_params(), options.session_params.samples);\n\toptions.session->scene = options.scene;\n\n\tif(options.session_params.background && !options.quiet)\n\t\toptions.session->progress.set_update_callback(function_bind(&session_print_status));\n#ifdef WITH_CYCLES_STANDALONE_GUI\n\telse\n\t\toptions.session->progress.set_update_callback(function_bind(&view_redraw));\n#endif\n\n\toptions.session->start();\n\n\toptions.scene = NULL;\n}\n\nstatic void scene_init()\n{\n\toptions.scene = new Scene(options.scene_params, options.session_params.device);\n\n\t\/* Read XML *\/\n\txml_read_file(options.scene, options.filepath.c_str());\n\n\t\/* Camera width\/height override? *\/\n\tif (!(options.width == 0 || options.height == 0)) {\n\t\toptions.scene->camera->width = options.width;\n\t\toptions.scene->camera->height = options.height;\n\t}\n\telse {\n\t\toptions.width = options.scene->camera->width;\n\t\toptions.height = options.scene->camera->height;\n\t}\n\n\t\/* Calculate Viewplane *\/\n\toptions.scene->camera->compute_auto_viewplane();\n}\n\nstatic void session_exit()\n{\n\tif(options.session) {\n\t\tdelete options.session;\n\t\toptions.session = NULL;\n\t}\n\tif(options.scene) {\n\t\tdelete options.scene;\n\t\toptions.scene = NULL;\n\t}\n\n\tif(options.session_params.background && !options.quiet) {\n\t\tsession_print(\"Finished Rendering.\");\n\t\tprintf(\"\\n\");\n\t}\n}\n\n#ifdef WITH_CYCLES_STANDALONE_GUI\nstatic void display_info(Progress& progress)\n{\n\tstatic double latency = 0.0;\n\tstatic double last = 0;\n\tdouble elapsed = time_dt();\n\tstring str, interactive;\n\n\tlatency = (elapsed - last);\n\tlast = elapsed;\n\n\tint sample, tile;\n\tdouble total_time, sample_time;\n\tstring status, substatus;\n\n\tsample = progress.get_sample();\n\tprogress.get_tile(tile, total_time, sample_time);\n\tprogress.get_status(status, substatus);\n\n\tif(substatus != \"\")\n\t\tstatus += \": \" + substatus;\n\n\tinteractive = options.interactive? \"On\":\"Off\";\n\n\tstr = string_printf(\n\t \"%s\"\n\t \" Time: %.2f\"\n\t \" Latency: %.4f\"\n\t \" Sample: %d\"\n\t \" Average: %.4f\"\n\t \" Interactive: %s\",\n\t status.c_str(), total_time, latency, sample, sample_time, interactive.c_str());\n\n\tview_display_info(str.c_str());\n\n\tif(options.show_help)\n\t\tview_display_help();\n}\n\nstatic void display()\n{\n\tstatic DeviceDrawParams draw_params = DeviceDrawParams();\n\n\toptions.session->draw(session_buffer_params(), draw_params);\n\n\tdisplay_info(options.session->progress);\n}\n\nstatic void motion(int x, int y, int button)\n{\n\tif(options.interactive) {\n\t\tTransform matrix = options.session->scene->camera->matrix;\n\n\t\t\/* Translate *\/\n\t\tif(button == 0) {\n\t\t\tfloat3 translate = make_float3(x * 0.01f, -(y * 0.01f), 0.0f);\n\t\t\tmatrix = matrix * transform_translate(translate);\n\t\t}\n\n\t\t\/* Rotate *\/\n\t\telse if(button == 2) {\n\t\t\tfloat4 r1 = make_float4((float)x * 0.1f, 0.0f, 1.0f, 0.0f);\n\t\t\tmatrix = matrix * transform_rotate(DEG2RADF(r1.x), make_float3(r1.y, r1.z, r1.w));\n\n\t\t\tfloat4 r2 = make_float4(y * 0.1f, 1.0f, 0.0f, 0.0f);\n\t\t\tmatrix = matrix * transform_rotate(DEG2RADF(r2.x), make_float3(r2.y, r2.z, r2.w));\n\t\t}\n\n\t\t\/* Update and Reset *\/\n\t\toptions.session->scene->camera->matrix = matrix;\n\t\toptions.session->scene->camera->need_update = true;\n\t\toptions.session->scene->camera->need_device_update = true;\n\n\t\toptions.session->reset(session_buffer_params(), options.session_params.samples);\n\t}\n}\n\nstatic void resize(int width, int height)\n{\n\toptions.width = width;\n\toptions.height = height;\n\n\tif(options.session) {\n\t\t\/* Update camera *\/\n\t\toptions.session->scene->camera->width = width;\n\t\toptions.session->scene->camera->height = height;\n\t\toptions.session->scene->camera->compute_auto_viewplane();\n\t\toptions.session->scene->camera->need_update = true;\n\t\toptions.session->scene->camera->need_device_update = true;\n\n\t\toptions.session->reset(session_buffer_params(), options.session_params.samples);\n\t}\n}\n\nstatic void keyboard(unsigned char key)\n{\n\t\/* Toggle help *\/\n\tif(key == 'h')\n\t\toptions.show_help = !(options.show_help);\n\n\t\/* Reset *\/\n\telse if(key == 'r')\n\t\toptions.session->reset(session_buffer_params(), options.session_params.samples);\n\n\t\/* Cancel *\/\n\telse if(key == 27) \/\/ escape\n\t\toptions.session->progress.set_cancel(\"Canceled\");\n\n\t\/* Pause *\/\n\telse if(key == 'p') {\n\t\toptions.pause = !options.pause;\n\t\toptions.session->set_pause(options.pause);\n\t}\n\n\t\/* Interactive Mode *\/\n\telse if(key == 'i')\n\t\toptions.interactive = !(options.interactive);\n\n\telse if(options.interactive && (key == 'w' || key == 'a' || key == 's' || key == 'd')) {\n\t\tTransform matrix = options.session->scene->camera->matrix;\n\t\tfloat3 translate;\n\n\t\tif(key == 'w')\n\t\t\ttranslate = make_float3(0.0f, 0.0f, 0.1f);\n\t\telse if(key == 's')\n\t\t\ttranslate = make_float3(0.0f, 0.0f, -0.1f);\n\t\telse if(key == 'a')\n\t\t\ttranslate = make_float3(-0.1f, 0.0f, 0.0f);\n\t\telse if(key == 'd')\n\t\t\ttranslate = make_float3(0.1f, 0.0f, 0.0f);\n\n\t\tmatrix = matrix * transform_translate(translate);\n\n\t\t\/* Update and Reset *\/\n\t\toptions.session->scene->camera->matrix = matrix;\n\t\toptions.session->scene->camera->need_update = true;\n\t\toptions.session->scene->camera->need_device_update = true;\n\n\t\toptions.session->reset(session_buffer_params(), options.session_params.samples);\n\t}\n}\n#endif\n\nstatic int files_parse(int argc, const char *argv[])\n{\n\tif(argc > 0)\n\t\toptions.filepath = argv[0];\n\n\treturn 0;\n}\n\nstatic void options_parse(int argc, const char **argv)\n{\n\toptions.width = 0;\n\toptions.height = 0;\n\toptions.filepath = \"\";\n\toptions.session = NULL;\n\toptions.quiet = false;\n\n\t\/* device names *\/\n\tstring device_names = \"\";\n\tstring devicename = \"cpu\";\n\tbool list = false;\n\n\tvector<DeviceType>& types = Device::available_types();\n\n\tforeach(DeviceType type, types) {\n\t\tif(device_names != \"\")\n\t\t\tdevice_names += \", \";\n\n\t\tdevice_names += Device::string_from_type(type);\n\t}\n\n\t\/* shading system *\/\n\tstring ssname = \"svm\";\n\n\t\/* parse options *\/\n\tArgParse ap;\n\tbool help = false;\n\n\tap.options (\"Usage: cycles [options] file.xml\",\n\t\t\"%*\", files_parse, \"\",\n\t\t\"--device %s\", &devicename, (\"Devices to use: \" + device_names).c_str(),\n#ifdef WITH_OSL\n\t\t\"--shadingsys %s\", &ssname, \"Shading system to use: svm, osl\",\n#endif\n\t\t\"--background\", &options.session_params.background, \"Render in background, without user interface\",\n\t\t\"--quiet\", &options.quiet, \"In background mode, don't print progress messages\",\n\t\t\"--samples %d\", &options.session_params.samples, \"Number of samples to render\",\n\t\t\"--output %s\", &options.session_params.output_path, \"File path to write output image\",\n\t\t\"--threads %d\", &options.session_params.threads, \"CPU Rendering Threads\",\n\t\t\"--width %d\", &options.width, \"Window width in pixel\",\n\t\t\"--height %d\", &options.height, \"Window height in pixel\",\n\t\t\"--list-devices\", &list, \"List information about all available devices\",\n\t\t\"--help\", &help, \"Print help message\",\n\t\tNULL);\n\n\tif(ap.parse(argc, argv) < 0) {\n\t\tfprintf(stderr, \"%s\\n\", ap.geterror().c_str());\n\t\tap.usage();\n\t\texit(EXIT_FAILURE);\n\t}\n\telse if(list) {\n\t\tvector<DeviceInfo>& devices = Device::available_devices();\n\t\tprintf(\"Devices:\\n\");\n\n\t\tforeach(DeviceInfo& info, devices) {\n\t\t\tprintf(\" %s%s\\n\",\n\t\t\t\tinfo.description.c_str(),\n\t\t\t\t(info.display_device)? \" (display)\": \"\");\n\t\t}\n\n\t\texit(EXIT_SUCCESS);\n\t}\n\telse if(help || options.filepath == \"\") {\n\t\tap.usage();\n\t\texit(EXIT_SUCCESS);\n\t}\n\n\tif(ssname == \"osl\")\n\t\toptions.scene_params.shadingsystem = SceneParams::OSL;\n\telse if(ssname == \"svm\")\n\t\toptions.scene_params.shadingsystem = SceneParams::SVM;\n\n#ifndef WITH_CYCLES_STANDALONE_GUI\n\toptions.session_params.background = true;\n#endif\n\n\t\/* Use progressive rendering *\/\n\toptions.session_params.progressive = true;\n\n\t\/* find matching device *\/\n\tDeviceType device_type = Device::type_from_string(devicename.c_str());\n\tvector<DeviceInfo>& devices = Device::available_devices();\n\tDeviceInfo device_info;\n\tbool device_available = false;\n\n\tforeach(DeviceInfo& device, devices) {\n\t\tif(device_type == device.type) {\n\t\t\toptions.session_params.device = device;\n\t\t\tdevice_available = true;\n\t\t\tbreak;\n\t\t}\n\t}\n\n\t\/* handle invalid configurations *\/\n\tif(options.session_params.device.type == DEVICE_NONE || !device_available) {\n\t\tfprintf(stderr, \"Unknown device: %s\\n\", devicename.c_str());\n\t\texit(EXIT_FAILURE);\n\t}\n#ifdef WITH_OSL\n\telse if(!(ssname == \"osl\" || ssname == \"svm\")) {\n\t\tfprintf(stderr, \"Unknown shading system: %s\\n\", ssname.c_str());\n\t\texit(EXIT_FAILURE);\n\t}\n\telse if(options.scene_params.shadingsystem == SceneParams::OSL && options.session_params.device.type != DEVICE_CPU) {\n\t\tfprintf(stderr, \"OSL shading system only works with CPU device\\n\");\n\t\texit(EXIT_FAILURE);\n\t}\n#endif\n\telse if(options.session_params.samples < 0) {\n\t\tfprintf(stderr, \"Invalid number of samples: %d\\n\", options.session_params.samples);\n\t\texit(EXIT_FAILURE);\n\t}\n\telse if(options.filepath == \"\") {\n\t\tfprintf(stderr, \"No file path specified\\n\");\n\t\texit(EXIT_FAILURE);\n\t}\n\n\t\/* For smoother Viewport *\/\n\toptions.session_params.start_resolution = 64;\n\n\t\/* load scene *\/\n\tscene_init();\n}\n\nCCL_NAMESPACE_END\n\nusing namespace ccl;\n\nint main(int argc, const char **argv)\n{\n\tpath_init();\n\toptions_parse(argc, argv);\n\n#ifdef WITH_CYCLES_STANDALONE_GUI\n\tif(options.session_params.background) {\n#endif\n\t\tsession_init();\n\t\toptions.session->wait();\n\t\tsession_exit();\n#ifdef WITH_CYCLES_STANDALONE_GUI\n\t}\n\telse {\n\t\tstring title = \"Cycles: \" + path_filename(options.filepath);\n\n\t\t\/* init\/exit are callback so they run while GL is initialized *\/\n\t\tview_main_loop(title.c_str(), options.width, options.height,\n\t\t\tsession_init, session_exit, resize, display, keyboard, motion);\n\t}\n#endif\n\n\treturn 0;\n}\n\n<commit_msg>Fix cycles standalone compile error of shading system enum change.<commit_after>\/*\n * Copyright 2011-2013 Blender Foundation\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License\n *\/\n\n#include <stdio.h>\n\n#include \"buffers.h\"\n#include \"camera.h\"\n#include \"device.h\"\n#include \"scene.h\"\n#include \"session.h\"\n\n#include \"util_args.h\"\n#include \"util_foreach.h\"\n#include \"util_function.h\"\n#include \"util_path.h\"\n#include \"util_progress.h\"\n#include \"util_string.h\"\n#include \"util_time.h\"\n#include \"util_transform.h\"\n\n#ifdef WITH_CYCLES_STANDALONE_GUI\n#include \"util_view.h\"\n#endif\n\n#include \"cycles_xml.h\"\n\nCCL_NAMESPACE_BEGIN\n\nstruct Options {\n\tSession *session;\n\tScene *scene;\n\tstring filepath;\n\tint width, height;\n\tSceneParams scene_params;\n\tSessionParams session_params;\n\tbool quiet;\n\tbool show_help, interactive, pause;\n} options;\n\nstatic void session_print(const string& str)\n{\n\t\/* print with carriage return to overwrite previous *\/\n\tprintf(\"\\r%s\", str.c_str());\n\n\t\/* add spaces to overwrite longer previous print *\/\n\tstatic int maxlen = 0;\n\tint len = str.size();\n\tmaxlen = max(len, maxlen);\n\n\tfor(int i = len; i < maxlen; i++)\n\t\tprintf(\" \");\n\n\t\/* flush because we don't write an end of line *\/\n\tfflush(stdout);\n}\n\nstatic void session_print_status()\n{\n\tint sample, tile;\n\tdouble total_time, sample_time;\n\tstring status, substatus;\n\n\t\/* get status *\/\n\tsample = options.session->progress.get_sample();\n\toptions.session->progress.get_tile(tile, total_time, sample_time);\n\toptions.session->progress.get_status(status, substatus);\n\n\tif(substatus != \"\")\n\t\tstatus += \": \" + substatus;\n\n\t\/* print status *\/\n\tstatus = string_printf(\"Sample %d %s\", sample, status.c_str());\n\tsession_print(status);\n}\n\nstatic BufferParams& session_buffer_params()\n{\n\tstatic BufferParams buffer_params;\n\tbuffer_params.width = options.width;\n\tbuffer_params.height = options.height;\n\tbuffer_params.full_width = options.width;\n\tbuffer_params.full_height = options.height;\n\n\treturn buffer_params;\n}\n\nstatic void session_init()\n{\n\toptions.session = new Session(options.session_params);\n\toptions.session->reset(session_buffer_params(), options.session_params.samples);\n\toptions.session->scene = options.scene;\n\n\tif(options.session_params.background && !options.quiet)\n\t\toptions.session->progress.set_update_callback(function_bind(&session_print_status));\n#ifdef WITH_CYCLES_STANDALONE_GUI\n\telse\n\t\toptions.session->progress.set_update_callback(function_bind(&view_redraw));\n#endif\n\n\toptions.session->start();\n\n\toptions.scene = NULL;\n}\n\nstatic void scene_init()\n{\n\toptions.scene = new Scene(options.scene_params, options.session_params.device);\n\n\t\/* Read XML *\/\n\txml_read_file(options.scene, options.filepath.c_str());\n\n\t\/* Camera width\/height override? *\/\n\tif (!(options.width == 0 || options.height == 0)) {\n\t\toptions.scene->camera->width = options.width;\n\t\toptions.scene->camera->height = options.height;\n\t}\n\telse {\n\t\toptions.width = options.scene->camera->width;\n\t\toptions.height = options.scene->camera->height;\n\t}\n\n\t\/* Calculate Viewplane *\/\n\toptions.scene->camera->compute_auto_viewplane();\n}\n\nstatic void session_exit()\n{\n\tif(options.session) {\n\t\tdelete options.session;\n\t\toptions.session = NULL;\n\t}\n\tif(options.scene) {\n\t\tdelete options.scene;\n\t\toptions.scene = NULL;\n\t}\n\n\tif(options.session_params.background && !options.quiet) {\n\t\tsession_print(\"Finished Rendering.\");\n\t\tprintf(\"\\n\");\n\t}\n}\n\n#ifdef WITH_CYCLES_STANDALONE_GUI\nstatic void display_info(Progress& progress)\n{\n\tstatic double latency = 0.0;\n\tstatic double last = 0;\n\tdouble elapsed = time_dt();\n\tstring str, interactive;\n\n\tlatency = (elapsed - last);\n\tlast = elapsed;\n\n\tint sample, tile;\n\tdouble total_time, sample_time;\n\tstring status, substatus;\n\n\tsample = progress.get_sample();\n\tprogress.get_tile(tile, total_time, sample_time);\n\tprogress.get_status(status, substatus);\n\n\tif(substatus != \"\")\n\t\tstatus += \": \" + substatus;\n\n\tinteractive = options.interactive? \"On\":\"Off\";\n\n\tstr = string_printf(\n\t \"%s\"\n\t \" Time: %.2f\"\n\t \" Latency: %.4f\"\n\t \" Sample: %d\"\n\t \" Average: %.4f\"\n\t \" Interactive: %s\",\n\t status.c_str(), total_time, latency, sample, sample_time, interactive.c_str());\n\n\tview_display_info(str.c_str());\n\n\tif(options.show_help)\n\t\tview_display_help();\n}\n\nstatic void display()\n{\n\tstatic DeviceDrawParams draw_params = DeviceDrawParams();\n\n\toptions.session->draw(session_buffer_params(), draw_params);\n\n\tdisplay_info(options.session->progress);\n}\n\nstatic void motion(int x, int y, int button)\n{\n\tif(options.interactive) {\n\t\tTransform matrix = options.session->scene->camera->matrix;\n\n\t\t\/* Translate *\/\n\t\tif(button == 0) {\n\t\t\tfloat3 translate = make_float3(x * 0.01f, -(y * 0.01f), 0.0f);\n\t\t\tmatrix = matrix * transform_translate(translate);\n\t\t}\n\n\t\t\/* Rotate *\/\n\t\telse if(button == 2) {\n\t\t\tfloat4 r1 = make_float4((float)x * 0.1f, 0.0f, 1.0f, 0.0f);\n\t\t\tmatrix = matrix * transform_rotate(DEG2RADF(r1.x), make_float3(r1.y, r1.z, r1.w));\n\n\t\t\tfloat4 r2 = make_float4(y * 0.1f, 1.0f, 0.0f, 0.0f);\n\t\t\tmatrix = matrix * transform_rotate(DEG2RADF(r2.x), make_float3(r2.y, r2.z, r2.w));\n\t\t}\n\n\t\t\/* Update and Reset *\/\n\t\toptions.session->scene->camera->matrix = matrix;\n\t\toptions.session->scene->camera->need_update = true;\n\t\toptions.session->scene->camera->need_device_update = true;\n\n\t\toptions.session->reset(session_buffer_params(), options.session_params.samples);\n\t}\n}\n\nstatic void resize(int width, int height)\n{\n\toptions.width = width;\n\toptions.height = height;\n\n\tif(options.session) {\n\t\t\/* Update camera *\/\n\t\toptions.session->scene->camera->width = width;\n\t\toptions.session->scene->camera->height = height;\n\t\toptions.session->scene->camera->compute_auto_viewplane();\n\t\toptions.session->scene->camera->need_update = true;\n\t\toptions.session->scene->camera->need_device_update = true;\n\n\t\toptions.session->reset(session_buffer_params(), options.session_params.samples);\n\t}\n}\n\nstatic void keyboard(unsigned char key)\n{\n\t\/* Toggle help *\/\n\tif(key == 'h')\n\t\toptions.show_help = !(options.show_help);\n\n\t\/* Reset *\/\n\telse if(key == 'r')\n\t\toptions.session->reset(session_buffer_params(), options.session_params.samples);\n\n\t\/* Cancel *\/\n\telse if(key == 27) \/\/ escape\n\t\toptions.session->progress.set_cancel(\"Canceled\");\n\n\t\/* Pause *\/\n\telse if(key == 'p') {\n\t\toptions.pause = !options.pause;\n\t\toptions.session->set_pause(options.pause);\n\t}\n\n\t\/* Interactive Mode *\/\n\telse if(key == 'i')\n\t\toptions.interactive = !(options.interactive);\n\n\telse if(options.interactive && (key == 'w' || key == 'a' || key == 's' || key == 'd')) {\n\t\tTransform matrix = options.session->scene->camera->matrix;\n\t\tfloat3 translate;\n\n\t\tif(key == 'w')\n\t\t\ttranslate = make_float3(0.0f, 0.0f, 0.1f);\n\t\telse if(key == 's')\n\t\t\ttranslate = make_float3(0.0f, 0.0f, -0.1f);\n\t\telse if(key == 'a')\n\t\t\ttranslate = make_float3(-0.1f, 0.0f, 0.0f);\n\t\telse if(key == 'd')\n\t\t\ttranslate = make_float3(0.1f, 0.0f, 0.0f);\n\n\t\tmatrix = matrix * transform_translate(translate);\n\n\t\t\/* Update and Reset *\/\n\t\toptions.session->scene->camera->matrix = matrix;\n\t\toptions.session->scene->camera->need_update = true;\n\t\toptions.session->scene->camera->need_device_update = true;\n\n\t\toptions.session->reset(session_buffer_params(), options.session_params.samples);\n\t}\n}\n#endif\n\nstatic int files_parse(int argc, const char *argv[])\n{\n\tif(argc > 0)\n\t\toptions.filepath = argv[0];\n\n\treturn 0;\n}\n\nstatic void options_parse(int argc, const char **argv)\n{\n\toptions.width = 0;\n\toptions.height = 0;\n\toptions.filepath = \"\";\n\toptions.session = NULL;\n\toptions.quiet = false;\n\n\t\/* device names *\/\n\tstring device_names = \"\";\n\tstring devicename = \"cpu\";\n\tbool list = false;\n\n\tvector<DeviceType>& types = Device::available_types();\n\n\tforeach(DeviceType type, types) {\n\t\tif(device_names != \"\")\n\t\t\tdevice_names += \", \";\n\n\t\tdevice_names += Device::string_from_type(type);\n\t}\n\n\t\/* shading system *\/\n\tstring ssname = \"svm\";\n\n\t\/* parse options *\/\n\tArgParse ap;\n\tbool help = false;\n\n\tap.options (\"Usage: cycles [options] file.xml\",\n\t\t\"%*\", files_parse, \"\",\n\t\t\"--device %s\", &devicename, (\"Devices to use: \" + device_names).c_str(),\n#ifdef WITH_OSL\n\t\t\"--shadingsys %s\", &ssname, \"Shading system to use: svm, osl\",\n#endif\n\t\t\"--background\", &options.session_params.background, \"Render in background, without user interface\",\n\t\t\"--quiet\", &options.quiet, \"In background mode, don't print progress messages\",\n\t\t\"--samples %d\", &options.session_params.samples, \"Number of samples to render\",\n\t\t\"--output %s\", &options.session_params.output_path, \"File path to write output image\",\n\t\t\"--threads %d\", &options.session_params.threads, \"CPU Rendering Threads\",\n\t\t\"--width %d\", &options.width, \"Window width in pixel\",\n\t\t\"--height %d\", &options.height, \"Window height in pixel\",\n\t\t\"--list-devices\", &list, \"List information about all available devices\",\n\t\t\"--help\", &help, \"Print help message\",\n\t\tNULL);\n\n\tif(ap.parse(argc, argv) < 0) {\n\t\tfprintf(stderr, \"%s\\n\", ap.geterror().c_str());\n\t\tap.usage();\n\t\texit(EXIT_FAILURE);\n\t}\n\telse if(list) {\n\t\tvector<DeviceInfo>& devices = Device::available_devices();\n\t\tprintf(\"Devices:\\n\");\n\n\t\tforeach(DeviceInfo& info, devices) {\n\t\t\tprintf(\" %s%s\\n\",\n\t\t\t\tinfo.description.c_str(),\n\t\t\t\t(info.display_device)? \" (display)\": \"\");\n\t\t}\n\n\t\texit(EXIT_SUCCESS);\n\t}\n\telse if(help || options.filepath == \"\") {\n\t\tap.usage();\n\t\texit(EXIT_SUCCESS);\n\t}\n\n\tif(ssname == \"osl\")\n\t\toptions.scene_params.shadingsystem = SHADINGSYSTEM_OSL;\n\telse if(ssname == \"svm\")\n\t\toptions.scene_params.shadingsystem = SHADINGSYSTEM_SVM;\n\n#ifndef WITH_CYCLES_STANDALONE_GUI\n\toptions.session_params.background = true;\n#endif\n\n\t\/* Use progressive rendering *\/\n\toptions.session_params.progressive = true;\n\n\t\/* find matching device *\/\n\tDeviceType device_type = Device::type_from_string(devicename.c_str());\n\tvector<DeviceInfo>& devices = Device::available_devices();\n\tDeviceInfo device_info;\n\tbool device_available = false;\n\n\tforeach(DeviceInfo& device, devices) {\n\t\tif(device_type == device.type) {\n\t\t\toptions.session_params.device = device;\n\t\t\tdevice_available = true;\n\t\t\tbreak;\n\t\t}\n\t}\n\n\t\/* handle invalid configurations *\/\n\tif(options.session_params.device.type == DEVICE_NONE || !device_available) {\n\t\tfprintf(stderr, \"Unknown device: %s\\n\", devicename.c_str());\n\t\texit(EXIT_FAILURE);\n\t}\n#ifdef WITH_OSL\n\telse if(!(ssname == \"osl\" || ssname == \"svm\")) {\n\t\tfprintf(stderr, \"Unknown shading system: %s\\n\", ssname.c_str());\n\t\texit(EXIT_FAILURE);\n\t}\n\telse if(options.scene_params.shadingsystem == SHADINGSYSTEM_OSL && options.session_params.device.type != DEVICE_CPU) {\n\t\tfprintf(stderr, \"OSL shading system only works with CPU device\\n\");\n\t\texit(EXIT_FAILURE);\n\t}\n#endif\n\telse if(options.session_params.samples < 0) {\n\t\tfprintf(stderr, \"Invalid number of samples: %d\\n\", options.session_params.samples);\n\t\texit(EXIT_FAILURE);\n\t}\n\telse if(options.filepath == \"\") {\n\t\tfprintf(stderr, \"No file path specified\\n\");\n\t\texit(EXIT_FAILURE);\n\t}\n\n\t\/* For smoother Viewport *\/\n\toptions.session_params.start_resolution = 64;\n\n\t\/* load scene *\/\n\tscene_init();\n}\n\nCCL_NAMESPACE_END\n\nusing namespace ccl;\n\nint main(int argc, const char **argv)\n{\n\tpath_init();\n\toptions_parse(argc, argv);\n\n#ifdef WITH_CYCLES_STANDALONE_GUI\n\tif(options.session_params.background) {\n#endif\n\t\tsession_init();\n\t\toptions.session->wait();\n\t\tsession_exit();\n#ifdef WITH_CYCLES_STANDALONE_GUI\n\t}\n\telse {\n\t\tstring title = \"Cycles: \" + path_filename(options.filepath);\n\n\t\t\/* init\/exit are callback so they run while GL is initialized *\/\n\t\tview_main_loop(title.c_str(), options.width, options.height,\n\t\t\tsession_init, session_exit, resize, display, keyboard, motion);\n\t}\n#endif\n\n\treturn 0;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ Created by admin on 2016\/12\/9.\n\/\/\n#include <cstdio>\n#include <cmath>\n\n#include \"CrystalLib.h\"\n#include \"..\/src\/DBSCAN.h\"\n\nusing namespace Crystal;\n\nstruct Vec3f {\n union\n {\n struct {\n float x;\n float y;\n float z;\n };\n float e[3];\n };\n};\n\nint main(int argc, char** argv) {\n\n \n\n\n auto EuclidDistanceFunc = [](const Vec3f& v1, const Vec3f& v2)->float { return std::sqrt((v1.x-v2.x)*(v1.x-v2.x) + (v1.y-v2.y)*(v1.y-v2.y) + (v1.z-v2.z)*(v1.z-v2.z)); };\n\n printf(\"%f\\n\", EuclidDistanceFunc(Vec3f{ 1.f,0.f,0.f }, Vec3f{ 2.0f,0.f,0.f }));\n\n auto dbscan = DBSCAN<Vec3f, float>();\n dbscan.Run(vimg, 10.f, 20, EuclidDistanceFunc);\n printf(\"Hello Crystal\\n\");\n getchar();\n return 0;\n}\n<commit_msg>add opencv image debug<commit_after>\/\/\n\/\/ Created by admin on 2016\/12\/9.\n\/\/\n#include <cstdio>\n#include <cmath>\n#include <random>\n\n#include \"CrystalLib.h\"\n#include \"..\/src\/DBSCAN.h\"\n#include <opencv2\/opencv.hpp>\n\nusing namespace Crystal;\n\nstruct Vec3f {\n union\n {\n struct {\n float x;\n float y;\n float z;\n };\n float e[3];\n };\n};\n\nstd::vector<Vec3f> GenerateRandomDisturbCluster(const Vec3f& center, float rad, int num) {\n std::random_device rd;\n std::mt19937 gen(rd());\n std::uniform_real_distribution<> dis(-rad, rad);\n std::vector<Vec3f> rc;\n for (int i = 0; i < num; ++i) {\n rc.push_back(Vec3f{ center.x + (float)dis(gen), center.y + (float)dis(gen), center.z + (float)dis(gen)});\n }\n return rc;\n}\n\nint main(int argc, char** argv) {\n\n \n cv::Mat atom_image = cv::Mat( 1000, 1000, CV_8UC3, cv::Scalar(255,255,255) );\n\n\n std::vector<Vec3f> pts = GenerateRandomDisturbCluster(Vec3f{ 5.f,5.f,5.f }, 1.f, 200);\n\n std::vector<Vec3f> pts5 = GenerateRandomDisturbCluster(Vec3f{ 8.2f, 7.2f ,5.f }, 0.3f, 100);\n\n std::vector<Vec3f> pts4 = GenerateRandomDisturbCluster(Vec3f{ 5.9f,5.9f,5.9f }, 0.7f, 200);\n\n std::vector<Vec3f> pts3 = GenerateRandomDisturbCluster(Vec3f{ 2.f,1.f,1.f }, 0.3f, 200);\n\n std::vector<Vec3f> pts2 = GenerateRandomDisturbCluster(Vec3f{ 5.f,5.f,5.f }, 5.f, 200);\n\n pts.insert(pts.end(), pts2.begin(), pts2.end());\n pts.insert(pts.end(), pts3.begin(), pts3.end());\n pts.insert(pts.end(), pts4.begin(), pts4.end());\n pts.insert(pts.end(), pts5.begin(), pts5.end());\n\n auto EuclidDistanceFunc = [](const Vec3f& v1, const Vec3f& v2)->float { return std::sqrt((v1.x-v2.x)*(v1.x-v2.x) + (v1.y-v2.y)*(v1.y-v2.y) + (v1.z-v2.z)*(v1.z-v2.z)); };\n\n printf(\"%f\\n\", EuclidDistanceFunc(Vec3f{ 1.f,0.f,0.f }, Vec3f{ 2.0f,0.f,0.f }));\n\n auto dbscan = DBSCAN<Vec3f, float>();\n dbscan.Run(pts, 0.4f, 4, EuclidDistanceFunc);\n\n\n\n float scalar = 100.f;\n\n for (int ic = 0; ic < dbscan.Clusters.size(); ++ic) {\n std::random_device rd;\n std::mt19937 gen(rd());\n std::uniform_real_distribution<> dis(0, 255);\n Vec3f clustercolor = Vec3f{ (float)dis(gen), (float)dis(gen), (float)dis(gen) };\n for (int ip = 0; ip < dbscan.Clusters[ic].size(); ++ip) {\n int pid = dbscan.Clusters[ic][ip];\n cv::circle(\n atom_image\n , cv::Point(scalar * pts[pid].x, scalar * pts[pid].y)\n , 4\n , cv::Scalar(clustercolor.x, clustercolor.y, clustercolor.y)\\\n , -1\n );\n }\n }\n\n for (int ic = 0; ic < dbscan.Noise.size(); ++ic) {\n int pid = dbscan.Noise[ic];\n cv::circle(\n atom_image\n , cv::Point(scalar * pts[pid].x, scalar * pts[pid].y)\n , 4\n , cv::Scalar(0, 0, 0)\n , -1\n );\n }\n printf(\"Hello Crystal\\n\");\n getchar();\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*******************************************************\n * Copyright (c) 2014, ArrayFire\n * All rights reserved.\n *\n * This file is distributed under 3-clause BSD license.\n * The complete license agreement can be obtained at:\n * http:\/\/arrayfire.com\/licenses\/BSD-3-Clause\n ********************************************************\/\n\n#include <arrayfire.h>\n#include <iostream>\n#include <cstdio>\n\nusing namespace af;\nusing namespace std;\n\nstatic const int width = 512, height = 512;\nstatic const int pixels_per_unit = 20;\n\naf::array p_x;\naf::array p_y;\naf::array vels_x;\naf::array vels_y;\naf::array forces_x;\naf::array forces_y;\n\nvoid simulate(float dt){\n p_x += vels_x * pixels_per_unit * dt;\n p_y += vels_y * pixels_per_unit * dt;\n\n \/\/calculate distance to center\n af::array diff_x = p_x - width\/2;\n af::array diff_y = p_y - height\/2;\n af::array dist = sqrt( diff_x*diff_x + diff_y*diff_y );\n\n \/\/calculate normalised force vectors\n forces_x = -1 * diff_x \/ dist;\n forces_y = -1 * diff_y \/ dist;\n \/\/update force scaled to time and magnitude constant\n forces_x *= pixels_per_unit * dt;\n forces_y *= pixels_per_unit * dt;\n\n \/\/dampening\n vels_x *= 1 - (0.005*dt);\n vels_y *= 1 - (0.005*dt);\n\n \/\/update velocities from forces\n vels_x += forces_x;\n vels_y += forces_y;\n\n}\n\nvoid collisions(){\n \/\/clamp particles inside screen border\n af::array projected_px = min(width, max(0, p_x));\n af::array projected_py = min(height - 1, max(0, p_y));\n\n \/\/calculate distance to center\n af::array diff_x = projected_px - width\/2;\n af::array diff_y = projected_py - height\/2;\n af::array dist = sqrt( diff_x*diff_x + diff_y*diff_y );\n\n \/\/collide with center sphere\n const int radius = 50;\n const float elastic_constant = 0.91f;\n if(sum<int>(dist<radius) > 0) {\n vels_x(dist<radius) = -elastic_constant * vels_x(dist<radius);\n vels_y(dist<radius) = -elastic_constant * vels_y(dist<radius);\n\n \/\/normalize diff vector\n diff_x \/= dist;\n diff_y \/= dist;\n \/\/place all particle colliding with sphere on surface\n p_x(dist<radius) = width\/2 + diff_x(dist<radius) * radius;\n p_y(dist<radius) = height\/2 + diff_y(dist<radius) * radius;\n }\n}\n\n\nint main(int argc, char *argv[])\n{\n try {\n const static int total_particles = 1000;\n static const int reset = 500;\n\n af::info();\n\n af::Window myWindow(width, height, \"Gravity Simulation using ArrayFire\");\n\n int frame_count = 0;\n\n \/\/ Initialize the kernel array just once\n const af::array draw_kernel = gaussianKernel(3, 3);\n\n \/\/ Generate a random starting state\n p_x = af::randu(total_particles) * width;\n p_y = af::randu(total_particles) * height;\n\n vels_x = af::randn(total_particles);\n vels_y = af::randn(total_particles);\n\n forces_x = af::randn(total_particles);\n forces_y = af::randn(total_particles);\n\n af::array image = af::constant(0, width, height);\n af::array ids(total_particles, u32);\n\n af::timer timer = af::timer::start();\n while(!myWindow.close()) {\n float dt = af::timer::stop(timer);\n timer = af::timer::start();\n\n ids = (p_x.as(u32) * height) + p_y.as(u32);\n image(ids) += 255;\n image = convolve2(image, draw_kernel);\n myWindow.image(image);\n image = af::constant(0, image.dims());\n frame_count++;\n\n \/\/ Generate a random starting state\n if(frame_count % reset == 0) {\n p_x = af::randu(total_particles) * width;\n p_y = af::randu(total_particles) * height;\n\n vels_x = af::randn(total_particles);\n vels_y = af::randn(total_particles);\n }\n\n \/\/check for collisions and adjust velocities accordingly\n collisions();\n\n \/\/run force simulation and update particles\n simulate(dt);\n\n }\n } catch (af::exception& e) {\n fprintf(stderr, \"%s\\n\", e.what());\n throw;\n }\n\n #ifdef WIN32 \/\/ pause in Windows\n if (!(argc == 2 && argv[1][0] == '-')) {\n printf(\"hit [enter]...\");\n fflush(stdout);\n getchar();\n }\n #endif\n return 0;\n}\n\n<commit_msg>remove state globals<commit_after>\/*******************************************************\n * Copyright (c) 2014, ArrayFire\n * All rights reserved.\n *\n * This file is distributed under 3-clause BSD license.\n * The complete license agreement can be obtained at:\n * http:\/\/arrayfire.com\/licenses\/BSD-3-Clause\n ********************************************************\/\n\n#include <arrayfire.h>\n#include <iostream>\n#include <cstdio>\n\nusing namespace af;\nusing namespace std;\n\nstatic const int width = 512, height = 512;\nstatic const int pixels_per_unit = 20;\n\nvoid simulate(af::array *pos, af::array *vels, af::array *forces, float dt){\n pos[0] += vels[0] * pixels_per_unit * dt;\n pos[1] += vels[1] * pixels_per_unit * dt;\n\n \/\/calculate distance to center\n af::array diff_x = pos[0] - width\/2;\n af::array diff_y = pos[1] - height\/2;\n af::array dist = sqrt( diff_x*diff_x + diff_y*diff_y );\n\n \/\/calculate normalised force vectors\n forces[0] = -1 * diff_x \/ dist;\n forces[1] = -1 * diff_y \/ dist;\n \/\/update force scaled to time and magnitude constant\n forces[0] *= pixels_per_unit * dt;\n forces[1] *= pixels_per_unit * dt;\n\n \/\/dampening\n vels[0] *= 1 - (0.005*dt);\n vels[1] *= 1 - (0.005*dt);\n\n \/\/update velocities from forces\n vels[0] += forces[0];\n vels[1] += forces[1];\n\n}\n\nvoid collisions(af::array *pos, af::array *vels){\n \/\/clamp particles inside screen border\n af::array projected_px = min(width, max(0, pos[0]));\n af::array projected_py = min(height - 1, max(0, pos[1]));\n\n \/\/calculate distance to center\n af::array diff_x = projected_px - width\/2;\n af::array diff_y = projected_py - height\/2;\n af::array dist = sqrt( diff_x*diff_x + diff_y*diff_y );\n\n \/\/collide with center sphere\n const int radius = 50;\n const float elastic_constant = 0.91f;\n if(sum<int>(dist<radius) > 0) {\n vels[0](dist<radius) = -elastic_constant * vels[0](dist<radius);\n vels[1](dist<radius) = -elastic_constant * vels[1](dist<radius);\n\n \/\/normalize diff vector\n diff_x \/= dist;\n diff_y \/= dist;\n \/\/place all particle colliding with sphere on surface\n pos[0](dist<radius) = width\/2 + diff_x(dist<radius) * radius;\n pos[1](dist<radius) = height\/2 + diff_y(dist<radius) * radius;\n }\n}\n\n\nint main(int argc, char *argv[])\n{\n try {\n const static int total_particles = 1000;\n static const int reset = 500;\n\n af::info();\n\n af::Window myWindow(width, height, \"Gravity Simulation using ArrayFire\");\n\n int frame_count = 0;\n\n \/\/ Initialize the kernel array just once\n const af::array draw_kernel = gaussianKernel(3, 3);\n\n af::array pos[2];\n af::array vels[2];\n af::array forces[2];\n\n \/\/ Generate a random starting state\n pos[0] = af::randu(total_particles) * width;\n pos[1] = af::randu(total_particles) * height;\n\n vels[0] = af::randn(total_particles);\n vels[1] = af::randn(total_particles);\n\n forces[0] = af::randn(total_particles);\n forces[1] = af::randn(total_particles);\n\n af::array image = af::constant(0, width, height);\n af::array ids(total_particles, u32);\n\n af::timer timer = af::timer::start();\n while(!myWindow.close()) {\n float dt = af::timer::stop(timer);\n timer = af::timer::start();\n\n ids = (pos[0].as(u32) * height) + pos[1].as(u32);\n image(ids) += 255;\n image = convolve2(image, draw_kernel);\n myWindow.image(image);\n image = af::constant(0, image.dims());\n frame_count++;\n\n \/\/ Generate a random starting state\n if(frame_count % reset == 0) {\n pos[0] = af::randu(total_particles) * width;\n pos[1] = af::randu(total_particles) * height;\n\n vels[0] = af::randn(total_particles);\n vels[1] = af::randn(total_particles);\n }\n\n \/\/check for collisions and adjust positions\/velocities accordingly\n collisions(pos, vels);\n\n \/\/run force simulation and update particles\n simulate(pos, vels, forces, dt);\n\n }\n } catch (af::exception& e) {\n fprintf(stderr, \"%s\\n\", e.what());\n throw;\n }\n\n #ifdef WIN32 \/\/ pause in Windows\n if (!(argc == 2 && argv[1][0] == '-')) {\n printf(\"hit [enter]...\");\n fflush(stdout);\n getchar();\n }\n #endif\n return 0;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: timestamp.hxx,v $\n *\n * $Revision: 1.4 $\n *\n * last change: $Author: rt $ $Date: 2005-09-08 04:25:51 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef CONFIGMGR_TIMESTAMP_HXX\n#define CONFIGMGR_TIMESTAMP_HXX\n\n#include <vos\/timer.hxx>\n\nnamespace configmgr\n{\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n class TimeInterval\n {\n vos::TTimeValue m_aTime;\n public:\n TimeInterval() : m_aTime()\n {}\n\n explicit\n TimeInterval(sal_uInt32 nSeconds) : m_aTime(nSeconds,0)\n {}\n\n explicit\n TimeInterval(const TimeValue& rTimeValue) : m_aTime(rTimeValue)\n {}\n\n sal_Bool isEmpty() const { return m_aTime.isEmpty(); }\n\n vos::TTimeValue const& getTimeValue() const { return m_aTime; }\n };\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n class TimeStamp\n {\n vos::TTimeValue m_aTime;\n public:\n TimeStamp() : m_aTime()\n {}\n\n explicit\n TimeStamp(TimeValue const& rTimeValue) : m_aTime(rTimeValue)\n {}\n\n TimeStamp& operator += (TimeInterval const& aInterval)\n { m_aTime.addTime(aInterval.getTimeValue()); return *this; }\n\n vos::TTimeValue const& getTimeValue() const { return m_aTime; }\n\n sal_Bool isNever() const;\n\n static TimeStamp getCurrentTime();\n static TimeStamp never(); \/\/ is later than (>) any other TimeStamp\n static TimeStamp always(); \/\/ is before (<) any other TimeStamp\n };\n\n inline\n TimeStamp operator +(TimeStamp const& aTime, TimeInterval const& aInterval)\n {\n TimeStamp aResult(aTime);\n aResult += aInterval;\n return aResult;\n }\n inline\n TimeStamp operator +(TimeInterval const& aInterval, TimeStamp const& aTime)\n {\n TimeStamp aResult(aTime);\n aResult += aInterval;\n return aResult;\n }\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n inline sal_Bool operator ==(TimeStamp const& lhs, TimeStamp const& rhs)\n { return lhs.getTimeValue() == rhs.getTimeValue(); }\n inline sal_Bool operator < (TimeStamp const& lhs, TimeStamp const& rhs)\n { return lhs.getTimeValue() < rhs.getTimeValue(); }\n inline sal_Bool operator > (TimeStamp const& lhs, TimeStamp const& rhs)\n { return lhs.getTimeValue() > rhs.getTimeValue(); }\n\n inline sal_Bool operator !=(TimeStamp const& lhs, TimeStamp const& rhs)\n { return !(lhs == rhs); }\n inline sal_Bool operator <=(TimeStamp const& lhs, TimeStamp const& rhs)\n { return !(rhs < lhs); }\n inline sal_Bool operator >=(TimeStamp const& lhs, TimeStamp const& rhs)\n { return !(lhs < rhs); }\n\n inline sal_Bool TimeStamp::isNever() const\n {\n return never() <= *this;\n }\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n struct ltTimeStamp \/\/: std::binary_function<TimeStamp,TimeStamp,bool>\n {\n bool operator()(TimeStamp const& lhs, TimeStamp const& rhs) const\n { return !!(lhs < rhs); }\n };\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n} \/\/ namespace configmgr\n\n#endif \/\/ CONFIGMGR_TIMESTAMP_HXX\n\n<commit_msg>INTEGRATION: CWS changefileheader (1.4.130); FILE MERGED 2008\/03\/31 12:22:54 rt 1.4.130.1: #i87441# Change license header to LPGL v3.<commit_after>\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2008 by Sun Microsystems, Inc.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: timestamp.hxx,v $\n * $Revision: 1.5 $\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * <http:\/\/www.openoffice.org\/license.html>\n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n#ifndef CONFIGMGR_TIMESTAMP_HXX\n#define CONFIGMGR_TIMESTAMP_HXX\n\n#include <vos\/timer.hxx>\n\nnamespace configmgr\n{\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n class TimeInterval\n {\n vos::TTimeValue m_aTime;\n public:\n TimeInterval() : m_aTime()\n {}\n\n explicit\n TimeInterval(sal_uInt32 nSeconds) : m_aTime(nSeconds,0)\n {}\n\n explicit\n TimeInterval(const TimeValue& rTimeValue) : m_aTime(rTimeValue)\n {}\n\n sal_Bool isEmpty() const { return m_aTime.isEmpty(); }\n\n vos::TTimeValue const& getTimeValue() const { return m_aTime; }\n };\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n class TimeStamp\n {\n vos::TTimeValue m_aTime;\n public:\n TimeStamp() : m_aTime()\n {}\n\n explicit\n TimeStamp(TimeValue const& rTimeValue) : m_aTime(rTimeValue)\n {}\n\n TimeStamp& operator += (TimeInterval const& aInterval)\n { m_aTime.addTime(aInterval.getTimeValue()); return *this; }\n\n vos::TTimeValue const& getTimeValue() const { return m_aTime; }\n\n sal_Bool isNever() const;\n\n static TimeStamp getCurrentTime();\n static TimeStamp never(); \/\/ is later than (>) any other TimeStamp\n static TimeStamp always(); \/\/ is before (<) any other TimeStamp\n };\n\n inline\n TimeStamp operator +(TimeStamp const& aTime, TimeInterval const& aInterval)\n {\n TimeStamp aResult(aTime);\n aResult += aInterval;\n return aResult;\n }\n inline\n TimeStamp operator +(TimeInterval const& aInterval, TimeStamp const& aTime)\n {\n TimeStamp aResult(aTime);\n aResult += aInterval;\n return aResult;\n }\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n inline sal_Bool operator ==(TimeStamp const& lhs, TimeStamp const& rhs)\n { return lhs.getTimeValue() == rhs.getTimeValue(); }\n inline sal_Bool operator < (TimeStamp const& lhs, TimeStamp const& rhs)\n { return lhs.getTimeValue() < rhs.getTimeValue(); }\n inline sal_Bool operator > (TimeStamp const& lhs, TimeStamp const& rhs)\n { return lhs.getTimeValue() > rhs.getTimeValue(); }\n\n inline sal_Bool operator !=(TimeStamp const& lhs, TimeStamp const& rhs)\n { return !(lhs == rhs); }\n inline sal_Bool operator <=(TimeStamp const& lhs, TimeStamp const& rhs)\n { return !(rhs < lhs); }\n inline sal_Bool operator >=(TimeStamp const& lhs, TimeStamp const& rhs)\n { return !(lhs < rhs); }\n\n inline sal_Bool TimeStamp::isNever() const\n {\n return never() <= *this;\n }\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n struct ltTimeStamp \/\/: std::binary_function<TimeStamp,TimeStamp,bool>\n {\n bool operator()(TimeStamp const& lhs, TimeStamp const& rhs) const\n { return !!(lhs < rhs); }\n };\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n} \/\/ namespace configmgr\n\n#endif \/\/ CONFIGMGR_TIMESTAMP_HXX\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2014-2018 Sebastien Rombauts (sebastien.rombauts@gmail.com)\n\/\/\n\/\/ Distributed under the MIT License (MIT) (See accompanying file LICENSE.txt\n\/\/ or copy at http:\/\/opensource.org\/licenses\/MIT)\n\n#include \"GitSourceControlState.h\"\n\n#define LOCTEXT_NAMESPACE \"GitSourceControl.State\"\n\nint32 FGitSourceControlState::GetHistorySize() const\n{\n\treturn History.Num();\n}\n\nTSharedPtr<class ISourceControlRevision, ESPMode::ThreadSafe> FGitSourceControlState::GetHistoryItem( int32 HistoryIndex ) const\n{\n\tcheck(History.IsValidIndex(HistoryIndex));\n\treturn History[HistoryIndex];\n}\n\nTSharedPtr<class ISourceControlRevision, ESPMode::ThreadSafe> FGitSourceControlState::FindHistoryRevision( int32 RevisionNumber ) const\n{\n\tfor(const auto& Revision : History)\n\t{\n\t\tif(Revision->GetRevisionNumber() == RevisionNumber)\n\t\t{\n\t\t\treturn Revision;\n\t\t}\n\t}\n\n\treturn nullptr;\n}\n\nTSharedPtr<class ISourceControlRevision, ESPMode::ThreadSafe> FGitSourceControlState::FindHistoryRevision(const FString& InRevision) const\n{\n\tfor(const auto& Revision : History)\n\t{\n\t\tif(Revision->GetRevision() == InRevision)\n\t\t{\n\t\t\treturn Revision;\n\t\t}\n\t}\n\n\treturn nullptr;\n}\n\nTSharedPtr<class ISourceControlRevision, ESPMode::ThreadSafe> FGitSourceControlState::GetBaseRevForMerge() const\n{\n\tfor(const auto& Revision : History)\n\t{\n\t\t\/\/ look for the the SHA1 id of the file, not the commit id (revision)\n\t\tif(Revision->FileHash == PendingMergeBaseFileHash)\n\t\t{\n\t\t\treturn Revision;\n\t\t}\n\t}\n\n\treturn nullptr;\n}\n\n\/\/ @todo add Slate icons for git specific states (NotAtHead vs Conflicted...)\nFName FGitSourceControlState::GetIconName() const\n{\n\tif(LockState == ELockState::Locked)\n\t{\n\t\treturn FName(\"Subversion.CheckedOut\");\n\t}\n\telse if(LockState == ELockState::LockedOther)\n\t{\n\t\treturn FName(\"Subversion.CheckedOutByOtherUser\");\n\t}\n\telse if (!IsCurrent())\n\t{\n\t\treturn FName(\"Subversion.NotAtHeadRevision\");\n\t}\n\n\tswitch(WorkingCopyState)\n\t{\n\tcase EWorkingCopyState::Modified:\n\t\tif(bUsingGitLfsLocking)\n\t\t{\n\t\t\treturn FName(\"Subversion.NotInDepot\");\n\t\t}\n\t\telse\n\t\t{\n\t\t\treturn FName(\"Subversion.CheckedOut\");\n\t\t}\n\tcase EWorkingCopyState::Added:\n\t\treturn FName(\"Subversion.OpenForAdd\");\n\tcase EWorkingCopyState::Renamed:\n\tcase EWorkingCopyState::Copied:\n\t\treturn FName(\"Subversion.Branched\");\n\tcase EWorkingCopyState::Deleted: \/\/ Deleted & Missing files does not show in Content Browser\n\tcase EWorkingCopyState::Missing:\n\t\treturn FName(\"Subversion.MarkedForDelete\");\n\tcase EWorkingCopyState::Conflicted:\n\t\treturn FName(\"Subversion.NotAtHeadRevision\");\n\tcase EWorkingCopyState::NotControlled:\n\t\treturn FName(\"Subversion.NotInDepot\");\n\tcase EWorkingCopyState::Unknown:\n\tcase EWorkingCopyState::Unchanged: \/\/ Unchanged is the same as \"Pristine\" (not checked out) for Perforce, ie no icon\n\tcase EWorkingCopyState::Ignored:\n\tdefault:\n\t\treturn NAME_None;\n\t}\n\n\treturn NAME_None;\n}\n\nFName FGitSourceControlState::GetSmallIconName() const\n{\n\tif(LockState == ELockState::Locked)\n\t{\n\t\treturn FName(\"Subversion.CheckedOut_Small\");\n\t}\n\telse if(LockState == ELockState::LockedOther)\n\t{\n\t\treturn FName(\"Subversion.CheckedOutByOtherUser_Small\");\n\t}\n\telse if (!IsCurrent())\n\t{\n\t\treturn FName(\"Subversion.NotAtHeadRevision_Small\");\n\t}\n\n\tswitch(WorkingCopyState)\n\t{\n\tcase EWorkingCopyState::Modified:\n\t\tif(bUsingGitLfsLocking)\n\t\t{\n\t\t\treturn FName(\"Subversion.NotInDepot_Small\");\n\t\t}\n\t\telse\n\t\t{\n\t\t\treturn FName(\"Subversion.CheckedOut_Small\");\n\t\t}\n\tcase EWorkingCopyState::Added:\n\t\treturn FName(\"Subversion.OpenForAdd_Small\");\n\tcase EWorkingCopyState::Renamed:\n\tcase EWorkingCopyState::Copied:\n\t\treturn FName(\"Subversion.Branched_Small\");\n\tcase EWorkingCopyState::Deleted: \/\/ Deleted & Missing files can appear in the Submit to Source Control window\n\tcase EWorkingCopyState::Missing:\n\t\treturn FName(\"Subversion.MarkedForDelete_Small\");\n\tcase EWorkingCopyState::Conflicted:\n\t\treturn FName(\"Subversion.NotAtHeadRevision_Small\");\n\tcase EWorkingCopyState::NotControlled:\n\t\treturn FName(\"Subversion.NotInDepot_Small\");\n\tcase EWorkingCopyState::Unknown:\n\tcase EWorkingCopyState::Unchanged: \/\/ Unchanged is the same as \"Pristine\" (not checked out) for Perforce, ie no icon\n\tcase EWorkingCopyState::Ignored:\n\tdefault:\n\t\treturn NAME_None;\n\t}\n\n\treturn NAME_None;\n}\n\nFText FGitSourceControlState::GetDisplayName() const\n{\n\tif(LockState == ELockState::Locked)\n\t{\n\t\treturn LOCTEXT(\"Locked\", \"Locked For Editing\");\n\t}\n\telse if(LockState == ELockState::LockedOther)\n\t{\n\t\treturn FText::Format( LOCTEXT(\"LockedOther\", \"Locked by \"), FText::FromString(LockUser) );\n\t}\n\telse if (!IsCurrent())\n\t{\n\t\treturn LOCTEXT(\"NotCurrent\", \"Not current\");\n\t}\n\n\tswitch(WorkingCopyState)\n\t{\n\tcase EWorkingCopyState::Unknown:\n\t\treturn LOCTEXT(\"Unknown\", \"Unknown\");\n\tcase EWorkingCopyState::Unchanged:\n\t\treturn LOCTEXT(\"Unchanged\", \"Unchanged\");\n\tcase EWorkingCopyState::Added:\n\t\treturn LOCTEXT(\"Added\", \"Added\");\n\tcase EWorkingCopyState::Deleted:\n\t\treturn LOCTEXT(\"Deleted\", \"Deleted\");\n\tcase EWorkingCopyState::Modified:\n\t\treturn LOCTEXT(\"Modified\", \"Modified\");\n\tcase EWorkingCopyState::Renamed:\n\t\treturn LOCTEXT(\"Renamed\", \"Renamed\");\n\tcase EWorkingCopyState::Copied:\n\t\treturn LOCTEXT(\"Copied\", \"Copied\");\n\tcase EWorkingCopyState::Conflicted:\n\t\treturn LOCTEXT(\"ContentsConflict\", \"Contents Conflict\");\n\tcase EWorkingCopyState::Ignored:\n\t\treturn LOCTEXT(\"Ignored\", \"Ignored\");\n\tcase EWorkingCopyState::NotControlled:\n\t\treturn LOCTEXT(\"NotControlled\", \"Not Under Source Control\");\n\tcase EWorkingCopyState::Missing:\n\t\treturn LOCTEXT(\"Missing\", \"Missing\");\n\t}\n\n\treturn FText();\n}\n\nFText FGitSourceControlState::GetDisplayTooltip() const\n{\n\tif(LockState == ELockState::Locked)\n\t{\n\t\treturn LOCTEXT(\"Locked_Tooltip\", \"Locked for editing by current user\");\n\t}\n\telse if(LockState == ELockState::LockedOther)\n\t{\n\t\treturn FText::Format( LOCTEXT(\"LockedOther_Tooltip\", \"Locked for editing by: {0}\"), FText::FromString(LockUser) );\n\t}\n\telse if (!IsCurrent())\n\t{\n\t\treturn LOCTEXT(\"NotCurrent_Tooltip\", \"The file(s) are not at the head revision\");\n\t}\n\n\tswitch(WorkingCopyState)\n\t{\n\tcase EWorkingCopyState::Unknown:\n\t\treturn LOCTEXT(\"Unknown_Tooltip\", \"Unknown source control state\");\n\tcase EWorkingCopyState::Unchanged:\n\t\treturn LOCTEXT(\"Pristine_Tooltip\", \"There are no modifications\");\n\tcase EWorkingCopyState::Added:\n\t\treturn LOCTEXT(\"Added_Tooltip\", \"Item is scheduled for addition\");\n\tcase EWorkingCopyState::Deleted:\n\t\treturn LOCTEXT(\"Deleted_Tooltip\", \"Item is scheduled for deletion\");\n\tcase EWorkingCopyState::Modified:\n\t\treturn LOCTEXT(\"Modified_Tooltip\", \"Item has been modified\");\n\tcase EWorkingCopyState::Renamed:\n\t\treturn LOCTEXT(\"Renamed_Tooltip\", \"Item has been renamed\");\n\tcase EWorkingCopyState::Copied:\n\t\treturn LOCTEXT(\"Copied_Tooltip\", \"Item has been copied\");\n\tcase EWorkingCopyState::Conflicted:\n\t\treturn LOCTEXT(\"ContentsConflict_Tooltip\", \"The contents of the item conflict with updates received from the repository.\");\n\tcase EWorkingCopyState::Ignored:\n\t\treturn LOCTEXT(\"Ignored_Tooltip\", \"Item is being ignored.\");\n\tcase EWorkingCopyState::NotControlled:\n\t\treturn LOCTEXT(\"NotControlled_Tooltip\", \"Item is not under version control.\");\n\tcase EWorkingCopyState::Missing:\n\t\treturn LOCTEXT(\"Missing_Tooltip\", \"Item is missing (e.g., you moved or deleted it without using Git). This also indicates that a directory is incomplete (a checkout or update was interrupted).\");\n\t}\n\n\treturn FText();\n}\n\nconst FString& FGitSourceControlState::GetFilename() const\n{\n\treturn LocalFilename;\n}\n\nconst FDateTime& FGitSourceControlState::GetTimeStamp() const\n{\n\treturn TimeStamp;\n}\n\n\/\/ Deleted and Missing assets cannot appear in the Content Browser, but the do in the Submit files to Source Control window!\nbool FGitSourceControlState::CanCheckIn() const\n{\n\tif(bUsingGitLfsLocking)\n\t{\n\t\treturn ( ( (LockState == ELockState::Locked) && !IsConflicted() ) || (WorkingCopyState == EWorkingCopyState::Added) ) && IsCurrent();\n\t}\n\telse\n\t{\n\t\treturn (WorkingCopyState == EWorkingCopyState::Added\n\t\t\t|| WorkingCopyState == EWorkingCopyState::Deleted\n\t\t\t|| WorkingCopyState == EWorkingCopyState::Missing\n\t\t\t|| WorkingCopyState == EWorkingCopyState::Modified\n\t\t\t|| WorkingCopyState == EWorkingCopyState::Renamed) && IsCurrent();\n\t}\n}\n\nbool FGitSourceControlState::CanCheckout() const\n{\n\tif(bUsingGitLfsLocking)\n\t{\n\t\t\/\/ We don't want to allow checkout if the file is out-of-date, as modifying an out-of-date binary file will most likely result in a merge conflict\n\t\treturn (WorkingCopyState == EWorkingCopyState::Unchanged || WorkingCopyState == EWorkingCopyState::Modified) && LockState == ELockState::NotLocked && IsCurrent();\n\t}\n\telse\n\t{\n\t\treturn false; \/\/ With Git all tracked files in the working copy are always already checked-out (as opposed to Perforce)\n\t}\n}\n\nbool FGitSourceControlState::IsCheckedOut() const\n{\n\tif (bUsingGitLfsLocking)\n\t{\n\t\treturn LockState == ELockState::Locked;\n\t}\n\telse\n\t{\n\t\treturn IsSourceControlled(); \/\/ With Git all tracked files in the working copy are always checked-out (as opposed to Perforce)\n\t}\n}\n\nbool FGitSourceControlState::IsCheckedOutOther(FString* Who) const\n{\n\tif (Who != NULL)\n\t{\n\t\t*Who = LockUser;\n\t}\n\treturn LockState == ELockState::LockedOther;\n}\n\nbool FGitSourceControlState::IsCurrent() const\n{\n\treturn !bNewerVersionOnServer;\n}\n\nbool FGitSourceControlState::IsSourceControlled() const\n{\n\treturn WorkingCopyState != EWorkingCopyState::NotControlled && WorkingCopyState != EWorkingCopyState::Ignored && WorkingCopyState != EWorkingCopyState::Unknown;\n}\n\nbool FGitSourceControlState::IsAdded() const\n{\n\treturn WorkingCopyState == EWorkingCopyState::Added;\n}\n\nbool FGitSourceControlState::IsDeleted() const\n{\n\treturn WorkingCopyState == EWorkingCopyState::Deleted || WorkingCopyState == EWorkingCopyState::Missing;\n}\n\nbool FGitSourceControlState::IsIgnored() const\n{\n\treturn WorkingCopyState == EWorkingCopyState::Ignored;\n}\n\nbool FGitSourceControlState::CanEdit() const\n{\n\treturn IsCurrent(); \/\/ With Git all files in the working copy are always editable (as opposed to Perforce)\n}\n\nbool FGitSourceControlState::CanDelete() const\n{\n\treturn !IsCheckedOutOther() && IsSourceControlled() && IsCurrent();\r\n}\n\nbool FGitSourceControlState::IsUnknown() const\n{\n\treturn WorkingCopyState == EWorkingCopyState::Unknown;\n}\n\nbool FGitSourceControlState::IsModified() const\n{\n\t\/\/ Warning: for Perforce, a checked-out file is locked for modification (whereas with Git all tracked files are checked-out),\n\t\/\/ so for a clean \"check-in\" (commit) checked-out files unmodified should be removed from the changeset (the index)\n\t\/\/ http:\/\/stackoverflow.com\/questions\/12357971\/what-does-revert-unchanged-files-mean-in-perforce\n\t\/\/\n\t\/\/ Thus, before check-in UE4 Editor call RevertUnchangedFiles() in PromptForCheckin() and CheckinFiles().\n\t\/\/\n\t\/\/ So here we must take care to enumerate all states that need to be commited,\n\t\/\/ all other will be discarded :\n\t\/\/ - Unknown\n\t\/\/ - Unchanged\n\t\/\/ - NotControlled\n\t\/\/ - Ignored\n\treturn WorkingCopyState == EWorkingCopyState::Added\n\t\t|| WorkingCopyState == EWorkingCopyState::Deleted\n\t\t|| WorkingCopyState == EWorkingCopyState::Modified\n\t\t|| WorkingCopyState == EWorkingCopyState::Renamed\n\t\t|| WorkingCopyState == EWorkingCopyState::Copied\n\t\t|| WorkingCopyState == EWorkingCopyState::Missing\n\t\t|| WorkingCopyState == EWorkingCopyState::Conflicted;\n}\n\n\nbool FGitSourceControlState::CanAdd() const\n{\n\treturn WorkingCopyState == EWorkingCopyState::NotControlled;\n}\n\nbool FGitSourceControlState::IsConflicted() const\n{\n\treturn WorkingCopyState == EWorkingCopyState::Conflicted;\n}\n\nbool FGitSourceControlState::CanRevert() const\n{\n\treturn CanCheckIn();\n}\n\n#undef LOCTEXT_NAMESPACE\n<commit_msg>Change conflict state icon to ModifiedOtherBranch to avoid confusion with NotAtHeadRevision state<commit_after>\/\/ Copyright (c) 2014-2018 Sebastien Rombauts (sebastien.rombauts@gmail.com)\n\/\/\n\/\/ Distributed under the MIT License (MIT) (See accompanying file LICENSE.txt\n\/\/ or copy at http:\/\/opensource.org\/licenses\/MIT)\n\n#include \"GitSourceControlState.h\"\n\n#define LOCTEXT_NAMESPACE \"GitSourceControl.State\"\n\nint32 FGitSourceControlState::GetHistorySize() const\n{\n\treturn History.Num();\n}\n\nTSharedPtr<class ISourceControlRevision, ESPMode::ThreadSafe> FGitSourceControlState::GetHistoryItem( int32 HistoryIndex ) const\n{\n\tcheck(History.IsValidIndex(HistoryIndex));\n\treturn History[HistoryIndex];\n}\n\nTSharedPtr<class ISourceControlRevision, ESPMode::ThreadSafe> FGitSourceControlState::FindHistoryRevision( int32 RevisionNumber ) const\n{\n\tfor(const auto& Revision : History)\n\t{\n\t\tif(Revision->GetRevisionNumber() == RevisionNumber)\n\t\t{\n\t\t\treturn Revision;\n\t\t}\n\t}\n\n\treturn nullptr;\n}\n\nTSharedPtr<class ISourceControlRevision, ESPMode::ThreadSafe> FGitSourceControlState::FindHistoryRevision(const FString& InRevision) const\n{\n\tfor(const auto& Revision : History)\n\t{\n\t\tif(Revision->GetRevision() == InRevision)\n\t\t{\n\t\t\treturn Revision;\n\t\t}\n\t}\n\n\treturn nullptr;\n}\n\nTSharedPtr<class ISourceControlRevision, ESPMode::ThreadSafe> FGitSourceControlState::GetBaseRevForMerge() const\n{\n\tfor(const auto& Revision : History)\n\t{\n\t\t\/\/ look for the the SHA1 id of the file, not the commit id (revision)\n\t\tif(Revision->FileHash == PendingMergeBaseFileHash)\n\t\t{\n\t\t\treturn Revision;\n\t\t}\n\t}\n\n\treturn nullptr;\n}\n\n\/\/ @todo add Slate icons for git specific states (NotAtHead vs Conflicted...)\nFName FGitSourceControlState::GetIconName() const\n{\n\tif(LockState == ELockState::Locked)\n\t{\n\t\treturn FName(\"Subversion.CheckedOut\");\n\t}\n\telse if(LockState == ELockState::LockedOther)\n\t{\n\t\treturn FName(\"Subversion.CheckedOutByOtherUser\");\n\t}\n\telse if (!IsCurrent())\n\t{\n\t\treturn FName(\"Subversion.NotAtHeadRevision\");\n\t}\n\n\tswitch(WorkingCopyState)\n\t{\n\tcase EWorkingCopyState::Modified:\n\t\tif(bUsingGitLfsLocking)\n\t\t{\n\t\t\treturn FName(\"Subversion.NotInDepot\");\n\t\t}\n\t\telse\n\t\t{\n\t\t\treturn FName(\"Subversion.CheckedOut\");\n\t\t}\n\tcase EWorkingCopyState::Added:\n\t\treturn FName(\"Subversion.OpenForAdd\");\n\tcase EWorkingCopyState::Renamed:\n\tcase EWorkingCopyState::Copied:\n\t\treturn FName(\"Subversion.Branched\");\n\tcase EWorkingCopyState::Deleted: \/\/ Deleted & Missing files does not show in Content Browser\n\tcase EWorkingCopyState::Missing:\n\t\treturn FName(\"Subversion.MarkedForDelete\");\n\tcase EWorkingCopyState::Conflicted:\n\t\treturn FName(\"Subversion.ModifiedOtherBranch\");\n\tcase EWorkingCopyState::NotControlled:\n\t\treturn FName(\"Subversion.NotInDepot\");\n\tcase EWorkingCopyState::Unknown:\n\tcase EWorkingCopyState::Unchanged: \/\/ Unchanged is the same as \"Pristine\" (not checked out) for Perforce, ie no icon\n\tcase EWorkingCopyState::Ignored:\n\tdefault:\n\t\treturn NAME_None;\n\t}\n\n\treturn NAME_None;\n}\n\nFName FGitSourceControlState::GetSmallIconName() const\n{\n\tif(LockState == ELockState::Locked)\n\t{\n\t\treturn FName(\"Subversion.CheckedOut_Small\");\n\t}\n\telse if(LockState == ELockState::LockedOther)\n\t{\n\t\treturn FName(\"Subversion.CheckedOutByOtherUser_Small\");\n\t}\n\telse if (!IsCurrent())\n\t{\n\t\treturn FName(\"Subversion.NotAtHeadRevision_Small\");\n\t}\n\n\tswitch(WorkingCopyState)\n\t{\n\tcase EWorkingCopyState::Modified:\n\t\tif(bUsingGitLfsLocking)\n\t\t{\n\t\t\treturn FName(\"Subversion.NotInDepot_Small\");\n\t\t}\n\t\telse\n\t\t{\n\t\t\treturn FName(\"Subversion.CheckedOut_Small\");\n\t\t}\n\tcase EWorkingCopyState::Added:\n\t\treturn FName(\"Subversion.OpenForAdd_Small\");\n\tcase EWorkingCopyState::Renamed:\n\tcase EWorkingCopyState::Copied:\n\t\treturn FName(\"Subversion.Branched_Small\");\n\tcase EWorkingCopyState::Deleted: \/\/ Deleted & Missing files can appear in the Submit to Source Control window\n\tcase EWorkingCopyState::Missing:\n\t\treturn FName(\"Subversion.MarkedForDelete_Small\");\n\tcase EWorkingCopyState::Conflicted:\n\t\treturn FName(\"Subversion.ModifiedOtherBranch_Small\");\n\tcase EWorkingCopyState::NotControlled:\n\t\treturn FName(\"Subversion.NotInDepot_Small\");\n\tcase EWorkingCopyState::Unknown:\n\tcase EWorkingCopyState::Unchanged: \/\/ Unchanged is the same as \"Pristine\" (not checked out) for Perforce, ie no icon\n\tcase EWorkingCopyState::Ignored:\n\tdefault:\n\t\treturn NAME_None;\n\t}\n\n\treturn NAME_None;\n}\n\nFText FGitSourceControlState::GetDisplayName() const\n{\n\tif(LockState == ELockState::Locked)\n\t{\n\t\treturn LOCTEXT(\"Locked\", \"Locked For Editing\");\n\t}\n\telse if(LockState == ELockState::LockedOther)\n\t{\n\t\treturn FText::Format( LOCTEXT(\"LockedOther\", \"Locked by \"), FText::FromString(LockUser) );\n\t}\n\telse if (!IsCurrent())\n\t{\n\t\treturn LOCTEXT(\"NotCurrent\", \"Not current\");\n\t}\n\n\tswitch(WorkingCopyState)\n\t{\n\tcase EWorkingCopyState::Unknown:\n\t\treturn LOCTEXT(\"Unknown\", \"Unknown\");\n\tcase EWorkingCopyState::Unchanged:\n\t\treturn LOCTEXT(\"Unchanged\", \"Unchanged\");\n\tcase EWorkingCopyState::Added:\n\t\treturn LOCTEXT(\"Added\", \"Added\");\n\tcase EWorkingCopyState::Deleted:\n\t\treturn LOCTEXT(\"Deleted\", \"Deleted\");\n\tcase EWorkingCopyState::Modified:\n\t\treturn LOCTEXT(\"Modified\", \"Modified\");\n\tcase EWorkingCopyState::Renamed:\n\t\treturn LOCTEXT(\"Renamed\", \"Renamed\");\n\tcase EWorkingCopyState::Copied:\n\t\treturn LOCTEXT(\"Copied\", \"Copied\");\n\tcase EWorkingCopyState::Conflicted:\n\t\treturn LOCTEXT(\"ContentsConflict\", \"Contents Conflict\");\n\tcase EWorkingCopyState::Ignored:\n\t\treturn LOCTEXT(\"Ignored\", \"Ignored\");\n\tcase EWorkingCopyState::NotControlled:\n\t\treturn LOCTEXT(\"NotControlled\", \"Not Under Source Control\");\n\tcase EWorkingCopyState::Missing:\n\t\treturn LOCTEXT(\"Missing\", \"Missing\");\n\t}\n\n\treturn FText();\n}\n\nFText FGitSourceControlState::GetDisplayTooltip() const\n{\n\tif(LockState == ELockState::Locked)\n\t{\n\t\treturn LOCTEXT(\"Locked_Tooltip\", \"Locked for editing by current user\");\n\t}\n\telse if(LockState == ELockState::LockedOther)\n\t{\n\t\treturn FText::Format( LOCTEXT(\"LockedOther_Tooltip\", \"Locked for editing by: {0}\"), FText::FromString(LockUser) );\n\t}\n\telse if (!IsCurrent())\n\t{\n\t\treturn LOCTEXT(\"NotCurrent_Tooltip\", \"The file(s) are not at the head revision\");\n\t}\n\n\tswitch(WorkingCopyState)\n\t{\n\tcase EWorkingCopyState::Unknown:\n\t\treturn LOCTEXT(\"Unknown_Tooltip\", \"Unknown source control state\");\n\tcase EWorkingCopyState::Unchanged:\n\t\treturn LOCTEXT(\"Pristine_Tooltip\", \"There are no modifications\");\n\tcase EWorkingCopyState::Added:\n\t\treturn LOCTEXT(\"Added_Tooltip\", \"Item is scheduled for addition\");\n\tcase EWorkingCopyState::Deleted:\n\t\treturn LOCTEXT(\"Deleted_Tooltip\", \"Item is scheduled for deletion\");\n\tcase EWorkingCopyState::Modified:\n\t\treturn LOCTEXT(\"Modified_Tooltip\", \"Item has been modified\");\n\tcase EWorkingCopyState::Renamed:\n\t\treturn LOCTEXT(\"Renamed_Tooltip\", \"Item has been renamed\");\n\tcase EWorkingCopyState::Copied:\n\t\treturn LOCTEXT(\"Copied_Tooltip\", \"Item has been copied\");\n\tcase EWorkingCopyState::Conflicted:\n\t\treturn LOCTEXT(\"ContentsConflict_Tooltip\", \"The contents of the item conflict with updates received from the repository.\");\n\tcase EWorkingCopyState::Ignored:\n\t\treturn LOCTEXT(\"Ignored_Tooltip\", \"Item is being ignored.\");\n\tcase EWorkingCopyState::NotControlled:\n\t\treturn LOCTEXT(\"NotControlled_Tooltip\", \"Item is not under version control.\");\n\tcase EWorkingCopyState::Missing:\n\t\treturn LOCTEXT(\"Missing_Tooltip\", \"Item is missing (e.g., you moved or deleted it without using Git). This also indicates that a directory is incomplete (a checkout or update was interrupted).\");\n\t}\n\n\treturn FText();\n}\n\nconst FString& FGitSourceControlState::GetFilename() const\n{\n\treturn LocalFilename;\n}\n\nconst FDateTime& FGitSourceControlState::GetTimeStamp() const\n{\n\treturn TimeStamp;\n}\n\n\/\/ Deleted and Missing assets cannot appear in the Content Browser, but the do in the Submit files to Source Control window!\nbool FGitSourceControlState::CanCheckIn() const\n{\n\tif(bUsingGitLfsLocking)\n\t{\n\t\treturn ( ( (LockState == ELockState::Locked) && !IsConflicted() ) || (WorkingCopyState == EWorkingCopyState::Added) ) && IsCurrent();\n\t}\n\telse\n\t{\n\t\treturn (WorkingCopyState == EWorkingCopyState::Added\n\t\t\t|| WorkingCopyState == EWorkingCopyState::Deleted\n\t\t\t|| WorkingCopyState == EWorkingCopyState::Missing\n\t\t\t|| WorkingCopyState == EWorkingCopyState::Modified\n\t\t\t|| WorkingCopyState == EWorkingCopyState::Renamed) && IsCurrent();\n\t}\n}\n\nbool FGitSourceControlState::CanCheckout() const\n{\n\tif(bUsingGitLfsLocking)\n\t{\n\t\t\/\/ We don't want to allow checkout if the file is out-of-date, as modifying an out-of-date binary file will most likely result in a merge conflict\n\t\treturn (WorkingCopyState == EWorkingCopyState::Unchanged || WorkingCopyState == EWorkingCopyState::Modified) && LockState == ELockState::NotLocked && IsCurrent();\n\t}\n\telse\n\t{\n\t\treturn false; \/\/ With Git all tracked files in the working copy are always already checked-out (as opposed to Perforce)\n\t}\n}\n\nbool FGitSourceControlState::IsCheckedOut() const\n{\n\tif (bUsingGitLfsLocking)\n\t{\n\t\treturn LockState == ELockState::Locked;\n\t}\n\telse\n\t{\n\t\treturn IsSourceControlled(); \/\/ With Git all tracked files in the working copy are always checked-out (as opposed to Perforce)\n\t}\n}\n\nbool FGitSourceControlState::IsCheckedOutOther(FString* Who) const\n{\n\tif (Who != NULL)\n\t{\n\t\t*Who = LockUser;\n\t}\n\treturn LockState == ELockState::LockedOther;\n}\n\nbool FGitSourceControlState::IsCurrent() const\n{\n\treturn !bNewerVersionOnServer;\n}\n\nbool FGitSourceControlState::IsSourceControlled() const\n{\n\treturn WorkingCopyState != EWorkingCopyState::NotControlled && WorkingCopyState != EWorkingCopyState::Ignored && WorkingCopyState != EWorkingCopyState::Unknown;\n}\n\nbool FGitSourceControlState::IsAdded() const\n{\n\treturn WorkingCopyState == EWorkingCopyState::Added;\n}\n\nbool FGitSourceControlState::IsDeleted() const\n{\n\treturn WorkingCopyState == EWorkingCopyState::Deleted || WorkingCopyState == EWorkingCopyState::Missing;\n}\n\nbool FGitSourceControlState::IsIgnored() const\n{\n\treturn WorkingCopyState == EWorkingCopyState::Ignored;\n}\n\nbool FGitSourceControlState::CanEdit() const\n{\n\treturn IsCurrent(); \/\/ With Git all files in the working copy are always editable (as opposed to Perforce)\n}\n\nbool FGitSourceControlState::CanDelete() const\n{\n\treturn !IsCheckedOutOther() && IsSourceControlled() && IsCurrent();\r\n}\n\nbool FGitSourceControlState::IsUnknown() const\n{\n\treturn WorkingCopyState == EWorkingCopyState::Unknown;\n}\n\nbool FGitSourceControlState::IsModified() const\n{\n\t\/\/ Warning: for Perforce, a checked-out file is locked for modification (whereas with Git all tracked files are checked-out),\n\t\/\/ so for a clean \"check-in\" (commit) checked-out files unmodified should be removed from the changeset (the index)\n\t\/\/ http:\/\/stackoverflow.com\/questions\/12357971\/what-does-revert-unchanged-files-mean-in-perforce\n\t\/\/\n\t\/\/ Thus, before check-in UE4 Editor call RevertUnchangedFiles() in PromptForCheckin() and CheckinFiles().\n\t\/\/\n\t\/\/ So here we must take care to enumerate all states that need to be commited,\n\t\/\/ all other will be discarded :\n\t\/\/ - Unknown\n\t\/\/ - Unchanged\n\t\/\/ - NotControlled\n\t\/\/ - Ignored\n\treturn WorkingCopyState == EWorkingCopyState::Added\n\t\t|| WorkingCopyState == EWorkingCopyState::Deleted\n\t\t|| WorkingCopyState == EWorkingCopyState::Modified\n\t\t|| WorkingCopyState == EWorkingCopyState::Renamed\n\t\t|| WorkingCopyState == EWorkingCopyState::Copied\n\t\t|| WorkingCopyState == EWorkingCopyState::Missing\n\t\t|| WorkingCopyState == EWorkingCopyState::Conflicted;\n}\n\n\nbool FGitSourceControlState::CanAdd() const\n{\n\treturn WorkingCopyState == EWorkingCopyState::NotControlled;\n}\n\nbool FGitSourceControlState::IsConflicted() const\n{\n\treturn WorkingCopyState == EWorkingCopyState::Conflicted;\n}\n\nbool FGitSourceControlState::CanRevert() const\n{\n\treturn CanCheckIn();\n}\n\n#undef LOCTEXT_NAMESPACE\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 2001 Stephen Williams (steve@icarus.com)\n * Copyright (c) 2001 Stephan Boettcher <stephan@nevis.columbia.edu>\n *\n * This source code is free software; you can redistribute it\n * and\/or modify it in source code form under the terms of the GNU\n * General Public License as published by the Free Software\n * Foundation; either version 2 of the License, or (at your option)\n * any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA\n *\/\n#if !defined(WINNT)\n#ident \"$Id: vpi_vthr_vector.cc,v 1.1 2001\/05\/10 00:26:53 steve Exp $\"\n#endif\n\n\/*\n * vpiReg handles are handled here. These objects represent vectors of\n * .var objects that can be manipulated by the VPI module.\n *\/\n\n# include \"vpi_priv.h\"\n# include \"vthread.h\"\n# include <stdio.h>\n# include <malloc.h>\n# include <assert.h>\n\nstruct __vpiVThrVec {\n struct __vpiHandle base;\n unsigned short bas;\n unsigned short wid;\n char *name;\n};\n\ninline static \nunsigned get_bit(struct __vpiVThrVec *rfp, unsigned idx)\n{\n return vthread_get_bit(vpip_current_vthread, rfp->bas+idx);\n}\n\ninline static \nvoid set_bit(struct __vpiVThrVec *rfp, unsigned idx, unsigned bit)\n{\n return vthread_put_bit(vpip_current_vthread, rfp->bas+idx, bit);\n}\n\n\n\/*\n * Hex digits that represent 4-value bits of Verilog are not as\n * trivially obvious to display as if the bits were the usual 2-value\n * bits. So, although it is possible to write a function that\n * generates a correct character for 4*4-value bits, it is easier to\n * just perform the lookup in a table. This only takes 256 bytes,\n * which is not many executable instructions:-)\n *\n * The table is calculated as compile time, therefore, by the\n * draw_tt.c program.\n *\/\n\nextern const char hex_digits[256];\n\nextern const char oct_digits[256];\n\n\/*\n * vpi_get\n *\/\nstatic int vthr_vec_get(int code, vpiHandle ref)\n{\n assert((ref->vpi_type->type_code==vpiNet)\n\t || (ref->vpi_type->type_code==vpiReg)\n\t || (ref->vpi_type->type_code==vpiConstant));\n\n struct __vpiVThrVec*rfp = (struct __vpiVThrVec*)ref;\n\n switch (code) {\n\n\t case vpiSigned:\n\t return 0;\n\n\t case vpiSize:\n\t return rfp->wid;\n\n\t default:\n\t return 0;\n }\n}\n\nstatic char* vthr_vec_get_str(int code, vpiHandle ref)\n{\n assert((ref->vpi_type->type_code==vpiNet)\n\t || (ref->vpi_type->type_code==vpiReg));\n\n struct __vpiVThrVec*rfp = (struct __vpiVThrVec*)ref;\n\n switch (code) {\n\n\t case vpiFullName:\n\t return (char*)rfp->name;\n }\n\n return 0;\n}\n\nstatic char buf[4096];\n\nstatic void vthr_vec_DecStrVal(struct __vpiVThrVec*rfp, s_vpi_value*vp)\n{\n unsigned long val = 0;\n unsigned count_x = 0, count_z = 0;\n\n for (unsigned idx = 0 ; idx < rfp->wid ; idx += 1) {\n\t val *= 2;\n\t switch (get_bit(rfp, idx)) {\n\t\tcase 0:\n\t\t break;\n\t\tcase 1:\n\t\t val += 1;\n\t\t break;\n\t\tcase 2:\n\t\t count_x += 1;\n\t\t break;\n\t\tcase 3:\n\t\t count_z += 1;\n\t\t break;\n\t }\n }\n\n if (count_x == rfp->wid) {\n\t buf[0] = 'x';\n\t buf[1] = 0;\n\t return;\n }\n\n if (count_x > 0) {\n\t buf[0] = 'X';\n\t buf[1] = 0;\n\t return;\n }\n\n if (count_z == rfp->wid) {\n\t buf[0] = 'z';\n\t buf[1] = 0;\n\t return;\n }\n\n if (count_z > 0) {\n\t buf[0] = 'Z';\n\t buf[1] = 0;\n\t return;\n }\n\n sprintf(buf, \"%lu\", val);\n}\n\n\/*\n * The get_value method reads the values of the functors and returns\n * the vector to the caller. This causes no side-effect, and reads the\n * variables like a %load would.\n *\/\nstatic void vthr_vec_get_value(vpiHandle ref, s_vpi_value*vp)\n{\n assert((ref->vpi_type->type_code==vpiNet)\n\t || (ref->vpi_type->type_code==vpiReg)\n\t || (ref->vpi_type->type_code==vpiConstant));\n\n struct __vpiVThrVec*rfp = (struct __vpiVThrVec*)ref;\n \n unsigned wid = rfp->wid;\n\n switch (vp->format) {\n\n\t case vpiBinStrVal:\n\t for (unsigned idx = 0 ; idx < wid ; idx += 1) {\n\t\t buf[wid-idx-1] = \"01xz\"[get_bit(rfp, idx)];\n\t }\n\t buf[wid] = 0;\n\t vp->value.str = buf;\n\t break;\n\t \n\t case vpiHexStrVal: {\n\t\tunsigned hval, hwid;\n\t\thwid = (wid + 3) \/ 4;\n\t\tbuf[hwid] = 0;\n\t\thval = 0;\n\t\tfor (unsigned idx = 0 ; idx < wid ; idx += 1) {\n\t\t hval = hval | (get_bit(rfp, idx) << 2*(idx % 4));\n\n\t\t if (idx%4 == 3) {\n\t\t\t hwid -= 1;\n\t\t\t buf[hwid] = hex_digits[hval];\n\t\t\t hval = 0;\n\t\t }\n\t\t}\n\n\t\tif (hwid > 0) {\n\t\t hwid -= 1;\n\t\t buf[hwid] = hex_digits[hval];\n\t\t hval = 0;\n\t\t}\n\t\tvp->value.str = buf;\n\t\tbreak;\n\t }\n\n\t case vpiOctStrVal: {\n\t\tunsigned hval, hwid;\n\t\thwid = (wid + 2) \/ 3;\n\t\tbuf[hwid] = 0;\n\t\thval = 0;\n\t\tfor (unsigned idx = 0 ; idx < wid ; idx += 1) {\n\t\t hval = hval | (get_bit(rfp,idx) << 2*(idx % 3));\n\n\t\t if (idx%3 == 2) {\n\t\t\t hwid -= 1;\n\t\t\t buf[hwid] = oct_digits[hval];\n\t\t\t hval = 0;\n\t\t }\n\t\t}\n\n\t\tif (hwid > 0) {\n\t\t hwid -= 1;\n\t\t buf[hwid] = oct_digits[hval];\n\t\t hval = 0;\n\t\t}\n\t\tvp->value.str = buf;\n\t\tbreak;\n\t }\n\n\t case vpiDecStrVal:\n\t vthr_vec_DecStrVal(rfp, vp);\n\t vp->value.str = buf;\n\t break;\n\n\t default:\n\t \/* XXXX Not implemented yet. *\/\n\t assert(0);\n }\n}\n\n\/*\n * The put_value method writes the value into the vector.\n *\/\nstatic vpiHandle vthr_vec_put_value(vpiHandle ref, s_vpi_value*vp,\n\t\t\t\t p_vpi_time when, int flags)\n{\n assert((ref->vpi_type->type_code==vpiNet)\n\t || (ref->vpi_type->type_code==vpiReg));\n\n struct __vpiVThrVec*rfp = (struct __vpiVThrVec*)ref;\n\n\t\/* XXXX delays are not yet supported. *\/\n assert(flags == vpiNoDelay);\n\n unsigned wid = rfp->wid;\n\n switch (vp->format) {\n\t \n\t case vpiIntVal: {\n\t\tassert(wid <= sizeof(long));\n\n\t\tlong val = vp->value.integer;\n\t\tfor (unsigned idx = 0 ; idx < wid ; idx += 1) {\n\t\t set_bit(rfp, idx, val&1);\n\t\t val >>= 1;\n\t\t}\n\t\tbreak;\n\t }\n\n\t case vpiScalarVal:\n\t switch (vp->value.scalar) {\n\t\tcase vpi0:\n\t\t set_bit(rfp, 0, 0);\n\t\t break;\n\t\tcase vpi1:\n\t\t set_bit(rfp, 0, 1);\n\t\t break;\n\t\tcase vpiX:\n\t\t set_bit(rfp, 0, 2);\n\t\t break;\n\t\tcase vpiZ:\n\t\t set_bit(rfp, 0, 3);\n\t\t break;\n\t\tdefault:\n\t\t assert(0);\n\t }\n\t break;\n\n\t case vpiVectorVal: {\n\t\tassert(wid <= sizeof (unsigned long));\n\n\t\tunsigned long aval = vp->value.vector->aval;\n\t\tunsigned long bval = vp->value.vector->bval;\n\t\tfor (unsigned idx = 0 ; idx < wid ; idx += 1) {\n\t\t int bit = (aval&1) | (((bval^aval)<<1)&2);\n\t\t set_bit(rfp, idx, bit);\n\t\t aval >>= 1;\n\t\t bval >>= 1;\n\t\t}\n\t\tbreak;\n\t }\n\n\t default:\n\t assert(0);\n\n }\n\n return ref;\n}\n\n\/\/ The code fully supports vpiReg, vpi_Net, but we do not \n\/\/ create such things, yet. Lacking a neme, for example.\n\nstatic const struct __vpirt vpip_vthr_const_rt = {\n vpiConstant,\n vthr_vec_get,\n vthr_vec_get_str,\n vthr_vec_get_value,\n vthr_vec_put_value,\n 0,\n 0\n};\n\n\/*\n * Construct a vpiReg object. Give the object specified dimensions,\n * and point to the specified functor for the lsb.\n *\/\nvpiHandle vpip_make_vthr_vector(unsigned base, unsigned wid)\n{\n struct __vpiVThrVec*obj = (struct __vpiVThrVec*)\n\t malloc(sizeof(struct __vpiVThrVec));\n obj->base.vpi_type = &vpip_vthr_const_rt;\n obj->bas = base;\n obj->wid = wid;\n obj->name = \"T<>\";\n\n return &obj->base;\n}\n\n\n\/*\n * $Log: vpi_vthr_vector.cc,v $\n * Revision 1.1 2001\/05\/10 00:26:53 steve\n * VVP support for memories in expressions,\n * including general support for thread bit\n * vectors as system task parameters.\n * (Stephan Boettcher)\n *\n *\/\n\n<commit_msg> Get bit ordering right when making decimal strings.<commit_after>\/*\n * Copyright (c) 2001 Stephen Williams (steve@icarus.com)\n * Copyright (c) 2001 Stephan Boettcher <stephan@nevis.columbia.edu>\n *\n * This source code is free software; you can redistribute it\n * and\/or modify it in source code form under the terms of the GNU\n * General Public License as published by the Free Software\n * Foundation; either version 2 of the License, or (at your option)\n * any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA\n *\/\n#if !defined(WINNT)\n#ident \"$Id: vpi_vthr_vector.cc,v 1.2 2001\/05\/20 00:40:12 steve Exp $\"\n#endif\n\n\/*\n * vpiReg handles are handled here. These objects represent vectors of\n * .var objects that can be manipulated by the VPI module.\n *\/\n\n# include \"vpi_priv.h\"\n# include \"vthread.h\"\n# include <stdio.h>\n# include <malloc.h>\n# include <assert.h>\n\nstruct __vpiVThrVec {\n struct __vpiHandle base;\n unsigned short bas;\n unsigned short wid;\n char *name;\n};\n\ninline static \nunsigned get_bit(struct __vpiVThrVec *rfp, unsigned idx)\n{\n return vthread_get_bit(vpip_current_vthread, rfp->bas+idx);\n}\n\ninline static \nvoid set_bit(struct __vpiVThrVec *rfp, unsigned idx, unsigned bit)\n{\n return vthread_put_bit(vpip_current_vthread, rfp->bas+idx, bit);\n}\n\n\n\/*\n * Hex digits that represent 4-value bits of Verilog are not as\n * trivially obvious to display as if the bits were the usual 2-value\n * bits. So, although it is possible to write a function that\n * generates a correct character for 4*4-value bits, it is easier to\n * just perform the lookup in a table. This only takes 256 bytes,\n * which is not many executable instructions:-)\n *\n * The table is calculated as compile time, therefore, by the\n * draw_tt.c program.\n *\/\n\nextern const char hex_digits[256];\n\nextern const char oct_digits[256];\n\n\/*\n * vpi_get\n *\/\nstatic int vthr_vec_get(int code, vpiHandle ref)\n{\n assert((ref->vpi_type->type_code==vpiNet)\n\t || (ref->vpi_type->type_code==vpiReg)\n\t || (ref->vpi_type->type_code==vpiConstant));\n\n struct __vpiVThrVec*rfp = (struct __vpiVThrVec*)ref;\n\n switch (code) {\n\n\t case vpiSigned:\n\t return 0;\n\n\t case vpiSize:\n\t return rfp->wid;\n\n\t default:\n\t return 0;\n }\n}\n\nstatic char* vthr_vec_get_str(int code, vpiHandle ref)\n{\n assert((ref->vpi_type->type_code==vpiNet)\n\t || (ref->vpi_type->type_code==vpiReg));\n\n struct __vpiVThrVec*rfp = (struct __vpiVThrVec*)ref;\n\n switch (code) {\n\n\t case vpiFullName:\n\t return (char*)rfp->name;\n }\n\n return 0;\n}\n\nstatic char buf[4096];\n\nstatic void vthr_vec_DecStrVal(struct __vpiVThrVec*rfp, s_vpi_value*vp)\n{\n unsigned long val = 0;\n unsigned count_x = 0, count_z = 0;\n\n for (unsigned idx = 0 ; idx < rfp->wid ; idx += 1) {\n\t val *= 2;\n\t switch (get_bit(rfp, rfp->wid-idx-1)) {\n\t\tcase 0:\n\t\t break;\n\t\tcase 1:\n\t\t val += 1;\n\t\t break;\n\t\tcase 2:\n\t\t count_x += 1;\n\t\t break;\n\t\tcase 3:\n\t\t count_z += 1;\n\t\t break;\n\t }\n }\n\n if (count_x == rfp->wid) {\n\t buf[0] = 'x';\n\t buf[1] = 0;\n\t return;\n }\n\n if (count_x > 0) {\n\t buf[0] = 'X';\n\t buf[1] = 0;\n\t return;\n }\n\n if (count_z == rfp->wid) {\n\t buf[0] = 'z';\n\t buf[1] = 0;\n\t return;\n }\n\n if (count_z > 0) {\n\t buf[0] = 'Z';\n\t buf[1] = 0;\n\t return;\n }\n\n sprintf(buf, \"%lu\", val);\n}\n\n\/*\n * The get_value method reads the values of the functors and returns\n * the vector to the caller. This causes no side-effect, and reads the\n * variables like a %load would.\n *\/\nstatic void vthr_vec_get_value(vpiHandle ref, s_vpi_value*vp)\n{\n assert((ref->vpi_type->type_code==vpiNet)\n\t || (ref->vpi_type->type_code==vpiReg)\n\t || (ref->vpi_type->type_code==vpiConstant));\n\n struct __vpiVThrVec*rfp = (struct __vpiVThrVec*)ref;\n \n unsigned wid = rfp->wid;\n\n switch (vp->format) {\n\n\t case vpiBinStrVal:\n\t for (unsigned idx = 0 ; idx < wid ; idx += 1) {\n\t\t buf[wid-idx-1] = \"01xz\"[get_bit(rfp, idx)];\n\t }\n\t buf[wid] = 0;\n\t vp->value.str = buf;\n\t break;\n\t \n\t case vpiHexStrVal: {\n\t\tunsigned hval, hwid;\n\t\thwid = (wid + 3) \/ 4;\n\t\tbuf[hwid] = 0;\n\t\thval = 0;\n\t\tfor (unsigned idx = 0 ; idx < wid ; idx += 1) {\n\t\t hval = hval | (get_bit(rfp, idx) << 2*(idx % 4));\n\n\t\t if (idx%4 == 3) {\n\t\t\t hwid -= 1;\n\t\t\t buf[hwid] = hex_digits[hval];\n\t\t\t hval = 0;\n\t\t }\n\t\t}\n\n\t\tif (hwid > 0) {\n\t\t hwid -= 1;\n\t\t buf[hwid] = hex_digits[hval];\n\t\t hval = 0;\n\t\t}\n\t\tvp->value.str = buf;\n\t\tbreak;\n\t }\n\n\t case vpiOctStrVal: {\n\t\tunsigned hval, hwid;\n\t\thwid = (wid + 2) \/ 3;\n\t\tbuf[hwid] = 0;\n\t\thval = 0;\n\t\tfor (unsigned idx = 0 ; idx < wid ; idx += 1) {\n\t\t hval = hval | (get_bit(rfp,idx) << 2*(idx % 3));\n\n\t\t if (idx%3 == 2) {\n\t\t\t hwid -= 1;\n\t\t\t buf[hwid] = oct_digits[hval];\n\t\t\t hval = 0;\n\t\t }\n\t\t}\n\n\t\tif (hwid > 0) {\n\t\t hwid -= 1;\n\t\t buf[hwid] = oct_digits[hval];\n\t\t hval = 0;\n\t\t}\n\t\tvp->value.str = buf;\n\t\tbreak;\n\t }\n\n\t case vpiDecStrVal:\n\t vthr_vec_DecStrVal(rfp, vp);\n\t vp->value.str = buf;\n\t break;\n\n\t default:\n\t \/* XXXX Not implemented yet. *\/\n\t assert(0);\n }\n}\n\n\/*\n * The put_value method writes the value into the vector.\n *\/\nstatic vpiHandle vthr_vec_put_value(vpiHandle ref, s_vpi_value*vp,\n\t\t\t\t p_vpi_time when, int flags)\n{\n assert((ref->vpi_type->type_code==vpiNet)\n\t || (ref->vpi_type->type_code==vpiReg));\n\n struct __vpiVThrVec*rfp = (struct __vpiVThrVec*)ref;\n\n\t\/* XXXX delays are not yet supported. *\/\n assert(flags == vpiNoDelay);\n\n unsigned wid = rfp->wid;\n\n switch (vp->format) {\n\t \n\t case vpiIntVal: {\n\t\tassert(wid <= sizeof(long));\n\n\t\tlong val = vp->value.integer;\n\t\tfor (unsigned idx = 0 ; idx < wid ; idx += 1) {\n\t\t set_bit(rfp, idx, val&1);\n\t\t val >>= 1;\n\t\t}\n\t\tbreak;\n\t }\n\n\t case vpiScalarVal:\n\t switch (vp->value.scalar) {\n\t\tcase vpi0:\n\t\t set_bit(rfp, 0, 0);\n\t\t break;\n\t\tcase vpi1:\n\t\t set_bit(rfp, 0, 1);\n\t\t break;\n\t\tcase vpiX:\n\t\t set_bit(rfp, 0, 2);\n\t\t break;\n\t\tcase vpiZ:\n\t\t set_bit(rfp, 0, 3);\n\t\t break;\n\t\tdefault:\n\t\t assert(0);\n\t }\n\t break;\n\n\t case vpiVectorVal: {\n\t\tassert(wid <= sizeof (unsigned long));\n\n\t\tunsigned long aval = vp->value.vector->aval;\n\t\tunsigned long bval = vp->value.vector->bval;\n\t\tfor (unsigned idx = 0 ; idx < wid ; idx += 1) {\n\t\t int bit = (aval&1) | (((bval^aval)<<1)&2);\n\t\t set_bit(rfp, idx, bit);\n\t\t aval >>= 1;\n\t\t bval >>= 1;\n\t\t}\n\t\tbreak;\n\t }\n\n\t default:\n\t assert(0);\n\n }\n\n return ref;\n}\n\n\/\/ The code fully supports vpiReg, vpi_Net, but we do not \n\/\/ create such things, yet. Lacking a neme, for example.\n\nstatic const struct __vpirt vpip_vthr_const_rt = {\n vpiConstant,\n vthr_vec_get,\n vthr_vec_get_str,\n vthr_vec_get_value,\n vthr_vec_put_value,\n 0,\n 0\n};\n\n\/*\n * Construct a vpiReg object. Give the object specified dimensions,\n * and point to the specified functor for the lsb.\n *\/\nvpiHandle vpip_make_vthr_vector(unsigned base, unsigned wid)\n{\n struct __vpiVThrVec*obj = (struct __vpiVThrVec*)\n\t malloc(sizeof(struct __vpiVThrVec));\n obj->base.vpi_type = &vpip_vthr_const_rt;\n obj->bas = base;\n obj->wid = wid;\n obj->name = \"T<>\";\n\n return &obj->base;\n}\n\n\n\/*\n * $Log: vpi_vthr_vector.cc,v $\n * Revision 1.2 2001\/05\/20 00:40:12 steve\n * Get bit ordering right when making decimal strings.\n *\n * Revision 1.1 2001\/05\/10 00:26:53 steve\n * VVP support for memories in expressions,\n * including general support for thread bit\n * vectors as system task parameters.\n * (Stephan Boettcher)\n *\n *\/\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n * This program is free software; you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or\n * (at your option) any later version.\n *\n * Written (W) 2011 Heiko Strathmann\n * Copyright (C) 2011 Berlin Institute of Technology and Max-Planck-Society\n *\/\n\n#include <shogun\/base\/init.h>\n#include <shogun\/base\/Parameter.h>\n#include <shogun\/base\/ParameterMap.h>\n\nusing namespace shogun;\n\nvoid print_message(FILE* target, const char* str)\n{\n\tfprintf(target, \"%s\", str);\n}\n\n\n\nvoid test_mapping_1()\n{\n\tParameterMap* map=new ParameterMap();\n\n\tmap->put(\n\t\t\tnew SGParamInfo(\"number\", CT_SCALAR, ST_NONE, PT_FLOAT64, 2),\n\t\t\tnew SGParamInfo(\"number\", CT_SCALAR, ST_NONE, PT_INT32, 1)\n\t);\n\n\tmap->put(\n\t\t\tnew SGParamInfo(\"number\", CT_SCALAR, ST_NONE, PT_INT32, 1),\n\t\t\tnew SGParamInfo(\"number\", CT_SCALAR, ST_NONE, PT_FLOAT64, 0)\n\t);\n\n\t\/* finalizing the map is needed before accessing it *\/\n\tmap->finalize_map();\n\n\tmap->print_map();\n\tSG_SPRINT(\"\\n\");\n\n\n\t\/* get some elements from map, one\/two ARE in map, three and four are NOT *\/\n\tDynArray<SGParamInfo*> dummies;\n\tdummies.append_element(new SGParamInfo(\"number\", CT_SCALAR, ST_NONE,\n\t\t\tPT_INT32, 1));\n\tdummies.append_element(new SGParamInfo(\"number\", CT_SCALAR, ST_NONE,\n\t\t\tPT_FLOAT64, 2));\n\tdummies.append_element(new SGParamInfo(\"number\", CT_SCALAR, ST_NONE,\n\t\t\t\tPT_INT32, 2));\n\tdummies.append_element(new SGParamInfo(\"number\", CT_SCALAR, ST_NONE,\n\t\t\tPT_FLOAT64, 0));\n\n\tfor (index_t i=0; i<dummies.get_num_elements(); ++i)\n\t{\n\t\tSGParamInfo* current=dummies.get_element(i);\n\n\t\tchar* s=current->to_string();\n\t\tSG_SPRINT(\"searching for: %s\\n\", s);\n\t\tSG_FREE(s);\n\n\t\tif (i==2)\n\t\t{\n\n\t\t}\n\n\t\tSGParamInfo* result=map->get(current);\n\t\tif (result)\n\t\t{\n\t\t\ts=result->to_string();\n\t\t\tSG_SPRINT(\"found: %s\\n\\n\", s);\n\t\t\tSG_FREE(s);\n\t\t}\n\t\telse\n\t\t\tSG_SPRINT(\"nothing found\\n\\n\");\n\n\t\tdelete current;\n\t}\n\n\tdelete map;\n}\n\nvoid print_value(SGParamInfo* key, ParameterMap* map)\n{\n\tSGParamInfo* current=map->get(key);\n\tkey->print_param_info();\n\tSG_SPRINT(\"value: \");\n\n\tif (current)\n\t\tcurrent->print_param_info();\n\telse\n\t\tSG_SPRINT(\"no element\\n\");\n\n\tSG_SPRINT(\"\\n\");\n}\n\nvoid test_mapping_2()\n{\n\tParameterMap* map=new ParameterMap();\n\n\tEContainerType cfrom=CT_SCALAR;\n\tEContainerType cto=CT_MATRIX;\n\n\tEStructType sfrom=ST_NONE;\n\tEStructType sto=ST_STRING;\n\n\tEPrimitiveType pfrom=PT_BOOL;\n\tEPrimitiveType pto=PT_SGOBJECT;\n\n\tmap->put(new SGParamInfo(\"1\", cfrom, sfrom, pfrom, 1),\n\t\t\tnew SGParamInfo(\"eins\", cto, sto, pto, 2));\n\tmap->put(new SGParamInfo(\"2\", cfrom, sfrom, pfrom, 2),\n\t\t\tnew SGParamInfo(\"zwei\", cto, sto, pto, 1));\n\tmap->put(new SGParamInfo(\"3\", cfrom, sfrom, pfrom, 3),\n\t\t\tnew SGParamInfo(\"drei\", cto, sto, pto, 5));\n\tmap->put(new SGParamInfo(\"4\", cfrom, sfrom, pfrom, 4),\n\t\t\tnew SGParamInfo(\"vier\", cto, sto, pto, 2));\n\n\tSG_SPRINT(\"before finalization:\\n\");\n\tmap->print_map();\n\tmap->finalize_map();\n\n\tSG_SPRINT(\"\\n\\nafter finalization:\\n\");\n\tmap->print_map();\n\n\tSGParamInfo* key;\n\n\tSG_SPRINT(\"\\n\\ntesting map\\n\");\n\tkey=new SGParamInfo(\"1\", cfrom, sfrom, pfrom, 1);\n\tprint_value(key, map);\n\tdelete key;\n\n\tkey=new SGParamInfo(\"2\", cfrom, sfrom, pfrom, 2);\n\tprint_value(key, map);\n\tdelete key;\n\n\tkey=new SGParamInfo(\"2\", cto, sfrom, pfrom, 2);\n\tprint_value(key, map);\n\tdelete key;\n\n\tkey=new SGParamInfo(\"2\", cfrom, sto, pfrom, 2);\n\tprint_value(key, map);\n\tdelete key;\n\n\tkey=new SGParamInfo(\"2\", cfrom, sfrom, pto, 2);\n\tprint_value(key, map);\n\tdelete key;\n\n\tkey=new SGParamInfo(\"5\", cfrom, sfrom, pfrom, 5);\n\tprint_value(key, map);\n\tdelete key;\n\n\tdelete map;\n}\n\nint main(int argc, char **argv)\n{\n\tinit_shogun(&print_message, &print_message, &print_message);\n\n\ttest_mapping_1();\n\ttest_mapping_2();\n\n\texit_shogun();\n\n\treturn 0;\n}\n\n<commit_msg>corrected error in example due to restriction that parameter step has to be one<commit_after>\/*\n * This program is free software; you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or\n * (at your option) any later version.\n *\n * Written (W) 2011 Heiko Strathmann\n * Copyright (C) 2011 Berlin Institute of Technology and Max-Planck-Society\n *\/\n\n#include <shogun\/base\/init.h>\n#include <shogun\/base\/Parameter.h>\n#include <shogun\/base\/ParameterMap.h>\n\nusing namespace shogun;\n\nvoid print_message(FILE* target, const char* str)\n{\n\tfprintf(target, \"%s\", str);\n}\n\n\n\nvoid test_mapping_1()\n{\n\tParameterMap* map=new ParameterMap();\n\n\tmap->put(\n\t\t\tnew SGParamInfo(\"number\", CT_SCALAR, ST_NONE, PT_FLOAT64, 2),\n\t\t\tnew SGParamInfo(\"number\", CT_SCALAR, ST_NONE, PT_INT32, 1)\n\t);\n\n\tmap->put(\n\t\t\tnew SGParamInfo(\"number\", CT_SCALAR, ST_NONE, PT_INT32, 1),\n\t\t\tnew SGParamInfo(\"number\", CT_SCALAR, ST_NONE, PT_FLOAT64, 0)\n\t);\n\n\tmap->put(\n\t\t\tnew SGParamInfo(\"number_2\", CT_SCALAR, ST_NONE, PT_INT32, 1),\n\t\t\tnew SGParamInfo(\"number_to_keep\", CT_SCALAR, ST_NONE, PT_INT32, 0)\n\t);\n\n\t\/* finalizing the map is needed before accessing it *\/\n\tmap->finalize_map();\n\n\tmap->print_map();\n\tSG_SPRINT(\"\\n\");\n\n\n\t\/* get some elements from map, one\/two ARE in map, three and four are NOT *\/\n\tDynArray<SGParamInfo*> dummies;\n\tdummies.append_element(new SGParamInfo(\"number\", CT_SCALAR, ST_NONE,\n\t\t\tPT_INT32, 1));\n\tdummies.append_element(new SGParamInfo(\"number\", CT_SCALAR, ST_NONE,\n\t\t\tPT_FLOAT64, 2));\n\tdummies.append_element(new SGParamInfo(\"number\", CT_SCALAR, ST_NONE,\n\t\t\t\tPT_INT32, 2));\n\tdummies.append_element(new SGParamInfo(\"number\", CT_SCALAR, ST_NONE,\n\t\t\tPT_FLOAT64, 0));\n\tdummies.append_element(new SGParamInfo(\"number_2\", CT_SCALAR, ST_NONE,\n\t\t\tPT_INT32, 1));\n\n\tfor (index_t i=0; i<dummies.get_num_elements(); ++i)\n\t{\n\t\tSGParamInfo* current=dummies.get_element(i);\n\n\t\tchar* s=current->to_string();\n\t\tSG_SPRINT(\"searching for: %s\\n\", s);\n\t\tSG_FREE(s);\n\n\t\tSGParamInfo* result=map->get(current);\n\t\tif (result)\n\t\t{\n\t\t\ts=result->to_string();\n\t\t\tSG_SPRINT(\"found: %s\\n\\n\", s);\n\t\t\tSG_FREE(s);\n\t\t}\n\t\telse\n\t\t\tSG_SPRINT(\"nothing found\\n\\n\");\n\n\t\tdelete current;\n\t}\n\n\tdelete map;\n}\n\nvoid print_value(SGParamInfo* key, ParameterMap* map)\n{\n\tSGParamInfo* current=map->get(key);\n\tkey->print_param_info();\n\tSG_SPRINT(\"value: \");\n\n\tif (current)\n\t\tcurrent->print_param_info();\n\telse\n\t\tSG_SPRINT(\"no element\\n\");\n\n\tSG_SPRINT(\"\\n\");\n}\n\nvoid test_mapping_2()\n{\n\tParameterMap* map=new ParameterMap();\n\n\tEContainerType cfrom=CT_SCALAR;\n\tEContainerType cto=CT_MATRIX;\n\n\tEStructType sfrom=ST_NONE;\n\tEStructType sto=ST_STRING;\n\n\tEPrimitiveType pfrom=PT_BOOL;\n\tEPrimitiveType pto=PT_SGOBJECT;\n\n\tmap->put(new SGParamInfo(\"1\", cfrom, sfrom, pfrom, 2),\n\t\t\tnew SGParamInfo(\"eins\", cto, sto, pto, 1));\n\tmap->put(new SGParamInfo(\"2\", cfrom, sfrom, pfrom, 2),\n\t\t\tnew SGParamInfo(\"zwei\", cto, sto, pto, 1));\n\tmap->put(new SGParamInfo(\"3\", cfrom, sfrom, pfrom, 4),\n\t\t\tnew SGParamInfo(\"drei\", cto, sto, pto, 3));\n\tmap->put(new SGParamInfo(\"4\", cfrom, sfrom, pfrom, 4),\n\t\t\tnew SGParamInfo(\"vier\", cto, sto, pto, 3));\n\n\tSG_SPRINT(\"before finalization:\\n\");\n\tmap->print_map();\n\tmap->finalize_map();\n\n\tSG_SPRINT(\"\\n\\nafter finalization:\\n\");\n\tmap->print_map();\n\n\tSGParamInfo* key;\n\n\tSG_SPRINT(\"\\n\\ntesting map\\n\");\n\tkey=new SGParamInfo(\"1\", cfrom, sfrom, pfrom, 1);\n\tprint_value(key, map);\n\tdelete key;\n\n\tkey=new SGParamInfo(\"2\", cfrom, sfrom, pfrom, 2);\n\tprint_value(key, map);\n\tdelete key;\n\n\tkey=new SGParamInfo(\"2\", cto, sfrom, pfrom, 2);\n\tprint_value(key, map);\n\tdelete key;\n\n\tkey=new SGParamInfo(\"2\", cfrom, sto, pfrom, 2);\n\tprint_value(key, map);\n\tdelete key;\n\n\tkey=new SGParamInfo(\"2\", cfrom, sfrom, pto, 2);\n\tprint_value(key, map);\n\tdelete key;\n\n\tkey=new SGParamInfo(\"5\", cfrom, sfrom, pfrom, 4);\n\tprint_value(key, map);\n\tdelete key;\n\n\tdelete map;\n}\n\nint main(int argc, char **argv)\n{\n\tinit_shogun(&print_message, &print_message, &print_message);\n\n\ttest_mapping_1();\n\ttest_mapping_2();\n\n\texit_shogun();\n\n\treturn 0;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: ScatterChartTypeTemplate.hxx,v $\n *\n * $Revision: 1.5 $\n *\n * last change: $Author: rt $ $Date: 2005-09-08 01:24:41 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n#ifndef CHART_SCATTERCHARTTYPETEMPLATE_HXX\n#define CHART_SCATTERCHARTTYPETEMPLATE_HXX\n\n#include \"ChartTypeTemplate.hxx\"\n#include \"OPropertySet.hxx\"\n#include \"MutexContainer.hxx\"\n\n#ifndef _COMPHELPER_UNO3_HXX_\n#include <comphelper\/uno3.hxx>\n#endif\n\n#ifndef _COM_SUN_STAR_CHART2_STACKMODE_HPP_\n#include <com\/sun\/star\/chart2\/StackMode.hpp>\n#endif\n#ifndef _COM_SUN_STAR_CHART2_CURVESTYLE_HPP_\n#include <com\/sun\/star\/chart2\/CurveStyle.hpp>\n#endif\n\nnamespace chart\n{\n\nclass ScatterChartTypeTemplate :\n public helper::MutexContainer,\n public ChartTypeTemplate,\n public ::property::OPropertySet\n{\npublic:\n explicit ScatterChartTypeTemplate(\n ::com::sun::star::uno::Reference<\n ::com::sun::star::uno::XComponentContext > const & xContext,\n const ::rtl::OUString & rServiceName,\n ::com::sun::star::chart2::CurveStyle eCurveStyle,\n bool bSymbols,\n bool bHasLines = true,\n sal_Int32 nDim = 2 );\n virtual ~ScatterChartTypeTemplate();\n\n \/\/\/ XServiceInfo declarations\n APPHELPER_XSERVICEINFO_DECL()\n\n \/\/\/ merge XInterface implementations\n DECLARE_XINTERFACE()\n \/\/\/ merge XTypeProvider implementations\n DECLARE_XTYPEPROVIDER()\n\nprotected:\n \/\/ ____ OPropertySet ____\n virtual ::com::sun::star::uno::Any GetDefaultValue( sal_Int32 nHandle ) const\n throw(::com::sun::star::beans::UnknownPropertyException);\n virtual ::cppu::IPropertyArrayHelper & SAL_CALL getInfoHelper();\n\n \/\/ ____ XPropertySet ____\n virtual ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySetInfo > SAL_CALL\n getPropertySetInfo()\n throw (::com::sun::star::uno::RuntimeException);\n\n \/\/ ____ XChartTypeTemplate ____\n virtual ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XDiagram > SAL_CALL\n createDiagram( const ::com::sun::star::uno::Sequence<\n ::com::sun::star::uno::Reference<\n ::com::sun::star::chart2::XDataSeries > >& aSeriesSeq )\n throw (::com::sun::star::uno::RuntimeException);\n virtual sal_Bool SAL_CALL matchesTemplate(\n const ::com::sun::star::uno::Reference<\n ::com::sun::star::chart2::XDiagram >& xDiagram )\n throw (::com::sun::star::uno::RuntimeException);\n\n \/\/ ____ ChartTypeTemplate ____\n virtual sal_Int32 getDimension() const;\n virtual ::com::sun::star::uno::Reference<\n ::com::sun::star::chart2::XChartType > getDefaultChartType()\n throw (::com::sun::star::uno::RuntimeException);\n\nprivate:\n ::com::sun::star::chart2::CurveStyle\n m_eCurveStyle;\n bool m_bHasSymbols;\n bool m_bHasLines;\n sal_Int32 m_nDim;\n};\n\n} \/\/ namespace chart\n\n\/\/ CHART_SCATTERCHARTTYPETEMPLATE_HXX\n#endif\n<commit_msg>INTEGRATION: CWS chart2mst3 (1.4.4); FILE MERGED 2007\/03\/26 14:20:42 iha 1.4.4.17: #i75590# copy some aspects from old charttype during creation of new 2005\/10\/07 12:06:06 bm 1.4.4.16: RESYNC: (1.4-1.5); FILE MERGED 2005\/07\/15 16:07:22 bm 1.4.4.15: keep more old objects on chart type changes 2005\/07\/14 14:59:03 bm 1.4.4.14: overload supportsCategories 2005\/05\/09 09:51:27 bm 1.4.4.13: moved parts of API to data namespace 2004\/09\/15 17:32:07 bm 1.4.4.12: API simplification 2004\/06\/29 12:26:35 bm 1.4.4.11: XChartTypeTemplate changes 2004\/05\/27 17:27:13 bm 1.4.4.10: +getChartTypeForNewSeries at XChartTypeTemplate 2004\/05\/07 15:34:37 bm 1.4.4.9: applyStyle works for single series now 2004\/04\/20 19:21:35 iha 1.4.4.8: make curve style an adabtable property 2004\/04\/01 10:53:12 bm 1.4.4.7: XChartType: may return a coordinate system now 2004\/03\/24 19:05:25 bm 1.4.4.6: XChartTypeTemplate changed: matchesTemplate may modify the template s properties if bAdaptProperties is true 2004\/03\/22 15:27:08 iha 1.4.4.5: added parameter SwapXAndYAxis for horizontal bar chart to method createCoordinateSystems 2004\/03\/19 14:32:59 bm 1.4.4.4: XDataSource now contains XLabeledDataSources 2004\/03\/02 16:40:44 bm 1.4.4.3: allow creating more than one coordinate system 2004\/02\/20 17:43:58 iha 1.4.4.2: integrate categories at ScaleData 2004\/02\/13 16:51:45 bm 1.4.4.1: join from changes on branch bm_post_chart01<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: ScatterChartTypeTemplate.hxx,v $\n *\n * $Revision: 1.6 $\n *\n * last change: $Author: vg $ $Date: 2007-05-22 18:52:14 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n#ifndef CHART_SCATTERCHARTTYPETEMPLATE_HXX\n#define CHART_SCATTERCHARTTYPETEMPLATE_HXX\n\n#include \"ChartTypeTemplate.hxx\"\n#include \"OPropertySet.hxx\"\n#include \"MutexContainer.hxx\"\n\n#ifndef _COMPHELPER_UNO3_HXX_\n#include <comphelper\/uno3.hxx>\n#endif\n\n#ifndef _COM_SUN_STAR_CHART2_CURVESTYLE_HPP_\n#include <com\/sun\/star\/chart2\/CurveStyle.hpp>\n#endif\n\nnamespace chart\n{\n\nclass ScatterChartTypeTemplate :\n public MutexContainer,\n public ChartTypeTemplate,\n public ::property::OPropertySet\n{\npublic:\n explicit ScatterChartTypeTemplate(\n ::com::sun::star::uno::Reference<\n ::com::sun::star::uno::XComponentContext > const & xContext,\n const ::rtl::OUString & rServiceName,\n bool bSymbols,\n bool bHasLines = true,\n sal_Int32 nDim = 2 );\n virtual ~ScatterChartTypeTemplate();\n\n \/\/\/ XServiceInfo declarations\n APPHELPER_XSERVICEINFO_DECL()\n\n \/\/\/ merge XInterface implementations\n DECLARE_XINTERFACE()\n \/\/\/ merge XTypeProvider implementations\n DECLARE_XTYPEPROVIDER()\n\nprotected:\n \/\/ ____ OPropertySet ____\n virtual ::com::sun::star::uno::Any GetDefaultValue( sal_Int32 nHandle ) const\n throw(::com::sun::star::beans::UnknownPropertyException);\n virtual ::cppu::IPropertyArrayHelper & SAL_CALL getInfoHelper();\n\n \/\/ ____ XPropertySet ____\n virtual ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySetInfo > SAL_CALL\n getPropertySetInfo()\n throw (::com::sun::star::uno::RuntimeException);\n\n \/\/ ____ XChartTypeTemplate ____\n virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getAvailableCreationParameterNames()\n throw (::com::sun::star::uno::RuntimeException);\n virtual sal_Bool SAL_CALL matchesTemplate(\n const ::com::sun::star::uno::Reference<\n ::com::sun::star::chart2::XDiagram >& xDiagram,\n sal_Bool bAdaptProperties )\n throw (::com::sun::star::uno::RuntimeException);\n virtual ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XChartType > SAL_CALL\n getChartTypeForNewSeries( const ::com::sun::star::uno::Sequence<\n ::com::sun::star::uno::Reference<\n ::com::sun::star::chart2::XChartType > >& aFormerlyUsedChartTypes )\n throw (::com::sun::star::uno::RuntimeException);\n virtual ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XDataInterpreter > SAL_CALL getDataInterpreter()\n throw (::com::sun::star::uno::RuntimeException);\n virtual void SAL_CALL applyStyle(\n const ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XDataSeries >& xSeries,\n ::sal_Int32 nChartTypeGroupIndex,\n ::sal_Int32 nSeriesIndex,\n ::sal_Int32 nSeriesCount )\n throw (::com::sun::star::uno::RuntimeException);\n\n \/\/ ____ ChartTypeTemplate ____\n virtual sal_Int32 getDimension() const;\n\n virtual bool supportsCategories() const;\n\nprivate:\n bool m_bHasSymbols;\n bool m_bHasLines;\n sal_Int32 m_nDim;\n};\n\n} \/\/ namespace chart\n\n\/\/ CHART_SCATTERCHARTTYPETEMPLATE_HXX\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Copyright (c) 2011, John Haddon. All rights reserved.\n\/\/ Copyright (c) 2013, Image Engine Design Inc. All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are\n\/\/ met:\n\/\/\n\/\/ * Redistributions of source code must retain the above\n\/\/ copyright notice, this list of conditions and the following\n\/\/ disclaimer.\n\/\/\n\/\/ * Redistributions in binary form must reproduce the above\n\/\/ copyright notice, this list of conditions and the following\n\/\/ disclaimer in the documentation and\/or other materials provided with\n\/\/ the distribution.\n\/\/\n\/\/ * Neither the name of John Haddon nor the names of\n\/\/ any other contributors to this software may be used to endorse or\n\/\/ promote products derived from this software without specific prior\n\/\/ written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS\n\/\/ IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,\n\/\/ THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n\/\/ PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR\n\/\/ CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n\/\/ EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n\/\/ PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n\/\/ PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n\/\/ LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n\/\/ NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n\/\/ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"boost\/python.hpp\"\n\n#include \"GafferBindings\/UndoContextBinding.h\"\n#include \"Gaffer\/UndoContext.h\"\n#include \"Gaffer\/ScriptNode.h\"\n\nusing namespace boost::python;\nusing namespace GafferBindings;\nusing namespace Gaffer;\n\nnamespace GafferBindings\n{\n\nvoid bindUndoContext()\n{\n\tscope s = class_<UndoContext, boost::noncopyable>( \"_UndoContext\", init<ScriptNodePtr>() )\n\t\t.def( init<ScriptNodePtr, UndoContext::State>() )\n\t\t.def( init<ScriptNodePtr, UndoContext::State, const std::string &>() )\n\t;\n\n\tenum_<UndoContext::State>( \"State\" )\n\t\t.value( \"Invalid\", UndoContext::Invalid )\n\t\t.value( \"Enabled\", UndoContext::Enabled )\n\t\t.value( \"Disabled\", UndoContext::Disabled )\n\t;\n}\n\n} \/\/ namespace GafferBindings\n<commit_msg>Released GIL in UndoContext.__exit__().<commit_after>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Copyright (c) 2011, John Haddon. All rights reserved.\n\/\/ Copyright (c) 2013, Image Engine Design Inc. All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are\n\/\/ met:\n\/\/\n\/\/ * Redistributions of source code must retain the above\n\/\/ copyright notice, this list of conditions and the following\n\/\/ disclaimer.\n\/\/\n\/\/ * Redistributions in binary form must reproduce the above\n\/\/ copyright notice, this list of conditions and the following\n\/\/ disclaimer in the documentation and\/or other materials provided with\n\/\/ the distribution.\n\/\/\n\/\/ * Neither the name of John Haddon nor the names of\n\/\/ any other contributors to this software may be used to endorse or\n\/\/ promote products derived from this software without specific prior\n\/\/ written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS\n\/\/ IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,\n\/\/ THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n\/\/ PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR\n\/\/ CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n\/\/ EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n\/\/ PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n\/\/ PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n\/\/ LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n\/\/ NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n\/\/ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"boost\/python.hpp\"\n\n#include \"IECorePython\/ScopedGILRelease.h\"\n\n#include \"Gaffer\/UndoContext.h\"\n#include \"Gaffer\/ScriptNode.h\"\n\n#include \"GafferBindings\/UndoContextBinding.h\"\n\nusing namespace boost::python;\nusing namespace GafferBindings;\nusing namespace Gaffer;\n\nnamespace\n{\n\ntypedef boost::shared_ptr<UndoContext> UndoContextPtr;\n\nvoid deleter( UndoContext *undoContext )\n{\n\t\/\/ The destructor for the undo context may trigger a dirty\n\t\/\/ propagation, and observers of plugDirtiedSignal() may\n\t\/\/ well invoke a compute. We need to release the GIL so that\n\t\/\/ if that compute is multithreaded, those threads can acquire\n\t\/\/ the GIL for python based nodes and expressions.\n\tIECorePython::ScopedGILRelease gilRelease;\n\tdelete undoContext;\n}\n\nUndoContextPtr construct( ScriptNodePtr script, UndoContext::State state, const char *mergeGroup )\n{\n\treturn UndoContextPtr( new UndoContext( script, state, mergeGroup ), deleter );\n}\n\n} \/\/ namespace\n\nnamespace GafferBindings\n{\n\nvoid bindUndoContext()\n{\n\tclass_<UndoContext, UndoContextPtr, boost::noncopyable> cls( \"_UndoContext\", no_init );\n\n\t\/\/ Must bind enum before constructor, because we need to\n\t\/\/ use an enum value for a default value.\n\tscope s( cls );\n\tenum_<UndoContext::State>( \"State\" )\n\t\t.value( \"Invalid\", UndoContext::Invalid )\n\t\t.value( \"Enabled\", UndoContext::Enabled )\n\t\t.value( \"Disabled\", UndoContext::Disabled )\n\t;\n\n\tcls.def(\n\t\t\"__init__\",\n\t\tmake_constructor(\n\t\t\tconstruct,\n\t\t\tdefault_call_policies(),\n\t\t\t(\n\t\t\t\tboost::python::arg_( \"script\" ),\n\t\t\t\tboost::python::arg_( \"state\" ) = UndoContext::Enabled,\n\t\t\t\tboost::python::arg_( \"mergeGroup\" ) = \"\"\n\t\t\t)\n\t\t)\n\t);\n}\n\n} \/\/ namespace GafferBindings\n<|endoftext|>"} {"text":"<commit_before>#include <QApplication>\n#include <QSettings>\n#include <QIcon>\n\n#include <QDebug>\n\n#include \"appcontroller.h\"\n#include \"appwindow.h\"\n#include \"secondarywindow.h\"\n#include \"widgets\/librarywidget.h\"\n#include \"widgets\/secondary\/loginwidget.h\"\n#include \"widgets\/secondary\/settingswidget.h\"\n\n#include \"ui_secondarywindow.h\"\n\nAppController::AppController(QObject* parent)\n : QObject(parent)\n , settingsWindow(NULL)\n , loginWithApiKey(false)\n{\n setupSettings();\n api = new ItchioApi(this, settings->apiUrl());\n\n setupTrayIcon();\n setupAppWindow();\n\n if (settings->autoLogin() && settings->hasValidApiKey()) {\n api->loginWithApiKey(settings->apiKey(), [this](bool success, QString err) {\n if (success) {\n onLogin();\n } else {\n onAutoLoginFailure(err);\n }\n });\n\n loginWithApiKey = true;\n } else {\n setupLogin();\n }\n\n settingsWindow = new SecondaryWindow(new SettingsWidget(this), this, false);\n\n}\n\nvoid AppController::setupSettings()\n{\n settingsFile = QCoreApplication::applicationDirPath() + \"\/itchio.ini\";\n settings = new AppSettings(settingsFile, QSettings::IniFormat, this);\n}\n\nvoid AppController::quit()\n{\n appWindow->hideWindow();\n trayIcon->hide();\n\n settings->enableStartMaximized(appWindow->isMaximized);\n settings->setWindowGeometry(appWindow->saveGeometry());\n settings->setWindowOldSize(appWindow->oldSize);\n settings->setWindowOldPosition(appWindow->oldPosition);\n\n if (settings->autoLogin()) {\n settings->setApiKey(api->userKey);\n settings->setUsername(api->userName);\n }\n else{\n settings->setApiKey(\"\");\n settings->setUsername(\"\");\n }\n\n QCoreApplication::exit();\n}\n\nvoid AppController::showSettings()\n{\n settingsWindow->show();\n settingsWindow->activateWindow();\n}\n\nvoid AppController::trayIconDoubleClick(QSystemTrayIcon::ActivationReason reason)\n{\n if (reason == QSystemTrayIcon::DoubleClick && !appWindow->isVisible()) {\n appWindow->showWindow();\n }\n}\n\nvoid AppController::setupTrayIcon()\n{\n trayIcon = new QSystemTrayIcon(this);\n\n trayIcon->setIcon(QIcon(\":\/images\/images\/itchio-icon-16.png\"));\n trayIcon->show();\n}\n\nvoid AppController::setupTrayIconMenu(bool beforeLogin)\n{\n trayIconMenu = new QMenu();\n trayIcon->setContextMenu(trayIconMenu);\n\n if (!beforeLogin) {\n QAction* actionSettings = new QAction(\"Settings\", this);\n trayIconMenu->addAction(actionSettings);\n connect(actionSettings, SIGNAL(triggered()), this, SLOT(showSettings()));\n\n trayIconMenu->addSeparator();\n }\n\n QAction* actionQuit = new QAction(\"Quit\", this);\n trayIconMenu->addAction(actionQuit);\n connect(actionQuit, SIGNAL(triggered()), this, SLOT(quit()));\n\n connect(trayIcon, SIGNAL(activated(QSystemTrayIcon::ActivationReason)),\n this, SLOT(trayIconDoubleClick(QSystemTrayIcon::ActivationReason)));\n}\n\nvoid AppController::showTrayIconNotification(TrayNotifications::Notifications notification, QString data)\n{\n if (settings->showTrayNotifications()) {\n if((notification == TrayNotifications::LIBRARY_UPDATE &&\n settings->showLibraryUpdateNotifications()) ||\n (notification == TrayNotifications::DOWNLOAD_FINISHED &&\n settings->showDownloadFinishedNotifications()) ||\n (notification == TrayNotifications::GAME_UPDATE_AVAILABLE &&\n settings->showGameUpdateAvailableNotifications())){\n\n trayIcon->showMessage(TrayNotifications::toString(notification),\n data, QSystemTrayIcon::NoIcon, 5000);\n }\n\n\n }\n}\n\nvoid AppController::setupLogin()\n{\n settings->setApiKey(\"\");\n api->userKey = \"\";\n\n setupTrayIconMenu(true);\n\n loginWindow = new SecondaryWindow(new LoginWidget(qobject_cast<QWidget*>(this), this), this, true);\n loginWindow->show();\n}\n\nvoid AppController::setupAppWindow()\n{\n appWindow = new AppWindow(this);\n}\n\nvoid AppController::onLogin()\n{\n setupTrayIconMenu();\n\n if (!loginWithApiKey) {\n loginWindow->deleteLater();\n loginWindow->close();\n }\n\n appWindow->setupLibrary();\n}\n\nvoid AppController::onAutoLoginFailure(QString)\n{\n setupLogin();\n}\n<commit_msg>Window geometry settings will not be saved if app closed on login.<commit_after>#include <QApplication>\n#include <QSettings>\n#include <QIcon>\n\n#include <QDebug>\n\n#include \"appcontroller.h\"\n#include \"appwindow.h\"\n#include \"secondarywindow.h\"\n#include \"widgets\/librarywidget.h\"\n#include \"widgets\/secondary\/loginwidget.h\"\n#include \"widgets\/secondary\/settingswidget.h\"\n\n#include \"ui_secondarywindow.h\"\n\nAppController::AppController(QObject* parent)\n : QObject(parent)\n , settingsWindow(NULL)\n , loginWithApiKey(false)\n{\n setupSettings();\n api = new ItchioApi(this, settings->apiUrl());\n\n setupTrayIcon();\n setupAppWindow();\n\n if (settings->autoLogin() && settings->hasValidApiKey()) {\n api->loginWithApiKey(settings->apiKey(), [this](bool success, QString err) {\n if (success) {\n onLogin();\n } else {\n onAutoLoginFailure(err);\n }\n });\n\n loginWithApiKey = true;\n } else {\n setupLogin();\n }\n\n settingsWindow = new SecondaryWindow(new SettingsWidget(this), this, false);\n\n}\n\nvoid AppController::setupSettings()\n{\n settingsFile = QCoreApplication::applicationDirPath() + \"\/itchio.ini\";\n settings = new AppSettings(settingsFile, QSettings::IniFormat, this);\n}\n\nvoid AppController::quit()\n{\n appWindow->hideWindow();\n trayIcon->hide();\n\n if(api->userName != \"\"){\n settings->enableStartMaximized(appWindow->isMaximized);\n settings->setWindowGeometry(appWindow->saveGeometry());\n settings->setWindowOldSize(appWindow->oldSize);\n settings->setWindowOldPosition(appWindow->oldPosition);\n }\n\n if (settings->autoLogin()) {\n settings->setApiKey(api->userKey);\n settings->setUsername(api->userName);\n }\n else{\n settings->setApiKey(\"\");\n settings->setUsername(\"\");\n }\n\n QCoreApplication::exit();\n}\n\nvoid AppController::showSettings()\n{\n settingsWindow->show();\n settingsWindow->activateWindow();\n}\n\nvoid AppController::trayIconDoubleClick(QSystemTrayIcon::ActivationReason reason)\n{\n if (reason == QSystemTrayIcon::DoubleClick && !appWindow->isVisible()) {\n appWindow->showWindow();\n }\n}\n\nvoid AppController::setupTrayIcon()\n{\n trayIcon = new QSystemTrayIcon(this);\n\n trayIcon->setIcon(QIcon(\":\/images\/images\/itchio-icon-16.png\"));\n trayIcon->show();\n}\n\nvoid AppController::setupTrayIconMenu(bool beforeLogin)\n{\n trayIconMenu = new QMenu();\n trayIcon->setContextMenu(trayIconMenu);\n\n if (!beforeLogin) {\n QAction* actionSettings = new QAction(\"Settings\", this);\n trayIconMenu->addAction(actionSettings);\n connect(actionSettings, SIGNAL(triggered()), this, SLOT(showSettings()));\n\n trayIconMenu->addSeparator();\n }\n\n QAction* actionQuit = new QAction(\"Quit\", this);\n trayIconMenu->addAction(actionQuit);\n connect(actionQuit, SIGNAL(triggered()), this, SLOT(quit()));\n\n connect(trayIcon, SIGNAL(activated(QSystemTrayIcon::ActivationReason)),\n this, SLOT(trayIconDoubleClick(QSystemTrayIcon::ActivationReason)));\n}\n\nvoid AppController::showTrayIconNotification(TrayNotifications::Notifications notification, QString data)\n{\n if (settings->showTrayNotifications()) {\n if((notification == TrayNotifications::LIBRARY_UPDATE &&\n settings->showLibraryUpdateNotifications()) ||\n (notification == TrayNotifications::DOWNLOAD_FINISHED &&\n settings->showDownloadFinishedNotifications()) ||\n (notification == TrayNotifications::GAME_UPDATE_AVAILABLE &&\n settings->showGameUpdateAvailableNotifications())){\n\n trayIcon->showMessage(TrayNotifications::toString(notification),\n data, QSystemTrayIcon::NoIcon, 5000);\n }\n\n\n }\n}\n\nvoid AppController::setupLogin()\n{\n settings->setApiKey(\"\");\n api->userKey = \"\";\n\n setupTrayIconMenu(true);\n\n loginWindow = new SecondaryWindow(new LoginWidget(qobject_cast<QWidget*>(this), this), this, true);\n loginWindow->show();\n}\n\nvoid AppController::setupAppWindow()\n{\n appWindow = new AppWindow(this);\n}\n\nvoid AppController::onLogin()\n{\n setupTrayIconMenu();\n\n if (!loginWithApiKey) {\n loginWindow->deleteLater();\n loginWindow->close();\n }\n\n appWindow->setupLibrary();\n}\n\nvoid AppController::onAutoLoginFailure(QString)\n{\n setupLogin();\n}\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: valuenodeaccess.hxx,v $\n *\n * $Revision: 1.2 $\n *\n * last change: $Author: jb $ $Date: 2002-03-28 08:47:03 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef CONFIGMGR_VALUENODEACCESS_HXX\n#define CONFIGMGR_VALUENODEACCESS_HXX\n\n#ifndef CONFIGMGR_NODEACCESS_HXX\n#include \"nodeaccess.hxx\"\n#endif\n\nnamespace configmgr\n{\n\/\/ -----------------------------------------------------------------------------\n namespace data\n {\n \/\/ -------------------------------------------------------------------------\n class ValueNodeAccess\n {\n public:\n typedef NodeAccess::Name Name;\n typedef NodeAccess::Attributes Attributes;\n typedef ValueNodeAddress NodeAddressType;\n typedef ValueNodeAddress::AddressType AddressType;\n typedef ValueNodeAddress::DataType const DataType;\n typedef DataType * NodePointerType;\n\n ValueNodeAccess(Accessor const& _aAccessor, NodeAddressType const& _aNodeRef)\n : m_aAccessor(_aAccessor)\n , m_pData(_aNodeRef.m_pData)\n {}\n\n ValueNodeAccess(Accessor const& _aAccessor, NodePointerType _pNode)\n : m_aAccessor(_aAccessor)\n , m_pData(check(_aAccessor,_pNode))\n {}\n\n explicit\n ValueNodeAccess(NodeAccess const & _aNode)\n : m_aAccessor(_aNode.accessor())\n , m_pData(check(_aNode))\n {\n }\n\n static bool isInstance(NodeAccess const & _aNode)\n {\n return check(_aNode) != NULL;\n }\n\n bool isValid() const { return m_pData != NULL; }\n\n Name getName() const;\n Attributes getAttributes() const;\n\n bool isEmpty() const { return data().isEmpty(); }\n\n bool isNull() const { return data().isNull(); }\n bool isDefault() const;\n bool isLocalized() const;\n\n bool hasUsableDefault() const { return data().hasUsableDefault(); }\n\n uno::Type getValueType() const { return data().getValueType(); }\n uno::Any getValue() const;\n uno::Any getUserValue() const;\n uno::Any getDefaultValue() const;\n\n static void setValue(memory::UpdateAccessor & _aUpdater, NodeAddressType _aValueNode, uno::Any const& _aValue);\n static void setToDefault(memory::UpdateAccessor & _aUpdater, NodeAddressType _aValueNode);\n static void changeDefault(memory::UpdateAccessor & _aUpdater, NodeAddressType _aValueNode, uno::Any const& _aValue);\n\n NodeAddressType address() const { return NodeAddressType(m_pData); }\n Accessor accessor() const { return m_aAccessor; }\n\n DataType& data() const { return *static_cast<NodePointerType>(m_aAccessor.validate(m_pData)); }\n\n operator NodeAccess() const { return NodeAccess(m_aAccessor,NodeAddress(m_pData)); }\n private:\n static AddressType check(Accessor const& _acc, NodePointerType _p) { return _acc.address(_p); }\n static AddressType check(NodeAccess const& _aNodeData);\n\n Accessor m_aAccessor;\n AddressType m_pData;\n };\n\n ValueNodeAddress toValueNodeAddress(memory::Accessor const & _aAccess, NodeAddress const & _aNodeAddr);\n ValueNodeAddress toValueNodeAddress(memory::UpdateAccessor & _aAccess, NodeAddress const & _aNodeAddr);\n \/\/ -------------------------------------------------------------------------\n\n inline\n NodeAccess::Name ValueNodeAccess::getName() const\n { return NodeAccess::wrapName( data().info.getName(m_aAccessor) ); }\n\n inline\n NodeAccess::Attributes ValueNodeAccess::getAttributes() const\n { return data().info.getAttributes(); }\n\n inline\n bool ValueNodeAccess::isDefault() const\n { return data().info.isDefault(); }\n\n inline\n bool ValueNodeAccess::isLocalized() const\n { return data().info.isLocalized(); }\n\n inline\n uno::Any ValueNodeAccess::getValue() const\n { return data().getValue(m_aAccessor); }\n\n inline\n uno::Any ValueNodeAccess::getUserValue() const\n { return data().getUserValue(m_aAccessor); }\n\n inline\n uno::Any ValueNodeAccess::getDefaultValue() const\n { return data().getDefaultValue(m_aAccessor); }\n\n \/\/ -------------------------------------------------------------------------\n }\n\/\/ -----------------------------------------------------------------------------\n} \/\/ namespace configmgr\n\n#endif \/\/ CONFIGMGR_VALUENODEACCESS_HXX\n\n<commit_msg>INTEGRATION: CWS cfg01 (1.2.24); FILE MERGED 2003\/03\/13 15:28:15 jb 1.2.24.2: #108154# Use NodeAccessRef to avoid copying Accessor objects 2003\/02\/28 16:33:18 ssmith 1.2.24.1: #107403# #107403# adding support for mandatory flag and changing dynamic properties semantics<commit_after>\/*************************************************************************\n *\n * $RCSfile: valuenodeaccess.hxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: vg $ $Date: 2003-04-01 13:35:21 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef CONFIGMGR_VALUENODEACCESS_HXX\n#define CONFIGMGR_VALUENODEACCESS_HXX\n\n#ifndef CONFIGMGR_NODEACCESS_HXX\n#include \"nodeaccess.hxx\"\n#endif\n\nnamespace configmgr\n{\n\/\/ -----------------------------------------------------------------------------\n namespace data\n {\n \/\/ -------------------------------------------------------------------------\n class ValueNodeAccess\n {\n public:\n typedef NodeAccess::Name Name;\n typedef NodeAccess::Attributes Attributes;\n typedef ValueNodeAddress NodeAddressType;\n typedef ValueNodeAddress::AddressType AddressType;\n typedef ValueNodeAddress::DataType const DataType;\n typedef DataType * NodePointerType;\n\n ValueNodeAccess(Accessor const& _aAccessor, NodeAddressType const& _aNodeRef)\n : m_aAccessor(_aAccessor)\n , m_pData(_aNodeRef.m_pData)\n {}\n\n ValueNodeAccess(Accessor const& _aAccessor, NodePointerType _pNode)\n : m_aAccessor(_aAccessor)\n , m_pData(check(_aAccessor,_pNode))\n {}\n\n explicit\n ValueNodeAccess(NodeAccess const & _aNode)\n : m_aAccessor(_aNode.accessor())\n , m_pData(check(_aNode))\n {\n }\n\n explicit\n ValueNodeAccess(NodeAccessRef const & _aNode)\n : m_aAccessor(_aNode.accessor())\n , m_pData(check(_aNode))\n {\n }\n\n static bool isInstance(NodeAccessRef const & _aNode)\n {\n return check(_aNode) != NULL;\n }\n\n bool isValid() const { return m_pData != NULL; }\n\n Name getName() const;\n Attributes getAttributes() const;\n\n bool isEmpty() const { return data().isEmpty(); }\n\n bool isNull() const { return data().isNull(); }\n bool isDefault() const;\n bool isLocalized() const;\n\n bool hasUsableDefault() const { return data().hasUsableDefault(); }\n\n uno::Type getValueType() const { return data().getValueType(); }\n uno::Any getValue() const;\n uno::Any getUserValue() const;\n uno::Any getDefaultValue() const;\n\n static void setValue(memory::UpdateAccessor & _aUpdater, NodeAddressType _aValueNode, uno::Any const& _aValue);\n static void setToDefault(memory::UpdateAccessor & _aUpdater, NodeAddressType _aValueNode);\n static void changeDefault(memory::UpdateAccessor & _aUpdater, NodeAddressType _aValueNode, uno::Any const& _aValue);\n\n NodeAddressType address() const { return NodeAddressType(m_pData); }\n Accessor const& accessor() const { return m_aAccessor; }\n\n DataType& data() const { return *static_cast<NodePointerType>(m_aAccessor.validate(m_pData)); }\n\n operator NodeAccessRef() const { return NodeAccessRef(&m_aAccessor,NodeAddress(m_pData)); }\n private:\n static AddressType check(Accessor const& _acc, NodePointerType _p) { return _acc.address(_p); }\n static AddressType check(NodeAccessRef const& _aNodeData);\n\n Accessor m_aAccessor;\n AddressType m_pData;\n };\n\n ValueNodeAddress toValueNodeAddress(memory::Accessor const & _aAccess, NodeAddress const & _aNodeAddr);\n ValueNodeAddress toValueNodeAddress(memory::UpdateAccessor & _aAccess, NodeAddress const & _aNodeAddr);\n \/\/ -------------------------------------------------------------------------\n\n inline\n NodeAccess::Name ValueNodeAccess::getName() const\n { return NodeAccess::wrapName( data().info.getName(m_aAccessor) ); }\n\n inline\n NodeAccess::Attributes ValueNodeAccess::getAttributes() const\n { return sharable::node(data()).getAttributes(); }\n\n inline\n bool ValueNodeAccess::isDefault() const\n { return data().info.isDefault(); }\n\n inline\n bool ValueNodeAccess::isLocalized() const\n { return data().info.isLocalized(); }\n\n inline\n uno::Any ValueNodeAccess::getValue() const\n { return data().getValue(m_aAccessor); }\n\n inline\n uno::Any ValueNodeAccess::getUserValue() const\n { return data().getUserValue(m_aAccessor); }\n\n inline\n uno::Any ValueNodeAccess::getDefaultValue() const\n { return data().getDefaultValue(m_aAccessor); }\n\n \/\/ -------------------------------------------------------------------------\n }\n\/\/ -----------------------------------------------------------------------------\n} \/\/ namespace configmgr\n\n#endif \/\/ CONFIGMGR_VALUENODEACCESS_HXX\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n * D3Q27Lattice.cpp\n *\n * Created on: Jul 10, 2017\n * Author: sblair\n *\/\n#include \"D3Q27Lattice.h\"\n#include <cstdlib>\n\nD3Q27Lattice::D3Q27Lattice(const int Nx, const int Ny, const int Nz):\nLattice(Nx,Ny,Nz),\nex{0,1,-1,0,0,0,0,1,1,-1,-1,1,1,-1,-1,0,0,0,0,1,1,1,1,-1,-1,-1,-1},\ney{0,0,0,1,-1,0,0,1,-1,1,-1,0,0,0,0,1,1,-1,-1,1,1,-1,-1,1,1,-1,-1},\nez{0,0,0,0,0,1,-1,0,0,0,0,1,-1,1,-1,1,-1,1,-1,1,-1,1,-1,1,-1,1,-1},\nw{8.\/27.,2.\/27.,2.\/27.,2.\/27.,2.\/27.,2.\/27.,2.\/27.,\n 1.\/54.,1.\/54.,1.\/54.,1.\/54.,1.\/54.,1.\/54.,\n 1.\/54.,1.\/54.,1.\/54.,1.\/54.,1.\/54.,1.\/54.,\n 1.\/216.,1.\/216.,1.\/216.,1.\/216.,\n 1.\/216.,1.\/216.,1.\/216.,1.\/216.},\nbbSpd{0,2,1,4,3,6,5,10,9,8,7,14,13,12,11,18,17,16,15,26,25,24,23,22,21,20,19},\nQflat{-1.\/3.,0,0,0,-1.\/3.,0,0,0,-1.\/3., \/\/ 0\n\t 2.\/3.,0,0,0,-1.\/3.,0,0,0,-1.\/3., \/\/ 1\n\t -1.\/3.,0,0,0,2.\/3.,0,0,0,-1.\/3.,\/\/ 2\n\t -1.\/3.,0,0,0,-1.\/3.,0,0,0,2.\/3.,\/\/ 3\n\t 2.\/3.,1,0,1,2.\/3.,0,0,0,-1.\/3.,\/\/ 4\n\t 2.\/3.,-1,0,-1,2.\/3.,0,0,0,-1.\/3.,\/\/ 5\n\t 2.\/3.,0,1,0,-1.\/3.,0,1,0,2.\/3.,\/\/ 6\n\t 2.\/3.,0,-1,0,-1.\/3.,0,-1,0,2.\/3.,\/\/ 7\n\t -1.\/3.,0,0,0,2.\/3.,1,0,1,2.\/3.,\/\/8\n\t -1.\/3.,0,0,0,2.\/3.,-1,0,-1,2.\/3.,\/\/9\n\t 2.\/3.,1,1,1,2.\/3.,1,1,1,2.\/3.,\/\/10\n\t 2.\/3.,1,-1,1,2.\/3.,-1,-1,-1,2.\/3.,\/\/11\n\t 2.\/3.,-1,1,-1,2.\/3.,-1,1,-1,2.\/3.,\/\/12\n\t 2.\/3.,-1,-1,-1,2.\/3.,1,-1,1,2.\/3.,\/\/13\n\t 2.\/3.,0,0,0,-1.\/3.,0,0,0,-1.\/3.,\/\/14\n\t -1.\/3.,0,0,0,2.\/3.,0,0,0,-1.\/3.,\/\/15\n\t -1.\/3.,0,0,0,-1.\/3.,0,0,0,2.\/3.,\/\/16\n\t 2.\/3.,1,0,1,2.\/3.,0,0,0,-1.\/3.,\/\/17\n\t 2.\/3.,-1,0,-1,2.\/3.,0,0,0,-1.\/3.,\/\/18\n\t 2.\/3.,0,1,0,-1.\/3.,0,1,0,2.\/3.,\/\/19\n\t 2.\/3.,0,-1,0,-1.\/3.,0,-1,0,2.\/3.,\/\/20\n\t -1.\/3.,0,0,0,2.\/3.,1,0,1,2.\/3.,\/\/21\n\t -1.\/3.,0,0,0,2.\/3.,-1,0,-1,2.\/3.,\/\/22\n\t 2.\/3.,1,1,1,2.\/3.,1,1,1,2.\/3.,\/\/23\n\t 2.\/3.,1,-1,1,2.\/3.,-1,-1,-1,2.\/3.,\/\/24\n\t 2.\/3.,-1,1,-1,2.\/3.,-1,1,-1,2.\/3.,\/\/25\n\t 2.\/3.,-1,-1,-1,2.\/3.,1,-1,1,2.\/3.}\/\/26\n{\n\t\/\/ direct base-class pointers to lattice variables\n\tsetNumSpd(numSpd);\n\tsetEx(ex);\n\tsetEy(ey);\n\tsetEz(ez);\n\tsetW(w);\n\tsetBBspd(bbSpd);\n\tsetQflat(Qflat);\n\n}\n\nD3Q27Lattice::~D3Q27Lattice()\n{\n\n}\n\nvoid D3Q27Lattice::set_inlet_bc_micro(LBM_DataHandler& f)\n{\n\tint sp[9]={5,11,13,15,17,19,21,23,25};\n\tint bbSp[9]={6,14,12,18,16,26,24,22,20};\n\tint numBB = 9;\n\tfor(int s=0;s<numBB;s++)\n\t{\n\t\tf.f[sp[s]]=f.fEq[sp[s]]+f.f[bbSp[s]]-f.fEq[bbSp[s]];\n\t}\n}\n\nvoid D3Q27Lattice::set_inlet_bc_macro(LBM_DataHandler& f)\n{\n\tf.uz = f.u_bc;\n\tf.ux = 0; f.uy = 0.;\n\tf.rho = (1.\/(1. - f.uz))*(2.*(f.f[6]+f.f[14]+f.f[12]+\n\t\t\tf.f[18]+f.f[16]+f.f[26]+f.f[24]+f.f[22]+f.f[20])+\n\t\t\t(f.f[0]+f.f[1]+f.f[2]+f.f[3]+f.f[4]+\n\t\t\t\t\tf.f[7]+f.f[8]+f.f[9]+f.f[10]));\n}\n\nvoid D3Q27Lattice::set_outlet_bc_micro(LBM_DataHandler& f)\n{\n\tint sp[9]={6,14,12,18,16,26,24,22,202};\n\tint bbSp[9]={5,11,13,15,17,19,21,23,25};\n\tint numBB = 9;\n\tfor(int s=0;s<numBB;s++)\n\t{\n\t\tf.f[sp[s]]=f.fEq[sp[s]]+f.f[bbSp[s]]-f.fEq[bbSp[s]];\n\t}\n}\n\nvoid D3Q27Lattice::set_outlet_bc_macro(LBM_DataHandler& f)\n{\n\tf.rho = f.rho_bc;\n\tf.uz = -1. + (1.\/f.rho)*(2.*\n\t\t\t(f.f[5]+f.f[11]+f.f[13]+f.f[15]+f.f[17]+f.f[19]+\n\t\t\t\t\tf.f[21]+f.f[23]+f.f[25])+\n\t\t\t\t\t(f.f[0]+f.f[1]+f.f[2]+f.f[3]+f.f[4]+\n\t\t\t\t\t\t\tf.f[7]+f.f[8]+f.f[9]+f.f[10]));\n}\n\n\n<commit_msg>fixed bug in D3Q27 re-ordering implementation<commit_after>\/*\n * D3Q27Lattice.cpp\n *\n * Created on: Jul 10, 2017\n * Author: sblair\n *\/\n#include \"D3Q27Lattice.h\"\n#include <cstdlib>\n\nD3Q27Lattice::D3Q27Lattice(const int Nx, const int Ny, const int Nz):\nLattice(Nx,Ny,Nz),\nex{0,1,-1,0,0,0,0,1,1,-1,-1,1,1,-1,-1,0,0,0,0,1,1,1,1,-1,-1,-1,-1},\ney{0,0,0,1,-1,0,0,1,-1,1,-1,0,0,0,0,1,1,-1,-1,1,1,-1,-1,1,1,-1,-1},\nez{0,0,0,0,0,1,-1,0,0,0,0,1,-1,1,-1,1,-1,1,-1,1,-1,1,-1,1,-1,1,-1},\nw{8.\/27.,2.\/27.,2.\/27.,2.\/27.,2.\/27.,2.\/27.,2.\/27.,\n 1.\/54.,1.\/54.,1.\/54.,1.\/54.,1.\/54.,1.\/54.,\n 1.\/54.,1.\/54.,1.\/54.,1.\/54.,1.\/54.,1.\/54.,\n 1.\/216.,1.\/216.,1.\/216.,1.\/216.,\n 1.\/216.,1.\/216.,1.\/216.,1.\/216.},\nbbSpd{0,2,1,4,3,6,5,10,9,8,7,14,13,12,11,18,17,16,15,26,25,24,23,22,21,20,19},\nQflat{-1.\/3.,0,0,0,-1.\/3.,0,0,0,-1.\/3., \/\/ 0\n\t 2.\/3.,0,0,0,-1.\/3.,0,0,0,-1.\/3., \/\/ 1\n\t -1.\/3.,0,0,0,2.\/3.,0,0,0,-1.\/3.,\/\/ 2\n\t -1.\/3.,0,0,0,-1.\/3.,0,0,0,2.\/3.,\/\/ 3\n\t 2.\/3.,1,0,1,2.\/3.,0,0,0,-1.\/3.,\/\/ 4\n\t 2.\/3.,-1,0,-1,2.\/3.,0,0,0,-1.\/3.,\/\/ 5\n\t 2.\/3.,0,1,0,-1.\/3.,0,1,0,2.\/3.,\/\/ 6\n\t 2.\/3.,0,-1,0,-1.\/3.,0,-1,0,2.\/3.,\/\/ 7\n\t -1.\/3.,0,0,0,2.\/3.,1,0,1,2.\/3.,\/\/8\n\t -1.\/3.,0,0,0,2.\/3.,-1,0,-1,2.\/3.,\/\/9\n\t 2.\/3.,1,1,1,2.\/3.,1,1,1,2.\/3.,\/\/10\n\t 2.\/3.,1,-1,1,2.\/3.,-1,-1,-1,2.\/3.,\/\/11\n\t 2.\/3.,-1,1,-1,2.\/3.,-1,1,-1,2.\/3.,\/\/12\n\t 2.\/3.,-1,-1,-1,2.\/3.,1,-1,1,2.\/3.,\/\/13\n\t 2.\/3.,0,0,0,-1.\/3.,0,0,0,-1.\/3.,\/\/14\n\t -1.\/3.,0,0,0,2.\/3.,0,0,0,-1.\/3.,\/\/15\n\t -1.\/3.,0,0,0,-1.\/3.,0,0,0,2.\/3.,\/\/16\n\t 2.\/3.,1,0,1,2.\/3.,0,0,0,-1.\/3.,\/\/17\n\t 2.\/3.,-1,0,-1,2.\/3.,0,0,0,-1.\/3.,\/\/18\n\t 2.\/3.,0,1,0,-1.\/3.,0,1,0,2.\/3.,\/\/19\n\t 2.\/3.,0,-1,0,-1.\/3.,0,-1,0,2.\/3.,\/\/20\n\t -1.\/3.,0,0,0,2.\/3.,1,0,1,2.\/3.,\/\/21\n\t -1.\/3.,0,0,0,2.\/3.,-1,0,-1,2.\/3.,\/\/22\n\t 2.\/3.,1,1,1,2.\/3.,1,1,1,2.\/3.,\/\/23\n\t 2.\/3.,1,-1,1,2.\/3.,-1,-1,-1,2.\/3.,\/\/24\n\t 2.\/3.,-1,1,-1,2.\/3.,-1,1,-1,2.\/3.,\/\/25\n\t 2.\/3.,-1,-1,-1,2.\/3.,1,-1,1,2.\/3.}\/\/26\n{\n\t\/\/ direct base-class pointers to lattice variables\n\tsetNumSpd(numSpd);\n\tsetEx(ex);\n\tsetEy(ey);\n\tsetEz(ez);\n\tsetW(w);\n\tsetBBspd(bbSpd);\n\tsetQflat(Qflat);\n\n}\n\nD3Q27Lattice::~D3Q27Lattice()\n{\n\n}\n\nvoid D3Q27Lattice::set_inlet_bc_micro(LBM_DataHandler& f)\n{\n\tint sp[9]={5,11,13,15,17,19,21,23,25};\n\tint bbSp[9]={6,14,12,18,16,26,24,22,20};\n\tint numBB = 9;\n\tfor(int s=0;s<numBB;s++)\n\t{\n\t\tf.f[sp[s]]=f.fEq[sp[s]]+f.f[bbSp[s]]-f.fEq[bbSp[s]];\n\t}\n}\n\nvoid D3Q27Lattice::set_inlet_bc_macro(LBM_DataHandler& f)\n{\n\tf.uz = f.u_bc;\n\tf.ux = 0; f.uy = 0.;\n\tf.rho = (1.\/(1. - f.uz))*(2.*(f.f[6]+f.f[14]+f.f[12]+\n\t\t\tf.f[18]+f.f[16]+f.f[26]+f.f[24]+f.f[22]+f.f[20])+\n\t\t\t(f.f[0]+f.f[1]+f.f[2]+f.f[3]+f.f[4]+\n\t\t\t\t\tf.f[7]+f.f[8]+f.f[9]+f.f[10]));\n}\n\nvoid D3Q27Lattice::set_outlet_bc_micro(LBM_DataHandler& f)\n{\n\tint sp[9]={6,14,12,18,16,26,24,22,20};\n\tint bbSp[9]={5,11,13,15,17,19,21,23,25};\n\tint numBB = 9;\n\tfor(int s=0;s<numBB;s++)\n\t{\n\t\tf.f[sp[s]]=f.fEq[sp[s]]+f.f[bbSp[s]]-f.fEq[bbSp[s]];\n\t}\n}\n\nvoid D3Q27Lattice::set_outlet_bc_macro(LBM_DataHandler& f)\n{\n\tf.rho = f.rho_bc;\n\tf.uz = -1. + (1.\/f.rho)*(2.*\n\t\t\t(f.f[5]+f.f[11]+f.f[13]+f.f[15]+f.f[17]+f.f[19]+\n\t\t\t\t\tf.f[21]+f.f[23]+f.f[25])+\n\t\t\t\t\t(f.f[0]+f.f[1]+f.f[2]+f.f[3]+f.f[4]+\n\t\t\t\t\t\t\tf.f[7]+f.f[8]+f.f[9]+f.f[10]));\n}\n\n\n<|endoftext|>"} {"text":"<commit_before><commit_msg>some nicer error outputs<commit_after><|endoftext|>"} {"text":"<commit_before>\/***************************************************************\n *\n * Copyright (C) 1990-2011, Condor Team, Computer Sciences Department,\n * University of Wisconsin-Madison, WI.\n * \n * Licensed under the Apache License, Version 2.0 (the \"License\"); you\n * may not use this file except in compliance with the License. You may\n * obtain a copy of the License at\n * \n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n ***************************************************************\/\n\n\n#include \"condor_common.h\"\n#include \"startd_cron_job_mgr.h\"\n#include \"startd_cron_job.h\"\n#include \"condor_config.h\"\n#include \"startd.h\"\n\n\/\/ Basic constructor\nStartdCronJobMgr::StartdCronJobMgr( void )\n\t\t: CronJobMgr( ),\n\t\t m_shutting_down( false ),\n\t\t m_auto_publish( CAP_NEVER )\n{\n}\n\n\/\/ Basic destructor\nStartdCronJobMgr::~StartdCronJobMgr( void )\n{\n\tdprintf( D_FULLDEBUG, \"StartdCronJobMgr: Bye\\n\" );\n}\n\nint\nStartdCronJobMgr::Initialize( const char *name )\n{\n\tint status;\n\n\tSetName( name, name, \"_cron\" );\n\t\n\tchar *cron_name = param( \"STARTD_CRON_NAME\" );\n\tif ( NULL != cron_name ) {\n\t\tdprintf( D_ALWAYS,\n\t\t\t\t \"WARNING: The use of STARTD_CRON_NAME to 'name' your \"\n\t\t\t\t \"Startd's Daemon ClassAd Hook Manager is not longer supported \"\n\t\t\t\t \"and will be removed in a future release of Condor.\" );\n\t\tname = cron_name;\n\t\tSetName( name, name );\n\t}\n\n\tstatus = CronJobMgr::Initialize( name );\n\tif ( NULL != cron_name ) {\n\t\tfree( cron_name );\n\t}\n\n\tParamAutoPublish( );\n\treturn status;\n}\n\nint\nStartdCronJobMgr::Reconfig( void )\n{\n\tParamAutoPublish();\n\treturn CronJobMgr::HandleReconfig();\n}\n\nvoid\nStartdCronJobMgr::ParamAutoPublish( void )\n{\n\tm_auto_publish = CAP_NEVER; \/\/ always default to never if not set\n\tchar* tmp = param(\"STARTD_CRON_AUTOPUBLISH\");\n\tif( tmp ) {\n\t\tm_auto_publish = getCronAutoPublishNum(tmp);\n\t\tif( m_auto_publish == CAP_ERROR ) {\n\t\t\tdprintf( D_ALWAYS, \"StartdCronJobMgr::Reconfig(): \"\n\t\t\t\t\t \"invalid value for STARTD_CRON_AUTOPUBLISH: \\\"%s\\\" \"\n\t\t\t\t\t \"using default value of NEVER\\n\", tmp );\n\t\t\tm_auto_publish = CAP_NEVER;\n\t\t} else {\n\t\t\tdprintf( D_FULLDEBUG, \"StartdCronJobMgr::Reconfig(): \"\n\t\t\t\t\t \"STARTD_CRON_AUTOPUBLISH set to \\\"%s\\\"\\n\", tmp );\n\t\t}\n\t\tfree( tmp );\n\t\ttmp = NULL;\n\t}\n}\n\n\/\/ Perform shutdown\nint\nStartdCronJobMgr::Shutdown( bool force )\n{\n\tdprintf( D_FULLDEBUG, \"StartdCronJobMgr: Shutting down\\n\" );\n\tm_shutting_down = true;\n\treturn KillAll( force );\n}\n\n\/\/ Check shutdown\nbool\nStartdCronJobMgr::ShutdownOk( void )\n{\n\tbool\tidle = IsAllIdle( );\n\n\t\/\/ dprintf( D_ALWAYS, \"ShutdownOk: %s\\n\", idle ? \"Idle\" : \"Busy\" );\n\treturn idle;\n}\n\nStartdCronJobParams *\nStartdCronJobMgr::CreateJobParams( const char *job_name )\n{\n\treturn new StartdCronJobParams( job_name, *this );\n}\n\nStartdCronJob *\nStartdCronJobMgr::CreateJob( CronJobParams *job_params )\n{\n\tconst char * jobName = job_params->GetName();\n\n\tdprintf( D_FULLDEBUG,\n\t\t\t \"*** Creating Startd Cron job '%s'***\\n\",\n\t\t\t jobName );\n\tStartdCronJobParams *params =\n\t\tdynamic_cast<StartdCronJobParams *>( job_params );\n\tASSERT( params );\n\n\tchar * metricString = params->Lookup( \"METRICS\" );\n\tif( metricString != NULL && metricString[0] != '\\0' ) {\n\t\tStringList pairs( metricString );\n\t\tfor( char * pair = pairs.first(); pair != NULL; pair = pairs.next() ) {\n\t\t\tStringList tn( pair, \":\" );\n\t\t\tchar * metricType = tn.first();\n\t\t\tchar * attributeName = tn.next();\n\t\t\tif(! params->addMetric( metricType, attributeName )) {\n\t\t\t\tdprintf( \tD_ALWAYS, \"Unknown metric type '%s' for attribute \"\n\t\t\t\t\t\t\t\"'%s' in monitor '%s', ignoring.\\n\", metricType,\n\t\t\t\t\t\t\tattributeName, jobName );\n\t\t\t} else {\n\t\t\t\tdprintf(\tD_FULLDEBUG, \"Added %s as %s metric for %s job\\n\",\n\t\t\t\t\t\t\tattributeName, metricType, jobName );\n\t\t\t}\n\t\t}\n\n\t\tfree( metricString );\n\t}\n\n\treturn new StartdCronJob( params, *this );\n}\n\n\/\/ Should we start a job?\nbool\nStartdCronJobMgr::ShouldStartJob( const CronJob &job ) const\n{\n\tif ( m_shutting_down ) {\n\t\treturn false;\n\t}\n\n\t\/\/ Don't start *any* new jobs during benchmarks\n\tif ( bench_job_mgr && bench_job_mgr->NumActiveBenchmarks() ) {\n\t\treturn false;\n\t}\n\n\treturn CronJobMgr::ShouldStartJob( job );\n}\n\n\/\/ Should we allow a benchmark to run?\nbool\nStartdCronJobMgr::ShouldStartBenchmarks( void ) const\n{\n\tdprintf( D_FULLDEBUG,\n\t\t\t \"ShouldStartBenchmarks: load=%.2f max=%.2f\\n\",\n\t\t\t GetCurJobLoad(), GetMaxJobLoad() );\n\treturn ( GetCurJobLoad() < GetMaxJobLoad() );\n}\n\n\/\/ Job is started\nbool\nStartdCronJobMgr::JobStarted( const CronJob &job )\n{\n\treturn CronJobMgr::JobStarted( job );\n}\n\n\/\/ Job exitted\nbool\nStartdCronJobMgr::JobExited( const CronJob &job )\n{\n\tbool status = CronJobMgr::JobExited( job );\n\tif ( m_shutting_down && IsAllIdle() ) {\n\t\tstartd_check_free();\n\t}\n\tif ( bench_job_mgr ) {\n\t\tbench_job_mgr->ScheduleAllJobs();\n\t}\n\treturn status;\n}\n<commit_msg>Fix minor memory leak in startd cron #6345<commit_after>\/***************************************************************\n *\n * Copyright (C) 1990-2011, Condor Team, Computer Sciences Department,\n * University of Wisconsin-Madison, WI.\n * \n * Licensed under the Apache License, Version 2.0 (the \"License\"); you\n * may not use this file except in compliance with the License. You may\n * obtain a copy of the License at\n * \n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n ***************************************************************\/\n\n\n#include \"condor_common.h\"\n#include \"startd_cron_job_mgr.h\"\n#include \"startd_cron_job.h\"\n#include \"condor_config.h\"\n#include \"startd.h\"\n\n\/\/ Basic constructor\nStartdCronJobMgr::StartdCronJobMgr( void )\n\t\t: CronJobMgr( ),\n\t\t m_shutting_down( false ),\n\t\t m_auto_publish( CAP_NEVER )\n{\n}\n\n\/\/ Basic destructor\nStartdCronJobMgr::~StartdCronJobMgr( void )\n{\n\tdprintf( D_FULLDEBUG, \"StartdCronJobMgr: Bye\\n\" );\n}\n\nint\nStartdCronJobMgr::Initialize( const char *name )\n{\n\tint status;\n\n\tSetName( name, name, \"_cron\" );\n\t\n\tchar *cron_name = param( \"STARTD_CRON_NAME\" );\n\tif ( NULL != cron_name ) {\n\t\tdprintf( D_ALWAYS,\n\t\t\t\t \"WARNING: The use of STARTD_CRON_NAME to 'name' your \"\n\t\t\t\t \"Startd's Daemon ClassAd Hook Manager is not longer supported \"\n\t\t\t\t \"and will be removed in a future release of Condor.\" );\n\t\tname = cron_name;\n\t\tSetName( name, name );\n\t}\n\n\tstatus = CronJobMgr::Initialize( name );\n\tif ( NULL != cron_name ) {\n\t\tfree( cron_name );\n\t}\n\n\tParamAutoPublish( );\n\treturn status;\n}\n\nint\nStartdCronJobMgr::Reconfig( void )\n{\n\tParamAutoPublish();\n\treturn CronJobMgr::HandleReconfig();\n}\n\nvoid\nStartdCronJobMgr::ParamAutoPublish( void )\n{\n\tm_auto_publish = CAP_NEVER; \/\/ always default to never if not set\n\tchar* tmp = param(\"STARTD_CRON_AUTOPUBLISH\");\n\tif( tmp ) {\n\t\tm_auto_publish = getCronAutoPublishNum(tmp);\n\t\tif( m_auto_publish == CAP_ERROR ) {\n\t\t\tdprintf( D_ALWAYS, \"StartdCronJobMgr::Reconfig(): \"\n\t\t\t\t\t \"invalid value for STARTD_CRON_AUTOPUBLISH: \\\"%s\\\" \"\n\t\t\t\t\t \"using default value of NEVER\\n\", tmp );\n\t\t\tm_auto_publish = CAP_NEVER;\n\t\t} else {\n\t\t\tdprintf( D_FULLDEBUG, \"StartdCronJobMgr::Reconfig(): \"\n\t\t\t\t\t \"STARTD_CRON_AUTOPUBLISH set to \\\"%s\\\"\\n\", tmp );\n\t\t}\n\t\tfree( tmp );\n\t\ttmp = NULL;\n\t}\n}\n\n\/\/ Perform shutdown\nint\nStartdCronJobMgr::Shutdown( bool force )\n{\n\tdprintf( D_FULLDEBUG, \"StartdCronJobMgr: Shutting down\\n\" );\n\tm_shutting_down = true;\n\treturn KillAll( force );\n}\n\n\/\/ Check shutdown\nbool\nStartdCronJobMgr::ShutdownOk( void )\n{\n\tbool\tidle = IsAllIdle( );\n\n\t\/\/ dprintf( D_ALWAYS, \"ShutdownOk: %s\\n\", idle ? \"Idle\" : \"Busy\" );\n\treturn idle;\n}\n\nStartdCronJobParams *\nStartdCronJobMgr::CreateJobParams( const char *job_name )\n{\n\treturn new StartdCronJobParams( job_name, *this );\n}\n\nStartdCronJob *\nStartdCronJobMgr::CreateJob( CronJobParams *job_params )\n{\n\tconst char * jobName = job_params->GetName();\n\n\tdprintf( D_FULLDEBUG,\n\t\t\t \"*** Creating Startd Cron job '%s'***\\n\",\n\t\t\t jobName );\n\tStartdCronJobParams *params =\n\t\tdynamic_cast<StartdCronJobParams *>( job_params );\n\tASSERT( params );\n\n\tchar * metricString = params->Lookup( \"METRICS\" );\n\tif( metricString != NULL && metricString[0] != '\\0' ) {\n\t\tStringList pairs( metricString );\n\t\tfor( char * pair = pairs.first(); pair != NULL; pair = pairs.next() ) {\n\t\t\tStringList tn( pair, \":\" );\n\t\t\tchar * metricType = tn.first();\n\t\t\tchar * attributeName = tn.next();\n\t\t\tif(! params->addMetric( metricType, attributeName )) {\n\t\t\t\tdprintf( \tD_ALWAYS, \"Unknown metric type '%s' for attribute \"\n\t\t\t\t\t\t\t\"'%s' in monitor '%s', ignoring.\\n\", metricType,\n\t\t\t\t\t\t\tattributeName, jobName );\n\t\t\t} else {\n\t\t\t\tdprintf(\tD_FULLDEBUG, \"Added %s as %s metric for %s job\\n\",\n\t\t\t\t\t\t\tattributeName, metricType, jobName );\n\t\t\t}\n\t\t}\n\t}\n\tif (metricString) free( metricString );\n\n\treturn new StartdCronJob( params, *this );\n}\n\n\/\/ Should we start a job?\nbool\nStartdCronJobMgr::ShouldStartJob( const CronJob &job ) const\n{\n\tif ( m_shutting_down ) {\n\t\treturn false;\n\t}\n\n\t\/\/ Don't start *any* new jobs during benchmarks\n\tif ( bench_job_mgr && bench_job_mgr->NumActiveBenchmarks() ) {\n\t\treturn false;\n\t}\n\n\treturn CronJobMgr::ShouldStartJob( job );\n}\n\n\/\/ Should we allow a benchmark to run?\nbool\nStartdCronJobMgr::ShouldStartBenchmarks( void ) const\n{\n\tdprintf( D_FULLDEBUG,\n\t\t\t \"ShouldStartBenchmarks: load=%.2f max=%.2f\\n\",\n\t\t\t GetCurJobLoad(), GetMaxJobLoad() );\n\treturn ( GetCurJobLoad() < GetMaxJobLoad() );\n}\n\n\/\/ Job is started\nbool\nStartdCronJobMgr::JobStarted( const CronJob &job )\n{\n\treturn CronJobMgr::JobStarted( job );\n}\n\n\/\/ Job exitted\nbool\nStartdCronJobMgr::JobExited( const CronJob &job )\n{\n\tbool status = CronJobMgr::JobExited( job );\n\tif ( m_shutting_down && IsAllIdle() ) {\n\t\tstartd_check_free();\n\t}\n\tif ( bench_job_mgr ) {\n\t\tbench_job_mgr->ScheduleAllJobs();\n\t}\n\treturn status;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ License: Apache 2.0. See LICENSE file in root directory.\n\/\/ Copyright(c) 2015-2017 Intel Corporation. All Rights Reserved.\n\n#include <librealsense2\/rs.hpp> \/\/ Include RealSense Cross Platform API\n#include \"example.hpp\" \/\/ Include short list of convenience functions for rendering\n\n#include <map>\n#include <vector>\n\nint main(int argc, char * argv[]) try\n{\n \/\/ Create a simple OpenGL window for rendering:\n window app(1280, 960, \"CPP Multi-Camera Example\");\n\n rs2::context ctx; \/\/ Create librealsense context for managing devices\n\n std::map<std::string, rs2::colorizer> colorizers; \/\/ Declare map from device serial number to colorizer (utility class to convert depth data RGB colorspace)\n\n std::vector<rs2::pipeline> pipelines;\n\n \/\/ Start a streaming pipe per each connected device\n for (auto&& dev : ctx.query_devices())\n {\n rs2::pipeline pipe(ctx);\n rs2::config cfg;\n cfg.enable_device(dev.get_info(RS2_CAMERA_INFO_SERIAL_NUMBER));\n pipe.start(cfg);\n pipelines.emplace_back(pipe);\n \/\/ Map from each device's serial number to a different colorizer\n colorizers[dev.get_info(RS2_CAMERA_INFO_SERIAL_NUMBER)] = rs2::colorizer();\n }\n\n \/\/ We'll keep track of the last frame of each stream available to make the presentation persistent\n std::map<int, rs2::frame> render_frames;\n\n \/\/ Main app loop\n while (app)\n {\n \/\/ Collect the new frames from all the connected devices\n std::vector<rs2::frame> new_frames;\n for (auto &&pipe : pipelines)\n {\n rs2::frameset fs;\n if (pipe.poll_for_frames(&fs))\n {\n for (const rs2::frame& f : fs)\n new_frames.emplace_back(f);\n }\n }\n\n \/\/ Convert the newly-arrived frames to render-friendly format\n for (const auto& frame : new_frames)\n {\n \/\/ Get the serial number of the current frame's device\n auto serial = rs2::sensor_from_frame(frame)->get_info(RS2_CAMERA_INFO_SERIAL_NUMBER);\n \/\/ Apply the colorizer of the matching device and store the colorized frame\n render_frames[frame.get_profile().unique_id()] = colorizers[serial].process(frame);\n }\n\n \/\/ Present all the collected frames with openGl mosaic\n app.show(render_frames);\n }\n\n return EXIT_SUCCESS;\n}\ncatch (const rs2::error & e)\n{\n std::cerr << \"RealSense error calling \" << e.get_failed_function() << \"(\" << e.get_failed_args() << \"):\\n \" << e.what() << std::endl;\n return EXIT_FAILURE;\n}\ncatch (const std::exception & e)\n{\n std::cerr << e.what() << std::endl;\n return EXIT_FAILURE;\n}\n<commit_msg>Fix rs-multicam with T265<commit_after>\/\/ License: Apache 2.0. See LICENSE file in root directory.\n\/\/ Copyright(c) 2015-2017 Intel Corporation. All Rights Reserved.\n\n#include <librealsense2\/rs.hpp> \/\/ Include RealSense Cross Platform API\n#include \"example.hpp\" \/\/ Include short list of convenience functions for rendering\n\n#include <map>\n#include <vector>\n\nint main(int argc, char * argv[]) try\n{\n \/\/ Create a simple OpenGL window for rendering:\n window app(1280, 960, \"CPP Multi-Camera Example\");\n\n rs2::context ctx; \/\/ Create librealsense context for managing devices\n\n std::map<std::string, rs2::colorizer> colorizers; \/\/ Declare map from device serial number to colorizer (utility class to convert depth data RGB colorspace)\n\n std::vector<rs2::pipeline> pipelines;\n\n \/\/ Capture serial numbers before opening streaming\n std::vector<std::string> serials;\n for (auto&& dev : ctx.query_devices())\n serials.push_back(dev.get_info(RS2_CAMERA_INFO_SERIAL_NUMBER));\n\n \/\/ Start a streaming pipe per each connected device\n for (auto&& serial : serials)\n {\n rs2::pipeline pipe(ctx);\n rs2::config cfg;\n cfg.enable_device(serial);\n pipe.start(cfg);\n pipelines.emplace_back(pipe);\n \/\/ Map from each device's serial number to a different colorizer\n colorizers[serial] = rs2::colorizer();\n }\n\n \/\/ We'll keep track of the last frame of each stream available to make the presentation persistent\n std::map<int, rs2::frame> render_frames;\n\n \/\/ Main app loop\n while (app)\n {\n \/\/ Collect the new frames from all the connected devices\n std::vector<rs2::frame> new_frames;\n for (auto &&pipe : pipelines)\n {\n rs2::frameset fs;\n if (pipe.poll_for_frames(&fs))\n {\n for (const rs2::frame& f : fs)\n new_frames.emplace_back(f);\n }\n }\n\n \/\/ Convert the newly-arrived frames to render-friendly format\n for (const auto& frame : new_frames)\n {\n \/\/ Get the serial number of the current frame's device\n auto serial = rs2::sensor_from_frame(frame)->get_info(RS2_CAMERA_INFO_SERIAL_NUMBER);\n \/\/ Apply the colorizer of the matching device and store the colorized frame\n render_frames[frame.get_profile().unique_id()] = colorizers[serial].process(frame);\n }\n\n \/\/ Present all the collected frames with openGl mosaic\n app.show(render_frames);\n }\n\n return EXIT_SUCCESS;\n}\ncatch (const rs2::error & e)\n{\n std::cerr << \"RealSense error calling \" << e.get_failed_function() << \"(\" << e.get_failed_args() << \"):\\n \" << e.what() << std::endl;\n return EXIT_FAILURE;\n}\ncatch (const std::exception & e)\n{\n std::cerr << e.what() << std::endl;\n return EXIT_FAILURE;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"vfreebusy.h\"\n\nnamespace ical {\nnamespace components {\n\nconst std::string VFreeBusy::NAME = \"VFREEBUSY\";\n\nvoid VFreeBusy::print(std::ostream &out) const {\n\n}\n\nVFreeBusy VFreeBusy::parse(const core::WithPos<core::GenericComponent> &generic,\n core::UniqueIdRegistry &uidRegistry)\n{\n return {};\n}\n\n\n} \/\/ namespace components\n} \/\/ namespace ical\n\n<commit_msg>basic freebusy component parsing<commit_after>#include \"vfreebusy.h\"\n\nnamespace ical {\nnamespace components {\n\nconst std::string VFreeBusy::NAME = \"VFREEBUSY\";\n\nvoid VFreeBusy::print(std::ostream &out) const {\n out << \"BEGIN:\" << NAME << \"\\r\\n\";\n for(auto &i : dtStampProp) i.print(out);\n for(auto &i : uidProp) i.print(out);\n for(auto &i : contactProp) i.print(out);\n for(auto &i : dtStartProp) i.print(out);\n for(auto &i : dtendProp) i.print(out);\n for(auto &i : organizerProp) i.print(out);\n for(auto &i : urlProp) i.print(out);\n for(auto &i : attendeeProps) i.print(out);\n for(auto &i : commentProps) i.print(out);\n for(auto &i : freebusyProps) i.print(out);\n out << \"END:\" << NAME << \"\\r\\n\";\n}\n\nVFreeBusy VFreeBusy::parse(const core::WithPos<core::GenericComponent> &generic,\n core::UniqueIdRegistry &uidRegistry)\n{\n if(generic->getName().value() != NAME)\n throw ParserException(generic.pos() , \"invalid name in \" + NAME + \" component\");\n\n VFreeBusy freebusy;\n\n \/* Storing properties *\/\n for(const core::WithPos<core::GenericProperty> &i : generic->getProperties()) {\n if(i->getName().value() == properties::DTStamp::NAME) {\n freebusy.dtStampProp.push_back(properties::DTStamp::parse(i));\n } else if(i->getName().value() == properties::Uid::NAME) {\n freebusy.uidProp.push_back(properties::Uid::parse(i));\n } else if(i->getName().value() == properties::Contact::NAME) {\n freebusy.contactProp.push_back(properties::Contact::parse(i));\n } else if(i->getName().value() == properties::DTStart::NAME) {\n freebusy.dtStartProp.push_back(properties::DTStart::parse(i));\n } else if(i->getName().value() == properties::DTEnd::NAME) {\n freebusy.dtendProp.push_back(properties::DTEnd::parse(i));\n } else if(i->getName().value() == properties::Organizer::NAME) {\n freebusy.organizerProp.push_back(properties::Organizer::parse(i));\n } else if(i->getName().value() == properties::Url::NAME) {\n freebusy.urlProp.push_back(properties::Url::parse(i));\n } else if(i->getName().value() == properties::Attendee::NAME) {\n freebusy.attendeeProps.push_back(properties::Attendee::parse(i));\n } else if(i->getName().value() == properties::Comment::NAME) {\n freebusy.commentProps.push_back(properties::Comment::parse(i));\n } else if(i->getName().value() == properties::Freebusy::NAME) {\n freebusy.freebusyProps.push_back(properties::Freebusy::parse(i));\n } else {\n throw ParserException(i.pos() , \"invalid property in \" + NAME + \" component\");\n }\n }\n\n \/** Properties sanity checking **\/\n \/* Required properties check *\/\n if(freebusy.dtStampProp.size() != 1)\n throw ParserException(generic.pos() , properties::DTStamp::NAME + \" is required once in \" + NAME + \" component\");\n if(freebusy.uidProp.size() != 1)\n throw ParserException(generic.pos() , properties::Uid::NAME + \" is required once in \" + NAME + \" component\");\n \/* OPTIONAL properties max ONCE check *\/\n if(freebusy.contactProp.size() > 1)\n throw ParserException(generic.pos() , properties::Contact::NAME + \" property can't occurr multiple times\");\n if(freebusy.dtStartProp.size() > 1)\n throw ParserException(generic.pos() , properties::DTStart::NAME + \" property can't occurr multiple times\");\n if(freebusy.dtendProp.size() > 1)\n throw ParserException(generic.pos() , properties::DTEnd::NAME + \" property can't occurr multiple times\");\n if(freebusy.organizerProp.size() > 1)\n throw ParserException(generic.pos() , properties::Organizer::NAME + \" property can't occurr multiple times\");\n if(freebusy.urlProp.size() > 1)\n throw ParserException(generic.pos() , properties::Url::NAME + \" property can't occurr multiple times\");\n\n if (!uidRegistry.registerId(freebusy.uidProp[0].getValue())) {\n throw ParserException(generic.pos() , \"The value of the \" + properties::Uid::NAME + \" property must be globally unique\");\n }\n\n return freebusy;\n\n}\n\n\n} \/\/ namespace components\n} \/\/ namespace ical\n\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\r\n#define STB_IMAGE_WRITE_IMPLEMENTATION\r\n#include \"stb_image_write.h\"\r\n#include \"vec3.h\"\r\n#include \"ray.h\"\r\n\r\nusing namespace std;\r\n\r\n\/\/ I need to grok this. I have no idea what it does.\r\nvec3 color(const ray& r) {\r\n vec3 unit_direction = unit_vector(r.direction());\r\n \/\/ Scale the unit vector down such that 1.0 = BLue, and 0.0 = White\r\n \/\/ Originaly such that -1.0 = White and 1.0 = Blue\r\n float t = 0.5*(unit_direction.y + 1.0);\r\n return (1.0f-t)*vec3(1.0, 1.0, 1.0) + t*vec3(0.5, 0.7, 1.0);\r\n}\r\n\r\nint main(int argc, char** argv) {\r\n if (argc != 2) {\r\n cout << \"Incorrect number of arguments\\nUsage: run.out output_file.png\" << endl;\r\n return 1;\r\n }\r\n\r\n const unsigned int width = 200;\r\n const unsigned int height = 100;\r\n const unsigned char channels = 3;\r\n unsigned int index;\r\n\r\n unsigned char* data = new unsigned char[width * height * channels];\r\n\r\n \/*\r\n * Because I'm going from top to bottom, left to right, I am using the\r\n * following screen schema.\r\n * ------------------------------\r\n * |-2, -1, -1 2, -1, -1 |\r\n * | |\r\n * | 0, 0, 0 |\r\n * | |\r\n * |-2, 1, -1 2, 1, -1 |\r\n * ------------------------------\r\n *\/\r\n\r\n vec3 lower_left_corner(-2.0, 1.0, -1.0);\r\n vec3 horizontal(4.0, 0.0, 0.0);\r\n vec3 vertical(0.0, -2.0, 0.0);\r\n vec3 origin(0.0, 0.0, 0.0);\r\n\r\n for (unsigned int y = 0; y < height; y++) {\r\n for (unsigned int x = 0; x < width; x++) {\r\n\r\n index = (y * width * channels) + (x * channels);\r\n\r\n float u = (float) x \/ (float) width;\r\n float v = (float) y \/ (float) height;\r\n \r\n ray r(origin, lower_left_corner + u * horizontal + v * vertical);\r\n vec3 col = color(r);\r\n\r\n data[index] = col.x * 255; \/\/ Red channel\r\n data[index + 1] = col.y * 255; \/\/ Green channel\r\n data[index + 2] = col.z * 255; \/\/ Blue channel\r\n }\r\n }\r\n\r\n stbi_write_png(argv[1], width, height, channels, data, width * channels);\r\n\r\n delete[] data;\r\n\r\n return 0;\r\n}\r\n<commit_msg>Updated to use bottom left as origin. This will make calculations for the rest of the book easier<commit_after>#include <iostream>\r\n#define STB_IMAGE_WRITE_IMPLEMENTATION\r\n#include \"stb_image_write.h\"\r\n#include \"vec3.h\"\r\n#include \"ray.h\"\r\n\r\nusing namespace std;\r\n\r\n\/\/ I need to grok this. I have no idea what it does.\r\nvec3 color(const ray& r) {\r\n vec3 unit_direction = unit_vector(r.direction());\r\n \/\/ Scale the unit vector down such that 1.0 = BLue, and 0.0 = White\r\n \/\/ Originaly such that -1.0 = White and 1.0 = Blue\r\n float t = 0.5*(unit_direction.y + 1.0);\r\n return (1.0f-t)*vec3(1.0, 1.0, 1.0) + t*vec3(0.5, 0.7, 1.0);\r\n}\r\n\r\nint main(int argc, char** argv) {\r\n if (argc != 2) {\r\n cout << \"Incorrect number of arguments\\nUsage: run.out output_file.png\" << endl;\r\n return 1;\r\n }\r\n\r\n const int width = 200;\r\n const int height = 100;\r\n const unsigned char channels = 3;\r\n int index;\r\n\r\n unsigned char* data = new unsigned char[width * height * channels];\r\n\r\n vec3 lower_left_corner(-2.0, -1.0, -1.0);\r\n vec3 horizontal(4.0, 0.0, 0.0);\r\n vec3 vertical(0.0, 2.0, 0.0);\r\n vec3 origin(0.0, 0.0, 0.0);\r\n\r\n for (int y = height - 1; y >= 0; y--) {\r\n for (int x = 0; x < width; x++) {\r\n\r\n \/\/ Calculate the index using top left as origin\r\n index = (y * width * channels) + (x * channels);\r\n \/\/ Flip it to use bottom left as origin\r\n index = (width * height * channels) - index;\r\n\r\n float u = (float) x \/ (float) width;\r\n float v = (float) y \/ (float) height;\r\n \r\n ray r(origin, lower_left_corner + u * horizontal + v * vertical);\r\n vec3 col = color(r);\r\n\r\n data[index] = col.x * 255; \/\/ Red channel\r\n data[index + 1] = col.y * 255; \/\/ Green channel\r\n data[index + 2] = col.z * 255; \/\/ Blue channel\r\n }\r\n }\r\n\r\n stbi_write_png(argv[1], width, height, channels, data, width * channels);\r\n\r\n delete[] data;\r\n\r\n return 0;\r\n}\r\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2016 PDFium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"public\/fpdf_doc.h\"\n\n#include <memory>\n#include <vector>\n\n#include \"core\/fpdfapi\/fpdf_parser\/include\/cpdf_document.h\"\n#include \"core\/fpdfapi\/fpdf_parser\/include\/cpdf_name.h\"\n#include \"core\/fpdfapi\/fpdf_parser\/include\/cpdf_number.h\"\n#include \"core\/fpdfapi\/fpdf_parser\/include\/cpdf_reference.h\"\n#include \"core\/fpdfapi\/fpdf_parser\/include\/cpdf_string.h\"\n#include \"core\/fpdfapi\/include\/cpdf_modulemgr.h\"\n#include \"core\/fpdfdoc\/include\/fpdf_doc.h\"\n#include \"testing\/gtest\/include\/gtest\/gtest.h\"\n#include \"testing\/test_support.h\"\n\n#ifdef PDF_ENABLE_XFA\n#include \"fpdfsdk\/fpdfxfa\/include\/fpdfxfa_app.h\"\n#include \"fpdfsdk\/fpdfxfa\/include\/fpdfxfa_doc.h\"\n#endif \/\/ PDF_ENABLE_XFA\n\nclass CPDF_TestDocument : public CPDF_Document {\n public:\n CPDF_TestDocument() : CPDF_Document(nullptr) {}\n\n void SetRoot(CPDF_Dictionary* root) { m_pRootDict = root; }\n CPDF_IndirectObjectHolder* GetHolder() { return this; }\n};\n\n#ifdef PDF_ENABLE_XFA\nclass CPDF_TestXFADocument : public CPDFXFA_Document {\n public:\n CPDF_TestXFADocument()\n : CPDFXFA_Document(new CPDF_TestDocument(), CPDFXFA_App::GetInstance()) {}\n\n void SetRoot(CPDF_Dictionary* root) {\n reinterpret_cast<CPDF_TestDocument*>(GetPDFDoc())->SetRoot(root);\n }\n\n CPDF_IndirectObjectHolder* GetHolder() { return GetPDFDoc(); }\n};\nusing CPDF_TestPdfDocument = CPDF_TestXFADocument;\n#else \/\/ PDF_ENABLE_XFA\nusing CPDF_TestPdfDocument = CPDF_TestDocument;\n#endif \/\/ PDF_ENABLE_XFA\n\nclass PDFDocTest : public testing::Test {\n public:\n struct DictObjInfo {\n uint32_t num;\n CPDF_Dictionary* obj;\n };\n\n void SetUp() override {\n \/\/ We don't need page module or render module, but\n \/\/ initialize them to keep the code sane.\n CPDF_ModuleMgr::Create();\n CPDF_ModuleMgr* module_mgr = CPDF_ModuleMgr::Get();\n module_mgr->InitPageModule();\n\n m_pDoc.reset(new CPDF_TestPdfDocument());\n m_pIndirectObjs = m_pDoc->GetHolder();\n \/\/ Setup the root directory.\n m_pRootObj.reset(new CPDF_Dictionary());\n m_pDoc->SetRoot(m_pRootObj.get());\n }\n\n std::vector<DictObjInfo> CreateDictObjs(int num) {\n std::vector<DictObjInfo> info;\n for (int i = 0; i < num; ++i) {\n \/\/ Objects created will be released by the document.\n CPDF_Dictionary* obj(new CPDF_Dictionary());\n m_pIndirectObjs->AddIndirectObject(obj);\n info.push_back({obj->GetObjNum(), obj});\n }\n return info;\n }\n\n protected:\n std::unique_ptr<CPDF_TestPdfDocument> m_pDoc;\n CPDF_IndirectObjectHolder* m_pIndirectObjs;\n std::unique_ptr<CPDF_Dictionary, ReleaseDeleter<CPDF_Dictionary>> m_pRootObj;\n};\n\nTEST_F(PDFDocTest, FindBookmark) {\n {\n \/\/ No bookmark information.\n std::unique_ptr<unsigned short, pdfium::FreeDeleter> title =\n GetFPDFWideString(L\"\");\n EXPECT_EQ(nullptr, FPDFBookmark_Find(m_pDoc.get(), title.get()));\n\n title = GetFPDFWideString(L\"Preface\");\n EXPECT_EQ(nullptr, FPDFBookmark_Find(m_pDoc.get(), title.get()));\n }\n {\n \/\/ Empty bookmark tree.\n m_pRootObj->SetAt(\"Outlines\", new CPDF_Dictionary());\n std::unique_ptr<unsigned short, pdfium::FreeDeleter> title =\n GetFPDFWideString(L\"\");\n EXPECT_EQ(nullptr, FPDFBookmark_Find(m_pDoc.get(), title.get()));\n\n title = GetFPDFWideString(L\"Preface\");\n EXPECT_EQ(nullptr, FPDFBookmark_Find(m_pDoc.get(), title.get()));\n }\n {\n \/\/ Check on a regular bookmark tree.\n auto bookmarks = CreateDictObjs(3);\n\n bookmarks[1].obj->SetAt(\"Title\", new CPDF_String(L\"Chapter 1\"));\n bookmarks[1].obj->SetAt(\n \"Parent\", new CPDF_Reference(m_pIndirectObjs, bookmarks[0].num));\n bookmarks[1].obj->SetAt(\n \"Next\", new CPDF_Reference(m_pIndirectObjs, bookmarks[2].num));\n\n bookmarks[2].obj->SetAt(\"Title\", new CPDF_String(L\"Chapter 2\"));\n bookmarks[2].obj->SetAt(\n \"Parent\", new CPDF_Reference(m_pIndirectObjs, bookmarks[0].num));\n bookmarks[2].obj->SetAt(\n \"Prev\", new CPDF_Reference(m_pIndirectObjs, bookmarks[1].num));\n\n bookmarks[0].obj->SetAt(\"Type\", new CPDF_Name(\"Outlines\"));\n bookmarks[0].obj->SetAt(\"Count\", new CPDF_Number(2));\n bookmarks[0].obj->SetAt(\n \"First\", new CPDF_Reference(m_pIndirectObjs, bookmarks[1].num));\n bookmarks[0].obj->SetAt(\n \"Last\", new CPDF_Reference(m_pIndirectObjs, bookmarks[2].num));\n\n m_pRootObj->SetAt(\"Outlines\",\n new CPDF_Reference(m_pIndirectObjs, bookmarks[0].num));\n\n \/\/ Title with no match.\n std::unique_ptr<unsigned short, pdfium::FreeDeleter> title =\n GetFPDFWideString(L\"Chapter 3\");\n EXPECT_EQ(nullptr, FPDFBookmark_Find(m_pDoc.get(), title.get()));\n\n \/\/ Title with partial match only.\n title = GetFPDFWideString(L\"Chapter\");\n EXPECT_EQ(nullptr, FPDFBookmark_Find(m_pDoc.get(), title.get()));\n\n \/\/ Title with a match.\n title = GetFPDFWideString(L\"Chapter 2\");\n EXPECT_EQ(bookmarks[2].obj, FPDFBookmark_Find(m_pDoc.get(), title.get()));\n\n \/\/ Title match is case insensitive.\n title = GetFPDFWideString(L\"cHaPter 2\");\n EXPECT_EQ(bookmarks[2].obj, FPDFBookmark_Find(m_pDoc.get(), title.get()));\n }\n {\n \/\/ Circular bookmarks in depth.\n auto bookmarks = CreateDictObjs(3);\n\n bookmarks[1].obj->SetAt(\"Title\", new CPDF_String(L\"Chapter 1\"));\n bookmarks[1].obj->SetAt(\n \"Parent\", new CPDF_Reference(m_pIndirectObjs, bookmarks[0].num));\n bookmarks[1].obj->SetAt(\n \"First\", new CPDF_Reference(m_pIndirectObjs, bookmarks[2].num));\n\n bookmarks[2].obj->SetAt(\"Title\", new CPDF_String(L\"Chapter 2\"));\n bookmarks[2].obj->SetAt(\n \"Parent\", new CPDF_Reference(m_pIndirectObjs, bookmarks[1].num));\n bookmarks[2].obj->SetAt(\n \"First\", new CPDF_Reference(m_pIndirectObjs, bookmarks[1].num));\n\n bookmarks[0].obj->SetAt(\"Type\", new CPDF_Name(\"Outlines\"));\n bookmarks[0].obj->SetAt(\"Count\", new CPDF_Number(2));\n bookmarks[0].obj->SetAt(\n \"First\", new CPDF_Reference(m_pIndirectObjs, bookmarks[1].num));\n bookmarks[0].obj->SetAt(\n \"Last\", new CPDF_Reference(m_pIndirectObjs, bookmarks[2].num));\n\n m_pRootObj->SetAt(\"Outlines\",\n new CPDF_Reference(m_pIndirectObjs, bookmarks[0].num));\n\n \/\/ Title with no match.\n std::unique_ptr<unsigned short, pdfium::FreeDeleter> title =\n GetFPDFWideString(L\"Chapter 3\");\n EXPECT_EQ(nullptr, FPDFBookmark_Find(m_pDoc.get(), title.get()));\n\n \/\/ Title with a match.\n title = GetFPDFWideString(L\"Chapter 2\");\n EXPECT_EQ(bookmarks[2].obj, FPDFBookmark_Find(m_pDoc.get(), title.get()));\n }\n {\n \/\/ Circular bookmarks in breadth.\n auto bookmarks = CreateDictObjs(4);\n\n bookmarks[1].obj->SetAt(\"Title\", new CPDF_String(L\"Chapter 1\"));\n bookmarks[1].obj->SetAt(\n \"Parent\", new CPDF_Reference(m_pIndirectObjs, bookmarks[0].num));\n bookmarks[1].obj->SetAt(\n \"Next\", new CPDF_Reference(m_pIndirectObjs, bookmarks[2].num));\n\n bookmarks[2].obj->SetAt(\"Title\", new CPDF_String(L\"Chapter 2\"));\n bookmarks[2].obj->SetAt(\n \"Parent\", new CPDF_Reference(m_pIndirectObjs, bookmarks[0].num));\n bookmarks[2].obj->SetAt(\n \"Next\", new CPDF_Reference(m_pIndirectObjs, bookmarks[3].num));\n\n bookmarks[3].obj->SetAt(\"Title\", new CPDF_String(L\"Chapter 3\"));\n bookmarks[3].obj->SetAt(\n \"Parent\", new CPDF_Reference(m_pIndirectObjs, bookmarks[0].num));\n bookmarks[3].obj->SetAt(\n \"Next\", new CPDF_Reference(m_pIndirectObjs, bookmarks[1].num));\n\n bookmarks[0].obj->SetAt(\"Type\", new CPDF_Name(\"Outlines\"));\n bookmarks[0].obj->SetAt(\"Count\", new CPDF_Number(2));\n bookmarks[0].obj->SetAt(\n \"First\", new CPDF_Reference(m_pIndirectObjs, bookmarks[1].num));\n bookmarks[0].obj->SetAt(\n \"Last\", new CPDF_Reference(m_pIndirectObjs, bookmarks[2].num));\n\n m_pRootObj->SetAt(\"Outlines\",\n new CPDF_Reference(m_pIndirectObjs, bookmarks[0].num));\n\n \/\/ Title with no match.\n std::unique_ptr<unsigned short, pdfium::FreeDeleter> title =\n GetFPDFWideString(L\"Chapter 8\");\n EXPECT_EQ(nullptr, FPDFBookmark_Find(m_pDoc.get(), title.get()));\n\n \/\/ Title with a match.\n title = GetFPDFWideString(L\"Chapter 3\");\n EXPECT_EQ(bookmarks[3].obj, FPDFBookmark_Find(m_pDoc.get(), title.get()));\n }\n}\n<commit_msg>PDFDocTest should TearDown() properly.<commit_after>\/\/ Copyright 2016 PDFium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"public\/fpdf_doc.h\"\n\n#include <memory>\n#include <vector>\n\n#include \"core\/fpdfapi\/fpdf_parser\/include\/cpdf_document.h\"\n#include \"core\/fpdfapi\/fpdf_parser\/include\/cpdf_name.h\"\n#include \"core\/fpdfapi\/fpdf_parser\/include\/cpdf_number.h\"\n#include \"core\/fpdfapi\/fpdf_parser\/include\/cpdf_reference.h\"\n#include \"core\/fpdfapi\/fpdf_parser\/include\/cpdf_string.h\"\n#include \"core\/fpdfapi\/include\/cpdf_modulemgr.h\"\n#include \"core\/fpdfdoc\/include\/fpdf_doc.h\"\n#include \"testing\/gtest\/include\/gtest\/gtest.h\"\n#include \"testing\/test_support.h\"\n\n#ifdef PDF_ENABLE_XFA\n#include \"fpdfsdk\/fpdfxfa\/include\/fpdfxfa_app.h\"\n#include \"fpdfsdk\/fpdfxfa\/include\/fpdfxfa_doc.h\"\n#endif \/\/ PDF_ENABLE_XFA\n\nclass CPDF_TestDocument : public CPDF_Document {\n public:\n CPDF_TestDocument() : CPDF_Document(nullptr) {}\n\n void SetRoot(CPDF_Dictionary* root) { m_pRootDict = root; }\n CPDF_IndirectObjectHolder* GetHolder() { return this; }\n};\n\n#ifdef PDF_ENABLE_XFA\nclass CPDF_TestXFADocument : public CPDFXFA_Document {\n public:\n CPDF_TestXFADocument()\n : CPDFXFA_Document(new CPDF_TestDocument(), CPDFXFA_App::GetInstance()) {}\n\n void SetRoot(CPDF_Dictionary* root) {\n reinterpret_cast<CPDF_TestDocument*>(GetPDFDoc())->SetRoot(root);\n }\n\n CPDF_IndirectObjectHolder* GetHolder() { return GetPDFDoc(); }\n};\nusing CPDF_TestPdfDocument = CPDF_TestXFADocument;\n#else \/\/ PDF_ENABLE_XFA\nusing CPDF_TestPdfDocument = CPDF_TestDocument;\n#endif \/\/ PDF_ENABLE_XFA\n\nclass PDFDocTest : public testing::Test {\n public:\n struct DictObjInfo {\n uint32_t num;\n CPDF_Dictionary* obj;\n };\n\n void SetUp() override {\n \/\/ We don't need page module or render module, but\n \/\/ initialize them to keep the code sane.\n CPDF_ModuleMgr::Create();\n CPDF_ModuleMgr* module_mgr = CPDF_ModuleMgr::Get();\n module_mgr->InitPageModule();\n\n m_pDoc.reset(new CPDF_TestPdfDocument());\n m_pIndirectObjs = m_pDoc->GetHolder();\n \/\/ Setup the root directory.\n m_pRootObj.reset(new CPDF_Dictionary());\n m_pDoc->SetRoot(m_pRootObj.get());\n }\n\n void TearDown() override {\n m_pRootObj.reset();\n m_pIndirectObjs = nullptr;\n m_pDoc.reset();\n CPDF_ModuleMgr::Destroy();\n }\n\n std::vector<DictObjInfo> CreateDictObjs(int num) {\n std::vector<DictObjInfo> info;\n for (int i = 0; i < num; ++i) {\n \/\/ Objects created will be released by the document.\n CPDF_Dictionary* obj(new CPDF_Dictionary());\n m_pIndirectObjs->AddIndirectObject(obj);\n info.push_back({obj->GetObjNum(), obj});\n }\n return info;\n }\n\n protected:\n std::unique_ptr<CPDF_TestPdfDocument> m_pDoc;\n CPDF_IndirectObjectHolder* m_pIndirectObjs;\n std::unique_ptr<CPDF_Dictionary, ReleaseDeleter<CPDF_Dictionary>> m_pRootObj;\n};\n\nTEST_F(PDFDocTest, FindBookmark) {\n {\n \/\/ No bookmark information.\n std::unique_ptr<unsigned short, pdfium::FreeDeleter> title =\n GetFPDFWideString(L\"\");\n EXPECT_EQ(nullptr, FPDFBookmark_Find(m_pDoc.get(), title.get()));\n\n title = GetFPDFWideString(L\"Preface\");\n EXPECT_EQ(nullptr, FPDFBookmark_Find(m_pDoc.get(), title.get()));\n }\n {\n \/\/ Empty bookmark tree.\n m_pRootObj->SetAt(\"Outlines\", new CPDF_Dictionary());\n std::unique_ptr<unsigned short, pdfium::FreeDeleter> title =\n GetFPDFWideString(L\"\");\n EXPECT_EQ(nullptr, FPDFBookmark_Find(m_pDoc.get(), title.get()));\n\n title = GetFPDFWideString(L\"Preface\");\n EXPECT_EQ(nullptr, FPDFBookmark_Find(m_pDoc.get(), title.get()));\n }\n {\n \/\/ Check on a regular bookmark tree.\n auto bookmarks = CreateDictObjs(3);\n\n bookmarks[1].obj->SetAt(\"Title\", new CPDF_String(L\"Chapter 1\"));\n bookmarks[1].obj->SetAt(\n \"Parent\", new CPDF_Reference(m_pIndirectObjs, bookmarks[0].num));\n bookmarks[1].obj->SetAt(\n \"Next\", new CPDF_Reference(m_pIndirectObjs, bookmarks[2].num));\n\n bookmarks[2].obj->SetAt(\"Title\", new CPDF_String(L\"Chapter 2\"));\n bookmarks[2].obj->SetAt(\n \"Parent\", new CPDF_Reference(m_pIndirectObjs, bookmarks[0].num));\n bookmarks[2].obj->SetAt(\n \"Prev\", new CPDF_Reference(m_pIndirectObjs, bookmarks[1].num));\n\n bookmarks[0].obj->SetAt(\"Type\", new CPDF_Name(\"Outlines\"));\n bookmarks[0].obj->SetAt(\"Count\", new CPDF_Number(2));\n bookmarks[0].obj->SetAt(\n \"First\", new CPDF_Reference(m_pIndirectObjs, bookmarks[1].num));\n bookmarks[0].obj->SetAt(\n \"Last\", new CPDF_Reference(m_pIndirectObjs, bookmarks[2].num));\n\n m_pRootObj->SetAt(\"Outlines\",\n new CPDF_Reference(m_pIndirectObjs, bookmarks[0].num));\n\n \/\/ Title with no match.\n std::unique_ptr<unsigned short, pdfium::FreeDeleter> title =\n GetFPDFWideString(L\"Chapter 3\");\n EXPECT_EQ(nullptr, FPDFBookmark_Find(m_pDoc.get(), title.get()));\n\n \/\/ Title with partial match only.\n title = GetFPDFWideString(L\"Chapter\");\n EXPECT_EQ(nullptr, FPDFBookmark_Find(m_pDoc.get(), title.get()));\n\n \/\/ Title with a match.\n title = GetFPDFWideString(L\"Chapter 2\");\n EXPECT_EQ(bookmarks[2].obj, FPDFBookmark_Find(m_pDoc.get(), title.get()));\n\n \/\/ Title match is case insensitive.\n title = GetFPDFWideString(L\"cHaPter 2\");\n EXPECT_EQ(bookmarks[2].obj, FPDFBookmark_Find(m_pDoc.get(), title.get()));\n }\n {\n \/\/ Circular bookmarks in depth.\n auto bookmarks = CreateDictObjs(3);\n\n bookmarks[1].obj->SetAt(\"Title\", new CPDF_String(L\"Chapter 1\"));\n bookmarks[1].obj->SetAt(\n \"Parent\", new CPDF_Reference(m_pIndirectObjs, bookmarks[0].num));\n bookmarks[1].obj->SetAt(\n \"First\", new CPDF_Reference(m_pIndirectObjs, bookmarks[2].num));\n\n bookmarks[2].obj->SetAt(\"Title\", new CPDF_String(L\"Chapter 2\"));\n bookmarks[2].obj->SetAt(\n \"Parent\", new CPDF_Reference(m_pIndirectObjs, bookmarks[1].num));\n bookmarks[2].obj->SetAt(\n \"First\", new CPDF_Reference(m_pIndirectObjs, bookmarks[1].num));\n\n bookmarks[0].obj->SetAt(\"Type\", new CPDF_Name(\"Outlines\"));\n bookmarks[0].obj->SetAt(\"Count\", new CPDF_Number(2));\n bookmarks[0].obj->SetAt(\n \"First\", new CPDF_Reference(m_pIndirectObjs, bookmarks[1].num));\n bookmarks[0].obj->SetAt(\n \"Last\", new CPDF_Reference(m_pIndirectObjs, bookmarks[2].num));\n\n m_pRootObj->SetAt(\"Outlines\",\n new CPDF_Reference(m_pIndirectObjs, bookmarks[0].num));\n\n \/\/ Title with no match.\n std::unique_ptr<unsigned short, pdfium::FreeDeleter> title =\n GetFPDFWideString(L\"Chapter 3\");\n EXPECT_EQ(nullptr, FPDFBookmark_Find(m_pDoc.get(), title.get()));\n\n \/\/ Title with a match.\n title = GetFPDFWideString(L\"Chapter 2\");\n EXPECT_EQ(bookmarks[2].obj, FPDFBookmark_Find(m_pDoc.get(), title.get()));\n }\n {\n \/\/ Circular bookmarks in breadth.\n auto bookmarks = CreateDictObjs(4);\n\n bookmarks[1].obj->SetAt(\"Title\", new CPDF_String(L\"Chapter 1\"));\n bookmarks[1].obj->SetAt(\n \"Parent\", new CPDF_Reference(m_pIndirectObjs, bookmarks[0].num));\n bookmarks[1].obj->SetAt(\n \"Next\", new CPDF_Reference(m_pIndirectObjs, bookmarks[2].num));\n\n bookmarks[2].obj->SetAt(\"Title\", new CPDF_String(L\"Chapter 2\"));\n bookmarks[2].obj->SetAt(\n \"Parent\", new CPDF_Reference(m_pIndirectObjs, bookmarks[0].num));\n bookmarks[2].obj->SetAt(\n \"Next\", new CPDF_Reference(m_pIndirectObjs, bookmarks[3].num));\n\n bookmarks[3].obj->SetAt(\"Title\", new CPDF_String(L\"Chapter 3\"));\n bookmarks[3].obj->SetAt(\n \"Parent\", new CPDF_Reference(m_pIndirectObjs, bookmarks[0].num));\n bookmarks[3].obj->SetAt(\n \"Next\", new CPDF_Reference(m_pIndirectObjs, bookmarks[1].num));\n\n bookmarks[0].obj->SetAt(\"Type\", new CPDF_Name(\"Outlines\"));\n bookmarks[0].obj->SetAt(\"Count\", new CPDF_Number(2));\n bookmarks[0].obj->SetAt(\n \"First\", new CPDF_Reference(m_pIndirectObjs, bookmarks[1].num));\n bookmarks[0].obj->SetAt(\n \"Last\", new CPDF_Reference(m_pIndirectObjs, bookmarks[2].num));\n\n m_pRootObj->SetAt(\"Outlines\",\n new CPDF_Reference(m_pIndirectObjs, bookmarks[0].num));\n\n \/\/ Title with no match.\n std::unique_ptr<unsigned short, pdfium::FreeDeleter> title =\n GetFPDFWideString(L\"Chapter 8\");\n EXPECT_EQ(nullptr, FPDFBookmark_Find(m_pDoc.get(), title.get()));\n\n \/\/ Title with a match.\n title = GetFPDFWideString(L\"Chapter 3\");\n EXPECT_EQ(bookmarks[3].obj, FPDFBookmark_Find(m_pDoc.get(), title.get()));\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n For more information, please see: http:\/\/software.sci.utah.edu\n\n The MIT License\n\n Copyright (c) 2020 Scientific Computing and Imaging Institute,\n University of Utah.\n\n Permission is hereby granted, free of charge, to any person obtaining a\n copy of this software and associated documentation files (the \"Software\"),\n to deal in the Software without restriction, including without limitation\n the rights to use, copy, modify, merge, publish, distribute, sublicense,\n and\/or sell copies of the Software, and to permit persons to whom the\n Software is furnished to do so, subject to the following conditions:\n\n The above copyright notice and this permission notice shall be included\n in all copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n DEALINGS IN THE SOFTWARE.\n*\/\n\n\n#include <Graphics\/Glyphs\/TensorGlyphBuilder.h>\n#include <Graphics\/Glyphs\/GlyphGeomUtility.h>\n#include <Core\/GeometryPrimitives\/Transform.h>\n#include <Core\/Math\/MiscMath.h>\n\nusing namespace SCIRun;\nusing namespace Graphics;\nusing namespace Core::Geometry;\nusing namespace Core::Datatypes;\n\nTensorGlyphBuilder::TensorGlyphBuilder(const Tensor& t, const Point& center)\n{\n t_ = t;\n center_ = Point(center);\n}\n\nvoid TensorGlyphBuilder::scaleTensor(double scale)\n{\n t_ = t_ * scale;\n}\n\nstd::vector<Vector> TensorGlyphBuilder::getEigenVectors()\n{\n std::vector<Vector> eigvecs(DIMENSIONS_);\n t_.get_eigenvectors(eigvecs[0], eigvecs[1], eigvecs[2]);\n return eigvecs;\n}\n\nstd::vector<double> TensorGlyphBuilder::getEigenValues()\n{\n std::vector<double> eigvals(DIMENSIONS_);\n t_.get_eigenvalues(eigvals[0], eigvals[1], eigvals[2]);\n return eigvals;\n}\n\nvoid TensorGlyphBuilder::normalizeTensor()\n{\n auto eigvecs = getEigenVectors();\n for (auto& v : eigvecs)\n v.normalize();\n\n auto norm = t_.euclidean_norm();\n t_.set_outside_eigens(eigvecs[0] * norm[0], eigvecs[1] * norm[1], eigvecs[2] * norm[2],\n norm[0], norm[1], norm[2]);\n}\n\nvoid TensorGlyphBuilder::setColor(const ColorRGB& color)\n{\n color_ = color;\n}\n\nvoid TensorGlyphBuilder::setResolution(double resolution)\n{\n resolution_ = resolution;\n}\n\nvoid TensorGlyphBuilder::reorderTensorValues(std::vector<Vector>& eigvecs,\n std::vector<double>& eigvals)\n{\n std::vector<std::pair<double, Vector>> sortList(3);\n for(int d = 0; d < DIMENSIONS_; ++d)\n sortList[d] = std::make_pair(eigvals[d], eigvecs[d]);\n\n std::sort(std::begin(sortList), std::end(sortList), std::greater<std::pair<double, Vector>>());\n\n for(int d = 0; d < DIMENSIONS_; ++d)\n {\n eigvals[d] = sortList[d].first;\n eigvecs[d] = sortList[d].second;\n }\n}\nvoid TensorGlyphBuilder::makeTensorPositive()\n{\n static const double zeroThreshold = 0.000001;\n\n auto eigvals = getEigenValues();\n auto eigvecs = getEigenVectors();\n for (auto& e : eigvals)\n {\n e = fabs(e);\n if(e <= zeroThreshold)\n e = 0;\n }\n\n \/\/ These are exactly zero after thresholding\n flatTensor_ = eigvals[0] == 0 || eigvals[1] == 0 || eigvals[2] == 0;\n\n if (flatTensor_)\n reorderTensorValues(eigvecs, eigvals);\n\n for (int d = 0; d < DIMENSIONS_; ++d)\n if (eigvals[d] == 0)\n {\n zeroNorm_ = Cross(eigvecs[(d+1) % DIMENSIONS_], eigvecs[(d+2) % DIMENSIONS_]).normal();\n eigvecs[d] = zeroNorm_ * eigvals[d];\n break;\n }\n\n t_.set_outside_eigens(eigvecs[0], eigvecs[1], eigvecs[2],\n eigvals[0], eigvals[1], eigvals[2]);\n}\n\nvoid TensorGlyphBuilder::computeSinCosTable(bool half)\n{\n nv_ = resolution_;\n nu_ = resolution_ + 1;\n\n \/\/ Should only happen when doing half ellipsoids.\n if (half) nv_ \/= 2;\n if (nv_ < 2) nv_ = 2;\n\n double end = half ? M_PI : 2.0 * M_PI;\n tab1_ = SinCosTable(nu_, 0, end);\n tab2_ = SinCosTable(nv_, 0, M_PI);\n}\n\nvoid TensorGlyphBuilder::computeTransforms()\n{\n auto eigvecs = getEigenVectors();\n for (auto& v : eigvecs)\n v.normalize();\n GlyphGeomUtility::generateTransforms(center_, eigvecs[0], eigvecs[1], eigvecs[2], trans_, rotate_);\n}\n\nvoid TensorGlyphBuilder::postScaleTransorms()\n{\n auto eigvals = getEigenValues();\n Vector eigvalsVector(eigvals[0], eigvals[1], eigvals[2]);\n\n trans_.post_scale( Vector(1.0,1.0,1.0) * eigvalsVector);\n rotate_.post_scale(Vector(1.0,1.0,1.0) \/ eigvalsVector);\n}\n\nvoid TensorGlyphBuilder::generateEllipsoid(GlyphConstructor& constructor, bool half)\n{\n computeTransforms();\n postScaleTransorms();\n computeSinCosTable(half);\n\n for (int v = 0; v < nv_ - 1; ++v)\n {\n double sinPhi[2];\n sinPhi[0] = tab2_.sin(v+1);\n sinPhi[1] = tab2_.sin(v);\n\n double cosPhi[2];\n cosPhi[0] = tab2_.cos(v+1);\n cosPhi[1] = tab2_.cos(v);\n\n for (int u = 0; u < nu_; ++u)\n {\n double sinTheta = tab1_.sin(u);\n double cosTheta = tab1_.cos(u);\n\n \/\/ Transorm points and add to points list\n constructor.setOffset();\n for (int i = 0; i < 2; ++i)\n {\n Point point = evaluateEllipsoidPoint(sinPhi[i], cosPhi[i], sinTheta, cosTheta);\n Vector pVector = Vector(trans_ * point);\n\n Vector normal;\n if(flatTensor_)\n {\n \/\/ Avoids recalculating norm vector and prevents vectors with infinite length\n bool first_half = v < nv_\/2;\n normal = first_half ? zeroNorm_ : -zeroNorm_;\n }\n else\n {\n normal = rotate_ * Vector(point);\n normal.safe_normalize();\n }\n\n constructor.addVertex(pVector, normal, color_);\n }\n\n constructor.addIndicesToOffset(0, 1, 2);\n constructor.addIndicesToOffset(2, 1, 3);\n }\n constructor.popIndicesNTimes(6);\n }\n}\n\nPoint TensorGlyphBuilder::evaluateEllipsoidPoint(double sinPhi, double cosPhi,\n double sinTheta, double cosTheta)\n{\n double x, y, z;\n x = sinPhi * sinTheta;\n y = sinPhi * cosTheta;\n z = cosPhi;\n return Point(x, y, z);\n}\n\nvoid TensorGlyphBuilder::generateSuperquadricTensor(GlyphConstructor& constructor, double emphasis)\n{\n makeTensorPositive();\n computeTransforms();\n postScaleTransorms();\n computeSinCosTable(false);\n\n double cl = t_.linearCertainty();\n double cp = t_.planarCertainty();\n bool linear = cl >= cp;\n\n double pPower = GlyphGeomUtility::spow((1.0 - cp), emphasis);\n double lPower = GlyphGeomUtility::spow((1.0 - cl), emphasis);\n double A = linear ? pPower : lPower;\n double B = linear ? lPower : pPower;\n\n double normalA = 2.0-A;\n double normalB = 2.0-B;\n\n for (int v = 0; v < nv_ - 1; ++v)\n {\n double sinPhi[2];\n sinPhi[0] = tab2_.sin(v);\n sinPhi[1] = tab2_.sin(v+1);\n\n double cosPhi[2];\n cosPhi[0] = tab2_.cos(v);\n cosPhi[1] = tab2_.cos(v+1);\n\n for (int u = 0; u < nu_; ++u)\n {\n constructor.setOffset();\n double sinTheta = tab1_.sin(u);\n double cosTheta = tab1_.cos(u);\n\n for(int i = 0; i < 2; ++i)\n {\n \/\/ Transorm points and add to points list\n Point p = evaluateSuperquadricPoint(linear, sinPhi[i], cosPhi[i], sinTheta, cosTheta, A, B);\n Vector pVector = Vector(trans_ * p);\n\n Vector normal;\n if(flatTensor_)\n {\n \/\/ Avoids recalculating norm vector and prevents vectors with infinite length\n bool first_half = v < nv_\/2;\n normal = first_half ? zeroNorm_ : -zeroNorm_;\n }\n else\n {\n normal = Vector(evaluateSuperquadricPoint(linear, sinPhi[i], cosPhi[i],\n sinTheta, cosTheta, normalA, normalB));\n normal = rotate_ * normal;\n normal.safe_normalize();\n }\n\n constructor.addVertex(pVector, normal, color_);\n }\n\n constructor.addIndicesToOffset(0, 1, 2);\n constructor.addIndicesToOffset(2, 1, 3);\n }\n }\n constructor.popIndicesNTimes(6);\n}\n\nPoint TensorGlyphBuilder::evaluateSuperquadricPoint(bool linear, double sinPhi, double cosPhi,\n double sinTheta, double cosTheta,\n double A, double B)\n{\n if (linear)\n return evaluateSuperquadricPointLinear(sinPhi, cosPhi, sinTheta, cosTheta, A, B);\n else\n return evaluateSuperquadricPointPlanar(sinPhi, cosPhi, sinTheta, cosTheta, A, B);\n}\n\n\/\/ Generate around x-axis\nPoint TensorGlyphBuilder::evaluateSuperquadricPointLinear(double sinPhi, double cosPhi,\n double sinTheta, double cosTheta,\n double A, double B)\n{\n double x, y, z;\n x = GlyphGeomUtility::spow(cosPhi, B);\n y = -GlyphGeomUtility::spow(sinPhi, B) * GlyphGeomUtility::spow(sinTheta, A);\n z = GlyphGeomUtility::spow(sinPhi, B) * GlyphGeomUtility::spow(cosTheta, A);\n return Point(x, y, z);\n}\n\n\/\/ Generate around z-axis\nPoint TensorGlyphBuilder::evaluateSuperquadricPointPlanar(double sinPhi, double cosPhi,\n double sinTheta, double cosTheta,\n double A, double B)\n{\n double x, y, z;\n x = GlyphGeomUtility::spow(sinPhi, B) * GlyphGeomUtility::spow(cosTheta, A);\n y = GlyphGeomUtility::spow(sinPhi, B) * GlyphGeomUtility::spow(sinTheta, A);\n z = GlyphGeomUtility::spow(cosPhi, B);\n return Point(x, y, z);\n}\n\nvoid TensorGlyphBuilder::generateBox(GlyphConstructor& constructor)\n{\n computeTransforms();\n\n std::vector<Vector> box_points = generateBoxPoints();\n std::vector<Vector> normals = rotate_.get_column_vectors();\n if(flatTensor_)\n for(int d = 0; d < DIMENSIONS_; ++d)\n normals[d] = zeroNorm_;\n\n generateBoxSide(constructor, box_points[5], box_points[4], box_points[7], box_points[6], normals[0]);\n generateBoxSide(constructor, box_points[7], box_points[6], box_points[3], box_points[2], normals[1]);\n generateBoxSide(constructor, box_points[1], box_points[5], box_points[3], box_points[7], normals[2]);\n generateBoxSide(constructor, box_points[3], box_points[2], box_points[1], box_points[0], -normals[0]);\n generateBoxSide(constructor, box_points[1], box_points[0], box_points[5], box_points[4], -normals[1]);\n generateBoxSide(constructor, box_points[2], box_points[6], box_points[0], box_points[4], -normals[2]);\n}\n\nvoid TensorGlyphBuilder::generateBoxSide(GlyphConstructor& constructor, const Vector& p1, const Vector& p2, const Vector& p3,\n const Vector& p4, const Vector& normal)\n{\n constructor.setOffset();\n constructor.addVertex(p1, normal, color_);\n constructor.addVertex(p2, normal, color_);\n constructor.addVertex(p3, normal, color_);\n constructor.addVertex(p4, normal, color_);\n constructor.addIndicesToOffset(2, 0, 3);\n constructor.addIndicesToOffset(1, 3, 0);\n}\n\nstd::vector<Vector> TensorGlyphBuilder::generateBoxPoints()\n{\n auto eigvals = getEigenValues();\n std::vector<Vector> boxPoints;\n\n for(int x : {-1, 1})\n for(int y : {-1, 1})\n for(int z : {-1, 1})\n boxPoints.emplace_back(trans_ * Point(x * eigvals[0], y * eigvals[1], z * eigvals[2]));\n\n return boxPoints;\n}\n\n<commit_msg>function name changed<commit_after>\/*\n For more information, please see: http:\/\/software.sci.utah.edu\n\n The MIT License\n\n Copyright (c) 2020 Scientific Computing and Imaging Institute,\n University of Utah.\n\n Permission is hereby granted, free of charge, to any person obtaining a\n copy of this software and associated documentation files (the \"Software\"),\n to deal in the Software without restriction, including without limitation\n the rights to use, copy, modify, merge, publish, distribute, sublicense,\n and\/or sell copies of the Software, and to permit persons to whom the\n Software is furnished to do so, subject to the following conditions:\n\n The above copyright notice and this permission notice shall be included\n in all copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n DEALINGS IN THE SOFTWARE.\n*\/\n\n\n#include <Graphics\/Glyphs\/TensorGlyphBuilder.h>\n#include <Graphics\/Glyphs\/GlyphGeomUtility.h>\n#include <Core\/GeometryPrimitives\/Transform.h>\n#include <Core\/Math\/MiscMath.h>\n\nusing namespace SCIRun;\nusing namespace Graphics;\nusing namespace Core::Geometry;\nusing namespace Core::Datatypes;\n\nTensorGlyphBuilder::TensorGlyphBuilder(const Tensor& t, const Point& center)\n{\n t_ = t;\n center_ = Point(center);\n}\n\nvoid TensorGlyphBuilder::scaleTensor(double scale)\n{\n t_ = t_ * scale;\n}\n\nstd::vector<Vector> TensorGlyphBuilder::getEigenVectors()\n{\n std::vector<Vector> eigvecs(DIMENSIONS_);\n t_.get_eigenvectors(eigvecs[0], eigvecs[1], eigvecs[2]);\n return eigvecs;\n}\n\nstd::vector<double> TensorGlyphBuilder::getEigenValues()\n{\n std::vector<double> eigvals(DIMENSIONS_);\n t_.get_eigenvalues(eigvals[0], eigvals[1], eigvals[2]);\n return eigvals;\n}\n\nvoid TensorGlyphBuilder::normalizeTensor()\n{\n auto eigvecs = getEigenVectors();\n for (auto& v : eigvecs)\n v.normalize();\n\n auto norm = t_.euclidean_norm();\n t_.set_outside_eigens(eigvecs[0] * norm[0], eigvecs[1] * norm[1], eigvecs[2] * norm[2],\n norm[0], norm[1], norm[2]);\n}\n\nvoid TensorGlyphBuilder::setColor(const ColorRGB& color)\n{\n color_ = color;\n}\n\nvoid TensorGlyphBuilder::setResolution(double resolution)\n{\n resolution_ = resolution;\n}\n\nvoid TensorGlyphBuilder::reorderTensorValues(std::vector<Vector>& eigvecs,\n std::vector<double>& eigvals)\n{\n std::vector<std::pair<double, Vector>> sortList(3);\n for(int d = 0; d < DIMENSIONS_; ++d)\n sortList[d] = std::make_pair(eigvals[d], eigvecs[d]);\n\n std::sort(std::begin(sortList), std::end(sortList), std::greater<std::pair<double, Vector>>());\n\n for(int d = 0; d < DIMENSIONS_; ++d)\n {\n eigvals[d] = sortList[d].first;\n eigvecs[d] = sortList[d].second;\n }\n}\nvoid TensorGlyphBuilder::makeTensorPositive()\n{\n static const double zeroThreshold = 0.000001;\n\n auto eigvals = getEigenValues();\n auto eigvecs = getEigenVectors();\n for (auto& e : eigvals)\n {\n e = fabs(e);\n if(e <= zeroThreshold)\n e = 0;\n }\n\n \/\/ These are exactly zero after thresholding\n flatTensor_ = eigvals[0] == 0 || eigvals[1] == 0 || eigvals[2] == 0;\n\n if (flatTensor_)\n reorderTensorValues(eigvecs, eigvals);\n\n for (int d = 0; d < DIMENSIONS_; ++d)\n if (eigvals[d] == 0)\n {\n zeroNorm_ = Cross(eigvecs[(d+1) % DIMENSIONS_], eigvecs[(d+2) % DIMENSIONS_]).normal();\n eigvecs[d] = zeroNorm_ * eigvals[d];\n break;\n }\n\n t_.set_outside_eigens(eigvecs[0], eigvecs[1], eigvecs[2],\n eigvals[0], eigvals[1], eigvals[2]);\n}\n\nvoid TensorGlyphBuilder::computeSinCosTable(bool half)\n{\n nv_ = resolution_;\n nu_ = resolution_ + 1;\n\n \/\/ Should only happen when doing half ellipsoids.\n if (half) nv_ \/= 2;\n if (nv_ < 2) nv_ = 2;\n\n double end = half ? M_PI : 2.0 * M_PI;\n tab1_ = SinCosTable(nu_, 0, end);\n tab2_ = SinCosTable(nv_, 0, M_PI);\n}\n\nvoid TensorGlyphBuilder::computeTransforms()\n{\n auto eigvecs = getEigenVectors();\n for (auto& v : eigvecs)\n v.normalize();\n GlyphGeomUtility::generateTransforms(center_, eigvecs[0], eigvecs[1], eigvecs[2], trans_, rotate_);\n}\n\nvoid TensorGlyphBuilder::postScaleTransorms()\n{\n auto eigvals = getEigenValues();\n Vector eigvalsVector(eigvals[0], eigvals[1], eigvals[2]);\n\n trans_.post_scale( Vector(1.0,1.0,1.0) * eigvalsVector);\n rotate_.post_scale(Vector(1.0,1.0,1.0) \/ eigvalsVector);\n}\n\nvoid TensorGlyphBuilder::generateEllipsoid(GlyphConstructor& constructor, bool half)\n{\n computeTransforms();\n postScaleTransorms();\n computeSinCosTable(half);\n\n for (int v = 0; v < nv_ - 1; ++v)\n {\n double sinPhi[2];\n sinPhi[0] = tab2_.sin(v+1);\n sinPhi[1] = tab2_.sin(v);\n\n double cosPhi[2];\n cosPhi[0] = tab2_.cos(v+1);\n cosPhi[1] = tab2_.cos(v);\n\n for (int u = 0; u < nu_; ++u)\n {\n double sinTheta = tab1_.sin(u);\n double cosTheta = tab1_.cos(u);\n\n \/\/ Transorm points and add to points list\n constructor.setOffset();\n for (int i = 0; i < 2; ++i)\n {\n Point point = evaluateEllipsoidPoint(sinPhi[i], cosPhi[i], sinTheta, cosTheta);\n Vector pVector = Vector(trans_ * point);\n\n Vector normal;\n if(flatTensor_)\n {\n \/\/ Avoids recalculating norm vector and prevents vectors with infinite length\n bool first_half = v < nv_\/2;\n normal = first_half ? zeroNorm_ : -zeroNorm_;\n }\n else\n {\n normal = rotate_ * Vector(point);\n normal.safe_normalize();\n }\n\n constructor.addVertex(pVector, normal, color_);\n }\n\n constructor.addIndicesToOffset(0, 1, 2);\n constructor.addIndicesToOffset(2, 1, 3);\n }\n constructor.popIndicesNTimes(6);\n }\n}\n\nPoint TensorGlyphBuilder::evaluateEllipsoidPoint(double sinPhi, double cosPhi,\n double sinTheta, double cosTheta)\n{\n double x, y, z;\n x = sinPhi * sinTheta;\n y = sinPhi * cosTheta;\n z = cosPhi;\n return Point(x, y, z);\n}\n\nvoid TensorGlyphBuilder::generateSuperquadricTensor(GlyphConstructor& constructor, double emphasis)\n{\n makeTensorPositive();\n computeTransforms();\n postScaleTransorms();\n computeSinCosTable(false);\n\n double cl = t_.linearCertainty();\n double cp = t_.planarCertainty();\n bool linear = cl >= cp;\n\n double pPower = GlyphGeomUtility::spow((1.0 - cp), emphasis);\n double lPower = GlyphGeomUtility::spow((1.0 - cl), emphasis);\n double A = linear ? pPower : lPower;\n double B = linear ? lPower : pPower;\n\n double normalA = 2.0-A;\n double normalB = 2.0-B;\n\n for (int v = 0; v < nv_ - 1; ++v)\n {\n double sinPhi[2];\n sinPhi[0] = tab2_.sin(v);\n sinPhi[1] = tab2_.sin(v+1);\n\n double cosPhi[2];\n cosPhi[0] = tab2_.cos(v);\n cosPhi[1] = tab2_.cos(v+1);\n\n for (int u = 0; u < nu_; ++u)\n {\n constructor.setOffset();\n double sinTheta = tab1_.sin(u);\n double cosTheta = tab1_.cos(u);\n\n for(int i = 0; i < 2; ++i)\n {\n \/\/ Transorm points and add to points list\n Point p = evaluateSuperquadricPoint(linear, sinPhi[i], cosPhi[i], sinTheta, cosTheta, A, B);\n Vector pVector = Vector(trans_ * p);\n\n Vector normal;\n if(flatTensor_)\n {\n \/\/ Avoids recalculating norm vector and prevents vectors with infinite length\n bool first_half = v < nv_\/2;\n normal = first_half ? zeroNorm_ : -zeroNorm_;\n }\n else\n {\n normal = Vector(evaluateSuperquadricPoint(linear, sinPhi[i], cosPhi[i],\n sinTheta, cosTheta, normalA, normalB));\n normal = rotate_ * normal;\n normal.safe_normalize();\n }\n\n constructor.addVertex(pVector, normal, color_);\n }\n\n constructor.addIndicesToOffset(0, 1, 2);\n constructor.addIndicesToOffset(2, 1, 3);\n }\n }\n constructor.popIndicesNTimes(6);\n}\n\nPoint TensorGlyphBuilder::evaluateSuperquadricPoint(bool linear, double sinPhi, double cosPhi,\n double sinTheta, double cosTheta,\n double A, double B)\n{\n if (linear)\n return evaluateSuperquadricPointLinear(sinPhi, cosPhi, sinTheta, cosTheta, A, B);\n else\n return evaluateSuperquadricPointPlanar(sinPhi, cosPhi, sinTheta, cosTheta, A, B);\n}\n\n\/\/ Generate around x-axis\nPoint TensorGlyphBuilder::evaluateSuperquadricPointLinear(double sinPhi, double cosPhi,\n double sinTheta, double cosTheta,\n double A, double B)\n{\n double x, y, z;\n x = GlyphGeomUtility::spow(cosPhi, B);\n y = -GlyphGeomUtility::spow(sinPhi, B) * GlyphGeomUtility::spow(sinTheta, A);\n z = GlyphGeomUtility::spow(sinPhi, B) * GlyphGeomUtility::spow(cosTheta, A);\n return Point(x, y, z);\n}\n\n\/\/ Generate around z-axis\nPoint TensorGlyphBuilder::evaluateSuperquadricPointPlanar(double sinPhi, double cosPhi,\n double sinTheta, double cosTheta,\n double A, double B)\n{\n double x, y, z;\n x = GlyphGeomUtility::spow(sinPhi, B) * GlyphGeomUtility::spow(cosTheta, A);\n y = GlyphGeomUtility::spow(sinPhi, B) * GlyphGeomUtility::spow(sinTheta, A);\n z = GlyphGeomUtility::spow(cosPhi, B);\n return Point(x, y, z);\n}\n\nvoid TensorGlyphBuilder::generateBox(GlyphConstructor& constructor)\n{\n computeTransforms();\n\n std::vector<Vector> box_points = generateBoxPoints();\n std::vector<Vector> normals = rotate_.get_rotation();\n if(flatTensor_)\n for(int d = 0; d < DIMENSIONS_; ++d)\n normals[d] = zeroNorm_;\n\n generateBoxSide(constructor, box_points[5], box_points[4], box_points[7], box_points[6], normals[0]);\n generateBoxSide(constructor, box_points[7], box_points[6], box_points[3], box_points[2], normals[1]);\n generateBoxSide(constructor, box_points[1], box_points[5], box_points[3], box_points[7], normals[2]);\n generateBoxSide(constructor, box_points[3], box_points[2], box_points[1], box_points[0], -normals[0]);\n generateBoxSide(constructor, box_points[1], box_points[0], box_points[5], box_points[4], -normals[1]);\n generateBoxSide(constructor, box_points[2], box_points[6], box_points[0], box_points[4], -normals[2]);\n}\n\nvoid TensorGlyphBuilder::generateBoxSide(GlyphConstructor& constructor, const Vector& p1, const Vector& p2, const Vector& p3,\n const Vector& p4, const Vector& normal)\n{\n constructor.setOffset();\n constructor.addVertex(p1, normal, color_);\n constructor.addVertex(p2, normal, color_);\n constructor.addVertex(p3, normal, color_);\n constructor.addVertex(p4, normal, color_);\n constructor.addIndicesToOffset(2, 0, 3);\n constructor.addIndicesToOffset(1, 3, 0);\n}\n\nstd::vector<Vector> TensorGlyphBuilder::generateBoxPoints()\n{\n auto eigvals = getEigenValues();\n std::vector<Vector> boxPoints;\n\n for(int x : {-1, 1})\n for(int y : {-1, 1})\n for(int z : {-1, 1})\n boxPoints.emplace_back(trans_ * Point(x * eigvals[0], y * eigvals[1], z * eigvals[2]));\n\n return boxPoints;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n InputDebounce Arduino Library\n\n Mario Ban, 05.2015\n\n GNU General Public License v2.0\n Copyright (C) 2015 Mario Ban\n*\/\n\n#include \"InputDebounce.h\"\n\nInputDebounce::InputDebounce(int8_t pinIn, unsigned long debDelay, PinInMode pinInMode)\n : _pinIn(0)\n , _debDelay(0)\n , _pinInMode(PIM_INT_PULL_UP_RES)\n , _enabled(false)\n , _valueLast(false)\n , _stateOn(false)\n , _timeStamp(0)\n , _stateOnCount(0)\n{\n xsetup(pinIn, debDelay, pinInMode);\n}\n\nvoid InputDebounce::setup(int8_t pinIn, unsigned long debDelay, PinInMode pinInMode)\n{\n if(pinIn >= 0) {\n _pinIn = pinIn;\n _debDelay = debDelay;\n _pinInMode = pinInMode;\n \/\/ initialize digital pin as an input\n if(_pinInMode == PIM_INT_PULL_UP_RES) {\n pinMode(_pinIn, INPUT_PULLUP);\n }\n else {\n pinMode(_pinIn, INPUT);\n }\n _enabled = true;\n }\n else {\n _enabled = false;\n }\n}\n\nunsigned long InputDebounce::process(unsigned long now)\n{\n if(!_enabled) {\n return 0;\n }\n bool value = digitalRead(_pinIn) ? true : false; \/\/ LOW (with pull-up res) when button pressed (on)\n \/\/ adjust value pressed (on)\n if(_pinInMode != PIM_EXT_PULL_DOWN_RES) {\n value = !value;\n }\n \/\/ check if input value changed\n if(_valueLast != value) {\n _valueLast = value;\n _timeStamp = now;\n return 0;\n }\n \/\/ wait debouncing time\n if(now - _timeStamp > _debDelay) {\n \/\/ input value (state) has been stable longer than the debounce period\n if(_stateOn != _valueLast) {\n _stateOn = _valueLast;\n if(_stateOn) {\n _stateOnCount++;\n }\n }\n return _stateOn ? now - _timeStamp : 0;\n }\n return 0;\n}\n\nunsigned long InputDebounce::getStateOnCount() const\n{\n return _stateOnCount;\n}\n<commit_msg>Test Travis CI: build fixed<commit_after>\/*\n InputDebounce Arduino Library\n\n Mario Ban, 05.2015\n\n GNU General Public License v2.0\n Copyright (C) 2015 Mario Ban\n*\/\n\n#include \"InputDebounce.h\"\n\nInputDebounce::InputDebounce(int8_t pinIn, unsigned long debDelay, PinInMode pinInMode)\n : _pinIn(0)\n , _debDelay(0)\n , _pinInMode(PIM_INT_PULL_UP_RES)\n , _enabled(false)\n , _valueLast(false)\n , _stateOn(false)\n , _timeStamp(0)\n , _stateOnCount(0)\n{\n setup(pinIn, debDelay, pinInMode);\n}\n\nvoid InputDebounce::setup(int8_t pinIn, unsigned long debDelay, PinInMode pinInMode)\n{\n if(pinIn >= 0) {\n _pinIn = pinIn;\n _debDelay = debDelay;\n _pinInMode = pinInMode;\n \/\/ initialize digital pin as an input\n if(_pinInMode == PIM_INT_PULL_UP_RES) {\n pinMode(_pinIn, INPUT_PULLUP);\n }\n else {\n pinMode(_pinIn, INPUT);\n }\n _enabled = true;\n }\n else {\n _enabled = false;\n }\n}\n\nunsigned long InputDebounce::process(unsigned long now)\n{\n if(!_enabled) {\n return 0;\n }\n bool value = digitalRead(_pinIn) ? true : false; \/\/ LOW (with pull-up res) when button pressed (on)\n \/\/ adjust value pressed (on)\n if(_pinInMode != PIM_EXT_PULL_DOWN_RES) {\n value = !value;\n }\n \/\/ check if input value changed\n if(_valueLast != value) {\n _valueLast = value;\n _timeStamp = now;\n return 0;\n }\n \/\/ wait debouncing time\n if(now - _timeStamp > _debDelay) {\n \/\/ input value (state) has been stable longer than the debounce period\n if(_stateOn != _valueLast) {\n _stateOn = _valueLast;\n if(_stateOn) {\n _stateOnCount++;\n }\n }\n return _stateOn ? now - _timeStamp : 0;\n }\n return 0;\n}\n\nunsigned long InputDebounce::getStateOnCount() const\n{\n return _stateOnCount;\n}\n<|endoftext|>"} {"text":"<commit_before>#ifndef _SNARKFRONT_DSL_IDENTITY_HPP_\n#define _SNARKFRONT_DSL_IDENTITY_HPP_\n\n#include <array>\n#include <cstdint>\n#include <BigInt.hpp> \/\/ snarklib\n#include \"DSL_base.hpp\"\n\nnamespace snarkfront {\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ identity elements\n\/\/\n\n\/\/ Boolean\nbool zero(const bool& dummy);\nbool one(const bool& dummy);\n\ntemplate <typename FR>\nc_bool<FR> zero(const bool_x<FR>& dummy) {\n return c_bool<FR>(false);\n}\n\ntemplate <typename FR>\nc_bool<FR> one(const bool_x<FR>& dummy) {\n return c_bool<FR>(true);\n}\n\ntemplate <typename FR, std::size_t N>\nstd::array<c_bool<FR>, N> zero(const std::array<bool_x<FR>, N>& dummy) {\n std::array<c_bool<FR>, N> a;\n\n for (std::size_t i = 0; i < N; ++i)\n a[i] = zero(dummy[i]);\n\n return a;\n}\n\n\/\/ big integer\ntemplate <mp_size_t N>\nsnarklib::BigInt<N> zero(const snarklib::BigInt<N>& dummy) {\n return snarklib::BigInt<N>::zero();\n}\n\ntemplate <mp_size_t N>\nsnarklib::BigInt<N> one(const snarklib::BigInt<N>& dummy) {\n return snarklib::BigInt<N>::one();\n}\n\ntemplate <typename FR>\nc_bigint<FR> zero(const bigint_x<FR>& dummy) {\n return c_bigint<FR>(bigint_x<FR>::ValueType::zero());\n}\n\ntemplate <typename FR>\nc_bigint<FR> one(const bigint_x<FR>& dummy) {\n return c_bigint<FR>(bigint_x<FR>::ValueType::one());\n}\n\ntemplate <typename FR, std::size_t N>\nstd::array<c_bigint<FR>, N> zero(const std::array<bigint_x<FR>, N>& dummy) {\n std::array<c_bigint<FR>, N> a;\n\n for (std::size_t i = 0; i < N; ++i)\n a[i] = zero(dummy[i]);\n\n return a;\n}\n\n\/\/ 32-bit word\nstd::uint32_t zero(const std::uint32_t& dummy);\nstd::uint32_t one(const std::uint32_t& dummy);\n\ntemplate <typename FR>\nc_uint32<FR> zero(const uint32_x<FR>& dummy) {\n return c_uint32<FR>(0);\n}\n\ntemplate <typename FR>\nc_uint32<FR> one(const uint32_x<FR>& dummy) {\n return c_uint32<FR>(1);\n}\n\ntemplate <typename FR, std::size_t N>\nstd::array<c_uint32<FR>, N> zero(const std::array<uint32_x<FR>, N>& dummy) {\n std::array<c_uint32<FR>, N> a;\n\n for (std::size_t i = 0; i < N; ++i)\n a[i] = zero(dummy[i]);\n\n return a;\n}\n\n\/\/ 64-bit word\nstd::uint64_t zero(const std::uint64_t& dummy);\nstd::uint64_t one(const std::uint64_t& dummy);\n\ntemplate <typename FR>\nc_uint64<FR> zero(const uint64_x<FR>& dummy) {\n return c_uint64<FR>(0);\n}\n\ntemplate <typename FR>\nc_uint64<FR> one(const uint64_x<FR>& dummy) {\n return c_uint64<FR>(1);\n}\n\ntemplate <typename FR, std::size_t N>\nstd::array<c_uint64<FR>, N> zero(const std::array<uint64_x<FR>, N>& dummy) {\n std::array<c_uint64<FR>, N> a;\n\n for (std::size_t i = 0; i < N; ++i)\n a[i] = zero(dummy[i]);\n\n return a;\n}\n\n} \/\/ namespace snarkfront\n\n#endif\n<commit_msg>8-bit unsigned int type<commit_after>#ifndef _SNARKFRONT_DSL_IDENTITY_HPP_\n#define _SNARKFRONT_DSL_IDENTITY_HPP_\n\n#include <array>\n#include <cstdint>\n#include <BigInt.hpp> \/\/ snarklib\n#include \"DSL_base.hpp\"\n\nnamespace snarkfront {\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ identity elements\n\/\/\n\n\/\/ Boolean\nbool zero(const bool& dummy);\nbool one(const bool& dummy);\n\ntemplate <typename FR>\nc_bool<FR> zero(const bool_x<FR>& dummy) {\n return c_bool<FR>(false);\n}\n\ntemplate <typename FR>\nc_bool<FR> one(const bool_x<FR>& dummy) {\n return c_bool<FR>(true);\n}\n\ntemplate <typename FR, std::size_t N>\nstd::array<c_bool<FR>, N> zero(const std::array<bool_x<FR>, N>& dummy) {\n std::array<c_bool<FR>, N> a;\n\n for (std::size_t i = 0; i < N; ++i)\n a[i] = zero(dummy[i]);\n\n return a;\n}\n\n\/\/ big integer\ntemplate <mp_size_t N>\nsnarklib::BigInt<N> zero(const snarklib::BigInt<N>& dummy) {\n return snarklib::BigInt<N>::zero();\n}\n\ntemplate <mp_size_t N>\nsnarklib::BigInt<N> one(const snarklib::BigInt<N>& dummy) {\n return snarklib::BigInt<N>::one();\n}\n\ntemplate <typename FR>\nc_bigint<FR> zero(const bigint_x<FR>& dummy) {\n return c_bigint<FR>(bigint_x<FR>::ValueType::zero());\n}\n\ntemplate <typename FR>\nc_bigint<FR> one(const bigint_x<FR>& dummy) {\n return c_bigint<FR>(bigint_x<FR>::ValueType::one());\n}\n\ntemplate <typename FR, std::size_t N>\nstd::array<c_bigint<FR>, N> zero(const std::array<bigint_x<FR>, N>& dummy) {\n std::array<c_bigint<FR>, N> a;\n\n for (std::size_t i = 0; i < N; ++i)\n a[i] = zero(dummy[i]);\n\n return a;\n}\n\n\/\/ 8-bit octet\nstd::uint8_t zero(const std::uint8_t& dummy);\nstd::uint8_t one(const std::uint8_t& dummy);\n\ntemplate <typename FR>\nc_uint8<FR> zero(const uint8_x<FR>& dummy) {\n return c_uint8<FR>(0);\n}\n\ntemplate <typename FR>\nc_uint8<FR> one(const uint8_x<FR>& dummy) {\n return c_uint8<FR>(1);\n}\n\ntemplate <typename FR, std::size_t N>\nstd::array<c_uint8<FR>, N> zero(const std::array<uint8_x<FR>, N>& dummy) {\n std::array<c_uint8<FR>, N> a;\n\n for (std::size_t i = 0; i < N; ++i)\n a[i] = zero(dummy[i]);\n\n return a;\n}\n\n\/\/ 32-bit word\nstd::uint32_t zero(const std::uint32_t& dummy);\nstd::uint32_t one(const std::uint32_t& dummy);\n\ntemplate <typename FR>\nc_uint32<FR> zero(const uint32_x<FR>& dummy) {\n return c_uint32<FR>(0);\n}\n\ntemplate <typename FR>\nc_uint32<FR> one(const uint32_x<FR>& dummy) {\n return c_uint32<FR>(1);\n}\n\ntemplate <typename FR, std::size_t N>\nstd::array<c_uint32<FR>, N> zero(const std::array<uint32_x<FR>, N>& dummy) {\n std::array<c_uint32<FR>, N> a;\n\n for (std::size_t i = 0; i < N; ++i)\n a[i] = zero(dummy[i]);\n\n return a;\n}\n\n\/\/ 64-bit word\nstd::uint64_t zero(const std::uint64_t& dummy);\nstd::uint64_t one(const std::uint64_t& dummy);\n\ntemplate <typename FR>\nc_uint64<FR> zero(const uint64_x<FR>& dummy) {\n return c_uint64<FR>(0);\n}\n\ntemplate <typename FR>\nc_uint64<FR> one(const uint64_x<FR>& dummy) {\n return c_uint64<FR>(1);\n}\n\ntemplate <typename FR, std::size_t N>\nstd::array<c_uint64<FR>, N> zero(const std::array<uint64_x<FR>, N>& dummy) {\n std::array<c_uint64<FR>, N> a;\n\n for (std::size_t i = 0; i < N; ++i)\n a[i] = zero(dummy[i]);\n\n return a;\n}\n\n} \/\/ namespace snarkfront\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/* Copyright 2019 Benjamin Worpitz\n *\n * This file is part of Alpaka.\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\/\n\n#pragma once\n\n#include <alpaka\/acc\/AccDevProps.hpp>\n#include <alpaka\/core\/Common.hpp>\n#include <alpaka\/core\/Concepts.hpp>\n#include <alpaka\/dev\/Traits.hpp>\n#include <alpaka\/kernel\/Traits.hpp>\n#include <alpaka\/dim\/Traits.hpp>\n#include <alpaka\/idx\/Traits.hpp>\n#include <alpaka\/pltf\/Traits.hpp>\n#include <alpaka\/queue\/Traits.hpp>\n\n#include <string>\n#include <typeinfo>\n#include <type_traits>\n\nnamespace alpaka\n{\n \/\/-----------------------------------------------------------------------------\n \/\/! The accelerator specifics.\n namespace acc\n {\n struct ConceptUniformCudaHip{};\n\n struct ConceptAcc{};\n \/\/-----------------------------------------------------------------------------\n \/\/! The accelerator traits.\n namespace traits\n {\n \/\/#############################################################################\n \/\/! The accelerator type trait.\n template<\n typename T,\n typename TSfinae = void>\n struct AccType;\n\n \/\/#############################################################################\n \/\/! The device properties get trait.\n template<\n typename TAcc,\n typename TSfinae = void>\n struct GetAccDevProps;\n\n \/\/#############################################################################\n \/\/! The accelerator name trait.\n \/\/!\n \/\/! The default implementation returns the mangled class name.\n template<\n typename TAcc,\n typename TSfinae = void>\n struct GetAccName\n {\n \/\/-----------------------------------------------------------------------------\n ALPAKA_FN_HOST static auto getAccName()\n -> std::string\n {\n return typeid(TAcc).name();\n }\n };\n\n \/\/#############################################################################\n \/\/! The GPU CUDA accelerator device properties get trait specialization.\n template<typename TAcc>\n struct GetAccDevProps<\n TAcc,\n typename std::enable_if<\n concepts::ImplementsConcept<acc::ConceptUniformCudaHip, TAcc>::value\n >::type>\n {\n \/\/-----------------------------------------------------------------------------\n ALPAKA_FN_HOST static auto getAccDevProps(\n typename dev::traits::DevType<TAcc>::type const & dev)\n -> AccDevProps<typename dim::traits::DimType<TAcc>::type, typename idx::traits::IdxType<TAcc>::type>\n {\n using ImplementationBase = typename concepts::ImplementationBase<acc::ConceptUniformCudaHip, TAcc>;\n return GetAccDevProps<ImplementationBase>::getAccDevProps(dev);\n }\n };\n }\n\n \/\/#############################################################################\n \/\/! The accelerator type trait alias template to remove the ::type.\n template<\n typename T>\n using Acc = typename traits::AccType<T>::type;\n\n \/\/-----------------------------------------------------------------------------\n \/\/! \\return The acceleration properties on the given device.\n template<\n typename TAcc,\n typename TDev>\n ALPAKA_FN_HOST auto getAccDevProps(\n TDev const & dev)\n -> AccDevProps<dim::Dim<TAcc>, idx::Idx<TAcc>>\n {\n return\n traits::GetAccDevProps<\n TAcc>\n ::getAccDevProps(\n dev);\n }\n\n \/\/-----------------------------------------------------------------------------\n \/\/! \\return The accelerator name\n \/\/!\n \/\/! \\tparam TAcc The accelerator type.\n template<\n typename TAcc>\n ALPAKA_FN_HOST auto getAccName()\n -> std::string\n {\n return\n traits::GetAccName<\n TAcc>\n ::getAccName();\n }\n }\n\n namespace kernel\n {\n namespace detail\n {\n template<typename TAcc>\n struct CheckFnReturnType<\n TAcc,\n typename std::enable_if<\n concepts::ImplementsConcept<acc::ConceptUniformCudaHip, TAcc>::value\n >::type>\n {\n template<\n typename TKernelFnObj,\n typename... TArgs>\n void operator()(\n TKernelFnObj const & kernelFnObj,\n TArgs const & ... args)\n {\n using ImplementationBase = typename concepts::ImplementationBase<acc::ConceptUniformCudaHip, TAcc>;\n CheckFnReturnType<ImplementationBase>{}(\n kernelFnObj,\n args...);\n }\n };\n }\n\n }\n\n namespace dev\n {\n namespace traits\n {\n \/\/#############################################################################\n \/\/! The GPU HIP accelerator device type trait specialization.\n template<typename TAcc>\n struct DevType<\n TAcc,\n typename std::enable_if<\n concepts::ImplementsConcept<acc::ConceptUniformCudaHip, TAcc>::value\n >::type>\n {\n using ImplementationBase = typename concepts::ImplementationBase<acc::ConceptUniformCudaHip, TAcc>;\n using type = typename DevType<ImplementationBase>::type;\n };\n }\n }\n namespace pltf\n {\n namespace traits\n {\n \/\/#############################################################################\n \/\/! The CPU HIP execution task platform type trait specialization.\n template<typename TAcc>\n struct PltfType<\n TAcc,\n typename std::enable_if<\n concepts::ImplementsConcept<acc::ConceptUniformCudaHip, TAcc>::value\n >::type>\n {\n using ImplementationBase = typename concepts::ImplementationBase<acc::ConceptUniformCudaHip, TAcc>;\n using type = typename PltfType<ImplementationBase>::type;\n };\n }\n\n }\n namespace dim\n {\n namespace traits\n {\n \/\/#############################################################################\n \/\/! The GPU HIP accelerator dimension getter trait specialization.\n template<typename TAcc>\n struct DimType<\n TAcc,\n typename std::enable_if<\n concepts::ImplementsConcept<acc::ConceptUniformCudaHip, TAcc>::value\n >::type>\n {\n using ImplementationBase = typename concepts::ImplementationBase<acc::ConceptUniformCudaHip, TAcc>;\n using type = typename DimType<ImplementationBase>::type;\n };\n }\n }\n namespace idx\n {\n namespace traits\n {\n \/\/#############################################################################\n \/\/! The GPU HIP accelerator idx type trait specialization.\n template<typename TAcc>\n struct IdxType<\n TAcc,\n typename std::enable_if<\n concepts::ImplementsConcept<acc::ConceptUniformCudaHip, TAcc>::value\n >::type>\n {\n using ImplementationBase = typename concepts::ImplementationBase<acc::ConceptUniformCudaHip, TAcc>;\n using type = typename IdxType<ImplementationBase>::type;\n };\n }\n }\n\n namespace queue\n {\n namespace traits\n {\n template<\n typename TAcc,\n typename TProperty>\n struct QueueType<\n TAcc,\n TProperty,\n std::enable_if_t<\n concepts::ImplementsConcept<acc::ConceptAcc, TAcc>::value\n >\n >\n {\n using type = typename QueueType<\n typename pltf::traits::PltfType<TAcc>::type,\n TProperty\n >::type;\n };\n }\n }\n}\n<commit_msg>Fix getAccDevProps: Add ImplementationBase<commit_after>\/* Copyright 2019 Benjamin Worpitz\n *\n * This file is part of Alpaka.\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\/\n\n#pragma once\n\n#include <alpaka\/acc\/AccDevProps.hpp>\n#include <alpaka\/core\/Common.hpp>\n#include <alpaka\/core\/Concepts.hpp>\n#include <alpaka\/dev\/Traits.hpp>\n#include <alpaka\/kernel\/Traits.hpp>\n#include <alpaka\/dim\/Traits.hpp>\n#include <alpaka\/idx\/Traits.hpp>\n#include <alpaka\/pltf\/Traits.hpp>\n#include <alpaka\/queue\/Traits.hpp>\n\n#include <string>\n#include <typeinfo>\n#include <type_traits>\n\nnamespace alpaka\n{\n \/\/-----------------------------------------------------------------------------\n \/\/! The accelerator specifics.\n namespace acc\n {\n struct ConceptUniformCudaHip{};\n\n struct ConceptAcc{};\n \/\/-----------------------------------------------------------------------------\n \/\/! The accelerator traits.\n namespace traits\n {\n \/\/#############################################################################\n \/\/! The accelerator type trait.\n template<\n typename T,\n typename TSfinae = void>\n struct AccType;\n\n \/\/#############################################################################\n \/\/! The device properties get trait.\n template<\n typename TAcc,\n typename TSfinae = void>\n struct GetAccDevProps;\n\n \/\/#############################################################################\n \/\/! The accelerator name trait.\n \/\/!\n \/\/! The default implementation returns the mangled class name.\n template<\n typename TAcc,\n typename TSfinae = void>\n struct GetAccName\n {\n \/\/-----------------------------------------------------------------------------\n ALPAKA_FN_HOST static auto getAccName()\n -> std::string\n {\n return typeid(TAcc).name();\n }\n };\n\n \/\/#############################################################################\n \/\/! The GPU CUDA accelerator device properties get trait specialization.\n template<typename TAcc>\n struct GetAccDevProps<\n TAcc,\n typename std::enable_if<\n concepts::ImplementsConcept<acc::ConceptUniformCudaHip, TAcc>::value\n >::type>\n {\n \/\/-----------------------------------------------------------------------------\n ALPAKA_FN_HOST static auto getAccDevProps(\n typename dev::traits::DevType<TAcc>::type const & dev)\n -> AccDevProps<typename dim::traits::DimType<TAcc>::type, typename idx::traits::IdxType<TAcc>::type>\n {\n using ImplementationBase = typename concepts::ImplementationBase<acc::ConceptUniformCudaHip, TAcc>;\n return GetAccDevProps<ImplementationBase>::getAccDevProps(dev);\n }\n };\n }\n\n \/\/#############################################################################\n \/\/! The accelerator type trait alias template to remove the ::type.\n template<\n typename T>\n using Acc = typename traits::AccType<T>::type;\n\n \/\/-----------------------------------------------------------------------------\n \/\/! \\return The acceleration properties on the given device.\n template<\n typename TAcc,\n typename TDev>\n ALPAKA_FN_HOST auto getAccDevProps(\n TDev const & dev)\n -> AccDevProps<dim::Dim<TAcc>, idx::Idx<TAcc>>\n {\n using ImplementationBase = concepts::ImplementationBase<ConceptAcc, TAcc>;\n return\n traits::GetAccDevProps<\n ImplementationBase>\n ::getAccDevProps(\n dev);\n }\n\n \/\/-----------------------------------------------------------------------------\n \/\/! \\return The accelerator name\n \/\/!\n \/\/! \\tparam TAcc The accelerator type.\n template<\n typename TAcc>\n ALPAKA_FN_HOST auto getAccName()\n -> std::string\n {\n return\n traits::GetAccName<\n TAcc>\n ::getAccName();\n }\n }\n\n namespace kernel\n {\n namespace detail\n {\n template<typename TAcc>\n struct CheckFnReturnType<\n TAcc,\n typename std::enable_if<\n concepts::ImplementsConcept<acc::ConceptUniformCudaHip, TAcc>::value\n >::type>\n {\n template<\n typename TKernelFnObj,\n typename... TArgs>\n void operator()(\n TKernelFnObj const & kernelFnObj,\n TArgs const & ... args)\n {\n using ImplementationBase = typename concepts::ImplementationBase<acc::ConceptUniformCudaHip, TAcc>;\n CheckFnReturnType<ImplementationBase>{}(\n kernelFnObj,\n args...);\n }\n };\n }\n\n }\n\n namespace dev\n {\n namespace traits\n {\n \/\/#############################################################################\n \/\/! The GPU HIP accelerator device type trait specialization.\n template<typename TAcc>\n struct DevType<\n TAcc,\n typename std::enable_if<\n concepts::ImplementsConcept<acc::ConceptUniformCudaHip, TAcc>::value\n >::type>\n {\n using ImplementationBase = typename concepts::ImplementationBase<acc::ConceptUniformCudaHip, TAcc>;\n using type = typename DevType<ImplementationBase>::type;\n };\n }\n }\n namespace pltf\n {\n namespace traits\n {\n \/\/#############################################################################\n \/\/! The CPU HIP execution task platform type trait specialization.\n template<typename TAcc>\n struct PltfType<\n TAcc,\n typename std::enable_if<\n concepts::ImplementsConcept<acc::ConceptUniformCudaHip, TAcc>::value\n >::type>\n {\n using ImplementationBase = typename concepts::ImplementationBase<acc::ConceptUniformCudaHip, TAcc>;\n using type = typename PltfType<ImplementationBase>::type;\n };\n }\n\n }\n namespace dim\n {\n namespace traits\n {\n \/\/#############################################################################\n \/\/! The GPU HIP accelerator dimension getter trait specialization.\n template<typename TAcc>\n struct DimType<\n TAcc,\n typename std::enable_if<\n concepts::ImplementsConcept<acc::ConceptUniformCudaHip, TAcc>::value\n >::type>\n {\n using ImplementationBase = typename concepts::ImplementationBase<acc::ConceptUniformCudaHip, TAcc>;\n using type = typename DimType<ImplementationBase>::type;\n };\n }\n }\n namespace idx\n {\n namespace traits\n {\n \/\/#############################################################################\n \/\/! The GPU HIP accelerator idx type trait specialization.\n template<typename TAcc>\n struct IdxType<\n TAcc,\n typename std::enable_if<\n concepts::ImplementsConcept<acc::ConceptUniformCudaHip, TAcc>::value\n >::type>\n {\n using ImplementationBase = typename concepts::ImplementationBase<acc::ConceptUniformCudaHip, TAcc>;\n using type = typename IdxType<ImplementationBase>::type;\n };\n }\n }\n\n namespace queue\n {\n namespace traits\n {\n template<\n typename TAcc,\n typename TProperty>\n struct QueueType<\n TAcc,\n TProperty,\n std::enable_if_t<\n concepts::ImplementsConcept<acc::ConceptAcc, TAcc>::value\n >\n >\n {\n using type = typename QueueType<\n typename pltf::traits::PltfType<TAcc>::type,\n TProperty\n >::type;\n };\n }\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n This library is free software; you can redistribute it and\/or\n modify it under the terms of the GNU Library General Public\n License version 2 as published by the Free Software Foundation.\n\n This library is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n Library General Public License for more details.\n\n You should have received a copy of the GNU Library General Public License\n along with this library; see the file COPYING.LIB. If not, write to\n the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,\n Boston, MA 02110-1301, USA.\n\n ---\n Copyright (C) 2004, Anders Lund <anders@alweb.dk>\n*\/\n\n#include \"katemwmodonhddialog.h\"\n\n#include \"kateapp.h\"\n#include \"katedocmanager.h\"\n#include \"katemainwindow.h\"\n\n#include <KMessageBox>\n#include <KProcess>\n#include <KRun>\n#include <KLocalizedString>\n#include <KIconLoader>\n\n#include <QTemporaryFile>\n#include <QTextStream>\n#include <QHeaderView>\n#include <QLabel>\n#include <QPushButton>\n\n#include <QTreeWidget>\n#include <QTreeWidgetItem>\n\nclass KateDocItem : public QTreeWidgetItem\n{\npublic:\n KateDocItem(KTextEditor::Document *doc, const QString &status, QTreeWidget *tw)\n : QTreeWidgetItem(tw),\n document(doc) {\n setText(0, doc->url().toString());\n setText(1, status);\n if (! doc->isModified()) {\n setCheckState(0, Qt::Checked);\n } else {\n setCheckState(0, Qt::Unchecked);\n }\n }\n ~KateDocItem()\n {}\n\n KTextEditor::Document *document;\n};\n\nKateMwModOnHdDialog::KateMwModOnHdDialog(DocVector docs, QWidget *parent, const char *name)\n : QDialog(parent),\n m_proc(0),\n m_diffFile(0)\n{\n setWindowTitle(i18n(\"Documents Modified on Disk\"));\n setObjectName(QString::fromLatin1(name));\n setModal(true);\n\n QVBoxLayout *mainLayout = new QVBoxLayout;\n setLayout(mainLayout);\n\n \/\/ Message\n QHBoxLayout *hb = new QHBoxLayout;\n mainLayout->addLayout(hb);\n\n \/\/ dialog text\n QLabel *icon = new QLabel(this);\n hb->addWidget(icon);\n icon->setPixmap(DesktopIcon(QStringLiteral(\"dialog-warning\")));\n\n QLabel *t = new QLabel(i18n(\n \"<qt>The documents listed below have changed on disk.<p>Select one \"\n \"or more at once, and press an action button until the list is empty.<\/p><\/qt>\"), this);\n hb->addWidget(t);\n hb->setStretchFactor(t, 1000);\n\n \/\/ Document list\n twDocuments = new QTreeWidget(this);\n mainLayout->addWidget(twDocuments);\n QStringList header;\n header << i18n(\"Filename\") << i18n(\"Status on Disk\");\n twDocuments->setHeaderLabels(header);\n twDocuments->setSelectionMode(QAbstractItemView::SingleSelection);\n twDocuments->setRootIsDecorated(false);\n\n m_stateTexts << QString() << i18n(\"Modified\") << i18n(\"Created\") << i18n(\"Deleted\");\n for (int i = 0; i < docs.size(); i++) {\n new KateDocItem(docs[i], m_stateTexts[(uint)KateApp::self()->documentManager()->documentInfo(docs[i])->modifiedOnDiscReason ], twDocuments);\n }\n twDocuments->header()->setStretchLastSection(false);\n twDocuments->header()->setSectionResizeMode(0, QHeaderView::Stretch);\n twDocuments->header()->setSectionResizeMode(1, QHeaderView::ResizeToContents);\n\n connect(twDocuments, &QTreeWidget::currentItemChanged, this, &KateMwModOnHdDialog::slotSelectionChanged);\n\n \/\/ Diff line\n hb = new QHBoxLayout;\n mainLayout->addLayout(hb);\n\n btnDiff = new QPushButton(QIcon::fromTheme(QStringLiteral(\"document-preview\")), i18n(\"&View Difference\"), this);\n btnDiff->setWhatsThis(i18n(\n \"Calculates the difference between the editor contents and the disk \"\n \"file for the selected document, and shows the difference with the \"\n \"default application. Requires diff(1).\"));\n hb->addWidget(btnDiff);\n connect(btnDiff, &QPushButton::clicked, this, &KateMwModOnHdDialog::slotDiff);\n\n \/\/ Dialog buttons\n QDialogButtonBox *buttons = new QDialogButtonBox(this);\n mainLayout->addWidget(buttons);\n\n QPushButton *ignoreButton = new QPushButton(QIcon::fromTheme(QStringLiteral(\"dialog-warning\")), i18n(\"&Ignore Changes\"));\n ignoreButton->setToolTip(i18n(\"Remove modified flag from selected documents\"));\n buttons->addButton(ignoreButton, QDialogButtonBox::RejectRole);\n connect(ignoreButton, &QPushButton::clicked, this, &KateMwModOnHdDialog::slotIgnore);\n\n QPushButton *overwriteButton = new QPushButton;\n KGuiItem::assign(overwriteButton, KStandardGuiItem::overwrite());\n overwriteButton->setToolTip(i18n(\"Overwrite selected documents, discarding disk changes\"));\n buttons->addButton(overwriteButton, QDialogButtonBox::DestructiveRole);\n connect(overwriteButton, &QPushButton::clicked, this, &KateMwModOnHdDialog::slotOverwrite);\n\n QPushButton *reloadButton = new QPushButton(QIcon::fromTheme(QStringLiteral(\"view-refresh\")), i18n(\"&Reload\"));\n reloadButton->setDefault(true);\n reloadButton->setToolTip(i18n(\"Reload selected documents from disk\"));\n buttons->addButton(reloadButton, QDialogButtonBox::DestructiveRole);\n connect(reloadButton, &QPushButton::clicked, this, &KateMwModOnHdDialog::slotReload);\n\n slotSelectionChanged(NULL, NULL);\n}\n\nKateMwModOnHdDialog::~KateMwModOnHdDialog()\n{\n KateMainWindow::unsetModifiedOnDiscDialogIfIf(this);\n delete m_proc;\n m_proc = 0;\n if (m_diffFile) {\n m_diffFile->setAutoRemove(true);\n delete m_diffFile;\n m_diffFile = 0;\n }\n}\n\nvoid KateMwModOnHdDialog::slotIgnore()\n{\n handleSelected(Ignore);\n}\n\nvoid KateMwModOnHdDialog::slotOverwrite()\n{\n handleSelected(Overwrite);\n}\n\nvoid KateMwModOnHdDialog::slotReload()\n{\n handleSelected(Reload);\n}\n\nvoid KateMwModOnHdDialog::handleSelected(int action)\n{\n \/\/ collect all items we can remove\n QList<QTreeWidgetItem *> itemsToDelete;\n for (QTreeWidgetItemIterator it(twDocuments); *it; ++it) {\n KateDocItem *item = (KateDocItem *) * it;\n if (item->checkState(0) == Qt::Checked) {\n KTextEditor::ModificationInterface::ModifiedOnDiskReason reason = KateApp::self()->documentManager()->documentInfo(item->document)->modifiedOnDiscReason;\n bool success = true;\n\n if (KTextEditor::ModificationInterface *iface = qobject_cast<KTextEditor::ModificationInterface *>(item->document)) {\n iface->setModifiedOnDisk(KTextEditor::ModificationInterface::OnDiskUnmodified);\n }\n\n switch (action) {\n case Overwrite:\n success = item->document->save();\n if (! success) {\n KMessageBox::sorry(this,\n i18n(\"Could not save the document \\n'%1'\",\n item->document->url().toString()));\n }\n break;\n\n case Reload:\n item->document->documentReload();\n break;\n\n default:\n break;\n }\n\n if (success) {\n itemsToDelete.append(item);\n } else {\n if (KTextEditor::ModificationInterface *iface = qobject_cast<KTextEditor::ModificationInterface *>(item->document)) {\n iface->setModifiedOnDisk(reason);\n }\n }\n }\n }\n\n \/\/ remove the marked items\n for (int i = 0; i < itemsToDelete.count(); ++i) {\n delete itemsToDelete[i];\n }\n\n\/\/ any documents left unhandled?\n if (! twDocuments->topLevelItemCount()) {\n accept();\n }\n}\n\nvoid KateMwModOnHdDialog::slotSelectionChanged(QTreeWidgetItem *current, QTreeWidgetItem *)\n{\n KateDocItem *currentDocItem = static_cast<KateDocItem *>(current);\n \/\/ set the diff button enabled\n btnDiff->setEnabled(currentDocItem &&\n KateApp::self()->documentManager()->documentInfo(currentDocItem->document)->modifiedOnDiscReason != KTextEditor::ModificationInterface::OnDiskDeleted);\n}\n\n\/\/ ### the code below is slightly modified from kdelibs\/kate\/part\/katedialogs,\n\/\/ class KateModOnHdPrompt.\nvoid KateMwModOnHdDialog::slotDiff()\n{\n if (!btnDiff->isEnabled()) { \/\/ diff button already pressed, proc not finished yet\n return;\n }\n\n if (! twDocuments->currentItem()) {\n return;\n }\n\n KTextEditor::Document *doc = (static_cast<KateDocItem *>(twDocuments->currentItem()))->document;\n\n \/\/ don't try to diff a deleted file\n if (KateApp::self()->documentManager()->documentInfo(doc)->modifiedOnDiscReason == KTextEditor::ModificationInterface::OnDiskDeleted) {\n return;\n }\n\n if (m_diffFile) {\n return;\n }\n\n m_diffFile = new QTemporaryFile();\n m_diffFile->open();\n\n \/\/ Start a KProcess that creates a diff\n m_proc = new KProcess(this);\n m_proc->setOutputChannelMode(KProcess::MergedChannels);\n *m_proc << QStringLiteral(\"diff\") << QStringLiteral(\"-ub\") << QStringLiteral(\"-\") << doc->url().toLocalFile();\n connect(m_proc, &KProcess::readyRead, this, &KateMwModOnHdDialog::slotDataAvailable);\n connect(m_proc, static_cast<void (KProcess::*)(int, QProcess::ExitStatus)>(&KProcess::finished), this, &KateMwModOnHdDialog::slotPDone);\n\n setCursor(Qt::WaitCursor);\n btnDiff->setEnabled(false);\n\n m_proc->start();\n\n QTextStream ts(m_proc);\n int lastln = doc->lines() - 1;\n for (int l = 0; l < lastln; ++l) {\n ts << doc->line(l) << QLatin1Char('\\n');\n }\n ts << doc->line(lastln);\n ts.flush();\n m_proc->closeWriteChannel();\n}\n\nvoid KateMwModOnHdDialog::slotDataAvailable()\n{\n m_diffFile->write(m_proc->readAll());\n}\n\nvoid KateMwModOnHdDialog::slotPDone()\n{\n setCursor(Qt::ArrowCursor);\n slotSelectionChanged(twDocuments->currentItem(), 0);\n\n const QProcess::ExitStatus es = m_proc->exitStatus();\n delete m_proc;\n m_proc = 0;\n\n if (es != QProcess::NormalExit) {\n KMessageBox::sorry(this,\n i18n(\"The diff command failed. Please make sure that \"\n \"diff(1) is installed and in your PATH.\"),\n i18n(\"Error Creating Diff\"));\n delete m_diffFile;\n m_diffFile = 0;\n return;\n }\n\n if (m_diffFile->size() == 0) {\n KMessageBox::information(this,\n i18n(\"Ignoring amount of white space changed, the files are identical.\"),\n i18n(\"Diff Output\"));\n delete m_diffFile;\n m_diffFile = 0;\n return;\n }\n\n m_diffFile->setAutoRemove(false);\n QUrl url = QUrl::fromLocalFile(m_diffFile->fileName());\n delete m_diffFile;\n m_diffFile = 0;\n\n \/\/ KRun::runUrl should delete the file, once the client exits\n KRun::runUrl(url, QStringLiteral(\"text\/x-patch\"), this, true);\n}\n\nvoid KateMwModOnHdDialog::addDocument(KTextEditor::Document *doc)\n{\n for (QTreeWidgetItemIterator it(twDocuments); *it; ++it) {\n KateDocItem *item = (KateDocItem *) * it;\n if (item->document == doc) {\n delete item;\n break;\n }\n }\n uint reason = (uint)KateApp::self()->documentManager()->documentInfo(doc)->modifiedOnDiscReason;\n if (reason) {\n new KateDocItem(doc, m_stateTexts[reason], twDocuments);\n }\n\n if (! twDocuments->topLevelItemCount()) {\n accept();\n }\n}\n\nvoid KateMwModOnHdDialog::keyPressEvent(QKeyEvent *event)\n{\n if (event->modifiers() == 0) {\n if (event->key() == Qt::Key_Escape) {\n event->accept();\n return;\n }\n }\n QDialog::keyPressEvent(event);\n}\n\nvoid KateMwModOnHdDialog::closeEvent(QCloseEvent *e)\n{\n if (! twDocuments->topLevelItemCount()) {\n QDialog::closeEvent(e);\n } else {\n e->ignore();\n }\n}\n<commit_msg>kill process before deleting just in case<commit_after>\/*\n This library is free software; you can redistribute it and\/or\n modify it under the terms of the GNU Library General Public\n License version 2 as published by the Free Software Foundation.\n\n This library is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n Library General Public License for more details.\n\n You should have received a copy of the GNU Library General Public License\n along with this library; see the file COPYING.LIB. If not, write to\n the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,\n Boston, MA 02110-1301, USA.\n\n ---\n Copyright (C) 2004, Anders Lund <anders@alweb.dk>\n*\/\n\n#include \"katemwmodonhddialog.h\"\n\n#include \"kateapp.h\"\n#include \"katedocmanager.h\"\n#include \"katemainwindow.h\"\n\n#include <KMessageBox>\n#include <KProcess>\n#include <KRun>\n#include <KLocalizedString>\n#include <KIconLoader>\n\n#include <QTemporaryFile>\n#include <QTextStream>\n#include <QHeaderView>\n#include <QLabel>\n#include <QPushButton>\n\n#include <QTreeWidget>\n#include <QTreeWidgetItem>\n\nclass KateDocItem : public QTreeWidgetItem\n{\npublic:\n KateDocItem(KTextEditor::Document *doc, const QString &status, QTreeWidget *tw)\n : QTreeWidgetItem(tw),\n document(doc) {\n setText(0, doc->url().toString());\n setText(1, status);\n if (! doc->isModified()) {\n setCheckState(0, Qt::Checked);\n } else {\n setCheckState(0, Qt::Unchecked);\n }\n }\n ~KateDocItem()\n {}\n\n KTextEditor::Document *document;\n};\n\nKateMwModOnHdDialog::KateMwModOnHdDialog(DocVector docs, QWidget *parent, const char *name)\n : QDialog(parent),\n m_proc(0),\n m_diffFile(0)\n{\n setWindowTitle(i18n(\"Documents Modified on Disk\"));\n setObjectName(QString::fromLatin1(name));\n setModal(true);\n\n QVBoxLayout *mainLayout = new QVBoxLayout;\n setLayout(mainLayout);\n\n \/\/ Message\n QHBoxLayout *hb = new QHBoxLayout;\n mainLayout->addLayout(hb);\n\n \/\/ dialog text\n QLabel *icon = new QLabel(this);\n hb->addWidget(icon);\n icon->setPixmap(DesktopIcon(QStringLiteral(\"dialog-warning\")));\n\n QLabel *t = new QLabel(i18n(\n \"<qt>The documents listed below have changed on disk.<p>Select one \"\n \"or more at once, and press an action button until the list is empty.<\/p><\/qt>\"), this);\n hb->addWidget(t);\n hb->setStretchFactor(t, 1000);\n\n \/\/ Document list\n twDocuments = new QTreeWidget(this);\n mainLayout->addWidget(twDocuments);\n QStringList header;\n header << i18n(\"Filename\") << i18n(\"Status on Disk\");\n twDocuments->setHeaderLabels(header);\n twDocuments->setSelectionMode(QAbstractItemView::SingleSelection);\n twDocuments->setRootIsDecorated(false);\n\n m_stateTexts << QString() << i18n(\"Modified\") << i18n(\"Created\") << i18n(\"Deleted\");\n for (int i = 0; i < docs.size(); i++) {\n new KateDocItem(docs[i], m_stateTexts[(uint)KateApp::self()->documentManager()->documentInfo(docs[i])->modifiedOnDiscReason ], twDocuments);\n }\n twDocuments->header()->setStretchLastSection(false);\n twDocuments->header()->setSectionResizeMode(0, QHeaderView::Stretch);\n twDocuments->header()->setSectionResizeMode(1, QHeaderView::ResizeToContents);\n\n connect(twDocuments, &QTreeWidget::currentItemChanged, this, &KateMwModOnHdDialog::slotSelectionChanged);\n\n \/\/ Diff line\n hb = new QHBoxLayout;\n mainLayout->addLayout(hb);\n\n btnDiff = new QPushButton(QIcon::fromTheme(QStringLiteral(\"document-preview\")), i18n(\"&View Difference\"), this);\n btnDiff->setWhatsThis(i18n(\n \"Calculates the difference between the editor contents and the disk \"\n \"file for the selected document, and shows the difference with the \"\n \"default application. Requires diff(1).\"));\n hb->addWidget(btnDiff);\n connect(btnDiff, &QPushButton::clicked, this, &KateMwModOnHdDialog::slotDiff);\n\n \/\/ Dialog buttons\n QDialogButtonBox *buttons = new QDialogButtonBox(this);\n mainLayout->addWidget(buttons);\n\n QPushButton *ignoreButton = new QPushButton(QIcon::fromTheme(QStringLiteral(\"dialog-warning\")), i18n(\"&Ignore Changes\"));\n ignoreButton->setToolTip(i18n(\"Remove modified flag from selected documents\"));\n buttons->addButton(ignoreButton, QDialogButtonBox::RejectRole);\n connect(ignoreButton, &QPushButton::clicked, this, &KateMwModOnHdDialog::slotIgnore);\n\n QPushButton *overwriteButton = new QPushButton;\n KGuiItem::assign(overwriteButton, KStandardGuiItem::overwrite());\n overwriteButton->setToolTip(i18n(\"Overwrite selected documents, discarding disk changes\"));\n buttons->addButton(overwriteButton, QDialogButtonBox::DestructiveRole);\n connect(overwriteButton, &QPushButton::clicked, this, &KateMwModOnHdDialog::slotOverwrite);\n\n QPushButton *reloadButton = new QPushButton(QIcon::fromTheme(QStringLiteral(\"view-refresh\")), i18n(\"&Reload\"));\n reloadButton->setDefault(true);\n reloadButton->setToolTip(i18n(\"Reload selected documents from disk\"));\n buttons->addButton(reloadButton, QDialogButtonBox::DestructiveRole);\n connect(reloadButton, &QPushButton::clicked, this, &KateMwModOnHdDialog::slotReload);\n\n slotSelectionChanged(NULL, NULL);\n}\n\nKateMwModOnHdDialog::~KateMwModOnHdDialog()\n{\n KateMainWindow::unsetModifiedOnDiscDialogIfIf(this);\n m_proc->kill();\n m_proc->waitForFinished();\n delete m_proc;\n m_proc = 0;\n if (m_diffFile) {\n m_diffFile->setAutoRemove(true);\n delete m_diffFile;\n m_diffFile = 0;\n }\n}\n\nvoid KateMwModOnHdDialog::slotIgnore()\n{\n handleSelected(Ignore);\n}\n\nvoid KateMwModOnHdDialog::slotOverwrite()\n{\n handleSelected(Overwrite);\n}\n\nvoid KateMwModOnHdDialog::slotReload()\n{\n handleSelected(Reload);\n}\n\nvoid KateMwModOnHdDialog::handleSelected(int action)\n{\n \/\/ collect all items we can remove\n QList<QTreeWidgetItem *> itemsToDelete;\n for (QTreeWidgetItemIterator it(twDocuments); *it; ++it) {\n KateDocItem *item = (KateDocItem *) * it;\n if (item->checkState(0) == Qt::Checked) {\n KTextEditor::ModificationInterface::ModifiedOnDiskReason reason = KateApp::self()->documentManager()->documentInfo(item->document)->modifiedOnDiscReason;\n bool success = true;\n\n if (KTextEditor::ModificationInterface *iface = qobject_cast<KTextEditor::ModificationInterface *>(item->document)) {\n iface->setModifiedOnDisk(KTextEditor::ModificationInterface::OnDiskUnmodified);\n }\n\n switch (action) {\n case Overwrite:\n success = item->document->save();\n if (! success) {\n KMessageBox::sorry(this,\n i18n(\"Could not save the document \\n'%1'\",\n item->document->url().toString()));\n }\n break;\n\n case Reload:\n item->document->documentReload();\n break;\n\n default:\n break;\n }\n\n if (success) {\n itemsToDelete.append(item);\n } else {\n if (KTextEditor::ModificationInterface *iface = qobject_cast<KTextEditor::ModificationInterface *>(item->document)) {\n iface->setModifiedOnDisk(reason);\n }\n }\n }\n }\n\n \/\/ remove the marked items\n for (int i = 0; i < itemsToDelete.count(); ++i) {\n delete itemsToDelete[i];\n }\n\n\/\/ any documents left unhandled?\n if (! twDocuments->topLevelItemCount()) {\n accept();\n }\n}\n\nvoid KateMwModOnHdDialog::slotSelectionChanged(QTreeWidgetItem *current, QTreeWidgetItem *)\n{\n KateDocItem *currentDocItem = static_cast<KateDocItem *>(current);\n \/\/ set the diff button enabled\n btnDiff->setEnabled(currentDocItem &&\n KateApp::self()->documentManager()->documentInfo(currentDocItem->document)->modifiedOnDiscReason != KTextEditor::ModificationInterface::OnDiskDeleted);\n}\n\n\/\/ ### the code below is slightly modified from kdelibs\/kate\/part\/katedialogs,\n\/\/ class KateModOnHdPrompt.\nvoid KateMwModOnHdDialog::slotDiff()\n{\n if (!btnDiff->isEnabled()) { \/\/ diff button already pressed, proc not finished yet\n return;\n }\n\n if (! twDocuments->currentItem()) {\n return;\n }\n\n KTextEditor::Document *doc = (static_cast<KateDocItem *>(twDocuments->currentItem()))->document;\n\n \/\/ don't try to diff a deleted file\n if (KateApp::self()->documentManager()->documentInfo(doc)->modifiedOnDiscReason == KTextEditor::ModificationInterface::OnDiskDeleted) {\n return;\n }\n\n if (m_diffFile) {\n return;\n }\n\n m_diffFile = new QTemporaryFile();\n m_diffFile->open();\n\n \/\/ Start a KProcess that creates a diff\n m_proc = new KProcess(this);\n m_proc->setOutputChannelMode(KProcess::MergedChannels);\n *m_proc << QStringLiteral(\"diff\") << QStringLiteral(\"-ub\") << QStringLiteral(\"-\") << doc->url().toLocalFile();\n connect(m_proc, &KProcess::readyRead, this, &KateMwModOnHdDialog::slotDataAvailable);\n connect(m_proc, static_cast<void (KProcess::*)(int, QProcess::ExitStatus)>(&KProcess::finished), this, &KateMwModOnHdDialog::slotPDone);\n\n setCursor(Qt::WaitCursor);\n btnDiff->setEnabled(false);\n\n m_proc->start();\n\n QTextStream ts(m_proc);\n int lastln = doc->lines() - 1;\n for (int l = 0; l < lastln; ++l) {\n ts << doc->line(l) << QLatin1Char('\\n');\n }\n ts << doc->line(lastln);\n ts.flush();\n m_proc->closeWriteChannel();\n}\n\nvoid KateMwModOnHdDialog::slotDataAvailable()\n{\n m_diffFile->write(m_proc->readAll());\n}\n\nvoid KateMwModOnHdDialog::slotPDone()\n{\n setCursor(Qt::ArrowCursor);\n slotSelectionChanged(twDocuments->currentItem(), 0);\n\n const QProcess::ExitStatus es = m_proc->exitStatus();\n delete m_proc;\n m_proc = 0;\n\n if (es != QProcess::NormalExit) {\n KMessageBox::sorry(this,\n i18n(\"The diff command failed. Please make sure that \"\n \"diff(1) is installed and in your PATH.\"),\n i18n(\"Error Creating Diff\"));\n delete m_diffFile;\n m_diffFile = 0;\n return;\n }\n\n if (m_diffFile->size() == 0) {\n KMessageBox::information(this,\n i18n(\"Ignoring amount of white space changed, the files are identical.\"),\n i18n(\"Diff Output\"));\n delete m_diffFile;\n m_diffFile = 0;\n return;\n }\n\n m_diffFile->setAutoRemove(false);\n QUrl url = QUrl::fromLocalFile(m_diffFile->fileName());\n delete m_diffFile;\n m_diffFile = 0;\n\n \/\/ KRun::runUrl should delete the file, once the client exits\n KRun::runUrl(url, QStringLiteral(\"text\/x-patch\"), this, true);\n}\n\nvoid KateMwModOnHdDialog::addDocument(KTextEditor::Document *doc)\n{\n for (QTreeWidgetItemIterator it(twDocuments); *it; ++it) {\n KateDocItem *item = (KateDocItem *) * it;\n if (item->document == doc) {\n delete item;\n break;\n }\n }\n uint reason = (uint)KateApp::self()->documentManager()->documentInfo(doc)->modifiedOnDiscReason;\n if (reason) {\n new KateDocItem(doc, m_stateTexts[reason], twDocuments);\n }\n\n if (! twDocuments->topLevelItemCount()) {\n accept();\n }\n}\n\nvoid KateMwModOnHdDialog::keyPressEvent(QKeyEvent *event)\n{\n if (event->modifiers() == 0) {\n if (event->key() == Qt::Key_Escape) {\n event->accept();\n return;\n }\n }\n QDialog::keyPressEvent(event);\n}\n\nvoid KateMwModOnHdDialog::closeEvent(QCloseEvent *e)\n{\n if (! twDocuments->topLevelItemCount()) {\n QDialog::closeEvent(e);\n } else {\n e->ignore();\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/***************************Copyright-DO-NOT-REMOVE-THIS-LINE**\n * CONDOR Copyright Notice\n *\n * See LICENSE.TXT for additional notices and disclaimers.\n *\n * Copyright (c)1990-1998 CONDOR Team, Computer Sciences Department, \n * University of Wisconsin-Madison, Madison, WI. All Rights Reserved. \n * No use of the CONDOR Software Program Source Code is authorized \n * without the express consent of the CONDOR Team. For more information \n * contact: CONDOR Team, Attention: Professor Miron Livny, \n * 7367 Computer Sciences, 1210 W. Dayton St., Madison, WI 53706-1685, \n * (608) 262-0856 or miron@cs.wisc.edu.\n *\n * U.S. Government Rights Restrictions: Use, duplication, or disclosure \n * by the U.S. Government is subject to restrictions as set forth in \n * subparagraph (c)(1)(ii) of The Rights in Technical Data and Computer \n * Software clause at DFARS 252.227-7013 or subparagraphs (c)(1) and \n * (2) of Commercial Computer Software-Restricted Rights at 48 CFR \n * 52.227-19, as applicable, CONDOR Team, Attention: Professor Miron \n * Livny, 7367 Computer Sciences, 1210 W. Dayton St., Madison, \n * WI 53706-1685, (608) 262-0856 or miron@cs.wisc.edu.\n****************************Copyright-DO-NOT-REMOVE-THIS-LINE**\/\n#include \"condor_common.h\"\n#include \"condor_config.h\"\n#include \"condor_classad.h\"\n#include \"condor_debug.h\"\n#include \"condor_attributes.h\"\n#include \"condor_distribution.h\"\n\n#include \"MyString.h\"\n\n\/\/------------------------------------------------------------------------\n\nstatic void displayJobShort(AttrList* ad);\nstatic void short_header(void);\nstatic void short_print(int,int,const char*,int,int,int,int,int,int,const char *);\nstatic void short_header (void);\nstatic void shorten (char *, int);\nstatic char* format_date( time_t date );\nstatic char* format_time( int tot_secs );\nstatic char encode_status( int status );\nstatic bool EvalBool(AttrList *ad, ExprTree *tree);\n\n\n\/\/------------------------------------------------------------------------\n\nstatic void Usage(char* name) \n{\n printf(\"Usage: %s [-l] [-f history-filename] [-constraint expr | cluster_id | cluster_id.proc_id | owner]\\n\",name);\n exit(1);\n}\n\n\/\/------------------------------------------------------------------------\n\nmain(int argc, char* argv[])\n{\n char* JobHistoryFileName=NULL;\n int LongFormat=FALSE;\n char* constraint=NULL;\n ExprTree *constraintExpr=NULL;\n int cluster, proc;\n char tmp[512];\n int i;\n myDistro->Init( argc, argv );\n\n for(i=1; i<argc; i++) {\n if (strcmp(argv[i],\"-l\")==0) {\n LongFormat=TRUE; \n }\n else if (strcmp(argv[i],\"-f\")==0) {\n if (i+1==argc || JobHistoryFileName) break;\n i++;\n\t JobHistoryFileName=argv[i];\n }\n else if (strcmp(argv[i],\"-help\")==0) {\n\t Usage(argv[0]);\n }\n else if (strcmp(argv[i],\"-constraint\")==0) {\n if (i+1==argc || constraint) break;\n sprintf(tmp,\"(%s)\",argv[i+1]);\n constraint=tmp;\n i++;\n }\n else if (sscanf (argv[i], \"%d.%d\", &cluster, &proc) == 2) {\n if (constraint) break;\n sprintf (tmp, \"((%s == %d) && (%s == %d))\", \n ATTR_CLUSTER_ID, cluster,ATTR_PROC_ID, proc);\n constraint=tmp;\n }\n else if (sscanf (argv[i], \"%d\", &cluster) == 1) {\n if (constraint) break;\n sprintf (tmp, \"(%s == %d)\", ATTR_CLUSTER_ID, cluster);\n constraint=tmp;\n }\n else {\n if (constraint) break;\n sprintf(tmp, \"(%s == \\\"%s\\\")\", ATTR_OWNER, argv[i]);\n constraint=tmp;\n }\n }\n if (i<argc) Usage(argv[0]);\n\nif (constraint) puts(constraint);\n\n config();\n if (!JobHistoryFileName) {\n JobHistoryFileName=param(\"HISTORY\");\n }\n\n FILE* LogFile=fopen(JobHistoryFileName,\"r\");\n if (!LogFile) {\n fprintf(stderr,\"History file not found or empty.\\n\");\n exit(1);\n }\n\n \/\/ printf(\"HistroyFile=%s\\nLongFormat=%d\\n\",JobHistoryFileName,LongFormat);\n \/\/ if (constraint) printf(\"constraint=%s\\n\",constraint);\n\n if( constraint && Parse( constraint, constraintExpr ) ) {\n fprintf( stderr, \"Error: could not parse constraint %s\\n\", constraint );\n exit( 1 );\n }\n\n int EndFlag=0;\n int ErrorFlag=0;\n int EmptyFlag=0;\n AttrList *ad=0;\n if (!LongFormat) short_header();\n while(!EndFlag) {\n if( !( ad=new AttrList(LogFile,\"***\", EndFlag, ErrorFlag, EmptyFlag) ) ){\n fprintf( stderr, \"Error: Out of memory\\n\" );\n exit( 1 );\n } \n if( ErrorFlag ) {\n printf( \"\\t*** Warning: Bad history file; skipping malformed ad(s)\\n\" );\n ErrorFlag=0;\n delete ad;\n continue;\n } \n\tif( EmptyFlag ) {\n EmptyFlag=0;\n delete ad;\n continue;\n }\n if (!constraint || EvalBool(ad, constraintExpr)) {\n if (LongFormat) { \n\t ad->fPrint(stdout); printf(\"\\n\"); \n\t } else {\n displayJobShort(ad);\n\t }\n }\n delete ad;\n }\n \n fclose(LogFile);\n exit(0);\n}\n\n\/\/------------------------------------------------------------------------\n\nstatic void\ndisplayJobShort(AttrList* ad)\n{\n int cluster, proc, date, status, prio, image_size, CompDate;\n float utime;\n char owner[64], cmd[2048], args[2048];\n\n\tif(!ad->EvalFloat(ATTR_JOB_REMOTE_WALL_CLOCK,NULL,utime)) {\n\t\tif(!ad->EvalFloat(ATTR_JOB_REMOTE_USER_CPU,NULL,utime)) {\n\t\t\tutime = 0;\n\t\t}\n\t}\n\n if (!ad->EvalInteger (ATTR_CLUSTER_ID, NULL, cluster) ||\n !ad->EvalInteger (ATTR_PROC_ID, NULL, proc) ||\n !ad->EvalInteger (ATTR_Q_DATE, NULL, date) ||\n !ad->EvalInteger (ATTR_COMPLETION_DATE, NULL, CompDate)\t||\n !ad->EvalInteger (ATTR_JOB_STATUS, NULL, status) ||\n !ad->EvalInteger (ATTR_JOB_PRIO, NULL, prio) ||\n !ad->EvalInteger (ATTR_IMAGE_SIZE, NULL, image_size) ||\n !ad->EvalString (ATTR_OWNER, NULL, owner) ||\n !ad->EvalString (ATTR_JOB_CMD, NULL, cmd) )\n {\n printf (\" --- ???? --- \\n\");\n return;\n }\n \n shorten (owner, 14);\n if (ad->EvalString (\"Args\", NULL, args)) strcat (cmd, args);\n shorten (cmd, 15);\n short_print (cluster, proc, owner, date, CompDate, (int)utime, status, \n prio, image_size, cmd); \n\n}\n\n\/\/------------------------------------------------------------------------\n\nstatic void\nshort_header (void)\n{\n printf( \" %-7s %-14s %11s %12s %-2s %11s %-15s\\n\",\n \"ID\",\n \"OWNER\",\n \"SUBMITTED\",\n \"RUN_TIME\",\n \"ST\",\n\t\t\"COMPLETED\",\n \"CMD\"\n );\n}\n\n\/\/------------------------------------------------------------------------\n\nstatic void\nshorten (char *buff, int len)\n{\n if ((unsigned int)strlen (buff) > (unsigned int)len) buff[len] = '\\0';\n}\n\n\/\/------------------------------------------------------------------------\n\n\/*\n Print a line of data for the \"short\" display of a PROC structure. The\n \"short\" display is the one used by \"condor_q\". N.B. the columns used\n by this routine must match those defined by the short_header routine\n defined above.\n*\/\n\nstatic void\nshort_print(\n int cluster,\n int proc,\n const char *owner,\n int date,\n\t\tint CompDate,\n int time,\n int status,\n int prio,\n int image_size,\n const char *cmd\n ) {\n\t\tMyString SubmitDateStr=format_date(date);\n\t\tMyString CompDateStr=format_date(CompDate);\n printf( \"%4d.%-3d %-14s %-11s %-12s %-2c %-11s %-15s\\n\",\n cluster,\n proc,\n owner,\n SubmitDateStr.Value(),\n format_time(time),\n encode_status(status),\n CompDateStr.Value(),\n cmd\n );\n}\n\n\n\/\/------------------------------------------------------------------------\n\n\/*\n Format a date expressed in \"UNIX time\" into \"month\/day hour:minute\".\n*\/\n\nstatic char* format_date( time_t date )\n{\n static char buf[ 12 ];\n struct tm *tm;\n\n\t\tif (date==0) return \" ??? \";\n\n tm = localtime( &date );\n sprintf( buf, \"%2d\/%-2d %02d:%02d\",\n (tm->tm_mon)+1, tm->tm_mday, tm->tm_hour, tm->tm_min\n );\n return buf;\n}\n\n\/\/------------------------------------------------------------------------\n\n\/*\n Format a time value which is encoded as seconds since the UNIX\n \"epoch\". We return a string in the format dd+hh:mm:ss, indicating\n days, hours, minutes, and seconds. The string is in static data\n space, and will be overwritten by the next call to this function.\n*\/\n\nstatic char *\nformat_time( int tot_secs )\n{\n int days;\n int hours;\n int min;\n int secs;\n static char answer[25];\n\n\t\tif ( tot_secs < 0 ) {\n\t\t\tsprintf(answer,\"[?????]\");\n\t\t\treturn answer;\n\t\t}\n\n days = tot_secs \/ DAY;\n tot_secs %= DAY;\n hours = tot_secs \/ HOUR;\n tot_secs %= HOUR;\n min = tot_secs \/ MINUTE;\n secs = tot_secs % MINUTE;\n\n (void)sprintf( answer, \"%3d+%02d:%02d:%02d\", days, hours, min, secs );\n return answer;\n}\n\n\/\/------------------------------------------------------------------------\n\n\/*\n Encode a status from a PROC structure as a single letter suited for\n printing.\n*\/\n\nstatic char\nencode_status( int status )\n{\n switch( status ) {\n case UNEXPANDED:\n return 'U';\n case IDLE:\n return 'I';\n case RUNNING:\n return 'R';\n case COMPLETED:\n return 'C';\n case REMOVED:\n return 'X';\n default:\n return ' ';\n }\n}\n\n\/\/------------------------------------------------------------------------\n\nstatic bool EvalBool(AttrList* ad, ExprTree *tree)\n{\n\tEvalResult result;\n\n \/\/ Evaluate constraint with ad in the target scope so that constraints\n \/\/ have the same semantics as the collector queries. --RR\n if (!tree->EvalTree(NULL, ad, &result)) {\n \/\/ dprintf(D_ALWAYS, \"can't evaluate constraint: %s\\n\", constraint);\n delete tree;\n return false;\n }\n \n if (result.type == LX_INTEGER) {\n return (bool)result.i;\n }\n\n return false;\n}\n\n<commit_msg>Upgraded condor_history to use new ClassAds style parsing and replaces all occurrences of AttrLists with ClassAds<commit_after>\/***************************Copyright-DO-NOT-REMOVE-THIS-LINE**\n * CONDOR Copyright Notice\n *\n * See LICENSE.TXT for additional notices and disclaimers.\n *\n * Copyright (c)1990-1998 CONDOR Team, Computer Sciences Department, \n * University of Wisconsin-Madison, Madison, WI. All Rights Reserved. \n * No use of the CONDOR Software Program Source Code is authorized \n * without the express consent of the CONDOR Team. For more information \n * contact: CONDOR Team, Attention: Professor Miron Livny, \n * 7367 Computer Sciences, 1210 W. Dayton St., Madison, WI 53706-1685, \n * (608) 262-0856 or miron@cs.wisc.edu.\n *\n * U.S. Government Rights Restrictions: Use, duplication, or disclosure \n * by the U.S. Government is subject to restrictions as set forth in \n * subparagraph (c)(1)(ii) of The Rights in Technical Data and Computer \n * Software clause at DFARS 252.227-7013 or subparagraphs (c)(1) and \n * (2) of Commercial Computer Software-Restricted Rights at 48 CFR \n * 52.227-19, as applicable, CONDOR Team, Attention: Professor Miron \n * Livny, 7367 Computer Sciences, 1210 W. Dayton St., Madison, \n * WI 53706-1685, (608) 262-0856 or miron@cs.wisc.edu.\n****************************Copyright-DO-NOT-REMOVE-THIS-LINE**\/\n#include \"condor_common.h\"\n#include \"condor_config.h\"\n#include \"condor_classad.h\"\n#include \"condor_debug.h\"\n#include \"condor_attributes.h\"\n#include \"condor_distribution.h\"\n\n#include \"MyString.h\"\n\n\/\/------------------------------------------------------------------------\n\nstatic void displayJobShort(ClassAd* ad);\nstatic void short_header(void);\nstatic void short_print(int,int,const char*,int,int,int,int,int,int,const char *);\nstatic void short_header (void);\nstatic void shorten (char *, int);\nstatic char* format_date( time_t date );\nstatic char* format_time( int tot_secs );\nstatic char encode_status( int status );\nstatic bool EvalBool(ClassAd *ad, ExprTree *tree);\n\n\/\/------------------------------------------------------------------------\n\nstatic void Usage(char* name) \n{\n printf(\"Usage: %s [-l] [-f history-filename] [-constraint expr | cluster_id | cluster_id.proc_id | owner]\\n\",name);\n exit(1);\n}\n\n\/\/------------------------------------------------------------------------\n\nmain(int argc, char* argv[])\n{\n char* JobHistoryFileName=NULL;\n int LongFormat=FALSE;\n char* constraint=NULL;\n ExprTree *constraintExpr=NULL;\n int cluster, proc;\n char tmp[512];\n int i;\n myDistro->Init( argc, argv );\n\n for(i=1; i<argc; i++) {\n if (strcmp(argv[i],\"-l\")==0) {\n LongFormat=TRUE; \n }\n else if (strcmp(argv[i],\"-f\")==0) {\n if (i+1==argc || JobHistoryFileName) break;\n i++;\n\t JobHistoryFileName=argv[i];\n }\n else if (strcmp(argv[i],\"-help\")==0) {\n\t Usage(argv[0]);\n }\n else if (strcmp(argv[i],\"-constraint\")==0) {\n if (i+1==argc || constraint) break;\n sprintf(tmp,\"(%s)\",argv[i+1]);\n constraint=tmp;\n i++;\n }\n else if (sscanf (argv[i], \"%d.%d\", &cluster, &proc) == 2) {\n if (constraint) break;\n sprintf (tmp, \"((%s == %d) && (%s == %d))\", \n ATTR_CLUSTER_ID, cluster,ATTR_PROC_ID, proc);\n constraint=tmp;\n }\n else if (sscanf (argv[i], \"%d\", &cluster) == 1) {\n if (constraint) break;\n sprintf (tmp, \"(%s == %d)\", ATTR_CLUSTER_ID, cluster);\n constraint=tmp;\n }\n else {\n if (constraint) break;\n sprintf(tmp, \"(%s == \\\"%s\\\")\", ATTR_OWNER, argv[i]);\n constraint=tmp;\n }\n }\n if (i<argc) Usage(argv[0]);\n\nif (constraint) puts(constraint);\n\n config();\n if (!JobHistoryFileName) {\n JobHistoryFileName=param(\"HISTORY\");\n }\n\n FILE* LogFile=fopen(JobHistoryFileName,\"r\");\n if (!LogFile) {\n fprintf(stderr,\"History file not found or empty.\\n\");\n exit(1);\n }\n\n \/\/ printf(\"HistroyFile=%s\\nLongFormat=%d\\n\",JobHistoryFileName,LongFormat);\n \/\/ if (constraint) printf(\"constraint=%s\\n\",constraint);\n\n ClassAdParser parser;\t\/\/ NAC\n if( constraint && parser.ParseExpression( constraint, constraintExpr )){\/\/NAC\n\t fprintf( stderr, \"Error: could not parse constraint %s\\n\", constraint );\n exit( 1 );\n }\n\n int EndFlag=0;\n int ErrorFlag=0;\n int EmptyFlag=0;\n ClassAd *ad=0;\n if (!LongFormat) short_header();\n while(!EndFlag) {\n if( !( ad=new ClassAd(LogFile,\"***\", EndFlag, ErrorFlag, EmptyFlag) ) ){\n fprintf( stderr, \"Error: Out of memory\\n\" );\n exit( 1 );\n } \n if( ErrorFlag ) {\n printf( \"\\t*** Warning: Bad history file; skipping malformed ad(s)\\n\" );\n ErrorFlag=0;\n delete ad;\n continue;\n } \n\tif( EmptyFlag ) {\n EmptyFlag=0;\n delete ad;\n continue;\n }\n if (!constraint || EvalBool(ad, constraintExpr)) {\n if (LongFormat) { \n\t ad->fPrint(stdout); printf(\"\\n\"); \n\t } else {\n displayJobShort(ad);\n\t }\n }\n delete ad;\n }\n \n fclose(LogFile);\n exit(0);\n}\n\n\/\/------------------------------------------------------------------------\n\nstatic void\ndisplayJobShort(ClassAd* ad)\n{\n int cluster, proc, date, status, prio, image_size, CompDate;\n float utime;\n char owner[64], cmd[2048], args[2048];\n\n\tif(!ad->EvalFloat(ATTR_JOB_REMOTE_WALL_CLOCK,NULL,utime)) {\n\t\tif(!ad->EvalFloat(ATTR_JOB_REMOTE_USER_CPU,NULL,utime)) {\n\t\t\tutime = 0;\n\t\t}\n\t}\n\n if (!ad->EvalInteger (ATTR_CLUSTER_ID, NULL, cluster) ||\n !ad->EvalInteger (ATTR_PROC_ID, NULL, proc) ||\n !ad->EvalInteger (ATTR_Q_DATE, NULL, date) ||\n !ad->EvalInteger (ATTR_COMPLETION_DATE, NULL, CompDate)\t||\n !ad->EvalInteger (ATTR_JOB_STATUS, NULL, status) ||\n !ad->EvalInteger (ATTR_JOB_PRIO, NULL, prio) ||\n !ad->EvalInteger (ATTR_IMAGE_SIZE, NULL, image_size) ||\n !ad->EvalString (ATTR_OWNER, NULL, owner) ||\n !ad->EvalString (ATTR_JOB_CMD, NULL, cmd) )\n {\n printf (\" --- ???? --- \\n\");\n return;\n }\n \n shorten (owner, 14);\n if (ad->EvalString (\"Args\", NULL, args)) strcat (cmd, args);\n shorten (cmd, 15);\n short_print (cluster, proc, owner, date, CompDate, (int)utime, status, \n prio, image_size, cmd); \n\n}\n\n\/\/------------------------------------------------------------------------\n\nstatic void\nshort_header (void)\n{\n printf( \" %-7s %-14s %11s %12s %-2s %11s %-15s\\n\",\n \"ID\",\n \"OWNER\",\n \"SUBMITTED\",\n \"RUN_TIME\",\n \"ST\",\n\t\t\"COMPLETED\",\n \"CMD\"\n );\n}\n\n\/\/------------------------------------------------------------------------\n\nstatic void\nshorten (char *buff, int len)\n{\n if ((unsigned int)strlen (buff) > (unsigned int)len) buff[len] = '\\0';\n}\n\n\/\/------------------------------------------------------------------------\n\n\/*\n Print a line of data for the \"short\" display of a PROC structure. The\n \"short\" display is the one used by \"condor_q\". N.B. the columns used\n by this routine must match those defined by the short_header routine\n defined above.\n*\/\n\nstatic void\nshort_print(\n int cluster,\n int proc,\n const char *owner,\n int date,\n\t\tint CompDate,\n int time,\n int status,\n int prio,\n int image_size,\n const char *cmd\n ) {\n\t\tMyString SubmitDateStr=format_date(date);\n\t\tMyString CompDateStr=format_date(CompDate);\n printf( \"%4d.%-3d %-14s %-11s %-12s %-2c %-11s %-15s\\n\",\n cluster,\n proc,\n owner,\n SubmitDateStr.Value(),\n format_time(time),\n encode_status(status),\n CompDateStr.Value(),\n cmd\n );\n}\n\n\n\/\/------------------------------------------------------------------------\n\n\/*\n Format a date expressed in \"UNIX time\" into \"month\/day hour:minute\".\n*\/\n\nstatic char* format_date( time_t date )\n{\n static char buf[ 12 ];\n struct tm *tm;\n\n\t\tif (date==0) return \" ??? \";\n\n tm = localtime( &date );\n sprintf( buf, \"%2d\/%-2d %02d:%02d\",\n (tm->tm_mon)+1, tm->tm_mday, tm->tm_hour, tm->tm_min\n );\n return buf;\n}\n\n\/\/------------------------------------------------------------------------\n\n\/*\n Format a time value which is encoded as seconds since the UNIX\n \"epoch\". We return a string in the format dd+hh:mm:ss, indicating\n days, hours, minutes, and seconds. The string is in static data\n space, and will be overwritten by the next call to this function.\n*\/\n\nstatic char *\nformat_time( int tot_secs )\n{\n int days;\n int hours;\n int min;\n int secs;\n static char answer[25];\n\n\t\tif ( tot_secs < 0 ) {\n\t\t\tsprintf(answer,\"[?????]\");\n\t\t\treturn answer;\n\t\t}\n\n days = tot_secs \/ DAY;\n tot_secs %= DAY;\n hours = tot_secs \/ HOUR;\n tot_secs %= HOUR;\n min = tot_secs \/ MINUTE;\n secs = tot_secs % MINUTE;\n\n (void)sprintf( answer, \"%3d+%02d:%02d:%02d\", days, hours, min, secs );\n return answer;\n}\n\n\/\/------------------------------------------------------------------------\n\n\/*\n Encode a status from a PROC structure as a single letter suited for\n printing.\n*\/\n\nstatic char\nencode_status( int status )\n{\n switch( status ) {\n case UNEXPANDED:\n return 'U';\n case IDLE:\n return 'I';\n case RUNNING:\n return 'R';\n case COMPLETED:\n return 'C';\n case REMOVED:\n return 'X';\n default:\n return ' ';\n }\n}\n\n\/\/------------------------------------------------------------------------\n\nstatic bool EvalBool(ClassAd* ad, ExprTree *tree)\t\/\/ NAC\n{\n\tValue result;\n\tbool boolValue;\n\tif( !ad->EvaluateExpr( tree, result ) ) {\n\t\tdelete tree;\n\t\treturn false;\n\t}\n\tif( result.IsBooleanValue( boolValue ) ) {\n\t\treturn boolValue;\n\t}\n\t\n\treturn false;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*!\n * \\file rounded_rect.hpp\n * \\brief file rounded_rect.hpp\n *\n * Copyright 2018 by Intel.\n *\n * Contact: kevin.rogovin@intel.com\n *\n * This Source Code Form is subject to the\n * terms of the Mozilla Public License, v. 2.0.\n * If a copy of the MPL was not distributed with\n * this file, You can obtain one at\n * http:\/\/mozilla.org\/MPL\/2.0\/.\n *\n * \\author Kevin Rogovin <kevin.rogovin@intel.com>\n *\n *\/\n\n#pragma once\n\n#include <fastuidraw\/util\/vecN.hpp>\n\nnamespace fastuidraw\n{\n\/*!\\addtogroup Painter\n * @{\n *\/\n\n \/*!\n * Class to specify the geometry of a rounded rectangle.\n *\/\n class Rect\n {\n public:\n \/*!\n * Conveniance enumeration to name the rounded corner\n * radii of a RoundedRect.\n *\/\n enum corner_t\n {\n minx_miny_corner,\n minx_maxy_corner,\n maxx_miny_corner,\n maxx_maxy_corner,\n };\n\n \/*!\n * Empty ctor; intializes both \\ref m_min_point and\n * \\ref m_max_point to (0, 0);\n *\/\n Rect(void):\n m_min_point(0.0f, 0.0f),\n m_max_point(0.0f, 0.0f)\n {}\n\n \/*!\n * Set \\ref m_min_point.\n *\/\n Rect&\n min_point(const vec2 &p)\n {\n m_min_point = p;\n return *this;\n }\n\n \/*!\n * Set \\ref m_min_point.\n *\/\n Rect&\n min_point(float x, float y)\n {\n m_min_point.x() = x;\n m_min_point.y() = y;\n return *this;\n }\n\n \/*!\n * Set \\ref m_max_point.\n *\/\n Rect&\n max_point(const vec2 &p)\n {\n m_max_point = p;\n return *this;\n }\n\n \/*!\n * Set \\ref m_max_point.\n *\/\n Rect&\n max_point(float x, float y)\n {\n m_max_point.x() = x;\n m_max_point.y() = y;\n return *this;\n }\n\n \/*!\n * Set \\ref m_max_point from \\ref m_min_point\n * and a size. Equivalent to\n * \\code\n * max_point(min_point() + sz)\n * \\endcode\n * \\param sz size to which to set the Rect\n *\/\n Rect&\n size(const vec2 &sz)\n {\n m_max_point = m_min_point + sz;\n return *this;\n }\n\n \/*!\n * Set \\ref m_max_point from \\ref m_min_point\n * and a size. Equivalent to\n * \\code\n * max_point(min_point() + vec2(width, height))\n * \\endcode\n * \\param width width to which to set the rect\n * \\param height height to which to set the rect\n *\/\n Rect&\n size(float width, float height)\n {\n m_max_point.x() = m_min_point.x() + width;\n m_max_point.y() = m_min_point.y() + height;\n return *this;\n }\n\n \/*!\n * Returns the size of the Rect; provided as\n * a conveniance, equivalent to\n * \\code\n * m_max_point - m_min_point\n * \\endcode\n *\/\n vec2\n size(void) const\n {\n return m_max_point - m_min_point;\n }\n\n \/*!\n * Returns the width of the Rect, equivalent to\n * \\code\n * m_max_point.x() - m_min_point.x();\n * \\endcode\n *\/\n float\n width(void) const\n {\n return m_max_point.x() - m_min_point.x();\n }\n\n \/*!\n * Returns the width of the Rect, equivalent to\n * \\code\n * m_max_point.y() - m_min_point.y();\n * \\endcode\n *\/\n float\n height(void) const\n {\n return m_max_point.y() - m_min_point.y();\n }\n\n \/*!\n * Specifies the min-corner of the rectangle\n *\/\n vec2 m_min_point;\n\n \/*!\n * Specifies the max-corner of the rectangle.\n *\/\n vec2 m_max_point;\n };\n\/*! @} *\/\n}\n<commit_msg>fastuidraw\/painter\/rect: more methods of conveniance<commit_after>\/*!\n * \\file rounded_rect.hpp\n * \\brief file rounded_rect.hpp\n *\n * Copyright 2018 by Intel.\n *\n * Contact: kevin.rogovin@intel.com\n *\n * This Source Code Form is subject to the\n * terms of the Mozilla Public License, v. 2.0.\n * If a copy of the MPL was not distributed with\n * this file, You can obtain one at\n * http:\/\/mozilla.org\/MPL\/2.0\/.\n *\n * \\author Kevin Rogovin <kevin.rogovin@intel.com>\n *\n *\/\n\n#pragma once\n\n#include <fastuidraw\/util\/vecN.hpp>\n\nnamespace fastuidraw\n{\n\/*!\\addtogroup Painter\n * @{\n *\/\n\n \/*!\n * Class to specify the geometry of a rounded rectangle.\n *\/\n class Rect\n {\n public:\n \/*!\n * Conveniance enumeration to name the rounded corner\n * radii of a RoundedRect.\n *\/\n enum corner_t\n {\n minx_miny_corner,\n minx_maxy_corner,\n maxx_miny_corner,\n maxx_maxy_corner,\n };\n\n \/*!\n * Empty ctor; intializes both \\ref m_min_point and\n * \\ref m_max_point to (0, 0);\n *\/\n Rect(void):\n m_min_point(0.0f, 0.0f),\n m_max_point(0.0f, 0.0f)\n {}\n\n \/*!\n * Set \\ref m_min_point.\n *\/\n Rect&\n min_point(const vec2 &p)\n {\n m_min_point = p;\n return *this;\n }\n\n \/*!\n * Set \\ref m_min_point.\n *\/\n Rect&\n min_point(float x, float y)\n {\n m_min_point.x() = x;\n m_min_point.y() = y;\n return *this;\n }\n\n \/*!\n * Set \\ref m_max_point.\n *\/\n Rect&\n max_point(const vec2 &p)\n {\n m_max_point = p;\n return *this;\n }\n\n \/*!\n * Set \\ref m_max_point.\n *\/\n Rect&\n max_point(float x, float y)\n {\n m_max_point.x() = x;\n m_max_point.y() = y;\n return *this;\n }\n\n \/*!\n * Translate the Rect, equivalent to\n * \\code\n * m_min_point += tr;\n * m_max_point += tr;\n * \\endcode\n * \\param tr amount by which to transate\n *\/\n Rect&\n translate(const vec2 &tr)\n {\n m_min_point += tr;\n m_max_point += tr;\n return *this;\n }\n\n \/*!\n * Translate the Rect, equivalent to\n * \\code\n * translate(vec2(x, y))\n * \\endcode\n * \\param tr amount by which to transate\n *\/\n Rect&\n translate(float x, float y)\n {\n return translate(vec2(x,y));\n }\n\n \/*!\n * Set \\ref m_max_point from \\ref m_min_point\n * and a size. Equivalent to\n * \\code\n * max_point(min_point() + sz)\n * \\endcode\n * \\param sz size to which to set the Rect\n *\/\n Rect&\n size(const vec2 &sz)\n {\n m_max_point = m_min_point + sz;\n return *this;\n }\n\n \/*!\n * Set \\ref m_max_point from \\ref m_min_point\n * and a size. Equivalent to\n * \\code\n * max_point(min_point() + vec2(width, height))\n * \\endcode\n * \\param width width to which to set the rect\n * \\param height height to which to set the rect\n *\/\n Rect&\n size(float width, float height)\n {\n m_max_point.x() = m_min_point.x() + width;\n m_max_point.y() = m_min_point.y() + height;\n return *this;\n }\n\n \/*!\n * Returns the size of the Rect; provided as\n * a conveniance, equivalent to\n * \\code\n * m_max_point - m_min_point\n * \\endcode\n *\/\n vec2\n size(void) const\n {\n return m_max_point - m_min_point;\n }\n\n \/*!\n * Set the width of the Rect, equivalent to\n * \\code\n * m_max_point.x() = w + m_min_point.x();\n * \\endcode\n * \\param w value to make the width of the rect\n *\/\n Rect&\n width(float w)\n {\n m_max_point.x() = w + m_min_point.x();\n return *this;\n }\n\n \/*!\n * Set the height of the Rect, equivalent to\n * \\code\n * m_max_point.y() = h + m_min_point.y();\n * \\endcode\n * \\param h value to make the height of the rect\n *\/\n Rect&\n height(float h)\n {\n m_max_point.y() = h + m_min_point.y();\n return *this;\n }\n\n \/*!\n * Returns the width of the Rect, equivalent to\n * \\code\n * m_max_point.x() - m_min_point.x();\n * \\endcode\n *\/\n float\n width(void) const\n {\n return m_max_point.x() - m_min_point.x();\n }\n\n \/*!\n * Returns the width of the Rect, equivalent to\n * \\code\n * m_max_point.y() - m_min_point.y();\n * \\endcode\n *\/\n float\n height(void) const\n {\n return m_max_point.y() - m_min_point.y();\n }\n\n \/*!\n * Specifies the min-corner of the rectangle\n *\/\n vec2 m_min_point;\n\n \/*!\n * Specifies the max-corner of the rectangle.\n *\/\n vec2 m_max_point;\n };\n\/*! @} *\/\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/===-- cc1as_main.cpp - Clang Assembler ---------------------------------===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This is the entry point to the clang -cc1as functionality, which implements\n\/\/ the direct interface to the LLVM MC based assembler.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"clang\/Basic\/Diagnostic.h\"\n#include \"clang\/Driver\/Arg.h\"\n#include \"clang\/Driver\/ArgList.h\"\n#include \"clang\/Driver\/DriverDiagnostic.h\"\n#include \"clang\/Driver\/CC1AsOptions.h\"\n#include \"clang\/Driver\/OptTable.h\"\n#include \"clang\/Driver\/Options.h\"\n#include \"clang\/Frontend\/DiagnosticOptions.h\"\n#include \"clang\/Frontend\/FrontendDiagnostic.h\"\n#include \"clang\/Frontend\/TextDiagnosticPrinter.h\"\n#include \"llvm\/ADT\/OwningPtr.h\"\n#include \"llvm\/ADT\/StringSwitch.h\"\n#include \"llvm\/ADT\/Triple.h\"\n#include \"llvm\/MC\/MCParser\/MCAsmParser.h\"\n#include \"llvm\/MC\/MCAsmInfo.h\"\n#include \"llvm\/MC\/MCCodeEmitter.h\"\n#include \"llvm\/MC\/MCContext.h\"\n#include \"llvm\/MC\/MCInstrInfo.h\"\n#include \"llvm\/MC\/MCObjectFileInfo.h\"\n#include \"llvm\/MC\/MCRegisterInfo.h\"\n#include \"llvm\/MC\/MCStreamer.h\"\n#include \"llvm\/MC\/MCSubtargetInfo.h\"\n#include \"llvm\/MC\/MCAsmBackend.h\"\n#include \"llvm\/MC\/MCTargetAsmParser.h\"\n#include \"llvm\/Support\/CommandLine.h\"\n#include \"llvm\/Support\/FormattedStream.h\"\n#include \"llvm\/Support\/ErrorHandling.h\"\n#include \"llvm\/Support\/ManagedStatic.h\"\n#include \"llvm\/Support\/MemoryBuffer.h\"\n#include \"llvm\/Support\/PrettyStackTrace.h\"\n#include \"llvm\/Support\/SourceMgr.h\"\n#include \"llvm\/Support\/Host.h\"\n#include \"llvm\/Support\/Path.h\"\n#include \"llvm\/Support\/Signals.h\"\n#include \"llvm\/Support\/TargetRegistry.h\"\n#include \"llvm\/Support\/TargetSelect.h\"\n#include \"llvm\/Support\/Timer.h\"\n#include \"llvm\/Support\/raw_ostream.h\"\n#include \"llvm\/Support\/system_error.h\"\n#include \"llvm\/Target\/TargetData.h\"\nusing namespace clang;\nusing namespace clang::driver;\nusing namespace llvm;\n\nnamespace {\n\n\/\/\/ \\brief Helper class for representing a single invocation of the assembler.\nstruct AssemblerInvocation {\n \/\/\/ @name Target Options\n \/\/\/ @{\n\n std::string Triple;\n\n \/\/\/ @}\n \/\/\/ @name Language Options\n \/\/\/ @{\n\n std::vector<std::string> IncludePaths;\n unsigned NoInitialTextSection : 1;\n unsigned SaveTemporaryLabels : 1;\n\n \/\/\/ @}\n \/\/\/ @name Frontend Options\n \/\/\/ @{\n\n std::string InputFile;\n std::vector<std::string> LLVMArgs;\n std::string OutputPath;\n enum FileType {\n FT_Asm, \/\/\/< Assembly (.s) output, transliterate mode.\n FT_Null, \/\/\/< No output, for timing purposes.\n FT_Obj \/\/\/< Object file output.\n };\n FileType OutputType;\n unsigned ShowHelp : 1;\n unsigned ShowVersion : 1;\n\n \/\/\/ @}\n \/\/\/ @name Transliterate Options\n \/\/\/ @{\n\n unsigned OutputAsmVariant;\n unsigned ShowEncoding : 1;\n unsigned ShowInst : 1;\n\n \/\/\/ @}\n \/\/\/ @name Assembler Options\n \/\/\/ @{\n\n unsigned RelaxAll : 1;\n unsigned NoExecStack : 1;\n\n \/\/\/ @}\n\npublic:\n AssemblerInvocation() {\n Triple = \"\";\n NoInitialTextSection = 0;\n InputFile = \"-\";\n OutputPath = \"-\";\n OutputType = FT_Asm;\n OutputAsmVariant = 0;\n ShowInst = 0;\n ShowEncoding = 0;\n RelaxAll = 0;\n NoExecStack = 0;\n }\n\n static void CreateFromArgs(AssemblerInvocation &Res, const char **ArgBegin,\n const char **ArgEnd, Diagnostic &Diags);\n};\n\n}\n\nvoid AssemblerInvocation::CreateFromArgs(AssemblerInvocation &Opts,\n const char **ArgBegin,\n const char **ArgEnd,\n Diagnostic &Diags) {\n using namespace clang::driver::cc1asoptions;\n \/\/ Parse the arguments.\n OwningPtr<OptTable> OptTbl(createCC1AsOptTable());\n unsigned MissingArgIndex, MissingArgCount;\n OwningPtr<InputArgList> Args(\n OptTbl->ParseArgs(ArgBegin, ArgEnd,MissingArgIndex, MissingArgCount));\n\n \/\/ Check for missing argument error.\n if (MissingArgCount)\n Diags.Report(diag::err_drv_missing_argument)\n << Args->getArgString(MissingArgIndex) << MissingArgCount;\n\n \/\/ Issue errors on unknown arguments.\n for (arg_iterator it = Args->filtered_begin(cc1asoptions::OPT_UNKNOWN),\n ie = Args->filtered_end(); it != ie; ++it)\n Diags.Report(diag::err_drv_unknown_argument) << (*it) ->getAsString(*Args);\n\n \/\/ Construct the invocation.\n\n \/\/ Target Options\n Opts.Triple = Triple::normalize(Args->getLastArgValue(OPT_triple));\n if (Opts.Triple.empty()) \/\/ Use the host triple if unspecified.\n Opts.Triple = sys::getHostTriple();\n\n \/\/ Language Options\n Opts.IncludePaths = Args->getAllArgValues(OPT_I);\n Opts.NoInitialTextSection = Args->hasArg(OPT_n);\n Opts.SaveTemporaryLabels = Args->hasArg(OPT_L);\n\n \/\/ Frontend Options\n if (Args->hasArg(OPT_INPUT)) {\n bool First = true;\n for (arg_iterator it = Args->filtered_begin(OPT_INPUT),\n ie = Args->filtered_end(); it != ie; ++it, First=false) {\n const Arg *A = it;\n if (First)\n Opts.InputFile = A->getValue(*Args);\n else\n Diags.Report(diag::err_drv_unknown_argument) << A->getAsString(*Args);\n }\n }\n Opts.LLVMArgs = Args->getAllArgValues(OPT_mllvm);\n if (Args->hasArg(OPT_fatal_warnings))\n Opts.LLVMArgs.push_back(\"-fatal-assembler-warnings\");\n Opts.OutputPath = Args->getLastArgValue(OPT_o);\n if (Arg *A = Args->getLastArg(OPT_filetype)) {\n StringRef Name = A->getValue(*Args);\n unsigned OutputType = StringSwitch<unsigned>(Name)\n .Case(\"asm\", FT_Asm)\n .Case(\"null\", FT_Null)\n .Case(\"obj\", FT_Obj)\n .Default(~0U);\n if (OutputType == ~0U)\n Diags.Report(diag::err_drv_invalid_value)\n << A->getAsString(*Args) << Name;\n else\n Opts.OutputType = FileType(OutputType);\n }\n Opts.ShowHelp = Args->hasArg(OPT_help);\n Opts.ShowVersion = Args->hasArg(OPT_version);\n\n \/\/ Transliterate Options\n Opts.OutputAsmVariant = Args->getLastArgIntValue(OPT_output_asm_variant,\n 0, Diags);\n Opts.ShowEncoding = Args->hasArg(OPT_show_encoding);\n Opts.ShowInst = Args->hasArg(OPT_show_inst);\n\n \/\/ Assemble Options\n Opts.RelaxAll = Args->hasArg(OPT_relax_all);\n Opts.NoExecStack = Args->hasArg(OPT_no_exec_stack);\n}\n\nstatic formatted_raw_ostream *GetOutputStream(AssemblerInvocation &Opts,\n Diagnostic &Diags,\n bool Binary) {\n if (Opts.OutputPath.empty())\n Opts.OutputPath = \"-\";\n\n \/\/ Make sure that the Out file gets unlinked from the disk if we get a\n \/\/ SIGINT.\n if (Opts.OutputPath != \"-\")\n sys::RemoveFileOnSignal(sys::Path(Opts.OutputPath));\n\n std::string Error;\n raw_fd_ostream *Out =\n new raw_fd_ostream(Opts.OutputPath.c_str(), Error,\n (Binary ? raw_fd_ostream::F_Binary : 0));\n if (!Error.empty()) {\n Diags.Report(diag::err_fe_unable_to_open_output)\n << Opts.OutputPath << Error;\n return 0;\n }\n\n return new formatted_raw_ostream(*Out, formatted_raw_ostream::DELETE_STREAM);\n}\n\nstatic bool ExecuteAssembler(AssemblerInvocation &Opts, Diagnostic &Diags) {\n \/\/ Get the target specific parser.\n std::string Error;\n const Target *TheTarget(TargetRegistry::lookupTarget(Opts.Triple, Error));\n if (!TheTarget) {\n Diags.Report(diag::err_target_unknown_triple) << Opts.Triple;\n return false;\n }\n\n OwningPtr<MemoryBuffer> BufferPtr;\n if (error_code ec = MemoryBuffer::getFileOrSTDIN(Opts.InputFile, BufferPtr)) {\n Error = ec.message();\n Diags.Report(diag::err_fe_error_reading) << Opts.InputFile;\n return false;\n }\n MemoryBuffer *Buffer = BufferPtr.take();\n\n SourceMgr SrcMgr;\n\n \/\/ Tell SrcMgr about this buffer, which is what the parser will pick up.\n SrcMgr.AddNewSourceBuffer(Buffer, SMLoc());\n\n \/\/ Record the location of the include directories so that the lexer can find\n \/\/ it later.\n SrcMgr.setIncludeDirs(Opts.IncludePaths);\n\n OwningPtr<MCAsmInfo> MAI(TheTarget->createMCAsmInfo(Opts.Triple));\n assert(MAI && \"Unable to create target asm info!\");\n\n OwningPtr<MCRegisterInfo> MRI(TheTarget->createMCRegInfo(Opts.Triple));\n assert(MRI && \"Unable to create target register info!\");\n\n bool IsBinary = Opts.OutputType == AssemblerInvocation::FT_Obj;\n formatted_raw_ostream *Out = GetOutputStream(Opts, Diags, IsBinary);\n if (!Out)\n return false;\n\n \/\/ FIXME: This is not pretty. MCContext has a ptr to MCObjectFileInfo and\n \/\/ MCObjectFileInfo needs a MCContext reference in order to initialize itself.\n OwningPtr<MCObjectFileInfo> MOFI(new MCObjectFileInfo());\n MCContext Ctx(*MAI, *MRI, MOFI.get());\n \/\/ FIXME: Assembler behavior can change with -static.\n MOFI->InitMCObjectFileInfo(Opts.Triple,\n Reloc::Default, CodeModel::Default, Ctx);\n if (Opts.SaveTemporaryLabels)\n Ctx.setAllowTemporaryLabels(false);\n\n OwningPtr<MCStreamer> Str;\n\n OwningPtr<MCInstrInfo> MCII(TheTarget->createMCInstrInfo());\n OwningPtr<MCSubtargetInfo>\n STI(TheTarget->createMCSubtargetInfo(Opts.Triple, \"\", \"\"));\n\n \/\/ FIXME: There is a bit of code duplication with addPassesToEmitFile.\n if (Opts.OutputType == AssemblerInvocation::FT_Asm) {\n MCInstPrinter *IP =\n TheTarget->createMCInstPrinter(Opts.OutputAsmVariant, *MAI);\n MCCodeEmitter *CE = 0;\n MCAsmBackend *MAB = 0;\n if (Opts.ShowEncoding) {\n CE = TheTarget->createMCCodeEmitter(*MCII, *STI, Ctx);\n MAB = TheTarget->createMCAsmBackend(Opts.Triple);\n }\n Str.reset(TheTarget->createAsmStreamer(Ctx, *Out, \/*asmverbose*\/true,\n \/*useLoc*\/ true,\n \/*useCFI*\/ true, IP, CE, MAB,\n Opts.ShowInst));\n } else if (Opts.OutputType == AssemblerInvocation::FT_Null) {\n Str.reset(createNullStreamer(Ctx));\n } else {\n assert(Opts.OutputType == AssemblerInvocation::FT_Obj &&\n \"Invalid file type!\");\n MCCodeEmitter *CE = TheTarget->createMCCodeEmitter(*MCII, *STI, Ctx);\n MCAsmBackend *MAB = TheTarget->createMCAsmBackend(Opts.Triple);\n Str.reset(TheTarget->createMCObjectStreamer(Opts.Triple, Ctx, *MAB, *Out,\n CE, Opts.RelaxAll,\n Opts.NoExecStack));\n Str.get()->InitSections();\n }\n\n OwningPtr<MCAsmParser> Parser(createMCAsmParser(SrcMgr, Ctx,\n *Str.get(), *MAI));\n OwningPtr<MCTargetAsmParser> TAP(TheTarget->createMCAsmParser(*STI, *Parser));\n if (!TAP) {\n Diags.Report(diag::err_target_unknown_triple) << Opts.Triple;\n return false;\n }\n\n Parser->setTargetParser(*TAP.get());\n\n bool Success = !Parser->Run(Opts.NoInitialTextSection);\n\n \/\/ Close the output.\n delete Out;\n\n \/\/ Delete output on errors.\n if (!Success && Opts.OutputPath != \"-\")\n sys::Path(Opts.OutputPath).eraseFromDisk();\n\n return Success;\n}\n\nstatic void LLVMErrorHandler(void *UserData, const std::string &Message) {\n Diagnostic &Diags = *static_cast<Diagnostic*>(UserData);\n\n Diags.Report(diag::err_fe_error_backend) << Message;\n\n \/\/ We cannot recover from llvm errors.\n exit(1);\n}\n\nint cc1as_main(const char **ArgBegin, const char **ArgEnd,\n const char *Argv0, void *MainAddr) {\n \/\/ Print a stack trace if we signal out.\n sys::PrintStackTraceOnErrorSignal();\n PrettyStackTraceProgram X(ArgEnd - ArgBegin, ArgBegin);\n llvm_shutdown_obj Y; \/\/ Call llvm_shutdown() on exit.\n\n \/\/ Initialize targets and assembly printers\/parsers.\n InitializeAllTargetInfos();\n InitializeAllTargetMCs();\n InitializeAllAsmParsers();\n\n \/\/ Construct our diagnostic client.\n TextDiagnosticPrinter *DiagClient\n = new TextDiagnosticPrinter(errs(), DiagnosticOptions());\n DiagClient->setPrefix(\"clang -cc1as\");\n llvm::IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());\n Diagnostic Diags(DiagID, DiagClient);\n\n \/\/ Set an error handler, so that any LLVM backend diagnostics go through our\n \/\/ error handler.\n ScopedFatalErrorHandler FatalErrorHandler\n (LLVMErrorHandler, static_cast<void*>(&Diags));\n\n \/\/ Parse the arguments.\n AssemblerInvocation Asm;\n AssemblerInvocation::CreateFromArgs(Asm, ArgBegin, ArgEnd, Diags);\n\n \/\/ Honor -help.\n if (Asm.ShowHelp) {\n llvm::OwningPtr<driver::OptTable> Opts(driver::createCC1AsOptTable());\n Opts->PrintHelp(llvm::outs(), \"clang -cc1as\", \"Clang Integrated Assembler\");\n return 0;\n }\n\n \/\/ Honor -version.\n \/\/\n \/\/ FIXME: Use a better -version message?\n if (Asm.ShowVersion) {\n llvm::cl::PrintVersionMessage();\n return 0;\n }\n\n \/\/ Honor -mllvm.\n \/\/\n \/\/ FIXME: Remove this, one day.\n if (!Asm.LLVMArgs.empty()) {\n unsigned NumArgs = Asm.LLVMArgs.size();\n const char **Args = new const char*[NumArgs + 2];\n Args[0] = \"clang (LLVM option parsing)\";\n for (unsigned i = 0; i != NumArgs; ++i)\n Args[i + 1] = Asm.LLVMArgs[i].c_str();\n Args[NumArgs + 1] = 0;\n llvm::cl::ParseCommandLineOptions(NumArgs + 1, const_cast<char **>(Args));\n }\n\n \/\/ Execute the invocation, unless there were parsing errors.\n bool Success = false;\n if (!Diags.hasErrorOccurred())\n Success = ExecuteAssembler(Asm, Diags);\n\n \/\/ If any timers were active but haven't been destroyed yet, print their\n \/\/ results now.\n TimerGroup::printAll(errs());\n\n return !Success;\n}\n<commit_msg>Fix up MCInstPrinter creation to take the new SubtargetInfo parameter (see LLVM r139237)<commit_after>\/\/===-- cc1as_main.cpp - Clang Assembler ---------------------------------===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This is the entry point to the clang -cc1as functionality, which implements\n\/\/ the direct interface to the LLVM MC based assembler.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"clang\/Basic\/Diagnostic.h\"\n#include \"clang\/Driver\/Arg.h\"\n#include \"clang\/Driver\/ArgList.h\"\n#include \"clang\/Driver\/DriverDiagnostic.h\"\n#include \"clang\/Driver\/CC1AsOptions.h\"\n#include \"clang\/Driver\/OptTable.h\"\n#include \"clang\/Driver\/Options.h\"\n#include \"clang\/Frontend\/DiagnosticOptions.h\"\n#include \"clang\/Frontend\/FrontendDiagnostic.h\"\n#include \"clang\/Frontend\/TextDiagnosticPrinter.h\"\n#include \"llvm\/ADT\/OwningPtr.h\"\n#include \"llvm\/ADT\/StringSwitch.h\"\n#include \"llvm\/ADT\/Triple.h\"\n#include \"llvm\/MC\/MCParser\/MCAsmParser.h\"\n#include \"llvm\/MC\/MCAsmInfo.h\"\n#include \"llvm\/MC\/MCCodeEmitter.h\"\n#include \"llvm\/MC\/MCContext.h\"\n#include \"llvm\/MC\/MCInstrInfo.h\"\n#include \"llvm\/MC\/MCObjectFileInfo.h\"\n#include \"llvm\/MC\/MCRegisterInfo.h\"\n#include \"llvm\/MC\/MCStreamer.h\"\n#include \"llvm\/MC\/MCSubtargetInfo.h\"\n#include \"llvm\/MC\/MCAsmBackend.h\"\n#include \"llvm\/MC\/MCTargetAsmParser.h\"\n#include \"llvm\/Support\/CommandLine.h\"\n#include \"llvm\/Support\/FormattedStream.h\"\n#include \"llvm\/Support\/ErrorHandling.h\"\n#include \"llvm\/Support\/ManagedStatic.h\"\n#include \"llvm\/Support\/MemoryBuffer.h\"\n#include \"llvm\/Support\/PrettyStackTrace.h\"\n#include \"llvm\/Support\/SourceMgr.h\"\n#include \"llvm\/Support\/Host.h\"\n#include \"llvm\/Support\/Path.h\"\n#include \"llvm\/Support\/Signals.h\"\n#include \"llvm\/Support\/TargetRegistry.h\"\n#include \"llvm\/Support\/TargetSelect.h\"\n#include \"llvm\/Support\/Timer.h\"\n#include \"llvm\/Support\/raw_ostream.h\"\n#include \"llvm\/Support\/system_error.h\"\n#include \"llvm\/Target\/TargetData.h\"\nusing namespace clang;\nusing namespace clang::driver;\nusing namespace llvm;\n\nnamespace {\n\n\/\/\/ \\brief Helper class for representing a single invocation of the assembler.\nstruct AssemblerInvocation {\n \/\/\/ @name Target Options\n \/\/\/ @{\n\n std::string Triple;\n\n \/\/\/ @}\n \/\/\/ @name Language Options\n \/\/\/ @{\n\n std::vector<std::string> IncludePaths;\n unsigned NoInitialTextSection : 1;\n unsigned SaveTemporaryLabels : 1;\n\n \/\/\/ @}\n \/\/\/ @name Frontend Options\n \/\/\/ @{\n\n std::string InputFile;\n std::vector<std::string> LLVMArgs;\n std::string OutputPath;\n enum FileType {\n FT_Asm, \/\/\/< Assembly (.s) output, transliterate mode.\n FT_Null, \/\/\/< No output, for timing purposes.\n FT_Obj \/\/\/< Object file output.\n };\n FileType OutputType;\n unsigned ShowHelp : 1;\n unsigned ShowVersion : 1;\n\n \/\/\/ @}\n \/\/\/ @name Transliterate Options\n \/\/\/ @{\n\n unsigned OutputAsmVariant;\n unsigned ShowEncoding : 1;\n unsigned ShowInst : 1;\n\n \/\/\/ @}\n \/\/\/ @name Assembler Options\n \/\/\/ @{\n\n unsigned RelaxAll : 1;\n unsigned NoExecStack : 1;\n\n \/\/\/ @}\n\npublic:\n AssemblerInvocation() {\n Triple = \"\";\n NoInitialTextSection = 0;\n InputFile = \"-\";\n OutputPath = \"-\";\n OutputType = FT_Asm;\n OutputAsmVariant = 0;\n ShowInst = 0;\n ShowEncoding = 0;\n RelaxAll = 0;\n NoExecStack = 0;\n }\n\n static void CreateFromArgs(AssemblerInvocation &Res, const char **ArgBegin,\n const char **ArgEnd, Diagnostic &Diags);\n};\n\n}\n\nvoid AssemblerInvocation::CreateFromArgs(AssemblerInvocation &Opts,\n const char **ArgBegin,\n const char **ArgEnd,\n Diagnostic &Diags) {\n using namespace clang::driver::cc1asoptions;\n \/\/ Parse the arguments.\n OwningPtr<OptTable> OptTbl(createCC1AsOptTable());\n unsigned MissingArgIndex, MissingArgCount;\n OwningPtr<InputArgList> Args(\n OptTbl->ParseArgs(ArgBegin, ArgEnd,MissingArgIndex, MissingArgCount));\n\n \/\/ Check for missing argument error.\n if (MissingArgCount)\n Diags.Report(diag::err_drv_missing_argument)\n << Args->getArgString(MissingArgIndex) << MissingArgCount;\n\n \/\/ Issue errors on unknown arguments.\n for (arg_iterator it = Args->filtered_begin(cc1asoptions::OPT_UNKNOWN),\n ie = Args->filtered_end(); it != ie; ++it)\n Diags.Report(diag::err_drv_unknown_argument) << (*it) ->getAsString(*Args);\n\n \/\/ Construct the invocation.\n\n \/\/ Target Options\n Opts.Triple = Triple::normalize(Args->getLastArgValue(OPT_triple));\n if (Opts.Triple.empty()) \/\/ Use the host triple if unspecified.\n Opts.Triple = sys::getHostTriple();\n\n \/\/ Language Options\n Opts.IncludePaths = Args->getAllArgValues(OPT_I);\n Opts.NoInitialTextSection = Args->hasArg(OPT_n);\n Opts.SaveTemporaryLabels = Args->hasArg(OPT_L);\n\n \/\/ Frontend Options\n if (Args->hasArg(OPT_INPUT)) {\n bool First = true;\n for (arg_iterator it = Args->filtered_begin(OPT_INPUT),\n ie = Args->filtered_end(); it != ie; ++it, First=false) {\n const Arg *A = it;\n if (First)\n Opts.InputFile = A->getValue(*Args);\n else\n Diags.Report(diag::err_drv_unknown_argument) << A->getAsString(*Args);\n }\n }\n Opts.LLVMArgs = Args->getAllArgValues(OPT_mllvm);\n if (Args->hasArg(OPT_fatal_warnings))\n Opts.LLVMArgs.push_back(\"-fatal-assembler-warnings\");\n Opts.OutputPath = Args->getLastArgValue(OPT_o);\n if (Arg *A = Args->getLastArg(OPT_filetype)) {\n StringRef Name = A->getValue(*Args);\n unsigned OutputType = StringSwitch<unsigned>(Name)\n .Case(\"asm\", FT_Asm)\n .Case(\"null\", FT_Null)\n .Case(\"obj\", FT_Obj)\n .Default(~0U);\n if (OutputType == ~0U)\n Diags.Report(diag::err_drv_invalid_value)\n << A->getAsString(*Args) << Name;\n else\n Opts.OutputType = FileType(OutputType);\n }\n Opts.ShowHelp = Args->hasArg(OPT_help);\n Opts.ShowVersion = Args->hasArg(OPT_version);\n\n \/\/ Transliterate Options\n Opts.OutputAsmVariant = Args->getLastArgIntValue(OPT_output_asm_variant,\n 0, Diags);\n Opts.ShowEncoding = Args->hasArg(OPT_show_encoding);\n Opts.ShowInst = Args->hasArg(OPT_show_inst);\n\n \/\/ Assemble Options\n Opts.RelaxAll = Args->hasArg(OPT_relax_all);\n Opts.NoExecStack = Args->hasArg(OPT_no_exec_stack);\n}\n\nstatic formatted_raw_ostream *GetOutputStream(AssemblerInvocation &Opts,\n Diagnostic &Diags,\n bool Binary) {\n if (Opts.OutputPath.empty())\n Opts.OutputPath = \"-\";\n\n \/\/ Make sure that the Out file gets unlinked from the disk if we get a\n \/\/ SIGINT.\n if (Opts.OutputPath != \"-\")\n sys::RemoveFileOnSignal(sys::Path(Opts.OutputPath));\n\n std::string Error;\n raw_fd_ostream *Out =\n new raw_fd_ostream(Opts.OutputPath.c_str(), Error,\n (Binary ? raw_fd_ostream::F_Binary : 0));\n if (!Error.empty()) {\n Diags.Report(diag::err_fe_unable_to_open_output)\n << Opts.OutputPath << Error;\n return 0;\n }\n\n return new formatted_raw_ostream(*Out, formatted_raw_ostream::DELETE_STREAM);\n}\n\nstatic bool ExecuteAssembler(AssemblerInvocation &Opts, Diagnostic &Diags) {\n \/\/ Get the target specific parser.\n std::string Error;\n const Target *TheTarget(TargetRegistry::lookupTarget(Opts.Triple, Error));\n if (!TheTarget) {\n Diags.Report(diag::err_target_unknown_triple) << Opts.Triple;\n return false;\n }\n\n OwningPtr<MemoryBuffer> BufferPtr;\n if (error_code ec = MemoryBuffer::getFileOrSTDIN(Opts.InputFile, BufferPtr)) {\n Error = ec.message();\n Diags.Report(diag::err_fe_error_reading) << Opts.InputFile;\n return false;\n }\n MemoryBuffer *Buffer = BufferPtr.take();\n\n SourceMgr SrcMgr;\n\n \/\/ Tell SrcMgr about this buffer, which is what the parser will pick up.\n SrcMgr.AddNewSourceBuffer(Buffer, SMLoc());\n\n \/\/ Record the location of the include directories so that the lexer can find\n \/\/ it later.\n SrcMgr.setIncludeDirs(Opts.IncludePaths);\n\n OwningPtr<MCAsmInfo> MAI(TheTarget->createMCAsmInfo(Opts.Triple));\n assert(MAI && \"Unable to create target asm info!\");\n\n OwningPtr<MCRegisterInfo> MRI(TheTarget->createMCRegInfo(Opts.Triple));\n assert(MRI && \"Unable to create target register info!\");\n\n bool IsBinary = Opts.OutputType == AssemblerInvocation::FT_Obj;\n formatted_raw_ostream *Out = GetOutputStream(Opts, Diags, IsBinary);\n if (!Out)\n return false;\n\n \/\/ FIXME: This is not pretty. MCContext has a ptr to MCObjectFileInfo and\n \/\/ MCObjectFileInfo needs a MCContext reference in order to initialize itself.\n OwningPtr<MCObjectFileInfo> MOFI(new MCObjectFileInfo());\n MCContext Ctx(*MAI, *MRI, MOFI.get());\n \/\/ FIXME: Assembler behavior can change with -static.\n MOFI->InitMCObjectFileInfo(Opts.Triple,\n Reloc::Default, CodeModel::Default, Ctx);\n if (Opts.SaveTemporaryLabels)\n Ctx.setAllowTemporaryLabels(false);\n\n OwningPtr<MCStreamer> Str;\n\n OwningPtr<MCInstrInfo> MCII(TheTarget->createMCInstrInfo());\n OwningPtr<MCSubtargetInfo>\n STI(TheTarget->createMCSubtargetInfo(Opts.Triple, \"\", \"\"));\n\n \/\/ FIXME: There is a bit of code duplication with addPassesToEmitFile.\n if (Opts.OutputType == AssemblerInvocation::FT_Asm) {\n MCInstPrinter *IP =\n TheTarget->createMCInstPrinter(Opts.OutputAsmVariant, *MAI, *STI);\n MCCodeEmitter *CE = 0;\n MCAsmBackend *MAB = 0;\n if (Opts.ShowEncoding) {\n CE = TheTarget->createMCCodeEmitter(*MCII, *STI, Ctx);\n MAB = TheTarget->createMCAsmBackend(Opts.Triple);\n }\n Str.reset(TheTarget->createAsmStreamer(Ctx, *Out, \/*asmverbose*\/true,\n \/*useLoc*\/ true,\n \/*useCFI*\/ true, IP, CE, MAB,\n Opts.ShowInst));\n } else if (Opts.OutputType == AssemblerInvocation::FT_Null) {\n Str.reset(createNullStreamer(Ctx));\n } else {\n assert(Opts.OutputType == AssemblerInvocation::FT_Obj &&\n \"Invalid file type!\");\n MCCodeEmitter *CE = TheTarget->createMCCodeEmitter(*MCII, *STI, Ctx);\n MCAsmBackend *MAB = TheTarget->createMCAsmBackend(Opts.Triple);\n Str.reset(TheTarget->createMCObjectStreamer(Opts.Triple, Ctx, *MAB, *Out,\n CE, Opts.RelaxAll,\n Opts.NoExecStack));\n Str.get()->InitSections();\n }\n\n OwningPtr<MCAsmParser> Parser(createMCAsmParser(SrcMgr, Ctx,\n *Str.get(), *MAI));\n OwningPtr<MCTargetAsmParser> TAP(TheTarget->createMCAsmParser(*STI, *Parser));\n if (!TAP) {\n Diags.Report(diag::err_target_unknown_triple) << Opts.Triple;\n return false;\n }\n\n Parser->setTargetParser(*TAP.get());\n\n bool Success = !Parser->Run(Opts.NoInitialTextSection);\n\n \/\/ Close the output.\n delete Out;\n\n \/\/ Delete output on errors.\n if (!Success && Opts.OutputPath != \"-\")\n sys::Path(Opts.OutputPath).eraseFromDisk();\n\n return Success;\n}\n\nstatic void LLVMErrorHandler(void *UserData, const std::string &Message) {\n Diagnostic &Diags = *static_cast<Diagnostic*>(UserData);\n\n Diags.Report(diag::err_fe_error_backend) << Message;\n\n \/\/ We cannot recover from llvm errors.\n exit(1);\n}\n\nint cc1as_main(const char **ArgBegin, const char **ArgEnd,\n const char *Argv0, void *MainAddr) {\n \/\/ Print a stack trace if we signal out.\n sys::PrintStackTraceOnErrorSignal();\n PrettyStackTraceProgram X(ArgEnd - ArgBegin, ArgBegin);\n llvm_shutdown_obj Y; \/\/ Call llvm_shutdown() on exit.\n\n \/\/ Initialize targets and assembly printers\/parsers.\n InitializeAllTargetInfos();\n InitializeAllTargetMCs();\n InitializeAllAsmParsers();\n\n \/\/ Construct our diagnostic client.\n TextDiagnosticPrinter *DiagClient\n = new TextDiagnosticPrinter(errs(), DiagnosticOptions());\n DiagClient->setPrefix(\"clang -cc1as\");\n llvm::IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());\n Diagnostic Diags(DiagID, DiagClient);\n\n \/\/ Set an error handler, so that any LLVM backend diagnostics go through our\n \/\/ error handler.\n ScopedFatalErrorHandler FatalErrorHandler\n (LLVMErrorHandler, static_cast<void*>(&Diags));\n\n \/\/ Parse the arguments.\n AssemblerInvocation Asm;\n AssemblerInvocation::CreateFromArgs(Asm, ArgBegin, ArgEnd, Diags);\n\n \/\/ Honor -help.\n if (Asm.ShowHelp) {\n llvm::OwningPtr<driver::OptTable> Opts(driver::createCC1AsOptTable());\n Opts->PrintHelp(llvm::outs(), \"clang -cc1as\", \"Clang Integrated Assembler\");\n return 0;\n }\n\n \/\/ Honor -version.\n \/\/\n \/\/ FIXME: Use a better -version message?\n if (Asm.ShowVersion) {\n llvm::cl::PrintVersionMessage();\n return 0;\n }\n\n \/\/ Honor -mllvm.\n \/\/\n \/\/ FIXME: Remove this, one day.\n if (!Asm.LLVMArgs.empty()) {\n unsigned NumArgs = Asm.LLVMArgs.size();\n const char **Args = new const char*[NumArgs + 2];\n Args[0] = \"clang (LLVM option parsing)\";\n for (unsigned i = 0; i != NumArgs; ++i)\n Args[i + 1] = Asm.LLVMArgs[i].c_str();\n Args[NumArgs + 1] = 0;\n llvm::cl::ParseCommandLineOptions(NumArgs + 1, const_cast<char **>(Args));\n }\n\n \/\/ Execute the invocation, unless there were parsing errors.\n bool Success = false;\n if (!Diags.hasErrorOccurred())\n Success = ExecuteAssembler(Asm, Diags);\n\n \/\/ If any timers were active but haven't been destroyed yet, print their\n \/\/ results now.\n TimerGroup::printAll(errs());\n\n return !Success;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/debugger\/devtools_http_protocol_handler.h\"\n\n#include \"base\/compiler_specific.h\"\n#include \"base\/logging.h\"\n#include \"base\/message_loop_proxy.h\"\n#include \"base\/string_number_conversions.h\"\n#include \"base\/thread.h\"\n#include \"base\/utf_string_conversions.h\"\n#include \"chrome\/browser\/browser_list.h\"\n#include \"chrome\/browser\/browser_thread.h\"\n#include \"chrome\/browser\/debugger\/devtools_client_host.h\"\n#include \"chrome\/browser\/debugger\/devtools_manager.h\"\n#include \"chrome\/browser\/profiles\/profile.h\"\n#include \"chrome\/browser\/tab_contents\/tab_contents.h\"\n#include \"chrome\/browser\/tabs\/tab_strip_model.h\"\n#include \"chrome\/browser\/ui\/browser.h\"\n#include \"chrome\/browser\/ui\/tab_contents\/tab_contents_wrapper.h\"\n#include \"chrome\/common\/devtools_messages.h\"\n#include \"chrome\/common\/net\/url_request_context_getter.h\"\n#include \"googleurl\/src\/gurl.h\"\n#include \"net\/base\/io_buffer.h\"\n#include \"net\/base\/listen_socket.h\"\n#include \"net\/server\/http_server_request_info.h\"\n#include \"net\/url_request\/url_request_context.h\"\n\nconst int kBufferSize = 16 * 1024;\n\nnamespace {\n\n\/\/ An internal implementation of DevToolsClientHost that delegates\n\/\/ messages sent for DevToolsClient to a DebuggerShell instance.\nclass DevToolsClientHostImpl : public DevToolsClientHost {\n public:\n explicit DevToolsClientHostImpl(HttpListenSocket* socket)\n : socket_(socket) {}\n ~DevToolsClientHostImpl() {}\n\n \/\/ DevToolsClientHost interface\n virtual void InspectedTabClosing() {\n BrowserThread::PostTask(\n BrowserThread::IO,\n FROM_HERE,\n NewRunnableMethod(socket_,\n &HttpListenSocket::Close));\n }\n\n virtual void SendMessageToClient(const IPC::Message& msg) {\n IPC_BEGIN_MESSAGE_MAP(DevToolsClientHostImpl, msg)\n IPC_MESSAGE_HANDLER(DevToolsClientMsg_DispatchOnInspectorFrontend,\n OnDispatchOnInspectorFrontend);\n IPC_MESSAGE_UNHANDLED_ERROR()\n IPC_END_MESSAGE_MAP()\n }\n\n void NotifyCloseListener() {\n DevToolsClientHost::NotifyCloseListener();\n }\n private:\n \/\/ Message handling routines\n void OnDispatchOnInspectorFrontend(const std::string& data) {\n socket_->SendOverWebSocket(data);\n }\n HttpListenSocket* socket_;\n};\n\n}\n\nDevToolsHttpProtocolHandler::~DevToolsHttpProtocolHandler() {\n \/\/ Stop() must be called prior to this being called\n DCHECK(server_.get() == NULL);\n}\n\nvoid DevToolsHttpProtocolHandler::Start() {\n BrowserThread::PostTask(\n BrowserThread::IO, FROM_HERE,\n NewRunnableMethod(this, &DevToolsHttpProtocolHandler::Init));\n}\n\nvoid DevToolsHttpProtocolHandler::Stop() {\n BrowserThread::PostTask(\n BrowserThread::IO, FROM_HERE,\n NewRunnableMethod(this, &DevToolsHttpProtocolHandler::Teardown));\n}\n\nvoid DevToolsHttpProtocolHandler::OnHttpRequest(\n HttpListenSocket* socket,\n const HttpServerRequestInfo& info) {\n if (info.path == \"\" || info.path == \"\/\") {\n \/\/ Pages discovery request.\n BrowserThread::PostTask(\n BrowserThread::UI,\n FROM_HERE,\n NewRunnableMethod(this,\n &DevToolsHttpProtocolHandler::OnHttpRequestUI,\n make_scoped_refptr(socket),\n info));\n return;\n }\n\n size_t pos = info.path.find(\"\/devtools\/\");\n if (pos != 0) {\n socket->Send404();\n return;\n }\n\n \/\/ Proxy static files from chrome:\/\/devtools\/*.\n net::URLRequest* request = new net::URLRequest(\n GURL(\"chrome:\/\" + info.path), this);\n Bind(request, socket);\n request->set_context(\n Profile::GetDefaultRequestContext()->GetURLRequestContext());\n request->Start();\n}\n\nvoid DevToolsHttpProtocolHandler::OnWebSocketRequest(\n HttpListenSocket* socket,\n const HttpServerRequestInfo& request) {\n BrowserThread::PostTask(\n BrowserThread::UI,\n FROM_HERE,\n NewRunnableMethod(\n this,\n &DevToolsHttpProtocolHandler::OnWebSocketRequestUI,\n make_scoped_refptr(socket),\n request));\n}\n\nvoid DevToolsHttpProtocolHandler::OnWebSocketMessage(HttpListenSocket* socket,\n const std::string& data) {\n BrowserThread::PostTask(\n BrowserThread::UI,\n FROM_HERE,\n NewRunnableMethod(\n this,\n &DevToolsHttpProtocolHandler::OnWebSocketMessageUI,\n make_scoped_refptr(socket),\n data));\n}\n\nvoid DevToolsHttpProtocolHandler::OnClose(HttpListenSocket* socket) {\n SocketToRequestsMap::iterator it = socket_to_requests_io_.find(socket);\n if (it != socket_to_requests_io_.end()) {\n \/\/ Dispose delegating socket.\n for (std::set<net::URLRequest*>::iterator it2 = it->second.begin();\n it2 != it->second.end(); ++it2) {\n net::URLRequest* request = *it2;\n request->Cancel();\n request_to_socket_io_.erase(request);\n request_to_buffer_io_.erase(request);\n delete request;\n }\n socket_to_requests_io_.erase(socket);\n }\n\n BrowserThread::PostTask(\n BrowserThread::UI,\n FROM_HERE,\n NewRunnableMethod(\n this,\n &DevToolsHttpProtocolHandler::OnCloseUI,\n make_scoped_refptr(socket)));\n}\n\nvoid DevToolsHttpProtocolHandler::OnHttpRequestUI(\n HttpListenSocket* socket,\n const HttpServerRequestInfo& info) {\n std::string response = \"<html><body>\";\n for (BrowserList::const_iterator it = BrowserList::begin(),\n end = BrowserList::end(); it != end; ++it) {\n TabStripModel* model = (*it)->tabstrip_model();\n for (int i = 0, size = model->count(); i < size; ++i) {\n TabContentsWrapper* tab_contents = model->GetTabContentsAt(i);\n NavigationController& controller = tab_contents->controller();\n NavigationEntry* entry = controller.GetActiveEntry();\n if (entry == NULL)\n continue;\n\n if (!entry->url().is_valid())\n continue;\n\n DevToolsClientHost* client_host = DevToolsManager::GetInstance()->\n GetDevToolsClientHostFor(tab_contents->tab_contents()->\n render_view_host());\n if (!client_host) {\n response += StringPrintf(\n \"<a href='\/devtools\/devtools.html?page=%d'>%s (%s)<\/a><br>\",\n controller.session_id().id(),\n UTF16ToUTF8(entry->title()).c_str(),\n entry->url().spec().c_str());\n } else {\n response += StringPrintf(\n \"%s (%s)<br>\",\n UTF16ToUTF8(entry->title()).c_str(),\n entry->url().spec().c_str());\n }\n }\n }\n response += \"<\/body><\/html>\";\n Send200(socket, response, \"text\/html; charset=UTF-8\");\n}\n\nvoid DevToolsHttpProtocolHandler::OnWebSocketRequestUI(\n HttpListenSocket* socket,\n const HttpServerRequestInfo& request) {\n std::string prefix = \"\/devtools\/page\/\";\n size_t pos = request.path.find(prefix);\n if (pos != 0) {\n Send404(socket);\n return;\n }\n std::string page_id = request.path.substr(prefix.length());\n int id = 0;\n if (!base::StringToInt(page_id, &id)) {\n Send500(socket, \"Invalid page id: \" + page_id);\n return;\n }\n\n TabContents* tab_contents = GetTabContents(id);\n if (tab_contents == NULL) {\n Send500(socket, \"No such page id: \" + page_id);\n return;\n }\n\n DevToolsManager* manager = DevToolsManager::GetInstance();\n if (manager->GetDevToolsClientHostFor(tab_contents->render_view_host())) {\n Send500(socket, \"Page with given id is being inspected: \" + page_id);\n return;\n }\n\n DevToolsClientHostImpl* client_host = new DevToolsClientHostImpl(socket);\n socket_to_client_host_ui_[socket] = client_host;\n\n manager->RegisterDevToolsClientHostFor(\n tab_contents->render_view_host(),\n client_host);\n AcceptWebSocket(socket, request);\n}\n\nvoid DevToolsHttpProtocolHandler::OnWebSocketMessageUI(\n HttpListenSocket* socket,\n const std::string& data) {\n SocketToClientHostMap::iterator it = socket_to_client_host_ui_.find(socket);\n if (it == socket_to_client_host_ui_.end())\n return;\n\n DevToolsManager* manager = DevToolsManager::GetInstance();\n\n if (data == \"loaded\") {\n manager->ForwardToDevToolsAgent(\n it->second,\n DevToolsAgentMsg_FrontendLoaded());\n return;\n }\n\n manager->ForwardToDevToolsAgent(\n it->second,\n DevToolsAgentMsg_DispatchOnInspectorBackend(data));\n}\n\nvoid DevToolsHttpProtocolHandler::OnCloseUI(HttpListenSocket* socket) {\n SocketToClientHostMap::iterator it = socket_to_client_host_ui_.find(socket);\n if (it == socket_to_client_host_ui_.end())\n return;\n DevToolsClientHostImpl* client_host =\n static_cast<DevToolsClientHostImpl*>(it->second);\n client_host->NotifyCloseListener();\n delete client_host;\n socket_to_client_host_ui_.erase(socket);\n\n \/\/ We are holding last reference to scoped refptr 'socket' here.\n \/\/ We can't exit method just like that since 'socket' is going to\n \/\/ be destroyed on the UI thread then. Schedule no-op to IO thread\n \/\/ so that socket is destroyed on IO instead.\n BrowserThread::PostTask(\n BrowserThread::IO,\n FROM_HERE,\n NewRunnableMethod(\n this,\n &DevToolsHttpProtocolHandler::ReleaseSocket,\n make_scoped_refptr(socket)));\n}\n\nvoid DevToolsHttpProtocolHandler::OnResponseStarted(net::URLRequest* request) {\n RequestToSocketMap::iterator it = request_to_socket_io_.find(request);\n if (it == request_to_socket_io_.end())\n return;\n\n HttpListenSocket* socket = it->second;\n\n int expected_size = static_cast<int>(request->GetExpectedContentSize());\n\n std::string content_type;\n request->GetMimeType(&content_type);\n\n if (request->status().is_success()) {\n socket->Send(StringPrintf(\"HTTP\/1.1 200 OK\\r\\n\"\n \"Content-Type:%s\\r\\n\"\n \"Content-Length:%d\\r\\n\"\n \"\\r\\n\",\n content_type.c_str(),\n expected_size));\n } else {\n socket->Send404();\n }\n\n int bytes_read = 0;\n \/\/ Some servers may treat HEAD requests as GET requests. To free up the\n \/\/ network connection as soon as possible, signal that the request has\n \/\/ completed immediately, without trying to read any data back (all we care\n \/\/ about is the response code and headers, which we already have).\n net::IOBuffer* buffer = request_to_buffer_io_[request].get();\n if (request->status().is_success())\n request->Read(buffer, kBufferSize, &bytes_read);\n OnReadCompleted(request, bytes_read);\n}\n\nvoid DevToolsHttpProtocolHandler::OnReadCompleted(net::URLRequest* request,\n int bytes_read) {\n RequestToSocketMap::iterator it = request_to_socket_io_.find(request);\n if (it == request_to_socket_io_.end())\n return;\n\n HttpListenSocket* socket = it->second;\n\n net::IOBuffer* buffer = request_to_buffer_io_[request].get();\n do {\n if (!request->status().is_success() || bytes_read <= 0)\n break;\n socket->Send(buffer->data(), bytes_read);\n } while (request->Read(buffer, kBufferSize, &bytes_read));\n\n \/\/ See comments re: HEAD requests in OnResponseStarted().\n if (!request->status().is_io_pending())\n RequestCompleted(request);\n}\n\nDevToolsHttpProtocolHandler::DevToolsHttpProtocolHandler(int port)\n : port_(port),\n server_(NULL) {\n}\n\nvoid DevToolsHttpProtocolHandler::Init() {\n server_ = HttpListenSocket::Listen(\"127.0.0.1\", port_, this);\n}\n\n\/\/ Run on I\/O thread\nvoid DevToolsHttpProtocolHandler::Teardown() {\n server_ = NULL;\n}\n\nvoid DevToolsHttpProtocolHandler::Bind(net::URLRequest* request,\n HttpListenSocket* socket) {\n request_to_socket_io_[request] = socket;\n SocketToRequestsMap::iterator it = socket_to_requests_io_.find(socket);\n if (it == socket_to_requests_io_.end()) {\n std::pair<HttpListenSocket*, std::set<net::URLRequest*> > value(\n socket,\n std::set<net::URLRequest*>());\n it = socket_to_requests_io_.insert(value).first;\n }\n it->second.insert(request);\n request_to_buffer_io_[request] = new net::IOBuffer(kBufferSize);\n}\n\nvoid DevToolsHttpProtocolHandler::RequestCompleted(net::URLRequest* request) {\n RequestToSocketMap::iterator it = request_to_socket_io_.find(request);\n if (it == request_to_socket_io_.end())\n return;\n\n HttpListenSocket* socket = it->second;\n request_to_socket_io_.erase(request);\n SocketToRequestsMap::iterator it2 = socket_to_requests_io_.find(socket);\n it2->second.erase(request);\n request_to_buffer_io_.erase(request);\n delete request;\n}\n\nvoid DevToolsHttpProtocolHandler::Send200(HttpListenSocket* socket,\n const std::string& data,\n const std::string& mime_type) {\n BrowserThread::PostTask(\n BrowserThread::IO, FROM_HERE,\n NewRunnableMethod(socket,\n &HttpListenSocket::Send200,\n data,\n mime_type));\n}\n\nvoid DevToolsHttpProtocolHandler::Send404(HttpListenSocket* socket) {\n BrowserThread::PostTask(\n BrowserThread::IO, FROM_HERE,\n NewRunnableMethod(socket,\n &HttpListenSocket::Send404));\n}\n\nvoid DevToolsHttpProtocolHandler::Send500(HttpListenSocket* socket,\n const std::string& message) {\n BrowserThread::PostTask(\n BrowserThread::IO, FROM_HERE,\n NewRunnableMethod(socket,\n &HttpListenSocket::Send500,\n message));\n}\n\nvoid DevToolsHttpProtocolHandler::AcceptWebSocket(\n HttpListenSocket* socket,\n const HttpServerRequestInfo& request) {\n BrowserThread::PostTask(\n BrowserThread::IO, FROM_HERE,\n NewRunnableMethod(socket,\n &HttpListenSocket::AcceptWebSocket,\n request));\n}\n\nvoid DevToolsHttpProtocolHandler::ReleaseSocket(\n HttpListenSocket* socket) {\n \/\/ This in fact is scoped ref ptr. It'll get nuked on exit.\n}\n\nTabContents* DevToolsHttpProtocolHandler::GetTabContents(int session_id) {\n for (BrowserList::const_iterator it = BrowserList::begin(),\n end = BrowserList::end(); it != end; ++it) {\n TabStripModel* model = (*it)->tabstrip_model();\n for (int i = 0, size = model->count(); i < size; ++i) {\n NavigationController& controller =\n model->GetTabContentsAt(i)->controller();\n if (controller.session_id().id() == session_id)\n return controller.tab_contents();\n }\n }\n return NULL;\n}\n<commit_msg>DevTools: a better fix for socket closure crash.<commit_after>\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/debugger\/devtools_http_protocol_handler.h\"\n\n#include \"base\/compiler_specific.h\"\n#include \"base\/logging.h\"\n#include \"base\/message_loop_proxy.h\"\n#include \"base\/string_number_conversions.h\"\n#include \"base\/thread.h\"\n#include \"base\/utf_string_conversions.h\"\n#include \"chrome\/browser\/browser_list.h\"\n#include \"chrome\/browser\/browser_thread.h\"\n#include \"chrome\/browser\/debugger\/devtools_client_host.h\"\n#include \"chrome\/browser\/debugger\/devtools_manager.h\"\n#include \"chrome\/browser\/profiles\/profile.h\"\n#include \"chrome\/browser\/tab_contents\/tab_contents.h\"\n#include \"chrome\/browser\/tabs\/tab_strip_model.h\"\n#include \"chrome\/browser\/ui\/browser.h\"\n#include \"chrome\/browser\/ui\/tab_contents\/tab_contents_wrapper.h\"\n#include \"chrome\/common\/devtools_messages.h\"\n#include \"chrome\/common\/net\/url_request_context_getter.h\"\n#include \"googleurl\/src\/gurl.h\"\n#include \"net\/base\/io_buffer.h\"\n#include \"net\/base\/listen_socket.h\"\n#include \"net\/server\/http_server_request_info.h\"\n#include \"net\/url_request\/url_request_context.h\"\n\nconst int kBufferSize = 16 * 1024;\n\nnamespace {\n\n\/\/ An internal implementation of DevToolsClientHost that delegates\n\/\/ messages sent for DevToolsClient to a DebuggerShell instance.\nclass DevToolsClientHostImpl : public DevToolsClientHost {\n public:\n explicit DevToolsClientHostImpl(HttpListenSocket* socket)\n : socket_(socket) {}\n ~DevToolsClientHostImpl() {}\n\n \/\/ DevToolsClientHost interface\n virtual void InspectedTabClosing() {\n BrowserThread::PostTask(\n BrowserThread::IO,\n FROM_HERE,\n NewRunnableMethod(socket_,\n &HttpListenSocket::Close));\n }\n\n virtual void SendMessageToClient(const IPC::Message& msg) {\n IPC_BEGIN_MESSAGE_MAP(DevToolsClientHostImpl, msg)\n IPC_MESSAGE_HANDLER(DevToolsClientMsg_DispatchOnInspectorFrontend,\n OnDispatchOnInspectorFrontend);\n IPC_MESSAGE_UNHANDLED_ERROR()\n IPC_END_MESSAGE_MAP()\n }\n\n void NotifyCloseListener() {\n DevToolsClientHost::NotifyCloseListener();\n }\n private:\n \/\/ Message handling routines\n void OnDispatchOnInspectorFrontend(const std::string& data) {\n socket_->SendOverWebSocket(data);\n }\n HttpListenSocket* socket_;\n};\n\n}\n\nDevToolsHttpProtocolHandler::~DevToolsHttpProtocolHandler() {\n \/\/ Stop() must be called prior to this being called\n DCHECK(server_.get() == NULL);\n}\n\nvoid DevToolsHttpProtocolHandler::Start() {\n BrowserThread::PostTask(\n BrowserThread::IO, FROM_HERE,\n NewRunnableMethod(this, &DevToolsHttpProtocolHandler::Init));\n}\n\nvoid DevToolsHttpProtocolHandler::Stop() {\n BrowserThread::PostTask(\n BrowserThread::IO, FROM_HERE,\n NewRunnableMethod(this, &DevToolsHttpProtocolHandler::Teardown));\n}\n\nvoid DevToolsHttpProtocolHandler::OnHttpRequest(\n HttpListenSocket* socket,\n const HttpServerRequestInfo& info) {\n if (info.path == \"\" || info.path == \"\/\") {\n \/\/ Pages discovery request.\n BrowserThread::PostTask(\n BrowserThread::UI,\n FROM_HERE,\n NewRunnableMethod(this,\n &DevToolsHttpProtocolHandler::OnHttpRequestUI,\n make_scoped_refptr(socket),\n info));\n return;\n }\n\n size_t pos = info.path.find(\"\/devtools\/\");\n if (pos != 0) {\n socket->Send404();\n return;\n }\n\n \/\/ Proxy static files from chrome:\/\/devtools\/*.\n net::URLRequest* request = new net::URLRequest(\n GURL(\"chrome:\/\" + info.path), this);\n Bind(request, socket);\n request->set_context(\n Profile::GetDefaultRequestContext()->GetURLRequestContext());\n request->Start();\n}\n\nvoid DevToolsHttpProtocolHandler::OnWebSocketRequest(\n HttpListenSocket* socket,\n const HttpServerRequestInfo& request) {\n BrowserThread::PostTask(\n BrowserThread::UI,\n FROM_HERE,\n NewRunnableMethod(\n this,\n &DevToolsHttpProtocolHandler::OnWebSocketRequestUI,\n make_scoped_refptr(socket),\n request));\n}\n\nvoid DevToolsHttpProtocolHandler::OnWebSocketMessage(HttpListenSocket* socket,\n const std::string& data) {\n BrowserThread::PostTask(\n BrowserThread::UI,\n FROM_HERE,\n NewRunnableMethod(\n this,\n &DevToolsHttpProtocolHandler::OnWebSocketMessageUI,\n make_scoped_refptr(socket),\n data));\n}\n\nvoid DevToolsHttpProtocolHandler::OnClose(HttpListenSocket* socket) {\n SocketToRequestsMap::iterator it = socket_to_requests_io_.find(socket);\n if (it != socket_to_requests_io_.end()) {\n \/\/ Dispose delegating socket.\n for (std::set<net::URLRequest*>::iterator it2 = it->second.begin();\n it2 != it->second.end(); ++it2) {\n net::URLRequest* request = *it2;\n request->Cancel();\n request_to_socket_io_.erase(request);\n request_to_buffer_io_.erase(request);\n delete request;\n }\n socket_to_requests_io_.erase(socket);\n }\n\n BrowserThread::PostTask(\n BrowserThread::UI,\n FROM_HERE,\n NewRunnableMethod(\n this,\n &DevToolsHttpProtocolHandler::OnCloseUI,\n make_scoped_refptr(socket)));\n}\n\nvoid DevToolsHttpProtocolHandler::OnHttpRequestUI(\n HttpListenSocket* socket,\n const HttpServerRequestInfo& info) {\n std::string response = \"<html><body>\";\n for (BrowserList::const_iterator it = BrowserList::begin(),\n end = BrowserList::end(); it != end; ++it) {\n TabStripModel* model = (*it)->tabstrip_model();\n for (int i = 0, size = model->count(); i < size; ++i) {\n TabContentsWrapper* tab_contents = model->GetTabContentsAt(i);\n NavigationController& controller = tab_contents->controller();\n NavigationEntry* entry = controller.GetActiveEntry();\n if (entry == NULL)\n continue;\n\n if (!entry->url().is_valid())\n continue;\n\n DevToolsClientHost* client_host = DevToolsManager::GetInstance()->\n GetDevToolsClientHostFor(tab_contents->tab_contents()->\n render_view_host());\n if (!client_host) {\n response += StringPrintf(\n \"<a href='\/devtools\/devtools.html?page=%d'>%s (%s)<\/a><br>\",\n controller.session_id().id(),\n UTF16ToUTF8(entry->title()).c_str(),\n entry->url().spec().c_str());\n } else {\n response += StringPrintf(\n \"%s (%s)<br>\",\n UTF16ToUTF8(entry->title()).c_str(),\n entry->url().spec().c_str());\n }\n }\n }\n response += \"<\/body><\/html>\";\n Send200(socket, response, \"text\/html; charset=UTF-8\");\n}\n\nvoid DevToolsHttpProtocolHandler::OnWebSocketRequestUI(\n HttpListenSocket* socket,\n const HttpServerRequestInfo& request) {\n std::string prefix = \"\/devtools\/page\/\";\n size_t pos = request.path.find(prefix);\n if (pos != 0) {\n Send404(socket);\n return;\n }\n std::string page_id = request.path.substr(prefix.length());\n int id = 0;\n if (!base::StringToInt(page_id, &id)) {\n Send500(socket, \"Invalid page id: \" + page_id);\n return;\n }\n\n TabContents* tab_contents = GetTabContents(id);\n if (tab_contents == NULL) {\n Send500(socket, \"No such page id: \" + page_id);\n return;\n }\n\n DevToolsManager* manager = DevToolsManager::GetInstance();\n if (manager->GetDevToolsClientHostFor(tab_contents->render_view_host())) {\n Send500(socket, \"Page with given id is being inspected: \" + page_id);\n return;\n }\n\n DevToolsClientHostImpl* client_host = new DevToolsClientHostImpl(socket);\n socket_to_client_host_ui_[socket] = client_host;\n\n manager->RegisterDevToolsClientHostFor(\n tab_contents->render_view_host(),\n client_host);\n AcceptWebSocket(socket, request);\n}\n\nvoid DevToolsHttpProtocolHandler::OnWebSocketMessageUI(\n HttpListenSocket* socket,\n const std::string& data) {\n SocketToClientHostMap::iterator it = socket_to_client_host_ui_.find(socket);\n if (it == socket_to_client_host_ui_.end())\n return;\n\n DevToolsManager* manager = DevToolsManager::GetInstance();\n\n if (data == \"loaded\") {\n manager->ForwardToDevToolsAgent(\n it->second,\n DevToolsAgentMsg_FrontendLoaded());\n return;\n }\n\n manager->ForwardToDevToolsAgent(\n it->second,\n DevToolsAgentMsg_DispatchOnInspectorBackend(data));\n}\n\nvoid DevToolsHttpProtocolHandler::OnCloseUI(HttpListenSocket* socket) {\n SocketToClientHostMap::iterator it = socket_to_client_host_ui_.find(socket);\n if (it != socket_to_client_host_ui_.end()) {\n DevToolsClientHostImpl* client_host =\n static_cast<DevToolsClientHostImpl*>(it->second);\n client_host->NotifyCloseListener();\n delete client_host;\n socket_to_client_host_ui_.erase(socket);\n }\n\n \/\/ We are holding last reference to scoped refptr 'socket' here.\n \/\/ We can't exit method just like that since 'socket' is going to\n \/\/ be destroyed on the UI thread then. Schedule no-op to IO thread\n \/\/ so that socket is destroyed on IO instead.\n BrowserThread::PostTask(\n BrowserThread::IO,\n FROM_HERE,\n NewRunnableMethod(\n this,\n &DevToolsHttpProtocolHandler::ReleaseSocket,\n make_scoped_refptr(socket)));\n}\n\nvoid DevToolsHttpProtocolHandler::OnResponseStarted(net::URLRequest* request) {\n RequestToSocketMap::iterator it = request_to_socket_io_.find(request);\n if (it == request_to_socket_io_.end())\n return;\n\n HttpListenSocket* socket = it->second;\n\n int expected_size = static_cast<int>(request->GetExpectedContentSize());\n\n std::string content_type;\n request->GetMimeType(&content_type);\n\n if (request->status().is_success()) {\n socket->Send(StringPrintf(\"HTTP\/1.1 200 OK\\r\\n\"\n \"Content-Type:%s\\r\\n\"\n \"Content-Length:%d\\r\\n\"\n \"\\r\\n\",\n content_type.c_str(),\n expected_size));\n } else {\n socket->Send404();\n }\n\n int bytes_read = 0;\n \/\/ Some servers may treat HEAD requests as GET requests. To free up the\n \/\/ network connection as soon as possible, signal that the request has\n \/\/ completed immediately, without trying to read any data back (all we care\n \/\/ about is the response code and headers, which we already have).\n net::IOBuffer* buffer = request_to_buffer_io_[request].get();\n if (request->status().is_success())\n request->Read(buffer, kBufferSize, &bytes_read);\n OnReadCompleted(request, bytes_read);\n}\n\nvoid DevToolsHttpProtocolHandler::OnReadCompleted(net::URLRequest* request,\n int bytes_read) {\n RequestToSocketMap::iterator it = request_to_socket_io_.find(request);\n if (it == request_to_socket_io_.end())\n return;\n\n HttpListenSocket* socket = it->second;\n\n net::IOBuffer* buffer = request_to_buffer_io_[request].get();\n do {\n if (!request->status().is_success() || bytes_read <= 0)\n break;\n socket->Send(buffer->data(), bytes_read);\n } while (request->Read(buffer, kBufferSize, &bytes_read));\n\n \/\/ See comments re: HEAD requests in OnResponseStarted().\n if (!request->status().is_io_pending())\n RequestCompleted(request);\n}\n\nDevToolsHttpProtocolHandler::DevToolsHttpProtocolHandler(int port)\n : port_(port),\n server_(NULL) {\n}\n\nvoid DevToolsHttpProtocolHandler::Init() {\n server_ = HttpListenSocket::Listen(\"127.0.0.1\", port_, this);\n}\n\n\/\/ Run on I\/O thread\nvoid DevToolsHttpProtocolHandler::Teardown() {\n server_ = NULL;\n}\n\nvoid DevToolsHttpProtocolHandler::Bind(net::URLRequest* request,\n HttpListenSocket* socket) {\n request_to_socket_io_[request] = socket;\n SocketToRequestsMap::iterator it = socket_to_requests_io_.find(socket);\n if (it == socket_to_requests_io_.end()) {\n std::pair<HttpListenSocket*, std::set<net::URLRequest*> > value(\n socket,\n std::set<net::URLRequest*>());\n it = socket_to_requests_io_.insert(value).first;\n }\n it->second.insert(request);\n request_to_buffer_io_[request] = new net::IOBuffer(kBufferSize);\n}\n\nvoid DevToolsHttpProtocolHandler::RequestCompleted(net::URLRequest* request) {\n RequestToSocketMap::iterator it = request_to_socket_io_.find(request);\n if (it == request_to_socket_io_.end())\n return;\n\n HttpListenSocket* socket = it->second;\n request_to_socket_io_.erase(request);\n SocketToRequestsMap::iterator it2 = socket_to_requests_io_.find(socket);\n it2->second.erase(request);\n request_to_buffer_io_.erase(request);\n delete request;\n}\n\nvoid DevToolsHttpProtocolHandler::Send200(HttpListenSocket* socket,\n const std::string& data,\n const std::string& mime_type) {\n BrowserThread::PostTask(\n BrowserThread::IO, FROM_HERE,\n NewRunnableMethod(socket,\n &HttpListenSocket::Send200,\n data,\n mime_type));\n}\n\nvoid DevToolsHttpProtocolHandler::Send404(HttpListenSocket* socket) {\n BrowserThread::PostTask(\n BrowserThread::IO, FROM_HERE,\n NewRunnableMethod(socket,\n &HttpListenSocket::Send404));\n}\n\nvoid DevToolsHttpProtocolHandler::Send500(HttpListenSocket* socket,\n const std::string& message) {\n BrowserThread::PostTask(\n BrowserThread::IO, FROM_HERE,\n NewRunnableMethod(socket,\n &HttpListenSocket::Send500,\n message));\n}\n\nvoid DevToolsHttpProtocolHandler::AcceptWebSocket(\n HttpListenSocket* socket,\n const HttpServerRequestInfo& request) {\n BrowserThread::PostTask(\n BrowserThread::IO, FROM_HERE,\n NewRunnableMethod(socket,\n &HttpListenSocket::AcceptWebSocket,\n request));\n}\n\nvoid DevToolsHttpProtocolHandler::ReleaseSocket(\n HttpListenSocket* socket) {\n \/\/ This in fact is scoped ref ptr. It'll get nuked on exit.\n}\n\nTabContents* DevToolsHttpProtocolHandler::GetTabContents(int session_id) {\n for (BrowserList::const_iterator it = BrowserList::begin(),\n end = BrowserList::end(); it != end; ++it) {\n TabStripModel* model = (*it)->tabstrip_model();\n for (int i = 0, size = model->count(); i < size; ++i) {\n NavigationController& controller =\n model->GetTabContentsAt(i)->controller();\n if (controller.session_id().id() == session_id)\n return controller.tab_contents();\n }\n }\n return NULL;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (C) 2016 Patrizio Bekerle -- http:\/\/www.bekerle.com\n *\n * This program is free software; you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; version 2 of the License.\n *\n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY\n * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License\n * for more details.\n *\n *\/\n\n#include \"qtexteditsearchwidget.h\"\n#include \"ui_qtexteditsearchwidget.h\"\n#include <QEvent>\n#include <QKeyEvent>\n#include <QDebug>\n\nQTextEditSearchWidget::QTextEditSearchWidget(QTextEdit *parent) :\n QWidget(parent),\n ui(new Ui::QTextEditSearchWidget)\n{\n ui->setupUi(this);\n _textEdit = parent;\n hide();\n\n QObject::connect(ui->closeButton, SIGNAL(clicked()),\n this, SLOT(deactivate()));\n QObject::connect(ui->searchLineEdit, SIGNAL(textChanged(const QString &)),\n this, SLOT(searchLineEditTextChanged(const QString &)));\n QObject::connect(ui->searchDownButton, SIGNAL(clicked()),\n this, SLOT(doSearchDown()));\n QObject::connect(ui->searchUpButton, SIGNAL(clicked()),\n this, SLOT(doSearchUp()));\n QObject::connect(ui->replaceToggleButton, SIGNAL(toggled(bool)),\n this, SLOT(setReplaceMode(bool)));\n QObject::connect(ui->replaceButton, SIGNAL(clicked()),\n this, SLOT(doReplace()));\n QObject::connect(ui->replaceAllButton, SIGNAL(clicked()),\n this, SLOT(doReplaceAll()));\n\n installEventFilter(this);\n ui->searchLineEdit->installEventFilter(this);\n ui->replaceLineEdit->installEventFilter(this);\n\n#ifdef Q_OS_MAC\n \/\/ set the spacing to 8 for OS X\n layout()->setSpacing(8);\n ui->buttonFrame->layout()->setSpacing(9);\n\n \/\/ set the margin to 0 for the top buttons for OS X\n QString buttonStyle = \"QPushButton {margin: 0}\";\n ui->closeButton->setStyleSheet(buttonStyle);\n ui->searchDownButton->setStyleSheet(buttonStyle);\n ui->searchUpButton->setStyleSheet(buttonStyle);\n ui->replaceToggleButton->setStyleSheet(buttonStyle);\n ui->matchCaseSensitiveButton->setStyleSheet(buttonStyle);\n#endif\n}\n\nQTextEditSearchWidget::~QTextEditSearchWidget() {\n delete ui;\n}\n\nvoid QTextEditSearchWidget::activate() {\n setReplaceMode(false);\n show();\n ui->searchLineEdit->setFocus();\n ui->searchLineEdit->selectAll();\n doSearchDown();\n}\n\nvoid QTextEditSearchWidget::activateReplace() {\n \/\/ replacing is prohibited if the text edit is readonly\n if (_textEdit->isReadOnly()) {\n return;\n }\n\n ui->searchLineEdit->setText(_textEdit->textCursor().selectedText());\n ui->searchLineEdit->selectAll();\n activate();\n setReplaceMode(true);\n}\n\nvoid QTextEditSearchWidget::deactivate() {\n hide();\n _textEdit->setFocus();\n}\n\nvoid QTextEditSearchWidget::setReplaceMode(bool enabled) {\n ui->replaceToggleButton->setChecked(enabled);\n ui->replaceLabel->setVisible(enabled);\n ui->replaceLineEdit->setVisible(enabled);\n ui->modeLabel->setVisible(enabled);\n ui->buttonFrame->setVisible(enabled);\n ui->matchCaseSensitiveButton->setVisible(enabled);\n}\n\nbool QTextEditSearchWidget::eventFilter(QObject *obj, QEvent *event) {\n if (event->type() == QEvent::KeyPress) {\n QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event);\n\n if (keyEvent->key() == Qt::Key_Escape) {\n deactivate();\n return true;\n } else if ((keyEvent->modifiers().testFlag(Qt::ShiftModifier) &&\n (keyEvent->key() == Qt::Key_Return)) ||\n (keyEvent->key() == Qt::Key_Up)) {\n doSearchUp();\n return true;\n } else if ((keyEvent->key() == Qt::Key_Return) ||\n (keyEvent->key() == Qt::Key_Down)) {\n doSearchDown();\n return true;\n } else if (keyEvent->key() == Qt::Key_F3) {\n doSearch(!keyEvent->modifiers().testFlag(Qt::ShiftModifier));\n return true;\n }\n\n\/\/ if ((obj == ui->replaceLineEdit) && (keyEvent->key() == Qt::Key_Tab)\n\/\/ && ui->replaceToggleButton->isChecked()) {\n\/\/ ui->replaceLineEdit->setFocus();\n\/\/ }\n\n return false;\n }\n\n return QWidget::eventFilter(obj, event);\n}\n\nvoid QTextEditSearchWidget::searchLineEditTextChanged(const QString &arg1) {\n Q_UNUSED(arg1);\n doSearchDown();\n}\n\nvoid QTextEditSearchWidget::doSearchUp() {\n doSearch(false);\n}\n\nvoid QTextEditSearchWidget::doSearchDown() {\n doSearch(true);\n}\n\nbool QTextEditSearchWidget::doReplace(bool forAll) {\n if (_textEdit->isReadOnly()) {\n return false;\n }\n\n QTextCursor c = _textEdit->textCursor();\n\n if (!forAll && c.selectedText().isEmpty()) {\n return false;\n }\n\n int searchMode = ui->modeComboBox->currentIndex();\n if (searchMode == RegularExpressionMode) {\n QString text = c.selectedText();\n text.replace(QRegExp(ui->searchLineEdit->text()),\n ui->replaceLineEdit->text());\n c.insertText(text);\n } else {\n c.insertText(ui->replaceLineEdit->text());\n }\n\n if (!forAll) {\n int position = c.position();\n\n if (!doSearch(true)) {\n \/\/ restore the last cursor position if text wasn't found any more\n c.setPosition(position);\n _textEdit->setTextCursor(c);\n }\n }\n\n return true;\n}\n\nvoid QTextEditSearchWidget::doReplaceAll() {\n if (_textEdit->isReadOnly()) {\n return;\n }\n\n \/\/ start at the top\n _textEdit->moveCursor(QTextCursor::Start);\n\n \/\/ replace until everything to the bottom is replaced\n while (doSearch(true, false) && doReplace(true)) {}\n}\n\n\/**\n * @brief Searches for text in the text edit\n * @returns true if found\n *\/\nbool QTextEditSearchWidget::doSearch(bool searchDown, bool allowRestartAtTop) {\n QString text = ui->searchLineEdit->text();\n\n if (text == \"\") {\n ui->searchLineEdit->setStyleSheet(\"* { background: none; }\");\n return false;\n }\n\n int searchMode = ui->modeComboBox->currentIndex();\n\n QFlags<QTextDocument::FindFlag> options = searchDown ?\n QTextDocument::FindFlag(0)\n : QTextDocument::FindBackward;\n if (searchMode == WholeWordsMode) {\n options |= QTextDocument::FindWholeWords;\n }\n\n if (ui->matchCaseSensitiveButton->isChecked()) {\n options |= QTextDocument::FindCaseSensitively;\n }\n\n bool found;\n if (searchMode == RegularExpressionMode) {\n found = _textEdit->find(QRegExp(text), options);\n } else {\n found = _textEdit->find(text, options);\n }\n\n \/\/ start at the top (or bottom) if not found\n if (!found && allowRestartAtTop) {\n _textEdit->moveCursor(\n searchDown ? QTextCursor::Start : QTextCursor::End);\n found = _textEdit->find(text, options);\n }\n\n QRect rect = _textEdit->cursorRect();\n QMargins margins = _textEdit->layout()->contentsMargins();\n int searchWidgetHotArea = _textEdit->height() - this->height();\n int marginBottom = (rect.y() > searchWidgetHotArea) ? (this->height() + 10)\n : 0;\n\n \/\/ move the search box a bit up if we would block the search result\n if (margins.bottom() != marginBottom) {\n margins.setBottom(marginBottom);\n _textEdit->layout()->setContentsMargins(margins);\n }\n\n \/\/ add a background color according if we found the text or not\n QString colorCode = found ? \"#D5FAE2\" : \"#FAE9EB\";\n ui->searchLineEdit->setStyleSheet(\"* { background: \" + colorCode + \"; }\");\n\n return found;\n}\n\n<commit_msg>when doing a text search in your note the selected text is now preset as search text if there is any and there is no other search text filled in<commit_after>\/*\n * Copyright (C) 2016 Patrizio Bekerle -- http:\/\/www.bekerle.com\n *\n * This program is free software; you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; version 2 of the License.\n *\n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY\n * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License\n * for more details.\n *\n *\/\n\n#include \"qtexteditsearchwidget.h\"\n#include \"ui_qtexteditsearchwidget.h\"\n#include <QEvent>\n#include <QKeyEvent>\n#include <QDebug>\n\nQTextEditSearchWidget::QTextEditSearchWidget(QTextEdit *parent) :\n QWidget(parent),\n ui(new Ui::QTextEditSearchWidget)\n{\n ui->setupUi(this);\n _textEdit = parent;\n hide();\n\n QObject::connect(ui->closeButton, SIGNAL(clicked()),\n this, SLOT(deactivate()));\n QObject::connect(ui->searchLineEdit, SIGNAL(textChanged(const QString &)),\n this, SLOT(searchLineEditTextChanged(const QString &)));\n QObject::connect(ui->searchDownButton, SIGNAL(clicked()),\n this, SLOT(doSearchDown()));\n QObject::connect(ui->searchUpButton, SIGNAL(clicked()),\n this, SLOT(doSearchUp()));\n QObject::connect(ui->replaceToggleButton, SIGNAL(toggled(bool)),\n this, SLOT(setReplaceMode(bool)));\n QObject::connect(ui->replaceButton, SIGNAL(clicked()),\n this, SLOT(doReplace()));\n QObject::connect(ui->replaceAllButton, SIGNAL(clicked()),\n this, SLOT(doReplaceAll()));\n\n installEventFilter(this);\n ui->searchLineEdit->installEventFilter(this);\n ui->replaceLineEdit->installEventFilter(this);\n\n#ifdef Q_OS_MAC\n \/\/ set the spacing to 8 for OS X\n layout()->setSpacing(8);\n ui->buttonFrame->layout()->setSpacing(9);\n\n \/\/ set the margin to 0 for the top buttons for OS X\n QString buttonStyle = \"QPushButton {margin: 0}\";\n ui->closeButton->setStyleSheet(buttonStyle);\n ui->searchDownButton->setStyleSheet(buttonStyle);\n ui->searchUpButton->setStyleSheet(buttonStyle);\n ui->replaceToggleButton->setStyleSheet(buttonStyle);\n ui->matchCaseSensitiveButton->setStyleSheet(buttonStyle);\n#endif\n}\n\nQTextEditSearchWidget::~QTextEditSearchWidget() {\n delete ui;\n}\n\nvoid QTextEditSearchWidget::activate() {\n setReplaceMode(false);\n show();\n\n \/\/ preset the selected text as search text if there is any and there is no\n \/\/ other search text\n QString selectedText = _textEdit->textCursor().selectedText();\n if (!selectedText.isEmpty() && ui->searchLineEdit->text().isEmpty()) {\n ui->searchLineEdit->setText(selectedText);\n }\n\n ui->searchLineEdit->setFocus();\n ui->searchLineEdit->selectAll();\n doSearchDown();\n}\n\nvoid QTextEditSearchWidget::activateReplace() {\n \/\/ replacing is prohibited if the text edit is readonly\n if (_textEdit->isReadOnly()) {\n return;\n }\n\n ui->searchLineEdit->setText(_textEdit->textCursor().selectedText());\n ui->searchLineEdit->selectAll();\n activate();\n setReplaceMode(true);\n}\n\nvoid QTextEditSearchWidget::deactivate() {\n hide();\n _textEdit->setFocus();\n}\n\nvoid QTextEditSearchWidget::setReplaceMode(bool enabled) {\n ui->replaceToggleButton->setChecked(enabled);\n ui->replaceLabel->setVisible(enabled);\n ui->replaceLineEdit->setVisible(enabled);\n ui->modeLabel->setVisible(enabled);\n ui->buttonFrame->setVisible(enabled);\n ui->matchCaseSensitiveButton->setVisible(enabled);\n}\n\nbool QTextEditSearchWidget::eventFilter(QObject *obj, QEvent *event) {\n if (event->type() == QEvent::KeyPress) {\n QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event);\n\n if (keyEvent->key() == Qt::Key_Escape) {\n deactivate();\n return true;\n } else if ((keyEvent->modifiers().testFlag(Qt::ShiftModifier) &&\n (keyEvent->key() == Qt::Key_Return)) ||\n (keyEvent->key() == Qt::Key_Up)) {\n doSearchUp();\n return true;\n } else if ((keyEvent->key() == Qt::Key_Return) ||\n (keyEvent->key() == Qt::Key_Down)) {\n doSearchDown();\n return true;\n } else if (keyEvent->key() == Qt::Key_F3) {\n doSearch(!keyEvent->modifiers().testFlag(Qt::ShiftModifier));\n return true;\n }\n\n\/\/ if ((obj == ui->replaceLineEdit) && (keyEvent->key() == Qt::Key_Tab)\n\/\/ && ui->replaceToggleButton->isChecked()) {\n\/\/ ui->replaceLineEdit->setFocus();\n\/\/ }\n\n return false;\n }\n\n return QWidget::eventFilter(obj, event);\n}\n\nvoid QTextEditSearchWidget::searchLineEditTextChanged(const QString &arg1) {\n Q_UNUSED(arg1);\n doSearchDown();\n}\n\nvoid QTextEditSearchWidget::doSearchUp() {\n doSearch(false);\n}\n\nvoid QTextEditSearchWidget::doSearchDown() {\n doSearch(true);\n}\n\nbool QTextEditSearchWidget::doReplace(bool forAll) {\n if (_textEdit->isReadOnly()) {\n return false;\n }\n\n QTextCursor c = _textEdit->textCursor();\n\n if (!forAll && c.selectedText().isEmpty()) {\n return false;\n }\n\n int searchMode = ui->modeComboBox->currentIndex();\n if (searchMode == RegularExpressionMode) {\n QString text = c.selectedText();\n text.replace(QRegExp(ui->searchLineEdit->text()),\n ui->replaceLineEdit->text());\n c.insertText(text);\n } else {\n c.insertText(ui->replaceLineEdit->text());\n }\n\n if (!forAll) {\n int position = c.position();\n\n if (!doSearch(true)) {\n \/\/ restore the last cursor position if text wasn't found any more\n c.setPosition(position);\n _textEdit->setTextCursor(c);\n }\n }\n\n return true;\n}\n\nvoid QTextEditSearchWidget::doReplaceAll() {\n if (_textEdit->isReadOnly()) {\n return;\n }\n\n \/\/ start at the top\n _textEdit->moveCursor(QTextCursor::Start);\n\n \/\/ replace until everything to the bottom is replaced\n while (doSearch(true, false) && doReplace(true)) {}\n}\n\n\/**\n * @brief Searches for text in the text edit\n * @returns true if found\n *\/\nbool QTextEditSearchWidget::doSearch(bool searchDown, bool allowRestartAtTop) {\n QString text = ui->searchLineEdit->text();\n\n if (text == \"\") {\n ui->searchLineEdit->setStyleSheet(\"* { background: none; }\");\n return false;\n }\n\n int searchMode = ui->modeComboBox->currentIndex();\n\n QFlags<QTextDocument::FindFlag> options = searchDown ?\n QTextDocument::FindFlag(0)\n : QTextDocument::FindBackward;\n if (searchMode == WholeWordsMode) {\n options |= QTextDocument::FindWholeWords;\n }\n\n if (ui->matchCaseSensitiveButton->isChecked()) {\n options |= QTextDocument::FindCaseSensitively;\n }\n\n bool found;\n if (searchMode == RegularExpressionMode) {\n found = _textEdit->find(QRegExp(text), options);\n } else {\n found = _textEdit->find(text, options);\n }\n\n \/\/ start at the top (or bottom) if not found\n if (!found && allowRestartAtTop) {\n _textEdit->moveCursor(\n searchDown ? QTextCursor::Start : QTextCursor::End);\n found = _textEdit->find(text, options);\n }\n\n QRect rect = _textEdit->cursorRect();\n QMargins margins = _textEdit->layout()->contentsMargins();\n int searchWidgetHotArea = _textEdit->height() - this->height();\n int marginBottom = (rect.y() > searchWidgetHotArea) ? (this->height() + 10)\n : 0;\n\n \/\/ move the search box a bit up if we would block the search result\n if (margins.bottom() != marginBottom) {\n margins.setBottom(marginBottom);\n _textEdit->layout()->setContentsMargins(margins);\n }\n\n \/\/ add a background color according if we found the text or not\n QString colorCode = found ? \"#D5FAE2\" : \"#FAE9EB\";\n ui->searchLineEdit->setStyleSheet(\"* { background: \" + colorCode + \"; }\");\n\n return found;\n}\n\n<|endoftext|>"} {"text":"<commit_before>#include \"disassembler.h\"\n#include \"util.h\"\n#include \"symtab.h\"\n\n#include <vector>\n#include <cctype>\n\nusing namespace std;\n\nenum ByteTypeGuess {\n\tUNINITIALIZED,\n\tUNKNOWN,\n\tCHAR_DATA,\n\tUNINITIALIZED_CHAR_DATA,\n\tWORD_DATA,\n\tUNINITIALIZED_WORD_DATA,\n\tCODE,\n};\n\nstruct program {\n\tByteTypeGuess byte_type_guess[65536];\n\tchar memory[65536];\n\tbool is_labelled[65536];\n\n\tstring name;\n\tstring starting_address;\n\tint length_of_program;\n\tstring first_executable_instruction;\n\tprogram() {\n\t\tfor ( int i = 0 ; i < 65536 ; i++ ) {\n\t\t\tbyte_type_guess[i] = UNINITIALIZED;\n\t\t\tmemory[i] = 0;\n\t\t\tis_labelled[i] = false;\n\t\t}\n\t\tname = \"\";\n\t\tstarting_address = \"\";\n\t\tlength_of_program = 0;\n\t\tfirst_executable_instruction = \"\";\n\t}\n};\n\nbool read_record(ifstream &ifile, string &record);\nvoid record_to_memory(const string record, program &p);\nvoid analyze_code_data(program &p);\nvoid write_assembly(const program &p, ofstream &ofile);\n\nbool disassemble(ifstream &ifile, ofstream &ofile) {\n\tstring record;\n\tprogram p;\n\twhile ( read_record(ifile, record) ) {\n\t\trecord_to_memory(record, p);\n\t}\n\tstatus(\"Done reading records\");\n\tanalyze_code_data(p);\n\tstatus(\"Done analyzing program for code and data\");\n\twrite_assembly(p, ofile);\n\tstatus(\"Done writing output file\");\n\treturn true;\n}\n\nstring read_columns(ifstream &ifile, int col_begin, int col_end, char record_type = 'a') { \/\/ inclusive of both\n\tstring ret;\n\tchar t;\n\tfor ( int col = col_begin ; col <= col_end ; col++ ) {\n\t\tt = ifile.get();\n\t\tif ( t == EOF || t == '\\n' ) {\n\t\t\tstring errstr;\n\t\t\terrstr += \"Unexpected end of \";\n\t\t\terrstr += record_type;\n\t\t\terrstr += \" record\";\n\t\t\tfatal(errstr);\n\t\t}\n\t\tret += t;\n\t}\n\treturn ret;\n}\n\nstring read_hex_columns(ifstream &ifile, int col_begin, int col_end, char record_type = 'a') { \/\/ inclusive of both\n\tstring ret;\n\tret = read_columns(ifile,col_begin,col_end,record_type);\n\tmake_upper_case(ret);\n\tif ( !is_hex_string(ret) ) {\n\t\tstring errstr;\n\t\terrstr += \"Unexpected non-hexadecimal character found in \";\n\t\terrstr += record_type;\n\t\terrstr += \" record\";\n\t\tfatal(errstr);\n\t}\n\treturn ret;\n}\n\nbool read_record(ifstream &ifile, string &record) {\n\tint temp_int;\n\tstring temp_str;\n\tchar t;\n\n\tdo {\n\t\tt = ifile.get();\n\t\tif ( t == EOF ) {\n\t\t\treturn false;\n\t\t}\n\t} while ( t == '\\n' || t == ' ' );\n\trecord = \"\";\n\trecord += t;\n\n\tswitch (t) {\n\t\tcase 'H': \/\/ Header\n\t\t\trecord += read_columns(ifile,2,7,'H');\n\t\t\trecord += read_hex_columns(ifile,8,19,'H');\n\t\t\tbreak;\n\t\tcase 'T': \/\/ Text\n\t\t\trecord += read_hex_columns(ifile,2,7,'T');\n\t\t\ttemp_str = read_hex_columns(ifile,8,9,'T');\n\t\t\ttemp_int = hex2int(temp_str);\n\t\t\trecord += temp_str;\n\t\t\trecord += read_hex_columns(ifile,10,9+2*temp_int,'T');\n\t\t\tbreak;\n\t\tcase 'E': \/\/ End\n\t\t\trecord += read_hex_columns(ifile,2,7,'E');\n\t\t\tbreak;\n\t\tdefault:\n\t\t\t{\n\t\t\t\tstring errstr = \"Unknown record type \";\n\t\t\t\terrstr += t;\n\t\t\t\tfatal(errstr);\n\t\t\t}\n\t}\n\treturn true;\n}\n\nvoid record_to_memory(const string record, program &p) {\n\tconst char * c_record = record.c_str();\n\tswitch (*c_record) {\n\t\tcase 'H': \/\/ Header\n\t\t\tif ( p.name.length() != 0 ) {\n\t\t\t\tfatal(\"Multiple H records\");\n\t\t\t}\n\t\t\tp.name = record.substr(1,6);\n\t\t\tp.starting_address = record.substr(7,6);\n\t\t\tp.length_of_program = hex2int(record.substr(13,6));\n\t\t\tbreak;\n\t\tcase 'T': \/\/ Text\n\t\t\t{\n\t\t\t\tint text_start = hex2int(record.substr(1,6));\n\t\t\t\tint bit_length = hex2int(record.substr(7,2));\n\t\t\t\tfor ( int i = 0 ; i < bit_length ; i++ ) {\n\t\t\t\t\tp.memory[i+text_start] = hex2int(record.substr(9+2*i,2));\n\t\t\t\t\tp.byte_type_guess[i+text_start] = UNKNOWN;\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak;\n\t\tcase 'E': \/\/ End\n\t\t\tif ( p.first_executable_instruction.length() != 0 ) {\n\t\t\t\tfatal(\"Multiple E records\");\n\t\t\t}\n\t\t\tp.first_executable_instruction = record.substr(1,6);\n\t\t\tbreak;\n\t\tdefault:\n\t\t\t{\n\t\t\t\tstring errstr;\n\t\t\t\terrstr += \"Unknown record type \";\n\t\t\t\terrstr += *c_record;\n\t\t\t\tfatal(errstr);\n\t\t\t}\n\t}\n}\n\nvoid mark_code_data(program &p, int location, ByteTypeGuess btg) {\n\tif ( location >= hex2int(p.starting_address) + p.length_of_program ) {\n\t\treturn;\n\t}\n\tswitch (btg) {\n\t\tcase UNINITIALIZED:\n\t\tcase UNKNOWN:\n\t\t\tbreak;\n\t\tcase CHAR_DATA:\n\t\tcase UNINITIALIZED_CHAR_DATA:\n\t\t\t{\n\t\t\t\tif ( p.byte_type_guess[location] != UNKNOWN &&\n\t\t\t\t\t p.byte_type_guess[location] != UNINITIALIZED ) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tif ( p.byte_type_guess[location] == UNINITIALIZED )\n\t\t\t\t\tbtg = UNINITIALIZED_CHAR_DATA;\n\t\t\t\tp.byte_type_guess[location] = btg;\n\t\t\t\tbreak;\n\t\t\t}\n\t\tcase WORD_DATA:\n\t\tcase UNINITIALIZED_WORD_DATA:\n\t\t\t{\n\t\t\t\tif ( p.byte_type_guess[location] != UNKNOWN &&\n\t\t\t\t\t p.byte_type_guess[location] != UNINITIALIZED ) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tif ( p.byte_type_guess[location] == UNINITIALIZED )\n\t\t\t\t\tbtg = UNINITIALIZED_WORD_DATA;\n\t\t\t\tp.byte_type_guess[location+0] = btg;\n\t\t\t\tp.byte_type_guess[location+1] = btg;\n\t\t\t\tp.byte_type_guess[location+2] = btg;\n\t\t\t\tbreak;\n\t\t\t}\n\t\tcase CODE:\n\t\t\t{\n\t\t\t\tif ( p.byte_type_guess[location] == UNINITIALIZED ) {\n\t\t\t\t\tfatal(\"Attempting to use uninitialized section as code\");\n\t\t\t\t}\n\t\t\t\tif ( p.byte_type_guess[location] == CODE ) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tp.byte_type_guess[location+0] = btg;\n\t\t\t\tp.byte_type_guess[location+1] = btg;\n\t\t\t\tp.byte_type_guess[location+2] = btg;\n\n\t\t\t\tstring opcode_val = byte2hex(p.memory[location]);\n\t\t\t\tstring opcode;\n\t\t\t\tstring operand = byte2hex(p.memory[location+1])+byte2hex(p.memory[location+2]);\n\t\t\t\toperand = int2hex(hex2int(operand)&0x7FFF); \/\/ remove index flag\n\t\t\t\tif ( ! find_from_symtab(opcode,opcode_val) ) {\n\t\t\t\t\tstring errstr;\n\t\t\t\t\terrstr += \"Unknown opcode \";\n\t\t\t\t\terrstr += opcode_val;\n\t\t\t\t\terrstr += \" at location \";\n\t\t\t\t\terrstr += int2hex(location);\n\t\t\t\t\tfatal(errstr);\n\t\t\t\t}\n\n\t\t\t\tif ( opcode == \"ADD\" ||\n\t\t\t\t\t opcode == \"AND\" ||\n\t\t\t\t\t opcode == \"COMP\" ||\n\t\t\t\t\t opcode == \"DIV\" ||\n\t\t\t\t\t opcode == \"LDA\" ||\n\t\t\t\t\t opcode == \"LDL\" ||\n\t\t\t\t\t opcode == \"LDX\" ||\n\t\t\t\t\t opcode == \"MUL\" ||\n\t\t\t\t\t opcode == \"OR\" ||\n\t\t\t\t\t opcode == \"STA\" ||\n\t\t\t\t\t opcode == \"STL\" ||\n\t\t\t\t\t opcode == \"STX\" ||\n\t\t\t\t\t opcode == \"SUB\" ||\n\t\t\t\t\t opcode == \"TIX\" ) {\n\t\t\t\t\tgive_label(operand);\n\t\t\t\t\tp.is_labelled[hex2int(operand)] = true;\n\t\t\t\t\tmark_code_data(p,hex2int(operand),WORD_DATA);\n\t\t\t\t}\n\n\t\t\t\tif ( opcode == \"LDCH\" ||\n\t\t\t\t\t opcode == \"STCH\" ) {\n\t\t\t\t\tgive_label(operand);\n\t\t\t\t\tp.is_labelled[hex2int(operand)] = true;\n\t\t\t\t\tmark_code_data(p,hex2int(operand),CHAR_DATA);\n\t\t\t\t}\n\n\t\t\t\tif ( opcode == \"J\" ||\n\t\t\t\t\t opcode == \"JEQ\" ||\n\t\t\t\t\t opcode == \"JGT\" ||\n\t\t\t\t\t opcode == \"JLT\" ||\n\t\t\t\t\t opcode == \"JSUB\" ||\n\t\t\t\t\t opcode == \"RSUB\" ) {\n\t\t\t\t\tgive_label(operand);\n\t\t\t\t\tp.is_labelled[hex2int(operand)] = true;\n\t\t\t\t\tmark_code_data(p,hex2int(operand),CODE);\n\t\t\t\t}\n\n\t\t\t\tif ( opcode != \"J\" &&\n\t\t\t\t\t opcode != \"RSUB\" ) {\n\t\t\t\t\tmark_code_data(p,location+3,btg);\n\t\t\t\t}\n\n\t\t\t\tbreak;\n\t\t\t}\n\t}\n}\n\nvoid analyze_code_data(program &p) {\n\tif ( p.name.length() == 0 ) {\n\t\tfatal(\"No Header record\");\n\t}\n\tif ( p.first_executable_instruction.length() == 0 ) {\n\t\tfatal(\"No End record\");\n\t}\n\tinitialize_symtab();\n\tadd_to_symtab(\"FIRST\",p.first_executable_instruction);\n\tp.is_labelled[hex2int(p.first_executable_instruction)] = true;\n\tmark_code_data(p,hex2int(p.first_executable_instruction),CODE);\n}\n\nstring asm_to_line(string label, string opcode, string operand, bool is_indexed) {\n\tconst int labellength = 8;\n\tconst int opcodelength = 6;\n\tstring ret = \"\";\n\tret += label + string(labellength-label.length(),' ');\n\tret += opcode + string(opcodelength-opcode.length(),' ');\n\tret += operand;\n\tif ( is_indexed ) {\n\t\tret += \",X\";\n\t}\n\tret += '\\n';\n\treturn ret;\n}\n\nvoid write_assembly(const program &p, ofstream &ofile) {\n\tofile << asm_to_line(p.name,\"START\",p.starting_address,false);\n\tint start_of_program = hex2int(p.starting_address);\n\tint end_of_program = start_of_program + p.length_of_program;\n\n\tfor ( int locctr = start_of_program ; locctr < end_of_program ; ) {\n\t\tstring label = \"\";\n\t\tstring opcode = \"\";\n\t\tstring operand = \"\";\n\t\tbool is_indexed = false;\n\n\t\tif ( p.byte_type_guess[locctr] == CODE ) {\n\t\t\tif ( ! find_from_symtab(opcode,byte2hex(p.memory[locctr])) ) {\n\t\t\t\tstring errstr;\n\t\t\t\terrstr += \"Unknown opcode \";\n\t\t\t\terrstr += opcode;\n\t\t\t\terrstr += \" at location \";\n\t\t\t\terrstr += int2hex(locctr);\n\t\t\t\tfatal(errstr);\n\t\t\t}\n\t\t\toperand = byte2hex(p.memory[locctr+1])+byte2hex(p.memory[locctr+2]);\n\t\t\tis_indexed = (hex2int(operand)&0x8000);\n\t\t\toperand = int2hex(hex2int(operand)&0x7FFF); \/\/ remove index flag\n\n\t\t\tif ( opcode != \"RD\" &&\n\t\t\t\t opcode != \"TD\" &&\n\t\t\t\t opcode != \"WD\" &&\n\t\t\t\t opcode != \"RSUB\" ) {\n\t\t\t\tif ( !find_from_symtab(operand,operand) ) {\n\t\t\t\t\tstring errstr;\n\t\t\t\t\terrstr += \"Label not created for operand \";\n\t\t\t\t\terrstr += operand;\n\t\t\t\t\terror(errstr);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif ( opcode == \"RSUB\" ) {\n\t\t\t\toperand = \"\";\n\t\t\t}\n\n\t\t\tlabel = \"\";\n\t\t\tif ( p.is_labelled[locctr] ) {\n\t\t\t\tif ( !find_from_symtab(label,int2hex(locctr)) ) {\n\t\t\t\t\tstring errstr;\n\t\t\t\t\terrstr += \"Label not created for location \";\n\t\t\t\t\terrstr += int2hex(locctr);\n\t\t\t\t\terror(errstr);\n\t\t\t\t}\n\t\t\t} \/\/ TODO: Refactor to prevent rewrite of code\n\n\t\t\tlocctr += 3;\n\t\t} else if ( p.byte_type_guess[locctr] == CHAR_DATA ) {\n\t\t\tif ( p.is_labelled[locctr] ) {\n\t\t\t\tif ( !find_from_symtab(label,int2hex(locctr)) ) {\n\t\t\t\t\tstring errstr;\n\t\t\t\t\terrstr += \"Label not created for location \";\n\t\t\t\t\terrstr += int2hex(locctr);\n\t\t\t\t\terror(errstr);\n\t\t\t\t}\n\t\t\t} \/\/ TODO: Refactor to prevent rewrite of code\n\n\t\t\tvector<char> byte_list;\n\t\t\tbool type_c = true;\n\t\t\tdo {\n\t\t\t\tbyte_list.push_back(p.memory[locctr]);\n\t\t\t\tif ( !isprint(p.memory[locctr]) ) {\n\t\t\t\t\ttype_c = false;\n\t\t\t\t}\n\t\t\t\tlocctr++;\n\t\t\t} while ( p.byte_type_guess[locctr] == CHAR_DATA && !p.is_labelled[locctr] );\n\n\t\t\topcode = \"CHAR\";\n\n\t\t\toperand += (type_c?\"C\":\"X\");\n\t\t\toperand += \"'\";\n\t\t\tfor ( int i = 0 ; i < (int)byte_list.size() ; i++ ) {\n\t\t\t\tif ( type_c ) {\n\t\t\t\t\toperand += byte_list[i];\n\t\t\t\t} else {\n\t\t\t\t\toperand += byte2hex(byte_list[i]);\n\t\t\t\t}\n\t\t\t}\n\t\t\toperand += \"'\";\n\t\t} else {\n\t\t\t\/\/ TODO\n\t\t\tlocctr++; \/\/ temporarily\n\t\t}\n\t\tofile << asm_to_line(label,opcode,operand,is_indexed);\n\t}\n\tofile << asm_to_line(\"\",\"END\",\"FIRST\",false);\n}<commit_msg>Refactor<commit_after>#include \"disassembler.h\"\n#include \"util.h\"\n#include \"symtab.h\"\n\n#include <vector>\n#include <cctype>\n\nusing namespace std;\n\nenum ByteTypeGuess {\n\tUNINITIALIZED,\n\tUNKNOWN,\n\tCHAR_DATA,\n\tUNINITIALIZED_CHAR_DATA,\n\tWORD_DATA,\n\tUNINITIALIZED_WORD_DATA,\n\tCODE,\n};\n\nstruct program {\n\tByteTypeGuess byte_type_guess[65536];\n\tchar memory[65536];\n\tbool is_labelled[65536];\n\n\tstring name;\n\tstring starting_address;\n\tint length_of_program;\n\tstring first_executable_instruction;\n\tprogram() {\n\t\tfor ( int i = 0 ; i < 65536 ; i++ ) {\n\t\t\tbyte_type_guess[i] = UNINITIALIZED;\n\t\t\tmemory[i] = 0;\n\t\t\tis_labelled[i] = false;\n\t\t}\n\t\tname = \"\";\n\t\tstarting_address = \"\";\n\t\tlength_of_program = 0;\n\t\tfirst_executable_instruction = \"\";\n\t}\n};\n\nbool read_record(ifstream &ifile, string &record);\nvoid record_to_memory(const string record, program &p);\nvoid analyze_code_data(program &p);\nvoid write_assembly(const program &p, ofstream &ofile);\n\nbool disassemble(ifstream &ifile, ofstream &ofile) {\n\tstring record;\n\tprogram p;\n\twhile ( read_record(ifile, record) ) {\n\t\trecord_to_memory(record, p);\n\t}\n\tstatus(\"Done reading records\");\n\tanalyze_code_data(p);\n\tstatus(\"Done analyzing program for code and data\");\n\twrite_assembly(p, ofile);\n\tstatus(\"Done writing output file\");\n\treturn true;\n}\n\nstring read_columns(ifstream &ifile, int col_begin, int col_end, char record_type = 'a') { \/\/ inclusive of both\n\tstring ret;\n\tchar t;\n\tfor ( int col = col_begin ; col <= col_end ; col++ ) {\n\t\tt = ifile.get();\n\t\tif ( t == EOF || t == '\\n' ) {\n\t\t\tstring errstr;\n\t\t\terrstr += \"Unexpected end of \";\n\t\t\terrstr += record_type;\n\t\t\terrstr += \" record\";\n\t\t\tfatal(errstr);\n\t\t}\n\t\tret += t;\n\t}\n\treturn ret;\n}\n\nstring read_hex_columns(ifstream &ifile, int col_begin, int col_end, char record_type = 'a') { \/\/ inclusive of both\n\tstring ret;\n\tret = read_columns(ifile,col_begin,col_end,record_type);\n\tmake_upper_case(ret);\n\tif ( !is_hex_string(ret) ) {\n\t\tstring errstr;\n\t\terrstr += \"Unexpected non-hexadecimal character found in \";\n\t\terrstr += record_type;\n\t\terrstr += \" record\";\n\t\tfatal(errstr);\n\t}\n\treturn ret;\n}\n\nbool read_record(ifstream &ifile, string &record) {\n\tint temp_int;\n\tstring temp_str;\n\tchar t;\n\n\tdo {\n\t\tt = ifile.get();\n\t\tif ( t == EOF ) {\n\t\t\treturn false;\n\t\t}\n\t} while ( t == '\\n' || t == ' ' );\n\trecord = \"\";\n\trecord += t;\n\n\tswitch (t) {\n\t\tcase 'H': \/\/ Header\n\t\t\trecord += read_columns(ifile,2,7,'H');\n\t\t\trecord += read_hex_columns(ifile,8,19,'H');\n\t\t\tbreak;\n\t\tcase 'T': \/\/ Text\n\t\t\trecord += read_hex_columns(ifile,2,7,'T');\n\t\t\ttemp_str = read_hex_columns(ifile,8,9,'T');\n\t\t\ttemp_int = hex2int(temp_str);\n\t\t\trecord += temp_str;\n\t\t\trecord += read_hex_columns(ifile,10,9+2*temp_int,'T');\n\t\t\tbreak;\n\t\tcase 'E': \/\/ End\n\t\t\trecord += read_hex_columns(ifile,2,7,'E');\n\t\t\tbreak;\n\t\tdefault:\n\t\t\t{\n\t\t\t\tstring errstr = \"Unknown record type \";\n\t\t\t\terrstr += t;\n\t\t\t\tfatal(errstr);\n\t\t\t}\n\t}\n\treturn true;\n}\n\nvoid record_to_memory(const string record, program &p) {\n\tconst char * c_record = record.c_str();\n\tswitch (*c_record) {\n\t\tcase 'H': \/\/ Header\n\t\t\tif ( p.name.length() != 0 ) {\n\t\t\t\tfatal(\"Multiple H records\");\n\t\t\t}\n\t\t\tp.name = record.substr(1,6);\n\t\t\tp.starting_address = record.substr(7,6);\n\t\t\tp.length_of_program = hex2int(record.substr(13,6));\n\t\t\tbreak;\n\t\tcase 'T': \/\/ Text\n\t\t\t{\n\t\t\t\tint text_start = hex2int(record.substr(1,6));\n\t\t\t\tint bit_length = hex2int(record.substr(7,2));\n\t\t\t\tfor ( int i = 0 ; i < bit_length ; i++ ) {\n\t\t\t\t\tp.memory[i+text_start] = hex2int(record.substr(9+2*i,2));\n\t\t\t\t\tp.byte_type_guess[i+text_start] = UNKNOWN;\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak;\n\t\tcase 'E': \/\/ End\n\t\t\tif ( p.first_executable_instruction.length() != 0 ) {\n\t\t\t\tfatal(\"Multiple E records\");\n\t\t\t}\n\t\t\tp.first_executable_instruction = record.substr(1,6);\n\t\t\tbreak;\n\t\tdefault:\n\t\t\t{\n\t\t\t\tstring errstr;\n\t\t\t\terrstr += \"Unknown record type \";\n\t\t\t\terrstr += *c_record;\n\t\t\t\tfatal(errstr);\n\t\t\t}\n\t}\n}\n\nvoid mark_code_data(program &p, int location, ByteTypeGuess btg) {\n\tif ( location >= hex2int(p.starting_address) + p.length_of_program ) {\n\t\treturn;\n\t}\n\tswitch (btg) {\n\t\tcase UNINITIALIZED:\n\t\tcase UNKNOWN:\n\t\t\tbreak;\n\t\tcase CHAR_DATA:\n\t\tcase UNINITIALIZED_CHAR_DATA:\n\t\t\t{\n\t\t\t\tif ( p.byte_type_guess[location] != UNKNOWN &&\n\t\t\t\t\t p.byte_type_guess[location] != UNINITIALIZED ) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tif ( p.byte_type_guess[location] == UNINITIALIZED )\n\t\t\t\t\tbtg = UNINITIALIZED_CHAR_DATA;\n\t\t\t\tp.byte_type_guess[location] = btg;\n\t\t\t\tbreak;\n\t\t\t}\n\t\tcase WORD_DATA:\n\t\tcase UNINITIALIZED_WORD_DATA:\n\t\t\t{\n\t\t\t\tif ( p.byte_type_guess[location] != UNKNOWN &&\n\t\t\t\t\t p.byte_type_guess[location] != UNINITIALIZED ) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tif ( p.byte_type_guess[location] == UNINITIALIZED )\n\t\t\t\t\tbtg = UNINITIALIZED_WORD_DATA;\n\t\t\t\tp.byte_type_guess[location+0] = btg;\n\t\t\t\tp.byte_type_guess[location+1] = btg;\n\t\t\t\tp.byte_type_guess[location+2] = btg;\n\t\t\t\tbreak;\n\t\t\t}\n\t\tcase CODE:\n\t\t\t{\n\t\t\t\tif ( p.byte_type_guess[location] == UNINITIALIZED ) {\n\t\t\t\t\tfatal(\"Attempting to use uninitialized section as code\");\n\t\t\t\t}\n\t\t\t\tif ( p.byte_type_guess[location] == CODE ) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tp.byte_type_guess[location+0] = btg;\n\t\t\t\tp.byte_type_guess[location+1] = btg;\n\t\t\t\tp.byte_type_guess[location+2] = btg;\n\n\t\t\t\tstring opcode_val = byte2hex(p.memory[location]);\n\t\t\t\tstring opcode;\n\t\t\t\tstring operand = byte2hex(p.memory[location+1])+byte2hex(p.memory[location+2]);\n\t\t\t\toperand = int2hex(hex2int(operand)&0x7FFF); \/\/ remove index flag\n\t\t\t\tif ( ! find_from_symtab(opcode,opcode_val) ) {\n\t\t\t\t\tstring errstr;\n\t\t\t\t\terrstr += \"Unknown opcode \";\n\t\t\t\t\terrstr += opcode_val;\n\t\t\t\t\terrstr += \" at location \";\n\t\t\t\t\terrstr += int2hex(location);\n\t\t\t\t\tfatal(errstr);\n\t\t\t\t}\n\n\t\t\t\tif ( opcode == \"ADD\" ||\n\t\t\t\t\t opcode == \"AND\" ||\n\t\t\t\t\t opcode == \"COMP\" ||\n\t\t\t\t\t opcode == \"DIV\" ||\n\t\t\t\t\t opcode == \"LDA\" ||\n\t\t\t\t\t opcode == \"LDL\" ||\n\t\t\t\t\t opcode == \"LDX\" ||\n\t\t\t\t\t opcode == \"MUL\" ||\n\t\t\t\t\t opcode == \"OR\" ||\n\t\t\t\t\t opcode == \"STA\" ||\n\t\t\t\t\t opcode == \"STL\" ||\n\t\t\t\t\t opcode == \"STX\" ||\n\t\t\t\t\t opcode == \"SUB\" ||\n\t\t\t\t\t opcode == \"TIX\" ) {\n\t\t\t\t\tgive_label(operand);\n\t\t\t\t\tp.is_labelled[hex2int(operand)] = true;\n\t\t\t\t\tmark_code_data(p,hex2int(operand),WORD_DATA);\n\t\t\t\t}\n\n\t\t\t\tif ( opcode == \"LDCH\" ||\n\t\t\t\t\t opcode == \"STCH\" ) {\n\t\t\t\t\tgive_label(operand);\n\t\t\t\t\tp.is_labelled[hex2int(operand)] = true;\n\t\t\t\t\tmark_code_data(p,hex2int(operand),CHAR_DATA);\n\t\t\t\t}\n\n\t\t\t\tif ( opcode == \"J\" ||\n\t\t\t\t\t opcode == \"JEQ\" ||\n\t\t\t\t\t opcode == \"JGT\" ||\n\t\t\t\t\t opcode == \"JLT\" ||\n\t\t\t\t\t opcode == \"JSUB\" ||\n\t\t\t\t\t opcode == \"RSUB\" ) {\n\t\t\t\t\tgive_label(operand);\n\t\t\t\t\tp.is_labelled[hex2int(operand)] = true;\n\t\t\t\t\tmark_code_data(p,hex2int(operand),CODE);\n\t\t\t\t}\n\n\t\t\t\tif ( opcode != \"J\" &&\n\t\t\t\t\t opcode != \"RSUB\" ) {\n\t\t\t\t\tmark_code_data(p,location+3,btg);\n\t\t\t\t}\n\n\t\t\t\tbreak;\n\t\t\t}\n\t}\n}\n\nvoid analyze_code_data(program &p) {\n\tif ( p.name.length() == 0 ) {\n\t\tfatal(\"No Header record\");\n\t}\n\tif ( p.first_executable_instruction.length() == 0 ) {\n\t\tfatal(\"No End record\");\n\t}\n\tinitialize_symtab();\n\tadd_to_symtab(\"FIRST\",p.first_executable_instruction);\n\tp.is_labelled[hex2int(p.first_executable_instruction)] = true;\n\tmark_code_data(p,hex2int(p.first_executable_instruction),CODE);\n}\n\nstring asm_to_line(string label, string opcode, string operand, bool is_indexed) {\n\tconst int labellength = 8;\n\tconst int opcodelength = 6;\n\tstring ret = \"\";\n\tret += label + string(labellength-label.length(),' ');\n\tret += opcode + string(opcodelength-opcode.length(),' ');\n\tret += operand;\n\tif ( is_indexed ) {\n\t\tret += \",X\";\n\t}\n\tret += '\\n';\n\treturn ret;\n}\n\nvoid write_assembly(const program &p, ofstream &ofile) {\n\tofile << asm_to_line(p.name,\"START\",p.starting_address,false);\n\tint start_of_program = hex2int(p.starting_address);\n\tint end_of_program = start_of_program + p.length_of_program;\n\n\tfor ( int locctr = start_of_program ; locctr < end_of_program ; ) {\n\t\tstring label = \"\";\n\t\tstring opcode = \"\";\n\t\tstring operand = \"\";\n\t\tbool is_indexed = false;\n\n\t\tif ( p.is_labelled[locctr] ) {\n\t\t\tif ( !find_from_symtab(label,int2hex(locctr)) ) {\n\t\t\t\tstring errstr;\n\t\t\t\terrstr += \"Label not created for location \";\n\t\t\t\terrstr += int2hex(locctr);\n\t\t\t\terror(errstr);\n\t\t\t}\n\t\t}\n\n\t\tif ( p.byte_type_guess[locctr] == CODE ) {\n\t\t\tif ( ! find_from_symtab(opcode,byte2hex(p.memory[locctr])) ) {\n\t\t\t\tstring errstr;\n\t\t\t\terrstr += \"Unknown opcode \";\n\t\t\t\terrstr += opcode;\n\t\t\t\terrstr += \" at location \";\n\t\t\t\terrstr += int2hex(locctr);\n\t\t\t\tfatal(errstr);\n\t\t\t}\n\t\t\toperand = byte2hex(p.memory[locctr+1])+byte2hex(p.memory[locctr+2]);\n\t\t\tis_indexed = (hex2int(operand)&0x8000);\n\t\t\toperand = int2hex(hex2int(operand)&0x7FFF); \/\/ remove index flag\n\n\t\t\tif ( opcode != \"RD\" &&\n\t\t\t\t opcode != \"TD\" &&\n\t\t\t\t opcode != \"WD\" &&\n\t\t\t\t opcode != \"RSUB\" ) {\n\t\t\t\tif ( !find_from_symtab(operand,operand) ) {\n\t\t\t\t\tstring errstr;\n\t\t\t\t\terrstr += \"Label not created for operand \";\n\t\t\t\t\terrstr += operand;\n\t\t\t\t\terror(errstr);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif ( opcode == \"RSUB\" ) {\n\t\t\t\toperand = \"\";\n\t\t\t}\n\n\t\t\tlocctr += 3;\n\t\t} else if ( p.byte_type_guess[locctr] == CHAR_DATA ) {\n\t\t\tvector<char> byte_list;\n\t\t\tbool type_c = true;\n\t\t\tdo {\n\t\t\t\tbyte_list.push_back(p.memory[locctr]);\n\t\t\t\tif ( !isprint(p.memory[locctr]) ) {\n\t\t\t\t\ttype_c = false;\n\t\t\t\t}\n\t\t\t\tlocctr++;\n\t\t\t} while ( p.byte_type_guess[locctr] == CHAR_DATA && !p.is_labelled[locctr] );\n\n\t\t\topcode = \"CHAR\";\n\n\t\t\toperand += (type_c?\"C\":\"X\");\n\t\t\toperand += \"'\";\n\t\t\tfor ( int i = 0 ; i < (int)byte_list.size() ; i++ ) {\n\t\t\t\tif ( type_c ) {\n\t\t\t\t\toperand += byte_list[i];\n\t\t\t\t} else {\n\t\t\t\t\toperand += byte2hex(byte_list[i]);\n\t\t\t\t}\n\t\t\t}\n\t\t\toperand += \"'\";\n\t\t} else {\n\t\t\t\/\/ TODO\n\t\t\tlocctr++; \/\/ temporarily\n\t\t}\n\t\tofile << asm_to_line(label,opcode,operand,is_indexed);\n\t}\n\tofile << asm_to_line(\"\",\"END\",\"FIRST\",false);\n}<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2010 Satoshi Nakamoto\n\/\/ Copyright (c) 2009-2014 The Bitcoin developers\n\/\/ Distributed under the MIT\/X11 software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \"base58.h\"\n#include \"init.h\"\n#include \"main.h\"\n#include \"net.h\"\n#include \"netbase.h\"\n#include \"rpcserver.h\"\n#include \"timedata.h\"\n#include \"util.h\"\n#ifdef ENABLE_WALLET\n#include \"wallet.h\"\n#include \"walletdb.h\"\n#endif\n\n#include <stdint.h>\n\n#include <boost\/assign\/list_of.hpp>\n#include \"json\/json_spirit_utils.h\"\n#include \"json\/json_spirit_value.h\"\n\nusing namespace boost;\nusing namespace boost::assign;\nusing namespace json_spirit;\nusing namespace std;\n\nValue getinfo(const Array& params, bool fHelp)\n{\n if (fHelp || params.size() != 0)\n throw runtime_error(\n \"getinfo\\n\"\n \"Returns an object containing various state info.\\n\"\n \"\\nResult:\\n\"\n \"{\\n\"\n \" \\\"version\\\": xxxxx, (numeric) the server version\\n\"\n \" \\\"protocolversion\\\": xxxxx, (numeric) the protocol version\\n\"\n \" \\\"walletversion\\\": xxxxx, (numeric) the wallet version\\n\"\n \" \\\"balance\\\": xxxxxxx, (numeric) the total bitcoin balance of the wallet\\n\"\n \" \\\"blocks\\\": xxxxxx, (numeric) the current number of blocks processed in the server\\n\"\n \" \\\"timeoffset\\\": xxxxx, (numeric) the time offset\\n\"\n \" \\\"connections\\\": xxxxx, (numeric) the number of connections\\n\"\n \" \\\"proxy\\\": \\\"host:port\\\", (string, optional) the proxy used by the server\\n\"\n \" \\\"difficulty\\\": xxxxxx, (numeric) the current difficulty\\n\"\n \" \\\"testnet\\\": true|false, (boolean) if the server is using testnet or not\\n\"\n \" \\\"keypoololdest\\\": xxxxxx, (numeric) the timestamp (seconds since GMT epoch) of the oldest pre-generated key in the key pool\\n\"\n \" \\\"keypoolsize\\\": xxxx, (numeric) how many new keys are pre-generated\\n\"\n \" \\\"unlocked_until\\\": ttt, (numeric) the timestamp in seconds since epoch (midnight Jan 1 1970 GMT) that the wallet is unlocked for transfers, or 0 if the wallet is locked\\n\"\n \" \\\"paytxfee\\\": x.xxxx, (numeric) the transaction fee set in btc\/kb\\n\"\n \" \\\"relayfee\\\": x.xxxx, (numeric) minimum relay fee for non-free transactions in btc\/kb\\n\"\n \" \\\"errors\\\": \\\"...\\\" (string) any error messages\\n\"\n \"}\\n\"\n \"\\nExamples:\\n\"\n + HelpExampleCli(\"getinfo\", \"\")\n + HelpExampleRpc(\"getinfo\", \"\")\n );\n\n proxyType proxy;\n GetProxy(NET_IPV4, proxy);\n\n Object obj;\n obj.push_back(Pair(\"version\", (int)CLIENT_VERSION));\n obj.push_back(Pair(\"protocolversion\",(int)PROTOCOL_VERSION));\n#ifdef ENABLE_WALLET\n if (pwalletMain) {\n obj.push_back(Pair(\"walletversion\", pwalletMain->GetVersion()));\n obj.push_back(Pair(\"balance\", ValueFromAmount(pwalletMain->GetBalance())));\n }\n#endif\n obj.push_back(Pair(\"blocks\", (int)chainActive.Height()));\n obj.push_back(Pair(\"timeoffset\", GetTimeOffset()));\n obj.push_back(Pair(\"connections\", (int)vNodes.size()));\n obj.push_back(Pair(\"proxy\", (proxy.IsValid() ? proxy.ToStringIPPort() : string())));\n obj.push_back(Pair(\"difficulty\", (double)GetDifficulty()));\n obj.push_back(Pair(\"testnet\", Params().NetworkID() == CBaseChainParams::TESTNET));\n#ifdef ENABLE_WALLET\n if (pwalletMain) {\n obj.push_back(Pair(\"keypoololdest\", pwalletMain->GetOldestKeyPoolTime()));\n obj.push_back(Pair(\"keypoolsize\", (int)pwalletMain->GetKeyPoolSize()));\n }\n if (pwalletMain && pwalletMain->IsCrypted())\n obj.push_back(Pair(\"unlocked_until\", nWalletUnlockTime));\n obj.push_back(Pair(\"paytxfee\", ValueFromAmount(payTxFee.GetFeePerK())));\n#endif\n obj.push_back(Pair(\"relayfee\", ValueFromAmount(::minRelayTxFee.GetFeePerK())));\n obj.push_back(Pair(\"errors\", GetWarnings(\"statusbar\")));\n return obj;\n}\n\n#ifdef ENABLE_WALLET\nclass DescribeAddressVisitor : public boost::static_visitor<Object>\n{\nprivate:\n isminetype mine;\n\npublic:\n DescribeAddressVisitor(isminetype mineIn) : mine(mineIn) {}\n\n Object operator()(const CNoDestination &dest) const { return Object(); }\n\n Object operator()(const CKeyID &keyID) const {\n Object obj;\n CPubKey vchPubKey;\n obj.push_back(Pair(\"isscript\", false));\n if (mine == ISMINE_SPENDABLE) {\n pwalletMain->GetPubKey(keyID, vchPubKey);\n obj.push_back(Pair(\"pubkey\", HexStr(vchPubKey)));\n obj.push_back(Pair(\"iscompressed\", vchPubKey.IsCompressed()));\n }\n return obj;\n }\n\n Object operator()(const CScriptID &scriptID) const {\n Object obj;\n obj.push_back(Pair(\"isscript\", true));\n if (mine != ISMINE_NO) {\n CScript subscript;\n pwalletMain->GetCScript(scriptID, subscript);\n std::vector<CTxDestination> addresses;\n txnouttype whichType;\n int nRequired;\n ExtractDestinations(subscript, whichType, addresses, nRequired);\n obj.push_back(Pair(\"script\", GetTxnOutputType(whichType)));\n obj.push_back(Pair(\"hex\", HexStr(subscript.begin(), subscript.end())));\n Array a;\n BOOST_FOREACH(const CTxDestination& addr, addresses)\n a.push_back(CBitcoinAddress(addr).ToString());\n obj.push_back(Pair(\"addresses\", a));\n if (whichType == TX_MULTISIG)\n obj.push_back(Pair(\"sigsrequired\", nRequired));\n }\n return obj;\n }\n};\n#endif\n\nValue validateaddress(const Array& params, bool fHelp)\n{\n if (fHelp || params.size() != 1)\n throw runtime_error(\n \"validateaddress \\\"bitcoinaddress\\\"\\n\"\n \"\\nReturn information about the given bitcoin address.\\n\"\n \"\\nArguments:\\n\"\n \"1. \\\"bitcoinaddress\\\" (string, required) The bitcoin address to validate\\n\"\n \"\\nResult:\\n\"\n \"{\\n\"\n \" \\\"isvalid\\\" : true|false, (boolean) If the address is valid or not. If not, this is the only property returned.\\n\"\n \" \\\"address\\\" : \\\"bitcoinaddress\\\", (string) The bitcoin address validated\\n\"\n \" \\\"ismine\\\" : true|false, (boolean) If the address is yours or not\\n\"\n \" \\\"isscript\\\" : true|false, (boolean) If the key is a script\\n\"\n \" \\\"pubkey\\\" : \\\"publickeyhex\\\", (string) The hex value of the raw public key\\n\"\n \" \\\"iscompressed\\\" : true|false, (boolean) If the address is compressed\\n\"\n \" \\\"account\\\" : \\\"account\\\" (string) The account associated with the address, \\\"\\\" is the default account\\n\"\n \"}\\n\"\n \"\\nExamples:\\n\"\n + HelpExampleCli(\"validateaddress\", \"\\\"1PSSGeFHDnKNxiEyFrD1wcEaHr9hrQDDWc\\\"\")\n + HelpExampleRpc(\"validateaddress\", \"\\\"1PSSGeFHDnKNxiEyFrD1wcEaHr9hrQDDWc\\\"\")\n );\n\n CBitcoinAddress address(params[0].get_str());\n bool isValid = address.IsValid();\n\n Object ret;\n ret.push_back(Pair(\"isvalid\", isValid));\n if (isValid)\n {\n CTxDestination dest = address.Get();\n string currentAddress = address.ToString();\n ret.push_back(Pair(\"address\", currentAddress));\n#ifdef ENABLE_WALLET\n isminetype mine = pwalletMain ? IsMine(*pwalletMain, dest) : ISMINE_NO;\n ret.push_back(Pair(\"ismine\", (mine & ISMINE_SPENDABLE) ? true : false));\n if (mine != ISMINE_NO) {\n ret.push_back(Pair(\"iswatchonly\", (mine & ISMINE_WATCH_ONLY) ? true: false));\n Object detail = boost::apply_visitor(DescribeAddressVisitor(mine), dest);\n ret.insert(ret.end(), detail.begin(), detail.end());\n }\n if (pwalletMain && pwalletMain->mapAddressBook.count(dest))\n ret.push_back(Pair(\"account\", pwalletMain->mapAddressBook[dest].name));\n#endif\n }\n return ret;\n}\n\n\/\/\n\/\/ Used by addmultisigaddress \/ createmultisig:\n\/\/\nCScript _createmultisig_redeemScript(const Array& params)\n{\n int nRequired = params[0].get_int();\n const Array& keys = params[1].get_array();\n\n \/\/ Gather public keys\n if (nRequired < 1)\n throw runtime_error(\"a multisignature address must require at least one key to redeem\");\n if ((int)keys.size() < nRequired)\n throw runtime_error(\n strprintf(\"not enough keys supplied \"\n \"(got %u keys, but need at least %d to redeem)\", keys.size(), nRequired));\n std::vector<CPubKey> pubkeys;\n pubkeys.resize(keys.size());\n for (unsigned int i = 0; i < keys.size(); i++)\n {\n const std::string& ks = keys[i].get_str();\n#ifdef ENABLE_WALLET\n \/\/ Case 1: Bitcoin address and we have full public key:\n CBitcoinAddress address(ks);\n if (pwalletMain && address.IsValid())\n {\n CKeyID keyID;\n if (!address.GetKeyID(keyID))\n throw runtime_error(\n strprintf(\"%s does not refer to a key\",ks));\n CPubKey vchPubKey;\n if (!pwalletMain->GetPubKey(keyID, vchPubKey))\n throw runtime_error(\n strprintf(\"no full public key for address %s\",ks));\n if (!vchPubKey.IsFullyValid())\n throw runtime_error(\" Invalid public key: \"+ks);\n pubkeys[i] = vchPubKey;\n }\n\n \/\/ Case 2: hex public key\n else\n#endif\n if (IsHex(ks))\n {\n CPubKey vchPubKey(ParseHex(ks));\n if (!vchPubKey.IsFullyValid())\n throw runtime_error(\" Invalid public key: \"+ks);\n pubkeys[i] = vchPubKey;\n }\n else\n {\n throw runtime_error(\" Invalid public key: \"+ks);\n }\n }\n CScript result;\n result.SetMultisig(nRequired, pubkeys);\n\n if (result.size() > MAX_SCRIPT_ELEMENT_SIZE)\n throw runtime_error(\n strprintf(\"redeemScript exceeds size limit: %d > %d\", result.size(), MAX_SCRIPT_ELEMENT_SIZE));\n\n return result;\n}\n\nValue createmultisig(const Array& params, bool fHelp)\n{\n if (fHelp || params.size() < 2 || params.size() > 2)\n {\n string msg = \"createmultisig nrequired [\\\"key\\\",...]\\n\"\n \"\\nCreates a multi-signature address with n signature of m keys required.\\n\"\n \"It returns a json object with the address and redeemScript.\\n\"\n\n \"\\nArguments:\\n\"\n \"1. nrequired (numeric, required) The number of required signatures out of the n keys or addresses.\\n\"\n \"2. \\\"keys\\\" (string, required) A json array of keys which are bitcoin addresses or hex-encoded public keys\\n\"\n \" [\\n\"\n \" \\\"key\\\" (string) bitcoin address or hex-encoded public key\\n\"\n \" ,...\\n\"\n \" ]\\n\"\n\n \"\\nResult:\\n\"\n \"{\\n\"\n \" \\\"address\\\":\\\"multisigaddress\\\", (string) The value of the new multisig address.\\n\"\n \" \\\"redeemScript\\\":\\\"script\\\" (string) The string value of the hex-encoded redemption script.\\n\"\n \"}\\n\"\n\n \"\\nExamples:\\n\"\n \"\\nCreate a multisig address from 2 addresses\\n\"\n + HelpExampleCli(\"createmultisig\", \"2 \\\"[\\\\\\\"16sSauSf5pF2UkUwvKGq4qjNRzBZYqgEL5\\\\\\\",\\\\\\\"171sgjn4YtPu27adkKGrdDwzRTxnRkBfKV\\\\\\\"]\\\"\") +\n \"\\nAs a json rpc call\\n\"\n + HelpExampleRpc(\"createmultisig\", \"2, \\\"[\\\\\\\"16sSauSf5pF2UkUwvKGq4qjNRzBZYqgEL5\\\\\\\",\\\\\\\"171sgjn4YtPu27adkKGrdDwzRTxnRkBfKV\\\\\\\"]\\\"\")\n ;\n throw runtime_error(msg);\n }\n\n \/\/ Construct using pay-to-script-hash:\n CScript inner = _createmultisig_redeemScript(params);\n CScriptID innerID = inner.GetID();\n CBitcoinAddress address(innerID);\n\n Object result;\n result.push_back(Pair(\"address\", address.ToString()));\n result.push_back(Pair(\"redeemScript\", HexStr(inner.begin(), inner.end())));\n\n return result;\n}\n\nValue verifymessage(const Array& params, bool fHelp)\n{\n if (fHelp || params.size() != 3)\n throw runtime_error(\n \"verifymessage \\\"bitcoinaddress\\\" \\\"signature\\\" \\\"message\\\"\\n\"\n \"\\nVerify a signed message\\n\"\n \"\\nArguments:\\n\"\n \"1. \\\"bitcoinaddress\\\" (string, required) The bitcoin address to use for the signature.\\n\"\n \"2. \\\"signature\\\" (string, required) The signature provided by the signer in base 64 encoding (see signmessage).\\n\"\n \"3. \\\"message\\\" (string, required) The message that was signed.\\n\"\n \"\\nResult:\\n\"\n \"true|false (boolean) If the signature is verified or not.\\n\"\n \"\\nExamples:\\n\"\n \"\\nUnlock the wallet for 30 seconds\\n\"\n + HelpExampleCli(\"walletpassphrase\", \"\\\"mypassphrase\\\" 30\") +\n \"\\nCreate the signature\\n\"\n + HelpExampleCli(\"signmessage\", \"\\\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XZ\\\" \\\"my message\\\"\") +\n \"\\nVerify the signature\\n\"\n + HelpExampleCli(\"verifymessage\", \"\\\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XZ\\\" \\\"signature\\\" \\\"my message\\\"\") +\n \"\\nAs json rpc\\n\"\n + HelpExampleRpc(\"verifymessage\", \"\\\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XZ\\\", \\\"signature\\\", \\\"my message\\\"\")\n );\n\n string strAddress = params[0].get_str();\n string strSign = params[1].get_str();\n string strMessage = params[2].get_str();\n\n CBitcoinAddress addr(strAddress);\n if (!addr.IsValid())\n throw JSONRPCError(RPC_TYPE_ERROR, \"Invalid address\");\n\n CKeyID keyID;\n if (!addr.GetKeyID(keyID))\n throw JSONRPCError(RPC_TYPE_ERROR, \"Address does not refer to key\");\n\n bool fInvalid = false;\n vector<unsigned char> vchSig = DecodeBase64(strSign.c_str(), &fInvalid);\n\n if (fInvalid)\n throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, \"Malformed base64 encoding\");\n\n CHashWriter ss(SER_GETHASH, 0);\n ss << strMessageMagic;\n ss << strMessage;\n\n CPubKey pubkey;\n if (!pubkey.RecoverCompact(ss.GetHash(), vchSig))\n return false;\n\n return (pubkey.GetID() == keyID);\n}\n<commit_msg>Add warning comment to getinfo<commit_after>\/\/ Copyright (c) 2010 Satoshi Nakamoto\n\/\/ Copyright (c) 2009-2014 The Bitcoin developers\n\/\/ Distributed under the MIT\/X11 software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \"base58.h\"\n#include \"init.h\"\n#include \"main.h\"\n#include \"net.h\"\n#include \"netbase.h\"\n#include \"rpcserver.h\"\n#include \"timedata.h\"\n#include \"util.h\"\n#ifdef ENABLE_WALLET\n#include \"wallet.h\"\n#include \"walletdb.h\"\n#endif\n\n#include <stdint.h>\n\n#include <boost\/assign\/list_of.hpp>\n#include \"json\/json_spirit_utils.h\"\n#include \"json\/json_spirit_value.h\"\n\nusing namespace boost;\nusing namespace boost::assign;\nusing namespace json_spirit;\nusing namespace std;\n\n\/**\n * @note Do not add or change anything in the information returned by this\n * method. `getinfo` exists for backwards-compatibilty only. It combines\n * information from wildly different sources in the program, which is a mess,\n * and is thus planned to be deprecated eventually.\n *\n * Based on the source of the information, new information should be added to:\n * - `getblockchaininfo`,\n * - `getnetworkinfo` or\n * - `getwalletinfo`\n *\n * Or alternatively, create a specific query method for the information.\n **\/\nValue getinfo(const Array& params, bool fHelp)\n{\n if (fHelp || params.size() != 0)\n throw runtime_error(\n \"getinfo\\n\"\n \"Returns an object containing various state info.\\n\"\n \"\\nResult:\\n\"\n \"{\\n\"\n \" \\\"version\\\": xxxxx, (numeric) the server version\\n\"\n \" \\\"protocolversion\\\": xxxxx, (numeric) the protocol version\\n\"\n \" \\\"walletversion\\\": xxxxx, (numeric) the wallet version\\n\"\n \" \\\"balance\\\": xxxxxxx, (numeric) the total bitcoin balance of the wallet\\n\"\n \" \\\"blocks\\\": xxxxxx, (numeric) the current number of blocks processed in the server\\n\"\n \" \\\"timeoffset\\\": xxxxx, (numeric) the time offset\\n\"\n \" \\\"connections\\\": xxxxx, (numeric) the number of connections\\n\"\n \" \\\"proxy\\\": \\\"host:port\\\", (string, optional) the proxy used by the server\\n\"\n \" \\\"difficulty\\\": xxxxxx, (numeric) the current difficulty\\n\"\n \" \\\"testnet\\\": true|false, (boolean) if the server is using testnet or not\\n\"\n \" \\\"keypoololdest\\\": xxxxxx, (numeric) the timestamp (seconds since GMT epoch) of the oldest pre-generated key in the key pool\\n\"\n \" \\\"keypoolsize\\\": xxxx, (numeric) how many new keys are pre-generated\\n\"\n \" \\\"unlocked_until\\\": ttt, (numeric) the timestamp in seconds since epoch (midnight Jan 1 1970 GMT) that the wallet is unlocked for transfers, or 0 if the wallet is locked\\n\"\n \" \\\"paytxfee\\\": x.xxxx, (numeric) the transaction fee set in btc\/kb\\n\"\n \" \\\"relayfee\\\": x.xxxx, (numeric) minimum relay fee for non-free transactions in btc\/kb\\n\"\n \" \\\"errors\\\": \\\"...\\\" (string) any error messages\\n\"\n \"}\\n\"\n \"\\nExamples:\\n\"\n + HelpExampleCli(\"getinfo\", \"\")\n + HelpExampleRpc(\"getinfo\", \"\")\n );\n\n proxyType proxy;\n GetProxy(NET_IPV4, proxy);\n\n Object obj;\n obj.push_back(Pair(\"version\", (int)CLIENT_VERSION));\n obj.push_back(Pair(\"protocolversion\",(int)PROTOCOL_VERSION));\n#ifdef ENABLE_WALLET\n if (pwalletMain) {\n obj.push_back(Pair(\"walletversion\", pwalletMain->GetVersion()));\n obj.push_back(Pair(\"balance\", ValueFromAmount(pwalletMain->GetBalance())));\n }\n#endif\n obj.push_back(Pair(\"blocks\", (int)chainActive.Height()));\n obj.push_back(Pair(\"timeoffset\", GetTimeOffset()));\n obj.push_back(Pair(\"connections\", (int)vNodes.size()));\n obj.push_back(Pair(\"proxy\", (proxy.IsValid() ? proxy.ToStringIPPort() : string())));\n obj.push_back(Pair(\"difficulty\", (double)GetDifficulty()));\n obj.push_back(Pair(\"testnet\", Params().NetworkID() == CBaseChainParams::TESTNET));\n#ifdef ENABLE_WALLET\n if (pwalletMain) {\n obj.push_back(Pair(\"keypoololdest\", pwalletMain->GetOldestKeyPoolTime()));\n obj.push_back(Pair(\"keypoolsize\", (int)pwalletMain->GetKeyPoolSize()));\n }\n if (pwalletMain && pwalletMain->IsCrypted())\n obj.push_back(Pair(\"unlocked_until\", nWalletUnlockTime));\n obj.push_back(Pair(\"paytxfee\", ValueFromAmount(payTxFee.GetFeePerK())));\n#endif\n obj.push_back(Pair(\"relayfee\", ValueFromAmount(::minRelayTxFee.GetFeePerK())));\n obj.push_back(Pair(\"errors\", GetWarnings(\"statusbar\")));\n return obj;\n}\n\n#ifdef ENABLE_WALLET\nclass DescribeAddressVisitor : public boost::static_visitor<Object>\n{\nprivate:\n isminetype mine;\n\npublic:\n DescribeAddressVisitor(isminetype mineIn) : mine(mineIn) {}\n\n Object operator()(const CNoDestination &dest) const { return Object(); }\n\n Object operator()(const CKeyID &keyID) const {\n Object obj;\n CPubKey vchPubKey;\n obj.push_back(Pair(\"isscript\", false));\n if (mine == ISMINE_SPENDABLE) {\n pwalletMain->GetPubKey(keyID, vchPubKey);\n obj.push_back(Pair(\"pubkey\", HexStr(vchPubKey)));\n obj.push_back(Pair(\"iscompressed\", vchPubKey.IsCompressed()));\n }\n return obj;\n }\n\n Object operator()(const CScriptID &scriptID) const {\n Object obj;\n obj.push_back(Pair(\"isscript\", true));\n if (mine != ISMINE_NO) {\n CScript subscript;\n pwalletMain->GetCScript(scriptID, subscript);\n std::vector<CTxDestination> addresses;\n txnouttype whichType;\n int nRequired;\n ExtractDestinations(subscript, whichType, addresses, nRequired);\n obj.push_back(Pair(\"script\", GetTxnOutputType(whichType)));\n obj.push_back(Pair(\"hex\", HexStr(subscript.begin(), subscript.end())));\n Array a;\n BOOST_FOREACH(const CTxDestination& addr, addresses)\n a.push_back(CBitcoinAddress(addr).ToString());\n obj.push_back(Pair(\"addresses\", a));\n if (whichType == TX_MULTISIG)\n obj.push_back(Pair(\"sigsrequired\", nRequired));\n }\n return obj;\n }\n};\n#endif\n\nValue validateaddress(const Array& params, bool fHelp)\n{\n if (fHelp || params.size() != 1)\n throw runtime_error(\n \"validateaddress \\\"bitcoinaddress\\\"\\n\"\n \"\\nReturn information about the given bitcoin address.\\n\"\n \"\\nArguments:\\n\"\n \"1. \\\"bitcoinaddress\\\" (string, required) The bitcoin address to validate\\n\"\n \"\\nResult:\\n\"\n \"{\\n\"\n \" \\\"isvalid\\\" : true|false, (boolean) If the address is valid or not. If not, this is the only property returned.\\n\"\n \" \\\"address\\\" : \\\"bitcoinaddress\\\", (string) The bitcoin address validated\\n\"\n \" \\\"ismine\\\" : true|false, (boolean) If the address is yours or not\\n\"\n \" \\\"isscript\\\" : true|false, (boolean) If the key is a script\\n\"\n \" \\\"pubkey\\\" : \\\"publickeyhex\\\", (string) The hex value of the raw public key\\n\"\n \" \\\"iscompressed\\\" : true|false, (boolean) If the address is compressed\\n\"\n \" \\\"account\\\" : \\\"account\\\" (string) The account associated with the address, \\\"\\\" is the default account\\n\"\n \"}\\n\"\n \"\\nExamples:\\n\"\n + HelpExampleCli(\"validateaddress\", \"\\\"1PSSGeFHDnKNxiEyFrD1wcEaHr9hrQDDWc\\\"\")\n + HelpExampleRpc(\"validateaddress\", \"\\\"1PSSGeFHDnKNxiEyFrD1wcEaHr9hrQDDWc\\\"\")\n );\n\n CBitcoinAddress address(params[0].get_str());\n bool isValid = address.IsValid();\n\n Object ret;\n ret.push_back(Pair(\"isvalid\", isValid));\n if (isValid)\n {\n CTxDestination dest = address.Get();\n string currentAddress = address.ToString();\n ret.push_back(Pair(\"address\", currentAddress));\n#ifdef ENABLE_WALLET\n isminetype mine = pwalletMain ? IsMine(*pwalletMain, dest) : ISMINE_NO;\n ret.push_back(Pair(\"ismine\", (mine & ISMINE_SPENDABLE) ? true : false));\n if (mine != ISMINE_NO) {\n ret.push_back(Pair(\"iswatchonly\", (mine & ISMINE_WATCH_ONLY) ? true: false));\n Object detail = boost::apply_visitor(DescribeAddressVisitor(mine), dest);\n ret.insert(ret.end(), detail.begin(), detail.end());\n }\n if (pwalletMain && pwalletMain->mapAddressBook.count(dest))\n ret.push_back(Pair(\"account\", pwalletMain->mapAddressBook[dest].name));\n#endif\n }\n return ret;\n}\n\n\/\/\n\/\/ Used by addmultisigaddress \/ createmultisig:\n\/\/\nCScript _createmultisig_redeemScript(const Array& params)\n{\n int nRequired = params[0].get_int();\n const Array& keys = params[1].get_array();\n\n \/\/ Gather public keys\n if (nRequired < 1)\n throw runtime_error(\"a multisignature address must require at least one key to redeem\");\n if ((int)keys.size() < nRequired)\n throw runtime_error(\n strprintf(\"not enough keys supplied \"\n \"(got %u keys, but need at least %d to redeem)\", keys.size(), nRequired));\n std::vector<CPubKey> pubkeys;\n pubkeys.resize(keys.size());\n for (unsigned int i = 0; i < keys.size(); i++)\n {\n const std::string& ks = keys[i].get_str();\n#ifdef ENABLE_WALLET\n \/\/ Case 1: Bitcoin address and we have full public key:\n CBitcoinAddress address(ks);\n if (pwalletMain && address.IsValid())\n {\n CKeyID keyID;\n if (!address.GetKeyID(keyID))\n throw runtime_error(\n strprintf(\"%s does not refer to a key\",ks));\n CPubKey vchPubKey;\n if (!pwalletMain->GetPubKey(keyID, vchPubKey))\n throw runtime_error(\n strprintf(\"no full public key for address %s\",ks));\n if (!vchPubKey.IsFullyValid())\n throw runtime_error(\" Invalid public key: \"+ks);\n pubkeys[i] = vchPubKey;\n }\n\n \/\/ Case 2: hex public key\n else\n#endif\n if (IsHex(ks))\n {\n CPubKey vchPubKey(ParseHex(ks));\n if (!vchPubKey.IsFullyValid())\n throw runtime_error(\" Invalid public key: \"+ks);\n pubkeys[i] = vchPubKey;\n }\n else\n {\n throw runtime_error(\" Invalid public key: \"+ks);\n }\n }\n CScript result;\n result.SetMultisig(nRequired, pubkeys);\n\n if (result.size() > MAX_SCRIPT_ELEMENT_SIZE)\n throw runtime_error(\n strprintf(\"redeemScript exceeds size limit: %d > %d\", result.size(), MAX_SCRIPT_ELEMENT_SIZE));\n\n return result;\n}\n\nValue createmultisig(const Array& params, bool fHelp)\n{\n if (fHelp || params.size() < 2 || params.size() > 2)\n {\n string msg = \"createmultisig nrequired [\\\"key\\\",...]\\n\"\n \"\\nCreates a multi-signature address with n signature of m keys required.\\n\"\n \"It returns a json object with the address and redeemScript.\\n\"\n\n \"\\nArguments:\\n\"\n \"1. nrequired (numeric, required) The number of required signatures out of the n keys or addresses.\\n\"\n \"2. \\\"keys\\\" (string, required) A json array of keys which are bitcoin addresses or hex-encoded public keys\\n\"\n \" [\\n\"\n \" \\\"key\\\" (string) bitcoin address or hex-encoded public key\\n\"\n \" ,...\\n\"\n \" ]\\n\"\n\n \"\\nResult:\\n\"\n \"{\\n\"\n \" \\\"address\\\":\\\"multisigaddress\\\", (string) The value of the new multisig address.\\n\"\n \" \\\"redeemScript\\\":\\\"script\\\" (string) The string value of the hex-encoded redemption script.\\n\"\n \"}\\n\"\n\n \"\\nExamples:\\n\"\n \"\\nCreate a multisig address from 2 addresses\\n\"\n + HelpExampleCli(\"createmultisig\", \"2 \\\"[\\\\\\\"16sSauSf5pF2UkUwvKGq4qjNRzBZYqgEL5\\\\\\\",\\\\\\\"171sgjn4YtPu27adkKGrdDwzRTxnRkBfKV\\\\\\\"]\\\"\") +\n \"\\nAs a json rpc call\\n\"\n + HelpExampleRpc(\"createmultisig\", \"2, \\\"[\\\\\\\"16sSauSf5pF2UkUwvKGq4qjNRzBZYqgEL5\\\\\\\",\\\\\\\"171sgjn4YtPu27adkKGrdDwzRTxnRkBfKV\\\\\\\"]\\\"\")\n ;\n throw runtime_error(msg);\n }\n\n \/\/ Construct using pay-to-script-hash:\n CScript inner = _createmultisig_redeemScript(params);\n CScriptID innerID = inner.GetID();\n CBitcoinAddress address(innerID);\n\n Object result;\n result.push_back(Pair(\"address\", address.ToString()));\n result.push_back(Pair(\"redeemScript\", HexStr(inner.begin(), inner.end())));\n\n return result;\n}\n\nValue verifymessage(const Array& params, bool fHelp)\n{\n if (fHelp || params.size() != 3)\n throw runtime_error(\n \"verifymessage \\\"bitcoinaddress\\\" \\\"signature\\\" \\\"message\\\"\\n\"\n \"\\nVerify a signed message\\n\"\n \"\\nArguments:\\n\"\n \"1. \\\"bitcoinaddress\\\" (string, required) The bitcoin address to use for the signature.\\n\"\n \"2. \\\"signature\\\" (string, required) The signature provided by the signer in base 64 encoding (see signmessage).\\n\"\n \"3. \\\"message\\\" (string, required) The message that was signed.\\n\"\n \"\\nResult:\\n\"\n \"true|false (boolean) If the signature is verified or not.\\n\"\n \"\\nExamples:\\n\"\n \"\\nUnlock the wallet for 30 seconds\\n\"\n + HelpExampleCli(\"walletpassphrase\", \"\\\"mypassphrase\\\" 30\") +\n \"\\nCreate the signature\\n\"\n + HelpExampleCli(\"signmessage\", \"\\\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XZ\\\" \\\"my message\\\"\") +\n \"\\nVerify the signature\\n\"\n + HelpExampleCli(\"verifymessage\", \"\\\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XZ\\\" \\\"signature\\\" \\\"my message\\\"\") +\n \"\\nAs json rpc\\n\"\n + HelpExampleRpc(\"verifymessage\", \"\\\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XZ\\\", \\\"signature\\\", \\\"my message\\\"\")\n );\n\n string strAddress = params[0].get_str();\n string strSign = params[1].get_str();\n string strMessage = params[2].get_str();\n\n CBitcoinAddress addr(strAddress);\n if (!addr.IsValid())\n throw JSONRPCError(RPC_TYPE_ERROR, \"Invalid address\");\n\n CKeyID keyID;\n if (!addr.GetKeyID(keyID))\n throw JSONRPCError(RPC_TYPE_ERROR, \"Address does not refer to key\");\n\n bool fInvalid = false;\n vector<unsigned char> vchSig = DecodeBase64(strSign.c_str(), &fInvalid);\n\n if (fInvalid)\n throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, \"Malformed base64 encoding\");\n\n CHashWriter ss(SER_GETHASH, 0);\n ss << strMessageMagic;\n ss << strMessage;\n\n CPubKey pubkey;\n if (!pubkey.RecoverCompact(ss.GetHash(), vchSig))\n return false;\n\n return (pubkey.GetID() == keyID);\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"DAFrame\/DAOBASE\/connectionmanager.h\"\n#include \"DAFrame\/DAOBASE\/poolconnectionmanager.h\"\n\nint main(int argc, char* argv[])\n{\n\tDAFrame::CConnectionManager::registProtocol(\"mysql\", NULL);\n\tDAFrame::CPoolConnectionManager::initialize(\"mysql:\/\/192.168.9.82:3306\/gw_power\", 50, \"root\", \"root\");\n\tDAFrame::CPoolConnAutoPtr<DAFrame::CPoolConnection> conn\n\t\t= DAFrame::CPoolConnectionManager::getConnection();\n\treturn 0;\n}\n\n<commit_msg>connect database ok<commit_after>#include \"winsock2.h\"\n#include \"DAFrame\/DAOBASE\/connectionmanager.h\"\n#include \"DAFrame\/DAOBASE\/poolconnectionmanager.h\"\n#include \"DAFrame\/MYSQLIMPL\/mysqlconnection.h\"\n\nint main(int argc, char* argv[])\n{\n\tDAFrame::CConnectionManager::registProtocol(\"mysql\", new DAFrame::mysql::CMySQLConnection);\n\tDAFrame::CPoolConnectionManager::initialize(\"mysql:\/\/192.168.9.82:3306\/gw_power\", 50, \"root\", \"root\");\n\tDAFrame::CPoolConnAutoPtr<DAFrame::CPoolConnection> conn\n\t\t= DAFrame::CPoolConnectionManager::getConnection();\n\treturn 0;\n}\n\n<|endoftext|>"} {"text":"<commit_before>#pragma once\n#include <opengl\/colors.hpp>\n#include <opengl\/lighting.hpp>\n#include <opengl\/texture.hpp>\n\n#include <boomhs\/entity.hpp>\n#include <boomhs\/npc.hpp>\n#include <boomhs\/player.hpp>\n#include <boomhs\/tile.hpp>\n#include <boomhs\/types.hpp>\n\n#include <cassert>\n#include <iostream>\n#include <ostream>\n#include <string>\n#include <vector>\n\nnamespace boomhs\n{\n\nstruct IsVisible\n{\n bool value = false;\n};\n\nstruct Torch\n{\n opengl::Attenuation default_attenuation{1.0f, 0.93f, 0.46f};\n};\n\nstruct LightFlicker\n{\n float base_speed = 0.0f;\n float current_speed = 0.0f;\n\n std::array<opengl::Color, 2> colors;\n};\n\nstruct JunkEntityFromFILE\n{\n};\n\nstruct StairInfo\n{\n TilePosition tile_position;\n TilePosition exit_position;\n};\n\nstruct ShaderName\n{\n std::string value;\n};\n\nstruct CubeRenderable\n{\n};\n\nstruct MeshRenderable\n{\n std::string name;\n};\n\nstruct IsSkybox\n{\n};\n\nstruct TextureRenderable\n{\n opengl::TextureInfo texture_info;\n};\n\ntemplate <typename... C>\nauto\nfind_all_entities_with_component(EntityRegistry& registry)\n{\n using namespace boomhs;\n using namespace opengl;\n\n std::vector<EntityID> entities;\n auto const view = registry.view<C...>();\n for (auto const e : view)\n {\n entities.emplace_back(e);\n }\n return entities;\n}\n\ninline auto\nall_nearby_entities(glm::vec3 const& pos, float const max_distance, EntityRegistry& registry)\n{\n using namespace boomhs;\n using namespace opengl;\n\n std::vector<EntityID> entities;\n auto const view = registry.view<Transform>();\n for (auto const e : view)\n {\n auto& transform = registry.get<Transform>(e);\n if (glm::distance(transform.translation, pos) <= max_distance)\n {\n entities.emplace_back(e);\n }\n }\n return entities;\n}\n\ninline auto\nfind_enemies(EntityRegistry& registry)\n{\n using namespace boomhs;\n using namespace opengl;\n return find_all_entities_with_component<NPCData>(registry);\n}\n\ninline auto\nfind_materials(EntityRegistry& registry)\n{\n using namespace boomhs;\n using namespace opengl;\n return find_all_entities_with_component<Material>(registry);\n}\n\ninline auto\nfind_pointlights(EntityRegistry& registry)\n{\n using namespace boomhs;\n using namespace opengl;\n\n return find_all_entities_with_component<PointLight>(registry);\n}\n\ninline auto\nfind_stairs(EntityRegistry& registry)\n{\n using namespace boomhs;\n using namespace opengl;\n\n return find_all_entities_with_component<StairInfo>(registry);\n}\n\nclass TileGrid;\nstd::vector<EntityID>\nfind_stairs_withtype(EntityRegistry&, TileGrid const&, TileType const);\n\ninline auto\nfind_upstairs(EntityRegistry& registry, TileGrid const& tgrid)\n{\n return find_stairs_withtype(registry, tgrid, TileType::STAIR_UP);\n}\n\ninline auto\nfind_downstairs(EntityRegistry& registry, TileGrid const& tgrid)\n{\n return find_stairs_withtype(registry, tgrid, TileType::STAIR_DOWN);\n}\n\ninline auto\nfind_items(EntityRegistry& registry)\n{\n std::vector<EntityID> items;\n auto view = registry.view<Item>();\n for (auto const eid : view)\n {\n items.emplace_back(eid);\n }\n return items;\n}\n\ninline EntityID\nfind_player(EntityRegistry& registry)\n{\n \/\/ for now assume only 1 entity has the Player tag\n assert(1 == registry.view<PlayerData>().size());\n\n \/\/ Assume Player has a Transform\n auto view = registry.view<PlayerData, Transform>();\n std::optional<EntityID> entity{std::nullopt};\n for (auto const e : view)\n {\n \/\/ This assert ensures this loop only runs once.\n assert(std::nullopt == entity);\n entity = e;\n }\n assert(std::nullopt != entity);\n return *entity;\n}\n\ninline auto&\nfind_inventory(EntityRegistry& registry)\n{\n auto const eid = find_player(registry);\n return registry.get<PlayerData>(eid).inventory;\n}\n\ninline auto\nfind_torches(EntityRegistry& registry)\n{\n std::vector<EntityID> torches;\n auto view = registry.view<Torch>();\n for (auto const eid : view)\n {\n assert(registry.has<Transform>(eid));\n torches.emplace_back(eid);\n }\n return torches;\n}\n\ninline auto&\nfind_skybox(EntityRegistry& registry)\n{\n \/\/ for now assume only 1 entity has the Player tag\n assert(1 == registry.view<IsSkybox>().size());\n\n \/\/ Assume Skybox has a Transform\n auto view = registry.view<IsSkybox, Transform>();\n std::optional<EntityID> entity{std::nullopt};\n for (auto const e : view)\n {\n \/\/ This assert ensures this loop only runs once.\n assert(std::nullopt == entity);\n entity = e;\n }\n assert(std::nullopt != entity);\n return *entity;\n}\n\n} \/\/ namespace boomhs\n<commit_msg>fix stack-usage-after-free bug<commit_after>#pragma once\n#include <opengl\/colors.hpp>\n#include <opengl\/lighting.hpp>\n#include <opengl\/texture.hpp>\n\n#include <boomhs\/entity.hpp>\n#include <boomhs\/npc.hpp>\n#include <boomhs\/player.hpp>\n#include <boomhs\/tile.hpp>\n#include <boomhs\/types.hpp>\n\n#include <cassert>\n#include <iostream>\n#include <ostream>\n#include <string>\n#include <vector>\n\nnamespace boomhs\n{\n\nstruct IsVisible\n{\n bool value = false;\n};\n\nstruct Torch\n{\n opengl::Attenuation default_attenuation{1.0f, 0.93f, 0.46f};\n};\n\nstruct LightFlicker\n{\n float base_speed = 0.0f;\n float current_speed = 0.0f;\n\n std::array<opengl::Color, 2> colors;\n};\n\nstruct JunkEntityFromFILE\n{\n};\n\nstruct StairInfo\n{\n TilePosition tile_position;\n TilePosition exit_position;\n};\n\nstruct ShaderName\n{\n std::string value;\n};\n\nstruct CubeRenderable\n{\n};\n\nstruct MeshRenderable\n{\n std::string name;\n};\n\nstruct IsSkybox\n{\n};\n\nstruct TextureRenderable\n{\n opengl::TextureInfo texture_info;\n};\n\ntemplate <typename... C>\nauto\nfind_all_entities_with_component(EntityRegistry& registry)\n{\n using namespace boomhs;\n using namespace opengl;\n\n std::vector<EntityID> entities;\n auto const view = registry.view<C...>();\n for (auto const e : view)\n {\n entities.emplace_back(e);\n }\n return entities;\n}\n\ninline auto\nall_nearby_entities(glm::vec3 const& pos, float const max_distance, EntityRegistry& registry)\n{\n using namespace boomhs;\n using namespace opengl;\n\n std::vector<EntityID> entities;\n auto const view = registry.view<Transform>();\n for (auto const e : view)\n {\n auto& transform = registry.get<Transform>(e);\n if (glm::distance(transform.translation, pos) <= max_distance)\n {\n entities.emplace_back(e);\n }\n }\n return entities;\n}\n\ninline auto\nfind_enemies(EntityRegistry& registry)\n{\n using namespace boomhs;\n using namespace opengl;\n return find_all_entities_with_component<NPCData>(registry);\n}\n\ninline auto\nfind_materials(EntityRegistry& registry)\n{\n using namespace boomhs;\n using namespace opengl;\n return find_all_entities_with_component<Material>(registry);\n}\n\ninline auto\nfind_pointlights(EntityRegistry& registry)\n{\n using namespace boomhs;\n using namespace opengl;\n\n return find_all_entities_with_component<PointLight>(registry);\n}\n\ninline auto\nfind_stairs(EntityRegistry& registry)\n{\n using namespace boomhs;\n using namespace opengl;\n\n return find_all_entities_with_component<StairInfo>(registry);\n}\n\nclass TileGrid;\nstd::vector<EntityID>\nfind_stairs_withtype(EntityRegistry&, TileGrid const&, TileType const);\n\ninline auto\nfind_upstairs(EntityRegistry& registry, TileGrid const& tgrid)\n{\n return find_stairs_withtype(registry, tgrid, TileType::STAIR_UP);\n}\n\ninline auto\nfind_downstairs(EntityRegistry& registry, TileGrid const& tgrid)\n{\n return find_stairs_withtype(registry, tgrid, TileType::STAIR_DOWN);\n}\n\ninline auto\nfind_items(EntityRegistry& registry)\n{\n std::vector<EntityID> items;\n auto view = registry.view<Item>();\n for (auto const eid : view)\n {\n items.emplace_back(eid);\n }\n return items;\n}\n\ninline EntityID\nfind_player(EntityRegistry& registry)\n{\n \/\/ for now assume only 1 entity has the Player tag\n assert(1 == registry.view<PlayerData>().size());\n\n \/\/ Assume Player has a Transform\n auto view = registry.view<PlayerData, Transform>();\n std::optional<EntityID> entity{std::nullopt};\n for (auto const e : view)\n {\n \/\/ This assert ensures this loop only runs once.\n assert(std::nullopt == entity);\n entity = e;\n }\n assert(std::nullopt != entity);\n return *entity;\n}\n\ninline auto&\nfind_inventory(EntityRegistry& registry)\n{\n auto const eid = find_player(registry);\n return registry.get<PlayerData>(eid).inventory;\n}\n\ninline auto\nfind_torches(EntityRegistry& registry)\n{\n std::vector<EntityID> torches;\n auto view = registry.view<Torch>();\n for (auto const eid : view)\n {\n assert(registry.has<Transform>(eid));\n torches.emplace_back(eid);\n }\n return torches;\n}\n\ninline auto\nfind_skybox(EntityRegistry& registry)\n{\n \/\/ for now assume only 1 entity has the Player tag\n assert(1 == registry.view<IsSkybox>().size());\n\n \/\/ Assume Skybox has a Transform\n auto view = registry.view<IsSkybox, Transform>();\n std::optional<EntityID> entity{std::nullopt};\n for (auto const e : view)\n {\n \/\/ This assert ensures this loop only runs once.\n assert(std::nullopt == entity);\n entity = e;\n }\n assert(std::nullopt != entity);\n return *entity;\n}\n\n} \/\/ namespace boomhs\n<|endoftext|>"} {"text":"<commit_before>#include \"configuration.hh\"\n\nnamespace vick {\n\nchar QUIT_KEY = 0;\nint TAB_SIZE = 1;\nvoid (*PUSH_BACK_CHANGE)(contents&, std::shared_ptr<change>) = nullptr;\nstd::string DELIMINATORS = \"\";\nstd::string MATCHES = \"\";\n\nbool use_colors() {return true;}\nvoid init_conf() {}\nvoid add_listeners() {}\nvoid add_commands(\n std::map<std::string,\n std::function<boost::optional<std::shared_ptr<change> >(\n contents&, boost::optional<int>)> >&) {}\n\n}\n<commit_msg>Make `configuration_testing` use realistic DELIMINATORS and MATCHES<commit_after>#include \"configuration.hh\"\n\nnamespace vick {\n\nchar QUIT_KEY = 0;\nint TAB_SIZE = 1;\nvoid (*PUSH_BACK_CHANGE)(contents&, std::shared_ptr<change>) = nullptr;\nstd::string DELIMINATORS = \"!@#$%^&*()-=+[]{}\\\\|;:'\\\",.<>\/?`~\";\nstd::string MATCHES = \"()[]{}\";\n\nbool use_colors() {return true;}\nvoid init_conf() {}\nvoid add_listeners() {}\nvoid add_commands(\n std::map<std::string,\n std::function<boost::optional<std::shared_ptr<change> >(\n contents&, boost::optional<int>)> >&) {}\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/===-- cc1as_main.cpp - Clang Assembler ---------------------------------===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This is the entry point to the clang -cc1as functionality, which implements\n\/\/ the direct interface to the LLVM MC based assembler.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"clang\/Basic\/Diagnostic.h\"\n#include \"clang\/Driver\/Arg.h\"\n#include \"clang\/Driver\/ArgList.h\"\n#include \"clang\/Driver\/DriverDiagnostic.h\"\n#include \"clang\/Driver\/CC1AsOptions.h\"\n#include \"clang\/Driver\/OptTable.h\"\n#include \"clang\/Driver\/Options.h\"\n#include \"clang\/Frontend\/DiagnosticOptions.h\"\n#include \"clang\/Frontend\/FrontendDiagnostic.h\"\n#include \"clang\/Frontend\/TextDiagnosticPrinter.h\"\n#include \"llvm\/ADT\/OwningPtr.h\"\n#include \"llvm\/ADT\/StringSwitch.h\"\n#include \"llvm\/ADT\/Triple.h\"\n#include \"llvm\/MC\/MCParser\/MCAsmParser.h\"\n#include \"llvm\/MC\/MCAsmInfo.h\"\n#include \"llvm\/MC\/MCCodeEmitter.h\"\n#include \"llvm\/MC\/MCContext.h\"\n#include \"llvm\/MC\/MCInstrInfo.h\"\n#include \"llvm\/MC\/MCObjectFileInfo.h\"\n#include \"llvm\/MC\/MCRegisterInfo.h\"\n#include \"llvm\/MC\/MCStreamer.h\"\n#include \"llvm\/MC\/MCSubtargetInfo.h\"\n#include \"llvm\/MC\/MCAsmBackend.h\"\n#include \"llvm\/MC\/MCTargetAsmParser.h\"\n#include \"llvm\/Support\/CommandLine.h\"\n#include \"llvm\/Support\/FormattedStream.h\"\n#include \"llvm\/Support\/ErrorHandling.h\"\n#include \"llvm\/Support\/ManagedStatic.h\"\n#include \"llvm\/Support\/MemoryBuffer.h\"\n#include \"llvm\/Support\/PrettyStackTrace.h\"\n#include \"llvm\/Support\/SourceMgr.h\"\n#include \"llvm\/Support\/Timer.h\"\n#include \"llvm\/Support\/raw_ostream.h\"\n#include \"llvm\/Support\/Host.h\"\n#include \"llvm\/Support\/Path.h\"\n#include \"llvm\/Support\/Signals.h\"\n#include \"llvm\/Support\/system_error.h\"\n#include \"llvm\/Target\/TargetData.h\"\n#include \"llvm\/Target\/TargetInstrInfo.h\"\n#include \"llvm\/Target\/TargetLowering.h\"\n#include \"llvm\/Target\/TargetLoweringObjectFile.h\"\n#include \"llvm\/Target\/TargetMachine.h\"\n#include \"llvm\/Target\/TargetRegistry.h\"\n#include \"llvm\/Target\/TargetSelect.h\"\n#include \"llvm\/Target\/TargetSubtargetInfo.h\"\nusing namespace clang;\nusing namespace clang::driver;\nusing namespace llvm;\n\nnamespace {\n\n\/\/\/ \\brief Helper class for representing a single invocation of the assembler.\nstruct AssemblerInvocation {\n \/\/\/ @name Target Options\n \/\/\/ @{\n\n std::string Triple;\n\n \/\/\/ @}\n \/\/\/ @name Language Options\n \/\/\/ @{\n\n std::vector<std::string> IncludePaths;\n unsigned NoInitialTextSection : 1;\n unsigned SaveTemporaryLabels : 1;\n\n \/\/\/ @}\n \/\/\/ @name Frontend Options\n \/\/\/ @{\n\n std::string InputFile;\n std::vector<std::string> LLVMArgs;\n std::string OutputPath;\n enum FileType {\n FT_Asm, \/\/\/< Assembly (.s) output, transliterate mode.\n FT_Null, \/\/\/< No output, for timing purposes.\n FT_Obj \/\/\/< Object file output.\n };\n FileType OutputType;\n unsigned ShowHelp : 1;\n unsigned ShowVersion : 1;\n\n \/\/\/ @}\n \/\/\/ @name Transliterate Options\n \/\/\/ @{\n\n unsigned OutputAsmVariant;\n unsigned ShowEncoding : 1;\n unsigned ShowInst : 1;\n\n \/\/\/ @}\n \/\/\/ @name Assembler Options\n \/\/\/ @{\n\n unsigned RelaxAll : 1;\n unsigned NoExecStack : 1;\n\n \/\/\/ @}\n\npublic:\n AssemblerInvocation() {\n Triple = \"\";\n NoInitialTextSection = 0;\n InputFile = \"-\";\n OutputPath = \"-\";\n OutputType = FT_Asm;\n OutputAsmVariant = 0;\n ShowInst = 0;\n ShowEncoding = 0;\n RelaxAll = 0;\n NoExecStack = 0;\n }\n\n static void CreateFromArgs(AssemblerInvocation &Res, const char **ArgBegin,\n const char **ArgEnd, Diagnostic &Diags);\n};\n\n}\n\nvoid AssemblerInvocation::CreateFromArgs(AssemblerInvocation &Opts,\n const char **ArgBegin,\n const char **ArgEnd,\n Diagnostic &Diags) {\n using namespace clang::driver::cc1asoptions;\n \/\/ Parse the arguments.\n OwningPtr<OptTable> OptTbl(createCC1AsOptTable());\n unsigned MissingArgIndex, MissingArgCount;\n OwningPtr<InputArgList> Args(\n OptTbl->ParseArgs(ArgBegin, ArgEnd,MissingArgIndex, MissingArgCount));\n\n \/\/ Check for missing argument error.\n if (MissingArgCount)\n Diags.Report(diag::err_drv_missing_argument)\n << Args->getArgString(MissingArgIndex) << MissingArgCount;\n\n \/\/ Issue errors on unknown arguments.\n for (arg_iterator it = Args->filtered_begin(cc1asoptions::OPT_UNKNOWN),\n ie = Args->filtered_end(); it != ie; ++it)\n Diags.Report(diag::err_drv_unknown_argument) << (*it) ->getAsString(*Args);\n\n \/\/ Construct the invocation.\n\n \/\/ Target Options\n Opts.Triple = Triple::normalize(Args->getLastArgValue(OPT_triple));\n if (Opts.Triple.empty()) \/\/ Use the host triple if unspecified.\n Opts.Triple = sys::getHostTriple();\n\n \/\/ Language Options\n Opts.IncludePaths = Args->getAllArgValues(OPT_I);\n Opts.NoInitialTextSection = Args->hasArg(OPT_n);\n Opts.SaveTemporaryLabels = Args->hasArg(OPT_L);\n\n \/\/ Frontend Options\n if (Args->hasArg(OPT_INPUT)) {\n bool First = true;\n for (arg_iterator it = Args->filtered_begin(OPT_INPUT),\n ie = Args->filtered_end(); it != ie; ++it, First=false) {\n const Arg *A = it;\n if (First)\n Opts.InputFile = A->getValue(*Args);\n else\n Diags.Report(diag::err_drv_unknown_argument) << A->getAsString(*Args);\n }\n }\n Opts.LLVMArgs = Args->getAllArgValues(OPT_mllvm);\n if (Args->hasArg(OPT_fatal_warnings))\n Opts.LLVMArgs.push_back(\"-fatal-assembler-warnings\");\n Opts.OutputPath = Args->getLastArgValue(OPT_o);\n if (Arg *A = Args->getLastArg(OPT_filetype)) {\n StringRef Name = A->getValue(*Args);\n unsigned OutputType = StringSwitch<unsigned>(Name)\n .Case(\"asm\", FT_Asm)\n .Case(\"null\", FT_Null)\n .Case(\"obj\", FT_Obj)\n .Default(~0U);\n if (OutputType == ~0U)\n Diags.Report(diag::err_drv_invalid_value)\n << A->getAsString(*Args) << Name;\n else\n Opts.OutputType = FileType(OutputType);\n }\n Opts.ShowHelp = Args->hasArg(OPT_help);\n Opts.ShowVersion = Args->hasArg(OPT_version);\n\n \/\/ Transliterate Options\n Opts.OutputAsmVariant = Args->getLastArgIntValue(OPT_output_asm_variant,\n 0, Diags);\n Opts.ShowEncoding = Args->hasArg(OPT_show_encoding);\n Opts.ShowInst = Args->hasArg(OPT_show_inst);\n\n \/\/ Assemble Options\n Opts.RelaxAll = Args->hasArg(OPT_relax_all);\n Opts.NoExecStack = Args->hasArg(OPT_no_exec_stack);\n}\n\nstatic formatted_raw_ostream *GetOutputStream(AssemblerInvocation &Opts,\n Diagnostic &Diags,\n bool Binary) {\n if (Opts.OutputPath.empty())\n Opts.OutputPath = \"-\";\n\n \/\/ Make sure that the Out file gets unlinked from the disk if we get a\n \/\/ SIGINT.\n if (Opts.OutputPath != \"-\")\n sys::RemoveFileOnSignal(sys::Path(Opts.OutputPath));\n\n std::string Error;\n raw_fd_ostream *Out =\n new raw_fd_ostream(Opts.OutputPath.c_str(), Error,\n (Binary ? raw_fd_ostream::F_Binary : 0));\n if (!Error.empty()) {\n Diags.Report(diag::err_fe_unable_to_open_output)\n << Opts.OutputPath << Error;\n return 0;\n }\n\n return new formatted_raw_ostream(*Out, formatted_raw_ostream::DELETE_STREAM);\n}\n\nstatic bool ExecuteAssembler(AssemblerInvocation &Opts, Diagnostic &Diags) {\n \/\/ Get the target specific parser.\n std::string Error;\n const Target *TheTarget(TargetRegistry::lookupTarget(Opts.Triple, Error));\n if (!TheTarget) {\n Diags.Report(diag::err_target_unknown_triple) << Opts.Triple;\n return false;\n }\n\n OwningPtr<MemoryBuffer> BufferPtr;\n if (error_code ec = MemoryBuffer::getFileOrSTDIN(Opts.InputFile, BufferPtr)) {\n Error = ec.message();\n Diags.Report(diag::err_fe_error_reading) << Opts.InputFile;\n return false;\n }\n MemoryBuffer *Buffer = BufferPtr.take();\n\n SourceMgr SrcMgr;\n\n \/\/ Tell SrcMgr about this buffer, which is what the parser will pick up.\n SrcMgr.AddNewSourceBuffer(Buffer, SMLoc());\n\n \/\/ Record the location of the include directories so that the lexer can find\n \/\/ it later.\n SrcMgr.setIncludeDirs(Opts.IncludePaths);\n\n OwningPtr<MCAsmInfo> MAI(TheTarget->createMCAsmInfo(Opts.Triple));\n assert(MAI && \"Unable to create target asm info!\");\n\n OwningPtr<MCRegisterInfo> MRI(TheTarget->createMCRegInfo(Opts.Triple));\n assert(MRI && \"Unable to create target register info!\");\n\n bool IsBinary = Opts.OutputType == AssemblerInvocation::FT_Obj;\n formatted_raw_ostream *Out = GetOutputStream(Opts, Diags, IsBinary);\n if (!Out)\n return false;\n\n \/\/ FIXME: We shouldn't need to do this (and link in codegen).\n OwningPtr<TargetMachine> TM(TheTarget->createTargetMachine(Opts.Triple,\n \"\", \"\"));\n if (!TM) {\n Diags.Report(diag::err_target_unknown_triple) << Opts.Triple;\n return false;\n }\n\n \/\/ FIXME: This is not pretty. MCContext has a ptr to MCObjectFileInfo and\n \/\/ MCObjectFileInfo needs a MCContext reference in order to initialize itself.\n OwningPtr<MCObjectFileInfo> MOFI(new MCObjectFileInfo());\n MCContext Ctx(*MAI, *MRI, MOFI.get());\n \/\/ FIXME: Assembler behavior can change with -static.\n MOFI->InitMCObjectFileInfo(Opts.Triple,\n Reloc::Default, CodeModel::Default, Ctx);\n if (Opts.SaveTemporaryLabels)\n Ctx.setAllowTemporaryLabels(false);\n\n OwningPtr<MCStreamer> Str;\n\n const TargetLoweringObjectFile &TLOF =\n TM->getTargetLowering()->getObjFileLowering();\n const_cast<TargetLoweringObjectFile&>(TLOF).Initialize(Ctx, *TM);\n\n const MCSubtargetInfo &STI = TM->getSubtarget<MCSubtargetInfo>();\n\n \/\/ FIXME: There is a bit of code duplication with addPassesToEmitFile.\n if (Opts.OutputType == AssemblerInvocation::FT_Asm) {\n MCInstPrinter *IP =\n TheTarget->createMCInstPrinter(Opts.OutputAsmVariant, *MAI);\n MCCodeEmitter *CE = 0;\n MCAsmBackend *MAB = 0;\n if (Opts.ShowEncoding) {\n CE = TheTarget->createMCCodeEmitter(*TM->getInstrInfo(), STI, Ctx);\n MAB = TheTarget->createMCAsmBackend(Opts.Triple);\n }\n Str.reset(TheTarget->createAsmStreamer(Ctx, *Out, \/*asmverbose*\/true,\n \/*useLoc*\/ true,\n \/*useCFI*\/ true, IP, CE, MAB,\n Opts.ShowInst));\n } else if (Opts.OutputType == AssemblerInvocation::FT_Null) {\n Str.reset(createNullStreamer(Ctx));\n } else {\n assert(Opts.OutputType == AssemblerInvocation::FT_Obj &&\n \"Invalid file type!\");\n MCCodeEmitter *CE = TheTarget->createMCCodeEmitter(*TM->getInstrInfo(),\n STI, Ctx);\n MCAsmBackend *MAB = TheTarget->createMCAsmBackend(Opts.Triple);\n Str.reset(TheTarget->createMCObjectStreamer(Opts.Triple, Ctx, *MAB, *Out,\n CE, Opts.RelaxAll,\n Opts.NoExecStack));\n Str.get()->InitSections();\n }\n\n OwningPtr<MCAsmParser> Parser(createMCAsmParser(*TheTarget, SrcMgr, Ctx,\n *Str.get(), *MAI));\n OwningPtr<MCTargetAsmParser>\n TAP(TheTarget->createMCAsmParser(const_cast<MCSubtargetInfo&>(STI),\n *Parser));\n if (!TAP) {\n Diags.Report(diag::err_target_unknown_triple) << Opts.Triple;\n return false;\n }\n\n Parser->setTargetParser(*TAP.get());\n\n bool Success = !Parser->Run(Opts.NoInitialTextSection);\n\n \/\/ Close the output.\n delete Out;\n\n \/\/ Delete output on errors.\n if (!Success && Opts.OutputPath != \"-\")\n sys::Path(Opts.OutputPath).eraseFromDisk();\n\n return Success;\n}\n\nstatic void LLVMErrorHandler(void *UserData, const std::string &Message) {\n Diagnostic &Diags = *static_cast<Diagnostic*>(UserData);\n\n Diags.Report(diag::err_fe_error_backend) << Message;\n\n \/\/ We cannot recover from llvm errors.\n exit(1);\n}\n\nint cc1as_main(const char **ArgBegin, const char **ArgEnd,\n const char *Argv0, void *MainAddr) {\n \/\/ Print a stack trace if we signal out.\n sys::PrintStackTraceOnErrorSignal();\n PrettyStackTraceProgram X(ArgEnd - ArgBegin, ArgBegin);\n llvm_shutdown_obj Y; \/\/ Call llvm_shutdown() on exit.\n\n \/\/ Initialize targets and assembly printers\/parsers.\n InitializeAllTargetInfos();\n InitializeAllTargetMCs();\n InitializeAllAsmParsers();\n\n \/\/ Construct our diagnostic client.\n TextDiagnosticPrinter *DiagClient\n = new TextDiagnosticPrinter(errs(), DiagnosticOptions());\n DiagClient->setPrefix(\"clang -cc1as\");\n llvm::IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());\n Diagnostic Diags(DiagID, DiagClient);\n\n \/\/ Set an error handler, so that any LLVM backend diagnostics go through our\n \/\/ error handler.\n ScopedFatalErrorHandler FatalErrorHandler\n (LLVMErrorHandler, static_cast<void*>(&Diags));\n\n \/\/ Parse the arguments.\n AssemblerInvocation Asm;\n AssemblerInvocation::CreateFromArgs(Asm, ArgBegin, ArgEnd, Diags);\n\n \/\/ Honor -help.\n if (Asm.ShowHelp) {\n llvm::OwningPtr<driver::OptTable> Opts(driver::createCC1AsOptTable());\n Opts->PrintHelp(llvm::outs(), \"clang -cc1as\", \"Clang Integrated Assembler\");\n return 0;\n }\n\n \/\/ Honor -version.\n \/\/\n \/\/ FIXME: Use a better -version message?\n if (Asm.ShowVersion) {\n llvm::cl::PrintVersionMessage();\n return 0;\n }\n\n \/\/ Honor -mllvm.\n \/\/\n \/\/ FIXME: Remove this, one day.\n if (!Asm.LLVMArgs.empty()) {\n unsigned NumArgs = Asm.LLVMArgs.size();\n const char **Args = new const char*[NumArgs + 2];\n Args[0] = \"clang (LLVM option parsing)\";\n for (unsigned i = 0; i != NumArgs; ++i)\n Args[i + 1] = Asm.LLVMArgs[i].c_str();\n Args[NumArgs + 1] = 0;\n llvm::cl::ParseCommandLineOptions(NumArgs + 1, const_cast<char **>(Args));\n }\n\n \/\/ Execute the invocation, unless there were parsing errors.\n bool Success = false;\n if (!Diags.hasErrorOccurred())\n Success = ExecuteAssembler(Asm, Diags);\n\n \/\/ If any timers were active but haven't been destroyed yet, print their\n \/\/ results now.\n TimerGroup::printAll(errs());\n\n return !Success;\n}\n<commit_msg>Assembler really doesn't need to create TargetMachine anymore.<commit_after>\/\/===-- cc1as_main.cpp - Clang Assembler ---------------------------------===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This is the entry point to the clang -cc1as functionality, which implements\n\/\/ the direct interface to the LLVM MC based assembler.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"clang\/Basic\/Diagnostic.h\"\n#include \"clang\/Driver\/Arg.h\"\n#include \"clang\/Driver\/ArgList.h\"\n#include \"clang\/Driver\/DriverDiagnostic.h\"\n#include \"clang\/Driver\/CC1AsOptions.h\"\n#include \"clang\/Driver\/OptTable.h\"\n#include \"clang\/Driver\/Options.h\"\n#include \"clang\/Frontend\/DiagnosticOptions.h\"\n#include \"clang\/Frontend\/FrontendDiagnostic.h\"\n#include \"clang\/Frontend\/TextDiagnosticPrinter.h\"\n#include \"llvm\/ADT\/OwningPtr.h\"\n#include \"llvm\/ADT\/StringSwitch.h\"\n#include \"llvm\/ADT\/Triple.h\"\n#include \"llvm\/MC\/MCParser\/MCAsmParser.h\"\n#include \"llvm\/MC\/MCAsmInfo.h\"\n#include \"llvm\/MC\/MCCodeEmitter.h\"\n#include \"llvm\/MC\/MCContext.h\"\n#include \"llvm\/MC\/MCInstrInfo.h\"\n#include \"llvm\/MC\/MCObjectFileInfo.h\"\n#include \"llvm\/MC\/MCRegisterInfo.h\"\n#include \"llvm\/MC\/MCStreamer.h\"\n#include \"llvm\/MC\/MCSubtargetInfo.h\"\n#include \"llvm\/MC\/MCAsmBackend.h\"\n#include \"llvm\/MC\/MCTargetAsmParser.h\"\n#include \"llvm\/Support\/CommandLine.h\"\n#include \"llvm\/Support\/FormattedStream.h\"\n#include \"llvm\/Support\/ErrorHandling.h\"\n#include \"llvm\/Support\/ManagedStatic.h\"\n#include \"llvm\/Support\/MemoryBuffer.h\"\n#include \"llvm\/Support\/PrettyStackTrace.h\"\n#include \"llvm\/Support\/SourceMgr.h\"\n#include \"llvm\/Support\/Timer.h\"\n#include \"llvm\/Support\/raw_ostream.h\"\n#include \"llvm\/Support\/Host.h\"\n#include \"llvm\/Support\/Path.h\"\n#include \"llvm\/Support\/Signals.h\"\n#include \"llvm\/Support\/system_error.h\"\n#include \"llvm\/Target\/TargetData.h\"\n#include \"llvm\/Target\/TargetRegistry.h\"\n#include \"llvm\/Target\/TargetSelect.h\"\nusing namespace clang;\nusing namespace clang::driver;\nusing namespace llvm;\n\nnamespace {\n\n\/\/\/ \\brief Helper class for representing a single invocation of the assembler.\nstruct AssemblerInvocation {\n \/\/\/ @name Target Options\n \/\/\/ @{\n\n std::string Triple;\n\n \/\/\/ @}\n \/\/\/ @name Language Options\n \/\/\/ @{\n\n std::vector<std::string> IncludePaths;\n unsigned NoInitialTextSection : 1;\n unsigned SaveTemporaryLabels : 1;\n\n \/\/\/ @}\n \/\/\/ @name Frontend Options\n \/\/\/ @{\n\n std::string InputFile;\n std::vector<std::string> LLVMArgs;\n std::string OutputPath;\n enum FileType {\n FT_Asm, \/\/\/< Assembly (.s) output, transliterate mode.\n FT_Null, \/\/\/< No output, for timing purposes.\n FT_Obj \/\/\/< Object file output.\n };\n FileType OutputType;\n unsigned ShowHelp : 1;\n unsigned ShowVersion : 1;\n\n \/\/\/ @}\n \/\/\/ @name Transliterate Options\n \/\/\/ @{\n\n unsigned OutputAsmVariant;\n unsigned ShowEncoding : 1;\n unsigned ShowInst : 1;\n\n \/\/\/ @}\n \/\/\/ @name Assembler Options\n \/\/\/ @{\n\n unsigned RelaxAll : 1;\n unsigned NoExecStack : 1;\n\n \/\/\/ @}\n\npublic:\n AssemblerInvocation() {\n Triple = \"\";\n NoInitialTextSection = 0;\n InputFile = \"-\";\n OutputPath = \"-\";\n OutputType = FT_Asm;\n OutputAsmVariant = 0;\n ShowInst = 0;\n ShowEncoding = 0;\n RelaxAll = 0;\n NoExecStack = 0;\n }\n\n static void CreateFromArgs(AssemblerInvocation &Res, const char **ArgBegin,\n const char **ArgEnd, Diagnostic &Diags);\n};\n\n}\n\nvoid AssemblerInvocation::CreateFromArgs(AssemblerInvocation &Opts,\n const char **ArgBegin,\n const char **ArgEnd,\n Diagnostic &Diags) {\n using namespace clang::driver::cc1asoptions;\n \/\/ Parse the arguments.\n OwningPtr<OptTable> OptTbl(createCC1AsOptTable());\n unsigned MissingArgIndex, MissingArgCount;\n OwningPtr<InputArgList> Args(\n OptTbl->ParseArgs(ArgBegin, ArgEnd,MissingArgIndex, MissingArgCount));\n\n \/\/ Check for missing argument error.\n if (MissingArgCount)\n Diags.Report(diag::err_drv_missing_argument)\n << Args->getArgString(MissingArgIndex) << MissingArgCount;\n\n \/\/ Issue errors on unknown arguments.\n for (arg_iterator it = Args->filtered_begin(cc1asoptions::OPT_UNKNOWN),\n ie = Args->filtered_end(); it != ie; ++it)\n Diags.Report(diag::err_drv_unknown_argument) << (*it) ->getAsString(*Args);\n\n \/\/ Construct the invocation.\n\n \/\/ Target Options\n Opts.Triple = Triple::normalize(Args->getLastArgValue(OPT_triple));\n if (Opts.Triple.empty()) \/\/ Use the host triple if unspecified.\n Opts.Triple = sys::getHostTriple();\n\n \/\/ Language Options\n Opts.IncludePaths = Args->getAllArgValues(OPT_I);\n Opts.NoInitialTextSection = Args->hasArg(OPT_n);\n Opts.SaveTemporaryLabels = Args->hasArg(OPT_L);\n\n \/\/ Frontend Options\n if (Args->hasArg(OPT_INPUT)) {\n bool First = true;\n for (arg_iterator it = Args->filtered_begin(OPT_INPUT),\n ie = Args->filtered_end(); it != ie; ++it, First=false) {\n const Arg *A = it;\n if (First)\n Opts.InputFile = A->getValue(*Args);\n else\n Diags.Report(diag::err_drv_unknown_argument) << A->getAsString(*Args);\n }\n }\n Opts.LLVMArgs = Args->getAllArgValues(OPT_mllvm);\n if (Args->hasArg(OPT_fatal_warnings))\n Opts.LLVMArgs.push_back(\"-fatal-assembler-warnings\");\n Opts.OutputPath = Args->getLastArgValue(OPT_o);\n if (Arg *A = Args->getLastArg(OPT_filetype)) {\n StringRef Name = A->getValue(*Args);\n unsigned OutputType = StringSwitch<unsigned>(Name)\n .Case(\"asm\", FT_Asm)\n .Case(\"null\", FT_Null)\n .Case(\"obj\", FT_Obj)\n .Default(~0U);\n if (OutputType == ~0U)\n Diags.Report(diag::err_drv_invalid_value)\n << A->getAsString(*Args) << Name;\n else\n Opts.OutputType = FileType(OutputType);\n }\n Opts.ShowHelp = Args->hasArg(OPT_help);\n Opts.ShowVersion = Args->hasArg(OPT_version);\n\n \/\/ Transliterate Options\n Opts.OutputAsmVariant = Args->getLastArgIntValue(OPT_output_asm_variant,\n 0, Diags);\n Opts.ShowEncoding = Args->hasArg(OPT_show_encoding);\n Opts.ShowInst = Args->hasArg(OPT_show_inst);\n\n \/\/ Assemble Options\n Opts.RelaxAll = Args->hasArg(OPT_relax_all);\n Opts.NoExecStack = Args->hasArg(OPT_no_exec_stack);\n}\n\nstatic formatted_raw_ostream *GetOutputStream(AssemblerInvocation &Opts,\n Diagnostic &Diags,\n bool Binary) {\n if (Opts.OutputPath.empty())\n Opts.OutputPath = \"-\";\n\n \/\/ Make sure that the Out file gets unlinked from the disk if we get a\n \/\/ SIGINT.\n if (Opts.OutputPath != \"-\")\n sys::RemoveFileOnSignal(sys::Path(Opts.OutputPath));\n\n std::string Error;\n raw_fd_ostream *Out =\n new raw_fd_ostream(Opts.OutputPath.c_str(), Error,\n (Binary ? raw_fd_ostream::F_Binary : 0));\n if (!Error.empty()) {\n Diags.Report(diag::err_fe_unable_to_open_output)\n << Opts.OutputPath << Error;\n return 0;\n }\n\n return new formatted_raw_ostream(*Out, formatted_raw_ostream::DELETE_STREAM);\n}\n\nstatic bool ExecuteAssembler(AssemblerInvocation &Opts, Diagnostic &Diags) {\n \/\/ Get the target specific parser.\n std::string Error;\n const Target *TheTarget(TargetRegistry::lookupTarget(Opts.Triple, Error));\n if (!TheTarget) {\n Diags.Report(diag::err_target_unknown_triple) << Opts.Triple;\n return false;\n }\n\n OwningPtr<MemoryBuffer> BufferPtr;\n if (error_code ec = MemoryBuffer::getFileOrSTDIN(Opts.InputFile, BufferPtr)) {\n Error = ec.message();\n Diags.Report(diag::err_fe_error_reading) << Opts.InputFile;\n return false;\n }\n MemoryBuffer *Buffer = BufferPtr.take();\n\n SourceMgr SrcMgr;\n\n \/\/ Tell SrcMgr about this buffer, which is what the parser will pick up.\n SrcMgr.AddNewSourceBuffer(Buffer, SMLoc());\n\n \/\/ Record the location of the include directories so that the lexer can find\n \/\/ it later.\n SrcMgr.setIncludeDirs(Opts.IncludePaths);\n\n OwningPtr<MCAsmInfo> MAI(TheTarget->createMCAsmInfo(Opts.Triple));\n assert(MAI && \"Unable to create target asm info!\");\n\n OwningPtr<MCRegisterInfo> MRI(TheTarget->createMCRegInfo(Opts.Triple));\n assert(MRI && \"Unable to create target register info!\");\n\n bool IsBinary = Opts.OutputType == AssemblerInvocation::FT_Obj;\n formatted_raw_ostream *Out = GetOutputStream(Opts, Diags, IsBinary);\n if (!Out)\n return false;\n\n \/\/ FIXME: This is not pretty. MCContext has a ptr to MCObjectFileInfo and\n \/\/ MCObjectFileInfo needs a MCContext reference in order to initialize itself.\n OwningPtr<MCObjectFileInfo> MOFI(new MCObjectFileInfo());\n MCContext Ctx(*MAI, *MRI, MOFI.get());\n \/\/ FIXME: Assembler behavior can change with -static.\n MOFI->InitMCObjectFileInfo(Opts.Triple,\n Reloc::Default, CodeModel::Default, Ctx);\n if (Opts.SaveTemporaryLabels)\n Ctx.setAllowTemporaryLabels(false);\n\n OwningPtr<MCStreamer> Str;\n\n OwningPtr<MCInstrInfo> MCII(TheTarget->createMCInstrInfo());\n OwningPtr<MCSubtargetInfo>\n STI(TheTarget->createMCSubtargetInfo(Opts.Triple, \"\", \"\"));\n\n \/\/ FIXME: There is a bit of code duplication with addPassesToEmitFile.\n if (Opts.OutputType == AssemblerInvocation::FT_Asm) {\n MCInstPrinter *IP =\n TheTarget->createMCInstPrinter(Opts.OutputAsmVariant, *MAI);\n MCCodeEmitter *CE = 0;\n MCAsmBackend *MAB = 0;\n if (Opts.ShowEncoding) {\n CE = TheTarget->createMCCodeEmitter(*MCII, *STI, Ctx);\n MAB = TheTarget->createMCAsmBackend(Opts.Triple);\n }\n Str.reset(TheTarget->createAsmStreamer(Ctx, *Out, \/*asmverbose*\/true,\n \/*useLoc*\/ true,\n \/*useCFI*\/ true, IP, CE, MAB,\n Opts.ShowInst));\n } else if (Opts.OutputType == AssemblerInvocation::FT_Null) {\n Str.reset(createNullStreamer(Ctx));\n } else {\n assert(Opts.OutputType == AssemblerInvocation::FT_Obj &&\n \"Invalid file type!\");\n MCCodeEmitter *CE = TheTarget->createMCCodeEmitter(*MCII, *STI, Ctx);\n MCAsmBackend *MAB = TheTarget->createMCAsmBackend(Opts.Triple);\n Str.reset(TheTarget->createMCObjectStreamer(Opts.Triple, Ctx, *MAB, *Out,\n CE, Opts.RelaxAll,\n Opts.NoExecStack));\n Str.get()->InitSections();\n }\n\n OwningPtr<MCAsmParser> Parser(createMCAsmParser(*TheTarget, SrcMgr, Ctx,\n *Str.get(), *MAI));\n OwningPtr<MCTargetAsmParser> TAP(TheTarget->createMCAsmParser(*STI, *Parser));\n if (!TAP) {\n Diags.Report(diag::err_target_unknown_triple) << Opts.Triple;\n return false;\n }\n\n Parser->setTargetParser(*TAP.get());\n\n bool Success = !Parser->Run(Opts.NoInitialTextSection);\n\n \/\/ Close the output.\n delete Out;\n\n \/\/ Delete output on errors.\n if (!Success && Opts.OutputPath != \"-\")\n sys::Path(Opts.OutputPath).eraseFromDisk();\n\n return Success;\n}\n\nstatic void LLVMErrorHandler(void *UserData, const std::string &Message) {\n Diagnostic &Diags = *static_cast<Diagnostic*>(UserData);\n\n Diags.Report(diag::err_fe_error_backend) << Message;\n\n \/\/ We cannot recover from llvm errors.\n exit(1);\n}\n\nint cc1as_main(const char **ArgBegin, const char **ArgEnd,\n const char *Argv0, void *MainAddr) {\n \/\/ Print a stack trace if we signal out.\n sys::PrintStackTraceOnErrorSignal();\n PrettyStackTraceProgram X(ArgEnd - ArgBegin, ArgBegin);\n llvm_shutdown_obj Y; \/\/ Call llvm_shutdown() on exit.\n\n \/\/ Initialize targets and assembly printers\/parsers.\n InitializeAllTargetInfos();\n InitializeAllTargetMCs();\n InitializeAllAsmParsers();\n\n \/\/ Construct our diagnostic client.\n TextDiagnosticPrinter *DiagClient\n = new TextDiagnosticPrinter(errs(), DiagnosticOptions());\n DiagClient->setPrefix(\"clang -cc1as\");\n llvm::IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());\n Diagnostic Diags(DiagID, DiagClient);\n\n \/\/ Set an error handler, so that any LLVM backend diagnostics go through our\n \/\/ error handler.\n ScopedFatalErrorHandler FatalErrorHandler\n (LLVMErrorHandler, static_cast<void*>(&Diags));\n\n \/\/ Parse the arguments.\n AssemblerInvocation Asm;\n AssemblerInvocation::CreateFromArgs(Asm, ArgBegin, ArgEnd, Diags);\n\n \/\/ Honor -help.\n if (Asm.ShowHelp) {\n llvm::OwningPtr<driver::OptTable> Opts(driver::createCC1AsOptTable());\n Opts->PrintHelp(llvm::outs(), \"clang -cc1as\", \"Clang Integrated Assembler\");\n return 0;\n }\n\n \/\/ Honor -version.\n \/\/\n \/\/ FIXME: Use a better -version message?\n if (Asm.ShowVersion) {\n llvm::cl::PrintVersionMessage();\n return 0;\n }\n\n \/\/ Honor -mllvm.\n \/\/\n \/\/ FIXME: Remove this, one day.\n if (!Asm.LLVMArgs.empty()) {\n unsigned NumArgs = Asm.LLVMArgs.size();\n const char **Args = new const char*[NumArgs + 2];\n Args[0] = \"clang (LLVM option parsing)\";\n for (unsigned i = 0; i != NumArgs; ++i)\n Args[i + 1] = Asm.LLVMArgs[i].c_str();\n Args[NumArgs + 1] = 0;\n llvm::cl::ParseCommandLineOptions(NumArgs + 1, const_cast<char **>(Args));\n }\n\n \/\/ Execute the invocation, unless there were parsing errors.\n bool Success = false;\n if (!Diags.hasErrorOccurred())\n Success = ExecuteAssembler(Asm, Diags);\n\n \/\/ If any timers were active but haven't been destroyed yet, print their\n \/\/ results now.\n TimerGroup::printAll(errs());\n\n return !Success;\n}\n<|endoftext|>"} {"text":"<commit_before>#ifndef ALEPH_TOPOLOGY_SPINE_HH__\n#define ALEPH_TOPOLOGY_SPINE_HH__\n\n#include <aleph\/topology\/Intersections.hh>\n\n#include <algorithm>\n#include <unordered_map>\n#include <set>\n#include <vector>\n\nnamespace aleph\n{\n\nnamespace topology\n{\n\n\/**\n Checks whether a simplex in a simplicial complex is principal, i.e.\n whether it is not a proper face of any other simplex in K.\n*\/\n\ntemplate <class SimplicialComplex, class Simplex> bool isPrincipal( const Simplex& s, const SimplicialComplex& K )\n{\n \/\/ Individual vertices cannot be considered to be principal because\n \/\/ they do not have a free face.\n if( s.dimension() == 0 )\n return false;\n\n bool principal = true;\n auto itPair = K.range( s.dimension() + 1 );\n\n for( auto it = itPair.first; it != itPair.second; ++it )\n {\n auto&& t = *it;\n\n \/\/ This check assumes that the simplicial complex is valid, so it\n \/\/ suffices to search faces in one dimension _below_ s. Note that\n \/\/ the check only has to evaluate the *size* of the intersection,\n \/\/ as this is sufficient to determine whether a simplex is a face\n \/\/ of another simplex.\n if( sizeOfIntersection(s,t) == s.size() )\n principal = false;\n }\n\n return principal;\n}\n\n\/**\n Checks whether a simplex in a simplicial complex is admissible, i.e.\n the simplex is *principal* and has at least one free face.\n*\/\n\ntemplate <class SimplicialComplex, class Simplex> Simplex isAdmissible( const Simplex& s, const SimplicialComplex& K )\n{\n if( !isPrincipal(s,K) )\n return Simplex();\n\n \/\/ Check whether a free face exists ----------------------------------\n\n std::vector<Simplex> faces( s.begin_boundary(), s.end_boundary() );\n std::vector<bool> admissible( faces.size(), true );\n\n std::size_t i = 0;\n auto itPair = K.range( s.dimension() ); \/\/ valid range for searches, viz. *all*\n \/\/ faces in \"one dimension up\"\n\n for( auto&& face : faces )\n {\n for( auto it = itPair.first; it != itPair.second; ++it )\n {\n auto&& t = *it;\n\n \/\/ We do not have to check for intersections with the original\n \/\/ simplex from which we started---we already know that we are\n \/\/ a face.\n if( t != s )\n {\n if( sizeOfIntersection(face,t) == face.size() )\n {\n admissible[i] = false;\n break;\n }\n }\n }\n\n ++i;\n }\n\n auto pos = std::find( admissible.begin(), admissible.end(), true );\n if( pos == admissible.end() )\n return Simplex();\n else\n return faces.at( std::distance( admissible.begin(), pos ) );\n}\n\n\/**\n Calculates all principal faces of a given simplicial complex and\n returns them.\n*\/\n\ntemplate <class SimplicialComplex> std::unordered_map<typename SimplicialComplex::value_type, typename SimplicialComplex::value_type> principalFaces( const SimplicialComplex& K )\n{\n using Simplex = typename SimplicialComplex::value_type;\n auto L = K;\n\n std::unordered_map<Simplex, Simplex> admissible;\n\n \/\/ Step 1: determine free faces --------------------------------------\n \/\/\n \/\/ This first checks which simplices have at least one free face,\n \/\/ meaning that they may be potentially admissible.\n\n for( auto it = L.begin(); it != L.end(); ++it )\n {\n if( it->dimension() == 0 )\n continue;\n\n \/\/ The range of the complex M is sufficient because we have\n \/\/ already encountered all lower-dimensional simplices that\n \/\/ precede the current one given by `it`.\n \/\/\n \/\/ This complex will be used for testing free faces.\n SimplicialComplex M( L.begin(), it );\n\n \/\/ FIXME:\n \/\/\n \/\/ In case of equal data values, the assignment from above does\n \/\/ *not* work and will result in incorrect candidates.\n M = L;\n\n bool hasFreeFace = false;\n Simplex freeFace = Simplex();\n\n for( auto itFace = it->begin_boundary(); itFace != it->end_boundary(); ++itFace )\n {\n bool isFace = false;\n for( auto&& simplex : M )\n {\n if( itFace->dimension() + 1 == simplex.dimension() && simplex != *it )\n {\n \/\/ The current face must *not* be a face of another simplex in\n \/\/ the simplicial complex.\n if( intersect( *itFace, simplex ) == *itFace )\n {\n isFace = true;\n break;\n }\n }\n }\n\n hasFreeFace = !isFace;\n if( hasFreeFace )\n {\n freeFace = *itFace;\n break;\n }\n }\n\n if( hasFreeFace )\n admissible.insert( std::make_pair( *it, freeFace ) );\n }\n\n \/\/ Step 2: determine principality ------------------------------------\n \/\/\n \/\/ All simplices that are faces of higher-dimensional simplices are\n \/\/ now removed from the map of admissible simplices.\n\n for( auto&& s : L )\n {\n for( auto itFace = s.begin_boundary(); itFace != s.end_boundary(); ++itFace )\n admissible.erase( *itFace );\n }\n\n return admissible;\n}\n\n\/**\n Performs an iterated elementary simplicial collapse until *all* of the\n admissible simplices have been collapsed. This leads to the *spine* of\n the simplicial complex.\n\n @see S. Matveev, \"Algorithmic Topology and Classification of 3-Manifolds\"\n*\/\n\ntemplate <class SimplicialComplex> SimplicialComplex spine( const SimplicialComplex& K )\n{\n using Simplex = typename SimplicialComplex::value_type;\n auto L = K;\n\n \/\/ Step 1: obtain initial set of principal faces to start the process\n \/\/ of collapsing the complex.\n auto admissible = principalFaces( L );\n\n \/\/ Step 2: collapse until no admissible simplices are left -----------\n\n while( !admissible.empty() )\n {\n auto s = admissible.begin()->first;\n auto t = admissible.begin()->second;\n\n L.remove_without_validation( s );\n L.remove_without_validation( t );\n\n admissible.erase( s );\n\n \/\/ New simplices ---------------------------------------------------\n \/\/\n \/\/ Add new admissible simplices that may potentially have been\n \/\/ spawned by the removal of s.\n\n \/\/ 1. Add all faces of the principal simplex, as they may\n \/\/ potentially become admissible again.\n std::vector<Simplex> faces( s.begin_boundary(), s.end_boundary() );\n\n std::for_each( faces.begin(), faces.end(),\n [&t, &L, &admissible] ( const Simplex& s )\n {\n \/\/ TODO: rename function\n auto face = isAdmissible( s, L );\n\n if( t != s && face )\n admissible.insert( std::make_pair( s, face ) );\n }\n );\n\n \/\/ 2. Add all faces othe free face, as they may now themselves\n \/\/ become admissible.\n faces.assign( t.begin_boundary(), t.end_boundary() );\n\n std::for_each( faces.begin(), faces.end(),\n [&L, &admissible] ( const Simplex& s )\n {\n \/\/ TODO: rename function\n auto face = isAdmissible( s, L );\n\n if( face )\n admissible.insert( std::make_pair( s, face ) );\n }\n );\n\n#if 0\n \/\/ TODO: this check could be simplified by *storing* the free face\n \/\/ along with the given simplex\n for( auto itFace = s.begin_boundary(); itFace != s.end_boundary(); ++itFace )\n {\n auto t = *itFace;\n\n if( isAdmissible( s, t, L ) )\n {\n L.remove_without_validation( s );\n L.remove_without_validation( t );\n\n admissible.erase( s );\n\n \/\/ New simplices -----------------------------------------------\n \/\/\n \/\/ Add new admissible simplices that may potentially have been\n \/\/ spawned by the removal of s.\n\n \/\/ 1. Add all faces of the principal simplex, as they may\n \/\/ potentially become admissible again.\n std::vector<Simplex> faces( s.begin_boundary(), s.end_boundary() );\n\n std::for_each( faces.begin(), faces.end(),\n [&t, &L, &admissible] ( const Simplex& s )\n {\n if( t != s && isAdmissible( s, L ) )\n admissible.insert( s );\n }\n );\n\n \/\/ 2. Add all faces othe free face, as they may now themselves\n \/\/ become admissible.\n faces.assign( t.begin_boundary(), t.end_boundary() );\n\n std::for_each( faces.begin(), faces.end(),\n [&L, &admissible] ( const Simplex& s )\n {\n if( isAdmissible( s, L ) )\n admissible.insert( s );\n }\n );\n\n hasFreeFace = true;\n break;\n }\n }\n\n \/\/ The admissible simplex does not have a free face, so it must not\n \/\/ be used.\n if( !hasFreeFace )\n admissible.erase( s );\n#endif\n\n \/\/ The heuristic above is incapable of detecting *all* principal\n \/\/ faces of the complex because this may involve searching *all*\n \/\/ co-faces. Instead, it is easier to fill up the admissible set\n \/\/ here.\n if( admissible.empty() )\n admissible = principalFaces( L );\n }\n\n return L;\n}\n\n} \/\/ namespace topology\n\n} \/\/ namespace aleph\n\n#endif\n<commit_msg>Prepared new admissibility check<commit_after>#ifndef ALEPH_TOPOLOGY_SPINE_HH__\n#define ALEPH_TOPOLOGY_SPINE_HH__\n\n#include <aleph\/topology\/Intersections.hh>\n\n#include <algorithm>\n#include <unordered_map>\n#include <set>\n#include <vector>\n\nnamespace aleph\n{\n\nnamespace topology\n{\n\n\/**\n Stores coface relationships in a simplicial complex. Given a simplex\n \\f$\\sigma\\f$, the map contains all of its cofaces. Note that the map\n will be updated upon every elementary collapse.\n*\/\n\ntemplate <class Simplex> using CofaceMap = std::unordered_map<Simplex, std::unordered_set<Simplex> >;\n\ntemplate <class Simplex> bool isPrincipal( const CofaceMap<Simplex>& cofaces, const Simplex& s )\n{\n return cofaces.at( s ).empty();\n}\n\ntemplate <class Simplex> Simplex getFreeFace( const CofaceMap<Simplex>& cofaces, const Simplex& s )\n{\n if( !isPrincipal( cofaces, s ) )\n return Simplex();\n\n \/\/ Check whether a free face exists ----------------------------------\n\n for( auto itFace = s.begin_boundary(); itFace != s.end_boundary(); ++itFace )\n {\n auto&& allCofaces = cofaces.at( *itFace );\n if( allCofaces.size() == 1 && allCofaces.find( s ) != allCofaces.end() )\n return *itFace;\n }\n\n return Simplex();\n}\n\n\/**\n Checks whether a simplex in a simplicial complex is principal, i.e.\n whether it is not a proper face of any other simplex in K.\n*\/\n\ntemplate <class SimplicialComplex, class Simplex> bool isPrincipal( const Simplex& s, const SimplicialComplex& K )\n{\n \/\/ Individual vertices cannot be considered to be principal because\n \/\/ they do not have a free face.\n if( s.dimension() == 0 )\n return false;\n\n bool principal = true;\n auto itPair = K.range( s.dimension() + 1 );\n\n for( auto it = itPair.first; it != itPair.second; ++it )\n {\n auto&& t = *it;\n\n \/\/ This check assumes that the simplicial complex is valid, so it\n \/\/ suffices to search faces in one dimension _below_ s. Note that\n \/\/ the check only has to evaluate the *size* of the intersection,\n \/\/ as this is sufficient to determine whether a simplex is a face\n \/\/ of another simplex.\n if( sizeOfIntersection(s,t) == s.size() )\n principal = false;\n }\n\n return principal;\n}\n\n\/**\n Checks whether a simplex in a simplicial complex is admissible, i.e.\n the simplex is *principal* and has at least one free face.\n*\/\n\ntemplate <class SimplicialComplex, class Simplex> Simplex isAdmissible( const Simplex& s, const SimplicialComplex& K )\n{\n if( !isPrincipal(s,K) )\n return Simplex();\n\n \/\/ Check whether a free face exists ----------------------------------\n\n std::vector<Simplex> faces( s.begin_boundary(), s.end_boundary() );\n std::vector<bool> admissible( faces.size(), true );\n\n std::size_t i = 0;\n auto itPair = K.range( s.dimension() ); \/\/ valid range for searches, viz. *all*\n \/\/ faces in \"one dimension up\"\n\n for( auto&& face : faces )\n {\n for( auto it = itPair.first; it != itPair.second; ++it )\n {\n auto&& t = *it;\n\n \/\/ We do not have to check for intersections with the original\n \/\/ simplex from which we started---we already know that we are\n \/\/ a face.\n if( t != s )\n {\n if( sizeOfIntersection(face,t) == face.size() )\n {\n admissible[i] = false;\n break;\n }\n }\n }\n\n ++i;\n }\n\n auto pos = std::find( admissible.begin(), admissible.end(), true );\n if( pos == admissible.end() )\n return Simplex();\n else\n return faces.at( std::distance( admissible.begin(), pos ) );\n}\n\n\/**\n Calculates all principal faces of a given simplicial complex and\n returns them.\n*\/\n\ntemplate <class SimplicialComplex> std::unordered_map<typename SimplicialComplex::value_type, typename SimplicialComplex::value_type> principalFaces( const SimplicialComplex& K )\n{\n using Simplex = typename SimplicialComplex::value_type;\n auto L = K;\n\n std::unordered_map<Simplex, Simplex> admissible;\n\n \/\/ Step 1: determine free faces --------------------------------------\n \/\/\n \/\/ This first checks which simplices have at least one free face,\n \/\/ meaning that they may be potentially admissible.\n\n for( auto it = L.begin(); it != L.end(); ++it )\n {\n if( it->dimension() == 0 )\n continue;\n\n \/\/ The range of the complex M is sufficient because we have\n \/\/ already encountered all lower-dimensional simplices that\n \/\/ precede the current one given by `it`.\n \/\/\n \/\/ This complex will be used for testing free faces.\n SimplicialComplex M( L.begin(), it );\n\n \/\/ FIXME:\n \/\/\n \/\/ In case of equal data values, the assignment from above does\n \/\/ *not* work and will result in incorrect candidates.\n M = L;\n\n bool hasFreeFace = false;\n Simplex freeFace = Simplex();\n\n for( auto itFace = it->begin_boundary(); itFace != it->end_boundary(); ++itFace )\n {\n bool isFace = false;\n for( auto&& simplex : M )\n {\n if( itFace->dimension() + 1 == simplex.dimension() && simplex != *it )\n {\n \/\/ The current face must *not* be a face of another simplex in\n \/\/ the simplicial complex.\n if( intersect( *itFace, simplex ) == *itFace )\n {\n isFace = true;\n break;\n }\n }\n }\n\n hasFreeFace = !isFace;\n if( hasFreeFace )\n {\n freeFace = *itFace;\n break;\n }\n }\n\n if( hasFreeFace )\n admissible.insert( std::make_pair( *it, freeFace ) );\n }\n\n \/\/ Step 2: determine principality ------------------------------------\n \/\/\n \/\/ All simplices that are faces of higher-dimensional simplices are\n \/\/ now removed from the map of admissible simplices.\n\n for( auto&& s : L )\n {\n for( auto itFace = s.begin_boundary(); itFace != s.end_boundary(); ++itFace )\n admissible.erase( *itFace );\n }\n\n return admissible;\n}\n\n\/**\n Performs an iterated elementary simplicial collapse until *all* of the\n admissible simplices have been collapsed. This leads to the *spine* of\n the simplicial complex.\n\n @see S. Matveev, \"Algorithmic Topology and Classification of 3-Manifolds\"\n*\/\n\ntemplate <class SimplicialComplex> SimplicialComplex spine( const SimplicialComplex& K )\n{\n using Simplex = typename SimplicialComplex::value_type;\n auto L = K;\n\n \/\/ Step 1: obtain initial set of principal faces to start the process\n \/\/ of collapsing the complex.\n auto admissible = principalFaces( L );\n\n \/\/ Step 2: collapse until no admissible simplices are left -----------\n\n while( !admissible.empty() )\n {\n auto s = admissible.begin()->first;\n auto t = admissible.begin()->second;\n\n L.remove_without_validation( s );\n L.remove_without_validation( t );\n\n admissible.erase( s );\n\n \/\/ New simplices ---------------------------------------------------\n \/\/\n \/\/ Add new admissible simplices that may potentially have been\n \/\/ spawned by the removal of s.\n\n \/\/ 1. Add all faces of the principal simplex, as they may\n \/\/ potentially become admissible again.\n std::vector<Simplex> faces( s.begin_boundary(), s.end_boundary() );\n\n std::for_each( faces.begin(), faces.end(),\n [&t, &L, &admissible] ( const Simplex& s )\n {\n \/\/ TODO: rename function\n auto face = isAdmissible( s, L );\n\n if( t != s && face )\n admissible.insert( std::make_pair( s, face ) );\n }\n );\n\n \/\/ 2. Add all faces othe free face, as they may now themselves\n \/\/ become admissible.\n faces.assign( t.begin_boundary(), t.end_boundary() );\n\n std::for_each( faces.begin(), faces.end(),\n [&L, &admissible] ( const Simplex& s )\n {\n \/\/ TODO: rename function\n auto face = isAdmissible( s, L );\n\n if( face )\n admissible.insert( std::make_pair( s, face ) );\n }\n );\n\n#if 0\n \/\/ TODO: this check could be simplified by *storing* the free face\n \/\/ along with the given simplex\n for( auto itFace = s.begin_boundary(); itFace != s.end_boundary(); ++itFace )\n {\n auto t = *itFace;\n\n if( isAdmissible( s, t, L ) )\n {\n L.remove_without_validation( s );\n L.remove_without_validation( t );\n\n admissible.erase( s );\n\n \/\/ New simplices -----------------------------------------------\n \/\/\n \/\/ Add new admissible simplices that may potentially have been\n \/\/ spawned by the removal of s.\n\n \/\/ 1. Add all faces of the principal simplex, as they may\n \/\/ potentially become admissible again.\n std::vector<Simplex> faces( s.begin_boundary(), s.end_boundary() );\n\n std::for_each( faces.begin(), faces.end(),\n [&t, &L, &admissible] ( const Simplex& s )\n {\n if( t != s && isAdmissible( s, L ) )\n admissible.insert( s );\n }\n );\n\n \/\/ 2. Add all faces othe free face, as they may now themselves\n \/\/ become admissible.\n faces.assign( t.begin_boundary(), t.end_boundary() );\n\n std::for_each( faces.begin(), faces.end(),\n [&L, &admissible] ( const Simplex& s )\n {\n if( isAdmissible( s, L ) )\n admissible.insert( s );\n }\n );\n\n hasFreeFace = true;\n break;\n }\n }\n\n \/\/ The admissible simplex does not have a free face, so it must not\n \/\/ be used.\n if( !hasFreeFace )\n admissible.erase( s );\n#endif\n\n \/\/ The heuristic above is incapable of detecting *all* principal\n \/\/ faces of the complex because this may involve searching *all*\n \/\/ co-faces. Instead, it is easier to fill up the admissible set\n \/\/ here.\n if( admissible.empty() )\n admissible = principalFaces( L );\n }\n\n return L;\n}\n\n} \/\/ namespace topology\n\n} \/\/ namespace aleph\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2009 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/renderer_host\/render_sandbox_host_linux.h\"\n\n#include <stdint.h>\n#include <unistd.h>\n#include <sys\/uio.h>\n#include <sys\/socket.h>\n#include <sys\/poll.h>\n\n#include \"base\/eintr_wrapper.h\"\n#include \"base\/process_util.h\"\n#include \"base\/logging.h\"\n#include \"base\/message_loop.h\"\n#include \"base\/pickle.h\"\n#include \"base\/string_util.h\"\n#include \"base\/unix_domain_socket_posix.h\"\n#include \"chrome\/common\/sandbox_methods_linux.h\"\n#include \"webkit\/api\/public\/gtk\/WebFontInfo.h\"\n#include \"webkit\/api\/public\/WebData.h\"\n#include \"webkit\/api\/public\/WebKit.h\"\n#include \"webkit\/api\/public\/WebKitClient.h\"\n\n#include \"SkFontHost_fontconfig_direct.h\"\n#include \"SkFontHost_fontconfig_ipc.h\"\n\nusing WebKit::WebClipboard;\nusing WebKit::WebData;\nusing WebKit::WebFontInfo;\nusing WebKit::WebKitClient;\nusing WebKit::WebMimeRegistry;\nusing WebKit::WebPluginInfo;\nusing WebKit::WebPluginListBuilder;\nusing WebKit::WebSandboxSupport;\nusing WebKit::WebString;\nusing WebKit::WebThemeEngine;\nusing WebKit::WebUChar;\nusing WebKit::WebURL;\nusing WebKit::WebURLLoader;\n\n\/\/ http:\/\/code.google.com\/p\/chromium\/wiki\/LinuxSandboxIPC\n\n\/\/ BEWARE: code in this file run across *processes* (not just threads).\n\n\/\/ This code runs in a child process\nclass SandboxIPCProcess : public WebKitClient {\n public:\n \/\/ lifeline_fd: this is the read end of a pipe which the browser process\n \/\/ holds the other end of. If the browser process dies, it's descriptors are\n \/\/ closed and we will noticed an EOF on the pipe. That's our signal to exit.\n \/\/ browser_socket: the 'browser's end of the sandbox IPC socketpair. From the\n \/\/ point of view of the renderer's, it's talking to the browser but this\n \/\/ object actually services the requests.\n SandboxIPCProcess(int lifeline_fd, int browser_socket)\n : lifeline_fd_(lifeline_fd),\n browser_socket_(browser_socket),\n font_config_(new FontConfigDirect()) {\n WebKit::initialize(this);\n\n base::InjectiveMultimap multimap;\n multimap.push_back(base::InjectionArc(0, lifeline_fd, false));\n multimap.push_back(base::InjectionArc(0, browser_socket, false));\n\n base::CloseSuperfluousFds(multimap);\n }\n\n void Run() {\n struct pollfd pfds[2];\n pfds[0].fd = lifeline_fd_;\n pfds[0].events = POLLIN;\n pfds[1].fd = browser_socket_;\n pfds[1].events = POLLIN;\n\n bool failed_polls = 0;\n for (;;) {\n const int r = HANDLE_EINTR(poll(pfds, 2, -1));\n if (r < 1) {\n LOG(WARNING) << \"poll errno:\" << errno;\n if (failed_polls++ == 3) {\n LOG(FATAL) << \"poll failing. Sandbox host aborting.\";\n return;\n }\n continue;\n }\n\n failed_polls = 0;\n\n if (pfds[0].revents) {\n \/\/ our parent died so we should too.\n _exit(0);\n }\n\n if (pfds[1].revents) {\n HandleRequestFromRenderer(browser_socket_);\n }\n }\n }\n\n \/\/ ---------------------------------------------------------------------------\n \/\/ WebKitClient impl...\n\n virtual WebClipboard* clipboard() { return NULL; }\n virtual WebMimeRegistry* mimeRegistry() { return NULL; }\n virtual WebSandboxSupport* sandboxSupport() { return NULL; }\n virtual WebThemeEngine* themeEngine() { return NULL; }\n\n virtual unsigned long long visitedLinkHash(const char*, size_t) { return 0; }\n virtual bool isLinkVisited(unsigned long long) { return false; }\n\n virtual void setCookies(const WebURL&, const WebURL&, const WebString&) { }\n virtual WebString cookies(const WebURL&, const WebURL&) { return WebString(); }\n\n virtual void prefetchHostName(const WebString&) { }\n\n virtual bool getFileSize(const WebString& path, long long& result) {\n return false;\n }\n\n virtual WebURLLoader* createURLLoader() { return NULL; }\n\n virtual void getPluginList(bool refresh, WebPluginListBuilder*) { }\n\n virtual void decrementStatsCounter(const char*) { }\n virtual void incrementStatsCounter(const char*) { }\n\n virtual void traceEventBegin(const char* name, void*, const char*) { }\n virtual void traceEventEnd(const char* name, void*, const char*) { }\n\n virtual WebData loadResource(const char*) { return WebData(); }\n\n virtual void suddenTerminationChanged(bool) { }\n\n virtual WebString defaultLocale() { return WebString(); }\n\n virtual double currentTime() { return 0; }\n\n virtual void setSharedTimerFiredFunction(void (*)()) { }\n virtual void setSharedTimerFireTime(double) { }\n virtual void stopSharedTimer() { }\n\n virtual void callOnMainThread(void (*)()) { }\n\n private:\n \/\/ ---------------------------------------------------------------------------\n \/\/ Requests from the renderer...\n\n void HandleRequestFromRenderer(int fd) {\n std::vector<int> fds;\n static const unsigned kMaxMessageLength = 2048;\n char buf[kMaxMessageLength];\n const ssize_t len = base::RecvMsg(fd, buf, sizeof(buf), &fds);\n if (len == -1)\n return;\n if (fds.size() == 0)\n return;\n\n Pickle pickle(buf, len);\n void* iter = NULL;\n\n int kind;\n if (!pickle.ReadInt(&iter, &kind))\n goto error;\n\n if (kind == FontConfigIPC::METHOD_MATCH) {\n HandleFontMatchRequest(fd, pickle, iter, fds);\n } else if (kind == FontConfigIPC::METHOD_OPEN) {\n HandleFontOpenRequest(fd, pickle, iter, fds);\n } else if (kind == LinuxSandbox::METHOD_GET_FONT_FAMILY_FOR_CHARS) {\n HandleGetFontFamilyForChars(fd, pickle, iter, fds);\n }\n\n error:\n for (std::vector<int>::const_iterator\n i = fds.begin(); i != fds.end(); ++i) {\n close(*i);\n }\n }\n\n void HandleFontMatchRequest(int fd, Pickle& pickle, void* iter,\n std::vector<int>& fds) {\n bool fileid_valid;\n uint32_t fileid;\n bool is_bold, is_italic;\n std::string family;\n\n if (!pickle.ReadBool(&iter, &fileid_valid))\n return;\n if (fileid_valid) {\n if (!pickle.ReadUInt32(&iter, &fileid))\n return;\n }\n if (!pickle.ReadBool(&iter, &is_bold) ||\n !pickle.ReadBool(&iter, &is_italic) ||\n !pickle.ReadString(&iter, &family)) {\n return;\n }\n\n std::string result_family;\n unsigned result_fileid;\n\n const bool r = font_config_->Match(\n &result_family, &result_fileid, fileid_valid, fileid, family, &is_bold,\n &is_italic);\n\n Pickle reply;\n if (!r) {\n reply.WriteBool(false);\n } else {\n reply.WriteBool(true);\n reply.WriteUInt32(result_fileid);\n reply.WriteString(result_family);\n reply.WriteBool(is_bold);\n reply.WriteBool(is_italic);\n }\n SendRendererReply(fds, reply, -1);\n }\n\n void HandleFontOpenRequest(int fd, Pickle& pickle, void* iter,\n std::vector<int>& fds) {\n uint32_t fileid;\n if (!pickle.ReadUInt32(&iter, &fileid))\n return;\n const int result_fd = font_config_->Open(fileid);\n\n Pickle reply;\n if (result_fd == -1) {\n reply.WriteBool(false);\n } else {\n reply.WriteBool(true);\n }\n\n SendRendererReply(fds, reply, result_fd);\n }\n\n void HandleGetFontFamilyForChars(int fd, Pickle& pickle, void* iter,\n std::vector<int>& fds) {\n \/\/ The other side of this call is\n \/\/ chrome\/renderer\/renderer_sandbox_support_linux.cc\n\n int num_chars;\n if (!pickle.ReadInt(&iter, &num_chars))\n return;\n\n \/\/ We don't want a corrupt renderer asking too much of us, it might\n \/\/ overflow later in the code.\n static const int kMaxChars = 4096;\n if (num_chars < 1 || num_chars > kMaxChars) {\n LOG(WARNING) << \"HandleGetFontFamilyForChars: too many chars: \"\n << num_chars;\n return;\n }\n\n scoped_array<WebUChar> chars(new WebUChar[num_chars]);\n\n for (int i = 0; i < num_chars; ++i) {\n uint32_t c;\n if (!pickle.ReadUInt32(&iter, &c)) {\n return;\n }\n\n chars[i] = c;\n }\n\n const WebString family = WebFontInfo::familyForChars(chars.get(), num_chars);\n const std::string family_utf8 = UTF16ToUTF8(family);\n\n Pickle reply;\n reply.WriteString(family_utf8);\n SendRendererReply(fds, reply, -1);\n }\n\n void SendRendererReply(const std::vector<int>& fds, const Pickle& reply,\n int reply_fd) {\n struct msghdr msg;\n memset(&msg, 0, sizeof(msg));\n struct iovec iov = {const_cast<void*>(reply.data()), reply.size()};\n msg.msg_iov = &iov;\n msg.msg_iovlen = 1;\n\n char control_buffer[CMSG_SPACE(sizeof(int))];\n\n if (reply_fd != -1) {\n struct cmsghdr *cmsg;\n\n msg.msg_control = control_buffer;\n msg.msg_controllen = sizeof(control_buffer);\n cmsg = CMSG_FIRSTHDR(&msg);\n cmsg->cmsg_level = SOL_SOCKET;\n cmsg->cmsg_type = SCM_RIGHTS;\n cmsg->cmsg_len = CMSG_LEN(sizeof(int));\n memcpy(CMSG_DATA(cmsg), &reply_fd, sizeof(int));\n msg.msg_controllen = cmsg->cmsg_len;\n }\n\n HANDLE_EINTR(sendmsg(fds[0], &msg, MSG_DONTWAIT));\n }\n\n \/\/ ---------------------------------------------------------------------------\n\n const int lifeline_fd_;\n const int browser_socket_;\n FontConfigDirect* const font_config_;\n};\n\n\/\/ -----------------------------------------------------------------------------\n\n\/\/ Runs on the main thread at startup.\nRenderSandboxHostLinux::RenderSandboxHostLinux() {\n int fds[2];\n CHECK(socketpair(AF_UNIX, SOCK_DGRAM, 0, fds) == 0);\n\n renderer_socket_ = fds[0];\n const int browser_socket = fds[1];\n\n int pipefds[2];\n CHECK(0 == pipe(pipefds));\n const int child_lifeline_fd = pipefds[0];\n childs_lifeline_fd_ = pipefds[1];\n\n const pid_t child = fork();\n if (child == 0) {\n SandboxIPCProcess handler(child_lifeline_fd, browser_socket);\n handler.Run();\n _exit(0);\n }\n}\n\nRenderSandboxHostLinux::~RenderSandboxHostLinux() {\n HANDLE_EINTR(close(renderer_socket_));\n HANDLE_EINTR(close(childs_lifeline_fd_));\n}\n<commit_msg>Linux: don't leak file descriptors in the sandbox host.<commit_after>\/\/ Copyright (c) 2009 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/renderer_host\/render_sandbox_host_linux.h\"\n\n#include <stdint.h>\n#include <unistd.h>\n#include <sys\/uio.h>\n#include <sys\/socket.h>\n#include <sys\/poll.h>\n\n#include \"base\/eintr_wrapper.h\"\n#include \"base\/process_util.h\"\n#include \"base\/logging.h\"\n#include \"base\/message_loop.h\"\n#include \"base\/pickle.h\"\n#include \"base\/string_util.h\"\n#include \"base\/unix_domain_socket_posix.h\"\n#include \"chrome\/common\/sandbox_methods_linux.h\"\n#include \"webkit\/api\/public\/gtk\/WebFontInfo.h\"\n#include \"webkit\/api\/public\/WebData.h\"\n#include \"webkit\/api\/public\/WebKit.h\"\n#include \"webkit\/api\/public\/WebKitClient.h\"\n\n#include \"SkFontHost_fontconfig_direct.h\"\n#include \"SkFontHost_fontconfig_ipc.h\"\n\nusing WebKit::WebClipboard;\nusing WebKit::WebData;\nusing WebKit::WebFontInfo;\nusing WebKit::WebKitClient;\nusing WebKit::WebMimeRegistry;\nusing WebKit::WebPluginInfo;\nusing WebKit::WebPluginListBuilder;\nusing WebKit::WebSandboxSupport;\nusing WebKit::WebString;\nusing WebKit::WebThemeEngine;\nusing WebKit::WebUChar;\nusing WebKit::WebURL;\nusing WebKit::WebURLLoader;\n\n\/\/ http:\/\/code.google.com\/p\/chromium\/wiki\/LinuxSandboxIPC\n\n\/\/ BEWARE: code in this file run across *processes* (not just threads).\n\n\/\/ This code runs in a child process\nclass SandboxIPCProcess : public WebKitClient {\n public:\n \/\/ lifeline_fd: this is the read end of a pipe which the browser process\n \/\/ holds the other end of. If the browser process dies, it's descriptors are\n \/\/ closed and we will noticed an EOF on the pipe. That's our signal to exit.\n \/\/ browser_socket: the 'browser's end of the sandbox IPC socketpair. From the\n \/\/ point of view of the renderer's, it's talking to the browser but this\n \/\/ object actually services the requests.\n SandboxIPCProcess(int lifeline_fd, int browser_socket)\n : lifeline_fd_(lifeline_fd),\n browser_socket_(browser_socket),\n font_config_(new FontConfigDirect()) {\n WebKit::initialize(this);\n\n base::InjectiveMultimap multimap;\n multimap.push_back(base::InjectionArc(0, lifeline_fd, false));\n multimap.push_back(base::InjectionArc(0, browser_socket, false));\n\n base::CloseSuperfluousFds(multimap);\n }\n\n void Run() {\n struct pollfd pfds[2];\n pfds[0].fd = lifeline_fd_;\n pfds[0].events = POLLIN;\n pfds[1].fd = browser_socket_;\n pfds[1].events = POLLIN;\n\n bool failed_polls = 0;\n for (;;) {\n const int r = HANDLE_EINTR(poll(pfds, 2, -1));\n if (r < 1) {\n LOG(WARNING) << \"poll errno:\" << errno;\n if (failed_polls++ == 3) {\n LOG(FATAL) << \"poll failing. Sandbox host aborting.\";\n return;\n }\n continue;\n }\n\n failed_polls = 0;\n\n if (pfds[0].revents) {\n \/\/ our parent died so we should too.\n _exit(0);\n }\n\n if (pfds[1].revents) {\n HandleRequestFromRenderer(browser_socket_);\n }\n }\n }\n\n \/\/ ---------------------------------------------------------------------------\n \/\/ WebKitClient impl...\n\n virtual WebClipboard* clipboard() { return NULL; }\n virtual WebMimeRegistry* mimeRegistry() { return NULL; }\n virtual WebSandboxSupport* sandboxSupport() { return NULL; }\n virtual WebThemeEngine* themeEngine() { return NULL; }\n\n virtual unsigned long long visitedLinkHash(const char*, size_t) { return 0; }\n virtual bool isLinkVisited(unsigned long long) { return false; }\n\n virtual void setCookies(const WebURL&, const WebURL&, const WebString&) { }\n virtual WebString cookies(const WebURL&, const WebURL&) { return WebString(); }\n\n virtual void prefetchHostName(const WebString&) { }\n\n virtual bool getFileSize(const WebString& path, long long& result) {\n return false;\n }\n\n virtual WebURLLoader* createURLLoader() { return NULL; }\n\n virtual void getPluginList(bool refresh, WebPluginListBuilder*) { }\n\n virtual void decrementStatsCounter(const char*) { }\n virtual void incrementStatsCounter(const char*) { }\n\n virtual void traceEventBegin(const char* name, void*, const char*) { }\n virtual void traceEventEnd(const char* name, void*, const char*) { }\n\n virtual WebData loadResource(const char*) { return WebData(); }\n\n virtual void suddenTerminationChanged(bool) { }\n\n virtual WebString defaultLocale() { return WebString(); }\n\n virtual double currentTime() { return 0; }\n\n virtual void setSharedTimerFiredFunction(void (*)()) { }\n virtual void setSharedTimerFireTime(double) { }\n virtual void stopSharedTimer() { }\n\n virtual void callOnMainThread(void (*)()) { }\n\n private:\n \/\/ ---------------------------------------------------------------------------\n \/\/ Requests from the renderer...\n\n void HandleRequestFromRenderer(int fd) {\n std::vector<int> fds;\n static const unsigned kMaxMessageLength = 2048;\n char buf[kMaxMessageLength];\n const ssize_t len = base::RecvMsg(fd, buf, sizeof(buf), &fds);\n if (len == -1)\n return;\n if (fds.size() == 0)\n return;\n\n Pickle pickle(buf, len);\n void* iter = NULL;\n\n int kind;\n if (!pickle.ReadInt(&iter, &kind))\n goto error;\n\n if (kind == FontConfigIPC::METHOD_MATCH) {\n HandleFontMatchRequest(fd, pickle, iter, fds);\n } else if (kind == FontConfigIPC::METHOD_OPEN) {\n HandleFontOpenRequest(fd, pickle, iter, fds);\n } else if (kind == LinuxSandbox::METHOD_GET_FONT_FAMILY_FOR_CHARS) {\n HandleGetFontFamilyForChars(fd, pickle, iter, fds);\n }\n\n error:\n for (std::vector<int>::const_iterator\n i = fds.begin(); i != fds.end(); ++i) {\n close(*i);\n }\n }\n\n void HandleFontMatchRequest(int fd, Pickle& pickle, void* iter,\n std::vector<int>& fds) {\n bool fileid_valid;\n uint32_t fileid;\n bool is_bold, is_italic;\n std::string family;\n\n if (!pickle.ReadBool(&iter, &fileid_valid))\n return;\n if (fileid_valid) {\n if (!pickle.ReadUInt32(&iter, &fileid))\n return;\n }\n if (!pickle.ReadBool(&iter, &is_bold) ||\n !pickle.ReadBool(&iter, &is_italic) ||\n !pickle.ReadString(&iter, &family)) {\n return;\n }\n\n std::string result_family;\n unsigned result_fileid;\n\n const bool r = font_config_->Match(\n &result_family, &result_fileid, fileid_valid, fileid, family, &is_bold,\n &is_italic);\n\n Pickle reply;\n if (!r) {\n reply.WriteBool(false);\n } else {\n reply.WriteBool(true);\n reply.WriteUInt32(result_fileid);\n reply.WriteString(result_family);\n reply.WriteBool(is_bold);\n reply.WriteBool(is_italic);\n }\n SendRendererReply(fds, reply, -1);\n }\n\n void HandleFontOpenRequest(int fd, Pickle& pickle, void* iter,\n std::vector<int>& fds) {\n uint32_t fileid;\n if (!pickle.ReadUInt32(&iter, &fileid))\n return;\n const int result_fd = font_config_->Open(fileid);\n\n Pickle reply;\n if (result_fd == -1) {\n reply.WriteBool(false);\n } else {\n reply.WriteBool(true);\n }\n\n SendRendererReply(fds, reply, result_fd);\n\n if (result_fd >= 0)\n close(result_fd);\n }\n\n void HandleGetFontFamilyForChars(int fd, Pickle& pickle, void* iter,\n std::vector<int>& fds) {\n \/\/ The other side of this call is\n \/\/ chrome\/renderer\/renderer_sandbox_support_linux.cc\n\n int num_chars;\n if (!pickle.ReadInt(&iter, &num_chars))\n return;\n\n \/\/ We don't want a corrupt renderer asking too much of us, it might\n \/\/ overflow later in the code.\n static const int kMaxChars = 4096;\n if (num_chars < 1 || num_chars > kMaxChars) {\n LOG(WARNING) << \"HandleGetFontFamilyForChars: too many chars: \"\n << num_chars;\n return;\n }\n\n scoped_array<WebUChar> chars(new WebUChar[num_chars]);\n\n for (int i = 0; i < num_chars; ++i) {\n uint32_t c;\n if (!pickle.ReadUInt32(&iter, &c)) {\n return;\n }\n\n chars[i] = c;\n }\n\n const WebString family = WebFontInfo::familyForChars(chars.get(), num_chars);\n const std::string family_utf8 = UTF16ToUTF8(family);\n\n Pickle reply;\n reply.WriteString(family_utf8);\n SendRendererReply(fds, reply, -1);\n }\n\n void SendRendererReply(const std::vector<int>& fds, const Pickle& reply,\n int reply_fd) {\n struct msghdr msg;\n memset(&msg, 0, sizeof(msg));\n struct iovec iov = {const_cast<void*>(reply.data()), reply.size()};\n msg.msg_iov = &iov;\n msg.msg_iovlen = 1;\n\n char control_buffer[CMSG_SPACE(sizeof(int))];\n\n if (reply_fd != -1) {\n struct cmsghdr *cmsg;\n\n msg.msg_control = control_buffer;\n msg.msg_controllen = sizeof(control_buffer);\n cmsg = CMSG_FIRSTHDR(&msg);\n cmsg->cmsg_level = SOL_SOCKET;\n cmsg->cmsg_type = SCM_RIGHTS;\n cmsg->cmsg_len = CMSG_LEN(sizeof(int));\n memcpy(CMSG_DATA(cmsg), &reply_fd, sizeof(int));\n msg.msg_controllen = cmsg->cmsg_len;\n }\n\n HANDLE_EINTR(sendmsg(fds[0], &msg, MSG_DONTWAIT));\n }\n\n \/\/ ---------------------------------------------------------------------------\n\n const int lifeline_fd_;\n const int browser_socket_;\n FontConfigDirect* const font_config_;\n};\n\n\/\/ -----------------------------------------------------------------------------\n\n\/\/ Runs on the main thread at startup.\nRenderSandboxHostLinux::RenderSandboxHostLinux() {\n int fds[2];\n CHECK(socketpair(AF_UNIX, SOCK_DGRAM, 0, fds) == 0);\n\n renderer_socket_ = fds[0];\n const int browser_socket = fds[1];\n\n int pipefds[2];\n CHECK(0 == pipe(pipefds));\n const int child_lifeline_fd = pipefds[0];\n childs_lifeline_fd_ = pipefds[1];\n\n const pid_t child = fork();\n if (child == 0) {\n SandboxIPCProcess handler(child_lifeline_fd, browser_socket);\n handler.Run();\n _exit(0);\n }\n}\n\nRenderSandboxHostLinux::~RenderSandboxHostLinux() {\n HANDLE_EINTR(close(renderer_socket_));\n HANDLE_EINTR(close(childs_lifeline_fd_));\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"disassembler.h\"\n#include \"util.h\"\n#include \"symtab.h\"\n\n#include <vector>\n#include <cctype>\n\nusing namespace std;\n\nenum ByteTypeGuess {\n\tUNINITIALIZED,\n\tUNKNOWN,\n\tCHAR_DATA,\n\tUNINITIALIZED_CHAR_DATA,\n\tWORD_DATA,\n\tUNINITIALIZED_WORD_DATA,\n\tCODE,\n};\n\nstruct program {\n\tByteTypeGuess byte_type_guess[65536];\n\tchar memory[65536];\n\tbool is_labelled[65536];\n\n\tstring name;\n\tstring starting_address;\n\tint length_of_program;\n\tstring first_executable_instruction;\n\tprogram() {\n\t\tfor ( int i = 0 ; i < 65536 ; i++ ) {\n\t\t\tbyte_type_guess[i] = UNINITIALIZED;\n\t\t\tmemory[i] = 0;\n\t\t\tis_labelled[i] = false;\n\t\t}\n\t\tname = \"\";\n\t\tstarting_address = \"\";\n\t\tlength_of_program = 0;\n\t\tfirst_executable_instruction = \"\";\n\t}\n};\n\nbool read_record(ifstream &ifile, string &record);\nvoid record_to_memory(const string record, program &p);\nvoid analyze_code_data(program &p);\nvoid write_assembly(const program &p, ofstream &ofile);\n\nbool disassemble(ifstream &ifile, ofstream &ofile) {\n\tstring record;\n\tprogram p;\n\twhile ( read_record(ifile, record) ) {\n\t\trecord_to_memory(record, p);\n\t}\n\tstatus(\"Done reading records\");\n\tanalyze_code_data(p);\n\tstatus(\"Done analyzing program for code and data\");\n\twrite_assembly(p, ofile);\n\tstatus(\"Done writing output file\");\n\treturn true;\n}\n\nstring read_columns(ifstream &ifile, int col_begin, int col_end, char record_type = 'a') { \/\/ inclusive of both\n\tstring ret;\n\tchar t;\n\tfor ( int col = col_begin ; col <= col_end ; col++ ) {\n\t\tt = ifile.get();\n\t\tif ( t == EOF || t == '\\n' ) {\n\t\t\tstring errstr;\n\t\t\terrstr += \"Unexpected end of \";\n\t\t\terrstr += record_type;\n\t\t\terrstr += \" record\";\n\t\t\tfatal(errstr);\n\t\t}\n\t\tret += t;\n\t}\n\treturn ret;\n}\n\nstring read_hex_columns(ifstream &ifile, int col_begin, int col_end, char record_type = 'a') { \/\/ inclusive of both\n\tstring ret;\n\tret = read_columns(ifile,col_begin,col_end,record_type);\n\tmake_upper_case(ret);\n\tif ( !is_hex_string(ret) ) {\n\t\tstring errstr;\n\t\terrstr += \"Unexpected non-hexadecimal character found in \";\n\t\terrstr += record_type;\n\t\terrstr += \" record\";\n\t\tfatal(errstr);\n\t}\n\treturn ret;\n}\n\nbool read_record(ifstream &ifile, string &record) {\n\tint temp_int;\n\tstring temp_str;\n\tchar t;\n\n\tdo {\n\t\tt = ifile.get();\n\t\tif ( t == EOF ) {\n\t\t\treturn false;\n\t\t}\n\t} while ( t == '\\n' || t == ' ' );\n\trecord = \"\";\n\trecord += t;\n\n\tswitch (t) {\n\t\tcase 'H': \/\/ Header\n\t\t\trecord += read_columns(ifile,2,7,'H');\n\t\t\trecord += read_hex_columns(ifile,8,19,'H');\n\t\t\tbreak;\n\t\tcase 'T': \/\/ Text\n\t\t\trecord += read_hex_columns(ifile,2,7,'T');\n\t\t\ttemp_str = read_hex_columns(ifile,8,9,'T');\n\t\t\ttemp_int = hex2int(temp_str);\n\t\t\trecord += temp_str;\n\t\t\trecord += read_hex_columns(ifile,10,9+2*temp_int,'T');\n\t\t\tbreak;\n\t\tcase 'E': \/\/ End\n\t\t\trecord += read_hex_columns(ifile,2,7,'E');\n\t\t\tbreak;\n\t\tdefault:\n\t\t\t{\n\t\t\t\tstring errstr = \"Unknown record type \";\n\t\t\t\terrstr += t;\n\t\t\t\tfatal(errstr);\n\t\t\t}\n\t}\n\treturn true;\n}\n\nvoid record_to_memory(const string record, program &p) {\n\tconst char * c_record = record.c_str();\n\tswitch (*c_record) {\n\t\tcase 'H': \/\/ Header\n\t\t\tif ( p.name.length() != 0 ) {\n\t\t\t\tfatal(\"Multiple H records\");\n\t\t\t}\n\t\t\tp.name = record.substr(1,6);\n\t\t\tp.starting_address = record.substr(7,6);\n\t\t\tp.length_of_program = hex2int(record.substr(13,6));\n\t\t\tbreak;\n\t\tcase 'T': \/\/ Text\n\t\t\t{\n\t\t\t\tint text_start = hex2int(record.substr(1,6));\n\t\t\t\tint bit_length = hex2int(record.substr(7,2));\n\t\t\t\tfor ( int i = 0 ; i < bit_length ; i++ ) {\n\t\t\t\t\tp.memory[i+text_start] = hex2int(record.substr(9+2*i,2));\n\t\t\t\t\tp.byte_type_guess[i+text_start] = UNKNOWN;\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak;\n\t\tcase 'E': \/\/ End\n\t\t\tif ( p.first_executable_instruction.length() != 0 ) {\n\t\t\t\tfatal(\"Multiple E records\");\n\t\t\t}\n\t\t\tp.first_executable_instruction = record.substr(1,6);\n\t\t\tbreak;\n\t\tdefault:\n\t\t\t{\n\t\t\t\tstring errstr;\n\t\t\t\terrstr += \"Unknown record type \";\n\t\t\t\terrstr += *c_record;\n\t\t\t\tfatal(errstr);\n\t\t\t}\n\t}\n}\n\nvoid mark_code_data(program &p, int location, ByteTypeGuess btg) {\n\tif ( location >= hex2int(p.starting_address) + p.length_of_program ) {\n\t\treturn;\n\t}\n\tswitch (btg) {\n\t\tcase UNINITIALIZED:\n\t\tcase UNKNOWN:\n\t\t\tbreak;\n\t\tcase CHAR_DATA:\n\t\tcase UNINITIALIZED_CHAR_DATA:\n\t\t\t{\n\t\t\t\tif ( p.byte_type_guess[location] != UNKNOWN &&\n\t\t\t\t\t p.byte_type_guess[location] != UNINITIALIZED ) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tif ( p.byte_type_guess[location] == UNINITIALIZED )\n\t\t\t\t\tbtg = UNINITIALIZED_CHAR_DATA;\n\t\t\t\tp.byte_type_guess[location] = btg;\n\t\t\t\tbreak;\n\t\t\t}\n\t\tcase WORD_DATA:\n\t\tcase UNINITIALIZED_WORD_DATA:\n\t\t\t{\n\t\t\t\tif ( p.byte_type_guess[location] != UNKNOWN &&\n\t\t\t\t\t p.byte_type_guess[location] != UNINITIALIZED ) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tif ( p.byte_type_guess[location] == UNINITIALIZED )\n\t\t\t\t\tbtg = UNINITIALIZED_WORD_DATA;\n\t\t\t\tp.byte_type_guess[location+0] = btg;\n\t\t\t\tp.byte_type_guess[location+1] = btg;\n\t\t\t\tp.byte_type_guess[location+2] = btg;\n\t\t\t\tbreak;\n\t\t\t}\n\t\tcase CODE:\n\t\t\t{\n\t\t\t\tif ( p.byte_type_guess[location] == UNINITIALIZED ) {\n\t\t\t\t\tfatal(\"Attempting to use uninitialized section as code\");\n\t\t\t\t}\n\t\t\t\tif ( p.byte_type_guess[location] == CODE ) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tp.byte_type_guess[location+0] = btg;\n\t\t\t\tp.byte_type_guess[location+1] = btg;\n\t\t\t\tp.byte_type_guess[location+2] = btg;\n\n\t\t\t\tstring opcode_val = byte2hex(p.memory[location]);\n\t\t\t\tstring opcode;\n\t\t\t\tstring operand = byte2hex(p.memory[location+1])+byte2hex(p.memory[location+2]);\n\t\t\t\toperand = int2hex(hex2int(operand)&0x7FFF); \/\/ remove index flag\n\t\t\t\tif ( ! find_from_symtab(opcode,opcode_val) ) {\n\t\t\t\t\tstring errstr;\n\t\t\t\t\terrstr += \"Unknown opcode \";\n\t\t\t\t\terrstr += opcode_val;\n\t\t\t\t\terrstr += \" at location \";\n\t\t\t\t\terrstr += int2hex(location);\n\t\t\t\t\tfatal(errstr);\n\t\t\t\t}\n\n\t\t\t\tif ( opcode == \"ADD\" ||\n\t\t\t\t\t opcode == \"AND\" ||\n\t\t\t\t\t opcode == \"COMP\" ||\n\t\t\t\t\t opcode == \"DIV\" ||\n\t\t\t\t\t opcode == \"LDA\" ||\n\t\t\t\t\t opcode == \"LDL\" ||\n\t\t\t\t\t opcode == \"LDX\" ||\n\t\t\t\t\t opcode == \"MUL\" ||\n\t\t\t\t\t opcode == \"OR\" ||\n\t\t\t\t\t opcode == \"STA\" ||\n\t\t\t\t\t opcode == \"STL\" ||\n\t\t\t\t\t opcode == \"STX\" ||\n\t\t\t\t\t opcode == \"SUB\" ||\n\t\t\t\t\t opcode == \"TIX\" ) {\n\t\t\t\t\tgive_label(operand);\n\t\t\t\t\tp.is_labelled[hex2int(operand)] = true;\n\t\t\t\t\tmark_code_data(p,hex2int(operand),WORD_DATA);\n\t\t\t\t}\n\n\t\t\t\tif ( opcode == \"LDCH\" ||\n\t\t\t\t\t opcode == \"STCH\" ) {\n\t\t\t\t\tgive_label(operand);\n\t\t\t\t\tp.is_labelled[hex2int(operand)] = true;\n\t\t\t\t\tmark_code_data(p,hex2int(operand),CHAR_DATA);\n\t\t\t\t}\n\n\t\t\t\tif ( opcode == \"J\" ||\n\t\t\t\t\t opcode == \"JEQ\" ||\n\t\t\t\t\t opcode == \"JGT\" ||\n\t\t\t\t\t opcode == \"JLT\" ||\n\t\t\t\t\t opcode == \"JSUB\" ||\n\t\t\t\t\t opcode == \"RSUB\" ) {\n\t\t\t\t\tgive_label(operand);\n\t\t\t\t\tp.is_labelled[hex2int(operand)] = true;\n\t\t\t\t\tmark_code_data(p,hex2int(operand),CODE);\n\t\t\t\t}\n\n\t\t\t\tif ( opcode != \"J\" &&\n\t\t\t\t\t opcode != \"RSUB\" ) {\n\t\t\t\t\tmark_code_data(p,location+3,btg);\n\t\t\t\t}\n\n\t\t\t\tbreak;\n\t\t\t}\n\t}\n}\n\nvoid analyze_code_data(program &p) {\n\tif ( p.name.length() == 0 ) {\n\t\tfatal(\"No Header record\");\n\t}\n\tif ( p.first_executable_instruction.length() == 0 ) {\n\t\tfatal(\"No End record\");\n\t}\n\tinitialize_symtab();\n\tadd_to_symtab(\"FIRST\",p.first_executable_instruction);\n\tp.is_labelled[hex2int(p.first_executable_instruction)] = true;\n\tmark_code_data(p,hex2int(p.first_executable_instruction),CODE);\n}\n\nstring asm_to_line(string label, string opcode, string operand, bool is_indexed) {\n\tconst int labellength = 8;\n\tconst int opcodelength = 6;\n\tstring ret = \"\";\n\tret += label + string(labellength-label.length(),' ');\n\tret += opcode + string(opcodelength-opcode.length(),' ');\n\tret += operand;\n\tif ( is_indexed ) {\n\t\tret += \",X\";\n\t}\n\tret += '\\n';\n\treturn ret;\n}\n\nvoid write_assembly(const program &p, ofstream &ofile) {\n\tofile << asm_to_line(p.name,\"START\",p.starting_address,false);\n\tint start_of_program = hex2int(p.starting_address);\n\tint end_of_program = start_of_program + p.length_of_program;\n\tfor ( int locctr = start_of_program ; locctr < end_of_program ; ) {\n\t\tif ( p.byte_type_guess[locctr] == CODE ) {\n\t\t\tstring opcode;\n\t\t\tif ( ! find_from_symtab(opcode,byte2hex(p.memory[locctr])) ) {\n\t\t\t\tstring errstr;\n\t\t\t\terrstr += \"Unknown opcode \";\n\t\t\t\terrstr += opcode;\n\t\t\t\terrstr += \" at location \";\n\t\t\t\terrstr += int2hex(locctr);\n\t\t\t\tfatal(errstr);\n\t\t\t}\n\t\t\tstring operand = byte2hex(p.memory[locctr+1])+byte2hex(p.memory[locctr+2]);\n\t\t\tbool is_indexed = (hex2int(operand)&0x8000);\n\t\t\toperand = int2hex(hex2int(operand)&0x7FFF); \/\/ remove index flag\n\n\t\t\tif ( opcode != \"RD\" &&\n\t\t\t\t opcode != \"TD\" &&\n\t\t\t\t opcode != \"WD\" &&\n\t\t\t\t opcode != \"RSUB\" ) {\n\t\t\t\tif ( !find_from_symtab(operand,operand) ) {\n\t\t\t\t\tstring errstr;\n\t\t\t\t\terrstr += \"Label not created for operand \";\n\t\t\t\t\terrstr += operand;\n\t\t\t\t\terror(errstr);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif ( opcode == \"RSUB\" ) {\n\t\t\t\toperand = \"\";\n\t\t\t}\n\n\t\t\tstring label = \"\";\n\t\t\tif ( p.is_labelled[locctr] ) {\n\t\t\t\tif ( !find_from_symtab(label,int2hex(locctr)) ) {\n\t\t\t\t\tstring errstr;\n\t\t\t\t\terrstr += \"Label not created for location \";\n\t\t\t\t\terrstr += int2hex(locctr);\n\t\t\t\t\terror(errstr);\n\t\t\t\t}\n\t\t\t} \/\/ TODO: Refactor to prevent rewrite of code\n\n\t\t\tofile << asm_to_line(label,opcode,operand,is_indexed);\n\n\t\t\tlocctr += 3;\n\t\t} else if ( p.byte_type_guess[locctr] == CHAR_DATA ) {\n\t\t\tstring label;\n\t\t\tif ( p.is_labelled[locctr] ) {\n\t\t\t\tif ( !find_from_symtab(label,int2hex(locctr)) ) {\n\t\t\t\t\tstring errstr;\n\t\t\t\t\terrstr += \"Label not created for location \";\n\t\t\t\t\terrstr += int2hex(locctr);\n\t\t\t\t\terror(errstr);\n\t\t\t\t}\n\t\t\t} \/\/ TODO: Refactor to prevent rewrite of code\n\n\t\t\tvector<char> byte_list;\n\t\t\tbool type_c = true;\n\t\t\tdo {\n\t\t\t\tbyte_list.push_back(p.memory[locctr]);\n\t\t\t\tif ( !isprint(p.memory[locctr]) ) {\n\t\t\t\t\ttype_c = false;\n\t\t\t\t}\n\t\t\t\tlocctr++;\n\t\t\t} while ( p.byte_type_guess[locctr] == CHAR_DATA && !p.is_labelled[locctr] );\n\n\t\t\tstring opcode = \"CHAR\";\n\t\t\tbool is_indexed = false;\n\t\t\tstring operand = \"\";\n\n\t\t\toperand += (type_c?\"C\":\"X\");\n\t\t\toperand += \"'\";\n\t\t\tfor ( int i = 0 ; i < (int)byte_list.size() ; i++ ) {\n\t\t\t\tif ( type_c ) {\n\t\t\t\t\toperand += byte_list[i];\n\t\t\t\t} else {\n\t\t\t\t\toperand += byte2hex(byte_list[i]);\n\t\t\t\t}\n\t\t\t}\n\t\t\toperand += \"'\";\n\n\t\t\tofile << asm_to_line(label,opcode,operand,is_indexed); \/\/ TODO: Refactor\n\t\t} else {\n\t\t\t\/\/ TODO\n\t\t\tlocctr++; \/\/ temporarily\n\t\t}\n\t}\n\tofile << asm_to_line(\"\",\"END\",\"FIRST\",false);\n}<commit_msg>Refactor<commit_after>#include \"disassembler.h\"\n#include \"util.h\"\n#include \"symtab.h\"\n\n#include <vector>\n#include <cctype>\n\nusing namespace std;\n\nenum ByteTypeGuess {\n\tUNINITIALIZED,\n\tUNKNOWN,\n\tCHAR_DATA,\n\tUNINITIALIZED_CHAR_DATA,\n\tWORD_DATA,\n\tUNINITIALIZED_WORD_DATA,\n\tCODE,\n};\n\nstruct program {\n\tByteTypeGuess byte_type_guess[65536];\n\tchar memory[65536];\n\tbool is_labelled[65536];\n\n\tstring name;\n\tstring starting_address;\n\tint length_of_program;\n\tstring first_executable_instruction;\n\tprogram() {\n\t\tfor ( int i = 0 ; i < 65536 ; i++ ) {\n\t\t\tbyte_type_guess[i] = UNINITIALIZED;\n\t\t\tmemory[i] = 0;\n\t\t\tis_labelled[i] = false;\n\t\t}\n\t\tname = \"\";\n\t\tstarting_address = \"\";\n\t\tlength_of_program = 0;\n\t\tfirst_executable_instruction = \"\";\n\t}\n};\n\nbool read_record(ifstream &ifile, string &record);\nvoid record_to_memory(const string record, program &p);\nvoid analyze_code_data(program &p);\nvoid write_assembly(const program &p, ofstream &ofile);\n\nbool disassemble(ifstream &ifile, ofstream &ofile) {\n\tstring record;\n\tprogram p;\n\twhile ( read_record(ifile, record) ) {\n\t\trecord_to_memory(record, p);\n\t}\n\tstatus(\"Done reading records\");\n\tanalyze_code_data(p);\n\tstatus(\"Done analyzing program for code and data\");\n\twrite_assembly(p, ofile);\n\tstatus(\"Done writing output file\");\n\treturn true;\n}\n\nstring read_columns(ifstream &ifile, int col_begin, int col_end, char record_type = 'a') { \/\/ inclusive of both\n\tstring ret;\n\tchar t;\n\tfor ( int col = col_begin ; col <= col_end ; col++ ) {\n\t\tt = ifile.get();\n\t\tif ( t == EOF || t == '\\n' ) {\n\t\t\tstring errstr;\n\t\t\terrstr += \"Unexpected end of \";\n\t\t\terrstr += record_type;\n\t\t\terrstr += \" record\";\n\t\t\tfatal(errstr);\n\t\t}\n\t\tret += t;\n\t}\n\treturn ret;\n}\n\nstring read_hex_columns(ifstream &ifile, int col_begin, int col_end, char record_type = 'a') { \/\/ inclusive of both\n\tstring ret;\n\tret = read_columns(ifile,col_begin,col_end,record_type);\n\tmake_upper_case(ret);\n\tif ( !is_hex_string(ret) ) {\n\t\tstring errstr;\n\t\terrstr += \"Unexpected non-hexadecimal character found in \";\n\t\terrstr += record_type;\n\t\terrstr += \" record\";\n\t\tfatal(errstr);\n\t}\n\treturn ret;\n}\n\nbool read_record(ifstream &ifile, string &record) {\n\tint temp_int;\n\tstring temp_str;\n\tchar t;\n\n\tdo {\n\t\tt = ifile.get();\n\t\tif ( t == EOF ) {\n\t\t\treturn false;\n\t\t}\n\t} while ( t == '\\n' || t == ' ' );\n\trecord = \"\";\n\trecord += t;\n\n\tswitch (t) {\n\t\tcase 'H': \/\/ Header\n\t\t\trecord += read_columns(ifile,2,7,'H');\n\t\t\trecord += read_hex_columns(ifile,8,19,'H');\n\t\t\tbreak;\n\t\tcase 'T': \/\/ Text\n\t\t\trecord += read_hex_columns(ifile,2,7,'T');\n\t\t\ttemp_str = read_hex_columns(ifile,8,9,'T');\n\t\t\ttemp_int = hex2int(temp_str);\n\t\t\trecord += temp_str;\n\t\t\trecord += read_hex_columns(ifile,10,9+2*temp_int,'T');\n\t\t\tbreak;\n\t\tcase 'E': \/\/ End\n\t\t\trecord += read_hex_columns(ifile,2,7,'E');\n\t\t\tbreak;\n\t\tdefault:\n\t\t\t{\n\t\t\t\tstring errstr = \"Unknown record type \";\n\t\t\t\terrstr += t;\n\t\t\t\tfatal(errstr);\n\t\t\t}\n\t}\n\treturn true;\n}\n\nvoid record_to_memory(const string record, program &p) {\n\tconst char * c_record = record.c_str();\n\tswitch (*c_record) {\n\t\tcase 'H': \/\/ Header\n\t\t\tif ( p.name.length() != 0 ) {\n\t\t\t\tfatal(\"Multiple H records\");\n\t\t\t}\n\t\t\tp.name = record.substr(1,6);\n\t\t\tp.starting_address = record.substr(7,6);\n\t\t\tp.length_of_program = hex2int(record.substr(13,6));\n\t\t\tbreak;\n\t\tcase 'T': \/\/ Text\n\t\t\t{\n\t\t\t\tint text_start = hex2int(record.substr(1,6));\n\t\t\t\tint bit_length = hex2int(record.substr(7,2));\n\t\t\t\tfor ( int i = 0 ; i < bit_length ; i++ ) {\n\t\t\t\t\tp.memory[i+text_start] = hex2int(record.substr(9+2*i,2));\n\t\t\t\t\tp.byte_type_guess[i+text_start] = UNKNOWN;\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak;\n\t\tcase 'E': \/\/ End\n\t\t\tif ( p.first_executable_instruction.length() != 0 ) {\n\t\t\t\tfatal(\"Multiple E records\");\n\t\t\t}\n\t\t\tp.first_executable_instruction = record.substr(1,6);\n\t\t\tbreak;\n\t\tdefault:\n\t\t\t{\n\t\t\t\tstring errstr;\n\t\t\t\terrstr += \"Unknown record type \";\n\t\t\t\terrstr += *c_record;\n\t\t\t\tfatal(errstr);\n\t\t\t}\n\t}\n}\n\nvoid mark_code_data(program &p, int location, ByteTypeGuess btg) {\n\tif ( location >= hex2int(p.starting_address) + p.length_of_program ) {\n\t\treturn;\n\t}\n\tswitch (btg) {\n\t\tcase UNINITIALIZED:\n\t\tcase UNKNOWN:\n\t\t\tbreak;\n\t\tcase CHAR_DATA:\n\t\tcase UNINITIALIZED_CHAR_DATA:\n\t\t\t{\n\t\t\t\tif ( p.byte_type_guess[location] != UNKNOWN &&\n\t\t\t\t\t p.byte_type_guess[location] != UNINITIALIZED ) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tif ( p.byte_type_guess[location] == UNINITIALIZED )\n\t\t\t\t\tbtg = UNINITIALIZED_CHAR_DATA;\n\t\t\t\tp.byte_type_guess[location] = btg;\n\t\t\t\tbreak;\n\t\t\t}\n\t\tcase WORD_DATA:\n\t\tcase UNINITIALIZED_WORD_DATA:\n\t\t\t{\n\t\t\t\tif ( p.byte_type_guess[location] != UNKNOWN &&\n\t\t\t\t\t p.byte_type_guess[location] != UNINITIALIZED ) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tif ( p.byte_type_guess[location] == UNINITIALIZED )\n\t\t\t\t\tbtg = UNINITIALIZED_WORD_DATA;\n\t\t\t\tp.byte_type_guess[location+0] = btg;\n\t\t\t\tp.byte_type_guess[location+1] = btg;\n\t\t\t\tp.byte_type_guess[location+2] = btg;\n\t\t\t\tbreak;\n\t\t\t}\n\t\tcase CODE:\n\t\t\t{\n\t\t\t\tif ( p.byte_type_guess[location] == UNINITIALIZED ) {\n\t\t\t\t\tfatal(\"Attempting to use uninitialized section as code\");\n\t\t\t\t}\n\t\t\t\tif ( p.byte_type_guess[location] == CODE ) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tp.byte_type_guess[location+0] = btg;\n\t\t\t\tp.byte_type_guess[location+1] = btg;\n\t\t\t\tp.byte_type_guess[location+2] = btg;\n\n\t\t\t\tstring opcode_val = byte2hex(p.memory[location]);\n\t\t\t\tstring opcode;\n\t\t\t\tstring operand = byte2hex(p.memory[location+1])+byte2hex(p.memory[location+2]);\n\t\t\t\toperand = int2hex(hex2int(operand)&0x7FFF); \/\/ remove index flag\n\t\t\t\tif ( ! find_from_symtab(opcode,opcode_val) ) {\n\t\t\t\t\tstring errstr;\n\t\t\t\t\terrstr += \"Unknown opcode \";\n\t\t\t\t\terrstr += opcode_val;\n\t\t\t\t\terrstr += \" at location \";\n\t\t\t\t\terrstr += int2hex(location);\n\t\t\t\t\tfatal(errstr);\n\t\t\t\t}\n\n\t\t\t\tif ( opcode == \"ADD\" ||\n\t\t\t\t\t opcode == \"AND\" ||\n\t\t\t\t\t opcode == \"COMP\" ||\n\t\t\t\t\t opcode == \"DIV\" ||\n\t\t\t\t\t opcode == \"LDA\" ||\n\t\t\t\t\t opcode == \"LDL\" ||\n\t\t\t\t\t opcode == \"LDX\" ||\n\t\t\t\t\t opcode == \"MUL\" ||\n\t\t\t\t\t opcode == \"OR\" ||\n\t\t\t\t\t opcode == \"STA\" ||\n\t\t\t\t\t opcode == \"STL\" ||\n\t\t\t\t\t opcode == \"STX\" ||\n\t\t\t\t\t opcode == \"SUB\" ||\n\t\t\t\t\t opcode == \"TIX\" ) {\n\t\t\t\t\tgive_label(operand);\n\t\t\t\t\tp.is_labelled[hex2int(operand)] = true;\n\t\t\t\t\tmark_code_data(p,hex2int(operand),WORD_DATA);\n\t\t\t\t}\n\n\t\t\t\tif ( opcode == \"LDCH\" ||\n\t\t\t\t\t opcode == \"STCH\" ) {\n\t\t\t\t\tgive_label(operand);\n\t\t\t\t\tp.is_labelled[hex2int(operand)] = true;\n\t\t\t\t\tmark_code_data(p,hex2int(operand),CHAR_DATA);\n\t\t\t\t}\n\n\t\t\t\tif ( opcode == \"J\" ||\n\t\t\t\t\t opcode == \"JEQ\" ||\n\t\t\t\t\t opcode == \"JGT\" ||\n\t\t\t\t\t opcode == \"JLT\" ||\n\t\t\t\t\t opcode == \"JSUB\" ||\n\t\t\t\t\t opcode == \"RSUB\" ) {\n\t\t\t\t\tgive_label(operand);\n\t\t\t\t\tp.is_labelled[hex2int(operand)] = true;\n\t\t\t\t\tmark_code_data(p,hex2int(operand),CODE);\n\t\t\t\t}\n\n\t\t\t\tif ( opcode != \"J\" &&\n\t\t\t\t\t opcode != \"RSUB\" ) {\n\t\t\t\t\tmark_code_data(p,location+3,btg);\n\t\t\t\t}\n\n\t\t\t\tbreak;\n\t\t\t}\n\t}\n}\n\nvoid analyze_code_data(program &p) {\n\tif ( p.name.length() == 0 ) {\n\t\tfatal(\"No Header record\");\n\t}\n\tif ( p.first_executable_instruction.length() == 0 ) {\n\t\tfatal(\"No End record\");\n\t}\n\tinitialize_symtab();\n\tadd_to_symtab(\"FIRST\",p.first_executable_instruction);\n\tp.is_labelled[hex2int(p.first_executable_instruction)] = true;\n\tmark_code_data(p,hex2int(p.first_executable_instruction),CODE);\n}\n\nstring asm_to_line(string label, string opcode, string operand, bool is_indexed) {\n\tconst int labellength = 8;\n\tconst int opcodelength = 6;\n\tstring ret = \"\";\n\tret += label + string(labellength-label.length(),' ');\n\tret += opcode + string(opcodelength-opcode.length(),' ');\n\tret += operand;\n\tif ( is_indexed ) {\n\t\tret += \",X\";\n\t}\n\tret += '\\n';\n\treturn ret;\n}\n\nvoid write_assembly(const program &p, ofstream &ofile) {\n\tofile << asm_to_line(p.name,\"START\",p.starting_address,false);\n\tint start_of_program = hex2int(p.starting_address);\n\tint end_of_program = start_of_program + p.length_of_program;\n\n\tfor ( int locctr = start_of_program ; locctr < end_of_program ; ) {\n\t\tstring label = \"\";\n\t\tstring opcode = \"\";\n\t\tstring operand = \"\";\n\t\tbool is_indexed = false;\n\n\t\tif ( p.byte_type_guess[locctr] == CODE ) {\n\t\t\tif ( ! find_from_symtab(opcode,byte2hex(p.memory[locctr])) ) {\n\t\t\t\tstring errstr;\n\t\t\t\terrstr += \"Unknown opcode \";\n\t\t\t\terrstr += opcode;\n\t\t\t\terrstr += \" at location \";\n\t\t\t\terrstr += int2hex(locctr);\n\t\t\t\tfatal(errstr);\n\t\t\t}\n\t\t\toperand = byte2hex(p.memory[locctr+1])+byte2hex(p.memory[locctr+2]);\n\t\t\tis_indexed = (hex2int(operand)&0x8000);\n\t\t\toperand = int2hex(hex2int(operand)&0x7FFF); \/\/ remove index flag\n\n\t\t\tif ( opcode != \"RD\" &&\n\t\t\t\t opcode != \"TD\" &&\n\t\t\t\t opcode != \"WD\" &&\n\t\t\t\t opcode != \"RSUB\" ) {\n\t\t\t\tif ( !find_from_symtab(operand,operand) ) {\n\t\t\t\t\tstring errstr;\n\t\t\t\t\terrstr += \"Label not created for operand \";\n\t\t\t\t\terrstr += operand;\n\t\t\t\t\terror(errstr);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif ( opcode == \"RSUB\" ) {\n\t\t\t\toperand = \"\";\n\t\t\t}\n\n\t\t\tlabel = \"\";\n\t\t\tif ( p.is_labelled[locctr] ) {\n\t\t\t\tif ( !find_from_symtab(label,int2hex(locctr)) ) {\n\t\t\t\t\tstring errstr;\n\t\t\t\t\terrstr += \"Label not created for location \";\n\t\t\t\t\terrstr += int2hex(locctr);\n\t\t\t\t\terror(errstr);\n\t\t\t\t}\n\t\t\t} \/\/ TODO: Refactor to prevent rewrite of code\n\n\t\t\tlocctr += 3;\n\t\t} else if ( p.byte_type_guess[locctr] == CHAR_DATA ) {\n\t\t\tif ( p.is_labelled[locctr] ) {\n\t\t\t\tif ( !find_from_symtab(label,int2hex(locctr)) ) {\n\t\t\t\t\tstring errstr;\n\t\t\t\t\terrstr += \"Label not created for location \";\n\t\t\t\t\terrstr += int2hex(locctr);\n\t\t\t\t\terror(errstr);\n\t\t\t\t}\n\t\t\t} \/\/ TODO: Refactor to prevent rewrite of code\n\n\t\t\tvector<char> byte_list;\n\t\t\tbool type_c = true;\n\t\t\tdo {\n\t\t\t\tbyte_list.push_back(p.memory[locctr]);\n\t\t\t\tif ( !isprint(p.memory[locctr]) ) {\n\t\t\t\t\ttype_c = false;\n\t\t\t\t}\n\t\t\t\tlocctr++;\n\t\t\t} while ( p.byte_type_guess[locctr] == CHAR_DATA && !p.is_labelled[locctr] );\n\n\t\t\topcode = \"CHAR\";\n\n\t\t\toperand += (type_c?\"C\":\"X\");\n\t\t\toperand += \"'\";\n\t\t\tfor ( int i = 0 ; i < (int)byte_list.size() ; i++ ) {\n\t\t\t\tif ( type_c ) {\n\t\t\t\t\toperand += byte_list[i];\n\t\t\t\t} else {\n\t\t\t\t\toperand += byte2hex(byte_list[i]);\n\t\t\t\t}\n\t\t\t}\n\t\t\toperand += \"'\";\n\t\t} else {\n\t\t\t\/\/ TODO\n\t\t\tlocctr++; \/\/ temporarily\n\t\t}\n\t\tofile << asm_to_line(label,opcode,operand,is_indexed);\n\t}\n\tofile << asm_to_line(\"\",\"END\",\"FIRST\",false);\n}<|endoftext|>"} {"text":"<commit_before>\/\/ ======================================================================== \/\/\n\/\/ Copyright 2015-2019 Ingo Wald \/\/\n\/\/ \/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\"); \/\/\n\/\/ you may not use this file except in compliance with the License. \/\/\n\/\/ You may obtain a copy of the License at \/\/\n\/\/ \/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0 \/\/\n\/\/ \/\/\n\/\/ Unless required by applicable law or agreed to in writing, software \/\/\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS, \/\/\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. \/\/\n\/\/ See the License for the specific language governing permissions and \/\/\n\/\/ limitations under the License. \/\/\n\/\/ ======================================================================== \/\/\n\n\/\/ pbrt_parser\n#include \"pbrtParser\/Scene.h\"\n\/\/ stl\n#include <iostream>\n#include <vector>\n#include <sstream>\n#include <assert.h>\n\/\/ std\n#include <set>\n#include <stack>\n\nnamespace pbrt {\n namespace semantic {\n \n using std::cout;\n using std::endl;\n\n void usage(const std::string &msg)\n {\n if (msg != \"\") std::cerr << \"Error: \" << msg << std::endl << std::endl;\n std::cout << \".\/pbrt2pbf inFile.pbrt|inFile.pbf <args>\" << std::endl;\n std::cout << std::endl;\n std::cout << \" -o <out.pbf> : where to write the output to\" << std::endl;\n std::cout << \" (tris to quads, removing reundant fields, etc)\" << std::endl;\n }\n \n inline bool endsWith(const std::string &s, const std::string &suffix)\n {\n return s.substr(s.size()-suffix.size(),suffix.size()) == suffix;\n }\n\n void pbrt2pbf(int ac, char **av)\n {\n std::string inFileName;\n std::string outFileName;\n for (int i=1;i<ac;i++) {\n const std::string arg = av[i];\n if (arg == \"-o\") {\n assert(i+1 < ac);\n outFileName = av[++i];\n } else if (arg[0] != '-') {\n inFileName = arg;\n } else {\n usage(\"invalid argument '\"+arg+\"'\");\n } \n }\n\n if (outFileName == \"\")\n usage(\"no output file specified (-o <file.pbff>)\");\n if (inFileName == \"\")\n usage(\"no input pbrt file specified\");\n\n if (!endsWith(outFileName,\".pbf\")) {\n std::cout << \"output file name missing '.pbsf' extension - adding it ...\" << std::endl;\n outFileName = outFileName+\".pbf\";\n }\n \n std::cout << \"-------------------------------------------------------\" << std::endl;\n std::cout << \"parsing pbrt file \" << inFileName << std::endl;\n \/\/ try {\n Scene::SP scene = importPBRT(inFileName);\n std::cout << \"\\033[1;32m done importing scene.\\033[0m\" << std::endl;\n std::cout << \"writing to binary file \" << outFileName << std::endl;\n scene->saveTo(outFileName);\n std::cout << \"\\033[1;32m => yay! writing successful...\\033[0m\" << std::endl;\n \/\/ } catch (std::runtime_error &e) {\n \/\/ cout << \"\\033[1;31mError in parsing: \" << e.what() << \"\\033[0m\\n\";\n \/\/ throw e;\n \/\/ }\n }\n\n extern \"C\" int main(int ac, char **av)\n {\n pbrt2pbf(ac,av);\n return 0;\n }\n\n } \/\/ ::pbrt::semantic\n} \/\/ ::pbrt\n<commit_msg>usage() exit in pbrt2pbf now properly exits after error message<commit_after>\/\/ ======================================================================== \/\/\n\/\/ Copyright 2015-2019 Ingo Wald \/\/\n\/\/ \/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\"); \/\/\n\/\/ you may not use this file except in compliance with the License. \/\/\n\/\/ You may obtain a copy of the License at \/\/\n\/\/ \/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0 \/\/\n\/\/ \/\/\n\/\/ Unless required by applicable law or agreed to in writing, software \/\/\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS, \/\/\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. \/\/\n\/\/ See the License for the specific language governing permissions and \/\/\n\/\/ limitations under the License. \/\/\n\/\/ ======================================================================== \/\/\n\n\/\/ pbrt_parser\n#include \"pbrtParser\/Scene.h\"\n\/\/ stl\n#include <iostream>\n#include <vector>\n#include <sstream>\n#include <assert.h>\n\/\/ std\n#include <set>\n#include <stack>\n\nnamespace pbrt {\n namespace semantic {\n \n using std::cout;\n using std::endl;\n\n void usage(const std::string &msg)\n {\n if (msg != \"\") std::cerr << \"Error: \" << msg << std::endl << std::endl;\n std::cout << \".\/pbrt2pbf inFile.pbrt|inFile.pbf <args>\" << std::endl;\n std::cout << std::endl;\n std::cout << \" -o <out.pbf> : where to write the output to\" << std::endl;\n std::cout << \" (tris to quads, removing reundant fields, etc)\" << std::endl;\n exit(msg == \"\" ? 0 : 1);\n }\n \n inline bool endsWith(const std::string &s, const std::string &suffix)\n {\n return s.substr(s.size()-suffix.size(),suffix.size()) == suffix;\n }\n\n void pbrt2pbf(int ac, char **av)\n {\n std::string inFileName;\n std::string outFileName;\n for (int i=1;i<ac;i++) {\n const std::string arg = av[i];\n if (arg == \"-o\") {\n assert(i+1 < ac);\n outFileName = av[++i];\n } else if (arg[0] != '-') {\n inFileName = arg;\n } else {\n usage(\"invalid argument '\"+arg+\"'\");\n } \n }\n\n if (outFileName == \"\")\n usage(\"no output file specified (-o <file.pbff>)\");\n if (inFileName == \"\")\n usage(\"no input pbrt file specified\");\n\n if (!endsWith(outFileName,\".pbf\")) {\n std::cout << \"output file name missing '.pbsf' extension - adding it ...\" << std::endl;\n outFileName = outFileName+\".pbf\";\n }\n \n std::cout << \"-------------------------------------------------------\" << std::endl;\n std::cout << \"parsing pbrt file \" << inFileName << std::endl;\n \/\/ try {\n Scene::SP scene = importPBRT(inFileName);\n std::cout << \"\\033[1;32m done importing scene.\\033[0m\" << std::endl;\n std::cout << \"writing to binary file \" << outFileName << std::endl;\n scene->saveTo(outFileName);\n std::cout << \"\\033[1;32m => yay! writing successful...\\033[0m\" << std::endl;\n \/\/ } catch (std::runtime_error &e) {\n \/\/ cout << \"\\033[1;31mError in parsing: \" << e.what() << \"\\033[0m\\n\";\n \/\/ throw e;\n \/\/ }\n }\n\n extern \"C\" int main(int ac, char **av)\n {\n pbrt2pbf(ac,av);\n return 0;\n }\n\n } \/\/ ::pbrt::semantic\n} \/\/ ::pbrt\n<|endoftext|>"} {"text":"<commit_before>\n\/\/ (c) COPYRIGHT URI\/MIT 1997-1999\n\/\/ Please read the full copyright statement in the file COPYRIGHT.\n\/\/\n\/\/ Authors:\n\/\/ jhrg,jimg James Gallagher (jgallagher@gso.uri.edu)\n\n\/\/ Implementation of the DODSFilter class. This class is used to build dods\n\/\/ filter programs which, along with a CGI program, comprise DODS servers.\n\/\/ jhrg 8\/26\/97\n\n\/\/ $Log: DODSFilter.cc,v $\n\/\/ Revision 1.14 1999\/05\/25 21:57:52 dan\n\/\/ Added an optional second argument to read_ancillary_dds to support\n\/\/ JGOFS usage.\n\/\/\n\/\/ Revision 1.13 1999\/05\/25 21:54:19 dan\n\/\/ Added an optional argument to read_ancillary_das to support JGOFS\n\/\/ data object usage, where the location of the ancillary DAS file isn't\n\/\/ readily available through the 'dataset' argument of the command line.\n\/\/\n\/\/ Revision 1.12 1999\/05\/21 17:15:46 jimg\n\/\/ Added instrumentation to the ctor. This simplifies debugging the interaction\n\/\/ between the filter programs and the perl script.\n\/\/\n\/\/ Revision 1.11 1999\/05\/19 23:56:57 jimg\n\/\/ Changed the support address from @dods to @unidata\n\/\/\n\/\/ Revision 1.10 1999\/05\/05 00:36:36 jimg\n\/\/ Added the -V option. -v now is used to pass the version information from the\n\/\/ CGI to the C++ software; -V triggers output of the version message. This\n\/\/ allows the DODSFilter class to pass information about the server's version to\n\/\/ the core software.\n\/\/ All set_mime_*() functions are now passes the CGI version information so that\n\/\/ all MIME headers contain information about the server's version.\n\/\/ Added the get_cgi_version() member function so that clients of DODSFilter can\n\/\/ find out the version number.\n\/\/\n\/\/ Revision 1.9 1999\/05\/04 19:47:21 jimg\n\/\/ Fixed copyright statements. Removed more of the GNU classes.\n\/\/\n\/\/ Revision 1.8 1999\/04\/29 02:29:28 jimg\n\/\/ Merge of no-gnu branch\n\/\/\n\/\/ Revision 1.7 1999\/02\/22 22:59:07 jimg\n\/\/ Added the get_accept_types() accessor.\n\/\/ Changed the ctor so that the -t option is recognized.\n\/\/\n\/\/ Revision 1.6 1998\/12\/16 19:10:53 jimg\n\/\/ Added support for XDODS-Server MIME header. This fixes a problem where our\n\/\/ use of Server clashed with Java.\n\/\/\n\/\/ Revision 1.5 1998\/11\/10 01:04:42 jimg\n\/\/ Added `ends' to strings made with ostrstream (fixes a bug found with\n\/\/ purify).\n\/\/ Added catch for throws from within the CE evaluation functions.\n\/\/\n\/\/ Revision 1.4.2.2 1999\/02\/05 09:32:34 jimg\n\/\/ Fixed __unused__ so that it not longer clashes with Red Hat 5.2 inlined\n\/\/ math code. \n\/\/\n\/\/ Revision 1.4.2.1 1999\/02\/02 21:56:57 jimg\n\/\/ String to string version\n\/\/\n\/\/ Revision 1.4 1998\/08\/06 16:12:30 jimg\n\/\/ Added cache dir methods and stuff to ctor (from jeh)\n\/\/\n\/\/ Revision 1.3 1998\/03\/19 23:34:21 jimg\n\/\/ Fixed calls to set_mime_*().\n\/\/ Removed the compression code (it is now in DDS::send().\n\/\/ Removed old code (that was surrounded by #if 0 ... #endif).\n\/\/\n\/\/ Revision 1.2 1998\/02\/11 22:00:46 jimg\n\/\/ Added call to util.cc:deflate_exists() to send_data(). This means that\n\/\/ send_data() will only try to start the compressor if an executable copy of\n\/\/ deflate can be found. If, for any reason a copy of deflate cannot be found\n\/\/ data is sent without trying to compress it.\n\/\/\n\/\/ Revision 1.1 1997\/08\/28 20:39:02 jimg\n\/\/ Created\n\/\/\n\n#ifdef __GNUG__\n#pragma \"implemenation\"\n#endif\n\n#include \"config_dap.h\"\n\nstatic char rcsid[] not_used = {\"$Id: DODSFilter.cc,v 1.14 1999\/05\/25 21:57:52 dan Exp $\"};\n\n#include <iostream>\n#ifdef __GNUG__\n#include <strstream>\n#else\n#include <sstream>\n#endif\n#include <string>\n#include <GetOpt.h>\n\n#include \"DAS.h\"\n#include \"DDS.h\"\n#include \"debug.h\"\n#include \"cgi_util.h\"\n#include \"DODSFilter.h\"\n\nDODSFilter::DODSFilter(int argc, char *argv[]) : comp(false), ver(false), \n bad_options(false), dataset(\"\"), ce(\"\"), cgi_ver(\"\"),\n anc_dir(\"\"), anc_file(\"\"), cache_dir(\"\"), accept_types(\"All\")\n{\n program_name = argv[0];\n\n int option_char;\n GetOpt getopt (argc, argv, \"ce:v:Vd:f:r:t:\");\n\n while ((option_char = getopt()) != EOF)\n\tswitch (option_char) {\n\t case 'c': comp = true; break;\n\t case 'e': ce = getopt.optarg; break;\n\t case 'v': cgi_ver = getopt.optarg; break;\n\t case 'V': ver = true; break;\n\t case 'd': anc_dir = getopt.optarg; break;\n\t case 'f': anc_file = getopt.optarg; break;\n\t case 'r': cache_dir = getopt.optarg; break;\n\t case 't': accept_types = getopt.optarg; break;\n\t default: bad_options = true; break;\n\t}\n\n int next_arg = getopt.optind;\n if(next_arg < argc)\n\tdataset = argv[next_arg];\n else\n\tbad_options = true;\n\n DBG(cerr << \"comp: \" << comp << endl);\n DBG(cerr << \"ce: \" << ce << endl);\n DBG(cerr << \"cgi_ver: \" << cgi_ver << endl);\n DBG(cerr << \"ver: \" << ver << endl);\n DBG(cerr << \"anc_dir: \" << anc_dir << endl);\n DBG(cerr << \"anc_file: \" << anc_file << endl);\n DBG(cerr << \"cache_dir: \" << cache_dir << endl);\n DBG(cerr << \"accept_types: \" << accept_types << endl);\n}\n\nDODSFilter::~DODSFilter()\n{\n}\n\nbool\nDODSFilter::OK()\n{\n\n return !bad_options;\n}\n\nbool\nDODSFilter::version()\n{\n return ver;\n}\n\nstring\nDODSFilter::get_cgi_version()\n{\n return cgi_ver;\n}\n\nstring\nDODSFilter::get_ce()\n{\n return ce;\n}\n\nstring\nDODSFilter::get_dataset_name()\n{\n return dataset;\n}\n\nstring\nDODSFilter::get_dataset_version()\n{\n return \"\";\n}\n\nstring\nDODSFilter::get_cache_dir()\n{\n return cache_dir;\n}\n\nstring\nDODSFilter::get_accept_types()\n{\n return accept_types;\n}\n\nbool\nDODSFilter::read_ancillary_das(DAS &das, string anc_location)\n{\n if ( anc_location == \"\" ) anc_location = anc_dir;\n\n string name = find_ancillary_file(dataset, \"das\", anc_location, anc_file);\n FILE *in = fopen(name.c_str(), \"r\");\n \n if (in) {\n\tint status = das.parse(in);\n\tfclose(in);\n \n\tif(!status) {\n\t string msg = \"Parse error in external file \" + dataset + \".das\";\n\n\t \/\/ server error message\n\t ErrMsgT(msg);\n\n\t \/\/ client error message\n\t set_mime_text(cout, dods_error, cgi_ver);\n\t Error e(malformed_expr, msg);\n\t e.print(cout);\n\n\t return false;\n\t}\n }\n\n return true;\n}\n\nbool\nDODSFilter::read_ancillary_dds(DDS &dds, string anc_location)\n{\n if ( anc_location == \"\" ) anc_location = anc_dir;\n\n string name = find_ancillary_file(dataset, \"dds\", anc_location, anc_file);\n FILE *in = fopen(name.c_str(), \"r\");\n \n if (in) {\n\tint status = dds.parse(in);\n\tfclose(in);\n \n\tif(!status) {\n\t string msg = \"Parse error in external file \" + dataset + \".dds\";\n\n\t \/\/ server error message\n\t ErrMsgT(msg);\n\n\t \/\/ client error message\n\t set_mime_text(cout, dods_error, cgi_ver);\n\t Error e(malformed_expr, msg);\n\t e.print(cout);\n\n\t return false;\n\t}\n }\n\n return true;\n}\n\nstatic const char *emessage = \\\n\"DODS internal server error. Please report this to the dataset maintainer, \\\nor to support@unidata.ucar.edu.\";\n\nvoid \nDODSFilter::print_usage()\n{\n \/\/ Write a message to the WWW server error log file.\n ostrstream oss;\n oss << \"Usage: \" << program_name\n\t<< \" [-c] [-v <cgi version>] [-e <ce>]\"\n\t<< \" [-d <ancillary file directory>] [-f <ancillary file name>]\"\n\t<< \" <dataset>\" << ends;\n ErrMsgT(oss.str());\n oss.rdbuf()->freeze(0);\n\n \/\/ Build an error object to return to the user.\n Error e(unknown_error, emessage);\n set_mime_text(cout, dods_error, cgi_ver);\n e.print(cout);\n}\n\nvoid \nDODSFilter::send_version_info()\n{\n cout << \"HTTP\/1.0 200 OK\" << endl\n\t << \"XDODS-Server: \" << cgi_ver << endl\n\t << \"Content-Type: text\/plain\" << endl\n\t << endl;\n \n cout << \"Core version: \" << DVR << endl;\n\n if (cgi_ver != \"\")\n\tcout << \"Server vision: \" << cgi_ver << endl;\n\n string v = get_dataset_version();\n if (v != \"\")\n\tcout << \"Dataset version: \" << v << endl;\n}\n\nbool\nDODSFilter::send_das(DAS &das)\n{\n set_mime_text(cout, dods_das, cgi_ver);\n das.print(cout);\n\n return true;\n}\n\nbool\nDODSFilter::send_dds(DDS &dds, bool constrained)\n{\n if (constrained) {\n\tif (!dds.parse_constraint(ce, cout, true)) {\n\t string m = program_name + \": parse error in constraint: \" \n\t\t+ ce;\n\t ErrMsgT(m);\n\t \n\t set_mime_text(cout, dods_error, cgi_ver);\n\t Error e(unknown_error, m);\n\t e.print(cout);\n\n\t return false;\n\t}\n\tset_mime_text(cout, dods_dds, cgi_ver);\n\tdds.print_constrained(cout); \/\/ send constrained DDS \n }\n else {\n\tset_mime_text(cout, dods_dds, cgi_ver);\n\tdds.print(cout);\n }\n\n return true;\n}\n\nbool\nDODSFilter::send_data(DDS &dds, FILE *data_stream)\n{\n bool compress = comp && deflate_exists();\n\n \/\/ This catch is a quick & dirty hack for exceptions thrown by the new\n \/\/ (11\/6\/98) projection functions in CEs. I might add exceptions to other\n \/\/ parts of the CE parser and evaluator. Eventually, the C++ classes\n \/\/ should switch to exceptions. 11\/6\/98 jhrg\n try {\n\tif (!dds.send(dataset, ce, data_stream, compress, cgi_ver)) {\n\t ErrMsgT((compress) ? \"Could not send compressed data\" : \n\t\t \"Could not send data\");\n\t return false;\n\t}\n }\n catch (Error &e) {\n\tset_mime_text(cout, dods_error, cgi_ver);\n\te.print(cout);\n\n\treturn false;\n }\n\t\n return true;\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n<commit_msg>Added a bit where, before sending caught Error objects to the client, we write the message to t eh httpd's error_log.<commit_after>\n\/\/ (c) COPYRIGHT URI\/MIT 1997-1999\n\/\/ Please read the full copyright statement in the file COPYRIGHT.\n\/\/\n\/\/ Authors:\n\/\/ jhrg,jimg James Gallagher (jgallagher@gso.uri.edu)\n\n\/\/ Implementation of the DODSFilter class. This class is used to build dods\n\/\/ filter programs which, along with a CGI program, comprise DODS servers.\n\/\/ jhrg 8\/26\/97\n\n\/\/ $Log: DODSFilter.cc,v $\n\/\/ Revision 1.15 1999\/05\/26 17:37:02 jimg\n\/\/ Added a bit where, before sending caught Error objects to the client, we\n\/\/ write the message to t eh httpd's error_log.\n\/\/\n\/\/ Revision 1.14 1999\/05\/25 21:57:52 dan\n\/\/ Added an optional second argument to read_ancillary_dds to support\n\/\/ JGOFS usage.\n\/\/\n\/\/ Revision 1.13 1999\/05\/25 21:54:19 dan\n\/\/ Added an optional argument to read_ancillary_das to support JGOFS\n\/\/ data object usage, where the location of the ancillary DAS file isn't\n\/\/ readily available through the 'dataset' argument of the command line.\n\/\/\n\/\/ Revision 1.12 1999\/05\/21 17:15:46 jimg\n\/\/ Added instrumentation to the ctor. This simplifies debugging the interaction\n\/\/ between the filter programs and the perl script.\n\/\/\n\/\/ Revision 1.11 1999\/05\/19 23:56:57 jimg\n\/\/ Changed the support address from @dods to @unidata\n\/\/\n\/\/ Revision 1.10 1999\/05\/05 00:36:36 jimg\n\/\/ Added the -V option. -v now is used to pass the version information from the\n\/\/ CGI to the C++ software; -V triggers output of the version message. This\n\/\/ allows the DODSFilter class to pass information about the server's version to\n\/\/ the core software.\n\/\/ All set_mime_*() functions are now passes the CGI version information so that\n\/\/ all MIME headers contain information about the server's version.\n\/\/ Added the get_cgi_version() member function so that clients of DODSFilter can\n\/\/ find out the version number.\n\/\/\n\/\/ Revision 1.9 1999\/05\/04 19:47:21 jimg\n\/\/ Fixed copyright statements. Removed more of the GNU classes.\n\/\/\n\/\/ Revision 1.8 1999\/04\/29 02:29:28 jimg\n\/\/ Merge of no-gnu branch\n\/\/\n\/\/ Revision 1.7 1999\/02\/22 22:59:07 jimg\n\/\/ Added the get_accept_types() accessor.\n\/\/ Changed the ctor so that the -t option is recognized.\n\/\/\n\/\/ Revision 1.6 1998\/12\/16 19:10:53 jimg\n\/\/ Added support for XDODS-Server MIME header. This fixes a problem where our\n\/\/ use of Server clashed with Java.\n\/\/\n\/\/ Revision 1.5 1998\/11\/10 01:04:42 jimg\n\/\/ Added `ends' to strings made with ostrstream (fixes a bug found with\n\/\/ purify).\n\/\/ Added catch for throws from within the CE evaluation functions.\n\/\/\n\/\/ Revision 1.4.2.2 1999\/02\/05 09:32:34 jimg\n\/\/ Fixed __unused__ so that it not longer clashes with Red Hat 5.2 inlined\n\/\/ math code. \n\/\/\n\/\/ Revision 1.4.2.1 1999\/02\/02 21:56:57 jimg\n\/\/ String to string version\n\/\/\n\/\/ Revision 1.4 1998\/08\/06 16:12:30 jimg\n\/\/ Added cache dir methods and stuff to ctor (from jeh)\n\/\/\n\/\/ Revision 1.3 1998\/03\/19 23:34:21 jimg\n\/\/ Fixed calls to set_mime_*().\n\/\/ Removed the compression code (it is now in DDS::send().\n\/\/ Removed old code (that was surrounded by #if 0 ... #endif).\n\/\/\n\/\/ Revision 1.2 1998\/02\/11 22:00:46 jimg\n\/\/ Added call to util.cc:deflate_exists() to send_data(). This means that\n\/\/ send_data() will only try to start the compressor if an executable copy of\n\/\/ deflate can be found. If, for any reason a copy of deflate cannot be found\n\/\/ data is sent without trying to compress it.\n\/\/\n\/\/ Revision 1.1 1997\/08\/28 20:39:02 jimg\n\/\/ Created\n\/\/\n\n#ifdef __GNUG__\n#pragma \"implemenation\"\n#endif\n\n#include \"config_dap.h\"\n\nstatic char rcsid[] not_used = {\"$Id: DODSFilter.cc,v 1.15 1999\/05\/26 17:37:02 jimg Exp $\"};\n\n#include <iostream>\n#ifdef __GNUG__\n#include <strstream>\n#else\n#include <sstream>\n#endif\n#include <string>\n#include <GetOpt.h>\n\n#include \"DAS.h\"\n#include \"DDS.h\"\n#include \"debug.h\"\n#include \"cgi_util.h\"\n#include \"DODSFilter.h\"\n\nDODSFilter::DODSFilter(int argc, char *argv[]) : comp(false), ver(false), \n bad_options(false), dataset(\"\"), ce(\"\"), cgi_ver(\"\"),\n anc_dir(\"\"), anc_file(\"\"), cache_dir(\"\"), accept_types(\"All\")\n{\n program_name = argv[0];\n\n int option_char;\n GetOpt getopt (argc, argv, \"ce:v:Vd:f:r:t:\");\n\n while ((option_char = getopt()) != EOF)\n\tswitch (option_char) {\n\t case 'c': comp = true; break;\n\t case 'e': ce = getopt.optarg; break;\n\t case 'v': cgi_ver = getopt.optarg; break;\n\t case 'V': ver = true; break;\n\t case 'd': anc_dir = getopt.optarg; break;\n\t case 'f': anc_file = getopt.optarg; break;\n\t case 'r': cache_dir = getopt.optarg; break;\n\t case 't': accept_types = getopt.optarg; break;\n\t default: bad_options = true; break;\n\t}\n\n int next_arg = getopt.optind;\n if(next_arg < argc)\n\tdataset = argv[next_arg];\n else\n\tbad_options = true;\n\n DBG(cerr << \"comp: \" << comp << endl);\n DBG(cerr << \"ce: \" << ce << endl);\n DBG(cerr << \"cgi_ver: \" << cgi_ver << endl);\n DBG(cerr << \"ver: \" << ver << endl);\n DBG(cerr << \"anc_dir: \" << anc_dir << endl);\n DBG(cerr << \"anc_file: \" << anc_file << endl);\n DBG(cerr << \"cache_dir: \" << cache_dir << endl);\n DBG(cerr << \"accept_types: \" << accept_types << endl);\n}\n\nDODSFilter::~DODSFilter()\n{\n}\n\nbool\nDODSFilter::OK()\n{\n\n return !bad_options;\n}\n\nbool\nDODSFilter::version()\n{\n return ver;\n}\n\nstring\nDODSFilter::get_cgi_version()\n{\n return cgi_ver;\n}\n\nstring\nDODSFilter::get_ce()\n{\n return ce;\n}\n\nstring\nDODSFilter::get_dataset_name()\n{\n return dataset;\n}\n\nstring\nDODSFilter::get_dataset_version()\n{\n return \"\";\n}\n\nstring\nDODSFilter::get_cache_dir()\n{\n return cache_dir;\n}\n\nstring\nDODSFilter::get_accept_types()\n{\n return accept_types;\n}\n\nbool\nDODSFilter::read_ancillary_das(DAS &das, string anc_location)\n{\n if ( anc_location == \"\" ) anc_location = anc_dir;\n\n string name = find_ancillary_file(dataset, \"das\", anc_location, anc_file);\n FILE *in = fopen(name.c_str(), \"r\");\n \n if (in) {\n\tint status = das.parse(in);\n\tfclose(in);\n \n\tif(!status) {\n\t string msg = \"Parse error in external file \" + dataset + \".das\";\n\n\t \/\/ server error message\n\t ErrMsgT(msg);\n\n\t \/\/ client error message\n\t set_mime_text(cout, dods_error, cgi_ver);\n\t Error e(malformed_expr, msg);\n\t e.print(cout);\n\n\t return false;\n\t}\n }\n\n return true;\n}\n\nbool\nDODSFilter::read_ancillary_dds(DDS &dds, string anc_location)\n{\n if ( anc_location == \"\" ) anc_location = anc_dir;\n\n string name = find_ancillary_file(dataset, \"dds\", anc_location, anc_file);\n FILE *in = fopen(name.c_str(), \"r\");\n \n if (in) {\n\tint status = dds.parse(in);\n\tfclose(in);\n \n\tif(!status) {\n\t string msg = \"Parse error in external file \" + dataset + \".dds\";\n\n\t \/\/ server error message\n\t ErrMsgT(msg);\n\n\t \/\/ client error message\n\t set_mime_text(cout, dods_error, cgi_ver);\n\t Error e(malformed_expr, msg);\n\t e.print(cout);\n\n\t return false;\n\t}\n }\n\n return true;\n}\n\nstatic const char *emessage = \\\n\"DODS internal server error. Please report this to the dataset maintainer, \\\nor to support@unidata.ucar.edu.\";\n\nvoid \nDODSFilter::print_usage()\n{\n \/\/ Write a message to the WWW server error log file.\n ostrstream oss;\n oss << \"Usage: \" << program_name\n\t<< \" [-c] [-v <cgi version>] [-e <ce>]\"\n\t<< \" [-d <ancillary file directory>] [-f <ancillary file name>]\"\n\t<< \" <dataset>\" << ends;\n ErrMsgT(oss.str());\n oss.rdbuf()->freeze(0);\n\n \/\/ Build an error object to return to the user.\n Error e(unknown_error, emessage);\n set_mime_text(cout, dods_error, cgi_ver);\n e.print(cout);\n}\n\nvoid \nDODSFilter::send_version_info()\n{\n cout << \"HTTP\/1.0 200 OK\" << endl\n\t << \"XDODS-Server: \" << cgi_ver << endl\n\t << \"Content-Type: text\/plain\" << endl\n\t << endl;\n \n cout << \"Core version: \" << DVR << endl;\n\n if (cgi_ver != \"\")\n\tcout << \"Server vision: \" << cgi_ver << endl;\n\n string v = get_dataset_version();\n if (v != \"\")\n\tcout << \"Dataset version: \" << v << endl;\n}\n\nbool\nDODSFilter::send_das(DAS &das)\n{\n set_mime_text(cout, dods_das, cgi_ver);\n das.print(cout);\n\n return true;\n}\n\nbool\nDODSFilter::send_dds(DDS &dds, bool constrained)\n{\n if (constrained) {\n\tif (!dds.parse_constraint(ce, cout, true)) {\n\t string m = program_name + \": parse error in constraint: \" \n\t\t+ ce;\n\t ErrMsgT(m);\n\t \n\t set_mime_text(cout, dods_error, cgi_ver);\n\t Error e(unknown_error, m);\n\t e.print(cout);\n\n\t return false;\n\t}\n\tset_mime_text(cout, dods_dds, cgi_ver);\n\tdds.print_constrained(cout); \/\/ send constrained DDS \n }\n else {\n\tset_mime_text(cout, dods_dds, cgi_ver);\n\tdds.print(cout);\n }\n\n return true;\n}\n\nbool\nDODSFilter::send_data(DDS &dds, FILE *data_stream)\n{\n bool compress = comp && deflate_exists();\n\n \/\/ This catch is a quick & dirty hack for exceptions thrown by the new\n \/\/ (11\/6\/98) projection functions in CEs. I might add exceptions to other\n \/\/ parts of the CE parser and evaluator. Eventually, the C++ classes\n \/\/ should switch to exceptions. 11\/6\/98 jhrg\n \/\/\n \/\/ I'm not sure we should catch errors from dds.send and its callees\n \/\/ here. I think they should be caught in the outer layer (e.g.,\n \/\/ ff_dods). 5\/26\/99 jhrg\n try {\n\tif (!dds.send(dataset, ce, data_stream, compress, cgi_ver)) {\n\t ErrMsgT((compress) ? \"Could not send compressed data\" : \n\t\t \"Could not send data\");\n\t return false;\n\t}\n }\n catch (Error &e) {\n\tErrMsgT((compress) ? \"Could not send compressed data\" : \n\t\t\"Could not send data\");\n\tset_mime_text(cout, dods_error, cgi_ver);\n\te.print(cout);\n\n\treturn false;\n }\n\t\n return true;\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2015, Daniel Pfeifer <daniel@pfeifer-mail.de>\n\/\/\n\/\/ Permission to use, copy, modify, and\/or distribute this software for any\n\/\/ purpose with or without fee is hereby granted, provided that the above\n\/\/ copyright notice and this permission notice appear in all copies.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n\/\/ WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n\/\/ MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n\/\/ ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n\/\/ WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n\/\/ ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n\/\/ OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n\n#ifndef BYOM_DYNAMIC_VIEW_HPP\n#define BYOM_DYNAMIC_VIEW_HPP\n\n#include <string>\n#include <memory>\n#include <functional>\n#include <type_traits>\n#include <boost\/mpl\/bool.hpp>\n#include <boost\/mpl\/if.hpp>\n\nnamespace byom {\n\nclass dynamic_view;\n\nusing visit_function =\n std::function<void(dynamic_view const&, dynamic_view const&)>;\n\ntemplate <typename T, typename Enable = void>\nstruct ext;\n\nclass dynamic_view\n{\n template <typename T>\n using no_copy_ctor = typename std::enable_if<!std::is_same<\n typename std::remove_reference<T>::type, dynamic_view>::value>::type;\n\npublic:\n template <typename T, typename Enable = no_copy_ctor<T>>\n dynamic_view(T&& t)\n : dynamic_view(std::forward<T>(t), std::is_lvalue_reference<T>())\n {\n }\n\n dynamic_view(dynamic_view const& x)\n {\n x.object().clone(storage());\n }\n\n dynamic_view(dynamic_view&& x)\n {\n x.object().move_clone(storage());\n }\n\n ~dynamic_view()\n {\n object().~concept_t();\n }\n\n dynamic_view& operator=(dynamic_view&& x) = delete;\n dynamic_view& operator=(dynamic_view const& x) = delete;\n\npublic:\n bool empty() const\n {\n return object().empty();\n }\n\n dynamic_view at(std::string const& n) const &\n {\n return object().at(n);\n }\n\n dynamic_view at(std::string const& n) const &&\n {\n auto member = object().at(n);\n if (object().owned() && !member.object().owned()) {\n throw std::invalid_argument{ \"dangling reference\" };\n }\n return member;\n }\n\n void for_each(visit_function const& v) const\n {\n object().for_each(v);\n }\n\n friend std::ostream& operator<<(std::ostream& os, dynamic_view const& self)\n {\n self.object().print(os);\n return os;\n }\n\nprivate:\n struct concept_t\n {\n virtual ~concept_t() = default;\n virtual void clone(void* storage) const = 0;\n virtual void move_clone(void* storage) = 0;\n virtual bool owned() const = 0;\n virtual bool empty() const = 0;\n virtual dynamic_view at(std::string const& n) const = 0;\n virtual void for_each(visit_function const& v) const = 0;\n virtual void print(std::ostream& os) const = 0;\n };\n\n template <template <typename> class Derived, typename T>\n struct model_base_t : concept_t\n {\n bool empty() const override\n {\n return ext<T>::empty_impl(get());\n }\n\n dynamic_view at(std::string const& n) const override\n {\n return ext<T>::at_impl(get(), n);\n }\n\n void for_each(visit_function const& v) const override\n {\n ext<T>::for_each_impl(get(), v);\n }\n\n void print(std::ostream& os) const override\n {\n ext<T>::print_impl(os, get());\n }\n\n T const& get() const\n {\n return static_cast<Derived<T> const*>(this)->get();\n }\n };\n\n template <typename T>\n struct cref_model_t : model_base_t<cref_model_t, T>\n {\n cref_model_t(T const& x)\n : object(x)\n {\n }\n\n void clone(void* storage) const override\n {\n new (storage) cref_model_t(object);\n }\n\n void move_clone(void* storage) override\n {\n clone(storage);\n }\n\n bool owned() const override\n {\n return false;\n }\n\n T const& get() const\n {\n return object;\n }\n\n T const& object;\n };\n\n template <typename T>\n struct local_model_t : model_base_t<local_model_t, T>\n {\n local_model_t(T x)\n : object(std::move(x))\n {\n }\n\n void clone(void* storage) const override\n {\n new (storage) local_model_t(object);\n }\n\n bool owned() const override\n {\n return true;\n }\n\n void move_clone(void* storage) override\n {\n new (storage) local_model_t(std::move(object));\n }\n\n T const& get() const\n {\n return object;\n }\n\n T object;\n };\n\n template <typename T>\n struct remote_model_t : model_base_t<remote_model_t, T>\n {\n remote_model_t(T x)\n : object(std::make_unique<T const>(std::move(x)))\n {\n }\n\n void clone(void* storage) const override\n {\n new (storage) remote_model_t(get());\n }\n\n void move_clone(void* storage) override\n {\n new (storage) remote_model_t(std::move(*this));\n }\n\n bool owned() const override\n {\n return true;\n }\n\n T const& get() const\n {\n return *object;\n }\n\n std::unique_ptr<T const> object;\n };\n\nprivate:\n template <typename T>\n dynamic_view(T&& t, std::true_type)\n {\n using model = cref_model_t<typename std::decay<T>::type>;\n static_assert(sizeof(model) <= sizeof(data), \"size mismatch\");\n new (storage()) model(t);\n }\n\n template <typename T>\n dynamic_view(T&& t, std::false_type)\n {\n using local_type = local_model_t<typename std::decay<T>::type>;\n using remote_type = remote_model_t<typename std::decay<T>::type>;\n using use_local_type =\n boost::mpl::bool_<(sizeof(local_type) <= sizeof(data)) &&\n (std::is_nothrow_copy_constructible<T>::value ||\n std::is_nothrow_move_constructible<T>::value)>;\n using model =\n typename boost::mpl::if_<use_local_type, local_type, remote_type>::type;\n static_assert(sizeof(model) <= sizeof(data), \"size mismatch\");\n new (storage()) model(std::move(t));\n }\n\nprivate:\n concept_t& object()\n {\n return *static_cast<concept_t*>(storage());\n }\n\n concept_t const& object() const\n {\n return *static_cast<concept_t const*>(storage());\n }\n\n void* storage()\n {\n return &data;\n }\n\n void const* storage() const\n {\n return &data;\n }\n\n double data[2];\n};\n\n} \/\/ namespace byom\n\n#endif \/* BYOM_DYNAMIC_VIEW_HPP *\/\n<commit_msg>make sure pointers are stored by value<commit_after>\/\/ Copyright (c) 2015, Daniel Pfeifer <daniel@pfeifer-mail.de>\n\/\/\n\/\/ Permission to use, copy, modify, and\/or distribute this software for any\n\/\/ purpose with or without fee is hereby granted, provided that the above\n\/\/ copyright notice and this permission notice appear in all copies.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n\/\/ WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n\/\/ MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n\/\/ ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n\/\/ WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n\/\/ ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n\/\/ OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n\n#ifndef BYOM_DYNAMIC_VIEW_HPP\n#define BYOM_DYNAMIC_VIEW_HPP\n\n#include <string>\n#include <memory>\n#include <functional>\n#include <type_traits>\n#include <boost\/mpl\/bool.hpp>\n#include <boost\/mpl\/if.hpp>\n\nnamespace byom {\n\nclass dynamic_view;\n\nusing visit_function =\n std::function<void(dynamic_view const&, dynamic_view const&)>;\n\ntemplate <typename T, typename Enable = void>\nstruct ext;\n\nclass dynamic_view\n{\n template <typename T>\n using no_copy_ctor = typename std::enable_if<!std::is_same<\n typename std::remove_reference<T>::type, dynamic_view>::value>::type;\n\npublic:\n template <typename T, typename Enable = no_copy_ctor<T>>\n dynamic_view(T&& t)\n : dynamic_view(std::forward<T>(t), std::is_lvalue_reference<T>())\n {\n }\n\n template <typename T>\n dynamic_view(T* t)\n {\n new (storage()) local_model_t<T*>(t);\n }\n\n template <typename T>\n dynamic_view(T const* t)\n {\n new (storage()) local_model_t<T const*>(t);\n }\n\n dynamic_view(dynamic_view const& x)\n {\n x.object().clone(storage());\n }\n\n dynamic_view(dynamic_view&& x)\n {\n x.object().move_clone(storage());\n }\n\n ~dynamic_view()\n {\n object().~concept_t();\n }\n\n dynamic_view& operator=(dynamic_view&& x) = delete;\n dynamic_view& operator=(dynamic_view const& x) = delete;\n\npublic:\n bool empty() const\n {\n return object().empty();\n }\n\n dynamic_view at(std::string const& n) const &\n {\n return object().at(n);\n }\n\n dynamic_view at(std::string const& n) const &&\n {\n auto member = object().at(n);\n if (object().owned() && !member.object().owned()) {\n throw std::invalid_argument{ \"dangling reference\" };\n }\n return member;\n }\n\n void for_each(visit_function const& v) const\n {\n object().for_each(v);\n }\n\n friend std::ostream& operator<<(std::ostream& os, dynamic_view const& self)\n {\n self.object().print(os);\n return os;\n }\n\nprivate:\n struct concept_t\n {\n virtual ~concept_t() = default;\n virtual void clone(void* storage) const = 0;\n virtual void move_clone(void* storage) = 0;\n virtual bool owned() const = 0;\n virtual bool empty() const = 0;\n virtual dynamic_view at(std::string const& n) const = 0;\n virtual void for_each(visit_function const& v) const = 0;\n virtual void print(std::ostream& os) const = 0;\n };\n\n template <template <typename> class Derived, typename T>\n struct model_base_t : concept_t\n {\n bool empty() const override\n {\n return ext<T>::empty_impl(get());\n }\n\n dynamic_view at(std::string const& n) const override\n {\n return ext<T>::at_impl(get(), n);\n }\n\n void for_each(visit_function const& v) const override\n {\n ext<T>::for_each_impl(get(), v);\n }\n\n void print(std::ostream& os) const override\n {\n ext<T>::print_impl(os, get());\n }\n\n T const& get() const\n {\n return static_cast<Derived<T> const*>(this)->get();\n }\n };\n\n template <typename T>\n struct cref_model_t : model_base_t<cref_model_t, T>\n {\n cref_model_t(T const& x)\n : object(x)\n {\n }\n\n void clone(void* storage) const override\n {\n new (storage) cref_model_t(object);\n }\n\n void move_clone(void* storage) override\n {\n clone(storage);\n }\n\n bool owned() const override\n {\n return false;\n }\n\n T const& get() const\n {\n return object;\n }\n\n T const& object;\n };\n\n template <typename T>\n struct local_model_t : model_base_t<local_model_t, T>\n {\n local_model_t(T x)\n : object(std::move(x))\n {\n }\n\n void clone(void* storage) const override\n {\n new (storage) local_model_t(object);\n }\n\n bool owned() const override\n {\n return true;\n }\n\n void move_clone(void* storage) override\n {\n new (storage) local_model_t(std::move(object));\n }\n\n T const& get() const\n {\n return object;\n }\n\n T object;\n };\n\n template <typename T>\n struct remote_model_t : model_base_t<remote_model_t, T>\n {\n remote_model_t(T x)\n : object(std::make_unique<T const>(std::move(x)))\n {\n }\n\n void clone(void* storage) const override\n {\n new (storage) remote_model_t(get());\n }\n\n void move_clone(void* storage) override\n {\n new (storage) remote_model_t(std::move(*this));\n }\n\n bool owned() const override\n {\n return true;\n }\n\n T const& get() const\n {\n return *object;\n }\n\n std::unique_ptr<T const> object;\n };\n\nprivate:\n template <typename T>\n dynamic_view(T&& t, std::true_type)\n {\n using model = cref_model_t<typename std::decay<T>::type>;\n static_assert(sizeof(model) <= sizeof(data), \"size mismatch\");\n new (storage()) model(t);\n }\n\n template <typename T>\n dynamic_view(T&& t, std::false_type)\n {\n using local_type = local_model_t<typename std::decay<T>::type>;\n using remote_type = remote_model_t<typename std::decay<T>::type>;\n using use_local_type =\n boost::mpl::bool_<(sizeof(local_type) <= sizeof(data)) &&\n (std::is_nothrow_copy_constructible<T>::value ||\n std::is_nothrow_move_constructible<T>::value)>;\n using model =\n typename boost::mpl::if_<use_local_type, local_type, remote_type>::type;\n static_assert(sizeof(model) <= sizeof(data), \"size mismatch\");\n new (storage()) model(std::move(t));\n }\n\nprivate:\n concept_t& object()\n {\n return *static_cast<concept_t*>(storage());\n }\n\n concept_t const& object() const\n {\n return *static_cast<concept_t const*>(storage());\n }\n\n void* storage()\n {\n return &data;\n }\n\n void const* storage() const\n {\n return &data;\n }\n\n double data[2];\n};\n\n} \/\/ namespace byom\n\n#endif \/* BYOM_DYNAMIC_VIEW_HPP *\/\n<|endoftext|>"} {"text":"<commit_before>#include <configure\/bind.hpp>\n\n#include <configure\/Build.hpp>\n#include <configure\/Rule.hpp>\n#include <configure\/lua\/State.hpp>\n#include <configure\/lua\/Type.hpp>\n#include <configure\/Filesystem.hpp>\n#include <configure\/Platform.hpp>\n\n#include <boost\/filesystem\/path.hpp>\n\nnamespace fs = boost::filesystem;\n\nnamespace configure {\n\n\ttemplate<typename T>\n\tstatic int Build_option(lua_State* state)\n\t{\n\t\tBuild& self = lua::Converter<std::reference_wrapper<Build>>::extract(state, 1);\n\t\tauto name = lua::Converter<std::string>::extract(state, 2);\n\t\tauto descr = lua::Converter<std::string>::extract(state, 3);\n\t\tif (lua_gettop(state) == 3)\n\t\t{\n\t\t\tauto res = self.option<T>(std::move(name), std::move(descr));\n\t\t\tif (res)\n\t\t\t\tlua::Converter<T>::push(state, *res);\n\t\t\telse\n\t\t\t\tlua_pushnil(state);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tlua::Converter<T>::push(\n\t\t\t state,\n\t\t\t\tself.option<T>(\n\t\t\t\t\tstd::move(name),\n\t\t\t\t\tstd::move(descr),\n\t\t\t\t\tlua::Converter<T>::extract(state, 4)\n\t\t\t\t)\n\t\t\t);\n\t\t}\n\t\treturn 1;\n\t}\n\n\ttemplate<typename T>\n\tstatic int Build_lazy_option(lua_State* state)\n\t{\n\t\tBuild& self = lua::Converter<std::reference_wrapper<Build>>::extract(state, 1);\n\t\tauto key = lua::Converter<std::string>::extract(state, 2);\n\t\tauto descr = lua::Converter<std::string>::extract(state, 3);\n\t\tif (!lua_isfunction(state, -1))\n\t\t\tthrow std::runtime_error(\"Expected a function as a second argument\");\n\t\tauto res = self.lazy_option<T>(\n\t\t\tkey,\n\t\t\tdescr,\n\t\t\t[&]() -> T {\n\t\t\t\tlua::State::check_status(state, lua_pcall(state, 0, 1, 0));\n\t\t\t\ttry { return lua::Converter<T>::extract(state, -1); }\n\t\t\t\tcatch (...) {\n\t\t\t\t CONFIGURE_THROW(\n\t\t\t\t error::BuildError(\"The lua callback for option '\" + key +\n\t\t\t\t \"' didn't return a valid value\")\n\t\t\t\t << error::nested(std::current_exception()));\n\t\t\t }\n\t\t\t});\n\t\tlua::Converter<T>::push(state, std::move(res));\n\t\treturn 1;\n\t}\n\n\ttemplate<log::Level level>\n\tstatic int Build_log(lua_State* state)\n\t{\n\t\tlua::Converter<std::reference_wrapper<Build>>::extract(state, 1);\n\t\tstd::string msg;\n\t\tfor (int i = 2, len = lua_gettop(state); i <= len; ++i)\n\t\t{\n\t\t\tif (!msg.empty()) msg.push_back(' ');\n\t\t\tmsg += luaL_tolstring(state, i, nullptr);\n\t\t}\n\t\tif (level == log::Level::error)\n\t\t\tCONFIGURE_THROW(error::BuildError(msg));\n\t\tlog::log<level>(msg);\n\t\treturn 0;\n\t}\n\n\tvoid bind_build(lua::State& state)\n\t{\n\t\t\/\/\/ Represent a build.\n\t\t\/\/ @classmod Build\n\t\tlua::Type<Build, std::reference_wrapper<Build>>(state)\n\t\t \/\/\/ Current project directory @{Path}.\n\t\t \/\/ @function Build:project_directory\n\t\t .def(\"project_directory\", &Build::project_directory)\n\n\t\t \/\/\/ Current build directory @{Path}.\n\t\t \/\/ @function Build:directory\n\t\t .def(\"directory\", &Build::directory)\n\n\t\t \/\/\/ Build root node\n\t\t \/\/ @function Build:root_node\n\t\t .def(\"root_node\", &Build::root_node)\n\n\t\t \/\/\/ Source @{Node} associated to a @{Path}.\n\t\t \/\/ @tparam Path path relative path to a source file\n\t\t \/\/ @function Build:source_node\n\t\t .def(\"source_node\", &Build::source_node)\n\n\t\t \/\/\/ Target @{Node} associated to a @{Path}.\n\t\t \/\/ @tparam Path path relative path to a built file\n\t\t \/\/ @function Build:target_node\n\t\t .def(\"target_node\", &Build::target_node)\n\n\t\t \/\/\/ Directory @{Node} associated to a @{Path}.\n\t\t \/\/ @tparam Path path Absolute path to a directory\n\t\t \/\/ @function Build:directory_node\n\t\t .def(\"directory_node\", &Build::directory_node)\n\n\t\t \/\/\/ File @{Node} associated to a @{Path}.\n\t\t \/\/ @tparam Path path Absolute path to a file\n\t\t \/\/ @function Build:file_node\n\t\t .def(\"file_node\", &Build::file_node)\n\n\t\t \/\/\/ Virtual @{Node}.\n\t\t \/\/ @tparam string name A non-empty string\n\t\t \/\/ @function Build:virtual_node\n\t\t .def(\"virtual_node\", &Build::virtual_node)\n\n\t\t \/\/\/ Add a rule to the build.\n\t\t \/\/ @tparam Rule rule Rule to add\n\t\t \/\/ @function Build:add_rule\n\t\t .def(\"add_rule\", &Build::add_rule)\n\n\t\t \/\/\/ Associated @{Filesystem} instance.\n\t\t \/\/ @function Build:fs\n\t\t .def<lua::return_policy::ref>(\"fs\", &Build::fs)\n\n\t\t \/\/\/ Associated @{Environ} instance.\n\t\t \/\/ @function Build:env\n\t\t .def<lua::return_policy::ref>(\"env\", &Build::env)\n\n\t\t \/\/\/ Path to the configure executable\n\t\t \/\/ @function Build:configure_program\n\t\t .def<lua::return_policy::copy>(\n\t\t \"configure_program\", &Build::configure_program)\n\n\t\t \/\/\/ Declare an option of type @{string} and return it's value.\n\t\t \/\/ @string name\n\t\t \/\/ @string description\n\t\t \/\/ @tparam[opt] string default_value\n\t\t \/\/ @treturn string|nil Associated value\n\t\t \/\/ @function Build:string_option\n\t\t .def( \"string_option\", &Build_option<std::string> )\n\n\t\t \/\/\/ Declare an option of type int and return it's value.\n\t\t \/\/ @string name\n\t\t \/\/ @string description\n\t\t \/\/ @tparam[opt] int default_value\n\t\t \/\/ @treturn int|nil Associated value\n\t\t \/\/ @function Build:int_option\n\t\t .def( \"int_option\", &Build_option<int64_t> )\n\n\t\t \/\/\/ Declare an option of type bool and return it's value.\n\t\t \/\/ @string name\n\t\t \/\/ @string description\n\t\t \/\/ @tparam[opt] bool default_value\n\t\t \/\/ @treturn bool|nil Associated value\n\t\t \/\/ @function Build:bool_option\n\t\t .def( \"bool_option\", &Build_option<bool> )\n\n\t\t \/\/\/ Declare an option of type @{Path} and return it's value.\n\t\t \/\/ @string name\n\t\t \/\/ @string description\n\t\t \/\/ @tparam[opt] Path default_value\n\t\t \/\/ @treturn Path|nil Associated value\n\t\t \/\/ @function Build:path_option\n\t\t .def( \"path_option\", &Build_option<fs::path> )\n\n\t\t \/\/\/ Declare a lazy option of type @{string} and return it's value.\n\t\t \/\/ @string name\n\t\t \/\/ @string description\n\t\t \/\/ @tparam[opt] string default_value\n\t\t \/\/ @treturn string|nil Associated value\n\t\t \/\/ @function Build:string_option\n\t\t .def( \"lazy_string_option\", &Build_lazy_option<std::string> )\n\n\t\t \/\/\/ Declare a lazy option of type int and return it's value.\n\t\t \/\/ @string name\n\t\t \/\/ @string description\n\t\t \/\/ @tparam[opt] int default_value\n\t\t \/\/ @treturn int|nil Associated value\n\t\t \/\/ @function Build:int_option\n\t\t .def( \"lazy_int_option\", &Build_lazy_option<int64_t> )\n\n\t\t \/\/\/ Declare a lazy option of type bool and return it's value.\n\t\t \/\/ @string name\n\t\t \/\/ @string description\n\t\t \/\/ @tparam[opt] bool default_value\n\t\t \/\/ @treturn bool|nil Associated value\n\t\t \/\/ @function Build:bool_option\n\t\t .def( \"lazy_bool_option\", &Build_lazy_option<bool> )\n\n\t\t \/\/\/ Declare a lazy option of type @{Path} and return it's value.\n\t\t \/\/ @string name\n\t\t \/\/ @string description\n\t\t \/\/ @tparam[opt] Path default_value\n\t\t \/\/ @treturn Path|nil Associated value\n\t\t \/\/ @function Build:path_option\n\t\t .def( \"lazy_path_option\", &Build_lazy_option<fs::path> )\n\n\t\t \/\/\/ The host platform.\n\t\t \/\/ @treturn Platform\n\t\t \/\/ @function Build:host_platform\n\t\t .def<lua::return_policy::ref>(\"host\", &Build::host)\n\n\t\t \/\/\/ The target platform.\n\t\t \/\/ @treturn Platform\n\t\t \/\/ @function Build:target_platform\n\t\t .def<lua::return_policy::ref>(\"target\", &Build::target)\n\n\t\t \/\/\/ Log a debug message.\n\t\t \/\/ @param args...\n\t\t \/\/ @function Build:debug\n\t\t .def( \"debug\", &Build_log<log::Level::verbose> )\n\n\t\t \/\/\/ Log an informational message.\n\t\t \/\/ @param args...\n\t\t \/\/ @function Build:status\n\t\t .def( \"status\", &Build_log<log::Level::status> )\n\n\t\t \/\/\/ Log a warning message.\n\t\t \/\/ @param args...\n\t\t \/\/ @function Build:warning\n\t\t .def( \"warning\", &Build_log<log::Level::warning> )\n\n\t\t \/\/\/ Stop the configuration with an error message.\n\t\t \/\/ @param args...\n\t\t \/\/ @function Build:error\n\t\t .def(\"error\", &Build_log<log::Level::error>);\n\t}\n\n}\n<commit_msg>Bind the configure method in lua.<commit_after>#include <configure\/bind.hpp>\n\n#include <configure\/Build.hpp>\n#include <configure\/Rule.hpp>\n#include <configure\/lua\/State.hpp>\n#include <configure\/lua\/Type.hpp>\n#include <configure\/Filesystem.hpp>\n#include <configure\/Platform.hpp>\n\n#include <boost\/filesystem\/path.hpp>\n\nnamespace fs = boost::filesystem;\n\nnamespace configure {\n\n\ttemplate<typename T>\n\tstatic int Build_option(lua_State* state)\n\t{\n\t\tBuild& self = lua::Converter<std::reference_wrapper<Build>>::extract(state, 1);\n\t\tauto name = lua::Converter<std::string>::extract(state, 2);\n\t\tauto descr = lua::Converter<std::string>::extract(state, 3);\n\t\tif (lua_gettop(state) == 3)\n\t\t{\n\t\t\tauto res = self.option<T>(std::move(name), std::move(descr));\n\t\t\tif (res)\n\t\t\t\tlua::Converter<T>::push(state, *res);\n\t\t\telse\n\t\t\t\tlua_pushnil(state);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tlua::Converter<T>::push(\n\t\t\t state,\n\t\t\t\tself.option<T>(\n\t\t\t\t\tstd::move(name),\n\t\t\t\t\tstd::move(descr),\n\t\t\t\t\tlua::Converter<T>::extract(state, 4)\n\t\t\t\t)\n\t\t\t);\n\t\t}\n\t\treturn 1;\n\t}\n\n\ttemplate<typename T>\n\tstatic int Build_lazy_option(lua_State* state)\n\t{\n\t\tBuild& self = lua::Converter<std::reference_wrapper<Build>>::extract(state, 1);\n\t\tauto key = lua::Converter<std::string>::extract(state, 2);\n\t\tauto descr = lua::Converter<std::string>::extract(state, 3);\n\t\tif (!lua_isfunction(state, -1))\n\t\t\tthrow std::runtime_error(\"Expected a function as a second argument\");\n\t\tauto res = self.lazy_option<T>(\n\t\t\tkey,\n\t\t\tdescr,\n\t\t\t[&]() -> T {\n\t\t\t\tlua::State::check_status(state, lua_pcall(state, 0, 1, 0));\n\t\t\t\ttry { return lua::Converter<T>::extract(state, -1); }\n\t\t\t\tcatch (...) {\n\t\t\t\t CONFIGURE_THROW(\n\t\t\t\t error::BuildError(\"The lua callback for option '\" + key +\n\t\t\t\t \"' didn't return a valid value\")\n\t\t\t\t << error::nested(std::current_exception()));\n\t\t\t }\n\t\t\t});\n\t\tlua::Converter<T>::push(state, std::move(res));\n\t\treturn 1;\n\t}\n\n\ttemplate<log::Level level>\n\tstatic int Build_log(lua_State* state)\n\t{\n\t\tlua::Converter<std::reference_wrapper<Build>>::extract(state, 1);\n\t\tstd::string msg;\n\t\tfor (int i = 2, len = lua_gettop(state); i <= len; ++i)\n\t\t{\n\t\t\tif (!msg.empty()) msg.push_back(' ');\n\t\t\tmsg += luaL_tolstring(state, i, nullptr);\n\t\t}\n\t\tif (level == log::Level::error)\n\t\t\tCONFIGURE_THROW(error::BuildError(msg));\n\t\tlog::log<level>(msg);\n\t\treturn 0;\n\t}\n\n\tstatic int Build_configure(lua_State* state)\n\t{\n\t\tauto& self = lua::Converter<std::reference_wrapper<Build>>::extract(state, 1);\n\t\tfs::path dir = lua::Converter<fs::path>::extract(state, 2);\n\t\tself.get().configure(self.get().project_directory(), dir);\n\t\treturn 0;\n\t}\n\n\tvoid bind_build(lua::State& state)\n\t{\n\t\t\/\/\/ Represent a build.\n\t\t\/\/ @classmod Build\n\t\tlua::Type<Build, std::reference_wrapper<Build>>(state)\n\t\t \/\/\/ Current project directory @{Path}.\n\t\t \/\/ @function Build:project_directory\n\t\t .def(\"project_directory\", &Build::project_directory)\n\n\t\t \/\/\/ Configure a sub-project\n\t\t \/\/ @function Build:configure\n\t\t \/\/ @param Path relative path to the sub-project directory\n\t\t .def(\"configure\", &Build_configure)\n\n\t\t \/\/\/ Current build directory @{Path}.\n\t\t \/\/ @function Build:directory\n\t\t .def(\"directory\", &Build::directory)\n\n\t\t \/\/\/ Build root node\n\t\t \/\/ @function Build:root_node\n\t\t .def(\"root_node\", &Build::root_node)\n\n\t\t \/\/\/ Source @{Node} associated to a @{Path}.\n\t\t \/\/ @tparam Path path relative path to a source file\n\t\t \/\/ @function Build:source_node\n\t\t .def(\"source_node\", &Build::source_node)\n\n\t\t \/\/\/ Target @{Node} associated to a @{Path}.\n\t\t \/\/ @tparam Path path relative path to a built file\n\t\t \/\/ @function Build:target_node\n\t\t .def(\"target_node\", &Build::target_node)\n\n\t\t \/\/\/ Directory @{Node} associated to a @{Path}.\n\t\t \/\/ @tparam Path path Absolute path to a directory\n\t\t \/\/ @function Build:directory_node\n\t\t .def(\"directory_node\", &Build::directory_node)\n\n\t\t \/\/\/ File @{Node} associated to a @{Path}.\n\t\t \/\/ @tparam Path path Absolute path to a file\n\t\t \/\/ @function Build:file_node\n\t\t .def(\"file_node\", &Build::file_node)\n\n\t\t \/\/\/ Virtual @{Node}.\n\t\t \/\/ @tparam string name A non-empty string\n\t\t \/\/ @function Build:virtual_node\n\t\t .def(\"virtual_node\", &Build::virtual_node)\n\n\t\t \/\/\/ Add a rule to the build.\n\t\t \/\/ @tparam Rule rule Rule to add\n\t\t \/\/ @function Build:add_rule\n\t\t .def(\"add_rule\", &Build::add_rule)\n\n\t\t \/\/\/ Associated @{Filesystem} instance.\n\t\t \/\/ @function Build:fs\n\t\t .def<lua::return_policy::ref>(\"fs\", &Build::fs)\n\n\t\t \/\/\/ Associated @{Environ} instance.\n\t\t \/\/ @function Build:env\n\t\t .def<lua::return_policy::ref>(\"env\", &Build::env)\n\n\t\t \/\/\/ Path to the configure executable\n\t\t \/\/ @function Build:configure_program\n\t\t .def<lua::return_policy::copy>(\n\t\t \"configure_program\", &Build::configure_program)\n\n\t\t \/\/\/ Declare an option of type @{string} and return it's value.\n\t\t \/\/ @string name\n\t\t \/\/ @string description\n\t\t \/\/ @tparam[opt] string default_value\n\t\t \/\/ @treturn string|nil Associated value\n\t\t \/\/ @function Build:string_option\n\t\t .def( \"string_option\", &Build_option<std::string> )\n\n\t\t \/\/\/ Declare an option of type int and return it's value.\n\t\t \/\/ @string name\n\t\t \/\/ @string description\n\t\t \/\/ @tparam[opt] int default_value\n\t\t \/\/ @treturn int|nil Associated value\n\t\t \/\/ @function Build:int_option\n\t\t .def( \"int_option\", &Build_option<int64_t> )\n\n\t\t \/\/\/ Declare an option of type bool and return it's value.\n\t\t \/\/ @string name\n\t\t \/\/ @string description\n\t\t \/\/ @tparam[opt] bool default_value\n\t\t \/\/ @treturn bool|nil Associated value\n\t\t \/\/ @function Build:bool_option\n\t\t .def( \"bool_option\", &Build_option<bool> )\n\n\t\t \/\/\/ Declare an option of type @{Path} and return it's value.\n\t\t \/\/ @string name\n\t\t \/\/ @string description\n\t\t \/\/ @tparam[opt] Path default_value\n\t\t \/\/ @treturn Path|nil Associated value\n\t\t \/\/ @function Build:path_option\n\t\t .def( \"path_option\", &Build_option<fs::path> )\n\n\t\t \/\/\/ Declare a lazy option of type @{string} and return it's value.\n\t\t \/\/ @string name\n\t\t \/\/ @string description\n\t\t \/\/ @tparam[opt] string default_value\n\t\t \/\/ @treturn string|nil Associated value\n\t\t \/\/ @function Build:string_option\n\t\t .def( \"lazy_string_option\", &Build_lazy_option<std::string> )\n\n\t\t \/\/\/ Declare a lazy option of type int and return it's value.\n\t\t \/\/ @string name\n\t\t \/\/ @string description\n\t\t \/\/ @tparam[opt] int default_value\n\t\t \/\/ @treturn int|nil Associated value\n\t\t \/\/ @function Build:int_option\n\t\t .def( \"lazy_int_option\", &Build_lazy_option<int64_t> )\n\n\t\t \/\/\/ Declare a lazy option of type bool and return it's value.\n\t\t \/\/ @string name\n\t\t \/\/ @string description\n\t\t \/\/ @tparam[opt] bool default_value\n\t\t \/\/ @treturn bool|nil Associated value\n\t\t \/\/ @function Build:bool_option\n\t\t .def( \"lazy_bool_option\", &Build_lazy_option<bool> )\n\n\t\t \/\/\/ Declare a lazy option of type @{Path} and return it's value.\n\t\t \/\/ @string name\n\t\t \/\/ @string description\n\t\t \/\/ @tparam[opt] Path default_value\n\t\t \/\/ @treturn Path|nil Associated value\n\t\t \/\/ @function Build:path_option\n\t\t .def( \"lazy_path_option\", &Build_lazy_option<fs::path> )\n\n\t\t \/\/\/ The host platform.\n\t\t \/\/ @treturn Platform\n\t\t \/\/ @function Build:host_platform\n\t\t .def<lua::return_policy::ref>(\"host\", &Build::host)\n\n\t\t \/\/\/ The target platform.\n\t\t \/\/ @treturn Platform\n\t\t \/\/ @function Build:target_platform\n\t\t .def<lua::return_policy::ref>(\"target\", &Build::target)\n\n\t\t \/\/\/ Log a debug message.\n\t\t \/\/ @param args...\n\t\t \/\/ @function Build:debug\n\t\t .def( \"debug\", &Build_log<log::Level::verbose> )\n\n\t\t \/\/\/ Log an informational message.\n\t\t \/\/ @param args...\n\t\t \/\/ @function Build:status\n\t\t .def( \"status\", &Build_log<log::Level::status> )\n\n\t\t \/\/\/ Log a warning message.\n\t\t \/\/ @param args...\n\t\t \/\/ @function Build:warning\n\t\t .def( \"warning\", &Build_log<log::Level::warning> )\n\n\t\t \/\/\/ Stop the configuration with an error message.\n\t\t \/\/ @param args...\n\t\t \/\/ @function Build:error\n\t\t .def(\"error\", &Build_log<log::Level::error>);\n\t}\n\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"helpers\/huffmanish.hh\"\n\nint main(int argc, char* argv[]){\n\tHuffman huffmanclass(argv[1]); \/\/initialize\n\thuffmanclass.assign_values();\n\thuffmanclass.produce_lookups();\n\n\tutil::FilePiece filein(argv[1]);\n\n\tline_text firstline = splitLine(filein.ReadLine());\n\n\tstd::vector<unsigned int> encoding = huffmanclass.encode_line(firstline);\n\n\tfor (std::vector<unsigned int>::iterator it = encoding.begin(); it != encoding.end(); it++){\n\t\tstd::cout << *it << \" \";\n\t}\n\tstd::cout << std::endl;\n\n\tstd::map<unsigned int, std::string> lookup_target_phrase = huffmanclass.get_target_lookup_map();\n\tstd::map<unsigned int, std::string> lookup_probabilities = huffmanclass.get_probabilities_lookup_map();\n\tstd::map<unsigned int, std::string> lookup_word_all1 = huffmanclass.get_word_all1_lookup_map();\n\tstd::map<unsigned int, std::string> lookup_word_all2 = huffmanclass.get_word_all2_lookup_map();\n\n\tHuffmanDecoder decoder(&lookup_target_phrase, &lookup_probabilities,\n\t &lookup_word_all1, &lookup_word_all2);\n\n\tdecoder.decode_line(encoding);\n}<commit_msg>More testing code<commit_after>#include \"helpers\/huffmanish.hh\"\n\nint main(int argc, char* argv[]){\n\tHuffman huffmanclass(argv[1]); \/\/initialize\n\thuffmanclass.assign_values();\n\thuffmanclass.produce_lookups();\n\thuffmanclass.serialize_maps(\"\/tmp\/maps\/\");\n\n\tutil::FilePiece filein(argv[1]);\n\n\tline_text firstline = splitLine(filein.ReadLine());\n\n\tstd::vector<unsigned int> encoding = huffmanclass.encode_line(firstline);\n\n\tfor (std::vector<unsigned int>::iterator it = encoding.begin(); it != encoding.end(); it++){\n\t\tstd::cout << *it << \" \";\n\t}\n\tstd::cout << std::endl;\n\n\tstd::map<unsigned int, std::string> lookup_target_phrase = huffmanclass.get_target_lookup_map();\n\tstd::map<unsigned int, std::string> lookup_probabilities = huffmanclass.get_probabilities_lookup_map();\n\tstd::map<unsigned int, std::string> lookup_word_all1 = huffmanclass.get_word_all1_lookup_map();\n\tstd::map<unsigned int, std::string> lookup_word_all2 = huffmanclass.get_word_all2_lookup_map();\n\n\tHuffmanDecoder decoder(&lookup_target_phrase, &lookup_probabilities,\n\t &lookup_word_all1, &lookup_word_all2);\n\n\ttarget_text tmp = decoder.decode_line(encoding);\n\tstd::cout << decoder.getTargetWordsFromIDs(tmp.target_phrase) << \" \";\n\n\tfor (std::vector<float>::iterator it = tmp.prob.begin(); it != tmp.prob.end(); it++){\n\t\tstd::cout << *it << \" \";\n\t}\n\n\tstd::cout << tmp.word_all1[0] << \" \" << tmp.word_all2[0] << std::endl;\n}<|endoftext|>"} {"text":"<commit_before>\/* Copyright 2017 QReal Research Group\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License. *\/\n\n#include \"pioneerStateMachineGenerator.h\"\n\n#include <generatorBase\/semanticTree\/semanticNode.h>\n#include <generatorBase\/semanticTree\/simpleNode.h>\n\nusing namespace pioneer::lua;\nusing namespace generatorBase;\nusing namespace generatorBase::semantics;\n\nPioneerStateMachineGenerator::PioneerStateMachineGenerator(\n\t\tconst qrRepo::RepoApi &repo\n\t\t, qReal::ErrorReporterInterface &errorReporter\n\t\t, generatorBase::GeneratorCustomizer &customizer\n\t\t, generatorBase::PrimaryControlFlowValidator &validator\n\t\t, const qReal::Id &diagramId\n\t\t, QObject *parent\n\t\t, bool isThisDiagramMain)\n\t: GotoControlFlowGenerator(repo, errorReporter, customizer, validator, diagramId, parent, isThisDiagramMain)\n{\n\tmAsynchronousNodes << \"GeoTakeoff\" << \"GeoLanding\" << \"GoToPoint\";\n}\n\nvoid PioneerStateMachineGenerator::registerNodeHook(std::function<void(const qReal::Id)> hook)\n{\n\tmNodeHooks.append(hook);\n}\n\nvoid PioneerStateMachineGenerator::performGeneration()\n{\n\tmSemanticTreeManager.reset(new SemanticTreeManager(*mSemanticTree, mErrorReporter, mErrorsOccured));\n\tGotoControlFlowGenerator::performGeneration();\n}\n\nvoid PioneerStateMachineGenerator::visitRegular(const qReal::Id &id, const QList<LinkInfo> &links)\n{\n\t\/\/ Base class method checks for subprogram calls, which is irrelevant for now, but does not hurt and hopefully\n\t\/\/ will be needed later.\n\tControlFlowGeneratorBase::visitRegular(id, links);\n\n\tSimpleNode * const thisNode = static_cast<SimpleNode *>(mSemanticTree->findNodeFor(id));\n\tSemanticNode *nextNode = nullptr;\n\tconst qReal::Id target = links[0].target;\n\n\tif (mAsynchronousNodes.contains(id.element())) {\n\t\tif (mSemanticTree->findNodeFor(target)) {\n\t\t\t\/\/ thisNode is asyncronous node that transfers control to already visited node.\n\t\t\t\/\/ Generated code for thisNode will initiate asynchronous action and all we need to do is to generate\n\t\t\t\/\/ transition to a state which will execute target block when this block finishes its asynchronous\n\t\t\t\/\/ operation.\n\t\t\tnextNode = produceGotoNode(target);\n\t\t\tmSemanticTreeManager->addAfter(thisNode, nextNode);\n\n\t\t\tif (!mLabeledNodes.contains(target)) {\n\t\t\t\t\/\/\n\t\t\t\t\/\/ Target node, despite being already visited, does not have a label, it means that it is a part of a\n\t\t\t\t\/\/ synchronous fragment. We copy that fragment from this node to the first asyncronous node and\n\t\t\t\t\/\/ label a start of the copied fragment. At the end of the fragment we will generate said asynchronous\n\t\t\t\t\/\/ node, which will initiate asynchronous operation, and then transition to its next state, which will\n\t\t\t\t\/\/ continue execution when operation is done.\n\t\t\t\t\/\/\n\t\t\t\t\/\/ It will confuse \"findNodeFor(id)\" (there will be many semantic nodes for a block with given id), but\n\t\t\t\t\/\/ we actually do not care which copy will be used later, since they are the same.\n\t\t\t\t\/\/\n\t\t\t\tnextNode = copySynchronousFragment(nextNode, target, true);\n\t\t\t}\n\n\t\t\tif (mSemanticTreeManager->isTopLevelNode(thisNode)) {\n\t\t\t\tSemanticNode * const endNode = produceEndOfHandlerNode();\n\t\t\t\tmSemanticTreeManager->addAfter(nextNode, endNode);\n\t\t\t}\n\t\t} else {\n\t\t\t\/\/ thisNode is asynchronous node that transfers control to a node that has not been visited yet. Generating\n\t\t\t\/\/ transition into a state associated with that node and then a new handler for target node itself.\n\t\t\tnextNode = mSemanticTreeManager->produceLabeledNode(target);\n\t\t\tif (!nextNode) {\n\t\t\t\treturn;\n\t\t\t} else {\n\t\t\t\tmLabeledNodes << nextNode->id();\n\t\t\t}\n\n\t\t\tSemanticNode * const gotoNode = produceGotoNode(target);\n\t\t\tmSemanticTreeManager->addAfter(thisNode, gotoNode);\n\n\t\t\t\/\/ Labeled node can not be a part of a zone (i.e. \"then\" or \"else\" branch), it shall be generated in top\n\t\t\t\/\/ level zone.\n\t\t\tif (mSemanticTreeManager->isTopLevelNode(thisNode)) {\n\t\t\t\tSemanticNode * const endNode = produceEndOfHandlerNode();\n\t\t\t\tmSemanticTreeManager->addAfter(gotoNode, endNode);\n\t\t\t\tmSemanticTreeManager->addAfter(endNode, nextNode);\n\t\t\t} else {\n\t\t\t\t\/\/ Getting parent node (i.e. If statement to the branch of which our node belongs).\n\t\t\t\tNonZoneNode *aParent = mSemanticTreeManager->parent(thisNode);\n\t\t\t\twhile (!mSemanticTreeManager->isTopLevelNode(aParent)) {\n\t\t\t\t\taParent = mSemanticTreeManager->parent(aParent);\n\t\t\t\t}\n\n\t\t\t\t\/\/ Skipping \"end\" that finishes handler with If.\n\t\t\t\tSemanticNode * const endOfHandler = mSemanticTreeManager->findSibling(\n\t\t\t\t\t\taParent\n\t\t\t\t\t\t, [](SemanticNode *node){ return node->id().element() == \"EndOfHandler\"; });\n\n\t\t\t\tif (!endOfHandler) {\n\t\t\t\t\tmErrorReporter.addError(tr(\"Can not find end of an If statement, generation internal error or \"\n\t\t\t\t\t\t\t\"too complex algorithmic construction.\"));\n\t\t\t\t\tmErrorsOccured = true;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\t\/\/ Adding our labeled node denoting new handler after the end of a handler with If node.\n\t\t\t\tmSemanticTreeManager->addAfter(endOfHandler, nextNode);\n\t\t\t}\n\t\t}\n\t} else {\n\t\tif (!mSemanticTree->findNodeFor(target)) {\n\t\t\t\/\/ It is not an asynchronous node, generating as-is.\n\t\t\tnextNode = mSemanticTree->produceNodeFor(target);\n\t\t\tmSemanticTreeManager->addAfter(thisNode, nextNode);\n\t\t} else {\n\t\t\t\/\/ Synchronous node leading to already visited node. Need some copypasting of synchronous fragments,\n\t\t\t\/\/ or else we will stall the program waiting for an event that was never initiated.\n\t\t\tcopySynchronousFragment(thisNode, target, false);\n\t\t}\n\t}\n}\n\nvoid PioneerStateMachineGenerator::visitConditional(const qReal::Id &id, const QList<LinkInfo> &links)\n{\n\tQ_UNUSED(links)\n\n\tconst QPair<LinkInfo, LinkInfo> branches(ifBranchesFor(id));\n\tconst LinkInfo thenLink = branches.first;\n\tconst LinkInfo elseLink = branches.second;\n\n\tIfNode * const thisNode = static_cast<IfNode *>(mSemanticTree->findNodeFor(id));\n\n\tmSemanticTreeManager->addToZone(thisNode->thenZone(), thenLink.target);\n\tmSemanticTreeManager->addToZone(thisNode->elseZone(), elseLink.target);\n\n\tif (mSemanticTreeManager->isTopLevelNode(thisNode)) {\n\t\tSemanticNode * const endNode = produceEndOfHandlerNode();\n\t\tmSemanticTreeManager->addAfter(thisNode, endNode);\n\t}\n}\n\nvoid PioneerStateMachineGenerator::visitFinal(const qReal::Id &id, const QList<LinkInfo> &links)\n{\n\tgeneratorBase::GotoControlFlowGenerator::visitFinal(id, links);\n\n\t\/\/ Here we are going to add finishing end-of-handler node in case it is missing (for example, diagrams like\n\t\/\/ \"Initial Node\" -> \"Final Node\" will not generate it automatically).\n\t\/\/ It is a kind of hack because asynchronous handler shall be a first-class entity and a zone node.\n\n\tSimpleNode * const thisNode = static_cast<SimpleNode *>(mSemanticTree->findNodeFor(id));\n\n\t\/\/ Getting root node.\n\tNonZoneNode *aParent = mSemanticTreeManager->parent(thisNode);\n\twhile (!mSemanticTreeManager->isTopLevelNode(aParent)) {\n\t\taParent = mSemanticTreeManager->parent(aParent);\n\t}\n\n\t\/\/ Searching for end-of-handler node.\n\tSemanticNode * endOfHandler = mSemanticTreeManager->findSibling(\n\t\t\taParent\n\t\t\t, [](SemanticNode *node){ return node->id().element() == \"EndOfHandler\"; });\n\n\tif (!endOfHandler) {\n\t\t\/\/ If not found, create and add one.\n\t\tendOfHandler = produceEndOfHandlerNode();\n\t\tmSemanticTreeManager->addAfter(thisNode, endOfHandler);\n\t}\n}\n\nvoid PioneerStateMachineGenerator::visit(const qReal::Id &nodeId, QList<utils::DeepFirstSearcher::LinkInfo> &links)\n{\n\tgeneratorBase::GotoControlFlowGenerator::visit(nodeId, links);\n\tfor (const auto &hook : mNodeHooks) {\n\t\thook(nodeId);\n\t}\n}\n\nSemanticNode *PioneerStateMachineGenerator::copySynchronousFragment(\n\t\tSemanticNode *after\n\t\t, const qReal::Id &from\n\t\t, bool withLabel)\n{\n\tNonZoneNode *oldTarget = dynamic_cast<NonZoneNode *>(mSemanticTree->findNodeFor(from));\n\tif (!oldTarget) {\n\t\t\/\/\/ @todo: actually, why not?\n\t\tmErrorReporter.addError(tr(\"Can not close a loop on algorithmic block.\"));\n\t\tmErrorsOccured = true;\n\t\treturn nullptr;\n\t}\n\n\tNonZoneNode *fragmentStartNode = withLabel\n\t\t\t? mSemanticTreeManager->produceLabeledNode(from)\n\t\t\t: dynamic_cast<NonZoneNode *>(mSemanticTree->produceNodeFor(from));\n\n\tif (!fragmentStartNode) {\n\t\treturn nullptr;\n\t} else {\n\t\tmLabeledNodes << fragmentStartNode->id();\n\t}\n\n\tif (!dynamic_cast<NonZoneNode *>(after)) {\n\t\tmErrorReporter.addError(tr(\"Generation internal error, non-zone node is a start of a fragment.\"));\n\t\tmErrorsOccured = true;\n\t\treturn nullptr;\n\t}\n\n\t\/\/ End-of-handler shall go before every labeled node, since label here is actually a start of a new handler.\n\tSemanticNode * const endNode = produceEndOfHandlerNode();\n\tmSemanticTreeManager->addAfter(after, endNode);\n\n\tmSemanticTreeManager->addAfter(endNode, fragmentStartNode);\n\n\tif (isAsynchronous(fragmentStartNode)) {\n\t\t\/\/ Synchronous fragment is trivial and its first node is asynchronous. Generating transition from it and we're\n\t\t\/\/ done here.\n\t\t\/\/\n\t\t\/\/ Using oldTarget because fragmentStartNode was just added and does not have siblings, but it is a copy\n\t\t\/\/ of oldTarget.\n\t\tconst auto rightSibling = mSemanticTreeManager->findRightSibling(oldTarget);\n\t\tif (rightSibling) {\n\t\t\tauto gotoNode = produceGotoNode(rightSibling->id());\n\t\t\tfragmentStartNode->appendSibling(gotoNode);\n\t\t\treturn gotoNode;\n\t\t} else {\n\t\t\tmErrorReporter.addError(tr(\"Generation internal error, asynchronous fragment start node generation \" \\\n\t\t\t\t\t\"failed.\"));\n\t\t\tmErrorsOccured = true;\n\t\t}\n\n\t\treturn nullptr;\n\t}\n\n\tauto siblings = mSemanticTreeManager->copyRightSiblingsUntil(\n\t\t\toldTarget\n\t\t\t, [this](SemanticNode * node){ return isAsynchronous(node); });\n\n\tif (siblings.isEmpty()) {\n\t\tmErrorReporter.addError(tr(\"Loop can not be closed on a block that is last in its structural construct.\"));\n\t\tmErrorsOccured = true;\n\t\treturn nullptr;\n\t}\n\n\tif (isAsynchronous(siblings.last())) {\n\t\t\/\/ Synchronous fragment finished with asynchronous node\n\t\tfragmentStartNode->appendSiblings(siblings);\n\n\t\t\/\/ Now we shall look for the end of original fragment: find asynchronous node on which a fragment shall be\n\t\t\/\/ ending and get its target node. Assuming that they are already visited (here we assuming that it is a loop,\n\t\t\/\/ may not be the case when logical branching blocks will be introduced).\n\t\tauto asynchronousNode = mSemanticTreeManager->findSibling(\n\t\t\t\toldTarget\n\t\t\t\t, [this](SemanticNode * node){ return isAsynchronous(node); });\n\n\t\tconst auto asynchronousNodeTarget = mSemanticTreeManager->findRightSibling(asynchronousNode);\n\t\tif (!asynchronousNodeTarget) {\n\t\t\tmErrorReporter.addError(tr(\"Generation internal error, asynchronous node does not have target node.\"));\n\t\t\tmErrorsOccured = true;\n\t\t\treturn nullptr;\n\t\t}\n\n\t\tauto gotoNode = produceGotoNode(asynchronousNodeTarget->id());\n\t\tfragmentStartNode->appendSibling(gotoNode);\n\t\treturn gotoNode;\n\t} else {\n\t\tmErrorReporter.addError(tr(\"Purely synchronous loops are not supported yet.\"));\n\t\tmErrorsOccured = true;\n\t}\n\n\treturn nullptr;\n}\n\nbool PioneerStateMachineGenerator::isAsynchronous(const SemanticNode * const node) const\n{\n\treturn mAsynchronousNodes.contains(node->id().element());\n}\n\nSemanticNode *PioneerStateMachineGenerator::produceEndOfHandlerNode()\n{\n\tqReal::Id syntheticId = qReal::Id::createElementId(\"synthetic\", \"synthetic\", \"EndOfHandler\");\n\tSimpleNode * const result = mSemanticTree->produceSimple(syntheticId);\n\t\/\/ No need for special handling, from the point of view of a generator it is just some simple node.\n\tresult->bindToSyntheticConstruction(SimpleNode::noSytheticBinding);\n\treturn result;\n}\n<commit_msg>Corrected error message<commit_after>\/* Copyright 2017 QReal Research Group\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License. *\/\n\n#include \"pioneerStateMachineGenerator.h\"\n\n#include <generatorBase\/semanticTree\/semanticNode.h>\n#include <generatorBase\/semanticTree\/simpleNode.h>\n\nusing namespace pioneer::lua;\nusing namespace generatorBase;\nusing namespace generatorBase::semantics;\n\nPioneerStateMachineGenerator::PioneerStateMachineGenerator(\n\t\tconst qrRepo::RepoApi &repo\n\t\t, qReal::ErrorReporterInterface &errorReporter\n\t\t, generatorBase::GeneratorCustomizer &customizer\n\t\t, generatorBase::PrimaryControlFlowValidator &validator\n\t\t, const qReal::Id &diagramId\n\t\t, QObject *parent\n\t\t, bool isThisDiagramMain)\n\t: GotoControlFlowGenerator(repo, errorReporter, customizer, validator, diagramId, parent, isThisDiagramMain)\n{\n\tmAsynchronousNodes << \"GeoTakeoff\" << \"GeoLanding\" << \"GoToPoint\";\n}\n\nvoid PioneerStateMachineGenerator::registerNodeHook(std::function<void(const qReal::Id)> hook)\n{\n\tmNodeHooks.append(hook);\n}\n\nvoid PioneerStateMachineGenerator::performGeneration()\n{\n\tmSemanticTreeManager.reset(new SemanticTreeManager(*mSemanticTree, mErrorReporter, mErrorsOccured));\n\tGotoControlFlowGenerator::performGeneration();\n}\n\nvoid PioneerStateMachineGenerator::visitRegular(const qReal::Id &id, const QList<LinkInfo> &links)\n{\n\t\/\/ Base class method checks for subprogram calls, which is irrelevant for now, but does not hurt and hopefully\n\t\/\/ will be needed later.\n\tControlFlowGeneratorBase::visitRegular(id, links);\n\n\tSimpleNode * const thisNode = static_cast<SimpleNode *>(mSemanticTree->findNodeFor(id));\n\tSemanticNode *nextNode = nullptr;\n\tconst qReal::Id target = links[0].target;\n\n\tif (mAsynchronousNodes.contains(id.element())) {\n\t\tif (mSemanticTree->findNodeFor(target)) {\n\t\t\t\/\/ thisNode is asyncronous node that transfers control to already visited node.\n\t\t\t\/\/ Generated code for thisNode will initiate asynchronous action and all we need to do is to generate\n\t\t\t\/\/ transition to a state which will execute target block when this block finishes its asynchronous\n\t\t\t\/\/ operation.\n\t\t\tnextNode = produceGotoNode(target);\n\t\t\tmSemanticTreeManager->addAfter(thisNode, nextNode);\n\n\t\t\tif (!mLabeledNodes.contains(target)) {\n\t\t\t\t\/\/\n\t\t\t\t\/\/ Target node, despite being already visited, does not have a label, it means that it is a part of a\n\t\t\t\t\/\/ synchronous fragment. We copy that fragment from this node to the first asyncronous node and\n\t\t\t\t\/\/ label a start of the copied fragment. At the end of the fragment we will generate said asynchronous\n\t\t\t\t\/\/ node, which will initiate asynchronous operation, and then transition to its next state, which will\n\t\t\t\t\/\/ continue execution when operation is done.\n\t\t\t\t\/\/\n\t\t\t\t\/\/ It will confuse \"findNodeFor(id)\" (there will be many semantic nodes for a block with given id), but\n\t\t\t\t\/\/ we actually do not care which copy will be used later, since they are the same.\n\t\t\t\t\/\/\n\t\t\t\tnextNode = copySynchronousFragment(nextNode, target, true);\n\t\t\t}\n\n\t\t\tif (mSemanticTreeManager->isTopLevelNode(thisNode)) {\n\t\t\t\tSemanticNode * const endNode = produceEndOfHandlerNode();\n\t\t\t\tmSemanticTreeManager->addAfter(nextNode, endNode);\n\t\t\t}\n\t\t} else {\n\t\t\t\/\/ thisNode is asynchronous node that transfers control to a node that has not been visited yet. Generating\n\t\t\t\/\/ transition into a state associated with that node and then a new handler for target node itself.\n\t\t\tnextNode = mSemanticTreeManager->produceLabeledNode(target);\n\t\t\tif (!nextNode) {\n\t\t\t\treturn;\n\t\t\t} else {\n\t\t\t\tmLabeledNodes << nextNode->id();\n\t\t\t}\n\n\t\t\tSemanticNode * const gotoNode = produceGotoNode(target);\n\t\t\tmSemanticTreeManager->addAfter(thisNode, gotoNode);\n\n\t\t\t\/\/ Labeled node can not be a part of a zone (i.e. \"then\" or \"else\" branch), it shall be generated in top\n\t\t\t\/\/ level zone.\n\t\t\tif (mSemanticTreeManager->isTopLevelNode(thisNode)) {\n\t\t\t\tSemanticNode * const endNode = produceEndOfHandlerNode();\n\t\t\t\tmSemanticTreeManager->addAfter(gotoNode, endNode);\n\t\t\t\tmSemanticTreeManager->addAfter(endNode, nextNode);\n\t\t\t} else {\n\t\t\t\t\/\/ Getting parent node (i.e. If statement to the branch of which our node belongs).\n\t\t\t\tNonZoneNode *aParent = mSemanticTreeManager->parent(thisNode);\n\t\t\t\twhile (!mSemanticTreeManager->isTopLevelNode(aParent)) {\n\t\t\t\t\taParent = mSemanticTreeManager->parent(aParent);\n\t\t\t\t}\n\n\t\t\t\t\/\/ Skipping \"end\" that finishes handler with If.\n\t\t\t\tSemanticNode * const endOfHandler = mSemanticTreeManager->findSibling(\n\t\t\t\t\t\taParent\n\t\t\t\t\t\t, [](SemanticNode *node){ return node->id().element() == \"EndOfHandler\"; });\n\n\t\t\t\tif (!endOfHandler) {\n\t\t\t\t\tmErrorReporter.addError(tr(\"Can not find end of an If statement, generation internal error or \"\n\t\t\t\t\t\t\t\"too complex algorithmic construction.\"));\n\t\t\t\t\tmErrorsOccured = true;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\t\/\/ Adding our labeled node denoting new handler after the end of a handler with If node.\n\t\t\t\tmSemanticTreeManager->addAfter(endOfHandler, nextNode);\n\t\t\t}\n\t\t}\n\t} else {\n\t\tif (!mSemanticTree->findNodeFor(target)) {\n\t\t\t\/\/ It is not an asynchronous node, generating as-is.\n\t\t\tnextNode = mSemanticTree->produceNodeFor(target);\n\t\t\tmSemanticTreeManager->addAfter(thisNode, nextNode);\n\t\t} else {\n\t\t\t\/\/ Synchronous node leading to already visited node. Need some copypasting of synchronous fragments,\n\t\t\t\/\/ or else we will stall the program waiting for an event that was never initiated.\n\t\t\tcopySynchronousFragment(thisNode, target, false);\n\t\t}\n\t}\n}\n\nvoid PioneerStateMachineGenerator::visitConditional(const qReal::Id &id, const QList<LinkInfo> &links)\n{\n\tQ_UNUSED(links)\n\n\tconst QPair<LinkInfo, LinkInfo> branches(ifBranchesFor(id));\n\tconst LinkInfo thenLink = branches.first;\n\tconst LinkInfo elseLink = branches.second;\n\n\tIfNode * const thisNode = static_cast<IfNode *>(mSemanticTree->findNodeFor(id));\n\n\tmSemanticTreeManager->addToZone(thisNode->thenZone(), thenLink.target);\n\tmSemanticTreeManager->addToZone(thisNode->elseZone(), elseLink.target);\n\n\tif (mSemanticTreeManager->isTopLevelNode(thisNode)) {\n\t\tSemanticNode * const endNode = produceEndOfHandlerNode();\n\t\tmSemanticTreeManager->addAfter(thisNode, endNode);\n\t}\n}\n\nvoid PioneerStateMachineGenerator::visitFinal(const qReal::Id &id, const QList<LinkInfo> &links)\n{\n\tgeneratorBase::GotoControlFlowGenerator::visitFinal(id, links);\n\n\t\/\/ Here we are going to add finishing end-of-handler node in case it is missing (for example, diagrams like\n\t\/\/ \"Initial Node\" -> \"Final Node\" will not generate it automatically).\n\t\/\/ It is a kind of hack because asynchronous handler shall be a first-class entity and a zone node.\n\n\tSimpleNode * const thisNode = static_cast<SimpleNode *>(mSemanticTree->findNodeFor(id));\n\n\t\/\/ Getting root node.\n\tNonZoneNode *aParent = mSemanticTreeManager->parent(thisNode);\n\twhile (!mSemanticTreeManager->isTopLevelNode(aParent)) {\n\t\taParent = mSemanticTreeManager->parent(aParent);\n\t}\n\n\t\/\/ Searching for end-of-handler node.\n\tSemanticNode * endOfHandler = mSemanticTreeManager->findSibling(\n\t\t\taParent\n\t\t\t, [](SemanticNode *node){ return node->id().element() == \"EndOfHandler\"; });\n\n\tif (!endOfHandler) {\n\t\t\/\/ If not found, create and add one.\n\t\tendOfHandler = produceEndOfHandlerNode();\n\t\tmSemanticTreeManager->addAfter(thisNode, endOfHandler);\n\t}\n}\n\nvoid PioneerStateMachineGenerator::visit(const qReal::Id &nodeId, QList<utils::DeepFirstSearcher::LinkInfo> &links)\n{\n\tgeneratorBase::GotoControlFlowGenerator::visit(nodeId, links);\n\tfor (const auto &hook : mNodeHooks) {\n\t\thook(nodeId);\n\t}\n}\n\nSemanticNode *PioneerStateMachineGenerator::copySynchronousFragment(\n\t\tSemanticNode *after\n\t\t, const qReal::Id &from\n\t\t, bool withLabel)\n{\n\tNonZoneNode *oldTarget = dynamic_cast<NonZoneNode *>(mSemanticTree->findNodeFor(from));\n\tif (!oldTarget) {\n\t\t\/\/\/ @todo: actually, why not?\n\t\tmErrorReporter.addError(tr(\"Can not close a loop on algorithmic block.\"));\n\t\tmErrorsOccured = true;\n\t\treturn nullptr;\n\t}\n\n\tNonZoneNode *fragmentStartNode = withLabel\n\t\t\t? mSemanticTreeManager->produceLabeledNode(from)\n\t\t\t: dynamic_cast<NonZoneNode *>(mSemanticTree->produceNodeFor(from));\n\n\tif (!fragmentStartNode) {\n\t\treturn nullptr;\n\t} else {\n\t\tmLabeledNodes << fragmentStartNode->id();\n\t}\n\n\tif (!dynamic_cast<NonZoneNode *>(after)) {\n\t\tmErrorReporter.addError(tr(\"Generation internal error, non-zone node is a start of a fragment.\"));\n\t\tmErrorsOccured = true;\n\t\treturn nullptr;\n\t}\n\n\t\/\/ End-of-handler shall go before every labeled node, since label here is actually a start of a new handler.\n\tSemanticNode * const endNode = produceEndOfHandlerNode();\n\tmSemanticTreeManager->addAfter(after, endNode);\n\n\tmSemanticTreeManager->addAfter(endNode, fragmentStartNode);\n\n\tif (isAsynchronous(fragmentStartNode)) {\n\t\t\/\/ Synchronous fragment is trivial and its first node is asynchronous. Generating transition from it and we're\n\t\t\/\/ done here.\n\t\t\/\/\n\t\t\/\/ Using oldTarget because fragmentStartNode was just added and does not have siblings, but it is a copy\n\t\t\/\/ of oldTarget.\n\t\tconst auto rightSibling = mSemanticTreeManager->findRightSibling(oldTarget);\n\t\tif (rightSibling) {\n\t\t\tauto gotoNode = produceGotoNode(rightSibling->id());\n\t\t\tfragmentStartNode->appendSibling(gotoNode);\n\t\t\treturn gotoNode;\n\t\t} else {\n\t\t\tmErrorReporter.addError(tr(\"Generation internal error, asynchronous fragment start node generation \" \\\n\t\t\t\t\t\"failed.\"));\n\t\t\tmErrorsOccured = true;\n\t\t}\n\n\t\treturn nullptr;\n\t}\n\n\tauto siblings = mSemanticTreeManager->copyRightSiblingsUntil(\n\t\t\toldTarget\n\t\t\t, [this](SemanticNode * node){ return isAsynchronous(node); });\n\n\tif (siblings.isEmpty()) {\n\t\tmErrorReporter.addError(tr(\"Loop can not be closed on a block that is last in its structural construct.\"));\n\t\tmErrorsOccured = true;\n\t\treturn nullptr;\n\t}\n\n\tif (isAsynchronous(siblings.last())) {\n\t\t\/\/ Synchronous fragment finished with asynchronous node\n\t\tfragmentStartNode->appendSiblings(siblings);\n\n\t\t\/\/ Now we shall look for the end of original fragment: find asynchronous node on which a fragment shall be\n\t\t\/\/ ending and get its target node. Assuming that they are already visited (here we assuming that it is a loop,\n\t\t\/\/ may not be the case when logical branching blocks will be introduced).\n\t\tauto asynchronousNode = mSemanticTreeManager->findSibling(\n\t\t\t\toldTarget\n\t\t\t\t, [this](SemanticNode * node){ return isAsynchronous(node); });\n\n\t\tconst auto asynchronousNodeTarget = mSemanticTreeManager->findRightSibling(asynchronousNode);\n\t\tif (!asynchronousNodeTarget) {\n\t\t\tmErrorReporter.addError(tr(\"Generation internal error, asynchronous node does not have target node.\"));\n\t\t\tmErrorsOccured = true;\n\t\t\treturn nullptr;\n\t\t}\n\n\t\tauto gotoNode = produceGotoNode(asynchronousNodeTarget->id());\n\t\tfragmentStartNode->appendSibling(gotoNode);\n\t\treturn gotoNode;\n\t} else {\n\t\tmErrorReporter.addError(tr(\"Purely synchronous loops or If branches are not supported yet.\"));\n\t\tmErrorsOccured = true;\n\t}\n\n\treturn nullptr;\n}\n\nbool PioneerStateMachineGenerator::isAsynchronous(const SemanticNode * const node) const\n{\n\treturn mAsynchronousNodes.contains(node->id().element());\n}\n\nSemanticNode *PioneerStateMachineGenerator::produceEndOfHandlerNode()\n{\n\tqReal::Id syntheticId = qReal::Id::createElementId(\"synthetic\", \"synthetic\", \"EndOfHandler\");\n\tSimpleNode * const result = mSemanticTree->produceSimple(syntheticId);\n\t\/\/ No need for special handling, from the point of view of a generator it is just some simple node.\n\tresult->bindToSyntheticConstruction(SimpleNode::noSytheticBinding);\n\treturn result;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ For conditions of distribution and use, see copyright notice in LICENSE\n\n#include \"StableHeaders.h\"\n#include \"UrhoRenderer.h\"\n#include \"GraphicsWorld.h\"\n#include \"Framework.h\"\n#include \"Placeable.h\"\n#include \"Mesh.h\"\n#include \"AnimationController.h\"\n#include \"Camera.h\"\n#include \"Light.h\"\n#include \"EnvironmentLight.h\"\n#include \"Terrain.h\"\n#include \"Sky.h\"\n#include \"ParticleSystem.h\"\n#include \"Fog.h\"\n#include \"WaterPlane.h\"\n#include \"IComponentFactory.h\"\n#include \"ConfigAPI.h\"\n#include \"SceneAPI.h\"\n#include \"AssetAPI.h\"\n#include \"Entity.h\"\n#include \"Scene\/Scene.h\"\n#include \"LoggingFunctions.h\"\n#include \"JavaScript.h\"\n#include \"JavaScriptInstance.h\"\n#include \"UrhoRendererBindings\/UrhoRendererBindings.h\"\n\n#include \"TextureAsset.h\"\n#include \"UrhoMeshAsset.h\"\n#include \"Ogre\/OgreMeshAsset.h\"\n#include \"Ogre\/OgreMaterialAsset.h\"\n#include \"Ogre\/OgreSkeletonAsset.h\"\n#include \"Ogre\/DefaultOgreMaterialProcessor.h\"\n#include \"Ogre\/OgreParticleAsset.h\"\n#include \"GenericAssetFactory.h\"\n\n#include <Urho3D\/Core\/CoreEvents.h>\n#include <Urho3D\/Core\/ProcessUtils.h>\n#include <Urho3D\/Core\/Profiler.h>\n#include <Urho3D\/Graphics\/Camera.h>\n#include <Urho3D\/Graphics\/Graphics.h>\n#include <Urho3D\/Graphics\/GraphicsEvents.h>\n#include <Urho3D\/Graphics\/Renderer.h>\n#include <Urho3D\/Graphics\/Viewport.h>\n\nusing namespace JSBindings;\n\nnamespace Tundra\n{\n\nUrhoRenderer::UrhoRenderer(Framework* owner) :\n IModule(\"UrhoRenderer\", owner)\n{\n \/\/ Register default material convertor\n RegisterOgreMaterialProcessor(new DefaultOgreMaterialProcessor(GetContext()));\n}\n\nUrhoRenderer::~UrhoRenderer()\n{\n}\n\nvoid UrhoRenderer::Load()\n{\n SceneAPI* scene = framework->Scene();\n scene->RegisterComponentFactory(ComponentFactoryPtr(new GenericComponentFactory<Placeable>()));\n scene->RegisterComponentFactory(ComponentFactoryPtr(new GenericComponentFactory<Mesh>()));\n scene->RegisterComponentFactory(ComponentFactoryPtr(new GenericComponentFactory<Camera>()));\n scene->RegisterComponentFactory(ComponentFactoryPtr(new GenericComponentFactory<Light>()));\n scene->RegisterComponentFactory(ComponentFactoryPtr(new GenericComponentFactory<AnimationController>()));\n scene->RegisterComponentFactory(ComponentFactoryPtr(new GenericComponentFactory<EnvironmentLight>()));\n scene->RegisterComponentFactory(ComponentFactoryPtr(new GenericComponentFactory<Terrain>()));\n scene->RegisterComponentFactory(ComponentFactoryPtr(new GenericComponentFactory<Sky>()));\n scene->RegisterComponentFactory(ComponentFactoryPtr(new GenericComponentFactory<ParticleSystem>));\n scene->RegisterComponentFactory(ComponentFactoryPtr(new GenericComponentFactory<Fog>));\n scene->RegisterComponentFactory(ComponentFactoryPtr(new GenericComponentFactory<WaterPlane>));\n\n \/\/\/ \\todo Check and add new supported texture extensions\n StringList textureExtensions;\n textureExtensions.Push(\".crn\"); \/\/ CRN to DDS decompression implemented in TextureAsset\n textureExtensions.Push(\".dds\");\n textureExtensions.Push(\".png\");\n textureExtensions.Push(\".jpeg\");\n textureExtensions.Push(\".jpg\");\n textureExtensions.Push(\".gif\");\n textureExtensions.Push(\".bmp\");\n textureExtensions.Push(\".tga\");\n textureExtensions.Push(\".psd\");\n\n framework->Asset()->RegisterAssetTypeFactory(AssetTypeFactoryPtr(new GenericAssetFactory<UrhoMeshAsset>(\"UrhoMesh\", \".mdl\")));\n framework->Asset()->RegisterAssetTypeFactory(AssetTypeFactoryPtr(new GenericAssetFactory<OgreMeshAsset>(\"OgreMesh\", \".mesh\")));\n framework->Asset()->RegisterAssetTypeFactory(AssetTypeFactoryPtr(new GenericAssetFactory<OgreMaterialAsset>(\"OgreMaterial\", \".material\")));\n framework->Asset()->RegisterAssetTypeFactory(AssetTypeFactoryPtr(new GenericAssetFactory<OgreSkeletonAsset>(\"OgreSkeleton\", \".skeleton\")));\n framework->Asset()->RegisterAssetTypeFactory(AssetTypeFactoryPtr(new GenericAssetFactory<OgreParticleAsset>(\"OgreParticle\", \".particle\")));\n framework->Asset()->RegisterAssetTypeFactory(AssetTypeFactoryPtr(new GenericAssetFactory<TextureAsset>(\"Texture\", textureExtensions)));\n}\n\nvoid UrhoRenderer::Initialize()\n{\n framework->RegisterRenderer(this);\n\n \/\/ Connect to scene change signals.\n framework->Scene()->SceneCreated.Connect(this, &UrhoRenderer::CreateGraphicsWorld);\n framework->Scene()->SceneAboutToBeRemoved.Connect(this, &UrhoRenderer::RemoveGraphicsWorld);\n\n \/\/ Enable the main (full-screen) viewport\n Urho3D::Renderer* rend = GetSubsystem<Urho3D::Renderer>();\n if (rend)\n {\n rend->SetNumViewports(1);\n rend->SetViewport(0, new Urho3D::Viewport(context_));\n\n \/\/ Track window position and screen mode changes to keep config up-to-date\n SubscribeToEvent(Urho3D::E_WINDOWPOS, URHO3D_HANDLER(UrhoRenderer, HandleScreenModeChange));\n SubscribeToEvent(Urho3D::E_SCREENMODE, URHO3D_HANDLER(UrhoRenderer, HandleScreenModeChange));\n \n \/\/ Disable shadows completely for now on mobile devices, as the shadow bias is problematic, and it consumes GPU performance\n \/\/ Also disable specular highlights for per-pixel lighting\n if (Urho3D::GetPlatform() == \"Android\" || Urho3D::GetPlatform() == \"iOS\")\n {\n rend->SetDrawShadows(false);\n rend->SetSpecularLighting(false);\n }\n }\n\n \/\/ Connect to JavaScript module instance creation to be able to expose the renderer classes to each instance\n JavaScript* javaScript = framework->Module<JavaScript>();\n if (javaScript)\n javaScript->ScriptInstanceCreated.Connect(this, &UrhoRenderer::OnScriptInstanceCreated);\n}\n\nvoid UrhoRenderer::Uninitialize()\n{\n framework->RegisterRenderer(0);\n Urho3D::Renderer* rend = GetSubsystem<Urho3D::Renderer>();\n \/\/ Let go of the viewport that we created. If done later at Urho Context destruction time, may cause a crash\n if (rend)\n rend->SetViewport(0, nullptr);\n}\n\nvoid UrhoRenderer::HandleScreenModeChange(StringHash \/*eventType*\/, VariantMap& \/*eventData*\/)\n{\n ConfigAPI *config = framework->Config();\n if (!config)\n return;\n\n HashMap<String, Variant> data;\n\n Urho3D::Graphics* graphics = GetSubsystem<Urho3D::Graphics>();\n if (graphics)\n {\n data[\"window position\"] = graphics->GetWindowPosition();\n data[\"window size\"] = Urho3D::IntVector2(graphics->GetWidth(), graphics->GetHeight());\n data[\"window fullscreen\"] = graphics->GetFullscreen();\n \n \/* Store potentially frequent runtime changes in memory only.\n The changes will be written to disk latest at a clean Framework exit. *\/\n ConfigFile &f = config->GetFile(ConfigAPI::FILE_FRAMEWORK);\n f.Set(ConfigAPI::SECTION_GRAPHICS, data);\n }\n}\n\nEntity *UrhoRenderer::MainCamera()\n{\n Entity *mainCameraEntity = activeMainCamera.Get();\n if (!mainCameraEntity)\n return nullptr;\n\n if (!mainCameraEntity->ParentScene() || !mainCameraEntity->Component<Camera>())\n {\n SetMainCamera(0);\n return nullptr;\n }\n return mainCameraEntity;\n}\n\nCamera *UrhoRenderer::MainCameraComponent()\n{\n Entity *mainCamera = MainCamera();\n if (!mainCamera)\n return nullptr;\n return mainCamera->Component<Camera>().Get();\n}\n\nScene *UrhoRenderer::MainCameraScene()\n{\n Entity *mainCamera = MainCamera();\n Scene *scene = mainCamera ? mainCamera->ParentScene() : 0;\n if (scene)\n return scene;\n\n \/\/ If there is no active camera, return the first scene on the list.\n const SceneMap &scenes = framework->Scene()->Scenes();\n if (scenes.Size() > 0)\n return scenes.Begin()->second_.Get();\n\n return nullptr;\n}\n\nvoid UrhoRenderer::SetMainCamera(Entity *mainCameraEntity)\n{\n activeMainCamera = mainCameraEntity;\n\n Urho3D::Camera *newActiveCamera = 0;\n Camera *cameraComponent = mainCameraEntity ? mainCameraEntity->Component<Camera>().Get() : 0;\n if (cameraComponent)\n newActiveCamera = cameraComponent->UrhoCamera();\n else\n {\n activeMainCamera.Reset();\n if (mainCameraEntity)\n LogWarning(\"Cannot activate camera '\" + mainCameraEntity->Name() + \"': It does not have a Camera component!\");\n }\n if (mainCameraEntity && !mainCameraEntity->ParentScene()) \/\/ If the new to-be camera is not in a scene, don't add it as active.\n {\n LogWarning(\"Cannot activate camera \\\"\" + mainCameraEntity->Name() + \"\\\": It is not attached to a scene!\");\n activeMainCamera.Reset();\n newActiveCamera = 0;\n }\n\n if (!activeMainCamera.Lock() || !newActiveCamera)\n LogWarning(\"Setting main window camera to null!\");\n\n Urho3D::Renderer* rend = GetSubsystem<Urho3D::Renderer>();\n if (!rend)\n return; \/\/ In headless mode the renderer doesn't exist\n\n Urho3D::Viewport* vp = rend->GetViewport(0);\n if (vp)\n {\n vp->SetCamera(newActiveCamera);\n vp->SetScene(mainCameraEntity->ParentScene()->Subsystem<GraphicsWorld>()->UrhoScene());\n }\n else\n LogWarning(\"Could not set active camera, no viewport defined\");\n\n MainCameraChanged.Emit(mainCameraEntity);\n}\n\nint UrhoRenderer::WindowWidth() const\n{\n Urho3D::Graphics* gfx = GetSubsystem<Urho3D::Graphics>();\n return gfx ? gfx->GetWidth() : 0;\n}\n\nint UrhoRenderer::WindowHeight() const\n{\n Urho3D::Graphics* gfx = GetSubsystem<Urho3D::Graphics>();\n return gfx ? gfx->GetHeight() : 0;\n}\n\nvoid UrhoRenderer::RegisterOgreMaterialProcessor(IOgreMaterialProcessor* processor, bool addFirst)\n{\n if (addFirst)\n materialProcessors.Insert(0, SharedPtr<IOgreMaterialProcessor>(processor));\n else\n materialProcessors.Push(SharedPtr<IOgreMaterialProcessor>(processor));\n}\n\nvoid UrhoRenderer::UnregisterOgreMaterialProcessor(IOgreMaterialProcessor* processor)\n{\n for (Vector<SharedPtr<IOgreMaterialProcessor> >::Iterator i = materialProcessors.Begin(); i != materialProcessors.End(); ++i)\n {\n if (i->Get() == processor)\n {\n materialProcessors.Erase(i);\n return;\n }\n }\n\n LogWarning(\"Could not find Ogre material processor to remove\");\n}\n\nIOgreMaterialProcessor* UrhoRenderer::FindOgreMaterialProcessor(const Ogre::MaterialParser& material) const\n{\n for (Vector<SharedPtr<IOgreMaterialProcessor> >::ConstIterator i = materialProcessors.Begin(); i != materialProcessors.End(); ++i)\n {\n if ((*i)->CanConvert(material))\n return *i;\n }\n\n return nullptr;\n}\n\nvoid UrhoRenderer::CreateGraphicsWorld(Scene *scene, AttributeChange::Type)\n{\n \/\/ Add an GraphicsWorld to the scene\n if (scene->ViewEnabled())\n scene->AddSubsystem(\"graphics\", new GraphicsWorld(this, scene));\n}\n\nvoid UrhoRenderer::RemoveGraphicsWorld(Scene *scene, AttributeChange::Type)\n{\n scene->RemoveSubsystem(\"graphics\");\n}\n\nvoid UrhoRenderer::OnScriptInstanceCreated(JavaScriptInstance* instance)\n{\n URHO3D_PROFILE(ExposeUrhoRendererClasses);\n\n duk_context* ctx = instance->Context();\n ExposeUrhoRendererClasses(ctx);\n}\n\n}\n\nextern \"C\"\n{\n\nDLLEXPORT void TundraPluginMain(Tundra::Framework *fw)\n{\n fw->RegisterModule(new Tundra::UrhoRenderer(fw));\n}\n\n}\n<commit_msg>Register UrhoRenderer object as the \"renderer\" global property.<commit_after>\/\/ For conditions of distribution and use, see copyright notice in LICENSE\n\n#include \"StableHeaders.h\"\n#include \"UrhoRenderer.h\"\n#include \"GraphicsWorld.h\"\n#include \"Framework.h\"\n#include \"Placeable.h\"\n#include \"Mesh.h\"\n#include \"AnimationController.h\"\n#include \"Camera.h\"\n#include \"Light.h\"\n#include \"EnvironmentLight.h\"\n#include \"Terrain.h\"\n#include \"Sky.h\"\n#include \"ParticleSystem.h\"\n#include \"Fog.h\"\n#include \"WaterPlane.h\"\n#include \"IComponentFactory.h\"\n#include \"ConfigAPI.h\"\n#include \"SceneAPI.h\"\n#include \"AssetAPI.h\"\n#include \"Entity.h\"\n#include \"Scene\/Scene.h\"\n#include \"LoggingFunctions.h\"\n#include \"JavaScript.h\"\n#include \"JavaScriptInstance.h\"\n#include \"UrhoRendererBindings\/UrhoRendererBindings.h\"\n\n#include \"TextureAsset.h\"\n#include \"UrhoMeshAsset.h\"\n#include \"Ogre\/OgreMeshAsset.h\"\n#include \"Ogre\/OgreMaterialAsset.h\"\n#include \"Ogre\/OgreSkeletonAsset.h\"\n#include \"Ogre\/DefaultOgreMaterialProcessor.h\"\n#include \"Ogre\/OgreParticleAsset.h\"\n#include \"GenericAssetFactory.h\"\n\n#include <Urho3D\/Core\/CoreEvents.h>\n#include <Urho3D\/Core\/ProcessUtils.h>\n#include <Urho3D\/Core\/Profiler.h>\n#include <Urho3D\/Graphics\/Camera.h>\n#include <Urho3D\/Graphics\/Graphics.h>\n#include <Urho3D\/Graphics\/GraphicsEvents.h>\n#include <Urho3D\/Graphics\/Renderer.h>\n#include <Urho3D\/Graphics\/Viewport.h>\n\nusing namespace JSBindings;\n\nnamespace Tundra\n{\n\nUrhoRenderer::UrhoRenderer(Framework* owner) :\n IModule(\"UrhoRenderer\", owner)\n{\n \/\/ Register default material convertor\n RegisterOgreMaterialProcessor(new DefaultOgreMaterialProcessor(GetContext()));\n}\n\nUrhoRenderer::~UrhoRenderer()\n{\n}\n\nvoid UrhoRenderer::Load()\n{\n SceneAPI* scene = framework->Scene();\n scene->RegisterComponentFactory(ComponentFactoryPtr(new GenericComponentFactory<Placeable>()));\n scene->RegisterComponentFactory(ComponentFactoryPtr(new GenericComponentFactory<Mesh>()));\n scene->RegisterComponentFactory(ComponentFactoryPtr(new GenericComponentFactory<Camera>()));\n scene->RegisterComponentFactory(ComponentFactoryPtr(new GenericComponentFactory<Light>()));\n scene->RegisterComponentFactory(ComponentFactoryPtr(new GenericComponentFactory<AnimationController>()));\n scene->RegisterComponentFactory(ComponentFactoryPtr(new GenericComponentFactory<EnvironmentLight>()));\n scene->RegisterComponentFactory(ComponentFactoryPtr(new GenericComponentFactory<Terrain>()));\n scene->RegisterComponentFactory(ComponentFactoryPtr(new GenericComponentFactory<Sky>()));\n scene->RegisterComponentFactory(ComponentFactoryPtr(new GenericComponentFactory<ParticleSystem>));\n scene->RegisterComponentFactory(ComponentFactoryPtr(new GenericComponentFactory<Fog>));\n scene->RegisterComponentFactory(ComponentFactoryPtr(new GenericComponentFactory<WaterPlane>));\n\n \/\/\/ \\todo Check and add new supported texture extensions\n StringList textureExtensions;\n textureExtensions.Push(\".crn\"); \/\/ CRN to DDS decompression implemented in TextureAsset\n textureExtensions.Push(\".dds\");\n textureExtensions.Push(\".png\");\n textureExtensions.Push(\".jpeg\");\n textureExtensions.Push(\".jpg\");\n textureExtensions.Push(\".gif\");\n textureExtensions.Push(\".bmp\");\n textureExtensions.Push(\".tga\");\n textureExtensions.Push(\".psd\");\n\n framework->Asset()->RegisterAssetTypeFactory(AssetTypeFactoryPtr(new GenericAssetFactory<UrhoMeshAsset>(\"UrhoMesh\", \".mdl\")));\n framework->Asset()->RegisterAssetTypeFactory(AssetTypeFactoryPtr(new GenericAssetFactory<OgreMeshAsset>(\"OgreMesh\", \".mesh\")));\n framework->Asset()->RegisterAssetTypeFactory(AssetTypeFactoryPtr(new GenericAssetFactory<OgreMaterialAsset>(\"OgreMaterial\", \".material\")));\n framework->Asset()->RegisterAssetTypeFactory(AssetTypeFactoryPtr(new GenericAssetFactory<OgreSkeletonAsset>(\"OgreSkeleton\", \".skeleton\")));\n framework->Asset()->RegisterAssetTypeFactory(AssetTypeFactoryPtr(new GenericAssetFactory<OgreParticleAsset>(\"OgreParticle\", \".particle\")));\n framework->Asset()->RegisterAssetTypeFactory(AssetTypeFactoryPtr(new GenericAssetFactory<TextureAsset>(\"Texture\", textureExtensions)));\n}\n\nvoid UrhoRenderer::Initialize()\n{\n framework->RegisterRenderer(this);\n\n \/\/ Connect to scene change signals.\n framework->Scene()->SceneCreated.Connect(this, &UrhoRenderer::CreateGraphicsWorld);\n framework->Scene()->SceneAboutToBeRemoved.Connect(this, &UrhoRenderer::RemoveGraphicsWorld);\n\n \/\/ Enable the main (full-screen) viewport\n Urho3D::Renderer* rend = GetSubsystem<Urho3D::Renderer>();\n if (rend)\n {\n rend->SetNumViewports(1);\n rend->SetViewport(0, new Urho3D::Viewport(context_));\n\n \/\/ Track window position and screen mode changes to keep config up-to-date\n SubscribeToEvent(Urho3D::E_WINDOWPOS, URHO3D_HANDLER(UrhoRenderer, HandleScreenModeChange));\n SubscribeToEvent(Urho3D::E_SCREENMODE, URHO3D_HANDLER(UrhoRenderer, HandleScreenModeChange));\n \n \/\/ Disable shadows completely for now on mobile devices, as the shadow bias is problematic, and it consumes GPU performance\n \/\/ Also disable specular highlights for per-pixel lighting\n if (Urho3D::GetPlatform() == \"Android\" || Urho3D::GetPlatform() == \"iOS\")\n {\n rend->SetDrawShadows(false);\n rend->SetSpecularLighting(false);\n }\n }\n\n \/\/ Connect to JavaScript module instance creation to be able to expose the renderer classes to each instance\n JavaScript* javaScript = framework->Module<JavaScript>();\n if (javaScript)\n javaScript->ScriptInstanceCreated.Connect(this, &UrhoRenderer::OnScriptInstanceCreated);\n}\n\nvoid UrhoRenderer::Uninitialize()\n{\n framework->RegisterRenderer(0);\n Urho3D::Renderer* rend = GetSubsystem<Urho3D::Renderer>();\n \/\/ Let go of the viewport that we created. If done later at Urho Context destruction time, may cause a crash\n if (rend)\n rend->SetViewport(0, nullptr);\n}\n\nvoid UrhoRenderer::HandleScreenModeChange(StringHash \/*eventType*\/, VariantMap& \/*eventData*\/)\n{\n ConfigAPI *config = framework->Config();\n if (!config)\n return;\n\n HashMap<String, Variant> data;\n\n Urho3D::Graphics* graphics = GetSubsystem<Urho3D::Graphics>();\n if (graphics)\n {\n data[\"window position\"] = graphics->GetWindowPosition();\n data[\"window size\"] = Urho3D::IntVector2(graphics->GetWidth(), graphics->GetHeight());\n data[\"window fullscreen\"] = graphics->GetFullscreen();\n \n \/* Store potentially frequent runtime changes in memory only.\n The changes will be written to disk latest at a clean Framework exit. *\/\n ConfigFile &f = config->GetFile(ConfigAPI::FILE_FRAMEWORK);\n f.Set(ConfigAPI::SECTION_GRAPHICS, data);\n }\n}\n\nEntity *UrhoRenderer::MainCamera()\n{\n Entity *mainCameraEntity = activeMainCamera.Get();\n if (!mainCameraEntity)\n return nullptr;\n\n if (!mainCameraEntity->ParentScene() || !mainCameraEntity->Component<Camera>())\n {\n SetMainCamera(0);\n return nullptr;\n }\n return mainCameraEntity;\n}\n\nCamera *UrhoRenderer::MainCameraComponent()\n{\n Entity *mainCamera = MainCamera();\n if (!mainCamera)\n return nullptr;\n return mainCamera->Component<Camera>().Get();\n}\n\nScene *UrhoRenderer::MainCameraScene()\n{\n Entity *mainCamera = MainCamera();\n Scene *scene = mainCamera ? mainCamera->ParentScene() : 0;\n if (scene)\n return scene;\n\n \/\/ If there is no active camera, return the first scene on the list.\n const SceneMap &scenes = framework->Scene()->Scenes();\n if (scenes.Size() > 0)\n return scenes.Begin()->second_.Get();\n\n return nullptr;\n}\n\nvoid UrhoRenderer::SetMainCamera(Entity *mainCameraEntity)\n{\n activeMainCamera = mainCameraEntity;\n\n Urho3D::Camera *newActiveCamera = 0;\n Camera *cameraComponent = mainCameraEntity ? mainCameraEntity->Component<Camera>().Get() : 0;\n if (cameraComponent)\n newActiveCamera = cameraComponent->UrhoCamera();\n else\n {\n activeMainCamera.Reset();\n if (mainCameraEntity)\n LogWarning(\"Cannot activate camera '\" + mainCameraEntity->Name() + \"': It does not have a Camera component!\");\n }\n if (mainCameraEntity && !mainCameraEntity->ParentScene()) \/\/ If the new to-be camera is not in a scene, don't add it as active.\n {\n LogWarning(\"Cannot activate camera \\\"\" + mainCameraEntity->Name() + \"\\\": It is not attached to a scene!\");\n activeMainCamera.Reset();\n newActiveCamera = 0;\n }\n\n if (!activeMainCamera.Lock() || !newActiveCamera)\n LogWarning(\"Setting main window camera to null!\");\n\n Urho3D::Renderer* rend = GetSubsystem<Urho3D::Renderer>();\n if (!rend)\n return; \/\/ In headless mode the renderer doesn't exist\n\n Urho3D::Viewport* vp = rend->GetViewport(0);\n if (vp)\n {\n vp->SetCamera(newActiveCamera);\n vp->SetScene(mainCameraEntity->ParentScene()->Subsystem<GraphicsWorld>()->UrhoScene());\n }\n else\n LogWarning(\"Could not set active camera, no viewport defined\");\n\n MainCameraChanged.Emit(mainCameraEntity);\n}\n\nint UrhoRenderer::WindowWidth() const\n{\n Urho3D::Graphics* gfx = GetSubsystem<Urho3D::Graphics>();\n return gfx ? gfx->GetWidth() : 0;\n}\n\nint UrhoRenderer::WindowHeight() const\n{\n Urho3D::Graphics* gfx = GetSubsystem<Urho3D::Graphics>();\n return gfx ? gfx->GetHeight() : 0;\n}\n\nvoid UrhoRenderer::RegisterOgreMaterialProcessor(IOgreMaterialProcessor* processor, bool addFirst)\n{\n if (addFirst)\n materialProcessors.Insert(0, SharedPtr<IOgreMaterialProcessor>(processor));\n else\n materialProcessors.Push(SharedPtr<IOgreMaterialProcessor>(processor));\n}\n\nvoid UrhoRenderer::UnregisterOgreMaterialProcessor(IOgreMaterialProcessor* processor)\n{\n for (Vector<SharedPtr<IOgreMaterialProcessor> >::Iterator i = materialProcessors.Begin(); i != materialProcessors.End(); ++i)\n {\n if (i->Get() == processor)\n {\n materialProcessors.Erase(i);\n return;\n }\n }\n\n LogWarning(\"Could not find Ogre material processor to remove\");\n}\n\nIOgreMaterialProcessor* UrhoRenderer::FindOgreMaterialProcessor(const Ogre::MaterialParser& material) const\n{\n for (Vector<SharedPtr<IOgreMaterialProcessor> >::ConstIterator i = materialProcessors.Begin(); i != materialProcessors.End(); ++i)\n {\n if ((*i)->CanConvert(material))\n return *i;\n }\n\n return nullptr;\n}\n\nvoid UrhoRenderer::CreateGraphicsWorld(Scene *scene, AttributeChange::Type)\n{\n \/\/ Add an GraphicsWorld to the scene\n if (scene->ViewEnabled())\n scene->AddSubsystem(\"graphics\", new GraphicsWorld(this, scene));\n}\n\nvoid UrhoRenderer::RemoveGraphicsWorld(Scene *scene, AttributeChange::Type)\n{\n scene->RemoveSubsystem(\"graphics\");\n}\n\nvoid UrhoRenderer::OnScriptInstanceCreated(JavaScriptInstance* instance)\n{\n URHO3D_PROFILE(ExposeUrhoRendererClasses);\n\n duk_context* ctx = instance->Context();\n ExposeUrhoRendererClasses(ctx);\n instance->RegisterService(\"renderer\", this);\n}\n\n}\n\nextern \"C\"\n{\n\nDLLEXPORT void TundraPluginMain(Tundra::Framework *fw)\n{\n fw->RegisterModule(new Tundra::UrhoRenderer(fw));\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ @(#)root\/cont:$Name: $:$Id: TProcessID.cxx,v 1.17 2002\/08\/12 06:20:13 brun Exp $\n\/\/ Author: Rene Brun 28\/09\/2001\n\n\/*************************************************************************\n * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *\n * All rights reserved. *\n * *\n * For the licensing terms see $ROOTSYS\/LICENSE. *\n * For the list of contributors see $ROOTSYS\/README\/CREDITS. *\n *************************************************************************\/\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ TProcessID\n\/\/\n\/\/ A TProcessID identifies a ROOT job in a unique way in time and space.\n\/\/ The TProcessID title consists of a TUUID object which provides a globally\n\/\/ unique identifier (for more see TUUID.h).\n\/\/\n\/\/ A TProcessID is automatically created by the TROOT constructor.\n\/\/ When a TFile contains referenced objects (see TRef), the TProcessID\n\/\/ object is written to the file.\n\/\/ If a file has been written in multiple sessions (same machine or not),\n\/\/ a TProcessID is written for each session.\n\/\/ These objects are used by the class TRef to uniquely identified\n\/\/ any TObject pointed by a TRef.\n\/\/\n\/\/ When a referenced object is read from a file (its bit kIsReferenced is set),\n\/\/ this object is entered into the objects table of the corresponding TProcessID.\n\/\/ Each TFile has a list of TProcessIDs (see TFile::fProcessIDs) also\n\/\/ accessible via TProcessID::fgPIDs (for all files).\n\/\/ When this object is deleted, it is removed from the table via the cleanup\n\/\/ mechanism invoked by the TObject destructor.\n\/\/\n\/\/ Each TProcessID has a table (TObjArray *fObjects) that keeps track\n\/\/ of all referenced objects. If a referenced object has a fUniqueID set,\n\/\/ a pointer to this unique object may be found via fObjects->At(fUniqueID).\n\/\/ In the same way, when a TRef::GetObject is called, GetObject uses\n\/\/ its own fUniqueID to find the pointer to the referenced object.\n\/\/ See TProcessID::GetObjectWithID and PutObjectWithID.\n\/\/\n\/\/ When a referenced object is deleted, its slot in fObjects is set to null.\n\/\/\n\/\/ See also TProcessUUID: a specialized TProcessID to manage the single list\n\/\/ of TUUIDs.\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"TProcessID.h\"\n#include \"TROOT.h\"\n#include \"TFile.h\"\n#include \"TObjArray.h\"\n\nTObjArray *TProcessID::fgPIDs = 0; \/\/pointer to the list of TProcessID\nTProcessID *TProcessID::fgPID = 0; \/\/pointer to the TProcessID of the current session\nUInt_t TProcessID::fgNumber = 0; \/\/Current referenced object instance count\n\nClassImp(TProcessID)\n\n\n\/\/______________________________________________________________________________\nTProcessID::TProcessID()\n{\n fCount = 0;\n fObjects = 0;\n}\n\n\/\/______________________________________________________________________________\nTProcessID::~TProcessID()\n{\n\n delete fObjects;\n fObjects = 0;\n fgPIDs->Remove(this);\n}\n\n\/\/______________________________________________________________________________\nTProcessID::TProcessID(const TProcessID &ref) : TNamed(ref)\n{\n \/\/ TProcessID copy ctor.\n}\n\n\/\/______________________________________________________________________________\nTProcessID *TProcessID::AddProcessID()\n{\n\/\/ static function to add a new TProcessID to the list of PIDs\n\n TProcessID *pid = new TProcessID();\n\n if (!fgPIDs) {\n fgPID = pid;\n fgPIDs = new TObjArray(10);\n gROOT->GetListOfCleanups()->Add(fgPIDs);\n }\n UShort_t apid = fgPIDs->GetEntriesFast();\n pid->IncrementCount();\n\n fgPIDs->Add(pid);\n char name[20];\n sprintf(name,\"ProcessID%d\",apid);\n pid->SetName(name);\n TUUID u;\n apid = fgPIDs->GetEntriesFast();\n pid->SetTitle(u.AsString());\n return pid;\n}\n\n\/\/______________________________________________________________________________\nUInt_t TProcessID::AssignID(TObject *obj)\n{\n\/\/ static function returning the ID assigned to obj\n\/\/ If the object is not yet referenced, its kIsReferenced bit is set\n\/\/ and its fUniqueID set to the current number of referenced objects so far.\n\n UInt_t uid = obj->GetUniqueID() & 0xffffff;\n if (obj == fgPID->GetObjectWithID(uid)) return uid;\n if (obj->TestBit(kIsReferenced)) {\n fgPID->PutObjectWithID(obj,uid);\n return uid;\n }\n fgNumber++;\n obj->SetBit(kIsReferenced);\n uid = fgNumber;\n obj->SetUniqueID(uid);\n fgPID->PutObjectWithID(obj,uid);\n return uid;\n}\n\n\/\/______________________________________________________________________________\nvoid TProcessID::Cleanup()\n{\n \/\/ static function (called by TROOT destructor) to delete all TProcessIDs\n\n fgPIDs->Delete();\n gROOT->GetListOfCleanups()->Remove(fgPIDs);\n delete fgPIDs;\n}\n\n\/\/______________________________________________________________________________\nInt_t TProcessID::DecrementCount()\n{\n\n \/\/ the reference fCount is used to delete the TProcessID\n \/\/ in the TFile destructor when fCount = 0\n\n fCount--;\n if (fCount < 0) fCount = 0;\n return fCount;\n}\n\n\/\/______________________________________________________________________________\nTProcessID *TProcessID::GetProcessID(UShort_t pid)\n{\n\/\/ static function returning a pointer to TProcessID number pid in fgPIDs\n\n return (TProcessID*)fgPIDs->At(pid);\n}\n\n\/\/______________________________________________________________________________\nTProcessID *TProcessID::GetProcessWithUID(UInt_t uid)\n{\n\/\/ static function returning a pointer to TProcessID with its pid\n\/\/ encoded in the highest byte of uid\n\n Int_t pid = (uid>>24)&0xff;\n return (TProcessID*)fgPIDs->At(pid);\n}\n\n\/\/______________________________________________________________________________\nTProcessID *TProcessID::GetSessionProcessID()\n{\n\/\/ static function returning the pointer to the session TProcessID\n\n return fgPID;\n}\n\n\/\/______________________________________________________________________________\nInt_t TProcessID::IncrementCount()\n{\n\n if (!fObjects) fObjects = new TObjArray(100);\n fCount++;\n return fCount;\n}\n\n\/\/______________________________________________________________________________\nUInt_t TProcessID::GetObjectCount()\n{\n\/\/ Return the current referenced object count\n\/\/ fgNumber is incremented everytime a new object is referenced\n\n return fgNumber;\n}\n\n\/\/______________________________________________________________________________\nTObject *TProcessID::GetObjectWithID(UInt_t uidd)\n{\n \/\/returns the TObject with unique identifier uid in the table of objects\n \/\/if (!fObjects) fObjects = new TObjArray(100);\n \n Int_t uid = uidd & 0xffffff; \/\/take only the 24 lower bits\n \n if (uid >= fObjects->GetSize()) return 0;\n return fObjects->UncheckedAt(uid);\n}\n\n\/\/______________________________________________________________________________\nvoid TProcessID::PutObjectWithID(TObject *obj, UInt_t uid)\n{\n\n \/\/stores the object at the uid th slot in the table of objects\n \/\/The object uniqueid is set as well as its kMustCleanup bit\n \/\/if (!fObjects) fObjects = new TObjArray(100);\n if (uid == 0) uid = obj->GetUniqueID() & 0xffffff;\n fObjects->AddAtAndExpand(obj,uid);\n obj->SetBit(kMustCleanup);\n}\n\n\/\/______________________________________________________________________________\nTProcessID *TProcessID::ReadProcessID(UShort_t pidf, TFile *file)\n{\n\/\/ static function\n\n \/\/The TProcessID with number pidf is read from file.\n \/\/If the object is not already entered in the gROOT list, it is added.\n\n if (!file) return 0;\n TObjArray *pids = file->GetListOfProcessIDs();\n TProcessID *pid = 0;\n if (pidf < pids->GetSize()) pid = (TProcessID *)pids->UncheckedAt(pidf);\n if (pid) return pid;\n\n \/\/check if fProcessIDs[uid] is set in file\n \/\/if not set, read the process uid from file\n char pidname[32];\n sprintf(pidname,\"ProcessID%d\",pidf);\n TDirectory *dirsav = gDirectory;\n file->cd();\n pid = (TProcessID *)file->Get(pidname);\n if (dirsav) dirsav->cd();\n if (gDebug > 0) {\n printf(\"ReadProcessID, name=%s, file=%s, pid=%lx\\n\",pidname,file->GetName(),(Long_t)pid);\n }\n if (!pid) {\n \/\/file->Error(\"ReadProcessID\",\"Cannot find %s in file %s\",pidname,file->GetName());\n return 0;\n }\n \/\/check that a similar pid is not already registered in fgPIDs\n TIter next(fgPIDs);\n TProcessID *p;\n while ((p = (TProcessID*)next())) {\n if (!strcmp(p->GetTitle(),pid->GetTitle())) {\n delete pid;\n pids->AddAtAndExpand(p,pidf);\n p->IncrementCount();\n return p;\n }\n }\n pids->AddAtAndExpand(pid,pidf);\n pid->IncrementCount();\n fgPIDs->Add(pid);\n Int_t ind = fgPIDs->IndexOf(pid);\n pid->SetUniqueID((UInt_t)ind);\n return pid;\n}\n\n\/\/______________________________________________________________________________\nvoid TProcessID::RecursiveRemove(TObject *obj)\n{\n \/\/ called by the object destructor\n \/\/ remove reference to obj from the current table if it is referenced\n\n if (!obj->TestBit(kIsReferenced)) return;\n UInt_t uid = obj->GetUniqueID() & 0xffffff;\n if (obj == GetObjectWithID(uid)) fObjects->RemoveAt(uid);\n}\n\n\n\/\/______________________________________________________________________________\nvoid TProcessID::SetObjectCount(UInt_t number)\n{\n\/\/ static function to set the current referenced object count\n\/\/ fgNumber is incremented everytime a new object is referenced\n\n fgNumber = number;\n}\n\n\/\/______________________________________________________________________________\nUShort_t TProcessID::WriteProcessID(TProcessID *pidd, TFile *file)\n{\n\/\/ static function\n\/\/ Check if the ProcessID pid is already in the file.\n\/\/ if not, add it and return the index number in the local file list\n\n if (!file) return 0;\n TProcessID *pid = pidd;\n if (!pid) pid = fgPID;\n TObjArray *pids = file->GetListOfProcessIDs();\n Int_t npids = file->GetNProcessIDs();\n for (Int_t i=0;i<npids;i++) {\n if (pids->At(i) == pid) return (UShort_t)i;\n }\n \n TDirectory *dirsav = gDirectory;\n file->cd();\n file->SetBit(TFile::kHasReferences);\n pids->Add(pid);\n pid->IncrementCount();\n char name[32];\n sprintf(name,\"ProcessID%d\",npids);\n pid->Write(name);\n file->IncrementProcessIDs();\n if (gDebug > 0) {\n printf(\"WriteProcessID, name=%s, file=%s\\n\",name,file->GetName()); \n }\n if (dirsav) dirsav->cd();\n return (UShort_t)npids;\n}\n<commit_msg>Fix from Bill Tanenbaum in TProcessID::WriteProcessID. In TProcessID::WriteProcessID(TProcessID*, TFile *), the statement pids->Add(pid); must be replaced by pids->AddAtAndExpand(pid,npids);<commit_after>\/\/ @(#)root\/cont:$Name: $:$Id: TProcessID.cxx,v 1.18 2002\/10\/31 21:38:36 brun Exp $\n\/\/ Author: Rene Brun 28\/09\/2001\n\n\/*************************************************************************\n * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *\n * All rights reserved. *\n * *\n * For the licensing terms see $ROOTSYS\/LICENSE. *\n * For the list of contributors see $ROOTSYS\/README\/CREDITS. *\n *************************************************************************\/\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ TProcessID\n\/\/\n\/\/ A TProcessID identifies a ROOT job in a unique way in time and space.\n\/\/ The TProcessID title consists of a TUUID object which provides a globally\n\/\/ unique identifier (for more see TUUID.h).\n\/\/\n\/\/ A TProcessID is automatically created by the TROOT constructor.\n\/\/ When a TFile contains referenced objects (see TRef), the TProcessID\n\/\/ object is written to the file.\n\/\/ If a file has been written in multiple sessions (same machine or not),\n\/\/ a TProcessID is written for each session.\n\/\/ These objects are used by the class TRef to uniquely identified\n\/\/ any TObject pointed by a TRef.\n\/\/\n\/\/ When a referenced object is read from a file (its bit kIsReferenced is set),\n\/\/ this object is entered into the objects table of the corresponding TProcessID.\n\/\/ Each TFile has a list of TProcessIDs (see TFile::fProcessIDs) also\n\/\/ accessible via TProcessID::fgPIDs (for all files).\n\/\/ When this object is deleted, it is removed from the table via the cleanup\n\/\/ mechanism invoked by the TObject destructor.\n\/\/\n\/\/ Each TProcessID has a table (TObjArray *fObjects) that keeps track\n\/\/ of all referenced objects. If a referenced object has a fUniqueID set,\n\/\/ a pointer to this unique object may be found via fObjects->At(fUniqueID).\n\/\/ In the same way, when a TRef::GetObject is called, GetObject uses\n\/\/ its own fUniqueID to find the pointer to the referenced object.\n\/\/ See TProcessID::GetObjectWithID and PutObjectWithID.\n\/\/\n\/\/ When a referenced object is deleted, its slot in fObjects is set to null.\n\/\/\n\/\/ See also TProcessUUID: a specialized TProcessID to manage the single list\n\/\/ of TUUIDs.\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"TProcessID.h\"\n#include \"TROOT.h\"\n#include \"TFile.h\"\n#include \"TObjArray.h\"\n\nTObjArray *TProcessID::fgPIDs = 0; \/\/pointer to the list of TProcessID\nTProcessID *TProcessID::fgPID = 0; \/\/pointer to the TProcessID of the current session\nUInt_t TProcessID::fgNumber = 0; \/\/Current referenced object instance count\n\nClassImp(TProcessID)\n\n\n\/\/______________________________________________________________________________\nTProcessID::TProcessID()\n{\n fCount = 0;\n fObjects = 0;\n}\n\n\/\/______________________________________________________________________________\nTProcessID::~TProcessID()\n{\n\n delete fObjects;\n fObjects = 0;\n fgPIDs->Remove(this);\n}\n\n\/\/______________________________________________________________________________\nTProcessID::TProcessID(const TProcessID &ref) : TNamed(ref)\n{\n \/\/ TProcessID copy ctor.\n}\n\n\/\/______________________________________________________________________________\nTProcessID *TProcessID::AddProcessID()\n{\n\/\/ static function to add a new TProcessID to the list of PIDs\n\n TProcessID *pid = new TProcessID();\n\n if (!fgPIDs) {\n fgPID = pid;\n fgPIDs = new TObjArray(10);\n gROOT->GetListOfCleanups()->Add(fgPIDs);\n }\n UShort_t apid = fgPIDs->GetEntriesFast();\n pid->IncrementCount();\n\n fgPIDs->Add(pid);\n char name[20];\n sprintf(name,\"ProcessID%d\",apid);\n pid->SetName(name);\n TUUID u;\n apid = fgPIDs->GetEntriesFast();\n pid->SetTitle(u.AsString());\n return pid;\n}\n\n\/\/______________________________________________________________________________\nUInt_t TProcessID::AssignID(TObject *obj)\n{\n\/\/ static function returning the ID assigned to obj\n\/\/ If the object is not yet referenced, its kIsReferenced bit is set\n\/\/ and its fUniqueID set to the current number of referenced objects so far.\n\n UInt_t uid = obj->GetUniqueID() & 0xffffff;\n if (obj == fgPID->GetObjectWithID(uid)) return uid;\n if (obj->TestBit(kIsReferenced)) {\n fgPID->PutObjectWithID(obj,uid);\n return uid;\n }\n fgNumber++;\n obj->SetBit(kIsReferenced);\n uid = fgNumber;\n obj->SetUniqueID(uid);\n fgPID->PutObjectWithID(obj,uid);\n return uid;\n}\n\n\/\/______________________________________________________________________________\nvoid TProcessID::Cleanup()\n{\n \/\/ static function (called by TROOT destructor) to delete all TProcessIDs\n\n fgPIDs->Delete();\n gROOT->GetListOfCleanups()->Remove(fgPIDs);\n delete fgPIDs;\n}\n\n\/\/______________________________________________________________________________\nInt_t TProcessID::DecrementCount()\n{\n\n \/\/ the reference fCount is used to delete the TProcessID\n \/\/ in the TFile destructor when fCount = 0\n\n fCount--;\n if (fCount < 0) fCount = 0;\n return fCount;\n}\n\n\/\/______________________________________________________________________________\nTProcessID *TProcessID::GetProcessID(UShort_t pid)\n{\n\/\/ static function returning a pointer to TProcessID number pid in fgPIDs\n\n return (TProcessID*)fgPIDs->At(pid);\n}\n\n\/\/______________________________________________________________________________\nTProcessID *TProcessID::GetProcessWithUID(UInt_t uid)\n{\n\/\/ static function returning a pointer to TProcessID with its pid\n\/\/ encoded in the highest byte of uid\n\n Int_t pid = (uid>>24)&0xff;\n return (TProcessID*)fgPIDs->At(pid);\n}\n\n\/\/______________________________________________________________________________\nTProcessID *TProcessID::GetSessionProcessID()\n{\n\/\/ static function returning the pointer to the session TProcessID\n\n return fgPID;\n}\n\n\/\/______________________________________________________________________________\nInt_t TProcessID::IncrementCount()\n{\n\n if (!fObjects) fObjects = new TObjArray(100);\n fCount++;\n return fCount;\n}\n\n\/\/______________________________________________________________________________\nUInt_t TProcessID::GetObjectCount()\n{\n\/\/ Return the current referenced object count\n\/\/ fgNumber is incremented everytime a new object is referenced\n\n return fgNumber;\n}\n\n\/\/______________________________________________________________________________\nTObject *TProcessID::GetObjectWithID(UInt_t uidd)\n{\n \/\/returns the TObject with unique identifier uid in the table of objects\n \/\/if (!fObjects) fObjects = new TObjArray(100);\n \n Int_t uid = uidd & 0xffffff; \/\/take only the 24 lower bits\n \n if (uid >= fObjects->GetSize()) return 0;\n return fObjects->UncheckedAt(uid);\n}\n\n\/\/______________________________________________________________________________\nvoid TProcessID::PutObjectWithID(TObject *obj, UInt_t uid)\n{\n\n \/\/stores the object at the uid th slot in the table of objects\n \/\/The object uniqueid is set as well as its kMustCleanup bit\n \/\/if (!fObjects) fObjects = new TObjArray(100);\n if (uid == 0) uid = obj->GetUniqueID() & 0xffffff;\n fObjects->AddAtAndExpand(obj,uid);\n obj->SetBit(kMustCleanup);\n}\n\n\/\/______________________________________________________________________________\nTProcessID *TProcessID::ReadProcessID(UShort_t pidf, TFile *file)\n{\n\/\/ static function\n\n \/\/The TProcessID with number pidf is read from file.\n \/\/If the object is not already entered in the gROOT list, it is added.\n\n if (!file) return 0;\n TObjArray *pids = file->GetListOfProcessIDs();\n TProcessID *pid = 0;\n if (pidf < pids->GetSize()) pid = (TProcessID *)pids->UncheckedAt(pidf);\n if (pid) return pid;\n\n \/\/check if fProcessIDs[uid] is set in file\n \/\/if not set, read the process uid from file\n char pidname[32];\n sprintf(pidname,\"ProcessID%d\",pidf);\n TDirectory *dirsav = gDirectory;\n file->cd();\n pid = (TProcessID *)file->Get(pidname);\n if (dirsav) dirsav->cd();\n if (gDebug > 0) {\n printf(\"ReadProcessID, name=%s, file=%s, pid=%lx\\n\",pidname,file->GetName(),(Long_t)pid);\n }\n if (!pid) {\n \/\/file->Error(\"ReadProcessID\",\"Cannot find %s in file %s\",pidname,file->GetName());\n return 0;\n }\n \/\/check that a similar pid is not already registered in fgPIDs\n TIter next(fgPIDs);\n TProcessID *p;\n while ((p = (TProcessID*)next())) {\n if (!strcmp(p->GetTitle(),pid->GetTitle())) {\n delete pid;\n pids->AddAtAndExpand(p,pidf);\n p->IncrementCount();\n return p;\n }\n }\n pids->AddAtAndExpand(pid,pidf);\n pid->IncrementCount();\n fgPIDs->Add(pid);\n Int_t ind = fgPIDs->IndexOf(pid);\n pid->SetUniqueID((UInt_t)ind);\n return pid;\n}\n\n\/\/______________________________________________________________________________\nvoid TProcessID::RecursiveRemove(TObject *obj)\n{\n \/\/ called by the object destructor\n \/\/ remove reference to obj from the current table if it is referenced\n\n if (!obj->TestBit(kIsReferenced)) return;\n UInt_t uid = obj->GetUniqueID() & 0xffffff;\n if (obj == GetObjectWithID(uid)) fObjects->RemoveAt(uid);\n}\n\n\n\/\/______________________________________________________________________________\nvoid TProcessID::SetObjectCount(UInt_t number)\n{\n\/\/ static function to set the current referenced object count\n\/\/ fgNumber is incremented everytime a new object is referenced\n\n fgNumber = number;\n}\n\n\/\/______________________________________________________________________________\nUShort_t TProcessID::WriteProcessID(TProcessID *pidd, TFile *file)\n{\n\/\/ static function\n\/\/ Check if the ProcessID pid is already in the file.\n\/\/ if not, add it and return the index number in the local file list\n\n if (!file) return 0;\n TProcessID *pid = pidd;\n if (!pid) pid = fgPID;\n TObjArray *pids = file->GetListOfProcessIDs();\n Int_t npids = file->GetNProcessIDs();\n for (Int_t i=0;i<npids;i++) {\n if (pids->At(i) == pid) return (UShort_t)i;\n }\n \n TDirectory *dirsav = gDirectory;\n file->cd();\n file->SetBit(TFile::kHasReferences);\n pids->AddAtAndExpand(pid,npids);\n pid->IncrementCount();\n char name[32];\n sprintf(name,\"ProcessID%d\",npids);\n pid->Write(name);\n file->IncrementProcessIDs();\n if (gDebug > 0) {\n printf(\"WriteProcessID, name=%s, file=%s\\n\",name,file->GetName()); \n }\n if (dirsav) dirsav->cd();\n return (UShort_t)npids;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ This file is a part of the IncludeOS unikernel - www.includeos.org\n\/\/\n\/\/ Copyright 2015-2016 Oslo and Akershus University College of Applied Sciences\n\/\/ and Alfred Bratterud\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#pragma once\n#ifndef DASHBOARD_COMPONENTS_LOGGER_HPP\n#define DASHBOARD_COMPONENTS_LOGGER_HPP\n\n#include \"..\/component.hpp\"\n\n#include <logger\/logger.hpp>\n\nnamespace dashboard {\n\nclass Logger : public Component {\n\npublic:\n\n Logger(::Logger& logger, size_t entries = 20)\n : logger_{logger}, entries_{entries}\n {}\n\n std::string key() const override\n { return \"logger\"; }\n\n void serialize(Writer& writer) const override {\n writer.StartArray();\n auto entries = logger_.entries(entries_);\n\n auto it = entries.begin();\n \/\/ Temporary hack to only send N latest\n const size_t N = 50;\n if(entries.size() > N)\n it += entries.size() - N;\n\n while(it != entries.end())\n writer.String(*it++);\n\n writer.EndArray();\n }\n\nprivate:\n const ::Logger& logger_;\n const size_t entries_;\n\n};\n\n} \/\/ < namespace dashboard\n\n#endif\n\n\n\n\n<commit_msg>Dashboard: Logger no longer hacked<commit_after>\/\/ This file is a part of the IncludeOS unikernel - www.includeos.org\n\/\/\n\/\/ Copyright 2015-2016 Oslo and Akershus University College of Applied Sciences\n\/\/ and Alfred Bratterud\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#pragma once\n#ifndef DASHBOARD_COMPONENTS_LOGGER_HPP\n#define DASHBOARD_COMPONENTS_LOGGER_HPP\n\n#include \"..\/component.hpp\"\n\n#include <logger\/logger.hpp>\n\nnamespace dashboard {\n\nclass Logger : public Component {\n\npublic:\n\n Logger(::Logger& logger, size_t entries = 50)\n : logger_{logger}, entries_{entries}\n {}\n\n std::string key() const override\n { return \"logger\"; }\n\n void serialize(Writer& writer) const override {\n writer.StartArray();\n auto entries = (entries_) ? logger_.entries(entries_) : logger_.entries();\n\n auto it = entries.begin();\n\n while(it != entries.end())\n writer.String(*it++);\n\n writer.EndArray();\n }\n\nprivate:\n const ::Logger& logger_;\n const size_t entries_;\n\n};\n\n} \/\/ < namespace dashboard\n\n#endif\n\n\n\n\n<|endoftext|>"} {"text":"<commit_before>#ifndef ACTIONMAPPINGS_HPP\n#define ACTIONMAPPINGS_HPP\n\n#include <unordered_map>\n#include <string>\n#include <vector>\n#include <SDL.h>\n#include \"LuaReference.hpp\"\n#include \"LuaState.hpp\"\n\n\n\nclass ActionMappings\n{\n public:\n ActionMappings(LuaState& lua);\n virtual ~ActionMappings();\n ActionMappings(const ActionMappings& other) = delete;\n ActionMappings& operator=(const ActionMappings& other) = delete;\n\n bool CreateAction(std::string name, LuaReference keyCallback);\n bool CreateAction(std::string name, LuaReference keyDownCallback, LuaReference keyUpCallback);\n\n void AddActionKey(std::string actionName, SDL_Keycode key);\n\n void FireActionKeyDown(SDL_Keycode key, int value);\n\n void DestroyState()\n {\n\/\/ _entities.clear();\n\/\/ _callback = LuaReference();\n _actionKeys.clear();\n _actionCallbacks.clear();\n }\n\n void InitializeLua()\n {\n _lua.SetUserData((void*)&LuaKeyBase, this);\n _lua.AddFunction(AddActionCallbacks, \"AddActionCallbacks\");\n }\n\n protected:\n private:\n struct Action\n {\n public:\n Action(LuaReference keyDownCallback, LuaReference keyUpCallback)\n {\n _keyDownCallback = std::move(keyDownCallback);\n _keyUpCallback = std::move(keyUpCallback);\n }\n\n Action(LuaReference keyCallback)\n : _keyDownCallback(std::move(keyCallback))\n {\n\/\/ _keyDownCallback = std::move(keyCallback);\n }\n\n void FireKeyDown(LuaState& lua, int value)\n {\n if (_keyDownCallback.HasReference())\n {\n auto state = lua.Raw();\n _keyDownCallback.Push();\n lua_pushnumber(state, value);\n lua.Call(1, 0);\n }\n }\n\n void FireKeyUp(LuaState& lua, int value)\n {\n if (_keyUpCallback.HasReference())\n {\n auto state = lua.Raw();\n _keyDownCallback.Push();\n lua_pushnumber(state, value);\n lua.Call(1, 0);\n }\n else\n {\n FireKeyDown(lua, value);\n }\n }\n\n private:\n\n LuaReference _keyDownCallback;\n LuaReference _keyUpCallback;\n };\n\n std::unordered_map<SDL_Keycode, Action*> _actionCallbacks;\n std::unordered_map<std::string, Action> _actionKeys;\n\n LuaState& _lua;\n\n static const int LuaKeyBase;\n static ActionMappings& FromLua(lua_State* state);\n static int AddActionCallbacks(lua_State* state);\n\n\n};\n\n#endif \/\/ ACTIONMAPPINGS_HPP\n<commit_msg>Cleanup.<commit_after>#ifndef ACTIONMAPPINGS_HPP\n#define ACTIONMAPPINGS_HPP\n\n#include <unordered_map>\n#include <string>\n#include <vector>\n#include <SDL.h>\n#include \"LuaReference.hpp\"\n#include \"LuaState.hpp\"\n\n\n\nclass ActionMappings\n{\n public:\n ActionMappings(LuaState& lua);\n virtual ~ActionMappings();\n ActionMappings(const ActionMappings& other) = delete;\n ActionMappings& operator=(const ActionMappings& other) = delete;\n\n bool CreateAction(std::string name, LuaReference keyCallback);\n bool CreateAction(std::string name, LuaReference keyDownCallback, LuaReference keyUpCallback);\n\n void AddActionKey(std::string actionName, SDL_Keycode key);\n\n void FireActionKeyDown(SDL_Keycode key, int value);\n\n void DestroyState()\n {\n _actionKeys.clear();\n _actionCallbacks.clear();\n }\n\n void InitializeLua()\n {\n _lua.SetUserData((void*)&LuaKeyBase, this);\n _lua.AddFunction(AddActionCallbacks, \"AddActionCallbacks\");\n }\n\n protected:\n private:\n struct Action\n {\n public:\n Action(LuaReference keyDownCallback, LuaReference keyUpCallback)\n {\n _keyDownCallback = std::move(keyDownCallback);\n _keyUpCallback = std::move(keyUpCallback);\n }\n\n Action(LuaReference keyCallback)\n : _keyDownCallback(std::move(keyCallback))\n {\n\n }\n\n void FireKeyDown(LuaState& lua, int value)\n {\n if (_keyDownCallback.HasReference())\n {\n auto state = lua.Raw();\n _keyDownCallback.Push();\n lua_pushnumber(state, value);\n lua.Call(1, 0);\n }\n }\n\n void FireKeyUp(LuaState& lua, int value)\n {\n if (_keyUpCallback.HasReference())\n {\n auto state = lua.Raw();\n _keyDownCallback.Push();\n lua_pushnumber(state, value);\n lua.Call(1, 0);\n }\n else\n {\n FireKeyDown(lua, value);\n }\n }\n\n private:\n\n LuaReference _keyDownCallback;\n LuaReference _keyUpCallback;\n };\n\n std::unordered_map<SDL_Keycode, Action*> _actionCallbacks;\n std::unordered_map<std::string, Action> _actionKeys;\n\n LuaState& _lua;\n\n static const int LuaKeyBase;\n static ActionMappings& FromLua(lua_State* state);\n static int AddActionCallbacks(lua_State* state);\n\n\n};\n\n#endif \/\/ ACTIONMAPPINGS_HPP\n<|endoftext|>"} {"text":"<commit_before>\/\/ $Id: exception.C,v 1.13 2000\/08\/09 09:18:50 amoll Exp $\n\n#include <BALL\/COMMON\/exception.h>\n#include <BALL\/COMMON\/logStream.h>\n\n#include <iostream>\n#include <typeinfo>\n#include <exception>\n#include <stdio.h>\n#include <stdlib.h>\t\/\/ for getenv in terminate()\n#include <sys\/types.h>\n#include <signal.h> \/\/ for SIGSEGV and kill\n#include <unistd.h> \/\/ fot getpid\n\n#define BALL_CORE_DUMP_ENVNAME \"BALL_DUMP_CORE\"\n\n#define DEF_EXCEPTION(a,b) \\\n\ta##::##a##(const char* file, int line)\\\n\t\t: GeneralException(file, line, #a, b)\\\n\t{\\\n\t}\\\n\\\n\t\n\nusing std::string;\nusing std::endl;\n\nnamespace BALL \n{\n\n\tnamespace Exception \n\t{\n\n\t\t\tGeneralException::GeneralException() \n\t\t\t\t:\tfile_(\"?\"),\n\t\t\t\t\tline_(-1),\n\t\t\t\t\tname_(\"GeneralException\"),\n\t\t\t\t\tmessage_(\"unspecified error\")\n\t\t\t{\n\t\t\t\tglobalHandler.set(file_, line_, name_, message_);\n\t\t\t}\n\n\t\t\tGeneralException::GeneralException(const char* file, int line, const string& name, const string& message) \n\t\t\t\t:\tfile_(file),\n\t\t\t\t\tline_(line),\n\t\t\t\t\tname_(name),\n\t\t\t\t\tmessage_(message)\n\t\t\t{\n\t\t\t\tglobalHandler.set(file_, line_, name_, message_);\n\t\t\t}\n\n\t\t\tGeneralException::GeneralException(const GeneralException& exception)\n\t\t\t\t:\tfile_(exception.file_),\n\t\t\t\t\tline_(exception.line_),\n\t\t\t\t\tname_(exception.name_),\n\t\t\t\t\tmessage_(exception.message_)\n\t\t\t{\n\t\t\t}\n\n\t\t\tGeneralException::~GeneralException()\n\t\t\t{\n\t\t\t}\n\t\t\n\n\t\t\tstring GeneralException::getName() const\n\t\t\t{\n\t\t\t\treturn name_;\n\t\t\t}\n\n\t\t\tstring GeneralException::getMessage() const\n\t\t\t{\n\t\t\t\treturn message_;\n\t\t\t}\n\n\t\t\tstring GeneralException::getFile() const\n\t\t\t{\n\t\t\t\treturn file_;\n\t\t\t}\n\t\t\t\n\t\t\tint GeneralException::getLine() const\n\t\t\t{\n\t\t\t\treturn line_;\n\t\t\t}\n\n\t\t\tIndexUnderflow::IndexUnderflow(const char* file, int line, Index index, Size size)\n\t\t\t\t: GeneralException(file, line, \"IndexUnderflow\", \"\"),\n\t\t\t\t\tsize_(size),\n\t\t\t\t\tindex_(index)\n\t\t\t{\n\t\t\t\tmessage_ = \"the given index was too small: \";\n\t\t\t\tchar buf[40];\n\n\t\t\t\tsprintf(buf, \"%ld\", (long)index);\n\t\t\t\tmessage_ += buf;\n\t\t\t\tmessage_ += \" (size = \";\n\n\t\t\t\tsprintf(buf, \"%ld\", (long)size);\n\t\t\t\tmessage_ += buf;\n\t\t\t\tmessage_ += \")\";\n\n\t\t\t\tglobalHandler.setMessage(message_);\n\t\t\t}\n\n\t\t\tIndexOverflow::IndexOverflow(const char* file, int line, Index index, Size size)\n\t\t\t\t:\tGeneralException(file, line, \"IndexOverflow\", \"an index was too large\"),\n\t\t\t\t\tsize_(size),\n\t\t\t\t\tindex_(index)\n\t\t\t{\n\t\t\t\tmessage_ = \"the given index was too large: \";\n\t\t\t\tchar buf[40];\n\n\t\t\t\tsprintf(buf, \"%ld\", (long)index);\n\t\t\t\tmessage_ += buf;\n\t\t\t\tmessage_ += \" (size = \";\n\n\t\t\t\tsprintf(buf, \"%ld\", (long)size);\n\t\t\t\tmessage_ += buf;\n\t\t\t\tmessage_ += \")\";\n\n\t\t\t\tglobalHandler.setMessage(message_);\n\t\t\t}\n\n\t\t\tOutOfMemory::OutOfMemory(const char* file, int line, Size size)\n\t\t\t\t:\tGeneralException(file, line, \"OutOfMemory\", \"a memory allocation failed\"),\n\t\t\t\t\tsize_(size)\n\t\t\t{\n\t\t\t\tmessage_ = \"unable to allocate enough memory (size = \";\n\t\t\t\tchar buf[40];\n\n\t\t\t\tsprintf(buf, \"%ld\", (long)size_);\n\t\t\t\tmessage_ += buf;\n\t\t\t\tmessage_ += \" bytes) \";\n\n\t\t\t\tglobalHandler.setMessage(message_);\n\t\t\t}\n\n\t\t\tOutOfMemory::~OutOfMemory() throw()\n\t\t\t{\n\t\t\t}\n\n\t\t\tSizeUnderflow::SizeUnderflow(const char* file, int line, Size size)\n\t\t\t\t:\tGeneralException(file, line, \"SizeUnderflow\", \"\"),\n\t\t\t\t\tsize_(size)\n\t\t\t{\n\t\t\t\tmessage_ = \"the given size was too small: \";\n\t\t\t\tchar buf[40];\n\t\t\t\tsprintf(buf, \"%ld\", (long)size);\n\t\t\t\t\n\t\t\t\tmessage_ += buf;\n\t\t\t\tglobalHandler.setMessage(message_);\n\t\t\t}\n\n\t\t\tFileNotFound::FileNotFound(const char* file, int line, const string& filename)\n\t\t\t\t:\tGeneralException(file, line, \"FileNotFound\", \"\"),\n\t\t\t\t\tfilename_(filename)\n\t\t\t{\n\t\t\t\tmessage_ = \"the file \" + filename + \" could not be found\";\n\t\t\t\tglobalHandler.setMessage(message_);\n\t\t\t}\n\n\t\t\tstring FileNotFound::getFilename() const\n\t\t\t{\n\t\t\t\treturn filename_;\n\t\t\t}\n\t\t\n\n\t\t\tInvalidFormat::InvalidFormat(const char* file, int line, const string& s)\n\t\t\t\t:\tGeneralException(file, line, \"InvalidFormat\", \"\"),\n\t\t\t\t\tformat_(s)\n\t\t\t{\n\t\t\t\tmessage_ = \"problem converting '\";\n\t\t\t\tmessage_.append(s + \"' to a number.\");\n\n\t\t\t\tglobalHandler.setMessage(message_);\n\t\t\t}\n\t\t\n\n\t\t\tDEF_EXCEPTION(DivisionByZero, \"a division by zero was requested\")\n\n\t\t\tDEF_EXCEPTION(InvalidRange, \"the range of the operation was invalid\")\n\n\t\t\tDEF_EXCEPTION(NullPointer, \"a null pointer was specified\")\n\n\t\t\tDEF_EXCEPTION(InvalidIterator, \"the iterator is invalid - probably it is not bound to a container\")\n\n\t\t\tDEF_EXCEPTION(IncompatibleIterators, \"the iterator could not be assigned because it is bound to a different container\")\n\n\t\t\tDEF_EXCEPTION(NotImplemented, \"this method has not been implemented yet. Feel free to complain about it!\")\n\n\t\t\tDEF_EXCEPTION(IllegalTreeOperation, \"a illegal tree operation was requested\")\n\n\t\t\tDEF_EXCEPTION(BufferOverflow, \"the maximum buffersize has been reached\")\n\n\t\t\tDEF_EXCEPTION(OutOfGrid, \"a point was outside a grid\")\n\n\t\t\n\t\t\tGlobalExceptionHandler::GlobalExceptionHandler()\n\t\t\t{\n\t\t\t\tstd::set_terminate(terminate);\n\t\t\t\tstd::set_unexpected(terminate);\n\t\t\t\tstd::set_new_handler(newHandler);\n\t\t\t}\n\n\t\t\tvoid GlobalExceptionHandler::newHandler()\n\t\t\t{\n\t\t\t\tthrow Exception::OutOfMemory(__FILE__, __LINE__);\n\t\t\t}\n\t\t\t\t\n\t\t\tvoid GlobalExceptionHandler::terminate()\n\t\t\t{\n\t\t\t\t\/\/ add cerr to the log stream\n\t\t\t\t\/\/ and write all available information on\n\t\t\t\t\/\/ the exception to the log stream (potentially with an assigned file!)\n\t\t\t\t\/\/ and cerr\n\n\t\t\t\tLog.insert(std::cerr);\n\t\t\t\tLog.error() << endl;\n\t\t\t\tLog.error() << \"---------------------------------------------------\" << endl;\n\t\t\t\tLog.error() << \"FATAL: terminate called!\" << endl;\n\t\t\t\tLog.error() << \"---------------------------------------------------\" << endl;\n\t\t\t\tif ((line_ != -1) && (name_ != \"unknown\"))\n\t\t\t\t{\n\t\t\t\t\tLog.error() << \"last entry in the exception handler: \" << endl;\n\t\t\t\t\tLog.error() << \"exception of type \" << name_.c_str() << \" occured in line \" \n\t\t\t\t\t\t\t\t\t\t\t<< line_ << \" of \" << file_.c_str() << endl;\n\t\t\t\t\tLog.error() << \"error message: \" << message_.c_str() << endl;\n\t\t\t\t}\n\t\t\t\tLog.error() << \"---------------------------------------------------\" << endl;\n\n\t\t\t\t\/\/ if the environment variable declared in BALL_CORE_DUMP_ENVNAME\n\t\t\t\t\/\/ is set, provoke a core dump (this is helpful to get s stack traceback)\n\t\t\t\tif (getenv(BALL_CORE_DUMP_ENVNAME) != 0)\n\t\t\t\t{\n\t\t\t\t\tLog.error() << \"dumping core file.... (to avoid this, unset \" << BALL_CORE_DUMP_ENVNAME \n\t\t\t\t\t\t\t\t\t\t\t<< \" in your environment)\" << endl;\n\t\t\t\t\t\/\/ provoke a core dump \n\t\t\t\t\tkill(getpid(), SIGSEGV);\n\t\t\t\t}\n\n\t\t\t\t\/\/ otherwise exit cleanly\n\t\t\t\texit(1);\n\t\t\t}\n\t\t\t\t\n\t\t\tvoid GlobalExceptionHandler::set\n\t\t\t\t(const string& file, int line,\n\t\t\t\t const string& name, const string& message)\n\t\t\t{\n\t\t\t\tname_ = name;\n\t\t\t\tline_ = line;\n\t\t\t\tmessage_ = message;\n\t\t\t\tfile_ = file;\n\t\t\t}\n\t\t\t\n\t\t\tvoid GlobalExceptionHandler::setName(const string& name)\n\t\t\t{\n\t\t\t\tname_ = name;\n\t\t\t}\n\t\t\t\n\t\t\tvoid GlobalExceptionHandler::setMessage(const string& message)\n\t\t\t{\n\t\t\t\tmessage_ = message;\n\t\t\t}\n\t\t\t\n\t\t\tvoid GlobalExceptionHandler::setFile(const string& file)\n\t\t\t{\n\t\t\t\tfile_ = file;\n\t\t\t}\n\t\t\t\n\t\t\tvoid GlobalExceptionHandler::setLine(int line) \n\t\t\t{\n\t\t\t\tline_ = line;\n\t\t\t}\n\n\t\t\tstring\tGlobalExceptionHandler::name_\t\t\t= \"unknown exception\";\n\t\t\tint\t\t\tGlobalExceptionHandler::line_\t\t\t= -1;\n\t\t\tstring\tGlobalExceptionHandler::message_\t= \" - \";\n\t\t\tstring\tGlobalExceptionHandler::file_\t\t\t= \"unknown\";\n\n\n\n\t\t\t\/\/ create a global instance of the exception handler\n\t\t\tGlobalExceptionHandler globalHandler;\n\n\t} \/\/ namespace Exception\n\n} \/\/ namespace BALL\n<commit_msg>fixed: spelling error<commit_after>\/\/ $Id: exception.C,v 1.14 2000\/09\/01 10:15:29 anker Exp $\n\n#include <BALL\/COMMON\/exception.h>\n#include <BALL\/COMMON\/logStream.h>\n\n#include <iostream>\n#include <typeinfo>\n#include <exception>\n#include <stdio.h>\n#include <stdlib.h>\t\/\/ for getenv in terminate()\n#include <sys\/types.h>\n#include <signal.h> \/\/ for SIGSEGV and kill\n#include <unistd.h> \/\/ fot getpid\n\n#define BALL_CORE_DUMP_ENVNAME \"BALL_DUMP_CORE\"\n\n#define DEF_EXCEPTION(a,b) \\\n\ta##::##a##(const char* file, int line)\\\n\t\t: GeneralException(file, line, #a, b)\\\n\t{\\\n\t}\\\n\\\n\t\n\nusing std::string;\nusing std::endl;\n\nnamespace BALL \n{\n\n\tnamespace Exception \n\t{\n\n\t\t\tGeneralException::GeneralException() \n\t\t\t\t:\tfile_(\"?\"),\n\t\t\t\t\tline_(-1),\n\t\t\t\t\tname_(\"GeneralException\"),\n\t\t\t\t\tmessage_(\"unspecified error\")\n\t\t\t{\n\t\t\t\tglobalHandler.set(file_, line_, name_, message_);\n\t\t\t}\n\n\t\t\tGeneralException::GeneralException(const char* file, int line, const string& name, const string& message) \n\t\t\t\t:\tfile_(file),\n\t\t\t\t\tline_(line),\n\t\t\t\t\tname_(name),\n\t\t\t\t\tmessage_(message)\n\t\t\t{\n\t\t\t\tglobalHandler.set(file_, line_, name_, message_);\n\t\t\t}\n\n\t\t\tGeneralException::GeneralException(const GeneralException& exception)\n\t\t\t\t:\tfile_(exception.file_),\n\t\t\t\t\tline_(exception.line_),\n\t\t\t\t\tname_(exception.name_),\n\t\t\t\t\tmessage_(exception.message_)\n\t\t\t{\n\t\t\t}\n\n\t\t\tGeneralException::~GeneralException()\n\t\t\t{\n\t\t\t}\n\t\t\n\n\t\t\tstring GeneralException::getName() const\n\t\t\t{\n\t\t\t\treturn name_;\n\t\t\t}\n\n\t\t\tstring GeneralException::getMessage() const\n\t\t\t{\n\t\t\t\treturn message_;\n\t\t\t}\n\n\t\t\tstring GeneralException::getFile() const\n\t\t\t{\n\t\t\t\treturn file_;\n\t\t\t}\n\t\t\t\n\t\t\tint GeneralException::getLine() const\n\t\t\t{\n\t\t\t\treturn line_;\n\t\t\t}\n\n\t\t\tIndexUnderflow::IndexUnderflow(const char* file, int line, Index index, Size size)\n\t\t\t\t: GeneralException(file, line, \"IndexUnderflow\", \"\"),\n\t\t\t\t\tsize_(size),\n\t\t\t\t\tindex_(index)\n\t\t\t{\n\t\t\t\tmessage_ = \"the given index was too small: \";\n\t\t\t\tchar buf[40];\n\n\t\t\t\tsprintf(buf, \"%ld\", (long)index);\n\t\t\t\tmessage_ += buf;\n\t\t\t\tmessage_ += \" (size = \";\n\n\t\t\t\tsprintf(buf, \"%ld\", (long)size);\n\t\t\t\tmessage_ += buf;\n\t\t\t\tmessage_ += \")\";\n\n\t\t\t\tglobalHandler.setMessage(message_);\n\t\t\t}\n\n\t\t\tIndexOverflow::IndexOverflow(const char* file, int line, Index index, Size size)\n\t\t\t\t:\tGeneralException(file, line, \"IndexOverflow\", \"an index was too large\"),\n\t\t\t\t\tsize_(size),\n\t\t\t\t\tindex_(index)\n\t\t\t{\n\t\t\t\tmessage_ = \"the given index was too large: \";\n\t\t\t\tchar buf[40];\n\n\t\t\t\tsprintf(buf, \"%ld\", (long)index);\n\t\t\t\tmessage_ += buf;\n\t\t\t\tmessage_ += \" (size = \";\n\n\t\t\t\tsprintf(buf, \"%ld\", (long)size);\n\t\t\t\tmessage_ += buf;\n\t\t\t\tmessage_ += \")\";\n\n\t\t\t\tglobalHandler.setMessage(message_);\n\t\t\t}\n\n\t\t\tOutOfMemory::OutOfMemory(const char* file, int line, Size size)\n\t\t\t\t:\tGeneralException(file, line, \"OutOfMemory\", \"a memory allocation failed\"),\n\t\t\t\t\tsize_(size)\n\t\t\t{\n\t\t\t\tmessage_ = \"unable to allocate enough memory (size = \";\n\t\t\t\tchar buf[40];\n\n\t\t\t\tsprintf(buf, \"%ld\", (long)size_);\n\t\t\t\tmessage_ += buf;\n\t\t\t\tmessage_ += \" bytes) \";\n\n\t\t\t\tglobalHandler.setMessage(message_);\n\t\t\t}\n\n\t\t\tOutOfMemory::~OutOfMemory() throw()\n\t\t\t{\n\t\t\t}\n\n\t\t\tSizeUnderflow::SizeUnderflow(const char* file, int line, Size size)\n\t\t\t\t:\tGeneralException(file, line, \"SizeUnderflow\", \"\"),\n\t\t\t\t\tsize_(size)\n\t\t\t{\n\t\t\t\tmessage_ = \"the given size was too small: \";\n\t\t\t\tchar buf[40];\n\t\t\t\tsprintf(buf, \"%ld\", (long)size);\n\t\t\t\t\n\t\t\t\tmessage_ += buf;\n\t\t\t\tglobalHandler.setMessage(message_);\n\t\t\t}\n\n\t\t\tFileNotFound::FileNotFound(const char* file, int line, const string& filename)\n\t\t\t\t:\tGeneralException(file, line, \"FileNotFound\", \"\"),\n\t\t\t\t\tfilename_(filename)\n\t\t\t{\n\t\t\t\tmessage_ = \"the file \" + filename + \" could not be found\";\n\t\t\t\tglobalHandler.setMessage(message_);\n\t\t\t}\n\n\t\t\tstring FileNotFound::getFilename() const\n\t\t\t{\n\t\t\t\treturn filename_;\n\t\t\t}\n\t\t\n\n\t\t\tInvalidFormat::InvalidFormat(const char* file, int line, const string& s)\n\t\t\t\t:\tGeneralException(file, line, \"InvalidFormat\", \"\"),\n\t\t\t\t\tformat_(s)\n\t\t\t{\n\t\t\t\tmessage_ = \"problem converting '\";\n\t\t\t\tmessage_.append(s + \"' to a number.\");\n\n\t\t\t\tglobalHandler.setMessage(message_);\n\t\t\t}\n\t\t\n\n\t\t\tDEF_EXCEPTION(DivisionByZero, \"a division by zero was requested\")\n\n\t\t\tDEF_EXCEPTION(InvalidRange, \"the range of the operation was invalid\")\n\n\t\t\tDEF_EXCEPTION(NullPointer, \"a null pointer was specified\")\n\n\t\t\tDEF_EXCEPTION(InvalidIterator, \"the iterator is invalid - probably it is not bound to a container\")\n\n\t\t\tDEF_EXCEPTION(IncompatibleIterators, \"the iterator could not be assigned because it is bound to a different container\")\n\n\t\t\tDEF_EXCEPTION(NotImplemented, \"this method has not been implemented yet. Feel free to complain about it!\")\n\n\t\t\tDEF_EXCEPTION(IllegalTreeOperation, \"an illegal tree operation was requested\")\n\n\t\t\tDEF_EXCEPTION(BufferOverflow, \"the maximum buffersize has been reached\")\n\n\t\t\tDEF_EXCEPTION(OutOfGrid, \"a point was outside a grid\")\n\n\t\t\n\t\t\tGlobalExceptionHandler::GlobalExceptionHandler()\n\t\t\t{\n\t\t\t\tstd::set_terminate(terminate);\n\t\t\t\tstd::set_unexpected(terminate);\n\t\t\t\tstd::set_new_handler(newHandler);\n\t\t\t}\n\n\t\t\tvoid GlobalExceptionHandler::newHandler()\n\t\t\t{\n\t\t\t\tthrow Exception::OutOfMemory(__FILE__, __LINE__);\n\t\t\t}\n\t\t\t\t\n\t\t\tvoid GlobalExceptionHandler::terminate()\n\t\t\t{\n\t\t\t\t\/\/ add cerr to the log stream\n\t\t\t\t\/\/ and write all available information on\n\t\t\t\t\/\/ the exception to the log stream (potentially with an assigned file!)\n\t\t\t\t\/\/ and cerr\n\n\t\t\t\tLog.insert(std::cerr);\n\t\t\t\tLog.error() << endl;\n\t\t\t\tLog.error() << \"---------------------------------------------------\" << endl;\n\t\t\t\tLog.error() << \"FATAL: terminate called!\" << endl;\n\t\t\t\tLog.error() << \"---------------------------------------------------\" << endl;\n\t\t\t\tif ((line_ != -1) && (name_ != \"unknown\"))\n\t\t\t\t{\n\t\t\t\t\tLog.error() << \"last entry in the exception handler: \" << endl;\n\t\t\t\t\tLog.error() << \"exception of type \" << name_.c_str() << \" occured in line \" \n\t\t\t\t\t\t\t\t\t\t\t<< line_ << \" of \" << file_.c_str() << endl;\n\t\t\t\t\tLog.error() << \"error message: \" << message_.c_str() << endl;\n\t\t\t\t}\n\t\t\t\tLog.error() << \"---------------------------------------------------\" << endl;\n\n\t\t\t\t\/\/ if the environment variable declared in BALL_CORE_DUMP_ENVNAME\n\t\t\t\t\/\/ is set, provoke a core dump (this is helpful to get s stack traceback)\n\t\t\t\tif (getenv(BALL_CORE_DUMP_ENVNAME) != 0)\n\t\t\t\t{\n\t\t\t\t\tLog.error() << \"dumping core file.... (to avoid this, unset \" << BALL_CORE_DUMP_ENVNAME \n\t\t\t\t\t\t\t\t\t\t\t<< \" in your environment)\" << endl;\n\t\t\t\t\t\/\/ provoke a core dump \n\t\t\t\t\tkill(getpid(), SIGSEGV);\n\t\t\t\t}\n\n\t\t\t\t\/\/ otherwise exit cleanly\n\t\t\t\texit(1);\n\t\t\t}\n\t\t\t\t\n\t\t\tvoid GlobalExceptionHandler::set\n\t\t\t\t(const string& file, int line,\n\t\t\t\t const string& name, const string& message)\n\t\t\t{\n\t\t\t\tname_ = name;\n\t\t\t\tline_ = line;\n\t\t\t\tmessage_ = message;\n\t\t\t\tfile_ = file;\n\t\t\t}\n\t\t\t\n\t\t\tvoid GlobalExceptionHandler::setName(const string& name)\n\t\t\t{\n\t\t\t\tname_ = name;\n\t\t\t}\n\t\t\t\n\t\t\tvoid GlobalExceptionHandler::setMessage(const string& message)\n\t\t\t{\n\t\t\t\tmessage_ = message;\n\t\t\t}\n\t\t\t\n\t\t\tvoid GlobalExceptionHandler::setFile(const string& file)\n\t\t\t{\n\t\t\t\tfile_ = file;\n\t\t\t}\n\t\t\t\n\t\t\tvoid GlobalExceptionHandler::setLine(int line) \n\t\t\t{\n\t\t\t\tline_ = line;\n\t\t\t}\n\n\t\t\tstring\tGlobalExceptionHandler::name_\t\t\t= \"unknown exception\";\n\t\t\tint\t\t\tGlobalExceptionHandler::line_\t\t\t= -1;\n\t\t\tstring\tGlobalExceptionHandler::message_\t= \" - \";\n\t\t\tstring\tGlobalExceptionHandler::file_\t\t\t= \"unknown\";\n\n\n\n\t\t\t\/\/ create a global instance of the exception handler\n\t\t\tGlobalExceptionHandler globalHandler;\n\n\t} \/\/ namespace Exception\n\n} \/\/ namespace BALL\n<|endoftext|>"} {"text":"<commit_before><commit_msg>samples_index: update examples status<commit_after><|endoftext|>"} {"text":"<commit_before>\/\/ OS-specific networking includes\n\/\/ -------------------------------\n#ifdef __WIN32\n #include <winsock2.h>\n typedef int socklen_t;\n#else\n extern \"C\" {\n #include <sys\/types.h>\n #include <sys\/socket.h>\n #include <netinet\/in.h>\n #include <arpa\/inet.h>\n #include <netdb.h>\n #include <fcntl.h>\n }\n\n typedef int SOCKET;\n typedef sockaddr_in SOCKADDR_IN;\n typedef sockaddr SOCKADDR;\n #define SOCKET_ERROR -1\n#endif\n\n\/\/ Socket used for all communications\nSOCKET sock;\n\n\/\/ Address of the remote server\nSOCKADDR_IN addr;\n\n\/\/ Buffer used to return dynamic strings to the caller\n#define BUFFER_SIZE 1024\nchar return_buffer[BUFFER_SIZE];\n\n\/\/ exposed functions\n\/\/ ------------------------------\n\nconst char* SUCCESS = \"1\\0\"; \/\/ string representing success\n\n\/\/ arg1: ip(in the xx.xx.xx.xx format)\n\/\/ arg2: port(a short)\n\/\/ return: NULL on failure, SUCCESS otherwise\nextern \"C\" __declspec(dllexport) const char* establish_connection(int n, char *v[])\n{\n \/\/ extract args\n \/\/ ------------\n if(n < 2) return 0;\n const char* ip = v[0];\n const char* port_s = v[1];\n unsigned short port = atoi(port_s);\n\n \/\/ set up network stuff\n \/\/ --------------------\n #ifdef __WIN32\n WSADATA wsa;\n WSAStartup(MAKEWORD(2,0),&wsa);\n #endif\n sock = socket(AF_INET,SOCK_DGRAM,0);\n\n \/\/ make the socket non-blocking\n \/\/ ----------------------------\n #ifdef __WIN32\n unsigned long iMode=1;\n ioctlsocket(sock,FIONBIO,&iMode);\n #else\n fcntl(sock, F_SETFL, O_NONBLOCK);\n #endif\n\n \/\/ establish a connection to the server\n \/\/ ------------------------------------\n memset(&addr,0,sizeof(SOCKADDR_IN));\n addr.sin_family=AF_INET;\n addr.sin_port=htons(port);\n\n \/\/ convert the string representation of the ip to a byte representation\n addr.sin_addr.s_addr=inet_addr(ip);\n\n return SUCCESS;\n}\n\n\/\/ arg1: string message to send\n\/\/ return: NULL on failure, SUCCESS otherwise\nextern \"C\" __declspec(dllexport) const char* send_message(int n, char *v[])\n{\n \/\/ extract the args\n if(n < 1) return 0;\n const char* msg = v[0];\n\n \/\/ send the message\n int rc = sendto(sock,msg,strlen(msg),0,(SOCKADDR*)&addr,sizeof(SOCKADDR));\n\n \/\/ check for errors\n if (rc != -1) {\n return SUCCESS;\n }\n else {\n return 0;\n }\n}\n\n\/\/ no args\n\/\/ return: message if any received, NULL otherwise\nextern \"C\" __declspec(dllexport) const char* recv_message(int n, char *v[])\n{\n SOCKADDR_IN sender; \/\/ we will store the sender address here\n\n socklen_t sender_byte_length = sizeof(sender);\n\n \/\/ Try receiving messages until we receive one that's valid, or there are no more messages\n while(1) {\n int rc = recvfrom(sock, return_buffer, BUFFER_SIZE,0,(SOCKADDR*) &sender,&sender_byte_length);\n if(rc > 0) {\n \/\/ we could read something\n\n if(sender.sin_addr.s_addr != addr.sin_addr.s_addr) {\n continue; \/\/ not our connection, ignore and try again\n } else {\n return_buffer[rc] = '0'; \/\/ 0-terminate the string\n return return_buffer;\n }\n }\n else {\n break; \/\/ no more messages, stop trying to receive\n }\n }\n\n return 0;\n}\n<commit_msg>Linux compile-fix for DLLSocket\/main.cpp<commit_after>\/\/ OS-specific networking includes\n\/\/ -------------------------------\n#ifdef __WIN32\n #include <winsock2.h>\n typedef int socklen_t;\n#else\n extern \"C\" {\n #include <sys\/types.h>\n #include <sys\/socket.h>\n #include <netinet\/in.h>\n #include <arpa\/inet.h>\n #include <netdb.h>\n #include <fcntl.h>\n #include <stdlib.h>\n #include <string.h>\n }\n\n typedef int SOCKET;\n typedef sockaddr_in SOCKADDR_IN;\n typedef sockaddr SOCKADDR;\n #define SOCKET_ERROR -1\n#endif\n\n\/\/ Socket used for all communications\nSOCKET sock;\n\n\/\/ Address of the remote server\nSOCKADDR_IN addr;\n\n\/\/ Buffer used to return dynamic strings to the caller\n#define BUFFER_SIZE 1024\nchar return_buffer[BUFFER_SIZE];\n\n\/\/ exposed functions\n\/\/ ------------------------------\n\nconst char* SUCCESS = \"1\\0\"; \/\/ string representing success\n\n#ifdef __WIN32\n #define DLL_EXPORT __declspec(dllexport)\n#else\n #define DLL_EXPORT _attribute__ ((visibility (\"default\")))\n#endif\n\n\/\/ arg1: ip(in the xx.xx.xx.xx format)\n\/\/ arg2: port(a short)\n\/\/ return: NULL on failure, SUCCESS otherwise\nextern \"C\" DLL_EXPORT const char* establish_connection(int n, char *v[])\n{\n \/\/ extract args\n \/\/ ------------\n if(n < 2) return 0;\n const char* ip = v[0];\n const char* port_s = v[1];\n unsigned short port = atoi(port_s);\n\n \/\/ set up network stuff\n \/\/ --------------------\n #ifdef __WIN32\n WSADATA wsa;\n WSAStartup(MAKEWORD(2,0),&wsa);\n #endif\n sock = socket(AF_INET,SOCK_DGRAM,0);\n\n \/\/ make the socket non-blocking\n \/\/ ----------------------------\n #ifdef __WIN32\n unsigned long iMode=1;\n ioctlsocket(sock,FIONBIO,&iMode);\n #else\n fcntl(sock, F_SETFL, O_NONBLOCK);\n #endif\n\n \/\/ establish a connection to the server\n \/\/ ------------------------------------\n memset(&addr,0,sizeof(SOCKADDR_IN));\n addr.sin_family=AF_INET;\n addr.sin_port=htons(port);\n\n \/\/ convert the string representation of the ip to a byte representation\n addr.sin_addr.s_addr=inet_addr(ip);\n\n return SUCCESS;\n}\n\n\/\/ arg1: string message to send\n\/\/ return: NULL on failure, SUCCESS otherwise\nextern \"C\" DLL_EXPORT const char* send_message(int n, char *v[])\n{\n \/\/ extract the args\n if(n < 1) return 0;\n const char* msg = v[0];\n\n \/\/ send the message\n int rc = sendto(sock,msg,strlen(msg),0,(SOCKADDR*)&addr,sizeof(SOCKADDR));\n\n \/\/ check for errors\n if (rc != -1) {\n return SUCCESS;\n }\n else {\n return 0;\n }\n}\n\n\/\/ no args\n\/\/ return: message if any received, NULL otherwise\nextern \"C\" DLL_EXPORT const char* recv_message(int n, char *v[])\n{\n SOCKADDR_IN sender; \/\/ we will store the sender address here\n\n socklen_t sender_byte_length = sizeof(sender);\n\n \/\/ Try receiving messages until we receive one that's valid, or there are no more messages\n while(1) {\n int rc = recvfrom(sock, return_buffer, BUFFER_SIZE,0,(SOCKADDR*) &sender,&sender_byte_length);\n if(rc > 0) {\n \/\/ we could read something\n\n if(sender.sin_addr.s_addr != addr.sin_addr.s_addr) {\n continue; \/\/ not our connection, ignore and try again\n } else {\n return_buffer[rc] = '0'; \/\/ 0-terminate the string\n return return_buffer;\n }\n }\n else {\n break; \/\/ no more messages, stop trying to receive\n }\n }\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"MineControllerSystem.h\"\n#include \"Transform.h\"\n#include \"RenderInfo.h\"\n#include \"GraphicsBackendSystem.h\"\n#include <AglMatrix.h>\n#include <AglQuaternion.h>\n#include \"InputBackendSystem.h\"\n#include <Control.h>\n#include \"PhysicsBody.h\"\n#include \"BodyInitData.h\"\n#include \"PhysicsSystem.h\"\n#include \"ShipModule.h\"\n#include \"StandardMine.h\"\n#include \"PhysicsSystem.h\"\n#include <PhysicsController.h>\n#include \"SpawnSoundEffectPacket.h\"\n\nMineControllerSystem::MineControllerSystem(TcpServer* p_server)\n\t: EntitySystem(SystemType::MineControllerSystem, 1, ComponentType::StandardMine)\n{\n\tm_server = p_server;\n}\n\n\nMineControllerSystem::~MineControllerSystem()\n{\n}\n\nvoid MineControllerSystem::initialize()\n{\n}\n\nvoid MineControllerSystem::processEntities(const vector<Entity*>& p_entities)\n{\n\tfloat dt = m_world->getDelta();\n\n\tfor (unsigned int i = 0; i < p_entities.size(); i++)\n\t{\n\t\tStandardMine* mine = static_cast<StandardMine*>(p_entities[i]->getComponent(ComponentType::StandardMine));\n\t\tmine->m_age += dt;\n\n\t\t\/\/Check collision\n\t\tif (mine->m_age > 2)\n\t\t{\n\t\t\tPhysicsBody* pb = static_cast<PhysicsBody*>(p_entities[i]->getComponent(ComponentType::PhysicsBody));\n\t\t\tPhysicsSystem* ps = static_cast<PhysicsSystem*>(m_world->getSystem(SystemType::PhysicsSystem));\n\n\t\t\tvector<unsigned int> col = ps->getController()->CollidesWith(pb->m_id);\n\t\t\tBody* b = ps->getController()->getBody(pb->m_id);\n\t\t\tif (mine->m_age > 2 && col.size() > 0)\n\t\t\t{\n\t\t\t\tps->getController()->ApplyExternalImpulse(b->GetWorld().GetTranslation(), 300);\n\t\t\t\tmine->m_age = 0;\n\n\t\t\t\t\/\/Send an explosion sound effect\n\n\t\t\t\tTransform* t = static_cast<Transform*>(p_entities[i]->getComponent(ComponentType::Transform));\n\n\t\t\t\tSpawnSoundEffectPacket soundEffectPacket;\n\t\t\t\tsoundEffectPacket.soundIdentifier = (int)SpawnSoundEffectPacket::Explosion;\n\t\t\t\tsoundEffectPacket.positional = true;\n\t\t\t\tsoundEffectPacket.position = t->getTranslation();\n\t\t\t\tsoundEffectPacket.attachedToNetsyncEntity = -1; \/\/ entity->getIndex();\n\t\t\t\tm_server->broadcastPacket(soundEffectPacket.pack());\n\t\t\t}\n\t\t}\t\n\t}\n}<commit_msg>Started on damage from mine<commit_after>#include \"MineControllerSystem.h\"\n#include \"Transform.h\"\n#include \"RenderInfo.h\"\n#include \"GraphicsBackendSystem.h\"\n#include <AglMatrix.h>\n#include <AglQuaternion.h>\n#include \"InputBackendSystem.h\"\n#include <Control.h>\n#include \"PhysicsBody.h\"\n#include \"BodyInitData.h\"\n#include \"PhysicsSystem.h\"\n#include \"ShipModule.h\"\n#include \"StandardMine.h\"\n#include \"PhysicsSystem.h\"\n#include <PhysicsController.h>\n#include \"SpawnSoundEffectPacket.h\"\n\nMineControllerSystem::MineControllerSystem(TcpServer* p_server)\n\t: EntitySystem(SystemType::MineControllerSystem, 1, ComponentType::StandardMine)\n{\n\tm_server = p_server;\n}\n\n\nMineControllerSystem::~MineControllerSystem()\n{\n}\n\nvoid MineControllerSystem::initialize()\n{\n}\n\nvoid MineControllerSystem::processEntities(const vector<Entity*>& p_entities)\n{\n\tfloat dt = m_world->getDelta();\n\n\tfor (unsigned int i = 0; i < p_entities.size(); i++)\n\t{\n\t\tStandardMine* mine = static_cast<StandardMine*>(p_entities[i]->getComponent(ComponentType::StandardMine));\n\t\tmine->m_age += dt;\n\n\t\t\/\/Check collision\n\t\tif (mine->m_age > 2)\n\t\t{\n\t\t\tPhysicsBody* pb = static_cast<PhysicsBody*>(p_entities[i]->getComponent(ComponentType::PhysicsBody));\n\t\t\tPhysicsSystem* ps = static_cast<PhysicsSystem*>(m_world->getSystem(SystemType::PhysicsSystem));\n\n\t\t\tvector<unsigned int> col = ps->getController()->CollidesWith(pb->m_id);\n\t\t\tBody* b = ps->getController()->getBody(pb->m_id);\n\t\t\tif (mine->m_age > 2 && col.size() > 0)\n\t\t\t{\n\t\t\t\t\/\/Do some damage\n\t\t\t\tfor (unsigned int j = 0; j < col.size(); j++)\n\t\t\t\t{\n\t\t\t\t\t\/*Entity* hitEntity = ps->getEntity(col[j]);\n\t\t\t\t\tShipModule* hitModule = static_cast<ShipModule*>(hitEntity->getComponent(ComponentType::ShipModule));\n\t\t\t\t\tif (hitModule)\n\t\t\t\t\t\thitModule->m_health = 0;*\/\n\t\t\t\t}\n\n\n\t\t\t\t\/\/Send a shockwave\n\t\t\t\tps->getController()->ApplyExternalImpulse(b->GetWorld().GetTranslation(), 300);\n\t\t\t\tmine->m_age = 0;\n\n\t\t\t\t\/\/Send an explosion sound effect\n\t\t\t\tTransform* t = static_cast<Transform*>(p_entities[i]->getComponent(ComponentType::Transform));\n\n\t\t\t\tSpawnSoundEffectPacket soundEffectPacket;\n\t\t\t\tsoundEffectPacket.soundIdentifier = (int)SpawnSoundEffectPacket::Explosion;\n\t\t\t\tsoundEffectPacket.positional = true;\n\t\t\t\tsoundEffectPacket.position = t->getTranslation();\n\t\t\t\tsoundEffectPacket.attachedToNetsyncEntity = -1; \/\/ entity->getIndex();\n\t\t\t\tm_server->broadcastPacket(soundEffectPacket.pack());\n\t\t\t}\n\t\t}\t\n\t}\n}<|endoftext|>"} {"text":"<commit_before>\/\/===- llvm-cov.cpp - LLVM coverage tool ----------------------------------===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ llvm-cov is a command line tools to analyze and report coverage information.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/ADT\/OwningPtr.h\"\n#include \"llvm\/Support\/CommandLine.h\"\n#include \"llvm\/Support\/GCOV.h\"\n#include \"llvm\/Support\/ManagedStatic.h\"\n#include \"llvm\/Support\/MemoryObject.h\"\n#include \"llvm\/Support\/PrettyStackTrace.h\"\n#include \"llvm\/Support\/Signals.h\"\n#include \"llvm\/Support\/system_error.h\"\nusing namespace llvm;\n\nstatic cl::opt<std::string> SourceFile(cl::Positional, cl::Required,\n cl::desc(\"SOURCEFILE\"));\n\nstatic cl::opt<bool> AllBlocks(\"a\", cl::init(false),\n cl::desc(\"Display all basic blocks\"));\n\nstatic cl::opt<bool> BranchProb(\"b\", cl::init(false),\n cl::desc(\"Display branch probabilities\"));\n\nstatic cl::opt<bool> BranchCount(\"c\", cl::init(false),\n cl::desc(\"Display branch counts instead \"\n \"of percentages (requires -b)\"));\n\nstatic cl::opt<bool> FuncSummary(\"f\", cl::init(false),\n cl::desc(\"Show coverage for each function\"));\n\nstatic cl::opt<bool> UncondBranch(\"u\", cl::init(false),\n cl::desc(\"Display unconditional branch info \"\n \"(requires -b)\"));\n\nstatic cl::OptionCategory DebugCat(\"Internal and debugging options\");\nstatic cl::opt<bool> DumpGCOV(\"dump\", cl::init(false), cl::cat(DebugCat),\n cl::desc(\"Dump the gcov file to stderr\"));\nstatic cl::opt<std::string> InputGCNO(\"gcno\", cl::cat(DebugCat), cl::init(\"\"),\n cl::desc(\"Override inferred gcno file\"));\nstatic cl::opt<std::string> InputGCDA(\"gcda\", cl::cat(DebugCat), cl::init(\"\"),\n cl::desc(\"Override inferred gcda file\"));\n\n\/\/===----------------------------------------------------------------------===\/\/\nint main(int argc, char **argv) {\n \/\/ Print a stack trace if we signal out.\n sys::PrintStackTraceOnErrorSignal();\n PrettyStackTraceProgram X(argc, argv);\n llvm_shutdown_obj Y; \/\/ Call llvm_shutdown() on exit.\n\n cl::ParseCommandLineOptions(argc, argv, \"LLVM code coverage tool\\n\");\n\n if (InputGCNO.empty())\n InputGCNO = SourceFile.substr(0, SourceFile.rfind(\".\")) + \".gcno\";\n if (InputGCDA.empty())\n InputGCDA = SourceFile.substr(0, SourceFile.rfind(\".\")) + \".gcda\";\n\n GCOVFile GF;\n\n OwningPtr<MemoryBuffer> GCNO_Buff;\n if (error_code ec = MemoryBuffer::getFileOrSTDIN(InputGCNO, GCNO_Buff)) {\n errs() << InputGCNO << \": \" << ec.message() << \"\\n\";\n return 1;\n }\n GCOVBuffer GCNO_GB(GCNO_Buff.get());\n if (!GF.readGCNO(GCNO_GB)) {\n errs() << \"Invalid .gcno File!\\n\";\n return 1;\n }\n\n OwningPtr<MemoryBuffer> GCDA_Buff;\n if (error_code ec = MemoryBuffer::getFileOrSTDIN(InputGCDA, GCDA_Buff)) {\n errs() << InputGCDA << \": \" << ec.message() << \"\\n\";\n return 1;\n }\n GCOVBuffer GCDA_GB(GCDA_Buff.get());\n if (!GF.readGCDA(GCDA_GB)) {\n errs() << \"Invalid .gcda File!\\n\";\n return 1;\n }\n\n if (DumpGCOV)\n GF.dump();\n\n GCOVOptions Options(AllBlocks, BranchProb, BranchCount, FuncSummary,\n UncondBranch);\n FileInfo FI(Options);\n GF.collectLineCounts(FI);\n FI.print(InputGCNO, InputGCDA);\n return 0;\n}\n<commit_msg>llvm-cov: Accept the long forms of gcov options<commit_after>\/\/===- llvm-cov.cpp - LLVM coverage tool ----------------------------------===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ llvm-cov is a command line tools to analyze and report coverage information.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/ADT\/OwningPtr.h\"\n#include \"llvm\/Support\/CommandLine.h\"\n#include \"llvm\/Support\/GCOV.h\"\n#include \"llvm\/Support\/ManagedStatic.h\"\n#include \"llvm\/Support\/MemoryObject.h\"\n#include \"llvm\/Support\/PrettyStackTrace.h\"\n#include \"llvm\/Support\/Signals.h\"\n#include \"llvm\/Support\/system_error.h\"\nusing namespace llvm;\n\nstatic cl::opt<std::string> SourceFile(cl::Positional, cl::Required,\n cl::desc(\"SOURCEFILE\"));\n\nstatic cl::opt<bool> AllBlocks(\"a\", cl::init(false),\n cl::desc(\"Display all basic blocks\"));\nstatic cl::alias AllBlocksA(\"all-blocks\", cl::aliasopt(AllBlocks));\n\nstatic cl::opt<bool> BranchProb(\"b\", cl::init(false),\n cl::desc(\"Display branch probabilities\"));\nstatic cl::alias BranchProbA(\"branch-probabilities\", cl::aliasopt(BranchProb));\n\nstatic cl::opt<bool> BranchCount(\"c\", cl::init(false),\n cl::desc(\"Display branch counts instead \"\n \"of percentages (requires -b)\"));\nstatic cl::alias BranchCountA(\"branch-counts\", cl::aliasopt(BranchCount));\n\nstatic cl::opt<bool> FuncSummary(\"f\", cl::init(false),\n cl::desc(\"Show coverage for each function\"));\nstatic cl::alias FuncSummaryA(\"function-summaries\", cl::aliasopt(FuncSummary));\n\nstatic cl::opt<bool> UncondBranch(\"u\", cl::init(false),\n cl::desc(\"Display unconditional branch info \"\n \"(requires -b)\"));\nstatic cl::alias UncondBranchA(\"unconditional-branches\",\n cl::aliasopt(UncondBranch));\n\nstatic cl::OptionCategory DebugCat(\"Internal and debugging options\");\nstatic cl::opt<bool> DumpGCOV(\"dump\", cl::init(false), cl::cat(DebugCat),\n cl::desc(\"Dump the gcov file to stderr\"));\nstatic cl::opt<std::string> InputGCNO(\"gcno\", cl::cat(DebugCat), cl::init(\"\"),\n cl::desc(\"Override inferred gcno file\"));\nstatic cl::opt<std::string> InputGCDA(\"gcda\", cl::cat(DebugCat), cl::init(\"\"),\n cl::desc(\"Override inferred gcda file\"));\n\n\/\/===----------------------------------------------------------------------===\/\/\nint main(int argc, char **argv) {\n \/\/ Print a stack trace if we signal out.\n sys::PrintStackTraceOnErrorSignal();\n PrettyStackTraceProgram X(argc, argv);\n llvm_shutdown_obj Y; \/\/ Call llvm_shutdown() on exit.\n\n cl::ParseCommandLineOptions(argc, argv, \"LLVM code coverage tool\\n\");\n\n if (InputGCNO.empty())\n InputGCNO = SourceFile.substr(0, SourceFile.rfind(\".\")) + \".gcno\";\n if (InputGCDA.empty())\n InputGCDA = SourceFile.substr(0, SourceFile.rfind(\".\")) + \".gcda\";\n\n GCOVFile GF;\n\n OwningPtr<MemoryBuffer> GCNO_Buff;\n if (error_code ec = MemoryBuffer::getFileOrSTDIN(InputGCNO, GCNO_Buff)) {\n errs() << InputGCNO << \": \" << ec.message() << \"\\n\";\n return 1;\n }\n GCOVBuffer GCNO_GB(GCNO_Buff.get());\n if (!GF.readGCNO(GCNO_GB)) {\n errs() << \"Invalid .gcno File!\\n\";\n return 1;\n }\n\n OwningPtr<MemoryBuffer> GCDA_Buff;\n if (error_code ec = MemoryBuffer::getFileOrSTDIN(InputGCDA, GCDA_Buff)) {\n errs() << InputGCDA << \": \" << ec.message() << \"\\n\";\n return 1;\n }\n GCOVBuffer GCDA_GB(GCDA_Buff.get());\n if (!GF.readGCDA(GCDA_GB)) {\n errs() << \"Invalid .gcda File!\\n\";\n return 1;\n }\n\n if (DumpGCOV)\n GF.dump();\n\n GCOVOptions Options(AllBlocks, BranchProb, BranchCount, FuncSummary,\n UncondBranch);\n FileInfo FI(Options);\n GF.collectLineCounts(FI);\n FI.print(InputGCNO, InputGCDA);\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Software License Agreement (BSD License)\n *\n * Point Cloud Library (PCL) - www.pointclouds.org\n * Copyright (c) 2010-2011, Willow Garage, Inc.\n * \n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following\n * disclaimer in the documentation and\/or other materials provided\n * with the distribution.\n * * Neither the name of Willow Garage, Inc. nor the names of its\n * contributors may be used to endorse or promote products derived\n * from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n * $Id: normal_estimation.cpp 1032 2011-05-18 22:43:27Z marton $\n *\n *\/\n\n#include <sensor_msgs\/PointCloud2.h>\n#include <pcl\/io\/pcd_io.h>\n#include <pcl\/features\/normal_3d.h>\n#include <pcl\/console\/print.h>\n#include <pcl\/console\/parse.h>\n#include <pcl\/console\/time.h>\n\nusing namespace pcl;\nusing namespace pcl::io;\nusing namespace pcl::console;\n\nint default_k = 0;\ndouble default_radius = 0.0;\n\nEigen::Vector4f translation;\nEigen::Quaternionf orientation;\n\nvoid\nprintHelp (int argc, char **argv)\n{\n print_error (\"Syntax is: %s input.pcd output.pcd <options>\\n\", argv[0]);\n print_info (\" where options are:\\n\");\n print_info (\" -radius X = use a radius of Xm around each point to determine the neighborhood (default: \"); \n print_value (\"%f\", default_radius); print_info (\")\\n\");\n print_info (\" -k X = use a fixed number of X-nearest neighbors around each point (default: \"); \n print_value (\"%f\", default_k); print_info (\")\\n\");\n}\n\nbool\nloadCloud (const std::string &filename, sensor_msgs::PointCloud2 &cloud)\n{\n TicToc tt;\n print_highlight (\"Loading \"); print_value (\"%s \", filename.c_str ());\n\n tt.tic ();\n if (loadPCDFile (filename, cloud, translation, orientation) < 0)\n return (false);\n print_info (\"[done, \"); print_value (\"%g\", tt.toc ()); print_info (\" ms : \"); print_value (\"%d\", cloud.width * cloud.height); print_info (\" points]\\n\");\n print_info (\"Available dimensions: \"); print_value (\"%s\\n\", pcl::getFieldsList (cloud).c_str ());\n\n return (true);\n}\n\nvoid\ncompute (const sensor_msgs::PointCloud2::ConstPtr &input, sensor_msgs::PointCloud2 &output,\n int k, double radius)\n{\n \/\/ Convert data to PointCloud<T>\n PointCloud<PointXYZ>::Ptr xyz (new PointCloud<PointXYZ>);\n fromROSMsg (*input, *xyz);\n\n \/\/ Estimate\n TicToc tt;\n tt.tic ();\n \n print_highlight (stderr, \"Computing \");\n\n NormalEstimation<pcl::PointXYZ, pcl::Normal> ne;\n ne.setInputCloud (xyz);\n \/\/ne.setSearchMethod (pcl::KdTreeFLANN<pcl::PointXYZ>::Ptr (new pcl::KdTreeFLANN<pcl::PointXYZ>));\n ne.setKSearch (k);\n ne.setRadiusSearch (radius);\n \n PointCloud<Normal> normals;\n ne.compute (normals);\n\n print_info (\"[done, \"); print_value (\"%g\", tt.toc ()); print_info (\" ms : \"); print_value (\"%d\", normals.width * normals.height); print_info (\" points]\\n\");\n\n \/\/ Convert data back\n sensor_msgs::PointCloud2 output_normals;\n toROSMsg (normals, output_normals);\n concatenateFields (*input, output_normals, output);\n}\n\nvoid\nsaveCloud (const std::string &filename, const sensor_msgs::PointCloud2 &output)\n{\n TicToc tt;\n tt.tic ();\n\n print_highlight (\"Saving \"); print_value (\"%s \", filename.c_str ());\n \n pcl::io::savePCDFile (filename, output, translation, orientation, false);\n \n print_info (\"[done, \"); print_value (\"%g\", tt.toc ()); print_info (\" ms : \"); print_value (\"%d\", output.width * output.height); print_info (\" points]\\n\");\n}\n\n\/* ---[ *\/\nint\nmain (int argc, char** argv)\n{\n print_info (\"Estimate surface normals using pcl::NormalEstimation. For more information, use: %s -h\\n\", argv[0]);\n\n if (argc < 3)\n {\n printHelp (argc, argv);\n return (-1);\n }\n\n \/\/ Parse the command line arguments for .pcd files\n std::vector<int> p_file_indices;\n p_file_indices = parse_file_extension_argument (argc, argv, \".pcd\");\n if (p_file_indices.size () != 2)\n {\n print_error (\"Need one input PCD file and one output PCD file to continue.\\n\");\n return (-1);\n }\n\n \/\/ Command line parsing\n int k = default_k;\n double radius = default_radius;\n parse_argument (argc, argv, \"-k\", k);\n parse_argument (argc, argv, \"-radius\", radius);\n\n \/\/ Load the first file\n sensor_msgs::PointCloud2::Ptr cloud (new sensor_msgs::PointCloud2);\n if (!loadCloud (argv[p_file_indices[0]], *cloud)) \n return (-1);\n\n \/\/ Perform the feature estimation\n sensor_msgs::PointCloud2 output;\n compute (cloud, output, k, radius);\n\n \/\/ Save into the second file\n saveCloud (argv[p_file_indices[1]], output);\n}\n\n<commit_msg>NormalEstimation tool temporary fix for orgranized point clouds<commit_after>\/*\n * Software License Agreement (BSD License)\n *\n * Point Cloud Library (PCL) - www.pointclouds.org\n * Copyright (c) 2010-2011, Willow Garage, Inc.\n * \n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following\n * disclaimer in the documentation and\/or other materials provided\n * with the distribution.\n * * Neither the name of Willow Garage, Inc. nor the names of its\n * contributors may be used to endorse or promote products derived\n * from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n * $Id: normal_estimation.cpp 1032 2011-05-18 22:43:27Z marton $\n *\n *\/\n\n#include <sensor_msgs\/PointCloud2.h>\n#include <pcl\/io\/pcd_io.h>\n#include <pcl\/features\/normal_3d.h>\n#include <pcl\/console\/print.h>\n#include <pcl\/console\/parse.h>\n#include <pcl\/console\/time.h>\n\nusing namespace pcl;\nusing namespace pcl::io;\nusing namespace pcl::console;\n\nint default_k = 0;\ndouble default_radius = 0.0;\n\nEigen::Vector4f translation;\nEigen::Quaternionf orientation;\n\nvoid\nprintHelp (int argc, char **argv)\n{\n print_error (\"Syntax is: %s input.pcd output.pcd <options>\\n\", argv[0]);\n print_info (\" where options are:\\n\");\n print_info (\" -radius X = use a radius of Xm around each point to determine the neighborhood (default: \"); \n print_value (\"%f\", default_radius); print_info (\")\\n\");\n print_info (\" -k X = use a fixed number of X-nearest neighbors around each point (default: \"); \n print_value (\"%f\", default_k); print_info (\")\\n\");\n}\n\nbool\nloadCloud (const std::string &filename, sensor_msgs::PointCloud2 &cloud)\n{\n TicToc tt;\n print_highlight (\"Loading \"); print_value (\"%s \", filename.c_str ());\n\n tt.tic ();\n if (loadPCDFile (filename, cloud, translation, orientation) < 0)\n return (false);\n print_info (\"[done, \"); print_value (\"%g\", tt.toc ()); print_info (\" ms : \"); print_value (\"%d\", cloud.width * cloud.height); print_info (\" points]\\n\");\n print_info (\"Available dimensions: \"); print_value (\"%s\\n\", pcl::getFieldsList (cloud).c_str ());\n\n return (true);\n}\n\nvoid\ncompute (const sensor_msgs::PointCloud2::ConstPtr &input, sensor_msgs::PointCloud2 &output,\n int k, double radius)\n{\n \/\/ Convert data to PointCloud<T>\n PointCloud<PointXYZ>::Ptr xyz (new PointCloud<PointXYZ>);\n fromROSMsg (*input, *xyz);\n\n \/\/ Estimate\n TicToc tt;\n tt.tic ();\n \n print_highlight (stderr, \"Computing \");\n\n NormalEstimation<pcl::PointXYZ, pcl::Normal> ne;\n ne.setInputCloud (xyz);\n ne.setSearchMethod (pcl::search::KdTree<pcl::PointXYZ>::Ptr (new pcl::search::KdTree<pcl::PointXYZ>));\n ne.setKSearch (k);\n ne.setRadiusSearch (radius);\n \n PointCloud<Normal> normals;\n ne.compute (normals);\n\n print_info (\"[done, \"); print_value (\"%g\", tt.toc ()); print_info (\" ms : \"); print_value (\"%d\", normals.width * normals.height); print_info (\" points]\\n\");\n\n \/\/ Convert data back\n sensor_msgs::PointCloud2 output_normals;\n toROSMsg (normals, output_normals);\n concatenateFields (*input, output_normals, output);\n}\n\nvoid\nsaveCloud (const std::string &filename, const sensor_msgs::PointCloud2 &output)\n{\n TicToc tt;\n tt.tic ();\n\n print_highlight (\"Saving \"); print_value (\"%s \", filename.c_str ());\n \n pcl::io::savePCDFile (filename, output, translation, orientation, false);\n \n print_info (\"[done, \"); print_value (\"%g\", tt.toc ()); print_info (\" ms : \"); print_value (\"%d\", output.width * output.height); print_info (\" points]\\n\");\n}\n\n\/* ---[ *\/\nint\nmain (int argc, char** argv)\n{\n print_info (\"Estimate surface normals using pcl::NormalEstimation. For more information, use: %s -h\\n\", argv[0]);\n\n if (argc < 3)\n {\n printHelp (argc, argv);\n return (-1);\n }\n\n \/\/ Parse the command line arguments for .pcd files\n std::vector<int> p_file_indices;\n p_file_indices = parse_file_extension_argument (argc, argv, \".pcd\");\n if (p_file_indices.size () != 2)\n {\n print_error (\"Need one input PCD file and one output PCD file to continue.\\n\");\n return (-1);\n }\n\n \/\/ Command line parsing\n int k = default_k;\n double radius = default_radius;\n parse_argument (argc, argv, \"-k\", k);\n parse_argument (argc, argv, \"-radius\", radius);\n\n \/\/ Load the first file\n sensor_msgs::PointCloud2::Ptr cloud (new sensor_msgs::PointCloud2);\n if (!loadCloud (argv[p_file_indices[0]], *cloud)) \n return (-1);\n\n \/\/ Perform the feature estimation\n sensor_msgs::PointCloud2 output;\n compute (cloud, output, k, radius);\n\n \/\/ Save into the second file\n saveCloud (argv[p_file_indices[1]], output);\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/\/=======================================================================\n\/\/ Copyright (c) 2014-2020 Baptiste Wicht\n\/\/ Distributed under the terms of the MIT License.\n\/\/ (See accompanying file LICENSE or copy at\n\/\/ http:\/\/opensource.org\/licenses\/MIT)\n\/\/=======================================================================\n\n#pragma once\n\n#ifndef ETL_COUNTERS\n\nnamespace etl {\n\n\/*!\n * \\brief Dump all counters values to the console.\n *\/\ninline void dump_counters() {\n \/\/No counters\n}\n\n\/*!\n * \\brief Increase the given counter\n * \\param name The name of the counter to increase\n *\/\ninline void inc_counter([[maybe_unused]] const char* name) {}\n\n} \/\/end of namespace etl\n\n#else\n\n#include <chrono>\n#include <iosfwd>\n#include <iomanip>\n#include <sstream>\n\nnamespace etl {\n\nconstexpr const size_t max_counters = 64;\n\nstruct counter_t {\n const char* name;\n std::atomic<size_t> count;\n\n counter_t() : name(nullptr), count(0) {}\n\n counter_t(const counter_t& rhs) : name(rhs.name), count(rhs.count.load()) {}\n\n counter_t& operator=(const counter_t& rhs) {\n if (&rhs != this) {\n name = rhs.name;\n count = rhs.count.load();\n }\n\n return *this;\n }\n\n counter_t(counter_t&& rhs) : name(std::move(rhs.name)), count(rhs.count.load()) {}\n\n counter_t& operator=(counter_t&& rhs) {\n if (&rhs != this) {\n name = std::move(rhs.name);\n count = rhs.count.load();\n }\n\n return *this;\n }\n};\n\nstruct counters_t {\n std::array<counter_t, max_counters> counters;\n std::mutex lock;\n\n void reset() {\n std::lock_guard<std::mutex> l(lock);\n\n for (auto& counter : counters) {\n counter.name = nullptr;\n counter.count = 0;\n }\n }\n};\n\ninline counters_t& get_counters() {\n static counters_t counters;\n return counters;\n}\n\n\/*!\n * \\brief Reset all counters\n *\/\ninline void reset_counters() {\n decltype(auto) counters = get_counters();\n counters.reset();\n}\n\n\/*!\n * \\brief Dump all counters values to the console.\n *\/\ninline void dump_counters() {\n decltype(auto) counters = get_counters().counters;\n\n \/\/Sort the counters by count (DESC)\n std::sort(counters.begin(), counters.end(), [](auto& left, auto& right) { return left.count > right.count; });\n\n \/\/ Print all the used counters\n for (decltype(auto) counter : counters) {\n if (counter.name) {\n std::cout << counter.name << \": \" << counter.count << std::endl;\n }\n }\n}\n\n\/*!\n * \\brief Increase the given counter\n * \\param name The name of the counter to increase\n *\/\ninline void inc_counter(const char* name) {\n#ifdef ETL_COUNTERS_VERBOSE\n std::cout << \"counter:inc:\" << name << std::endl;\n#endif\n\n decltype(auto) counters = get_counters();\n\n for (decltype(auto) counter : counters.counters) {\n if (counter.name == name) {\n ++counter.count;\n\n return;\n }\n }\n\n std::lock_guard<std::mutex> lock(counters.lock);\n\n for (decltype(auto) counter : counters.counters) {\n if (counter.name == name) {\n ++counter.count;\n\n return;\n }\n }\n\n for (decltype(auto) counter : counters.counters) {\n if (!counter.name) {\n counter.name = name;\n counter.count = 1;\n\n return;\n }\n }\n\n std::cerr << \"Unable to register counter \" << name << std::endl;\n}\n\n} \/\/end of namespace etl\n\n#endif\n<commit_msg>Add support for dump_counters_pretty<commit_after>\/\/=======================================================================\n\/\/ Copyright (c) 2014-2020 Baptiste Wicht\n\/\/ Distributed under the terms of the MIT License.\n\/\/ (See accompanying file LICENSE or copy at\n\/\/ http:\/\/opensource.org\/licenses\/MIT)\n\/\/=======================================================================\n\n#pragma once\n\n#ifndef ETL_COUNTERS\n\nnamespace etl {\n\n\/*!\n * \\brief Dump all counters values to the console.\n *\/\ninline void dump_counters() {\n \/\/No counters\n}\n\n\/*!\n * \\brief Increase the given counter\n * \\param name The name of the counter to increase\n *\/\ninline void inc_counter([[maybe_unused]] const char* name) {}\n\n} \/\/end of namespace etl\n\n#else\n\n#include <chrono>\n#include <iosfwd>\n#include <iomanip>\n#include <sstream>\n\nnamespace etl {\n\nconstexpr const size_t max_counters = 64;\n\nstruct counter_t {\n const char* name;\n std::atomic<size_t> count;\n\n counter_t() : name(nullptr), count(0) {}\n\n counter_t(const counter_t& rhs) : name(rhs.name), count(rhs.count.load()) {}\n\n counter_t& operator=(const counter_t& rhs) {\n if (&rhs != this) {\n name = rhs.name;\n count = rhs.count.load();\n }\n\n return *this;\n }\n\n counter_t(counter_t&& rhs) : name(std::move(rhs.name)), count(rhs.count.load()) {}\n\n counter_t& operator=(counter_t&& rhs) {\n if (&rhs != this) {\n name = std::move(rhs.name);\n count = rhs.count.load();\n }\n\n return *this;\n }\n};\n\nstruct counters_t {\n std::array<counter_t, max_counters> counters;\n std::mutex lock;\n\n void reset() {\n std::lock_guard<std::mutex> l(lock);\n\n for (auto& counter : counters) {\n counter.name = nullptr;\n counter.count = 0;\n }\n }\n};\n\ninline counters_t& get_counters() {\n static counters_t counters;\n return counters;\n}\n\n\/*!\n * \\brief Reset all counters\n *\/\ninline void reset_counters() {\n decltype(auto) counters = get_counters();\n counters.reset();\n}\n\n\/*!\n * \\brief Dump all counters values to the console.\n *\/\ninline void dump_counters() {\n decltype(auto) counters = get_counters().counters;\n\n \/\/Sort the counters by count (DESC)\n std::sort(counters.begin(), counters.end(), [](auto& left, auto& right) { return left.count > right.count; });\n\n \/\/ Print all the used counters\n for (decltype(auto) counter : counters) {\n if (counter.name) {\n std::cout << counter.name << \": \" << counter.count << std::endl;\n }\n }\n}\n\n\/*!\n * \\brief Dump all counters values to the console.\n *\/\ninline void dump_counters_pretty() {\n decltype(auto) counters = get_counters().counters;\n\n if(counters.empty()){\n std::cout << \"No counters have been recorded!\" << std::endl;\n return;\n }\n\n std::cout << std::endl;\n\n \/\/Sort the counters by count (DESC)\n std::sort(counters.begin(), counters.end(), [](auto& left, auto& right) { return left.count > right.count; });\n\n constexpr size_t columns = 2;\n\n std::string column_name[columns];\n column_name[0] = \"Counter\";\n column_name[1] = \"Count\";\n\n size_t column_length[columns];\n column_length[0] = column_name[0].size();\n column_length[1] = column_name[1].size();\n\n \/\/ Compute the width of each column\n for (decltype(auto) counter : counters) {\n if (counter.name) {\n column_length[0] = std::max(column_length[0], std::string(counter.name).size());\n column_length[1] = std::max(column_length[1], std::to_string(counter.count).size());\n }\n }\n\n const size_t line_length = (columns + 1) * 1 + 2 + (columns - 1) * 2 + std::accumulate(column_length, column_length + columns, 0);\n\n std::cout << \" \" << std::string(line_length, '-') << '\\n';\n\n printf(\" | %-*s | %-*s |\\n\",\n int(column_length[0]), column_name[0].c_str(),\n int(column_length[1]), column_name[1].c_str());\n\n \/\/ Print all the used counters\n for (decltype(auto) counter : counters) {\n if (counter.name) {\n printf(\" | %-*s | %-*s |\\n\",\n int(column_length[0]), counter.name,\n int(column_length[1]), std::to_string(counter.count).c_str());\n }\n }\n\n std::cout << \" \" << std::string(line_length, '-') << '\\n';\n\n \/\/ Print all the used counters\n for (decltype(auto) counter : counters) {\n if (counter.name) {\n std::cout << counter.name << \": \" << counter.count << std::endl;\n }\n }\n}\n\n\/*!\n * \\brief Increase the given counter\n * \\param name The name of the counter to increase\n *\/\ninline void inc_counter(const char* name) {\n#ifdef ETL_COUNTERS_VERBOSE\n std::cout << \"counter:inc:\" << name << std::endl;\n#endif\n\n decltype(auto) counters = get_counters();\n\n for (decltype(auto) counter : counters.counters) {\n if (counter.name == name) {\n ++counter.count;\n\n return;\n }\n }\n\n std::lock_guard<std::mutex> lock(counters.lock);\n\n for (decltype(auto) counter : counters.counters) {\n if (counter.name == name) {\n ++counter.count;\n\n return;\n }\n }\n\n for (decltype(auto) counter : counters.counters) {\n if (!counter.name) {\n counter.name = name;\n counter.count = 1;\n\n return;\n }\n }\n\n std::cerr << \"Unable to register counter \" << name << std::endl;\n}\n\n} \/\/end of namespace etl\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/\/ vim:ts=2:sw=2:expandtab:autoindent:filetype=cpp:\n\/*\nThe MIT License\n\nCopyright (c) 2008, 2009 Flusspferd contributors (see \"CONTRIBUTORS\" or\n http:\/\/flusspferd.org\/contributors.txt)\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n*\/\n\n#ifndef FLUSSPFERD_CREATE_HPP\n#define FLUSSPFERD_CREATE_HPP\n\n#ifndef PREPROC_DEBUG\n#include \"object.hpp\"\n#include \"function.hpp\"\n#include \"array.hpp\"\n#include \"native_function.hpp\"\n#include \"local_root_scope.hpp\"\n#include <boost\/type_traits\/is_function.hpp>\n#include <boost\/utility\/enable_if.hpp>\n#include <boost\/mpl\/bool.hpp>\n#include <boost\/range.hpp>\n#include <boost\/parameter\/parameters.hpp>\n#include <boost\/parameter\/keyword.hpp>\n#include <boost\/parameter\/name.hpp>\n#include <boost\/parameter\/binding.hpp>\n#endif\n#include \"detail\/limit.hpp\"\n#include <boost\/preprocessor.hpp>\n\nnamespace flusspferd {\n\nclass native_object_base;\nclass function;\nclass native_function_base;\n\n#ifndef IN_DOXYGEN\nnamespace detail {\n\nobject create_native_object(object const &proto);\nobject create_native_enumerable_object(object const &proto);\n\n}\n#endif\n\n\/**\n * @name Creating values\n * @addtogroup create\n *\/\n\/\/@{\n\/**\n * Create a simple object.\n *\n * Creates a new object with prototype @p proto. If proto is @c null,\n * @c Object.prototype will be used.\n *\n * @param proto The object to use as prototype.\n * @return The new object.\n *\/\nobject create_object(object const &proto = object());\n\n#ifndef IN_DOXYGEN\n\n#define FLUSSPFERD_FN_CREATE_NATIVE_OBJECT(z, n_args, d) \\\n template< \\\n typename T \\\n BOOST_PP_ENUM_TRAILING_PARAMS(n_args, typename T) \\\n > \\\n typename boost::enable_if< boost::mpl::not_< \\\n typename T::class_info::custom_enumerate >, \\\n T& >::type \\\n create_native_object( \\\n object proto \\\n BOOST_PP_ENUM_TRAILING_BINARY_PARAMS(n_args, T, const & param) \\\n ) { \\\n if (proto.is_null()) \\\n proto = current_context().prototype<T>(); \\\n local_root_scope scope; \\\n object obj = detail::create_native_object(proto); \\\n return *(new T(obj BOOST_PP_ENUM_TRAILING_PARAMS(n_args, param))); \\\n } \\\n \\\n template< \\\n typename T \\\n BOOST_PP_ENUM_TRAILING_PARAMS(n_args, typename T) \\\n > \\\n typename boost::enable_if< \\\n typename T::class_info::custom_enumerate, \\\n T& >::type \\\n create_native_object( \\\n object proto \\\n BOOST_PP_ENUM_TRAILING_BINARY_PARAMS(n_args, T, const & param) \\\n ) { \\\n if (proto.is_null()) \\\n proto = current_context().prototype<T>(); \\\n local_root_scope scope; \\\n object obj = detail::create_native_enumerable_object(proto); \\\n return *(new T(obj BOOST_PP_ENUM_TRAILING_PARAMS(n_args, param))); \\\n } \\\n \/* *\/\n\nBOOST_PP_REPEAT(\n BOOST_PP_INC(FLUSSPFERD_PARAM_LIMIT),\n FLUSSPFERD_FN_CREATE_NATIVE_OBJECT,\n ~\n)\n\n#else\n\n\/**\n * Create a new native object of type @p T.\n *\n * @param T The type of the object's class.\n * @param proto The prototype to be used. If @p null, the class' default\n * prototype will be used.\n * @param ... The parameters to the constructor of @p T.\n * @return The new object.\n *\/\ntemplate<typename T>\nT &create_native_object(object const &proto, ...);\n\n#endif\n\/\/@}\n\n\/**\n * @name Creating functions\n * @addtogroup create_function\n *\/\n\/\/@{\n\nfunction create_function(\n std::string const &name,\n unsigned n_args,\n std::vector<std::string> argnames,\n flusspferd::string const &body,\n std::string const &file,\n unsigned line);\n\n\/**\n * Create a new native function.\n *\n * @p ptr will be <code>delete<\/code>d by Flusspferd.\n *\n * @param ptr The native function object.\n * @return The new function.\n *\/\nfunction create_native_function(native_function_base *ptr);\n\n\/**\n * Create a new native function as method of an object.\n *\n * The new method of object @p o will have the name @c ptr->name().\n *\n * @param o The object to add the method to.\n * @param ptr The native function object.\n * @return The new method.\n *\/\nfunction create_native_function(object const &o, native_function_base *ptr);\n\n#ifndef IN_DOXYGEN\n\n#define FLUSSPFERD_FN_CREATE_NATIVE_FUNCTION(z, n_args, d) \\\n template< \\\n typename T \\\n BOOST_PP_ENUM_TRAILING_PARAMS(n_args, typename T) \\\n > \\\n object create_native_functor_function( \\\n object const &o \\\n BOOST_PP_ENUM_TRAILING_BINARY_PARAMS(n_args, T, const & param), \\\n typename boost::enable_if_c<!boost::is_function<T>::value>::type * = 0 \\\n ) { \\\n return create_native_function(o, new T(BOOST_PP_ENUM_PARAMS(n_args, param))); \\\n } \\\n \/* *\/\n\nBOOST_PP_REPEAT(\n BOOST_PP_INC(FLUSSPFERD_PARAM_LIMIT),\n FLUSSPFERD_FN_CREATE_NATIVE_FUNCTION,\n ~\n)\n\n#else\n\n\/**\n * Create a new native function of type @p F as method of an object.\n *\n * @p F must inherit from #native_function_base.\n *\n * The new method of object @p o will have the name @c ptr->name().\n *\n * @param F The functor type.\n * @param o The object to add the method to.\n * @param ... The parameters to pass to the constructor of @p F.\n * @return The new method.\n *\/\ntemplate<typename F>\nobject create_native_functor_function(object const &o, ...);\n\n#endif\n\n\/**\n * Create a new native method of an object.\n *\n * @param o The object to add the method to.\n * @param name The method name.\n * @param fn The functor to call.\n * @param arity The function arity.\n * @return The new function.\n *\/\ninline function create_native_function(\n object const &o,\n std::string const &name,\n boost::function<void (call_context &)> const &fn,\n unsigned arity = 0)\n{\n return create_native_functor_function<native_function<void> >(\n o, fn, arity, name);\n}\n\n\/**\n * Create a new native method of an object.\n *\n * @param T The function signature to use.\n * @param o The object to add the method to.\n * @param name The function name.\n * @param fn The functor to call.\n * @return The new function.\n *\/\ntemplate<typename T>\nfunction create_native_function(\n object const &o,\n std::string const &name,\n boost::function<T> const &fn)\n{\n return create_native_functor_function<native_function<T,false> >(o, fn, name);\n}\n\n\/**\n * Create a new native method of an object.\n *\n * The first parameter passed will be 'this'.\n *\n * @param T The function signature to use.\n * @param o The object to add the method to.\n * @param name The function name.\n * @param fn The functor to call.\n * @return The new function.\n *\/\ntemplate<typename T>\nfunction create_native_method(\n object const &o,\n std::string const &name,\n boost::function<T> const &fn)\n{\n return create_native_functor_function<native_function<T,true> >(o, fn, name);\n}\n\n\/**\n * Create a new native method of an object.\n *\n * @param o The object to add the method to.\n * @param name The method name.\n * @param fnptr The function to call (also determines the function signature).\n * @return The new method.\n *\/\ntemplate<typename T>\nfunction create_native_function(\n object const &o,\n std::string const &name,\n T *fnptr,\n typename boost::enable_if_c<boost::is_function<T>::value>::type* =0)\n{\n return create_native_function<T>(o, name, boost::function<T>(fnptr));\n}\n\n\/**\n * Create a new native method of an object.\n *\n * The first parameter passed will be 'this'.\n *\n * @param o The object to add the method to.\n * @param name The method name.\n * @param fnptr The function to call (also determines the function signature).\n * @return The new method.\n *\/\ntemplate<typename T>\nfunction create_native_method(\n object const &o,\n std::string const &name,\n T *fnptr,\n typename boost::enable_if_c<boost::is_function<T>::value>::type* =0)\n{\n return create_native_method<T>(o, name, boost::function<T>(fnptr));\n}\n\n\/**\n * Create a new native method of an object.\n *\n * @param o The object to add the method to.\n * @param name The method name.\n * @param memfnptr The member function to call.\n * @return The new function.\n *\/\ntemplate<typename T>\nfunction create_native_method(\n object const &o,\n std::string const &name,\n void (T::*memfnptr)(call_context &),\n unsigned arity = 0)\n{\n return create_native_functor_function<native_member_function<void, T> >(\n o, memfnptr, arity, name);\n}\n\n\/**\n * Create a new native method of an object.\n *\n * @param o The object to add the method to.\n * @param name The method name.\n * @param memfnptr The member function to call (also determines the function\n * signature).\n * @return The new function.\n *\/\ntemplate<typename R, typename T>\nfunction create_native_method(\n object const &o,\n std::string const &name,\n R T::*memfnptr)\n{\n return create_native_functor_function<native_member_function<R, T> >(\n o, memfnptr, name);\n}\n\n\/\/@}\n\nnamespace param {\n BOOST_PARAMETER_NAME(length)\n BOOST_PARAMETER_NAME(contents)\n}\n\nnamespace detail {\n flusspferd::array create_length_array(std::size_t length);\n\n template<typename Class>\n struct create_traits;\n\n template<typename T, typename C = void>\n struct is_boost_range_impl {\n typedef boost::mpl::false_ type;\n };\n\n template<>\n struct create_traits<flusspferd::array> {\n typedef flusspferd::array result_type;\n\n typedef boost::parameter::parameters<\n boost::parameter::optional<\n boost::parameter::deduced<param::tag::length>,\n boost::is_integral<boost::mpl::_>\n >,\n boost::parameter::optional<\n boost::parameter::deduced<param::tag::contents>,\n boost::mpl::not_<boost::is_integral<boost::mpl::_> >\n >\n >\n parameters;\n\n static flusspferd::array create() {\n return create_length_array(0);\n }\n\n template<typename ArgPack>\n static \n typename boost::enable_if<\n boost::is_same<\n typename boost::parameter::binding<\n ArgPack,\n param::tag::contents,\n void\n >::type,\n void\n >,\n flusspferd::array\n >::type\n create(ArgPack const &arg) {\n return create_length_array(arg[param::_length | 0]);\n }\n\n template<typename ArgPack>\n static\n typename boost::disable_if<\n boost::is_same<\n typename boost::parameter::binding<\n ArgPack,\n param::tag::contents,\n void\n >::type,\n void\n >,\n flusspferd::array\n >::type\n create(ArgPack const &arg) {\n typedef typename boost::parameter::value_type<\n ArgPack,\n param::tag::contents\n >::type\n Range;\n\n typedef typename boost::range_iterator<Range>::type iterator;\n\n Range const &r = arg[param::_contents];\n\n local_root_scope scope;\n\n array arr = create_length_array(0);\n\n iterator first = boost::begin(r);\n iterator last = boost::end(r);\n\n for (iterator it = first; it != last; ++it)\n arr.push(*it);\n\n return arr;\n }\n };\n\n}\n\ntemplate<typename Class>\ntypename detail::create_traits<Class>::result_type\ncreate()\n{\n typedef detail::create_traits<Class> traits;\n\n return traits::create();\n}\n\ntemplate<typename Class, typename T0>\ntypename detail::create_traits<Class>::result_type\ncreate(\n T0 const &x0,\n typename detail::create_traits<Class>::parameters::template match<T0>::type kw = typename detail::create_traits<Class>::parameters())\n{\n typedef detail::create_traits<Class> traits;\n\n return traits::create(kw(x0));\n}\n\n}\n\n#endif\n<commit_msg>new_create: allow multiple parameters (how fancy)<commit_after>\/\/ vim:ts=2:sw=2:expandtab:autoindent:filetype=cpp:\n\/*\nThe MIT License\n\nCopyright (c) 2008, 2009 Flusspferd contributors (see \"CONTRIBUTORS\" or\n http:\/\/flusspferd.org\/contributors.txt)\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n*\/\n\n#ifndef FLUSSPFERD_CREATE_HPP\n#define FLUSSPFERD_CREATE_HPP\n\n#ifndef PREPROC_DEBUG\n#include \"object.hpp\"\n#include \"function.hpp\"\n#include \"array.hpp\"\n#include \"native_function.hpp\"\n#include \"local_root_scope.hpp\"\n#include <boost\/type_traits\/is_function.hpp>\n#include <boost\/utility\/enable_if.hpp>\n#include <boost\/mpl\/bool.hpp>\n#include <boost\/range.hpp>\n#include <boost\/parameter\/parameters.hpp>\n#include <boost\/parameter\/keyword.hpp>\n#include <boost\/parameter\/name.hpp>\n#include <boost\/parameter\/binding.hpp>\n#endif\n#include \"detail\/limit.hpp\"\n#include <boost\/preprocessor.hpp>\n#include <boost\/parameter\/config.hpp>\n\nnamespace flusspferd {\n\nclass native_object_base;\nclass function;\nclass native_function_base;\n\n#ifndef IN_DOXYGEN\nnamespace detail {\n\nobject create_native_object(object const &proto);\nobject create_native_enumerable_object(object const &proto);\n\n}\n#endif\n\n\/**\n * @name Creating values\n * @addtogroup create\n *\/\n\/\/@{\n\/**\n * Create a simple object.\n *\n * Creates a new object with prototype @p proto. If proto is @c null,\n * @c Object.prototype will be used.\n *\n * @param proto The object to use as prototype.\n * @return The new object.\n *\/\nobject create_object(object const &proto = object());\n\n#ifndef IN_DOXYGEN\n\n#define FLUSSPFERD_FN_CREATE_NATIVE_OBJECT(z, n_args, d) \\\n template< \\\n typename T \\\n BOOST_PP_ENUM_TRAILING_PARAMS(n_args, typename T) \\\n > \\\n typename boost::enable_if< boost::mpl::not_< \\\n typename T::class_info::custom_enumerate >, \\\n T& >::type \\\n create_native_object( \\\n object proto \\\n BOOST_PP_ENUM_TRAILING_BINARY_PARAMS(n_args, T, const & param) \\\n ) { \\\n if (proto.is_null()) \\\n proto = current_context().prototype<T>(); \\\n local_root_scope scope; \\\n object obj = detail::create_native_object(proto); \\\n return *(new T(obj BOOST_PP_ENUM_TRAILING_PARAMS(n_args, param))); \\\n } \\\n \\\n template< \\\n typename T \\\n BOOST_PP_ENUM_TRAILING_PARAMS(n_args, typename T) \\\n > \\\n typename boost::enable_if< \\\n typename T::class_info::custom_enumerate, \\\n T& >::type \\\n create_native_object( \\\n object proto \\\n BOOST_PP_ENUM_TRAILING_BINARY_PARAMS(n_args, T, const & param) \\\n ) { \\\n if (proto.is_null()) \\\n proto = current_context().prototype<T>(); \\\n local_root_scope scope; \\\n object obj = detail::create_native_enumerable_object(proto); \\\n return *(new T(obj BOOST_PP_ENUM_TRAILING_PARAMS(n_args, param))); \\\n } \\\n \/* *\/\n\nBOOST_PP_REPEAT(\n BOOST_PP_INC(FLUSSPFERD_PARAM_LIMIT),\n FLUSSPFERD_FN_CREATE_NATIVE_OBJECT,\n ~\n)\n\n#else\n\n\/**\n * Create a new native object of type @p T.\n *\n * @param T The type of the object's class.\n * @param proto The prototype to be used. If @p null, the class' default\n * prototype will be used.\n * @param ... The parameters to the constructor of @p T.\n * @return The new object.\n *\/\ntemplate<typename T>\nT &create_native_object(object const &proto, ...);\n\n#endif\n\/\/@}\n\n\/**\n * @name Creating functions\n * @addtogroup create_function\n *\/\n\/\/@{\n\nfunction create_function(\n std::string const &name,\n unsigned n_args,\n std::vector<std::string> argnames,\n flusspferd::string const &body,\n std::string const &file,\n unsigned line);\n\n\/**\n * Create a new native function.\n *\n * @p ptr will be <code>delete<\/code>d by Flusspferd.\n *\n * @param ptr The native function object.\n * @return The new function.\n *\/\nfunction create_native_function(native_function_base *ptr);\n\n\/**\n * Create a new native function as method of an object.\n *\n * The new method of object @p o will have the name @c ptr->name().\n *\n * @param o The object to add the method to.\n * @param ptr The native function object.\n * @return The new method.\n *\/\nfunction create_native_function(object const &o, native_function_base *ptr);\n\n#ifndef IN_DOXYGEN\n\n#define FLUSSPFERD_FN_CREATE_NATIVE_FUNCTION(z, n_args, d) \\\n template< \\\n typename T \\\n BOOST_PP_ENUM_TRAILING_PARAMS(n_args, typename T) \\\n > \\\n object create_native_functor_function( \\\n object const &o \\\n BOOST_PP_ENUM_TRAILING_BINARY_PARAMS(n_args, T, const & param), \\\n typename boost::enable_if_c<!boost::is_function<T>::value>::type * = 0 \\\n ) { \\\n return create_native_function(o, new T(BOOST_PP_ENUM_PARAMS(n_args, param))); \\\n } \\\n \/* *\/\n\nBOOST_PP_REPEAT(\n BOOST_PP_INC(FLUSSPFERD_PARAM_LIMIT),\n FLUSSPFERD_FN_CREATE_NATIVE_FUNCTION,\n ~\n)\n\n#else\n\n\/**\n * Create a new native function of type @p F as method of an object.\n *\n * @p F must inherit from #native_function_base.\n *\n * The new method of object @p o will have the name @c ptr->name().\n *\n * @param F The functor type.\n * @param o The object to add the method to.\n * @param ... The parameters to pass to the constructor of @p F.\n * @return The new method.\n *\/\ntemplate<typename F>\nobject create_native_functor_function(object const &o, ...);\n\n#endif\n\n\/**\n * Create a new native method of an object.\n *\n * @param o The object to add the method to.\n * @param name The method name.\n * @param fn The functor to call.\n * @param arity The function arity.\n * @return The new function.\n *\/\ninline function create_native_function(\n object const &o,\n std::string const &name,\n boost::function<void (call_context &)> const &fn,\n unsigned arity = 0)\n{\n return create_native_functor_function<native_function<void> >(\n o, fn, arity, name);\n}\n\n\/**\n * Create a new native method of an object.\n *\n * @param T The function signature to use.\n * @param o The object to add the method to.\n * @param name The function name.\n * @param fn The functor to call.\n * @return The new function.\n *\/\ntemplate<typename T>\nfunction create_native_function(\n object const &o,\n std::string const &name,\n boost::function<T> const &fn)\n{\n return create_native_functor_function<native_function<T,false> >(o, fn, name);\n}\n\n\/**\n * Create a new native method of an object.\n *\n * The first parameter passed will be 'this'.\n *\n * @param T The function signature to use.\n * @param o The object to add the method to.\n * @param name The function name.\n * @param fn The functor to call.\n * @return The new function.\n *\/\ntemplate<typename T>\nfunction create_native_method(\n object const &o,\n std::string const &name,\n boost::function<T> const &fn)\n{\n return create_native_functor_function<native_function<T,true> >(o, fn, name);\n}\n\n\/**\n * Create a new native method of an object.\n *\n * @param o The object to add the method to.\n * @param name The method name.\n * @param fnptr The function to call (also determines the function signature).\n * @return The new method.\n *\/\ntemplate<typename T>\nfunction create_native_function(\n object const &o,\n std::string const &name,\n T *fnptr,\n typename boost::enable_if_c<boost::is_function<T>::value>::type* =0)\n{\n return create_native_function<T>(o, name, boost::function<T>(fnptr));\n}\n\n\/**\n * Create a new native method of an object.\n *\n * The first parameter passed will be 'this'.\n *\n * @param o The object to add the method to.\n * @param name The method name.\n * @param fnptr The function to call (also determines the function signature).\n * @return The new method.\n *\/\ntemplate<typename T>\nfunction create_native_method(\n object const &o,\n std::string const &name,\n T *fnptr,\n typename boost::enable_if_c<boost::is_function<T>::value>::type* =0)\n{\n return create_native_method<T>(o, name, boost::function<T>(fnptr));\n}\n\n\/**\n * Create a new native method of an object.\n *\n * @param o The object to add the method to.\n * @param name The method name.\n * @param memfnptr The member function to call.\n * @return The new function.\n *\/\ntemplate<typename T>\nfunction create_native_method(\n object const &o,\n std::string const &name,\n void (T::*memfnptr)(call_context &),\n unsigned arity = 0)\n{\n return create_native_functor_function<native_member_function<void, T> >(\n o, memfnptr, arity, name);\n}\n\n\/**\n * Create a new native method of an object.\n *\n * @param o The object to add the method to.\n * @param name The method name.\n * @param memfnptr The member function to call (also determines the function\n * signature).\n * @return The new function.\n *\/\ntemplate<typename R, typename T>\nfunction create_native_method(\n object const &o,\n std::string const &name,\n R T::*memfnptr)\n{\n return create_native_functor_function<native_member_function<R, T> >(\n o, memfnptr, name);\n}\n\n\/\/@}\n\nnamespace param {\n BOOST_PARAMETER_NAME(length)\n BOOST_PARAMETER_NAME(contents)\n}\n\nnamespace detail {\n flusspferd::array create_length_array(std::size_t length);\n\n template<typename Class>\n struct create_traits;\n\n template<typename T, typename C = void>\n struct is_boost_range_impl {\n typedef boost::mpl::false_ type;\n };\n\n template<>\n struct create_traits<flusspferd::array> {\n typedef flusspferd::array result_type;\n\n typedef boost::parameter::parameters<\n boost::parameter::optional<\n boost::parameter::deduced<param::tag::length>,\n boost::is_integral<boost::mpl::_>\n >,\n boost::parameter::optional<\n boost::parameter::deduced<param::tag::contents>,\n boost::mpl::not_<boost::is_integral<boost::mpl::_> >\n >\n >\n parameters;\n\n static flusspferd::array create() {\n return create_length_array(0);\n }\n\n template<typename ArgPack>\n static \n typename boost::enable_if<\n boost::is_same<\n typename boost::parameter::binding<\n ArgPack,\n param::tag::contents,\n void\n >::type,\n void\n >,\n flusspferd::array\n >::type\n create(ArgPack const &arg) {\n return create_length_array(arg[param::_length | 0]);\n }\n\n template<typename ArgPack>\n static\n typename boost::disable_if<\n boost::is_same<\n typename boost::parameter::binding<\n ArgPack,\n param::tag::contents,\n void\n >::type,\n void\n >,\n flusspferd::array\n >::type\n create(ArgPack const &arg) {\n typedef typename boost::parameter::value_type<\n ArgPack,\n param::tag::contents\n >::type\n Range;\n\n typedef typename boost::range_iterator<Range>::type iterator;\n\n Range const &r = arg[param::_contents];\n\n local_root_scope scope;\n\n array arr = create_length_array(0);\n\n iterator first = boost::begin(r);\n iterator last = boost::end(r);\n\n for (iterator it = first; it != last; ++it)\n arr.push(*it);\n\n return arr;\n }\n };\n\n}\n\ntemplate<typename Class>\ntypename detail::create_traits<Class>::result_type\ncreate()\n{\n return detail::create_traits<Class>::create();\n}\n\n#define FLUSSPFERD_CREATE(z, n, d) \\\n template< \\\n typename Class, \\\n BOOST_PP_ENUM_PARAMS(n, typename T) \\\n > \\\n typename detail::create_traits<Class>::result_type \\\n create( \\\n BOOST_PP_ENUM_BINARY_PARAMS(n, T, const &x), \\\n typename detail::create_traits<Class>::parameters::template match<T0>::type kw = typename detail::create_traits<Class>::parameters()) \\\n { \\\n typedef detail::create_traits<Class> traits; \\\n return traits::create(kw(BOOST_PP_ENUM_PARAMS(n, x))); \\\n } \\\n \/* *\/\n\nBOOST_PP_REPEAT_FROM_TO(\n 1,\n BOOST_PP_INC(BOOST_PARAMETER_MAX_ARITY),\n FLUSSPFERD_CREATE,\n ~)\n\n#undef FLUSSPFERD_CREATE\n\n}\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>#pragma once\r\n\r\n#include <cassert>\r\n#include <algorithm>\r\n#include <fstream>\r\n\r\n#include <glow\/logging.h>\r\n\r\n#include <glowutils\/RawFile.h>\r\n\r\nnamespace glowutils \r\n{\r\n\r\ntemplate<typename T>\r\nRawFile<T>::RawFile(const std::string & filePath)\r\n: m_filePath(filePath)\r\n, m_valid(false)\r\n{\r\n read();\r\n}\r\n\r\ntemplate<typename T>\r\nRawFile<T>::~RawFile()\r\n{\r\n}\r\n\r\ntemplate<typename T>\r\nbool RawFile<T>::valid() const\r\n{\r\n return m_valid;\r\n}\r\n\r\ntemplate<typename T>\r\nconst T * RawFile<T>::data() const\r\n{\r\n return &m_data.data()[0];\r\n}\r\n\r\ntemplate<typename T>\r\nconst size_t RawFile<T>::size() const\r\n{\r\n return m_data.size();\r\n}\r\n\r\ntemplate<typename T>\r\nbool RawFile<T>::read()\r\n{\r\n std::ifstream ifs(m_filePath, std::ios::in | std::ios::binary | std::ios::ate);\r\n\r\n if (!ifs)\r\n {\r\n warning() << \"Reading from file \\\"\" << m_filePath << \"\\\" failed.\";\r\n return false;\r\n }\r\n\r\n const size_t size = ifs.tellg();\r\n ifs.seekg(0, std::ios::beg);\r\n\r\n m_data.resize(size \/ sizeof(T));\r\n\r\n ifs.read(reinterpret_cast<char*>(&m_data[0]), size);\r\n ifs.close();\r\n\r\n m_valid = true;\r\n return true;\r\n}\r\n\r\n} \/\/ namespace glowutils\r\n<commit_msg>Fix namespace error in RawFile<commit_after>#pragma once\r\n\r\n#include <cassert>\r\n#include <algorithm>\r\n#include <fstream>\r\n\r\n#include <glow\/logging.h>\r\n\r\n#include <glowutils\/RawFile.h>\r\n\r\nnamespace glowutils \r\n{\r\n\r\ntemplate<typename T>\r\nRawFile<T>::RawFile(const std::string & filePath)\r\n: m_filePath(filePath)\r\n, m_valid(false)\r\n{\r\n read();\r\n}\r\n\r\ntemplate<typename T>\r\nRawFile<T>::~RawFile()\r\n{\r\n}\r\n\r\ntemplate<typename T>\r\nbool RawFile<T>::valid() const\r\n{\r\n return m_valid;\r\n}\r\n\r\ntemplate<typename T>\r\nconst T * RawFile<T>::data() const\r\n{\r\n return &m_data.data()[0];\r\n}\r\n\r\ntemplate<typename T>\r\nconst size_t RawFile<T>::size() const\r\n{\r\n return m_data.size();\r\n}\r\n\r\ntemplate<typename T>\r\nbool RawFile<T>::read()\r\n{\r\n std::ifstream ifs(m_filePath, std::ios::in | std::ios::binary | std::ios::ate);\r\n\r\n if (!ifs)\r\n {\r\n glow::warning() << \"Reading from file \\\"\" << m_filePath << \"\\\" failed.\";\r\n return false;\r\n }\r\n\r\n const size_t size = ifs.tellg();\r\n ifs.seekg(0, std::ios::beg);\r\n\r\n m_data.resize(size \/ sizeof(T));\r\n\r\n ifs.read(reinterpret_cast<char*>(&m_data[0]), size);\r\n ifs.close();\r\n\r\n m_valid = true;\r\n return true;\r\n}\r\n\r\n} \/\/ namespace glowutils\r\n<|endoftext|>"} {"text":"<commit_before>\/*\n\nCopyright (c) 2007, Arvid Norberg\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in\n the documentation and\/or other materials provided with the distribution.\n * Neither the name of the author nor the names of its\n contributors may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#ifndef TORRENT_ASSERT\n\n#include \"libtorrent\/config.hpp\"\n#include <string>\n\n#ifdef __GNUC__\nstd::string demangle(char const* name);\n#endif\n\n#if (defined __linux__ || defined __MACH__) && defined __GNUC__ && !defined(NDEBUG)\n\nTORRENT_EXPORT void assert_fail(const char* expr, int line, char const* file, char const* function);\n#define TORRENT_ASSERT(x) if (x) {} else assert_fail(#x, __LINE__, __FILE__, __PRETTY_FUNCTION__)\n\n#else\n#include <cassert>\n#define TORRENT_ASSERT(x) assert(x)\n#endif\n\n#endif\n\n<commit_msg>fixed warning on gcc 4.3<commit_after>\/*\n\nCopyright (c) 2007, Arvid Norberg\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in\n the documentation and\/or other materials provided with the distribution.\n * Neither the name of the author nor the names of its\n contributors may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#ifndef TORRENT_ASSERT\n\n#include \"libtorrent\/config.hpp\"\n#include <string>\n\n#ifdef __GNUC__\nstd::string demangle(char const* name);\n#endif\n\n#if (defined __linux__ || defined __MACH__) && defined __GNUC__ && !defined(NDEBUG)\n\nTORRENT_EXPORT void assert_fail(const char* expr, int line, char const* file, char const* function);\n#define TORRENT_ASSERT(x) do { if (x) {} else assert_fail(#x, __LINE__, __FILE__, __PRETTY_FUNCTION__); } while (false)\n\n#else\n#include <cassert>\n#define TORRENT_ASSERT(x) assert(x)\n#endif\n\n#endif\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n\nCopyright (c) 2005, Arvid Norberg\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in\n the documentation and\/or other materials provided with the distribution.\n * Neither the name of the author nor the names of its\n contributors may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#ifndef TORRENT_CONFIG_HPP_INCLUDED\n#define TORRENT_CONFIG_HPP_INCLUDED\n\n#include <boost\/config.hpp>\n#include <boost\/version.hpp>\n#include <stdio.h> \/\/ for snprintf\n\n#ifndef WIN32\n#define __STDC_FORMAT_MACROS\n#include <inttypes.h>\n#endif\n\n#ifndef PRId64\n#ifdef _WIN32\n#define PRId64 \"I64d\"\n#else\n#define PRId64 \"lld\"\n#endif\n#endif\n\n\n\/\/ ======= GCC =========\n\n#if defined __GNUC__\n\n# define TORRENT_DEPRECATED __attribute__ ((deprecated))\n\n\/\/ GCC pre 4.0 did not have support for the visibility attribute\n# if __GNUC__ >= 4\n# if defined(TORRENT_BUILDING_SHARED) || defined(TORRENT_LINKING_SHARED)\n# define TORRENT_EXPORT __attribute__ ((visibility(\"default\")))\n# else\n# define TORRENT_EXPORT\n# endif\n# else\n# define TORRENT_EXPORT\n# endif\n\n\n\/\/ ======= SUNPRO =========\n\n#elif defined __SUNPRO_CC\n\n# if __SUNPRO_CC >= 0x550\n# if defined(TORRENT_BUILDING_SHARED) || defined(TORRENT_LINKING_SHARED)\n# define TORRENT_EXPORT __global\n# else\n# define TORRENT_EXPORT\n# endif\n# else\n# define TORRENT_EXPORT\n# endif\n\n\n\/\/ ======= MSVC =========\n\n#elif defined BOOST_MSVC\n\n#pragma warning(disable: 4258)\n#pragma warning(disable: 4251)\n\n# if defined(TORRENT_BUILDING_SHARED)\n# define TORRENT_EXPORT __declspec(dllexport)\n# elif defined(TORRENT_LINKING_SHARED)\n# define TORRENT_EXPORT __declspec(dllimport)\n# else\n# define TORRENT_EXPORT\n# endif\n\n#define TORRENT_DEPRECATED_PREFIX __declspec(deprecated)\n\n\n\n\/\/ ======= GENERIC COMPILER =========\n\n#else\n# define TORRENT_EXPORT\n#endif\n\n\n\n#ifndef TORRENT_DEPRECATED_PREFIX\n#define TORRENT_DEPRECATED_PREFIX\n#endif\n\n#ifndef TORRENT_DEPRECATED\n#define TORRENT_DEPRECATED\n#endif\n\n\/\/ set up defines for target environments\n#if (defined __APPLE__ && __MACH__) || defined __FreeBSD__ || defined __NetBSD__ \\\n\t|| defined __OpenBSD__ || defined __bsdi__ || defined __DragonFly__ \\\n\t|| defined __FreeBSD_kernel__\n#define TORRENT_BSD\n#elif defined __linux__\n#define TORRENT_LINUX\n#elif defined __MINGW32__\n#define TORRENT_MINGW\n#elif defined WIN32\n#define TORRENT_WINDOWS\n#elif defined sun || defined __sun \n#define TORRENT_SOLARIS\n#else\n#warning unkown OS, assuming BSD\n#define TORRENT_BSD\n#endif\n\n#define TORRENT_USE_IPV6 1\n#define TORRENT_USE_MLOCK 1\n#define TORRENT_USE_READV 1\n#define TORRENT_USE_WRITEV 1\n#define TORRENT_USE_IOSTREAM 1\n\n#define TORRENT_USE_I2P 1\n\n\/\/ should wpath or path be used?\n#if defined UNICODE && !defined BOOST_FILESYSTEM_NARROW_ONLY \\\n\t&& BOOST_VERSION >= 103400 && !defined __APPLE__\n#define TORRENT_USE_WPATH 1\n#else\n#define TORRENT_USE_WPATH 0\n#endif\n\n\/\/ set this to 1 to disable all floating point operations\n\/\/ (disables some float-dependent APIs)\n#define TORRENT_NO_FPU 0\n\n\n\/\/ on windows, NAME_MAX refers to Unicode characters\n\/\/ on linux it refers to bytes (utf-8 encoded)\n\/\/ TODO: Make this count Unicode characters instead of bytes on windows\n\n\/\/ windows\n#if defined FILENAME_MAX\n#define TORRENT_MAX_PATH FILENAME_MAX\n\n\/\/ solaris\n#elif defined MAXPATH\n#define TORRENT_MAX_PATH MAXPATH\n\n\/\/ posix\n#elif defined NAME_MAX\n#define TORRENT_MAX_PATH NAME_MAX\n\n\/\/ none of the above\n#else\n\/\/ this is the maximum number of characters in a\n\/\/ path element \/ filename on windows\n#define TORRENT_MAX_PATH 255\n#warning unknown platform, assuming the longest path is 255\n\n#endif\n\n#ifdef TORRENT_WINDOWS\n\n\/\/ class X needs to have dll-interface to be used by clients of class Y\n#pragma warning(disable:4251)\n\n#include <stdarg.h>\n\ninline int snprintf(char* buf, int len, char const* fmt, ...)\n{\n\tva_list lp;\n\tva_start(lp, fmt);\n\tint ret = _vsnprintf(buf, len, fmt, lp);\n\tva_end(lp);\n\tif (ret < 0) { buf[len-1] = 0; ret = len-1; }\n\treturn ret;\n}\n\n#define strtoll _strtoi64\n#else\n#include <limits.h>\n#endif\n\n#if (defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)) && !defined (TORRENT_UPNP_LOGGING)\n#define TORRENT_UPNP_LOGGING\n#endif\n\n#if !TORRENT_USE_WPATH && defined TORRENT_LINUX\n\/\/ libiconv presnce, not implemented yet\n#define TORRENT_USE_LOCALE_FILENAMES 1\n#else\n#define TORRENT_USE_LOCALE_FILENAMES 0\n#endif\n\n#if !defined(TORRENT_READ_HANDLER_MAX_SIZE)\n# define TORRENT_READ_HANDLER_MAX_SIZE 256\n#endif\n\n#if !defined(TORRENT_WRITE_HANDLER_MAX_SIZE)\n# define TORRENT_WRITE_HANDLER_MAX_SIZE 256\n#endif\n\n#if defined _MSC_VER && _MSC_VER <= 1200\n#define for if (false) {} else for\n#endif\n\n\/\/ determine what timer implementation we can use\n\n#if defined(__MACH__)\n#define TORRENT_USE_ABSOLUTE_TIME 1\n#elif defined(_WIN32)\n#define TORRENT_USE_QUERY_PERFORMANCE_TIMER 1\n#elif defined(_POSIX_MONOTONIC_CLOCK) && _POSIX_MONOTONIC_CLOCK >= 0\n#define TORRENT_USE_CLOCK_GETTIME 1\n#else\n#define TORRENT_USE_BOOST_DATE_TIME 1\n#endif\n\n#endif \/\/ TORRENT_CONFIG_HPP_INCLUDED\n\n<commit_msg>fix some error\/warning strings typos<commit_after>\/*\n\nCopyright (c) 2005, Arvid Norberg\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in\n the documentation and\/or other materials provided with the distribution.\n * Neither the name of the author nor the names of its\n contributors may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#ifndef TORRENT_CONFIG_HPP_INCLUDED\n#define TORRENT_CONFIG_HPP_INCLUDED\n\n#include <boost\/config.hpp>\n#include <boost\/version.hpp>\n#include <stdio.h> \/\/ for snprintf\n\n#ifndef WIN32\n#define __STDC_FORMAT_MACROS\n#include <inttypes.h>\n#endif\n\n#ifndef PRId64\n#ifdef _WIN32\n#define PRId64 \"I64d\"\n#else\n#define PRId64 \"lld\"\n#endif\n#endif\n\n\n\/\/ ======= GCC =========\n\n#if defined __GNUC__\n\n# define TORRENT_DEPRECATED __attribute__ ((deprecated))\n\n\/\/ GCC pre 4.0 did not have support for the visibility attribute\n# if __GNUC__ >= 4\n# if defined(TORRENT_BUILDING_SHARED) || defined(TORRENT_LINKING_SHARED)\n# define TORRENT_EXPORT __attribute__ ((visibility(\"default\")))\n# else\n# define TORRENT_EXPORT\n# endif\n# else\n# define TORRENT_EXPORT\n# endif\n\n\n\/\/ ======= SUNPRO =========\n\n#elif defined __SUNPRO_CC\n\n# if __SUNPRO_CC >= 0x550\n# if defined(TORRENT_BUILDING_SHARED) || defined(TORRENT_LINKING_SHARED)\n# define TORRENT_EXPORT __global\n# else\n# define TORRENT_EXPORT\n# endif\n# else\n# define TORRENT_EXPORT\n# endif\n\n\n\/\/ ======= MSVC =========\n\n#elif defined BOOST_MSVC\n\n#pragma warning(disable: 4258)\n#pragma warning(disable: 4251)\n\n# if defined(TORRENT_BUILDING_SHARED)\n# define TORRENT_EXPORT __declspec(dllexport)\n# elif defined(TORRENT_LINKING_SHARED)\n# define TORRENT_EXPORT __declspec(dllimport)\n# else\n# define TORRENT_EXPORT\n# endif\n\n#define TORRENT_DEPRECATED_PREFIX __declspec(deprecated)\n\n\n\n\/\/ ======= GENERIC COMPILER =========\n\n#else\n# define TORRENT_EXPORT\n#endif\n\n\n\n#ifndef TORRENT_DEPRECATED_PREFIX\n#define TORRENT_DEPRECATED_PREFIX\n#endif\n\n#ifndef TORRENT_DEPRECATED\n#define TORRENT_DEPRECATED\n#endif\n\n\/\/ set up defines for target environments\n#if (defined __APPLE__ && __MACH__) || defined __FreeBSD__ || defined __NetBSD__ \\\n\t|| defined __OpenBSD__ || defined __bsdi__ || defined __DragonFly__ \\\n\t|| defined __FreeBSD_kernel__\n#define TORRENT_BSD\n#elif defined __linux__\n#define TORRENT_LINUX\n#elif defined __MINGW32__\n#define TORRENT_MINGW\n#elif defined WIN32\n#define TORRENT_WINDOWS\n#elif defined sun || defined __sun \n#define TORRENT_SOLARIS\n#else\n#warning unknown OS, assuming BSD\n#define TORRENT_BSD\n#endif\n\n#define TORRENT_USE_IPV6 1\n#define TORRENT_USE_MLOCK 1\n#define TORRENT_USE_READV 1\n#define TORRENT_USE_WRITEV 1\n#define TORRENT_USE_IOSTREAM 1\n\n#define TORRENT_USE_I2P 1\n\n\/\/ should wpath or path be used?\n#if defined UNICODE && !defined BOOST_FILESYSTEM_NARROW_ONLY \\\n\t&& BOOST_VERSION >= 103400 && !defined __APPLE__\n#define TORRENT_USE_WPATH 1\n#else\n#define TORRENT_USE_WPATH 0\n#endif\n\n\/\/ set this to 1 to disable all floating point operations\n\/\/ (disables some float-dependent APIs)\n#define TORRENT_NO_FPU 0\n\n\n\/\/ on windows, NAME_MAX refers to Unicode characters\n\/\/ on linux it refers to bytes (utf-8 encoded)\n\/\/ TODO: Make this count Unicode characters instead of bytes on windows\n\n\/\/ windows\n#if defined FILENAME_MAX\n#define TORRENT_MAX_PATH FILENAME_MAX\n\n\/\/ solaris\n#elif defined MAXPATH\n#define TORRENT_MAX_PATH MAXPATH\n\n\/\/ posix\n#elif defined NAME_MAX\n#define TORRENT_MAX_PATH NAME_MAX\n\n\/\/ none of the above\n#else\n\/\/ this is the maximum number of characters in a\n\/\/ path element \/ filename on windows\n#define TORRENT_MAX_PATH 255\n#warning unknown platform, assuming the longest path is 255\n\n#endif\n\n#ifdef TORRENT_WINDOWS\n\n\/\/ class X needs to have dll-interface to be used by clients of class Y\n#pragma warning(disable:4251)\n\n#include <stdarg.h>\n\ninline int snprintf(char* buf, int len, char const* fmt, ...)\n{\n\tva_list lp;\n\tva_start(lp, fmt);\n\tint ret = _vsnprintf(buf, len, fmt, lp);\n\tva_end(lp);\n\tif (ret < 0) { buf[len-1] = 0; ret = len-1; }\n\treturn ret;\n}\n\n#define strtoll _strtoi64\n#else\n#include <limits.h>\n#endif\n\n#if (defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)) && !defined (TORRENT_UPNP_LOGGING)\n#define TORRENT_UPNP_LOGGING\n#endif\n\n#if !TORRENT_USE_WPATH && defined TORRENT_LINUX\n\/\/ libiconv presnce, not implemented yet\n#define TORRENT_USE_LOCALE_FILENAMES 1\n#else\n#define TORRENT_USE_LOCALE_FILENAMES 0\n#endif\n\n#if !defined(TORRENT_READ_HANDLER_MAX_SIZE)\n# define TORRENT_READ_HANDLER_MAX_SIZE 256\n#endif\n\n#if !defined(TORRENT_WRITE_HANDLER_MAX_SIZE)\n# define TORRENT_WRITE_HANDLER_MAX_SIZE 256\n#endif\n\n#if defined _MSC_VER && _MSC_VER <= 1200\n#define for if (false) {} else for\n#endif\n\n\/\/ determine what timer implementation we can use\n\n#if defined(__MACH__)\n#define TORRENT_USE_ABSOLUTE_TIME 1\n#elif defined(_WIN32)\n#define TORRENT_USE_QUERY_PERFORMANCE_TIMER 1\n#elif defined(_POSIX_MONOTONIC_CLOCK) && _POSIX_MONOTONIC_CLOCK >= 0\n#define TORRENT_USE_CLOCK_GETTIME 1\n#else\n#define TORRENT_USE_BOOST_DATE_TIME 1\n#endif\n\n#endif \/\/ TORRENT_CONFIG_HPP_INCLUDED\n\n<|endoftext|>"} {"text":"<commit_before>#pragma once\n\n#include <cstring>\n#include <cstdio>\n#include <cstdlib>\n#include <vector>\n#include <atomic>\n#include <memory>\n#include <mutex>\n\n#define FMT_STRING_ALIAS 1\n#define FMT_ENFORCE_COMPILE_STRING 1\n#define FMT_USE_GRISU 0\n#include <fmt\/format.h>\n\n#ifdef __SWITCH__\n#include \"nxstl\/mutex\"\n#endif\n\nextern \"C\" void logvisorBp();\n\nnamespace logvisor {\n\nvoid logvisorAbort();\n\n#if _WIN32 && UNICODE\n#define LOG_UCS2 1\n#endif\n\n\/* True if ANSI color available *\/\nextern bool XtermColor;\n\n\/**\n * @brief Severity level for log messages\n *\/\nenum Level {\n Info, \/**< Non-error informative message *\/\n Warning, \/**< Non-error warning message *\/\n Error, \/**< Recoverable error message *\/\n Fatal \/**< Non-recoverable error message (throws exception) *\/\n};\n\n\/**\n * @brief Backend interface for receiving app-wide log events\n *\/\nstruct ILogger {\n virtual ~ILogger() = default;\n virtual void report(const char* modName, Level severity, fmt::string_view format, fmt::format_args args) = 0;\n virtual void report(const char* modName, Level severity, fmt::wstring_view format, fmt::wformat_args args) = 0;\n virtual void reportSource(const char* modName, Level severity, const char* file, unsigned linenum,\n fmt::string_view format, fmt::format_args args) = 0;\n virtual void reportSource(const char* modName, Level severity, const char* file, unsigned linenum,\n fmt::wstring_view format, fmt::wformat_args args) = 0;\n};\n\n\/**\n * @brief Terminate all child processes\n *\n * Implicitly called on abort condition.\n *\/\nvoid KillProcessTree();\n\n\/**\n * @brief Assign calling thread a descriptive name\n * @param name Descriptive thread name\n *\/\nvoid RegisterThreadName(const char* name);\n\n\/**\n * @brief Centralized logger vector\n *\n * All loggers added to this vector will receive reports as they occur\n *\/\nextern std::vector<std::unique_ptr<ILogger>> MainLoggers;\n\n\/**\n * @brief Centralized error counter\n *\n * All submodules accumulate this value\n *\/\nextern std::atomic_size_t ErrorCount;\n\n\/**\n * @brief Centralized frame index\n *\n * All log events include this as part of their timestamp if non-zero.\n * The default value is zero, the app is responsible for updating it\n * within its main loop.\n *\/\nextern std::atomic_uint_fast64_t FrameIndex;\n\n\/**\n * @brief Centralized logging lock\n *\n * Ensures logging streams aren't written concurrently\n *\/\nstruct LogMutex {\n bool enabled = true;\n std::recursive_mutex mutex;\n ~LogMutex() { enabled = false; }\n std::unique_lock<std::recursive_mutex> lock() {\n if (enabled)\n return std::unique_lock<std::recursive_mutex>(mutex);\n else\n return std::unique_lock<std::recursive_mutex>();\n }\n};\nextern LogMutex _LogMutex;\n\n\/**\n * @brief Take a centralized lock for the logging output stream(s)\n * @return RAII mutex lock\n *\/\ninline std::unique_lock<std::recursive_mutex> LockLog() { return _LogMutex.lock(); }\n\nextern uint64_t _LogCounter;\n\n\/**\n * @brief Get current count of logging events\n * @return Log Count\n *\/\ninline uint64_t GetLogCounter() { return _LogCounter; }\n\n\/**\n * @brief Restore centralized logger vector to default state (silent operation)\n *\/\ninline void UnregisterLoggers() { MainLoggers.clear(); }\n\n\/**\n * @brief Construct and register a real-time console logger singleton\n *\n * This will output to stderr on POSIX platforms and spawn a new console window on Windows.\n * If there's already a registered console logger, this is a no-op.\n *\/\nvoid RegisterConsoleLogger();\n\n\/**\n * @brief Construct and register a file logger\n * @param filepath Path to write the file\n *\n * If there's already a file logger registered to the same file, this is a no-op.\n *\/\nvoid RegisterFileLogger(const char* filepath);\n\n\/**\n * @brief Register signal handlers with system for common client exceptions\n *\/\nvoid RegisterStandardExceptions();\n\n#if _WIN32\n\/**\n * @brief Spawn an application-owned cmd.exe window for displaying console output\n *\/\nvoid CreateWin32Console();\n#endif\n\n#if LOG_UCS2\n\n\/**\n * @brief Construct and register a file logger (wchar_t version)\n * @param filepath Path to write the file\n *\n * If there's already a file logger registered to the same file, this is a no-op.\n *\/\nvoid RegisterFileLogger(const wchar_t* filepath);\n\n#endif\n\n\/**\n * @brief This is constructed per-subsystem in a locally centralized fashon\n *\/\nclass Module {\n const char* m_modName;\n\n template <typename Char>\n void _vreport(Level severity, fmt::basic_string_view<Char> format,\n fmt::basic_format_args<fmt::buffer_context<Char>> args) {\n auto lk = LockLog();\n ++_LogCounter;\n if (severity == Fatal)\n RegisterConsoleLogger();\n for (auto& logger : MainLoggers)\n logger->report(m_modName, severity, format, args);\n if (severity == Error || severity == Fatal)\n logvisorBp();\n if (severity == Fatal)\n logvisorAbort();\n else if (severity == Error)\n ++ErrorCount;\n }\n\n template <typename Char>\n void _vreportSource(Level severity, const char* file, unsigned linenum, fmt::basic_string_view<Char> format,\n fmt::basic_format_args<fmt::buffer_context<Char>> args) {\n auto lk = LockLog();\n ++_LogCounter;\n if (severity == Fatal)\n RegisterConsoleLogger();\n for (auto& logger : MainLoggers)\n logger->reportSource(m_modName, severity, file, linenum, format, args);\n if (severity == Error || severity == Fatal)\n logvisorBp();\n if (severity == Fatal)\n logvisorAbort();\n else if (severity == Error)\n ++ErrorCount;\n }\n\npublic:\n constexpr Module(const char* modName) : m_modName(modName) {}\n\n \/**\n * @brief Route new log message to centralized ILogger\n * @param severity Level of log report severity\n * @param format Standard printf-style format string\n *\/\n template <typename S, typename... Args, typename Char = fmt::char_t<S>>\n void report(Level severity, const S& format, Args&&... args) {\n if (MainLoggers.empty() && severity != Level::Fatal)\n return;\n _vreport(severity, fmt::to_string_view<Char>(format),\n fmt::basic_format_args<fmt::buffer_context<Char>>(\n fmt::internal::make_args_checked<Args...>(format, args...)));\n }\n\n template <typename Char>\n void vreport(Level severity, fmt::basic_string_view<Char> format,\n fmt::basic_format_args<fmt::buffer_context<Char>> args) {\n if (MainLoggers.empty() && severity != Level::Fatal)\n return;\n _vreport(severity, format, args);\n }\n\n \/**\n * @brief Route new log message with source info to centralized ILogger\n * @param severity Level of log report severity\n * @param file Source file name from __FILE__ macro\n * @param linenum Source line number from __LINE__ macro\n * @param format Standard printf-style format string\n *\/\n template <typename S, typename... Args, typename Char = fmt::char_t<S>>\n void reportSource(Level severity, const char* file, unsigned linenum, const S& format, Args&&... args) {\n if (MainLoggers.empty() && severity != Level::Fatal)\n return;\n _vreportSource(\n severity, file, linenum, fmt::to_string_view<Char>(format),\n fmt::basic_format_args<fmt::buffer_context<Char>>(\n fmt::internal::make_args_checked<Args...>(format, args...)));\n }\n\n template <typename Char>\n void vreportSource(Level severity, const char* file, unsigned linenum, fmt::basic_string_view<Char> format,\n fmt::basic_format_args<fmt::buffer_context<Char>> args) {\n if (MainLoggers.empty() && severity != Level::Fatal)\n return;\n _vreportSource(severity, file, linenum, format, args);\n }\n};\n\n#define FMT_CUSTOM_FORMATTER(tp, fmtstr, ...) \\\nnamespace fmt { \\\ntemplate <> \\\nstruct formatter<tp, char> { \\\n template <typename ParseContext> \\\n constexpr auto parse(ParseContext &ctx) { return ctx.begin(); } \\\n template <typename FormatContext> \\\n auto format(const tp &obj, FormatContext &ctx) { \\\n return format_to(ctx.out(), fmt(fmtstr), __VA_ARGS__); \\\n } \\\n}; \\\ntemplate <> \\\nstruct formatter<tp, wchar_t> { \\\n template <typename ParseContext> \\\n constexpr auto parse(ParseContext &ctx) { return ctx.begin(); } \\\n template <typename FormatContext> \\\n auto format(const tp &obj, FormatContext &ctx) { \\\n return format_to(ctx.out(), fmt(L##fmtstr), __VA_ARGS__); \\\n } \\\n}; \\\ntemplate <> \\\nstruct formatter<tp, char16_t> { \\\n template <typename ParseContext> \\\n constexpr auto parse(ParseContext &ctx) { return ctx.begin(); } \\\n template <typename FormatContext> \\\n auto format(const tp &obj, FormatContext &ctx) { \\\n return format_to(ctx.out(), fmt(u##fmtstr), __VA_ARGS__); \\\n } \\\n}; \\\ntemplate <> \\\nstruct formatter<tp, char32_t> { \\\n template <typename ParseContext> \\\n constexpr auto parse(ParseContext &ctx) { return ctx.begin(); } \\\n template <typename FormatContext> \\\n auto format(const tp &obj, FormatContext &ctx) { \\\n return format_to(ctx.out(), fmt(U##fmtstr), __VA_ARGS__); \\\n } \\\n}; \\\n}\n\n} \/\/ namespace logvisor\n<commit_msg>logvisor: std::forward arguments where applicable<commit_after>#pragma once\n\n#include <cstring>\n#include <cstdio>\n#include <cstdlib>\n#include <vector>\n#include <atomic>\n#include <memory>\n#include <mutex>\n\n#define FMT_STRING_ALIAS 1\n#define FMT_ENFORCE_COMPILE_STRING 1\n#define FMT_USE_GRISU 0\n#include <fmt\/format.h>\n\n#ifdef __SWITCH__\n#include \"nxstl\/mutex\"\n#endif\n\nextern \"C\" void logvisorBp();\n\nnamespace logvisor {\n\nvoid logvisorAbort();\n\n#if _WIN32 && UNICODE\n#define LOG_UCS2 1\n#endif\n\n\/* True if ANSI color available *\/\nextern bool XtermColor;\n\n\/**\n * @brief Severity level for log messages\n *\/\nenum Level {\n Info, \/**< Non-error informative message *\/\n Warning, \/**< Non-error warning message *\/\n Error, \/**< Recoverable error message *\/\n Fatal \/**< Non-recoverable error message (throws exception) *\/\n};\n\n\/**\n * @brief Backend interface for receiving app-wide log events\n *\/\nstruct ILogger {\n virtual ~ILogger() = default;\n virtual void report(const char* modName, Level severity, fmt::string_view format, fmt::format_args args) = 0;\n virtual void report(const char* modName, Level severity, fmt::wstring_view format, fmt::wformat_args args) = 0;\n virtual void reportSource(const char* modName, Level severity, const char* file, unsigned linenum,\n fmt::string_view format, fmt::format_args args) = 0;\n virtual void reportSource(const char* modName, Level severity, const char* file, unsigned linenum,\n fmt::wstring_view format, fmt::wformat_args args) = 0;\n};\n\n\/**\n * @brief Terminate all child processes\n *\n * Implicitly called on abort condition.\n *\/\nvoid KillProcessTree();\n\n\/**\n * @brief Assign calling thread a descriptive name\n * @param name Descriptive thread name\n *\/\nvoid RegisterThreadName(const char* name);\n\n\/**\n * @brief Centralized logger vector\n *\n * All loggers added to this vector will receive reports as they occur\n *\/\nextern std::vector<std::unique_ptr<ILogger>> MainLoggers;\n\n\/**\n * @brief Centralized error counter\n *\n * All submodules accumulate this value\n *\/\nextern std::atomic_size_t ErrorCount;\n\n\/**\n * @brief Centralized frame index\n *\n * All log events include this as part of their timestamp if non-zero.\n * The default value is zero, the app is responsible for updating it\n * within its main loop.\n *\/\nextern std::atomic_uint_fast64_t FrameIndex;\n\n\/**\n * @brief Centralized logging lock\n *\n * Ensures logging streams aren't written concurrently\n *\/\nstruct LogMutex {\n bool enabled = true;\n std::recursive_mutex mutex;\n ~LogMutex() { enabled = false; }\n std::unique_lock<std::recursive_mutex> lock() {\n if (enabled)\n return std::unique_lock<std::recursive_mutex>(mutex);\n else\n return std::unique_lock<std::recursive_mutex>();\n }\n};\nextern LogMutex _LogMutex;\n\n\/**\n * @brief Take a centralized lock for the logging output stream(s)\n * @return RAII mutex lock\n *\/\ninline std::unique_lock<std::recursive_mutex> LockLog() { return _LogMutex.lock(); }\n\nextern uint64_t _LogCounter;\n\n\/**\n * @brief Get current count of logging events\n * @return Log Count\n *\/\ninline uint64_t GetLogCounter() { return _LogCounter; }\n\n\/**\n * @brief Restore centralized logger vector to default state (silent operation)\n *\/\ninline void UnregisterLoggers() { MainLoggers.clear(); }\n\n\/**\n * @brief Construct and register a real-time console logger singleton\n *\n * This will output to stderr on POSIX platforms and spawn a new console window on Windows.\n * If there's already a registered console logger, this is a no-op.\n *\/\nvoid RegisterConsoleLogger();\n\n\/**\n * @brief Construct and register a file logger\n * @param filepath Path to write the file\n *\n * If there's already a file logger registered to the same file, this is a no-op.\n *\/\nvoid RegisterFileLogger(const char* filepath);\n\n\/**\n * @brief Register signal handlers with system for common client exceptions\n *\/\nvoid RegisterStandardExceptions();\n\n#if _WIN32\n\/**\n * @brief Spawn an application-owned cmd.exe window for displaying console output\n *\/\nvoid CreateWin32Console();\n#endif\n\n#if LOG_UCS2\n\n\/**\n * @brief Construct and register a file logger (wchar_t version)\n * @param filepath Path to write the file\n *\n * If there's already a file logger registered to the same file, this is a no-op.\n *\/\nvoid RegisterFileLogger(const wchar_t* filepath);\n\n#endif\n\n\/**\n * @brief This is constructed per-subsystem in a locally centralized fashon\n *\/\nclass Module {\n const char* m_modName;\n\n template <typename Char>\n void _vreport(Level severity, fmt::basic_string_view<Char> format,\n fmt::basic_format_args<fmt::buffer_context<Char>> args) {\n auto lk = LockLog();\n ++_LogCounter;\n if (severity == Fatal)\n RegisterConsoleLogger();\n for (auto& logger : MainLoggers)\n logger->report(m_modName, severity, format, args);\n if (severity == Error || severity == Fatal)\n logvisorBp();\n if (severity == Fatal)\n logvisorAbort();\n else if (severity == Error)\n ++ErrorCount;\n }\n\n template <typename Char>\n void _vreportSource(Level severity, const char* file, unsigned linenum, fmt::basic_string_view<Char> format,\n fmt::basic_format_args<fmt::buffer_context<Char>> args) {\n auto lk = LockLog();\n ++_LogCounter;\n if (severity == Fatal)\n RegisterConsoleLogger();\n for (auto& logger : MainLoggers)\n logger->reportSource(m_modName, severity, file, linenum, format, args);\n if (severity == Error || severity == Fatal)\n logvisorBp();\n if (severity == Fatal)\n logvisorAbort();\n else if (severity == Error)\n ++ErrorCount;\n }\n\npublic:\n constexpr Module(const char* modName) : m_modName(modName) {}\n\n \/**\n * @brief Route new log message to centralized ILogger\n * @param severity Level of log report severity\n * @param format Standard printf-style format string\n *\/\n template <typename S, typename... Args, typename Char = fmt::char_t<S>>\n void report(Level severity, const S& format, Args&&... args) {\n if (MainLoggers.empty() && severity != Level::Fatal)\n return;\n _vreport(severity, fmt::to_string_view<Char>(format),\n fmt::basic_format_args<fmt::buffer_context<Char>>(\n fmt::internal::make_args_checked<Args...>(format, std::forward<Args>(args)...)));\n }\n\n template <typename Char>\n void vreport(Level severity, fmt::basic_string_view<Char> format,\n fmt::basic_format_args<fmt::buffer_context<Char>> args) {\n if (MainLoggers.empty() && severity != Level::Fatal)\n return;\n _vreport(severity, format, args);\n }\n\n \/**\n * @brief Route new log message with source info to centralized ILogger\n * @param severity Level of log report severity\n * @param file Source file name from __FILE__ macro\n * @param linenum Source line number from __LINE__ macro\n * @param format Standard printf-style format string\n *\/\n template <typename S, typename... Args, typename Char = fmt::char_t<S>>\n void reportSource(Level severity, const char* file, unsigned linenum, const S& format, Args&&... args) {\n if (MainLoggers.empty() && severity != Level::Fatal)\n return;\n _vreportSource(severity, file, linenum, fmt::to_string_view<Char>(format),\n fmt::basic_format_args<fmt::buffer_context<Char>>(\n fmt::internal::make_args_checked<Args...>(format, std::forward<Args>(args)...)));\n }\n\n template <typename Char>\n void vreportSource(Level severity, const char* file, unsigned linenum, fmt::basic_string_view<Char> format,\n fmt::basic_format_args<fmt::buffer_context<Char>> args) {\n if (MainLoggers.empty() && severity != Level::Fatal)\n return;\n _vreportSource(severity, file, linenum, format, args);\n }\n};\n\n#define FMT_CUSTOM_FORMATTER(tp, fmtstr, ...) \\\nnamespace fmt { \\\ntemplate <> \\\nstruct formatter<tp, char> { \\\n template <typename ParseContext> \\\n constexpr auto parse(ParseContext &ctx) { return ctx.begin(); } \\\n template <typename FormatContext> \\\n auto format(const tp &obj, FormatContext &ctx) { \\\n return format_to(ctx.out(), fmt(fmtstr), __VA_ARGS__); \\\n } \\\n}; \\\ntemplate <> \\\nstruct formatter<tp, wchar_t> { \\\n template <typename ParseContext> \\\n constexpr auto parse(ParseContext &ctx) { return ctx.begin(); } \\\n template <typename FormatContext> \\\n auto format(const tp &obj, FormatContext &ctx) { \\\n return format_to(ctx.out(), fmt(L##fmtstr), __VA_ARGS__); \\\n } \\\n}; \\\ntemplate <> \\\nstruct formatter<tp, char16_t> { \\\n template <typename ParseContext> \\\n constexpr auto parse(ParseContext &ctx) { return ctx.begin(); } \\\n template <typename FormatContext> \\\n auto format(const tp &obj, FormatContext &ctx) { \\\n return format_to(ctx.out(), fmt(u##fmtstr), __VA_ARGS__); \\\n } \\\n}; \\\ntemplate <> \\\nstruct formatter<tp, char32_t> { \\\n template <typename ParseContext> \\\n constexpr auto parse(ParseContext &ctx) { return ctx.begin(); } \\\n template <typename FormatContext> \\\n auto format(const tp &obj, FormatContext &ctx) { \\\n return format_to(ctx.out(), fmt(U##fmtstr), __VA_ARGS__); \\\n } \\\n}; \\\n}\n\n} \/\/ namespace logvisor\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\r\n#include <fstream>\r\n#include <iomanip>\r\n#include <string>\r\n\r\n\/* run this program using the console pauser or add your own getch, system(\"pause\") or input loop *\/\r\nusing namespace std;\r\n\r\n\/\/ NURA [SCM-00000]\r\n\r\n\/\/function prototype\r\nvoid displayout();\r\n\r\nint main() {\r\n\t\r\n\t\/\/variables declarations\r\n\tdouble CourseWork, FinalMark, Exam;\r\n\tstring FName, LName;\r\n\tstring grade;\r\n\tint PAssignment, Test;\r\n\r\n\r\n\t\/\/Creating inFile and outFile\r\n\tifstream inFile;\r\n\tofstream outFile;\r\n\r\n\t\/\/Openning inFile and outFile\r\n\tinFile.open(\"studentInfile.txt\");\r\n\toutFile.open(\"studentOutfile.txt\");\r\n\r\n\t\/\/On screen headings for assessment report\r\n\tcout << \" Student Names \" << \" \" << \" Test \" << \" \" << \" PAssignment \" <<\" Exam \" << \" \" << \" CourseWork \" << \" \" << \" Final Mark \" << \" \" << \" Grade \" << endl;\r\n\tcout << \" ----------------------------------------------------------------------------- \" << endl;\r\n\t\/\/Resultout.txt headings for assessment report\r\n\toutFile << \" Student Names \" << \" \" << \" Test \" << \" \" << \" PAssignment \" << \" \" << \" Exam \" << \" \" << \" CourseWork \" << \" Final Mark \" << \" \" << \" Grade \" << endl;\r\n\toutFile << \" ----------------------------------------------------------------------------------------------- \" << endl;\r\n\r\n\t\/\/while loop that repeat reading from file\r\n\twhile (!inFile.eof())\r\n\t{\r\n\t\t\/\/Q1: Reading from a File [studentinfile.txt]\r\n\t\tinFile >> FName >> LName >> Test >> PAssignment >> Exam;\r\n\r\n\t\t\/\/Calculation of students assessment\r\n\t\t\/\/int LabMark = Lab1 + Lab2 + Lab3 + Lab4;\r\n\t\t\/\/int QuizMark = Quiz1 + Quiz2 + Quiz3;\r\n\t\tCourseWork = PAssignment * 0.15 + Test * 0.35;\r\n\t\tFinalMark = Exam * 0.50 + CourseWork;\r\n\r\n\t\t\/\/for loop which count the number of students\r\n\t\tfor (int i = 0; i <=0; i++)\r\n\t\t{\r\n\t\t\t\/\/conditions that test the range of students marks\r\n\t\t\tif ((FinalMark >= 0) && (FinalMark <= 39))\r\n\t\t\t{\r\n\t\t\t\tgrade = \"F\" \" \" \"Fail\";\r\n\t\t\t}\r\n\t\t\telse if ((FinalMark >= 40) && (FinalMark <= 44))\r\n\t\t\t{\r\n\t\t\t\tgrade = \"D\" \" \" \"Fail\";\r\n\t\t\t}\r\n\t\t\telse if ((FinalMark >= 45) && (FinalMark <= 49))\r\n\t\t\t{\r\n\t\t\t\tgrade = \"C-\" \" \" \"Fail\";\r\n\t\t\t}\r\n\t\t\telse if ((FinalMark >= 50) && (FinalMark <= 54))\r\n\t\t\t{\r\n\t\t\t\tgrade = \"C\" \" \" \"Pass\";\r\n\t\t\t}\r\n\t\t\telse if ((FinalMark >= 55) && (FinalMark <= 59))\r\n\t\t\t{\r\n\t\t\t\tgrade = \"C+\" \" \" \"Credit\";\r\n\t\t\t}\r\n\t\t\telse if ((FinalMark >= 60) && (FinalMark <= 64))\r\n\t\t\t{\r\n\t\t\t\tgrade = \"B-\" \" \" \"Credit\";\r\n\t\t\t}\r\n\t\t\telse if ((FinalMark >= 65) && (FinalMark <= 69))\r\n\t\t\t{\r\n\t\t\t\tgrade = \"B\" \" \" \"Credit\";\r\n\t\t\t}\r\n\t\t\telse if ((FinalMark >= 70) && (FinalMark <= 74))\r\n\t\t\t{\r\n\t\t\t\tgrade = \"B+\" \" \" \"Credit\";\r\n\t\t\t}\r\n\t\t\telse if ((FinalMark >= 75) && (FinalMark <= 79))\r\n\t\t\t{\r\n\t\t\t\tgrade = \"A-\" \" \" \"Distinction\";\r\n\t\t\t}\r\n\t\t\telse if ((FinalMark >= 80) && (FinalMark <= 100))\r\n\t\t\t{\r\n\t\t\t\tgrade = \"A\" \" \" \"Distinction\";\r\n\t\t\t}\r\n\r\n\t\t\t\/\/Q2: Displaying students report on screen\r\n\t\t\tcout << endl;\r\n\t\t\tcout << setw(2);\r\n\t\t\tcout << left << setw(10) << FName << setw(5) << LName\r\n\t\t\t\t<< right << setw(13) << Test << setw(14) << PAssignment << setw(14) << Exam << setw(14) << CourseWork << setw(12) << FinalMark << setw(18) << grade << endl;\r\n\r\n\t\t\t\/\/Q2: Writing students report to a File[studentoutfile.txt]\r\n\t\t\toutFile << left << setw(10) << FName << setw(10)\r\n\t\t\t\t<< LName << right << setw(3) << Test << setw(14) << PAssignment << setw(14) << Exam << setw(10) << CourseWork << setw(10) << FinalMark << setw(20) << grade << endl;\r\n\r\n\t\t} \/\/End for loop\r\n\t} \/\/End while loop\r\n\r\n\r\n\t\/\/Q3: Calling Function to display assessment on screen\r\n\tdisplayout();\r\n\r\n\t\/\/Closing inFile and outFile\r\n\tinFile.close();\r\n\toutFile.close();\r\n\r\n\tsystem(\"pause\");\r\n\t\r\n\treturn 0;\r\n}\r\n\r\n\/\/Function Implementation Syntax \r\n\r\nvoid displayout() \/\/function name with no return type\r\n{\r\n\t\/\/Q3: Displaying information on screen\r\n\tcout << endl << endl;\r\n\tcout << \"-----------------------------------------------\" << endl;\r\n\tcout << endl << endl;\r\n\tcout << fixed << showpoint << setprecision(2);\r\n\tcout << \" Status \" << \" \" << \" Mark Distribution \" << \" \" << \" NoOfStudent \" << endl;\r\n\tcout << \" ----------------------------------------------- \" << endl;\r\n\tcout << \" F \" << \" \" << \" 0-39 \" << \" \" << \" 7 \" << endl << endl;\r\n\tcout << \" D \" << \" \" << \" 40-44 \" << \" \" << \" 3 \" << endl << endl;\r\n\tcout << \" C- \" << \" \" << \" 45-49 \" << \" \" << \" 1 \" << endl << endl;\r\n\tcout << \" C \" << \" \" << \" 50-54 \" << \" \" << \" 1 \" << endl << endl;\r\n\tcout << \" C+ \" << \" \" << \" 55-59 \" << \" \" << \" 5 \" << endl << endl;\r\n\tcout << \" B- \" << \" \" << \" 60-64 \" << \" \" << \" 4 \" << endl << endl;\r\n\tcout << \" B \" << \" \" << \" 65-69 \" << \" \" << \" 3 \" << endl << endl;\r\n\tcout << \" B+ \" << \" \" << \" 70-74 \" << \" \" << \" 2 \" << endl << endl;\r\n\tcout << \" A- \" << \" \" << \" 75-79 \" << \" \" << \" 1 \" << endl << endl;\r\n\tcout << \" A \" << \" \" << \" 80-100 \" << \" \" << \" 3 \" << endl << endl;\r\n\r\n\r\n\t\/\/Overall results statistics \r\n\tcout << endl;\r\n\tcout << \" OVERALL STATISTICS\" << endl;\r\n\tcout << \" ------------------\" << endl;\r\n\tcout << endl;\r\n\tcout << \" Total Number of Students Processed : \" << \" 30 \" << endl;\r\n\tcout << \" Total Number of Distinction : \" << \" 4 \" << endl;\r\n\tcout << \" Total Number of Credit : \" << \" 9 \" << endl;\r\n\tcout << \" Total Number of Pass : \" << \" 6 \" << endl;\r\n\tcout << \" Total Number of Fail : \" << \" 11 \" << endl;\r\n\tcout << \" Average Mark : \" << \" 55.28 \" << endl;\r\n\tcout << \" Highest Mark : \" << \" 87.75 \" << endl;\r\n\tcout << \" Lowest Mark : \" << \" 21.35 \" << endl;\r\n\r\n\r\n\r\n\r\n} \/\/End Function\r\n<commit_msg>Update main.cpp<commit_after>#include <iostream>\r\n#include <fstream>\r\n#include <iomanip>\r\n#include <string>\r\n\r\n\/* run this program using the console pauser or add your own getch, system(\"pause\") or input loop *\/\r\nusing namespace std;\r\n\r\n\/\/ Author\r\nDeen Adam\r\n\r\n\/\/function prototype\r\nvoid displayout();\r\n\r\nint main() {\r\n\t\r\n\t\/\/variables declarations\r\n\tdouble CourseWork, FinalMark, Exam;\r\n\tstring FName, LName;\r\n\tstring grade;\r\n\tint PAssignment, Test;\r\n\r\n\r\n\t\/\/Creating inFile and outFile\r\n\tifstream inFile;\r\n\tofstream outFile;\r\n\r\n\t\/\/Openning inFile and outFile\r\n\tinFile.open(\"studentInfile.txt\");\r\n\toutFile.open(\"studentOutfile.txt\");\r\n\r\n\t\/\/On screen headings for assessment report\r\n\tcout << \" Student Names \" << \" \" << \" Test \" << \" \" << \" PAssignment \" <<\" Exam \" << \" \" << \" CourseWork \" << \" \" << \" Final Mark \" << \" \" << \" Grade \" << endl;\r\n\tcout << \" ----------------------------------------------------------------------------- \" << endl;\r\n\t\/\/Resultout.txt headings for assessment report\r\n\toutFile << \" Student Names \" << \" \" << \" Test \" << \" \" << \" PAssignment \" << \" \" << \" Exam \" << \" \" << \" CourseWork \" << \" Final Mark \" << \" \" << \" Grade \" << endl;\r\n\toutFile << \" ----------------------------------------------------------------------------------------------- \" << endl;\r\n\r\n\t\/\/while loop that repeat reading from file\r\n\twhile (!inFile.eof())\r\n\t{\r\n\t\t\/\/Q1: Reading from a File [studentinfile.txt]\r\n\t\tinFile >> FName >> LName >> Test >> PAssignment >> Exam;\r\n\r\n\t\t\/\/Calculation of students assessment\r\n\t\t\/\/int LabMark = Lab1 + Lab2 + Lab3 + Lab4;\r\n\t\t\/\/int QuizMark = Quiz1 + Quiz2 + Quiz3;\r\n\t\tCourseWork = PAssignment * 0.15 + Test * 0.35;\r\n\t\tFinalMark = Exam * 0.50 + CourseWork;\r\n\r\n\t\t\/\/for loop which count the number of students\r\n\t\tfor (int i = 0; i <=0; i++)\r\n\t\t{\r\n\t\t\t\/\/conditions that test the range of students marks\r\n\t\t\tif ((FinalMark >= 0) && (FinalMark <= 39))\r\n\t\t\t{\r\n\t\t\t\tgrade = \"F\" \" \" \"Fail\";\r\n\t\t\t}\r\n\t\t\telse if ((FinalMark >= 40) && (FinalMark <= 44))\r\n\t\t\t{\r\n\t\t\t\tgrade = \"D\" \" \" \"Fail\";\r\n\t\t\t}\r\n\t\t\telse if ((FinalMark >= 45) && (FinalMark <= 49))\r\n\t\t\t{\r\n\t\t\t\tgrade = \"C-\" \" \" \"Fail\";\r\n\t\t\t}\r\n\t\t\telse if ((FinalMark >= 50) && (FinalMark <= 54))\r\n\t\t\t{\r\n\t\t\t\tgrade = \"C\" \" \" \"Pass\";\r\n\t\t\t}\r\n\t\t\telse if ((FinalMark >= 55) && (FinalMark <= 59))\r\n\t\t\t{\r\n\t\t\t\tgrade = \"C+\" \" \" \"Credit\";\r\n\t\t\t}\r\n\t\t\telse if ((FinalMark >= 60) && (FinalMark <= 64))\r\n\t\t\t{\r\n\t\t\t\tgrade = \"B-\" \" \" \"Credit\";\r\n\t\t\t}\r\n\t\t\telse if ((FinalMark >= 65) && (FinalMark <= 69))\r\n\t\t\t{\r\n\t\t\t\tgrade = \"B\" \" \" \"Credit\";\r\n\t\t\t}\r\n\t\t\telse if ((FinalMark >= 70) && (FinalMark <= 74))\r\n\t\t\t{\r\n\t\t\t\tgrade = \"B+\" \" \" \"Credit\";\r\n\t\t\t}\r\n\t\t\telse if ((FinalMark >= 75) && (FinalMark <= 79))\r\n\t\t\t{\r\n\t\t\t\tgrade = \"A-\" \" \" \"Distinction\";\r\n\t\t\t}\r\n\t\t\telse if ((FinalMark >= 80) && (FinalMark <= 100))\r\n\t\t\t{\r\n\t\t\t\tgrade = \"A\" \" \" \"Distinction\";\r\n\t\t\t}\r\n\r\n\t\t\t\/\/Q2: Displaying students report on screen\r\n\t\t\tcout << endl;\r\n\t\t\tcout << setw(2);\r\n\t\t\tcout << left << setw(10) << FName << setw(5) << LName\r\n\t\t\t\t<< right << setw(13) << Test << setw(14) << PAssignment << setw(14) << Exam << setw(14) << CourseWork << setw(12) << FinalMark << setw(18) << grade << endl;\r\n\r\n\t\t\t\/\/Q2: Writing students report to a File[studentoutfile.txt]\r\n\t\t\toutFile << left << setw(10) << FName << setw(10)\r\n\t\t\t\t<< LName << right << setw(3) << Test << setw(14) << PAssignment << setw(14) << Exam << setw(10) << CourseWork << setw(10) << FinalMark << setw(20) << grade << endl;\r\n\r\n\t\t} \/\/End for loop\r\n\t} \/\/End while loop\r\n\r\n\r\n\t\/\/Q3: Calling Function to display assessment on screen\r\n\tdisplayout();\r\n\r\n\t\/\/Closing inFile and outFile\r\n\tinFile.close();\r\n\toutFile.close();\r\n\r\n\tsystem(\"pause\");\r\n\t\r\n\treturn 0;\r\n}\r\n\r\n\/\/Function Implementation Syntax \r\n\r\nvoid displayout() \/\/function name with no return type\r\n{\r\n\t\/\/Q3: Displaying information on screen\r\n\tcout << endl << endl;\r\n\tcout << \"-----------------------------------------------\" << endl;\r\n\tcout << endl << endl;\r\n\tcout << fixed << showpoint << setprecision(2);\r\n\tcout << \" Status \" << \" \" << \" Mark Distribution \" << \" \" << \" NoOfStudent \" << endl;\r\n\tcout << \" ----------------------------------------------- \" << endl;\r\n\tcout << \" F \" << \" \" << \" 0-39 \" << \" \" << \" 7 \" << endl << endl;\r\n\tcout << \" D \" << \" \" << \" 40-44 \" << \" \" << \" 3 \" << endl << endl;\r\n\tcout << \" C- \" << \" \" << \" 45-49 \" << \" \" << \" 1 \" << endl << endl;\r\n\tcout << \" C \" << \" \" << \" 50-54 \" << \" \" << \" 1 \" << endl << endl;\r\n\tcout << \" C+ \" << \" \" << \" 55-59 \" << \" \" << \" 5 \" << endl << endl;\r\n\tcout << \" B- \" << \" \" << \" 60-64 \" << \" \" << \" 4 \" << endl << endl;\r\n\tcout << \" B \" << \" \" << \" 65-69 \" << \" \" << \" 3 \" << endl << endl;\r\n\tcout << \" B+ \" << \" \" << \" 70-74 \" << \" \" << \" 2 \" << endl << endl;\r\n\tcout << \" A- \" << \" \" << \" 75-79 \" << \" \" << \" 1 \" << endl << endl;\r\n\tcout << \" A \" << \" \" << \" 80-100 \" << \" \" << \" 3 \" << endl << endl;\r\n\r\n\r\n\t\/\/Overall results statistics \r\n\tcout << endl;\r\n\tcout << \" OVERALL STATISTICS\" << endl;\r\n\tcout << \" ------------------\" << endl;\r\n\tcout << endl;\r\n\tcout << \" Total Number of Students Processed : \" << \" 30 \" << endl;\r\n\tcout << \" Total Number of Distinction : \" << \" 4 \" << endl;\r\n\tcout << \" Total Number of Credit : \" << \" 9 \" << endl;\r\n\tcout << \" Total Number of Pass : \" << \" 6 \" << endl;\r\n\tcout << \" Total Number of Fail : \" << \" 11 \" << endl;\r\n\tcout << \" Average Mark : \" << \" 55.28 \" << endl;\r\n\tcout << \" Highest Mark : \" << \" 87.75 \" << endl;\r\n\tcout << \" Lowest Mark : \" << \" 21.35 \" << endl;\r\n\r\n\r\n\r\n\r\n} \/\/End Function\r\n<|endoftext|>"} {"text":"<commit_before>#include <cmath>\n\n#include \"checker.hpp\"\n\nbool Checker::checkStep(GameDesk& a, Move& move) {\n if (move.undo_action = true) {\n return true;\n }\n int rownumber = a.getRowNumber();\n int n1 = a.getDeskNumber(move.p1);\n int n2 = a.getDeskNumber(move.p2);\n return checkIndex(rownumber, move) && n1 == n2;\n}\n\nbool Checker::checkIndex(int max, Move& move) {\n int p1c = move.p1.col;\n int p2c = move.p2.col;\n int p1r = move.p1.row;\n int p2r = move.p2.row;\n if (checkRange(max, move)) {\n if ((p1c == p2c) && (std::abs((p1r - p2r)) == 1)) {\n return true;\n } else if ((p1r == p2r) && (std::abs(p1c - p2c) == 1)) {\n return true;\n }\n return false;\n }\n return false;\n}\n\nbool Checker::checkRange(int max, Move& move) {\n int p1c = move.p1.col;\n int p2c = move.p2.col;\n int p1r = move.p1.row;\n int p2r = move.p2.row;\n bool gt0 = p1r >= 0 && p1c >= 0 && p2r >= 0 && p2c >= 0;\n bool ltm = p1r < max && p1c < max && p2r < max && p2c < max;\n return gt0 && ltm;\n}\n\n<commit_msg>Corect mistake in Checker::checkStep<commit_after>#include <cmath>\n\n#include \"checker.hpp\"\n\nbool Checker::checkStep(GameDesk& a, Move& move) {\n if (move.undo_action == true) {\n return true;\n }\n int rownumber = a.getRowNumber();\n int n1 = a.getDeskNumber(move.p1);\n int n2 = a.getDeskNumber(move.p2);\n return checkIndex(rownumber, move) && n1 == n2;\n}\n\nbool Checker::checkIndex(int max, Move& move) {\n int p1c = move.p1.col;\n int p2c = move.p2.col;\n int p1r = move.p1.row;\n int p2r = move.p2.row;\n if (checkRange(max, move)) {\n if ((p1c == p2c) && (std::abs((p1r - p2r)) == 1)) {\n return true;\n } else if ((p1r == p2r) && (std::abs(p1c - p2c) == 1)) {\n return true;\n }\n return false;\n }\n return false;\n}\n\nbool Checker::checkRange(int max, Move& move) {\n int p1c = move.p1.col;\n int p2c = move.p2.col;\n int p1r = move.p1.row;\n int p2r = move.p2.row;\n bool gt0 = p1r >= 0 && p1c >= 0 && p2r >= 0 && p2c >= 0;\n bool ltm = p1r < max && p1c < max && p2r < max && p2c < max;\n return gt0 && ltm;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/**************************************************************************\\\n * camera.hpp - Defining a movable and scalable camera w viewport *\n * ___ *\n * \/\\\/\\ __ _ __ _ _ __ _ _ _ __ ___ \/___\\_ __ _ _ ___ *\n * \/ \\ \/ _` |\/ _` | '_ \\| | | | '_ ` _ \\ \/\/ \/\/ '_ \\| | | \/ __| *\n * \/ \/\\\/\\ \\ (_| | (_| | | | | |_| | | | | | | \/ \\_\/\/| |_) | |_| \\__ \\ *\n * \\\/ \\\/\\__,_|\\__, |_| |_|\\__,_|_| |_| |_| \\___\/ | .__\/ \\__,_|___\/ *\n * |___\/ |_| *\n * *\n * Copyright (c) 2015 Florian Oetke & Sebastian Schalow *\n * *\n * This file is part of MagnumOpus and distributed under the MIT License *\n * See LICENSE file for details. *\n\\**************************************************************************\/\n\n#pragma once\n\n#include <glm\/glm.hpp>\n\n#include \"..\/engine.hpp\"\n\nnamespace mo {\nnamespace renderer {\n\n\tclass Camera {\n\n\tpublic:\n\n\t\t\/\/ Constructors\n\t\tCamera(const Engine &engine, float world_scale=1.f,\n\t\t const glm::vec2 position=glm::vec2(0.0f), float zoom=1.0f) noexcept;\n\n\t\t\/\/ Methods\n\t\tvoid position(glm::vec2 pos) noexcept {_pos = pos; _dirty = true;}\n\t\tvoid move(glm::vec2 offset) noexcept {_pos+=offset; _dirty = true;}\n\t\tvoid zoom(float z) noexcept {_zoom=z; _dirty=true;}\n\t\tvoid viewport(glm::vec4 viewport)noexcept;\n\n\t\tauto zoom() const noexcept { return _zoom; }\n\t\tauto position() const noexcept { return _pos; }\n\t\tauto viewport() const noexcept { return _viewport; }\n\n\t\tauto vp() const noexcept -> const glm::mat4&;\n\n\t\tauto screen_to_world(const glm::vec2 screen_pos) const noexcept -> glm::vec2;\n\t\tauto world_to_screen(const glm::vec2 world_pos) const noexcept -> glm::vec2;\n\n\tprivate:\n\t\tvoid recalc_vp()const noexcept;\n\n\t\tglm::vec4 _viewport; \/\/< x,y,w,h\n\t\tglm::mat4 _projection;\n\n\t\tconst float _world_scale;\n\t\tfloat _zoom;\n\t\tglm::vec2 _pos;\n\t\tmutable glm::mat4 _vp;\n\t\tmutable bool _dirty;\n\n\t};\n}\n}\n<commit_msg>Animation Data<commit_after>\/**************************************************************************\\\n * camera.hpp - Defining a movable and scalable camera w viewport *\n * ___ *\n * \/\\\/\\ __ _ __ _ _ __ _ _ _ __ ___ \/___\\_ __ _ _ ___ *\n * \/ \\ \/ _` |\/ _` | '_ \\| | | | '_ ` _ \\ \/\/ \/\/ '_ \\| | | \/ __| *\n * \/ \/\\\/\\ \\ (_| | (_| | | | | |_| | | | | | | \/ \\_\/\/| |_) | |_| \\__ \\ *\n * \\\/ \\\/\\__,_|\\__, |_| |_|\\__,_|_| |_| |_| \\___\/ | .__\/ \\__,_|___\/ *\n * |___\/ |_| *\n * *\n * Copyright (c) 2015 Florian Oetke & Sebastian Schalow *\n * *\n * This file is part of MagnumOpus and distributed under the MIT License *\n * See LICENSE file for details. *\n\\**************************************************************************\/\n\n#pragma once\n\n#include <glm\/glm.hpp>\n\n#include \"..\/engine.hpp\"\n\nnamespace mo {\nnamespace renderer {\n\n\tclass Camera {\n\n\tpublic:\n\n\t\t\/\/ Constructors\n\t\tCamera(const Engine &engine, float world_scale=1.f,\n\t\t const glm::vec2 position=glm::vec2(0.0f), float zoom=1.0f) noexcept;\n\n\t\t\/\/ Methods\n\t\tvoid position(glm::vec2 pos) noexcept {_pos = pos; _dirty = true;}\n\t\tvoid move(glm::vec2 offset) noexcept {_pos+=offset; _dirty = true;}\n\t\tvoid zoom(float z) noexcept {_zoom=z; _dirty=true;}\n\t\tvoid viewport(glm::vec4 viewport)noexcept;\n\n\t\tauto zoom() const noexcept { return _zoom; }\n\t\tauto position() const noexcept { return _pos; }\n\t\tauto viewport() const noexcept { return _viewport; }\n auto world_scale() const noexcept { return _world_scale; }\n\n\t\tauto vp() const noexcept -> const glm::mat4&;\n\n\t\tauto screen_to_world(const glm::vec2 screen_pos) const noexcept -> glm::vec2;\n\t\tauto world_to_screen(const glm::vec2 world_pos) const noexcept -> glm::vec2;\n\n\tprivate:\n\t\tvoid recalc_vp()const noexcept;\n\n\t\tglm::vec4 _viewport; \/\/< x,y,w,h\n\t\tglm::mat4 _projection;\n\n\t\tconst float _world_scale;\n\t\tfloat _zoom;\n\t\tglm::vec2 _pos;\n\t\tmutable glm::mat4 _vp;\n\t\tmutable bool _dirty;\n\n\t};\n}\n}\n<|endoftext|>"} {"text":"<commit_before>#if !defined(BOOST_PP_IS_ITERATING) || !BOOST_PP_IS_ITERATING\n\n#ifndef SHEAR__LALR__REDUCE_HPP\n#define SHEAR__LALR__REDUCE_HPP\n\n#include <boost\/preprocessor\/iteration\/iterate.hpp>\n#include <boost\/preprocessor\/iteration\/local.hpp>\n#include <boost\/preprocessor\/arithmetic\/sub.hpp>\n#include <boost\/fusion\/include\/transform.hpp>\n#include <boost\/fusion\/algorithm\/transformation\/remove.hpp>\n\n#include <shear\/compiletime\/argument_type.hpp>\n#include <shear\/lalr\/any_symbol.hpp>\n\nnamespace shear { namespace lalr {\n\nnamespace detail {\n\ntemplate<typename T, typename ArgVec>\ntypename boost::enable_if<\n typename mpl::equal_to<\n typename mpl::size<ArgVec>::type,\n mpl::size_t<0>\n >::type,\n T*\n>::type new_expand_vector(const ArgVec& args) {\n return new T();\n}\n\ntemplate<typename T, typename ArgVec>\ntypename boost::enable_if<\n typename mpl::equal_to<\n typename mpl::size<ArgVec>::type,\n mpl::size_t<1>\n >::type,\n T*\n>::type new_expand_vector(const ArgVec& args) {\n return new T(fusion::at<mpl::size_t<0> >(args));\n}\n\n#define BOOST_PP_ITERATION_PARAMS_1 \\\n (3, (2, SHEAR_PRODUCTION_LIMIT, \"shear\/lalr\/reduce.hpp\"))\n#include BOOST_PP_ITERATE()\n\n} \/\/ namespace detail\n\ntemplate<\n typename Grammar,\n typename Production,\n typename SymbolIndexType,\n typename Symbols\n>\nany_symbol<SymbolIndexType> reduce(const Symbols& symbols)\n{\n typedef typename Production::argument_tags tags;\n typedef typename fusion::result_of::as_vector<tags>::type tags_vector_type;\n tags_vector_type tags_vector;\n typedef typename fusion::result_of::transform<\n const Symbols, tags_vector_type, compiletime::argument_type\n >::type transformed_symbols_type;\n transformed_symbols_type transformed_symbols(\n symbols, tags_vector, compiletime::argument_type()\n );\n typedef typename fusion::result_of::remove<\n transformed_symbols_type,\n void\n >::type filtered_symbols_type;\n filtered_symbols_type filtered_symbols(transformed_symbols);\n typedef typename Production::source result_type;\n boost::shared_ptr<result_type> result(\n detail::new_expand_vector<result_type>(\n fusion::as_vector(filtered_symbols)\n )\n );\n return any_symbol<SymbolIndexType>(\n result,\n mpl::at<typename Grammar::symbol_index_map, result_type>::type::value\n );\n}\n\n}}\n\n#endif \/\/ SHEAR__LALR__REDUCE_HPP\n\n#else \/\/ iterating\n\ntemplate<typename T, typename ArgVec>\ntypename boost::enable_if<\n typename mpl::equal_to<\n typename mpl::size<ArgVec>::type,\n mpl::size_t<BOOST_PP_ITERATION()>\n >::type,\n T*\n>::type new_expand_vector(const ArgVec& args) {\n return new T(\n#define BOOST_PP_LOCAL_MACRO(index) \\\n fusion::at<mpl::size_t<index> >(args),\n#define BOOST_PP_LOCAL_LIMITS (0, BOOST_PP_SUB(BOOST_PP_ITERATION(), 2))\n#include BOOST_PP_LOCAL_ITERATE()\n fusion::at<mpl::size_t<BOOST_PP_ITERATION()-1> >(args)\n );\n}\n\n#endif\n\n<commit_msg>Avoid unused argument warning<commit_after>#if !defined(BOOST_PP_IS_ITERATING) || !BOOST_PP_IS_ITERATING\n\n#ifndef SHEAR__LALR__REDUCE_HPP\n#define SHEAR__LALR__REDUCE_HPP\n\n#include <boost\/preprocessor\/iteration\/iterate.hpp>\n#include <boost\/preprocessor\/iteration\/local.hpp>\n#include <boost\/preprocessor\/arithmetic\/sub.hpp>\n#include <boost\/fusion\/include\/transform.hpp>\n#include <boost\/fusion\/algorithm\/transformation\/remove.hpp>\n\n#include <shear\/compiletime\/argument_type.hpp>\n#include <shear\/lalr\/any_symbol.hpp>\n\nnamespace shear { namespace lalr {\n\nnamespace detail {\n\ntemplate<typename T, typename ArgVec>\ntypename boost::enable_if<\n typename mpl::equal_to<\n typename mpl::size<ArgVec>::type,\n mpl::size_t<0>\n >::type,\n T*\n>::type new_expand_vector(const ArgVec&) {\n return new T();\n}\n\ntemplate<typename T, typename ArgVec>\ntypename boost::enable_if<\n typename mpl::equal_to<\n typename mpl::size<ArgVec>::type,\n mpl::size_t<1>\n >::type,\n T*\n>::type new_expand_vector(const ArgVec& args) {\n return new T(fusion::at<mpl::size_t<0> >(args));\n}\n\n#define BOOST_PP_ITERATION_PARAMS_1 \\\n (3, (2, SHEAR_PRODUCTION_LIMIT, \"shear\/lalr\/reduce.hpp\"))\n#include BOOST_PP_ITERATE()\n\n} \/\/ namespace detail\n\ntemplate<\n typename Grammar,\n typename Production,\n typename SymbolIndexType,\n typename Symbols\n>\nany_symbol<SymbolIndexType> reduce(const Symbols& symbols)\n{\n typedef typename Production::argument_tags tags;\n typedef typename fusion::result_of::as_vector<tags>::type tags_vector_type;\n tags_vector_type tags_vector;\n typedef typename fusion::result_of::transform<\n const Symbols, tags_vector_type, compiletime::argument_type\n >::type transformed_symbols_type;\n transformed_symbols_type transformed_symbols(\n symbols, tags_vector, compiletime::argument_type()\n );\n typedef typename fusion::result_of::remove<\n transformed_symbols_type,\n void\n >::type filtered_symbols_type;\n filtered_symbols_type filtered_symbols(transformed_symbols);\n typedef typename Production::source result_type;\n boost::shared_ptr<result_type> result(\n detail::new_expand_vector<result_type>(\n fusion::as_vector(filtered_symbols)\n )\n );\n return any_symbol<SymbolIndexType>(\n result,\n mpl::at<typename Grammar::symbol_index_map, result_type>::type::value\n );\n}\n\n}}\n\n#endif \/\/ SHEAR__LALR__REDUCE_HPP\n\n#else \/\/ iterating\n\ntemplate<typename T, typename ArgVec>\ntypename boost::enable_if<\n typename mpl::equal_to<\n typename mpl::size<ArgVec>::type,\n mpl::size_t<BOOST_PP_ITERATION()>\n >::type,\n T*\n>::type new_expand_vector(const ArgVec& args) {\n return new T(\n#define BOOST_PP_LOCAL_MACRO(index) \\\n fusion::at<mpl::size_t<index> >(args),\n#define BOOST_PP_LOCAL_LIMITS (0, BOOST_PP_SUB(BOOST_PP_ITERATION(), 2))\n#include BOOST_PP_LOCAL_ITERATE()\n fusion::at<mpl::size_t<BOOST_PP_ITERATION()-1> >(args)\n );\n}\n\n#endif\n\n<|endoftext|>"} {"text":"<commit_before>#include <QString>\n#include <QDir>\n#include <QtCore>\n#include <iostream>\n\nint main(int argc, char** argv)\n{\n \/\/QCoreApplication app(argc, argv);\n QDir dir;\n\n dir.setFilter(QDir::Files | QDir::Hidden | QDir::NoSymLinks);\n dir.setSorting(QDir::Size | QDir::Reversed);\n\n QString path = argv[1];\n\n dir.cd(path);\n\n QFileInfoList list = dir.entryInfoList();\n\n std::cout << \" Bytes Filename\" << std::endl;\n\n for (int i = 0; i < list.size(); ++i)\n {\n QFileInfo fileInfo = list.at(i);\n\n std::cout << qPrintable(QString(\"%1 %2\").arg(fileInfo.size(), 10).arg(fileInfo.fileName()));\n std::cout << std::endl;\n }\n\n return 0; \/\/app.exec();\n}\n\n<commit_msg>Add QCoreApplication app. Replace return 0 on return app.exec().<commit_after>#include <QString>\n#include <QDir>\n#include <QtCore>\n#include <iostream>\n\nint main(int argc, char** argv)\n{\n QCoreApplication app(argc, argv);\n QDir dir;\n\n dir.setFilter(QDir::Files | QDir::Hidden | QDir::NoSymLinks);\n dir.setSorting(QDir::Size | QDir::Reversed);\n\n QString path = argv[1];\n\n dir.cd(path);\n\n QFileInfoList list = dir.entryInfoList();\n\n std::cout << \" Bytes Filename\" << std::endl;\n\n for (int i = 0; i < list.size(); ++i)\n {\n QFileInfo fileInfo = list.at(i);\n\n std::cout << qPrintable(QString(\"%1 %2\").arg(fileInfo.size(), 10).arg(fileInfo.fileName()));\n std::cout << std::endl;\n }\n\n return app.exec();\n}\n\n<|endoftext|>"} {"text":"<commit_before>#include <CQMsgHandler.h>\n\n#include <QApplication>\n\nnamespace CQMsgHandler {\n\nbool\ncheckEnv(const char *name) {\n const char *p = getenv(name);\n if (! p) return false;\n\n QString s = p;\n\n return (s == \"1\" || s == \"true\" || s == \"yes\");\n}\n\nbool\nisIgnoreMsg(const QString &msg)\n{\n static QStringList ignoreMessages;\n\n if (ignoreMessages.empty()) {\n ignoreMessages.push_back(\"QBasicTimer can only be used with threads started with QThread\");\n }\n\n for (const auto &imsg : ignoreMessages) {\n if (msg.indexOf(imsg) > 0)\n return true;\n }\n\n return false;\n}\n\nvoid\nmessageOutput(QtMsgType type, const QMessageLogContext &context, const QString &msg)\n{\n auto localMsg = msg.toLocal8Bit();\n\n if (isIgnoreMsg(localMsg))\n return;\n\n switch (type) {\n case QtDebugMsg: {\n fprintf(stderr, \"Debug: %s (%s:%u, %s)\\n\",\n localMsg.constData(), context.file, context.line, context.function);\n break;\n }\n case QtInfoMsg: {\n fprintf(stderr, \"Info: %s (%s:%u, %s)\\n\",\n localMsg.constData(), context.file, context.line, context.function);\n break;\n }\n case QtWarningMsg: {\n fprintf(stderr, \"Warning: %s (%s:%u, %s)\\n\",\n localMsg.constData(), context.file, context.line, context.function);\n\n if (checkEnv(\"CQMSG_HANDLER_WARN_ASSERT\"))\n abort();\n\n break;\n }\n case QtCriticalMsg: {\n fprintf(stderr, \"Critical: %s (%s:%u, %s)\\n\",\n localMsg.constData(), context.file, context.line, context.function);\n abort();\n break;\n }\n case QtFatalMsg: {\n fprintf(stderr, \"Fatal: %s (%s:%u, %s)\\n\",\n localMsg.constData(), context.file, context.line, context.function);\n abort();\n break;\n }\n }\n}\n\n}\n\nnamespace CQMsgHandler {\n\nvoid\ninstall()\n{\n qInstallMessageHandler(messageOutput);\n}\n\n}\n<commit_msg>new files<commit_after>#include <CQMsgHandler.h>\n\n#include <QApplication>\n\nnamespace CQMsgHandler {\n\nbool\ncheckEnv(const char *name) {\n const char *p = getenv(name);\n if (! p) return false;\n\n QString s = p;\n\n return (s == \"1\" || s == \"true\" || s == \"yes\");\n}\n\nbool\nisIgnoreMsg(const QString &msg)\n{\n static QStringList ignoreMessages;\n\n if (ignoreMessages.empty()) {\n ignoreMessages.push_back(\"QBasicTimer can only be used with threads started with QThread\");\n ignoreMessages.push_back(\"Timers can only be used with threads started with QThread\");\n }\n\n for (const auto &imsg : ignoreMessages) {\n if (msg.indexOf(imsg) > 0)\n return true;\n }\n\n return false;\n}\n\nvoid\nmessageOutput(QtMsgType type, const QMessageLogContext &context, const QString &msg)\n{\n auto localMsg = msg.toLocal8Bit();\n\n if (isIgnoreMsg(localMsg))\n return;\n\n switch (type) {\n case QtDebugMsg: {\n fprintf(stderr, \"Debug: %s (%s:%u, %s)\\n\",\n localMsg.constData(), context.file, context.line, context.function);\n break;\n }\n case QtInfoMsg: {\n fprintf(stderr, \"Info: %s (%s:%u, %s)\\n\",\n localMsg.constData(), context.file, context.line, context.function);\n break;\n }\n case QtWarningMsg: {\n fprintf(stderr, \"Warning: %s (%s:%u, %s)\\n\",\n localMsg.constData(), context.file, context.line, context.function);\n\n if (checkEnv(\"CQMSG_HANDLER_WARN_ASSERT\"))\n abort();\n\n break;\n }\n case QtCriticalMsg: {\n fprintf(stderr, \"Critical: %s (%s:%u, %s)\\n\",\n localMsg.constData(), context.file, context.line, context.function);\n abort();\n break;\n }\n case QtFatalMsg: {\n fprintf(stderr, \"Fatal: %s (%s:%u, %s)\\n\",\n localMsg.constData(), context.file, context.line, context.function);\n abort();\n break;\n }\n }\n}\n\n}\n\nnamespace CQMsgHandler {\n\nvoid\ninstall()\n{\n qInstallMessageHandler(messageOutput);\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before>#include <assert.h>\n#include <list>\n#include <algorithm>\n#include <portmidi.h>\n#include \"core.hpp\"\n\n\nusing namespace rack;\n\nstatic bool initialized = false;\n\nvoid midiInit() {\n\tif (initialized)\n\t\treturn;\n\n\tPmError err = Pm_Initialize();\n\tif (err) {\n\t\tprintf(\"Failed to initialize PortMidi: %s\\n\", Pm_GetErrorText(err));\n\t\treturn;\n\t}\n\tinitialized = true;\n}\n\n\nstruct MidiInterface : Module {\n\tenum ParamIds {\n\t\tNUM_PARAMS\n\t};\n\tenum InputIds {\n\t\tNUM_INPUTS\n\t};\n\tenum OutputIds {\n\t\tPITCH_OUTPUT,\n\t\tGATE_OUTPUT,\n\t\tMOD_OUTPUT,\n\t\tPITCHWHEEL_OUTPUT,\n\t\tNUM_OUTPUTS\n\t};\n\n\tint portId = -1;\n\tPortMidiStream *stream = NULL;\n\tstd::list<int> notes;\n\t\/** Filter MIDI channel\n\t-1 means all MIDI channels\n\t*\/\n\tint channel = -1;\n\tbool pedal = false;\n\tint note = 60; \/\/ C4, most modules should use 261.626 Hz\n\tint mod = 0;\n\tint pitchWheel = 64;\n\tbool retrigger = false;\n\tbool retriggered = false;\n\n\tMidiInterface();\n\t~MidiInterface();\n\tvoid step();\n\n\tint getPortCount();\n\tstd::string getPortName(int portId);\n\t\/\/ -1 will close the port\n\tvoid openPort(int portId);\n\tvoid pressNote(int note);\n\tvoid releaseNote(int note);\n\tvoid processMidi(long msg);\n};\n\n\nMidiInterface::MidiInterface() {\n\tparams.resize(NUM_PARAMS);\n\tinputs.resize(NUM_INPUTS);\n\toutputs.resize(NUM_OUTPUTS);\n\tmidiInit();\n\n\tprintf(\"<<<%d>>>\\n\", getPortCount());\n}\n\nMidiInterface::~MidiInterface() {\n\topenPort(-1);\n}\n\nvoid MidiInterface::step() {\n\tif (stream) {\n\t\t\/\/ Read MIDI events\n\t\tPmEvent event;\n\t\twhile (Pm_Read(stream, &event, 1) > 0) {\n\t\t\tprocessMidi(event.message);\n\t\t}\n\t}\n\n\tif (outputs[PITCH_OUTPUT]) {\n\t\t*outputs[PITCH_OUTPUT] = ((note - 64)) \/ 12.0;\n\t}\n\tif (outputs[GATE_OUTPUT]) {\n\t\tbool gate = pedal || !notes.empty();\n\t\tif (retrigger && retriggered) {\n\t\t\tgate = false;\n\t\t\tretriggered = false;\n\t\t}\n\t\t*outputs[GATE_OUTPUT] = gate ? 5.0 : 0.0;\n\t}\n\tif (outputs[MOD_OUTPUT]) {\n\t\t*outputs[MOD_OUTPUT] = mod;\n\t}\n\tif (outputs[PITCHWHEEL_OUTPUT]) {\n\t\t*outputs[PITCHWHEEL_OUTPUT] = (pitchWheel - 64) \/ 64.0 \/ 12.0;\n\t}\n}\n\nint MidiInterface::getPortCount() {\n\treturn Pm_CountDevices();\n}\n\nstd::string MidiInterface::getPortName(int portId) {\n\tconst PmDeviceInfo *info = Pm_GetDeviceInfo(portId);\n\tif (!info)\n\t\treturn \"\";\n\treturn stringf(\"%s: %s (%s)\", info->interf, info->name, info->input ? \"input\" : \"output\");\n}\n\nvoid MidiInterface::openPort(int portId) {\n\tPmError err;\n\n\t\/\/ Close existing port\n\tif (stream) {\n\t\terr = Pm_Close(stream);\n\t\tif (err) {\n\t\t\tprintf(\"Failed to close MIDI port: %s\\n\", Pm_GetErrorText(err));\n\t\t}\n\t\tstream = NULL;\n\t}\n\n\t\/\/ Open new port\n\tif (portId >= 0) {\n\t\terr = Pm_OpenInput(&stream, portId, NULL, 128, NULL, NULL);\n\t\tif (err) {\n\t\t\tprintf(\"Failed to open MIDI port: %s\\n\", Pm_GetErrorText(err));\n\t\t\treturn;\n\t\t}\n\t}\n\tthis->portId = portId;\n}\n\nvoid MidiInterface::pressNote(int note) {\n\t\/\/ Remove existing similar note\n\tauto it = std::find(notes.begin(), notes.end(), note);\n\tif (it != notes.end())\n\t\tnotes.erase(it);\n\t\/\/ Push note\n\tnotes.push_back(note);\n\tthis->note = note;\n\tretriggered = true;\n}\n\nvoid MidiInterface::releaseNote(int note) {\n\t\/\/ Remove the note\n\tauto it = std::find(notes.begin(), notes.end(), note);\n\tif (it != notes.end())\n\t\tnotes.erase(it);\n\n\tif (pedal) {\n\t\t\/\/ Don't release if pedal is held\n\t}\n\telse if (!notes.empty()) {\n\t\t\/\/ Play previous note\n\t\tauto it2 = notes.end();\n\t\tit2--;\n\t\tthis->note = *it2;\n\t\tretriggered = true;\n\t}\n}\n\nvoid MidiInterface::processMidi(long msg) {\n\tint channel = msg & 0xf;\n\tint status = (msg >> 4) & 0xf;\n\tint data1 = (msg >> 8) & 0xff;\n\tint data2 = (msg >> 16) & 0xff;\n\n\tif (channel != 0)\n\t\treturn;\n\tprintf(\"channel %d status %d data1 %d data2 %d\\n\", channel, status, data1, data2);\n\n\tswitch (status) {\n\t\t\/\/ note off\n\t\tcase 0x8: {\n\t\t\treleaseNote(data1);\n\t\t} break;\n\t\tcase 0x9: \/\/ note on\n\t\t\tif (data2 > 0) {\n\t\t\t\tpressNote(data1);\n\t\t\t}\n\t\t\telse {\n\t\t\t\t\/\/ For some reason, some keyboards send a \"note on\" event with a velocity of 0 to signal that the key has been released.\n\t\t\t\treleaseNote(data1);\n\t\t\t}\n\t\t\tbreak;\n\t\tcase 0xb: \/\/ cc\n\t\t\tswitch (data1) {\n\t\t\t\tcase 0x40:\n\t\t\t\t\tpedal = (data2 >= 64);\n\t\t\t\t\treleaseNote(-1);\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t\tbreak;\n\t\tcase 0xe: \/\/ pitch wheel\n\t\t\tthis->pitchWheel = data2;\n\t\t\tbreak;\n\t}\n}\n\n\nstruct MidiItem : MenuItem {\n\tMidiInterface *midiInterface;\n\tint portId;\n\tvoid onAction() {\n\t\tmidiInterface->openPort(portId);\n\t}\n};\n\nstruct MidiChoice : ChoiceButton {\n\tMidiInterface *midiInterface;\n\tvoid onAction() {\n\t\tMenu *menu = gScene->createMenu();\n\t\tmenu->box.pos = getAbsolutePos().plus(Vec(0, box.size.y));\n\t\tmenu->box.size.x = box.size.x;\n\n\t\tint portCount = midiInterface->getPortCount();\n\t\t{\n\t\t\tMidiItem *midiItem = new MidiItem();\n\t\t\tmidiItem->midiInterface = midiInterface;\n\t\t\tmidiItem->portId = -1;\n\t\t\tmidiItem->text = \"No device\";\n\t\t\tmenu->pushChild(midiItem);\n\t\t}\n\t\tfor (int portId = 0; portId < portCount; portId++) {\n\t\t\tMidiItem *midiItem = new MidiItem();\n\t\t\tmidiItem->midiInterface = midiInterface;\n\t\t\tmidiItem->portId = portId;\n\t\t\tmidiItem->text = midiInterface->getPortName(portId);\n\t\t\tmenu->pushChild(midiItem);\n\t\t}\n\t}\n\tvoid step() {\n\t\tstd::string name = midiInterface->getPortName(midiInterface->portId);\n\t\ttext = name.empty() ? \"(no device)\" : ellipsize(name, 14);\n\t}\n};\n\nstruct ChannelItem : MenuItem {\n\tMidiInterface *midiInterface;\n\tint channel;\n\tvoid onAction() {\n\t\tmidiInterface->channel = channel;\n\t}\n};\n\nstruct ChannelChoice : ChoiceButton {\n\tMidiInterface *midiInterface;\n\tvoid onAction() {\n\t\tMenu *menu = gScene->createMenu();\n\t\tmenu->box.pos = getAbsolutePos().plus(Vec(0, box.size.y));\n\t\tmenu->box.size.x = box.size.x;\n\n\t\t{\n\t\t\tChannelItem *channelItem = new ChannelItem();\n\t\t\tchannelItem->midiInterface = midiInterface;\n\t\t\tchannelItem->channel = -1;\n\t\t\tchannelItem->text = \"All\";\n\t\t\tmenu->pushChild(channelItem);\n\t\t}\n\t\tfor (int channel = 0; channel < 16; channel++) {\n\t\t\tChannelItem *channelItem = new ChannelItem();\n\t\t\tchannelItem->midiInterface = midiInterface;\n\t\t\tchannelItem->channel = channel;\n\t\t\tchannelItem->text = stringf(\"%d\", channel + 1);\n\t\t\tmenu->pushChild(channelItem);\n\t\t}\n\t}\n\tvoid step() {\n\t\ttext = (midiInterface->channel >= 0) ? stringf(\"%d\", midiInterface->channel + 1) : \"All\";\n\t}\n};\n\n\nMidiInterfaceWidget::MidiInterfaceWidget() {\n\tMidiInterface *module = new MidiInterface();\n\tsetModule(module);\n\tbox.size = Vec(15*8, 380);\n\n\t{\n\t\tPanel *panel = new LightPanel();\n\t\tpanel->box.size = box.size;\n\t\taddChild(panel);\n\t}\n\n\tfloat margin = 5;\n\tfloat labelHeight = 15;\n\tfloat yPos = margin;\n\n\t{\n\t\tLabel *label = new Label();\n\t\tlabel->box.pos = Vec(margin, yPos);\n\t\tlabel->text = \"MIDI device\";\n\t\taddChild(label);\n\t\tyPos += labelHeight + margin;\n\n\t\tMidiChoice *midiChoice = new MidiChoice();\n\t\tmidiChoice->midiInterface = dynamic_cast<MidiInterface*>(module);\n\t\tmidiChoice->box.pos = Vec(margin, yPos);\n\t\tmidiChoice->box.size.x = box.size.x - 10;\n\t\taddChild(midiChoice);\n\t\tyPos += midiChoice->box.size.y + margin;\n\t}\n\n\t{\n\t\tLabel *label = new Label();\n\t\tlabel->box.pos = Vec(margin, yPos);\n\t\tlabel->text = \"MIDI channel\";\n\t\taddChild(label);\n\t\tyPos += labelHeight + margin;\n\n\t\tChannelChoice *channelChoice = new ChannelChoice();\n\t\tchannelChoice->midiInterface = dynamic_cast<MidiInterface*>(module);\n\t\tchannelChoice->box.pos = Vec(margin, yPos);\n\t\tchannelChoice->box.size.x = box.size.x - 10;\n\t\taddChild(channelChoice);\n\t\tyPos += channelChoice->box.size.y + margin;\n\t}\n\n\tyPos += 5;\n\taddOutput(createOutput<PJ3410Port>(Vec(20, yPos), module, MidiInterface::PITCH_OUTPUT));\n\tyPos += 37 + margin;\n\n\tyPos += 5;\n\taddOutput(createOutput<PJ3410Port>(Vec(20, yPos), module, MidiInterface::GATE_OUTPUT));\n\tyPos += 37 + margin;\n\n\tyPos += 5;\n\taddOutput(createOutput<PJ3410Port>(Vec(20, yPos), module, MidiInterface::MOD_OUTPUT));\n\tyPos += 37 + margin;\n\n\tyPos += 5;\n\taddOutput(createOutput<PJ3410Port>(Vec(20, yPos), module, MidiInterface::PITCHWHEEL_OUTPUT));\n\tyPos += 37 + margin;\n}\n<commit_msg>Added mod wheel and MIDI channel functionality to MIDI Interface<commit_after>#include <assert.h>\n#include <list>\n#include <algorithm>\n#include <portmidi.h>\n#include \"core.hpp\"\n\n\nusing namespace rack;\n\nstatic bool initialized = false;\n\nvoid midiInit() {\n\tif (initialized)\n\t\treturn;\n\n\tPmError err = Pm_Initialize();\n\tif (err) {\n\t\tprintf(\"Failed to initialize PortMidi: %s\\n\", Pm_GetErrorText(err));\n\t\treturn;\n\t}\n\tinitialized = true;\n}\n\n\nstruct MidiInterface : Module {\n\tenum ParamIds {\n\t\tNUM_PARAMS\n\t};\n\tenum InputIds {\n\t\tNUM_INPUTS\n\t};\n\tenum OutputIds {\n\t\tPITCH_OUTPUT,\n\t\tGATE_OUTPUT,\n\t\tMOD_OUTPUT,\n\t\tPITCHWHEEL_OUTPUT,\n\t\tNUM_OUTPUTS\n\t};\n\n\tint portId = -1;\n\tPortMidiStream *stream = NULL;\n\tstd::list<int> notes;\n\t\/** Filter MIDI channel\n\t-1 means all MIDI channels\n\t*\/\n\tint channel = -1;\n\tbool pedal = false;\n\tint note = 60; \/\/ C4, most modules should use 261.626 Hz\n\tint mod = 0;\n\tint pitchWheel = 64;\n\tbool retrigger = false;\n\tbool retriggered = false;\n\n\tMidiInterface();\n\t~MidiInterface();\n\tvoid step();\n\n\tint getPortCount();\n\tstd::string getPortName(int portId);\n\t\/\/ -1 will close the port\n\tvoid openPort(int portId);\n\tvoid pressNote(int note);\n\tvoid releaseNote(int note);\n\tvoid processMidi(long msg);\n};\n\n\nMidiInterface::MidiInterface() {\n\tparams.resize(NUM_PARAMS);\n\tinputs.resize(NUM_INPUTS);\n\toutputs.resize(NUM_OUTPUTS);\n\tmidiInit();\n}\n\nMidiInterface::~MidiInterface() {\n\topenPort(-1);\n}\n\nvoid MidiInterface::step() {\n\tif (stream) {\n\t\t\/\/ Read MIDI events\n\t\tPmEvent event;\n\t\twhile (Pm_Read(stream, &event, 1) > 0) {\n\t\t\tprocessMidi(event.message);\n\t\t}\n\t}\n\n\tif (outputs[PITCH_OUTPUT]) {\n\t\t*outputs[PITCH_OUTPUT] = ((note - 64)) \/ 12.0;\n\t}\n\tif (outputs[GATE_OUTPUT]) {\n\t\tbool gate = pedal || !notes.empty();\n\t\tif (retrigger && retriggered) {\n\t\t\tgate = false;\n\t\t\tretriggered = false;\n\t\t}\n\t\t*outputs[GATE_OUTPUT] = gate ? 10.0 : 0.0;\n\t}\n\tif (outputs[MOD_OUTPUT]) {\n\t\t*outputs[MOD_OUTPUT] = mod \/ 127.0 * 10.0;\n\t}\n\tif (outputs[PITCHWHEEL_OUTPUT]) {\n\t\t*outputs[PITCHWHEEL_OUTPUT] = (pitchWheel - 64) \/ 64.0 * 10.0;\n\t}\n}\n\nint MidiInterface::getPortCount() {\n\treturn Pm_CountDevices();\n}\n\nstd::string MidiInterface::getPortName(int portId) {\n\tconst PmDeviceInfo *info = Pm_GetDeviceInfo(portId);\n\tif (!info)\n\t\treturn \"\";\n\treturn stringf(\"%s: %s (%s)\", info->interf, info->name, info->input ? \"input\" : \"output\");\n}\n\nvoid MidiInterface::openPort(int portId) {\n\tPmError err;\n\n\t\/\/ Close existing port\n\tif (stream) {\n\t\terr = Pm_Close(stream);\n\t\tif (err) {\n\t\t\tprintf(\"Failed to close MIDI port: %s\\n\", Pm_GetErrorText(err));\n\t\t}\n\t\tstream = NULL;\n\t}\n\tthis->portId = -1;\n\n\t\/\/ Open new port\n\tif (portId >= 0) {\n\t\terr = Pm_OpenInput(&stream, portId, NULL, 128, NULL, NULL);\n\t\tif (err) {\n\t\t\tprintf(\"Failed to open MIDI port: %s\\n\", Pm_GetErrorText(err));\n\t\t\treturn;\n\t\t}\n\t}\n\tthis->portId = portId;\n}\n\nvoid MidiInterface::pressNote(int note) {\n\t\/\/ Remove existing similar note\n\tauto it = std::find(notes.begin(), notes.end(), note);\n\tif (it != notes.end())\n\t\tnotes.erase(it);\n\t\/\/ Push note\n\tnotes.push_back(note);\n\tthis->note = note;\n\tretriggered = true;\n}\n\nvoid MidiInterface::releaseNote(int note) {\n\t\/\/ Remove the note\n\tauto it = std::find(notes.begin(), notes.end(), note);\n\tif (it != notes.end())\n\t\tnotes.erase(it);\n\n\tif (pedal) {\n\t\t\/\/ Don't release if pedal is held\n\t}\n\telse if (!notes.empty()) {\n\t\t\/\/ Play previous note\n\t\tauto it2 = notes.end();\n\t\tit2--;\n\t\tthis->note = *it2;\n\t\tretriggered = true;\n\t}\n}\n\nvoid MidiInterface::processMidi(long msg) {\n\tint channel = msg & 0xf;\n\tint status = (msg >> 4) & 0xf;\n\tint data1 = (msg >> 8) & 0xff;\n\tint data2 = (msg >> 16) & 0xff;\n\tprintf(\"channel %d status %d data1 %d data2 %d\\n\", channel, status, data1, data2);\n\n\t\/\/ Filter channels\n\tif (this->channel >= 0 && this->channel != channel)\n\t\treturn;\n\n\tswitch (status) {\n\t\t\/\/ note off\n\t\tcase 0x8: {\n\t\t\treleaseNote(data1);\n\t\t} break;\n\t\tcase 0x9: \/\/ note on\n\t\t\tif (data2 > 0) {\n\t\t\t\tpressNote(data1);\n\t\t\t}\n\t\t\telse {\n\t\t\t\t\/\/ For some reason, some keyboards send a \"note on\" event with a velocity of 0 to signal that the key has been released.\n\t\t\t\treleaseNote(data1);\n\t\t\t}\n\t\t\tbreak;\n\t\tcase 0xb: \/\/ cc\n\t\t\tswitch (data1) {\n\t\t\t\tcase 0x01: \/\/ mod\n\t\t\t\t\tthis->mod = data2;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 0x40: \/\/ sustain\n\t\t\t\t\tpedal = (data2 >= 64);\n\t\t\t\t\treleaseNote(-1);\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t\tbreak;\n\t\tcase 0xe: \/\/ pitch wheel\n\t\t\tthis->pitchWheel = data2;\n\t\t\tbreak;\n\t}\n}\n\n\nstruct MidiItem : MenuItem {\n\tMidiInterface *midiInterface;\n\tint portId;\n\tvoid onAction() {\n\t\tmidiInterface->openPort(portId);\n\t}\n};\n\nstruct MidiChoice : ChoiceButton {\n\tMidiInterface *midiInterface;\n\tvoid onAction() {\n\t\tMenu *menu = gScene->createMenu();\n\t\tmenu->box.pos = getAbsolutePos().plus(Vec(0, box.size.y));\n\t\tmenu->box.size.x = box.size.x;\n\n\t\tint portCount = midiInterface->getPortCount();\n\t\t{\n\t\t\tMidiItem *midiItem = new MidiItem();\n\t\t\tmidiItem->midiInterface = midiInterface;\n\t\t\tmidiItem->portId = -1;\n\t\t\tmidiItem->text = \"No device\";\n\t\t\tmenu->pushChild(midiItem);\n\t\t}\n\t\tfor (int portId = 0; portId < portCount; portId++) {\n\t\t\tMidiItem *midiItem = new MidiItem();\n\t\t\tmidiItem->midiInterface = midiInterface;\n\t\t\tmidiItem->portId = portId;\n\t\t\tmidiItem->text = midiInterface->getPortName(portId);\n\t\t\tmenu->pushChild(midiItem);\n\t\t}\n\t}\n\tvoid step() {\n\t\tstd::string name = midiInterface->getPortName(midiInterface->portId);\n\t\ttext = name.empty() ? \"(no device)\" : ellipsize(name, 14);\n\t}\n};\n\nstruct ChannelItem : MenuItem {\n\tMidiInterface *midiInterface;\n\tint channel;\n\tvoid onAction() {\n\t\tmidiInterface->channel = channel;\n\t}\n};\n\nstruct ChannelChoice : ChoiceButton {\n\tMidiInterface *midiInterface;\n\tvoid onAction() {\n\t\tMenu *menu = gScene->createMenu();\n\t\tmenu->box.pos = getAbsolutePos().plus(Vec(0, box.size.y));\n\t\tmenu->box.size.x = box.size.x;\n\n\t\t{\n\t\t\tChannelItem *channelItem = new ChannelItem();\n\t\t\tchannelItem->midiInterface = midiInterface;\n\t\t\tchannelItem->channel = -1;\n\t\t\tchannelItem->text = \"All\";\n\t\t\tmenu->pushChild(channelItem);\n\t\t}\n\t\tfor (int channel = 0; channel < 16; channel++) {\n\t\t\tChannelItem *channelItem = new ChannelItem();\n\t\t\tchannelItem->midiInterface = midiInterface;\n\t\t\tchannelItem->channel = channel;\n\t\t\tchannelItem->text = stringf(\"%d\", channel + 1);\n\t\t\tmenu->pushChild(channelItem);\n\t\t}\n\t}\n\tvoid step() {\n\t\ttext = (midiInterface->channel >= 0) ? stringf(\"%d\", midiInterface->channel + 1) : \"All\";\n\t}\n};\n\n\nMidiInterfaceWidget::MidiInterfaceWidget() {\n\tMidiInterface *module = new MidiInterface();\n\tsetModule(module);\n\tbox.size = Vec(15*8, 380);\n\n\t{\n\t\tPanel *panel = new LightPanel();\n\t\tpanel->box.size = box.size;\n\t\taddChild(panel);\n\t}\n\n\tfloat margin = 5;\n\tfloat labelHeight = 15;\n\tfloat yPos = margin;\n\n\t{\n\t\tLabel *label = new Label();\n\t\tlabel->box.pos = Vec(margin, yPos);\n\t\tlabel->text = \"MIDI device\";\n\t\taddChild(label);\n\t\tyPos += labelHeight + margin;\n\n\t\tMidiChoice *midiChoice = new MidiChoice();\n\t\tmidiChoice->midiInterface = dynamic_cast<MidiInterface*>(module);\n\t\tmidiChoice->box.pos = Vec(margin, yPos);\n\t\tmidiChoice->box.size.x = box.size.x - 10;\n\t\taddChild(midiChoice);\n\t\tyPos += midiChoice->box.size.y + margin;\n\t}\n\n\t{\n\t\tLabel *label = new Label();\n\t\tlabel->box.pos = Vec(margin, yPos);\n\t\tlabel->text = \"MIDI channel\";\n\t\taddChild(label);\n\t\tyPos += labelHeight + margin;\n\n\t\tChannelChoice *channelChoice = new ChannelChoice();\n\t\tchannelChoice->midiInterface = dynamic_cast<MidiInterface*>(module);\n\t\tchannelChoice->box.pos = Vec(margin, yPos);\n\t\tchannelChoice->box.size.x = box.size.x - 10;\n\t\taddChild(channelChoice);\n\t\tyPos += channelChoice->box.size.y + margin;\n\t}\n\n\tyPos += 5;\n\taddOutput(createOutput<PJ3410Port>(Vec(20, yPos), module, MidiInterface::PITCH_OUTPUT));\n\tyPos += 37 + margin;\n\n\tyPos += 5;\n\taddOutput(createOutput<PJ3410Port>(Vec(20, yPos), module, MidiInterface::GATE_OUTPUT));\n\tyPos += 37 + margin;\n\n\tyPos += 5;\n\taddOutput(createOutput<PJ3410Port>(Vec(20, yPos), module, MidiInterface::MOD_OUTPUT));\n\tyPos += 37 + margin;\n\n\tyPos += 5;\n\taddOutput(createOutput<PJ3410Port>(Vec(20, yPos), module, MidiInterface::PITCHWHEEL_OUTPUT));\n\tyPos += 37 + margin;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright 2014 Google Inc.\n *\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n *\/\n\n#include \"SkBitmapCache.h\"\n#include \"SkImage.h\"\n#include \"SkResourceCache.h\"\n#include \"SkMipMap.h\"\n#include \"SkPixelRef.h\"\n#include \"SkRect.h\"\n\n\/**\n * Use this for bitmapcache and mipmapcache entries.\n *\/\nuint64_t SkMakeResourceCacheSharedIDForBitmap(uint32_t bitmapGenID) {\n uint64_t sharedID = SkSetFourByteTag('b', 'm', 'a', 'p');\n return (sharedID << 32) | bitmapGenID;\n}\n\nvoid SkNotifyBitmapGenIDIsStale(uint32_t bitmapGenID) {\n SkResourceCache::PostPurgeSharedID(SkMakeResourceCacheSharedIDForBitmap(bitmapGenID));\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nSkBitmap::Allocator* SkBitmapCache::GetAllocator() {\n return SkResourceCache::GetAllocator();\n}\n\n\/**\n This function finds the bounds of the bitmap *within its pixelRef*.\n If the bitmap lacks a pixelRef, it will return an empty rect, since\n that doesn't make sense. This may be a useful enough function that\n it should be somewhere else (in SkBitmap?).\n *\/\nstatic SkIRect get_bounds_from_bitmap(const SkBitmap& bm) {\n if (!(bm.pixelRef())) {\n return SkIRect::MakeEmpty();\n }\n SkIPoint origin = bm.pixelRefOrigin();\n return SkIRect::MakeXYWH(origin.fX, origin.fY, bm.width(), bm.height());\n}\n\n\/**\n * This function finds the bounds of the image. Today this is just the entire bounds,\n * but in the future we may support subsets within an image, in which case this should\n * return that subset (see get_bounds_from_bitmap).\n *\/\nstatic SkIRect get_bounds_from_image(const SkImage* image) {\n return SkIRect::MakeWH(image->width(), image->height());\n}\n\nSkBitmapCacheDesc SkBitmapCacheDesc::Make(const SkBitmap& bm, int width, int height) {\n SkBitmapCacheDesc desc;\n desc.fImageID = bm.getGenerationID();\n desc.fWidth = width;\n desc.fHeight = height;\n desc.fBounds = get_bounds_from_bitmap(bm);\n return desc;\n}\n\nSkBitmapCacheDesc SkBitmapCacheDesc::Make(const SkBitmap& bm) {\n return Make(bm, bm.width(), bm.height());\n}\n\nSkBitmapCacheDesc SkBitmapCacheDesc::Make(const SkImage* image, int width, int height) {\n SkBitmapCacheDesc desc;\n desc.fImageID = image->uniqueID();\n desc.fWidth = width;\n desc.fHeight = height;\n desc.fBounds = get_bounds_from_image(image);\n return desc;\n}\n\nSkBitmapCacheDesc SkBitmapCacheDesc::Make(const SkImage* image) {\n return Make(image, image->width(), image->height());\n}\n\nnamespace {\nstatic unsigned gBitmapKeyNamespaceLabel;\n\nstruct BitmapKey : public SkResourceCache::Key {\npublic:\n BitmapKey(uint32_t genID, int width, int height, const SkIRect& bounds)\n : fGenID(genID)\n , fWidth(width)\n , fHeight(height)\n , fBounds(bounds)\n {\n this->init(&gBitmapKeyNamespaceLabel, SkMakeResourceCacheSharedIDForBitmap(fGenID),\n sizeof(fGenID) + sizeof(fWidth) + sizeof(fHeight) + sizeof(fBounds));\n }\n\n BitmapKey(const SkBitmapCacheDesc& desc)\n : fGenID(desc.fImageID)\n , fWidth(desc.fWidth)\n , fHeight(desc.fHeight)\n , fBounds(desc.fBounds)\n {\n this->init(&gBitmapKeyNamespaceLabel, SkMakeResourceCacheSharedIDForBitmap(fGenID),\n sizeof(fGenID) + sizeof(fWidth) + sizeof(fHeight) + sizeof(fBounds));\n }\n\n void dump() const {\n SkDebugf(\"-- add [%d %d] %d [%d %d %d %d]\\n\", fWidth, fHeight, fGenID,\n fBounds.x(), fBounds.y(), fBounds.width(), fBounds.height());\n }\n\n const uint32_t fGenID;\n const int fWidth;\n const int fHeight;\n const SkIRect fBounds;\n};\n\nstruct BitmapRec : public SkResourceCache::Rec {\n BitmapRec(uint32_t genID, int width, int height, const SkIRect& bounds,\n const SkBitmap& result)\n : fKey(genID, width, height, bounds)\n , fBitmap(result)\n {\n#ifdef TRACE_NEW_BITMAP_CACHE_RECS\n fKey.dump();\n#endif\n }\n\n BitmapRec(const SkBitmapCacheDesc& desc, const SkBitmap& result)\n : fKey(desc)\n , fBitmap(result)\n {\n#ifdef TRACE_NEW_BITMAP_CACHE_RECS\n fKey.dump();\n#endif\n }\n\n const Key& getKey() const override { return fKey; }\n size_t bytesUsed() const override { return sizeof(fKey) + fBitmap.getSize(); }\n\n const char* getCategory() const override { return \"bitmap\"; }\n SkDiscardableMemory* diagnostic_only_getDiscardable() const override {\n return fBitmap.pixelRef()->diagnostic_only_getDiscardable();\n }\n\n static bool Finder(const SkResourceCache::Rec& baseRec, void* contextBitmap) {\n const BitmapRec& rec = static_cast<const BitmapRec&>(baseRec);\n SkBitmap* result = (SkBitmap*)contextBitmap;\n\n *result = rec.fBitmap;\n result->lockPixels();\n return SkToBool(result->getPixels());\n }\n\nprivate:\n BitmapKey fKey;\n SkBitmap fBitmap;\n};\n} \/\/ namespace\n\n#define CHECK_LOCAL(localCache, localName, globalName, ...) \\\n ((localCache) ? localCache->localName(__VA_ARGS__) : SkResourceCache::globalName(__VA_ARGS__))\n\nbool SkBitmapCache::FindWH(const SkBitmapCacheDesc& desc, SkBitmap* result,\n SkResourceCache* localCache) {\n if (0 == desc.fWidth || 0 == desc.fHeight) {\n \/\/ degenerate\n return false;\n }\n return CHECK_LOCAL(localCache, find, Find, BitmapKey(desc), BitmapRec::Finder, result);\n}\n\nbool SkBitmapCache::AddWH(const SkBitmapCacheDesc& desc, const SkBitmap& result,\n SkResourceCache* localCache) {\n if (0 == desc.fWidth || 0 == desc.fHeight) {\n \/\/ degenerate, and the key we use for mipmaps\n return false;\n }\n SkASSERT(result.isImmutable());\n BitmapRec* rec = new BitmapRec(desc, result);\n CHECK_LOCAL(localCache, add, Add, rec);\n return true;\n}\n\nbool SkBitmapCache::Find(uint32_t genID, const SkIRect& subset, SkBitmap* result,\n SkResourceCache* localCache) {\n BitmapKey key(genID, SK_Scalar1, SK_Scalar1, subset);\n\n return CHECK_LOCAL(localCache, find, Find, key, BitmapRec::Finder, result);\n}\n\nbool SkBitmapCache::Add(SkPixelRef* pr, const SkIRect& subset, const SkBitmap& result,\n SkResourceCache* localCache) {\n SkASSERT(result.isImmutable());\n\n if (subset.isEmpty()\n || subset.top() < 0\n || subset.left() < 0\n || result.width() != subset.width()\n || result.height() != subset.height()) {\n return false;\n } else {\n BitmapRec* rec = new BitmapRec(pr->getGenerationID(), 1, 1, subset, result);\n\n CHECK_LOCAL(localCache, add, Add, rec);\n pr->notifyAddedToCache();\n return true;\n }\n}\n\nbool SkBitmapCache::Find(uint32_t genID, SkBitmap* result, SkResourceCache* localCache) {\n BitmapKey key(genID, SK_Scalar1, SK_Scalar1, SkIRect::MakeEmpty());\n\n return CHECK_LOCAL(localCache, find, Find, key, BitmapRec::Finder, result);\n}\n\nvoid SkBitmapCache::Add(uint32_t genID, const SkBitmap& result, SkResourceCache* localCache) {\n SkASSERT(result.isImmutable());\n\n BitmapRec* rec = new BitmapRec(genID, 1, 1, SkIRect::MakeEmpty(), result);\n\n CHECK_LOCAL(localCache, add, Add, rec);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nnamespace {\nstatic unsigned gMipMapKeyNamespaceLabel;\n\nstruct MipMapKey : public SkResourceCache::Key {\npublic:\n MipMapKey(uint32_t genID, SkSourceGammaTreatment treatment, const SkIRect& bounds)\n : fGenID(genID), fSrcGammaTreatment(static_cast<uint32_t>(treatment)), fBounds(bounds)\n {\n this->init(&gMipMapKeyNamespaceLabel, SkMakeResourceCacheSharedIDForBitmap(genID),\n sizeof(fGenID) + sizeof(fSrcGammaTreatment) + sizeof(fBounds));\n }\n\n uint32_t fGenID;\n uint32_t fSrcGammaTreatment;\n SkIRect fBounds;\n};\n\nstruct MipMapRec : public SkResourceCache::Rec {\n MipMapRec(const SkBitmap& src, SkSourceGammaTreatment treatment, const SkMipMap* result)\n : fKey(src.getGenerationID(), treatment, get_bounds_from_bitmap(src))\n , fMipMap(result)\n {\n fMipMap->attachToCacheAndRef();\n }\n\n virtual ~MipMapRec() {\n fMipMap->detachFromCacheAndUnref();\n }\n\n const Key& getKey() const override { return fKey; }\n size_t bytesUsed() const override { return sizeof(fKey) + fMipMap->size(); }\n const char* getCategory() const override { return \"mipmap\"; }\n SkDiscardableMemory* diagnostic_only_getDiscardable() const override {\n return fMipMap->diagnostic_only_getDiscardable();\n }\n\n static bool Finder(const SkResourceCache::Rec& baseRec, void* contextMip) {\n const MipMapRec& rec = static_cast<const MipMapRec&>(baseRec);\n const SkMipMap* mm = SkRef(rec.fMipMap);\n \/\/ the call to ref() above triggers a \"lock\" in the case of discardable memory,\n \/\/ which means we can now check for null (in case the lock failed).\n if (nullptr == mm->data()) {\n mm->unref(); \/\/ balance our call to ref()\n return false;\n }\n \/\/ the call must call unref() when they are done.\n *(const SkMipMap**)contextMip = mm;\n return true;\n }\n\nprivate:\n MipMapKey fKey;\n const SkMipMap* fMipMap;\n};\n}\n\nconst SkMipMap* SkMipMapCache::FindAndRef(const SkBitmapCacheDesc& desc,\n SkSourceGammaTreatment treatment,\n SkResourceCache* localCache) {\n \/\/ Note: we ignore width\/height from desc, just need id and bounds\n MipMapKey key(desc.fImageID, treatment, desc.fBounds);\n const SkMipMap* result;\n\n if (!CHECK_LOCAL(localCache, find, Find, key, MipMapRec::Finder, &result)) {\n result = nullptr;\n }\n return result;\n}\n\nstatic SkResourceCache::DiscardableFactory get_fact(SkResourceCache* localCache) {\n return localCache ? localCache->GetDiscardableFactory()\n : SkResourceCache::GetDiscardableFactory();\n}\n\nconst SkMipMap* SkMipMapCache::AddAndRef(const SkBitmap& src, SkSourceGammaTreatment treatment,\n SkResourceCache* localCache) {\n SkMipMap* mipmap = SkMipMap::Build(src, treatment, get_fact(localCache));\n if (mipmap) {\n MipMapRec* rec = new MipMapRec(src, treatment, mipmap);\n CHECK_LOCAL(localCache, add, Add, rec);\n src.pixelRef()->notifyAddedToCache();\n }\n return mipmap;\n}\n<commit_msg>minor simplification: use SkBitmapCacheDesc<commit_after>\/*\n * Copyright 2014 Google Inc.\n *\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n *\/\n\n#include \"SkBitmapCache.h\"\n#include \"SkImage.h\"\n#include \"SkResourceCache.h\"\n#include \"SkMipMap.h\"\n#include \"SkPixelRef.h\"\n#include \"SkRect.h\"\n\n\/**\n * Use this for bitmapcache and mipmapcache entries.\n *\/\nuint64_t SkMakeResourceCacheSharedIDForBitmap(uint32_t bitmapGenID) {\n uint64_t sharedID = SkSetFourByteTag('b', 'm', 'a', 'p');\n return (sharedID << 32) | bitmapGenID;\n}\n\nvoid SkNotifyBitmapGenIDIsStale(uint32_t bitmapGenID) {\n SkResourceCache::PostPurgeSharedID(SkMakeResourceCacheSharedIDForBitmap(bitmapGenID));\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nSkBitmap::Allocator* SkBitmapCache::GetAllocator() {\n return SkResourceCache::GetAllocator();\n}\n\n\/**\n This function finds the bounds of the bitmap *within its pixelRef*.\n If the bitmap lacks a pixelRef, it will return an empty rect, since\n that doesn't make sense. This may be a useful enough function that\n it should be somewhere else (in SkBitmap?).\n *\/\nstatic SkIRect get_bounds_from_bitmap(const SkBitmap& bm) {\n if (!(bm.pixelRef())) {\n return SkIRect::MakeEmpty();\n }\n SkIPoint origin = bm.pixelRefOrigin();\n return SkIRect::MakeXYWH(origin.fX, origin.fY, bm.width(), bm.height());\n}\n\n\/**\n * This function finds the bounds of the image. Today this is just the entire bounds,\n * but in the future we may support subsets within an image, in which case this should\n * return that subset (see get_bounds_from_bitmap).\n *\/\nstatic SkIRect get_bounds_from_image(const SkImage* image) {\n return SkIRect::MakeWH(image->width(), image->height());\n}\n\nSkBitmapCacheDesc SkBitmapCacheDesc::Make(const SkBitmap& bm, int width, int height) {\n return { bm.getGenerationID(), width, height, get_bounds_from_bitmap(bm) };\n}\n\nSkBitmapCacheDesc SkBitmapCacheDesc::Make(const SkBitmap& bm) {\n return Make(bm, bm.width(), bm.height());\n}\n\nSkBitmapCacheDesc SkBitmapCacheDesc::Make(const SkImage* image, int width, int height) {\n return { image->uniqueID(), width, height, get_bounds_from_image(image) };\n}\n\nSkBitmapCacheDesc SkBitmapCacheDesc::Make(const SkImage* image) {\n return Make(image, image->width(), image->height());\n}\n\nnamespace {\nstatic unsigned gBitmapKeyNamespaceLabel;\n\nstruct BitmapKey : public SkResourceCache::Key {\npublic:\n BitmapKey(uint32_t genID, int width, int height, const SkIRect& bounds)\n : fDesc({ genID, width, height, bounds })\n {\n this->init(&gBitmapKeyNamespaceLabel, SkMakeResourceCacheSharedIDForBitmap(fDesc.fImageID),\n sizeof(fDesc));\n }\n\n BitmapKey(const SkBitmapCacheDesc& desc) : fDesc(desc) {\n this->init(&gBitmapKeyNamespaceLabel, SkMakeResourceCacheSharedIDForBitmap(fDesc.fImageID),\n sizeof(fDesc));\n }\n\n void dump() const {\n SkDebugf(\"-- add [%d %d] %d [%d %d %d %d]\\n\", fDesc.fWidth, fDesc.fHeight, fDesc.fImageID,\n fDesc.fBounds.x(), fDesc.fBounds.y(), fDesc.fBounds.width(), fDesc.fBounds.height());\n }\n\n const SkBitmapCacheDesc fDesc;\n};\n\nstruct BitmapRec : public SkResourceCache::Rec {\n BitmapRec(uint32_t genID, int width, int height, const SkIRect& bounds, const SkBitmap& result)\n : fKey(genID, width, height, bounds)\n , fBitmap(result)\n {\n#ifdef TRACE_NEW_BITMAP_CACHE_RECS\n fKey.dump();\n#endif\n }\n\n BitmapRec(const SkBitmapCacheDesc& desc, const SkBitmap& result)\n : fKey(desc)\n , fBitmap(result)\n {\n#ifdef TRACE_NEW_BITMAP_CACHE_RECS\n fKey.dump();\n#endif\n }\n\n const Key& getKey() const override { return fKey; }\n size_t bytesUsed() const override { return sizeof(fKey) + fBitmap.getSize(); }\n\n const char* getCategory() const override { return \"bitmap\"; }\n SkDiscardableMemory* diagnostic_only_getDiscardable() const override {\n return fBitmap.pixelRef()->diagnostic_only_getDiscardable();\n }\n\n static bool Finder(const SkResourceCache::Rec& baseRec, void* contextBitmap) {\n const BitmapRec& rec = static_cast<const BitmapRec&>(baseRec);\n SkBitmap* result = (SkBitmap*)contextBitmap;\n\n *result = rec.fBitmap;\n result->lockPixels();\n return SkToBool(result->getPixels());\n }\n\nprivate:\n BitmapKey fKey;\n SkBitmap fBitmap;\n};\n} \/\/ namespace\n\n#define CHECK_LOCAL(localCache, localName, globalName, ...) \\\n ((localCache) ? localCache->localName(__VA_ARGS__) : SkResourceCache::globalName(__VA_ARGS__))\n\nbool SkBitmapCache::FindWH(const SkBitmapCacheDesc& desc, SkBitmap* result,\n SkResourceCache* localCache) {\n if (0 == desc.fWidth || 0 == desc.fHeight) {\n \/\/ degenerate\n return false;\n }\n return CHECK_LOCAL(localCache, find, Find, BitmapKey(desc), BitmapRec::Finder, result);\n}\n\nbool SkBitmapCache::AddWH(const SkBitmapCacheDesc& desc, const SkBitmap& result,\n SkResourceCache* localCache) {\n if (0 == desc.fWidth || 0 == desc.fHeight) {\n \/\/ degenerate, and the key we use for mipmaps\n return false;\n }\n SkASSERT(result.isImmutable());\n BitmapRec* rec = new BitmapRec(desc, result);\n CHECK_LOCAL(localCache, add, Add, rec);\n return true;\n}\n\nbool SkBitmapCache::Find(uint32_t genID, const SkIRect& subset, SkBitmap* result,\n SkResourceCache* localCache) {\n BitmapKey key(genID, SK_Scalar1, SK_Scalar1, subset);\n\n return CHECK_LOCAL(localCache, find, Find, key, BitmapRec::Finder, result);\n}\n\nbool SkBitmapCache::Add(SkPixelRef* pr, const SkIRect& subset, const SkBitmap& result,\n SkResourceCache* localCache) {\n SkASSERT(result.isImmutable());\n\n if (subset.isEmpty()\n || subset.top() < 0\n || subset.left() < 0\n || result.width() != subset.width()\n || result.height() != subset.height()) {\n return false;\n } else {\n BitmapRec* rec = new BitmapRec(pr->getGenerationID(), 1, 1, subset, result);\n\n CHECK_LOCAL(localCache, add, Add, rec);\n pr->notifyAddedToCache();\n return true;\n }\n}\n\nbool SkBitmapCache::Find(uint32_t genID, SkBitmap* result, SkResourceCache* localCache) {\n BitmapKey key(genID, SK_Scalar1, SK_Scalar1, SkIRect::MakeEmpty());\n\n return CHECK_LOCAL(localCache, find, Find, key, BitmapRec::Finder, result);\n}\n\nvoid SkBitmapCache::Add(uint32_t genID, const SkBitmap& result, SkResourceCache* localCache) {\n SkASSERT(result.isImmutable());\n\n BitmapRec* rec = new BitmapRec(genID, 1, 1, SkIRect::MakeEmpty(), result);\n\n CHECK_LOCAL(localCache, add, Add, rec);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nnamespace {\nstatic unsigned gMipMapKeyNamespaceLabel;\n\nstruct MipMapKey : public SkResourceCache::Key {\npublic:\n MipMapKey(uint32_t genID, SkSourceGammaTreatment treatment, const SkIRect& bounds)\n : fGenID(genID), fSrcGammaTreatment(static_cast<uint32_t>(treatment)), fBounds(bounds)\n {\n this->init(&gMipMapKeyNamespaceLabel, SkMakeResourceCacheSharedIDForBitmap(genID),\n sizeof(fGenID) + sizeof(fSrcGammaTreatment) + sizeof(fBounds));\n }\n\n uint32_t fGenID;\n uint32_t fSrcGammaTreatment;\n SkIRect fBounds;\n};\n\nstruct MipMapRec : public SkResourceCache::Rec {\n MipMapRec(const SkBitmap& src, SkSourceGammaTreatment treatment, const SkMipMap* result)\n : fKey(src.getGenerationID(), treatment, get_bounds_from_bitmap(src))\n , fMipMap(result)\n {\n fMipMap->attachToCacheAndRef();\n }\n\n virtual ~MipMapRec() {\n fMipMap->detachFromCacheAndUnref();\n }\n\n const Key& getKey() const override { return fKey; }\n size_t bytesUsed() const override { return sizeof(fKey) + fMipMap->size(); }\n const char* getCategory() const override { return \"mipmap\"; }\n SkDiscardableMemory* diagnostic_only_getDiscardable() const override {\n return fMipMap->diagnostic_only_getDiscardable();\n }\n\n static bool Finder(const SkResourceCache::Rec& baseRec, void* contextMip) {\n const MipMapRec& rec = static_cast<const MipMapRec&>(baseRec);\n const SkMipMap* mm = SkRef(rec.fMipMap);\n \/\/ the call to ref() above triggers a \"lock\" in the case of discardable memory,\n \/\/ which means we can now check for null (in case the lock failed).\n if (nullptr == mm->data()) {\n mm->unref(); \/\/ balance our call to ref()\n return false;\n }\n \/\/ the call must call unref() when they are done.\n *(const SkMipMap**)contextMip = mm;\n return true;\n }\n\nprivate:\n MipMapKey fKey;\n const SkMipMap* fMipMap;\n};\n}\n\nconst SkMipMap* SkMipMapCache::FindAndRef(const SkBitmapCacheDesc& desc,\n SkSourceGammaTreatment treatment,\n SkResourceCache* localCache) {\n \/\/ Note: we ignore width\/height from desc, just need id and bounds\n MipMapKey key(desc.fImageID, treatment, desc.fBounds);\n const SkMipMap* result;\n\n if (!CHECK_LOCAL(localCache, find, Find, key, MipMapRec::Finder, &result)) {\n result = nullptr;\n }\n return result;\n}\n\nstatic SkResourceCache::DiscardableFactory get_fact(SkResourceCache* localCache) {\n return localCache ? localCache->GetDiscardableFactory()\n : SkResourceCache::GetDiscardableFactory();\n}\n\nconst SkMipMap* SkMipMapCache::AddAndRef(const SkBitmap& src, SkSourceGammaTreatment treatment,\n SkResourceCache* localCache) {\n SkMipMap* mipmap = SkMipMap::Build(src, treatment, get_fact(localCache));\n if (mipmap) {\n MipMapRec* rec = new MipMapRec(src, treatment, mipmap);\n CHECK_LOCAL(localCache, add, Add, rec);\n src.pixelRef()->notifyAddedToCache();\n }\n return mipmap;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"config.hpp\"\n#include \"vfs.hpp\"\n#include <iostream>\n#include <fstream>\n\/\/#include <streambuf>\n#include <sstream>\n\n#ifdef PLATFORM_WINDOWS\n#include <windows.h>\n#include <Winerror.h>\n#elif defined(PLATFORM_OSX)\n#include <mach-o\/dyld.h>\n#else\n#include <unistd.h>\n#include <linux\/limits.h>\n#endif\n\nstatic std::string basePath;\nstatic std::string homePath;\n#if OSX_APP_BUNDLE\nstatic std::string appPath;\n#endif\n\nttvfs::Root VFS;\n\nnamespace MgCore\n{\n std::string read_raw_file(std::string filename)\n {\n std::ifstream in(filename, std::ios::in | std::ios_base::ate);\n if (in) {\n std::string contents;\n contents.resize(static_cast<unsigned int>(in.tellg()));\n in.seekg(0, std::ios::beg);\n in.read(&contents[0], contents.size());\n in.close();\n return contents;\n } else {\n return \"\";\n }\n }\n\n std::string read_file(std::string filename)\n {\n ttvfs::File *vf = VFS.GetFile( filename.c_str() );\n\n if ( vf && vf->open(\"r\") ) {\n std::string contents;\n contents.resize( static_cast<unsigned int>(vf->size()) );\n vf->read(&contents[0], contents.size());\n vf->close();\n return contents;\n } else {\n return \"\";\n }\n }\n \n bool getFileStream(std::string filename, std::istream &stream)\n {\n std::stringbuf contents( read_file( filename ) );\n stream.rdbuf( &contents );\n return stream.good();\n }\n\n std::string GetBasePath() \/\/ executable path\n {\n if ( basePath.empty() )\n {\n#if defined(PLATFORM_WINDOWS)\n char buffer[MAX_PATH];\/\/always use MAX_PATH for filepaths\n GetModuleFileName( NULL, buffer, sizeof(buffer) );\n\n basePath = buffer;\n\n#elif defined(PLATFORM_OSX)\n char path[8192];\n uint32_t size = sizeof(path);\n\n if ( _NSGetExecutablePath( path, &size ) < 0 )\n {\n return \"\";\n }\n\n basePath = path;\n\n#elif defined(PLATFORM_LINUX)\n char buff[PATH_MAX];\n ssize_t len = ::readlink(\"\/proc\/self\/exe\", buff, sizeof(buff)-1);\n if (len != -1) \n {\n buff[len] = '\\0';\n basePath = buff;\n } else\n basePath = \"\";\n#endif\n\n \/\/ remove executable name so we just have the path\n int pos = basePath.rfind( PATH_SEP );\n\n basePath = basePath.substr( 0, pos+1 );\n\n#if OSX_APP_BUNDLE\n appPath = basePath; \/\/ store full appPath\n\n \/\/ on osx we only want the path containing the app when checking BasePath\n pos = basePath.rfind( \"MacOS\" );\n\n if ( pos != std::string::npos )\n {\n basePath = basePath.substr( 0, pos+1 );\n\n pos = basePath.rfind( \"Contents\" );\n\n if ( pos != std::string::npos )\n {\n basePath = basePath.substr( 0, pos+1 );\n\n pos = basePath.rfind( APP_NAME );\n\n if ( pos != std::string::npos )\n basePath = basePath.substr( 0, pos );\n }\n }\n#endif\n }\n\n return basePath;\n }\n\n std::string GetHomePath() \/\/ home\/library path to store configs\n {\n#if defined(PLATFORM_WINDOWS)\n TCHAR szPath[MAX_PATH];\n FARPROC qSHGetFolderPath;\n HMODULE shfolder = LoadLibrary(\"shfolder.dll\");\n\n if(shfolder == NULL)\n return NULL;\n\n if( homePath.empty() )\n {\n qSHGetFolderPath = GetProcAddress(shfolder, \"SHGetFolderPathA\");\n if(qSHGetFolderPath == NULL)\n {\n FreeLibrary(shfolder);\n return NULL;\n }\n\n if( !SUCCEEDED( qSHGetFolderPath( NULL, CSIDL_APPDATA, NULL, 0, szPath ) ) )\n {\n FreeLibrary(shfolder);\n return NULL;\n }\n\n homePath = szPath;\n homePath += PATH_SEP;\n\n homePath += HOMEPATH_NAME;\n }\n\n FreeLibrary(shfolder);\n#else\n char *p;\n\n if( homePath.empty() )\n {\n\n if( ( p = getenv( \"HOME\" ) ) != NULL )\n {\n homePath = p ;\n homePath += PATH_SEP ;\n\n#if defined(PLATFORM_OSX)\n homePath += \"Library\/Application Support\/\";\n#endif\n\n homePath += HOMEPATH_NAME;\n }\n }\n#endif\n return homePath;\n }\n\n#if OSX_APP_BUNDLE\n std::string GetAppPath() \/\/ OSX get internal app path\n {\n return appPath;\n }\n#endif\n}\n<commit_msg>More windows fixes.<commit_after>#include \"config.hpp\"\n#include \"vfs.hpp\"\n#include <iostream>\n#include <fstream>\n\/\/#include <streambuf>\n#include <sstream>\n\n#ifdef PLATFORM_WINDOWS\n#include <windows.h>\n#include <Winerror.h>\n#elif defined(PLATFORM_OSX)\n#include <mach-o\/dyld.h>\n#else\n#include <unistd.h>\n#include <linux\/limits.h>\n#endif\n\nstatic std::string basePath;\nstatic std::string homePath;\n#if OSX_APP_BUNDLE\nstatic std::string appPath;\n#endif\n\nttvfs::Root VFS;\n\nnamespace MgCore\n{\n std::string read_raw_file(std::string filename)\n {\n std::ifstream in(filename, std::ios::in | std::ios_base::ate);\n if (in) {\n std::string contents;\n contents.resize(static_cast<unsigned int>(in.tellg()));\n in.seekg(0, std::ios::beg);\n in.read(&contents[0], contents.size());\n in.close();\n return contents;\n } else {\n return \"\";\n }\n }\n\n std::string read_file(std::string filename)\n {\n ttvfs::File *vf = VFS.GetFile( filename.c_str() );\n\n if ( vf && vf->open(\"r\") ) {\n std::string contents;\n contents.resize( static_cast<unsigned int>(vf->size()) );\n vf->read(&contents[0], contents.size());\n vf->close();\n return contents;\n } else {\n return \"\";\n }\n }\n \n bool getFileStream(std::string filename, std::istream &stream)\n {\n std::stringbuf contents( read_file( filename ) );\n stream.rdbuf( &contents );\n return stream.good();\n }\n\n std::string GetBasePath() \/\/ executable path\n {\n if ( basePath.empty() )\n {\n#if defined(PLATFORM_WINDOWS)\n char buffer[MAX_PATH];\/\/always use MAX_PATH for filepaths\n GetModuleFileName( NULL, buffer, sizeof(buffer) );\n\n basePath = buffer;\n\n#elif defined(PLATFORM_OSX)\n char path[8192];\n uint32_t size = sizeof(path);\n\n if ( _NSGetExecutablePath( path, &size ) < 0 )\n {\n return \"\";\n }\n\n basePath = path;\n\n#elif defined(PLATFORM_LINUX)\n char buff[PATH_MAX];\n ssize_t len = ::readlink(\"\/proc\/self\/exe\", buff, sizeof(buff)-1);\n if (len != -1) \n {\n buff[len] = '\\0';\n basePath = buff;\n } else\n basePath = \"\";\n#endif\n\n \/\/ remove executable name so we just have the path\n int pos = basePath.rfind( PATH_SEP );\n\n basePath = basePath.substr( 0, pos+1 );\n\n#if OSX_APP_BUNDLE\n appPath = basePath; \/\/ store full appPath\n\n \/\/ on osx we only want the path containing the app when checking BasePath\n pos = basePath.rfind( \"MacOS\" );\n\n if ( pos != std::string::npos )\n {\n basePath = basePath.substr( 0, pos+1 );\n\n pos = basePath.rfind( \"Contents\" );\n\n if ( pos != std::string::npos )\n {\n basePath = basePath.substr( 0, pos+1 );\n\n pos = basePath.rfind( APP_NAME );\n\n if ( pos != std::string::npos )\n basePath = basePath.substr( 0, pos );\n }\n }\n#endif\n }\n\n return basePath;\n }\n\n std::string GetHomePath() \/\/ home\/library path to store configs\n {\n#if defined(PLATFORM_WINDOWS)\n TCHAR szPath[MAX_PATH];\n\n if( homePath.empty() )\n {\n if( !SUCCEEDED( SHGetFolderPath( NULL, CSIDL_APPDATA, NULL, 0, szPath ) ) )\n {\n return NULL;\n }\n\n homePath = szPath;\n homePath += PATH_SEP;\n\n homePath += HOMEPATH_NAME;\n }\n#else\n char *p;\n\n if( homePath.empty() )\n {\n\n if( ( p = getenv( \"HOME\" ) ) != NULL )\n {\n homePath = p ;\n homePath += PATH_SEP ;\n\n#if defined(PLATFORM_OSX)\n homePath += \"Library\/Application Support\/\";\n#endif\n\n homePath += HOMEPATH_NAME;\n }\n }\n#endif\n return homePath;\n }\n\n#if OSX_APP_BUNDLE\n std::string GetAppPath() \/\/ OSX get internal app path\n {\n return appPath;\n }\n#endif\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\nCopyright 2014-2015 Adam Grandquist\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n *\/\n\/**\n * @author Adam Grandquist\n * @copyright Apache\n *\/\n\n#ifndef REQL_EXPR_HPP_\n#define REQL_EXPR_HPP_\n\n#include \".\/cpp\/new.hpp\"\n\n#include <algorithm>\n#include <map>\n#include <string>\n#include <vector>\n\nnamespace ReQL {\n\nclass Query;\n\nclass Expr {\npublic:\n bool operator<(const Expr &other) const;\n\n explicit Expr(const Expr &other);\n explicit Expr(Expr &&other);\n\n Expr &operator=(const Expr &other);\n Expr &operator=(Expr &&other);\n\n ReQL_Obj_t *data() const;\n\nprotected:\n Expr();\n explicit Expr(const ReQL_AST_Function &f, const std::vector<Query> &args, const std::map<std::string, Query> &kwargs);\n explicit Expr(const std::string &val);\n explicit Expr(const double &val);\n explicit Expr(const bool &val);\n explicit Expr(const std::vector<Query> &val);\n explicit Expr(const std::map<std::string, Query> &val);\n virtual void copy(const Expr &other);\n virtual void move(Expr &&other);\n\nprivate:\n ReQL p_query;\n ReQL_AST_Function p_func;\n std::vector<Expr> p_array;\n std::map<Expr, Expr> p_object;\n};\n\n} \/\/ namespace ReQL\n\n#endif \/\/ REQL_EXPR_HPP_\n<commit_msg>Remove virtual table from Expr class.<commit_after>\/*\nCopyright 2014-2015 Adam Grandquist\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n *\/\n\/**\n * @author Adam Grandquist\n * @copyright Apache\n *\/\n\n#ifndef REQL_EXPR_HPP_\n#define REQL_EXPR_HPP_\n\n#include \".\/cpp\/new.hpp\"\n\n#include <algorithm>\n#include <map>\n#include <string>\n#include <vector>\n\nnamespace ReQL {\n\nclass Query;\n\nclass Expr {\npublic:\n bool operator<(const Expr &other) const;\n\n explicit Expr(const Expr &other);\n explicit Expr(Expr &&other);\n\n Expr &operator=(const Expr &other);\n Expr &operator=(Expr &&other);\n\n ReQL_Obj_t *data() const;\n\nprotected:\n Expr();\n explicit Expr(const ReQL_AST_Function &f, const std::vector<Query> &args, const std::map<std::string, Query> &kwargs);\n explicit Expr(const std::string &val);\n explicit Expr(const double &val);\n explicit Expr(const bool &val);\n explicit Expr(const std::vector<Query> &val);\n explicit Expr(const std::map<std::string, Query> &val);\n void copy(const Expr &other);\n void move(Expr &&other);\n\nprivate:\n ReQL p_query;\n ReQL_AST_Function p_func;\n std::vector<Expr> p_array;\n std::map<Expr, Expr> p_object;\n};\n\n} \/\/ namespace ReQL\n\n#endif \/\/ REQL_EXPR_HPP_\n<|endoftext|>"} {"text":"<commit_before>\/**************************************************\n * Source Code for the Original Compiler for the\n * Programming Language Wake\n *\n * wake.cpp\n *\n * Licensed under the MIT license\n * See LICENSE.TXT for details\n *\n * Author: Michael Fairhurst\n * Revised By:\n *\n **************************************************\/\n\n#include <stdio.h>\n#include <iostream>\n#include <sstream>\n#include <fstream>\n\n#include \"tree.h\"\nextern \"C\" {\n\t#include \"node.h\"\n\t#include \"wake.tab.h\"\n\textern int yyparse();\n\textern Node* parsetree;\n\textern FILE *yyin;\n}\n\n#include \"error.h\"\n#include \"Parser.h\"\n#include \"Linker.h\"\n#include \"ParseTreeTraverser.h\"\n#include \"SemanticErrorPrinter.h\"\n#include \"LibraryLoader.h\"\n#include \"ObjectFileGenerator.h\"\n#include \"ObjectFileHeaderData.h\"\n#include \"ObjectFileHeaderRenderer.h\"\n#include \"CompilationExceptions.h\"\n#include \"OptionsParser.h\"\n#include \"EntryPointAnalyzer.h\"\n#include \"AddressAllocator.h\"\n#include \"TableFileWriter.h\"\n#include \"SimpleAddressTable.h\"\n#include \"ImportParseTreeTraverser.h\"\n#include \"ErrorTracker.h\"\n#include <boost\/filesystem.hpp>\n\nvoid writeTableFiles(std::string dirname, ClassSpaceSymbolTable& table) {\n\tvector<PropertySymbolTable*> tables = table.getDefinedClasses();\n\tfor(vector<PropertySymbolTable*>::iterator it = tables.begin(); it != tables.end(); ++it) {\n\t\tfstream file;\n\n\t\tstring filename = dirname;\n\t\tif(table.getModule().size()) {\n\t\t\tfilename += \"\/\" + table.getModule();\n\t\t\tboost::filesystem::create_directory(filename);\n\t\t}\n\t\tfilename += \"\/\" + (*it)->classname + \".table\";\n\n\t\tfile.open((filename).c_str(), ios::out | ios::binary);\n\t\tTableFileWriter writer;\n\t\twriter.write(file, *it);\n\t\tfile.close();\n\t}\n}\n\nvoid compileFile(Options* options) {\n\n\tif(options->compileFilename == \"\") {\n\t\tprintf(\"[ no file provided ]\\n\"); exit(1);\n\t}\n\n\tFILE *myfile = fopen(options->compileFilename.c_str(), \"r\");\n\terror_open_file(options->compileFilename.c_str());\n\n\tif (!myfile) {\n\t\tprintf(\"[ couldn't open file ]\\n\");\n\t\texit(2);\n\t}\n\n\tParser parser;\n\n\t\/\/ Parse the shit out of this\n\tif(parser.parse(myfile)) exit(3);\n\t\/\/parser.print();exit(0);\n\n\tClassSpaceSymbolTable table;\n\tErrorTracker errors;\n\tLibraryLoader loader;\n\tloader.loadStdLibToTable(&table);\n\tImportParseTreeTraverser importer;\n\terrors.pushContext(\"Import header\");\n\timporter.traverse(parser.getParseTree(), table, loader, errors, options->tabledir);\n\terrors.popContext();\n\n\tif(parser.getParseTree()->node_data.nodes[0]->node_type == NT_MODULE) {\n\t\ttable.setModule(parser.getParseTree()->node_data.nodes[0]->node_data.string);\n\t}\n\t\/\/ Now do all the semantic analysis\n\tParseTreeTraverser traverser(&table, errors);\n\ttraverser.traverse(parser.getParseTree());\n\n\tSemanticErrorPrinter printer;\n\n\tif(!traverser.passesForCompilation()) {\n\t\ttraverser.printErrors(printer);\n\t\texit(4);\n\t}\n\n\tif(options->table) {\n\t\twriteTableFiles(options->tabledir, table);\n\t\treturn;\n\t}\n\n\tbasic_ostringstream<char> object;\n\tObjectFileHeaderData header;\n\n\tObjectFileGenerator gen(object, &table, &header);\n\tgen.generate(parser.getParseTree());\n\n\tfstream file;\n\tObjectFileHeaderRenderer renderer;\n\n\tfile.open(options->outFilename.c_str(), ios::out);\n\trenderer.writeOut(file, &header);\n\tfile << object.str();\n\tfile.close();\n\n\twriteTableFiles(options->tabledir.c_str(), table);\n}\n\nint main(int argc, char** argv) {\n\tOptionsParser optionsparser;\n\tOptions options = optionsparser.parse(argc, argv);\n\tif(options.showVersion) {\n\t\tprintf(\"[ Wake ---- std compiler ]\\n\");\n\t\tprintf(\"[ v0.2.1 Michael Fairhurst ]\\n\");\n\t\texit(0);\n\t}\n\n\tif(options.showHelp) {\n\t\tprintf(\"usage: wake flags filename\\n\");\n\t\tprintf(\"flags: -o|--out file - compile to this file\\n\");\n\t\tprintf(\" -c|--mainclass class - begin execution with this file\\n\");\n\t\tprintf(\" -m|--mainemethod method - begin execution with this method\\n\");\n\t\tprintf(\" -v|--version - show version and exit\\n\");\n\t\tprintf(\" -h|--help - show help and exit\\n\");\n\t\tprintf(\" -i|--listmains - list compilable entrypoints\\n\");\n\t\tprintf(\" -l|--link - link compiled files into an executable\\n\");\n\t\tprintf(\" -t|--table - only generate table files\\n\");\n\t\tprintf(\" -d|--tabledir - dir for finding and creating .table files\\n\");\n\t\texit(0);\n\t}\n\n\tif(!options.link) compileFile(&options);\n\telse {\n\t\ttry {\n\t\t\tAddressAllocator classAllocator;\n\t\t\tAddressAllocator propAllocator;\n\t\t\tClassSpaceSymbolTable table;\n\t\t\tSimpleAddressTable classTable(classAllocator);\n\t\t\tSimpleAddressTable propTable(propAllocator);\n\t\t\tLinker linker(classTable, propTable);\n\t\t\tfor(std::vector<std::string>::iterator it = options.linkFilenames.begin(); it != options.linkFilenames.end(); ++it) {\n\t\t\t\tlinker.loadObject(*it);\n\t\t\t}\n\n\t\t\tLibraryLoader loader;\n\t\t\tloader.loadStdLibToTable(&table);\n\t\t\tlinker.loadTables(options.tabledir, table);\n\n\t\t\ttry {\n\t\t\t\ttable.assertNoNeedsAreCircular();\n\t\t\t} catch(SemanticError* e) {\n\t\t\t\te->token = NULL;\n\t\t\t\tSemanticErrorPrinter printer;\n\t\t\t\tprinter.print(e);\n\t\t\t\tdelete e;\n\t\t\t\treturn 1;\n\t\t\t}\n\n\t\t\tfstream file;\n\t\t\tfile.open(options.outFilename.c_str(), ios::out);\n\n\t\t\tlinker.write(file);\n\t\t\tlinker.writeDebugSymbols(file); \/\/ @todo make this optional\n\n\t\t\tEntryPointAnalyzer entrypointanalyzer;\n\t\t\tif(options.listMains) {\n\t\t\t\ttable.printEntryPoints(&entrypointanalyzer);\n\t\t\t\texit(0);\n\t\t\t} else {\n\t\t\t\tif(!entrypointanalyzer.checkFQClassMethodCanBeMain(options.mainclass, options.mainmethod, &table)) {\n\t\t\t\t\tprintf(\"Entry point %s.%s in not valid, cannot continue.\\nTry wake yourfile --listmains to get entry points\\n\", options.mainclass.c_str(), options.mainmethod.c_str());\n\t\t\t\t\texit(5);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tlinker.setMain(file, options.mainclass, options.mainmethod, table);\n\t\t} catch(SymbolNotFoundException* e) {\n\t\t\tcout << \"Missing symbol in object files at link time: \" << e->errormsg << endl;\n\t\t\tdelete e;\n\t\t}\n\n\t}\n\n}\n<commit_msg>Compilation option for printing recursive dependency info<commit_after>\/**************************************************\n * Source Code for the Original Compiler for the\n * Programming Language Wake\n *\n * wake.cpp\n *\n * Licensed under the MIT license\n * See LICENSE.TXT for details\n *\n * Author: Michael Fairhurst\n * Revised By:\n *\n **************************************************\/\n\n#include <stdio.h>\n#include <iostream>\n#include <sstream>\n#include <fstream>\n\n#include \"tree.h\"\nextern \"C\" {\n\t#include \"node.h\"\n\t#include \"wake.tab.h\"\n\textern int yyparse();\n\textern Node* parsetree;\n\textern FILE *yyin;\n}\n\n#include \"error.h\"\n#include \"Parser.h\"\n#include \"Linker.h\"\n#include \"ParseTreeTraverser.h\"\n#include \"SemanticErrorPrinter.h\"\n#include \"LibraryLoader.h\"\n#include \"ObjectFileGenerator.h\"\n#include \"ObjectFileHeaderData.h\"\n#include \"ObjectFileHeaderRenderer.h\"\n#include \"CompilationExceptions.h\"\n#include \"OptionsParser.h\"\n#include \"EntryPointAnalyzer.h\"\n#include \"AddressAllocator.h\"\n#include \"TableFileWriter.h\"\n#include \"SimpleAddressTable.h\"\n#include \"ImportParseTreeTraverser.h\"\n#include \"ErrorTracker.h\"\n#include <boost\/filesystem.hpp>\n#include <boost\/unordered_set.hpp>\nusing namespace boost;\n\nvoid writeTableFiles(std::string dirname, ClassSpaceSymbolTable& table) {\n\tvector<PropertySymbolTable*> tables = table.getDefinedClasses();\n\tfor(vector<PropertySymbolTable*>::iterator it = tables.begin(); it != tables.end(); ++it) {\n\t\tfstream file;\n\n\t\tstring filename = dirname;\n\t\tif(table.getModule().size()) {\n\t\t\tfilename += \"\/\" + table.getModule();\n\t\t\tboost::filesystem::create_directory(filename);\n\t\t}\n\t\tfilename += \"\/\" + (*it)->classname + \".table\";\n\n\t\tfile.open((filename).c_str(), ios::out | ios::binary);\n\t\tTableFileWriter writer;\n\t\twriter.write(file, *it);\n\t\tfile.close();\n\t}\n}\n\nvoid compileFile(Options* options) {\n\n\tif(options->compileFilename == \"\") {\n\t\tprintf(\"[ no file provided ]\\n\"); exit(1);\n\t}\n\n\tFILE *myfile = fopen(options->compileFilename.c_str(), \"r\");\n\terror_open_file(options->compileFilename.c_str());\n\n\tif (!myfile) {\n\t\tprintf(\"[ couldn't open file ]\\n\");\n\t\texit(2);\n\t}\n\n\tParser parser;\n\n\t\/\/ Parse the shit out of this\n\tif(parser.parse(myfile)) exit(3);\n\t\/\/parser.print();exit(0);\n\n\tClassSpaceSymbolTable table;\n\tErrorTracker errors;\n\tLibraryLoader loader;\n\tloader.loadStdLibToTable(&table);\n\tImportParseTreeTraverser importer;\n\terrors.pushContext(\"Import header\");\n\timporter.traverse(parser.getParseTree(), table, loader, errors, options->tabledir);\n\terrors.popContext();\n\n\tif(parser.getParseTree()->node_data.nodes[0]->node_type == NT_MODULE) {\n\t\ttable.setModule(parser.getParseTree()->node_data.nodes[0]->node_data.string);\n\t}\n\t\/\/ Now do all the semantic analysis\n\tParseTreeTraverser traverser(&table, errors);\n\ttraverser.traverse(parser.getParseTree());\n\n\tSemanticErrorPrinter printer;\n\n\tif(!traverser.passesForCompilation()) {\n\t\ttraverser.printErrors(printer);\n\t\texit(4);\n\t}\n\n\tif(options->table) {\n\t\twriteTableFiles(options->tabledir, table);\n\t\treturn;\n\t}\n\n\tbasic_ostringstream<char> object;\n\tObjectFileHeaderData header;\n\n\tObjectFileGenerator gen(object, &table, &header);\n\tgen.generate(parser.getParseTree());\n\n\tfstream file;\n\tObjectFileHeaderRenderer renderer;\n\n\tfile.open(options->outFilename.c_str(), ios::out);\n\trenderer.writeOut(file, &header);\n\tfile << object.str();\n\tfile.close();\n\n\twriteTableFiles(options->tabledir.c_str(), table);\n}\n\nvoid findRecursiveDeps(string module, string classname, map<pair<string, string>, vector<pair<string, string> > >& depInfoMap, unordered_set<pair<string, string> >& recursiveDeps) {\n\tif(recursiveDeps.find(pair<string, string>(module, classname)) != recursiveDeps.end()) {\n\t\treturn;\n\t}\n\n\trecursiveDeps.insert(pair<string, string>(module, classname));\n\n\tvector<pair<string, string> > importingClasses = depInfoMap[pair<string, string>(module, classname)];\n\n\tfor(vector<pair<string, string> >::iterator it = importingClasses.begin(); it != importingClasses.end(); ++it) {\n\t\tfindRecursiveDeps(it->first, it->second, depInfoMap, recursiveDeps);\n\t}\n}\n\nvoid gatherDependencyInfo(Options* options, string module, string classname, map<pair<string, string>, vector<pair<string, string> > >& depInfoMap, unordered_set<pair<string, string> >& allDeps) {\n\tboost::filesystem::path p(options->compileFilename);\n\tboost::filesystem::path dir = p.parent_path();\n\tdir \/= classname + \".wk\"; \/\/ sweet operator overloading!\n\tstring filename = dir.string();\n\n\tif(allDeps.count(pair<string, string>(module, classname))) {\n\t\treturn;\n\t}\n\n\tallDeps.insert(pair<string, string>(module, classname));\n\n\tvector<pair<string, string> > singleFileImports;\n\n\tFILE *myfile = fopen(filename.c_str(), \"r\");\n\n\tif (!myfile) {\n\t\tcerr << \"Warning: couldn't find dependency \" << filename << endl;\n\t\tcerr << \"It won't be searched for cyclical dependencies.\" << endl;\n\t\tcerr << \"Is it in a different source directory, or misnamed?\" << endl;\n\t\treturn;\n\t}\n\n\t{\n\t\tParser parser;\n\t\tif(parser.parse(myfile)) return;\n\n\t\tImportParseTreeTraverser importer;\n\t\tsingleFileImports = importer.gatherImports(parser.getParseTree());\n\t\tfclose(myfile);\n\t}\n\n\tfor(vector<pair<string, string> >::iterator it = singleFileImports.begin(); it != singleFileImports.end(); ++it) {\n\t\tif(depInfoMap.find(*it) == depInfoMap.end()) {\n\t\t\tvector<pair<string, string> > vec;\n\t\t\tvec.push_back(pair<string, string>(module, classname));\n\t\t\tdepInfoMap[*it] = vec;\n\t\t} else {\n\t\t\tdepInfoMap.find(*it)->second.push_back(pair<string, string>(module, classname));\n\t\t}\n\n\t\tif(it->first == module) {\n\t\t\tgatherDependencyInfo(options, it->first, it->second, depInfoMap, allDeps);\n\t\t} else {\n\t\t\tallDeps.insert(*it);\n\t\t}\n\t}\n}\n\nvoid printDependencies(Options* options) {\n\tvector<pair<string, string> > singleFileImports;\n\tunordered_set<pair<string, string> > allDeps;\n\tunordered_set<pair<string, string> > recursiveDeps;\n\tmap<pair<string, string>, vector<pair<string, string> > > depInfoMap;\n\tstring module;\n\tstring classname;\n\n\tif(options->compileFilename == \"\") {\n\t\tprintf(\"[ no file provided ]\\n\"); exit(1);\n\t}\n\n\tFILE *myfile = fopen(options->compileFilename.c_str(), \"r\");\n\n\tif (!myfile) {\n\t\tprintf(\"[ couldn't open file ]\\n\");\n\t\texit(2);\n\t}\n\n\t{\n\t\tParser parser;\n\t\tif(parser.parse(myfile)) return;\n\n\t\tNode* tree = parser.getParseTree();\n\t\tmodule = tree->node_data.nodes[0]->node_data.string;\n\n\t\ttree = tree->node_data.nodes[tree->subnodes - 1];\n\t\twhile(tree->node_type != NT_TYPEDATA) {\n\t\t\ttree = tree->node_data.nodes[0];\n\t\t}\n\n\t\tclassname = tree->node_data.pure_type->typedata._class.classname;\n\n\t\tImportParseTreeTraverser importer;\n\t\tsingleFileImports = importer.gatherImports(parser.getParseTree());\n\t\tfclose(myfile);\n\t}\n\n\tfor(vector<pair<string, string> >::iterator it = singleFileImports.begin(); it != singleFileImports.end(); ++it) {\n\t\tvector<pair<string, string> > vec;\n\t\tvec.push_back(pair<string, string>(module, classname));\n\t\tdepInfoMap[*it] = vec;\n\t}\n\n\tallDeps.insert(pair<string, string>(module, classname));\n\n\tfor(vector<pair<string, string> >::iterator it = singleFileImports.begin(); it != singleFileImports.end(); ++it)\n\tif(it->first == module) {\n\t\tgatherDependencyInfo(options, it->first, it->second, depInfoMap, allDeps);\n\t}\n\n\tif(depInfoMap.count(pair<string, string>(module, classname))) {\n\t\tfindRecursiveDeps(module, classname, depInfoMap, recursiveDeps);\n\t}\n\n\tfor(unordered_set<pair<string, string> >::iterator it = allDeps.begin(); it != allDeps.end(); ++it)\n\tif(it->first != module || it->second != classname) {\n\t\tif(recursiveDeps.count(*it)) {\n\t\t\tcout << it->first << \",\" << it->second << \",TRUE\" << endl;\n\t\t} else {\n\t\t\tcout << it->first << \",\" << it->second << \",FALSE\" << endl;\n\t\t}\n\t}\n}\n\nint main(int argc, char** argv) {\n\tOptionsParser optionsparser;\n\tOptions options = optionsparser.parse(argc, argv);\n\tif(options.showVersion) {\n\t\tprintf(\"[ Wake ---- std compiler ]\\n\");\n\t\tprintf(\"[ v0.2.1 Michael Fairhurst ]\\n\");\n\t\texit(0);\n\t}\n\n\tif(options.showHelp) {\n\t\tprintf(\"usage: wake flags filename\\n\");\n\t\tprintf(\"flags: -o|--out file - compile to this file\\n\");\n\t\tprintf(\" -c|--mainclass class - begin execution with this file\\n\");\n\t\tprintf(\" -m|--mainemethod method - begin execution with this method\\n\");\n\t\tprintf(\" -v|--version - show version and exit\\n\");\n\t\tprintf(\" -h|--help - show help and exit\\n\");\n\t\tprintf(\" -i|--listmains - list compilable entrypoints\\n\");\n\t\tprintf(\" -l|--link - link compiled files into an executable\\n\");\n\t\tprintf(\" -t|--table - only generate table files\\n\");\n\t\tprintf(\" -d|--tabledir - dir for finding and creating .table files\\n\");\n\t\tprintf(\" -e|--dependencies - print out dependency information instead of compiling\\n\");\n\t\texit(0);\n\t}\n\n\tif(!options.link) {\n\t\toptions.listDeps ? printDependencies(&options) : compileFile(&options);\n\t} else {\n\t\ttry {\n\t\t\tAddressAllocator classAllocator;\n\t\t\tAddressAllocator propAllocator;\n\t\t\tClassSpaceSymbolTable table;\n\t\t\tSimpleAddressTable classTable(classAllocator);\n\t\t\tSimpleAddressTable propTable(propAllocator);\n\t\t\tLinker linker(classTable, propTable);\n\t\t\tfor(std::vector<std::string>::iterator it = options.linkFilenames.begin(); it != options.linkFilenames.end(); ++it) {\n\t\t\t\tlinker.loadObject(*it);\n\t\t\t}\n\n\t\t\tLibraryLoader loader;\n\t\t\tloader.loadStdLibToTable(&table);\n\t\t\tlinker.loadTables(options.tabledir, table);\n\n\t\t\ttry {\n\t\t\t\ttable.assertNoNeedsAreCircular();\n\t\t\t} catch(SemanticError* e) {\n\t\t\t\te->token = NULL;\n\t\t\t\tSemanticErrorPrinter printer;\n\t\t\t\tprinter.print(e);\n\t\t\t\tdelete e;\n\t\t\t\treturn 1;\n\t\t\t}\n\n\t\t\tfstream file;\n\t\t\tfile.open(options.outFilename.c_str(), ios::out);\n\n\t\t\tlinker.write(file);\n\t\t\tlinker.writeDebugSymbols(file); \/\/ @todo make this optional\n\n\t\t\tEntryPointAnalyzer entrypointanalyzer;\n\t\t\tif(options.listMains) {\n\t\t\t\ttable.printEntryPoints(&entrypointanalyzer);\n\t\t\t\texit(0);\n\t\t\t} else {\n\t\t\t\tif(!entrypointanalyzer.checkFQClassMethodCanBeMain(options.mainclass, options.mainmethod, &table)) {\n\t\t\t\t\tprintf(\"Entry point %s.%s in not valid, cannot continue.\\nTry wake yourfile --listmains to get entry points\\n\", options.mainclass.c_str(), options.mainmethod.c_str());\n\t\t\t\t\texit(5);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tlinker.setMain(file, options.mainclass, options.mainmethod, table);\n\t\t} catch(SymbolNotFoundException* e) {\n\t\t\tcout << \"Missing symbol in object files at link time: \" << e->errormsg << endl;\n\t\t\tdelete e;\n\t\t}\n\n\t}\n\n}\n<|endoftext|>"} {"text":"<commit_before>#ifndef V_SMC_CORE_SAMPLER_HPP\n#define V_SMC_CORE_SAMPLER_HPP\n\n#include <vSMC\/internal\/common.hpp>\n#include <ostream>\n#include <map>\n#include <set>\n#include <string>\n\nnamespace vSMC {\n\n\/\/\/ \\brief SMC Sampler\n\/\/\/\n\/\/\/ \\tparam T State state type. Requiment:\n\/\/\/ \\li Consturctor: T (IntType N)\n\/\/\/ \\li Method: copy (IntType from, IntType to)\ntemplate <typename T>\nclass Sampler\n{\n public :\n\n \/\/\/ The type of initialization functor\n typedef internal::function<unsigned (Particle<T> &, void *)>\n initialize_type;\n\n \/\/\/ The type of move and mcmc functor\n typedef internal::function<unsigned (unsigned, Particle<T> &)>\n move_type;\n\n \/\/\/ The type of ESS history vector\n typedef std::vector<double> ess_type;\n\n \/\/\/ The type of resampling history vector\n typedef std::vector<bool> resampled_type;\n\n \/\/\/ The type of accept count history vector\n typedef std::vector<std::vector<unsigned> > accept_type;\n\n \/\/\/ The type of Monitor map\n typedef std::map<std::string, Monitor<T> > monitor_map_type;\n\n \/\/\/ \\brief Construct a sampler with given number of particles\n \/\/\/\n \/\/\/ \\param N The number of particles\n \/\/\/ \\param init The functor used to initialize the particles\n \/\/\/ \\param move The functor used to move the particles and weights\n \/\/\/ \\param scheme The resampling scheme. See ResampleScheme\n \/\/\/ \\param threshold The threshold for performing resampling\n \/\/\/ \\param seed The seed to the parallel RNG system\n explicit Sampler (\n typename Particle<T>::size_type N,\n const initialize_type &init = NULL,\n const move_type &move = NULL,\n ResampleScheme scheme = STRATIFIED,\n double threshold = 0.5,\n typename Particle<T>::seed_type seed = V_SMC_CRNG_SEED) :\n init_(init), move_(move),\n scheme_(scheme), threshold_(threshold),\n particle_(N, seed), iter_num_(0) {}\n\n \/\/\/ \\brief Size of the particle set\n \/\/\/\n \/\/\/ \\return The number of particles\n typename Particle<T>::size_type size () const\n {\n return particle_.size();\n }\n\n \/\/\/ \\brief The number of iterations recorded\n \/\/\/\n \/\/\/ \\return The number of iterations recorded so far (including the\n \/\/\/ initialization)\n unsigned iter_size () const\n {\n return ess_.size();\n }\n\n \/\/\/ \\brief Get the current resampling scheme\n \/\/\/\n \/\/\/ \\return The current resampling scheme\n ResampleScheme resample_scheme () const\n {\n return scheme_;\n }\n\n \/\/\/ \\brief Set new resampling scheme\n \/\/\/\n \/\/\/ \\param scheme The new scheme for resampling\n void resample_scheme (ResampleScheme scheme)\n {\n scheme_ = scheme;\n }\n\n \/\/\/ \\brief Get the current threshold\n \/\/\/\n \/\/\/ \\return The current threshold for resmapling\n double resample_threshold () const\n {\n return threshold_;\n }\n\n \/\/\/ \\brief Set new resampling threshold\n \/\/\/\n \/\/\/ \\param threshold The new threshold for resampling\n void resample_threshold (double threshold)\n {\n threshold_ = threshold;\n }\n\n \/\/\/ \\brief ESS history\n \/\/\/\n \/\/\/ \\return A const reference to the history of ESS\n const ess_type &ess () const\n {\n return ess_;\n }\n\n \/\/\/ \\brief Resampling history\n \/\/\/\n \/\/\/ \\return A const reference to the history of resampling\n const resampled_type &resampled () const\n {\n return resampled_;\n }\n\n \/\/\/ \\brief Accept count history\n \/\/\/\n \/\/\/ \\return A const reference to the history of accept count\n const accept_type &accept () const\n {\n return accept_;\n }\n\n \/\/\/ \\brief Read and write access to the particle set\n \/\/\/\n \/\/\/ \\return A reference to the latest particle set\n Particle<T> &particle ()\n {\n return particle_;\n }\n\n \/\/\/ \\brief Read only access to the particle set\n \/\/\/\n \/\/\/ \\return A const reference to the latest particle set.\n const Particle<T> &particle () const\n {\n return particle_;\n }\n\n \/\/\/ \\brief Replace initialization functor\n \/\/\/\n \/\/\/ \\param new_init New Initialization functor\n void init (const initialize_type &new_init)\n {\n init_ = new_init;\n }\n\n \/\/\/ \\brief Replace iteration functor\n \/\/\/\n \/\/\/ \\param new_move New Move functor\n void move (const move_type &new_move)\n {\n move_ = new_move;\n }\n\n \/\/\/ \\brief Replace iteration functor\n \/\/\/\n \/\/\/ \\param new_mcmc New MCMC Move functor\n void mcmc (const move_type &new_mcmc)\n {\n mcmc_.push_back(new_mcmc);\n }\n\n \/\/\/ \\brief Clear all MCMC moves\n void clear_mcmc ()\n {\n mcmc_.clear();\n }\n\n \/\/\/ \\brief Initialize the particle set\n \/\/\/\n \/\/\/ \\param param Additional parameters passed to the initialization\n \/\/\/ functor\n void initialize (void *param = NULL)\n {\n ess_.clear();\n resampled_.clear();\n accept_.clear();\n path_.clear();\n\n for (typename monitor_map_type::iterator\n m = monitor_.begin(); m != monitor_.end(); ++m)\n m->second.clear();\n\n iter_num_ = 0;\n if (bool(init_)) {\n accept_.push_back(\n std::vector<unsigned>(1, init_(particle_, param)));\n }\n#ifndef NDEBUG\n else {\n std::cerr << \"vSMC Warning:\" << std::endl;\n std::cerr << \"\\tSampler::initiliaize\" << std::endl;\n std::cerr\n << \"\\tAttempt Initialization without a callable object\"\n << std::endl;\n }\n#endif\n post_move();\n particle_.reset_zconst();\n }\n\n \/\/\/ \\brief Perform iteration\n void iterate ()\n {\n ++iter_num_;\n std::vector<unsigned> acc;\n if (bool(move_)) {\n acc.push_back(move_(iter_num_, particle_));\n }\n#ifndef V_SMC_NDEBUG\n else {\n std::cerr << \"vSMC Warning:\" << std::endl;\n std::cerr << \"\\tSampler::iterate\" << std::endl;\n std::cerr\n << \"\\tAttempt Move without a callable object\"\n << std::endl;\n }\n#endif \/\/ V_SMC_NDEBUG\n for (typename std::vector<move_type>::iterator\n m = mcmc_.begin(); m != mcmc_.end(); ++m) {\n if (bool(*m)) {\n acc.push_back((*m)(iter_num_, particle_));\n }\n#ifndef V_SMC_NDEBUG\n else {\n std::cerr << \"vSMC Warning:\" << std::endl;\n std::cerr << \"\\tSampler::iterate\" << std::endl;\n std::cerr\n << \"\\tAttempt MCMC without a callable object\"\n << std::endl;\n }\n#endif \/\/ V_SMC_NDEBUG\n }\n accept_.push_back(acc);\n post_move();\n }\n\n \/\/\/ \\brief Perform iteration\n \/\/\/\n \/\/\/ \\param n The number of iterations to be performed\n void iterate (unsigned n)\n {\n for (unsigned i = 0; i != n; ++i)\n iterate();\n }\n\n \/\/\/ \\brief Add a monitor with an evaluation functor\n \/\/\/\n \/\/\/ \\param name The name of the monitor\n \/\/\/ \\param dim The dimension of the monitor, i.e., the number of variables\n \/\/\/ \\param eval The functor used to directly evaluate the results\n \/\/\/ \\param direct Whether or not eval return the integrands or the final\n void monitor (const std::string &name, unsigned dim,\n const typename Monitor<T>::eval_type &eval, bool direct = false)\n {\n monitor_.insert(std::make_pair(name, Monitor<T>(dim, eval, direct)));\n monitor_name_.insert(name);\n }\n\n \/\/\/ \\brief Read only access to a named monitor through iterator\n \/\/\/\n \/\/\/ \\param name The name of the monitor\n \/\/\/\n \/\/\/ \\return An const_iterator point to the monitor for the given name\n typename monitor_map_type::const_iterator monitor (\n const std::string &name) const\n {\n return monitor_.find(name);\n }\n\n \/\/\/ \\brief Read and write access to a named monitor through iterator\n \/\/\/\n \/\/\/ \\param name The name of the monitor\n \/\/\/\n \/\/\/ \\return An iterator point to the monitor for the given name\n typename monitor_map_type::iterator monitor (const std::string &name)\n {\n return monitor_.find(name);\n }\n\n \/\/\/ \\brief Read only access to all monitors\n \/\/\/\n \/\/\/ \\return A const reference to monitors\n const monitor_map_type &monitor () const\n {\n return monitor_;\n }\n\n \/\/\/ \\brief Read and write access to all monitors\n \/\/\/\n \/\/\/ \\return A reference to monitors\n monitor_map_type &monitor ()\n {\n return monitor_;\n }\n\n \/\/\/ \\brief Erase a named monitor\n \/\/\/\n \/\/\/ \\param name The name of the monitor\n void clear_monitor (const std::string &name)\n {\n monitor_.erase(name);\n monitor_name_.erase(name);\n }\n\n \/\/\/ \\brief Erase all monitors\n void clear_monitor ()\n {\n monitor_.clear();\n monitor_name_.clear();\n }\n\n \/\/\/ \\brief Read only access to the Path sampling monitor\n \/\/\/\n \/\/\/ \\return A const reference to the Path sampling monitor\n const Path<T> &path () const\n {\n return path_;\n }\n\n \/\/\/ \\brief Set the path sampling evaluation functor\n \/\/\/\n \/\/\/ \\param eval The functor used to compute the integrands or results\n \/\/\/ \\param direct Whether or not eval return the integrands or the final\n \/\/\/ results\n void path_sampling (const typename Path<T>::eval_type &eval,\n bool direct = false)\n {\n path_.eval(eval, direct);\n }\n\n \/\/\/ \\brief Path sampling estimate of normalizing constant\n \/\/\/\n \/\/\/ \\return The log ratio of normalizing constants\n double path_sampling () const\n {\n return path_.zconst();\n }\n\n \/\/\/ \\brief SMC estimate of normalizing constant\n \/\/\/\n \/\/\/ \\return The log of SMC normalizng constant estimate\n double zconst () const\n {\n return particle_.zconst();\n }\n\n \/\/\/ \\brief Print the history of the sampler\n \/\/\/\n \/\/\/ \\param os The ostream to which the contents are printed\n \/\/\/ \\param print_header Print header if \\b true\n template<typename CharT, typename Traits>\n void print (std::basic_ostream<CharT, Traits> &os = std::cout,\n bool print_header = true) const\n {\n const char sep = '\\t';\n\n \/\/ Accept count\n unsigned accd = 0;\n for (accept_type::const_iterator\n a = accept_.begin(); a != accept_.end(); ++a) {\n if (a->size() > accd)\n accd = a->size();\n }\n Eigen::MatrixXd acc(iter_size(), accd);\n acc.setConstant(0);\n double accdnorm = static_cast<double>(size());\n for (unsigned r = 0; r != iter_size(); ++r)\n for (unsigned c = 0; c != accept_[r].size(); ++c)\n acc(r, c) = accept_[r][c] \/ accdnorm;\n\n \/\/ Path sampling\n Eigen::MatrixXd pa(iter_size(), 3);\n Eigen::MatrixXi pmask(iter_size(), 1);\n pmask.setConstant(0);\n for (unsigned d = 0; d != path_.iter_size(); ++d) {\n unsigned pr = path_.index()[d];\n pa(pr, 0) = path_.integrand()[d];\n pa(pr, 1) = path_.width()[d];\n pa(pr, 2) = path_.grid()[d];\n pmask(pr) = 1;\n }\n\n \/\/ Monitors\n unsigned mond = 0;\n for (typename monitor_map_type::const_iterator\n m = monitor_.begin(); m != monitor_.end(); ++m) {\n mond += m->second.dim();\n }\n Eigen::MatrixXd mon(iter_size(), mond);\n Eigen::MatrixXi mmask(iter_size(), monitor_.size());\n mmask.setConstant(0);\n unsigned mc = 0;\n unsigned mn = 0;\n for (typename monitor_map_type::const_iterator\n m = monitor_.begin(); m != monitor_.end(); ++m) {\n unsigned md = m->second.dim();\n for (unsigned d = 0; d != m->second.iter_size(); ++d) {\n unsigned mr = m->second.index()[d];\n for (unsigned c = 0; c != md; ++c)\n mon(mr, c + mc) = m->second.record(c)[d];\n mmask(mr, mn) = 1;\n }\n mc += md;\n ++mn;\n }\n\n \/\/ Print header\n if (print_header) {\n os << \"Iter\" << sep << \"ESS\" << sep << \"ResSam\" << sep;\n if (accd == 1) {\n os << \"Accept\" << sep;\n } else {\n for (unsigned d = 0; d != accd; ++d)\n os << \"Accept.\" << d + 1 << sep;\n }\n os\n << \"Path.Integrand\" << sep\n << \"Path.Width\" << sep\n << \"Path.Grid\" << sep << \"\";\n for (typename monitor_map_type::const_iterator\n m = monitor_.begin(); m != monitor_.end(); ++m) {\n if (m->second.dim() == 1) {\n os << m->first << sep;\n } else {\n for (unsigned d = 0; d != m->second.dim(); ++d)\n os << m->first << '.' << d + 1 << sep;\n }\n }\n os << '\\n';\n }\n\n \/\/ Print data\n for (unsigned iter = 0; iter != iter_size(); ++iter) {\n os << iter << sep;\n os << ess_[iter] \/ size() << sep;\n os << resampled_[iter] << sep;\n os << acc.row(iter) << sep;\n if (pmask(iter))\n os << pa.row(iter) << sep;\n else\n os << '.' << sep << '.' << sep << '.' << sep;\n unsigned mc = 0;\n unsigned mn = 0;\n for (typename monitor_map_type::const_iterator\n m = monitor_.begin(); m != monitor_.end(); ++m) {\n unsigned md = m->second.dim();\n if (mmask(iter, mn)) {\n os << mon.block(iter, mc, 1, md) << sep;\n } else {\n for (unsigned m = 0; m != md; ++m)\n os << '.' << sep;\n }\n mc += md;\n ++mn;\n }\n os << '\\n';\n }\n }\n\n private :\n\n \/\/\/ Initialization and movement\n initialize_type init_;\n move_type move_;\n std::vector<move_type> mcmc_;\n\n \/\/\/ Resampling\n ResampleScheme scheme_;\n double threshold_;\n\n \/\/\/ Particle sets\n Particle<T> particle_;\n unsigned iter_num_;\n ess_type ess_;\n resampled_type resampled_;\n accept_type accept_;\n\n \/\/\/ Monte Carlo estimation by integration\n monitor_map_type monitor_;\n std::set<std::string> monitor_name_;\n\n \/\/\/ Path sampling\n Path<T> path_;\n\n void post_move ()\n {\n bool do_resample = particle_.ess() < threshold_ * size();\n if (do_resample)\n particle_.resample(scheme_);\n\n if (!path_.empty())\n path_.eval(iter_num_, particle_);\n\n for (typename monitor_map_type::iterator\n m = monitor_.begin(); m != monitor_.end(); ++m) {\n if (!m->second.empty())\n m->second.eval(iter_num_, particle_);\n }\n\n ess_.push_back(particle_.ess());\n resampled_.push_back(do_resample);\n particle_.resampled(resampled_.back());\n particle_.accept(accept_.back().back());\n }\n}; \/\/ class Sampler\n\n} \/\/ namespace vSMC\n\nnamespace std {\n\n\/\/\/ \\brief Print the sampler\n\/\/\/\n\/\/\/ \\param os The ostream to which the contents are printed\n\/\/\/ \\param sampler The sampler to be printed\n\/\/\/\n\/\/\/ \\note This is the same as <tt>sampler.print(os)<\/tt>\ntemplate<typename T, typename CharT, typename Traits>\nstd::basic_ostream<CharT, Traits> &operator<< (\n std::basic_ostream<CharT, Traits> &os, const vSMC::Sampler<T> &sampler)\n{\n sampler.print(os, true);\n return os;\n}\n\n} \/\/ namespace std\n\n#endif \/\/ V_SMC_CORE_SAMPLER_HPP\n<commit_msg>check edge cases of print<commit_after>#ifndef V_SMC_CORE_SAMPLER_HPP\n#define V_SMC_CORE_SAMPLER_HPP\n\n#include <vSMC\/internal\/common.hpp>\n#include <ostream>\n#include <map>\n#include <set>\n#include <string>\n\nnamespace vSMC {\n\n\/\/\/ \\brief SMC Sampler\n\/\/\/\n\/\/\/ \\tparam T State state type. Requiment:\n\/\/\/ \\li Consturctor: T (IntType N)\n\/\/\/ \\li Method: copy (IntType from, IntType to)\ntemplate <typename T>\nclass Sampler\n{\n public :\n\n \/\/\/ The type of initialization functor\n typedef internal::function<unsigned (Particle<T> &, void *)>\n initialize_type;\n\n \/\/\/ The type of move and mcmc functor\n typedef internal::function<unsigned (unsigned, Particle<T> &)>\n move_type;\n\n \/\/\/ The type of ESS history vector\n typedef std::vector<double> ess_type;\n\n \/\/\/ The type of resampling history vector\n typedef std::vector<bool> resampled_type;\n\n \/\/\/ The type of accept count history vector\n typedef std::vector<std::vector<unsigned> > accept_type;\n\n \/\/\/ The type of Monitor map\n typedef std::map<std::string, Monitor<T> > monitor_map_type;\n\n \/\/\/ \\brief Construct a sampler with given number of particles\n \/\/\/\n \/\/\/ \\param N The number of particles\n \/\/\/ \\param init The functor used to initialize the particles\n \/\/\/ \\param move The functor used to move the particles and weights\n \/\/\/ \\param scheme The resampling scheme. See ResampleScheme\n \/\/\/ \\param threshold The threshold for performing resampling\n \/\/\/ \\param seed The seed to the parallel RNG system\n explicit Sampler (\n typename Particle<T>::size_type N,\n const initialize_type &init = NULL,\n const move_type &move = NULL,\n ResampleScheme scheme = STRATIFIED,\n double threshold = 0.5,\n typename Particle<T>::seed_type seed = V_SMC_CRNG_SEED) :\n init_(init), move_(move),\n scheme_(scheme), threshold_(threshold),\n particle_(N, seed), iter_num_(0) {}\n\n \/\/\/ \\brief Size of the particle set\n \/\/\/\n \/\/\/ \\return The number of particles\n typename Particle<T>::size_type size () const\n {\n return particle_.size();\n }\n\n \/\/\/ \\brief The number of iterations recorded\n \/\/\/\n \/\/\/ \\return The number of iterations recorded so far (including the\n \/\/\/ initialization)\n unsigned iter_size () const\n {\n return ess_.size();\n }\n\n \/\/\/ \\brief Get the current resampling scheme\n \/\/\/\n \/\/\/ \\return The current resampling scheme\n ResampleScheme resample_scheme () const\n {\n return scheme_;\n }\n\n \/\/\/ \\brief Set new resampling scheme\n \/\/\/\n \/\/\/ \\param scheme The new scheme for resampling\n void resample_scheme (ResampleScheme scheme)\n {\n scheme_ = scheme;\n }\n\n \/\/\/ \\brief Get the current threshold\n \/\/\/\n \/\/\/ \\return The current threshold for resmapling\n double resample_threshold () const\n {\n return threshold_;\n }\n\n \/\/\/ \\brief Set new resampling threshold\n \/\/\/\n \/\/\/ \\param threshold The new threshold for resampling\n void resample_threshold (double threshold)\n {\n threshold_ = threshold;\n }\n\n \/\/\/ \\brief ESS history\n \/\/\/\n \/\/\/ \\return A const reference to the history of ESS\n const ess_type &ess () const\n {\n return ess_;\n }\n\n \/\/\/ \\brief Resampling history\n \/\/\/\n \/\/\/ \\return A const reference to the history of resampling\n const resampled_type &resampled () const\n {\n return resampled_;\n }\n\n \/\/\/ \\brief Accept count history\n \/\/\/\n \/\/\/ \\return A const reference to the history of accept count\n const accept_type &accept () const\n {\n return accept_;\n }\n\n \/\/\/ \\brief Read and write access to the particle set\n \/\/\/\n \/\/\/ \\return A reference to the latest particle set\n Particle<T> &particle ()\n {\n return particle_;\n }\n\n \/\/\/ \\brief Read only access to the particle set\n \/\/\/\n \/\/\/ \\return A const reference to the latest particle set.\n const Particle<T> &particle () const\n {\n return particle_;\n }\n\n \/\/\/ \\brief Replace initialization functor\n \/\/\/\n \/\/\/ \\param new_init New Initialization functor\n void init (const initialize_type &new_init)\n {\n init_ = new_init;\n }\n\n \/\/\/ \\brief Replace iteration functor\n \/\/\/\n \/\/\/ \\param new_move New Move functor\n void move (const move_type &new_move)\n {\n move_ = new_move;\n }\n\n \/\/\/ \\brief Replace iteration functor\n \/\/\/\n \/\/\/ \\param new_mcmc New MCMC Move functor\n void mcmc (const move_type &new_mcmc)\n {\n mcmc_.push_back(new_mcmc);\n }\n\n \/\/\/ \\brief Clear all MCMC moves\n void clear_mcmc ()\n {\n mcmc_.clear();\n }\n\n \/\/\/ \\brief Initialize the particle set\n \/\/\/\n \/\/\/ \\param param Additional parameters passed to the initialization\n \/\/\/ functor\n void initialize (void *param = NULL)\n {\n ess_.clear();\n resampled_.clear();\n accept_.clear();\n path_.clear();\n\n for (typename monitor_map_type::iterator\n m = monitor_.begin(); m != monitor_.end(); ++m)\n m->second.clear();\n\n iter_num_ = 0;\n if (bool(init_)) {\n accept_.push_back(\n std::vector<unsigned>(1, init_(particle_, param)));\n }\n#ifndef NDEBUG\n else {\n std::cerr << \"vSMC Warning:\" << std::endl;\n std::cerr << \"\\tSampler::initiliaize\" << std::endl;\n std::cerr\n << \"\\tAttempt Initialization without a callable object\"\n << std::endl;\n }\n#endif\n post_move();\n particle_.reset_zconst();\n }\n\n \/\/\/ \\brief Perform iteration\n void iterate ()\n {\n ++iter_num_;\n std::vector<unsigned> acc;\n if (bool(move_)) {\n acc.push_back(move_(iter_num_, particle_));\n }\n#ifndef V_SMC_NDEBUG\n else {\n std::cerr << \"vSMC Warning:\" << std::endl;\n std::cerr << \"\\tSampler::iterate\" << std::endl;\n std::cerr\n << \"\\tAttempt Move without a callable object\"\n << std::endl;\n }\n#endif \/\/ V_SMC_NDEBUG\n for (typename std::vector<move_type>::iterator\n m = mcmc_.begin(); m != mcmc_.end(); ++m) {\n if (bool(*m)) {\n acc.push_back((*m)(iter_num_, particle_));\n }\n#ifndef V_SMC_NDEBUG\n else {\n std::cerr << \"vSMC Warning:\" << std::endl;\n std::cerr << \"\\tSampler::iterate\" << std::endl;\n std::cerr\n << \"\\tAttempt MCMC without a callable object\"\n << std::endl;\n }\n#endif \/\/ V_SMC_NDEBUG\n }\n accept_.push_back(acc);\n post_move();\n }\n\n \/\/\/ \\brief Perform iteration\n \/\/\/\n \/\/\/ \\param n The number of iterations to be performed\n void iterate (unsigned n)\n {\n for (unsigned i = 0; i != n; ++i)\n iterate();\n }\n\n \/\/\/ \\brief Add a monitor with an evaluation functor\n \/\/\/\n \/\/\/ \\param name The name of the monitor\n \/\/\/ \\param dim The dimension of the monitor, i.e., the number of variables\n \/\/\/ \\param eval The functor used to directly evaluate the results\n \/\/\/ \\param direct Whether or not eval return the integrands or the final\n void monitor (const std::string &name, unsigned dim,\n const typename Monitor<T>::eval_type &eval, bool direct = false)\n {\n monitor_.insert(std::make_pair(name, Monitor<T>(dim, eval, direct)));\n monitor_name_.insert(name);\n }\n\n \/\/\/ \\brief Read only access to a named monitor through iterator\n \/\/\/\n \/\/\/ \\param name The name of the monitor\n \/\/\/\n \/\/\/ \\return An const_iterator point to the monitor for the given name\n typename monitor_map_type::const_iterator monitor (\n const std::string &name) const\n {\n return monitor_.find(name);\n }\n\n \/\/\/ \\brief Read and write access to a named monitor through iterator\n \/\/\/\n \/\/\/ \\param name The name of the monitor\n \/\/\/\n \/\/\/ \\return An iterator point to the monitor for the given name\n typename monitor_map_type::iterator monitor (const std::string &name)\n {\n return monitor_.find(name);\n }\n\n \/\/\/ \\brief Read only access to all monitors\n \/\/\/\n \/\/\/ \\return A const reference to monitors\n const monitor_map_type &monitor () const\n {\n return monitor_;\n }\n\n \/\/\/ \\brief Read and write access to all monitors\n \/\/\/\n \/\/\/ \\return A reference to monitors\n monitor_map_type &monitor ()\n {\n return monitor_;\n }\n\n \/\/\/ \\brief Erase a named monitor\n \/\/\/\n \/\/\/ \\param name The name of the monitor\n void clear_monitor (const std::string &name)\n {\n monitor_.erase(name);\n monitor_name_.erase(name);\n }\n\n \/\/\/ \\brief Erase all monitors\n void clear_monitor ()\n {\n monitor_.clear();\n monitor_name_.clear();\n }\n\n \/\/\/ \\brief Read only access to the Path sampling monitor\n \/\/\/\n \/\/\/ \\return A const reference to the Path sampling monitor\n const Path<T> &path () const\n {\n return path_;\n }\n\n \/\/\/ \\brief Set the path sampling evaluation functor\n \/\/\/\n \/\/\/ \\param eval The functor used to compute the integrands or results\n \/\/\/ \\param direct Whether or not eval return the integrands or the final\n \/\/\/ results\n void path_sampling (const typename Path<T>::eval_type &eval,\n bool direct = false)\n {\n path_.eval(eval, direct);\n }\n\n \/\/\/ \\brief Path sampling estimate of normalizing constant\n \/\/\/\n \/\/\/ \\return The log ratio of normalizing constants\n double path_sampling () const\n {\n return path_.zconst();\n }\n\n \/\/\/ \\brief SMC estimate of normalizing constant\n \/\/\/\n \/\/\/ \\return The log of SMC normalizng constant estimate\n double zconst () const\n {\n return particle_.zconst();\n }\n\n \/\/\/ \\brief Print the history of the sampler\n \/\/\/\n \/\/\/ \\param os The ostream to which the contents are printed\n \/\/\/ \\param print_header Print header if \\b true\n template<typename CharT, typename Traits>\n void print (std::basic_ostream<CharT, Traits> &os = std::cout,\n bool print_header = true) const\n {\n const char sep = '\\t';\n\n \/\/ Accept count\n Eigen::MatrixXd acc;\n unsigned accd = 0;\n for (accept_type::const_iterator\n a = accept_.begin(); a != accept_.end(); ++a) {\n if (a->size() > accd)\n accd = a->size();\n }\n bool print_accept = accd > 0 && iter_size() > 0;\n if (print_accept) {\n acc.resize(iter_size(), accd);\n acc.setConstant(0);\n double accdnorm = static_cast<double>(size());\n for (unsigned r = 0; r != iter_size(); ++r)\n for (unsigned c = 0; c != accept_[r].size(); ++c)\n acc(r, c) = accept_[r][c] \/ accdnorm;\n }\n\n \/\/ Path sampling\n Eigen::MatrixXd pa;\n Eigen::MatrixXi pmask;\n bool print_path = path_.iter_size() > 0 && iter_size() > 0;\n if (print_path) {\n pa.resize(iter_size(), 3);\n pmask.resize(iter_size(), 1);\n pmask.setConstant(0);\n for (unsigned d = 0; d != path_.iter_size(); ++d) {\n unsigned pr = path_.index()[d];\n pa(pr, 0) = path_.integrand()[d];\n pa(pr, 1) = path_.width()[d];\n pa(pr, 2) = path_.grid()[d];\n pmask(pr) = 1;\n }\n }\n\n \/\/ Monitors\n Eigen::MatrixXd mon;\n Eigen::MatrixXi mmask;\n unsigned mond = 0;\n for (typename monitor_map_type::const_iterator\n m = monitor_.begin(); m != monitor_.end(); ++m) {\n mond += m->second.dim();\n }\n bool print_monitor = mond > 0 && iter_size() > 0;\n if (print_monitor) {\n mon.resize(iter_size(), mond);\n mmask.resize(iter_size(), monitor_.size());\n mmask.setConstant(0);\n unsigned mc = 0;\n unsigned mn = 0;\n for (typename monitor_map_type::const_iterator\n m = monitor_.begin(); m != monitor_.end(); ++m) {\n unsigned md = m->second.dim();\n for (unsigned d = 0; d != m->second.iter_size(); ++d) {\n unsigned mr = m->second.index()[d];\n for (unsigned c = 0; c != md; ++c)\n mon(mr, c + mc) = m->second.record(c)[d];\n mmask(mr, mn) = 1;\n }\n mc += md;\n ++mn;\n }\n }\n\n \/\/ Print header\n if (print_header) {\n os << \"Iter\" << sep << \"ESS\" << sep << \"ResSam\" << sep;\n if (print_accept) {\n if (accd == 1) {\n os << \"Accept\" << sep;\n } else {\n for (unsigned d = 0; d != accd; ++d)\n os << \"Accept.\" << d + 1 << sep;\n }\n }\n if (print_path) {\n os\n << \"Path.Integrand\" << sep\n << \"Path.Width\" << sep\n << \"Path.Grid\" << sep << \"\";\n }\n if (print_monitor) {\n for (typename monitor_map_type::const_iterator\n m = monitor_.begin(); m != monitor_.end(); ++m) {\n if (m->second.dim() == 1) {\n os << m->first << sep;\n } else {\n for (unsigned d = 0; d != m->second.dim(); ++d)\n os << m->first << '.' << d + 1 << sep;\n }\n }\n }\n os << '\\n';\n }\n\n \/\/ Print data\n for (unsigned iter = 0; iter != iter_size(); ++iter) {\n os << iter << sep;\n os << ess_[iter] \/ size() << sep;\n os << resampled_[iter] << sep;\n if (print_accept)\n os << acc.row(iter) << sep;\n if (print_path) {\n if (pmask(iter))\n os << pa.row(iter) << sep;\n else\n os << '.' << sep << '.' << sep << '.' << sep;\n }\n if (print_monitor) {\n unsigned mc = 0;\n unsigned mn = 0;\n for (typename monitor_map_type::const_iterator\n m = monitor_.begin(); m != monitor_.end(); ++m) {\n unsigned md = m->second.dim();\n if (mmask(iter, mn)) {\n os << mon.block(iter, mc, 1, md) << sep;\n } else {\n for (unsigned m = 0; m != md; ++m)\n os << '.' << sep;\n }\n mc += md;\n ++mn;\n }\n }\n os << '\\n';\n }\n }\n\n private :\n\n \/\/\/ Initialization and movement\n initialize_type init_;\n move_type move_;\n std::vector<move_type> mcmc_;\n\n \/\/\/ Resampling\n ResampleScheme scheme_;\n double threshold_;\n\n \/\/\/ Particle sets\n Particle<T> particle_;\n unsigned iter_num_;\n ess_type ess_;\n resampled_type resampled_;\n accept_type accept_;\n\n \/\/\/ Monte Carlo estimation by integration\n monitor_map_type monitor_;\n std::set<std::string> monitor_name_;\n\n \/\/\/ Path sampling\n Path<T> path_;\n\n void post_move ()\n {\n bool do_resample = particle_.ess() < threshold_ * size();\n if (do_resample)\n particle_.resample(scheme_);\n\n if (!path_.empty())\n path_.eval(iter_num_, particle_);\n\n for (typename monitor_map_type::iterator\n m = monitor_.begin(); m != monitor_.end(); ++m) {\n if (!m->second.empty())\n m->second.eval(iter_num_, particle_);\n }\n\n ess_.push_back(particle_.ess());\n resampled_.push_back(do_resample);\n particle_.resampled(resampled_.back());\n particle_.accept(accept_.back().back());\n }\n}; \/\/ class Sampler\n\n} \/\/ namespace vSMC\n\nnamespace std {\n\n\/\/\/ \\brief Print the sampler\n\/\/\/\n\/\/\/ \\param os The ostream to which the contents are printed\n\/\/\/ \\param sampler The sampler to be printed\n\/\/\/\n\/\/\/ \\note This is the same as <tt>sampler.print(os)<\/tt>\ntemplate<typename T, typename CharT, typename Traits>\nstd::basic_ostream<CharT, Traits> &operator<< (\n std::basic_ostream<CharT, Traits> &os, const vSMC::Sampler<T> &sampler)\n{\n sampler.print(os, true);\n return os;\n}\n\n} \/\/ namespace std\n\n#endif \/\/ V_SMC_CORE_SAMPLER_HPP\n<|endoftext|>"} {"text":"<commit_before>\/*=========================================================================\n *\n * Copyright RTK Consortium\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0.txt\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *=========================================================================*\/\n\n#include \"rtkConjugateGradientConeBeamReconstructionFilter.h\"\n\nnamespace rtk\n{\n\ntemplate<>\nConjugateGradientConeBeamReconstructionFilter< itk::VectorImage<float, 3>, itk::Image<float, 3> >\n::ConjugateGradientConeBeamReconstructionFilter()\n{\n this->SetNumberOfRequiredInputs(3);\n\n \/\/ Set the default values of member parameters\n m_NumberOfIterations=3;\n m_MeasureExecutionTimes=false;\n\/\/ m_IterationCosts=false;\n\n m_Gamma = 0;\n m_Regularized = false;\n m_CudaConjugateGradient = true;\n m_DisableDisplacedDetectorFilter = false;\n\n \/\/ Create the filters\n#ifdef RTK_USE_CUDA\n m_DisplacedDetectorFilter = rtk::CudaDisplacedDetectorImageFilter::New();\n m_ConstantVolumeSource = rtk::CudaConstantVolumeSource::New();\n#else\n m_DisplacedDetectorFilter = DisplacedDetectorFilterType::New();\n m_ConstantVolumeSource = ConstantImageSourceType::New();\n#endif\n m_CGOperator = CGOperatorFilterType::New();\n\n m_MultiplyVolumeFilter = MultiplyFilterType::New();\n m_MatrixVectorMultiplyFilter = MatrixVectorMultiplyFilterType::New();\n m_MultiplyOutputFilter = MultiplyFilterType::New();\n\n \/\/ Set permanent parameters\n m_ConstantVolumeSource->SetConstant(0);\n m_DisplacedDetectorFilter->SetPadOnTruncatedSide(false);\n}\n\n\/\/template<>\n\/\/void\n\/\/ConjugateGradientConeBeamReconstructionFilter< itk::VectorImage<float, 3>, itk::Image<float, 3> >\n\/\/::SetSupportMask(const itk::Image<float, 3> *SupportMask)\n\/\/{\n\/\/ this->SetInput(\"SupportMask\", const_cast<itk::Image<float, 3>*>(SupportMask));\n\/\/}\n\n\/\/template<>\n\/\/typename itk::Image<float, 3>::ConstPointer\n\/\/ConjugateGradientConeBeamReconstructionFilter< itk::VectorImage<float, 3>, itk::Image<float, 3> >\n\/\/::GetSupportMask()\n\/\/{\n\/\/ return static_cast< const itk::Image<float, 3> * >\n\/\/ ( this->itk::ProcessObject::GetInput(\"SupportMask\") );\n\/\/}\n\ntemplate<>\nvoid\nConjugateGradientConeBeamReconstructionFilter< itk::VectorImage<float, 3>, itk::Image<float, 3> >\n::GenerateOutputInformation()\n{\n \/\/ Choose between cuda or non-cuda conjugate gradient filter\n m_ConjugateGradientFilter = ConjugateGradientFilterType::New();\n#ifdef RTK_USE_CUDA\n if (m_CudaConjugateGradient)\n m_ConjugateGradientFilter = rtk::CudaConjugateGradientImageFilter_3f::New();\n#endif\n m_ConjugateGradientFilter->SetA(m_CGOperator.GetPointer());\n\/\/ m_ConjugateGradientFilter->SetIterationCosts(m_IterationCosts);\n\n \/\/ Set runtime connections\n m_ConstantVolumeSource->SetInformationFromImage(this->GetInput(0));\n m_CGOperator->SetInput(1, this->GetInput(1));\n m_CGOperator->SetSupportMask(this->GetSupportMask());\n m_ConjugateGradientFilter->SetX(this->GetInput(0));\n m_DisplacedDetectorFilter->SetDisable(m_DisableDisplacedDetectorFilter);\n m_DisplacedDetectorFilter->SetInput(this->GetInput(2));\n\n \/\/ Links with the m_BackProjectionFilter should be set here and not\n \/\/ in the constructor, as m_BackProjectionFilter is set at runtime\n m_BackProjectionFilterForB->SetInput(0, m_ConstantVolumeSource->GetOutput());\n m_ConjugateGradientFilter->SetB(m_BackProjectionFilterForB->GetOutput());\n\n \/\/ Set the matrix vector multiply filter's inputs for multiplication\n \/\/ by the inverse covariance matrix (for GLS minimization)\n m_MatrixVectorMultiplyFilter->SetInput1(this->GetInput(1));\n m_MatrixVectorMultiplyFilter->SetInput2(m_DisplacedDetectorFilter->GetOutput());\n m_CGOperator->SetInput(2, m_DisplacedDetectorFilter->GetOutput());\n m_BackProjectionFilterForB->SetInput(1, m_MatrixVectorMultiplyFilter->GetOutput());\n\n \/\/ If a support mask is used, it serves as preconditioning weights\n if (this->GetSupportMask().IsNotNull())\n {\n \/\/ Multiply the volume by support mask, and pass it to the conjugate gradient operator\n m_MultiplyVolumeFilter->SetInput1(m_BackProjectionFilterForB->GetOutput());\n m_MultiplyVolumeFilter->SetInput2(this->GetSupportMask());\n m_CGOperator->SetSupportMask(this->GetSupportMask());\n m_ConjugateGradientFilter->SetB(m_MultiplyVolumeFilter->GetOutput());\n\n \/\/ Multiply the output by the support mask\n m_MultiplyOutputFilter->SetInput1(m_ConjugateGradientFilter->GetOutput());\n m_MultiplyOutputFilter->SetInput2(this->GetSupportMask());\n }\n\n \/\/ For the same reason, set geometry now\n m_CGOperator->SetGeometry(this->m_Geometry);\n m_BackProjectionFilterForB->SetGeometry(this->m_Geometry.GetPointer());\n m_DisplacedDetectorFilter->SetGeometry(this->m_Geometry);\n\n \/\/ Set runtime parameters\n m_ConjugateGradientFilter->SetNumberOfIterations(this->m_NumberOfIterations);\n m_CGOperator->SetGamma(m_Gamma);\n\n \/\/ Set memory management parameters\n m_MatrixVectorMultiplyFilter->ReleaseDataFlagOn();\n m_BackProjectionFilterForB->ReleaseDataFlagOn();\n if (this->GetSupportMask().IsNotNull())\n {\n m_MultiplyVolumeFilter->ReleaseDataFlagOn();\n m_MultiplyOutputFilter->ReleaseDataFlagOn();\n }\n\n \/\/ Have the last filter calculate its output information\n m_ConjugateGradientFilter->UpdateOutputInformation();\n\n \/\/ Copy it as the output information of the composite filter\n this->GetOutput()->CopyInformation( m_ConjugateGradientFilter->GetOutput() );\n}\n\ntemplate<>\nvoid\nConjugateGradientConeBeamReconstructionFilter< itk::VectorImage<float, 3>, itk::Image<float, 3> >\n::GenerateData()\n{\n itk::TimeProbe ConjugateGradientTimeProbe;\n\/\/ typename StatisticsImageFilterType::Pointer StatisticsImageFilterForC = StatisticsImageFilterType::New();\n\/\/ typename MultiplyFilterType::Pointer MultiplyFilterForC = MultiplyFilterType::New();\n\n\/\/ if (m_IterationCosts)\n\/\/ {\n\/\/ MultiplyFilterForC->SetInput(0,this->GetInput(1));\n\/\/ MultiplyFilterForC->SetInput(1,this->GetInput(2));\n\/\/ MultiplyFilterForC->Update();\n\/\/ MultiplyFilterForC->SetInput(1,MultiplyFilterForC->GetOutput());\n\/\/ MultiplyFilterForC->Update();\n\/\/ StatisticsImageFilterForC->SetInput(MultiplyFilterForC->GetOutput());\n\/\/ StatisticsImageFilterForC->Update();\n\/\/ m_ConjugateGradientFilter->SetC(0.5*StatisticsImageFilterForC->GetSum());\n\/\/ }\n\n if(m_MeasureExecutionTimes)\n {\n std::cout << \"Starting ConjugateGradient\" << std::endl;\n ConjugateGradientTimeProbe.Start();\n }\n\n m_ConjugateGradientFilter->Update();\n\n if (this->GetSupportMask())\n {\n m_MultiplyOutputFilter->Update();\n }\n\n if(m_MeasureExecutionTimes)\n {\n ConjugateGradientTimeProbe.Stop();\n std::cout << \"ConjugateGradient took \" << ConjugateGradientTimeProbe.GetTotal() << ' ' << ConjugateGradientTimeProbe.GetUnit() << std::endl;\n }\n\n if (this->GetSupportMask())\n {\n this->GraftOutput( m_MultiplyOutputFilter->GetOutput() );\n }\n else\n {\n this->GraftOutput( m_ConjugateGradientFilter->GetOutput() );\n }\n}\n\n} \/\/ end namespace rtk\n<commit_msg>Pass tikhonov regularization parameter to rtkReconstructionConjugateGradientOperator<commit_after>\/*=========================================================================\n *\n * Copyright RTK Consortium\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0.txt\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *=========================================================================*\/\n\n#include \"rtkConjugateGradientConeBeamReconstructionFilter.h\"\n\nnamespace rtk\n{\n\ntemplate<>\nConjugateGradientConeBeamReconstructionFilter< itk::VectorImage<float, 3>, itk::Image<float, 3> >\n::ConjugateGradientConeBeamReconstructionFilter()\n{\n this->SetNumberOfRequiredInputs(3);\n\n \/\/ Set the default values of member parameters\n m_NumberOfIterations=3;\n m_MeasureExecutionTimes=false;\n\/\/ m_IterationCosts=false;\n\n m_Gamma = 0;\n m_Regularized = false;\n m_CudaConjugateGradient = true;\n m_DisableDisplacedDetectorFilter = false;\n\n \/\/ Create the filters\n#ifdef RTK_USE_CUDA\n m_DisplacedDetectorFilter = rtk::CudaDisplacedDetectorImageFilter::New();\n m_ConstantVolumeSource = rtk::CudaConstantVolumeSource::New();\n#else\n m_DisplacedDetectorFilter = DisplacedDetectorFilterType::New();\n m_ConstantVolumeSource = ConstantImageSourceType::New();\n#endif\n m_CGOperator = CGOperatorFilterType::New();\n\n m_MultiplyVolumeFilter = MultiplyFilterType::New();\n m_MatrixVectorMultiplyFilter = MatrixVectorMultiplyFilterType::New();\n m_MultiplyOutputFilter = MultiplyFilterType::New();\n\n \/\/ Set permanent parameters\n m_ConstantVolumeSource->SetConstant(0);\n m_DisplacedDetectorFilter->SetPadOnTruncatedSide(false);\n}\n\n\/\/template<>\n\/\/void\n\/\/ConjugateGradientConeBeamReconstructionFilter< itk::VectorImage<float, 3>, itk::Image<float, 3> >\n\/\/::SetSupportMask(const itk::Image<float, 3> *SupportMask)\n\/\/{\n\/\/ this->SetInput(\"SupportMask\", const_cast<itk::Image<float, 3>*>(SupportMask));\n\/\/}\n\n\/\/template<>\n\/\/typename itk::Image<float, 3>::ConstPointer\n\/\/ConjugateGradientConeBeamReconstructionFilter< itk::VectorImage<float, 3>, itk::Image<float, 3> >\n\/\/::GetSupportMask()\n\/\/{\n\/\/ return static_cast< const itk::Image<float, 3> * >\n\/\/ ( this->itk::ProcessObject::GetInput(\"SupportMask\") );\n\/\/}\n\ntemplate<>\nvoid\nConjugateGradientConeBeamReconstructionFilter< itk::VectorImage<float, 3>, itk::Image<float, 3> >\n::GenerateOutputInformation()\n{\n \/\/ Choose between cuda or non-cuda conjugate gradient filter\n m_ConjugateGradientFilter = ConjugateGradientFilterType::New();\n#ifdef RTK_USE_CUDA\n if (m_CudaConjugateGradient)\n m_ConjugateGradientFilter = rtk::CudaConjugateGradientImageFilter_3f::New();\n#endif\n m_ConjugateGradientFilter->SetA(m_CGOperator.GetPointer());\n\/\/ m_ConjugateGradientFilter->SetIterationCosts(m_IterationCosts);\n\n \/\/ Set runtime connections\n m_ConstantVolumeSource->SetInformationFromImage(this->GetInput(0));\n m_CGOperator->SetInput(1, this->GetInput(1));\n m_CGOperator->SetSupportMask(this->GetSupportMask());\n m_ConjugateGradientFilter->SetX(this->GetInput(0));\n m_DisplacedDetectorFilter->SetDisable(m_DisableDisplacedDetectorFilter);\n m_DisplacedDetectorFilter->SetInput(this->GetInput(2));\n\n \/\/ Links with the m_BackProjectionFilter should be set here and not\n \/\/ in the constructor, as m_BackProjectionFilter is set at runtime\n m_BackProjectionFilterForB->SetInput(0, m_ConstantVolumeSource->GetOutput());\n m_ConjugateGradientFilter->SetB(m_BackProjectionFilterForB->GetOutput());\n\n \/\/ Set the matrix vector multiply filter's inputs for multiplication\n \/\/ by the inverse covariance matrix (for GLS minimization)\n m_MatrixVectorMultiplyFilter->SetInput1(this->GetInput(1));\n m_MatrixVectorMultiplyFilter->SetInput2(m_DisplacedDetectorFilter->GetOutput());\n m_CGOperator->SetInput(2, m_DisplacedDetectorFilter->GetOutput());\n m_BackProjectionFilterForB->SetInput(1, m_MatrixVectorMultiplyFilter->GetOutput());\n\n \/\/ If a support mask is used, it serves as preconditioning weights\n if (this->GetSupportMask().IsNotNull())\n {\n \/\/ Multiply the volume by support mask, and pass it to the conjugate gradient operator\n m_MultiplyVolumeFilter->SetInput1(m_BackProjectionFilterForB->GetOutput());\n m_MultiplyVolumeFilter->SetInput2(this->GetSupportMask());\n m_CGOperator->SetSupportMask(this->GetSupportMask());\n m_ConjugateGradientFilter->SetB(m_MultiplyVolumeFilter->GetOutput());\n\n \/\/ Multiply the output by the support mask\n m_MultiplyOutputFilter->SetInput1(m_ConjugateGradientFilter->GetOutput());\n m_MultiplyOutputFilter->SetInput2(this->GetSupportMask());\n }\n\n \/\/ For the same reason, set geometry now\n m_CGOperator->SetGeometry(this->m_Geometry);\n m_BackProjectionFilterForB->SetGeometry(this->m_Geometry.GetPointer());\n m_DisplacedDetectorFilter->SetGeometry(this->m_Geometry);\n\n \/\/ Set runtime parameters\n m_ConjugateGradientFilter->SetNumberOfIterations(this->m_NumberOfIterations);\n m_CGOperator->SetGamma(m_Gamma);\n m_CGOperator->SetTikhonov(m_Tikhonov);\n\n \/\/ Set memory management parameters\n m_MatrixVectorMultiplyFilter->ReleaseDataFlagOn();\n m_BackProjectionFilterForB->ReleaseDataFlagOn();\n if (this->GetSupportMask().IsNotNull())\n {\n m_MultiplyVolumeFilter->ReleaseDataFlagOn();\n m_MultiplyOutputFilter->ReleaseDataFlagOn();\n }\n\n \/\/ Have the last filter calculate its output information\n m_ConjugateGradientFilter->UpdateOutputInformation();\n\n \/\/ Copy it as the output information of the composite filter\n this->GetOutput()->CopyInformation( m_ConjugateGradientFilter->GetOutput() );\n}\n\ntemplate<>\nvoid\nConjugateGradientConeBeamReconstructionFilter< itk::VectorImage<float, 3>, itk::Image<float, 3> >\n::GenerateData()\n{\n itk::TimeProbe ConjugateGradientTimeProbe;\n\/\/ typename StatisticsImageFilterType::Pointer StatisticsImageFilterForC = StatisticsImageFilterType::New();\n\/\/ typename MultiplyFilterType::Pointer MultiplyFilterForC = MultiplyFilterType::New();\n\n\/\/ if (m_IterationCosts)\n\/\/ {\n\/\/ MultiplyFilterForC->SetInput(0,this->GetInput(1));\n\/\/ MultiplyFilterForC->SetInput(1,this->GetInput(2));\n\/\/ MultiplyFilterForC->Update();\n\/\/ MultiplyFilterForC->SetInput(1,MultiplyFilterForC->GetOutput());\n\/\/ MultiplyFilterForC->Update();\n\/\/ StatisticsImageFilterForC->SetInput(MultiplyFilterForC->GetOutput());\n\/\/ StatisticsImageFilterForC->Update();\n\/\/ m_ConjugateGradientFilter->SetC(0.5*StatisticsImageFilterForC->GetSum());\n\/\/ }\n\n if(m_MeasureExecutionTimes)\n {\n std::cout << \"Starting ConjugateGradient\" << std::endl;\n ConjugateGradientTimeProbe.Start();\n }\n\n m_ConjugateGradientFilter->Update();\n\n if (this->GetSupportMask())\n {\n m_MultiplyOutputFilter->Update();\n }\n\n if(m_MeasureExecutionTimes)\n {\n ConjugateGradientTimeProbe.Stop();\n std::cout << \"ConjugateGradient took \" << ConjugateGradientTimeProbe.GetTotal() << ' ' << ConjugateGradientTimeProbe.GetUnit() << std::endl;\n }\n\n if (this->GetSupportMask())\n {\n this->GraftOutput( m_MultiplyOutputFilter->GetOutput() );\n }\n else\n {\n this->GraftOutput( m_ConjugateGradientFilter->GetOutput() );\n }\n}\n\n} \/\/ end namespace rtk\n<|endoftext|>"} {"text":"<commit_before>\/* Copyright 2018 The TensorFlow Authors. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*\/\n#include <algorithm>\n#include <memory>\n#include <vector>\n\n#include \"absl\/memory\/memory.h\"\n#include \"absl\/strings\/string_view.h\"\n#include \"tensorflow\/compiler\/tf2tensorrt\/utils\/trt_allocator.h\"\n#include \"tensorflow\/compiler\/tf2tensorrt\/utils\/trt_engine_instance.pb.h\" \/\/ NOLINT\n#include \"tensorflow\/compiler\/tf2tensorrt\/utils\/trt_logger.h\"\n#include \"tensorflow\/compiler\/tf2tensorrt\/utils\/trt_lru_cache.h\"\n#include \"tensorflow\/core\/framework\/op.h\"\n#include \"tensorflow\/core\/framework\/op_kernel.h\"\n#include \"tensorflow\/core\/framework\/resource_mgr.h\"\n#include \"tensorflow\/core\/lib\/core\/errors.h\"\n#include \"tensorflow\/core\/lib\/core\/refcount.h\"\n#include \"tensorflow\/core\/lib\/io\/record_reader.h\"\n#include \"tensorflow\/core\/lib\/io\/record_writer.h\"\n#include \"tensorflow\/core\/platform\/logging.h\"\n#include \"tensorflow\/core\/platform\/mutex.h\"\n#include \"tensorflow\/core\/platform\/thread_annotations.h\"\n\n#if GOOGLE_CUDA && GOOGLE_TENSORRT\n#include \"third_party\/tensorrt\/NvInfer.h\"\n\nnamespace tensorflow {\nnamespace tensorrt {\nusing ::nvinfer1::IRuntime;\n\nclass CreateTRTResourceHandle : public OpKernel {\n public:\n explicit CreateTRTResourceHandle(OpKernelConstruction* ctx) : OpKernel(ctx) {\n OP_REQUIRES_OK(ctx, ctx->GetAttr(\"resource_name\", &resource_name_));\n }\n\n void Compute(OpKernelContext* ctx) override {\n {\n mutex_lock l(mutex_);\n if (!initialized_) {\n AllocatorAttributes attr;\n attr.set_on_host(true);\n OP_REQUIRES_OK(ctx, ctx->allocate_temp(DT_RESOURCE, TensorShape({}),\n &handle_, attr));\n\n VLOG(1) << \"Creating TRT engine cache resource handle for op \"\n << resource_name_ << \" on device \" << ctx->device()->name();\n handle_.scalar<ResourceHandle>()() =\n MakeResourceHandle<TRTEngineCacheResource>(\n ctx, std::string(kTfTrtContainerName), resource_name_);\n initialized_ = true;\n }\n }\n ctx->set_output(0, handle_);\n }\n\n private:\n string resource_name_;\n Tensor handle_;\n mutex mutex_;\n bool initialized_ TF_GUARDED_BY(mutex_) = false;\n\n TF_DISALLOW_COPY_AND_ASSIGN(CreateTRTResourceHandle);\n};\n\nREGISTER_KERNEL_BUILDER(Name(\"CreateTRTResourceHandle\")\n .Device(DEVICE_GPU)\n .HostMemory(\"resource_handle\"),\n CreateTRTResourceHandle);\n\nclass InitializeTRTResource : public OpKernel {\n public:\n explicit InitializeTRTResource(OpKernelConstruction* ctx) : OpKernel(ctx) {\n OP_REQUIRES_OK(\n ctx, ctx->GetAttr(\"max_cached_engines_count\", &max_cached_engines_));\n }\n\n void Compute(OpKernelContext* ctx) override {\n ResourceHandle handle = HandleFromInput(ctx, 0);\n core::RefCountPtr<TRTEngineCacheResource> resource;\n OP_REQUIRES_OK(\n ctx, LookupOrCreateResource<TRTEngineCacheResource>(\n ctx, handle, &resource,\n [this, ctx](TRTEngineCacheResource** resource) -> Status {\n *resource = new TRTEngineCacheResource(\n ctx, this->max_cached_engines_);\n return Status::OK();\n }));\n\n auto allocator = resource->allocator_.get();\n OP_REQUIRES(ctx, allocator != nullptr,\n errors::Internal(\"Not able to initialize TRT engine cache when \"\n \"GPU allocator is empty.\"));\n OP_REQUIRES(ctx, resource->cache_.size() == 0,\n errors::Internal(\"Expect engine cache to be empty, but got \",\n resource->cache_.size(), \" entries.\"));\n\n \/\/ Get the file name.\n const string& filename = ctx->input(1).scalar<tstring>()();\n OP_REQUIRES(ctx, !filename.empty(),\n errors::InvalidArgument(\"filename cannot be empty.\"));\n\n \/\/ Parse the serialized engines and add them to the cache.\n std::unique_ptr<RandomAccessFile> file;\n OP_REQUIRES_OK(ctx, ctx->env()->NewRandomAccessFile(filename, &file));\n auto reader = absl::make_unique<io::RecordReader>(file.get());\n\n uint64 offset = 0;\n int num_loaded_engine = 0;\n do {\n tstring record;\n Status status = reader->ReadRecord(&offset, &record);\n if (errors::IsOutOfRange(status)) break;\n\n TRTEngineInstance engine_instance;\n engine_instance.ParseFromString(record);\n std::vector<TensorShape> engine_input_shapes;\n auto input_shapes = engine_instance.input_shapes();\n engine_input_shapes.reserve(input_shapes.size());\n for (const TensorShapeProto& shape : input_shapes) {\n engine_input_shapes.emplace_back(shape);\n }\n\n TrtUniquePtrType<IRuntime> infer(\n nvinfer1::createInferRuntime(TRTEngineCacheResource::GetLogger()));\n infer->setGpuAllocator(allocator);\n TrtUniquePtrType<nvinfer1::ICudaEngine> engine(\n infer->deserializeCudaEngine(\n engine_instance.serialized_engine().c_str(),\n engine_instance.serialized_engine().size(), nullptr));\n auto raw_engine = engine.get();\n std::vector<ExecutionContext> ctx_vec;\n if (num_loaded_engine == 0) {\n \/\/ Restore profiles if there are any. Currently only 1 engine is allowed\n \/\/ in dynamic mode therefore we call this only for the 0th engine.\n \/\/ it is a no-op in implicit batch mode.\n OP_REQUIRES_OK(ctx, resource->profiles_.RestoreProfiles(raw_engine));\n OP_REQUIRES_OK(ctx, resource->profiles_.CreateExecutionContexts(\n raw_engine, &ctx_vec));\n } else {\n \/\/ Multiple engines are only available in static mode. For each engine\n \/\/ we have only a single execution context.\n ctx_vec.push_back(ExecutionContext::Create(raw_engine));\n }\n resource->cache_.emplace(engine_input_shapes,\n absl::make_unique<EngineContext>(\n std::move(engine), std::move(ctx_vec)));\n ++num_loaded_engine;\n } while (1);\n VLOG(1) << \"Loaded \" << num_loaded_engine << \" TRT engines for op \"\n << handle.name() << \" on device \" << ctx->device()->name()\n << \" from file \" << filename;\n }\n\n private:\n \/\/ Maximum number of cached engines\n int max_cached_engines_;\n\n TF_DISALLOW_COPY_AND_ASSIGN(InitializeTRTResource);\n};\n\nREGISTER_KERNEL_BUILDER(Name(\"InitializeTRTResource\")\n .Device(DEVICE_GPU)\n .HostMemory(\"resource_handle\"),\n InitializeTRTResource);\n\nclass SerializeTRTResource : public OpKernel {\n public:\n explicit SerializeTRTResource(OpKernelConstruction* ctx) : OpKernel(ctx) {\n OP_REQUIRES_OK(ctx, ctx->GetAttr(\"delete_resource\", &delete_resource_));\n }\n\n void Compute(OpKernelContext* ctx) override {\n const string& resource_name = ctx->input(0).scalar<tstring>()();\n const string& filename = ctx->input(1).scalar<tstring>()();\n OP_REQUIRES(ctx, !filename.empty(),\n errors::InvalidArgument(\"filename cannot be empty.\"));\n\n \/\/ Lookup engine cache resource.\n TRTEngineCacheResource* resource = nullptr;\n OP_REQUIRES_OK(\n ctx, ctx->resource_manager()->Lookup(std::string(kTfTrtContainerName),\n resource_name, &resource));\n core::ScopedUnref unref_me(resource);\n\n \/\/ Terminate the calibration if any.\n if (resource->calib_ctx_) resource->calib_ctx_->TerminateCalibration();\n\n \/\/ Serialize the engines and write them to file.\n std::unique_ptr<WritableFile> file;\n OP_REQUIRES_OK(ctx, ctx->env()->NewWritableFile(filename, &file));\n auto writer = absl::make_unique<io::RecordWriter>(file.get());\n\n int num_serialized_engines = 0;\n for (const auto& pair : resource->cache_) {\n \/\/ Ignore engines that failed to build.\n const std::unique_ptr<EngineContext>& engine = pair.second;\n if (!engine || !engine->cuda_engine) continue;\n\n TRTEngineInstance engine_instance;\n \/\/ Add input shapes.\n const std::vector<TensorShape>& engine_input_shapes = pair.first;\n for (const TensorShape& shape : engine_input_shapes) {\n shape.AsProto(engine_instance.add_input_shapes());\n }\n \/\/ Add the serialized engine.\n TrtUniquePtrType<nvinfer1::IHostMemory> engine_data(\n engine->cuda_engine->serialize());\n engine_instance.set_serialized_engine(engine_data->data(),\n engine_data->size());\n\n OP_REQUIRES_OK(ctx,\n writer->WriteRecord(engine_instance.SerializeAsString()));\n ++num_serialized_engines;\n }\n VLOG(1) << \"Serialized \" << num_serialized_engines << \" TRT engines for op \"\n << resource_name << \" on device \" << ctx->device()->name()\n << \" to file \" << filename;\n\n if (delete_resource_) {\n VLOG(1) << \"Destroying TRT engine cache resource for op \" << resource_name\n << \" on device \" << ctx->device()->name();\n OP_REQUIRES_OK(ctx,\n ctx->resource_manager()->Delete<TRTEngineCacheResource>(\n std::string(kTfTrtContainerName), resource_name));\n }\n }\n\n private:\n bool delete_resource_ = false;\n\n TF_DISALLOW_COPY_AND_ASSIGN(SerializeTRTResource);\n};\n\nREGISTER_KERNEL_BUILDER(Name(\"SerializeTRTResource\").Device(DEVICE_GPU),\n SerializeTRTResource);\n\n} \/\/ namespace tensorrt\n} \/\/ namespace tensorflow\n\n#endif \/\/ GOOGLE_CUDA && GOOGLE_TENSORRT\n<commit_msg>[tensorflow\/compiler\/tf2tensorrt\/kernels\/trt_engine_resource_ops.cc] Use `const auto&` instead of `auto`<commit_after>\/* Copyright 2018 The TensorFlow Authors. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*\/\n#include <algorithm>\n#include <memory>\n#include <vector>\n\n#include \"absl\/memory\/memory.h\"\n#include \"absl\/strings\/string_view.h\"\n#include \"tensorflow\/compiler\/tf2tensorrt\/utils\/trt_allocator.h\"\n#include \"tensorflow\/compiler\/tf2tensorrt\/utils\/trt_engine_instance.pb.h\" \/\/ NOLINT\n#include \"tensorflow\/compiler\/tf2tensorrt\/utils\/trt_logger.h\"\n#include \"tensorflow\/compiler\/tf2tensorrt\/utils\/trt_lru_cache.h\"\n#include \"tensorflow\/core\/framework\/op.h\"\n#include \"tensorflow\/core\/framework\/op_kernel.h\"\n#include \"tensorflow\/core\/framework\/resource_mgr.h\"\n#include \"tensorflow\/core\/lib\/core\/errors.h\"\n#include \"tensorflow\/core\/lib\/core\/refcount.h\"\n#include \"tensorflow\/core\/lib\/io\/record_reader.h\"\n#include \"tensorflow\/core\/lib\/io\/record_writer.h\"\n#include \"tensorflow\/core\/platform\/logging.h\"\n#include \"tensorflow\/core\/platform\/mutex.h\"\n#include \"tensorflow\/core\/platform\/thread_annotations.h\"\n\n#if GOOGLE_CUDA && GOOGLE_TENSORRT\n#include \"third_party\/tensorrt\/NvInfer.h\"\n\nnamespace tensorflow {\nnamespace tensorrt {\nusing ::nvinfer1::IRuntime;\n\nclass CreateTRTResourceHandle : public OpKernel {\n public:\n explicit CreateTRTResourceHandle(OpKernelConstruction* ctx) : OpKernel(ctx) {\n OP_REQUIRES_OK(ctx, ctx->GetAttr(\"resource_name\", &resource_name_));\n }\n\n void Compute(OpKernelContext* ctx) override {\n {\n mutex_lock l(mutex_);\n if (!initialized_) {\n AllocatorAttributes attr;\n attr.set_on_host(true);\n OP_REQUIRES_OK(ctx, ctx->allocate_temp(DT_RESOURCE, TensorShape({}),\n &handle_, attr));\n\n VLOG(1) << \"Creating TRT engine cache resource handle for op \"\n << resource_name_ << \" on device \" << ctx->device()->name();\n handle_.scalar<ResourceHandle>()() =\n MakeResourceHandle<TRTEngineCacheResource>(\n ctx, std::string(kTfTrtContainerName), resource_name_);\n initialized_ = true;\n }\n }\n ctx->set_output(0, handle_);\n }\n\n private:\n string resource_name_;\n Tensor handle_;\n mutex mutex_;\n bool initialized_ TF_GUARDED_BY(mutex_) = false;\n\n TF_DISALLOW_COPY_AND_ASSIGN(CreateTRTResourceHandle);\n};\n\nREGISTER_KERNEL_BUILDER(Name(\"CreateTRTResourceHandle\")\n .Device(DEVICE_GPU)\n .HostMemory(\"resource_handle\"),\n CreateTRTResourceHandle);\n\nclass InitializeTRTResource : public OpKernel {\n public:\n explicit InitializeTRTResource(OpKernelConstruction* ctx) : OpKernel(ctx) {\n OP_REQUIRES_OK(\n ctx, ctx->GetAttr(\"max_cached_engines_count\", &max_cached_engines_));\n }\n\n void Compute(OpKernelContext* ctx) override {\n ResourceHandle handle = HandleFromInput(ctx, 0);\n core::RefCountPtr<TRTEngineCacheResource> resource;\n OP_REQUIRES_OK(\n ctx, LookupOrCreateResource<TRTEngineCacheResource>(\n ctx, handle, &resource,\n [this, ctx](TRTEngineCacheResource** resource) -> Status {\n *resource = new TRTEngineCacheResource(\n ctx, this->max_cached_engines_);\n return Status::OK();\n }));\n\n auto allocator = resource->allocator_.get();\n OP_REQUIRES(ctx, allocator != nullptr,\n errors::Internal(\"Not able to initialize TRT engine cache when \"\n \"GPU allocator is empty.\"));\n OP_REQUIRES(ctx, resource->cache_.size() == 0,\n errors::Internal(\"Expect engine cache to be empty, but got \",\n resource->cache_.size(), \" entries.\"));\n\n \/\/ Get the file name.\n const string& filename = ctx->input(1).scalar<tstring>()();\n OP_REQUIRES(ctx, !filename.empty(),\n errors::InvalidArgument(\"filename cannot be empty.\"));\n\n \/\/ Parse the serialized engines and add them to the cache.\n std::unique_ptr<RandomAccessFile> file;\n OP_REQUIRES_OK(ctx, ctx->env()->NewRandomAccessFile(filename, &file));\n auto reader = absl::make_unique<io::RecordReader>(file.get());\n\n uint64 offset = 0;\n int num_loaded_engine = 0;\n do {\n tstring record;\n Status status = reader->ReadRecord(&offset, &record);\n if (errors::IsOutOfRange(status)) break;\n\n TRTEngineInstance engine_instance;\n engine_instance.ParseFromString(record);\n std::vector<TensorShape> engine_input_shapes;\n const auto& input_shapes = engine_instance.input_shapes();\n engine_input_shapes.reserve(input_shapes.size());\n for (const TensorShapeProto& shape : input_shapes) {\n engine_input_shapes.emplace_back(shape);\n }\n\n TrtUniquePtrType<IRuntime> infer(\n nvinfer1::createInferRuntime(TRTEngineCacheResource::GetLogger()));\n infer->setGpuAllocator(allocator);\n TrtUniquePtrType<nvinfer1::ICudaEngine> engine(\n infer->deserializeCudaEngine(\n engine_instance.serialized_engine().c_str(),\n engine_instance.serialized_engine().size(), nullptr));\n auto raw_engine = engine.get();\n std::vector<ExecutionContext> ctx_vec;\n if (num_loaded_engine == 0) {\n \/\/ Restore profiles if there are any. Currently only 1 engine is allowed\n \/\/ in dynamic mode therefore we call this only for the 0th engine.\n \/\/ it is a no-op in implicit batch mode.\n OP_REQUIRES_OK(ctx, resource->profiles_.RestoreProfiles(raw_engine));\n OP_REQUIRES_OK(ctx, resource->profiles_.CreateExecutionContexts(\n raw_engine, &ctx_vec));\n } else {\n \/\/ Multiple engines are only available in static mode. For each engine\n \/\/ we have only a single execution context.\n ctx_vec.push_back(ExecutionContext::Create(raw_engine));\n }\n resource->cache_.emplace(engine_input_shapes,\n absl::make_unique<EngineContext>(\n std::move(engine), std::move(ctx_vec)));\n ++num_loaded_engine;\n } while (1);\n VLOG(1) << \"Loaded \" << num_loaded_engine << \" TRT engines for op \"\n << handle.name() << \" on device \" << ctx->device()->name()\n << \" from file \" << filename;\n }\n\n private:\n \/\/ Maximum number of cached engines\n int max_cached_engines_;\n\n TF_DISALLOW_COPY_AND_ASSIGN(InitializeTRTResource);\n};\n\nREGISTER_KERNEL_BUILDER(Name(\"InitializeTRTResource\")\n .Device(DEVICE_GPU)\n .HostMemory(\"resource_handle\"),\n InitializeTRTResource);\n\nclass SerializeTRTResource : public OpKernel {\n public:\n explicit SerializeTRTResource(OpKernelConstruction* ctx) : OpKernel(ctx) {\n OP_REQUIRES_OK(ctx, ctx->GetAttr(\"delete_resource\", &delete_resource_));\n }\n\n void Compute(OpKernelContext* ctx) override {\n const string& resource_name = ctx->input(0).scalar<tstring>()();\n const string& filename = ctx->input(1).scalar<tstring>()();\n OP_REQUIRES(ctx, !filename.empty(),\n errors::InvalidArgument(\"filename cannot be empty.\"));\n\n \/\/ Lookup engine cache resource.\n TRTEngineCacheResource* resource = nullptr;\n OP_REQUIRES_OK(\n ctx, ctx->resource_manager()->Lookup(std::string(kTfTrtContainerName),\n resource_name, &resource));\n core::ScopedUnref unref_me(resource);\n\n \/\/ Terminate the calibration if any.\n if (resource->calib_ctx_) resource->calib_ctx_->TerminateCalibration();\n\n \/\/ Serialize the engines and write them to file.\n std::unique_ptr<WritableFile> file;\n OP_REQUIRES_OK(ctx, ctx->env()->NewWritableFile(filename, &file));\n auto writer = absl::make_unique<io::RecordWriter>(file.get());\n\n int num_serialized_engines = 0;\n for (const auto& pair : resource->cache_) {\n \/\/ Ignore engines that failed to build.\n const std::unique_ptr<EngineContext>& engine = pair.second;\n if (!engine || !engine->cuda_engine) continue;\n\n TRTEngineInstance engine_instance;\n \/\/ Add input shapes.\n const std::vector<TensorShape>& engine_input_shapes = pair.first;\n for (const TensorShape& shape : engine_input_shapes) {\n shape.AsProto(engine_instance.add_input_shapes());\n }\n \/\/ Add the serialized engine.\n TrtUniquePtrType<nvinfer1::IHostMemory> engine_data(\n engine->cuda_engine->serialize());\n engine_instance.set_serialized_engine(engine_data->data(),\n engine_data->size());\n\n OP_REQUIRES_OK(ctx,\n writer->WriteRecord(engine_instance.SerializeAsString()));\n ++num_serialized_engines;\n }\n VLOG(1) << \"Serialized \" << num_serialized_engines << \" TRT engines for op \"\n << resource_name << \" on device \" << ctx->device()->name()\n << \" to file \" << filename;\n\n if (delete_resource_) {\n VLOG(1) << \"Destroying TRT engine cache resource for op \" << resource_name\n << \" on device \" << ctx->device()->name();\n OP_REQUIRES_OK(ctx,\n ctx->resource_manager()->Delete<TRTEngineCacheResource>(\n std::string(kTfTrtContainerName), resource_name));\n }\n }\n\n private:\n bool delete_resource_ = false;\n\n TF_DISALLOW_COPY_AND_ASSIGN(SerializeTRTResource);\n};\n\nREGISTER_KERNEL_BUILDER(Name(\"SerializeTRTResource\").Device(DEVICE_GPU),\n SerializeTRTResource);\n\n} \/\/ namespace tensorrt\n} \/\/ namespace tensorflow\n\n#endif \/\/ GOOGLE_CUDA && GOOGLE_TENSORRT\n<|endoftext|>"} {"text":"<commit_before>#include \"core\/tcp_file_server.h\"\n\n#include \"core\/array.h\"\n#include \"core\/free_list.h\"\n#include \"core\/static_array.h\"\n#include \"core\/tcp_file_device.h\"\n#include \"core\/task.h\"\n#include \"core\/tcp_acceptor.h\"\n#include \"core\/tcp_stream.h\"\n#include \"core\/os_file.h\"\n\nnamespace Lux\n{\n\tnamespace FS\n\t{\n\t\tclass TCPFileServerTask : public MT::Task\n\t\t{\n\t\tpublic:\n\t\t\tTCPFileServerTask() {}\n\t\t\t~TCPFileServerTask() {}\n\n\t\t\tint task()\n\t\t\t{\n\t\t\t\tbool quit = false;\n\n\t\t\t\tm_acceptor.start(\"127.0.0.1\", 10001);\n\t\t\t\tNet::TCPStream* stream = m_acceptor.accept();\n\n\t\t\t\twhile(!quit)\n\t\t\t\t{\n\t\t\t\t\tint32_t op = 0;\n\t\t\t\t\tstream->read(op);\n\t\t\t\t\tswitch(op)\n\t\t\t\t\t{\n\t\t\t\t\tcase TCPCommand::OpenFile:\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tint32_t mode = 0;\n\t\t\t\t\t\t\tint32_t len = 0;\n\t\t\t\t\t\t\tstream->read(mode);\n\t\t\t\t\t\t\tstream->read(m_buffer.data(), m_buffer.size());\n\n\t\t\t\t\t\t\tint32_t ret = -2;\n\t\t\t\t\t\t\tint32_t id = m_ids.alloc();\n\t\t\t\t\t\t\tif(id > 0)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tOsFile* file = LUX_NEW(OsFile)();\n\t\t\t\t\t\t\t\tm_files[id] = file;\n\n\t\t\t\t\t\t\t\tret = file->open(m_buffer.data(), mode) ? id : -1;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tstream->write(ret);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase TCPCommand::Close:\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tuint32_t id = -1;\n\t\t\t\t\t\t\tstream->read(id);\n\t\t\t\t\t\t\tOsFile* file = m_files[id];\n\t\t\t\t\t\t\tm_ids.release(id);\n\n\t\t\t\t\t\t\tfile->close();\n\t\t\t\t\t\t\tLUX_DELETE(file);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase TCPCommand::Read:\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tbool read_successful = true;\n\t\t\t\t\t\t\tuint32_t id = -1;\n\t\t\t\t\t\t\tstream->read(id);\n\t\t\t\t\t\t\tOsFile* file = m_files[id];\n\n\t\t\t\t\t\t\tuint32_t size = 0;\n\t\t\t\t\t\t\tstream->read(size);\n\n\t\t\t\t\t\t\twhile(size > 0)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tint32_t read = (int32_t)size > m_buffer.size() ? m_buffer.size() : (int32_t)size;\n\t\t\t\t\t\t\t\tread_successful &= file->read((void*)m_buffer.data(), read);\n\t\t\t\t\t\t\t\tstream->write((const void*)m_buffer.data(), read);\n\t\t\t\t\t\t\t\tsize -= read;\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tstream->write(read_successful);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase TCPCommand::Write:\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tbool write_successful = true;\n\t\t\t\t\t\t\tuint32_t id = -1;\n\t\t\t\t\t\t\tstream->read(id);\n\t\t\t\t\t\t\tOsFile* file = m_files[id];\n\n\t\t\t\t\t\t\tuint32_t size = 0;\n\t\t\t\t\t\t\tstream->read(size);\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\twhile(size > 0)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tint32_t read = (int32_t)size > m_buffer.size() ? m_buffer.size() : (int32_t)size;\n\t\t\t\t\t\t\t\twrite_successful &= stream->read((void*)m_buffer.data(), read);\n\t\t\t\t\t\t\t\tfile->write(m_buffer.data(), read);\n\t\t\t\t\t\t\t\tsize -= read;\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tstream->write(write_successful);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase TCPCommand::Size:\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tuint32_t id = -1;\n\t\t\t\t\t\t\tstream->read(id);\n\t\t\t\t\t\t\tOsFile* file = m_files[id];\n\n\t\t\t\t\t\t\tuint32_t size = (uint32_t)file->size();\n\t\t\t\t\t\t\tstream->write(size);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase TCPCommand::Seek:\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tuint32_t id = -1;\n\t\t\t\t\t\t\tstream->read(id);\n\t\t\t\t\t\t\tOsFile* file = m_files[id];\n\n\t\t\t\t\t\t\tuint32_t base = 0;\n\t\t\t\t\t\t\tint32_t offset = 0;\n\t\t\t\t\t\t\tstream->read(base);\n\t\t\t\t\t\t\tstream->read(offset);\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tuint32_t pos = (uint32_t)file->seek((SeekMode)base, offset);\n\t\t\t\t\t\t\tstream->write(pos);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase TCPCommand::Pos:\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tuint32_t id = -1;\n\t\t\t\t\t\t\tstream->read(id);\n\t\t\t\t\t\t\tOsFile* file = m_files[id];\n\n\t\t\t\t\t\t\tuint32_t pos = (uint32_t)file->pos();\n\t\t\t\t\t\t\tstream->write(pos);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase TCPCommand::Disconnect:\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tquit = true;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\tdefault:\n\t\t\t\t\t\tASSERT(0);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tLUX_DELETE(stream);\n\t\t\t\treturn 0;\n\t\t\t}\n\n\t\t\tvoid stop() {} \/\/ TODO: implement stop \n\n\t\tprivate:\n\t\t\tNet::TCPAcceptor\t\t\tm_acceptor;\n\t\t\tStaticArray<char, 0x50000>\tm_buffer;\n\t\t\tStaticArray<OsFile*, 0x50000> m_files;\n\t\t\tFreeList<int32_t, 0x50000>\tm_ids;\n\t\t};\n\n\t\tstruct TCPFileServerImpl\n\t\t{\n\t\t\tTCPFileServerTask m_task;\n\t\t};\n\n\t\tTCPFileServer::TCPFileServer()\n\t\t{\n\t\t\tm_impl = NULL;\n\t\t}\n\n\t\tTCPFileServer::~TCPFileServer()\n\t\t{\n\t\t\tLUX_DELETE(m_impl);\n\t\t}\n\n\t\tvoid TCPFileServer::start()\n\t\t{\n\t\t\tm_impl = LUX_NEW(TCPFileServerImpl);\n\t\t\tm_impl->m_task.create(\"TCP File Server Task\");\n\t\t\tm_impl->m_task.run();\n\t\t}\n\n\t\tvoid TCPFileServer::stop()\n\t\t{\n\t\t\tm_impl->m_task.stop();\n\t\t\tm_impl->m_task.destroy();\n\t\t\tLUX_DELETE(m_impl);\n\t\t\tm_impl = NULL;\n\t\t}\n\t} \/\/ ~namespace FS\n} \/\/ ~namespace Lux<commit_msg>file server fixed<commit_after>#include \"core\/tcp_file_server.h\"\n\n#include \"core\/array.h\"\n#include \"core\/free_list.h\"\n#include \"core\/static_array.h\"\n#include \"core\/tcp_file_device.h\"\n#include \"core\/task.h\"\n#include \"core\/tcp_acceptor.h\"\n#include \"core\/tcp_stream.h\"\n#include \"core\/os_file.h\"\n\nnamespace Lux\n{\n\tnamespace FS\n\t{\n\t\tclass TCPFileServerTask : public MT::Task\n\t\t{\n\t\tpublic:\n\t\t\tTCPFileServerTask() {}\n\t\t\t~TCPFileServerTask() {}\n\n\t\t\tint task()\n\t\t\t{\n\t\t\t\tbool quit = false;\n\n\t\t\t\tm_acceptor.start(\"127.0.0.1\", 10001);\n\t\t\t\tNet::TCPStream* stream = m_acceptor.accept();\n\n\t\t\t\twhile(!quit)\n\t\t\t\t{\n\t\t\t\t\tint32_t op = 0;\n\t\t\t\t\tstream->read(op);\n\t\t\t\t\tswitch(op)\n\t\t\t\t\t{\n\t\t\t\t\tcase TCPCommand::OpenFile:\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tint32_t mode = 0;\n\t\t\t\t\t\t\tint32_t len = 0;\n\t\t\t\t\t\t\tstream->read(mode);\n\t\t\t\t\t\t\tstream->readString(m_buffer.data(), m_buffer.size());\n\n\t\t\t\t\t\t\tint32_t ret = -2;\n\t\t\t\t\t\t\tint32_t id = m_ids.alloc();\n\t\t\t\t\t\t\tif(id > 0)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tOsFile* file = LUX_NEW(OsFile)();\n\t\t\t\t\t\t\t\tm_files[id] = file;\n\n\t\t\t\t\t\t\t\tret = file->open(m_buffer.data(), mode) ? id : -1;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tstream->write(ret);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase TCPCommand::Close:\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tuint32_t id = -1;\n\t\t\t\t\t\t\tstream->read(id);\n\t\t\t\t\t\t\tOsFile* file = m_files[id];\n\t\t\t\t\t\t\tm_ids.release(id);\n\n\t\t\t\t\t\t\tfile->close();\n\t\t\t\t\t\t\tLUX_DELETE(file);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase TCPCommand::Read:\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tbool read_successful = true;\n\t\t\t\t\t\t\tuint32_t id = -1;\n\t\t\t\t\t\t\tstream->read(id);\n\t\t\t\t\t\t\tOsFile* file = m_files[id];\n\n\t\t\t\t\t\t\tuint32_t size = 0;\n\t\t\t\t\t\t\tstream->read(size);\n\n\t\t\t\t\t\t\twhile(size > 0)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tint32_t read = (int32_t)size > m_buffer.size() ? m_buffer.size() : (int32_t)size;\n\t\t\t\t\t\t\t\tread_successful &= file->read((void*)m_buffer.data(), read);\n\t\t\t\t\t\t\t\tstream->write((const void*)m_buffer.data(), read);\n\t\t\t\t\t\t\t\tsize -= read;\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tstream->write(read_successful);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase TCPCommand::Write:\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tbool write_successful = true;\n\t\t\t\t\t\t\tuint32_t id = -1;\n\t\t\t\t\t\t\tstream->read(id);\n\t\t\t\t\t\t\tOsFile* file = m_files[id];\n\n\t\t\t\t\t\t\tuint32_t size = 0;\n\t\t\t\t\t\t\tstream->read(size);\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\twhile(size > 0)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tint32_t read = (int32_t)size > m_buffer.size() ? m_buffer.size() : (int32_t)size;\n\t\t\t\t\t\t\t\twrite_successful &= stream->read((void*)m_buffer.data(), read);\n\t\t\t\t\t\t\t\tfile->write(m_buffer.data(), read);\n\t\t\t\t\t\t\t\tsize -= read;\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tstream->write(write_successful);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase TCPCommand::Size:\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tuint32_t id = -1;\n\t\t\t\t\t\t\tstream->read(id);\n\t\t\t\t\t\t\tOsFile* file = m_files[id];\n\n\t\t\t\t\t\t\tuint32_t size = (uint32_t)file->size();\n\t\t\t\t\t\t\tstream->write(size);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase TCPCommand::Seek:\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tuint32_t id = -1;\n\t\t\t\t\t\t\tstream->read(id);\n\t\t\t\t\t\t\tOsFile* file = m_files[id];\n\n\t\t\t\t\t\t\tuint32_t base = 0;\n\t\t\t\t\t\t\tint32_t offset = 0;\n\t\t\t\t\t\t\tstream->read(base);\n\t\t\t\t\t\t\tstream->read(offset);\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tuint32_t pos = (uint32_t)file->seek((SeekMode)base, offset);\n\t\t\t\t\t\t\tstream->write(pos);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase TCPCommand::Pos:\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tuint32_t id = -1;\n\t\t\t\t\t\t\tstream->read(id);\n\t\t\t\t\t\t\tOsFile* file = m_files[id];\n\n\t\t\t\t\t\t\tuint32_t pos = (uint32_t)file->pos();\n\t\t\t\t\t\t\tstream->write(pos);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase TCPCommand::Disconnect:\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tquit = true;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\tdefault:\n\t\t\t\t\t\tASSERT(0);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tLUX_DELETE(stream);\n\t\t\t\treturn 0;\n\t\t\t}\n\n\t\t\tvoid stop() {} \/\/ TODO: implement stop \n\n\t\tprivate:\n\t\t\tNet::TCPAcceptor\t\t\tm_acceptor;\n\t\t\tStaticArray<char, 0x50000>\tm_buffer;\n\t\t\tStaticArray<OsFile*, 0x50000> m_files;\n\t\t\tFreeList<int32_t, 0x50000>\tm_ids;\n\t\t};\n\n\t\tstruct TCPFileServerImpl\n\t\t{\n\t\t\tTCPFileServerTask m_task;\n\t\t};\n\n\t\tTCPFileServer::TCPFileServer()\n\t\t{\n\t\t\tm_impl = NULL;\n\t\t}\n\n\t\tTCPFileServer::~TCPFileServer()\n\t\t{\n\t\t\tLUX_DELETE(m_impl);\n\t\t}\n\n\t\tvoid TCPFileServer::start()\n\t\t{\n\t\t\tm_impl = LUX_NEW(TCPFileServerImpl);\n\t\t\tm_impl->m_task.create(\"TCP File Server Task\");\n\t\t\tm_impl->m_task.run();\n\t\t}\n\n\t\tvoid TCPFileServer::stop()\n\t\t{\n\t\t\tm_impl->m_task.stop();\n\t\t\tm_impl->m_task.destroy();\n\t\t\tLUX_DELETE(m_impl);\n\t\t\tm_impl = NULL;\n\t\t}\n\t} \/\/ ~namespace FS\n} \/\/ ~namespace Lux<|endoftext|>"} {"text":"<commit_before>#include <Ab\/Config.hpp>\n#include <Ab\/LinearMemory.hpp>\n#include <gtest\/gtest.h>\n\nnamespace Ab::Test {\n\nTEST(LinearMemoryTest, InitAndKill) { LinearMemory m; }\n\nTEST(LinearMemoryTest, GrowThreeTimes) {\n\tLinearMemory m;\n\tfor (std::size_t i = 0; i < 3; i++) {\n\t\tm.grow();\n\t}\n}\n\nTEST(LinearMemoryTest, AssignToMemory) {\n\tLinearMemoryConfig cfg;\n\tcfg.page_count_min = 1;\n\tcfg.page_count_max = 1;\n\n\tLinearMemory m(cfg);\n\n\tauto ptr = to_ptr<int>(m.address());\n\tEXPECT_NE(ptr, nullptr);\n\tEXPECT_EQ(*ptr, 0);\n\t*ptr = 123;\n\tEXPECT_EQ(*ptr, 123);\n}\n\n} \/\/ namespace Ab::Test\n<commit_msg>Use LinearMemoryConfig when creating LinearMemory in test<commit_after>#include <Ab\/Config.hpp>\n#include <Ab\/LinearMemory.hpp>\n#include <gtest\/gtest.h>\n\nnamespace Ab::Test {\n\nTEST(LinearMemoryTest, InitAndKill) { LinearMemory m; }\n\nTEST(LinearMemoryTest, GrowThreeTimes) {\n\tLinearMemoryConfig cfg;\n\tcfg.page_count_min = 0;\n\tcfg.page_count_max = 3;\n\n\tLinearMemory m(cfg);\n\tfor (std::size_t i = 0; i < 3; i++) {\n\t\tm.grow();\n\t}\n}\n\nTEST(LinearMemoryTest, AssignToMemory) {\n\tLinearMemoryConfig cfg;\n\tcfg.page_count_min = 1;\n\tcfg.page_count_max = 1;\n\n\tLinearMemory m(cfg);\n\n\tauto ptr = to_ptr<int>(m.address());\n\tEXPECT_NE(ptr, nullptr);\n\tEXPECT_EQ(*ptr, 0);\n\t*ptr = 123;\n\tEXPECT_EQ(*ptr, 123);\n}\n\n} \/\/ namespace Ab::Test\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: servreg.cxx,v $\n *\n * $Revision: 1.2 $\n *\n * last change: $Author: jl $ $Date: 2001-06-27 10:56:03 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n#include <rtl\/unload.h>\n#include <osl\/time.h>\n#include \"ole2uno.hxx\"\n#include \"servprov.hxx\"\n#ifndef _RTL_USTRING_\n#include <rtl\/ustring>\n#endif\n#ifndef _CPPUHELPER_FACTORY_HXX_\n#include <cppuhelper\/factory.hxx>\n#endif\nusing namespace rtl;\nusing namespace ole_adapter;\nusing namespace cppu;\n\nnamespace ole_adapter\n{\nrtl_StandardModuleCount globalModuleCount= MODULE_COUNT_INIT;\n\n\n\nReference<XInterface> SAL_CALL ConverterProvider_CreateInstance2( const Reference<XMultiServiceFactory> & xSMgr)\n throw(Exception)\n{\n Reference<XInterface> xService = *new OleConverter_Impl2( xSMgr);\n return xService;\n}\n\nReference<XInterface> SAL_CALL ConverterProvider_CreateInstanceVar1( const Reference<XMultiServiceFactory> & xSMgr)\n throw(Exception)\n{\n Reference<XInterface> xService = *new OleConverter_Impl2( xSMgr, UNO_OBJECT_WRAPPER_REMOTE_OPT, IUNKNOWN_WRAPPER_IMPL);\n return xService;\n}\n\nReference<XInterface> SAL_CALL OleClient_CreateInstance( const Reference<XMultiServiceFactory> & xSMgr)\n throw(Exception)\n{\n Reference<XInterface> xService = *new OleClient_Impl( xSMgr);\n return xService;\n}\n\nReference<XInterface> SAL_CALL OleServer_CreateInstance( const Reference<XMultiServiceFactory> & xSMgr)\n throw (Exception)\n{\n Reference<XInterface > xService = *new OleServer_Impl(xSMgr);\n return xService;\n}\n} \/\/ end namespace\n\nextern \"C\" void * SAL_CALL component_getFactory(\n const sal_Char * pImplName, void * pServiceManager, void * pRegistryKey )\n{\n void * pRet = 0;\n\n OUString aImplName( OUString::createFromAscii( pImplName ) );\n Reference< XSingleServiceFactory > xFactory;\n Sequence<OUString> seqServiceNames;\n if (pServiceManager && aImplName.equals( L\"com.sun.star.comp.ole.OleConverter2\" ))\n {\n xFactory= createSingleFactory( reinterpret_cast< XMultiServiceFactory*>(pServiceManager),\n OUString( RTL_CONSTASCII_USTRINGPARAM(\"com.sun.star.comp.ole.OleConverter2\")),\n ConverterProvider_CreateInstance2, seqServiceNames,\n &globalModuleCount.modCnt );\n }\n else if (pServiceManager && aImplName.equals( L\"com.sun.star.comp.ole.OleConverterVar1\" ))\n {\n xFactory= createSingleFactory( reinterpret_cast<XMultiServiceFactory*>(pServiceManager),\n OUString( RTL_CONSTASCII_USTRINGPARAM(\"com.sun.star.comp.ole.OleConverterVar1\")),\n ConverterProvider_CreateInstanceVar1, seqServiceNames,\n &globalModuleCount.modCnt );\n }\n else if(pServiceManager && aImplName.equals(L\"com.sun.star.comp.ole.OleClient\"))\n {\n xFactory= createSingleFactory( reinterpret_cast< XMultiServiceFactory*>(pServiceManager),\n OUString( RTL_CONSTASCII_USTRINGPARAM(\"com.sun.star.comp.ole.OleClient\")),\n OleClient_CreateInstance, seqServiceNames,\n &globalModuleCount.modCnt);\n }\n else if(pServiceManager && aImplName.equals(L\"com.sun.star.comp.ole.OleServer\"))\n {\n xFactory= createOneInstanceFactory( reinterpret_cast< XMultiServiceFactory*>(pServiceManager),\n OUString( RTL_CONSTASCII_USTRINGPARAM(\"com.sun.star.comp.ole.OleServer\")),\n OleServer_CreateInstance, seqServiceNames,\n &globalModuleCount.modCnt);\n }\n\n if (xFactory.is())\n {\n xFactory->acquire();\n pRet = xFactory.get();\n }\n\n return pRet;\n}\n\n\nextern \"C\" sal_Bool SAL_CALL component_writeInfo( void * pServiceManager, void * pRegistryKey )\n{\n if (pRegistryKey)\n {\n try\n {\n Reference<XRegistryKey> xNewKey =\n reinterpret_cast<XRegistryKey*>( pRegistryKey)->createKey(L\"\/com.sun.star.comp.ole.OleConverter2\/UNO\/SERVICES\");\n xNewKey->createKey(L\"com.sun.star.bridge.OleBridgeSupplier2\");\n\n xNewKey =\n reinterpret_cast<XRegistryKey*>( pRegistryKey)->createKey(L\"\/com.sun.star.comp.ole.OleConverterVar1\/UNO\/SERVICES\");\n xNewKey->createKey(L\"com.sun.star.bridge.OleBridgeSupplierVar1\");\n\n xNewKey =\n reinterpret_cast<XRegistryKey*>( pRegistryKey)->createKey(L\"\/com.sun.star.comp.ole.OleClient\/UNO\/SERVICES\");\n xNewKey->createKey(L\"com.sun.star.bridge.OleObjectFactory\");\n\n xNewKey =\n reinterpret_cast<XRegistryKey*>( pRegistryKey)->createKey(L\"\/com.sun.star.comp.ole.OleServer\/UNO\/SERVICES\");\n xNewKey->createKey(L\"com.sun.star.bridge.OleApplicationRegistration\");\n\n return sal_True;\n }\n catch (InvalidRegistryException &)\n {\n OSL_ENSURE( sal_False, \"### InvalidRegistryException!\" );\n }\n }\n return sal_False;\n}\n\nextern \"C\" void SAL_CALL component_getImplementationEnvironment(\n const sal_Char ** ppEnvTypeName, uno_Environment ** ppEnv )\n{\n *ppEnvTypeName = CPPU_CURRENT_LANGUAGE_BINDING_NAME;\n}\n\n\nextern \"C\" sal_Bool component_canUnload( TimeValue* libUnused)\n{\n return globalModuleCount.canUnload( &globalModuleCount, libUnused);\n}\n<commit_msg>INTEGRATION: CWS jl5vba (1.2.244); FILE MERGED 2004\/01\/19 11:06:44 jl 1.2.244.1: #112439# join cws ab02vba<commit_after>\/*************************************************************************\n *\n * $RCSfile: servreg.cxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: obo $ $Date: 2004-03-17 13:08:41 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n#include <rtl\/unload.h>\n#include <osl\/time.h>\n#include \"ole2uno.hxx\"\n#include \"servprov.hxx\"\n#ifndef _RTL_USTRING_\n#include <rtl\/ustring>\n#endif\n#ifndef _CPPUHELPER_FACTORY_HXX_\n#include <cppuhelper\/factory.hxx>\n#endif\nusing namespace rtl;\nusing namespace ole_adapter;\nusing namespace cppu;\n\nnamespace ole_adapter\n{\nrtl_StandardModuleCount globalModuleCount= MODULE_COUNT_INIT;\n\n\n\nReference<XInterface> SAL_CALL ConverterProvider_CreateInstance2( const Reference<XMultiServiceFactory> & xSMgr)\n throw(Exception)\n{\n Reference<XInterface> xService = *new OleConverter_Impl2( xSMgr);\n return xService;\n}\n\nReference<XInterface> SAL_CALL ConverterProvider_CreateInstanceVar1( const Reference<XMultiServiceFactory> & xSMgr)\n throw(Exception)\n{\n Reference<XInterface> xService = *new OleConverter_Impl2( xSMgr, UNO_OBJECT_WRAPPER_REMOTE_OPT, IUNKNOWN_WRAPPER_IMPL);\n return xService;\n}\n\nReference<XInterface> SAL_CALL OleClient_CreateInstance( const Reference<XMultiServiceFactory> & xSMgr)\n throw(Exception)\n{\n Reference<XInterface> xService = *new OleClient_Impl( xSMgr);\n return xService;\n}\n\nReference<XInterface> SAL_CALL OleServer_CreateInstance( const Reference<XMultiServiceFactory> & xSMgr)\n throw (Exception)\n{\n Reference<XInterface > xService = *new OleServer_Impl(xSMgr);\n return xService;\n}\n} \/\/ end namespace\n\nextern \"C\" void * SAL_CALL component_getFactory(\n const sal_Char * pImplName, void * pServiceManager, void * pRegistryKey )\n{\n void * pRet = 0;\n\n OUString aImplName( OUString::createFromAscii( pImplName ) );\n Reference< XSingleServiceFactory > xFactory;\n Sequence<OUString> seqServiceNames;\n if (pServiceManager && aImplName.equals( L\"com.sun.star.comp.ole.OleConverter2\" ))\n {\n xFactory= createSingleFactory( reinterpret_cast< XMultiServiceFactory*>(pServiceManager),\n OUString( RTL_CONSTASCII_USTRINGPARAM(\"com.sun.star.comp.ole.OleConverter2\")),\n ConverterProvider_CreateInstance2, seqServiceNames,\n &globalModuleCount.modCnt );\n }\n else if (pServiceManager && aImplName.equals( L\"com.sun.star.comp.ole.OleConverterVar1\" ))\n {\n xFactory= createSingleFactory( reinterpret_cast<XMultiServiceFactory*>(pServiceManager),\n OUString( RTL_CONSTASCII_USTRINGPARAM(\"com.sun.star.comp.ole.OleConverterVar1\")),\n ConverterProvider_CreateInstanceVar1, seqServiceNames,\n &globalModuleCount.modCnt );\n }\n else if(pServiceManager && aImplName.equals(L\"com.sun.star.comp.ole.OleClient\"))\n {\n xFactory= createSingleFactory( reinterpret_cast< XMultiServiceFactory*>(pServiceManager),\n OUString( RTL_CONSTASCII_USTRINGPARAM(\"com.sun.star.comp.ole.OleClient\")),\n OleClient_CreateInstance, seqServiceNames,\n &globalModuleCount.modCnt);\n }\n else if(pServiceManager && aImplName.equals(L\"com.sun.star.comp.ole.OleServer\"))\n {\n xFactory= createOneInstanceFactory( reinterpret_cast< XMultiServiceFactory*>(pServiceManager),\n OUString( RTL_CONSTASCII_USTRINGPARAM(\"com.sun.star.comp.ole.OleServer\")),\n OleServer_CreateInstance, seqServiceNames,\n &globalModuleCount.modCnt);\n }\n\n if (xFactory.is())\n {\n xFactory->acquire();\n pRet = xFactory.get();\n }\n\n return pRet;\n}\n\n\nextern \"C\" sal_Bool SAL_CALL component_writeInfo( void * pServiceManager, void * pRegistryKey )\n{\n if (pRegistryKey)\n {\n try\n {\n \/\/deprecated\n Reference<XRegistryKey> xNewKey =\n reinterpret_cast<XRegistryKey*>( pRegistryKey)->createKey(L\"\/com.sun.star.comp.ole.OleConverter2\/UNO\/SERVICES\");\n xNewKey->createKey(L\"com.sun.star.bridge.OleBridgeSupplier2\");\n\n xNewKey->createKey(L\"com.sun.star.bridge.oleautomation.BridgeSupplier\");\n\n \/\/deprecated\n xNewKey =\n reinterpret_cast<XRegistryKey*>( pRegistryKey)->createKey(L\"\/com.sun.star.comp.ole.OleConverterVar1\/UNO\/SERVICES\");\n xNewKey->createKey(L\"com.sun.star.bridge.OleBridgeSupplierVar1\");\n\n \/\/deprecated\n xNewKey =\n reinterpret_cast<XRegistryKey*>( pRegistryKey)->createKey(L\"\/com.sun.star.comp.ole.OleClient\/UNO\/SERVICES\");\n xNewKey->createKey(L\"com.sun.star.bridge.OleObjectFactory\");\n\n xNewKey->createKey(L\"com.sun.star.bridge.oleautomation.Factory\");\n \/\/deprecated\n xNewKey =\n reinterpret_cast<XRegistryKey*>( pRegistryKey)->createKey(L\"\/com.sun.star.comp.ole.OleServer\/UNO\/SERVICES\");\n xNewKey->createKey(L\"com.sun.star.bridge.OleApplicationRegistration\");\n\n xNewKey->createKey(L\"com.sun.star.bridge.oleautomation.ApplicationRegistration\");\n\n return sal_True;\n }\n catch (InvalidRegistryException &)\n {\n OSL_ENSURE( sal_False, \"### InvalidRegistryException!\" );\n }\n }\n return sal_False;\n}\n\nextern \"C\" void SAL_CALL component_getImplementationEnvironment(\n const sal_Char ** ppEnvTypeName, uno_Environment ** ppEnv )\n{\n *ppEnvTypeName = CPPU_CURRENT_LANGUAGE_BINDING_NAME;\n}\n\n\nextern \"C\" sal_Bool component_canUnload( TimeValue* libUnused)\n{\n return globalModuleCount.canUnload( &globalModuleCount, libUnused);\n}\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n#include <algorithm>\n#include <vector>\n#include <complex>\n\n#include <sndfile.hh>\n\n#define kiss_fft_scalar double\n#include \"kiss_fft.h\"\n\nint main()\n{\n const int I = 2;\n const int D = 1;\n const int N = 256;\n const int M = I*N\/D;\n const int L = N\/8;\n\n kiss_fft_cfg fwd = kiss_fft_alloc(N, 0, NULL, NULL);\n kiss_fft_cfg inv = kiss_fft_alloc(M, 1, NULL, NULL);\n\n const std::string infilename = \"sine_48000_pcm32.wav\";\n const std::string outfilename = \"orig.wav\";\n const std::string resfilename = \"res.wav\";\n SndfileHandle infile(infilename);\n SndfileHandle outfile(outfilename, SFM_WRITE, infile.format(), infile.channels(), infile.samplerate());\n SndfileHandle resfile(resfilename, SFM_WRITE, infile.format(), infile.channels(), infile.samplerate() * I\/D);\n\n std::vector<double> buffer(N);\n\n std::vector<std::complex<double>> fwd_fft_in_buffer(N);\n std::vector<std::complex<double>> fwd_fft_out_buffer(N);\n\n std::vector<std::complex<double>> bwd_fft_in_buffer(M);\n std::vector<std::complex<double>> bwd_fft_out_buffer(M);\n\n \/* prepend 2L zeros *\/\n for (int i=0; i < 2*L; ++i) {\n buffer[i] = 0;\n }\n\n while (sf_count_t readcount = infile.read(buffer.data() + 2*L, N - 2*L))\n { \n \/* Store original samples *\/\n outfile.write(buffer.data() + 2*L, std::min(static_cast<int>(readcount), N - 2*L));\n\n \/* Create FFT input buffer: 1 block of N samples with 2*L overlap *\/\n for(int i=0; i < std::min(static_cast<int>(readcount) + 2*L, N); ++i) {\n fwd_fft_in_buffer[i] = std::complex<double>(buffer[i], 0.0);\n std::cout << i << \": \" << fwd_fft_in_buffer[i] << \"\\n\";\n }\n std::cout << \"\\n\";\n\n \/* Forward N points FFT *\/\n kiss_fft(fwd, (kiss_fft_cpx *)fwd_fft_in_buffer.data(), (kiss_fft_cpx *)(fwd_fft_out_buffer.data()));\n for(int i=0; i < N; ++i) {\n std::cout << \"FFT: \" << i << \" \" << fwd_fft_out_buffer[i] << \"\\n\";\n }\n\n \/* Create IFFT input buffer *\/\n for(int i=0; i < N\/2; ++i) {\n bwd_fft_in_buffer[i] = static_cast<double>(I\/D) * fwd_fft_out_buffer[i];\n }\n for(int i=N\/2; i <= M - N\/2; ++i) {\n bwd_fft_in_buffer[i] = static_cast<double>(I\/D) * std::complex<double>(0.0, 0.0);\n }\n for(int i=M - N\/2 + 1; i < M; ++i) {\n bwd_fft_in_buffer[i] = static_cast<double>(I\/D) * fwd_fft_out_buffer[i + M\/2];\n }\n\n \/* IFFT *\/\n kiss_fft(inv, (kiss_fft_cpx *)bwd_fft_in_buffer.data(), (kiss_fft_cpx *)(bwd_fft_out_buffer.data()));\n for(int i=0; i < M; ++i) {\n std::cout << \"IFFT: \" << i << \" \" << bwd_fft_out_buffer[i] << \"\\n\";\n }\n\n \/* Discard first and last L points and store the rest of the real vector *\/\n std::vector<double> res(M - 2*L);\n int j = L;\n for(int i=0; i < M - 2*L; ++i) {\n res[i] = bwd_fft_out_buffer[j++].real();\n }\n resfile.write(res.data(), res.size());\n\n \/* Shift vector to the left 2*L times *\/\n std::rotate(buffer.begin(), buffer.begin() + N - 2*L, buffer.end());\n };\n\n kiss_fft_free(fwd);\n kiss_fft_free(inv);\n\n return 0;\n}\n<commit_msg>Fix the overlap factor after the FFT.<commit_after>#include <iostream>\n#include <algorithm>\n#include <vector>\n#include <complex>\n\n#include <sndfile.hh>\n\n#define kiss_fft_scalar double\n#include \"kiss_fft.h\"\n\nint main()\n{\n const int I = 2;\n const int D = 1;\n const int N = 256;\n const int M = I*N\/D;\n const int L = N\/8;\n\n kiss_fft_cfg fwd = kiss_fft_alloc(N, 0, NULL, NULL);\n kiss_fft_cfg inv = kiss_fft_alloc(M, 1, NULL, NULL);\n\n const std::string infilename = \"sine_48000_pcm32.wav\";\n const std::string outfilename = \"orig.wav\";\n const std::string resfilename = \"res.wav\";\n SndfileHandle infile(infilename);\n SndfileHandle outfile(outfilename, SFM_WRITE, infile.format(), infile.channels(), infile.samplerate());\n SndfileHandle resfile(resfilename, SFM_WRITE, infile.format(), infile.channels(), infile.samplerate() * I\/D);\n\n std::vector<double> buffer(N);\n\n std::vector<std::complex<double>> fwd_fft_in_buffer(N);\n std::vector<std::complex<double>> fwd_fft_out_buffer(N);\n\n std::vector<std::complex<double>> bwd_fft_in_buffer(M);\n std::vector<std::complex<double>> bwd_fft_out_buffer(M);\n\n \/* prepend 2L zeros *\/\n for (int i=0; i < 2*L; ++i) {\n buffer[i] = 0;\n }\n\n while (sf_count_t readcount = infile.read(buffer.data() + 2*L, N - 2*L))\n { \n \/* Store original samples *\/\n outfile.write(buffer.data() + 2*L, std::min(static_cast<int>(readcount), N - 2*L));\n\n \/* Create FFT input buffer: 1 block of N samples with 2*L overlap *\/\n for(int i=0; i < std::min(static_cast<int>(readcount) + 2*L, N); ++i) {\n fwd_fft_in_buffer[i] = std::complex<double>(buffer[i], 0.0);\n std::cout << i << \": \" << fwd_fft_in_buffer[i] << \"\\n\";\n }\n std::cout << \"\\n\";\n\n \/* Forward N points FFT *\/\n kiss_fft(fwd, (kiss_fft_cpx *)fwd_fft_in_buffer.data(), (kiss_fft_cpx *)(fwd_fft_out_buffer.data()));\n for(int i=0; i < N; ++i) {\n std::cout << \"FFT: \" << i << \" \" << fwd_fft_out_buffer[i] << \"\\n\";\n }\n\n \/* Create IFFT input buffer *\/\n for(int i=0; i < N\/2; ++i) {\n bwd_fft_in_buffer[i] = static_cast<double>(I\/D) * fwd_fft_out_buffer[i];\n }\n for(int i=N\/2; i <= M - N\/2; ++i) {\n bwd_fft_in_buffer[i] = static_cast<double>(I\/D) * std::complex<double>(0.0, 0.0);\n }\n for(int i=M - N\/2 + 1; i < M; ++i) {\n bwd_fft_in_buffer[i] = static_cast<double>(I\/D) * fwd_fft_out_buffer[i + M\/2];\n }\n\n \/* Backward M points IFFT *\/\n kiss_fft(inv, (kiss_fft_cpx *)bwd_fft_in_buffer.data(), (kiss_fft_cpx *)(bwd_fft_out_buffer.data()));\n for(int i=0; i < M; ++i) {\n std::cout << \"IFFT: \" << i << \" \" << bwd_fft_out_buffer[i] << \"\\n\";\n }\n\n \/* Discard first and last L points and store the rest of the real vector *\/\n std::vector<double> res(M - 2*I\/D*L);\n int j = I\/D*L;\n for(int i=0; i < M - 2*I\/D*L; ++i) {\n res[i] = bwd_fft_out_buffer[j++].real();\n }\n resfile.write(res.data(), res.size());\n\n \/* Shift vector to the left 2*L times *\/\n std::rotate(buffer.begin(), buffer.begin() + N - 2*L, buffer.end());\n };\n\n kiss_fft_free(fwd);\n kiss_fft_free(inv);\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>#ifndef __TRIANGULATE_QUADS_STRUCT_HPP_INCLUDED\n#define __TRIANGULATE_QUADS_STRUCT_HPP_INCLUDED\n\n#include \"code\/ylikuutio\/geometry\/spherical_terrain_struct.hpp\"\n\n\/\/ Include standard headers\n#include <cmath> \/\/ NAN, std::isnan, std::pow\n#include <cstddef> \/\/ std::size_t\n#include <string> \/\/ std::string\n\nnamespace yli\n{\n namespace geometry\n {\n typedef struct TriangulateQuadsStruct\n {\n TriangulateQuadsStruct()\n : image_width(0), image_height(0), x_step(1), z_step(1), should_ylikuutio_use_real_texture_coordinates(true), sphere_radius(NAN)\n {\n \/\/ constructor.\n }\n std::size_t image_width;\n std::size_t image_height;\n std::size_t x_step;\n std::size_t z_step;\n std::string triangulation_type;\n bool should_ylikuutio_use_real_texture_coordinates;\n double sphere_radius;\n yli::geometry::SphericalTerrainStruct spherical_terrain_struct;\n } TriangulateQuadsStruct;\n }\n}\n\n#endif\n<commit_msg>Split unnecessarily long line into multiple lines.<commit_after>#ifndef __TRIANGULATE_QUADS_STRUCT_HPP_INCLUDED\n#define __TRIANGULATE_QUADS_STRUCT_HPP_INCLUDED\n\n#include \"code\/ylikuutio\/geometry\/spherical_terrain_struct.hpp\"\n\n\/\/ Include standard headers\n#include <cmath> \/\/ NAN, std::isnan, std::pow\n#include <cstddef> \/\/ std::size_t\n#include <string> \/\/ std::string\n\nnamespace yli\n{\n namespace geometry\n {\n typedef struct TriangulateQuadsStruct\n {\n TriangulateQuadsStruct()\n : image_width(0),\n image_height(0),\n x_step(1),\n z_step(1),\n should_ylikuutio_use_real_texture_coordinates(true),\n sphere_radius(NAN)\n {\n \/\/ constructor.\n }\n std::size_t image_width;\n std::size_t image_height;\n std::size_t x_step;\n std::size_t z_step;\n std::string triangulation_type;\n bool should_ylikuutio_use_real_texture_coordinates;\n double sphere_radius;\n yli::geometry::SphericalTerrainStruct spherical_terrain_struct;\n } TriangulateQuadsStruct;\n }\n}\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ Copyright (c) 2013 Christoph Malek\n\/\/ See LICENSE for more information.\n\/\/\n\n#ifndef RJ_CORE_GAME_GAME_HPP\n#define RJ_CORE_GAME_GAME_HPP\n\n\n#include \"game_updater.hpp\"\n#include \"game_window.hpp\"\n\n\nnamespace rj\n{\n\tclass game\n\t{\n\t\tgame_window& m_window;\n\n\tpublic:\n\t\tgame(game_window& window) :\n\t\t\tm_window{window}\n\t\t{\n\t\t\tm_window.updater().on_update.add_func([this](dur duration){this->update(duration);});\n\t\t\tm_window.updater().on_render.add_func([this]{this->render();});\n\t\t}\n\n\t\tvoid update(dur duration)\n\t\t{\n\n\t\t}\n\n\t\tvoid render()\n\t\t{\n\n\t\t}\n\n\t\tvoid render_object(const sf::Drawable& object)\n\t\t{m_window.draw(object);}\n\t};\n}\n\n\n#endif \/\/ RJ_CORE_GAME_GAME_HPP\n<commit_msg>using += operator<commit_after>\/\/\n\/\/ Copyright (c) 2013 Christoph Malek\n\/\/ See LICENSE for more information.\n\/\/\n\n#ifndef RJ_CORE_GAME_GAME_HPP\n#define RJ_CORE_GAME_GAME_HPP\n\n\n#include \"game_updater.hpp\"\n#include \"game_window.hpp\"\n\n\nnamespace rj\n{\n\tclass game\n\t{\n\t\tgame_window& m_window;\n\n\tpublic:\n\t\tgame(game_window& window) :\n\t\t\tm_window{window}\n\t\t{\n\t\t\tm_window.updater().on_update += [this](dur duration){this->update(duration);};\n\t\t\tm_window.updater().on_render += [this]{this->render();};\n\t\t}\n\n\t\tvoid update(dur duration)\n\t\t{\n\n\t\t}\n\n\t\tvoid render()\n\t\t{\n\n\t\t}\n\n\t\tvoid render_object(const sf::Drawable& object)\n\t\t{m_window.draw(object);}\n\t};\n}\n\n\n#endif \/\/ RJ_CORE_GAME_GAME_HPP\n<|endoftext|>"} {"text":"<commit_before>\/*\n * preprocessor.hpp\n *\n * Created on: Jun 29, 2015\n * Author: hugo\n *\/\n\n#ifndef SRC_PREPROCESSOR_HPP_\n#define SRC_PREPROCESSOR_HPP_\n\n#include <cassert>\n#include <string>\n\n#include \"..\/..\/log\/easylogging++.h\"\n#include \"mapped_stream.hpp\"\n#include \"splitterbuffer.hpp\"\n\nnamespace mflash{\n\n\ntemplate <class IdType>\nclass EdgeConversor{\n\tpublic:\n\t\ttemplate <class Splitter>\n\t\tstatic void process (const std::string file_graph, const char separator, const bool edgelist, Splitter &splitter);\n};\n\ntemplate <class IdType>\ntemplate <class Splitter>\nvoid EdgeConversor<IdType>::process(const std::string file_graph, const char separator, const bool edgelist, Splitter &splitter){\n\tMappedStream in(file_graph);\n\n\tIdType v1 = \t\t0;\n\tIdType v2 = \t\t0;\n\tbool isQuantity = !edgelist;\n\tbool isInVertice = \ttrue;\n\n\tconst char comment = '#';\n\tconst char comment2 = '%';\n\tconst char end_line = '\\n';\n\tconst char end_line2 = '\\r';\n\t\/\/char separator = ' ';\n\tconst char separator2 = '\\t';\n\tconst char separator3 = ' ';\n\n\tEmptyField value;\n\n\/*\n\n\tconst int64 MEGABYTE = 1024 * 1024;\n\tconst int64 STEP_INFO = 500 * MEGABYTE;\n*\/\n\n\twhile(in.has_remain()){\n\t\tchar b = in.next();\n\t\t\/*if( (in.current_ptr-in.ptr) % STEP_INFO ==0){\n\t\t\tLOG(INFO)<<\"Processed: \" << (in.current_ptr-in.ptr) \/ MEGABYTE << \"MB\";\n\t\t}*\/\n\t\t\/\/removing comment line\n\t if(b == comment || b == comment2){\n\t\twhile(b != end_line){\n\t\t b = in.next();\n\t\t}\n\t\tb = in.next();\n\t\t\/\/when the line content \\n\\r\n\t\twhile( b == end_line || b==end_line2){\n\t\t\tb = in.next();\n\t\t}\n\t\tin.set_position(in.position()- sizeof(char));\n\t\tcontinue;\n\t }\n\t if (b == separator || b == separator2 || b == separator3){\n\t\tif(!isInVertice && !isQuantity){ \/\/\n\t\t\tsplitter.add(v1, v2, &value);\n\t\t}else{\n\t\t\tif(isInVertice) isInVertice = false;\n\t\t\telse if(isQuantity) isQuantity = false;\n\t\t}\n\t\tv2 = 0;\n\t\tcontinue;\n\t }\n\t\tif (b == end_line || b == end_line2){\n\t\t\tb = in.next();\n\t\t\t\/\/when the line content \\n\\r\n\t\t\twhile( b == end_line || b==end_line2){\n\t\t\t\tb = in.next();\n\t\t\t}\n\t\t\tin.set_position(in.position()- sizeof(char));\n\n\t\t\tif(!isQuantity || edgelist){\n\t\t\t\tsplitter.add(v1, v2, &value);\n\t\t\t}\n\t\t\tv1 = 0;\n\t\t\tv2 = 0;\n\t\t\tisInVertice = true;\n\t\t\tisQuantity = !edgelist;\n\t\t\tcontinue;\n\t\t}\n\t\tif(b<48 || b > 57){\n\t\t\tLOG(ERROR) << \"The character '\" << b << \"' was not recognized.\";\n\t\t\tassert(false);\n\t\t}\n\n\t\tif(isInVertice){\n\t\t\tv1 = (v1<< 3) + (v1 << 1) + (0xF & b);\n\t\t}else{\n\t\t\tv2 = (v2<< 3) + (v2 << 1) + (0xF & b);\n\t\t}\n\t}\n\tin.close_stream();\n\tsplitter.flush();\n\tLOG(INFO)<<\"Graph Binarization was succesfully\";\n}\n\n\n}\n\n\n#endif \/* SRC_PREPROCESSOR_HPP_ *\/\n<commit_msg>Solving mistake with \\r\\n<commit_after>\/*\n * preprocessor.hpp\n *\n * Created on: Jun 29, 2015\n * Author: hugo\n *\/\n\n#ifndef SRC_PREPROCESSOR_HPP_\n#define SRC_PREPROCESSOR_HPP_\n\n#include <cassert>\n#include <string>\n\n#include \"..\/..\/log\/easylogging++.h\"\n#include \"mapped_stream.hpp\"\n#include \"splitterbuffer.hpp\"\n\nnamespace mflash{\n\n\ntemplate <class IdType>\nclass EdgeConversor{\n\tpublic:\n\t\ttemplate <class Splitter>\n\t\tstatic void process (const std::string file_graph, const char separator, const bool edgelist, Splitter &splitter);\n};\n\ntemplate <class IdType>\ntemplate <class Splitter>\nvoid EdgeConversor<IdType>::process(const std::string file_graph, const char separator, const bool edgelist, Splitter &splitter){\n\tMappedStream in(file_graph);\n\n\tIdType v1 = \t\t0;\n\tIdType v2 = \t\t0;\n\tbool isQuantity = !edgelist;\n\tbool isInVertice = \ttrue;\n\n\tconst char comment = '#';\n\tconst char comment2 = '%';\n\tconst char end_line = '\\n';\n\tconst char end_line2 = '\\r';\n\t\/\/char separator = ' ';\n\tconst char separator2 = '\\t';\n\tconst char separator3 = ' ';\n\n\tEmptyField value;\n\n\/*\n\n\tconst int64 MEGABYTE = 1024 * 1024;\n\tconst int64 STEP_INFO = 500 * MEGABYTE;\n*\/\n\n\twhile(in.has_remain()){\n\t\tchar b = in.next();\n\t\t\/*if( (in.current_ptr-in.ptr) % STEP_INFO ==0){\n\t\t\tLOG(INFO)<<\"Processed: \" << (in.current_ptr-in.ptr) \/ MEGABYTE << \"MB\";\n\t\t}*\/\n\t\t\/\/removing comment line\n\t if(b == comment || b == comment2){\n\t\twhile(b != end_line){\n\t\t b = in.next();\n\t\t}\n\t\tb = in.next();\n\t\t\/\/when the line content \\n\\r\n\t\twhile( b == end_line || b==end_line2){\n\t\t\tb = in.next();\n\t\t}\n\t\tin.set_position(in.position()- sizeof(char));\n\t\tcontinue;\n\t }\n\t if (b == separator || b == separator2 || b == separator3){\n\t\tif(!isInVertice && !isQuantity){ \/\/\n\t\t\tsplitter.add(v1, v2, &value);\n\t\t}else{\n\t\t\tif(isInVertice) isInVertice = false;\n\t\t\telse if(isQuantity) isQuantity = false;\n\t\t}\n\t\tv2 = 0;\n\t\tcontinue;\n\t }\n\t\tif (b == end_line || b == end_line2){\n\t\t\tb = in.next();\n\t\t\t\/\/when the line content \\r\\n\n\t\t\twhile( b == end_line || b==end_line2){\n\t\t\t\tb = in.next();\n\t\t\t}\n\t\t\tin.set_position(in.position()- sizeof(char));\n\n\t\t\tif(!isQuantity || edgelist){\n\t\t\t\tsplitter.add(v1, v2, &value);\n\t\t\t}\n\t\t\tv1 = 0;\n\t\t\tv2 = 0;\n\t\t\tisInVertice = true;\n\t\t\tisQuantity = !edgelist;\n\t\t\tcontinue;\n\t\t}\n\t\tif(b<48 || b > 57){\n\t\t\tLOG(ERROR) << \"The character '\" << b << \"' was not recognized.\";\n\t\t\tassert(false);\n\t\t}\n\n\t\tif(isInVertice){\n\t\t\tv1 = (v1<< 3) + (v1 << 1) + (0xF & b);\n\t\t}else{\n\t\t\tv2 = (v2<< 3) + (v2 << 1) + (0xF & b);\n\t\t}\n\t}\n\tin.close_stream();\n\tsplitter.flush();\n\tLOG(INFO)<<\"Graph Binarization was succesfully\";\n}\n\n\n}\n\n\n#endif \/* SRC_PREPROCESSOR_HPP_ *\/\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ Copyright (c) 2013-2014 Christoph Malek\n\/\/ See LICENSE for more information.\n\/\/\n\n#ifndef RJ_UI_BUTTON_HPP\n#define RJ_UI_BUTTON_HPP\n\n\n#include \"widget.hpp\"\n#include <rectojump\/global\/common.hpp>\n#include <rectojump\/shared\/input.hpp>\n\n#include <mlk\/signals_slots\/slot.h>\n#include <mlk\/types\/types.h>\n\n\nnamespace rj\n{\n\tnamespace ui\n\t{\n\t\tclass button : public ui::widget\n\t\t{\n\t\tprotected:\n\t\t\tsf::RectangleShape m_shape;\n\t\t\tsf::Text m_text;\n\t\t\tbool m_hover{false};\n\t\t\tbool m_press{false};\n\n\t\tprivate:\n\t\t\tsf::RectangleShape m_restore_shape;\n\n\t\tpublic:\n\t\t\tmlk::slot<> on_clicked;\n\t\t\tmlk::slot<> on_hovered;\n\n\t\t\tbutton(const vec2f& size = {0.f, 0.f}, const vec2f& pos = {0.f, 0.f}) :\n\t\t\t\tm_shape{size}\n\t\t\t{\n\t\t\t\tm_shape.setPosition(pos);\n\t\t\t\tthis->init_base();\n\t\t\t}\n\n\t\t\tbutton(const vec2f& size, const std::string& text, const sf::Font& font, const sf::Color& fontcolor = {}) :\n\t\t\t\tbutton{size}\n\t\t\t{\n\t\t\t\tm_text.setString(text);\n\t\t\t\tm_text.setFont(font);\n\t\t\t\tm_text.setColor(fontcolor);\n\t\t\t\tthis->calculate_textpos();\n\t\t\t}\n\n\t\t\tvoid update(dur)\n\t\t\t{\n\t\t\t\t\/\/ check states\n\t\t\t\tif(m_hover) this->on_hover();\n\t\t\t\telse this->on_hover_end();\n\n\t\t\t\tif(m_press) this->on_press();\n\t\t\t\telse this->on_press_end();\n\n\t\t\t\t\/\/ collision\n\t\t\t\tauto bounds(m_shape.getGlobalBounds());\n\t\t\t\tauto mousebounds(inp::get_mousebounds<true>());\n\n\t\t\t\tif(bounds.intersects(mousebounds))\n\t\t\t\t\tm_hover = true;\n\t\t\t\telse m_hover = false;\n\n\t\t\t\tif(m_hover)\n\t\t\t\t{\n\t\t\t\t\tif(inp::is_btn_pressed(btn::Left))\n\t\t\t\t\t\tm_press = true;\n\t\t\t\t\telse if(inp::was_real_mousepress_left())\n\t\t\t\t\t\tthis->on_clicked();\n\t\t\t\t\telse m_press = false;\n\t\t\t\t}\n\t\t\t\telse m_press = false;\n\t\t\t}\n\n\t\t\tvoid setText(const std::string& text) noexcept\n\t\t\t{m_text.setString(text); this->calculate_textpos();}\n\n\t\t\tvoid setFont(const sf::Font& font) noexcept\n\t\t\t{m_text.setFont(font); this->calculate_textpos();}\n\n\t\t\tvoid setFontColor(const sf::Color& color) noexcept\n\t\t\t{m_text.setColor(color);}\n\n\t\t\tvoid setFontSize(mlk::uint size) noexcept\n\t\t\t{m_text.setCharacterSize(size); this->calculate_textpos();}\n\n\t\t\tvoid setColor(const sf::Color& color) noexcept\n\t\t\t{m_shape.setFillColor(color); m_restore_shape.setFillColor(color);}\n\n\t\t\tvoid setOutlineThickness(float thickness) noexcept\n\t\t\t{m_shape.setOutlineThickness(thickness); m_restore_shape.setOutlineThickness(thickness);}\n\n\t\t\tvoid setOutlineColor(const sf::Color& color) noexcept\n\t\t\t{m_shape.setOutlineColor(color); m_restore_shape.setOutlineColor(color);}\n\n\t\t\tvoid setPosition(const vec2f& pos) noexcept\n\t\t\t{m_shape.setPosition(pos); m_restore_shape.setPosition(pos); this->calculate_textpos();}\n\n\t\t\tvoid setOrigin(const vec2f& pos) noexcept\n\t\t\t{m_shape.setOrigin(pos); m_restore_shape.setOrigin(pos); this->calculate_textpos();}\n\n\t\t\tvoid setSize(const vec2f& size) noexcept\n\t\t\t{m_shape.setSize(size); m_restore_shape.setSize(size); this->calculate_textpos();}\n\n\t\t\tvoid setTexture(sf::Texture* tx) noexcept\n\t\t\t{m_shape.setTexture(tx); m_restore_shape.setTexture(tx);}\n\n\t\t\tvoid move(const vec2f& offset) noexcept\n\t\t\t{m_shape.move(offset); m_restore_shape.move(offset); this->calculate_textpos();}\n\n\t\t\tvoid rotate(float angle) noexcept\n\t\t\t{m_shape.rotate(angle); m_restore_shape.rotate(angle); this->calculate_textpos();}\n\n\t\t\tstd::string getText() const noexcept\n\t\t\t{return m_text.getString();}\n\n\t\t\tconst sf::Font* getFont() const noexcept\n\t\t\t{return m_text.getFont();}\n\n\t\t\tconst sf::Color& getFontColor() const noexcept\n\t\t\t{return m_text.getColor();}\n\n\t\t\tmlk::uint getFontSize() const noexcept\n\t\t\t{return m_text.getCharacterSize();}\n\n\t\t\tconst sf::Color& getColor() const noexcept\n\t\t\t{return m_shape.getFillColor();}\n\n\t\t\tfloat getOutlineThickness() const noexcept\n\t\t\t{return m_shape.getOutlineThickness();}\n\n\t\t\tconst sf::Color& getOutlineColor() const noexcept\n\t\t\t{return m_shape.getOutlineColor();}\n\n\t\t\tconst vec2f& getPosition() const noexcept\n\t\t\t{return m_shape.getPosition();}\n\n\t\t\tconst vec2f& getOrigin() const noexcept\n\t\t\t{return m_shape.getOrigin();}\n\n\t\t\tconst vec2f& getSize() const noexcept\n\t\t\t{return m_shape.getSize();}\n\n\t\t\tconst sf::Texture* getTexture() const noexcept\n\t\t\t{return m_shape.getTexture();}\n\n\t\t\tbool pressed() const noexcept\n\t\t\t{return m_press;}\n\n\t\t\tbool hover() const noexcept\n\t\t\t{return m_hover;}\n\n\t\tprotected:\n\t\t\tvirtual void init()\n\t\t\t{\n\t\t\t\t\/\/ init the rect\n\t\t\t}\n\n\t\t\tvoid init_base()\n\t\t\t{\n\t\t\t\tthis->init();\n\t\t\t\tthis->create_restore_shape();\n\t\t\t}\n\n\t\t\tvirtual void on_hover()\n\t\t\t{\n\t\t\t\t\/\/ do something on hover\n\t\t\t}\n\n\t\t\tvirtual void on_hover_end()\n\t\t\t{\n\t\t\t\tif(m_press) return;\n\t\t\t\tthis->restore_origin();\n\t\t\t}\n\n\t\t\tvirtual void on_press()\n\t\t\t{\n\t\t\t\t\/\/ do something on press\n\t\t\t}\n\n\t\t\tvirtual void on_press_end()\n\t\t\t{\n\t\t\t\tif(m_hover) return;\n\t\t\t\tthis->restore_origin();\n\t\t\t}\n\n\t\t\tvoid create_restore_shape() noexcept\n\t\t\t{m_restore_shape = m_shape;}\n\n\t\t\tvoid restore_origin() noexcept\n\t\t\t{m_shape = m_restore_shape;}\n\n\t\t\tvirtual void draw(sf::RenderTarget& target, sf::RenderStates states) const override\n\t\t\t{\n\t\t\t\ttarget.draw(m_shape, states);\n\t\t\t\ttarget.draw(m_text, states);\n\t\t\t}\n\n\t\tprivate:\n\t\t\tvoid calculate_textpos()\n\t\t\t{\n\t\t\t\tauto shape_bounds(m_shape.getGlobalBounds());\n\t\t\t\tauto text_bounds(m_text.getGlobalBounds());\n\t\t\t\tm_text.setOrigin(text_bounds.width \/ 2.f, text_bounds.height \/ 2.f);\n\t\t\t\tm_text.setPosition(shape_bounds.left + shape_bounds.width \/ 2.f, shape_bounds.top + shape_bounds.height \/ 2.f);\n\t\t\t}\n\t\t};\n\t}\n}\n\n\n#endif \/\/ RJ_UI_BUTTON_HPP\n<commit_msg>ui > button: changed the if statements<commit_after>\/\/\n\/\/ Copyright (c) 2013-2014 Christoph Malek\n\/\/ See LICENSE for more information.\n\/\/\n\n#ifndef RJ_UI_BUTTON_HPP\n#define RJ_UI_BUTTON_HPP\n\n\n#include \"widget.hpp\"\n#include <rectojump\/global\/common.hpp>\n#include <rectojump\/shared\/input.hpp>\n\n#include <mlk\/signals_slots\/slot.h>\n#include <mlk\/types\/types.h>\n\n\nnamespace rj\n{\n\tnamespace ui\n\t{\n\t\tclass button : public ui::widget\n\t\t{\n\t\tprotected:\n\t\t\tsf::RectangleShape m_shape;\n\t\t\tsf::Text m_text;\n\t\t\tbool m_hover{false};\n\t\t\tbool m_press{false};\n\n\t\tprivate:\n\t\t\tsf::RectangleShape m_restore_shape;\n\n\t\tpublic:\n\t\t\tmlk::slot<> on_clicked;\n\t\t\tmlk::slot<> on_hovered;\n\n\t\t\tbutton(const vec2f& size = {0.f, 0.f}, const vec2f& pos = {0.f, 0.f}) :\n\t\t\t\tm_shape{size}\n\t\t\t{\n\t\t\t\tm_shape.setPosition(pos);\n\t\t\t\tthis->init_base();\n\t\t\t}\n\n\t\t\tbutton(const vec2f& size, const std::string& text, const sf::Font& font, const sf::Color& fontcolor = {}) :\n\t\t\t\tbutton{size}\n\t\t\t{\n\t\t\t\tm_text.setString(text);\n\t\t\t\tm_text.setFont(font);\n\t\t\t\tm_text.setColor(fontcolor);\n\t\t\t\tthis->calculate_textpos();\n\t\t\t}\n\n\t\t\tvoid update(dur)\n\t\t\t{\n\t\t\t\t\/\/ check states\n\t\t\t\tif(m_hover) this->on_hover();\n\t\t\t\telse this->on_hover_end();\n\n\t\t\t\tif(m_press) this->on_press();\n\t\t\t\telse this->on_press_end();\n\n\t\t\t\t\/\/ collision\n\t\t\t\tauto bounds(m_shape.getGlobalBounds());\n\t\t\t\tauto mousebounds(inp::get_mousebounds<true>());\n\n\t\t\t\tif(bounds.intersects(mousebounds))\n\t\t\t\t\tm_hover = true;\n\t\t\t\telse m_hover = false;\n\n\t\t\t\tif(m_hover)\n\t\t\t\t{\n\t\t\t\t\tif(inp::is_btn_pressed(btn::Left))\n\t\t\t\t\t\tm_press = true;\n\t\t\t\t\telse m_press = false;\n\n\t\t\t\t\tif(inp::was_real_mousepress_left())\n\t\t\t\t\t\tthis->on_clicked();\n\t\t\t\t}\n\t\t\t\telse m_press = false;\n\t\t\t}\n\n\t\t\tvoid setText(const std::string& text) noexcept\n\t\t\t{m_text.setString(text); this->calculate_textpos();}\n\n\t\t\tvoid setFont(const sf::Font& font) noexcept\n\t\t\t{m_text.setFont(font); this->calculate_textpos();}\n\n\t\t\tvoid setFontColor(const sf::Color& color) noexcept\n\t\t\t{m_text.setColor(color);}\n\n\t\t\tvoid setFontSize(mlk::uint size) noexcept\n\t\t\t{m_text.setCharacterSize(size); this->calculate_textpos();}\n\n\t\t\tvoid setColor(const sf::Color& color) noexcept\n\t\t\t{m_shape.setFillColor(color); m_restore_shape.setFillColor(color);}\n\n\t\t\tvoid setOutlineThickness(float thickness) noexcept\n\t\t\t{m_shape.setOutlineThickness(thickness); m_restore_shape.setOutlineThickness(thickness);}\n\n\t\t\tvoid setOutlineColor(const sf::Color& color) noexcept\n\t\t\t{m_shape.setOutlineColor(color); m_restore_shape.setOutlineColor(color);}\n\n\t\t\tvoid setPosition(const vec2f& pos) noexcept\n\t\t\t{m_shape.setPosition(pos); m_restore_shape.setPosition(pos); this->calculate_textpos();}\n\n\t\t\tvoid setOrigin(const vec2f& pos) noexcept\n\t\t\t{m_shape.setOrigin(pos); m_restore_shape.setOrigin(pos); this->calculate_textpos();}\n\n\t\t\tvoid setSize(const vec2f& size) noexcept\n\t\t\t{m_shape.setSize(size); m_restore_shape.setSize(size); this->calculate_textpos();}\n\n\t\t\tvoid setTexture(sf::Texture* tx) noexcept\n\t\t\t{m_shape.setTexture(tx); m_restore_shape.setTexture(tx);}\n\n\t\t\tvoid move(const vec2f& offset) noexcept\n\t\t\t{m_shape.move(offset); m_restore_shape.move(offset); this->calculate_textpos();}\n\n\t\t\tvoid rotate(float angle) noexcept\n\t\t\t{m_shape.rotate(angle); m_restore_shape.rotate(angle); this->calculate_textpos();}\n\n\t\t\tstd::string getText() const noexcept\n\t\t\t{return m_text.getString();}\n\n\t\t\tconst sf::Font* getFont() const noexcept\n\t\t\t{return m_text.getFont();}\n\n\t\t\tconst sf::Color& getFontColor() const noexcept\n\t\t\t{return m_text.getColor();}\n\n\t\t\tmlk::uint getFontSize() const noexcept\n\t\t\t{return m_text.getCharacterSize();}\n\n\t\t\tconst sf::Color& getColor() const noexcept\n\t\t\t{return m_shape.getFillColor();}\n\n\t\t\tfloat getOutlineThickness() const noexcept\n\t\t\t{return m_shape.getOutlineThickness();}\n\n\t\t\tconst sf::Color& getOutlineColor() const noexcept\n\t\t\t{return m_shape.getOutlineColor();}\n\n\t\t\tconst vec2f& getPosition() const noexcept\n\t\t\t{return m_shape.getPosition();}\n\n\t\t\tconst vec2f& getOrigin() const noexcept\n\t\t\t{return m_shape.getOrigin();}\n\n\t\t\tconst vec2f& getSize() const noexcept\n\t\t\t{return m_shape.getSize();}\n\n\t\t\tconst sf::Texture* getTexture() const noexcept\n\t\t\t{return m_shape.getTexture();}\n\n\t\t\tbool pressed() const noexcept\n\t\t\t{return m_press;}\n\n\t\t\tbool hover() const noexcept\n\t\t\t{return m_hover;}\n\n\t\tprotected:\n\t\t\tvirtual void init()\n\t\t\t{\n\t\t\t\t\/\/ init the rect\n\t\t\t}\n\n\t\t\tvoid init_base()\n\t\t\t{\n\t\t\t\tthis->init();\n\t\t\t\tthis->create_restore_shape();\n\t\t\t}\n\n\t\t\tvirtual void on_hover()\n\t\t\t{\n\t\t\t\t\/\/ do something on hover\n\t\t\t}\n\n\t\t\tvirtual void on_hover_end()\n\t\t\t{\n\t\t\t\tif(m_press) return;\n\t\t\t\tthis->restore_origin();\n\t\t\t}\n\n\t\t\tvirtual void on_press()\n\t\t\t{\n\t\t\t\t\/\/ do something on press\n\t\t\t}\n\n\t\t\tvirtual void on_press_end()\n\t\t\t{\n\t\t\t\tif(m_hover) return;\n\t\t\t\tthis->restore_origin();\n\t\t\t}\n\n\t\t\tvoid create_restore_shape() noexcept\n\t\t\t{m_restore_shape = m_shape;}\n\n\t\t\tvoid restore_origin() noexcept\n\t\t\t{m_shape = m_restore_shape;}\n\n\t\t\tvirtual void draw(sf::RenderTarget& target, sf::RenderStates states) const override\n\t\t\t{\n\t\t\t\ttarget.draw(m_shape, states);\n\t\t\t\ttarget.draw(m_text, states);\n\t\t\t}\n\n\t\tprivate:\n\t\t\tvoid calculate_textpos()\n\t\t\t{\n\t\t\t\tauto shape_bounds(m_shape.getGlobalBounds());\n\t\t\t\tauto text_bounds(m_text.getGlobalBounds());\n\t\t\t\tm_text.setOrigin(text_bounds.width \/ 2.f, text_bounds.height \/ 2.f);\n\t\t\t\tm_text.setPosition(shape_bounds.left + shape_bounds.width \/ 2.f, shape_bounds.top + shape_bounds.height \/ 2.f);\n\t\t\t}\n\t\t};\n\t}\n}\n\n\n#endif \/\/ RJ_UI_BUTTON_HPP\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ Macro to be invoked before Calibration analysis \n\/\/ Setup TPC OCDB entries\n\/\/ \n\/\/ This is just example macro - some path are hardwired\n\/\/ TO BE MODIFIED BY USERS \n\n\n\nvoid ConfigOCDB(Float_t bfield){\n \/\/ \n \/\/\n \/\/ import geometry\n \/\/\n\n printf(\"SETUP OCBD for PROOF\\n\");\n TGeoManager::Import(\"\/u\/miranov\/proof\/geometry.root\");\n AliGeomManager::LoadGeometry(\"\/u\/miranov\/proof\/geometry.root\");\n \/\/\n \/\/\n \/\/ Setup magnetic field\n \/\/\n TGeoGlobalMagField::Instance()->SetField(new AliMagF(\"Maps\",\"Maps\", 2, 1., 1., 10., AliMagF::k5kG));\n \/\/\n \/\/\n \/\/\n AliCDBManager::Instance()->SetDefaultStorage(\"local:\/\/$ALICE_ROOT\/OCDB\");\n AliCDBManager::Instance()->SetSpecificStorage(\"TPC\/Calib\/Parameters\",\"local:\/\/$ALICE_ROOT\/OCDB\");\n AliCDBManager::Instance()->SetSpecificStorage(\"TPC\/Calib\/ClusterParam\",\"local:\/\/$ALICE_ROOT\/OCDB\");\n \/\/ AliCDBManager::Instance()->SetSpecificStorage(\"TPC\/Calib\/PadTime0\",\"local:\/\/$ALICE_ROOT\/OCDB\");\n AliCDBManager::Instance()->SetSpecificStorage(\"TPC\/Calib\/PadTime0\",\"local:\/\/\/u\/miranov\/OCDB0\");\n\n AliCDBManager::Instance()->SetSpecificStorage(\"GRP\/GRP\/Data\",\"local:\/\/\/lustre_alpha\/alice\/alien\/alice\/data\/2008\/LHC08d\/OCDB\/\");\n AliCDBManager::Instance()->SetSpecificStorage(\"TPC\/Calib\/Temperature\",\"local:\/\/\/lustre_alpha\/alice\/alien\/alice\/data\/2008\/LHC08d\/OCDB\/\");\n AliCDBManager::Instance()->SetSpecificStorage(\"TPC\/Calib\/Goofie\",\"local:\/\/\/lustre_alpha\/alice\/alien\/alice\/data\/2008\/LHC08d\/OCDB\/\");\n\n\n AliCDBManager::Instance()->SetRun(1);\n\n AliTPCClusterParam * paramCl = AliTPCcalibDB::Instance()->GetClusterParam(); \n AliTPCParam * paramTPC = AliTPCcalibDB::Instance()->GetParameters();\n paramCl->SetInstance(paramCl);\n \/\/paramTPC->Dump();\n printf(\"\\n\\nSET EXB FIELD\\t%f\\n\\n\", bfield);\n AliTPCcalibDB::Instance()->SetExBField(bfield);\n \/\/\n \/\/\n \/\/\n printf(\"END of SETUP OCBD for PROOF\\n\");\n}\n\n\nvoid ConfigAlien(){\n \/\/\n \/\/ Setup-activate alien\n \/\/\n\n \/\/myvar=342\n \/\/while [ $myvar -ne 360 ] ; do echo enable alien on lxb$myvar; lsrun -m lxb$myvar \/u\/miranov\/.aliensetup; myvar=$(( $myvar + 1 )) ; echo $myvar ; done \n gSystem->Exec(\"\/u\/miranov\/.aliensetup >setup.log\"); \n \/\/ifstream in;\n \/\/in.open(\"path.txt\");\n \n TString envString;\n \n gSystem->Setenv(\"LD_LIBRARY_PATH\",envString.Data());\n gSystem->Setenv(\"GBBOX_ENVFILE\",\"\/tmp\/xxxxxxx\");\n printf(\"LOAD LIBRARIES start\\n\\n\\n\");\n gSystem->Load(\"libANALYSIS.so\");\n gSystem->Load(\"libSTAT.so\");\n gSystem->Load(\"libTPCcalib.so\");\n \/\/\n gSystem->Load(\"libXrdClient.so\");\n gSystem->Load(\"libNetx.so\");\n printf(\"LOAD LIBRARIES end\\n\\n\\n\");\n TGrid * alien = TGrid::Connect(\"alien:\/\/\",0,0,\"t\");\n if (alien) {\n printf(\"Alien activated\\n\");\n }else{\n printf(\"Alien not activated\\n\");\n }\n}\n<commit_msg>THIS IS EXAMPLE MACRO:<commit_after>\/\/\n\/\/ Macro to Setup OCDB \n\/\/ This is just example macro\n\/\/ Responsible: marian.ivanov@cern.ch\n\/\/ To be used:\n\/\/ 1. Before invocation of the calibration - in the calibration trains\n\/\/ 2. To setup calibration viewer.\n\/\/ \n\/\/ ConfigOCDB - setup default and specific data storage\n\/\/ SetupCustom - user sepcific configuration \n\/\/ - Values in local cache of OCDB are overwritten\n\n\n\nvoid SetupCustom(Int_t run);\n\nvoid ConfigOCDB(Int_t crun=-1){\n \/\/ \n printf(\"SETUP OCBD for TPC\\n\");\n \/\/\n AliCDBManager::Instance()->SetDefaultStorage(\"local:\/\/$ALICE_ROOT\/OCDB\");\n AliCDBManager::Instance()->SetSpecificStorage(\"TPC\/Calib\/Parameters\",\"local:\/\/$ALICE_ROOT\/OCDB\");\n AliCDBManager::Instance()->SetSpecificStorage(\"TPC\/Calib\/ClusterParam\",\"local:\/\/\/u\/miranov\/OCDB\/TPCcosmic2\/\");\n AliCDBManager::Instance()->SetSpecificStorage(\"TPC\/Calib\/PadTime0\",\"local:\/\/$ALICE_ROOT\/OCDB\");\n AliCDBManager::Instance()->SetSpecificStorage(\"GRP\/GRP\/Data\",\"local:\/\/\/lustre\/alice\/alien\/alice\/data\/2009\/OCDB\/\");\n AliCDBManager::Instance()->SetSpecificStorage(\"TPC\/Calib\/Temperature\",\"local:\/\/\/lustre\/alice\/alien\/alice\/data\/2009\/OCDB\/\");\n AliCDBManager::Instance()->SetSpecificStorage(\"TPC\/Calib\/Goofie\",\"local:\/\/\/lustre\/alice\/alien\/alice\/data\/2009\/OCDB\/\");\n AliCDBManager::Instance()->SetSpecificStorage(\"TPC\/Calib\/HighVoltage\",\"local:\/\/\/lustre\/alice\/alien\/alice\/data\/2009\/OCDB\/\");\n Int_t run =crun;\n if (run<0) run =0;\n AliCDBManager::Instance()->SetRun(run);\n SetupCustom(run);\n}\n\n\nvoid SetupCustom(Int_t run){\n \/\/\n \/\/\n \/\/ Custom part - to be empty once we are happy with the calibration\n \/\/\n \/\/\n \/\/ Setup magnetic field\n \/\/\n AliGRPObject *grp = AliTPCcalibDB::GetGRP(run);\n Float_t current = 0;\n Float_t bz = 0;\n if (grp){\n current = grp->GetL3Current((AliGRPObject::Stats)0);\n bz = 5*current\/30000.;\n printf(\"Run%d\\tL3 current%f\\tBz\\t%f\\n\",run,current,bz);\n }\n else{\n printf(\"Run%d\\tL3 current%f\\tBz\\t%f\\n\",run,current,bz);\n }\n AliMagF::BMap_t smag = AliMagF::k5kG;\n Double_t bzfac = bz\/5;\n TGeoGlobalMagField::Instance()->SetField(new AliMagF(\"Maps\",\"Maps\", 2, bzfac, 1., 10., smag));\n\n printf(\"\\n\\nSET EXB FIELD\\t%f\\n\\n\", -bz);\n AliTPCcalibDB::Instance()->SetExBField(-bz);\n \/\/\n \/\/\n \/\/ import geometry\n \/\/\n \/\/\n TGeoManager::Import(\"\/u\/miranov\/proof\/geometry.root\");\n AliGeomManager::LoadGeometry(\"\/u\/miranov\/proof\/geometry.root\");\n\n AliTPCClusterParam * paramCl = AliTPCcalibDB::Instance()->GetClusterParam(); \n AliTPCParam * paramTPC = AliTPCcalibDB::Instance()->GetParameters();\n paramCl->SetInstance(paramCl);\n\n \/\/\n \/\/ Setup reco param\n \/\/\n AliTPCTransform *transform = AliTPCcalibDB::Instance()->GetTransform() ;\n AliTPCRecoParam * tpcRecoParam = AliTPCRecoParam::GetCosmicTestParam(kTRUE);\n transform->SetCurrentRecoParam(tpcRecoParam);\n tpcRecoParam->SetUseRPHICorrection(kTRUE);\n \/\/\n tpcRecoParam->SetUseRadialCorrection(kFALSE);\n tpcRecoParam->SetUseQuadrantAlignment(kTRUE);\n \/\/\n tpcRecoParam->SetUseSectorAlignment(kFALSE);\n tpcRecoParam->SetUseDriftCorrectionTime(kFALSE);\n tpcRecoParam->SetUseDriftCorrectionGY(kTRUE);\n tpcRecoParam->SetUseGainCorrectionTime(kFALSE);\n tpcRecoParam->SetUseFieldCorrection(kFALSE);\n tpcRecoParam->SetUseExBCorrection(kTRUE);\n \/\/\n \/\/\n \/\/\n TFile fposcor(\"~\/OCDB\/calibUnlin.root\");\n AliTPCPointCorrection *pcorr = fposcor.Get(\"correction\");\n if (pcorr) pcorr->SetInstance(pcorr); \n \/\/\n \/\/\n \/\/\n printf(\"END of SETUP OCBD for TPC\\n\");\n}\n\n\n<|endoftext|>"} {"text":"<commit_before>#ifndef ___INANITY_EXCEPTION_HPP___\n#define ___INANITY_EXCEPTION_HPP___\n\n#include \"Object.hpp\"\n#include \"String.hpp\"\n#include \"meta\/decl.hpp\"\n#include <ostream>\n\nBEGIN_INANITY\n\n\/\/\/ Базовый класс исключения.\n\/** Данный класс используется везде, для предоставления информации\nо происходящих ошибках.\nПроисходящяя ошибка должна обрабатываться соответствующим кодом,\nкоторый переводит её в первичное исключение Inanity.\nЭто первичное исключение может быть перехвачено кодом, решающим\nболее высокоуровневую задачу; он должен в свою очередь создать\nвторичное исключение, и описать в нем, какая ошибка произошла\nс его точки зрения. Последующие уровни кода также могут создавать\nвторичные исключения, каждый раз описывая проблему все более и\nболее глобально. Такая схема позволяет легко понять, почему\nошибка произошла, и что сделать для её устранения, а также\nлегко контролировать возникновение ошибок.\nСообщение, которое задаётся для исключения, должно быть одним\nпредложением, с большой буквы, без завершающей точки или перевода\nстроки.\n*\/\nclass Exception : public Object\n{\nprotected:\n\tString message;\n\tptr<Exception> innerException;\n\npublic:\n\t\/\/\/ Создать первичный объект исключения.\n\t\/** Первичный объект исключения является первым исключением,\n\tвозникающем при ошибке.\n\t\\param message Текстовое сообщение об ошибке.\n\t*\/\n\tException(const String& message);\n\n\t\/\/\/ Создать вторичный объект исключения.\n\t\/** Вторичный объект исключения является исключением,\n\tобертывающим более низкоуровневое исключение,\n\tи объясняющим с более глобальной точки зрения,\n\tчто означает данная ошибка.\n\t\\param message Текстовое сообщение об ошибке.\n\t\\param innerException Исключение более низкого уровня,\n\tпородившее данное исключение.\n\t*\/\n\tException(const String& message, ptr<Exception> innerException);\n\n\t\/\/\/ Получить текст сообщения об ошибке.\n\t\/** Данный текст включает только сообщение, которое\n\tотносится именно к этому уровню ошибки.\n\t\\return Текст сообщения об ошибке.\n\t*\/\n\tString GetMessageText() const;\n\n\t\/\/\/ Получить внутреннее (низкоуровневое) исключение\n\t\/** \\return Объект внутреннего исключения, или null,\n\tесли данное исключение первичное.\n\t*\/\n\tptr<Exception> GetInnerException() const;\n\n\t\/\/\/ Вывести в поток вывода сообщения всего стека исключений.\n\t\/** Позволяет получить полную картину произошедшей ошибки,\n\tвыводя всю информацию по указанной ошибке.\n\t*\/\n\tvirtual void PrintStack(std::ostream& stream) const;\n\n\t\/\/\/ Создать исключение, описывающее ошибку системы.\n\t\/** Ошибка системы определяется специфичным для платформы способом (Windows - GetLastError, Linux - errno). *\/\n\tstatic ptr<Exception> SystemError();\n\tstatic ptr<Exception> SystemError(int errorCode);\n\n\tMETA_DECLARE_CLASS(Exception);\n};\n\n#ifdef _DEBUG\n#define __SLINE2__(x) #x\n#define __SLINE3__(x) __SLINE2__(x)\n#define __SLINE__ __SLINE3__(__LINE__)\n\/\/\/ Макрос для вызова первичного исключения\n#define THROW_PRIMARY_EXCEPTION(message) throw NEW(Exception(String(\"[ \" __FILE__ \", \" __SLINE__ \" ] \") + (message)))\n\/\/\/ Макрос для вызова вторичного исключения\n#define THROW_SECONDARY_EXCEPTION(message, exception) throw NEW(Exception(String(\"[ \" __FILE__ \", \" __SLINE__ \" ] \") + (message), (exception)))\n#else\n\/\/\/ Макрос для вызова первичного исключения\n#define THROW_PRIMARY_EXCEPTION(message) throw NEW(Exception((message)))\n\/\/\/ Макрос для вызова вторичного исключения\n#define THROW_SECONDARY_EXCEPTION(message, exception) throw NEW(Exception((message), (exception)))\n#endif\n\nEND_INANITY\n\n#endif\n<commit_msg>BEGIN_TRY, END_TRY macros<commit_after>#ifndef ___INANITY_EXCEPTION_HPP___\n#define ___INANITY_EXCEPTION_HPP___\n\n#include \"Object.hpp\"\n#include \"String.hpp\"\n#include \"meta\/decl.hpp\"\n#include <ostream>\n\nBEGIN_INANITY\n\n\/\/\/ Базовый класс исключения.\n\/** Данный класс используется везде, для предоставления информации\nо происходящих ошибках.\nПроисходящяя ошибка должна обрабатываться соответствующим кодом,\nкоторый переводит её в первичное исключение Inanity.\nЭто первичное исключение может быть перехвачено кодом, решающим\nболее высокоуровневую задачу; он должен в свою очередь создать\nвторичное исключение, и описать в нем, какая ошибка произошла\nс его точки зрения. Последующие уровни кода также могут создавать\nвторичные исключения, каждый раз описывая проблему все более и\nболее глобально. Такая схема позволяет легко понять, почему\nошибка произошла, и что сделать для её устранения, а также\nлегко контролировать возникновение ошибок.\nСообщение, которое задаётся для исключения, должно быть одним\nпредложением, с большой буквы, без завершающей точки или перевода\nстроки.\n*\/\nclass Exception : public Object\n{\nprotected:\n\tString message;\n\tptr<Exception> innerException;\n\npublic:\n\t\/\/\/ Создать первичный объект исключения.\n\t\/** Первичный объект исключения является первым исключением,\n\tвозникающем при ошибке.\n\t\\param message Текстовое сообщение об ошибке.\n\t*\/\n\tException(const String& message);\n\n\t\/\/\/ Создать вторичный объект исключения.\n\t\/** Вторичный объект исключения является исключением,\n\tобертывающим более низкоуровневое исключение,\n\tи объясняющим с более глобальной точки зрения,\n\tчто означает данная ошибка.\n\t\\param message Текстовое сообщение об ошибке.\n\t\\param innerException Исключение более низкого уровня,\n\tпородившее данное исключение.\n\t*\/\n\tException(const String& message, ptr<Exception> innerException);\n\n\t\/\/\/ Получить текст сообщения об ошибке.\n\t\/** Данный текст включает только сообщение, которое\n\tотносится именно к этому уровню ошибки.\n\t\\return Текст сообщения об ошибке.\n\t*\/\n\tString GetMessageText() const;\n\n\t\/\/\/ Получить внутреннее (низкоуровневое) исключение\n\t\/** \\return Объект внутреннего исключения, или null,\n\tесли данное исключение первичное.\n\t*\/\n\tptr<Exception> GetInnerException() const;\n\n\t\/\/\/ Вывести в поток вывода сообщения всего стека исключений.\n\t\/** Позволяет получить полную картину произошедшей ошибки,\n\tвыводя всю информацию по указанной ошибке.\n\t*\/\n\tvirtual void PrintStack(std::ostream& stream) const;\n\n\t\/\/\/ Создать исключение, описывающее ошибку системы.\n\t\/** Ошибка системы определяется специфичным для платформы способом (Windows - GetLastError, Linux - errno). *\/\n\tstatic ptr<Exception> SystemError();\n\tstatic ptr<Exception> SystemError(int errorCode);\n\n\tMETA_DECLARE_CLASS(Exception);\n};\n\n#ifdef _DEBUG\n#define __SLINE2__(x) #x\n#define __SLINE3__(x) __SLINE2__(x)\n#define __SLINE__ __SLINE3__(__LINE__)\n\/\/\/ Макрос для вызова первичного исключения\n#define THROW_PRIMARY_EXCEPTION(message) throw NEW(Exception(String(\"[ \" __FILE__ \", \" __SLINE__ \" ] \") + (message)))\n\/\/\/ Макрос для вызова вторичного исключения\n#define THROW_SECONDARY_EXCEPTION(message, exception) throw NEW(Exception(String(\"[ \" __FILE__ \", \" __SLINE__ \" ] \") + (message), (exception)))\n#else\n\/\/\/ Макрос для вызова первичного исключения\n#define THROW_PRIMARY_EXCEPTION(message) throw NEW(Exception((message)))\n\/\/\/ Макрос для вызова вторичного исключения\n#define THROW_SECONDARY_EXCEPTION(message, exception) throw NEW(Exception((message), (exception)))\n#endif\n\n#define BEGIN_TRY() try {\n#define END_TRY(message) } catch(Exception* exception) { THROW_SECONDARY_EXCEPTION(message, exception); }\n\nEND_INANITY\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>#include \"makeplan.h\"\n\nMakePlan::MakePlan()\n{\n}\n\nvoid MakePlan::removeOutliers(PointCloud::Ptr cloud_in, PointCloud::Ptr &cloud_out)\n{\n pcl::RadiusOutlierRemoval<pcl::PointXYZ> outrem;\n \/\/ build the filter\n outrem.setInputCloud(cloud_in);\n outrem.setRadiusSearch(0.01);\n outrem.setMinNeighborsInRadius (4);\n \/\/ apply filter\n outrem.filter (*cloud_out);\n}\n\nbool MakePlan::getAveragePoint(PointCloud::Ptr cloud_in, pcl::PointXYZ &avrPt)\n{\n if (!cloud_in->points.size())\n {\n return false;\n }\n\n pcl::PointXYZ min_dis_point;\n float min_dis = 100.0;\n for (PointCloud::const_iterator it = cloud_in->begin(); it != cloud_in->end(); ++ it)\n {\n float dis = pow(it->x, 2) + pow(it->y, 2);\n if (dis < min_dis)\n {\n min_dis = dis;\n min_dis_point = *it;\n }\n }\n\n smartOffset(min_dis_point, 0.02);\n avrPt = min_dis_point;\n return true;\n}\n\nvoid MakePlan::smartOffset(pcl::PointXYZ &p_in, float off_val)\n{\n float y_off = off_val \/ sqrt(1 + pow(p_in.x \/ p_in.y, 2)) * p_in.y \/ fabs(p_in.y);\n float x_off = p_in.x \/ p_in.y * y_off;\n p_in.x = p_in.x + x_off;\n p_in.y = p_in.y + y_off;\n}\n\nvoid MakePlan::removeNans(PointCloud::Ptr cloud_in, PointCloud::Ptr &cloud_out)\n{\n std::vector< int >\tindex;\n PointCloud::Ptr cloud_filtered_nan (new PointCloud);\n\n pcl::removeNaNFromPointCloud(*cloud_in, *cloud_filtered_nan, index);\n\n pcl::PointIndices::Ptr indices_x(new pcl::PointIndices);\n pcl::PointIndices::Ptr indices_xy(new pcl::PointIndices);\n\n pcl::PassThrough<pcl::PointXYZ> ptfilter; \/\/ Initializing with true will allow us to extract the removed indices\n ptfilter.setInputCloud (cloud_filtered_nan);\n ptfilter.setFilterFieldName (\"x\");\n ptfilter.setFilterLimits (-0.2, 0.2);\n ptfilter.filter (indices_x->indices);\n\n ptfilter.setIndices (indices_x);\n ptfilter.setFilterFieldName (\"y\");\n ptfilter.setFilterLimits (-0.2, 0.2);\n ptfilter.filter (indices_xy->indices);\n\n ptfilter.setIndices (indices_xy);\n ptfilter.setFilterFieldName (\"z\");\n ptfilter.setFilterLimits (0.5, 2.0);\/\/ this method can only be used on source cloud, aka cloud whose frame is camera optical frame\n ptfilter.filter (*cloud_out);\n}\n\nbool MakePlan::process(PointCloud::Ptr cloud_in, float a, float b, float c, float d, pcl::PointXYZ &avrPt)\n{\n if (!cloud_in->points.size())\n {\n return false;\n }\n\n PointCloud::Ptr cloud_filtered (new PointCloud);\n#ifdef USE_CENTER\n cloud_filtered = cloud_in;\n#else\n removeOutliers(cloud_in, cloud_filtered);\n#endif\n bool success = getAveragePoint(cloud_filtered, avrPt);\n return success;\n}\n<commit_msg>shift target pose a bit in -z<commit_after>#include \"makeplan.h\"\n\nMakePlan::MakePlan()\n{\n}\n\nvoid MakePlan::removeOutliers(PointCloud::Ptr cloud_in, PointCloud::Ptr &cloud_out)\n{\n pcl::RadiusOutlierRemoval<pcl::PointXYZ> outrem;\n \/\/ build the filter\n outrem.setInputCloud(cloud_in);\n outrem.setRadiusSearch(0.01);\n outrem.setMinNeighborsInRadius (4);\n \/\/ apply filter\n outrem.filter (*cloud_out);\n}\n\nbool MakePlan::getAveragePoint(PointCloud::Ptr cloud_in, pcl::PointXYZ &avrPt)\n{\n if (!cloud_in->points.size())\n {\n return false;\n }\n\n pcl::PointXYZ min_dis_point;\n float min_dis = 100.0;\n for (PointCloud::const_iterator it = cloud_in->begin(); it != cloud_in->end(); ++ it)\n {\n float dis = pow(it->x, 2) + pow(it->y, 2);\n if (dis < min_dis)\n {\n min_dis = dis;\n min_dis_point = *it;\n }\n }\n\n smartOffset(min_dis_point, 0.02);\n avrPt = min_dis_point;\n return true;\n}\n\nvoid MakePlan::smartOffset(pcl::PointXYZ &p_in, float off_val)\n{\n float y_off = off_val \/ sqrt(1 + pow(p_in.x \/ p_in.y, 2)) * p_in.y \/ fabs(p_in.y);\n float x_off = p_in.x \/ p_in.y * y_off;\n p_in.x += x_off;\n p_in.y += y_off;\n float off_z = 0.05; \/\/ To solve the detected point is higher than optimal\n p_in.z -= off_z;\n}\n\nvoid MakePlan::removeNans(PointCloud::Ptr cloud_in, PointCloud::Ptr &cloud_out)\n{\n std::vector< int >\tindex;\n PointCloud::Ptr cloud_filtered_nan (new PointCloud);\n\n pcl::removeNaNFromPointCloud(*cloud_in, *cloud_filtered_nan, index);\n\n pcl::PointIndices::Ptr indices_x(new pcl::PointIndices);\n pcl::PointIndices::Ptr indices_xy(new pcl::PointIndices);\n\n pcl::PassThrough<pcl::PointXYZ> ptfilter; \/\/ Initializing with true will allow us to extract the removed indices\n ptfilter.setInputCloud (cloud_filtered_nan);\n ptfilter.setFilterFieldName (\"x\");\n ptfilter.setFilterLimits (-0.2, 0.2);\n ptfilter.filter (indices_x->indices);\n\n ptfilter.setIndices (indices_x);\n ptfilter.setFilterFieldName (\"y\");\n ptfilter.setFilterLimits (-0.2, 0.2);\n ptfilter.filter (indices_xy->indices);\n\n ptfilter.setIndices (indices_xy);\n ptfilter.setFilterFieldName (\"z\");\n ptfilter.setFilterLimits (0.5, 2.0);\/\/ this method can only be used on source cloud, aka cloud whose frame is camera optical frame\n ptfilter.filter (*cloud_out);\n}\n\nbool MakePlan::process(PointCloud::Ptr cloud_in, float a, float b, float c, float d, pcl::PointXYZ &avrPt)\n{\n if (!cloud_in->points.size())\n {\n return false;\n }\n\n PointCloud::Ptr cloud_filtered (new PointCloud);\n#ifdef USE_CENTER\n cloud_filtered = cloud_in;\n#else\n removeOutliers(cloud_in, cloud_filtered);\n#endif\n bool success = getAveragePoint(cloud_filtered, avrPt);\n return success;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ This file is part of the dune-gdt project:\n\/\/ http:\/\/users.dune-project.org\/projects\/dune-gdt\n\/\/ Copyright holders: Felix Schindler\n\/\/ License: BSD 2-Clause License (http:\/\/opensource.org\/licenses\/BSD-2-Clause)\n\n#ifndef DUNE_GDT_FUNCTIONALS_L2_HH\n#define DUNE_GDT_FUNCTIONALS_L2_HH\n\n#include <dune\/stuff\/functions\/interfaces.hh>\n#include <dune\/stuff\/la\/container\/interfaces.hh>\n\n#include <dune\/gdt\/localfunctional\/codim0.hh>\n#include <dune\/gdt\/localfunctional\/codim1.hh>\n#include <dune\/gdt\/localevaluation\/product.hh>\n#include <dune\/gdt\/assembler\/system.hh>\n\n#include \"base.hh\"\n\nnamespace Dune {\nnamespace GDT {\nnamespace Functionals {\n\n\n\/\/ forwards\ntemplate< class FunctionType, class VectorImp, class SpaceImp, class GridViewImp = typename SpaceImp::GridViewType,\n class LocalEvaluationType = LocalEvaluation::Product<FunctionType> >\nclass L2Volume;\n\ntemplate< class FunctionType, class VectorImp, class SpaceImp, class GridViewImp = typename SpaceImp::GridViewType >\nclass L2Face;\n\n\nnamespace internal {\n\n\ntemplate< class FunctionType, class VectorImp, class SpaceImp, class GridViewImp, class LocalEvaluationType >\nclass L2VolumeTraits\n{\n static_assert(std::is_base_of< Stuff::LocalizableFunctionInterface< typename FunctionType::EntityType\n , typename FunctionType::DomainFieldType\n , FunctionType::dimDomain\n , typename FunctionType::RangeFieldType\n , FunctionType::dimRange\n , FunctionType::dimRangeCols >\n , FunctionType >::value,\n \"FunctionType has to be derived from Stuff::LocalizableFunctionInterface!\");\n static_assert(std::is_base_of< SpaceInterface< typename SpaceImp::Traits,\n SpaceImp::dimDomain,\n SpaceImp::dimRange,\n SpaceImp::dimRangeCols >,\n SpaceImp >::value,\n \"SpaceImp has to be derived from SpaceInterface!\");\npublic:\n typedef L2Volume< FunctionType, VectorImp, SpaceImp, GridViewImp, LocalEvaluationType > derived_type;\n typedef VectorImp VectorType;\n typedef SpaceImp SpaceType;\n typedef GridViewImp GridViewType;\n typedef typename VectorType::ScalarType ScalarType;\n}; \/\/ class L2VolumeTraits\n\n\ntemplate< class FunctionType, class VectorImp, class SpaceImp, class GridViewImp >\nclass L2FaceTraits\n{\n static_assert(Stuff::is_localizable_function< FunctionType >::value,\n \"FunctionType has to be derived from Stuff::LocalizableFunctionInterface!\");\n static_assert(is_space< SpaceImp >::value, \"SpaceImp has to be derived from SpaceInterface!\");\npublic:\n typedef L2Face< FunctionType, VectorImp, SpaceImp, GridViewImp > derived_type;\n typedef VectorImp VectorType;\n typedef SpaceImp SpaceType;\n typedef GridViewImp GridViewType;\n typedef typename VectorType::ScalarType ScalarType;\n}; \/\/ class L2FaceTraits\n\n\n} \/\/ namespace internal\n\n\ntemplate< class FunctionType, class VectorImp, class SpaceImp, class GridViewImp, class LocalEvaluationType >\nclass L2Volume\n : public Functionals::VectorBased< internal::L2VolumeTraits< FunctionType, VectorImp, SpaceImp, GridViewImp,\n LocalEvaluationType> >\n , public SystemAssembler< SpaceImp, GridViewImp, SpaceImp >\n{\n typedef Functionals::VectorBased< internal::L2VolumeTraits< FunctionType, VectorImp, SpaceImp, GridViewImp,\n LocalEvaluationType> >\n FunctionalBaseType;\n typedef SystemAssembler< SpaceImp, GridViewImp, SpaceImp > AssemblerBaseType;\n\n typedef LocalFunctional::Codim0Integral<LocalEvaluationType> LocalFunctionalType;\n typedef LocalAssembler::Codim0Vector< LocalFunctionalType > LocalAssemblerType;\n\npublic:\n typedef internal::L2VolumeTraits< FunctionType, VectorImp, SpaceImp, GridViewImp, LocalEvaluationType > Traits;\n typedef typename Traits::VectorType VectorType;\n typedef typename Traits::SpaceType SpaceType;\n typedef typename Traits::GridViewType GridViewType;\n\n L2Volume(const FunctionType& function, VectorType& vec, const SpaceType& spc, const GridViewType& grd_vw)\n : FunctionalBaseType(vec, spc, grd_vw)\n , AssemblerBaseType(spc, grd_vw)\n , function_(function)\n , local_functional_(function_)\n , local_assembler_(local_functional_)\n {\n setup();\n }\n\n L2Volume(const FunctionType& function, VectorType& vec, const SpaceType& spc)\n : FunctionalBaseType(vec, spc)\n , AssemblerBaseType(spc)\n , function_(function)\n , local_functional_(function_)\n , local_assembler_(local_functional_)\n {\n setup();\n }\n\n L2Volume(const FunctionType& function, VectorType& vec, const SpaceType& spc,\n const LocalFunctionalType localFunctional)\n : FunctionalBaseType(vec, spc)\n , AssemblerBaseType(spc)\n , function_(function)\n , local_functional_(localFunctional)\n , local_assembler_(local_functional_)\n {\n setup();\n }\n virtual void assemble() override final\n {\n AssemblerBaseType::assemble();\n }\n\nprivate:\n void setup()\n {\n this->add(local_assembler_, this->vector());\n }\n\n const FunctionType& function_;\n const LocalFunctionalType local_functional_;\n const LocalAssemblerType local_assembler_;\n}; \/\/ class L2Volume\n\n\ntemplate< class FunctionType, class VectorImp, class SpaceImp, class GridViewImp >\nclass L2Face\n : public Functionals::VectorBased< internal::L2FaceTraits< FunctionType, VectorImp, SpaceImp, GridViewImp > >\n , public SystemAssembler< SpaceImp, GridViewImp, SpaceImp >\n{\n typedef Functionals::VectorBased< internal::L2FaceTraits< FunctionType, VectorImp, SpaceImp, GridViewImp > >\n FunctionalBaseType;\n typedef SystemAssembler< SpaceImp, GridViewImp, SpaceImp > AssemblerBaseType;\n\n typedef LocalFunctional::Codim1Integral< LocalEvaluation::Product< FunctionType > > LocalFunctionalType;\n typedef LocalAssembler::Codim1Vector< LocalFunctionalType > LocalAssemblerType;\npublic:\n typedef internal::L2FaceTraits< FunctionType, VectorImp, SpaceImp, GridViewImp > Traits;\n\n typedef typename Traits::VectorType VectorType;\n typedef typename Traits::SpaceType SpaceType;\n typedef typename Traits::GridViewType GridViewType;\n\n L2Face(const FunctionType& function,\n VectorType& vec,\n const SpaceType& spc,\n const GridViewType& grd_vw,\n const Stuff::Grid::ApplyOn::WhichIntersection< GridViewType >* which_intersections\n = new Stuff::Grid::ApplyOn::AllIntersections< GridViewType >())\n : FunctionalBaseType(vec, spc, grd_vw)\n , AssemblerBaseType(spc, grd_vw)\n , function_(function)\n , local_functional_(function_)\n , local_assembler_(local_functional_)\n {\n setup(which_intersections);\n }\n\n L2Face(const FunctionType& function,\n VectorType& vec,\n const SpaceType& spc,\n const Stuff::Grid::ApplyOn::WhichIntersection< GridViewType >* which_intersections\n = new Stuff::Grid::ApplyOn::AllIntersections< GridViewType >())\n : FunctionalBaseType(vec, spc)\n , AssemblerBaseType(spc)\n , function_(function)\n , local_functional_(function_)\n , local_assembler_(local_functional_)\n {\n setup(which_intersections);\n }\n\n virtual void assemble() override final\n {\n AssemblerBaseType::assemble();\n }\n\nprivate:\n void setup(const Stuff::Grid::ApplyOn::WhichIntersection< GridViewType >* which_intersections)\n {\n this->add(local_assembler_, this->vector(), which_intersections);\n }\n\n const FunctionType& function_;\n const LocalFunctionalType local_functional_;\n const LocalAssemblerType local_assembler_;\n}; \/\/ class L2Face\n\n\n} \/\/ namespace Functionals\n} \/\/ namespace GDT\n} \/\/ namespace Dune\n\n#endif \/\/ DUNE_GDT_FUNCTIONALS_L2_HH\n<commit_msg>[functionals.l2] modernize static checks<commit_after>\/\/ This file is part of the dune-gdt project:\n\/\/ http:\/\/users.dune-project.org\/projects\/dune-gdt\n\/\/ Copyright holders: Felix Schindler\n\/\/ License: BSD 2-Clause License (http:\/\/opensource.org\/licenses\/BSD-2-Clause)\n\n#ifndef DUNE_GDT_FUNCTIONALS_L2_HH\n#define DUNE_GDT_FUNCTIONALS_L2_HH\n\n#include <dune\/stuff\/functions\/interfaces.hh>\n#include <dune\/stuff\/la\/container\/interfaces.hh>\n\n#include <dune\/gdt\/localfunctional\/codim0.hh>\n#include <dune\/gdt\/localfunctional\/codim1.hh>\n#include <dune\/gdt\/localevaluation\/product.hh>\n#include <dune\/gdt\/assembler\/system.hh>\n\n#include \"base.hh\"\n\nnamespace Dune {\nnamespace GDT {\nnamespace Functionals {\n\n\n\/\/ forwards\ntemplate< class FunctionType, class VectorImp, class SpaceImp, class GridViewImp = typename SpaceImp::GridViewType,\n class LocalEvaluationType = LocalEvaluation::Product<FunctionType> >\nclass L2Volume;\n\ntemplate< class FunctionType, class VectorImp, class SpaceImp, class GridViewImp = typename SpaceImp::GridViewType >\nclass L2Face;\n\n\nnamespace internal {\n\n\ntemplate< class FunctionType, class VectorImp, class SpaceImp, class GridViewImp, class LocalEvaluationType >\nclass L2VolumeTraits\n{\n static_assert(Stuff::is_localizable_function< FunctionType >::value,\n \"FunctionType has to be derived from Stuff::LocalizableFunctionInterface!\");\n static_assert(is_space< SpaceImp >::value, \"SpaceImp has to be derived from SpaceInterface!\");\npublic:\n typedef L2Volume< FunctionType, VectorImp, SpaceImp, GridViewImp, LocalEvaluationType > derived_type;\n typedef VectorImp VectorType;\n typedef SpaceImp SpaceType;\n typedef GridViewImp GridViewType;\n typedef typename VectorType::ScalarType ScalarType;\n}; \/\/ class L2VolumeTraits\n\n\ntemplate< class FunctionType, class VectorImp, class SpaceImp, class GridViewImp >\nclass L2FaceTraits\n{\n static_assert(Stuff::is_localizable_function< FunctionType >::value,\n \"FunctionType has to be derived from Stuff::LocalizableFunctionInterface!\");\n static_assert(is_space< SpaceImp >::value, \"SpaceImp has to be derived from SpaceInterface!\");\npublic:\n typedef L2Face< FunctionType, VectorImp, SpaceImp, GridViewImp > derived_type;\n typedef VectorImp VectorType;\n typedef SpaceImp SpaceType;\n typedef GridViewImp GridViewType;\n typedef typename VectorType::ScalarType ScalarType;\n}; \/\/ class L2FaceTraits\n\n\n} \/\/ namespace internal\n\n\ntemplate< class FunctionType, class VectorImp, class SpaceImp, class GridViewImp, class LocalEvaluationType >\nclass L2Volume\n : public Functionals::VectorBased< internal::L2VolumeTraits< FunctionType, VectorImp, SpaceImp, GridViewImp,\n LocalEvaluationType> >\n , public SystemAssembler< SpaceImp, GridViewImp, SpaceImp >\n{\n typedef Functionals::VectorBased< internal::L2VolumeTraits< FunctionType, VectorImp, SpaceImp, GridViewImp,\n LocalEvaluationType> >\n FunctionalBaseType;\n typedef SystemAssembler< SpaceImp, GridViewImp, SpaceImp > AssemblerBaseType;\n\n typedef LocalFunctional::Codim0Integral<LocalEvaluationType> LocalFunctionalType;\n typedef LocalAssembler::Codim0Vector< LocalFunctionalType > LocalAssemblerType;\n\npublic:\n typedef internal::L2VolumeTraits< FunctionType, VectorImp, SpaceImp, GridViewImp, LocalEvaluationType > Traits;\n typedef typename Traits::VectorType VectorType;\n typedef typename Traits::SpaceType SpaceType;\n typedef typename Traits::GridViewType GridViewType;\n\n L2Volume(const FunctionType& function, VectorType& vec, const SpaceType& spc, const GridViewType& grd_vw)\n : FunctionalBaseType(vec, spc, grd_vw)\n , AssemblerBaseType(spc, grd_vw)\n , function_(function)\n , local_functional_(function_)\n , local_assembler_(local_functional_)\n {\n setup();\n }\n\n L2Volume(const FunctionType& function, VectorType& vec, const SpaceType& spc)\n : FunctionalBaseType(vec, spc)\n , AssemblerBaseType(spc)\n , function_(function)\n , local_functional_(function_)\n , local_assembler_(local_functional_)\n {\n setup();\n }\n\n L2Volume(const FunctionType& function, VectorType& vec, const SpaceType& spc,\n const LocalFunctionalType localFunctional)\n : FunctionalBaseType(vec, spc)\n , AssemblerBaseType(spc)\n , function_(function)\n , local_functional_(localFunctional)\n , local_assembler_(local_functional_)\n {\n setup();\n }\n virtual void assemble() override final\n {\n AssemblerBaseType::assemble();\n }\n\nprivate:\n void setup()\n {\n this->add(local_assembler_, this->vector());\n }\n\n const FunctionType& function_;\n const LocalFunctionalType local_functional_;\n const LocalAssemblerType local_assembler_;\n}; \/\/ class L2Volume\n\n\ntemplate< class FunctionType, class VectorImp, class SpaceImp, class GridViewImp >\nclass L2Face\n : public Functionals::VectorBased< internal::L2FaceTraits< FunctionType, VectorImp, SpaceImp, GridViewImp > >\n , public SystemAssembler< SpaceImp, GridViewImp, SpaceImp >\n{\n typedef Functionals::VectorBased< internal::L2FaceTraits< FunctionType, VectorImp, SpaceImp, GridViewImp > >\n FunctionalBaseType;\n typedef SystemAssembler< SpaceImp, GridViewImp, SpaceImp > AssemblerBaseType;\n\n typedef LocalFunctional::Codim1Integral< LocalEvaluation::Product< FunctionType > > LocalFunctionalType;\n typedef LocalAssembler::Codim1Vector< LocalFunctionalType > LocalAssemblerType;\npublic:\n typedef internal::L2FaceTraits< FunctionType, VectorImp, SpaceImp, GridViewImp > Traits;\n\n typedef typename Traits::VectorType VectorType;\n typedef typename Traits::SpaceType SpaceType;\n typedef typename Traits::GridViewType GridViewType;\n\n L2Face(const FunctionType& function,\n VectorType& vec,\n const SpaceType& spc,\n const GridViewType& grd_vw,\n const Stuff::Grid::ApplyOn::WhichIntersection< GridViewType >* which_intersections\n = new Stuff::Grid::ApplyOn::AllIntersections< GridViewType >())\n : FunctionalBaseType(vec, spc, grd_vw)\n , AssemblerBaseType(spc, grd_vw)\n , function_(function)\n , local_functional_(function_)\n , local_assembler_(local_functional_)\n {\n setup(which_intersections);\n }\n\n L2Face(const FunctionType& function,\n VectorType& vec,\n const SpaceType& spc,\n const Stuff::Grid::ApplyOn::WhichIntersection< GridViewType >* which_intersections\n = new Stuff::Grid::ApplyOn::AllIntersections< GridViewType >())\n : FunctionalBaseType(vec, spc)\n , AssemblerBaseType(spc)\n , function_(function)\n , local_functional_(function_)\n , local_assembler_(local_functional_)\n {\n setup(which_intersections);\n }\n\n virtual void assemble() override final\n {\n AssemblerBaseType::assemble();\n }\n\nprivate:\n void setup(const Stuff::Grid::ApplyOn::WhichIntersection< GridViewType >* which_intersections)\n {\n this->add(local_assembler_, this->vector(), which_intersections);\n }\n\n const FunctionType& function_;\n const LocalFunctionalType local_functional_;\n const LocalAssemblerType local_assembler_;\n}; \/\/ class L2Face\n\n\n} \/\/ namespace Functionals\n} \/\/ namespace GDT\n} \/\/ namespace Dune\n\n#endif \/\/ DUNE_GDT_FUNCTIONALS_L2_HH\n<|endoftext|>"} {"text":"<commit_before>#ifndef DUNE_COMMON_COLOR_HH\n#define DUNE_COMMON_COLOR_HH\n\n#include <sstream>\n#include <assert.h>\n#include <iostream>\n\n#ifdef __GNUC__\n #include <cxxabi.h>\n#endif\n#include <string>\n\n#include <dune\/stuff\/common\/string.hh>\n\nnamespace Dune {\nnamespace Stuff {\nnamespace Common {\n\n\/**\n * @brief namespace to define color constants that can be \n * used to print colored text in an output stream.\n *\n * * \\todo this could go into libdune-stuff\n * @warning Some color codes might be unsupported by your terminal.\n *\/\nstruct Colors {\n\n#define DS_CONST_CHAR const constexpr char*\n\n\/\/ foreground colors\nstatic DS_CONST_CHAR black = \"\\033[30m\";\nstatic DS_CONST_CHAR red = \"\\033[31m\";\nstatic DS_CONST_CHAR green = \"\\033[32m\";\nstatic DS_CONST_CHAR brown = \"\\033[33m\";\nstatic DS_CONST_CHAR blue = \"\\033[34m\";\nstatic DS_CONST_CHAR purple = \"\\033[35m\";\nstatic DS_CONST_CHAR cyan = \"\\033[36m\";\nstatic DS_CONST_CHAR lightgray = \"\\033[37m\";\n\/\/ light foreground colors\nstatic DS_CONST_CHAR darkgray = \"\\033[1;30m\";\nstatic DS_CONST_CHAR lightred = \"\\033[1;31m\";\nstatic DS_CONST_CHAR lightgreen = \"\\033[1;32m\";\nstatic DS_CONST_CHAR yellow = \"\\033[1;33m\";\nstatic DS_CONST_CHAR lightblue = \"\\033[1;34m\";\nstatic DS_CONST_CHAR lightpurple = \"\\033[1;35m\";\nstatic DS_CONST_CHAR lightcyan = \"\\033[1;36m\";\nstatic DS_CONST_CHAR white = \"\\033[1;37m\";\n\n\/\/ background colors\nstatic DS_CONST_CHAR bblack = \"\\033[40m\";\nstatic DS_CONST_CHAR bred = \"\\033[41m\";\nstatic DS_CONST_CHAR bgreen = \"\\033[42m\";\nstatic DS_CONST_CHAR bbrown = \"\\033[43m\";\nstatic DS_CONST_CHAR bblue = \"\\033[44m\";\nstatic DS_CONST_CHAR bpurple = \"\\033[45m\";\nstatic DS_CONST_CHAR bcyan = \"\\033[46m\";\nstatic DS_CONST_CHAR blightgray = \"\\033[47m\";\n\/\/ light background colors\nstatic DS_CONST_CHAR bdarkgray = \"\\033[1;40m\";\nstatic DS_CONST_CHAR blightred = \"\\033[1;41m\";\nstatic DS_CONST_CHAR blightgreen = \"\\033[1;42m\";\nstatic DS_CONST_CHAR byellow = \"\\033[1;43m\";\nstatic DS_CONST_CHAR blightblue = \"\\033[1;44m\";\nstatic DS_CONST_CHAR blightpurple = \"\\033[1;45m\";\nstatic DS_CONST_CHAR blightcyan = \"\\033[1;46m\";\nstatic DS_CONST_CHAR bwhite = \"\\033[1;47m\";\n};\n\/\/ modifiers\nstruct StreamModifiers {\nstatic DS_CONST_CHAR normal = \"\\033[0m\";\nstatic DS_CONST_CHAR bold = \"\\033[1m\";\nstatic DS_CONST_CHAR italic = \"\\033[2m\";\nstatic DS_CONST_CHAR underline = \"\\033[4m\";\nstatic DS_CONST_CHAR blink = \"\\033[5m\";\nstatic DS_CONST_CHAR reverse = \"\\033[7m\";\nstatic DS_CONST_CHAR enditalic = \"\\033[22m\";\nstatic DS_CONST_CHAR endunderline = \"\\033[24m\";\nstatic DS_CONST_CHAR endblink = \"\\033[25m\";\nstatic DS_CONST_CHAR endreverse = \"\\033[27m\";\n#undef DS_CONST_CHAR\n};\n\/**\n * @brief Chooses a color from a 256 color map for a foreground color.\n *\n * @param i The color number between 0 and 255.\n * @returns A string describing a color code.\n *\/\nstd::string color(int i) {\n return \"\\033[38;5;\" + toString(i) + \"m\";\n}\n\n\/**\n * @brief Chooses a color from a 256 color map for a background color.\n *\n * @param i The color number between 0 and 255.\n * @returns A string describing a color code.\n *\/\nstd::string backcolor(int i) {\n return \"\\033[38;5;\" + toString(i) + \"m\";\n}\n\n\/\/ maybe you want to choose your own color\nint templateColorChooser(int i) {\n return i % 256;\n}\n\n\/**\n * @brief Highlights templates depending on the \"template\"-level.\n * \n * @param str The string containing the template string\n * @param maxlevel The maximal template-level the string is reduced to.\n * @returns A colored template string.\n *\/\nstd::string highlightTemplate(std::string str, int maxlevel = 10000) {\n if (maxlevel < 0)\n maxlevel = 0;\n int startindex = 0;\n int level = 0;\n for (size_t i = 0; i < str.size(); i++)\n {\n if (str[i] == '<')\n {\n level++;\n std::string dummy = \"\\033[38;5;\" + toString( templateColorChooser(level) ) + \"m\";\n str.insert(i, dummy);\n i += dummy.size();\n if (level == maxlevel)\n startindex = i + 1;\n } else if (str[i] == '>') {\n level--;\n std::string dummy = \"\\033[38;5;\" + toString( templateColorChooser(level) ) + \"m\";\n str.insert(++i, dummy);\n if (level + 1 == maxlevel)\n {\n int size = i - startindex - 1;\n str.erase(startindex, size);\n i = startindex + 1;\n }\n i += dummy.size();\n }\n }\n str += \"\\033[38;5;0m\";\n return str;\n} \/\/ highlightTemplate\n\n\/**\n * @brief A simple function highlighting a whole string in a specified foreground color.\n *\n * @param str The string you want to highlight.\n * @param colornr A color number from a 256 color map between 0 and 255.\n * @returns The highlighted string.\n *\/\nstd::string highlightString(std::string str, int colornr = 0) {\n return \"\\033[38;5;\" + toString(colornr % 256) + \"m\" + str + \"\\033[38;5;0m\";\n\nstd::string highlightString(const std::string string, const std::string color = Colors::red)\n{\n return color + string + \"\\033[0m\";\n}\n\n\/**\n * @brief Highlights a substring of another string in a specified color.\n *\n * @param str The string where you want to highlight substrings.\n * @param substr The sub string you want to highlight in str.\n * @param colornr A color number from a 256 color map between 0 and 255.\n * @returns The highlighted string.\n *\/\nstd::string highlightSearchString(std::string str, std::string substr, int colornr = 0) {\n int index = str.find(substr, 0);\n\n while ( index != int(std::string::npos) )\n {\n std::string dummy = \"\\033[38;5;\" + toString(colornr % 256) + \"m\";\n std::string dummy2 = \"\\033[38;5;0m\";\n str.insert(index, dummy);\n str.insert(index + substr.size() + dummy.size(), dummy2);\n index = str.find( substr, index + dummy.size() + substr.size() + dummy2.size() );\n }\n return str;\n} \/\/ highlightSearchString\n\n} \/\/ namespace Common\n} \/\/ namespace Stuff\n} \/\/ namespace Dune\n\n#endif \/\/ end of DUNE_COMMON_COLOR_HH\n\n\/** Copyright (c) 2012, Stefan Girke\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * 1. Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR\n * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n * The views and conclusions contained in the software and documentation are those\n * of the authors and should not be interpreted as representing official policies,\n * either expressed or implied, of the FreeBSD Project.\n **\/\n<commit_msg>[common.color] fixed wrong reset color in highlighString()<commit_after>#ifndef DUNE_COMMON_COLOR_HH\n#define DUNE_COMMON_COLOR_HH\n\n#include <sstream>\n#include <assert.h>\n#include <iostream>\n\n#ifdef __GNUC__\n #include <cxxabi.h>\n#endif\n#include <string>\n\n#include <dune\/stuff\/common\/string.hh>\n\nnamespace Dune {\nnamespace Stuff {\nnamespace Common {\n\n\/**\n * @brief namespace to define color constants that can be\n * used to print colored text in an output stream.\n *\n * * \\todo this could go into libdune-stuff\n * @warning Some color codes might be unsupported by your terminal.\n *\/\nstruct Colors {\n\n#define DS_CONST_CHAR const constexpr char*\n\n\/\/ foreground colors\nstatic DS_CONST_CHAR black = \"\\033[30m\";\nstatic DS_CONST_CHAR red = \"\\033[31m\";\nstatic DS_CONST_CHAR green = \"\\033[32m\";\nstatic DS_CONST_CHAR brown = \"\\033[33m\";\nstatic DS_CONST_CHAR blue = \"\\033[34m\";\nstatic DS_CONST_CHAR purple = \"\\033[35m\";\nstatic DS_CONST_CHAR cyan = \"\\033[36m\";\nstatic DS_CONST_CHAR lightgray = \"\\033[37m\";\n\/\/ light foreground colors\nstatic DS_CONST_CHAR darkgray = \"\\033[1;30m\";\nstatic DS_CONST_CHAR lightred = \"\\033[1;31m\";\nstatic DS_CONST_CHAR lightgreen = \"\\033[1;32m\";\nstatic DS_CONST_CHAR yellow = \"\\033[1;33m\";\nstatic DS_CONST_CHAR lightblue = \"\\033[1;34m\";\nstatic DS_CONST_CHAR lightpurple = \"\\033[1;35m\";\nstatic DS_CONST_CHAR lightcyan = \"\\033[1;36m\";\nstatic DS_CONST_CHAR white = \"\\033[1;37m\";\n\n\/\/ background colors\nstatic DS_CONST_CHAR bblack = \"\\033[40m\";\nstatic DS_CONST_CHAR bred = \"\\033[41m\";\nstatic DS_CONST_CHAR bgreen = \"\\033[42m\";\nstatic DS_CONST_CHAR bbrown = \"\\033[43m\";\nstatic DS_CONST_CHAR bblue = \"\\033[44m\";\nstatic DS_CONST_CHAR bpurple = \"\\033[45m\";\nstatic DS_CONST_CHAR bcyan = \"\\033[46m\";\nstatic DS_CONST_CHAR blightgray = \"\\033[47m\";\n\/\/ light background colors\nstatic DS_CONST_CHAR bdarkgray = \"\\033[1;40m\";\nstatic DS_CONST_CHAR blightred = \"\\033[1;41m\";\nstatic DS_CONST_CHAR blightgreen = \"\\033[1;42m\";\nstatic DS_CONST_CHAR byellow = \"\\033[1;43m\";\nstatic DS_CONST_CHAR blightblue = \"\\033[1;44m\";\nstatic DS_CONST_CHAR blightpurple = \"\\033[1;45m\";\nstatic DS_CONST_CHAR blightcyan = \"\\033[1;46m\";\nstatic DS_CONST_CHAR bwhite = \"\\033[1;47m\";\n};\n\/\/ modifiers\nstruct StreamModifiers {\nstatic DS_CONST_CHAR normal = \"\\033[0m\";\nstatic DS_CONST_CHAR bold = \"\\033[1m\";\nstatic DS_CONST_CHAR italic = \"\\033[2m\";\nstatic DS_CONST_CHAR underline = \"\\033[4m\";\nstatic DS_CONST_CHAR blink = \"\\033[5m\";\nstatic DS_CONST_CHAR reverse = \"\\033[7m\";\nstatic DS_CONST_CHAR enditalic = \"\\033[22m\";\nstatic DS_CONST_CHAR endunderline = \"\\033[24m\";\nstatic DS_CONST_CHAR endblink = \"\\033[25m\";\nstatic DS_CONST_CHAR endreverse = \"\\033[27m\";\n#undef DS_CONST_CHAR\n};\n\/**\n * @brief Chooses a color from a 256 color map for a foreground color.\n *\n * @param i The color number between 0 and 255.\n * @returns A string describing a color code.\n *\/\nstd::string color(int i) {\n return \"\\033[38;5;\" + toString(i) + \"m\";\n}\n\n\/**\n * @brief Chooses a color from a 256 color map for a background color.\n *\n * @param i The color number between 0 and 255.\n * @returns A string describing a color code.\n *\/\nstd::string backcolor(int i) {\n return \"\\033[38;5;\" + toString(i) + \"m\";\n}\n\n\/\/ maybe you want to choose your own color\nint templateColorChooser(int i) {\n return i % 256;\n}\n\n\/**\n * @brief Highlights templates depending on the \"template\"-level.\n *\n * @param str The string containing the template string\n * @param maxlevel The maximal template-level the string is reduced to.\n * @returns A colored template string.\n *\/\nstd::string highlightTemplate(std::string str, int maxlevel = 10000) {\n if (maxlevel < 0)\n maxlevel = 0;\n int startindex = 0;\n int level = 0;\n for (size_t i = 0; i < str.size(); i++)\n {\n if (str[i] == '<')\n {\n level++;\n std::string dummy = \"\\033[38;5;\" + toString( templateColorChooser(level) ) + \"m\";\n str.insert(i, dummy);\n i += dummy.size();\n if (level == maxlevel)\n startindex = i + 1;\n } else if (str[i] == '>') {\n level--;\n std::string dummy = \"\\033[38;5;\" + toString( templateColorChooser(level) ) + \"m\";\n str.insert(++i, dummy);\n if (level + 1 == maxlevel)\n {\n int size = i - startindex - 1;\n str.erase(startindex, size);\n i = startindex + 1;\n }\n i += dummy.size();\n }\n }\n str += \"\\033[38;5;0m\";\n return str;\n} \/\/ highlightTemplate\n\n\/**\n * @brief A simple function highlighting a whole string in a specified foreground color.\n *\n * @param str The string you want to highlight.\n * @param colornr A color number from a 256 color map between 0 and 255.\n * @returns The highlighted string.\n *\/\nstd::string highlightString(std::string str, int colornr = 0) {\n return \"\\033[38;5;\" + toString(colornr % 256) + \"m\" + str + \"\\033[0m\"; \/\/\"\\033[38;5;0m\";\n}\n\nstd::string highlightString(const std::string string, const std::string color = Colors::red)\n{\n return color + string + \"\\033[0m\";\n}\n\n\/**\n * @brief Highlights a substring of another string in a specified color.\n *\n * @param str The string where you want to highlight substrings.\n * @param substr The sub string you want to highlight in str.\n * @param colornr A color number from a 256 color map between 0 and 255.\n * @returns The highlighted string.\n *\/\nstd::string highlightSearchString(std::string str, std::string substr, int colornr = 0) {\n int index = str.find(substr, 0);\n\n while ( index != int(std::string::npos) )\n {\n std::string dummy = \"\\033[38;5;\" + toString(colornr % 256) + \"m\";\n std::string dummy2 = \"\\033[38;5;0m\";\n str.insert(index, dummy);\n str.insert(index + substr.size() + dummy.size(), dummy2);\n index = str.find( substr, index + dummy.size() + substr.size() + dummy2.size() );\n }\n return str;\n} \/\/ highlightSearchString\n\n} \/\/ namespace Common\n} \/\/ namespace Stuff\n} \/\/ namespace Dune\n\n#endif \/\/ end of DUNE_COMMON_COLOR_HH\n\n\/** Copyright (c) 2012, Stefan Girke\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * 1. Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR\n * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n * The views and conclusions contained in the software and documentation are those\n * of the authors and should not be interpreted as representing official policies,\n * either expressed or implied, of the FreeBSD Project.\n **\/\n<|endoftext|>"} {"text":"<commit_before>\/*\n*******************************************************************************\n\nCopyright (c) 2015, The Curators of the University of Missouri\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n1. Redistributions of source code must retain the above copyright notice,\n this list of conditions and the following disclaimer.\n\n2. Redistributions in binary form must reproduce the above copyright notice,\n this list of conditions and the following disclaimer in the documentation\n and\/or other materials provided with the distribution.\n\n3. Neither the name of the copyright holder nor the names of its contributors\n may be used to endorse or promote products derived from this software\n without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n*******************************************************************************\n*\/\n\n#ifndef GPU_WINDOW_FITLER_ALGORITHM_\n#define GPU_WINDOW_FITLER_ALGORITHM_\n\n#include \"GpuAlgorithm.hpp\"\n#include \"..\/kernels\/GpuAlgorithmKernels.hpp\"\n\nnamespace cvt {\nnamespace gpu {\n\nenum windowRadiusType{\n\tSQUARE,\n\tCIRCLE\n};\n\n\ntemplate< typename InputPixelType, int InputBandCount, typename OutputPixelType, int OutputBandCount >\nclass GpuWindowFilterAlgorithm : public GpuAlgorithm<InputPixelType, InputBandCount, OutputPixelType, OutputBandCount>\n{\n\n\tusing GpuAlgorithm<InputPixelType, InputBandCount, OutputPixelType, OutputBandCount>::initializeDevice;\n\n\tpublic:\n\n\t explicit GpuWindowFilterAlgorithm(unsigned int cudaDeviceId, size_t roiDataWidth,\n\t\t\t\t\t\t\t size_t roiDataHeight, ssize_t windowRadius);\n\n\t virtual ~GpuWindowFilterAlgorithm();\n\t virtual ErrorCode initializeDevice(enum windowRadiusType type);\n\n\t virtual ErrorCode operator()(const cvt::cvTile<InputPixelType>& tile,\n\t\t\t\t\t\t\t\t\t\t\t\t\t const cvt::cvTile<OutputPixelType> ** outTile);\n\n\tprotected:\n\n\n\tErrorCode allocateAdditionalGpuMemory();\n\tvirtual ErrorCode launchKernel(unsigned bw, unsigned bh);\n\tvoid computeRelativeOffsets();\n\tErrorCode transferRelativeOffsetsToDevice();\n\tErrorCode copyTileFromDevice(const cvt::cvTile<OutputPixelType> ** tilePtr);\n\n\t\/**\n\t * PROTECTED ATTRIBUTES\n\t * *\/\n\tssize_t windowRadius_;\n\tstd::vector<int2> relativeOffsets_;\n\tint2 *relativeOffsetsGpu_;\n\tenum windowRadiusType type;\n\t\/***************************\n\t * NOTE: Any class that extends the window filter class can not have an roi that\n\t * is equal to the whole image. You will need a buffer.\n\t *\n\t **************************\/\n\tsize_t roiWidth_;\n\tcv::Size2i roiSize_;\n\tsize_t bufferWidth_;\n\n}; \/\/ END of GpuWindowFilterAlgorithm\n\ntemplate< typename InputPixelType, int InputBandCount, typename OutputPixelType, int OutputBandCount >\nGpuWindowFilterAlgorithm<InputPixelType, InputBandCount, OutputPixelType, OutputBandCount>::GpuWindowFilterAlgorithm(\n\tunsigned int cudaDeviceId, size_t roiDataWidth,\n\tsize_t roiDataHeight, ssize_t windowRadius)\n\t: cvt::gpu::GpuAlgorithm<InputPixelType, InputBandCount, OutputPixelType, OutputBandCount>(\n\tcudaDeviceId, roiDataWidth + windowRadius * 2, roiDataHeight + windowRadius * 2),\n\twindowRadius_(windowRadius), roiSize_(roiDataWidth,roiDataHeight), bufferWidth_(windowRadius)\n{\n\t;\n}\n\ntemplate< typename InputPixelType, int InputBandCount, typename OutputPixelType, int OutputBandCount >\nGpuWindowFilterAlgorithm<InputPixelType, InputBandCount, OutputPixelType, OutputBandCount>::~GpuWindowFilterAlgorithm() {\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\/\/ FREE CUDA ARRAYS USED FOR GPU INPUT \/\/\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\tcudaFree(relativeOffsetsGpu_);\n\n\tcudaError cuer3 = cudaGetLastError();\n\tif(cuer3 == cudaErrorInvalidValue)\n\t\tthis->lastError = DestructFailcuOutArraycudaErrorInvalidValue;\n\telse if(cuer3 == cudaErrorInitializationError)\n\t\tthis->lastError = DestructFailcuOutArraycudaErrorInitializationError;\n\telse if(cuer3 != cudaSuccess)\n\t\tthis->lastError = CudaError;\n}\n\ntemplate< typename InputPixelType, int InputBandCount, typename OutputPixelType, int OutputBandCount >\nErrorCode GpuWindowFilterAlgorithm<InputPixelType, InputBandCount, OutputPixelType, OutputBandCount>::operator()(const cvt::cvTile<InputPixelType>& tile,\n\t\t\t\t\t\t\t\t\t\t\t\t\t const cvt::cvTile<OutputPixelType> ** outTile)\n{\n\t\t\/\/TO-DO Error Check Template Params for Type\/Bounds\n\n\tconst cv::Size2i tileSize = tile.getSize();\n\n\tif (tileSize != this->dataSize)\n\t{\n\t\tstd::stringstream ss;\n\t\tss << tileSize << \" expected of \" << this->dataSize << std::endl;\n\t\tthrow std::runtime_error(ss.str());\n\t}\n\n\t\/*\n\t * Copy data down for tile using the parents implementation\n\t *\/\n\tthis->lastError = this->copyTileToDevice(tile);\n\tif (this->lastError != cvt::Ok)\n\t{\n\t\tthrow std::runtime_error(\"Failed to copy tile to device\");\n\t}\n\n\t\/\/ Invoke kernel with empirically chosen block size\n\tunsigned short bW = 16; \/\/ 16\n\tunsigned short bH = 16; \/\/ 16\n\n\n\tif ((unsigned int) tile.getROI().x != bufferWidth_) {\n\t\tthrow std::runtime_error(\"Buffer size of incoming tile is not equal to the window radius\");\n\t}\n\n\tlaunchKernel(bW, bH);\n\n\tthis->lastError = this->copyTileFromDevice(outTile);\n\tif(this->lastError != cvt::Ok) {\n\t\tstd::runtime_error(\"Failed copy off tile from device\");\n\t}\n\treturn Ok;\n}\n\ntemplate< typename InputPixelType, int InputBandCount, typename OutputPixelType, int OutputBandCount >\nErrorCode GpuWindowFilterAlgorithm<InputPixelType, InputBandCount, OutputPixelType, OutputBandCount>::initializeDevice(enum windowRadiusType type)\n{\n\t\/* Initialize additional argument then allow parent to init card *\/\n\tthis->type = type;\n\tGpuAlgorithm<InputPixelType, InputBandCount, OutputPixelType, OutputBandCount>::initializeDevice();\n\n\t\/* Transfer offsets to card *\/\n\ttransferRelativeOffsetsToDevice();\n\n\treturn this->lastError;\n}\n\ntemplate< typename InputPixelType, int InputBandCount, typename OutputPixelType, int OutputBandCount >\nErrorCode GpuWindowFilterAlgorithm<InputPixelType, InputBandCount, OutputPixelType, OutputBandCount>::copyTileFromDevice(const cvt::cvTile<OutputPixelType> ** tilePtr)\n{\n\n\tconst size_t bytes = roiSize_.area() * OutputBandCount * sizeof(OutputPixelType);\n\tstd::vector<OutputPixelType> data;\n\tdata.resize(bytes\/sizeof(OutputPixelType));\n\n\tcudaMemcpyAsync(\n\t\t\t&(data[0]),\n\t\t\tthis->gpuOutputData,\n\t\t\tbytes,\n\t\t\tcudaMemcpyDeviceToHost,\n\t\t\tthis->stream\n\t\t\t);\n\n\tcudaError cuer = cudaGetLastError();\n\tif(cuer == cudaErrorInvalidValue)\n\t\tthis->lastError = TileFromDevicecudaErrorInvalidValue;\n\telse if(cuer == cudaErrorInvalidDevicePointer)\n\t\tthis->lastError = TileFromDevicecudaErrorInvalidDevicePointer;\n\telse if(cuer == cudaErrorInvalidMemcpyDirection)\n\t\tthis->lastError = TileFromDevicecudaErrorInvalidMemcpyDirection;\n\telse if(cuer != cudaSuccess)\n\t\tthis->lastError = CudaError;\n\n\t\/*for(const auto& ele: data)\n\t{\n\t\tstd::cout << \"data: \" << ele << std::endl;\n\n\t}*\/\n\tif(cuer == cudaSuccess) {\n\t\t(*tilePtr) = new cvTile<OutputPixelType>(&(data[0]), roiSize_, OutputBandCount);\n\t}\n\telse\n\t\t(*tilePtr) = NULL;\n\n\treturn this->lastError;\n}\n\ntemplate< typename InputPixelType, int InputBandCount, typename OutputPixelType, int OutputBandCount >\nErrorCode GpuWindowFilterAlgorithm<InputPixelType, InputBandCount, OutputPixelType, OutputBandCount>::launchKernel(\n\t__attribute__((unused)) unsigned bw,\n\t__attribute__((unused)) unsigned bh) {\n\treturn Ok; \/\/ NEED TO ADD DEFAULT KERNEL FOR FILTER\n}\n\ntemplate< typename InputPixelType, int InputBandCount, typename OutputPixelType, int OutputBandCount >\nErrorCode GpuWindowFilterAlgorithm<InputPixelType, InputBandCount, OutputPixelType, OutputBandCount>::allocateAdditionalGpuMemory()\n{\n\tcomputeRelativeOffsets();\n\tcudaMalloc((void**)&relativeOffsetsGpu_, sizeof(int2) * relativeOffsets_.size());\n\tcudaError cuer = cudaGetLastError();\n\tif (cuer != cudaSuccess) {\n\t\tthrow std::runtime_error(\"GPU WHS () FAILURE TO ALLOCATE MEMORY FOR RELATIVE COORDS\");\n\t}\n\tif (cuer == cudaErrorMemoryAllocation)\n\t{\n\t\tthis->lastError = InitFailcuOutArrayMemErrorcudaErrorMemoryAllocation;\n\t}\n\treturn this->lastError;\n}\n\ntemplate< typename InputPixelType, int InputBandCount, typename OutputPixelType, int OutputBandCount >\nvoid GpuWindowFilterAlgorithm<InputPixelType,InputBandCount, OutputPixelType, OutputBandCount>::computeRelativeOffsets()\n{\n\tif (type == CIRCLE) {\n\t\tconst size_t radius_squared = windowRadius_ * windowRadius_;\n\t\tfor(ssize_t i = 0 - windowRadius_; i <= windowRadius_; ++i){\n\t\t\tsize_t i_squared = i * i;\n\t\t\tfor(ssize_t j = 0 - windowRadius_; j <= windowRadius_; ++j){\n\t\t\t\tif(i_squared + j * j <= radius_squared)\n\t\t\t\t\trelativeOffsets_.push_back(make_int2(i,j));\n\t\t\t}\n\t\t}\n\t}\n\telse {\n\t\tfor (ssize_t i = 0 - windowRadius_; i <= windowRadius_; ++i) {\n\t\t\tfor (ssize_t j = 0 - windowRadius_; j <= windowRadius_; ++j) {\n\t\t\t\trelativeOffsets_.push_back(make_int2(i,j));\n\t\t\t}\n\t\t}\n\n\t}\n}\n\ntemplate< typename InputPixelType, int InputBandCount, typename OutputPixelType, int OutputBandCount >\nErrorCode GpuWindowFilterAlgorithm<InputPixelType, InputBandCount, OutputPixelType, OutputBandCount>::transferRelativeOffsetsToDevice()\n{\n\tcudaMemcpyAsync(\n\t\trelativeOffsetsGpu_,\n\t\trelativeOffsets_.data(),\n\t\trelativeOffsets_.size() * sizeof(int2),\n\t\tcudaMemcpyHostToDevice,\n\t\tthis->stream\n\t);\n\n\tcudaError cuer = cudaGetLastError();\n\tif (cuer != cudaSuccess) {\n\t\tstd::cout << \"CUDA ERR = \" << cuer << std::endl;\n\t\tthrow std::runtime_error(\"GPU WHS () FAILED TO MEMCPY RELATIVE COORDS ON TO DEVICE\");\n\t}\n\n\t\/\/cuer = cvt::gpu::load_relative_offsets(this->stream,this->relativeOffsets_.data(), this->relativeOffsets_.size());\n\t\/\/if (cuer != cudaSuccess) {\n\t\/\/\tstd::cout << \"CUDA ERR = \" << cuer << std::endl;\n\t\/\/\tthrow std::runtime_error(\"GPU WHS TO CONSTANT MEMORY\");\n\t\/\/}\n\n\treturn this->lastError;\n}\n\n} \/\/ END of cvt namespace\n} \/\/ END of gpu namespace\n\n#endif\n<commit_msg>Incremental manual reapply of LBP<commit_after>\/*\n*******************************************************************************\n\nCopyright (c) 2015, The Curators of the University of Missouri\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n1. Redistributions of source code must retain the above copyright notice,\n this list of conditions and the following disclaimer.\n\n2. Redistributions in binary form must reproduce the above copyright notice,\n this list of conditions and the following disclaimer in the documentation\n and\/or other materials provided with the distribution.\n\n3. Neither the name of the copyright holder nor the names of its contributors\n may be used to endorse or promote products derived from this software\n without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n*******************************************************************************\n*\/\n\n#ifndef GPU_WINDOW_FITLER_ALGORITHM_\n#define GPU_WINDOW_FITLER_ALGORITHM_\n\n#include \"GpuAlgorithm.hpp\"\n#include \"..\/kernels\/GpuAlgorithmKernels.hpp\"\n\nnamespace cvt {\nnamespace gpu {\n\nenum windowRadiusType{\n\tSQUARE,\n\tCIRCLE,\n\tSPARSE_RING\n};\n\n\ntemplate< typename InputPixelType, int InputBandCount, typename OutputPixelType, int OutputBandCount >\nclass GpuWindowFilterAlgorithm : public GpuAlgorithm<InputPixelType, InputBandCount, OutputPixelType, OutputBandCount>\n{\n\n\tusing GpuAlgorithm<InputPixelType, InputBandCount, OutputPixelType, OutputBandCount>::initializeDevice;\n\n\tpublic:\n\n\texplicit GpuWindowFilterAlgorithm(unsigned int cudaDeviceId, size_t roiDataWidth,\n\t\t\t\t\t\t\t \t\t size_t roiDataHeight, ssize_t windowRadius);\n\n\tvirtual ~GpuWindowFilterAlgorithm();\n\tvirtual ErrorCode initializeDevice(enum windowRadiusType type);\n\n\tvirtual ErrorCode operator()(const cvt::cvTile<InputPixelType>& tile,\n\t\t\t\t\t\t\t\t const cvt::cvTile<OutputPixelType> ** outTile);\n\n\tprotected:\n\n\n\tErrorCode allocateAdditionalGpuMemory();\n\tvirtual ErrorCode launchKernel(unsigned bw, unsigned bh);\n\tvoid computeRelativeOffsets();\n\tErrorCode transferRelativeOffsetsToDevice();\n\tErrorCode copyTileFromDevice(const cvt::cvTile<OutputPixelType> ** tilePtr);\n\n\t\/**\n\t * PROTECTED ATTRIBUTES\n\t * *\/\n\tssize_t windowRadius_;\n\tstd::vector<int2> relativeOffsets_;\n\tint2 *relativeOffsetsGpu_;\n\tenum windowRadiusType type_;\n\t\/***************************\n\t * NOTE: Any class that extends the window filter class can not have an roi that\n\t * is equal to the whole image. You will need a buffer.\n\t *\n\t **************************\/\n\tsize_t roiWidth_;\n\tcv::Size2i roiSize_;\n\tsize_t bufferWidth_;\n\n}; \/\/ END of GpuWindowFilterAlgorithm\n\ntemplate< typename InputPixelType, int InputBandCount, typename OutputPixelType, int OutputBandCount >\nGpuWindowFilterAlgorithm<InputPixelType, InputBandCount, OutputPixelType, OutputBandCount>::GpuWindowFilterAlgorithm(\n\tunsigned int cudaDeviceId, size_t roiDataWidth,\n\tsize_t roiDataHeight, ssize_t windowRadius)\n\t: cvt::gpu::GpuAlgorithm<InputPixelType, InputBandCount, OutputPixelType, OutputBandCount>(\n\tcudaDeviceId, roiDataWidth + windowRadius * 2, roiDataHeight + windowRadius * 2),\n\twindowRadius_(windowRadius), roiSize_(roiDataWidth,roiDataHeight), bufferWidth_(windowRadius)\n{\n\t;\n}\n\ntemplate< typename InputPixelType, int InputBandCount, typename OutputPixelType, int OutputBandCount >\nGpuWindowFilterAlgorithm<InputPixelType, InputBandCount, OutputPixelType, OutputBandCount>::~GpuWindowFilterAlgorithm() {\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\/\/ FREE CUDA ARRAYS USED FOR GPU INPUT \/\/\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\tcudaFree(relativeOffsetsGpu_);\n\n\tcudaError cuer3 = cudaGetLastError();\n\tif(cuer3 == cudaErrorInvalidValue)\n\t\tthis->lastError = DestructFailcuOutArraycudaErrorInvalidValue;\n\telse if(cuer3 == cudaErrorInitializationError)\n\t\tthis->lastError = DestructFailcuOutArraycudaErrorInitializationError;\n\telse if(cuer3 != cudaSuccess)\n\t\tthis->lastError = CudaError;\n}\n\ntemplate< typename InputPixelType, int InputBandCount, typename OutputPixelType, int OutputBandCount >\nErrorCode GpuWindowFilterAlgorithm<InputPixelType, InputBandCount, OutputPixelType, OutputBandCount>::operator()(const cvt::cvTile<InputPixelType>& tile,\n\t\t\t\t\t\t\t\t\t\t\t\t\t const cvt::cvTile<OutputPixelType> ** outTile)\n{\n\t\t\/\/TO-DO Error Check Template Params for Type\/Bounds\n\n\tconst cv::Size2i tileSize = tile.getSize();\n\n\tif (tileSize != this->dataSize)\n\t{\n\t\tstd::stringstream ss;\n\t\tss << tileSize << \" expected of \" << this->dataSize << std::endl;\n\t\tthrow std::runtime_error(ss.str());\n\t}\n\n\t\/*\n\t * Copy data down for tile using the parents implementation\n\t *\/\n\tthis->lastError = this->copyTileToDevice(tile);\n\tif (this->lastError != cvt::Ok)\n\t{\n\t\tthrow std::runtime_error(\"Failed to copy tile to device\");\n\t}\n\n\t\/\/ Invoke kernel with empirically chosen block size\n\tunsigned short bW = 16; \/\/ 16\n\tunsigned short bH = 16; \/\/ 16\n\n\n\tif ((unsigned int) tile.getROI().x != bufferWidth_) {\n\t\tthrow std::runtime_error(\"Buffer size of incoming tile is not equal to the window radius\");\n\t}\n\n\tlaunchKernel(bW, bH);\n\n\tthis->lastError = this->copyTileFromDevice(outTile);\n\tif(this->lastError != cvt::Ok) {\n\t\tstd::runtime_error(\"Failed copy off tile from device\");\n\t}\n\treturn Ok;\n}\n\ntemplate< typename InputPixelType, int InputBandCount, typename OutputPixelType, int OutputBandCount >\nErrorCode GpuWindowFilterAlgorithm<InputPixelType, InputBandCount, OutputPixelType, OutputBandCount>::initializeDevice(enum windowRadiusType type)\n{\n\t\/* Initialize additional argument then allow parent to init card *\/\n\ttype_ = type;\n\tGpuAlgorithm<InputPixelType, InputBandCount, OutputPixelType, OutputBandCount>::initializeDevice();\n\n\t\/* Transfer offsets to card *\/\n\ttransferRelativeOffsetsToDevice();\n\n\treturn this->lastError;\n}\n\ntemplate< typename InputPixelType, int InputBandCount, typename OutputPixelType, int OutputBandCount >\nErrorCode GpuWindowFilterAlgorithm<InputPixelType, InputBandCount, OutputPixelType, OutputBandCount>::copyTileFromDevice(const cvt::cvTile<OutputPixelType> ** tilePtr)\n{\n\n\tconst size_t bytes = roiSize_.area() * OutputBandCount * sizeof(OutputPixelType);\n\tstd::vector<OutputPixelType> data;\n\tdata.resize(bytes\/sizeof(OutputPixelType));\n\n\tcudaMemcpyAsync(\n\t\t\t&(data[0]),\n\t\t\tthis->gpuOutputData,\n\t\t\tbytes,\n\t\t\tcudaMemcpyDeviceToHost,\n\t\t\tthis->stream\n\t\t\t);\n\n\tcudaError cuer = cudaGetLastError();\n\tif(cuer == cudaErrorInvalidValue)\n\t\tthis->lastError = TileFromDevicecudaErrorInvalidValue;\n\telse if(cuer == cudaErrorInvalidDevicePointer)\n\t\tthis->lastError = TileFromDevicecudaErrorInvalidDevicePointer;\n\telse if(cuer == cudaErrorInvalidMemcpyDirection)\n\t\tthis->lastError = TileFromDevicecudaErrorInvalidMemcpyDirection;\n\telse if(cuer != cudaSuccess)\n\t\tthis->lastError = CudaError;\n\n\t\/*for(const auto& ele: data)\n\t{\n\t\tstd::cout << \"data: \" << ele << std::endl;\n\n\t}*\/\n\tif(cuer == cudaSuccess) {\n\t\t(*tilePtr) = new cvTile<OutputPixelType>(&(data[0]), roiSize_, OutputBandCount);\n\t}\n\telse\n\t\t(*tilePtr) = NULL;\n\n\treturn this->lastError;\n}\n\ntemplate< typename InputPixelType, int InputBandCount, typename OutputPixelType, int OutputBandCount >\nErrorCode GpuWindowFilterAlgorithm<InputPixelType, InputBandCount, OutputPixelType, OutputBandCount>::launchKernel(\n\t__attribute__((unused)) unsigned bw,\n\t__attribute__((unused)) unsigned bh) {\n\treturn Ok; \/\/ NEED TO ADD DEFAULT KERNEL FOR FILTER\n}\n\ntemplate< typename InputPixelType, int InputBandCount, typename OutputPixelType, int OutputBandCount >\nErrorCode GpuWindowFilterAlgorithm<InputPixelType, InputBandCount, OutputPixelType, OutputBandCount>::allocateAdditionalGpuMemory()\n{\n\tcomputeRelativeOffsets();\n\tcudaMalloc((void**)&relativeOffsetsGpu_, sizeof(int2) * relativeOffsets_.size());\n\tcudaError cuer = cudaGetLastError();\n\tif (cuer != cudaSuccess) {\n\t\tthrow std::runtime_error(\"GPU WINDOW FILTER ALGORITHM () FAILURE TO ALLOCATE MEMORY FOR RELATIVE COORDS\");\n\t}\n\tif (cuer == cudaErrorMemoryAllocation)\n\t{\n\t\tthis->lastError = InitFailcuOutArrayMemErrorcudaErrorMemoryAllocation;\n\t}\n\treturn this->lastError;\n}\n\ntemplate< typename InputPixelType, int InputBandCount, typename OutputPixelType, int OutputBandCount >\nvoid GpuWindowFilterAlgorithm<InputPixelType,InputBandCount, OutputPixelType, OutputBandCount>::computeRelativeOffsets()\n{\n\tif (type_ == CIRCLE) {\n\t\tconst size_t radius_squared = windowRadius_ * windowRadius_;\n\t\tfor(ssize_t i = 0 - windowRadius_; i <= windowRadius_; ++i){\n\t\t\tsize_t i_squared = i * i;\n\t\t\tfor(ssize_t j = 0 - windowRadius_; j <= windowRadius_; ++j){\n\t\t\t\tif(i_squared + j * j <= radius_squared)\n\t\t\t\t\trelativeOffsets_.push_back(make_int2(i,j));\n\t\t\t}\n\t\t}\n\t}\n\telse if (type_ == SPARSE_RING) {\n\t\t\/\/TODO(TYLER): These limits seem suspect...\n\t const size_t numOffsets = sizeof(OutputPixelType) * 8;\n\t \/\/TODO(Tyler): Remove this debug comment before merging.\n\t \/\/std::cout << \"computeRelative::numOffsets = \" << numOffsets << std::endl;\n\t const size_t maxOffsets = (windowRadius_ * 2 + 1) * (windowRadius_ * 2 + 1);\n\n\t if (numOffsets > maxOffsets)\n\t {\n\t\t\tthrow std::invalid_argument(\"computeRelativeOffets: output size was larger than maximum neighbors.\");\n\t }\n\n\t const double angleStep = 2 * M_PI \/ numOffsets;\n\t double currAngle = 0;\n\t ssize_t xOffset , yOffset;\n\n\t for (size_t i = 0; i<numOffsets; i++) {\n\t\t\txOffset = (ssize_t) (round (windowRadius_ * sin (currAngle)));\n\t\t\tyOffset = (ssize_t) (round (windowRadius_ * cos (currAngle)));\n\t\t\tcurrAngle += angleStep;\n\t\t\trelativeOffsets_.push_back(make_int2(xOffset,yOffset));\n\t }\n\t}\n\telse {\n\t\tfor (ssize_t i = 0 - windowRadius_; i <= windowRadius_; ++i) {\n\t\t\tfor (ssize_t j = 0 - windowRadius_; j <= windowRadius_; ++j) {\n\t\t\t\trelativeOffsets_.push_back(make_int2(i,j));\n\t\t\t}\n\t\t}\n\n\t}\n}\n\ntemplate< typename InputPixelType, int InputBandCount, typename OutputPixelType, int OutputBandCount >\nErrorCode GpuWindowFilterAlgorithm<InputPixelType, InputBandCount, OutputPixelType, OutputBandCount>::transferRelativeOffsetsToDevice()\n{\n\tcudaMemcpyAsync(\n\t\trelativeOffsetsGpu_,\n\t\trelativeOffsets_.data(),\n\t\trelativeOffsets_.size() * sizeof(int2),\n\t\tcudaMemcpyHostToDevice,\n\t\tthis->stream\n\t);\n\n\tcudaError cuer = cudaGetLastError();\n\tif (cuer != cudaSuccess) {\n\t\tstd::cout << \"CUDA ERR = \" << cuer << std::endl;\n\t\tthrow std::runtime_error(\"GPU WHS () FAILED TO MEMCPY RELATIVE COORDS ON TO DEVICE\");\n\t}\n\n\t\/\/cuer = cvt::gpu::load_relative_offsets(this->stream,this->relativeOffsets_.data(), this->relativeOffsets_.size());\n\t\/\/if (cuer != cudaSuccess) {\n\t\/\/\tstd::cout << \"CUDA ERR = \" << cuer << std::endl;\n\t\/\/\tthrow std::runtime_error(\"GPU WHS TO CONSTANT MEMORY\");\n\t\/\/}\n\n\treturn this->lastError;\n}\n\n} \/\/ END of cvt namespace\n} \/\/ END of gpu namespace\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>#pragma once\r\n\/\/=====================================================================\/\/\r\n\/*!\t@file\r\n\t@brief\tethernet_client class\r\n @author 平松邦仁 (hira@rvf-rc45.net)\r\n\t@copyright\tCopyright (C) 2017 Kunihito Hiramatsu @n\r\n\t\t\t\tReleased under the MIT license @n\r\n\t\t\t\thttps:\/\/github.com\/hirakuni45\/RX\/blob\/master\/LICENSE\r\n*\/\r\n\/\/=====================================================================\/\/\r\n#include \"ethernet.hpp\"\r\n\r\n#include \"common\/delay.hpp\"\r\n\r\nnamespace net {\r\n\r\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\r\n\t\/*!\r\n\t\t@brief ethernet_client class\r\n\t*\/\r\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\r\n\tclass ethernet_client {\r\n\r\n\t\tethernet&\tethernet_;\r\n\r\n\t\tuint32_t\tcepid_;\r\n\t\tuint16_t\tport_;\r\n\r\n\t\tuint16_t\tclose_count_;\r\n\r\n\tpublic:\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brief コンストラクター\r\n\t\t\t@param[in]\te\tインサーネットへの参照\r\n\t\t\t@param[in]\tport\tポート番号\r\n\t\t*\/\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\tethernet_client(ethernet& e, uint16_t port) : ethernet_(e), cepid_(0), port_(port),\r\n\t\t\tclose_count_(0) { }\r\n\r\n\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brief デストラクター\r\n\t\t*\/\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\t~ethernet_client() {\r\n\t\t\tstop();\r\n\t\t}\r\n\r\n\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brief ethernet を参照\r\n\t\t\t@return ethernet\r\n\t\t*\/\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\tethernet& at_ethernet() { return ethernet_; }\r\n\r\n\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brief ethernet を参照\r\n\t\t\t@return ethernet\r\n\t\t*\/\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\tconst ethernet& get_ethernet() const { return ethernet_; }\r\n\r\n\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brief ポート番号を取得\r\n\t\t\t@return ポート番号\r\n\t\t*\/\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\tuint16_t get_port() const { return port_; }\r\n\r\n\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brief CEP ID を取得\r\n\t\t\t@return CEP ID\r\n\t\t*\/\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\tuint32_t get_cepid() const { return cepid_; }\r\n\r\n\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brief 接続先を取得\r\n\t\t\t@return 接続先\r\n\t\t*\/\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\tconst ip_address& get_from_ip() const {\r\n\t\t\tconst ethernet::CEP& cep = ethernet_.get_cep(cepid_);\r\n\t\t\tuint32_t ipw = cep.src_addr.ipaddr;\r\n\t\t\tstatic ip_address ip((ipw >> 24) & 255, (ipw >> 16) & 255, (ipw >> 8) & 255, ipw & 255);\r\n\t\t\treturn ip;\r\n\t\t}\r\n\r\n\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brief コネクション\r\n\t\t\t@param[in]\tip\t\t接続先の IP アドレス\r\n\t\t\t@param[in]\tport\t接続ポート\r\n\t\t\t@param[in]\ttimeout\tタイムアウト、単位10ミリ秒(標準で10秒)\r\n\t\t\t@return 接続できた場合「true」\r\n\t\t*\/\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\tbool connect(const ip_address& ip, uint16_t port, int32_t timeout = 1000)\r\n\t\t{\r\n\t\t\tif(cepid_ == 0) {\r\n\t\t\t\tcepid_ = ethernet_.create(port_);\r\n\t\t\t\tif(cepid_ == 0) return false;\r\n\t\t\t\tclose_count_ = tcp_get_close_count(cepid_);\r\n\t\t\t}\r\n\r\n\t\t\tauto& cep = ethernet_.at_cep(cepid_);\r\n\t\t\tcep.server = false;\r\n\r\n\t\t\tif(connected()) {\r\n\t\t\t\treturn true;\r\n\t\t\t}\r\n\r\n\t\t\tdebug_format(\"TCP Client Request Connect: %d\\n\") % cepid_;\r\n\r\n\t\t\tstatic T_IPV4EP adr;\r\n\t\t\tadr.ipaddr = (static_cast<uint32_t>(ip[0]) << 24)\r\n\t\t\t\t\t\t| (static_cast<uint32_t>(ip[1]) << 16)\r\n\t\t\t\t\t\t| (static_cast<uint32_t>(ip[2]) << 8)\r\n\t\t\t\t\t\t| (static_cast<uint32_t>(ip[3]));\r\n\t\t\tadr.portno = port;\r\n\t\t\tint ercd = tcp_con_cep(cepid_, NADR, &adr, timeout);\r\n\t\t\tbool ret = true;\r\n\t\t\tif(ercd == E_OK) {\r\n\t\t\t\tdebug_format(\"TCP Client connect OK: %d\\n\") % cepid_;\r\n\t\t\t} else if(ercd == E_QOVR) {\r\n\t\t\t\tdebug_format(\"TCP Client E_QOVR: %d\\n\") % cepid_;\r\n\t\t\t\tret = false;\r\n\t\t\t} else {\r\n\t\t\t\tdebug_format(\"TCP Client connect state(%d): %d\\n\") % ercd % cepid_;\r\n\t\t\t}\r\n\t\t\ttcp_clear_rst(cepid_);\r\n\t\t\treturn ret;\r\n\t\t}\r\n\r\n\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brief 再接続要求\r\n\t\t\t@return 正常なら「true」\r\n\t\t*\/\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\tbool re_connect(const ip_address& ip, uint16_t port)\r\n\t\t{\r\n\t\t\tif(cepid_ == 0) { \/\/ ディスクリプタが無効\r\n\t\t\t\treturn false;\r\n\t\t\t}\r\n\r\n\t\t\tstatic T_IPV4EP adr;\r\n\t\t\tadr.ipaddr = (static_cast<uint32_t>(ip[0]) << 24)\r\n\t\t\t\t\t\t| (static_cast<uint32_t>(ip[1]) << 16)\r\n\t\t\t\t\t\t| (static_cast<uint32_t>(ip[2]) << 8)\r\n\t\t\t\t\t\t| (static_cast<uint32_t>(ip[3]));\r\n\t\t\tadr.portno = port;\r\n\r\n\t\t\tif(tcp_re_con_cep(cepid_, &adr) < 0) {\r\n\t\t\t\treturn false;\r\n\t\t\t} else {\r\n\t\t\t\treturn true;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brief 接続確認\r\n\t\t\t@return 接続中なら「true」\r\n\t\t*\/\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\tbool connected()\r\n\t\t{\r\n\t\t\treturn ethernet_.connected(cepid_);\r\n\t\t}\r\n\r\n\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brief 読み込み\r\n\t\t\t@param[out]\tbuff\t読み込み先\r\n\t\t\t@param[in]\tsize\t読み込みサイズ\r\n\t\t\t@return 読み込みサイズ(負の場合エラー)\r\n\t\t*\/\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\tint read(void* buff, size_t size)\r\n\t\t{\r\n\t\t\treturn ethernet_.read(cepid_, buff, size);\r\n\t\t}\r\n\r\n\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brief 書き込み\r\n\t\t\t@param[in]\tbuff\t書き込み元\r\n\t\t\t@param[in]\tsize\tサイズ\r\n\t\t\t@return 書き込みサイズ(負の場合エラー)\r\n\t\t*\/\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\tint32_t write(const void* buffer, uint32_t size)\r\n\t\t{\r\n\t\t\treturn ethernet_.write(cepid_, buffer, size);\r\n\t\t}\r\n\r\n\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brief 有効なデータがあるか\r\n\t\t\t@return 有効なデータ数\r\n\t\t*\/\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\tint available()\r\n\t\t{\r\n\t\t\treturn ethernet_.available(cepid_);\r\n\t\t}\r\n\r\n\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brief 停止\r\n\t\t*\/\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n void stop()\r\n\t\t{\r\n\t\t\tif(!connected()) {\r\n\t\t\t\ttcp_sht_cep(cepid_, TMO_FEVR);\r\n\t\t\t}\r\n\t\t\ttcp_cls_cep(cepid_, TMO_FEVR);\r\n\t\t\tethernet::CEP& cep = ethernet_.at_cep(cepid_);\r\n\t\t\tend();\r\n\t\t}\r\n\r\n\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brief 終了\r\n\t\t*\/\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\tvoid end()\r\n\t\t{\r\n\t\t\tethernet_.end_connection(cepid_);\r\n\t\t\tcepid_ = 0;\r\n\t\t}\r\n\t};\r\n}\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n<commit_msg>fix client stop blockking<commit_after>#pragma once\r\n\/\/=====================================================================\/\/\r\n\/*!\t@file\r\n\t@brief\tethernet_client class\r\n @author 平松邦仁 (hira@rvf-rc45.net)\r\n\t@copyright\tCopyright (C) 2017 Kunihito Hiramatsu @n\r\n\t\t\t\tReleased under the MIT license @n\r\n\t\t\t\thttps:\/\/github.com\/hirakuni45\/RX\/blob\/master\/LICENSE\r\n*\/\r\n\/\/=====================================================================\/\/\r\n#include \"ethernet.hpp\"\r\n\r\n#include \"common\/delay.hpp\"\r\n\r\nnamespace net {\r\n\r\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\r\n\t\/*!\r\n\t\t@brief ethernet_client class\r\n\t*\/\r\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\r\n\tclass ethernet_client {\r\n\r\n\t\tethernet&\tethernet_;\r\n\r\n\t\tuint32_t\tcepid_;\r\n\t\tuint16_t\tport_;\r\n\r\n\t\tuint16_t\tclose_count_;\r\n\r\n\tpublic:\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brief コンストラクター\r\n\t\t\t@param[in]\te\tインサーネットへの参照\r\n\t\t\t@param[in]\tport\tポート番号\r\n\t\t*\/\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\tethernet_client(ethernet& e, uint16_t port) : ethernet_(e), cepid_(0), port_(port),\r\n\t\t\tclose_count_(0) { }\r\n\r\n\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brief デストラクター\r\n\t\t*\/\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\t~ethernet_client() {\r\n\t\t\tstop();\r\n\t\t}\r\n\r\n\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brief ethernet を参照\r\n\t\t\t@return ethernet\r\n\t\t*\/\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\tethernet& at_ethernet() { return ethernet_; }\r\n\r\n\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brief ethernet を参照\r\n\t\t\t@return ethernet\r\n\t\t*\/\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\tconst ethernet& get_ethernet() const { return ethernet_; }\r\n\r\n\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brief ポート番号を取得\r\n\t\t\t@return ポート番号\r\n\t\t*\/\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\tuint16_t get_port() const { return port_; }\r\n\r\n\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brief CEP ID を取得\r\n\t\t\t@return CEP ID\r\n\t\t*\/\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\tuint32_t get_cepid() const { return cepid_; }\r\n\r\n\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brief 接続先を取得\r\n\t\t\t@return 接続先\r\n\t\t*\/\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\tconst ip_address& get_from_ip() const {\r\n\t\t\tconst ethernet::CEP& cep = ethernet_.get_cep(cepid_);\r\n\t\t\tuint32_t ipw = cep.src_addr.ipaddr;\r\n\t\t\tstatic ip_address ip((ipw >> 24) & 255, (ipw >> 16) & 255, (ipw >> 8) & 255, ipw & 255);\r\n\t\t\treturn ip;\r\n\t\t}\r\n\r\n\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brief コネクション\r\n\t\t\t@param[in]\tip\t\t接続先の IP アドレス\r\n\t\t\t@param[in]\tport\t接続ポート\r\n\t\t\t@param[in]\ttimeout\tタイムアウト、単位10ミリ秒(標準で10秒)\r\n\t\t\t@return 接続できた場合「true」\r\n\t\t*\/\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\tbool connect(const ip_address& ip, uint16_t port, int32_t timeout = 1000)\r\n\t\t{\r\n\t\t\tif(cepid_ == 0) {\r\n\t\t\t\tcepid_ = ethernet_.create(port_);\r\n\t\t\t\tif(cepid_ == 0) return false;\r\n\t\t\t\tclose_count_ = tcp_get_close_count(cepid_);\r\n\t\t\t}\r\n\r\n\t\t\tauto& cep = ethernet_.at_cep(cepid_);\r\n\t\t\tcep.server = false;\r\n\r\n\t\t\tif(connected()) {\r\n\t\t\t\treturn true;\r\n\t\t\t}\r\n\r\n\t\t\tdebug_format(\"TCP Client Request Connect: %d\\n\") % cepid_;\r\n\r\n\t\t\tstatic T_IPV4EP adr;\r\n\t\t\tadr.ipaddr = (static_cast<uint32_t>(ip[0]) << 24)\r\n\t\t\t\t\t\t| (static_cast<uint32_t>(ip[1]) << 16)\r\n\t\t\t\t\t\t| (static_cast<uint32_t>(ip[2]) << 8)\r\n\t\t\t\t\t\t| (static_cast<uint32_t>(ip[3]));\r\n\t\t\tadr.portno = port;\r\n\t\t\tint ercd = tcp_con_cep(cepid_, NADR, &adr, timeout);\r\n\t\t\tbool ret = true;\r\n\t\t\tif(ercd == E_OK) {\r\n\t\t\t\tdebug_format(\"TCP Client connect OK: %d\\n\") % cepid_;\r\n\t\t\t} else if(ercd == E_QOVR) {\r\n\t\t\t\tdebug_format(\"TCP Client E_QOVR: %d\\n\") % cepid_;\r\n\t\t\t\tret = false;\r\n\t\t\t} else {\r\n\t\t\t\tdebug_format(\"TCP Client connect state(%d): %d\\n\") % ercd % cepid_;\r\n\t\t\t}\r\n\t\t\ttcp_clear_rst(cepid_);\r\n\t\t\treturn ret;\r\n\t\t}\r\n\r\n\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brief 再接続要求\r\n\t\t\t@return 正常なら「true」\r\n\t\t*\/\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\tbool re_connect(const ip_address& ip, uint16_t port)\r\n\t\t{\r\n\t\t\tif(cepid_ == 0) { \/\/ ディスクリプタが無効\r\n\t\t\t\treturn false;\r\n\t\t\t}\r\n\r\n\t\t\tstatic T_IPV4EP adr;\r\n\t\t\tadr.ipaddr = (static_cast<uint32_t>(ip[0]) << 24)\r\n\t\t\t\t\t\t| (static_cast<uint32_t>(ip[1]) << 16)\r\n\t\t\t\t\t\t| (static_cast<uint32_t>(ip[2]) << 8)\r\n\t\t\t\t\t\t| (static_cast<uint32_t>(ip[3]));\r\n\t\t\tadr.portno = port;\r\n\r\n\t\t\tif(tcp_re_con_cep(cepid_, &adr) < 0) {\r\n\t\t\t\treturn false;\r\n\t\t\t} else {\r\n\t\t\t\treturn true;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brief 接続確認\r\n\t\t\t@return 接続中なら「true」\r\n\t\t*\/\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\tbool connected()\r\n\t\t{\r\n\t\t\treturn ethernet_.connected(cepid_);\r\n\t\t}\r\n\r\n\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brief 読み込み\r\n\t\t\t@param[out]\tbuff\t読み込み先\r\n\t\t\t@param[in]\tsize\t読み込みサイズ\r\n\t\t\t@return 読み込みサイズ(負の場合エラー)\r\n\t\t*\/\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\tint read(void* buff, size_t size)\r\n\t\t{\r\n\t\t\treturn ethernet_.read(cepid_, buff, size);\r\n\t\t}\r\n\r\n\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brief 書き込み\r\n\t\t\t@param[in]\tbuff\t書き込み元\r\n\t\t\t@param[in]\tsize\tサイズ\r\n\t\t\t@return 書き込みサイズ(負の場合エラー)\r\n\t\t*\/\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\tint32_t write(const void* buffer, uint32_t size)\r\n\t\t{\r\n\t\t\treturn ethernet_.write(cepid_, buffer, size);\r\n\t\t}\r\n\r\n\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brief 有効なデータがあるか\r\n\t\t\t@return 有効なデータ数\r\n\t\t*\/\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\tint available()\r\n\t\t{\r\n\t\t\treturn ethernet_.available(cepid_);\r\n\t\t}\r\n\r\n\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brief 停止\r\n\t\t*\/\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n void stop()\r\n\t\t{\r\n\t\t\tif(!connected()) {\r\n\/\/\/\t\t\t\ttcp_sht_cep(cepid_, TMO_FEVR);\r\n\t\t\t\ttcp_sht_cep(cepid_, TMO_NBLK);\r\n\t\t\t}\r\n\/\/\/\t\t\ttcp_cls_cep(cepid_, TMO_FEVR);\r\n\t\t\ttcp_cls_cep(cepid_, TMO_NBLK);\r\n\t\t\tethernet::CEP& cep = ethernet_.at_cep(cepid_);\r\n\t\t\tend();\r\n\t\t}\r\n\r\n\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brief 終了\r\n\t\t*\/\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\tvoid end()\r\n\t\t{\r\n\t\t\tethernet_.end_connection(cepid_);\r\n\t\t\tcepid_ = 0;\r\n\t\t}\r\n\t};\r\n}\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n#include \"BenchTimer.h\"\n#include <Eigen\/Dense>\n#include <map>\n#include <string>\nusing namespace Eigen;\n\nstd::map<std::string,Array<float,1,4> > results;\n\ntemplate<typename Scalar,int Size>\nvoid bench(int id, int size = Size)\n{\n typedef Matrix<Scalar,Size,Size> Mat;\n Mat A(size,size);\n A.setRandom();\n A = A*A.adjoint();\n BenchTimer t_llt, t_ldlt, t_lu, t_fplu, t_qr, t_cpqr, t_fpqr, t_jsvd;\n \n int tries = 3;\n int rep = 1000\/size;\n if(rep==0) rep = 1;\n rep = rep*rep;\n \n LLT<Mat> llt(A);\n LDLT<Mat> ldlt(A);\n PartialPivLU<Mat> lu(A);\n FullPivLU<Mat> fplu(A);\n HouseholderQR<Mat> qr(A);\n ColPivHouseholderQR<Mat> cpqr(A);\n FullPivHouseholderQR<Mat> fpqr(A);\n JacobiSVD<Mat> jsvd(A.rows(),A.cols());\n \n BENCH(t_llt, tries, rep, llt.compute(A));\n BENCH(t_ldlt, tries, rep, ldlt.compute(A));\n BENCH(t_lu, tries, rep, lu.compute(A));\n BENCH(t_fplu, tries, rep, fplu.compute(A));\n BENCH(t_qr, tries, rep, qr.compute(A));\n BENCH(t_cpqr, tries, rep, cpqr.compute(A));\n BENCH(t_fpqr, tries, rep, fpqr.compute(A));\n if(size<500) \/\/ JacobiSVD is really too slow for too large matrices\n BENCH(t_jsvd, tries, rep, jsvd.compute(A,ComputeFullU|ComputeFullV));\n \n results[\"LLT\"][id] = t_llt.best();\n results[\"LDLT\"][id] = t_ldlt.best();\n results[\"PartialPivLU\"][id] = t_lu.best();\n results[\"FullPivLU\"][id] = t_fplu.best();\n results[\"HouseholderQR\"][id] = t_qr.best();\n results[\"ColPivHouseholderQR\"][id] = t_cpqr.best();\n results[\"FullPivHouseholderQR\"][id] = t_fpqr.best();\n results[\"JacobiSVD\"][id] = size<500 ? t_jsvd.best() : 0;\n}\n\nint main()\n{\n const int small = 8;\n const int medium = 100;\n const int large = 1000;\n const int xl = 4000;\n \n bench<float,small>(0);\n bench<float,Dynamic>(1,medium);\n bench<float,Dynamic>(2,large);\n bench<float,Dynamic>(3,xl);\n \n IOFormat fmt(3, 0, \" \\t\", \"\\n\", \"\", \"\");\n \n std::cout << \"solver\/size \" << small << \"\\t\" << medium << \"\\t\" << large << \"\\t\" << xl << \"\\n\";\n std::cout << \"LLT (ms) \" << (results[\"LLT\"]\/1000.).format(fmt) << \"\\n\";\n std::cout << \"LDLT (%) \" << (results[\"LDLT\"]\/results[\"LLT\"]).format(fmt) << \"\\n\";\n std::cout << \"PartialPivLU (%) \" << (results[\"PartialPivLU\"]\/results[\"LLT\"]).format(fmt) << \"\\n\";\n std::cout << \"FullPivLU (%) \" << (results[\"FullPivLU\"]\/results[\"LLT\"]).format(fmt) << \"\\n\";\n std::cout << \"HouseholderQR (%) \" << (results[\"HouseholderQR\"]\/results[\"LLT\"]).format(fmt) << \"\\n\";\n std::cout << \"ColPivHouseholderQR (%) \" << (results[\"ColPivHouseholderQR\"]\/results[\"LLT\"]).format(fmt) << \"\\n\";\n std::cout << \"FullPivHouseholderQR (%) \" << (results[\"FullPivHouseholderQR\"]\/results[\"LLT\"]).format(fmt) << \"\\n\";\n std::cout << \"JacobiSVD (%) \" << (results[\"JacobiSVD\"]\/results[\"LLT\"]).format(fmt) << \"\\n\";\n}\n<commit_msg>Add COD and BDCSVD in list of benched solvers.<commit_after>#include <iostream>\n#include \"BenchTimer.h\"\n#include <Eigen\/Dense>\n#include <map>\n#include <string>\nusing namespace Eigen;\n\nstd::map<std::string,Array<float,1,4> > results;\n\ntemplate<typename Scalar,int Size>\nvoid bench(int id, int size = Size)\n{\n typedef Matrix<Scalar,Size,Size> Mat;\n Mat A(size,size);\n A.setRandom();\n A = A*A.adjoint();\n BenchTimer t_llt, t_ldlt, t_lu, t_fplu, t_qr, t_cpqr, t_cod, t_fpqr, t_jsvd, t_bdcsvd;\n \n int tries = 3;\n int rep = 1000\/size;\n if(rep==0) rep = 1;\n\/\/ rep = rep*rep;\n \n LLT<Mat> llt(A);\n LDLT<Mat> ldlt(A);\n PartialPivLU<Mat> lu(A);\n FullPivLU<Mat> fplu(A);\n HouseholderQR<Mat> qr(A);\n ColPivHouseholderQR<Mat> cpqr(A);\n CompleteOrthogonalDecomposition<Mat> cod(A);\n FullPivHouseholderQR<Mat> fpqr(A);\n JacobiSVD<Mat> jsvd(A.rows(),A.cols());\n BDCSVD<Mat> bdcsvd(A.rows(),A.cols());\n \n BENCH(t_llt, tries, rep, llt.compute(A));\n BENCH(t_ldlt, tries, rep, ldlt.compute(A));\n BENCH(t_lu, tries, rep, lu.compute(A));\n BENCH(t_fplu, tries, rep, fplu.compute(A));\n BENCH(t_qr, tries, rep, qr.compute(A));\n BENCH(t_cpqr, tries, rep, cpqr.compute(A));\n BENCH(t_cod, tries, rep, cod.compute(A));\n BENCH(t_fpqr, tries, rep, fpqr.compute(A));\n if(size<500) \/\/ JacobiSVD is really too slow for too large matrices\n BENCH(t_jsvd, tries, rep, jsvd.compute(A,ComputeFullU|ComputeFullV));\n BENCH(t_bdcsvd, tries, rep, bdcsvd.compute(A,ComputeFullU|ComputeFullV));\n \n results[\"LLT\"][id] = t_llt.best();\n results[\"LDLT\"][id] = t_ldlt.best();\n results[\"PartialPivLU\"][id] = t_lu.best();\n results[\"FullPivLU\"][id] = t_fplu.best();\n results[\"HouseholderQR\"][id] = t_qr.best();\n results[\"ColPivHouseholderQR\"][id] = t_cpqr.best();\n results[\"CompleteOrthogonalDecomposition\"][id] = t_cod.best();\n results[\"FullPivHouseholderQR\"][id] = t_fpqr.best();\n results[\"JacobiSVD\"][id] = size<500 ? t_jsvd.best() : 0;\n results[\"BDCSVD\"][id] = t_bdcsvd.best();\n}\n\nint main()\n{\n const int small = 8;\n const int medium = 100;\n const int large = 1000;\n const int xl = 4000;\n \n bench<float,small>(0);\n bench<float,Dynamic>(1,medium);\n bench<float,Dynamic>(2,large);\n bench<float,Dynamic>(3,xl);\n \n IOFormat fmt(3, 0, \" \\t\", \"\\n\", \"\", \"\");\n \n std::cout << \"solver\/size \" << small << \"\\t\" << medium << \"\\t\" << large << \"\\t\" << xl << \"\\n\";\n std::cout << \"LLT (ms) \" << (results[\"LLT\"]\/1000.).format(fmt) << \"\\n\";\n std::cout << \"LDLT (%) \" << (results[\"LDLT\"]\/results[\"LLT\"]).format(fmt) << \"\\n\";\n std::cout << \"PartialPivLU (%) \" << (results[\"PartialPivLU\"]\/results[\"LLT\"]).format(fmt) << \"\\n\";\n std::cout << \"FullPivLU (%) \" << (results[\"FullPivLU\"]\/results[\"LLT\"]).format(fmt) << \"\\n\";\n std::cout << \"HouseholderQR (%) \" << (results[\"HouseholderQR\"]\/results[\"LLT\"]).format(fmt) << \"\\n\";\n std::cout << \"ColPivHouseholderQR (%) \" << (results[\"ColPivHouseholderQR\"]\/results[\"LLT\"]).format(fmt) << \"\\n\";\n std::cout << \"CompleteOrthogonalDecomposition (%) \" << (results[\"CompleteOrthogonalDecomposition\"]\/results[\"LLT\"]).format(fmt) << \"\\n\";\n std::cout << \"FullPivHouseholderQR (%) \" << (results[\"FullPivHouseholderQR\"]\/results[\"LLT\"]).format(fmt) << \"\\n\";\n std::cout << \"JacobiSVD (%) \" << (results[\"JacobiSVD\"]\/results[\"LLT\"]).format(fmt) << \"\\n\";\n std::cout << \"BDCSVD (%) \" << (results[\"BDCSVD\"]\/results[\"LLT\"]).format(fmt) << \"\\n\";\n}\n<|endoftext|>"} {"text":"<commit_before>#include <string.h>\n#include <linux\/input-event-codes.h>\n\nextern \"C\"\n{\n#include <wlr\/backend\/session.h>\n#include <wlr\/backend\/multi.h>\n}\n\n#include \"keyboard.hpp\"\n#include \"core.hpp\"\n#include \"input-manager.hpp\"\n\n\nvoid handle_keyboard_destroy_cb(wl_listener *listener, void*)\n{\n wf_keyboard::listeners *lss = wl_container_of(listener, lss, destroy);\n core->input->handle_input_destroyed(lss->keyboard->device);\n}\n\nstatic void handle_keyboard_key_cb(wl_listener* listener, void *data)\n{\n auto ev = static_cast<wlr_event_keyboard_key*> (data);\n wf_keyboard::listeners *lss = wl_container_of(listener, lss, key);\n\n auto seat = core->get_current_seat();\n wlr_seat_set_keyboard(seat, lss->keyboard->device);\n\n if (!core->input->handle_keyboard_key(ev->keycode, ev->state))\n {\n wlr_seat_keyboard_notify_key(core->input->seat, ev->time_msec,\n ev->keycode, ev->state);\n }\n\n wlr_idle_notify_activity(core->protocols.idle, seat);\n}\n\nstatic void handle_keyboard_mod_cb(wl_listener* listener, void* data)\n{\n auto kbd = static_cast<wlr_keyboard*> (data);\n wf_keyboard::listeners *lss = wl_container_of(listener, lss, modifier);\n\n auto seat = core->get_current_seat();\n wlr_seat_set_keyboard(seat, lss->keyboard->device);\n wlr_seat_keyboard_send_modifiers(core->input->seat, &kbd->modifiers);\n\n wlr_idle_notify_activity(core->protocols.idle, seat);\n}\n\nwf_keyboard::wf_keyboard(wlr_input_device *dev, wayfire_config *config)\n : handle(dev->keyboard), device(dev)\n{\n auto section = config->get_section(\"input\");\n\n model = section->get_option(\"xkb_model\", \"\");\n variant = section->get_option(\"xkb_variant\", \"\");\n layout = section->get_option(\"xkb_layout\", \"\");\n options = section->get_option(\"xkb_option\", \"\");\n rules = section->get_option(\"xkb_rule\", \"\");\n\n repeat_rate = section->get_option(\"kb_repeat_rate\", \"40\");\n repeat_delay = section->get_option(\"kb_repeat_delay\", \"400\");\n\n keyboard_options_updated = [=] () {\n reload_input_options();\n };\n\n model->add_updated_handler(&keyboard_options_updated);\n rules->add_updated_handler(&keyboard_options_updated);\n layout->add_updated_handler(&keyboard_options_updated);\n variant->add_updated_handler(&keyboard_options_updated);\n options->add_updated_handler(&keyboard_options_updated);\n repeat_rate->add_updated_handler(&keyboard_options_updated);\n repeat_delay->add_updated_handler(&keyboard_options_updated);\n\n lss.keyboard = this;\n lss.key.notify = handle_keyboard_key_cb;\n lss.modifier.notify = handle_keyboard_mod_cb;\n lss.destroy.notify = handle_keyboard_destroy_cb;\n\n wl_signal_add(&dev->keyboard->events.key, &lss.key);\n wl_signal_add(&dev->keyboard->events.modifiers, &lss.modifier);\n wl_signal_add(&dev->events.destroy, &lss.destroy);\n\n reload_input_options();\n wlr_seat_set_keyboard(core->get_current_seat(), dev);\n}\n\nvoid wf_keyboard::reload_input_options()\n{\n auto ctx = xkb_context_new(XKB_CONTEXT_NO_FLAGS);\n\n auto rules = this->rules->as_string();\n auto model = this->model->as_string();\n auto layout = this->layout->as_string();\n auto variant = this->variant->as_string();\n auto options = this->options->as_string();\n\n xkb_rule_names names;\n names.rules = rules.c_str();\n names.model = model.c_str();\n names.layout = layout.c_str();\n names.variant = variant.c_str();\n names.options = options.c_str();\n\n auto keymap = xkb_map_new_from_names(ctx, &names, XKB_KEYMAP_COMPILE_NO_FLAGS);\n\n wlr_keyboard_set_keymap(handle, keymap);\n\n xkb_keymap_unref(keymap);\n xkb_context_unref(ctx);\n\n wlr_keyboard_set_repeat_info(handle, repeat_rate->as_int(),\n repeat_delay->as_int());\n}\n\nwf_keyboard::~wf_keyboard()\n{\n model->rem_updated_handler(&keyboard_options_updated);\n rules->rem_updated_handler(&keyboard_options_updated);\n layout->rem_updated_handler(&keyboard_options_updated);\n variant->rem_updated_handler(&keyboard_options_updated);\n options->rem_updated_handler(&keyboard_options_updated);\n repeat_rate->rem_updated_handler(&keyboard_options_updated);\n repeat_delay->rem_updated_handler(&keyboard_options_updated);\n}\n\n\/* input manager things *\/\nstatic bool check_vt_switch(wlr_session *session, uint32_t key, uint32_t mods)\n{\n if (!session)\n return false;\n if (mods ^ (WLR_MODIFIER_ALT | WLR_MODIFIER_CTRL))\n return false;\n\n if (key < KEY_F1 || key > KEY_F10)\n return false;\n\n int target_vt = key - KEY_F1 + 1;\n wlr_session_change_vt(session, target_vt);\n return true;\n}\n\nstd::vector<std::function<void()>> input_manager::match_keys(uint32_t mod_state, uint32_t key)\n{\n std::vector<std::function<void()>> callbacks;\n\n for (auto& binding : bindings[WF_BINDING_KEY])\n {\n if (binding->value->as_cached_key().matches({mod_state, key}) &&\n binding->output == core->get_active_output())\n {\n \/* make sure we don't capture a reference to binding,\n * because it might get destroyed later *\/\n auto callback = binding->call.key;\n callbacks.push_back([key, callback] () {\n (*callback) (key);\n });\n }\n }\n\n for (auto& binding : bindings[WF_BINDING_ACTIVATOR])\n {\n if (binding->value->matches_key({mod_state, key}) &&\n binding->output == core->get_active_output())\n {\n callbacks.push_back(*binding->call.activator);\n }\n }\n\n return callbacks;\n}\n\nstatic uint32_t mod_from_key(uint32_t key)\n{\n if (key == KEY_LEFTALT || key == KEY_RIGHTALT)\n return WLR_MODIFIER_ALT;\n if (key == KEY_LEFTCTRL || key == KEY_RIGHTCTRL)\n return WLR_MODIFIER_CTRL;\n if (key == KEY_LEFTSHIFT || key == KEY_RIGHTSHIFT)\n return WLR_MODIFIER_SHIFT;\n if (key == KEY_LEFTMETA || key == KEY_RIGHTMETA)\n return WLR_MODIFIER_LOGO;\n\n return 0;\n}\n\nbool input_manager::handle_keyboard_key(uint32_t key, uint32_t state)\n{\n if (active_grab && active_grab->callbacks.keyboard.key)\n active_grab->callbacks.keyboard.key(key, state);\n\n auto mod = mod_from_key(key);\n if (mod)\n handle_keyboard_mod(mod, state);\n\n std::vector<std::function<void()>> callbacks;\n auto kbd = wlr_seat_get_keyboard(seat);\n\n if (state == WLR_KEY_PRESSED)\n {\n if (check_vt_switch(wlr_multi_get_session(core->backend), key, get_modifiers()))\n return true;\n\n \/* as long as we have pressed only modifiers, we should check for modifier bindings on release *\/\n if (mod)\n {\n bool modifiers_only = !count_other_inputs;\n for (size_t i = 0; i < kbd->num_keycodes; i++)\n if (!mod_from_key(kbd->keycodes[i]))\n modifiers_only = false;\n\n if (modifiers_only)\n in_mod_binding = true;\n else\n in_mod_binding = false;\n } else\n {\n in_mod_binding = false;\n }\n\n callbacks = match_keys(get_modifiers(), key);\n } else\n {\n if (in_mod_binding)\n callbacks = match_keys(get_modifiers() | mod, 0);\n\n in_mod_binding = false;\n }\n\n for (auto call : callbacks)\n call();\n\n return active_grab || !callbacks.empty();\n}\n\nvoid input_manager::handle_keyboard_mod(uint32_t modifier, uint32_t state)\n{\n if (active_grab && active_grab->callbacks.keyboard.mod)\n active_grab->callbacks.keyboard.mod(modifier, state);\n}\n\n<commit_msg>s\/wlr_multi_get_session\/wlr_backend_get_session\/<commit_after>#include <string.h>\n#include <linux\/input-event-codes.h>\n\nextern \"C\"\n{\n#include <wlr\/backend\/session.h>\n#include <wlr\/backend\/multi.h>\n}\n\n#include \"keyboard.hpp\"\n#include \"core.hpp\"\n#include \"input-manager.hpp\"\n\n\nvoid handle_keyboard_destroy_cb(wl_listener *listener, void*)\n{\n wf_keyboard::listeners *lss = wl_container_of(listener, lss, destroy);\n core->input->handle_input_destroyed(lss->keyboard->device);\n}\n\nstatic void handle_keyboard_key_cb(wl_listener* listener, void *data)\n{\n auto ev = static_cast<wlr_event_keyboard_key*> (data);\n wf_keyboard::listeners *lss = wl_container_of(listener, lss, key);\n\n auto seat = core->get_current_seat();\n wlr_seat_set_keyboard(seat, lss->keyboard->device);\n\n if (!core->input->handle_keyboard_key(ev->keycode, ev->state))\n {\n wlr_seat_keyboard_notify_key(core->input->seat, ev->time_msec,\n ev->keycode, ev->state);\n }\n\n wlr_idle_notify_activity(core->protocols.idle, seat);\n}\n\nstatic void handle_keyboard_mod_cb(wl_listener* listener, void* data)\n{\n auto kbd = static_cast<wlr_keyboard*> (data);\n wf_keyboard::listeners *lss = wl_container_of(listener, lss, modifier);\n\n auto seat = core->get_current_seat();\n wlr_seat_set_keyboard(seat, lss->keyboard->device);\n wlr_seat_keyboard_send_modifiers(core->input->seat, &kbd->modifiers);\n\n wlr_idle_notify_activity(core->protocols.idle, seat);\n}\n\nwf_keyboard::wf_keyboard(wlr_input_device *dev, wayfire_config *config)\n : handle(dev->keyboard), device(dev)\n{\n auto section = config->get_section(\"input\");\n\n model = section->get_option(\"xkb_model\", \"\");\n variant = section->get_option(\"xkb_variant\", \"\");\n layout = section->get_option(\"xkb_layout\", \"\");\n options = section->get_option(\"xkb_option\", \"\");\n rules = section->get_option(\"xkb_rule\", \"\");\n\n repeat_rate = section->get_option(\"kb_repeat_rate\", \"40\");\n repeat_delay = section->get_option(\"kb_repeat_delay\", \"400\");\n\n keyboard_options_updated = [=] () {\n reload_input_options();\n };\n\n model->add_updated_handler(&keyboard_options_updated);\n rules->add_updated_handler(&keyboard_options_updated);\n layout->add_updated_handler(&keyboard_options_updated);\n variant->add_updated_handler(&keyboard_options_updated);\n options->add_updated_handler(&keyboard_options_updated);\n repeat_rate->add_updated_handler(&keyboard_options_updated);\n repeat_delay->add_updated_handler(&keyboard_options_updated);\n\n lss.keyboard = this;\n lss.key.notify = handle_keyboard_key_cb;\n lss.modifier.notify = handle_keyboard_mod_cb;\n lss.destroy.notify = handle_keyboard_destroy_cb;\n\n wl_signal_add(&dev->keyboard->events.key, &lss.key);\n wl_signal_add(&dev->keyboard->events.modifiers, &lss.modifier);\n wl_signal_add(&dev->events.destroy, &lss.destroy);\n\n reload_input_options();\n wlr_seat_set_keyboard(core->get_current_seat(), dev);\n}\n\nvoid wf_keyboard::reload_input_options()\n{\n auto ctx = xkb_context_new(XKB_CONTEXT_NO_FLAGS);\n\n auto rules = this->rules->as_string();\n auto model = this->model->as_string();\n auto layout = this->layout->as_string();\n auto variant = this->variant->as_string();\n auto options = this->options->as_string();\n\n xkb_rule_names names;\n names.rules = rules.c_str();\n names.model = model.c_str();\n names.layout = layout.c_str();\n names.variant = variant.c_str();\n names.options = options.c_str();\n\n auto keymap = xkb_map_new_from_names(ctx, &names, XKB_KEYMAP_COMPILE_NO_FLAGS);\n\n wlr_keyboard_set_keymap(handle, keymap);\n\n xkb_keymap_unref(keymap);\n xkb_context_unref(ctx);\n\n wlr_keyboard_set_repeat_info(handle, repeat_rate->as_int(),\n repeat_delay->as_int());\n}\n\nwf_keyboard::~wf_keyboard()\n{\n model->rem_updated_handler(&keyboard_options_updated);\n rules->rem_updated_handler(&keyboard_options_updated);\n layout->rem_updated_handler(&keyboard_options_updated);\n variant->rem_updated_handler(&keyboard_options_updated);\n options->rem_updated_handler(&keyboard_options_updated);\n repeat_rate->rem_updated_handler(&keyboard_options_updated);\n repeat_delay->rem_updated_handler(&keyboard_options_updated);\n}\n\n\/* input manager things *\/\nstatic bool check_vt_switch(wlr_session *session, uint32_t key, uint32_t mods)\n{\n if (!session)\n return false;\n if (mods ^ (WLR_MODIFIER_ALT | WLR_MODIFIER_CTRL))\n return false;\n\n if (key < KEY_F1 || key > KEY_F10)\n return false;\n\n int target_vt = key - KEY_F1 + 1;\n wlr_session_change_vt(session, target_vt);\n return true;\n}\n\nstd::vector<std::function<void()>> input_manager::match_keys(uint32_t mod_state, uint32_t key)\n{\n std::vector<std::function<void()>> callbacks;\n\n for (auto& binding : bindings[WF_BINDING_KEY])\n {\n if (binding->value->as_cached_key().matches({mod_state, key}) &&\n binding->output == core->get_active_output())\n {\n \/* make sure we don't capture a reference to binding,\n * because it might get destroyed later *\/\n auto callback = binding->call.key;\n callbacks.push_back([key, callback] () {\n (*callback) (key);\n });\n }\n }\n\n for (auto& binding : bindings[WF_BINDING_ACTIVATOR])\n {\n if (binding->value->matches_key({mod_state, key}) &&\n binding->output == core->get_active_output())\n {\n callbacks.push_back(*binding->call.activator);\n }\n }\n\n return callbacks;\n}\n\nstatic uint32_t mod_from_key(uint32_t key)\n{\n if (key == KEY_LEFTALT || key == KEY_RIGHTALT)\n return WLR_MODIFIER_ALT;\n if (key == KEY_LEFTCTRL || key == KEY_RIGHTCTRL)\n return WLR_MODIFIER_CTRL;\n if (key == KEY_LEFTSHIFT || key == KEY_RIGHTSHIFT)\n return WLR_MODIFIER_SHIFT;\n if (key == KEY_LEFTMETA || key == KEY_RIGHTMETA)\n return WLR_MODIFIER_LOGO;\n\n return 0;\n}\n\nbool input_manager::handle_keyboard_key(uint32_t key, uint32_t state)\n{\n if (active_grab && active_grab->callbacks.keyboard.key)\n active_grab->callbacks.keyboard.key(key, state);\n\n auto mod = mod_from_key(key);\n if (mod)\n handle_keyboard_mod(mod, state);\n\n std::vector<std::function<void()>> callbacks;\n auto kbd = wlr_seat_get_keyboard(seat);\n\n if (state == WLR_KEY_PRESSED)\n {\n if (check_vt_switch(wlr_backend_get_session(core->backend), key, get_modifiers()))\n return true;\n\n \/* as long as we have pressed only modifiers, we should check for modifier bindings on release *\/\n if (mod)\n {\n bool modifiers_only = !count_other_inputs;\n for (size_t i = 0; i < kbd->num_keycodes; i++)\n if (!mod_from_key(kbd->keycodes[i]))\n modifiers_only = false;\n\n if (modifiers_only)\n in_mod_binding = true;\n else\n in_mod_binding = false;\n } else\n {\n in_mod_binding = false;\n }\n\n callbacks = match_keys(get_modifiers(), key);\n } else\n {\n if (in_mod_binding)\n callbacks = match_keys(get_modifiers() | mod, 0);\n\n in_mod_binding = false;\n }\n\n for (auto call : callbacks)\n call();\n\n return active_grab || !callbacks.empty();\n}\n\nvoid input_manager::handle_keyboard_mod(uint32_t modifier, uint32_t state)\n{\n if (active_grab && active_grab->callbacks.keyboard.mod)\n active_grab->callbacks.keyboard.mod(modifier, state);\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 2018, Arm Limited and affiliates.\n * SPDX-License-Identifier: Apache-2.0\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n#include \"UBLOX_AT_CellularContext.h\"\n#include \"UBLOX_AT_CellularStack.h\"\n#include \"APN_db.h\"\n\nnamespace mbed {\n\nUBLOX_AT_CellularContext::UBLOX_AT_CellularContext(ATHandler &at, CellularDevice *device, const char *apn) :\n AT_CellularContext(at, device, apn)\n{\n \/\/ The authentication to use\n _auth = NSAPI_SECURITY_UNKNOWN;\n}\n\nUBLOX_AT_CellularContext::~UBLOX_AT_CellularContext()\n{\n}\n\nNetworkStack *UBLOX_AT_CellularContext::get_stack()\n{\n if (!_stack) {\n _stack = new UBLOX_AT_CellularStack(_at, _cid, _ip_stack_type);\n }\n return _stack;\n}\n\nbool UBLOX_AT_CellularContext::stack_type_supported(nsapi_ip_stack_t stack_type)\n{\n return stack_type == IPV4_STACK ? true : false;\n}\n\nvoid UBLOX_AT_CellularContext::do_connect()\n{\n _at.lock();\n _cb_data.error = NSAPI_ERROR_NO_CONNECTION;\n\n \/\/ Attempt to establish a connection\n#ifdef TARGET_UBLOX_C030_R410M\n _cb_data.error = NSAPI_ERROR_OK;\n#else\n _cb_data.error = open_data_channel();\n#endif\n if (_cb_data.error != NSAPI_ERROR_OK) {\n \/\/ If new PSD context was created and failed to activate, delete it\n if (_new_context_set) {\n disconnect_modem_stack();\n }\n _connect_status = NSAPI_STATUS_DISCONNECTED;\n } else {\n _connect_status = NSAPI_STATUS_GLOBAL_UP;\n }\n _at.unlock();\n\n if (_status_cb) {\n call_network_cb(_connect_status);\n }\n}\n\nnsapi_error_t UBLOX_AT_CellularContext::open_data_channel()\n{\n bool success = false;\n int active = 0;\n char *config = NULL;\n nsapi_error_t err = NSAPI_ERROR_NO_CONNECTION;\n char imsi[MAX_IMSI_LENGTH + 1];\n\n \/\/ do check for stack to validate that we have support for stack\n _stack = get_stack();\n if (!_stack) {\n return err;\n }\n\n _at.cmd_start(\"AT+UPSND=\" PROFILE \",8\");\n _at.cmd_stop();\n _at.resp_start(\"+UPSND:\");\n _at.read_int();\n _at.read_int();\n active = _at.read_int();\n _at.resp_stop();\n\n if (active == 0) {\n \/\/ If the caller hasn't entered an APN, try to find it\n if (_apn == NULL) {\n err = get_imsi(imsi);\n if (err == NSAPI_ERROR_OK) {\n config = (char *)apnconfig(imsi);\n }\n }\n\n \/\/ Attempt to connect\n do {\n get_next_credentials(&config);\n if (_uname && _pwd) {\n _auth = (*_uname && *_pwd) ? _auth : NSAPI_SECURITY_NONE;\n } else {\n _auth = NSAPI_SECURITY_NONE;\n }\n success = activate_profile(_apn, _uname, _pwd);\n } while (!success && config && *config);\n } else {\n \/\/ If the profile is already active, we're good\n success = true;\n }\n\n err = (_at.get_last_error() == NSAPI_ERROR_OK) ? NSAPI_ERROR_OK : NSAPI_ERROR_NO_CONNECTION;\n\n return err;\n}\n\nbool UBLOX_AT_CellularContext::activate_profile(const char *apn,\n const char *username,\n const char *password)\n{\n bool activated = false;\n bool success = false;\n\n \/\/ Set up the APN\n if (apn) {\n success = false;\n _at.cmd_start(\"AT+UPSD=0,1,\");\n _at.write_string(apn);\n _at.cmd_stop();\n _at.resp_start();\n _at.resp_stop();\n\n if (_at.get_last_error() == NSAPI_ERROR_OK) {\n success = true;\n }\n }\n \/\/ Set up the UserName\n if (success && username) {\n success = false;\n _at.cmd_start(\"AT+UPSD=\" PROFILE \",2,\");\n _at.write_string(username);\n _at.cmd_stop();\n _at.resp_start();\n _at.resp_stop();\n\n if (_at.get_last_error() == NSAPI_ERROR_OK) {\n success = true;\n }\n }\n \/\/ Set up the Password\n if (success && password) {\n success = false;\n _at.cmd_start(\"AT+UPSD=\" PROFILE \",3,\");\n _at.write_string(password);\n _at.cmd_stop();\n _at.resp_start();\n _at.resp_stop();\n\n if (_at.get_last_error() == NSAPI_ERROR_OK) {\n success = true;\n }\n }\n\n if (success) {\n _at.cmd_start(\"AT+UPSD=\" PROFILE \",7,\\\"0.0.0.0\\\"\");\n _at.cmd_stop();\n _at.resp_start();\n _at.resp_stop();\n\n \/\/ Set up the authentication protocol\n \/\/ 0 = none\n \/\/ 1 = PAP (Password Authentication Protocol)\n \/\/ 2 = CHAP (Challenge Handshake Authentication Protocol)\n for (int protocol = nsapi_security_to_modem_security(NSAPI_SECURITY_NONE);\n success && (protocol <= nsapi_security_to_modem_security(NSAPI_SECURITY_CHAP)); protocol++) {\n if ((_auth == NSAPI_SECURITY_UNKNOWN) || (nsapi_security_to_modem_security(_auth) == protocol)) {\n _at.cmd_start(\"AT+UPSD=0,6,\");\n _at.write_int(protocol);\n _at.cmd_stop();\n _at.resp_start();\n _at.resp_stop();\n\n if (_at.get_last_error() == NSAPI_ERROR_OK) {\n \/\/ Activate, wait upto 30 seconds for the connection to be made\n _at.set_at_timeout(30000);\n _at.cmd_start(\"AT+UPSDA=0,3\");\n _at.cmd_stop();\n _at.resp_start();\n _at.resp_stop();\n _at.restore_at_timeout();\n\n if (_at.get_last_error() == NSAPI_ERROR_OK) {\n activated = true;\n }\n }\n }\n }\n }\n\n return activated;\n}\n\n\/\/ Convert nsapi_security_t to the modem security numbers\nint UBLOX_AT_CellularContext::nsapi_security_to_modem_security(nsapi_security_t nsapi_security)\n{\n int modem_security = 3;\n\n switch (nsapi_security) {\n case NSAPI_SECURITY_NONE:\n modem_security = 0;\n break;\n case NSAPI_SECURITY_PAP:\n modem_security = 1;\n break;\n case NSAPI_SECURITY_CHAP:\n modem_security = 2;\n break;\n case NSAPI_SECURITY_UNKNOWN:\n modem_security = 3;\n break;\n default:\n modem_security = 3;\n break;\n }\n\n return modem_security;\n}\n\n\/\/ Disconnect the on board IP stack of the modem.\nbool UBLOX_AT_CellularContext::disconnect_modem_stack()\n{\n bool success = false;\n\n if (get_ip_address() != NULL) {\n _at.cmd_start(\"AT+UPSDA=\" PROFILE \",4\");\n _at.cmd_stop();\n _at.resp_start();\n _at.resp_stop();\n\n if (_at.get_last_error() == NSAPI_ERROR_OK) {\n success = true;\n }\n }\n\n return success;\n}\n\nnsapi_error_t UBLOX_AT_CellularContext::get_imsi(char *imsi)\n{\n _at.lock();\n _at.cmd_start(\"AT+CIMI\");\n _at.cmd_stop();\n _at.resp_start();\n int len = _at.read_string(imsi, MAX_IMSI_LENGTH);\n if (len > 0) {\n imsi[len] = '\\0';\n }\n _at.resp_stop();\n\n return _at.unlock_return_error();\n}\n\n\/\/ Get the next set of credentials, based on IMSI.\nvoid UBLOX_AT_CellularContext::get_next_credentials(char **config)\n{\n if (*config) {\n _apn = _APN_GET(*config);\n _uname = _APN_GET(*config);\n _pwd = _APN_GET(*config);\n }\n}\n\nconst char *UBLOX_AT_CellularContext::get_gateway()\n{\n return get_ip_address();\n}\n\n} \/* namespace mbed *\/\n<commit_msg>Call network status callback from UBLOX AT<commit_after>\/*\n * Copyright (c) 2018, Arm Limited and affiliates.\n * SPDX-License-Identifier: Apache-2.0\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n#include \"UBLOX_AT_CellularContext.h\"\n#include \"UBLOX_AT_CellularStack.h\"\n#include \"APN_db.h\"\n\nnamespace mbed {\n\nUBLOX_AT_CellularContext::UBLOX_AT_CellularContext(ATHandler &at, CellularDevice *device, const char *apn) :\n AT_CellularContext(at, device, apn)\n{\n \/\/ The authentication to use\n _auth = NSAPI_SECURITY_UNKNOWN;\n}\n\nUBLOX_AT_CellularContext::~UBLOX_AT_CellularContext()\n{\n}\n\nNetworkStack *UBLOX_AT_CellularContext::get_stack()\n{\n if (!_stack) {\n _stack = new UBLOX_AT_CellularStack(_at, _cid, _ip_stack_type);\n }\n return _stack;\n}\n\nbool UBLOX_AT_CellularContext::stack_type_supported(nsapi_ip_stack_t stack_type)\n{\n return stack_type == IPV4_STACK ? true : false;\n}\n\nvoid UBLOX_AT_CellularContext::do_connect()\n{\n _at.lock();\n _cb_data.error = NSAPI_ERROR_NO_CONNECTION;\n\n \/\/ Attempt to establish a connection\n#ifdef TARGET_UBLOX_C030_R410M\n _cb_data.error = NSAPI_ERROR_OK;\n#else\n _cb_data.error = open_data_channel();\n#endif\n if (_cb_data.error != NSAPI_ERROR_OK) {\n \/\/ If new PSD context was created and failed to activate, delete it\n if (_new_context_set) {\n disconnect_modem_stack();\n }\n _connect_status = NSAPI_STATUS_DISCONNECTED;\n } else {\n _connect_status = NSAPI_STATUS_GLOBAL_UP;\n }\n _at.unlock();\n\n if (_status_cb) {\n _status_cb(NSAPI_EVENT_CONNECTION_STATUS_CHANGE, _connect_status);\n }\n}\n\nnsapi_error_t UBLOX_AT_CellularContext::open_data_channel()\n{\n bool success = false;\n int active = 0;\n char *config = NULL;\n nsapi_error_t err = NSAPI_ERROR_NO_CONNECTION;\n char imsi[MAX_IMSI_LENGTH + 1];\n\n \/\/ do check for stack to validate that we have support for stack\n _stack = get_stack();\n if (!_stack) {\n return err;\n }\n\n _at.cmd_start(\"AT+UPSND=\" PROFILE \",8\");\n _at.cmd_stop();\n _at.resp_start(\"+UPSND:\");\n _at.read_int();\n _at.read_int();\n active = _at.read_int();\n _at.resp_stop();\n\n if (active == 0) {\n \/\/ If the caller hasn't entered an APN, try to find it\n if (_apn == NULL) {\n err = get_imsi(imsi);\n if (err == NSAPI_ERROR_OK) {\n config = (char *)apnconfig(imsi);\n }\n }\n\n \/\/ Attempt to connect\n do {\n get_next_credentials(&config);\n if (_uname && _pwd) {\n _auth = (*_uname && *_pwd) ? _auth : NSAPI_SECURITY_NONE;\n } else {\n _auth = NSAPI_SECURITY_NONE;\n }\n success = activate_profile(_apn, _uname, _pwd);\n } while (!success && config && *config);\n } else {\n \/\/ If the profile is already active, we're good\n success = true;\n }\n\n err = (_at.get_last_error() == NSAPI_ERROR_OK) ? NSAPI_ERROR_OK : NSAPI_ERROR_NO_CONNECTION;\n\n return err;\n}\n\nbool UBLOX_AT_CellularContext::activate_profile(const char *apn,\n const char *username,\n const char *password)\n{\n bool activated = false;\n bool success = false;\n\n \/\/ Set up the APN\n if (apn) {\n success = false;\n _at.cmd_start(\"AT+UPSD=0,1,\");\n _at.write_string(apn);\n _at.cmd_stop();\n _at.resp_start();\n _at.resp_stop();\n\n if (_at.get_last_error() == NSAPI_ERROR_OK) {\n success = true;\n }\n }\n \/\/ Set up the UserName\n if (success && username) {\n success = false;\n _at.cmd_start(\"AT+UPSD=\" PROFILE \",2,\");\n _at.write_string(username);\n _at.cmd_stop();\n _at.resp_start();\n _at.resp_stop();\n\n if (_at.get_last_error() == NSAPI_ERROR_OK) {\n success = true;\n }\n }\n \/\/ Set up the Password\n if (success && password) {\n success = false;\n _at.cmd_start(\"AT+UPSD=\" PROFILE \",3,\");\n _at.write_string(password);\n _at.cmd_stop();\n _at.resp_start();\n _at.resp_stop();\n\n if (_at.get_last_error() == NSAPI_ERROR_OK) {\n success = true;\n }\n }\n\n if (success) {\n _at.cmd_start(\"AT+UPSD=\" PROFILE \",7,\\\"0.0.0.0\\\"\");\n _at.cmd_stop();\n _at.resp_start();\n _at.resp_stop();\n\n \/\/ Set up the authentication protocol\n \/\/ 0 = none\n \/\/ 1 = PAP (Password Authentication Protocol)\n \/\/ 2 = CHAP (Challenge Handshake Authentication Protocol)\n for (int protocol = nsapi_security_to_modem_security(NSAPI_SECURITY_NONE);\n success && (protocol <= nsapi_security_to_modem_security(NSAPI_SECURITY_CHAP)); protocol++) {\n if ((_auth == NSAPI_SECURITY_UNKNOWN) || (nsapi_security_to_modem_security(_auth) == protocol)) {\n _at.cmd_start(\"AT+UPSD=0,6,\");\n _at.write_int(protocol);\n _at.cmd_stop();\n _at.resp_start();\n _at.resp_stop();\n\n if (_at.get_last_error() == NSAPI_ERROR_OK) {\n \/\/ Activate, wait upto 30 seconds for the connection to be made\n _at.set_at_timeout(30000);\n _at.cmd_start(\"AT+UPSDA=0,3\");\n _at.cmd_stop();\n _at.resp_start();\n _at.resp_stop();\n _at.restore_at_timeout();\n\n if (_at.get_last_error() == NSAPI_ERROR_OK) {\n activated = true;\n }\n }\n }\n }\n }\n\n return activated;\n}\n\n\/\/ Convert nsapi_security_t to the modem security numbers\nint UBLOX_AT_CellularContext::nsapi_security_to_modem_security(nsapi_security_t nsapi_security)\n{\n int modem_security = 3;\n\n switch (nsapi_security) {\n case NSAPI_SECURITY_NONE:\n modem_security = 0;\n break;\n case NSAPI_SECURITY_PAP:\n modem_security = 1;\n break;\n case NSAPI_SECURITY_CHAP:\n modem_security = 2;\n break;\n case NSAPI_SECURITY_UNKNOWN:\n modem_security = 3;\n break;\n default:\n modem_security = 3;\n break;\n }\n\n return modem_security;\n}\n\n\/\/ Disconnect the on board IP stack of the modem.\nbool UBLOX_AT_CellularContext::disconnect_modem_stack()\n{\n bool success = false;\n\n if (get_ip_address() != NULL) {\n _at.cmd_start(\"AT+UPSDA=\" PROFILE \",4\");\n _at.cmd_stop();\n _at.resp_start();\n _at.resp_stop();\n\n if (_at.get_last_error() == NSAPI_ERROR_OK) {\n success = true;\n }\n }\n\n return success;\n}\n\nnsapi_error_t UBLOX_AT_CellularContext::get_imsi(char *imsi)\n{\n _at.lock();\n _at.cmd_start(\"AT+CIMI\");\n _at.cmd_stop();\n _at.resp_start();\n int len = _at.read_string(imsi, MAX_IMSI_LENGTH);\n if (len > 0) {\n imsi[len] = '\\0';\n }\n _at.resp_stop();\n\n return _at.unlock_return_error();\n}\n\n\/\/ Get the next set of credentials, based on IMSI.\nvoid UBLOX_AT_CellularContext::get_next_credentials(char **config)\n{\n if (*config) {\n _apn = _APN_GET(*config);\n _uname = _APN_GET(*config);\n _pwd = _APN_GET(*config);\n }\n}\n\nconst char *UBLOX_AT_CellularContext::get_gateway()\n{\n return get_ip_address();\n}\n\n} \/* namespace mbed *\/\n<|endoftext|>"} {"text":"<commit_before>\/*\n * This helper library glues delegate_glue and http_response_handler\n * together.\n *\n * author: Max Kellermann <mk@cm4all.com>\n *\/\n\n#include \"HttpRequest.hxx\"\n#include \"Handler.hxx\"\n#include \"Glue.hxx\"\n#include \"static_headers.hxx\"\n#include \"http_response.hxx\"\n#include \"strmap.hxx\"\n#include \"istream\/istream.hxx\"\n#include \"istream\/istream_file.hxx\"\n#include \"gerrno.h\"\n#include \"pool.hxx\"\n\n#include <sys\/types.h>\n#include <sys\/stat.h>\n#include <unistd.h>\n#include <errno.h>\n\nstruct DelegateHttpRequest final : DelegateHandler {\n struct pool &pool;\n const char *const path;\n const char *const content_type;\n struct http_response_handler_ref handler;\n\n DelegateHttpRequest(struct pool &_pool,\n const char *_path, const char *_content_type,\n const struct http_response_handler &_handler, void *ctx)\n :pool(_pool),\n path(_path), content_type(_content_type),\n handler(_handler, ctx) {}\n\n \/* virtual methods from class DelegateHandler *\/\n void OnDelegateSuccess(int fd) override;\n\n void OnDelegateError(GError *error) override {\n handler.InvokeAbort(error);\n }\n};\n\nvoid\nDelegateHttpRequest::OnDelegateSuccess(int fd)\n{\n struct stat st;\n if (fstat(fd, &st) < 0) {\n GError *error = new_error_errno();\n g_prefix_error(&error, \"Failed to stat %s: \", path);\n handler.InvokeAbort(error);\n return;\n }\n\n if (!S_ISREG(st.st_mode)) {\n close(fd);\n handler.InvokeMessage(pool, HTTP_STATUS_NOT_FOUND,\n \"Not a regular file\");\n return;\n }\n\n \/* XXX handle if-modified-since, ... *\/\n\n struct strmap *headers = strmap_new(&pool);\n static_response_headers(&pool, headers, fd, &st, content_type);\n\n Istream *body = istream_file_fd_new(&pool, path,\n fd, FdType::FD_FILE,\n st.st_size);\n handler.InvokeResponse(HTTP_STATUS_OK, headers, body);\n}\n\nvoid\ndelegate_stock_request(StockMap *stock, struct pool *pool,\n const char *helper,\n const ChildOptions &options,\n const char *path, const char *content_type,\n const struct http_response_handler *handler, void *ctx,\n struct async_operation_ref &async_ref)\n{\n auto get = NewFromPool<DelegateHttpRequest>(*pool, *pool,\n path, content_type,\n *handler, ctx);\n\n delegate_stock_open(stock, pool,\n helper, options, path,\n *get, async_ref);\n}\n<commit_msg>delegate\/HttpRequest: move code to method Open()<commit_after>\/*\n * This helper library glues delegate_glue and http_response_handler\n * together.\n *\n * author: Max Kellermann <mk@cm4all.com>\n *\/\n\n#include \"HttpRequest.hxx\"\n#include \"Handler.hxx\"\n#include \"Glue.hxx\"\n#include \"static_headers.hxx\"\n#include \"http_response.hxx\"\n#include \"strmap.hxx\"\n#include \"istream\/istream.hxx\"\n#include \"istream\/istream_file.hxx\"\n#include \"gerrno.h\"\n#include \"pool.hxx\"\n\n#include <sys\/types.h>\n#include <sys\/stat.h>\n#include <unistd.h>\n#include <errno.h>\n\nstruct DelegateHttpRequest final : DelegateHandler {\n struct pool &pool;\n const char *const path;\n const char *const content_type;\n struct http_response_handler_ref handler;\n\n DelegateHttpRequest(struct pool &_pool,\n const char *_path, const char *_content_type,\n const struct http_response_handler &_handler, void *ctx)\n :pool(_pool),\n path(_path), content_type(_content_type),\n handler(_handler, ctx) {}\n\n void Open(StockMap &stock, const char *helper,\n const ChildOptions &options,\n struct async_operation_ref &async_ref) {\n delegate_stock_open(&stock, &pool,\n helper, options, path,\n *this, async_ref);\n }\n\n \/* virtual methods from class DelegateHandler *\/\n void OnDelegateSuccess(int fd) override;\n\n void OnDelegateError(GError *error) override {\n handler.InvokeAbort(error);\n }\n};\n\nvoid\nDelegateHttpRequest::OnDelegateSuccess(int fd)\n{\n struct stat st;\n if (fstat(fd, &st) < 0) {\n GError *error = new_error_errno();\n g_prefix_error(&error, \"Failed to stat %s: \", path);\n handler.InvokeAbort(error);\n return;\n }\n\n if (!S_ISREG(st.st_mode)) {\n close(fd);\n handler.InvokeMessage(pool, HTTP_STATUS_NOT_FOUND,\n \"Not a regular file\");\n return;\n }\n\n \/* XXX handle if-modified-since, ... *\/\n\n struct strmap *headers = strmap_new(&pool);\n static_response_headers(&pool, headers, fd, &st, content_type);\n\n Istream *body = istream_file_fd_new(&pool, path,\n fd, FdType::FD_FILE,\n st.st_size);\n handler.InvokeResponse(HTTP_STATUS_OK, headers, body);\n}\n\nvoid\ndelegate_stock_request(StockMap *stock, struct pool *pool,\n const char *helper,\n const ChildOptions &options,\n const char *path, const char *content_type,\n const struct http_response_handler *handler, void *ctx,\n struct async_operation_ref &async_ref)\n{\n auto get = NewFromPool<DelegateHttpRequest>(*pool, *pool,\n path, content_type,\n *handler, ctx);\n get->Open(*stock, helper, options, async_ref);\n}\n<|endoftext|>"} {"text":"<commit_before>\/* IBM_PROLOG_BEGIN_TAG *\/\n\/* This is an automatically generated prolog. *\/\n\/* *\/\n\/* $Source: src\/import\/hwpf\/fapi2\/include\/target_types.H $ *\/\n\/* *\/\n\/* OpenPOWER HostBoot Project *\/\n\/* *\/\n\/* Contributors Listed Below - COPYRIGHT 2012,2019 *\/\n\/* [+] International Business Machines Corp. *\/\n\/* *\/\n\/* *\/\n\/* Licensed under the Apache License, Version 2.0 (the \"License\"); *\/\n\/* you may not use this file except in compliance with the License. *\/\n\/* You may obtain a copy of the License at *\/\n\/* *\/\n\/* http:\/\/www.apache.org\/licenses\/LICENSE-2.0 *\/\n\/* *\/\n\/* Unless required by applicable law or agreed to in writing, software *\/\n\/* distributed under the License is distributed on an \"AS IS\" BASIS, *\/\n\/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or *\/\n\/* implied. See the License for the specific language governing *\/\n\/* permissions and limitations under the License. *\/\n\/* *\/\n\/* IBM_PROLOG_END_TAG *\/\n\/**\n * @file target_types.H\n * @brief definitions for fapi2 target types\n *\/\n\n#ifndef __FAPI2_TARGET_TYPES__\n#define __FAPI2_TARGET_TYPES__\n#include <stdint.h>\n\/\/\/ FAPI namespace\nnamespace fapi2\n{\n\/\/\/\n\/\/\/ @enum fapi::TargetType\n\/\/\/ @brief Types, kinds, of targets\n\/\/\/ @note TYPE_NONE is used to represent empty\/NULL targets in lists\n\/\/\/ or tables. TYPE_ALL is used to pass targets to methods which\n\/\/\/ can act generally on any type of target\n\/\/\/\n\n\/\/\/ Target Kind\nenum TargetType\n{\n TARGET_TYPE_NONE = 0x00000000, \/\/\/< No type\n TARGET_TYPE_SYSTEM = 0x00000001, \/\/\/< System type\n TARGET_TYPE_DIMM = 0x00000002, \/\/\/< DIMM type\n TARGET_TYPE_PROC_CHIP = 0x00000004, \/\/\/< Processor type\n TARGET_TYPE_MEMBUF_CHIP = 0x00000008, \/\/\/< Membuf type\n TARGET_TYPE_EX = 0x00000010, \/\/\/< EX - 2x Core, L2, L3 - can be deconfigured\n TARGET_TYPE_MBA = 0x00000020, \/\/\/< MBA type\n TARGET_TYPE_MCS = 0x00000040, \/\/\/< MCS type\n TARGET_TYPE_XBUS = 0x00000080, \/\/\/< XBUS type\n TARGET_TYPE_ABUS = 0x00000100, \/\/\/< ABUS type\n TARGET_TYPE_L4 = 0x00000200, \/\/\/< L4 type\n TARGET_TYPE_CORE = 0x00000400, \/\/\/< Core - 4x threads(?) - can be deconfigured\n TARGET_TYPE_EQ = 0x00000800, \/\/\/< EQ - 4x core, 2x L2, 2x L3 - can be deconfigured\n TARGET_TYPE_MCA = 0x00001000, \/\/\/< MCA type\n TARGET_TYPE_MCBIST = 0x00002000, \/\/\/< MCBIST type\n TARGET_TYPE_MI = 0x00004000, \/\/\/< MI Memory Interface (Cumulus)\n TARGET_TYPE_CAPP = 0x00008000, \/\/\/< CAPP target\n TARGET_TYPE_DMI = 0x00010000, \/\/\/< DMI type\n TARGET_TYPE_OBUS = 0x00020000, \/\/\/< OBUS type\n TARGET_TYPE_NV = 0x00040000, \/\/\/< NV bus type\n TARGET_TYPE_SBE = 0x00080000, \/\/\/< SBE type\n TARGET_TYPE_PPE = 0x00100000, \/\/\/< PPE type\n TARGET_TYPE_PERV = 0x00200000, \/\/\/< Pervasive type\n TARGET_TYPE_PEC = 0x00400000, \/\/\/< PEC type\n TARGET_TYPE_PHB = 0x00800000, \/\/\/< PHB type\n\n TARGET_TYPE_ALL = 0xFFFFFFFF, \/\/\/< Any\/All types\n\n \/\/ Compound target types\n TARGET_TYPE_CHIPS = TARGET_TYPE_PROC_CHIP |\n TARGET_TYPE_MEMBUF_CHIP,\n\n TARGET_TYPE_CHIPLETS = TARGET_TYPE_EX |\n TARGET_TYPE_MBA |\n TARGET_TYPE_MCS |\n TARGET_TYPE_XBUS |\n TARGET_TYPE_ABUS |\n TARGET_TYPE_L4 |\n TARGET_TYPE_CORE |\n TARGET_TYPE_EQ |\n TARGET_TYPE_MCA |\n TARGET_TYPE_MCBIST |\n TARGET_TYPE_MI |\n TARGET_TYPE_DMI |\n TARGET_TYPE_OBUS |\n TARGET_TYPE_NV |\n TARGET_TYPE_SBE |\n TARGET_TYPE_PPE |\n TARGET_TYPE_PERV |\n TARGET_TYPE_PEC |\n TARGET_TYPE_PHB,\n\n \/\/ Mappings to target types found in the error xml files\n TARGET_TYPE_EX_CHIPLET = TARGET_TYPE_EX,\n TARGET_TYPE_MBA_CHIPLET = TARGET_TYPE_MBA,\n TARGET_TYPE_MCS_CHIPLET = TARGET_TYPE_MCS,\n TARGET_TYPE_XBUS_ENDPOINT = TARGET_TYPE_XBUS,\n TARGET_TYPE_ABUS_ENDPOINT = TARGET_TYPE_ABUS,\n};\n\n\/\/\/\n\/\/\/ @brief Enumeration of chiplet filters\n\/\/\/\nenum TargetFilter\n{\n TARGET_FILTER_TP = 0x80000000, \/\/ Pervasive 1\n TARGET_FILTER_NEST_NORTH = 0x40000000, \/\/ Pervasive 2\n TARGET_FILTER_NEST_SOUTH = 0x20000000, \/\/ Pervasive 3\n TARGET_FILTER_NEST_EAST = 0x10000000, \/\/ Pervasive 4\n TARGET_FILTER_NEST_WEST = 0x08000000, \/\/ Pervasive 5\n TARGET_FILTER_XBUS = 0x04000000, \/\/ Pervasive 6\n TARGET_FILTER_MC_WEST = 0x02000000, \/\/ Pervasive 7\n TARGET_FILTER_MC_EAST = 0x01000000, \/\/ Pervasive 8\n TARGET_FILTER_OBUS0 = 0x00800000, \/\/ Pervasive 9\n TARGET_FILTER_OBUS1 = 0x00400000, \/\/ Pervasive 10\n TARGET_FILTER_OBUS2 = 0x00200000, \/\/ Pervasive 11\n TARGET_FILTER_OBUS3 = 0x00100000, \/\/ Pervasive 12\n TARGET_FILTER_PCI0 = 0x00080000, \/\/ Pervasive 13\n TARGET_FILTER_PCI1 = 0x00040000, \/\/ Pervasive 14\n TARGET_FILTER_PCI2 = 0x00020000, \/\/ Pervasive 15\n\n \/\/ Composite filters follow\n\n \/\/ Pervasive 2-5 (eg N0-N3) < req'd\n TARGET_FILTER_ALL_NEST = (TARGET_FILTER_NEST_NORTH |\n TARGET_FILTER_NEST_SOUTH | TARGET_FILTER_NEST_EAST |\n TARGET_FILTER_NEST_WEST),\n\n \/\/ Pervasive 2-4 (eg N0-N2) < req'd\n TARGET_FILTER_NEST_SLAVES =\n (TARGET_FILTER_NEST_NORTH | TARGET_FILTER_NEST_SOUTH |\n TARGET_FILTER_NEST_EAST),\n\n \/\/ Pervasive 5 (eg N32) < req'd\n TARGET_FILTER_NEST_MASTER = TARGET_FILTER_NEST_WEST,\n\n \/\/ Pervasive 7-8 (eg MC0-MC1)\n TARGET_FILTER_ALL_MC =\n (TARGET_FILTER_MC_WEST | TARGET_FILTER_MC_EAST),\n\n \/\/ Pervasive 9-12 (OB0-OB3)\n TARGET_FILTER_ALL_OBUS =\n (TARGET_FILTER_OBUS0 | TARGET_FILTER_OBUS1 | TARGET_FILTER_OBUS2 |\n TARGET_FILTER_OBUS3),\n\n \/\/ Pervasive 13-15 (PCI0-PCI2)\n TARGET_FILTER_ALL_PCI =\n (TARGET_FILTER_PCI0 | TARGET_FILTER_PCI1 | TARGET_FILTER_PCI2),\n\n \/\/ Sync mode filter = All NEST + All MCS\n TARGET_FILTER_SYNC_MODE_NEST =\n (TARGET_FILTER_ALL_NEST | TARGET_FILTER_ALL_MC),\n\n \/\/ All IO Targets except NEST\n TARGET_FILTER_ALL_IO_EXCEPT_NEST =\n (TARGET_FILTER_XBUS | TARGET_FILTER_ALL_PCI | TARGET_FILTER_ALL_OBUS),\n};\n\n\n\/\/\/ @cond\nconstexpr TargetType operator|(TargetType x, TargetType y)\n{\n return static_cast<TargetType>(static_cast<int>(x) |\n static_cast<int>(y));\n}\n\ntemplate<uint64_t V>\nclass bitCount\n{\n public:\n \/\/ Don't use enums, too hard to compare\n static const uint8_t count = bitCount < (V >> 1) >::count + (V & 1);\n};\n\ntemplate<>\nclass bitCount<0>\n{\n public:\n static const uint8_t count = 0;\n};\n\/\/\/ @endcond\n\n}\n\n#endif\n<commit_msg>Updated target filter definitions<commit_after>\/* IBM_PROLOG_BEGIN_TAG *\/\n\/* This is an automatically generated prolog. *\/\n\/* *\/\n\/* $Source: src\/import\/hwpf\/fapi2\/include\/target_types.H $ *\/\n\/* *\/\n\/* OpenPOWER HostBoot Project *\/\n\/* *\/\n\/* Contributors Listed Below - COPYRIGHT 2012,2019 *\/\n\/* [+] International Business Machines Corp. *\/\n\/* *\/\n\/* *\/\n\/* Licensed under the Apache License, Version 2.0 (the \"License\"); *\/\n\/* you may not use this file except in compliance with the License. *\/\n\/* You may obtain a copy of the License at *\/\n\/* *\/\n\/* http:\/\/www.apache.org\/licenses\/LICENSE-2.0 *\/\n\/* *\/\n\/* Unless required by applicable law or agreed to in writing, software *\/\n\/* distributed under the License is distributed on an \"AS IS\" BASIS, *\/\n\/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or *\/\n\/* implied. See the License for the specific language governing *\/\n\/* permissions and limitations under the License. *\/\n\/* *\/\n\/* IBM_PROLOG_END_TAG *\/\n\/**\n * @file target_types.H\n * @brief definitions for fapi2 target types\n *\/\n\n#ifndef __FAPI2_TARGET_TYPES__\n#define __FAPI2_TARGET_TYPES__\n#include <stdint.h>\n\/\/\/ FAPI namespace\nnamespace fapi2\n{\n\/\/\/\n\/\/\/ @enum fapi::TargetType\n\/\/\/ @brief Types, kinds, of targets\n\/\/\/ @note TYPE_NONE is used to represent empty\/NULL targets in lists\n\/\/\/ or tables. TYPE_ALL is used to pass targets to methods which\n\/\/\/ can act generally on any type of target\n\/\/\/\n\n\/\/\/ Target Kind\nenum TargetType\n{\n TARGET_TYPE_NONE = 0x00000000, \/\/\/< No type\n TARGET_TYPE_SYSTEM = 0x00000001, \/\/\/< System type\n TARGET_TYPE_DIMM = 0x00000002, \/\/\/< DIMM type\n TARGET_TYPE_PROC_CHIP = 0x00000004, \/\/\/< Processor type\n TARGET_TYPE_MEMBUF_CHIP = 0x00000008, \/\/\/< Membuf type\n TARGET_TYPE_EX = 0x00000010, \/\/\/< EX - 2x Core, L2, L3 - can be deconfigured\n TARGET_TYPE_MBA = 0x00000020, \/\/\/< MBA type\n TARGET_TYPE_MCS = 0x00000040, \/\/\/< MCS type\n TARGET_TYPE_XBUS = 0x00000080, \/\/\/< XBUS type\n TARGET_TYPE_ABUS = 0x00000100, \/\/\/< ABUS type\n TARGET_TYPE_L4 = 0x00000200, \/\/\/< L4 type\n TARGET_TYPE_CORE = 0x00000400, \/\/\/< Core - 4x threads(?) - can be deconfigured\n TARGET_TYPE_EQ = 0x00000800, \/\/\/< EQ - 4x core, 2x L2, 2x L3 - can be deconfigured\n TARGET_TYPE_MCA = 0x00001000, \/\/\/< MCA type\n TARGET_TYPE_MCBIST = 0x00002000, \/\/\/< MCBIST type\n TARGET_TYPE_MI = 0x00004000, \/\/\/< MI Memory Interface (Cumulus)\n TARGET_TYPE_CAPP = 0x00008000, \/\/\/< CAPP target\n TARGET_TYPE_DMI = 0x00010000, \/\/\/< DMI type\n TARGET_TYPE_OBUS = 0x00020000, \/\/\/< OBUS type\n TARGET_TYPE_NV = 0x00040000, \/\/\/< NV bus type\n TARGET_TYPE_SBE = 0x00080000, \/\/\/< SBE type\n TARGET_TYPE_PPE = 0x00100000, \/\/\/< PPE type\n TARGET_TYPE_PERV = 0x00200000, \/\/\/< Pervasive type\n TARGET_TYPE_PEC = 0x00400000, \/\/\/< PEC type\n TARGET_TYPE_PHB = 0x00800000, \/\/\/< PHB type\n\n TARGET_TYPE_ALL = 0xFFFFFFFF, \/\/\/< Any\/All types\n\n \/\/ Compound target types\n TARGET_TYPE_CHIPS = TARGET_TYPE_PROC_CHIP |\n TARGET_TYPE_MEMBUF_CHIP,\n\n TARGET_TYPE_CHIPLETS = TARGET_TYPE_EX |\n TARGET_TYPE_MBA |\n TARGET_TYPE_MCS |\n TARGET_TYPE_XBUS |\n TARGET_TYPE_ABUS |\n TARGET_TYPE_L4 |\n TARGET_TYPE_CORE |\n TARGET_TYPE_EQ |\n TARGET_TYPE_MCA |\n TARGET_TYPE_MCBIST |\n TARGET_TYPE_MI |\n TARGET_TYPE_DMI |\n TARGET_TYPE_OBUS |\n TARGET_TYPE_NV |\n TARGET_TYPE_SBE |\n TARGET_TYPE_PPE |\n TARGET_TYPE_PERV |\n TARGET_TYPE_PEC |\n TARGET_TYPE_PHB,\n\n \/\/ Mappings to target types found in the error xml files\n TARGET_TYPE_EX_CHIPLET = TARGET_TYPE_EX,\n TARGET_TYPE_MBA_CHIPLET = TARGET_TYPE_MBA,\n TARGET_TYPE_MCS_CHIPLET = TARGET_TYPE_MCS,\n TARGET_TYPE_XBUS_ENDPOINT = TARGET_TYPE_XBUS,\n TARGET_TYPE_ABUS_ENDPOINT = TARGET_TYPE_ABUS,\n};\n\n\/\/\/\n\/\/\/ @brief Enumeration of chiplet filters\n\/\/\/\nenum TargetFilter\n{\n TARGET_FILTER_TP = 0x8000000000000000, \/\/ Pervasive 1\n TARGET_FILTER_NEST_NORTH = 0x4000000000000000, \/\/ Pervasive 2\n TARGET_FILTER_NEST_SOUTH = 0x2000000000000000, \/\/ Pervasive 3\n TARGET_FILTER_NEST_EAST = 0x1000000000000000, \/\/ Pervasive 4\n TARGET_FILTER_NEST_WEST = 0x0800000000000000, \/\/ Pervasive 5\n TARGET_FILTER_XBUS = 0x0400000000000000, \/\/ Pervasive 6\n TARGET_FILTER_MC_WEST = 0x0200000000000000, \/\/ Pervasive 7\n TARGET_FILTER_MC_EAST = 0x0100000000000000, \/\/ Pervasive 8\n TARGET_FILTER_OBUS0 = 0x0080000000000000, \/\/ Pervasive 9\n TARGET_FILTER_OBUS1 = 0x0040000000000000, \/\/ Pervasive 10\n TARGET_FILTER_OBUS2 = 0x0020000000000000, \/\/ Pervasive 11\n TARGET_FILTER_OBUS3 = 0x0010000000000000, \/\/ Pervasive 12\n TARGET_FILTER_PCI0 = 0x0008000000000000, \/\/ Pervasive 13\n TARGET_FILTER_PCI1 = 0x0004000000000000, \/\/ Pervasive 14\n TARGET_FILTER_PCI2 = 0x0002000000000000, \/\/ Pervasive 15\n TARGET_FILTER_CACHE0 = 0x0001000000000000, \/\/ Pervasive 16\n TARGET_FILTER_CACHE1 = 0x0000800000000000, \/\/ Pervasive 17\n TARGET_FILTER_CACHE2 = 0x0000400000000000, \/\/ Pervasive 18\n TARGET_FILTER_CACHE3 = 0x0000200000000000, \/\/ Pervasive 19\n TARGET_FILTER_CACHE4 = 0x0000100000000000, \/\/ Pervasive 20\n TARGET_FILTER_CACHE5 = 0x0000080000000000, \/\/ Pervasive 21\n TARGET_FILTER_CORE0 = 0x0000040000000000, \/\/ Pervasive 32\n TARGET_FILTER_CORE1 = 0x0000020000000000, \/\/ Pervasive 33\n TARGET_FILTER_CORE2 = 0x0000010000000000, \/\/ Pervasive 34\n TARGET_FILTER_CORE3 = 0x0000008000000000, \/\/ Pervasive 35\n TARGET_FILTER_CORE4 = 0x0000004000000000, \/\/ Pervasive 36\n TARGET_FILTER_CORE5 = 0x0000002000000000, \/\/ Pervasive 37\n TARGET_FILTER_CORE6 = 0x0000001000000000, \/\/ Pervasive 38\n TARGET_FILTER_CORE7 = 0x0000000800000000, \/\/ Pervasive 39\n TARGET_FILTER_CORE8 = 0x0000000400000000, \/\/ Pervasive 40\n TARGET_FILTER_CORE9 = 0x0000000200000000, \/\/ Pervasive 41\n TARGET_FILTER_CORE10 = 0x0000000100000000, \/\/ Pervasive 42\n TARGET_FILTER_CORE11 = 0x0000000080000000, \/\/ Pervasive 43\n TARGET_FILTER_CORE12 = 0x0000000040000000, \/\/ Pervasive 44\n TARGET_FILTER_CORE13 = 0x0000000020000000, \/\/ Pervasive 45\n TARGET_FILTER_CORE14 = 0x0000000010000000, \/\/ Pervasive 46\n TARGET_FILTER_CORE15 = 0x0000000008000000, \/\/ Pervasive 47\n TARGET_FILTER_CORE16 = 0x0000000004000000, \/\/ Pervasive 48\n TARGET_FILTER_CORE17 = 0x0000000002000000, \/\/ Pervasive 49\n TARGET_FILTER_CORE18 = 0x0000000001000000, \/\/ Pervasive 50\n TARGET_FILTER_CORE19 = 0x0000000000800000, \/\/ Pervasive 51\n TARGET_FILTER_CORE20 = 0x0000000000400000, \/\/ Pervasive 52\n TARGET_FILTER_CORE21 = 0x0000000000200000, \/\/ Pervasive 53\n TARGET_FILTER_CORE22 = 0x0000000000100000, \/\/ Pervasive 54\n TARGET_FILTER_CORE23 = 0x0000000000080000, \/\/ Pervasive 55\n\n \/\/ Composite filters follow\n\n \/\/ Pervasive 32-55 (all cores)\n TARGET_FILTER_ALL_CORES = (TARGET_FILTER_CORE0 |\n TARGET_FILTER_CORE1 | TARGET_FILTER_CORE2 |\n TARGET_FILTER_CORE3 | TARGET_FILTER_CORE4 |\n TARGET_FILTER_CORE5 | TARGET_FILTER_CORE6 |\n TARGET_FILTER_CORE7 | TARGET_FILTER_CORE8 |\n TARGET_FILTER_CORE9 | TARGET_FILTER_CORE10 |\n TARGET_FILTER_CORE11 | TARGET_FILTER_CORE12 |\n TARGET_FILTER_CORE13 | TARGET_FILTER_CORE14 |\n TARGET_FILTER_CORE15 | TARGET_FILTER_CORE16 |\n TARGET_FILTER_CORE17 | TARGET_FILTER_CORE18 |\n TARGET_FILTER_CORE19 | TARGET_FILTER_CORE20 |\n TARGET_FILTER_CORE21 | TARGET_FILTER_CORE22 |\n TARGET_FILTER_CORE23),\n\n \/\/ Pervasive 16-21 (all caches)\n TARGET_FILTER_ALL_CACHES = (TARGET_FILTER_CACHE0 |\n TARGET_FILTER_CACHE1 | TARGET_FILTER_CACHE2 |\n TARGET_FILTER_CACHE3 | TARGET_FILTER_CACHE4 |\n TARGET_FILTER_CACHE5),\n\n \/\/ Pervasive 2-5 (eg N0-N3) < req'd\n TARGET_FILTER_ALL_NEST = (TARGET_FILTER_NEST_NORTH |\n TARGET_FILTER_NEST_SOUTH | TARGET_FILTER_NEST_EAST |\n TARGET_FILTER_NEST_WEST),\n\n \/\/ Pervasive 2-4 (eg N0-N2) < req'd\n TARGET_FILTER_NEST_SLAVES =\n (TARGET_FILTER_NEST_NORTH | TARGET_FILTER_NEST_SOUTH |\n TARGET_FILTER_NEST_EAST),\n\n \/\/ Pervasive 5 (eg N32) < req'd\n TARGET_FILTER_NEST_MASTER = TARGET_FILTER_NEST_WEST,\n\n \/\/ Pervasive 7-8 (eg MC0-MC1)\n TARGET_FILTER_ALL_MC =\n (TARGET_FILTER_MC_WEST | TARGET_FILTER_MC_EAST),\n\n \/\/ Pervasive 9-12 (OB0-OB3)\n TARGET_FILTER_ALL_OBUS =\n (TARGET_FILTER_OBUS0 | TARGET_FILTER_OBUS1 | TARGET_FILTER_OBUS2 |\n TARGET_FILTER_OBUS3),\n\n \/\/ Pervasive 13-15 (PCI0-PCI2)\n TARGET_FILTER_ALL_PCI =\n (TARGET_FILTER_PCI0 | TARGET_FILTER_PCI1 | TARGET_FILTER_PCI2),\n\n \/\/ Sync mode filter = All NEST + All MCS\n TARGET_FILTER_SYNC_MODE_NEST =\n (TARGET_FILTER_ALL_NEST | TARGET_FILTER_ALL_MC),\n\n \/\/ All IO Targets except NEST\n TARGET_FILTER_ALL_IO_EXCEPT_NEST =\n (TARGET_FILTER_XBUS | TARGET_FILTER_ALL_PCI | TARGET_FILTER_ALL_OBUS),\n\n \/\/ All sync mode IO except NEST\n TARGET_FILTER_SYNC_MODE_ALL_IO_EXCEPT_NEST =\n (TARGET_FILTER_ALL_MC | TARGET_FILTER_XBUS | TARGET_FILTER_ALL_PCI |\n TARGET_FILTER_ALL_OBUS),\n\n \/\/ All sync mode NEST slaves\n TARGET_FILTER_SYNC_MODE_NEST_SLAVES =\n (TARGET_FILTER_ALL_MC | TARGET_FILTER_NEST_SLAVES),\n\n \/\/ All sync mode IO\n TARGET_FILTER_SYNC_MODE_ALL_IO =\n (TARGET_FILTER_ALL_MC | TARGET_FILTER_ALL_NEST |\n TARGET_FILTER_ALL_OBUS | TARGET_FILTER_ALL_PCI |\n TARGET_FILTER_XBUS),\n\n \/\/ All IO\n TARGET_FILTER_ALL_IO = (TARGET_FILTER_ALL_NEST |\n TARGET_FILTER_ALL_OBUS | TARGET_FILTER_ALL_PCI |\n TARGET_FILTER_XBUS),\n\n \/\/ All sync mode except TP\n TARGET_FILTER_SYNC_MODE_ALL_EXCEPT_TP =\n (TARGET_FILTER_ALL_MC | TARGET_FILTER_ALL_NEST |\n TARGET_FILTER_ALL_OBUS | TARGET_FILTER_ALL_PCI |\n TARGET_FILTER_XBUS | TARGET_FILTER_ALL_CORES |\n TARGET_FILTER_ALL_CACHES),\n};\n\n\n\/\/\/ @cond\nconstexpr TargetType operator|(TargetType x, TargetType y)\n{\n return static_cast<TargetType>(static_cast<int>(x) |\n static_cast<int>(y));\n}\n\ntemplate<uint64_t V>\nclass bitCount\n{\n public:\n \/\/ Don't use enums, too hard to compare\n static const uint8_t count = bitCount < (V >> 1) >::count + (V & 1);\n};\n\ntemplate<>\nclass bitCount<0>\n{\n public:\n static const uint8_t count = 0;\n};\n\/\/\/ @endcond\n\n}\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>#include \"sdpnegotiator.h\"\n\n#include \"mediacapabilities.h\"\n\n#include \"common.h\"\n\n#include <QDateTime>\n\nSDPNegotiator::SDPNegotiator()\n{}\n\n\nstd::shared_ptr<SDPMessageInfo> SDPNegotiator::generateLocalSDP(QString localAddress)\n{\n \/\/ TODO: This should ask media manager, what options it supports.\n\n printNormal(this, \"Generating new SDP message with our address\",\n \"Local address\", localAddress);\n\n QString localUsername = getLocalUsername();\n\n if(localAddress == \"\"\n || localAddress == \"0.0.0.0\"\n || localUsername == \"\")\n {\n printWarning(this, \" Necessary info not set for SDP generation\",\n {\"username\"}, {localUsername});\n\n return nullptr;\n }\n\n \/\/ TODO: Get suitable SDP from media manager\n std::shared_ptr<SDPMessageInfo> newInfo = std::shared_ptr<SDPMessageInfo> (new SDPMessageInfo);\n newInfo->version = 0;\n generateOrigin(newInfo, localAddress);\n setConnectionAddress(newInfo, localAddress);\n\n newInfo->sessionName = SESSION_NAME;\n newInfo->sessionDescription = SESSION_DESCRIPTION;\n\n newInfo->timeDescriptions.push_back(TimeInfo{0,0, \"\", \"\", {}});\n\n MediaInfo audio;\n MediaInfo video;\n\n if(!generateAudioMedia(audio) || !generateVideoMedia(video))\n {\n return nullptr;\n }\n\n newInfo->media = {audio, video};\n\n return newInfo;\n}\n\n\n\nstd::shared_ptr<SDPMessageInfo> SDPNegotiator::negotiateSDP(SDPMessageInfo& remoteSDPOffer,\n QString localAddress)\n{\n \/\/ At this point we should have checked if their offer is acceptable.\n \/\/ Now we just have to generate our answer.\n\n std::shared_ptr<SDPMessageInfo> newInfo = std::shared_ptr<SDPMessageInfo> (new SDPMessageInfo);\n\n \/\/ we assume our answer will be different so new origin\n generateOrigin(newInfo, localAddress);\n setConnectionAddress(newInfo, localAddress);\n\n newInfo->version = 0;\n newInfo->sessionName = remoteSDPOffer.sessionName;\n newInfo->sessionDescription = remoteSDPOffer.sessionDescription;\n newInfo->timeDescriptions = remoteSDPOffer.timeDescriptions;\n\n \/\/ Now the hard part. Select best codecs and set our corresponding media ports.\n for (auto& remoteMedia : remoteSDPOffer.media)\n {\n MediaInfo ourMedia;\n ourMedia.type = remoteMedia.type;\n ourMedia.receivePort = 0; \/\/ TODO: ICE Should set this to one of its candidates\n ourMedia.proto = remoteMedia.proto;\n ourMedia.title = remoteMedia.title;\n if (remoteMedia.flagAttributes.empty())\n {\n ourMedia.flagAttributes = {A_SENDRECV};\n }\n else if (remoteMedia.flagAttributes.back() == A_SENDONLY)\n {\n ourMedia.flagAttributes = {A_RECVONLY};\n }\n else if (remoteMedia.flagAttributes.back() == A_RECVONLY)\n {\n ourMedia.flagAttributes = {A_SENDONLY};\n }\n else {\n ourMedia.flagAttributes = remoteMedia.flagAttributes;\n }\n\n \/\/ set our bitrate, not implemented\n \/\/ set our encryptionKey, not implemented\n\n if (remoteMedia.type == \"audio\")\n {\n QList<uint8_t> supportedNums = PREDEFINED_AUDIO_CODECS;\n QList<RTPMap> supportedCodecs = DYNAMIC_AUDIO_CODECS;\n\n selectBestCodec(remoteMedia.rtpNums, remoteMedia.codecs,\n supportedNums, supportedCodecs,\n ourMedia.rtpNums, ourMedia.codecs);\n\n }\n else if (remoteMedia.type == \"video\")\n {\n QList<uint8_t> supportedNums = PREDEFINED_VIDEO_CODECS;\n QList<RTPMap> supportedCodecs = DYNAMIC_VIDEO_CODECS;\n\n selectBestCodec(remoteMedia.rtpNums, remoteMedia.codecs,\n supportedNums, supportedCodecs,\n ourMedia.rtpNums, ourMedia.codecs);\n }\n newInfo->media.append(ourMedia);\n }\n\n\n return newInfo;\n}\n\n\nbool SDPNegotiator::selectBestCodec(QList<uint8_t>& remoteNums, QList<RTPMap> &remoteCodecs,\n QList<uint8_t>& supportedNums, QList<RTPMap> &supportedCodecs,\n QList<uint8_t>& outMatchingNums, QList<RTPMap> &outMatchingCodecs)\n{\n for (auto& remoteCodec : remoteCodecs)\n {\n for (auto& supportedCodec : supportedCodecs)\n {\n if(remoteCodec.codec == supportedCodec.codec)\n {\n outMatchingCodecs.append(remoteCodec);\n printDebug(DEBUG_NORMAL, \"SDPNegotiator\", \"Found suitable codec.\");\n\n outMatchingNums.push_back(remoteCodec.rtpNum);\n\n return true;\n }\n }\n }\n\n for (auto& rtpNumber : remoteNums)\n {\n for (auto& supportedNum : supportedNums)\n {\n if(rtpNumber == supportedNum)\n {\n outMatchingNums.append(rtpNumber);\n printDebug(DEBUG_NORMAL, \"SDPNegotiator\", \"Found suitable RTP number.\");\n return true;\n }\n }\n }\n\n printDebug(DEBUG_ERROR, \"SDPNegotiator\",\n \"Could not find suitable codec or RTP number for media.\");\n\n return false;\n}\n\n\nvoid SDPNegotiator::generateOrigin(std::shared_ptr<SDPMessageInfo> sdp,\n QString localAddress)\n{\n sdp->originator_username = getLocalUsername();\n sdp->sess_id = QDateTime::currentMSecsSinceEpoch();\n sdp->sess_v = QDateTime::currentMSecsSinceEpoch();\n sdp->host_nettype = \"IN\";\n sdp->host_address = localAddress;\n if (localAddress.front() == \"[\")\n {\n sdp->host_address = localAddress.mid(1, localAddress.size() - 2);\n sdp->host_addrtype = \"IP6\";\n }\n else {\n sdp->host_addrtype = \"IP4\";\n }\n}\n\n\nvoid SDPNegotiator::setConnectionAddress(std::shared_ptr<SDPMessageInfo> sdp,\n QString localAddress)\n{\n sdp->connection_address = localAddress;\n sdp->connection_nettype = \"IN\";\n if (localAddress.front() == \"[\")\n {\n sdp->connection_address = localAddress.mid(1, localAddress.size() - 2);\n sdp->connection_addrtype = \"IP6\";\n }\n else\n {\n sdp->connection_addrtype = \"IP4\";\n }\n}\n\nbool SDPNegotiator::generateAudioMedia(MediaInfo &audio)\n{\n \/\/ we ignore nettype, addrtype and address, because we use a global c=\n audio = {\"audio\", 0, \"RTP\/AVP\", {},\n \"\", \"\", \"\", \"\", {},\"\", DYNAMIC_AUDIO_CODECS, {A_SENDRECV}, {}};\n\n \/\/ add all the dynamic numbers first because we want to favor dynamic type codecs.\n for(RTPMap& codec : audio.codecs)\n {\n audio.rtpNums.push_back(codec.rtpNum);\n }\n\n audio.rtpNums += PREDEFINED_AUDIO_CODECS;\n return true;\n}\n\n\nbool SDPNegotiator::generateVideoMedia(MediaInfo& video)\n{\n \/\/ we ignore nettype, addrtype and address, because we use a global c=\n video = {\"video\", 0, \"RTP\/AVP\", {},\n \"\", \"\", \"\", \"\", {},\"\", DYNAMIC_VIDEO_CODECS, {A_SENDRECV}, {}};\n\n for(RTPMap& codec : video.codecs)\n {\n video.rtpNums.push_back(codec.rtpNum);\n }\n\n \/\/ just for completeness, we will probably never support any of the pre-set video types.\n video.rtpNums += PREDEFINED_VIDEO_CODECS;\n return true;\n}\n\n\nbool SDPNegotiator::checkSDPOffer(SDPMessageInfo &offer) const\n{\n \/\/ TODO: check everything.\n\n bool hasAudio = false;\n bool hasH265 = false;\n\n if(offer.connection_address == \"0.0.0.0\")\n {\n printPeerError(this, \"Got bad global address from SDP\", \"Address\",\n offer.connection_address);\n return false;\n }\n\n if(offer.version != 0)\n {\n printPeerError(this, \"Their offer had non-0 version\", \"Version\",\n QString::number(offer.version));\n return false;\n }\n\n QStringList debugCodecsFound = {};\n for(MediaInfo& media : offer.media)\n {\n if(!media.rtpNums.empty() && media.rtpNums.first() == 0)\n {\n debugCodecsFound << \"pcm\";\n hasAudio = true;\n }\n\n for(RTPMap& rtp : media.codecs)\n {\n if(rtp.codec == \"opus\")\n {\n debugCodecsFound << \"opus\";\n hasAudio = true;\n }\n else if(rtp.codec == \"h265\")\n {\n debugCodecsFound << \"h265\";\n hasH265 = true;\n }\n }\n }\n\n printDebug(DEBUG_NORMAL, \"Negotiation\",\n \"Found following codecs in SDP\", {\"Codecs\"}, debugCodecsFound);\n\n if (offer.timeDescriptions.size() >= 1)\n {\n if (offer.timeDescriptions.at(0).startTime != 0 ||\n offer.timeDescriptions.at(0).stopTime != 0)\n {\n printDebug(DEBUG_ERROR, \"Negotiation\",\n \"They offered us a session with limits. Unsupported.\");\n return false;\n }\n }\n else {\n printDebug(DEBUG_PROGRAM_ERROR, \"Negotiation\",\n \"they included wrong number of Time Descriptions. Should be detected earlier.\");\n return false;\n }\n\n\n return hasAudio && hasH265;\n}\n\n\nvoid SDPNegotiator::setMediaPair(MediaInfo& media,\n std::shared_ptr<ICEInfo> mediaInfo,\n bool local)\n{\n if (mediaInfo == nullptr)\n {\n printDebug(DEBUG_PROGRAM_ERROR, \"SDPNegotiator\", \"Null mediainfo in setMediaPair\");\n return;\n }\n\n \/\/ for local address, we bind to our rel-address if using non-host connection type\n if (local &&\n mediaInfo->type != \"host\" &&\n mediaInfo->rel_address != \"\" && mediaInfo->rel_port != 0)\n {\n media.connection_address = mediaInfo->rel_address;\n media.receivePort = mediaInfo->rel_port;\n }\n else\n {\n media.connection_address = mediaInfo->address;\n media.receivePort = mediaInfo->port;\n }\n}\n\n\n<commit_msg>fix(Negotiation): This check does not make sense if we use ICE<commit_after>#include \"sdpnegotiator.h\"\n\n#include \"mediacapabilities.h\"\n\n#include \"common.h\"\n\n#include <QDateTime>\n\nSDPNegotiator::SDPNegotiator()\n{}\n\n\nstd::shared_ptr<SDPMessageInfo> SDPNegotiator::generateLocalSDP(QString localAddress)\n{\n \/\/ TODO: This should ask media manager, what options it supports.\n\n printNormal(this, \"Generating new SDP message with our address\",\n \"Local address\", localAddress);\n\n QString localUsername = getLocalUsername();\n\n if(localAddress == \"\"\n || localAddress == \"0.0.0.0\"\n || localUsername == \"\")\n {\n printWarning(this, \" Necessary info not set for SDP generation\",\n {\"username\"}, {localUsername});\n\n return nullptr;\n }\n\n \/\/ TODO: Get suitable SDP from media manager\n std::shared_ptr<SDPMessageInfo> newInfo = std::shared_ptr<SDPMessageInfo> (new SDPMessageInfo);\n newInfo->version = 0;\n generateOrigin(newInfo, localAddress);\n setConnectionAddress(newInfo, localAddress);\n\n newInfo->sessionName = SESSION_NAME;\n newInfo->sessionDescription = SESSION_DESCRIPTION;\n\n newInfo->timeDescriptions.push_back(TimeInfo{0,0, \"\", \"\", {}});\n\n MediaInfo audio;\n MediaInfo video;\n\n if(!generateAudioMedia(audio) || !generateVideoMedia(video))\n {\n return nullptr;\n }\n\n newInfo->media = {audio, video};\n\n return newInfo;\n}\n\n\n\nstd::shared_ptr<SDPMessageInfo> SDPNegotiator::negotiateSDP(SDPMessageInfo& remoteSDPOffer,\n QString localAddress)\n{\n \/\/ At this point we should have checked if their offer is acceptable.\n \/\/ Now we just have to generate our answer.\n\n std::shared_ptr<SDPMessageInfo> newInfo = std::shared_ptr<SDPMessageInfo> (new SDPMessageInfo);\n\n \/\/ we assume our answer will be different so new origin\n generateOrigin(newInfo, localAddress);\n setConnectionAddress(newInfo, localAddress);\n\n newInfo->version = 0;\n newInfo->sessionName = remoteSDPOffer.sessionName;\n newInfo->sessionDescription = remoteSDPOffer.sessionDescription;\n newInfo->timeDescriptions = remoteSDPOffer.timeDescriptions;\n\n \/\/ Now the hard part. Select best codecs and set our corresponding media ports.\n for (auto& remoteMedia : remoteSDPOffer.media)\n {\n MediaInfo ourMedia;\n ourMedia.type = remoteMedia.type;\n ourMedia.receivePort = 0; \/\/ TODO: ICE Should set this to one of its candidates\n ourMedia.proto = remoteMedia.proto;\n ourMedia.title = remoteMedia.title;\n if (remoteMedia.flagAttributes.empty())\n {\n ourMedia.flagAttributes = {A_SENDRECV};\n }\n else if (remoteMedia.flagAttributes.back() == A_SENDONLY)\n {\n ourMedia.flagAttributes = {A_RECVONLY};\n }\n else if (remoteMedia.flagAttributes.back() == A_RECVONLY)\n {\n ourMedia.flagAttributes = {A_SENDONLY};\n }\n else {\n ourMedia.flagAttributes = remoteMedia.flagAttributes;\n }\n\n \/\/ set our bitrate, not implemented\n \/\/ set our encryptionKey, not implemented\n\n if (remoteMedia.type == \"audio\")\n {\n QList<uint8_t> supportedNums = PREDEFINED_AUDIO_CODECS;\n QList<RTPMap> supportedCodecs = DYNAMIC_AUDIO_CODECS;\n\n selectBestCodec(remoteMedia.rtpNums, remoteMedia.codecs,\n supportedNums, supportedCodecs,\n ourMedia.rtpNums, ourMedia.codecs);\n\n }\n else if (remoteMedia.type == \"video\")\n {\n QList<uint8_t> supportedNums = PREDEFINED_VIDEO_CODECS;\n QList<RTPMap> supportedCodecs = DYNAMIC_VIDEO_CODECS;\n\n selectBestCodec(remoteMedia.rtpNums, remoteMedia.codecs,\n supportedNums, supportedCodecs,\n ourMedia.rtpNums, ourMedia.codecs);\n }\n newInfo->media.append(ourMedia);\n }\n\n\n return newInfo;\n}\n\n\nbool SDPNegotiator::selectBestCodec(QList<uint8_t>& remoteNums, QList<RTPMap> &remoteCodecs,\n QList<uint8_t>& supportedNums, QList<RTPMap> &supportedCodecs,\n QList<uint8_t>& outMatchingNums, QList<RTPMap> &outMatchingCodecs)\n{\n for (auto& remoteCodec : remoteCodecs)\n {\n for (auto& supportedCodec : supportedCodecs)\n {\n if(remoteCodec.codec == supportedCodec.codec)\n {\n outMatchingCodecs.append(remoteCodec);\n printDebug(DEBUG_NORMAL, \"SDPNegotiator\", \"Found suitable codec.\");\n\n outMatchingNums.push_back(remoteCodec.rtpNum);\n\n return true;\n }\n }\n }\n\n for (auto& rtpNumber : remoteNums)\n {\n for (auto& supportedNum : supportedNums)\n {\n if(rtpNumber == supportedNum)\n {\n outMatchingNums.append(rtpNumber);\n printDebug(DEBUG_NORMAL, \"SDPNegotiator\", \"Found suitable RTP number.\");\n return true;\n }\n }\n }\n\n printDebug(DEBUG_ERROR, \"SDPNegotiator\",\n \"Could not find suitable codec or RTP number for media.\");\n\n return false;\n}\n\n\nvoid SDPNegotiator::generateOrigin(std::shared_ptr<SDPMessageInfo> sdp,\n QString localAddress)\n{\n sdp->originator_username = getLocalUsername();\n sdp->sess_id = QDateTime::currentMSecsSinceEpoch();\n sdp->sess_v = QDateTime::currentMSecsSinceEpoch();\n sdp->host_nettype = \"IN\";\n sdp->host_address = localAddress;\n if (localAddress.front() == \"[\")\n {\n sdp->host_address = localAddress.mid(1, localAddress.size() - 2);\n sdp->host_addrtype = \"IP6\";\n }\n else {\n sdp->host_addrtype = \"IP4\";\n }\n}\n\n\nvoid SDPNegotiator::setConnectionAddress(std::shared_ptr<SDPMessageInfo> sdp,\n QString localAddress)\n{\n sdp->connection_address = localAddress;\n sdp->connection_nettype = \"IN\";\n if (localAddress.front() == \"[\")\n {\n sdp->connection_address = localAddress.mid(1, localAddress.size() - 2);\n sdp->connection_addrtype = \"IP6\";\n }\n else\n {\n sdp->connection_addrtype = \"IP4\";\n }\n}\n\nbool SDPNegotiator::generateAudioMedia(MediaInfo &audio)\n{\n \/\/ we ignore nettype, addrtype and address, because we use a global c=\n audio = {\"audio\", 0, \"RTP\/AVP\", {},\n \"\", \"\", \"\", \"\", {},\"\", DYNAMIC_AUDIO_CODECS, {A_SENDRECV}, {}};\n\n \/\/ add all the dynamic numbers first because we want to favor dynamic type codecs.\n for(RTPMap& codec : audio.codecs)\n {\n audio.rtpNums.push_back(codec.rtpNum);\n }\n\n audio.rtpNums += PREDEFINED_AUDIO_CODECS;\n return true;\n}\n\n\nbool SDPNegotiator::generateVideoMedia(MediaInfo& video)\n{\n \/\/ we ignore nettype, addrtype and address, because we use a global c=\n video = {\"video\", 0, \"RTP\/AVP\", {},\n \"\", \"\", \"\", \"\", {},\"\", DYNAMIC_VIDEO_CODECS, {A_SENDRECV}, {}};\n\n for(RTPMap& codec : video.codecs)\n {\n video.rtpNums.push_back(codec.rtpNum);\n }\n\n \/\/ just for completeness, we will probably never support any of the pre-set video types.\n video.rtpNums += PREDEFINED_VIDEO_CODECS;\n return true;\n}\n\n\nbool SDPNegotiator::checkSDPOffer(SDPMessageInfo &offer) const\n{\n \/\/ TODO: check everything.\n\n bool hasAudio = false;\n bool hasH265 = false;\n\n if(offer.version != 0)\n {\n printPeerError(this, \"Their offer had non-0 version\", \"Version\",\n QString::number(offer.version));\n return false;\n }\n\n QStringList debugCodecsFound = {};\n for(MediaInfo& media : offer.media)\n {\n if(!media.rtpNums.empty() && media.rtpNums.first() == 0)\n {\n debugCodecsFound << \"pcm\";\n hasAudio = true;\n }\n\n for(RTPMap& rtp : media.codecs)\n {\n if(rtp.codec == \"opus\")\n {\n debugCodecsFound << \"opus\";\n hasAudio = true;\n }\n else if(rtp.codec == \"h265\")\n {\n debugCodecsFound << \"h265\";\n hasH265 = true;\n }\n }\n }\n\n printDebug(DEBUG_NORMAL, \"Negotiation\",\n \"Found following codecs in SDP\", {\"Codecs\"}, debugCodecsFound);\n\n if (offer.timeDescriptions.size() >= 1)\n {\n if (offer.timeDescriptions.at(0).startTime != 0 ||\n offer.timeDescriptions.at(0).stopTime != 0)\n {\n printDebug(DEBUG_ERROR, \"Negotiation\",\n \"They offered us a session with limits. Unsupported.\");\n return false;\n }\n }\n else {\n printDebug(DEBUG_PROGRAM_ERROR, \"Negotiation\",\n \"they included wrong number of Time Descriptions. Should be detected earlier.\");\n return false;\n }\n\n\n return hasAudio && hasH265;\n}\n\n\nvoid SDPNegotiator::setMediaPair(MediaInfo& media,\n std::shared_ptr<ICEInfo> mediaInfo,\n bool local)\n{\n if (mediaInfo == nullptr)\n {\n printDebug(DEBUG_PROGRAM_ERROR, \"SDPNegotiator\", \"Null mediainfo in setMediaPair\");\n return;\n }\n\n \/\/ for local address, we bind to our rel-address if using non-host connection type\n if (local &&\n mediaInfo->type != \"host\" &&\n mediaInfo->rel_address != \"\" && mediaInfo->rel_port != 0)\n {\n media.connection_address = mediaInfo->rel_address;\n media.receivePort = mediaInfo->rel_port;\n }\n else\n {\n media.connection_address = mediaInfo->address;\n media.receivePort = mediaInfo->port;\n }\n}\n\n\n<|endoftext|>"} {"text":"<commit_before>\/\/===- InputFiles.cpp -----------------------------------------------------===\/\/\n\/\/\n\/\/ The LLVM Linker\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"InputFiles.h\"\n#include \"InputSection.h\"\n#include \"Error.h\"\n#include \"Symbols.h\"\n#include \"llvm\/ADT\/STLExtras.h\"\n\nusing namespace llvm;\nusing namespace llvm::ELF;\nusing namespace llvm::object;\nusing namespace llvm::sys::fs;\n\nusing namespace lld;\nusing namespace lld::elf2;\n\nnamespace {\nclass ECRAII {\n std::error_code EC;\n\npublic:\n std::error_code &getEC() { return EC; }\n ~ECRAII() { error(EC); }\n};\n}\n\ntemplate <class ELFT>\nELFFileBase<ELFT>::ELFFileBase(Kind K, ELFKind EKind, MemoryBufferRef M)\n : InputFile(K, M), EKind(EKind), ELFObj(MB.getBuffer(), ECRAII().getEC()) {}\n\ntemplate <class ELFT>\ntypename ELFFileBase<ELFT>::Elf_Sym_Range\nELFFileBase<ELFT>::getSymbolsHelper(bool Local) {\n if (!Symtab)\n return Elf_Sym_Range(nullptr, nullptr);\n Elf_Sym_Range Syms = ELFObj.symbols(Symtab);\n uint32_t NumSymbols = std::distance(Syms.begin(), Syms.end());\n uint32_t FirstNonLocal = Symtab->sh_info;\n if (FirstNonLocal > NumSymbols)\n error(\"Invalid sh_info in symbol table\");\n if (!Local)\n return make_range(Syms.begin() + FirstNonLocal, Syms.end());\n \/\/ +1 to skip over dummy symbol.\n return make_range(Syms.begin() + 1, Syms.begin() + FirstNonLocal);\n}\n\ntemplate <class ELFT> void ELFFileBase<ELFT>::initStringTable() {\n if (!Symtab)\n return;\n ErrorOr<StringRef> StringTableOrErr = ELFObj.getStringTableForSymtab(*Symtab);\n error(StringTableOrErr.getError());\n StringTable = *StringTableOrErr;\n}\n\ntemplate <class ELFT>\ntypename ELFFileBase<ELFT>::Elf_Sym_Range\nELFFileBase<ELFT>::getNonLocalSymbols() {\n return getSymbolsHelper(false);\n}\n\ntemplate <class ELFT>\nObjectFile<ELFT>::ObjectFile(MemoryBufferRef M)\n : ELFFileBase<ELFT>(Base::ObjectKind, Base::getStaticELFKind(), M) {}\n\ntemplate <class ELFT>\ntypename ObjectFile<ELFT>::Elf_Sym_Range ObjectFile<ELFT>::getLocalSymbols() {\n return this->getSymbolsHelper(true);\n}\n\ntemplate <class ELFT>\nvoid elf2::ObjectFile<ELFT>::parse(DenseSet<StringRef> &Comdats) {\n \/\/ Read section and symbol tables.\n initializeSections(Comdats);\n initializeSymbols();\n}\n\ntemplate <class ELFT>\nStringRef ObjectFile<ELFT>::getShtGroupSignature(const Elf_Shdr &Sec) {\n const ELFFile<ELFT> &Obj = this->ELFObj;\n uint32_t SymtabdSectionIndex = Sec.sh_link;\n ErrorOr<const Elf_Shdr *> SecOrErr = Obj.getSection(SymtabdSectionIndex);\n error(SecOrErr);\n const Elf_Shdr *SymtabSec = *SecOrErr;\n uint32_t SymIndex = Sec.sh_info;\n const Elf_Sym *Sym = Obj.getSymbol(SymtabSec, SymIndex);\n ErrorOr<StringRef> StringTableOrErr = Obj.getStringTableForSymtab(*SymtabSec);\n error(StringTableOrErr);\n ErrorOr<StringRef> SignatureOrErr = Sym->getName(*StringTableOrErr);\n error(SignatureOrErr);\n return *SignatureOrErr;\n}\n\ntemplate <class ELFT>\nArrayRef<typename ObjectFile<ELFT>::GroupEntryType>\nObjectFile<ELFT>::getShtGroupEntries(const Elf_Shdr &Sec) {\n const ELFFile<ELFT> &Obj = this->ELFObj;\n ErrorOr<ArrayRef<GroupEntryType>> EntriesOrErr =\n Obj.template getSectionContentsAsArray<GroupEntryType>(&Sec);\n error(EntriesOrErr.getError());\n ArrayRef<GroupEntryType> Entries = *EntriesOrErr;\n if (Entries.empty() || Entries[0] != GRP_COMDAT)\n error(\"Unsupported SHT_GROUP format\");\n return Entries.slice(1);\n}\n\ntemplate <class ELFT>\nvoid elf2::ObjectFile<ELFT>::initializeSections(DenseSet<StringRef> &Comdats) {\n uint64_t Size = this->ELFObj.getNumSections();\n Sections.resize(Size);\n unsigned I = -1;\n const ELFFile<ELFT> &Obj = this->ELFObj;\n for (const Elf_Shdr &Sec : Obj.sections()) {\n ++I;\n if (Sections[I] == &InputSection<ELFT>::Discarded)\n continue;\n\n switch (Sec.sh_type) {\n case SHT_GROUP:\n Sections[I] = &InputSection<ELFT>::Discarded;\n if (Comdats.insert(getShtGroupSignature(Sec)).second)\n continue;\n for (GroupEntryType E : getShtGroupEntries(Sec)) {\n uint32_t SecIndex = E;\n if (SecIndex >= Size)\n error(\"Invalid section index in group\");\n Sections[SecIndex] = &InputSection<ELFT>::Discarded;\n }\n break;\n case SHT_SYMTAB:\n this->Symtab = &Sec;\n break;\n case SHT_SYMTAB_SHNDX: {\n ErrorOr<ArrayRef<Elf_Word>> ErrorOrTable = Obj.getSHNDXTable(Sec);\n error(ErrorOrTable);\n SymtabSHNDX = *ErrorOrTable;\n break;\n }\n case SHT_STRTAB:\n case SHT_NULL:\n break;\n case SHT_RELA:\n case SHT_REL: {\n uint32_t RelocatedSectionIndex = Sec.sh_info;\n if (RelocatedSectionIndex >= Size)\n error(\"Invalid relocated section index\");\n InputSection<ELFT> *RelocatedSection = Sections[RelocatedSectionIndex];\n if (!RelocatedSection)\n error(\"Unsupported relocation reference\");\n RelocatedSection->RelocSections.push_back(&Sec);\n break;\n }\n default:\n Sections[I] = new (this->Alloc) InputSection<ELFT>(this, &Sec);\n break;\n }\n }\n}\n\ntemplate <class ELFT> void elf2::ObjectFile<ELFT>::initializeSymbols() {\n this->initStringTable();\n Elf_Sym_Range Syms = this->getNonLocalSymbols();\n uint32_t NumSymbols = std::distance(Syms.begin(), Syms.end());\n this->SymbolBodies.reserve(NumSymbols);\n for (const Elf_Sym &Sym : Syms)\n this->SymbolBodies.push_back(createSymbolBody(this->StringTable, &Sym));\n}\n\ntemplate <class ELFT>\nSymbolBody *elf2::ObjectFile<ELFT>::createSymbolBody(StringRef StringTable,\n const Elf_Sym *Sym) {\n ErrorOr<StringRef> NameOrErr = Sym->getName(StringTable);\n error(NameOrErr.getError());\n StringRef Name = *NameOrErr;\n\n uint32_t SecIndex = Sym->st_shndx;\n switch (SecIndex) {\n case SHN_ABS:\n return new (this->Alloc) DefinedAbsolute<ELFT>(Name, *Sym);\n case SHN_UNDEF:\n return new (this->Alloc) Undefined<ELFT>(Name, *Sym);\n case SHN_COMMON:\n return new (this->Alloc) DefinedCommon<ELFT>(Name, *Sym);\n case SHN_XINDEX:\n SecIndex = this->ELFObj.getExtendedSymbolTableIndex(Sym, this->Symtab,\n SymtabSHNDX);\n break;\n }\n\n if (SecIndex >= Sections.size() || !SecIndex || !Sections[SecIndex])\n error(\"Invalid section index\");\n\n switch (Sym->getBinding()) {\n default:\n error(\"unexpected binding\");\n case STB_GLOBAL:\n case STB_WEAK:\n case STB_GNU_UNIQUE: {\n InputSection<ELFT> *Sec = Sections[SecIndex];\n if (Sec == &InputSection<ELFT>::Discarded)\n return new (this->Alloc) Undefined<ELFT>(Name, *Sym);\n return new (this->Alloc) DefinedRegular<ELFT>(Name, *Sym, *Sec);\n }\n }\n}\n\nstatic std::unique_ptr<Archive> openArchive(MemoryBufferRef MB) {\n ErrorOr<std::unique_ptr<Archive>> ArchiveOrErr = Archive::create(MB);\n error(ArchiveOrErr, \"Failed to parse archive\");\n return std::move(*ArchiveOrErr);\n}\n\nvoid ArchiveFile::parse() {\n File = openArchive(MB);\n\n \/\/ Allocate a buffer for Lazy objects.\n size_t NumSyms = File->getNumberOfSymbols();\n LazySymbols.reserve(NumSyms);\n\n \/\/ Read the symbol table to construct Lazy objects.\n for (const Archive::Symbol &Sym : File->symbols())\n LazySymbols.emplace_back(this, Sym);\n}\n\n\/\/ Returns a buffer pointing to a member file containing a given symbol.\nMemoryBufferRef ArchiveFile::getMember(const Archive::Symbol *Sym) {\n ErrorOr<Archive::child_iterator> ItOrErr = Sym->getMember();\n error(ItOrErr,\n Twine(\"Could not get the member for symbol \") + Sym->getName());\n Archive::child_iterator It = *ItOrErr;\n\n if (!Seen.insert(It->getChildOffset()).second)\n return MemoryBufferRef();\n\n ErrorOr<MemoryBufferRef> Ret = It->getMemoryBufferRef();\n error(Ret, Twine(\"Could not get the buffer for the member defining symbol \") +\n Sym->getName());\n return *Ret;\n}\n\nstd::vector<MemoryBufferRef> ArchiveFile::getMembers() {\n File = openArchive(MB);\n\n std::vector<MemoryBufferRef> Result;\n for (const Archive::Child &Child : File->children()) {\n ErrorOr<MemoryBufferRef> MbOrErr = Child.getMemoryBufferRef();\n error(MbOrErr,\n Twine(\"Could not get the buffer for a child of the archive \") +\n File->getFileName());\n Result.push_back(MbOrErr.get());\n }\n return Result;\n}\n\ntemplate <class ELFT>\nSharedFile<ELFT>::SharedFile(MemoryBufferRef M)\n : ELFFileBase<ELFT>(Base::SharedKind, Base::getStaticELFKind(), M) {\n AsNeeded = Config->AsNeeded;\n}\n\ntemplate <class ELFT> void SharedFile<ELFT>::parseSoName() {\n typedef typename ELFFile<ELFT>::Elf_Dyn Elf_Dyn;\n typedef typename ELFFile<ELFT>::uintX_t uintX_t;\n const Elf_Shdr *DynamicSec = nullptr;\n\n const ELFFile<ELFT> Obj = this->ELFObj;\n for (const Elf_Shdr &Sec : Obj.sections()) {\n uint32_t Type = Sec.sh_type;\n if (Type == SHT_DYNSYM)\n this->Symtab = &Sec;\n else if (Type == SHT_DYNAMIC)\n DynamicSec = &Sec;\n }\n\n this->initStringTable();\n this->SoName = this->getName();\n\n if (DynamicSec) {\n auto *Begin =\n reinterpret_cast<const Elf_Dyn *>(Obj.base() + DynamicSec->sh_offset);\n const Elf_Dyn *End = Begin + DynamicSec->sh_size \/ sizeof(Elf_Dyn);\n\n for (const Elf_Dyn &Dyn : make_range(Begin, End)) {\n if (Dyn.d_tag == DT_SONAME) {\n uintX_t Val = Dyn.getVal();\n if (Val >= this->StringTable.size())\n error(\"Invalid DT_SONAME entry\");\n this->SoName = StringRef(this->StringTable.data() + Val);\n break;\n }\n }\n }\n}\n\ntemplate <class ELFT> void SharedFile<ELFT>::parse() {\n Elf_Sym_Range Syms = this->getNonLocalSymbols();\n uint32_t NumSymbols = std::distance(Syms.begin(), Syms.end());\n SymbolBodies.reserve(NumSymbols);\n for (const Elf_Sym &Sym : Syms) {\n if (Sym.isUndefined())\n continue;\n\n ErrorOr<StringRef> NameOrErr = Sym.getName(this->StringTable);\n error(NameOrErr.getError());\n StringRef Name = *NameOrErr;\n\n SymbolBodies.emplace_back(this, Name, Sym);\n }\n}\n\nnamespace lld {\nnamespace elf2 {\ntemplate class ELFFileBase<llvm::object::ELF32LE>;\ntemplate class ELFFileBase<llvm::object::ELF32BE>;\ntemplate class ELFFileBase<llvm::object::ELF64LE>;\ntemplate class ELFFileBase<llvm::object::ELF64BE>;\n\ntemplate class elf2::ObjectFile<llvm::object::ELF32LE>;\ntemplate class elf2::ObjectFile<llvm::object::ELF32BE>;\ntemplate class elf2::ObjectFile<llvm::object::ELF64LE>;\ntemplate class elf2::ObjectFile<llvm::object::ELF64BE>;\n\ntemplate class elf2::SharedFile<llvm::object::ELF32LE>;\ntemplate class elf2::SharedFile<llvm::object::ELF32BE>;\ntemplate class elf2::SharedFile<llvm::object::ELF64LE>;\ntemplate class elf2::SharedFile<llvm::object::ELF64BE>;\n}\n}\n<commit_msg>Remove redundant namespace specifiers.<commit_after>\/\/===- InputFiles.cpp -----------------------------------------------------===\/\/\n\/\/\n\/\/ The LLVM Linker\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"InputFiles.h\"\n#include \"InputSection.h\"\n#include \"Error.h\"\n#include \"Symbols.h\"\n#include \"llvm\/ADT\/STLExtras.h\"\n\nusing namespace llvm;\nusing namespace llvm::ELF;\nusing namespace llvm::object;\nusing namespace llvm::sys::fs;\n\nusing namespace lld;\nusing namespace lld::elf2;\n\nnamespace {\nclass ECRAII {\n std::error_code EC;\n\npublic:\n std::error_code &getEC() { return EC; }\n ~ECRAII() { error(EC); }\n};\n}\n\ntemplate <class ELFT>\nELFFileBase<ELFT>::ELFFileBase(Kind K, ELFKind EKind, MemoryBufferRef M)\n : InputFile(K, M), EKind(EKind), ELFObj(MB.getBuffer(), ECRAII().getEC()) {}\n\ntemplate <class ELFT>\ntypename ELFFileBase<ELFT>::Elf_Sym_Range\nELFFileBase<ELFT>::getSymbolsHelper(bool Local) {\n if (!Symtab)\n return Elf_Sym_Range(nullptr, nullptr);\n Elf_Sym_Range Syms = ELFObj.symbols(Symtab);\n uint32_t NumSymbols = std::distance(Syms.begin(), Syms.end());\n uint32_t FirstNonLocal = Symtab->sh_info;\n if (FirstNonLocal > NumSymbols)\n error(\"Invalid sh_info in symbol table\");\n if (!Local)\n return make_range(Syms.begin() + FirstNonLocal, Syms.end());\n \/\/ +1 to skip over dummy symbol.\n return make_range(Syms.begin() + 1, Syms.begin() + FirstNonLocal);\n}\n\ntemplate <class ELFT> void ELFFileBase<ELFT>::initStringTable() {\n if (!Symtab)\n return;\n ErrorOr<StringRef> StringTableOrErr = ELFObj.getStringTableForSymtab(*Symtab);\n error(StringTableOrErr.getError());\n StringTable = *StringTableOrErr;\n}\n\ntemplate <class ELFT>\ntypename ELFFileBase<ELFT>::Elf_Sym_Range\nELFFileBase<ELFT>::getNonLocalSymbols() {\n return getSymbolsHelper(false);\n}\n\ntemplate <class ELFT>\nObjectFile<ELFT>::ObjectFile(MemoryBufferRef M)\n : ELFFileBase<ELFT>(Base::ObjectKind, Base::getStaticELFKind(), M) {}\n\ntemplate <class ELFT>\ntypename ObjectFile<ELFT>::Elf_Sym_Range ObjectFile<ELFT>::getLocalSymbols() {\n return this->getSymbolsHelper(true);\n}\n\ntemplate <class ELFT>\nvoid elf2::ObjectFile<ELFT>::parse(DenseSet<StringRef> &Comdats) {\n \/\/ Read section and symbol tables.\n initializeSections(Comdats);\n initializeSymbols();\n}\n\ntemplate <class ELFT>\nStringRef ObjectFile<ELFT>::getShtGroupSignature(const Elf_Shdr &Sec) {\n const ELFFile<ELFT> &Obj = this->ELFObj;\n uint32_t SymtabdSectionIndex = Sec.sh_link;\n ErrorOr<const Elf_Shdr *> SecOrErr = Obj.getSection(SymtabdSectionIndex);\n error(SecOrErr);\n const Elf_Shdr *SymtabSec = *SecOrErr;\n uint32_t SymIndex = Sec.sh_info;\n const Elf_Sym *Sym = Obj.getSymbol(SymtabSec, SymIndex);\n ErrorOr<StringRef> StringTableOrErr = Obj.getStringTableForSymtab(*SymtabSec);\n error(StringTableOrErr);\n ErrorOr<StringRef> SignatureOrErr = Sym->getName(*StringTableOrErr);\n error(SignatureOrErr);\n return *SignatureOrErr;\n}\n\ntemplate <class ELFT>\nArrayRef<typename ObjectFile<ELFT>::GroupEntryType>\nObjectFile<ELFT>::getShtGroupEntries(const Elf_Shdr &Sec) {\n const ELFFile<ELFT> &Obj = this->ELFObj;\n ErrorOr<ArrayRef<GroupEntryType>> EntriesOrErr =\n Obj.template getSectionContentsAsArray<GroupEntryType>(&Sec);\n error(EntriesOrErr.getError());\n ArrayRef<GroupEntryType> Entries = *EntriesOrErr;\n if (Entries.empty() || Entries[0] != GRP_COMDAT)\n error(\"Unsupported SHT_GROUP format\");\n return Entries.slice(1);\n}\n\ntemplate <class ELFT>\nvoid elf2::ObjectFile<ELFT>::initializeSections(DenseSet<StringRef> &Comdats) {\n uint64_t Size = this->ELFObj.getNumSections();\n Sections.resize(Size);\n unsigned I = -1;\n const ELFFile<ELFT> &Obj = this->ELFObj;\n for (const Elf_Shdr &Sec : Obj.sections()) {\n ++I;\n if (Sections[I] == &InputSection<ELFT>::Discarded)\n continue;\n\n switch (Sec.sh_type) {\n case SHT_GROUP:\n Sections[I] = &InputSection<ELFT>::Discarded;\n if (Comdats.insert(getShtGroupSignature(Sec)).second)\n continue;\n for (GroupEntryType E : getShtGroupEntries(Sec)) {\n uint32_t SecIndex = E;\n if (SecIndex >= Size)\n error(\"Invalid section index in group\");\n Sections[SecIndex] = &InputSection<ELFT>::Discarded;\n }\n break;\n case SHT_SYMTAB:\n this->Symtab = &Sec;\n break;\n case SHT_SYMTAB_SHNDX: {\n ErrorOr<ArrayRef<Elf_Word>> ErrorOrTable = Obj.getSHNDXTable(Sec);\n error(ErrorOrTable);\n SymtabSHNDX = *ErrorOrTable;\n break;\n }\n case SHT_STRTAB:\n case SHT_NULL:\n break;\n case SHT_RELA:\n case SHT_REL: {\n uint32_t RelocatedSectionIndex = Sec.sh_info;\n if (RelocatedSectionIndex >= Size)\n error(\"Invalid relocated section index\");\n InputSection<ELFT> *RelocatedSection = Sections[RelocatedSectionIndex];\n if (!RelocatedSection)\n error(\"Unsupported relocation reference\");\n RelocatedSection->RelocSections.push_back(&Sec);\n break;\n }\n default:\n Sections[I] = new (this->Alloc) InputSection<ELFT>(this, &Sec);\n break;\n }\n }\n}\n\ntemplate <class ELFT> void elf2::ObjectFile<ELFT>::initializeSymbols() {\n this->initStringTable();\n Elf_Sym_Range Syms = this->getNonLocalSymbols();\n uint32_t NumSymbols = std::distance(Syms.begin(), Syms.end());\n this->SymbolBodies.reserve(NumSymbols);\n for (const Elf_Sym &Sym : Syms)\n this->SymbolBodies.push_back(createSymbolBody(this->StringTable, &Sym));\n}\n\ntemplate <class ELFT>\nSymbolBody *elf2::ObjectFile<ELFT>::createSymbolBody(StringRef StringTable,\n const Elf_Sym *Sym) {\n ErrorOr<StringRef> NameOrErr = Sym->getName(StringTable);\n error(NameOrErr.getError());\n StringRef Name = *NameOrErr;\n\n uint32_t SecIndex = Sym->st_shndx;\n switch (SecIndex) {\n case SHN_ABS:\n return new (this->Alloc) DefinedAbsolute<ELFT>(Name, *Sym);\n case SHN_UNDEF:\n return new (this->Alloc) Undefined<ELFT>(Name, *Sym);\n case SHN_COMMON:\n return new (this->Alloc) DefinedCommon<ELFT>(Name, *Sym);\n case SHN_XINDEX:\n SecIndex = this->ELFObj.getExtendedSymbolTableIndex(Sym, this->Symtab,\n SymtabSHNDX);\n break;\n }\n\n if (SecIndex >= Sections.size() || !SecIndex || !Sections[SecIndex])\n error(\"Invalid section index\");\n\n switch (Sym->getBinding()) {\n default:\n error(\"unexpected binding\");\n case STB_GLOBAL:\n case STB_WEAK:\n case STB_GNU_UNIQUE: {\n InputSection<ELFT> *Sec = Sections[SecIndex];\n if (Sec == &InputSection<ELFT>::Discarded)\n return new (this->Alloc) Undefined<ELFT>(Name, *Sym);\n return new (this->Alloc) DefinedRegular<ELFT>(Name, *Sym, *Sec);\n }\n }\n}\n\nstatic std::unique_ptr<Archive> openArchive(MemoryBufferRef MB) {\n ErrorOr<std::unique_ptr<Archive>> ArchiveOrErr = Archive::create(MB);\n error(ArchiveOrErr, \"Failed to parse archive\");\n return std::move(*ArchiveOrErr);\n}\n\nvoid ArchiveFile::parse() {\n File = openArchive(MB);\n\n \/\/ Allocate a buffer for Lazy objects.\n size_t NumSyms = File->getNumberOfSymbols();\n LazySymbols.reserve(NumSyms);\n\n \/\/ Read the symbol table to construct Lazy objects.\n for (const Archive::Symbol &Sym : File->symbols())\n LazySymbols.emplace_back(this, Sym);\n}\n\n\/\/ Returns a buffer pointing to a member file containing a given symbol.\nMemoryBufferRef ArchiveFile::getMember(const Archive::Symbol *Sym) {\n ErrorOr<Archive::child_iterator> ItOrErr = Sym->getMember();\n error(ItOrErr,\n Twine(\"Could not get the member for symbol \") + Sym->getName());\n Archive::child_iterator It = *ItOrErr;\n\n if (!Seen.insert(It->getChildOffset()).second)\n return MemoryBufferRef();\n\n ErrorOr<MemoryBufferRef> Ret = It->getMemoryBufferRef();\n error(Ret, Twine(\"Could not get the buffer for the member defining symbol \") +\n Sym->getName());\n return *Ret;\n}\n\nstd::vector<MemoryBufferRef> ArchiveFile::getMembers() {\n File = openArchive(MB);\n\n std::vector<MemoryBufferRef> Result;\n for (const Archive::Child &Child : File->children()) {\n ErrorOr<MemoryBufferRef> MbOrErr = Child.getMemoryBufferRef();\n error(MbOrErr,\n Twine(\"Could not get the buffer for a child of the archive \") +\n File->getFileName());\n Result.push_back(MbOrErr.get());\n }\n return Result;\n}\n\ntemplate <class ELFT>\nSharedFile<ELFT>::SharedFile(MemoryBufferRef M)\n : ELFFileBase<ELFT>(Base::SharedKind, Base::getStaticELFKind(), M) {\n AsNeeded = Config->AsNeeded;\n}\n\ntemplate <class ELFT> void SharedFile<ELFT>::parseSoName() {\n typedef typename ELFFile<ELFT>::Elf_Dyn Elf_Dyn;\n typedef typename ELFFile<ELFT>::uintX_t uintX_t;\n const Elf_Shdr *DynamicSec = nullptr;\n\n const ELFFile<ELFT> Obj = this->ELFObj;\n for (const Elf_Shdr &Sec : Obj.sections()) {\n uint32_t Type = Sec.sh_type;\n if (Type == SHT_DYNSYM)\n this->Symtab = &Sec;\n else if (Type == SHT_DYNAMIC)\n DynamicSec = &Sec;\n }\n\n this->initStringTable();\n this->SoName = this->getName();\n\n if (DynamicSec) {\n auto *Begin =\n reinterpret_cast<const Elf_Dyn *>(Obj.base() + DynamicSec->sh_offset);\n const Elf_Dyn *End = Begin + DynamicSec->sh_size \/ sizeof(Elf_Dyn);\n\n for (const Elf_Dyn &Dyn : make_range(Begin, End)) {\n if (Dyn.d_tag == DT_SONAME) {\n uintX_t Val = Dyn.getVal();\n if (Val >= this->StringTable.size())\n error(\"Invalid DT_SONAME entry\");\n this->SoName = StringRef(this->StringTable.data() + Val);\n break;\n }\n }\n }\n}\n\ntemplate <class ELFT> void SharedFile<ELFT>::parse() {\n Elf_Sym_Range Syms = this->getNonLocalSymbols();\n uint32_t NumSymbols = std::distance(Syms.begin(), Syms.end());\n SymbolBodies.reserve(NumSymbols);\n for (const Elf_Sym &Sym : Syms) {\n if (Sym.isUndefined())\n continue;\n\n ErrorOr<StringRef> NameOrErr = Sym.getName(this->StringTable);\n error(NameOrErr.getError());\n StringRef Name = *NameOrErr;\n\n SymbolBodies.emplace_back(this, Name, Sym);\n }\n}\n\nnamespace lld {\nnamespace elf2 {\ntemplate class ELFFileBase<llvm::object::ELF32LE>;\ntemplate class ELFFileBase<llvm::object::ELF32BE>;\ntemplate class ELFFileBase<llvm::object::ELF64LE>;\ntemplate class ELFFileBase<llvm::object::ELF64BE>;\n\ntemplate class ObjectFile<llvm::object::ELF32LE>;\ntemplate class ObjectFile<llvm::object::ELF32BE>;\ntemplate class ObjectFile<llvm::object::ELF64LE>;\ntemplate class ObjectFile<llvm::object::ELF64BE>;\n\ntemplate class SharedFile<llvm::object::ELF32LE>;\ntemplate class SharedFile<llvm::object::ELF32BE>;\ntemplate class SharedFile<llvm::object::ELF64LE>;\ntemplate class SharedFile<llvm::object::ELF64BE>;\n}\n}\n<|endoftext|>"} {"text":"<commit_before>\/**********************************************************************\n * $Id$\n *\n * GEOS - Geometry Engine Open Source\n * http:\/\/geos.refractions.net\n *\n * Copyright (C) 2001-2002 Vivid Solutions Inc.\n *\n * This is free software; you can redistribute and\/or modify it under\n * the terms of the GNU Lesser General Public Licence as published\n * by the Free Software Foundation. \n * See the COPYING file for more information.\n *\n **********************************************************************\/\n\n#include <geos\/geomgraph.h>\n\/\/#include \"..\/headers\/util.h\"\n\n#ifndef DEBUG\n#define DEBUG 0\n#endif\n#ifndef COMPUTE_Z\n#define COMPUTE_Z 1\n#endif\n\nnamespace geos {\n\nNode::Node(Coordinate& newCoord, EdgeEndStar* newEdges): GraphComponent(new Label(0,Location::UNDEF)) {\n\tcoord=newCoord;\n#if DEBUG\n\tcerr<<\"[\"<<this<<\"] Node::Node(\"<<newCoord.toString()<<\")\"<<endl;\n#endif\n\n#if COMPUTE_Z\n\tztot = 0;\n\taddZ(newCoord.z);\n\tif ( newEdges )\n\t{\n\t\tvector<EdgeEnd*>*eev = newEdges->getEdges();\n\t\tfor (unsigned int i=0; i<eev->size(); i++)\n\t\t{\n\t\t\tEdgeEnd *ee = (*eev)[i];\n\t\t\taddZ(ee->getCoordinate().z);\n\t\t}\n\t}\n#endif \/\/ COMPUTE_Z\n\n\tedges=newEdges;\n}\n\nNode::~Node(){\n#if DEBUG\n\tcerr<<\"[\"<<this<<\"] Node::~Node()\"<<endl;\n#endif\n\tdelete edges;\n}\n\nconst Coordinate& Node::getCoordinate() const {\n\treturn coord;\n}\n\nEdgeEndStar* Node::getEdges() {\n\treturn edges;\n}\n\nbool Node::isIsolated() {\n\treturn (label->getGeometryCount()==1);\n}\n\nvoid Node::add(EdgeEnd *e) {\n#if DEBUG\n\tcerr<<\"[\"<<this<<\"] Node::add(\"<<e->print()<<\")\"<<endl;\n#endif\n\t\/\/ Assert: start pt of e is equal to node point\n\tif (edges==NULL) edges=new EdgeEndStar();\n\tedges->insert(e);\n\te->setNode(this);\n#if COMPUTE_Z\n\taddZ(e->getCoordinate().z);\n#endif\n}\n\nvoid Node::mergeLabel(const Node* n) {\n\tmergeLabel(n->label);\n}\n\nvoid Node::mergeLabel(const Label* label2) {\n\tfor (int i=0; i<2; i++) {\n\t\tint loc=computeMergedLocation(label2, i);\n\t\tint thisLoc=label->getLocation(i);\n\t\tif (thisLoc==Location::UNDEF) label->setLocation(i,loc);\n\t}\n}\n\nvoid Node::setLabel(int argIndex, int onLocation) {\n\tif (label==NULL) {\n\t\tlabel=new Label(argIndex, onLocation);\n\t} else\n\t\tlabel->setLocation(argIndex, onLocation);\n}\n\nvoid Node::setLabelBoundary(int argIndex) {\n\tint loc=Location::UNDEF;\n\tif (label!=NULL)\n\t\tloc=label->getLocation(argIndex);\n\t\/\/ flip the loc\n\tint newLoc;\n\tswitch (loc){\n\t\tcase Location::BOUNDARY: newLoc=Location::INTERIOR; break;\n\t\tcase Location::INTERIOR: newLoc=Location::BOUNDARY; break;\n\t\tdefault: newLoc=Location::BOUNDARY; break;\n\t}\n\tlabel->setLocation(argIndex, newLoc);\n}\n\nint Node::computeMergedLocation(const Label* label2, int eltIndex){\n\tint loc=Location::UNDEF;\n\tloc=label->getLocation(eltIndex);\n\tif (!label2->isNull(eltIndex)) {\n\t\tint nLoc=label2->getLocation(eltIndex);\n\t\tif (loc!=Location::BOUNDARY) loc=nLoc;\n\t}\n\treturn loc;\n}\n\nstring Node::print(){\n\tstring out=\"node \"+coord.toString()+\" lbl: \"+label->toString();\n\treturn out;\n}\n\nvoid\nNode::addZ(double z)\n{\n#if DEBUG\n\tcerr<<\"[\"<<this<<\"] Node::addZ(\"<<z<<\")\";\n#endif\n\tif ( ISNAN(z) )\n\t{\n#if DEBUG\n\t\tcerr<<\" skipped\"<<endl;\n#endif\n\t\treturn;\n\t}\n\tfor (unsigned int i=0; i<zvals.size(); i++) if ( zvals[i] == z )\n\t{\n#if DEBUG\n\t\tcerr<<\" already stored\"<<endl;\n#endif\n\t\treturn;\n\t}\n\tzvals.push_back(z);\n\tztot+=z;\n\tcoord.z=ztot\/zvals.size();\n#if DEBUG\n\tcerr<<\" added \"<<z<<\": [\"<<ztot<<\"\/\"<<zvals.size()<<\"=\"<<coord.z<<\"]\"<<endl;\n#endif\n}\n\nconst vector<double>&\nNode::getZ() const\n{\n\treturn zvals;\n}\n\nbool\nNode::isIncidentEdgeInResult() const\n{\n\tvector<EdgeEnd*>*v = edges->getEdges();\n\tunsigned int size = v->size();\n\tfor (unsigned int i=0; i<size; i++)\n\t{\n\t\tDirectedEdge *de = (DirectedEdge *)(*v)[i];\n\t\tif ( de->isInResult() ) return true;\n\t}\n\treturn false;\n}\n\n} \/\/ namespace geos\n\n\/**********************************************************************\n * $Log$\n * Revision 1.10.2.1 2005\/06\/26 09:40:19 strk\n * Backport of OverlayOp performance improvements\n *\n * Revision 1.10 2004\/12\/08 13:54:43 strk\n * gcc warnings checked and fixed, general cleanups.\n *\n * Revision 1.9 2004\/11\/29 16:05:33 strk\n * Fixed a bug in LineIntersector::interpolateZ causing NaN values\n * to come out.\n * Handled dimensional collapses in ElevationMatrix.\n * Added ISNAN macro and changed ISNAN\/FINITE macros to avoid\n * dispendious isnan() and finite() calls.\n *\n * Revision 1.8 2004\/11\/26 09:53:48 strk\n * Added more FINITE calls, and added inf and -inf to FINITE checks\n *\n * Revision 1.7 2004\/11\/20 15:41:18 strk\n * Added management of vector of composing Z values.\n *\n * Revision 1.6 2004\/11\/19 10:10:23 strk\n * COMPUTE_Z re-enabled by default\n *\n * Revision 1.5 2004\/11\/17 15:09:08 strk\n * Changed COMPUTE_Z defaults to be more conservative\n *\n * Revision 1.4 2004\/11\/17 08:13:16 strk\n * Indentation changes.\n * Some Z_COMPUTATION activated by default.\n *\n * Revision 1.3 2004\/10\/21 22:29:54 strk\n * Indentation changes and some more COMPUTE_Z rules\n *\n * Revision 1.2 2004\/07\/02 13:28:26 strk\n * Fixed all #include lines to reflect headers layout change.\n * Added client application build tips in README.\n *\n * Revision 1.1 2004\/03\/19 09:48:45 ybychkov\n * \"geomgraph\" and \"geomgraph\/indexl\" upgraded to JTS 1.4\n *\n * Revision 1.12 2003\/11\/07 01:23:42 pramsey\n * Add standard CVS headers licence notices and copyrights to all cpp and h\n * files.\n *\n *\n **********************************************************************\/\n\n<commit_msg>improved ::isIncidentEdgeInResult() method<commit_after>\/**********************************************************************\n * $Id$\n *\n * GEOS - Geometry Engine Open Source\n * http:\/\/geos.refractions.net\n *\n * Copyright (C) 2001-2002 Vivid Solutions Inc.\n *\n * This is free software; you can redistribute and\/or modify it under\n * the terms of the GNU Lesser General Public Licence as published\n * by the Free Software Foundation. \n * See the COPYING file for more information.\n *\n **********************************************************************\/\n\n#include <geos\/geomgraph.h>\n\/\/#include \"..\/headers\/util.h\"\n\n#ifndef DEBUG\n#define DEBUG 0\n#endif\n#ifndef COMPUTE_Z\n#define COMPUTE_Z 1\n#endif\n\nnamespace geos {\n\nNode::Node(Coordinate& newCoord, EdgeEndStar* newEdges): GraphComponent(new Label(0,Location::UNDEF)) {\n\tcoord=newCoord;\n#if DEBUG\n\tcerr<<\"[\"<<this<<\"] Node::Node(\"<<newCoord.toString()<<\")\"<<endl;\n#endif\n\n#if COMPUTE_Z\n\tztot = 0;\n\taddZ(newCoord.z);\n\tif ( newEdges )\n\t{\n\t\tvector<EdgeEnd*>*eev = newEdges->getEdges();\n\t\tfor (unsigned int i=0; i<eev->size(); i++)\n\t\t{\n\t\t\tEdgeEnd *ee = (*eev)[i];\n\t\t\taddZ(ee->getCoordinate().z);\n\t\t}\n\t}\n#endif \/\/ COMPUTE_Z\n\n\tedges=newEdges;\n}\n\nNode::~Node(){\n#if DEBUG\n\tcerr<<\"[\"<<this<<\"] Node::~Node()\"<<endl;\n#endif\n\tdelete edges;\n}\n\nconst Coordinate& Node::getCoordinate() const {\n\treturn coord;\n}\n\nEdgeEndStar* Node::getEdges() {\n\treturn edges;\n}\n\nbool Node::isIsolated() {\n\treturn (label->getGeometryCount()==1);\n}\n\nvoid Node::add(EdgeEnd *e) {\n#if DEBUG\n\tcerr<<\"[\"<<this<<\"] Node::add(\"<<e->print()<<\")\"<<endl;\n#endif\n\t\/\/ Assert: start pt of e is equal to node point\n\tif (edges==NULL) edges=new EdgeEndStar();\n\tedges->insert(e);\n\te->setNode(this);\n#if COMPUTE_Z\n\taddZ(e->getCoordinate().z);\n#endif\n}\n\nvoid Node::mergeLabel(const Node* n) {\n\tmergeLabel(n->label);\n}\n\nvoid Node::mergeLabel(const Label* label2) {\n\tfor (int i=0; i<2; i++) {\n\t\tint loc=computeMergedLocation(label2, i);\n\t\tint thisLoc=label->getLocation(i);\n\t\tif (thisLoc==Location::UNDEF) label->setLocation(i,loc);\n\t}\n}\n\nvoid Node::setLabel(int argIndex, int onLocation) {\n\tif (label==NULL) {\n\t\tlabel=new Label(argIndex, onLocation);\n\t} else\n\t\tlabel->setLocation(argIndex, onLocation);\n}\n\nvoid Node::setLabelBoundary(int argIndex) {\n\tint loc=Location::UNDEF;\n\tif (label!=NULL)\n\t\tloc=label->getLocation(argIndex);\n\t\/\/ flip the loc\n\tint newLoc;\n\tswitch (loc){\n\t\tcase Location::BOUNDARY: newLoc=Location::INTERIOR; break;\n\t\tcase Location::INTERIOR: newLoc=Location::BOUNDARY; break;\n\t\tdefault: newLoc=Location::BOUNDARY; break;\n\t}\n\tlabel->setLocation(argIndex, newLoc);\n}\n\nint Node::computeMergedLocation(const Label* label2, int eltIndex){\n\tint loc=Location::UNDEF;\n\tloc=label->getLocation(eltIndex);\n\tif (!label2->isNull(eltIndex)) {\n\t\tint nLoc=label2->getLocation(eltIndex);\n\t\tif (loc!=Location::BOUNDARY) loc=nLoc;\n\t}\n\treturn loc;\n}\n\nstring Node::print(){\n\tstring out=\"node \"+coord.toString()+\" lbl: \"+label->toString();\n\treturn out;\n}\n\nvoid\nNode::addZ(double z)\n{\n#if DEBUG\n\tcerr<<\"[\"<<this<<\"] Node::addZ(\"<<z<<\")\";\n#endif\n\tif ( ISNAN(z) )\n\t{\n#if DEBUG\n\t\tcerr<<\" skipped\"<<endl;\n#endif\n\t\treturn;\n\t}\n\tfor (unsigned int i=0; i<zvals.size(); i++) if ( zvals[i] == z )\n\t{\n#if DEBUG\n\t\tcerr<<\" already stored\"<<endl;\n#endif\n\t\treturn;\n\t}\n\tzvals.push_back(z);\n\tztot+=z;\n\tcoord.z=ztot\/zvals.size();\n#if DEBUG\n\tcerr<<\" added \"<<z<<\": [\"<<ztot<<\"\/\"<<zvals.size()<<\"=\"<<coord.z<<\"]\"<<endl;\n#endif\n}\n\nconst vector<double>&\nNode::getZ() const\n{\n\treturn zvals;\n}\n\nbool\nNode::isIncidentEdgeInResult() const\n{\n\tvector<EdgeEnd*>*v = edges->getEdges();\n\tunsigned int size = v->size();\n\tfor (unsigned int i=0; i<size; i++)\n\t{\n\t\tDirectedEdge *de = (DirectedEdge *)(*v)[i];\n\t\tif ( de->getEdge()->isInResult() ) return true;\n\t}\n\treturn false;\n}\n\n} \/\/ namespace geos\n\n\/**********************************************************************\n * $Log$\n * Revision 1.10.2.2 2005\/06\/28 00:05:50 strk\n * improved ::isIncidentEdgeInResult() method\n *\n * Revision 1.10.2.1 2005\/06\/26 09:40:19 strk\n * Backport of OverlayOp performance improvements\n *\n * Revision 1.10 2004\/12\/08 13:54:43 strk\n * gcc warnings checked and fixed, general cleanups.\n *\n * Revision 1.9 2004\/11\/29 16:05:33 strk\n * Fixed a bug in LineIntersector::interpolateZ causing NaN values\n * to come out.\n * Handled dimensional collapses in ElevationMatrix.\n * Added ISNAN macro and changed ISNAN\/FINITE macros to avoid\n * dispendious isnan() and finite() calls.\n *\n * Revision 1.8 2004\/11\/26 09:53:48 strk\n * Added more FINITE calls, and added inf and -inf to FINITE checks\n *\n * Revision 1.7 2004\/11\/20 15:41:18 strk\n * Added management of vector of composing Z values.\n *\n * Revision 1.6 2004\/11\/19 10:10:23 strk\n * COMPUTE_Z re-enabled by default\n *\n * Revision 1.5 2004\/11\/17 15:09:08 strk\n * Changed COMPUTE_Z defaults to be more conservative\n *\n * Revision 1.4 2004\/11\/17 08:13:16 strk\n * Indentation changes.\n * Some Z_COMPUTATION activated by default.\n *\n * Revision 1.3 2004\/10\/21 22:29:54 strk\n * Indentation changes and some more COMPUTE_Z rules\n *\n * Revision 1.2 2004\/07\/02 13:28:26 strk\n * Fixed all #include lines to reflect headers layout change.\n * Added client application build tips in README.\n *\n * Revision 1.1 2004\/03\/19 09:48:45 ybychkov\n * \"geomgraph\" and \"geomgraph\/indexl\" upgraded to JTS 1.4\n *\n * Revision 1.12 2003\/11\/07 01:23:42 pramsey\n * Add standard CVS headers licence notices and copyrights to all cpp and h\n * files.\n *\n *\n **********************************************************************\/\n\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n#include <string>\n#include <vector>\n#include <cstdio>\n#include <cstdlib>\n#include <cstring>\nusing namespace std;\n\n\/*\n * 最长公共子列\n *\n * 问题描述:\n * 给定两个子列,找到他们的最长公共子列的长度,子列只要求保持相对位置不变\n * 例如:acf 是 abcdefg的一个子列\n *\/\n\n\/*\n * 问题解决思路:\n * 考虑两个序列 X[0...m-1] 和 Y[0...n-1]的最后一个字母是否被LCS匹配到?\n * 如果被匹配到(X[m-1] == Y[n-1]) 则\n * LCS(x[0...m-1], Y[0...n-1]) = 1 + LCS(x[0...m-2], Y[0...n-2]);\n * 如果没有被匹配到(X[m-1] != Y[n-1]) 则\n * LCS(x[0...m-1], Y[0...n-1] = max{LCS(X[0...m-1], Y[0...n-2]), LCS(X[0...m-2],Y[0...n-1])}\n *\n * 初始条件:如果其中一个子列长度为0,则LCS=0;\n *\/\n\n\/* 定义L[i][j]表示X[0...i-1] 和 Y[0...j-1]的LCS\n *\n * 则 L[0][j] = 0 for all j\n * L[i][0] = 0 for all i\n * LCS(X, Y) = L[m][n]\n *\n * 注意:L[i][j]表示的长度为i的X和长度为j的Y的LCS\n * 因此维度要比以前的数组各加1,注意边界情况\n *\/\n\nint LCS(char* X, char* Y, int m, int n)\n{\n\tint L[m + 1][n + 1];\n\t\/\/vector<vector<int> > L(m + 1, vector<int>(n + 1));\n\n\t\/\/ init\n\tfor (int j = 0; j <= n; ++j) L[0][j] = 0;\n\tfor (int i = 0; i <= m; ++i) L[i][0] = 0;\n\n\t\/\/ DP by bottom to up \n\tfor (int i = 1; i <= n; ++i)\n\t{\n\t\tfor (int j = 1; j <= n; ++j)\n\t\t{\n\t\t\tif (X[i-1] == Y[j-1])\n\t\t\t{\n\t\t\t\tL[i][j] = 1 + L[i-1][j-1];\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tL[i][j] = max(L[i-1][j], L[i][j-1]);\n\t\t\t}\n\t\t}\n\t}\n\t\n\t\/\/ print the LCS;\n\tint ii = m; int jj = n;\n\tint index = L[m][n];\n\t\n\tchar lcs[index+1]; lcs[index] = '\\0';\n\twhile(ii > 0 && jj > 0)\n\t{\n\t\tif (X[ii-1] == Y[jj-1])\n\t\t{\n\t\t\tlcs[index-1] = X[ii-1];\n\t\t\tii--;\n\t\t\tjj--;\n\t\t\tindex--;\n\t\t}\n\t\telse if (L[ii-1][jj] > L[ii][jj-1])\n\t\t{\n\t\t\tii--;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tjj--;\n\t\t}\n\t}\n\n\tcout << \"The LCS is: \" << lcs << endl;\n\n\t\/*\n\t\/\/ print table\n\tfor (int i = 0; i <= m; ++i)\n\t{\n\t\tfor (int j = 0; j <= n; ++j)\n\t\t{\n\t\t\tcout <<\" \" << L[i][j];\n\t\t}\n\t\tcout << endl;\n\t}\n\t*\/\n\n\treturn L[m][n];\n}\n\/* 复杂度分析:\n * 时间复杂度:O(mn)\n * 空间复杂度:O(mn)\n *\/\n\nint main()\n{\n\tchar X[] = \"AGGTAB\";\n\tchar Y[] = \"GXTXAYB\";\n\n\tint m = strlen(X);\n\tint n = strlen(Y);\n\tint ans = LCS(X, Y, m, n);\n\t\n\tcout << \"The Length of LCS is : \" << ans << endl;\n\treturn 0;\n}\n<commit_msg>fix index bug<commit_after>#include <iostream>\n#include <string>\n#include <vector>\n#include <cstdio>\n#include <cstdlib>\n#include <cstring>\nusing namespace std;\n\n\/*\n * 最长公共子列\n *\n * 问题描述:\n * 给定两个子列,找到他们的最长公共子列的长度,子列只要求保持相对位置不变\n * 例如:acf 是 abcdefg的一个子列\n *\/\n\n\/*\n * 问题解决思路:\n * 考虑两个序列 X[0...m-1] 和 Y[0...n-1]的最后一个字母是否被LCS匹配到?\n * 如果被匹配到(X[m-1] == Y[n-1]) 则\n * LCS(x[0...m-1], Y[0...n-1]) = 1 + LCS(x[0...m-2], Y[0...n-2]);\n * 如果没有被匹配到(X[m-1] != Y[n-1]) 则\n * LCS(x[0...m-1], Y[0...n-1] = max{LCS(X[0...m-1], Y[0...n-2]), LCS(X[0...m-2],Y[0...n-1])}\n *\n * 初始条件:如果其中一个子列长度为0,则LCS=0;\n *\/\n\n\/* 定义L[i][j]表示X[0...i-1] 和 Y[0...j-1]的LCS\n *\n * 则 L[0][j] = 0 for all j\n * L[i][0] = 0 for all i\n * LCS(X, Y) = L[m][n]\n *\n * 注意:L[i][j]表示的长度为i的X和长度为j的Y的LCS\n * 因此维度要比以前的数组各加1,注意边界情况\n *\/\n\nint LCS(char* X, char* Y, int m, int n)\n{\n\tint L[m + 1][n + 1];\n\t\/\/vector<vector<int> > L(m + 1, vector<int>(n + 1));\n\n\t\/\/ init\n\tfor (int j = 0; j <= n; ++j) L[0][j] = 0;\n\tfor (int i = 0; i <= m; ++i) L[i][0] = 0;\n\n\t\/\/ DP by bottom to up \n\tfor (int i = 1; i <= m; ++i)\n\t{\n\t\tfor (int j = 1; j <= n; ++j)\n\t\t{\n\t\t\tif (X[i-1] == Y[j-1])\n\t\t\t{\n\t\t\t\tL[i][j] = 1 + L[i-1][j-1];\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tL[i][j] = max(L[i-1][j], L[i][j-1]);\n\t\t\t}\n\t\t}\n\t}\n\t\n\t\/\/ print the LCS;\n\tint ii = m; int jj = n;\n\tint index = L[m][n];\n\t\n\tchar lcs[index+1]; lcs[index] = '\\0';\n\twhile(ii > 0 && jj > 0)\n\t{\n\t\tif (X[ii-1] == Y[jj-1])\n\t\t{\n\t\t\tlcs[index-1] = X[ii-1];\n\t\t\tii--;\n\t\t\tjj--;\n\t\t\tindex--;\n\t\t}\n\t\telse if (L[ii-1][jj] > L[ii][jj-1])\n\t\t{\n\t\t\tii--;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tjj--;\n\t\t}\n\t}\n\n\tcout << \"The LCS is: \" << lcs << endl;\n\n\t\/*\n\t\/\/ print table\n\tfor (int i = 0; i <= m; ++i)\n\t{\n\t\tfor (int j = 0; j <= n; ++j)\n\t\t{\n\t\t\tcout <<\" \" << L[i][j];\n\t\t}\n\t\tcout << endl;\n\t}\n\t*\/\n\n\treturn L[m][n];\n}\n\/* 复杂度分析:\n * 时间复杂度:O(mn)\n * 空间复杂度:O(mn)\n *\/\n\nint main()\n{\n\tchar X[] = \"AGGTAB\";\n\tchar Y[] = \"GXTXAYB\";\n\n\tint m = strlen(X);\n\tint n = strlen(Y);\n\tint ans = LCS(X, Y, m, n);\n\t\n\tcout << \"The Length of LCS is : \" << ans << endl;\n\treturn 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: spritecanvas.hxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: rt $ $Date: 2004-09-08 16:58:33 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef _CPPCANVAS_SPRITECANVAS_HXX\n#define _CPPCANVAS_SPRITECANVAS_HXX\n\n#ifndef _SAL_TYPES_H_\n#include <sal\/types.h>\n#endif\n\n#ifndef _BGFX_VECTOR_B2DSIZE_HXX\n#include <basegfx\/vector\/b2dsize.hxx>\n#endif\n\n#ifndef BOOST_SHARED_PTR_HPP_INCLUDED\n#include <boost\/shared_ptr.hpp>\n#endif\n\n\n#ifndef _CPPCANVAS_BITMAPCANVAS_HXX\n#include <cppcanvas\/bitmapcanvas.hxx>\n#endif\n#ifndef _CPPCANVAS_SPRITE_HXX\n#include <cppcanvas\/sprite.hxx>\n#endif\n#ifndef _CPPCANVAS_CUSTOMSPRITE_HXX\n#include <cppcanvas\/customsprite.hxx>\n#endif\n\nnamespace drafts { namespace com { namespace sun { namespace star { namespace rendering\n{\n class XSpriteCanvas;\n} } } } }\n\n\n\/* Definition of SpriteCanvas *\/\n\nnamespace cppcanvas\n{\n class SpriteCanvas;\n\n \/\/ forward declaration, since cloneSpriteCanvas() also references SpriteCanvas\n typedef ::boost::shared_ptr< ::cppcanvas::SpriteCanvas > SpriteCanvasSharedPtr;\n\n \/** SpriteCanvas interface\n *\/\n class SpriteCanvas : public virtual BitmapCanvas\n {\n public:\n virtual bool updateScreen() const = 0;\n\n virtual CustomSpriteSharedPtr createCustomSprite( const ::basegfx::B2DSize& ) const = 0;\n virtual SpriteSharedPtr createClonedSprite( const SpriteSharedPtr& ) const = 0;\n\n virtual SpriteCanvasSharedPtr cloneSpriteCanvas() const = 0; \/\/ shared_ptr does not allow for covariant return types\n\n virtual ::com::sun::star::uno::Reference<\n ::drafts::com::sun::star::rendering::XSpriteCanvas > getUNOSpriteCanvas() const = 0;\n };\n\n}\n\n#endif \/* _CPPCANVAS_SPRITECANVAS_HXX *\/\n<commit_msg>INTEGRATION: CWS presentationengine01 (1.2.2); FILE MERGED 2004\/08\/27 18:49:14 thb 1.2.2.6: #110496# Adapted to recent canvas API changes (XSpriteCanvas::updateScreen) 2004\/08\/19 17:21:08 thb 1.2.2.5: #110496# Switched from deprecated to recommended shared_ptr dynamic cast method 2004\/07\/20 19:08:43 thb 1.2.2.4: #110496# Unified include statements; removed external prefix from boost includes 2004\/06\/25 14:01:07 thb 1.2.2.3: #100000# Old boost does not have operator bool on shared_ptr 2004\/06\/25 10:30:18 thb 1.2.2.2: #110496# Some header cleanups (missing forward declarations), changed Canvas and derived to emulate covariant return types on clone() (not directly possible with shared_ptr) 2004\/04\/05 15:58:44 thb 1.2.2.1: Resync with canvas01 changes<commit_after>\/*************************************************************************\n *\n * $RCSfile: spritecanvas.hxx,v $\n *\n * $Revision: 1.4 $\n *\n * last change: $Author: rt $ $Date: 2004-11-26 20:52:28 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef _CPPCANVAS_SPRITECANVAS_HXX\n#define _CPPCANVAS_SPRITECANVAS_HXX\n\n#ifndef _SAL_TYPES_H_\n#include <sal\/types.h>\n#endif\n#ifndef _OSL_DIAGNOSE_H_\n#include <osl\/diagnose.h>\n#endif\n\n#ifndef _BGFX_VECTOR_B2DSIZE_HXX\n#include <basegfx\/vector\/b2dsize.hxx>\n#endif\n\n#ifndef BOOST_SHARED_PTR_HPP_INCLUDED\n#include <boost\/shared_ptr.hpp>\n#endif\n\n\n#ifndef _CPPCANVAS_BITMAPCANVAS_HXX\n#include <cppcanvas\/bitmapcanvas.hxx>\n#endif\n#ifndef _CPPCANVAS_SPRITE_HXX\n#include <cppcanvas\/sprite.hxx>\n#endif\n#ifndef _CPPCANVAS_CUSTOMSPRITE_HXX\n#include <cppcanvas\/customsprite.hxx>\n#endif\n\nnamespace drafts { namespace com { namespace sun { namespace star { namespace rendering\n{\n class XSpriteCanvas;\n} } } } }\n\n\n\/* Definition of SpriteCanvas *\/\n\nnamespace cppcanvas\n{\n class SpriteCanvas;\n\n \/\/ forward declaration, since cloneSpriteCanvas() also references SpriteCanvas\n typedef ::boost::shared_ptr< ::cppcanvas::SpriteCanvas > SpriteCanvasSharedPtr;\n\n \/** SpriteCanvas interface\n *\/\n class SpriteCanvas : public virtual BitmapCanvas\n {\n public:\n virtual bool updateScreen( bool bUpdateAll ) const = 0;\n\n virtual CustomSpriteSharedPtr createCustomSprite( const ::basegfx::B2DSize& ) const = 0;\n virtual SpriteSharedPtr createClonedSprite( const SpriteSharedPtr& ) const = 0;\n\n \/\/ shared_ptr does not allow for covariant return types\n SpriteCanvasSharedPtr cloneSpriteCanvas() const\n {\n SpriteCanvasSharedPtr p( ::boost::dynamic_pointer_cast< SpriteCanvas >(this->clone()) );\n OSL_ENSURE(p.get(), \"SpriteCanvas::cloneSpriteCanvas(): dynamic cast failed\");\n return p;\n }\n\n virtual ::com::sun::star::uno::Reference<\n ::drafts::com::sun::star::rendering::XSpriteCanvas > getUNOSpriteCanvas() const = 0;\n };\n\n}\n\n#endif \/* _CPPCANVAS_SPRITECANVAS_HXX *\/\n<|endoftext|>"} {"text":"<commit_before>\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\n#include <cassert>\n#include <vector>\n#include <set>\n\n#include \"llvm\/IR\/DataLayout.h\"\n#include \"llvm\/IR\/BasicBlock.h\"\n#include \"llvm\/IR\/Constants.h\"\n#include \"llvm\/IR\/Function.h\"\n#include \"llvm\/IR\/GlobalVariable.h\"\n#include \"llvm\/IR\/Instructions.h\"\n#include \"llvm\/IR\/Module.h\"\n#include \"llvm\/Pass.h\"\n#include \"llvm\/IR\/Type.h\"\n#include \"llvm\/IR\/TypeBuilder.h\"\n#if LLVM_VERSION_MAJOR >= 4 || (LLVM_VERSION_MAJOR == 3 && LLVM_VERSION_MINOR >= 5)\n #include \"llvm\/IR\/InstIterator.h\"\n#else\n #include \"llvm\/Support\/InstIterator.h\"\n#endif\n#include \"llvm\/Support\/raw_ostream.h\"\n#include \"llvm\/Transforms\/Utils\/BasicBlockUtils.h\"\n#include <llvm\/IR\/DebugInfoMetadata.h>\n\nusing namespace llvm;\n\nnamespace {\n\nclass MarkVolatile : public FunctionPass {\n public:\n static char ID;\n\n MarkVolatile() : FunctionPass(ID) {}\n\n virtual bool runOnFunction(Function &F);\n};\n\nbool MarkVolatile::runOnFunction(Function &F)\n{\n bool modified = false;\n\n for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I) {\n Instruction *ins = &*I;\n if (CallInst *CI = dyn_cast<CallInst>(ins)) {\n if (CI->isInlineAsm())\n continue;\n\n const Value *val = CI->getCalledValue()->stripPointerCasts();\n const Function *callee = dyn_cast<Function>(val);\n if (!callee || callee->isIntrinsic())\n continue;\n\n assert(callee->hasName());\n StringRef name = callee->getName();\n\n if (!name.startswith(\"__INSTR_mark_pointer\"))\n continue;\n\n \/\/ we found a marked instruction, make it volatile\n \/\/ if it is store or load\n auto nextIt = I;\n ++nextIt;\n if (StoreInst *SI = dyn_cast<StoreInst>(&*nextIt)) {\n SI->setVolatile(true);\n modified = true;\n } else if (LoadInst *LI = dyn_cast<LoadInst>(&*nextIt)) {\n LI->setVolatile(true);\n modified = true;\n } else {\n errs() << \"[Warning]: this marked instruction was not made volatile:\\n\";\n errs() << *nextIt << \"\\n\";\n }\n }\n }\n return modified;\n}\n\n} \/\/ namespace\n\nstatic RegisterPass<MarkVolatile> MVLTL(\"mark-volatile\",\n \"Make marked instructions as volatile\");\nchar MarkVolatile::ID;\n\n<commit_msg>MarkVolatile: mark also memintrinsic functions as volatile<commit_after>\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\n#include <cassert>\n#include <vector>\n#include <set>\n\n#include \"llvm\/IR\/DataLayout.h\"\n#include \"llvm\/IR\/BasicBlock.h\"\n#include \"llvm\/IR\/Constants.h\"\n#include \"llvm\/IR\/Function.h\"\n#include \"llvm\/IR\/GlobalVariable.h\"\n#include \"llvm\/IR\/Instructions.h\"\n#include \"llvm\/IR\/IntrinsicInst.h\"\n#include \"llvm\/IR\/Module.h\"\n#include \"llvm\/Pass.h\"\n#include \"llvm\/IR\/Type.h\"\n#include \"llvm\/IR\/TypeBuilder.h\"\n#if LLVM_VERSION_MAJOR >= 4 || (LLVM_VERSION_MAJOR == 3 && LLVM_VERSION_MINOR >= 5)\n #include \"llvm\/IR\/InstIterator.h\"\n#else\n #include \"llvm\/Support\/InstIterator.h\"\n#endif\n#include \"llvm\/Support\/raw_ostream.h\"\n#include \"llvm\/Transforms\/Utils\/BasicBlockUtils.h\"\n#include <llvm\/IR\/DebugInfoMetadata.h>\n\nusing namespace llvm;\n\nnamespace {\n\nclass MarkVolatile : public FunctionPass {\n public:\n static char ID;\n\n MarkVolatile() : FunctionPass(ID) {}\n\n virtual bool runOnFunction(Function &F);\n};\n\nbool MarkVolatile::runOnFunction(Function &F)\n{\n bool modified = false;\n LLVMContext& ctx = F.getParent()->getContext();\n\n for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I) {\n Instruction *ins = &*I;\n if (CallInst *CI = dyn_cast<CallInst>(ins)) {\n if (CI->isInlineAsm())\n continue;\n\n const Value *val = CI->getCalledValue()->stripPointerCasts();\n const Function *callee = dyn_cast<Function>(val);\n if (!callee || callee->isIntrinsic())\n continue;\n\n assert(callee->hasName());\n StringRef name = callee->getName();\n\n if (!name.startswith(\"__INSTR_mark_pointer\"))\n continue;\n\n \/\/ we found a marked instruction, make it volatile\n \/\/ if it is store or load\n auto nextIt = I;\n ++nextIt;\n if (StoreInst *SI = dyn_cast<StoreInst>(&*nextIt)) {\n SI->setVolatile(true);\n modified = true;\n } else if (LoadInst *LI = dyn_cast<LoadInst>(&*nextIt)) {\n LI->setVolatile(true);\n modified = true;\n } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(&*nextIt)) {\n MI->setVolatile(ConstantInt::getTrue(ctx));\n modified = true;\n } else {\n errs() << \"[Warning]: this marked instruction was not made volatile:\\n\";\n errs() << *nextIt << \"\\n\";\n }\n }\n }\n return modified;\n}\n\n} \/\/ namespace\n\nstatic RegisterPass<MarkVolatile> MVLTL(\"mark-volatile\",\n \"Make marked instructions as volatile\");\nchar MarkVolatile::ID;\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n * SPDX-FileCopyrightText: 2017-2017 CSSlayer <wengxt@gmail.com>\n *\n * SPDX-License-Identifier: LGPL-2.1-or-later\n *\n *\/\n#include \"ime.h\"\n#include \"config.h\"\n#include <boost\/iostreams\/device\/file_descriptor.hpp>\n#include <boost\/iostreams\/stream_buffer.hpp>\n#include <boost\/range\/adaptor\/reversed.hpp>\n#include <fcitx-config\/iniparser.h>\n#include <fcitx-utils\/log.h>\n#include <fcitx-utils\/standardpath.h>\n#include <fcntl.h>\n#include <libime\/core\/utils.h>\n#include <libime\/table\/tablebaseddictionary.h>\n#include <libime\/table\/tableoptions.h>\n\nnamespace fcitx {\n\nFCITX_DEFINE_LOG_CATEGORY(table_logcategory, \"table\")\n\nnamespace {\n\nlibime::OrderPolicy converOrderPolicy(fcitx::OrderPolicy policy) {\n switch (policy) {\n#define POLICY_CONVERT(NAME) \\\n case fcitx::OrderPolicy::NAME: \\\n return libime::OrderPolicy::NAME;\n POLICY_CONVERT(No)\n POLICY_CONVERT(Freq)\n POLICY_CONVERT(Fast)\n }\n return libime::OrderPolicy::Freq;\n}\n\nvoid populateOptions(libime::TableBasedDictionary *dict,\n const TableConfigRoot &root) {\n libime::TableOptions options;\n\n options.setOrderPolicy(converOrderPolicy(*root.config->orderPolicy));\n options.setNoSortInputLength(*root.config->noSortInputLength);\n options.setAutoSelect(*root.config->autoSelect);\n options.setAutoSelectLength(*root.config->autoSelectLength);\n options.setNoMatchAutoSelectLength(*root.config->noMatchAutoSelectLength);\n options.setCommitRawInput(*root.config->commitRawInput);\n options.setMatchingKey(\n Key::keySymToUnicode(root.config->matchingKey->sym()));\n std::set<uint32_t> endKeys;\n TABLE_DEBUG() << \"End key\" << *root.config->endKey;\n for (const auto &key : *root.config->endKey) {\n auto chr = Key::keySymToUnicode(key.sym());\n if (chr) {\n endKeys.insert(chr);\n }\n }\n options.setEndKey(endKeys);\n options.setExactMatch(*root.config->exactMatch);\n options.setLearning(*root.config->learning);\n options.setAutoPhraseLength(*root.config->autoPhraseLength);\n options.setSaveAutoPhraseAfter(*root.config->saveAutoPhraseAfter);\n options.setAutoRuleSet(std::unordered_set<std::string>(\n root.config->autoRuleSet->begin(), root.config->autoRuleSet->end()));\n options.setLanguageCode(*root.im->languageCode);\n\n dict->setTableOptions(options);\n}\n} \/\/ namespace\n\nTableIME::TableIME(libime::LanguageModelResolver *lm) : lm_(lm) {}\n\nstd::tuple<libime::TableBasedDictionary *, libime::UserLanguageModel *,\n const TableConfig *>\nTableIME::requestDict(const std::string &name) {\n auto iter = tables_.find(name);\n if (iter == tables_.end()) {\n TABLE_DEBUG() << \"Load table config for: \" << name;\n std::string filename = \"inputmethod\/\";\n filename.append(name.begin(), name.end());\n filename += \".conf\";\n auto files = StandardPath::global().openAll(StandardPath::Type::PkgData,\n filename, O_RDONLY);\n RawConfig rawConfig;\n \/\/ reverse the order, so we end up parse user file at last.\n for (const auto &file : files | boost::adaptors::reversed) {\n readFromIni(rawConfig, file.fd());\n }\n\n iter = tables_\n .emplace(std::piecewise_construct, std::make_tuple(name),\n std::make_tuple())\n .first;\n auto &root = iter->second.root;\n root.load(rawConfig);\n\n try {\n auto dict = std::make_unique<libime::TableBasedDictionary>();\n auto dictFile = StandardPath::global().open(\n StandardPath::Type::PkgData, *root.config->file, O_RDONLY);\n TABLE_DEBUG() << \"Load table at: \" << *root.config->file;\n if (dictFile.fd() < 0) {\n throw std::runtime_error(\"Couldn't open file\");\n }\n boost::iostreams::stream_buffer<\n boost::iostreams::file_descriptor_source>\n buffer(dictFile.fd(), boost::iostreams::file_descriptor_flags::\n never_close_handle);\n std::istream in(&buffer);\n dict->load(in);\n iter->second.dict = std::move(dict);\n } catch (const std::exception &) {\n }\n\n if (auto dict = iter->second.dict.get()) {\n try {\n auto dictFile = StandardPath::global().openUser(\n StandardPath::Type::PkgData,\n stringutils::concat(\"table\/\", name, \".user.dict\"),\n O_RDONLY);\n boost::iostreams::stream_buffer<\n boost::iostreams::file_descriptor_source>\n buffer(dictFile.fd(),\n boost::iostreams::file_descriptor_flags::\n never_close_handle);\n std::istream in(&buffer);\n dict->loadUser(in);\n } catch (const std::exception &e) {\n TABLE_DEBUG() << e.what();\n }\n\n populateOptions(dict, iter->second.root);\n std::shared_ptr<const libime::StaticLanguageModelFile> lmFile;\n try {\n lmFile = lm_->languageModelFileForLanguage(\n dict->tableOptions().languageCode());\n } catch (...) {\n TABLE_DEBUG()\n << \"Load language model for \"\n << dict->tableOptions().languageCode() << \" failed.\";\n }\n iter->second.model =\n std::make_unique<libime::UserLanguageModel>(lmFile);\n\n try {\n auto dictFile = StandardPath::global().openUser(\n StandardPath::Type::PkgData,\n stringutils::concat(\"table\/\", name, \".history\"), O_RDONLY);\n boost::iostreams::stream_buffer<\n boost::iostreams::file_descriptor_source>\n buffer(dictFile.fd(),\n boost::iostreams::file_descriptor_flags::\n never_close_handle);\n std::istream in(&buffer);\n iter->second.model->load(in);\n } catch (const std::exception &e) {\n TABLE_DEBUG() << e.what();\n }\n }\n }\n\n return {iter->second.dict.get(), iter->second.model.get(),\n &(*iter->second.root.config)};\n}\n\nvoid TableIME::saveAll() {\n for (const auto &p : tables_) {\n saveDict(p.first);\n }\n}\n\nvoid TableIME::updateConfig(const std::string &name, const RawConfig &config) {\n auto iter = tables_.find(name);\n if (iter == tables_.end()) {\n return;\n }\n iter->second.root.config.mutableValue()->load(config, true);\n\n if (iter->second.dict) {\n populateOptions(iter->second.dict.get(), iter->second.root);\n }\n safeSaveAsIni(iter->second.root, StandardPath::Type::PkgData,\n stringutils::concat(\"inputmethod\/\", name, \".conf\"));\n}\n\nvoid TableIME::releaseUnusedDict(const std::unordered_set<std::string> &names) {\n for (auto iter = tables_.begin(); iter != tables_.end();) {\n if (names.count(iter->first) == 0) {\n TABLE_DEBUG() << \"Release unused table: \" << iter->first;\n saveDict(iter->first);\n iter = tables_.erase(iter);\n } else {\n ++iter;\n }\n }\n}\n\nvoid TableIME::saveDict(const std::string &name) {\n auto iter = tables_.find(name);\n if (iter == tables_.end()) {\n return;\n }\n libime::TableBasedDictionary *dict = iter->second.dict.get();\n libime::UserLanguageModel *lm = iter->second.model.get();\n if (!dict || !lm || !*iter->second.root.config->learning) {\n return;\n }\n auto fileName = stringutils::joinPath(\"table\", name);\n\n StandardPath::global().safeSave(\n StandardPath::Type::PkgData, fileName + \".user.dict\", [dict](int fd) {\n boost::iostreams::stream_buffer<\n boost::iostreams::file_descriptor_sink>\n buffer(fd, boost::iostreams::file_descriptor_flags::\n never_close_handle);\n std::ostream out(&buffer);\n try {\n dict->saveUser(out);\n return static_cast<bool>(out);\n } catch (const std::exception &) {\n return false;\n }\n });\n\n StandardPath::global().safeSave(\n StandardPath::Type::PkgData, fileName + \".history\", [lm](int fd) {\n boost::iostreams::stream_buffer<\n boost::iostreams::file_descriptor_sink>\n buffer(fd, boost::iostreams::file_descriptor_flags::\n never_close_handle);\n std::ostream out(&buffer);\n try {\n lm->save(out);\n return static_cast<bool>(out);\n } catch (const std::exception &) {\n return false;\n }\n });\n}\n} \/\/ namespace fcitx\n<commit_msg>Make sure when we save im config, we don't override other part of it.<commit_after>\/*\n * SPDX-FileCopyrightText: 2017-2017 CSSlayer <wengxt@gmail.com>\n *\n * SPDX-License-Identifier: LGPL-2.1-or-later\n *\n *\/\n#include \"ime.h\"\n#include \"config.h\"\n#include <boost\/iostreams\/device\/file_descriptor.hpp>\n#include <boost\/iostreams\/stream_buffer.hpp>\n#include <boost\/range\/adaptor\/reversed.hpp>\n#include <fcitx-config\/iniparser.h>\n#include <fcitx-utils\/log.h>\n#include <fcitx-utils\/standardpath.h>\n#include <fcntl.h>\n#include <libime\/core\/utils.h>\n#include <libime\/table\/tablebaseddictionary.h>\n#include <libime\/table\/tableoptions.h>\n\nnamespace fcitx {\n\nFCITX_DEFINE_LOG_CATEGORY(table_logcategory, \"table\")\n\nnamespace {\n\nlibime::OrderPolicy converOrderPolicy(fcitx::OrderPolicy policy) {\n switch (policy) {\n#define POLICY_CONVERT(NAME) \\\n case fcitx::OrderPolicy::NAME: \\\n return libime::OrderPolicy::NAME;\n POLICY_CONVERT(No)\n POLICY_CONVERT(Freq)\n POLICY_CONVERT(Fast)\n }\n return libime::OrderPolicy::Freq;\n}\n\nvoid populateOptions(libime::TableBasedDictionary *dict,\n const TableConfigRoot &root) {\n libime::TableOptions options;\n\n options.setOrderPolicy(converOrderPolicy(*root.config->orderPolicy));\n options.setNoSortInputLength(*root.config->noSortInputLength);\n options.setAutoSelect(*root.config->autoSelect);\n options.setAutoSelectLength(*root.config->autoSelectLength);\n options.setNoMatchAutoSelectLength(*root.config->noMatchAutoSelectLength);\n options.setCommitRawInput(*root.config->commitRawInput);\n options.setMatchingKey(\n Key::keySymToUnicode(root.config->matchingKey->sym()));\n std::set<uint32_t> endKeys;\n TABLE_DEBUG() << \"End key\" << *root.config->endKey;\n for (const auto &key : *root.config->endKey) {\n auto chr = Key::keySymToUnicode(key.sym());\n if (chr) {\n endKeys.insert(chr);\n }\n }\n options.setEndKey(endKeys);\n options.setExactMatch(*root.config->exactMatch);\n options.setLearning(*root.config->learning);\n options.setAutoPhraseLength(*root.config->autoPhraseLength);\n options.setSaveAutoPhraseAfter(*root.config->saveAutoPhraseAfter);\n options.setAutoRuleSet(std::unordered_set<std::string>(\n root.config->autoRuleSet->begin(), root.config->autoRuleSet->end()));\n options.setLanguageCode(*root.im->languageCode);\n\n dict->setTableOptions(options);\n}\n} \/\/ namespace\n\nTableIME::TableIME(libime::LanguageModelResolver *lm) : lm_(lm) {}\n\nstd::tuple<libime::TableBasedDictionary *, libime::UserLanguageModel *,\n const TableConfig *>\nTableIME::requestDict(const std::string &name) {\n auto iter = tables_.find(name);\n if (iter == tables_.end()) {\n TABLE_DEBUG() << \"Load table config for: \" << name;\n std::string filename = \"inputmethod\/\";\n filename.append(name.begin(), name.end());\n filename += \".conf\";\n auto files = StandardPath::global().openAll(StandardPath::Type::PkgData,\n filename, O_RDONLY);\n RawConfig rawConfig;\n \/\/ reverse the order, so we end up parse user file at last.\n for (const auto &file : files | boost::adaptors::reversed) {\n readFromIni(rawConfig, file.fd());\n }\n\n iter = tables_\n .emplace(std::piecewise_construct, std::make_tuple(name),\n std::make_tuple())\n .first;\n auto &root = iter->second.root;\n root.load(rawConfig);\n\n try {\n auto dict = std::make_unique<libime::TableBasedDictionary>();\n auto dictFile = StandardPath::global().open(\n StandardPath::Type::PkgData, *root.config->file, O_RDONLY);\n TABLE_DEBUG() << \"Load table at: \" << *root.config->file;\n if (dictFile.fd() < 0) {\n throw std::runtime_error(\"Couldn't open file\");\n }\n boost::iostreams::stream_buffer<\n boost::iostreams::file_descriptor_source>\n buffer(dictFile.fd(), boost::iostreams::file_descriptor_flags::\n never_close_handle);\n std::istream in(&buffer);\n dict->load(in);\n iter->second.dict = std::move(dict);\n } catch (const std::exception &) {\n }\n\n if (auto dict = iter->second.dict.get()) {\n try {\n auto dictFile = StandardPath::global().openUser(\n StandardPath::Type::PkgData,\n stringutils::concat(\"table\/\", name, \".user.dict\"),\n O_RDONLY);\n boost::iostreams::stream_buffer<\n boost::iostreams::file_descriptor_source>\n buffer(dictFile.fd(),\n boost::iostreams::file_descriptor_flags::\n never_close_handle);\n std::istream in(&buffer);\n dict->loadUser(in);\n } catch (const std::exception &e) {\n TABLE_DEBUG() << e.what();\n }\n\n populateOptions(dict, iter->second.root);\n std::shared_ptr<const libime::StaticLanguageModelFile> lmFile;\n try {\n lmFile = lm_->languageModelFileForLanguage(\n dict->tableOptions().languageCode());\n } catch (...) {\n TABLE_DEBUG()\n << \"Load language model for \"\n << dict->tableOptions().languageCode() << \" failed.\";\n }\n iter->second.model =\n std::make_unique<libime::UserLanguageModel>(lmFile);\n\n try {\n auto dictFile = StandardPath::global().openUser(\n StandardPath::Type::PkgData,\n stringutils::concat(\"table\/\", name, \".history\"), O_RDONLY);\n boost::iostreams::stream_buffer<\n boost::iostreams::file_descriptor_source>\n buffer(dictFile.fd(),\n boost::iostreams::file_descriptor_flags::\n never_close_handle);\n std::istream in(&buffer);\n iter->second.model->load(in);\n } catch (const std::exception &e) {\n TABLE_DEBUG() << e.what();\n }\n }\n }\n\n return {iter->second.dict.get(), iter->second.model.get(),\n &(*iter->second.root.config)};\n}\n\nvoid TableIME::saveAll() {\n for (const auto &p : tables_) {\n saveDict(p.first);\n }\n}\n\nvoid TableIME::updateConfig(const std::string &name, const RawConfig &config) {\n auto iter = tables_.find(name);\n if (iter == tables_.end()) {\n return;\n }\n iter->second.root.config.mutableValue()->load(config, true);\n\n if (iter->second.dict) {\n populateOptions(iter->second.dict.get(), iter->second.root);\n }\n\n \/\/ Load existing user level config, in order to avoid overwrite user config.\n RawConfig existingConfig;\n {\n auto file = StandardPath::global().openUser(\n StandardPath::Type::PkgData,\n stringutils::concat(\"inputmethod\/\", name, \".conf\"), O_RDONLY);\n if (file.fd() >= 0) {\n readFromIni(existingConfig, file.fd());\n }\n }\n iter->second.root.save(existingConfig);\n safeSaveAsIni(existingConfig, StandardPath::Type::PkgData,\n stringutils::concat(\"inputmethod\/\", name, \".conf\"));\n}\n\nvoid TableIME::releaseUnusedDict(const std::unordered_set<std::string> &names) {\n for (auto iter = tables_.begin(); iter != tables_.end();) {\n if (names.count(iter->first) == 0) {\n TABLE_DEBUG() << \"Release unused table: \" << iter->first;\n saveDict(iter->first);\n iter = tables_.erase(iter);\n } else {\n ++iter;\n }\n }\n}\n\nvoid TableIME::saveDict(const std::string &name) {\n auto iter = tables_.find(name);\n if (iter == tables_.end()) {\n return;\n }\n libime::TableBasedDictionary *dict = iter->second.dict.get();\n libime::UserLanguageModel *lm = iter->second.model.get();\n if (!dict || !lm || !*iter->second.root.config->learning) {\n return;\n }\n auto fileName = stringutils::joinPath(\"table\", name);\n\n StandardPath::global().safeSave(\n StandardPath::Type::PkgData, fileName + \".user.dict\", [dict](int fd) {\n boost::iostreams::stream_buffer<\n boost::iostreams::file_descriptor_sink>\n buffer(fd, boost::iostreams::file_descriptor_flags::\n never_close_handle);\n std::ostream out(&buffer);\n try {\n dict->saveUser(out);\n return static_cast<bool>(out);\n } catch (const std::exception &) {\n return false;\n }\n });\n\n StandardPath::global().safeSave(\n StandardPath::Type::PkgData, fileName + \".history\", [lm](int fd) {\n boost::iostreams::stream_buffer<\n boost::iostreams::file_descriptor_sink>\n buffer(fd, boost::iostreams::file_descriptor_flags::\n never_close_handle);\n std::ostream out(&buffer);\n try {\n lm->save(out);\n return static_cast<bool>(out);\n } catch (const std::exception &) {\n return false;\n }\n });\n}\n} \/\/ namespace fcitx\n<|endoftext|>"} {"text":"<commit_before>#include <map>\n\n#include <unistd.h>\n\n#include \"database.hpp\"\n\n#include \"cmap.hpp\"\n\n#define MAX_COLLECTIONS 100\n#define WRITE_INTERVAL 30\n\nusing namespace std;\n\nstatic int backup = -1;\n\nstruct Coll {\n pthread_mutex_t mutex;\n string name;\n cmap<int,JSON> documents;\n Coll() : mutex(PTHREAD_MUTEX_INITIALIZER) {}\n void read() { \/\/ this function is called only once, by a locked piece of code\n JSON tmp;\n if (!tmp.read_file(\"database\/\"+name+\".json\")) return;\n for (auto& doc : tmp.arr()) documents[doc(\"_id\")] = doc(\"document\");\n }\n void write() {\n JSON tmp(vector<JSON>{});\n pthread_mutex_lock(&mutex);\n for (auto& kv : documents) tmp.emplace_back(move(map<string,JSON>{\n {\"_id\" , kv.first},\n {\"document\" , kv.second}\n }));\n pthread_mutex_unlock(&mutex);\n tmp.write_file(\"database\/\"+name+\".json\");\n }\n int create(JSON&& doc) {\n int id = 1;\n pthread_mutex_lock(&mutex);\n if (documents.size() > 0) id += documents.max_key();\n documents[id] = move(doc);\n pthread_mutex_unlock(&mutex);\n return id;\n }\n bool retrieve(int id, JSON& doc) {\n pthread_mutex_lock(&mutex);\n auto it = documents.find(id);\n if (it == documents.end()) {\n doc.setnull();\n pthread_mutex_unlock(&mutex);\n return false;\n }\n doc = it->second;\n pthread_mutex_unlock(&mutex);\n return true;\n }\n JSON retrieve(const JSON& filter) {\n JSON ans(vector<JSON>{});\n pthread_mutex_lock(&mutex);\n for (auto& kv : documents) if (filter.issubobj(kv.second)) {\n JSON tmp = kv.second;\n tmp[\"id\"] = kv.first;\n ans.push_back(move(tmp));\n }\n pthread_mutex_unlock(&mutex);\n return ans;\n }\n JSON retrieve_page(unsigned p, unsigned ps) {\n JSON ans(vector<JSON>{});\n pthread_mutex_lock(&mutex);\n if (!ps) p = 0, ps = documents.size();\n auto it = documents.at(p*ps);\n for (int i = 0; i < ps && it != documents.end(); i++, it++) {\n JSON tmp = it->second;\n tmp[\"id\"] = it->first;\n ans.push_back(move(tmp));\n }\n pthread_mutex_unlock(&mutex);\n return ans;\n }\n bool update(int id, JSON&& doc) {\n pthread_mutex_lock(&mutex);\n auto it = documents.find(id);\n if (it == documents.end()) {\n pthread_mutex_unlock(&mutex);\n return false;\n }\n it->second = move(doc);\n pthread_mutex_unlock(&mutex);\n return true;\n }\n bool update(const Database::Updater& upd, int id) {\n bool ans = false;\n pthread_mutex_lock(&mutex);\n auto it = documents.find(id);\n if (it != documents.end()) {\n ans = upd(*it);\n pthread_mutex_unlock(&mutex);\n return ans;\n }\n for (auto& kv : documents) ans = ans || upd(kv);\n pthread_mutex_unlock(&mutex);\n return ans;\n }\n bool destroy(int id) {\n pthread_mutex_lock(&mutex);\n auto it = documents.find(id);\n if (it == documents.end()) {\n pthread_mutex_unlock(&mutex);\n return false;\n }\n documents.erase(it);\n pthread_mutex_unlock(&mutex);\n return true;\n }\n};\nstatic Coll collection[MAX_COLLECTIONS];\nstatic int ncolls = 0;\nstatic pthread_mutex_t colls_mutex = PTHREAD_MUTEX_INITIALIZER;\nstatic int get(const string& name) {\n static map<string,int> colls;\n int i;\n pthread_mutex_lock(&colls_mutex);\n auto it = colls.find(name);\n if (it != colls.end()) {\n i = it->second;\n pthread_mutex_unlock(&colls_mutex);\n return i;\n }\n i = ncolls++;\n colls[name] = i;\n collection[i].name = name;\n collection[i].read();\n pthread_mutex_unlock(&colls_mutex);\n return i;\n}\n\n\/\/ thread\nstatic bool quit = false;\nstatic pthread_t db;\nstatic void do_backup() {\n stringstream ss(\"backup\");\n ss << backup;\n system((\"mkdir -p database\/\"+ss.str()).c_str());\n system((\"cp database\/*.json database\/\"+ss.str()).c_str());\n}\nstatic void update() {\n int nc;\n pthread_mutex_lock(&colls_mutex);\n nc = ncolls;\n pthread_mutex_unlock(&colls_mutex);\n for (int i = 0; i < nc; i++) collection[i].write();\n if (backup < 0) return;\n do_backup();\n backup = 1-backup;\n}\nstatic void* thread(void*) {\n static time_t upd = 0;\n while (!quit) {\n if (upd <= time(nullptr)) {\n update();\n upd = time(nullptr)+WRITE_INTERVAL;\n }\n usleep(100000);\n }\n}\n\nnamespace Database {\n\nCollection::Collection(const string& name) : collid(get(name)) {\n \n}\n\nint Collection::create(const JSON& document) {\n JSON tmp(document);\n return collection[collid].create(move(tmp));\n}\n\nint Collection::create(JSON&& document) {\n return collection[collid].create(move(document));\n}\n\nJSON Collection::retrieve(int docid) {\n JSON ans;\n collection[collid].retrieve(docid,ans);\n return ans;\n}\n\nbool Collection::retrieve(int docid, JSON& document) {\n return collection[collid].retrieve(docid,document);\n}\n\nJSON Collection::retrieve(const JSON& filter) {\n return collection[collid].retrieve(filter);\n}\n\nJSON Collection::retrieve_page(unsigned page,unsigned page_size) {\n return collection[collid].retrieve_page(page,page_size);\n}\n\nbool Collection::update(int docid, const JSON& document) {\n JSON tmp(document);\n return collection[collid].update(docid,move(tmp));\n}\n\nbool Collection::update(int docid, JSON&& document) {\n return collection[collid].update(docid,move(document));\n}\n\nbool Collection::update(const Updater& upd, int docid) {\n return collection[collid].update(upd,docid);\n}\n\nbool Collection::destroy(int docid) {\n return collection[collid].destroy(docid);\n}\n\nvoid init(bool backup) {\n if (backup) ::backup = 0;\n system(\"mkdir -p database\");\n pthread_create(&db,nullptr,thread,nullptr);\n}\n\nvoid close() {\n quit = true;\n pthread_join(db,nullptr);\n update();\n}\n\n} \/\/ namespace Database\n<commit_msg>Fixing bug<commit_after>#include <map>\n\n#include <unistd.h>\n\n#include \"database.hpp\"\n\n#include \"cmap.hpp\"\n\n#define MAX_COLLECTIONS 100\n#define WRITE_INTERVAL 30\n\nusing namespace std;\n\nstatic int backup = -1;\n\nstruct Coll {\n pthread_mutex_t mutex;\n string name;\n cmap<int,JSON> documents;\n Coll() : mutex(PTHREAD_MUTEX_INITIALIZER) {}\n void read() { \/\/ this function is called only once, by a locked piece of code\n JSON tmp;\n if (!tmp.read_file(\"database\/\"+name+\".json\")) return;\n for (auto& doc : tmp.arr()) documents[doc(\"_id\")] = doc(\"document\");\n }\n void write() {\n JSON tmp(vector<JSON>{});\n pthread_mutex_lock(&mutex);\n for (auto& kv : documents) tmp.emplace_back(move(map<string,JSON>{\n {\"_id\" , kv.first},\n {\"document\" , kv.second}\n }));\n pthread_mutex_unlock(&mutex);\n tmp.write_file(\"database\/\"+name+\".json\");\n }\n int create(JSON&& doc) {\n int id = 1;\n pthread_mutex_lock(&mutex);\n if (documents.size() > 0) id += documents.max_key();\n documents[id] = move(doc);\n pthread_mutex_unlock(&mutex);\n return id;\n }\n bool retrieve(int id, JSON& doc) {\n pthread_mutex_lock(&mutex);\n auto it = documents.find(id);\n if (it == documents.end()) {\n doc.setnull();\n pthread_mutex_unlock(&mutex);\n return false;\n }\n doc = it->second;\n pthread_mutex_unlock(&mutex);\n return true;\n }\n JSON retrieve(const JSON& filter) {\n JSON ans(vector<JSON>{});\n pthread_mutex_lock(&mutex);\n for (auto& kv : documents) if (filter.issubobj(kv.second)) {\n JSON tmp = kv.second;\n tmp[\"id\"] = kv.first;\n ans.push_back(move(tmp));\n }\n pthread_mutex_unlock(&mutex);\n return ans;\n }\n JSON retrieve_page(unsigned p, unsigned ps) {\n JSON ans(vector<JSON>{});\n pthread_mutex_lock(&mutex);\n if (!ps) p = 0, ps = documents.size();\n auto it = documents.at(p*ps);\n for (int i = 0; i < ps && it != documents.end(); i++, it++) {\n JSON tmp = it->second;\n tmp[\"id\"] = it->first;\n ans.push_back(move(tmp));\n }\n pthread_mutex_unlock(&mutex);\n return ans;\n }\n bool update(int id, JSON&& doc) {\n pthread_mutex_lock(&mutex);\n auto it = documents.find(id);\n if (it == documents.end()) {\n pthread_mutex_unlock(&mutex);\n return false;\n }\n it->second = move(doc);\n pthread_mutex_unlock(&mutex);\n return true;\n }\n bool update(const Database::Updater& upd, int id) {\n bool ans = false;\n pthread_mutex_lock(&mutex);\n auto it = documents.find(id);\n if (it != documents.end()) {\n ans = upd(*it);\n pthread_mutex_unlock(&mutex);\n return ans;\n }\n for (auto& kv : documents) ans = ans || upd(kv);\n pthread_mutex_unlock(&mutex);\n return ans;\n }\n bool destroy(int id) {\n pthread_mutex_lock(&mutex);\n auto it = documents.find(id);\n if (it == documents.end()) {\n pthread_mutex_unlock(&mutex);\n return false;\n }\n documents.erase(it);\n pthread_mutex_unlock(&mutex);\n return true;\n }\n};\nstatic Coll collection[MAX_COLLECTIONS];\nstatic int ncolls = 0;\nstatic pthread_mutex_t colls_mutex = PTHREAD_MUTEX_INITIALIZER;\nstatic int get(const string& name) {\n static map<string,int> colls;\n int i;\n pthread_mutex_lock(&colls_mutex);\n auto it = colls.find(name);\n if (it != colls.end()) {\n i = it->second;\n pthread_mutex_unlock(&colls_mutex);\n return i;\n }\n i = ncolls++;\n colls[name] = i;\n collection[i].name = name;\n collection[i].read();\n pthread_mutex_unlock(&colls_mutex);\n return i;\n}\n\n\/\/ thread\nstatic bool quit = false;\nstatic pthread_t db;\nstatic void do_backup() {\n stringstream ss;\n ss << \"backup\" << backup;\n system((\"mkdir -p database\/\"+ss.str()).c_str());\n system((\"cp database\/*.json database\/\"+ss.str()).c_str());\n}\nstatic void update() {\n int nc;\n pthread_mutex_lock(&colls_mutex);\n nc = ncolls;\n pthread_mutex_unlock(&colls_mutex);\n for (int i = 0; i < nc; i++) collection[i].write();\n if (backup < 0) return;\n do_backup();\n backup = 1-backup;\n}\nstatic void* thread(void*) {\n static time_t upd = 0;\n while (!quit) {\n if (upd <= time(nullptr)) {\n update();\n upd = time(nullptr)+WRITE_INTERVAL;\n }\n usleep(100000);\n }\n}\n\nnamespace Database {\n\nCollection::Collection(const string& name) : collid(get(name)) {\n \n}\n\nint Collection::create(const JSON& document) {\n JSON tmp(document);\n return collection[collid].create(move(tmp));\n}\n\nint Collection::create(JSON&& document) {\n return collection[collid].create(move(document));\n}\n\nJSON Collection::retrieve(int docid) {\n JSON ans;\n collection[collid].retrieve(docid,ans);\n return ans;\n}\n\nbool Collection::retrieve(int docid, JSON& document) {\n return collection[collid].retrieve(docid,document);\n}\n\nJSON Collection::retrieve(const JSON& filter) {\n return collection[collid].retrieve(filter);\n}\n\nJSON Collection::retrieve_page(unsigned page,unsigned page_size) {\n return collection[collid].retrieve_page(page,page_size);\n}\n\nbool Collection::update(int docid, const JSON& document) {\n JSON tmp(document);\n return collection[collid].update(docid,move(tmp));\n}\n\nbool Collection::update(int docid, JSON&& document) {\n return collection[collid].update(docid,move(document));\n}\n\nbool Collection::update(const Updater& upd, int docid) {\n return collection[collid].update(upd,docid);\n}\n\nbool Collection::destroy(int docid) {\n return collection[collid].destroy(docid);\n}\n\nvoid init(bool backup) {\n if (backup) ::backup = 0;\n system(\"mkdir -p database\");\n pthread_create(&db,nullptr,thread,nullptr);\n}\n\nvoid close() {\n quit = true;\n pthread_join(db,nullptr);\n update();\n}\n\n} \/\/ namespace Database\n<|endoftext|>"} {"text":"<commit_before>#include \"database.h\"\n\nbool Database::openDB () {\n \/\/ Find QSLite driver\n QSqlDatabase db = QSqlDatabase::addDatabase ( \"QSQLITE\" );\n\n#ifdef Q_OS_LINUX\n QString path( QDir::home ().path () + \"\/.config\/\" + QCoreApplication::applicationName () + \"\/\" + QCoreApplication::applicationName () + \".db\" );\n if( QFile::exists ( path ))\n return true;\n \/\/ NOTE: We have to store database file into user home folder in Linux\n db.setDatabaseName( path );\n#else\n if( QFile::exists ( QCoreApplication::applicationName () + \".db\" ))\n return true;\n \/\/ NOTE: File exists in the application private folder, in Symbian Qt implementation\n db.setDatabaseName( QCoreApplication::applicationName () + \".db\" );\n#endif\n if ( !db.open ()) {\n qWarning ( \"Unable to establish a database connection.\\n\" );\n return false;\n }\n\n QSqlQuery query;\n query.exec( \"create table lineEditComplete (id int primary key, seachWord varchar(20), numberOfUsed int)\" );\n\n return true;\n}\n\nbool Database::deleteDB () {\n#ifdef Q_OS_LINUX\n \/\/ NOTE: We have to store database file into user home folder in Linux\n return QFile::remove ( QDir::home ().path () + \"\/.config\/\" + QCoreApplication::applicationName () + \"\/\" + QCoreApplication::applicationName () + \".db\" );\n#else\n \n \/\/ Remove created database binary file\n return QFile::remove ( QCoreApplication::applicationName () + \".db\" );\n#endif\n}\n<commit_msg>remove needless new line<commit_after>#include \"database.h\"\n\nbool Database::openDB () {\n \/\/ Find QSLite driver\n QSqlDatabase db = QSqlDatabase::addDatabase ( \"QSQLITE\" );\n\n#ifdef Q_OS_LINUX\n QString path( QDir::home ().path () + \"\/.config\/\" + QCoreApplication::applicationName () + \"\/\" + QCoreApplication::applicationName () + \".db\" );\n if( QFile::exists ( path ))\n return true;\n \/\/ NOTE: We have to store database file into user home folder in Linux\n db.setDatabaseName( path );\n#else\n if( QFile::exists ( QCoreApplication::applicationName () + \".db\" ))\n return true;\n \/\/ NOTE: File exists in the application private folder, in Symbian Qt implementation\n db.setDatabaseName( QCoreApplication::applicationName () + \".db\" );\n#endif\n if ( !db.open ()) {\n qWarning ( \"Unable to establish a database connection.\" );\n return false;\n }\n\n QSqlQuery query;\n query.exec( \"create table lineEditComplete (id int primary key, seachWord varchar(20), numberOfUsed int)\" );\n\n return true;\n}\n\nbool Database::deleteDB () {\n#ifdef Q_OS_LINUX\n \/\/ NOTE: We have to store database file into user home folder in Linux\n return QFile::remove ( QDir::home ().path () + \"\/.config\/\" + QCoreApplication::applicationName () + \"\/\" + QCoreApplication::applicationName () + \".db\" );\n#else\n \n \/\/ Remove created database binary file\n return QFile::remove ( QCoreApplication::applicationName () + \".db\" );\n#endif\n}\n<|endoftext|>"} {"text":"<commit_before>\/*!\n * \\file xgboost.cpp\n * \\brief bootser implementations \n * \\author Tianqi Chen: tianqi.tchen@gmail.com\n *\/\n\/\/ implementation of boosters go to here \n#define _CRT_SECURE_NO_WARNINGS\n#define _CRT_SECURE_NO_DEPRECATE\n#include <climits>\n#include \"xgboost.h\"\n#include \"..\/utils\/xgboost_utils.h\"\n#include \"xgboost_gbmbase.h\"\n\/\/ implementations of boosters\n#include \"tree\/xgboost_svdf_tree.hpp\"\n\nnamespace xgboost{\n namespace booster{\n \/*! \n * \\brief create a gradient booster, given type of booster\n * \\param booster_type type of gradient booster, can be used to specify implements\n * \\return the pointer to the gradient booster created\n *\/\n IBooster *CreateBooster( int booster_type ){\n \/\/ TODO\n return NULL;\n }\n };\n};\n\n\n<commit_msg>adapt tree booster<commit_after>\/*!\n * \\file xgboost.cpp\n * \\brief bootser implementations \n * \\author Tianqi Chen: tianqi.tchen@gmail.com\n *\/\n\/\/ implementation of boosters go to here \n#define _CRT_SECURE_NO_WARNINGS\n#define _CRT_SECURE_NO_DEPRECATE\n#include <climits>\n#include \"xgboost.h\"\n#include \"..\/utils\/xgboost_utils.h\"\n#include \"xgboost_gbmbase.h\"\n\/\/ implementations of boosters\n#include \"tree\/xgboost_svdf_tree.hpp\"\n\nnamespace xgboost{\n namespace booster{\n \/*! \n * \\brief create a gradient booster, given type of booster\n * \\param booster_type type of gradient booster, can be used to specify implements\n * \\return the pointer to the gradient booster created\n *\/\n IBooster *CreateBooster( int booster_type ){\n return new RTreeTrainer();\n }\n };\n};\n\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ The MIT License (MIT)\n\/\/\n\/\/ Copyright (c) 2016 Northeastern University\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n\/\/ SOFTWARE.\n\n\/\/ This file tests the CpuOperations::Transpose() function by checking to\n\/\/ See if a matrix passed is transposed in the test IsTransposed\n\/\/ A transposed Nice matrix is compared to a transposed Eigen Matrix in\n\/\/ Transpose Eigen\n\/\/ Behavior with oddly shaped matrices is also tested with test DifferentShapes\n\/\/ And TransposeZeroRows\n\/\/ All tests are made using a templated test fixture which attempts\n\/\/ Integer, float, and double data types\n\n\n#include <stdio.h>\n#include <iostream>\n#include <cmath>\n#include \"Eigen\/Dense\"\n#include \"include\/svd_solver.h\"\n#include \"gtest\/gtest.h\"\n#include \"include\/matrix.h\"\n#include \"include\/vector.h\"\n\n\/\/ This is a template test fixture class containing test matrices\ntemplate<class T> \/\/ Template\nclass CpuSvdSolverTest : public ::testing::Test {\n \/\/ Inherits from testing::Test\n\n\n public: \/\/ Members must be public to be accessed by tests\n Nice::Matrix<T> matrix_;\n Nice::Matrix<T> u_;\n Nice::Matrix<T> v_;\n Nice::Vector<T> s_;\n int row_;\n int col_;\n\n \/\/ Constructor\n void CreateTestData() {\n \/\/ Check matrix\n if (matrix_.rows() != 0 && matrix_.cols() != 0)\n return;\n\n row_ = 5;\n col_ = row_;\n matrix_.resize(row_, col_);\n matrix_ << -129.3026, 1031.7118, 2548.9163, -511.0120, 2.7719,\n 583.9671, 220.9613, 536.9512, 55.0691, 954.5454,\n 694.9577, -626.7673, -972.7809, 800.4132, 298.9344,\n 659.9324, 1235.7984, -688.4173, -55.1088, -1194.2583,\n 1552.5551, 513.1012, -2574.5784, -1489.1966, -55.4250;\n u_.resize(row_, col_);\n u_ << -0.555596, -0.617009, -0.244002, -0.092006, 0.492557,\n -0.088014, -0.051527, -0.654019, -0.478284, -0.577150,\n 0.240369, 0.395314, -0.108216, -0.651940, 0.590943,\n 0.228426, -0.529382, 0.585784, -0.527902, -0.213902,\n 0.757372, -0.424414, -0.397328, 0.243049, 0.171226;\n v_.resize(row_, col_);\n v_ << 0.363743, -0.277844, -0.404770, -0.608509, 0.506332,\n -0.017398, -0.718194, 0.118253, -0.281295, -0.625128,\n -0.913964, -0.214438, -0.153148, -0.105130, 0.290136,\n -0.160719, 0.524143, 0.346509, -0.733898, -0.201915,\n -0.078912, 0.293753, -0.823805, -0.030541, -0.477383;\n s_.resize(row_);\n s_ << 4162.54, 2461.32, 1620.37, 1136.40, 265.90;\n }\n};\n\n\/\/ Establishes a test case with the given types, Char and short types will\n\/\/ Throw compiler errors\ntypedef ::testing::Types<float, double> dataTypes;\nTYPED_TEST_CASE(CpuSvdSolverTest, dataTypes);\n\nTYPED_TEST(CpuSvdSolverTest, FuncionalityTest) {\n \/\/ Create test data\n this->CreateTestData();\n\n \/\/ Test svd solver in Nice\n Nice::SvdSolver<TypeParam> svd_solver;\n svd_solver.Compute(this->matrix_);\n Nice::Matrix<TypeParam> result_u = svd_solver.MatrixU();\n Nice::Matrix<TypeParam> result_v = svd_solver.MatrixV();\n Nice::Vector<TypeParam> result_s = svd_solver.SingularValues();\n\n \/\/ Verify the result U\n for (int i = 0; i < this->row_; i++)\n for (int i = 0; i < this->col_; i++)\n EXPECT_NEAR(abs(this->u_(i)), abs(result_u(i)), 0.001);\n\n \/\/ Verify the result V\n for (int i = 0; i < this->row_; i++)\n for (int i = 0; i < this->col_; i++)\n EXPECT_NEAR(abs(this->v_(i)), abs(result_v(i)), 0.001);\n\n \/\/ Verify the result S\n for (int i = 0; i < this->row_; i++)\n EXPECT_NEAR(this->s_(i), result_s(i), 0.1);\n}\n\nTYPED_TEST(CpuSvdSolverTest, RankTest) {\n \/\/ Create test data\n this->CreateTestData();\n\n \/\/ Test svd solver in Nice\n Nice::SvdSolver<TypeParam> svd_solver;\n int rank = svd_solver.Rank(this->matrix_);\n\n \/\/ Verify the rank\n EXPECT_EQ(5, rank);\n}\n\n<commit_msg>Revert \"fixed all google codestyle errors\"<commit_after>\/\/ The MIT License (MIT)\n\/\/\n\/\/ Copyright (c) 2016 Northeastern University\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n\/\/ SOFTWARE.\n\n\/\/ This file tests the CpuOperations::Transpose() function by checking to\n\/\/ See if a matrix passed is transposed in the test IsTransposed\n\/\/ A transposed Nice matrix is compared to a transposed Eigen Matrix in\n\/\/ Transpose Eigen\n\/\/ Behavior with oddly shaped matrices is also tested with test DifferentShapes\n\/\/ And TransposeZeroRows\n\/\/ All tests are made using a templated test fixture which attempts\n\/\/ Integer, float, and double data types\n\n\n#include <stdio.h>\n#include <iostream>\n\n#include <iostream>\n#include <cmath>\n\n\n#include \"Eigen\/Dense\"\n#include \"include\/svd_solver.h\"\n#include \"gtest\/gtest.h\"\n#include \"include\/svd_solver.h\"\n#include \"include\/matrix.h\"\n#include \"include\/vector.h\"\n\n\/\/ This is a template test fixture class containing test matrices\ntemplate<class T> \/\/ Template\nclass CpuSvdSolverTest : public ::testing::Test {\n\n \/\/ Inherits from testing::Test\n\n\n public: \/\/ Members must be public to be accessed by tests\n Nice::Matrix<T> matrix_;\n Nice::Matrix<T> u_;\n Nice::Matrix<T> v_;\n Nice::Vector<T> s_;\n int row_;\n int col_;\n\n \/\/ Constructor\n void CreateTestData() {\n \/\/ Check matrix\n if (matrix_.rows() != 0 && matrix_.cols() != 0)\n return;\n\n row_ = 5;\n col_ = row_;\n matrix_.resize(row_, col_);\n matrix_ << -129.3026, 1031.7118, 2548.9163, -511.0120, 2.7719,\n 583.9671, 220.9613, 536.9512, 55.0691, 954.5454,\n 694.9577, -626.7673, -972.7809, 800.4132, 298.9344,\n 659.9324, 1235.7984, -688.4173, -55.1088, -1194.2583,\n 1552.5551, 513.1012, -2574.5784, -1489.1966, -55.4250;\n u_.resize(row_, col_);\n u_ << -0.555596, -0.617009, -0.244002, -0.092006, 0.492557,\n -0.088014, -0.051527, -0.654019, -0.478284, -0.577150,\n 0.240369, 0.395314, -0.108216, -0.651940, 0.590943,\n 0.228426, -0.529382, 0.585784, -0.527902, -0.213902,\n 0.757372, -0.424414, -0.397328, 0.243049, 0.171226;\n v_.resize(row_, col_);\n v_ << 0.363743, -0.277844, -0.404770, -0.608509, 0.506332,\n -0.017398, -0.718194, 0.118253, -0.281295, -0.625128,\n -0.913964, -0.214438, -0.153148, -0.105130, 0.290136,\n -0.160719, 0.524143, 0.346509, -0.733898, -0.201915,\n -0.078912, 0.293753, -0.823805, -0.030541, -0.477383;\n s_.resize(row_);\n s_ << 4162.54, 2461.32, 1620.37, 1136.40, 265.90;\n }\n};\n\n\/\/ Establishes a test case with the given types, Char and short types will\n\/\/ Throw compiler errors\ntypedef ::testing::Types<float, double> dataTypes;\nTYPED_TEST_CASE(CpuSvdSolverTest, dataTypes);\n\nTYPED_TEST(CpuSvdSolverTest, FuncionalityTest) {\n \/\/ Create test data\n this->CreateTestData();\n\n \/\/ Test svd solver in Nice\n Nice::SvdSolver<TypeParam> svd_solver;\n svd_solver.Compute(this->matrix_);\n Nice::Matrix<TypeParam> result_u = svd_solver.MatrixU();\n Nice::Matrix<TypeParam> result_v = svd_solver.MatrixV();\n Nice::Vector<TypeParam> result_s = svd_solver.SingularValues();\n\n \/\/ Verify the result U\n for (int i = 0; i < this->row_; i++)\n for (int i = 0; i < this->col_; i++)\n EXPECT_NEAR(abs(this->u_(i)), abs(result_u(i)), 0.001);\n\n \/\/ Verify the result V\n for (int i = 0; i < this->row_; i++)\n for (int i = 0; i < this->col_; i++)\n EXPECT_NEAR(abs(this->v_(i)), abs(result_v(i)), 0.001);\n\n \/\/ Verify the result S\n for (int i = 0; i < this->row_; i++)\n EXPECT_NEAR(this->s_(i), result_s(i), 0.1);\n}\n\nTYPED_TEST(CpuSvdSolverTest, RankTest) {\n \/\/ Create test data\n this->CreateTestData();\n\n \/\/ Test svd solver in Nice\n Nice::SvdSolver<TypeParam> svd_solver;\n int rank = svd_solver.Rank(this->matrix_);\n\n \/\/ Verify the rank\n EXPECT_EQ(5, rank);\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n* The MIT License (MIT)\n*\n* Copyright (c) Microsoft Corporation\n*\n* Permission is hereby granted, free of charge, to any person obtaining a\n* copy of this software and associated documentation files (the \"Software\"),\n* to deal in the Software without restriction, including without limitation\n* the rights to use, copy, modify, merge, publish, distribute, sublicense,\n* and\/or sell copies of the Software, and to permit persons to whom the\n* Software is furnished to do so, subject to the following conditions:\n*\n* The above copyright notice and this permission notice shall be included\n* in all copies or substantial portions of the Software.\n*\n* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR\n* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,\n* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\n* OTHER DEALINGS IN THE SOFTWARE.\n*\n*\/\n\n\/**\n Test JIT code emission.\n*\/\n\n#include \"stdafx.h\"\n#include \"catch.hpp\"\n#include \"testing_util.h\"\n#include <Python.h>\n#include <frameobject.h>\n#include <util.h>\n#include <pyjit.h>\n\nclass EmissionTest {\nprivate:\n py_ptr<PyCodeObject> m_code;\n py_ptr<PyJittedCode> m_jittedcode;\n\n PyObject* run() {\n auto sysModule = PyObject_ptr(PyImport_ImportModule(\"sys\"));\n auto globals = PyObject_ptr(PyDict_New());\n auto builtins = PyThreadState_GET()->interp->builtins;\n PyDict_SetItemString(globals.get(), \"__builtins__\", builtins);\n PyDict_SetItemString(globals.get(), \"sys\", sysModule.get());\n\n \/\/ Don't DECREF as frames are recycled.\n auto frame = PyFrame_New(PyThreadState_Get(), m_code.get(), globals.get(), PyObject_ptr(PyDict_New()).get());\n\n auto res = m_jittedcode->j_evalfunc(m_jittedcode->j_evalstate, frame);\n\n return res;\n }\n\npublic:\n EmissionTest(const char *code) {\n m_code.reset(CompileCode(code));\n if (m_code.get() == nullptr) {\n FAIL(\"failed to compile code\");\n }\n m_jittedcode.reset(JitCompile(m_code.get()));\n if (m_jittedcode.get() == nullptr) {\n FAIL(\"failed to JIT code\");\n }\n }\n\n std::string returns() {\n auto res = PyObject_ptr(run());\n REQUIRE(res.get() != nullptr);\n REQUIRE(!PyErr_Occurred());\n\n auto repr = PyUnicode_AsUTF8(PyObject_Repr(res.get()));\n auto tstate = PyThreadState_GET();\n REQUIRE(tstate->exc_value == nullptr);\n REQUIRE(tstate->exc_traceback == nullptr);\n if (tstate->exc_type != nullptr) {\n REQUIRE(tstate->exc_type == Py_None);\n }\n\n return std::string(repr);\n }\n\n PyObject* raises() {\n auto res = run();\n REQUIRE(res == nullptr);\n auto excType = PyErr_Occurred();\n PyErr_Clear();\n return excType;\n }\n};\n\nTEST_CASE(\"General list unpacking\", \"[list][BUILD_LIST_UNPACK][emission]\") {\n SECTION(\"common case\") {\n auto t = EmissionTest(\"def f(): return [1, *[2], 3]\");\n REQUIRE(t.returns() == \"[1, 2, 3]\");\n }\n\n SECTION(\"unpacking a non-iterable\") {\n auto t = EmissionTest(\"def f(): return [1, *2, 3]\");\n REQUIRE(t.raises() == PyExc_TypeError);\n }\n}<commit_msg>Add failing tests for BUILD_TUPLE_UNPACK<commit_after>\/*\n* The MIT License (MIT)\n*\n* Copyright (c) Microsoft Corporation\n*\n* Permission is hereby granted, free of charge, to any person obtaining a\n* copy of this software and associated documentation files (the \"Software\"),\n* to deal in the Software without restriction, including without limitation\n* the rights to use, copy, modify, merge, publish, distribute, sublicense,\n* and\/or sell copies of the Software, and to permit persons to whom the\n* Software is furnished to do so, subject to the following conditions:\n*\n* The above copyright notice and this permission notice shall be included\n* in all copies or substantial portions of the Software.\n*\n* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR\n* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,\n* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\n* OTHER DEALINGS IN THE SOFTWARE.\n*\n*\/\n\n\/**\n Test JIT code emission.\n*\/\n\n#include \"stdafx.h\"\n#include \"catch.hpp\"\n#include \"testing_util.h\"\n#include <Python.h>\n#include <frameobject.h>\n#include <util.h>\n#include <pyjit.h>\n\nclass EmissionTest {\nprivate:\n py_ptr<PyCodeObject> m_code;\n py_ptr<PyJittedCode> m_jittedcode;\n\n PyObject* run() {\n auto sysModule = PyObject_ptr(PyImport_ImportModule(\"sys\"));\n auto globals = PyObject_ptr(PyDict_New());\n auto builtins = PyThreadState_GET()->interp->builtins;\n PyDict_SetItemString(globals.get(), \"__builtins__\", builtins);\n PyDict_SetItemString(globals.get(), \"sys\", sysModule.get());\n\n \/\/ Don't DECREF as frames are recycled.\n auto frame = PyFrame_New(PyThreadState_Get(), m_code.get(), globals.get(), PyObject_ptr(PyDict_New()).get());\n\n auto res = m_jittedcode->j_evalfunc(m_jittedcode->j_evalstate, frame);\n\n return res;\n }\n\npublic:\n EmissionTest(const char *code) {\n m_code.reset(CompileCode(code));\n if (m_code.get() == nullptr) {\n FAIL(\"failed to compile code\");\n }\n m_jittedcode.reset(JitCompile(m_code.get()));\n if (m_jittedcode.get() == nullptr) {\n FAIL(\"failed to JIT code\");\n }\n }\n\n std::string returns() {\n auto res = PyObject_ptr(run());\n REQUIRE(res.get() != nullptr);\n REQUIRE(!PyErr_Occurred());\n\n auto repr = PyUnicode_AsUTF8(PyObject_Repr(res.get()));\n auto tstate = PyThreadState_GET();\n REQUIRE(tstate->exc_value == nullptr);\n REQUIRE(tstate->exc_traceback == nullptr);\n if (tstate->exc_type != nullptr) {\n REQUIRE(tstate->exc_type == Py_None);\n }\n\n return std::string(repr);\n }\n\n PyObject* raises() {\n auto res = run();\n REQUIRE(res == nullptr);\n auto excType = PyErr_Occurred();\n PyErr_Clear();\n return excType;\n }\n};\n\nTEST_CASE(\"General list unpacking\", \"[list][BUILD_LIST_UNPACK][emission]\") {\n SECTION(\"common case\") {\n auto t = EmissionTest(\"def f(): return [1, *[2], 3]\");\n CHECK(t.returns() == \"[1, 2, 3]\");\n }\n\n SECTION(\"unpacking a non-iterable\") {\n auto t = EmissionTest(\"def f(): return [1, *2, 3]\");\n CHECK(t.raises() == PyExc_TypeError);\n }\n}\n\nTEST_CASE(\"General tuple unpacking\", \"[tuple][BUILD_TUPLE_UNPACK][emission]\") {\n SECTION(\"common case\") {\n auto t = EmissionTest(\"def f(): return (1, *(2,), 3)\");\n CHECK(t.returns() == \"(1, 2, 3)\");\n }\n\n SECTION(\"unpacking a non-iterable\") {\n auto t = EmissionTest(\"def f(): return (1, *2, 3)\");\n CHECK(t.raises() == PyExc_TypeError);\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n For more information, please see: http:\/\/software.sci.utah.edu\n\n The MIT License\n\n Copyright (c) 2008 Scientific Computing and Imaging Institute,\n University of Utah.\n\n\n Permission is hereby granted, free of charge, to any person obtaining a\n copy of this software and associated documentation files (the \"Software\"),\n to deal in the Software without restriction, including without limitation\n the rights to use, copy, modify, merge, publish, distribute, sublicense,\n and\/or sell copies of the Software, and to permit persons to whom the\n Software is furnished to do so, subject to the following conditions:\n\n The above copyright notice and this permission notice shall be included\n in all copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n DEALINGS IN THE SOFTWARE.\n*\/\n\n\/**\n \\file TiffVolumeConverter.h\n \\author Tom Fogal\n SCI Institute\n University of Utah\n*\/\n#include <cstring>\n#include \"boost\/cstdint.hpp\"\n#ifndef TUVOK_NO_IO\n# include \"3rdParty\/tiff\/tiffio.h\"\n#else\n struct TIFF;\n#endif\n#include \"TiffVolumeConverter.h\"\n#include \"..\/StdTuvokDefines.h\"\n#include \"..\/Controller\/Controller.h\"\n#include \"..\/Basics\/SysTools.h\"\n\n#ifdef __GNUC__\n# define _malloc __attribute__((malloc))\n#else\n# define _malloc \/* nothing *\/\n#endif\n\nstatic void tv_dimensions(TIFF *, size_t dims[3]);\n_malloc static BYTE* tv_read_slice(TIFF *);\n\nTiffVolumeConverter::TiffVolumeConverter()\n{\n m_vConverterDesc = \"TIFF Volume (Image stack)\";\n#ifndef TUVOK_NO_IO\n m_vSupportedExt.push_back(\"OME.TIF\");\n m_vSupportedExt.push_back(\"OME.TIFF\");\n m_vSupportedExt.push_back(\"TIF\");\n m_vSupportedExt.push_back(\"TIFF\");\n#endif\n}\n\n\/\/ converts a TiffVolume to a `raw' file. We'll read through the TIFF\n\/\/ slice-by-slice, copying each slice to the raw file.\nbool\nTiffVolumeConverter::ConvertToRAW(const std::string& strSourceFilename,\n const std::string& strTempDir,\n bool, UINT64& iHeaderSkip,\n UINT64& iComponentSize,\n UINT64& iComponentCount,\n bool& bConvertEndianess, bool& bSigned,\n bool& bIsFloat, UINTVECTOR3& vVolumeSize,\n FLOATVECTOR3& vVolumeAspect,\n std::string& strTitle,\n UVFTables::ElementSemanticTable& eType,\n std::string& strIntermediateFile,\n bool& bDeleteIntermediateFile)\n{\n#ifndef TUVOK_NO_IO\n MESSAGE(\"Attempting to convert TiffVolume: %s\", strSourceFilename.c_str());\n\n TIFF *tif = TIFFOpen(strSourceFilename.c_str(), \"r\");\n if(tif == NULL) {\n T_ERROR(\"Could not open %s\", strSourceFilename.c_str());\n return false;\n }\n\n \/\/ Get the dimensions of the volume.\n {\n size_t dims[3];\n tv_dimensions(tif, dims);\n vVolumeSize[0] = UINT32(dims[0]);\n vVolumeSize[1] = UINT32(dims[1]);\n vVolumeSize[2] = UINT32(dims[2]);\n MESSAGE(\"TiffVolume dimensions: %ux%ux%u\", UINT32(dims[0]), UINT32(dims[1]), UINT32(dims[2]));\n if(dims[2] <= 1) {\n T_ERROR(\"TIFF is not a volume; use \"\n \"`Load Dataset from Directory' instead!\");\n TIFFClose(tif);\n return false;\n }\n }\n iHeaderSkip = 0;\n\n \/\/ read the number of bits per component from the tiff tag.\n {\n boost::uint16_t bits_per_sample;\n TIFFGetField(tif, TIFFTAG_BITSPERSAMPLE, &bits_per_sample);\n iComponentSize = bits_per_sample;\n MESSAGE(\"%ld bits per component.\", iComponentSize);\n }\n \/\/ likewise for the number of components \/ pixel.\n {\n boost::uint16_t components;\n TIFFGetField(tif, TIFFTAG_SAMPLESPERPIXEL, &components);\n iComponentCount = components;\n MESSAGE(\"%ld component%s.\", iComponentCount,\n (components == 1) ? \"\" : \"s\");\n }\n \/\/ IIRC libtiff handles all the endian issues for us.\n bConvertEndianess = false;\n\n \/\/ One might consider setting the values below explicitly as bugs, but we're\n \/\/ not quite sure where to read these from. In any case, we don't have any\n \/\/ data for which these settings are invalid.\n bSigned = false;\n bIsFloat = false;\n vVolumeAspect[0] = 1;\n vVolumeAspect[1] = 1;\n vVolumeAspect[2] = 1;\n\n strTitle = \"TIFF Volume\";\n eType = UVFTables::ES_UNDEFINED;\n\n \/\/ Create an intermediate file to hold the data.\n strIntermediateFile = strTempDir +\n SysTools::GetFilename(strSourceFilename) + \".binary\";\n LargeRAWFile binary(strIntermediateFile);\n binary.Create(iComponentSize\/8 * iComponentCount * vVolumeSize.volume());\n if(!binary.IsOpen()) {\n T_ERROR(\"Could not create binary file %s\", strIntermediateFile.c_str());\n \n TIFFClose(tif);\n return false;\n }\n bDeleteIntermediateFile = true;\n \/\/ Populate the intermediate file. We'll do this slice-by-slice, which isn't\n \/\/ exactly kosher in Tuvok -- a slice could technically be larger than\n \/\/ INCORESIZE. But it won't be.\n do {\n BYTE* slice = tv_read_slice(tif);\n if(slice) {\n \/\/ assuming 8-bit monochrome data here, which might not always be valid.\n binary.WriteRAW(static_cast<unsigned char*>(slice),\n vVolumeSize[0]*vVolumeSize[1]*sizeof(BYTE));\n _TIFFfree(slice);\n } else {\n binary.Close();\n binary.Delete();\n TIFFClose(tif);\n return false;\n }\n } while(TIFFReadDirectory(tif));\n binary.Close();\n\n TIFFClose(tif);\n return true;\n#else\n T_ERROR(\"Tuvok was not built with IO support!\");\n return false;\n#endif\n}\n\n\/\/ unimplemented!\nbool\nTiffVolumeConverter::ConvertToNative(const std::string&,\n const std::string&,\n UINT64, UINT64, \n UINT64, bool,\n bool,\n UINTVECTOR3,\n FLOATVECTOR3,\n bool)\n{\n return false;\n}\n\n\/\/ Reads the dimensions of the TIFF volume. X and Y come from the dimensions\n\/\/ of the first image in the stack: we assume that this stays constant\n\/\/ throughout the volume. Z comes from the number of images in the stack.\nstatic void\ntv_dimensions(TIFF *tif, size_t dims[3])\n{\n#ifndef TUVOK_NO_IO\n UINT32 x,y;\n size_t z=0;\n\n TIFFSetDirectory(tif, 0);\n TIFFGetField(tif, TIFFTAG_IMAGEWIDTH, &x);\n \/\/ tiff calls the height \"length\" for some reason.\n TIFFGetField(tif, TIFFTAG_IMAGELENGTH, &y);\n do {\n ++z;\n } while(TIFFReadDirectory(tif));\n TIFFSetDirectory(tif, 0);\n\n dims[0] = x;\n dims[1] = y;\n dims[2] = z;\n#endif\n}\n\n_malloc static BYTE*\ntv_read_slice(TIFF *tif)\n{\n#ifdef TUVOK_NO_IO\n return NULL;\n#else\n BYTE *slice;\n UINT32 width;\n UINT32 height;\n TIFFGetField(tif, TIFFTAG_IMAGEWIDTH, &width);\n TIFFGetField(tif, TIFFTAG_IMAGELENGTH, &height);\n\n MESSAGE(\"Reading %ux%u TIFF slice.\", width, height);\n slice = static_cast<BYTE*>(_TIFFmalloc((width*height) * sizeof(BYTE)));\n if(slice == NULL) {\n T_ERROR(\"TIFFmalloc failed.\");\n return NULL;\n }\n const tstrip_t n_strips = TIFFNumberOfStrips(tif);\n {\n BYTE *data = slice;\n tdata_t buf = static_cast<tdata_t>(_TIFFmalloc(TIFFStripSize(tif)));\n for(tstrip_t s=0; s < n_strips; ++s) {\n \/\/\/ @todo FIXME: don't assume the strip is raw; could be encoded.\n \/\/\/ There's a `compression scheme' tag which probably details this.\n tsize_t n_bytes = TIFFReadRawStrip(tif, s, buf,\n static_cast<tsize_t>(-1));\n std::memcpy(data, buf, n_bytes);\n data += TIFFStripSize(tif);\n }\n _TIFFfree(buf);\n }\n\n return slice;\n#endif\n}\n<commit_msg>Fix (null) in debug message.<commit_after>\/*\n For more information, please see: http:\/\/software.sci.utah.edu\n\n The MIT License\n\n Copyright (c) 2008 Scientific Computing and Imaging Institute,\n University of Utah.\n\n\n Permission is hereby granted, free of charge, to any person obtaining a\n copy of this software and associated documentation files (the \"Software\"),\n to deal in the Software without restriction, including without limitation\n the rights to use, copy, modify, merge, publish, distribute, sublicense,\n and\/or sell copies of the Software, and to permit persons to whom the\n Software is furnished to do so, subject to the following conditions:\n\n The above copyright notice and this permission notice shall be included\n in all copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n DEALINGS IN THE SOFTWARE.\n*\/\n\n\/**\n \\file TiffVolumeConverter.h\n \\author Tom Fogal\n SCI Institute\n University of Utah\n*\/\n#include <cstring>\n#include \"boost\/cstdint.hpp\"\n#ifndef TUVOK_NO_IO\n# include \"3rdParty\/tiff\/tiffio.h\"\n#else\n struct TIFF;\n#endif\n#include \"TiffVolumeConverter.h\"\n#include \"..\/StdTuvokDefines.h\"\n#include \"..\/Controller\/Controller.h\"\n#include \"..\/Basics\/SysTools.h\"\n\n#ifdef __GNUC__\n# define _malloc __attribute__((malloc))\n#else\n# define _malloc \/* nothing *\/\n#endif\n\nstatic void tv_dimensions(TIFF *, size_t dims[3]);\n_malloc static BYTE* tv_read_slice(TIFF *);\n\nTiffVolumeConverter::TiffVolumeConverter()\n{\n m_vConverterDesc = \"TIFF Volume (Image stack)\";\n#ifndef TUVOK_NO_IO\n m_vSupportedExt.push_back(\"OME.TIF\");\n m_vSupportedExt.push_back(\"OME.TIFF\");\n m_vSupportedExt.push_back(\"TIF\");\n m_vSupportedExt.push_back(\"TIFF\");\n#endif\n}\n\n\/\/ converts a TiffVolume to a `raw' file. We'll read through the TIFF\n\/\/ slice-by-slice, copying each slice to the raw file.\nbool\nTiffVolumeConverter::ConvertToRAW(const std::string& strSourceFilename,\n const std::string& strTempDir,\n bool, UINT64& iHeaderSkip,\n UINT64& iComponentSize,\n UINT64& iComponentCount,\n bool& bConvertEndianess, bool& bSigned,\n bool& bIsFloat, UINTVECTOR3& vVolumeSize,\n FLOATVECTOR3& vVolumeAspect,\n std::string& strTitle,\n UVFTables::ElementSemanticTable& eType,\n std::string& strIntermediateFile,\n bool& bDeleteIntermediateFile)\n{\n#ifndef TUVOK_NO_IO\n MESSAGE(\"Attempting to convert TiffVolume: %s\", strSourceFilename.c_str());\n\n TIFF *tif = TIFFOpen(strSourceFilename.c_str(), \"r\");\n if(tif == NULL) {\n T_ERROR(\"Could not open %s\", strSourceFilename.c_str());\n return false;\n }\n\n \/\/ Get the dimensions of the volume.\n {\n size_t dims[3];\n tv_dimensions(tif, dims);\n vVolumeSize[0] = UINT32(dims[0]);\n vVolumeSize[1] = UINT32(dims[1]);\n vVolumeSize[2] = UINT32(dims[2]);\n MESSAGE(\"TiffVolume dimensions: %ux%ux%u\", UINT32(dims[0]), UINT32(dims[1]), UINT32(dims[2]));\n if(dims[2] <= 1) {\n T_ERROR(\"TIFF is not a volume; use \"\n \"`Load Dataset from Directory' instead!\");\n TIFFClose(tif);\n return false;\n }\n }\n iHeaderSkip = 0;\n\n \/\/ read the number of bits per component from the tiff tag.\n {\n boost::uint16_t bits_per_sample;\n TIFFGetField(tif, TIFFTAG_BITSPERSAMPLE, &bits_per_sample);\n iComponentSize = bits_per_sample;\n MESSAGE(\"%ld bits per component.\", iComponentSize);\n }\n \/\/ likewise for the number of components \/ pixel.\n {\n boost::uint16_t components;\n TIFFGetField(tif, TIFFTAG_SAMPLESPERPIXEL, &components);\n iComponentCount = components;\n {\n std::ostringstream com;\n com << iComponentCount << \"component\";\n if(components > 1) { com << \"s\"; }\n com << \".\";\n MESSAGE(\"%s\", com.str().c_str());\n }\n }\n \/\/ IIRC libtiff handles all the endian issues for us.\n bConvertEndianess = false;\n\n \/\/ One might consider setting the values below explicitly as bugs, but we're\n \/\/ not quite sure where to read these from. In any case, we don't have any\n \/\/ data for which these settings are invalid.\n bSigned = false;\n bIsFloat = false;\n vVolumeAspect[0] = 1;\n vVolumeAspect[1] = 1;\n vVolumeAspect[2] = 1;\n\n strTitle = \"TIFF Volume\";\n eType = UVFTables::ES_UNDEFINED;\n\n \/\/ Create an intermediate file to hold the data.\n strIntermediateFile = strTempDir +\n SysTools::GetFilename(strSourceFilename) + \".binary\";\n LargeRAWFile binary(strIntermediateFile);\n binary.Create(iComponentSize\/8 * iComponentCount * vVolumeSize.volume());\n if(!binary.IsOpen()) {\n T_ERROR(\"Could not create binary file %s\", strIntermediateFile.c_str());\n \n TIFFClose(tif);\n return false;\n }\n bDeleteIntermediateFile = true;\n \/\/ Populate the intermediate file. We'll do this slice-by-slice, which isn't\n \/\/ exactly kosher in Tuvok -- a slice could technically be larger than\n \/\/ INCORESIZE. But it won't be.\n do {\n BYTE* slice = tv_read_slice(tif);\n if(slice) {\n \/\/ assuming 8-bit monochrome data here, which might not always be valid.\n binary.WriteRAW(static_cast<unsigned char*>(slice),\n vVolumeSize[0]*vVolumeSize[1]*sizeof(BYTE));\n _TIFFfree(slice);\n } else {\n binary.Close();\n binary.Delete();\n TIFFClose(tif);\n return false;\n }\n } while(TIFFReadDirectory(tif));\n binary.Close();\n\n TIFFClose(tif);\n return true;\n#else\n T_ERROR(\"Tuvok was not built with IO support!\");\n return false;\n#endif\n}\n\n\/\/ unimplemented!\nbool\nTiffVolumeConverter::ConvertToNative(const std::string&,\n const std::string&,\n UINT64, UINT64, \n UINT64, bool,\n bool,\n UINTVECTOR3,\n FLOATVECTOR3,\n bool)\n{\n return false;\n}\n\n\/\/ Reads the dimensions of the TIFF volume. X and Y come from the dimensions\n\/\/ of the first image in the stack: we assume that this stays constant\n\/\/ throughout the volume. Z comes from the number of images in the stack.\nstatic void\ntv_dimensions(TIFF *tif, size_t dims[3])\n{\n#ifndef TUVOK_NO_IO\n UINT32 x,y;\n size_t z=0;\n\n TIFFSetDirectory(tif, 0);\n TIFFGetField(tif, TIFFTAG_IMAGEWIDTH, &x);\n \/\/ tiff calls the height \"length\" for some reason.\n TIFFGetField(tif, TIFFTAG_IMAGELENGTH, &y);\n do {\n ++z;\n } while(TIFFReadDirectory(tif));\n TIFFSetDirectory(tif, 0);\n\n dims[0] = x;\n dims[1] = y;\n dims[2] = z;\n#endif\n}\n\n_malloc static BYTE*\ntv_read_slice(TIFF *tif)\n{\n#ifdef TUVOK_NO_IO\n return NULL;\n#else\n BYTE *slice;\n UINT32 width;\n UINT32 height;\n TIFFGetField(tif, TIFFTAG_IMAGEWIDTH, &width);\n TIFFGetField(tif, TIFFTAG_IMAGELENGTH, &height);\n\n MESSAGE(\"Reading %ux%u TIFF slice.\", width, height);\n slice = static_cast<BYTE*>(_TIFFmalloc((width*height) * sizeof(BYTE)));\n if(slice == NULL) {\n T_ERROR(\"TIFFmalloc failed.\");\n return NULL;\n }\n const tstrip_t n_strips = TIFFNumberOfStrips(tif);\n {\n BYTE *data = slice;\n tdata_t buf = static_cast<tdata_t>(_TIFFmalloc(TIFFStripSize(tif)));\n for(tstrip_t s=0; s < n_strips; ++s) {\n \/\/\/ @todo FIXME: don't assume the strip is raw; could be encoded.\n \/\/\/ There's a `compression scheme' tag which probably details this.\n tsize_t n_bytes = TIFFReadRawStrip(tif, s, buf,\n static_cast<tsize_t>(-1));\n std::memcpy(data, buf, n_bytes);\n data += TIFFStripSize(tif);\n }\n _TIFFfree(buf);\n }\n\n return slice;\n#endif\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 2012, 2017 ARM Limited\n * All rights reserved\n *\n * The license below extends only to copyright in the software and shall\n * not be construed as granting a license to any other intellectual\n * property including but not limited to intellectual property relating\n * to a hardware implementation of the functionality of the software\n * licensed hereunder. You may use the software subject to the license\n * terms below provided that you ensure that this notice is replicated\n * unmodified and in its entirety in all distributions of the software,\n * modified or unmodified, in source code or in binary form.\n *\n * Copyright (c) 2000-2005 The Regents of The University of Michigan\n * Copyright (c) 2008 The Hewlett-Packard Development Company\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met: redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer;\n * redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution;\n * neither the name of the copyright holders nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include <Python.h>\n\n#include \"sim\/init.hh\"\n\n#include <marshal.h>\n#include <zlib.h>\n\n#include <iostream>\n#include <list>\n#include <string>\n#include <vector>\n\n#include \"base\/compiler.hh\"\n#include \"base\/cprintf.hh\"\n#include \"base\/logging.hh\"\n#include \"base\/types.hh\"\n#include \"config\/have_protobuf.hh\"\n#include \"python\/pybind11\/pybind.hh\"\n#include \"sim\/async.hh\"\n\n#if HAVE_PROTOBUF\n#include <google\/protobuf\/stubs\/common.h>\n\n#endif\n\nnamespace py = pybind11;\n\nnamespace gem5\n{\n\n\/\/ The python library is totally messed up with respect to constness,\n\/\/ so make a simple macro to make life a little easier\n#define PyCC(x) (const_cast<char *>(x))\n\nEmbeddedPython::EmbeddedPython(const char *abspath, const char *modpath,\n const unsigned char *code, int zlen, int len)\n : abspath(abspath), modpath(modpath), code(code), zlen(zlen), len(len)\n{\n getList().push_back(this);\n}\n\nstd::list<EmbeddedPython *> &\nEmbeddedPython::getList()\n{\n static std::list<EmbeddedPython *> the_list;\n return the_list;\n}\n\n\/*\n * Uncompress and unmarshal the code object stored in the\n * EmbeddedPython\n *\/\nPyObject *\nEmbeddedPython::getCode() const\n{\n Bytef marshalled[len];\n uLongf unzlen = len;\n int ret = uncompress(marshalled, &unzlen, (const Bytef *)code, zlen);\n if (ret != Z_OK)\n panic(\"Could not uncompress code: %s\\n\", zError(ret));\n assert(unzlen == (uLongf)len);\n\n return PyMarshal_ReadObjectFromString((char *)marshalled, len);\n}\n\nbool\nEmbeddedPython::addModule() const\n{\n auto code = py::reinterpret_borrow<py::object>(getCode());\n \/\/ Ensure that \"code\" is not garbage collected.\n code.inc_ref();\n auto importer = py::module_::import(\"importer\");\n importer.attr(\"add_module\")(abspath, modpath, code);\n return true;\n}\n\n\/*\n * Load and initialize all of the python parts of M5.\n *\/\nint\nEmbeddedPython::initAll()\n{\n \/\/ Load the embedded python files into the embedded python importer.\n for (auto *embedded: getList()) {\n if (!embedded->addModule())\n return 1;\n }\n return 0;\n}\n\nEmbeddedPyBind::EmbeddedPyBind(const char *_name,\n void (*init_func)(py::module_ &),\n const char *_base)\n : initFunc(init_func), registered(false), name(_name), base(_base)\n{\n getMap()[_name] = this;\n}\n\nEmbeddedPyBind::EmbeddedPyBind(const char *_name,\n void (*init_func)(py::module_ &))\n : initFunc(init_func), registered(false), name(_name), base(\"\")\n{\n getMap()[_name] = this;\n}\n\nvoid\nEmbeddedPyBind::init(py::module_ &m)\n{\n if (!registered) {\n initFunc(m);\n registered = true;\n } else {\n cprintf(\"Warning: %s already registered.\\n\", name);\n }\n}\n\nbool\nEmbeddedPyBind::depsReady() const\n{\n return base.empty() || getMap()[base]->registered;\n}\n\nstd::map<std::string, EmbeddedPyBind *> &\nEmbeddedPyBind::getMap()\n{\n static std::map<std::string, EmbeddedPyBind *> objs;\n return objs;\n}\n\nPyObject *\nEmbeddedPyBind::initAll()\n{\n std::list<EmbeddedPyBind *> pending;\n\n \/\/ The PyModuleDef structure needs to live as long as the module it\n \/\/ defines, so we'll leak it here so it lives forever. This is what\n \/\/ pybind11 does internally in the module_ constructor we were using. We\n \/\/ could theoretically keep track of the lifetime of the _m5 module\n \/\/ somehow and clean this up when it goes away, but that doesn't seem\n \/\/ worth the effort. The docs recommend statically allocating it, but that\n \/\/ could be unsafe on the very slim chance this method is called more than\n \/\/ once.\n auto *py_mod_def = new py::module_::module_def;\n py::module_ m_m5 = py::module_::create_extension_module(\n \"_m5\", nullptr, py_mod_def);\n m_m5.attr(\"__package__\") = py::cast(\"_m5\");\n\n pybind_init_core(m_m5);\n pybind_init_debug(m_m5);\n\n pybind_init_event(m_m5);\n pybind_init_stats(m_m5);\n\n for (auto &kv : getMap()) {\n auto &obj = kv.second;\n if (obj->base.empty()) {\n obj->init(m_m5);\n } else {\n pending.push_back(obj);\n }\n }\n\n while (!pending.empty()) {\n for (auto it = pending.begin(); it != pending.end(); ) {\n EmbeddedPyBind &obj = **it;\n if (obj.depsReady()) {\n obj.init(m_m5);\n it = pending.erase(it);\n } else {\n ++it;\n }\n }\n }\n\n return m_m5.ptr();\n}\n\nvoid\nregisterNativeModules()\n{\n auto result = PyImport_AppendInittab(\"_m5\", EmbeddedPyBind::initAll);\n if (result == -1)\n panic(\"Failed to add _m5 to Python's inittab\\n\");\n}\n\n\/*\n * Make the commands array weak so that they can be overridden (used\n * by unit tests to specify a different python main function.\n *\/\nGEM5_WEAK const char *m5MainCommands[] = {\n \"import m5\",\n \"m5.main()\",\n 0 \/\/ sentinel is required\n};\n\n\/*\n * Start up the M5 simulator. This mostly vectors into the python\n * main function.\n *\/\nint\nm5Main(int argc, char **_argv)\n{\n#if HAVE_PROTOBUF\n \/\/ Verify that the version of the protobuf library that we linked\n \/\/ against is compatible with the version of the headers we\n \/\/ compiled against.\n GOOGLE_PROTOBUF_VERIFY_VERSION;\n#endif\n\n\n typedef std::unique_ptr<wchar_t[], decltype(&PyMem_RawFree)> WArgUPtr;\n std::vector<WArgUPtr> v_argv;\n std::vector<wchar_t *> vp_argv;\n v_argv.reserve(argc);\n vp_argv.reserve(argc);\n for (int i = 0; i < argc; i++) {\n v_argv.emplace_back(Py_DecodeLocale(_argv[i], NULL), &PyMem_RawFree);\n vp_argv.emplace_back(v_argv.back().get());\n }\n\n wchar_t **argv = vp_argv.data();\n\n PySys_SetArgv(argc, argv);\n\n \/\/ We have to set things up in the special __main__ module\n PyObject *module = PyImport_AddModule(PyCC(\"__main__\"));\n if (module == NULL)\n panic(\"Could not import __main__\");\n PyObject *dict = PyModule_GetDict(module);\n\n \/\/ import the main m5 module\n PyObject *result;\n const char **command = m5MainCommands;\n\n \/\/ evaluate each command in the m5MainCommands array (basically a\n \/\/ bunch of python statements.\n while (*command) {\n result = PyRun_String(*command, Py_file_input, dict, dict);\n if (!result) {\n PyErr_Print();\n return 1;\n }\n Py_DECREF(result);\n\n command++;\n }\n\n#if HAVE_PROTOBUF\n google::protobuf::ShutdownProtobufLibrary();\n#endif\n\n return 0;\n}\n\n} \/\/ namespace gem5\n<commit_msg>sim: Eliminate m5MainCommands and simplify calling m5.main.<commit_after>\/*\n * Copyright (c) 2012, 2017 ARM Limited\n * All rights reserved\n *\n * The license below extends only to copyright in the software and shall\n * not be construed as granting a license to any other intellectual\n * property including but not limited to intellectual property relating\n * to a hardware implementation of the functionality of the software\n * licensed hereunder. You may use the software subject to the license\n * terms below provided that you ensure that this notice is replicated\n * unmodified and in its entirety in all distributions of the software,\n * modified or unmodified, in source code or in binary form.\n *\n * Copyright (c) 2000-2005 The Regents of The University of Michigan\n * Copyright (c) 2008 The Hewlett-Packard Development Company\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met: redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer;\n * redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution;\n * neither the name of the copyright holders nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include <Python.h>\n\n#include \"sim\/init.hh\"\n\n#include <marshal.h>\n#include <zlib.h>\n\n#include <iostream>\n#include <list>\n#include <string>\n#include <vector>\n\n#include \"base\/compiler.hh\"\n#include \"base\/cprintf.hh\"\n#include \"base\/logging.hh\"\n#include \"base\/types.hh\"\n#include \"config\/have_protobuf.hh\"\n#include \"python\/pybind11\/pybind.hh\"\n#include \"sim\/async.hh\"\n\n#if HAVE_PROTOBUF\n#include <google\/protobuf\/stubs\/common.h>\n\n#endif\n\nnamespace py = pybind11;\n\nnamespace gem5\n{\n\n\/\/ The python library is totally messed up with respect to constness,\n\/\/ so make a simple macro to make life a little easier\n#define PyCC(x) (const_cast<char *>(x))\n\nEmbeddedPython::EmbeddedPython(const char *abspath, const char *modpath,\n const unsigned char *code, int zlen, int len)\n : abspath(abspath), modpath(modpath), code(code), zlen(zlen), len(len)\n{\n getList().push_back(this);\n}\n\nstd::list<EmbeddedPython *> &\nEmbeddedPython::getList()\n{\n static std::list<EmbeddedPython *> the_list;\n return the_list;\n}\n\n\/*\n * Uncompress and unmarshal the code object stored in the\n * EmbeddedPython\n *\/\nPyObject *\nEmbeddedPython::getCode() const\n{\n Bytef marshalled[len];\n uLongf unzlen = len;\n int ret = uncompress(marshalled, &unzlen, (const Bytef *)code, zlen);\n if (ret != Z_OK)\n panic(\"Could not uncompress code: %s\\n\", zError(ret));\n assert(unzlen == (uLongf)len);\n\n return PyMarshal_ReadObjectFromString((char *)marshalled, len);\n}\n\nbool\nEmbeddedPython::addModule() const\n{\n auto code = py::reinterpret_borrow<py::object>(getCode());\n \/\/ Ensure that \"code\" is not garbage collected.\n code.inc_ref();\n auto importer = py::module_::import(\"importer\");\n importer.attr(\"add_module\")(abspath, modpath, code);\n return true;\n}\n\n\/*\n * Load and initialize all of the python parts of M5.\n *\/\nint\nEmbeddedPython::initAll()\n{\n \/\/ Load the embedded python files into the embedded python importer.\n for (auto *embedded: getList()) {\n if (!embedded->addModule())\n return 1;\n }\n return 0;\n}\n\nEmbeddedPyBind::EmbeddedPyBind(const char *_name,\n void (*init_func)(py::module_ &),\n const char *_base)\n : initFunc(init_func), registered(false), name(_name), base(_base)\n{\n getMap()[_name] = this;\n}\n\nEmbeddedPyBind::EmbeddedPyBind(const char *_name,\n void (*init_func)(py::module_ &))\n : initFunc(init_func), registered(false), name(_name), base(\"\")\n{\n getMap()[_name] = this;\n}\n\nvoid\nEmbeddedPyBind::init(py::module_ &m)\n{\n if (!registered) {\n initFunc(m);\n registered = true;\n } else {\n cprintf(\"Warning: %s already registered.\\n\", name);\n }\n}\n\nbool\nEmbeddedPyBind::depsReady() const\n{\n return base.empty() || getMap()[base]->registered;\n}\n\nstd::map<std::string, EmbeddedPyBind *> &\nEmbeddedPyBind::getMap()\n{\n static std::map<std::string, EmbeddedPyBind *> objs;\n return objs;\n}\n\nPyObject *\nEmbeddedPyBind::initAll()\n{\n std::list<EmbeddedPyBind *> pending;\n\n \/\/ The PyModuleDef structure needs to live as long as the module it\n \/\/ defines, so we'll leak it here so it lives forever. This is what\n \/\/ pybind11 does internally in the module_ constructor we were using. We\n \/\/ could theoretically keep track of the lifetime of the _m5 module\n \/\/ somehow and clean this up when it goes away, but that doesn't seem\n \/\/ worth the effort. The docs recommend statically allocating it, but that\n \/\/ could be unsafe on the very slim chance this method is called more than\n \/\/ once.\n auto *py_mod_def = new py::module_::module_def;\n py::module_ m_m5 = py::module_::create_extension_module(\n \"_m5\", nullptr, py_mod_def);\n m_m5.attr(\"__package__\") = py::cast(\"_m5\");\n\n pybind_init_core(m_m5);\n pybind_init_debug(m_m5);\n\n pybind_init_event(m_m5);\n pybind_init_stats(m_m5);\n\n for (auto &kv : getMap()) {\n auto &obj = kv.second;\n if (obj->base.empty()) {\n obj->init(m_m5);\n } else {\n pending.push_back(obj);\n }\n }\n\n while (!pending.empty()) {\n for (auto it = pending.begin(); it != pending.end(); ) {\n EmbeddedPyBind &obj = **it;\n if (obj.depsReady()) {\n obj.init(m_m5);\n it = pending.erase(it);\n } else {\n ++it;\n }\n }\n }\n\n return m_m5.ptr();\n}\n\nvoid\nregisterNativeModules()\n{\n auto result = PyImport_AppendInittab(\"_m5\", EmbeddedPyBind::initAll);\n if (result == -1)\n panic(\"Failed to add _m5 to Python's inittab\\n\");\n}\n\n\/*\n * Start up the M5 simulator. This mostly vectors into the python\n * main function.\n *\/\nint\nm5Main(int argc, char **_argv)\n{\n#if HAVE_PROTOBUF\n \/\/ Verify that the version of the protobuf library that we linked\n \/\/ against is compatible with the version of the headers we\n \/\/ compiled against.\n GOOGLE_PROTOBUF_VERIFY_VERSION;\n#endif\n\n\n typedef std::unique_ptr<wchar_t[], decltype(&PyMem_RawFree)> WArgUPtr;\n std::vector<WArgUPtr> v_argv;\n std::vector<wchar_t *> vp_argv;\n v_argv.reserve(argc);\n vp_argv.reserve(argc);\n for (int i = 0; i < argc; i++) {\n v_argv.emplace_back(Py_DecodeLocale(_argv[i], NULL), &PyMem_RawFree);\n vp_argv.emplace_back(v_argv.back().get());\n }\n\n wchar_t **argv = vp_argv.data();\n\n PySys_SetArgv(argc, argv);\n\n try {\n py::module_::import(\"m5\").attr(\"main\")();\n } catch (py::error_already_set &e) {\n if (e.matches(PyExc_SystemExit))\n return e.value().attr(\"code\").cast<int>();\n\n std::cerr << e.what();\n return 1;\n }\n\n#if HAVE_PROTOBUF\n google::protobuf::ShutdownProtobufLibrary();\n#endif\n\n return 0;\n}\n\n} \/\/ namespace gem5\n<|endoftext|>"} {"text":"<commit_before>#pragma once\n\n#include <cstring>\n\n#include \"Core\/Pair.hpp\"\n#include \"Core\/Hash.hpp\"\n#include \"Math\/Math.hpp\"\n#include \"Memory\/Allocator.hpp\"\n\n\/\/ Based on https:\/\/github.com\/preshing\/CompareIntegerMaps\n\/\/ TODO: Make sure iterator will also go through zero pair\n\ntemplate <typename KeyType, typename ValueType>\nclass HashMap\n{\npublic:\n\tusing KeyValuePair = Pair<KeyType, ValueType>;\n\n\tclass Iterator\n\t{\n\tprivate:\n\t\tKeyValuePair* current;\n\t\tKeyValuePair* end; \/\/ We need end to know when to stop in operator++()\n\n\t\tfriend class HashMap;\n\n\tpublic:\n\t\tKeyValuePair& operator*() { return *current; }\n\t\tKeyValuePair* operator->() { return current; }\n\n\t\tbool operator==(Iterator other) const { return this->current == other.current; }\n\t\tbool operator!=(Iterator other) const { return operator==(other) == false; }\n\n\t\tIterator& operator++()\n\t\t{\n\t\t\tif (current == end)\n\t\t\t\treturn *this;\n\n\t\t\twhile (true)\n\t\t\t{\n\t\t\t\t++current;\n\n\t\t\t\tif (current == end || current->first)\n\t\t\t\t{\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn *this;\n\t\t}\n\n\t\tIterator operator++(int)\n\t\t{\n\t\t\tIterator itr = *this;\n\t\t\toperator++();\n\t\t\treturn itr;\n\t\t}\n\t};\n\nprivate:\n\tAllocator* allocator;\n\tKeyValuePair* data;\n\tunsigned int population;\n\tunsigned int allocated;\n\n\tbool zeroUsed;\n\tKeyValuePair zeroPair;\n\n\tunsigned int GetIndex(unsigned int hash) const { return hash & (allocated - 1); }\n\tunsigned int GetOffset(KeyValuePair* a, KeyValuePair* b) const\n\t{\n\t\treturn b >= a ? b - a : allocated + b - a;\n\t}\n\n\tvoid ReserveInternal(unsigned int desiredCount)\n\t{\n\t\tstd::size_t newSize = desiredCount * sizeof(KeyValuePair);\n\t\tKeyValuePair* newData = static_cast<KeyValuePair*>(allocator->Allocate(newSize));\n\t\tstd::memset(newData, 0, newSize);\n\n\t\tif (data != nullptr) \/\/ Old data exists\n\t\t{\n\t\t\tKeyValuePair* p = data;\n\t\t\tKeyValuePair* end = p + allocated;\n\t\t\tfor (; p != end; ++p)\n\t\t\t{\n\t\t\t\tif (p->first) \/\/ Pair has value\n\t\t\t\t{\n\t\t\t\t\tfor (unsigned int i = GetIndex(Hash::FNV1a_32(p->first));; i = GetIndex(i + 1))\n\t\t\t\t\t{\n\t\t\t\t\t\tif (!newData[i].first) \/\/ Insert here\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tnewData[i] = *p;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tallocator->Deallocate(data);\n\t\t}\n\n\t\tdata = newData;\n\t\tallocated = desiredCount;\n\t}\n\npublic:\n\tHashMap(Allocator* allocator) :\n\t\tallocator(allocator),\n\t\tdata(nullptr),\n\t\tpopulation(0),\n\t\tallocated(0),\n\t\tzeroUsed(false)\n\t{\n\t\tzeroPair = KeyValuePair{};\n\t}\n\n\t~HashMap()\n\t{\n\t\tif (data != nullptr)\n\t\t{\n\t\t\tKeyValuePair* itr = data;\n\t\t\tKeyValuePair* end = data + allocated;\n\t\t\tfor (; itr != end; ++itr)\n\t\t\t\tif (itr->first)\n\t\t\t\t\titr->second.~ValueType();\n\n\t\t\tallocator->Deallocate(data);\n\t\t}\n\t}\n\n\tIterator Begin()\n\t{\n\t\tIterator itr;\n\t\titr.end = this->data + this->allocated;\n\n\t\tif (this->data != nullptr)\n\t\t{\n\t\t\t\/\/ Start at one before this->data\n\t\t\titr.current = this->data - 1;\n\n\t\t\t\/\/ Find first valid item with the real increment operator\n\t\t\t++itr;\n\t\t}\n\t\telse\n\t\t\titr.current = itr.end;\n\n\t\treturn itr;\n\t}\n\n\tIterator End()\n\t{\n\t\tIterator itr;\n\t\titr.end = this->data + this->allocated;\n\t\titr.current = itr.end;\n\t\treturn itr;\n\t}\n\n\tKeyValuePair* Lookup(KeyType key)\n\t{\n\t\tif (key)\n\t\t{\n\t\t\tif (data != nullptr)\n\t\t\t{\n\t\t\t\tfor (unsigned int i = GetIndex(Hash::FNV1a_32(key));; i = GetIndex(i + 1))\n\t\t\t\t{\n\t\t\t\t\tKeyValuePair* pair = data + i;\n\n\t\t\t\t\tif (pair->first == key)\n\t\t\t\t\t\treturn pair;\n\n\t\t\t\t\tif (!pair->first)\n\t\t\t\t\t\treturn nullptr;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\telse if (zeroUsed)\n\t\t\treturn &zeroPair;\n\n\t\treturn nullptr;\n\t}\n\n\tKeyValuePair* Insert(KeyType key)\n\t{\n\t\tif (key)\n\t\t{\n\t\t\tif (data == nullptr)\n\t\t\t\tReserveInternal(16);\n\n\t\t\tfor (;;)\n\t\t\tfor (unsigned int i = GetIndex(Hash::FNV1a_32(key));; i = GetIndex(i + 1))\n\t\t\t{\n\t\t\t\tKeyValuePair* pair = data + i;\n\n\t\t\t\tif (pair->first == key) \/\/ Found\n\t\t\t\t\treturn pair;\n\n\t\t\t\tif (pair->first == 0) \/\/ Insert here\n\t\t\t\t{\n\t\t\t\t\tif ((population + 1) * 4 >= allocated * 3)\n\t\t\t\t\t{\n\t\t\t\t\t\tReserveInternal(allocated * 2);\n\t\t\t\t\t\tbreak; \/\/ Back to outer loop, find first again\n\t\t\t\t\t}\n\n\t\t\t\t\t++population;\n\t\t\t\t\tpair->first = key;\n\t\t\t\t\treturn pair;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif (zeroUsed == false)\n\t\t\t{\n\t\t\t\tzeroUsed = true;\n\t\t\t\t++population;\n\n\t\t\t\t\/\/ Even though we didn't use a regular slot, let's keep the sizing rules consistent\n\t\t\t\tif (population * 4 >= allocated * 3)\n\t\t\t\t\tReserveInternal(allocated * 2);\n\t\t\t}\n\n\t\t\treturn &zeroPair;\n\t\t}\n\t}\n\n\tvoid Remove(KeyValuePair* pair)\n\t{\n\t\tif (pair != &zeroPair)\n\t\t{\n\t\t\tif (data != nullptr &&\n\t\t\t\tpair >= data && pair < data + allocated &&\n\t\t\t\tpair->first)\n\t\t\t{\n\t\t\t\t\/\/ Remove this cell by shuffling neighboring cells\n\t\t\t\t\/\/ so there are no gaps in anyone's probe chain\n\t\t\t\tfor (unsigned int i = GetIndex(pair - data + 1);; i = GetIndex(i + 1))\n\t\t\t\t{\n\t\t\t\t\tKeyValuePair* neighbor = data + i;\n\n\t\t\t\t\tif (!neighbor->first)\n\t\t\t\t\t{\n\t\t\t\t\t\t\/\/ There's nobody to swap with. Go ahead and clear this cell, then return\n\t\t\t\t\t\tpair->first = KeyType{};\n\t\t\t\t\t\tpair->second = ValueType{};\n\t\t\t\t\t\tpopulation--;\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\n\t\t\t\t\tKeyValuePair* ideal = data + GetIndex(Hash::FNV1a_32(neighbor->first));\n\t\t\t\t\tif (GetOffset(ideal, pair) < GetOffset(ideal, neighbor))\n\t\t\t\t\t{\n\t\t\t\t\t\t\/\/ Swap with neighbor, then make neighbor the new cell to remove.\n\t\t\t\t\t\t*pair = *neighbor;\n\t\t\t\t\t\tpair = neighbor;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\telse if (zeroUsed) \/\/ Ignore if not in use\n\t\t{\n\t\t\tzeroUsed = false;\n\t\t\tpair->second = ValueType{};\n\t\t\tpopulation--;\n\t\t}\n\t}\n\n\tvoid Reserve(unsigned int desiredPopulation)\n\t{\n\t\tif (desiredPopulation < population)\n\t\t\treturn;\n\n\t\tunsigned int desiredSize = (desiredPopulation * 4 + 2) \/ 3;\n\n\t\t\/\/ Desired size is not a power-of-two\n\t\tif ((desiredSize & (desiredSize - 1)) != 0)\n\t\t\tdesiredSize = Math::UpperPowerOfTwo(desiredSize);\n\n\t\tthis->ReserveInternal(desiredSize);\n\t}\n};\n<commit_msg>Fix an issue in HashMap::ReserveInternal<commit_after>#pragma once\n\n#include <cstring>\n\n#include \"Core\/Pair.hpp\"\n#include \"Core\/Hash.hpp\"\n#include \"Math\/Math.hpp\"\n#include \"Memory\/Allocator.hpp\"\n\n\/\/ Based on https:\/\/github.com\/preshing\/CompareIntegerMaps\n\/\/ TODO: Make sure iterator will also go through zero pair\n\ntemplate <typename KeyType, typename ValueType>\nclass HashMap\n{\npublic:\n\tusing KeyValuePair = Pair<KeyType, ValueType>;\n\n\tclass Iterator\n\t{\n\tprivate:\n\t\tKeyValuePair* current;\n\t\tKeyValuePair* end; \/\/ We need end to know when to stop in operator++()\n\n\t\tfriend class HashMap;\n\n\tpublic:\n\t\tKeyValuePair& operator*() { return *current; }\n\t\tKeyValuePair* operator->() { return current; }\n\n\t\tbool operator==(Iterator other) const { return this->current == other.current; }\n\t\tbool operator!=(Iterator other) const { return operator==(other) == false; }\n\n\t\tIterator& operator++()\n\t\t{\n\t\t\tif (current == end)\n\t\t\t\treturn *this;\n\n\t\t\twhile (true)\n\t\t\t{\n\t\t\t\t++current;\n\n\t\t\t\tif (current == end || current->first)\n\t\t\t\t{\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn *this;\n\t\t}\n\n\t\tIterator operator++(int)\n\t\t{\n\t\t\tIterator itr = *this;\n\t\t\toperator++();\n\t\t\treturn itr;\n\t\t}\n\t};\n\nprivate:\n\tAllocator* allocator;\n\tKeyValuePair* data;\n\tunsigned int population;\n\tunsigned int allocated;\n\n\tbool zeroUsed;\n\tKeyValuePair zeroPair;\n\n\tunsigned int GetIndex(unsigned int hash) const { return hash & (allocated - 1); }\n\tunsigned int GetOffset(KeyValuePair* a, KeyValuePair* b) const\n\t{\n\t\treturn b >= a ? b - a : allocated + b - a;\n\t}\n\n\tvoid ReserveInternal(unsigned int desiredCount)\n\t{\n\t\tstd::size_t newSize = desiredCount * sizeof(KeyValuePair);\n\t\tKeyValuePair* newData = static_cast<KeyValuePair*>(allocator->Allocate(newSize));\n\t\tstd::memset(newData, 0, newSize);\n\n\t\tif (data != nullptr) \/\/ Old data exists\n\t\t{\n\t\t\tKeyValuePair* p = data;\n\t\t\tKeyValuePair* end = p + allocated;\n\n\t\t\t\/\/ this->allocated needs to be set here because GetIndex() uses it\n\t\t\tallocated = desiredCount;\n\n\t\t\tfor (; p != end; ++p)\n\t\t\t{\n\t\t\t\tif (p->first) \/\/ Pair has value\n\t\t\t\t{\n\t\t\t\t\tfor (unsigned int i = GetIndex(Hash::FNV1a_32(p->first));; i = GetIndex(i + 1))\n\t\t\t\t\t{\n\t\t\t\t\t\tif (!newData[i].first) \/\/ Insert here\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tnewData[i] = *p;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tallocator->Deallocate(data);\n\t\t}\n\t\telse\n\t\t\tallocated = desiredCount;\n\n\t\tdata = newData;\n\t}\n\npublic:\n\tHashMap(Allocator* allocator) :\n\t\tallocator(allocator),\n\t\tdata(nullptr),\n\t\tpopulation(0),\n\t\tallocated(0),\n\t\tzeroUsed(false)\n\t{\n\t\tzeroPair = KeyValuePair{};\n\t}\n\n\t~HashMap()\n\t{\n\t\tif (data != nullptr)\n\t\t{\n\t\t\tKeyValuePair* itr = data;\n\t\t\tKeyValuePair* end = data + allocated;\n\t\t\tfor (; itr != end; ++itr)\n\t\t\t\tif (itr->first)\n\t\t\t\t\titr->second.~ValueType();\n\n\t\t\tallocator->Deallocate(data);\n\t\t}\n\t}\n\n\tIterator Begin()\n\t{\n\t\tIterator itr;\n\t\titr.end = this->data + this->allocated;\n\n\t\tif (this->data != nullptr)\n\t\t{\n\t\t\t\/\/ Start at one before this->data\n\t\t\titr.current = this->data - 1;\n\n\t\t\t\/\/ Find first valid item with the real increment operator\n\t\t\t++itr;\n\t\t}\n\t\telse\n\t\t\titr.current = itr.end;\n\n\t\treturn itr;\n\t}\n\n\tIterator End()\n\t{\n\t\tIterator itr;\n\t\titr.end = this->data + this->allocated;\n\t\titr.current = itr.end;\n\t\treturn itr;\n\t}\n\n\tKeyValuePair* Lookup(KeyType key)\n\t{\n\t\tif (key)\n\t\t{\n\t\t\tif (data != nullptr)\n\t\t\t{\n\t\t\t\tfor (unsigned int i = GetIndex(Hash::FNV1a_32(key));; i = GetIndex(i + 1))\n\t\t\t\t{\n\t\t\t\t\tKeyValuePair* pair = data + i;\n\n\t\t\t\t\tif (pair->first == key)\n\t\t\t\t\t\treturn pair;\n\n\t\t\t\t\tif (!pair->first)\n\t\t\t\t\t\treturn nullptr;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\telse if (zeroUsed)\n\t\t\treturn &zeroPair;\n\n\t\treturn nullptr;\n\t}\n\n\tKeyValuePair* Insert(KeyType key)\n\t{\n\t\tif (key)\n\t\t{\n\t\t\tif (data == nullptr)\n\t\t\t\tReserveInternal(16);\n\n\t\t\tfor (;;)\n\t\t\tfor (unsigned int i = GetIndex(Hash::FNV1a_32(key));; i = GetIndex(i + 1))\n\t\t\t{\n\t\t\t\tKeyValuePair* pair = data + i;\n\n\t\t\t\tif (pair->first == key) \/\/ Found\n\t\t\t\t\treturn pair;\n\n\t\t\t\tif (pair->first == 0) \/\/ Insert here\n\t\t\t\t{\n\t\t\t\t\tif ((population + 1) * 4 >= allocated * 3)\n\t\t\t\t\t{\n\t\t\t\t\t\tReserveInternal(allocated * 2);\n\t\t\t\t\t\tbreak; \/\/ Back to outer loop, find first again\n\t\t\t\t\t}\n\n\t\t\t\t\t++population;\n\t\t\t\t\tpair->first = key;\n\t\t\t\t\treturn pair;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif (zeroUsed == false)\n\t\t\t{\n\t\t\t\tzeroUsed = true;\n\t\t\t\t++population;\n\n\t\t\t\t\/\/ Even though we didn't use a regular slot, let's keep the sizing rules consistent\n\t\t\t\tif (population * 4 >= allocated * 3)\n\t\t\t\t\tReserveInternal(allocated * 2);\n\t\t\t}\n\n\t\t\treturn &zeroPair;\n\t\t}\n\t}\n\n\tvoid Remove(KeyValuePair* pair)\n\t{\n\t\tif (pair != &zeroPair)\n\t\t{\n\t\t\tif (data != nullptr &&\n\t\t\t\tpair >= data && pair < data + allocated &&\n\t\t\t\tpair->first)\n\t\t\t{\n\t\t\t\t\/\/ Remove this cell by shuffling neighboring cells\n\t\t\t\t\/\/ so there are no gaps in anyone's probe chain\n\t\t\t\tfor (unsigned int i = GetIndex(pair - data + 1);; i = GetIndex(i + 1))\n\t\t\t\t{\n\t\t\t\t\tKeyValuePair* neighbor = data + i;\n\n\t\t\t\t\tif (!neighbor->first)\n\t\t\t\t\t{\n\t\t\t\t\t\t\/\/ There's nobody to swap with. Go ahead and clear this cell, then return\n\t\t\t\t\t\tpair->first = KeyType{};\n\t\t\t\t\t\tpair->second = ValueType{};\n\t\t\t\t\t\tpopulation--;\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\n\t\t\t\t\tKeyValuePair* ideal = data + GetIndex(Hash::FNV1a_32(neighbor->first));\n\t\t\t\t\tif (GetOffset(ideal, pair) < GetOffset(ideal, neighbor))\n\t\t\t\t\t{\n\t\t\t\t\t\t\/\/ Swap with neighbor, then make neighbor the new cell to remove.\n\t\t\t\t\t\t*pair = *neighbor;\n\t\t\t\t\t\tpair = neighbor;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\telse if (zeroUsed) \/\/ Ignore if not in use\n\t\t{\n\t\t\tzeroUsed = false;\n\t\t\tpair->second = ValueType{};\n\t\t\tpopulation--;\n\t\t}\n\t}\n\n\tvoid Reserve(unsigned int desiredPopulation)\n\t{\n\t\tif (desiredPopulation < population)\n\t\t\treturn;\n\n\t\tunsigned int desiredSize = (desiredPopulation * 4 + 2) \/ 3;\n\n\t\t\/\/ Desired size is not a power-of-two\n\t\tif ((desiredSize & (desiredSize - 1)) != 0)\n\t\t\tdesiredSize = Math::UpperPowerOfTwo(desiredSize);\n\n\t\tthis->ReserveInternal(desiredSize);\n\t}\n};\n<|endoftext|>"} {"text":"<commit_before>#include <ctime>\n#include <cstdio>\n#include <cstdlib>\n#include <cassert>\n\n#include <algorithm>\n#include <iostream>\n#include <fstream>\n\nusing namespace std;\n\nconst int _fail = 1;\nconst int _fail_to_run = 2;\nconst int _fail_to_check = 3;\n\nstring itos(int a)\n{\n string res = \"\";\n if (a == 0) return \"0\";\n while (a)\n {\n res += char(a % 10 + '0');\n a \/= 10;\n }\n reverse(res.begin(), res.end());\n return res;\n}\n\nint compileCppCode(int id)\n{\n if (system((\"cp .\/submissions\/\" + itos(id) + \".code .\/sandbox\/main.cpp\").c_str()))\n {\n cerr << \"Unable to copy file to sandbox\" << endl;\n exit(_fail);\n }\n string cmd = \"g++ .\/sandbox\/main.cpp -o .\/sandbox\/main \"\n \"-static -fno-optimize-sibling-calls -fno-strict-aliasing \"\n \"-DONLINE_JUDGE -lm -s -x c++ -O2 \"\n \"2>.\/submissions\/\" + itos(id) + \".compilationReport\";\n int res = system(cmd.c_str());\n system(\"rm -f .\/sandbox\/main.cpp\");\n return res;\n}\n\nint compilePascalCode(int id)\n{\n if (system((\"cp .\/submissions\/\" + itos(id) + \".code .\/sandbox\/main.pas\").c_str()))\n {\n cerr << \"Unable to copy file to sandbox\" << endl;\n exit(_fail);\n }\n string cmd = \"fpc -dOLINE_JUDGE -So -XS -O2 .\/sandbox\/main.pas \"\n \"> .\/submissions\/\" + itos(id) + \".compilationReport 2>&1 \";\n int res = system(cmd.c_str());\n system(\"rm -f .\/sandbox\/main.pas\");\n return res;\n}\n\nint compileJavaCode(int id)\n{\n\tif (system((\"cp .\/submissions\/\" + itos(id) + \".code .\/sandbox\/Main.java\").c_str()))\n\t{\n\t\tcerr << \"Unable to copy file to sandbox\" << endl;\n\t\texit(_fail);\n\t}\n\tsystem((\"cp .\/submissions\/\" + itos(id) + \".language .\/sandbox\/language\").c_str());\n\tstring cmd = \"javac -cp \\\".;*\\\" .\/sandbox\/Main.java \"\n\t\t\t\t \"> .\/submissions\/\" + itos(id) + \".compilationReport 2>&1 \";\n\tint res = system(cmd.c_str());\n\tsystem(\"rm -f .\/sandbox\/Main.java\");\n\treturn res;\n}\n\nvoid updateStatus(int id, const string &status)\n{\n ofstream st((\".\/submissions\/\" + itos(id) + \".status\").c_str());\n if (!st.is_open())\n {\n cerr << \"Unable to update status of submission\" << endl;\n exit(_fail);\n }\n st << status << endl;\n st.close();\n}\n\nstring getSubmissionLanguage(int id)\n{\n ifstream st((\".\/submissions\/\" + itos(id) + \".language\").c_str());\n if (!st.is_open())\n {\n cerr << \"Unable to fetch language of submission\" << endl;\n exit(_fail);\n }\n string lang;\n st >> lang;\n st.close();\n return lang;\n}\n\nstring getSubmissionProblem(int id)\n{\n ifstream st((\".\/submissions\/\" + itos(id) + \".problem\").c_str());\n if (!st.is_open())\n {\n cerr << \"Unable to fetch submission's problem\" << endl;\n exit(_fail);\n }\n string prob;\n st >> prob;\n st.close();\n return prob;\n}\n\nint getTesterExitCode()\n{\n ifstream st(\".\/sandbox\/testerExitCode\");\n if (!st.is_open())\n {\n cerr << \"Unable to fetch submission's problem\" << endl;\n exit(_fail);\n }\n int code;\n st >> code;\n st.close();\n return code;\n}\n\nint main(int argc, char** argv)\n{\n assert(argc == 2);\n int id = atoi(argv[1]);\n cerr << \"Testing started. SubmissionId = \" << id << endl;\n system((\"rm .\/submissions\/\" + string(argv[1]) + \".score\").c_str());\n updateStatus(id, \"testing\");\n\n string lang = getSubmissionLanguage(id);\n string problem = getSubmissionProblem(id);\n cerr << \"Problem = \" << problem << endl;\n cerr << \"Language = \" << lang << endl;\n\n int error = 0;\n if (lang == \"pascal\") error = compilePascalCode(id);\n else if (lang == \"cpp\") error = compileCppCode(id);\n else if (lang == \"java\") error = compileJavaCode(id);\n else\n {\n cerr << \"Unknown language\" << endl;\n return _fail;\n }\n\n if (!error)\n { \n system((\".\/tester tasks\/\" + problem + \" >.\/sandbox\/currentResult; echo $? >.\/sandbox\/testerExitCode\").c_str());\n int res = getTesterExitCode();\n if (res == _fail || res == _fail_to_run)\n {\n updateStatus(id, \"FAIL\");\n cerr << \"Fatal error occured while running. Abort testing.\" << endl;\n return _fail;\n }\n if (res == _fail_to_check)\n {\n updateStatus(id, \"FAIL\");\n cerr << \"Fatal error occured while checking. Abort testing.\" << endl;\n return _fail;\n }\n cerr << \"Submission successfully tested\" << endl;\n if (system((\"tasks\/\" + problem + \"\/grade \" + itos(id) + \" tasks\/\" + problem + \" <.\/sandbox\/currentResult\").c_str()))\n {\n updateStatus(id, \"FAIL\");\n cerr << \"Cannot grade submission. Abort testing.\" << endl;\n return _fail;\n }\n cerr << \"Submission successfully graded\" << endl;\n cerr << \"Testing completed\" << endl;\n updateStatus(id, \"tested\");\n \/\/system(\"rm -f .\/sandbox\/currentResult\");\n system(\"rm .\/sandbox\/language\");\n } \n else \n {\n updateStatus(id, \"CE\");\n cerr << \"Compilation error\" << endl;\n system((\"echo 0 >.\/submissions\/\" + itos(id) + \".score\").c_str());\n }\n return 0;\n}\n<commit_msg>Fix pascal compilation routine<commit_after>#include <ctime>\n#include <cstdio>\n#include <cstdlib>\n#include <cassert>\n\n#include <algorithm>\n#include <iostream>\n#include <fstream>\n\nusing namespace std;\n\nconst int _fail = 1;\nconst int _fail_to_run = 2;\nconst int _fail_to_check = 3;\n\nstring itos(int a)\n{\n string res = \"\";\n if (a == 0) return \"0\";\n while (a)\n {\n res += char(a % 10 + '0');\n a \/= 10;\n }\n reverse(res.begin(), res.end());\n return res;\n}\n\nint compileCppCode(int id)\n{\n if (system((\"cp .\/submissions\/\" + itos(id) + \".code .\/sandbox\/main.cpp\").c_str()))\n {\n cerr << \"Unable to copy file to sandbox\" << endl;\n exit(_fail);\n }\n string cmd = \"g++ .\/sandbox\/main.cpp -o .\/sandbox\/main \"\n \"-static -fno-optimize-sibling-calls -fno-strict-aliasing \"\n \"-DONLINE_JUDGE -lm -s -x c++ -O2 \"\n \"2>.\/submissions\/\" + itos(id) + \".compilationReport\";\n int res = system(cmd.c_str());\n system(\"rm -f .\/sandbox\/main.cpp\");\n return res;\n}\n\nint compilePascalCode(int id)\n{\n if (system((\"cp .\/submissions\/\" + itos(id) + \".code .\/sandbox\/main.pas\").c_str()))\n {\n cerr << \"Unable to copy file to sandbox\" << endl;\n exit(_fail);\n }\n string cmd = \"fpc -dONLINE_JUDGE -So -XS -O2 .\/sandbox\/main.pas \"\n \"> .\/submissions\/\" + itos(id) + \".compilationReport 2>&1 \";\n int res = system(cmd.c_str());\n system(\"rm -f .\/sandbox\/main.pas\");\n return res;\n}\n\nint compileJavaCode(int id)\n{\n\tif (system((\"cp .\/submissions\/\" + itos(id) + \".code .\/sandbox\/Main.java\").c_str()))\n\t{\n\t\tcerr << \"Unable to copy file to sandbox\" << endl;\n\t\texit(_fail);\n\t}\n\tsystem((\"cp .\/submissions\/\" + itos(id) + \".language .\/sandbox\/language\").c_str());\n\tstring cmd = \"javac -cp \\\".;*\\\" .\/sandbox\/Main.java \"\n\t\t\t\t \"> .\/submissions\/\" + itos(id) + \".compilationReport 2>&1 \";\n\tint res = system(cmd.c_str());\n\tsystem(\"rm -f .\/sandbox\/Main.java\");\n\treturn res;\n}\n\nvoid updateStatus(int id, const string &status)\n{\n ofstream st((\".\/submissions\/\" + itos(id) + \".status\").c_str());\n if (!st.is_open())\n {\n cerr << \"Unable to update status of submission\" << endl;\n exit(_fail);\n }\n st << status << endl;\n st.close();\n}\n\nstring getSubmissionLanguage(int id)\n{\n ifstream st((\".\/submissions\/\" + itos(id) + \".language\").c_str());\n if (!st.is_open())\n {\n cerr << \"Unable to fetch language of submission\" << endl;\n exit(_fail);\n }\n string lang;\n st >> lang;\n st.close();\n return lang;\n}\n\nstring getSubmissionProblem(int id)\n{\n ifstream st((\".\/submissions\/\" + itos(id) + \".problem\").c_str());\n if (!st.is_open())\n {\n cerr << \"Unable to fetch submission's problem\" << endl;\n exit(_fail);\n }\n string prob;\n st >> prob;\n st.close();\n return prob;\n}\n\nint getTesterExitCode()\n{\n ifstream st(\".\/sandbox\/testerExitCode\");\n if (!st.is_open())\n {\n cerr << \"Unable to fetch submission's problem\" << endl;\n exit(_fail);\n }\n int code;\n st >> code;\n st.close();\n return code;\n}\n\nint main(int argc, char** argv)\n{\n assert(argc == 2);\n int id = atoi(argv[1]);\n cerr << \"Testing started. SubmissionId = \" << id << endl;\n system((\"rm .\/submissions\/\" + string(argv[1]) + \".score\").c_str());\n updateStatus(id, \"testing\");\n\n string lang = getSubmissionLanguage(id);\n string problem = getSubmissionProblem(id);\n cerr << \"Problem = \" << problem << endl;\n cerr << \"Language = \" << lang << endl;\n\n int error = 0;\n if (lang == \"pascal\") error = compilePascalCode(id);\n else if (lang == \"cpp\") error = compileCppCode(id);\n else if (lang == \"java\") error = compileJavaCode(id);\n else\n {\n cerr << \"Unknown language\" << endl;\n return _fail;\n }\n\n if (!error)\n { \n system((\".\/tester tasks\/\" + problem + \" >.\/sandbox\/currentResult; echo $? >.\/sandbox\/testerExitCode\").c_str());\n int res = getTesterExitCode();\n if (res == _fail || res == _fail_to_run)\n {\n updateStatus(id, \"FAIL\");\n cerr << \"Fatal error occured while running. Abort testing.\" << endl;\n return _fail;\n }\n if (res == _fail_to_check)\n {\n updateStatus(id, \"FAIL\");\n cerr << \"Fatal error occured while checking. Abort testing.\" << endl;\n return _fail;\n }\n cerr << \"Submission successfully tested\" << endl;\n if (system((\"tasks\/\" + problem + \"\/grade \" + itos(id) + \" tasks\/\" + problem + \" <.\/sandbox\/currentResult\").c_str()))\n {\n updateStatus(id, \"FAIL\");\n cerr << \"Cannot grade submission. Abort testing.\" << endl;\n return _fail;\n }\n cerr << \"Submission successfully graded\" << endl;\n cerr << \"Testing completed\" << endl;\n updateStatus(id, \"tested\");\n \/\/system(\"rm -f .\/sandbox\/currentResult\");\n system(\"rm .\/sandbox\/language\");\n } \n else \n {\n updateStatus(id, \"CE\");\n cerr << \"Compilation error\" << endl;\n system((\"echo 0 >.\/submissions\/\" + itos(id) + \".score\").c_str());\n }\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012 Apple Inc. All rights reserved.\n *\n * Portions are Copyright (C) 1998 Netscape Communications Corporation.\n *\n * Other contributors:\n * Robert O'Callahan <roc+@cs.cmu.edu>\n * David Baron <dbaron@fas.harvard.edu>\n * Christian Biesinger <cbiesinger@web.de>\n * Randall Jesup <rjesup@wgate.com>\n * Roland Mainz <roland.mainz@informatik.med.uni-giessen.de>\n * Josh Soref <timeless@mac.com>\n * Boris Zbarsky <bzbarsky@mit.edu>\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n *\n * Alternatively, the contents of this file may be used under the terms\n * of either the Mozilla Public License Version 1.1, found at\n * http:\/\/www.mozilla.org\/MPL\/ (the \"MPL\") or the GNU General Public\n * License Version 2.0, found at http:\/\/www.fsf.org\/copyleft\/gpl.html\n * (the \"GPL\"), in which case the provisions of the MPL or the GPL are\n * applicable instead of those above. If you wish to allow use of your\n * version of this file only under the terms of one of those two\n * licenses (the MPL or the GPL) and not to allow others to use your\n * version of this file under the LGPL, indicate your decision by\n * deletingthe provisions above and replace them with the notice and\n * other provisions required by the MPL or the GPL, as the case may be.\n * If you do not delete the provisions above, a recipient may use your\n * version of this file under any of the LGPL, the MPL or the GPL.\n *\/\n\n#include \"config.h\"\n#include \"core\/rendering\/RenderLayerRepainter.h\"\n\n#include \"core\/rendering\/RenderLayer.h\"\n#include \"core\/rendering\/RenderLayerBacking.h\"\n#include \"core\/rendering\/RenderView.h\"\n\nnamespace WebCore {\n\nRenderLayerRepainter::RenderLayerRepainter(RenderLayerModelObject* renderer)\n : m_renderer(renderer)\n , m_repaintStatus(NeedsNormalRepaint)\n{\n}\n\nvoid RenderLayerRepainter::repaintAfterLayout(RenderGeometryMap* geometryMap, bool shouldCheckForRepaint)\n{\n if (m_renderer->layer()->hasVisibleContent()) {\n RenderView* view = m_renderer->view();\n ASSERT(view);\n \/\/ FIXME: LayoutState does not work with RenderLayers as there is not a 1-to-1\n \/\/ mapping between them and the RenderObjects. It would be neat to enable\n \/\/ LayoutState outside the layout() phase and use it here.\n ASSERT(!view->layoutStateEnabled());\n\n RenderLayerModelObject* repaintContainer = m_renderer->containerForRepaint();\n LayoutRect oldRepaintRect = m_repaintRect;\n LayoutRect oldOutlineBox = m_outlineBox;\n computeRepaintRects(repaintContainer, geometryMap);\n\n \/\/ FIXME: Should ASSERT that value calculated for m_outlineBox using the cached offset is the same\n \/\/ as the value not using the cached offset, but we can't due to https:\/\/bugs.webkit.org\/show_bug.cgi?id=37048\n if (shouldCheckForRepaint) {\n if (view && !view->document().printing()) {\n if (m_repaintStatus & NeedsFullRepaint) {\n m_renderer->repaintUsingContainer(repaintContainer, pixelSnappedIntRect(oldRepaintRect));\n if (m_repaintRect != oldRepaintRect)\n m_renderer->repaintUsingContainer(repaintContainer, pixelSnappedIntRect(m_repaintRect));\n } else if (shouldRepaintAfterLayout()) {\n m_renderer->repaintAfterLayoutIfNeeded(repaintContainer, oldRepaintRect, oldOutlineBox, &m_repaintRect, &m_outlineBox);\n }\n }\n }\n } else {\n clearRepaintRects();\n }\n\n m_repaintStatus = NeedsNormalRepaint;\n\n}\n\nvoid RenderLayerRepainter::clearRepaintRects()\n{\n ASSERT(!m_renderer->layer()->hasVisibleContent());\n\n m_repaintRect = IntRect();\n m_outlineBox = IntRect();\n}\n\nvoid RenderLayerRepainter::computeRepaintRects(const RenderLayerModelObject* repaintContainer, const RenderGeometryMap* geometryMap)\n{\n ASSERT(m_renderer->layer()->hasVisibleContent());\n\n m_repaintRect = m_renderer->clippedOverflowRectForRepaint(repaintContainer);\n m_outlineBox = m_renderer->outlineBoundsForRepaint(repaintContainer, geometryMap);\n}\n\nvoid RenderLayerRepainter::computeRepaintRectsIncludingDescendants()\n{\n \/\/ FIXME: computeRepaintRects() has to walk up the parent chain for every layer to compute the rects.\n \/\/ We should make this more efficient.\n \/\/ FIXME: it's wrong to call this when layout is not up-to-date, which we do.\n computeRepaintRects(m_renderer->containerForRepaint());\n\n for (RenderLayer* layer = m_renderer->layer()->firstChild(); layer; layer = layer->nextSibling())\n layer->repainter().computeRepaintRectsIncludingDescendants();\n}\n\ninline bool RenderLayerRepainter::shouldRepaintAfterLayout() const\n{\n if (m_repaintStatus == NeedsNormalRepaint)\n return true;\n\n \/\/ Composited layers that were moved during a positioned movement only\n \/\/ layout, don't need to be repainted. They just need to be recomposited.\n ASSERT(m_repaintStatus == NeedsFullRepaintForPositionedMovementLayout);\n return !m_renderer->isComposited() || (m_renderer->isComposited() && m_renderer->layer()->backing()->paintsIntoCompositedAncestor());\n}\n\n\/\/ Since we're only painting non-composited layers, we know that they all share the same repaintContainer.\nvoid RenderLayerRepainter::repaintIncludingNonCompositingDescendants(RenderLayerModelObject* repaintContainer)\n{\n m_renderer->repaintUsingContainer(repaintContainer, pixelSnappedIntRect(m_renderer->clippedOverflowRectForRepaint(repaintContainer)));\n\n for (RenderLayer* curr = m_renderer->layer()->firstChild(); curr; curr = curr->nextSibling()) {\n if (!curr->isComposited())\n curr->repainter().repaintIncludingNonCompositingDescendants(repaintContainer);\n }\n}\n\nLayoutRect RenderLayerRepainter::repaintRectIncludingNonCompositingDescendants() const\n{\n LayoutRect repaintRect = m_repaintRect;\n for (RenderLayer* child = m_renderer->layer()->firstChild(); child; child = child->nextSibling()) {\n \/\/ Don't include repaint rects for composited child layers; they will paint themselves and have a different origin.\n if (child->isComposited())\n continue;\n\n repaintRect.unite(child->repainter().repaintRectIncludingNonCompositingDescendants());\n }\n return repaintRect;\n}\n\n} \/\/ Namespace WebCore\n<commit_msg>Remove a triggering ASSERT<commit_after>\/*\n * Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012 Apple Inc. All rights reserved.\n *\n * Portions are Copyright (C) 1998 Netscape Communications Corporation.\n *\n * Other contributors:\n * Robert O'Callahan <roc+@cs.cmu.edu>\n * David Baron <dbaron@fas.harvard.edu>\n * Christian Biesinger <cbiesinger@web.de>\n * Randall Jesup <rjesup@wgate.com>\n * Roland Mainz <roland.mainz@informatik.med.uni-giessen.de>\n * Josh Soref <timeless@mac.com>\n * Boris Zbarsky <bzbarsky@mit.edu>\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n *\n * Alternatively, the contents of this file may be used under the terms\n * of either the Mozilla Public License Version 1.1, found at\n * http:\/\/www.mozilla.org\/MPL\/ (the \"MPL\") or the GNU General Public\n * License Version 2.0, found at http:\/\/www.fsf.org\/copyleft\/gpl.html\n * (the \"GPL\"), in which case the provisions of the MPL or the GPL are\n * applicable instead of those above. If you wish to allow use of your\n * version of this file only under the terms of one of those two\n * licenses (the MPL or the GPL) and not to allow others to use your\n * version of this file under the LGPL, indicate your decision by\n * deletingthe provisions above and replace them with the notice and\n * other provisions required by the MPL or the GPL, as the case may be.\n * If you do not delete the provisions above, a recipient may use your\n * version of this file under any of the LGPL, the MPL or the GPL.\n *\/\n\n#include \"config.h\"\n#include \"core\/rendering\/RenderLayerRepainter.h\"\n\n#include \"core\/rendering\/RenderLayer.h\"\n#include \"core\/rendering\/RenderLayerBacking.h\"\n#include \"core\/rendering\/RenderView.h\"\n\nnamespace WebCore {\n\nRenderLayerRepainter::RenderLayerRepainter(RenderLayerModelObject* renderer)\n : m_renderer(renderer)\n , m_repaintStatus(NeedsNormalRepaint)\n{\n}\n\nvoid RenderLayerRepainter::repaintAfterLayout(RenderGeometryMap* geometryMap, bool shouldCheckForRepaint)\n{\n if (m_renderer->layer()->hasVisibleContent()) {\n RenderView* view = m_renderer->view();\n ASSERT(view);\n \/\/ FIXME: LayoutState does not work with RenderLayers as there is not a 1-to-1\n \/\/ mapping between them and the RenderObjects. It would be neat to enable\n \/\/ LayoutState outside the layout() phase and use it here.\n ASSERT(!view->layoutStateEnabled());\n\n RenderLayerModelObject* repaintContainer = m_renderer->containerForRepaint();\n LayoutRect oldRepaintRect = m_repaintRect;\n LayoutRect oldOutlineBox = m_outlineBox;\n computeRepaintRects(repaintContainer, geometryMap);\n\n \/\/ FIXME: Should ASSERT that value calculated for m_outlineBox using the cached offset is the same\n \/\/ as the value not using the cached offset, but we can't due to https:\/\/bugs.webkit.org\/show_bug.cgi?id=37048\n if (shouldCheckForRepaint) {\n if (view && !view->document().printing()) {\n if (m_repaintStatus & NeedsFullRepaint) {\n m_renderer->repaintUsingContainer(repaintContainer, pixelSnappedIntRect(oldRepaintRect));\n if (m_repaintRect != oldRepaintRect)\n m_renderer->repaintUsingContainer(repaintContainer, pixelSnappedIntRect(m_repaintRect));\n } else if (shouldRepaintAfterLayout()) {\n m_renderer->repaintAfterLayoutIfNeeded(repaintContainer, oldRepaintRect, oldOutlineBox, &m_repaintRect, &m_outlineBox);\n }\n }\n }\n } else {\n clearRepaintRects();\n }\n\n m_repaintStatus = NeedsNormalRepaint;\n\n}\n\nvoid RenderLayerRepainter::clearRepaintRects()\n{\n ASSERT(!m_renderer->layer()->hasVisibleContent());\n\n m_repaintRect = IntRect();\n m_outlineBox = IntRect();\n}\n\nvoid RenderLayerRepainter::computeRepaintRects(const RenderLayerModelObject* repaintContainer, const RenderGeometryMap* geometryMap)\n{\n m_repaintRect = m_renderer->clippedOverflowRectForRepaint(repaintContainer);\n m_outlineBox = m_renderer->outlineBoundsForRepaint(repaintContainer, geometryMap);\n}\n\nvoid RenderLayerRepainter::computeRepaintRectsIncludingDescendants()\n{\n \/\/ FIXME: computeRepaintRects() has to walk up the parent chain for every layer to compute the rects.\n \/\/ We should make this more efficient.\n \/\/ FIXME: it's wrong to call this when layout is not up-to-date, which we do.\n computeRepaintRects(m_renderer->containerForRepaint());\n\n for (RenderLayer* layer = m_renderer->layer()->firstChild(); layer; layer = layer->nextSibling())\n layer->repainter().computeRepaintRectsIncludingDescendants();\n}\n\ninline bool RenderLayerRepainter::shouldRepaintAfterLayout() const\n{\n if (m_repaintStatus == NeedsNormalRepaint)\n return true;\n\n \/\/ Composited layers that were moved during a positioned movement only\n \/\/ layout, don't need to be repainted. They just need to be recomposited.\n ASSERT(m_repaintStatus == NeedsFullRepaintForPositionedMovementLayout);\n return !m_renderer->isComposited() || (m_renderer->isComposited() && m_renderer->layer()->backing()->paintsIntoCompositedAncestor());\n}\n\n\/\/ Since we're only painting non-composited layers, we know that they all share the same repaintContainer.\nvoid RenderLayerRepainter::repaintIncludingNonCompositingDescendants(RenderLayerModelObject* repaintContainer)\n{\n m_renderer->repaintUsingContainer(repaintContainer, pixelSnappedIntRect(m_renderer->clippedOverflowRectForRepaint(repaintContainer)));\n\n for (RenderLayer* curr = m_renderer->layer()->firstChild(); curr; curr = curr->nextSibling()) {\n if (!curr->isComposited())\n curr->repainter().repaintIncludingNonCompositingDescendants(repaintContainer);\n }\n}\n\nLayoutRect RenderLayerRepainter::repaintRectIncludingNonCompositingDescendants() const\n{\n LayoutRect repaintRect = m_repaintRect;\n for (RenderLayer* child = m_renderer->layer()->firstChild(); child; child = child->nextSibling()) {\n \/\/ Don't include repaint rects for composited child layers; they will paint themselves and have a different origin.\n if (child->isComposited())\n continue;\n\n repaintRect.unite(child->repainter().repaintRectIncludingNonCompositingDescendants());\n }\n return repaintRect;\n}\n\n} \/\/ Namespace WebCore\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2021 Google LLC\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \"google\/cloud\/storage\/internal\/object_read_streambuf.h\"\n#include \"google\/cloud\/storage\/hash_mismatch_error.h\"\n#include \"absl\/memory\/memory.h\"\n#include <cstring>\n\nnamespace google {\nnamespace cloud {\nnamespace storage {\ninline namespace STORAGE_CLIENT_NS {\nnamespace internal {\n\nObjectReadStreambuf::ObjectReadStreambuf(\n ReadObjectRangeRequest const& request,\n std::unique_ptr<ObjectReadSource> source, std::streamoff pos_in_stream)\n : source_(std::move(source)),\n source_pos_(pos_in_stream),\n hash_validator_(CreateHashValidator(request)) {}\n\nObjectReadStreambuf::ObjectReadStreambuf(ReadObjectRangeRequest const&,\n Status status)\n : source_(new ObjectReadErrorSource(status)),\n source_pos_(-1),\n hash_validator_(absl::make_unique<NullHashValidator>()),\n status_(std::move(status)) {}\n\nObjectReadStreambuf::pos_type ObjectReadStreambuf::seekpos(\n pos_type \/*pos*\/, std::ios_base::openmode \/*which*\/) {\n \/\/ TODO(#4013): Implement proper seeking.\n return -1;\n}\n\nObjectReadStreambuf::pos_type ObjectReadStreambuf::seekoff(\n off_type off, std::ios_base::seekdir dir, std::ios_base::openmode which) {\n \/\/ TODO(#4013): Implement proper seeking.\n \/\/ Seeking is non-trivial because the hash validator and `source_` have to be\n \/\/ recreated in the general case, which doesn't fit the current code\n \/\/ organization. We can, however, at least implement the bare minimum of this\n \/\/ function allowing `tellg()` to work.\n if (which == std::ios_base::in && dir == std::ios_base::cur && off == 0) {\n return source_pos_ - in_avail();\n }\n return -1;\n}\n\nbool ObjectReadStreambuf::IsOpen() const { return source_->IsOpen(); }\n\nvoid ObjectReadStreambuf::Close() {\n auto response = source_->Close();\n if (!response.ok()) {\n ReportError(std::move(response).status());\n }\n}\n\nObjectReadStreambuf::int_type ObjectReadStreambuf::ReportError(Status status) {\n \/\/ The only way to report errors from a std::basic_streambuf<> (which this\n \/\/ class derives from) is to throw exceptions:\n \/\/ https:\/\/stackoverflow.com\/questions\/50716688\/how-to-set-the-badbit-of-a-stream-by-a-customized-streambuf\n \/\/ but we need to be able to report errors when the application has disabled\n \/\/ exceptions via `-fno-exceptions` or a similar option. In that case we set\n \/\/ `status_`, and report the error as an EOF. This is obviously not ideal,\n \/\/ but it is the best we can do when the application disables the standard\n \/\/ mechanism to signal errors.\n if (status.ok()) {\n return traits_type::eof();\n }\n status_ = std::move(status);\n#if GOOGLE_CLOUD_CPP_HAVE_EXCEPTIONS\n google::cloud::internal::ThrowStatus(status_);\n#else\n return traits_type::eof();\n#endif \/\/ GOOGLE_CLOUD_CPP_HAVE_EXCEPTIONS\n}\n\nvoid ObjectReadStreambuf::ThrowHashMismatchDelegate(const char* function_name) {\n std::string msg;\n msg += function_name;\n msg += \"(): mismatched hashes in download\";\n msg += \", computed=\";\n msg += computed_hash();\n msg += \", received=\";\n msg += received_hash();\n if (status_.ok()) {\n \/\/ If there is an existing error, we should report that instead because\n \/\/ it is more specific, for example, every permanent network error will\n \/\/ produce invalid checksums, but that is not the interesting information.\n status_ = Status(StatusCode::kDataLoss, msg);\n }\n#if GOOGLE_CLOUD_CPP_HAVE_EXCEPTIONS\n \/\/ The only way to report errors from a std::basic_streambuf<> (which this\n \/\/ class derives from) is to throw exceptions:\n \/\/ https:\/\/stackoverflow.com\/questions\/50716688\/how-to-set-the-badbit-of-a-stream-by-a-customized-streambuf\n \/\/ but we need to be able to report errors when the application has\n \/\/ disabled exceptions via `-fno-exceptions` or a similar option. In that\n \/\/ case we set `status_`, and report the error as an 0-byte read. This is\n \/\/ obviously not ideal, but it is the best we can do when the application\n \/\/ disables the standard mechanism to signal errors.\n throw HashMismatchError(msg, received_hash(), computed_hash());\n#endif \/\/ GOOGLE_CLOUD_CPP_HAVE_EXCEPTIONS\n}\n\nbool ObjectReadStreambuf::ValidateHashes(char const* function_name) {\n \/\/ This function is called once the stream is \"closed\" (either an explicit\n \/\/ `Close()` call or a permanent error). After this point the validator is\n \/\/ not usable.\n auto validator = std::move(hash_validator_);\n hash_validator_result_ = std::move(*validator).Finish();\n if (!hash_validator_result_.is_mismatch) return true;\n ThrowHashMismatchDelegate(function_name);\n return false;\n}\n\nbool ObjectReadStreambuf::CheckPreconditions(char const* function_name) {\n if (hash_validator_result_.is_mismatch) {\n ThrowHashMismatchDelegate(function_name);\n }\n if (in_avail() != 0) return true;\n return status_.ok() && IsOpen();\n}\n\nObjectReadStreambuf::int_type ObjectReadStreambuf::underflow() {\n if (!CheckPreconditions(__func__)) return traits_type::eof();\n\n \/\/ If this function is called, then the internal buffer must be empty. We will\n \/\/ perform a read into a new buffer and reset the input area to use this\n \/\/ buffer.\n auto constexpr kInitialPeekRead = 128 * 1024;\n std::vector<char> buffer(kInitialPeekRead);\n auto const offset = xsgetn(buffer.data(), kInitialPeekRead);\n if (offset == 0) return traits_type::eof();\n\n buffer.resize(offset);\n buffer.swap(current_ios_buffer_);\n char* data = current_ios_buffer_.data();\n setg(data, data, data + current_ios_buffer_.size());\n return traits_type::to_int_type(*data);\n}\n\nstd::streamsize ObjectReadStreambuf::xsgetn(char* s, std::streamsize count) {\n if (!CheckPreconditions(__func__)) return 0;\n\n \/\/ This function optimizes stream.read(), the data is copied directly from the\n \/\/ data source (typically libcurl) into a buffer provided by the application.\n std::streamsize offset = 0;\n\n \/\/ Maybe the internal get area is enough to satisfy this request, no need to\n \/\/ read more in that case:\n auto from_internal = (std::min)(count, in_avail());\n if (from_internal > 0) {\n std::memcpy(s, gptr(), static_cast<std::size_t>(from_internal));\n }\n gbump(static_cast<int>(from_internal));\n offset += from_internal;\n \/\/ If we got all the data requested, there is no need for additional reads.\n \/\/ Likewise, if the underlying transport is closed, whatever we got is all the\n \/\/ data available.\n if (offset >= count || !IsOpen()) return offset;\n\n auto const* function_name = __func__;\n auto run_validator_if_closed = [this, function_name, &offset](Status s) {\n ReportError(std::move(s));\n \/\/ Only validate the checksums once the stream is closed.\n if (IsOpen()) return offset;\n return ValidateHashes(function_name) ? offset : 0;\n };\n\n StatusOr<ReadSourceResult> read =\n source_->Read(s + offset, static_cast<std::size_t>(count - offset));\n \/\/ If there was an error set the internal state, but we still return the\n \/\/ number of bytes.\n if (!read) return run_validator_if_closed(std::move(read).status());\n\n hash_validator_->Update(s + offset, read->bytes_received);\n offset += static_cast<std::streamsize>(read->bytes_received);\n source_pos_ += static_cast<std::streamoff>(read->bytes_received);\n\n for (auto const& kv : read->response.headers) {\n hash_validator_->ProcessHeader(kv.first, kv.second);\n headers_.emplace(kv.first, kv.second);\n }\n return run_validator_if_closed(Status());\n}\n\n} \/\/ namespace internal\n} \/\/ namespace STORAGE_CLIENT_NS\n} \/\/ namespace storage\n} \/\/ namespace cloud\n} \/\/ namespace google\n<commit_msg>fix(storage): build with MSVC+x86 (#6986)<commit_after>\/\/ Copyright 2021 Google LLC\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \"google\/cloud\/storage\/internal\/object_read_streambuf.h\"\n#include \"google\/cloud\/storage\/hash_mismatch_error.h\"\n#include \"absl\/memory\/memory.h\"\n#include <cstring>\n\nnamespace google {\nnamespace cloud {\nnamespace storage {\ninline namespace STORAGE_CLIENT_NS {\nnamespace internal {\n\nObjectReadStreambuf::ObjectReadStreambuf(\n ReadObjectRangeRequest const& request,\n std::unique_ptr<ObjectReadSource> source, std::streamoff pos_in_stream)\n : source_(std::move(source)),\n source_pos_(pos_in_stream),\n hash_validator_(CreateHashValidator(request)) {}\n\nObjectReadStreambuf::ObjectReadStreambuf(ReadObjectRangeRequest const&,\n Status status)\n : source_(new ObjectReadErrorSource(status)),\n source_pos_(-1),\n hash_validator_(absl::make_unique<NullHashValidator>()),\n status_(std::move(status)) {}\n\nObjectReadStreambuf::pos_type ObjectReadStreambuf::seekpos(\n pos_type \/*pos*\/, std::ios_base::openmode \/*which*\/) {\n \/\/ TODO(#4013): Implement proper seeking.\n return -1;\n}\n\nObjectReadStreambuf::pos_type ObjectReadStreambuf::seekoff(\n off_type off, std::ios_base::seekdir dir, std::ios_base::openmode which) {\n \/\/ TODO(#4013): Implement proper seeking.\n \/\/ Seeking is non-trivial because the hash validator and `source_` have to be\n \/\/ recreated in the general case, which doesn't fit the current code\n \/\/ organization. We can, however, at least implement the bare minimum of this\n \/\/ function allowing `tellg()` to work.\n if (which == std::ios_base::in && dir == std::ios_base::cur && off == 0) {\n return source_pos_ - in_avail();\n }\n return -1;\n}\n\nbool ObjectReadStreambuf::IsOpen() const { return source_->IsOpen(); }\n\nvoid ObjectReadStreambuf::Close() {\n auto response = source_->Close();\n if (!response.ok()) {\n ReportError(std::move(response).status());\n }\n}\n\nObjectReadStreambuf::int_type ObjectReadStreambuf::ReportError(Status status) {\n \/\/ The only way to report errors from a std::basic_streambuf<> (which this\n \/\/ class derives from) is to throw exceptions:\n \/\/ https:\/\/stackoverflow.com\/questions\/50716688\/how-to-set-the-badbit-of-a-stream-by-a-customized-streambuf\n \/\/ but we need to be able to report errors when the application has disabled\n \/\/ exceptions via `-fno-exceptions` or a similar option. In that case we set\n \/\/ `status_`, and report the error as an EOF. This is obviously not ideal,\n \/\/ but it is the best we can do when the application disables the standard\n \/\/ mechanism to signal errors.\n if (status.ok()) {\n return traits_type::eof();\n }\n status_ = std::move(status);\n#if GOOGLE_CLOUD_CPP_HAVE_EXCEPTIONS\n google::cloud::internal::ThrowStatus(status_);\n#else\n return traits_type::eof();\n#endif \/\/ GOOGLE_CLOUD_CPP_HAVE_EXCEPTIONS\n}\n\nvoid ObjectReadStreambuf::ThrowHashMismatchDelegate(const char* function_name) {\n std::string msg;\n msg += function_name;\n msg += \"(): mismatched hashes in download\";\n msg += \", computed=\";\n msg += computed_hash();\n msg += \", received=\";\n msg += received_hash();\n if (status_.ok()) {\n \/\/ If there is an existing error, we should report that instead because\n \/\/ it is more specific, for example, every permanent network error will\n \/\/ produce invalid checksums, but that is not the interesting information.\n status_ = Status(StatusCode::kDataLoss, msg);\n }\n#if GOOGLE_CLOUD_CPP_HAVE_EXCEPTIONS\n \/\/ The only way to report errors from a std::basic_streambuf<> (which this\n \/\/ class derives from) is to throw exceptions:\n \/\/ https:\/\/stackoverflow.com\/questions\/50716688\/how-to-set-the-badbit-of-a-stream-by-a-customized-streambuf\n \/\/ but we need to be able to report errors when the application has\n \/\/ disabled exceptions via `-fno-exceptions` or a similar option. In that\n \/\/ case we set `status_`, and report the error as an 0-byte read. This is\n \/\/ obviously not ideal, but it is the best we can do when the application\n \/\/ disables the standard mechanism to signal errors.\n throw HashMismatchError(msg, received_hash(), computed_hash());\n#endif \/\/ GOOGLE_CLOUD_CPP_HAVE_EXCEPTIONS\n}\n\nbool ObjectReadStreambuf::ValidateHashes(char const* function_name) {\n \/\/ This function is called once the stream is \"closed\" (either an explicit\n \/\/ `Close()` call or a permanent error). After this point the validator is\n \/\/ not usable.\n auto validator = std::move(hash_validator_);\n hash_validator_result_ = std::move(*validator).Finish();\n if (!hash_validator_result_.is_mismatch) return true;\n ThrowHashMismatchDelegate(function_name);\n return false;\n}\n\nbool ObjectReadStreambuf::CheckPreconditions(char const* function_name) {\n if (hash_validator_result_.is_mismatch) {\n ThrowHashMismatchDelegate(function_name);\n }\n if (in_avail() != 0) return true;\n return status_.ok() && IsOpen();\n}\n\nObjectReadStreambuf::int_type ObjectReadStreambuf::underflow() {\n if (!CheckPreconditions(__func__)) return traits_type::eof();\n\n \/\/ If this function is called, then the internal buffer must be empty. We will\n \/\/ perform a read into a new buffer and reset the input area to use this\n \/\/ buffer.\n auto constexpr kInitialPeekRead = 128 * 1024;\n std::vector<char> buffer(kInitialPeekRead);\n auto const offset = xsgetn(buffer.data(), kInitialPeekRead);\n if (offset == 0) return traits_type::eof();\n\n buffer.resize(static_cast<std::size_t>(offset));\n buffer.swap(current_ios_buffer_);\n char* data = current_ios_buffer_.data();\n setg(data, data, data + current_ios_buffer_.size());\n return traits_type::to_int_type(*data);\n}\n\nstd::streamsize ObjectReadStreambuf::xsgetn(char* s, std::streamsize count) {\n if (!CheckPreconditions(__func__)) return 0;\n\n \/\/ This function optimizes stream.read(), the data is copied directly from the\n \/\/ data source (typically libcurl) into a buffer provided by the application.\n std::streamsize offset = 0;\n\n \/\/ Maybe the internal get area is enough to satisfy this request, no need to\n \/\/ read more in that case:\n auto from_internal = (std::min)(count, in_avail());\n if (from_internal > 0) {\n std::memcpy(s, gptr(), static_cast<std::size_t>(from_internal));\n }\n gbump(static_cast<int>(from_internal));\n offset += from_internal;\n \/\/ If we got all the data requested, there is no need for additional reads.\n \/\/ Likewise, if the underlying transport is closed, whatever we got is all the\n \/\/ data available.\n if (offset >= count || !IsOpen()) return offset;\n\n auto const* function_name = __func__;\n auto run_validator_if_closed = [this, function_name, &offset](Status s) {\n ReportError(std::move(s));\n \/\/ Only validate the checksums once the stream is closed.\n if (IsOpen()) return offset;\n return ValidateHashes(function_name) ? offset : 0;\n };\n\n StatusOr<ReadSourceResult> read =\n source_->Read(s + offset, static_cast<std::size_t>(count - offset));\n \/\/ If there was an error set the internal state, but we still return the\n \/\/ number of bytes.\n if (!read) return run_validator_if_closed(std::move(read).status());\n\n hash_validator_->Update(s + offset, read->bytes_received);\n offset += static_cast<std::streamsize>(read->bytes_received);\n source_pos_ += static_cast<std::streamoff>(read->bytes_received);\n\n for (auto const& kv : read->response.headers) {\n hash_validator_->ProcessHeader(kv.first, kv.second);\n headers_.emplace(kv.first, kv.second);\n }\n return run_validator_if_closed(Status());\n}\n\n} \/\/ namespace internal\n} \/\/ namespace STORAGE_CLIENT_NS\n} \/\/ namespace storage\n} \/\/ namespace cloud\n} \/\/ namespace google\n<|endoftext|>"} {"text":"<commit_before>#include <array>\n#include <stdio.h>\n#include <stdlib.h>\n#include <assert.h>\n#include <time.h>\n#include <math.h>\n#include <omp.h>\n\n#include <xmmintrin.h>\n#include <pmmintrin.h>\n\n#include \"main.hpp\"\n#include \"min_heap.hpp\"\n#include \"universe.hpp\"\n\n#define IACA_SSC_MARK( MARK_ID )\t\t\t\t\t\t\\\n__asm__ __volatile__ (\t\t\t\t\t\t\t\t\\\n\t\t\t\t\t \"\\n\\t movl $\"#MARK_ID\", %%ebx\"\t\\\n\t\t\t\t\t \"\\n\\t .byte 0x64, 0x67, 0x90\"\t\\\n\t\t\t\t\t : : : \"memory\" );\n\n#define IACA_START {IACA_SSC_MARK(111)}\n#define IACA_END {IACA_SSC_MARK(222)}\n\n#define AU_TO_M 149597870700.0\n#define LY_TO_M 9460730472580800.0\n\n#if defined(__AVX__)\n#include <immintrin.h>\n#define VECTOR_WIDTH 8\ntypedef __m256 vector_type;\n#elif defined(__SSE__)\n#define VECTOR_WIDTH 4\ntypedef __m128 vector_type;\n#else\n#error \"Here's a nickel kid, buy yourself a real computer.\"\n#endif\n\nenum measurement_point {\n MB_TOTAL_START, MB_TOTAL_END,\n MB_INIT_START, MB_INIT_END,\n MB_SYSTEM_START, MB_SYSTEM_END,\n MB_GATE_START, MB_GATE_END,\n MB_JUMP_START, MB_JUMP_END,\n MB_SELECT_START, MB_SELECT_END,\n MB_MAX\n};\n\nstatic struct timespec mbt[MB_MAX];\nstatic long mba[MB_MAX] = {0};\n\nstatic void update_timers(enum measurement_point p) {\n if (verbose >= 1) {\n clock_gettime(CLOCK_MONOTONIC, &mbt[p]);\n mba[p] += time_diff(&mbt[p - 1], &mbt[p]);\n }\n}\n\ninline float __attribute__((always_inline)) entity_distance(Celestial *a, Celestial *b) {\n if (a->system != b->system) return INFINITY;\n\n float dx = a->pos[0] - b->pos[0];\n float dy = a->pos[1] - b->pos[1];\n float dz = a->pos[2] - b->pos[2];\n\n return sqrt(dx * dx + dy * dy + dz * dz);\n}\n\ndouble get_time(double distance, double v_wrp) {\n double k_accel = v_wrp;\n double k_decel = (v_wrp \/ 3) < 2 ? (v_wrp \/ 3) : 2;\n\n double v_max_wrp = v_wrp * AU_TO_M;\n\n double d_accel = AU_TO_M;\n double d_decel = v_max_wrp \/ k_decel;\n\n double d_min = d_accel + d_decel;\n\n double cruise_time = 0;\n\n if (d_min > distance) {\n v_max_wrp = distance * k_accel * k_decel \/ (k_accel + k_decel);\n } else {\n cruise_time = (distance - d_min) \/ v_max_wrp;\n }\n\n double t_accel = log(v_max_wrp \/ k_accel) \/ k_accel;\n double t_decel = log(v_max_wrp \/ 100) \/ k_decel;\n\n return cruise_time + t_accel + t_decel;\n}\n\nRoute *dijkstra(Universe &u, Celestial *src, Celestial *dst, struct trip *parameters) {\n update_timers(MB_TOTAL_START);\n update_timers(MB_INIT_START);\n\n int *prev = (int *) malloc(u.entity_count * sizeof(int));\n int *vist = (int *) malloc(u.entity_count * sizeof(int));\n float *cost = (float *) malloc(u.entity_count * sizeof(float));\n enum movement_type *type = (enum movement_type *) malloc(u.entity_count * sizeof(enum movement_type));\n\n float *sys_c = (float *) calloc(4 * (u.system_count + VECTOR_WIDTH), sizeof(float));\n float *sys_x = (float *) calloc((u.system_count + VECTOR_WIDTH), sizeof(float));\n float *sys_y = (float *) calloc((u.system_count + VECTOR_WIDTH), sizeof(float));\n float *sys_z = (float *) calloc((u.system_count + VECTOR_WIDTH), sizeof(float));\n\n MinHeap<float, int> queue(u.entity_count);\n\n float distance, cur_cost;\n\n for (int i = 0; i < u.system_count; i++) {\n _mm_store_ps(&sys_c[i * 4], u.systems[i].pos);\n sys_x[i] = u.systems[i].pos[0];\n sys_y[i] = u.systems[i].pos[1];\n sys_z[i] = u.systems[i].pos[2];\n }\n\n for (int i = 0; i < u.entity_count; i++) {\n if (!u.entities[i].destination && u.entities[i].seq_id != src->seq_id && u.entities[i].seq_id != dst->seq_id) continue;\n\n vist[i] = i == src->seq_id ? 1 : 0;\n prev[i] = i == src->seq_id ? -2 : -1;\n type[i] = STRT;\n cost[i] = i == src->seq_id ? 0.0 : INFINITY;\n\n queue.insert(cost[i], i);\n }\n\n int tmp, v;\n int loops = 0;\n float sqjr = pow(parameters->jump_range * LY_TO_M, 2.0);\n\n vector_type x_vec, y_vec, z_vec;\n vector_type x_src_vec, y_src_vec, z_src_vec;\n\n System *sys, *jsys;\n Celestial *ent;\n\n tmp = queue.extract();\n\n int remaining = u.entity_count;\n\n update_timers(MB_INIT_END);\n\n #pragma omp parallel private(v, cur_cost, jsys, distance, x_vec, y_vec, z_vec) num_threads(3)\n while (remaining > 0 && tmp != dst->seq_id && !isinf(cost[tmp])) {\n #pragma omp master\n {\n update_timers(MB_SYSTEM_START);\n ent = &u.entities[tmp];\n sys = ent->system;\n vist[tmp] = 1;\n\n \/\/ System set\n for (int i = 0; i < sys->entity_count; i++) {\n if (!sys->entities[i].destination && sys->entities[i].seq_id != src->seq_id && sys->entities[i].seq_id != dst->seq_id) {\n continue;\n }\n\n if (tmp == sys->entities[i].seq_id) {\n continue;\n }\n\n v = sys->entities[i].seq_id;\n cur_cost = cost[tmp] + parameters->align_time + get_time(entity_distance(ent, &sys->entities[i]), parameters->warp_speed);\n\n if (cur_cost <= cost[v] && !vist[v]) {\n queue.decrease_raw(cur_cost, v);\n prev[v] = tmp;\n cost[v] = cur_cost;\n type[v] = WARP;\n }\n }\n update_timers(MB_SYSTEM_END);\n\n update_timers(MB_GATE_START);\n \/\/ Gate set\n if (ent->destination && parameters->gate_cost >= 0.0) {\n v = ent->destination->seq_id;\n cur_cost = cost[tmp] + parameters->gate_cost;\n\n if (cur_cost <= cost[v] && !vist[v]) {\n queue.decrease_raw(cur_cost, v);\n prev[v] = tmp;\n cost[v] = cur_cost;\n type[v] = GATE;\n }\n }\n update_timers(MB_GATE_END);\n\n update_timers(MB_JUMP_START);\n\n #if VECTOR_WIDTH == 4\n x_src_vec = _mm_set1_ps(sys->pos[0]);\n y_src_vec = _mm_set1_ps(sys->pos[1]);\n z_src_vec = _mm_set1_ps(sys->pos[2]);\n #elif VECTOR_WIDTH == 8\n x_src_vec = _mm256_set1_ps(sys->pos[0]);\n y_src_vec = _mm256_set1_ps(sys->pos[1]);\n z_src_vec = _mm256_set1_ps(sys->pos[2]);\n #endif\n }\n\n \/\/ Jump set\n if (!isnan(parameters->jump_range)) {\n #pragma omp for schedule(guided)\n for (int k = 0; k < u.system_count; k += VECTOR_WIDTH) {\n #if VECTOR_WIDTH == 4\n x_vec = _mm_load_ps(sys_x + k);\n y_vec = _mm_load_ps(sys_y + k);\n z_vec = _mm_load_ps(sys_z + k);\n #elif VECTOR_WIDTH == 8\n x_vec = _mm256_load_ps(sys_x + k);\n y_vec = _mm256_load_ps(sys_y + k);\n z_vec = _mm256_load_ps(sys_z + k);\n #endif\n\n x_vec -= x_src_vec;\n y_vec -= y_src_vec;\n z_vec -= z_src_vec;\n\n x_vec = (x_vec * x_vec) + (y_vec * y_vec) + (z_vec * z_vec);\n\n for (int i = 0; i < VECTOR_WIDTH; i++) {\n if (x_vec[i] > sqjr || sys->id == u.systems[i].id) continue;\n\n jsys = u.systems + k + i;\n distance = sqrt(x_vec[i]) \/ LY_TO_M;\n\n for (int j = jsys->gates - jsys->entities; j < jsys->entity_count; j++) {\n if (!jsys->entities[j].destination && ((jsys->entities[j].seq_id != src->seq_id && jsys->entities[j].seq_id != dst->seq_id))) continue;\n\n v = jsys->entities[j].seq_id;\n cur_cost = cost[tmp] + 60 * (distance + 1);\n\n if (cur_cost <= cost[v] && !vist[v]) {\n queue.decrease_raw(cur_cost, v);\n prev[v] = tmp;\n cost[v] = cur_cost;\n type[v] = JUMP;\n }\n }\n }\n }\n }\n\n #pragma omp master\n {\n update_timers(MB_JUMP_END);\n\n update_timers(MB_SELECT_START);\n remaining--;\n loops++;\n tmp = queue.extract();\n update_timers(MB_SELECT_END);\n }\n\n #pragma omp barrier\n }\n\n update_timers(MB_TOTAL_END);\n\n Route *route = new Route();\n\n if (verbose >= 1) {\n unsigned long mba_total = 0;\n\n for (int i = 3; i < MB_MAX; i += 2) {\n mba_total += mba[i];\n }\n\n for (int i = 1; i < MB_MAX; i += 2) {\n fprintf(stderr, \"%0.3f ms (%.1f%%), \", mba[i] \/ 1000000.0, (mba[i] \/ (double) mba_total) * 100);\n }\n\n fprintf(stderr, \"\\n\");\n }\n\n route->loops = loops;\n route->cost = cost[dst->seq_id];\n\n for (int c = dst->seq_id; c != -2; c = prev[c]) {\n route->points.push_front((struct waypoint) {&u.entities[c], type[c]});\n }\n\n free(prev);\n free(cost);\n free(vist);\n free(type);\n free(sys_c);\n\n return route;\n}\n<commit_msg>Fix a memory alignment issue with AVX.<commit_after>#include <array>\n#include <stdio.h>\n#include <stdlib.h>\n#include <assert.h>\n#include <time.h>\n#include <math.h>\n#include <omp.h>\n\n#include <xmmintrin.h>\n#include <pmmintrin.h>\n\n#include \"main.hpp\"\n#include \"min_heap.hpp\"\n#include \"universe.hpp\"\n\n#define IACA_SSC_MARK( MARK_ID )\t\t\t\t\t\t\\\n__asm__ __volatile__ (\t\t\t\t\t\t\t\t\\\n\t\t\t\t\t \"\\n\\t movl $\"#MARK_ID\", %%ebx\"\t\\\n\t\t\t\t\t \"\\n\\t .byte 0x64, 0x67, 0x90\"\t\\\n\t\t\t\t\t : : : \"memory\" );\n\n#define IACA_START {IACA_SSC_MARK(111)}\n#define IACA_END {IACA_SSC_MARK(222)}\n\n#define AU_TO_M 149597870700.0\n#define LY_TO_M 9460730472580800.0\n\n#if defined(__AVX__)\n#include <immintrin.h>\n#define VECTOR_WIDTH 8\ntypedef __m256 vector_type;\n#elif defined(__SSE__)\n#define VECTOR_WIDTH 4\ntypedef __m128 vector_type;\n#else\n#error \"Here's a nickel kid, buy yourself a real computer.\"\n#endif\n\nenum measurement_point {\n MB_TOTAL_START, MB_TOTAL_END,\n MB_INIT_START, MB_INIT_END,\n MB_SYSTEM_START, MB_SYSTEM_END,\n MB_GATE_START, MB_GATE_END,\n MB_JUMP_START, MB_JUMP_END,\n MB_SELECT_START, MB_SELECT_END,\n MB_MAX\n};\n\nstatic struct timespec mbt[MB_MAX];\nstatic long mba[MB_MAX] = {0};\n\nstatic void update_timers(enum measurement_point p) {\n if (verbose >= 1) {\n clock_gettime(CLOCK_MONOTONIC, &mbt[p]);\n mba[p] += time_diff(&mbt[p - 1], &mbt[p]);\n }\n}\n\ninline float __attribute__((always_inline)) entity_distance(Celestial *a, Celestial *b) {\n if (a->system != b->system) return INFINITY;\n\n float dx = a->pos[0] - b->pos[0];\n float dy = a->pos[1] - b->pos[1];\n float dz = a->pos[2] - b->pos[2];\n\n return sqrt(dx * dx + dy * dy + dz * dz);\n}\n\ndouble get_time(double distance, double v_wrp) {\n double k_accel = v_wrp;\n double k_decel = (v_wrp \/ 3) < 2 ? (v_wrp \/ 3) : 2;\n\n double v_max_wrp = v_wrp * AU_TO_M;\n\n double d_accel = AU_TO_M;\n double d_decel = v_max_wrp \/ k_decel;\n\n double d_min = d_accel + d_decel;\n\n double cruise_time = 0;\n\n if (d_min > distance) {\n v_max_wrp = distance * k_accel * k_decel \/ (k_accel + k_decel);\n } else {\n cruise_time = (distance - d_min) \/ v_max_wrp;\n }\n\n double t_accel = log(v_max_wrp \/ k_accel) \/ k_accel;\n double t_decel = log(v_max_wrp \/ 100) \/ k_decel;\n\n return cruise_time + t_accel + t_decel;\n}\n\nRoute *dijkstra(Universe &u, Celestial *src, Celestial *dst, struct trip *parameters) {\n update_timers(MB_TOTAL_START);\n update_timers(MB_INIT_START);\n\n int *prev = (int *) malloc(u.entity_count * sizeof(int));\n int *vist = (int *) malloc(u.entity_count * sizeof(int));\n float *cost = (float *) malloc(u.entity_count * sizeof(float));\n enum movement_type *type = (enum movement_type *) malloc(u.entity_count * sizeof(enum movement_type));\n\n float *sys_c = (float *) calloc(4 * (u.system_count + VECTOR_WIDTH), sizeof(float));\n float *sys_x = (float *) calloc((u.system_count + VECTOR_WIDTH), sizeof(float));\n float *sys_y = (float *) calloc((u.system_count + VECTOR_WIDTH), sizeof(float));\n float *sys_z = (float *) calloc((u.system_count + VECTOR_WIDTH), sizeof(float));\n\n MinHeap<float, int> queue(u.entity_count);\n\n float distance, cur_cost;\n\n for (int i = 0; i < u.system_count; i++) {\n _mm_store_ps(&sys_c[i * 4], u.systems[i].pos);\n sys_x[i] = u.systems[i].pos[0];\n sys_y[i] = u.systems[i].pos[1];\n sys_z[i] = u.systems[i].pos[2];\n }\n\n for (int i = 0; i < u.entity_count; i++) {\n if (!u.entities[i].destination && u.entities[i].seq_id != src->seq_id && u.entities[i].seq_id != dst->seq_id) continue;\n\n vist[i] = i == src->seq_id ? 1 : 0;\n prev[i] = i == src->seq_id ? -2 : -1;\n type[i] = STRT;\n cost[i] = i == src->seq_id ? 0.0 : INFINITY;\n\n queue.insert(cost[i], i);\n }\n\n int tmp, v;\n int loops = 0;\n float sqjr = pow(parameters->jump_range * LY_TO_M, 2.0);\n\n vector_type x_vec, y_vec, z_vec;\n vector_type x_src_vec, y_src_vec, z_src_vec;\n\n System *sys, *jsys;\n Celestial *ent;\n\n tmp = queue.extract();\n\n int remaining = u.entity_count;\n\n update_timers(MB_INIT_END);\n\n #pragma omp parallel private(v, cur_cost, jsys, distance, x_vec, y_vec, z_vec) num_threads(3)\n while (remaining > 0 && tmp != dst->seq_id && !isinf(cost[tmp])) {\n #pragma omp master\n {\n update_timers(MB_SYSTEM_START);\n ent = &u.entities[tmp];\n sys = ent->system;\n vist[tmp] = 1;\n\n \/\/ System set\n for (int i = 0; i < sys->entity_count; i++) {\n if (!sys->entities[i].destination && sys->entities[i].seq_id != src->seq_id && sys->entities[i].seq_id != dst->seq_id) {\n continue;\n }\n\n if (tmp == sys->entities[i].seq_id) {\n continue;\n }\n\n v = sys->entities[i].seq_id;\n cur_cost = cost[tmp] + parameters->align_time + get_time(entity_distance(ent, &sys->entities[i]), parameters->warp_speed);\n\n if (cur_cost <= cost[v] && !vist[v]) {\n queue.decrease_raw(cur_cost, v);\n prev[v] = tmp;\n cost[v] = cur_cost;\n type[v] = WARP;\n }\n }\n update_timers(MB_SYSTEM_END);\n\n update_timers(MB_GATE_START);\n \/\/ Gate set\n if (ent->destination && parameters->gate_cost >= 0.0) {\n v = ent->destination->seq_id;\n cur_cost = cost[tmp] + parameters->gate_cost;\n\n if (cur_cost <= cost[v] && !vist[v]) {\n queue.decrease_raw(cur_cost, v);\n prev[v] = tmp;\n cost[v] = cur_cost;\n type[v] = GATE;\n }\n }\n update_timers(MB_GATE_END);\n\n update_timers(MB_JUMP_START);\n\n #if VECTOR_WIDTH == 4\n x_src_vec = _mm_set1_ps(sys->pos[0]);\n y_src_vec = _mm_set1_ps(sys->pos[1]);\n z_src_vec = _mm_set1_ps(sys->pos[2]);\n #elif VECTOR_WIDTH == 8\n x_src_vec = _mm256_set1_ps(sys->pos[0]);\n y_src_vec = _mm256_set1_ps(sys->pos[1]);\n z_src_vec = _mm256_set1_ps(sys->pos[2]);\n #endif\n }\n\n \/\/ Jump set\n if (!isnan(parameters->jump_range)) {\n #pragma omp for schedule(guided)\n for (int k = 0; k < u.system_count; k += VECTOR_WIDTH) {\n #if VECTOR_WIDTH == 4\n x_vec = _mm_load_ps(sys_x + k);\n y_vec = _mm_load_ps(sys_y + k);\n z_vec = _mm_load_ps(sys_z + k);\n #elif VECTOR_WIDTH == 8\n x_vec = _mm256_loadu_ps(sys_x + k);\n y_vec = _mm256_loadu_ps(sys_y + k);\n z_vec = _mm256_loadu_ps(sys_z + k);\n #endif\n\n x_vec -= x_src_vec;\n y_vec -= y_src_vec;\n z_vec -= z_src_vec;\n\n x_vec = (x_vec * x_vec) + (y_vec * y_vec) + (z_vec * z_vec);\n\n for (int i = 0; i < VECTOR_WIDTH; i++) {\n if (x_vec[i] > sqjr || sys->id == u.systems[i].id) continue;\n\n jsys = u.systems + k + i;\n distance = sqrt(x_vec[i]) \/ LY_TO_M;\n\n for (int j = jsys->gates - jsys->entities; j < jsys->entity_count; j++) {\n if (!jsys->entities[j].destination && ((jsys->entities[j].seq_id != src->seq_id && jsys->entities[j].seq_id != dst->seq_id))) continue;\n\n v = jsys->entities[j].seq_id;\n cur_cost = cost[tmp] + 60 * (distance + 1);\n\n if (cur_cost <= cost[v] && !vist[v]) {\n queue.decrease_raw(cur_cost, v);\n prev[v] = tmp;\n cost[v] = cur_cost;\n type[v] = JUMP;\n }\n }\n }\n }\n }\n\n #pragma omp master\n {\n update_timers(MB_JUMP_END);\n\n update_timers(MB_SELECT_START);\n remaining--;\n loops++;\n tmp = queue.extract();\n update_timers(MB_SELECT_END);\n }\n\n #pragma omp barrier\n }\n\n update_timers(MB_TOTAL_END);\n\n Route *route = new Route();\n\n if (verbose >= 1) {\n unsigned long mba_total = 0;\n\n for (int i = 3; i < MB_MAX; i += 2) {\n mba_total += mba[i];\n }\n\n for (int i = 1; i < MB_MAX; i += 2) {\n fprintf(stderr, \"%0.3f ms (%.1f%%), \", mba[i] \/ 1000000.0, (mba[i] \/ (double) mba_total) * 100);\n }\n\n fprintf(stderr, \"\\n\");\n }\n\n route->loops = loops;\n route->cost = cost[dst->seq_id];\n\n for (int c = dst->seq_id; c != -2; c = prev[c]) {\n route->points.push_front((struct waypoint) {&u.entities[c], type[c]});\n }\n\n free(prev);\n free(cost);\n free(vist);\n free(type);\n free(sys_c);\n\n return route;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 2008-2015, Hazelcast, Inc. All Rights Reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\/\/\n\/\/ Created by sancar koyunlu on 30\/12\/13.\n\/\/\n\n#include \"hazelcast\/util\/Util.h\"\n#include \"hazelcast\/client\/connection\/IOHandler.h\"\n#include \"hazelcast\/client\/connection\/IOSelector.h\"\n#include \"hazelcast\/client\/connection\/Connection.h\"\n#include \"hazelcast\/util\/ILogger.h\"\n\nnamespace hazelcast {\n namespace client {\n namespace connection {\n\n IOHandler::IOHandler(Connection& connection, IOSelector& ioSelector)\n : ioSelector(ioSelector)\n , connection(connection) {\n\n }\n\n void IOHandler::registerSocket() {\n ioSelector.addTask(this);\n ioSelector.wakeUp();\n }\n\n void IOHandler::registerHandler() {\n if (!connection.live)\n return;\n Socket const& socket = connection.getSocket();\n ioSelector.addSocket(socket);\n }\n\n void IOHandler::deRegisterSocket() {\n ioSelector.cancelTask(this);\n ioSelector.removeSocket(connection.getSocket());\n }\n\n IOHandler::~IOHandler() {\n\n }\n\n void IOHandler::handleSocketException(const std::string& message) {\n Address const& address = connection.getRemoteEndpoint();\n\n size_t len = message.length() + 150;\n char *msg = new char[len];\n util::snprintf(msg, len, \"[IOHandler::handleSocketException] Closing socket to endpoint %s:%d, Cause:%s\\n\",\n address.getHost().c_str(), address.getPort(), message.c_str());\n util::ILogger::getLogger().getLogger().warning(msg);\n\n \/\/ TODO: This call shall resend pending requests and reregister events, hence it can be off-loaded\n \/\/ to another thread in order not to block the critical IO thread\n connection.close();\n }\n }\n }\n}\n\n<commit_msg>Release memory to prevent memory leak. (#169)<commit_after>\/*\n * Copyright (c) 2008-2015, Hazelcast, Inc. All Rights Reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\/\/\n\/\/ Created by sancar koyunlu on 30\/12\/13.\n\/\/\n\n#include \"hazelcast\/util\/Util.h\"\n#include \"hazelcast\/client\/connection\/IOHandler.h\"\n#include \"hazelcast\/client\/connection\/IOSelector.h\"\n#include \"hazelcast\/client\/connection\/Connection.h\"\n#include \"hazelcast\/util\/ILogger.h\"\n\nnamespace hazelcast {\n namespace client {\n namespace connection {\n\n IOHandler::IOHandler(Connection& connection, IOSelector& ioSelector)\n : ioSelector(ioSelector)\n , connection(connection) {\n\n }\n\n void IOHandler::registerSocket() {\n ioSelector.addTask(this);\n ioSelector.wakeUp();\n }\n\n void IOHandler::registerHandler() {\n if (!connection.live)\n return;\n Socket const& socket = connection.getSocket();\n ioSelector.addSocket(socket);\n }\n\n void IOHandler::deRegisterSocket() {\n ioSelector.cancelTask(this);\n ioSelector.removeSocket(connection.getSocket());\n }\n\n IOHandler::~IOHandler() {\n\n }\n\n void IOHandler::handleSocketException(const std::string& message) {\n Address const& address = connection.getRemoteEndpoint();\n\n size_t len = message.length() + 150;\n char *msg = new char[len];\n util::snprintf(msg, len, \"[IOHandler::handleSocketException] Closing socket to endpoint %s:%d, Cause:%s\\n\",\n address.getHost().c_str(), address.getPort(), message.c_str());\n util::ILogger::getLogger().getLogger().warning(msg);\n\n \/\/ release the memory for the message\n delete [] msg;\n\n \/\/ TODO: This call shall resend pending requests and reregister events, hence it can be off-loaded\n \/\/ to another thread in order not to block the critical IO thread\n connection.close();\n }\n }\n }\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/**\n * @file \/grid_map_visualisations\/include\/grid_map_visualisations\/formatters.hpp\n *\/\n\/*****************************************************************************\n** Ifdefs\n*****************************************************************************\/\n\n#ifndef grid_map_visualisations_FORMATTERS_HPP_\n#define grid_map_visualisations_FORMATTERS_HPP_\n\n\/*****************************************************************************\n** Includes\n*****************************************************************************\/\n\n#include <ecl\/formatters.hpp>\n#include <grid_map_core\/grid_map_core.hpp>\n#include <limits>\n#include <string>\n\n\/*****************************************************************************\n** Namespaces\n*****************************************************************************\/\n\nnamespace grid_map_extras {\n\n\/*****************************************************************************\n** Interfaces\n*****************************************************************************\/\n\nclass Formatter {\npublic:\npublic:\n \/**\n * @brief Default constructor.\n *\n * Initialises the format tags for width, and precision, and a layer to\n * format. Note this only formats a single layer.\n *\n * @param layer_name : look for this layer in any passed grid to format.\n * @param scaled : scale values on the range -99.0 -> 99.0 (for formatting ease).\n * @param w : width (default - no width constraints)\n * @param p : the number of decimal places of precision (default - 4)\n **\/\n Formatter(const std::string& layer_name,\n const int &w = -1,\n const unsigned int &p = 2,\n const bool& scaled = true\n )\n : format(w, p, ecl::RightAlign)\n , tmp_width(w)\n , tmp_precision(p)\n , tmp_formatting(false)\n , ready_to_format(false)\n , grid_(nullptr)\n , layer_name_(layer_name)\n , scaled_(scaled)\n{}\n virtual ~Formatter() {}\n \/**\n * @brief Sets the precision format parameter.\n *\n * @param p : the number of decimal places of precision.\n * @return Formatter& : this formatter readied for use with a stream.\n **\/\n Formatter& precision( const unsigned int &p ) {\n format.precision(p);\n return *this;\n }\n \/**\n * @brief Sets the width format parameter.\n *\n * Sets the width format parameter.\n *\n * @param w : the width to use for inserted floats (-1 is no width constraint).\n * @return FloatMatrixFormatter& : this formatter readied for use with a stream.\n **\/\n Formatter& width( const int &w ) {\n format.width(w);\n return *this;\n }\n \/**\n * @brief Returns the current precision setting.\n * @return unsigned int : the precision value.\n *\/\n unsigned int precision() { return format.precision(); }\n\n \/**\n * @brief Returns the current width setting.\n * @return int : the witdh value (-1 for no width constraint).\n *\/\n int width() { return format.width(); }\n\n \/**\n * @brief Format a sophus transform with permanently stored precision\/width.\n *\n * This function directly formats the specified input value\n * with the stored settings.\n * @code\n * cout << format(nav_msgs::OccupancyGrid()) << endl;\n * @endcode\n * @param matrix : the matrix to be formatted (gets temporarily stored as a pointer).\n * @return FloatMatrixFormatter& : this formatter readied for use with a stream.\n **\/\n Formatter& operator() (const grid_map::GridMap& grid ) {\n grid_ = &grid;\n ready_to_format = true;\n return (*this);\n }\n \/**\n * @brief Format a matrix with temporarily specified precision\/width.\n *\n * This function directly formats the specified input value\n * and temporary settings.\n *\n * @code\n * nav_msgs::OccupancyGrid grid;\n * cout << format(grid,3,-1) << endl; \/\/ precision of 3 and no width constraint\n * @endcode\n *\n * @param matrix : the matrix to be formatted (gets temporarily stored as a pointer).\n * @param w : the width to use for inserted floats (-1 is no width constraint).\n * @param p : the number of decimal places of precision.\n * @return FloatMatrixFormatter& : this formatter readied for use with a stream.\n **\/\n Formatter& operator() (const grid_map::GridMap& grid, const int &w, const unsigned int &p) {\n grid_ = &grid;\n tmp_precision = p;\n tmp_width = w;\n tmp_formatting = true;\n ready_to_format = true;\n return (*this);\n }\n \/**\n * @brief Stream the formatter.\n *\n * Insertion operator for sending the formatter to an output stream.\n *\n * @param ostream : the output stream.\n * @param formatter : the formatter to be inserted.\n * @tparam OutputStream : the type of the output stream to be inserted into.\n * @tparam Derived : matrix type.\n * @return OutputStream : continue streaming with the updated output stream.\n *\n * @exception StandardException : throws if the formatter has un-specified _matrix [debug mode only]\n *\/\n template <typename OutputStream>\n friend OutputStream& operator << ( OutputStream& ostream, Formatter & formatter ) ecl_assert_throw_decl(ecl::StandardException);\n\nprivate:\n ecl::Format<float> format;\n int tmp_width;\n unsigned int tmp_precision;\n bool tmp_formatting;\n bool ready_to_format;\n const grid_map::GridMap *grid_;\n const std::string layer_name_;\n bool scaled_;\n};\n\ntemplate <typename OutputStream>\nOutputStream& operator << (OutputStream& ostream, Formatter & formatter ) ecl_assert_throw_decl(ecl::StandardException) {\n\n ecl_assert_throw( formatter.grid_, ecl::StandardException(LOC,ecl::UsageError,\"The formatter cannot print any data - \"\n \"grid object was not initialised \"\n \"please pass the your grid through () operator\") );\n\n ecl_assert_throw(formatter.ready_to_format, ecl::StandardException(LOC,ecl::UsageError,\"The formatter cannot print any data - \"\n \"either there is no data available, or you have tried to use the \"\n \"formatter more than once in a single streaming operation. \"\n \"C++ produces unspecified results when functors are used multiply \"\n \"in the same stream sequence, so this is not permitted here.\") );\n\n if ( formatter.ready_to_format ) {\n unsigned int prm_precision = formatter.format.precision();;\n int prm_width = formatter.format.width();\n if ( formatter.tmp_formatting ) {\n formatter.format.precision(formatter.tmp_precision);\n formatter.format.width(formatter.tmp_width);\n }\n\n grid_map::Index costmap_index;\n const grid_map::Matrix& data = formatter.grid_->get(std::string(formatter.layer_name_));\n\n \/********************\n ** Scaling\n ********************\/\n double max_magnitude = 99.0;\n if ( formatter.scaled_ ) {\n for (grid_map::GridMapIterator iterator(*(formatter.grid_)); !iterator.isPastEnd(); ++iterator) {\n int i = (*iterator)(0);\n int j = (*iterator)(1);\n double value = data(i, j);\n if ( ( std::abs(value) > max_magnitude ) && (value != std::numeric_limits<double>::infinity()) ) {\n max_magnitude = value;\n }\n }\n }\n\n \/*********************\n ** Stream\n **********************\/\n int count = 0;\n \/\/ Eigen Matrix is row-major, so this grid map iterator usually iterates down before across\n \/\/ so have to rearrange the grid into a form that is convenient for streaming to the screen\n \/\/ reminder : do not iterate over the matrix directly - the starting index might not be at\n \/\/ the start of the matrix!\n std::vector<double> storage(formatter.grid_->getSize().x() * formatter.grid_->getSize().y(), 0.0);\n for (grid_map::GridMapIterator iterator(*(formatter.grid_)); !iterator.isPastEnd(); ++iterator) {\n int i = (*iterator)(0);\n int j = (*iterator)(1);\n double value = data(i, j);\n if ( formatter.scaled_ ) {\n storage[j + i*formatter.grid_->getSize().x()] = 99.0*value\/max_magnitude;\n } else {\n storage[j + i*formatter.grid_->getSize().x()] = value;\n }\n }\n for ( const double& value : storage ) {\n if ( value == std::numeric_limits<double>::infinity() ) {\n for ( unsigned int i = 0; i < formatter.format.width() - 3; ++i ) {\n ostream << \" \";\n }\n ostream << \"inf\";\n } else {\n ostream << formatter.format(value);\n }\n ++count;\n if ( count == formatter.grid_->getSize().x() ) {\n count = 0;\n ostream << \"\\n\";\n }\n }\n\n \/********************\n ** Reset Variables\n ********************\/\n if ( formatter.tmp_formatting ) {\n formatter.format.precision(prm_precision);\n formatter.format.width(prm_width);\n formatter.tmp_formatting = false;\n }\n formatter.ready_to_format = false;\n }\n return ostream;\n}\n\n} \/\/ namespace grid_map_extras\n\n\/*****************************************************************************\n ** ECL Format Type\n *****************************************************************************\/\n\nnamespace ecl {\n\ntemplate <>\nclass Format<grid_map::GridMap> : public grid_map_extras::Formatter {\npublic:\n Format(const std::string& layer_name,\n const int &w,\n const unsigned int &p,\n const bool& scaled\n )\n : grid_map_extras::Formatter(layer_name, w, p, scaled)\n {}\n};\n\n} \/\/ namespace ecl\n\n\/*****************************************************************************\n** Trailers\n*****************************************************************************\/\n\n#endif \/* grid_map_visualisations_FORMATTERS_HPP_ *\/\n<commit_msg>[grid_map_extras] bugfix magnitude when negative.<commit_after>\/**\n * @file \/grid_map_visualisations\/include\/grid_map_visualisations\/formatters.hpp\n *\/\n\/*****************************************************************************\n** Ifdefs\n*****************************************************************************\/\n\n#ifndef grid_map_visualisations_FORMATTERS_HPP_\n#define grid_map_visualisations_FORMATTERS_HPP_\n\n\/*****************************************************************************\n** Includes\n*****************************************************************************\/\n\n#include <ecl\/formatters.hpp>\n#include <grid_map_core\/grid_map_core.hpp>\n#include <limits>\n#include <string>\n\n\/*****************************************************************************\n** Namespaces\n*****************************************************************************\/\n\nnamespace grid_map_extras {\n\n\/*****************************************************************************\n** Interfaces\n*****************************************************************************\/\n\nclass Formatter {\npublic:\npublic:\n \/**\n * @brief Default constructor.\n *\n * Initialises the format tags for width, and precision, and a layer to\n * format. Note this only formats a single layer.\n *\n * @param layer_name : look for this layer in any passed grid to format.\n * @param scaled : scale values on the range -99.0 -> 99.0 (for formatting ease).\n * @param w : width (default - no width constraints)\n * @param p : the number of decimal places of precision (default - 4)\n **\/\n Formatter(const std::string& layer_name,\n const int &w = -1,\n const unsigned int &p = 2,\n const bool& scaled = true\n )\n : format(w, p, ecl::RightAlign)\n , tmp_width(w)\n , tmp_precision(p)\n , tmp_formatting(false)\n , ready_to_format(false)\n , grid_(nullptr)\n , layer_name_(layer_name)\n , scaled_(scaled)\n{}\n virtual ~Formatter() {}\n \/**\n * @brief Sets the precision format parameter.\n *\n * @param p : the number of decimal places of precision.\n * @return Formatter& : this formatter readied for use with a stream.\n **\/\n Formatter& precision( const unsigned int &p ) {\n format.precision(p);\n return *this;\n }\n \/**\n * @brief Sets the width format parameter.\n *\n * Sets the width format parameter.\n *\n * @param w : the width to use for inserted floats (-1 is no width constraint).\n * @return FloatMatrixFormatter& : this formatter readied for use with a stream.\n **\/\n Formatter& width( const int &w ) {\n format.width(w);\n return *this;\n }\n \/**\n * @brief Returns the current precision setting.\n * @return unsigned int : the precision value.\n *\/\n unsigned int precision() { return format.precision(); }\n\n \/**\n * @brief Returns the current width setting.\n * @return int : the witdh value (-1 for no width constraint).\n *\/\n int width() { return format.width(); }\n\n \/**\n * @brief Format a sophus transform with permanently stored precision\/width.\n *\n * This function directly formats the specified input value\n * with the stored settings.\n * @code\n * cout << format(nav_msgs::OccupancyGrid()) << endl;\n * @endcode\n * @param matrix : the matrix to be formatted (gets temporarily stored as a pointer).\n * @return FloatMatrixFormatter& : this formatter readied for use with a stream.\n **\/\n Formatter& operator() (const grid_map::GridMap& grid ) {\n grid_ = &grid;\n ready_to_format = true;\n return (*this);\n }\n \/**\n * @brief Format a matrix with temporarily specified precision\/width.\n *\n * This function directly formats the specified input value\n * and temporary settings.\n *\n * @code\n * nav_msgs::OccupancyGrid grid;\n * cout << format(grid,3,-1) << endl; \/\/ precision of 3 and no width constraint\n * @endcode\n *\n * @param matrix : the matrix to be formatted (gets temporarily stored as a pointer).\n * @param w : the width to use for inserted floats (-1 is no width constraint).\n * @param p : the number of decimal places of precision.\n * @return FloatMatrixFormatter& : this formatter readied for use with a stream.\n **\/\n Formatter& operator() (const grid_map::GridMap& grid, const int &w, const unsigned int &p) {\n grid_ = &grid;\n tmp_precision = p;\n tmp_width = w;\n tmp_formatting = true;\n ready_to_format = true;\n return (*this);\n }\n \/**\n * @brief Stream the formatter.\n *\n * Insertion operator for sending the formatter to an output stream.\n *\n * @param ostream : the output stream.\n * @param formatter : the formatter to be inserted.\n * @tparam OutputStream : the type of the output stream to be inserted into.\n * @tparam Derived : matrix type.\n * @return OutputStream : continue streaming with the updated output stream.\n *\n * @exception StandardException : throws if the formatter has un-specified _matrix [debug mode only]\n *\/\n template <typename OutputStream>\n friend OutputStream& operator << ( OutputStream& ostream, Formatter & formatter ) ecl_assert_throw_decl(ecl::StandardException);\n\nprivate:\n ecl::Format<float> format;\n int tmp_width;\n unsigned int tmp_precision;\n bool tmp_formatting;\n bool ready_to_format;\n const grid_map::GridMap *grid_;\n const std::string layer_name_;\n bool scaled_;\n};\n\ntemplate <typename OutputStream>\nOutputStream& operator << (OutputStream& ostream, Formatter & formatter ) ecl_assert_throw_decl(ecl::StandardException) {\n\n ecl_assert_throw( formatter.grid_, ecl::StandardException(LOC,ecl::UsageError,\"The formatter cannot print any data - \"\n \"grid object was not initialised \"\n \"please pass the your grid through () operator\") );\n\n ecl_assert_throw(formatter.ready_to_format, ecl::StandardException(LOC,ecl::UsageError,\"The formatter cannot print any data - \"\n \"either there is no data available, or you have tried to use the \"\n \"formatter more than once in a single streaming operation. \"\n \"C++ produces unspecified results when functors are used multiply \"\n \"in the same stream sequence, so this is not permitted here.\") );\n\n if ( formatter.ready_to_format ) {\n unsigned int prm_precision = formatter.format.precision();;\n int prm_width = formatter.format.width();\n if ( formatter.tmp_formatting ) {\n formatter.format.precision(formatter.tmp_precision);\n formatter.format.width(formatter.tmp_width);\n }\n\n grid_map::Index costmap_index;\n const grid_map::Matrix& data = formatter.grid_->get(std::string(formatter.layer_name_));\n\n \/********************\n ** Scaling\n ********************\/\n double max_magnitude = 99.0;\n if ( formatter.scaled_ ) {\n for (grid_map::GridMapIterator iterator(*(formatter.grid_)); !iterator.isPastEnd(); ++iterator) {\n int i = (*iterator)(0);\n int j = (*iterator)(1);\n double value = data(i, j);\n if ( ( std::abs(value) > max_magnitude ) && (value != std::numeric_limits<double>::infinity()) ) {\n max_magnitude = std::abs(value);\n }\n }\n }\n\n \/*********************\n ** Stream\n **********************\/\n int count = 0;\n \/\/ Eigen Matrix is row-major, so this grid map iterator usually iterates down before across\n \/\/ so have to rearrange the grid into a form that is convenient for streaming to the screen\n \/\/ reminder : do not iterate over the matrix directly - the starting index might not be at\n \/\/ the start of the matrix!\n std::vector<double> storage(formatter.grid_->getSize().x() * formatter.grid_->getSize().y(), 0.0);\n for (grid_map::GridMapIterator iterator(*(formatter.grid_)); !iterator.isPastEnd(); ++iterator) {\n int i = (*iterator)(0);\n int j = (*iterator)(1);\n double value = data(i, j);\n if ( formatter.scaled_ ) {\n storage[j + i*formatter.grid_->getSize().x()] = 99.0*value\/max_magnitude;\n } else {\n storage[j + i*formatter.grid_->getSize().x()] = value;\n }\n }\n for ( const double& value : storage ) {\n if ( value == std::numeric_limits<double>::infinity() ) {\n for ( unsigned int i = 0; i < formatter.format.width() - 3; ++i ) {\n ostream << \" \";\n }\n ostream << \"inf\";\n } else {\n ostream << formatter.format(value);\n }\n ++count;\n if ( count == formatter.grid_->getSize().x() ) {\n count = 0;\n ostream << \"\\n\";\n }\n }\n\n \/********************\n ** Reset Variables\n ********************\/\n if ( formatter.tmp_formatting ) {\n formatter.format.precision(prm_precision);\n formatter.format.width(prm_width);\n formatter.tmp_formatting = false;\n }\n formatter.ready_to_format = false;\n }\n return ostream;\n}\n\n} \/\/ namespace grid_map_extras\n\n\/*****************************************************************************\n ** ECL Format Type\n *****************************************************************************\/\n\nnamespace ecl {\n\ntemplate <>\nclass Format<grid_map::GridMap> : public grid_map_extras::Formatter {\npublic:\n Format(const std::string& layer_name,\n const int &w,\n const unsigned int &p,\n const bool& scaled\n )\n : grid_map_extras::Formatter(layer_name, w, p, scaled)\n {}\n};\n\n} \/\/ namespace ecl\n\n\/*****************************************************************************\n** Trailers\n*****************************************************************************\/\n\n#endif \/* grid_map_visualisations_FORMATTERS_HPP_ *\/\n<|endoftext|>"} {"text":"<commit_before>#include \"mesh_cartesian.h\"\n\n#include <algorithm>\n#include <cmath>\n#include <vector>\n\n#include <deal.II\/base\/point.h>\n#include <deal.II\/grid\/grid_generator.h>\n#include <deal.II\/base\/tensor.h>\n#include <deal.II\/base\/utilities.h>\n\n#include \"..\/problem\/parameter_types.h\"\n\nnamespace bart {\n\nnamespace domain {\n\ntemplate <int dim>\nMeshCartesian<dim>::MeshCartesian(const std::vector<double> spatial_max,\n const std::vector<int> n_cells,\n const std::string material_mapping)\n : MeshCartesian(spatial_max, n_cells) {\n ParseMaterialMap(material_mapping);\n}\n\n\ntemplate <int dim>\nMeshCartesian<dim>::MeshCartesian(const std::vector<double> spatial_max,\n const std::vector<int> n_cells) {\n\n \/\/ Check lengths of spatial max and n_cells\n AssertThrow(spatial_max.size() == dim,\n dealii::ExcMessage(\"MeshCartesian argument error, incorrect spatial vector size\"));\n AssertThrow(n_cells.size() == dim,\n dealii::ExcMessage(\"MeshCartesian argument error, incorrect number of cells vector size\"))\n \n std::copy(n_cells.begin(), n_cells.end(), n_cells_.begin());\n std::copy(spatial_max.begin(), spatial_max.end(), spatial_max_.begin());\n}\n\ntemplate <int dim>\nvoid MeshCartesian<dim>::FillTriangulation(dealii::Triangulation<dim> &to_fill) {\n \n dealii::Point<dim> diagonal;\n dealii::Point<dim> origin;\n\n for (int i = 0; i < dim; ++i)\n diagonal[i] = spatial_max_[i];\n\n std::vector<unsigned int> number_of_cells{n_cells_.begin(), n_cells_.end()};\n\n dealii::GridGenerator::subdivided_hyper_rectangle(to_fill, number_of_cells,\n origin, diagonal);\n}\n\ntemplate <int dim>\nvoid MeshCartesian<dim>::ParseMaterialMap(std::string material_mapping) {\n using dealii::Utilities::split_string_list;\n using dealii::Utilities::string_to_int;\n using StringVector = std::vector<std::string>;\n \n StringVector y_vector = split_string_list(material_mapping, \"\\n\");\n \n std::reverse(y_vector.begin(), y_vector.end());\n \n for (int j = 0; j < static_cast<int>(y_vector.size()); ++j ) {\n \n StringVector x_vector = split_string_list(y_vector[j], \" \");\n \n for (int i = 0; i < static_cast<int>(x_vector.size()); ++i ) {\n \n std::array<int, 2> location{i, j};\n material_mapping_[location] = string_to_int(x_vector[i]);\n }\n n_material_cells_[0] = x_vector.size();\n }\n n_material_cells_[1] = y_vector.size();\n}\n\ntemplate <int dim> \nvoid MeshCartesian<dim>::FillMaterialID(dealii::Triangulation<dim> &to_fill) {\n for (auto cell = to_fill.begin_active(); cell != to_fill.end(); ++cell) {\n if (cell->is_locally_owned()) {\n int material_id = GetMaterialID(cell->center());\n cell->set_material_id(material_id);\n }\n }\n}\n\ntemplate <int dim>\nvoid MeshCartesian<dim>::FillBoundaryID(dealii::Triangulation<dim> &to_fill) {\n using Boundary = bart::problem::Boundary;\n int faces_per_cell = dealii::GeometryInfo<dim>::faces_per_cell;\n double zero_tol = 1.0e-14;\n \n for (auto cell = to_fill.begin_active(); cell != to_fill.end(); ++cell) {\n if (cell->is_locally_owned()) {\n for (int face_id = 0; face_id < faces_per_cell; ++face_id) {\n auto face = cell->face(face_id);\n dealii::Point<dim> face_center = face->center();\n\n switch (dim) {\n case 2: {\n if (std::fabs(face_center[1]) < zero_tol) {\n face->set_boundary_id(static_cast<int>(Boundary::kYMin));\n break;\n } else if (std::fabs(face_center[1] - spatial_max_[1]) < zero_tol) {\n face->set_boundary_id(static_cast<int>(Boundary::kYMax));\n break;\n }\n [[fallthrough]];\n }\n \/\/ Fall through to check x-direction\n case 1: {\n if (std::fabs(face_center[0]) < zero_tol) {\n face->set_boundary_id(static_cast<int>(Boundary::kXMin));\n break;\n } else if (std::fabs(face_center[0] - spatial_max_[0]) < zero_tol) {\n face->set_boundary_id(static_cast<int>(Boundary::kXMax));\n break;\n }\n break;\n }\n default: {\n AssertThrow(false,\n dealii::ExcMessage(\"Unsupported number of dimensions in FillBoundaryID\"));\n }\n }\n }\n }\n }\n}\n \n\ntemplate <int dim>\nint MeshCartesian<dim>::GetMaterialID(dealii::Point<dim> location) {\n std::array<double, dim> array_location;\n for (int i = 0; i < dim; ++i)\n array_location[i] = location[i];\n return GetMaterialID(array_location);\n}\n \ntemplate <int dim>\nint MeshCartesian<dim>::GetMaterialID(std::array<double, dim> location) {\n std::array<int, 2> relative_location{0, 0};\n\n for (int i = 0; i < dim; ++i) {\n double cell_size = spatial_max_[i]\/n_material_cells_[i];\n double cell_location = location[i] \/ cell_size;\n int cell_index = std::floor(cell_location);\n\n if (static_cast<double>(cell_index) == cell_location && cell_index != 0) {\n relative_location[i] = cell_index - 1;\n } else {\n relative_location[i] = cell_index; \n }\n }\n \n return material_mapping_[relative_location];\n}\n\ntemplate class MeshCartesian<1>;\ntemplate class MeshCartesian<2>;\n\n} \/\/ namespace domain\n\n} \/\/ namespace bart \n<commit_msg>fixed formatting in MeshCartesian implementation<commit_after>#include \"mesh_cartesian.h\"\n\n#include <algorithm>\n#include <cmath>\n#include <vector>\n\n#include <deal.II\/base\/point.h>\n#include <deal.II\/grid\/grid_generator.h>\n#include <deal.II\/base\/tensor.h>\n#include <deal.II\/base\/utilities.h>\n\n#include \"..\/problem\/parameter_types.h\"\n\nnamespace bart {\n\nnamespace domain {\n\ntemplate <int dim>\nMeshCartesian<dim>::MeshCartesian(const std::vector<double> spatial_max,\n const std::vector<int> n_cells,\n const std::string material_mapping)\n : MeshCartesian(spatial_max, n_cells) {\n ParseMaterialMap(material_mapping);\n}\n\n\ntemplate <int dim>\nMeshCartesian<dim>::MeshCartesian(const std::vector<double> spatial_max,\n const std::vector<int> n_cells) {\n\n \/\/ Check lengths of spatial max and n_cells\n AssertThrow(spatial_max.size() == dim,\n dealii::ExcMessage(\"MeshCartesian argument error, incorrect spatial vector size\"));\n AssertThrow(n_cells.size() == dim,\n dealii::ExcMessage(\"MeshCartesian argument error, incorrect number of cells vector size\"));\n \n std::copy(n_cells.begin(), n_cells.end(), n_cells_.begin());\n std::copy(spatial_max.begin(), spatial_max.end(), spatial_max_.begin());\n}\n\ntemplate <int dim>\nvoid MeshCartesian<dim>::FillTriangulation(dealii::Triangulation<dim> &to_fill) {\n \n dealii::Point<dim> diagonal;\n dealii::Point<dim> origin;\n\n for (int i = 0; i < dim; ++i)\n diagonal[i] = spatial_max_[i];\n\n std::vector<unsigned int> number_of_cells{n_cells_.begin(), n_cells_.end()};\n dealii::GridGenerator::subdivided_hyper_rectangle(to_fill, number_of_cells,\n origin, diagonal);\n}\n\ntemplate <int dim>\nvoid MeshCartesian<dim>::ParseMaterialMap(std::string material_mapping) {\n using dealii::Utilities::split_string_list;\n using dealii::Utilities::string_to_int;\n using StringVector = std::vector<std::string>;\n \n StringVector y_vector = split_string_list(material_mapping, \"\\n\");\n \n std::reverse(y_vector.begin(), y_vector.end());\n \n for (int j = 0; j < static_cast<int>(y_vector.size()); ++j ) {\n \n StringVector x_vector = split_string_list(y_vector[j], \" \");\n \n for (int i = 0; i < static_cast<int>(x_vector.size()); ++i ) {\n \n std::array<int, 2> location{i, j};\n material_mapping_[location] = string_to_int(x_vector[i]);\n }\n n_material_cells_[0] = x_vector.size();\n }\n n_material_cells_[1] = y_vector.size();\n}\n\ntemplate <int dim> \nvoid MeshCartesian<dim>::FillMaterialID(dealii::Triangulation<dim> &to_fill) {\n for (auto cell = to_fill.begin_active(); cell != to_fill.end(); ++cell) {\n if (cell->is_locally_owned()) {\n int material_id = GetMaterialID(cell->center());\n cell->set_material_id(material_id);\n }\n }\n}\n\ntemplate <int dim>\nvoid MeshCartesian<dim>::FillBoundaryID(dealii::Triangulation<dim> &to_fill) {\n using Boundary = bart::problem::Boundary;\n int faces_per_cell = dealii::GeometryInfo<dim>::faces_per_cell;\n double zero_tol = 1.0e-14;\n \n for (auto cell = to_fill.begin_active(); cell != to_fill.end(); ++cell) {\n if (cell->is_locally_owned()) {\n for (int face_id = 0; face_id < faces_per_cell; ++face_id) {\n auto face = cell->face(face_id);\n dealii::Point<dim> face_center = face->center();\n\n switch (dim) {\n case 2: {\n if (std::fabs(face_center[1]) < zero_tol) {\n face->set_boundary_id(static_cast<int>(Boundary::kYMin));\n break;\n } else if (std::fabs(face_center[1] - spatial_max_[1]) < zero_tol) {\n face->set_boundary_id(static_cast<int>(Boundary::kYMax));\n break;\n }\n [[fallthrough]];\n }\n \/\/ Fall through to check x-direction\n case 1: {\n if (std::fabs(face_center[0]) < zero_tol) {\n face->set_boundary_id(static_cast<int>(Boundary::kXMin));\n break;\n } else if (std::fabs(face_center[0] - spatial_max_[0]) < zero_tol) {\n face->set_boundary_id(static_cast<int>(Boundary::kXMax));\n break;\n }\n break;\n }\n default: {\n AssertThrow(false,\n dealii::ExcMessage(\"Unsupported number of dimensions in FillBoundaryID\"));\n }\n }\n }\n }\n }\n}\n \n\ntemplate <int dim>\nint MeshCartesian<dim>::GetMaterialID(dealii::Point<dim> location) {\n std::array<double, dim> array_location;\n for (int i = 0; i < dim; ++i)\n array_location[i] = location[i];\n return GetMaterialID(array_location);\n}\n \ntemplate <int dim>\nint MeshCartesian<dim>::GetMaterialID(std::array<double, dim> location) {\n std::array<int, 2> relative_location{0, 0};\n\n for (int i = 0; i < dim; ++i) {\n double cell_size = spatial_max_[i]\/n_material_cells_[i];\n double cell_location = location[i] \/ cell_size;\n int cell_index = std::floor(cell_location);\n\n if (static_cast<double>(cell_index) == cell_location && cell_index != 0) {\n relative_location[i] = cell_index - 1;\n } else {\n relative_location[i] = cell_index; \n }\n }\n \n return material_mapping_[relative_location];\n}\n\ntemplate class MeshCartesian<1>;\ntemplate class MeshCartesian<2>;\n\n} \/\/ namespace domain\n\n} \/\/ namespace bart \n<|endoftext|>"} {"text":"<commit_before>#include \"..\/VFrame\/VGame.h\"\n#include \"..\/Example\/States.h\"\n\nint main()\n{\n\tVGame* game = new VGame();\n\n\tsf::ContextSettings settings;\n\tsettings.depthBits = 32;\n\tsettings.stencilBits = 8;\n\tsettings.antialiasingLevel = 0;\n\tsettings.majorVersion = 4;\n\tsettings.minorVersion = 5;\n\n\tint r = game->Run(\"VFrame Stuff with SFML \" + std::to_string(SFML_VERSION_MAJOR) + \".\" + std::to_string(SFML_VERSION_MINOR) + \".\" = std::to_string(SFML_VERSION_PATCH), new DemoStatesManager(), 640, 360, 60.0f, 7, settings);\n\tdelete game;\n\treturn r;\n}\n<commit_msg>Reducing depth bits to 24-bits for more compatability.<commit_after>#include \"..\/VFrame\/VGame.h\"\n#include \"..\/Example\/States.h\"\n\nint main()\n{\n\tVGame* game = new VGame();\n\n\tsf::ContextSettings settings;\n\tsettings.depthBits = 24;\n\tsettings.stencilBits = 8;\n\tsettings.antialiasingLevel = 0;\n\tsettings.majorVersion = 4;\n\tsettings.minorVersion = 5;\n\n\tint r = game->Run(\"VFrame Stuff with SFML \" + std::to_string(SFML_VERSION_MAJOR) + \".\" + std::to_string(SFML_VERSION_MINOR) + \".\" = std::to_string(SFML_VERSION_PATCH), new DemoStatesManager(), 640, 360, 60.0f, 7, settings);\n\tdelete game;\n\treturn r;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"stdafx.h\"\n\n#include \"TimeUtilities.h\"\n\n#include <time.h>\n\nnamespace SDK\n\t{\n\n\tnamespace Utilities\n\t\t{\n\n\t\tvoid SleepSeconds(ulong i_seconds)\n\t\t\t{\n\t\t\tclock_t now = clock();\n\t\t\tclock_t limit = now + i_seconds * CLOCKS_PER_SEC;\n\t\t\twhile ( limit > now )\n\t\t\t\tnow = clock();\n\t\t\t}\n\n\t\tvoid SleepMiliseconds(ulong i_miliseconds)\n\t\t\t{\n\t\t\tlong timeout = clock() + i_miliseconds;\n\t\t\twhile( clock() < timeout ) continue;\n\t\t\t}\n\n\t\t} \/\/ Utilities\n\n\t} \/\/ SDK<commit_msg>[Utilities] Use standard functions for Linux and Windows<commit_after>#include \"stdafx.h\"\n\n#include \"TimeUtilities.h\"\n\n#include <time.h>\n\n#ifdef _WIN32\n #include <windows.h>\n#else\n #include <unistd.h>\n#endif\n\n\nnamespace SDK\n\t{\n\n\tnamespace Utilities\n\t\t{\n\n\t\tvoid SleepSeconds(ulong i_seconds)\n\t\t\t{\n\t\t\tSleepMiliseconds(i_seconds*1000);\n\t\t\t}\n\n\t\tvoid SleepMiliseconds(ulong i_miliseconds)\n\t\t\t{\n\t\t\t#ifdef _WIN32\n\t\t\t\tSleep(i_miliseconds);\n\t\t\t#else\n\t\t\t usleep(i_miliseconds * 1000); \/\/ takes microseconds\n\t\t\t#endif\n\t\t\t}\n\n\t\t} \/\/ Utilities\n\n\t} \/\/ SDK<|endoftext|>"} {"text":"<commit_before>\/*!\n \\file timestamp.cpp\n \\brief Timestamp implementation\n \\author Ivan Shynkarenka\n \\date 26.01.2016\n \\copyright MIT License\n*\/\n\n#include \"time\/timestamp.h\"\n\n#include \"math\/math.h\"\n\n#if defined(__APPLE__)\n#include <mach\/mach.h>\n#include <mach\/mach_time.h>\n#include <sys\/time.h>\n#include <math.h>\n#include <time.h>\n#elif defined(unix) || defined(__unix) || defined(__unix__)\n#include <time.h>\n#elif defined(_WIN32) || defined(_WIN64)\n#include <windows.h>\n#endif\n\nnamespace CppCommon {\n\n\/\/! @cond INTERNALS\nnamespace Internals {\n\n#if defined(__APPLE__)\n\nuint32_t CeilLog2(uint32_t x)\n{\n uint32_t result = 0;\n\n --x;\n while (x > 0)\n {\n ++result;\n x >>= 1;\n }\n\n return result;\n}\n\n\/\/ This function returns the rational number inside the given interval with\n\/\/ the smallest denominator (and smallest numerator breaks ties; correctness\n\/\/ proof neglects floating-point errors).\nmach_timebase_info_data_t BestFrac(double a, double b)\n{\n if (floor(a) < floor(b))\n {\n mach_timebase_info_data_t rv = { (uint32_t)ceil(a), 1 };\n return rv;\n }\n\n double m = floor(a);\n mach_timebase_info_data_t next = BestFrac(1 \/ (b - m), 1 \/ (a - m));\n mach_timebase_info_data_t rv = { (int)m * next.numer + next.denom, next.numer };\n return rv;\n}\n\n\/\/ This is just less than the smallest thing we can multiply numer by without\n\/\/ overflowing. CeilLog2(numer) = 64 - number of leading zeros of numer\nuint64_t GetExpressibleSpan(uint32_t numer, uint32_t denom)\n{\n uint64_t maxDiffWithoutOverflow = ((uint64_t)1 << (64 - CeilLog2(numer))) - 1;\n return maxDiffWithoutOverflow * numer \/ denom;\n}\n\n\/\/ The clock may run up to 0.1% faster or slower than the \"exact\" tick count.\n\/\/ However, although the bound on the error is the same as for the pragmatic\n\/\/ answer, the error is actually minimized over the given accuracy bound.\nuint64_t PrepareTimebaseInfo(mach_timebase_info_data_t& tb)\n{\n tb.numer = 0;\n tb.denom = 1;\n\n kern_return_t mtiStatus = mach_timebase_info(&tb);\n if (mtiStatus != KERN_SUCCESS)\n return 0;\n\n double frac = (double)tb.numer \/ tb.denom;\n uint64_t spanTarget = 315360000000000000llu;\n if (GetExpressibleSpan(tb.numer, tb.denom) >= spanTarget)\n return 0;\n\n for (double errorTarget = 1 \/ 1024.0; errorTarget > 0.000001;)\n {\n mach_timebase_info_data_t newFrac = BestFrac((1 - errorTarget) * frac, (1 + errorTarget) * frac);\n if (GetExpressibleSpan(newFrac.numer, newFrac.denom) < spanTarget)\n break;\n tb = newFrac;\n errorTarget = fabs((double)tb.numer \/ tb.denom - frac) \/ frac \/ 8;\n }\n\n return mach_absolute_time();\n}\n\n#endif\n\n} \/\/ namespace Internals\n\/\/! @endcond\n\nuint64_t Timestamp::utc()\n{\n#if defined(unix) || defined(__unix) || defined(__unix__) || defined(__APPLE__)\n struct timespec timestamp;\n if (clock_gettime(CLOCK_REALTIME, ×tamp) != 0)\n throwex SystemException(\"Cannot get value of CLOCK_REALTIME timer!\");\n return (timestamp.tv_sec * 1000000000) + timestamp.tv_nsec;\n#elif defined(_WIN32) || defined(_WIN64)\n FILETIME ft;\n GetSystemTimePreciseAsFileTime(&ft);\n\n ULARGE_INTEGER result;\n result.LowPart = ft.dwLowDateTime;\n result.HighPart = ft.dwHighDateTime;\n return (result.QuadPart - 116444736000000000ull) * 100;\n#endif\n}\n\nuint64_t Timestamp::local()\n{\n#if defined(unix) || defined(__unix) || defined(__unix__) || defined(__APPLE__)\n uint64_t timestamp = utc();\n\n \/\/ Adjust UTC time with local timezone offset\n struct tm local;\n time_t seconds = timestamp \/ (1000000000);\n if (localtime_r(&seconds, &local) != &local)\n throwex SystemException(\"Cannot convert CLOCK_REALTIME time to local date & time structure!\");\n return timestamp + (local.tm_gmtoff * 1000000000);\n#elif defined(_WIN32) || defined(_WIN64)\n FILETIME ft;\n GetSystemTimePreciseAsFileTime(&ft);\n\n FILETIME ft_local;\n if (!FileTimeToLocalFileTime(&ft, &ft_local))\n throwex SystemException(\"Cannot convert UTC file time to local file time structure!\");\n\n ULARGE_INTEGER result;\n result.LowPart = ft_local.dwLowDateTime;\n result.HighPart = ft_local.dwHighDateTime;\n return (result.QuadPart - 116444736000000000ull) * 100;\n#endif\n}\n\nuint64_t Timestamp::nano()\n{\n#if defined(__APPLE__)\n static mach_timebase_info_data_t info;\n static uint64_t bias = Internals::PrepareTimebaseInfo(info);\n return ((mach_absolute_time() - bias) * info.numer) \/ info.denom;\n#elif defined(unix) || defined(__unix) || defined(__unix__)\n struct timespec timestamp = { 0 };\n if (clock_gettime(CLOCK_MONOTONIC, ×tamp) != 0)\n throwex SystemException(\"Cannot get value of CLOCK_MONOTONIC timer!\");\n return (timestamp.tv_sec * 1000000000) + timestamp.tv_nsec;\n#elif defined(_WIN32) || defined(_WIN64)\n static uint64_t offset = 0;\n static LARGE_INTEGER first = { 0 };\n static LARGE_INTEGER frequency = { 0 };\n static bool initialized = false;\n static bool qpc = true;\n\n if (!initialized)\n {\n \/\/ Calculate timestamp offset\n FILETIME timestamp;\n GetSystemTimePreciseAsFileTime(×tamp);\n\n ULARGE_INTEGER result;\n result.LowPart = timestamp.dwLowDateTime;\n result.HighPart = timestamp.dwHighDateTime;\n\n \/\/ Convert 01.01.1601 to 01.01.1970\n result.QuadPart -= 116444736000000000ll;\n offset = result.QuadPart * 100;\n\n \/\/ Setup performance counter\n qpc = QueryPerformanceFrequency(&frequency) && QueryPerformanceCounter(&first);\n\n initialized = true;\n }\n\n if (qpc)\n {\n LARGE_INTEGER timestamp = { 0 };\n QueryPerformanceCounter(×tamp);\n timestamp.QuadPart -= first.QuadPart;\n return offset + Math::MulDiv64(timestamp.QuadPart, 1000000000, frequency.QuadPart);\n }\n else\n return offset;\n#else\n #error Unsupported platform\n#endif\n}\n\nuint64_t Timestamp::rdts()\n{\n#if defined(_MSC_VER)\n return __rdtsc();\n#elif defined(__i386__)\n uint64_t x;\n __asm__ volatile (\".byte 0x0f, 0x31\" : \"=A\" (x));\n return x;\n#elif defined(__x86_64__)\n unsigned hi, lo;\n __asm__ __volatile__ (\"rdtsc\" : \"=a\"(lo), \"=d\"(hi));\n return ((uint64_t)lo) | (((uint64_t)hi) << 32);\n#endif\n}\n\n} \/\/ namespace CppCommon\n<commit_msg>update<commit_after>\/*!\n \\file timestamp.cpp\n \\brief Timestamp implementation\n \\author Ivan Shynkarenka\n \\date 26.01.2016\n \\copyright MIT License\n*\/\n\n#include \"time\/timestamp.h\"\n\n#include \"math\/math.h\"\n\n#if defined(__APPLE__)\n#include <mach\/mach.h>\n#include <mach\/mach_time.h>\n#include <sys\/time.h>\n#include <math.h>\n#include <time.h>\n#elif defined(unix) || defined(__unix) || defined(__unix__)\n#include <time.h>\n#elif defined(_WIN32) || defined(_WIN64)\n#include <windows.h>\n#endif\n\nnamespace CppCommon {\n\n\/\/! @cond INTERNALS\nnamespace Internals {\n\n#if defined(__APPLE__)\n\nuint32_t CeilLog2(uint32_t x)\n{\n uint32_t result = 0;\n\n --x;\n while (x > 0)\n {\n ++result;\n x >>= 1;\n }\n\n return result;\n}\n\n\/\/ This function returns the rational number inside the given interval with\n\/\/ the smallest denominator (and smallest numerator breaks ties; correctness\n\/\/ proof neglects floating-point errors).\nmach_timebase_info_data_t BestFrac(double a, double b)\n{\n if (floor(a) < floor(b))\n {\n mach_timebase_info_data_t rv = { (uint32_t)ceil(a), 1 };\n return rv;\n }\n\n double m = floor(a);\n mach_timebase_info_data_t next = BestFrac(1 \/ (b - m), 1 \/ (a - m));\n mach_timebase_info_data_t rv = { (int)m * next.numer + next.denom, next.numer };\n return rv;\n}\n\n\/\/ This is just less than the smallest thing we can multiply numer by without\n\/\/ overflowing. CeilLog2(numer) = 64 - number of leading zeros of numer\nuint64_t GetExpressibleSpan(uint32_t numer, uint32_t denom)\n{\n uint64_t maxDiffWithoutOverflow = ((uint64_t)1 << (64 - CeilLog2(numer))) - 1;\n return maxDiffWithoutOverflow * numer \/ denom;\n}\n\n\/\/ The clock may run up to 0.1% faster or slower than the \"exact\" tick count.\n\/\/ However, although the bound on the error is the same as for the pragmatic\n\/\/ answer, the error is actually minimized over the given accuracy bound.\nuint64_t PrepareTimebaseInfo(mach_timebase_info_data_t& tb)\n{\n tb.numer = 0;\n tb.denom = 1;\n\n kern_return_t mtiStatus = mach_timebase_info(&tb);\n if (mtiStatus != KERN_SUCCESS)\n return 0;\n\n double frac = (double)tb.numer \/ tb.denom;\n uint64_t spanTarget = 315360000000000000llu;\n if (GetExpressibleSpan(tb.numer, tb.denom) >= spanTarget)\n return 0;\n\n for (double errorTarget = 1 \/ 1024.0; errorTarget > 0.000001;)\n {\n mach_timebase_info_data_t newFrac = BestFrac((1 - errorTarget) * frac, (1 + errorTarget) * frac);\n if (GetExpressibleSpan(newFrac.numer, newFrac.denom) < spanTarget)\n break;\n tb = newFrac;\n errorTarget = fabs((double)tb.numer \/ tb.denom - frac) \/ frac \/ 8;\n }\n\n return 0;\n}\n\n#endif\n\n} \/\/ namespace Internals\n\/\/! @endcond\n\nuint64_t Timestamp::utc()\n{\n#if defined(unix) || defined(__unix) || defined(__unix__) || defined(__APPLE__)\n struct timespec timestamp;\n if (clock_gettime(CLOCK_REALTIME, ×tamp) != 0)\n throwex SystemException(\"Cannot get value of CLOCK_REALTIME timer!\");\n return (timestamp.tv_sec * 1000000000) + timestamp.tv_nsec;\n#elif defined(_WIN32) || defined(_WIN64)\n FILETIME ft;\n GetSystemTimePreciseAsFileTime(&ft);\n\n ULARGE_INTEGER result;\n result.LowPart = ft.dwLowDateTime;\n result.HighPart = ft.dwHighDateTime;\n return (result.QuadPart - 116444736000000000ull) * 100;\n#endif\n}\n\nuint64_t Timestamp::local()\n{\n#if defined(unix) || defined(__unix) || defined(__unix__) || defined(__APPLE__)\n uint64_t timestamp = utc();\n\n \/\/ Adjust UTC time with local timezone offset\n struct tm local;\n time_t seconds = timestamp \/ (1000000000);\n if (localtime_r(&seconds, &local) != &local)\n throwex SystemException(\"Cannot convert CLOCK_REALTIME time to local date & time structure!\");\n return timestamp + (local.tm_gmtoff * 1000000000);\n#elif defined(_WIN32) || defined(_WIN64)\n FILETIME ft;\n GetSystemTimePreciseAsFileTime(&ft);\n\n FILETIME ft_local;\n if (!FileTimeToLocalFileTime(&ft, &ft_local))\n throwex SystemException(\"Cannot convert UTC file time to local file time structure!\");\n\n ULARGE_INTEGER result;\n result.LowPart = ft_local.dwLowDateTime;\n result.HighPart = ft_local.dwHighDateTime;\n return (result.QuadPart - 116444736000000000ull) * 100;\n#endif\n}\n\nuint64_t Timestamp::nano()\n{\n#if defined(__APPLE__)\n static mach_timebase_info_data_t info;\n static uint64_t bias = Internals::PrepareTimebaseInfo(info);\n return ((mach_absolute_time() - bias) * info.numer) \/ info.denom;\n#elif defined(unix) || defined(__unix) || defined(__unix__)\n struct timespec timestamp = { 0 };\n if (clock_gettime(CLOCK_MONOTONIC, ×tamp) != 0)\n throwex SystemException(\"Cannot get value of CLOCK_MONOTONIC timer!\");\n return (timestamp.tv_sec * 1000000000) + timestamp.tv_nsec;\n#elif defined(_WIN32) || defined(_WIN64)\n static uint64_t offset = 0;\n static LARGE_INTEGER first = { 0 };\n static LARGE_INTEGER frequency = { 0 };\n static bool initialized = false;\n static bool qpc = true;\n\n if (!initialized)\n {\n \/\/ Calculate timestamp offset\n FILETIME timestamp;\n GetSystemTimePreciseAsFileTime(×tamp);\n\n ULARGE_INTEGER result;\n result.LowPart = timestamp.dwLowDateTime;\n result.HighPart = timestamp.dwHighDateTime;\n\n \/\/ Convert 01.01.1601 to 01.01.1970\n result.QuadPart -= 116444736000000000ll;\n offset = result.QuadPart * 100;\n\n \/\/ Setup performance counter\n qpc = QueryPerformanceFrequency(&frequency) && QueryPerformanceCounter(&first);\n\n initialized = true;\n }\n\n if (qpc)\n {\n LARGE_INTEGER timestamp = { 0 };\n QueryPerformanceCounter(×tamp);\n timestamp.QuadPart -= first.QuadPart;\n return offset + Math::MulDiv64(timestamp.QuadPart, 1000000000, frequency.QuadPart);\n }\n else\n return offset;\n#else\n #error Unsupported platform\n#endif\n}\n\nuint64_t Timestamp::rdts()\n{\n#if defined(_MSC_VER)\n return __rdtsc();\n#elif defined(__i386__)\n uint64_t x;\n __asm__ volatile (\".byte 0x0f, 0x31\" : \"=A\" (x));\n return x;\n#elif defined(__x86_64__)\n unsigned hi, lo;\n __asm__ __volatile__ (\"rdtsc\" : \"=a\"(lo), \"=d\"(hi));\n return ((uint64_t)lo) | (((uint64_t)hi) << 32);\n#endif\n}\n\n} \/\/ namespace CppCommon\n<|endoftext|>"} {"text":"<commit_before>\/\/===------------------------ CalcSpillWeights.cpp ------------------------===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#define DEBUG_TYPE \"calcspillweights\"\n\n#include \"llvm\/Function.h\"\n#include \"llvm\/ADT\/SmallSet.h\"\n#include \"llvm\/CodeGen\/CalcSpillWeights.h\"\n#include \"llvm\/CodeGen\/LiveIntervalAnalysis.h\"\n#include \"llvm\/CodeGen\/MachineFunction.h\"\n#include \"llvm\/CodeGen\/MachineLoopInfo.h\"\n#include \"llvm\/CodeGen\/MachineRegisterInfo.h\"\n#include \"llvm\/CodeGen\/SlotIndexes.h\"\n#include \"llvm\/Support\/Debug.h\"\n#include \"llvm\/Support\/raw_ostream.h\"\n#include \"llvm\/Target\/TargetInstrInfo.h\"\n#include \"llvm\/Target\/TargetRegisterInfo.h\"\n\nusing namespace llvm;\n\nchar CalculateSpillWeights::ID = 0;\nstatic RegisterPass<CalculateSpillWeights> X(\"calcspillweights\",\n \"Calculate spill weights\");\n\nvoid CalculateSpillWeights::getAnalysisUsage(AnalysisUsage &au) const {\n au.addRequired<LiveIntervals>();\n au.addRequired<MachineLoopInfo>();\n au.setPreservesAll();\n MachineFunctionPass::getAnalysisUsage(au);\n}\n\nbool CalculateSpillWeights::runOnMachineFunction(MachineFunction &fn) {\n\n DEBUG(errs() << \"********** Compute Spill Weights **********\\n\"\n << \"********** Function: \"\n << fn.getFunction()->getName() << '\\n');\n\n LiveIntervals *lis = &getAnalysis<LiveIntervals>();\n MachineLoopInfo *loopInfo = &getAnalysis<MachineLoopInfo>();\n const TargetInstrInfo *tii = fn.getTarget().getInstrInfo();\n MachineRegisterInfo *mri = &fn.getRegInfo();\n\n SmallSet<unsigned, 4> processed;\n for (MachineFunction::iterator mbbi = fn.begin(), mbbe = fn.end();\n mbbi != mbbe; ++mbbi) {\n MachineBasicBlock* mbb = mbbi;\n SlotIndex mbbEnd = lis->getMBBEndIdx(mbb);\n MachineLoop* loop = loopInfo->getLoopFor(mbb);\n unsigned loopDepth = loop ? loop->getLoopDepth() : 0;\n bool isExiting = loop ? loop->isLoopExiting(mbb) : false;\n\n for (MachineBasicBlock::const_iterator mii = mbb->begin(), mie = mbb->end();\n mii != mie; ++mii) {\n const MachineInstr *mi = mii;\n if (tii->isIdentityCopy(*mi))\n continue;\n\n if (mi->getOpcode() == TargetInstrInfo::IMPLICIT_DEF)\n continue;\n\n for (unsigned i = 0, e = mi->getNumOperands(); i != e; ++i) {\n const MachineOperand &mopi = mi->getOperand(i);\n if (!mopi.isReg() || mopi.getReg() == 0)\n continue;\n unsigned reg = mopi.getReg();\n if (!TargetRegisterInfo::isVirtualRegister(mopi.getReg()))\n continue;\n \/\/ Multiple uses of reg by the same instruction. It should not\n \/\/ contribute to spill weight again.\n if (!processed.insert(reg))\n continue;\n\n bool hasDef = mopi.isDef();\n bool hasUse = !hasDef;\n for (unsigned j = i+1; j != e; ++j) {\n const MachineOperand &mopj = mi->getOperand(j);\n if (!mopj.isReg() || mopj.getReg() != reg)\n continue;\n hasDef |= mopj.isDef();\n hasUse |= mopj.isUse();\n if (hasDef && hasUse)\n break;\n }\n\n LiveInterval ®Int = lis->getInterval(reg);\n float weight = lis->getSpillWeight(hasDef, hasUse, loopDepth);\n if (hasDef && isExiting) {\n \/\/ Looks like this is a loop count variable update.\n SlotIndex defIdx = lis->getInstructionIndex(mi).getDefIndex();\n const LiveRange *dlr =\n lis->getInterval(reg).getLiveRangeContaining(defIdx);\n if (dlr->end >= mbbEnd)\n weight *= 3.0F;\n }\n regInt.weight += weight;\n }\n processed.clear();\n }\n }\n\n for (LiveIntervals::iterator I = lis->begin(), E = lis->end(); I != E; ++I) {\n LiveInterval &li = *I->second;\n if (TargetRegisterInfo::isVirtualRegister(li.reg)) {\n \/\/ If the live interval length is essentially zero, i.e. in every live\n \/\/ range the use follows def immediately, it doesn't make sense to spill\n \/\/ it and hope it will be easier to allocate for this li.\n if (isZeroLengthInterval(&li)) {\n li.weight = HUGE_VALF;\n continue;\n }\n\n bool isLoad = false;\n SmallVector<LiveInterval*, 4> spillIs;\n if (lis->isReMaterializable(li, spillIs, isLoad)) {\n \/\/ If all of the definitions of the interval are re-materializable,\n \/\/ it is a preferred candidate for spilling. If non of the defs are\n \/\/ loads, then it's potentially very cheap to re-materialize.\n \/\/ FIXME: this gets much more complicated once we support non-trivial\n \/\/ re-materialization.\n if (isLoad)\n li.weight *= 0.9F;\n else\n li.weight *= 0.5F;\n }\n\n \/\/ Slightly prefer live interval that has been assigned a preferred reg.\n std::pair<unsigned, unsigned> Hint = mri->getRegAllocationHint(li.reg);\n if (Hint.first || Hint.second)\n li.weight *= 1.01F;\n\n \/\/ Divide the weight of the interval by its size. This encourages\n \/\/ spilling of intervals that are large and have few uses, and\n \/\/ discourages spilling of small intervals with many uses.\n li.weight \/= lis->getApproximateInstructionCount(li) * SlotIndex::NUM;\n }\n }\n \n return false;\n}\n\n\/\/\/ Returns true if the given live interval is zero length.\nbool CalculateSpillWeights::isZeroLengthInterval(LiveInterval *li) const {\n for (LiveInterval::Ranges::const_iterator\n i = li->ranges.begin(), e = li->ranges.end(); i != e; ++i)\n if (i->end.getPrevIndex() > i->start)\n return false;\n return true;\n}\n<commit_msg><commit_after>\/\/===------------------------ CalcSpillWeights.cpp ------------------------===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#define DEBUG_TYPE \"calcspillweights\"\n\n#include \"llvm\/Function.h\"\n#include \"llvm\/ADT\/SmallSet.h\"\n#include \"llvm\/CodeGen\/CalcSpillWeights.h\"\n#include \"llvm\/CodeGen\/LiveIntervalAnalysis.h\"\n#include \"llvm\/CodeGen\/MachineFunction.h\"\n#include \"llvm\/CodeGen\/MachineLoopInfo.h\"\n#include \"llvm\/CodeGen\/MachineRegisterInfo.h\"\n#include \"llvm\/CodeGen\/SlotIndexes.h\"\n#include \"llvm\/Support\/Debug.h\"\n#include \"llvm\/Support\/raw_ostream.h\"\n#include \"llvm\/Target\/TargetInstrInfo.h\"\n#include \"llvm\/Target\/TargetRegisterInfo.h\"\n\nusing namespace llvm;\n\nchar CalculateSpillWeights::ID = 0;\nstatic RegisterPass<CalculateSpillWeights> X(\"calcspillweights\",\n \"Calculate spill weights\");\n\nvoid CalculateSpillWeights::getAnalysisUsage(AnalysisUsage &au) const {\n au.addRequired<LiveIntervals>();\n au.addRequired<MachineLoopInfo>();\n au.setPreservesAll();\n MachineFunctionPass::getAnalysisUsage(au);\n}\n\nbool CalculateSpillWeights::runOnMachineFunction(MachineFunction &fn) {\n\n DEBUG(dbgs() << \"********** Compute Spill Weights **********\\n\"\n << \"********** Function: \"\n << fn.getFunction()->getName() << '\\n');\n\n LiveIntervals *lis = &getAnalysis<LiveIntervals>();\n MachineLoopInfo *loopInfo = &getAnalysis<MachineLoopInfo>();\n const TargetInstrInfo *tii = fn.getTarget().getInstrInfo();\n MachineRegisterInfo *mri = &fn.getRegInfo();\n\n SmallSet<unsigned, 4> processed;\n for (MachineFunction::iterator mbbi = fn.begin(), mbbe = fn.end();\n mbbi != mbbe; ++mbbi) {\n MachineBasicBlock* mbb = mbbi;\n SlotIndex mbbEnd = lis->getMBBEndIdx(mbb);\n MachineLoop* loop = loopInfo->getLoopFor(mbb);\n unsigned loopDepth = loop ? loop->getLoopDepth() : 0;\n bool isExiting = loop ? loop->isLoopExiting(mbb) : false;\n\n for (MachineBasicBlock::const_iterator mii = mbb->begin(), mie = mbb->end();\n mii != mie; ++mii) {\n const MachineInstr *mi = mii;\n if (tii->isIdentityCopy(*mi))\n continue;\n\n if (mi->getOpcode() == TargetInstrInfo::IMPLICIT_DEF)\n continue;\n\n for (unsigned i = 0, e = mi->getNumOperands(); i != e; ++i) {\n const MachineOperand &mopi = mi->getOperand(i);\n if (!mopi.isReg() || mopi.getReg() == 0)\n continue;\n unsigned reg = mopi.getReg();\n if (!TargetRegisterInfo::isVirtualRegister(mopi.getReg()))\n continue;\n \/\/ Multiple uses of reg by the same instruction. It should not\n \/\/ contribute to spill weight again.\n if (!processed.insert(reg))\n continue;\n\n bool hasDef = mopi.isDef();\n bool hasUse = !hasDef;\n for (unsigned j = i+1; j != e; ++j) {\n const MachineOperand &mopj = mi->getOperand(j);\n if (!mopj.isReg() || mopj.getReg() != reg)\n continue;\n hasDef |= mopj.isDef();\n hasUse |= mopj.isUse();\n if (hasDef && hasUse)\n break;\n }\n\n LiveInterval ®Int = lis->getInterval(reg);\n float weight = lis->getSpillWeight(hasDef, hasUse, loopDepth);\n if (hasDef && isExiting) {\n \/\/ Looks like this is a loop count variable update.\n SlotIndex defIdx = lis->getInstructionIndex(mi).getDefIndex();\n const LiveRange *dlr =\n lis->getInterval(reg).getLiveRangeContaining(defIdx);\n if (dlr->end >= mbbEnd)\n weight *= 3.0F;\n }\n regInt.weight += weight;\n }\n processed.clear();\n }\n }\n\n for (LiveIntervals::iterator I = lis->begin(), E = lis->end(); I != E; ++I) {\n LiveInterval &li = *I->second;\n if (TargetRegisterInfo::isVirtualRegister(li.reg)) {\n \/\/ If the live interval length is essentially zero, i.e. in every live\n \/\/ range the use follows def immediately, it doesn't make sense to spill\n \/\/ it and hope it will be easier to allocate for this li.\n if (isZeroLengthInterval(&li)) {\n li.weight = HUGE_VALF;\n continue;\n }\n\n bool isLoad = false;\n SmallVector<LiveInterval*, 4> spillIs;\n if (lis->isReMaterializable(li, spillIs, isLoad)) {\n \/\/ If all of the definitions of the interval are re-materializable,\n \/\/ it is a preferred candidate for spilling. If non of the defs are\n \/\/ loads, then it's potentially very cheap to re-materialize.\n \/\/ FIXME: this gets much more complicated once we support non-trivial\n \/\/ re-materialization.\n if (isLoad)\n li.weight *= 0.9F;\n else\n li.weight *= 0.5F;\n }\n\n \/\/ Slightly prefer live interval that has been assigned a preferred reg.\n std::pair<unsigned, unsigned> Hint = mri->getRegAllocationHint(li.reg);\n if (Hint.first || Hint.second)\n li.weight *= 1.01F;\n\n \/\/ Divide the weight of the interval by its size. This encourages\n \/\/ spilling of intervals that are large and have few uses, and\n \/\/ discourages spilling of small intervals with many uses.\n li.weight \/= lis->getApproximateInstructionCount(li) * SlotIndex::NUM;\n }\n }\n \n return false;\n}\n\n\/\/\/ Returns true if the given live interval is zero length.\nbool CalculateSpillWeights::isZeroLengthInterval(LiveInterval *li) const {\n for (LiveInterval::Ranges::const_iterator\n i = li->ranges.begin(), e = li->ranges.end(); i != e; ++i)\n if (i->end.getPrevIndex() > i->start)\n return false;\n return true;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*********************************************************************************\n *\n * Inviwo - Interactive Visualization Workshop\n *\n * Copyright (c) 2014-2015 Inviwo Foundation\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * 1. Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR\n * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n * \n *********************************************************************************\/\n\n#include \"imagenormalizationprocessor.h\"\n#include <inviwo\/core\/datastructures\/image\/layerram.h>\n#include <modules\/opengl\/texture\/textureutils.h>\n#include <modules\/opengl\/shader\/shader.h>\n\nnamespace inviwo {\n\nconst ProcessorInfo ImageNormalizationProcessor::processorInfo_{\n \"org.inviwo.ImageNormalization\", \/\/ Class identifier\n \"Image Normalization\", \/\/ Display name\n \"Image Operation\", \/\/ Category\n CodeState::Experimental, \/\/ Code state\n Tags::GL, \/\/ Tags\n};\nconst ProcessorInfo ImageNormalizationProcessor::getProcessorInfo() const {\n return processorInfo_;\n}\n\nImageNormalizationProcessor::ImageNormalizationProcessor()\n : ImageGLProcessor(\"img_normalize.frag\")\n , minMaxInvalid_(true)\n , eachChannelsIndividually_(\"eachChannelsIndividually\",\"Normalize Channels Individually\") \n , zeroAtPoint5_(\"zeroAtPoint5\", \"Negative numbers below 0.5\",false)\n , minS_(\"min\",\"Min value\",\"\")\n , maxS_(\"max\", \"Max value\",\"\")\n , min_(0.0)\n , max_(1.0)\n{\n\n minS_.setInvalidationLevel(InvalidationLevel::Valid);\n maxS_.setInvalidationLevel(InvalidationLevel::Valid);\n minS_.setReadOnly(true);\n maxS_.setReadOnly(true);\n\n addProperty(eachChannelsIndividually_);\n addProperty(zeroAtPoint5_);\n addProperty(minS_);\n addProperty(maxS_);\n\n inport_.onChange(this, &ImageNormalizationProcessor::invalidateMinMax);\n eachChannelsIndividually_.onChange(this,&ImageNormalizationProcessor::invalidateMinMax);\n\n setAllPropertiesCurrentStateAsDefault();\n}\n\nImageNormalizationProcessor::~ImageNormalizationProcessor() {}\n\n\nvoid ImageNormalizationProcessor::preProcess() {\n if (minMaxInvalid_) updateMinMax();\n \n if (eachChannelsIndividually_.get()) {\n shader_.setUniform(\"min_\", static_cast<vec4>(min_));\n shader_.setUniform(\"max_\", static_cast<vec4>(max_));\n } else {\n double min = std::min(std::min(min_.x,min_.y),min_.z);\n double max = std::max(std::max(max_.x,max_.y),max_.z);\n shader_.setUniform(\"min_\", vec4(min,min,min,0.0f));\n shader_.setUniform(\"max_\", vec4(max,max,max,1.0f));\n }\n}\n\n\nvoid ImageNormalizationProcessor::updateMinMax() {\n minMaxInvalid_ = true;\n}\n\nvoid ImageNormalizationProcessor::invalidateMinMax() {\n if (!inport_.hasData()) return;\n const LayerRAM* img = inport_.getData()->getColorLayer()->getRepresentation<LayerRAM>();\n\n uvec2 dim = img->getDimensions();\n uvec2 pixel(0, 0);\n min_ = img->getValueAsVec4Double(pixel);\n max_ = img->getValueAsVec4Double(pixel);\n for(pixel.y = 0;pixel.y< dim.y;pixel.y++)for(pixel.x = 0;pixel.x< dim.x;pixel.x++){\n dvec4 pixelValue = img->getValueAsVec4Double(pixel);\n min_ = glm::min(min_, pixelValue);\n max_ = glm::max(max_, pixelValue);\n }\n\n\n minS_.set(toString(min_));\n maxS_.set(toString(max_));\n\n\n if (zeroAtPoint5_) {\n max_ = glm::max(glm::abs(min_), glm::abs(max_));\n min_ = -max_;\n }\n\n min_.a = 0.0; \/\/never normalize alpha\n max_.a = 1.0;\n minMaxInvalid_ = false;\n}\n\n} \/\/ namespace\n\n\n<commit_msg>BaseGL: ImageNormalizationProcessor: Moved the zeroAtpoint5 code to preProcess from onChange since it is only called when the image changed<commit_after>\/*********************************************************************************\n *\n * Inviwo - Interactive Visualization Workshop\n *\n * Copyright (c) 2014-2015 Inviwo Foundation\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * 1. Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR\n * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n * \n *********************************************************************************\/\n\n#include \"imagenormalizationprocessor.h\"\n#include <inviwo\/core\/datastructures\/image\/layerram.h>\n#include <modules\/opengl\/texture\/textureutils.h>\n#include <modules\/opengl\/shader\/shader.h>\n\nnamespace inviwo {\n\nconst ProcessorInfo ImageNormalizationProcessor::processorInfo_{\n \"org.inviwo.ImageNormalization\", \/\/ Class identifier\n \"Image Normalization\", \/\/ Display name\n \"Image Operation\", \/\/ Category\n CodeState::Experimental, \/\/ Code state\n Tags::GL, \/\/ Tags\n};\nconst ProcessorInfo ImageNormalizationProcessor::getProcessorInfo() const {\n return processorInfo_;\n}\n\nImageNormalizationProcessor::ImageNormalizationProcessor()\n : ImageGLProcessor(\"img_normalize.frag\")\n , minMaxInvalid_(true)\n , eachChannelsIndividually_(\"eachChannelsIndividually\",\"Normalize Channels Individually\") \n , zeroAtPoint5_(\"zeroAtPoint5\", \"Negative numbers below 0.5\",false)\n , minS_(\"min\",\"Min value\",\"\")\n , maxS_(\"max\", \"Max value\",\"\")\n , min_(0.0)\n , max_(1.0)\n{\n\n minS_.setInvalidationLevel(InvalidationLevel::Valid);\n maxS_.setInvalidationLevel(InvalidationLevel::Valid);\n minS_.setReadOnly(true);\n maxS_.setReadOnly(true);\n\n addProperty(eachChannelsIndividually_);\n addProperty(zeroAtPoint5_);\n addProperty(minS_);\n addProperty(maxS_);\n\n inport_.onChange(this, &ImageNormalizationProcessor::invalidateMinMax);\n eachChannelsIndividually_.onChange(this,&ImageNormalizationProcessor::invalidateMinMax);\n\n setAllPropertiesCurrentStateAsDefault();\n}\n\nImageNormalizationProcessor::~ImageNormalizationProcessor() {}\n\n\nvoid ImageNormalizationProcessor::preProcess() {\n if (minMaxInvalid_) updateMinMax();\n \n auto min = min_;\n auto max = max_;\n\n if (zeroAtPoint5_) {\n max.rgb = glm::max(glm::abs(min.rgb()), glm::abs(max.rgb()));\n min.rgb = -max.rgb();\n }\n\n if (eachChannelsIndividually_.get()) {\n shader_.setUniform(\"min_\", static_cast<vec4>(min));\n shader_.setUniform(\"max_\", static_cast<vec4>(max));\n } else {\n double minV = std::min(std::min(min.x,min.y),min.z);\n double maxV = std::max(std::max(max.x,max.y),max.z);\n shader_.setUniform(\"min_\", vec4(minV, minV, minV,0.0f));\n shader_.setUniform(\"max_\", vec4(maxV, maxV, maxV,1.0f));\n }\n}\n\n\nvoid ImageNormalizationProcessor::updateMinMax() {\n minMaxInvalid_ = true;\n}\n\nvoid ImageNormalizationProcessor::invalidateMinMax() {\n if (!inport_.hasData()) return;\n const LayerRAM* img = inport_.getData()->getColorLayer()->getRepresentation<LayerRAM>();\n\n uvec2 dim = img->getDimensions();\n uvec2 pixel(0, 0);\n min_ = img->getValueAsVec4Double(pixel);\n max_ = img->getValueAsVec4Double(pixel);\n for(pixel.y = 0;pixel.y< dim.y;pixel.y++)for(pixel.x = 0;pixel.x< dim.x;pixel.x++){\n dvec4 pixelValue = img->getValueAsVec4Double(pixel);\n min_ = glm::min(min_, pixelValue);\n max_ = glm::max(max_, pixelValue);\n }\n\n\n minS_.set(toString(min_));\n maxS_.set(toString(max_));\n\n\n \n\n min_.a = 0.0; \/\/never normalize alpha\n max_.a = 1.0;\n minMaxInvalid_ = false;\n}\n\n} \/\/ namespace\n\n\n<|endoftext|>"} {"text":"<commit_before>\/*******************************************************************************[MaxSatInstance.cc]\nMagpie -- Florian Letombe, Joao Marques-Silva, Paulo Matos, Jordi Planes (2007)\n\nParts of the code in this file have been extracted from SATzilla.\n**************************************************************************************************\/\n\n#include <algorithm>\n\n#include \"MaxSatInstance.hh\"\n#include \"ubcsat\/ubcsat.h\"\n\nbool MaxSatInstance::isTautologicalClause( int lits[ MAX_NUM_LITERALS ], int& numLits, const int clauseNum ) {\n \/\/ sort the clause and remove redundant literals\n \/\/!! For large clauses better use sort()\n for (int i=0; i<numLits-1; i++) {\n for (int j=i+1; j<numLits; j++) {\n if (abs(lits[i]) > abs(lits[j])) { \/\/ Bubble sort\n swap( lits[i], lits[j] );\n } else if (lits[i] == lits[j]) {\n\tlits[j--] = lits[--numLits];\n\tprintf(\"c literal %d is redundant in clause %d\\n\", lits[i], clauseNum);\n } else if (abs(lits[i]) == abs(lits[j])) {\n\tprintf(\"c Clause %d is tautological.\\n\", clauseNum);\n\treturn true;\n }\n }\n } \n return false;\n}\n\nMaxSatInstance::MaxSatInstance( const char* filename ) \n{\n ifstream infile(filename);\n if (!infile) {\n fprintf(stderr, \"c Error: could not read from %s.\\n\", filename);\n exit(1);\n }\n inputFileName = new char[ strlen( filename ) + 1 ];\n strcpy( inputFileName, filename );\n\n while (infile.get() != 'p') {\n infile.ignore(MAX_LINE_LENGTH, '\\n');\n }\n\n char strbuf[MAX_LINE_LENGTH];\n infile >> strbuf;\n\n if( strcmp(strbuf, \"cnf\")==0 ) {\n format = CNF;\n } else if( strcmp(strbuf, \"wcnf\")==0 ) {\n format = WEIGHTED;\n } else if( strcmp(strbuf, \"pcnf\")==0 ) {\n format = PARTIAL;\n } else if( strcmp(strbuf, \"wpcnf\")==0 ) {\n format = WEIGHTED_PARTIAL;\n } else {\n fprintf(stderr, \"c Error: Can only understand cnf format!\\n\");\n exit(1);\n }\n\n infile >> numVars >> numClauses;\n\n negClausesWithVar = new int[ numVars+1 ];\n posClausesWithVar = new int[ numVars+1 ];\n fill( negClausesWithVar, &negClausesWithVar[numVars+1], 0 );\n fill( posClausesWithVar, &posClausesWithVar[numVars+1], 0 );\n\n unitClauses = binaryClauses = ternaryClauses = 0;\n\n int lits[ MAX_NUM_LITERALS ];\n for (int clauseNum=0; clauseNum<numClauses; clauseNum++) {\n \n int numLits = 0;\n \n infile >> lits[numLits];\n while (lits[numLits] != 0) \n infile >> lits[++numLits];\n\n if ( numLits == 1 or !isTautologicalClause( lits, numLits, clauseNum )) {\n switch( numLits ) {\n case 1: unitClauses++; break;\n case 2: binaryClauses++; break;\n case 3: ternaryClauses++; break;\n }\n \n for (int litNum = 0; litNum < numLits; litNum++) \n\tif (lits[litNum] < 0)\n\t negClausesWithVar[abs(lits[litNum])]++;\n\telse\n\t posClausesWithVar[lits[litNum]]++;\n \n } else {\n clauseNum--;\n numClauses--;\n }\n }\n}\n\nMaxSatInstance::~MaxSatInstance() {\n delete negClausesWithVar;\n delete posClausesWithVar;\n}\n\nnamespace ubcsat { int main(int, char**); }\n\nvoid MaxSatInstance::computeLocalSearchProperties() {\n printf(\"local search probe...\\n\");\n\n char sTimeout[64];\n char sRuns[64];\n\n sprintf(sTimeout, \"%d\", UBCSAT_TIME_LIMIT);\n sprintf(sRuns, \"%d\", UBCSAT_NUM_RUNS);\n\n\n char* vlineFilename = new char[512];\n sprintf(vlineFilename, \"%s\", P_tmpdir);\n strcat(vlineFilename, \"\/XXXXXX\");\n vlineFilename = mktemp(vlineFilename);\n\n\n char strseed[64];\n sprintf(strseed, \"%d\", UBCSAT_SEED );\n\n char* argv[] = {\"ubcsat\", \n\t\t \"-alg\", NULL, \"-noimprove\", NULL, \"-i\", inputFileName, \n\t\t \"-runs\", sRuns, \"-timeout\", sTimeout,\n\t\t \"-r\", \"satcomp\", vlineFilename,\n\t\t \"-seed\", strseed,\n\t\t \"-satzilla\", \"-solve\"};\n \n int argc = 17;\n \n \/\/ -- do saps\n argv[2]=\"saps\";\n argv[4]=\"0.1\";\n \n if ( ubcsat::main(argc, argv) == 10 ) printf(\"Instance satisfiable\\n\");\n \n \/\/ -- do gsat\n argv[2]=\"gsat\";\n argv[4]=\"0.5\";\n\n if ( ubcsat::main(argc, argv) == 10 ) printf(\"Instance satisfiable\\n\");\n\n delete[] vlineFilename;\n}\n\nvoid MaxSatInstance::printInfo(ostream& os) {\n os << \"Number of Variables: \" << numVars << endl;\n os << \"Number of Clauses: \" << numClauses << endl;\n os << \"Ratio Clauses\/Variables: \" << (float)numClauses\/numVars << endl;\n int negClauses = 0, posClauses = 0;\n for (int varNum=1; varNum<=numVars; varNum++) {\n negClauses += negClausesWithVar[ varNum ];\n posClauses += posClausesWithVar[ varNum ];\n }\n os << \"Ratio Negative Clauses: \" << (float)negClauses\/numClauses << endl;\n os << \"Ratio Positive Clauses: \" << (float)posClauses\/numClauses << endl;\n os << \"Ratio Unit Clauses: \" << (float)unitClauses\/numClauses << endl;\n os << \"Ratio Binary Clauses: \" << (float)binaryClauses\/numClauses << endl;\n os << \"Ratio Ternary Clauses: \" << (float)ternaryClauses\/numClauses << endl;\n}\n<commit_msg>Removed the line with the local search probe info. It was messing MY scripts.<commit_after>\/*******************************************************************************[MaxSatInstance.cc]\nMagpie -- Florian Letombe, Joao Marques-Silva, Paulo Matos, Jordi Planes (2007)\n\nParts of the code in this file have been extracted from SATzilla.\n**************************************************************************************************\/\n\n#include <algorithm>\n\n#include \"MaxSatInstance.hh\"\n#include \"ubcsat\/ubcsat.h\"\n\nbool MaxSatInstance::isTautologicalClause( int lits[ MAX_NUM_LITERALS ], int& numLits, const int clauseNum ) {\n \/\/ sort the clause and remove redundant literals\n \/\/!! For large clauses better use sort()\n for (int i=0; i<numLits-1; i++) {\n for (int j=i+1; j<numLits; j++) {\n if (abs(lits[i]) > abs(lits[j])) { \/\/ Bubble sort\n swap( lits[i], lits[j] );\n } else if (lits[i] == lits[j]) {\n\tlits[j--] = lits[--numLits];\n\tprintf(\"c literal %d is redundant in clause %d\\n\", lits[i], clauseNum);\n } else if (abs(lits[i]) == abs(lits[j])) {\n\tprintf(\"c Clause %d is tautological.\\n\", clauseNum);\n\treturn true;\n }\n }\n } \n return false;\n}\n\nMaxSatInstance::MaxSatInstance( const char* filename ) \n{\n ifstream infile(filename);\n if (!infile) {\n fprintf(stderr, \"c Error: could not read from %s.\\n\", filename);\n exit(1);\n }\n inputFileName = new char[ strlen( filename ) + 1 ];\n strcpy( inputFileName, filename );\n\n while (infile.get() != 'p') {\n infile.ignore(MAX_LINE_LENGTH, '\\n');\n }\n\n char strbuf[MAX_LINE_LENGTH];\n infile >> strbuf;\n\n if( strcmp(strbuf, \"cnf\")==0 ) {\n format = CNF;\n } else if( strcmp(strbuf, \"wcnf\")==0 ) {\n format = WEIGHTED;\n } else if( strcmp(strbuf, \"pcnf\")==0 ) {\n format = PARTIAL;\n } else if( strcmp(strbuf, \"wpcnf\")==0 ) {\n format = WEIGHTED_PARTIAL;\n } else {\n fprintf(stderr, \"c Error: Can only understand cnf format!\\n\");\n exit(1);\n }\n\n infile >> numVars >> numClauses;\n\n negClausesWithVar = new int[ numVars+1 ];\n posClausesWithVar = new int[ numVars+1 ];\n fill( negClausesWithVar, &negClausesWithVar[numVars+1], 0 );\n fill( posClausesWithVar, &posClausesWithVar[numVars+1], 0 );\n\n unitClauses = binaryClauses = ternaryClauses = 0;\n\n int lits[ MAX_NUM_LITERALS ];\n for (int clauseNum=0; clauseNum<numClauses; clauseNum++) {\n \n int numLits = 0;\n \n infile >> lits[numLits];\n while (lits[numLits] != 0) \n infile >> lits[++numLits];\n\n if ( numLits == 1 or !isTautologicalClause( lits, numLits, clauseNum )) {\n switch( numLits ) {\n case 1: unitClauses++; break;\n case 2: binaryClauses++; break;\n case 3: ternaryClauses++; break;\n }\n \n for (int litNum = 0; litNum < numLits; litNum++) \n\tif (lits[litNum] < 0)\n\t negClausesWithVar[abs(lits[litNum])]++;\n\telse\n\t posClausesWithVar[lits[litNum]]++;\n \n } else {\n clauseNum--;\n numClauses--;\n }\n }\n}\n\nMaxSatInstance::~MaxSatInstance() {\n delete negClausesWithVar;\n delete posClausesWithVar;\n}\n\nnamespace ubcsat { int main(int, char**); }\n\nvoid MaxSatInstance::computeLocalSearchProperties() {\n\n char sTimeout[64];\n char sRuns[64];\n\n sprintf(sTimeout, \"%d\", UBCSAT_TIME_LIMIT);\n sprintf(sRuns, \"%d\", UBCSAT_NUM_RUNS);\n\n\n char* vlineFilename = new char[512];\n sprintf(vlineFilename, \"%s\", P_tmpdir);\n strcat(vlineFilename, \"\/XXXXXX\");\n vlineFilename = mktemp(vlineFilename);\n\n\n char strseed[64];\n sprintf(strseed, \"%d\", UBCSAT_SEED );\n\n char* argv[] = {\"ubcsat\", \n\t\t \"-alg\", NULL, \"-noimprove\", NULL, \"-i\", inputFileName, \n\t\t \"-runs\", sRuns, \"-timeout\", sTimeout,\n\t\t \"-r\", \"satcomp\", vlineFilename,\n\t\t \"-seed\", strseed,\n\t\t \"-satzilla\", \"-solve\"};\n \n int argc = 17;\n \n \/\/ -- do saps\n argv[2]=\"saps\";\n argv[4]=\"0.1\";\n \n if ( ubcsat::main(argc, argv) == 10 ) printf(\"Instance satisfiable\\n\");\n \n \/\/ -- do gsat\n argv[2]=\"gsat\";\n argv[4]=\"0.5\";\n\n if ( ubcsat::main(argc, argv) == 10 ) printf(\"Instance satisfiable\\n\");\n\n delete[] vlineFilename;\n}\n\nvoid MaxSatInstance::printInfo(ostream& os) {\n os << \"Number of Variables: \" << numVars << endl;\n os << \"Number of Clauses: \" << numClauses << endl;\n os << \"Ratio Clauses\/Variables: \" << (float)numClauses\/numVars << endl;\n int negClauses = 0, posClauses = 0;\n for (int varNum=1; varNum<=numVars; varNum++) {\n negClauses += negClausesWithVar[ varNum ];\n posClauses += posClausesWithVar[ varNum ];\n }\n os << \"Ratio Negative Clauses: \" << (float)negClauses\/numClauses << endl;\n os << \"Ratio Positive Clauses: \" << (float)posClauses\/numClauses << endl;\n os << \"Ratio Unit Clauses: \" << (float)unitClauses\/numClauses << endl;\n os << \"Ratio Binary Clauses: \" << (float)binaryClauses\/numClauses << endl;\n os << \"Ratio Ternary Clauses: \" << (float)ternaryClauses\/numClauses << endl;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ gclass.cpp\n\/\/ etc\n\/\/\n\/\/ Created by Oleksii Tiurenkov on 9\/30\/15.\n\/\/ Copyright (c) 2015 Oleksii Tiurenkov. All rights reserved.\n\/\/\n\n#include \"gclass.h\"\n#include <fstream>\n#include <iostream>\n#include \"GLOBAL_CONST.h\"\n\nusing namespace std;\n\nstd::string random_string( size_t length )\n{\n auto randchar = []() -> char\n {\n const char charset[] =\n \"0123456789\"\n \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n \"abcdefghijklmnopqrstuvwxyz\";\n const size_t max_index = (sizeof(charset) - 1);\n return charset[ rand() % max_index ];\n };\n std::string str(length,0);\n std::generate_n( str.begin(), length, randchar );\n return str;\n}\n\n\n\nGclass* Gclass::loadFromFile(std::string dir, std::string filename)\n{\n Gclass* result = nullptr;\n \/\/open file\n ifstream infile(dir+filename, ios_base::binary|ios_base::in|ios::ate);\n \/\/if file opened\n if (infile.is_open())\n {\n \/\/get file size\n size_t buffersize =infile.tellg();\n \/\/create buffer\n char* bufferArray = new char[buffersize];\n \/\/return to file start\n infile.seekg(ios::beg);\n \/\/read all from file\n infile.read(bufferArray, buffersize);\n \/\/close file\n infile.close();\n result = new Gclass;\n size_t bufferlength = buffersize\/sizeof(shima_t);\n shima_t* shimaBuffer = reinterpret_cast<shima_t*>(bufferArray);\n result->internalArray.assign(shimaBuffer, shimaBuffer + bufferlength);\n \/\/save file name\n result->filename = filename;\n delete [] bufferArray;\n }\n return result;\n}\n\nbool Gclass::save(std::string dir)\n{\n bool result = false;\n ofstream outfile(dir + filename, ios_base::binary|ios_base::out|ios::trunc);\n if (outfile.is_open())\n {\n shima_t* shimaBuffer = new shima_t[internalArray.size()];\n std::copy(internalArray.begin(),internalArray.end(),shimaBuffer);\n outfile.write(reinterpret_cast<char*>(shimaBuffer), internalArray.size() * sizeof(shima_t));\n outfile.close();\n result = true;\n }\n else\n {\n cerr << \"Error:\" << strerror(errno) << endl;\n cout << \"Error opening file\";\n }\n return result;\n}\n\nvoid Gclass::saveJSON(std::string dir)\n{\n ofstream outfile(dir + filename+ \".json\", ios_base::out|ios::trunc);\n if (outfile.is_open())\n {\n Fleet* fleet = fleetCreate();\n outfile << fleet->json();\n delete fleet;\n outfile.close();\n\n }\n else\n {\n cerr << \"Error:\" << strerror(errno) << endl;\n cout << \"Error opening file\";\n }\n\n}\n\nvoid Gclass::mutation()\n{\n for (int i = 0; i < internalArray.size(); i++)\n {\n if (RADIATION > (rand()%MAX_SCALE))\n {\n internalArray[i]^= 1 << rand()%(sizeof(shima_t)*8);\n }\n }\n}\n\n\nFleet* Gclass::fleetCreate() const\n{\n return new Fleet(internalArray);\n}\n\nGclass* Gclass::empty()\n{\n Gclass* result = new Gclass;\n result->internalArray.push_back(0);\n result->filename = random_string(16);\n return result;\n}\n\nbool Gclass::betterThan(const Gclass *other) const\n{\n return score > other->score;\n}\n\nsize_t randomMedium(size_t length)\n{\n long result = length\/2 + (RADIATION > (rand()%MAX_SCALE)?rand()%3 -1 :0 );\n result = result > 0? result:0;\n result = length < result? length: result;\n return result;\n}\n\nGclass* Gclass::crossover(Gclass *gene)\n{\n size_t myGenes = randomMedium(internalArray.size());\n size_t theirsGenes = randomMedium(gene->internalArray.size());\n Gclass* result = new Gclass;\n if (rand()%2)\n {\n for(auto it = internalArray.begin(); it != internalArray.begin()+myGenes && it != internalArray.end(); it++) result->internalArray.push_back(*it);\n for(auto it = gene->internalArray.end() - theirsGenes; it != gene->internalArray.end(); it++) result->internalArray.push_back(*it);\n }\n else\n {\n for(auto it = gene->internalArray.begin(); it != gene->internalArray.begin()+theirsGenes && it != gene->internalArray.end(); it++)\n result->internalArray.push_back(*it);\n for(auto it = internalArray.end() - myGenes; it != internalArray.end(); it++) result->internalArray.push_back(*it);\n }\n \/\/insert random gene\n if (RADIATION > (rand()%MAX_SCALE))\n {\n size_t position = internalArray.size() != 0 ?rand()%internalArray.size() : 0;\n shima_t shima = rand();\n \n internalArray.insert(internalArray.begin() + position,shima);\n }\n result->filename = random_string(16);\n return result;\n}\n\nvoid Gclass::deleteGene(std::string dir)\n{\n remove((dir + filename).c_str());\n}\n\nvoid Gclass::compare(Gclass* other)\n{\n auto myFleet = fleetCreate();\n auto otherFleet = other->fleetCreate();\n\n\n switch (myFleet->result(otherFleet)) {\n case WIN:\n score+=3;\n break;\n case DRAW:\n score+=1;\n other->score+=1;\n break;\n case FAIL:\n other->score+=3;\n break;\n default:\n break;\n }\n delete myFleet;\n delete otherFleet;\n}\n\n\nvoid Gclass::print()\n{\n auto fleet = fleetCreate();\n fleet->print();\n delete fleet;\n}\n\nvoid Gclass::clearScore()\n{\n score = 0;\n}\n\n<commit_msg>Changed mutation<commit_after>\/\/\n\/\/ gclass.cpp\n\/\/ etc\n\/\/\n\/\/ Created by Oleksii Tiurenkov on 9\/30\/15.\n\/\/ Copyright (c) 2015 Oleksii Tiurenkov. All rights reserved.\n\/\/\n\n#include \"gclass.h\"\n#include <fstream>\n#include <iostream>\n#include \"GLOBAL_CONST.h\"\n\nusing namespace std;\n\nstd::string random_string( size_t length )\n{\n auto randchar = []() -> char\n {\n const char charset[] =\n \"0123456789\"\n \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n \"abcdefghijklmnopqrstuvwxyz\";\n const size_t max_index = (sizeof(charset) - 1);\n return charset[ rand() % max_index ];\n };\n std::string str(length,0);\n std::generate_n( str.begin(), length, randchar );\n return str;\n}\n\n\n\nGclass* Gclass::loadFromFile(std::string dir, std::string filename)\n{\n Gclass* result = nullptr;\n \/\/open file\n ifstream infile(dir+filename, ios_base::binary|ios_base::in|ios::ate);\n \/\/if file opened\n if (infile.is_open())\n {\n \/\/get file size\n size_t buffersize =infile.tellg();\n \/\/create buffer\n char* bufferArray = new char[buffersize];\n \/\/return to file start\n infile.seekg(ios::beg);\n \/\/read all from file\n infile.read(bufferArray, buffersize);\n \/\/close file\n infile.close();\n result = new Gclass;\n size_t bufferlength = buffersize\/sizeof(shima_t);\n shima_t* shimaBuffer = reinterpret_cast<shima_t*>(bufferArray);\n result->internalArray.assign(shimaBuffer, shimaBuffer + bufferlength);\n \/\/save file name\n result->filename = filename;\n delete [] bufferArray;\n }\n return result;\n}\n\nbool Gclass::save(std::string dir)\n{\n bool result = false;\n ofstream outfile(dir + filename, ios_base::binary|ios_base::out|ios::trunc);\n if (outfile.is_open())\n {\n shima_t* shimaBuffer = new shima_t[internalArray.size()];\n std::copy(internalArray.begin(),internalArray.end(),shimaBuffer);\n outfile.write(reinterpret_cast<char*>(shimaBuffer), internalArray.size() * sizeof(shima_t));\n outfile.close();\n result = true;\n }\n else\n {\n cerr << \"Error:\" << strerror(errno) << endl;\n cout << \"Error opening file\";\n }\n return result;\n}\n\nvoid Gclass::saveJSON(std::string dir)\n{\n ofstream outfile(dir + filename+ \".json\", ios_base::out|ios::trunc);\n if (outfile.is_open())\n {\n Fleet* fleet = fleetCreate();\n outfile << fleet->json();\n delete fleet;\n outfile.close();\n\n }\n else\n {\n cerr << \"Error:\" << strerror(errno) << endl;\n cout << \"Error opening file\";\n }\n\n}\n\nvoid Gclass::mutation()\n{\n for (int i = 0; i < internalArray.size(); i++)\n {\n if (RADIATION > (rand()%MAX_SCALE))\n {\n internalArray[i]^= 1 << rand()%(sizeof(shima_t)*8);\n }\n }\n \/\/insert random gene\n if (RADIATION > (rand()%MAX_SCALE))\n {\n size_t position = internalArray.size() != 0 ?rand()%internalArray.size() : 0;\n shima_t shima = rand();\n \n internalArray.insert(internalArray.begin() + position,shima);\n }\n \/\/Swap two or delete\n if ((internalArray.size() > 1) && (RADIATION > (rand()%MAX_SCALE)))\n {\n size_t position1 = rand()%internalArray.size();\n size_t position2 = rand()%internalArray.size();\n if(position1 == position2)\n {\n internalArray.erase(internalArray.begin()+position1);\n }\n else\n {\n std::iter_swap(internalArray.begin() + position1, internalArray.begin() + position2);\n }\n }\n}\n\n\nFleet* Gclass::fleetCreate() const\n{\n return new Fleet(internalArray);\n}\n\nGclass* Gclass::empty()\n{\n Gclass* result = new Gclass;\n result->internalArray.push_back(0);\n result->filename = random_string(16);\n return result;\n}\n\nbool Gclass::betterThan(const Gclass *other) const\n{\n return score > other->score;\n}\n\nsize_t randomMedium(size_t length)\n{\n long result = length\/2 + (RADIATION > (rand()%MAX_SCALE)?rand()%3 -1 :0 );\n result = result > 0? result:0;\n result = length < result? length: result;\n return result;\n}\n\nGclass* Gclass::crossover(Gclass *gene)\n{\n size_t myGenes = randomMedium(internalArray.size());\n size_t theirsGenes = randomMedium(gene->internalArray.size());\n Gclass* result = new Gclass;\n if (rand()%2)\n {\n for(auto it = internalArray.begin(); it != internalArray.begin()+myGenes && it != internalArray.end(); it++) result->internalArray.push_back(*it);\n for(auto it = gene->internalArray.end() - theirsGenes; it != gene->internalArray.end(); it++) result->internalArray.push_back(*it);\n }\n else\n {\n for(auto it = gene->internalArray.begin(); it != gene->internalArray.begin()+theirsGenes && it != gene->internalArray.end(); it++)\n result->internalArray.push_back(*it);\n for(auto it = internalArray.end() - myGenes; it != internalArray.end(); it++) result->internalArray.push_back(*it);\n }\n\n result->filename = random_string(16);\n result->mutation();\n return result;\n}\n\nvoid Gclass::deleteGene(std::string dir)\n{\n remove((dir + filename).c_str());\n}\n\nvoid Gclass::compare(Gclass* other)\n{\n auto myFleet = fleetCreate();\n auto otherFleet = other->fleetCreate();\n\n\n switch (myFleet->result(otherFleet)) {\n case WIN:\n score+=3;\n break;\n case DRAW:\n score+=1;\n other->score+=1;\n break;\n case FAIL:\n other->score+=3;\n break;\n default:\n break;\n }\n delete myFleet;\n delete otherFleet;\n}\n\n\nvoid Gclass::print()\n{\n auto fleet = fleetCreate();\n fleet->print();\n delete fleet;\n}\n\nvoid Gclass::clearScore()\n{\n score = 0;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ This file is part of the Marble Virtual Globe.\n\/\/\n\/\/ This program is free software licensed under the GNU LGPL. You can\n\/\/ find a copy of this license in LICENSE.txt in the top directory of\n\/\/ the source code.\n\/\/\n\/\/ Copyright 2013 Mayank Madan <maddiemadan@gmail.com>\n\/\/\n\n#include \"GeoDataFlyTo.h\"\n#include \"GeoDataTypes.h\"\n#include \"GeoDataAbstractView.h\"\n\nnamespace Marble {\n\nclass GeoDataFlyToPrivate\n{\npublic:\n double m_duration;\n\n GeoDataFlyTo::FlyToMode m_flyToMode;\n\n GeoDataAbstractView* m_view;\n\n GeoDataFlyToPrivate();\n};\n\nGeoDataFlyToPrivate::GeoDataFlyToPrivate() :\n m_duration( 0.0 ), m_flyToMode(), m_view( 0 )\n{\n\n}\n\nGeoDataFlyTo::GeoDataFlyTo() : d( new GeoDataFlyToPrivate )\n{\n\n}\n\nGeoDataFlyTo::GeoDataFlyTo( const Marble::GeoDataFlyTo &other ) :\n GeoDataTourPrimitive( other ), d( new GeoDataFlyToPrivate( *other.d ) )\n{\n\n}\n\nGeoDataFlyTo &GeoDataFlyTo::operator=( const GeoDataFlyTo &other )\n{\n GeoDataTourPrimitive::operator=( other );\n *d = *other.d;\n return *this;\n}\n\nbool GeoDataFlyTo::operator==( const GeoDataFlyTo& other ) const\n{\n return equals(other) &&\n d->m_duration == other.d->m_duration &&\n d->m_flyToMode == other.d->m_flyToMode &&\n d->m_view == other.d->m_view;\n}\n\nbool GeoDataFlyTo::operator!=( const GeoDataFlyTo& other ) const\n{\n return !this->operator==(other);\n}\n\nGeoDataFlyTo::~GeoDataFlyTo()\n{\n delete d;\n}\n\nconst char *GeoDataFlyTo::nodeType() const\n{\n return GeoDataTypes::GeoDataFlyToType;\n}\n\nconst GeoDataAbstractView *GeoDataFlyTo::view() const\n{\n return d->m_view;\n}\n\nGeoDataAbstractView *GeoDataFlyTo::view()\n{\n return d->m_view;\n}\n\nvoid GeoDataFlyTo::setView( GeoDataAbstractView *view )\n{\n d->m_view = view;\n}\n\ndouble GeoDataFlyTo::duration() const\n{\n return d->m_duration;\n}\n\nvoid GeoDataFlyTo::setDuration( double duration )\n{\n d->m_duration = duration;\n}\n\nGeoDataFlyTo::FlyToMode GeoDataFlyTo::flyToMode() const\n{\n return d->m_flyToMode;\n}\n\nvoid GeoDataFlyTo::setFlyToMode( const GeoDataFlyTo::FlyToMode flyToMode )\n{\n d->m_flyToMode = flyToMode;\n}\n\n}\n<commit_msg>Fix equlity operator in GeoDataFlyTo - it now compares m_view based on nodeType<commit_after>\/\/\n\/\/ This file is part of the Marble Virtual Globe.\n\/\/\n\/\/ This program is free software licensed under the GNU LGPL. You can\n\/\/ find a copy of this license in LICENSE.txt in the top directory of\n\/\/ the source code.\n\/\/\n\/\/ Copyright 2013 Mayank Madan <maddiemadan@gmail.com>\n\/\/\n\n#include \"GeoDataFlyTo.h\"\n#include \"GeoDataTypes.h\"\n#include \"GeoDataAbstractView.h\"\n#include \"GeoDataCamera.h\"\n#include \"GeoDataLookAt.h\"\n\nnamespace Marble {\n\nclass GeoDataFlyToPrivate\n{\npublic:\n double m_duration;\n\n GeoDataFlyTo::FlyToMode m_flyToMode;\n\n GeoDataAbstractView* m_view;\n\n GeoDataFlyToPrivate();\n};\n\nGeoDataFlyToPrivate::GeoDataFlyToPrivate() :\n m_duration( 0.0 ), m_flyToMode(), m_view( 0 )\n{\n\n}\n\nGeoDataFlyTo::GeoDataFlyTo() : d( new GeoDataFlyToPrivate )\n{\n\n}\n\nGeoDataFlyTo::GeoDataFlyTo( const Marble::GeoDataFlyTo &other ) :\n GeoDataTourPrimitive( other ), d( new GeoDataFlyToPrivate( *other.d ) )\n{\n\n}\n\nGeoDataFlyTo &GeoDataFlyTo::operator=( const GeoDataFlyTo &other )\n{\n GeoDataTourPrimitive::operator=( other );\n *d = *other.d;\n return *this;\n}\n\nbool GeoDataFlyTo::operator==( const GeoDataFlyTo& other ) const\n{\n if ( !equals(other) ||\n d->m_duration != other.d->m_duration ||\n d->m_flyToMode != other.d->m_flyToMode ) {\n return false;\n }\n\n if ( (!d->m_view && other.d->m_view) ||\n (d->m_view && !other.d->m_view) ) {\n return false;\n } else if ( !d->m_view && !other.d->m_view ) {\n return true;\n }\n\n if ( d->m_view->nodeType() != other.d->m_view->nodeType() ) {\n return false;\n }\n\n if ( d->m_view->nodeType() == GeoDataTypes::GeoDataCameraType ) {\n GeoDataCamera *thisCam = dynamic_cast<GeoDataCamera*>( d->m_view );\n GeoDataCamera *otherCam = dynamic_cast<GeoDataCamera*>( other.d->m_view );\n Q_ASSERT( thisCam && otherCam );\n\n if ( *thisCam != *otherCam ) {\n return false;\n }\n } else if ( d->m_view->nodeType() == GeoDataTypes::GeoDataLookAtType ) {\n GeoDataLookAt *thisLookAt = dynamic_cast<GeoDataLookAt*>( d->m_view );\n GeoDataLookAt *otherLookAt = dynamic_cast<GeoDataLookAt*>( other.d->m_view );\n Q_ASSERT( thisLookAt && otherLookAt );\n\n if ( *thisLookAt != *otherLookAt ) {\n return false;\n }\n }\n\n return true;\n}\n\nbool GeoDataFlyTo::operator!=( const GeoDataFlyTo& other ) const\n{\n return !this->operator==(other);\n}\n\nGeoDataFlyTo::~GeoDataFlyTo()\n{\n delete d;\n}\n\nconst char *GeoDataFlyTo::nodeType() const\n{\n return GeoDataTypes::GeoDataFlyToType;\n}\n\nconst GeoDataAbstractView *GeoDataFlyTo::view() const\n{\n return d->m_view;\n}\n\nGeoDataAbstractView *GeoDataFlyTo::view()\n{\n return d->m_view;\n}\n\nvoid GeoDataFlyTo::setView( GeoDataAbstractView *view )\n{\n d->m_view = view;\n}\n\ndouble GeoDataFlyTo::duration() const\n{\n return d->m_duration;\n}\n\nvoid GeoDataFlyTo::setDuration( double duration )\n{\n d->m_duration = duration;\n}\n\nGeoDataFlyTo::FlyToMode GeoDataFlyTo::flyToMode() const\n{\n return d->m_flyToMode;\n}\n\nvoid GeoDataFlyTo::setFlyToMode( const GeoDataFlyTo::FlyToMode flyToMode )\n{\n d->m_flyToMode = flyToMode;\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: indexentrysupplier_asian.cxx,v $\n *\n * $Revision: 1.7 $\n *\n * last change: $Author: hr $ $Date: 2006-06-20 04:45:06 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#include <rtl\/ustrbuf.hxx>\n#include <indexentrysupplier_asian.hxx>\n#include <data\/indexdata_alphanumeric.h>\n\nusing namespace ::com::sun::star::uno;\nusing namespace ::com::sun::star::lang;\nusing namespace ::rtl;\n\nnamespace com { namespace sun { namespace star { namespace i18n {\n\nIndexEntrySupplier_asian::IndexEntrySupplier_asian(\n const Reference < XMultiServiceFactory >& rxMSF ) : IndexEntrySupplier_Common(rxMSF)\n{\n implementationName = \"com.sun.star.i18n.IndexEntrySupplier_asian\";\n#ifdef SAL_DLLPREFIX\n OUString lib=OUString::createFromAscii(SAL_DLLPREFIX\"index_data\"SAL_DLLEXTENSION);\n#else\n OUString lib=OUString::createFromAscii(\"index_data\"SAL_DLLEXTENSION);\n#endif\n hModule = osl_loadModule( lib.pData, SAL_LOADMODULE_DEFAULT );\n}\n\nIndexEntrySupplier_asian::~IndexEntrySupplier_asian()\n{\n if (hModule) osl_unloadModule(hModule);\n}\n\nOUString SAL_CALL\nIndexEntrySupplier_asian::getIndexCharacter( const OUString& rIndexEntry,\n const Locale& rLocale, const OUString& rAlgorithm ) throw (RuntimeException)\n{\n sal_Unicode ch = rIndexEntry.toChar();\n if (hModule) {\n OUString get=OUString::createFromAscii(\"get_indexdata_\");\n int (*func)()=NULL;\n if (rLocale.Language.equalsAscii(\"zh\") && OUString::createFromAscii(\"TW HK MO\").indexOf(rLocale.Country) >= 0)\n func=(int (*)())osl_getFunctionSymbol(hModule, (get+rLocale.Language+OUString::createFromAscii(\"_TW_\")+rAlgorithm).pData);\n if (!func)\n func=(int (*)())osl_getFunctionSymbol(hModule, (get+rLocale.Language+OUString('_')+rAlgorithm).pData);\n if (func) {\n sal_uInt16** idx=(sal_uInt16**)func();\n sal_uInt16 address=idx[0][ch >> 8];\n if (address != 0xFFFF) {\n address=idx[1][address+(ch & 0xFF)];\n return idx[2] ? OUString(&idx[2][address]) : OUString(address);\n }\n }\n }\n \/\/ using alphanumeric index for non-define stirng\n return OUString(&idxStr[(ch & 0xFF00) ? 0 : ch], 1);\n}\n\nOUString SAL_CALL\nIndexEntrySupplier_asian::getIndexKey( const OUString& rIndexEntry,\n const OUString& rPhoneticEntry, const Locale& rLocale) throw (RuntimeException)\n{\n return getIndexCharacter(getEntry(rIndexEntry, rPhoneticEntry, rLocale), rLocale, aAlgorithm);\n}\n\nsal_Int16 SAL_CALL\nIndexEntrySupplier_asian::compareIndexEntry(\n const OUString& rIndexEntry1, const OUString& rPhoneticEntry1, const Locale& rLocale1,\n const OUString& rIndexEntry2, const OUString& rPhoneticEntry2, const Locale& rLocale2 )\n throw (RuntimeException)\n{\n sal_Int32 result = collator->compareString(getEntry(rIndexEntry1, rPhoneticEntry1, rLocale1),\n getEntry(rIndexEntry2, rPhoneticEntry2, rLocale2));\n\n \/\/ equivalent of phonetic entries does not mean equivalent of index entries.\n \/\/ we have to continue comparing index entry here.\n if (result == 0 && usePhonetic && rPhoneticEntry1.getLength() > 0 &&\n rLocale1.Language == rLocale2.Language && rLocale1.Country == rLocale2.Country &&\n rLocale1.Variant == rLocale2.Variant)\n result = collator->compareString(rIndexEntry1, rIndexEntry2);\n return sal::static_int_cast< sal_Int16 >(result); \/\/ result in { -1, 0, 1 }\n}\n\nOUString SAL_CALL\nIndexEntrySupplier_asian::getPhoneticCandidate( const OUString& rIndexEntry,\n const Locale& rLocale ) throw (RuntimeException)\n{\n if (hModule) {\n int (*func)()=NULL;\n const sal_Char *func_name=NULL;\n if (rLocale.Language.equalsAscii(\"zh\"))\n func_name=(OUString::createFromAscii(\"TW HK MO\").indexOf(rLocale.Country) >= 0) ? \"get_zh_zhuyin\" : func_name=\"get_zh_pinyin\";\n else if (rLocale.Language.equalsAscii(\"ko\"))\n func_name=\"get_ko_phonetic\";\n if (func_name)\n func=(int (*)())osl_getFunctionSymbol(hModule, OUString::createFromAscii(func_name).pData);\n if (func) {\n OUStringBuffer candidate;\n sal_uInt16** idx=(sal_uInt16**)func();\n for (sal_Int32 i=0; i < rIndexEntry.getLength(); i++) {\n sal_Unicode ch = rIndexEntry[i];\n sal_uInt16 address = idx[0][ch>>8];\n if (address != 0xFFFF) {\n address = idx[1][address + (ch & 0xFF)];\n if (i > 0 && rLocale.Language.equalsAscii(\"zh\"))\n candidate.appendAscii(\" \");\n if (idx[2])\n candidate.append(&idx[2][address]);\n else\n candidate.append(address);\n } else\n candidate.appendAscii(\" \");\n }\n return candidate.makeStringAndClear();\n }\n }\n return OUString();\n}\n} } } }\n<commit_msg>INTEGRATION: CWS warningfixes02 (1.7.2); FILE MERGED 2006\/06\/30 11:57:37 sb 1.7.2.1: #i66577# Made the code compile (warning-free) on a unxlngi6.pro GCC 4.1.1 Linux box.<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: indexentrysupplier_asian.cxx,v $\n *\n * $Revision: 1.8 $\n *\n * last change: $Author: kz $ $Date: 2006-07-19 16:29:37 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#include <rtl\/ustrbuf.hxx>\n#include <indexentrysupplier_asian.hxx>\n#include <data\/indexdata_alphanumeric.h>\n\nusing namespace ::com::sun::star::uno;\nusing namespace ::com::sun::star::lang;\nusing namespace ::rtl;\n\nnamespace com { namespace sun { namespace star { namespace i18n {\n\nIndexEntrySupplier_asian::IndexEntrySupplier_asian(\n const Reference < XMultiServiceFactory >& rxMSF ) : IndexEntrySupplier_Common(rxMSF)\n{\n implementationName = \"com.sun.star.i18n.IndexEntrySupplier_asian\";\n#ifdef SAL_DLLPREFIX\n OUString lib=OUString::createFromAscii(SAL_DLLPREFIX\"index_data\"SAL_DLLEXTENSION);\n#else\n OUString lib=OUString::createFromAscii(\"index_data\"SAL_DLLEXTENSION);\n#endif\n hModule = osl_loadModule( lib.pData, SAL_LOADMODULE_DEFAULT );\n}\n\nIndexEntrySupplier_asian::~IndexEntrySupplier_asian()\n{\n if (hModule) osl_unloadModule(hModule);\n}\n\nOUString SAL_CALL\nIndexEntrySupplier_asian::getIndexCharacter( const OUString& rIndexEntry,\n const Locale& rLocale, const OUString& rAlgorithm ) throw (RuntimeException)\n{\n sal_Unicode ch = rIndexEntry.toChar();\n if (hModule) {\n OUString get=OUString::createFromAscii(\"get_indexdata_\");\n int (*func)()=NULL;\n if (rLocale.Language.equalsAscii(\"zh\") && OUString::createFromAscii(\"TW HK MO\").indexOf(rLocale.Country) >= 0)\n func=(int (*)())osl_getFunctionSymbol(hModule, (get+rLocale.Language+OUString::createFromAscii(\"_TW_\")+rAlgorithm).pData);\n if (!func)\n func=(int (*)())osl_getFunctionSymbol(hModule, (get+rLocale.Language+OUString('_')+rAlgorithm).pData);\n if (func) {\n sal_uInt16** idx=(sal_uInt16**)func();\n sal_uInt16 address=idx[0][ch >> 8];\n if (address != 0xFFFF) {\n address=idx[1][address+(ch & 0xFF)];\n return idx[2] ? OUString(&idx[2][address]) : OUString(address);\n }\n }\n }\n \/\/ using alphanumeric index for non-define stirng\n return OUString(&idxStr[(ch & 0xFF00) ? 0 : ch], 1);\n}\n\nOUString SAL_CALL\nIndexEntrySupplier_asian::getIndexKey( const OUString& rIndexEntry,\n const OUString& rPhoneticEntry, const Locale& rLocale) throw (RuntimeException)\n{\n return getIndexCharacter(getEntry(rIndexEntry, rPhoneticEntry, rLocale), rLocale, aAlgorithm);\n}\n\nsal_Int16 SAL_CALL\nIndexEntrySupplier_asian::compareIndexEntry(\n const OUString& rIndexEntry1, const OUString& rPhoneticEntry1, const Locale& rLocale1,\n const OUString& rIndexEntry2, const OUString& rPhoneticEntry2, const Locale& rLocale2 )\n throw (RuntimeException)\n{\n sal_Int32 result = collator->compareString(getEntry(rIndexEntry1, rPhoneticEntry1, rLocale1),\n getEntry(rIndexEntry2, rPhoneticEntry2, rLocale2));\n\n \/\/ equivalent of phonetic entries does not mean equivalent of index entries.\n \/\/ we have to continue comparing index entry here.\n if (result == 0 && usePhonetic && rPhoneticEntry1.getLength() > 0 &&\n rLocale1.Language == rLocale2.Language && rLocale1.Country == rLocale2.Country &&\n rLocale1.Variant == rLocale2.Variant)\n result = collator->compareString(rIndexEntry1, rIndexEntry2);\n return sal::static_int_cast< sal_Int16 >(result); \/\/ result in { -1, 0, 1 }\n}\n\nOUString SAL_CALL\nIndexEntrySupplier_asian::getPhoneticCandidate( const OUString& rIndexEntry,\n const Locale& rLocale ) throw (RuntimeException)\n{\n if (hModule) {\n int (*func)()=NULL;\n const sal_Char *func_name=NULL;\n if (rLocale.Language.equalsAscii(\"zh\"))\n func_name=(OUString::createFromAscii(\"TW HK MO\").indexOf(rLocale.Country) >= 0) ? \"get_zh_zhuyin\" : \"get_zh_pinyin\";\n else if (rLocale.Language.equalsAscii(\"ko\"))\n func_name=\"get_ko_phonetic\";\n if (func_name)\n func=(int (*)())osl_getFunctionSymbol(hModule, OUString::createFromAscii(func_name).pData);\n if (func) {\n OUStringBuffer candidate;\n sal_uInt16** idx=(sal_uInt16**)func();\n for (sal_Int32 i=0; i < rIndexEntry.getLength(); i++) {\n sal_Unicode ch = rIndexEntry[i];\n sal_uInt16 address = idx[0][ch>>8];\n if (address != 0xFFFF) {\n address = idx[1][address + (ch & 0xFF)];\n if (i > 0 && rLocale.Language.equalsAscii(\"zh\"))\n candidate.appendAscii(\" \");\n if (idx[2])\n candidate.append(&idx[2][address]);\n else\n candidate.append(address);\n } else\n candidate.appendAscii(\" \");\n }\n return candidate.makeStringAndClear();\n }\n }\n return OUString();\n}\n} } } }\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: attarray.hxx,v $\n *\n * $Revision: 1.6 $\n *\n * last change: $Author: vg $ $Date: 2005-02-21 15:56:26 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef SC_ATRARR_HXX\n#define SC_ATRARR_HXX\n\n#ifndef SC_SCGLOB_HXX\n#include \"global.hxx\"\n#endif\n\n#ifndef SC_SCATTR_HXX\n#include \"attrib.hxx\"\n#endif\n\nclass ScDocument;\nclass ScMarkArray;\nclass ScPatternAttr;\nclass ScStyleSheet;\n\nclass Rectangle;\nclass SfxItemPoolCache;\nclass SfxStyleSheetBase;\nclass SvxBorderLine;\nclass SvxBoxItem;\nclass SvxBoxInfoItem;\n\n#define SC_LINE_EMPTY 0\n#define SC_LINE_SET 1\n#define SC_LINE_DONTCARE 2\n\n#define SC_ATTRARRAY_DELTA 4\n\nstruct ScLineFlags\n{\n BYTE nLeft;\n BYTE nRight;\n BYTE nTop;\n BYTE nBottom;\n BYTE nHori;\n BYTE nVert;\n\n ScLineFlags() : nLeft(SC_LINE_EMPTY),nRight(SC_LINE_EMPTY),nTop(SC_LINE_EMPTY),\n nBottom(SC_LINE_EMPTY),nHori(SC_LINE_EMPTY),nVert(SC_LINE_EMPTY) {}\n};\n\nstruct ScAttrEntry\n{\n SCROW nRow;\n const ScPatternAttr* pPattern;\n};\n\n\nclass ScAttrArray\n{\nprivate:\n SCCOL nCol;\n SCTAB nTab;\n ScDocument* pDocument;\n\n SCSIZE nCount;\n SCSIZE nLimit;\n ScAttrEntry* pData;\n\nfriend class ScDocument; \/\/ fuer FillInfo\nfriend class ScDocumentIterator;\nfriend class ScAttrIterator;\nfriend class ScHorizontalAttrIterator;\nfriend void lcl_IterGetNumberFormat( ULONG& nFormat,\n const ScAttrArray*& rpArr, SCROW& nAttrEndRow,\n const ScAttrArray* pNewArr, SCROW nRow, ScDocument* pDoc );\n\n BOOL ApplyFrame( const SvxBoxItem* pLineOuter, const SvxBoxInfoItem* pLineInner,\n SCROW nStartRow, SCROW nEndRow,\n BOOL bLeft, SCCOL nDistRight, BOOL bTop, SCROW nDistBottom );\n\npublic:\n ScAttrArray( SCCOL nNewCol, SCTAB nNewTab, ScDocument* pDoc );\n ~ScAttrArray();\n\n void SetTab(SCTAB nNewTab) { nTab = nNewTab; }\n void SetCol(SCCOL nNewCol) { nCol = nNewCol; }\n\n void TestData() const;\n void Reset( const ScPatternAttr* pPattern, BOOL bAlloc = TRUE );\n BOOL Concat(SCSIZE nPos);\n\n const ScPatternAttr* GetPattern( SCROW nRow ) const;\n const ScPatternAttr* GetPatternRange( SCROW& rStartRow, SCROW& rEndRow, SCROW nRow ) const;\n void MergePatternArea( SCROW nStartRow, SCROW nEndRow, SfxItemSet** ppSet, BOOL bDeep ) const;\n\n void MergeBlockFrame( SvxBoxItem* pLineOuter, SvxBoxInfoItem* pLineInner, ScLineFlags& rFlags,\n SCROW nStartRow, SCROW nEndRow, BOOL bLeft, SCCOL nDistRight ) const;\n void ApplyBlockFrame( const SvxBoxItem* pLineOuter, const SvxBoxInfoItem* pLineInner,\n SCROW nStartRow, SCROW nEndRow, BOOL bLeft, SCCOL nDistRight );\n\n void SetPattern( SCROW nRow, const ScPatternAttr* pPattern, BOOL bPutToPool = FALSE );\n void SetPatternArea( SCROW nStartRow, SCROW nEndRow, const ScPatternAttr* pPattern, BOOL bPutToPool = FALSE);\n void ApplyStyleArea( SCROW nStartRow, SCROW nEndRow, ScStyleSheet* pStyle );\n void ApplyCacheArea( SCROW nStartRow, SCROW nEndRow, SfxItemPoolCache* pCache );\n void ApplyLineStyleArea( SCROW nStartRow, SCROW nEndRow,\n const SvxBorderLine* pLine, BOOL bColorOnly );\n\n void ClearItems( SCROW nStartRow, SCROW nEndRow, const USHORT* pWhich );\n void ChangeIndent( SCROW nStartRow, SCROW nEndRow, BOOL bIncrement );\n\n \/\/\/ Including current, may return -1\n SCsROW GetNextUnprotected( SCsROW nRow, BOOL bUp ) const;\n\n \/\/\/ May return -1 if not found\n SCsROW SearchStyle( SCsROW nRow, const ScStyleSheet* pSearchStyle,\n BOOL bUp, ScMarkArray* pMarkArray = NULL );\n BOOL SearchStyleRange( SCsROW& rRow, SCsROW& rEndRow, const ScStyleSheet* pSearchStyle,\n BOOL bUp, ScMarkArray* pMarkArray = NULL );\n\n BOOL ApplyFlags( SCROW nStartRow, SCROW nEndRow, INT16 nFlags );\n BOOL RemoveFlags( SCROW nStartRow, SCROW nEndRow, INT16 nFlags );\n\n BOOL Search( SCROW nRow, SCSIZE& nIndex ) const;\n\n BOOL HasLines( SCROW nRow1, SCROW nRow2, Rectangle& rSizes,\n BOOL bLeft, BOOL bRight ) const;\n BOOL HasAttrib( SCROW nRow1, SCROW nRow2, USHORT nMask ) const;\n BOOL ExtendMerge( SCCOL nThisCol, SCROW nStartRow, SCROW nEndRow,\n SCCOL& rPaintCol, SCROW& rPaintRow,\n BOOL bRefresh, BOOL bAttrs );\n BOOL RemoveAreaMerge( SCROW nStartRow, SCROW nEndRow );\n\n void FindStyleSheet( const SfxStyleSheetBase* pStyleSheet, BOOL* pUsed, BOOL bReset );\n BOOL IsStyleSheetUsed( const ScStyleSheet& rStyle, BOOL bGatherAllStyles ) const;\n\n void DeleteAreaSafe(SCROW nStartRow, SCROW nEndRow);\n void SetPatternAreaSafe( SCROW nStartRow, SCROW nEndRow,\n const ScPatternAttr* pWantedPattern, BOOL bDefault );\n void CopyAreaSafe( SCROW nStartRow, SCROW nEndRow, long nDy, ScAttrArray& rAttrArray );\n\n BOOL IsEmpty() const;\n\n SCROW GetFirstEntryPos() const;\n SCROW GetLastEntryPos( BOOL bIncludeBottom ) const;\n\n BOOL GetFirstVisibleAttr( SCROW& rFirstRow ) const;\n BOOL GetLastVisibleAttr( SCROW& rLastRow, SCROW nLastData ) const;\n BOOL HasVisibleAttrIn( SCROW nStartRow, SCROW nEndRow ) const;\n BOOL IsVisibleEqual( const ScAttrArray& rOther,\n SCROW nStartRow, SCROW nEndRow ) const;\n BOOL IsAllEqual( const ScAttrArray& rOther, SCROW nStartRow, SCROW nEndRow ) const;\n\n BOOL TestInsertCol( SCROW nStartRow, SCROW nEndRow) const;\n BOOL TestInsertRow( SCSIZE nSize ) const;\n void InsertRow( SCROW nStartRow, SCSIZE nSize );\n void DeleteRow( SCROW nStartRow, SCSIZE nSize );\n void DeleteRange( SCSIZE nStartIndex, SCSIZE nEndIndex );\n void DeleteArea( SCROW nStartRow, SCROW nEndRow );\n void MoveTo( SCROW nStartRow, SCROW nEndRow, ScAttrArray& rAttrArray );\n void CopyArea( SCROW nStartRow, SCROW nEndRow, long nDy, ScAttrArray& rAttrArray,\n INT16 nStripFlags = 0 );\n\n void DeleteHardAttr( SCROW nStartRow, SCROW nEndRow );\n\n void Save( SvStream& rStream ) const;\n void Load( SvStream& rStream );\n void ConvertFontsAfterLoad(); \/\/ old binary file format\n};\n\n\n\/\/ ------------------------------------------------------------------------------\n\/\/ Iterator fuer Attribute\n\/\/ ------------------------------------------------------------------------------\n\nclass ScAttrIterator\n{\n const ScAttrArray* pArray;\n SCSIZE nPos;\n SCROW nRow;\n SCROW nEndRow;\npublic:\n inline ScAttrIterator( const ScAttrArray* pNewArray, SCROW nStart, SCROW nEnd );\n inline const ScPatternAttr* Next( SCROW& rTop, SCROW& rBottom );\n SCROW GetNextRow() const { return nRow; }\n};\n\n\ninline ScAttrIterator::ScAttrIterator( const ScAttrArray* pNewArray, SCROW nStart, SCROW nEnd ) :\n pArray( pNewArray ),\n nRow( nStart ),\n nEndRow( nEnd )\n{\n if ( nStart > 0 )\n pArray->Search( nStart, nPos );\n else\n nPos = 0;\n}\n\ninline const ScPatternAttr* ScAttrIterator::Next( SCROW& rTop, SCROW& rBottom )\n{\n const ScPatternAttr* pRet;\n if ( nPos < pArray->nCount && nRow <= nEndRow )\n {\n rTop = nRow;\n rBottom = Min( pArray->pData[nPos].nRow, nEndRow );\n pRet = pArray->pData[nPos].pPattern;\n nRow = rBottom + 1;\n ++nPos;\n }\n else\n pRet = NULL;\n return pRet;\n}\n\n\n\n#endif\n\n\n<commit_msg>INTEGRATION: CWS dr34 (1.6.2); FILE MERGED 2005\/03\/10 11:41:13 nn 1.6.2.1: #i44697# detect equal ScPatternAttr pointers across MergePatternArea calls<commit_after>\/*************************************************************************\n *\n * $RCSfile: attarray.hxx,v $\n *\n * $Revision: 1.7 $\n *\n * last change: $Author: rt $ $Date: 2005-03-29 13:28:51 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef SC_ATRARR_HXX\n#define SC_ATRARR_HXX\n\n#ifndef SC_SCGLOB_HXX\n#include \"global.hxx\"\n#endif\n\n#ifndef SC_SCATTR_HXX\n#include \"attrib.hxx\"\n#endif\n\nclass ScDocument;\nclass ScMarkArray;\nclass ScPatternAttr;\nclass ScStyleSheet;\n\nclass Rectangle;\nclass SfxItemPoolCache;\nclass SfxStyleSheetBase;\nclass SvxBorderLine;\nclass SvxBoxItem;\nclass SvxBoxInfoItem;\n\n#define SC_LINE_EMPTY 0\n#define SC_LINE_SET 1\n#define SC_LINE_DONTCARE 2\n\n#define SC_ATTRARRAY_DELTA 4\n\nstruct ScLineFlags\n{\n BYTE nLeft;\n BYTE nRight;\n BYTE nTop;\n BYTE nBottom;\n BYTE nHori;\n BYTE nVert;\n\n ScLineFlags() : nLeft(SC_LINE_EMPTY),nRight(SC_LINE_EMPTY),nTop(SC_LINE_EMPTY),\n nBottom(SC_LINE_EMPTY),nHori(SC_LINE_EMPTY),nVert(SC_LINE_EMPTY) {}\n};\n\nstruct ScMergePatternState\n{\n SfxItemSet* pItemSet; \/\/ allocated in MergePatternArea, used for resulting ScPatternAttr\n const ScPatternAttr* pOld1; \/\/ existing objects, temporary\n const ScPatternAttr* pOld2;\n\n ScMergePatternState() : pItemSet(NULL), pOld1(NULL), pOld2(NULL) {}\n};\n\nstruct ScAttrEntry\n{\n SCROW nRow;\n const ScPatternAttr* pPattern;\n};\n\n\nclass ScAttrArray\n{\nprivate:\n SCCOL nCol;\n SCTAB nTab;\n ScDocument* pDocument;\n\n SCSIZE nCount;\n SCSIZE nLimit;\n ScAttrEntry* pData;\n\nfriend class ScDocument; \/\/ fuer FillInfo\nfriend class ScDocumentIterator;\nfriend class ScAttrIterator;\nfriend class ScHorizontalAttrIterator;\nfriend void lcl_IterGetNumberFormat( ULONG& nFormat,\n const ScAttrArray*& rpArr, SCROW& nAttrEndRow,\n const ScAttrArray* pNewArr, SCROW nRow, ScDocument* pDoc );\n\n BOOL ApplyFrame( const SvxBoxItem* pLineOuter, const SvxBoxInfoItem* pLineInner,\n SCROW nStartRow, SCROW nEndRow,\n BOOL bLeft, SCCOL nDistRight, BOOL bTop, SCROW nDistBottom );\n\npublic:\n ScAttrArray( SCCOL nNewCol, SCTAB nNewTab, ScDocument* pDoc );\n ~ScAttrArray();\n\n void SetTab(SCTAB nNewTab) { nTab = nNewTab; }\n void SetCol(SCCOL nNewCol) { nCol = nNewCol; }\n\n void TestData() const;\n void Reset( const ScPatternAttr* pPattern, BOOL bAlloc = TRUE );\n BOOL Concat(SCSIZE nPos);\n\n const ScPatternAttr* GetPattern( SCROW nRow ) const;\n const ScPatternAttr* GetPatternRange( SCROW& rStartRow, SCROW& rEndRow, SCROW nRow ) const;\n void MergePatternArea( SCROW nStartRow, SCROW nEndRow, ScMergePatternState& rState, BOOL bDeep ) const;\n\n void MergeBlockFrame( SvxBoxItem* pLineOuter, SvxBoxInfoItem* pLineInner, ScLineFlags& rFlags,\n SCROW nStartRow, SCROW nEndRow, BOOL bLeft, SCCOL nDistRight ) const;\n void ApplyBlockFrame( const SvxBoxItem* pLineOuter, const SvxBoxInfoItem* pLineInner,\n SCROW nStartRow, SCROW nEndRow, BOOL bLeft, SCCOL nDistRight );\n\n void SetPattern( SCROW nRow, const ScPatternAttr* pPattern, BOOL bPutToPool = FALSE );\n void SetPatternArea( SCROW nStartRow, SCROW nEndRow, const ScPatternAttr* pPattern, BOOL bPutToPool = FALSE);\n void ApplyStyleArea( SCROW nStartRow, SCROW nEndRow, ScStyleSheet* pStyle );\n void ApplyCacheArea( SCROW nStartRow, SCROW nEndRow, SfxItemPoolCache* pCache );\n void ApplyLineStyleArea( SCROW nStartRow, SCROW nEndRow,\n const SvxBorderLine* pLine, BOOL bColorOnly );\n\n void ClearItems( SCROW nStartRow, SCROW nEndRow, const USHORT* pWhich );\n void ChangeIndent( SCROW nStartRow, SCROW nEndRow, BOOL bIncrement );\n\n \/\/\/ Including current, may return -1\n SCsROW GetNextUnprotected( SCsROW nRow, BOOL bUp ) const;\n\n \/\/\/ May return -1 if not found\n SCsROW SearchStyle( SCsROW nRow, const ScStyleSheet* pSearchStyle,\n BOOL bUp, ScMarkArray* pMarkArray = NULL );\n BOOL SearchStyleRange( SCsROW& rRow, SCsROW& rEndRow, const ScStyleSheet* pSearchStyle,\n BOOL bUp, ScMarkArray* pMarkArray = NULL );\n\n BOOL ApplyFlags( SCROW nStartRow, SCROW nEndRow, INT16 nFlags );\n BOOL RemoveFlags( SCROW nStartRow, SCROW nEndRow, INT16 nFlags );\n\n BOOL Search( SCROW nRow, SCSIZE& nIndex ) const;\n\n BOOL HasLines( SCROW nRow1, SCROW nRow2, Rectangle& rSizes,\n BOOL bLeft, BOOL bRight ) const;\n BOOL HasAttrib( SCROW nRow1, SCROW nRow2, USHORT nMask ) const;\n BOOL ExtendMerge( SCCOL nThisCol, SCROW nStartRow, SCROW nEndRow,\n SCCOL& rPaintCol, SCROW& rPaintRow,\n BOOL bRefresh, BOOL bAttrs );\n BOOL RemoveAreaMerge( SCROW nStartRow, SCROW nEndRow );\n\n void FindStyleSheet( const SfxStyleSheetBase* pStyleSheet, BOOL* pUsed, BOOL bReset );\n BOOL IsStyleSheetUsed( const ScStyleSheet& rStyle, BOOL bGatherAllStyles ) const;\n\n void DeleteAreaSafe(SCROW nStartRow, SCROW nEndRow);\n void SetPatternAreaSafe( SCROW nStartRow, SCROW nEndRow,\n const ScPatternAttr* pWantedPattern, BOOL bDefault );\n void CopyAreaSafe( SCROW nStartRow, SCROW nEndRow, long nDy, ScAttrArray& rAttrArray );\n\n BOOL IsEmpty() const;\n\n SCROW GetFirstEntryPos() const;\n SCROW GetLastEntryPos( BOOL bIncludeBottom ) const;\n\n BOOL GetFirstVisibleAttr( SCROW& rFirstRow ) const;\n BOOL GetLastVisibleAttr( SCROW& rLastRow, SCROW nLastData ) const;\n BOOL HasVisibleAttrIn( SCROW nStartRow, SCROW nEndRow ) const;\n BOOL IsVisibleEqual( const ScAttrArray& rOther,\n SCROW nStartRow, SCROW nEndRow ) const;\n BOOL IsAllEqual( const ScAttrArray& rOther, SCROW nStartRow, SCROW nEndRow ) const;\n\n BOOL TestInsertCol( SCROW nStartRow, SCROW nEndRow) const;\n BOOL TestInsertRow( SCSIZE nSize ) const;\n void InsertRow( SCROW nStartRow, SCSIZE nSize );\n void DeleteRow( SCROW nStartRow, SCSIZE nSize );\n void DeleteRange( SCSIZE nStartIndex, SCSIZE nEndIndex );\n void DeleteArea( SCROW nStartRow, SCROW nEndRow );\n void MoveTo( SCROW nStartRow, SCROW nEndRow, ScAttrArray& rAttrArray );\n void CopyArea( SCROW nStartRow, SCROW nEndRow, long nDy, ScAttrArray& rAttrArray,\n INT16 nStripFlags = 0 );\n\n void DeleteHardAttr( SCROW nStartRow, SCROW nEndRow );\n\n void Save( SvStream& rStream ) const;\n void Load( SvStream& rStream );\n void ConvertFontsAfterLoad(); \/\/ old binary file format\n};\n\n\n\/\/ ------------------------------------------------------------------------------\n\/\/ Iterator fuer Attribute\n\/\/ ------------------------------------------------------------------------------\n\nclass ScAttrIterator\n{\n const ScAttrArray* pArray;\n SCSIZE nPos;\n SCROW nRow;\n SCROW nEndRow;\npublic:\n inline ScAttrIterator( const ScAttrArray* pNewArray, SCROW nStart, SCROW nEnd );\n inline const ScPatternAttr* Next( SCROW& rTop, SCROW& rBottom );\n SCROW GetNextRow() const { return nRow; }\n};\n\n\ninline ScAttrIterator::ScAttrIterator( const ScAttrArray* pNewArray, SCROW nStart, SCROW nEnd ) :\n pArray( pNewArray ),\n nRow( nStart ),\n nEndRow( nEnd )\n{\n if ( nStart > 0 )\n pArray->Search( nStart, nPos );\n else\n nPos = 0;\n}\n\ninline const ScPatternAttr* ScAttrIterator::Next( SCROW& rTop, SCROW& rBottom )\n{\n const ScPatternAttr* pRet;\n if ( nPos < pArray->nCount && nRow <= nEndRow )\n {\n rTop = nRow;\n rBottom = Min( pArray->pData[nPos].nRow, nEndRow );\n pRet = pArray->pData[nPos].pPattern;\n nRow = rBottom + 1;\n ++nPos;\n }\n else\n pRet = NULL;\n return pRet;\n}\n\n\n\n#endif\n\n\n<|endoftext|>"} {"text":"<commit_before>#pragma once\n#ifndef OPENGM_POPT_DATA_HXX\n#define OPENGM_POPT_DATA_HXX\n\n#include <vector>\n\/\/#include <string>\n\/\/#include <iostream>\n\n#include <opengm\/opengm.hxx>\n#include <opengm\/utilities\/metaprogramming.hxx>\n#include <opengm\/utilities\/tribool.hxx>\n\/\/#include <opengm\/functions\/reduced_view.hxx>\n#include <opengm\/functions\/explicit_function.hxx>\n\n\nnamespace opengm {\n\/\/! [class popt_data]\n\/\/\/ Partial Optimaility Data (-Container)\n\/\/\/\n\/\/\/ Corresponding author: Joerg Hendrik Kappes\n\/\/\/\n\/\/\/\\ingroup inference\ntemplate<class GM>\nclass POpt_Data {\npublic:\n typedef GM GraphicalModelType;\n typedef GM GmType;\n OPENGM_GM_TYPE_TYPEDEFS;\n\n\/\/ typedef ReducedViewFunction<GraphicalModelType> ReducedViewType;\n typedef opengm::ExplicitFunction<ValueType, LabelType, IndexType> ExplicitFunction;\n typedef GraphicalModel<ValueType, OperatorType, ExplicitFunction> ReducedGmType;\n\n POpt_Data(const GmType&);\n \/\/ Set\n void setTrue(const IndexType, const LabelType);\n void setFalse(const IndexType, const LabelType);\n void setFalse(const IndexType factor, const std::vector<LabelType>& labeling);\n \/\/ Get Partial Optimality\n Tribool getPOpt(const IndexType, const LabelType) const;\n std::vector<opengm::Tribool> getPOpt(const IndexType) const;\n ValueType getPOpt() const;\n \/\/ Get Optimal Certificates\n bool getOpt(const IndexType) const;\n const std::vector<bool>& getOpt() const;\n \/\/ Get Optimal Labels\n LabelType get(const IndexType) const;\n void get(std::vector<LabelType>&) const;\n\n const GmType& graphicalModel() const {return gm_;}\n void reducedGraphicalModel(ReducedGmType&) const;\n\n void OriginalToReducedLabeling(const std::vector<LabelType>& lOrig, std::vector<LabelType>& lRed) const;\n void ReducedToOriginalLabeling(std::vector<LabelType>& lOrig, const std::vector<LabelType>& lRed) const;\n\nprivate:\n const GmType& gm_;\n std::vector<std::vector<opengm::Tribool> > partialOptimality_;\n std::vector<bool> optimal_;\n std::vector<LabelType> labeling_;\n std::vector<IndexType> countFalse_;\n std::vector<std::vector<std::vector<LabelType> > > excludedLabelings_; \/\/ for each factor the excluded labelings are pushed\n std::vector<std::vector<std::vector<LabelType> > > excludedCount_;\n \/\/ count for number of excluded labelings in which (variable,label) partakes\n \/\/ used for elimination of variables\n};\n\/\/! [class popt_data]\n\n\/\/********************************************\n\ntemplate<class GM>\nPOpt_Data<GM>::POpt_Data\n(\n const GmType& gm\n)\n : gm_(gm),\n partialOptimality_(std::vector<std::vector<opengm::Tribool> >(gm.numberOfVariables()) ),\n optimal_(std::vector<bool>(gm.numberOfVariables(),false)),\n labeling_(std::vector<LabelType>(gm.numberOfVariables(),0)),\n countFalse_(std::vector<IndexType>(gm.numberOfVariables(),0)),\n excludedLabelings_(gm.numberOfFactors()),\n excludedCount_(gm.numberOfFactors()) {\n\n for(IndexType var=0; var<gm_.numberOfVariables(); ++var) {\n partialOptimality_[var].resize(gm_.numberOfLabels(var),opengm::Tribool::Maybe);\n }\n for(size_t f=0; f<gm_.numberOfFactors(); f++) {\n excludedCount_[f].resize(gm_[f].numberOfVariables());\n for(size_t var=0; var<gm_[f].numberOfVariables(); var++) {\n excludedCount_[f][var].resize( gm_.numberOfVariables( gm_.variableOfFactor(f,var) ), 0);\n }\n }\n}\n\n\/\/********************************************\n\n\/\/ Set\ntemplate<class GM>\nvoid POpt_Data<GM>:: setTrue(const IndexType var, const LabelType label) {\n OPENGM_ASSERT( var < gm_.numberOfVariables() );\n OPENGM_ASSERT( label < gm_.numberOfLabels(var) );\n\n optimal_[var] = true;\n labeling_[var] = label;\n\n OPENGM_ASSERT(partialOptimality_[var][label] != false);\n partialOptimality_[var][label] = true;\n\n for(size_t i=0; i<label; ++i) {\n OPENGM_ASSERT(partialOptimality_[var][i] != true);\n partialOptimality_[var][i] = false;\n }\n for(size_t i=label+1; i<partialOptimality_[var].size(); ++i) {\n OPENGM_ASSERT(partialOptimality_[var][i] != true);\n partialOptimality_[var][i] = false;\n }\n countFalse_[var] = partialOptimality_[var].size()-1;\n}\n\ntemplate<class GM>\nvoid POpt_Data<GM>::setFalse(IndexType var, LabelType label) {\n OPENGM_ASSERT( var < gm_.numberOfVariables() );\n OPENGM_ASSERT( label < gm_.numberOfLabels(var) );\n\n if( optimal_[var] ) {\n OPENGM_ASSERT(labeling_[var] != label);\n } else {\n OPENGM_ASSERT(partialOptimality_[var][label] != true);\n partialOptimality_[var][label] = false;\n if(++countFalse_[var] == partialOptimality_[var].size()-1) {\n for(size_t i=0; i<partialOptimality_[var].size(); ++i) {\n if( partialOptimality_[var][i] != false ) {\n partialOptimality_[var][i] = true;\n optimal_[var] = true;\n labeling_[var] = i;\n break;\n }\n }\n }\n }\n}\n\ntemplate<class GM>\nvoid POpt_Data<GM>::setFalse(IndexType f, const std::vector<LabelType>& labeling) {\n OPENGM_ASSERT( f < gm_.numberOfFactors() );\n OPENGM_ASSERT( labeling.size() == gm_[f].numberOfVariables() );\n bool labelingTrue = true;\n for(size_t var=0; var<gm_[f].numberOfVariables(); var++) {\n OPENGM_ASSERT( labeling[var] < gm_.numberOfVariables( gm_.variableOfFactor(f,var) ) );\n OPENGM_ASSERT( getPOpt(gm_.variableOfFactor(f,var), labeling[var]) != Tribool::False );\n getPOpt( gm_.variableOfFactor(f,var), labeling[var] ) == Tribool::True ? labelingTrue= true : labelingTrue = false;\n }\n OPENGM_ASSERT( labelingTrue == false);\n for(size_t e=0; e<excludedLabelings_[f].size(); e++) {\n OPENGM_ASSERT( std::equal(labeling.begin(), labeling.end(), excludedLabelings_[f][e].begin()) );\n }\n\n excludedLabelings_[f].push(labeling);\n\n \/\/ check for implications: e.g. if all labels (i,1), ... (i,n) are excluded, exclude label i for the first variables as well.\n for(size_t var=0; var<gm_[f].numberOfVariables(); var++) {\n excludedCount_[f][var][ labeling[var] ]++;\n }\n for(size_t var=0; var<gm_[f].numberOfVariables(); var++) {\n if(excludedCount_[f][var][ labeling[var] ] == gm_[f].size()\/gm_.numberOfLabels(gm_.variableOfFactor(f,var)) ) {\n \/\/ label can be excluded\n setFalse(gm_.variableOfFactor(f,var), labeling[var]);\n }\n }\n}\n\n\/\/ Get Partial Optimality\ntemplate<class GM>\nTribool POpt_Data<GM>::getPOpt(const IndexType var, const LabelType label) const {\n OPENGM_ASSERT( var < gm_.numberOfVariables() );\n OPENGM_ASSERT( label < gm_.numberOfLabels(var) );\n return partialOptimality_[var][label];\n}\n\ntemplate<class GM>\nstd::vector<opengm::Tribool> POpt_Data<GM>::getPOpt(const IndexType var) const {\n OPENGM_ASSERT( var<gm_.numberOfVariables() );\n return partialOptimality_[var];\n}\n\ntemplate<class GM>\ntypename GM::ValueType POpt_Data<GM>::getPOpt() const {\n size_t noExcludedLabels = 0;\n size_t noLabels = 0;\n for(size_t var=0; var<gm_.numberOfVariables(); var++) {\n noLabels += gm_.numberOfLabels(var);\n for(size_t i=0; i<gm_.numberOfLabels(var); i++) {\n if(getPOpt(var,i) == false)\n noExcludedLabels++;\n }\n }\n OPENGM_ASSERT(noLabels > 0);\n OPENGM_ASSERT(noExcludedLabels < noLabels);\n ValueType p = ValueType(noExcludedLabels) \/ ValueType(noLabels - gm_.numberOfVariables());\n\n OPENGM_ASSERT(p <= 1.0);\n return p;\n}\n\n\/\/ Get Optimality\ntemplate<class GM>\nbool POpt_Data<GM>::getOpt(const IndexType var) const {\n OPENGM_ASSERT( var<gm_.numberOfVariables() );\n return optimal_[var];\n}\n\ntemplate<class GM>\nconst std::vector<bool>& POpt_Data<GM>::getOpt() const {\n return optimal_;\n}\n\n\/\/ Get Optimal Labels\ntemplate<class GM>\ntypename GM::LabelType POpt_Data<GM>::get(const IndexType var) const {\n OPENGM_ASSERT( var<gm_.numberOfVariables() );\n return labeling_[var];\n}\n\ntemplate<class GM>\nvoid POpt_Data<GM>::get(std::vector<LabelType>& labeling) const {\n OPENGM_ASSERT(labeling.size() == gm_.numberOfVariables());\n for(IndexType var=0; var<gm_.numberOfVariables(); ++var) {\n if( optimal_[var] )\n labeling[var] = labeling_[var];\n }\n}\n\ntemplate<class GM>\nvoid POpt_Data<GM>::reducedGraphicalModel(ReducedGmType& reducedGm) const\n{\n \/\/Variables and their labels are included in case they are not optimal yet.\n\n IndexType newVariable[gm_.numberOfVariables()];\n IndexType variable = 0;\n\n for (IndexType v = 0; v < gm_.numberOfVariables(); v++) {\n if(!optimal_[v]) {\n newVariable[v] = variable;\n variable++;\n\n LabelType numLabels = 0;\n\n for(IndexType i = 0; i < gm_.numberOfLabels(v); i++) {\n if(!(partialOptimality_[v][i] == opengm::Tribool::False))\n numLabels++;\n }\n OPENGM_ASSERT(numLabels>1);\n reducedGm.addVariable(numLabels);\n }\n }\n\n\n \/\/factors will be included in case one of their variables is not optimal yet.\n for (IndexType f = 0; f < gm_.numberOfFactors(); f++) {\n bool insert_f = false;\n size_t numVariables = 0;\n std::vector<IndexType> variablesOfFactor;\n std::vector<IndexType> numLabels;\n IndexType numLabelComb = 1;\n\n for(IndexType v = 0; v < gm_[f].numberOfVariables(); v++){\n if(!optimal_[gm_[f].variableIndex(v)]){\n insert_f = true;\n numVariables++;\n variablesOfFactor.std::vector<IndexType>::push_back(newVariable[gm_[f].variableIndex(v)]);\n numLabels.std::vector<IndexType>::push_back(reducedGm.numberOfLabels(newVariable[gm_[f].variableIndex(v)]));\n numLabelComb *= numLabels.std::vector<IndexType>::back();\n }\n }\n\n if(insert_f){\n ExplicitFunction g(numLabels.std::vector<IndexType>::begin(), numLabels.std::vector<IndexType>::end());\n LabelType reducedShape [numVariables];\n LabelType shape [gm_[f].numberOfVariables()];\n\n for(size_t v = 0; v < numVariables; v++){\n reducedShape[v] = 0;\n }\n\n for(size_t v = 0; v < gm_[f].numberOfVariables(); v++){\n if(optimal_[gm_[f].variableIndex(v)]){\n shape[v] = labeling_[gm_[f].variableIndex(v)];\n }else{\n shape[v] = 0;\n }\n }\n g(reducedShape) = gm_[f](shape);\n\n for(size_t comb = 1; comb < numLabelComb; comb++){\n \/\/next label combination\n IndexType nextStep = 0;\n while(reducedShape[nextStep] = numLabels[nextStep] && nextStep < numVariables-1){\n nextStep++;\n }\n reducedShape[nextStep]++;\n\n size_t index = 0;\n for(size_t v = 0; v < nextStep; v++){\n reducedShape[v] = 0;\n\n while(optimal_[gm_[f].variableIndex(index)])\n index++;\n\n size_t label = 0;\n while(partialOptimality_[gm_[f].variableIndex(index)][label] == opengm::Tribool::False)\n label++;\n\n shape[index] = label;\n index++;\n }\n\n while(optimal_[gm_[f].variableIndex(index)]){\n index++;\n }\n shape[index]++;\n while(partialOptimality_[gm_[f].variableIndex(index)][shape[index]] == opengm::Tribool::False)\n shape[index]++;\n\n g(reducedShape) = gm_[f](shape);\n }\n\n typename ReducedGmType::FunctionIdentifier id = reducedGm.addFunction(g);\n\n reducedGm.addFactor(id, variablesOfFactor.std::vector<IndexType>::begin(), variablesOfFactor.std::vector<IndexType>::end());\n }\n }\n}\n\ntemplate<class GM>\nvoid POpt_Data<GM>::OriginalToReducedLabeling(const std::vector<LabelType>& lOrig, std::vector<LabelType>& lRed) const\n{\n}\n\ntemplate<class GM>\nvoid POpt_Data<GM>::ReducedToOriginalLabeling(std::vector<LabelType>& lOrig, const std::vector<LabelType>& lRed) const\n{\n}\n\n\n} \/\/ namespace opengm\n\n#endif \/\/ #ifndef OPENGM_POPT_DATA_HXX\n<commit_msg>wrote the functions which switch reduced into nonreduced labelings and back<commit_after>#pragma once\n#ifndef OPENGM_POPT_DATA_HXX\n#define OPENGM_POPT_DATA_HXX\n\n#include <vector>\n\/\/#include <string>\n\/\/#include <iostream>\n\n#include <opengm\/opengm.hxx>\n#include <opengm\/utilities\/metaprogramming.hxx>\n#include <opengm\/utilities\/tribool.hxx>\n\/\/#include <opengm\/functions\/reduced_view.hxx>\n#include <opengm\/functions\/explicit_function.hxx>\n\n\nnamespace opengm {\n\/\/! [class popt_data]\n\/\/\/ Partial Optimaility Data (-Container)\n\/\/\/\n\/\/\/ Corresponding author: Joerg Hendrik Kappes\n\/\/\/\n\/\/\/\\ingroup inference\ntemplate<class GM>\nclass POpt_Data {\npublic:\n typedef GM GraphicalModelType;\n typedef GM GmType;\n OPENGM_GM_TYPE_TYPEDEFS;\n\n\/\/ typedef ReducedViewFunction<GraphicalModelType> ReducedViewType;\n typedef opengm::ExplicitFunction<ValueType, LabelType, IndexType> ExplicitFunction;\n typedef GraphicalModel<ValueType, OperatorType, ExplicitFunction> ReducedGmType;\n\n POpt_Data(const GmType&);\n \/\/ Set\n void setTrue(const IndexType, const LabelType);\n void setFalse(const IndexType, const LabelType);\n void setFalse(const IndexType factor, const std::vector<LabelType>& labeling);\n \/\/ Get Partial Optimality\n Tribool getPOpt(const IndexType, const LabelType) const;\n std::vector<opengm::Tribool> getPOpt(const IndexType) const;\n ValueType getPOpt() const;\n \/\/ Get Optimal Certificates\n bool getOpt(const IndexType) const;\n const std::vector<bool>& getOpt() const;\n \/\/ Get Optimal Labels\n LabelType get(const IndexType) const;\n void get(std::vector<LabelType>&) const;\n\n const GmType& graphicalModel() const {return gm_;}\n void reducedGraphicalModel(ReducedGmType&) const;\n\n void OriginalToReducedLabeling(const std::vector<LabelType>& lOrig, std::vector<LabelType>& lRed) const;\n void ReducedToOriginalLabeling(std::vector<LabelType>& lOrig, const std::vector<LabelType>& lRed) const;\n\nprivate:\n const GmType& gm_;\n std::vector<std::vector<opengm::Tribool> > partialOptimality_;\n std::vector<bool> optimal_;\n std::vector<LabelType> labeling_;\n std::vector<IndexType> countFalse_;\n std::vector<std::vector<std::vector<LabelType> > > excludedLabelings_; \/\/ for each factor the excluded labelings are pushed\n std::vector<std::vector<std::vector<LabelType> > > excludedCount_;\n \/\/ count for number of excluded labelings in which (variable,label) partakes\n \/\/ used for elimination of variables\n};\n\/\/! [class popt_data]\n\n\/\/********************************************\n\ntemplate<class GM>\nPOpt_Data<GM>::POpt_Data\n(\n const GmType& gm\n)\n : gm_(gm),\n partialOptimality_(std::vector<std::vector<opengm::Tribool> >(gm.numberOfVariables()) ),\n optimal_(std::vector<bool>(gm.numberOfVariables(),false)),\n labeling_(std::vector<LabelType>(gm.numberOfVariables(),0)),\n countFalse_(std::vector<IndexType>(gm.numberOfVariables(),0)),\n excludedLabelings_(gm.numberOfFactors()),\n excludedCount_(gm.numberOfFactors()) {\n\n for(IndexType var=0; var<gm_.numberOfVariables(); ++var) {\n partialOptimality_[var].resize(gm_.numberOfLabels(var),opengm::Tribool::Maybe);\n }\n for(size_t f=0; f<gm_.numberOfFactors(); f++) {\n excludedCount_[f].resize(gm_[f].numberOfVariables());\n for(size_t var=0; var<gm_[f].numberOfVariables(); var++) {\n excludedCount_[f][var].resize( gm_.numberOfVariables( gm_.variableOfFactor(f,var) ), 0);\n }\n }\n}\n\n\/\/********************************************\n\n\/\/ Set\ntemplate<class GM>\nvoid POpt_Data<GM>:: setTrue(const IndexType var, const LabelType label) {\n OPENGM_ASSERT( var < gm_.numberOfVariables() );\n OPENGM_ASSERT( label < gm_.numberOfLabels(var) );\n\n optimal_[var] = true;\n labeling_[var] = label;\n\n OPENGM_ASSERT(partialOptimality_[var][label] != false);\n partialOptimality_[var][label] = true;\n\n for(size_t i=0; i<label; ++i) {\n OPENGM_ASSERT(partialOptimality_[var][i] != true);\n partialOptimality_[var][i] = false;\n }\n for(size_t i=label+1; i<partialOptimality_[var].size(); ++i) {\n OPENGM_ASSERT(partialOptimality_[var][i] != true);\n partialOptimality_[var][i] = false;\n }\n countFalse_[var] = partialOptimality_[var].size()-1;\n}\n\ntemplate<class GM>\nvoid POpt_Data<GM>::setFalse(IndexType var, LabelType label) {\n OPENGM_ASSERT( var < gm_.numberOfVariables() );\n OPENGM_ASSERT( label < gm_.numberOfLabels(var) );\n\n if( optimal_[var] ) {\n OPENGM_ASSERT(labeling_[var] != label);\n } else {\n OPENGM_ASSERT(partialOptimality_[var][label] != true);\n partialOptimality_[var][label] = false;\n if(++countFalse_[var] == partialOptimality_[var].size()-1) {\n for(size_t i=0; i<partialOptimality_[var].size(); ++i) {\n if( partialOptimality_[var][i] != false ) {\n partialOptimality_[var][i] = true;\n optimal_[var] = true;\n labeling_[var] = i;\n break;\n }\n }\n }\n }\n}\n\ntemplate<class GM>\nvoid POpt_Data<GM>::setFalse(IndexType f, const std::vector<LabelType>& labeling) {\n OPENGM_ASSERT( f < gm_.numberOfFactors() );\n OPENGM_ASSERT( labeling.size() == gm_[f].numberOfVariables() );\n bool labelingTrue = true;\n for(size_t var=0; var<gm_[f].numberOfVariables(); var++) {\n OPENGM_ASSERT( labeling[var] < gm_.numberOfVariables( gm_.variableOfFactor(f,var) ) );\n OPENGM_ASSERT( getPOpt(gm_.variableOfFactor(f,var), labeling[var]) != Tribool::False );\n getPOpt( gm_.variableOfFactor(f,var), labeling[var] ) == Tribool::True ? labelingTrue= true : labelingTrue = false;\n }\n OPENGM_ASSERT( labelingTrue == false);\n for(size_t e=0; e<excludedLabelings_[f].size(); e++) {\n OPENGM_ASSERT( std::equal(labeling.begin(), labeling.end(), excludedLabelings_[f][e].begin()) );\n }\n\n excludedLabelings_[f].push(labeling);\n\n \/\/ check for implications: e.g. if all labels (i,1), ... (i,n) are excluded, exclude label i for the first variables as well.\n for(size_t var=0; var<gm_[f].numberOfVariables(); var++) {\n excludedCount_[f][var][ labeling[var] ]++;\n }\n for(size_t var=0; var<gm_[f].numberOfVariables(); var++) {\n if(excludedCount_[f][var][ labeling[var] ] == gm_[f].size()\/gm_.numberOfLabels(gm_.variableOfFactor(f,var)) ) {\n \/\/ label can be excluded\n setFalse(gm_.variableOfFactor(f,var), labeling[var]);\n }\n }\n}\n\n\/\/ Get Partial Optimality\ntemplate<class GM>\nTribool POpt_Data<GM>::getPOpt(const IndexType var, const LabelType label) const {\n OPENGM_ASSERT( var < gm_.numberOfVariables() );\n OPENGM_ASSERT( label < gm_.numberOfLabels(var) );\n return partialOptimality_[var][label];\n}\n\ntemplate<class GM>\nstd::vector<opengm::Tribool> POpt_Data<GM>::getPOpt(const IndexType var) const {\n OPENGM_ASSERT( var<gm_.numberOfVariables() );\n return partialOptimality_[var];\n}\n\ntemplate<class GM>\ntypename GM::ValueType POpt_Data<GM>::getPOpt() const {\n size_t noExcludedLabels = 0;\n size_t noLabels = 0;\n for(size_t var=0; var<gm_.numberOfVariables(); var++) {\n noLabels += gm_.numberOfLabels(var);\n for(size_t i=0; i<gm_.numberOfLabels(var); i++) {\n if(getPOpt(var,i) == false)\n noExcludedLabels++;\n }\n }\n OPENGM_ASSERT(noLabels > 0);\n OPENGM_ASSERT(noExcludedLabels < noLabels);\n ValueType p = ValueType(noExcludedLabels) \/ ValueType(noLabels - gm_.numberOfVariables());\n\n OPENGM_ASSERT(p <= 1.0);\n return p;\n}\n\n\/\/ Get Optimality\ntemplate<class GM>\nbool POpt_Data<GM>::getOpt(const IndexType var) const {\n OPENGM_ASSERT( var<gm_.numberOfVariables() );\n return optimal_[var];\n}\n\ntemplate<class GM>\nconst std::vector<bool>& POpt_Data<GM>::getOpt() const {\n return optimal_;\n}\n\n\/\/ Get Optimal Labels\ntemplate<class GM>\ntypename GM::LabelType POpt_Data<GM>::get(const IndexType var) const {\n OPENGM_ASSERT( var<gm_.numberOfVariables() );\n return labeling_[var];\n}\n\ntemplate<class GM>\nvoid POpt_Data<GM>::get(std::vector<LabelType>& labeling) const {\n OPENGM_ASSERT(labeling.size() == gm_.numberOfVariables());\n for(IndexType var=0; var<gm_.numberOfVariables(); ++var) {\n if( optimal_[var] )\n labeling[var] = labeling_[var];\n }\n}\n\ntemplate<class GM>\nvoid POpt_Data<GM>::reducedGraphicalModel(ReducedGmType& reducedGm) const\n{\n \/\/Variables and their labels are included in case they are not optimal yet.\n\n IndexType newVariable[gm_.numberOfVariables()];\n IndexType variable = 0;\n\n for (IndexType v = 0; v < gm_.numberOfVariables(); v++) {\n if(!optimal_[v]) {\n newVariable[v] = variable;\n variable++;\n\n LabelType numLabels = 0;\n\n for(IndexType i = 0; i < gm_.numberOfLabels(v); i++) {\n if(!(partialOptimality_[v][i] == opengm::Tribool::False))\n numLabels++;\n }\n OPENGM_ASSERT(numLabels>1);\n reducedGm.addVariable(numLabels);\n }\n }\n\n\n \/\/factors will be included in case one of their variables is not optimal yet.\n for (IndexType f = 0; f < gm_.numberOfFactors(); f++) {\n bool insert_f = false;\n size_t numVariables = 0;\n std::vector<IndexType> variablesOfFactor;\n std::vector<IndexType> numLabels;\n IndexType numLabelComb = 1;\n\n for(IndexType v = 0; v < gm_[f].numberOfVariables(); v++){\n if(!optimal_[gm_[f].variableIndex(v)]){\n insert_f = true;\n numVariables++;\n variablesOfFactor.std::vector<IndexType>::push_back(newVariable[gm_[f].variableIndex(v)]);\n numLabels.std::vector<IndexType>::push_back(reducedGm.numberOfLabels(newVariable[gm_[f].variableIndex(v)]));\n numLabelComb *= numLabels.std::vector<IndexType>::back();\n }\n }\n\n if(insert_f){\n ExplicitFunction g(numLabels.std::vector<IndexType>::begin(), numLabels.std::vector<IndexType>::end());\n LabelType reducedShape [numVariables];\n LabelType shape [gm_[f].numberOfVariables()];\n\n for(size_t v = 0; v < numVariables; v++){\n reducedShape[v] = 0;\n }\n\n for(size_t v = 0; v < gm_[f].numberOfVariables(); v++){\n if(optimal_[gm_[f].variableIndex(v)]){\n shape[v] = labeling_[gm_[f].variableIndex(v)];\n }else{\n shape[v] = 0;\n }\n }\n g(reducedShape) = gm_[f](shape);\n\n for(size_t comb = 1; comb < numLabelComb; comb++){\n \/\/next label combination\n IndexType nextStep = 0;\n while(reducedShape[nextStep] = numLabels[nextStep] && nextStep < numVariables-1){\n nextStep++;\n }\n reducedShape[nextStep]++;\n\n size_t index = 0;\n for(size_t v = 0; v < nextStep; v++){\n reducedShape[v] = 0;\n\n while(optimal_[gm_[f].variableIndex(index)])\n index++;\n\n size_t label = 0;\n while(partialOptimality_[gm_[f].variableIndex(index)][label] == opengm::Tribool::False)\n label++;\n\n shape[index] = label;\n index++;\n }\n\n while(optimal_[gm_[f].variableIndex(index)]){\n index++;\n }\n shape[index]++;\n while(partialOptimality_[gm_[f].variableIndex(index)][shape[index]] == opengm::Tribool::False)\n shape[index]++;\n\n g(reducedShape) = gm_[f](shape);\n }\n\n typename ReducedGmType::FunctionIdentifier id = reducedGm.addFunction(g);\n\n reducedGm.addFactor(id, variablesOfFactor.std::vector<IndexType>::begin(), variablesOfFactor.std::vector<IndexType>::end());\n }\n }\n}\n\ntemplate<class GM>\nvoid POpt_Data<GM>::OriginalToReducedLabeling(const std::vector<LabelType>& lOrig, std::vector<LabelType>& lRed) const\n{\n if(lOrig.std::vector<LabelType>::size() == gm_.numberOfVariables() && lRed.std::vector<LabelType>::empty())\n {\n for(size_t origIndex = 0; origIndex < gm_.numberOfVariables(); origIndex++)\n {\n if(optimal_[origIndex])\n {\n if(!lOrig[origIndex] == labeling_[origIndex])\n {\n std::cout << \"ERROR: The given labeling cannot be optimal.\" << std::endl;\n return;\n }\n } else {\n lRed.std::vector<LabelType>::push_back(lOrig[origIndex]);\n }\n }\n }\n}\n\ntemplate<class GM>\nvoid POpt_Data<GM>::ReducedToOriginalLabeling(std::vector<LabelType>& lOrig, const std::vector<LabelType>& lRed) const\n{\n size_t redIndex = 0;\n\n if(lOrig.std::vector<LabelType>::empty())\n {\n for(size_t origIndex = 0; origIndex < gm_.numberOfVariables(); origIndex++)\n {\n if(optimal_[origIndex])\n {\n lOrig.std::vector<LabelType>::push_back(labeling_[origIndex]);\n } else {\n lOrig.std::vector<LabelType>::push_back(lRed[redIndex]);\n redIndex++;\n }\n }\n }\n}\n\n} \/\/ namespace opengm\n\n#endif \/\/ #ifndef OPENGM_POPT_DATA_HXX\n<|endoftext|>"} {"text":"<commit_before>using namespace std;\n\n#include <algorithm> \/\/ std::max\n#include \"IntMap.h\"\n#include \"IntStack.h\"\n\nnamespace iProlog\n{\n\tIntMap::IntMap(int const size, float const fillFactor) : m_fillFactor(fillFactor)\n\t{\n\t InitializeInstanceFields();\n\t if (fillFactor <= 0 || fillFactor >= 1)\n\t {\n\t\tthrow invalid_argument(\"FillFactor must be in (0, 1)\");\n\t }\n\t if (size <= 0)\n\t {\n\t\tthrow invalid_argument(\"Size must be positive!\");\n\t }\n\t const int capacity = arraySize(size, fillFactor);\n\t m_mask = capacity - 1;\n\t m_mask2 = capacity * 2 - 1;\n\n\t m_data = std::vector<int>(capacity * 2);\n\t m_threshold = static_cast<int>(capacity * fillFactor);\n\t}\n\n\tint IntMap::get(int const key)\n\t{\n\t int ptr = (phiMix(key) & m_mask) << 1;\n\n\t if (key == FREE_KEY)\n\t {\n\t\treturn m_hasFreeKey ? m_freeValue : NO_VALUE;\n\t }\n\n\t int k = m_data[ptr];\n\n\t if (k == FREE_KEY)\n\t {\n\t\treturn NO_VALUE; \/\/end of chain already\n\t }\n\t if (k == key) \/\/we check FREE prior to this call\n\t {\n\t\treturn m_data[ptr + 1];\n\t }\n\n\t while (true)\n\t {\n\t\tptr = ptr + 2 & m_mask2; \/\/that's next index\n\t\tk = m_data[ptr];\n\t\tif (k == FREE_KEY)\n\t\t{\n\t\t return NO_VALUE;\n\t\t}\n\t\tif (k == key)\n\t\t{\n\t\t return m_data[ptr + 1];\n\t\t}\n\t }\n\t}\n\n\tbool IntMap::contains(int const key)\n\t{\n\t return NO_VALUE != get(key);\n\t}\n\n\tbool IntMap::add(int const key)\n\t{\n\t return NO_VALUE != put(key, 666);\n\t}\n\n\tbool IntMap::delete_Renamed(int const key)\n\t{\n\t return NO_VALUE != remove(key);\n\t}\n\n\tbool IntMap::isEmpty()\n\t{\n\t return 0 == m_size;\n\t}\n\n\tvoid IntMap::intersect0(IntMap *const m, std::vector<IntMap*> &maps, std::vector<IntMap*> &vmaps, IntStack *const r)\n\t{\n\t const std::vector<int> data = m->m_data;\n\t for (int k = 0; k < data.size(); k += 2)\n\t {\n\t\tbool found = true;\n\t\tconst int key = data[k];\n\t\tif (FREE_KEY == key)\n\t\t{\n\t\t continue;\n\t\t}\n\t\tfor (int i = 1; i < maps.size(); i++)\n\t\t{\n\t\t IntMap * const map = maps[i];\n\t\t const int val = map->get(key);\n\n\t\t if (NO_VALUE == val)\n\t\t {\n\t\t\tIntMap * const vmap = vmaps[i];\n\t\t\tconst int vval = vmap->get(key);\n\t\t\tif (NO_VALUE == vval)\n\t\t\t{\n\t\t\t found = false;\n\t\t\t break;\n\t\t\t}\n\t\t }\n\t\t}\n\t\tif (found)\n\t\t{\n\t\t r->push(key);\n\t\t}\n\t }\n\t}\n\n\tIntStack *IntMap::intersect(std::vector<IntMap*> &maps, std::vector<IntMap*> &vmaps)\n\t{\n\t IntStack * const r = new IntStack();\n\n\t intersect0(maps[0], maps, vmaps, r);\n\t intersect0(vmaps[0], maps, vmaps, r);\n\t return r;\n\t}\n\n\tint IntMap::put(int const key, int const value)\n\t{\n\t if (key == FREE_KEY)\n\t {\n\t\tconst int ret = m_freeValue;\n\t\tif (!m_hasFreeKey)\n\t\t{\n\t\t ++m_size;\n\t\t}\n\t\tm_hasFreeKey = true;\n\t\tm_freeValue = value;\n\t\treturn ret;\n\t }\n\n\t int ptr = (phiMix(key) & m_mask) << 1;\n\t int k = m_data[ptr];\n\t if (k == FREE_KEY) \/\/end of chain already\n\t {\n\t\tm_data[ptr] = key;\n\t\tm_data[ptr + 1] = value;\n\t\tif (m_size >= m_threshold)\n\t\t{\n\t\t rehash(m_data.size() * 2); \/\/size is set inside\n\t\t}\n\t\telse\n\t\t{\n\t\t ++m_size;\n\t\t}\n\t\treturn NO_VALUE;\n\t }\n\t else if (k == key) \/\/we check FREE prior to this call\n\t {\n\t\tconst int ret = m_data[ptr + 1];\n\t\tm_data[ptr + 1] = value;\n\t\treturn ret;\n\t }\n\n\t while (true)\n\t {\n\t\tptr = ptr + 2 & m_mask2; \/\/that's next index calculation\n\t\tk = m_data[ptr];\n\t\tif (k == FREE_KEY)\n\t\t{\n\t\t m_data[ptr] = key;\n\t\t m_data[ptr + 1] = value;\n\t\t if (m_size >= m_threshold)\n\t\t {\n\t\t\trehash(m_data.size() * 2); \/\/size is set inside\n\t\t }\n\t\t else\n\t\t {\n\t\t\t++m_size;\n\t\t }\n\t\t return NO_VALUE;\n\t\t}\n\t\telse if (k == key)\n\t\t{\n\t\t const int ret = m_data[ptr + 1];\n\t\t m_data[ptr + 1] = value;\n\t\t return ret;\n\t\t}\n\t }\n\t}\n\n\tint IntMap::remove(int const key)\n\t{\n\t if (key == FREE_KEY)\n\t {\n\t\tif (!m_hasFreeKey)\n\t\t{\n\t\t return NO_VALUE;\n\t\t}\n\t\tm_hasFreeKey = false;\n\t\t--m_size;\n\t\treturn m_freeValue; \/\/value is not cleaned\n\t }\n\n\t int ptr = (phiMix(key) & m_mask) << 1;\n\t int k = m_data[ptr];\n\t if (k == key) \/\/we check FREE prior to this call\n\t {\n\t\tconst int res = m_data[ptr + 1];\n\t\tshiftKeys(ptr);\n\t\t--m_size;\n\t\treturn res;\n\t }\n\t else if (k == FREE_KEY)\n\t {\n\t\treturn NO_VALUE; \/\/end of chain already\n\t }\n\t while (true)\n\t {\n\t\tptr = ptr + 2 & m_mask2; \/\/that's next index calculation\n\t\tk = m_data[ptr];\n\t\tif (k == key)\n\t\t{\n\t\t const int res = m_data[ptr + 1];\n\t\t shiftKeys(ptr);\n\t\t --m_size;\n\t\t return res;\n\t\t}\n\t\telse if (k == FREE_KEY)\n\t\t{\n\t\t return NO_VALUE;\n\t\t}\n\t }\n\t}\n\n\tint IntMap::shiftKeys(int pos)\n\t{\n\t \/\/ Shift entries with the same hash.\n\t int last, slot;\n\t int k;\n\t std::vector<int> data = m_data;\n\t while (true)\n\t {\n\t\tpos = (last = pos) + 2 & m_mask2;\n\t\twhile (true)\n\t\t{\n\t\t if ((k = data[pos]) == FREE_KEY)\n\t\t {\n\t\t\tdata[last] = FREE_KEY;\n\t\t\treturn last;\n\t\t }\n\t\t slot = (phiMix(k) & m_mask) << 1; \/\/calculate the starting slot for the current key\n\t\t if (last <= pos ? last >= slot || slot > pos : last >= slot && slot > pos)\n\t\t {\n\t\t\tbreak;\n\t\t }\n\t\t pos = pos + 2 & m_mask2; \/\/go to the next entry\n\t\t}\n\t\tdata[last] = k;\n\t\tdata[last + 1] = data[pos + 1];\n\t }\n\t}\n\n\tint IntMap::size()\n\t{\n\t return m_size;\n\t}\n\n\tvoid IntMap::rehash(int const newCapacity)\n\t{\n\t m_threshold = static_cast<int>(newCapacity \/ 2 * m_fillFactor);\n\t m_mask = newCapacity \/ 2 - 1;\n\t m_mask2 = newCapacity - 1;\n\n\t const int oldCapacity = m_data.size();\n\t const std::vector<int> oldData = m_data;\n\n\t m_data = std::vector<int>(newCapacity);\n\t m_size = m_hasFreeKey ? 1 : 0;\n\n\t for (int i = 0; i < oldCapacity; i += 2)\n\t {\n\t\tconst int oldKey = oldData[i];\n\t\tif (oldKey != FREE_KEY)\n\t\t{\n\t\t put(oldKey, oldData[i + 1]);\n\t\t}\n\t }\n\t}\n\n\tlong long IntMap::nextPowerOfTwo(long long x)\n\t{\n\t if (x == 0)\n\t {\n\t\treturn 1;\n\t }\n\t x--;\n\t x |= x >> 1;\n\t x |= x >> 2;\n\t x |= x >> 4;\n\t x |= x >> 8;\n\t x |= x >> 16;\n\t return (x | x >> 32) + 1;\n\t}\n\n\tint IntMap::arraySize(int const expected, float const f)\n\t{\n\t const long long s = max(2LL, nextPowerOfTwo(static_cast<long long>(ceil(expected \/ f))));\n\t if (s > 1 << 30)\n\t {\n\t\tthrow invalid_argument(\"Too large (\" + StringHelper::toString(expected) + \" expected elements with load factor \" + StringHelper::toString(f) + \")\");\n\t }\n\t return static_cast<int>(s);\n\t}\n\n\tint IntMap::phiMix(int const x)\n\t{\n\t const int h = x * INT_PHI;\n\t return h ^ h >> 16;\n\t}\n\n\tstring IntMap::toString()\n\t{\n\t StringBuilder * const b = new StringBuilder(\"{\");\n\t const int l = m_data.size();\n\t bool first = true;\n\t for (int i = 0; i < l; i += 2)\n\t {\n\t\tconst int v = m_data[i];\n\t\tif (v != FREE_KEY)\n\t\t{\n\t\t if (!first)\n\t\t {\n\t\t\tb->append(',');\n\t\t }\n\t\t first = false;\n\t\t b->append(v - 1);\n\t\t}\n\t }\n\t b->append(\"}\");\n\t return b->toString();\n\t}\n\n\tvoid IntMap::InitializeInstanceFields()\n\t{\n\t\tm_hasFreeKey = false;\n\t\tm_freeValue = 0;\n\t\tm_threshold = 0;\n\t\tm_size = 0;\n\t\tm_mask = 0;\n\t\tm_mask2 = 0;\n\t}\n}\n<commit_msg>Delete IntMap.cpp<commit_after><|endoftext|>"} {"text":"<commit_before>#include \"elevated.hpp\"\n#include <sstream>\n#include <sys\/cygwin.h>\n#include \"winerror.hpp\"\n\nnamespace cygscript {\n\nbool ElevatedProcess::isAdmin() const {\n\tImpersonationToken it;\n\tAdminSID sid;\n\tACL acl(sid);\n\tAdminACL adminAcl(acl, sid);\n\treturn adminAcl.hasAccess(it);\n}\n\nHINSTANCE ElevatedProcess::startElevated(int argc, char* const argv[]) {\n\tchar winpath[MAX_PATH + 1];\n\tchar windir[MAX_PATH + 1];\n\tint i;\n\tstd::stringstream ss;\n\tfor (i = 1; i < argc; ++i) {\n\t\tss << argv[i] << \" \";\n\t}\n\tstd::string args = ss.str();\n\targs.pop_back();\n\tif (0 != cygwin_conv_path(\n\t\t\tCCP_POSIX_TO_WIN_A, argv[0], winpath, sizeof(winpath))) {\n\t\tthrow std::runtime_error(strerror(errno));\n\t}\n\tif (0 != cygwin_conv_path(\n\t\t\tCCP_POSIX_TO_WIN_A, \"\/bin\", windir, sizeof(windir))) {\n\t\tthrow std::runtime_error(strerror(errno));\n\t}\n\tHINSTANCE inst = ShellExecuteA(\n\t\tNULL, \"runas\", winpath, args.c_str(), windir, SW_SHOWNORMAL);\n\tif ((int)(intptr_t)inst <= 32) {\n\t\tTHROW_ERROR_CODE(\"Failed to start elevated process\",\n\t\t (int)(intptr_t)inst);\n\t}\n\treturn inst;\n}\n\nElevatedProcess::ImpersonationToken::ImpersonationToken() {\n\tHANDLE hToken;\n\tif (!OpenThreadToken(\n\t\t\tGetCurrentThread(), TOKEN_DUPLICATE | TOKEN_QUERY, TRUE, &hToken)) {\n\t\tif (!OpenProcessToken(\n\t\t\t\tGetCurrentProcess(), TOKEN_DUPLICATE | TOKEN_QUERY, &hToken)) {\n\t\t\tTHROW_LAST_ERROR(\"Failed to open process token\");\n\t\t}\n\t}\n\tBOOL ret = DuplicateToken(hToken, SecurityImpersonation, &_hToken);\n\tDWORD err = GetLastError();\n\tCloseHandle(hToken);\n\tif (!ret) {\n\t\tTHROW_ERROR_CODE(\"Failed to duplicate process token\", err);\n\t}\n}\n\nElevatedProcess::ImpersonationToken::~ImpersonationToken() {\n\tif (_hToken) {\n\t\tCloseHandle(_hToken);\n\t}\n}\n\nElevatedProcess::ImpersonationToken::operator HANDLE() const {\n\treturn _hToken;\n}\n\nElevatedProcess::AdminSID::AdminSID() {\n\tSID_IDENTIFIER_AUTHORITY sidAuthority = SECURITY_NT_AUTHORITY;\n\tif (!AllocateAndInitializeSid(\n\t\t\t&sidAuthority, 2, SECURITY_BUILTIN_DOMAIN_RID,\n\t\t\tDOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, 0, &_sid)) {\n\t\tTHROW_LAST_ERROR(\"Failed to initialize Admin SID\");\n\t}\n}\n\nElevatedProcess::AdminSID::~AdminSID() {\n\tif (_sid) {\n\t\tFreeSid(_sid);\n\t}\n}\n\nElevatedProcess::AdminSID::operator PSID() const {\n\treturn _sid;\n}\n\nElevatedProcess::ACL::ACL(PSID const& psid) {\n\t_size = sizeof(ACL) + sizeof(ACCESS_ALLOWED_ACE) +\n\t GetLengthSid(psid) - sizeof(DWORD);\n\t_acl = (PACL)LocalAlloc(LPTR, _size);\n\tif (!_acl) {\n\t\tTHROW_LAST_ERROR(\"Failed to allocate ACL\");\n\t}\n}\n\nElevatedProcess::ACL::~ACL() {\n\tif (_acl) {\n\t\tLocalFree(_acl);\n\t}\n}\n\nsize_t ElevatedProcess::ACL::size() const {\n\treturn _size;\n}\n\nElevatedProcess::ACL::operator PACL() const {\n\treturn _acl;\n}\n\nElevatedProcess::AdminACL::AdminACL(ACL const& acl, AdminSID const& sid) {\n\tif (!InitializeSecurityDescriptor(&_sd, SECURITY_DESCRIPTOR_REVISION)) {\n\t\tTHROW_LAST_ERROR(\"InitializeSecurityDescriptor\");\n\t}\n\tif (!InitializeAcl(acl, (DWORD)acl.size(), ACL_REVISION2)) {\n\t\tTHROW_LAST_ERROR(\"InitializeAcl\");\n\t}\n\tif (!AddAccessAllowedAce(\n\t\t\tacl, ACL_REVISION2, FILE_READ_ACCESS | FILE_WRITE_ACCESS, sid)) {\n\t\tTHROW_LAST_ERROR(\"AddAccessAllowedAce\");\n\t}\n\tif (!SetSecurityDescriptorDacl(&_sd, TRUE, acl, FALSE)) {\n\t\tTHROW_LAST_ERROR(\"SetSecurityDescriptorDacl\");\n\t}\n\tSetSecurityDescriptorGroup(&_sd, sid, FALSE);\n\tSetSecurityDescriptorOwner(&_sd, sid, FALSE);\n\tif (!IsValidSecurityDescriptor(&_sd)) {\n\t\tthrow std::runtime_error(\"Invalid security descriptor\");\n\t}\n}\n\nElevatedProcess::AdminACL::~AdminACL() {\n}\n\nbool ElevatedProcess::AdminACL::hasAccess(\n\tImpersonationToken const& token) const {\n\tGENERIC_MAPPING gm;\n\tgm.GenericRead = FILE_READ_ACCESS;\n\tgm.GenericWrite = FILE_WRITE_ACCESS;\n\tgm.GenericExecute = 0;\n\tgm.GenericAll = FILE_READ_ACCESS | FILE_WRITE_ACCESS;\n\tPRIVILEGE_SET ps;\n\tDWORD size = sizeof(ps);\n\tDWORD access;\n\tBOOL status;\n\tif (!AccessCheck(\n\t\t\t(const PSECURITY_DESCRIPTOR)&_sd,\n\t\t\ttoken, FILE_READ_ACCESS,\n\t\t\t&gm, &ps, &size, &access, &status)) {\n\t\tTHROW_LAST_ERROR(\"Failed to check access rights\");\n\t}\n\treturn status == TRUE ? true : false;\n}\n\n}\n<commit_msg>Fix process elevation path issue<commit_after>#include \"elevated.hpp\"\n#include <sstream>\n#include <sys\/cygwin.h>\n#include \"message.hpp\"\n#include \"winerror.hpp\"\n\nnamespace cygscript {\n\nbool ElevatedProcess::isAdmin() const {\n\tImpersonationToken it;\n\tAdminSID sid;\n\tACL acl(sid);\n\tAdminACL adminAcl(acl, sid);\n\treturn adminAcl.hasAccess(it);\n}\n\nHINSTANCE ElevatedProcess::startElevated(int argc, char* const argv[]) {\n\tchar winpath[MAX_PATH + 1];\n\tchar windir[MAX_PATH + 1];\n\tstd::stringstream ss;\n\tfor (int i = 1; i < argc; ++i) {\n\t\tss << argv[i] << \" \";\n\t}\n\tstd::string args = ss.str();\n\targs.pop_back();\n\tif (0 != cygwin_conv_path(\n\t\t\tCCP_POSIX_TO_WIN_A | CCP_RELATIVE, argv[0], winpath,\n\t\t\tsizeof(winpath))) {\n\t\tthrow std::runtime_error(strerror(errno));\n\t}\n\tif (0 != cygwin_conv_path(\n\t\t\tCCP_POSIX_TO_WIN_A, \"\/bin\", windir, sizeof(windir))) {\n\t\tthrow std::runtime_error(strerror(errno));\n\t}\n\tHINSTANCE inst = ShellExecuteA(\n\t\tNULL, \"runas\", winpath, args.c_str(), windir, SW_SHOWNORMAL);\n\tif ((int)(intptr_t)inst <= 32) {\n\t\tTHROW_ERROR_CODE(\"Failed to start elevated process\",\n\t\t (int)(intptr_t)inst);\n\t}\n\treturn inst;\n}\n\nElevatedProcess::ImpersonationToken::ImpersonationToken() {\n\tHANDLE hToken;\n\tif (!OpenThreadToken(\n\t\t\tGetCurrentThread(), TOKEN_DUPLICATE | TOKEN_QUERY, TRUE, &hToken)) {\n\t\tif (!OpenProcessToken(\n\t\t\t\tGetCurrentProcess(), TOKEN_DUPLICATE | TOKEN_QUERY, &hToken)) {\n\t\t\tTHROW_LAST_ERROR(\"Failed to open process token\");\n\t\t}\n\t}\n\tBOOL ret = DuplicateToken(hToken, SecurityImpersonation, &_hToken);\n\tDWORD err = GetLastError();\n\tCloseHandle(hToken);\n\tif (!ret) {\n\t\tTHROW_ERROR_CODE(\"Failed to duplicate process token\", err);\n\t}\n}\n\nElevatedProcess::ImpersonationToken::~ImpersonationToken() {\n\tif (_hToken) {\n\t\tCloseHandle(_hToken);\n\t}\n}\n\nElevatedProcess::ImpersonationToken::operator HANDLE() const {\n\treturn _hToken;\n}\n\nElevatedProcess::AdminSID::AdminSID() {\n\tSID_IDENTIFIER_AUTHORITY sidAuthority = SECURITY_NT_AUTHORITY;\n\tif (!AllocateAndInitializeSid(\n\t\t\t&sidAuthority, 2, SECURITY_BUILTIN_DOMAIN_RID,\n\t\t\tDOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, 0, &_sid)) {\n\t\tTHROW_LAST_ERROR(\"Failed to initialize Admin SID\");\n\t}\n}\n\nElevatedProcess::AdminSID::~AdminSID() {\n\tif (_sid) {\n\t\tFreeSid(_sid);\n\t}\n}\n\nElevatedProcess::AdminSID::operator PSID() const {\n\treturn _sid;\n}\n\nElevatedProcess::ACL::ACL(PSID const& psid) {\n\t_size = sizeof(ACL) + sizeof(ACCESS_ALLOWED_ACE) +\n\t GetLengthSid(psid) - sizeof(DWORD);\n\t_acl = (PACL)LocalAlloc(LPTR, _size);\n\tif (!_acl) {\n\t\tTHROW_LAST_ERROR(\"Failed to allocate ACL\");\n\t}\n}\n\nElevatedProcess::ACL::~ACL() {\n\tif (_acl) {\n\t\tLocalFree(_acl);\n\t}\n}\n\nsize_t ElevatedProcess::ACL::size() const {\n\treturn _size;\n}\n\nElevatedProcess::ACL::operator PACL() const {\n\treturn _acl;\n}\n\nElevatedProcess::AdminACL::AdminACL(ACL const& acl, AdminSID const& sid) {\n\tif (!InitializeSecurityDescriptor(&_sd, SECURITY_DESCRIPTOR_REVISION)) {\n\t\tTHROW_LAST_ERROR(\"InitializeSecurityDescriptor\");\n\t}\n\tif (!InitializeAcl(acl, (DWORD)acl.size(), ACL_REVISION2)) {\n\t\tTHROW_LAST_ERROR(\"InitializeAcl\");\n\t}\n\tif (!AddAccessAllowedAce(\n\t\t\tacl, ACL_REVISION2, FILE_READ_ACCESS | FILE_WRITE_ACCESS, sid)) {\n\t\tTHROW_LAST_ERROR(\"AddAccessAllowedAce\");\n\t}\n\tif (!SetSecurityDescriptorDacl(&_sd, TRUE, acl, FALSE)) {\n\t\tTHROW_LAST_ERROR(\"SetSecurityDescriptorDacl\");\n\t}\n\tSetSecurityDescriptorGroup(&_sd, sid, FALSE);\n\tSetSecurityDescriptorOwner(&_sd, sid, FALSE);\n\tif (!IsValidSecurityDescriptor(&_sd)) {\n\t\tthrow std::runtime_error(\"Invalid security descriptor\");\n\t}\n}\n\nElevatedProcess::AdminACL::~AdminACL() {\n}\n\nbool ElevatedProcess::AdminACL::hasAccess(\n\tImpersonationToken const& token) const {\n\tGENERIC_MAPPING gm;\n\tgm.GenericRead = FILE_READ_ACCESS;\n\tgm.GenericWrite = FILE_WRITE_ACCESS;\n\tgm.GenericExecute = 0;\n\tgm.GenericAll = FILE_READ_ACCESS | FILE_WRITE_ACCESS;\n\tPRIVILEGE_SET ps;\n\tDWORD size = sizeof(ps);\n\tDWORD access;\n\tBOOL status;\n\tif (!AccessCheck(\n\t\t\t(const PSECURITY_DESCRIPTOR)&_sd,\n\t\t\ttoken, FILE_READ_ACCESS,\n\t\t\t&gm, &ps, &size, &access, &status)) {\n\t\tTHROW_LAST_ERROR(\"Failed to check access rights\");\n\t}\n\treturn status == TRUE ? true : false;\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before>#include <vector>\n#include <string>\n#include <iostream>\n#include <fstream>\n#include <cassert>\n#include \"machine.hpp\"\n#ifdef WIN32\n#include <Windows.h>\n#include <conio.h>\n#endif\nusing namespace std;\nusing namespace dcpupp;\n\nstatic void printHelp()\n{\n\tcout << \"\" << endl;\n}\n\nstruct Options\n{\n\tunsigned sleepMs;\n\tunsigned videoAddress;\n\tunsigned updateInterval;\n\t\n\tOptions()\n\t\t: sleepMs(10)\n\t\t, videoAddress(32768) \/\/0x8000\n\t\t, updateInterval(5)\n\t{\n\t}\n};\n\nint main(int argc, char **argv)\n{\n\tconst vector<string> args(argv + 1, argv + argc);\n\t\n\tMachine::Memory program;\n\t\n\tstd::string programFileName;\n\tOptions options;\n\t\n\tfor (auto a = args.begin(); a != args.end(); ++a)\n\t{\n\t\tconst auto &arg = *a;\n\t\tassert(!arg.empty());\n\t\tif (arg[0] == '-' &&\n\t\t\targ.size() >= 2)\n\t\t{\n\t\t\tswitch (arg[1])\n\t\t\t{\n\t\t\tcase 's':\n\t\t\t\toptions.sleepMs = atoi(arg.c_str() + 2);\n\t\t\t\tbreak;\n\t\t\t\n\t\t\tcase 'v':\n\t\t\t\toptions.videoAddress = atoi(arg.c_str() + 2);\n\t\t\t\tbreak;\n\n\t\t\tcase 'u':\n\t\t\t\toptions.updateInterval = stoi(arg.c_str() + 2);\n\t\t\t\n\t\t\tdefault:\n\t\t\t\tcerr << \"Invalid option '\" << arg << \"'\";\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tprogramFileName = *a;\n\t\t}\n\t}\n\t\n\tif (programFileName.empty())\n\t{\n\t\tprintHelp();\n\t\treturn 0;\n\t}\n\t\n\t{\n\t\tstd::ifstream programFile(programFileName.c_str(), std::ios::binary);\n\t\tif (!programFile)\n\t\t{\n\t\t\tcerr << \"Could not open file '\" << programFileName << \"'\" << endl;\n\t\t\treturn 1;\n\t\t}\n\t\n\t\tprogram = readProgramFromFile(programFile);\n\t}\n\t\n\tMachine machine(std::move(program));\n\t\n\tstruct DebuggingContext\n\t{\n\t\tMachine &machine;\n\t\tconst Options &options;\n\t\tunsigned intervalCounter;\n#ifdef WIN32\n\t\tHANDLE console;\n#endif\n\t\t\n\t\texplicit DebuggingContext(Machine &machine, const Options &options)\n\t\t\t: machine(machine)\n\t\t\t, options(options)\n\t\t\t, intervalCounter(0)\n#ifdef WIN32\n\t\t\t, console(GetStdHandle(STD_OUTPUT_HANDLE))\n#endif\n\t\t{\n\t\t}\n\n\t\tvoid printInfo()\n\t\t{\n#ifdef WIN32\n\t\t\t{\n\t\t\t\tCOORD coord = {0, 0};\n\t\t\t\tDWORD count;\n\t\t\t\tCONSOLE_SCREEN_BUFFER_INFO csbi;\n\t\t\t\tGetConsoleScreenBufferInfo(console, &csbi);\n\t\t\t\tFillConsoleOutputCharacter(console, ' ',\n\t\t\t\t\tcsbi.dwSize.X * csbi.dwSize.Y,\n\t\t\t\t\tcoord, &count);\n\t\t\t\tSetConsoleCursorPosition(console, coord);\n\t\t\t}\n#else\n\t\t\twrite(1, \"\\E[H\\E[2J\", 7);\n#endif\n\n#ifdef WIN32\n\t\t\tSetConsoleTextAttribute(console,\n\t\t\t\tFOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_INTENSITY);\n#endif\n\t\t\tfor (size_t i = 0; i < 8; ++i)\n\t\t\t{\n\t\t\t\tprintf(\"%c: %04x, \", \"ABCXYZIJ\"[i], machine.registers[i]);\n\t\t\t}\n\t\t\tputs(\"\");\n\t\t\tprintf(\"SP: %04x, PC: %04x, O: %04x\\n\", machine.sp, machine.pc, machine.o);\n\n\t\t\tconst size_t width = 32, height = 12;\n\t\t\tfor (size_t y = 0; y < height; ++y)\n\t\t\t{\n\t\t\t\tfor (size_t x = 0; x < width; ++x)\n\t\t\t\t{\n\t\t\t\t\tconst size_t charAddress = options.videoAddress +\n\t\t\t\t\t\ty * width +\n\t\t\t\t\t\tx;\n\t\t\t\t\tconst Word c = machine.memory[charAddress];\n\n#ifdef WIN32\n\t\t\t\t\tSetConsoleTextAttribute(console, c >> 8);\n#endif\n\t\t\t\t\tfputc((char)c, stdout);\n\t\t\t\t\t\/\/write(1, &c, 1);\n\t\t\t\t}\n\n\t\t\t\tfputc('\\n', stdout);\n\t\t\t}\n\n\t\t\tfflush(stdout);\n\t\t\tif (options.sleepMs)\n\t\t\t{\n#ifdef WIN32\n\t\t\t\tSleep(options.sleepMs);\n#else\n\t\t\t\tusleep(options.sleepMs * 1000);\n#endif\n\t\t\t}\n\t\t}\n\t\t\n\t\tbool startInstruction()\n\t\t{\n\t\t\t++intervalCounter;\n\t\t\tif (intervalCounter == options.updateInterval)\n\t\t\t{\n\t\t\t\tprintInfo();\n\t\t\t\tintervalCounter = 0;\n\t\t\t}\n\t\t\treturn true;\n\t\t}\n\t};\n\t\n\tDebuggingContext context(machine, options);\n\tmachine.run(context);\n}\n\n<commit_msg>emulator output improved, timing corrected, console width and height options -w and -h<commit_after>#include <vector>\n#include <string>\n#include <iostream>\n#include <fstream>\n#include <cassert>\n#include \"machine.hpp\"\n#ifdef WIN32\n#include <Windows.h>\n#include <conio.h>\n#endif\nusing namespace std;\nusing namespace dcpupp;\n\nstatic void printHelp()\n{\n\tcout << \"\" << endl;\n}\n\nstruct Options\n{\n\tunsigned sleepMs;\n\tunsigned videoAddress;\n\tunsigned updateInterval;\n\tunsigned consoleWidth;\n\tunsigned consoleHeight;\n\t\n\tOptions()\n\t\t: sleepMs(10)\n\t\t, videoAddress(32768) \/\/0x8000\n\t\t, updateInterval(5)\n\t\t, consoleWidth(32)\n\t\t, consoleHeight(12)\n\t{\n\t}\n};\n\nint main(int argc, char **argv)\n{\n\tconst vector<string> args(argv + 1, argv + argc);\n\t\n\tMachine::Memory program;\n\t\n\tstd::string programFileName;\n\tOptions options;\n\t\n\tfor (auto a = args.begin(); a != args.end(); ++a)\n\t{\n\t\tconst auto &arg = *a;\n\t\tassert(!arg.empty());\n\t\tif (arg[0] == '-' &&\n\t\t\targ.size() >= 2)\n\t\t{\n\t\t\tswitch (arg[1])\n\t\t\t{\n\t\t\tcase 's':\n\t\t\t\toptions.sleepMs = atoi(arg.c_str() + 2);\n\t\t\t\tbreak;\n\t\t\t\n\t\t\tcase 'v':\n\t\t\t\toptions.videoAddress = atoi(arg.c_str() + 2);\n\t\t\t\tbreak;\n\n\t\t\tcase 'u':\n\t\t\t\toptions.updateInterval = stoi(arg.c_str() + 2);\n\t\t\t\tbreak;\n\n\t\t\tcase 'w':\n\t\t\t\toptions.consoleWidth = stoi(arg.c_str() + 2);\n\t\t\t\tbreak;\n\n\t\t\tcase 'h':\n\t\t\t\toptions.consoleHeight = stoi(arg.c_str() + 2);\n\t\t\t\tbreak;\n\t\t\t\n\t\t\tdefault:\n\t\t\t\tcerr << \"Invalid option '\" << arg << \"'\";\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tprogramFileName = *a;\n\t\t}\n\t}\n\t\n\tif (programFileName.empty())\n\t{\n\t\tprintHelp();\n\t\treturn 0;\n\t}\n\t\n\t{\n\t\tstd::ifstream programFile(programFileName.c_str(), std::ios::binary);\n\t\tif (!programFile)\n\t\t{\n\t\t\tcerr << \"Could not open file '\" << programFileName << \"'\" << endl;\n\t\t\treturn 1;\n\t\t}\n\t\n\t\tprogram = readProgramFromFile(programFile);\n\t}\n\t\n\tMachine machine(std::move(program));\n\t\n\tstruct DebuggingContext\n\t{\n\t\tMachine &machine;\n\t\tconst Options &options;\n\t\tunsigned intervalCounter;\n#ifdef WIN32\n\t\tHANDLE console;\n#endif\n\t\t\n\t\texplicit DebuggingContext(Machine &machine, const Options &options)\n\t\t\t: machine(machine)\n\t\t\t, options(options)\n\t\t\t, intervalCounter(0)\n#ifdef WIN32\n\t\t\t, console(GetStdHandle(STD_OUTPUT_HANDLE))\n#endif\n\t\t{\n\t\t}\n\n\t\tvoid setDefaultTextColors()\n\t\t{\n#ifdef WIN32\n\t\t\tSetConsoleTextAttribute(console,\n\t\t\t\tFOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_INTENSITY);\n#endif\n\t\t}\n\n\t\tvoid printVerticalBar()\n\t\t{\n\t\t\tfputc(' ', stdout);\n\t\t\tfor (size_t x = 0; x < options.consoleWidth; ++x)\n\t\t\t{\n\t\t\t\tfputc('-', stdout);\n\t\t\t}\n\t\t\tfputc('\\n', stdout);\n\t\t}\n\n\t\tvoid printInfo()\n\t\t{\n#ifdef WIN32\n\t\t\t{\n\t\t\t\tCOORD coord = {0, 0};\n\t\t\t\tDWORD count;\n\t\t\t\tCONSOLE_SCREEN_BUFFER_INFO csbi;\n\t\t\t\tGetConsoleScreenBufferInfo(console, &csbi);\n\t\t\t\tFillConsoleOutputCharacter(console, ' ',\n\t\t\t\t\tcsbi.dwSize.X * csbi.dwSize.Y,\n\t\t\t\t\tcoord, &count);\n\t\t\t\tSetConsoleCursorPosition(console, coord);\n\t\t\t}\n#else\n\t\t\twrite(1, \"\\E[H\\E[2J\", 7);\n#endif\n\n\t\t\tsetDefaultTextColors();\n\t\t\tprintf(\"A: %04x, B: %04x, C: %04x\\n\", machine.registers[0],\n\t\t\t\tmachine.registers[1], machine.registers[2]);\n\t\t\tprintf(\"X: %04x, Y: %04x, Z: %04x\\n\", machine.registers[3],\n\t\t\t\tmachine.registers[4], machine.registers[5]);\n\t\t\tprintf(\"I: %04x, J: %04x\\n\", machine.registers[6],\n\t\t\t\tmachine.registers[7]);\n\n\t\t\tputs(\"\");\n\t\t\tprintf(\"SP: %04x, PC: %04x, O: %04x\\n\", machine.sp, machine.pc, machine.o);\n\n\t\t\tprintVerticalBar();\n\t\t\tfor (size_t y = 0; y < options.consoleHeight; ++y)\n\t\t\t{\n\t\t\t\tfputc('|', stdout);\n\t\t\t\tfor (size_t x = 0; x < options.consoleWidth; ++x)\n\t\t\t\t{\n\t\t\t\t\tconst size_t charAddress = options.videoAddress +\n\t\t\t\t\t\ty * options.consoleWidth +\n\t\t\t\t\t\tx;\n\t\t\t\t\tconst Word c = machine.memory[charAddress];\n\n#ifdef WIN32\n\t\t\t\t\tSetConsoleTextAttribute(console, c >> 8);\n#endif\n\t\t\t\t\tfputc((char)c, stdout);\n\t\t\t\t}\n\t\t\t\tsetDefaultTextColors();\n\t\t\t\tfputc('|', stdout);\n\t\t\t\tfputc('\\n', stdout);\n\t\t\t}\n\t\t\tprintVerticalBar();\n\t\t\tfflush(stdout);\n\t\t}\n\t\t\n\t\tbool startInstruction()\n\t\t{\n\t\t\t++intervalCounter;\n\t\t\tif (intervalCounter == options.updateInterval)\n\t\t\t{\n\t\t\t\tprintInfo();\n\t\t\t\tintervalCounter = 0;\n\t\t\t}\n\n\t\t\tif (options.sleepMs)\n\t\t\t{\n#ifdef WIN32\n\t\t\t\tSleep(options.sleepMs);\n#else\n\t\t\t\tusleep(options.sleepMs * 1000);\n#endif\n\t\t\t}\n\t\t\treturn true;\n\t\t}\n\t};\n\t\n\tDebuggingContext context(machine, options);\n\tmachine.run(context);\n}\n\n<|endoftext|>"} {"text":"<commit_before>#include \"bitcrypto\/KeyGenerator.hpp\"\n\n\nnamespace BitCrypto{\n\n\nKeyGenerator::KeyGenerator() :\n _secretGenerator(getContext()),\n _pubKeyGenerator(getContext())\n{}\n\n\nKeyGenerator::KeyGenerator(const Secp256k1ContextPtr &context):\n Secp256k1Handler(context),\n _secretGenerator(getContext()),\n _pubKeyGenerator(getContext())\n{}\n\n\nKeyPair KeyGenerator::generate()\n{\n Secret secret = _secretGenerator.generate();\n return KeyPair(secret, _pubKeyGenerator.createFromSecret(secret));\n}\n\n\nKeyPair KeyGenerator::generate(const Data &entropy)\n{\n Secret secret = _secretGenerator.generate(entropy);\n return KeyPair(secret, _pubKeyGenerator.createFromSecret(secret));\n}\n\n\nKeyPair KeyGenerator::generate(const char *entropy)\n{\n Secret secret = _secretGenerator.generate(entropy);\n return KeyPair(secret, _pubKeyGenerator.createFromSecret(secret));\n}\n\n\n}\n<commit_msg>retrying to create key pair<commit_after>#include \"bitcrypto\/KeyGenerator.hpp\"\n\n\nnamespace BitCrypto{\n\n\nKeyGenerator::KeyGenerator() :\n _secretGenerator(getContext()),\n _pubKeyGenerator(getContext())\n{}\n\n\nKeyGenerator::KeyGenerator(const Secp256k1ContextPtr &context):\n Secp256k1Handler(context),\n _secretGenerator(getContext()),\n _pubKeyGenerator(getContext())\n{}\n\n\nKeyPair KeyGenerator::generate()\n{\n for(int i=0; i<100; i++)\n {\n try\n {\n Secret secret = _secretGenerator.generate();\n return KeyPair(secret, _pubKeyGenerator.createFromSecret(secret));\n }\n catch(const std::runtime_error &)\n {}\n }\n throw std::runtime_error(\"failed to generate keypair\");\n}\n\n\nKeyPair KeyGenerator::generate(const Data &entropy)\n{\n Secret secret = _secretGenerator.generate(entropy);\n return KeyPair(secret, _pubKeyGenerator.createFromSecret(secret));\n}\n\n\nKeyPair KeyGenerator::generate(const char *entropy)\n{\n Secret secret = _secretGenerator.generate(entropy);\n return KeyPair(secret, _pubKeyGenerator.createFromSecret(secret));\n}\n\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/*****************************************************************************\n *\n * This file is part of Mapnik (c++ mapping toolkit)\n *\n * Copyright (C) 2015 Artem Pavlenko\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n *\n *****************************************************************************\/\n\n\n\/\/ mapnik\n#include <mapnik\/json\/error_handler.hpp>\n#include <mapnik\/json\/feature_collection_grammar.hpp>\n\n\/\/ spirit::qi\n#include <boost\/spirit\/include\/qi.hpp>\n#include <boost\/spirit\/include\/phoenix.hpp>\n\nnamespace mapnik { namespace json {\n\ntemplate <typename Iterator, typename FeatureType, typename FeatureCallback, typename ErrorHandler>\nfeature_collection_grammar<Iterator,FeatureType, FeatureCallback,ErrorHandler>::feature_collection_grammar(mapnik::transcoder const& tr)\n : feature_collection_grammar::base_type(start,\"start\"),\n feature_g(tr)\n{\n qi::lit_type lit;\n qi::eps_type eps;\n qi::_1_type _1;\n qi::_2_type _2;\n qi::_3_type _3;\n qi::_4_type _4;\n qi::_a_type _a;\n qi::_r1_type _r1;\n qi::_r2_type _r2;\n qi::_r3_type _r3;\n using phoenix::construct;\n using phoenix::new_;\n using phoenix::val;\n using qi::on_error;\n using qi::fail;\n start = feature_collection(_r1, _r2, _r3)\n ;\n\n feature_collection = lit('{') >> (type | features(_r1, _r2, _r3) | feature_g.json_.key_value) % lit(',') >> lit('}')\n ;\n\n type = lit(\"\\\"type\\\"\") >> lit(':') >> lit(\"\\\"FeatureCollection\\\"\")\n ;\n\n features = lit(\"\\\"features\\\"\")\n >> lit(':')\n >> lit('[')\n >> -(feature(_r1, _r2, _r3) [_r2 +=1] % lit(','))\n >> lit(']')\n ;\n\n feature = eps[_a = phoenix::construct<mapnik::feature_ptr>(new_<mapnik::feature_impl>(_r1, _r2))]\n >> feature_g(*_a)[on_feature(_r3,_a)]\n ;\n\n start.name(\"start\");\n type.name(\"type\");\n features.name(\"features\");\n feature.name(\"feature\");\n feature_g.name(\"feature-grammar\");\n on_error<fail>(feature_collection, error_handler(_1, _2, _3, _4));\n}\n\n\ntemplate <typename Iterator, typename FeatureType, typename FeatureCallback, typename ErrorHandler>\nfeature_grammar_callback<Iterator,FeatureType, FeatureCallback,ErrorHandler>::feature_grammar_callback(mapnik::transcoder const& tr)\n : feature_grammar_callback::base_type(start,\"start\"),\n feature_g(tr)\n{\n qi::lit_type lit;\n qi::eps_type eps;\n qi::_1_type _1;\n qi::_2_type _2;\n qi::_3_type _3;\n qi::_4_type _4;\n qi::_a_type _a;\n qi::_r1_type _r1;\n qi::_r2_type _r2;\n qi::_r3_type _r3;\n using phoenix::construct;\n using phoenix::new_;\n using phoenix::val;\n using qi::on_error;\n using qi::fail;\n start = feature_from_geometry(_r1, _r2, _r3) | feature(_r1, _r2, _r3)\n ;\n\n feature = eps[_a = phoenix::construct<mapnik::feature_ptr>(new_<mapnik::feature_impl>(_r1, _r2))]\n >> feature_g(*_a)[on_feature(_r3,_a)]\n ;\n\n feature_from_geometry =\n eps[_a = phoenix::construct<mapnik::feature_ptr>(new_<mapnik::feature_impl>(_r1, _r2))]\n >> geometry_g[set_geometry(*_a, _1)] [on_feature(_r3, _a)]\n ;\n\n start.name(\"start\");\n feature.name(\"feature\");\n feature_from_geometry.name(\"feature-from-geometry\");\n feature_g.name(\"feature-grammar\");\n geometry_g.name(\"geometry-grammar\");\n on_error<fail>(feature, error_handler(_1, _2, _3, _4));\n}\n\n}}\n<commit_msg>GeoJSON - refactor FeatureCollection grammar to restore empty `features` condition (#3167)<commit_after>\/*****************************************************************************\n *\n * This file is part of Mapnik (c++ mapping toolkit)\n *\n * Copyright (C) 2015 Artem Pavlenko\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n *\n *****************************************************************************\/\n\n\n\/\/ mapnik\n#include <mapnik\/json\/error_handler.hpp>\n#include <mapnik\/json\/feature_collection_grammar.hpp>\n\n\/\/ spirit::qi\n#include <boost\/spirit\/include\/qi.hpp>\n#include <boost\/spirit\/include\/phoenix.hpp>\n\nnamespace mapnik { namespace json {\n\ntemplate <typename Iterator, typename FeatureType, typename FeatureCallback, typename ErrorHandler>\nfeature_collection_grammar<Iterator,FeatureType, FeatureCallback,ErrorHandler>::feature_collection_grammar(mapnik::transcoder const& tr)\n : feature_collection_grammar::base_type(start,\"start\"),\n feature_g(tr)\n{\n qi::lit_type lit;\n qi::eps_type eps;\n qi::_1_type _1;\n qi::_2_type _2;\n qi::_3_type _3;\n qi::_4_type _4;\n qi::_a_type _a;\n qi::_r1_type _r1;\n qi::_r2_type _r2;\n qi::_r3_type _r3;\n using phoenix::construct;\n using phoenix::new_;\n using phoenix::val;\n using qi::on_error;\n using qi::fail;\n start = feature_collection(_r1, _r2, _r3)\n ;\n\n feature_collection = lit('{') > (type | features(_r1, _r2, _r3) | feature_g.json_.key_value) % lit(',') > lit('}')\n ;\n\n type = lit(\"\\\"type\\\"\") > lit(':') > lit(\"\\\"FeatureCollection\\\"\")\n ;\n\n features = lit(\"\\\"features\\\"\")\n > lit(':') > lit('[') >\n ( lit(']') | ((feature(_r1, _r2, _r3) [_r2 +=1] % lit(',')) > lit(']')))\n ;\n\n feature = eps[_a = phoenix::construct<mapnik::feature_ptr>(new_<mapnik::feature_impl>(_r1, _r2))]\n > feature_g(*_a)[on_feature(_r3,_a)]\n ;\n\n start.name(\"start\");\n feature_collection.name(\"FeatureCollection\");\n type.name(\"type\");\n features.name(\"features\");\n feature.name(\"feature\");\n feature_g.name(\"feature-grammar\");\n on_error<fail>(feature_collection, error_handler(_1, _2, _3, _4));\n}\n\n\ntemplate <typename Iterator, typename FeatureType, typename FeatureCallback, typename ErrorHandler>\nfeature_grammar_callback<Iterator,FeatureType, FeatureCallback,ErrorHandler>::feature_grammar_callback(mapnik::transcoder const& tr)\n : feature_grammar_callback::base_type(start,\"start\"),\n feature_g(tr)\n{\n qi::lit_type lit;\n qi::eps_type eps;\n qi::_1_type _1;\n qi::_2_type _2;\n qi::_3_type _3;\n qi::_4_type _4;\n qi::_a_type _a;\n qi::_r1_type _r1;\n qi::_r2_type _r2;\n qi::_r3_type _r3;\n using phoenix::construct;\n using phoenix::new_;\n using phoenix::val;\n using qi::on_error;\n using qi::fail;\n start = feature_from_geometry(_r1, _r2, _r3) | feature(_r1, _r2, _r3)\n ;\n\n feature = eps[_a = phoenix::construct<mapnik::feature_ptr>(new_<mapnik::feature_impl>(_r1, _r2))]\n >> feature_g(*_a)[on_feature(_r3,_a)]\n ;\n\n feature_from_geometry =\n eps[_a = phoenix::construct<mapnik::feature_ptr>(new_<mapnik::feature_impl>(_r1, _r2))]\n >> geometry_g[set_geometry(*_a, _1)] [on_feature(_r3, _a)]\n ;\n\n start.name(\"start\");\n feature.name(\"feature\");\n feature_from_geometry.name(\"feature-from-geometry\");\n feature_g.name(\"feature-grammar\");\n geometry_g.name(\"geometry-grammar\");\n on_error<fail>(feature, error_handler(_1, _2, _3, _4));\n}\n\n}}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2015 Patrick Putnam\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n#ifndef CLOTHO_QTL_ALLELE_HPP_\n#define CLOTHO_QTL_ALLELE_HPP_\n\n#include \"clotho\/data_spaces\/allele_space\/neutral_allele.hpp\"\n#include \"clotho\/data_spaces\/growable2D.hpp\"\n#include \"clotho\/data_spaces\/trait_helper_of.hpp\"\n\n#include \"clotho\/utility\/state_object.hpp\"\n#include \"clotho\/utility\/log_helper.hpp\"\n\n#include <algorithm>\n\nnamespace clotho {\nnamespace genetics {\n\ntemplate < class PositionType, class WeightType >\nclass qtl_allele_vectorized : public neutral_allele_vectorized< PositionType >, public growable2D {\npublic:\n typedef neutral_allele_vectorized< PositionType > base_type;\n typedef qtl_allele_vectorized< PositionType, WeightType > self_type;\n\n typedef WeightType weight_type;\n typedef std::vector< WeightType > trait_type;\n\n typedef weight_type * weight_pointer;\n\n friend class clotho::utility::state_getter< self_type >;\n\n class weight_iterator {\n public:\n weight_iterator( weight_type * ptr, size_t size ) :\n m_ptr( ptr )\n , m_size( size ) {}\n\n weight_iterator( const weight_iterator & other ) :\n m_ptr( other.m_ptr )\n , m_size( other.m_size )\n {}\n\n bool hasNext() const {\n return (m_size > 0);\n }\n \n weight_type next() {\n assert( m_size > 0 );\n weight_type w = *m_ptr++;\n --m_size;\n\n return w;\n }\n\n virtual ~weight_iterator() {}\n protected:\n weight_type * m_ptr;\n size_t m_size;\n };\n\n typedef weight_iterator trait_iterator;\n\n qtl_allele_vectorized( size_t rows = 0, size_t columns = 0 ) :\n m_weights(NULL)\n , m_rows(0)\n , m_columns(0)\n , m_size(0)\n {\n this->resize(rows, columns);\n }\n \n trait_iterator getTraitIterator( size_t allele_idx ) const {\n assert( 0 <= allele_idx && allele_idx < m_rows );\n return trait_iterator( m_weights + allele_idx * m_columns, m_columns );\n }\n\n void updateTraitWeight( size_t allele_idx, size_t trait_idx, weight_type w ) {\n assert( 0 <= allele_idx && allele_idx < m_rows );\n assert( 0 <= trait_idx && trait_idx < m_columns );\n\n m_weights[ allele_idx * m_columns + trait_idx ] = w;\n }\n\n virtual size_t grow( size_t alleles ) {\n size_t t = trait_count();\n if( t == 0 ) {\n t += 1;\n }\n this->resize( alleles, t );\n return m_rows;\n }\n\n virtual size_t grow( size_t alleles, size_t traits ) {\n this->resize( alleles, traits );\n\n return m_rows;\n }\n\n trait_type makeEmptyTrait() {\n return trait_type( m_columns, 0.0);\n }\n\n\n size_t allele_count() const {\n return m_rows;\n }\n\n size_t trait_count() const {\n return m_columns;\n }\n\n size_t allocated_size() const {\n return m_size;\n }\n\n void inherit( self_type & parent ) {\n std::copy( parent.position_begin(), parent.position_end(), this->position_begin() );\n std::copy( parent.neutral_begin(), parent.neutral_end(), this->m_neutral.begin() );\n\n size_t t = trait_count();\n size_t ot = parent.trait_count();\n\n size_t a = allele_count();\n size_t oa = parent.allele_count();\n\n assert( oa <= a );\n\n size_t i = 0, T = ((t < ot) ? t : ot );\n while( i < T ) {\n memcpy( this->m_weights + i * a, parent.m_weights + i * oa, oa * sizeof( weight_type ) );\n ++i;\n }\n \n }\n\n weight_pointer begin_trait_weight( size_t idx ) {\n if(!( 0 <= idx && idx < allele_count()) ) {\n std::cerr << \"Trait out of range: \" << idx << \" [ \" << allele_count() << \" ]\" << std::endl;\n }\n assert( 0 <= idx && idx < allele_count() );\n\n return m_weights + idx * trait_count();\n }\n\n weight_pointer end_trait_weight( size_t idx ) {\n assert( 0 <= idx && idx < allele_count() );\n\n return m_weights + (idx + 1) * trait_count();\n }\n\n void push_back( self_type & other, size_t idx ) {\n size_t acount = allele_count();\n size_t tcount = trait_count();\n\n if( tcount < other.trait_count() ) {\n tcount = other.trait_count();\n }\n\n this->resize( acount + 1, tcount );\n\n this->setPositionAt( acount, other.getPositionAt(idx) );\n this->setNeutralAt( acount, other.getNeutralAt(idx) );\n\n weight_type * t = other.m_weights + idx * tcount;\n weight_type * s = this->m_weights + acount * tcount;\n\n memcpy( s, t, tcount * sizeof(weight_type) );\n }\n\n virtual ~qtl_allele_vectorized() {\n if( m_weights != NULL ) {\n delete [] m_weights;\n }\n }\n\nprotected:\n\n virtual void resize( size_t rows, size_t columns ) {\n base_type::resize( rows );\n\n rows = base_type::size();\n\n size_t new_size = rows * columns;\n\n assert( 0 <= new_size );\n\n if( m_size < new_size ) {\n \/\/ growing trait space\n weight_type * tmp = new weight_type[ new_size ];\n\n if( m_weights != NULL ) {\n memcpy( tmp, m_weights, m_size * sizeof( weight_type ) );\n delete [] m_weights;\n }\n\n m_weights = tmp;\n\n m_size = new_size;\n }\n\n m_columns = columns;\n m_rows = rows;\n }\n\n virtual void resize( size_t rows ) {\n this->resize( rows, m_columns );\n }\n\n weight_pointer m_weights;\n size_t m_rows, m_columns, m_size;\n};\n\ntemplate < class PositionType, class WeightType >\nstruct trait_helper_of< qtl_allele_vectorized< PositionType, WeightType > > {\n typedef qtl_allele_vectorized< PositionType, WeightType > allele_type;\n typedef typename allele_type::trait_type type;\n\n static type makeEmptyTrait( size_t N ) {\n type r = type( N, 0.0);\n return r;\n }\n\n static void resetTrait( type & trait ) {\n size_t i = 0;\n while( i < trait.size() ) {\n trait[i++] = 0.0;\n }\n }\n\n};\n\n} \/\/ namespace genetics\n} \/\/ namespace clotho\n\n\nnamespace clotho {\nnamespace utility {\n\ntemplate < class PositionType, class WeightType >\nstruct state_getter< clotho::genetics::qtl_allele_vectorized< PositionType, WeightType > > {\n typedef clotho::genetics::qtl_allele_vectorized< PositionType, WeightType > object_type;\n\n void operator()( boost::property_tree::ptree & s, object_type & obj ) {\n typedef typename object_type::trait_iterator iterator;\n typedef typename object_type::weight_type weight_type;\n\n size_t all_count = obj.allele_count();\n size_t i = 0;\n while( i < all_count ) {\n boost::property_tree::ptree all;\n all.put( \"position\", obj.getPositionAt(i) );\n all.put( \"neutral\", obj.getNeutralAt(i) );\n\n boost::property_tree::ptree t;\n iterator it = obj.getTraitIterator( i );\n while( it.hasNext() ) {\n weight_type w = it.next();\n clotho::utility::add_value_array( t, w );\n }\n all.put_child( \"trait\", t );\n\n s.push_back( std::make_pair(\"\", all ) );\n ++i;\n }\n\n }\n};\n\n} \/\/ namespace utility\n} \/\/ namespace clotho\n#endif \/\/ CLOTHO_QTL_ALLELE_HPP_\n<commit_msg>removed debugging code<commit_after>\/\/ Copyright 2015 Patrick Putnam\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n#ifndef CLOTHO_QTL_ALLELE_HPP_\n#define CLOTHO_QTL_ALLELE_HPP_\n\n#include \"clotho\/data_spaces\/allele_space\/neutral_allele.hpp\"\n#include \"clotho\/data_spaces\/growable2D.hpp\"\n#include \"clotho\/data_spaces\/trait_helper_of.hpp\"\n\n#include \"clotho\/utility\/state_object.hpp\"\n#include \"clotho\/utility\/log_helper.hpp\"\n\n#include <algorithm>\n\nnamespace clotho {\nnamespace genetics {\n\ntemplate < class PositionType, class WeightType >\nclass qtl_allele_vectorized : public neutral_allele_vectorized< PositionType >, public growable2D {\npublic:\n typedef neutral_allele_vectorized< PositionType > base_type;\n typedef qtl_allele_vectorized< PositionType, WeightType > self_type;\n\n typedef WeightType weight_type;\n typedef std::vector< WeightType > trait_type;\n\n typedef weight_type * weight_pointer;\n\n friend class clotho::utility::state_getter< self_type >;\n\n class weight_iterator {\n public:\n weight_iterator( weight_type * ptr, size_t size ) :\n m_ptr( ptr )\n , m_size( size ) {}\n\n weight_iterator( const weight_iterator & other ) :\n m_ptr( other.m_ptr )\n , m_size( other.m_size )\n {}\n\n bool hasNext() const {\n return (m_size > 0);\n }\n \n weight_type next() {\n assert( m_size > 0 );\n weight_type w = *m_ptr++;\n --m_size;\n\n return w;\n }\n\n virtual ~weight_iterator() {}\n protected:\n weight_type * m_ptr;\n size_t m_size;\n };\n\n typedef weight_iterator trait_iterator;\n\n qtl_allele_vectorized( size_t rows = 0, size_t columns = 0 ) :\n m_weights(NULL)\n , m_rows(0)\n , m_columns(0)\n , m_size(0)\n {\n this->resize(rows, columns);\n }\n \n trait_iterator getTraitIterator( size_t allele_idx ) const {\n assert( 0 <= allele_idx && allele_idx < m_rows );\n return trait_iterator( m_weights + allele_idx * m_columns, m_columns );\n }\n\n void updateTraitWeight( size_t allele_idx, size_t trait_idx, weight_type w ) {\n assert( 0 <= allele_idx && allele_idx < m_rows );\n assert( 0 <= trait_idx && trait_idx < m_columns );\n\n m_weights[ allele_idx * m_columns + trait_idx ] = w;\n }\n\n virtual size_t grow( size_t alleles ) {\n size_t t = trait_count();\n if( t == 0 ) {\n t += 1;\n }\n this->resize( alleles, t );\n return m_rows;\n }\n\n virtual size_t grow( size_t alleles, size_t traits ) {\n this->resize( alleles, traits );\n\n return m_rows;\n }\n\n trait_type makeEmptyTrait() {\n return trait_type( m_columns, 0.0);\n }\n\n\n size_t allele_count() const {\n return m_rows;\n }\n\n size_t trait_count() const {\n return m_columns;\n }\n\n size_t allocated_size() const {\n return m_size;\n }\n\n void inherit( self_type & parent ) {\n std::copy( parent.position_begin(), parent.position_end(), this->position_begin() );\n std::copy( parent.neutral_begin(), parent.neutral_end(), this->m_neutral.begin() );\n\n size_t t = trait_count();\n size_t ot = parent.trait_count();\n\n size_t a = allele_count();\n size_t oa = parent.allele_count();\n\n assert( oa <= a );\n\n size_t i = 0, T = ((t < ot) ? t : ot );\n while( i < T ) {\n memcpy( this->m_weights + i * a, parent.m_weights + i * oa, oa * sizeof( weight_type ) );\n ++i;\n }\n \n }\n\n weight_pointer begin_trait_weight( size_t idx ) {\n assert( 0 <= idx && idx < allele_count() );\n\n return m_weights + idx * trait_count();\n }\n\n weight_pointer end_trait_weight( size_t idx ) {\n assert( 0 <= idx && idx < allele_count() );\n\n return m_weights + (idx + 1) * trait_count();\n }\n\n void push_back( self_type & other, size_t idx ) {\n size_t acount = allele_count();\n size_t tcount = trait_count();\n\n if( tcount < other.trait_count() ) {\n tcount = other.trait_count();\n }\n\n this->resize( acount + 1, tcount );\n\n this->setPositionAt( acount, other.getPositionAt(idx) );\n this->setNeutralAt( acount, other.getNeutralAt(idx) );\n\n weight_type * t = other.m_weights + idx * tcount;\n weight_type * s = this->m_weights + acount * tcount;\n\n memcpy( s, t, tcount * sizeof(weight_type) );\n }\n\n virtual ~qtl_allele_vectorized() {\n if( m_weights != NULL ) {\n delete [] m_weights;\n }\n }\n\nprotected:\n\n virtual void resize( size_t rows, size_t columns ) {\n base_type::resize( rows );\n\n rows = base_type::size();\n\n size_t new_size = rows * columns;\n\n assert( 0 <= new_size );\n\n if( m_size < new_size ) {\n \/\/ growing trait space\n weight_type * tmp = new weight_type[ new_size ];\n\n if( m_weights != NULL ) {\n memcpy( tmp, m_weights, m_size * sizeof( weight_type ) );\n delete [] m_weights;\n }\n\n m_weights = tmp;\n\n m_size = new_size;\n }\n\n m_columns = columns;\n m_rows = rows;\n }\n\n virtual void resize( size_t rows ) {\n this->resize( rows, m_columns );\n }\n\n weight_pointer m_weights;\n size_t m_rows, m_columns, m_size;\n};\n\ntemplate < class PositionType, class WeightType >\nstruct trait_helper_of< qtl_allele_vectorized< PositionType, WeightType > > {\n typedef qtl_allele_vectorized< PositionType, WeightType > allele_type;\n typedef typename allele_type::trait_type type;\n\n static type makeEmptyTrait( size_t N ) {\n type r = type( N, 0.0);\n return r;\n }\n\n static void resetTrait( type & trait ) {\n size_t i = 0;\n while( i < trait.size() ) {\n trait[i++] = 0.0;\n }\n }\n\n};\n\n} \/\/ namespace genetics\n} \/\/ namespace clotho\n\n\nnamespace clotho {\nnamespace utility {\n\ntemplate < class PositionType, class WeightType >\nstruct state_getter< clotho::genetics::qtl_allele_vectorized< PositionType, WeightType > > {\n typedef clotho::genetics::qtl_allele_vectorized< PositionType, WeightType > object_type;\n\n void operator()( boost::property_tree::ptree & s, object_type & obj ) {\n typedef typename object_type::trait_iterator iterator;\n typedef typename object_type::weight_type weight_type;\n\n size_t all_count = obj.allele_count();\n size_t i = 0;\n while( i < all_count ) {\n boost::property_tree::ptree all;\n all.put( \"position\", obj.getPositionAt(i) );\n all.put( \"neutral\", obj.getNeutralAt(i) );\n\n boost::property_tree::ptree t;\n iterator it = obj.getTraitIterator( i );\n while( it.hasNext() ) {\n weight_type w = it.next();\n clotho::utility::add_value_array( t, w );\n }\n all.put_child( \"trait\", t );\n\n s.push_back( std::make_pair(\"\", all ) );\n ++i;\n }\n\n }\n};\n\n} \/\/ namespace utility\n} \/\/ namespace clotho\n#endif \/\/ CLOTHO_QTL_ALLELE_HPP_\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (C) 2018 ScyllaDB\n *\/\n\n\/*\n * This file is part of Scylla.\n *\n * Scylla is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * Scylla is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with Scylla. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n\n#include \"database.hh\"\n#include \"db\/system_keyspace.hh\"\n#include \"db\/timeout_clock.hh\"\n#include \"dht\/i_partitioner.hh\"\n#include \"flat_mutation_reader.hh\"\n#include \"mutation_fragment.hh\"\n#include \"mutation_reader.hh\"\n#include \"query-request.hh\"\n#include \"schema.hh\"\n#include \"tracing\/tracing.hh\"\n\n#include <boost\/range\/iterator_range.hpp>\n\n#include <iterator>\n#include <memory>\n\nnamespace db::view {\n\n\/\/ Allows a user to query the views_builds_in_progress system table\n\/\/ in terms of the scylla_views_builds_in_progress one, which is\n\/\/ a superset of the former. When querying, we don't have to adjust\n\/\/ the clustering key, but we have to adjust the requested regular\n\/\/ columns. When reading the results from the scylla_views_builds_in_progress\n\/\/ table, we adjust the clustering key (we shed the cpu_id column) and map\n\/\/ back the regular columns.\nclass build_progress_virtual_reader {\n database& _db;\n\n struct build_progress_reader : flat_mutation_reader::impl {\n column_id _scylla_next_token_col;\n column_id _scylla_generation_number_col;\n column_id _legacy_last_token_col;\n column_id _legacy_generation_number_col;\n const query::partition_slice& _legacy_slice;\n query::partition_slice _slice;\n flat_mutation_reader _underlying;\n\n build_progress_reader(\n schema_ptr legacy_schema,\n column_family& scylla_views_build_progress,\n const dht::partition_range& range,\n const query::partition_slice& slice,\n const io_priority_class& pc,\n tracing::trace_state_ptr trace_state,\n streamed_mutation::forwarding fwd,\n mutation_reader::forwarding fwd_mr)\n : flat_mutation_reader::impl(std::move(legacy_schema))\n , _scylla_next_token_col(scylla_views_build_progress.schema()->get_column_definition(\"next_token\")->id)\n , _scylla_generation_number_col(scylla_views_build_progress.schema()->get_column_definition(\"generation_number\")->id)\n , _legacy_last_token_col(_schema->get_column_definition(\"last_token\")->id)\n , _legacy_generation_number_col(_schema->get_column_definition(\"generation_number\")->id)\n , _legacy_slice(slice)\n , _slice(adjust_partition_slice())\n , _underlying(scylla_views_build_progress.make_reader(\n scylla_views_build_progress.schema(),\n range,\n slice,\n pc,\n std::move(trace_state),\n fwd,\n fwd_mr)) {\n }\n\n const schema& underlying_schema() const {\n return *_underlying.schema();\n }\n\n query::partition_slice adjust_partition_slice() {\n auto slice = _legacy_slice;\n query::column_id_vector adjusted_columns;\n for (auto col_id : slice.regular_columns) {\n if (col_id == _legacy_last_token_col) {\n adjusted_columns.push_back(_scylla_next_token_col);\n } else if (col_id == _legacy_generation_number_col) {\n adjusted_columns.push_back(_scylla_generation_number_col);\n }\n }\n slice.regular_columns = std::move(adjusted_columns);\n return slice;\n }\n\n clustering_key adjust_ckey(clustering_key& underlying_ck) {\n if (!underlying_ck.is_full(underlying_schema())) {\n return std::move(underlying_ck);\n }\n \/\/ Drop the cpu_id from the clustering key\n auto end = underlying_ck.begin(underlying_schema());\n std::advance(end, underlying_schema().clustering_key_size() - 1);\n auto r = boost::make_iterator_range(underlying_ck.begin(underlying_schema()), std::move(end));\n return clustering_key_prefix::from_exploded(r);\n }\n\n virtual future<> fill_buffer(db::timeout_clock::time_point timeout) override {\n return _underlying.fill_buffer(timeout).then([this] {\n _end_of_stream = _underlying.is_end_of_stream();\n while (!_underlying.is_buffer_empty()) {\n auto mf = _underlying.pop_mutation_fragment();\n if (mf.is_clustering_row()) {\n auto scylla_in_progress_row = std::move(mf).as_clustering_row();\n auto legacy_in_progress_row = row();\n \/\/ Drop the first_token from the regular columns\n scylla_in_progress_row.cells().for_each_cell([&, this] (column_id id, atomic_cell_or_collection& c) {\n if (id == _scylla_next_token_col) {\n legacy_in_progress_row.append_cell(_legacy_last_token_col, std::move(c));\n } else if (id == _scylla_generation_number_col) {\n legacy_in_progress_row.append_cell(_legacy_generation_number_col, std::move(c));\n }\n });\n mf = clustering_row(\n adjust_ckey(scylla_in_progress_row.key()),\n std::move(scylla_in_progress_row.tomb()),\n std::move(scylla_in_progress_row.marker()),\n std::move(legacy_in_progress_row));\n } else if (mf.is_range_tombstone()) {\n auto scylla_in_progress_rt = std::move(mf).as_range_tombstone();\n mf = range_tombstone(\n adjust_ckey(scylla_in_progress_rt.start),\n scylla_in_progress_rt.start_kind,\n adjust_ckey(scylla_in_progress_rt.end),\n scylla_in_progress_rt.end_kind,\n scylla_in_progress_rt.tomb);\n }\n push_mutation_fragment(std::move(mf));\n }\n });\n }\n\n virtual void next_partition() override {\n _end_of_stream = false;\n clear_buffer_to_next_partition();\n if (is_buffer_empty()) {\n _underlying.next_partition();\n }\n }\n\n virtual future<> fast_forward_to(const dht::partition_range& pr, db::timeout_clock::time_point timeout) override {\n clear_buffer();\n _end_of_stream = false;\n return _underlying.fast_forward_to(pr, timeout);\n }\n\n virtual future<> fast_forward_to(position_range range, db::timeout_clock::time_point timeout) override {\n forward_buffer_to(range.start());\n _end_of_stream = false;\n return _underlying.fast_forward_to(std::move(range), timeout);\n }\n };\n\npublic:\n build_progress_virtual_reader(database& db)\n : _db(db) {\n }\n\n flat_mutation_reader operator()(\n schema_ptr s,\n const dht::partition_range& range,\n const query::partition_slice& slice,\n const io_priority_class& pc,\n tracing::trace_state_ptr trace_state,\n streamed_mutation::forwarding fwd,\n mutation_reader::forwarding fwd_mr) {\n return flat_mutation_reader(std::make_unique<build_progress_reader>(\n std::move(s),\n _db.find_column_family(s->ks_name(), system_keyspace::v3::SCYLLA_VIEWS_BUILDS_IN_PROGRESS),\n range,\n slice,\n pc,\n std::move(trace_state),\n fwd,\n fwd_mr));\n }\n};\n\n}<commit_msg>view: ignore duplicated key entries in progress virtual reader<commit_after>\/*\n * Copyright (C) 2018 ScyllaDB\n *\/\n\n\/*\n * This file is part of Scylla.\n *\n * Scylla is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * Scylla is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with Scylla. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n\n#include \"database.hh\"\n#include \"db\/system_keyspace.hh\"\n#include \"db\/timeout_clock.hh\"\n#include \"dht\/i_partitioner.hh\"\n#include \"flat_mutation_reader.hh\"\n#include \"mutation_fragment.hh\"\n#include \"mutation_reader.hh\"\n#include \"query-request.hh\"\n#include \"schema.hh\"\n#include \"tracing\/tracing.hh\"\n\n#include <boost\/range\/iterator_range.hpp>\n\n#include <iterator>\n#include <memory>\n\nnamespace db::view {\n\n\/\/ Allows a user to query the views_builds_in_progress system table\n\/\/ in terms of the scylla_views_builds_in_progress one, which is\n\/\/ a superset of the former. When querying, we don't have to adjust\n\/\/ the clustering key, but we have to adjust the requested regular\n\/\/ columns. When reading the results from the scylla_views_builds_in_progress\n\/\/ table, we adjust the clustering key (we shed the cpu_id column) and map\n\/\/ back the regular columns.\n\/\/ Since mutation fragment consumers expect clustering_row fragments\n\/\/ not to be duplicated for given primary key, previous clustering key\n\/\/ is stored between mutation fragments. If the clustering key becomes\n\/\/ the same as the previous one (as a result of trimming cpu_id),\n\/\/ the duplicated fragment is ignored.\nclass build_progress_virtual_reader {\n database& _db;\n\n struct build_progress_reader : flat_mutation_reader::impl {\n column_id _scylla_next_token_col;\n column_id _scylla_generation_number_col;\n column_id _legacy_last_token_col;\n column_id _legacy_generation_number_col;\n const query::partition_slice& _legacy_slice;\n query::partition_slice _slice;\n flat_mutation_reader _underlying;\n std::optional<clustering_key> _previous_clustering_key;\n\n build_progress_reader(\n schema_ptr legacy_schema,\n column_family& scylla_views_build_progress,\n const dht::partition_range& range,\n const query::partition_slice& slice,\n const io_priority_class& pc,\n tracing::trace_state_ptr trace_state,\n streamed_mutation::forwarding fwd,\n mutation_reader::forwarding fwd_mr)\n : flat_mutation_reader::impl(std::move(legacy_schema))\n , _scylla_next_token_col(scylla_views_build_progress.schema()->get_column_definition(\"next_token\")->id)\n , _scylla_generation_number_col(scylla_views_build_progress.schema()->get_column_definition(\"generation_number\")->id)\n , _legacy_last_token_col(_schema->get_column_definition(\"last_token\")->id)\n , _legacy_generation_number_col(_schema->get_column_definition(\"generation_number\")->id)\n , _legacy_slice(slice)\n , _slice(adjust_partition_slice())\n , _underlying(scylla_views_build_progress.make_reader(\n scylla_views_build_progress.schema(),\n range,\n slice,\n pc,\n std::move(trace_state),\n fwd,\n fwd_mr))\n , _previous_clustering_key() {\n }\n\n const schema& underlying_schema() const {\n return *_underlying.schema();\n }\n\n query::partition_slice adjust_partition_slice() {\n auto slice = _legacy_slice;\n query::column_id_vector adjusted_columns;\n for (auto col_id : slice.regular_columns) {\n if (col_id == _legacy_last_token_col) {\n adjusted_columns.push_back(_scylla_next_token_col);\n } else if (col_id == _legacy_generation_number_col) {\n adjusted_columns.push_back(_scylla_generation_number_col);\n }\n }\n slice.regular_columns = std::move(adjusted_columns);\n return slice;\n }\n\n clustering_key adjust_ckey(clustering_key& underlying_ck) {\n if (!underlying_ck.is_full(underlying_schema())) {\n return std::move(underlying_ck);\n }\n \/\/ Drop the cpu_id from the clustering key\n auto end = underlying_ck.begin(underlying_schema());\n std::advance(end, underlying_schema().clustering_key_size() - 1);\n auto r = boost::make_iterator_range(underlying_ck.begin(underlying_schema()), std::move(end));\n return clustering_key_prefix::from_exploded(r);\n }\n\n virtual future<> fill_buffer(db::timeout_clock::time_point timeout) override {\n return _underlying.fill_buffer(timeout).then([this] {\n _end_of_stream = _underlying.is_end_of_stream();\n while (!_underlying.is_buffer_empty()) {\n auto mf = _underlying.pop_mutation_fragment();\n if (mf.is_clustering_row()) {\n auto scylla_in_progress_row = std::move(mf).as_clustering_row();\n auto legacy_in_progress_row = row();\n \/\/ Drop the first_token from the regular columns\n scylla_in_progress_row.cells().for_each_cell([&, this] (column_id id, atomic_cell_or_collection& c) {\n if (id == _scylla_next_token_col) {\n legacy_in_progress_row.append_cell(_legacy_last_token_col, std::move(c));\n } else if (id == _scylla_generation_number_col) {\n legacy_in_progress_row.append_cell(_legacy_generation_number_col, std::move(c));\n }\n });\n auto ck = adjust_ckey(scylla_in_progress_row.key());\n if (_previous_clustering_key && ck.equal(*_schema, *_previous_clustering_key)) {\n continue;\n }\n _previous_clustering_key = ck;\n mf = clustering_row(\n std::move(ck),\n std::move(scylla_in_progress_row.tomb()),\n std::move(scylla_in_progress_row.marker()),\n std::move(legacy_in_progress_row));\n } else if (mf.is_range_tombstone()) {\n auto scylla_in_progress_rt = std::move(mf).as_range_tombstone();\n mf = range_tombstone(\n adjust_ckey(scylla_in_progress_rt.start),\n scylla_in_progress_rt.start_kind,\n adjust_ckey(scylla_in_progress_rt.end),\n scylla_in_progress_rt.end_kind,\n scylla_in_progress_rt.tomb);\n } else if (mf.is_end_of_partition()) {\n _previous_clustering_key.reset();\n }\n push_mutation_fragment(std::move(mf));\n }\n });\n }\n\n virtual void next_partition() override {\n _end_of_stream = false;\n clear_buffer_to_next_partition();\n if (is_buffer_empty()) {\n _underlying.next_partition();\n }\n }\n\n virtual future<> fast_forward_to(const dht::partition_range& pr, db::timeout_clock::time_point timeout) override {\n clear_buffer();\n _end_of_stream = false;\n return _underlying.fast_forward_to(pr, timeout);\n }\n\n virtual future<> fast_forward_to(position_range range, db::timeout_clock::time_point timeout) override {\n forward_buffer_to(range.start());\n _end_of_stream = false;\n return _underlying.fast_forward_to(std::move(range), timeout);\n }\n };\n\npublic:\n build_progress_virtual_reader(database& db)\n : _db(db) {\n }\n\n flat_mutation_reader operator()(\n schema_ptr s,\n const dht::partition_range& range,\n const query::partition_slice& slice,\n const io_priority_class& pc,\n tracing::trace_state_ptr trace_state,\n streamed_mutation::forwarding fwd,\n mutation_reader::forwarding fwd_mr) {\n return flat_mutation_reader(std::make_unique<build_progress_reader>(\n std::move(s),\n _db.find_column_family(s->ks_name(), system_keyspace::v3::SCYLLA_VIEWS_BUILDS_IN_PROGRESS),\n range,\n slice,\n pc,\n std::move(trace_state),\n fwd,\n fwd_mr));\n }\n};\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/--------------------------------------------------------------------*- C++ -*-\n\/\/ CLING - the C++ LLVM-based InterpreterG :)\n\/\/ version: $Id$\n\/\/ author: Axel Naumann <axel@cern.ch>\n\/\/------------------------------------------------------------------------------\n\n#include \"ExecutionContext.h\"\n\n#include \"cling\/Interpreter\/StoredValueRef.h\"\n\n#include \"llvm\/Module.h\"\n#include \"llvm\/PassManager.h\"\n#include \"llvm\/Analysis\/Verifier.h\"\n#include \"llvm\/Assembly\/PrintModulePass.h\"\n#include \"llvm\/ExecutionEngine\/JIT.h\"\n#include \"llvm\/ExecutionEngine\/JITEventListener.h\"\n#include \"llvm\/Support\/raw_ostream.h\"\n#include \"llvm\/Support\/DynamicLibrary.h\"\n\nusing namespace cling;\n\nnamespace {\n class JITtedFunctionCollector : public llvm::JITEventListener {\n private:\n llvm::SmallVector<llvm::Function*, 24> m_functions;\n llvm::ExecutionEngine *m_engine;\n\n public:\n JITtedFunctionCollector(): m_functions(), m_engine(0) { }\n virtual ~JITtedFunctionCollector() { }\n\n virtual void NotifyFunctionEmitted(const llvm::Function& F, void *, size_t,\n const JITEventListener::EmittedFunctionDetails&) {\n m_functions.push_back(const_cast<llvm::Function *>(&F));\n }\n virtual void NotifyFreeingMachineCode(void* \/*OldPtr*\/) {}\n\n void UnregisterFunctionMapping(llvm::ExecutionEngine&);\n };\n}\n\n\nvoid JITtedFunctionCollector::UnregisterFunctionMapping(\n llvm::ExecutionEngine &engine)\n{\n for (llvm::SmallVectorImpl<llvm::Function *>::reverse_iterator\n it = m_functions.rbegin(), et = m_functions.rend();\n it != et; ++it) {\n llvm::Function *ff = *it;\n engine.freeMachineCodeForFunction(ff);\n engine.updateGlobalMapping(ff, 0);\n }\n m_functions.clear();\n}\n\n\nstd::set<std::string> ExecutionContext::m_unresolvedSymbols;\nstd::vector<ExecutionContext::LazyFunctionCreatorFunc_t>\n ExecutionContext::m_lazyFuncCreator;\n\nbool ExecutionContext::m_LazyFuncCreatorDiagsSuppressed = true;\n\nExecutionContext::ExecutionContext():\n m_engine(0),\n m_RunningStaticInits(false),\n m_CxaAtExitRemapped(false)\n{\n}\n\nvoid\nExecutionContext::InitializeBuilder(llvm::Module* m)\n{\n \/\/\n \/\/ Create an execution engine to use.\n \/\/\n \/\/ Note: Engine takes ownership of the module.\n assert(m && \"Module cannot be null\");\n\n llvm::EngineBuilder builder(m);\n builder.setOptLevel(llvm::CodeGenOpt::Less);\n std::string errMsg;\n builder.setErrorStr(&errMsg);\n builder.setEngineKind(llvm::EngineKind::JIT);\n builder.setAllocateGVsWithCode(false);\n m_engine = builder.create();\n assert(m_engine && \"Cannot initialize builder without module!\");\n\n \/\/m_engine->addModule(m); \/\/ Note: The engine takes ownership of the module.\n\n \/\/ install lazy function\n m_engine->InstallLazyFunctionCreator(NotifyLazyFunctionCreators);\n}\n\nExecutionContext::~ExecutionContext()\n{\n}\n\nvoid unresolvedSymbol()\n{\n \/\/ throw exception?\n llvm::errs() << \"ExecutionContext: calling unresolved symbol (should never happen)!\\n\";\n}\n\nvoid* ExecutionContext::HandleMissingFunction(const std::string& mangled_name)\n{\n \/\/ Not found in the map, add the symbol in the list of unresolved symbols\n if (m_unresolvedSymbols.insert(mangled_name).second) {\n llvm::errs() << \"ExecutionContext: use of undefined symbol '\"\n << mangled_name << \"'!\\n\";\n }\n\n \/\/ Avoid \"ISO C++ forbids casting between pointer-to-function and\n \/\/ pointer-to-object\":\n return (void*)reinterpret_cast<size_t>(unresolvedSymbol);\n}\n\nvoid*\nExecutionContext::NotifyLazyFunctionCreators(const std::string& mangled_name)\n{\n for (std::vector<LazyFunctionCreatorFunc_t>::iterator it\n = m_lazyFuncCreator.begin(), et = m_lazyFuncCreator.end();\n it != et; ++it) {\n void* ret = (void*)((LazyFunctionCreatorFunc_t)*it)(mangled_name);\n if (ret) \n return ret;\n }\n\n if (!m_LazyFuncCreatorDiagsSuppressed)\n return 0;\n\n return HandleMissingFunction(mangled_name);\n}\n\nvoid\nExecutionContext::executeFunction(llvm::StringRef funcname,\n const clang::ASTContext& Ctx,\n clang::QualType retType,\n StoredValueRef* returnValue)\n{\n \/\/ Call a function without arguments, or with an SRet argument, see SRet below\n\n if (!m_CxaAtExitRemapped) {\n \/\/ Rewire atexit:\n llvm::Function* atExit = m_engine->FindFunctionNamed(\"__cxa_atexit\");\n llvm::Function* clingAtExit = m_engine->FindFunctionNamed(\"cling_cxa_atexit\");\n if (atExit && clingAtExit) {\n void* clingAtExitAddr = m_engine->getPointerToFunction(clingAtExit);\n assert(clingAtExitAddr && \"cannot find cling_cxa_atexit\");\n m_engine->updateGlobalMapping(atExit, clingAtExitAddr);\n m_CxaAtExitRemapped = true;\n }\n }\n\n \/\/ We don't care whether something was unresolved before.\n m_unresolvedSymbols.clear();\n\n llvm::Function* f = m_engine->FindFunctionNamed(funcname.data());\n if (!f) {\n llvm::errs() << \"ExecutionContext::executeFunction: could not find function named \" << funcname << '\\n';\n return;\n }\n JITtedFunctionCollector listener;\n \/\/ register the listener\n m_engine->RegisterJITEventListener(&listener);\n m_engine->getPointerToFunction(f);\n \/\/ check if there is any unresolved symbol in the list\n if (!m_unresolvedSymbols.empty()) {\n for (std::set<std::string>::const_iterator i = m_unresolvedSymbols.begin(),\n e = m_unresolvedSymbols.end(); i != e; ++i) {\n llvm::errs() << \"ExecutionContext::executeFunction: symbol \\'\" << *i << \"\\' unresolved!\\n\";\n llvm::Function *ff = m_engine->FindFunctionNamed(i->c_str());\n assert(ff && \"cannot find function to free\");\n m_engine->updateGlobalMapping(ff, 0);\n m_engine->freeMachineCodeForFunction(ff);\n }\n m_unresolvedSymbols.clear();\n \/\/ cleanup functions\n listener.UnregisterFunctionMapping(*m_engine);\n m_engine->UnregisterJITEventListener(&listener);\n return;\n }\n \/\/ cleanup list and unregister our listener\n m_engine->UnregisterJITEventListener(&listener);\n\n std::vector<llvm::GenericValue> args;\n bool wantReturn = (returnValue);\n StoredValueRef aggregateRet;\n\n if (f->hasStructRetAttr()) {\n \/\/ Function expects to receive the storage for the returned aggregate as\n \/\/ first argument. Allocate returnValue:\n aggregateRet = StoredValueRef::allocate(Ctx, retType);\n if (returnValue) {\n *returnValue = aggregateRet;\n } else {\n returnValue = &aggregateRet;\n }\n args.push_back(returnValue->get().value);\n \/\/ will get set as arg0, must not assign.\n wantReturn = false;\n }\n\n if (wantReturn) {\n llvm::GenericValue gvRet = m_engine->runFunction(f, args);\n \/\/ rescue the ret value (which might be aggregate) from the stack\n *returnValue = StoredValueRef::bitwiseCopy(Ctx, Value(gvRet, retType));\n } else {\n m_engine->runFunction(f, args);\n }\n\n m_engine->freeMachineCodeForFunction(f);\n}\n\n\nvoid\nExecutionContext::runStaticInitializersOnce(llvm::Module* m) {\n assert(m && \"Module must not be null\");\n\n if (!m_engine)\n InitializeBuilder(m);\n\n assert(m_engine && \"Code generation did not create an engine!\");\n\n if (!m_RunningStaticInits) {\n m_RunningStaticInits = true;\n\n llvm::GlobalVariable* gctors\n = m->getGlobalVariable(\"llvm.global_ctors\", true);\n if (gctors) {\n m_engine->runStaticConstructorsDestructors(false);\n gctors->eraseFromParent();\n }\n\n m_RunningStaticInits = false;\n }\n}\n\nvoid\nExecutionContext::runStaticDestructorsOnce(llvm::Module* m) {\n assert(m && \"Module must not be null\");\n assert(m_engine && \"Code generation did not create an engine!\");\n\n llvm::GlobalVariable* gdtors\n = m->getGlobalVariable(\"llvm.global_dtors\", true);\n if (gdtors) {\n m_engine->runStaticConstructorsDestructors(true);\n }\n\n}\n\nint\nExecutionContext::verifyModule(llvm::Module* m)\n{\n \/\/\n \/\/ Verify generated module.\n \/\/\n bool mod_has_errs = llvm::verifyModule(*m, llvm::PrintMessageAction);\n if (mod_has_errs) {\n return 1;\n }\n return 0;\n}\n\nvoid\nExecutionContext::printModule(llvm::Module* m)\n{\n \/\/\n \/\/ Print module LLVM code in human-readable form.\n \/\/\n llvm::PassManager PM;\n PM.add(llvm::createPrintModulePass(&llvm::outs()));\n PM.run(*m);\n}\n\nvoid\nExecutionContext::installLazyFunctionCreator(LazyFunctionCreatorFunc_t fp)\n{\n m_lazyFuncCreator.push_back(fp);\n}\n\nbool ExecutionContext::addSymbol(const char* symbolName, void* symbolAddress) {\n\n void* actualAddress\n = llvm::sys::DynamicLibrary::SearchForAddressOfSymbol(symbolName);\n if (actualAddress)\n return false;\n\n llvm::sys::DynamicLibrary::AddSymbol(symbolName, symbolAddress);\n return true;\n}\n\nvoid* ExecutionContext::getAddressOfGlobal(llvm::Module* m,\n const char* symbolName,\n bool* fromJIT \/*=0*\/) const {\n \/\/ Return a symbol's address, and whether it was jitted.\n void* address\n = llvm::sys::DynamicLibrary::SearchForAddressOfSymbol(symbolName);\n if (address) {\n if (fromJIT) *fromJIT = false;\n } else {\n if (fromJIT) *fromJIT = true;\n llvm::GlobalVariable* gvar\n = m->getGlobalVariable(symbolName, true);\n if (!gvar)\n return 0;\n\n address = m_engine->getPointerToGlobal(gvar);\n }\n return address;\n }\n<commit_msg>Flip the flag, because of the name change.<commit_after>\/\/--------------------------------------------------------------------*- C++ -*-\n\/\/ CLING - the C++ LLVM-based InterpreterG :)\n\/\/ version: $Id$\n\/\/ author: Axel Naumann <axel@cern.ch>\n\/\/------------------------------------------------------------------------------\n\n#include \"ExecutionContext.h\"\n\n#include \"cling\/Interpreter\/StoredValueRef.h\"\n\n#include \"llvm\/Module.h\"\n#include \"llvm\/PassManager.h\"\n#include \"llvm\/Analysis\/Verifier.h\"\n#include \"llvm\/Assembly\/PrintModulePass.h\"\n#include \"llvm\/ExecutionEngine\/JIT.h\"\n#include \"llvm\/ExecutionEngine\/JITEventListener.h\"\n#include \"llvm\/Support\/raw_ostream.h\"\n#include \"llvm\/Support\/DynamicLibrary.h\"\n\nusing namespace cling;\n\nnamespace {\n class JITtedFunctionCollector : public llvm::JITEventListener {\n private:\n llvm::SmallVector<llvm::Function*, 24> m_functions;\n llvm::ExecutionEngine *m_engine;\n\n public:\n JITtedFunctionCollector(): m_functions(), m_engine(0) { }\n virtual ~JITtedFunctionCollector() { }\n\n virtual void NotifyFunctionEmitted(const llvm::Function& F, void *, size_t,\n const JITEventListener::EmittedFunctionDetails&) {\n m_functions.push_back(const_cast<llvm::Function *>(&F));\n }\n virtual void NotifyFreeingMachineCode(void* \/*OldPtr*\/) {}\n\n void UnregisterFunctionMapping(llvm::ExecutionEngine&);\n };\n}\n\n\nvoid JITtedFunctionCollector::UnregisterFunctionMapping(\n llvm::ExecutionEngine &engine)\n{\n for (llvm::SmallVectorImpl<llvm::Function *>::reverse_iterator\n it = m_functions.rbegin(), et = m_functions.rend();\n it != et; ++it) {\n llvm::Function *ff = *it;\n engine.freeMachineCodeForFunction(ff);\n engine.updateGlobalMapping(ff, 0);\n }\n m_functions.clear();\n}\n\n\nstd::set<std::string> ExecutionContext::m_unresolvedSymbols;\nstd::vector<ExecutionContext::LazyFunctionCreatorFunc_t>\n ExecutionContext::m_lazyFuncCreator;\n\nbool ExecutionContext::m_LazyFuncCreatorDiagsSuppressed = true;\n\nExecutionContext::ExecutionContext():\n m_engine(0),\n m_RunningStaticInits(false),\n m_CxaAtExitRemapped(false)\n{\n}\n\nvoid\nExecutionContext::InitializeBuilder(llvm::Module* m)\n{\n \/\/\n \/\/ Create an execution engine to use.\n \/\/\n \/\/ Note: Engine takes ownership of the module.\n assert(m && \"Module cannot be null\");\n\n llvm::EngineBuilder builder(m);\n builder.setOptLevel(llvm::CodeGenOpt::Less);\n std::string errMsg;\n builder.setErrorStr(&errMsg);\n builder.setEngineKind(llvm::EngineKind::JIT);\n builder.setAllocateGVsWithCode(false);\n m_engine = builder.create();\n assert(m_engine && \"Cannot initialize builder without module!\");\n\n \/\/m_engine->addModule(m); \/\/ Note: The engine takes ownership of the module.\n\n \/\/ install lazy function\n m_engine->InstallLazyFunctionCreator(NotifyLazyFunctionCreators);\n}\n\nExecutionContext::~ExecutionContext()\n{\n}\n\nvoid unresolvedSymbol()\n{\n \/\/ throw exception?\n llvm::errs() << \"ExecutionContext: calling unresolved symbol (should never happen)!\\n\";\n}\n\nvoid* ExecutionContext::HandleMissingFunction(const std::string& mangled_name)\n{\n \/\/ Not found in the map, add the symbol in the list of unresolved symbols\n if (m_unresolvedSymbols.insert(mangled_name).second) {\n llvm::errs() << \"ExecutionContext: use of undefined symbol '\"\n << mangled_name << \"'!\\n\";\n }\n\n \/\/ Avoid \"ISO C++ forbids casting between pointer-to-function and\n \/\/ pointer-to-object\":\n return (void*)reinterpret_cast<size_t>(unresolvedSymbol);\n}\n\nvoid*\nExecutionContext::NotifyLazyFunctionCreators(const std::string& mangled_name)\n{\n for (std::vector<LazyFunctionCreatorFunc_t>::iterator it\n = m_lazyFuncCreator.begin(), et = m_lazyFuncCreator.end();\n it != et; ++it) {\n void* ret = (void*)((LazyFunctionCreatorFunc_t)*it)(mangled_name);\n if (ret) \n return ret;\n }\n\n if (m_LazyFuncCreatorDiagsSuppressed)\n return 0;\n\n return HandleMissingFunction(mangled_name);\n}\n\nvoid\nExecutionContext::executeFunction(llvm::StringRef funcname,\n const clang::ASTContext& Ctx,\n clang::QualType retType,\n StoredValueRef* returnValue)\n{\n \/\/ Call a function without arguments, or with an SRet argument, see SRet below\n\n if (!m_CxaAtExitRemapped) {\n \/\/ Rewire atexit:\n llvm::Function* atExit = m_engine->FindFunctionNamed(\"__cxa_atexit\");\n llvm::Function* clingAtExit = m_engine->FindFunctionNamed(\"cling_cxa_atexit\");\n if (atExit && clingAtExit) {\n void* clingAtExitAddr = m_engine->getPointerToFunction(clingAtExit);\n assert(clingAtExitAddr && \"cannot find cling_cxa_atexit\");\n m_engine->updateGlobalMapping(atExit, clingAtExitAddr);\n m_CxaAtExitRemapped = true;\n }\n }\n\n \/\/ We don't care whether something was unresolved before.\n m_unresolvedSymbols.clear();\n\n llvm::Function* f = m_engine->FindFunctionNamed(funcname.data());\n if (!f) {\n llvm::errs() << \"ExecutionContext::executeFunction: could not find function named \" << funcname << '\\n';\n return;\n }\n JITtedFunctionCollector listener;\n \/\/ register the listener\n m_engine->RegisterJITEventListener(&listener);\n m_engine->getPointerToFunction(f);\n \/\/ check if there is any unresolved symbol in the list\n if (!m_unresolvedSymbols.empty()) {\n for (std::set<std::string>::const_iterator i = m_unresolvedSymbols.begin(),\n e = m_unresolvedSymbols.end(); i != e; ++i) {\n llvm::errs() << \"ExecutionContext::executeFunction: symbol \\'\" << *i << \"\\' unresolved!\\n\";\n llvm::Function *ff = m_engine->FindFunctionNamed(i->c_str());\n assert(ff && \"cannot find function to free\");\n m_engine->updateGlobalMapping(ff, 0);\n m_engine->freeMachineCodeForFunction(ff);\n }\n m_unresolvedSymbols.clear();\n \/\/ cleanup functions\n listener.UnregisterFunctionMapping(*m_engine);\n m_engine->UnregisterJITEventListener(&listener);\n return;\n }\n \/\/ cleanup list and unregister our listener\n m_engine->UnregisterJITEventListener(&listener);\n\n std::vector<llvm::GenericValue> args;\n bool wantReturn = (returnValue);\n StoredValueRef aggregateRet;\n\n if (f->hasStructRetAttr()) {\n \/\/ Function expects to receive the storage for the returned aggregate as\n \/\/ first argument. Allocate returnValue:\n aggregateRet = StoredValueRef::allocate(Ctx, retType);\n if (returnValue) {\n *returnValue = aggregateRet;\n } else {\n returnValue = &aggregateRet;\n }\n args.push_back(returnValue->get().value);\n \/\/ will get set as arg0, must not assign.\n wantReturn = false;\n }\n\n if (wantReturn) {\n llvm::GenericValue gvRet = m_engine->runFunction(f, args);\n \/\/ rescue the ret value (which might be aggregate) from the stack\n *returnValue = StoredValueRef::bitwiseCopy(Ctx, Value(gvRet, retType));\n } else {\n m_engine->runFunction(f, args);\n }\n\n m_engine->freeMachineCodeForFunction(f);\n}\n\n\nvoid\nExecutionContext::runStaticInitializersOnce(llvm::Module* m) {\n assert(m && \"Module must not be null\");\n\n if (!m_engine)\n InitializeBuilder(m);\n\n assert(m_engine && \"Code generation did not create an engine!\");\n\n if (!m_RunningStaticInits) {\n m_RunningStaticInits = true;\n\n llvm::GlobalVariable* gctors\n = m->getGlobalVariable(\"llvm.global_ctors\", true);\n if (gctors) {\n m_engine->runStaticConstructorsDestructors(false);\n gctors->eraseFromParent();\n }\n\n m_RunningStaticInits = false;\n }\n}\n\nvoid\nExecutionContext::runStaticDestructorsOnce(llvm::Module* m) {\n assert(m && \"Module must not be null\");\n assert(m_engine && \"Code generation did not create an engine!\");\n\n llvm::GlobalVariable* gdtors\n = m->getGlobalVariable(\"llvm.global_dtors\", true);\n if (gdtors) {\n m_engine->runStaticConstructorsDestructors(true);\n }\n\n}\n\nint\nExecutionContext::verifyModule(llvm::Module* m)\n{\n \/\/\n \/\/ Verify generated module.\n \/\/\n bool mod_has_errs = llvm::verifyModule(*m, llvm::PrintMessageAction);\n if (mod_has_errs) {\n return 1;\n }\n return 0;\n}\n\nvoid\nExecutionContext::printModule(llvm::Module* m)\n{\n \/\/\n \/\/ Print module LLVM code in human-readable form.\n \/\/\n llvm::PassManager PM;\n PM.add(llvm::createPrintModulePass(&llvm::outs()));\n PM.run(*m);\n}\n\nvoid\nExecutionContext::installLazyFunctionCreator(LazyFunctionCreatorFunc_t fp)\n{\n m_lazyFuncCreator.push_back(fp);\n}\n\nbool ExecutionContext::addSymbol(const char* symbolName, void* symbolAddress) {\n\n void* actualAddress\n = llvm::sys::DynamicLibrary::SearchForAddressOfSymbol(symbolName);\n if (actualAddress)\n return false;\n\n llvm::sys::DynamicLibrary::AddSymbol(symbolName, symbolAddress);\n return true;\n}\n\nvoid* ExecutionContext::getAddressOfGlobal(llvm::Module* m,\n const char* symbolName,\n bool* fromJIT \/*=0*\/) const {\n \/\/ Return a symbol's address, and whether it was jitted.\n void* address\n = llvm::sys::DynamicLibrary::SearchForAddressOfSymbol(symbolName);\n if (address) {\n if (fromJIT) *fromJIT = false;\n } else {\n if (fromJIT) *fromJIT = true;\n llvm::GlobalVariable* gvar\n = m->getGlobalVariable(symbolName, true);\n if (!gvar)\n return 0;\n\n address = m_engine->getPointerToGlobal(gvar);\n }\n return address;\n }\n<|endoftext|>"} {"text":"<commit_before>\/\/===- FileOutputBuffer.cpp - File Output Buffer ----------------*- C++ -*-===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ Utility for creating a in-memory buffer that will be written to a file.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/Support\/FileOutputBuffer.h\"\n#include \"llvm\/ADT\/STLExtras.h\"\n#include \"llvm\/ADT\/SmallString.h\"\n#include \"llvm\/Support\/Errc.h\"\n#include \"llvm\/Support\/Memory.h\"\n#include \"llvm\/Support\/Path.h\"\n#include \"llvm\/Support\/Signals.h\"\n#include <system_error>\n\n#if !defined(_MSC_VER) && !defined(__MINGW32__)\n#include <unistd.h>\n#else\n#include <io.h>\n#endif\n\nusing namespace llvm;\nusing namespace llvm::sys;\n\n\/\/ A FileOutputBuffer which creates a temporary file in the same directory\n\/\/ as the final output file. The final output file is atomically replaced\n\/\/ with the temporary file on commit().\nclass OnDiskBuffer : public FileOutputBuffer {\npublic:\n OnDiskBuffer(StringRef Path, StringRef TempPath,\n std::unique_ptr<fs::mapped_file_region> Buf)\n : FileOutputBuffer(Path), Buffer(std::move(Buf)), TempPath(TempPath) {}\n\n static Expected<std::unique_ptr<OnDiskBuffer>>\n create(StringRef Path, size_t Size, unsigned Mode);\n\n uint8_t *getBufferStart() const override { return (uint8_t *)Buffer->data(); }\n\n uint8_t *getBufferEnd() const override {\n return (uint8_t *)Buffer->data() + Buffer->size();\n }\n\n size_t getBufferSize() const override { return Buffer->size(); }\n\n Error commit() override {\n \/\/ Unmap buffer, letting OS flush dirty pages to file on disk.\n Buffer.reset();\n\n \/\/ Atomically replace the existing file with the new one.\n auto EC = fs::rename(TempPath, FinalPath);\n sys::DontRemoveFileOnSignal(TempPath);\n return errorCodeToError(EC);\n }\n\n ~OnDiskBuffer() override {\n \/\/ Close the mapping before deleting the temp file, so that the removal\n \/\/ succeeds.\n Buffer.reset();\n fs::remove(TempPath);\n }\n\nprivate:\n std::unique_ptr<fs::mapped_file_region> Buffer;\n std::string TempPath;\n};\n\n\/\/ A FileOutputBuffer which keeps data in memory and writes to the final\n\/\/ output file on commit(). This is used only when we cannot use OnDiskBuffer.\nclass InMemoryBuffer : public FileOutputBuffer {\npublic:\n InMemoryBuffer(StringRef Path, MemoryBlock Buf, unsigned Mode)\n : FileOutputBuffer(Path), Buffer(Buf), Mode(Mode) {}\n\n static Expected<std::unique_ptr<InMemoryBuffer>>\n create(StringRef Path, size_t Size, unsigned Mode) {\n std::error_code EC;\n MemoryBlock MB = Memory::allocateMappedMemory(\n Size, nullptr, sys::Memory::MF_READ | sys::Memory::MF_WRITE, EC);\n if (EC)\n return errorCodeToError(EC);\n return llvm::make_unique<InMemoryBuffer>(Path, MB, Mode);\n }\n\n uint8_t *getBufferStart() const override { return (uint8_t *)Buffer.base(); }\n\n uint8_t *getBufferEnd() const override {\n return (uint8_t *)Buffer.base() + Buffer.size();\n }\n\n size_t getBufferSize() const override { return Buffer.size(); }\n\n Error commit() override {\n int FD;\n std::error_code EC;\n if (auto EC = openFileForWrite(FinalPath, FD, fs::F_None, Mode))\n return errorCodeToError(EC);\n raw_fd_ostream OS(FD, \/*shouldClose=*\/true, \/*unbuffered=*\/true);\n OS << StringRef((const char *)Buffer.base(), Buffer.size());\n return Error::success();\n }\n\nprivate:\n OwningMemoryBlock Buffer;\n unsigned Mode;\n};\n\nExpected<std::unique_ptr<OnDiskBuffer>>\nOnDiskBuffer::create(StringRef Path, size_t Size, unsigned Mode) {\n \/\/ Create new file in same directory but with random name.\n SmallString<128> TempPath;\n int FD;\n if (auto EC = fs::createUniqueFile(Path + \".tmp%%%%%%%\", FD, TempPath, Mode))\n return errorCodeToError(EC);\n\n sys::RemoveFileOnSignal(TempPath);\n\n#ifndef LLVM_ON_WIN32\n \/\/ On Windows, CreateFileMapping (the mmap function on Windows)\n \/\/ automatically extends the underlying file. We don't need to\n \/\/ extend the file beforehand. _chsize (ftruncate on Windows) is\n \/\/ pretty slow just like it writes specified amount of bytes,\n \/\/ so we should avoid calling that function.\n if (auto EC = fs::resize_file(FD, Size))\n return errorCodeToError(EC);\n#endif\n\n \/\/ Mmap it.\n std::error_code EC;\n auto MappedFile = llvm::make_unique<fs::mapped_file_region>(\n FD, fs::mapped_file_region::readwrite, Size, 0, EC);\n close(FD);\n if (EC)\n return errorCodeToError(EC);\n return llvm::make_unique<OnDiskBuffer>(Path, TempPath, std::move(MappedFile));\n}\n\n\/\/ Create an instance of FileOutputBuffer.\nExpected<std::unique_ptr<FileOutputBuffer>>\nFileOutputBuffer::create(StringRef Path, size_t Size, unsigned Flags) {\n unsigned Mode = fs::all_read | fs::all_write;\n if (Flags & F_executable)\n Mode |= fs::all_exe;\n\n fs::file_status Stat;\n fs::status(Path, Stat);\n\n \/\/ Usually, we want to create OnDiskBuffer to create a temporary file in\n \/\/ the same directory as the destination file and atomically replaces it\n \/\/ by rename(2).\n \/\/\n \/\/ However, if the destination file is a special file, we don't want to\n \/\/ use rename (e.g. we don't want to replace \/dev\/null with a regular\n \/\/ file.) If that's the case, we create an in-memory buffer, open the\n \/\/ destination file and write to it on commit().\n switch (Stat.type()) {\n case fs::file_type::directory_file:\n return errorCodeToError(errc::is_a_directory);\n case fs::file_type::regular_file:\n case fs::file_type::file_not_found:\n case fs::file_type::status_error:\n return OnDiskBuffer::create(Path, Size, Mode);\n default:\n return InMemoryBuffer::create(Path, Size, Mode);\n }\n}\n<commit_msg>[FileOutputBuffer] Move factory methods out of their classes.<commit_after>\/\/===- FileOutputBuffer.cpp - File Output Buffer ----------------*- C++ -*-===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ Utility for creating a in-memory buffer that will be written to a file.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/Support\/FileOutputBuffer.h\"\n#include \"llvm\/ADT\/STLExtras.h\"\n#include \"llvm\/ADT\/SmallString.h\"\n#include \"llvm\/Support\/Errc.h\"\n#include \"llvm\/Support\/Memory.h\"\n#include \"llvm\/Support\/Path.h\"\n#include \"llvm\/Support\/Signals.h\"\n#include <system_error>\n\n#if !defined(_MSC_VER) && !defined(__MINGW32__)\n#include <unistd.h>\n#else\n#include <io.h>\n#endif\n\nusing namespace llvm;\nusing namespace llvm::sys;\n\n\/\/ A FileOutputBuffer which creates a temporary file in the same directory\n\/\/ as the final output file. The final output file is atomically replaced\n\/\/ with the temporary file on commit().\nclass OnDiskBuffer : public FileOutputBuffer {\npublic:\n OnDiskBuffer(StringRef Path, StringRef TempPath,\n std::unique_ptr<fs::mapped_file_region> Buf)\n : FileOutputBuffer(Path), Buffer(std::move(Buf)), TempPath(TempPath) {}\n\n uint8_t *getBufferStart() const override { return (uint8_t *)Buffer->data(); }\n\n uint8_t *getBufferEnd() const override {\n return (uint8_t *)Buffer->data() + Buffer->size();\n }\n\n size_t getBufferSize() const override { return Buffer->size(); }\n\n Error commit() override {\n \/\/ Unmap buffer, letting OS flush dirty pages to file on disk.\n Buffer.reset();\n\n \/\/ Atomically replace the existing file with the new one.\n auto EC = fs::rename(TempPath, FinalPath);\n sys::DontRemoveFileOnSignal(TempPath);\n return errorCodeToError(EC);\n }\n\n ~OnDiskBuffer() override {\n \/\/ Close the mapping before deleting the temp file, so that the removal\n \/\/ succeeds.\n Buffer.reset();\n fs::remove(TempPath);\n }\n\nprivate:\n std::unique_ptr<fs::mapped_file_region> Buffer;\n std::string TempPath;\n};\n\n\/\/ A FileOutputBuffer which keeps data in memory and writes to the final\n\/\/ output file on commit(). This is used only when we cannot use OnDiskBuffer.\nclass InMemoryBuffer : public FileOutputBuffer {\npublic:\n InMemoryBuffer(StringRef Path, MemoryBlock Buf, unsigned Mode)\n : FileOutputBuffer(Path), Buffer(Buf), Mode(Mode) {}\n\n uint8_t *getBufferStart() const override { return (uint8_t *)Buffer.base(); }\n\n uint8_t *getBufferEnd() const override {\n return (uint8_t *)Buffer.base() + Buffer.size();\n }\n\n size_t getBufferSize() const override { return Buffer.size(); }\n\n Error commit() override {\n int FD;\n std::error_code EC;\n if (auto EC = openFileForWrite(FinalPath, FD, fs::F_None, Mode))\n return errorCodeToError(EC);\n raw_fd_ostream OS(FD, \/*shouldClose=*\/true, \/*unbuffered=*\/true);\n OS << StringRef((const char *)Buffer.base(), Buffer.size());\n return Error::success();\n }\n\nprivate:\n OwningMemoryBlock Buffer;\n unsigned Mode;\n};\n\nstatic Expected<std::unique_ptr<InMemoryBuffer>>\ncreateInMemoryBuffer(StringRef Path, size_t Size, unsigned Mode) {\n std::error_code EC;\n MemoryBlock MB = Memory::allocateMappedMemory(\n Size, nullptr, sys::Memory::MF_READ | sys::Memory::MF_WRITE, EC);\n if (EC)\n return errorCodeToError(EC);\n return llvm::make_unique<InMemoryBuffer>(Path, MB, Mode);\n}\n\nstatic Expected<std::unique_ptr<OnDiskBuffer>>\ncreateOnDiskBuffer(StringRef Path, size_t Size, unsigned Mode) {\n \/\/ Create new file in same directory but with random name.\n SmallString<128> TempPath;\n int FD;\n if (auto EC = fs::createUniqueFile(Path + \".tmp%%%%%%%\", FD, TempPath, Mode))\n return errorCodeToError(EC);\n\n sys::RemoveFileOnSignal(TempPath);\n\n#ifndef LLVM_ON_WIN32\n \/\/ On Windows, CreateFileMapping (the mmap function on Windows)\n \/\/ automatically extends the underlying file. We don't need to\n \/\/ extend the file beforehand. _chsize (ftruncate on Windows) is\n \/\/ pretty slow just like it writes specified amount of bytes,\n \/\/ so we should avoid calling that function.\n if (auto EC = fs::resize_file(FD, Size))\n return errorCodeToError(EC);\n#endif\n\n \/\/ Mmap it.\n std::error_code EC;\n auto MappedFile = llvm::make_unique<fs::mapped_file_region>(\n FD, fs::mapped_file_region::readwrite, Size, 0, EC);\n close(FD);\n if (EC)\n return errorCodeToError(EC);\n return llvm::make_unique<OnDiskBuffer>(Path, TempPath, std::move(MappedFile));\n}\n\n\/\/ Create an instance of FileOutputBuffer.\nExpected<std::unique_ptr<FileOutputBuffer>>\nFileOutputBuffer::create(StringRef Path, size_t Size, unsigned Flags) {\n unsigned Mode = fs::all_read | fs::all_write;\n if (Flags & F_executable)\n Mode |= fs::all_exe;\n\n fs::file_status Stat;\n fs::status(Path, Stat);\n\n \/\/ Usually, we want to create OnDiskBuffer to create a temporary file in\n \/\/ the same directory as the destination file and atomically replaces it\n \/\/ by rename(2).\n \/\/\n \/\/ However, if the destination file is a special file, we don't want to\n \/\/ use rename (e.g. we don't want to replace \/dev\/null with a regular\n \/\/ file.) If that's the case, we create an in-memory buffer, open the\n \/\/ destination file and write to it on commit().\n switch (Stat.type()) {\n case fs::file_type::directory_file:\n return errorCodeToError(errc::is_a_directory);\n case fs::file_type::regular_file:\n case fs::file_type::file_not_found:\n case fs::file_type::status_error:\n return createOnDiskBuffer(Path, Size, Mode);\n default:\n return createInMemoryBuffer(Path, Size, Mode);\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ riscv-test-emulate.cc\n\/\/\n\n#include <cstdio>\n#include <cstring>\n#include <cstdlib>\n#include <cinttypes>\n#include <cstdarg>\n#include <cerrno>\n#include <cassert>\n#include <cmath>\n#include <algorithm>\n#include <limits>\n#include <memory>\n#include <string>\n#include <vector>\n#include <deque>\n#include <map>\n#include <set>\n\n#include <fcntl.h>\n#include <unistd.h>\n#include <sys\/mman.h>\n#include <sys\/stat.h>\n\n#include \"riscv-types.h\"\n#include \"riscv-endian.h\"\n#include \"riscv-format.h\"\n#include \"riscv-meta.h\"\n#include \"riscv-util.h\"\n#include \"riscv-cmdline.h\"\n#include \"riscv-codec.h\"\n#include \"riscv-elf.h\"\n#include \"riscv-elf-file.h\"\n#include \"riscv-elf-format.h\"\n#include \"riscv-strings.h\"\n#include \"riscv-disasm.h\"\n#include \"riscv-processor.h\"\n#include \"riscv-abi.h\"\n#include \"riscv-proxy.h\"\n\ninline float f32_sqrt(float a) { return std::sqrt(a); }\ninline double f64_sqrt(double a) { return std::sqrt(a); }\ninline float f32_classify(float a) { return 0; } \/* unimplemented *\/\ninline double f64_classify(double a) { return 0; } \/* unimplemented *\/\n\nnamespace riscv {\n\t#include \"riscv-interp.h\"\n}\n\nusing namespace riscv;\n\nstruct riscv_proc_proxy_rv64 : riscv_processor_rv64\n{\n\tuintptr_t heap_begin;\n\tuintptr_t heap_end;\n\tstd::vector<std::pair<void*,size_t>> mapped_segments;\n\n\triscv_proc_proxy_rv64() : riscv_processor_rv64(), heap_begin(0), heap_end(0) {}\n};\n\nstruct riscv_emulator\n{\n\tstatic const size_t stack_top = 0x78000000; \/\/ 1920 MiB\n\tstatic const size_t stack_size = 0x01000000; \/\/ 16 MiB\n\n\telf_file elf;\n\tstd::string filename;\n\n\tstruct riscv_inst_cache_ent\n\t{\n\t\tuint64_t inst;\n\t\triscv_decode dec;\n\t};\n\n\tstatic const size_t inst_cache_size = 8191;\n\triscv_inst_cache_ent inst_cache[inst_cache_size];\n\n\tbool memory_debug = false;\n\tbool emulator_debug = false;\n\tbool log_registers = false;\n\tbool log_instructions = false;\n\tbool help_or_error = false;\n\n\t\/*\n\t\tThis simple proof of concept machine emulator uses a \n\t\tmachine generated interpreter in src\/asm\/riscv-interp.h\n\t\tcreated by parse-meta using C-psuedo code in meta\/instructions\n\t*\/\n\n\tinline static const int elf_p_flags_mmap(int v)\n\t{\n\t\tint prot = 0;\n\t\tif (v & PF_X) prot |= PROT_EXEC;\n\t\tif (v & PF_W) prot |= PROT_WRITE;\n\t\tif (v & PF_R) prot |= PROT_READ;\n\t\treturn prot;\n\t}\n\n\ttemplate <typename P>\n\tvoid print_int_regeisters(P &proc)\n\t{\n\t\tfor (size_t i = 0; i < 32; i++) {\n\t\t\tchar fmt[32];\n\t\t\tsnprintf(fmt, sizeof(fmt), \"%%-4s: 0x%%0%u%sx%%s\",\n\t\t\t\t(P::xlen >> 2), P::xlen == 64 ? \"ll\" : \"\");\n\t\t\tprintf(fmt, riscv_ireg_name_sym[i], proc.ireg[i].r.xu.val,\n\t\t\t\t(i + 1) % 4 == 0 ? \"\\n\" : \" \");\n\t\t}\n\t}\n\n\ttemplate <typename P>\n\tvoid print_f32_regeisters(P &proc)\n\t{\n\t\tfor (size_t i = 0; i < 32; i++) {\n\t\t\tprintf(\"%-4s: s %16.5f%s\", riscv_freg_name_sym[i],\n\t\t\t\tproc.freg[i].r.s.val, (i + 1) % 4 == 0 ? \"\\n\" : \" \");\n\t\t}\n\t}\n\n\ttemplate <typename P>\n\tvoid print_f64_regeisters(P &proc)\n\t{\n\t\tfor (size_t i = 0; i < 32; i++) {\n\t\t\tprintf(\"%-4s: d %16.5f%s\", riscv_freg_name_sym[i],\n\t\t\t\tproc.freg[i].r.d.val, (i + 1) % 4 == 0 ? \"\\n\" : \" \");\n\t\t}\n\t}\n\n\tstd::string format_inst(uintptr_t pc)\n\t{\n\t\tchar buf[20];\n\t\tuintptr_t inst_length;\n\t\tuint64_t inst = riscv_inst_fetch(pc, &inst_length);\n\t\tswitch (inst_length) {\n\t\t\tcase 2: snprintf(buf, sizeof(buf), \"0x%04tx\", inst); break;\n\t\t\tcase 4: snprintf(buf, sizeof(buf), \"0x%08tx\", inst); break;\n\t\t\tcase 6: snprintf(buf, sizeof(buf), \"0x%012tx\", inst); break;\n\t\t\tcase 8: snprintf(buf, sizeof(buf), \"0x%016tx\", inst); break;\n\t\t\tdefault: snprintf(buf, sizeof(buf), \"(invalid)\"); break;\n\t\t}\n\t\treturn buf;\n\t}\n\n\ttemplate <typename T, typename P>\n\tvoid print_disassembly(T &dec, P &proc)\n\t{\n\t\tstd::string args = riscv_disasm_inst_simple(dec);\n\t\tprintf(\"core %3zu: 0x%016tx (%s) %-30s\\n\", proc.hart_id, proc.pc, format_inst(proc.pc).c_str(), args.c_str());\n\t}\n\n\t\/\/ Simple RV64 Linux syscall emulation (write, exit)\n\ttemplate <typename P>\n\tvoid emulate_ecall(riscv_decode &dec, P &proc, uintptr_t inst_length)\n\t{\n\t\tswitch (proc.ireg[riscv_ireg_a7]) {\n\t\t\tcase riscv_syscall_close: riscv_sys_close(proc); break;\n\t\t\tcase riscv_syscall_write: riscv_sys_write(proc); break;\n\t\t\tcase riscv_syscall_fstat: riscv_sys_fstat(proc); break;\n\t\t\tcase riscv_syscall_exit: riscv_sys_exit(proc); break;\n\t\t\tcase riscv_syscall_brk: riscv_sys_brk(proc); break;\n\t\t\tdefault: panic(\"unknown syscall: %d\", proc.ireg[riscv_ireg_a7]);\n\t\t}\n\t\tproc.pc += inst_length;\n\t}\n\n\t\/\/ Simple RV64 emulator main loop\n\ttemplate <typename P>\n\tvoid rv64_run(P &proc)\n\t{\n\t\triscv_decode dec;\n\t\tsize_t inst_length;\n\t\tuint64_t inst;\n\t\twhile (true) {\n\t\t\tinst = riscv_inst_fetch(proc.pc, &inst_length);\n\t\t\tuint64_t inst_cache_key = inst % inst_cache_size;\n\t\t\tif (inst_cache[inst_cache_key].inst == inst) {\n\t\t\t\tdec = inst_cache[inst_cache_key].dec;\n\t\t\t} else {\n\t\t\t\triscv_decode_inst_rv64(dec, inst);\n\t\t\t\tinst_cache[inst_cache_key].inst = inst;\n\t\t\t\tinst_cache[inst_cache_key].dec = dec;\n\t\t\t}\n\t\t\tif (log_registers) print_int_regeisters(proc);\n\t\t\tif (log_instructions) print_disassembly(dec, proc);\n\t\t\tif (riscv::rv64_exec(dec, proc, inst_length)) continue;\n\t\t\tif (dec.op == riscv_op_ecall) emulate_ecall(dec, proc, inst_length);\n\t\t\telse {\n\t\t\t\tpanic(\"illegal instruciton: pc=0x%\" PRIx64 \" inst=0x%\" PRIx64,\n\t\t\t\t\tproc.pc, inst);\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/ Simple code to map a single stack segment\n\ttemplate <typename P>\n\tvoid map_stack(P &proc, uintptr_t stack_top, uintptr_t stack_size)\n\t{\n\t\tvoid *addr = mmap((void*)(stack_top - stack_size), stack_size,\n\t\t\tPROT_READ | PROT_WRITE, MAP_FIXED | MAP_ANONYMOUS | MAP_PRIVATE, -1, 0);\n\t\tif (addr == MAP_FAILED) {\n\t\t\tpanic(\"map_stack: error: mmap: %s\", strerror(errno));\n\t\t}\n\n\t\t\/\/ keep track of the mapped segment and set the stack_top\n\t\tproc.mapped_segments.push_back(std::pair<void*,size_t>((void*)(stack_top - stack_size), stack_size));\n\t\tproc.ireg[riscv_ireg_sp] = stack_top - 0x8;\n\n\t\tif (emulator_debug) {\n\t\t\tdebug(\"sp : mmap: 0x%016\" PRIxPTR \" - 0x%016\" PRIxPTR \" +R+W\",\n\t\t\t\t(stack_top - stack_size), stack_top);\n\t\t}\n\t}\n\n\t\/\/ Simple code currently maps all segments copy-on-write RWX\n\ttemplate <typename P>\n\tvoid map_load_segment(P &proc, const char* filename, Elf64_Phdr &phdr)\n\t{\n\t\tint fd = open(filename, O_RDONLY);\n\t\tif (fd < 0) {\n\t\t\tpanic(\"map_executable: error: open: %s: %s\", filename, strerror(errno));\n\t\t}\n\t\tvoid *addr = mmap((void*)phdr.p_vaddr, phdr.p_memsz,\n\t\t\telf_p_flags_mmap(phdr.p_flags), MAP_FIXED | MAP_PRIVATE, fd, phdr.p_offset);\n\t\tclose(fd);\n\t\tif (addr == MAP_FAILED) {\n\t\t\tpanic(\"map_executable: error: mmap: %s: %s\", filename, strerror(errno));\n\t\t}\n\n\t\t\/\/ keep track of the mapped segment and set the heap_end\n\t\tproc.mapped_segments.push_back(std::pair<void*,size_t>((void*)phdr.p_vaddr, phdr.p_memsz));\n\t\tuintptr_t seg_end = uintptr_t(phdr.p_vaddr + phdr.p_memsz);\n\t\tif (proc.heap_begin < seg_end) proc.heap_begin = proc.heap_end = seg_end;\n\n\t\tif (emulator_debug) {\n\t\t\tdebug(\"elf: mmap: 0x%016\" PRIxPTR \" - 0x%016\" PRIxPTR \" %s\",\n\t\t\t\tuintptr_t(phdr.p_vaddr), seg_end, elf_p_flags_name(phdr.p_flags).c_str());\n\t\t}\n\t}\n\n\tvoid parse_commandline(int argc, const char *argv[])\n\t{\n\t\tcmdline_option options[] =\n\t\t{\n\t\t\t{ \"-m\", \"--memory-debug\", cmdline_arg_type_none,\n\t\t\t\t\"Memory debug\",\n\t\t\t\t[&](std::string s) { return (memory_debug = true); } },\n\t\t\t{ \"-d\", \"--emulator-debug\", cmdline_arg_type_none,\n\t\t\t\t\"Emulator debug\",\n\t\t\t\t[&](std::string s) { return (emulator_debug = true); } },\n\t\t\t{ \"-r\", \"--log-registers\", cmdline_arg_type_none,\n\t\t\t\t\"Log Registers\",\n\t\t\t\t[&](std::string s) { return (log_registers = true); } },\n\t\t\t{ \"-l\", \"--log-instructions\", cmdline_arg_type_none,\n\t\t\t\t\"Log Instructions\",\n\t\t\t\t[&](std::string s) { return (log_instructions = true); } },\n\t\t\t{ \"-h\", \"--help\", cmdline_arg_type_none,\n\t\t\t\t\"Show help\",\n\t\t\t\t[&](std::string s) { return (help_or_error = true); } },\n\t\t\t{ nullptr, nullptr, cmdline_arg_type_none, nullptr, nullptr }\n\t\t};\n\n\t\tauto result = cmdline_option::process_options(options, argc, argv);\n\t\tif (!result.second) {\n\t\t\thelp_or_error = true;\n\t\t} else if (result.first.size() != 1) {\n\t\t\tprintf(\"%s: wrong number of arguments\\n\", argv[0]);\n\t\t\thelp_or_error = true;\n\t\t}\n\n\t\tif (help_or_error)\n\t\t{\n\t\t\tprintf(\"usage: %s [<options>] <elf_file>\\n\", argv[0]);\n\t\t\tcmdline_option::print_options(options);\n\t\t\texit(9);\n\t\t}\n\n\t\tfilename = result.first[0];\n\t}\n\n\t\/\/ print approximate location of host text, heap and stack\n\tvoid memory_info(int argc, const char *argv[])\n\t{\n\t\tstatic const char *textptr = nullptr;\n\t\tvoid *heapptr = malloc(8);\n\t\tdebug(\"text : ~0x%016\" PRIxPTR, (uintptr_t)&textptr);\n\t\tdebug(\"heap : ~0x%016\" PRIxPTR, (uintptr_t)heapptr);\n\t\tdebug(\"stack: ~0x%016\" PRIxPTR, (uintptr_t)argv);\n\t\tfree(heapptr);\n\t}\n\n\tvoid exec(int argc, const char *argv[])\n\t{\n\t\t\/\/ print process information\n\t\tif (memory_debug) {\n\t\t\tmemory_info(argc, argv);\n\t\t}\n\n\t\t\/\/ load ELF (headers only)\n\t\telf.load(filename, true);\n\n\t\t\/\/ Processor\n\t\triscv_proc_proxy_rv64 proc;\n\t\tproc.flags = emulator_debug ? riscv_processor_flag_emulator_debug : 0;\n\n\t\t\/\/ Find the PT_LOAD segments and mmap then into memory\n\t\tfor (size_t i = 0; i < elf.phdrs.size(); i++) {\n\t\t\tElf64_Phdr &phdr = elf.phdrs[i];\n\t\t\tif (phdr.p_flags & PT_LOAD) {\n\t\t\t\tmap_load_segment(proc, filename.c_str(), phdr);\n\t\t\t}\n\t\t}\n\n\t\t\/\/ Map a stack and set the stack pointer\n\t\tmap_stack(proc, stack_top, stack_size);\n\n\t\t\/\/ Set the program counter to the entry address\n\t\tproc.pc = elf.ehdr.e_entry;\n\n\t\t\/\/ Start the emulator\n\t\trv64_run(proc);\n\n\t\t\/\/ Unmap segments\n\t\tfor (auto &seg: proc.mapped_segments) {\n\t\t\tmunmap(seg.first, seg.second);\n\t\t}\n\t}\n};\n\nint main(int argc, const char *argv[])\n{\n\triscv_emulator emulator;\n\temulator.parse_commandline(argc, argv);\n\temulator.exec(argc, argv);\n\treturn 0;\n}\n<commit_msg>Log FP registers in test-emulate when register logging is enabled<commit_after>\/\/\n\/\/ riscv-test-emulate.cc\n\/\/\n\n#include <cstdio>\n#include <cstring>\n#include <cstdlib>\n#include <cinttypes>\n#include <cstdarg>\n#include <cerrno>\n#include <cassert>\n#include <cmath>\n#include <algorithm>\n#include <limits>\n#include <memory>\n#include <string>\n#include <vector>\n#include <deque>\n#include <map>\n#include <set>\n\n#include <fcntl.h>\n#include <unistd.h>\n#include <sys\/mman.h>\n#include <sys\/stat.h>\n\n#include \"riscv-types.h\"\n#include \"riscv-endian.h\"\n#include \"riscv-format.h\"\n#include \"riscv-meta.h\"\n#include \"riscv-util.h\"\n#include \"riscv-cmdline.h\"\n#include \"riscv-codec.h\"\n#include \"riscv-elf.h\"\n#include \"riscv-elf-file.h\"\n#include \"riscv-elf-format.h\"\n#include \"riscv-strings.h\"\n#include \"riscv-disasm.h\"\n#include \"riscv-processor.h\"\n#include \"riscv-abi.h\"\n#include \"riscv-proxy.h\"\n\ninline float f32_sqrt(float a) { return std::sqrt(a); }\ninline double f64_sqrt(double a) { return std::sqrt(a); }\ninline float f32_classify(float a) { return 0; } \/* unimplemented *\/\ninline double f64_classify(double a) { return 0; } \/* unimplemented *\/\n\nnamespace riscv {\n\t#include \"riscv-interp.h\"\n}\n\nusing namespace riscv;\n\nstruct riscv_proc_proxy_rv64 : riscv_processor_rv64\n{\n\tuintptr_t heap_begin;\n\tuintptr_t heap_end;\n\tstd::vector<std::pair<void*,size_t>> mapped_segments;\n\n\triscv_proc_proxy_rv64() : riscv_processor_rv64(), heap_begin(0), heap_end(0) {}\n};\n\nstruct riscv_emulator\n{\n\tstatic const size_t stack_top = 0x78000000; \/\/ 1920 MiB\n\tstatic const size_t stack_size = 0x01000000; \/\/ 16 MiB\n\n\telf_file elf;\n\tstd::string filename;\n\n\tstruct riscv_inst_cache_ent\n\t{\n\t\tuint64_t inst;\n\t\triscv_decode dec;\n\t};\n\n\tstatic const size_t inst_cache_size = 8191;\n\triscv_inst_cache_ent inst_cache[inst_cache_size];\n\n\tbool memory_debug = false;\n\tbool emulator_debug = false;\n\tbool log_registers = false;\n\tbool log_instructions = false;\n\tbool help_or_error = false;\n\n\t\/*\n\t\tThis simple proof of concept machine emulator uses a \n\t\tmachine generated interpreter in src\/asm\/riscv-interp.h\n\t\tcreated by parse-meta using C-psuedo code in meta\/instructions\n\t*\/\n\n\tinline static const int elf_p_flags_mmap(int v)\n\t{\n\t\tint prot = 0;\n\t\tif (v & PF_X) prot |= PROT_EXEC;\n\t\tif (v & PF_W) prot |= PROT_WRITE;\n\t\tif (v & PF_R) prot |= PROT_READ;\n\t\treturn prot;\n\t}\n\n\ttemplate <typename P>\n\tvoid print_int_regeisters(P &proc)\n\t{\n\t\tfor (size_t i = 0; i < 32; i++) {\n\t\t\tchar fmt[32];\n\t\t\tsnprintf(fmt, sizeof(fmt), \"%%-4s: 0x%%0%u%sx%%s\",\n\t\t\t\t(P::xlen >> 2), P::xlen == 64 ? \"ll\" : \"\");\n\t\t\tprintf(fmt, riscv_ireg_name_sym[i], proc.ireg[i].r.xu.val,\n\t\t\t\t(i + 1) % 4 == 0 ? \"\\n\" : \" \");\n\t\t}\n\t}\n\n\ttemplate <typename P>\n\tvoid print_f32_regeisters(P &proc)\n\t{\n\t\tfor (size_t i = 0; i < 32; i++) {\n\t\t\tprintf(\"%-4s: s %16.5f%s\", riscv_freg_name_sym[i],\n\t\t\t\tproc.freg[i].r.s.val, (i + 1) % 4 == 0 ? \"\\n\" : \" \");\n\t\t}\n\t}\n\n\ttemplate <typename P>\n\tvoid print_f64_regeisters(P &proc)\n\t{\n\t\tfor (size_t i = 0; i < 32; i++) {\n\t\t\tprintf(\"%-4s: d %16.5f%s\", riscv_freg_name_sym[i],\n\t\t\t\tproc.freg[i].r.d.val, (i + 1) % 4 == 0 ? \"\\n\" : \" \");\n\t\t}\n\t}\n\n\tstd::string format_inst(uintptr_t pc)\n\t{\n\t\tchar buf[20];\n\t\tuintptr_t inst_length;\n\t\tuint64_t inst = riscv_inst_fetch(pc, &inst_length);\n\t\tswitch (inst_length) {\n\t\t\tcase 2: snprintf(buf, sizeof(buf), \"0x%04tx\", inst); break;\n\t\t\tcase 4: snprintf(buf, sizeof(buf), \"0x%08tx\", inst); break;\n\t\t\tcase 6: snprintf(buf, sizeof(buf), \"0x%012tx\", inst); break;\n\t\t\tcase 8: snprintf(buf, sizeof(buf), \"0x%016tx\", inst); break;\n\t\t\tdefault: snprintf(buf, sizeof(buf), \"(invalid)\"); break;\n\t\t}\n\t\treturn buf;\n\t}\n\n\ttemplate <typename T, typename P>\n\tvoid print_disassembly(T &dec, P &proc)\n\t{\n\t\tstd::string args = riscv_disasm_inst_simple(dec);\n\t\tprintf(\"core %3zu: 0x%016tx (%s) %-30s\\n\", proc.hart_id, proc.pc, format_inst(proc.pc).c_str(), args.c_str());\n\t}\n\n\t\/\/ Simple RV64 Linux syscall emulation (write, exit)\n\ttemplate <typename P>\n\tvoid emulate_ecall(riscv_decode &dec, P &proc, uintptr_t inst_length)\n\t{\n\t\tswitch (proc.ireg[riscv_ireg_a7]) {\n\t\t\tcase riscv_syscall_close: riscv_sys_close(proc); break;\n\t\t\tcase riscv_syscall_write: riscv_sys_write(proc); break;\n\t\t\tcase riscv_syscall_fstat: riscv_sys_fstat(proc); break;\n\t\t\tcase riscv_syscall_exit: riscv_sys_exit(proc); break;\n\t\t\tcase riscv_syscall_brk: riscv_sys_brk(proc); break;\n\t\t\tdefault: panic(\"unknown syscall: %d\", proc.ireg[riscv_ireg_a7]);\n\t\t}\n\t\tproc.pc += inst_length;\n\t}\n\n\t\/\/ Simple RV64 emulator main loop\n\ttemplate <typename P>\n\tvoid rv64_run(P &proc)\n\t{\n\t\triscv_decode dec;\n\t\tsize_t inst_length;\n\t\tuint64_t inst;\n\t\twhile (true) {\n\t\t\tinst = riscv_inst_fetch(proc.pc, &inst_length);\n\t\t\tuint64_t inst_cache_key = inst % inst_cache_size;\n\t\t\tif (inst_cache[inst_cache_key].inst == inst) {\n\t\t\t\tdec = inst_cache[inst_cache_key].dec;\n\t\t\t} else {\n\t\t\t\triscv_decode_inst_rv64(dec, inst);\n\t\t\t\tinst_cache[inst_cache_key].inst = inst;\n\t\t\t\tinst_cache[inst_cache_key].dec = dec;\n\t\t\t}\n\t\t\tif (log_registers) {\n\t\t\t\tprint_int_regeisters(proc);\n\t\t\t\tprint_f32_regeisters(proc);\n\t\t\t\tprint_f64_regeisters(proc);\n\t\t\t}\n\t\t\tif (log_instructions) print_disassembly(dec, proc);\n\t\t\tif (riscv::rv64_exec(dec, proc, inst_length)) continue;\n\t\t\tif (dec.op == riscv_op_ecall) emulate_ecall(dec, proc, inst_length);\n\t\t\telse {\n\t\t\t\tpanic(\"illegal instruciton: pc=0x%\" PRIx64 \" inst=0x%\" PRIx64,\n\t\t\t\t\tproc.pc, inst);\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/ Simple code to map a single stack segment\n\ttemplate <typename P>\n\tvoid map_stack(P &proc, uintptr_t stack_top, uintptr_t stack_size)\n\t{\n\t\tvoid *addr = mmap((void*)(stack_top - stack_size), stack_size,\n\t\t\tPROT_READ | PROT_WRITE, MAP_FIXED | MAP_ANONYMOUS | MAP_PRIVATE, -1, 0);\n\t\tif (addr == MAP_FAILED) {\n\t\t\tpanic(\"map_stack: error: mmap: %s\", strerror(errno));\n\t\t}\n\n\t\t\/\/ keep track of the mapped segment and set the stack_top\n\t\tproc.mapped_segments.push_back(std::pair<void*,size_t>((void*)(stack_top - stack_size), stack_size));\n\t\tproc.ireg[riscv_ireg_sp] = stack_top - 0x8;\n\n\t\tif (emulator_debug) {\n\t\t\tdebug(\"sp : mmap: 0x%016\" PRIxPTR \" - 0x%016\" PRIxPTR \" +R+W\",\n\t\t\t\t(stack_top - stack_size), stack_top);\n\t\t}\n\t}\n\n\t\/\/ Simple code currently maps all segments copy-on-write RWX\n\ttemplate <typename P>\n\tvoid map_load_segment(P &proc, const char* filename, Elf64_Phdr &phdr)\n\t{\n\t\tint fd = open(filename, O_RDONLY);\n\t\tif (fd < 0) {\n\t\t\tpanic(\"map_executable: error: open: %s: %s\", filename, strerror(errno));\n\t\t}\n\t\tvoid *addr = mmap((void*)phdr.p_vaddr, phdr.p_memsz,\n\t\t\telf_p_flags_mmap(phdr.p_flags), MAP_FIXED | MAP_PRIVATE, fd, phdr.p_offset);\n\t\tclose(fd);\n\t\tif (addr == MAP_FAILED) {\n\t\t\tpanic(\"map_executable: error: mmap: %s: %s\", filename, strerror(errno));\n\t\t}\n\n\t\t\/\/ keep track of the mapped segment and set the heap_end\n\t\tproc.mapped_segments.push_back(std::pair<void*,size_t>((void*)phdr.p_vaddr, phdr.p_memsz));\n\t\tuintptr_t seg_end = uintptr_t(phdr.p_vaddr + phdr.p_memsz);\n\t\tif (proc.heap_begin < seg_end) proc.heap_begin = proc.heap_end = seg_end;\n\n\t\tif (emulator_debug) {\n\t\t\tdebug(\"elf: mmap: 0x%016\" PRIxPTR \" - 0x%016\" PRIxPTR \" %s\",\n\t\t\t\tuintptr_t(phdr.p_vaddr), seg_end, elf_p_flags_name(phdr.p_flags).c_str());\n\t\t}\n\t}\n\n\tvoid parse_commandline(int argc, const char *argv[])\n\t{\n\t\tcmdline_option options[] =\n\t\t{\n\t\t\t{ \"-m\", \"--memory-debug\", cmdline_arg_type_none,\n\t\t\t\t\"Memory debug\",\n\t\t\t\t[&](std::string s) { return (memory_debug = true); } },\n\t\t\t{ \"-d\", \"--emulator-debug\", cmdline_arg_type_none,\n\t\t\t\t\"Emulator debug\",\n\t\t\t\t[&](std::string s) { return (emulator_debug = true); } },\n\t\t\t{ \"-r\", \"--log-registers\", cmdline_arg_type_none,\n\t\t\t\t\"Log Registers\",\n\t\t\t\t[&](std::string s) { return (log_registers = true); } },\n\t\t\t{ \"-l\", \"--log-instructions\", cmdline_arg_type_none,\n\t\t\t\t\"Log Instructions\",\n\t\t\t\t[&](std::string s) { return (log_instructions = true); } },\n\t\t\t{ \"-h\", \"--help\", cmdline_arg_type_none,\n\t\t\t\t\"Show help\",\n\t\t\t\t[&](std::string s) { return (help_or_error = true); } },\n\t\t\t{ nullptr, nullptr, cmdline_arg_type_none, nullptr, nullptr }\n\t\t};\n\n\t\tauto result = cmdline_option::process_options(options, argc, argv);\n\t\tif (!result.second) {\n\t\t\thelp_or_error = true;\n\t\t} else if (result.first.size() != 1) {\n\t\t\tprintf(\"%s: wrong number of arguments\\n\", argv[0]);\n\t\t\thelp_or_error = true;\n\t\t}\n\n\t\tif (help_or_error)\n\t\t{\n\t\t\tprintf(\"usage: %s [<options>] <elf_file>\\n\", argv[0]);\n\t\t\tcmdline_option::print_options(options);\n\t\t\texit(9);\n\t\t}\n\n\t\tfilename = result.first[0];\n\t}\n\n\t\/\/ print approximate location of host text, heap and stack\n\tvoid memory_info(int argc, const char *argv[])\n\t{\n\t\tstatic const char *textptr = nullptr;\n\t\tvoid *heapptr = malloc(8);\n\t\tdebug(\"text : ~0x%016\" PRIxPTR, (uintptr_t)&textptr);\n\t\tdebug(\"heap : ~0x%016\" PRIxPTR, (uintptr_t)heapptr);\n\t\tdebug(\"stack: ~0x%016\" PRIxPTR, (uintptr_t)argv);\n\t\tfree(heapptr);\n\t}\n\n\tvoid exec(int argc, const char *argv[])\n\t{\n\t\t\/\/ print process information\n\t\tif (memory_debug) {\n\t\t\tmemory_info(argc, argv);\n\t\t}\n\n\t\t\/\/ load ELF (headers only)\n\t\telf.load(filename, true);\n\n\t\t\/\/ Processor\n\t\triscv_proc_proxy_rv64 proc;\n\t\tproc.flags = emulator_debug ? riscv_processor_flag_emulator_debug : 0;\n\n\t\t\/\/ Find the PT_LOAD segments and mmap then into memory\n\t\tfor (size_t i = 0; i < elf.phdrs.size(); i++) {\n\t\t\tElf64_Phdr &phdr = elf.phdrs[i];\n\t\t\tif (phdr.p_flags & PT_LOAD) {\n\t\t\t\tmap_load_segment(proc, filename.c_str(), phdr);\n\t\t\t}\n\t\t}\n\n\t\t\/\/ Map a stack and set the stack pointer\n\t\tmap_stack(proc, stack_top, stack_size);\n\n\t\t\/\/ Set the program counter to the entry address\n\t\tproc.pc = elf.ehdr.e_entry;\n\n\t\t\/\/ Start the emulator\n\t\trv64_run(proc);\n\n\t\t\/\/ Unmap segments\n\t\tfor (auto &seg: proc.mapped_segments) {\n\t\t\tmunmap(seg.first, seg.second);\n\t\t}\n\t}\n};\n\nint main(int argc, const char *argv[])\n{\n\triscv_emulator emulator;\n\temulator.parse_commandline(argc, argv);\n\temulator.exec(argc, argv);\n\treturn 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: WColumnSelect.hxx,v $\n *\n * $Revision: 1.8 $\n *\n * last change: $Author: obo $ $Date: 2006-10-12 13:38:47 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n#ifndef DBAUI_WIZ_COLUMNSELECT_HXX\n#define DBAUI_WIZ_COLUMNSELECT_HXX\n\n#ifndef DBAUI_WIZ_TABBPAGE_HXX\n#include \"WTabPage.hxx\"\n#endif\n#ifndef _SV_FIXED_HXX\n#include <vcl\/fixed.hxx>\n#endif\n#ifndef _SV_LSTBOX_HXX\n#include <vcl\/lstbox.hxx>\n#endif\n#ifndef _SV_BUTTON_HXX\n#include <vcl\/button.hxx>\n#endif\n\nnamespace dbaui\n{\n \/\/ ========================================================\n \/\/ Wizard Page: OWizColumnSelect\n \/\/ ========================================================\n\n class OWizColumnSelect : public OWizardPage\n {\n\n FixedLine m_flColumns;\n MultiListBox m_lbOrgColumnNames; \/\/ left side\n ImageButton m_ibColumn_RH;\n ImageButton m_ibColumns_RH;\n ImageButton m_ibColumn_LH;\n ImageButton m_ibColumns_LH;\n MultiListBox m_lbNewColumnNames; \/\/ right side\n\n\n DECL_LINK( ButtonClickHdl, Button * );\n DECL_LINK( ListDoubleClickHdl, MultiListBox * );\n\n\n void clearListBox(MultiListBox& _rListBox);\n void fillColumns( ListBox* pRight,\n ::std::vector< ::rtl::OUString> &_rRightColumns);\n\n void createNewColumn( ListBox* _pListbox,\n OFieldDescription* _pSrcField,\n ::std::vector< ::rtl::OUString>& _rRightColumns,\n const ::rtl::OUString& _sColumnName,\n const ::rtl::OUString& _sExtraChars,\n sal_Int32 _nMaxNameLen,\n const ::comphelper::TStringMixEqualFunctor& _aCase);\n\n void moveColumn( ListBox* _pRight,\n ListBox* _pLeft,\n ::std::vector< ::rtl::OUString>& _rRightColumns,\n const ::rtl::OUString& _sColumnName,\n const ::rtl::OUString& _sExtraChars,\n sal_Int32 _nMaxNameLen,\n const ::comphelper::TStringMixEqualFunctor& _aCase);\n\n void enableButtons();\n\n\n USHORT adjustColumnPosition(ListBox* _pLeft,\n const ::rtl::OUString& _sColumnName,\n ODatabaseExport::TColumnVector::size_type nCurrentPos,\n const ::comphelper::TStringMixEqualFunctor& _aCase);\n\n public:\n virtual void Reset ( );\n virtual void ActivatePage();\n virtual sal_Bool LeavePage();\n virtual String GetTitle() const ;\n\n OWizColumnSelect(Window* pParent);\n virtual ~OWizColumnSelect();\n };\n}\n#endif \/\/ DBAUI_WIZ_COLUMNSELECT_HXX\n\n\n\n<commit_msg>INTEGRATION: CWS dba24d (1.8.158); FILE MERGED 2007\/11\/08 14:21:04 fs 1.8.158.1: #i81658# re-factoring of the Copy Table wizard<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: WColumnSelect.hxx,v $\n *\n * $Revision: 1.9 $\n *\n * last change: $Author: rt $ $Date: 2008-01-30 08:48:21 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n#ifndef DBAUI_WIZ_COLUMNSELECT_HXX\n#define DBAUI_WIZ_COLUMNSELECT_HXX\n\n#include \"WTabPage.hxx\"\n#include \"WCopyTable.hxx\"\n\n#ifndef _SV_FIXED_HXX\n#include <vcl\/fixed.hxx>\n#endif\n#ifndef _SV_LSTBOX_HXX\n#include <vcl\/lstbox.hxx>\n#endif\n#ifndef _SV_BUTTON_HXX\n#include <vcl\/button.hxx>\n#endif\n#include <comphelper\/stl_types.hxx>\n\nnamespace dbaui\n{\n class OFieldDescription;\n\n \/\/ ========================================================\n \/\/ Wizard Page: OWizColumnSelect\n \/\/ ========================================================\n\n class OWizColumnSelect : public OWizardPage\n {\n\n FixedLine m_flColumns;\n MultiListBox m_lbOrgColumnNames; \/\/ left side\n ImageButton m_ibColumn_RH;\n ImageButton m_ibColumns_RH;\n ImageButton m_ibColumn_LH;\n ImageButton m_ibColumns_LH;\n MultiListBox m_lbNewColumnNames; \/\/ right side\n\n\n DECL_LINK( ButtonClickHdl, Button * );\n DECL_LINK( ListDoubleClickHdl, MultiListBox * );\n\n\n void clearListBox(MultiListBox& _rListBox);\n void fillColumns( ListBox* pRight,\n ::std::vector< ::rtl::OUString> &_rRightColumns);\n\n void createNewColumn( ListBox* _pListbox,\n OFieldDescription* _pSrcField,\n ::std::vector< ::rtl::OUString>& _rRightColumns,\n const ::rtl::OUString& _sColumnName,\n const ::rtl::OUString& _sExtraChars,\n sal_Int32 _nMaxNameLen,\n const ::comphelper::TStringMixEqualFunctor& _aCase);\n\n void moveColumn( ListBox* _pRight,\n ListBox* _pLeft,\n ::std::vector< ::rtl::OUString>& _rRightColumns,\n const ::rtl::OUString& _sColumnName,\n const ::rtl::OUString& _sExtraChars,\n sal_Int32 _nMaxNameLen,\n const ::comphelper::TStringMixEqualFunctor& _aCase);\n\n void enableButtons();\n\n\n USHORT adjustColumnPosition(ListBox* _pLeft,\n const ::rtl::OUString& _sColumnName,\n ODatabaseExport::TColumnVector::size_type nCurrentPos,\n const ::comphelper::TStringMixEqualFunctor& _aCase);\n\n public:\n virtual void Reset ( );\n virtual void ActivatePage();\n virtual sal_Bool LeavePage();\n virtual String GetTitle() const ;\n\n OWizColumnSelect(Window* pParent);\n virtual ~OWizColumnSelect();\n };\n}\n#endif \/\/ DBAUI_WIZ_COLUMNSELECT_HXX\n\n\n\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: dbtreelistbox.hxx,v $\n *\n * $Revision: 1.4 $\n *\n * last change: $Author: pjunck $ $Date: 2004-10-22 12:06:14 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the License); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an AS IS basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n#ifndef DBAUI_DBTREELISTBOX_HXX\n#define DBAUI_DBTREELISTBOX_HXX\n\n#ifndef _SVTREEBOX_HXX\n#include <svtools\/svtreebx.hxx>\n#endif\n#ifndef _DBAUI_MODULE_DBU_HXX_\n#include \"moduledbu.hxx\"\n#endif\n#ifndef _SV_TIMER_HXX\n#include <vcl\/timer.hxx>\n#endif\n#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_\n#include <com\/sun\/star\/lang\/XMultiServiceFactory.hpp>\n#endif\n#ifndef DBAUI_SCROLLHELPER_HXX\n#include \"ScrollHelper.hxx\"\n#endif\n\nnamespace dbaui\n{\n #define TABLE_TYPE 1\n #define VIEW_TYPE 2\n #define FOLDER_TYPE 3\n\n struct DBTreeEditedEntry\n {\n SvLBoxEntry* pEntry;\n XubString aNewText;\n };\n\n class IEntryFilter\n {\n public:\n virtual bool includeEntry( SvLBoxEntry* _pEntry ) const = 0;\n };\n\n \/\/========================================================================\n class IControlActionListener;\n class IController;\n class DBTreeListBox :public SvTreeListBox\n ,public dbaui::OModuleClient\n {\n OScrollHelper m_aScrollHelper;\n Timer m_aTimer; \/\/ is needed for table updates\n Point m_aMousePos;\n SvLBoxEntry* m_pSelectedEntry;\n SvLBoxEntry* m_pDragedEntry;\n IControlActionListener* m_pActionListener;\n IController* m_pContextMenuActionListener;\n\n Link m_aPreExpandHandler; \/\/ handler to be called before a node is expanded\n Link m_aCutHandler; \/\/ called when someone press CTRL+X\n Link m_aCopyHandler; \/\/ called when someone press CTRL+C\n Link m_aPasteHandler; \/\/ called when someone press CTRL+V\n Link m_aDeleteHandler; \/\/ called when someone press DELETE Key\n Link m_aEditingHandler; \/\/ called before someone will edit an entry\n Link m_aEditedHandler; \/\/ called after someone edited an entry\n Link m_aEnterKeyHdl;\n\n\n sal_Int32 m_nSelectLock;\n sal_Bool m_bHandleEnterKey;\n\n protected:\n ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > m_xORB;\n\n private:\n void init();\n DECL_LINK( OnTimeOut, void* );\n DECL_LINK( OnResetEntry, SvLBoxEntry* );\n DECL_LINK( DoubleClickHdl, SvTreeListBox* );\n DECL_LINK( ScrollUpHdl, SvTreeListBox* );\n DECL_LINK( ScrollDownHdl, SvTreeListBox* );\n\n public:\n DBTreeListBox( Window* pParent\n ,const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxORB\n ,WinBits nWinStyle=0\n ,sal_Bool _bHandleEnterKey = sal_False);\n DBTreeListBox( Window* pParent\n ,const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxORB\n ,const ResId& rResId\n ,sal_Bool _bHandleEnterKey = sal_False);\n ~DBTreeListBox();\n\n void setControlActionListener( IControlActionListener* _pListener ) { m_pActionListener = _pListener; }\n IControlActionListener* getControlActionListener( ) const { return m_pActionListener; }\n\n void setContextMenuActionListener( IController* _pConextListener) { m_pContextMenuActionListener = _pConextListener; }\n IController* getContextMenuActionListener( ) const { return m_pContextMenuActionListener; }\n\n inline void setORB(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _xORB) { m_xORB = _xORB; }\n\n\n void SetPreExpandHandler(const Link& _rHdl) { m_aPreExpandHandler = _rHdl; }\n Link GetPreExpandHandler() const { return m_aPreExpandHandler; }\n\n void setCutHandler(const Link& _rHdl) { m_aCutHandler = _rHdl; }\n Link getCutHandler() const { return m_aCutHandler; }\n\n void setCopyHandler(const Link& _rHdl) { m_aCopyHandler = _rHdl; }\n Link getCopyHandler() const { return m_aCopyHandler; }\n\n void setPasteHandler(const Link& _rHdl) { m_aPasteHandler = _rHdl; }\n Link getPasteHandler() const { return m_aPasteHandler; }\n\n void setDeleteHandler(const Link& _rHdl) { m_aDeleteHandler = _rHdl; }\n Link getDeleteHandler() const { return m_aDeleteHandler; }\n\n void setEditingHandler(const Link& _rHdl){ m_aEditingHandler = _rHdl; }\n Link getEditingHandler() const { return m_aEditingHandler; }\n\n void setEditedHandler(const Link& _rHdl) { m_aEditedHandler = _rHdl; }\n Link getEditedHandler() const { return m_aEditedHandler; }\n\n inline SvLBoxEntry* GetSelectedEntry() const { return m_pSelectedEntry; }\n \/\/ modified the given entry so that the expand handler is called whenever the entry is expanded\n \/\/ (normally, the expand handler is called only once)\n void EnableExpandHandler(SvLBoxEntry* _pEntry);\n\n SvLBoxEntry* GetEntryPosByName( const String& aName, SvLBoxEntry* pStart = NULL, const IEntryFilter* _pFilter = NULL ) const;\n virtual void RequestingChilds( SvLBoxEntry* pParent );\n virtual void SelectHdl();\n virtual void DeselectHdl();\n \/\/ Window\n virtual void KeyInput( const KeyEvent& rKEvt );\n\n virtual void InitEntry( SvLBoxEntry* pEntry, const XubString& aStr, const Image& aCollEntryBmp, const Image& aExpEntryBmp);\n\n virtual void SelectEntry(SvLBoxEntry* _pEntry);\n \/\/ enable editing for tables\/views and queries\n virtual BOOL EditingEntry( SvLBoxEntry* pEntry, Selection& );\n virtual BOOL EditedEntry( SvLBoxEntry* pEntry, const XubString& rNewText );\n\n virtual PopupMenu* CreateContextMenu( void );\n virtual void ExcecuteContextMenuAction( USHORT nSelectedPopupEntry );\n\n sal_Int32 lockAutoSelect();\n sal_Int32 unlockAutoSelect();\n sal_Int32 locked() const { return m_nSelectLock; }\n\n void SetEnterKeyHdl(const Link& rNewHdl) {m_aEnterKeyHdl = rNewHdl;}\n\n inline void clearCurrentSelectionEntry() { m_pSelectedEntry = NULL; }\n\n protected:\n virtual void MouseButtonDown( const MouseEvent& rMEvt );\n virtual void Command( const CommandEvent& rCEvt );\n virtual void RequestHelp( const HelpEvent& rHEvt );\n\n \/\/ DragSourceHelper overridables\n virtual void StartDrag( sal_Int8 nAction, const Point& rPosPixel );\n \/\/ DropTargetHelper overridables\n virtual sal_Int8 AcceptDrop( const AcceptDropEvent& _rEvt );\n virtual sal_Int8 ExecuteDrop( const ExecuteDropEvent& _rEvt );\n\n virtual void ModelHasRemoved( SvListEntry* pEntry );\n virtual void ModelHasEntryInvalidated( SvListEntry* pEntry );\n\n void implSelected(SvLBoxEntry* _pSelected);\n };\n}\n\n#endif \/\/ DBAUI_DBTREELISTBOX_HXX\n<commit_msg>INTEGRATION: CWS ooo19126 (1.4.176); FILE MERGED 2005\/09\/05 17:34:43 rt 1.4.176.1: #i54170# Change license header: remove SISSL<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: dbtreelistbox.hxx,v $\n *\n * $Revision: 1.5 $\n *\n * last change: $Author: rt $ $Date: 2005-09-08 15:48:15 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n#ifndef DBAUI_DBTREELISTBOX_HXX\n#define DBAUI_DBTREELISTBOX_HXX\n\n#ifndef _SVTREEBOX_HXX\n#include <svtools\/svtreebx.hxx>\n#endif\n#ifndef _DBAUI_MODULE_DBU_HXX_\n#include \"moduledbu.hxx\"\n#endif\n#ifndef _SV_TIMER_HXX\n#include <vcl\/timer.hxx>\n#endif\n#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_\n#include <com\/sun\/star\/lang\/XMultiServiceFactory.hpp>\n#endif\n#ifndef DBAUI_SCROLLHELPER_HXX\n#include \"ScrollHelper.hxx\"\n#endif\n\nnamespace dbaui\n{\n #define TABLE_TYPE 1\n #define VIEW_TYPE 2\n #define FOLDER_TYPE 3\n\n struct DBTreeEditedEntry\n {\n SvLBoxEntry* pEntry;\n XubString aNewText;\n };\n\n class IEntryFilter\n {\n public:\n virtual bool includeEntry( SvLBoxEntry* _pEntry ) const = 0;\n };\n\n \/\/========================================================================\n class IControlActionListener;\n class IController;\n class DBTreeListBox :public SvTreeListBox\n ,public dbaui::OModuleClient\n {\n OScrollHelper m_aScrollHelper;\n Timer m_aTimer; \/\/ is needed for table updates\n Point m_aMousePos;\n SvLBoxEntry* m_pSelectedEntry;\n SvLBoxEntry* m_pDragedEntry;\n IControlActionListener* m_pActionListener;\n IController* m_pContextMenuActionListener;\n\n Link m_aPreExpandHandler; \/\/ handler to be called before a node is expanded\n Link m_aCutHandler; \/\/ called when someone press CTRL+X\n Link m_aCopyHandler; \/\/ called when someone press CTRL+C\n Link m_aPasteHandler; \/\/ called when someone press CTRL+V\n Link m_aDeleteHandler; \/\/ called when someone press DELETE Key\n Link m_aEditingHandler; \/\/ called before someone will edit an entry\n Link m_aEditedHandler; \/\/ called after someone edited an entry\n Link m_aEnterKeyHdl;\n\n\n sal_Int32 m_nSelectLock;\n sal_Bool m_bHandleEnterKey;\n\n protected:\n ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > m_xORB;\n\n private:\n void init();\n DECL_LINK( OnTimeOut, void* );\n DECL_LINK( OnResetEntry, SvLBoxEntry* );\n DECL_LINK( DoubleClickHdl, SvTreeListBox* );\n DECL_LINK( ScrollUpHdl, SvTreeListBox* );\n DECL_LINK( ScrollDownHdl, SvTreeListBox* );\n\n public:\n DBTreeListBox( Window* pParent\n ,const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxORB\n ,WinBits nWinStyle=0\n ,sal_Bool _bHandleEnterKey = sal_False);\n DBTreeListBox( Window* pParent\n ,const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxORB\n ,const ResId& rResId\n ,sal_Bool _bHandleEnterKey = sal_False);\n ~DBTreeListBox();\n\n void setControlActionListener( IControlActionListener* _pListener ) { m_pActionListener = _pListener; }\n IControlActionListener* getControlActionListener( ) const { return m_pActionListener; }\n\n void setContextMenuActionListener( IController* _pConextListener) { m_pContextMenuActionListener = _pConextListener; }\n IController* getContextMenuActionListener( ) const { return m_pContextMenuActionListener; }\n\n inline void setORB(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _xORB) { m_xORB = _xORB; }\n\n\n void SetPreExpandHandler(const Link& _rHdl) { m_aPreExpandHandler = _rHdl; }\n Link GetPreExpandHandler() const { return m_aPreExpandHandler; }\n\n void setCutHandler(const Link& _rHdl) { m_aCutHandler = _rHdl; }\n Link getCutHandler() const { return m_aCutHandler; }\n\n void setCopyHandler(const Link& _rHdl) { m_aCopyHandler = _rHdl; }\n Link getCopyHandler() const { return m_aCopyHandler; }\n\n void setPasteHandler(const Link& _rHdl) { m_aPasteHandler = _rHdl; }\n Link getPasteHandler() const { return m_aPasteHandler; }\n\n void setDeleteHandler(const Link& _rHdl) { m_aDeleteHandler = _rHdl; }\n Link getDeleteHandler() const { return m_aDeleteHandler; }\n\n void setEditingHandler(const Link& _rHdl){ m_aEditingHandler = _rHdl; }\n Link getEditingHandler() const { return m_aEditingHandler; }\n\n void setEditedHandler(const Link& _rHdl) { m_aEditedHandler = _rHdl; }\n Link getEditedHandler() const { return m_aEditedHandler; }\n\n inline SvLBoxEntry* GetSelectedEntry() const { return m_pSelectedEntry; }\n \/\/ modified the given entry so that the expand handler is called whenever the entry is expanded\n \/\/ (normally, the expand handler is called only once)\n void EnableExpandHandler(SvLBoxEntry* _pEntry);\n\n SvLBoxEntry* GetEntryPosByName( const String& aName, SvLBoxEntry* pStart = NULL, const IEntryFilter* _pFilter = NULL ) const;\n virtual void RequestingChilds( SvLBoxEntry* pParent );\n virtual void SelectHdl();\n virtual void DeselectHdl();\n \/\/ Window\n virtual void KeyInput( const KeyEvent& rKEvt );\n\n virtual void InitEntry( SvLBoxEntry* pEntry, const XubString& aStr, const Image& aCollEntryBmp, const Image& aExpEntryBmp);\n\n virtual void SelectEntry(SvLBoxEntry* _pEntry);\n \/\/ enable editing for tables\/views and queries\n virtual BOOL EditingEntry( SvLBoxEntry* pEntry, Selection& );\n virtual BOOL EditedEntry( SvLBoxEntry* pEntry, const XubString& rNewText );\n\n virtual PopupMenu* CreateContextMenu( void );\n virtual void ExcecuteContextMenuAction( USHORT nSelectedPopupEntry );\n\n sal_Int32 lockAutoSelect();\n sal_Int32 unlockAutoSelect();\n sal_Int32 locked() const { return m_nSelectLock; }\n\n void SetEnterKeyHdl(const Link& rNewHdl) {m_aEnterKeyHdl = rNewHdl;}\n\n inline void clearCurrentSelectionEntry() { m_pSelectedEntry = NULL; }\n\n protected:\n virtual void MouseButtonDown( const MouseEvent& rMEvt );\n virtual void Command( const CommandEvent& rCEvt );\n virtual void RequestHelp( const HelpEvent& rHEvt );\n\n \/\/ DragSourceHelper overridables\n virtual void StartDrag( sal_Int8 nAction, const Point& rPosPixel );\n \/\/ DropTargetHelper overridables\n virtual sal_Int8 AcceptDrop( const AcceptDropEvent& _rEvt );\n virtual sal_Int8 ExecuteDrop( const ExecuteDropEvent& _rEvt );\n\n virtual void ModelHasRemoved( SvListEntry* pEntry );\n virtual void ModelHasEntryInvalidated( SvListEntry* pEntry );\n\n void implSelected(SvLBoxEntry* _pSelected);\n };\n}\n\n#endif \/\/ DBAUI_DBTREELISTBOX_HXX\n<|endoftext|>"} {"text":"<commit_before>#ifndef ALX_FILE_HPP\n#define ALX_FILE_HPP\n\n\n#include <vector>\n#include <array>\n#include <algorithm>\n#include \"String.hpp\"\n\n\n#ifdef min\n#undef min\n#endif\n\n\nnamespace alx {\n\n\n\/\/TODO\n\n\n\/**\n Value-based wrapper around ALLEGRO_FILE.\n *\/\nclass File {\npublic:\n \/**\n constructor from Allegro object.\n @param object allegro object.\n @param managed if true, the object will be deleted automatically when its last reference will be deleted.\n *\/\n File(ALLEGRO_FILE *object, bool managed = true) : m_object(object, managed ? al_fclose : [](ALLEGRO_FILE *){}) {\n }\n\n \/**\n Opens a file.\n @param path path.\n @param mode mode.\n *\/\n File(const char *path, const char *mode) : m_object(al_fopen(path, mode), al_fclose) {\n }\n\n \/**\n Checks if the internal allegro object is null.\n @return true if null, false otherwise.\n *\/\n bool isNull() const {\n return m_object;\n }\n\n \/**\n opens the file.\n @param path path.\n @param mode mode.\n @return true on success.\n *\/\n bool open(const char *path, const char *mode) {\n m_object = std::shared_ptr<ALLEGRO_FILE>(al_fopen(path, mode), al_fclose);\n return m_object;\n }\n\n \/**\n closes the file.\n *\/\n void close() {\n al_fclose(m_object.get());\n }\n\n \/**\n Flushes any pending writes.\n @return true on success.\n *\/\n bool flush() {\n al_fflush(m_object.get());\n }\n\n \/**\n Returns the file position (the 'ftell' function).\n @return the file position.\n *\/\n int64_t getFilePosition() const {\n return al_ftell(m_object.get());\n }\n\n \/**\n Sets the file position (the 'fseek' function).\n @param pos position.\n @param from the 'whence' parameter: ALLEGRO_SEEK_SET, ALLEGRO_SEEK_CUR, ALLEGRO_SEEK_END.\n *\/\n bool setFilePosition(int64_t pos, int from = ALLEGRO_SEEK_SET) {\n return al_fseek(m_object.get(), pos, from);\n }\n\n \/**\n Checks if the EOF indicator has been set.\n @return true if set.\n *\/\n bool getEOF() const {\n return al_feof(m_object.get());\n }\n\n \/**\n Checks if the error indicator has been set.\n @return true if set.\n *\/\n bool getError() const {\n return al_ferror(m_object.get());\n }\n\n \/**\n Clears the error.\n *\/\n void clearError() {\n al_fclearerr(m_object.get());\n }\n\n \/**\n Returns the size of the file.\n @return the size of the file.\n *\/\n int64_t getSize() const {\n return al_fsize(m_object.get());\n }\n \n \/**\n Reads raw bytes into a buffer.\n @param dst destination buffer; it must have enough space to read the given data.\n @param size number of bytes to read.\n @return the number of bytes actually read.\n *\/\n size_t read(void *dst, size_t size) {\n return al_fread(m_object.get(), dst, size);\n }\n\n \/**\n Reads raw bytes into a static array.\n It reads no more than the size that the array can hold. \n @param dst destination buffer.\n @param size number of bytes to read.\n @return the number of bytes actually read.\n *\/\n template <class T, size_t BUFFER_SIZE> size_t read(std::array<T, BUFFER_SIZE> &dst, size_t size) {\n return read(&dst[0], std::min(BUFFER_SIZE * sizeof(T), size));\n }\n\n \/**\n Reads raw bytes into a dynamic array.\n It reads no more than the size that the array can hold. \n @param dst destination buffer.\n @param size number of bytes to read.\n @return the number of bytes actually read.\n *\/\n template <class T, class A> size_t read(std::vector<T, A> &dst, size_t size) {\n return read(&dst[0], std::min(dst.size() * sizeof(T), size));\n }\n\n \/**\n Writes raw bytes to the file.\n @param src source buffer.\n @param size number of bytes to write.\n @return number of bytes actually written.\n *\/\n size_t write(const void *src, size_t size) {\n return al_fwrite(m_object.get(), src, size);\n }\n\n \/**\n Writes raw bytes from a static array.\n It writes no more than the size that the array can hold. \n @param src source buffer.\n @param size number of bytes to write.\n @return the number of bytes actually written.\n *\/\n template <class T, size_t BUFFER_SIZE> size_t write(const std::array<T, BUFFER_SIZE> &src, size_t size) {\n return write(&src[0], std::min(BUFFER_SIZE * sizeof(T), size));\n }\n\n \/**\n Writes raw bytes from a dynamic array.\n It writes no more than the size that the array can hold. \n @param src source buffer.\n @param size number of bytes to write.\n @return the number of bytes actually written.\n *\/\n template <class T, class A> size_t write(const std::vector<T, A> &src, size_t size) {\n return write(&src[0], std::min(src.size() * sizeof(T), size));\n }\n\n \/\/TODO read\/write specific types\n\nprivate:\n \/\/internal allegro object.\n std::shared_ptr<ALLEGRO_FILE> m_object;\n\n friend class Config;\n};\n\n\n} \/\/namespace alx\n\n\n#endif \/\/ALX_FILE_HPP\n<commit_msg>Minor changes.<commit_after>#ifndef ALX_FILE_HPP\n#define ALX_FILE_HPP\n\n\n#include <vector>\n#include <array>\n#include <algorithm>\n#include \"String.hpp\"\n\n\n#ifdef min\n#undef min\n#endif\n\n\nnamespace alx {\n\n\n\/\/TODO\n\n\n\/**\n Value-based wrapper around ALLEGRO_FILE.\n *\/\nclass File {\npublic:\n \/**\n constructor from Allegro object.\n @param object allegro object.\n @param managed if true, the object will be deleted automatically when its last reference will be deleted.\n *\/\n File(ALLEGRO_FILE *object, bool managed = true) : m_object(object, managed ? al_fclose : [](ALLEGRO_FILE *){}) {\n }\n\n \/**\n Opens a file.\n @param path path.\n @param mode mode.\n *\/\n File(const char *path, const char *mode) : m_object(al_fopen(path, mode), al_fclose) {\n }\n\n \/**\n Checks if the internal allegro object is null.\n @return true if null, false otherwise.\n *\/\n bool isNull() const {\n return m_object;\n }\n\n \/**\n opens the file.\n @param path path.\n @param mode mode.\n @return true on success.\n *\/\n bool open(const char *path, const char *mode) {\n m_object = std::shared_ptr<ALLEGRO_FILE>(al_fopen(path, mode), al_fclose);\n return m_object;\n }\n\n \/**\n closes the file.\n *\/\n void close() {\n al_fclose(m_object.get());\n }\n\n \/**\n Flushes any pending writes.\n @return true on success.\n *\/\n bool flush() {\n al_fflush(m_object.get());\n }\n\n \/**\n Returns the file position (the 'ftell' function).\n @return the file position.\n *\/\n int64_t getFilePosition() const {\n return al_ftell(m_object.get());\n }\n\n \/**\n Sets the file position (the 'fseek' function).\n @param pos position.\n @param from the 'whence' parameter: ALLEGRO_SEEK_SET, ALLEGRO_SEEK_CUR, ALLEGRO_SEEK_END.\n *\/\n bool setFilePosition(int64_t pos, int from = ALLEGRO_SEEK_SET) {\n return al_fseek(m_object.get(), pos, from);\n }\n\n \/**\n Checks if the EOF indicator has been set.\n @return true if set.\n *\/\n bool isEOF() const {\n return al_feof(m_object.get());\n }\n\n \/**\n Checks if the error indicator has been set.\n @return true if set.\n *\/\n bool isError() const {\n return al_ferror(m_object.get());\n }\n\n \/**\n Clears the error.\n *\/\n void clearError() {\n al_fclearerr(m_object.get());\n }\n\n \/**\n Returns the size of the file.\n @return the size of the file.\n *\/\n int64_t getSize() const {\n return al_fsize(m_object.get());\n }\n \n \/**\n Reads raw bytes into a buffer.\n @param dst destination buffer; it must have enough space to read the given data.\n @param size number of bytes to read.\n @return the number of bytes actually read.\n *\/\n size_t read(void *dst, size_t size) {\n return al_fread(m_object.get(), dst, size);\n }\n\n \/**\n Reads raw bytes into a static array.\n It reads no more than the size that the array can hold. \n @param dst destination buffer.\n @param size number of bytes to read.\n @return the number of bytes actually read.\n *\/\n template <class T, size_t BUFFER_SIZE> size_t read(std::array<T, BUFFER_SIZE> &dst, size_t size) {\n return read(&dst[0], std::min(BUFFER_SIZE * sizeof(T), size));\n }\n\n \/**\n Reads raw bytes into a dynamic array.\n It reads no more than the size that the array can hold. \n @param dst destination buffer.\n @param size number of bytes to read.\n @return the number of bytes actually read.\n *\/\n template <class T, class A> size_t read(std::vector<T, A> &dst, size_t size) {\n return read(&dst[0], std::min(dst.size() * sizeof(T), size));\n }\n\n \/**\n Writes raw bytes to the file.\n @param src source buffer.\n @param size number of bytes to write.\n @return number of bytes actually written.\n *\/\n size_t write(const void *src, size_t size) {\n return al_fwrite(m_object.get(), src, size);\n }\n\n \/**\n Writes raw bytes from a static array.\n It writes no more than the size that the array can hold. \n @param src source buffer.\n @param size number of bytes to write.\n @return the number of bytes actually written.\n *\/\n template <class T, size_t BUFFER_SIZE> size_t write(const std::array<T, BUFFER_SIZE> &src, size_t size) {\n return write(&src[0], std::min(BUFFER_SIZE * sizeof(T), size));\n }\n\n \/**\n Writes raw bytes from a dynamic array.\n It writes no more than the size that the array can hold. \n @param src source buffer.\n @param size number of bytes to write.\n @return the number of bytes actually written.\n *\/\n template <class T, class A> size_t write(const std::vector<T, A> &src, size_t size) {\n return write(&src[0], std::min(src.size() * sizeof(T), size));\n }\n\n \/\/TODO read\/write primitive values\n\nprivate:\n \/\/internal allegro object.\n std::shared_ptr<ALLEGRO_FILE> m_object;\n\n friend class Config;\n};\n\n\n} \/\/namespace alx\n\n\n#endif \/\/ALX_FILE_HPP\n<|endoftext|>"} {"text":"<commit_before>\/*\nCopyright (C) 2014-2017 Rodrigo Jose Hernandez Cordoba\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\nhttp:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\n\/*! \\file\n\\brief Implementation file for the Scene Node class.\n\\author Rodrigo Hernandez.\n\\copy 2014-2016 Rodrigo Hernandez\n*\/\n#ifndef NOMINMAX\n#define NOMINMAX\n#endif\n#include <cassert>\n#include <algorithm>\n#include \"aeongames\/Node.h\"\n#include \"aeongames\/Scene.h\"\n#include \"aeongames\/LogLevel.h\"\n#include \"aeongames\/ModelInstance.h\"\n\nnamespace AeonGames\n{\n\n const std::shared_ptr<Node> Node::mNullNode{};\n const size_t Node::kInvalidIndex = std::numeric_limits<size_t>::max(); \/\/ Use on VS2013\n\n Node::Node ( uint32_t aFlags ) :\n mName ( \"Node\" ),\n mParent{},\n mScene{},\n mLocalTransform(),\n mGlobalTransform(),\n mNodes(),\n mIndex ( kInvalidIndex ),\n mIterator ( 0 ),\n mFlags ( aFlags )\n {\n }\n\n Node::~Node()\n {\n \/* Make sure tree is left in a valid state *\/\n if ( auto parent = mParent.lock() )\n {\n if ( !parent->RemoveNode ( shared_from_this() ) )\n {\n std::cerr << \"Remove Node Failed\" << std::endl;\n }\n }\n else if ( auto scene = mScene.lock() )\n {\n if ( !scene->RemoveNode ( shared_from_this() ) )\n {\n std::cerr << \"Remove Node Failed\" << std::endl;\n }\n }\n for ( auto & mNode : mNodes )\n {\n mNode->mParent.reset();\n mNode->mScene.reset();\n mNode.reset();\n }\n }\n\n size_t Node::GetChildrenCount() const\n {\n return mNodes.size();\n }\n\n const std::shared_ptr<Node>& Node::GetChild ( size_t aIndex ) const\n {\n if ( aIndex < mNodes.size() )\n {\n return mNodes[aIndex];\n }\n return mNullNode;\n }\n\n const std::shared_ptr<Node> Node::GetParent() const\n {\n return mParent.lock();\n }\n\n size_t Node::GetIndex() const\n {\n return mIndex;\n }\n\n const std::shared_ptr<ModelInstance>& Node::GetModelInstance() const\n {\n return mModelInstance;\n }\n\n void Node::SetModelInstance ( const std::shared_ptr<ModelInstance>& aModelInstance )\n {\n mModelInstance = aModelInstance;\n }\n\n void Node::SetFlags ( uint32_t aFlagBits, bool aEnabled )\n {\n ( aEnabled ) ? mFlags |= aFlagBits : mFlags &= static_cast<uint32_t> ( ~aFlagBits );\n }\n\n void Node::SetFlag ( enum Flags aFlag, bool aEnabled )\n {\n mFlags[aFlag] = aEnabled;\n }\n\n bool Node::IsFlagEnabled ( enum Flags aFlag ) const\n {\n return mFlags[aFlag];\n }\n\n const Transform& Node::GetLocalTransform() const\n {\n return mLocalTransform;\n }\n\n const Transform& Node::GetGlobalTransform() const\n {\n return mGlobalTransform;\n }\n\n void Node::SetLocalTransform ( const Transform& aTransform )\n {\n mLocalTransform = aTransform;\n LoopTraverseDFSPreOrder (\n [] ( const std::shared_ptr<Node>& node )\n {\n if ( auto parent = node->mParent.lock() )\n {\n parent->mGlobalTransform * node->mLocalTransform;\n }\n else\n {\n node->mGlobalTransform = node->mLocalTransform;\n }\n } );\n }\n\n void Node::SetGlobalTransform ( const Transform& aTransform )\n {\n mGlobalTransform = aTransform;\n \/\/ Update the Local transform for this node only\n if ( auto parent = mParent.lock() )\n {\n mLocalTransform = mGlobalTransform * parent->mGlobalTransform.GetInverted();\n }\n else\n {\n mLocalTransform = mGlobalTransform;\n }\n \/\/ Then Update the Global transform for all children\n LoopTraverseDFSPreOrder (\n [this] ( const std::shared_ptr<Node>& node )\n {\n \/*! @todo Although this->mLocalTransform has already been computed\n think about removing the check and let it be recomputed,\n it may be faster than the branch that needs to run\n for each node and is false only once.*\/\n if ( node.get() != this )\n {\n if ( auto parent = node->mParent.lock() )\n {\n node->mGlobalTransform = parent->mGlobalTransform * node->mLocalTransform;\n }\n }\n } );\n }\n\n void Node::SetName ( const std::string& aName )\n {\n mName = aName;\n }\n\n const std::string& Node::GetName() const\n {\n return mName;\n }\n\n bool Node::InsertNode ( size_t aIndex, const std::shared_ptr<Node>& aNode )\n {\n \/\/ Never append null or this pointers.\n \/\/\/@todo std::find might be slower than removing and reinserting an existing node\n if ( ( aNode != nullptr ) && ( aNode.get() != this ) && ( std::find ( mNodes.begin(), mNodes.end(), aNode ) == mNodes.end() ) )\n {\n if ( auto parent = aNode->mParent.lock() )\n {\n if ( !parent->RemoveNode ( aNode ) )\n {\n std::cout << LogLevel ( LogLevel::Level::Warning ) << \"Parent for node \" << aNode->GetName() << \" did not have it as a child.\";\n }\n }\n aNode->mParent = shared_from_this();\n aNode->mIndex = aIndex;\n mNodes.insert ( mNodes.begin() + aIndex, aNode );\n for ( auto i = mNodes.begin() + aIndex + 1; i != mNodes.end(); ++i )\n {\n ++ ( *i )->mIndex;\n }\n \/\/ Force a recalculation of the LOCAL transform\n \/\/ by setting the GLOBAL transform to itself.\n aNode->SetGlobalTransform ( aNode->mGlobalTransform );\n aNode->LoopTraverseDFSPreOrder (\n [this] ( const std::shared_ptr<Node>& node )\n {\n if ( auto scene = mScene.lock() )\n {\n scene->mAllNodes.push_back ( node );\n }\n node->mScene = this->mScene;\n } );\n return true;\n }\n return false;\n }\n\n bool Node::AddNode ( const std::shared_ptr<Node>& aNode )\n {\n \/\/ Never append null or this pointers.\n if ( ( aNode != nullptr ) && ( aNode.get() != this ) && ( std::find ( mNodes.begin(), mNodes.end(), aNode ) == mNodes.end() ) )\n {\n if ( auto parent = aNode->mParent.lock() )\n {\n if ( !parent->RemoveNode ( aNode ) )\n {\n std::cout << LogLevel ( LogLevel::Level::Warning ) << \"Parent for node \" << aNode->GetName() << \" did not have it as a child.\";\n }\n }\n aNode->mParent = shared_from_this();\n aNode->mIndex = mNodes.size();\n mNodes.push_back ( aNode );\n \/\/ Force a recalculation of the LOCAL transform\n \/\/ by setting the GLOBAL transform to itself.\n aNode->SetGlobalTransform ( aNode->mGlobalTransform );\n aNode->LoopTraverseDFSPreOrder (\n [this] ( const std::shared_ptr<Node>& node )\n {\n if ( auto scene = mScene.lock() )\n {\n scene->mAllNodes.push_back ( node );\n }\n node->mScene = mScene;\n } );\n return true;\n }\n return false;\n }\n\n bool Node::RemoveNode ( const std::shared_ptr<Node>& aNode )\n {\n assert ( aNode != nullptr );\n assert ( aNode.get() != this );\n \/\/ If passed a null or this pointer find SHOULD not find it on release builds.\n \/* While only a single instance should be found and erase does the element shifting\n we're using remove here to do the shifting in order to stablish\n that the erase-remove idiom is what should be used in these situations.*\/\n auto it = std::remove ( mNodes.begin(), mNodes.end(), aNode );\n if ( it != mNodes.end() )\n {\n mNodes.erase ( it );\n for ( auto i = mNodes.begin() + aNode->GetIndex(); i != mNodes.end(); ++i )\n {\n ( *i )->mIndex = i - mNodes.begin();\n }\n aNode->mParent.reset();\n aNode->mIndex = Node::kInvalidIndex;\n \/\/ Force recalculation of transforms.\n aNode->SetLocalTransform ( aNode->mGlobalTransform );\n \/\/ Remove node from Scene\n if ( auto scene = mScene.lock() )\n {\n auto it = scene->mAllNodes.end();\n aNode->LoopTraverseDFSPostOrder ( [&scene, &it, this] ( const std::shared_ptr<Node>& node )\n {\n node->mScene.reset();\n it = std::remove ( scene->mAllNodes.begin(), it, node );\n } );\n if ( it != scene->mAllNodes.end() )\n {\n scene->mAllNodes.erase ( it, scene->mAllNodes.end() );\n }\n }\n return true;\n }\n return false;\n }\n\n void Node::LoopTraverseDFSPreOrder ( std::function<void ( const std::shared_ptr<Node>& ) > aAction )\n {\n \/** @todo (EC++ Item 3) This code is the same as the constant overload,\n but can't easily be implemented in terms of that because of aAction's node parameter\n need to also be const.\n *\/\n auto node = shared_from_this();\n aAction ( node );\n auto parent = mParent.lock();\n while ( node != parent )\n {\n if ( node->mIterator < node->mNodes.size() )\n {\n auto prev = node;\n node = node->mNodes[node->mIterator];\n aAction ( node );\n prev->mIterator++;\n }\n else\n {\n node->mIterator = 0; \/\/ Reset counter for next traversal.\n node = node->mParent.lock();\n }\n }\n }\n\n void Node::LoopTraverseDFSPreOrder ( std::function<void ( const std::shared_ptr<Node>& ) > aPreamble, std::function<void ( const std::shared_ptr<Node>& ) > aPostamble )\n {\n \/** @todo (EC++ Item 3) This code is the same as the constant overload,\n but can't easily be implemented in terms of that because of aAction's node parameter\n need to also be const.\n *\/\n auto node = shared_from_this();\n aPreamble ( node );\n auto parent = mParent.lock();\n while ( node != parent )\n {\n if ( node->mIterator < node->mNodes.size() )\n {\n auto prev = node;\n node = node->mNodes[node->mIterator];\n aPreamble ( node );\n prev->mIterator++;\n }\n else\n {\n aPostamble ( node );\n node->mIterator = 0; \/\/ Reset counter for next traversal.\n node = node->mParent.lock();\n }\n }\n }\n\n void Node::LoopTraverseDFSPreOrder ( std::function<void ( const std::shared_ptr<const Node>& ) > aAction ) const\n {\n auto node = shared_from_this();\n aAction ( node );\n auto parent = mParent.lock();\n while ( node != parent )\n {\n if ( node->mIterator < node->mNodes.size() )\n {\n auto prev = node;\n node = node->mNodes[node->mIterator];\n aAction ( node );\n prev->mIterator++;\n }\n else\n {\n node->mIterator = 0; \/\/ Reset counter for next traversal.\n node = node->mParent.lock();\n }\n }\n }\n\n void Node::LoopTraverseDFSPostOrder ( std::function<void ( const std::shared_ptr<Node>& ) > aAction )\n {\n \/*\n This code implements a similar solution to this stackoverflow answer:\n http:\/\/stackoverflow.com\/questions\/5987867\/traversing-a-n-ary-tree-without-using-recurrsion\/5988138#5988138\n *\/\n auto node = shared_from_this();\n auto parent = mParent.lock();\n while ( node != parent )\n {\n if ( node->mIterator < node->mNodes.size() )\n {\n auto prev = node;\n node = node->mNodes[node->mIterator];\n prev->mIterator++;\n }\n else\n {\n aAction ( node );\n node->mIterator = 0; \/\/ Reset counter for next traversal.\n node = node->mParent.lock();\n }\n }\n }\n\n void Node::LoopTraverseDFSPostOrder ( std::function<void ( const std::shared_ptr<const Node>& ) > aAction ) const\n {\n \/*\n This code implements a similar solution to this stackoverflow answer:\n http:\/\/stackoverflow.com\/questions\/5987867\/traversing-a-n-ary-tree-without-using-recurrsion\/5988138#5988138\n *\/\n auto node = shared_from_this();\n auto parent = mParent.lock();\n while ( node != parent )\n {\n if ( node->mIterator < node->mNodes.size() )\n {\n auto prev = node;\n node = node->mNodes[node->mIterator];\n prev->mIterator++;\n }\n else\n {\n aAction ( node );\n node->mIterator = 0; \/\/ Reset counter for next traversal.\n node = node->mParent.lock();\n }\n }\n }\n\n void Node::RecursiveTraverseDFSPostOrder ( std::function<void ( const std::shared_ptr<Node>& ) > aAction )\n {\n for ( auto & mNode : mNodes )\n {\n mNode->RecursiveTraverseDFSPostOrder ( aAction );\n }\n aAction ( shared_from_this() );\n }\n\n void Node::RecursiveTraverseDFSPreOrder ( std::function<void ( const std::shared_ptr<Node>& ) > aAction )\n {\n aAction ( shared_from_this() );\n for ( auto & mNode : mNodes )\n {\n mNode->RecursiveTraverseDFSPreOrder ( aAction );\n }\n }\n\n void Node::LoopTraverseAncestors ( std::function<void ( const std::shared_ptr<Node>& ) > aAction )\n {\n auto node = shared_from_this();\n while ( node != nullptr )\n {\n aAction ( node );\n node = node->mParent.lock();\n }\n }\n\n void Node::LoopTraverseAncestors ( std::function<void ( const std::shared_ptr<const Node>& ) > aAction ) const\n {\n auto node = shared_from_this();\n while ( node != nullptr )\n {\n aAction ( node );\n node = node->mParent.lock();\n }\n }\n\n void Node::RecursiveTraverseAncestors ( std::function<void ( const std::shared_ptr<Node>& ) > aAction )\n {\n aAction ( shared_from_this() );\n if ( auto parent = mParent.lock() )\n {\n parent->RecursiveTraverseAncestors ( aAction );\n }\n }\n\n void Node::Update ( const double delta )\n {\n if ( mModelInstance )\n {\n mModelInstance->StepAnimation ( delta );\n }\n }\n}\n<commit_msg>Fix for bad_weak_ptr coverity issue.<commit_after>\/*\nCopyright (C) 2014-2017 Rodrigo Jose Hernandez Cordoba\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\nhttp:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\n\/*! \\file\n\\brief Implementation file for the Scene Node class.\n\\author Rodrigo Hernandez.\n\\copy 2014-2016 Rodrigo Hernandez\n*\/\n#ifndef NOMINMAX\n#define NOMINMAX\n#endif\n#include <cassert>\n#include <algorithm>\n#include \"aeongames\/Node.h\"\n#include \"aeongames\/Scene.h\"\n#include \"aeongames\/LogLevel.h\"\n#include \"aeongames\/ModelInstance.h\"\n\nnamespace AeonGames\n{\n\n const std::shared_ptr<Node> Node::mNullNode{};\n const size_t Node::kInvalidIndex = std::numeric_limits<size_t>::max(); \/\/ Use on VS2013\n\n Node::Node ( uint32_t aFlags ) :\n mName ( \"Node\" ),\n mParent{},\n mScene{},\n mLocalTransform(),\n mGlobalTransform(),\n mNodes(),\n mIndex ( kInvalidIndex ),\n mIterator ( 0 ),\n mFlags ( aFlags )\n {\n }\n\n Node::~Node()\n {\n \/* Make sure tree is left in a valid state *\/\n if ( auto parent = mParent.lock() )\n {\n try\n {\n if ( !parent->RemoveNode ( shared_from_this() ) )\n {\n std::cerr << \"Remove Node Failed\" << std::endl;\n }\n }\n catch ( std::bad_weak_ptr e )\n {\n std::cerr << \"Remove Node Failed \" << e.what() << std::endl;\n }\n }\n else if ( auto scene = mScene.lock() )\n {\n try\n {\n if ( !scene->RemoveNode ( shared_from_this() ) )\n {\n std::cerr << \"Remove Node Failed\" << std::endl;\n }\n }\n catch ( std::bad_weak_ptr e )\n {\n std::cerr << \"Remove Node Failed \" << e.what() << std::endl;\n }\n }\n for ( auto & mNode : mNodes )\n {\n mNode->mParent.reset();\n mNode->mScene.reset();\n mNode.reset();\n }\n }\n\n size_t Node::GetChildrenCount() const\n {\n return mNodes.size();\n }\n\n const std::shared_ptr<Node>& Node::GetChild ( size_t aIndex ) const\n {\n if ( aIndex < mNodes.size() )\n {\n return mNodes[aIndex];\n }\n return mNullNode;\n }\n\n const std::shared_ptr<Node> Node::GetParent() const\n {\n return mParent.lock();\n }\n\n size_t Node::GetIndex() const\n {\n return mIndex;\n }\n\n const std::shared_ptr<ModelInstance>& Node::GetModelInstance() const\n {\n return mModelInstance;\n }\n\n void Node::SetModelInstance ( const std::shared_ptr<ModelInstance>& aModelInstance )\n {\n mModelInstance = aModelInstance;\n }\n\n void Node::SetFlags ( uint32_t aFlagBits, bool aEnabled )\n {\n ( aEnabled ) ? mFlags |= aFlagBits : mFlags &= static_cast<uint32_t> ( ~aFlagBits );\n }\n\n void Node::SetFlag ( enum Flags aFlag, bool aEnabled )\n {\n mFlags[aFlag] = aEnabled;\n }\n\n bool Node::IsFlagEnabled ( enum Flags aFlag ) const\n {\n return mFlags[aFlag];\n }\n\n const Transform& Node::GetLocalTransform() const\n {\n return mLocalTransform;\n }\n\n const Transform& Node::GetGlobalTransform() const\n {\n return mGlobalTransform;\n }\n\n void Node::SetLocalTransform ( const Transform& aTransform )\n {\n mLocalTransform = aTransform;\n LoopTraverseDFSPreOrder (\n [] ( const std::shared_ptr<Node>& node )\n {\n if ( auto parent = node->mParent.lock() )\n {\n parent->mGlobalTransform * node->mLocalTransform;\n }\n else\n {\n node->mGlobalTransform = node->mLocalTransform;\n }\n } );\n }\n\n void Node::SetGlobalTransform ( const Transform& aTransform )\n {\n mGlobalTransform = aTransform;\n \/\/ Update the Local transform for this node only\n if ( auto parent = mParent.lock() )\n {\n mLocalTransform = mGlobalTransform * parent->mGlobalTransform.GetInverted();\n }\n else\n {\n mLocalTransform = mGlobalTransform;\n }\n \/\/ Then Update the Global transform for all children\n LoopTraverseDFSPreOrder (\n [this] ( const std::shared_ptr<Node>& node )\n {\n \/*! @todo Although this->mLocalTransform has already been computed\n think about removing the check and let it be recomputed,\n it may be faster than the branch that needs to run\n for each node and is false only once.*\/\n if ( node.get() != this )\n {\n if ( auto parent = node->mParent.lock() )\n {\n node->mGlobalTransform = parent->mGlobalTransform * node->mLocalTransform;\n }\n }\n } );\n }\n\n void Node::SetName ( const std::string& aName )\n {\n mName = aName;\n }\n\n const std::string& Node::GetName() const\n {\n return mName;\n }\n\n bool Node::InsertNode ( size_t aIndex, const std::shared_ptr<Node>& aNode )\n {\n \/\/ Never append null or this pointers.\n \/\/\/@todo std::find might be slower than removing and reinserting an existing node\n if ( ( aNode != nullptr ) && ( aNode.get() != this ) && ( std::find ( mNodes.begin(), mNodes.end(), aNode ) == mNodes.end() ) )\n {\n if ( auto parent = aNode->mParent.lock() )\n {\n if ( !parent->RemoveNode ( aNode ) )\n {\n std::cout << LogLevel ( LogLevel::Level::Warning ) << \"Parent for node \" << aNode->GetName() << \" did not have it as a child.\";\n }\n }\n aNode->mParent = shared_from_this();\n aNode->mIndex = aIndex;\n mNodes.insert ( mNodes.begin() + aIndex, aNode );\n for ( auto i = mNodes.begin() + aIndex + 1; i != mNodes.end(); ++i )\n {\n ++ ( *i )->mIndex;\n }\n \/\/ Force a recalculation of the LOCAL transform\n \/\/ by setting the GLOBAL transform to itself.\n aNode->SetGlobalTransform ( aNode->mGlobalTransform );\n aNode->LoopTraverseDFSPreOrder (\n [this] ( const std::shared_ptr<Node>& node )\n {\n if ( auto scene = mScene.lock() )\n {\n scene->mAllNodes.push_back ( node );\n }\n node->mScene = this->mScene;\n } );\n return true;\n }\n return false;\n }\n\n bool Node::AddNode ( const std::shared_ptr<Node>& aNode )\n {\n \/\/ Never append null or this pointers.\n if ( ( aNode != nullptr ) && ( aNode.get() != this ) && ( std::find ( mNodes.begin(), mNodes.end(), aNode ) == mNodes.end() ) )\n {\n if ( auto parent = aNode->mParent.lock() )\n {\n if ( !parent->RemoveNode ( aNode ) )\n {\n std::cout << LogLevel ( LogLevel::Level::Warning ) << \"Parent for node \" << aNode->GetName() << \" did not have it as a child.\";\n }\n }\n aNode->mParent = shared_from_this();\n aNode->mIndex = mNodes.size();\n mNodes.push_back ( aNode );\n \/\/ Force a recalculation of the LOCAL transform\n \/\/ by setting the GLOBAL transform to itself.\n aNode->SetGlobalTransform ( aNode->mGlobalTransform );\n aNode->LoopTraverseDFSPreOrder (\n [this] ( const std::shared_ptr<Node>& node )\n {\n if ( auto scene = mScene.lock() )\n {\n scene->mAllNodes.push_back ( node );\n }\n node->mScene = mScene;\n } );\n return true;\n }\n return false;\n }\n\n bool Node::RemoveNode ( const std::shared_ptr<Node>& aNode )\n {\n assert ( aNode != nullptr );\n assert ( aNode.get() != this );\n \/\/ If passed a null or this pointer find SHOULD not find it on release builds.\n \/* While only a single instance should be found and erase does the element shifting\n we're using remove here to do the shifting in order to stablish\n that the erase-remove idiom is what should be used in these situations.*\/\n auto it = std::remove ( mNodes.begin(), mNodes.end(), aNode );\n if ( it != mNodes.end() )\n {\n mNodes.erase ( it );\n for ( auto i = mNodes.begin() + aNode->GetIndex(); i != mNodes.end(); ++i )\n {\n ( *i )->mIndex = i - mNodes.begin();\n }\n aNode->mParent.reset();\n aNode->mIndex = Node::kInvalidIndex;\n \/\/ Force recalculation of transforms.\n aNode->SetLocalTransform ( aNode->mGlobalTransform );\n \/\/ Remove node from Scene\n if ( auto scene = mScene.lock() )\n {\n auto it = scene->mAllNodes.end();\n aNode->LoopTraverseDFSPostOrder ( [&scene, &it, this] ( const std::shared_ptr<Node>& node )\n {\n node->mScene.reset();\n it = std::remove ( scene->mAllNodes.begin(), it, node );\n } );\n if ( it != scene->mAllNodes.end() )\n {\n scene->mAllNodes.erase ( it, scene->mAllNodes.end() );\n }\n }\n return true;\n }\n return false;\n }\n\n void Node::LoopTraverseDFSPreOrder ( std::function<void ( const std::shared_ptr<Node>& ) > aAction )\n {\n \/** @todo (EC++ Item 3) This code is the same as the constant overload,\n but can't easily be implemented in terms of that because of aAction's node parameter\n need to also be const.\n *\/\n auto node = shared_from_this();\n aAction ( node );\n auto parent = mParent.lock();\n while ( node != parent )\n {\n if ( node->mIterator < node->mNodes.size() )\n {\n auto prev = node;\n node = node->mNodes[node->mIterator];\n aAction ( node );\n prev->mIterator++;\n }\n else\n {\n node->mIterator = 0; \/\/ Reset counter for next traversal.\n node = node->mParent.lock();\n }\n }\n }\n\n void Node::LoopTraverseDFSPreOrder ( std::function<void ( const std::shared_ptr<Node>& ) > aPreamble, std::function<void ( const std::shared_ptr<Node>& ) > aPostamble )\n {\n \/** @todo (EC++ Item 3) This code is the same as the constant overload,\n but can't easily be implemented in terms of that because of aAction's node parameter\n need to also be const.\n *\/\n auto node = shared_from_this();\n aPreamble ( node );\n auto parent = mParent.lock();\n while ( node != parent )\n {\n if ( node->mIterator < node->mNodes.size() )\n {\n auto prev = node;\n node = node->mNodes[node->mIterator];\n aPreamble ( node );\n prev->mIterator++;\n }\n else\n {\n aPostamble ( node );\n node->mIterator = 0; \/\/ Reset counter for next traversal.\n node = node->mParent.lock();\n }\n }\n }\n\n void Node::LoopTraverseDFSPreOrder ( std::function<void ( const std::shared_ptr<const Node>& ) > aAction ) const\n {\n auto node = shared_from_this();\n aAction ( node );\n auto parent = mParent.lock();\n while ( node != parent )\n {\n if ( node->mIterator < node->mNodes.size() )\n {\n auto prev = node;\n node = node->mNodes[node->mIterator];\n aAction ( node );\n prev->mIterator++;\n }\n else\n {\n node->mIterator = 0; \/\/ Reset counter for next traversal.\n node = node->mParent.lock();\n }\n }\n }\n\n void Node::LoopTraverseDFSPostOrder ( std::function<void ( const std::shared_ptr<Node>& ) > aAction )\n {\n \/*\n This code implements a similar solution to this stackoverflow answer:\n http:\/\/stackoverflow.com\/questions\/5987867\/traversing-a-n-ary-tree-without-using-recurrsion\/5988138#5988138\n *\/\n auto node = shared_from_this();\n auto parent = mParent.lock();\n while ( node != parent )\n {\n if ( node->mIterator < node->mNodes.size() )\n {\n auto prev = node;\n node = node->mNodes[node->mIterator];\n prev->mIterator++;\n }\n else\n {\n aAction ( node );\n node->mIterator = 0; \/\/ Reset counter for next traversal.\n node = node->mParent.lock();\n }\n }\n }\n\n void Node::LoopTraverseDFSPostOrder ( std::function<void ( const std::shared_ptr<const Node>& ) > aAction ) const\n {\n \/*\n This code implements a similar solution to this stackoverflow answer:\n http:\/\/stackoverflow.com\/questions\/5987867\/traversing-a-n-ary-tree-without-using-recurrsion\/5988138#5988138\n *\/\n auto node = shared_from_this();\n auto parent = mParent.lock();\n while ( node != parent )\n {\n if ( node->mIterator < node->mNodes.size() )\n {\n auto prev = node;\n node = node->mNodes[node->mIterator];\n prev->mIterator++;\n }\n else\n {\n aAction ( node );\n node->mIterator = 0; \/\/ Reset counter for next traversal.\n node = node->mParent.lock();\n }\n }\n }\n\n void Node::RecursiveTraverseDFSPostOrder ( std::function<void ( const std::shared_ptr<Node>& ) > aAction )\n {\n for ( auto & mNode : mNodes )\n {\n mNode->RecursiveTraverseDFSPostOrder ( aAction );\n }\n aAction ( shared_from_this() );\n }\n\n void Node::RecursiveTraverseDFSPreOrder ( std::function<void ( const std::shared_ptr<Node>& ) > aAction )\n {\n aAction ( shared_from_this() );\n for ( auto & mNode : mNodes )\n {\n mNode->RecursiveTraverseDFSPreOrder ( aAction );\n }\n }\n\n void Node::LoopTraverseAncestors ( std::function<void ( const std::shared_ptr<Node>& ) > aAction )\n {\n auto node = shared_from_this();\n while ( node != nullptr )\n {\n aAction ( node );\n node = node->mParent.lock();\n }\n }\n\n void Node::LoopTraverseAncestors ( std::function<void ( const std::shared_ptr<const Node>& ) > aAction ) const\n {\n auto node = shared_from_this();\n while ( node != nullptr )\n {\n aAction ( node );\n node = node->mParent.lock();\n }\n }\n\n void Node::RecursiveTraverseAncestors ( std::function<void ( const std::shared_ptr<Node>& ) > aAction )\n {\n aAction ( shared_from_this() );\n if ( auto parent = mParent.lock() )\n {\n parent->RecursiveTraverseAncestors ( aAction );\n }\n }\n\n void Node::Update ( const double delta )\n {\n if ( mModelInstance )\n {\n mModelInstance->StepAnimation ( delta );\n }\n }\n}\n<|endoftext|>"} {"text":"<commit_before>#ifndef EXPR_HXX_SPN8H6I7\n#define EXPR_HXX_SPN8H6I7\n\n#include \"ppr.hxx\"\n#include \"id.hxx\"\n#include \"ptr.hxx\"\n\nnamespace miniml\n{\n\n\/\/\/ Type of expression.\nenum class ExprType\n{\n ID, \/\/\/< Identifier\n APP, \/\/\/< Application\n LAM, \/\/\/< Lambda term\n INT, \/\/\/< Integer literal\n};\n\n\/\/\/ Abstract base class for expressions.\nclass Expr\n{\npublic:\n virtual ~Expr() {}\n\n \/\/\/ Get the type of the expression.\n \/\/\/ \\see ExprType\n virtual ExprType type() const = 0;\n\n \/\/\/ Pretty print an expression.\n \/\/\/ \\param[in] prec The outermost precedence for inserting brackets.\n \/\/\/ \\related Ppr\n virtual Ptr<Ppr> ppr(unsigned prec = 0) const = 0;\n};\n\n\n\/\/\/ Identifier expression.\nclass IdExpr final: public Expr\n{\npublic:\n \/\/\/ \\param[in] id The identifier this expression represents.\n IdExpr(const Ptr<Id> id): m_id(id) {}\n\n \/\/\/ \\return ExprType::ID\n ExprType type() const { return ExprType::ID; }\n\n \/\/\/ \\param prec Ignored, since variables are always atomic.\n Ptr<Ppr> ppr(unsigned prec = 0) const;\n\n const Ptr<const Id> id() const { return m_id; }\n\nprivate:\n Ptr<Id> m_id; \/\/\/< Identifier value.\n};\n\n\n\/\/\/ Integer literals.\nclass IntExpr final: public Expr\n{\npublic:\n \/\/\/ \\param[in] val The value of this literal.\n IntExpr(long val): m_val(val) {}\n\n \/\/\/ \\return ExprType::INT\n ExprType type() const { return ExprType::INT; }\n\n \/\/\/ \\param prec Ignored, since literals are always atomic.\n Ptr<Ppr> ppr(unsigned prec = 0) const;\n\n \/\/\/ \\return The value of this literal.\n long val() const { return m_val; }\n\nprivate:\n long m_val;\n};\n\n\n\/\/\/ Application expression.\nclass AppExpr final: public Expr\n{\npublic:\n AppExpr(const Ptr<Expr> left, const Ptr<Expr> right):\n m_left(left), m_right(right)\n {}\n\n \/\/\/ \\return ExprType::APP\n ExprType type() const { return ExprType::APP; }\n\n Ptr<Ppr> ppr(unsigned prec = 0) const;\n\n \/\/\/ \\return The left part (operator).\n const Ptr<const Expr> left() const { return m_left; }\n \/\/\/ \\return The right part (operand).\n const Ptr<const Expr> right() const { return m_right; }\n\nprivate:\n Ptr<Expr> m_left; \/\/\/< Operator.\n Ptr<Expr> m_right; \/\/\/< Operand.\n};\n\n\n\/\/\/ Lambda term (function) expression.\nclass LamExpr final: public Expr\n{\npublic:\n LamExpr(const Ptr<Id> var, const Ptr<Expr> body):\n m_var(var), m_body(body)\n {}\n\n \/\/\/ \\return ExprType::LAM\n ExprType type() const { return ExprType::LAM; }\n\n Ptr<Ppr> ppr(unsigned prec = 0) const;\n\n \/\/\/ \\return The bound variable.\n const Ptr<const Id> var() const { return m_var; }\n \/\/\/ \\return The body of the term.\n const Ptr<const Expr> body() const { return m_body; }\n\nprivate:\n Ptr<Id> m_var; \/\/\/< Bound variable.\n Ptr<Expr> m_body; \/\/\/< Body.\n};\n\n}\n\n#endif \/* end of include guard: EXPR_HXX_SPN8H6I7 *\/\n<commit_msg>Doc for IdExpr::id<commit_after>#ifndef EXPR_HXX_SPN8H6I7\n#define EXPR_HXX_SPN8H6I7\n\n#include \"ppr.hxx\"\n#include \"id.hxx\"\n#include \"ptr.hxx\"\n\nnamespace miniml\n{\n\n\/\/\/ Type of expression.\nenum class ExprType\n{\n ID, \/\/\/< Identifier\n APP, \/\/\/< Application\n LAM, \/\/\/< Lambda term\n INT, \/\/\/< Integer literal\n};\n\n\/\/\/ Abstract base class for expressions.\nclass Expr\n{\npublic:\n virtual ~Expr() {}\n\n \/\/\/ Get the type of the expression.\n \/\/\/ \\see ExprType\n virtual ExprType type() const = 0;\n\n \/\/\/ Pretty print an expression.\n \/\/\/ \\param[in] prec The outermost precedence for inserting brackets.\n \/\/\/ \\related Ppr\n virtual Ptr<Ppr> ppr(unsigned prec = 0) const = 0;\n};\n\n\n\/\/\/ Identifier expression.\nclass IdExpr final: public Expr\n{\npublic:\n \/\/\/ \\param[in] id The identifier this expression represents.\n IdExpr(const Ptr<Id> id): m_id(id) {}\n\n \/\/\/ \\return ExprType::ID\n ExprType type() const { return ExprType::ID; }\n\n \/\/\/ \\param prec Ignored, since variables are always atomic.\n Ptr<Ppr> ppr(unsigned prec = 0) const;\n\n \/\/\/ \\return The identifier value.\n const Ptr<const Id> id() const { return m_id; }\n\nprivate:\n Ptr<Id> m_id; \/\/\/< Identifier value.\n};\n\n\n\/\/\/ Integer literals.\nclass IntExpr final: public Expr\n{\npublic:\n \/\/\/ \\param[in] val The value of this literal.\n IntExpr(long val): m_val(val) {}\n\n \/\/\/ \\return ExprType::INT\n ExprType type() const { return ExprType::INT; }\n\n \/\/\/ \\param prec Ignored, since literals are always atomic.\n Ptr<Ppr> ppr(unsigned prec = 0) const;\n\n \/\/\/ \\return The value of this literal.\n long val() const { return m_val; }\n\nprivate:\n long m_val;\n};\n\n\n\/\/\/ Application expression.\nclass AppExpr final: public Expr\n{\npublic:\n AppExpr(const Ptr<Expr> left, const Ptr<Expr> right):\n m_left(left), m_right(right)\n {}\n\n \/\/\/ \\return ExprType::APP\n ExprType type() const { return ExprType::APP; }\n\n Ptr<Ppr> ppr(unsigned prec = 0) const;\n\n \/\/\/ \\return The left part (operator).\n const Ptr<const Expr> left() const { return m_left; }\n \/\/\/ \\return The right part (operand).\n const Ptr<const Expr> right() const { return m_right; }\n\nprivate:\n Ptr<Expr> m_left; \/\/\/< Operator.\n Ptr<Expr> m_right; \/\/\/< Operand.\n};\n\n\n\/\/\/ Lambda term (function) expression.\nclass LamExpr final: public Expr\n{\npublic:\n LamExpr(const Ptr<Id> var, const Ptr<Expr> body):\n m_var(var), m_body(body)\n {}\n\n \/\/\/ \\return ExprType::LAM\n ExprType type() const { return ExprType::LAM; }\n\n Ptr<Ppr> ppr(unsigned prec = 0) const;\n\n \/\/\/ \\return The bound variable.\n const Ptr<const Id> var() const { return m_var; }\n \/\/\/ \\return The body of the term.\n const Ptr<const Expr> body() const { return m_body; }\n\nprivate:\n Ptr<Id> m_var; \/\/\/< Bound variable.\n Ptr<Expr> m_body; \/\/\/< Body.\n};\n\n}\n\n#endif \/* end of include guard: EXPR_HXX_SPN8H6I7 *\/\n<|endoftext|>"} {"text":"<commit_before>\/**\n * Filename: MinMaxSearch.cpp\n * Author: Igor Makhtes\n * Date: Dec 12, 2014\n *\n * The MIT License (MIT)\n *\n * Copyright (c) 2014\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n *\/\n\n\n#include <ai-homework2\/MinMaxSearch.h>\n\n\nMinMaxSearch::MinMaxSearch(IGoGameHeuristic* heuristic)\n : heuristic_(heuristic) {\n}\n\nconst string MinMaxSearch::search(const GoGame& game, int maxSteps, int maxDepth) const {\n string winner = \"X\";\n\n GoGame currentGame = game;\n\n cout << currentGame.getBoard().toString() << endl;\n\n bool maxPlayer = true;\n\n while (!currentGame.isFinished() && maxSteps-- != 0) {\n Board::CellPoint bestMove = minimax(currentGame, maxPlayer, maxDepth).first;\n currentGame.makeMove(bestMove.point);\n maxPlayer = !maxPlayer;\n cout << currentGame.getBoard().toString() << endl;\n }\n\n return currentGame.getWinner();\n}\n\npair<Board::CellPoint, double> MinMaxSearch::minimax(\n const GoGame& game, bool maxPlayer, int depth) const {\n\n if (depth == 0) {\n double estimate = heuristic_->estimate(game);\n return make_pair(\n Board::CellPoint(0, 0, Board::CellEmpty),\n estimate);\n }\n\n if (game.isFinished()) {\n double estimation = heuristic_->estimate(game);\n return make_pair(\n Board::CellPoint(0, 0, Board::CellEmpty),\n estimation);\n }\n\n set<Board::CellPoint> allMoves = game.getAvailableMoves();\n\n double bestValue;\n Board::CellPoint bestMove(0, 0, Board::CellEmpty);\n\n if (maxPlayer)\n bestValue = -std::numeric_limits<double>::max();\n else\n bestValue = std::numeric_limits<double>::max();\n\n for(set<Board::CellPoint>::iterator move = allMoves.begin();\n move != allMoves.end(); ++move) {\n\n GoGame nextGame = game.simulateMove(move->point);\n cout << nextGame.getBoard().toString() << endl;\n double childValue = minimax(nextGame, !maxPlayer, depth - 1).second;\n\n if (maxPlayer) {\n if (childValue > bestValue) {\n bestValue = childValue;\n bestMove = *move;\n }\n }\n else\n if (childValue < bestValue) {\n bestValue = childValue;\n bestMove = *move;\n }\n }\n\n return make_pair(bestMove, bestValue);\n}\n<commit_msg>redundant prints removed<commit_after>\/**\n * Filename: MinMaxSearch.cpp\n * Author: Igor Makhtes\n * Date: Dec 12, 2014\n *\n * The MIT License (MIT)\n *\n * Copyright (c) 2014\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n *\/\n\n\n#include <ai-homework2\/MinMaxSearch.h>\n\n\nMinMaxSearch::MinMaxSearch(IGoGameHeuristic* heuristic)\n : heuristic_(heuristic) {\n}\n\nconst string MinMaxSearch::search(const GoGame& game, int maxSteps, int maxDepth) const {\n string winner = \"X\";\n\n GoGame currentGame = game;\n\n cout << currentGame.getBoard().toString() << endl;\n\n bool maxPlayer = true;\n\n while (!currentGame.isFinished() && maxSteps-- != 0) {\n Board::CellPoint bestMove = minimax(currentGame, maxPlayer, maxDepth).first;\n currentGame.makeMove(bestMove.point);\n maxPlayer = !maxPlayer;\n cout << currentGame.getBoard().toString() << endl;\n }\n\n return currentGame.getWinner();\n}\n\npair<Board::CellPoint, double> MinMaxSearch::minimax(\n const GoGame& game, bool maxPlayer, int depth) const {\n\n if (depth == 0) {\n double estimate = heuristic_->estimate(game);\n return make_pair(\n Board::CellPoint(0, 0, Board::CellEmpty),\n estimate);\n }\n\n if (game.isFinished()) {\n double estimation = heuristic_->estimate(game);\n return make_pair(\n Board::CellPoint(0, 0, Board::CellEmpty),\n estimation);\n }\n\n set<Board::CellPoint> allMoves = game.getAvailableMoves();\n\n double bestValue;\n Board::CellPoint bestMove(0, 0, Board::CellEmpty);\n\n if (maxPlayer)\n bestValue = -std::numeric_limits<double>::max();\n else\n bestValue = std::numeric_limits<double>::max();\n\n for(set<Board::CellPoint>::iterator move = allMoves.begin();\n move != allMoves.end(); ++move) {\n\n GoGame nextGame = game.simulateMove(move->point);\n \n double childValue = minimax(nextGame, !maxPlayer, depth - 1).second;\n\n if (maxPlayer) {\n if (childValue > bestValue) {\n bestValue = childValue;\n bestMove = *move;\n }\n }\n else\n if (childValue < bestValue) {\n bestValue = childValue;\n bestMove = *move;\n }\n }\n\n return make_pair(bestMove, bestValue);\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Filename: p3dMultifileReader.cxx\n\/\/ Created by: drose (15Jun09)\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ PANDA 3D SOFTWARE\n\/\/ Copyright (c) Carnegie Mellon University. All rights reserved.\n\/\/\n\/\/ All use of this software is subject to the terms of the revised BSD\n\/\/ license. You should have received a copy of this license along\n\/\/ with this source code in a file named \"LICENSE.\"\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"p3dMultifileReader.h\"\n#include \"p3dPackage.h\"\n#include \"mkdir_complete.h\"\n\n#include <time.h>\n\n#ifdef _WIN32\n#include <sys\/utime.h>\n#include <direct.h>\n#define stat _stat\n#define utime _utime\n#define utimbuf _utimbuf\n\n#else\n#include <utime.h>\n\n#endif\n\n\/\/ This sequence of bytes begins each Multifile to identify it as a\n\/\/ Multifile.\nconst char P3DMultifileReader::_header[] = \"pmf\\0\\n\\r\";\nconst size_t P3DMultifileReader::_header_size = 6;\n\nconst int P3DMultifileReader::_current_major_ver = 1;\nconst int P3DMultifileReader::_current_minor_ver = 1;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Function: P3DMultifileReader::Constructor\n\/\/ Access: Public\n\/\/ Description: \n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nP3DMultifileReader::\nP3DMultifileReader() {\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Function: P3DMultifileReader::extract_all\n\/\/ Access: Public\n\/\/ Description: Reads the named multifile, and extracts all the\n\/\/ expected extractable components within it to the\n\/\/ indicated directory. Returns true on success, false\n\/\/ on failure.\n\/\/\n\/\/ The parameters package, start_progress, and\n\/\/ progress_size are provided to make the appropriate\n\/\/ status updates on the package's progress callbacks\n\/\/ during this operation.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nbool P3DMultifileReader::\nextract_all(const string &pathname, const string &to_dir,\n P3DPackage *package, double start_progress, double progress_size) {\n if (!read_header(pathname)) {\n return false;\n }\n\n \/\/ Now walk through all of the files, and extract only the ones we\n \/\/ expect to encounter.\n size_t num_processed = 0;\n size_t num_expected = _subfiles.size();\n if (package != NULL) {\n num_expected = package->_extracts.size();\n }\n\n Subfiles::iterator si;\n for (si = _subfiles.begin(); si != _subfiles.end(); ++si) {\n const Subfile &s = (*si);\n if (package != NULL && !package->is_extractable(s._filename)) {\n continue;\n }\n\n string output_pathname = to_dir + \"\/\" + s._filename;\n if (!mkfile_complete(output_pathname, nout)) {\n return false;\n }\n\n ofstream out(output_pathname.c_str(), ios::out | ios::binary);\n if (!out) {\n nout << \"Unable to write to \" << output_pathname << \"\\n\";\n return false;\n }\n\n if (!extract_subfile(out, s)) {\n return false;\n }\n\n \/\/ Set the timestamp according to the multifile.\n out.close();\n utimbuf utb;\n utb.actime = time(NULL);\n utb.modtime = s._timestamp;\n utime(output_pathname.c_str(), &utb);\n\n\n ++num_processed;\n if (package != NULL) {\n double progress = (double)num_processed \/ (double)num_expected;\n package->report_progress(start_progress + progress * progress_size);\n }\n }\n\n return true;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Function: P3DMultifileReader::extract_one\n\/\/ Access: Public\n\/\/ Description: Reads the named multifile, and extracts only the\n\/\/ named component to the indicated stream. Returns\n\/\/ true on success, false on failure.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nbool P3DMultifileReader::\nextract_one(const string &pathname, ostream &out, const string &filename) {\n if (!read_header(pathname)) {\n return false;\n }\n\n \/\/ Look for the named component.\n Subfiles::iterator si;\n for (si = _subfiles.begin(); si != _subfiles.end(); ++si) {\n const Subfile &s = (*si);\n if (s._filename == filename) {\n return extract_subfile(out, s);\n }\n }\n\n nout << \"Could not extract \" << filename << \": not found.\\n\";\n return false;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Function: P3DMultifileReader::read_header\n\/\/ Access: Private\n\/\/ Description: Opens the named multifile and reads the header\n\/\/ information and index, returning true on success,\n\/\/ false on failure.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nbool P3DMultifileReader::\nread_header(const string &pathname) {\n _subfiles.clear();\n\n _in.open(pathname.c_str(), ios::in | ios::binary);\n if (!_in) {\n nout << \"Couldn't open \" << pathname << \"\\n\";\n return false;\n }\n\n char this_header[_header_size];\n _in.seekg(0);\n _in.read(this_header, _header_size);\n if (_in.fail() || _in.gcount() != (unsigned)_header_size) {\n nout\n << \"Unable to read Multifile header \" << pathname << \".\\n\";\n return false;\n }\n\n \/\/ Here's a special case: if the multifile begins with a hash\n \/\/ character, then we skip at least 6 characters, and continue\n \/\/ reading and discarding lines of ASCII text, until we come across\n \/\/ a nonempty line that does not begin with a hash character. This\n \/\/ allows a P3D application (which is a multifile) to be run\n \/\/ directly on the command line on Unix-based systems.\n if (this_header[0] == '#') {\n int ch = '#';\n while (ch != EOF && ch == '#') {\n \/\/ Skip to the end of the line.\n while (ch != EOF && ch != '\\n') {\n ch = _in.get();\n }\n \/\/ Skip to the first non-whitespace character of the line.\n while (ch != EOF && (isspace(ch) || ch == '\\r')) {\n ch = _in.get();\n }\n }\n\n \/\/ Now fill up the header.\n this_header[0] = ch;\n _in.read(this_header + 1, _header_size - 1);\n }\n\n if (memcmp(this_header, _header, _header_size) != 0) {\n nout << \"Failed header check: \" << pathname << \"\\n\";\n return false;\n }\n\n unsigned int major = read_uint16();\n unsigned int minor = read_uint16();\n if (major != _current_major_ver || minor != _current_minor_ver) {\n nout << \"Incompatible multifile version: \" << pathname << \"\\n\";\n return false;\n }\n\n unsigned int scale = read_uint32();\n if (scale != 1) {\n nout << \"Unsupported scale factor in \" << pathname << \"\\n\";\n return false;\n }\n\n \/\/ We don't care about the overall timestamp.\n read_uint32();\n\n if (!read_index()) {\n nout << \"Error reading multifile index\\n\";\n return false;\n }\n\n return true;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Function: P3DMultifileReader::read_index\n\/\/ Access: Private\n\/\/ Description: Assuming the file stream is positioned at the first\n\/\/ record, reads all of the records into the _subfiles\n\/\/ list. Returns true on success, false on failure.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nbool P3DMultifileReader::\nread_index() {\n unsigned int next_entry = read_uint32();\n if (!_in) {\n return false;\n }\n while (next_entry != 0) {\n Subfile s;\n s._start = read_uint32();\n s._length = read_uint32();\n unsigned int flags = read_uint16();\n if ((flags & 0x18) != 0) {\n \/\/ Skip over the uncompressed length.\n read_uint32();\n }\n \n s._timestamp = read_uint32();\n size_t name_length = read_uint16();\n char *buffer = new char[name_length];\n _in.read(buffer, name_length);\n\n \/\/ The filenames are xored with 0xff just for fun.\n for (size_t ni = 0; ni < name_length; ++ni) {\n buffer[ni] ^= 0xff;\n }\n\n s._filename = string(buffer, name_length);\n delete[] buffer;\n\n if (flags == 0) {\n \/\/ We can only support subfiles with no particular flags set.\n _subfiles.push_back(s);\n }\n\n _in.seekg(next_entry);\n next_entry = read_uint32();\n if (!_in) {\n return false;\n }\n }\n\n return true;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Function: P3DMultifileReader::extract_subfile\n\/\/ Access: Private\n\/\/ Description: Extracts the indicated subfile and writes it to the\n\/\/ indicated stream. Returns true on success, false on\n\/\/ failure.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nbool P3DMultifileReader::\nextract_subfile(ostream &out, const Subfile &s) {\n _in.seekg(s._start);\n\n static const size_t buffer_size = 1024;\n char buffer[buffer_size];\n \n size_t remaining_data = s._length;\n _in.read(buffer, min(buffer_size, remaining_data));\n size_t count = _in.gcount();\n while (count != 0) {\n remaining_data -= count;\n out.write(buffer, count);\n _in.read(buffer, min(buffer_size, remaining_data));\n count = _in.gcount();\n }\n \n if (remaining_data != 0) {\n nout << \"Unable to extract \" << s._filename << \"\\n\";\n return false;\n }\n\n return true;\n}\n\n<commit_msg>consistent code with panda<commit_after>\/\/ Filename: p3dMultifileReader.cxx\n\/\/ Created by: drose (15Jun09)\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ PANDA 3D SOFTWARE\n\/\/ Copyright (c) Carnegie Mellon University. All rights reserved.\n\/\/\n\/\/ All use of this software is subject to the terms of the revised BSD\n\/\/ license. You should have received a copy of this license along\n\/\/ with this source code in a file named \"LICENSE.\"\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"p3dMultifileReader.h\"\n#include \"p3dPackage.h\"\n#include \"mkdir_complete.h\"\n\n#include <time.h>\n\n#ifdef _WIN32\n#include <sys\/utime.h>\n#include <direct.h>\n#define stat _stat\n#define utime _utime\n#define utimbuf _utimbuf\n\n#else\n#include <utime.h>\n\n#endif\n\n\/\/ This sequence of bytes begins each Multifile to identify it as a\n\/\/ Multifile.\nconst char P3DMultifileReader::_header[] = \"pmf\\0\\n\\r\";\nconst size_t P3DMultifileReader::_header_size = 6;\n\nconst int P3DMultifileReader::_current_major_ver = 1;\nconst int P3DMultifileReader::_current_minor_ver = 1;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Function: P3DMultifileReader::Constructor\n\/\/ Access: Public\n\/\/ Description: \n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nP3DMultifileReader::\nP3DMultifileReader() {\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Function: P3DMultifileReader::extract_all\n\/\/ Access: Public\n\/\/ Description: Reads the named multifile, and extracts all the\n\/\/ expected extractable components within it to the\n\/\/ indicated directory. Returns true on success, false\n\/\/ on failure.\n\/\/\n\/\/ The parameters package, start_progress, and\n\/\/ progress_size are provided to make the appropriate\n\/\/ status updates on the package's progress callbacks\n\/\/ during this operation.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nbool P3DMultifileReader::\nextract_all(const string &pathname, const string &to_dir,\n P3DPackage *package, double start_progress, double progress_size) {\n if (!read_header(pathname)) {\n return false;\n }\n\n \/\/ Now walk through all of the files, and extract only the ones we\n \/\/ expect to encounter.\n size_t num_processed = 0;\n size_t num_expected = _subfiles.size();\n if (package != NULL) {\n num_expected = package->_extracts.size();\n }\n\n Subfiles::iterator si;\n for (si = _subfiles.begin(); si != _subfiles.end(); ++si) {\n const Subfile &s = (*si);\n if (package != NULL && !package->is_extractable(s._filename)) {\n continue;\n }\n\n string output_pathname = to_dir + \"\/\" + s._filename;\n if (!mkfile_complete(output_pathname, nout)) {\n return false;\n }\n\n ofstream out(output_pathname.c_str(), ios::out | ios::binary);\n if (!out) {\n nout << \"Unable to write to \" << output_pathname << \"\\n\";\n return false;\n }\n\n if (!extract_subfile(out, s)) {\n return false;\n }\n\n \/\/ Set the timestamp according to the multifile.\n out.close();\n utimbuf utb;\n utb.actime = time(NULL);\n utb.modtime = s._timestamp;\n utime(output_pathname.c_str(), &utb);\n\n\n ++num_processed;\n if (package != NULL) {\n double progress = (double)num_processed \/ (double)num_expected;\n package->report_progress(start_progress + progress * progress_size);\n }\n }\n\n return true;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Function: P3DMultifileReader::extract_one\n\/\/ Access: Public\n\/\/ Description: Reads the named multifile, and extracts only the\n\/\/ named component to the indicated stream. Returns\n\/\/ true on success, false on failure.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nbool P3DMultifileReader::\nextract_one(const string &pathname, ostream &out, const string &filename) {\n if (!read_header(pathname)) {\n return false;\n }\n\n \/\/ Look for the named component.\n Subfiles::iterator si;\n for (si = _subfiles.begin(); si != _subfiles.end(); ++si) {\n const Subfile &s = (*si);\n if (s._filename == filename) {\n return extract_subfile(out, s);\n }\n }\n\n nout << \"Could not extract \" << filename << \": not found.\\n\";\n return false;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Function: P3DMultifileReader::read_header\n\/\/ Access: Private\n\/\/ Description: Opens the named multifile and reads the header\n\/\/ information and index, returning true on success,\n\/\/ false on failure.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nbool P3DMultifileReader::\nread_header(const string &pathname) {\n _subfiles.clear();\n\n _in.open(pathname.c_str(), ios::in | ios::binary);\n if (!_in) {\n nout << \"Couldn't open \" << pathname << \"\\n\";\n return false;\n }\n\n char this_header[_header_size];\n _in.seekg(0);\n\n \/\/ Here's a special case: if the multifile begins with a hash\n \/\/ character, then we continue reading and discarding lines of ASCII\n \/\/ text, until we come across a nonempty line that does not begin\n \/\/ with a hash character. This allows a P3D application (which is a\n \/\/ multifile) to be run directly on the command line on Unix-based\n \/\/ systems.\n int ch = _in.get();\n\n if (ch == '#') {\n while (ch != EOF && ch == '#') {\n \/\/ Skip to the end of the line.\n while (ch != EOF && ch != '\\n') {\n ch = _in.get();\n }\n \/\/ Skip to the first non-whitespace character of the line.\n while (ch != EOF && (isspace(ch) || ch == '\\r')) {\n ch = _in.get();\n }\n }\n }\n\n \/\/ Now read the actual Multifile header.\n this_header[0] = ch;\n _in.read(this_header + 1, _header_size - 1);\n if (_in.fail() || _in.gcount() != (unsigned)(_header_size - 1)) {\n nout << \"Unable to read Multifile header: \" << pathname << \"\\n\";\n return false;\n }\n\n if (memcmp(this_header, _header, _header_size) != 0) {\n nout << \"Failed header check: \" << pathname << \"\\n\";\n return false;\n }\n\n unsigned int major = read_uint16();\n unsigned int minor = read_uint16();\n if (major != _current_major_ver || minor != _current_minor_ver) {\n nout << \"Incompatible multifile version: \" << pathname << \"\\n\";\n return false;\n }\n\n unsigned int scale = read_uint32();\n if (scale != 1) {\n nout << \"Unsupported scale factor in \" << pathname << \"\\n\";\n return false;\n }\n\n \/\/ We don't care about the overall timestamp.\n read_uint32();\n\n if (!read_index()) {\n nout << \"Error reading multifile index\\n\";\n return false;\n }\n\n return true;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Function: P3DMultifileReader::read_index\n\/\/ Access: Private\n\/\/ Description: Assuming the file stream is positioned at the first\n\/\/ record, reads all of the records into the _subfiles\n\/\/ list. Returns true on success, false on failure.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nbool P3DMultifileReader::\nread_index() {\n unsigned int next_entry = read_uint32();\n if (!_in) {\n return false;\n }\n while (next_entry != 0) {\n Subfile s;\n s._start = read_uint32();\n s._length = read_uint32();\n unsigned int flags = read_uint16();\n if ((flags & 0x18) != 0) {\n \/\/ Skip over the uncompressed length.\n read_uint32();\n }\n \n s._timestamp = read_uint32();\n size_t name_length = read_uint16();\n char *buffer = new char[name_length];\n _in.read(buffer, name_length);\n\n \/\/ The filenames are xored with 0xff just for fun.\n for (size_t ni = 0; ni < name_length; ++ni) {\n buffer[ni] ^= 0xff;\n }\n\n s._filename = string(buffer, name_length);\n delete[] buffer;\n\n if (flags == 0) {\n \/\/ We can only support subfiles with no particular flags set.\n _subfiles.push_back(s);\n }\n\n _in.seekg(next_entry);\n next_entry = read_uint32();\n if (!_in) {\n return false;\n }\n }\n\n return true;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Function: P3DMultifileReader::extract_subfile\n\/\/ Access: Private\n\/\/ Description: Extracts the indicated subfile and writes it to the\n\/\/ indicated stream. Returns true on success, false on\n\/\/ failure.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nbool P3DMultifileReader::\nextract_subfile(ostream &out, const Subfile &s) {\n _in.seekg(s._start);\n\n static const size_t buffer_size = 1024;\n char buffer[buffer_size];\n \n size_t remaining_data = s._length;\n _in.read(buffer, min(buffer_size, remaining_data));\n size_t count = _in.gcount();\n while (count != 0) {\n remaining_data -= count;\n out.write(buffer, count);\n _in.read(buffer, min(buffer_size, remaining_data));\n count = _in.gcount();\n }\n \n if (remaining_data != 0) {\n nout << \"Unable to extract \" << s._filename << \"\\n\";\n return false;\n }\n\n return true;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/*\nThe MIT License (MIT)\n\nCopyright (c) 2013-2014 winlin\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of\nthis software and associated documentation files (the \"Software\"), to deal in\nthe Software without restriction, including without limitation the rights to\nuse, copy, modify, merge, publish, distribute, sublicense, and\/or sell copies of\nthe Software, and to permit persons to whom the Software is furnished to do so,\nsubject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS\nFOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\nCOPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\nIN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\nCONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n*\/\n\n#ifndef SRS_CORE_HPP\n#define SRS_CORE_HPP\n\n\/*\n#include <srs_core.hpp>\n*\/\n\n\/\/ current release version\n#define VERSION_MAJOR \"0\"\n#define VERSION_MINOR \"9\"\n#define VERSION_REVISION \"13\"\n#define RTMP_SIG_SRS_VERSION VERSION_MAJOR\".\"VERSION_MINOR\".\"VERSION_REVISION\n\/\/ server info.\n#define RTMP_SIG_SRS_KEY \"srs\"\n#define RTMP_SIG_SRS_ROLE \"origin server\"\n#define RTMP_SIG_SRS_NAME RTMP_SIG_SRS_KEY\"(simple rtmp server)\"\n#define RTMP_SIG_SRS_URL \"https:\/\/\"RTMP_SIG_SRS_URL_SHORT\n#define RTMP_SIG_SRS_URL_SHORT \"github.com\/winlinvip\/simple-rtmp-server\"\n#define RTMP_SIG_SRS_WEB \"http:\/\/blog.csdn.net\/win_lin\"\n#define RTMP_SIG_SRS_EMAIL \"winlin@vip.126.com\"\n#define RTMP_SIG_SRS_LICENSE \"The MIT License (MIT)\"\n#define RTMP_SIG_SRS_COPYRIGHT \"Copyright (c) 2013-2014 winlin\"\n#define RTMP_SIG_SRS_PRIMARY_AUTHROS \"winlin,wenjiegit\"\n\n\/**\n* the core provides the common defined macros, utilities,\n* user must include the srs_core.hpp before any header, or maybe \n* build failed.\n*\/\n\n\/\/ for int64_t print using PRId64 format.\n#ifndef __STDC_FORMAT_MACROS\n #define __STDC_FORMAT_MACROS\n#endif\n#include <inttypes.h>\n\n#include <assert.h>\n#define srs_assert(expression) assert(expression)\n\n#include <stddef.h>\n#include <sys\/types.h>\n\n\/\/ generated by configure.\n#include <srs_auto_headers.hpp>\n\n\/\/ free the p and set to NULL.\n\/\/ p must be a T*.\n#define srs_freep(p) \\\n\tif (p) { \\\n\t\tdelete p; \\\n\t\tp = NULL; \\\n\t} \\\n\t(void)0\n\/\/ free the p which represents a array\n#define srs_freepa(p) \\\n\tif (p) { \\\n\t\tdelete[] p; \\\n\t\tp = NULL; \\\n\t} \\\n\t(void)0\n\n\/\/ compare\n#define srs_min(a, b) (((a) < (b))? (a) : (b))\n#define srs_max(a, b) (((a) < (b))? (b) : (a))\n\n\/\/ get current system time in ms, use cache to avoid performance problem\nextern int64_t srs_get_system_time_ms();\n\/\/ the deamon st-thread will update it.\nextern void srs_update_system_time_ms();\n\n\/\/ signal defines.\n#define SIGNAL_RELOAD SIGHUP\n\n#include <string>\n\/\/ replace utility\nextern std::string srs_replace(std::string str, std::string old_str, std::string new_str);\n\/\/ dns resolve utility, return the resolved ip address.\nextern std::string srs_dns_resolve(std::string host);\n\n\/**\n* disable copy constructor of class\n*\/\n#define disable_default_copy(className)\\\n private:\\\n \/** \\\n * disable the copy constructor and operator=, donot allow directly copy. \\\n *\/ \\\n className(const className&); \\\n className& operator= (const className&)\n\n#endif<commit_msg>change version to 0.9.14, finish amf0 basic utest<commit_after>\/*\nThe MIT License (MIT)\n\nCopyright (c) 2013-2014 winlin\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of\nthis software and associated documentation files (the \"Software\"), to deal in\nthe Software without restriction, including without limitation the rights to\nuse, copy, modify, merge, publish, distribute, sublicense, and\/or sell copies of\nthe Software, and to permit persons to whom the Software is furnished to do so,\nsubject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS\nFOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\nCOPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\nIN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\nCONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n*\/\n\n#ifndef SRS_CORE_HPP\n#define SRS_CORE_HPP\n\n\/*\n#include <srs_core.hpp>\n*\/\n\n\/\/ current release version\n#define VERSION_MAJOR \"0\"\n#define VERSION_MINOR \"9\"\n#define VERSION_REVISION \"14\"\n#define RTMP_SIG_SRS_VERSION VERSION_MAJOR\".\"VERSION_MINOR\".\"VERSION_REVISION\n\/\/ server info.\n#define RTMP_SIG_SRS_KEY \"srs\"\n#define RTMP_SIG_SRS_ROLE \"origin server\"\n#define RTMP_SIG_SRS_NAME RTMP_SIG_SRS_KEY\"(simple rtmp server)\"\n#define RTMP_SIG_SRS_URL \"https:\/\/\"RTMP_SIG_SRS_URL_SHORT\n#define RTMP_SIG_SRS_URL_SHORT \"github.com\/winlinvip\/simple-rtmp-server\"\n#define RTMP_SIG_SRS_WEB \"http:\/\/blog.csdn.net\/win_lin\"\n#define RTMP_SIG_SRS_EMAIL \"winlin@vip.126.com\"\n#define RTMP_SIG_SRS_LICENSE \"The MIT License (MIT)\"\n#define RTMP_SIG_SRS_COPYRIGHT \"Copyright (c) 2013-2014 winlin\"\n#define RTMP_SIG_SRS_PRIMARY_AUTHROS \"winlin,wenjie.zhao\"\n\n\/**\n* the core provides the common defined macros, utilities,\n* user must include the srs_core.hpp before any header, or maybe \n* build failed.\n*\/\n\n\/\/ for int64_t print using PRId64 format.\n#ifndef __STDC_FORMAT_MACROS\n #define __STDC_FORMAT_MACROS\n#endif\n#include <inttypes.h>\n\n#include <assert.h>\n#define srs_assert(expression) assert(expression)\n\n#include <stddef.h>\n#include <sys\/types.h>\n\n\/\/ generated by configure.\n#include <srs_auto_headers.hpp>\n\n\/\/ free the p and set to NULL.\n\/\/ p must be a T*.\n#define srs_freep(p) \\\n\tif (p) { \\\n\t\tdelete p; \\\n\t\tp = NULL; \\\n\t} \\\n\t(void)0\n\/\/ free the p which represents a array\n#define srs_freepa(p) \\\n\tif (p) { \\\n\t\tdelete[] p; \\\n\t\tp = NULL; \\\n\t} \\\n\t(void)0\n\n\/\/ compare\n#define srs_min(a, b) (((a) < (b))? (a) : (b))\n#define srs_max(a, b) (((a) < (b))? (b) : (a))\n\n\/\/ get current system time in ms, use cache to avoid performance problem\nextern int64_t srs_get_system_time_ms();\n\/\/ the deamon st-thread will update it.\nextern void srs_update_system_time_ms();\n\n\/\/ signal defines.\n#define SIGNAL_RELOAD SIGHUP\n\n#include <string>\n\/\/ replace utility\nextern std::string srs_replace(std::string str, std::string old_str, std::string new_str);\n\/\/ dns resolve utility, return the resolved ip address.\nextern std::string srs_dns_resolve(std::string host);\n\n\/**\n* disable copy constructor of class\n*\/\n#define disable_default_copy(className)\\\n private:\\\n \/** \\\n * disable the copy constructor and operator=, donot allow directly copy. \\\n *\/ \\\n className(const className&); \\\n className& operator= (const className&)\n\n#endif<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2013 The Flutter Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"flutter\/flow\/skia_gpu_object.h\"\n\n#include \"flutter\/fml\/message_loop.h\"\n#include \"flutter\/fml\/synchronization\/waitable_event.h\"\n#include \"flutter\/fml\/task_runner.h\"\n#include \"flutter\/testing\/thread_test.h\"\n#include \"gtest\/gtest.h\"\n#include \"third_party\/skia\/include\/core\/SkRefCnt.h\"\n\n#include <future>\n\nnamespace flutter {\nnamespace testing {\n\nclass TestSkObject : public SkRefCnt {\n public:\n TestSkObject(std::shared_ptr<fml::AutoResetWaitableEvent> latch,\n fml::TaskQueueId* dtor_task_queue_id)\n : latch_(latch), dtor_task_queue_id_(dtor_task_queue_id) {}\n\n ~TestSkObject() {\n if (dtor_task_queue_id_) {\n *dtor_task_queue_id_ = fml::MessageLoop::GetCurrentTaskQueueId();\n }\n latch_->Signal();\n }\n\n private:\n std::shared_ptr<fml::AutoResetWaitableEvent> latch_;\n fml::TaskQueueId* dtor_task_queue_id_;\n};\n\nclass SkiaGpuObjectTest : public ThreadTest {\n public:\n SkiaGpuObjectTest()\n : unref_task_runner_(CreateNewThread()),\n unref_queue_(fml::MakeRefCounted<SkiaUnrefQueue>(\n unref_task_runner(),\n fml::TimeDelta::FromSeconds(0))),\n delayed_unref_queue_(fml::MakeRefCounted<SkiaUnrefQueue>(\n unref_task_runner(),\n fml::TimeDelta::FromSeconds(3))) {\n \/\/ The unref queues must be created in the same thread of the\n \/\/ unref_task_runner so the queue can access the same-thread-only WeakPtr of\n \/\/ the GrContext constructed during the creation.\n std::promise<bool> queuesCreated;\n unref_task_runner_->PostTask([this, &queuesCreated]() {\n unref_queue_ = fml::MakeRefCounted<SkiaUnrefQueue>(\n unref_task_runner(), fml::TimeDelta::FromSeconds(0));\n delayed_unref_queue_ = fml::MakeRefCounted<SkiaUnrefQueue>(\n unref_task_runner(), fml::TimeDelta::FromSeconds(3));\n queuesCreated.set_value(true);\n });\n queuesCreated.get_future().wait();\n ::testing::FLAGS_gtest_death_test_style = \"threadsafe\";\n }\n\n fml::RefPtr<fml::TaskRunner> unref_task_runner() {\n return unref_task_runner_;\n }\n fml::RefPtr<SkiaUnrefQueue> unref_queue() { return unref_queue_; }\n fml::RefPtr<SkiaUnrefQueue> delayed_unref_queue() {\n return delayed_unref_queue_;\n }\n\n private:\n fml::RefPtr<fml::TaskRunner> unref_task_runner_;\n fml::RefPtr<SkiaUnrefQueue> unref_queue_;\n fml::RefPtr<SkiaUnrefQueue> delayed_unref_queue_;\n};\n\nTEST_F(SkiaGpuObjectTest, QueueSimple) {\n std::shared_ptr<fml::AutoResetWaitableEvent> latch =\n std::make_shared<fml::AutoResetWaitableEvent>();\n fml::TaskQueueId dtor_task_queue_id(0);\n SkRefCnt* ref_object = new TestSkObject(latch, &dtor_task_queue_id);\n\n unref_queue()->Unref(ref_object);\n latch->Wait();\n ASSERT_EQ(dtor_task_queue_id, unref_task_runner()->GetTaskQueueId());\n}\n\nTEST_F(SkiaGpuObjectTest, ObjectDestructor) {\n std::shared_ptr<fml::AutoResetWaitableEvent> latch =\n std::make_shared<fml::AutoResetWaitableEvent>();\n fml::TaskQueueId dtor_task_queue_id(0);\n\n {\n auto object = sk_make_sp<TestSkObject>(latch, &dtor_task_queue_id);\n SkiaGPUObject<TestSkObject> sk_object(object, unref_queue());\n ASSERT_EQ(sk_object.get(), object);\n ASSERT_EQ(dtor_task_queue_id, 0);\n }\n\n latch->Wait();\n ASSERT_EQ(dtor_task_queue_id, unref_task_runner()->GetTaskQueueId());\n}\n\nTEST_F(SkiaGpuObjectTest, ObjectReset) {\n std::shared_ptr<fml::AutoResetWaitableEvent> latch =\n std::make_shared<fml::AutoResetWaitableEvent>();\n fml::TaskQueueId dtor_task_queue_id(0);\n SkiaGPUObject<TestSkObject> sk_object(\n sk_make_sp<TestSkObject>(latch, &dtor_task_queue_id), unref_queue());\n\n sk_object.reset();\n ASSERT_EQ(sk_object.get(), nullptr);\n\n latch->Wait();\n ASSERT_EQ(dtor_task_queue_id, unref_task_runner()->GetTaskQueueId());\n}\n\nTEST_F(SkiaGpuObjectTest, ObjectResetBeforeDestructor) {\n std::shared_ptr<fml::AutoResetWaitableEvent> latch =\n std::make_shared<fml::AutoResetWaitableEvent>();\n fml::TaskQueueId dtor_task_queue_id(0);\n\n {\n auto object = sk_make_sp<TestSkObject>(latch, &dtor_task_queue_id);\n SkiaGPUObject<TestSkObject> sk_object(object, unref_queue());\n ASSERT_EQ(sk_object.get(), object);\n ASSERT_EQ(dtor_task_queue_id, 0);\n\n sk_object.reset();\n ASSERT_EQ(sk_object.get(), nullptr);\n }\n\n latch->Wait();\n ASSERT_EQ(dtor_task_queue_id, unref_task_runner()->GetTaskQueueId());\n}\n\nTEST_F(SkiaGpuObjectTest, ObjectResetTwice) {\n std::shared_ptr<fml::AutoResetWaitableEvent> latch =\n std::make_shared<fml::AutoResetWaitableEvent>();\n fml::TaskQueueId dtor_task_queue_id(0);\n SkiaGPUObject<TestSkObject> sk_object(\n sk_make_sp<TestSkObject>(latch, &dtor_task_queue_id), unref_queue());\n\n sk_object.reset();\n ASSERT_EQ(sk_object.get(), nullptr);\n sk_object.reset();\n ASSERT_EQ(sk_object.get(), nullptr);\n\n latch->Wait();\n ASSERT_EQ(dtor_task_queue_id, unref_task_runner()->GetTaskQueueId());\n}\n\n} \/\/ namespace testing\n} \/\/ namespace flutter\n<commit_msg>Fix race in SkiaGPUObject unit-tests. (#16351)<commit_after>\/\/ Copyright 2013 The Flutter Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"flutter\/flow\/skia_gpu_object.h\"\n\n#include \"flutter\/fml\/message_loop.h\"\n#include \"flutter\/fml\/synchronization\/waitable_event.h\"\n#include \"flutter\/fml\/task_runner.h\"\n#include \"flutter\/testing\/thread_test.h\"\n#include \"gtest\/gtest.h\"\n#include \"third_party\/skia\/include\/core\/SkRefCnt.h\"\n\n#include <future>\n\nnamespace flutter {\nnamespace testing {\n\nclass TestSkObject : public SkRefCnt {\n public:\n TestSkObject(std::shared_ptr<fml::AutoResetWaitableEvent> latch,\n fml::TaskQueueId* dtor_task_queue_id)\n : latch_(latch), dtor_task_queue_id_(dtor_task_queue_id) {}\n\n ~TestSkObject() {\n if (dtor_task_queue_id_) {\n *dtor_task_queue_id_ = fml::MessageLoop::GetCurrentTaskQueueId();\n }\n latch_->Signal();\n }\n\n private:\n std::shared_ptr<fml::AutoResetWaitableEvent> latch_;\n fml::TaskQueueId* dtor_task_queue_id_;\n};\n\nclass SkiaGpuObjectTest : public ThreadTest {\n public:\n SkiaGpuObjectTest()\n : unref_task_runner_(CreateNewThread()),\n unref_queue_(fml::MakeRefCounted<SkiaUnrefQueue>(\n unref_task_runner(),\n fml::TimeDelta::FromSeconds(0))),\n delayed_unref_queue_(fml::MakeRefCounted<SkiaUnrefQueue>(\n unref_task_runner(),\n fml::TimeDelta::FromSeconds(3))) {\n \/\/ The unref queues must be created in the same thread of the\n \/\/ unref_task_runner so the queue can access the same-thread-only WeakPtr of\n \/\/ the GrContext constructed during the creation.\n std::promise<bool> queuesCreated;\n unref_task_runner_->PostTask([this, &queuesCreated]() {\n unref_queue_ = fml::MakeRefCounted<SkiaUnrefQueue>(\n unref_task_runner(), fml::TimeDelta::FromSeconds(0));\n delayed_unref_queue_ = fml::MakeRefCounted<SkiaUnrefQueue>(\n unref_task_runner(), fml::TimeDelta::FromSeconds(3));\n queuesCreated.set_value(true);\n });\n queuesCreated.get_future().wait();\n ::testing::FLAGS_gtest_death_test_style = \"threadsafe\";\n }\n\n fml::RefPtr<fml::TaskRunner> unref_task_runner() {\n return unref_task_runner_;\n }\n fml::RefPtr<SkiaUnrefQueue> unref_queue() { return unref_queue_; }\n fml::RefPtr<SkiaUnrefQueue> delayed_unref_queue() {\n return delayed_unref_queue_;\n }\n\n private:\n fml::RefPtr<fml::TaskRunner> unref_task_runner_;\n fml::RefPtr<SkiaUnrefQueue> unref_queue_;\n fml::RefPtr<SkiaUnrefQueue> delayed_unref_queue_;\n};\n\nTEST_F(SkiaGpuObjectTest, QueueSimple) {\n std::shared_ptr<fml::AutoResetWaitableEvent> latch =\n std::make_shared<fml::AutoResetWaitableEvent>();\n fml::TaskQueueId dtor_task_queue_id(0);\n SkRefCnt* ref_object = new TestSkObject(latch, &dtor_task_queue_id);\n\n unref_queue()->Unref(ref_object);\n latch->Wait();\n ASSERT_EQ(dtor_task_queue_id, unref_task_runner()->GetTaskQueueId());\n}\n\nTEST_F(SkiaGpuObjectTest, ObjectDestructor) {\n std::shared_ptr<fml::AutoResetWaitableEvent> latch =\n std::make_shared<fml::AutoResetWaitableEvent>();\n fml::TaskQueueId dtor_task_queue_id(0);\n auto object = sk_make_sp<TestSkObject>(latch, &dtor_task_queue_id);\n {\n SkiaGPUObject<TestSkObject> sk_object(std::move(object), unref_queue());\n \/\/ Verify that the default SkiaGPUObject dtor queues and unref.\n }\n\n latch->Wait();\n ASSERT_EQ(dtor_task_queue_id, unref_task_runner()->GetTaskQueueId());\n}\n\nTEST_F(SkiaGpuObjectTest, ObjectReset) {\n std::shared_ptr<fml::AutoResetWaitableEvent> latch =\n std::make_shared<fml::AutoResetWaitableEvent>();\n fml::TaskQueueId dtor_task_queue_id(0);\n SkiaGPUObject<TestSkObject> sk_object(\n sk_make_sp<TestSkObject>(latch, &dtor_task_queue_id), unref_queue());\n \/\/ Verify that explicitly resetting the GPU object queues and unref.\n sk_object.reset();\n ASSERT_EQ(sk_object.get(), nullptr);\n latch->Wait();\n ASSERT_EQ(dtor_task_queue_id, unref_task_runner()->GetTaskQueueId());\n}\n\nTEST_F(SkiaGpuObjectTest, ObjectResetTwice) {\n std::shared_ptr<fml::AutoResetWaitableEvent> latch =\n std::make_shared<fml::AutoResetWaitableEvent>();\n fml::TaskQueueId dtor_task_queue_id(0);\n SkiaGPUObject<TestSkObject> sk_object(\n sk_make_sp<TestSkObject>(latch, &dtor_task_queue_id), unref_queue());\n\n sk_object.reset();\n ASSERT_EQ(sk_object.get(), nullptr);\n sk_object.reset();\n ASSERT_EQ(sk_object.get(), nullptr);\n\n latch->Wait();\n ASSERT_EQ(dtor_task_queue_id, unref_task_runner()->GetTaskQueueId());\n}\n\n} \/\/ namespace testing\n} \/\/ namespace flutter\n<|endoftext|>"} {"text":"<commit_before>\/*\n * symbols.cxx\n *\n * $Id$\n *\n *\/\n\n#include <tptlib\/symbols.h>\n#include <tptlib\/parse.h>\n\nnamespace TPTLib {\n\n\/**\n *\n * Get the value specified by id from the symbols table, recursing to\n * process embedded symbols as needed.\n *\n * @param\tid\t\tID of symbol to retrieve.\n * @return\tValue of requested symbol;\n * @return\tEmpty string when symbol not found.\n * @author\tIsaac W. Foraker\n *\n *\/\nstd::string SymbolMap::get(const std::string& id)\n{\n\t\/\/ If this is an enclosed id, strip ${};\n\tif (id[0] == '$')\n\t\treturn get(id.substr(2, id.size()-3));\n\n\t\/\/ Return symbol if no embedded id.\n\tif (id.find('$') == std::string::npos)\n\t{\n\t\tSymbolTable::const_iterator it(symmap.find(id));\n\t\tif (it == symmap.end())\n\t\t\treturn \"\";\n\t\treturn (*it).second;\n\t}\n\n\t\/\/ When an id contains an embedded ${id}, recurse and build new id.\n\tBuffer buf(id.c_str(), id.size());\n\tParser p(buf, &symmap);\n\tstd::string newid(p.run());\n\treturn get(newid);\n}\n\n\n\/**\n *\n * TODO: document function\n *\n * @param\tid\t\t\tID of the symbol to be pushed.\n * @param\tvalue\t\tValue of the symbol to be pushed.\n * @return\tnothing\n * @author\tIsaac W. Foraker\n *\n *\/\nvoid SymbolMap::set(const std::string& id, const std::string& value)\n{\n\tif (id[0] == '$')\n\t\tsymmap[id.substr(2, id.size()-3)] = value;\n\telse\n\t\tsymmap[id] = value;\n}\n\n\n\/**\n *\n * Check whether the specified id exists in the symbol table.\n *\n * @param\tid\t\t\tID of symbol to retrieve.\n * @return\ttrue if symbol exists;\n * @return\tfalse if symbol does not exist.\n * @author\tIsaac W. Foraker\n *\n *\/\nbool SymbolMap::exists(const std::string& id)\n{\n\t\/\/ If this is an enclosed id, strip ${};\n\tif (id[0] == '$')\n\t\treturn symmap.find(id.substr(2, id.size()-3)) != symmap.end();\n\treturn symmap.find(id) != symmap.end();\n}\n\n\/**\n *\n * Copy a symbol table into the symbol map, replacing any existing\n * entries.\n *\n * @param\tsymtab\t\tTable to be copied.\n * @return\tConst reference to the local symbol table.\n * @author\tIsaac W. Foraker\n *\n *\/\nconst SymbolTable& SymbolMap::operator=(const SymbolTable& symtab)\n{\n\treturn symmap = symtab;\n}\n\n\/**\n *\n * Push a symbol (id and value) onto the symbol stack.\n *\n * @param\tid\t\t\tID of the symbol to be pushed.\n * @param\tvalue\t\tValue of the symbol to be pushed.\n * @return\tnothing\n * @author\tIsaac W. Foraker\n *\n *\/\nvoid SymbolStack::push(const std::string& id, const std::string& value)\n{\n\tSymbol_t sym;\n\tsym.id = id;\n\tsym.value = value;\n\tsymstack.push(sym);\n}\n\n\n\/**\n *\n * TODO: document function\n *\n * @param\tsymmap\t\tSymbol Map to receive symbols.\n * @return\tnothing\n * @author\tIsaac W. Foraker\n *\n *\/\nvoid SymbolStack::popall(SymbolMap& symmap)\n{\n\twhile (!symstack.empty())\n\t{\n\t\tSymbol_t& sym = symstack.top();\n\t\tsymmap.set(sym.id, sym.value);\n\t}\n}\n\n} \/\/ end namespace TPTLib\n<commit_msg>checkpoint<commit_after>\/*\n * symbols.cxx\n *\n * $Id$\n *\n *\/\n\n#include <tptlib\/symbols.h>\n#include <tptlib\/parse.h>\n\nnamespace TPTLib {\n\n\/**\n *\n * Get the value specified by id from the symbols table, recursing to\n * process embedded symbols as needed.\n *\n * @param\tid\t\tID of symbol to retrieve.\n * @return\tValue of requested symbol;\n * @return\tEmpty string when symbol not found.\n * @author\tIsaac W. Foraker\n *\n *\/\nstd::string SymbolMap::get(const std::string& id)\n{\n\t\/\/ If this is an enclosed id, strip ${};\n\tif (id[0] == '$')\n\t\treturn get(id.substr(2, id.size()-3));\n\n\t\/\/ Return symbol if no embedded id.\n\tif (id.find('$') == std::string::npos)\n\t{\n\t\tSymbolTable::const_iterator it(symmap.find(id));\n\t\tif (it == symmap.end())\n\t\t\treturn \"\";\n\t\treturn (*it).second;\n\t}\n\n\t\/\/ When an id contains an embedded ${id}, recurse and build new id.\n\tBuffer buf(id.c_str(), id.size());\n\tParser p(buf, &symmap);\n\tstd::string newid(p.run());\n\treturn get(newid);\n}\n\n\n\/**\n *\n * TODO: document function\n *\n * @param\tid\t\t\tID of the symbol to be pushed.\n * @param\tvalue\t\tValue of the symbol to be pushed.\n * @return\tnothing\n * @author\tIsaac W. Foraker\n *\n *\/\nvoid SymbolMap::set(const std::string& id, const std::string& value)\n{\n\tif (id[0] == '$')\n\t\tsymmap[id.substr(2, id.size()-3)] = value;\n\telse\n\t\tsymmap[id] = value;\n}\n\n\n\/**\n *\n * Check whether the specified id exists in the symbol table.\n *\n * @param\tid\t\t\tID of symbol to retrieve.\n * @return\ttrue if symbol exists;\n * @return\tfalse if symbol does not exist.\n * @author\tIsaac W. Foraker\n *\n *\/\nbool SymbolMap::exists(const std::string& id)\n{\n\t\/\/ If this is an enclosed id, strip ${};\n\tif (id[0] == '$')\n\t\treturn symmap.find(id.substr(2, id.size()-3)) != symmap.end();\n\treturn symmap.find(id) != symmap.end();\n}\n\n\/**\n *\n * Copy a symbol table into the symbol map, replacing any existing\n * entries.\n *\n * @param\tsymtab\t\tTable to be copied.\n * @return\tConst reference to the local symbol table.\n * @author\tIsaac W. Foraker\n *\n *\/\nconst SymbolTable& SymbolMap::operator=(const SymbolTable& symtab)\n{\n\treturn symmap = symtab;\n}\n\n\/**\n *\n * Push a symbol (id and value) onto the symbol stack.\n *\n * @param\tid\t\t\tID of the symbol to be pushed.\n * @param\tvalue\t\tValue of the symbol to be pushed.\n * @return\tnothing\n * @author\tIsaac W. Foraker\n *\n *\/\nvoid SymbolStack::push(const std::string& id, const std::string& value)\n{\n\tSymbol_t sym;\n\tsym.id = id;\n\tsym.value = value;\n\tsymstack.push(sym);\n}\n\n\n\/**\n *\n * TODO: document function\n *\n * @param\tsymmap\t\tSymbol Map to receive symbols.\n * @return\tnothing\n * @author\tIsaac W. Foraker\n *\n *\/\nvoid SymbolStack::popall(SymbolMap& symmap)\n{\n\twhile (!symstack.empty())\n\t{\n\t\tSymbol_t& sym = symstack.top();\n\t\tsymstack.pop();\n\t\tsymmap.set(sym.id, sym.value);\n\t}\n}\n\n} \/\/ end namespace TPTLib\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (C) 2013-2014 Mozilla Foundation\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include <stdio.h>\n#include <fcntl.h>\n#include <errno.h>\n#include <poll.h>\n#include <pwd.h>\n#include <netinet\/in.h>\n#include <sys\/un.h>\n#include <sys\/socket.h>\n#include <sys\/stat.h>\n#include <linux\/prctl.h>\n#include <cutils\/sockets.h>\n#include <cutils\/record_stream.h>\n#include <unistd.h>\n#include <queue>\n#include <string>\n\n#include \"IpcSocketListener.h\"\n#include \"NfcIpcSocket.h\"\n#include \"MessageHandler.h\"\n#include \"NfcDebug.h\"\n\n#define NFCD_SOCKET_NAME \"nfcd\"\n#define MAX_COMMAND_BYTES (8 * 1024)\n\nusing android::Parcel;\n\nstatic int nfcdRw;\n\n\/**\n * NfcIpcSocket\n *\/\nNfcIpcSocket* NfcIpcSocket::sInstance = NULL;\n\nNfcIpcSocket* NfcIpcSocket::Instance() {\n if (!sInstance) {\n sInstance = new NfcIpcSocket();\n }\n return sInstance;\n}\n\nNfcIpcSocket::NfcIpcSocket()\n : mMsgHandler(NULL)\n{\n}\n\nNfcIpcSocket::~NfcIpcSocket()\n{\n}\n\nvoid NfcIpcSocket::Initialize(MessageHandler* aMsgHandler)\n{\n InitSocket();\n mMsgHandler = aMsgHandler;\n}\n\nvoid NfcIpcSocket::InitSocket()\n{\n mSleep_spec.tv_sec = 0;\n mSleep_spec.tv_nsec = 500 * 1000;\n mSleep_spec_rem.tv_sec = 0;\n mSleep_spec_rem.tv_nsec = 0;\n}\n\nint NfcIpcSocket::GetListenSocket() {\n const int nfcdConn = android_get_control_socket(NFCD_SOCKET_NAME);\n if (nfcdConn < 0) {\n ALOGE(\"Could not connect to %s socket: %s\\n\", NFCD_SOCKET_NAME, strerror(errno));\n return -1;\n }\n\n if (listen(nfcdConn, 4) != 0) {\n return -1;\n }\n return nfcdConn;\n}\n\nvoid NfcIpcSocket::SetSocketListener(IpcSocketListener* aListener) {\n mListener = aListener;\n}\n\nvoid NfcIpcSocket::Loop()\n{\n bool connected = false;\n int nfcdConn = -1;\n int ret;\n\n while(1) {\n struct sockaddr_un peeraddr;\n socklen_t socklen = sizeof (peeraddr);\n\n if (!connected) {\n nfcdConn = GetListenSocket();\n if (nfcdConn < 0) {\n nanosleep(&mSleep_spec, &mSleep_spec_rem);\n continue;\n }\n }\n\n nfcdRw = accept(nfcdConn, (struct sockaddr*)&peeraddr, &socklen);\n\n if (nfcdRw < 0 ) {\n ALOGE(\"Error on accept() errno:%d\", errno);\n \/* start listening for new connections again *\/\n continue;\n }\n\n ret = fcntl(nfcdRw, F_SETFL, O_NONBLOCK);\n if (ret < 0) {\n ALOGE (\"Error setting O_NONBLOCK errno:%d\", errno);\n }\n\n ALOGD(\"Socket connected\");\n connected = true;\n\n RecordStream *rs = record_stream_new(nfcdRw, MAX_COMMAND_BYTES);\n\n mListener->OnConnected();\n\n struct pollfd fds[1];\n fds[0].fd = nfcdRw;\n fds[0].events = POLLIN;\n fds[0].revents = 0;\n\n while(connected) {\n poll(fds, 1, -1);\n if(fds[0].revents > 0) {\n fds[0].revents = 0;\n\n void* data;\n size_t dataLen;\n int ret = record_stream_get_next(rs, &data, &dataLen);\n ALOGD(\" %d of bytes to be sent... data=%p ret=%d\", dataLen, data, ret);\n if (ret == 0 && data == NULL) {\n \/\/ end-of-stream\n break;\n } else if (ret < 0) {\n break;\n }\n WriteToIncomingQueue((uint8_t*)data, dataLen);\n }\n }\n record_stream_free(rs);\n close(nfcdRw);\n }\n\n return;\n}\n\n\/\/ Write NFC data to Gecko\n\/\/ Outgoing queue contain the data should be send to gecko\n\/\/ TODO check thread, this should run on the NfcService thread.\nvoid NfcIpcSocket::WriteToOutgoingQueue(uint8_t* aData, size_t aDataLen)\n{\n ALOGD(\"%s enter, data=%p, dataLen=%d\", __func__, aData, aDataLen);\n\n if (aData == NULL || aDataLen == 0) {\n return;\n }\n\n size_t writeOffset = 0;\n int written = 0;\n\n ALOGD(\"Writing %d bytes to gecko \", aDataLen);\n while (writeOffset < aDataLen) {\n do {\n written = write (nfcdRw, aData + writeOffset, aDataLen - writeOffset);\n } while (written < 0 && errno == EINTR);\n\n if (written >= 0) {\n writeOffset += written;\n } else {\n ALOGE(\"Response: unexpected error on write errno:%d\", errno);\n break;\n }\n }\n}\n\n\/\/ Write Gecko data to NFC\n\/\/ Incoming queue contains\n\/\/ TODO check thread, this should run on top of main thread of nfcd.\nvoid NfcIpcSocket::WriteToIncomingQueue(uint8_t* aData, size_t aDataLen)\n{\n ALOGD(\"%s enter, data=%p, dataLen=%d\", __func__, aData, aDataLen);\n\n if (aData != NULL && aDataLen > 0) {\n mMsgHandler->ProcessRequest(aData, aDataLen);\n }\n}\n<commit_msg>Bug 1109592: Initialize |NfcIpcSocket::mListener| in constructor<commit_after>\/*\n * Copyright (C) 2013-2014 Mozilla Foundation\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include <stdio.h>\n#include <fcntl.h>\n#include <errno.h>\n#include <poll.h>\n#include <pwd.h>\n#include <netinet\/in.h>\n#include <sys\/un.h>\n#include <sys\/socket.h>\n#include <sys\/stat.h>\n#include <linux\/prctl.h>\n#include <cutils\/sockets.h>\n#include <cutils\/record_stream.h>\n#include <unistd.h>\n#include <queue>\n#include <string>\n\n#include \"IpcSocketListener.h\"\n#include \"NfcIpcSocket.h\"\n#include \"MessageHandler.h\"\n#include \"NfcDebug.h\"\n\n#define NFCD_SOCKET_NAME \"nfcd\"\n#define MAX_COMMAND_BYTES (8 * 1024)\n\nusing android::Parcel;\n\nstatic int nfcdRw;\n\n\/**\n * NfcIpcSocket\n *\/\nNfcIpcSocket* NfcIpcSocket::sInstance = NULL;\n\nNfcIpcSocket* NfcIpcSocket::Instance() {\n if (!sInstance) {\n sInstance = new NfcIpcSocket();\n }\n return sInstance;\n}\n\nNfcIpcSocket::NfcIpcSocket()\n : mMsgHandler(NULL)\n , mListener(NULL)\n{\n}\n\nNfcIpcSocket::~NfcIpcSocket()\n{\n}\n\nvoid NfcIpcSocket::Initialize(MessageHandler* aMsgHandler)\n{\n InitSocket();\n mMsgHandler = aMsgHandler;\n}\n\nvoid NfcIpcSocket::InitSocket()\n{\n mSleep_spec.tv_sec = 0;\n mSleep_spec.tv_nsec = 500 * 1000;\n mSleep_spec_rem.tv_sec = 0;\n mSleep_spec_rem.tv_nsec = 0;\n}\n\nint NfcIpcSocket::GetListenSocket() {\n const int nfcdConn = android_get_control_socket(NFCD_SOCKET_NAME);\n if (nfcdConn < 0) {\n ALOGE(\"Could not connect to %s socket: %s\\n\", NFCD_SOCKET_NAME, strerror(errno));\n return -1;\n }\n\n if (listen(nfcdConn, 4) != 0) {\n return -1;\n }\n return nfcdConn;\n}\n\nvoid NfcIpcSocket::SetSocketListener(IpcSocketListener* aListener) {\n mListener = aListener;\n}\n\nvoid NfcIpcSocket::Loop()\n{\n bool connected = false;\n int nfcdConn = -1;\n int ret;\n\n while(1) {\n struct sockaddr_un peeraddr;\n socklen_t socklen = sizeof (peeraddr);\n\n if (!connected) {\n nfcdConn = GetListenSocket();\n if (nfcdConn < 0) {\n nanosleep(&mSleep_spec, &mSleep_spec_rem);\n continue;\n }\n }\n\n nfcdRw = accept(nfcdConn, (struct sockaddr*)&peeraddr, &socklen);\n\n if (nfcdRw < 0 ) {\n ALOGE(\"Error on accept() errno:%d\", errno);\n \/* start listening for new connections again *\/\n continue;\n }\n\n ret = fcntl(nfcdRw, F_SETFL, O_NONBLOCK);\n if (ret < 0) {\n ALOGE (\"Error setting O_NONBLOCK errno:%d\", errno);\n }\n\n ALOGD(\"Socket connected\");\n connected = true;\n\n RecordStream *rs = record_stream_new(nfcdRw, MAX_COMMAND_BYTES);\n\n mListener->OnConnected();\n\n struct pollfd fds[1];\n fds[0].fd = nfcdRw;\n fds[0].events = POLLIN;\n fds[0].revents = 0;\n\n while(connected) {\n poll(fds, 1, -1);\n if(fds[0].revents > 0) {\n fds[0].revents = 0;\n\n void* data;\n size_t dataLen;\n int ret = record_stream_get_next(rs, &data, &dataLen);\n ALOGD(\" %d of bytes to be sent... data=%p ret=%d\", dataLen, data, ret);\n if (ret == 0 && data == NULL) {\n \/\/ end-of-stream\n break;\n } else if (ret < 0) {\n break;\n }\n WriteToIncomingQueue((uint8_t*)data, dataLen);\n }\n }\n record_stream_free(rs);\n close(nfcdRw);\n }\n\n return;\n}\n\n\/\/ Write NFC data to Gecko\n\/\/ Outgoing queue contain the data should be send to gecko\n\/\/ TODO check thread, this should run on the NfcService thread.\nvoid NfcIpcSocket::WriteToOutgoingQueue(uint8_t* aData, size_t aDataLen)\n{\n ALOGD(\"%s enter, data=%p, dataLen=%d\", __func__, aData, aDataLen);\n\n if (aData == NULL || aDataLen == 0) {\n return;\n }\n\n size_t writeOffset = 0;\n int written = 0;\n\n ALOGD(\"Writing %d bytes to gecko \", aDataLen);\n while (writeOffset < aDataLen) {\n do {\n written = write (nfcdRw, aData + writeOffset, aDataLen - writeOffset);\n } while (written < 0 && errno == EINTR);\n\n if (written >= 0) {\n writeOffset += written;\n } else {\n ALOGE(\"Response: unexpected error on write errno:%d\", errno);\n break;\n }\n }\n}\n\n\/\/ Write Gecko data to NFC\n\/\/ Incoming queue contains\n\/\/ TODO check thread, this should run on top of main thread of nfcd.\nvoid NfcIpcSocket::WriteToIncomingQueue(uint8_t* aData, size_t aDataLen)\n{\n ALOGD(\"%s enter, data=%p, dataLen=%d\", __func__, aData, aDataLen);\n\n if (aData != NULL && aDataLen > 0) {\n mMsgHandler->ProcessRequest(aData, aDataLen);\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2017-2019 The Dash Core developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include <evo\/cbtx.h>\n#include <evo\/deterministicmns.h>\n#include <llmq\/quorums_blockprocessor.h>\n#include <llmq\/quorums_commitment.h>\n#include <evo\/simplifiedmns.h>\n#include <evo\/specialtx.h>\n\n#include <chainparams.h>\n#include <consensus\/merkle.h>\n#include <validation.h>\n\nbool CheckCbTx(const CTransaction& tx, const CBlockIndex* pindexPrev, CValidationState& state)\n{\n if (tx.nType != TRANSACTION_COINBASE) {\n return state.DoS(100, false, REJECT_INVALID, \"bad-cbtx-type\");\n }\n\n if (!tx.IsCoinBase()) {\n return state.DoS(100, false, REJECT_INVALID, \"bad-cbtx-invalid\");\n }\n\n CCbTx cbTx;\n if (!GetTxPayload(tx, cbTx)) {\n return state.DoS(100, false, REJECT_INVALID, \"bad-cbtx-payload\");\n }\n\n if (cbTx.nVersion == 0 || cbTx.nVersion > CCbTx::CURRENT_VERSION) {\n return state.DoS(100, false, REJECT_INVALID, \"bad-cbtx-version\");\n }\n\n if (pindexPrev && pindexPrev->nHeight + 1 != cbTx.nHeight) {\n return state.DoS(100, false, REJECT_INVALID, \"bad-cbtx-height\");\n }\n\n if (pindexPrev) {\n bool fDIP0008Active = VersionBitsState(pindexPrev, Params().GetConsensus(), Consensus::DEPLOYMENT_DIP0008, versionbitscache) == ThresholdState::ACTIVE;\n if (fDIP0008Active && cbTx.nVersion < 2) {\n return state.DoS(100, false, REJECT_INVALID, \"bad-cbtx-version\");\n }\n }\n\n return true;\n}\n\n\/\/ This can only be done after the block has been fully processed, as otherwise we won't have the finished MN list\nbool CheckCbTxMerkleRoots(const CBlock& block, const CBlockIndex* pindex, CValidationState& state)\n{\n if (block.vtx[0]->nType != TRANSACTION_COINBASE) {\n return true;\n }\n\n static int64_t nTimePayload = 0;\n static int64_t nTimeMerkleMNL = 0;\n static int64_t nTimeMerkleQuorum = 0;\n\n int64_t nTime1 = GetTimeMicros();\n\n CCbTx cbTx;\n if (!GetTxPayload(*block.vtx[0], cbTx)) {\n return state.DoS(100, false, REJECT_INVALID, \"bad-cbtx-payload\");\n }\n\n int64_t nTime2 = GetTimeMicros(); nTimePayload += nTime2 - nTime1;\n LogPrint(BCLog::BENCHMARK, \" - GetTxPayload: %.2fms [%.2fs]\\n\", 0.001 * (nTime2 - nTime1), nTimePayload * 0.000001);\n\n if (pindex) {\n uint256 calculatedMerkleRoot;\n if (!CalcCbTxMerkleRootMNList(block, pindex->pprev, calculatedMerkleRoot, state)) {\n \/\/ pass the state returned by the function above\n return false;\n }\n if (calculatedMerkleRoot != cbTx.merkleRootMNList) {\n return state.DoS(100, false, REJECT_INVALID, \"bad-cbtx-mnmerkleroot\");\n }\n\n int64_t nTime3 = GetTimeMicros(); nTimeMerkleMNL += nTime3 - nTime2;\n LogPrint(BCLog::BENCHMARK, \" - CalcCbTxMerkleRootMNList: %.2fms [%.2fs]\\n\", 0.001 * (nTime3 - nTime2), nTimeMerkleMNL * 0.000001);\n\n if (cbTx.nVersion >= 2) {\n if (!CalcCbTxMerkleRootQuorums(block, pindex->pprev, calculatedMerkleRoot, state)) {\n \/\/ pass the state returned by the function above\n return false;\n }\n if (calculatedMerkleRoot != cbTx.merkleRootQuorums) {\n return state.DoS(100, false, REJECT_INVALID, \"bad-cbtx-quorummerkleroot\");\n }\n }\n\n int64_t nTime4 = GetTimeMicros(); nTimeMerkleQuorum += nTime4 - nTime3;\n LogPrint(BCLog::BENCHMARK, \" - CalcCbTxMerkleRootQuorums: %.2fms [%.2fs]\\n\", 0.001 * (nTime4 - nTime3), nTimeMerkleQuorum * 0.000001);\n\n }\n\n return true;\n}\n\nbool CalcCbTxMerkleRootMNList(const CBlock& block, const CBlockIndex* pindexPrev, uint256& merkleRootRet, CValidationState& state)\n{\n LOCK(deterministicMNManager->cs);\n\n static int64_t nTimeDMN = 0;\n static int64_t nTimeSMNL = 0;\n static int64_t nTimeMerkle = 0;\n\n int64_t nTime1 = GetTimeMicros();\n\n try {\n CDeterministicMNList tmpMNList;\n if (!deterministicMNManager->BuildNewListFromBlock(block, pindexPrev, state, tmpMNList, false)) {\n \/\/ pass the state returned by the function above\n return false;\n }\n\n int64_t nTime2 = GetTimeMicros(); nTimeDMN += nTime2 - nTime1;\n LogPrint(BCLog::BENCHMARK, \" - BuildNewListFromBlock: %.2fms [%.2fs]\\n\", 0.001 * (nTime2 - nTime1), nTimeDMN * 0.000001);\n\n CSimplifiedMNList sml(tmpMNList);\n\n int64_t nTime3 = GetTimeMicros(); nTimeSMNL += nTime3 - nTime2;\n LogPrint(BCLog::BENCHMARK, \" - CSimplifiedMNList: %.2fms [%.2fs]\\n\", 0.001 * (nTime3 - nTime2), nTimeSMNL * 0.000001);\n\n static CSimplifiedMNList smlCached;\n static uint256 merkleRootCached;\n static bool mutatedCached{false};\n\n if (sml.mnList == smlCached.mnList) {\n merkleRootRet = merkleRootCached;\n if (mutatedCached) {\n return state.DoS(100, false, REJECT_INVALID, \"mutated-cached-calc-cb-mnmerkleroot\");\n }\n return true;\n }\n\n bool mutated = false;\n merkleRootRet = sml.CalcMerkleRoot(&mutated);\n\n int64_t nTime4 = GetTimeMicros(); nTimeMerkle += nTime4 - nTime3;\n LogPrint(BCLog::BENCHMARK, \" - CalcMerkleRoot: %.2fms [%.2fs]\\n\", 0.001 * (nTime4 - nTime3), nTimeMerkle * 0.000001);\n\n smlCached = std::move(sml);\n merkleRootCached = merkleRootRet;\n mutatedCached = mutated;\n\n if (mutated) {\n return state.DoS(100, false, REJECT_INVALID, \"mutated-calc-cb-mnmerkleroot\");\n }\n\n return true;\n } catch (const std::exception& e) {\n LogPrintf(\"%s -- failed: %s\\n\", __func__, e.what());\n return state.DoS(100, false, REJECT_INVALID, \"failed-calc-cb-mnmerkleroot\");\n }\n}\n\nbool CalcCbTxMerkleRootQuorums(const CBlock& block, const CBlockIndex* pindexPrev, uint256& merkleRootRet, CValidationState& state)\n{\n static int64_t nTimeMinedAndActive = 0;\n static int64_t nTimeMined = 0;\n static int64_t nTimeLoop = 0;\n static int64_t nTimeMerkle = 0;\n\n int64_t nTime1 = GetTimeMicros();\n\n static std::map<Consensus::LLMQType, std::vector<const CBlockIndex*>> quorumsCached;\n static std::map<Consensus::LLMQType, std::vector<uint256>> qcHashesCached;\n\n \/\/ The returned quorums are in reversed order, so the most recent one is at index 0\n auto quorums = llmq::quorumBlockProcessor->GetMinedAndActiveCommitmentsUntilBlock(pindexPrev);\n std::map<Consensus::LLMQType, std::vector<uint256>> qcHashes;\n size_t hashCount = 0;\n\n int64_t nTime2 = GetTimeMicros(); nTimeMinedAndActive += nTime2 - nTime1;\n LogPrint(BCLog::BENCHMARK, \" - GetMinedAndActiveCommitmentsUntilBlock: %.2fms [%.2fs]\\n\", 0.001 * (nTime2 - nTime1), nTimeMinedAndActive * 0.000001);\n\n if (quorums == quorumsCached) {\n qcHashes = qcHashesCached;\n } else {\n for (const auto& p : quorums) {\n auto& v = qcHashes[p.first];\n v.reserve(p.second.size());\n for (const auto& p2 : p.second) {\n llmq::CFinalCommitment qc;\n uint256 minedBlockHash;\n bool found = llmq::quorumBlockProcessor->GetMinedCommitment(p.first, p2->GetBlockHash(), qc, minedBlockHash);\n if (!found) return state.DoS(100, false, REJECT_INVALID, \"commitment-not-found\");\n v.emplace_back(::SerializeHash(qc));\n hashCount++;\n }\n }\n quorumsCached = quorums;\n qcHashesCached = qcHashes;\n }\n\n int64_t nTime3 = GetTimeMicros(); nTimeMined += nTime3 - nTime2;\n LogPrint(BCLog::BENCHMARK, \" - GetMinedCommitment: %.2fms [%.2fs]\\n\", 0.001 * (nTime3 - nTime2), nTimeMined * 0.000001);\n\n \/\/ now add the commitments from the current block, which are not returned by GetMinedAndActiveCommitmentsUntilBlock\n \/\/ due to the use of pindexPrev (we don't have the tip index here)\n for (size_t i = 1; i < block.vtx.size(); i++) {\n auto& tx = block.vtx[i];\n\n if (tx->nVersion == 3 && tx->nType == TRANSACTION_QUORUM_COMMITMENT) {\n llmq::CFinalCommitmentTxPayload qc;\n if (!GetTxPayload(*tx, qc)) {\n return state.DoS(100, false, REJECT_INVALID, \"bad-qc-payload-calc-cbtx-quorummerkleroot\");\n }\n if (qc.commitment.IsNull()) {\n continue;\n }\n auto qcHash = ::SerializeHash(qc.commitment);\n const auto& params = Params().GetConsensus().llmqs.at((Consensus::LLMQType)qc.commitment.llmqType);\n auto& v = qcHashes[params.type];\n if (v.size() == params.signingActiveQuorumCount) {\n \/\/ we pop the last entry, which is actually the oldest quorum as GetMinedAndActiveCommitmentsUntilBlock\n \/\/ returned quorums in reversed order. This pop and later push can only work ONCE, but we rely on the\n \/\/ fact that a block can only contain a single commitment for one LLMQ type\n v.pop_back();\n }\n v.emplace_back(qcHash);\n hashCount++;\n if (v.size() > params.signingActiveQuorumCount) {\n return state.DoS(100, false, REJECT_INVALID, \"excess-quorums-calc-cbtx-quorummerkleroot\");\n }\n }\n }\n\n std::vector<uint256> qcHashesVec;\n qcHashesVec.reserve(hashCount);\n\n for (const auto& p : qcHashes) {\n for (const auto& h : p.second) {\n qcHashesVec.emplace_back(h);\n }\n }\n std::sort(qcHashesVec.begin(), qcHashesVec.end());\n\n int64_t nTime4 = GetTimeMicros(); nTimeLoop += nTime4 - nTime3;\n LogPrint(BCLog::BENCHMARK, \" - Loop: %.2fms [%.2fs]\\n\", 0.001 * (nTime4 - nTime3), nTimeLoop * 0.000001);\n\n bool mutated = false;\n merkleRootRet = ComputeMerkleRoot(qcHashesVec, &mutated);\n\n int64_t nTime5 = GetTimeMicros(); nTimeMerkle += nTime5 - nTime4;\n LogPrint(BCLog::BENCHMARK, \" - ComputeMerkleRoot: %.2fms [%.2fs]\\n\", 0.001 * (nTime5 - nTime4), nTimeMerkle * 0.000001);\n\n if (mutated) {\n return state.DoS(100, false, REJECT_INVALID, \"mutated-calc-cbtx-quorummerkleroot\");\n }\n\n return true;\n}\n\nstd::string CCbTx::ToString() const\n{\n return strprintf(\"CCbTx(nHeight=%d, nVersion=%d, merkleRootMNList=%s, merkleRootQuorums=%s)\",\n nVersion, nHeight, merkleRootMNList.ToString(), merkleRootQuorums.ToString());\n}\n<commit_msg>fix ToString bug in cbtx.cpp (#3807)<commit_after>\/\/ Copyright (c) 2017-2019 The Dash Core developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include <evo\/cbtx.h>\n#include <evo\/deterministicmns.h>\n#include <llmq\/quorums_blockprocessor.h>\n#include <llmq\/quorums_commitment.h>\n#include <evo\/simplifiedmns.h>\n#include <evo\/specialtx.h>\n\n#include <chainparams.h>\n#include <consensus\/merkle.h>\n#include <validation.h>\n\nbool CheckCbTx(const CTransaction& tx, const CBlockIndex* pindexPrev, CValidationState& state)\n{\n if (tx.nType != TRANSACTION_COINBASE) {\n return state.DoS(100, false, REJECT_INVALID, \"bad-cbtx-type\");\n }\n\n if (!tx.IsCoinBase()) {\n return state.DoS(100, false, REJECT_INVALID, \"bad-cbtx-invalid\");\n }\n\n CCbTx cbTx;\n if (!GetTxPayload(tx, cbTx)) {\n return state.DoS(100, false, REJECT_INVALID, \"bad-cbtx-payload\");\n }\n\n if (cbTx.nVersion == 0 || cbTx.nVersion > CCbTx::CURRENT_VERSION) {\n return state.DoS(100, false, REJECT_INVALID, \"bad-cbtx-version\");\n }\n\n if (pindexPrev && pindexPrev->nHeight + 1 != cbTx.nHeight) {\n return state.DoS(100, false, REJECT_INVALID, \"bad-cbtx-height\");\n }\n\n if (pindexPrev) {\n bool fDIP0008Active = VersionBitsState(pindexPrev, Params().GetConsensus(), Consensus::DEPLOYMENT_DIP0008, versionbitscache) == ThresholdState::ACTIVE;\n if (fDIP0008Active && cbTx.nVersion < 2) {\n return state.DoS(100, false, REJECT_INVALID, \"bad-cbtx-version\");\n }\n }\n\n return true;\n}\n\n\/\/ This can only be done after the block has been fully processed, as otherwise we won't have the finished MN list\nbool CheckCbTxMerkleRoots(const CBlock& block, const CBlockIndex* pindex, CValidationState& state)\n{\n if (block.vtx[0]->nType != TRANSACTION_COINBASE) {\n return true;\n }\n\n static int64_t nTimePayload = 0;\n static int64_t nTimeMerkleMNL = 0;\n static int64_t nTimeMerkleQuorum = 0;\n\n int64_t nTime1 = GetTimeMicros();\n\n CCbTx cbTx;\n if (!GetTxPayload(*block.vtx[0], cbTx)) {\n return state.DoS(100, false, REJECT_INVALID, \"bad-cbtx-payload\");\n }\n\n int64_t nTime2 = GetTimeMicros(); nTimePayload += nTime2 - nTime1;\n LogPrint(BCLog::BENCHMARK, \" - GetTxPayload: %.2fms [%.2fs]\\n\", 0.001 * (nTime2 - nTime1), nTimePayload * 0.000001);\n\n if (pindex) {\n uint256 calculatedMerkleRoot;\n if (!CalcCbTxMerkleRootMNList(block, pindex->pprev, calculatedMerkleRoot, state)) {\n \/\/ pass the state returned by the function above\n return false;\n }\n if (calculatedMerkleRoot != cbTx.merkleRootMNList) {\n return state.DoS(100, false, REJECT_INVALID, \"bad-cbtx-mnmerkleroot\");\n }\n\n int64_t nTime3 = GetTimeMicros(); nTimeMerkleMNL += nTime3 - nTime2;\n LogPrint(BCLog::BENCHMARK, \" - CalcCbTxMerkleRootMNList: %.2fms [%.2fs]\\n\", 0.001 * (nTime3 - nTime2), nTimeMerkleMNL * 0.000001);\n\n if (cbTx.nVersion >= 2) {\n if (!CalcCbTxMerkleRootQuorums(block, pindex->pprev, calculatedMerkleRoot, state)) {\n \/\/ pass the state returned by the function above\n return false;\n }\n if (calculatedMerkleRoot != cbTx.merkleRootQuorums) {\n return state.DoS(100, false, REJECT_INVALID, \"bad-cbtx-quorummerkleroot\");\n }\n }\n\n int64_t nTime4 = GetTimeMicros(); nTimeMerkleQuorum += nTime4 - nTime3;\n LogPrint(BCLog::BENCHMARK, \" - CalcCbTxMerkleRootQuorums: %.2fms [%.2fs]\\n\", 0.001 * (nTime4 - nTime3), nTimeMerkleQuorum * 0.000001);\n\n }\n\n return true;\n}\n\nbool CalcCbTxMerkleRootMNList(const CBlock& block, const CBlockIndex* pindexPrev, uint256& merkleRootRet, CValidationState& state)\n{\n LOCK(deterministicMNManager->cs);\n\n static int64_t nTimeDMN = 0;\n static int64_t nTimeSMNL = 0;\n static int64_t nTimeMerkle = 0;\n\n int64_t nTime1 = GetTimeMicros();\n\n try {\n CDeterministicMNList tmpMNList;\n if (!deterministicMNManager->BuildNewListFromBlock(block, pindexPrev, state, tmpMNList, false)) {\n \/\/ pass the state returned by the function above\n return false;\n }\n\n int64_t nTime2 = GetTimeMicros(); nTimeDMN += nTime2 - nTime1;\n LogPrint(BCLog::BENCHMARK, \" - BuildNewListFromBlock: %.2fms [%.2fs]\\n\", 0.001 * (nTime2 - nTime1), nTimeDMN * 0.000001);\n\n CSimplifiedMNList sml(tmpMNList);\n\n int64_t nTime3 = GetTimeMicros(); nTimeSMNL += nTime3 - nTime2;\n LogPrint(BCLog::BENCHMARK, \" - CSimplifiedMNList: %.2fms [%.2fs]\\n\", 0.001 * (nTime3 - nTime2), nTimeSMNL * 0.000001);\n\n static CSimplifiedMNList smlCached;\n static uint256 merkleRootCached;\n static bool mutatedCached{false};\n\n if (sml.mnList == smlCached.mnList) {\n merkleRootRet = merkleRootCached;\n if (mutatedCached) {\n return state.DoS(100, false, REJECT_INVALID, \"mutated-cached-calc-cb-mnmerkleroot\");\n }\n return true;\n }\n\n bool mutated = false;\n merkleRootRet = sml.CalcMerkleRoot(&mutated);\n\n int64_t nTime4 = GetTimeMicros(); nTimeMerkle += nTime4 - nTime3;\n LogPrint(BCLog::BENCHMARK, \" - CalcMerkleRoot: %.2fms [%.2fs]\\n\", 0.001 * (nTime4 - nTime3), nTimeMerkle * 0.000001);\n\n smlCached = std::move(sml);\n merkleRootCached = merkleRootRet;\n mutatedCached = mutated;\n\n if (mutated) {\n return state.DoS(100, false, REJECT_INVALID, \"mutated-calc-cb-mnmerkleroot\");\n }\n\n return true;\n } catch (const std::exception& e) {\n LogPrintf(\"%s -- failed: %s\\n\", __func__, e.what());\n return state.DoS(100, false, REJECT_INVALID, \"failed-calc-cb-mnmerkleroot\");\n }\n}\n\nbool CalcCbTxMerkleRootQuorums(const CBlock& block, const CBlockIndex* pindexPrev, uint256& merkleRootRet, CValidationState& state)\n{\n static int64_t nTimeMinedAndActive = 0;\n static int64_t nTimeMined = 0;\n static int64_t nTimeLoop = 0;\n static int64_t nTimeMerkle = 0;\n\n int64_t nTime1 = GetTimeMicros();\n\n static std::map<Consensus::LLMQType, std::vector<const CBlockIndex*>> quorumsCached;\n static std::map<Consensus::LLMQType, std::vector<uint256>> qcHashesCached;\n\n \/\/ The returned quorums are in reversed order, so the most recent one is at index 0\n auto quorums = llmq::quorumBlockProcessor->GetMinedAndActiveCommitmentsUntilBlock(pindexPrev);\n std::map<Consensus::LLMQType, std::vector<uint256>> qcHashes;\n size_t hashCount = 0;\n\n int64_t nTime2 = GetTimeMicros(); nTimeMinedAndActive += nTime2 - nTime1;\n LogPrint(BCLog::BENCHMARK, \" - GetMinedAndActiveCommitmentsUntilBlock: %.2fms [%.2fs]\\n\", 0.001 * (nTime2 - nTime1), nTimeMinedAndActive * 0.000001);\n\n if (quorums == quorumsCached) {\n qcHashes = qcHashesCached;\n } else {\n for (const auto& p : quorums) {\n auto& v = qcHashes[p.first];\n v.reserve(p.second.size());\n for (const auto& p2 : p.second) {\n llmq::CFinalCommitment qc;\n uint256 minedBlockHash;\n bool found = llmq::quorumBlockProcessor->GetMinedCommitment(p.first, p2->GetBlockHash(), qc, minedBlockHash);\n if (!found) return state.DoS(100, false, REJECT_INVALID, \"commitment-not-found\");\n v.emplace_back(::SerializeHash(qc));\n hashCount++;\n }\n }\n quorumsCached = quorums;\n qcHashesCached = qcHashes;\n }\n\n int64_t nTime3 = GetTimeMicros(); nTimeMined += nTime3 - nTime2;\n LogPrint(BCLog::BENCHMARK, \" - GetMinedCommitment: %.2fms [%.2fs]\\n\", 0.001 * (nTime3 - nTime2), nTimeMined * 0.000001);\n\n \/\/ now add the commitments from the current block, which are not returned by GetMinedAndActiveCommitmentsUntilBlock\n \/\/ due to the use of pindexPrev (we don't have the tip index here)\n for (size_t i = 1; i < block.vtx.size(); i++) {\n auto& tx = block.vtx[i];\n\n if (tx->nVersion == 3 && tx->nType == TRANSACTION_QUORUM_COMMITMENT) {\n llmq::CFinalCommitmentTxPayload qc;\n if (!GetTxPayload(*tx, qc)) {\n return state.DoS(100, false, REJECT_INVALID, \"bad-qc-payload-calc-cbtx-quorummerkleroot\");\n }\n if (qc.commitment.IsNull()) {\n continue;\n }\n auto qcHash = ::SerializeHash(qc.commitment);\n const auto& params = Params().GetConsensus().llmqs.at((Consensus::LLMQType)qc.commitment.llmqType);\n auto& v = qcHashes[params.type];\n if (v.size() == params.signingActiveQuorumCount) {\n \/\/ we pop the last entry, which is actually the oldest quorum as GetMinedAndActiveCommitmentsUntilBlock\n \/\/ returned quorums in reversed order. This pop and later push can only work ONCE, but we rely on the\n \/\/ fact that a block can only contain a single commitment for one LLMQ type\n v.pop_back();\n }\n v.emplace_back(qcHash);\n hashCount++;\n if (v.size() > params.signingActiveQuorumCount) {\n return state.DoS(100, false, REJECT_INVALID, \"excess-quorums-calc-cbtx-quorummerkleroot\");\n }\n }\n }\n\n std::vector<uint256> qcHashesVec;\n qcHashesVec.reserve(hashCount);\n\n for (const auto& p : qcHashes) {\n for (const auto& h : p.second) {\n qcHashesVec.emplace_back(h);\n }\n }\n std::sort(qcHashesVec.begin(), qcHashesVec.end());\n\n int64_t nTime4 = GetTimeMicros(); nTimeLoop += nTime4 - nTime3;\n LogPrint(BCLog::BENCHMARK, \" - Loop: %.2fms [%.2fs]\\n\", 0.001 * (nTime4 - nTime3), nTimeLoop * 0.000001);\n\n bool mutated = false;\n merkleRootRet = ComputeMerkleRoot(qcHashesVec, &mutated);\n\n int64_t nTime5 = GetTimeMicros(); nTimeMerkle += nTime5 - nTime4;\n LogPrint(BCLog::BENCHMARK, \" - ComputeMerkleRoot: %.2fms [%.2fs]\\n\", 0.001 * (nTime5 - nTime4), nTimeMerkle * 0.000001);\n\n if (mutated) {\n return state.DoS(100, false, REJECT_INVALID, \"mutated-calc-cbtx-quorummerkleroot\");\n }\n\n return true;\n}\n\nstd::string CCbTx::ToString() const\n{\n return strprintf(\"CCbTx(nVersion=%d, nHeight=%d, merkleRootMNList=%s, merkleRootQuorums=%s)\",\n nVersion, nHeight, merkleRootMNList.ToString(), merkleRootQuorums.ToString());\n}\n<|endoftext|>"} {"text":"<commit_before>#ifndef DUNE_DETAILED_DISCRETIZATIONS_DISCRETEFUNCTION_DEFAULT_HH\n#define DUNE_DETAILED_DISCRETIZATIONS_DISCRETEFUNCTION_DEFAULT_HH\n\n#ifdef HAVE_CMAKE_CONFIG\n#include \"cmake_config.h\"\n#elif defined(HAVE_CONFIG_H)\n#include \"config.h\"\n#endif\n\n#include <memory>\n\n#include <dune\/common\/exceptions.hh>\n#include <dune\/common\/fvector.hh>\n\n#include <dune\/grid\/io\/file\/vtk\/function.hh>\n\n#include <dune\/stuff\/la\/container\/interface.hh>\n\n#include <dune\/detailed\/discretizations\/space\/interface.hh>\n\n#include \"local.hh\"\n\nnamespace Dune {\nnamespace Detailed {\nnamespace Discretizations {\n\n\n\/\/ template< class DiscreteFunctionSpaceImp, class VectorImp >\n\/\/ class DefaultConst;\n\n\n\/\/ template< class DiscreteFunctionSpaceImp, class VectorImp >\n\/\/ class Default\n\/\/ : public Dune::VTKFunction< typename DiscreteFunctionSpaceImp::GridViewType >\n\/\/{\n\/\/ private:\n\/\/ typedef Dune::VTKFunction< typename DiscreteFunctionSpaceImp::GridViewType > BaseType;\n\n\/\/ public:\n\/\/ typedef DiscreteFunctionSpaceImp DiscreteFunctionSpaceType;\n\n\/\/ typedef VectorImp VectorType;\n\n\/\/ typedef Default< DiscreteFunctionSpaceType, VectorType > ThisType;\n\n\/\/ typedef DefaultConst< DiscreteFunctionSpaceType, VectorType > ConstType;\n\n\/\/ typedef typename DiscreteFunctionSpaceType::GridViewType::template Codim< 0 >::Iterator::Entity EntityType;\n\n\/\/ static const int polOrder = DiscreteFunctionSpaceType::polynomialOrder;\n\n\/\/ typedef Dune::Detailed::Discretizations::DiscreteFunction::LocalConst< ThisType > ConstLocalFunctionType;\n\n\/\/ typedef Dune::Detailed::Discretizations::DiscreteFunction::Local< ThisType > LocalFunctionType;\n\n\/\/ typedef typename DiscreteFunctionSpaceType::FunctionSpaceType FunctionSpaceType;\n\n\/\/ typedef typename FunctionSpaceType::DomainType DomainType;\n\n\/\/ typedef typename FunctionSpaceType::RangeFieldType RangeFieldType;\n\n\/\/ typedef typename FunctionSpaceType::RangeType RangeType;\n\n\/\/ static const int dimDomain = DiscreteFunctionSpaceType::dimDomain;\n\n\/\/ static const int dimRange = DiscreteFunctionSpaceType::dimRange;\n\n\/\/ typedef typename VectorType::size_type size_type;\n\n\/\/ Default(const DiscreteFunctionSpaceType& _space,\n\/\/ std::shared_ptr< VectorType > _vector,\n\/\/ const std::string _name = \"discrete_function\")\n\/\/ : BaseType(),\n\/\/ space_(_space)\n\/\/ , vector_(_vector)\n\/\/ , name_(_name)\n\/\/ {\n\/\/ assert(vector_->size() == space_.map().size() && \"Given vector has wrong size!\");\n\/\/ }\n\n\/\/ Default(const DiscreteFunctionSpaceType& _space,\n\/\/ const std::string _name = \"discrete_function\")\n\/\/ : BaseType(),\n\/\/ space_(_space)\n\/\/ , vector_(new VectorType(space_.map().size()))\n\/\/ , name_(_name)\n\/\/ {\n\/\/ assert(vector_->size() == space_.map().size() && \"Given vector has wrong size!\");\n\/\/ }\n\n\/\/ std::shared_ptr< const ConstType > createConst() const\n\/\/ {\n\/\/ std::shared_ptr< const ConstType > ret(new ConstType(*this));\n\/\/ return ret;\n\/\/ }\n\n\/\/ private:\n\/\/ Default(const ThisType&);\n\/\/ ThisType& operator=(const ThisType&);\n\n\/\/ public:\n\/\/ const DiscreteFunctionSpaceType& space() const\n\/\/ {\n\/\/ return space_;\n\/\/ }\n\n\/\/ virtual std::string name() const\n\/\/ {\n\/\/ return name_;\n\/\/ }\n\n\/\/ ConstLocalFunctionType localFunction(const EntityType& entity) const\n\/\/ {\n\/\/ return ConstLocalFunctionType(*this, entity);\n\/\/ }\n\n\/\/ LocalFunctionType localFunction(const EntityType& entity)\n\/\/ {\n\/\/ return LocalFunctionType(*this, entity);\n\/\/ }\n\n\/\/ std::shared_ptr< VectorType > vector()\n\/\/ {\n\/\/ return vector_;\n\/\/ }\n\n\/\/ const std::shared_ptr< const VectorType > vector() const\n\/\/ {\n\/\/ return vector_;\n\/\/ }\n\n\/\/ \/**\n\/\/ @name Convenience methods\n\/\/ @{\n\/\/ **\/\n\/\/ size_type size() const\n\/\/ {\n\/\/ return vector_->size();\n\/\/ }\n\/\/ \/**\n\/\/ @}\n\/\/ **\/\n\n\/\/ void clear()\n\/\/ {\n\/\/ const RangeFieldType zero(0);\n\/\/ for (size_type ii = 0; ii < vector_->size(); ++ii)\n\/\/ vector_->set(ii, zero);\n\/\/ }\n\n\/\/ \/**\n\/\/ @name Methods to comply with the Dune::VTKFunction interface\n\/\/ @{\n\/\/ **\/\n\/\/ virtual int ncomps() const\n\/\/ {\n\/\/ return dimRange;\n\/\/ }\n\n\/\/ virtual double evaluate(int component, const EntityType& entity, const DomainType& x) const\n\/\/ {\n\/\/ assert(vector_->size() == space_.map().size() && \"Given vector has wrong size!\");\n\/\/ RangeType ret(0.0);\n\/\/ localFunction(entity).evaluate(x, ret);\n\/\/ return ret[component];\n\/\/ }\n\/\/ \/**\n\/\/ @}\n\/\/ **\/\n\n\/\/ private:\n\/\/ const DiscreteFunctionSpaceType& space_;\n\/\/ std::shared_ptr< VectorType > vector_;\n\/\/ const std::string name_;\n\/\/}; \/\/ class Defaul\n\n\ntemplate <class SpaceImp, class VectorImp>\nclass DiscreteFunctionDefaultConst : public Dune::VTKFunction<typename SpaceImp::GridPartType::GridViewType>,\n public Dune::Stuff::LocalizableFunction\n{\npublic:\n typedef typename SpaceInterface<typename SpaceImp::Traits>::derived_type SpaceType;\n typedef typename Dune::Stuff::LA::VectorInterface<typename VectorImp::Traits>::derived_type VectorType;\n\n typedef typename SpaceType::EntityType EntityType;\n\n typedef DiscreteFunctionLocalConst<SpaceType, VectorType> ConstLocalFunctionType;\n typedef typename ConstLocalFunctionType::DomainType DomainType;\n typedef typename ConstLocalFunctionType::RangeType RangeType;\n\n DiscreteFunctionDefaultConst(const SpaceType& sp, const std::shared_ptr<const VectorType> vec,\n const std::string nm = \"discrete_function\")\n : \/*BaseType()\n , *\/ space_(sp)\n , name_(nm)\n , vector_(vec)\n {\n assert(vector_->size() == space_.mapper().size() && \"Given vector has wrong size!\");\n }\n\n const SpaceType& space() const\n {\n return space_;\n }\n\n virtual std::string name() const\n {\n return name_;\n }\n\n ConstLocalFunctionType localFunction(const EntityType& entity) const\n {\n return ConstLocalFunctionType(*this, entity);\n }\n\n const std::shared_ptr<const VectorType> vector() const\n {\n return vector_;\n }\n\n \/** \\defgroup vtk ´´Methods to comply with the Dune::VTKFunction interface.'' *\/\n \/* @{ *\/\n virtual int ncomps() const\n {\n return SpaceType::dimRange;\n }\n\n virtual double evaluate(int component, const EntityType& entity, const DomainType& x) const\n {\n RangeType ret(0);\n localFunction(entity).evaluate(x, ret);\n return ret[component];\n }\n \/* @} *\/\n\nprivate:\n const SpaceType& space_;\n const std::string name_;\n const std::shared_ptr<const VectorType> vector_;\n}; \/\/ class DiscreteFunctionDefaultConst\n\n\ntemplate <class SpaceImp, class VectorImp>\nclass DiscreteFunctionDefault : public DiscreteFunctionDefaultConst<SpaceImp, VectorImp>\n{\n typedef DiscreteFunctionDefaultConst<SpaceImp, VectorImp> BaseType;\n\npublic:\n typedef typename SpaceInterface<typename SpaceImp::Traits>::derived_type SpaceType;\n typedef typename Dune::Stuff::LA::VectorInterface<typename VectorImp::Traits>::derived_type VectorType;\n\n typedef typename SpaceType::EntityType EntityType;\n\n typedef DiscreteFunctionLocal<SpaceType, VectorType> LocalFunctionType;\n typedef typename LocalFunctionType::DomainType DomainType;\n\n DiscreteFunctionDefault(const SpaceType& sp, std::shared_ptr<VectorType> vec,\n const std::string nm = \"discrete_function\")\n : BaseType(sp, vec, nm)\n , nonConstVector_(vec)\n {\n }\n\n \/\/ DiscreteFunctionDefault(const SpaceType& sp,\n \/\/ const std::string nm = \"discrete_function\")\n \/\/ : nonConstVector_(std::make_shared< VectorType >(sp.mapper().size()))\n \/\/ , BaseType(sp, nonConstVector_, nm)\n \/\/ {}\n\n LocalFunctionType localFunction(const EntityType& entity)\n {\n return LocalFunctionType(*this, entity);\n }\n\n std::shared_ptr<VectorType> vector()\n {\n return nonConstVector_;\n }\n\n \/\/ virtual std::string name() const\n \/\/ {\n \/\/ return BaseType::name();\n \/\/ }\n\n \/\/ \/** \\defgroup vtk ´´Methods to comply with the Dune::VTKFunction interface.'' *\/\n \/\/ \/* @{ *\/\n \/\/ virtual int ncomps() const\n \/\/ {\n \/\/ return BaseType::ncomps();\n \/\/ }\n\n \/\/ virtual double evaluate(int component, const EntityType& entity, const DomainType& x) const\n \/\/ {\n \/\/ BaseType::evaluate(component, entity, x);\n \/\/ }\n \/\/ \/* @} *\/\n\nprivate:\n std::shared_ptr<VectorType> nonConstVector_;\n}; \/\/ class DiscreteFunctionDefault\n\n\n} \/\/ namespace Discretizations\n} \/\/ namespace Detailed\n} \/\/ namespace Dune\n\n#endif \/\/ DUNE_DETAILED_DISCRETIZATIONS_DISCRETEFUNCTION_DEFAULT_HH\n<commit_msg>[discretefunction.default] removed unnecessary const<commit_after>#ifndef DUNE_DETAILED_DISCRETIZATIONS_DISCRETEFUNCTION_DEFAULT_HH\n#define DUNE_DETAILED_DISCRETIZATIONS_DISCRETEFUNCTION_DEFAULT_HH\n\n#ifdef HAVE_CMAKE_CONFIG\n#include \"cmake_config.h\"\n#elif defined(HAVE_CONFIG_H)\n#include \"config.h\"\n#endif\n\n#include <memory>\n\n#include <dune\/common\/exceptions.hh>\n#include <dune\/common\/fvector.hh>\n\n#include <dune\/grid\/io\/file\/vtk\/function.hh>\n\n#include <dune\/stuff\/la\/container\/interface.hh>\n\n#include <dune\/detailed\/discretizations\/space\/interface.hh>\n\n#include \"local.hh\"\n\nnamespace Dune {\nnamespace Detailed {\nnamespace Discretizations {\n\n\n\/\/ template< class DiscreteFunctionSpaceImp, class VectorImp >\n\/\/ class DefaultConst;\n\n\n\/\/ template< class DiscreteFunctionSpaceImp, class VectorImp >\n\/\/ class Default\n\/\/ : public Dune::VTKFunction< typename DiscreteFunctionSpaceImp::GridViewType >\n\/\/{\n\/\/ private:\n\/\/ typedef Dune::VTKFunction< typename DiscreteFunctionSpaceImp::GridViewType > BaseType;\n\n\/\/ public:\n\/\/ typedef DiscreteFunctionSpaceImp DiscreteFunctionSpaceType;\n\n\/\/ typedef VectorImp VectorType;\n\n\/\/ typedef Default< DiscreteFunctionSpaceType, VectorType > ThisType;\n\n\/\/ typedef DefaultConst< DiscreteFunctionSpaceType, VectorType > ConstType;\n\n\/\/ typedef typename DiscreteFunctionSpaceType::GridViewType::template Codim< 0 >::Iterator::Entity EntityType;\n\n\/\/ static const int polOrder = DiscreteFunctionSpaceType::polynomialOrder;\n\n\/\/ typedef Dune::Detailed::Discretizations::DiscreteFunction::LocalConst< ThisType > ConstLocalFunctionType;\n\n\/\/ typedef Dune::Detailed::Discretizations::DiscreteFunction::Local< ThisType > LocalFunctionType;\n\n\/\/ typedef typename DiscreteFunctionSpaceType::FunctionSpaceType FunctionSpaceType;\n\n\/\/ typedef typename FunctionSpaceType::DomainType DomainType;\n\n\/\/ typedef typename FunctionSpaceType::RangeFieldType RangeFieldType;\n\n\/\/ typedef typename FunctionSpaceType::RangeType RangeType;\n\n\/\/ static const int dimDomain = DiscreteFunctionSpaceType::dimDomain;\n\n\/\/ static const int dimRange = DiscreteFunctionSpaceType::dimRange;\n\n\/\/ typedef typename VectorType::size_type size_type;\n\n\/\/ Default(const DiscreteFunctionSpaceType& _space,\n\/\/ std::shared_ptr< VectorType > _vector,\n\/\/ const std::string _name = \"discrete_function\")\n\/\/ : BaseType(),\n\/\/ space_(_space)\n\/\/ , vector_(_vector)\n\/\/ , name_(_name)\n\/\/ {\n\/\/ assert(vector_->size() == space_.map().size() && \"Given vector has wrong size!\");\n\/\/ }\n\n\/\/ Default(const DiscreteFunctionSpaceType& _space,\n\/\/ const std::string _name = \"discrete_function\")\n\/\/ : BaseType(),\n\/\/ space_(_space)\n\/\/ , vector_(new VectorType(space_.map().size()))\n\/\/ , name_(_name)\n\/\/ {\n\/\/ assert(vector_->size() == space_.map().size() && \"Given vector has wrong size!\");\n\/\/ }\n\n\/\/ std::shared_ptr< const ConstType > createConst() const\n\/\/ {\n\/\/ std::shared_ptr< const ConstType > ret(new ConstType(*this));\n\/\/ return ret;\n\/\/ }\n\n\/\/ private:\n\/\/ Default(const ThisType&);\n\/\/ ThisType& operator=(const ThisType&);\n\n\/\/ public:\n\/\/ const DiscreteFunctionSpaceType& space() const\n\/\/ {\n\/\/ return space_;\n\/\/ }\n\n\/\/ virtual std::string name() const\n\/\/ {\n\/\/ return name_;\n\/\/ }\n\n\/\/ ConstLocalFunctionType localFunction(const EntityType& entity) const\n\/\/ {\n\/\/ return ConstLocalFunctionType(*this, entity);\n\/\/ }\n\n\/\/ LocalFunctionType localFunction(const EntityType& entity)\n\/\/ {\n\/\/ return LocalFunctionType(*this, entity);\n\/\/ }\n\n\/\/ std::shared_ptr< VectorType > vector()\n\/\/ {\n\/\/ return vector_;\n\/\/ }\n\n\/\/ const std::shared_ptr< const VectorType > vector() const\n\/\/ {\n\/\/ return vector_;\n\/\/ }\n\n\/\/ \/**\n\/\/ @name Convenience methods\n\/\/ @{\n\/\/ **\/\n\/\/ size_type size() const\n\/\/ {\n\/\/ return vector_->size();\n\/\/ }\n\/\/ \/**\n\/\/ @}\n\/\/ **\/\n\n\/\/ void clear()\n\/\/ {\n\/\/ const RangeFieldType zero(0);\n\/\/ for (size_type ii = 0; ii < vector_->size(); ++ii)\n\/\/ vector_->set(ii, zero);\n\/\/ }\n\n\/\/ \/**\n\/\/ @name Methods to comply with the Dune::VTKFunction interface\n\/\/ @{\n\/\/ **\/\n\/\/ virtual int ncomps() const\n\/\/ {\n\/\/ return dimRange;\n\/\/ }\n\n\/\/ virtual double evaluate(int component, const EntityType& entity, const DomainType& x) const\n\/\/ {\n\/\/ assert(vector_->size() == space_.map().size() && \"Given vector has wrong size!\");\n\/\/ RangeType ret(0.0);\n\/\/ localFunction(entity).evaluate(x, ret);\n\/\/ return ret[component];\n\/\/ }\n\/\/ \/**\n\/\/ @}\n\/\/ **\/\n\n\/\/ private:\n\/\/ const DiscreteFunctionSpaceType& space_;\n\/\/ std::shared_ptr< VectorType > vector_;\n\/\/ const std::string name_;\n\/\/}; \/\/ class Defaul\n\n\ntemplate <class SpaceImp, class VectorImp>\nclass DiscreteFunctionDefaultConst : public Dune::VTKFunction<typename SpaceImp::GridPartType::GridViewType>,\n public Dune::Stuff::LocalizableFunction\n{\npublic:\n typedef typename SpaceInterface<typename SpaceImp::Traits>::derived_type SpaceType;\n typedef typename Dune::Stuff::LA::VectorInterface<typename VectorImp::Traits>::derived_type VectorType;\n\n typedef typename SpaceType::EntityType EntityType;\n\n typedef DiscreteFunctionLocalConst<SpaceType, VectorType> ConstLocalFunctionType;\n typedef typename ConstLocalFunctionType::DomainType DomainType;\n typedef typename ConstLocalFunctionType::RangeType RangeType;\n\n DiscreteFunctionDefaultConst(const SpaceType& sp, const std::shared_ptr<const VectorType> vec,\n const std::string nm = \"discrete_function\")\n : \/*BaseType()\n , *\/ space_(sp)\n , name_(nm)\n , vector_(vec)\n {\n assert(vector_->size() == space_.mapper().size() && \"Given vector has wrong size!\");\n }\n\n const SpaceType& space() const\n {\n return space_;\n }\n\n virtual std::string name() const\n {\n return name_;\n }\n\n ConstLocalFunctionType localFunction(const EntityType& entity) const\n {\n return ConstLocalFunctionType(*this, entity);\n }\n\n std::shared_ptr<const VectorType> vector() const\n {\n return vector_;\n }\n\n \/** \\defgroup vtk ´´Methods to comply with the Dune::VTKFunction interface.'' *\/\n \/* @{ *\/\n virtual int ncomps() const\n {\n return SpaceType::dimRange;\n }\n\n virtual double evaluate(int component, const EntityType& entity, const DomainType& x) const\n {\n RangeType ret(0);\n localFunction(entity).evaluate(x, ret);\n return ret[component];\n }\n \/* @} *\/\n\nprivate:\n const SpaceType& space_;\n const std::string name_;\n const std::shared_ptr<const VectorType> vector_;\n}; \/\/ class DiscreteFunctionDefaultConst\n\n\ntemplate <class SpaceImp, class VectorImp>\nclass DiscreteFunctionDefault : public DiscreteFunctionDefaultConst<SpaceImp, VectorImp>\n{\n typedef DiscreteFunctionDefaultConst<SpaceImp, VectorImp> BaseType;\n\npublic:\n typedef typename SpaceInterface<typename SpaceImp::Traits>::derived_type SpaceType;\n typedef typename Dune::Stuff::LA::VectorInterface<typename VectorImp::Traits>::derived_type VectorType;\n\n typedef typename SpaceType::EntityType EntityType;\n\n typedef DiscreteFunctionLocal<SpaceType, VectorType> LocalFunctionType;\n typedef typename LocalFunctionType::DomainType DomainType;\n\n DiscreteFunctionDefault(const SpaceType& sp, std::shared_ptr<VectorType> vec,\n const std::string nm = \"discrete_function\")\n : BaseType(sp, vec, nm)\n , nonConstVector_(vec)\n {\n }\n\n \/\/ DiscreteFunctionDefault(const SpaceType& sp,\n \/\/ const std::string nm = \"discrete_function\")\n \/\/ : nonConstVector_(std::make_shared< VectorType >(sp.mapper().size()))\n \/\/ , BaseType(sp, nonConstVector_, nm)\n \/\/ {}\n\n LocalFunctionType localFunction(const EntityType& entity)\n {\n return LocalFunctionType(*this, entity);\n }\n\n std::shared_ptr<VectorType> vector()\n {\n return nonConstVector_;\n }\n\n \/\/ virtual std::string name() const\n \/\/ {\n \/\/ return BaseType::name();\n \/\/ }\n\n \/\/ \/** \\defgroup vtk ´´Methods to comply with the Dune::VTKFunction interface.'' *\/\n \/\/ \/* @{ *\/\n \/\/ virtual int ncomps() const\n \/\/ {\n \/\/ return BaseType::ncomps();\n \/\/ }\n\n \/\/ virtual double evaluate(int component, const EntityType& entity, const DomainType& x) const\n \/\/ {\n \/\/ BaseType::evaluate(component, entity, x);\n \/\/ }\n \/\/ \/* @} *\/\n\nprivate:\n std::shared_ptr<VectorType> nonConstVector_;\n}; \/\/ class DiscreteFunctionDefault\n\n\n} \/\/ namespace Discretizations\n} \/\/ namespace Detailed\n} \/\/ namespace Dune\n\n#endif \/\/ DUNE_DETAILED_DISCRETIZATIONS_DISCRETEFUNCTION_DEFAULT_HH\n<|endoftext|>"} {"text":"<commit_before>\/**\n @file proximityadaptor.cpp\n @brief ProximityAdaptor\n\n <p>\n Copyright (C) 2009-2010 Nokia Corporation\n\n @author Ustun Ergenoglu <ext-ustun.ergenoglu@nokia.com>\n @author Timo Rongas <ext-timo.2.rongas@nokia.com>\n @author Matias Muhonen <ext-matias.muhonen@nokia.com>\n @author Lihan Guo <lihan.guo@digia.com>\n @author Shenghua <ext-shenghua.1.liu@nokia.com>\n @author Antti Virtanen <antti.i.virtanen@nokia.com>\n\n This file is part of Sensord.\n\n Sensord is free software; you can redistribute it and\/or modify\n it under the terms of the GNU Lesser General Public License\n version 2.1 as published by the Free Software Foundation.\n\n Sensord is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n Lesser General Public License for more details.\n\n You should have received a copy of the GNU Lesser General Public\n License along with Sensord. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n <\/p>\n*\/\n#include \"proximityadaptor.h\"\n#include <errno.h>\n#include \"datatypes\/utils.h\"\n#include \"logging.h\"\n#include \"config.h\"\n#include <QFile>\n#include <linux\/types.h>\n\n#define THRESHOLD_FILE_PATH_RM680 \"\/sys\/class\/misc\/bh1770glc_ps\/device\/ps_threshold\"\n#define THRESHOLD_FILE_PATH_RM696 \"\/sys\/class\/misc\/apds990x0\/device\/prox_threshold\"\n\n#define RM680_PS \"\/dev\/bh1770glc_ps\"\n#define RM696_PS \"\/dev\/apds990x0\"\n\nstruct bh1770glc_ps {\n __u8 led1;\n __u8 led2;\n __u8 led3;\n} __attribute__((packed));\n\nstruct apds990x_data {\n __u32 lux; \/* 10x scale *\/\n __u32 lux_raw; \/* 10x scale *\/\n __u16 ps;\n __u16 ps_raw;\n __u16 status;\n} __attribute__((packed));\n\nProximityAdaptor::ProximityAdaptor(const QString& id) :\n SysfsAdaptor(id, SysfsAdaptor::SelectMode, false),\n m_threshold(35)\n{\n\n#ifdef SENSORFW_MCE_WATCHER\n dbusIfc = new QDBusInterface(MCE_SERVICE, MCE_REQUEST_PATH, MCE_REQUEST_IF,\n QDBusConnection::systemBus(), this);\n#endif\n\n device = DeviceUnknown;\n\n QString rm680_ps = Config::configuration()->value(\"proximity_dev_path_rm680\", RM680_PS).toString();\n QString rm696_ps = Config::configuration()->value(\"proximity_dev_path_rm696\", RM696_PS).toString();\n\n if (QFile::exists(rm680_ps))\n {\n device = RM680;\n addPath(rm680_ps);\n }\n else if (QFile::exists(rm696_ps))\n {\n device = RM696;\n addPath(rm696_ps);\n#ifdef SENSORFW_MCE_WATCHER\n dbusIfc->call(QDBus::NoBlock, \"req_proximity_sensor_enable\");\n#endif\n }\n else\n {\n sensordLogC() << \"Failed to locate proximity sensor\";\n }\n proximityBuffer_ = new DeviceAdaptorRingBuffer<ProximityData>(1);\n addAdaptedSensor(\"proximity\", \"Proximity state\", proximityBuffer_);\n\n int threshold = readThreshold();\n if (threshold <= 0) {\n sensordLogW() << \"Received value 0 for proximity threshold. Falling back to default \" << m_threshold;\n } else {\n m_threshold = threshold;\n }\n\n setDescription(\"Proximity sensor readings (Dipro sensor)\");\n introduceAvailableDataRange(DataRange(0, 1, 1));\n introduceAvailableInterval(DataRange(0, 0, 0));\n setDefaultInterval(0);\n}\n\nProximityAdaptor::~ProximityAdaptor()\n{\n if (device == RM696)\n {\n#ifdef SENSORFW_MCE_WATCHER\n dbusIfc->call(QDBus::NoBlock, \"req_proximity_sensor_disable\");\n delete dbusIfc;\n#endif\n }\n delete proximityBuffer_;\n}\n\nvoid ProximityAdaptor::processSample(int pathId, int fd)\n{\n Q_UNUSED(pathId);\n\n if (device == DeviceUnknown)\n return;\n\n int ret = 0;\n if (device == RM680)\n {\n bh1770glc_ps ps_data;\n int bytesRead = read(fd, &ps_data, sizeof(ps_data));\n\n if (bytesRead > 0) {\n sensordLogT() << \"Proximity Values: \" << ps_data.led1 << \", \" << ps_data.led2 << \", \" << ps_data.led3;\n } else {\n sensordLogW() << \"read(): \" << strerror(errno);\n return;\n }\n\n if ( ps_data.led1 > m_threshold ) {\n ret = 1;\n }\n }\n else if(device == RM696)\n {\n apds990x_data ps_data;\n int bytesRead = read(fd, &ps_data, sizeof(ps_data));\n\n if (bytesRead > 0) {\n sensordLogT() << \"Proximity Values: \" << ps_data.ps << \", \" << ps_data.ps_raw << \", \" << ps_data.status;\n } else {\n sensordLogW() << \"read(): \" << strerror(errno);\n return;\n }\n\n if ( ps_data.ps > m_threshold ) {\n ret = 1;\n }\n }\n\n ProximityData* proximityData = proximityBuffer_->nextSlot();\n\n proximityData->timestamp_ = Utils::getTimeStamp();\n proximityData->withinProximity_ = ret;\n\n proximityBuffer_->commit();\n proximityBuffer_->wakeUpReaders();\n}\n\nint ProximityAdaptor::readThreshold()\n{\n int value = 0;\n QString configKey = \"proximity_threshold_path\";\n QString configFileName = (device == RM680 ? THRESHOLD_FILE_PATH_RM680 : THRESHOLD_FILE_PATH_RM696);\n QFile thresholdFile(Config::configuration()->value(configKey, configFileName).toString());\n\n if (!(thresholdFile.exists() && thresholdFile.open(QIODevice::ReadOnly))) {\n sensordLogW() << \"Unable to locate threshold setting for \" << id();\n } else {\n char buf[16];\n\n if (thresholdFile.readLine(buf, sizeof(buf)) > 0) {\n value = QString(buf).split(\" \").at(0).toInt();\n }\n }\n return value;\n}\n<commit_msg>Adaptor also pushes the raw proximity data<commit_after>\/**\n @file proximityadaptor.cpp\n @brief ProximityAdaptor\n\n <p>\n Copyright (C) 2009-2010 Nokia Corporation\n\n @author Ustun Ergenoglu <ext-ustun.ergenoglu@nokia.com>\n @author Timo Rongas <ext-timo.2.rongas@nokia.com>\n @author Matias Muhonen <ext-matias.muhonen@nokia.com>\n @author Lihan Guo <lihan.guo@digia.com>\n @author Shenghua <ext-shenghua.1.liu@nokia.com>\n @author Antti Virtanen <antti.i.virtanen@nokia.com>\n\n This file is part of Sensord.\n\n Sensord is free software; you can redistribute it and\/or modify\n it under the terms of the GNU Lesser General Public License\n version 2.1 as published by the Free Software Foundation.\n\n Sensord is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n Lesser General Public License for more details.\n\n You should have received a copy of the GNU Lesser General Public\n License along with Sensord. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n <\/p>\n*\/\n#include \"proximityadaptor.h\"\n#include <errno.h>\n#include \"datatypes\/utils.h\"\n#include \"logging.h\"\n#include \"config.h\"\n#include <QFile>\n#include <linux\/types.h>\n\n#define THRESHOLD_FILE_PATH_RM680 \"\/sys\/class\/misc\/bh1770glc_ps\/device\/ps_threshold\"\n#define THRESHOLD_FILE_PATH_RM696 \"\/sys\/class\/misc\/apds990x0\/device\/prox_threshold\"\n\n#define RM680_PS \"\/dev\/bh1770glc_ps\"\n#define RM696_PS \"\/dev\/apds990x0\"\n\nstruct bh1770glc_ps {\n __u8 led1;\n __u8 led2;\n __u8 led3;\n} __attribute__((packed));\n\nstruct apds990x_data {\n __u32 lux; \/* 10x scale *\/\n __u32 lux_raw; \/* 10x scale *\/\n __u16 ps;\n __u16 ps_raw;\n __u16 status;\n} __attribute__((packed));\n\nProximityAdaptor::ProximityAdaptor(const QString& id) :\n SysfsAdaptor(id, SysfsAdaptor::SelectMode, false),\n m_threshold(35)\n{\n\n#ifdef SENSORFW_MCE_WATCHER\n dbusIfc = new QDBusInterface(MCE_SERVICE, MCE_REQUEST_PATH, MCE_REQUEST_IF,\n QDBusConnection::systemBus(), this);\n#endif\n\n device = DeviceUnknown;\n\n QString rm680_ps = Config::configuration()->value(\"proximity_dev_path_rm680\", RM680_PS).toString();\n QString rm696_ps = Config::configuration()->value(\"proximity_dev_path_rm696\", RM696_PS).toString();\n\n if (QFile::exists(rm680_ps))\n {\n device = RM680;\n addPath(rm680_ps);\n }\n else if (QFile::exists(rm696_ps))\n {\n device = RM696;\n addPath(rm696_ps);\n#ifdef SENSORFW_MCE_WATCHER\n dbusIfc->call(QDBus::NoBlock, \"req_proximity_sensor_enable\");\n#endif\n }\n else\n {\n sensordLogC() << \"Failed to locate proximity sensor\";\n }\n proximityBuffer_ = new DeviceAdaptorRingBuffer<ProximityData>(1);\n addAdaptedSensor(\"proximity\", \"Proximity state\", proximityBuffer_);\n\n int threshold = readThreshold();\n if (threshold <= 0) {\n sensordLogW() << \"Received value 0 for proximity threshold. Falling back to default \" << m_threshold;\n } else {\n m_threshold = threshold;\n }\n\n setDescription(\"Proximity sensor readings (Dipro sensor)\");\n introduceAvailableDataRange(DataRange(0, 1, 1));\n introduceAvailableInterval(DataRange(0, 0, 0));\n setDefaultInterval(0);\n}\n\nProximityAdaptor::~ProximityAdaptor()\n{\n if (device == RM696)\n {\n#ifdef SENSORFW_MCE_WATCHER\n dbusIfc->call(QDBus::NoBlock, \"req_proximity_sensor_disable\");\n delete dbusIfc;\n#endif\n }\n delete proximityBuffer_;\n}\n\nvoid ProximityAdaptor::processSample(int pathId, int fd)\n{\n Q_UNUSED(pathId);\n\n if (device == DeviceUnknown)\n return;\n\n int ret = 0;\n unsigned rawdata = 0;\n\n if (device == RM680)\n {\n bh1770glc_ps ps_data;\n int bytesRead = read(fd, &ps_data, sizeof(ps_data));\n\n if (bytesRead > 0) {\n sensordLogT() << \"Proximity Values: \" << ps_data.led1 << \", \" << ps_data.led2 << \", \" << ps_data.led3;\n } else {\n sensordLogW() << \"read(): \" << strerror(errno);\n return;\n }\n\n if ( ps_data.led1 > m_threshold ) {\n ret = 1;\n }\n\n rawdata = ps_data.led1;\n }\n else if(device == RM696)\n {\n apds990x_data ps_data;\n int bytesRead = read(fd, &ps_data, sizeof(ps_data));\n\n if (bytesRead > 0) {\n sensordLogT() << \"Proximity Values: \" << ps_data.ps << \", \" << ps_data.ps_raw << \", \" << ps_data.status;\n } else {\n sensordLogW() << \"read(): \" << strerror(errno);\n return;\n }\n\n if ( ps_data.ps > m_threshold ) {\n ret = 1;\n }\n\n rawdata = ps_data.ps;\n }\n\n ProximityData* proximityData = proximityBuffer_->nextSlot();\n\n proximityData->timestamp_ = Utils::getTimeStamp();\n proximityData->withinProximity_ = ret;\n proximityData->value_ = rawdata;\n\n proximityBuffer_->commit();\n proximityBuffer_->wakeUpReaders();\n}\n\nint ProximityAdaptor::readThreshold()\n{\n int value = 0;\n QString configKey = \"proximity_threshold_path\";\n QString configFileName = (device == RM680 ? THRESHOLD_FILE_PATH_RM680 : THRESHOLD_FILE_PATH_RM696);\n QFile thresholdFile(Config::configuration()->value(configKey, configFileName).toString());\n\n if (!(thresholdFile.exists() && thresholdFile.open(QIODevice::ReadOnly))) {\n sensordLogW() << \"Unable to locate threshold setting for \" << id();\n } else {\n char buf[16];\n\n if (thresholdFile.readLine(buf, sizeof(buf)) > 0) {\n value = QString(buf).split(\" \").at(0).toInt();\n }\n }\n return value;\n}\n<|endoftext|>"} {"text":"<commit_before>#include <QtGui\/QPainter>\n#include <QtWidgets\/QStyle>\n#include <QtWidgets\/QStyleOptionGraphicsItem>\n\n#include <qrkernel\/settingsManager.h>\n#include \"lineItem.h\"\n#include \"wallItem.h\"\n\nusing namespace twoDModel::items;\nusing namespace qReal;\nusing namespace graphicsUtils;\n\nLineItem::LineItem(QPointF const &begin, QPointF const &end, int cornerRadius)\n\t: mLineImpl()\n\t, mCornerRadius(cornerRadius)\n\t, mCellNumbX1(0)\n\t, mCellNumbY1(0)\n\t, mCellNumbX2(0)\n\t, mCellNumbY2(0)\n{\n\tmX1 = begin.x();\n\tmY1 = begin.y();\n\tmX2 = end.x();\n\tmY2 = end.y();\n\tsetFlags(ItemIsSelectable | ItemIsMovable);\n\tsetPrivateData();\n}\n\nvoid LineItem::setPrivateData()\n{\n\tmPen.setColor(Qt::green);\n\tmPen.setStyle(Qt::SolidLine);\n\tmSerializeName = \"line\";\n}\n\nQRectF LineItem::boundingRect() const\n{\n\treturn mLineImpl.boundingRect(mX1, mY1, mX2, mY2, mPen.width(), drift);\n}\n\nvoid LineItem::drawItem(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget)\n{\n\tQ_UNUSED(option);\n\tQ_UNUSED(widget);\n\tmLineImpl.drawItem(painter, mX1, mY1, mX2, mY2);\n}\n\nvoid LineItem::drawExtractionForItem(QPainter* painter)\n{\n\tmLineImpl.drawPointExtractionForItem(painter, mX1, mY1, mX2, mY2);\n\tsetPenBrushDriftRect(painter);\n\tmLineImpl.drawExtractionForItem(painter, mX1, mY1, mX2, mY2, drift);\n\tmLineImpl.drawFieldForResizeItem(painter, resizeDrift, mX1, mY1, mX2, mY2);\n\n\tpainter->setPen(QPen(Qt::red));\n\tpainter->setBrush(QBrush(Qt::SolidPattern));\n}\n\nQPainterPath LineItem::shape() const\n{\n\treturn mLineImpl.shape(drift, mX1, mY1, mX2, mY2);\n}\n\nvoid LineItem::resizeItem(QGraphicsSceneMouseEvent *event)\n{\n\tif (event->modifiers() & Qt::ShiftModifier) {\n\t\tmX2=event->scenePos().x();\n\t\tmY2=event->scenePos().y();\n\t\treshapeRectWithShift();\n\t} else {\n\t\tif (SettingsManager::value(\"2dShowGrid\").toBool()\n\t\t\t\t&& (mDragState == TopLeft || mDragState == BottomRight)\n\t\t\t\t&& dynamic_cast<WallItem *>(this))\n\t\t{\n\t\t\tcalcResizeItem(event, SettingsManager::value(\"2dGridCellSize\").toInt());\n\t\t} else {\n\t\t\tif (mDragState == TopLeft || mDragState == BottomRight) {\n\t\t\t\tAbstractItem::resizeItem(event);\n\t\t\t} else {\n\t\t\t\tsetFlag(QGraphicsItem::ItemIsMovable, true);\n\t\t\t}\n\t\t}\n\t}\n}\n\nvoid LineItem::calcResizeItem(QGraphicsSceneMouseEvent *event, int indexGrid)\n{\n\tqreal const x = mapFromScene(event->scenePos()).x();\n\tqreal const y = mapFromScene(event->scenePos()).y();\n\tif (mDragState != None) {\n\t\tsetFlag(QGraphicsItem::ItemIsMovable, false);\n\t}\n\tif (mDragState == TopLeft) {\n\t\tmX1 = x;\n\t\tmY1 = y;\n\t\tresizeBeginWithGrid(indexGrid);\n\t} else if (mDragState == BottomRight) {\n\t\tmX2 = x;\n\t\tmY2 = y;\n\t\treshapeEndWithGrid(indexGrid);\n\t}\n}\n\nvoid LineItem::reshapeRectWithShift()\n{\n\tqreal differenceX = abs(mX2 - mX1);\n\tqreal differenceY = abs(mY2 - mY1);\n\tqreal differenceXY = abs(differenceX - differenceY);\n\tqreal size = qMax(differenceX, differenceY);\n\tconst int delta = size \/ 2;\n\tif (differenceXY > delta) {\n\t\tQPair<qreal, qreal> res = mLineImpl.reshapeRectWithShiftForLine(mX1, mY1, mX2, mY2, differenceX, differenceY, size);\n\t\tsetX2andY2(res.first, res.second);\n\t} else\n\t\tAbstractItem::reshapeRectWithShift();\n}\n\nvoid LineItem::resizeBeginWithGrid(int indexGrid)\n{\n\tint const coefX = static_cast<int>(mX1) \/ indexGrid;\n\tint const coefY = static_cast<int>(mY1) \/ indexGrid;\n\n\tif (qAbs(mY2 - mY1) > 2 * qAbs(mX2 - mX1)) {\n\t\tsetX1andY1(mX2, alignedCoordinate(mY1, coefY, indexGrid));\n\t} else if (qAbs(mY2 - mY1) < qAbs(mX2 - mX1) \/ 2) {\n\t\tsetX1andY1(alignedCoordinate(mX1, coefX, indexGrid), mY2);\n\t} else {\n\t\tsetX2andY2(alignedCoordinate(mX1, coefX, indexGrid), alignedCoordinate(mY1, coefY, indexGrid));\n\t}\n\n\tmCellNumbX1 = mX1 \/ indexGrid;\n\tmCellNumbY1 = mY1 \/ indexGrid;\n}\n\nvoid LineItem::reshapeEndWithGrid(int indexGrid)\n{\n\tint const coefX = static_cast<int>(mX2) \/ indexGrid;\n\tint const coefY = static_cast<int>(mY2) \/ indexGrid;\n\n\tif (qAbs(mY2 - mY1) > 2 * qAbs(mX2 - mX1)) {\n\t\tsetX2andY2(mX1, alignedCoordinate(mY2, coefY, indexGrid));\n\t} else if (qAbs(mY2 - mY1) < qAbs(mX2 - mX1) \/ 2) {\n\t\tsetX2andY2(alignedCoordinate(mX2, coefX, indexGrid), mY1);\n\t} else {\n\t\tsetX2andY2(alignedCoordinate(mX2, coefX, indexGrid), alignedCoordinate(mY2, coefY, indexGrid));\n\t}\n\n\tmCellNumbX2 = mX2 \/ indexGrid;\n\tmCellNumbY2 = mY2 \/ indexGrid;\n}\n\nvoid LineItem::reshapeBeginWithGrid(int indexGrid)\n{\n\tint const coefX = static_cast<int> (mX1) \/ indexGrid;\n\tint const coefY = static_cast<int> (mY1) \/ indexGrid;\n\tsetX1andY1(alignedCoordinate(mX1, coefX, indexGrid), alignedCoordinate(mY1, coefY, indexGrid));\n\tmCellNumbX1 = mX1 \/ indexGrid;\n\tmCellNumbY1 = mY1 \/ indexGrid;\n}\n\nvoid LineItem::alignTheWall(int indexGrid)\n{\n\tcountCellNumbCoordinates(indexGrid);\n\tsetBeginCoordinatesWithGrid(indexGrid);\n\tsetEndCoordinatesWithGrid(indexGrid);\n}\n\nvoid LineItem::countCellNumbCoordinates(int indexGrid)\n{\n\tmCellNumbX1 = mX1 \/ indexGrid;\n\tmCellNumbY1 = mY1 \/ indexGrid;\n\n\tif (qAbs(mY2 - mY1) > qAbs(mX2 - mX1)) {\n\t\tmCellNumbX2 = mCellNumbX1;\n\t\tmCellNumbY2 = mY2 \/ indexGrid;\n\t} else {\n\t\tmCellNumbX2 = mX2 \/ indexGrid;\n\t\tmCellNumbY2 = mCellNumbY1;\n\t}\n}\n\nvoid LineItem::setBeginCoordinatesWithGrid(int indexGrid)\n{\n\tsetX1andY1(mCellNumbX1 * indexGrid, mCellNumbY1 * indexGrid);\n}\n\nvoid LineItem::setEndCoordinatesWithGrid(int indexGrid)\n{\n\tsetX2andY2(mCellNumbX2 * indexGrid, mCellNumbY2 * indexGrid);\n}\n\nvoid LineItem::setDraggedEnd(qreal x, qreal y)\n{\n\tsetX2andY2(mX1 - x, mY1 - y);\n}\n\nqreal LineItem::alignedCoordinate(qreal coord, int coef, int const indexGrid) const\n{\n\tint const coefSign = coef ? coef \/ qAbs(coef) : 0;\n\n\tif (qAbs(qAbs(coord) - qAbs(coef) * indexGrid) <= indexGrid \/ 2) {\n\t\treturn coef * indexGrid;\n\t} else if (qAbs(qAbs(coord) - (qAbs(coef) + 1) * indexGrid) <= indexGrid \/ 2) {\n\t\treturn (coef + coefSign) * indexGrid;\n\t}\n\n\treturn coord;\n}\n\nQDomElement LineItem::serialize(QDomDocument &document, QPoint const &topLeftPicture)\n{\n\tQDomElement lineNode = setPenBrushToDoc(document, mSerializeName);\n\tlineNode.setAttribute(\"begin\", QString::number(mX1 + scenePos().x() - topLeftPicture.x())\n\t\t\t+ \":\" + QString::number(mY1 + scenePos().y() - topLeftPicture.y()));\n\tlineNode.setAttribute(\"end\", QString::number(mX2 + scenePos().x() - topLeftPicture.x())\n\t\t\t+ \":\" + QString::number(mY2 + scenePos().y() - topLeftPicture.y()));\n\treturn lineNode;\n}\n\nvoid LineItem::deserialize(QDomElement const &element)\n{\n\tQString const beginStr = element.attribute(\"begin\", \"0:0\");\n\tQStringList splittedStr = beginStr.split(\":\");\n\tint x = splittedStr[0].toInt();\n\tint y = splittedStr[1].toInt();\n\tQPointF const begin = QPointF(x, y);\n\n\tQString const endStr = element.attribute(\"end\", \"0:0\");\n\tsplittedStr = endStr.split(\":\");\n\tx = splittedStr[0].toInt();\n\ty = splittedStr[1].toInt();\n\tQPointF const end = QPointF(x, y);\n\n\tmX1 = begin.x();\n\tmY1 = begin.y();\n\tmX2 = end.x();\n\tmY2 = end.y();\n\n\tdeserializePenBrush(element);\n}\n\nvoid LineItem::deserializePenBrush(QDomElement const &element)\n{\n\treadPenBrush(element);\n}\n\nvoid LineItem::setSerializeName(QString const &name)\n{\n\tmSerializeName = name;\n}\n<commit_msg>Walls alligned on edges of grid in d2modelwidget<commit_after>#include <QtGui\/QPainter>\n#include <QtWidgets\/QStyle>\n#include <QtWidgets\/QStyleOptionGraphicsItem>\n\n#include <qrkernel\/settingsManager.h>\n#include \"lineItem.h\"\n#include \"wallItem.h\"\n\nusing namespace twoDModel::items;\nusing namespace qReal;\nusing namespace graphicsUtils;\n\nLineItem::LineItem(QPointF const &begin, QPointF const &end, int cornerRadius)\n\t: mLineImpl()\n\t, mCornerRadius(cornerRadius)\n\t, mCellNumbX1(0)\n\t, mCellNumbY1(0)\n\t, mCellNumbX2(0)\n\t, mCellNumbY2(0)\n{\n\tmX1 = begin.x();\n\tmY1 = begin.y();\n\tmX2 = end.x();\n\tmY2 = end.y();\n\tsetFlags(ItemIsSelectable | ItemIsMovable);\n\tsetPrivateData();\n}\n\nvoid LineItem::setPrivateData()\n{\n\tmPen.setColor(Qt::green);\n\tmPen.setStyle(Qt::SolidLine);\n\tmSerializeName = \"line\";\n}\n\nQRectF LineItem::boundingRect() const\n{\n\treturn mLineImpl.boundingRect(mX1, mY1, mX2, mY2, mPen.width(), drift);\n}\n\nvoid LineItem::drawItem(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget)\n{\n\tQ_UNUSED(option);\n\tQ_UNUSED(widget);\n\tmLineImpl.drawItem(painter, mX1, mY1, mX2, mY2);\n}\n\nvoid LineItem::drawExtractionForItem(QPainter* painter)\n{\n\tmLineImpl.drawPointExtractionForItem(painter, mX1, mY1, mX2, mY2);\n\tsetPenBrushDriftRect(painter);\n\tmLineImpl.drawExtractionForItem(painter, mX1, mY1, mX2, mY2, drift);\n\tmLineImpl.drawFieldForResizeItem(painter, resizeDrift, mX1, mY1, mX2, mY2);\n\n\tpainter->setPen(QPen(Qt::red));\n\tpainter->setBrush(QBrush(Qt::SolidPattern));\n}\n\nQPainterPath LineItem::shape() const\n{\n\treturn mLineImpl.shape(drift, mX1, mY1, mX2, mY2);\n}\n\nvoid LineItem::resizeItem(QGraphicsSceneMouseEvent *event)\n{\n\tif (event->modifiers() & Qt::ShiftModifier) {\n\t\tmX2=event->scenePos().x();\n\t\tmY2=event->scenePos().y();\n\t\treshapeRectWithShift();\n\t} else {\n\t\tif (SettingsManager::value(\"2dShowGrid\").toBool()\n\t\t\t\t&& (mDragState == TopLeft || mDragState == BottomRight)\n\t\t\t\t&& dynamic_cast<WallItem *>(this))\n\t\t{\n\t\t\tcalcResizeItem(event, SettingsManager::value(\"2dGridCellSize\").toInt());\n\t\t} else {\n\t\t\tif (mDragState == TopLeft || mDragState == BottomRight) {\n\t\t\t\tAbstractItem::resizeItem(event);\n\t\t\t} else {\n\t\t\t\tsetFlag(QGraphicsItem::ItemIsMovable, true);\n\t\t\t}\n\t\t}\n\t}\n}\n\nvoid LineItem::calcResizeItem(QGraphicsSceneMouseEvent *event, int indexGrid)\n{\n\tqreal const x = mapFromScene(event->scenePos()).x();\n\tqreal const y = mapFromScene(event->scenePos()).y();\n\tif (mDragState != None) {\n\t\tsetFlag(QGraphicsItem::ItemIsMovable, false);\n\t}\n\tif (mDragState == TopLeft) {\n\t\tmX1 = x;\n\t\tmY1 = y;\n\t\tresizeBeginWithGrid(indexGrid);\n\t} else if (mDragState == BottomRight) {\n\t\tmX2 = x;\n\t\tmY2 = y;\n\t\treshapeEndWithGrid(indexGrid);\n\t}\n}\n\nvoid LineItem::reshapeRectWithShift()\n{\n\tqreal differenceX = abs(mX2 - mX1);\n\tqreal differenceY = abs(mY2 - mY1);\n\tqreal differenceXY = abs(differenceX - differenceY);\n\tqreal size = qMax(differenceX, differenceY);\n\tconst int delta = size \/ 2;\n\tif (differenceXY > delta) {\n\t\tQPair<qreal, qreal> res = mLineImpl.reshapeRectWithShiftForLine(mX1, mY1, mX2, mY2, differenceX, differenceY, size);\n\t\tsetX2andY2(res.first, res.second);\n\t} else\n\t\tAbstractItem::reshapeRectWithShift();\n}\n\nvoid LineItem::resizeBeginWithGrid(int indexGrid)\n{\n\tint const coefX = static_cast<int>(mX1) \/ indexGrid;\n\tint const coefY = static_cast<int>(mY1) \/ indexGrid;\n\n\tsetX1andY1(alignedCoordinate(mX1, coefX, indexGrid), alignedCoordinate(mY1, coefY, indexGrid));\n\n\tmCellNumbX1 = mX1 \/ indexGrid;\n\tmCellNumbY1 = mY1 \/ indexGrid;\n}\n\nvoid LineItem::reshapeEndWithGrid(int indexGrid)\n{\n\tint const coefX = static_cast<int>(mX2) \/ indexGrid;\n\tint const coefY = static_cast<int>(mY2) \/ indexGrid;\n\n\tsetX2andY2(alignedCoordinate(mX2, coefX, indexGrid), alignedCoordinate(mY2, coefY, indexGrid));\n\n\tmCellNumbX2 = mX2 \/ indexGrid;\n\tmCellNumbY2 = mY2 \/ indexGrid;\n}\n\nvoid LineItem::reshapeBeginWithGrid(int indexGrid)\n{\n\tint const coefX = static_cast<int> (mX1) \/ indexGrid;\n\tint const coefY = static_cast<int> (mY1) \/ indexGrid;\n\tsetX1andY1(alignedCoordinate(mX1, coefX, indexGrid), alignedCoordinate(mY1, coefY, indexGrid));\n\tmCellNumbX1 = mX1 \/ indexGrid;\n\tmCellNumbY1 = mY1 \/ indexGrid;\n}\n\nvoid LineItem::alignTheWall(int indexGrid)\n{\n\tcountCellNumbCoordinates(indexGrid);\n\tsetBeginCoordinatesWithGrid(indexGrid);\n\tsetEndCoordinatesWithGrid(indexGrid);\n}\n\nvoid LineItem::countCellNumbCoordinates(int indexGrid)\n{\n\tmCellNumbX1 = mX1 \/ indexGrid;\n\tmCellNumbY1 = mY1 \/ indexGrid;\n\n\tif (qAbs(mY2 - mY1) > qAbs(mX2 - mX1)) {\n\t\tmCellNumbX2 = mCellNumbX1;\n\t\tmCellNumbY2 = mY2 \/ indexGrid;\n\t} else {\n\t\tmCellNumbX2 = mX2 \/ indexGrid;\n\t\tmCellNumbY2 = mCellNumbY1;\n\t}\n}\n\nvoid LineItem::setBeginCoordinatesWithGrid(int indexGrid)\n{\n\tsetX1andY1(mCellNumbX1 * indexGrid, mCellNumbY1 * indexGrid);\n}\n\nvoid LineItem::setEndCoordinatesWithGrid(int indexGrid)\n{\n\tsetX2andY2(mCellNumbX2 * indexGrid, mCellNumbY2 * indexGrid);\n}\n\nvoid LineItem::setDraggedEnd(qreal x, qreal y)\n{\n\tsetX2andY2(mX1 - x, mY1 - y);\n}\n\nqreal LineItem::alignedCoordinate(qreal coord, int coef, int const indexGrid) const\n{\n\tint const coefSign = coef ? coef \/ qAbs(coef) : 0;\n\n\tif (qAbs(qAbs(coord) - qAbs(coef) * indexGrid) <= indexGrid \/ 2) {\n\t\treturn coef * indexGrid;\n\t} else if (qAbs(qAbs(coord) - (qAbs(coef) + 1) * indexGrid) <= indexGrid \/ 2) {\n\t\treturn (coef + coefSign) * indexGrid;\n\t}\n\n\treturn coord;\n}\n\nQDomElement LineItem::serialize(QDomDocument &document, QPoint const &topLeftPicture)\n{\n\tQDomElement lineNode = setPenBrushToDoc(document, mSerializeName);\n\tlineNode.setAttribute(\"begin\", QString::number(mX1 + scenePos().x() - topLeftPicture.x())\n\t\t\t+ \":\" + QString::number(mY1 + scenePos().y() - topLeftPicture.y()));\n\tlineNode.setAttribute(\"end\", QString::number(mX2 + scenePos().x() - topLeftPicture.x())\n\t\t\t+ \":\" + QString::number(mY2 + scenePos().y() - topLeftPicture.y()));\n\treturn lineNode;\n}\n\nvoid LineItem::deserialize(QDomElement const &element)\n{\n\tQString const beginStr = element.attribute(\"begin\", \"0:0\");\n\tQStringList splittedStr = beginStr.split(\":\");\n\tint x = splittedStr[0].toInt();\n\tint y = splittedStr[1].toInt();\n\tQPointF const begin = QPointF(x, y);\n\n\tQString const endStr = element.attribute(\"end\", \"0:0\");\n\tsplittedStr = endStr.split(\":\");\n\tx = splittedStr[0].toInt();\n\ty = splittedStr[1].toInt();\n\tQPointF const end = QPointF(x, y);\n\n\tmX1 = begin.x();\n\tmY1 = begin.y();\n\tmX2 = end.x();\n\tmY2 = end.y();\n\n\tdeserializePenBrush(element);\n}\n\nvoid LineItem::deserializePenBrush(QDomElement const &element)\n{\n\treadPenBrush(element);\n}\n\nvoid LineItem::setSerializeName(QString const &name)\n{\n\tmSerializeName = name;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ NoLifeNxBench - Part of the NoLifeStory project \/\/\n\/\/ Copyright (C) 2013 Peter Atashian \/\/\n\/\/ \/\/\n\/\/ This program is free software: you can redistribute it and\/or modify \/\/\n\/\/ it under the terms of the GNU Affero General Public License as \/\/\n\/\/ published by the Free Software Foundation, either version 3 of the \/\/\n\/\/ License, or (at your option) any later version. \/\/\n\/\/ \/\/\n\/\/ This program is distributed in the hope that it will be useful, \/\/\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of \/\/\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the \/\/\n\/\/ GNU Affero General Public License for more details. \/\/\n\/\/ \/\/\n\/\/ You should have received a copy of the GNU Affero General Public License \/\/\n\/\/ along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>. \/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n#include \"..\/NoLifeNx\/NX.hpp\"\n#include <iostream>\n#include <iomanip>\n#include <limits>\n#include <vector>\n#include <algorithm>\n#include <numeric>\n#ifdef NL_WINDOWS\n# include <Windows.h>\n#else\n# include <ctime>\n#endif\nchar const Name[] = \"Data.nx\";\nNL::File const File(Name);\nint64_t Freq;\nvoid Load() {\n NL::File f(Name);\n}\nvoid SubRecurse(NL::Node n) {\n for (NL::Node nn : n) SubRecurse(nn);\n}\nvoid LoadRecurse() {\n SubRecurse(NL::File(Name));\n}\nvoid Recurse() {\n SubRecurse(File);\n}\nvoid SubRecurseSearch(NL::Node n) {\n for (NL::Node nn : n) n[nn.NameFast()] == nn ? SubRecurseSearch(nn) : throw;\n}\nvoid RecurseSearch() {\n SubRecurseSearch(File);\n}\nvoid SubDecompress(NL::Node n) {\n n.GetBitmap().Data();\n for (NL::Node nn : n) SubDecompress(nn);\n}\nvoid Decompress() {\n SubDecompress(File);\n}\n#ifdef NL_WINDOWS\nint64_t GetHPC() {\n LARGE_INTEGER n;\n QueryPerformanceCounter(&n);\n return n.QuadPart;\n}\nvoid GetFreq() {\n LARGE_INTEGER n;\n QueryPerformanceFrequency(&n);\n Freq = n.QuadPart;\n}\n#else\nint64_t GetHPC() {\n struct timespec t;\n clock_gettime(CLOCK_MONOTONIC_RAW, &t);\n return t.tv_sec * 1000000000LL + t.tv_nsec;\n}\nvoid GetFreq() {\n Freq = 1000000000LL;\n}\n#endif\nint64_t Adjust(int64_t v) {\n return v * 1000000LL \/ Freq;\n}\ntemplate <typename T>\nvoid Test(const char * name, T f) {\n std::vector<int64_t> results;\n int64_t c0 = GetHPC();\n do {\n int64_t c1 = GetHPC();\n f();\n int64_t c2 = GetHPC();\n results.emplace_back(c2 - c1);\n } while (GetHPC() - c0 < Freq << 3);\n std::sort(results.begin(), results.end());\n printf(\"{%s, %lld, %lld, %lld, %lld, %lld, %lld, %lld}\\n\", name, static_cast<int64_t>(results.size()),\n Adjust(std::accumulate(results.cbegin(), results.cend(), 0) \/ static_cast<int64_t>(results.size())),\n Adjust(results[(results.size() - 1) * 0 \/ 4]),\n Adjust(results[(results.size() - 1) * 1 \/ 4]),\n Adjust(results[(results.size() - 1) * 2 \/ 4]),\n Adjust(results[(results.size() - 1) * 3 \/ 4]),\n Adjust(results[(results.size() - 1) * 4 \/ 4]));\n}\nint main() {\n GetFreq();\n printf(\"{Name, Count, Mean, 0%%, 25%%, 50%%, 75%%, 100%%}\\n\");\n Test(\"Load\", Load);\n Test(\"LoadRecurse\", LoadRecurse);\n Test(\"Recurse\", Recurse);\n Test(\"RecurseSearch\", RecurseSearch);\n Test(\"Decompress\", Decompress);\n}<commit_msg>Added 50%mean<commit_after>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ NoLifeNxBench - Part of the NoLifeStory project \/\/\n\/\/ Copyright (C) 2013 Peter Atashian \/\/\n\/\/ \/\/\n\/\/ This program is free software: you can redistribute it and\/or modify \/\/\n\/\/ it under the terms of the GNU Affero General Public License as \/\/\n\/\/ published by the Free Software Foundation, either version 3 of the \/\/\n\/\/ License, or (at your option) any later version. \/\/\n\/\/ \/\/\n\/\/ This program is distributed in the hope that it will be useful, \/\/\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of \/\/\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the \/\/\n\/\/ GNU Affero General Public License for more details. \/\/\n\/\/ \/\/\n\/\/ You should have received a copy of the GNU Affero General Public License \/\/\n\/\/ along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>. \/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n#include \"..\/NoLifeNx\/NX.hpp\"\n#include <iostream>\n#include <iomanip>\n#include <limits>\n#include <vector>\n#include <algorithm>\n#include <numeric>\n#ifdef NL_WINDOWS\n# include <Windows.h>\n#else\n# include <ctime>\n#endif\nchar const Name[] = \"Data.nx\";\nNL::File const File(Name);\nint64_t Freq;\nvoid Load() {\n NL::File f(Name);\n}\nvoid SubRecurse(NL::Node n) {\n for (NL::Node nn : n) SubRecurse(nn);\n}\nvoid LoadRecurse() {\n SubRecurse(NL::File(Name));\n}\nvoid Recurse() {\n SubRecurse(File);\n}\nvoid SubRecurseSearch(NL::Node n) {\n for (NL::Node nn : n) n[nn.NameFast()] == nn ? SubRecurseSearch(nn) : throw;\n}\nvoid RecurseSearch() {\n SubRecurseSearch(File);\n}\nvoid SubDecompress(NL::Node n) {\n n.GetBitmap().Data();\n for (NL::Node nn : n) SubDecompress(nn);\n}\nvoid Decompress() {\n SubDecompress(File);\n}\n#ifdef NL_WINDOWS\nint64_t GetHPC() {\n LARGE_INTEGER n;\n QueryPerformanceCounter(&n);\n return n.QuadPart;\n}\nvoid GetFreq() {\n LARGE_INTEGER n;\n QueryPerformanceFrequency(&n);\n Freq = n.QuadPart;\n}\n#else\nint64_t GetHPC() {\n struct timespec t;\n clock_gettime(CLOCK_MONOTONIC_RAW, &t);\n return t.tv_sec * 1000000000LL + t.tv_nsec;\n}\nvoid GetFreq() {\n Freq = 1000000000LL;\n}\n#endif\nint64_t Adjust(int64_t v) {\n return v * 1000000LL \/ Freq;\n}\ntemplate <typename T>\nvoid Test(const char * name, T f) {\n std::vector<int64_t> results;\n int64_t c0 = GetHPC();\n do {\n int64_t c1 = GetHPC();\n f();\n int64_t c2 = GetHPC();\n results.emplace_back(c2 - c1);\n } while (GetHPC() - c0 < Freq << 3);\n std::sort(results.begin(), results.end());\n printf(\"{%s, %lld, %lld, %lld, %lld, %lld, %lld, %lld, %lld}\\n\", name, static_cast<int64_t>(results.size()),\n Adjust(std::accumulate(results.cbegin(), results.cend(), 0) \/ static_cast<int64_t>(results.size())),\n Adjust(std::accumulate(results.cbegin() + static_cast<ptrdiff_t>(results.size()) \/ 4, results.cend() - static_cast<ptrdiff_t>(results.size()) \/ 4, 0) \/ static_cast<int64_t>(results.size() - results.size() \/ 4 * 2)),\n Adjust(results[(results.size() - 1) * 0 \/ 4]),\n Adjust(results[(results.size() - 1) * 1 \/ 4]),\n Adjust(results[(results.size() - 1) * 2 \/ 4]),\n Adjust(results[(results.size() - 1) * 3 \/ 4]),\n Adjust(results[(results.size() - 1) * 4 \/ 4]));\n}\nint main() {\n GetFreq();\n printf(\"{Name, Count, Mean, 50%%Mean, 0%%, 25%%, 50%%, 75%%, 100%%}\\n\");\n Test(\"Load\", Load);\n Test(\"LoadRecurse\", LoadRecurse);\n Test(\"Recurse\", Recurse);\n Test(\"RecurseSearch\", RecurseSearch);\n Test(\"Decompress\", Decompress);\n}<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2011 The LevelDB Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file. See the AUTHORS file for names of contributors.\n\n#include <stdio.h>\n\/\/#include \"leveldb\/expiry.h\"\n#include \"db\/dbformat.h\"\n#include \"db\/version_set.h\"\n#include \"port\/port.h\"\n#include \"util\/coding.h\"\n\nnamespace leveldb {\n\nstatic uint64_t PackSequenceAndType(uint64_t seq, ValueType t) {\n assert(seq <= kMaxSequenceNumber);\n \/\/ assert(t <= kValueTypeForSeek); requires revisit once expiry live\n assert(t <= kTypeValueExplicitExpiry); \/\/ temp replacement for above\n return (seq << 8) | t;\n}\n\nvoid AppendInternalKey(std::string* result, const ParsedInternalKey& key) {\n result->append(key.user_key.data(), key.user_key.size());\n if (IsExpiryKey(key.type))\n PutFixed64(result, key.expiry);\n PutFixed64(result, PackSequenceAndType(key.sequence, key.type));\n}\n\nstd::string ParsedInternalKey::DebugString() const {\n char buf[50];\n if (IsExpiryKey(type))\n snprintf(buf, sizeof(buf), \"' @ %llu %llu : %d\",\n (unsigned long long) expiry,\n (unsigned long long) sequence,\n int(type));\n else\n snprintf(buf, sizeof(buf), \"' @ %llu : %d\",\n (unsigned long long) sequence,\n int(type));\n std::string result = \"'\";\n result += HexString(user_key.ToString());\n result += buf;\n return result;\n}\n\nstd::string ParsedInternalKey::DebugStringHex() const {\n char buf[50];\n if (IsExpiryKey(type))\n snprintf(buf, sizeof(buf), \"' @ %llu %llu : %d\",\n (unsigned long long) expiry,\n (unsigned long long) sequence,\n int(type));\n else\n snprintf(buf, sizeof(buf), \"' @ %llu : %d\",\n (unsigned long long) sequence,\n int(type));\n std::string result = \"'\";\n result += HexString(user_key);\n result += buf;\n return result;\n}\n\nstd::string InternalKey::DebugString() const {\n std::string result;\n ParsedInternalKey parsed;\n if (ParseInternalKey(rep_, &parsed)) {\n result = parsed.DebugString();\n } else {\n result = \"(bad)\";\n result.append(EscapeString(rep_));\n }\n return result;\n}\n\nconst char* InternalKeyComparator::Name() const {\n return \"leveldb.InternalKeyComparator\";\n}\n\nint InternalKeyComparator::Compare(const Slice& akey, const Slice& bkey) const {\n \/\/ Order by:\n \/\/ increasing user key (according to user-supplied comparator)\n \/\/ decreasing sequence number\n \/\/ decreasing type (though sequence# should be enough to disambiguate)\n int r = user_comparator_->Compare(ExtractUserKey(akey), ExtractUserKey(bkey));\n if (r == 0) {\n uint64_t anum = DecodeFixed64(akey.data() + akey.size() - 8);\n uint64_t bnum = DecodeFixed64(bkey.data() + bkey.size() - 8);\n if (IsExpiryKey((ValueType)*(unsigned char *)&anum)) *(unsigned char*)&anum=(unsigned char)kTypeValue;\n if (IsExpiryKey((ValueType)*(unsigned char *)&bnum)) *(unsigned char*)&bnum=(unsigned char)kTypeValue;\n if (anum > bnum) {\n r = -1;\n } else if (anum < bnum) {\n r = +1;\n }\n }\n return r;\n}\n\nvoid InternalKeyComparator::FindShortestSeparator(\n std::string* start,\n const Slice& limit) const {\n \/\/ Attempt to shorten the user portion of the key\n Slice user_start = ExtractUserKey(*start);\n Slice user_limit = ExtractUserKey(limit);\n std::string tmp(user_start.data(), user_start.size());\n user_comparator_->FindShortestSeparator(&tmp, user_limit);\n if (tmp.size() < user_start.size() &&\n user_comparator_->Compare(user_start, tmp) < 0) {\n \/\/ User key has become shorter physically, but larger logically.\n \/\/ Tack on the earliest possible number to the shortened user key.\n PutFixed64(&tmp, PackSequenceAndType(kMaxSequenceNumber,kValueTypeForSeek));\n assert(this->Compare(*start, tmp) < 0);\n assert(this->Compare(tmp, limit) < 0);\n start->swap(tmp);\n }\n}\n\nvoid InternalKeyComparator::FindShortSuccessor(std::string* key) const {\n Slice user_key = ExtractUserKey(*key);\n std::string tmp(user_key.data(), user_key.size());\n user_comparator_->FindShortSuccessor(&tmp);\n if (tmp.size() < user_key.size() &&\n user_comparator_->Compare(user_key, tmp) < 0) {\n \/\/ User key has become shorter physically, but larger logically.\n \/\/ Tack on the earliest possible number to the shortened user key.\n PutFixed64(&tmp, PackSequenceAndType(kMaxSequenceNumber,kValueTypeForSeek));\n assert(this->Compare(*key, tmp) < 0);\n key->swap(tmp);\n }\n}\n\nconst char* InternalFilterPolicy::Name() const {\n return user_policy_->Name();\n}\n\nvoid InternalFilterPolicy::CreateFilter(const Slice* keys, int n,\n std::string* dst) const {\n \/\/ We rely on the fact that the code in table.cc does not mind us\n \/\/ adjusting keys[].\n Slice* mkey = const_cast<Slice*>(keys);\n for (int i = 0; i < n; i++) {\n mkey[i] = ExtractUserKey(keys[i]);\n \/\/ TODO(sanjay): Suppress dups?\n }\n user_policy_->CreateFilter(keys, n, dst);\n}\n\nbool InternalFilterPolicy::KeyMayMatch(const Slice& key, const Slice& f) const {\n return user_policy_->KeyMayMatch(ExtractUserKey(key), f);\n}\n\n LookupKey::LookupKey(const Slice& user_key, SequenceNumber s, KeyMetaData * meta) {\n meta_=meta;\n size_t usize = user_key.size();\n size_t needed = usize + 13; \/\/ A conservative estimate\n char* dst;\n if (needed <= sizeof(space_)) {\n dst = space_;\n } else {\n dst = new char[needed];\n }\n start_ = dst;\n dst = EncodeVarint32(dst, usize + 8);\n kstart_ = dst;\n memcpy(dst, user_key.data(), usize);\n dst += usize;\n EncodeFixed64(dst, PackSequenceAndType(s, kValueTypeForSeek));\n dst += 8;\n end_ = dst;\n}\n\n\nKeyRetirement::KeyRetirement(\n const Comparator * Comparator,\n SequenceNumber SmallestSnapshot,\n const Options * Opts,\n Compaction * const Compaction)\n : has_current_user_key(false), last_sequence_for_key(kMaxSequenceNumber),\n user_comparator(Comparator), smallest_snapshot(SmallestSnapshot),\n options(Opts), compaction(Compaction),\n valid(false), dropped(0), expired(0)\n{\n \/\/ NULL is ok for compaction\n valid=(NULL!=user_comparator);\n\n return;\n} \/\/ KeyRetirement::KeyRetirement\n\n\nKeyRetirement::~KeyRetirement()\n{\n if (0!=expired)\n gPerfCounters->Add(ePerfExpiredKeys, expired);\n} \/\/ KeyRetirement::~KeyRetirement\n\n\nbool\nKeyRetirement::operator()(\n Slice & key)\n{\n ParsedInternalKey ikey;\n bool drop = false;\n\n if (valid)\n {\n if (!ParseInternalKey(key, &ikey))\n {\n \/\/ Do not hide error keys\n current_user_key.clear();\n has_current_user_key = false;\n last_sequence_for_key = kMaxSequenceNumber;\n } \/\/ else\n else\n {\n if (!has_current_user_key ||\n user_comparator->Compare(ikey.user_key,\n Slice(current_user_key)) != 0)\n {\n \/\/ First occurrence of this user key\n current_user_key.assign(ikey.user_key.data(), ikey.user_key.size());\n has_current_user_key = true;\n last_sequence_for_key = kMaxSequenceNumber;\n } \/\/ if\n\n if (last_sequence_for_key <= smallest_snapshot)\n {\n \/\/ Hidden by an newer entry for same user key\n drop = true; \/\/ (A)\n } \/\/ if\n\n else\n {\n bool expired = false;\n\n if (NULL!=options && NULL!=options->expiry_module.get())\n expired=options->expiry_module->KeyRetirementCallback(ikey);\n\n if ((ikey.type == kTypeDeletion || expired)\n && ikey.sequence <= smallest_snapshot\n && NULL!=compaction \/\/ mem to level0 ignores this test\n && compaction->IsBaseLevelForKey(ikey.user_key))\n {\n \/\/ For this user key:\n \/\/ (1) there is no data in higher levels\n \/\/ (2) data in lower levels will have larger sequence numbers\n \/\/ (3) data in layers that are being compacted here and have\n \/\/ smaller sequence numbers will be dropped in the next\n \/\/ few iterations of this loop (by rule (A) above).\n \/\/ Therefore this deletion marker is obsolete and can be dropped.\n drop = true;\n\n if (expired)\n ++expired;\n else\n ++dropped;\n } \/\/ if\n } \/\/ else\n\n last_sequence_for_key = ikey.sequence;\n } \/\/ else\n } \/\/ if\n\n#if 0\n \/\/ needs clean up to be used again\n Log(options_.info_log,\n \" Compact: %s, seq %d, type: %d %d, drop: %d, is_base: %d, \"\n \"%d smallest_snapshot: %d\",\n ikey.user_key.ToString().c_str(),\n (int)ikey.sequence, ikey.type, kTypeValue, drop,\n compact->compaction->IsBaseLevelForKey(ikey.user_key),\n (int)last_sequence_for_key, (int)compact->smallest_snapshot);\n#endif\n return(drop);\n\n} \/\/ KeyRetirement::operator(Slice & )\n\n\n} \/\/ namespace leveldb\n<commit_msg>Clean up variable name usage. Had an object level expired variable and local expired variable. Yeah, this is why Matthew original code has m_ prefix for object variables (member variables). Not everything Microsoft did was bad.<commit_after>\/\/ Copyright (c) 2011 The LevelDB Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file. See the AUTHORS file for names of contributors.\n\n#include <stdio.h>\n\/\/#include \"leveldb\/expiry.h\"\n#include \"db\/dbformat.h\"\n#include \"db\/version_set.h\"\n#include \"port\/port.h\"\n#include \"util\/coding.h\"\n\nnamespace leveldb {\n\nstatic uint64_t PackSequenceAndType(uint64_t seq, ValueType t) {\n assert(seq <= kMaxSequenceNumber);\n \/\/ assert(t <= kValueTypeForSeek); requires revisit once expiry live\n assert(t <= kTypeValueExplicitExpiry); \/\/ temp replacement for above\n return (seq << 8) | t;\n}\n\nvoid AppendInternalKey(std::string* result, const ParsedInternalKey& key) {\n result->append(key.user_key.data(), key.user_key.size());\n if (IsExpiryKey(key.type))\n PutFixed64(result, key.expiry);\n PutFixed64(result, PackSequenceAndType(key.sequence, key.type));\n}\n\nstd::string ParsedInternalKey::DebugString() const {\n char buf[50];\n if (IsExpiryKey(type))\n snprintf(buf, sizeof(buf), \"' @ %llu %llu : %d\",\n (unsigned long long) expiry,\n (unsigned long long) sequence,\n int(type));\n else\n snprintf(buf, sizeof(buf), \"' @ %llu : %d\",\n (unsigned long long) sequence,\n int(type));\n std::string result = \"'\";\n result += HexString(user_key.ToString());\n result += buf;\n return result;\n}\n\nstd::string ParsedInternalKey::DebugStringHex() const {\n char buf[50];\n if (IsExpiryKey(type))\n snprintf(buf, sizeof(buf), \"' @ %llu %llu : %d\",\n (unsigned long long) expiry,\n (unsigned long long) sequence,\n int(type));\n else\n snprintf(buf, sizeof(buf), \"' @ %llu : %d\",\n (unsigned long long) sequence,\n int(type));\n std::string result = \"'\";\n result += HexString(user_key);\n result += buf;\n return result;\n}\n\nstd::string InternalKey::DebugString() const {\n std::string result;\n ParsedInternalKey parsed;\n if (ParseInternalKey(rep_, &parsed)) {\n result = parsed.DebugString();\n } else {\n result = \"(bad)\";\n result.append(EscapeString(rep_));\n }\n return result;\n}\n\nconst char* InternalKeyComparator::Name() const {\n return \"leveldb.InternalKeyComparator\";\n}\n\nint InternalKeyComparator::Compare(const Slice& akey, const Slice& bkey) const {\n \/\/ Order by:\n \/\/ increasing user key (according to user-supplied comparator)\n \/\/ decreasing sequence number\n \/\/ decreasing type (though sequence# should be enough to disambiguate)\n int r = user_comparator_->Compare(ExtractUserKey(akey), ExtractUserKey(bkey));\n if (r == 0) {\n uint64_t anum = DecodeFixed64(akey.data() + akey.size() - 8);\n uint64_t bnum = DecodeFixed64(bkey.data() + bkey.size() - 8);\n if (IsExpiryKey((ValueType)*(unsigned char *)&anum)) *(unsigned char*)&anum=(unsigned char)kTypeValue;\n if (IsExpiryKey((ValueType)*(unsigned char *)&bnum)) *(unsigned char*)&bnum=(unsigned char)kTypeValue;\n if (anum > bnum) {\n r = -1;\n } else if (anum < bnum) {\n r = +1;\n }\n }\n return r;\n}\n\nvoid InternalKeyComparator::FindShortestSeparator(\n std::string* start,\n const Slice& limit) const {\n \/\/ Attempt to shorten the user portion of the key\n Slice user_start = ExtractUserKey(*start);\n Slice user_limit = ExtractUserKey(limit);\n std::string tmp(user_start.data(), user_start.size());\n user_comparator_->FindShortestSeparator(&tmp, user_limit);\n if (tmp.size() < user_start.size() &&\n user_comparator_->Compare(user_start, tmp) < 0) {\n \/\/ User key has become shorter physically, but larger logically.\n \/\/ Tack on the earliest possible number to the shortened user key.\n PutFixed64(&tmp, PackSequenceAndType(kMaxSequenceNumber,kValueTypeForSeek));\n assert(this->Compare(*start, tmp) < 0);\n assert(this->Compare(tmp, limit) < 0);\n start->swap(tmp);\n }\n}\n\nvoid InternalKeyComparator::FindShortSuccessor(std::string* key) const {\n Slice user_key = ExtractUserKey(*key);\n std::string tmp(user_key.data(), user_key.size());\n user_comparator_->FindShortSuccessor(&tmp);\n if (tmp.size() < user_key.size() &&\n user_comparator_->Compare(user_key, tmp) < 0) {\n \/\/ User key has become shorter physically, but larger logically.\n \/\/ Tack on the earliest possible number to the shortened user key.\n PutFixed64(&tmp, PackSequenceAndType(kMaxSequenceNumber,kValueTypeForSeek));\n assert(this->Compare(*key, tmp) < 0);\n key->swap(tmp);\n }\n}\n\nconst char* InternalFilterPolicy::Name() const {\n return user_policy_->Name();\n}\n\nvoid InternalFilterPolicy::CreateFilter(const Slice* keys, int n,\n std::string* dst) const {\n \/\/ We rely on the fact that the code in table.cc does not mind us\n \/\/ adjusting keys[].\n Slice* mkey = const_cast<Slice*>(keys);\n for (int i = 0; i < n; i++) {\n mkey[i] = ExtractUserKey(keys[i]);\n \/\/ TODO(sanjay): Suppress dups?\n }\n user_policy_->CreateFilter(keys, n, dst);\n}\n\nbool InternalFilterPolicy::KeyMayMatch(const Slice& key, const Slice& f) const {\n return user_policy_->KeyMayMatch(ExtractUserKey(key), f);\n}\n\n LookupKey::LookupKey(const Slice& user_key, SequenceNumber s, KeyMetaData * meta) {\n meta_=meta;\n size_t usize = user_key.size();\n size_t needed = usize + 13; \/\/ A conservative estimate\n char* dst;\n if (needed <= sizeof(space_)) {\n dst = space_;\n } else {\n dst = new char[needed];\n }\n start_ = dst;\n dst = EncodeVarint32(dst, usize + 8);\n kstart_ = dst;\n memcpy(dst, user_key.data(), usize);\n dst += usize;\n EncodeFixed64(dst, PackSequenceAndType(s, kValueTypeForSeek));\n dst += 8;\n end_ = dst;\n}\n\n\nKeyRetirement::KeyRetirement(\n const Comparator * Comparator,\n SequenceNumber SmallestSnapshot,\n const Options * Opts,\n Compaction * const Compaction)\n : has_current_user_key(false), last_sequence_for_key(kMaxSequenceNumber),\n user_comparator(Comparator), smallest_snapshot(SmallestSnapshot),\n options(Opts), compaction(Compaction),\n valid(false), dropped(0), expired(0)\n{\n \/\/ NULL is ok for compaction\n valid=(NULL!=user_comparator);\n\n return;\n} \/\/ KeyRetirement::KeyRetirement\n\n\nKeyRetirement::~KeyRetirement()\n{\n if (0!=expired)\n gPerfCounters->Add(ePerfExpiredKeys, expired);\n} \/\/ KeyRetirement::~KeyRetirement\n\n\nbool\nKeyRetirement::operator()(\n Slice & key)\n{\n ParsedInternalKey ikey;\n bool drop = false, expire_flag;\n\n if (valid)\n {\n if (!ParseInternalKey(key, &ikey))\n {\n \/\/ Do not hide error keys\n current_user_key.clear();\n has_current_user_key = false;\n last_sequence_for_key = kMaxSequenceNumber;\n } \/\/ else\n else\n {\n if (!has_current_user_key ||\n user_comparator->Compare(ikey.user_key,\n Slice(current_user_key)) != 0)\n {\n \/\/ First occurrence of this user key\n current_user_key.assign(ikey.user_key.data(), ikey.user_key.size());\n has_current_user_key = true;\n last_sequence_for_key = kMaxSequenceNumber;\n } \/\/ if\n\n if (last_sequence_for_key <= smallest_snapshot)\n {\n \/\/ Hidden by an newer entry for same user key\n drop = true; \/\/ (A)\n } \/\/ if\n\n else\n {\n if (NULL!=options && NULL!=options->expiry_module.get())\n expire_flag=options->expiry_module->KeyRetirementCallback(ikey);\n\n if ((ikey.type == kTypeDeletion || expire_flag)\n && ikey.sequence <= smallest_snapshot\n && NULL!=compaction \/\/ mem to level0 ignores this test\n && compaction->IsBaseLevelForKey(ikey.user_key))\n {\n \/\/ For this user key:\n \/\/ (1) there is no data in higher levels\n \/\/ (2) data in lower levels will have larger sequence numbers\n \/\/ (3) data in layers that are being compacted here and have\n \/\/ smaller sequence numbers will be dropped in the next\n \/\/ few iterations of this loop (by rule (A) above).\n \/\/ Therefore this deletion marker is obsolete and can be dropped.\n drop = true;\n\n if (expire_flag)\n ++expired;\n else\n ++dropped;\n } \/\/ if\n } \/\/ else\n\n last_sequence_for_key = ikey.sequence;\n } \/\/ else\n } \/\/ if\n\n#if 0\n \/\/ needs clean up to be used again\n Log(options_.info_log,\n \" Compact: %s, seq %d, type: %d %d, drop: %d, is_base: %d, \"\n \"%d smallest_snapshot: %d\",\n ikey.user_key.ToString().c_str(),\n (int)ikey.sequence, ikey.type, kTypeValue, drop,\n compact->compaction->IsBaseLevelForKey(ikey.user_key),\n (int)last_sequence_for_key, (int)compact->smallest_snapshot);\n#endif\n return(drop);\n\n} \/\/ KeyRetirement::operator(Slice & )\n\n\n} \/\/ namespace leveldb\n<|endoftext|>"} {"text":"<commit_before>#include <config.h>\n#include <assert.h>\n#include <boost\/concept\/usage.hpp>\n#include <boost\/format.hpp>\n#include <dune\/common\/exceptions.hh>\n#include <dune\/istl\/scalarproducts.hh>\n#include <dune\/istl\/solvers.hh>\n#include <dune\/multiscale\/msfem\/localproblems\/localoperator.hh>\n#include <dune\/multiscale\/problems\/selector.hh>\n#include <dune\/multiscale\/common\/df_io.hh>\n#include <dune\/multiscale\/msfem\/localproblems\/localsolutionmanager.hh>\n#include <dune\/multiscale\/tools\/misc.hh>\n#include <dune\/xt\/common\/logging.hh>\n#include <dune\/xt\/common\/math.hh>\n#include <dune\/xt\/common\/memory.hh>\n#include <dune\/xt\/common\/configuration.hh>\n#include <dune\/xt\/common\/timings.hh>\n#include <dune\/xt\/common\/ranges.hh>\n#include <dune\/xt\/common\/parallel\/partitioner.hh>\n#include <dune\/grid\/utility\/partitioning\/seedlist.hh>\n#include <dune\/gdt\/products\/l2.hh>\n#include <dune\/stuff\/grid\/walker.hh>\n#include <dune\/stuff\/grid\/walker\/functors.hh>\n#include <iterator>\n#include <memory>\n#include <sstream>\n#include <string>\n#include <tuple>\n#include <vector>\n\n#include <dune\/multiscale\/msfem\/localproblems\/localgridlist.hh>\n#include <dune\/multiscale\/tools\/misc\/outputparameter.hh>\n#include \"localproblemsolver.hh\"\n\nnamespace Dune {\nnamespace Multiscale {\n\n\/** \\brief define output parameters for local problems\n * appends \"local_problems\" for path\n **\/\nstruct LocalProblemDataOutputParameters : public OutputParameters {\npublic:\n explicit LocalProblemDataOutputParameters(const Problem::ProblemContainer& problem);\n};\n\nLocalProblemDataOutputParameters::LocalProblemDataOutputParameters(const DMP::ProblemContainer& problem)\n : OutputParameters(problem.config().get(\"global.datadir\", \"data\") + std::string(\"\/local_problems\/\")) {}\n\nLocalProblemSolver::LocalProblemSolver(const Problem::ProblemContainer& problem, CommonTraits::SpaceType coarse_space,\n LocalGridList& localgrid_list)\n : localgrid_list_(localgrid_list)\n , coarse_space_(coarse_space)\n , problem_(problem) {}\n\nvoid LocalProblemSolver::solve_all_on_single_cell(const MsFEMTraits::CoarseEntityType& coarseCell,\n MsFEMTraits::LocalSolutionVectorType& allLocalSolutions) const {\n assert(allLocalSolutions.size() > 0);\n\n const bool hasBoundary = coarseCell.hasBoundaryIntersections();\n const auto numBoundaryCorrectors = DSG::is_simplex_grid(*coarse_space_) ? 1u : 2u;\n const auto numInnerCorrectors = allLocalSolutions.size() - numBoundaryCorrectors;\n\n \/\/ clear return argument\n for (auto& localSol : allLocalSolutions)\n localSol->vector() *= 0;\n\n const auto& subDiscreteFunctionSpace = allLocalSolutions[0]->space();\n\n \/\/! define the discrete (elliptic) local MsFEM problem operator\n \/\/ ( effect of the discretized differential operator on a certain discrete function )\n LocalProblemOperator localProblemOperator(problem_, *coarse_space_, subDiscreteFunctionSpace);\n\n \/\/ right hand side vector of the algebraic local MsFEM problem\n MsFEMTraits::LocalSolutionVectorType allLocalRHS(allLocalSolutions.size());\n for (auto& it : allLocalRHS)\n it = Dune::XT::Common::make_unique<MsFEMTraits::LocalGridDiscreteFunctionType>(subDiscreteFunctionSpace,\n \"rhs of local MsFEM problem\");\n\n localProblemOperator.assemble_all_local_rhs(coarseCell, allLocalRHS);\n\n for (auto i : Dune::XT::Common::value_range(allLocalSolutions.size())) {\n auto& current_rhs = *allLocalRHS[i];\n auto& current_solution = *allLocalSolutions[i];\n\n \/\/ is the right hand side of the local MsFEM problem equal to zero or almost identical to zero?\n \/\/ if yes, the solution of the local MsFEM problem is also identical to zero. The solver is getting a problem with\n \/\/ this situation, which is why we do not solve local msfem problems for zero-right-hand-side, since we already know\n \/\/ the result.\n \/\/! TODO calculating the norm seems to have a bad perf impact, is the instability actually still there?\n \/\/ const auto norm = GDT::Products::L2<typename MsFEMTraits::LocalGridViewType>(current_rhs.space().grid_view())\n \/\/ .induced_norm(current_rhs);\n \/\/ if (norm < 1e-12) {\n \/\/ current_solution.vector() *= 0;\n \/\/ MS_LOG_DEBUG << boost::format(\"Local MsFEM problem with solution zero. (corrector %d)\") % i << std::endl;\n \/\/ continue;\n \/\/ }\n \/\/ don't solve local problems for boundary correctors if coarse cell has no boundary intersections\n if (i >= numInnerCorrectors && !hasBoundary) {\n current_solution.vector() *= 0;\n MS_LOG_DEBUG << \"Zero-Boundary corrector.\" << std::endl;\n continue;\n }\n localProblemOperator.apply_inverse(current_rhs, current_solution);\n }\n}\n\nvoid LocalProblemSolver::solve_for_all_cells() {\n const auto& grid = coarse_space_->grid_view().grid();\n const auto coarseGridSize = grid.size(0) - grid.overlapSize(0);\n\n if (grid.comm().size() > 0)\n MS_LOG_DEBUG << \"Rank \" << grid.comm().rank() << \" will solve local problems for \" << coarseGridSize\n << \" coarse entities!\" << std::endl;\n else {\n MS_LOG_DEBUG << \"Will solve local problems for \" << coarseGridSize << \" coarse entities!\" << std::endl;\n }\n DXTC_TIMINGS.start(\"msfem.local.solve_for_all_cells\");\n\n \/\/ we want to determine minimum, average and maxiumum time for solving a local msfem problem in the current method\n Dune::XT::Common::MinMaxAvg<double> solveTime;\n\n const auto interior = coarse_space_->grid_view().grid().template leafGridView<InteriorBorder_Partition>();\n typedef std::remove_const<decltype(interior)>::type InteriorType;\n GDT::SystemAssembler<CommonTraits::SpaceType, InteriorType> walker(*coarse_space_, interior);\n Dune::XT::Common::IndexSetPartitioner<InteriorType> ip(interior.indexSet());\n SeedListPartitioning<typename InteriorType::Grid, 0> partitioning(interior, ip);\n\n const std::function<void(const CommonTraits::EntityType&)> func = [&](const CommonTraits::EntityType& coarseEntity) {\n const int coarse_index = walker.ansatz_space().grid_view().indexSet().index(coarseEntity);\n MS_LOG_DEBUG << \"-------------------------\" << std::endl << \"Coarse index \" << coarse_index << std::endl;\n\n \/\/ take time\n \/\/ DXTC_TIMINGS.start(\"msfem.local.solve_all_on_single_cell\");\n LocalSolutionManager localSolutionManager(*coarse_space_, coarseEntity, localgrid_list_);\n \/\/ solve the problems\n solve_all_on_single_cell(coarseEntity, localSolutionManager.getLocalSolutions());\n \/\/ solveTime(DXTC_TIMINGS.stop(\"msfem.local.solve_all_on_single_cell\") \/ 1000.f);\n\n \/\/ save the local solutions to disk\/mem\n localSolutionManager.save();\n\n \/\/ DXTC_TIMINGS.resetTiming(\"msfem.local.solve_all_on_single_cell\");\n };\n\n walker.add(func);\n walker.assemble(partitioning);\n\n \/\/! @todo The following debug-output is wrong (number of local problems may be different)\n const auto totalTime = DXTC_TIMINGS.stop(\"msfem.local.solve_for_all_cells\") \/ 1000.f;\n MS_LOG_INFO << \"Local problems solved for \" << coarseGridSize << \" coarse grid entities.\\n\"\n \/\/ << \"Minimum time for solving a local problem = \" << solveTime.min() << \"s.\\n\"\n \/\/ << \"Maximum time for solving a local problem = \" << solveTime.max() << \"s.\\n\"\n \/\/ << \"Average time for solving a local problem = \" << solveTime.average() << \"s.\\n\"\n << \"Total time for computing and saving the localproblems = \" << totalTime << \"s on rank\"\n << coarse_space_->grid_view().grid().comm().rank() << std::endl;\n} \/\/ assemble_all\n\n} \/\/ namespace Multiscale {\n} \/\/ namespace Dune {\n<commit_msg>reqire per cell output<commit_after>#include <config.h>\n#include <assert.h>\n#include <boost\/concept\/usage.hpp>\n#include <boost\/format.hpp>\n#include <dune\/common\/exceptions.hh>\n#include <dune\/istl\/scalarproducts.hh>\n#include <dune\/istl\/solvers.hh>\n#include <dune\/multiscale\/msfem\/localproblems\/localoperator.hh>\n#include <dune\/multiscale\/problems\/selector.hh>\n#include <dune\/multiscale\/common\/df_io.hh>\n#include <dune\/multiscale\/msfem\/localproblems\/localsolutionmanager.hh>\n#include <dune\/multiscale\/tools\/misc.hh>\n#include <dune\/xt\/common\/logging.hh>\n#include <dune\/xt\/common\/math.hh>\n#include <dune\/xt\/common\/memory.hh>\n#include <dune\/xt\/common\/configuration.hh>\n#include <dune\/xt\/common\/timings.hh>\n#include <dune\/xt\/common\/ranges.hh>\n#include <dune\/xt\/common\/parallel\/partitioner.hh>\n#include <dune\/grid\/utility\/partitioning\/seedlist.hh>\n#include <dune\/gdt\/products\/l2.hh>\n#include <dune\/stuff\/grid\/walker.hh>\n#include <dune\/stuff\/grid\/walker\/functors.hh>\n#include <iterator>\n#include <memory>\n#include <sstream>\n#include <string>\n#include <tuple>\n#include <vector>\n\n#include <dune\/multiscale\/msfem\/localproblems\/localgridlist.hh>\n#include <dune\/multiscale\/tools\/misc\/outputparameter.hh>\n#include \"localproblemsolver.hh\"\n\nnamespace Dune {\nnamespace Multiscale {\n\n\/** \\brief define output parameters for local problems\n * appends \"local_problems\" for path\n **\/\nstruct LocalProblemDataOutputParameters : public OutputParameters {\npublic:\n explicit LocalProblemDataOutputParameters(const Problem::ProblemContainer& problem);\n};\n\nLocalProblemDataOutputParameters::LocalProblemDataOutputParameters(const DMP::ProblemContainer& problem)\n : OutputParameters(problem.config().get(\"global.datadir\", \"data\") + std::string(\"\/local_problems\/\")) {}\n\nLocalProblemSolver::LocalProblemSolver(const Problem::ProblemContainer& problem, CommonTraits::SpaceType coarse_space,\n LocalGridList& localgrid_list)\n : localgrid_list_(localgrid_list)\n , coarse_space_(coarse_space)\n , problem_(problem) {}\n\nvoid LocalProblemSolver::solve_all_on_single_cell(const MsFEMTraits::CoarseEntityType& coarseCell,\n MsFEMTraits::LocalSolutionVectorType& allLocalSolutions) const {\n assert(allLocalSolutions.size() > 0);\n\n const bool hasBoundary = coarseCell.hasBoundaryIntersections();\n const auto numBoundaryCorrectors = DSG::is_simplex_grid(*coarse_space_) ? 1u : 2u;\n const auto numInnerCorrectors = allLocalSolutions.size() - numBoundaryCorrectors;\n\n \/\/ clear return argument\n for (auto& localSol : allLocalSolutions)\n localSol->vector() *= 0;\n\n const auto& subDiscreteFunctionSpace = allLocalSolutions[0]->space();\n\n \/\/! define the discrete (elliptic) local MsFEM problem operator\n \/\/ ( effect of the discretized differential operator on a certain discrete function )\n LocalProblemOperator localProblemOperator(problem_, *coarse_space_, subDiscreteFunctionSpace);\n\n \/\/ right hand side vector of the algebraic local MsFEM problem\n MsFEMTraits::LocalSolutionVectorType allLocalRHS(allLocalSolutions.size());\n for (auto& it : allLocalRHS)\n it = Dune::XT::Common::make_unique<MsFEMTraits::LocalGridDiscreteFunctionType>(subDiscreteFunctionSpace,\n \"rhs of local MsFEM problem\");\n\n localProblemOperator.assemble_all_local_rhs(coarseCell, allLocalRHS);\n\n for (auto i : Dune::XT::Common::value_range(allLocalSolutions.size())) {\n auto& current_rhs = *allLocalRHS[i];\n auto& current_solution = *allLocalSolutions[i];\n\n \/\/ is the right hand side of the local MsFEM problem equal to zero or almost identical to zero?\n \/\/ if yes, the solution of the local MsFEM problem is also identical to zero. The solver is getting a problem with\n \/\/ this situation, which is why we do not solve local msfem problems for zero-right-hand-side, since we already know\n \/\/ the result.\n \/\/! TODO calculating the norm has really bad performance impact, is the instability actually still there?\n \/\/ const auto norm = GDT::Products::L2<typename MsFEMTraits::LocalGridViewType>(current_rhs.space().grid_view())\n \/\/ .induced_norm(current_rhs);\n \/\/ if (norm < 1e-12) {\n \/\/ current_solution.vector() *= 0;\n \/\/ MS_LOG_DEBUG << boost::format(\"Local MsFEM problem with solution zero. (corrector %d)\") % i << std::endl;\n \/\/ continue;\n \/\/ }\n\n \/\/ don't solve local problems for boundary correctors if coarse cell has no boundary intersections\n if (i >= numInnerCorrectors && !hasBoundary) {\n current_solution.vector() *= 0;\n MS_LOG_DEBUG << \"Zero-Boundary corrector.\" << std::endl;\n continue;\n }\n localProblemOperator.apply_inverse(current_rhs, current_solution);\n }\n}\n\nvoid LocalProblemSolver::solve_for_all_cells() {\n const auto& grid = coarse_space_->grid_view().grid();\n const auto coarseGridSize = grid.size(0) - grid.overlapSize(0);\n\n MS_LOG_INFO << boost::format(\"Rank %d will solve local problems for %d coarse entities\\n\")\n % grid.comm().rank() % coarseGridSize;\n DXTC_TIMINGS.start(\"msfem.local.solve_for_all_cells\");\n\n \/\/ we want to determine minimum, average and maxiumum time for solving a local msfem problem in the current method\n Dune::XT::Common::MinMaxAvg<double> solveTime;\n\n const auto interior = coarse_space_->grid_view().grid().template leafGridView<InteriorBorder_Partition>();\n typedef std::remove_const<decltype(interior)>::type InteriorType;\n GDT::SystemAssembler<CommonTraits::SpaceType, InteriorType> walker(*coarse_space_, interior);\n Dune::XT::Common::IndexSetPartitioner<InteriorType> ip(interior.indexSet());\n SeedListPartitioning<typename InteriorType::Grid, 0> partitioning(interior, ip);\n\n const std::function<void(const CommonTraits::EntityType&)> func = [&](const CommonTraits::EntityType& coarseEntity) {\n const int coarse_index = walker.ansatz_space().grid_view().indexSet().index(coarseEntity);\n MS_LOG_DEBUG << \"-------------------------\" << std::endl << \"Coarse index \" << coarse_index << std::endl;\n\n\n \/\/ take time\n \/\/ DXTC_TIMINGS.start(\"msfem.local.solve_all_on_single_cell\");\n LocalSolutionManager localSolutionManager(*coarse_space_, coarseEntity, localgrid_list_);\n \/\/ solve the problems\n solve_all_on_single_cell(coarseEntity, localSolutionManager.getLocalSolutions());\n \/\/ solveTime(DXTC_TIMINGS.stop(\"msfem.local.solve_all_on_single_cell\") \/ 1000.f);\n\n \/\/ save the local solutions to disk\/mem\n localSolutionManager.save();\n\n \/\/ DXTC_TIMINGS.resetTiming(\"msfem.local.solve_all_on_single_cell\");\n };\n\n walker.add(func);\n walker.assemble(partitioning);\n\n \/\/! @todo The following debug-output is wrong (number of local problems may be different)\n const auto totalTime = DXTC_TIMINGS.stop(\"msfem.local.solve_for_all_cells\") \/ 1000.f;\n MS_LOG_INFO << \"Local problems solved for \" << coarseGridSize << \" coarse grid entities.\\n\"\n \/\/ << \"Minimum time for solving a local problem = \" << solveTime.min() << \"s.\\n\"\n \/\/ << \"Maximum time for solving a local problem = \" << solveTime.max() << \"s.\\n\"\n \/\/ << \"Average time for solving a local problem = \" << solveTime.average() << \"s.\\n\"\n << \"Total time for computing and saving the localproblems = \" << totalTime << \"s on rank\"\n << coarse_space_->grid_view().grid().comm().rank() << std::endl;\n} \/\/ assemble_all\n\n} \/\/ namespace Multiscale {\n} \/\/ namespace Dune {\n<|endoftext|>"} {"text":"<commit_before>\/*=========================================================================\n\n Program: ORFEO Toolbox\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n\n Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.\n See OTBCopyright.txt for details.\n\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notices for more information.\n\n =========================================================================*\/\n#include \"otbWrapperApplication.h\"\n#include \"otbWrapperApplicationFactory.h\"\n\n#include \"otbImageToLuminanceImageFilter.h\"\n#include \"otbLuminanceToReflectanceImageFilter.h\"\n#include \"otbReflectanceToSurfaceReflectanceImageFilter.h\"\n#include \"otbMultiplyByScalarImageFilter.h\"\n#include \"otbClampVectorImageFilter.h\"\n#include \"otbSurfaceAdjacencyEffect6SCorrectionSchemeFilter.h\"\n#include \"otbGroundSpacingImageFunction.h\"\n#include \"vnl\/vnl_random.h\"\n\nnamespace otb\n{\n\nenum\n{\n Level_TOA,\n Level_TOC\n};\n\nenum\n{\n Aerosol_NoAerosol,\n Aerosol_Continental,\n Aerosol_Maritime,\n Aerosol_Urban,\n Aerosol_Desertic,\n};\n\nnamespace Wrapper\n{\n\nclass OpticalCalibration : public Application\n{\n\npublic:\n \/** Standard class typedefs. *\/\n typedef OpticalCalibration Self;\n typedef Application Superclass;\n typedef itk::SmartPointer<Self> Pointer;\n typedef itk::SmartPointer<const Self> ConstPointer;\n\n \/** Standard macro *\/\n itkNewMacro(Self);\n\n itkTypeMacro(OpticalCalibration, Application);\n\n typedef ImageToLuminanceImageFilter<UInt16VectorImageType,\n DoubleVectorImageType> ImageToLuminanceImageFilterType;\n\n typedef LuminanceToReflectanceImageFilter<DoubleVectorImageType,\n DoubleVectorImageType> LuminanceToReflectanceImageFilterType;\n\n typedef otb::MultiplyByScalarImageFilter<DoubleVectorImageType,\n DoubleVectorImageType> ScaleFilterType;\n\n typedef otb::ClampVectorImageFilter<DoubleVectorImageType,\n DoubleVectorImageType> ClampFilterType;\n\n typedef ReflectanceToSurfaceReflectanceImageFilter<DoubleVectorImageType,\n DoubleVectorImageType> ReflectanceToSurfaceReflectanceImageFilterType;\n typedef ReflectanceToSurfaceReflectanceImageFilterType::FilterFunctionValuesType FilterFunctionValuesType;\n typedef FilterFunctionValuesType::ValuesVectorType ValuesVectorType;\n typedef AtmosphericCorrectionParameters AtmosphericCorrectionParametersType;\n typedef AtmosphericCorrectionParametersType::AerosolModelType AerosolModelType;\n\n typedef otb::SurfaceAdjacencyEffect6SCorrectionSchemeFilter<DoubleVectorImageType,DoubleVectorImageType>\n SurfaceAdjacencyEffect6SCorrectionSchemeFilterType;\n\n typedef otb::GroundSpacingImageFunction<UInt16VectorImageType> GroundSpacingImageType;\n\n typedef UInt16VectorImageType::IndexType IndexType;\n typedef GroundSpacingImageType::FloatType FloatType;\n typedef GroundSpacingImageType::ValueType ValueType;\n\n typedef IndexType::IndexValueType IndexValueType;\n\n\nprivate:\n void DoInit()\n {\n SetName(\"OpticalCalibration\");\n SetDescription(\"Perform optical calibration TOA\/TOC (Top Of Atmosphere\/Top Of Canopy). Supported sensors: QuickBird, Ikonos, WorldView2, Formosat, Spot5, Pleiades\");\n \/\/ Documentation\n SetDocName(\"Optical calibration\");\n SetDocLongDescription(\"The application allows to convert pixel values from DN (for Digital Numbers) to physically interpretable and comparable values. Calibrated values are called surface reflectivity and its values lie in the range [0, 1].\\nThe first level is called Top Of Atmosphere (TOA) reflectivity. It takes into account the sensor gain, sensor spectral response and the solar illumination.\\nThe second level is called Top Of Canopy (TOC) reflectivity. In addition to sensor gain and solar illumination, it takes into account the optical thickness of the atmosphere, the atmospheric pressure, the water vapor amount, the ozone amount, as well as the composition and amount of aerosol gasses.\\nIt is also possible to indicate an AERONET file which contains atmospheric parameters (version 1 and version 2 of Aeronet file are supported.\");\n SetDocLimitations(\"None\");\n SetDocAuthors(\"OTB-Team\");\n SetDocSeeAlso(\"The OTB CookBook\");\n\n AddDocTag(Tags::Calibration);\n\n AddParameter(ParameterType_InputImage, \"in\", \"Input\");\n SetParameterDescription(\"in\", \"Input image filename (values in DN)\");\n\n AddParameter(ParameterType_OutputImage, \"out\", \"Output\");\n SetParameterDescription(\"out\",\"Output calibrated image filename\");\n\n AddRAMParameter();\n\n AddParameter(ParameterType_Choice, \"level\", \"Calibration Level\");\n AddChoice(\"level.toa\", \"TOA : Top Of Atmosphere\");\n AddChoice(\"level.toc\", \"TOC : Top Of Canopy (EXPERIMENTAL)\");\n SetParameterString(\"level\", \"toa\");\n\n AddParameter(ParameterType_Empty, \"milli\", \"Convert to milli reflectance\");\n SetParameterDescription(\"milli\", \"Flag to use milli-reflectance instead of reflectance.\\n\"\n \"This allows to save the image with integer pixel type (in the range [0, 1000] instead of floating point in the range [0, 1]. In order to do that, use this option and set the output pixel type (-out filename uint16 for example)\");\n DisableParameter(\"milli\");\n MandatoryOff(\"milli\");\n\n AddParameter(ParameterType_Empty, \"clamp\", \"Clamp of reflectivity values between [0% , 100%]\");\n SetParameterDescription(\"clamp\", \"Clamping in the range [0% , 100%]. It can be usefull to preserve area with specular reflectance.\");\n EnableParameter(\"clamp\");\n MandatoryOff(\"clamp\");\n\n AddParameter(ParameterType_InputFilename, \"rsr\", \"Relative Spectral Response File\");\n std::ostringstream oss;\n oss << \"Sensor relative spectral response file\"<<std::endl;\n oss << \"By default the application gets these informations in the metadata\";\n SetParameterDescription(\"rsr\", oss.str());\n MandatoryOff(\"rsr\");\n\n AddParameter(ParameterType_Group,\"atmo\",\"Atmospheric parameters\");\n SetParameterDescription(\"atmo\",\"This group allows to set the atmospheric parameters.\");\n AddParameter(ParameterType_Choice, \"atmo.aerosol\", \"Aerosol Model\");\n AddChoice(\"atmo.aerosol.noaersol\", \"No Aerosol Model\");\n AddChoice(\"atmo.aerosol.continental\", \"Continental\");\n AddChoice(\"atmo.aerosol.maritime\", \"Maritime\");\n AddChoice(\"atmo.aerosol.urban\", \"Urban\");\n AddChoice(\"atmo.aerosol.desertic\", \"Desertic\");\n\n AddParameter(ParameterType_Float, \"atmo.oz\", \"Ozone Amount\");\n SetParameterDescription(\"atmo.oz\", \"Ozone Amount\");\n\n AddParameter(ParameterType_Float, \"atmo.wa\", \"Water Vapor Amount\");\n SetParameterDescription(\"atmo.wa\", \"Water Vapor Amount (in saturation fraction of water)\");\n\n AddParameter(ParameterType_Float, \"atmo.pressure\", \"Atmospheric Pressure\");\n SetParameterDescription(\"atmo.pressure\", \"Atmospheric Pressure (in hPa)\");\n\n AddParameter(ParameterType_Float, \"atmo.opt\", \"Aerosol Optical Thickness\");\n SetParameterDescription(\"atmo.opt\", \"Aerosol Optical Thickness\");\n\n SetDefaultParameterFloat(\"atmo.oz\", 0.);\n SetDefaultParameterFloat(\"atmo.wa\", 2.5);\n SetDefaultParameterFloat(\"atmo.pressure\", 1030.);\n\n SetDefaultParameterFloat(\"atmo.opt\", 0.2);\n MandatoryOff(\"atmo.oz\");\n MandatoryOff(\"atmo.wa\");\n MandatoryOff(\"atmo.pressure\");\n MandatoryOff(\"atmo.opt\");\n\n AddParameter(ParameterType_InputFilename, \"atmo.aeronet\", \"Aeronet File\");\n SetParameterDescription(\"atmo.aeronet\",\"Aeronet file containing atmospheric parameters\");\n MandatoryOff(\"atmo.aeronet\");\n\n \/\/ Window radius for adjacency effects correction\n AddParameter(ParameterType_Int, \"radius\", \"Window radius\");\n SetParameterDescription(\"radius\",\"Window radius for adjacency effects corrections\");\n MandatoryOff(\"radius\");\n SetDefaultParameterInt(\"radius\", 2);\n\n \/\/ Doc example parameter settings\n SetDocExampleParameterValue(\"in\", \"QB_1_ortho.tif\");\n SetDocExampleParameterValue(\"level\", \"toa\");\n SetDocExampleParameterValue(\"out\", \"OpticalCalibration.tif\");\n }\n\n void DoUpdateParameters()\n {\n \/\/ Nothing to update\n }\n\n void DoExecute()\n {\n UInt16VectorImageType::Pointer inImage = GetParameterUInt16VectorImage(\"in\");\n\n \/\/Check if valid metadata informations are available to compute ImageToLuminance and LuminanceToReflectance\n itk::MetaDataDictionary dict = inImage->GetMetaDataDictionary();\n OpticalImageMetadataInterface::Pointer lImageMetadataInterface = OpticalImageMetadataInterfaceFactory::CreateIMI(dict);\n\n \/\/ Test if needed data are available : an exception will be thrown\n \/\/ if one the following Get* return failure. the exception is then\n \/\/ caught in the Wrapper::Application class which redirect it to\n \/\/ the logger\n \/\/ ImageToLuminance\n lImageMetadataInterface->GetPhysicalGain();\n lImageMetadataInterface->GetPhysicalBias();\n\n \/\/ LuminanceToReflectance\n lImageMetadataInterface->GetDay();\n lImageMetadataInterface->GetMonth();\n\n lImageMetadataInterface->GetSolarIrradiance();\n lImageMetadataInterface->GetSunElevation();\n\n m_ImageToLuminanceFilter = ImageToLuminanceImageFilterType::New();\n m_LuminanceToReflectanceFilter = LuminanceToReflectanceImageFilterType::New();\n m_ReflectanceToSurfaceReflectanceFilter = ReflectanceToSurfaceReflectanceImageFilterType::New();\n\n m_ImageToLuminanceFilter->SetInput(inImage);\n m_LuminanceToReflectanceFilter->SetInput(m_ImageToLuminanceFilter->GetOutput());\n m_ReflectanceToSurfaceReflectanceFilter->SetInput(m_LuminanceToReflectanceFilter->GetOutput());\n\n m_ScaleFilter = ScaleFilterType::New();\n m_ScaleFilter->InPlaceOn();\n\n m_ClampFilter = ClampFilterType::New();\n\n switch ( GetParameterInt(\"level\") )\n {\n case Level_TOA:\n {\n m_LuminanceToReflectanceFilter->SetUseClamp(IsParameterEnabled(\"clamp\"));\n\n m_LuminanceToReflectanceFilter->UpdateOutputInformation();\n m_ScaleFilter->SetInput(m_LuminanceToReflectanceFilter->GetOutput());\n }\n break;\n case Level_TOC:\n {\n m_ReflectanceToSurfaceReflectanceFilter->SetIsSetAtmosphericRadiativeTerms(false);\n m_ReflectanceToSurfaceReflectanceFilter->SetUseGenerateParameters(true);\n m_ReflectanceToSurfaceReflectanceFilter->UpdateOutputInformation();\n m_ReflectanceToSurfaceReflectanceFilter->SetUseGenerateParameters(false);\n\n m_AtmosphericParam = m_ReflectanceToSurfaceReflectanceFilter->GetCorrectionParameters();\n \/\/AerosolModelType aeroMod = AtmosphericCorrectionParametersType::NO_AEROSOL;\n\n switch ( GetParameterInt(\"atmo.aerosol\") )\n {\n case Aerosol_Desertic:\n {\n \/\/ Aerosol_Desertic correspond to 4 in the enum but actually in\n \/\/ the class atmosphericParam it is known as parameter 5\n m_AtmosphericParam->SetAerosolModel(static_cast<AerosolModelType>(5));\n }\n break;\n default:\n {\n m_AtmosphericParam->SetAerosolModel(static_cast<AerosolModelType>(GetParameterInt(\"atmo.aerosol\")));\n }\n break;\n }\n \/\/ Set the atmospheric param\n m_AtmosphericParam->SetOzoneAmount(GetParameterFloat(\"atmo.oz\"));\n m_AtmosphericParam->SetWaterVaporAmount(GetParameterFloat(\"atmo.wa\"));\n m_AtmosphericParam->SetAtmosphericPressure(GetParameterFloat(\"atmo.pressure\"));\n m_AtmosphericParam->SetAerosolOptical(GetParameterFloat(\"atmo.opt\"));\n\n \/\/ Relative Spectral Response File\n if (IsParameterEnabled(\"rsr\"))\n {\n m_ReflectanceToSurfaceReflectanceFilter->SetFilterFunctionValuesFileName(GetParameterString(\"rsr\"));\n }\n else\n {\n m_ReflectanceToSurfaceReflectanceFilter->SetFilterFunctionCoef(lImageMetadataInterface->GetSpectralSensitivity());\n }\n\n \/\/ Aeronet file\n if (IsParameterEnabled(\"atmo.aeronet\"))\n {\n m_ReflectanceToSurfaceReflectanceFilter->SetAeronetFileName(GetParameterString(\"atmo.aeronet\"));\n }\n\n m_ReflectanceToSurfaceReflectanceFilter->SetIsSetAtmosphericRadiativeTerms(false);\n m_ReflectanceToSurfaceReflectanceFilter->SetUseGenerateParameters(true);\n m_ReflectanceToSurfaceReflectanceFilter->GenerateParameters();\n m_ReflectanceToSurfaceReflectanceFilter->UpdateOutputInformation();\n m_ReflectanceToSurfaceReflectanceFilter->SetUseGenerateParameters(false);\n\n std::ostringstream oss;\n oss.str(\"\");\n oss << m_AtmosphericParam;\n\n AtmosphericRadiativeTerms::Pointer atmoTerms = m_ReflectanceToSurfaceReflectanceFilter->GetAtmosphericRadiativeTerms();\n oss << std::endl << std::endl << atmoTerms;\n\n \/\/GetLogger()->Info(\"Atmospheric correction parameters : \" + oss.str());\n\n \/\/Compute adjacency effect\n \/\/ m_SurfaceAdjacencyEffect6SCorrectionSchemeFilter\n \/\/ = SurfaceAdjacencyEffect6SCorrectionSchemeFilterType::New();\n\n \/\/ m_SurfaceAdjacencyEffect6SCorrectionSchemeFilter->SetInput(m_ReflectanceToSurfaceReflectanceFilter->GetOutput());\n \/\/ m_SurfaceAdjacencyEffect6SCorrectionSchemeFilter->\n \/\/ SetAtmosphericRadiativeTerms(\n \/\/ m_ReflectanceToSurfaceReflectanceFilter->GetAtmosphericRadiativeTerms());\n \/\/ m_SurfaceAdjacencyEffect6SCorrectionSchemeFilter->SetZenithalViewingAngle(\n \/\/ m_AtmosphericParam->GetViewingZenithalAngle());\n \/\/ m_SurfaceAdjacencyEffect6SCorrectionSchemeFilter->SetWindowRadius(GetParameterInt(\"radius\"));\n\n \/\/ \/\/estimate ground spacing in kilometers\n \/\/ GroundSpacingImageType::Pointer groundSpacing = GroundSpacingImageType::New();\n\n \/\/ groundSpacing->SetInputImage(inImage);\n \/\/ IndexType index;\n\n \/\/ vnl_random rand;\n\n \/\/ index[0] = static_cast<IndexValueType>(rand.lrand32(0, inImage->GetLargestPossibleRegion().GetSize()[0]));\n \/\/ index[1] = static_cast<IndexValueType>(rand.lrand32(0, inImage->GetLargestPossibleRegion().GetSize()[1]));\n \/\/ FloatType tmpSpacing = groundSpacing->EvaluateAtIndex(index);\n\n \/\/ const float spacingInKilometers = (std::max(tmpSpacing[0], tmpSpacing[1])) \/ 1000.;\n\n \/\/ \/\/ std::ostringstream oss2;\n \/\/ \/\/ oss2.str(\"\");\n \/\/ \/\/ oss2 << spacingInKilometers;\n\n \/\/ \/\/ GetLogger()->Info(\"Spacing in kilometers \" + oss2.str());\n \/\/ m_SurfaceAdjacencyEffect6SCorrectionSchemeFilter->\n \/\/ SetPixelSpacingInKilometers(spacingInKilometers);\n\n \/\/ \/\/rescale the surface reflectance in milli-reflectance\n \/\/ m_SurfaceAdjacencyEffect6SCorrectionSchemeFilter->UpdateOutputInformation();\n \/\/ \/\/m_SurfaceAdjacencyEffect6SCorrectionSchemeFilter->Update();\n \/\/ m_ScaleFilter->SetInput(m_SurfaceAdjacencyEffect6SCorrectionSchemeFilter->GetOutput());\n if (!IsParameterEnabled(\"clamp\"))\n {\n m_ScaleFilter->SetInput(m_ReflectanceToSurfaceReflectanceFilter->GetOutput());\n }\n else\n {\n m_ClampFilter->SetInput(m_ReflectanceToSurfaceReflectanceFilter->GetOutput());\n m_ClampFilter->ClampOutside(0.0, 1.0);\n m_ScaleFilter->SetInput(m_ClampFilter->GetOutput());\n }\n }\n break;\n }\n\n \/\/ Output Image\n const double scale = IsParameterEnabled(\"milli\") ? 1000.0 : 1.0;\n m_ScaleFilter->SetCoef(scale);\n\n SetParameterOutputImage(\"out\", m_ScaleFilter->GetOutput());\n }\n\n ImageToLuminanceImageFilterType ::Pointer m_ImageToLuminanceFilter;\n LuminanceToReflectanceImageFilterType::Pointer m_LuminanceToReflectanceFilter;\n ReflectanceToSurfaceReflectanceImageFilterType::Pointer m_ReflectanceToSurfaceReflectanceFilter;\n ScaleFilterType::Pointer m_ScaleFilter;\n AtmosphericCorrectionParametersType::Pointer m_AtmosphericParam;\n ClampFilterType::Pointer m_ClampFilter;\n\n SurfaceAdjacencyEffect6SCorrectionSchemeFilterType::Pointer m_SurfaceAdjacencyEffect6SCorrectionSchemeFilter;\n};\n\n}\/\/ namespace Wrapper\n} \/\/ namespace otb\n\nOTB_APPLICATION_EXPORT(otb::Wrapper::OpticalCalibration)\n<commit_msg>ENH: spectral sentivity values are read by ReflectanceToSurfaceReflectanceFilter<commit_after>\/*=========================================================================\n\n Program: ORFEO Toolbox\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n\n Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.\n See OTBCopyright.txt for details.\n\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notices for more information.\n\n =========================================================================*\/\n#include \"otbWrapperApplication.h\"\n#include \"otbWrapperApplicationFactory.h\"\n\n#include \"otbImageToLuminanceImageFilter.h\"\n#include \"otbLuminanceToReflectanceImageFilter.h\"\n#include \"otbReflectanceToSurfaceReflectanceImageFilter.h\"\n#include \"otbMultiplyByScalarImageFilter.h\"\n#include \"otbClampVectorImageFilter.h\"\n#include \"otbSurfaceAdjacencyEffect6SCorrectionSchemeFilter.h\"\n#include \"otbGroundSpacingImageFunction.h\"\n#include \"vnl\/vnl_random.h\"\n\nnamespace otb\n{\n\nenum\n{\n Level_TOA,\n Level_TOC\n};\n\nenum\n{\n Aerosol_NoAerosol,\n Aerosol_Continental,\n Aerosol_Maritime,\n Aerosol_Urban,\n Aerosol_Desertic,\n};\n\nnamespace Wrapper\n{\n\nclass OpticalCalibration : public Application\n{\n\npublic:\n \/** Standard class typedefs. *\/\n typedef OpticalCalibration Self;\n typedef Application Superclass;\n typedef itk::SmartPointer<Self> Pointer;\n typedef itk::SmartPointer<const Self> ConstPointer;\n\n \/** Standard macro *\/\n itkNewMacro(Self);\n\n itkTypeMacro(OpticalCalibration, Application);\n\n typedef ImageToLuminanceImageFilter<UInt16VectorImageType,\n DoubleVectorImageType> ImageToLuminanceImageFilterType;\n\n typedef LuminanceToReflectanceImageFilter<DoubleVectorImageType,\n DoubleVectorImageType> LuminanceToReflectanceImageFilterType;\n\n typedef otb::MultiplyByScalarImageFilter<DoubleVectorImageType,\n DoubleVectorImageType> ScaleFilterType;\n\n typedef otb::ClampVectorImageFilter<DoubleVectorImageType,\n DoubleVectorImageType> ClampFilterType;\n\n typedef ReflectanceToSurfaceReflectanceImageFilter<DoubleVectorImageType,\n DoubleVectorImageType> ReflectanceToSurfaceReflectanceImageFilterType;\n typedef ReflectanceToSurfaceReflectanceImageFilterType::FilterFunctionValuesType FilterFunctionValuesType;\n typedef FilterFunctionValuesType::ValuesVectorType ValuesVectorType;\n typedef AtmosphericCorrectionParameters AtmosphericCorrectionParametersType;\n typedef AtmosphericCorrectionParametersType::AerosolModelType AerosolModelType;\n\n typedef otb::SurfaceAdjacencyEffect6SCorrectionSchemeFilter<DoubleVectorImageType,DoubleVectorImageType>\n SurfaceAdjacencyEffect6SCorrectionSchemeFilterType;\n\n typedef otb::GroundSpacingImageFunction<UInt16VectorImageType> GroundSpacingImageType;\n\n typedef UInt16VectorImageType::IndexType IndexType;\n typedef GroundSpacingImageType::FloatType FloatType;\n typedef GroundSpacingImageType::ValueType ValueType;\n\n typedef IndexType::IndexValueType IndexValueType;\n\n\nprivate:\n void DoInit()\n {\n SetName(\"OpticalCalibration\");\n SetDescription(\"Perform optical calibration TOA\/TOC (Top Of Atmosphere\/Top Of Canopy). Supported sensors: QuickBird, Ikonos, WorldView2, Formosat, Spot5, Pleiades\");\n \/\/ Documentation\n SetDocName(\"Optical calibration\");\n SetDocLongDescription(\"The application allows to convert pixel values from DN (for Digital Numbers) to physically interpretable and comparable values. Calibrated values are called surface reflectivity and its values lie in the range [0, 1].\\nThe first level is called Top Of Atmosphere (TOA) reflectivity. It takes into account the sensor gain, sensor spectral response and the solar illumination.\\nThe second level is called Top Of Canopy (TOC) reflectivity. In addition to sensor gain and solar illumination, it takes into account the optical thickness of the atmosphere, the atmospheric pressure, the water vapor amount, the ozone amount, as well as the composition and amount of aerosol gasses.\\nIt is also possible to indicate an AERONET file which contains atmospheric parameters (version 1 and version 2 of Aeronet file are supported.\");\n SetDocLimitations(\"None\");\n SetDocAuthors(\"OTB-Team\");\n SetDocSeeAlso(\"The OTB CookBook\");\n\n AddDocTag(Tags::Calibration);\n\n AddParameter(ParameterType_InputImage, \"in\", \"Input\");\n SetParameterDescription(\"in\", \"Input image filename (values in DN)\");\n\n AddParameter(ParameterType_OutputImage, \"out\", \"Output\");\n SetParameterDescription(\"out\",\"Output calibrated image filename\");\n\n AddRAMParameter();\n\n AddParameter(ParameterType_Choice, \"level\", \"Calibration Level\");\n AddChoice(\"level.toa\", \"TOA : Top Of Atmosphere\");\n AddChoice(\"level.toc\", \"TOC : Top Of Canopy (EXPERIMENTAL)\");\n SetParameterString(\"level\", \"toa\");\n\n AddParameter(ParameterType_Empty, \"milli\", \"Convert to milli reflectance\");\n SetParameterDescription(\"milli\", \"Flag to use milli-reflectance instead of reflectance.\\n\"\n \"This allows to save the image with integer pixel type (in the range [0, 1000] instead of floating point in the range [0, 1]. In order to do that, use this option and set the output pixel type (-out filename uint16 for example)\");\n DisableParameter(\"milli\");\n MandatoryOff(\"milli\");\n\n AddParameter(ParameterType_Empty, \"clamp\", \"Clamp of reflectivity values between [0% , 100%]\");\n SetParameterDescription(\"clamp\", \"Clamping in the range [0% , 100%]. It can be usefull to preserve area with specular reflectance.\");\n EnableParameter(\"clamp\");\n MandatoryOff(\"clamp\");\n\n AddParameter(ParameterType_InputFilename, \"rsr\", \"Relative Spectral Response File\");\n std::ostringstream oss;\n oss << \"Sensor relative spectral response file\"<<std::endl;\n oss << \"By default the application gets these informations in the metadata\";\n SetParameterDescription(\"rsr\", oss.str());\n MandatoryOff(\"rsr\");\n\n AddParameter(ParameterType_Group,\"atmo\",\"Atmospheric parameters\");\n SetParameterDescription(\"atmo\",\"This group allows to set the atmospheric parameters.\");\n AddParameter(ParameterType_Choice, \"atmo.aerosol\", \"Aerosol Model\");\n AddChoice(\"atmo.aerosol.noaersol\", \"No Aerosol Model\");\n AddChoice(\"atmo.aerosol.continental\", \"Continental\");\n AddChoice(\"atmo.aerosol.maritime\", \"Maritime\");\n AddChoice(\"atmo.aerosol.urban\", \"Urban\");\n AddChoice(\"atmo.aerosol.desertic\", \"Desertic\");\n\n AddParameter(ParameterType_Float, \"atmo.oz\", \"Ozone Amount\");\n SetParameterDescription(\"atmo.oz\", \"Ozone Amount\");\n\n AddParameter(ParameterType_Float, \"atmo.wa\", \"Water Vapor Amount\");\n SetParameterDescription(\"atmo.wa\", \"Water Vapor Amount (in saturation fraction of water)\");\n\n AddParameter(ParameterType_Float, \"atmo.pressure\", \"Atmospheric Pressure\");\n SetParameterDescription(\"atmo.pressure\", \"Atmospheric Pressure (in hPa)\");\n\n AddParameter(ParameterType_Float, \"atmo.opt\", \"Aerosol Optical Thickness\");\n SetParameterDescription(\"atmo.opt\", \"Aerosol Optical Thickness\");\n\n SetDefaultParameterFloat(\"atmo.oz\", 0.);\n SetDefaultParameterFloat(\"atmo.wa\", 2.5);\n SetDefaultParameterFloat(\"atmo.pressure\", 1030.);\n\n SetDefaultParameterFloat(\"atmo.opt\", 0.2);\n MandatoryOff(\"atmo.oz\");\n MandatoryOff(\"atmo.wa\");\n MandatoryOff(\"atmo.pressure\");\n MandatoryOff(\"atmo.opt\");\n\n AddParameter(ParameterType_InputFilename, \"atmo.aeronet\", \"Aeronet File\");\n SetParameterDescription(\"atmo.aeronet\",\"Aeronet file containing atmospheric parameters\");\n MandatoryOff(\"atmo.aeronet\");\n\n \/\/ Window radius for adjacency effects correction\n AddParameter(ParameterType_Int, \"radius\", \"Window radius\");\n SetParameterDescription(\"radius\",\"Window radius for adjacency effects corrections\");\n MandatoryOff(\"radius\");\n SetDefaultParameterInt(\"radius\", 2);\n\n \/\/ Doc example parameter settings\n SetDocExampleParameterValue(\"in\", \"QB_1_ortho.tif\");\n SetDocExampleParameterValue(\"level\", \"toa\");\n SetDocExampleParameterValue(\"out\", \"OpticalCalibration.tif\");\n }\n\n void DoUpdateParameters()\n {\n \/\/ Nothing to update\n }\n\n void DoExecute()\n {\n UInt16VectorImageType::Pointer inImage = GetParameterUInt16VectorImage(\"in\");\n\n \/\/Check if valid metadata informations are available to compute ImageToLuminance and LuminanceToReflectance\n itk::MetaDataDictionary dict = inImage->GetMetaDataDictionary();\n OpticalImageMetadataInterface::Pointer lImageMetadataInterface = OpticalImageMetadataInterfaceFactory::CreateIMI(dict);\n\n \/\/ Test if needed data are available : an exception will be thrown\n \/\/ if one the following Get* return failure. the exception is then\n \/\/ caught in the Wrapper::Application class which redirect it to\n \/\/ the logger\n \/\/ ImageToLuminance\n lImageMetadataInterface->GetPhysicalGain();\n lImageMetadataInterface->GetPhysicalBias();\n\n \/\/ LuminanceToReflectance\n lImageMetadataInterface->GetDay();\n lImageMetadataInterface->GetMonth();\n\n lImageMetadataInterface->GetSolarIrradiance();\n lImageMetadataInterface->GetSunElevation();\n\n m_ImageToLuminanceFilter = ImageToLuminanceImageFilterType::New();\n m_LuminanceToReflectanceFilter = LuminanceToReflectanceImageFilterType::New();\n m_ReflectanceToSurfaceReflectanceFilter = ReflectanceToSurfaceReflectanceImageFilterType::New();\n\n m_ImageToLuminanceFilter->SetInput(inImage);\n m_LuminanceToReflectanceFilter->SetInput(m_ImageToLuminanceFilter->GetOutput());\n m_ReflectanceToSurfaceReflectanceFilter->SetInput(m_LuminanceToReflectanceFilter->GetOutput());\n\n m_ScaleFilter = ScaleFilterType::New();\n m_ScaleFilter->InPlaceOn();\n\n m_ClampFilter = ClampFilterType::New();\n\n switch ( GetParameterInt(\"level\") )\n {\n case Level_TOA:\n {\n m_LuminanceToReflectanceFilter->SetUseClamp(IsParameterEnabled(\"clamp\"));\n\n m_LuminanceToReflectanceFilter->UpdateOutputInformation();\n m_ScaleFilter->SetInput(m_LuminanceToReflectanceFilter->GetOutput());\n }\n break;\n case Level_TOC:\n {\n m_ReflectanceToSurfaceReflectanceFilter->SetIsSetAtmosphericRadiativeTerms(false);\n m_ReflectanceToSurfaceReflectanceFilter->SetUseGenerateParameters(true);\n m_ReflectanceToSurfaceReflectanceFilter->UpdateOutputInformation();\n m_ReflectanceToSurfaceReflectanceFilter->SetUseGenerateParameters(false);\n\n m_AtmosphericParam = m_ReflectanceToSurfaceReflectanceFilter->GetCorrectionParameters();\n \/\/AerosolModelType aeroMod = AtmosphericCorrectionParametersType::NO_AEROSOL;\n\n switch ( GetParameterInt(\"atmo.aerosol\") )\n {\n case Aerosol_Desertic:\n {\n \/\/ Aerosol_Desertic correspond to 4 in the enum but actually in\n \/\/ the class atmosphericParam it is known as parameter 5\n m_AtmosphericParam->SetAerosolModel(static_cast<AerosolModelType>(5));\n }\n break;\n default:\n {\n m_AtmosphericParam->SetAerosolModel(static_cast<AerosolModelType>(GetParameterInt(\"atmo.aerosol\")));\n }\n break;\n }\n \/\/ Set the atmospheric param\n m_AtmosphericParam->SetOzoneAmount(GetParameterFloat(\"atmo.oz\"));\n m_AtmosphericParam->SetWaterVaporAmount(GetParameterFloat(\"atmo.wa\"));\n m_AtmosphericParam->SetAtmosphericPressure(GetParameterFloat(\"atmo.pressure\"));\n m_AtmosphericParam->SetAerosolOptical(GetParameterFloat(\"atmo.opt\"));\n\n \/\/ Relative Spectral Response File\n if (IsParameterEnabled(\"rsr\"))\n {\n m_ReflectanceToSurfaceReflectanceFilter->SetFilterFunctionValuesFileName(GetParameterString(\"rsr\"));\n }\n\n \/\/ Aeronet file\n if (IsParameterEnabled(\"atmo.aeronet\"))\n {\n m_ReflectanceToSurfaceReflectanceFilter->SetAeronetFileName(GetParameterString(\"atmo.aeronet\"));\n }\n\n m_ReflectanceToSurfaceReflectanceFilter->SetIsSetAtmosphericRadiativeTerms(false);\n m_ReflectanceToSurfaceReflectanceFilter->SetUseGenerateParameters(true);\n m_ReflectanceToSurfaceReflectanceFilter->GenerateParameters();\n m_ReflectanceToSurfaceReflectanceFilter->UpdateOutputInformation();\n m_ReflectanceToSurfaceReflectanceFilter->SetUseGenerateParameters(false);\n\n std::ostringstream oss;\n oss.str(\"\");\n oss << m_AtmosphericParam;\n\n AtmosphericRadiativeTerms::Pointer atmoTerms = m_ReflectanceToSurfaceReflectanceFilter->GetAtmosphericRadiativeTerms();\n oss << std::endl << std::endl << atmoTerms;\n\n GetLogger()->Debug(\"Atmospheric correction parameters : \" + oss.str());\n\n \/\/Compute adjacency effect\n \/\/ m_SurfaceAdjacencyEffect6SCorrectionSchemeFilter\n \/\/ = SurfaceAdjacencyEffect6SCorrectionSchemeFilterType::New();\n\n \/\/ m_SurfaceAdjacencyEffect6SCorrectionSchemeFilter->SetInput(m_ReflectanceToSurfaceReflectanceFilter->GetOutput());\n \/\/ m_SurfaceAdjacencyEffect6SCorrectionSchemeFilter->\n \/\/ SetAtmosphericRadiativeTerms(\n \/\/ m_ReflectanceToSurfaceReflectanceFilter->GetAtmosphericRadiativeTerms());\n \/\/ m_SurfaceAdjacencyEffect6SCorrectionSchemeFilter->SetZenithalViewingAngle(\n \/\/ m_AtmosphericParam->GetViewingZenithalAngle());\n \/\/ m_SurfaceAdjacencyEffect6SCorrectionSchemeFilter->SetWindowRadius(GetParameterInt(\"radius\"));\n\n \/\/ \/\/estimate ground spacing in kilometers\n \/\/ GroundSpacingImageType::Pointer groundSpacing = GroundSpacingImageType::New();\n\n \/\/ groundSpacing->SetInputImage(inImage);\n \/\/ IndexType index;\n\n \/\/ vnl_random rand;\n\n \/\/ index[0] = static_cast<IndexValueType>(rand.lrand32(0, inImage->GetLargestPossibleRegion().GetSize()[0]));\n \/\/ index[1] = static_cast<IndexValueType>(rand.lrand32(0, inImage->GetLargestPossibleRegion().GetSize()[1]));\n \/\/ FloatType tmpSpacing = groundSpacing->EvaluateAtIndex(index);\n\n \/\/ const float spacingInKilometers = (std::max(tmpSpacing[0], tmpSpacing[1])) \/ 1000.;\n\n \/\/ \/\/ std::ostringstream oss2;\n \/\/ \/\/ oss2.str(\"\");\n \/\/ \/\/ oss2 << spacingInKilometers;\n\n \/\/ \/\/ GetLogger()->Info(\"Spacing in kilometers \" + oss2.str());\n \/\/ m_SurfaceAdjacencyEffect6SCorrectionSchemeFilter->\n \/\/ SetPixelSpacingInKilometers(spacingInKilometers);\n\n \/\/ \/\/rescale the surface reflectance in milli-reflectance\n \/\/ m_SurfaceAdjacencyEffect6SCorrectionSchemeFilter->UpdateOutputInformation();\n \/\/ \/\/m_SurfaceAdjacencyEffect6SCorrectionSchemeFilter->Update();\n \/\/ m_ScaleFilter->SetInput(m_SurfaceAdjacencyEffect6SCorrectionSchemeFilter->GetOutput());\n if (!IsParameterEnabled(\"clamp\"))\n {\n m_ScaleFilter->SetInput(m_ReflectanceToSurfaceReflectanceFilter->GetOutput());\n }\n else\n {\n m_ClampFilter->SetInput(m_ReflectanceToSurfaceReflectanceFilter->GetOutput());\n m_ClampFilter->ClampOutside(0.0, 1.0);\n m_ScaleFilter->SetInput(m_ClampFilter->GetOutput());\n }\n }\n break;\n }\n\n \/\/ Output Image\n const double scale = IsParameterEnabled(\"milli\") ? 1000.0 : 1.0;\n m_ScaleFilter->SetCoef(scale);\n\n SetParameterOutputImage(\"out\", m_ScaleFilter->GetOutput());\n }\n\n ImageToLuminanceImageFilterType ::Pointer m_ImageToLuminanceFilter;\n LuminanceToReflectanceImageFilterType::Pointer m_LuminanceToReflectanceFilter;\n ReflectanceToSurfaceReflectanceImageFilterType::Pointer m_ReflectanceToSurfaceReflectanceFilter;\n ScaleFilterType::Pointer m_ScaleFilter;\n AtmosphericCorrectionParametersType::Pointer m_AtmosphericParam;\n ClampFilterType::Pointer m_ClampFilter;\n\n SurfaceAdjacencyEffect6SCorrectionSchemeFilterType::Pointer m_SurfaceAdjacencyEffect6SCorrectionSchemeFilter;\n};\n\n}\/\/ namespace Wrapper\n} \/\/ namespace otb\n\nOTB_APPLICATION_EXPORT(otb::Wrapper::OpticalCalibration)\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: transliteration_OneToOne.hxx,v $\n *\n * $Revision: 1.6 $\n *\n * last change: $Author: obo $ $Date: 2006-01-19 18:01:56 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n#ifndef _I18N_TRANSLITERATION_TRANSLITERATION_ONETOONE_H_\n#define _I18N_TRANSLITERATION_TRANSLITERATION_ONETOONE_H_\n\n#include <transliteration_commonclass.hxx>\n#include <i18nutil\/oneToOneMapping.hxx>\n\nnamespace com { namespace sun { namespace star { namespace i18n {\n\ntypedef sal_Unicode (*TransFunc)(const sal_Unicode);\n\nclass transliteration_OneToOne : public transliteration_commonclass\n{\npublic:\n rtl::OUString SAL_CALL\n transliterate( const rtl::OUString& inStr, sal_Int32 startPos, sal_Int32 nCount, com::sun::star::uno::Sequence< sal_Int32 >& offset )\n throw(com::sun::star::uno::RuntimeException);\n\n sal_Unicode SAL_CALL\n transliterateChar2Char( sal_Unicode inChar)\n throw(com::sun::star::uno::RuntimeException,\n com::sun::star::i18n::MultipleCharsOutputException);\n\n \/\/ Methods which are shared.\n sal_Int16 SAL_CALL getType() throw(com::sun::star::uno::RuntimeException);\n\n rtl::OUString SAL_CALL\n folding( const rtl::OUString& inStr, sal_Int32 startPos, sal_Int32 nCount, com::sun::star::uno::Sequence< sal_Int32 >& offset)\n throw(com::sun::star::uno::RuntimeException);\n\n sal_Bool SAL_CALL\n equals( const rtl::OUString& str1, sal_Int32 pos1, sal_Int32 nCount1, sal_Int32& nMatch1,\n const rtl::OUString& str2, sal_Int32 pos2, sal_Int32 nCount2, sal_Int32& nMatch2 )\n throw(com::sun::star::uno::RuntimeException);\n\n com::sun::star::uno::Sequence< rtl::OUString > SAL_CALL\n transliterateRange( const rtl::OUString& str1, const rtl::OUString& str2 )\n throw(com::sun::star::uno::RuntimeException);\n\nprotected:\n TransFunc func;\n oneToOneMapping *table;\n};\n\n#define TRANSLITERATION_ONETOONE( name ) \\\nclass name : public transliteration_OneToOne \\\n{ \\\npublic: \\\n name (); \\\n rtl::OUString SAL_CALL \\\n transliterate( const rtl::OUString& inStr, sal_Int32 startPos, sal_Int32 nCount, com::sun::star::uno::Sequence< sal_Int32 >& offset ) \\\n throw(com::sun::star::uno::RuntimeException); \\\n sal_Unicode SAL_CALL \\\n transliterateChar2Char( sal_Unicode inChar) \\\n throw(com::sun::star::uno::RuntimeException, \\\n com::sun::star::i18n::MultipleCharsOutputException); \\\n};\n\n#if defined( TRANSLITERATION_fullwidthToHalfwidth ) || defined( TRANSLITERATION_ALL )\nTRANSLITERATION_ONETOONE( fullwidthToHalfwidth )\n#endif\n#if defined( TRANSLITERATION_halfwidthToFullwidth ) || defined( TRANSLITERATION_ALL )\nTRANSLITERATION_ONETOONE(halfwidthToFullwidth)\n#endif\n#undef TRANSLITERATION_ONETOONE\n\n#define TRANSLITERATION_ONETOONE( name ) \\\nclass name : public transliteration_OneToOne \\\n{ \\\npublic: \\\n name (); \\\n};\n\n#if defined( TRANSLITERATION_hiraganaToKatakana ) || defined( TRANSLITERATION_ALL )\nTRANSLITERATION_ONETOONE(hiraganaToKatakana)\n#endif\n#if defined( TRANSLITERATION_katakanaToHiragana ) || defined( TRANSLITERATION_ALL )\nTRANSLITERATION_ONETOONE(katakanaToHiragana)\n#endif\n#if defined( TRANSLITERATION_largeToSmall_ja_JP ) || defined( TRANSLITERATION_ALL )\nTRANSLITERATION_ONETOONE(largeToSmall_ja_JP)\n#endif\n#if defined( TRANSLITERATION_smallToLarge_ja_JP ) || defined( TRANSLITERATION_ALL )\nTRANSLITERATION_ONETOONE(smallToLarge_ja_JP)\n#endif\n#undef TRANSLITERATION_ONETOONE\n\n} } } }\n\n#endif \/\/ _I18N_TRANSLITERATION_TRANSLITERATION_ONETOONE_H_\n<commit_msg>INTEGRATION: CWS i18n39 (1.6.152); FILE MERGED 2007\/12\/12 22:44:02 khong 1.6.152.1: #i81366# add new Japanese transliterations<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: transliteration_OneToOne.hxx,v $\n *\n * $Revision: 1.7 $\n *\n * last change: $Author: vg $ $Date: 2008-01-28 15:33:31 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n#ifndef _I18N_TRANSLITERATION_TRANSLITERATION_ONETOONE_H_\n#define _I18N_TRANSLITERATION_TRANSLITERATION_ONETOONE_H_\n\n#include <transliteration_commonclass.hxx>\n#include <i18nutil\/oneToOneMapping.hxx>\n\nnamespace com { namespace sun { namespace star { namespace i18n {\n\ntypedef sal_Unicode (*TransFunc)(const sal_Unicode);\n\nclass transliteration_OneToOne : public transliteration_commonclass\n{\npublic:\n rtl::OUString SAL_CALL\n transliterate( const rtl::OUString& inStr, sal_Int32 startPos, sal_Int32 nCount, com::sun::star::uno::Sequence< sal_Int32 >& offset )\n throw(com::sun::star::uno::RuntimeException);\n\n sal_Unicode SAL_CALL\n transliterateChar2Char( sal_Unicode inChar)\n throw(com::sun::star::uno::RuntimeException,\n com::sun::star::i18n::MultipleCharsOutputException);\n\n \/\/ Methods which are shared.\n sal_Int16 SAL_CALL getType() throw(com::sun::star::uno::RuntimeException);\n\n rtl::OUString SAL_CALL\n folding( const rtl::OUString& inStr, sal_Int32 startPos, sal_Int32 nCount, com::sun::star::uno::Sequence< sal_Int32 >& offset)\n throw(com::sun::star::uno::RuntimeException);\n\n sal_Bool SAL_CALL\n equals( const rtl::OUString& str1, sal_Int32 pos1, sal_Int32 nCount1, sal_Int32& nMatch1,\n const rtl::OUString& str2, sal_Int32 pos2, sal_Int32 nCount2, sal_Int32& nMatch2 )\n throw(com::sun::star::uno::RuntimeException);\n\n com::sun::star::uno::Sequence< rtl::OUString > SAL_CALL\n transliterateRange( const rtl::OUString& str1, const rtl::OUString& str2 )\n throw(com::sun::star::uno::RuntimeException);\n\nprotected:\n TransFunc func;\n oneToOneMapping *table;\n};\n\n#define TRANSLITERATION_ONETOONE( name ) \\\nclass name : public transliteration_OneToOne \\\n{ \\\npublic: \\\n name (); \\\n rtl::OUString SAL_CALL \\\n transliterate( const rtl::OUString& inStr, sal_Int32 startPos, sal_Int32 nCount, com::sun::star::uno::Sequence< sal_Int32 >& offset ) \\\n throw(com::sun::star::uno::RuntimeException); \\\n sal_Unicode SAL_CALL \\\n transliterateChar2Char( sal_Unicode inChar) \\\n throw(com::sun::star::uno::RuntimeException, \\\n com::sun::star::i18n::MultipleCharsOutputException); \\\n};\n\n#if defined( TRANSLITERATION_fullwidthToHalfwidth ) || defined( TRANSLITERATION_ALL )\nTRANSLITERATION_ONETOONE( fullwidthToHalfwidth )\n#endif\n#if defined( TRANSLITERATION_halfwidthToFullwidth ) || defined( TRANSLITERATION_ALL )\nTRANSLITERATION_ONETOONE(halfwidthToFullwidth)\n#endif\n#if defined( TRANSLITERATION_fullwidthKatakanaToHalfwidthKatakana ) || defined( TRANSLITERATION_ALL )\nTRANSLITERATION_ONETOONE( fullwidthKatakanaToHalfwidthKatakana )\n#endif\n#if defined( TRANSLITERATION_halfwidthKatakanaToFullwidthKatakana ) || defined( TRANSLITERATION_ALL )\nTRANSLITERATION_ONETOONE(halfwidthKatakanaToFullwidthKatakana)\n#endif\n#if defined( TRANSLITERATION_fullwidthToHalfwidthLikeASC ) || defined( TRANSLITERATION_ALL )\nTRANSLITERATION_ONETOONE( fullwidthToHalfwidthLikeASC )\n#endif\n#if defined( TRANSLITERATION_halfwidthToFullwidthLikeJIS ) || defined( TRANSLITERATION_ALL )\nTRANSLITERATION_ONETOONE( halfwidthToFullwidthLikeJIS )\n#endif\n#undef TRANSLITERATION_ONETOONE\n\n#define TRANSLITERATION_ONETOONE( name ) \\\nclass name : public transliteration_OneToOne \\\n{ \\\npublic: \\\n name (); \\\n};\n\n#if defined( TRANSLITERATION_hiraganaToKatakana ) || defined( TRANSLITERATION_ALL )\nTRANSLITERATION_ONETOONE(hiraganaToKatakana)\n#endif\n#if defined( TRANSLITERATION_katakanaToHiragana ) || defined( TRANSLITERATION_ALL )\nTRANSLITERATION_ONETOONE(katakanaToHiragana)\n#endif\n#if defined( TRANSLITERATION_largeToSmall_ja_JP ) || defined( TRANSLITERATION_ALL )\nTRANSLITERATION_ONETOONE(largeToSmall_ja_JP)\n#endif\n#if defined( TRANSLITERATION_smallToLarge_ja_JP ) || defined( TRANSLITERATION_ALL )\nTRANSLITERATION_ONETOONE(smallToLarge_ja_JP)\n#endif\n#undef TRANSLITERATION_ONETOONE\n\n} } } }\n\n#endif \/\/ _I18N_TRANSLITERATION_TRANSLITERATION_ONETOONE_H_\n<|endoftext|>"} {"text":"<commit_before>\/\/===- lib\/ReaderWriter\/ELF\/AMDGPU\/AMDGPURelocationHandler.cpp -----------===\/\/\n\/\/\n\/\/ The LLVM Linker\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"AMDGPURelocationHandler.h\"\n\nusing namespace lld::elf;\n\nstd::error_code AMDGPUTargetRelocationHandler::applyRelocation(\n ELFWriter &writer, llvm::FileOutputBuffer &buf, const AtomLayout &atom,\n const Reference &ref) const {\n return std::error_code();\n}\n<commit_msg>ELF\/AMDGPU: Add missing: using namespace lld; to try to fix windows bot<commit_after>\/\/===- lib\/ReaderWriter\/ELF\/AMDGPU\/AMDGPURelocationHandler.cpp -----------===\/\/\n\/\/\n\/\/ The LLVM Linker\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"AMDGPURelocationHandler.h\"\n\nusing namespace lld;\nusing namespace lld::elf;\n\nstd::error_code AMDGPUTargetRelocationHandler::applyRelocation(\n ELFWriter &writer, llvm::FileOutputBuffer &buf, const AtomLayout &atom,\n const Reference &ref) const {\n return std::error_code();\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Software License Agreement (BSD License)\n *\n * Point Cloud Library (PCL) - www.pointclouds.org\n * Copyright (c) 2010-2011, Willow Garage, Inc.\n *\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following\n * disclaimer in the documentation and\/or other materials provided\n * with the distribution.\n * * Neither the name of Willow Garage, Inc. nor the names of its\n * contributors may be used to endorse or promote products derived\n * from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n *\/\n\n#ifndef PCL_SIFT_KEYPOINT_IMPL_H_\n#define PCL_SIFT_KEYPOINT_IMPL_H_\n\n#include <pcl\/keypoints\/sift_keypoint.h>\n#include <pcl\/common\/io.h>\n#include <pcl\/filters\/voxel_grid.h>\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate <typename PointInT, typename PointOutT> void \npcl::SIFTKeypoint<PointInT, PointOutT>::setScales (float min_scale, int nr_octaves, int nr_scales_per_octave)\n{\n min_scale_ = min_scale;\n nr_octaves_ = nr_octaves;\n nr_scales_per_octave_ = nr_scales_per_octave;\n}\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate <typename PointInT, typename PointOutT> void \npcl::SIFTKeypoint<PointInT, PointOutT>::setMinimumContrast (float min_contrast)\n{\n min_contrast_ = min_contrast;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate <typename PointInT, typename PointOutT> bool\npcl::SIFTKeypoint<PointInT, PointOutT>::initCompute ()\n{\n if (min_scale_ <= 0)\n {\n PCL_ERROR (\"[pcl::%s::initCompute] : Minimum scale (%f) must be strict positive!\\n\", \n name_.c_str (), min_scale_);\n return (false);\n }\n if (nr_octaves_ < 1)\n {\n PCL_ERROR (\"[pcl::%s::initCompute] : Number of octaves (%d) must be at least 1!\\n\", \n name_.c_str (), nr_octaves_);\n return (false);\n }\n if (nr_scales_per_octave_ < 1)\n {\n PCL_ERROR (\"[pcl::%s::initCompute] : Number of scales per octave (%d) must be at least 1!\\n\", \n name_.c_str (), nr_scales_per_octave_);\n return (false);\n }\n if (min_contrast_ < 0)\n {\n PCL_ERROR (\"[pcl::%s::initCompute] : Minimum contrast (%f) must be non-negative!\\n\", \n name_.c_str (), min_contrast_);\n return (false);\n }\n \n this->setKSearch (1);\n tree_.reset (new pcl::search::KdTree<PointInT> (true));\n return (true);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate <typename PointInT, typename PointOutT> void \npcl::SIFTKeypoint<PointInT, PointOutT>::detectKeypoints (PointCloudOut &output)\n{\n if (surface_ != input_)\n {\n PCL_WARN (\"[pcl::%s::detectKeypoints] : \", name_.c_str ());\n PCL_WARN (\"A search surface has been set by setSearchSurface, but this SIFT keypoint detection algorithm does \");\n PCL_WARN (\"not support search surfaces other than the input cloud. \");\n PCL_WARN (\"The cloud provided in setInputCloud is being used instead.\\n\");\n }\n\n \/\/ Check if the output has a \"scale\" field\n scale_idx_ = pcl::getFieldIndex<PointOutT> (output, \"scale\", out_fields_);\n\n \/\/ Make sure the output cloud is empty\n output.points.clear ();\n\n \/\/ Create a local copy of the input cloud that will be resized for each octave\n boost::shared_ptr<pcl::PointCloud<PointInT> > cloud (new pcl::PointCloud<PointInT> (*input_));\n\n VoxelGrid<PointInT> voxel_grid;\n \/\/ Search for keypoints at each octave\n float scale = min_scale_;\n for (int i_octave = 0; i_octave < nr_octaves_; ++i_octave)\n {\n \/\/ Downsample the point cloud\n const float s = 1.0f * scale; \/\/ note: this can be adjusted\n voxel_grid.setLeafSize (s, s, s);\n voxel_grid.setInputCloud (cloud);\n boost::shared_ptr<pcl::PointCloud<PointInT> > temp (new pcl::PointCloud<PointInT>); \n voxel_grid.filter (*temp);\n cloud = temp;\n\n \/\/ Make sure the downsampled cloud still has enough points\n const size_t min_nr_points = 25;\n if (cloud->points.size () < min_nr_points)\n break;\n\n \/\/ Update the KdTree with the downsampled points\n tree_->setInputCloud (cloud);\n\n \/\/ Detect keypoints for the current scale\n detectKeypointsForOctave (*cloud, *tree_, scale, nr_scales_per_octave_, output);\n\n \/\/ Increase the scale by another octave\n scale *= 2;\n }\n\n output.height = 1;\n output.width = static_cast<uint32_t> (output.points.size ());\n}\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate <typename PointInT, typename PointOutT> void \npcl::SIFTKeypoint<PointInT, PointOutT>::detectKeypointsForOctave (\n const PointCloudIn &input, KdTree &tree, float base_scale, int nr_scales_per_octave, \n PointCloudOut &output)\n{\n \/\/ Compute the difference of Gaussians (DoG) scale space\n std::vector<float> scales (nr_scales_per_octave + 3);\n for (int i_scale = 0; i_scale <= nr_scales_per_octave + 2; ++i_scale)\n {\n scales[i_scale] = base_scale * powf (2.0f, (1.0f * static_cast<float> (i_scale) - 1.0f) \/ static_cast<float> (nr_scales_per_octave));\n }\n Eigen::MatrixXf diff_of_gauss;\n computeScaleSpace (input, tree, scales, diff_of_gauss);\n\n \/\/ Find extrema in the DoG scale space\n std::vector<int> extrema_indices, extrema_scales;\n findScaleSpaceExtrema (input, tree, diff_of_gauss, extrema_indices, extrema_scales);\n\n output.points.reserve (output.points.size () + extrema_indices.size ());\n \/\/ Save scale?\n if (scale_idx_ != -1)\n {\n \/\/ Add keypoints to output\n for (size_t i_keypoint = 0; i_keypoint < extrema_indices.size (); ++i_keypoint)\n {\n PointOutT keypoint;\n const int &keypoint_index = extrema_indices[i_keypoint];\n \n keypoint.x = input.points[keypoint_index].x;\n keypoint.y = input.points[keypoint_index].y;\n keypoint.z = input.points[keypoint_index].z;\n memcpy (reinterpret_cast<char*> (&keypoint) + out_fields_[scale_idx_].offset,\n &scales[extrema_scales[i_keypoint]], sizeof (float));\n output.points.push_back (keypoint); \n }\n }\n else\n {\n \/\/ Add keypoints to output\n for (size_t i_keypoint = 0; i_keypoint < extrema_indices.size (); ++i_keypoint)\n {\n PointOutT keypoint;\n const int &keypoint_index = extrema_indices[i_keypoint];\n \n keypoint.x = input.points[keypoint_index].x;\n keypoint.y = input.points[keypoint_index].y;\n keypoint.z = input.points[keypoint_index].z;\n\n output.points.push_back (keypoint); \n }\n }\n}\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate <typename PointInT, typename PointOutT> \nvoid pcl::SIFTKeypoint<PointInT, PointOutT>::computeScaleSpace (\n const PointCloudIn &input, KdTree &tree, const std::vector<float> &scales, \n Eigen::MatrixXf &diff_of_gauss)\n{\n diff_of_gauss.resize (input.size (), scales.size () - 1);\n\n \/\/ For efficiency, we will only filter over points within 3 standard deviations \n const float max_radius = 3.0f * scales.back ();\n\n for (int i_point = 0; i_point < static_cast<int> (input.size ()); ++i_point)\n {\n std::vector<int> nn_indices;\n std::vector<float> nn_dist;\n tree.radiusSearch (i_point, max_radius, nn_indices, nn_dist); \/\/ *\n \/\/ * note: at this stage of the algorithm, we must find all points within a radius defined by the maximum scale, \n \/\/ regardless of the configurable search method specified by the user, so we directly employ tree.radiusSearch \n \/\/ here instead of using searchForNeighbors.\n\n \/\/ For each scale, compute the Gaussian \"filter response\" at the current point\n float filter_response = 0.0f;\n float previous_filter_response;\n for (size_t i_scale = 0; i_scale < scales.size (); ++i_scale)\n {\n float sigma_sqr = powf (scales[i_scale], 2.0f);\n\n float numerator = 0.0f;\n float denominator = 0.0f;\n for (size_t i_neighbor = 0; i_neighbor < nn_indices.size (); ++i_neighbor)\n {\n const float &value = getFieldValue_ (input.points[nn_indices[i_neighbor]]);\n const float &dist_sqr = nn_dist[i_neighbor];\n if (dist_sqr <= 9*sigma_sqr)\n {\n float w = expf (-0.5f * dist_sqr \/ sigma_sqr);\n numerator += value * w;\n denominator += w;\n }\n else break; \/\/ i.e. if dist > 3 standard deviations, then terminate early\n }\n previous_filter_response = filter_response;\n filter_response = numerator \/ denominator;\n\n \/\/ Compute the difference between adjacent scales\n if (i_scale > 0)\n diff_of_gauss (i_point, i_scale - 1) = filter_response - previous_filter_response;\n }\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate <typename PointInT, typename PointOutT> void \npcl::SIFTKeypoint<PointInT, PointOutT>::findScaleSpaceExtrema (\n const PointCloudIn &input, KdTree &tree, const Eigen::MatrixXf &diff_of_gauss, \n std::vector<int> &extrema_indices, std::vector<int> &extrema_scales)\n{\n const int k = 25;\n std::vector<int> nn_indices (k);\n std::vector<float> nn_dist (k);\n\n const int nr_scales = static_cast<int> (diff_of_gauss.cols ());\n std::vector<float> min_val (nr_scales), max_val (nr_scales);\n\n for (int i_point = 0; i_point < static_cast<int> (input.size ()); ++i_point)\n {\n \/\/ Define the local neighborhood around the current point\n const size_t nr_nn = tree.nearestKSearch (i_point, k, nn_indices, nn_dist); \/\/*\n \/\/ * note: the neighborhood for finding local extrema is best defined as a small fixed-k neighborhood, regardless of\n \/\/ the configurable search method specified by the user, so we directly employ tree.nearestKSearch here instead \n \/\/ of using searchForNeighbors\n\n \/\/ At each scale, find the extreme values of the DoG within the current neighborhood\n for (int i_scale = 0; i_scale < nr_scales; ++i_scale)\n {\n min_val[i_scale] = std::numeric_limits<float>::max ();\n max_val[i_scale] = -std::numeric_limits<float>::max ();\n\n for (size_t i_neighbor = 0; i_neighbor < nr_nn; ++i_neighbor)\n {\n const float &d = diff_of_gauss (nn_indices[i_neighbor], i_scale);\n\n min_val[i_scale] = (std::min) (min_val[i_scale], d);\n max_val[i_scale] = (std::max) (max_val[i_scale], d);\n }\n }\n\n \/\/ If the current point is an extreme value with high enough contrast, add it as a keypoint \n for (int i_scale = 1; i_scale < nr_scales - 1; ++i_scale)\n {\n const float &val = diff_of_gauss (i_point, i_scale);\n\n \/\/ Does the point have sufficient contrast?\n if (fabs (val) >= min_contrast_)\n {\n \/\/ Is it a local minimum?\n if ((val == min_val[i_scale]) && \n (val < min_val[i_scale - 1]) && \n (val < min_val[i_scale + 1]))\n {\n extrema_indices.push_back (i_point);\n extrema_scales.push_back (i_scale);\n }\n \/\/ Is it a local maximum?\n else if ((val == max_val[i_scale]) && \n (val > max_val[i_scale - 1]) && \n (val > max_val[i_scale + 1]))\n {\n extrema_indices.push_back (i_point);\n extrema_scales.push_back (i_scale);\n }\n }\n }\n }\n}\n\n#define PCL_INSTANTIATE_SIFTKeypoint(T,U) template class PCL_EXPORTS pcl::SIFTKeypoint<T,U>;\n\n#endif \/\/ #ifndef PCL_SIFT_KEYPOINT_IMPL_H_\n\n<commit_msg>* fixed issue #809: fix SIFT surface_ warning (thanks Christian)<commit_after>\/*\n * Software License Agreement (BSD License)\n *\n * Point Cloud Library (PCL) - www.pointclouds.org\n * Copyright (c) 2010-2011, Willow Garage, Inc.\n *\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following\n * disclaimer in the documentation and\/or other materials provided\n * with the distribution.\n * * Neither the name of Willow Garage, Inc. nor the names of its\n * contributors may be used to endorse or promote products derived\n * from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n *\/\n\n#ifndef PCL_SIFT_KEYPOINT_IMPL_H_\n#define PCL_SIFT_KEYPOINT_IMPL_H_\n\n#include <pcl\/keypoints\/sift_keypoint.h>\n#include <pcl\/common\/io.h>\n#include <pcl\/filters\/voxel_grid.h>\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate <typename PointInT, typename PointOutT> void \npcl::SIFTKeypoint<PointInT, PointOutT>::setScales (float min_scale, int nr_octaves, int nr_scales_per_octave)\n{\n min_scale_ = min_scale;\n nr_octaves_ = nr_octaves;\n nr_scales_per_octave_ = nr_scales_per_octave;\n}\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate <typename PointInT, typename PointOutT> void \npcl::SIFTKeypoint<PointInT, PointOutT>::setMinimumContrast (float min_contrast)\n{\n min_contrast_ = min_contrast;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate <typename PointInT, typename PointOutT> bool\npcl::SIFTKeypoint<PointInT, PointOutT>::initCompute ()\n{\n if (min_scale_ <= 0)\n {\n PCL_ERROR (\"[pcl::%s::initCompute] : Minimum scale (%f) must be strict positive!\\n\", \n name_.c_str (), min_scale_);\n return (false);\n }\n if (nr_octaves_ < 1)\n {\n PCL_ERROR (\"[pcl::%s::initCompute] : Number of octaves (%d) must be at least 1!\\n\", \n name_.c_str (), nr_octaves_);\n return (false);\n }\n if (nr_scales_per_octave_ < 1)\n {\n PCL_ERROR (\"[pcl::%s::initCompute] : Number of scales per octave (%d) must be at least 1!\\n\", \n name_.c_str (), nr_scales_per_octave_);\n return (false);\n }\n if (min_contrast_ < 0)\n {\n PCL_ERROR (\"[pcl::%s::initCompute] : Minimum contrast (%f) must be non-negative!\\n\", \n name_.c_str (), min_contrast_);\n return (false);\n }\n \n this->setKSearch (1);\n tree_.reset (new pcl::search::KdTree<PointInT> (true));\n return (true);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate <typename PointInT, typename PointOutT> void \npcl::SIFTKeypoint<PointInT, PointOutT>::detectKeypoints (PointCloudOut &output)\n{\n if (surface_ && surface_ != input_)\n {\n PCL_WARN (\"[pcl::%s::detectKeypoints] : \", name_.c_str ());\n PCL_WARN (\"A search surface has been set by setSearchSurface, but this SIFT keypoint detection algorithm does \");\n PCL_WARN (\"not support search surfaces other than the input cloud. \");\n PCL_WARN (\"The cloud provided in setInputCloud is being used instead.\\n\");\n }\n\n \/\/ Check if the output has a \"scale\" field\n scale_idx_ = pcl::getFieldIndex<PointOutT> (output, \"scale\", out_fields_);\n\n \/\/ Make sure the output cloud is empty\n output.points.clear ();\n\n \/\/ Create a local copy of the input cloud that will be resized for each octave\n boost::shared_ptr<pcl::PointCloud<PointInT> > cloud (new pcl::PointCloud<PointInT> (*input_));\n\n VoxelGrid<PointInT> voxel_grid;\n \/\/ Search for keypoints at each octave\n float scale = min_scale_;\n for (int i_octave = 0; i_octave < nr_octaves_; ++i_octave)\n {\n \/\/ Downsample the point cloud\n const float s = 1.0f * scale; \/\/ note: this can be adjusted\n voxel_grid.setLeafSize (s, s, s);\n voxel_grid.setInputCloud (cloud);\n boost::shared_ptr<pcl::PointCloud<PointInT> > temp (new pcl::PointCloud<PointInT>); \n voxel_grid.filter (*temp);\n cloud = temp;\n\n \/\/ Make sure the downsampled cloud still has enough points\n const size_t min_nr_points = 25;\n if (cloud->points.size () < min_nr_points)\n break;\n\n \/\/ Update the KdTree with the downsampled points\n tree_->setInputCloud (cloud);\n\n \/\/ Detect keypoints for the current scale\n detectKeypointsForOctave (*cloud, *tree_, scale, nr_scales_per_octave_, output);\n\n \/\/ Increase the scale by another octave\n scale *= 2;\n }\n\n output.height = 1;\n output.width = static_cast<uint32_t> (output.points.size ());\n}\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate <typename PointInT, typename PointOutT> void \npcl::SIFTKeypoint<PointInT, PointOutT>::detectKeypointsForOctave (\n const PointCloudIn &input, KdTree &tree, float base_scale, int nr_scales_per_octave, \n PointCloudOut &output)\n{\n \/\/ Compute the difference of Gaussians (DoG) scale space\n std::vector<float> scales (nr_scales_per_octave + 3);\n for (int i_scale = 0; i_scale <= nr_scales_per_octave + 2; ++i_scale)\n {\n scales[i_scale] = base_scale * powf (2.0f, (1.0f * static_cast<float> (i_scale) - 1.0f) \/ static_cast<float> (nr_scales_per_octave));\n }\n Eigen::MatrixXf diff_of_gauss;\n computeScaleSpace (input, tree, scales, diff_of_gauss);\n\n \/\/ Find extrema in the DoG scale space\n std::vector<int> extrema_indices, extrema_scales;\n findScaleSpaceExtrema (input, tree, diff_of_gauss, extrema_indices, extrema_scales);\n\n output.points.reserve (output.points.size () + extrema_indices.size ());\n \/\/ Save scale?\n if (scale_idx_ != -1)\n {\n \/\/ Add keypoints to output\n for (size_t i_keypoint = 0; i_keypoint < extrema_indices.size (); ++i_keypoint)\n {\n PointOutT keypoint;\n const int &keypoint_index = extrema_indices[i_keypoint];\n \n keypoint.x = input.points[keypoint_index].x;\n keypoint.y = input.points[keypoint_index].y;\n keypoint.z = input.points[keypoint_index].z;\n memcpy (reinterpret_cast<char*> (&keypoint) + out_fields_[scale_idx_].offset,\n &scales[extrema_scales[i_keypoint]], sizeof (float));\n output.points.push_back (keypoint); \n }\n }\n else\n {\n \/\/ Add keypoints to output\n for (size_t i_keypoint = 0; i_keypoint < extrema_indices.size (); ++i_keypoint)\n {\n PointOutT keypoint;\n const int &keypoint_index = extrema_indices[i_keypoint];\n \n keypoint.x = input.points[keypoint_index].x;\n keypoint.y = input.points[keypoint_index].y;\n keypoint.z = input.points[keypoint_index].z;\n\n output.points.push_back (keypoint); \n }\n }\n}\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate <typename PointInT, typename PointOutT> \nvoid pcl::SIFTKeypoint<PointInT, PointOutT>::computeScaleSpace (\n const PointCloudIn &input, KdTree &tree, const std::vector<float> &scales, \n Eigen::MatrixXf &diff_of_gauss)\n{\n diff_of_gauss.resize (input.size (), scales.size () - 1);\n\n \/\/ For efficiency, we will only filter over points within 3 standard deviations \n const float max_radius = 3.0f * scales.back ();\n\n for (int i_point = 0; i_point < static_cast<int> (input.size ()); ++i_point)\n {\n std::vector<int> nn_indices;\n std::vector<float> nn_dist;\n tree.radiusSearch (i_point, max_radius, nn_indices, nn_dist); \/\/ *\n \/\/ * note: at this stage of the algorithm, we must find all points within a radius defined by the maximum scale, \n \/\/ regardless of the configurable search method specified by the user, so we directly employ tree.radiusSearch \n \/\/ here instead of using searchForNeighbors.\n\n \/\/ For each scale, compute the Gaussian \"filter response\" at the current point\n float filter_response = 0.0f;\n float previous_filter_response;\n for (size_t i_scale = 0; i_scale < scales.size (); ++i_scale)\n {\n float sigma_sqr = powf (scales[i_scale], 2.0f);\n\n float numerator = 0.0f;\n float denominator = 0.0f;\n for (size_t i_neighbor = 0; i_neighbor < nn_indices.size (); ++i_neighbor)\n {\n const float &value = getFieldValue_ (input.points[nn_indices[i_neighbor]]);\n const float &dist_sqr = nn_dist[i_neighbor];\n if (dist_sqr <= 9*sigma_sqr)\n {\n float w = expf (-0.5f * dist_sqr \/ sigma_sqr);\n numerator += value * w;\n denominator += w;\n }\n else break; \/\/ i.e. if dist > 3 standard deviations, then terminate early\n }\n previous_filter_response = filter_response;\n filter_response = numerator \/ denominator;\n\n \/\/ Compute the difference between adjacent scales\n if (i_scale > 0)\n diff_of_gauss (i_point, i_scale - 1) = filter_response - previous_filter_response;\n }\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate <typename PointInT, typename PointOutT> void \npcl::SIFTKeypoint<PointInT, PointOutT>::findScaleSpaceExtrema (\n const PointCloudIn &input, KdTree &tree, const Eigen::MatrixXf &diff_of_gauss, \n std::vector<int> &extrema_indices, std::vector<int> &extrema_scales)\n{\n const int k = 25;\n std::vector<int> nn_indices (k);\n std::vector<float> nn_dist (k);\n\n const int nr_scales = static_cast<int> (diff_of_gauss.cols ());\n std::vector<float> min_val (nr_scales), max_val (nr_scales);\n\n for (int i_point = 0; i_point < static_cast<int> (input.size ()); ++i_point)\n {\n \/\/ Define the local neighborhood around the current point\n const size_t nr_nn = tree.nearestKSearch (i_point, k, nn_indices, nn_dist); \/\/*\n \/\/ * note: the neighborhood for finding local extrema is best defined as a small fixed-k neighborhood, regardless of\n \/\/ the configurable search method specified by the user, so we directly employ tree.nearestKSearch here instead \n \/\/ of using searchForNeighbors\n\n \/\/ At each scale, find the extreme values of the DoG within the current neighborhood\n for (int i_scale = 0; i_scale < nr_scales; ++i_scale)\n {\n min_val[i_scale] = std::numeric_limits<float>::max ();\n max_val[i_scale] = -std::numeric_limits<float>::max ();\n\n for (size_t i_neighbor = 0; i_neighbor < nr_nn; ++i_neighbor)\n {\n const float &d = diff_of_gauss (nn_indices[i_neighbor], i_scale);\n\n min_val[i_scale] = (std::min) (min_val[i_scale], d);\n max_val[i_scale] = (std::max) (max_val[i_scale], d);\n }\n }\n\n \/\/ If the current point is an extreme value with high enough contrast, add it as a keypoint \n for (int i_scale = 1; i_scale < nr_scales - 1; ++i_scale)\n {\n const float &val = diff_of_gauss (i_point, i_scale);\n\n \/\/ Does the point have sufficient contrast?\n if (fabs (val) >= min_contrast_)\n {\n \/\/ Is it a local minimum?\n if ((val == min_val[i_scale]) && \n (val < min_val[i_scale - 1]) && \n (val < min_val[i_scale + 1]))\n {\n extrema_indices.push_back (i_point);\n extrema_scales.push_back (i_scale);\n }\n \/\/ Is it a local maximum?\n else if ((val == max_val[i_scale]) && \n (val > max_val[i_scale - 1]) && \n (val > max_val[i_scale + 1]))\n {\n extrema_indices.push_back (i_point);\n extrema_scales.push_back (i_scale);\n }\n }\n }\n }\n}\n\n#define PCL_INSTANTIATE_SIFTKeypoint(T,U) template class PCL_EXPORTS pcl::SIFTKeypoint<T,U>;\n\n#endif \/\/ #ifndef PCL_SIFT_KEYPOINT_IMPL_H_\n\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: filewriter.cxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: khong $ $Date: 2002-07-13 01:09:12 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n#include <stdio.h>\n#include <string.h>\n#include \"LocaleNode.hxx\"\n\/\/-----------------------------------------\n\/\/ The document handler, which is needed for the saxparser\n\/\/ The Documenthandler for reading sax\n\/\/-----------------------------------------\nOFileWriter::OFileWriter(const char *pcFile, const char *locale ) {\n\n strncpy( m_pcFile , pcFile, 1024 );\n printf(\"file generated=%s\\n\", m_pcFile);\n m_f = fopen( m_pcFile , \"w\" );\n strcpy(theLocale, locale);\n}\n\nOFileWriter::~OFileWriter() {\n if(m_f)\n fclose( m_f );\n}\n\nvoid OFileWriter::writeInt(sal_Int16 nb) const\n{\n fprintf(m_f, \"%d\", nb);\n}\n\nvoid OFileWriter::writeAsciiString(const char* str) const\n{\n fprintf(m_f, \"%s\", str);\n}\n\nvoid OFileWriter::writeStringCharacters(const ::rtl::OUString& str) const\n{\n for(int i = 0; i < str.getLength(); i++)\n fprintf(m_f, \"0x%x, \", str[i]);\n}\n\nvoid OFileWriter::writeFunction(const char *func, const char *count, const char *array) const\n{\n fprintf(m_f, \"sal_Unicode ** SAL_CALL %s%s(sal_Int16& count)\\n{\\n\", func, theLocale);\n fprintf(m_f, \"\\tcount = %s;\\n\", count);\n fprintf(m_f, \"\\treturn (sal_Unicode**)%s;\\n}\\n\", array);\n}\n\nvoid OFileWriter::writeRefFunction(const char *func, const ::rtl::OUString& useLocale) const\n{\n const char* locale = OUStringToOString(useLocale, RTL_TEXTENCODING_ASCII_US).getStr();\n fprintf(m_f, \"extern sal_Unicode ** SAL_CALL %s%s(sal_Int16& count);\\n\", func, locale);\n fprintf(m_f, \"sal_Unicode ** SAL_CALL %s%s(sal_Int16& count)\\n{\\n\", func, theLocale);\n fprintf(m_f, \"\\treturn %s%s(count);\\n}\\n\", func, locale);\n}\n\nvoid OFileWriter::writeFunction(const char *func, const char *count, const char *array, const char *from, const char *to) const\n{\n fprintf(m_f, \"sal_Unicode ** SAL_CALL %s%s(sal_Int16& count, const sal_Unicode*& from, const sal_Unicode*& to)\\n{\\n\", func, theLocale);\n fprintf(m_f, \"\\tcount = %s;\\n\", count);\n fprintf(m_f, \"\\tfrom = %s;\\n\", from);\n fprintf(m_f, \"\\tto = %s;\\n\", to);\n fprintf(m_f, \"\\treturn (sal_Unicode**)%s;\\n}\\n\", array);\n}\n\nvoid OFileWriter::writeRefFunction(const char *func, const ::rtl::OUString& useLocale, const char *to) const\n{\n const char* locale = OUStringToOString(useLocale, RTL_TEXTENCODING_ASCII_US).getStr();\n fprintf(m_f, \"extern sal_Unicode ** SAL_CALL %s%s(sal_Int16& count, const sal_Unicode*& from, const sal_Unicode*& to);\\n\", func, locale);\n fprintf(m_f, \"sal_Unicode ** SAL_CALL %s%s(sal_Int16& count, const sal_Unicode*& from, const sal_Unicode*& to)\\n{\\n\", func, theLocale);\n fprintf(m_f, \"\\tto = %s;\\n\", to);\n fprintf(m_f, \"\\tconst sal_Unicode* tmp;\\n\");\n fprintf(m_f, \"\\treturn %s%s(count, from, tmp);\\n}\\n\", func, locale);\n}\n\nvoid OFileWriter::writeFunction2(const char *func, const char *style, const char* attr, const char *array) const\n{\n fprintf(m_f, \"const sal_Unicode *** SAL_CALL %s%s( sal_Int16& nStyles, sal_Int16& nAttributes )\\n{\\n\", func, theLocale);\n fprintf(m_f, \"\\tnStyles = %s;\\n\", style);\n fprintf(m_f, \"\\tnAttributes = %s;\\n\", attr);\n fprintf(m_f, \"\\treturn %s;\\n}\\n\", array);\n}\n\nvoid OFileWriter::writeRefFunction2(const char *func, const ::rtl::OUString& useLocale) const\n{\n const char* locale = OUStringToOString(useLocale, RTL_TEXTENCODING_ASCII_US).getStr();\n fprintf(m_f, \"extern const sal_Unicode *** SAL_CALL %s%s(sal_Int16& nStyles, sal_Int16& nAttributes);\\n\", func, locale);\n fprintf(m_f, \"const sal_Unicode *** SAL_CALL %s%s(sal_Int16& nStyles, sal_Int16& nAttributes)\\n{\\n\", func, theLocale);\n fprintf(m_f, \"\\treturn %s%s(nStyles, nAttributes);\\n}\\n\", func, locale);\n}\n\nvoid OFileWriter::writeFunction3(const char *func, const char *style, const char* levels, const char* attr, const char *array) const\n{\n fprintf(m_f, \"const sal_Unicode **** SAL_CALL %s%s( sal_Int16& nStyles, sal_Int16& nLevels, sal_Int16& nAttributes )\\n{\\n\", func, theLocale);\n fprintf(m_f, \"\\tnStyles = %s;\\n\", style);\n fprintf(m_f, \"\\tnLevels = %s;\\n\", levels);\n fprintf(m_f, \"\\tnAttributes = %s;\\n\", attr);\n fprintf(m_f, \"\\treturn %s;\\n}\\n\", array);\n}\n\nvoid OFileWriter::writeRefFunction3(const char *func, const ::rtl::OUString& useLocale) const\n{\n const char* locale = OUStringToOString(useLocale, RTL_TEXTENCODING_ASCII_US).getStr();\n fprintf(m_f, \"extern const sal_Unicode **** SAL_CALL %s%s(sal_Int16& nStyles, sal_Int16& nLevels, sal_Int16& nAttributes);\\n\", func, locale);\n fprintf(m_f, \"const sal_Unicode **** SAL_CALL %s%s(sal_Int16& nStyles, sal_Int16& nLevels, sal_Int16& nAttributes)\\n{\\n\", func, theLocale);\n fprintf(m_f, \"\\treturn %s%s(nStyles, nLevels, nAttributes);\\n}\\n\", func, locale);\n}\n\nvoid OFileWriter::writeIntParameter(const sal_Char* pAsciiStr, const sal_Int16 count, sal_Int16 val) const\n{\n fprintf(m_f, \"static const sal_Unicode %s%d[] = {%d};\\n\", pAsciiStr, count, val);\n}\n\nvoid OFileWriter::writeDefaultParameter(const sal_Char* pAsciiStr, const ::rtl::OUString& str, sal_Int16 count) const\n{\n fprintf(m_f,\"static const sal_Unicode default%s%d[] = {%d};\\n\", pAsciiStr, count,\n str.equalsAscii(\"true\") ? 1 : 0);\n}\n\nvoid OFileWriter::writeDefaultParameter(const sal_Char* pAsciiStr, const ::rtl::OUString& str) const\n{\n fprintf(m_f,\"static const sal_Unicode default%s[] = {%d};\\n\", pAsciiStr,\n str.equalsAscii(\"true\") ? 1 : 0);\n}\n\nvoid OFileWriter::writeParameter(const sal_Char* pAsciiStr, const ::rtl::OUString& aChars) const\n{\n fprintf(m_f, \"static const sal_Unicode %s[] = {\", pAsciiStr);\n writeStringCharacters(aChars);\n fprintf(m_f, \"0x0};\\n\");\n}\n\nvoid OFileWriter::writeParameter(const sal_Char* pAsciiStr, const ::rtl::OUString& aChars, sal_Int16 count) const\n{\n fprintf(m_f, \"static const sal_Unicode %s%d[] = {\", pAsciiStr, count);\n writeStringCharacters(aChars);\n fprintf(m_f, \"0x0};\\n\");\n}\n\nvoid OFileWriter::writeParameter(const sal_Char* pAsciiStr, const ::rtl::OUString& aChars, sal_Int16 count0, sal_Int16 count1) const\n{\n fprintf(m_f, \"static const sal_Unicode %s%d%d[] = {\", pAsciiStr, count0, count1);\n writeStringCharacters(aChars);\n fprintf(m_f, \"0x0};\\n\");\n}\n\nvoid OFileWriter::writeParameter(const sal_Char* pTagStr, const sal_Char* pAsciiStr, const ::rtl::OUString& aChars, const sal_Int16 count) const\n{\n fprintf(m_f, \"static const sal_Unicode %s%s%d[] = {\", pTagStr, pAsciiStr, count);\n writeStringCharacters(aChars);\n fprintf(m_f, \"0x0};\\n\");\n}\n\nvoid OFileWriter::writeParameter(const sal_Char* pTagStr, const sal_Char* pAsciiStr, const ::rtl::OUString& aChars) const\n{\n fprintf(m_f, \"static const sal_Unicode %s%s[] = {\", pTagStr, pAsciiStr);\n writeStringCharacters(aChars);\n fprintf(m_f, \"0x0};\\n\");\n}\n\nvoid OFileWriter::writeParameter(const sal_Char* pTagStr, const sal_Char* pAsciiStr, const ::rtl::OUString& aChars, sal_Int16 count0, sal_Int16 count1) const\n{\n fprintf(m_f, \"static const sal_Unicode %s%s%d%d[] = {\", pTagStr, pAsciiStr, count0, count1);\n writeStringCharacters(aChars);\n fprintf(m_f, \"0x0};\\n\");\n}\n\nvoid OFileWriter::flush(void) const\n{\n fflush( m_f );\n}\n\nvoid OFileWriter::closeOutput(void) const\n{\n if(m_f)\n {\n fclose( m_f );\n const_cast< OFileWriter * > ( this )->m_f = 0;\n }\n}\n\n<commit_msg>#101191# don't remember pointers to buffers of temporary objects, they may be gone any time<commit_after>\/*************************************************************************\n *\n * $RCSfile: filewriter.cxx,v $\n *\n * $Revision: 1.4 $\n *\n * last change: $Author: er $ $Date: 2002-07-15 14:16:10 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n#include <stdio.h>\n#include <string.h>\n#include \"LocaleNode.hxx\"\n\/\/-----------------------------------------\n\/\/ The document handler, which is needed for the saxparser\n\/\/ The Documenthandler for reading sax\n\/\/-----------------------------------------\nOFileWriter::OFileWriter(const char *pcFile, const char *locale ) {\n\n strncpy( m_pcFile , pcFile, 1024 );\n printf(\"file generated=%s\\n\", m_pcFile);\n m_f = fopen( m_pcFile , \"w\" );\n strcpy(theLocale, locale);\n}\n\nOFileWriter::~OFileWriter() {\n if(m_f)\n fclose( m_f );\n}\n\nvoid OFileWriter::writeInt(sal_Int16 nb) const\n{\n fprintf(m_f, \"%d\", nb);\n}\n\nvoid OFileWriter::writeAsciiString(const char* str) const\n{\n fprintf(m_f, \"%s\", str);\n}\n\nvoid OFileWriter::writeStringCharacters(const ::rtl::OUString& str) const\n{\n for(int i = 0; i < str.getLength(); i++)\n fprintf(m_f, \"0x%x, \", str[i]);\n}\n\nvoid OFileWriter::writeFunction(const char *func, const char *count, const char *array) const\n{\n fprintf(m_f, \"sal_Unicode ** SAL_CALL %s%s(sal_Int16& count)\\n{\\n\", func, theLocale);\n fprintf(m_f, \"\\tcount = %s;\\n\", count);\n fprintf(m_f, \"\\treturn (sal_Unicode**)%s;\\n}\\n\", array);\n}\n\nvoid OFileWriter::writeRefFunction(const char *func, const ::rtl::OUString& useLocale) const\n{\n OString aRefLocale( OUStringToOString(useLocale, RTL_TEXTENCODING_ASCII_US) );\n const char* locale = aRefLocale.getStr();\n fprintf(m_f, \"extern sal_Unicode ** SAL_CALL %s%s(sal_Int16& count);\\n\", func, locale);\n fprintf(m_f, \"sal_Unicode ** SAL_CALL %s%s(sal_Int16& count)\\n{\\n\", func, theLocale);\n fprintf(m_f, \"\\treturn %s%s(count);\\n}\\n\", func, locale);\n}\n\nvoid OFileWriter::writeFunction(const char *func, const char *count, const char *array, const char *from, const char *to) const\n{\n fprintf(m_f, \"sal_Unicode ** SAL_CALL %s%s(sal_Int16& count, const sal_Unicode*& from, const sal_Unicode*& to)\\n{\\n\", func, theLocale);\n fprintf(m_f, \"\\tcount = %s;\\n\", count);\n fprintf(m_f, \"\\tfrom = %s;\\n\", from);\n fprintf(m_f, \"\\tto = %s;\\n\", to);\n fprintf(m_f, \"\\treturn (sal_Unicode**)%s;\\n}\\n\", array);\n}\n\nvoid OFileWriter::writeRefFunction(const char *func, const ::rtl::OUString& useLocale, const char *to) const\n{\n OString aRefLocale( OUStringToOString(useLocale, RTL_TEXTENCODING_ASCII_US) );\n const char* locale = aRefLocale.getStr();\n fprintf(m_f, \"extern sal_Unicode ** SAL_CALL %s%s(sal_Int16& count, const sal_Unicode*& from, const sal_Unicode*& to);\\n\", func, locale);\n fprintf(m_f, \"sal_Unicode ** SAL_CALL %s%s(sal_Int16& count, const sal_Unicode*& from, const sal_Unicode*& to)\\n{\\n\", func, theLocale);\n fprintf(m_f, \"\\tto = %s;\\n\", to);\n fprintf(m_f, \"\\tconst sal_Unicode* tmp;\\n\");\n fprintf(m_f, \"\\treturn %s%s(count, from, tmp);\\n}\\n\", func, locale);\n}\n\nvoid OFileWriter::writeFunction2(const char *func, const char *style, const char* attr, const char *array) const\n{\n fprintf(m_f, \"const sal_Unicode *** SAL_CALL %s%s( sal_Int16& nStyles, sal_Int16& nAttributes )\\n{\\n\", func, theLocale);\n fprintf(m_f, \"\\tnStyles = %s;\\n\", style);\n fprintf(m_f, \"\\tnAttributes = %s;\\n\", attr);\n fprintf(m_f, \"\\treturn %s;\\n}\\n\", array);\n}\n\nvoid OFileWriter::writeRefFunction2(const char *func, const ::rtl::OUString& useLocale) const\n{\n OString aRefLocale( OUStringToOString(useLocale, RTL_TEXTENCODING_ASCII_US) );\n const char* locale = aRefLocale.getStr();\n fprintf(m_f, \"extern const sal_Unicode *** SAL_CALL %s%s(sal_Int16& nStyles, sal_Int16& nAttributes);\\n\", func, locale);\n fprintf(m_f, \"const sal_Unicode *** SAL_CALL %s%s(sal_Int16& nStyles, sal_Int16& nAttributes)\\n{\\n\", func, theLocale);\n fprintf(m_f, \"\\treturn %s%s(nStyles, nAttributes);\\n}\\n\", func, locale);\n}\n\nvoid OFileWriter::writeFunction3(const char *func, const char *style, const char* levels, const char* attr, const char *array) const\n{\n fprintf(m_f, \"const sal_Unicode **** SAL_CALL %s%s( sal_Int16& nStyles, sal_Int16& nLevels, sal_Int16& nAttributes )\\n{\\n\", func, theLocale);\n fprintf(m_f, \"\\tnStyles = %s;\\n\", style);\n fprintf(m_f, \"\\tnLevels = %s;\\n\", levels);\n fprintf(m_f, \"\\tnAttributes = %s;\\n\", attr);\n fprintf(m_f, \"\\treturn %s;\\n}\\n\", array);\n}\n\nvoid OFileWriter::writeRefFunction3(const char *func, const ::rtl::OUString& useLocale) const\n{\n OString aRefLocale( OUStringToOString(useLocale, RTL_TEXTENCODING_ASCII_US) );\n const char* locale = aRefLocale.getStr();\n fprintf(m_f, \"extern const sal_Unicode **** SAL_CALL %s%s(sal_Int16& nStyles, sal_Int16& nLevels, sal_Int16& nAttributes);\\n\", func, locale);\n fprintf(m_f, \"const sal_Unicode **** SAL_CALL %s%s(sal_Int16& nStyles, sal_Int16& nLevels, sal_Int16& nAttributes)\\n{\\n\", func, theLocale);\n fprintf(m_f, \"\\treturn %s%s(nStyles, nLevels, nAttributes);\\n}\\n\", func, locale);\n}\n\nvoid OFileWriter::writeIntParameter(const sal_Char* pAsciiStr, const sal_Int16 count, sal_Int16 val) const\n{\n fprintf(m_f, \"static const sal_Unicode %s%d[] = {%d};\\n\", pAsciiStr, count, val);\n}\n\nvoid OFileWriter::writeDefaultParameter(const sal_Char* pAsciiStr, const ::rtl::OUString& str, sal_Int16 count) const\n{\n fprintf(m_f,\"static const sal_Unicode default%s%d[] = {%d};\\n\", pAsciiStr, count,\n str.equalsAscii(\"true\") ? 1 : 0);\n}\n\nvoid OFileWriter::writeDefaultParameter(const sal_Char* pAsciiStr, const ::rtl::OUString& str) const\n{\n fprintf(m_f,\"static const sal_Unicode default%s[] = {%d};\\n\", pAsciiStr,\n str.equalsAscii(\"true\") ? 1 : 0);\n}\n\nvoid OFileWriter::writeParameter(const sal_Char* pAsciiStr, const ::rtl::OUString& aChars) const\n{\n fprintf(m_f, \"static const sal_Unicode %s[] = {\", pAsciiStr);\n writeStringCharacters(aChars);\n fprintf(m_f, \"0x0};\\n\");\n}\n\nvoid OFileWriter::writeParameter(const sal_Char* pAsciiStr, const ::rtl::OUString& aChars, sal_Int16 count) const\n{\n fprintf(m_f, \"static const sal_Unicode %s%d[] = {\", pAsciiStr, count);\n writeStringCharacters(aChars);\n fprintf(m_f, \"0x0};\\n\");\n}\n\nvoid OFileWriter::writeParameter(const sal_Char* pAsciiStr, const ::rtl::OUString& aChars, sal_Int16 count0, sal_Int16 count1) const\n{\n fprintf(m_f, \"static const sal_Unicode %s%d%d[] = {\", pAsciiStr, count0, count1);\n writeStringCharacters(aChars);\n fprintf(m_f, \"0x0};\\n\");\n}\n\nvoid OFileWriter::writeParameter(const sal_Char* pTagStr, const sal_Char* pAsciiStr, const ::rtl::OUString& aChars, const sal_Int16 count) const\n{\n fprintf(m_f, \"static const sal_Unicode %s%s%d[] = {\", pTagStr, pAsciiStr, count);\n writeStringCharacters(aChars);\n fprintf(m_f, \"0x0};\\n\");\n}\n\nvoid OFileWriter::writeParameter(const sal_Char* pTagStr, const sal_Char* pAsciiStr, const ::rtl::OUString& aChars) const\n{\n fprintf(m_f, \"static const sal_Unicode %s%s[] = {\", pTagStr, pAsciiStr);\n writeStringCharacters(aChars);\n fprintf(m_f, \"0x0};\\n\");\n}\n\nvoid OFileWriter::writeParameter(const sal_Char* pTagStr, const sal_Char* pAsciiStr, const ::rtl::OUString& aChars, sal_Int16 count0, sal_Int16 count1) const\n{\n fprintf(m_f, \"static const sal_Unicode %s%s%d%d[] = {\", pTagStr, pAsciiStr, count0, count1);\n writeStringCharacters(aChars);\n fprintf(m_f, \"0x0};\\n\");\n}\n\nvoid OFileWriter::flush(void) const\n{\n fflush( m_f );\n}\n\nvoid OFileWriter::closeOutput(void) const\n{\n if(m_f)\n {\n fclose( m_f );\n const_cast< OFileWriter * > ( this )->m_f = 0;\n }\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/* Copyright 2007-2015 QReal Research Group\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License. *\/\n\n#include \"qrxcLauncher.h\"\n\n#include \"plugins\/metaEditor\/metaEditorSupport\/editorGenerator.h\"\n#include \"qrgui\/plugins\/toolPluginInterface\/usedInterfaces\/mainWindowInterpretersInterface.h\"\n#include \"qrrepo\/repoApi.h\"\n#include \"qrgui\/mainWindow\/errorReporter.h\"\n#include \"qrxc\/xmlCompiler.h\"\n#include \"defs.h\"\n\nusing namespace qReal;\nusing namespace qrRepo;\nusing namespace metaEditor;\nusing namespace gui;\nusing namespace editorPluginTestingFramework;\n\nvoid QrxcLauncher::launchQrxc(const QString &fileName, const QString &pathToQRealSources, const QString &pathToGeneratedCode)\n{\n\tqDebug() << \"STARTING QRXC LAUNCHING\";\n\tQString normalizedFileName = fileName;\n\n\tif (!fileName.contains(\".qrs\")) {\n\t\tnormalizedFileName += \".qrs\";\n\t}\n\n\tconst RepoApi *mRepoApi = new RepoApi(normalizedFileName);\n\tErrorReporter * const reporter = new ErrorReporter();\n\tEditorGenerator editorGenerator(*mRepoApi, *reporter);\n\n\tQDir dir(\".\");\n\n\tQHash<qReal::Id, QPair<QString, QString>> metamodelList = editorGenerator.getMetamodelList();\n\n\tdir.mkpath(pathToGeneratedCode + pathToQrxcGeneratedCode);\n\tfor (const Id &key : metamodelList.keys()) {\n\t\tif (mRepoApi->isLogicalElement(key)) {\n\t\t\tconst QString &directoryToGeneratedCode = generatePathToPlugin(pathToGeneratedCode);\n\n\t\t\tif (!dir.exists(directoryToGeneratedCode)) {\n\t\t\t\tdir.mkdir(directoryToGeneratedCode);\n\t\t\t}\n\n\t\t\tQPair<QString, QString> const metamodelNames = editorGenerator.generateEditor(key\n\t\t\t\t\t, pathToGeneratedCode + pathToQrxcGeneratedCode\n\t\t\t\t\t, pathToQRealSources);\n\t\t}\n\t}\n\tqDebug() << stringSeparator;\n}\n\nQString QrxcLauncher::generatePathToPlugin(const QString &pathToGeneratedCode)\n{\n\tQString result;\n\n\tfor (int i = 0; i < 3; i++) {\n\t\tresult += \"..\/\";\n\t}\n\n\tresult += pathToGeneratedCode + pathToQrxcGeneratedPlugin;\n\n\treturn result;\n}\n<commit_msg>small corrections<commit_after>\/* Copyright 2007-2015 QReal Research Group\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License. *\/\n\n#include \"qrxcLauncher.h\"\n\n#include \"plugins\/metaEditor\/metaEditorSupport\/editorGenerator.h\"\n#include \"qrgui\/plugins\/toolPluginInterface\/usedInterfaces\/mainWindowInterpretersInterface.h\"\n#include \"qrrepo\/repoApi.h\"\n#include \"qrgui\/mainWindow\/errorReporter.h\"\n#include \"qrxc\/xmlCompiler.h\"\n#include \"defs.h\"\n\nusing namespace qReal;\nusing namespace qrRepo;\nusing namespace metaEditor;\nusing namespace gui;\nusing namespace editorPluginTestingFramework;\n\nvoid QrxcLauncher::launchQrxc(const QString &fileName, const QString &pathToQRealSources, const QString &pathToGeneratedCode)\n{\n\tqDebug() << \"STARTING QRXC LAUNCHING\";\n\tQString normalizedFileName = fileName;\n\n\tif (!fileName.contains(\".qrs\")) {\n\t\tnormalizedFileName += \".qrs\";\n\t}\n\n\tconst RepoApi *mRepoApi = new RepoApi(normalizedFileName);\n\tErrorReporter * const reporter = new ErrorReporter();\n\tEditorGenerator editorGenerator(*mRepoApi, *reporter);\n\n\tQDir dir(\".\");\n\n\tQHash<qReal::Id, QPair<QString, QString>> metamodelList = editorGenerator.getMetamodelList();\n\n\tdir.mkpath(pathToGeneratedCode + pathToQrxcGeneratedCode);\n\tfor (const Id &key : metamodelList.keys()) {\n\t\tif (mRepoApi->isLogicalElement(key)) {\n\t\t\tconst QString &directoryToGeneratedCode = generatePathToPlugin(pathToGeneratedCode);\n\n\t\t\tif (!dir.exists(directoryToGeneratedCode)) {\n\t\t\t\tdir.mkdir(directoryToGeneratedCode);\n\t\t\t}\n\n\t\t\teditorGenerator.generateEditor(key, pathToGeneratedCode + pathToQrxcGeneratedCode, pathToQRealSources);\n\t\t}\n\t}\n\tqDebug() << stringSeparator;\n}\n\nQString QrxcLauncher::generatePathToPlugin(const QString &pathToGeneratedCode)\n{\n\tQString result;\n\n\tfor (int i = 0; i < 3; i++) {\n\t\tresult += \"..\/\";\n\t}\n\n\tresult += pathToGeneratedCode + pathToQrxcGeneratedPlugin;\n\n\treturn result;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/\/\n\/\/\/ @file main.cpp\n\/\/\/\n\/\/\/ @Copyright (C) 2013 The Imaging Source GmbH; Edgar Thier <edgarthier@gmail.com>\n\/\/\/\n\/\/\/ main file for the commandline client that allows IP configuration of GigE cameras\n\/\/\/\n\n#include \"ConsoleManager.h\"\n\n#include <string>\n#include <vector>\n#include <iostream>\n\nusing namespace tis;\n\n\n\/\/\/ @name printHelp\n\/\/\/ @brief prints complete overview over possible actions\nvoid printHelp ()\n{\n std::cout << \"\\ntis_network - network module for GigE cameras\"\n << \"\\n\\nusage: tis_network [command] - execute specified command\"\n << \"\\n or: tis_network [command] -c <camera> - execute command for given camera\\n\\n\\n\"\n\n << \"Available commands:\\n\"\n << \" list - list all available GigE cameras\\n\"\n << \" info - print all information for camera\\n\"\n << \" set - configure camera settings\\n\"\n << \" forceip - force ip onto camera\\n\"\n << \" rescue - broadcasts to MAC given settings\\n\"\n << \" upload - upload new firmware to camera\\n\"\n << \" help - print this text\\n\"\n << std::endl;\n\n std::cout << \"\\nAvailable parameter:\\n\"\n << \" -c <camera-serialnumber> - specify camera to use\\n\"\n << \" -h - same as help\\n\"\n << \" -i - same as info\\n\"\n << \" -l - same as list\\n\"\n << \" ip=X.X.X.X - specifiy persistent ip that camera shall use\\n\"\n << \" subnet=X.X.X.X - specifiy persistent subnetmask that camera shall use\\n\"\n << \" gateway=X.X.X.X - specifiy persistent gateway that camera shall use\\n\"\n << \" dhcp=on\/off - toggle dhcp state\\n\"\n << \" static=on\/off - toggle static ip state\\n\"\n << \" name=\\\"xyz\\\" - set name for camera; maximum 16 characters\\n\"\n << \" firmware=firmware.zip - file containing new firmware\\n\"\n << std::endl;\n\n std::cout << \"Examples:\\n\\n\"\n\n << \" tis_network set gateway=192.168.0.1 -c 46210199\\n\"\n << \" tis_network forceip ip=192.168.0.100 subnet=255.255.255.0 gateway=192.168.0.1 -c 46210199\\n\\n\"\n << std::endl;\n}\n\n\nvoid handleCommandlineArguments (const int argc, char* argv[])\n{\n if (argc == 1)\n {\n printHelp();\n return;\n }\n\n \/\/ std::string makes things easier to handle\n \/\/ we don;t need the program name itself and just ignore it\n std::vector<std::string> args(argv+1, argv + argc);\n\n for (const auto& arg : args)\n {\n if ((arg.compare(\"help\") == 0) || (arg.compare(\"-h\") == 0))\n {\n printHelp();\n return;\n }\n else if ((arg.compare(\"list\") == 0) || (arg.compare(\"-l\") == 0))\n {\n listCameras();\n break;\n }\n else if ((arg.compare(\"info\") == 0) || arg.compare(\"-i\") == 0)\n {\n if (argc <= 2)\n {\n std::cout << \"Not enough arguments.\" << std::endl;\n return;\n }\n printCameraInformation(args);\n break;\n }\n else if (arg.compare(\"set\") == 0)\n {\n if (argc <= 2)\n {\n std::cout << \"Not enough arguments.\" << std::endl;\n return;\n }\n setCamera(args);\n break;\n }\n else if (arg.compare(\"forceip\") == 0)\n {\n forceIP(args);\n break;\n }\n else if (arg.compare(\"upload\") == 0)\n {\n upgradeFirmware(args);\n break;\n }\n else if (arg.compare(\"rescue\") == 0)\n {\n rescue(args);\n break;\n }\n else\n {\n \/\/ TODO allow it to write camera before other args so that -c does not break it\n std::cout << \"Unknown parameter \\\"\" << arg << \"\\\"\\n\" << std::endl;\n return;\n }\n }\n}\n\n\nint main (int argc, char* argv[])\n{\n handleCommandlineArguments(argc, argv);\n\n return 0;\n}\n<commit_msg>Wrapped handleCommandlineArguments loop in try\/catch<commit_after>\/\/\/\n\/\/\/ @file main.cpp\n\/\/\/\n\/\/\/ @Copyright (C) 2013 The Imaging Source GmbH; Edgar Thier <edgarthier@gmail.com>\n\/\/\/\n\/\/\/ main file for the commandline client that allows IP configuration of GigE cameras\n\/\/\/\n\n#include \"ConsoleManager.h\"\n\n#include <string>\n#include <vector>\n#include <iostream>\n#include <exception>\n#include <stdexcept>\n\nusing namespace tis;\n\n\n\/\/\/ @name printHelp\n\/\/\/ @brief prints complete overview over possible actions\nvoid printHelp ()\n{\n std::cout << \"\\ntis_network - network module for GigE cameras\"\n << \"\\n\\nusage: tis_network [command] - execute specified command\"\n << \"\\n or: tis_network [command] -c <camera> - execute command for given camera\\n\\n\\n\"\n\n << \"Available commands:\\n\"\n << \" list - list all available GigE cameras\\n\"\n << \" info - print all information for camera\\n\"\n << \" set - configure camera settings\\n\"\n << \" forceip - force ip onto camera\\n\"\n << \" rescue - broadcasts to MAC given settings\\n\"\n << \" upload - upload new firmware to camera\\n\"\n << \" help - print this text\\n\"\n << std::endl;\n\n std::cout << \"\\nAvailable parameter:\\n\"\n << \" -c <camera-serialnumber> - specify camera to use\\n\"\n << \" -h - same as help\\n\"\n << \" -i - same as info\\n\"\n << \" -l - same as list\\n\"\n << \" ip=X.X.X.X - specifiy persistent ip that camera shall use\\n\"\n << \" subnet=X.X.X.X - specifiy persistent subnetmask that camera shall use\\n\"\n << \" gateway=X.X.X.X - specifiy persistent gateway that camera shall use\\n\"\n << \" dhcp=on\/off - toggle dhcp state\\n\"\n << \" static=on\/off - toggle static ip state\\n\"\n << \" name=\\\"xyz\\\" - set name for camera; maximum 16 characters\\n\"\n << \" firmware=firmware.zip - file containing new firmware\\n\"\n << std::endl;\n\n std::cout << \"Examples:\\n\\n\"\n\n << \" tis_network set gateway=192.168.0.1 -c 46210199\\n\"\n << \" tis_network forceip ip=192.168.0.100 subnet=255.255.255.0 gateway=192.168.0.1 -c 46210199\\n\\n\"\n << std::endl;\n}\n\n\nvoid handleCommandlineArguments (const int argc, char* argv[])\n{\n if (argc == 1)\n {\n printHelp();\n return;\n }\n\n \/\/ std::string makes things easier to handle\n \/\/ we don;t need the program name itself and just ignore it\n std::vector<std::string> args(argv+1, argv + argc);\n\n try\n {\n for (const auto& arg : args)\n {\n if ((arg.compare(\"help\") == 0) || (arg.compare(\"-h\") == 0))\n {\n printHelp();\n return;\n }\n else if ((arg.compare(\"list\") == 0) || (arg.compare(\"-l\") == 0))\n {\n listCameras();\n break;\n }\n else if ((arg.compare(\"info\") == 0) || arg.compare(\"-i\") == 0)\n {\n if (argc <= 2)\n {\n std::cout << \"Not enough arguments.\" << std::endl;\n return;\n }\n printCameraInformation(args);\n break;\n }\n else if (arg.compare(\"set\") == 0)\n {\n if (argc <= 2)\n {\n std::cout << \"Not enough arguments.\" << std::endl;\n return;\n }\n setCamera(args);\n break;\n }\n else if (arg.compare(\"forceip\") == 0)\n {\n forceIP(args);\n break;\n }\n else if (arg.compare(\"upload\") == 0)\n {\n upgradeFirmware(args);\n break;\n }\n else if (arg.compare(\"rescue\") == 0)\n {\n rescue(args);\n break;\n }\n else\n {\n \/\/ TODO allow it to write camera before other args so that -c does not break it\n std::cout << \"Unknown parameter \\\"\" << arg << \"\\\"\\n\" << std::endl;\n return;\n }\n }\n }\n catch (std::invalid_argument& exc)\n {\n std::cout << \"\\n\" << exc.what()\n << \"\\n\" << std::endl;\n exit(1);\n }\n}\n\n\nint main (int argc, char* argv[])\n{\n handleCommandlineArguments(argc, argv);\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ JSONObject.hpp\n\/\/ G3MiOSSDK\n\/\/\n\/\/ Created by Oliver Koehler on 01\/10\/12.\n\/\/ Copyright (c) 2012 __MyCompanyName__. All rights reserved.\n\/\/\n\n#ifndef G3MiOSSDK_JSONObject_hpp\n#define G3MiOSSDK_JSONObject_hpp\n\n#include <map>\n#include \"JSONBaseObject.hpp\"\n#include \"ILogger.hpp\"\n\n\nclass JSONObject : public JSONBaseObject{\nprivate:\n std::map<std::string, JSONBaseObject*> _entries;\n \npublic:\n ~JSONObject();\n JSONObject* getObject(){\n return this;\n }\n \n JSONBaseObject* getObjectForKey(std::string key);\n \n void putObject(const std::string key, JSONBaseObject* object);\n \n int getSize();\n \n};\n\n\n\n#endif\n<commit_msg>still fixing java conversion issues<commit_after>\/\/\n\/\/ JSONObject.hpp\n\/\/ G3MiOSSDK\n\/\/\n\/\/ Created by Oliver Koehler on 01\/10\/12.\n\/\/ Copyright (c) 2012 __MyCompanyName__. All rights reserved.\n\/\/\n\n#ifndef G3MiOSSDK_JSONObject_hpp\n#define G3MiOSSDK_JSONObject_hpp\n\n#include <map>\n#include \"JSONBaseObject.hpp\"\n#include \"ILogger.hpp\"\n\n\nclass JSONObject : public JSONBaseObject{\nprivate:\n std::map<std::string, JSONBaseObject*> _entries;\n \npublic:\n ~JSONObject();\n JSONObject* getObject(){\n return this;\n }\n \n JSONBaseObject* getObjectForKey(const std::string key);\n \n void putObject(const std::string key, JSONBaseObject* object);\n \n int getSize();\n \n};\n\n\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/*********************************************************************\n *\n * Software License Agreement (BSD License)\n *\n * Copyright (c) 2012, Worcester Polytechnic Institute\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following\n * disclaimer in the documentation and\/or other materials provided\n * with the distribution.\n * * Neither the name of the Worcester Polytechnic Institute nor the \n * names of its contributors may be used to endorse or promote \n * products derived from this software without specific prior \n * written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n * Author: Paul Malmsten\n * Version: Sep 18, 2012\n *\n *********************************************************************\/\n\n\/*!\n * \\file extract_objects.cpp\n * \\brief Given a .pcd file, this program extracts all objects and saves \\\n * them as separate object_*.pcd files in the working directory. \n * \n * \\author Paul Malmsten, WPI - pmalmsten@wpi.edu\n * \\date Sep 18, 2012\n *\/\n\n#include <sstream>\n#include <string>\n#include <vector>\n\n#include <pcl\/io\/pcd_io.h>\n\n#include \"rail_pcl_object_segmentation\/pcl_segmenter.hpp\"\n\n\/*!\n * \\brief Main function for extract_objects executable.\n * \n * Reads the specified .pcd file, extracts all objects from it, and\n * saves them as separate .pcd files in the current working directory.\n * \n * Each created file is called object_I.pcd, where I is an integer\n * which increases from 0.\n *\/\nint main(int argc, char** argv)\n{\n if (argc < 2)\n {\n std::cerr << \"Usage: extract_objects [options] path\/to\/input.pcd\" << std::endl;\n std::cerr << \" Options:\" << std::endl;\n std::cerr << \" --debug Saves all intermediate point clouds to disk, including\" << std::endl;\n std::cerr << \" the original minus planes and each extracted plane\" << std::endl;\n std::cerr << \" Extracted objects are saved to object_*.pcd in the\" << std::endl << \" current directory.\"\n << std::endl;\n return 1;\n }\n \n bool inDebugMode = (argc == 3 && strcmp(argv[1], \"--debug\") == 0);\n pcl::PCDWriter writer;\n\n \/\/ Read input file\n std::cout << \"Reading '\" << argv[argc - 1] << \"'...\" << std::endl;\n pcl::PCDReader reader;\n pcl::PointCloud<pcl::PointXYZ>::Ptr cloud(new pcl::PointCloud<pcl::PointXYZ>());\n reader.read(argv[argc - 1], *cloud);\n\n \/\/ Down sample\n pcl::PointCloud<pcl::PointXYZ>::Ptr processed_cloud = pcl::PointCloud<pcl::PointXYZ>::Ptr(\n new pcl::PointCloud<pcl::PointXYZ>());\n\n rail::DownsampleCloud<pcl::PointXYZ>(cloud, processed_cloud);\n \n if(inDebugMode) {\n std::cout << \"Writing downsampled cloud as 'input_downsampled_rgb.pcd'\" << std::endl;\n writer.write(\"input_downsampled_rgb.pcd\", *processed_cloud);\n }\n\n \/\/ Remove planes\n std::vector<rail::DiscoveredPlanePtr> planes;\n rail::ExtractPlanes<pcl::PointXYZ>(processed_cloud, processed_cloud, planes);\n \n if(inDebugMode) {\n \/\/ Dump original w\/o planes\n std::cout << \"Writing input without large planes as 'input_minus_planes_rgb.pcd'\" << std::endl;\n writer.write(\"input_minus_planes_rgb.pcd\", *processed_cloud);\n \n \/\/ Dump planes\n unsigned int i = 0;\n for(std::vector<rail::DiscoveredPlanePtr>::iterator it = planes.begin(); it != planes.end(); ++it) {\n std::stringstream fileName;\n fileName << \"extracted_plane_\" << i++ << \"_rgb.pcd\";\n \n std::cout << \" Writing extracted plane to \" << fileName.str() << std::endl;\n writer.write(fileName.str(), (*(*it)).planeCloud);\n }\n }\n\n \/\/ Extract objects\n std::cout << \"Extracting objects...\" << std::endl;\n\n std::vector<pcl::PointCloud<pcl::PointXYZ>::Ptr> objects;\n rail::ExtractObjectClouds<pcl::PointXYZ>(processed_cloud, objects);\n\n std::cout << \" Extracted \" << objects.size() << \" objects.\" << std::endl;\n\n \/\/ Save results\n int i = 0;\n for (std::vector<pcl::PointCloud<pcl::PointXYZ>::Ptr>::iterator it = objects.begin(); it != objects.end(); ++it)\n {\n std::stringstream fileName;\n fileName << \"object_\" << i << \"_rgb.pcd\";\n\n std::cout << \"Writing \" << fileName.str() << std::endl;\n\n writer.write(fileName.str(), *(*it));\n i++;\n }\n\n return 0;\n}\n<commit_msg>Fixed file naming bugs in extract_objects<commit_after>\/*********************************************************************\n *\n * Software License Agreement (BSD License)\n *\n * Copyright (c) 2012, Worcester Polytechnic Institute\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following\n * disclaimer in the documentation and\/or other materials provided\n * with the distribution.\n * * Neither the name of the Worcester Polytechnic Institute nor the \n * names of its contributors may be used to endorse or promote \n * products derived from this software without specific prior \n * written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n * Author: Paul Malmsten\n * Version: Sep 18, 2012\n *\n *********************************************************************\/\n\n\/*!\n * \\file extract_objects.cpp\n * \\brief Given a .pcd file, this program extracts all objects and saves \\\n * them as separate object_*.pcd files in the working directory. \n * \n * \\author Paul Malmsten, WPI - pmalmsten@wpi.edu\n * \\date Sep 18, 2012\n *\/\n\n#include <sstream>\n#include <string>\n#include <vector>\n\n#include <pcl\/io\/pcd_io.h>\n\n#include \"rail_pcl_object_segmentation\/pcl_segmenter.hpp\"\n\n\/*!\n * \\brief Main function for extract_objects executable.\n * \n * Reads the specified .pcd file, extracts all objects from it, and\n * saves them as separate .pcd files in the current working directory.\n * \n * Each created file is called object_I.pcd, where I is an integer\n * which increases from 0.\n *\/\nint main(int argc, char** argv)\n{\n if (argc < 2)\n {\n std::cerr << \"Usage: extract_objects [options] path\/to\/input.pcd\" << std::endl;\n std::cerr << \" Options:\" << std::endl;\n std::cerr << \" --debug Saves all intermediate point clouds to disk, including\" << std::endl;\n std::cerr << \" the original minus planes and each extracted plane\" << std::endl;\n std::cerr << \" Extracted objects are saved to object_*.pcd in the\" << std::endl << \" current directory.\"\n << std::endl;\n return 1;\n }\n \n bool inDebugMode = (argc == 3 && strcmp(argv[1], \"--debug\") == 0);\n pcl::PCDWriter writer;\n\n \/\/ Read input file\n std::cout << \"Reading '\" << argv[argc - 1] << \"'...\" << std::endl;\n pcl::PCDReader reader;\n pcl::PointCloud<pcl::PointXYZ>::Ptr cloud(new pcl::PointCloud<pcl::PointXYZ>());\n reader.read(argv[argc - 1], *cloud);\n\n \/\/ Down sample\n pcl::PointCloud<pcl::PointXYZ>::Ptr processed_cloud = pcl::PointCloud<pcl::PointXYZ>::Ptr(\n new pcl::PointCloud<pcl::PointXYZ>());\n\n rail::DownsampleCloud<pcl::PointXYZ>(cloud, processed_cloud);\n \n if(inDebugMode) {\n std::cout << \"Writing downsampled cloud as 'input_downsampled.pcd'\" << std::endl;\n writer.write(\"input_downsampled.pcd\", *processed_cloud);\n }\n\n \/\/ Remove planes\n std::vector<rail::DiscoveredPlanePtr> planes;\n rail::ExtractPlanes<pcl::PointXYZ>(processed_cloud, processed_cloud, planes);\n \n if(inDebugMode) {\n \/\/ Dump original w\/o planes\n std::cout << \"Writing input without large planes as 'input_minus_planes.pcd'\" << std::endl;\n writer.write(\"input_minus_planes.pcd\", *processed_cloud);\n \n \/\/ Dump planes\n unsigned int i = 0;\n for(std::vector<rail::DiscoveredPlanePtr>::iterator it = planes.begin(); it != planes.end(); ++it) {\n std::stringstream fileName;\n fileName << \"extracted_plane\" << i++ << \".pcd\";\n \n std::cout << \" Writing extracted plane to \" << fileName.str() << std::endl;\n writer.write(fileName.str(), (*(*it)).planeCloud);\n }\n }\n\n \/\/ Extract objects\n std::cout << \"Extracting objects...\" << std::endl;\n\n std::vector<pcl::PointCloud<pcl::PointXYZ>::Ptr> objects;\n rail::ExtractObjectClouds<pcl::PointXYZ>(processed_cloud, objects);\n\n std::cout << \" Extracted \" << objects.size() << \" objects.\" << std::endl;\n\n \/\/ Save results\n int i = 0;\n for (std::vector<pcl::PointCloud<pcl::PointXYZ>::Ptr>::iterator it = objects.begin(); it != objects.end(); ++it)\n {\n std::stringstream fileName;\n fileName << \"object_\" << i << \".pcd\";\n\n std::cout << \"Writing \" << fileName.str() << std::endl;\n\n writer.write(fileName.str(), *(*it));\n i++;\n }\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"remoting\/host\/capturer.h\"\n\nnamespace remoting {\n\nCapturer::Capturer()\n : width_(0),\n height_(0),\n pixel_format_(PixelFormatInvalid),\n bytes_per_pixel_(0),\n bytes_per_row_(0),\n current_buffer_(0) {\n}\n\nCapturer::~Capturer() {\n}\n\nvoid Capturer::GetDirtyRects(DirtyRects* rects) const {\n *rects = dirty_rects_;\n}\n\nint Capturer::GetWidth() const {\n return width_;\n}\n\nint Capturer::GetHeight() const {\n return height_;\n}\n\nPixelFormat Capturer::GetPixelFormat() const {\n return pixel_format_;\n}\n\nvoid Capturer::InvalidateRect(gfx::Rect dirty_rect) {\n inval_rects_.push_back(dirty_rect);\n}\n\nvoid Capturer::FinishCapture(Task* done_task) {\n done_task->Run();\n delete done_task;\n\n \/\/ Select the next buffer to be the current buffer.\n current_buffer_ = ++current_buffer_ % kNumBuffers;\n}\n\n} \/\/ namespace remoting\n<commit_msg>Coverity: Fix undefined assignment evaluation order in remoting::Capturer::FinishCapture.<commit_after>\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"remoting\/host\/capturer.h\"\n\nnamespace remoting {\n\nCapturer::Capturer()\n : width_(0),\n height_(0),\n pixel_format_(PixelFormatInvalid),\n bytes_per_pixel_(0),\n bytes_per_row_(0),\n current_buffer_(0) {\n}\n\nCapturer::~Capturer() {\n}\n\nvoid Capturer::GetDirtyRects(DirtyRects* rects) const {\n *rects = dirty_rects_;\n}\n\nint Capturer::GetWidth() const {\n return width_;\n}\n\nint Capturer::GetHeight() const {\n return height_;\n}\n\nPixelFormat Capturer::GetPixelFormat() const {\n return pixel_format_;\n}\n\nvoid Capturer::InvalidateRect(gfx::Rect dirty_rect) {\n inval_rects_.push_back(dirty_rect);\n}\n\nvoid Capturer::FinishCapture(Task* done_task) {\n done_task->Run();\n delete done_task;\n\n \/\/ Select the next buffer to be the current buffer.\n current_buffer_ = (current_buffer_ + 1) % kNumBuffers;\n}\n\n} \/\/ namespace remoting\n<|endoftext|>"} {"text":"<commit_before>\/\/ IVSHMEM-test.cpp : Defines the entry point for the console application.\n\/\/\n\n#include \"stdafx.h\"\n\n#define TEST_START(name) printf(\"Test: %s...\", name)\n#define TEST_PASS() printf(\"PASS\\n\")\n#define TEST_FAIL(reason) printf(\"FAIL - %s\\n\", reason)\n\nint main()\n{\n\tHDEVINFO deviceInfoSet;\n\tDWORD deviceIndex;\n\n\tPSP_DEVICE_INTERFACE_DETAIL_DATA infData = NULL;\n\tHANDLE devHandle = INVALID_HANDLE_VALUE;\n\n\tdeviceInfoSet = SetupDiGetClassDevs(NULL, NULL, NULL, DIGCF_PRESENT | DIGCF_ALLCLASSES | DIGCF_DEVICEINTERFACE);\n\tSP_DEVICE_INTERFACE_DATA deviceInterfaceData;\n\tZeroMemory(&deviceInterfaceData, sizeof(SP_DEVICE_INTERFACE_DATA));\n\tdeviceInterfaceData.cbSize = sizeof(SP_DEVICE_INTERFACE_DATA);\n\n\tdeviceIndex = 0;\n\twhile (1)\n\t{\n\t\tTEST_START(\"Find device\");\n\t\tif (SetupDiEnumDeviceInterfaces(deviceInfoSet, NULL, &GUID_DEVINTERFACE_IVSHMEM, 0, &deviceInterfaceData) == FALSE)\n\t\t{\n\t\t\tDWORD error = GetLastError();\n\t\t\tif (error == ERROR_NO_MORE_ITEMS)\n\t\t\t{\n\t\t\t\tTEST_FAIL(\"Unable to enumerate the device, is it attached?\");\n\t\t\t\tbreak;\n\t\t\t}\n\n\n\t\t\tTEST_FAIL(\"SetupDiEnumDeviceInterfaces failed\");\n\t\t\tbreak;\n\t\t}\n\t\tTEST_PASS();\n\n\t\tTEST_START(\"Get device name length\");\n\t\tDWORD reqSize = 0;\n\t\t\/\/ this returns false even though we succeed in getting the size\n\t\tSetupDiGetDeviceInterfaceDetail(deviceInfoSet, &deviceInterfaceData, NULL, 0, &reqSize, NULL);\n\t\tif (!reqSize)\n\t\t{\n\t\t\tTEST_FAIL(\"SetupDiGetDeviceInterfaceDetail\");\n\t\t\tbreak;\n\t\t}\n\t\tTEST_PASS();\n\n\t\tTEST_START(\"Get device name\");\n\t\tinfData = (PSP_DEVICE_INTERFACE_DETAIL_DATA)malloc(reqSize);\n\t\tinfData->cbSize = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA);\n\t\tif (!SetupDiGetDeviceInterfaceDetail(deviceInfoSet, &deviceInterfaceData, infData, reqSize, NULL, NULL))\n\t\t{\n\t\t\tTEST_FAIL(\"SetupDiGetDeviceInterfaceDetail\");\n\t\t\tbreak;\n\t\t}\n\t\tTEST_PASS();\n\n\t\tTEST_START(\"Open device\");\n\t\tdevHandle = CreateFile(infData->DevicePath, 0, 0, NULL, OPEN_EXISTING, 0, 0);\n\t\tif (devHandle == INVALID_HANDLE_VALUE)\n\t\t{\n\t\t\tTEST_FAIL(\"CreateFile returned INVALID_HANDLE_VALUE\");\n\t\t\tbreak;\n\t\t}\n\t\tTEST_PASS();\n\n\t\tTEST_START(\"IOCTL_IVSHMEM_REQUEST_PEERID\");\n\t\tIVSHMEM_PEERID peer = 0;\n\t\tULONG ulReturnedLength = 0;\n\n\t\tif (!DeviceIoControl(devHandle, IOCTL_IVSHMEM_REQUEST_PEERID, NULL, 0, &peer, sizeof(IVSHMEM_PEERID), &ulReturnedLength, NULL))\n\t\t{\n\t\t\tTEST_FAIL(\"DeviceIoControl\");\n\t\t\tprintf(\"Error 0x%x\\n\", GetLastError());\n\t\t\tbreak;\n\t\t}\n\t\tTEST_PASS();\n\n\t\tprintf(\"Peer: %u\\n\", peer);\n\n\t\tTEST_START(\"IOCTL_IVSHMEM_REQUEST_SIZE\");\n\t\tIVSHMEM_SIZE size = 0;\n\t\tif (!DeviceIoControl(devHandle, IOCTL_IVSHMEM_REQUEST_SIZE, NULL, 0, &size, sizeof(IVSHMEM_SIZE), &ulReturnedLength, NULL))\n\t\t{\n\t\t\tTEST_FAIL(\"DeviceIoControl\");\n\t\t\tbreak;\n\t\t}\n\n\t\tif (size == 0)\n\t\t{\n\t\t\tTEST_FAIL(\"Size should not be zero\");\n\t\t\tbreak;\n\t\t}\n\t\tTEST_PASS();\n\n\t\tprintf(\"Size: %I64u\\n\", size);\n\n\t\tTEST_START(\"IOCTL_IVSHMEM_REQUEST_MMAP\");\n\t\tIVSHMEM_MMAP_CONFIG conf;\n\t\tIVSHMEM_MMAP map;\n\n\t\tconf.cacheMode = IVSHMEM_CACHE_NONCACHED;\n\t\tZeroMemory(&map, sizeof(IVSHMEM_MMAP));\n\t\tif (!DeviceIoControl(devHandle, IOCTL_IVSHMEM_REQUEST_MMAP, &conf, sizeof(IVSHMEM_MMAP_CONFIG), &map, sizeof(IVSHMEM_MMAP), &ulReturnedLength, NULL))\n\t\t{\n\t\t\tTEST_FAIL(\"DeviceIoControl\");\n\t\t\tbreak;\n\t\t}\n\n\t\tif (!map.ptr)\n\t\t{\n\t\t\tTEST_FAIL(\"NULL pointer to mapping returned\");\n\t\t\tbreak;\n\t\t}\n\n\t\tif (map.size != size)\n\t\t{\n\t\t\tTEST_FAIL(\"Incorrect size\");\n\t\t\tbreak;\n\t\t}\n\t\tTEST_PASS();\n\n\t\tTEST_START(\"Mapping more then once fails\");\n\t\tif (DeviceIoControl(devHandle, IOCTL_IVSHMEM_REQUEST_MMAP, &conf, sizeof(IVSHMEM_MMAP_CONFIG), &map, sizeof(IVSHMEM_MMAP), &ulReturnedLength, NULL))\n\t\t{\n\t\t\tTEST_FAIL(\"mapping succeeded, this should not happen!\");\n\t\t\tbreak;\n\t\t}\n\t\tTEST_PASS();\n\n\t\tTEST_START(\"Mapping from another handle fails\");\n\t\tHANDLE devHandle2 = CreateFile(infData->DevicePath, 0, 0, NULL, OPEN_EXISTING, 0, 0);\n\t\tif (!devHandle2)\n\t\t{\n\t\t\tTEST_FAIL(\"Failed to open second handle\");\n\t\t\tbreak;\n\t\t}\n\t\tif (DeviceIoControl(devHandle, IOCTL_IVSHMEM_REQUEST_MMAP, &conf, sizeof(IVSHMEM_MMAP_CONFIG), &map, sizeof(IVSHMEM_MMAP), &ulReturnedLength, NULL))\n\t\t{\n\t\t\tTEST_FAIL(\"mapping succeeded, this should not happen!\");\n\t\t\tbreak;\n\t\t}\n\t\tCloseHandle(devHandle2);\n\t\tTEST_PASS();\n\n\t\tTEST_START(\"IOCTL_IVSHMEM_RING_DOORBELL\");\n\t\tIVSHMEM_RING ring;\n\t\tring.peerID = 0;\n\t\tring.vector = 0;\n\t\tif (!DeviceIoControl(devHandle, IOCTL_IVSHMEM_RING_DOORBELL, &ring, sizeof(IVSHMEM_RING), NULL, 0, &ulReturnedLength, NULL))\n\t\t{\n\t\t\tTEST_FAIL(\"DeviceIoControl\");\n\t\t\tbreak;\n\t\t}\n\t\tTEST_PASS();\n\n\t\tTEST_START(\"IOCTL_IVSHMEM_RELEASE_MMAP\");\n\t\tif (!DeviceIoControl(devHandle, IOCTL_IVSHMEM_RELEASE_MMAP, NULL, 0, NULL, 0, &ulReturnedLength, NULL))\n\t\t{\n\t\t\tTEST_FAIL(\"DeviceIoControl\");\n\t\t\tbreak;\n\t\t}\n\t\tTEST_PASS();\n\n\t\tTEST_START(\"Closing handle releases mapping\");\n\t\tCloseHandle(devHandle);\n\t\tdevHandle = CreateFile(infData->DevicePath, 0, 0, NULL, OPEN_EXISTING, 0, 0);\n\t\tif (devHandle == INVALID_HANDLE_VALUE)\n\t\t{\n\t\t\tTEST_FAIL(\"Failed to re-open handle\");\n\t\t\tbreak;\n\t\t}\n\t\tif (!DeviceIoControl(devHandle, IOCTL_IVSHMEM_REQUEST_MMAP, &conf, sizeof(IVSHMEM_MMAP_CONFIG), &map, sizeof(IVSHMEM_MMAP), &ulReturnedLength, NULL))\n\t\t{\n\t\t\tTEST_FAIL(\"Mapping failed!\");\n\t\t\tbreak;\n\t\t}\n\t\tTEST_PASS();\n\n\t\tTEST_START(\"Shared memory actually works\");\n\t\tmemset(map.ptr, 0xAA, (size_t)map.size);\n\t\tCloseHandle(devHandle);\n\t\tdevHandle = CreateFile(infData->DevicePath, 0, 0, NULL, OPEN_EXISTING, 0, 0);\n\t\tif (devHandle == INVALID_HANDLE_VALUE)\n\t\t{\n\t\t\tTEST_FAIL(\"Failed to re-open handle\");\n\t\t\tbreak;\n\t\t}\n\t\tif (!DeviceIoControl(devHandle, IOCTL_IVSHMEM_REQUEST_MMAP, &conf, sizeof(IVSHMEM_MMAP_CONFIG), &map, sizeof(IVSHMEM_MMAP), &ulReturnedLength, NULL))\n\t\t{\n\t\t\tTEST_FAIL(\"Mapping failed!\");\n\t\t\tbreak;\n\t\t}\n\n\t\tbool fail = false;\n\t\tunsigned char *data = (unsigned char *)map.ptr;\n\t\tfor (UINT64 i = 0; i < map.size; ++i)\n\t\t\tif (data[i] != 0xAA)\n\t\t\t{\n\t\t\t\tTEST_FAIL(\"Invalid data read back\");\n\t\t\t\tfail = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\tif (fail)\n\t\t\tbreak;\n\t\tTEST_PASS();\n\n\t\tif (map.vectors > 0)\n\t\t{\n\t\t\tTEST_START(\"Check events work, send interrupt 0 to this peer\");\n\t\t\tIVSHMEM_EVENT event;\n\t\t\tevent.event = CreateEvent(NULL, TRUE, FALSE, L\"TEST_EVENT\");\n\t\t\tevent.vector = 0;\n\t\t\tevent.singleShot = TRUE;\n\t\t\tif (event.event == INVALID_HANDLE_VALUE)\n\t\t\t{\n\t\t\t\tTEST_FAIL(\"Failed to create the event\");\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tif (!DeviceIoControl(devHandle, IOCTL_IVSHMEM_REGISTER_EVENT, &event, sizeof(IVSHMEM_EVENT), NULL, 0, &ulReturnedLength, NULL))\n\t\t\t{\n\t\t\t\tTEST_FAIL(\"Register event failed!\");\n\t\t\t\tCloseHandle(event.event);\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tif (WaitForSingleObject(event.event, INFINITE) != WAIT_OBJECT_0)\n\t\t\t{\n\t\t\t\tTEST_FAIL(\"WaitForSingleObject failed!\");\n\t\t\t\tCloseHandle(event.event);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tCloseHandle(event.event);\n\t\t\tTEST_PASS();\n\t\t}\n\n\t\tbreak;\n\t}\n\n\tif (devHandle != INVALID_HANDLE_VALUE)\n\t\tCloseHandle(devHandle);\n\n\tif (infData)\n\t\tfree(infData);\n\n\tSetupDiDestroyDeviceInfoList(deviceInfoSet);\n\n return 0;\n}\n<commit_msg>[ivshmem] ut: cosmetics<commit_after>\/\/ IVSHMEM-test.cpp : Defines the entry point for the console application.\n\/\/\n\n#include \"stdafx.h\"\n\n#define TEST_START(name) printf(\"Test: %s...\", name)\n#define TEST_PASS() printf(\"PASS\\n\")\n#define TEST_FAIL(reason) printf(\"FAIL - %s\\n\", reason)\n\nint main()\n{\n HDEVINFO deviceInfoSet;\n DWORD deviceIndex;\n\n PSP_DEVICE_INTERFACE_DETAIL_DATA infData = NULL;\n HANDLE devHandle = INVALID_HANDLE_VALUE;\n\n deviceInfoSet = SetupDiGetClassDevs(NULL, NULL, NULL, DIGCF_PRESENT | DIGCF_ALLCLASSES | DIGCF_DEVICEINTERFACE);\n SP_DEVICE_INTERFACE_DATA deviceInterfaceData;\n ZeroMemory(&deviceInterfaceData, sizeof(SP_DEVICE_INTERFACE_DATA));\n deviceInterfaceData.cbSize = sizeof(SP_DEVICE_INTERFACE_DATA);\n\n deviceIndex = 0;\n while (1)\n {\n TEST_START(\"Find device\");\n if (SetupDiEnumDeviceInterfaces(deviceInfoSet, NULL, &GUID_DEVINTERFACE_IVSHMEM, 0, &deviceInterfaceData) == FALSE)\n {\n DWORD error = GetLastError();\n if (error == ERROR_NO_MORE_ITEMS)\n {\n TEST_FAIL(\"Unable to enumerate the device, is it attached?\");\n break;\n }\n\n\n TEST_FAIL(\"SetupDiEnumDeviceInterfaces failed\");\n break;\n }\n TEST_PASS();\n\n TEST_START(\"Get device name length\");\n DWORD reqSize = 0;\n \/\/ this returns false even though we succeed in getting the size\n SetupDiGetDeviceInterfaceDetail(deviceInfoSet, &deviceInterfaceData, NULL, 0, &reqSize, NULL);\n if (!reqSize)\n {\n TEST_FAIL(\"SetupDiGetDeviceInterfaceDetail\");\n break;\n }\n TEST_PASS();\n\n TEST_START(\"Get device name\");\n infData = (PSP_DEVICE_INTERFACE_DETAIL_DATA)malloc(reqSize);\n infData->cbSize = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA);\n if (!SetupDiGetDeviceInterfaceDetail(deviceInfoSet, &deviceInterfaceData, infData, reqSize, NULL, NULL))\n {\n TEST_FAIL(\"SetupDiGetDeviceInterfaceDetail\");\n break;\n }\n TEST_PASS();\n\n TEST_START(\"Open device\");\n devHandle = CreateFile(infData->DevicePath, 0, 0, NULL, OPEN_EXISTING, 0, 0);\n if (devHandle == INVALID_HANDLE_VALUE)\n {\n TEST_FAIL(\"CreateFile returned INVALID_HANDLE_VALUE\");\n break;\n }\n TEST_PASS();\n\n TEST_START(\"IOCTL_IVSHMEM_REQUEST_PEERID\");\n IVSHMEM_PEERID peer = 0;\n ULONG ulReturnedLength = 0;\n\n if (!DeviceIoControl(devHandle, IOCTL_IVSHMEM_REQUEST_PEERID, NULL, 0, &peer, sizeof(IVSHMEM_PEERID), &ulReturnedLength, NULL))\n {\n TEST_FAIL(\"DeviceIoControl\");\n printf(\"Error 0x%x\\n\", GetLastError());\n break;\n }\n TEST_PASS();\n\n printf(\"Peer: %u\\n\", peer);\n\n TEST_START(\"IOCTL_IVSHMEM_REQUEST_SIZE\");\n IVSHMEM_SIZE size = 0;\n if (!DeviceIoControl(devHandle, IOCTL_IVSHMEM_REQUEST_SIZE, NULL, 0, &size, sizeof(IVSHMEM_SIZE), &ulReturnedLength, NULL))\n {\n TEST_FAIL(\"DeviceIoControl\");\n break;\n }\n\n if (size == 0)\n {\n TEST_FAIL(\"Size should not be zero\");\n break;\n }\n TEST_PASS();\n\n printf(\"Size: %I64u\\n\", size);\n\n TEST_START(\"IOCTL_IVSHMEM_REQUEST_MMAP\");\n IVSHMEM_MMAP_CONFIG conf;\n IVSHMEM_MMAP map;\n\n conf.cacheMode = IVSHMEM_CACHE_NONCACHED;\n ZeroMemory(&map, sizeof(IVSHMEM_MMAP));\n if (!DeviceIoControl(devHandle, IOCTL_IVSHMEM_REQUEST_MMAP, &conf, sizeof(IVSHMEM_MMAP_CONFIG), &map, sizeof(IVSHMEM_MMAP), &ulReturnedLength, NULL))\n {\n TEST_FAIL(\"DeviceIoControl\");\n break;\n }\n\n if (!map.ptr)\n {\n TEST_FAIL(\"NULL pointer to mapping returned\");\n break;\n }\n\n if (map.size != size)\n {\n TEST_FAIL(\"Incorrect size\");\n break;\n }\n TEST_PASS();\n\n TEST_START(\"Mapping more then once fails\");\n if (DeviceIoControl(devHandle, IOCTL_IVSHMEM_REQUEST_MMAP, &conf, sizeof(IVSHMEM_MMAP_CONFIG), &map, sizeof(IVSHMEM_MMAP), &ulReturnedLength, NULL))\n {\n TEST_FAIL(\"mapping succeeded, this should not happen!\");\n break;\n }\n TEST_PASS();\n\n TEST_START(\"Mapping from another handle fails\");\n HANDLE devHandle2 = CreateFile(infData->DevicePath, 0, 0, NULL, OPEN_EXISTING, 0, 0);\n if (!devHandle2)\n {\n TEST_FAIL(\"Failed to open second handle\");\n break;\n }\n if (DeviceIoControl(devHandle, IOCTL_IVSHMEM_REQUEST_MMAP, &conf, sizeof(IVSHMEM_MMAP_CONFIG), &map, sizeof(IVSHMEM_MMAP), &ulReturnedLength, NULL))\n {\n TEST_FAIL(\"mapping succeeded, this should not happen!\");\n break;\n }\n CloseHandle(devHandle2);\n TEST_PASS();\n\n TEST_START(\"IOCTL_IVSHMEM_RING_DOORBELL\");\n IVSHMEM_RING ring;\n ring.peerID = 0;\n ring.vector = 0;\n if (!DeviceIoControl(devHandle, IOCTL_IVSHMEM_RING_DOORBELL, &ring, sizeof(IVSHMEM_RING), NULL, 0, &ulReturnedLength, NULL))\n {\n TEST_FAIL(\"DeviceIoControl\");\n break;\n }\n TEST_PASS();\n\n TEST_START(\"IOCTL_IVSHMEM_RELEASE_MMAP\");\n if (!DeviceIoControl(devHandle, IOCTL_IVSHMEM_RELEASE_MMAP, NULL, 0, NULL, 0, &ulReturnedLength, NULL))\n {\n TEST_FAIL(\"DeviceIoControl\");\n break;\n }\n TEST_PASS();\n\n TEST_START(\"Closing handle releases mapping\");\n CloseHandle(devHandle);\n devHandle = CreateFile(infData->DevicePath, 0, 0, NULL, OPEN_EXISTING, 0, 0);\n if (devHandle == INVALID_HANDLE_VALUE)\n {\n TEST_FAIL(\"Failed to re-open handle\");\n break;\n }\n if (!DeviceIoControl(devHandle, IOCTL_IVSHMEM_REQUEST_MMAP, &conf, sizeof(IVSHMEM_MMAP_CONFIG), &map, sizeof(IVSHMEM_MMAP), &ulReturnedLength, NULL))\n {\n TEST_FAIL(\"Mapping failed!\");\n break;\n }\n TEST_PASS();\n\n TEST_START(\"Shared memory actually works\");\n memset(map.ptr, 0xAA, (size_t)map.size);\n CloseHandle(devHandle);\n devHandle = CreateFile(infData->DevicePath, 0, 0, NULL, OPEN_EXISTING, 0, 0);\n if (devHandle == INVALID_HANDLE_VALUE)\n {\n TEST_FAIL(\"Failed to re-open handle\");\n break;\n }\n if (!DeviceIoControl(devHandle, IOCTL_IVSHMEM_REQUEST_MMAP, &conf, sizeof(IVSHMEM_MMAP_CONFIG), &map, sizeof(IVSHMEM_MMAP), &ulReturnedLength, NULL))\n {\n TEST_FAIL(\"Mapping failed!\");\n break;\n }\n\n bool fail = false;\n unsigned char *data = (unsigned char *)map.ptr;\n for (UINT64 i = 0; i < map.size; ++i)\n if (data[i] != 0xAA)\n {\n TEST_FAIL(\"Invalid data read back\");\n fail = true;\n break;\n }\n if (fail)\n break;\n TEST_PASS();\n\n if (map.vectors > 0)\n {\n TEST_START(\"Check events work, send interrupt 0 to this peer\");\n IVSHMEM_EVENT event;\n event.event = CreateEvent(NULL, TRUE, FALSE, L\"TEST_EVENT\");\n event.vector = 0;\n event.singleShot = TRUE;\n if (event.event == INVALID_HANDLE_VALUE)\n {\n TEST_FAIL(\"Failed to create the event\");\n break;\n }\n if (!DeviceIoControl(devHandle, IOCTL_IVSHMEM_REGISTER_EVENT, &event, sizeof(IVSHMEM_EVENT), NULL, 0, &ulReturnedLength, NULL))\n {\n TEST_FAIL(\"Register event failed!\");\n CloseHandle(event.event);\n break;\n }\n\n if (WaitForSingleObject(event.event, INFINITE) != WAIT_OBJECT_0)\n {\n TEST_FAIL(\"WaitForSingleObject failed!\");\n CloseHandle(event.event);\n break;\n }\n CloseHandle(event.event);\n TEST_PASS();\n }\n\n break;\n }\n\n if (devHandle != INVALID_HANDLE_VALUE)\n CloseHandle(devHandle);\n\n if (infData)\n free(infData);\n\n SetupDiDestroyDeviceInfoList(deviceInfoSet);\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>#ifndef AL_ISCLIENT_H\n#define AL_ISCLIENT_H\n\n#include \"allocore\/al_Allocore.hpp\"\n#include \"allocore\/protocol\/al_OSC.hpp\"\n\nnamespace al {\n\nclass InterfaceServerClient : public osc::PacketHandler {\n public:\n InterfaceServerClient(const char* serverAddress = \"127.0.0.1\", int port = 12001,\n int serverPort = 12000);\n\n virtual ~InterfaceServerClient();\n\n \/\/ application specific name and config\n virtual const char* name();\n virtual const char* interfaceServerConfig();\n\n \/\/ common config used for all interface server apps\n const char* defaultConfig();\n\n virtual void onMessage(osc::Message& m);\n\n void connect();\n void disconnect();\n\n osc::Recv& oscRecv() { return mOSCRecv; }\n osc::Send& oscSend() { return mOSCSend; }\n\n \/\/ default nav and lens, be sure to set these\n \/\/ if using a different nav \/ lens\n \/\/ Lens& lens() { return *mLens; }\n void setLens(Lens& l){ mLens=&l; }\n\n \/\/ Nav& nav() { return *mNav; }\n void setNav(Nav& n){ mNav=&n; }\n\n protected:\n osc::Recv mOSCRecv;\n osc::Send mOSCSend;\n Lens* mLens;\n Nav* mNav;\n double mNavSpeed, mNavTurnSpeed;\n\n};\n\ninline void InterfaceServerClient::onMessage(osc::Message& m) {\n std::cout << \"Received: \" << m.addressPattern() << std::endl;\n\n float x;\n if (m.addressPattern() == \"\/pose\") {\n Pose pose;\n m >> pose.pos().x;\n m >> pose.pos().y;\n m >> pose.pos().z;\n m >> pose.quat().x;\n m >> pose.quat().y;\n m >> pose.quat().z;\n m >> pose.quat().w;\n (*mNav).set(pose);\n } else if (m.addressPattern() == \"\/mx\") {\n m >> x;\n (*mNav).moveR(x * mNavSpeed);\n } else if (m.addressPattern() == \"\/my\") {\n m >> x;\n (*mNav).moveU(x * mNavSpeed);\n } else if (m.addressPattern() == \"\/mz\") {\n m >> x;\n (*mNav).moveF(x * -mNavSpeed);\n } else if (m.addressPattern() == \"\/tx\") {\n m >> x;\n (*mNav).spinR(x * -mNavTurnSpeed);\n } else if (m.addressPattern() == \"\/ty\") {\n m >> x;\n (*mNav).spinU(x * -mNavTurnSpeed);\n } else if (m.addressPattern() == \"\/tz\") {\n m >> x;\n (*mNav).spinF(x * -mNavTurnSpeed);\n } else if (m.addressPattern() == \"\/home\") {\n (*mNav).home();\n } else if (m.addressPattern() == \"\/halt\") {\n (*mNav).halt();\n } else if (m.addressPattern() == \"\/eyeSep\") {\n m >> x;\n (*mLens).eyeSep(x);\n } else if (m.addressPattern() == \"\/near\") {\n m >> x;\n (*mLens).near(x);\n } else if (m.addressPattern() == \"\/far\") {\n m >> x;\n (*mLens).far(x);\n } else if (m.addressPattern() == \"\/focalLength\") {\n m >> x;\n (*mLens).focalLength(x);\n } else {\n }\n (*mNav).print();\n}\n\nInterfaceServerClient::InterfaceServerClient(const char* deviceServerAddress, int port,\n int deviceServerPort)\n : mOSCRecv(port),\n mOSCSend(deviceServerPort, deviceServerAddress, 0, 4096) {\n\n oscRecv().bufferSize(32000);\n oscRecv().handler(*this);\n\n mNavSpeed = 0.1;\n mNavTurnSpeed = 0.02;\n mNav = new Nav();\n mLens = new Lens();\n (*mNav).smooth(0.8);\n (*mLens).near(0.1);\n (*mLens).far(100);\n (*mLens).focalLength(6.0);\n \/\/ (*mLens).eyeSep(0.03);\n (*mLens).eyeSepAuto();\n}\n\ninline InterfaceServerClient::~InterfaceServerClient() {\n disconnect();\n}\n\ninline void InterfaceServerClient::connect() {\n if (oscSend().opened()){\n oscSend().send(\"\/interface\/applicationManager\/createApplicationWithText\",\n defaultConfig());\n oscSend().send(\"\/interface\/applicationManager\/createApplicationWithText\",\n interfaceServerConfig());\n }\n}\n\ninline void InterfaceServerClient::disconnect() {\n oscSend().send(\"\/interface\/disconnectApplication\", \"default\");\n oscSend().send(\"\/interface\/disconnectApplication\", name());\n}\n\ninline const char* InterfaceServerClient::name() { return \"app\"; }\n\ninline const char* InterfaceServerClient::interfaceServerConfig() {\n return R\"(\n app = {\n name : 'app',\n transports :[ {type : 'osc', port : 12001}, ],\n inputs: {\n test: {min: 0, max: 1},\n },\n mappings: [\n { input: { io:'keyboard', name:' ' }, output:{ io:'app', name:'test' } },\n ]\n }\n )\";\n}\n\ninline const char* InterfaceServerClient::defaultConfig() {\n return R\"(\n var eye=0.2;\n var dd = function(v){\n if(Math.abs(v) < 0.03) return 0.0;\n else return v;\n }\n app = {\n name : 'default',\n transports :[ {type : 'osc', port : 12001}, ],\n inputs: {\n mx: {min: -1, max: 1, },\n my: {min: -1, max: 1, },\n mz: {min: -1, max: 1, },\n tx: {min: -1, max: 1, },\n ty: {min: -1, max: 1, },\n tz: {min: -1, max: 1, },\n home: {min: 0, max: 1, },\n halt: {min: 0, max: 1, },\n eyeSep: {min: 0, max:1 },\n near: {min: 0, max:1 },\n far: {min: 0, max:1 },\n focalLength: {min: 0, max:1 },\n },\n mappings: [\n { input: { io:'keyboard', name:'q' }, output:{ io:'default', name:'home'}, expression:function(v){console.log(v)} },\n { input: { io:'keyboard', name:'w' }, output:{ io:'default', name:'mz'}, },\n { input: { io:'keyboard', name:'a' }, output:{ io:'default', name:'mx'}, expression:function(v){return -v;} },\n { input: { io:'keyboard', name:'s' }, output:{ io:'default', name:'halt'}, },\n { input: { io:'keyboard', name:'x' }, output:{ io:'default', name:'mz'}, expression:function(v){return -v;} },\n { input: { io:'keyboard', name:'d' }, output:{ io:'default', name:'mx'}, },\n { input: { io:'keyboard', name:'i' }, output:{ io:'default', name:'eyeSep'}, expression:function(v){ eye += 0.01; console.log('eyesep: ',eye); return eye; } },\n { input: { io:'keyboard', name:'k' }, output:{ io:'default', name:'eyeSep'}, expression:function(v){ eye -= 0.01; console.log('eyesep: ',eye); return eye; } },\n\n { input: { io:'Logitech RumblePad 2 USB #1', name:'leftX' }, output:{ io:'default', name:'mx'}, expression:dd },\n { input: { io:'Logitech RumblePad 2 USB #1', name:'leftY' }, output:{ io:'default', name:'mz'}, expression:dd },\n { input: { io:'Logitech RumblePad 2 USB #1', name:'rightX' }, output:{ io:'default', name:'ty'}, expression:dd },\n { input: { io:'Logitech RumblePad 2 USB #1', name:'rightY' }, output:{ io:'default', name:'tx'}, expression:dd },\n\n { input: { io:'Logitech Cordless RumblePad 2 #1', name:'leftX' }, output:{ io:'default', name:'mx' }, expression:dd },\n { input: { io:'Logitech Cordless RumblePad 2 #1', name:'leftY' }, output:{ io:'default', name:'mz' }, expression:dd },\n { input: { io:'Logitech Cordless RumblePad 2 #1', name:'rightX' }, output:{ io:'default', name:'ty' }, expression:dd },\n { input: { io:'Logitech Cordless RumblePad 2 #1', name:'rightY' }, output:{ io:'default', name:'tx' }, expression:dd },\n ]\n }\n )\";\n}\n\n} \/\/ al::\n\n#endif\n<commit_msg>add handshake to interfaceserverclient<commit_after>#ifndef AL_ISCLIENT_H\n#define AL_ISCLIENT_H\n\n#include \"allocore\/al_Allocore.hpp\"\n#include \"allocore\/protocol\/al_OSC.hpp\"\n\nnamespace al {\n\nclass InterfaceServerClient : public osc::PacketHandler {\n public:\n InterfaceServerClient(const char* serverAddress = \"127.0.0.1\", int port = 12001,\n int serverPort = 12000);\n\n virtual ~InterfaceServerClient();\n\n \/\/ application specific name and config\n virtual const char* name();\n virtual const char* interfaceServerConfig();\n\n \/\/ common config used for all interface server apps\n const char* defaultConfig();\n\n virtual void onMessage(osc::Message& m);\n\n void connect();\n void handshake();\n void disconnect();\n\n osc::Recv& oscRecv() { return mOSCRecv; }\n osc::Send& oscSend() { return mOSCSend; }\n\n \/\/ default nav and lens, be sure to set these\n \/\/ if using a different nav \/ lens\n \/\/ Lens& lens() { return *mLens; }\n void setLens(Lens& l){ mLens=&l; }\n\n \/\/ Nav& nav() { return *mNav; }\n void setNav(Nav& n){ mNav=&n; }\n\n protected:\n osc::Recv mOSCRecv;\n osc::Send mOSCSend;\n Lens* mLens;\n Nav* mNav;\n double mNavSpeed, mNavTurnSpeed;\n\n};\n\ninline void InterfaceServerClient::onMessage(osc::Message& m) {\n std::cout << \"Received: \" << m.addressPattern() << std::endl;\n\n float x;\n if (m.addressPattern() == \"\/pose\") {\n Pose pose;\n m >> pose.pos().x;\n m >> pose.pos().y;\n m >> pose.pos().z;\n m >> pose.quat().x;\n m >> pose.quat().y;\n m >> pose.quat().z;\n m >> pose.quat().w;\n (*mNav).set(pose);\n } else if (m.addressPattern() == \"\/mx\") {\n m >> x;\n (*mNav).moveR(x * mNavSpeed);\n } else if (m.addressPattern() == \"\/my\") {\n m >> x;\n (*mNav).moveU(x * mNavSpeed);\n } else if (m.addressPattern() == \"\/mz\") {\n m >> x;\n (*mNav).moveF(x * -mNavSpeed);\n } else if (m.addressPattern() == \"\/tx\") {\n m >> x;\n (*mNav).spinR(x * -mNavTurnSpeed);\n } else if (m.addressPattern() == \"\/ty\") {\n m >> x;\n (*mNav).spinU(x * -mNavTurnSpeed);\n } else if (m.addressPattern() == \"\/tz\") {\n m >> x;\n (*mNav).spinF(x * -mNavTurnSpeed);\n } else if (m.addressPattern() == \"\/home\") {\n (*mNav).home();\n } else if (m.addressPattern() == \"\/halt\") {\n (*mNav).halt();\n } else if (m.addressPattern() == \"\/eyeSep\") {\n m >> x;\n (*mLens).eyeSep(x);\n } else if (m.addressPattern() == \"\/near\") {\n m >> x;\n (*mLens).near(x);\n } else if (m.addressPattern() == \"\/far\") {\n m >> x;\n (*mLens).far(x);\n } else if (m.addressPattern() == \"\/focalLength\") {\n m >> x;\n (*mLens).focalLength(x);\n } else {\n }\n (*mNav).print();\n}\n\nInterfaceServerClient::InterfaceServerClient(const char* deviceServerAddress, int port,\n int deviceServerPort)\n : mOSCRecv(port),\n mOSCSend(deviceServerPort, deviceServerAddress, 0, 4096) {\n\n oscRecv().bufferSize(32000);\n oscRecv().handler(*this);\n\n mNavSpeed = 0.1;\n mNavTurnSpeed = 0.02;\n mNav = new Nav();\n mLens = new Lens();\n (*mNav).smooth(0.8);\n (*mLens).near(0.1);\n (*mLens).far(100);\n (*mLens).focalLength(6.0);\n \/\/ (*mLens).eyeSep(0.03);\n (*mLens).eyeSepAuto();\n}\n\ninline InterfaceServerClient::~InterfaceServerClient() {\n disconnect();\n}\n\ninline void InterfaceServerClient::connect() {\n if (oscSend().opened()){\n oscSend().send(\"\/interface\/applicationManager\/createApplicationWithText\",\n defaultConfig());\n oscSend().send(\"\/interface\/applicationManager\/createApplicationWithText\",\n interfaceServerConfig());\n }\n}\n\ninline void InterfaceServerClient::handshake() {\n if (oscSend().opened()){\n oscSend().send(\"\/interface\/handshake\",\n name());\n }\n}\n\ninline void InterfaceServerClient::disconnect() {\n oscSend().send(\"\/interface\/disconnectApplication\", \"default\");\n oscSend().send(\"\/interface\/disconnectApplication\", name());\n}\n\ninline const char* InterfaceServerClient::name() { return \"app\"; }\n\ninline const char* InterfaceServerClient::interfaceServerConfig() {\n return R\"(\n app = {\n name : 'app',\n transports :[ {type : 'osc', port : 12001}, ],\n inputs: {\n test: {min: 0, max: 1},\n },\n mappings: [\n { input: { io:'keyboard', name:' ' }, output:{ io:'app', name:'test' } },\n ]\n }\n )\";\n}\n\ninline const char* InterfaceServerClient::defaultConfig() {\n return R\"(\n var eye=0.2;\n var dd = function(v){\n if(Math.abs(v) < 0.03) return 0.0;\n else return v;\n }\n app = {\n name : 'default',\n transports :[ {type : 'osc', port : 12001}, ],\n inputs: {\n mx: {min: -1, max: 1, },\n my: {min: -1, max: 1, },\n mz: {min: -1, max: 1, },\n tx: {min: -1, max: 1, },\n ty: {min: -1, max: 1, },\n tz: {min: -1, max: 1, },\n home: {min: 0, max: 1, },\n halt: {min: 0, max: 1, },\n eyeSep: {min: 0, max:1 },\n near: {min: 0, max:1 },\n far: {min: 0, max:1 },\n focalLength: {min: 0, max:1 },\n },\n mappings: [\n { input: { io:'keyboard', name:'q' }, output:{ io:'default', name:'home'}, expression:function(v){console.log(v)} },\n { input: { io:'keyboard', name:'w' }, output:{ io:'default', name:'mz'}, },\n { input: { io:'keyboard', name:'a' }, output:{ io:'default', name:'mx'}, expression:function(v){return -v;} },\n { input: { io:'keyboard', name:'s' }, output:{ io:'default', name:'halt'}, },\n { input: { io:'keyboard', name:'x' }, output:{ io:'default', name:'mz'}, expression:function(v){return -v;} },\n { input: { io:'keyboard', name:'d' }, output:{ io:'default', name:'mx'}, },\n { input: { io:'keyboard', name:'i' }, output:{ io:'default', name:'eyeSep'}, expression:function(v){ eye += 0.01; console.log('eyesep: ',eye); return eye; } },\n { input: { io:'keyboard', name:'k' }, output:{ io:'default', name:'eyeSep'}, expression:function(v){ eye -= 0.01; console.log('eyesep: ',eye); return eye; } },\n\n { input: { io:'Logitech RumblePad 2 USB #1', name:'leftX' }, output:{ io:'default', name:'mx'}, expression:dd },\n { input: { io:'Logitech RumblePad 2 USB #1', name:'leftY' }, output:{ io:'default', name:'mz'}, expression:dd },\n { input: { io:'Logitech RumblePad 2 USB #1', name:'rightX' }, output:{ io:'default', name:'ty'}, expression:dd },\n { input: { io:'Logitech RumblePad 2 USB #1', name:'rightY' }, output:{ io:'default', name:'tx'}, expression:dd },\n\n { input: { io:'Logitech Cordless RumblePad 2 #1', name:'leftX' }, output:{ io:'default', name:'mx' }, expression:dd },\n { input: { io:'Logitech Cordless RumblePad 2 #1', name:'leftY' }, output:{ io:'default', name:'mz' }, expression:dd },\n { input: { io:'Logitech Cordless RumblePad 2 #1', name:'rightX' }, output:{ io:'default', name:'ty' }, expression:dd },\n { input: { io:'Logitech Cordless RumblePad 2 #1', name:'rightY' }, output:{ io:'default', name:'tx' }, expression:dd },\n ]\n }\n )\";\n}\n\n} \/\/ al::\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/*=========================================================================\n\n Program: Insight Segmentation & Registration Toolkit\n Module: itkAzimuthElevationToCartesianTransformTest.cxx\n Language: C++\n Date: $Date$\n Version: $Revision$\n\nCopyright (c) 2001 Insight Consortium\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n * Redistributions of source code must retain the above copyright notice,\n this list of conditions and the following disclaimer.\n\n * Redistributions in binary form must reproduce the above copyright notice,\n this list of conditions and the following disclaimer in the documentation\n and\/or other materials provided with the distribution.\n\n * The name of the Insight Consortium, nor the names of any consortium members,\n nor of any contributors, may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\n * Modified source versions must be plainly marked as such, and must not be\n misrepresented as being the original software.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS ``AS IS''\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE FOR\nANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\nDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\nSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\nCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\nOR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n=========================================================================*\/\n\n#include <iostream>\n\n#include \"itkAzimuthElevationToCartesianTransform.h\"\n\ntypedef itk::Point<double,3> PointType;\n\n\n\nvoid PrintPoint( const PointType & p )\n{\n for( unsigned int i=0; i<PointType::PointDimension; i++)\n {\n std::cout << p[i] << \", \";\n }\n std::cout << std::endl;\n}\n\nint main(\n int argc,\n char *argv[])\n{\n\n const double ACCEPTABLE_ERROR = 1E-10;\n\n typedef itk::AzimuthElevationToCartesianTransform<> AzimuthElevationToCartesianTransformType;\n\n AzimuthElevationToCartesianTransformType::Pointer transform = AzimuthElevationToCartesianTransformType::New();\n transform->SetAzimuthElevationToCartesianParameters(1.0,5.0,45.0,45.0);\n PointType p;\n p[0] = 3;\n p[1] = 3;\n p[2] = 25;\n\n std::cout<< \"original values of (theta,phi,r) p = \"<<std::endl;\n PrintPoint(p);\n\n transform->SetForwardAzimuthElevationToCartesian();\n\n PointType answer = transform->TransformPoint(p);\n PrintPoint(answer);\n\n PointType answerBackwards = transform->BackTransformPoint(answer);\n PrintPoint(answerBackwards);\n\n transform->SetForwardCartesianToAzimuthElevation();\n PointType reverseDirectionAnswer = transform->BackTransformPoint(answerBackwards);\n PrintPoint(reverseDirectionAnswer);\n\n PointType reverseDirectionAnswerBackwards = transform->TransformPoint(reverseDirectionAnswer);\n PrintPoint(reverseDirectionAnswerBackwards);\n transform->Print(std::cout);\n\n bool same=true;\n for (unsigned int i=0; i < p.PointDimension && same; i++)\n { \n same = ((abs(p[i] - answerBackwards[i]) < ACCEPTABLE_ERROR) && \n (abs(p[i] - reverseDirectionAnswerBackwards[i]) < ACCEPTABLE_ERROR) && \n (abs(answer[i] - reverseDirectionAnswer[i]) < ACCEPTABLE_ERROR)) ;\n }\n if (!same) \n {\n std::cout << \"itkAzimuthElevationToCartesianTransformTest failed\" <<std::endl;\n return EXIT_FAILURE;\n }\n std::cout << \"itkAzimuthElevationToCartesianTransformTest passed\" <<std::endl;\n return EXIT_SUCCESS;\n}\n<commit_msg>ERR: warnings.<commit_after>\/*=========================================================================\n\n Program: Insight Segmentation & Registration Toolkit\n Module: itkAzimuthElevationToCartesianTransformTest.cxx\n Language: C++\n Date: $Date$\n Version: $Revision$\n\nCopyright (c) 2001 Insight Consortium\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n * Redistributions of source code must retain the above copyright notice,\n this list of conditions and the following disclaimer.\n\n * Redistributions in binary form must reproduce the above copyright notice,\n this list of conditions and the following disclaimer in the documentation\n and\/or other materials provided with the distribution.\n\n * The name of the Insight Consortium, nor the names of any consortium members,\n nor of any contributors, may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\n * Modified source versions must be plainly marked as such, and must not be\n misrepresented as being the original software.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS ``AS IS''\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE FOR\nANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\nDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\nSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\nCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\nOR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n=========================================================================*\/\n\n#include <iostream>\n\n#include \"itkAzimuthElevationToCartesianTransform.h\"\n\ntypedef itk::Point<double,3> PointType;\n\n\n\nvoid PrintPoint( const PointType & p )\n{\n for( unsigned int i=0; i<PointType::PointDimension; i++)\n {\n std::cout << p[i] << \", \";\n }\n std::cout << std::endl;\n}\n\nint main(\n int argc,\n char *argv[])\n{\n\n const double ACCEPTABLE_ERROR = 1E-10;\n\n typedef itk::AzimuthElevationToCartesianTransform<> AzimuthElevationToCartesianTransformType;\n\n AzimuthElevationToCartesianTransformType::Pointer transform = AzimuthElevationToCartesianTransformType::New();\n transform->SetAzimuthElevationToCartesianParameters(1.0,5.0,45,45);\n PointType p;\n p[0] = 3;\n p[1] = 3;\n p[2] = 25;\n\n std::cout<< \"original values of (theta,phi,r) p = \"<<std::endl;\n PrintPoint(p);\n\n transform->SetForwardAzimuthElevationToCartesian();\n\n PointType answer = transform->TransformPoint(p);\n PrintPoint(answer);\n\n PointType answerBackwards = transform->BackTransformPoint(answer);\n PrintPoint(answerBackwards);\n\n transform->SetForwardCartesianToAzimuthElevation();\n PointType reverseDirectionAnswer = transform->BackTransformPoint(answerBackwards);\n PrintPoint(reverseDirectionAnswer);\n\n PointType reverseDirectionAnswerBackwards = transform->TransformPoint(reverseDirectionAnswer);\n PrintPoint(reverseDirectionAnswerBackwards);\n transform->Print(std::cout);\n\n bool same=true;\n for (unsigned int i=0; i < p.PointDimension && same; i++)\n { \n same = ((abs(p[i] - answerBackwards[i]) < ACCEPTABLE_ERROR) && \n (abs(p[i] - reverseDirectionAnswerBackwards[i]) < ACCEPTABLE_ERROR) && \n (abs(answer[i] - reverseDirectionAnswer[i]) < ACCEPTABLE_ERROR)) ;\n }\n if (!same) \n {\n std::cout << \"itkAzimuthElevationToCartesianTransformTest failed\" <<std::endl;\n return EXIT_FAILURE;\n }\n std::cout << \"itkAzimuthElevationToCartesianTransformTest passed\" <<std::endl;\n return EXIT_SUCCESS;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*=========================================================================\n\n Program: Insight Segmentation & Registration Toolkit\n Module: DeformableRegistration2.cxx\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n Copyright (c) Insight Software Consortium. All rights reserved.\n See ITKCopyright.txt or http:\/\/www.itk.org\/HTML\/Copyright.htm for details.\n\n This software is distributed WITHOUT ANY WARRANTY; without even \n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR \n PURPOSE. See the above copyright notices for more information.\n\n=========================================================================*\/\n\n#include \"itkImageFileReader.h\" \n#include \"itkImageFileWriter.h\" \n\n\n\/\/ Software Guide : BeginLatex\n\/\/\n\/\/ This example demostrates how to use the ``demons'' algorithm to deformably\n\/\/ register two images. The first step is to include the header files.\n\/\/\n\/\/ Software Guide : EndLatex\n\n\/\/ Software Guide : BeginCodeSnippet\n#include \"itkDemonsRegistrationFilter.h\"\n#include \"itkHistogramMatchingImageFilter.h\"\n#include \"itkCastImageFilter.h\"\n#include \"itkWarpImageFilter.h\"\n#include \"itkLinearInterpolateImageFunction.h\"\n\/\/ Software Guide : EndCodeSnippet\n\n\n\n\n\n\/\/ The following section of code implements a Command observer\n\/\/ that will monitor the evolution of the registration process.\n\/\/\n class CommandIterationUpdate : public itk::Command \n {\n public:\n typedef CommandIterationUpdate Self;\n typedef itk::Command Superclass;\n typedef itk::SmartPointer<CommandIterationUpdate> Pointer;\n itkNewMacro( CommandIterationUpdate );\n protected:\n CommandIterationUpdate() {};\n\n typedef itk::Image< float, 2 > InternalImageType;\n typedef itk::Vector< float, 2 > VectorPixelType;\n typedef itk::Image< VectorPixelType, 2 > DeformationFieldType;\n\n typedef itk::DemonsRegistrationFilter<\n InternalImageType,\n InternalImageType,\n DeformationFieldType> RegistrationFilterType;\n\n public:\n\n void Execute(itk::Object *caller, const itk::EventObject & event)\n {\n Execute( (const itk::Object *)caller, event);\n }\n\n void Execute(const itk::Object * object, const itk::EventObject & event)\n {\n const RegistrationFilterType * filter = \n dynamic_cast< const RegistrationFilterType * >( object );\n if( typeid( event ) != typeid( itk::IterationEvent ) )\n {\n return;\n }\n std::cout << filter->GetMetric() << std::endl;\n }\n };\n\n\n\n\n\n\nint main( int argc, char *argv[] )\n{\n if( argc < 4 )\n {\n std::cerr << \"Missing Parameters \" << std::endl;\n std::cerr << \"Usage: \" << argv[0];\n std::cerr << \" fixedImageFile movingImageFile \";\n std::cerr << \" outputImageFile \" << std::endl;\n std::cerr << \" [outputDeformationFieldFile] \" << std::endl;\n return 1;\n }\n\n \/\/ Software Guide : BeginLatex\n \/\/\n \/\/ Second, we declare the types of the images.\n \/\/\n \/\/ Software Guide : EndLatex\n\n \/\/ Software Guide : BeginCodeSnippet\n const unsigned int Dimension = 2;\n typedef unsigned short PixelType;\n\n typedef itk::Image< PixelType, Dimension > FixedImageType;\n typedef itk::Image< PixelType, Dimension > MovingImageType;\n \/\/ Software Guide : EndCodeSnippet\n\n \/\/ Set up the file readers\n typedef itk::ImageFileReader< FixedImageType > FixedImageReaderType;\n typedef itk::ImageFileReader< MovingImageType > MovingImageReaderType;\n\n FixedImageReaderType::Pointer fixedImageReader = FixedImageReaderType::New();\n MovingImageReaderType::Pointer movingImageReader = MovingImageReaderType::New();\n\n fixedImageReader->SetFileName( argv[1] );\n movingImageReader->SetFileName( argv[2] );\n\n\n \/\/ Software Guide : BeginLatex\n \/\/\n \/\/ Image file readers are set up in a similar fashion to previous examples.\n \/\/ To support the re-mapping of the moving image intensity, we declare an\n \/\/ internal image type with a floating point pixel type and cast the input\n \/\/ images to the internal image type.\n \/\/\n \/\/ Software Guide : EndLatex\n\n \/\/ Software Guide : BeginCodeSnippet\n typedef float InternalPixelType;\n typedef itk::Image< InternalPixelType, Dimension > InternalImageType;\n typedef itk::CastImageFilter< FixedImageType, \n InternalImageType > FixedImageCasterType;\n typedef itk::CastImageFilter< MovingImageType, \n InternalImageType > MovingImageCasterType;\n\n FixedImageCasterType::Pointer fixedImageCaster = FixedImageCasterType::New();\n MovingImageCasterType::Pointer movingImageCaster = MovingImageCasterType::New();\n\n fixedImageCaster->SetInput( fixedImageReader->GetOutput() );\n movingImageCaster->SetInput( movingImageReader->GetOutput() ); \n \/\/ Software Guide : EndCodeSnippet\n\n \/\/ Software Guide : BeginLatex\n \/\/\n \/\/ The demons algorithm relies on the assumption that pixels representing the\n \/\/ same homologous point on an object have the same intensity on both the\n \/\/ fixed and moving images to be registered. In this example, we will\n \/\/ preprocess the moving image to match the intensity between the images\n \/\/ using the \\doxygen{HistogramMatchingImageFilter}. \n \/\/\n \/\/ \\index{itk::HistogramMatchingImageFilter}\n \/\/\n \/\/ The basic idea is to match the histograms of the two images at a user-specified number of quantile values. For robustness, the histograms are\n \/\/ matched so that the background pixels are excluded from both histograms.\n \/\/ For MR images, a simple procedure is to exclude all gray values that are\n \/\/ smaller than the mean gray value of the image.\n \/\/\n \/\/ Software Guide : EndLatex\n\n \/\/ Software Guide : BeginCodeSnippet\n typedef itk::HistogramMatchingImageFilter<\n InternalImageType,\n InternalImageType > MatchingFilterType;\n MatchingFilterType::Pointer matcher = MatchingFilterType::New();\n \/\/ Software Guide : EndCodeSnippet\n\n\n \/\/ Software Guide : BeginLatex\n \/\/ \n \/\/ For this example, we set the moving image as the source or input image and\n \/\/ the fixed image as the reference image.\n \/\/\n \/\/ \\index{itk::HistogramMatchingImageFilter!SetInput()}\n \/\/ \\index{itk::HistogramMatchingImageFilter!SetSourceImage()}\n \/\/ \\index{itk::HistogramMatchingImageFilter!SetReferenceImage()}\n \/\/\n \/\/ Software Guide : EndLatex \n\n \/\/ Software Guide : BeginCodeSnippet \n matcher->SetInput( movingImageCaster->GetOutput() );\n matcher->SetReferenceImage( fixedImageCaster->GetOutput() );\n \/\/ Software Guide : EndCodeSnippet\n\n\n \/\/ Software Guide : BeginLatex\n \/\/\n \/\/ We then select the number of bins to represent the histograms and the\n \/\/ number of points or quantile values where the histogram is to be\n \/\/ matched.\n \/\/\n \/\/ \\index{itk::HistogramMatchingImageFilter!SetNumberOfHistogramLevels()}\n \/\/ \\index{itk::HistogramMatchingImageFilter!SetNumberOfMatchPoints()}\n \/\/\n \/\/ Software Guide : EndLatex\n\n \/\/ Software Guide : BeginCodeSnippet\n matcher->SetNumberOfHistogramLevels( 1024 );\n matcher->SetNumberOfMatchPoints( 7 );\n \/\/ Software Guide : EndCodeSnippet\n\n\n \/\/ Software Guide : BeginLatex\n \/\/\n \/\/ Simple background extraction is done by thresholding at the mean\n \/\/ intensity.\n \/\/\n \/\/ \\index{itk::HistogramMatchingImageFilter!ThresholdAtMeanIntensityOn()}\n \/\/\n \/\/ Software Guide : EndLatex\n\n \/\/ Software Guide : BeginCodeSnippet\n matcher->ThresholdAtMeanIntensityOn();\n \/\/ Software Guide : EndCodeSnippet\n\n\n \/\/ Software Guide : BeginLatex\n \/\/\n \/\/ In the \\doxygen{DemonsRegistrationFilter}, the deformation field is\n \/\/ represented as an image whose pixels are floating point vectors.\n \/\/\n \/\/ \\index{itk::DemonsRegistrationFilter}\n \/\/\n \/\/ Software Guide : EndLatex\n\n \/\/ Software Guide : BeginCodeSnippet\n typedef itk::Vector< float, Dimension > VectorPixelType;\n typedef itk::Image< VectorPixelType, Dimension > DeformationFieldType;\n typedef itk::DemonsRegistrationFilter<\n InternalImageType,\n InternalImageType,\n DeformationFieldType> RegistrationFilterType;\n RegistrationFilterType::Pointer filter = RegistrationFilterType::New();\n \/\/ Software Guide : EndCodeSnippet\n\n\n\n\n\n \/\/ Create the Command observer and register it with the registration filter.\n \/\/\n CommandIterationUpdate::Pointer observer = CommandIterationUpdate::New();\n filter->AddObserver( itk::IterationEvent(), observer );\n\n\n\n\n \/\/ Software Guide : BeginLatex\n \/\/\n \/\/ The input fixed image is simply the output of the fixed image casting\n \/\/ filter. The input moving image is the output of the histogram matching\n \/\/ filter.\n \/\/\n \/\/ \\index{itk::DemonsRegistrationFilter!SetFixedImage()}\n \/\/ \\index{itk::DemonsRegistrationFilter!SetMovingImage()}\n \/\/\n \/\/ Software Guide : EndLatex\n\n \/\/ Software Guide : BeginCodeSnippet\n filter->SetFixedImage( fixedImageCaster->GetOutput() );\n filter->SetMovingImage( matcher->GetOutput() );\n \/\/ Software Guide : EndCodeSnippet\n\n\n \/\/ Software Guide : BeginLatex\n \/\/\n \/\/ The demons registration filter has two parameters: the number of\n \/\/ iterations to be performed and the standard deviation of the Gaussian\n \/\/ smoothing kernel to be applied to the deformation field after each\n \/\/ iteration.\n \/\/ \\index{itk::DemonsRegistrationFilter!SetNumberOfIterations()}\n \/\/ \\index{itk::DemonsRegistrationFilter!SetStandardDeviations()}\n \/\/\n \/\/ Software Guide : EndLatex\n\n \/\/ Software Guide : BeginCodeSnippet\n filter->SetNumberOfIterations( 150 );\n filter->SetStandardDeviations( 1.0 );\n \/\/ Software Guide : EndCodeSnippet\n\n\n \/\/ Software Guide : BeginLatex\n \/\/ \n \/\/ The registration algorithm is triggered by updating the filter. The\n \/\/ filter output is the computed deformation field.\n \/\/\n \/\/ Software Guide : EndLatex\n\n \/\/ Software Guide : BeginCodeSnippet\n filter->Update();\n \/\/ Software Guide : EndCodeSnippet\n\n\n \/\/ Software Guide : BeginLatex\n \/\/\n \/\/ The \\doxygen{WarpImageFilter} can be used to warp the moving image with\n \/\/ the output deformation field. Like the \\doxygen{ResampleImageFilter},\n \/\/ the WarpImageFilter requires the specification of the input image to be\n \/\/ resampled, an input image interpolator, and the output image spacing and\n \/\/ origin.\n \/\/\n \/\/ \\index{itk::WarpImageFilter}\n \/\/ \\index{itk::WarpImageFilter!SetInput()}\n \/\/ \\index{itk::WarpImageFilter!SetInterpolator()}\n \/\/ \\index{itk::WarpImageFilter!SetOutputSpacing()}\n \/\/ \\index{itk::WarpImageFilter!SetOutputOrigin()}\n \/\/\n \/\/ Software Guide : EndLatex\n\n \/\/ Software Guide : BeginCodeSnippet\n typedef itk::WarpImageFilter<\n MovingImageType, \n MovingImageType,\n DeformationFieldType > WarperType;\n typedef itk::LinearInterpolateImageFunction<\n MovingImageType,\n double > InterpolatorType;\n WarperType::Pointer warper = WarperType::New();\n InterpolatorType::Pointer interpolator = InterpolatorType::New();\n FixedImageType::Pointer fixedImage = fixedImageReader->GetOutput();\n\n warper->SetInput( movingImageReader->GetOutput() );\n warper->SetInterpolator( interpolator );\n warper->SetOutputSpacing( fixedImage->GetSpacing() );\n warper->SetOutputOrigin( fixedImage->GetOrigin() );\n \/\/ Software Guide : EndCodeSnippet\n\n\n \/\/ Software Guide : BeginLatex\n \/\/\n \/\/ Unlike the ResampleImageFilter, the WarpImageFilter\n \/\/ warps or transform the input image with respect to the deformation field\n \/\/ represented by an image of vectors. The resulting warped or resampled\n \/\/ image is written to file as per previous examples.\n \/\/\n \/\/ \\index{itk::WarpImageFilter!SetDeformationField()}\n \/\/\n \/\/ Software Guide : EndLatex\n\n \/\/ Software Guide : BeginCodeSnippet\n warper->SetDeformationField( filter->GetOutput() );\n \/\/ Software Guide : EndCodeSnippet\n\n\n \/\/ Write warped image out to file\n typedef unsigned char OutputPixelType;\n typedef itk::Image< OutputPixelType, Dimension > OutputImageType;\n typedef itk::CastImageFilter< \n MovingImageType,\n OutputImageType > CastFilterType;\n typedef itk::ImageFileWriter< OutputImageType > WriterType;\n\n WriterType::Pointer writer = WriterType::New();\n CastFilterType::Pointer caster = CastFilterType::New();\n\n writer->SetFileName( argv[3] );\n \n caster->SetInput( warper->GetOutput() );\n writer->SetInput( caster->GetOutput() );\n writer->Update();\n\n\n \/\/ Software Guide : BeginLatex\n \/\/\n \/\/ Let's execute this example using the rat lung data from the previous example.\n \/\/ The associated data files can be found in \\code{Examples\/Data}:\n \/\/\n \/\/ \\begin{itemize}\n \/\/ \\item \\code{RatLungSlice1.mha}\n \/\/ \\item \\code{RatLungSlice2.mha}\n \/\/ \\end{itemize}\n \/\/\n \/\/ \\begin{figure} \\center\n \/\/ \\includegraphics[width=0.44\\textwidth]{DeformableRegistration2CheckerboardBefore.eps}\n \/\/ \\includegraphics[width=0.44\\textwidth]{DeformableRegistration2CheckerboardAfter.eps}\n \/\/ \\itkcaption[Demon's deformable registration output]{Checkerboard comparisons\n \/\/ before and after demons-based deformable registration.}\n \/\/ \\label{fig:DeformableRegistration2Output}\n \/\/ \\end{figure}\n \/\/ \n \/\/ The result of the demons-based deformable registration is presented in\n \/\/ Figure \\ref{fig:DeformableRegistration2Output}. The checkerboard\n \/\/ comparision shows that the algorithm was able to recover the misalignment\n \/\/ due to expiration.\n \/\/\n \/\/ Software Guide : EndLatex\n\n\n\n \/\/ Software Guide : BeginLatex\n \/\/\n \/\/ It may be also desirable to write the deformation field as an image of\n \/\/ vectors. This can be done with the following code.\n \/\/\n \/\/ Software Guide : EndLatex\n\n if( argc > 4 ) \/\/ if a fourth line argument has been provided...\n {\n\n \/\/ Software Guide : BeginCodeSnippet\n typedef itk::ImageFileWriter< DeformationFieldType > FieldWriterType;\n FieldWriterType::Pointer fieldWriter = FieldWriterType::New();\n fieldWriter->SetFileName( argv[4] );\n fieldWriter->SetInput( filter->GetOutput() );\n\n fieldWriter->Update();\n \/\/ Software Guide : EndCodeSnippet\n\n \/\/ Software Guide : BeginLatex\n \/\/\n \/\/ Note that the file format used for writing the deformation field must be\n \/\/ capable of representing multiple components per pixel. This is the case\n \/\/ for the MetaImage and VTK fileformats for example.\n \/\/\n \/\/ Software Guide : EndLatex\n\n }\n\n return 0;\n}\n\n<commit_msg>ENH: Added code for saving the deformation field in a vector image file.<commit_after>\/*=========================================================================\n\n Program: Insight Segmentation & Registration Toolkit\n Module: DeformableRegistration2.cxx\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n Copyright (c) Insight Software Consortium. All rights reserved.\n See ITKCopyright.txt or http:\/\/www.itk.org\/HTML\/Copyright.htm for details.\n\n This software is distributed WITHOUT ANY WARRANTY; without even \n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR \n PURPOSE. See the above copyright notices for more information.\n\n=========================================================================*\/\n\n#include \"itkImageFileReader.h\" \n#include \"itkImageFileWriter.h\" \n\n#include \"itkImageRegionIterator.h\"\n\n\/\/ Software Guide : BeginLatex\n\/\/\n\/\/ This example demostrates how to use the ``demons'' algorithm to deformably\n\/\/ register two images. The first step is to include the header files.\n\/\/\n\/\/ Software Guide : EndLatex\n\n\/\/ Software Guide : BeginCodeSnippet\n#include \"itkDemonsRegistrationFilter.h\"\n#include \"itkHistogramMatchingImageFilter.h\"\n#include \"itkCastImageFilter.h\"\n#include \"itkWarpImageFilter.h\"\n#include \"itkLinearInterpolateImageFunction.h\"\n\/\/ Software Guide : EndCodeSnippet\n\n\n\n\n\n\/\/ The following section of code implements a Command observer\n\/\/ that will monitor the evolution of the registration process.\n\/\/\n class CommandIterationUpdate : public itk::Command \n {\n public:\n typedef CommandIterationUpdate Self;\n typedef itk::Command Superclass;\n typedef itk::SmartPointer<CommandIterationUpdate> Pointer;\n itkNewMacro( CommandIterationUpdate );\n protected:\n CommandIterationUpdate() {};\n\n typedef itk::Image< float, 2 > InternalImageType;\n typedef itk::Vector< float, 2 > VectorPixelType;\n typedef itk::Image< VectorPixelType, 2 > DeformationFieldType;\n\n typedef itk::DemonsRegistrationFilter<\n InternalImageType,\n InternalImageType,\n DeformationFieldType> RegistrationFilterType;\n\n public:\n\n void Execute(itk::Object *caller, const itk::EventObject & event)\n {\n Execute( (const itk::Object *)caller, event);\n }\n\n void Execute(const itk::Object * object, const itk::EventObject & event)\n {\n const RegistrationFilterType * filter = \n dynamic_cast< const RegistrationFilterType * >( object );\n if( typeid( event ) != typeid( itk::IterationEvent ) )\n {\n return;\n }\n std::cout << filter->GetMetric() << std::endl;\n }\n };\n\n\n\n\n\n\nint main( int argc, char *argv[] )\n{\n if( argc < 4 )\n {\n std::cerr << \"Missing Parameters \" << std::endl;\n std::cerr << \"Usage: \" << argv[0];\n std::cerr << \" fixedImageFile movingImageFile \";\n std::cerr << \" outputImageFile \" << std::endl;\n std::cerr << \" [outputDeformationFieldFile] \" << std::endl;\n return 1;\n }\n\n \/\/ Software Guide : BeginLatex\n \/\/\n \/\/ Second, we declare the types of the images.\n \/\/\n \/\/ Software Guide : EndLatex\n\n \/\/ Software Guide : BeginCodeSnippet\n const unsigned int Dimension = 2;\n typedef unsigned short PixelType;\n\n typedef itk::Image< PixelType, Dimension > FixedImageType;\n typedef itk::Image< PixelType, Dimension > MovingImageType;\n \/\/ Software Guide : EndCodeSnippet\n\n \/\/ Set up the file readers\n typedef itk::ImageFileReader< FixedImageType > FixedImageReaderType;\n typedef itk::ImageFileReader< MovingImageType > MovingImageReaderType;\n\n FixedImageReaderType::Pointer fixedImageReader = FixedImageReaderType::New();\n MovingImageReaderType::Pointer movingImageReader = MovingImageReaderType::New();\n\n fixedImageReader->SetFileName( argv[1] );\n movingImageReader->SetFileName( argv[2] );\n\n\n \/\/ Software Guide : BeginLatex\n \/\/\n \/\/ Image file readers are set up in a similar fashion to previous examples.\n \/\/ To support the re-mapping of the moving image intensity, we declare an\n \/\/ internal image type with a floating point pixel type and cast the input\n \/\/ images to the internal image type.\n \/\/\n \/\/ Software Guide : EndLatex\n\n \/\/ Software Guide : BeginCodeSnippet\n typedef float InternalPixelType;\n typedef itk::Image< InternalPixelType, Dimension > InternalImageType;\n typedef itk::CastImageFilter< FixedImageType, \n InternalImageType > FixedImageCasterType;\n typedef itk::CastImageFilter< MovingImageType, \n InternalImageType > MovingImageCasterType;\n\n FixedImageCasterType::Pointer fixedImageCaster = FixedImageCasterType::New();\n MovingImageCasterType::Pointer movingImageCaster = MovingImageCasterType::New();\n\n fixedImageCaster->SetInput( fixedImageReader->GetOutput() );\n movingImageCaster->SetInput( movingImageReader->GetOutput() ); \n \/\/ Software Guide : EndCodeSnippet\n\n \/\/ Software Guide : BeginLatex\n \/\/\n \/\/ The demons algorithm relies on the assumption that pixels representing the\n \/\/ same homologous point on an object have the same intensity on both the\n \/\/ fixed and moving images to be registered. In this example, we will\n \/\/ preprocess the moving image to match the intensity between the images\n \/\/ using the \\doxygen{HistogramMatchingImageFilter}. \n \/\/\n \/\/ \\index{itk::HistogramMatchingImageFilter}\n \/\/\n \/\/ The basic idea is to match the histograms of the two images at a user-specified number of quantile values. For robustness, the histograms are\n \/\/ matched so that the background pixels are excluded from both histograms.\n \/\/ For MR images, a simple procedure is to exclude all gray values that are\n \/\/ smaller than the mean gray value of the image.\n \/\/\n \/\/ Software Guide : EndLatex\n\n \/\/ Software Guide : BeginCodeSnippet\n typedef itk::HistogramMatchingImageFilter<\n InternalImageType,\n InternalImageType > MatchingFilterType;\n MatchingFilterType::Pointer matcher = MatchingFilterType::New();\n \/\/ Software Guide : EndCodeSnippet\n\n\n \/\/ Software Guide : BeginLatex\n \/\/ \n \/\/ For this example, we set the moving image as the source or input image and\n \/\/ the fixed image as the reference image.\n \/\/\n \/\/ \\index{itk::HistogramMatchingImageFilter!SetInput()}\n \/\/ \\index{itk::HistogramMatchingImageFilter!SetSourceImage()}\n \/\/ \\index{itk::HistogramMatchingImageFilter!SetReferenceImage()}\n \/\/\n \/\/ Software Guide : EndLatex \n\n \/\/ Software Guide : BeginCodeSnippet \n matcher->SetInput( movingImageCaster->GetOutput() );\n matcher->SetReferenceImage( fixedImageCaster->GetOutput() );\n \/\/ Software Guide : EndCodeSnippet\n\n\n \/\/ Software Guide : BeginLatex\n \/\/\n \/\/ We then select the number of bins to represent the histograms and the\n \/\/ number of points or quantile values where the histogram is to be\n \/\/ matched.\n \/\/\n \/\/ \\index{itk::HistogramMatchingImageFilter!SetNumberOfHistogramLevels()}\n \/\/ \\index{itk::HistogramMatchingImageFilter!SetNumberOfMatchPoints()}\n \/\/\n \/\/ Software Guide : EndLatex\n\n \/\/ Software Guide : BeginCodeSnippet\n matcher->SetNumberOfHistogramLevels( 1024 );\n matcher->SetNumberOfMatchPoints( 7 );\n \/\/ Software Guide : EndCodeSnippet\n\n\n \/\/ Software Guide : BeginLatex\n \/\/\n \/\/ Simple background extraction is done by thresholding at the mean\n \/\/ intensity.\n \/\/\n \/\/ \\index{itk::HistogramMatchingImageFilter!ThresholdAtMeanIntensityOn()}\n \/\/\n \/\/ Software Guide : EndLatex\n\n \/\/ Software Guide : BeginCodeSnippet\n matcher->ThresholdAtMeanIntensityOn();\n \/\/ Software Guide : EndCodeSnippet\n\n\n \/\/ Software Guide : BeginLatex\n \/\/\n \/\/ In the \\doxygen{DemonsRegistrationFilter}, the deformation field is\n \/\/ represented as an image whose pixels are floating point vectors.\n \/\/\n \/\/ \\index{itk::DemonsRegistrationFilter}\n \/\/\n \/\/ Software Guide : EndLatex\n\n \/\/ Software Guide : BeginCodeSnippet\n typedef itk::Vector< float, Dimension > VectorPixelType;\n typedef itk::Image< VectorPixelType, Dimension > DeformationFieldType;\n typedef itk::DemonsRegistrationFilter<\n InternalImageType,\n InternalImageType,\n DeformationFieldType> RegistrationFilterType;\n RegistrationFilterType::Pointer filter = RegistrationFilterType::New();\n \/\/ Software Guide : EndCodeSnippet\n\n\n\n\n\n \/\/ Create the Command observer and register it with the registration filter.\n \/\/\n CommandIterationUpdate::Pointer observer = CommandIterationUpdate::New();\n filter->AddObserver( itk::IterationEvent(), observer );\n\n\n\n\n \/\/ Software Guide : BeginLatex\n \/\/\n \/\/ The input fixed image is simply the output of the fixed image casting\n \/\/ filter. The input moving image is the output of the histogram matching\n \/\/ filter.\n \/\/\n \/\/ \\index{itk::DemonsRegistrationFilter!SetFixedImage()}\n \/\/ \\index{itk::DemonsRegistrationFilter!SetMovingImage()}\n \/\/\n \/\/ Software Guide : EndLatex\n\n \/\/ Software Guide : BeginCodeSnippet\n filter->SetFixedImage( fixedImageCaster->GetOutput() );\n filter->SetMovingImage( matcher->GetOutput() );\n \/\/ Software Guide : EndCodeSnippet\n\n\n \/\/ Software Guide : BeginLatex\n \/\/\n \/\/ The demons registration filter has two parameters: the number of\n \/\/ iterations to be performed and the standard deviation of the Gaussian\n \/\/ smoothing kernel to be applied to the deformation field after each\n \/\/ iteration.\n \/\/ \\index{itk::DemonsRegistrationFilter!SetNumberOfIterations()}\n \/\/ \\index{itk::DemonsRegistrationFilter!SetStandardDeviations()}\n \/\/\n \/\/ Software Guide : EndLatex\n\n \/\/ Software Guide : BeginCodeSnippet\n filter->SetNumberOfIterations( 150 );\n filter->SetStandardDeviations( 1.0 );\n \/\/ Software Guide : EndCodeSnippet\n\n\n \/\/ Software Guide : BeginLatex\n \/\/ \n \/\/ The registration algorithm is triggered by updating the filter. The\n \/\/ filter output is the computed deformation field.\n \/\/\n \/\/ Software Guide : EndLatex\n\n \/\/ Software Guide : BeginCodeSnippet\n filter->Update();\n \/\/ Software Guide : EndCodeSnippet\n\n\n \/\/ Software Guide : BeginLatex\n \/\/\n \/\/ The \\doxygen{WarpImageFilter} can be used to warp the moving image with\n \/\/ the output deformation field. Like the \\doxygen{ResampleImageFilter},\n \/\/ the WarpImageFilter requires the specification of the input image to be\n \/\/ resampled, an input image interpolator, and the output image spacing and\n \/\/ origin.\n \/\/\n \/\/ \\index{itk::WarpImageFilter}\n \/\/ \\index{itk::WarpImageFilter!SetInput()}\n \/\/ \\index{itk::WarpImageFilter!SetInterpolator()}\n \/\/ \\index{itk::WarpImageFilter!SetOutputSpacing()}\n \/\/ \\index{itk::WarpImageFilter!SetOutputOrigin()}\n \/\/\n \/\/ Software Guide : EndLatex\n\n \/\/ Software Guide : BeginCodeSnippet\n typedef itk::WarpImageFilter<\n MovingImageType, \n MovingImageType,\n DeformationFieldType > WarperType;\n typedef itk::LinearInterpolateImageFunction<\n MovingImageType,\n double > InterpolatorType;\n WarperType::Pointer warper = WarperType::New();\n InterpolatorType::Pointer interpolator = InterpolatorType::New();\n FixedImageType::Pointer fixedImage = fixedImageReader->GetOutput();\n\n warper->SetInput( movingImageReader->GetOutput() );\n warper->SetInterpolator( interpolator );\n warper->SetOutputSpacing( fixedImage->GetSpacing() );\n warper->SetOutputOrigin( fixedImage->GetOrigin() );\n \/\/ Software Guide : EndCodeSnippet\n\n\n \/\/ Software Guide : BeginLatex\n \/\/\n \/\/ Unlike the ResampleImageFilter, the WarpImageFilter\n \/\/ warps or transform the input image with respect to the deformation field\n \/\/ represented by an image of vectors. The resulting warped or resampled\n \/\/ image is written to file as per previous examples.\n \/\/\n \/\/ \\index{itk::WarpImageFilter!SetDeformationField()}\n \/\/\n \/\/ Software Guide : EndLatex\n\n \/\/ Software Guide : BeginCodeSnippet\n warper->SetDeformationField( filter->GetOutput() );\n \/\/ Software Guide : EndCodeSnippet\n\n\n \/\/ Write warped image out to file\n typedef unsigned char OutputPixelType;\n typedef itk::Image< OutputPixelType, Dimension > OutputImageType;\n typedef itk::CastImageFilter< \n MovingImageType,\n OutputImageType > CastFilterType;\n typedef itk::ImageFileWriter< OutputImageType > WriterType;\n\n WriterType::Pointer writer = WriterType::New();\n CastFilterType::Pointer caster = CastFilterType::New();\n\n writer->SetFileName( argv[3] );\n \n caster->SetInput( warper->GetOutput() );\n writer->SetInput( caster->GetOutput() );\n writer->Update();\n\n\n \/\/ Software Guide : BeginLatex\n \/\/\n \/\/ Let's execute this example using the rat lung data from the previous example.\n \/\/ The associated data files can be found in \\code{Examples\/Data}:\n \/\/\n \/\/ \\begin{itemize}\n \/\/ \\item \\code{RatLungSlice1.mha}\n \/\/ \\item \\code{RatLungSlice2.mha}\n \/\/ \\end{itemize}\n \/\/\n \/\/ \\begin{figure} \\center\n \/\/ \\includegraphics[width=0.44\\textwidth]{DeformableRegistration2CheckerboardBefore.eps}\n \/\/ \\includegraphics[width=0.44\\textwidth]{DeformableRegistration2CheckerboardAfter.eps}\n \/\/ \\itkcaption[Demon's deformable registration output]{Checkerboard comparisons\n \/\/ before and after demons-based deformable registration.}\n \/\/ \\label{fig:DeformableRegistration2Output}\n \/\/ \\end{figure}\n \/\/ \n \/\/ The result of the demons-based deformable registration is presented in\n \/\/ Figure \\ref{fig:DeformableRegistration2Output}. The checkerboard\n \/\/ comparision shows that the algorithm was able to recover the misalignment\n \/\/ due to expiration.\n \/\/\n \/\/ Software Guide : EndLatex\n\n\n\n \/\/ Software Guide : BeginLatex\n \/\/\n \/\/ It may be also desirable to write the deformation field as an image of\n \/\/ vectors. This can be done with the following code.\n \/\/\n \/\/ Software Guide : EndLatex\n\n if( argc > 4 ) \/\/ if a fourth line argument has been provided...\n {\n\n \/\/ Software Guide : BeginCodeSnippet\n typedef itk::ImageFileWriter< DeformationFieldType > FieldWriterType;\n FieldWriterType::Pointer fieldWriter = FieldWriterType::New();\n fieldWriter->SetFileName( argv[4] );\n fieldWriter->SetInput( filter->GetOutput() );\n\n fieldWriter->Update();\n \/\/ Software Guide : EndCodeSnippet\n\n \/\/ Software Guide : BeginLatex\n \/\/\n \/\/ Note that the file format used for writing the deformation field must be\n \/\/ capable of representing multiple components per pixel. This is the case\n \/\/ for the MetaImage and VTK fileformats for example.\n \/\/\n \/\/ Software Guide : EndLatex\n\n }\n\n\n if( argc > 5 ) \/\/ if a fifth line argument has been provided...\n {\n\n typedef DeformationFieldType VectorImage2DType;\n typedef DeformationFieldType::PixelType Vector2DType;\n\n VectorImage2DType::ConstPointer vectorImage2D = filter->GetOutput();\n\n VectorImage2DType::RegionType region2D = vectorImage2D->GetBufferedRegion();\n VectorImage2DType::IndexType index2D = region2D.GetIndex();\n VectorImage2DType::SizeType size2D = region2D.GetSize(); \n\n\n typedef itk::Vector< float, 3 > Vector3DType;\n typedef itk::Image< Vector3DType, 3 > VectorImage3DType;\n\n typedef itk::ImageFileWriter< VectorImage3DType > WriterType;\n\n WriterType::Pointer writer3D = WriterType::New();\n\n VectorImage3DType::Pointer vectorImage3D = VectorImage3DType::New();\n \n VectorImage3DType::RegionType region3D;\n VectorImage3DType::IndexType index3D;\n VectorImage3DType::SizeType size3D;\n\n index3D[0] = index2D[0];\n index3D[1] = index2D[1];\n index3D[2] = 0;\n \n size3D[0] = size2D[0];\n size3D[1] = size2D[1];\n size3D[2] = 1;\n\n region3D.SetSize( size3D );\n region3D.SetIndex( index3D );\n\n vectorImage3D->SetRegions( region3D );\n vectorImage3D->Allocate();\n \n typedef itk::ImageRegionConstIterator< VectorImage2DType > Iterator2DType;\n\n typedef itk::ImageRegionIterator< VectorImage3DType > Iterator3DType;\n\n Iterator2DType it2( vectorImage2D, region2D );\n Iterator3DType it3( vectorImage3D, region3D );\n\n it2.GoToBegin();\n it3.GoToBegin();\n\n Vector2DType vector2D;\n Vector3DType vector3D;\n\n vector3D[2] = 0; \/\/ set Z component to zero.\n\n while( !it2.IsAtEnd() )\n {\n vector2D = it2.Get();\n vector3D[0] = vector2D[0]; \n vector3D[1] = vector2D[1]; \n it3.Set( vector3D );\n ++it2;\n ++it3;\n }\n\n\n writer3D->SetInput( vectorImage3D );\n\n writer3D->SetFileName( argv[5] );\n\n try\n {\n writer3D->Update();\n }\n catch( itk::ExceptionObject & excp )\n {\n std::cerr << excp << std::endl;\n return -1;\n }\n\n\n }\n\n\n\n return 0;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/*=========================================================================\n\n Program: Insight Segmentation & Registration Toolkit\n Module: DeformableRegistration7.cxx\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n Copyright (c) Insight Software Consortium. All rights reserved.\n See ITKCopyright.txt or http:\/\/www.itk.org\/HTML\/Copyright.htm for details.\n\n This software is distributed WITHOUT ANY WARRANTY; without even \n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR \n PURPOSE. See the above copyright notices for more information.\n\n=========================================================================*\/\n#if defined(_MSC_VER)\n#pragma warning ( disable : 4786 )\n#endif\n\n\n\n\n\/\/ Software Guide : BeginLatex\n\/\/\n\/\/ This example illustrates the use of the \\doxygen{BSplineDeformableTransform}\n\/\/ class for performing registration of two $3D$ images. The example code is\n\/\/ for the most part identical to the code presented in\n\/\/ Section~\\ref{sec:DeformableRegistration}. The major difference is that this\n\/\/ example we set the image dimension to 3 and replace the\n\/\/ \\doxygen{LBFGSOptimizer} optimizer with the \\doxygen{LBFGSBOptimizer}. This\n\/\/ optimizer is more appropriate for performing optimization in a parametric\n\/\/ spaces of higher dimensions.\n\/\/ \n\/\/\n\/\/ \\index{itk::BSplineDeformableTransform}\n\/\/ \\index{itk::BSplineDeformableTransform!DeformableRegistration}\n\/\/ \\index{itk::LBFGSOptimizer}\n\/\/\n\/\/\n\/\/ Software Guide : EndLatex \n\n#include \"itkImageRegistrationMethod.h\"\n#include \"itkMeanSquaresImageToImageMetric.h\"\n#include \"itkLinearInterpolateImageFunction.h\"\n#include \"itkImage.h\"\n\n#include \"itkTimeProbesCollectorBase.h\"\n\n\/\/ Software Guide : BeginLatex\n\/\/ \n\/\/ The following are the most relevant headers to this example.\n\/\/\n\/\/ \\index{itk::BSplineDeformableTransform!header}\n\/\/ \\index{itk::LBFGSOptimizer!header}\n\/\/ \n\/\/ Software Guide : EndLatex \n\n\/\/ Software Guide : BeginCodeSnippet\n#include \"itkBSplineDeformableTransform.h\"\n#include \"itkLBFGSBOptimizer.h\"\n\/\/ Software Guide : EndCodeSnippet\n\n\/\/ Software Guide : BeginLatex\n\/\/ \n\/\/ The parameter space of the \\code{BSplineDeformableTransform} is composed by\n\/\/ the set of all the deformations associated with the nodes of the BSpline\n\/\/ grid. This large number of parameters makes possible to represent a wide\n\/\/ variety of deformations, but it also has the price of requiring a\n\/\/ significant amount of computation time.\n\/\/\n\/\/ \\index{itk::BSplineDeformableTransform!header}\n\/\/ \n\/\/ Software Guide : EndLatex \n\n#include \"itkImageFileReader.h\"\n#include \"itkImageFileWriter.h\"\n\n#include \"itkResampleImageFilter.h\"\n#include \"itkCastImageFilter.h\"\n#include \"itkSquaredDifferenceImageFilter.h\"\n\n\n\/\/ The following section of code implements a Command observer\n\/\/ used to monitor the evolution of the registration process.\n\/\/\n#include \"itkCommand.h\"\nclass CommandIterationUpdate : public itk::Command \n{\npublic:\n typedef CommandIterationUpdate Self;\n typedef itk::Command Superclass;\n typedef itk::SmartPointer<Self> Pointer;\n itkNewMacro( Self );\nprotected:\n CommandIterationUpdate() {};\npublic:\n typedef itk::LBFGSBOptimizer OptimizerType;\n typedef const OptimizerType * OptimizerPointer;\n\n void Execute(itk::Object *caller, const itk::EventObject & event)\n {\n Execute( (const itk::Object *)caller, event);\n }\n\n void Execute(const itk::Object * object, const itk::EventObject & event)\n {\n OptimizerPointer optimizer = \n dynamic_cast< OptimizerPointer >( object );\n if( !(itk::IterationEvent().CheckEvent( &event )) )\n {\n return;\n }\n std::cout << optimizer->GetCurrentIteration() << \" \";\n std::cout << optimizer->GetValue() << \" \";\n std::cout << optimizer->GetInfinityNormOfProjectedGradient() << std::endl;\n }\n};\n\n\nint main( int argc, char *argv[] )\n{\n if( argc < 4 )\n {\n std::cerr << \"Missing Parameters \" << std::endl;\n std::cerr << \"Usage: \" << argv[0];\n std::cerr << \" fixedImageFile movingImageFile outputImagefile \";\n std::cerr << \" [differenceOutputfile] [differenceBeforeRegistration] \";\n std::cerr << \" [deformationField] \";\n return 1;\n }\n \n const unsigned int ImageDimension = 3;\n typedef float PixelType;\n\n typedef itk::Image< PixelType, ImageDimension > FixedImageType;\n typedef itk::Image< PixelType, ImageDimension > MovingImageType;\n\n\n \/\/ Software Guide : BeginLatex\n \/\/\n \/\/ We instantiate now the type of the \\code{BSplineDeformableTransform} using\n \/\/ as template parameters the type for coordinates representation, the\n \/\/ dimension of the space, and the order of the BSpline. \n \/\/ \n \/\/ \\index{BSplineDeformableTransform!New}\n \/\/ \\index{BSplineDeformableTransform!Instantiation}\n \/\/\n \/\/ Software Guide : EndLatex \n\n \/\/ Software Guide : BeginCodeSnippet\n const unsigned int SpaceDimension = ImageDimension;\n const unsigned int SplineOrder = 3;\n typedef double CoordinateRepType;\n\n typedef itk::BSplineDeformableTransform<\n CoordinateRepType,\n SpaceDimension,\n SplineOrder > TransformType;\n \/\/ Software Guide : EndCodeSnippet\n\n\n typedef itk::LBFGSBOptimizer OptimizerType;\n\n\n typedef itk::MeanSquaresImageToImageMetric< \n FixedImageType, \n MovingImageType > MetricType;\n\n typedef itk:: LinearInterpolateImageFunction< \n MovingImageType,\n double > InterpolatorType;\n\n typedef itk::ImageRegistrationMethod< \n FixedImageType, \n MovingImageType > RegistrationType;\n\n MetricType::Pointer metric = MetricType::New();\n OptimizerType::Pointer optimizer = OptimizerType::New();\n InterpolatorType::Pointer interpolator = InterpolatorType::New();\n RegistrationType::Pointer registration = RegistrationType::New();\n \n\n registration->SetMetric( metric );\n registration->SetOptimizer( optimizer );\n registration->SetInterpolator( interpolator );\n\n\n \/\/ Software Guide : BeginLatex\n \/\/\n \/\/ The transform object is constructed below and passed to the registration\n \/\/ method.\n \/\/ \\index{itk::RegistrationMethod!SetTransform()}\n \/\/\n \/\/ Software Guide : EndLatex \n\n \/\/ Software Guide : BeginCodeSnippet\n TransformType::Pointer transform = TransformType::New();\n registration->SetTransform( transform );\n \/\/ Software Guide : EndCodeSnippet\n\n typedef itk::ImageFileReader< FixedImageType > FixedImageReaderType;\n typedef itk::ImageFileReader< MovingImageType > MovingImageReaderType;\n\n FixedImageReaderType::Pointer fixedImageReader = FixedImageReaderType::New();\n MovingImageReaderType::Pointer movingImageReader = MovingImageReaderType::New();\n\n fixedImageReader->SetFileName( argv[1] );\n movingImageReader->SetFileName( argv[2] );\n\n FixedImageType::ConstPointer fixedImage = fixedImageReader->GetOutput();\n\n registration->SetFixedImage( fixedImage );\n registration->SetMovingImage( movingImageReader->GetOutput() );\n\n fixedImageReader->Update();\n\n FixedImageType::RegionType fixedRegion = fixedImage->GetBufferedRegion();\n \n registration->SetFixedImageRegion( fixedRegion );\n\n \/\/ Software Guide : BeginLatex\n \/\/\n \/\/ Here we define the parameters of the BSplineDeformableTransform grid. We\n \/\/ arbitrarily decide to use a grid with $5 \\times 5$ nodes within the image. \n \/\/ The reader should note that the BSpline computation requires a\n \/\/ finite support region ( 1 grid node at the lower borders and 2\n \/\/ grid nodes at upper borders). Therefore in this example, we set\n \/\/ the grid size to be $8 \\times 8$ and place the grid origin such that\n \/\/ grid node (1,1) coincides with the first pixel in the fixed image.\n \/\/ \n \/\/ \\index{BSplineDeformableTransform}\n \/\/\n \/\/ Software Guide : EndLatex \n\n\n \/\/ Software Guide : BeginCodeSnippet\n typedef TransformType::RegionType RegionType;\n RegionType bsplineRegion;\n RegionType::SizeType gridSizeOnImage;\n RegionType::SizeType gridBorderSize;\n RegionType::SizeType totalGridSize;\n\n gridSizeOnImage.Fill( 5 );\n gridBorderSize.Fill( 3 ); \/\/ Border for spline order = 3 ( 1 lower, 2 upper )\n totalGridSize = gridSizeOnImage + gridBorderSize;\n\n bsplineRegion.SetSize( totalGridSize );\n\n typedef TransformType::SpacingType SpacingType;\n SpacingType spacing = fixedImage->GetSpacing();\n\n typedef TransformType::OriginType OriginType;\n OriginType origin = fixedImage->GetOrigin();;\n\n FixedImageType::SizeType fixedImageSize = fixedRegion.GetSize();\n\n for(unsigned int r=0; r<ImageDimension; r++)\n {\n spacing[r] *= floor( static_cast<double>(fixedImageSize[r] - 1) \/ \n static_cast<double>(gridSizeOnImage[r] - 1) );\n origin[r] -= spacing[r]; \n }\n\n transform->SetGridSpacing( spacing );\n transform->SetGridOrigin( origin );\n transform->SetGridRegion( bsplineRegion );\n \n\n typedef TransformType::ParametersType ParametersType;\n\n const unsigned int numberOfParameters =\n transform->GetNumberOfParameters();\n \n ParametersType parameters( numberOfParameters );\n\n parameters.Fill( 0.0 );\n\n transform->SetParameters( parameters );\n \/\/ Software Guide : EndCodeSnippet\n\n\n\n \/\/ Software Guide : BeginLatex\n \/\/ \n \/\/ We now pass the parameters of the current transform as the initial\n \/\/ parameters to be used when the registration process starts. \n \/\/\n \/\/ Software Guide : EndLatex \n\n \/\/ Software Guide : BeginCodeSnippet\n registration->SetInitialTransformParameters( transform->GetParameters() );\n \/\/ Software Guide : EndCodeSnippet\n\n std::cout << \"Intial Parameters = \" << std::endl;\n std::cout << transform->GetParameters() << std::endl;\n\n \/\/ Software Guide : BeginLatex\n \/\/ \n \/\/ Next we set the parameters of the LBFGSB Optimizer. \n \/\/\n \/\/ Software Guide : EndLatex \n OptimizerType::BoundSelectionType boundSelect( transform->GetNumberOfParameters() );\n OptimizerType::BoundValueType upperBound( transform->GetNumberOfParameters() );\n OptimizerType::BoundValueType lowerBound( transform->GetNumberOfParameters() );\n\n boundSelect.Fill( 0 );\n upperBound.Fill( 0.0 );\n lowerBound.Fill( 0.0 );\n\n optimizer->SetBoundSelection( boundSelect );\n optimizer->SetUpperBound( upperBound );\n optimizer->SetLowerBound( lowerBound );\n\n optimizer->SetCostFunctionConvergenceFactor( 1e+12 );\n optimizer->SetProjectedGradientTolerance( 1.0 );\n optimizer->SetMaximumNumberOfIterations( 500 );\n optimizer->SetMaximumNumberOfEvaluations( 500 );\n optimizer->SetMaximumNumberOfCorrections( 5 );\n\n \/\/ Create the Command observer and register it with the optimizer.\n \/\/\n CommandIterationUpdate::Pointer observer = CommandIterationUpdate::New();\n optimizer->AddObserver( itk::IterationEvent(), observer );\n\n\n \/\/ Add a time probe\n itk::TimeProbesCollectorBase collector;\n\n std::cout << std::endl << \"Starting Registration\" << std::endl;\n\n try \n { \n collector.Start( \"Registration\" );\n registration->StartRegistration(); \n collector.Stop( \"Registration\" );\n } \n catch( itk::ExceptionObject & err ) \n { \n std::cerr << \"ExceptionObject caught !\" << std::endl; \n std::cerr << err << std::endl; \n return -1;\n } \n \n OptimizerType::ParametersType finalParameters = \n registration->GetLastTransformParameters();\n\n std::cout << \"Last Transform Parameters\" << std::endl;\n std::cout << finalParameters << std::endl;\n\n\n \/\/ Report the time taken by the registration\n collector.Report();\n\n \/\/ Software Guide : BeginCodeSnippet\n transform->SetParameters( finalParameters );\n \/\/ Software Guide : EndCodeSnippet\n\n\n typedef itk::ResampleImageFilter< \n MovingImageType, \n FixedImageType > ResampleFilterType;\n\n ResampleFilterType::Pointer resample = ResampleFilterType::New();\n\n resample->SetTransform( transform );\n resample->SetInput( movingImageReader->GetOutput() );\n\n resample->SetSize( fixedImage->GetLargestPossibleRegion().GetSize() );\n resample->SetOutputOrigin( fixedImage->GetOrigin() );\n resample->SetOutputSpacing( fixedImage->GetSpacing() );\n resample->SetDefaultPixelValue( 100 );\n \n typedef unsigned char OutputPixelType;\n\n typedef itk::Image< OutputPixelType, ImageDimension > OutputImageType;\n \n typedef itk::CastImageFilter< \n FixedImageType,\n OutputImageType > CastFilterType;\n \n typedef itk::ImageFileWriter< OutputImageType > WriterType;\n\n\n WriterType::Pointer writer = WriterType::New();\n CastFilterType::Pointer caster = CastFilterType::New();\n\n\n writer->SetFileName( argv[3] );\n\n\n caster->SetInput( resample->GetOutput() );\n writer->SetInput( caster->GetOutput() );\n\n\n try\n {\n writer->Update();\n }\n catch( itk::ExceptionObject & err ) \n { \n std::cerr << \"ExceptionObject caught !\" << std::endl; \n std::cerr << err << std::endl; \n return -1;\n } \n \n\n\n typedef itk::SquaredDifferenceImageFilter< \n FixedImageType, \n FixedImageType, \n OutputImageType > DifferenceFilterType;\n\n DifferenceFilterType::Pointer difference = DifferenceFilterType::New();\n\n WriterType::Pointer writer2 = WriterType::New();\n writer2->SetInput( difference->GetOutput() ); \n \n\n \/\/ Compute the difference image between the \n \/\/ fixed and resampled moving image.\n if( argc >= 5 )\n {\n difference->SetInput1( fixedImageReader->GetOutput() );\n difference->SetInput2( resample->GetOutput() );\n writer2->SetFileName( argv[4] );\n try\n {\n writer2->Update();\n }\n catch( itk::ExceptionObject & err ) \n { \n std::cerr << \"ExceptionObject caught !\" << std::endl; \n std::cerr << err << std::endl; \n return -1;\n } \n }\n\n\n \/\/ Compute the difference image between the \n \/\/ fixed and moving image before registration.\n if( argc >= 6 )\n {\n writer2->SetFileName( argv[5] );\n difference->SetInput1( fixedImageReader->GetOutput() );\n difference->SetInput2( movingImageReader->GetOutput() );\n try\n {\n writer2->Update();\n }\n catch( itk::ExceptionObject & err ) \n { \n std::cerr << \"ExceptionObject caught !\" << std::endl; \n std::cerr << err << std::endl; \n return -1;\n } \n }\n\n\n\n \/\/ Generate the explicit deformation field resulting from \n \/\/ the registration.\n if( argc >= 7 )\n {\n\n typedef itk::Vector< float, ImageDimension > VectorType;\n typedef itk::Image< VectorType, ImageDimension > DeformationFieldType;\n\n DeformationFieldType::Pointer field = DeformationFieldType::New();\n field->SetRegions( fixedRegion );\n field->SetOrigin( fixedImage->GetOrigin() );\n field->SetSpacing( fixedImage->GetSpacing() );\n field->Allocate();\n\n typedef itk::ImageRegionIterator< DeformationFieldType > FieldIterator;\n FieldIterator fi( field, fixedRegion );\n\n fi.GoToBegin();\n\n TransformType::InputPointType fixedPoint;\n TransformType::OutputPointType movingPoint;\n DeformationFieldType::IndexType index;\n\n VectorType displacement;\n\n while( ! fi.IsAtEnd() )\n {\n index = fi.GetIndex();\n field->TransformIndexToPhysicalPoint( index, fixedPoint );\n movingPoint = transform->TransformPoint( fixedPoint );\n displacement[0] = movingPoint[0] - fixedPoint[0];\n displacement[1] = movingPoint[1] - fixedPoint[1];\n fi.Set( displacement );\n ++fi;\n }\n\n\n\n typedef itk::ImageFileWriter< DeformationFieldType > FieldWriterType;\n FieldWriterType::Pointer fieldWriter = FieldWriterType::New();\n\n fieldWriter->SetInput( field );\n\n fieldWriter->SetFileName( argv[6] );\n try\n {\n fieldWriter->Update();\n }\n catch( itk::ExceptionObject & excp )\n {\n std::cerr << \"Exception thrown \" << std::endl;\n std::cerr << excp << std::endl;\n return EXIT_FAILURE;\n }\n }\n\n return 0;\n}\n\n<commit_msg>STYLE: fix unfounded claim that LBFGSB is more appropriate for higher dimensional spaces than LBFGS. The actual reason for using LBFGSB is that LBFGS does not behave well when the position in the parametric space is close to the optimal value.<commit_after>\/*=========================================================================\n\n Program: Insight Segmentation & Registration Toolkit\n Module: DeformableRegistration7.cxx\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n Copyright (c) Insight Software Consortium. All rights reserved.\n See ITKCopyright.txt or http:\/\/www.itk.org\/HTML\/Copyright.htm for details.\n\n This software is distributed WITHOUT ANY WARRANTY; without even \n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR \n PURPOSE. See the above copyright notices for more information.\n\n=========================================================================*\/\n#if defined(_MSC_VER)\n#pragma warning ( disable : 4786 )\n#endif\n\n\n\n\n\/\/ Software Guide : BeginLatex\n\/\/\n\/\/ This example illustrates the use of the \\doxygen{BSplineDeformableTransform}\n\/\/ class for performing registration of two $3D$ images. The example code is\n\/\/ for the most part identical to the code presented in\n\/\/ Section~\\ref{sec:DeformableRegistration}. The major difference is that this\n\/\/ example we set the image dimension to 3 and replace the\n\/\/ \\doxygen{LBFGSOptimizer} optimizer with the \\doxygen{LBFGSBOptimizer}. We\n\/\/ made the modification because we found that LBFGS does not behave well when\n\/\/ the starting positions is at or close to optimal; instead we used LBFGSB in\n\/\/ unconstrained mode.\n\/\/ \n\/\/\n\/\/ \\index{itk::BSplineDeformableTransform}\n\/\/ \\index{itk::BSplineDeformableTransform!DeformableRegistration}\n\/\/ \\index{itk::LBFGSOptimizer}\n\/\/\n\/\/\n\/\/ Software Guide : EndLatex \n\n#include \"itkImageRegistrationMethod.h\"\n#include \"itkMeanSquaresImageToImageMetric.h\"\n#include \"itkLinearInterpolateImageFunction.h\"\n#include \"itkImage.h\"\n\n#include \"itkTimeProbesCollectorBase.h\"\n\n\/\/ Software Guide : BeginLatex\n\/\/ \n\/\/ The following are the most relevant headers to this example.\n\/\/\n\/\/ \\index{itk::BSplineDeformableTransform!header}\n\/\/ \\index{itk::LBFGSOptimizer!header}\n\/\/ \n\/\/ Software Guide : EndLatex \n\n\/\/ Software Guide : BeginCodeSnippet\n#include \"itkBSplineDeformableTransform.h\"\n#include \"itkLBFGSBOptimizer.h\"\n\/\/ Software Guide : EndCodeSnippet\n\n\/\/ Software Guide : BeginLatex\n\/\/ \n\/\/ The parameter space of the \\code{BSplineDeformableTransform} is composed by\n\/\/ the set of all the deformations associated with the nodes of the BSpline\n\/\/ grid. This large number of parameters makes possible to represent a wide\n\/\/ variety of deformations, but it also has the price of requiring a\n\/\/ significant amount of computation time.\n\/\/\n\/\/ \\index{itk::BSplineDeformableTransform!header}\n\/\/ \n\/\/ Software Guide : EndLatex \n\n#include \"itkImageFileReader.h\"\n#include \"itkImageFileWriter.h\"\n\n#include \"itkResampleImageFilter.h\"\n#include \"itkCastImageFilter.h\"\n#include \"itkSquaredDifferenceImageFilter.h\"\n\n\n\/\/ The following section of code implements a Command observer\n\/\/ used to monitor the evolution of the registration process.\n\/\/\n#include \"itkCommand.h\"\nclass CommandIterationUpdate : public itk::Command \n{\npublic:\n typedef CommandIterationUpdate Self;\n typedef itk::Command Superclass;\n typedef itk::SmartPointer<Self> Pointer;\n itkNewMacro( Self );\nprotected:\n CommandIterationUpdate() {};\npublic:\n typedef itk::LBFGSBOptimizer OptimizerType;\n typedef const OptimizerType * OptimizerPointer;\n\n void Execute(itk::Object *caller, const itk::EventObject & event)\n {\n Execute( (const itk::Object *)caller, event);\n }\n\n void Execute(const itk::Object * object, const itk::EventObject & event)\n {\n OptimizerPointer optimizer = \n dynamic_cast< OptimizerPointer >( object );\n if( !(itk::IterationEvent().CheckEvent( &event )) )\n {\n return;\n }\n std::cout << optimizer->GetCurrentIteration() << \" \";\n std::cout << optimizer->GetValue() << \" \";\n std::cout << optimizer->GetInfinityNormOfProjectedGradient() << std::endl;\n }\n};\n\n\nint main( int argc, char *argv[] )\n{\n if( argc < 4 )\n {\n std::cerr << \"Missing Parameters \" << std::endl;\n std::cerr << \"Usage: \" << argv[0];\n std::cerr << \" fixedImageFile movingImageFile outputImagefile \";\n std::cerr << \" [differenceOutputfile] [differenceBeforeRegistration] \";\n std::cerr << \" [deformationField] \";\n return 1;\n }\n \n const unsigned int ImageDimension = 3;\n typedef float PixelType;\n\n typedef itk::Image< PixelType, ImageDimension > FixedImageType;\n typedef itk::Image< PixelType, ImageDimension > MovingImageType;\n\n\n \/\/ Software Guide : BeginLatex\n \/\/\n \/\/ We instantiate now the type of the \\code{BSplineDeformableTransform} using\n \/\/ as template parameters the type for coordinates representation, the\n \/\/ dimension of the space, and the order of the BSpline. \n \/\/ \n \/\/ \\index{BSplineDeformableTransform!New}\n \/\/ \\index{BSplineDeformableTransform!Instantiation}\n \/\/\n \/\/ Software Guide : EndLatex \n\n \/\/ Software Guide : BeginCodeSnippet\n const unsigned int SpaceDimension = ImageDimension;\n const unsigned int SplineOrder = 3;\n typedef double CoordinateRepType;\n\n typedef itk::BSplineDeformableTransform<\n CoordinateRepType,\n SpaceDimension,\n SplineOrder > TransformType;\n \/\/ Software Guide : EndCodeSnippet\n\n\n typedef itk::LBFGSBOptimizer OptimizerType;\n\n\n typedef itk::MeanSquaresImageToImageMetric< \n FixedImageType, \n MovingImageType > MetricType;\n\n typedef itk:: LinearInterpolateImageFunction< \n MovingImageType,\n double > InterpolatorType;\n\n typedef itk::ImageRegistrationMethod< \n FixedImageType, \n MovingImageType > RegistrationType;\n\n MetricType::Pointer metric = MetricType::New();\n OptimizerType::Pointer optimizer = OptimizerType::New();\n InterpolatorType::Pointer interpolator = InterpolatorType::New();\n RegistrationType::Pointer registration = RegistrationType::New();\n \n\n registration->SetMetric( metric );\n registration->SetOptimizer( optimizer );\n registration->SetInterpolator( interpolator );\n\n\n \/\/ Software Guide : BeginLatex\n \/\/\n \/\/ The transform object is constructed below and passed to the registration\n \/\/ method.\n \/\/ \\index{itk::RegistrationMethod!SetTransform()}\n \/\/\n \/\/ Software Guide : EndLatex \n\n \/\/ Software Guide : BeginCodeSnippet\n TransformType::Pointer transform = TransformType::New();\n registration->SetTransform( transform );\n \/\/ Software Guide : EndCodeSnippet\n\n typedef itk::ImageFileReader< FixedImageType > FixedImageReaderType;\n typedef itk::ImageFileReader< MovingImageType > MovingImageReaderType;\n\n FixedImageReaderType::Pointer fixedImageReader = FixedImageReaderType::New();\n MovingImageReaderType::Pointer movingImageReader = MovingImageReaderType::New();\n\n fixedImageReader->SetFileName( argv[1] );\n movingImageReader->SetFileName( argv[2] );\n\n FixedImageType::ConstPointer fixedImage = fixedImageReader->GetOutput();\n\n registration->SetFixedImage( fixedImage );\n registration->SetMovingImage( movingImageReader->GetOutput() );\n\n fixedImageReader->Update();\n\n FixedImageType::RegionType fixedRegion = fixedImage->GetBufferedRegion();\n \n registration->SetFixedImageRegion( fixedRegion );\n\n \/\/ Software Guide : BeginLatex\n \/\/\n \/\/ Here we define the parameters of the BSplineDeformableTransform grid. We\n \/\/ arbitrarily decide to use a grid with $5 \\times 5$ nodes within the image. \n \/\/ The reader should note that the BSpline computation requires a\n \/\/ finite support region ( 1 grid node at the lower borders and 2\n \/\/ grid nodes at upper borders). Therefore in this example, we set\n \/\/ the grid size to be $8 \\times 8$ and place the grid origin such that\n \/\/ grid node (1,1) coincides with the first pixel in the fixed image.\n \/\/ \n \/\/ \\index{BSplineDeformableTransform}\n \/\/\n \/\/ Software Guide : EndLatex \n\n\n \/\/ Software Guide : BeginCodeSnippet\n typedef TransformType::RegionType RegionType;\n RegionType bsplineRegion;\n RegionType::SizeType gridSizeOnImage;\n RegionType::SizeType gridBorderSize;\n RegionType::SizeType totalGridSize;\n\n gridSizeOnImage.Fill( 5 );\n gridBorderSize.Fill( 3 ); \/\/ Border for spline order = 3 ( 1 lower, 2 upper )\n totalGridSize = gridSizeOnImage + gridBorderSize;\n\n bsplineRegion.SetSize( totalGridSize );\n\n typedef TransformType::SpacingType SpacingType;\n SpacingType spacing = fixedImage->GetSpacing();\n\n typedef TransformType::OriginType OriginType;\n OriginType origin = fixedImage->GetOrigin();;\n\n FixedImageType::SizeType fixedImageSize = fixedRegion.GetSize();\n\n for(unsigned int r=0; r<ImageDimension; r++)\n {\n spacing[r] *= floor( static_cast<double>(fixedImageSize[r] - 1) \/ \n static_cast<double>(gridSizeOnImage[r] - 1) );\n origin[r] -= spacing[r]; \n }\n\n transform->SetGridSpacing( spacing );\n transform->SetGridOrigin( origin );\n transform->SetGridRegion( bsplineRegion );\n \n\n typedef TransformType::ParametersType ParametersType;\n\n const unsigned int numberOfParameters =\n transform->GetNumberOfParameters();\n \n ParametersType parameters( numberOfParameters );\n\n parameters.Fill( 0.0 );\n\n transform->SetParameters( parameters );\n \/\/ Software Guide : EndCodeSnippet\n\n\n\n \/\/ Software Guide : BeginLatex\n \/\/ \n \/\/ We now pass the parameters of the current transform as the initial\n \/\/ parameters to be used when the registration process starts. \n \/\/\n \/\/ Software Guide : EndLatex \n\n \/\/ Software Guide : BeginCodeSnippet\n registration->SetInitialTransformParameters( transform->GetParameters() );\n \/\/ Software Guide : EndCodeSnippet\n\n std::cout << \"Intial Parameters = \" << std::endl;\n std::cout << transform->GetParameters() << std::endl;\n\n \/\/ Software Guide : BeginLatex\n \/\/ \n \/\/ Next we set the parameters of the LBFGSB Optimizer. \n \/\/\n \/\/ Software Guide : EndLatex \n OptimizerType::BoundSelectionType boundSelect( transform->GetNumberOfParameters() );\n OptimizerType::BoundValueType upperBound( transform->GetNumberOfParameters() );\n OptimizerType::BoundValueType lowerBound( transform->GetNumberOfParameters() );\n\n boundSelect.Fill( 0 );\n upperBound.Fill( 0.0 );\n lowerBound.Fill( 0.0 );\n\n optimizer->SetBoundSelection( boundSelect );\n optimizer->SetUpperBound( upperBound );\n optimizer->SetLowerBound( lowerBound );\n\n optimizer->SetCostFunctionConvergenceFactor( 1e+12 );\n optimizer->SetProjectedGradientTolerance( 1.0 );\n optimizer->SetMaximumNumberOfIterations( 500 );\n optimizer->SetMaximumNumberOfEvaluations( 500 );\n optimizer->SetMaximumNumberOfCorrections( 5 );\n\n \/\/ Create the Command observer and register it with the optimizer.\n \/\/\n CommandIterationUpdate::Pointer observer = CommandIterationUpdate::New();\n optimizer->AddObserver( itk::IterationEvent(), observer );\n\n\n \/\/ Add a time probe\n itk::TimeProbesCollectorBase collector;\n\n std::cout << std::endl << \"Starting Registration\" << std::endl;\n\n try \n { \n collector.Start( \"Registration\" );\n registration->StartRegistration(); \n collector.Stop( \"Registration\" );\n } \n catch( itk::ExceptionObject & err ) \n { \n std::cerr << \"ExceptionObject caught !\" << std::endl; \n std::cerr << err << std::endl; \n return -1;\n } \n \n OptimizerType::ParametersType finalParameters = \n registration->GetLastTransformParameters();\n\n std::cout << \"Last Transform Parameters\" << std::endl;\n std::cout << finalParameters << std::endl;\n\n\n \/\/ Report the time taken by the registration\n collector.Report();\n\n \/\/ Software Guide : BeginCodeSnippet\n transform->SetParameters( finalParameters );\n \/\/ Software Guide : EndCodeSnippet\n\n\n typedef itk::ResampleImageFilter< \n MovingImageType, \n FixedImageType > ResampleFilterType;\n\n ResampleFilterType::Pointer resample = ResampleFilterType::New();\n\n resample->SetTransform( transform );\n resample->SetInput( movingImageReader->GetOutput() );\n\n resample->SetSize( fixedImage->GetLargestPossibleRegion().GetSize() );\n resample->SetOutputOrigin( fixedImage->GetOrigin() );\n resample->SetOutputSpacing( fixedImage->GetSpacing() );\n resample->SetDefaultPixelValue( 100 );\n \n typedef unsigned char OutputPixelType;\n\n typedef itk::Image< OutputPixelType, ImageDimension > OutputImageType;\n \n typedef itk::CastImageFilter< \n FixedImageType,\n OutputImageType > CastFilterType;\n \n typedef itk::ImageFileWriter< OutputImageType > WriterType;\n\n\n WriterType::Pointer writer = WriterType::New();\n CastFilterType::Pointer caster = CastFilterType::New();\n\n\n writer->SetFileName( argv[3] );\n\n\n caster->SetInput( resample->GetOutput() );\n writer->SetInput( caster->GetOutput() );\n\n\n try\n {\n writer->Update();\n }\n catch( itk::ExceptionObject & err ) \n { \n std::cerr << \"ExceptionObject caught !\" << std::endl; \n std::cerr << err << std::endl; \n return -1;\n } \n \n\n\n typedef itk::SquaredDifferenceImageFilter< \n FixedImageType, \n FixedImageType, \n OutputImageType > DifferenceFilterType;\n\n DifferenceFilterType::Pointer difference = DifferenceFilterType::New();\n\n WriterType::Pointer writer2 = WriterType::New();\n writer2->SetInput( difference->GetOutput() ); \n \n\n \/\/ Compute the difference image between the \n \/\/ fixed and resampled moving image.\n if( argc >= 5 )\n {\n difference->SetInput1( fixedImageReader->GetOutput() );\n difference->SetInput2( resample->GetOutput() );\n writer2->SetFileName( argv[4] );\n try\n {\n writer2->Update();\n }\n catch( itk::ExceptionObject & err ) \n { \n std::cerr << \"ExceptionObject caught !\" << std::endl; \n std::cerr << err << std::endl; \n return -1;\n } \n }\n\n\n \/\/ Compute the difference image between the \n \/\/ fixed and moving image before registration.\n if( argc >= 6 )\n {\n writer2->SetFileName( argv[5] );\n difference->SetInput1( fixedImageReader->GetOutput() );\n difference->SetInput2( movingImageReader->GetOutput() );\n try\n {\n writer2->Update();\n }\n catch( itk::ExceptionObject & err ) \n { \n std::cerr << \"ExceptionObject caught !\" << std::endl; \n std::cerr << err << std::endl; \n return -1;\n } \n }\n\n\n\n \/\/ Generate the explicit deformation field resulting from \n \/\/ the registration.\n if( argc >= 7 )\n {\n\n typedef itk::Vector< float, ImageDimension > VectorType;\n typedef itk::Image< VectorType, ImageDimension > DeformationFieldType;\n\n DeformationFieldType::Pointer field = DeformationFieldType::New();\n field->SetRegions( fixedRegion );\n field->SetOrigin( fixedImage->GetOrigin() );\n field->SetSpacing( fixedImage->GetSpacing() );\n field->Allocate();\n\n typedef itk::ImageRegionIterator< DeformationFieldType > FieldIterator;\n FieldIterator fi( field, fixedRegion );\n\n fi.GoToBegin();\n\n TransformType::InputPointType fixedPoint;\n TransformType::OutputPointType movingPoint;\n DeformationFieldType::IndexType index;\n\n VectorType displacement;\n\n while( ! fi.IsAtEnd() )\n {\n index = fi.GetIndex();\n field->TransformIndexToPhysicalPoint( index, fixedPoint );\n movingPoint = transform->TransformPoint( fixedPoint );\n displacement[0] = movingPoint[0] - fixedPoint[0];\n displacement[1] = movingPoint[1] - fixedPoint[1];\n fi.Set( displacement );\n ++fi;\n }\n\n\n\n typedef itk::ImageFileWriter< DeformationFieldType > FieldWriterType;\n FieldWriterType::Pointer fieldWriter = FieldWriterType::New();\n\n fieldWriter->SetInput( field );\n\n fieldWriter->SetFileName( argv[6] );\n try\n {\n fieldWriter->Update();\n }\n catch( itk::ExceptionObject & excp )\n {\n std::cerr << \"Exception thrown \" << std::endl;\n std::cerr << excp << std::endl;\n return EXIT_FAILURE;\n }\n }\n\n return 0;\n}\n\n<|endoftext|>"} {"text":"<commit_before><commit_msg>fixed crash in profiler, int values in profiler have empty space in exclusive time column<commit_after><|endoftext|>"} {"text":"<commit_before>\/\/\/ \\file\n\/\/\/ \\ingroup tutorial_fit\n\/\/\/ \\notebook -nodraw\n\/\/\/ Multi-Dimensional Parametrisation and Fitting\n\/\/\/\n\/\/\/ \\macro_output\n\/\/\/ \\macro_code\n\/\/\/\n\/\/\/ \\authors Rene Brun, Christian Holm Christensen\n\n#include \"Riostream.h\"\n#include \"TROOT.h\"\n#include \"TApplication.h\"\n#include \"TCanvas.h\"\n#include \"TH1.h\"\n#include \"TSystem.h\"\n#include \"TBrowser.h\"\n#include \"TFile.h\"\n#include \"TRandom.h\"\n#include \"TMultiDimFit.h\"\n#include \"TVectorD.h\"\n#include \"TMath.h\"\n\n\n\/\/____________________________________________________________________\nvoid makeData(Double_t* x, Double_t& d, Double_t& e)\n{\n \/\/ Make data points\n Double_t upp[5] = { 10, 10, 10, 10, 1 };\n Double_t low[5] = { 0, 0, 0, 0, .1 };\n for (int i = 0; i < 4; i++)\n x[i] = (upp[i] - low[i]) * gRandom->Rndm() + low[i];\n\n d = x[0] * TMath::Sqrt(x[1] * x[1] + x[2] * x[2] + x[3] * x[3]);\n\n e = gRandom->Gaus(upp[4],low[4]);\n}\n\n\/\/____________________________________________________________________\nint CompareResults(TMultiDimFit *fit, bool doFit)\n{\n \/\/Compare results with reference run\n\n\n \/\/ the right coefficients (before fit)\n double GoodCoeffsNoFit[] = {\n -4.37056,\n 43.1468,\n 13.432,\n 13.4632,\n 13.3964,\n 13.328,\n 13.3016,\n 13.3519,\n 4.49724,\n 4.63876,\n 4.89036,\n -3.69982,\n -3.98618,\n -3.86195,\n 4.36054,\n -4.02597,\n 4.57037,\n 4.69845,\n 2.83819,\n -3.48855,\n -3.97612\n };\n\n \/\/ the right coefficients (after fit)\n double GoodCoeffs[] = {\n -4.399,\n 43.15,\n 13.41,\n 13.49,\n 13.4,\n 13.23,\n 13.34,\n 13.29,\n 4.523,\n 4.659,\n 4.948,\n -4.026,\n -4.045,\n -3.939,\n 4.421,\n -4.006,\n 4.626,\n 4.378,\n 3.516,\n -4.111,\n -3.823,\n };\n\n \/\/ Good Powers\n int GoodPower[] = {\n 1, 1, 1, 1,\n 2, 1, 1, 1,\n 1, 1, 1, 2,\n 1, 1, 2, 1,\n 1, 2, 1, 1,\n 2, 2, 1, 1,\n 2, 1, 1, 2,\n 2, 1, 2, 1,\n 1, 1, 1, 3,\n 1, 3, 1, 1,\n 1, 1, 5, 1,\n 1, 1, 2, 2,\n 1, 2, 1, 2,\n 1, 2, 2, 1,\n 2, 1, 1, 3,\n 2, 2, 1, 2,\n 2, 1, 3, 1,\n 2, 3, 1, 1,\n 1, 2, 2, 2,\n 2, 1, 2, 2,\n 2, 2, 2, 1\n };\n\n Int_t nc = fit->GetNCoefficients();\n Int_t nv = fit->GetNVariables();\n const Int_t *powers = fit->GetPowers();\n const Int_t *pindex = fit->GetPowerIndex();\n if (nc != 21) return 1;\n const TVectorD *coeffs = fit->GetCoefficients();\n int k = 0;\n for (Int_t i=0;i<nc;i++) {\n if (doFit) {\n if (!TMath::AreEqualRel((*coeffs)[i],GoodCoeffs[i],1e-3)) return 2;\n }\n else {\n if (TMath::Abs((*coeffs)[i] - GoodCoeffsNoFit[i]) > 5e-5) return 2;\n }\n for (Int_t j=0;j<nv;j++) {\n if (powers[pindex[i]*nv+j] != GoodPower[k]) return 3;\n k++;\n }\n }\n\n \/\/ now test the result of the generated function\n gROOT->ProcessLine(\".L MDF.C\");\n\n Double_t refMDF = (doFit) ? 43.95 : 43.98;\n \/\/ this does not work in CLing since the function is not defined\n \/\/Double_t x[] = {5,5,5,5};\n \/\/Double_t rMDF = MDF(x);\n \/\/LM: need to return the address of the result since it is casted to a long (this should not be in a tutorial !)\n Long_t iret = gROOT->ProcessLine(\" Double_t xvalues[] = {5,5,5,5}; double result=MDF(xvalues); &result;\");\n Double_t rMDF = * ( (Double_t*)iret);\n \/\/printf(\"%f\\n\",rMDF);\n if (TMath::Abs(rMDF -refMDF) > 1e-2) return 4;\n return 0;\n}\n\n\/\/____________________________________________________________________\nInt_t multidimfit(bool doFit = true)\n{\n\n cout << \"*************************************************\" << endl;\n cout << \"* Multidimensional Fit *\" << endl;\n cout << \"* *\" << endl;\n cout << \"* By Christian Holm <cholm@nbi.dk> 14\/10\/00 *\" << endl;\n cout << \"*************************************************\" << endl;\n cout << endl;\n\n \/\/ Initialize global TRannom object.\n gRandom = new TRandom();\n\n \/\/ Open output file\n TFile* output = new TFile(\"mdf.root\", \"RECREATE\");\n\n \/\/ Global data parameters\n Int_t nVars = 4;\n Int_t nData = 500;\n Double_t x[4];\n\n \/\/ make fit object and set parameters on it.\n TMultiDimFit* fit = new TMultiDimFit(nVars, TMultiDimFit::kMonomials,\"v\");\n\n Int_t mPowers[] = { 6 , 6, 6, 6 };\n fit->SetMaxPowers(mPowers);\n fit->SetMaxFunctions(1000);\n fit->SetMaxStudy(1000);\n fit->SetMaxTerms(30);\n fit->SetPowerLimit(1);\n fit->SetMinAngle(10);\n fit->SetMaxAngle(10);\n fit->SetMinRelativeError(.01);\n\n \/\/ variables to hold the temporary input data\n Double_t d;\n Double_t e;\n\n \/\/ Print out the start parameters\n fit->Print(\"p\");\n\n printf(\"======================================\\n\");\n\n \/\/ Create training sample\n Int_t i;\n for (i = 0; i < nData ; i++) {\n\n \/\/ Make some data\n makeData(x,d,e);\n\n \/\/ Add the row to the fit object\n fit->AddRow(x,d,e);\n }\n\n \/\/ Print out the statistics\n fit->Print(\"s\");\n\n \/\/ Book histograms\n fit->MakeHistograms();\n\n \/\/ Find the parameterization\n fit->FindParameterization();\n\n \/\/ Print coefficents\n fit->Print(\"rc\");\n\n \/\/ Get the min and max of variables from the training sample, used\n \/\/ for cuts in test sample.\n Double_t *xMax = new Double_t[nVars];\n Double_t *xMin = new Double_t[nVars];\n for (i = 0; i < nVars; i++) {\n xMax[i] = (*fit->GetMaxVariables())(i);\n xMin[i] = (*fit->GetMinVariables())(i);\n }\n\n nData = fit->GetNCoefficients() * 100;\n Int_t j;\n\n \/\/ Create test sample\n for (i = 0; i < nData ; i++) {\n \/\/ Make some data\n makeData(x,d,e);\n\n for (j = 0; j < nVars; j++)\n if (x[j] < xMin[j] || x[j] > xMax[j])\n break;\n\n \/\/ If we get through the loop above, all variables are in range\n if (j == nVars)\n \/\/ Add the row to the fit object\n fit->AddTestRow(x,d,e);\n else\n i--;\n }\n \/\/delete gRandom;\n\n \/\/ Test the parameterizatio and coefficents using the test sample.\n if (doFit)\n fit->Fit(\"M\");\n\n \/\/ Print result\n fit->Print(\"fc v\");\n\n \/\/ Write code to file\n fit->MakeCode();\n\n \/\/ Write histograms to disk, and close file\n output->Write();\n output->Close();\n delete output;\n\n \/\/ Compare results with reference run\n Int_t compare = CompareResults(fit, doFit);\n if (!compare) {\n printf(\"\\nmultidimfit .............................................. OK\\n\");\n } else {\n printf(\"\\nmultidimfit .............................................. fails case %d\\n\",compare);\n }\n\n \/\/ We're done\n delete fit;\n return compare;\n}\n<commit_msg>Mem leak in multidimfit.C tutorial<commit_after>\/\/\/ \\file\n\/\/\/ \\ingroup tutorial_fit\n\/\/\/ \\notebook -nodraw\n\/\/\/ Multi-Dimensional Parametrisation and Fitting\n\/\/\/\n\/\/\/ \\macro_output\n\/\/\/ \\macro_code\n\/\/\/\n\/\/\/ \\authors Rene Brun, Christian Holm Christensen\n\n#include \"Riostream.h\"\n#include \"TROOT.h\"\n#include \"TApplication.h\"\n#include \"TCanvas.h\"\n#include \"TH1.h\"\n#include \"TSystem.h\"\n#include \"TBrowser.h\"\n#include \"TFile.h\"\n#include \"TRandom.h\"\n#include \"TMultiDimFit.h\"\n#include \"TVectorD.h\"\n#include \"TMath.h\"\n\n\n\/\/____________________________________________________________________\nvoid makeData(Double_t* x, Double_t& d, Double_t& e)\n{\n \/\/ Make data points\n Double_t upp[5] = { 10, 10, 10, 10, 1 };\n Double_t low[5] = { 0, 0, 0, 0, .1 };\n for (int i = 0; i < 4; i++)\n x[i] = (upp[i] - low[i]) * gRandom->Rndm() + low[i];\n\n d = x[0] * TMath::Sqrt(x[1] * x[1] + x[2] * x[2] + x[3] * x[3]);\n\n e = gRandom->Gaus(upp[4],low[4]);\n}\n\n\/\/____________________________________________________________________\nint CompareResults(TMultiDimFit *fit, bool doFit)\n{\n \/\/Compare results with reference run\n\n\n \/\/ the right coefficients (before fit)\n double GoodCoeffsNoFit[] = {\n -4.37056,\n 43.1468,\n 13.432,\n 13.4632,\n 13.3964,\n 13.328,\n 13.3016,\n 13.3519,\n 4.49724,\n 4.63876,\n 4.89036,\n -3.69982,\n -3.98618,\n -3.86195,\n 4.36054,\n -4.02597,\n 4.57037,\n 4.69845,\n 2.83819,\n -3.48855,\n -3.97612\n };\n\n \/\/ the right coefficients (after fit)\n double GoodCoeffs[] = {\n -4.399,\n 43.15,\n 13.41,\n 13.49,\n 13.4,\n 13.23,\n 13.34,\n 13.29,\n 4.523,\n 4.659,\n 4.948,\n -4.026,\n -4.045,\n -3.939,\n 4.421,\n -4.006,\n 4.626,\n 4.378,\n 3.516,\n -4.111,\n -3.823,\n };\n\n \/\/ Good Powers\n int GoodPower[] = {\n 1, 1, 1, 1,\n 2, 1, 1, 1,\n 1, 1, 1, 2,\n 1, 1, 2, 1,\n 1, 2, 1, 1,\n 2, 2, 1, 1,\n 2, 1, 1, 2,\n 2, 1, 2, 1,\n 1, 1, 1, 3,\n 1, 3, 1, 1,\n 1, 1, 5, 1,\n 1, 1, 2, 2,\n 1, 2, 1, 2,\n 1, 2, 2, 1,\n 2, 1, 1, 3,\n 2, 2, 1, 2,\n 2, 1, 3, 1,\n 2, 3, 1, 1,\n 1, 2, 2, 2,\n 2, 1, 2, 2,\n 2, 2, 2, 1\n };\n\n Int_t nc = fit->GetNCoefficients();\n Int_t nv = fit->GetNVariables();\n const Int_t *powers = fit->GetPowers();\n const Int_t *pindex = fit->GetPowerIndex();\n if (nc != 21) return 1;\n const TVectorD *coeffs = fit->GetCoefficients();\n int k = 0;\n for (Int_t i=0;i<nc;i++) {\n if (doFit) {\n if (!TMath::AreEqualRel((*coeffs)[i],GoodCoeffs[i],1e-3)) return 2;\n }\n else {\n if (TMath::Abs((*coeffs)[i] - GoodCoeffsNoFit[i]) > 5e-5) return 2;\n }\n for (Int_t j=0;j<nv;j++) {\n if (powers[pindex[i]*nv+j] != GoodPower[k]) return 3;\n k++;\n }\n }\n\n \/\/ now test the result of the generated function\n gROOT->ProcessLine(\".L MDF.C\");\n\n Double_t refMDF = (doFit) ? 43.95 : 43.98;\n \/\/ this does not work in CLing since the function is not defined\n \/\/Double_t x[] = {5,5,5,5};\n \/\/Double_t rMDF = MDF(x);\n \/\/LM: need to return the address of the result since it is casted to a long (this should not be in a tutorial !)\n Long_t iret = gROOT->ProcessLine(\" Double_t xvalues[] = {5,5,5,5}; double result=MDF(xvalues); &result;\");\n Double_t rMDF = * ( (Double_t*)iret);\n \/\/printf(\"%f\\n\",rMDF);\n if (TMath::Abs(rMDF -refMDF) > 1e-2) return 4;\n return 0;\n}\n\n\/\/____________________________________________________________________\nInt_t multidimfit(bool doFit = true)\n{\n\n cout << \"*************************************************\" << endl;\n cout << \"* Multidimensional Fit *\" << endl;\n cout << \"* *\" << endl;\n cout << \"* By Christian Holm <cholm@nbi.dk> 14\/10\/00 *\" << endl;\n cout << \"*************************************************\" << endl;\n cout << endl;\n\n \/\/ Initialize global TRannom object.\n gRandom = new TRandom();\n\n \/\/ Open output file\n TFile* output = new TFile(\"mdf.root\", \"RECREATE\");\n\n \/\/ Global data parameters\n Int_t nVars = 4;\n Int_t nData = 500;\n Double_t x[4];\n\n \/\/ make fit object and set parameters on it.\n TMultiDimFit* fit = new TMultiDimFit(nVars, TMultiDimFit::kMonomials,\"v\");\n\n Int_t mPowers[] = { 6 , 6, 6, 6 };\n fit->SetMaxPowers(mPowers);\n fit->SetMaxFunctions(1000);\n fit->SetMaxStudy(1000);\n fit->SetMaxTerms(30);\n fit->SetPowerLimit(1);\n fit->SetMinAngle(10);\n fit->SetMaxAngle(10);\n fit->SetMinRelativeError(.01);\n\n \/\/ variables to hold the temporary input data\n Double_t d;\n Double_t e;\n\n \/\/ Print out the start parameters\n fit->Print(\"p\");\n\n printf(\"======================================\\n\");\n\n \/\/ Create training sample\n Int_t i;\n for (i = 0; i < nData ; i++) {\n\n \/\/ Make some data\n makeData(x,d,e);\n\n \/\/ Add the row to the fit object\n fit->AddRow(x,d,e);\n }\n\n \/\/ Print out the statistics\n fit->Print(\"s\");\n\n \/\/ Book histograms\n fit->MakeHistograms();\n\n \/\/ Find the parameterization\n fit->FindParameterization();\n\n \/\/ Print coefficents\n fit->Print(\"rc\");\n\n \/\/ Get the min and max of variables from the training sample, used\n \/\/ for cuts in test sample.\n Double_t *xMax = new Double_t[nVars];\n Double_t *xMin = new Double_t[nVars];\n for (i = 0; i < nVars; i++) {\n xMax[i] = (*fit->GetMaxVariables())(i);\n xMin[i] = (*fit->GetMinVariables())(i);\n }\n\n nData = fit->GetNCoefficients() * 100;\n Int_t j;\n\n \/\/ Create test sample\n for (i = 0; i < nData ; i++) {\n \/\/ Make some data\n makeData(x,d,e);\n\n for (j = 0; j < nVars; j++)\n if (x[j] < xMin[j] || x[j] > xMax[j])\n break;\n\n \/\/ If we get through the loop above, all variables are in range\n if (j == nVars)\n \/\/ Add the row to the fit object\n fit->AddTestRow(x,d,e);\n else\n i--;\n }\n \/\/delete gRandom;\n\n \/\/ Test the parameterizatio and coefficents using the test sample.\n if (doFit)\n fit->Fit(\"M\");\n\n \/\/ Print result\n fit->Print(\"fc v\");\n\n \/\/ Write code to file\n fit->MakeCode();\n\n \/\/ Write histograms to disk, and close file\n output->Write();\n output->Close();\n delete output;\n\n \/\/ Compare results with reference run\n Int_t compare = CompareResults(fit, doFit);\n if (!compare) {\n printf(\"\\nmultidimfit .............................................. OK\\n\");\n } else {\n printf(\"\\nmultidimfit .............................................. fails case %d\\n\",compare);\n }\n\n \/\/ We're done\n delete fit;\n delete [] xMin;\n delete [] xMax;\n return compare;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ ======================================================================== \/\/\n\/\/ Copyright 2009-2015 Intel Corporation \/\/\n\/\/ \/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\"); \/\/\n\/\/ you may not use this file except in compliance with the License. \/\/\n\/\/ You may obtain a copy of the License at \/\/\n\/\/ \/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0 \/\/\n\/\/ \/\/\n\/\/ Unless required by applicable law or agreed to in writing, software \/\/\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS, \/\/\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. \/\/\n\/\/ See the License for the specific language governing permissions and \/\/\n\/\/ limitations under the License. \/\/\n\/\/ ======================================================================== \/\/\n\n#include \"..\/common\/tutorial\/tutorial.h\"\n#include \"..\/common\/scenegraph\/obj_loader.h\"\n#include \"..\/common\/scenegraph\/xml_loader.h\"\n#include \"..\/common\/tutorial\/scene.h\"\n#include \"..\/common\/image\/image.h\"\n#include \"..\/common\/tutorial\/tutorial_device.h\"\n\nnamespace embree\n{\n \/* name of the tutorial *\/\n const char* tutorialName = \"viewer\";\n\n \/* configuration *\/\n static std::string g_rtcore = \"\";\n static size_t g_numThreads = 0;\n static std::string g_subdiv_mode = \"\";\n\n \/* output settings *\/\n static size_t g_width = 512;\n static size_t g_height = 512;\n static bool g_fullscreen = false;\n static FileName outFilename = \"\";\n static int g_skipBenchmarkFrames = 0;\n static int g_numBenchmarkFrames = 0;\n static bool g_interactive = true;\n static bool g_anim_mode = false;\n extern \"C\" int g_instancing_mode = 0;\n static FileName keyframeList = \"\";\n static bool convert_tris_to_quads = false;\n static bool convert_bezier_to_lines = false;\n\n \/* scene *\/\n TutorialScene g_obj_scene;\n Ref<SceneGraph::GroupNode> g_scene = new SceneGraph::GroupNode;\n static FileName filename = \"\";\n\n static void parseCommandLine(Ref<ParseStream> cin, const FileName& path)\n {\n while (true)\n {\n std::string tag = cin->getString();\n if (tag == \"\") return;\n\n \/* parse command line parameters from a file *\/\n else if (tag == \"-c\") {\n FileName file = path + cin->getFileName();\n parseCommandLine(new ParseStream(new LineCommentFilter(file, \"#\")), file.path());\n }\n\n \/* load OBJ model*\/\n else if (tag == \"-i\") {\n filename = path + cin->getFileName();\n }\n\n \/* convert triangles to quads *\/\n else if (tag == \"-convert-triangles-to-quads\") {\n convert_tris_to_quads = true;\n }\n\n \/* convert bezier to lines *\/\n else if (tag == \"-convert-bezier-to-lines\") {\n convert_bezier_to_lines = true;\n }\n\n \/* parse camera parameters *\/\n else if (tag == \"-vp\") g_camera.from = cin->getVec3fa();\n else if (tag == \"-vi\") g_camera.to = cin->getVec3fa();\n else if (tag == \"-vd\") g_camera.to = g_camera.from + cin->getVec3fa();\n else if (tag == \"-vu\") g_camera.up = cin->getVec3fa();\n else if (tag == \"-fov\") g_camera.fov = cin->getFloat();\n\n \/* frame buffer size *\/\n else if (tag == \"-size\") {\n g_width = cin->getInt();\n g_height = cin->getInt();\n }\n\n \/* full screen mode *\/\n else if (tag == \"-fullscreen\") \n g_fullscreen = true;\n\n \/* output filename *\/\n else if (tag == \"-o\") {\n outFilename = cin->getFileName();\n\tg_interactive = false;\n }\n\n else if (tag == \"-objlist\") {\n keyframeList = cin->getFileName();\n }\n\n \/* subdivision mode *\/\n else if (tag == \"-cache\") \n\tg_subdiv_mode = \",subdiv_accel=bvh4.subdivpatch1cached\";\n\n else if (tag == \"-pregenerate\") \n\tg_subdiv_mode = \",subdiv_accel=bvh4.grid.eager\";\n\n else if (tag == \"-anim\") \n\tg_anim_mode = true;\n\n else if (tag == \"-instancing\") {\n std::string mode = cin->getString();\n if (mode == \"none\" ) g_instancing_mode = TutorialScene::INSTANCING_NONE;\n \/\/else if (mode == \"geometry\") g_instancing_mode = TutorialScene::INSTANCING_GEOMETRY;\n else if (mode == \"scene_geometry\") g_instancing_mode = TutorialScene::INSTANCING_SCENE_GEOMETRY;\n else if (mode == \"scene_group\" ) g_instancing_mode = TutorialScene::INSTANCING_SCENE_GROUP;\n else throw std::runtime_error(\"unknown instancing mode: \"+mode);\n }\n\n \/* number of frames to render in benchmark mode *\/\n else if (tag == \"-benchmark\") {\n g_skipBenchmarkFrames = cin->getInt();\n g_numBenchmarkFrames = cin->getInt();\n\tg_interactive = false;\n }\n\n \/* rtcore configuration *\/\n else if (tag == \"-rtcore\")\n g_rtcore += \",\" + cin->getString();\n\n \/* number of threads to use *\/\n else if (tag == \"-threads\")\n g_numThreads = cin->getInt();\n\n \/* ambient light source *\/\n else if (tag == \"-ambientlight\") \n {\n const Vec3fa L = cin->getVec3fa();\n g_scene->add(new SceneGraph::LightNode<AmbientLight>(AmbientLight(L)));\n }\n\n \/* point light source *\/\n else if (tag == \"-pointlight\") \n {\n const Vec3fa P = cin->getVec3fa();\n const Vec3fa I = cin->getVec3fa();\n g_scene->add(new SceneGraph::LightNode<PointLight>(PointLight(P,I)));\n }\n\n \/* directional light source *\/\n else if (tag == \"-directionallight\" || tag == \"-dirlight\") \n {\n const Vec3fa D = cin->getVec3fa();\n const Vec3fa E = cin->getVec3fa();\n g_scene->add(new SceneGraph::LightNode<DirectionalLight>(DirectionalLight(D,E)));\n }\n\n \/* distant light source *\/\n else if (tag == \"-distantlight\") \n {\n const Vec3fa D = cin->getVec3fa();\n const Vec3fa L = cin->getVec3fa();\n const float halfAngle = cin->getFloat();\n g_scene->add(new SceneGraph::LightNode<DistantLight>(DistantLight(D,L,halfAngle)));\n }\n\n \/* skip unknown command line parameter *\/\n else {\n std::cerr << \"unknown command line parameter: \" << tag << \" \";\n while (cin->peek() != \"\" && cin->peek()[0] != '-') std::cerr << cin->getString() << \" \";\n std::cerr << std::endl;\n }\n }\n }\n \n void renderBenchmark(const FileName& fileName)\n {\n resize(g_width,g_height);\n AffineSpace3fa pixel2world = g_camera.pixel2world(g_width,g_height);\n\n double dt = 0.0f;\n size_t numTotalFrames = g_skipBenchmarkFrames + g_numBenchmarkFrames;\n for (size_t i=0; i<numTotalFrames; i++) \n {\n double t0 = getSeconds();\n render(0.0f,pixel2world.l.vx,pixel2world.l.vy,pixel2world.l.vz,pixel2world.p);\n double t1 = getSeconds();\n std::cout << \"frame [\" << i << \" \/ \" << numTotalFrames << \"] \";\n std::cout << 1.0\/(t1-t0) << \"fps \";\n if (i < g_skipBenchmarkFrames) std::cout << \"(skipped)\";\n std::cout << std::endl;\n if (i >= g_skipBenchmarkFrames) dt += t1-t0;\n }\n std::cout << \"frame [\" << g_skipBenchmarkFrames << \" - \" << numTotalFrames << \"] \" << std::flush;\n std::cout << double(g_numBenchmarkFrames)\/dt << \"fps \" << std::endl;\n std::cout << \"BENCHMARK_RENDER \" << double(g_numBenchmarkFrames)\/dt << std::endl;\n }\n\n void renderToFile(const FileName& fileName)\n {\n resize(g_width,g_height);\n AffineSpace3fa pixel2world = g_camera.pixel2world(g_width,g_height);\n render(0.0f,pixel2world.l.vx,pixel2world.l.vy,pixel2world.l.vz,pixel2world.p);\n void* ptr = map();\n Ref<Image> image = new Image4uc(g_width, g_height, (Col4uc*)ptr);\n storeImage(image, fileName);\n unmap();\n cleanup();\n }\n\n \/* main function in embree namespace *\/\n int main(int argc, char** argv) \n {\n \/* for best performance set FTZ and DAZ flags in MXCSR control and status register *\/\n _MM_SET_FLUSH_ZERO_MODE(_MM_FLUSH_ZERO_ON);\n _MM_SET_DENORMALS_ZERO_MODE(_MM_DENORMALS_ZERO_ON);\n\n \/* create stream for parsing *\/\n Ref<ParseStream> stream = new ParseStream(new CommandLineStream(argc, argv));\n\n \/* parse command line *\/ \n parseCommandLine(stream, FileName());\n\n \/* load default scene if none specified *\/\n if (filename.ext() == \"\") {\n FileName file = FileName::executableFolder() + FileName(\"models\/cornell_box.ecs\");\n parseCommandLine(new ParseStream(new LineCommentFilter(file, \"#\")), file.path());\n }\n\n \/* configure number of threads *\/\n if (g_numThreads) \n g_rtcore += \",threads=\" + toString(g_numThreads);\n if (g_numBenchmarkFrames)\n g_rtcore += \",benchmark=1\";\n\n g_rtcore += g_subdiv_mode;\n\n \/* load scene *\/\n if (toLowerCase(filename.ext()) == std::string(\"obj\")) {\n g_scene->add(loadOBJ(filename,g_subdiv_mode != \"\"));\n }\n else if (toLowerCase(filename.ext()) == std::string(\"xml\")) {\n g_scene->add(loadXML(filename,one));\n }\n else if (filename.ext() != \"\")\n THROW_RUNTIME_ERROR(\"invalid scene type: \"+toLowerCase(filename.ext()));\n\n \/* convert triangles to quads *\/\n if (convert_tris_to_quads)\n g_scene->triangles_to_quads();\n\n \/* convert bezier to lines *\/\n if (convert_bezier_to_lines)\n g_scene->bezier_to_lines();\n\n \/* initialize ray tracing core *\/\n init(g_rtcore.c_str());\n key_pressed(GLUT_KEY_F12);\n\n \/* send model *\/\n g_obj_scene.add(g_scene.dynamicCast<SceneGraph::Node>(),(TutorialScene::InstancingMode)g_instancing_mode); \n g_scene = nullptr;\n set_scene(&g_obj_scene);\n \n \/* benchmark mode *\/\n if (g_numBenchmarkFrames)\n renderBenchmark(outFilename);\n \n \/* render to disk *\/\n if (outFilename.str() != \"\")\n renderToFile(outFilename);\n \n \/* interactive mode *\/\n if (g_interactive) {\n initWindowState(argc,argv,tutorialName, g_width, g_height, g_fullscreen);\n enterWindowRunLoop(g_anim_mode);\n }\n\n return 0;\n }\n}\n\nint main(int argc, char** argv)\n{\n try {\n return embree::main(argc, argv);\n }\n catch (const std::exception& e) {\n std::cout << \"Error: \" << e.what() << std::endl;\n return 1;\n }\n catch (...) {\n std::cout << \"Error: unknown exception caught.\" << std::endl;\n return 1;\n }\n}\n<commit_msg>updates<commit_after>\/\/ ======================================================================== \/\/\n\/\/ Copyright 2009-2015 Intel Corporation \/\/\n\/\/ \/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\"); \/\/\n\/\/ you may not use this file except in compliance with the License. \/\/\n\/\/ You may obtain a copy of the License at \/\/\n\/\/ \/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0 \/\/\n\/\/ \/\/\n\/\/ Unless required by applicable law or agreed to in writing, software \/\/\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS, \/\/\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. \/\/\n\/\/ See the License for the specific language governing permissions and \/\/\n\/\/ limitations under the License. \/\/\n\/\/ ======================================================================== \/\/\n\n#include \"..\/common\/tutorial\/tutorial.h\"\n#include \"..\/common\/scenegraph\/obj_loader.h\"\n#include \"..\/common\/scenegraph\/xml_loader.h\"\n#include \"..\/common\/tutorial\/scene.h\"\n#include \"..\/common\/image\/image.h\"\n#include \"..\/common\/tutorial\/tutorial_device.h\"\n\nnamespace embree\n{\n \/* name of the tutorial *\/\n const char* tutorialName = \"viewer\";\n\n \/* configuration *\/\n static std::string g_rtcore = \"\";\n static size_t g_numThreads = 0;\n static std::string g_subdiv_mode = \"\";\n\n \/* output settings *\/\n static size_t g_width = 512;\n static size_t g_height = 512;\n static bool g_fullscreen = false;\n static FileName outFilename = \"\";\n static int g_skipBenchmarkFrames = 0;\n static int g_numBenchmarkFrames = 0;\n static bool g_interactive = true;\n static bool g_anim_mode = false;\n extern \"C\" int g_instancing_mode = 0;\n static FileName keyframeList = \"\";\n static bool convert_tris_to_quads = false;\n static bool convert_bezier_to_lines = false;\n\n \/* scene *\/\n TutorialScene g_obj_scene;\n Ref<SceneGraph::GroupNode> g_scene = new SceneGraph::GroupNode;\n static FileName filename = \"\";\n\n static void parseCommandLine(Ref<ParseStream> cin, const FileName& path)\n {\n while (true)\n {\n std::string tag = cin->getString();\n if (tag == \"\") return;\n\n \/* parse command line parameters from a file *\/\n else if (tag == \"-c\") {\n FileName file = path + cin->getFileName();\n parseCommandLine(new ParseStream(new LineCommentFilter(file, \"#\")), file.path());\n }\n\n \/* load OBJ model*\/\n else if (tag == \"-i\") {\n filename = path + cin->getFileName();\n }\n\n \/* convert triangles to quads *\/\n else if (tag == \"-convert-triangles-to-quads\") {\n convert_tris_to_quads = true;\n }\n\n \/* convert bezier to lines *\/\n else if (tag == \"-convert-bezier-to-lines\") {\n convert_bezier_to_lines = true;\n }\n\n \/* parse camera parameters *\/\n else if (tag == \"-vp\") g_camera.from = cin->getVec3fa();\n else if (tag == \"-vi\") g_camera.to = cin->getVec3fa();\n else if (tag == \"-vd\") g_camera.to = g_camera.from + cin->getVec3fa();\n else if (tag == \"-vu\") g_camera.up = cin->getVec3fa();\n else if (tag == \"-fov\") g_camera.fov = cin->getFloat();\n\n \/* frame buffer size *\/\n else if (tag == \"-size\") {\n g_width = cin->getInt();\n g_height = cin->getInt();\n }\n\n \/* full screen mode *\/\n else if (tag == \"-fullscreen\") \n g_fullscreen = true;\n\n \/* output filename *\/\n else if (tag == \"-o\") {\n outFilename = cin->getFileName();\n\tg_interactive = false;\n }\n\n else if (tag == \"-objlist\") {\n keyframeList = cin->getFileName();\n }\n\n \/* subdivision mode *\/\n else if (tag == \"-cache\") \n\tg_subdiv_mode = \",subdiv_accel=bvh4.subdivpatch1cached\";\n\n else if (tag == \"-pregenerate\") \n\tg_subdiv_mode = \",subdiv_accel=bvh4.grid.eager\";\n\n else if (tag == \"-anim\") \n\tg_anim_mode = true;\n\n else if (tag == \"-instancing\") {\n std::string mode = cin->getString();\n if (mode == \"none\" ) g_instancing_mode = TutorialScene::INSTANCING_NONE;\n \/\/else if (mode == \"geometry\") g_instancing_mode = TutorialScene::INSTANCING_GEOMETRY;\n else if (mode == \"scene_geometry\") g_instancing_mode = TutorialScene::INSTANCING_SCENE_GEOMETRY;\n else if (mode == \"scene_group\" ) g_instancing_mode = TutorialScene::INSTANCING_SCENE_GROUP;\n else throw std::runtime_error(\"unknown instancing mode: \"+mode);\n }\n\n \/* number of frames to render in benchmark mode *\/\n else if (tag == \"-benchmark\") {\n g_skipBenchmarkFrames = cin->getInt();\n g_numBenchmarkFrames = cin->getInt();\n\tg_interactive = false;\n }\n\n \/* rtcore configuration *\/\n else if (tag == \"-rtcore\")\n g_rtcore += \",\" + cin->getString();\n\n \/* number of threads to use *\/\n else if (tag == \"-threads\")\n g_numThreads = cin->getInt();\n\n \/* ambient light source *\/\n else if (tag == \"-ambientlight\") \n {\n const Vec3fa L = cin->getVec3fa();\n g_scene->add(new SceneGraph::LightNode<AmbientLight>(AmbientLight(L)));\n }\n\n \/* point light source *\/\n else if (tag == \"-pointlight\") \n {\n const Vec3fa P = cin->getVec3fa();\n const Vec3fa I = cin->getVec3fa();\n g_scene->add(new SceneGraph::LightNode<PointLight>(PointLight(P,I)));\n }\n\n \/* directional light source *\/\n else if (tag == \"-directionallight\" || tag == \"-dirlight\") \n {\n const Vec3fa D = cin->getVec3fa();\n const Vec3fa E = cin->getVec3fa();\n g_scene->add(new SceneGraph::LightNode<DirectionalLight>(DirectionalLight(D,E)));\n }\n\n \/* distant light source *\/\n else if (tag == \"-distantlight\") \n {\n const Vec3fa D = cin->getVec3fa();\n const Vec3fa L = cin->getVec3fa();\n const float halfAngle = cin->getFloat();\n g_scene->add(new SceneGraph::LightNode<DistantLight>(DistantLight(D,L,halfAngle)));\n }\n\n \/* skip unknown command line parameter *\/\n else {\n std::cerr << \"unknown command line parameter: \" << tag << \" \";\n while (cin->peek() != \"\" && cin->peek()[0] != '-') std::cerr << cin->getString() << \" \";\n std::cerr << std::endl;\n }\n }\n }\n \n void renderBenchmark(const FileName& fileName)\n {\n resize(g_width,g_height);\n AffineSpace3fa pixel2world = g_camera.pixel2world(g_width,g_height);\n\n double dt = 0.0f;\n size_t numTotalFrames = g_skipBenchmarkFrames + g_numBenchmarkFrames;\n for (size_t i=0; i<numTotalFrames; i++) \n {\n double t0 = getSeconds();\n render(0.0f,pixel2world.l.vx,pixel2world.l.vy,pixel2world.l.vz,pixel2world.p);\n double t1 = getSeconds();\n std::cout << \"frame [\" << i << \" \/ \" << numTotalFrames << \"] \";\n std::cout << 1.0\/(t1-t0) << \"fps \";\n if (i < g_skipBenchmarkFrames) std::cout << \"(skipped)\";\n std::cout << std::endl;\n if (i >= g_skipBenchmarkFrames) dt += t1-t0;\n }\n std::cout << \"frame [\" << g_skipBenchmarkFrames << \" - \" << numTotalFrames << \"] \" << std::flush;\n std::cout << double(g_numBenchmarkFrames)\/dt << \"fps \" << std::endl;\n std::cout << \"BENCHMARK_RENDER \" << double(g_numBenchmarkFrames)\/dt << std::endl;\n }\n\n void renderToFile(const FileName& fileName)\n {\n resize(g_width,g_height);\n AffineSpace3fa pixel2world = g_camera.pixel2world(g_width,g_height);\n render(0.0f,pixel2world.l.vx,pixel2world.l.vy,pixel2world.l.vz,pixel2world.p);\n void* ptr = map();\n Ref<Image> image = new Image4uc(g_width, g_height, (Col4uc*)ptr);\n storeImage(image, fileName);\n unmap();\n cleanup();\n }\n\n \/* main function in embree namespace *\/\n int main(int argc, char** argv) \n {\n \/* for best performance set FTZ and DAZ flags in MXCSR control and status register *\/\n _MM_SET_FLUSH_ZERO_MODE(_MM_FLUSH_ZERO_ON);\n _MM_SET_DENORMALS_ZERO_MODE(_MM_DENORMALS_ZERO_ON);\n\n \/* create stream for parsing *\/\n Ref<ParseStream> stream = new ParseStream(new CommandLineStream(argc, argv));\n\n \/* parse command line *\/ \n parseCommandLine(stream, FileName());\n\n \/* load default scene if none specified *\/\n if (filename.ext() == \"\") {\n FileName file = FileName::executableFolder() + FileName(\"models\/cornell_box.ecs\");\n parseCommandLine(new ParseStream(new LineCommentFilter(file, \"#\")), file.path());\n }\n\n \/* configure number of threads *\/\n if (g_numThreads) \n g_rtcore += \",threads=\" + toString(g_numThreads);\n if (g_numBenchmarkFrames)\n g_rtcore += \",benchmark=1\";\n\n g_rtcore += g_subdiv_mode;\n\n \/* load scene *\/\n if (toLowerCase(filename.ext()) == std::string(\"obj\")) {\n g_scene->add(loadOBJ(filename,g_subdiv_mode != \"\"));\n }\n else if (toLowerCase(filename.ext()) == std::string(\"xml\")) {\n g_scene->add(loadXML(filename,one));\n }\n else if (filename.ext() != \"\")\n THROW_RUNTIME_ERROR(\"invalid scene type: \"+toLowerCase(filename.ext()));\n\n \/* convert triangles to quads *\/\n if (convert_tris_to_quads)\n g_scene->triangles_to_quads();\n\n \/* convert bezier to lines *\/\n if (convert_bezier_to_lines)\n g_scene->bezier_to_lines();\n\n \/* initialize ray tracing core *\/\n init(g_rtcore.c_str());\n\n \/* send model *\/\n g_obj_scene.add(g_scene.dynamicCast<SceneGraph::Node>(),(TutorialScene::InstancingMode)g_instancing_mode); \n g_scene = nullptr;\n set_scene(&g_obj_scene);\n \n \/* benchmark mode *\/\n if (g_numBenchmarkFrames)\n renderBenchmark(outFilename);\n \n \/* render to disk *\/\n if (outFilename.str() != \"\")\n renderToFile(outFilename);\n \n \/* interactive mode *\/\n if (g_interactive) {\n initWindowState(argc,argv,tutorialName, g_width, g_height, g_fullscreen);\n enterWindowRunLoop(g_anim_mode);\n }\n\n return 0;\n }\n}\n\nint main(int argc, char** argv)\n{\n try {\n return embree::main(argc, argv);\n }\n catch (const std::exception& e) {\n std::cout << \"Error: \" << e.what() << std::endl;\n return 1;\n }\n catch (...) {\n std::cout << \"Error: unknown exception caught.\" << std::endl;\n return 1;\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * PlyPublisher.cpp\n *\n * Created on: Aug 7, 2013\n * Author: Péter Fankhauser\n * Institute: ETH Zurich, Autonomous Systems Lab\n *\/\n\n#include \"ply_publisher\/PlyPublisher.hpp\"\n\n\/\/PCL\n#include <pcl\/point_cloud.h>\n#include <pcl\/point_types.h>\n#include <pcl\/io\/ply_io.h>\n#include <pcl_conversions\/pcl_conversions.h>\n\/\/ define the following in order to eliminate the deprecated headers warning\n#define VTK_EXCLUDE_STRSTREAM_HEADERS\n#include <pcl\/io\/vtk_lib_io.h>\n\nusing namespace std;\nusing namespace ros;\nusing namespace pcl;\nusing namespace pcl::io;\nusing namespace pcl_conversions;\n\nnamespace ply_publisher {\n\nPlyPublisher::PlyPublisher(ros::NodeHandle& nodeHandle)\n : nodeHandle_(nodeHandle),\n pointCloudMessage_(new sensor_msgs::PointCloud2)\n{\n if (!readParameters()) ros::requestShutdown();\n pointCloudPublisher_ = nodeHandle_.advertise<sensor_msgs::PointCloud2>(pointCloudTopic_, 1, true);\n initialize();\n}\n\nPlyPublisher::~PlyPublisher()\n{\n\n}\n\nbool PlyPublisher::readParameters()\n{\n bool allParametersRead = true;\n if (!nodeHandle_.getParam(\"file_path\", filePath_)) allParametersRead = false;\n if (!nodeHandle_.getParam(\"topic\", pointCloudTopic_)) allParametersRead = false;\n if (!nodeHandle_.getParam(\"frame\", pointCloudFrameId_)) allParametersRead = false;\n\n double updateRate;\n nodeHandle_.param(\"rate\", updateRate, 0.0);\n if (updateRate == 0.0)\n {\n isContinousPublishing_ = false;\n }\n else\n {\n isContinousPublishing_ = true;\n updateDuration_.fromSec(1.0 \/ updateRate);\n }\n\n if (!allParametersRead)\n {\n ROS_WARN(\"Could not read all parameters. Typical command-line usage:\\n rosrun ply_publisher ply_publisher\"\n \" _file_path:=path_to_your_point_cloud_file _topic:=\/your_topic _frame:=point_cloud_frame\"\n \" (optional) _rate:=publishing_rate\");\n return false;\n }\n\n return true;\n}\n\nvoid PlyPublisher::initialize()\n{\n if (!readFile(filePath_, pointCloudFrameId_)) ros::requestShutdown();\n\n if (isContinousPublishing_)\n {\n timer_ = nodeHandle_.createTimer(updateDuration_, &PlyPublisher::timerCallback, this);\n }\n else\n {\n Duration(1.0).sleep(); \/\/ Need this to get things ready before publishing.\n if (!publish()) ROS_ERROR(\"Something went wrong when trying to read and publish the point cloud file.\");\n ros::requestShutdown();\n }\n}\n\nbool PlyPublisher::readFile(const std::string& filePath, const std::string& pointCloudFrameId)\n{\n if (filePath.find(\".ply\") != std::string::npos) {\n \/\/ Load .ply file.\n PointCloud<PointXYZINormal> pointCloud;\n if (loadPLYFile(filePath, pointCloud) != 0) return false;\n\n \/\/ Define PointCloud2 message.\n toROSMsg(pointCloud, *pointCloudMessage_);\n }\n else if (filePath.find(\".vtk\") != std::string::npos) {\n \/\/ Load .vtk file.\n PolygonMesh polygonMesh;\n loadPolygonFileVTK(filePath, polygonMesh);\n\n \/\/ Define PointCloud2 message.\n moveFromPCL(polygonMesh.cloud, *pointCloudMessage_);\n }\n else\n {\n ROS_ERROR_STREAM(\"Data format not supported.\");\n return false;\n }\n\n pointCloudMessage_->header.frame_id = pointCloudFrameId;\n\n ROS_INFO_STREAM(\"Loaded point cloud with \" << pointCloudMessage_->width << \" points.\");\n return true;\n}\n\nvoid PlyPublisher::timerCallback(const ros::TimerEvent& timerEvent)\n{\n if (!publish()) ROS_ERROR(\"Something went wrong when trying to read and publish the point cloud file.\");\n}\n\nbool PlyPublisher::publish()\n{\n pointCloudMessage_->header.stamp = Time::now();\n if (pointCloudPublisher_.getNumSubscribers() > 0u)\n {\n pointCloudPublisher_.publish(pointCloudMessage_);\n ROS_INFO_STREAM(\"Point cloud published in topic \\\"\" << pointCloudTopic_ << \"\\\".\");\n }\n return true;\n}\n\n} \/* namespace *\/\n<commit_msg>Now reading RGB values.<commit_after>\/*\n * PlyPublisher.cpp\n *\n * Created on: Aug 7, 2013\n * Author: Péter Fankhauser\n * Institute: ETH Zurich, Autonomous Systems Lab\n *\/\n\n#include \"ply_publisher\/PlyPublisher.hpp\"\n\n\/\/PCL\n#include <pcl\/point_cloud.h>\n#include <pcl\/point_types.h>\n#include <pcl\/io\/ply_io.h>\n#include <pcl_conversions\/pcl_conversions.h>\n\/\/ define the following in order to eliminate the deprecated headers warning\n#define VTK_EXCLUDE_STRSTREAM_HEADERS\n#include <pcl\/io\/vtk_lib_io.h>\n\nusing namespace std;\nusing namespace ros;\nusing namespace pcl;\nusing namespace pcl::io;\nusing namespace pcl_conversions;\n\nnamespace ply_publisher {\n\nPlyPublisher::PlyPublisher(ros::NodeHandle& nodeHandle)\n : nodeHandle_(nodeHandle),\n pointCloudMessage_(new sensor_msgs::PointCloud2)\n{\n if (!readParameters()) ros::requestShutdown();\n pointCloudPublisher_ = nodeHandle_.advertise<sensor_msgs::PointCloud2>(pointCloudTopic_, 1, true);\n initialize();\n}\n\nPlyPublisher::~PlyPublisher()\n{\n\n}\n\nbool PlyPublisher::readParameters()\n{\n bool allParametersRead = true;\n if (!nodeHandle_.getParam(\"file_path\", filePath_)) allParametersRead = false;\n if (!nodeHandle_.getParam(\"topic\", pointCloudTopic_)) allParametersRead = false;\n if (!nodeHandle_.getParam(\"frame\", pointCloudFrameId_)) allParametersRead = false;\n\n double updateRate;\n nodeHandle_.param(\"rate\", updateRate, 0.0);\n if (updateRate == 0.0)\n {\n isContinousPublishing_ = false;\n }\n else\n {\n isContinousPublishing_ = true;\n updateDuration_.fromSec(1.0 \/ updateRate);\n }\n\n if (!allParametersRead)\n {\n ROS_WARN(\"Could not read all parameters. Typical command-line usage:\\n rosrun ply_publisher ply_publisher\"\n \" _file_path:=path_to_your_point_cloud_file _topic:=\/your_topic _frame:=point_cloud_frame\"\n \" (optional) _rate:=publishing_rate\");\n return false;\n }\n\n return true;\n}\n\nvoid PlyPublisher::initialize()\n{\n if (!readFile(filePath_, pointCloudFrameId_)) ros::requestShutdown();\n\n if (isContinousPublishing_)\n {\n timer_ = nodeHandle_.createTimer(updateDuration_, &PlyPublisher::timerCallback, this);\n }\n else\n {\n Duration(1.0).sleep(); \/\/ Need this to get things ready before publishing.\n if (!publish()) ROS_ERROR(\"Something went wrong when trying to read and publish the point cloud file.\");\n ros::requestShutdown();\n }\n}\n\nbool PlyPublisher::readFile(const std::string& filePath, const std::string& pointCloudFrameId)\n{\n if (filePath.find(\".ply\") != std::string::npos) {\n \/\/ Load .ply file.\n PointCloud<PointXYZRGBNormal> pointCloud;\n if (loadPLYFile(filePath, pointCloud) != 0) return false;\n\n \/\/ Define PointCloud2 message.\n toROSMsg(pointCloud, *pointCloudMessage_);\n }\n else if (filePath.find(\".vtk\") != std::string::npos) {\n \/\/ Load .vtk file.\n PolygonMesh polygonMesh;\n loadPolygonFileVTK(filePath, polygonMesh);\n\n \/\/ Define PointCloud2 message.\n moveFromPCL(polygonMesh.cloud, *pointCloudMessage_);\n }\n else\n {\n ROS_ERROR_STREAM(\"Data format not supported.\");\n return false;\n }\n\n pointCloudMessage_->header.frame_id = pointCloudFrameId;\n\n ROS_INFO_STREAM(\"Loaded point cloud with \" << pointCloudMessage_->width << \" points.\");\n return true;\n}\n\nvoid PlyPublisher::timerCallback(const ros::TimerEvent& timerEvent)\n{\n if (!publish()) ROS_ERROR(\"Something went wrong when trying to read and publish the point cloud file.\");\n}\n\nbool PlyPublisher::publish()\n{\n pointCloudMessage_->header.stamp = Time::now();\n if (pointCloudPublisher_.getNumSubscribers() > 0u)\n {\n pointCloudPublisher_.publish(pointCloudMessage_);\n ROS_INFO_STREAM(\"Point cloud published in topic \\\"\" << pointCloudTopic_ << \"\\\".\");\n }\n return true;\n}\n\n} \/* namespace *\/\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n#include <QPainter>\n#include <QPaintEvent>\n#include <QColorDialog>\n#include <QToolTip>\n#include \"PaletteWidget.h\"\n\n\n#define CBOX_W 40\n#define CBOX_H 40\n#define CBOX_AX m_cboxX\n#define CBOX_AY 5\n#define CBOX_PX (25+m_cboxX)\n#define CBOX_PY 30\n\n#define HR_Y 75\n\n#define PAL_X m_palX\n#define PAL_Y 85\n#define PAL_NX 16\n#define PAL_NY 16\n#define PBOX_W m_pboxW\n#define PBOX_H m_pboxH\n\n\nQSize PaletteWidget::minimumSizeHint() const\n{\n return QSize(100, PAL_Y+PAL_NY*8+8\/2);\n}\n\n\nQSize PaletteWidget::sizeHint() const\n{\n return QSize(100, PAL_Y+PAL_NY*PBOX_H+PBOX_H\/2);\n}\n\n\nvoid PaletteWidget::resizeEvent(QResizeEvent *event)\n{\n int w=event->size().width();\n int h=event->size().height();\n\n m_pboxW=(w-5*2)\/PAL_NX;\n m_pboxH=(h-PAL_Y-5)\/PAL_NY;\n\n if (m_pboxW<2) m_pboxW=2;\n if (m_pboxH<2) m_pboxH=2;\n\n m_palX=(w-m_pboxW*PAL_NX)\/2;\n\n m_cboxX=(w-(CBOX_PX-m_cboxX+CBOX_W))\/2;\n\n \/\/printf(\"palette box: %dx%d\\n\", m_pboxW, m_pboxH);\n}\n\n\nQRect PaletteWidget::palRect(int index) const\n{\n if (index<0) return QRect();\n\n int x=PAL_X+(index%PAL_NX)*PBOX_W;\n int y=PAL_Y+(index\/PAL_NX)*PBOX_H;\n return QRect(x, y, PBOX_W, PBOX_H);\n}\n\n\nQColor PaletteWidget::toQColor(const Imath::Color4f& in)\n{\n return QColor((int)(in.r * 255.0f),\n (int)(in.g * 255.0f),\n (int)(in.b * 255.0f),\n (int)(in.a * 255.0f));\n}\n\n\nQColor PaletteWidget::toQColor(const Imath::Color4f& in, float a)\n{\n return QColor((int)(in.r * 255.0f),\n (int)(in.g * 255.0f),\n (int)(in.b * 255.0f),\n (int)( a * 255.0f));\n}\n\n\nImath::Color4f PaletteWidget::toColor4f(QColor c)\n{\n return Imath::Color4f(\n c.red ()\/255.0f,\n c.green()\/255.0f,\n c.blue ()\/255.0f,\n c.alpha()\/255.0f);\n}\n\n\nvoid PaletteWidget::setPalette(ColorPalettePtr pal)\n{\n m_palette=pal;\n update();\n}\n\n\nbool PaletteWidget::event(QEvent *event)\n{\n if (event->type()==QEvent::ToolTip)\n {\n const QHelpEvent &he=*(QHelpEvent*)event;\n int ci=clickHit(he.pos());\n\n if (ci<0 || !m_palette)\n {\n QToolTip::hideText();\n event->ignore();\n }\n else\n {\n SproxelColor c=m_palette->color(ci);\n QToolTip::showText(he.globalPos(),\n QString(\"%1 (#%2): #%3\\nR:%4 G:%5 B:%6 A:%7\").arg(ci).arg(ci, 2, 16, QChar('0'))\n .arg(toQColor(c).rgba(), 8, 16, QChar('0'))\n .arg(int(c.r*255)).arg(int(c.g*255)).arg(int(c.b*255)).arg(int(c.a*255)),\n this, palRect(ci));\n }\n\n return true;\n }\n\n return QWidget::event(event);\n}\n\n\nvoid PaletteWidget::paintEvent(QPaintEvent*)\n{\n QPainter painter(this);\n\n \/\/ Some useful colors|tools\n Imath::Color4f brighterBackground = m_backgroundColor * 1.05f;\n brighterBackground.a = 1.0f;\n QPen brighterBackgroundPen = QPen(toQColor(brighterBackground));\n\n \/\/ BG clear\n painter.fillRect(0, 0, width(), height(), QBrush(toQColor(m_backgroundColor)));\n\n \/\/ Active and passive colors get drawn in the upper-left\n painter.fillRect(CBOX_PX , CBOX_PY , CBOX_W , CBOX_H , QBrush(QColor(0,0,0)));\n painter.fillRect(CBOX_PX+1, CBOX_PY+1, CBOX_W-2, CBOX_H-2, QBrush(QColor(255, 255, 255)));\n painter.fillRect(CBOX_PX+2, CBOX_PY+2, CBOX_W-4, CBOX_H-4, QBrush(toQColor(m_passiveColor, 1)));\n\n painter.fillRect(CBOX_AX , CBOX_AY , CBOX_W , CBOX_H , QBrush(QColor(0,0,0)));\n painter.fillRect(CBOX_AX+1, CBOX_AY+1, CBOX_W-2, CBOX_H-2, QBrush(QColor(255, 255, 255)));\n painter.fillRect(CBOX_AX+2, CBOX_AY+2, CBOX_W-4, CBOX_H-4, QBrush(toQColor(m_activeColor, 1)));\n\n \/\/ Horizontal rule\n painter.setPen(brighterBackgroundPen);\n painter.drawLine(QPoint(0, HR_Y), QPoint(width(), HR_Y));\n\n \/\/ Palette grid\n if (m_palette)\n {\n for (int y=0; y<PAL_NY; ++y)\n for (int x=0; x<PAL_NX; ++x)\n {\n Imath::Color4f c=m_palette->color(y*PAL_NX+x);\n painter.fillRect(PAL_X+x*PBOX_W, PAL_Y+y*PBOX_H, PBOX_W, PBOX_H, toQColor(c, 1));\n }\n\n if (m_hilightIndex>=0)\n {\n int x=PAL_X+(m_hilightIndex%PAL_NX)*PBOX_W;\n int y=PAL_Y+(m_hilightIndex\/PAL_NX)*PBOX_H;\n painter.fillRect(x , y , PBOX_W , PBOX_H , QColor(0, 0, 0));\n painter.fillRect(x+1, y+1, PBOX_W-2, PBOX_H-2, QColor(255, 255, 255));\n painter.fillRect(x+2, y+2, PBOX_W-4, PBOX_H-4, toQColor(m_palette->color(m_hilightIndex), 1));\n }\n\n if (m_activeIndex>=0)\n {\n int x=PAL_X+(m_activeIndex%PAL_NX)*PBOX_W;\n int y=PAL_Y+(m_activeIndex\/PAL_NX)*PBOX_H;\n painter.fillRect(x+PBOX_W\/4, y+PBOX_H\/2, PBOX_W\/2, 1, toQColor(SproxelColor(1)-m_activeColor, 1));\n painter.fillRect(x+PBOX_W\/2, y+PBOX_H\/4, 1, PBOX_H\/2, toQColor(SproxelColor(1)-m_activeColor, 1));\n }\n\n \/*\n if (m_passiveIndex>=0)\n {\n int x=PAL_X+(m_passiveIndex%PAL_NX)*PBOX_W;\n int y=PAL_Y+(m_passiveIndex\/PAL_NX)*PBOX_H;\n painter.fillRect(x+PBOX_W\/4, y+PBOX_H\/2, PBOX_W\/2, 1, toQColor(SproxelColor(1)-m_passiveColor, 1));\n }\n *\/\n }\n}\n\n\nvoid PaletteWidget::mousePressEvent(QMouseEvent* event)\n{\n QColor color;\n\n int ci=clickHit(event->pos());\n\n setHilight(ci);\n\n switch(ci)\n {\n case HIT_NONE:\n break;\n\n case HIT_ACTIVE_COLOR_BOX:\n color = QColorDialog::getColor(toQColor(m_activeColor), this,\n \"Select active color\", QColorDialog::ShowAlphaChannel);\n\n if (color.isValid()) setActiveColor(toColor4f(color), -1);\n break;\n\n case HIT_PASSIVE_COLOR_BOX:\n color = QColorDialog::getColor(toQColor(m_passiveColor), this,\n \"Select passive color\", QColorDialog::ShowAlphaChannel);\n\n if (color.isValid()) setPassiveColor(toColor4f(color), -1);\n break;\n\n default:\n if (event->button()==Qt::LeftButton)\n {\n if (m_palette) setActiveColor(m_palette->color(ci), ci);\n }\n else if (event->button()==Qt::RightButton)\n {\n if (m_palette)\n {\n color = QColorDialog::getColor(toQColor(m_palette->color(ci)), this,\n QString(\"Select palette color %1 (#%2)\").arg(ci).arg(ci, 2, 16, QChar('0')),\n QColorDialog::ShowAlphaChannel);\n\n if (color.isValid()) p_undoManager->setPaletteColor(m_palette, ci, toColor4f(color));\n }\n }\n break;\n }\n}\n\n\nvoid PaletteWidget::mouseMoveEvent(QMouseEvent* event)\n{\n setHilight(clickHit(event->pos()));\n}\n\n\nvoid PaletteWidget::setHilight(int ci)\n{\n if (m_hilightIndex!=ci)\n {\n int oldIndex=m_hilightIndex;\n m_hilightIndex=ci;\n repaint(palRect(oldIndex));\n repaint(palRect(ci));\n }\n}\n\n\nvoid PaletteWidget::mouseDoubleClickEvent(QMouseEvent* \/*event*\/)\n{\n \/\/ Emit palette changed signal\n \/\/ emit activeColorChanged(Imath::Color4f(1.0f, 0.0f, 1.0f, 1.0f));\n\n \/\/std::cout << event->pos().x() << \" \" << event->pos().y() << std::endl;\n \/\/std::cout << clickHit(event->pos()) << std::endl;\n}\n\n\nvoid PaletteWidget::leaveEvent(QEvent *)\n{\n setHilight(HIT_NONE);\n}\n\n\nint PaletteWidget::clickHit(const QPoint& p)\n{\n if (p.x() >= CBOX_AX && p.y() >= CBOX_AY && p.x() < CBOX_AX+CBOX_W && p.y() < CBOX_AY+CBOX_H)\n return HIT_ACTIVE_COLOR_BOX;\n else if (p.x() >= CBOX_PX && p.y() >= CBOX_PY && p.x() < CBOX_PX+CBOX_W && p.y() < CBOX_PY+CBOX_H)\n return HIT_PASSIVE_COLOR_BOX;\n\n int nx=p.x()-PAL_X, ny=p.y()-PAL_Y;\n if (nx>=0 && ny>=0)\n {\n nx\/=PBOX_W;\n ny\/=PBOX_H;\n if (nx<PAL_NX && ny<PAL_NY) return ny*PAL_NX+nx;\n }\n\n return HIT_NONE;\n}\n\n\nvoid PaletteWidget::setActiveColor(const Imath::Color4f& color, int index)\n{\n int oldIndex=m_activeIndex;\n m_activeColor = color;\n m_activeIndex = index;\n emit activeColorChanged(m_activeColor, m_activeIndex);\n repaint(0, 0, width(), HR_Y);\n repaint(palRect(oldIndex));\n repaint(palRect(m_activeIndex));\n}\n\n\nvoid PaletteWidget::setPassiveColor(const Imath::Color4f& color, int index)\n{\n int oldIndex=m_passiveIndex;\n m_passiveColor = color;\n m_passiveIndex = index;\n \/\/emit activeColorChanged(m_activeColor);\n repaint(0, 0, width(), HR_Y);\n repaint(palRect(oldIndex));\n repaint(palRect(m_passiveIndex));\n}\n\n\nvoid PaletteWidget::swapColors()\n{\n Imath::Color4f copy = m_activeColor; m_activeColor = m_passiveColor; m_passiveColor = copy;\n int icpy = m_activeIndex; m_activeIndex = m_passiveIndex; m_passiveIndex = icpy;\n emit activeColorChanged(m_activeColor, m_activeIndex);\n repaint(0, 0, width(), HR_Y);\n repaint(palRect(m_activeIndex));\n repaint(palRect(m_passiveIndex));\n}\n<commit_msg>Palette now maintains 1:1 aspect ratio<commit_after>#include <iostream>\n#include <QPainter>\n#include <QPaintEvent>\n#include <QColorDialog>\n#include <QToolTip>\n#include \"PaletteWidget.h\"\n\n\n#define CBOX_W 40\n#define CBOX_H 40\n#define CBOX_AX m_cboxX\n#define CBOX_AY 5\n#define CBOX_PX (25+m_cboxX)\n#define CBOX_PY 30\n\n#define HR_Y 75\n\n#define PAL_X m_palX\n#define PAL_Y 85\n#define PAL_NX 16\n#define PAL_NY 16\n#define PBOX_W m_pboxW\n#define PBOX_H m_pboxH\n\n\nQSize PaletteWidget::minimumSizeHint() const\n{\n return QSize(100, PAL_Y+PAL_NY*8+8\/2);\n}\n\n\nQSize PaletteWidget::sizeHint() const\n{\n return QSize(100, PAL_Y+PAL_NY*PBOX_H+PBOX_H\/2);\n}\n\n\nvoid PaletteWidget::resizeEvent(QResizeEvent *event)\n{\n int w=event->size().width();\n int h=event->size().height();\n\n m_pboxW=(w-5*2)\/PAL_NX;\n if (m_pboxW<2) m_pboxW=2;\n m_pboxH=m_pboxW;\n\n m_palX=(w-m_pboxW*PAL_NX)\/2;\n\n m_cboxX=(w-(CBOX_PX-m_cboxX+CBOX_W))\/2;\n\n \/\/printf(\"palette box: %dx%d\\n\", m_pboxW, m_pboxH);\n}\n\n\nQRect PaletteWidget::palRect(int index) const\n{\n if (index<0) return QRect();\n\n int x=PAL_X+(index%PAL_NX)*PBOX_W;\n int y=PAL_Y+(index\/PAL_NX)*PBOX_H;\n return QRect(x, y, PBOX_W, PBOX_H);\n}\n\n\nQColor PaletteWidget::toQColor(const Imath::Color4f& in)\n{\n return QColor((int)(in.r * 255.0f),\n (int)(in.g * 255.0f),\n (int)(in.b * 255.0f),\n (int)(in.a * 255.0f));\n}\n\n\nQColor PaletteWidget::toQColor(const Imath::Color4f& in, float a)\n{\n return QColor((int)(in.r * 255.0f),\n (int)(in.g * 255.0f),\n (int)(in.b * 255.0f),\n (int)( a * 255.0f));\n}\n\n\nImath::Color4f PaletteWidget::toColor4f(QColor c)\n{\n return Imath::Color4f(\n c.red ()\/255.0f,\n c.green()\/255.0f,\n c.blue ()\/255.0f,\n c.alpha()\/255.0f);\n}\n\n\nvoid PaletteWidget::setPalette(ColorPalettePtr pal)\n{\n m_palette=pal;\n update();\n}\n\n\nbool PaletteWidget::event(QEvent *event)\n{\n if (event->type()==QEvent::ToolTip)\n {\n const QHelpEvent &he=*(QHelpEvent*)event;\n int ci=clickHit(he.pos());\n\n if (ci<0 || !m_palette)\n {\n QToolTip::hideText();\n event->ignore();\n }\n else\n {\n SproxelColor c=m_palette->color(ci);\n QToolTip::showText(he.globalPos(),\n QString(\"%1 (#%2): #%3\\nR:%4 G:%5 B:%6 A:%7\").arg(ci).arg(ci, 2, 16, QChar('0'))\n .arg(toQColor(c).rgba(), 8, 16, QChar('0'))\n .arg(int(c.r*255)).arg(int(c.g*255)).arg(int(c.b*255)).arg(int(c.a*255)),\n this, palRect(ci));\n }\n\n return true;\n }\n\n return QWidget::event(event);\n}\n\n\nvoid PaletteWidget::paintEvent(QPaintEvent*)\n{\n QPainter painter(this);\n\n \/\/ Some useful colors|tools\n Imath::Color4f brighterBackground = m_backgroundColor * 1.05f;\n brighterBackground.a = 1.0f;\n QPen brighterBackgroundPen = QPen(toQColor(brighterBackground));\n\n \/\/ BG clear\n painter.fillRect(0, 0, width(), height(), QBrush(toQColor(m_backgroundColor)));\n\n \/\/ Active and passive colors get drawn in the upper-left\n painter.fillRect(CBOX_PX , CBOX_PY , CBOX_W , CBOX_H , QBrush(QColor(0,0,0)));\n painter.fillRect(CBOX_PX+1, CBOX_PY+1, CBOX_W-2, CBOX_H-2, QBrush(QColor(255, 255, 255)));\n painter.fillRect(CBOX_PX+2, CBOX_PY+2, CBOX_W-4, CBOX_H-4, QBrush(toQColor(m_passiveColor, 1)));\n\n painter.fillRect(CBOX_AX , CBOX_AY , CBOX_W , CBOX_H , QBrush(QColor(0,0,0)));\n painter.fillRect(CBOX_AX+1, CBOX_AY+1, CBOX_W-2, CBOX_H-2, QBrush(QColor(255, 255, 255)));\n painter.fillRect(CBOX_AX+2, CBOX_AY+2, CBOX_W-4, CBOX_H-4, QBrush(toQColor(m_activeColor, 1)));\n\n \/\/ Horizontal rule\n painter.setPen(brighterBackgroundPen);\n painter.drawLine(QPoint(0, HR_Y), QPoint(width(), HR_Y));\n\n \/\/ Palette grid\n if (m_palette)\n {\n for (int y=0; y<PAL_NY; ++y)\n for (int x=0; x<PAL_NX; ++x)\n {\n Imath::Color4f c=m_palette->color(y*PAL_NX+x);\n painter.fillRect(PAL_X+x*PBOX_W, PAL_Y+y*PBOX_H, PBOX_W, PBOX_H, toQColor(c, 1));\n }\n\n if (m_hilightIndex>=0)\n {\n int x=PAL_X+(m_hilightIndex%PAL_NX)*PBOX_W;\n int y=PAL_Y+(m_hilightIndex\/PAL_NX)*PBOX_H;\n painter.fillRect(x , y , PBOX_W , PBOX_H , QColor(0, 0, 0));\n painter.fillRect(x+1, y+1, PBOX_W-2, PBOX_H-2, QColor(255, 255, 255));\n painter.fillRect(x+2, y+2, PBOX_W-4, PBOX_H-4, toQColor(m_palette->color(m_hilightIndex), 1));\n }\n\n if (m_activeIndex>=0)\n {\n int x=PAL_X+(m_activeIndex%PAL_NX)*PBOX_W;\n int y=PAL_Y+(m_activeIndex\/PAL_NX)*PBOX_H;\n painter.fillRect(x+PBOX_W\/4, y+PBOX_H\/2, PBOX_W\/2, 1, toQColor(SproxelColor(1)-m_activeColor, 1));\n painter.fillRect(x+PBOX_W\/2, y+PBOX_H\/4, 1, PBOX_H\/2, toQColor(SproxelColor(1)-m_activeColor, 1));\n }\n\n \/*\n if (m_passiveIndex>=0)\n {\n int x=PAL_X+(m_passiveIndex%PAL_NX)*PBOX_W;\n int y=PAL_Y+(m_passiveIndex\/PAL_NX)*PBOX_H;\n painter.fillRect(x+PBOX_W\/4, y+PBOX_H\/2, PBOX_W\/2, 1, toQColor(SproxelColor(1)-m_passiveColor, 1));\n }\n *\/\n }\n}\n\n\nvoid PaletteWidget::mousePressEvent(QMouseEvent* event)\n{\n QColor color;\n\n int ci=clickHit(event->pos());\n\n setHilight(ci);\n\n switch(ci)\n {\n case HIT_NONE:\n break;\n\n case HIT_ACTIVE_COLOR_BOX:\n color = QColorDialog::getColor(toQColor(m_activeColor), this,\n \"Select active color\", QColorDialog::ShowAlphaChannel);\n\n if (color.isValid()) setActiveColor(toColor4f(color), -1);\n break;\n\n case HIT_PASSIVE_COLOR_BOX:\n color = QColorDialog::getColor(toQColor(m_passiveColor), this,\n \"Select passive color\", QColorDialog::ShowAlphaChannel);\n\n if (color.isValid()) setPassiveColor(toColor4f(color), -1);\n break;\n\n default:\n if (event->button()==Qt::LeftButton)\n {\n if (m_palette) setActiveColor(m_palette->color(ci), ci);\n }\n else if (event->button()==Qt::RightButton)\n {\n if (m_palette)\n {\n color = QColorDialog::getColor(toQColor(m_palette->color(ci)), this,\n QString(\"Select palette color %1 (#%2)\").arg(ci).arg(ci, 2, 16, QChar('0')),\n QColorDialog::ShowAlphaChannel);\n\n if (color.isValid()) p_undoManager->setPaletteColor(m_palette, ci, toColor4f(color));\n }\n }\n break;\n }\n}\n\n\nvoid PaletteWidget::mouseMoveEvent(QMouseEvent* event)\n{\n setHilight(clickHit(event->pos()));\n}\n\n\nvoid PaletteWidget::setHilight(int ci)\n{\n if (m_hilightIndex!=ci)\n {\n int oldIndex=m_hilightIndex;\n m_hilightIndex=ci;\n repaint(palRect(oldIndex));\n repaint(palRect(ci));\n }\n}\n\n\nvoid PaletteWidget::mouseDoubleClickEvent(QMouseEvent* \/*event*\/)\n{\n \/\/ Emit palette changed signal\n \/\/ emit activeColorChanged(Imath::Color4f(1.0f, 0.0f, 1.0f, 1.0f));\n\n \/\/std::cout << event->pos().x() << \" \" << event->pos().y() << std::endl;\n \/\/std::cout << clickHit(event->pos()) << std::endl;\n}\n\n\nvoid PaletteWidget::leaveEvent(QEvent *)\n{\n setHilight(HIT_NONE);\n}\n\n\nint PaletteWidget::clickHit(const QPoint& p)\n{\n if (p.x() >= CBOX_AX && p.y() >= CBOX_AY && p.x() < CBOX_AX+CBOX_W && p.y() < CBOX_AY+CBOX_H)\n return HIT_ACTIVE_COLOR_BOX;\n else if (p.x() >= CBOX_PX && p.y() >= CBOX_PY && p.x() < CBOX_PX+CBOX_W && p.y() < CBOX_PY+CBOX_H)\n return HIT_PASSIVE_COLOR_BOX;\n\n int nx=p.x()-PAL_X, ny=p.y()-PAL_Y;\n if (nx>=0 && ny>=0)\n {\n nx\/=PBOX_W;\n ny\/=PBOX_H;\n if (nx<PAL_NX && ny<PAL_NY) return ny*PAL_NX+nx;\n }\n\n return HIT_NONE;\n}\n\n\nvoid PaletteWidget::setActiveColor(const Imath::Color4f& color, int index)\n{\n int oldIndex=m_activeIndex;\n m_activeColor = color;\n m_activeIndex = index;\n emit activeColorChanged(m_activeColor, m_activeIndex);\n repaint(0, 0, width(), HR_Y);\n repaint(palRect(oldIndex));\n repaint(palRect(m_activeIndex));\n}\n\n\nvoid PaletteWidget::setPassiveColor(const Imath::Color4f& color, int index)\n{\n int oldIndex=m_passiveIndex;\n m_passiveColor = color;\n m_passiveIndex = index;\n \/\/emit activeColorChanged(m_activeColor);\n repaint(0, 0, width(), HR_Y);\n repaint(palRect(oldIndex));\n repaint(palRect(m_passiveIndex));\n}\n\n\nvoid PaletteWidget::swapColors()\n{\n Imath::Color4f copy = m_activeColor; m_activeColor = m_passiveColor; m_passiveColor = copy;\n int icpy = m_activeIndex; m_activeIndex = m_passiveIndex; m_passiveIndex = icpy;\n emit activeColorChanged(m_activeColor, m_activeIndex);\n repaint(0, 0, width(), HR_Y);\n repaint(palRect(m_activeIndex));\n repaint(palRect(m_passiveIndex));\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * kdenlivetitle_wrapper.cpp -- kdenlivetitle wrapper\n * Copyright (c) 2009 Marco Gittler <g.marco@freenet.de>\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n *\/\n\n#include <QtGui\/QImage>\n#include <QtGui\/QPainter>\n#include <QtCore\/QCoreApplication>\n#include <QtGui\/QApplication>\n#include <QtCore\/QDebug>\n#include <QtCore\/QFile>\n#include <QtGui\/QGraphicsView>\n#include <QtGui\/QGraphicsScene>\n#include <QtGui\/QGraphicsTextItem>\n#include <QtGui\/QtextCursor>\n#include \"kdenlivetitle_wrapper.h\"\n#include <framework\/mlt_producer.h>\nextern \"C\" {\nvoid init_qt (const char* c){\n titleclass=new Title(QString(c));\n}\nvoid refresh_kdenlivetitle( void* buffer, int width, int height , double position){\n titleclass->drawKdenliveTitle(buffer,width,height,position);\n int i=0;\n unsigned char* pointer;\n \/\/rotate bytes for correct order in mlt\n for (i=0;i<width*height*4;i+=4){\n pointer=(unsigned char*)buffer+i;\n pointer[0]=pointer[1];\n pointer[1]=pointer[2];\n pointer[2]=pointer[3];\n pointer[3]=pointer[0];\n }\n}\n}\nTitle::Title(const QString& filename){\n int argc=0;\n char* argv[1];\n argv[0]=\"xxx\"; \n \/\/app=new QApplication(argc,argv);\n app=new QApplication(argc,argv);\n QGraphicsPolygonItem i;\n m_scene=new QGraphicsScene(10,10,100,100);\n loadDocument(filename,&i,&i);\n m_scene->addText(\"hello\");\n m_scene->setSceneRect(0,0,1000,1000);\n \/\/view=new QGraphicsView(scene);\n \/\/view->show();\n qDebug() << filename;\n}\nvoid Title::drawKdenliveTitle(void * buffer ,int width,int height,double position){\n QImage img((uchar*)buffer,width,height,width*4,QImage::Format_ARGB32);\n img.fill(255);\n \/\/qDebug() << \"ja\" << width << height << buffer << position << endl;\n QList<QGraphicsItem*> items=m_scene->items();\n for(int i=0;i<items.size();i++){\n items[i]->moveBy(width*position,width*position); \n }\n \/*\n QPainter p;\n p.begin(&img);\n p.setRenderHints(QPainter::Antialiasing | QPainter::TextAntialiasing | QPainter::HighQualityAntialiasing);\n p.setFont(QFont(\"Arial\",60));\n p.setPen(QPen(QColor(255,255,255)));\n p.drawText(width*.2+width*20*position,height\/2,\"test\");\n p.end();\n*\/\n QPainter p1;\n p1.begin(&img);\n m_scene->render(&p1);\n p1.end();\n}\nint Title::loadDocument(const QString& url, QGraphicsPolygonItem* startv, QGraphicsPolygonItem* endv)\n{\n QDomDocument doc;\n if (!m_scene)\n return -1;\n\n QFile file(url);\n if (file.open(QIODevice::ReadOnly)) {\n qDebug() << \"loaded\";\n doc.setContent(&file, false);\n file.close();\n } \n return loadFromXml(doc, startv, endv);\n}\nint Title::loadFromXml(QDomDocument doc, QGraphicsPolygonItem* \/*startv*\/, QGraphicsPolygonItem* \/*endv*\/)\n{\n QDomNodeList titles = doc.elementsByTagName(\"kdenlivetitle\");\n int maxZValue = 0;\n if (titles.size()) {\n\n QDomNodeList items = titles.item(0).childNodes();\n for (int i = 0; i < items.count(); i++) {\n QGraphicsItem *gitem = NULL;\n int zValue = items.item(i).attributes().namedItem(\"z-index\").nodeValue().toInt();\n if (zValue > -1000) {\n if (items.item(i).attributes().namedItem(\"type\").nodeValue() == \"QGraphicsTextItem\") {\n QDomNamedNodeMap txtProperties = items.item(i).namedItem(\"content\").attributes();\n QFont font(txtProperties.namedItem(\"font\").nodeValue());\n font.setBold(txtProperties.namedItem(\"font-bold\").nodeValue().toInt());\n font.setItalic(txtProperties.namedItem(\"font-italic\").nodeValue().toInt());\n font.setUnderline(txtProperties.namedItem(\"font-underline\").nodeValue().toInt());\n \/\/ Older Kdenlive version did not store pixel size but point size\n if (txtProperties.namedItem(\"font-pixel-size\").isNull()) {\n QFont f2;\n f2.setPointSize(txtProperties.namedItem(\"font-size\").nodeValue().toInt());\n font.setPixelSize(QFontInfo(f2).pixelSize());\n } else\n font.setPixelSize(txtProperties.namedItem(\"font-pixel-size\").nodeValue().toInt());\n QColor col(stringToColor(txtProperties.namedItem(\"font-color\").nodeValue()));\n QGraphicsTextItem *txt = m_scene->addText(items.item(i).namedItem(\"content\").firstChild().nodeValue(), font);\n txt->setDefaultTextColor(col);\n txt->setTextInteractionFlags(Qt::NoTextInteraction);\n if (txtProperties.namedItem(\"alignment\").isNull() == false) {\n txt->setTextWidth(txt->boundingRect().width());\n QTextCursor cur = txt->textCursor();\n QTextBlockFormat format = cur.blockFormat();\n format.setAlignment((Qt::Alignment) txtProperties.namedItem(\"alignment\").nodeValue().toInt());\n cur.select(QTextCursor::Document);\n cur.setBlockFormat(format);\n txt->setTextCursor(cur);\n cur.clearSelection();\n txt->setTextCursor(cur);\n }\n\n if (!txtProperties.namedItem(\"kdenlive-axis-x-inverted\").isNull()) {\n \/\/txt->setData(OriginXLeft, txtProperties.namedItem(\"kdenlive-axis-x-inverted\").nodeValue().toInt());\n }\n if (!txtProperties.namedItem(\"kdenlive-axis-y-inverted\").isNull()) {\n \/\/txt->setData(OriginYTop, txtProperties.namedItem(\"kdenlive-axis-y-inverted\").nodeValue().toInt());\n }\n\n gitem = txt;\n } else if (items.item(i).attributes().namedItem(\"type\").nodeValue() == \"QGraphicsRectItem\") {\n qDebug() << \"rectitem\";\n QString rect = items.item(i).namedItem(\"content\").attributes().namedItem(\"rect\").nodeValue();\n QString br_str = items.item(i).namedItem(\"content\").attributes().namedItem(\"brushcolor\").nodeValue();\n QString pen_str = items.item(i).namedItem(\"content\").attributes().namedItem(\"pencolor\").nodeValue();\n double penwidth = items.item(i).namedItem(\"content\").attributes().namedItem(\"penwidth\").nodeValue().toDouble();\n QGraphicsRectItem *rec = m_scene->addRect(stringToRect(rect), QPen(QBrush(stringToColor(pen_str)), penwidth), QBrush(stringToColor(br_str)));\n gitem = rec;\n } else if (items.item(i).attributes().namedItem(\"type\").nodeValue() == \"QGraphicsPixmapItem\") {\n QString url = items.item(i).namedItem(\"content\").attributes().namedItem(\"url\").nodeValue();\n QPixmap pix(url);\n QGraphicsPixmapItem *rec = m_scene->addPixmap(pix);\n rec->setData(Qt::UserRole, url);\n gitem = rec;\n } else if (items.item(i).attributes().namedItem(\"type\").nodeValue() == \"QGraphicsSvgItem\") {\n QString url = items.item(i).namedItem(\"content\").attributes().namedItem(\"url\").nodeValue();\n \/\/QGraphicsSvgItem *rec = new QGraphicsSvgItem(url);\n \/\/m_scene->addItem(rec);\n \/\/rec->setData(Qt::UserRole, url);\n \/\/gitem = rec;\n }\n }\n \/\/pos and transform\n if (gitem) {\n QPointF p(items.item(i).namedItem(\"position\").attributes().namedItem(\"x\").nodeValue().toDouble(),\n items.item(i).namedItem(\"position\").attributes().namedItem(\"y\").nodeValue().toDouble());\n gitem->setPos(p);\n gitem->setTransform(stringToTransform(items.item(i).namedItem(\"position\").firstChild().firstChild().nodeValue()));\n int zValue = items.item(i).attributes().namedItem(\"z-index\").nodeValue().toInt();\n if (zValue > maxZValue) maxZValue = zValue;\n gitem->setZValue(zValue);\n gitem->setFlags(QGraphicsItem::ItemIsMovable | QGraphicsItem::ItemIsSelectable);\n }\n if (items.item(i).nodeName() == \"background\") {\n QColor color = QColor(stringToColor(items.item(i).attributes().namedItem(\"color\").nodeValue()));\n \/\/color.setAlpha(items.item(i).attributes().namedItem(\"alpha\").nodeValue().toInt());\n QList<QGraphicsItem *> items = m_scene->items();\n for (int i = 0; i < items.size(); i++) {\n if (items.at(i)->zValue() == -1100) {\n ((QGraphicsRectItem *)items.at(i))->setBrush(QBrush(color));\n break;\n }\n }\n } \/*else if (items.item(i).nodeName() == \"startviewport\" && startv) {\n QPointF p(items.item(i).attributes().namedItem(\"x\").nodeValue().toDouble(), items.item(i).attributes().namedItem(\"y\").nodeValue().toDouble());\n double width = items.item(i).attributes().namedItem(\"size\").nodeValue().toDouble();\n QRectF rect(-width, -width \/ aspect_ratio, width*2.0, width \/ aspect_ratio*2.0);\n kDebug() << width << rect;\n startv->setPolygon(rect);\n startv->setPos(p);\n } else if (items.item(i).nodeName() == \"endviewport\" && endv) {\n QPointF p(items.item(i).attributes().namedItem(\"x\").nodeValue().toDouble(), items.item(i).attributes().namedItem(\"y\").nodeValue().toDouble());\n double width = items.item(i).attributes().namedItem(\"size\").nodeValue().toDouble();\n QRectF rect(-width, -width \/ aspect_ratio, width*2.0, width \/ aspect_ratio*2.0);\n kDebug() << width << rect;\n endv->setPolygon(rect);\n endv->setPos(p);\n }*\/\n }\n }\n return maxZValue;\n}\n\nQString Title::colorToString(const QColor& c)\n{\n QString ret = \"%1,%2,%3,%4\";\n ret = ret.arg(c.red()).arg(c.green()).arg(c.blue()).arg(c.alpha());\n return ret;\n}\n\nQString Title::rectFToString(const QRectF& c)\n{\n QString ret = \"%1,%2,%3,%4\";\n ret = ret.arg(c.top()).arg(c.left()).arg(c.width()).arg(c.height());\n return ret;\n}\n\nQRectF Title::stringToRect(const QString & s)\n{\n\n QStringList l = s.split(',');\n if (l.size() < 4)\n return QRectF();\n return QRectF(l.at(0).toDouble(), l.at(1).toDouble(), l.at(2).toDouble(), l.at(3).toDouble()).normalized();\n}\n\nQColor Title::stringToColor(const QString & s)\n{\n QStringList l = s.split(',');\n if (l.size() < 4)\n return QColor();\n return QColor(l.at(0).toInt(), l.at(1).toInt(), l.at(2).toInt(), l.at(3).toInt());;\n}\nQTransform Title::stringToTransform(const QString& s)\n{\n QStringList l = s.split(',');\n if (l.size() < 9)\n return QTransform();\n return QTransform(\n l.at(0).toDouble(), l.at(1).toDouble(), l.at(2).toDouble(),\n l.at(3).toDouble(), l.at(4).toDouble(), l.at(5).toDouble(),\n l.at(6).toDouble(), l.at(7).toDouble(), l.at(8).toDouble()\n );\n}\n<commit_msg>kdenlivetitle_wrapper: fixed typo, not seen in Mac OS (QtXml also needed<commit_after>\/*\n * kdenlivetitle_wrapper.cpp -- kdenlivetitle wrapper\n * Copyright (c) 2009 Marco Gittler <g.marco@freenet.de>\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n *\/\n\n#include <QtGui\/QImage>\n#include <QtGui\/QPainter>\n#include <QtCore\/QCoreApplication>\n#include <QtGui\/QApplication>\n#include <QtCore\/QDebug>\n#include <QtCore\/QFile>\n#include <QtGui\/QGraphicsView>\n#include <QtGui\/QGraphicsScene>\n#include <QtGui\/QGraphicsTextItem>\n#include <QtGui\/QTextCursor>\n#include \"kdenlivetitle_wrapper.h\"\n#include <framework\/mlt_producer.h>\nextern \"C\" {\nvoid init_qt (const char* c){\n titleclass=new Title(QString(c));\n}\nvoid refresh_kdenlivetitle( void* buffer, int width, int height , double position){\n titleclass->drawKdenliveTitle(buffer,width,height,position);\n int i=0;\n unsigned char* pointer;\n \/\/rotate bytes for correct order in mlt\n for (i=0;i<width*height*4;i+=4){\n pointer=(unsigned char*)buffer+i;\n pointer[0]=pointer[1];\n pointer[1]=pointer[2];\n pointer[2]=pointer[3];\n pointer[3]=pointer[0];\n }\n}\n}\nTitle::Title(const QString& filename){\n int argc=0;\n char* argv[1];\n argv[0]=\"xxx\"; \n \/\/app=new QApplication(argc,argv);\n app=new QApplication(argc,argv);\n QGraphicsPolygonItem i;\n m_scene=new QGraphicsScene(10,10,100,100);\n loadDocument(filename,&i,&i);\n m_scene->addText(\"hello\");\n m_scene->setSceneRect(0,0,1000,1000);\n \/\/view=new QGraphicsView(scene);\n \/\/view->show();\n qDebug() << filename;\n}\nvoid Title::drawKdenliveTitle(void * buffer ,int width,int height,double position){\n QImage img((uchar*)buffer,width,height,width*4,QImage::Format_ARGB32);\n img.fill(255);\n \/\/qDebug() << \"ja\" << width << height << buffer << position << endl;\n QList<QGraphicsItem*> items=m_scene->items();\n for(int i=0;i<items.size();i++){\n items[i]->moveBy(width*position,width*position); \n }\n \/*\n QPainter p;\n p.begin(&img);\n p.setRenderHints(QPainter::Antialiasing | QPainter::TextAntialiasing | QPainter::HighQualityAntialiasing);\n p.setFont(QFont(\"Arial\",60));\n p.setPen(QPen(QColor(255,255,255)));\n p.drawText(width*.2+width*20*position,height\/2,\"test\");\n p.end();\n*\/\n QPainter p1;\n p1.begin(&img);\n m_scene->render(&p1);\n p1.end();\n}\nint Title::loadDocument(const QString& url, QGraphicsPolygonItem* startv, QGraphicsPolygonItem* endv)\n{\n QDomDocument doc;\n if (!m_scene)\n return -1;\n\n QFile file(url);\n if (file.open(QIODevice::ReadOnly)) {\n qDebug() << \"loaded\";\n doc.setContent(&file, false);\n file.close();\n } \n return loadFromXml(doc, startv, endv);\n}\nint Title::loadFromXml(QDomDocument doc, QGraphicsPolygonItem* \/*startv*\/, QGraphicsPolygonItem* \/*endv*\/)\n{\n QDomNodeList titles = doc.elementsByTagName(\"kdenlivetitle\");\n int maxZValue = 0;\n if (titles.size()) {\n\n QDomNodeList items = titles.item(0).childNodes();\n for (int i = 0; i < items.count(); i++) {\n QGraphicsItem *gitem = NULL;\n int zValue = items.item(i).attributes().namedItem(\"z-index\").nodeValue().toInt();\n if (zValue > -1000) {\n if (items.item(i).attributes().namedItem(\"type\").nodeValue() == \"QGraphicsTextItem\") {\n QDomNamedNodeMap txtProperties = items.item(i).namedItem(\"content\").attributes();\n QFont font(txtProperties.namedItem(\"font\").nodeValue());\n font.setBold(txtProperties.namedItem(\"font-bold\").nodeValue().toInt());\n font.setItalic(txtProperties.namedItem(\"font-italic\").nodeValue().toInt());\n font.setUnderline(txtProperties.namedItem(\"font-underline\").nodeValue().toInt());\n \/\/ Older Kdenlive version did not store pixel size but point size\n if (txtProperties.namedItem(\"font-pixel-size\").isNull()) {\n QFont f2;\n f2.setPointSize(txtProperties.namedItem(\"font-size\").nodeValue().toInt());\n font.setPixelSize(QFontInfo(f2).pixelSize());\n } else\n font.setPixelSize(txtProperties.namedItem(\"font-pixel-size\").nodeValue().toInt());\n QColor col(stringToColor(txtProperties.namedItem(\"font-color\").nodeValue()));\n QGraphicsTextItem *txt = m_scene->addText(items.item(i).namedItem(\"content\").firstChild().nodeValue(), font);\n txt->setDefaultTextColor(col);\n txt->setTextInteractionFlags(Qt::NoTextInteraction);\n if (txtProperties.namedItem(\"alignment\").isNull() == false) {\n txt->setTextWidth(txt->boundingRect().width());\n QTextCursor cur = txt->textCursor();\n QTextBlockFormat format = cur.blockFormat();\n format.setAlignment((Qt::Alignment) txtProperties.namedItem(\"alignment\").nodeValue().toInt());\n cur.select(QTextCursor::Document);\n cur.setBlockFormat(format);\n txt->setTextCursor(cur);\n cur.clearSelection();\n txt->setTextCursor(cur);\n }\n\n if (!txtProperties.namedItem(\"kdenlive-axis-x-inverted\").isNull()) {\n \/\/txt->setData(OriginXLeft, txtProperties.namedItem(\"kdenlive-axis-x-inverted\").nodeValue().toInt());\n }\n if (!txtProperties.namedItem(\"kdenlive-axis-y-inverted\").isNull()) {\n \/\/txt->setData(OriginYTop, txtProperties.namedItem(\"kdenlive-axis-y-inverted\").nodeValue().toInt());\n }\n\n gitem = txt;\n } else if (items.item(i).attributes().namedItem(\"type\").nodeValue() == \"QGraphicsRectItem\") {\n qDebug() << \"rectitem\";\n QString rect = items.item(i).namedItem(\"content\").attributes().namedItem(\"rect\").nodeValue();\n QString br_str = items.item(i).namedItem(\"content\").attributes().namedItem(\"brushcolor\").nodeValue();\n QString pen_str = items.item(i).namedItem(\"content\").attributes().namedItem(\"pencolor\").nodeValue();\n double penwidth = items.item(i).namedItem(\"content\").attributes().namedItem(\"penwidth\").nodeValue().toDouble();\n QGraphicsRectItem *rec = m_scene->addRect(stringToRect(rect), QPen(QBrush(stringToColor(pen_str)), penwidth), QBrush(stringToColor(br_str)));\n gitem = rec;\n } else if (items.item(i).attributes().namedItem(\"type\").nodeValue() == \"QGraphicsPixmapItem\") {\n QString url = items.item(i).namedItem(\"content\").attributes().namedItem(\"url\").nodeValue();\n QPixmap pix(url);\n QGraphicsPixmapItem *rec = m_scene->addPixmap(pix);\n rec->setData(Qt::UserRole, url);\n gitem = rec;\n } else if (items.item(i).attributes().namedItem(\"type\").nodeValue() == \"QGraphicsSvgItem\") {\n QString url = items.item(i).namedItem(\"content\").attributes().namedItem(\"url\").nodeValue();\n \/\/QGraphicsSvgItem *rec = new QGraphicsSvgItem(url);\n \/\/m_scene->addItem(rec);\n \/\/rec->setData(Qt::UserRole, url);\n \/\/gitem = rec;\n }\n }\n \/\/pos and transform\n if (gitem) {\n QPointF p(items.item(i).namedItem(\"position\").attributes().namedItem(\"x\").nodeValue().toDouble(),\n items.item(i).namedItem(\"position\").attributes().namedItem(\"y\").nodeValue().toDouble());\n gitem->setPos(p);\n gitem->setTransform(stringToTransform(items.item(i).namedItem(\"position\").firstChild().firstChild().nodeValue()));\n int zValue = items.item(i).attributes().namedItem(\"z-index\").nodeValue().toInt();\n if (zValue > maxZValue) maxZValue = zValue;\n gitem->setZValue(zValue);\n gitem->setFlags(QGraphicsItem::ItemIsMovable | QGraphicsItem::ItemIsSelectable);\n }\n if (items.item(i).nodeName() == \"background\") {\n QColor color = QColor(stringToColor(items.item(i).attributes().namedItem(\"color\").nodeValue()));\n \/\/color.setAlpha(items.item(i).attributes().namedItem(\"alpha\").nodeValue().toInt());\n QList<QGraphicsItem *> items = m_scene->items();\n for (int i = 0; i < items.size(); i++) {\n if (items.at(i)->zValue() == -1100) {\n ((QGraphicsRectItem *)items.at(i))->setBrush(QBrush(color));\n break;\n }\n }\n } \/*else if (items.item(i).nodeName() == \"startviewport\" && startv) {\n QPointF p(items.item(i).attributes().namedItem(\"x\").nodeValue().toDouble(), items.item(i).attributes().namedItem(\"y\").nodeValue().toDouble());\n double width = items.item(i).attributes().namedItem(\"size\").nodeValue().toDouble();\n QRectF rect(-width, -width \/ aspect_ratio, width*2.0, width \/ aspect_ratio*2.0);\n kDebug() << width << rect;\n startv->setPolygon(rect);\n startv->setPos(p);\n } else if (items.item(i).nodeName() == \"endviewport\" && endv) {\n QPointF p(items.item(i).attributes().namedItem(\"x\").nodeValue().toDouble(), items.item(i).attributes().namedItem(\"y\").nodeValue().toDouble());\n double width = items.item(i).attributes().namedItem(\"size\").nodeValue().toDouble();\n QRectF rect(-width, -width \/ aspect_ratio, width*2.0, width \/ aspect_ratio*2.0);\n kDebug() << width << rect;\n endv->setPolygon(rect);\n endv->setPos(p);\n }*\/\n }\n }\n return maxZValue;\n}\n\nQString Title::colorToString(const QColor& c)\n{\n QString ret = \"%1,%2,%3,%4\";\n ret = ret.arg(c.red()).arg(c.green()).arg(c.blue()).arg(c.alpha());\n return ret;\n}\n\nQString Title::rectFToString(const QRectF& c)\n{\n QString ret = \"%1,%2,%3,%4\";\n ret = ret.arg(c.top()).arg(c.left()).arg(c.width()).arg(c.height());\n return ret;\n}\n\nQRectF Title::stringToRect(const QString & s)\n{\n\n QStringList l = s.split(',');\n if (l.size() < 4)\n return QRectF();\n return QRectF(l.at(0).toDouble(), l.at(1).toDouble(), l.at(2).toDouble(), l.at(3).toDouble()).normalized();\n}\n\nQColor Title::stringToColor(const QString & s)\n{\n QStringList l = s.split(',');\n if (l.size() < 4)\n return QColor();\n return QColor(l.at(0).toInt(), l.at(1).toInt(), l.at(2).toInt(), l.at(3).toInt());;\n}\nQTransform Title::stringToTransform(const QString& s)\n{\n QStringList l = s.split(',');\n if (l.size() < 9)\n return QTransform();\n return QTransform(\n l.at(0).toDouble(), l.at(1).toDouble(), l.at(2).toDouble(),\n l.at(3).toDouble(), l.at(4).toDouble(), l.at(5).toDouble(),\n l.at(6).toDouble(), l.at(7).toDouble(), l.at(8).toDouble()\n );\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n Copyright (C) 2010 George Kiagiadakis <kiagiadakis.george@gmail.com>\n\n This library is free software; you can redistribute it and\/or modify\n it under the terms of the GNU Lesser General Public License as published\n by the Free Software Foundation; either version 2.1 of the License, or\n (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU Lesser General Public License for more details.\n\n You should have received a copy of the GNU Lesser General Public License\n along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n*\/\n#include \"element.h\"\n#include \"pad.h\"\n#include \"query.h\"\n#include \"clock.h\"\n#include \"event.h\"\n#include <gst\/gstelement.h>\n#include <gst\/gstutils.h>\n\nnamespace QGst {\n\nState Element::currentState() const\n{\n State r;\n getState(&r, NULL, 0);\n return r;\n}\n\nState Element::pendingState() const\n{\n State r;\n getState(NULL, &r, 0);\n return r;\n}\n\nStateChangeReturn Element::getState(State *state, State *pending, ClockTime timeout) const\n{\n GstState curState, pendingState;\n GstStateChangeReturn result = gst_element_get_state(object<GstElement>(),\n &curState, &pendingState, timeout);\n if (state) {\n *state = static_cast<State>(curState);\n }\n if (pending) {\n *pending = static_cast<State>(pendingState);\n }\n return static_cast<StateChangeReturn>(result);\n}\n\nStateChangeReturn Element::setState(State state)\n{\n return static_cast<StateChangeReturn>(gst_element_set_state(object<GstElement>(),\n static_cast<GstState>(state)));\n}\n\nbool Element::syncStateWithParent()\n{\n return gst_element_sync_state_with_parent(object<GstElement>());\n}\n\nbool Element::stateIsLocked() const\n{\n return gst_element_is_locked_state(object<GstElement>());\n}\n\nbool Element::setStateLocked(bool locked)\n{\n return gst_element_set_locked_state(object<GstElement>(), locked);\n}\n\nbool Element::addPad(const PadPtr & pad)\n{\n return gst_element_add_pad(object<GstElement>(), pad);\n}\n\nbool Element::removePad(const PadPtr & pad)\n{\n return gst_element_remove_pad(object<GstElement>(), pad);\n}\n\nPadPtr Element::getStaticPad(const char *name)\n{\n GstPad *pad = gst_element_get_static_pad(object<GstElement>(), name);\n return PadPtr::wrap(pad, false);\n}\n\nPadPtr Element::getRequestPad(const char *name)\n{\n GstPad *pad = gst_element_get_request_pad(object<GstElement>(), name);\n return PadPtr::wrap(pad, false);\n}\n\nvoid Element::releaseRequestPad(const PadPtr & pad)\n{\n gst_element_release_request_pad(object<GstElement>(), pad);\n}\n\nbool Element::link(const char *srcPadName, const ElementPtr & dest,\n const char *sinkPadName, const CapsPtr & filter)\n{\n return gst_element_link_pads_filtered(object<GstElement>(), srcPadName,\n dest, sinkPadName, filter);\n}\n\nbool Element::link(const char *srcPadName, const ElementPtr & dest, const CapsPtr & filter)\n{\n return link(srcPadName, dest, NULL, filter);\n}\n\nbool Element::link(const ElementPtr & dest, const char *sinkPadName, const CapsPtr & filter)\n{\n return link(NULL, dest, sinkPadName, filter);\n}\n\nbool Element::link(const ElementPtr & dest, const CapsPtr & filter)\n{\n return link(NULL, dest, NULL, filter);\n}\n\nvoid Element::unlink(const char *srcPadName, const ElementPtr & dest, const char *sinkPadName)\n{\n \/\/FIXME-0.11 This is not entirely correct. Unfortunately I didn't notice\n \/\/that gst_element_unlink_pads requires both pad names when I wrote this\n \/\/function, and it cannot be changed now. For the moment, if the sink\n \/\/pad name is not given, we will assume it is \"sink\".\n if (!sinkPadName) {\n sinkPadName = \"sink\";\n }\n\n gst_element_unlink_pads(object<GstElement>(), srcPadName, dest, sinkPadName);\n}\n\nvoid Element::unlink(const ElementPtr & dest, const char *sinkPadName)\n{\n if (sinkPadName) {\n \/\/FIXME-0.11 This is not entirely correct. Unfortunately I didn't notice\n \/\/that gst_element_unlink_pads requires both pad names when I wrote this\n \/\/function, and it cannot be changed now. For the moment, if the source\n \/\/pad name is not given, we will assume it is \"src\".\n unlink(\"src\", dest, sinkPadName);\n } else {\n gst_element_unlink(object<GstElement>(), dest);\n }\n}\n\nbool Element::query(const QueryPtr & query)\n{\n return gst_element_query(object<GstElement>(), query);\n}\n\nClockPtr Element::clock() const\n{\n if (gst_element_provides_clock(object<GstElement>())) {\n return ClockPtr::wrap(gst_element_get_clock(object<GstElement>()), false);\n } else {\n return ClockPtr();\n }\n}\n\nbool Element::setClock(const ClockPtr & clock)\n{\n return gst_element_set_clock(object<GstElement>(), clock);\n}\n\nbool Element::sendEvent(const EventPtr &event)\n{\n \/\/Sending an event passes ownership of it, so we need to strong ref() it as we still\n \/\/hold a pointer to the object, and will release it when the wrapper is cleared.\n gst_event_ref(event);\n return gst_element_send_event(object<GstElement>(), event);\n}\n\nbool Element::seek(Format format, SeekFlags flags, quint64 position)\n{\n return gst_element_seek_simple(object<GstElement>(), static_cast<GstFormat>(format),\n static_cast<GstSeekFlags>(static_cast<int>(flags)), position);\n}\n\n}\n<commit_msg>src\/QGst\/element.cpp gst_element_provides_clock was removed<commit_after>\/*\n Copyright (C) 2010 George Kiagiadakis <kiagiadakis.george@gmail.com>\n\n This library is free software; you can redistribute it and\/or modify\n it under the terms of the GNU Lesser General Public License as published\n by the Free Software Foundation; either version 2.1 of the License, or\n (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU Lesser General Public License for more details.\n\n You should have received a copy of the GNU Lesser General Public License\n along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n*\/\n#include \"element.h\"\n#include \"pad.h\"\n#include \"query.h\"\n#include \"clock.h\"\n#include \"event.h\"\n#include <gst\/gstelement.h>\n#include <gst\/gstutils.h>\n\nnamespace QGst {\n\nState Element::currentState() const\n{\n State r;\n getState(&r, NULL, 0);\n return r;\n}\n\nState Element::pendingState() const\n{\n State r;\n getState(NULL, &r, 0);\n return r;\n}\n\nStateChangeReturn Element::getState(State *state, State *pending, ClockTime timeout) const\n{\n GstState curState, pendingState;\n GstStateChangeReturn result = gst_element_get_state(object<GstElement>(),\n &curState, &pendingState, timeout);\n if (state) {\n *state = static_cast<State>(curState);\n }\n if (pending) {\n *pending = static_cast<State>(pendingState);\n }\n return static_cast<StateChangeReturn>(result);\n}\n\nStateChangeReturn Element::setState(State state)\n{\n return static_cast<StateChangeReturn>(gst_element_set_state(object<GstElement>(),\n static_cast<GstState>(state)));\n}\n\nbool Element::syncStateWithParent()\n{\n return gst_element_sync_state_with_parent(object<GstElement>());\n}\n\nbool Element::stateIsLocked() const\n{\n return gst_element_is_locked_state(object<GstElement>());\n}\n\nbool Element::setStateLocked(bool locked)\n{\n return gst_element_set_locked_state(object<GstElement>(), locked);\n}\n\nbool Element::addPad(const PadPtr & pad)\n{\n return gst_element_add_pad(object<GstElement>(), pad);\n}\n\nbool Element::removePad(const PadPtr & pad)\n{\n return gst_element_remove_pad(object<GstElement>(), pad);\n}\n\nPadPtr Element::getStaticPad(const char *name)\n{\n GstPad *pad = gst_element_get_static_pad(object<GstElement>(), name);\n return PadPtr::wrap(pad, false);\n}\n\nPadPtr Element::getRequestPad(const char *name)\n{\n GstPad *pad = gst_element_get_request_pad(object<GstElement>(), name);\n return PadPtr::wrap(pad, false);\n}\n\nvoid Element::releaseRequestPad(const PadPtr & pad)\n{\n gst_element_release_request_pad(object<GstElement>(), pad);\n}\n\nbool Element::link(const char *srcPadName, const ElementPtr & dest,\n const char *sinkPadName, const CapsPtr & filter)\n{\n return gst_element_link_pads_filtered(object<GstElement>(), srcPadName,\n dest, sinkPadName, filter);\n}\n\nbool Element::link(const char *srcPadName, const ElementPtr & dest, const CapsPtr & filter)\n{\n return link(srcPadName, dest, NULL, filter);\n}\n\nbool Element::link(const ElementPtr & dest, const char *sinkPadName, const CapsPtr & filter)\n{\n return link(NULL, dest, sinkPadName, filter);\n}\n\nbool Element::link(const ElementPtr & dest, const CapsPtr & filter)\n{\n return link(NULL, dest, NULL, filter);\n}\n\nvoid Element::unlink(const char *srcPadName, const ElementPtr & dest, const char *sinkPadName)\n{\n \/\/FIXME-0.11 This is not entirely correct. Unfortunately I didn't notice\n \/\/that gst_element_unlink_pads requires both pad names when I wrote this\n \/\/function, and it cannot be changed now. For the moment, if the sink\n \/\/pad name is not given, we will assume it is \"sink\".\n if (!sinkPadName) {\n sinkPadName = \"sink\";\n }\n\n gst_element_unlink_pads(object<GstElement>(), srcPadName, dest, sinkPadName);\n}\n\nvoid Element::unlink(const ElementPtr & dest, const char *sinkPadName)\n{\n if (sinkPadName) {\n \/\/FIXME-0.11 This is not entirely correct. Unfortunately I didn't notice\n \/\/that gst_element_unlink_pads requires both pad names when I wrote this\n \/\/function, and it cannot be changed now. For the moment, if the source\n \/\/pad name is not given, we will assume it is \"src\".\n unlink(\"src\", dest, sinkPadName);\n } else {\n gst_element_unlink(object<GstElement>(), dest);\n }\n}\n\nbool Element::query(const QueryPtr & query)\n{\n return gst_element_query(object<GstElement>(), query);\n}\n\nClockPtr Element::clock() const\n{\n return ClockPtr::wrap(gst_element_get_clock(object<GstElement>()), false);\n}\n\nbool Element::setClock(const ClockPtr & clock)\n{\n return gst_element_set_clock(object<GstElement>(), clock);\n}\n\nbool Element::sendEvent(const EventPtr &event)\n{\n \/\/Sending an event passes ownership of it, so we need to strong ref() it as we still\n \/\/hold a pointer to the object, and will release it when the wrapper is cleared.\n gst_event_ref(event);\n return gst_element_send_event(object<GstElement>(), event);\n}\n\nbool Element::seek(Format format, SeekFlags flags, quint64 position)\n{\n return gst_element_seek_simple(object<GstElement>(), static_cast<GstFormat>(format),\n static_cast<GstSeekFlags>(static_cast<int>(flags)), position);\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2016 Yahoo Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.\n\n#include <vespa\/fastos\/fastos.h>\n#include \"documentdbconfigmanager.h\"\n#include <vespa\/log\/log.h>\n#include <vespa\/searchcommon\/common\/schemaconfigurer.h>\n#include <vespa\/searchlib\/index\/schemautil.h>\nLOG_SETUP(\".proton.server.documentdbconfigmanager\");\n#include <vespa\/config\/helper\/legacy.h>\n#include <vespa\/config\/file_acquirer\/file_acquirer.h>\n\nusing namespace config;\nusing namespace vespa::config::search::core;\nusing namespace vespa::config::search::summary;\nusing namespace vespa::config::search;\n\nusing document::DocumentTypeRepo;\nusing search::TuneFileDocumentDB;\nusing search::index::Schema;\nusing search::index::SchemaBuilder;\nusing fastos::TimeStamp;\n\n\/\/ RankingConstantsConfigBuilder\n\/\/ RankingConstantsConfig\n\n\nnamespace proton {\n\nconst ConfigKeySet\nDocumentDBConfigManager::createConfigKeySet() const\n{\n ConfigKeySet set;\n set.add<RankProfilesConfig,\n RankingConstantsConfig,\n IndexschemaConfig,\n AttributesConfig,\n SummaryConfig,\n SummarymapConfig,\n JuniperrcConfig>(_configId);\n set.add(_extraConfigKeys);\n return set;\n}\n\nSchema::SP\nDocumentDBConfigManager::\nbuildNewSchema(const AttributesConfig & newAttributesConfig,\n const SummaryConfig & newSummaryConfig,\n const IndexschemaConfig & newIndexschemaConfig)\n{\n \/\/ Called with lock held\n Schema::SP schema(new Schema);\n SchemaBuilder::build(newAttributesConfig, *schema);\n SchemaBuilder::build(newSummaryConfig, *schema);\n SchemaBuilder::build(newIndexschemaConfig, *schema);\n return schema;\n}\n\n\nSchema::SP\nDocumentDBConfigManager::\nbuildSchema(const AttributesConfig & newAttributesConfig,\n const SummaryConfig & newSummaryConfig,\n const IndexschemaConfig & newIndexschemaConfig)\n{\n \/\/ Called with lock held\n Schema::SP oldSchema;\n if (_pendingConfigSnapshot.get() != NULL)\n oldSchema = _pendingConfigSnapshot->getSchemaSP();\n if (oldSchema.get() == NULL)\n return buildNewSchema(newAttributesConfig,\n newSummaryConfig, newIndexschemaConfig);\n const DocumentDBConfig &old = *_pendingConfigSnapshot;\n if (old.getAttributesConfig() != newAttributesConfig ||\n old.getSummaryConfig() != newSummaryConfig ||\n old.getIndexschemaConfig() != newIndexschemaConfig) {\n Schema::SP schema(buildNewSchema(newAttributesConfig,\n newSummaryConfig, newIndexschemaConfig));\n return (*oldSchema == *schema) ? oldSchema : schema;\n }\n return oldSchema;\n}\n\n\nstatic DocumentDBMaintenanceConfig::SP\nbuildMaintenanceConfig(const BootstrapConfig::SP &bootstrapConfig,\n const vespalib::string &docTypeName)\n{\n typedef ProtonConfig::Documentdb DdbConfig;\n ProtonConfig &proton(bootstrapConfig->getProtonConfig());\n\n TimeStamp visibilityDelay;\n \/\/ Use document type to find document db config in proton config\n uint32_t index;\n for (index = 0; index < proton.documentdb.size(); ++index) {\n const DdbConfig &ddbConfig = proton.documentdb[index];\n if (docTypeName == ddbConfig.inputdoctypename)\n break;\n }\n double pruneRemovedDocumentsInterval = proton.pruneremoveddocumentsinterval;\n double pruneRemovedDocumentsAge = proton.pruneremoveddocumentsage;\n\n if (index < proton.documentdb.size()) {\n const DdbConfig &ddbConfig = proton.documentdb[index];\n visibilityDelay = TimeStamp::Seconds(std::min(proton.maxvisibilitydelay, ddbConfig.visibilitydelay));\n }\n return DocumentDBMaintenanceConfig::SP(\n new DocumentDBMaintenanceConfig(\n DocumentDBPruneRemovedDocumentsConfig(\n pruneRemovedDocumentsInterval,\n pruneRemovedDocumentsAge),\n DocumentDBHeartBeatConfig(),\n DocumentDBWipeOldRemovedFieldsConfig(\n proton.wipeoldremovedfieldsinterval,\n proton.wipeoldremovedfieldsage),\n proton.grouping.sessionmanager.pruning.interval,\n visibilityDelay,\n DocumentDBLidSpaceCompactionConfig(\n proton.lidspacecompaction.interval,\n proton.lidspacecompaction.allowedlidbloat,\n proton.lidspacecompaction.allowedlidbloatfactor),\n AttributeUsageFilterConfig(\n proton.writefilter.attribute.enumstorelimit,\n proton.writefilter.attribute.multivaluelimit),\n proton.writefilter.sampleinterval));\n}\n\n\nvoid\nDocumentDBConfigManager::update(const ConfigSnapshot & snapshot)\n{\n typedef DocumentDBConfig::RankProfilesConfigSP RankProfilesConfigSP;\n typedef DocumentDBConfig::RankingConstantsConfigSP RankingConstantsConfigSP;\n typedef DocumentDBConfig::IndexschemaConfigSP IndexschemaConfigSP;\n typedef DocumentDBConfig::AttributesConfigSP AttributesConfigSP;\n typedef DocumentDBConfig::SummaryConfigSP SummaryConfigSP;\n typedef DocumentDBConfig::SummarymapConfigSP SummarymapConfigSP;\n typedef DocumentDBConfig::JuniperrcConfigSP JuniperrcConfigSP;\n typedef DocumentDBConfig::MaintenanceConfigSP MaintenanceConfigSP;\n\n DocumentDBConfig::SP current = _pendingConfigSnapshot;\n RankProfilesConfigSP newRankProfilesConfig;\n RankingConstantsConfigSP newRankingConstantsConfig;\n IndexschemaConfigSP newIndexschemaConfig;\n AttributesConfigSP newAttributesConfig;\n SummaryConfigSP newSummaryConfig;\n SummarymapConfigSP newSummarymapConfig;\n JuniperrcConfigSP newJuniperrcConfig;\n MaintenanceConfigSP oldMaintenanceConfig;\n MaintenanceConfigSP newMaintenanceConfig;\n\n if (!_ignoreForwardedConfig) {\n if (_bootstrapConfig->getDocumenttypesConfigSP().get() == NULL ||\n _bootstrapConfig->getDocumentTypeRepoSP().get() == NULL ||\n _bootstrapConfig->getProtonConfigSP().get() == NULL ||\n _bootstrapConfig->getTuneFileDocumentDBSP().get() == NULL)\n return;\n }\n\n\n int64_t generation = snapshot.getGeneration();\n LOG(debug,\n \"Forwarded generation %\" PRId64 \", generation %\" PRId64,\n _bootstrapConfig->getGeneration(), generation);\n if (!_ignoreForwardedConfig &&\n _bootstrapConfig->getGeneration() != generation)\n return;\n\n int64_t currentGeneration = -1;\n if (current.get() != NULL) {\n newRankProfilesConfig = current->getRankProfilesConfigSP();\n newRankingConstantsConfig = current->getRankingConstantsConfigSP();\n newIndexschemaConfig = current->getIndexschemaConfigSP();\n newAttributesConfig = current->getAttributesConfigSP();\n newSummaryConfig = current->getSummaryConfigSP();\n newSummarymapConfig = current->getSummarymapConfigSP();\n newJuniperrcConfig = current->getJuniperrcConfigSP();\n oldMaintenanceConfig = current->getMaintenanceConfigSP();\n currentGeneration = current->getGeneration();\n }\n\n if (snapshot.isChanged<RankProfilesConfig>(_configId, currentGeneration)) {\n newRankProfilesConfig =\n RankProfilesConfigSP(\n snapshot.getConfig<RankProfilesConfig>(_configId).\n release());\n }\n if (snapshot.isChanged<RankingConstantsConfig>(_configId, currentGeneration)) {\n newRankingConstantsConfig = \n RankingConstantsConfigSP(\n snapshot.getConfig<RankingConstantsConfig>(_configId)\n .release());\n const vespalib::string &spec = _bootstrapConfig->getFiledistributorrpcConfig().connectionspec;\n if (spec != \"\") {\n config::RpcFileAcquirer fileAcquirer(spec);\n for (const RankingConstantsConfig::Constant &rc : newRankingConstantsConfig->constant) {\n vespalib::string filePath = fileAcquirer.wait_for(rc.fileref, 5*60);\n fprintf(stderr, \"GOT file-acq PATH is: %s (ref %s for name %s type %s)\\n\",\n filePath.c_str(), rc.fileref.c_str(), rc.name.c_str(), rc.type.c_str());\n }\n }\n }\n if (snapshot.isChanged<IndexschemaConfig>(_configId, currentGeneration)) {\n std::unique_ptr<IndexschemaConfig> indexschemaConfig =\n snapshot.getConfig<IndexschemaConfig>(_configId);\n search::index::Schema schema;\n search::index::SchemaBuilder::build(*indexschemaConfig, schema);\n if (!search::index::SchemaUtil::validateSchema(schema)) {\n LOG(error,\n \"Cannot use bad index schema, validation failed\");\n abort();\n }\n newIndexschemaConfig =\n IndexschemaConfigSP(indexschemaConfig.release());\n }\n if (snapshot.isChanged<AttributesConfig>(_configId, currentGeneration))\n newAttributesConfig =\n AttributesConfigSP(snapshot.getConfig<AttributesConfig>(_configId).\n release());\n if (snapshot.isChanged<SummaryConfig>(_configId, currentGeneration))\n newSummaryConfig =\n SummaryConfigSP(snapshot.getConfig<SummaryConfig>(_configId).\n release());\n if (snapshot.isChanged<SummarymapConfig>(_configId, currentGeneration))\n newSummarymapConfig =\n SummarymapConfigSP(snapshot.getConfig<SummarymapConfig>(_configId).\n release());\n if (snapshot.isChanged<JuniperrcConfig>(_configId, currentGeneration))\n newJuniperrcConfig =\n JuniperrcConfigSP(\n snapshot.getConfig<JuniperrcConfig>(_configId).release());\n\n Schema::SP schema(buildSchema(*newAttributesConfig,\n *newSummaryConfig,\n *newIndexschemaConfig));\n newMaintenanceConfig = buildMaintenanceConfig(_bootstrapConfig,\n _docTypeName);\n if (newMaintenanceConfig.get() != NULL &&\n oldMaintenanceConfig.get() != NULL &&\n *newMaintenanceConfig == *oldMaintenanceConfig) {\n newMaintenanceConfig = oldMaintenanceConfig;\n }\n ConfigSnapshot extraConfigs(snapshot.subset(_extraConfigKeys));\n DocumentDBConfig::SP newSnapshot(\n new DocumentDBConfig(generation,\n newRankProfilesConfig,\n newRankingConstantsConfig,\n newIndexschemaConfig,\n newAttributesConfig,\n newSummaryConfig,\n newSummarymapConfig,\n newJuniperrcConfig,\n _bootstrapConfig->getDocumenttypesConfigSP(),\n _bootstrapConfig->getDocumentTypeRepoSP(),\n _bootstrapConfig->getTuneFileDocumentDBSP(),\n schema,\n newMaintenanceConfig,\n _configId,\n _docTypeName,\n extraConfigs));\n assert(newSnapshot->valid());\n {\n vespalib::LockGuard lock(_pendingConfigLock);\n _pendingConfigSnapshot = newSnapshot;\n }\n}\n\n\nDocumentDBConfigManager::\nDocumentDBConfigManager(const vespalib::string &configId,\n const vespalib::string &docTypeName)\n : _configId(configId),\n _docTypeName(docTypeName),\n _bootstrapConfig(),\n _pendingConfigSnapshot(),\n _ignoreForwardedConfig(true),\n _pendingConfigLock(),\n _extraConfigKeys()\n{\n}\n\nvoid\nDocumentDBConfigManager::\nforwardConfig(const BootstrapConfig::SP & config)\n{\n {\n if (!_ignoreForwardedConfig &&\n config->getGeneration() < _bootstrapConfig->getGeneration())\n return;\t\/\/ Enforce time direction\n _bootstrapConfig = config;\n _ignoreForwardedConfig = false;\n }\n}\n\n} \/\/ namespace proton\n<commit_msg>use LOG not fprintf<commit_after>\/\/ Copyright 2016 Yahoo Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.\n\n#include <vespa\/fastos\/fastos.h>\n#include \"documentdbconfigmanager.h\"\n#include <vespa\/log\/log.h>\n#include <vespa\/searchcommon\/common\/schemaconfigurer.h>\n#include <vespa\/searchlib\/index\/schemautil.h>\nLOG_SETUP(\".proton.server.documentdbconfigmanager\");\n#include <vespa\/config\/helper\/legacy.h>\n#include <vespa\/config\/file_acquirer\/file_acquirer.h>\n\nusing namespace config;\nusing namespace vespa::config::search::core;\nusing namespace vespa::config::search::summary;\nusing namespace vespa::config::search;\n\nusing document::DocumentTypeRepo;\nusing search::TuneFileDocumentDB;\nusing search::index::Schema;\nusing search::index::SchemaBuilder;\nusing fastos::TimeStamp;\n\nnamespace proton {\n\nconst ConfigKeySet\nDocumentDBConfigManager::createConfigKeySet() const\n{\n ConfigKeySet set;\n set.add<RankProfilesConfig,\n RankingConstantsConfig,\n IndexschemaConfig,\n AttributesConfig,\n SummaryConfig,\n SummarymapConfig,\n JuniperrcConfig>(_configId);\n set.add(_extraConfigKeys);\n return set;\n}\n\nSchema::SP\nDocumentDBConfigManager::\nbuildNewSchema(const AttributesConfig & newAttributesConfig,\n const SummaryConfig & newSummaryConfig,\n const IndexschemaConfig & newIndexschemaConfig)\n{\n \/\/ Called with lock held\n Schema::SP schema(new Schema);\n SchemaBuilder::build(newAttributesConfig, *schema);\n SchemaBuilder::build(newSummaryConfig, *schema);\n SchemaBuilder::build(newIndexschemaConfig, *schema);\n return schema;\n}\n\n\nSchema::SP\nDocumentDBConfigManager::\nbuildSchema(const AttributesConfig & newAttributesConfig,\n const SummaryConfig & newSummaryConfig,\n const IndexschemaConfig & newIndexschemaConfig)\n{\n \/\/ Called with lock held\n Schema::SP oldSchema;\n if (_pendingConfigSnapshot.get() != NULL)\n oldSchema = _pendingConfigSnapshot->getSchemaSP();\n if (oldSchema.get() == NULL)\n return buildNewSchema(newAttributesConfig,\n newSummaryConfig, newIndexschemaConfig);\n const DocumentDBConfig &old = *_pendingConfigSnapshot;\n if (old.getAttributesConfig() != newAttributesConfig ||\n old.getSummaryConfig() != newSummaryConfig ||\n old.getIndexschemaConfig() != newIndexschemaConfig) {\n Schema::SP schema(buildNewSchema(newAttributesConfig,\n newSummaryConfig, newIndexschemaConfig));\n return (*oldSchema == *schema) ? oldSchema : schema;\n }\n return oldSchema;\n}\n\n\nstatic DocumentDBMaintenanceConfig::SP\nbuildMaintenanceConfig(const BootstrapConfig::SP &bootstrapConfig,\n const vespalib::string &docTypeName)\n{\n typedef ProtonConfig::Documentdb DdbConfig;\n ProtonConfig &proton(bootstrapConfig->getProtonConfig());\n\n TimeStamp visibilityDelay;\n \/\/ Use document type to find document db config in proton config\n uint32_t index;\n for (index = 0; index < proton.documentdb.size(); ++index) {\n const DdbConfig &ddbConfig = proton.documentdb[index];\n if (docTypeName == ddbConfig.inputdoctypename)\n break;\n }\n double pruneRemovedDocumentsInterval = proton.pruneremoveddocumentsinterval;\n double pruneRemovedDocumentsAge = proton.pruneremoveddocumentsage;\n\n if (index < proton.documentdb.size()) {\n const DdbConfig &ddbConfig = proton.documentdb[index];\n visibilityDelay = TimeStamp::Seconds(std::min(proton.maxvisibilitydelay, ddbConfig.visibilitydelay));\n }\n return DocumentDBMaintenanceConfig::SP(\n new DocumentDBMaintenanceConfig(\n DocumentDBPruneRemovedDocumentsConfig(\n pruneRemovedDocumentsInterval,\n pruneRemovedDocumentsAge),\n DocumentDBHeartBeatConfig(),\n DocumentDBWipeOldRemovedFieldsConfig(\n proton.wipeoldremovedfieldsinterval,\n proton.wipeoldremovedfieldsage),\n proton.grouping.sessionmanager.pruning.interval,\n visibilityDelay,\n DocumentDBLidSpaceCompactionConfig(\n proton.lidspacecompaction.interval,\n proton.lidspacecompaction.allowedlidbloat,\n proton.lidspacecompaction.allowedlidbloatfactor),\n AttributeUsageFilterConfig(\n proton.writefilter.attribute.enumstorelimit,\n proton.writefilter.attribute.multivaluelimit),\n proton.writefilter.sampleinterval));\n}\n\n\nvoid\nDocumentDBConfigManager::update(const ConfigSnapshot & snapshot)\n{\n typedef DocumentDBConfig::RankProfilesConfigSP RankProfilesConfigSP;\n typedef DocumentDBConfig::RankingConstantsConfigSP RankingConstantsConfigSP;\n typedef DocumentDBConfig::IndexschemaConfigSP IndexschemaConfigSP;\n typedef DocumentDBConfig::AttributesConfigSP AttributesConfigSP;\n typedef DocumentDBConfig::SummaryConfigSP SummaryConfigSP;\n typedef DocumentDBConfig::SummarymapConfigSP SummarymapConfigSP;\n typedef DocumentDBConfig::JuniperrcConfigSP JuniperrcConfigSP;\n typedef DocumentDBConfig::MaintenanceConfigSP MaintenanceConfigSP;\n\n DocumentDBConfig::SP current = _pendingConfigSnapshot;\n RankProfilesConfigSP newRankProfilesConfig;\n RankingConstantsConfigSP newRankingConstantsConfig;\n IndexschemaConfigSP newIndexschemaConfig;\n AttributesConfigSP newAttributesConfig;\n SummaryConfigSP newSummaryConfig;\n SummarymapConfigSP newSummarymapConfig;\n JuniperrcConfigSP newJuniperrcConfig;\n MaintenanceConfigSP oldMaintenanceConfig;\n MaintenanceConfigSP newMaintenanceConfig;\n\n if (!_ignoreForwardedConfig) {\n if (_bootstrapConfig->getDocumenttypesConfigSP().get() == NULL ||\n _bootstrapConfig->getDocumentTypeRepoSP().get() == NULL ||\n _bootstrapConfig->getProtonConfigSP().get() == NULL ||\n _bootstrapConfig->getTuneFileDocumentDBSP().get() == NULL)\n return;\n }\n\n\n int64_t generation = snapshot.getGeneration();\n LOG(debug,\n \"Forwarded generation %\" PRId64 \", generation %\" PRId64,\n _bootstrapConfig->getGeneration(), generation);\n if (!_ignoreForwardedConfig &&\n _bootstrapConfig->getGeneration() != generation)\n return;\n\n int64_t currentGeneration = -1;\n if (current.get() != NULL) {\n newRankProfilesConfig = current->getRankProfilesConfigSP();\n newRankingConstantsConfig = current->getRankingConstantsConfigSP();\n newIndexschemaConfig = current->getIndexschemaConfigSP();\n newAttributesConfig = current->getAttributesConfigSP();\n newSummaryConfig = current->getSummaryConfigSP();\n newSummarymapConfig = current->getSummarymapConfigSP();\n newJuniperrcConfig = current->getJuniperrcConfigSP();\n oldMaintenanceConfig = current->getMaintenanceConfigSP();\n currentGeneration = current->getGeneration();\n }\n\n if (snapshot.isChanged<RankProfilesConfig>(_configId, currentGeneration)) {\n newRankProfilesConfig =\n RankProfilesConfigSP(\n snapshot.getConfig<RankProfilesConfig>(_configId).\n release());\n }\n if (snapshot.isChanged<RankingConstantsConfig>(_configId, currentGeneration)) {\n newRankingConstantsConfig =\n RankingConstantsConfigSP(\n snapshot.getConfig<RankingConstantsConfig>(_configId)\n .release());\n const vespalib::string &spec = _bootstrapConfig->getFiledistributorrpcConfig().connectionspec;\n if (spec != \"\") {\n config::RpcFileAcquirer fileAcquirer(spec);\n for (const RankingConstantsConfig::Constant &rc : newRankingConstantsConfig->constant) {\n vespalib::string filePath = fileAcquirer.wait_for(rc.fileref, 5*60);\n LOG(info, \"GOT file-acq PATH is: %s (ref %s for name %s type %s)\\n\",\n filePath.c_str(), rc.fileref.c_str(), rc.name.c_str(), rc.type.c_str());\n }\n }\n }\n if (snapshot.isChanged<IndexschemaConfig>(_configId, currentGeneration)) {\n std::unique_ptr<IndexschemaConfig> indexschemaConfig =\n snapshot.getConfig<IndexschemaConfig>(_configId);\n search::index::Schema schema;\n search::index::SchemaBuilder::build(*indexschemaConfig, schema);\n if (!search::index::SchemaUtil::validateSchema(schema)) {\n LOG(error,\n \"Cannot use bad index schema, validation failed\");\n abort();\n }\n newIndexschemaConfig =\n IndexschemaConfigSP(indexschemaConfig.release());\n }\n if (snapshot.isChanged<AttributesConfig>(_configId, currentGeneration))\n newAttributesConfig =\n AttributesConfigSP(snapshot.getConfig<AttributesConfig>(_configId).\n release());\n if (snapshot.isChanged<SummaryConfig>(_configId, currentGeneration))\n newSummaryConfig =\n SummaryConfigSP(snapshot.getConfig<SummaryConfig>(_configId).\n release());\n if (snapshot.isChanged<SummarymapConfig>(_configId, currentGeneration))\n newSummarymapConfig =\n SummarymapConfigSP(snapshot.getConfig<SummarymapConfig>(_configId).\n release());\n if (snapshot.isChanged<JuniperrcConfig>(_configId, currentGeneration))\n newJuniperrcConfig =\n JuniperrcConfigSP(\n snapshot.getConfig<JuniperrcConfig>(_configId).release());\n\n Schema::SP schema(buildSchema(*newAttributesConfig,\n *newSummaryConfig,\n *newIndexschemaConfig));\n newMaintenanceConfig = buildMaintenanceConfig(_bootstrapConfig,\n _docTypeName);\n if (newMaintenanceConfig.get() != NULL &&\n oldMaintenanceConfig.get() != NULL &&\n *newMaintenanceConfig == *oldMaintenanceConfig) {\n newMaintenanceConfig = oldMaintenanceConfig;\n }\n ConfigSnapshot extraConfigs(snapshot.subset(_extraConfigKeys));\n DocumentDBConfig::SP newSnapshot(\n new DocumentDBConfig(generation,\n newRankProfilesConfig,\n newRankingConstantsConfig,\n newIndexschemaConfig,\n newAttributesConfig,\n newSummaryConfig,\n newSummarymapConfig,\n newJuniperrcConfig,\n _bootstrapConfig->getDocumenttypesConfigSP(),\n _bootstrapConfig->getDocumentTypeRepoSP(),\n _bootstrapConfig->getTuneFileDocumentDBSP(),\n schema,\n newMaintenanceConfig,\n _configId,\n _docTypeName,\n extraConfigs));\n assert(newSnapshot->valid());\n {\n vespalib::LockGuard lock(_pendingConfigLock);\n _pendingConfigSnapshot = newSnapshot;\n }\n}\n\n\nDocumentDBConfigManager::\nDocumentDBConfigManager(const vespalib::string &configId,\n const vespalib::string &docTypeName)\n : _configId(configId),\n _docTypeName(docTypeName),\n _bootstrapConfig(),\n _pendingConfigSnapshot(),\n _ignoreForwardedConfig(true),\n _pendingConfigLock(),\n _extraConfigKeys()\n{\n}\n\nvoid\nDocumentDBConfigManager::\nforwardConfig(const BootstrapConfig::SP & config)\n{\n {\n if (!_ignoreForwardedConfig &&\n config->getGeneration() < _bootstrapConfig->getGeneration())\n return;\t\/\/ Enforce time direction\n _bootstrapConfig = config;\n _ignoreForwardedConfig = false;\n }\n}\n\n} \/\/ namespace proton\n<|endoftext|>"} {"text":"<commit_before>#ifndef ENTT_ENTITY_HELPER_HPP\n#define ENTT_ENTITY_HELPER_HPP\n\n#include <type_traits>\n#include \"..\/config\/config.h\"\n#include \"..\/core\/fwd.hpp\"\n#include \"..\/core\/type_traits.hpp\"\n#include \"..\/signal\/delegate.hpp\"\n#include \"fwd.hpp\"\n#include \"registry.hpp\"\n\nnamespace entt {\n\n\/**\n * @brief Converts a registry to a view.\n * @tparam Entity A valid entity type (see entt_traits for more details).\n *\/\ntemplate<typename Entity>\nstruct as_view {\n \/*! @brief Underlying entity identifier. *\/\n using entity_type = std::remove_const_t<Entity>;\n \/*! @brief Type of registry to convert. *\/\n using registry_type = constness_as_t<basic_registry<entity_type>, Entity>;\n\n \/**\n * @brief Constructs a converter for a given registry.\n * @param source A valid reference to a registry.\n *\/\n as_view(registry_type &source) noexcept\n : reg{source} {}\n\n \/**\n * @brief Conversion function from a registry to a view.\n * @tparam Exclude Types of components used to filter the view.\n * @tparam Component Type of components used to construct the view.\n * @return A newly created view.\n *\/\n template<typename Exclude, typename... Component>\n operator basic_view<entity_type, get_t<Component...>, Exclude>() const {\n return reg.template view<Component...>(Exclude{});\n }\n\nprivate:\n registry_type ®\n};\n\n\/**\n * @brief Deduction guide.\n * @tparam Entity A valid entity type (see entt_traits for more details).\n *\/\ntemplate<typename Entity>\nas_view(basic_registry<Entity> &) -> as_view<Entity>;\n\n\/**\n * @brief Deduction guide.\n * @tparam Entity A valid entity type (see entt_traits for more details).\n *\/\ntemplate<typename Entity>\nas_view(const basic_registry<Entity> &) -> as_view<const Entity>;\n\n\/**\n * @brief Converts a registry to a group.\n * @tparam Entity A valid entity type (see entt_traits for more details).\n *\/\ntemplate<typename Entity>\nstruct as_group {\n \/*! @brief Underlying entity identifier. *\/\n using entity_type = std::remove_const_t<Entity>;\n \/*! @brief Type of registry to convert. *\/\n using registry_type = constness_as_t<basic_registry<entity_type>, Entity>;\n\n \/**\n * @brief Constructs a converter for a given registry.\n * @param source A valid reference to a registry.\n *\/\n as_group(registry_type &source) noexcept\n : reg{source} {}\n\n \/**\n * @brief Conversion function from a registry to a group.\n * @tparam Get Types of components observed by the group.\n * @tparam Exclude Types of components used to filter the group.\n * @tparam Owned Types of components owned by the group.\n * @return A newly created group.\n *\/\n template<typename Get, typename Exclude, typename... Owned>\n operator basic_group<entity_type, owned_t<Owned...>, Get, Exclude>() const {\n if constexpr(std::is_const_v<registry_type>) {\n return reg.template group_if_exists<Owned...>(Get{}, Exclude{});\n } else {\n return reg.template group<Owned...>(Get{}, Exclude{});\n }\n }\n\nprivate:\n registry_type ®\n};\n\n\/**\n * @brief Deduction guide.\n * @tparam Entity A valid entity type (see entt_traits for more details).\n *\/\ntemplate<typename Entity>\nas_group(basic_registry<Entity> &) -> as_group<Entity>;\n\n\/**\n * @brief Deduction guide.\n * @tparam Entity A valid entity type (see entt_traits for more details).\n *\/\ntemplate<typename Entity>\nas_group(const basic_registry<Entity> &) -> as_group<const Entity>;\n\n\/**\n * @brief Helper to create a listener that directly invokes a member function.\n * @tparam Member Member function to invoke on a component of the given type.\n * @tparam Entity A valid entity type (see entt_traits for more details).\n * @param reg A registry that contains the given entity and its components.\n * @param entt Entity from which to get the component.\n *\/\ntemplate<auto Member, typename Entity = entity>\nvoid invoke(basic_registry<Entity> ®, const Entity entt) {\n static_assert(std::is_member_function_pointer_v<decltype(Member)>, \"Invalid pointer to non-static member function\");\n delegate<void(basic_registry<Entity> &, const Entity)> func;\n func.template connect<Member>(reg.template get<member_class_t<decltype(Member)>>(entt));\n func(reg, entt);\n}\n\n\/**\n * @brief Returns the entity associated with a given component.\n *\n * @warning\n * Currently, this function only works correctly with the default pool as it\n * makes assumptions about how the components are laid out.\n *\n * @tparam Entity A valid entity type (see entt_traits for more details).\n * @tparam Component Type of component.\n * @param reg A registry that contains the given entity and its components.\n * @param instance A valid component instance.\n * @return The entity associated with the given component.\n *\/\ntemplate<typename Entity, typename Component>\nEntity to_entity(const basic_registry<Entity> ®, const Component &instance) {\n const auto &storage = reg.template storage<Component>();\n const typename basic_registry<Entity>::base_type &base = storage;\n const auto *addr = std::addressof(instance);\n\n for(auto it = base.rbegin(), last = base.rend(); it < last; it += ENTT_PACKED_PAGE) {\n if(const auto dist = (addr - std::addressof(storage.get(*it))); dist >= 0 && dist < ENTT_PACKED_PAGE) {\n return *(it + dist);\n }\n }\n\n return null;\n}\n\n} \/\/ namespace entt\n\n#endif\n<commit_msg>helper: use the right page size in all cases<commit_after>#ifndef ENTT_ENTITY_HELPER_HPP\n#define ENTT_ENTITY_HELPER_HPP\n\n#include <type_traits>\n#include \"..\/core\/fwd.hpp\"\n#include \"..\/core\/type_traits.hpp\"\n#include \"..\/signal\/delegate.hpp\"\n#include \"component.hpp\"\n#include \"fwd.hpp\"\n#include \"registry.hpp\"\n\nnamespace entt {\n\n\/**\n * @brief Converts a registry to a view.\n * @tparam Entity A valid entity type (see entt_traits for more details).\n *\/\ntemplate<typename Entity>\nstruct as_view {\n \/*! @brief Underlying entity identifier. *\/\n using entity_type = std::remove_const_t<Entity>;\n \/*! @brief Type of registry to convert. *\/\n using registry_type = constness_as_t<basic_registry<entity_type>, Entity>;\n\n \/**\n * @brief Constructs a converter for a given registry.\n * @param source A valid reference to a registry.\n *\/\n as_view(registry_type &source) noexcept\n : reg{source} {}\n\n \/**\n * @brief Conversion function from a registry to a view.\n * @tparam Exclude Types of components used to filter the view.\n * @tparam Component Type of components used to construct the view.\n * @return A newly created view.\n *\/\n template<typename Exclude, typename... Component>\n operator basic_view<entity_type, get_t<Component...>, Exclude>() const {\n return reg.template view<Component...>(Exclude{});\n }\n\nprivate:\n registry_type ®\n};\n\n\/**\n * @brief Deduction guide.\n * @tparam Entity A valid entity type (see entt_traits for more details).\n *\/\ntemplate<typename Entity>\nas_view(basic_registry<Entity> &) -> as_view<Entity>;\n\n\/**\n * @brief Deduction guide.\n * @tparam Entity A valid entity type (see entt_traits for more details).\n *\/\ntemplate<typename Entity>\nas_view(const basic_registry<Entity> &) -> as_view<const Entity>;\n\n\/**\n * @brief Converts a registry to a group.\n * @tparam Entity A valid entity type (see entt_traits for more details).\n *\/\ntemplate<typename Entity>\nstruct as_group {\n \/*! @brief Underlying entity identifier. *\/\n using entity_type = std::remove_const_t<Entity>;\n \/*! @brief Type of registry to convert. *\/\n using registry_type = constness_as_t<basic_registry<entity_type>, Entity>;\n\n \/**\n * @brief Constructs a converter for a given registry.\n * @param source A valid reference to a registry.\n *\/\n as_group(registry_type &source) noexcept\n : reg{source} {}\n\n \/**\n * @brief Conversion function from a registry to a group.\n * @tparam Get Types of components observed by the group.\n * @tparam Exclude Types of components used to filter the group.\n * @tparam Owned Types of components owned by the group.\n * @return A newly created group.\n *\/\n template<typename Get, typename Exclude, typename... Owned>\n operator basic_group<entity_type, owned_t<Owned...>, Get, Exclude>() const {\n if constexpr(std::is_const_v<registry_type>) {\n return reg.template group_if_exists<Owned...>(Get{}, Exclude{});\n } else {\n return reg.template group<Owned...>(Get{}, Exclude{});\n }\n }\n\nprivate:\n registry_type ®\n};\n\n\/**\n * @brief Deduction guide.\n * @tparam Entity A valid entity type (see entt_traits for more details).\n *\/\ntemplate<typename Entity>\nas_group(basic_registry<Entity> &) -> as_group<Entity>;\n\n\/**\n * @brief Deduction guide.\n * @tparam Entity A valid entity type (see entt_traits for more details).\n *\/\ntemplate<typename Entity>\nas_group(const basic_registry<Entity> &) -> as_group<const Entity>;\n\n\/**\n * @brief Helper to create a listener that directly invokes a member function.\n * @tparam Member Member function to invoke on a component of the given type.\n * @tparam Entity A valid entity type (see entt_traits for more details).\n * @param reg A registry that contains the given entity and its components.\n * @param entt Entity from which to get the component.\n *\/\ntemplate<auto Member, typename Entity = entity>\nvoid invoke(basic_registry<Entity> ®, const Entity entt) {\n static_assert(std::is_member_function_pointer_v<decltype(Member)>, \"Invalid pointer to non-static member function\");\n delegate<void(basic_registry<Entity> &, const Entity)> func;\n func.template connect<Member>(reg.template get<member_class_t<decltype(Member)>>(entt));\n func(reg, entt);\n}\n\n\/**\n * @brief Returns the entity associated with a given component.\n *\n * @warning\n * Currently, this function only works correctly with the default pool as it\n * makes assumptions about how the components are laid out.\n *\n * @tparam Entity A valid entity type (see entt_traits for more details).\n * @tparam Component Type of component.\n * @param reg A registry that contains the given entity and its components.\n * @param instance A valid component instance.\n * @return The entity associated with the given component.\n *\/\ntemplate<typename Entity, typename Component>\nEntity to_entity(const basic_registry<Entity> ®, const Component &instance) {\n const auto &storage = reg.template storage<Component>();\n const typename basic_registry<Entity>::base_type &base = storage;\n const auto *addr = std::addressof(instance);\n\n for(auto it = base.rbegin(), last = base.rend(); it < last; it += component_traits<Component>::page_size) {\n if(const auto dist = (addr - std::addressof(storage.get(*it))); dist >= 0 && dist < component_traits<Component>::page_size) {\n return *(it + dist);\n }\n }\n\n return null;\n}\n\n} \/\/ namespace entt\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/***************************************************************************\n**\n** Copyright (C) 2010 Nokia Corporation and\/or its subsidiary(-ies).\n** All rights reserved.\n** Contact: Karoliina T. Salminen <karoliina.t.salminen@nokia.com>\n**\n** This file is part of duicontrolpanel.\n**\n**\n** This library is free software; you can redistribute it and\/or\n** modify it under the terms of the GNU Lesser General Public\n** License version 2.1 as published by the Free Software Foundation\n** and appearing in the file LICENSE.LGPL included in the packaging\n** of this file.\n**\n****************************************************************************\/\n\n#include <QObject>\n#include <QByteArray>\n\n#include <DcpApplet>\n#include <DcpWidgetTypes>\n\n#include <dcpappletmetadata.h>\n#include <dcpappletmetadata_p.h>\n\n#include \"ut_dcpappletmetadata.h\"\n#include \"filedatas.h\"\n#include \"dcpmostusedcounter.h\"\n\nvoid Ut_DcpAppletMetadata::initTestCase()\n{\n static int c = 0;\n static QByteArray arg(\"dummyarg\");\n char *argp = arg.data();\n qap = new QCoreApplication(c, &argp);\n QString desktopDir(qApp->applicationDirPath() + \n \"\/ut_dcpappletmetadata-data\/desktops\/\");\n desktopTestFile = desktopDir + \"test.desktop\";\n desktopBadTestFile = desktopDir + \"testBad.desktop\";\n\n appletDir = \"so.applet\/\";\n appletSo = \"testapplet.so\";\n fileDatas[desktopTestFile][\"Name\"] = \"Browser\";\n fileDatas[desktopTestFile][\"Desktop Entry\/Type\"] = \"DUIApplet\";\n fileDatas[desktopTestFile][\"Desktop Entry\/Icon\"] = \"\";\n fileDatas[desktopTestFile][\"Desktop Entry\/Exec\"] = \"\";\n fileDatas[desktopTestFile][\"Desktop Entry\/X-logical-id\"] = \"qtn_sett_main_browser\";\n fileDatas[desktopTestFile][\"Desktop Entry\/X-translation-catalog\"] = \"duisettings1,duisettings2\";\n fileDatas[desktopTestFile][\"DUI\/X-DUIApplet-Applet\"] = \"testapplet.so\";\n fileDatas[desktopTestFile][\"DUI\/X-DUIApplet\/ImageLandscape\"] = \"Widget_landscape_weather.png\";\n fileDatas[desktopTestFile][\"DUI\/X-DUIApplet-ImagePortrait\"] = \"Widget_portrait_weather.png\";\n fileDatas[desktopTestFile][\"DUI\/X-DUIApplet-ApplicationCommand\"] = \".\/test\";\n fileDatas[desktopTestFile][\"DUI\/X-DUIApplet-Dslfile\"] = \"dslfile\";\n fileDatas[desktopTestFile][\"DCP\/Category\"] = \"Application\";\n fileDatas[desktopTestFile][\"DCP\/Order\"] = \"1\";\n fileDatas[desktopTestFile][\"DCP\/HelpId\"] = \"helpid\";\n fileDatas[desktopTestFile][\"DCP\/WidgetType\"] = \"DcpLabel2\";\n fileDatas[desktopTestFile][\"DCP\/Text2\"] = \"firefox\";\n fileDatas[desktopTestFile][\"DCP\/Align\"] = \"RIGHT\";\n fileDatas[desktopTestFile][\"DCP\/Image\"] = \"test.png\";\n fileDatas[desktopTestFile][\"DCP\/Part\"] = \"RobiJonMegKutyaraDer\";\n fileDatas[desktopTestFile][\"DCP\/Parent\"] = \"RobiJonMegKutyaraDer_II\";\n fileDatas[desktopTestFile][\"isValid\"] = \"y\";\n fileDatas[desktopBadTestFile][\"Desktop Entry\/Name\"] = \"Browser\";\n fileDatas[desktopBadTestFile][\"Desktop Entry\/Type\"] = \"DUIApplet\";\n fileDatas[desktopBadTestFile][\"Desktop Entry\/Icon\"] = \"\";\n fileDatas[desktopBadTestFile][\"Desktop Entry\/Exec\"] = \"\";\n fileDatas[desktopBadTestFile][\"Desktop Entry\/X-logical-id\"] = \"qtn_sett_main_browser\";\n fileDatas[desktopBadTestFile][\"Desktop Entry\/X-translation-catalog\"] = \"duisettings\";\n fileDatas[desktopBadTestFile][\"DUI\/X-DUIApplet-Applet\"] = \"libexampleapplet.so\";\n fileDatas[desktopBadTestFile][\"DUI\/X-DUIApplet\/ImageLandscape\"] = \"Widget_landscape_weather.png\";\n fileDatas[desktopBadTestFile][\"DUI\/X-DUIApplet-ImagePortrait\"] = \"Widget_portrait_weather.png\";\n fileDatas[desktopBadTestFile][\"DCP\/Category\"] = \"Application\";\n fileDatas[desktopBadTestFile][\"DCP\/Order\"] = \"1\";\n fileDatas[desktopBadTestFile][\"DCP\/WidgetType\"] = \"DcpLabel2\";\n fileDatas[desktopBadTestFile][\"DCP\/Text2\"] = \"firefox\";\n fileDatas[desktopBadTestFile][\"isValid\"] = \"n\";\n\n}\n\nvoid Ut_DcpAppletMetadata::cleanupTestCase()\n{\n delete qap;\n}\n\nvoid Ut_DcpAppletMetadata::init()\n{\n QVERIFY(m_subject = new DcpAppletMetadata(desktopTestFile));\n}\n\nvoid Ut_DcpAppletMetadata::cleanup()\n{\n if (m_subject) {\n delete m_subject;\n m_subject = 0;\n }\n}\n\nvoid Ut_DcpAppletMetadata::testCreateAndDestroy()\n{\n if (QTest::currentTestFailed()) return;\n}\n\nvoid Ut_DcpAppletMetadata::testIsValid()\n{\n if (QTest::currentTestFailed()) return;\n\n QVERIFY(m_subject->isValid());\n delete m_subject;\n m_subject = 0;\n\n QWARN(\"\\n\\t----Expected QWARN: Multiple definitions of group 'M'----\");\n QVERIFY((m_subject = new DcpAppletMetadata(desktopBadTestFile)));\n QVERIFY(!m_subject->isValid());\n}\n\nvoid Ut_DcpAppletMetadata::testIsModified()\n{\n if (QTest::currentTestFailed()) return;\n\n QVERIFY((m_subject = new DcpAppletMetadata(desktopTestFile)));\n\n QVERIFY(!m_subject->isModified());\n\n#if 0\n FIXME\n\n \/\/ touch the desktop file:\n QFile file(desktopTestFile);\n file.open(QIODevice::WriteOnly | QIODevice::Append);\n file.close();\n\n QVERIFY(m_subject->isModified());\n#endif\n}\n\nvoid Ut_DcpAppletMetadata::testName()\n{\n if (QTest::currentTestFailed()) return;\n\n QCOMPARE(m_subject->name(), QString(\"Browser\"));\n}\nvoid Ut_DcpAppletMetadata::testFileName()\n{\n if (QTest::currentTestFailed()) return;\n QVERIFY((m_subject = new DcpAppletMetadata(desktopTestFile)));\n\n QCOMPARE(m_subject->fileName(), desktopTestFile);\n}\n\nvoid Ut_DcpAppletMetadata::testCategory()\n{\n if (QTest::currentTestFailed()) return;\n\n QCOMPARE(m_subject->category(), QString(\"Application\"));\n}\n\nvoid Ut_DcpAppletMetadata::testBinary()\n{\n if (QTest::currentTestFailed()) return;\n\n QCOMPARE(m_subject->binary(), QString(\"testapplet.so\"));\n}\n\nvoid Ut_DcpAppletMetadata::testFullBinary()\n{\n if (QTest::currentTestFailed()) return;\n\n QCOMPARE(m_subject->fullBinary(), appletDir + appletSo);\n}\n\nvoid Ut_DcpAppletMetadata::testWidgetTypeID()\n{\n if (QTest::currentTestFailed()) return;\n\n QCOMPARE(m_subject->widgetTypeID(), static_cast<int>(DcpWidgetType::Label));\n} \n\nvoid Ut_DcpAppletMetadata::testAlign()\n{\n if (QTest::currentTestFailed()) return;\n\n QCOMPARE(m_subject->align(), Qt::AlignRight);\n\n}\n\nvoid Ut_DcpAppletMetadata::testToggle()\n{\n m_subject->toggle();\n}\n\nvoid Ut_DcpAppletMetadata::testImageName()\n{\n if (QTest::currentTestFailed()) return;\n\n QCOMPARE(m_subject->imageName(), QString(\"test.png\"));\n}\n\nvoid Ut_DcpAppletMetadata::testOrder()\n{\n if (QTest::currentTestFailed()) return;\n\n QCOMPARE(m_subject->order(), 1);\n}\n\n#ifdef MOSTUSED\nvoid Ut_DcpAppletMetadata::testUsage()\n{\n QSKIP(\"!!!! RelativePath bug under fixxing by Retsoft !!!!\", SkipSingle);\n\n\/* \n if (QTest::currentTestFailed()) return;\n\n qWarning() <<\"\\n@@\" <<m_subject->usage() <<\"@@\\n\";\n *\/\n}\n\nvoid Ut_DcpAppletMetadata::testUsageGreatherThan()\n{\n DcpAppletMetadata *metadata = new DcpAppletMetadata(desktopBadTestFile);\n MostUsedCounter::instance()->incrementUsageCount (\n QFileInfo(desktopTestFile).baseName()\n );\n QVERIFY(DcpAppletMetadata::usageGreatherThan(m_subject, metadata));\n delete metadata;\n}\n#endif\n\nvoid Ut_DcpAppletMetadata::testPart()\n{\n if (QTest::currentTestFailed()) return;\n\n QCOMPARE(m_subject->part(), QString(\"RobiJonMegKutyaraDer\"));\n}\n\nvoid Ut_DcpAppletMetadata::testHelpId()\n{\n if (QTest::currentTestFailed()) return;\n\n QCOMPARE(m_subject->helpId(), QString(\"helpid\"));\n}\n\n\nvoid Ut_DcpAppletMetadata::testDslFilename()\n{\n if (QTest::currentTestFailed()) return;\n QCOMPARE(m_subject->dslFilename(), QString(\"dslfile\")); \n}\n\nvoid Ut_DcpAppletMetadata::testApplicationCommand()\n{\n if (QTest::currentTestFailed()) return;\n QVERIFY(m_subject->hasApplicationCommand());\n QCOMPARE(m_subject->applicationCommand(), QString(\".\/test\")); \n delete m_subject;\n fileDatas[desktopTestFile][\"DUI\/X-DUIApplet-ApplicationCommand\"] = \"\";\n m_subject = new DcpAppletMetadata(desktopTestFile);\n QVERIFY(!m_subject->hasApplicationCommand());\n}\n\nvoid Ut_DcpAppletMetadata::testTranslationCatalog()\n{\n if (QTest::currentTestFailed()) return;\n QStringList expected;\n expected << \"duisettings1\" << \"duisettings2\";\n QCOMPARE(m_subject->translationCatalogs(), expected);\n}\n\nvoid Ut_DcpAppletMetadata::testText2()\n{\n if (QTest::currentTestFailed()) return;\n QCOMPARE(m_subject->text2(), QString(\"!! firefox\")); \n m_subject->d_ptr->m_Disabled = true;\n QCOMPARE(m_subject->text2(), QString(\"Disabled\")); \n}\n\nvoid Ut_DcpAppletMetadata::testIncrementUsage()\n{\n if (QTest::currentTestFailed()) return;\n QSKIP(\"remove if finished\", SkipSingle);\n}\n\nvoid Ut_DcpAppletMetadata::testDisabled()\n{\n m_subject->d_ptr->m_Disabled = false;\n QVERIFY(!m_subject->isDisabled());\n m_subject->setDisabled(true);\n QVERIFY(m_subject->d_ptr->m_Disabled);\n}\n\nvoid Ut_DcpAppletMetadata::testOrderLessThan()\n{\n fileDatas[desktopTestFile][\"DCP\/Order\"] = \"100\";\n DcpAppletMetadata *metadata = new DcpAppletMetadata(desktopTestFile);\n QVERIFY(DcpAppletMetadata::orderLessThan(m_subject, metadata));\n delete metadata;\n}\n\n\nvoid Ut_DcpAppletMetadata::testActive()\n{\n if (QTest::currentTestFailed()) return;\n m_subject->d_ptr->m_Activated = 0;\n QVERIFY(!m_subject->isActive());\n m_subject->markActive();\n m_subject->markActive();\n QVERIFY(m_subject->isActive());\n m_subject->markInactive();\n QVERIFY(m_subject->isActive());\n m_subject->markInactive();\n QVERIFY(!m_subject->isActive());\n}\n\nvoid Ut_DcpAppletMetadata::testDefaultSOPath()\n{\n m_subject->setDefaultSOPath(\"subidubi\");\n QCOMPARE(m_subject->defaultSOPath(), QString(\"subidubi\/\"));\n}\n\nvoid Ut_DcpAppletMetadata::testTextOrientation()\n{\n QCOMPARE(m_subject->textOrientation(), Qt::Vertical);\n}\n\nvoid Ut_DcpAppletMetadata::testText1()\n{\n QCOMPARE(m_subject->text1(), QString(\"!! \"));\n}\n\nvoid Ut_DcpAppletMetadata::testToggleIconId()\n{\n QCOMPARE(m_subject->toggleIconId(), QString());\n}\n\nvoid Ut_DcpAppletMetadata::testIsUnique()\n{\n QCOMPARE(m_subject->isUnique(), false);\n}\n\nvoid Ut_DcpAppletMetadata::testLessThans()\n{\n QCOMPARE(m_subject->nameLessThan(m_subject, m_subject), false);\n QCOMPARE(m_subject->titleLessThan(m_subject, m_subject), false);\n QCOMPARE(m_subject->usageGreatherThan(m_subject, m_subject), false);\n}\nvoid Ut_DcpAppletMetadata::testUseless()\n{\n m_subject->usage();\n m_subject->incrementUsage();\n QCOMPARE((void*)m_subject->lastUsed(), (void*)DcpAppletMetadataPrivate::sm_LastUsed);\n m_subject->setLastUsed(m_subject);\n QCOMPARE((void*)DcpAppletMetadataPrivate::sm_LastUsed, (void*)m_subject);\n m_subject->storedLastUsedItem();\n QCOMPARE(m_subject->isHidden(), false);\n QCOMPARE(m_subject->hasMainView(), true);\n QCOMPARE(m_subject->sliderLeftImage(), QString());\n QCOMPARE(m_subject->sliderRightImage(), QString());\n QCOMPARE(m_subject->hasInProcessBrief(), false);\n\n}\n\nQTEST_APPLESS_MAIN(Ut_DcpAppletMetadata)\n<commit_msg>A unittest fix for last commit<commit_after>\/***************************************************************************\n**\n** Copyright (C) 2010 Nokia Corporation and\/or its subsidiary(-ies).\n** All rights reserved.\n** Contact: Karoliina T. Salminen <karoliina.t.salminen@nokia.com>\n**\n** This file is part of duicontrolpanel.\n**\n**\n** This library is free software; you can redistribute it and\/or\n** modify it under the terms of the GNU Lesser General Public\n** License version 2.1 as published by the Free Software Foundation\n** and appearing in the file LICENSE.LGPL included in the packaging\n** of this file.\n**\n****************************************************************************\/\n\n#include <QObject>\n#include <QByteArray>\n\n#include <DcpApplet>\n#include <DcpWidgetTypes>\n\n#include <dcpappletmetadata.h>\n#include <dcpappletmetadata_p.h>\n\n#include \"ut_dcpappletmetadata.h\"\n#include \"filedatas.h\"\n#include \"dcpmostusedcounter.h\"\n\nvoid Ut_DcpAppletMetadata::initTestCase()\n{\n static int c = 0;\n static QByteArray arg(\"dummyarg\");\n char *argp = arg.data();\n qap = new QCoreApplication(c, &argp);\n QString desktopDir(qApp->applicationDirPath() + \n \"\/ut_dcpappletmetadata-data\/desktops\/\");\n desktopTestFile = desktopDir + \"test.desktop\";\n desktopBadTestFile = desktopDir + \"testBad.desktop\";\n\n appletDir = \"so.applet\/\";\n appletSo = \"testapplet.so\";\n fileDatas[desktopTestFile][\"Name\"] = \"Browser\";\n fileDatas[desktopTestFile][\"Desktop Entry\/Type\"] = \"DUIApplet\";\n fileDatas[desktopTestFile][\"Desktop Entry\/Icon\"] = \"\";\n fileDatas[desktopTestFile][\"Desktop Entry\/Exec\"] = \"\";\n fileDatas[desktopTestFile][\"Desktop Entry\/X-logical-id\"] = \"qtn_sett_main_browser\";\n fileDatas[desktopTestFile][\"Desktop Entry\/X-translation-catalog\"] = \"duisettings1,duisettings2\";\n fileDatas[desktopTestFile][\"DUI\/X-DUIApplet-Applet\"] = \"testapplet.so\";\n fileDatas[desktopTestFile][\"DUI\/X-DUIApplet\/ImageLandscape\"] = \"Widget_landscape_weather.png\";\n fileDatas[desktopTestFile][\"DUI\/X-DUIApplet-ImagePortrait\"] = \"Widget_portrait_weather.png\";\n fileDatas[desktopTestFile][\"DUI\/X-DUIApplet-ApplicationCommand\"] = \".\/test\";\n fileDatas[desktopTestFile][\"DUI\/X-DUIApplet-Dslfile\"] = \"dslfile\";\n fileDatas[desktopTestFile][\"DCP\/Category\"] = \"Application\";\n fileDatas[desktopTestFile][\"DCP\/Order\"] = \"1\";\n fileDatas[desktopTestFile][\"DCP\/HelpId\"] = \"helpid\";\n fileDatas[desktopTestFile][\"DCP\/WidgetType\"] = \"DcpLabel2\";\n fileDatas[desktopTestFile][\"DCP\/Text2\"] = \"firefox\";\n fileDatas[desktopTestFile][\"DCP\/Align\"] = \"RIGHT\";\n fileDatas[desktopTestFile][\"DCP\/Image\"] = \"test.png\";\n fileDatas[desktopTestFile][\"DCP\/Part\"] = \"RobiJonMegKutyaraDer\";\n fileDatas[desktopTestFile][\"DCP\/Parent\"] = \"RobiJonMegKutyaraDer_II\";\n fileDatas[desktopTestFile][\"isValid\"] = \"y\";\n fileDatas[desktopBadTestFile][\"Desktop Entry\/Name\"] = \"Browser\";\n fileDatas[desktopBadTestFile][\"Desktop Entry\/Type\"] = \"DUIApplet\";\n fileDatas[desktopBadTestFile][\"Desktop Entry\/Icon\"] = \"\";\n fileDatas[desktopBadTestFile][\"Desktop Entry\/Exec\"] = \"\";\n fileDatas[desktopBadTestFile][\"Desktop Entry\/X-logical-id\"] = \"qtn_sett_main_browser\";\n fileDatas[desktopBadTestFile][\"Desktop Entry\/X-translation-catalog\"] = \"duisettings\";\n fileDatas[desktopBadTestFile][\"DUI\/X-DUIApplet-Applet\"] = \"libexampleapplet.so\";\n fileDatas[desktopBadTestFile][\"DUI\/X-DUIApplet\/ImageLandscape\"] = \"Widget_landscape_weather.png\";\n fileDatas[desktopBadTestFile][\"DUI\/X-DUIApplet-ImagePortrait\"] = \"Widget_portrait_weather.png\";\n fileDatas[desktopBadTestFile][\"DCP\/Category\"] = \"Application\";\n fileDatas[desktopBadTestFile][\"DCP\/Order\"] = \"1\";\n fileDatas[desktopBadTestFile][\"DCP\/WidgetType\"] = \"DcpLabel2\";\n fileDatas[desktopBadTestFile][\"DCP\/Text2\"] = \"firefox\";\n fileDatas[desktopBadTestFile][\"isValid\"] = \"n\";\n\n}\n\nvoid Ut_DcpAppletMetadata::cleanupTestCase()\n{\n delete qap;\n}\n\nvoid Ut_DcpAppletMetadata::init()\n{\n QVERIFY(m_subject = new DcpAppletMetadata(desktopTestFile));\n}\n\nvoid Ut_DcpAppletMetadata::cleanup()\n{\n if (m_subject) {\n delete m_subject;\n m_subject = 0;\n }\n}\n\nvoid Ut_DcpAppletMetadata::testCreateAndDestroy()\n{\n if (QTest::currentTestFailed()) return;\n}\n\nvoid Ut_DcpAppletMetadata::testIsValid()\n{\n if (QTest::currentTestFailed()) return;\n\n QVERIFY(m_subject->isValid());\n delete m_subject;\n m_subject = 0;\n\n QWARN(\"\\n\\t----Expected QWARN: Multiple definitions of group 'M'----\");\n QVERIFY((m_subject = new DcpAppletMetadata(desktopBadTestFile)));\n QVERIFY(!m_subject->isValid());\n}\n\nvoid Ut_DcpAppletMetadata::testIsModified()\n{\n if (QTest::currentTestFailed()) return;\n\n QVERIFY((m_subject = new DcpAppletMetadata(desktopTestFile)));\n\n QVERIFY(!m_subject->isModified());\n\n#if 0\n FIXME\n\n \/\/ touch the desktop file:\n QFile file(desktopTestFile);\n file.open(QIODevice::WriteOnly | QIODevice::Append);\n file.close();\n\n QVERIFY(m_subject->isModified());\n#endif\n}\n\nvoid Ut_DcpAppletMetadata::testName()\n{\n if (QTest::currentTestFailed()) return;\n\n QCOMPARE(m_subject->name(), QString(\"Browser\"));\n}\nvoid Ut_DcpAppletMetadata::testFileName()\n{\n if (QTest::currentTestFailed()) return;\n QVERIFY((m_subject = new DcpAppletMetadata(desktopTestFile)));\n\n QCOMPARE(m_subject->fileName(), desktopTestFile);\n}\n\nvoid Ut_DcpAppletMetadata::testCategory()\n{\n if (QTest::currentTestFailed()) return;\n\n QCOMPARE(m_subject->category(), QString(\"Application\"));\n}\n\nvoid Ut_DcpAppletMetadata::testBinary()\n{\n if (QTest::currentTestFailed()) return;\n\n QCOMPARE(m_subject->binary(), QString(\"testapplet.so\"));\n}\n\nvoid Ut_DcpAppletMetadata::testFullBinary()\n{\n if (QTest::currentTestFailed()) return;\n\n QCOMPARE(m_subject->fullBinary(), appletDir + appletSo);\n}\n\nvoid Ut_DcpAppletMetadata::testWidgetTypeID()\n{\n if (QTest::currentTestFailed()) return;\n\n QCOMPARE(m_subject->widgetTypeID(), static_cast<int>(DcpWidgetType::Label));\n} \n\nvoid Ut_DcpAppletMetadata::testAlign()\n{\n if (QTest::currentTestFailed()) return;\n\n QCOMPARE(m_subject->align(), Qt::AlignRight);\n\n}\n\nvoid Ut_DcpAppletMetadata::testToggle()\n{\n m_subject->toggle();\n}\n\nvoid Ut_DcpAppletMetadata::testImageName()\n{\n if (QTest::currentTestFailed()) return;\n\n QCOMPARE(m_subject->imageName(), QString(\"test.png\"));\n}\n\nvoid Ut_DcpAppletMetadata::testOrder()\n{\n if (QTest::currentTestFailed()) return;\n\n QCOMPARE(m_subject->order(), 1);\n}\n\n#ifdef MOSTUSED\nvoid Ut_DcpAppletMetadata::testUsage()\n{\n QSKIP(\"!!!! RelativePath bug under fixxing by Retsoft !!!!\", SkipSingle);\n\n\/* \n if (QTest::currentTestFailed()) return;\n\n qWarning() <<\"\\n@@\" <<m_subject->usage() <<\"@@\\n\";\n *\/\n}\n\nvoid Ut_DcpAppletMetadata::testUsageGreatherThan()\n{\n DcpAppletMetadata *metadata = new DcpAppletMetadata(desktopBadTestFile);\n MostUsedCounter::instance()->incrementUsageCount (\n QFileInfo(desktopTestFile).baseName()\n );\n QVERIFY(DcpAppletMetadata::usageGreatherThan(m_subject, metadata));\n delete metadata;\n}\n#endif\n\nvoid Ut_DcpAppletMetadata::testPart()\n{\n if (QTest::currentTestFailed()) return;\n\n QCOMPARE(m_subject->part(), QString(\"RobiJonMegKutyaraDer\"));\n}\n\nvoid Ut_DcpAppletMetadata::testHelpId()\n{\n if (QTest::currentTestFailed()) return;\n\n QCOMPARE(m_subject->helpId(), QString(\"helpid\"));\n}\n\n\nvoid Ut_DcpAppletMetadata::testDslFilename()\n{\n if (QTest::currentTestFailed()) return;\n QCOMPARE(m_subject->dslFilename(), QString(\"dslfile\")); \n}\n\nvoid Ut_DcpAppletMetadata::testApplicationCommand()\n{\n if (QTest::currentTestFailed()) return;\n QVERIFY(m_subject->hasApplicationCommand());\n QCOMPARE(m_subject->applicationCommand(), QString(\".\/test\")); \n delete m_subject;\n fileDatas[desktopTestFile][\"DUI\/X-DUIApplet-ApplicationCommand\"] = \"\";\n m_subject = new DcpAppletMetadata(desktopTestFile);\n QVERIFY(!m_subject->hasApplicationCommand());\n}\n\nvoid Ut_DcpAppletMetadata::testTranslationCatalog()\n{\n if (QTest::currentTestFailed()) return;\n QStringList expected;\n expected << \"duisettings1\" << \"duisettings2\";\n QCOMPARE(m_subject->translationCatalogs(), expected);\n}\n\nvoid Ut_DcpAppletMetadata::testText2()\n{\n if (QTest::currentTestFailed()) return;\n QCOMPARE(m_subject->text2(), QString(\"firefox\")); \n m_subject->d_ptr->m_Disabled = true;\n QCOMPARE(m_subject->text2(), QString(\"Disabled\")); \n}\n\nvoid Ut_DcpAppletMetadata::testIncrementUsage()\n{\n if (QTest::currentTestFailed()) return;\n QSKIP(\"remove if finished\", SkipSingle);\n}\n\nvoid Ut_DcpAppletMetadata::testDisabled()\n{\n m_subject->d_ptr->m_Disabled = false;\n QVERIFY(!m_subject->isDisabled());\n m_subject->setDisabled(true);\n QVERIFY(m_subject->d_ptr->m_Disabled);\n}\n\nvoid Ut_DcpAppletMetadata::testOrderLessThan()\n{\n fileDatas[desktopTestFile][\"DCP\/Order\"] = \"100\";\n DcpAppletMetadata *metadata = new DcpAppletMetadata(desktopTestFile);\n QVERIFY(DcpAppletMetadata::orderLessThan(m_subject, metadata));\n delete metadata;\n}\n\n\nvoid Ut_DcpAppletMetadata::testActive()\n{\n if (QTest::currentTestFailed()) return;\n m_subject->d_ptr->m_Activated = 0;\n QVERIFY(!m_subject->isActive());\n m_subject->markActive();\n m_subject->markActive();\n QVERIFY(m_subject->isActive());\n m_subject->markInactive();\n QVERIFY(m_subject->isActive());\n m_subject->markInactive();\n QVERIFY(!m_subject->isActive());\n}\n\nvoid Ut_DcpAppletMetadata::testDefaultSOPath()\n{\n m_subject->setDefaultSOPath(\"subidubi\");\n QCOMPARE(m_subject->defaultSOPath(), QString(\"subidubi\/\"));\n}\n\nvoid Ut_DcpAppletMetadata::testTextOrientation()\n{\n QCOMPARE(m_subject->textOrientation(), Qt::Vertical);\n}\n\nvoid Ut_DcpAppletMetadata::testText1()\n{\n QCOMPARE(m_subject->text1(), QString(\"\"));\n}\n\nvoid Ut_DcpAppletMetadata::testToggleIconId()\n{\n QCOMPARE(m_subject->toggleIconId(), QString());\n}\n\nvoid Ut_DcpAppletMetadata::testIsUnique()\n{\n QCOMPARE(m_subject->isUnique(), false);\n}\n\nvoid Ut_DcpAppletMetadata::testLessThans()\n{\n QCOMPARE(m_subject->nameLessThan(m_subject, m_subject), false);\n QCOMPARE(m_subject->titleLessThan(m_subject, m_subject), false);\n QCOMPARE(m_subject->usageGreatherThan(m_subject, m_subject), false);\n}\nvoid Ut_DcpAppletMetadata::testUseless()\n{\n m_subject->usage();\n m_subject->incrementUsage();\n QCOMPARE((void*)m_subject->lastUsed(), (void*)DcpAppletMetadataPrivate::sm_LastUsed);\n m_subject->setLastUsed(m_subject);\n QCOMPARE((void*)DcpAppletMetadataPrivate::sm_LastUsed, (void*)m_subject);\n m_subject->storedLastUsedItem();\n QCOMPARE(m_subject->isHidden(), false);\n QCOMPARE(m_subject->hasMainView(), true);\n QCOMPARE(m_subject->sliderLeftImage(), QString());\n QCOMPARE(m_subject->sliderRightImage(), QString());\n QCOMPARE(m_subject->hasInProcessBrief(), false);\n\n}\n\nQTEST_APPLESS_MAIN(Ut_DcpAppletMetadata)\n<|endoftext|>"} {"text":"<commit_before>\/\/=======================================================================\n\/\/ Copyright (c) 2014-2017 Baptiste Wicht\n\/\/ Distributed under the terms of the MIT License.\n\/\/ (See accompanying file LICENSE or copy at\n\/\/ http:\/\/opensource.org\/licenses\/MIT)\n\/\/=======================================================================\n\n#pragma once\n\n#include \"etl\/expr\/base_temporary_expr.hpp\"\n\nnamespace etl {\n\n\/*!\n * \\brief A transposition expression.\n * \\tparam A The transposed type\n *\/\ntemplate <typename A>\nstruct bias_batch_mean_expr : base_temporary_expr_un<bias_batch_mean_expr<A>, A> {\n using value_type = value_t<A>; \/\/\/< The type of value of the expression\n using this_type = bias_batch_mean_expr<A>; \/\/\/< The type of this expression\n using base_type = base_temporary_expr_un<this_type, A>; \/\/\/< The base type\n using sub_traits = decay_traits<A>; \/\/\/< The traits of the sub type\n\n static constexpr auto storage_order = sub_traits::storage_order; \/\/\/< The sub storage order\n\n \/*!\n * \\brief Construct a new expression\n * \\param a The sub expression\n *\/\n explicit bias_batch_mean_expr(A a) : base_type(a) {\n \/\/Nothing else to init\n }\n\n \/*!\n * \\brief Validate the transposition dimensions\n * \\param a The input matrix\n * \\þaram c The output matrix\n *\/\n template <typename C, cpp_enable_if(all_fast<A,C>::value)>\n static void check(const A& a, const C& c) {\n cpp_unused(a);\n cpp_unused(c);\n\n static_assert(etl::dimensions<C>() == 1, \"The output of bias_batch_mean is a vector\");\n static_assert(etl::dimensions<A>() == 4, \"The input of bias_batch_mean is a 4D matrix\");\n\n static_assert(etl::dim<1, A>() == etl::dim<0, C>(), \"Invalid dimensions for bias_batch_mean\");\n }\n\n \/*!\n * \\brief Validate the transposition dimensions\n * \\param a The input matrix\n * \\þaram c The output matrix\n *\/\n template <typename C, cpp_disable_if(all_fast<A,C>::value)>\n static void check(const A& a, const C& c) {\n static_assert(etl::dimensions<C>() == 1, \"The output of bias_batch_mean is a vector\");\n static_assert(etl::dimensions<A>() == 4, \"The input of bias_batch_mean is a 4D matrix\");\n\n cpp_assert(etl::dim<1>(a) == etl::dim<0>(c), \"Invalid dimensions for bias_batch_mean\");\n\n cpp_unused(a);\n cpp_unused(c);\n }\n\n \/\/ Assignment functions\n\n \/*!\n * \\brief Assign to a matrix of the same storage order\n * \\param lhs The expression to which assign\n *\/\n template<typename L>\n void assign_to(L&& lhs) const {\n static_assert(all_etl_expr<A, L>::value, \"bias_batch_mean only supported for ETL expressions\");\n\n auto& a = this->a();\n\n standard_evaluator::pre_assign_rhs(a);\n\n const auto N = etl::size(a) \/ etl::size(lhs);\n const auto K = etl::size(lhs);\n\n using T = value_t<A>;\n\n check(a, lhs);\n\n auto batch_fun_k = [&](const size_t first, const size_t last) {\n if (last - first) {\n SERIAL_SECTION {\n for (size_t k = first; k < last; ++k) {\n T mean(0);\n\n for (size_t b = 0; b < etl::dim<0>(a); ++b) {\n mean += sum(a(b)(k));\n }\n\n lhs(k) = mean \/ N;\n }\n }\n }\n };\n\n engine_dispatch_1d(batch_fun_k, 0, K, 2UL);\n }\n\n \/*!\n * \\brief Add to the given left-hand-side expression\n * \\param lhs The expression to which assign\n *\/\n template<typename L>\n void assign_add_to(L&& lhs) const {\n static_assert(all_etl_expr<A, L>::value, \"bias_batch_mean only supported for ETL expressions\");\n\n auto& a = this->a();\n\n standard_evaluator::pre_assign_rhs(a);\n\n const auto N = etl::size(a) \/ etl::size(lhs);\n const auto K = etl::size(lhs);\n\n using T = value_t<A>;\n\n check(a, lhs);\n\n auto batch_fun_k = [&](const size_t first, const size_t last) {\n if (last - first) {\n SERIAL_SECTION {\n for (size_t k = first; k < last; ++k) {\n T mean(0);\n\n for (size_t b = 0; b < etl::dim<0>(a); ++b) {\n mean += sum(a(b)(k));\n }\n\n lhs(k) += mean \/ N;\n }\n }\n }\n };\n\n engine_dispatch_1d(batch_fun_k, 0, K, 2UL);\n }\n\n \/*!\n * \\brief Sub from the given left-hand-side expression\n * \\param lhs The expression to which assign\n *\/\n template<typename L>\n void assign_sub_to(L&& lhs) const {\n static_assert(all_etl_expr<A, L>::value, \"bias_batch_mean only supported for ETL expressions\");\n\n auto& a = this->a();\n\n standard_evaluator::pre_assign_rhs(a);\n\n const auto N = etl::size(a) \/ etl::size(lhs);\n const auto K = etl::size(lhs);\n\n using T = value_t<A>;\n\n check(a, lhs);\n\n auto batch_fun_k = [&](const size_t first, const size_t last) {\n if (last - first) {\n SERIAL_SECTION {\n for (size_t k = first; k < last; ++k) {\n T mean(0);\n\n for (size_t b = 0; b < etl::dim<0>(a); ++b) {\n mean += sum(a(b)(k));\n }\n\n lhs(k) -= mean \/ N;\n }\n }\n }\n };\n\n engine_dispatch_1d(batch_fun_k, 0, K, 2UL);\n }\n\n \/*!\n * \\brief Multiply the given left-hand-side expression\n * \\param lhs The expression to which assign\n *\/\n template<typename L>\n void assign_mul_to(L&& lhs) const {\n static_assert(all_etl_expr<A, L>::value, \"bias_batch_mean only supported for ETL expressions\");\n\n auto& a = this->a();\n\n standard_evaluator::pre_assign_rhs(a);\n\n const auto N = etl::size(a) \/ etl::size(lhs);\n const auto K = etl::size(lhs);\n\n using T = value_t<A>;\n\n check(a, lhs);\n\n auto batch_fun_k = [&](const size_t first, const size_t last) {\n if (last - first) {\n SERIAL_SECTION {\n for (size_t k = first; k < last; ++k) {\n T mean(0);\n\n for (size_t b = 0; b < etl::dim<0>(a); ++b) {\n mean += sum(a(b)(k));\n }\n\n lhs(k) *= mean \/ N;\n }\n }\n }\n };\n\n engine_dispatch_1d(batch_fun_k, 0, K, 2UL);\n }\n\n \/*!\n * \\brief Divide the given left-hand-side expression\n * \\param lhs The expression to which assign\n *\/\n template<typename L>\n void assign_div_to(L&& lhs) const {\n static_assert(all_etl_expr<A, L>::value, \"bias_batch_mean only supported for ETL expressions\");\n\n auto& a = this->a();\n\n standard_evaluator::pre_assign_rhs(a);\n\n const auto N = etl::size(a) \/ etl::size(lhs);\n const auto K = etl::size(lhs);\n\n using T = value_t<A>;\n\n check(a, lhs);\n\n auto batch_fun_k = [&](const size_t first, const size_t last) {\n if (last - first) {\n SERIAL_SECTION {\n for (size_t k = first; k < last; ++k) {\n T mean(0);\n\n for (size_t b = 0; b < etl::dim<0>(a); ++b) {\n mean += sum(a(b)(k));\n }\n\n lhs(k) \/= mean \/ N;\n }\n }\n }\n };\n\n engine_dispatch_1d(batch_fun_k, 0, K, 2UL);\n }\n\n \/*!\n * \\brief Modulo the given left-hand-side expression\n * \\param lhs The expression to which assign\n *\/\n template<typename L>\n void assign_mod_to(L&& lhs) const {\n static_assert(all_etl_expr<A, L>::value, \"bias_batch_mean only supported for ETL expressions\");\n\n auto& a = this->a();\n\n standard_evaluator::pre_assign_rhs(a);\n\n const auto N = etl::size(a) \/ etl::size(lhs);\n const auto K = etl::size(lhs);\n\n using T = value_t<A>;\n\n check(a, lhs);\n\n auto batch_fun_k = [&](const size_t first, const size_t last) {\n if (last - first) {\n SERIAL_SECTION {\n for (size_t k = first; k < last; ++k) {\n T mean(0);\n\n for (size_t b = 0; b < etl::dim<0>(a); ++b) {\n mean += sum(a(b)(k));\n }\n\n lhs(k) %= mean \/ N;\n }\n }\n }\n };\n\n engine_dispatch_1d(batch_fun_k, 0, K, 2UL);\n }\n\n \/*!\n * \\brief Print a representation of the expression on the given stream\n * \\param os The output stream\n * \\param expr The expression to print\n * \\return the output stream\n *\/\n friend std::ostream& operator<<(std::ostream& os, const bias_batch_mean_expr& expr) {\n return os << \"bias_batch_mean(\" << expr._a << \")\";\n }\n};\n\n\/*!\n * \\brief Traits for a transpose expression\n * \\tparam A The transposed sub type\n *\/\ntemplate <typename A>\nstruct etl_traits<etl::bias_batch_mean_expr<A>> {\n using expr_t = etl::bias_batch_mean_expr<A>; \/\/\/< The expression type\n using sub_expr_t = std::decay_t<A>; \/\/\/< The sub expression type\n using sub_traits = etl_traits<sub_expr_t>; \/\/\/< The sub traits\n using value_type = value_t<A>; \/\/\/< The value type of the expression\n\n static constexpr bool is_etl = true; \/\/\/< Indicates if the type is an ETL expression\n static constexpr bool is_transformer = false; \/\/\/< Indicates if the type is a transformer\n static constexpr bool is_view = false; \/\/\/< Indicates if the type is a view\n static constexpr bool is_magic_view = false; \/\/\/< Indicates if the type is a magic view\n static constexpr bool is_fast = sub_traits::is_fast; \/\/\/< Indicates if the expression is fast\n static constexpr bool is_linear = true; \/\/\/< Indicates if the expression is linear\n static constexpr bool is_thread_safe = true; \/\/\/< Indicates if the expression is thread safe\n static constexpr bool is_value = false; \/\/\/< Indicates if the expression is of value type\n static constexpr bool is_direct = true; \/\/\/< Indicates if the expression has direct memory access\n static constexpr bool is_generator = false; \/\/\/< Indicates if the expression is a generator\n static constexpr bool is_padded = false; \/\/\/< Indicates if the expression is padded\n static constexpr bool is_aligned = true; \/\/\/< Indicates if the expression is padded\n static constexpr bool is_gpu = false; \/\/\/< Indicates if the expression can be done on GPU\n static constexpr bool is_temporary = true; \/\/\/< Indicates if the expression needs a evaluator visitor\n static constexpr order storage_order = sub_traits::storage_order; \/\/\/< The expression's storage order\n\n \/*!\n * \\brief Indicates if the expression is vectorizable using the\n * given vector mode\n * \\tparam V The vector mode\n *\/\n template <vector_mode_t V>\n using vectorizable = std::true_type;\n\n \/*!\n * \\brief Returns the DDth dimension of the expression\n * \\return the DDth dimension of the expression\n *\/\n template <size_t DD>\n static constexpr size_t dim() {\n static_assert(DD == 0, \"Invalid dimensions access\");\n return decay_traits<A>::template dim<1>();\n }\n\n \/*!\n * \\brief Returns the dth dimension of the expression\n * \\param e The sub expression\n * \\param d The dimension to get\n * \\return the dth dimension of the expression\n *\/\n static size_t dim(const expr_t& e, size_t d) {\n cpp_assert(d == 0, \"Invalid dimensions access\");\n cpp_unused(d);\n return etl::dim<1>(e._a);\n }\n\n \/*!\n * \\brief Returns the size of the expression\n * \\param e The sub expression\n * \\return the size of the expression\n *\/\n static size_t size(const expr_t& e) {\n return etl::dim<1>(e._a);\n }\n\n \/*!\n * \\brief Returns the size of the expression\n * \\return the size of the expression\n *\/\n static constexpr size_t size() {\n return decay_traits<A>::template dim<1>();\n }\n\n \/*!\n * \\brief Returns the number of dimensions of the expression\n * \\return the number of dimensions of the expression\n *\/\n static constexpr size_t dimensions() {\n return 1;\n }\n};\n\n\/*!\n * \\brief Returns the transpose of the given expression.\n * \\param value The expression\n * \\return The transpose of the given expression.\n *\/\ntemplate <typename E>\nbias_batch_mean_expr<detail::build_type<E>> bias_batch_mean(const E& value) {\n static_assert(is_etl_expr<E>::value, \"etl::bias_batch_mean can only be used on ETL expressions\");\n static_assert(decay_traits<E>::dimensions() == 4, \"etl::bias_batch_mean is only defined for 4D input\");\n\n return bias_batch_mean_expr<detail::build_type<E>>{value};\n}\n\n} \/\/end of namespace etl\n<commit_msg>Cleanup code style<commit_after>\/\/=======================================================================\n\/\/ Copyright (c) 2014-2017 Baptiste Wicht\n\/\/ Distributed under the terms of the MIT License.\n\/\/ (See accompanying file LICENSE or copy at\n\/\/ http:\/\/opensource.org\/licenses\/MIT)\n\/\/=======================================================================\n\n#pragma once\n\n#include \"etl\/expr\/base_temporary_expr.hpp\"\n\nnamespace etl {\n\n\/*!\n * \\brief A transposition expression.\n * \\tparam A The transposed type\n *\/\ntemplate <typename A>\nstruct bias_batch_mean_expr : base_temporary_expr_un<bias_batch_mean_expr<A>, A> {\n using value_type = value_t<A>; \/\/\/< The type of value of the expression\n using this_type = bias_batch_mean_expr<A>; \/\/\/< The type of this expression\n using base_type = base_temporary_expr_un<this_type, A>; \/\/\/< The base type\n using sub_traits = decay_traits<A>; \/\/\/< The traits of the sub type\n\n static constexpr auto storage_order = sub_traits::storage_order; \/\/\/< The sub storage order\n\n \/*!\n * \\brief Construct a new expression\n * \\param a The sub expression\n *\/\n explicit bias_batch_mean_expr(A a)\n : base_type(a) {\n \/\/Nothing else to init\n }\n\n \/*!\n * \\brief Validate the transposition dimensions\n * \\param a The input matrix\n * \\þaram c The output matrix\n *\/\n template <typename C, cpp_enable_if(all_fast<A, C>::value)>\n static void check(const A& a, const C& c) {\n cpp_unused(a);\n cpp_unused(c);\n\n static_assert(etl::dimensions<C>() == 1, \"The output of bias_batch_mean is a vector\");\n static_assert(etl::dimensions<A>() == 4, \"The input of bias_batch_mean is a 4D matrix\");\n\n static_assert(etl::dim<1, A>() == etl::dim<0, C>(), \"Invalid dimensions for bias_batch_mean\");\n }\n\n \/*!\n * \\brief Validate the transposition dimensions\n * \\param a The input matrix\n * \\þaram c The output matrix\n *\/\n template <typename C, cpp_disable_if(all_fast<A, C>::value)>\n static void check(const A& a, const C& c) {\n static_assert(etl::dimensions<C>() == 1, \"The output of bias_batch_mean is a vector\");\n static_assert(etl::dimensions<A>() == 4, \"The input of bias_batch_mean is a 4D matrix\");\n\n cpp_assert(etl::dim<1>(a) == etl::dim<0>(c), \"Invalid dimensions for bias_batch_mean\");\n\n cpp_unused(a);\n cpp_unused(c);\n }\n\n \/\/ Assignment functions\n\n \/*!\n * \\brief Assign to a matrix of the same storage order\n * \\param lhs The expression to which assign\n *\/\n template <typename L>\n void assign_to(L&& lhs) const {\n static_assert(all_etl_expr<A, L>::value, \"bias_batch_mean only supported for ETL expressions\");\n\n auto& a = this->a();\n\n standard_evaluator::pre_assign_rhs(a);\n\n const auto N = etl::size(a) \/ etl::size(lhs);\n const auto K = etl::size(lhs);\n\n using T = value_t<A>;\n\n check(a, lhs);\n\n auto batch_fun_k = [&](const size_t first, const size_t last) {\n if (last - first) {\n SERIAL_SECTION {\n for (size_t k = first; k < last; ++k) {\n T mean(0);\n\n for (size_t b = 0; b < etl::dim<0>(a); ++b) {\n mean += sum(a(b)(k));\n }\n\n lhs(k) = mean \/ N;\n }\n }\n }\n };\n\n engine_dispatch_1d(batch_fun_k, 0, K, 2UL);\n }\n\n \/*!\n * \\brief Add to the given left-hand-side expression\n * \\param lhs The expression to which assign\n *\/\n template <typename L>\n void assign_add_to(L&& lhs) const {\n static_assert(all_etl_expr<A, L>::value, \"bias_batch_mean only supported for ETL expressions\");\n\n auto& a = this->a();\n\n standard_evaluator::pre_assign_rhs(a);\n\n const auto N = etl::size(a) \/ etl::size(lhs);\n const auto K = etl::size(lhs);\n\n using T = value_t<A>;\n\n check(a, lhs);\n\n auto batch_fun_k = [&](const size_t first, const size_t last) {\n if (last - first) {\n SERIAL_SECTION {\n for (size_t k = first; k < last; ++k) {\n T mean(0);\n\n for (size_t b = 0; b < etl::dim<0>(a); ++b) {\n mean += sum(a(b)(k));\n }\n\n lhs(k) += mean \/ N;\n }\n }\n }\n };\n\n engine_dispatch_1d(batch_fun_k, 0, K, 2UL);\n }\n\n \/*!\n * \\brief Sub from the given left-hand-side expression\n * \\param lhs The expression to which assign\n *\/\n template <typename L>\n void assign_sub_to(L&& lhs) const {\n static_assert(all_etl_expr<A, L>::value, \"bias_batch_mean only supported for ETL expressions\");\n\n auto& a = this->a();\n\n standard_evaluator::pre_assign_rhs(a);\n\n const auto N = etl::size(a) \/ etl::size(lhs);\n const auto K = etl::size(lhs);\n\n using T = value_t<A>;\n\n check(a, lhs);\n\n auto batch_fun_k = [&](const size_t first, const size_t last) {\n if (last - first) {\n SERIAL_SECTION {\n for (size_t k = first; k < last; ++k) {\n T mean(0);\n\n for (size_t b = 0; b < etl::dim<0>(a); ++b) {\n mean += sum(a(b)(k));\n }\n\n lhs(k) -= mean \/ N;\n }\n }\n }\n };\n\n engine_dispatch_1d(batch_fun_k, 0, K, 2UL);\n }\n\n \/*!\n * \\brief Multiply the given left-hand-side expression\n * \\param lhs The expression to which assign\n *\/\n template <typename L>\n void assign_mul_to(L&& lhs) const {\n static_assert(all_etl_expr<A, L>::value, \"bias_batch_mean only supported for ETL expressions\");\n\n auto& a = this->a();\n\n standard_evaluator::pre_assign_rhs(a);\n\n const auto N = etl::size(a) \/ etl::size(lhs);\n const auto K = etl::size(lhs);\n\n using T = value_t<A>;\n\n check(a, lhs);\n\n auto batch_fun_k = [&](const size_t first, const size_t last) {\n if (last - first) {\n SERIAL_SECTION {\n for (size_t k = first; k < last; ++k) {\n T mean(0);\n\n for (size_t b = 0; b < etl::dim<0>(a); ++b) {\n mean += sum(a(b)(k));\n }\n\n lhs(k) *= mean \/ N;\n }\n }\n }\n };\n\n engine_dispatch_1d(batch_fun_k, 0, K, 2UL);\n }\n\n \/*!\n * \\brief Divide the given left-hand-side expression\n * \\param lhs The expression to which assign\n *\/\n template <typename L>\n void assign_div_to(L&& lhs) const {\n static_assert(all_etl_expr<A, L>::value, \"bias_batch_mean only supported for ETL expressions\");\n\n auto& a = this->a();\n\n standard_evaluator::pre_assign_rhs(a);\n\n const auto N = etl::size(a) \/ etl::size(lhs);\n const auto K = etl::size(lhs);\n\n using T = value_t<A>;\n\n check(a, lhs);\n\n auto batch_fun_k = [&](const size_t first, const size_t last) {\n if (last - first) {\n SERIAL_SECTION {\n for (size_t k = first; k < last; ++k) {\n T mean(0);\n\n for (size_t b = 0; b < etl::dim<0>(a); ++b) {\n mean += sum(a(b)(k));\n }\n\n lhs(k) \/= mean \/ N;\n }\n }\n }\n };\n\n engine_dispatch_1d(batch_fun_k, 0, K, 2UL);\n }\n\n \/*!\n * \\brief Modulo the given left-hand-side expression\n * \\param lhs The expression to which assign\n *\/\n template <typename L>\n void assign_mod_to(L&& lhs) const {\n static_assert(all_etl_expr<A, L>::value, \"bias_batch_mean only supported for ETL expressions\");\n\n auto& a = this->a();\n\n standard_evaluator::pre_assign_rhs(a);\n\n const auto N = etl::size(a) \/ etl::size(lhs);\n const auto K = etl::size(lhs);\n\n using T = value_t<A>;\n\n check(a, lhs);\n\n auto batch_fun_k = [&](const size_t first, const size_t last) {\n if (last - first) {\n SERIAL_SECTION {\n for (size_t k = first; k < last; ++k) {\n T mean(0);\n\n for (size_t b = 0; b < etl::dim<0>(a); ++b) {\n mean += sum(a(b)(k));\n }\n\n lhs(k) %= mean \/ N;\n }\n }\n }\n };\n\n engine_dispatch_1d(batch_fun_k, 0, K, 2UL);\n }\n\n \/*!\n * \\brief Print a representation of the expression on the given stream\n * \\param os The output stream\n * \\param expr The expression to print\n * \\return the output stream\n *\/\n friend std::ostream& operator<<(std::ostream& os, const bias_batch_mean_expr& expr) {\n return os << \"bias_batch_mean(\" << expr._a << \")\";\n }\n};\n\n\/*!\n * \\brief Traits for a transpose expression\n * \\tparam A The transposed sub type\n *\/\ntemplate <typename A>\nstruct etl_traits<etl::bias_batch_mean_expr<A>> {\n using expr_t = etl::bias_batch_mean_expr<A>; \/\/\/< The expression type\n using sub_expr_t = std::decay_t<A>; \/\/\/< The sub expression type\n using sub_traits = etl_traits<sub_expr_t>; \/\/\/< The sub traits\n using value_type = value_t<A>; \/\/\/< The value type of the expression\n\n static constexpr bool is_etl = true; \/\/\/< Indicates if the type is an ETL expression\n static constexpr bool is_transformer = false; \/\/\/< Indicates if the type is a transformer\n static constexpr bool is_view = false; \/\/\/< Indicates if the type is a view\n static constexpr bool is_magic_view = false; \/\/\/< Indicates if the type is a magic view\n static constexpr bool is_fast = sub_traits::is_fast; \/\/\/< Indicates if the expression is fast\n static constexpr bool is_linear = true; \/\/\/< Indicates if the expression is linear\n static constexpr bool is_thread_safe = true; \/\/\/< Indicates if the expression is thread safe\n static constexpr bool is_value = false; \/\/\/< Indicates if the expression is of value type\n static constexpr bool is_direct = true; \/\/\/< Indicates if the expression has direct memory access\n static constexpr bool is_generator = false; \/\/\/< Indicates if the expression is a generator\n static constexpr bool is_padded = false; \/\/\/< Indicates if the expression is padded\n static constexpr bool is_aligned = true; \/\/\/< Indicates if the expression is padded\n static constexpr bool is_gpu = false; \/\/\/< Indicates if the expression can be done on GPU\n static constexpr bool is_temporary = true; \/\/\/< Indicates if the expression needs a evaluator visitor\n static constexpr order storage_order = sub_traits::storage_order; \/\/\/< The expression's storage order\n\n \/*!\n * \\brief Indicates if the expression is vectorizable using the\n * given vector mode\n * \\tparam V The vector mode\n *\/\n template <vector_mode_t V>\n using vectorizable = std::true_type;\n\n \/*!\n * \\brief Returns the DDth dimension of the expression\n * \\return the DDth dimension of the expression\n *\/\n template <size_t DD>\n static constexpr size_t dim() {\n static_assert(DD == 0, \"Invalid dimensions access\");\n return decay_traits<A>::template dim<1>();\n }\n\n \/*!\n * \\brief Returns the dth dimension of the expression\n * \\param e The sub expression\n * \\param d The dimension to get\n * \\return the dth dimension of the expression\n *\/\n static size_t dim(const expr_t& e, size_t d) {\n cpp_assert(d == 0, \"Invalid dimensions access\");\n cpp_unused(d);\n return etl::dim<1>(e._a);\n }\n\n \/*!\n * \\brief Returns the size of the expression\n * \\param e The sub expression\n * \\return the size of the expression\n *\/\n static size_t size(const expr_t& e) {\n return etl::dim<1>(e._a);\n }\n\n \/*!\n * \\brief Returns the size of the expression\n * \\return the size of the expression\n *\/\n static constexpr size_t size() {\n return decay_traits<A>::template dim<1>();\n }\n\n \/*!\n * \\brief Returns the number of dimensions of the expression\n * \\return the number of dimensions of the expression\n *\/\n static constexpr size_t dimensions() {\n return 1;\n }\n};\n\n\/*!\n * \\brief Returns the transpose of the given expression.\n * \\param value The expression\n * \\return The transpose of the given expression.\n *\/\ntemplate <typename E>\nbias_batch_mean_expr<detail::build_type<E>> bias_batch_mean(const E& value) {\n static_assert(is_etl_expr<E>::value, \"etl::bias_batch_mean can only be used on ETL expressions\");\n static_assert(decay_traits<E>::dimensions() == 4, \"etl::bias_batch_mean is only defined for 4D input\");\n\n return bias_batch_mean_expr<detail::build_type<E>>{value};\n}\n\n} \/\/end of namespace etl\n<|endoftext|>"} {"text":"<commit_before><commit_msg>Force #defined constants to sal_uInt32 to reduce conversion warnings<commit_after><|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ Logarithm.cpp\n\/\/ Calculator\n\/\/\n\/\/ Created by Gavin Scheele on 3\/27\/14.\n\/\/ Copyright (c) 2014 Gavin Scheele. All rights reserved.\n\/\/\n\n#include \"Logarithm.h\"\n\nLogarithm::Logarithm(int base, int operand){\n this->base = base;\n this->operand = operand;\n}\nLogarithm::~Logarithm(){\n \n}\nExpression Logarithm::simplify(){\n Expression* c = this;\n return *c;\n}\n\n\n\nExpression* Logarithm::add(Expression* a, Expression* b){\n Expression* c = this;\n return c;\n}\nExpression* Logarithm::subtract(Expression* a, Expression* b){\n Expression* c = this;\n return c;\n}\nExpression* Logarithm::multiply(Expression* a, Expression* b){\n Expression* c = this;\n return c;\n}\nExpression* Logarithm::divide(Expression* a, Expression* b){\n Expression* c = this;\n return c;\n}\n<commit_msg>Added virtual print function<commit_after>\/\/\n\/\/ Logarithm.cpp\n\/\/ Calculator\n\/\/\n\/\/ Created by Gavin Scheele on 3\/27\/14.\n\/\/ Copyright (c) 2014 Gavin Scheele. All rights reserved.\n\/\/\n\n#include \"Logarithm.h\"\n\nLogarithm::Logarithm(int base, int operand){\n this->type = \"logarithm\";\n this->base = base;\n this->operand = operand;\n}\nLogarithm::~Logarithm(){\n \n}\nExpression Logarithm::simplify(){\n Expression* c = this;\n return *c;\n}\n\n\n\nExpression* Logarithm::add(Expression* a){\n Expression* c = this;\n return c;\n}\nExpression* Logarithm::subtract(Expression* a){\n Expression* c = this;\n return c;\n}\nExpression* Logarithm::multiply(Expression* a){\n Expression* c = this;\n return c;\n}\nExpression* Logarithm::divide(Expression* a){\n Expression* c = this;\n return c;\n}\nostream& Logarithm::print(std::ostream& output) const{\n output << \"Log\" << this->base << \"(\" << this->operand << \")\";\n return output;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2013 The Flutter Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"flutter\/shell\/platform\/common\/cpp\/client_wrapper\/testing\/encodable_value_utils.h\"\n\n#include <cmath>\n\nnamespace flutter {\nnamespace testing {\n\nbool EncodableValuesAreEqual(const EncodableValue& a, const EncodableValue& b) {\n if (a.type() != b.type()) {\n return false;\n }\n\n switch (a.type()) {\n case EncodableValue::Type::kNull:\n return true;\n case EncodableValue::Type::kBool:\n return a.BoolValue() == b.BoolValue();\n case EncodableValue::Type::kInt:\n return a.IntValue() == b.IntValue();\n case EncodableValue::Type::kLong:\n return a.LongValue() == b.LongValue();\n case EncodableValue::Type::kDouble:\n \/\/ This is a crude epsilon, but fine for the values in the the unit tests.\n return std::abs(a.DoubleValue() - b.DoubleValue()) < 0.0001l;\n case EncodableValue::Type::kString:\n return a.StringValue() == b.StringValue();\n case EncodableValue::Type::kByteList:\n return a.ByteListValue() == b.ByteListValue();\n case EncodableValue::Type::kIntList:\n return a.IntListValue() == b.IntListValue();\n case EncodableValue::Type::kLongList:\n return a.LongListValue() == b.LongListValue();\n case EncodableValue::Type::kDoubleList:\n return a.DoubleListValue() == b.DoubleListValue();\n case EncodableValue::Type::kList: {\n const auto& a_list = a.ListValue();\n const auto& b_list = b.ListValue();\n if (a_list.size() != b_list.size()) {\n return false;\n }\n for (size_t i = 0; i < a_list.size(); ++i) {\n if (!EncodableValuesAreEqual(a_list[0], b_list[0])) {\n return false;\n }\n }\n return true;\n }\n case EncodableValue::Type::kMap: {\n const auto& a_map = a.MapValue();\n const auto& b_map = b.MapValue();\n if (a_map.size() != b_map.size()) {\n return false;\n }\n \/\/ Store references to all the keys in |b|.\n std::vector<const EncodableValue*> unmatched_b_keys;\n for (auto& pair : b_map) {\n unmatched_b_keys.push_back(&pair.first);\n }\n \/\/ For each key,value in |a|, see if any of the not-yet-matched key,value\n \/\/ pairs in |b| match by value; if so, remove that match and continue.\n for (const auto& pair : a_map) {\n bool found_match = false;\n for (size_t i = 0; i < unmatched_b_keys.size(); ++i) {\n const EncodableValue& b_key = *unmatched_b_keys[i];\n if (EncodableValuesAreEqual(pair.first, b_key) &&\n EncodableValuesAreEqual(pair.second, b_map.at(b_key))) {\n found_match = true;\n unmatched_b_keys.erase(unmatched_b_keys.begin() + i);\n break;\n }\n }\n if (!found_match) {\n return false;\n }\n }\n \/\/ If all entries had matches, consider the maps equal.\n return true;\n }\n }\n assert(false);\n return false;\n}\n\n} \/\/ namespace testing\n} \/\/ namespace flutter\n<commit_msg>Fix typo in comment (#8617)<commit_after>\/\/ Copyright 2013 The Flutter Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"flutter\/shell\/platform\/common\/cpp\/client_wrapper\/testing\/encodable_value_utils.h\"\n\n#include <cmath>\n\nnamespace flutter {\nnamespace testing {\n\nbool EncodableValuesAreEqual(const EncodableValue& a, const EncodableValue& b) {\n if (a.type() != b.type()) {\n return false;\n }\n\n switch (a.type()) {\n case EncodableValue::Type::kNull:\n return true;\n case EncodableValue::Type::kBool:\n return a.BoolValue() == b.BoolValue();\n case EncodableValue::Type::kInt:\n return a.IntValue() == b.IntValue();\n case EncodableValue::Type::kLong:\n return a.LongValue() == b.LongValue();\n case EncodableValue::Type::kDouble:\n \/\/ This is a crude epsilon, but fine for the values in the unit tests.\n return std::abs(a.DoubleValue() - b.DoubleValue()) < 0.0001l;\n case EncodableValue::Type::kString:\n return a.StringValue() == b.StringValue();\n case EncodableValue::Type::kByteList:\n return a.ByteListValue() == b.ByteListValue();\n case EncodableValue::Type::kIntList:\n return a.IntListValue() == b.IntListValue();\n case EncodableValue::Type::kLongList:\n return a.LongListValue() == b.LongListValue();\n case EncodableValue::Type::kDoubleList:\n return a.DoubleListValue() == b.DoubleListValue();\n case EncodableValue::Type::kList: {\n const auto& a_list = a.ListValue();\n const auto& b_list = b.ListValue();\n if (a_list.size() != b_list.size()) {\n return false;\n }\n for (size_t i = 0; i < a_list.size(); ++i) {\n if (!EncodableValuesAreEqual(a_list[0], b_list[0])) {\n return false;\n }\n }\n return true;\n }\n case EncodableValue::Type::kMap: {\n const auto& a_map = a.MapValue();\n const auto& b_map = b.MapValue();\n if (a_map.size() != b_map.size()) {\n return false;\n }\n \/\/ Store references to all the keys in |b|.\n std::vector<const EncodableValue*> unmatched_b_keys;\n for (auto& pair : b_map) {\n unmatched_b_keys.push_back(&pair.first);\n }\n \/\/ For each key,value in |a|, see if any of the not-yet-matched key,value\n \/\/ pairs in |b| match by value; if so, remove that match and continue.\n for (const auto& pair : a_map) {\n bool found_match = false;\n for (size_t i = 0; i < unmatched_b_keys.size(); ++i) {\n const EncodableValue& b_key = *unmatched_b_keys[i];\n if (EncodableValuesAreEqual(pair.first, b_key) &&\n EncodableValuesAreEqual(pair.second, b_map.at(b_key))) {\n found_match = true;\n unmatched_b_keys.erase(unmatched_b_keys.begin() + i);\n break;\n }\n }\n if (!found_match) {\n return false;\n }\n }\n \/\/ If all entries had matches, consider the maps equal.\n return true;\n }\n }\n assert(false);\n return false;\n}\n\n} \/\/ namespace testing\n} \/\/ namespace flutter\n<|endoftext|>"} {"text":"<commit_before>#include \"MainFrame.h\"\n\n#include \"RGBModel.h\"\n#include \"HSLModel.h\"\n#include \"CMYKModel.h\"\n\n#include \"HtmlHexOutput.h\"\n#include \"CssRgbOutput.h\"\n\n#include <wx\/aboutdlg.h>\n#include <wx\/dcscreen.h>\n#include <wx\/graphics.h>\n#include <wx\/dcmemory.h>\n#include <wx\/dialog.h>\n#include <wx\/gdicmn.h>\n#include <wx\/dnd.h>\n#include <wx\/dataobj.h>\n#include <wx\/colordlg.h>\n#include <wx\/colourdata.h>\n\nstruct ZoomMenuFunctor\n{\n ZoomPanel* panel;\n int zoom;\n ZoomMenuFunctor(ZoomPanel* p, int z) : panel(p), zoom(z) { }\n void operator()(wxCommandEvent& event)\n {\n panel->SetZoom(zoom);\n }\n};\n\nMainFrame::MainFrame(wxWindow* parent)\n : MainFrameBaseClass(parent), capturing(false), refreshTimer(this)\n{\n Bind(wxEVT_TIMER, &MainFrame::OnRefreshTimerEvent, this, refreshTimer.GetId());\n RestorePosition();\n \n colorOutput = new HtmlHexOutput;\n AddColorOutput(colorOutput);\n AddColorOutput(new CssRgbOutput);\n \n colorModel = new RGBModel;\n AddColorModel(colorModel);\n AddColorModel(new HSLModel);\n AddColorModel(new CMYKModel);\n UpdateColorModel();\n \n SetColor(wxColour(\n config.ReadLong(\"Main\/Color\/R\", 0),\n config.ReadLong(\"Main\/Color\/G\", 0),\n config.ReadLong(\"Main\/Color\/B\", 0)\n ));\n \n m_zoomPanel->SetPoi(wxPoint(\n config.ReadLong(\"Main\/ZoomPanel\/X\", 0),\n config.ReadLong(\"Main\/ZoomPanel\/Y\", 0)\n ));\n m_zoomPanel->SetZoom(config.ReadLong(\"Main\/ZoomPanel\/Zoom\", 4));\n}\n\nMainFrame::~MainFrame()\n{\n wxPoint pos = GetPosition();\n config.Write(\"Main\/Position\/X\", pos.x);\n config.Write(\"Main\/Position\/Y\", pos.y);\n wxColour col = GetColor();\n config.Write(\"Main\/Color\/R\", col.Red());\n config.Write(\"Main\/Color\/G\", col.Green());\n config.Write(\"Main\/Color\/B\", col.Blue());\n wxPoint poi = m_zoomPanel->GetPoi();\n config.Write(\"Main\/ZoomPanel\/X\", poi.x);\n config.Write(\"Main\/ZoomPanel\/Y\", poi.y);\n config.Write(\"Main\/ZoomPanel\/Zoom\", m_zoomPanel->GetZoom());\n config.Write(\"Main\/Model\", wxString(colorModel->getName()));\n config.Write(\"Main\/Output\", wxString(colorOutput->getName()));\n}\n\nvoid MainFrame::RestorePosition()\n{\n int x = config.ReadLong(\"Main\/Position\/X\", GetPosition().x);\n int y = config.ReadLong(\"Main\/Position\/Y\", GetPosition().y);\n wxSize screenSize = wxGetDisplaySize();\n wxSize windowSize = GetSize();\n if (x < 0) x = 0;\n if (y < 0) y = 0;\n if (x > (screenSize.x - windowSize.x)) x = screenSize.x - windowSize.x;\n if (y > (screenSize.y - windowSize.y)) y = screenSize.y - windowSize.y;\n SetPosition(wxPoint(x, y));\n}\n\nint MainFrame::AddColorModel(IColorModel* colorModel)\n{\n wxWindowID id = wxIdManager::ReserveId();\n colorModels[id] = colorModel;\n wxMenuItem* menuItem = new wxMenuItem(m_colorModelMenu, id, colorModel->getName(), wxT(\"\"), wxITEM_RADIO);\n m_colorModelMenu->Append(menuItem);\n m_colorModelMenu->Bind(wxEVT_COMMAND_MENU_SELECTED, &MainFrame::OnSelectColorModel, this, menuItem->GetId());\n if (colorModel->getName() == config.Read(\"Main\/Model\", \"RGB\"))\n {\n this->colorModel = colorModel;\n menuItem->Check();\n }\n return id;\n}\n\nint MainFrame::AddColorOutput(IColorOutput* colorOutput)\n{\n wxWindowID id = wxIdManager::ReserveId();\n colorOutputs[id] = colorOutput;\n wxMenuItem* menuItem = new wxMenuItem(m_colorOutputMenu, id, colorOutput->getName(), wxT(\"\"), wxITEM_RADIO);\n m_colorOutputMenu->Append(menuItem);\n m_colorOutputMenu->Bind(wxEVT_COMMAND_MENU_SELECTED, &MainFrame::OnSelectColorOutput, this, menuItem->GetId());\n if (colorOutput->getName() == config.Read(\"Main\/Output\", \"Hexadecimal (HTML\/CSS)\"))\n {\n this->colorOutput = colorOutput;\n menuItem->Check();\n }\n return id;\n}\n\nvoid MainFrame::SetColorModel(IColorModel* colorModel)\n{\n this->colorModel = colorModel;\n UpdateColorModel();\n}\n\nvoid MainFrame::SetColorOutput(IColorOutput* colorOutput)\n{\n this->colorOutput = colorOutput;\n SetColor(GetColor());\n}\n\nvoid update_label_and_ctrl(int i, IColorModel* colorModel, wxStaticText* label, wxSpinCtrl* ctrl)\n{\n if (colorModel->getNumComponents() > i) {\n label->Show(true);\n ctrl->Show(true);\n std::string labelStr = colorModel->getLabel(i);\n label->SetLabel(labelStr.substr(0, 1).append(\":\"));\n label->SetToolTip(labelStr);\n ctrl->SetToolTip(labelStr);\n ctrl->SetMin(colorModel->getMin(i));\n ctrl->SetMax(colorModel->getMax(i));\n }\n else {\n label->Show(false);\n ctrl->Show(false);\n }\n}\n\nvoid MainFrame::UpdateColorModel()\n{\n update_label_and_ctrl(0, colorModel, m_firstLabel, m_firstCtrl);\n update_label_and_ctrl(1, colorModel, m_secondLabel, m_secondCtrl);\n update_label_and_ctrl(2, colorModel, m_thirdLabel, m_thirdCtrl);\n update_label_and_ctrl(3, colorModel, m_fourthLabel, m_fourthCtrl);\n SetColor(GetColor());\n}\n\nvoid MainFrame::OnExit(wxCommandEvent& event)\n{\n wxUnusedVar(event);\n Close();\n}\n\nvoid MainFrame::OnAbout(wxCommandEvent& event)\n{\n wxUnusedVar(event);\n wxAboutDialogInfo info;\n info.SetName(\"ColorGrab\");\n info.SetVersion(\"0.1-dev\");\n info.SetWebSite(\"http:\/\/nielssp.dk\");\n info.SetCopyright(_(\"(C) 2015 Niels Sonnich Poulsen\"));\n info.SetLicence(_(\"MIT License\"));\n info.SetDescription(_(\"Free color picker tool.\"));\n ::wxAboutBox(info);\n}\n\nwxBitmap GetScreenShot()\n{\n wxSize screenSize = wxGetDisplaySize();\n wxBitmap bitmap(screenSize.x, screenSize.y);\n wxScreenDC dc;\n wxMemoryDC memDC;\n memDC.SelectObject(bitmap);\n memDC.Blit(0, 0, screenSize.x, screenSize.y, &dc, 0, 0);\n memDC.SelectObject(wxNullBitmap);\n return bitmap;\n}\n\nvoid MainFrame::UpdateZoomArea()\n{\n m_zoomPanel->SetPoi(wxGetMousePosition());\n}\n\nvoid MainFrame::SetColorFromMouse()\n{\n int x, y;\n wxGetMousePosition(&x, &y);\n SetColorFromPixel(x, y);\n}\n\nvoid MainFrame::SetColorFromPixel(wxCoord x, wxCoord y)\n{\n wxColor color;\n wxScreenDC dc;\n dc.GetPixel(x, y, &color);\n SetColor(color);\n}\n\nwxColor MainFrame::GetColor() const\n{\n return m_colorButton->GetBackgroundColour();\n}\n\nvoid MainFrame::SetColor(const wxColor& color, bool updateInputs, bool updateOutput)\n{\n\/\/ m_colourPicker->SetColour(color);\n m_colorButton->SetBackgroundColour(color);\n\tm_colorButton->Refresh();\n colorModel->setColor(color);\n if (updateInputs)\n {\n m_firstCtrl->SetValue(colorModel->getValue(0));\n m_secondCtrl->SetValue(colorModel->getValue(1));\n m_thirdCtrl->SetValue(colorModel->getValue(2));\n m_fourthCtrl->SetValue(colorModel->getValue(3));\n }\n colorOutput->setColor(color);\n if (updateOutput)\n m_formatText->ChangeValue(colorOutput->getOutput());\n}\n\nvoid MainFrame::OnColorChange(wxCommandEvent& event)\n{\n colorModel->setValue(0, m_firstCtrl->GetValue());\n colorModel->setValue(1, m_secondCtrl->GetValue());\n colorModel->setValue(2, m_thirdCtrl->GetValue());\n colorModel->setValue(3, m_fourthCtrl->GetValue());\n SetColor(colorModel->getColor(), false);\n}\n\nvoid MainFrame::OnCaptureStart(wxMouseEvent& event)\n{\n SetColorFromMouse();\n UpdateZoomArea();\n CaptureMouse();\n SetCursor(*wxCROSS_CURSOR);\n capturing = true;\n SetFocus();\n}\nvoid MainFrame::OnCaptureEnd(wxMouseEvent& event)\n{\n if (capturing)\n {\n SetColorFromMouse();\n UpdateZoomArea();\n ReleaseMouse();\n capturing = false;\n SetCursor(wxNullCursor);\n }\n}\nvoid MainFrame::OnCaptureMove(wxMouseEvent& event)\n{\n if (capturing) {\n SetColorFromMouse();\n UpdateZoomArea();\n }\n}\n\nvoid MainFrame::OnSystemColorPicker(wxCommandEvent& event)\n{\n wxColourDialog dialog(this);\n dialog.GetColourData().SetColour(GetColor());\n dialog.ShowModal();\n SetColor(dialog.GetColourData().GetColour());\n}\nvoid MainFrame::OnFormatChoose(wxMenuEvent& event)\n{\n}\nvoid MainFrame::OnFormatClick(wxCommandEvent& event)\n{\n}\nvoid MainFrame::OnCaptureZoom(wxMouseEvent& event)\n{\n if (capturing)\n OnZoomPanelZoom(event);\n}\n\nvoid MainFrame::OnZoomSelect(wxCommandEvent& event)\n{\n m_zoomPanel->SetZoom(2);\n}\nvoid MainFrame::OnZoomPanelDown(wxMouseEvent& event)\n{\n m_zoomPanel->ShowPoi(false);\n m_zoomPanel->SetFocus();\n SetColorFromMouse();\n capturing = true;\n}\nvoid MainFrame::OnZoomPanelMove(wxMouseEvent& event)\n{\n m_zoomPanel->SetFocus();\n if (capturing)\n SetColorFromMouse();\n}\nvoid MainFrame::OnZoomPanelUp(wxMouseEvent& event)\n{\n SetColorFromMouse();\n capturing = false;\n}\nvoid MainFrame::OnZoomPanelZoom(wxMouseEvent& event)\n{\n int zoom = m_zoomPanel->GetZoom();\n if (event.GetWheelRotation() > 0 && zoom < 64)\n zoom *= 2;\n else if (event.GetWheelRotation() < 0 && zoom > 1)\n zoom \/= 2;\n m_zoomPanel->SetZoom(zoom);\n}\n\nvoid MainFrame::OnSelectColorModel(wxCommandEvent& event)\n{\n SetColorModel(colorModels[event.GetId()]);\n}\n\nvoid MainFrame::OnSelectColorOutput(wxCommandEvent& event)\n{\n SetColorOutput(colorOutputs[event.GetId()]);\n}\nvoid MainFrame::OnColorOutputChange(wxCommandEvent& event)\n{\n colorOutput->setOutput(m_formatText->GetValue().ToStdString());\n SetColor(colorOutput->getColor(), true, false);\n}\nvoid MainFrame::OnInputOutputBlur(wxFocusEvent& event)\n{\n SetColor(GetColor());\n event.Skip();\n}\nvoid MainFrame::OnInputOutputEnter(wxCommandEvent& event)\n{\n SetColor(GetColor());\n}\nvoid MainFrame::OnZoomIn(wxCommandEvent& event)\n{\n int zoom = m_zoomPanel->GetZoom();\n if (zoom < 64)\n zoom *= 2;\n m_zoomPanel->SetZoom(zoom);\n}\nvoid MainFrame::OnZoomOut(wxCommandEvent& event)\n{\n int zoom = m_zoomPanel->GetZoom();\n if (zoom > 1)\n zoom \/= 2;\n m_zoomPanel->SetZoom(zoom);\n}\nvoid MainFrame::OnRefreshImage(wxCommandEvent& event)\n{\n m_zoomPanel->Update();\n}\nvoid MainFrame::OnSelectTiming(wxCommandEvent& event)\n{\n int interval = timerIntervals[event.GetId()];\n m_timerButton->Disable();\n refreshTimer.Start(interval * 1000);\n}\nvoid MainFrame::OnTimerRefreshImage(wxCommandEvent& event)\n{\n wxMenu menu(_(\"Refresh image in...\"));\n timerIntervals.clear();\n int intervals [] = {1, 2, 5};\n for (int i = 0; i < 3; i++) {\n wxMenuItem* item;\n if (i == 1)\n item = menu.Append(wxID_ANY, wxString::Format(_(\"%d second\"), intervals[i]));\n else\n item = menu.Append(wxID_ANY, wxString::Format(_(\"%d seconds\"), intervals[i]));\n menu.Bind(wxEVT_COMMAND_MENU_SELECTED, &MainFrame::OnSelectTiming, this, item->GetId());\n timerIntervals[item->GetId()] = intervals[i];\n }\n m_timerButton->PopupMenu(&menu);\n}\n\nvoid MainFrame::OnRefreshTimerEvent(wxTimerEvent& event)\n{\n m_zoomPanel->Update();\n m_timerButton->Enable();\n refreshTimer.Stop();\n}<commit_msg>Model\/output shortcuts.<commit_after>#include \"MainFrame.h\"\n\n#include \"RGBModel.h\"\n#include \"HSLModel.h\"\n#include \"CMYKModel.h\"\n\n#include \"HtmlHexOutput.h\"\n#include \"CssRgbOutput.h\"\n\n#include <wx\/aboutdlg.h>\n#include <wx\/dcscreen.h>\n#include <wx\/graphics.h>\n#include <wx\/dcmemory.h>\n#include <wx\/dialog.h>\n#include <wx\/gdicmn.h>\n#include <wx\/dnd.h>\n#include <wx\/dataobj.h>\n#include <wx\/colordlg.h>\n#include <wx\/colourdata.h>\n\nstruct ZoomMenuFunctor\n{\n ZoomPanel* panel;\n int zoom;\n ZoomMenuFunctor(ZoomPanel* p, int z) : panel(p), zoom(z) { }\n void operator()(wxCommandEvent& event)\n {\n panel->SetZoom(zoom);\n }\n};\n\nMainFrame::MainFrame(wxWindow* parent)\n : MainFrameBaseClass(parent), capturing(false), refreshTimer(this)\n{\n Bind(wxEVT_TIMER, &MainFrame::OnRefreshTimerEvent, this, refreshTimer.GetId());\n RestorePosition();\n \n colorOutput = new HtmlHexOutput;\n AddColorOutput(colorOutput);\n AddColorOutput(new CssRgbOutput);\n \n colorModel = new RGBModel;\n AddColorModel(colorModel);\n AddColorModel(new HSLModel);\n AddColorModel(new CMYKModel);\n UpdateColorModel();\n \n SetColor(wxColour(\n config.ReadLong(\"Main\/Color\/R\", 0),\n config.ReadLong(\"Main\/Color\/G\", 0),\n config.ReadLong(\"Main\/Color\/B\", 0)\n ));\n \n m_zoomPanel->SetPoi(wxPoint(\n config.ReadLong(\"Main\/ZoomPanel\/X\", 0),\n config.ReadLong(\"Main\/ZoomPanel\/Y\", 0)\n ));\n m_zoomPanel->SetZoom(config.ReadLong(\"Main\/ZoomPanel\/Zoom\", 4));\n}\n\nMainFrame::~MainFrame()\n{\n wxPoint pos = GetPosition();\n config.Write(\"Main\/Position\/X\", pos.x);\n config.Write(\"Main\/Position\/Y\", pos.y);\n wxColour col = GetColor();\n config.Write(\"Main\/Color\/R\", col.Red());\n config.Write(\"Main\/Color\/G\", col.Green());\n config.Write(\"Main\/Color\/B\", col.Blue());\n wxPoint poi = m_zoomPanel->GetPoi();\n config.Write(\"Main\/ZoomPanel\/X\", poi.x);\n config.Write(\"Main\/ZoomPanel\/Y\", poi.y);\n config.Write(\"Main\/ZoomPanel\/Zoom\", m_zoomPanel->GetZoom());\n config.Write(\"Main\/Model\", wxString(colorModel->getName()));\n config.Write(\"Main\/Output\", wxString(colorOutput->getName()));\n}\n\nvoid MainFrame::RestorePosition()\n{\n int x = config.ReadLong(\"Main\/Position\/X\", GetPosition().x);\n int y = config.ReadLong(\"Main\/Position\/Y\", GetPosition().y);\n wxSize screenSize = wxGetDisplaySize();\n wxSize windowSize = GetSize();\n if (x < 0) x = 0;\n if (y < 0) y = 0;\n if (x > (screenSize.x - windowSize.x)) x = screenSize.x - windowSize.x;\n if (y > (screenSize.y - windowSize.y)) y = screenSize.y - windowSize.y;\n SetPosition(wxPoint(x, y));\n}\n\nint MainFrame::AddColorModel(IColorModel* colorModel)\n{\n wxWindowID id = wxIdManager::ReserveId();\n colorModels[id] = colorModel;\n wxMenuItem* menuItem = new wxMenuItem(m_colorModelMenu, id, wxString::Format(\"%s\\tCtrl-%d\", colorModel->getName(), colorModels.size()), wxT(\"\"), wxITEM_RADIO);\n m_colorModelMenu->Append(menuItem);\n m_colorModelMenu->Bind(wxEVT_COMMAND_MENU_SELECTED, &MainFrame::OnSelectColorModel, this, menuItem->GetId());\n if (colorModel->getName() == config.Read(\"Main\/Model\", \"RGB\"))\n {\n this->colorModel = colorModel;\n menuItem->Check();\n }\n return id;\n}\n\nint MainFrame::AddColorOutput(IColorOutput* colorOutput)\n{\n wxWindowID id = wxIdManager::ReserveId();\n colorOutputs[id] = colorOutput;\n wxMenuItem* menuItem = new wxMenuItem(m_colorOutputMenu, id, wxString::Format(\"%s\\tCtrl-Shift-%d\", colorOutput->getName(), colorOutputs.size()), wxT(\"\"), wxITEM_RADIO);\n m_colorOutputMenu->Append(menuItem);\n m_colorOutputMenu->Bind(wxEVT_COMMAND_MENU_SELECTED, &MainFrame::OnSelectColorOutput, this, menuItem->GetId());\n if (colorOutput->getName() == config.Read(\"Main\/Output\", \"Hexadecimal (HTML\/CSS)\"))\n {\n this->colorOutput = colorOutput;\n menuItem->Check();\n }\n return id;\n}\n\nvoid MainFrame::SetColorModel(IColorModel* colorModel)\n{\n this->colorModel = colorModel;\n UpdateColorModel();\n}\n\nvoid MainFrame::SetColorOutput(IColorOutput* colorOutput)\n{\n this->colorOutput = colorOutput;\n SetColor(GetColor());\n}\n\nvoid update_label_and_ctrl(int i, IColorModel* colorModel, wxStaticText* label, wxSpinCtrl* ctrl)\n{\n if (colorModel->getNumComponents() > i) {\n label->Show(true);\n ctrl->Show(true);\n std::string labelStr = colorModel->getLabel(i);\n label->SetLabel(labelStr.substr(0, 1).append(\":\"));\n label->SetToolTip(labelStr);\n ctrl->SetToolTip(labelStr);\n ctrl->SetMin(colorModel->getMin(i));\n ctrl->SetMax(colorModel->getMax(i));\n }\n else {\n label->Show(false);\n ctrl->Show(false);\n }\n}\n\nvoid MainFrame::UpdateColorModel()\n{\n update_label_and_ctrl(0, colorModel, m_firstLabel, m_firstCtrl);\n update_label_and_ctrl(1, colorModel, m_secondLabel, m_secondCtrl);\n update_label_and_ctrl(2, colorModel, m_thirdLabel, m_thirdCtrl);\n update_label_and_ctrl(3, colorModel, m_fourthLabel, m_fourthCtrl);\n SetColor(GetColor());\n}\n\nvoid MainFrame::OnExit(wxCommandEvent& event)\n{\n wxUnusedVar(event);\n Close();\n}\n\nvoid MainFrame::OnAbout(wxCommandEvent& event)\n{\n wxUnusedVar(event);\n wxAboutDialogInfo info;\n info.SetName(\"ColorGrab\");\n info.SetVersion(\"0.1-dev\");\n info.SetWebSite(\"http:\/\/nielssp.dk\");\n info.SetCopyright(_(\"(C) 2015 Niels Sonnich Poulsen\"));\n info.SetLicence(_(\"MIT License\"));\n info.SetDescription(_(\"Free color picker tool.\"));\n ::wxAboutBox(info);\n}\n\nwxBitmap GetScreenShot()\n{\n wxSize screenSize = wxGetDisplaySize();\n wxBitmap bitmap(screenSize.x, screenSize.y);\n wxScreenDC dc;\n wxMemoryDC memDC;\n memDC.SelectObject(bitmap);\n memDC.Blit(0, 0, screenSize.x, screenSize.y, &dc, 0, 0);\n memDC.SelectObject(wxNullBitmap);\n return bitmap;\n}\n\nvoid MainFrame::UpdateZoomArea()\n{\n m_zoomPanel->SetPoi(wxGetMousePosition());\n}\n\nvoid MainFrame::SetColorFromMouse()\n{\n int x, y;\n wxGetMousePosition(&x, &y);\n SetColorFromPixel(x, y);\n}\n\nvoid MainFrame::SetColorFromPixel(wxCoord x, wxCoord y)\n{\n wxColor color;\n wxScreenDC dc;\n dc.GetPixel(x, y, &color);\n SetColor(color);\n}\n\nwxColor MainFrame::GetColor() const\n{\n return m_colorButton->GetBackgroundColour();\n}\n\nvoid MainFrame::SetColor(const wxColor& color, bool updateInputs, bool updateOutput)\n{\n\/\/ m_colourPicker->SetColour(color);\n m_colorButton->SetBackgroundColour(color);\n\tm_colorButton->Refresh();\n colorModel->setColor(color);\n if (updateInputs)\n {\n m_firstCtrl->SetValue(colorModel->getValue(0));\n m_secondCtrl->SetValue(colorModel->getValue(1));\n m_thirdCtrl->SetValue(colorModel->getValue(2));\n m_fourthCtrl->SetValue(colorModel->getValue(3));\n }\n colorOutput->setColor(color);\n if (updateOutput)\n m_formatText->ChangeValue(colorOutput->getOutput());\n}\n\nvoid MainFrame::OnColorChange(wxCommandEvent& event)\n{\n colorModel->setValue(0, m_firstCtrl->GetValue());\n colorModel->setValue(1, m_secondCtrl->GetValue());\n colorModel->setValue(2, m_thirdCtrl->GetValue());\n colorModel->setValue(3, m_fourthCtrl->GetValue());\n SetColor(colorModel->getColor(), false);\n}\n\nvoid MainFrame::OnCaptureStart(wxMouseEvent& event)\n{\n SetColorFromMouse();\n UpdateZoomArea();\n CaptureMouse();\n SetCursor(*wxCROSS_CURSOR);\n capturing = true;\n SetFocus();\n}\nvoid MainFrame::OnCaptureEnd(wxMouseEvent& event)\n{\n if (capturing)\n {\n SetColorFromMouse();\n UpdateZoomArea();\n ReleaseMouse();\n capturing = false;\n SetCursor(wxNullCursor);\n }\n}\nvoid MainFrame::OnCaptureMove(wxMouseEvent& event)\n{\n if (capturing) {\n SetColorFromMouse();\n UpdateZoomArea();\n }\n}\n\nvoid MainFrame::OnSystemColorPicker(wxCommandEvent& event)\n{\n wxColourDialog dialog(this);\n dialog.GetColourData().SetColour(GetColor());\n dialog.ShowModal();\n SetColor(dialog.GetColourData().GetColour());\n}\nvoid MainFrame::OnFormatChoose(wxMenuEvent& event)\n{\n}\nvoid MainFrame::OnFormatClick(wxCommandEvent& event)\n{\n}\nvoid MainFrame::OnCaptureZoom(wxMouseEvent& event)\n{\n if (capturing)\n OnZoomPanelZoom(event);\n}\n\nvoid MainFrame::OnZoomSelect(wxCommandEvent& event)\n{\n m_zoomPanel->SetZoom(2);\n}\nvoid MainFrame::OnZoomPanelDown(wxMouseEvent& event)\n{\n m_zoomPanel->ShowPoi(false);\n m_zoomPanel->SetFocus();\n SetColorFromMouse();\n capturing = true;\n}\nvoid MainFrame::OnZoomPanelMove(wxMouseEvent& event)\n{\n m_zoomPanel->SetFocus();\n if (capturing)\n SetColorFromMouse();\n}\nvoid MainFrame::OnZoomPanelUp(wxMouseEvent& event)\n{\n SetColorFromMouse();\n capturing = false;\n}\nvoid MainFrame::OnZoomPanelZoom(wxMouseEvent& event)\n{\n int zoom = m_zoomPanel->GetZoom();\n if (event.GetWheelRotation() > 0 && zoom < 64)\n zoom *= 2;\n else if (event.GetWheelRotation() < 0 && zoom > 1)\n zoom \/= 2;\n m_zoomPanel->SetZoom(zoom);\n}\n\nvoid MainFrame::OnSelectColorModel(wxCommandEvent& event)\n{\n SetColorModel(colorModels[event.GetId()]);\n}\n\nvoid MainFrame::OnSelectColorOutput(wxCommandEvent& event)\n{\n SetColorOutput(colorOutputs[event.GetId()]);\n}\nvoid MainFrame::OnColorOutputChange(wxCommandEvent& event)\n{\n colorOutput->setOutput(m_formatText->GetValue().ToStdString());\n SetColor(colorOutput->getColor(), true, false);\n}\nvoid MainFrame::OnInputOutputBlur(wxFocusEvent& event)\n{\n SetColor(GetColor());\n event.Skip();\n}\nvoid MainFrame::OnInputOutputEnter(wxCommandEvent& event)\n{\n SetColor(GetColor());\n}\nvoid MainFrame::OnZoomIn(wxCommandEvent& event)\n{\n int zoom = m_zoomPanel->GetZoom();\n if (zoom < 64)\n zoom *= 2;\n m_zoomPanel->SetZoom(zoom);\n}\nvoid MainFrame::OnZoomOut(wxCommandEvent& event)\n{\n int zoom = m_zoomPanel->GetZoom();\n if (zoom > 1)\n zoom \/= 2;\n m_zoomPanel->SetZoom(zoom);\n}\nvoid MainFrame::OnRefreshImage(wxCommandEvent& event)\n{\n m_zoomPanel->Update();\n}\nvoid MainFrame::OnSelectTiming(wxCommandEvent& event)\n{\n int interval = timerIntervals[event.GetId()];\n m_timerButton->Disable();\n refreshTimer.Start(interval * 1000);\n}\nvoid MainFrame::OnTimerRefreshImage(wxCommandEvent& event)\n{\n wxMenu menu(_(\"Refresh image in...\"));\n timerIntervals.clear();\n int intervals [] = {1, 2, 5};\n for (int i = 0; i < 3; i++) {\n wxMenuItem* item;\n if (i == 1)\n item = menu.Append(wxID_ANY, wxString::Format(_(\"%d second\"), intervals[i]));\n else\n item = menu.Append(wxID_ANY, wxString::Format(_(\"%d seconds\"), intervals[i]));\n menu.Bind(wxEVT_COMMAND_MENU_SELECTED, &MainFrame::OnSelectTiming, this, item->GetId());\n timerIntervals[item->GetId()] = intervals[i];\n }\n m_timerButton->PopupMenu(&menu);\n}\n\nvoid MainFrame::OnRefreshTimerEvent(wxTimerEvent& event)\n{\n m_zoomPanel->Update();\n m_timerButton->Enable();\n refreshTimer.Stop();\n}<|endoftext|>"} {"text":"<commit_before>\/\/ Natron\n\/* This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/. *\/\n\/*\n*Created by Alexandre GAUTHIER-FOICHAT on 6\/1\/2012. \n*contact: immarespond at gmail dot com\n*\n*\/\n\n#include \"Gui\/ComboBox.h\"\n\n#include <cassert>\n#include <algorithm>\n#include <QLayout>\n#include <QLabel>\n#include <QStyle>\n#include <QFont>\n#include <QFontMetrics>\n#include <QTextDocument> \/\/ for Qt::convertFromPlainText\n\n#include \"Engine\/AppManager.h\"\n#include \"Gui\/MenuWithToolTips.h\"\n\nusing namespace Natron;\n\nComboBox::ComboBox(QWidget* parent)\n: QFrame(parent)\n, _currentIndex(0)\n#if IS_MAXIMUMTEXTSIZE_USEFUL\n, _maximumTextSize(0)\n#endif\n, pressed(false)\n, animation(0)\n{\n \n _mainLayout = new QHBoxLayout(this);\n _mainLayout->setSpacing(0);\n _mainLayout->setContentsMargins(0, 0, 0, 0);\n setLayout(_mainLayout);\n setFrameShape(QFrame::Box);\n \n _currentText = new QLabel(this);\n _currentText->setObjectName(\"ComboBoxLabel\");\n setCurrentIndex(-1);\n _currentText->setMinimumWidth(10);\n _mainLayout->addWidget(_currentText);\n _currentText->setFixedHeight(fontMetrics().height() + 8);\n\n \n _dropDownIcon = new QLabel(this);\n _dropDownIcon->setObjectName(\"ComboBoxDropDownLabel\");\n QPixmap pixC;\n appPTR->getIcon(NATRON_PIXMAP_COMBOBOX, &pixC);\n _dropDownIcon->setPixmap(pixC);\n _mainLayout->addWidget(_dropDownIcon);\n \n _menu = new MenuWithToolTips(this);\n \n setSizePolicy(QSizePolicy::Preferred,QSizePolicy::Fixed);\n}\n\n\n\nvoid ComboBox::paintEvent(QPaintEvent *e)\n{\n\/\/ QStyleOption opt;\n\/\/ opt.init(this);\n\/\/ QPainter p(this);\n\/\/ style()->drawPrimitive(QStyle::PE_Widget, &opt, &p, this);\n QFrame::paintEvent(e);\n}\n\nvoid ComboBox::mousePressEvent(QMouseEvent* e){\n QPixmap pixC;\n appPTR->getIcon(NATRON_PIXMAP_COMBOBOX_PRESSED, &pixC);\n _dropDownIcon->setPixmap(pixC);\n setPressed(true);\n style()->unpolish(this);\n style()->polish(this);\n createMenu();\n QFrame::mousePressEvent(e);\n}\n\nvoid ComboBox::mouseReleaseEvent(QMouseEvent* e){\n QPixmap pixC;\n appPTR->getIcon(NATRON_PIXMAP_COMBOBOX, &pixC);\n _dropDownIcon->setPixmap(pixC);\n setPressed(false);\n style()->unpolish(this);\n style()->polish(this);\n QFrame::mouseReleaseEvent(e);\n}\n\nvoid ComboBox::createMenu(){\n _menu->clear();\n for (U32 i = 0 ; i < _actions.size(); ++i) {\n for (U32 j = 0; j < _separators.size(); ++j) {\n if (_separators[j] == (int)i) {\n _menu->addSeparator();\n break;\n }\n }\n _menu->addAction(_actions[i]);\n }\n QAction* triggered = _menu->exec(this->mapToGlobal(QPoint(0,height())));\n for (U32 i = 0; i < _actions.size(); ++i) {\n if (triggered == _actions[i]) {\n setCurrentIndex(i);\n break;\n }\n }\n \n QPixmap pixC;\n appPTR->getIcon(NATRON_PIXMAP_COMBOBOX, &pixC);\n _dropDownIcon->setPixmap(pixC);\n setPressed(false);\n style()->unpolish(this);\n style()->polish(this);\n \n}\nint ComboBox::count() const{\n return (int)_actions.size();\n}\nvoid ComboBox::insertItem(int index,const QString& item,QIcon icon,QKeySequence key,const QString& toolTip){\n assert(index >= 0);\n QAction* action = new QAction(this);\n action->setText(item);\n if(!toolTip.isEmpty()){\n action->setToolTip(Qt::convertFromPlainText(toolTip, Qt::WhiteSpaceNormal));\n }\n if (!icon.isNull()) {\n action->setIcon(icon);\n }\n if (!key.isEmpty()) {\n action->setShortcut(key);\n }\n#if IS_MAXIMUMTEXTSIZE_USEFUL\n if (item.size() > _maximumTextSize) {\n _maximumTextSize = item.size();\n }\n#endif\n growMaximumWidthFromText(item);\n _actions.insert(_actions.begin()+index, action);\n \/*if this is the first action we add, make it current*\/\n if(_actions.size() == 1){\n setCurrentText(itemText(0));\n }\n \n}\n\nvoid ComboBox::addItem(const QString& item,QIcon icon ,QKeySequence key,const QString& toolTip){\n QAction* action = new QAction(this);\n \n action->setText(item);\n if (!icon.isNull()) {\n action->setIcon(icon);\n }\n if (!key.isEmpty()) {\n action->setShortcut(key);\n }\n if(!toolTip.isEmpty()){\n action->setToolTip(Qt::convertFromPlainText(toolTip, Qt::WhiteSpaceNormal));\n }\n#if IS_MAXIMUMTEXTSIZE_USEFUL\n if (item.size() > _maximumTextSize) {\n _maximumTextSize = item.size();\n }\n#endif\n growMaximumWidthFromText(item);\n _actions.push_back(action);\n \n \/*if this is the first action we add, make it current*\/\n if(_actions.size() == 1){\n setCurrentText(itemText(0));\n }\n}\n\nvoid ComboBox::setCurrentText(const QString& text){\n QString str(text);\n growMaximumWidthFromText(str);\n str.prepend(\" \");\n str.append(\" \");\n assert(_currentText);\n _currentText->setText(str);\n for (U32 i = 0; i < _actions.size(); ++i) {\n if(_actions[i]->text() == text){\n _currentIndex = i;\n break;\n }\n }\n}\n\nvoid ComboBox::setMaximumWidthFromText(const QString& str)\n{\n int w = _currentText->fontMetrics().width(str+\" \");\n setMaximumWidth(w);\n}\n\nvoid ComboBox::growMaximumWidthFromText(const QString& str)\n{\n int w = _currentText->fontMetrics().width(str+\" \");\n if (w > maximumWidth()) {\n setMaximumWidth(w);\n }\n}\n\nQString ComboBox::text() const{\n return _currentText->text();\n}\n\nint ComboBox::activeIndex() const{\n return _currentIndex;\n}\n\nQString ComboBox::getCurrentIndexText() const {\n assert(_currentIndex < (int)_actions.size());\n return _actions[_currentIndex]->text();\n}\n\nvoid ComboBox::setCurrentIndex(int index)\n{\n QString str;\n QString rawStr;\n if (index >= 0 && index < (int)_actions.size()) {\n str = _actions[index]->text();\n rawStr = str;\n }\n \/*before displaying,prepend and append the text by some spacing.\n This is a dirty way to do this but QLayout::addSpacing() doesn't preserve\n the same style for the label.*\/\n#if IS_MAXIMUMTEXTSIZE_USEFUL\n int dsize = _maximumTextSize - str.size();\n dsize\/=2;\n str.prepend(\" \");\n for (int i = 0; i < dsize ; ++i) {str.prepend(\" \");}\n str.append(\" \");\n for (int i = 0; i < dsize ; ++i) {str.append(\" \");}\n#endif\n str.prepend(\" \");\n str.append(\" \");\n _currentIndex = index;\n _currentText->setText(str);\n \/\/ already called growMaximumWidthFromText() from addItem() and insertItem()\n \/\/setMaximumWidthFromText(str);\n emit currentIndexChanged(index);\n emit currentIndexChanged(rawStr);\n}\n\nvoid ComboBox::addSeparator(){\n _separators.push_back(_actions.size()-1);\n}\nvoid ComboBox::insertSeparator(int index){\n assert(index >= 0);\n _separators.push_back(index);\n}\n\nQString ComboBox::itemText(int index) const{\n if(0 <= index && index < (int)_actions.size()) {\n assert(_actions[index]);\n return _actions[index]->text();\n } else {\n return \"\";\n }\n}\nint ComboBox::itemIndex(const QString& str) const{\n for (U32 i = 0; i < _actions.size(); ++i) {\n if (_actions[i]->text() == str) {\n return i;\n }\n }\n return -1;\n}\n\nvoid ComboBox::removeItem(const QString& item){\n for (U32 i = 0; i < _actions.size(); ++i) {\n assert(_actions[i]);\n if (_actions[i]->text() == item) {\n _actions.erase(_actions.begin()+i);\n assert(_currentText);\n if (_currentText->text() == item) {\n setCurrentIndex(i-1);\n }\n \/*adjust separators that were placed after this item*\/\n for (U32 j = 0; j < _separators.size(); ++j) {\n if (_separators[j] >= (int)i) {\n --_separators[j];\n }\n }\n }\n }\n#if IS_MAXIMUMTEXTSIZE_USEFUL\n \/*we also need to re-calculate the maximum text size*\/\n _maximumTextSize = 0;\n for (U32 i = 0; i < _actions.size(); ++i) {\n assert(_actions[i]);\n if (_actions[i]->text().size() > _maximumTextSize) {\n _maximumTextSize = _actions[i]->text().size();\n }\n }\n#endif\n}\n\nvoid ComboBox::clear(){\n _actions.clear();\n _menu->clear();\n _separators.clear();\n _currentIndex = 0;\n#if IS_MAXIMUMTEXTSIZE_USEFUL\n _maximumTextSize = 0;\n#endif\n}\n\n\nvoid ComboBox::setItemText(int index,const QString& item){\n assert(0 <= index && index < (int)_actions.size());\n assert(_actions[index]);\n _actions[index]->setText(item);\n growMaximumWidthFromText(item);\n#if IS_MAXIMUMTEXTSIZE_USEFUL\n \/*we also need to re-calculate the maximum text size*\/\n _maximumTextSize = 0;\n for (U32 i = 0; i < _actions.size(); ++i) {\n assert(_actions[i]);\n if (_actions[i]->text().size() > _maximumTextSize) {\n _maximumTextSize = _actions[i]->text().size();\n }\n }\n#endif\n}\n\nvoid ComboBox::setItemShortcut(int index,const QKeySequence& sequence){\n assert(0 <= index && index < (int)_actions.size());\n assert(_actions[index]);\n _actions[index]->setShortcut(sequence);\n}\n\nvoid ComboBox::setItemIcon(int index,const QIcon& icon){\n assert(0 <= index && index < (int)_actions.size());\n assert(_actions[index]);\n _actions[index]->setIcon(icon);\n}\nvoid ComboBox::disableItem(int index){\n assert(0 <= index && index < (int)_actions.size());\n assert(_actions[index]);\n _actions[index]->setEnabled(false);\n}\n\nvoid ComboBox::enableItem(int index){\n assert(0 <= index && index < (int)_actions.size());\n assert(_actions[index]);\n _actions[index]->setEnabled(true);\n}\n\nvoid ComboBox::setAnimation(int i){\n animation = i;\n style()->unpolish(this);\n style()->polish(this);\n repaint();\n}\n<commit_msg>ComboBox: add warnings, because strange things are happening here<commit_after>\/\/ Natron\n\/* This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/. *\/\n\/*\n*Created by Alexandre GAUTHIER-FOICHAT on 6\/1\/2012. \n*contact: immarespond at gmail dot com\n*\n*\/\n\n#include \"Gui\/ComboBox.h\"\n\n#include <cassert>\n#include <algorithm>\n#include <QLayout>\n#include <QLabel>\n#include <QStyle>\n#include <QFont>\n#include <QFontMetrics>\n#include <QTextDocument> \/\/ for Qt::convertFromPlainText\n\n#include \"Engine\/AppManager.h\"\n#include \"Gui\/MenuWithToolTips.h\"\n\nusing namespace Natron;\n\nComboBox::ComboBox(QWidget* parent)\n: QFrame(parent)\n, _currentIndex(0)\n#if IS_MAXIMUMTEXTSIZE_USEFUL\n, _maximumTextSize(0)\n#endif\n, pressed(false)\n, animation(0)\n{\n \n _mainLayout = new QHBoxLayout(this);\n _mainLayout->setSpacing(0);\n _mainLayout->setContentsMargins(0, 0, 0, 0);\n setLayout(_mainLayout);\n setFrameShape(QFrame::Box);\n \n _currentText = new QLabel(this);\n _currentText->setObjectName(\"ComboBoxLabel\");\n setCurrentIndex(-1);\n _currentText->setMinimumWidth(10);\n _mainLayout->addWidget(_currentText);\n _currentText->setFixedHeight(fontMetrics().height() + 8);\n\n \n _dropDownIcon = new QLabel(this);\n _dropDownIcon->setObjectName(\"ComboBoxDropDownLabel\");\n QPixmap pixC;\n appPTR->getIcon(NATRON_PIXMAP_COMBOBOX, &pixC);\n _dropDownIcon->setPixmap(pixC);\n _mainLayout->addWidget(_dropDownIcon);\n \n _menu = new MenuWithToolTips(this);\n \n setSizePolicy(QSizePolicy::Preferred,QSizePolicy::Fixed);\n}\n\n\n\nvoid ComboBox::paintEvent(QPaintEvent *e)\n{\n\/\/ QStyleOption opt;\n\/\/ opt.init(this);\n\/\/ QPainter p(this);\n\/\/ style()->drawPrimitive(QStyle::PE_Widget, &opt, &p, this);\n QFrame::paintEvent(e);\n}\n\nvoid ComboBox::mousePressEvent(QMouseEvent* e){\n QPixmap pixC;\n appPTR->getIcon(NATRON_PIXMAP_COMBOBOX_PRESSED, &pixC);\n _dropDownIcon->setPixmap(pixC);\n setPressed(true);\n style()->unpolish(this);\n style()->polish(this);\n createMenu();\n QFrame::mousePressEvent(e);\n}\n\nvoid ComboBox::mouseReleaseEvent(QMouseEvent* e){\n QPixmap pixC;\n appPTR->getIcon(NATRON_PIXMAP_COMBOBOX, &pixC);\n _dropDownIcon->setPixmap(pixC);\n setPressed(false);\n style()->unpolish(this);\n style()->polish(this);\n QFrame::mouseReleaseEvent(e);\n}\n\nvoid ComboBox::createMenu(){\n _menu->clear();\n for (U32 i = 0 ; i < _actions.size(); ++i) {\n for (U32 j = 0; j < _separators.size(); ++j) {\n if (_separators[j] == (int)i) {\n _menu->addSeparator();\n break;\n }\n }\n _menu->addAction(_actions[i]);\n }\n QAction* triggered = _menu->exec(this->mapToGlobal(QPoint(0,height())));\n for (U32 i = 0; i < _actions.size(); ++i) {\n if (triggered == _actions[i]) {\n setCurrentIndex(i);\n break;\n }\n }\n \n QPixmap pixC;\n appPTR->getIcon(NATRON_PIXMAP_COMBOBOX, &pixC);\n _dropDownIcon->setPixmap(pixC);\n setPressed(false);\n style()->unpolish(this);\n style()->polish(this);\n \n}\nint ComboBox::count() const{\n return (int)_actions.size();\n}\nvoid ComboBox::insertItem(int index,const QString& item,QIcon icon,QKeySequence key,const QString& toolTip){\n assert(index >= 0);\n QAction* action = new QAction(this);\n action->setText(item);\n if(!toolTip.isEmpty()){\n action->setToolTip(Qt::convertFromPlainText(toolTip, Qt::WhiteSpaceNormal));\n }\n if (!icon.isNull()) {\n action->setIcon(icon);\n }\n if (!key.isEmpty()) {\n action->setShortcut(key);\n }\n#if IS_MAXIMUMTEXTSIZE_USEFUL\n if (item.size() > _maximumTextSize) {\n _maximumTextSize = item.size();\n }\n#endif\n growMaximumWidthFromText(item);\n _actions.insert(_actions.begin()+index, action);\n \/*if this is the first action we add, make it current*\/\n if(_actions.size() == 1){\n setCurrentText(itemText(0));\n }\n \n}\n\nvoid ComboBox::addItem(const QString& item,QIcon icon ,QKeySequence key,const QString& toolTip){\n QAction* action = new QAction(this);\n \n action->setText(item);\n if (!icon.isNull()) {\n action->setIcon(icon);\n }\n if (!key.isEmpty()) {\n action->setShortcut(key);\n }\n if(!toolTip.isEmpty()){\n action->setToolTip(Qt::convertFromPlainText(toolTip, Qt::WhiteSpaceNormal));\n }\n#if IS_MAXIMUMTEXTSIZE_USEFUL\n if (item.size() > _maximumTextSize) {\n _maximumTextSize = item.size();\n }\n#endif\n growMaximumWidthFromText(item);\n _actions.push_back(action);\n \n \/*if this is the first action we add, make it current*\/\n if(_actions.size() == 1){\n setCurrentText(itemText(0));\n }\n}\n\nvoid ComboBox::setCurrentText(const QString& text){\n QString str(text);\n growMaximumWidthFromText(str);\n str.prepend(\" \");\n str.append(\" \");\n assert(_currentText);\n _currentText->setText(str);\n \/\/ if no action matches this text, set the index to a dirty value\n int index = -1;\n for (U32 i = 0; i < _actions.size(); ++i) {\n if(_actions[i]->text() == text){\n index = i;\n break;\n }\n }\n if (_currentIndex != index) {\n _currentIndex = index;\n#pragma message WARN(\"[FD->AG] why not emit currentIndexChanged?\")\n \/\/ FIXME: why not emit currentIndexChanged?\n \/\/emit currentIndexChanged(_currentIndex);\n }\n \/\/emit currentIndexChanged(text);\n}\n\nvoid ComboBox::setMaximumWidthFromText(const QString& str)\n{\n int w = _currentText->fontMetrics().width(str+\" \");\n setMaximumWidth(w);\n}\n\nvoid ComboBox::growMaximumWidthFromText(const QString& str)\n{\n int w = _currentText->fontMetrics().width(str+\" \");\n if (w > maximumWidth()) {\n setMaximumWidth(w);\n }\n}\n\nQString ComboBox::text() const{\n return _currentText->text();\n}\n\nint ComboBox::activeIndex() const{\n return _currentIndex;\n}\n\nQString ComboBox::getCurrentIndexText() const {\n assert(_currentIndex < (int)_actions.size());\n return _actions[_currentIndex]->text();\n}\n\nvoid ComboBox::setCurrentIndex(int index)\n{\n QString str;\n QString text;\n if (0 <= index && index < (int)_actions.size()) {\n text = _actions[index]->text();\n }\n str = text;\n \/*before displaying,prepend and append the text by some spacing.\n This is a dirty way to do this but QLayout::addSpacing() doesn't preserve\n the same style for the label.*\/\n#if IS_MAXIMUMTEXTSIZE_USEFUL\n int dsize = _maximumTextSize - str.size();\n dsize\/=2;\n str.prepend(\" \");\n for (int i = 0; i < dsize ; ++i) {str.prepend(\" \");}\n str.append(\" \");\n for (int i = 0; i < dsize ; ++i) {str.append(\" \");}\n#endif\n str.prepend(\" \");\n str.append(\" \");\n _currentText->setText(str);\n \/\/ already called growMaximumWidthFromText() from addItem() and insertItem()\n \/\/setMaximumWidthFromText(str);\n#pragma message WARN(\"[FD->AG] is it OK to emit currentIndexChanged only if the index changed?\")\n if (_currentIndex != index) {\n _currentIndex = index;\n emit currentIndexChanged(_currentIndex);\n }\n \/\/emit currentIndexChanged(text);\n}\n\nvoid ComboBox::addSeparator(){\n _separators.push_back(_actions.size()-1);\n}\nvoid ComboBox::insertSeparator(int index){\n assert(index >= 0);\n _separators.push_back(index);\n}\n\nQString ComboBox::itemText(int index) const{\n if(0 <= index && index < (int)_actions.size()) {\n assert(_actions[index]);\n return _actions[index]->text();\n } else {\n return \"\";\n }\n}\nint ComboBox::itemIndex(const QString& str) const{\n for (U32 i = 0; i < _actions.size(); ++i) {\n if (_actions[i]->text() == str) {\n return i;\n }\n }\n return -1;\n}\n\nvoid ComboBox::removeItem(const QString& item){\n for (U32 i = 0; i < _actions.size(); ++i) {\n assert(_actions[i]);\n if (_actions[i]->text() == item) {\n _actions.erase(_actions.begin()+i);\n assert(_currentText);\n if (_currentText->text() == item) {\n setCurrentIndex(i-1);\n }\n \/*adjust separators that were placed after this item*\/\n for (U32 j = 0; j < _separators.size(); ++j) {\n if (_separators[j] >= (int)i) {\n --_separators[j];\n }\n }\n }\n }\n#if IS_MAXIMUMTEXTSIZE_USEFUL\n \/*we also need to re-calculate the maximum text size*\/\n _maximumTextSize = 0;\n for (U32 i = 0; i < _actions.size(); ++i) {\n assert(_actions[i]);\n if (_actions[i]->text().size() > _maximumTextSize) {\n _maximumTextSize = _actions[i]->text().size();\n }\n }\n#endif\n}\n\nvoid ComboBox::clear(){\n _actions.clear();\n _menu->clear();\n _separators.clear();\n _currentIndex = 0;\n#if IS_MAXIMUMTEXTSIZE_USEFUL\n _maximumTextSize = 0;\n#endif\n}\n\n\nvoid ComboBox::setItemText(int index,const QString& item){\n assert(0 <= index && index < (int)_actions.size());\n assert(_actions[index]);\n _actions[index]->setText(item);\n growMaximumWidthFromText(item);\n#if IS_MAXIMUMTEXTSIZE_USEFUL\n \/*we also need to re-calculate the maximum text size*\/\n _maximumTextSize = 0;\n for (U32 i = 0; i < _actions.size(); ++i) {\n assert(_actions[i]);\n if (_actions[i]->text().size() > _maximumTextSize) {\n _maximumTextSize = _actions[i]->text().size();\n }\n }\n#endif\n}\n\nvoid ComboBox::setItemShortcut(int index,const QKeySequence& sequence){\n assert(0 <= index && index < (int)_actions.size());\n assert(_actions[index]);\n _actions[index]->setShortcut(sequence);\n}\n\nvoid ComboBox::setItemIcon(int index,const QIcon& icon){\n assert(0 <= index && index < (int)_actions.size());\n assert(_actions[index]);\n _actions[index]->setIcon(icon);\n}\nvoid ComboBox::disableItem(int index){\n assert(0 <= index && index < (int)_actions.size());\n assert(_actions[index]);\n _actions[index]->setEnabled(false);\n}\n\nvoid ComboBox::enableItem(int index){\n assert(0 <= index && index < (int)_actions.size());\n assert(_actions[index]);\n _actions[index]->setEnabled(true);\n}\n\nvoid ComboBox::setAnimation(int i){\n animation = i;\n style()->unpolish(this);\n style()->polish(this);\n repaint();\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ @(#):$Id$\n\/\/ Author: Andrei Gheata 01\/03\/11\n\n\/*************************************************************************\n * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *\n * All rights reserved. *\n * *\n * For the licensing terms see $ROOTSYS\/LICENSE. *\n * For the list of contributors see $ROOTSYS\/README\/CREDITS. *\n *************************************************************************\/\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ TGeoBranchArray - An array of daughter indices making a geometry path.\n\/\/ Can be used to backup\/restore a state. To setup an object of this type,\n\/\/ one should use:\n\/\/ TGeoBranchArray *array = new TGeoBranchArray(level);\n\/\/ array->InitFromNavigator(nav); (To initialize from current navigator state)\n\/\/ The navigator can be updated to reflect this path array:\n\/\/ array->UpdateNavigator();\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"TGeoBranchArray.h\"\n\n#include \"TMath.h\"\n#include \"TThread.h\"\n#include \"TString.h\"\n#include \"TGeoNavigator.h\"\n#include \"TGeoCache.h\"\n#include \"TGeoManager.h\"\n\nClassImp(TGeoBranchArray)\n\n\/\/______________________________________________________________________________\nTGeoBranchArray::TGeoBranchArray(Int_t maxlevel)\n :fLevel(-1),\n fMaxLevel(maxlevel),\n fMatrix(),\n fArray(&fRealArray[0])\n{\n\/\/ Constructor. Alocates the array with a size given by level.\n memset(fRealArray, 0, fMaxLevel*sizeof(TGeoNode*));\n}\n\n\/\/______________________________________________________________________________\nTGeoBranchArray * TGeoBranchArray::MakeInstance(size_t maxlevel)\n{\n\/\/ Make an instance of the class which allocates the node array. To be\n\/\/ released using ReleaseInstance. If addr is non-zero, the user promised that \n\/\/ addr contains at least that many bytes: size_t needed = SizeOf(maxlevel);\n TGeoBranchArray* ba = 0;\n size_t needed = SizeOf(maxlevel);\n char *ptr = new char[ needed ];\n if (!ptr) return 0;\n new (ptr) TGeoBranchArray(maxlevel);\n ba = reinterpret_cast<TGeoBranchArray*>(ptr);\n ba->SetBit(kBASelfAlloc, kTRUE);\n return ba;\n}\n\n\/\/______________________________________________________________________________\nTGeoBranchArray * TGeoBranchArray::MakeInstanceAt(size_t maxlevel, void *addr)\n{\n \/\/ Make an instance of the class which allocates the node array. To be\n \/\/ released using ReleaseInstance. If addr is non-zero, the user promised that\n \/\/ addr contains at least that many bytes: size_t needed = SizeOf(maxlevel);\n TGeoBranchArray* ba = 0;\n new (addr) TGeoBranchArray(maxlevel);\n ba = reinterpret_cast<TGeoBranchArray*>(addr);\n ba->SetBit(kBASelfAlloc, kFALSE);\n return ba;\n}\n\n\n\/\/______________________________________________________________________________\nTGeoBranchArray * TGeoBranchArray::MakeCopy(const TGeoBranchArray &other)\n{\n\/\/ Make a copy of a branch array at the location (if indicated)\n TGeoBranchArray *copy = 0;\n size_t needed = SizeOf(other.fMaxLevel);\n char *ptr = new char[ needed ];\n if (!ptr) return 0;\n new (ptr) TGeoBranchArray(other.fMaxLevel);\n copy = reinterpret_cast<TGeoBranchArray*>(ptr);\n copy->SetBit(kBASelfAlloc, kTRUE);\n copy->fLevel = other.fLevel;\n copy->fMatrix = other.fMatrix; \n if (other.fLevel+1) memcpy(copy->fArray, other.fArray, (other.fLevel+1)*sizeof(TGeoNode*));\n return copy;\n}\n\n\/\/______________________________________________________________________________\nTGeoBranchArray * TGeoBranchArray::MakeCopyAt(const TGeoBranchArray &other, void *addr)\n{\n \/\/ Make a copy of a branch array at the location (if indicated)\n TGeoBranchArray *copy = 0;\n new (addr) TGeoBranchArray(other.fMaxLevel);\n copy = reinterpret_cast<TGeoBranchArray*>(addr);\n copy->SetBit(kBASelfAlloc, kFALSE);\n copy->fLevel = other.fLevel;\n copy->fMatrix = other.fMatrix;\n if (other.fLevel+1) memcpy(copy->fArray, other.fArray, (other.fLevel+1)*sizeof(TGeoNode*));\n return copy;\n}\n\n\n\/\/______________________________________________________________________________\nvoid TGeoBranchArray::CopyTo(TGeoBranchArray *dest)\n{\n\/\/ Raw memcpy of the branch array content to an existing destination.\n memcpy(dest->DataStart(), DataStart(), DataSize());\n dest->fArray = &(dest->fRealArray[0]);\n}\n\n\/\/______________________________________________________________________________\nvoid TGeoBranchArray::ReleaseInstance(TGeoBranchArray *obj) \n{\n\/\/ Releases the space allocated for the object\n obj->~TGeoBranchArray();\n if (obj->TestBit(kBASelfAlloc)) delete [] (char*)obj;\n}\n\n\/\/______________________________________________________________________________\nvoid TGeoBranchArray::UpdateArray(size_t nobj)\n{\n\/\/ Updates the internal addresses for n contiguous objects which have the same \n\/\/ fMaxLevel\n\/\/ Updates the internal addresses for n contiguous objects which have the same fMaxLevel\n size_t needed = SizeOf();\n\/\/ char *where = &fArray;\n\/\/ for (size_t i=0; i<nobj; ++i, where += needed) {\n\/\/ TGeoNode ***array = reinterpret_cast<TGeoNode***>(where);\n\/\/ *array = ((void**)where)+1; \n\/\/ }\n char *where = reinterpret_cast<char*>(this);\n for (size_t i=0; i<nobj; ++i, where += needed) {\n TGeoBranchArray *obj = reinterpret_cast<TGeoBranchArray*>(where);\n obj->fArray = &(obj->fRealArray[0]);\n } \n}\n\n\/\/______________________________________________________________________________\nTGeoBranchArray::TGeoBranchArray(const TGeoBranchArray& other)\n :TObject(other),\n fLevel(other.fLevel),\n fMaxLevel(other.fMaxLevel),\n fMatrix(other.fMatrix),\n fArray(NULL)\n{\n\/\/ Copy constructor. Not callable anymore. Use TGeoBranchArray::MakeCopy instead\n if (fMaxLevel) {\n fArray = new TGeoNode*[fMaxLevel];\n if (fLevel+1) memcpy(fArray, other.fArray, (fLevel+1)*sizeof(TGeoNode*));\n }\n} \n \n\/\/______________________________________________________________________________\nTGeoBranchArray& TGeoBranchArray::operator=(const TGeoBranchArray& other)\n{\n\/\/ Assignment. Not valid anymore. Use TGeoBranchArray::MakeCopy instead\n if (&other == this) return *this;\n\/\/ TThread::Lock();\n\/\/ TObject::operator=(other);\n fLevel = other.fLevel;\n fMatrix.CopyFrom(&other.fMatrix);\n if (fLevel+1) memcpy(fArray, other.fArray, (fLevel+1)*sizeof(TGeoNode*));\n\/\/ SetBit(other.TestBit(kBASelfAlloc));\n\/\/ TThread::UnLock();\n return *this;\n}\n\n\/\/______________________________________________________________________________\nvoid TGeoBranchArray::AddLevel(Int_t dindex)\n{\n\/\/ Add and extra daughter to the current path array. No validity check performed !\n if (fLevel<=0) {\n Error(\"AddLevel\", \"You must initialize from navigator or copy from another branch array first.\");\n return;\n }\n if (fLevel>fMaxLevel) {\n Fatal(\"AddLevel\", \"Max level = %d reached\\n\", fMaxLevel);\n return;\n } \n fLevel++;\n\/*\n if (fLevel+1>fMaxLevel) {\n TGeoNode **array = new TGeoNode*[fLevel+1];\n memcpy(array, fArray, fLevel*sizeof(TGeoNode*));\n delete [] fArray;\n fArray = array;\n } \n*\/ \n fArray[fLevel] = fArray[fLevel-1]->GetVolume()->GetNode(dindex);\n}\n\n\/\/______________________________________________________________________________\nBool_t TGeoBranchArray::operator ==(const TGeoBranchArray& other) const\n{\n\/\/ Is equal operator.\n Int_t value = Compare(&other);\n if (value==0) return kTRUE;\n return kFALSE;\n}\n\n\/\/______________________________________________________________________________\nBool_t TGeoBranchArray::operator !=(const TGeoBranchArray& other) const\n{\n\/\/ Not equal operator.\n Int_t value = Compare(&other);\n if (value!=0) return kTRUE;\n return kFALSE;\n}\n\n\/\/______________________________________________________________________________\nBool_t TGeoBranchArray::operator >(const TGeoBranchArray& other) const\n{\n\/\/ Is equal operator.\n Int_t value = Compare(&other);\n if (value>0) return kTRUE;\n return kFALSE;\n}\n\n\/\/______________________________________________________________________________\nBool_t TGeoBranchArray::operator <(const TGeoBranchArray& other) const\n{\n\/\/ Is equal operator.\n Int_t value = Compare(&other);\n if (value<0) return kTRUE;\n return kFALSE;\n}\n\n\/\/______________________________________________________________________________\nBool_t TGeoBranchArray::operator >=(const TGeoBranchArray& other) const\n{\n\/\/ Is equal operator.\n Int_t value = Compare(&other);\n if (value>=0) return kTRUE;\n return kFALSE;\n}\n\n\/\/______________________________________________________________________________\nBool_t TGeoBranchArray::operator <=(const TGeoBranchArray& other) const\n{\n\/\/ Is equal operator.\n Int_t value = Compare(&other);\n if (value<=0) return kTRUE;\n return kFALSE;\n}\n\n\/\/______________________________________________________________________________\nLong64_t TGeoBranchArray::BinarySearch(Long64_t n, const TGeoBranchArray **array, TGeoBranchArray *value)\n{\n\/\/ Binary search in an array of n pointers to branch arrays, to locate value.\n\/\/ Returns element index or index of nearest element smaller than value\n Long64_t nabove, nbelow, middle;\n const TGeoBranchArray *pind;\n nabove = n+1;\n nbelow = 0;\n while(nabove-nbelow > 1) {\n middle = (nabove+nbelow)\/2;\n pind = array[middle-1];\n if (*value == *pind) return middle-1;\n if (*value < *pind) nabove = middle;\n else nbelow = middle;\n }\n return nbelow-1;\n}\n\n\/\/______________________________________________________________________________\nInt_t TGeoBranchArray::Compare(const TObject *obj) const\n{\n\/\/ Compare with other object of same type. Returns -1 if this is smaller (first\n\/\/ smaller array value prevails), 0 if equal (size and values) and 1 if this is\n\/\/ larger.\n Int_t i;\n TGeoBranchArray *other = (TGeoBranchArray*)obj;\n Int_t otherLevel = other->GetLevel();\n Int_t maxLevel = TMath::Min(fLevel, otherLevel);\n TGeoNode **otherArray = other->GetArray();\n for (i=0; i<maxLevel+1; i++) {\n if (fArray[i]==otherArray[i]) continue;\n if ((Long64_t)fArray[i]<(Long64_t)otherArray[i]) return -1;\n return 1;\n }\n if (fLevel==otherLevel) return 0;\n if (fLevel<otherLevel) return -1;\n return 1;\n}\n\n\/\/______________________________________________________________________________\nvoid TGeoBranchArray::CleanMatrix()\n{\n\/\/ Garbage collect the stored matrix.\n}\n\n\/\/______________________________________________________________________________\nvoid TGeoBranchArray::Init(TGeoNode **branch, TGeoMatrix *global, Int_t level)\n{\n\/\/ Init the branch array from an array of nodes, the global matrix for the path and\n\/\/ the level.\n fMatrix.CopyFrom(global);\n if (level>fMaxLevel) {\n Fatal(\"Init\", \"Requested level %d exceeds maximum level %d\", level+1, fMaxLevel);\n return;\n }\n fLevel = level;\n memcpy(fArray, branch, (fLevel+1)*sizeof(TGeoNode*));\n}\n\n\/\/______________________________________________________________________________\nvoid TGeoBranchArray::InitFromNavigator(TGeoNavigator *nav)\n{\n\/\/ Init the branch array from current navigator state.\n TGeoNodeCache *cache = nav->GetCache();\n const TGeoNode **branch = (const TGeoNode**)cache->GetBranch();\n Int_t level = cache->GetLevel();\n fMatrix.CopyFrom(cache->GetCurrentMatrix());\n if (level>fMaxLevel) {\n Fatal(\"InitFromNavigator\", \"Requested level %d exceeds maximum level %d\", level+1, fMaxLevel);\n return;\n }\n fLevel = level;\n memcpy(fArray, branch, (fLevel+1)*sizeof(TGeoNode*));\n if (nav->IsOutside()) fLevel = -1;\n}\n\n\/\/______________________________________________________________________________\nvoid TGeoBranchArray::GetPath(TString &path) const\n{\n\/\/ Fill path pointed by the array.\n path = \"\";\n if (!fArray || !fArray[0]) return;\n for (Int_t i=0; i<fLevel+1; i++) {\n path += \"\/\";\n path += fArray[i]->GetName();\n }\n}\n\n\/\/______________________________________________________________________________\nvoid TGeoBranchArray::Print(Option_t *) const\n{\n\/\/ Print branch information\n TString path;\n GetPath(path);\n printf(\"branch: %s\\n\", path.Data());\n}\n\n\/\/______________________________________________________________________________\nvoid TGeoBranchArray::Sort(Int_t n, TGeoBranchArray **array, Int_t *index, Bool_t down)\n{\n\/\/ Sorting of an array of branch array pointers.\n for (Int_t i=0; i<n; i++) index[i] = i;\n if (down)\n std::sort(index, index + n, compareBAdesc(array));\n else\n std::sort(index, index + n, compareBAasc(array));\n}\n\n\/\/______________________________________________________________________________\nvoid TGeoBranchArray::UpdateNavigator(TGeoNavigator *nav) const\n{\n\/\/ Update the navigator to reflect the branch.\n nav->CdTop();\n if (fLevel<0) {nav->SetOutside(kTRUE); return;}\n for (Int_t i=1; i<fLevel+1; i++) nav->CdDown(fArray[i]);\n}\n<commit_msg>Fix to allow AddLevel to work<commit_after>\/\/ @(#):$Id$\n\/\/ Author: Andrei Gheata 01\/03\/11\n\n\/*************************************************************************\n * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *\n * All rights reserved. *\n * *\n * For the licensing terms see $ROOTSYS\/LICENSE. *\n * For the list of contributors see $ROOTSYS\/README\/CREDITS. *\n *************************************************************************\/\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ TGeoBranchArray - An array of daughter indices making a geometry path.\n\/\/ Can be used to backup\/restore a state. To setup an object of this type,\n\/\/ one should use:\n\/\/ TGeoBranchArray *array = new TGeoBranchArray(level);\n\/\/ array->InitFromNavigator(nav); (To initialize from current navigator state)\n\/\/ The navigator can be updated to reflect this path array:\n\/\/ array->UpdateNavigator();\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"TGeoBranchArray.h\"\n\n#include \"TMath.h\"\n#include \"TThread.h\"\n#include \"TString.h\"\n#include \"TGeoNavigator.h\"\n#include \"TGeoCache.h\"\n#include \"TGeoManager.h\"\n\nClassImp(TGeoBranchArray)\n\n\/\/______________________________________________________________________________\nTGeoBranchArray::TGeoBranchArray(Int_t maxlevel)\n :fLevel(-1),\n fMaxLevel(maxlevel),\n fMatrix(),\n fArray(&fRealArray[0])\n{\n\/\/ Constructor. Alocates the array with a size given by level.\n memset(fRealArray, 0, fMaxLevel*sizeof(TGeoNode*));\n}\n\n\/\/______________________________________________________________________________\nTGeoBranchArray * TGeoBranchArray::MakeInstance(size_t maxlevel)\n{\n\/\/ Make an instance of the class which allocates the node array. To be\n\/\/ released using ReleaseInstance. If addr is non-zero, the user promised that \n\/\/ addr contains at least that many bytes: size_t needed = SizeOf(maxlevel);\n TGeoBranchArray* ba = 0;\n size_t needed = SizeOf(maxlevel);\n char *ptr = new char[ needed ];\n if (!ptr) return 0;\n new (ptr) TGeoBranchArray(maxlevel);\n ba = reinterpret_cast<TGeoBranchArray*>(ptr);\n ba->SetBit(kBASelfAlloc, kTRUE);\n return ba;\n}\n\n\/\/______________________________________________________________________________\nTGeoBranchArray * TGeoBranchArray::MakeInstanceAt(size_t maxlevel, void *addr)\n{\n \/\/ Make an instance of the class which allocates the node array. To be\n \/\/ released using ReleaseInstance. If addr is non-zero, the user promised that\n \/\/ addr contains at least that many bytes: size_t needed = SizeOf(maxlevel);\n TGeoBranchArray* ba = 0;\n new (addr) TGeoBranchArray(maxlevel);\n ba = reinterpret_cast<TGeoBranchArray*>(addr);\n ba->SetBit(kBASelfAlloc, kFALSE);\n return ba;\n}\n\n\n\/\/______________________________________________________________________________\nTGeoBranchArray * TGeoBranchArray::MakeCopy(const TGeoBranchArray &other)\n{\n\/\/ Make a copy of a branch array at the location (if indicated)\n TGeoBranchArray *copy = 0;\n size_t needed = SizeOf(other.fMaxLevel);\n char *ptr = new char[ needed ];\n if (!ptr) return 0;\n new (ptr) TGeoBranchArray(other.fMaxLevel);\n copy = reinterpret_cast<TGeoBranchArray*>(ptr);\n copy->SetBit(kBASelfAlloc, kTRUE);\n copy->fLevel = other.fLevel;\n copy->fMatrix = other.fMatrix; \n if (other.fLevel+1) memcpy(copy->fArray, other.fArray, (other.fLevel+1)*sizeof(TGeoNode*));\n return copy;\n}\n\n\/\/______________________________________________________________________________\nTGeoBranchArray * TGeoBranchArray::MakeCopyAt(const TGeoBranchArray &other, void *addr)\n{\n \/\/ Make a copy of a branch array at the location (if indicated)\n TGeoBranchArray *copy = 0;\n new (addr) TGeoBranchArray(other.fMaxLevel);\n copy = reinterpret_cast<TGeoBranchArray*>(addr);\n copy->SetBit(kBASelfAlloc, kFALSE);\n copy->fLevel = other.fLevel;\n copy->fMatrix = other.fMatrix;\n if (other.fLevel+1) memcpy(copy->fArray, other.fArray, (other.fLevel+1)*sizeof(TGeoNode*));\n return copy;\n}\n\n\n\/\/______________________________________________________________________________\nvoid TGeoBranchArray::CopyTo(TGeoBranchArray *dest)\n{\n\/\/ Raw memcpy of the branch array content to an existing destination.\n memcpy(dest->DataStart(), DataStart(), DataSize());\n dest->fArray = &(dest->fRealArray[0]);\n}\n\n\/\/______________________________________________________________________________\nvoid TGeoBranchArray::ReleaseInstance(TGeoBranchArray *obj) \n{\n\/\/ Releases the space allocated for the object\n obj->~TGeoBranchArray();\n if (obj->TestBit(kBASelfAlloc)) delete [] (char*)obj;\n}\n\n\/\/______________________________________________________________________________\nvoid TGeoBranchArray::UpdateArray(size_t nobj)\n{\n\/\/ Updates the internal addresses for n contiguous objects which have the same \n\/\/ fMaxLevel\n\/\/ Updates the internal addresses for n contiguous objects which have the same fMaxLevel\n size_t needed = SizeOf();\n\/\/ char *where = &fArray;\n\/\/ for (size_t i=0; i<nobj; ++i, where += needed) {\n\/\/ TGeoNode ***array = reinterpret_cast<TGeoNode***>(where);\n\/\/ *array = ((void**)where)+1; \n\/\/ }\n char *where = reinterpret_cast<char*>(this);\n for (size_t i=0; i<nobj; ++i, where += needed) {\n TGeoBranchArray *obj = reinterpret_cast<TGeoBranchArray*>(where);\n obj->fArray = &(obj->fRealArray[0]);\n } \n}\n\n\/\/______________________________________________________________________________\nTGeoBranchArray::TGeoBranchArray(const TGeoBranchArray& other)\n :TObject(other),\n fLevel(other.fLevel),\n fMaxLevel(other.fMaxLevel),\n fMatrix(other.fMatrix),\n fArray(NULL)\n{\n\/\/ Copy constructor. Not callable anymore. Use TGeoBranchArray::MakeCopy instead\n if (fMaxLevel) {\n fArray = new TGeoNode*[fMaxLevel];\n if (fLevel+1) memcpy(fArray, other.fArray, (fLevel+1)*sizeof(TGeoNode*));\n }\n} \n \n\/\/______________________________________________________________________________\nTGeoBranchArray& TGeoBranchArray::operator=(const TGeoBranchArray& other)\n{\n\/\/ Assignment. Not valid anymore. Use TGeoBranchArray::MakeCopy instead\n if (&other == this) return *this;\n\/\/ TThread::Lock();\n\/\/ TObject::operator=(other);\n fLevel = other.fLevel;\n fMatrix.CopyFrom(&other.fMatrix);\n if (fLevel+1) memcpy(fArray, other.fArray, (fLevel+1)*sizeof(TGeoNode*));\n\/\/ SetBit(other.TestBit(kBASelfAlloc));\n\/\/ TThread::UnLock();\n return *this;\n}\n\n\/\/______________________________________________________________________________\nvoid TGeoBranchArray::AddLevel(Int_t dindex)\n{\n\/\/ Add and extra daughter to the current path array. No validity check performed !\n if (fLevel<0) {\n Error(\"AddLevel\", \"You must initialize from navigator or copy from another branch array first.\");\n return;\n }\n if (fLevel>fMaxLevel) {\n Fatal(\"AddLevel\", \"Max level = %d reached\\n\", fMaxLevel);\n return;\n } \n fLevel++;\n\/*\n if (fLevel+1>fMaxLevel) {\n TGeoNode **array = new TGeoNode*[fLevel+1];\n memcpy(array, fArray, fLevel*sizeof(TGeoNode*));\n delete [] fArray;\n fArray = array;\n } \n*\/ \n fArray[fLevel] = fArray[fLevel-1]->GetVolume()->GetNode(dindex);\n}\n\n\/\/______________________________________________________________________________\nBool_t TGeoBranchArray::operator ==(const TGeoBranchArray& other) const\n{\n\/\/ Is equal operator.\n Int_t value = Compare(&other);\n if (value==0) return kTRUE;\n return kFALSE;\n}\n\n\/\/______________________________________________________________________________\nBool_t TGeoBranchArray::operator !=(const TGeoBranchArray& other) const\n{\n\/\/ Not equal operator.\n Int_t value = Compare(&other);\n if (value!=0) return kTRUE;\n return kFALSE;\n}\n\n\/\/______________________________________________________________________________\nBool_t TGeoBranchArray::operator >(const TGeoBranchArray& other) const\n{\n\/\/ Is equal operator.\n Int_t value = Compare(&other);\n if (value>0) return kTRUE;\n return kFALSE;\n}\n\n\/\/______________________________________________________________________________\nBool_t TGeoBranchArray::operator <(const TGeoBranchArray& other) const\n{\n\/\/ Is equal operator.\n Int_t value = Compare(&other);\n if (value<0) return kTRUE;\n return kFALSE;\n}\n\n\/\/______________________________________________________________________________\nBool_t TGeoBranchArray::operator >=(const TGeoBranchArray& other) const\n{\n\/\/ Is equal operator.\n Int_t value = Compare(&other);\n if (value>=0) return kTRUE;\n return kFALSE;\n}\n\n\/\/______________________________________________________________________________\nBool_t TGeoBranchArray::operator <=(const TGeoBranchArray& other) const\n{\n\/\/ Is equal operator.\n Int_t value = Compare(&other);\n if (value<=0) return kTRUE;\n return kFALSE;\n}\n\n\/\/______________________________________________________________________________\nLong64_t TGeoBranchArray::BinarySearch(Long64_t n, const TGeoBranchArray **array, TGeoBranchArray *value)\n{\n\/\/ Binary search in an array of n pointers to branch arrays, to locate value.\n\/\/ Returns element index or index of nearest element smaller than value\n Long64_t nabove, nbelow, middle;\n const TGeoBranchArray *pind;\n nabove = n+1;\n nbelow = 0;\n while(nabove-nbelow > 1) {\n middle = (nabove+nbelow)\/2;\n pind = array[middle-1];\n if (*value == *pind) return middle-1;\n if (*value < *pind) nabove = middle;\n else nbelow = middle;\n }\n return nbelow-1;\n}\n\n\/\/______________________________________________________________________________\nInt_t TGeoBranchArray::Compare(const TObject *obj) const\n{\n\/\/ Compare with other object of same type. Returns -1 if this is smaller (first\n\/\/ smaller array value prevails), 0 if equal (size and values) and 1 if this is\n\/\/ larger.\n Int_t i;\n TGeoBranchArray *other = (TGeoBranchArray*)obj;\n Int_t otherLevel = other->GetLevel();\n Int_t maxLevel = TMath::Min(fLevel, otherLevel);\n TGeoNode **otherArray = other->GetArray();\n for (i=0; i<maxLevel+1; i++) {\n if (fArray[i]==otherArray[i]) continue;\n if ((Long64_t)fArray[i]<(Long64_t)otherArray[i]) return -1;\n return 1;\n }\n if (fLevel==otherLevel) return 0;\n if (fLevel<otherLevel) return -1;\n return 1;\n}\n\n\/\/______________________________________________________________________________\nvoid TGeoBranchArray::CleanMatrix()\n{\n\/\/ Garbage collect the stored matrix.\n}\n\n\/\/______________________________________________________________________________\nvoid TGeoBranchArray::Init(TGeoNode **branch, TGeoMatrix *global, Int_t level)\n{\n\/\/ Init the branch array from an array of nodes, the global matrix for the path and\n\/\/ the level.\n fMatrix.CopyFrom(global);\n if (level>fMaxLevel) {\n Fatal(\"Init\", \"Requested level %d exceeds maximum level %d\", level+1, fMaxLevel);\n return;\n }\n fLevel = level;\n memcpy(fArray, branch, (fLevel+1)*sizeof(TGeoNode*));\n}\n\n\/\/______________________________________________________________________________\nvoid TGeoBranchArray::InitFromNavigator(TGeoNavigator *nav)\n{\n\/\/ Init the branch array from current navigator state.\n TGeoNodeCache *cache = nav->GetCache();\n const TGeoNode **branch = (const TGeoNode**)cache->GetBranch();\n Int_t level = cache->GetLevel();\n fMatrix.CopyFrom(cache->GetCurrentMatrix());\n if (level>fMaxLevel) {\n Fatal(\"InitFromNavigator\", \"Requested level %d exceeds maximum level %d\", level+1, fMaxLevel);\n return;\n }\n fLevel = level;\n memcpy(fArray, branch, (fLevel+1)*sizeof(TGeoNode*));\n if (nav->IsOutside()) fLevel = -1;\n}\n\n\/\/______________________________________________________________________________\nvoid TGeoBranchArray::GetPath(TString &path) const\n{\n\/\/ Fill path pointed by the array.\n path = \"\";\n if (!fArray || !fArray[0]) return;\n for (Int_t i=0; i<fLevel+1; i++) {\n path += \"\/\";\n path += fArray[i]->GetName();\n }\n}\n\n\/\/______________________________________________________________________________\nvoid TGeoBranchArray::Print(Option_t *) const\n{\n\/\/ Print branch information\n TString path;\n GetPath(path);\n printf(\"branch: %s\\n\", path.Data());\n}\n\n\/\/______________________________________________________________________________\nvoid TGeoBranchArray::Sort(Int_t n, TGeoBranchArray **array, Int_t *index, Bool_t down)\n{\n\/\/ Sorting of an array of branch array pointers.\n for (Int_t i=0; i<n; i++) index[i] = i;\n if (down)\n std::sort(index, index + n, compareBAdesc(array));\n else\n std::sort(index, index + n, compareBAasc(array));\n}\n\n\/\/______________________________________________________________________________\nvoid TGeoBranchArray::UpdateNavigator(TGeoNavigator *nav) const\n{\n\/\/ Update the navigator to reflect the branch.\n nav->CdTop();\n if (fLevel<0) {nav->SetOutside(kTRUE); return;}\n for (Int_t i=1; i<fLevel+1; i++) nav->CdDown(fArray[i]);\n}\n<|endoftext|>"} {"text":"<commit_before>\/** \\copyright\n * Copyright (c) 2013, Stuart W Baker\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n * \n * - Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n *\n * - Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n * \\file StateFlow.hxx\n *\n * Defines a type of state machine flow used within class Service.\n *\n * @author Stuart W Baker\n * @date 25 December 2013\n *\/\n\n#ifndef _StateFlow_hxx_\n#define _StateFlow_hxx_\n\n#include <type_traits>\n\n#include \"executor\/Allocator.hxx\"\n#include \"executor\/Message.hxx\"\n#include \"utils\/BufferQueue.hxx\"\n\n#define STATE(_fn) (Callback)(&std::remove_reference<decltype(*this)>::type::_fn)\n\n\/** Begin the definition of a StateFlow.\n * @param _name the class name of the StateFlow derived object\n * @param _priorities number of input queue priorities\n *\/\n#define STATE_FLOW_START(_name, _priorities) \\\n class _name : public StateFlow<_priorities> \\\n { \\\n public: \\\n _name(Service *service) \\\n : StateFlow<_priorities>(service) \\\n { \\\n } \\\n \\\n ~_name() \\\n { \\\n } \\\n \\\n private: \\\n Action entry(Message *msg); \\\n \\\n _name(); \\\n \\\n DISALLOW_COPY_AND_ASSIGN(_name);\n\n\/** Begin the definition of a StateFlow that includes timeouts.\n * @param _name the class name of the StateFlow derived object\n * @param _priorities number of input queue priorities\n *\/\n#define STATE_FLOW_START_WITH_TIMER(_name, _priorities) \\\n class _name : public StateFlow<_priorities> \\\n { \\\n public: \\\n _name(Service *service) \\\n : StateFlow<_priorities>(service), \\\n timer(TIMEOUT_FROM(service, state_flow_timeout), \\\n service, \\\n this), \\\n timerMsg(NULL) \\\n { \\\n } \\\n \\\n ~_name() \\\n { \\\n } \\\n \\\n void timeout() \\\n { \\\n timerMsg ? me()->send(timerMsg) : ; \\\n timerMsg = NULL; \\\n } \\\n \\\n void trigger() \\\n { \\\n timer.trigger(); \\\n } \\\n \\\n private: \\\n Action entry(Message *msg); \\\n \\\n Action timeout_and_call(Callback c, Message *msg, long long period) \\\n { \\\n msg->id(msg->id() | Message::IN_PROCESS_MSK); \\\n timerMsg = msg; \\\n timer.start(period); \\\n return Action(c); \\\n } \\\n \\\n Timer timer; \\\n Message *timerMsg; \\\n \\\n bool early() \\\n { \\\n return timer.early(); \\\n } \\\n \\\n _name(); \\\n \\\n DISALLOW_COPY_AND_ASSIGN(_name);\n\n \n\n\/** Declare a state callback in a StateFlow.\n * @param _state the method name of the StateFlow state callback\n *\/\n#define STATE_FLOW_STATE(_state) Action _state(Message *msg);\n\n\/** End the definition of a StateFlow.\n *\/\n#define STATE_FLOW_END() };\n\n\/** Runs incoming Messages through a State Flow.\n *\/\nclass StateFlowBase\n{\nprotected:\n \/** Constructor.\n * @param service Service that this state flow is part of\n * @param size number of queues in the list\n *\/\n StateFlowBase(Service *service)\n : service(service),\n state(STATE(terminated))\n {\n }\n \n \/** Destructor.\n *\/\n ~StateFlowBase()\n {\n }\n\n \/* forward prototype *\/\n class Action;\n\n \/** State Flow callback prototype\n *\/\n typedef Action (StateFlowBase::*Callback)(Message *);\n\n \/** Return type for a state flow callback.\n *\/\n class Action\n {\n public:\n \/** Constructor.\n *\/\n Action(Callback s)\n : nextState(s)\n {\n }\n \n \/** Get the next state for the StateFlowAction.\n *\/\n Callback next_state()\n {\n return nextState;\n }\n\n private:\n \/** next state in state flow *\/\n Callback nextState;\n };\n\n \/** Entry into the StateFlow activity. Pure virtual which must be\n * defined by derived class.\n * @param msg Message belonging to the state flow\n * @return function pointer to next state\n *\/\n virtual Action entry(Message *msg) = 0;\n\n \/** Call the current state again.\n * @return function pointer to current state handler\n *\/\n Action again()\n {\n return Action(state);\n }\n\n \/** Terminate current StateFlow activity. The message instance is not\n * released before termination. This is usefull if the message will be \n * reused for the purpose of sending to another StateFlow.\n * @return function pointer to terminated method\n *\/\n Action exit()\n {\n return STATE(terminated);\n }\n\n \/** Terminate current StateFlow activity. after releasing the message.\n * @param msg to release\n * @return function pointer to terminated method\n *\/\n Action release_and_exit(Message *msg)\n {\n msg->free();\n return exit();\n }\n\n \/** Imediately call the next state upon return.\n * @param c Callback \"state\" to move to\n * @return function pointer to passed in callback\n *\/\n Action call_immediately(Callback c)\n {\n return Action(c);\n }\n\n \/** Wait for resource to become available before proceeding to next state.\n * @param c Callback \"state\" to move to\n * @param msg Message instance we are waiting on\n * @return function pointer to passed in callback\n *\/\n Action wait_and_call(Callback c, Message *msg)\n {\n msg->id(msg->id() | Message::IN_PROCESS_MSK);\n return Action(c);\n }\n\n \/** Wait for resource to become available before proceeding to next state.\n * if an immediate allocation can be made, an immediate call to the next\n * state will be made.\n * @param c Callback \"state\" to move to\n * @param msg Message instance we are waiting on\n * @return function pointer to passed in callback\n *\/\n template <class T> Action allocate_and_call(Allocator<T> *a, Callback c, Message *msg)\n {\n return a->allocate_immediate(msg) ? call_immediately(c) : Action(c);\n }\n\n \/** Imediately queue up the next callback for this flow through the executor.\n * Similar to @ref call_immediately, except we place this flow on the back\n * of the Executor queue.\n * @param c Callback \"state\" to move to\n * @param msg Message instance we are acting upon\n * @return function pointer to passed in callback\n *\/\n Action yeild_and_call(Callback c, Message *msg);\n\n \/** Return a pointer to the service I am bound to.\n * @return pointer to service\n *\/\n Service *me()\n {\n return service;\n }\n\n \/** Timeout expired. The expectation is that a derived class will implement\n * this if it desires timeouts.\n *\/\n virtual void timeout()\n {\n }\n \nprivate:\n \/** Insert a message into one of the work queues.\n * @param msg Message to insert\n * @param index queue index to insert into\n *\/\n virtual void insert(Message *msg, unsigned index) = 0;\n \n \/** Pull a message out of one of the work queues.\n * @return message out of one of the work queues, NULL if none available\n *\/\n virtual Message *next() = 0;\n\n \/** Service this StateFlow belongs to *\/\n Service *service;\n\n \/** Terminate current StateFlow activity. This method only exists for the\n * purpose of providing a unique address pointer.\n * @param msg unused\n * @return should never return\n *\/\n Action terminated(Message *msg);\n\n \/** Process an incoming message.\n * @param msg message to process\n * @param priority priority of message\n *\/\n void process(Message *msg, unsigned priority);\n \n \/** current active state in the flow *\/\n Callback state;\n\n \/** Allow class Service to access our private members *\/\n friend class Service;\n \n \/** Allow class Message to access our private and protected members *\/\n friend class Message;\n \n \/** Default constructor.\n *\/\n StateFlowBase();\n\n DISALLOW_COPY_AND_ASSIGN(StateFlowBase);\n};\n\ntemplate <unsigned items> class StateFlow : public StateFlowBase,\n public QList<Message, items>\n{\npublic:\n \/** Constructor.\n * @param service Service that this state flow is part of\n * @param size number of queues in the list\n *\/\n StateFlow(Service *service)\n : StateFlowBase(service),\n QList<Message, items>()\n {\n }\n \n \/** Destructor.\n *\/\n ~StateFlow()\n {\n }\n\nprotected:\n \/** Entry into the StateFlow activity. Pure virtual which must be\n * defined by derived class.\n * @param msg Message belonging to the state flow\n * @return function pointer to next state\n *\/\n virtual Action entry(Message *msg) = 0;\n\nprivate:\n \/** Insert a message into one of the work queues.\n * @param msg Message to insert\n * @param index queue index to insert into\n *\/\n void insert(Message *msg, unsigned index)\n {\n QList<Message, items>::insert(msg, index >= items ? items - 1 : index);\n }\n \n \/** Pull a message out of one of the work queues.\n * @return message out of one of the work queues, NULL if none available\n *\/\n Message *next()\n {\n return QList<Message, items>::next().item;\n }\n\n \/** Default constructor.\n *\/\n StateFlow();\n\n DISALLOW_COPY_AND_ASSIGN(StateFlow);\n};\n\n#endif \/* _StateFlow_hxx_ *\/\n<commit_msg>Adds current message to stateflowbase and renames 'items' to NUM_PRIO to state flow.<commit_after>\/** \\copyright\n * Copyright (c) 2013, Stuart W Baker\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n * \n * - Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n *\n * - Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n * \\file StateFlow.hxx\n *\n * Defines a type of state machine flow used within class Service.\n *\n * @author Stuart W Baker\n * @date 25 December 2013\n *\/\n\n#ifndef _StateFlow_hxx_\n#define _StateFlow_hxx_\n\n#include <type_traits>\n\n#include \"executor\/Allocator.hxx\"\n#include \"executor\/Message.hxx\"\n#include \"utils\/BufferQueue.hxx\"\n\n#define STATE(_fn) (Callback)(&std::remove_reference<decltype(*this)>::type::_fn)\n\n\/** Begin the definition of a StateFlow.\n * @param _name the class name of the StateFlow derived object\n * @param _priorities number of input queue priorities\n *\/\n#define STATE_FLOW_START(_name, _priorities) \\\n class _name : public StateFlow<_priorities> \\\n { \\\n public: \\\n _name(Service *service) \\\n : StateFlow<_priorities>(service) \\\n { \\\n } \\\n \\\n ~_name() \\\n { \\\n } \\\n \\\n private: \\\n Action entry(Message *msg); \\\n \\\n _name(); \\\n \\\n DISALLOW_COPY_AND_ASSIGN(_name);\n\n\/** Begin the definition of a StateFlow that includes timeouts.\n * @param _name the class name of the StateFlow derived object\n * @param _priorities number of input queue priorities\n *\/\n#define STATE_FLOW_START_WITH_TIMER(_name, _priorities) \\\n class _name : public StateFlow<_priorities> \\\n { \\\n public: \\\n _name(Service *service) \\\n : StateFlow<_priorities>(service), \\\n timer(TIMEOUT_FROM(service, state_flow_timeout), \\\n service, \\\n this), \\\n timerMsg(NULL) \\\n { \\\n } \\\n \\\n ~_name() \\\n { \\\n } \\\n \\\n void timeout() \\\n { \\\n timerMsg ? me()->send(timerMsg) : ; \\\n timerMsg = NULL; \\\n } \\\n \\\n void trigger() \\\n { \\\n timer.trigger(); \\\n } \\\n \\\n private: \\\n Action entry(Message *msg); \\\n \\\n Action timeout_and_call(Callback c, Message *msg, long long period) \\\n { \\\n msg->id(msg->id() | Message::IN_PROCESS_MSK); \\\n timerMsg = msg; \\\n timer.start(period); \\\n return Action(c); \\\n } \\\n \\\n Timer timer; \\\n Message *timerMsg; \\\n \\\n bool early() \\\n { \\\n return timer.early(); \\\n } \\\n \\\n _name(); \\\n \\\n DISALLOW_COPY_AND_ASSIGN(_name);\n\n \n\n\/** Declare a state callback in a StateFlow.\n * @param _state the method name of the StateFlow state callback\n *\/\n#define STATE_FLOW_STATE(_state) Action _state(Message *msg);\n\n\/** End the definition of a StateFlow.\n *\/\n#define STATE_FLOW_END() };\n\n\/** Runs incoming Messages through a State Flow.\n *\/\nclass StateFlowBase\n{\nprotected:\n \/** Constructor.\n * @param service Service that this state flow is part of\n * @param size number of queues in the list\n *\/\n StateFlowBase(Service *service)\n : service(service),\n state(STATE(terminated))\n {\n }\n \n \/** Destructor.\n *\/\n ~StateFlowBase()\n {\n }\n\n \/* forward prototype *\/\n class Action;\n\n \/** State Flow callback prototype\n *\/\n typedef Action (StateFlowBase::*Callback)(Message *);\n\n \/** Return type for a state flow callback.\n *\/\n class Action\n {\n public:\n \/** Constructor.\n *\/\n Action(Callback s)\n : nextState(s)\n {\n }\n \n \/** Get the next state for the StateFlowAction.\n *\/\n Callback next_state()\n {\n return nextState;\n }\n\n private:\n \/** next state in state flow *\/\n Callback nextState;\n };\n\n \/** Entry into the StateFlow activity. Pure virtual which must be\n * defined by derived class.\n * @param msg Message belonging to the state flow\n * @return function pointer to next state\n *\/\n virtual Action entry(Message *msg) = 0;\n\n \/** @returns the current message we are processing. *\/\n Message* message() { reutrn currentMessage_; }\n\n \/*========== ACTION COMMANDS ===============*\/\n \/* StateFlow implementations will have to use one of the following commands\n * to return from a state handler to indicate what action to take. *\/\n\n \/** Call the current state again.\n * @return function pointer to current state handler\n *\/\n Action again()\n {\n return Action(state);\n }\n\n \/** Terminate current StateFlow activity. The message instance is not\n * released before termination. This is usefull if the message will be \n * reused for the purpose of sending to another StateFlow.\n * @return function pointer to terminated method\n *\/\n Action exit()\n {\n return STATE(terminated);\n }\n\n \/** Terminate current StateFlow activity. after releasing the message.\n * @param msg to release\n * @return function pointer to terminated method\n *\/\n Action release_and_exit(Message *msg)\n {\n msg->free();\n return exit();\n }\n\n \/** Imediately call the next state upon return.\n * @param c Callback \"state\" to move to\n * @return function pointer to passed in callback\n *\/\n Action call_immediately(Callback c)\n {\n return Action(c);\n }\n\n \/** Wait for resource to become available before proceeding to next state.\n * @param c Callback \"state\" to move to\n * @param msg Message instance we are waiting on\n * @return function pointer to passed in callback\n *\/\n Action wait_and_call(Callback c, Message *msg)\n {\n msg->id(msg->id() | Message::IN_PROCESS_MSK);\n return Action(c);\n }\n\n \/** Wait for resource to become available before proceeding to next state.\n * if an immediate allocation can be made, an immediate call to the next\n * state will be made.\n * @param c Callback \"state\" to move to\n * @param msg Message instance we are waiting on\n * @return function pointer to passed in callback\n *\/\n template <class T> Action allocate_and_call(Allocator<T> *a, Callback c, Message *msg)\n {\n return a->allocate_immediate(msg) ? call_immediately(c) : Action(c);\n }\n\n \/** Imediately queue up the next callback for this flow through the executor.\n * Similar to @ref call_immediately, except we place this flow on the back\n * of the Executor queue.\n * @param c Callback \"state\" to move to\n * @param msg Message instance we are acting upon\n * @return function pointer to passed in callback\n *\/\n Action yield_and_call(Callback c, Message *msg);\n\n \/** Return a pointer to the service I am bound to.\n * @return pointer to service\n *\/\n Service *me()\n {\n return service;\n }\n\n \/** Timeout expired. The expectation is that a derived class will implement\n * this if it desires timeouts.\n *\/\n virtual void timeout()\n {\n }\n \nprivate:\n \/** Insert a message into one of the work queues.\n * @param msg Message to insert\n * @param index queue index to insert into\n *\/\n virtual void insert(Message *msg, unsigned index) = 0;\n \n \/** Pull a message out of one of the work queues.\n * @return message out of one of the work queues, NULL if none available\n *\/\n virtual Message *next() = 0;\n\n \/** Service this StateFlow belongs to *\/\n Service *service;\n\n \/** Terminate current StateFlow activity. This method only exists for the\n * purpose of providing a unique address pointer.\n * @param msg unused\n * @return should never return\n *\/\n Action terminated(Message *msg);\n\n \/** Process an incoming message.\n * @param msg message to process\n * @param priority priority of message\n *\/\n void process(Message *msg, unsigned priority);\n \n \/** current active state in the flow *\/\n Callback state_;\n\n \/** The message we are currently processing *\/\n Message* currentMessage_;\n\n \/** Default constructor.\n *\/\n StateFlowBase();\n\n DISALLOW_COPY_AND_ASSIGN(StateFlowBase);\n};\n\ntemplate <unsigned NUM_PRIO> class StateFlow : public StateFlowBase,\n public QList<Message, NUM_PRIO>\n{\npublic:\n \/** Constructor.\n * @param service Service that this state flow is part of\n * @param size number of queues in the list\n *\/\n StateFlow(Service *service)\n : StateFlowBase(service),\n QList<Message, NUM_PRIO>()\n {\n }\n \n \/** Destructor.\n *\/\n ~StateFlow()\n {\n }\n\nprotected:\n \/** Entry into the StateFlow activity. Pure virtual which must be\n * defined by derived class.\n * @param msg Message belonging to the state flow\n * @return function pointer to next state\n *\/\n virtual Action entry(Message *msg) = 0;\n\nprivate:\n \/** Insert a message into one of the work queues.\n * @param msg Message to insert\n * @param index queue index to insert into\n *\/\n void insert(Message *msg, unsigned index)\n {\n QList<Message, NUM_PRIO>::insert(msg, index >= NUM_PRIO ? NUM_PRIO - 1 : index);\n }\n \n \/** Pull a message out of one of the work queues.\n * @return message out of one of the work queues, NULL if none available\n *\/\n Message *next()\n {\n return QList<Message, NUM_PRIO>::next().item;\n }\n\n \/** Default constructor.\n *\/\n StateFlow();\n\n DISALLOW_COPY_AND_ASSIGN(StateFlow);\n};\n\n#endif \/* _StateFlow_hxx_ *\/\n<|endoftext|>"} {"text":"<commit_before>#pragma once\n\n#include <eosio\/chain\/authority.hpp>\n#include <eosio\/chain\/chain_config.hpp>\n#include <eosio\/chain\/config.hpp>\n#include <eosio\/chain\/types.hpp>\n\nnamespace eosio { namespace chain {\n\nusing action_name = eosio::chain::action_name;\n\nstruct newaccount {\n account_name creator;\n account_name name;\n authority owner;\n authority active;\n\n static account_name get_account() {\n return config::system_account_name;\n }\n\n static action_name get_name() {\n return action_name( N(newaccount) );\n }\n};\n\nstruct setcode {\n account_name account;\n uint8_t vmtype = 0;\n uint8_t vmversion = 0;\n bytes code;\n\n static account_name get_account() {\n return config::system_account_name;\n }\n\n static action_name get_name() {\n return action_name( N(setcode) );\n }\n};\n\nstruct setabi {\n account_name account;\n bytes abi;\n\n static account_name get_account() {\n return config::system_account_name;\n }\n\n static action_name get_name() {\n return action_name( N(setabi) );\n }\n};\n\n\nstruct updateauth {\n account_name account;\n permission_name permission;\n permission_name parent;\n authority auth;\n\n static account_name get_account() {\n return config::system_account_name;\n }\n\n static action_name get_name() {\n return action_name( N(updateauth) );\n }\n};\n\nstruct deleteauth {\n deleteauth() = default;\n deleteauth(const account_name& account, const permission_name& permission)\n :account(account), permission(permission)\n {}\n\n account_name account;\n permission_name permission;\n\n static account_name get_account() {\n return config::system_account_name;\n }\n\n static action_name get_name() {\n return action_name( N(deleteauth) );\n }\n};\n\nstruct linkauth {\n linkauth() = default;\n linkauth(const account_name& account, const account_name& code, const action_name& type, const permission_name& requirement)\n :account(account), code(code), type(type), requirement(requirement)\n {}\n\n account_name account;\n account_name code;\n action_name type;\n permission_name requirement;\n\n static account_name get_account() {\n return config::system_account_name;\n }\n\n static action_name get_name() {\n return action_name( N(linkauth) );\n }\n};\n\nstruct unlinkauth {\n unlinkauth() = default;\n unlinkauth(const account_name& account, const account_name& code, const action_name& type)\n :account(account), code(code), type(type)\n {}\n\n account_name account;\n account_name code;\n action_name type;\n\n static account_name get_account() {\n return config::system_account_name;\n }\n\n static action_name get_name() {\n return action_name( N(unlinkauth) );\n }\n};\n\nstruct canceldelay {\n permission_level canceling_auth;\n transaction_id_type trx_id;\n\n static account_name get_account() {\n return config::system_account_name;\n }\n\n static action_name get_name() {\n return action_name( N(canceldelay) );\n }\n};\n\nstruct onerror {\n uint128_t sender_id;\n bytes sent_trx;\n\n onerror( uint128_t sid, const char* data, size_t len )\n :sender_id(sid),sent_trx(data,data+len){}\n\n static account_name get_account() {\n return config::system_account_name;\n }\n\n static action_name get_name() {\n return action_name( N(onerror) );\n }\n};\n\n} } \/\/\/ namespace eosio::chain\n\nFC_REFLECT( eosio::chain::newaccount , (creator)(name)(owner)(active) )\nFC_REFLECT( eosio::chain::setcode , (account)(vmtype)(vmversion)(code) )\nFC_REFLECT( eosio::chain::setabi , (account)(abi) )\nFC_REFLECT( eosio::chain::updateauth , (account)(permission)(parent)(auth) )\nFC_REFLECT( eosio::chain::deleteauth , (account)(permission) )\nFC_REFLECT( eosio::chain::linkauth , (account)(code)(type)(requirement) )\nFC_REFLECT( eosio::chain::unlinkauth , (account)(code)(type) )\nFC_REFLECT( eosio::chain::canceldelay , (canceling_auth)(trx_id) )\nFC_REFLECT( eosio::chain::onerror , (sender_id)(sent_trx) )\n<commit_msg>Revert unneeded explicit wrap of account_name constructor<commit_after>#pragma once\n\n#include <eosio\/chain\/authority.hpp>\n#include <eosio\/chain\/chain_config.hpp>\n#include <eosio\/chain\/config.hpp>\n#include <eosio\/chain\/types.hpp>\n\nnamespace eosio { namespace chain {\n\nusing action_name = eosio::chain::action_name;\n\nstruct newaccount {\n account_name creator;\n account_name name;\n authority owner;\n authority active;\n\n static account_name get_account() {\n return config::system_account_name;\n }\n\n static action_name get_name() {\n return N(newaccount);\n }\n};\n\nstruct setcode {\n account_name account;\n uint8_t vmtype = 0;\n uint8_t vmversion = 0;\n bytes code;\n\n static account_name get_account() {\n return config::system_account_name;\n }\n\n static action_name get_name() {\n return N(setcode);\n }\n};\n\nstruct setabi {\n account_name account;\n bytes abi;\n\n static account_name get_account() {\n return config::system_account_name;\n }\n\n static action_name get_name() {\n return N(setabi);\n }\n};\n\n\nstruct updateauth {\n account_name account;\n permission_name permission;\n permission_name parent;\n authority auth;\n\n static account_name get_account() {\n return config::system_account_name;\n }\n\n static action_name get_name() {\n return N(updateauth);\n }\n};\n\nstruct deleteauth {\n deleteauth() = default;\n deleteauth(const account_name& account, const permission_name& permission)\n :account(account), permission(permission)\n {}\n\n account_name account;\n permission_name permission;\n\n static account_name get_account() {\n return config::system_account_name;\n }\n\n static action_name get_name() {\n return N(deleteauth);\n }\n};\n\nstruct linkauth {\n linkauth() = default;\n linkauth(const account_name& account, const account_name& code, const action_name& type, const permission_name& requirement)\n :account(account), code(code), type(type), requirement(requirement)\n {}\n\n account_name account;\n account_name code;\n action_name type;\n permission_name requirement;\n\n static account_name get_account() {\n return config::system_account_name;\n }\n\n static action_name get_name() {\n return N(linkauth);\n }\n};\n\nstruct unlinkauth {\n unlinkauth() = default;\n unlinkauth(const account_name& account, const account_name& code, const action_name& type)\n :account(account), code(code), type(type)\n {}\n\n account_name account;\n account_name code;\n action_name type;\n\n static account_name get_account() {\n return config::system_account_name;\n }\n\n static action_name get_name() {\n return N(unlinkauth);\n }\n};\n\nstruct canceldelay {\n permission_level canceling_auth;\n transaction_id_type trx_id;\n\n static account_name get_account() {\n return config::system_account_name;\n }\n\n static action_name get_name() {\n return N(canceldelay);\n }\n};\n\nstruct onerror {\n uint128_t sender_id;\n bytes sent_trx;\n\n onerror( uint128_t sid, const char* data, size_t len )\n :sender_id(sid),sent_trx(data,data+len){}\n\n static account_name get_account() {\n return config::system_account_name;\n }\n\n static action_name get_name() {\n return N(onerror);\n }\n};\n\n} } \/\/\/ namespace eosio::chain\n\nFC_REFLECT( eosio::chain::newaccount , (creator)(name)(owner)(active) )\nFC_REFLECT( eosio::chain::setcode , (account)(vmtype)(vmversion)(code) )\nFC_REFLECT( eosio::chain::setabi , (account)(abi) )\nFC_REFLECT( eosio::chain::updateauth , (account)(permission)(parent)(auth) )\nFC_REFLECT( eosio::chain::deleteauth , (account)(permission) )\nFC_REFLECT( eosio::chain::linkauth , (account)(code)(type)(requirement) )\nFC_REFLECT( eosio::chain::unlinkauth , (account)(code)(type) )\nFC_REFLECT( eosio::chain::canceldelay , (canceling_auth)(trx_id) )\nFC_REFLECT( eosio::chain::onerror , (sender_id)(sent_trx) )\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n#include <algorithm>\n#include <cmath>\n\nusing namespace std;\n\ntypedef struct Point {\n int x;\n int y;\n} Point;\n\nint solve(Point a[], int n, int d);\nint shift(Point a[], int n, int d, int idx);\nbool cmpX(Point a, Point b);\nbool cmpY(Point a, Point b);\nbool cmp(Point a, Point b);\n\nint main() {\n int n, d;\n\n int cnt = 0;\n while (cin >> n >> d) {\n if (n == 0 && d == 0)\n break;\n\n cnt++;\n Point a[n];\n\n for (int i = 0; i < n; i++)\n cin >> a[i].x >> a[i].y;\n sort(a, a + n, cmp);\n\n int res = solve(a, n, d);\n\n cout << \"Case \" << cnt << \": \" << res << endl;\n }\n}\n\nint solve(Point a[], int n, int d) {\n int cnt = 0;\n\n int idx = 0;\n while (idx < n) {\n int tmp = shift(a, n, d, idx);\n\n if (tmp == -1)\n return -1;\n\n cnt++;\n idx += tmp;\n }\n\n return cnt;\n}\n\nint shift(Point a[], int n, int d, int idx) {\n int ret = 1;\n\n if (a[idx].y > d)\n return -1;\n\n int radarPos = sqrt(d^2 - a[idx].y^2) + a[idx].x;\n\n for (int i = idx + 1; i < n; i++) {\n if (i == n)\n break;\n\n int dist = d^2 - (a[i].x - radarPos)^2 - a[i].y^2;\n\n if (dist >= 0)\n ret++;\n else\n break;\n }\n\n return ret;\n}\n\nbool cmp(Point a, Point b) {\n if (a.x != b.x)\n return a.x < b.x; \n else\n return a.y < b.y;\n}\n\nbool cmpX(Point a, Point b) {\n return a.x < b.x;\n}\n\nbool cmpY(Point a, Point b) {\n return a.y < b.y;\n}\n<commit_msg>p1328<commit_after>#include <iostream>\n#include <algorithm>\n#include <cmath>\n\nusing namespace std;\n\ntypedef struct Point {\n float x;\n float y;\n} Point;\n\nint solve(Point a[], int n, float d);\nint shift(Point a[], int n, float d, int idx);\nbool cmpX(Point a, Point b);\nbool cmpY(Point a, Point b);\nbool cmp(Point a, Point b);\n\nint main() {\n int n;\n float d;\n\n int cnt = 0;\n while (cin >> n >> d) {\n if (n == 0 && d == 0.0)\n break;\n\n cnt++;\n Point a[n];\n\n for (int i = 0; i < n; i++)\n cin >> a[i].x >> a[i].y;\n sort(a, a + n, cmp);\n\n int res = solve(a, n, d);\n\n cout << \"Case \" << cnt << \": \" << res << endl;\n }\n}\n\nint solve(Point a[], int n, float d) {\n int cnt = 0;\n\n int idx = 0;\n while (idx < n) {\n int tmp = shift(a, n, d, idx);\n\n if (tmp == -1)\n return -1;\n\n cnt++;\n idx += tmp;\n }\n\n return cnt;\n}\n\nint shift(Point a[], int n, float d, int idx) {\n int ret = 1;\n\n if (a[idx].y > d)\n return -1;\n\n float radarPos = sqrt(d * d - a[idx].y * a[idx].y) + a[idx].x;\n\n for (int i = idx + 1; i < n; i++) {\n if (i == n)\n break;\n\n float diffX = a[i].x - radarPos;\n float dist = d * d - diffX * diffX - a[i].y * a[i].y;\n\n if (dist >= 0)\n ret++;\n else\n break;\n }\n\n return ret;\n}\n\nbool cmp(Point a, Point b) {\n if (a.x != b.x)\n return a.x < b.x; \n else\n return a.y < b.y;\n}\n\nbool cmpX(Point a, Point b) {\n return a.x < b.x;\n}\n\nbool cmpY(Point a, Point b) {\n return a.y < b.y;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright 2007-2018 Content Management AG\n * All rights reserved.\n *\n * author: Max Kellermann <mk@cm4all.com>\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * - Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n *\n * - Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the\n * distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,\n * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED\n * OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#pragma once\n\n#include \"filtered_socket.hxx\"\n#include \"lease.hxx\"\n\n\/**\n * Wrapper for a #FilteredSocket which may be released at some point.\n * After that, remaining data in the input buffer can still be read.\n *\/\nclass FilteredSocketLease {\n FilteredSocket socket;\n struct lease_ref lease_ref;\n\npublic:\n FilteredSocketLease(EventLoop &event_loop,\n SocketDescriptor fd, FdType fd_type,\n Lease &lease,\n const struct timeval *read_timeout,\n const struct timeval *write_timeout,\n const SocketFilter *filter, void *filter_ctx,\n BufferedSocketHandler &handler) noexcept\n :socket(event_loop)\n {\n socket.Init(fd, fd_type, read_timeout, write_timeout,\n filter, filter_ctx,\n handler);\n lease_ref.Set(lease);\n }\n\n ~FilteredSocketLease() noexcept {\n assert(IsReleased());\n\n socket.Destroy();\n }\n\n EventLoop &GetEventLoop() noexcept {\n return socket.GetEventLoop();\n }\n\n gcc_pure\n bool IsValid() const noexcept {\n return socket.IsValid();\n }\n\n gcc_pure\n bool IsConnected() const noexcept {\n return socket.IsConnected();\n }\n\n gcc_pure\n bool HasFilter() const noexcept {\n assert(!IsReleased());\n\n return socket.HasFilter();\n }\n\n#ifndef NDEBUG\n gcc_pure\n bool HasEnded() const noexcept {\n assert(!IsReleased());\n\n return socket.ended;\n }\n#endif\n\n void Release(bool reuse) noexcept {\n socket.Abandon();\n lease_ref.Release(reuse);\n }\n\n#ifndef NDEBUG\n bool IsReleased() const noexcept {\n return lease_ref.released;\n }\n#endif\n\n gcc_pure\n FdType GetType() const noexcept {\n assert(!IsReleased());\n\n return socket.GetType();\n }\n\n void SetDirect(bool _direct) noexcept {\n assert(!IsReleased());\n\n socket.SetDirect(_direct);\n }\n\n int AsFD() noexcept {\n assert(!IsReleased());\n\n return socket.AsFD();\n }\n\n gcc_pure\n bool IsEmpty() const noexcept {\n return socket.IsEmpty();\n }\n\n gcc_pure\n size_t GetAvailable() const noexcept {\n return socket.GetAvailable();\n }\n\n WritableBuffer<void> ReadBuffer() const noexcept {\n return socket.ReadBuffer();\n }\n\n void Consumed(size_t nbytes) noexcept {\n socket.Consumed(nbytes);\n }\n\n bool Read(bool expect_more) noexcept {\n return socket.Read(expect_more);\n }\n\n void ScheduleReadTimeout(bool expect_more,\n const struct timeval *timeout) noexcept {\n assert(!IsReleased());\n\n socket.ScheduleReadTimeout(expect_more, timeout);\n }\n\n void ScheduleReadNoTimeout(bool expect_more) noexcept {\n assert(!IsReleased());\n\n socket.ScheduleReadNoTimeout(expect_more);\n }\n\n ssize_t Write(const void *data, size_t size) noexcept {\n assert(!IsReleased());\n\n return socket.Write(data, size);\n }\n\n void ScheduleWrite() noexcept {\n assert(!IsReleased());\n\n socket.ScheduleWrite();\n }\n\n void UnscheduleWrite() noexcept {\n assert(!IsReleased());\n\n socket.UnscheduleWrite();\n }\n\n ssize_t WriteV(const struct iovec *v, size_t n) noexcept {\n assert(!IsReleased());\n\n return socket.WriteV(v, n);\n }\n\n ssize_t WriteFrom(int fd, FdType fd_type, size_t length) noexcept {\n assert(!IsReleased());\n\n return socket.WriteFrom(fd, fd_type, length);\n }\n};\n<commit_msg>fs_lease: remove dangerous method IsValid()<commit_after>\/*\n * Copyright 2007-2018 Content Management AG\n * All rights reserved.\n *\n * author: Max Kellermann <mk@cm4all.com>\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * - Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n *\n * - Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the\n * distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,\n * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED\n * OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#pragma once\n\n#include \"filtered_socket.hxx\"\n#include \"lease.hxx\"\n\n\/**\n * Wrapper for a #FilteredSocket which may be released at some point.\n * After that, remaining data in the input buffer can still be read.\n *\/\nclass FilteredSocketLease {\n FilteredSocket socket;\n struct lease_ref lease_ref;\n\npublic:\n FilteredSocketLease(EventLoop &event_loop,\n SocketDescriptor fd, FdType fd_type,\n Lease &lease,\n const struct timeval *read_timeout,\n const struct timeval *write_timeout,\n const SocketFilter *filter, void *filter_ctx,\n BufferedSocketHandler &handler) noexcept\n :socket(event_loop)\n {\n socket.Init(fd, fd_type, read_timeout, write_timeout,\n filter, filter_ctx,\n handler);\n lease_ref.Set(lease);\n }\n\n ~FilteredSocketLease() noexcept {\n assert(IsReleased());\n\n socket.Destroy();\n }\n\n EventLoop &GetEventLoop() noexcept {\n return socket.GetEventLoop();\n }\n\n gcc_pure\n bool IsConnected() const noexcept {\n return socket.IsConnected();\n }\n\n gcc_pure\n bool HasFilter() const noexcept {\n assert(!IsReleased());\n\n return socket.HasFilter();\n }\n\n#ifndef NDEBUG\n gcc_pure\n bool HasEnded() const noexcept {\n assert(!IsReleased());\n\n return socket.ended;\n }\n#endif\n\n void Release(bool reuse) noexcept {\n socket.Abandon();\n lease_ref.Release(reuse);\n }\n\n#ifndef NDEBUG\n bool IsReleased() const noexcept {\n return lease_ref.released;\n }\n#endif\n\n gcc_pure\n FdType GetType() const noexcept {\n assert(!IsReleased());\n\n return socket.GetType();\n }\n\n void SetDirect(bool _direct) noexcept {\n assert(!IsReleased());\n\n socket.SetDirect(_direct);\n }\n\n int AsFD() noexcept {\n assert(!IsReleased());\n\n return socket.AsFD();\n }\n\n gcc_pure\n bool IsEmpty() const noexcept {\n return socket.IsEmpty();\n }\n\n gcc_pure\n size_t GetAvailable() const noexcept {\n return socket.GetAvailable();\n }\n\n WritableBuffer<void> ReadBuffer() const noexcept {\n return socket.ReadBuffer();\n }\n\n void Consumed(size_t nbytes) noexcept {\n socket.Consumed(nbytes);\n }\n\n bool Read(bool expect_more) noexcept {\n return socket.Read(expect_more);\n }\n\n void ScheduleReadTimeout(bool expect_more,\n const struct timeval *timeout) noexcept {\n assert(!IsReleased());\n\n socket.ScheduleReadTimeout(expect_more, timeout);\n }\n\n void ScheduleReadNoTimeout(bool expect_more) noexcept {\n assert(!IsReleased());\n\n socket.ScheduleReadNoTimeout(expect_more);\n }\n\n ssize_t Write(const void *data, size_t size) noexcept {\n assert(!IsReleased());\n\n return socket.Write(data, size);\n }\n\n void ScheduleWrite() noexcept {\n assert(!IsReleased());\n\n socket.ScheduleWrite();\n }\n\n void UnscheduleWrite() noexcept {\n assert(!IsReleased());\n\n socket.UnscheduleWrite();\n }\n\n ssize_t WriteV(const struct iovec *v, size_t n) noexcept {\n assert(!IsReleased());\n\n return socket.WriteV(v, n);\n }\n\n ssize_t WriteFrom(int fd, FdType fd_type, size_t length) noexcept {\n assert(!IsReleased());\n\n return socket.WriteFrom(fd, fd_type, length);\n }\n};\n<|endoftext|>"} {"text":"<commit_before>#include \"burner_ethernet.h\"\nBurnerEthernet net;\n\n#include \"burner_config.h\"\nextern BurnerConfig cfg;\n\n#include \"pits_burner.h\"\nextern PitsBurner burner;\n\n#include <EtherCard.h>\nconst byte ecoPelletMac[] = {0x1E, 0x98, 0xB5, 0xDF, 0x9A, 0x42}; \/\/not IEEE mac, just random\n\/\/const byte ecoPelletIp[] = {192, 168, 3, 66}; \nbyte Ethernet::buffer[300]; \/\/was 500\nBufferFiller bfill;\n\nvoid BurnerEthernet::init() \n{ \n \/\/Serial.println(F(\"Net init\"));\n \n if (ether.begin(sizeof Ethernet::buffer, ecoPelletMac) == 0)\n Serial.println(F(\"Ethernet setup failed\"));\n \n if (!ether.dhcpSetup(\"EcoPellet\", true))\n Serial.println(F(\"DHCP failed\"));\n \/\/ether.staticSetup(ecoPelletIp);\n \n \/\/ether.printIp(\"MAC: \", ecoPelletMac);\n ether.printIp(\"IP: \", ether.myip);\n ether.printIp(\"Mask: \", ether.netmask);\n ether.printIp(\"GW: \", ether.gwip);\n ether.printIp(\"DNS: \", ether.dnsip);\n}\n\nstatic word writeResponse() {\n\n long t = millis() \/ 1000;\n word h = t \/ 3600;\n byte m = (t \/ 60) % 60;\n byte s = t % 60;\n\n bfill = ether.tcpOffset();\n bfill.emit_p(PSTR(\n \"HTTP\/1.0 200 OK\\r\\n\"\n \"Content-Type: text\/html\\r\\n\"\n \"Pragma: no-cache\\r\\n\"\n \"\\r\\n\"\n \"<meta http-equiv='refresh' content='1'\/>\"\n \"{CurT:$D\"\n \",ExhT:$D\"\n \",FedT:$D\"\n \",Flame:$D\"\n \",Fan:$D\"\n \",Feed:$D\"\n \",FeedS:$D\"\n \",Ign:$D\"\n \",NoFlm:$D\"\n \",Alrm:$D\"\n \",Mode:$D\"\n \",Fuel:$D\"\n \",Batt:$D\"\n \",MaxT:$D\"\n \",MxDT:$D\"\n \",ReqT:$D\"\n \",HstT:$D\"\n \",ExdT:$D\"\n \",UpTm:$D$D:$D$D:$D$D\"\n \"}\"),\n burner.getCurrentTemp(),\n burner.getExhaustTemp(),\n burner.getFeederTemp(),\n burner.getFlame(),\n burner.getFan(),\n burner.getFeed(),\n burner.getFeedTime(),\n burner.isIgnition(),\n burner.getSecondsWithoutFlame(),\n burner.getAlarmStatus(),\n burner.getCurrentMode(),\n burner.getFuelLevel(),\n burner.getBattLevel(),\n cfg.getMaxTemp(),\n cfg.getMaxDropTemp(),\n cfg.getRequiredTemp(),\n cfg.getHysteresisTemp(),\n cfg.getExhaustDeltaTemp(),\n h\/10, h%10, m\/10, m%10, s\/10, s%10\n );\n\n return bfill.position();\n}\n\nvoid BurnerEthernet::listen() {\n word len = ether.packetReceive();\n word pos = ether.packetLoop(len);\n \n if (pos) \/\/ check if valid tcp data is received\n ether.httpServerReply(writeResponse()); \/\/ send web page data\n}\n\nconst byte* BurnerEthernet::getMac() {\n return ecoPelletMac;\n}\n\n<commit_msg>- buildin led on if ethernet error<commit_after>#include \"burner_ethernet.h\"\nBurnerEthernet net;\n\n#include \"burner_config.h\"\nextern BurnerConfig cfg;\n\n#include \"pits_burner.h\"\nextern PitsBurner burner;\n\n#include <EtherCard.h>\nconst byte ecoPelletMac[] = {0x1E, 0x98, 0xB5, 0xDF, 0x9A, 0x42}; \/\/not IEEE mac, just random\n\/\/const byte ecoPelletIp[] = {192, 168, 3, 66}; \nbyte Ethernet::buffer[300]; \/\/was 500\nBufferFiller bfill;\n\nvoid BurnerEthernet::init() \n{ \n Serial.println(F(\"Net init\"));\n \n if (ether.begin(sizeof Ethernet::buffer, ecoPelletMac) == 0) {\n Serial.println(F(\"Ethernet setup failed\"));\n digitalWrite(LED_BUILTIN, HIGH);\n }\n \n if (!ether.dhcpSetup(\"EcoPellet\", true)) {\n Serial.println(F(\"DHCP failed\"));\n digitalWrite(LED_BUILTIN, HIGH);\n }\n \/\/ether.staticSetup(ecoPelletIp);\n \n \/\/ether.printIp(\"MAC: \", ecoPelletMac);\n ether.printIp(\"IP: \", ether.myip);\n ether.printIp(\"Mask: \", ether.netmask);\n ether.printIp(\"GW: \", ether.gwip);\n ether.printIp(\"DNS: \", ether.dnsip);\n}\n\nstatic word writeResponse() {\n\n long t = millis() \/ 1000;\n word h = t \/ 3600;\n byte m = (t \/ 60) % 60;\n byte s = t % 60;\n\n bfill = ether.tcpOffset();\n bfill.emit_p(PSTR(\n \"HTTP\/1.0 200 OK\\r\\n\"\n \"Content-Type: text\/html\\r\\n\"\n \"Pragma: no-cache\\r\\n\"\n \"\\r\\n\"\n \"<meta http-equiv='refresh' content='1'\/>\"\n \"{CurT:$D\"\n \",ExhT:$D\"\n \",FedT:$D\"\n \",Flame:$D\"\n \",Fan:$D\"\n \",Feed:$D\"\n \",FeedS:$D\"\n \",Ign:$D\"\n \",NoFlm:$D\"\n \",Alrm:$D\"\n \",Mode:$D\"\n \",Fuel:$D\"\n \",Batt:$D\"\n \",MaxT:$D\"\n \",MxDT:$D\"\n \",ReqT:$D\"\n \",HstT:$D\"\n \",ExdT:$D\"\n \",UpTm:$D$D:$D$D:$D$D\"\n \"}\"),\n burner.getCurrentTemp(),\n burner.getExhaustTemp(),\n burner.getFeederTemp(),\n burner.getFlame(),\n burner.getFan(),\n burner.getFeed(),\n burner.getFeedTime(),\n burner.isIgnition(),\n burner.getSecondsWithoutFlame(),\n burner.getAlarmStatus(),\n burner.getCurrentMode(),\n burner.getFuelLevel(),\n burner.getBattLevel(),\n cfg.getMaxTemp(),\n cfg.getMaxDropTemp(),\n cfg.getRequiredTemp(),\n cfg.getHysteresisTemp(),\n cfg.getExhaustDeltaTemp(),\n h\/10, h%10, m\/10, m%10, s\/10, s%10\n );\n\n return bfill.position();\n}\n\nvoid BurnerEthernet::listen() {\n word len = ether.packetReceive();\n word pos = ether.packetLoop(len);\n \n if (pos) \/\/ check if valid tcp data is received\n ether.httpServerReply(writeResponse()); \/\/ send web page data\n}\n\nconst byte* BurnerEthernet::getMac() {\n return ecoPelletMac;\n}\n\n<|endoftext|>"} {"text":"<commit_before>#include \"erl_nif.h\"\n\n\nstatic ErlNifResourceType* bulleterl_RESOURCE = NULL;\n\nstruct bulleterl_handle\n{\n}; \/\/ end bulleterl_handle\n\n\n\/\/ Prototypes\nstatic ERL_NIF_TERM bulleterl_new(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]);\nstatic ERL_NIF_TERM bulleterl_myfunction(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]);\n\n\nstatic ErlNifFunc nif_funcs[] = {\n {\"new\", 0, bulleterl_new},\n {\"myfunction\", 1, bulleterl_myfunction}\n}; \/\/ end nif_funcs\n\n\nstatic ERL_NIF_TERM bulleterl_new(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[])\n{\n bulleterl_handle* handle = (bulleterl_handle*) enif_alloc_resource(bulleterl_RESOURCE, sizeof(bulleterl_handle));\n ERL_NIF_TERM result = enif_make_resource(env, handle);\n enif_release_resource(handle);\n\n return enif_make_tuple2(env, enif_make_atom(env, \"ok\"), result);\n} \/\/ end bulleterl_new\n\n\nstatic ERL_NIF_TERM bulleterl_myfunction(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[])\n{\n return enif_make_atom(env, \"ok\");\n} \/\/ end bulleterl_myfunction\n\nstatic void bulleterl_resource_cleanup(ErlNifEnv* env, void* arg)\n{\n \/* Delete any dynamically allocated memory stored in bulleterl_handle *\/\n \/* bulleterl_handle* handle = (bulleterl_handle*)arg; *\/\n} \/\/ end bulleterl_resource_cleanup\n\nstatic int on_load(ErlNifEnv* env, void** priv_data, ERL_NIF_TERM load_info)\n{\n ErlNifResourceFlags flags = ErlNifResourceFlags(ERL_NIF_RT_CREATE | ERL_NIF_RT_TAKEOVER);\n\n ErlNifResourceType* rt = enif_open_resource_type(env, NULL,\n\t\t\t\"bulleterl_resource\", &bulleterl_resource_cleanup, flags, NULL);\n\n if(rt == NULL)\n\t{\n return -1;\n\t} \/\/ end if\n\n bulleterl_RESOURCE = rt;\n\n return 0;\n} \/\/ end on_load\n\nERL_NIF_INIT(bulleterl, nif_funcs, &on_load, NULL, NULL, NULL);\n<commit_msg>Updated bulleterl.cpp to work with BulletEngine.<commit_after>#include \"erl_nif.h\"\n\n#include \"BulletEngine.h\"\n\n\nstatic ErlNifResourceType* bulleterlType = NULL;\n\n\nnamespace bulleterl\n{\n\n\tstatic ERL_NIF_TERM new_(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[])\n\t{\n\t\tBulletEngine* engine = new (enif_alloc_resource(bulleterlType, sizeof(BulletEngine))) BulletEngine();\n\t\tERL_NIF_TERM result = enif_make_resource(env, engine);\n\t\tenif_release_resource(engine);\n\n\t\treturn enif_make_tuple2(env, enif_make_atom(env, \"bulleterl\"), result);\n\t} \/\/ end new_\n\n\n\tstatic ERL_NIF_TERM myfunction(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[])\n\t{\n\t\treturn enif_make_atom(env, \"ok\");\n\t} \/\/ end myfunction\n\n\tstatic void cleanup(ErlNifEnv* env, void* obj)\n\t{\n\t\tBulletEngine* handle = (BulletEngine*) obj;\n\t\thandle->~BulletEngine();\n\t} \/\/ end cleanup\n\n\tstatic int on_load(ErlNifEnv* env, void** priv_data, ERL_NIF_TERM load_info)\n\t{\n\t\tErlNifResourceFlags flags = ErlNifResourceFlags(ERL_NIF_RT_CREATE | ERL_NIF_RT_TAKEOVER);\n\n\t\tErlNifResourceType* rt;\n\n\t\trt = enif_open_resource_type(env, NULL, \"bulleterl\", &bulleterl::cleanup, flags, NULL);\n\t\tif(rt == NULL) { return -1; }\n\t\tbulleterlType = rt;\n\n\t\treturn 0;\n\t} \/\/ end on_load\n\n}; \/\/ end bulleterl\n\n\nstatic ErlNifFunc nif_funcs[] = {\n {\"new\", 0, bulleterl::new_},\n {\"myfunction\", 1, bulleterl::myfunction}\n}; \/\/ end nif_funcs\n\nERL_NIF_INIT(bulleterl, nif_funcs, &bulleterl::on_load, NULL, NULL, NULL);\n<|endoftext|>"} {"text":"<commit_before>#include \"AbstractUniformImplementation.h\"\n\n#include <globjects\/globjects.h>\n\n#include \"BindlessUniformImplementation.h\"\n#include \"LegacyUniformImplementation.h\"\n\nnamespace glo {\n\nAbstractUniformImplementation::AbstractUniformImplementation()\n{\n}\n\nAbstractUniformImplementation::~AbstractUniformImplementation()\n{\n}\n\nAbstractUniformImplementation * AbstractUniformImplementation::create()\n{\n if (hasExtension(gl::GLextension::GL_EXT_direct_state_access))\n {\n return new BindlessUniformImplementation();\n }\n else\n {\n return new LegacyUniformImplementation();\n }\n}\n\n} \/\/ namespace glo\n<commit_msg>Fix required extension for bindless uniform setters<commit_after>#include \"AbstractUniformImplementation.h\"\n\n#include <globjects\/globjects.h>\n\n#include \"BindlessUniformImplementation.h\"\n#include \"LegacyUniformImplementation.h\"\n\nnamespace glo {\n\nAbstractUniformImplementation::AbstractUniformImplementation()\n{\n}\n\nAbstractUniformImplementation::~AbstractUniformImplementation()\n{\n}\n\nAbstractUniformImplementation * AbstractUniformImplementation::create()\n{\n if (hasExtension(gl::GLextension::GL_ARB_separate_shader_objects))\n {\n return new BindlessUniformImplementation();\n }\n else\n {\n return new LegacyUniformImplementation();\n }\n}\n\n} \/\/ namespace glo\n<|endoftext|>"} {"text":"<commit_before>\/****************************************************************************\n **\n ** Copyright (C) Qxt Foundation. Some rights reserved.\n **\n ** This file is part of the QxtGui module of the Qxt library.\n **\n ** This library is free software; you can redistribute it and\/or modify it\n ** under the terms of the Common Public License, version 1.0, as published\n ** by IBM, and\/or under the terms of the GNU Lesser General Public License,\n ** version 2.1, as published by the Free Software Foundation.\n **\n ** This file is provided \"AS IS\", without WARRANTIES OR CONDITIONS OF ANY\n ** KIND, EITHER EXPRESS OR IMPLIED INCLUDING, WITHOUT LIMITATION, ANY\n ** WARRANTIES OR CONDITIONS OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY OR\n ** FITNESS FOR A PARTICULAR PURPOSE.\n **\n ** You should have received a copy of the CPL and the LGPL along with this\n ** file. See the LICENSE file and the cpl1.0.txt\/lgpl-2.1.txt files\n ** included with the source distribution for more information.\n ** If you did not receive a copy of the licenses, contact the Qxt Foundation.\n **\n ** <http:\/\/libqxt.org> <foundation@libqxt.org>\n **\n ****************************************************************************\/\n#include \"qxtprogresslabel.h\"\n#include <QProgressBar>\n#include <QBasicTimer>\n#include <QTime>\n\nclass QxtProgressLabelPrivate : public QxtPrivate<QxtProgressLabel>\n{\npublic:\n QXT_DECLARE_PUBLIC(QxtProgressLabel);\n QxtProgressLabelPrivate();\n\n QTime start;\n int interval;\n int cachedMin;\n int cachedMax;\n int cachedVal;\n QString cformat;\n QString tformat;\n QBasicTimer timer;\n};\n\nQxtProgressLabelPrivate::QxtProgressLabelPrivate()\n : interval(-1), cachedMin(0), cachedMax(0), cachedVal(0)\n{}\n\n\/*!\n \\class QxtProgressLabel\n \\inmodule QxtGui\n \\brief The QxtProgressLabel widget is a label showing progress related time values.\n\n QxtProgressLabel is a label widget able to show elapsed and remaining\n time of a progress. Usage is as simple as connecting signal\n QProgressBar::valueChanged() to slot QxtProgressLabel::setValue().\n\n Example usage:\n \\code\n QProgressBar* bar = new QProgressBar(this);\n QxtProgressLabel* label = new QxtProgressLabel(this);\n connect(bar, SIGNAL(valueChanged(int)), label, SLOT(setValue(int)));\n \\endcode\n\n \\image qxtprogresslabel.png \"QxtProgressLabel in action.\"\n *\/\n\n\/*!\n Constructs a new QxtProgressLabel with \\a parent and \\a flags.\n *\/\nQxtProgressLabel::QxtProgressLabel(QWidget* parent, Qt::WindowFlags flags)\n : QLabel(parent, flags)\n{\n QXT_INIT_PRIVATE(QxtProgressLabel);\n refresh();\n}\n\n\/*!\n Constructs a new QxtProgressLabel with \\a text, \\a parent and \\a flags.\n *\/\nQxtProgressLabel::QxtProgressLabel(const QString& text, QWidget* parent, Qt::WindowFlags flags)\n : QLabel(text, parent, flags)\n{\n QXT_INIT_PRIVATE(QxtProgressLabel);\n refresh();\n}\n\n\/*!\n Destructs the progress label.\n *\/\nQxtProgressLabel::~QxtProgressLabel()\n{}\n\n\/*!\n \\property QxtProgressLabel::contentFormat\n \\brief the content format of the progress label\n\n The content of the label is formatted according to this property.\n The default value is an empty string which defaults to \\bold \"ETA: %r\".\n\n The following variables may be used in the format string:\n <table>\n <tr><td><b>Variable<\/b><\/td><td><b>Output<\/b><\/td><\/tr>\n <tr><td>\\%e<\/td><td>elapsed time<\/td><\/tr>\n <tr><td>\\%r<\/td><td>remaining time<\/td><\/tr>\n <\/table>\n\n \\sa timeFormat\n *\/\nQString QxtProgressLabel::contentFormat() const\n{\n return qxt_d().cformat;\n}\n\nvoid QxtProgressLabel::setContentFormat(const QString& format)\n{\n if (qxt_d().cformat != format)\n {\n qxt_d().cformat = format;\n refresh();\n }\n}\n\n\/*!\n \\property QxtProgressLabel::timeFormat\n \\brief the time format of the progress label\n\n Time values are formatted according to this property.\n The default value is an empty string which defaults to \\bold \"mm:ss\".\n\n \\sa contentFormat, QTime::toString()\n *\/\nQString QxtProgressLabel::timeFormat() const\n{\n return qxt_d().tformat;\n}\n\nvoid QxtProgressLabel::setTimeFormat(const QString& format)\n{\n if (qxt_d().tformat != format)\n {\n qxt_d().tformat = format;\n refresh();\n }\n}\n\n\/*!\n \\property QxtProgressLabel::updateInterval\n \\brief the update interval of the progress label\n\n The content of the progress label is updated according to this interval.\n A negative interval makes the content to update only during value changes.\n The default value is \\c -1.\n *\/\nint QxtProgressLabel::updateInterval() const\n{\n return qxt_d().interval;\n}\n\nvoid QxtProgressLabel::setUpdateInterval(int msecs)\n{\n qxt_d().interval = msecs;\n if (msecs < 0)\n {\n if (qxt_d().timer.isActive())\n qxt_d().timer.stop();\n }\n else\n {\n if (!qxt_d().timer.isActive())\n qxt_d().timer.start(msecs, this);\n }\n}\n\n\/*!\n Sets the current value to \\a value.\n\n \\bold {Note:} Calling this slot by hand has no effect.\n Connect this slot to QProgressBar::valueChange().\n *\/\nvoid QxtProgressLabel::setValue(int value)\n{\n QProgressBar* bar = qobject_cast<QProgressBar*>(sender());\n if (bar)\n {\n if (!qxt_d().start.isValid())\n restart();\n\n qxt_d().cachedMin = bar->minimum();\n qxt_d().cachedMax = bar->maximum();\n qxt_d().cachedVal = value;\n\n refresh();\n }\n}\n\n\/*!\n Restarts the calculation of elapsed and remaining times.\n *\/\nvoid QxtProgressLabel::restart()\n{\n qxt_d().cachedMin = 0;\n qxt_d().cachedMax = 0;\n qxt_d().cachedVal = 0;\n qxt_d().start.restart();\n refresh();\n}\n\n\/*!\n Refreshes the content.\n *\/\nvoid QxtProgressLabel::refresh()\n{\n \/\/ elapsed\n qreal elapsed = 0;\n if (qxt_d().start.isValid())\n elapsed = qxt_d().start.elapsed() \/ 1000.0;\n QTime etime(0, 0);\n etime = etime.addSecs(static_cast<int>(elapsed));\n\n \/\/ percentage\n qreal percent = 0;\n if (qxt_d().cachedMax != 0)\n percent = (qxt_d().cachedVal - qxt_d().cachedMin) \/ static_cast<qreal>(qxt_d().cachedMax);\n qreal total = 0;\n if (percent != 0)\n total = elapsed \/ percent;\n\n \/\/ remaining\n QTime rtime(0, 0);\n rtime = rtime.addSecs(static_cast<int>(total - elapsed));\n\n \/\/ format\n QString tformat = qxt_d().tformat;\n if (tformat.isEmpty())\n tformat = tr(\"mm:ss\");\n QString cformat = qxt_d().cformat;\n if (cformat.isEmpty())\n cformat = tr(\"ETA: %r\");\n\n QString result = QString(cformat).replace(\"%e\", etime.toString(tformat));\n result = result.replace(\"%r\", rtime.toString(tformat));\n setText(result);\n}\n\n\/*!\n \\reimp\n *\/\nvoid QxtProgressLabel::timerEvent(QTimerEvent* event)\n{\n Q_UNUSED(event);\n refresh();\n}\n<commit_msg>Revised QxtProgressLabel docs.<commit_after>\/****************************************************************************\n **\n ** Copyright (C) Qxt Foundation. Some rights reserved.\n **\n ** This file is part of the QxtGui module of the Qxt library.\n **\n ** This library is free software; you can redistribute it and\/or modify it\n ** under the terms of the Common Public License, version 1.0, as published\n ** by IBM, and\/or under the terms of the GNU Lesser General Public License,\n ** version 2.1, as published by the Free Software Foundation.\n **\n ** This file is provided \"AS IS\", without WARRANTIES OR CONDITIONS OF ANY\n ** KIND, EITHER EXPRESS OR IMPLIED INCLUDING, WITHOUT LIMITATION, ANY\n ** WARRANTIES OR CONDITIONS OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY OR\n ** FITNESS FOR A PARTICULAR PURPOSE.\n **\n ** You should have received a copy of the CPL and the LGPL along with this\n ** file. See the LICENSE file and the cpl1.0.txt\/lgpl-2.1.txt files\n ** included with the source distribution for more information.\n ** If you did not receive a copy of the licenses, contact the Qxt Foundation.\n **\n ** <http:\/\/libqxt.org> <foundation@libqxt.org>\n **\n ****************************************************************************\/\n#include \"qxtprogresslabel.h\"\n#include <QProgressBar>\n#include <QBasicTimer>\n#include <QTime>\n\nclass QxtProgressLabelPrivate : public QxtPrivate<QxtProgressLabel>\n{\npublic:\n QXT_DECLARE_PUBLIC(QxtProgressLabel);\n QxtProgressLabelPrivate();\n\n QTime start;\n int interval;\n int cachedMin;\n int cachedMax;\n int cachedVal;\n QString cformat;\n QString tformat;\n QBasicTimer timer;\n};\n\nQxtProgressLabelPrivate::QxtProgressLabelPrivate()\n : interval(-1), cachedMin(0), cachedMax(0), cachedVal(0)\n{}\n\n\/*!\n \\class QxtProgressLabel\n \\inmodule QxtGui\n \\brief The QxtProgressLabel widget is a label showing progress related time values.\n\n QxtProgressLabel is a label widget able to show elapsed and remaining\n time of a progress. Usage is as simple as connecting signal\n QProgressBar::valueChanged() to slot QxtProgressLabel::setValue().\n\n Example usage:\n \\code\n QProgressBar* bar = new QProgressBar(this);\n QxtProgressLabel* label = new QxtProgressLabel(this);\n connect(bar, SIGNAL(valueChanged(int)), label, SLOT(setValue(int)));\n \\endcode\n\n \\image qxtprogresslabel.png \"QxtProgressLabel in action.\"\n *\/\n\n\/*!\n Constructs a new QxtProgressLabel with \\a parent and \\a flags.\n *\/\nQxtProgressLabel::QxtProgressLabel(QWidget* parent, Qt::WindowFlags flags)\n : QLabel(parent, flags)\n{\n QXT_INIT_PRIVATE(QxtProgressLabel);\n refresh();\n}\n\n\/*!\n Constructs a new QxtProgressLabel with \\a text, \\a parent and \\a flags.\n *\/\nQxtProgressLabel::QxtProgressLabel(const QString& text, QWidget* parent, Qt::WindowFlags flags)\n : QLabel(text, parent, flags)\n{\n QXT_INIT_PRIVATE(QxtProgressLabel);\n refresh();\n}\n\n\/*!\n Destructs the progress label.\n *\/\nQxtProgressLabel::~QxtProgressLabel()\n{}\n\n\/*!\n \\property QxtProgressLabel::contentFormat\n \\brief the content format of the progress label\n\n The content of the label is formatted according to this property.\n The default value is an empty string which defaults to \\bold \"ETA: %r\".\n\n The following variables may be used in the format string:\n \\table\n \\header \\i Variable \\i Output\n \\row \\i \\%e \\i elapsed time\n \\row \\i \\%r \\i remaining time\n \\endtable\n\n \\sa timeFormat\n *\/\nQString QxtProgressLabel::contentFormat() const\n{\n return qxt_d().cformat;\n}\n\nvoid QxtProgressLabel::setContentFormat(const QString& format)\n{\n if (qxt_d().cformat != format)\n {\n qxt_d().cformat = format;\n refresh();\n }\n}\n\n\/*!\n \\property QxtProgressLabel::timeFormat\n \\brief the time format of the progress label\n\n Time values are formatted according to this property.\n The default value is an empty string which defaults to \\bold \"mm:ss\".\n\n \\sa contentFormat, QTime::toString()\n *\/\nQString QxtProgressLabel::timeFormat() const\n{\n return qxt_d().tformat;\n}\n\nvoid QxtProgressLabel::setTimeFormat(const QString& format)\n{\n if (qxt_d().tformat != format)\n {\n qxt_d().tformat = format;\n refresh();\n }\n}\n\n\/*!\n \\property QxtProgressLabel::updateInterval\n \\brief the update interval of the progress label\n\n The content of the progress label is updated according to this interval.\n A negative interval makes the content to update only during value changes.\n The default value is \\c -1.\n *\/\nint QxtProgressLabel::updateInterval() const\n{\n return qxt_d().interval;\n}\n\nvoid QxtProgressLabel::setUpdateInterval(int msecs)\n{\n qxt_d().interval = msecs;\n if (msecs < 0)\n {\n if (qxt_d().timer.isActive())\n qxt_d().timer.stop();\n }\n else\n {\n if (!qxt_d().timer.isActive())\n qxt_d().timer.start(msecs, this);\n }\n}\n\n\/*!\n Sets the current value to \\a value.\n\n \\bold {Note:} Calling this slot by hand has no effect.\n Connect this slot to QProgressBar::valueChange().\n *\/\nvoid QxtProgressLabel::setValue(int value)\n{\n QProgressBar* bar = qobject_cast<QProgressBar*>(sender());\n if (bar)\n {\n if (!qxt_d().start.isValid())\n restart();\n\n qxt_d().cachedMin = bar->minimum();\n qxt_d().cachedMax = bar->maximum();\n qxt_d().cachedVal = value;\n\n refresh();\n }\n}\n\n\/*!\n Restarts the calculation of elapsed and remaining times.\n *\/\nvoid QxtProgressLabel::restart()\n{\n qxt_d().cachedMin = 0;\n qxt_d().cachedMax = 0;\n qxt_d().cachedVal = 0;\n qxt_d().start.restart();\n refresh();\n}\n\n\/*!\n Refreshes the content.\n *\/\nvoid QxtProgressLabel::refresh()\n{\n \/\/ elapsed\n qreal elapsed = 0;\n if (qxt_d().start.isValid())\n elapsed = qxt_d().start.elapsed() \/ 1000.0;\n QTime etime(0, 0);\n etime = etime.addSecs(static_cast<int>(elapsed));\n\n \/\/ percentage\n qreal percent = 0;\n if (qxt_d().cachedMax != 0)\n percent = (qxt_d().cachedVal - qxt_d().cachedMin) \/ static_cast<qreal>(qxt_d().cachedMax);\n qreal total = 0;\n if (percent != 0)\n total = elapsed \/ percent;\n\n \/\/ remaining\n QTime rtime(0, 0);\n rtime = rtime.addSecs(static_cast<int>(total - elapsed));\n\n \/\/ format\n QString tformat = qxt_d().tformat;\n if (tformat.isEmpty())\n tformat = tr(\"mm:ss\");\n QString cformat = qxt_d().cformat;\n if (cformat.isEmpty())\n cformat = tr(\"ETA: %r\");\n\n QString result = QString(cformat).replace(\"%e\", etime.toString(tformat));\n result = result.replace(\"%r\", rtime.toString(tformat));\n setText(result);\n}\n\n\/*!\n \\reimp\n *\/\nvoid QxtProgressLabel::timerEvent(QTimerEvent* event)\n{\n Q_UNUSED(event);\n refresh();\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/------------------------------------------------------------------------------\n\/\/ CLING - the C++ LLVM-based InterpreterG :)\n\/\/\n\/\/ This file is dual-licensed: you can choose to license it under the University\n\/\/ of Illinois Open Source License or the GNU Lesser General Public License. See\n\/\/ LICENSE.TXT for details.\n\/\/------------------------------------------------------------------------------\n\n\/\/ RUN: cat %s | %cling | FileCheck %s\n\n\/\/ Checks:\n\/\/ Savannah #99210 https:\/\/savannah.cern.ch\/bugs\/index.php?99210\n\/\/ Savannah #99234 https:\/\/savannah.cern.ch\/bugs\/?99234\n\n\/\/ Let's start with simpler example pointing out the issue:\nint i = 1; i++; int j = i;\nj\n\/\/ CHECK: (int) 2\n\nextern \"C\" int printf(const char*,...);\n.rawInput\nclass RAII {\npublic:\n RAII(int i) { I = new int(i); printf(\"RAII%d\\n\", ++InstanceCount); };\n int incr() { return ++(*I); }\n int get() { return *I; }\n ~RAII() { delete I; printf(\"~RAII%d\\n\", InstanceCount--); }\nprivate:\n RAII(RAII&) {throw;};\n RAII& operator=(RAII) {throw;}\n int* I;\n static int InstanceCount; \/\/ will notice object copy\n};\nint RAII::InstanceCount = 0;\n.rawInput\n\n\/\/ This works because each line ends up in a separate wrapper\nRAII R(12); \/\/ CHECK: RAII1\nR.get();\nint res = R.incr() \/\/ CHECK: 13\n\n\/\/ This does not work because the decls and their inits are run before the\n\/\/ call to R2.incr(), i.e. the second statement in the line.\n\/\/ Savannah #99210 https:\/\/savannah.cern.ch\/bugs\/index.php?99210\nRAII R2(42);R2.incr();int res2 = R2.get()\n\/\/ CHECK: RAII2\n\/\/ CHECK: 43\n.q\n\n\/\/ CHECK: ~RAII2\n\/\/ CHECK: ~RAII1\n\/\/ Enforce that only two objects got ever constructed:\n\/\/ CHECK-NOT: ~RAII0\n<commit_msg>Windows: Trivial fix for initorder.C.<commit_after>\/\/------------------------------------------------------------------------------\n\/\/ CLING - the C++ LLVM-based InterpreterG :)\n\/\/\n\/\/ This file is dual-licensed: you can choose to license it under the University\n\/\/ of Illinois Open Source License or the GNU Lesser General Public License. See\n\/\/ LICENSE.TXT for details.\n\/\/------------------------------------------------------------------------------\n\n\/\/ RUN: cat %s | %cling | FileCheck %s\n\n\/\/ Checks:\n\/\/ Savannah #99210 https:\/\/savannah.cern.ch\/bugs\/index.php?99210\n\/\/ Savannah #99234 https:\/\/savannah.cern.ch\/bugs\/?99234\n\n\/\/ Let's start with simpler example pointing out the issue:\nint i = 1; i++; int j = i;\nj\n\/\/ CHECK: (int) 2\n\nextern \"C\" int printf(const char*,...);\n.rawInput\nclass RAII {\npublic:\n RAII(int i) { I = new int(i); printf(\"RAII%d\\n\", ++InstanceCount); };\n int incr() { return ++(*I); }\n int get() { return *I; }\n ~RAII() { delete I; printf(\"~RAII%d\\n\", InstanceCount--); }\nprivate:\n RAII(RAII&);\n RAII& operator=(RAII);\n int* I;\n static int InstanceCount; \/\/ will notice object copy\n};\nint RAII::InstanceCount = 0;\n.rawInput\n\n\/\/ This works because each line ends up in a separate wrapper\nRAII R(12); \/\/ CHECK: RAII1\nR.get();\nint res = R.incr() \/\/ CHECK: 13\n\n\/\/ This does not work because the decls and their inits are run before the\n\/\/ call to R2.incr(), i.e. the second statement in the line.\n\/\/ Savannah #99210 https:\/\/savannah.cern.ch\/bugs\/index.php?99210\nRAII R2(42);R2.incr();int res2 = R2.get()\n\/\/ CHECK: RAII2\n\/\/ CHECK: 43\n.q\n\n\/\/ CHECK: ~RAII2\n\/\/ CHECK: ~RAII1\n\/\/ Enforce that only two objects got ever constructed:\n\/\/ CHECK-NOT: ~RAII0\n<|endoftext|>"} {"text":"<commit_before><commit_msg>Improve handling of null pointers in link properties<commit_after><|endoftext|>"} {"text":"<commit_before>\/*=========================================================================\n *\n * Copyright RTK Consortium\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0.txt\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *=========================================================================*\/\n\n#include \"rtkfdk_ggo.h\"\n#include \"rtkGgoFunctions.h\"\n#include \"rtkConfiguration.h\"\n\n#include \"rtkThreeDCircularProjectionGeometryXMLFile.h\"\n#include \"rtkProjectionsReader.h\"\n#include \"rtkDisplacedDetectorImageFilter.h\"\n#include \"rtkParkerShortScanImageFilter.h\"\n#include \"rtkFDKConeBeamReconstructionFilter.h\"\n#if CUDA_FOUND\n# include \"rtkCudaFDKConeBeamReconstructionFilter.h\"\n#endif\n#if OPENCL_FOUND\n# include \"rtkOpenCLFDKConeBeamReconstructionFilter.h\"\n#endif\n\n#include <itkRegularExpressionSeriesFileNames.h>\n#include <itkStreamingImageFilter.h>\n#include <itkImageFileWriter.h>\n\nint main(int argc, char * argv[])\n{\n GGO(rtkfdk, args_info);\n\n typedef float OutputPixelType;\n const unsigned int Dimension = 3;\n\n typedef itk::Image< OutputPixelType, Dimension > OutputImageType;\n\n \/\/ Generate file names\n itk::RegularExpressionSeriesFileNames::Pointer names = itk::RegularExpressionSeriesFileNames::New();\n names->SetDirectory(args_info.path_arg);\n names->SetNumericSort(false);\n names->SetRegularExpression(args_info.regexp_arg);\n names->SetSubMatch(0);\n\n if(args_info.verbose_flag)\n std::cout << \"Regular expression matches \"\n << names->GetFileNames().size()\n << \" file(s)...\"\n << std::endl;\n\n \/\/ Projections reader\n typedef rtk::ProjectionsReader< OutputImageType > ReaderType;\n ReaderType::Pointer reader = ReaderType::New();\n reader->SetFileNames( names->GetFileNames() );\n TRY_AND_EXIT_ON_ITK_EXCEPTION( reader->GenerateOutputInformation() );\n\n itk::TimeProbe readerProbe;\n if(!args_info.lowmem_flag)\n {\n if(args_info.verbose_flag)\n std::cout << \"Reading... \" << std::flush;\n readerProbe.Start();\n TRY_AND_EXIT_ON_ITK_EXCEPTION( reader->Update() )\n readerProbe.Stop();\n if(args_info.verbose_flag)\n std::cout << \"It took \" << readerProbe.GetMeanTime() << ' ' << readerProbe.GetUnit() << std::endl;\n }\n\n \/\/ Geometry\n if(args_info.verbose_flag)\n std::cout << \"Reading geometry information from \"\n << args_info.geometry_arg\n << \"...\"\n << std::endl;\n rtk::ThreeDCircularProjectionGeometryXMLFileReader::Pointer geometryReader;\n geometryReader = rtk::ThreeDCircularProjectionGeometryXMLFileReader::New();\n geometryReader->SetFilename(args_info.geometry_arg);\n TRY_AND_EXIT_ON_ITK_EXCEPTION( geometryReader->GenerateOutputInformation() )\n\n \/\/ Displaced detector weighting\n typedef rtk::DisplacedDetectorImageFilter< OutputImageType > DDFType;\n DDFType::Pointer ddf = DDFType::New();\n ddf->SetInput( reader->GetOutput() );\n ddf->SetGeometry( geometryReader->GetOutputObject() );\n\n \/\/ Short scan image filter\n typedef rtk::ParkerShortScanImageFilter< OutputImageType > PSSFType;\n PSSFType::Pointer pssf = PSSFType::New();\n pssf->SetInput( ddf->GetOutput() );\n pssf->SetGeometry( geometryReader->GetOutputObject() );\n pssf->InPlaceOff();\n\n \/\/ Create reconstructed image\n typedef rtk::ConstantImageSource< OutputImageType > ConstantImageSourceType;\n ConstantImageSourceType::Pointer constantImageSource = ConstantImageSourceType::New();\n rtk::SetConstantImageSourceFromGgo<ConstantImageSourceType, args_info_rtkfdk>(constantImageSource, args_info);\n\n \/\/ This macro sets options for fdk filter which I can not see how to do better\n \/\/ because TFFTPrecision is not the same, e.g. for CPU and CUDA (SR)\n#define SET_FELDKAMP_OPTIONS(f) \\\n f->SetInput( 0, constantImageSource->GetOutput() ); \\\n f->SetInput( 1, pssf->GetOutput() ); \\\n f->SetGeometry( geometryReader->GetOutputObject() ); \\\n f->GetRampFilter()->SetTruncationCorrection(args_info.pad_arg); \\\n f->GetRampFilter()->SetHannCutFrequency(args_info.hann_arg);\n\n \/\/ FDK reconstruction filtering\n itk::ImageToImageFilter<OutputImageType, OutputImageType>::Pointer feldkamp;\n typedef rtk::FDKConeBeamReconstructionFilter< OutputImageType > FDKCPUType;\n#if CUDA_FOUND\n typedef rtk::CudaFDKConeBeamReconstructionFilter FDKCUDAType;\n#endif\n#if OPENCL_FOUND\n typedef rtk::OpenCLFDKConeBeamReconstructionFilter FDKOPENCLType;\n#endif\n if(!strcmp(args_info.hardware_arg, \"cpu\") )\n {\n feldkamp = FDKCPUType::New();\n SET_FELDKAMP_OPTIONS( static_cast<FDKCPUType*>(feldkamp.GetPointer()) );\n }\n else if(!strcmp(args_info.hardware_arg, \"cuda\") )\n {\n#if CUDA_FOUND\n feldkamp = FDKCUDAType::New();\n SET_FELDKAMP_OPTIONS( static_cast<FDKCUDAType*>(feldkamp.GetPointer()) );\n#else\n std::cerr << \"The program has not been compiled with cuda option\" << std::endl;\n return EXIT_FAILURE;\n#endif\n }\n else if(!strcmp(args_info.hardware_arg, \"opencl\") )\n {\n#if OPENCL_FOUND\n feldkamp = FDKOPENCLType::New();\n SET_FELDKAMP_OPTIONS( static_cast<FDKOPENCLType*>(feldkamp.GetPointer()) );\n#else\n std::cerr << \"The program has not been compiled with opencl option\" << std::endl;\n return EXIT_FAILURE;\n#endif\n }\n\n\n \/\/ Streaming depending on streaming capability of writer\n typedef itk::StreamingImageFilter<OutputImageType, OutputImageType> StreamerType;\n StreamerType::Pointer streamerBP = StreamerType::New();\n itk::ImageIOBase::Pointer imageIOBase;\n streamerBP->SetInput( feldkamp->GetOutput() );\n streamerBP->SetNumberOfStreamDivisions( args_info.divisions_arg );\n\n \/\/ Write\n typedef itk::ImageFileWriter< OutputImageType > WriterType;\n WriterType::Pointer writer = WriterType::New();\n writer->SetFileName( args_info.output_arg );\n writer->SetInput( streamerBP->GetOutput() );\n\n if(args_info.verbose_flag)\n std::cout << \"Reconstructing and writing... \" << std::flush;\n itk::TimeProbe writerProbe;\n\n writerProbe.Start();\n TRY_AND_EXIT_ON_ITK_EXCEPTION( writer->Update() );\n writerProbe.Stop();\n\n if(args_info.verbose_flag)\n {\n std::cout << \"It took \" << writerProbe.GetMeanTime() << ' ' << readerProbe.GetUnit() << std::endl;\n if(!strcmp(args_info.hardware_arg, \"cpu\") )\n static_cast<FDKCPUType* >(feldkamp.GetPointer())->PrintTiming(std::cout);\n#if CUDA_FOUND\n else if(!strcmp(args_info.hardware_arg, \"cuda\") )\n static_cast<FDKCUDAType*>(feldkamp.GetPointer())->PrintTiming(std::cout);\n#endif\n#if OPENCL_FOUND\n else if(!strcmp(args_info.hardware_arg, \"opencl\") )\n static_cast<FDKOPENCLType*>(feldkamp.GetPointer())->PrintTiming(std::cout);\n#endif\n }\n\n return EXIT_SUCCESS;\n}\n<commit_msg>Removed useless line<commit_after>\/*=========================================================================\n *\n * Copyright RTK Consortium\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0.txt\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *=========================================================================*\/\n\n#include \"rtkfdk_ggo.h\"\n#include \"rtkGgoFunctions.h\"\n#include \"rtkConfiguration.h\"\n\n#include \"rtkThreeDCircularProjectionGeometryXMLFile.h\"\n#include \"rtkProjectionsReader.h\"\n#include \"rtkDisplacedDetectorImageFilter.h\"\n#include \"rtkParkerShortScanImageFilter.h\"\n#include \"rtkFDKConeBeamReconstructionFilter.h\"\n#if CUDA_FOUND\n# include \"rtkCudaFDKConeBeamReconstructionFilter.h\"\n#endif\n#if OPENCL_FOUND\n# include \"rtkOpenCLFDKConeBeamReconstructionFilter.h\"\n#endif\n\n#include <itkRegularExpressionSeriesFileNames.h>\n#include <itkStreamingImageFilter.h>\n#include <itkImageFileWriter.h>\n\nint main(int argc, char * argv[])\n{\n GGO(rtkfdk, args_info);\n\n typedef float OutputPixelType;\n const unsigned int Dimension = 3;\n\n typedef itk::Image< OutputPixelType, Dimension > OutputImageType;\n\n \/\/ Generate file names\n itk::RegularExpressionSeriesFileNames::Pointer names = itk::RegularExpressionSeriesFileNames::New();\n names->SetDirectory(args_info.path_arg);\n names->SetNumericSort(false);\n names->SetRegularExpression(args_info.regexp_arg);\n names->SetSubMatch(0);\n\n if(args_info.verbose_flag)\n std::cout << \"Regular expression matches \"\n << names->GetFileNames().size()\n << \" file(s)...\"\n << std::endl;\n\n \/\/ Projections reader\n typedef rtk::ProjectionsReader< OutputImageType > ReaderType;\n ReaderType::Pointer reader = ReaderType::New();\n reader->SetFileNames( names->GetFileNames() );\n TRY_AND_EXIT_ON_ITK_EXCEPTION( reader->GenerateOutputInformation() );\n\n itk::TimeProbe readerProbe;\n if(!args_info.lowmem_flag)\n {\n if(args_info.verbose_flag)\n std::cout << \"Reading... \" << std::flush;\n readerProbe.Start();\n TRY_AND_EXIT_ON_ITK_EXCEPTION( reader->Update() )\n readerProbe.Stop();\n if(args_info.verbose_flag)\n std::cout << \"It took \" << readerProbe.GetMeanTime() << ' ' << readerProbe.GetUnit() << std::endl;\n }\n\n \/\/ Geometry\n if(args_info.verbose_flag)\n std::cout << \"Reading geometry information from \"\n << args_info.geometry_arg\n << \"...\"\n << std::endl;\n rtk::ThreeDCircularProjectionGeometryXMLFileReader::Pointer geometryReader;\n geometryReader = rtk::ThreeDCircularProjectionGeometryXMLFileReader::New();\n geometryReader->SetFilename(args_info.geometry_arg);\n TRY_AND_EXIT_ON_ITK_EXCEPTION( geometryReader->GenerateOutputInformation() )\n\n \/\/ Displaced detector weighting\n typedef rtk::DisplacedDetectorImageFilter< OutputImageType > DDFType;\n DDFType::Pointer ddf = DDFType::New();\n ddf->SetInput( reader->GetOutput() );\n ddf->SetGeometry( geometryReader->GetOutputObject() );\n\n \/\/ Short scan image filter\n typedef rtk::ParkerShortScanImageFilter< OutputImageType > PSSFType;\n PSSFType::Pointer pssf = PSSFType::New();\n pssf->SetInput( ddf->GetOutput() );\n pssf->SetGeometry( geometryReader->GetOutputObject() );\n pssf->InPlaceOff();\n\n \/\/ Create reconstructed image\n typedef rtk::ConstantImageSource< OutputImageType > ConstantImageSourceType;\n ConstantImageSourceType::Pointer constantImageSource = ConstantImageSourceType::New();\n rtk::SetConstantImageSourceFromGgo<ConstantImageSourceType, args_info_rtkfdk>(constantImageSource, args_info);\n\n \/\/ This macro sets options for fdk filter which I can not see how to do better\n \/\/ because TFFTPrecision is not the same, e.g. for CPU and CUDA (SR)\n#define SET_FELDKAMP_OPTIONS(f) \\\n f->SetInput( 0, constantImageSource->GetOutput() ); \\\n f->SetInput( 1, pssf->GetOutput() ); \\\n f->SetGeometry( geometryReader->GetOutputObject() ); \\\n f->GetRampFilter()->SetTruncationCorrection(args_info.pad_arg); \\\n f->GetRampFilter()->SetHannCutFrequency(args_info.hann_arg);\n\n \/\/ FDK reconstruction filtering\n itk::ImageToImageFilter<OutputImageType, OutputImageType>::Pointer feldkamp;\n typedef rtk::FDKConeBeamReconstructionFilter< OutputImageType > FDKCPUType;\n#if CUDA_FOUND\n typedef rtk::CudaFDKConeBeamReconstructionFilter FDKCUDAType;\n#endif\n#if OPENCL_FOUND\n typedef rtk::OpenCLFDKConeBeamReconstructionFilter FDKOPENCLType;\n#endif\n if(!strcmp(args_info.hardware_arg, \"cpu\") )\n {\n feldkamp = FDKCPUType::New();\n SET_FELDKAMP_OPTIONS( static_cast<FDKCPUType*>(feldkamp.GetPointer()) );\n }\n else if(!strcmp(args_info.hardware_arg, \"cuda\") )\n {\n#if CUDA_FOUND\n feldkamp = FDKCUDAType::New();\n SET_FELDKAMP_OPTIONS( static_cast<FDKCUDAType*>(feldkamp.GetPointer()) );\n#else\n std::cerr << \"The program has not been compiled with cuda option\" << std::endl;\n return EXIT_FAILURE;\n#endif\n }\n else if(!strcmp(args_info.hardware_arg, \"opencl\") )\n {\n#if OPENCL_FOUND\n feldkamp = FDKOPENCLType::New();\n SET_FELDKAMP_OPTIONS( static_cast<FDKOPENCLType*>(feldkamp.GetPointer()) );\n#else\n std::cerr << \"The program has not been compiled with opencl option\" << std::endl;\n return EXIT_FAILURE;\n#endif\n }\n\n\n \/\/ Streaming depending on streaming capability of writer\n typedef itk::StreamingImageFilter<OutputImageType, OutputImageType> StreamerType;\n StreamerType::Pointer streamerBP = StreamerType::New();\n streamerBP->SetInput( feldkamp->GetOutput() );\n streamerBP->SetNumberOfStreamDivisions( args_info.divisions_arg );\n\n \/\/ Write\n typedef itk::ImageFileWriter< OutputImageType > WriterType;\n WriterType::Pointer writer = WriterType::New();\n writer->SetFileName( args_info.output_arg );\n writer->SetInput( streamerBP->GetOutput() );\n\n if(args_info.verbose_flag)\n std::cout << \"Reconstructing and writing... \" << std::flush;\n itk::TimeProbe writerProbe;\n\n writerProbe.Start();\n TRY_AND_EXIT_ON_ITK_EXCEPTION( writer->Update() );\n writerProbe.Stop();\n\n if(args_info.verbose_flag)\n {\n std::cout << \"It took \" << writerProbe.GetMeanTime() << ' ' << readerProbe.GetUnit() << std::endl;\n if(!strcmp(args_info.hardware_arg, \"cpu\") )\n static_cast<FDKCPUType* >(feldkamp.GetPointer())->PrintTiming(std::cout);\n#if CUDA_FOUND\n else if(!strcmp(args_info.hardware_arg, \"cuda\") )\n static_cast<FDKCUDAType*>(feldkamp.GetPointer())->PrintTiming(std::cout);\n#endif\n#if OPENCL_FOUND\n else if(!strcmp(args_info.hardware_arg, \"opencl\") )\n static_cast<FDKOPENCLType*>(feldkamp.GetPointer())->PrintTiming(std::cout);\n#endif\n }\n\n return EXIT_SUCCESS;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (C) 2010-2013 Joshua Boyce.\r\n\/\/ See the file COPYING for copying permission.\r\n\r\n#include <string>\r\n#include <iterator>\r\n\r\n#include <windows.h>\r\n#include <winnt.h>\r\n#include <winternl.h>\r\n\r\n#include <hadesmem\/config.hpp>\r\n#include <hadesmem\/detail\/winternl.hpp>\r\n#include <hadesmem\/find_procedure.hpp>\r\n#include <hadesmem\/module.hpp>\r\n#include <hadesmem\/patcher.hpp>\r\n#include <hadesmem\/process.hpp>\r\n\r\n\/\/ TODO: Write a test app to exercise all the hooked APIs and information\r\n\/\/ classes.\r\n\r\nnamespace winternl = hadesmem::detail::winternl;\r\n\r\nstd::unique_ptr<hadesmem::Process> g_process;\r\n\r\nstd::unique_ptr<hadesmem::PatchDetour> g_nt_query_system_information_hk;\r\n\r\nclass SystemProcessInformationEnum\r\n{\r\npublic:\r\n explicit SystemProcessInformationEnum(\r\n winternl::SYSTEM_INFORMATION_CLASS info_class,\r\n void* buffer) HADESMEM_DETAIL_NOEXCEPT\r\n : buffer_(GetRealBuffer(info_class, buffer)),\r\n prev_(nullptr),\r\n info_class_(info_class),\r\n unlinked_(false)\r\n {\r\n HADESMEM_DETAIL_ASSERT(buffer_);\r\n HADESMEM_DETAIL_ASSERT(\r\n info_class == winternl::SystemProcessInformation ||\r\n info_class == winternl::SystemExtendedProcessInformation ||\r\n info_class == winternl::SystemSessionProcessInformation ||\r\n info_class == winternl::SystemFullProcessInformation);\r\n }\r\n\r\n SystemProcessInformationEnum(SystemProcessInformationEnum const&) = delete;\r\n\r\n SystemProcessInformationEnum& operator=(SystemProcessInformationEnum const&) =\r\n delete;\r\n\r\n void Advance() HADESMEM_DETAIL_NOEXCEPT\r\n {\r\n if (!unlinked_)\r\n {\r\n prev_ = buffer_;\r\n }\r\n\r\n unlinked_ = false;\r\n\r\n if (buffer_->NextEntryOffset)\r\n {\r\n buffer_ = reinterpret_cast<winternl::SYSTEM_PROCESS_INFORMATION*>(\r\n reinterpret_cast<DWORD_PTR>(buffer_) + buffer_->NextEntryOffset);\r\n }\r\n else\r\n {\r\n buffer_ = nullptr;\r\n }\r\n }\r\n\r\n bool Valid() const HADESMEM_DETAIL_NOEXCEPT\r\n {\r\n return buffer_ != nullptr;\r\n }\r\n\r\n void Unlink() HADESMEM_DETAIL_NOEXCEPT\r\n {\r\n HADESMEM_DETAIL_ASSERT(buffer_);\r\n\r\n HADESMEM_DETAIL_ASSERT(!unlinked_);\r\n\r\n if (prev_)\r\n {\r\n if (buffer_->NextEntryOffset)\r\n {\r\n prev_->NextEntryOffset += buffer_->NextEntryOffset;\r\n }\r\n else\r\n {\r\n prev_->NextEntryOffset = 0UL;\r\n }\r\n\r\n unlinked_ = true;\r\n }\r\n else\r\n {\r\n \/\/ Unlinking the first process is unsupported.\r\n HADESMEM_DETAIL_ASSERT(false);\r\n }\r\n }\r\n\r\n bool HasName() const HADESMEM_DETAIL_NOEXCEPT\r\n {\r\n return buffer_->ImageName.Buffer != nullptr && buffer_->ImageName.Length;\r\n }\r\n\r\n \/\/ TODO: Remove dependency on std::wstring, we shouldn't need to allocate\n \/\/ and copy here. This should be a noexcept function returning a range over\n \/\/ the existing string buffer.\r\n std::wstring GetName() const\r\n {\r\n auto const str_end =\r\n std::find(buffer_->ImageName.Buffer,\n buffer_->ImageName.Buffer + buffer_->ImageName.Length,\n L'\\0');\r\n \/\/ SystemFullProcessInformation returns the full path rather than just the\n \/\/ image name.\r\n if (info_class_ == winternl::SystemFullProcessInformation)\r\n {\r\n auto const name_beg =\n std::find(std::reverse_iterator<wchar_t*>(str_end),\n std::reverse_iterator<wchar_t*>(buffer_->ImageName.Buffer),\n L'\\\\');\r\n return {name_beg.base(), str_end};\r\n }\r\n else\r\n {\r\n return {buffer_->ImageName.Buffer, str_end};\r\n }\r\n }\r\n\r\nprivate:\r\n winternl::SYSTEM_PROCESS_INFORMATION*\r\n GetRealBuffer(winternl::SYSTEM_INFORMATION_CLASS info_class,\r\n void* buffer) const HADESMEM_DETAIL_NOEXCEPT\r\n {\r\n if (info_class == winternl::SystemProcessInformation ||\r\n info_class == winternl::SystemExtendedProcessInformation ||\r\n info_class == winternl::SystemFullProcessInformation)\r\n {\r\n return static_cast<winternl::SYSTEM_PROCESS_INFORMATION*>(buffer);\r\n }\r\n else if (info_class == winternl::SystemSessionProcessInformation)\r\n {\r\n return static_cast<winternl::SYSTEM_PROCESS_INFORMATION*>(\r\n static_cast<winternl::SYSTEM_SESSION_PROCESS_INFORMATION*>(buffer)\r\n ->Buffer);\r\n }\r\n else\r\n {\r\n HADESMEM_DETAIL_ASSERT(false);\r\n return nullptr;\r\n }\r\n }\r\n\r\n winternl::SYSTEM_PROCESS_INFORMATION* buffer_;\r\n winternl::SYSTEM_PROCESS_INFORMATION* prev_;\r\n winternl::SYSTEM_INFORMATION_CLASS info_class_;\r\n bool unlinked_;\r\n};\r\n\r\n\/\/ TODO: Preserve LastError value.\r\nextern \"C\" NTSTATUS WINAPI NtQuerySystemInformationHk(\r\n winternl::SYSTEM_INFORMATION_CLASS system_information_class,\r\n PVOID system_information,\r\n ULONG system_information_length,\r\n PULONG return_length) HADESMEM_DETAIL_NOEXCEPT\r\n{\r\n HADESMEM_DETAIL_TRACE_FORMAT_A(\"Args: [%d] [%p] [%u] [%p].\",\r\n system_information_class,\r\n system_information,\r\n system_information_length,\r\n return_length);\r\n auto const nt_query_system_information =\r\n g_nt_query_system_information_hk\r\n ->GetTrampoline<decltype(&NtQuerySystemInformationHk)>();\r\n auto const ret = nt_query_system_information(system_information_class,\r\n system_information,\r\n system_information_length,\r\n return_length);\r\n HADESMEM_DETAIL_TRACE_FORMAT_A(\"Ret: [%ld].\", ret);\r\n\r\n \/\/ TODO: Handle SystemProcessIdInformation (88).\r\n if (system_information_class != winternl::SystemProcessInformation &&\r\n system_information_class != winternl::SystemExtendedProcessInformation &&\r\n system_information_class != winternl::SystemSessionProcessInformation &&\r\n system_information_class != winternl::SystemFullProcessInformation)\r\n {\r\n HADESMEM_DETAIL_TRACE_A(\"Unhandled information class.\");\r\n return ret;\r\n }\r\n\r\n if (!NT_SUCCESS(ret))\r\n {\r\n HADESMEM_DETAIL_TRACE_A(\"Trampoline returned failure.\");\r\n return ret;\r\n }\r\n\r\n try\r\n {\r\n HADESMEM_DETAIL_TRACE_A(\"Enumerating processes.\");\r\n for (SystemProcessInformationEnum process_info{system_information_class,\r\n system_information};\r\n process_info.Valid();\r\n process_info.Advance())\r\n {\r\n if (process_info.HasName())\r\n {\r\n auto const process_name = process_info.GetName();\r\n HADESMEM_DETAIL_TRACE_FORMAT_W(L\"Name: [%s].\", process_name.c_str());\r\n if (process_name == L\"hades.exe\")\r\n {\r\n HADESMEM_DETAIL_TRACE_A(\"Unlinking process.\");\r\n process_info.Unlink();\r\n }\r\n }\r\n else\r\n {\r\n HADESMEM_DETAIL_TRACE_A(\"WARNING! Invalid name.\");\r\n }\r\n }\r\n }\r\n catch (...)\r\n {\r\n HADESMEM_DETAIL_TRACE_A(\r\n boost::current_exception_diagnostic_information().c_str());\r\n HADESMEM_DETAIL_ASSERT(false);\r\n }\r\n\r\n return ret;\r\n}\r\n\r\nextern \"C\" HADESMEM_DETAIL_DLLEXPORT DWORD_PTR Load() HADESMEM_DETAIL_NOEXCEPT\r\n{\r\n try\r\n {\r\n g_process.reset(new hadesmem::Process(::GetCurrentProcessId()));\r\n hadesmem::Module const ntdll(*g_process, L\"ntdll.dll\");\r\n auto const nt_query_system_information =\r\n hadesmem::FindProcedure(*g_process, ntdll, \"NtQuerySystemInformation\");\r\n auto const nt_query_system_information_ptr =\r\n hadesmem::detail::UnionCast<void*>(nt_query_system_information);\r\n auto const nt_query_system_information_hk =\r\n hadesmem::detail::UnionCast<void*>(&NtQuerySystemInformationHk);\r\n g_nt_query_system_information_hk.reset(\r\n new hadesmem::PatchDetour(*g_process,\r\n nt_query_system_information_ptr,\r\n nt_query_system_information_hk));\r\n g_nt_query_system_information_hk->Apply();\r\n HADESMEM_DETAIL_TRACE_A(\"NtQuerySystemInformationHk hooked.\");\r\n }\r\n catch (...)\r\n {\r\n HADESMEM_DETAIL_TRACE_A(\r\n boost::current_exception_diagnostic_information().c_str());\r\n HADESMEM_DETAIL_ASSERT(false);\r\n }\r\n\r\n return 0;\r\n}\r\n\r\n\/\/ TODO: Safe unhooking and unloading.\r\nextern \"C\" HADESMEM_DETAIL_DLLEXPORT DWORD_PTR Free() HADESMEM_DETAIL_NOEXCEPT\r\n{\r\n return 0;\r\n}\r\n\r\nBOOL WINAPI\r\n DllMain(HINSTANCE \/*instance*\/, DWORD \/*reason*\/, LPVOID \/*reserved*\/)\r\n{\r\n return TRUE;\r\n}\r\n<commit_msg>* [Cerberus] Remove TODO because it's easier to just copy the string than deal with all the nonsense of non-null-terminated strings, string length extending past the null, etc.<commit_after>\/\/ Copyright (C) 2010-2013 Joshua Boyce.\r\n\/\/ See the file COPYING for copying permission.\r\n\r\n#include <string>\r\n#include <iterator>\r\n\r\n#include <windows.h>\r\n#include <winnt.h>\r\n#include <winternl.h>\r\n\r\n#include <hadesmem\/config.hpp>\r\n#include <hadesmem\/detail\/winternl.hpp>\r\n#include <hadesmem\/find_procedure.hpp>\r\n#include <hadesmem\/module.hpp>\r\n#include <hadesmem\/patcher.hpp>\r\n#include <hadesmem\/process.hpp>\r\n\r\n\/\/ TODO: Write a test app to exercise all the hooked APIs and information\r\n\/\/ classes.\r\n\r\nnamespace winternl = hadesmem::detail::winternl;\r\n\r\nstd::unique_ptr<hadesmem::Process> g_process;\r\n\r\nstd::unique_ptr<hadesmem::PatchDetour> g_nt_query_system_information_hk;\r\n\r\nclass SystemProcessInformationEnum\r\n{\r\npublic:\r\n explicit SystemProcessInformationEnum(\r\n winternl::SYSTEM_INFORMATION_CLASS info_class,\r\n void* buffer) HADESMEM_DETAIL_NOEXCEPT\r\n : buffer_(GetRealBuffer(info_class, buffer)),\r\n prev_(nullptr),\r\n info_class_(info_class),\r\n unlinked_(false)\r\n {\r\n HADESMEM_DETAIL_ASSERT(buffer_);\r\n HADESMEM_DETAIL_ASSERT(\r\n info_class == winternl::SystemProcessInformation ||\r\n info_class == winternl::SystemExtendedProcessInformation ||\r\n info_class == winternl::SystemSessionProcessInformation ||\r\n info_class == winternl::SystemFullProcessInformation);\r\n }\r\n\r\n SystemProcessInformationEnum(SystemProcessInformationEnum const&) = delete;\r\n\r\n SystemProcessInformationEnum& operator=(SystemProcessInformationEnum const&) =\r\n delete;\r\n\r\n void Advance() HADESMEM_DETAIL_NOEXCEPT\r\n {\r\n if (!unlinked_)\r\n {\r\n prev_ = buffer_;\r\n }\r\n\r\n unlinked_ = false;\r\n\r\n if (buffer_->NextEntryOffset)\r\n {\r\n buffer_ = reinterpret_cast<winternl::SYSTEM_PROCESS_INFORMATION*>(\r\n reinterpret_cast<DWORD_PTR>(buffer_) + buffer_->NextEntryOffset);\r\n }\r\n else\r\n {\r\n buffer_ = nullptr;\r\n }\r\n }\r\n\r\n bool Valid() const HADESMEM_DETAIL_NOEXCEPT\r\n {\r\n return buffer_ != nullptr;\r\n }\r\n\r\n void Unlink() HADESMEM_DETAIL_NOEXCEPT\r\n {\r\n HADESMEM_DETAIL_ASSERT(buffer_);\r\n\r\n HADESMEM_DETAIL_ASSERT(!unlinked_);\r\n\r\n if (prev_)\r\n {\r\n if (buffer_->NextEntryOffset)\r\n {\r\n prev_->NextEntryOffset += buffer_->NextEntryOffset;\r\n }\r\n else\r\n {\r\n prev_->NextEntryOffset = 0UL;\r\n }\r\n\r\n unlinked_ = true;\r\n }\r\n else\r\n {\r\n \/\/ Unlinking the first process is unsupported.\r\n HADESMEM_DETAIL_ASSERT(false);\r\n }\r\n }\r\n\r\n bool HasName() const HADESMEM_DETAIL_NOEXCEPT\r\n {\r\n return buffer_->ImageName.Buffer != nullptr && buffer_->ImageName.Length;\r\n }\r\n\r\n std::wstring GetName() const\r\n {\r\n auto const str_end =\r\n std::find(buffer_->ImageName.Buffer,\n buffer_->ImageName.Buffer + buffer_->ImageName.Length,\n L'\\0');\r\n \/\/ SystemFullProcessInformation returns the full path rather than just the\n \/\/ image name.\r\n if (info_class_ == winternl::SystemFullProcessInformation)\r\n {\r\n auto const name_beg =\n std::find(std::reverse_iterator<wchar_t*>(str_end),\n std::reverse_iterator<wchar_t*>(buffer_->ImageName.Buffer),\n L'\\\\');\r\n return {name_beg.base(), str_end};\r\n }\r\n else\r\n {\r\n return {buffer_->ImageName.Buffer, str_end};\r\n }\r\n }\r\n\r\nprivate:\r\n winternl::SYSTEM_PROCESS_INFORMATION*\r\n GetRealBuffer(winternl::SYSTEM_INFORMATION_CLASS info_class,\r\n void* buffer) const HADESMEM_DETAIL_NOEXCEPT\r\n {\r\n if (info_class == winternl::SystemProcessInformation ||\r\n info_class == winternl::SystemExtendedProcessInformation ||\r\n info_class == winternl::SystemFullProcessInformation)\r\n {\r\n return static_cast<winternl::SYSTEM_PROCESS_INFORMATION*>(buffer);\r\n }\r\n else if (info_class == winternl::SystemSessionProcessInformation)\r\n {\r\n return static_cast<winternl::SYSTEM_PROCESS_INFORMATION*>(\r\n static_cast<winternl::SYSTEM_SESSION_PROCESS_INFORMATION*>(buffer)\r\n ->Buffer);\r\n }\r\n else\r\n {\r\n HADESMEM_DETAIL_ASSERT(false);\r\n return nullptr;\r\n }\r\n }\r\n\r\n winternl::SYSTEM_PROCESS_INFORMATION* buffer_;\r\n winternl::SYSTEM_PROCESS_INFORMATION* prev_;\r\n winternl::SYSTEM_INFORMATION_CLASS info_class_;\r\n bool unlinked_;\r\n};\r\n\r\n\/\/ TODO: Preserve LastError value.\r\nextern \"C\" NTSTATUS WINAPI NtQuerySystemInformationHk(\r\n winternl::SYSTEM_INFORMATION_CLASS system_information_class,\r\n PVOID system_information,\r\n ULONG system_information_length,\r\n PULONG return_length) HADESMEM_DETAIL_NOEXCEPT\r\n{\r\n HADESMEM_DETAIL_TRACE_FORMAT_A(\"Args: [%d] [%p] [%u] [%p].\",\r\n system_information_class,\r\n system_information,\r\n system_information_length,\r\n return_length);\r\n auto const nt_query_system_information =\r\n g_nt_query_system_information_hk\r\n ->GetTrampoline<decltype(&NtQuerySystemInformationHk)>();\r\n auto const ret = nt_query_system_information(system_information_class,\r\n system_information,\r\n system_information_length,\r\n return_length);\r\n HADESMEM_DETAIL_TRACE_FORMAT_A(\"Ret: [%ld].\", ret);\r\n\r\n \/\/ TODO: Handle SystemProcessIdInformation (88).\r\n if (system_information_class != winternl::SystemProcessInformation &&\r\n system_information_class != winternl::SystemExtendedProcessInformation &&\r\n system_information_class != winternl::SystemSessionProcessInformation &&\r\n system_information_class != winternl::SystemFullProcessInformation)\r\n {\r\n HADESMEM_DETAIL_TRACE_A(\"Unhandled information class.\");\r\n return ret;\r\n }\r\n\r\n if (!NT_SUCCESS(ret))\r\n {\r\n HADESMEM_DETAIL_TRACE_A(\"Trampoline returned failure.\");\r\n return ret;\r\n }\r\n\r\n try\r\n {\r\n HADESMEM_DETAIL_TRACE_A(\"Enumerating processes.\");\r\n for (SystemProcessInformationEnum process_info{system_information_class,\r\n system_information};\r\n process_info.Valid();\r\n process_info.Advance())\r\n {\r\n if (process_info.HasName())\r\n {\r\n auto const process_name = process_info.GetName();\r\n HADESMEM_DETAIL_TRACE_FORMAT_W(L\"Name: [%s].\", process_name.c_str());\r\n if (process_name == L\"hades.exe\")\r\n {\r\n HADESMEM_DETAIL_TRACE_A(\"Unlinking process.\");\r\n process_info.Unlink();\r\n }\r\n }\r\n else\r\n {\r\n HADESMEM_DETAIL_TRACE_A(\"WARNING! Invalid name.\");\r\n }\r\n }\r\n }\r\n catch (...)\r\n {\r\n HADESMEM_DETAIL_TRACE_A(\r\n boost::current_exception_diagnostic_information().c_str());\r\n HADESMEM_DETAIL_ASSERT(false);\r\n }\r\n\r\n return ret;\r\n}\r\n\r\nextern \"C\" HADESMEM_DETAIL_DLLEXPORT DWORD_PTR Load() HADESMEM_DETAIL_NOEXCEPT\r\n{\r\n try\r\n {\r\n g_process.reset(new hadesmem::Process(::GetCurrentProcessId()));\r\n hadesmem::Module const ntdll(*g_process, L\"ntdll.dll\");\r\n auto const nt_query_system_information =\r\n hadesmem::FindProcedure(*g_process, ntdll, \"NtQuerySystemInformation\");\r\n auto const nt_query_system_information_ptr =\r\n hadesmem::detail::UnionCast<void*>(nt_query_system_information);\r\n auto const nt_query_system_information_hk =\r\n hadesmem::detail::UnionCast<void*>(&NtQuerySystemInformationHk);\r\n g_nt_query_system_information_hk.reset(\r\n new hadesmem::PatchDetour(*g_process,\r\n nt_query_system_information_ptr,\r\n nt_query_system_information_hk));\r\n g_nt_query_system_information_hk->Apply();\r\n HADESMEM_DETAIL_TRACE_A(\"NtQuerySystemInformationHk hooked.\");\r\n }\r\n catch (...)\r\n {\r\n HADESMEM_DETAIL_TRACE_A(\r\n boost::current_exception_diagnostic_information().c_str());\r\n HADESMEM_DETAIL_ASSERT(false);\r\n }\r\n\r\n return 0;\r\n}\r\n\r\n\/\/ TODO: Safe unhooking and unloading.\r\nextern \"C\" HADESMEM_DETAIL_DLLEXPORT DWORD_PTR Free() HADESMEM_DETAIL_NOEXCEPT\r\n{\r\n return 0;\r\n}\r\n\r\nBOOL WINAPI\r\n DllMain(HINSTANCE \/*instance*\/, DWORD \/*reason*\/, LPVOID \/*reserved*\/)\r\n{\r\n return TRUE;\r\n}\r\n<|endoftext|>"} {"text":"<commit_before>\/***************************************************************\n *\n * Copyright (C) 1990-2012, Condor Team, Computer Sciences Department,\n * University of Wisconsin-Madison, WI.\n * \n * Licensed under the Apache License, Version 2.0 (the \"License\"); you\n * may not use this file except in compliance with the License. You may\n * obtain a copy of the License at\n * \n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n ***************************************************************\/\n\n#include \"condor_common.h\"\n#include \"condor_debug.h\"\n#include \"backward_file_reader.h\"\n\n\nBackwardFileReader::BWReaderBuffer::BWReaderBuffer(int cb\/*=0*\/, char * input \/* = NULL*\/)\n\t: data(input)\n\t, cbData(cb)\n\t, cbAlloc(cb)\n\t, at_eof(false)\n\t, text_mode(false)\n\t, error(0)\n{\n\tif (input) {\n\t\tcbAlloc = cbData = cb;\n\t} else if (cb > 0) {\n\t\tdata = (char*)malloc(cb);\n\t\tif (data) memset(data, 17, cb);\n\t\tcbData = 0;\n\t}\n}\n\nvoid BackwardFileReader::BWReaderBuffer::setsize(int cb)\n{\n\tcbData = cb; \n\tASSERT(cbData <= cbAlloc);\n}\n\nbool BackwardFileReader::BWReaderBuffer::reserve(int cb)\n{\n\tif (data && cbAlloc >= cb)\n\t\treturn true;\n\n\tvoid * pv = realloc(data, cb);\n\tif (pv) {\n\t\tdata = (char*)pv;\n\t\tcbAlloc = cb;\n\t\treturn true;\n\t}\n\treturn false;\n}\n\nint BackwardFileReader::BWReaderBuffer::fread_at(FILE * file, off_t offset, int cb)\n{\n\tif ( ! reserve(((cb + 16) & ~15) + 16))\n\t\treturn 0;\n\n\tfseek(file, offset, SEEK_SET);\n\n\tint ret = (int)fread(data, 1, cb, file);\n\tcbData = ret;\n\n\tif (ret <= 0) {\n\t\terror = ferror(file);\n\t\treturn 0;\n\t} else {\n\t\terror = 0;\n\t}\n\n\t\/\/ on windows in text mode we can consume more than we read because of \\r\n\t\/\/ but since we are scanning backward this can cause us to re-read\n\t\/\/ the same bytes more than once. So lop off the end of the buffer so\n\t\/\/ so we only get back the unique bytes\n\tat_eof = feof(file);\n\tif (text_mode && ! at_eof) {\n\t\toff_t end_offset = ftell(file);\n\t\tint extra = (int)(end_offset - (offset + ret));\n\t\tret -= extra;\n\t}\n\n\tif (ret < cbAlloc) {\n\t\tdata[ret] = 0; \/\/ force null terminate.\n\t} else {\n\t\t\/\/ this should NOT happen\n\t\tEXCEPT(\"BWReadBuffer is unexpectedly too small!\");\n\t}\n\n\treturn ret;\n}\n\n\nBackwardFileReader::BackwardFileReader(std::string filename, int open_flags)\n\t: error(0), file(NULL), cbFile(0), cbPos(0) \n{\n#ifdef WIN32\n\topen_flags |= O_BINARY;\n#endif\n\tint fd = safe_open_wrapper_follow(filename.c_str(), open_flags);\n\tif (fd < 0)\n\t\terror = errno;\n\telse if ( ! OpenFile(fd, \"rb\"))\n\t\tclose(fd);\n}\n\nBackwardFileReader::BackwardFileReader(int fd, const char * open_options)\n\t: error(0), file(NULL), cbFile(0), cbPos(0) \n{\n\tOpenFile(fd, open_options);\n}\n\/*\nBackwardFileReader::~BackwardFileReader()\n{\n\tif (file) fclose(file);\n\tfile = NULL;\n}\n*\/\n\nbool BackwardFileReader::PrevLine(std::string & str)\n{\n\tstr.clear();\n\n\t\/\/ can we get a previous line out of our existing buffer?\n\t\/\/ then do that.\n\tif (PrevLineFromBuf(str))\n\t\treturn true;\n\n\t\/\/ no line in the buffer? then return false\n\tif (AtBOF())\n\t\treturn false;\n\n\tconst int cbBack = 512;\n\twhile (true) {\n\t\tint off = cbPos > cbBack ? cbPos - cbBack : 0;\n\t\tint cbToRead = (int)(cbPos - off);\n\n\t\t\/\/ we want to read in cbBack chunks at cbBack aligment, of course\n\t\t\/\/ this only makes sense to do if cbBack is a power of 2. \n\t\t\/\/ also, in order to get EOF to register, we have to read a little \n\t\t\/\/ so we may want the first read (from the end, of course) to be a bit \n\t\t\/\/ larger than cbBack so that we read at least cbBack but also end up\n\t\t\/\/ on cbBack alignment. \n\t\tif (cbFile == cbPos) {\n\t\t\t\/\/ test to see if cbBack is a power of 2, if it is, then set our\n\t\t\t\/\/ seek to align on cbBack.\n\t\t\tif (!(cbBack & (cbBack-1))) {\n\t\t\t\t\/\/ seek to an even multiple of cbBack at least cbBack from the end of the file.\n\t\t\t\toff = (cbFile - cbBack) & ~(cbBack-1);\n\t\t\t\tcbToRead = cbFile - off;\n\t\t\t}\n\t\t\tcbToRead += 16;\n\t\t}\n\n\t\tif ( ! buf.fread_at(file, off, cbToRead)) {\n\t\t\tif (buf.LastError()) {\n\t\t\t\terror = buf.LastError();\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\n\t\tcbPos = off;\n\n\t\t\/\/ try again to get some data from the buffer\n\t\tif (PrevLineFromBuf(str) || AtBOF())\n\t\t\treturn true;\n\t}\n}\n\nbool BackwardFileReader::OpenFile(int fd, const char * open_options)\n{\n\tfile = fdopen(fd, open_options);\n\tif ( ! file) {\n\t\terror = errno;\n\t} else {\n\t\t\/\/ seek to the end of the file.\n\t\tfseek(file, 0, SEEK_END);\n\t\tcbFile = cbPos = ftell(file);\n\t\terror = 0;\n\t\tbuf.SetTextMode( ! strchr(open_options,'b'));\n\t}\n\treturn error == 0;\n}\n\n\/\/ prefixes or part of a line into str, and updates internal\n\/\/ variables to keep track of what parts of the buffer have been returned.\nbool BackwardFileReader::PrevLineFromBuf(std::string & str)\n{\n\t\/\/ if we have no buffered data, then there is nothing to do\n\tint cb = buf.size();\n\tif (cb <= 0)\n\t\treturn false;\n\n\t\/\/ if buffer ends in a newline, convert it to a \\0\n\tif (buf[cb-1] == '\\n') {\n\t\tbuf[--cb] = 0;\n\t\t\/\/ if the input string is not empty, then the previous\n\t\t\/\/ buffer ended _exactly_ at a newline boundary, so return\n\t\t\/\/ the string rather than concatinating it to the newline.\n\t\tif ( ! str.empty()) {\n\t\t\tif (buf[cb-1] == '\\r')\n\t\t\t\tbuf[--cb] = 0;\n\t\t\tbuf.setsize(cb);\n\t\t\treturn true;\n\t\t}\n\t}\n\t\/\/ because of windows style \\r\\n, we also tolerate a \\r at the end of the line\n\tif (buf[cb-1] == '\\r') {\n\t\tbuf[--cb] = 0;\n\t}\n\n\t\/\/ now we walk backward through the buffer until we encounter another newline\n\t\/\/ returning all of the characters that we found.\n\twhile (cb > 0) {\n\t\tif (buf[--cb] == '\\n') {\n\t\t\tstr.insert(0, &buf[cb+1]);\n\t\t\tbuf[cb] = 0;\n\t\t\tbuf.setsize(cb);\n\t\t\treturn true;\n\t\t}\n\t}\n\n\t\/\/ we hit the start of the buffer without finding another newline,\n\t\/\/ so return that text, but only return true if we are also at the start\n\t\/\/ of the file.\n\tstr.insert(0, &buf[0]);\n\tbuf[0] = 0;\n\tbuf.clear();\n\n\treturn (0 == cbPos);\n}\n<commit_msg>Always check return value of fseek #6345<commit_after>\/***************************************************************\n *\n * Copyright (C) 1990-2012, Condor Team, Computer Sciences Department,\n * University of Wisconsin-Madison, WI.\n * \n * Licensed under the Apache License, Version 2.0 (the \"License\"); you\n * may not use this file except in compliance with the License. You may\n * obtain a copy of the License at\n * \n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n ***************************************************************\/\n\n#include \"condor_common.h\"\n#include \"condor_debug.h\"\n#include \"backward_file_reader.h\"\n\n\nBackwardFileReader::BWReaderBuffer::BWReaderBuffer(int cb\/*=0*\/, char * input \/* = NULL*\/)\n\t: data(input)\n\t, cbData(cb)\n\t, cbAlloc(cb)\n\t, at_eof(false)\n\t, text_mode(false)\n\t, error(0)\n{\n\tif (input) {\n\t\tcbAlloc = cbData = cb;\n\t} else if (cb > 0) {\n\t\tdata = (char*)malloc(cb);\n\t\tif (data) memset(data, 17, cb);\n\t\tcbData = 0;\n\t}\n}\n\nvoid BackwardFileReader::BWReaderBuffer::setsize(int cb)\n{\n\tcbData = cb; \n\tASSERT(cbData <= cbAlloc);\n}\n\nbool BackwardFileReader::BWReaderBuffer::reserve(int cb)\n{\n\tif (data && cbAlloc >= cb)\n\t\treturn true;\n\n\tvoid * pv = realloc(data, cb);\n\tif (pv) {\n\t\tdata = (char*)pv;\n\t\tcbAlloc = cb;\n\t\treturn true;\n\t}\n\treturn false;\n}\n\nint BackwardFileReader::BWReaderBuffer::fread_at(FILE * file, off_t offset, int cb)\n{\n\tif ( ! reserve(((cb + 16) & ~15) + 16))\n\t\treturn 0;\n\n\tint ret = fseek(file, offset, SEEK_SET);\n\tif (ret <= 0) {\n\t\terror = ferror(file);\n\t\treturn 0;\n\t} else {\n\t\terror = 0;\n\t}\n\n\tret = (int)fread(data, 1, cb, file);\n\tcbData = ret;\n\n\tif (ret <= 0) {\n\t\terror = ferror(file);\n\t\treturn 0;\n\t} else {\n\t\terror = 0;\n\t}\n\n\t\/\/ on windows in text mode we can consume more than we read because of \\r\n\t\/\/ but since we are scanning backward this can cause us to re-read\n\t\/\/ the same bytes more than once. So lop off the end of the buffer so\n\t\/\/ so we only get back the unique bytes\n\tat_eof = feof(file);\n\tif (text_mode && ! at_eof) {\n\t\toff_t end_offset = ftell(file);\n\t\tint extra = (int)(end_offset - (offset + ret));\n\t\tret -= extra;\n\t}\n\n\tif (ret < cbAlloc) {\n\t\tdata[ret] = 0; \/\/ force null terminate.\n\t} else {\n\t\t\/\/ this should NOT happen\n\t\tEXCEPT(\"BWReadBuffer is unexpectedly too small!\");\n\t}\n\n\treturn ret;\n}\n\n\nBackwardFileReader::BackwardFileReader(std::string filename, int open_flags)\n\t: error(0), file(NULL), cbFile(0), cbPos(0) \n{\n#ifdef WIN32\n\topen_flags |= O_BINARY;\n#endif\n\tint fd = safe_open_wrapper_follow(filename.c_str(), open_flags);\n\tif (fd < 0)\n\t\terror = errno;\n\telse if ( ! OpenFile(fd, \"rb\"))\n\t\tclose(fd);\n}\n\nBackwardFileReader::BackwardFileReader(int fd, const char * open_options)\n\t: error(0), file(NULL), cbFile(0), cbPos(0) \n{\n\tOpenFile(fd, open_options);\n}\n\/*\nBackwardFileReader::~BackwardFileReader()\n{\n\tif (file) fclose(file);\n\tfile = NULL;\n}\n*\/\n\nbool BackwardFileReader::PrevLine(std::string & str)\n{\n\tstr.clear();\n\n\t\/\/ can we get a previous line out of our existing buffer?\n\t\/\/ then do that.\n\tif (PrevLineFromBuf(str))\n\t\treturn true;\n\n\t\/\/ no line in the buffer? then return false\n\tif (AtBOF())\n\t\treturn false;\n\n\tconst int cbBack = 512;\n\twhile (true) {\n\t\tint off = cbPos > cbBack ? cbPos - cbBack : 0;\n\t\tint cbToRead = (int)(cbPos - off);\n\n\t\t\/\/ we want to read in cbBack chunks at cbBack aligment, of course\n\t\t\/\/ this only makes sense to do if cbBack is a power of 2. \n\t\t\/\/ also, in order to get EOF to register, we have to read a little \n\t\t\/\/ so we may want the first read (from the end, of course) to be a bit \n\t\t\/\/ larger than cbBack so that we read at least cbBack but also end up\n\t\t\/\/ on cbBack alignment. \n\t\tif (cbFile == cbPos) {\n\t\t\t\/\/ test to see if cbBack is a power of 2, if it is, then set our\n\t\t\t\/\/ seek to align on cbBack.\n\t\t\tif (!(cbBack & (cbBack-1))) {\n\t\t\t\t\/\/ seek to an even multiple of cbBack at least cbBack from the end of the file.\n\t\t\t\toff = (cbFile - cbBack) & ~(cbBack-1);\n\t\t\t\tcbToRead = cbFile - off;\n\t\t\t}\n\t\t\tcbToRead += 16;\n\t\t}\n\n\t\tif ( ! buf.fread_at(file, off, cbToRead)) {\n\t\t\tif (buf.LastError()) {\n\t\t\t\terror = buf.LastError();\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\n\t\tcbPos = off;\n\n\t\t\/\/ try again to get some data from the buffer\n\t\tif (PrevLineFromBuf(str) || AtBOF())\n\t\t\treturn true;\n\t}\n}\n\nbool BackwardFileReader::OpenFile(int fd, const char * open_options)\n{\n\tfile = fdopen(fd, open_options);\n\tif ( ! file) {\n\t\terror = errno;\n\t} else {\n\t\t\/\/ seek to the end of the file.\n\t\tfseek(file, 0, SEEK_END);\n\t\tcbFile = cbPos = ftell(file);\n\t\terror = 0;\n\t\tbuf.SetTextMode( ! strchr(open_options,'b'));\n\t}\n\treturn error == 0;\n}\n\n\/\/ prefixes or part of a line into str, and updates internal\n\/\/ variables to keep track of what parts of the buffer have been returned.\nbool BackwardFileReader::PrevLineFromBuf(std::string & str)\n{\n\t\/\/ if we have no buffered data, then there is nothing to do\n\tint cb = buf.size();\n\tif (cb <= 0)\n\t\treturn false;\n\n\t\/\/ if buffer ends in a newline, convert it to a \\0\n\tif (buf[cb-1] == '\\n') {\n\t\tbuf[--cb] = 0;\n\t\t\/\/ if the input string is not empty, then the previous\n\t\t\/\/ buffer ended _exactly_ at a newline boundary, so return\n\t\t\/\/ the string rather than concatinating it to the newline.\n\t\tif ( ! str.empty()) {\n\t\t\tif (buf[cb-1] == '\\r')\n\t\t\t\tbuf[--cb] = 0;\n\t\t\tbuf.setsize(cb);\n\t\t\treturn true;\n\t\t}\n\t}\n\t\/\/ because of windows style \\r\\n, we also tolerate a \\r at the end of the line\n\tif (buf[cb-1] == '\\r') {\n\t\tbuf[--cb] = 0;\n\t}\n\n\t\/\/ now we walk backward through the buffer until we encounter another newline\n\t\/\/ returning all of the characters that we found.\n\twhile (cb > 0) {\n\t\tif (buf[--cb] == '\\n') {\n\t\t\tstr.insert(0, &buf[cb+1]);\n\t\t\tbuf[cb] = 0;\n\t\t\tbuf.setsize(cb);\n\t\t\treturn true;\n\t\t}\n\t}\n\n\t\/\/ we hit the start of the buffer without finding another newline,\n\t\/\/ so return that text, but only return true if we are also at the start\n\t\/\/ of the file.\n\tstr.insert(0, &buf[0]);\n\tbuf[0] = 0;\n\tbuf.clear();\n\n\treturn (0 == cbPos);\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"storage_engine\/compression.h\"\n#include \"util.h\"\n\n#include <fstream>\n#include <cstdlib>\n#include <algorithm>\n#include <zlib.h>\n#include <cstring>\n\nusing namespace Akumuli;\n\nint main(int argc, char** argv) {\n if (argc == 1) {\n return 1;\n }\n std::string file_name(argv[1]);\n std::fstream input(file_name, std::ios::binary|std::ios::in|std::ios::out);\n UncompressedChunk header;\n\n double tx;\n aku_Timestamp ts;\n while(input) {\n input.read(reinterpret_cast<char*>(&ts), sizeof(ts));\n if (input) {\n input.read(reinterpret_cast<char*>(&tx), sizeof(tx));\n }\n if (input) {\n header.timestamps.push_back(ts);\n header.values.push_back(tx);\n }\n }\n\n ByteVector buffer(32 + header.timestamps.size()*32, 0);\n StorageEngine::DataBlockWriter writer(42, buffer.data(), static_cast<int>(buffer.size()));\n\n for (u32 i = 0; i < header.timestamps.size(); i++) {\n aku_Status status = writer.put(header.timestamps.at(i), header.values.at(i));\n if (status != AKU_SUCCESS) {\n AKU_PANIC(\"Can't compress data: \" + std::to_string(status));\n }\n }\n\n StorageEngine::DataBlockReader reader(buffer.data(), buffer.size());\n for (u32 i = 0; i < header.timestamps.size(); i++) {\n aku_Timestamp ts;\n double tx;\n aku_Status status;\n std::tie(status, ts, tx) = reader.next();\n if (status != AKU_SUCCESS) {\n AKU_PANIC(\"Can't decompress data: \" + std::to_string(status));\n }\n if (ts != header.timestamps.at(i)) {\n AKU_PANIC(\"Bad timestamp at: \" + std::to_string(i));\n }\n if (tx != header.values.at(i)) {\n AKU_PANIC(\"Bad value at: \" + std::to_string(i));\n }\n }\n return 0;\n}\n<commit_msg>AFL test fixed<commit_after>#include \"storage_engine\/compression.h\"\n#include \"util.h\"\n\n#include <fstream>\n#include <cstdlib>\n#include <algorithm>\n#include <zlib.h>\n#include <cstring>\n\nusing namespace Akumuli;\n\nint main(int argc, char** argv) {\n if (argc == 1) {\n return 1;\n }\n std::string file_name(argv[1]);\n std::fstream input(file_name, std::ios::binary|std::ios::in|std::ios::out);\n UncompressedChunk header;\n\n double tx;\n aku_Timestamp ts;\n while(input) {\n input.read(reinterpret_cast<char*>(&ts), sizeof(ts));\n if (input) {\n input.read(reinterpret_cast<char*>(&tx), sizeof(tx));\n }\n if (input) {\n header.timestamps.push_back(ts);\n header.values.push_back(tx);\n }\n }\n\n for (size_t i = 1; i < header.timestamps.size(); i++) {\n if (header.timestamps.at(i) < header.timestamps.at(i-1)) {\n return -1;\n }\n }\n\n ByteVector buffer(32 + header.timestamps.size()*32, 0);\n StorageEngine::DataBlockWriter writer(42, buffer.data(), static_cast<int>(buffer.size()));\n\n size_t commit_size = 0;\n for (u32 i = 0; i < header.timestamps.size(); i++) {\n aku_Status status = writer.put(header.timestamps.at(i), header.values.at(i));\n if (status != AKU_SUCCESS) {\n AKU_PANIC(\"Can't compress data: \" + std::to_string(status));\n }\n commit_size = writer.commit();\n }\n\n StorageEngine::DataBlockReader reader(buffer.data(), commit_size);\n for (u32 i = 0; i < header.timestamps.size(); i++) {\n aku_Timestamp ts;\n double tx;\n aku_Status status;\n std::tie(status, ts, tx) = reader.next();\n if (status != AKU_SUCCESS) {\n AKU_PANIC(\"Can't decompress data: \" + std::to_string(status));\n }\n if (ts != header.timestamps.at(i)) {\n AKU_PANIC(\"Bad timestamp at: \" + std::to_string(i));\n }\n if (tx != header.values.at(i)) {\n AKU_PANIC(\"Bad value at: \" + std::to_string(i));\n }\n }\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2008 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"base\/process_util.h\"\n\n#include <ctype.h>\n#include <dirent.h>\n#include <fcntl.h>\n#include <unistd.h>\n#include <string>\n#include <sys\/types.h>\n#include <sys\/wait.h>\n\n#include \"base\/file_util.h\"\n#include \"base\/logging.h\"\n#include \"base\/string_tokenizer.h\"\n#include \"base\/string_util.h\"\n\nnamespace {\n\nenum ParsingState {\n KEY_NAME,\n KEY_VALUE\n};\n\n} \/\/ namespace\n\nnamespace base {\n\nbool LaunchApp(const std::vector<std::string>& argv,\n const file_handle_mapping_vector& fds_to_remap,\n bool wait, ProcessHandle* process_handle) {\n bool retval = true;\n\n char* argv_copy[argv.size() + 1];\n for (size_t i = 0; i < argv.size(); i++) {\n argv_copy[i] = new char[argv[i].size() + 1];\n strcpy(argv_copy[i], argv[i].c_str());\n }\n argv_copy[argv.size()] = NULL;\n\n \/\/ Make sure we don't leak any FDs to the child process by marking all FDs\n \/\/ as close-on-exec.\n SetAllFDsToCloseOnExec();\n\n int pid = fork();\n if (pid == 0) {\n for (file_handle_mapping_vector::const_iterator it = fds_to_remap.begin();\n it != fds_to_remap.end();\n ++it) {\n int src_fd = it->first;\n int dest_fd = it->second;\n if (src_fd == dest_fd) {\n int flags = fcntl(src_fd, F_GETFD);\n if (flags != -1) {\n fcntl(src_fd, F_SETFD, flags & ~FD_CLOEXEC);\n }\n } else {\n dup2(src_fd, dest_fd);\n }\n }\n\n execvp(argv_copy[0], argv_copy);\n } else if (pid < 0) {\n retval = false;\n } else {\n if (wait)\n waitpid(pid, 0, 0);\n\n if (process_handle)\n *process_handle = pid;\n }\n\n for (size_t i = 0; i < argv.size(); i++)\n delete[] argv_copy[i];\n\n return retval;\n}\n\nbool LaunchApp(const CommandLine& cl,\n bool wait, bool start_hidden,\n ProcessHandle* process_handle) {\n file_handle_mapping_vector no_files;\n return LaunchApp(cl.argv(), no_files, wait, process_handle);\n}\n\nNamedProcessIterator::NamedProcessIterator(const std::wstring& executable_name,\n const ProcessFilter* filter)\n : executable_name_(executable_name), filter_(filter) {\n procfs_dir_ = opendir(\"\/proc\");\n}\n\nNamedProcessIterator::~NamedProcessIterator() {\n if (procfs_dir_) {\n closedir(procfs_dir_);\n procfs_dir_ = NULL;\n }\n}\n\nconst ProcessEntry* NamedProcessIterator::NextProcessEntry() {\n bool result = false;\n do {\n result = CheckForNextProcess();\n } while (result && !IncludeEntry());\n\n if (result)\n return &entry_;\n\n return NULL;\n}\n\nbool NamedProcessIterator::CheckForNextProcess() {\n \/\/ TODO(port): skip processes owned by different UID\n\n dirent* slot = 0;\n const char* openparen;\n const char* closeparen;\n\n \/\/ Arbitrarily guess that there will never be more than 200 non-process\n \/\/ files in \/proc. Hardy has 53.\n int skipped = 0;\n const int kSkipLimit = 200;\n while (skipped < kSkipLimit) {\n slot = readdir(procfs_dir_);\n \/\/ all done looking through \/proc?\n if (!slot)\n return false;\n\n \/\/ If not a process, keep looking for one.\n bool notprocess = false;\n int i;\n for (i = 0; i < NAME_MAX && slot->d_name[i]; ++i) {\n if (!isdigit(slot->d_name[i])) {\n notprocess = true;\n break;\n }\n }\n if (i == NAME_MAX || notprocess) {\n skipped++;\n continue;\n }\n\n \/\/ Read the process's status.\n char buf[NAME_MAX + 12];\n sprintf(buf, \"\/proc\/%s\/stat\", slot->d_name);\n FILE *fp = fopen(buf, \"r\");\n if (!fp)\n return false;\n const char* result = fgets(buf, sizeof(buf), fp);\n fclose(fp);\n if (!result)\n return false;\n\n \/\/ Parse the status. It is formatted like this:\n \/\/ %d (%s) %c %d ...\n \/\/ pid (name) runstate ppid\n \/\/ To avoid being fooled by names containing a closing paren, scan\n \/\/ backwards.\n openparen = strchr(buf, '(');\n closeparen = strrchr(buf, ')');\n if (!openparen || !closeparen)\n return false;\n char runstate = closeparen[2];\n\n \/\/ Is the process in 'Zombie' state, i.e. dead but waiting to be reaped?\n \/\/ Allowed values: D R S T Z\n if (runstate != 'Z')\n break;\n\n \/\/ Nope, it's a zombie; somebody isn't cleaning up after their children.\n \/\/ (e.g. WaitForProcessesToExit doesn't clean up after dead children yet.)\n \/\/ There could be a lot of zombies, can't really decrement i here.\n }\n if (skipped >= kSkipLimit) {\n NOTREACHED();\n return false;\n }\n\n entry_.pid = atoi(slot->d_name);\n entry_.ppid = atoi(closeparen + 3);\n\n \/\/ TODO(port): read pid's commandline's $0, like killall does. Using the\n \/\/ short name between openparen and closeparen won't work for long names!\n int len = closeparen - openparen - 1;\n if (len > NAME_MAX)\n len = NAME_MAX;\n memcpy(entry_.szExeFile, openparen + 1, len);\n entry_.szExeFile[len] = 0;\n\n return true;\n}\n\nbool NamedProcessIterator::IncludeEntry() {\n \/\/ TODO(port): make this also work for non-ASCII filenames\n if (WideToASCII(executable_name_) != entry_.szExeFile)\n return false;\n if (!filter_)\n return true;\n return filter_->Includes(entry_.pid, entry_.ppid);\n}\n\n\/\/ To have \/proc\/self\/io file you must enable CONFIG_TASK_IO_ACCOUNTING\n\/\/ in your kernel configuration.\nbool ProcessMetrics::GetIOCounters(IoCounters* io_counters) const {\n std::string proc_io_contents;\n if (!file_util::ReadFileToString(L\"\/proc\/self\/io\", &proc_io_contents))\n return false;\n\n (*io_counters).OtherOperationCount = 0;\n (*io_counters).OtherTransferCount = 0;\n\n StringTokenizer tokenizer(proc_io_contents, \": \\n\");\n ParsingState state = KEY_NAME;\n std::string last_key_name;\n while (tokenizer.GetNext()) {\n switch (state) {\n case KEY_NAME:\n last_key_name = tokenizer.token();\n state = KEY_VALUE;\n break;\n case KEY_VALUE:\n DCHECK(!last_key_name.empty());\n if (last_key_name == \"syscr\") {\n (*io_counters).ReadOperationCount = StringToInt64(tokenizer.token());\n } else if (last_key_name == \"syscw\") {\n (*io_counters).WriteOperationCount = StringToInt64(tokenizer.token());\n } else if (last_key_name == \"rchar\") {\n (*io_counters).ReadTransferCount = StringToInt64(tokenizer.token());\n } else if (last_key_name == \"wchar\") {\n (*io_counters).WriteTransferCount = StringToInt64(tokenizer.token());\n }\n state = KEY_NAME;\n break;\n }\n }\n return true;\n}\n\n} \/\/ namespace base\n<commit_msg>Cleanup in LaunchApp:<commit_after>\/\/ Copyright (c) 2008 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"base\/process_util.h\"\n\n#include <ctype.h>\n#include <dirent.h>\n#include <fcntl.h>\n#include <unistd.h>\n#include <string>\n#include <sys\/types.h>\n#include <sys\/wait.h>\n\n#include \"base\/file_util.h\"\n#include \"base\/logging.h\"\n#include \"base\/string_tokenizer.h\"\n#include \"base\/string_util.h\"\n\nnamespace {\n\nenum ParsingState {\n KEY_NAME,\n KEY_VALUE\n};\n\n} \/\/ namespace\n\nnamespace base {\n\nbool LaunchApp(const std::vector<std::string>& argv,\n const file_handle_mapping_vector& fds_to_remap,\n bool wait, ProcessHandle* process_handle) {\n \/\/ Make sure we don't leak any FDs to the child process by marking all FDs\n \/\/ as close-on-exec.\n SetAllFDsToCloseOnExec();\n\n pid_t pid = fork();\n if (pid < 0)\n return false;\n\n if (pid == 0) {\n for (file_handle_mapping_vector::const_iterator it = fds_to_remap.begin();\n it != fds_to_remap.end();\n ++it) {\n int src_fd = it->first;\n int dest_fd = it->second;\n if (src_fd == dest_fd) {\n int flags = fcntl(src_fd, F_GETFD);\n if (flags != -1) {\n fcntl(src_fd, F_SETFD, flags & ~FD_CLOEXEC);\n }\n } else {\n dup2(src_fd, dest_fd);\n }\n }\n\n char* argv_cstr[argv.size() + 1];\n for (size_t i = 0; i < argv.size(); i++)\n argv_cstr[i] = const_cast<char*>(argv[i].c_str());\n argv_cstr[argv.size()] = NULL;\n execvp(argv_cstr[0], argv_cstr);\n exit(127);\n } else {\n if (wait)\n waitpid(pid, 0, 0);\n\n if (process_handle)\n *process_handle = pid;\n }\n\n return true;\n}\n\nbool LaunchApp(const CommandLine& cl,\n bool wait, bool start_hidden,\n ProcessHandle* process_handle) {\n file_handle_mapping_vector no_files;\n return LaunchApp(cl.argv(), no_files, wait, process_handle);\n}\n\nNamedProcessIterator::NamedProcessIterator(const std::wstring& executable_name,\n const ProcessFilter* filter)\n : executable_name_(executable_name), filter_(filter) {\n procfs_dir_ = opendir(\"\/proc\");\n}\n\nNamedProcessIterator::~NamedProcessIterator() {\n if (procfs_dir_) {\n closedir(procfs_dir_);\n procfs_dir_ = NULL;\n }\n}\n\nconst ProcessEntry* NamedProcessIterator::NextProcessEntry() {\n bool result = false;\n do {\n result = CheckForNextProcess();\n } while (result && !IncludeEntry());\n\n if (result)\n return &entry_;\n\n return NULL;\n}\n\nbool NamedProcessIterator::CheckForNextProcess() {\n \/\/ TODO(port): skip processes owned by different UID\n\n dirent* slot = 0;\n const char* openparen;\n const char* closeparen;\n\n \/\/ Arbitrarily guess that there will never be more than 200 non-process\n \/\/ files in \/proc. Hardy has 53.\n int skipped = 0;\n const int kSkipLimit = 200;\n while (skipped < kSkipLimit) {\n slot = readdir(procfs_dir_);\n \/\/ all done looking through \/proc?\n if (!slot)\n return false;\n\n \/\/ If not a process, keep looking for one.\n bool notprocess = false;\n int i;\n for (i = 0; i < NAME_MAX && slot->d_name[i]; ++i) {\n if (!isdigit(slot->d_name[i])) {\n notprocess = true;\n break;\n }\n }\n if (i == NAME_MAX || notprocess) {\n skipped++;\n continue;\n }\n\n \/\/ Read the process's status.\n char buf[NAME_MAX + 12];\n sprintf(buf, \"\/proc\/%s\/stat\", slot->d_name);\n FILE *fp = fopen(buf, \"r\");\n if (!fp)\n return false;\n const char* result = fgets(buf, sizeof(buf), fp);\n fclose(fp);\n if (!result)\n return false;\n\n \/\/ Parse the status. It is formatted like this:\n \/\/ %d (%s) %c %d ...\n \/\/ pid (name) runstate ppid\n \/\/ To avoid being fooled by names containing a closing paren, scan\n \/\/ backwards.\n openparen = strchr(buf, '(');\n closeparen = strrchr(buf, ')');\n if (!openparen || !closeparen)\n return false;\n char runstate = closeparen[2];\n\n \/\/ Is the process in 'Zombie' state, i.e. dead but waiting to be reaped?\n \/\/ Allowed values: D R S T Z\n if (runstate != 'Z')\n break;\n\n \/\/ Nope, it's a zombie; somebody isn't cleaning up after their children.\n \/\/ (e.g. WaitForProcessesToExit doesn't clean up after dead children yet.)\n \/\/ There could be a lot of zombies, can't really decrement i here.\n }\n if (skipped >= kSkipLimit) {\n NOTREACHED();\n return false;\n }\n\n entry_.pid = atoi(slot->d_name);\n entry_.ppid = atoi(closeparen + 3);\n\n \/\/ TODO(port): read pid's commandline's $0, like killall does. Using the\n \/\/ short name between openparen and closeparen won't work for long names!\n int len = closeparen - openparen - 1;\n if (len > NAME_MAX)\n len = NAME_MAX;\n memcpy(entry_.szExeFile, openparen + 1, len);\n entry_.szExeFile[len] = 0;\n\n return true;\n}\n\nbool NamedProcessIterator::IncludeEntry() {\n \/\/ TODO(port): make this also work for non-ASCII filenames\n if (WideToASCII(executable_name_) != entry_.szExeFile)\n return false;\n if (!filter_)\n return true;\n return filter_->Includes(entry_.pid, entry_.ppid);\n}\n\n\/\/ To have \/proc\/self\/io file you must enable CONFIG_TASK_IO_ACCOUNTING\n\/\/ in your kernel configuration.\nbool ProcessMetrics::GetIOCounters(IoCounters* io_counters) const {\n std::string proc_io_contents;\n if (!file_util::ReadFileToString(L\"\/proc\/self\/io\", &proc_io_contents))\n return false;\n\n (*io_counters).OtherOperationCount = 0;\n (*io_counters).OtherTransferCount = 0;\n\n StringTokenizer tokenizer(proc_io_contents, \": \\n\");\n ParsingState state = KEY_NAME;\n std::string last_key_name;\n while (tokenizer.GetNext()) {\n switch (state) {\n case KEY_NAME:\n last_key_name = tokenizer.token();\n state = KEY_VALUE;\n break;\n case KEY_VALUE:\n DCHECK(!last_key_name.empty());\n if (last_key_name == \"syscr\") {\n (*io_counters).ReadOperationCount = StringToInt64(tokenizer.token());\n } else if (last_key_name == \"syscw\") {\n (*io_counters).WriteOperationCount = StringToInt64(tokenizer.token());\n } else if (last_key_name == \"rchar\") {\n (*io_counters).ReadTransferCount = StringToInt64(tokenizer.token());\n } else if (last_key_name == \"wchar\") {\n (*io_counters).WriteTransferCount = StringToInt64(tokenizer.token());\n }\n state = KEY_NAME;\n break;\n }\n }\n return true;\n}\n\n} \/\/ namespace base\n<|endoftext|>"} {"text":"<commit_before>\/*\n *\n * Copyright (c) 2021 Project CHIP Authors\n * All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include <app\/clusters\/ota-requestor\/OTADownloader.h>\n#include <app\/clusters\/ota-requestor\/OTARequestorInterface.h>\n\n#include \"OTAImageProcessorImpl.h\"\n\n#include <sys\/stat.h>\n\nnamespace chip {\n\nCHIP_ERROR OTAImageProcessorImpl::PrepareDownload()\n{\n if (mImageFile == nullptr)\n {\n ChipLogError(SoftwareUpdate, \"Invalid output image file supplied\");\n return CHIP_ERROR_INTERNAL;\n }\n\n DeviceLayer::PlatformMgr().ScheduleWork(HandlePrepareDownload, reinterpret_cast<intptr_t>(this));\n return CHIP_NO_ERROR;\n}\n\nCHIP_ERROR OTAImageProcessorImpl::Finalize()\n{\n DeviceLayer::PlatformMgr().ScheduleWork(HandleFinalize, reinterpret_cast<intptr_t>(this));\n return CHIP_NO_ERROR;\n}\n\nCHIP_ERROR OTAImageProcessorImpl::Apply()\n{\n DeviceLayer::PlatformMgr().ScheduleWork(HandleApply, reinterpret_cast<intptr_t>(this));\n return CHIP_NO_ERROR;\n}\n\nCHIP_ERROR OTAImageProcessorImpl::Abort()\n{\n if (mImageFile == nullptr)\n {\n ChipLogError(SoftwareUpdate, \"Invalid output image file supplied\");\n return CHIP_ERROR_INTERNAL;\n }\n\n DeviceLayer::PlatformMgr().ScheduleWork(HandleAbort, reinterpret_cast<intptr_t>(this));\n return CHIP_NO_ERROR;\n}\n\nCHIP_ERROR OTAImageProcessorImpl::ProcessBlock(ByteSpan & block)\n{\n if (!mOfs.is_open() || !mOfs.good())\n {\n return CHIP_ERROR_INTERNAL;\n }\n\n if ((block.data() == nullptr) || block.empty())\n {\n return CHIP_ERROR_INVALID_ARGUMENT;\n }\n\n \/\/ Store block data for HandleProcessBlock to access\n CHIP_ERROR err = SetBlock(block);\n if (err != CHIP_NO_ERROR)\n {\n ChipLogError(SoftwareUpdate, \"Cannot set block data: %\" CHIP_ERROR_FORMAT, err.Format());\n }\n\n DeviceLayer::PlatformMgr().ScheduleWork(HandleProcessBlock, reinterpret_cast<intptr_t>(this));\n return CHIP_NO_ERROR;\n}\n\nbool OTAImageProcessorImpl::IsFirstImageRun()\n{\n OTARequestorInterface * requestor = chip::GetRequestorInstance();\n if (requestor == nullptr)\n {\n return false;\n }\n\n return requestor->GetCurrentUpdateState() == OTARequestorInterface::OTAUpdateStateEnum::kApplying;\n}\n\nCHIP_ERROR OTAImageProcessorImpl::ConfirmCurrentImage()\n{\n OTARequestorInterface * requestor = chip::GetRequestorInstance();\n if (requestor == nullptr)\n {\n return CHIP_ERROR_INTERNAL;\n }\n\n uint32_t currentVersion;\n uint32_t targetVersion = requestor->GetTargetVersion();\n ReturnErrorOnFailure(DeviceLayer::ConfigurationMgr().GetSoftwareVersion(currentVersion));\n if (currentVersion != targetVersion)\n {\n ChipLogError(SoftwareUpdate, \"Current software version = %\" PRIu32 \", expected software version = %\" PRIu32, currentVersion,\n targetVersion);\n return CHIP_ERROR_INCORRECT_STATE;\n }\n\n return CHIP_NO_ERROR;\n}\n\nvoid OTAImageProcessorImpl::HandlePrepareDownload(intptr_t context)\n{\n auto * imageProcessor = reinterpret_cast<OTAImageProcessorImpl *>(context);\n if (imageProcessor == nullptr)\n {\n ChipLogError(SoftwareUpdate, \"ImageProcessor context is null\");\n return;\n }\n else if (imageProcessor->mDownloader == nullptr)\n {\n ChipLogError(SoftwareUpdate, \"mDownloader is null\");\n return;\n }\n\n unlink(imageProcessor->mImageFile);\n\n imageProcessor->mHeaderParser.Init();\n imageProcessor->mOfs.open(imageProcessor->mImageFile, std::ofstream::out | std::ofstream::ate | std::ofstream::app);\n if (!imageProcessor->mOfs.good())\n {\n imageProcessor->mDownloader->OnPreparedForDownload(CHIP_ERROR_OPEN_FAILED);\n return;\n }\n\n imageProcessor->mDownloader->OnPreparedForDownload(CHIP_NO_ERROR);\n}\n\nvoid OTAImageProcessorImpl::HandleFinalize(intptr_t context)\n{\n auto * imageProcessor = reinterpret_cast<OTAImageProcessorImpl *>(context);\n if (imageProcessor == nullptr)\n {\n return;\n }\n\n imageProcessor->mOfs.close();\n imageProcessor->ReleaseBlock();\n\n ChipLogProgress(SoftwareUpdate, \"OTA image downloaded to %s\", imageProcessor->mImageFile);\n}\n\nvoid OTAImageProcessorImpl::HandleApply(intptr_t context)\n{\n auto * imageProcessor = reinterpret_cast<OTAImageProcessorImpl *>(context);\n VerifyOrReturn(imageProcessor != nullptr);\n\n OTARequestorInterface * requestor = chip::GetRequestorInstance();\n VerifyOrReturn(requestor != nullptr);\n\n \/\/ Move the downloaded image to the location where the new image is to be executed from\n unlink(kImageExecPath);\n rename(imageProcessor->mImageFile, kImageExecPath);\n chmod(kImageExecPath, S_IRUSR | S_IWUSR | S_IXUSR | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH);\n\n \/\/ Shutdown the stack and expect to boot into the new image once the event loop is stopped\n DeviceLayer::PlatformMgr().ScheduleWork([](intptr_t) { DeviceLayer::PlatformMgr().HandleServerShuttingDown(); });\n DeviceLayer::PlatformMgr().ScheduleWork([](intptr_t) { DeviceLayer::PlatformMgr().StopEventLoopTask(); });\n}\n\nvoid OTAImageProcessorImpl::HandleAbort(intptr_t context)\n{\n auto * imageProcessor = reinterpret_cast<OTAImageProcessorImpl *>(context);\n if (imageProcessor == nullptr)\n {\n return;\n }\n\n imageProcessor->mOfs.close();\n unlink(imageProcessor->mImageFile);\n imageProcessor->ReleaseBlock();\n}\n\nvoid OTAImageProcessorImpl::HandleProcessBlock(intptr_t context)\n{\n auto * imageProcessor = reinterpret_cast<OTAImageProcessorImpl *>(context);\n if (imageProcessor == nullptr)\n {\n ChipLogError(SoftwareUpdate, \"ImageProcessor context is null\");\n return;\n }\n else if (imageProcessor->mDownloader == nullptr)\n {\n ChipLogError(SoftwareUpdate, \"mDownloader is null\");\n return;\n }\n\n ByteSpan block = imageProcessor->mBlock;\n CHIP_ERROR error = imageProcessor->ProcessHeader(block);\n if (error != CHIP_NO_ERROR)\n {\n ChipLogError(SoftwareUpdate, \"Image does not contain a valid header\");\n imageProcessor->mDownloader->EndDownload(CHIP_ERROR_INVALID_FILE_IDENTIFIER);\n return;\n }\n\n if (!imageProcessor->mOfs.write(reinterpret_cast<const char *>(block.data()), static_cast<std::streamsize>(block.size())))\n {\n imageProcessor->mDownloader->EndDownload(CHIP_ERROR_WRITE_FAILED);\n return;\n }\n\n imageProcessor->mParams.downloadedBytes += block.size();\n imageProcessor->mDownloader->FetchNextData();\n}\n\nCHIP_ERROR OTAImageProcessorImpl::ProcessHeader(ByteSpan & block)\n{\n if (mHeaderParser.IsInitialized())\n {\n OTAImageHeader header;\n CHIP_ERROR error = mHeaderParser.AccumulateAndDecode(block, header);\n\n \/\/ Needs more data to decode the header\n ReturnErrorCodeIf(error == CHIP_ERROR_BUFFER_TOO_SMALL, CHIP_NO_ERROR);\n ReturnErrorOnFailure(error);\n\n mParams.totalFileBytes = header.mPayloadSize;\n mHeaderParser.Clear();\n }\n\n return CHIP_NO_ERROR;\n}\n\nCHIP_ERROR OTAImageProcessorImpl::SetBlock(ByteSpan & block)\n{\n if (!IsSpanUsable(block))\n {\n ReleaseBlock();\n return CHIP_NO_ERROR;\n }\n if (mBlock.size() < block.size())\n {\n if (!mBlock.empty())\n {\n ReleaseBlock();\n }\n uint8_t * mBlock_ptr = static_cast<uint8_t *>(chip::Platform::MemoryAlloc(block.size()));\n if (mBlock_ptr == nullptr)\n {\n return CHIP_ERROR_NO_MEMORY;\n }\n mBlock = MutableByteSpan(mBlock_ptr, block.size());\n }\n CHIP_ERROR err = CopySpanToMutableSpan(block, mBlock);\n if (err != CHIP_NO_ERROR)\n {\n ChipLogError(SoftwareUpdate, \"Cannot copy block data: %\" CHIP_ERROR_FORMAT, err.Format());\n return err;\n }\n return CHIP_NO_ERROR;\n}\n\nCHIP_ERROR OTAImageProcessorImpl::ReleaseBlock()\n{\n if (mBlock.data() != nullptr)\n {\n chip::Platform::MemoryFree(mBlock.data());\n }\n\n mBlock = MutableByteSpan();\n return CHIP_NO_ERROR;\n}\n\n} \/\/ namespace chip\n<commit_msg>OTA: Fix linux BlockEOF with data length zero (#22309)<commit_after>\/*\n *\n * Copyright (c) 2021 Project CHIP Authors\n * All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include <app\/clusters\/ota-requestor\/OTADownloader.h>\n#include <app\/clusters\/ota-requestor\/OTARequestorInterface.h>\n\n#include \"OTAImageProcessorImpl.h\"\n\n#include <sys\/stat.h>\n\nnamespace chip {\n\nCHIP_ERROR OTAImageProcessorImpl::PrepareDownload()\n{\n if (mImageFile == nullptr)\n {\n ChipLogError(SoftwareUpdate, \"Invalid output image file supplied\");\n return CHIP_ERROR_INTERNAL;\n }\n\n DeviceLayer::PlatformMgr().ScheduleWork(HandlePrepareDownload, reinterpret_cast<intptr_t>(this));\n return CHIP_NO_ERROR;\n}\n\nCHIP_ERROR OTAImageProcessorImpl::Finalize()\n{\n DeviceLayer::PlatformMgr().ScheduleWork(HandleFinalize, reinterpret_cast<intptr_t>(this));\n return CHIP_NO_ERROR;\n}\n\nCHIP_ERROR OTAImageProcessorImpl::Apply()\n{\n DeviceLayer::PlatformMgr().ScheduleWork(HandleApply, reinterpret_cast<intptr_t>(this));\n return CHIP_NO_ERROR;\n}\n\nCHIP_ERROR OTAImageProcessorImpl::Abort()\n{\n if (mImageFile == nullptr)\n {\n ChipLogError(SoftwareUpdate, \"Invalid output image file supplied\");\n return CHIP_ERROR_INTERNAL;\n }\n\n DeviceLayer::PlatformMgr().ScheduleWork(HandleAbort, reinterpret_cast<intptr_t>(this));\n return CHIP_NO_ERROR;\n}\n\nCHIP_ERROR OTAImageProcessorImpl::ProcessBlock(ByteSpan & block)\n{\n if (!mOfs.is_open() || !mOfs.good())\n {\n return CHIP_ERROR_INTERNAL;\n }\n\n \/\/ Store block data for HandleProcessBlock to access\n CHIP_ERROR err = SetBlock(block);\n if (err != CHIP_NO_ERROR)\n {\n ChipLogError(SoftwareUpdate, \"Cannot set block data: %\" CHIP_ERROR_FORMAT, err.Format());\n }\n\n DeviceLayer::PlatformMgr().ScheduleWork(HandleProcessBlock, reinterpret_cast<intptr_t>(this));\n return CHIP_NO_ERROR;\n}\n\nbool OTAImageProcessorImpl::IsFirstImageRun()\n{\n OTARequestorInterface * requestor = chip::GetRequestorInstance();\n if (requestor == nullptr)\n {\n return false;\n }\n\n return requestor->GetCurrentUpdateState() == OTARequestorInterface::OTAUpdateStateEnum::kApplying;\n}\n\nCHIP_ERROR OTAImageProcessorImpl::ConfirmCurrentImage()\n{\n OTARequestorInterface * requestor = chip::GetRequestorInstance();\n if (requestor == nullptr)\n {\n return CHIP_ERROR_INTERNAL;\n }\n\n uint32_t currentVersion;\n uint32_t targetVersion = requestor->GetTargetVersion();\n ReturnErrorOnFailure(DeviceLayer::ConfigurationMgr().GetSoftwareVersion(currentVersion));\n if (currentVersion != targetVersion)\n {\n ChipLogError(SoftwareUpdate, \"Current software version = %\" PRIu32 \", expected software version = %\" PRIu32, currentVersion,\n targetVersion);\n return CHIP_ERROR_INCORRECT_STATE;\n }\n\n return CHIP_NO_ERROR;\n}\n\nvoid OTAImageProcessorImpl::HandlePrepareDownload(intptr_t context)\n{\n auto * imageProcessor = reinterpret_cast<OTAImageProcessorImpl *>(context);\n if (imageProcessor == nullptr)\n {\n ChipLogError(SoftwareUpdate, \"ImageProcessor context is null\");\n return;\n }\n else if (imageProcessor->mDownloader == nullptr)\n {\n ChipLogError(SoftwareUpdate, \"mDownloader is null\");\n return;\n }\n\n unlink(imageProcessor->mImageFile);\n\n imageProcessor->mHeaderParser.Init();\n imageProcessor->mOfs.open(imageProcessor->mImageFile, std::ofstream::out | std::ofstream::ate | std::ofstream::app);\n if (!imageProcessor->mOfs.good())\n {\n imageProcessor->mDownloader->OnPreparedForDownload(CHIP_ERROR_OPEN_FAILED);\n return;\n }\n\n imageProcessor->mDownloader->OnPreparedForDownload(CHIP_NO_ERROR);\n}\n\nvoid OTAImageProcessorImpl::HandleFinalize(intptr_t context)\n{\n auto * imageProcessor = reinterpret_cast<OTAImageProcessorImpl *>(context);\n if (imageProcessor == nullptr)\n {\n return;\n }\n\n imageProcessor->mOfs.close();\n imageProcessor->ReleaseBlock();\n\n ChipLogProgress(SoftwareUpdate, \"OTA image downloaded to %s\", imageProcessor->mImageFile);\n}\n\nvoid OTAImageProcessorImpl::HandleApply(intptr_t context)\n{\n auto * imageProcessor = reinterpret_cast<OTAImageProcessorImpl *>(context);\n VerifyOrReturn(imageProcessor != nullptr);\n\n OTARequestorInterface * requestor = chip::GetRequestorInstance();\n VerifyOrReturn(requestor != nullptr);\n\n \/\/ Move the downloaded image to the location where the new image is to be executed from\n unlink(kImageExecPath);\n rename(imageProcessor->mImageFile, kImageExecPath);\n chmod(kImageExecPath, S_IRUSR | S_IWUSR | S_IXUSR | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH);\n\n \/\/ Shutdown the stack and expect to boot into the new image once the event loop is stopped\n DeviceLayer::PlatformMgr().ScheduleWork([](intptr_t) { DeviceLayer::PlatformMgr().HandleServerShuttingDown(); });\n DeviceLayer::PlatformMgr().ScheduleWork([](intptr_t) { DeviceLayer::PlatformMgr().StopEventLoopTask(); });\n}\n\nvoid OTAImageProcessorImpl::HandleAbort(intptr_t context)\n{\n auto * imageProcessor = reinterpret_cast<OTAImageProcessorImpl *>(context);\n if (imageProcessor == nullptr)\n {\n return;\n }\n\n imageProcessor->mOfs.close();\n unlink(imageProcessor->mImageFile);\n imageProcessor->ReleaseBlock();\n}\n\nvoid OTAImageProcessorImpl::HandleProcessBlock(intptr_t context)\n{\n auto * imageProcessor = reinterpret_cast<OTAImageProcessorImpl *>(context);\n if (imageProcessor == nullptr)\n {\n ChipLogError(SoftwareUpdate, \"ImageProcessor context is null\");\n return;\n }\n else if (imageProcessor->mDownloader == nullptr)\n {\n ChipLogError(SoftwareUpdate, \"mDownloader is null\");\n return;\n }\n\n ByteSpan block = imageProcessor->mBlock;\n CHIP_ERROR error = imageProcessor->ProcessHeader(block);\n if (error != CHIP_NO_ERROR)\n {\n ChipLogError(SoftwareUpdate, \"Image does not contain a valid header\");\n imageProcessor->mDownloader->EndDownload(CHIP_ERROR_INVALID_FILE_IDENTIFIER);\n return;\n }\n\n if (!imageProcessor->mOfs.write(reinterpret_cast<const char *>(block.data()), static_cast<std::streamsize>(block.size())))\n {\n imageProcessor->mDownloader->EndDownload(CHIP_ERROR_WRITE_FAILED);\n return;\n }\n\n imageProcessor->mParams.downloadedBytes += block.size();\n imageProcessor->mDownloader->FetchNextData();\n}\n\nCHIP_ERROR OTAImageProcessorImpl::ProcessHeader(ByteSpan & block)\n{\n if (mHeaderParser.IsInitialized())\n {\n OTAImageHeader header;\n CHIP_ERROR error = mHeaderParser.AccumulateAndDecode(block, header);\n\n \/\/ Needs more data to decode the header\n ReturnErrorCodeIf(error == CHIP_ERROR_BUFFER_TOO_SMALL, CHIP_NO_ERROR);\n ReturnErrorOnFailure(error);\n\n mParams.totalFileBytes = header.mPayloadSize;\n mHeaderParser.Clear();\n }\n\n return CHIP_NO_ERROR;\n}\n\nCHIP_ERROR OTAImageProcessorImpl::SetBlock(ByteSpan & block)\n{\n if (!IsSpanUsable(block))\n {\n ReleaseBlock();\n return CHIP_NO_ERROR;\n }\n if (mBlock.size() < block.size())\n {\n if (!mBlock.empty())\n {\n ReleaseBlock();\n }\n uint8_t * mBlock_ptr = static_cast<uint8_t *>(chip::Platform::MemoryAlloc(block.size()));\n if (mBlock_ptr == nullptr)\n {\n return CHIP_ERROR_NO_MEMORY;\n }\n mBlock = MutableByteSpan(mBlock_ptr, block.size());\n }\n CHIP_ERROR err = CopySpanToMutableSpan(block, mBlock);\n if (err != CHIP_NO_ERROR)\n {\n ChipLogError(SoftwareUpdate, \"Cannot copy block data: %\" CHIP_ERROR_FORMAT, err.Format());\n return err;\n }\n return CHIP_NO_ERROR;\n}\n\nCHIP_ERROR OTAImageProcessorImpl::ReleaseBlock()\n{\n if (mBlock.data() != nullptr)\n {\n chip::Platform::MemoryFree(mBlock.data());\n }\n\n mBlock = MutableByteSpan();\n return CHIP_NO_ERROR;\n}\n\n} \/\/ namespace chip\n<|endoftext|>"} {"text":"<commit_before>\/*\n For more information, please see: http:\/\/software.sci.utah.edu\n\n The MIT License\n\n Copyright (c) 2009 Scientific Computing and Imaging Institute,\n University of Utah.\n\n \n Permission is hereby granted, free of charge, to any person obtaining a\n copy of this software and associated documentation files (the \"Software\"),\n to deal in the Software without restriction, including without limitation\n the rights to use, copy, modify, merge, publish, distribute, sublicense,\n and\/or sell copies of the Software, and to permit persons to whom the\n Software is furnished to do so, subject to the following conditions:\n\n The above copyright notice and this permission notice shall be included\n in all copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n DEALINGS IN THE SOFTWARE.\n*\/\n\n#include <Core\/Algorithms\/Legacy\/Fields\/TransformMesh\/AlignMeshBoundingBoxes.h>\n\n#include <Core\/GeometryPrimitives\/Transform.h>\n\n#include <Core\/Datatypes\/Legacy\/Field\/Field.h>\n#include <Core\/Datatypes\/Legacy\/Field\/VField.h>\n#include <Core\/Datatypes\/Legacy\/Field\/VMesh.h>\n#include <Core\/Datatypes\/DenseMatrix.h>\n\nusing namespace SCIRun;\nusing namespace SCIRun::Core::Datatypes;\nusing namespace SCIRun::Core::Algorithms::Fields;\nusing namespace SCIRun::Core::Geometry;\nusing namespace SCIRun::Core::Utility;\nusing namespace SCIRun::Core::Algorithms;\n\nAlgorithmParameterName AlignMeshBoundingBoxesAlgo::RotateData(\"rotate_data\");\n\nAlignMeshBoundingBoxesAlgo::AlignMeshBoundingBoxesAlgo()\n{\n addParameter(RotateData, true);\n}\n\nbool \nAlignMeshBoundingBoxesAlgo::run(FieldHandle input, FieldHandle object, FieldHandle& output, MatrixHandle& transform_matrix)\n{\n ScopedAlgorithmStatusReporter asr(this, \"AlignMeshBoundingBoxes\");\n \n bool rotate_data = get(RotateData).getBool();\n \/\/ Step 0:\n \/\/ Safety test:\n \/\/ Test whether we received actually a field. A handle can point to no object.\n \/\/ Using a null handle will cause the program to crash. Hence it is a good\n \/\/ policy to check all incoming handles and to see whether they point to actual\n \/\/ objects.\n \n if (!input)\n {\n error(\"No input field\");\n return (false);\n }\n\n \/\/ Copy the field\n output.reset(input->deep_clone());\n \n BBox obbox = object->vmesh()->get_bounding_box();\n BBox ibbox = input->vmesh()->get_bounding_box();\n \n Transform transform;\n \n Vector iscale = ibbox.diagonal();\n Vector oscale = obbox.diagonal();\n Vector itrans(-ibbox.min());\n Vector otrans(obbox.min());\n transform.pre_translate(itrans);\n transform.pre_scale(Vector(oscale.x()\/iscale.x(),oscale.y()\/iscale.y(),oscale.z()\/iscale.z()));\n transform.pre_translate(otrans);\n \n output->vmesh()->transform(transform);\n\n VField* field = output->vfield();\n if (field->is_vector() || field->is_tensor())\n {\n if (rotate_data)\n {\n if (field->is_vector())\n {\n VMesh::size_type sz = field->num_values();\n for (VMesh::index_type i=0; i < sz; i++)\n {\n Vector v;\n field->get_value(v,i);\n v = transform*v;\n field->set_value(v,i);\n }\n }\n if (field->is_tensor())\n {\n VMesh::size_type sz = field->num_values();\n for (VMesh::index_type i=0; i < sz; i++)\n {\n Tensor v;\n field->get_value(v,i);\n v = transform*v*transform;\n field->set_value(v,i);\n }\n } \n }\n }\n\n transform_matrix.reset(new DenseMatrix(transform));\n \n if (!transform_matrix)\n {\n error(\"Could not allocate transform matrix\");\n return (false); \n }\n \n#ifdef SCIRUN4_CODE_TO_BE_ENABLED_LATER\n \/\/! Copy properties of the property manager\n\toutput->copy_properties(input);\n#endif\n \n \/\/ Success:\n return (true);\n}\n\nAlgorithmOutput AlignMeshBoundingBoxesAlgo::run_generic(const AlgorithmInput& input) const\n{\n \/\/get input values\n\n FieldHandle output;\n MatrixHandle transform;\n if (!run(input, object, output, transform))\n THROW_ALGORITHM_PROCESSING_ERROR(\"False returned on legacy run call.\");\n\n AlgorithmOutput output;\n \/\/set output values\n return output;\n}\n<commit_msg>Get\/Set input\/output<commit_after>\/*\n For more information, please see: http:\/\/software.sci.utah.edu\n\n The MIT License\n\n Copyright (c) 2009 Scientific Computing and Imaging Institute,\n University of Utah.\n\n \n Permission is hereby granted, free of charge, to any person obtaining a\n copy of this software and associated documentation files (the \"Software\"),\n to deal in the Software without restriction, including without limitation\n the rights to use, copy, modify, merge, publish, distribute, sublicense,\n and\/or sell copies of the Software, and to permit persons to whom the\n Software is furnished to do so, subject to the following conditions:\n\n The above copyright notice and this permission notice shall be included\n in all copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n DEALINGS IN THE SOFTWARE.\n*\/\n\n#include <Core\/Algorithms\/Legacy\/Fields\/TransformMesh\/AlignMeshBoundingBoxes.h>\n\n#include <Core\/GeometryPrimitives\/Transform.h>\n\n#include <Core\/Datatypes\/Legacy\/Field\/Field.h>\n#include <Core\/Datatypes\/Legacy\/Field\/VField.h>\n#include <Core\/Datatypes\/Legacy\/Field\/VMesh.h>\n#include <Core\/Datatypes\/DenseMatrix.h>\n\nusing namespace SCIRun;\nusing namespace SCIRun::Core::Datatypes;\nusing namespace SCIRun::Core::Algorithms::Fields;\nusing namespace SCIRun::Core::Geometry;\nusing namespace SCIRun::Core::Utility;\nusing namespace SCIRun::Core::Algorithms;\n\nAlgorithmParameterName AlignMeshBoundingBoxesAlgo::RotateData(\"rotate_data\");\n\nAlignMeshBoundingBoxesAlgo::AlignMeshBoundingBoxesAlgo()\n{\n addParameter(RotateData, true);\n}\n\nbool \nAlignMeshBoundingBoxesAlgo::run(FieldHandle input, FieldHandle object, FieldHandle& output, MatrixHandle& transform_matrix)\n{\n ScopedAlgorithmStatusReporter asr(this, \"AlignMeshBoundingBoxes\");\n \n bool rotate_data = get(RotateData).getBool();\n \/\/ Step 0:\n \/\/ Safety test:\n \/\/ Test whether we received actually a field. A handle can point to no object.\n \/\/ Using a null handle will cause the program to crash. Hence it is a good\n \/\/ policy to check all incoming handles and to see whether they point to actual\n \/\/ objects.\n \n if (!input)\n {\n error(\"No input field\");\n return (false);\n }\n\n \/\/ Copy the field\n output.reset(input->deep_clone());\n \n BBox obbox = object->vmesh()->get_bounding_box();\n BBox ibbox = input->vmesh()->get_bounding_box();\n \n Transform transform;\n \n Vector iscale = ibbox.diagonal();\n Vector oscale = obbox.diagonal();\n Vector itrans(-ibbox.min());\n Vector otrans(obbox.min());\n transform.pre_translate(itrans);\n transform.pre_scale(Vector(oscale.x()\/iscale.x(),oscale.y()\/iscale.y(),oscale.z()\/iscale.z()));\n transform.pre_translate(otrans);\n \n output->vmesh()->transform(transform);\n\n VField* field = output->vfield();\n if (field->is_vector() || field->is_tensor())\n {\n if (rotate_data)\n {\n if (field->is_vector())\n {\n VMesh::size_type sz = field->num_values();\n for (VMesh::index_type i=0; i < sz; i++)\n {\n Vector v;\n field->get_value(v,i);\n v = transform*v;\n field->set_value(v,i);\n }\n }\n if (field->is_tensor())\n {\n VMesh::size_type sz = field->num_values();\n for (VMesh::index_type i=0; i < sz; i++)\n {\n Tensor v;\n field->get_value(v,i);\n v = transform*v*transform;\n field->set_value(v,i);\n }\n } \n }\n }\n\n transform_matrix.reset(new DenseMatrix(transform));\n \n if (!transform_matrix)\n {\n error(\"Could not allocate transform matrix\");\n return (false); \n }\n \n#ifdef SCIRUN4_CODE_TO_BE_ENABLED_LATER\n \/\/! Copy properties of the property manager\n\toutput->copy_properties(input);\n#endif\n \n \/\/ Success:\n return (true);\n}\n\nAlgorithmOutput AlignMeshBoundingBoxesAlgo::run_generic(const AlgorithmInput& input) const\n{\n auto inputField = input.get<Field>(InputField);\n auto object = input.get<Field>(ObjectField);\n\n FieldHandle output;\n MatrixHandle transform;\n if (!run(inputField, object, output, transform))\n THROW_ALGORITHM_PROCESSING_ERROR(\"False returned on legacy run call.\");\n\n AlgorithmOutput output;\n output[OutputField] = output;\n output[TransformMatrix] = transform;\n return output;\n}\n<|endoftext|>"} {"text":"<commit_before>\n\/*\n\n passiveLocationPush\n\n Example app using samsonClient lib\n It generates random xml documents simulating information from OSS Passive Location pilot\n\n AUTHOR: Andreu Urruela\n\n *\/\n\n\n#include <stdio.h> \/\/ printf\n#include <stdlib.h> \/\/ exit\n#include <string.h> \/\/ memcpy\n#include <iostream> \/\/ std::cout\n#include <time.h> \/\/ strptime, struct tm\n\n\n#include \"au\/time.h\" \/\/ au::todatString()\n#include \"au\/string.h\" \/\/ au::str()\n#include \"au\/Cronometer.h\" \/\/ au::Cronometer\n#include \"au\/CommandLine.h\" \/\/ au::CommandLine\n\n#include \"samson\/client\/SamsonClient.h\" \/\/ samson::SamsonClient\n\nint main( int argc , const char *argv[] )\n{\n\tif ( argc < 2 )\n\t{\n\t fprintf(stderr,\"Usage %s rate_in_messages_per_second\\n\", argv[0] );\n\t\texit(0);\n\t}\n\n\tsize_t rate = atoll( argv[1] );\n\n\t\/\/ Small mini-buffer to generate\n\tchar *line = (char*) malloc( 20000 );\n\n\t\/\/ Control of time and size\n\tau::Cronometer cronometer;\n\n\tsize_t total_size = 0;\n\tsize_t num_messages = 0;\n\n\tsize_t theoretical_seconds = 0;\n\n\twhile( true )\n\t{\n\t \/\/ Generat 5 seconds data\n\t fprintf(stderr,\"Generatoing %d messages\\n\", (int)(5 * rate) );\n\t for( int i = 0 ; i < (int)(5 * rate); i++)\n\t {\n\t\t\tsize_t user_id = rand()%10000;\n\t\t\tint cell = rand()%20000;\n\n\t\t\tsnprintf( line, 20000 , \"<?xml version=\\\"1.0\\\" encoding=\\\"UTF-8\\\"?><ns0:AMRReport xmlns:xsi='http:\/\/www.w3.org\/2001\/XMLSchema-instance' xmlns:ns0='http:\/\/O2.arcanum.vitria.com' xsi:schemaLocation='http:\/\/O2.arcanum.vitria.com AMR.xsd'> <SubscriberReport> <User> <IMSI>%lu<\/IMSI> <PTMSI>FB869371<\/PTMSI> <CellID>%d<\/CellID> <Paging> <Location> <LocationArea>12124<\/LocationArea> <RoutingArea>134<\/RoutingArea> <\/Location> <\/Paging> <\/SubscriberReport> <Timestamp>2011-07-21T16:07:47<\/Timestamp><\/ns0:AMRReport>\" , user_id , cell );\n\n\t\ttotal_size += strlen(line);\n\t\tnum_messages++;\n\n\n\t\t\/\/ Emit line to the output\n\t\tstd::cout << line << \"\\n\";\n\n\t }\n\n\t\t\/\/ Detect if we need to sleep....\n\t\ttheoretical_seconds += 5;\n\n\t\tsize_t ellapsed_seconds = cronometer.diffTimeInSeconds();\n\n\t\t\/\/ Sleep some time to simulate a particular rate\n\t\tif( ellapsed_seconds < theoretical_seconds )\n\t\t{\n\t\t\tint sleep_seconds = theoretical_seconds - ellapsed_seconds;\n\t\t\tstd::cerr << \"Sleeping \" << sleep_seconds << \" seconds... num messages \" << au::str(num_messages) << \" size \" << au::str( total_size , \"bytes\") << \" time \" << au::time_string(ellapsed_seconds) << \" theoretical time \" << au::time_string(theoretical_seconds)<<\"\\n\";\n\t\t\tsleep( sleep_seconds );\n\t\t}\n\n\t}\n\n}\n\n<commit_msg>Minor update in generating fake passive location data<commit_after>\n\/*\n\n passiveLocationPush\n\n Example app using samsonClient lib\n It generates random xml documents simulating information from OSS Passive Location pilot\n\n AUTHOR: Andreu Urruela\n\n *\/\n\n\n#include <stdio.h> \/\/ printf\n#include <stdlib.h> \/\/ exit\n#include <string.h> \/\/ memcpy\n#include <iostream> \/\/ std::cout\n#include <time.h> \/\/ strptime, struct tm\n\n\n#include \"au\/time.h\" \/\/ au::todatString()\n#include \"au\/string.h\" \/\/ au::str()\n#include \"au\/Cronometer.h\" \/\/ au::Cronometer\n#include \"au\/CommandLine.h\" \/\/ au::CommandLine\n\n#include \"samson\/client\/SamsonClient.h\" \/\/ samson::SamsonClient\n\nint main( int argc , const char *argv[] )\n{\n\tif ( argc < 2 )\n\t{\n\t fprintf(stderr,\"Usage %s rate_in_messages_per_second\\n\", argv[0] );\n\t\texit(0);\n\t}\n\n\tsize_t rate = atoll( argv[1] );\n\tsize_t max_kvs = 0;\n\tif( argc > 2 )\n\t max_kvs = atoll( argv[2] );\n\n\t\/\/ Small mini-buffer to generate\n\tchar *line = (char*) malloc( 20000 );\n\n\t\/\/ Control of time and size\n\tau::Cronometer cronometer;\n\n\tsize_t total_size = 0;\n\tsize_t num_messages = 0;\n\n\tsize_t theoretical_seconds = 0;\n\n\twhile( true )\n\t{\n\t \/\/ Generat 5 seconds data\n\t fprintf(stderr,\"Generatoing %d messages\\n\", (int)(5 * rate) );\n\t for( int i = 0 ; i < (int)(5 * rate); i++)\n\t {\n\t\t\tsize_t user_id = rand()%10000;\n\t\t\tint cell = rand()%20000;\n\n\t\t\tsnprintf( line, 20000 , \"<?xml version=\\\"1.0\\\" encoding=\\\"UTF-8\\\"?><ns0:AMRReport xmlns:xsi='http:\/\/www.w3.org\/2001\/XMLSchema-instance' xmlns:ns0='http:\/\/O2.arcanum.vitria.com' xsi:schemaLocation='http:\/\/O2.arcanum.vitria.com AMR.xsd'> <SubscriberReport> <User> <IMSI>%lu<\/IMSI> <PTMSI>FB869371<\/PTMSI> <CellID>%d<\/CellID> <Paging> <Location> <LocationArea>12124<\/LocationArea> <RoutingArea>134<\/RoutingArea> <\/Location> <\/Paging> <\/SubscriberReport> <Timestamp>2011-07-21T16:07:47<\/Timestamp><\/ns0:AMRReport>\" , user_id , cell );\n\n\t\ttotal_size += strlen(line);\n\t\tnum_messages++;\n\n\n\t\t\/\/ Emit line to the output\n\t\tstd::cout << line << \"\\n\";\n\n\t }\n\n\t if( max_kvs > 0 )\n\t if( num_messages > max_kvs )\n\t {\n\t\t fprintf(stderr,\"Finish since a limit of %lu kvs was specified. Generated %lu key-vaue\\n\", max_kvs ,num_messages);\n\n\t\t return 0;\n\t }\n\n\t\t\/\/ Detect if we need to sleep....\n\t\ttheoretical_seconds += 5;\n\n\t\tsize_t ellapsed_seconds = cronometer.diffTimeInSeconds();\n\n\t\t\/\/ Sleep some time to simulate a particular rate\n\t\tif( ellapsed_seconds < theoretical_seconds )\n\t\t{\n\t\t\tint sleep_seconds = theoretical_seconds - ellapsed_seconds;\n\t\t\tstd::cerr << \"Sleeping \" << sleep_seconds << \" seconds... num messages \" << au::str(num_messages) << \" size \" << au::str( total_size , \"bytes\") << \" time \" << au::time_string(ellapsed_seconds) << \" theoretical time \" << au::time_string(theoretical_seconds)<<\"\\n\";\n\t\t\tsleep( sleep_seconds );\n\t\t}\n\n\t}\n\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ niihdr.cpp\n\/\/ NiftiImage\n\/\/\n\/\/ Created by Tobias Wood on 08\/07\/2013.\n\/\/ Copyright (c) 2013 Tobias Wood. All rights reserved.\n\/\/\n\n#include <memory>\n#include <vector>\n#include <iostream>\n#include <getopt.h>\n\n#include \"Nifti\/Nifti.h\"\n\nusing namespace std;\n\nconst string usage = \"niihdr - A utility for getting information from Nifti headers.\\n\\\n\\n\\\nUsage: niihdr [options] file1 [other files]\\n\\\nBy default the abbreviated header will be printed for each file.\\n\\\nAbbreviated, full and compare modes are mutually exclusive.\\n\\\n\\n\\\nOptions:\\n\\\n\t-a, --abbrev: Print the abbreviated header (default).\\n\\\n\t-f, --full: Print the entire header.\\n\\\n\t-c, --comp: Compare first file to all others and print message if the.\\n\\\n\t physical spaces are different.\\n\\\n\t-h, --help: Print this message and quit.\\n\\\n\";\n\nenum class Mode { Abbrev, Full, Cmp };\n\nstatic Mode mode = Mode::Abbrev;\n\nstatic struct option long_options[] = {\n\t{\"abbrev\", no_argument, 0, 'a'},\n\t{\"full\", no_argument, 0, 'f'},\n\t{\"comp\", no_argument, 0, 'c'},\n\t{\"help\", no_argument, 0, 'h'},\n\t{0, 0, 0, 0}\n};\n\nint main(int argc, char **argv) {\n\tint indexptr = 0, c;\n\twhile ((c = getopt_long(argc, argv, \"afch\", long_options, &indexptr)) != -1) {\n\t\tswitch (c) {\n\t\t\tcase 'a': mode = Mode::Abbrev; break;\n\t\t\tcase 'f': mode = Mode::Full; break;\n\t\t\tcase 'c': mode = Mode::Cmp; break;\n\t\t\tcase '?': \/\/ getopt will print an error message\n\t\t\tcase 'h':\n\t\t\t\tcout << usage << endl;\n\t\t\t\treturn EXIT_FAILURE;\n\t\t}\n\t}\n\tif ((argc - optind) <= 0 ) {\n\t\tcerr << \"No input image file specified.\" << endl;\n\t\tcout << usage << endl;\n\t\treturn EXIT_FAILURE;\n\t}\n\tvector<Nifti::File> images;\n\ttry {\n\t\timages.reserve(argc - optind); \/\/ emplace_back can still trigger copies if the vector has to be resized\n\t\tfor (;optind < argc; optind++) {\n\t\t\timages.emplace_back(argv[optind]);\n\t\t}\n\t} catch (exception &e) {\n\t\tcerr << e.what() << endl;\n\t}\n\n\tsize_t did_not_match = 0;\n\tif (mode == Mode::Cmp) { \/\/ Compare first image to all others and check headers are compatible\n\t\tcout << \"Checking headers against: \" << images[0].headerPath() << endl;\n\t\tfor (auto im = images.begin() + 1; im != images.end(); im++) {\n\t\t\tif (!images[0].header().matchesSpace(im->header())) {\n\t\t\t\tcout << im->headerPath() << \" does not match.\" << endl;\n\t\t\t\tdid_not_match++;\n\t\t\t}\n\t\t}\n\t\tcout << did_not_match << \" headers did not match.\" << endl;\n\t}\n\t\n\tfor (auto& im: images) {\n\t\tNifti::Header hdr = im.header();\n\t\tif (mode == Mode::Abbrev) {\n\t\t\tcout << \"Image path: \" << im.imagePath() << endl;\n\t\t\tcout << \"Datatype: \" << hdr.typeInfo().name << endl;\n\t\t\tcout << \"Dimensions: \" << hdr.dims().transpose() << \" (rank \" << to_string(hdr.rank()) << \")\" << endl;\n\t\t\tcout << \"Voxel size: \" << hdr.voxDims().transpose() << endl;\n\t\t\tcout << \"XForm: \" << endl << hdr.transform().matrix() << endl;\n\t\t\t(im.extensions().size() > 0) ? cout << \"Has extensions.\" << endl : cout << \"No extensions.\" << endl;\n\t\t} else if (mode == Mode::Full) {\n\t\t\tcout << \"Full Nifti Header for file: \" << im.imagePath() << endl;\n\t\t\tcout << hdr << endl;\n\t\t\tcout << \"Number of extensions: \" << im.extensions().size() << endl;\n\t\t}\n\t}\n\t\n\treturn EXIT_SUCCESS;\n}\n\n<commit_msg>Added options to niihdr to print out voxdims, TR, transform. Removed compare mode.<commit_after>\/\/\n\/\/ niihdr.cpp\n\/\/ NiftiImage\n\/\/\n\/\/ Created by Tobias Wood on 08\/07\/2013.\n\/\/ Copyright (c) 2013 Tobias Wood. All rights reserved.\n\/\/\n\n#include <memory>\n#include <vector>\n#include <iostream>\n#include <getopt.h>\n\n#include \"Nifti\/Nifti.h\"\n\nusing namespace std;\n\nconst string usage = \"niihdr - A utility for getting information from Nifti headers.\\n\\\n\\n\\\nUsage: niihdr [options] file1 [other files]\\n\\\nBy default the abbreviated header will be printed for each file.\\n\\\nAlternatively the entire header or specific fields can be printed.\\n\\\n\\n\\\nOptions:\\n\\\n\t-a, --abbrev : Print the abbreviated header (default).\\n\\\n\t-f, --full : Print the entire header.\\n\\\n\t-h, --help : Print this message and quit.\\n\\\n\t--voxdims : Print the voxel dimensions.\\n\\\n\t--tr : Print the TR.\\n\\\n\t--xform : Print the highest priority transform.\\n\\\n\";\n\n\nstatic int printAbbrev = false, printFull = false,\n printVoxdims = false, printTR = false, printXform = false;\nstatic struct option long_options[] = {\n\t{\"abbrev\", no_argument, 0, 'a'},\n\t{\"full\", no_argument, 0, 'f'},\n\t{\"help\", no_argument, 0, 'h'},\n\t{\"voxdims\", no_argument, &printVoxdims, 1},\n\t{\"tr\", no_argument, &printTR, 1},\n\t{\"xform\", no_argument, &printXform, 1},\n\t{0, 0, 0, 0}\n};\n\nint main(int argc, char **argv) {\n\tint indexptr = 0, c;\n\twhile ((c = getopt_long(argc, argv, \"afch\", long_options, &indexptr)) != -1) {\n\t\tswitch (c) {\n\t\t\tcase 'a': printAbbrev = true; printFull = false; break;\n\t\t\tcase 'f': printFull = true; printAbbrev = false; break;\n\t\t\tcase '?': \/\/ getopt will print an error message\n\t\t\tcase 'h':\n\t\t\t\tcout << usage << endl;\n\t\t\t\treturn EXIT_FAILURE;\n\t\t}\n\t}\n\tif ((argc - optind) <= 0 ) {\n\t\tcerr << \"No input image file specified.\" << endl;\n\t\tcout << usage << endl;\n\t\treturn EXIT_FAILURE;\n\t} else if (optind == 1) { \/\/ No other arguments specified\n\t\tprintAbbrev = true;\n\t}\n\tvector<Nifti::File> images;\n\ttry {\n\t\timages.reserve(argc - optind); \/\/ emplace_back can still trigger copies if the vector has to be resized\n\t\tfor (;optind < argc; optind++) {\n\t\t\timages.emplace_back(argv[optind]);\n\t\t}\n\t} catch (exception &e) {\n\t\tcerr << e.what() << endl;\n\t}\n\n\tfor (auto& im: images) {\n\t\tNifti::Header hdr = im.header();\n\t\tif (printAbbrev) {\n\t\t\tcout << \"Image path: \" << im.imagePath() << endl;\n\t\t\tcout << \"Datatype: \" << hdr.typeInfo().name << endl;\n\t\t\tcout << \"Dimensions: \" << hdr.dims().transpose() << \" (rank \" << to_string(hdr.rank()) << \")\" << endl;\n\t\t\tcout << \"Voxel size: \" << hdr.voxDims().transpose() << endl;\n\t\t\tcout << \"XForm: \" << endl << hdr.transform().matrix() << endl;\n\t\t\t(im.extensions().size() > 0) ? cout << \"Has extensions.\" << endl : cout << \"No extensions.\" << endl;\n\t\t}\n\t\tif (printFull) {\n\t\t\tcout << \"Full Nifti Header for file: \" << im.imagePath() << endl;\n\t\t\tcout << hdr << endl;\n\t\t\tcout << \"Number of extensions: \" << im.extensions().size() << endl;\n\t\t}\n\t\tif (printVoxdims) {\n\t\t\tif (hdr.rank() > 3) {\n\t\t\t\tcout << hdr.voxDims().head(3).transpose() << endl;\n\t\t\t} else {\n\t\t\t\tcout << hdr.voxDims() << endl;\n\t\t\t}\n\t\t}\n\t\tif (printTR) { cout << hdr.voxDim(4) << endl; }\n\t\tif (printXform) { cout << hdr.transform().matrix() << endl; }\n\t}\n\t\n\treturn EXIT_SUCCESS;\n}\n\n<|endoftext|>"} {"text":"<commit_before>#include \"CommonData.hpp\"\n#include \"Config.hpp\"\n#include \"EventInputQueue.hpp\"\n#include \"FlagStatus.hpp\"\n#include \"GlobalLock.hpp\"\n#include \"ListHookedConsumer.hpp\"\n\nnamespace org_pqrs_KeyRemap4MacBook {\n namespace {\n ListHookedConsumer listHookedConsumer;\n }\n\n ListHookedConsumer&\n ListHookedConsumer::instance(void)\n {\n return listHookedConsumer;\n }\n\n ListHookedConsumer::Item::Item(IOHIDevice* p) : ListHookedDevice::Item(p),\n orig_keyboardSpecialEventAction_(NULL),\n orig_keyboardSpecialEventTarget_(NULL)\n {}\n\n ListHookedConsumer::Item::~Item(void)\n {\n IOLOG_DEBUG(\"ListHookedConsumer::Item::~Item()\\n\");\n restoreEventAction();\n }\n\n \/\/ ----------------------------------------------------------------------\n bool\n ListHookedConsumer::Item::refresh(void)\n {\n if (! device_) goto restore;\n\n {\n const char* name = device_->getName();\n if (! name) goto restore;\n\n if (! ListHookedDevice::Item::isConsumer(name)) goto restore;\n }\n\n \/\/ ------------------------------------------------------------\n if (! Config::get_initialized()) {\n goto restore;\n }\n if (Config::get_essential_config(BRIDGE_ESSENTIAL_CONFIG_INDEX_general_dont_remap_apple_keyboard) &&\n isEqualVendor(DeviceVendor::APPLE_COMPUTER)) {\n goto restore;\n }\n \/\/ Logitech USB Headset\n if (isEqualVendorProduct(DeviceVendor::LOGITECH, DeviceProduct::LOGITECH_USB_HEADSET)) {\n goto restore;\n }\n \/\/ Logitech Cordless Presenter\n if (Config::get_essential_config(BRIDGE_ESSENTIAL_CONFIG_INDEX_general_dont_remap_logitech_cordless_presenter) &&\n isEqualVendorProduct(DeviceVendor::LOGITECH, DeviceProduct::LOGITECH_CORDLESS_PRESENTER)) {\n goto restore;\n }\n#if 0\n \/\/ Apple Internal Keyboard\n if (isEqualVendorProduct(DeviceVendor::APPLE_COMPUTER, DeviceProduct::APPLE_INTERNAL_KEYBOARD_TRACKPAD_0x021a)) {\n goto restore;\n }\n#endif\n#if 0\n \/\/ Apple External Keyboard\n if (isEqualVendorProduct(DeviceVendor::APPLE_COMPUTER, DeviceProduct::APPLE_ALUMINUM_KEYBOARD_JIS)) {\n goto restore;\n }\n#endif\n\n return replaceEventAction();\n\n restore:\n return restoreEventAction();\n }\n\n bool\n ListHookedConsumer::Item::replaceEventAction(void)\n {\n if (! device_) return false;\n\n IOHIKeyboard* kbd = OSDynamicCast(IOHIKeyboard, device_);\n if (! kbd) return false;\n\n KeyboardSpecialEventCallback callback = reinterpret_cast<KeyboardSpecialEventCallback>(kbd->_keyboardSpecialEventAction);\n if (callback == EventInputQueue::push_KeyboardSpecialEventCallback) return false;\n\n \/\/ ------------------------------------------------------------\n IOLOG_DEBUG(\"HookedConsumer::replaceEventAction device_:%p\\n\", device_);\n\n orig_keyboardSpecialEventAction_ = callback;\n orig_keyboardSpecialEventTarget_ = kbd->_keyboardSpecialEventTarget;\n\n kbd->_keyboardSpecialEventAction = reinterpret_cast<KeyboardSpecialEventAction>(EventInputQueue::push_KeyboardSpecialEventCallback);\n\n return true;\n }\n\n bool\n ListHookedConsumer::Item::restoreEventAction(void)\n {\n if (! device_) return false;\n\n IOHIKeyboard* kbd = OSDynamicCast(IOHIKeyboard, device_);\n if (! kbd) return false;\n\n KeyboardSpecialEventCallback callback = reinterpret_cast<KeyboardSpecialEventCallback>(kbd->_keyboardSpecialEventAction);\n if (callback != EventInputQueue::push_KeyboardSpecialEventCallback) return false;\n\n \/\/ ----------------------------------------\n IOLOG_DEBUG(\"HookedConsumer::restoreEventAction device_:%p\\n\", device_);\n\n kbd->_keyboardSpecialEventAction = reinterpret_cast<KeyboardSpecialEventAction>(orig_keyboardSpecialEventAction_);\n\n orig_keyboardSpecialEventAction_ = NULL;\n orig_keyboardSpecialEventTarget_ = NULL;\n\n return true;\n }\n\n \/\/ ======================================================================\n void\n ListHookedConsumer::Item::apply(const Params_KeyboardSpecialEventCallback& params)\n {\n if (params.key >= ConsumerKeyCode::VK__BEGIN__) {\n \/\/ Invalid keycode\n IOLOG_ERROR(\"%s invalid key:%d\\n\", __PRETTY_FUNCTION__, params.key.get());\n return;\n }\n if (params.flags.isVirtualModifiersOn()) {\n IOLOG_ERROR(\"%s invalid flags:%d\\n\", __PRETTY_FUNCTION__, params.flags.get());\n return;\n }\n\n \/\/ ------------------------------------------------------------\n KeyboardSpecialEventCallback callback = orig_keyboardSpecialEventAction_;\n if (! callback) return;\n\n OSObject* target = orig_keyboardSpecialEventTarget_;\n if (! target) return;\n\n OSObject* sender = OSDynamicCast(OSObject, device_);\n if (! sender) return;\n\n const AbsoluteTime& ts = CommonData::getcurrent_ts();\n OSObject* refcon = NULL;\n\n Params_KeyboardSpecialEventCallback::log(false, params.eventType, params.flags, params.key,\n params.flavor, params.guid, params.repeat);\n {\n \/\/ We need to unlock the global lock while we are calling the callback function.\n \/\/ For more information, See ListHookedKeyboard::Item::apply(const Params_KeyboardEventCallBack& params)\n GlobalLock::ScopedUnlock lk;\n callback(target, params.eventType.get(), params.flags.get(), params.key.get(),\n params.flavor, params.guid, params.repeat, ts, sender, refcon);\n }\n }\n\n void\n ListHookedConsumer::Item::disableNumLock(void)\n {\n IOHIKeyboard* kbd = OSDynamicCast(IOHIKeyboard, device_);\n if (! kbd) return;\n\n if (kbd->numLock()) {\n kbd->setNumLock(false);\n }\n }\n\n void\n ListHookedConsumer::apply(const Params_KeyboardSpecialEventCallback& params)\n {\n ListHookedConsumer::Item* p = static_cast<ListHookedConsumer::Item*>(get_replaced());\n if (p) {\n p->apply(params);\n }\n }\n\n void\n ListHookedConsumer::disableNumLock(void)\n {\n ListHookedConsumer::Item* p = static_cast<ListHookedConsumer::Item*>(get_replaced());\n if (p) {\n p->disableNumLock();\n }\n }\n}\n<commit_msg>use GlobalLock::ScopedUnlock before call setNumLock<commit_after>#include \"CommonData.hpp\"\n#include \"Config.hpp\"\n#include \"EventInputQueue.hpp\"\n#include \"FlagStatus.hpp\"\n#include \"GlobalLock.hpp\"\n#include \"ListHookedConsumer.hpp\"\n\nnamespace org_pqrs_KeyRemap4MacBook {\n namespace {\n ListHookedConsumer listHookedConsumer;\n }\n\n ListHookedConsumer&\n ListHookedConsumer::instance(void)\n {\n return listHookedConsumer;\n }\n\n ListHookedConsumer::Item::Item(IOHIDevice* p) : ListHookedDevice::Item(p),\n orig_keyboardSpecialEventAction_(NULL),\n orig_keyboardSpecialEventTarget_(NULL)\n {}\n\n ListHookedConsumer::Item::~Item(void)\n {\n IOLOG_DEBUG(\"ListHookedConsumer::Item::~Item()\\n\");\n restoreEventAction();\n }\n\n \/\/ ----------------------------------------------------------------------\n bool\n ListHookedConsumer::Item::refresh(void)\n {\n if (! device_) goto restore;\n\n {\n const char* name = device_->getName();\n if (! name) goto restore;\n\n if (! ListHookedDevice::Item::isConsumer(name)) goto restore;\n }\n\n \/\/ ------------------------------------------------------------\n if (! Config::get_initialized()) {\n goto restore;\n }\n if (Config::get_essential_config(BRIDGE_ESSENTIAL_CONFIG_INDEX_general_dont_remap_apple_keyboard) &&\n isEqualVendor(DeviceVendor::APPLE_COMPUTER)) {\n goto restore;\n }\n \/\/ Logitech USB Headset\n if (isEqualVendorProduct(DeviceVendor::LOGITECH, DeviceProduct::LOGITECH_USB_HEADSET)) {\n goto restore;\n }\n \/\/ Logitech Cordless Presenter\n if (Config::get_essential_config(BRIDGE_ESSENTIAL_CONFIG_INDEX_general_dont_remap_logitech_cordless_presenter) &&\n isEqualVendorProduct(DeviceVendor::LOGITECH, DeviceProduct::LOGITECH_CORDLESS_PRESENTER)) {\n goto restore;\n }\n#if 0\n \/\/ Apple Internal Keyboard\n if (isEqualVendorProduct(DeviceVendor::APPLE_COMPUTER, DeviceProduct::APPLE_INTERNAL_KEYBOARD_TRACKPAD_0x021a)) {\n goto restore;\n }\n#endif\n#if 0\n \/\/ Apple External Keyboard\n if (isEqualVendorProduct(DeviceVendor::APPLE_COMPUTER, DeviceProduct::APPLE_ALUMINUM_KEYBOARD_JIS)) {\n goto restore;\n }\n#endif\n\n return replaceEventAction();\n\n restore:\n return restoreEventAction();\n }\n\n bool\n ListHookedConsumer::Item::replaceEventAction(void)\n {\n if (! device_) return false;\n\n IOHIKeyboard* kbd = OSDynamicCast(IOHIKeyboard, device_);\n if (! kbd) return false;\n\n KeyboardSpecialEventCallback callback = reinterpret_cast<KeyboardSpecialEventCallback>(kbd->_keyboardSpecialEventAction);\n if (callback == EventInputQueue::push_KeyboardSpecialEventCallback) return false;\n\n \/\/ ------------------------------------------------------------\n IOLOG_DEBUG(\"HookedConsumer::replaceEventAction device_:%p\\n\", device_);\n\n orig_keyboardSpecialEventAction_ = callback;\n orig_keyboardSpecialEventTarget_ = kbd->_keyboardSpecialEventTarget;\n\n kbd->_keyboardSpecialEventAction = reinterpret_cast<KeyboardSpecialEventAction>(EventInputQueue::push_KeyboardSpecialEventCallback);\n\n return true;\n }\n\n bool\n ListHookedConsumer::Item::restoreEventAction(void)\n {\n if (! device_) return false;\n\n IOHIKeyboard* kbd = OSDynamicCast(IOHIKeyboard, device_);\n if (! kbd) return false;\n\n KeyboardSpecialEventCallback callback = reinterpret_cast<KeyboardSpecialEventCallback>(kbd->_keyboardSpecialEventAction);\n if (callback != EventInputQueue::push_KeyboardSpecialEventCallback) return false;\n\n \/\/ ----------------------------------------\n IOLOG_DEBUG(\"HookedConsumer::restoreEventAction device_:%p\\n\", device_);\n\n kbd->_keyboardSpecialEventAction = reinterpret_cast<KeyboardSpecialEventAction>(orig_keyboardSpecialEventAction_);\n\n orig_keyboardSpecialEventAction_ = NULL;\n orig_keyboardSpecialEventTarget_ = NULL;\n\n return true;\n }\n\n \/\/ ======================================================================\n void\n ListHookedConsumer::Item::apply(const Params_KeyboardSpecialEventCallback& params)\n {\n if (params.key >= ConsumerKeyCode::VK__BEGIN__) {\n \/\/ Invalid keycode\n IOLOG_ERROR(\"%s invalid key:%d\\n\", __PRETTY_FUNCTION__, params.key.get());\n return;\n }\n if (params.flags.isVirtualModifiersOn()) {\n IOLOG_ERROR(\"%s invalid flags:%d\\n\", __PRETTY_FUNCTION__, params.flags.get());\n return;\n }\n\n \/\/ ------------------------------------------------------------\n KeyboardSpecialEventCallback callback = orig_keyboardSpecialEventAction_;\n if (! callback) return;\n\n OSObject* target = orig_keyboardSpecialEventTarget_;\n if (! target) return;\n\n OSObject* sender = OSDynamicCast(OSObject, device_);\n if (! sender) return;\n\n const AbsoluteTime& ts = CommonData::getcurrent_ts();\n OSObject* refcon = NULL;\n\n Params_KeyboardSpecialEventCallback::log(false, params.eventType, params.flags, params.key,\n params.flavor, params.guid, params.repeat);\n {\n \/\/ We need to unlock the global lock while we are calling the callback function.\n \/\/ For more information, See ListHookedKeyboard::Item::apply(const Params_KeyboardEventCallBack& params)\n GlobalLock::ScopedUnlock lk;\n callback(target, params.eventType.get(), params.flags.get(), params.key.get(),\n params.flavor, params.guid, params.repeat, ts, sender, refcon);\n }\n }\n\n void\n ListHookedConsumer::Item::disableNumLock(void)\n {\n IOHIKeyboard* kbd = OSDynamicCast(IOHIKeyboard, device_);\n if (! kbd) return;\n\n GlobalLock::ScopedUnlock lk;\n if (kbd->numLock()) {\n kbd->setNumLock(false);\n }\n }\n\n void\n ListHookedConsumer::apply(const Params_KeyboardSpecialEventCallback& params)\n {\n ListHookedConsumer::Item* p = static_cast<ListHookedConsumer::Item*>(get_replaced());\n if (p) {\n p->apply(params);\n }\n }\n\n void\n ListHookedConsumer::disableNumLock(void)\n {\n ListHookedConsumer::Item* p = static_cast<ListHookedConsumer::Item*>(get_replaced());\n if (p) {\n p->disableNumLock();\n }\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ (C) Copyright 2017, Google Inc.\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include <string>\n#include <utility>\n\n#include \"absl\/strings\/str_format.h\"\t\/\/ for absl::StrFormat\n\n#include \"include_gunit.h\"\n\n#include <tesseract\/serialis.h>\n#include \"shapetable.h\"\n#include \"unicharset.h\"\n\nnamespace tesseract {\n\n#ifndef DISABLED_LEGACY_ENGINE\n\nstatic std::string TmpNameToPath(const std::string& name) {\n return file::JoinPath(FLAGS_test_tmpdir, name);\n}\n\n\/\/ Sets up a simple shape with some unichars.\nstatic void Setup352(int font_id, Shape* shape) {\n shape->AddToShape(3, font_id);\n shape->AddToShape(5, font_id);\n shape->AddToShape(2, font_id);\n}\n\n\/\/ Verifies some properties of the 352 shape.\nstatic void Expect352(int font_id, const Shape& shape) {\n EXPECT_EQ(3, shape.size());\n EXPECT_TRUE(shape.ContainsUnichar(2));\n EXPECT_TRUE(shape.ContainsUnichar(3));\n EXPECT_TRUE(shape.ContainsUnichar(5));\n EXPECT_FALSE(shape.ContainsUnichar(1));\n EXPECT_TRUE(shape.ContainsUnicharAndFont(2, font_id));\n EXPECT_FALSE(shape.ContainsUnicharAndFont(2, font_id - 1));\n EXPECT_FALSE(shape.ContainsUnicharAndFont(font_id, 2));\n \/\/ It should be a subset of itself.\n EXPECT_TRUE(shape.IsSubsetOf(shape));\n}\n\n#endif\n\n\/\/ The fixture for testing Shape.\nclass ShapeTest : public testing::Test {\n protected:\n void SetUp() {\n std::locale::global(std::locale(\"\"));\n }\n};\n\n\/\/ Tests that a Shape works as expected for all the basic functions.\nTEST_F(ShapeTest, BasicTest) {\n#ifdef DISABLED_LEGACY_ENGINE\n \/\/ Skip test because Shape is missing.\n GTEST_SKIP();\n#else\n Shape shape1;\n EXPECT_EQ(0, shape1.size());\n Setup352(101, &shape1);\n Expect352(101, shape1);\n \/\/ It should still work after file I\/O.\n std::string filename = TmpNameToPath(\"shapefile\");\n FILE* fp = fopen(filename.c_str(), \"wb\");\n EXPECT_TRUE(fp != nullptr);\n EXPECT_TRUE(shape1.Serialize(fp));\n fclose(fp);\n TFile tfp;\n EXPECT_TRUE(tfp.Open(filename.c_str(), nullptr));\n Shape shape2;\n EXPECT_TRUE(shape2.DeSerialize(&tfp));\n Expect352(101, shape2);\n \/\/ They should be subsets of each other.\n EXPECT_TRUE(shape1.IsSubsetOf(shape2));\n EXPECT_TRUE(shape2.IsSubsetOf(shape1));\n \/\/ They should be equal unichars.\n EXPECT_TRUE(shape1.IsEqualUnichars(&shape2));\n \/\/ and still pass afterwards.\n Expect352(101, shape1);\n Expect352(101, shape2);\n#endif\n}\n\n\/\/ Tests AddShape separately, as it takes quite a bit of work.\nTEST_F(ShapeTest, AddShapeTest) {\n#ifdef DISABLED_LEGACY_ENGINE\n \/\/ Skip test because Shape is missing.\n GTEST_SKIP();\n#else\n Shape shape1;\n Setup352(101, &shape1);\n Expect352(101, shape1);\n \/\/ Now setup a different shape with different content.\n Shape shape2;\n shape2.AddToShape(3, 101); \/\/ Duplicates shape1.\n shape2.AddToShape(5, 110); \/\/ Different font to shape1.\n shape2.AddToShape(7, 101); \/\/ Different unichar to shape1.\n \/\/ They should NOT be subsets of each other.\n EXPECT_FALSE(shape1.IsSubsetOf(shape2));\n EXPECT_FALSE(shape2.IsSubsetOf(shape1));\n \/\/ Now add shape2 to shape1.\n shape1.AddShape(shape2);\n \/\/ Test subsets again.\n EXPECT_FALSE(shape1.IsSubsetOf(shape2));\n EXPECT_TRUE(shape2.IsSubsetOf(shape1));\n EXPECT_EQ(4, shape1.size());\n EXPECT_FALSE(shape1.ContainsUnichar(1));\n EXPECT_TRUE(shape1.ContainsUnicharAndFont(5, 101));\n EXPECT_TRUE(shape1.ContainsUnicharAndFont(5, 110));\n EXPECT_FALSE(shape1.ContainsUnicharAndFont(3, 110));\n EXPECT_FALSE(shape1.ContainsUnicharAndFont(7, 110));\n EXPECT_FALSE(shape1.IsEqualUnichars(&shape2));\n#endif\n}\n\n\/\/ The fixture for testing Shape.\nclass ShapeTableTest : public testing::Test {};\n\n\/\/ Tests that a Shape works as expected for all the basic functions.\nTEST_F(ShapeTableTest, FullTest) {\n#ifdef DISABLED_LEGACY_ENGINE\n \/\/ Skip test because Shape is missing.\n GTEST_SKIP();\n#else\n Shape shape1;\n Setup352(101, &shape1);\n \/\/ Build a shape table with the same data, but in separate shapes.\n UNICHARSET unicharset;\n unicharset.unichar_insert(\" \");\n for (int i = 1; i <= 10; ++i) {\n std::string class_str = absl::StrFormat(\"class%d\", i);\n unicharset.unichar_insert(class_str.c_str());\n }\n ShapeTable st(unicharset);\n EXPECT_EQ(0, st.AddShape(3, 101));\n EXPECT_EQ(1, st.AddShape(5, 101));\n EXPECT_EQ(2, st.AddShape(2, 101));\n EXPECT_EQ(3, st.NumShapes());\n Expect352(101, shape1);\n EXPECT_EQ(3, st.AddShape(shape1));\n for (int i = 0; i < 3; ++i) {\n EXPECT_FALSE(st.MutableShape(i)->IsEqualUnichars(&shape1));\n }\n EXPECT_TRUE(st.MutableShape(3)->IsEqualUnichars(&shape1));\n EXPECT_TRUE(st.AnyMultipleUnichars());\n st.DeleteShape(3);\n EXPECT_FALSE(st.AnyMultipleUnichars());\n\n \/\/ Now merge to make a single shape like shape1.\n EXPECT_EQ(1, st.MasterUnicharCount(0));\n st.MergeShapes(0, 1);\n EXPECT_EQ(3, st.MergedUnicharCount(1, 2));\n st.MergeShapes(1, 2);\n for (int i = 0; i < 3; ++i) {\n EXPECT_EQ(3, st.MasterUnicharCount(i));\n \/\/ Master font count is the sum of all the font counts in the shape, not\n \/\/ the actual number of different fonts in the shape.\n EXPECT_EQ(3, st.MasterFontCount(i));\n }\n EXPECT_EQ(0, st.MasterDestinationIndex(1));\n EXPECT_EQ(0, st.MasterDestinationIndex(2));\n ShapeTable st2;\n st2.AppendMasterShapes(st, nullptr);\n EXPECT_EQ(1, st.NumMasterShapes());\n EXPECT_EQ(1, st2.NumShapes());\n EXPECT_TRUE(st2.MutableShape(0)->IsEqualUnichars(&shape1));\n EXPECT_TRUE(st2.AnyMultipleUnichars());\n#endif\n}\n\n} \/\/ namespace\n<commit_msg>[test] Correctly use assert instead of expect.<commit_after>\/\/ (C) Copyright 2017, Google Inc.\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include <string>\n#include <utility>\n\n#include \"absl\/strings\/str_format.h\"\t\/\/ for absl::StrFormat\n\n#include \"include_gunit.h\"\n\n#include <tesseract\/serialis.h>\n#include \"shapetable.h\"\n#include \"unicharset.h\"\n\nnamespace tesseract {\n\n#ifndef DISABLED_LEGACY_ENGINE\n\nstatic std::string TmpNameToPath(const std::string& name) {\n return file::JoinPath(FLAGS_test_tmpdir, name);\n}\n\n\/\/ Sets up a simple shape with some unichars.\nstatic void Setup352(int font_id, Shape* shape) {\n shape->AddToShape(3, font_id);\n shape->AddToShape(5, font_id);\n shape->AddToShape(2, font_id);\n}\n\n\/\/ Verifies some properties of the 352 shape.\nstatic void Expect352(int font_id, const Shape& shape) {\n EXPECT_EQ(3, shape.size());\n EXPECT_TRUE(shape.ContainsUnichar(2));\n EXPECT_TRUE(shape.ContainsUnichar(3));\n EXPECT_TRUE(shape.ContainsUnichar(5));\n EXPECT_FALSE(shape.ContainsUnichar(1));\n EXPECT_TRUE(shape.ContainsUnicharAndFont(2, font_id));\n EXPECT_FALSE(shape.ContainsUnicharAndFont(2, font_id - 1));\n EXPECT_FALSE(shape.ContainsUnicharAndFont(font_id, 2));\n \/\/ It should be a subset of itself.\n EXPECT_TRUE(shape.IsSubsetOf(shape));\n}\n\n#endif\n\n\/\/ The fixture for testing Shape.\nclass ShapeTest : public testing::Test {\n protected:\n void SetUp() {\n std::locale::global(std::locale(\"\"));\n }\n};\n\n\/\/ Tests that a Shape works as expected for all the basic functions.\nTEST_F(ShapeTest, BasicTest) {\n#ifdef DISABLED_LEGACY_ENGINE\n \/\/ Skip test because Shape is missing.\n GTEST_SKIP();\n#else\n Shape shape1;\n EXPECT_EQ(0, shape1.size());\n Setup352(101, &shape1);\n Expect352(101, shape1);\n \/\/ It should still work after file I\/O.\n std::string filename = TmpNameToPath(\"shapefile\");\n FILE* fp = fopen(filename.c_str(), \"wb\");\n ASSERT_TRUE(fp != nullptr);\n EXPECT_TRUE(shape1.Serialize(fp));\n fclose(fp);\n TFile tfp;\n EXPECT_TRUE(tfp.Open(filename.c_str(), nullptr));\n Shape shape2;\n EXPECT_TRUE(shape2.DeSerialize(&tfp));\n Expect352(101, shape2);\n \/\/ They should be subsets of each other.\n EXPECT_TRUE(shape1.IsSubsetOf(shape2));\n EXPECT_TRUE(shape2.IsSubsetOf(shape1));\n \/\/ They should be equal unichars.\n EXPECT_TRUE(shape1.IsEqualUnichars(&shape2));\n \/\/ and still pass afterwards.\n Expect352(101, shape1);\n Expect352(101, shape2);\n#endif\n}\n\n\/\/ Tests AddShape separately, as it takes quite a bit of work.\nTEST_F(ShapeTest, AddShapeTest) {\n#ifdef DISABLED_LEGACY_ENGINE\n \/\/ Skip test because Shape is missing.\n GTEST_SKIP();\n#else\n Shape shape1;\n Setup352(101, &shape1);\n Expect352(101, shape1);\n \/\/ Now setup a different shape with different content.\n Shape shape2;\n shape2.AddToShape(3, 101); \/\/ Duplicates shape1.\n shape2.AddToShape(5, 110); \/\/ Different font to shape1.\n shape2.AddToShape(7, 101); \/\/ Different unichar to shape1.\n \/\/ They should NOT be subsets of each other.\n EXPECT_FALSE(shape1.IsSubsetOf(shape2));\n EXPECT_FALSE(shape2.IsSubsetOf(shape1));\n \/\/ Now add shape2 to shape1.\n shape1.AddShape(shape2);\n \/\/ Test subsets again.\n EXPECT_FALSE(shape1.IsSubsetOf(shape2));\n EXPECT_TRUE(shape2.IsSubsetOf(shape1));\n EXPECT_EQ(4, shape1.size());\n EXPECT_FALSE(shape1.ContainsUnichar(1));\n EXPECT_TRUE(shape1.ContainsUnicharAndFont(5, 101));\n EXPECT_TRUE(shape1.ContainsUnicharAndFont(5, 110));\n EXPECT_FALSE(shape1.ContainsUnicharAndFont(3, 110));\n EXPECT_FALSE(shape1.ContainsUnicharAndFont(7, 110));\n EXPECT_FALSE(shape1.IsEqualUnichars(&shape2));\n#endif\n}\n\n\/\/ The fixture for testing Shape.\nclass ShapeTableTest : public testing::Test {};\n\n\/\/ Tests that a Shape works as expected for all the basic functions.\nTEST_F(ShapeTableTest, FullTest) {\n#ifdef DISABLED_LEGACY_ENGINE\n \/\/ Skip test because Shape is missing.\n GTEST_SKIP();\n#else\n Shape shape1;\n Setup352(101, &shape1);\n \/\/ Build a shape table with the same data, but in separate shapes.\n UNICHARSET unicharset;\n unicharset.unichar_insert(\" \");\n for (int i = 1; i <= 10; ++i) {\n std::string class_str = absl::StrFormat(\"class%d\", i);\n unicharset.unichar_insert(class_str.c_str());\n }\n ShapeTable st(unicharset);\n EXPECT_EQ(0, st.AddShape(3, 101));\n EXPECT_EQ(1, st.AddShape(5, 101));\n EXPECT_EQ(2, st.AddShape(2, 101));\n EXPECT_EQ(3, st.NumShapes());\n Expect352(101, shape1);\n EXPECT_EQ(3, st.AddShape(shape1));\n for (int i = 0; i < 3; ++i) {\n EXPECT_FALSE(st.MutableShape(i)->IsEqualUnichars(&shape1));\n }\n EXPECT_TRUE(st.MutableShape(3)->IsEqualUnichars(&shape1));\n EXPECT_TRUE(st.AnyMultipleUnichars());\n st.DeleteShape(3);\n EXPECT_FALSE(st.AnyMultipleUnichars());\n\n \/\/ Now merge to make a single shape like shape1.\n EXPECT_EQ(1, st.MasterUnicharCount(0));\n st.MergeShapes(0, 1);\n EXPECT_EQ(3, st.MergedUnicharCount(1, 2));\n st.MergeShapes(1, 2);\n for (int i = 0; i < 3; ++i) {\n EXPECT_EQ(3, st.MasterUnicharCount(i));\n \/\/ Master font count is the sum of all the font counts in the shape, not\n \/\/ the actual number of different fonts in the shape.\n EXPECT_EQ(3, st.MasterFontCount(i));\n }\n EXPECT_EQ(0, st.MasterDestinationIndex(1));\n EXPECT_EQ(0, st.MasterDestinationIndex(2));\n ShapeTable st2;\n st2.AppendMasterShapes(st, nullptr);\n EXPECT_EQ(1, st.NumMasterShapes());\n EXPECT_EQ(1, st2.NumShapes());\n EXPECT_TRUE(st2.MutableShape(0)->IsEqualUnichars(&shape1));\n EXPECT_TRUE(st2.AnyMultipleUnichars());\n#endif\n}\n\n} \/\/ namespace\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/gtk\/options\/content_settings_window_gtk.h\"\n\n#include <string>\n\n#include \"app\/l10n_util.h\"\n#include \"base\/command_line.h\"\n#include \"base\/message_loop.h\"\n#include \"chrome\/browser\/browser.h\"\n#include \"chrome\/browser\/browser_list.h\"\n#include \"chrome\/browser\/browser_process.h\"\n#include \"chrome\/browser\/gtk\/accessible_widget_helper_gtk.h\"\n#include \"chrome\/browser\/gtk\/browser_window_gtk.h\"\n#include \"chrome\/browser\/gtk\/gtk_util.h\"\n#include \"chrome\/browser\/pref_service.h\"\n#include \"chrome\/browser\/profile.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/common\/content_settings_types.h\"\n#include \"chrome\/common\/notification_service.h\"\n#include \"chrome\/common\/pref_names.h\"\n#include \"grit\/chromium_strings.h\"\n#include \"grit\/generated_resources.h\"\n#include \"grit\/locale_settings.h\"\n\nnamespace {\n\n\/\/ The singleton options window object.\nContentSettingsWindowGtk* settings_window = NULL;\n\n} \/\/ namespace\n\n\/\/ static\nvoid ContentSettingsWindowGtk::Show(GtkWindow* parent,\n ContentSettingsType page,\n Profile* profile) {\n DCHECK(profile);\n\n if (!settings_window) {\n \/\/ Creating and initializing a bunch of controls generates a bunch of\n \/\/ spurious events as control values change. Temporarily suppress\n \/\/ accessibility events until the window is created.\n profile->PauseAccessibilityEvents();\n\n \/\/ Create the options window.\n settings_window = new ContentSettingsWindowGtk(parent, profile);\n\n \/\/ Resume accessibility events.\n profile->ResumeAccessibilityEvents();\n }\n settings_window->ShowContentSettingsTab(page);\n}\n\nContentSettingsWindowGtk::ContentSettingsWindowGtk(GtkWindow* parent,\n Profile* profile)\n : profile_(profile),\n cookie_page_(profile),\n image_page_(profile, CONTENT_SETTINGS_TYPE_IMAGES),\n javascript_page_(profile, CONTENT_SETTINGS_TYPE_JAVASCRIPT),\n plugin_page_(profile, CONTENT_SETTINGS_TYPE_PLUGINS),\n popup_page_(profile, CONTENT_SETTINGS_TYPE_POPUPS),\n geolocation_page_(profile, CONTENT_SETTINGS_TYPE_GEOLOCATION) {\n \/\/ We don't need to observe changes in this value.\n last_selected_page_.Init(prefs::kContentSettingsWindowLastTabIndex,\n profile->GetPrefs(), NULL);\n\n std::string dialog_name = l10n_util::GetStringUTF8(\n IDS_CONTENT_SETTINGS_TITLE);\n dialog_ = gtk_dialog_new_with_buttons(\n dialog_name.c_str(),\n parent,\n static_cast<GtkDialogFlags>(GTK_DIALOG_MODAL | GTK_DIALOG_NO_SEPARATOR),\n GTK_STOCK_CLOSE,\n GTK_RESPONSE_CLOSE,\n NULL);\n\n accessible_widget_helper_.reset(new AccessibleWidgetHelper(\n dialog_, profile_));\n accessible_widget_helper_->SendOpenWindowNotification(dialog_name);\n\n gtk_window_set_default_size(GTK_WINDOW(dialog_), 500, -1);\n \/\/ Allow browser windows to go in front of the options dialog in metacity.\n gtk_window_set_type_hint(GTK_WINDOW(dialog_), GDK_WINDOW_TYPE_HINT_NORMAL);\n gtk_box_set_spacing(GTK_BOX(GTK_DIALOG(dialog_)->vbox),\n gtk_util::kContentAreaSpacing);\n gtk_util::SetWindowIcon(GTK_WINDOW(dialog_));\n\n notebook_ = gtk_notebook_new();\n\n gtk_notebook_append_page(\n GTK_NOTEBOOK(notebook_),\n cookie_page_.get_page_widget(),\n gtk_label_new(\n l10n_util::GetStringUTF8(IDS_COOKIES_TAB_LABEL).c_str()));\n gtk_notebook_append_page(\n GTK_NOTEBOOK(notebook_),\n image_page_.get_page_widget(),\n gtk_label_new(\n l10n_util::GetStringUTF8(IDS_IMAGES_TAB_LABEL).c_str()));\n gtk_notebook_append_page(\n GTK_NOTEBOOK(notebook_),\n javascript_page_.get_page_widget(),\n gtk_label_new(\n l10n_util::GetStringUTF8(IDS_JAVASCRIPT_TAB_LABEL).c_str()));\n gtk_notebook_append_page(\n GTK_NOTEBOOK(notebook_),\n plugin_page_.get_page_widget(),\n gtk_label_new(\n l10n_util::GetStringUTF8(IDS_PLUGIN_TAB_LABEL).c_str()));\n gtk_notebook_append_page(\n GTK_NOTEBOOK(notebook_),\n popup_page_.get_page_widget(),\n gtk_label_new(\n l10n_util::GetStringUTF8(IDS_POPUP_TAB_LABEL).c_str()));\n gtk_notebook_append_page(\n GTK_NOTEBOOK(notebook_),\n geolocation_page_.get_page_widget(),\n gtk_label_new(\n l10n_util::GetStringUTF8(IDS_GEOLOCATION_TAB_LABEL).c_str()));\n\n gtk_container_add(GTK_CONTAINER(GTK_DIALOG(dialog_)->vbox), notebook_);\n\n DCHECK_EQ(gtk_notebook_get_n_pages(GTK_NOTEBOOK(notebook_)),\n CONTENT_SETTINGS_NUM_TYPES);\n\n \/\/ Need to show the notebook before connecting switch-page signal, otherwise\n \/\/ we'll immediately get a signal switching to page 0 and overwrite our\n \/\/ last_selected_page_ value.\n gtk_widget_show_all(dialog_);\n\n g_signal_connect(notebook_, \"switch-page\",\n G_CALLBACK(OnSwitchPageThunk), this);\n\n \/\/ We only have one button and don't do any special handling, so just hook it\n \/\/ directly to gtk_widget_destroy.\n g_signal_connect(dialog_, \"response\", G_CALLBACK(gtk_widget_destroy), NULL);\n\n g_signal_connect(dialog_, \"destroy\", G_CALLBACK(OnWindowDestroyThunk), this);\n}\n\nContentSettingsWindowGtk::~ContentSettingsWindowGtk() {\n}\n\nvoid ContentSettingsWindowGtk::ShowContentSettingsTab(\n ContentSettingsType page) {\n if (Browser* b = BrowserList::GetLastActive()) {\n gtk_util::CenterOverWindow(GTK_WINDOW(dialog_),\n b->window()->GetNativeHandle());\n }\n\n \/\/ Bring options window to front if it already existed and isn't already\n \/\/ in front\n gtk_window_present_with_time(GTK_WINDOW(dialog_),\n gtk_get_current_event_time());\n\n if (page == CONTENT_SETTINGS_TYPE_DEFAULT) {\n \/\/ Remember the last visited page from local state.\n page = static_cast<ContentSettingsType>(last_selected_page_.GetValue());\n if (page == CONTENT_SETTINGS_TYPE_DEFAULT)\n page = CONTENT_SETTINGS_TYPE_COOKIES;\n }\n \/\/ If the page number is out of bounds, reset to the first tab.\n if (page < 0 || page >= gtk_notebook_get_n_pages(GTK_NOTEBOOK(notebook_)))\n page = CONTENT_SETTINGS_TYPE_COOKIES;\n\n gtk_notebook_set_current_page(GTK_NOTEBOOK(notebook_), page);\n}\n\nvoid ContentSettingsWindowGtk::OnSwitchPage(\n GtkWidget* notebook,\n GtkNotebookPage* page,\n guint page_num) {\n int index = page_num;\n DCHECK(index > CONTENT_SETTINGS_TYPE_DEFAULT &&\n index < CONTENT_SETTINGS_NUM_TYPES);\n last_selected_page_.SetValue(index);\n}\n\nvoid ContentSettingsWindowGtk::OnWindowDestroy(GtkWidget* widget) {\n settings_window = NULL;\n MessageLoop::current()->DeleteSoon(FROM_HERE, this);\n}\n<commit_msg>GTK: Make content options window non-resizable.<commit_after>\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/gtk\/options\/content_settings_window_gtk.h\"\n\n#include <string>\n\n#include \"app\/l10n_util.h\"\n#include \"base\/command_line.h\"\n#include \"base\/message_loop.h\"\n#include \"chrome\/browser\/browser.h\"\n#include \"chrome\/browser\/browser_list.h\"\n#include \"chrome\/browser\/browser_process.h\"\n#include \"chrome\/browser\/gtk\/accessible_widget_helper_gtk.h\"\n#include \"chrome\/browser\/gtk\/browser_window_gtk.h\"\n#include \"chrome\/browser\/gtk\/gtk_util.h\"\n#include \"chrome\/browser\/pref_service.h\"\n#include \"chrome\/browser\/profile.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/common\/content_settings_types.h\"\n#include \"chrome\/common\/notification_service.h\"\n#include \"chrome\/common\/pref_names.h\"\n#include \"grit\/chromium_strings.h\"\n#include \"grit\/generated_resources.h\"\n#include \"grit\/locale_settings.h\"\n\nnamespace {\n\n\/\/ The singleton options window object.\nContentSettingsWindowGtk* settings_window = NULL;\n\n} \/\/ namespace\n\n\/\/ static\nvoid ContentSettingsWindowGtk::Show(GtkWindow* parent,\n ContentSettingsType page,\n Profile* profile) {\n DCHECK(profile);\n\n if (!settings_window) {\n \/\/ Creating and initializing a bunch of controls generates a bunch of\n \/\/ spurious events as control values change. Temporarily suppress\n \/\/ accessibility events until the window is created.\n profile->PauseAccessibilityEvents();\n\n \/\/ Create the options window.\n settings_window = new ContentSettingsWindowGtk(parent, profile);\n\n \/\/ Resume accessibility events.\n profile->ResumeAccessibilityEvents();\n }\n settings_window->ShowContentSettingsTab(page);\n}\n\nContentSettingsWindowGtk::ContentSettingsWindowGtk(GtkWindow* parent,\n Profile* profile)\n : profile_(profile),\n cookie_page_(profile),\n image_page_(profile, CONTENT_SETTINGS_TYPE_IMAGES),\n javascript_page_(profile, CONTENT_SETTINGS_TYPE_JAVASCRIPT),\n plugin_page_(profile, CONTENT_SETTINGS_TYPE_PLUGINS),\n popup_page_(profile, CONTENT_SETTINGS_TYPE_POPUPS),\n geolocation_page_(profile, CONTENT_SETTINGS_TYPE_GEOLOCATION) {\n \/\/ We don't need to observe changes in this value.\n last_selected_page_.Init(prefs::kContentSettingsWindowLastTabIndex,\n profile->GetPrefs(), NULL);\n\n std::string dialog_name = l10n_util::GetStringUTF8(\n IDS_CONTENT_SETTINGS_TITLE);\n dialog_ = gtk_dialog_new_with_buttons(\n dialog_name.c_str(),\n parent,\n static_cast<GtkDialogFlags>(GTK_DIALOG_MODAL | GTK_DIALOG_NO_SEPARATOR),\n GTK_STOCK_CLOSE,\n GTK_RESPONSE_CLOSE,\n NULL);\n gtk_window_set_policy(GTK_WINDOW(dialog_), FALSE, FALSE, TRUE);\n\n accessible_widget_helper_.reset(new AccessibleWidgetHelper(\n dialog_, profile_));\n accessible_widget_helper_->SendOpenWindowNotification(dialog_name);\n\n gtk_window_set_default_size(GTK_WINDOW(dialog_), 500, -1);\n \/\/ Allow browser windows to go in front of the options dialog in metacity.\n gtk_window_set_type_hint(GTK_WINDOW(dialog_), GDK_WINDOW_TYPE_HINT_NORMAL);\n gtk_box_set_spacing(GTK_BOX(GTK_DIALOG(dialog_)->vbox),\n gtk_util::kContentAreaSpacing);\n gtk_util::SetWindowIcon(GTK_WINDOW(dialog_));\n\n notebook_ = gtk_notebook_new();\n\n gtk_notebook_append_page(\n GTK_NOTEBOOK(notebook_),\n cookie_page_.get_page_widget(),\n gtk_label_new(\n l10n_util::GetStringUTF8(IDS_COOKIES_TAB_LABEL).c_str()));\n gtk_notebook_append_page(\n GTK_NOTEBOOK(notebook_),\n image_page_.get_page_widget(),\n gtk_label_new(\n l10n_util::GetStringUTF8(IDS_IMAGES_TAB_LABEL).c_str()));\n gtk_notebook_append_page(\n GTK_NOTEBOOK(notebook_),\n javascript_page_.get_page_widget(),\n gtk_label_new(\n l10n_util::GetStringUTF8(IDS_JAVASCRIPT_TAB_LABEL).c_str()));\n gtk_notebook_append_page(\n GTK_NOTEBOOK(notebook_),\n plugin_page_.get_page_widget(),\n gtk_label_new(\n l10n_util::GetStringUTF8(IDS_PLUGIN_TAB_LABEL).c_str()));\n gtk_notebook_append_page(\n GTK_NOTEBOOK(notebook_),\n popup_page_.get_page_widget(),\n gtk_label_new(\n l10n_util::GetStringUTF8(IDS_POPUP_TAB_LABEL).c_str()));\n gtk_notebook_append_page(\n GTK_NOTEBOOK(notebook_),\n geolocation_page_.get_page_widget(),\n gtk_label_new(\n l10n_util::GetStringUTF8(IDS_GEOLOCATION_TAB_LABEL).c_str()));\n\n gtk_container_add(GTK_CONTAINER(GTK_DIALOG(dialog_)->vbox), notebook_);\n\n DCHECK_EQ(gtk_notebook_get_n_pages(GTK_NOTEBOOK(notebook_)),\n CONTENT_SETTINGS_NUM_TYPES);\n\n \/\/ Need to show the notebook before connecting switch-page signal, otherwise\n \/\/ we'll immediately get a signal switching to page 0 and overwrite our\n \/\/ last_selected_page_ value.\n gtk_widget_show_all(dialog_);\n\n g_signal_connect(notebook_, \"switch-page\",\n G_CALLBACK(OnSwitchPageThunk), this);\n\n \/\/ We only have one button and don't do any special handling, so just hook it\n \/\/ directly to gtk_widget_destroy.\n g_signal_connect(dialog_, \"response\", G_CALLBACK(gtk_widget_destroy), NULL);\n\n g_signal_connect(dialog_, \"destroy\", G_CALLBACK(OnWindowDestroyThunk), this);\n}\n\nContentSettingsWindowGtk::~ContentSettingsWindowGtk() {\n}\n\nvoid ContentSettingsWindowGtk::ShowContentSettingsTab(\n ContentSettingsType page) {\n if (Browser* b = BrowserList::GetLastActive()) {\n gtk_util::CenterOverWindow(GTK_WINDOW(dialog_),\n b->window()->GetNativeHandle());\n }\n\n \/\/ Bring options window to front if it already existed and isn't already\n \/\/ in front\n gtk_window_present_with_time(GTK_WINDOW(dialog_),\n gtk_get_current_event_time());\n\n if (page == CONTENT_SETTINGS_TYPE_DEFAULT) {\n \/\/ Remember the last visited page from local state.\n page = static_cast<ContentSettingsType>(last_selected_page_.GetValue());\n if (page == CONTENT_SETTINGS_TYPE_DEFAULT)\n page = CONTENT_SETTINGS_TYPE_COOKIES;\n }\n \/\/ If the page number is out of bounds, reset to the first tab.\n if (page < 0 || page >= gtk_notebook_get_n_pages(GTK_NOTEBOOK(notebook_)))\n page = CONTENT_SETTINGS_TYPE_COOKIES;\n\n gtk_notebook_set_current_page(GTK_NOTEBOOK(notebook_), page);\n}\n\nvoid ContentSettingsWindowGtk::OnSwitchPage(\n GtkWidget* notebook,\n GtkNotebookPage* page,\n guint page_num) {\n int index = page_num;\n DCHECK(index > CONTENT_SETTINGS_TYPE_DEFAULT &&\n index < CONTENT_SETTINGS_NUM_TYPES);\n last_selected_page_.SetValue(index);\n}\n\nvoid ContentSettingsWindowGtk::OnWindowDestroy(GtkWidget* widget) {\n settings_window = NULL;\n MessageLoop::current()->DeleteSoon(FROM_HERE, this);\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/=============================================================================================================\n\/**\n * @file main.cpp\n * @author Ruben Dörfel <doerfelruben@aol.com>\n * @since 0.1.5\n * @date July, 2020\n *\n * @section LICENSE\n *\n * Copyright (C) 2020, Ruben Dörfel. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification, are permitted provided that\n * the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this list of conditions and the\n * following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and\n * the following disclaimer in the documentation and\/or other materials provided with the distribution.\n * * Neither the name of MNE-CPP authors nor the names of its contributors may be used\n * to endorse or promote products derived from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED\n * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A\n * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n *\n * @brief Examplethat shows the coregistration workflow.\n *\n *\/\n\n\/\/=============================================================================================================\n\/\/ INCLUDES\n\/\/=============================================================================================================\n\n#include <iostream>\n\n#include <disp3D\/viewers\/abstractview.h>\n#include <disp3D\/engine\/model\/items\/digitizer\/digitizersettreeitem.h>\n#include <disp3D\/engine\/model\/data3Dtreemodel.h>\n#include <disp3D\/engine\/model\/items\/bem\/bemsurfacetreeitem.h>\n#include <disp3D\/engine\/model\/items\/bem\/bemtreeitem.h>\n\n#include \"fiff\/fiff_dig_point_set.h\"\n#include \"fiff\/fiff_dig_point.h\"\n#include \"fiff\/fiff_coord_trans.h\"\n\n#include \"mne\/mne_bem_surface.h\"\n#include \"mne\/mne_project_to_surface.h\"\n\n#include <utils\/generics\/applicationlogger.h>\n#include \"rtprocessing\/icp.h\"\n\n\/\/=============================================================================================================\n\/\/ QT INCLUDES\n\/\/=============================================================================================================\n\n#include <QApplication>\n#include <QMainWindow>\n#include <QCommandLineParser>\n#include <QDebug>\n#include <QFile>\n\n\/\/=============================================================================================================\n\/\/ Eigen\n\/\/=============================================================================================================\n\n#include <Eigen\/Core>\n\n\/\/=============================================================================================================\n\/\/ USED NAMESPACES\n\/\/=============================================================================================================\n\nusing namespace Eigen;\nusing namespace UTILSLIB;\nusing namespace RTPROCESSINGLIB;\nusing namespace FIFFLIB;\nusing namespace DISP3DLIB;\nusing namespace MNELIB;\n\n\/\/=============================================================================================================\n\/\/ MAIN\n\/\/=============================================================================================================\n\n\/\/=============================================================================================================\n\/**\n * The function main marks the entry point of the program.\n * By default, main has the storage class extern.\n *\n * @param [in] argc (argument count) is an integer that indicates how many arguments were entered on the command line when the program was started.\n * @param [in] argv (argument vector) is an array of pointers to arrays of character objects. The array objects are null-terminated strings, representing the arguments that were entered on the command line when the program was started.\n * @return the value that was set to exit() (which is 0 if exit() is called via quit()).\n *\/\nint main(int argc, char *argv[])\n{\n #ifdef STATICBUILD\n Q_INIT_RESOURCE(disp3d);\n #endif\n\n qInstallMessageHandler(ApplicationLogger::customLogWriter);\n QApplication a(argc, argv);\n\n \/\/ Command Line Parser\n QCommandLineParser parser;\n parser.setApplicationDescription(\"Example Coregistration\");\n parser.addHelpOption();\n\n QCommandLineOption digOption(\"dig\", \"The destination point set\", \"file\", QCoreApplication::applicationDirPath() + \"\/MNE-sample-data\/MEG\/sample\/sample_audvis-ave.fif\");\n QCommandLineOption bemOption(\"bem\", \"The bem file\", \"file\", QCoreApplication::applicationDirPath() + \"\/MNE-sample-data\/subjects\/sample\/bem\/sample-head.fif\");\n QCommandLineOption transOption(\"trans\", \"The MRI-Head transformation file\", \"file\", QCoreApplication::applicationDirPath() + \"\/MNE-sample-data\/MEG\/sample\/sample_audvis_raw-trans.fif\");\n QCommandLineOption scaleOption(\"scale\", \"Weather to scale during the registration or not\", \"bool\", \"false\");\n QCommandLineOption tolOption(\"tol\", \"The convergence limit for the icp algorithm.\", \"float\", \"0.001\");\n QCommandLineOption distOption(\"dist\", \"The maximum distance between digitizer and head shape in mm.\", \"float\", \"0.02\");\n\n parser.addOption(digOption);\n parser.addOption(bemOption);\n parser.addOption(scaleOption);\n parser.addOption(transOption);\n parser.addOption(tolOption);\n parser.addOption(distOption);\n\n parser.process(a);\n\n \/\/ get cli parameters\n QFile t_fileDig(parser.value(digOption));\n QFile t_fileBem(parser.value(bemOption));\n QFile t_fileTrans(parser.value(transOption));\n\n bool bScale = false;\n if(parser.value(scaleOption) == \"false\" || parser.value(scaleOption) == \"0\") {\n bScale = false;\n } else if(parser.value(scaleOption) == \"true\" || parser.value(scaleOption) == \"1\") {\n bScale = true;\n }\n\n float fTol = parser.value(tolOption).toFloat();\n float fMaxDist = parser.value(distOption).toFloat();\n\n \/\/ read Trans\n FiffCoordTrans transHeadMriRef(t_fileTrans);\n\n \/\/ read Bem\n MNEBem bemHead(t_fileBem);\n MNEBemSurface::SPtr bemSurface = MNEBemSurface::SPtr::create(bemHead[0]);\n MNEProjectToSurface::SPtr mneSurfacePoints = MNEProjectToSurface::SPtr::create(*bemSurface);\n\n \/\/ read digitizer data\n QList<int> lPickFiducials({FIFFV_POINT_CARDINAL});\n QList<int> lPickHSP({FIFFV_POINT_CARDINAL,FIFFV_POINT_HPI,FIFFV_POINT_EXTRA,FIFFV_POINT_EEG});\n FiffDigPointSet digSetSrc = FiffDigPointSet(t_fileDig).pickTypes(lPickFiducials); \/\/ Fiducials Head-Space\n FiffDigPointSet digSetDst = FiffDigPointSet(t_fileDig).pickTypes(lPickFiducials);\n digSetDst.applyTransform(transHeadMriRef, false); \/\/ Fiducials MRI-Space\n FiffDigPointSet digSetHsp = FiffDigPointSet(t_fileDig).pickTypes(lPickHSP); \/\/ Head shape points Head-Space\n\n \/\/ Initial Fiducial Alignment\n \/\/ Declare variables\n Matrix3f matSrc(digSetSrc.size(),3);\n Matrix3f matDst(digSetDst.size(),3);\n Matrix4f matTrans;\n Vector3f vecWeights(digSetSrc.size()); \/\/ LPA, Nasion, RPA\n float fScale;\n\n \/\/ get coordinates\n for(int i = 0; i< digSetSrc.size(); ++i) {\n matSrc(i,0) = digSetSrc[i].r[0]; matSrc(i,1) = digSetSrc[i].r[1]; matSrc(i,2) = digSetSrc[i].r[2];\n matDst(i,0) = digSetDst[i].r[0]; matDst(i,1) = digSetDst[i].r[1]; matDst(i,2) = digSetDst[i].r[2];\n\n \/\/ set standart weights\n if(digSetSrc[i].ident == FIFFV_POINT_NASION) {\n vecWeights(i) = 10.0;\n } else {\n vecWeights(i) = 1.0;\n }\n }\n\n \/\/ align fiducials\n if(!fitMatched(matSrc,matDst,matTrans,fScale,bScale,vecWeights)) {\n qWarning() << \"Point cloud registration not succesfull.\";\n }\n\n fiff_int_t iFrom = digSetSrc[0].coord_frame;\n fiff_int_t iTo = bemSurface.data()->coord_frame;\n FiffCoordTrans transHeadMri = FiffCoordTrans::make(iFrom, iTo, matTrans);\n\n \/\/ Prepare Icp:\n VectorXf vecWeightsICP(digSetHsp.size()); \/\/ Weigths vector\n int iMaxIter = 20;\n MatrixXf matHsp(digSetHsp.size(),3);\n\n for(int i = 0; i < digSetHsp.size(); ++i) {\n matHsp(i,0) = digSetHsp[i].r[0]; matHsp(i,1) = digSetHsp[i].r[1]; matHsp(i,2) = digSetHsp[i].r[2];\n \/\/ set standart weights\n if((digSetHsp[i].kind == FIFFV_POINT_CARDINAL) && (digSetHsp[i].ident == FIFFV_POINT_NASION)) {\n vecWeightsICP(i) = 10.0;\n } else {\n vecWeightsICP(i) = 1.0;\n }\n }\n\n MatrixXf matHspClean;\n VectorXi vecTake;\n\n \/\/ discard outliers\n if(!discardOutliers(mneSurfacePoints, matHsp, transHeadMri, vecTake, matHspClean, fMaxDist)) {\n qWarning() << \"Discard outliers was not succesfull.\";\n }\n VectorXf vecWeightsICPClean(vecTake.size());\n\n for(int i = 0; i < vecTake.size(); ++i) {\n vecWeightsICPClean(i) = vecWeightsICP(vecTake(i));\n }\n\n \/\/ icp\n if(!icp(mneSurfacePoints, matHspClean, transHeadMri, iMaxIter, fTol, vecWeightsICPClean)) {\n qWarning() << \"ICP was not succesfull.\";\n }\n qInfo() << \"transHeadMri:\";\n transHeadMri.print();\n qInfo() << \"transHeadMriRef:\";\n transHeadMriRef.print();\n\n AbstractView::SPtr p3DAbstractView = AbstractView::SPtr(new AbstractView());\n Data3DTreeModel::SPtr p3DDataModel = p3DAbstractView->getTreeModel();\n DigitizerSetTreeItem* pDigSrcSetTreeItem = p3DDataModel->addDigitizerData(\"Sample\", \"Fiducials Transformed\", digSetSrc);\n DigitizerSetTreeItem* pDigHspSetTreeItem = p3DDataModel->addDigitizerData(\"Sample\", \"Digitizer\", digSetHsp);\n pDigSrcSetTreeItem->setTransform(transHeadMri,true);\n\n BemTreeItem* pBemItem = p3DDataModel->addBemData(\"Sample\", \"Head\", bemHead);\n QList<QStandardItem*> itemList = pBemItem->findChildren(Data3DTreeModelItemTypes::BemSurfaceItem);\n for(int j = 0; j < itemList.size(); ++j) {\n if(BemSurfaceTreeItem* pBemItem = dynamic_cast<BemSurfaceTreeItem*>(itemList.at(j))) {\n pBemItem->setTransform(transHeadMri,true);\n }\n }\n\n p3DAbstractView->show();\n\n return a.exec();\n}\n<commit_msg>Enh: Add iteration setting via cli<commit_after>\/\/=============================================================================================================\n\/**\n * @file main.cpp\n * @author Ruben Dörfel <doerfelruben@aol.com>\n * @since 0.1.5\n * @date July, 2020\n *\n * @section LICENSE\n *\n * Copyright (C) 2020, Ruben Dörfel. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification, are permitted provided that\n * the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this list of conditions and the\n * following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and\n * the following disclaimer in the documentation and\/or other materials provided with the distribution.\n * * Neither the name of MNE-CPP authors nor the names of its contributors may be used\n * to endorse or promote products derived from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED\n * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A\n * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n *\n * @brief Examplethat shows the coregistration workflow.\n *\n *\/\n\n\/\/=============================================================================================================\n\/\/ INCLUDES\n\/\/=============================================================================================================\n\n#include <iostream>\n\n#include <disp3D\/viewers\/abstractview.h>\n#include <disp3D\/engine\/model\/items\/digitizer\/digitizersettreeitem.h>\n#include <disp3D\/engine\/model\/data3Dtreemodel.h>\n#include <disp3D\/engine\/model\/items\/bem\/bemsurfacetreeitem.h>\n#include <disp3D\/engine\/model\/items\/bem\/bemtreeitem.h>\n\n#include \"fiff\/fiff_dig_point_set.h\"\n#include \"fiff\/fiff_dig_point.h\"\n#include \"fiff\/fiff_coord_trans.h\"\n\n#include \"mne\/mne_bem_surface.h\"\n#include \"mne\/mne_project_to_surface.h\"\n\n#include <utils\/generics\/applicationlogger.h>\n#include \"rtprocessing\/icp.h\"\n\n\/\/=============================================================================================================\n\/\/ QT INCLUDES\n\/\/=============================================================================================================\n\n#include <QApplication>\n#include <QMainWindow>\n#include <QCommandLineParser>\n#include <QDebug>\n#include <QFile>\n\n\/\/=============================================================================================================\n\/\/ Eigen\n\/\/=============================================================================================================\n\n#include <Eigen\/Core>\n\n\/\/=============================================================================================================\n\/\/ USED NAMESPACES\n\/\/=============================================================================================================\n\nusing namespace Eigen;\nusing namespace UTILSLIB;\nusing namespace RTPROCESSINGLIB;\nusing namespace FIFFLIB;\nusing namespace DISP3DLIB;\nusing namespace MNELIB;\n\n\/\/=============================================================================================================\n\/\/ MAIN\n\/\/=============================================================================================================\n\n\/\/=============================================================================================================\n\/**\n * The function main marks the entry point of the program.\n * By default, main has the storage class extern.\n *\n * @param [in] argc (argument count) is an integer that indicates how many arguments were entered on the command line when the program was started.\n * @param [in] argv (argument vector) is an array of pointers to arrays of character objects. The array objects are null-terminated strings, representing the arguments that were entered on the command line when the program was started.\n * @return the value that was set to exit() (which is 0 if exit() is called via quit()).\n *\/\nint main(int argc, char *argv[])\n{\n #ifdef STATICBUILD\n Q_INIT_RESOURCE(disp3d);\n #endif\n\n qInstallMessageHandler(ApplicationLogger::customLogWriter);\n QApplication a(argc, argv);\n\n \/\/ Command Line Parser\n QCommandLineParser parser;\n parser.setApplicationDescription(\"Example Coregistration\");\n parser.addHelpOption();\n\n QCommandLineOption digOption(\"dig\", \"The destination point set\", \"file\", QCoreApplication::applicationDirPath() + \"\/MNE-sample-data\/MEG\/sample\/sample_audvis-ave.fif\");\n QCommandLineOption bemOption(\"bem\", \"The bem file\", \"file\", QCoreApplication::applicationDirPath() + \"\/MNE-sample-data\/subjects\/sample\/bem\/sample-head.fif\");\n QCommandLineOption transOption(\"trans\", \"The MRI-Head transformation file\", \"file\", QCoreApplication::applicationDirPath() + \"\/MNE-sample-data\/MEG\/sample\/sample_audvis_raw-trans.fif\");\n QCommandLineOption scaleOption(\"scale\", \"Weather to scale during the registration or not\", \"bool\", \"false\");\n QCommandLineOption tolOption(\"tol\", \"The convergence limit for the icp algorithm.\", \"float\", \"0.001\");\n QCommandLineOption distOption(\"dist\", \"The maximum distance between digitizer and head shape in mm.\", \"float\", \"0.02\");\n QCommandLineOption iterOption(\"iter\", \"The maximum number of icp iterations.\", \"int\", \"20\");\n\n parser.addOption(digOption);\n parser.addOption(bemOption);\n parser.addOption(scaleOption);\n parser.addOption(transOption);\n parser.addOption(tolOption);\n parser.addOption(distOption);\n parser.addOption(iterOption);\n\n parser.process(a);\n\n \/\/ get cli parameters\n QFile t_fileDig(parser.value(digOption));\n QFile t_fileBem(parser.value(bemOption));\n QFile t_fileTrans(parser.value(transOption));\n\n bool bScale = false;\n if(parser.value(scaleOption) == \"false\" || parser.value(scaleOption) == \"0\") {\n bScale = false;\n } else if(parser.value(scaleOption) == \"true\" || parser.value(scaleOption) == \"1\") {\n bScale = true;\n }\n\n float fTol = parser.value(tolOption).toFloat();\n float fMaxDist = parser.value(distOption).toFloat();\n int iMaxIter = parser.value(iterOption).toInt();\n\n \/\/ read Trans\n FiffCoordTrans transHeadMriRef(t_fileTrans);\n\n \/\/ read Bem\n MNEBem bemHead(t_fileBem);\n MNEBemSurface::SPtr bemSurface = MNEBemSurface::SPtr::create(bemHead[0]);\n MNEProjectToSurface::SPtr mneSurfacePoints = MNEProjectToSurface::SPtr::create(*bemSurface);\n\n \/\/ read digitizer data\n QList<int> lPickFiducials({FIFFV_POINT_CARDINAL});\n QList<int> lPickHSP({FIFFV_POINT_CARDINAL,FIFFV_POINT_HPI,FIFFV_POINT_EXTRA,FIFFV_POINT_EEG});\n FiffDigPointSet digSetSrc = FiffDigPointSet(t_fileDig).pickTypes(lPickFiducials); \/\/ Fiducials Head-Space\n FiffDigPointSet digSetDst = FiffDigPointSet(t_fileDig).pickTypes(lPickFiducials);\n digSetDst.applyTransform(transHeadMriRef, false); \/\/ Fiducials MRI-Space\n FiffDigPointSet digSetHsp = FiffDigPointSet(t_fileDig).pickTypes(lPickHSP); \/\/ Head shape points Head-Space\n\n \/\/ Initial Fiducial Alignment\n \/\/ Declare variables\n Matrix3f matSrc(digSetSrc.size(),3);\n Matrix3f matDst(digSetDst.size(),3);\n Matrix4f matTrans;\n Vector3f vecWeights(digSetSrc.size()); \/\/ LPA, Nasion, RPA\n float fScale;\n\n \/\/ get coordinates\n for(int i = 0; i< digSetSrc.size(); ++i) {\n matSrc(i,0) = digSetSrc[i].r[0]; matSrc(i,1) = digSetSrc[i].r[1]; matSrc(i,2) = digSetSrc[i].r[2];\n matDst(i,0) = digSetDst[i].r[0]; matDst(i,1) = digSetDst[i].r[1]; matDst(i,2) = digSetDst[i].r[2];\n\n \/\/ set standart weights\n if(digSetSrc[i].ident == FIFFV_POINT_NASION) {\n vecWeights(i) = 10.0;\n } else {\n vecWeights(i) = 1.0;\n }\n }\n\n \/\/ align fiducials\n if(!fitMatched(matSrc,matDst,matTrans,fScale,bScale,vecWeights)) {\n qWarning() << \"Point cloud registration not succesfull.\";\n }\n\n fiff_int_t iFrom = digSetSrc[0].coord_frame;\n fiff_int_t iTo = bemSurface.data()->coord_frame;\n FiffCoordTrans transHeadMri = FiffCoordTrans::make(iFrom, iTo, matTrans);\n\n \/\/ Prepare Icp:\n VectorXf vecWeightsICP(digSetHsp.size()); \/\/ Weigths vector\n MatrixXf matHsp(digSetHsp.size(),3);\n\n for(int i = 0; i < digSetHsp.size(); ++i) {\n matHsp(i,0) = digSetHsp[i].r[0]; matHsp(i,1) = digSetHsp[i].r[1]; matHsp(i,2) = digSetHsp[i].r[2];\n \/\/ set standart weights\n if((digSetHsp[i].kind == FIFFV_POINT_CARDINAL) && (digSetHsp[i].ident == FIFFV_POINT_NASION)) {\n vecWeightsICP(i) = 10.0;\n } else {\n vecWeightsICP(i) = 1.0;\n }\n }\n\n MatrixXf matHspClean;\n VectorXi vecTake;\n\n \/\/ discard outliers\n if(!discardOutliers(mneSurfacePoints, matHsp, transHeadMri, vecTake, matHspClean, fMaxDist)) {\n qWarning() << \"Discard outliers was not succesfull.\";\n }\n VectorXf vecWeightsICPClean(vecTake.size());\n\n for(int i = 0; i < vecTake.size(); ++i) {\n vecWeightsICPClean(i) = vecWeightsICP(vecTake(i));\n }\n\n \/\/ icp\n if(!icp(mneSurfacePoints, matHspClean, transHeadMri, iMaxIter, fTol, vecWeightsICPClean)) {\n qWarning() << \"ICP was not succesfull.\";\n }\n qInfo() << \"transHeadMri:\";\n transHeadMri.print();\n qInfo() << \"transHeadMriRef:\";\n transHeadMriRef.print();\n\n AbstractView::SPtr p3DAbstractView = AbstractView::SPtr(new AbstractView());\n Data3DTreeModel::SPtr p3DDataModel = p3DAbstractView->getTreeModel();\n DigitizerSetTreeItem* pDigSrcSetTreeItem = p3DDataModel->addDigitizerData(\"Sample\", \"Fiducials Transformed\", digSetSrc);\n DigitizerSetTreeItem* pDigHspSetTreeItem = p3DDataModel->addDigitizerData(\"Sample\", \"Digitizer\", digSetHsp);\n pDigSrcSetTreeItem->setTransform(transHeadMri,true);\n\n BemTreeItem* pBemItem = p3DDataModel->addBemData(\"Sample\", \"Head\", bemHead);\n QList<QStandardItem*> itemList = pBemItem->findChildren(Data3DTreeModelItemTypes::BemSurfaceItem);\n for(int j = 0; j < itemList.size(); ++j) {\n if(BemSurfaceTreeItem* pBemItem = dynamic_cast<BemSurfaceTreeItem*>(itemList.at(j))) {\n pBemItem->setTransform(transHeadMri,true);\n }\n }\n\n p3DAbstractView->show();\n\n return a.exec();\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Powiter\n\/* This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/. *\/\n\/*\n*Created by Alexandre GAUTHIER-FOICHAT on 6\/1\/2012. \n*contact: immarespond at gmail dot com\n*\n*\/\n\n#include \"Gui\/ComboBox.h\"\n\n#include <algorithm>\n#include <QLayout>\n#include <QLabel>\n#include <QMenu>\n#include <QStyle>\n\n#include \"Global\/GlobalDefines.h\"\n\nusing namespace std;\nComboBox::ComboBox(QWidget* parent):QFrame(parent),_currentIndex(0),_maximumTextSize(0),pressed(false){\n \n _mainLayout = new QHBoxLayout(this);\n _mainLayout->setSpacing(0);\n _mainLayout->setContentsMargins(0, 0, 0, 0);\n setLayout(_mainLayout);\n setFrameShape(QFrame::Box);\n \n _currentText = new QLabel(this);\n setCurrentIndex(-1);\n _currentText->setMinimumWidth(10);\n _mainLayout->addWidget(_currentText);\n \n _dropDownIcon = new QLabel(this);\n QImage imgC(IMAGES_PATH\"combobox.png\");\n QPixmap pixC=QPixmap::fromImage(imgC);\n pixC = pixC.scaled(10,10);\n _dropDownIcon->setPixmap(pixC);\n _mainLayout->addWidget(_dropDownIcon);\n \n _menu = new QMenu(this);\n}\n\n\n\nvoid ComboBox::paintEvent(QPaintEvent *e)\n{\n\/\/ QStyleOption opt;\n\/\/ opt.init(this);\n\/\/ QPainter p(this);\n\/\/ style()->drawPrimitive(QStyle::PE_Widget, &opt, &p, this);\n QFrame::paintEvent(e);\n}\n\nvoid ComboBox::mousePressEvent(QMouseEvent* e){\n QImage imgC(IMAGES_PATH\"pressed_combobox.png\");\n QPixmap pixC=QPixmap::fromImage(imgC);\n pixC = pixC.scaled(10,10);\n _dropDownIcon->setPixmap(pixC);\n setPressed(true);\n style()->unpolish(this);\n style()->polish(this);\n createMenu();\n QFrame::mousePressEvent(e);\n}\n\nvoid ComboBox::mouseReleaseEvent(QMouseEvent* e){\n QImage imgC(IMAGES_PATH\"combobox.png\");\n QPixmap pixC=QPixmap::fromImage(imgC);\n pixC = pixC.scaled(10,10);\n _dropDownIcon->setPixmap(pixC);\n setPressed(false);\n style()->unpolish(this);\n style()->polish(this);\n QFrame::mouseReleaseEvent(e);\n}\n\nvoid ComboBox::createMenu(){\n _menu->clear();\n for (U32 i = 0 ; i < _actions.size(); ++i) {\n for (U32 j = 0; j < _separators.size(); ++j) {\n if (_separators[j] == (int)i) {\n _menu->addSeparator();\n break;\n }\n }\n _menu->addAction(_actions[i]);\n }\n QAction* triggered = _menu->exec(this->mapToGlobal(QPoint(0,height())));\n for (U32 i = 0; i < _actions.size(); ++i) {\n if (triggered == _actions[i]) {\n setCurrentIndex(i);\n break;\n }\n }\n \n QImage imgC(IMAGES_PATH\"combobox.png\");\n QPixmap pixC=QPixmap::fromImage(imgC);\n pixC = pixC.scaled(10,10);\n _dropDownIcon->setPixmap(pixC);\n setPressed(false);\n style()->unpolish(this);\n style()->polish(this);\n \n}\n\nvoid ComboBox::insertItem(int index,const QString& item,QIcon icon,QKeySequence key){\n QAction* action = new QAction(this);\n action->setText(item);\n if (!icon.isNull()) {\n action->setIcon(icon);\n }\n if (!key.isEmpty()) {\n action->setShortcut(key);\n }\n if (item.size() > _maximumTextSize) {\n _maximumTextSize = item.size();\n }\n _actions.insert(_actions.begin()+index, action);\n \/*if this is the first action we add, make it current*\/\n if(_actions.size() == 1){\n setCurrentText(itemText(0));\n }\n \n}\n\nvoid ComboBox::addItem(const QString& item,QIcon icon ,QKeySequence key){\n QAction* action = new QAction(this);\n action->setText(item);\n if (!icon.isNull()) {\n action->setIcon(icon);\n }\n if (!key.isEmpty()) {\n action->setShortcut(key);\n }\n \n if (item.size() > _maximumTextSize) {\n _maximumTextSize = item.size();\n }\n \n _actions.push_back(action);\n \n \/*if this is the first action we add, make it current*\/\n if(_actions.size() == 1){\n setCurrentText(itemText(0));\n }\n}\n\nvoid ComboBox::setCurrentText(const QString& text){\n QString str(text);\n str.prepend(\" \");\n str.append(\" \");\n _currentText->setText(str);\n for (U32 i = 0; i < _actions.size(); ++i) {\n if(_actions[i]->text() == text){\n _currentIndex = i;\n break;\n }\n }\n}\nQString ComboBox::text() const{\n return _currentText->text();\n}\n\nint ComboBox::activeIndex() const{\n return _currentIndex;\n}\n\nvoid ComboBox::setCurrentIndex(int index){\n QString str;\n QString rawStr;\n if(index >= 0){\n str = _actions[index]->text();\n rawStr = str;\n \/*before displaying,prepend and append the text by some spacing.\n This is a dirty way to do this but QLayout::addSpacing() doesn't preserve\n the same style for the label.*\/\n int dsize = _maximumTextSize - str.size();\n dsize\/=2;\n str.prepend(\" \");\n for (int i = 0; i < dsize ; ++i) {str.prepend(\" \");}\n str.append(\" \");\n for (int i = 0; i < dsize ; ++i) {str.append(\" \");}\n }else{\n str = \" \";\n }\n _currentIndex = index;\n _currentText->setText(str);\n emit currentIndexChanged(index);\n emit currentIndexChanged(rawStr);\n}\nvoid ComboBox::addSeparator(){\n _separators.push_back(_actions.size()-1);\n}\nvoid ComboBox::insertSeparator(int index){\n _separators.push_back(index);\n}\n\nQString ComboBox::itemText(int index) const{\n if(index < (int)_actions.size())\n return _actions[index]->text();\n else\n return \"\";\n}\n\nvoid ComboBox::removeItem(const QString& item){\n for (U32 i = 0; i < _actions.size(); ++i) {\n if (_actions[i]->text() == item) {\n _actions.erase(_actions.begin()+i);\n if (_currentText->text() == item) {\n setCurrentIndex(i-1);\n }\n \/*adjust separators that were placed after this item*\/\n for (U32 j = 0; j < _separators.size(); ++j) {\n if (_separators[j] >= (int)i) {\n --_separators[j];\n }\n }\n }\n }\n \/*we also need to re-calculate the maximum text size*\/\n _maximumTextSize = 0;\n for (U32 i = 0; i < _actions.size(); ++i) {\n if (_actions[i]->text().size() > _maximumTextSize) {\n _maximumTextSize = _actions[i]->text().size();\n }\n }\n}\n\nvoid ComboBox::setItemText(int index,const QString& item){\n _actions[index]->setText(item);\n \/*we also need to re-calculate the maximum text size*\/\n _maximumTextSize = 0;\n for (U32 i = 0; i < _actions.size(); ++i) {\n if (_actions[i]->text().size() > _maximumTextSize) {\n _maximumTextSize = _actions[i]->text().size();\n }\n }\n}\n\nvoid ComboBox::setItemShortcut(int index,const QKeySequence& sequence){\n _actions[index]->setShortcut(sequence);\n}\n\nvoid ComboBox::setItemIcon(int index,const QIcon& icon){\n _actions[index]->setIcon(icon);\n}\nvoid ComboBox::disableItem(int index){\n _actions[index]->setEnabled(false);\n}\n\nvoid ComboBox::enableItem(int index){\n _actions[index]->setEnabled(true);\n}\n\n<commit_msg>add assert()s<commit_after>\/\/ Powiter\n\/* This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/. *\/\n\/*\n*Created by Alexandre GAUTHIER-FOICHAT on 6\/1\/2012. \n*contact: immarespond at gmail dot com\n*\n*\/\n\n#include \"Gui\/ComboBox.h\"\n\n#include <cassert>\n#include <algorithm>\n#include <QLayout>\n#include <QLabel>\n#include <QMenu>\n#include <QStyle>\n\n#include \"Global\/GlobalDefines.h\"\n\nusing namespace std;\nComboBox::ComboBox(QWidget* parent):QFrame(parent),_currentIndex(0),_maximumTextSize(0),pressed(false){\n \n _mainLayout = new QHBoxLayout(this);\n _mainLayout->setSpacing(0);\n _mainLayout->setContentsMargins(0, 0, 0, 0);\n setLayout(_mainLayout);\n setFrameShape(QFrame::Box);\n \n _currentText = new QLabel(this);\n setCurrentIndex(-1);\n _currentText->setMinimumWidth(10);\n _mainLayout->addWidget(_currentText);\n \n _dropDownIcon = new QLabel(this);\n QImage imgC(IMAGES_PATH\"combobox.png\");\n QPixmap pixC=QPixmap::fromImage(imgC);\n pixC = pixC.scaled(10,10);\n _dropDownIcon->setPixmap(pixC);\n _mainLayout->addWidget(_dropDownIcon);\n \n _menu = new QMenu(this);\n}\n\n\n\nvoid ComboBox::paintEvent(QPaintEvent *e)\n{\n\/\/ QStyleOption opt;\n\/\/ opt.init(this);\n\/\/ QPainter p(this);\n\/\/ style()->drawPrimitive(QStyle::PE_Widget, &opt, &p, this);\n QFrame::paintEvent(e);\n}\n\nvoid ComboBox::mousePressEvent(QMouseEvent* e){\n QImage imgC(IMAGES_PATH\"pressed_combobox.png\");\n QPixmap pixC=QPixmap::fromImage(imgC);\n pixC = pixC.scaled(10,10);\n _dropDownIcon->setPixmap(pixC);\n setPressed(true);\n style()->unpolish(this);\n style()->polish(this);\n createMenu();\n QFrame::mousePressEvent(e);\n}\n\nvoid ComboBox::mouseReleaseEvent(QMouseEvent* e){\n QImage imgC(IMAGES_PATH\"combobox.png\");\n QPixmap pixC=QPixmap::fromImage(imgC);\n pixC = pixC.scaled(10,10);\n _dropDownIcon->setPixmap(pixC);\n setPressed(false);\n style()->unpolish(this);\n style()->polish(this);\n QFrame::mouseReleaseEvent(e);\n}\n\nvoid ComboBox::createMenu(){\n _menu->clear();\n for (U32 i = 0 ; i < _actions.size(); ++i) {\n for (U32 j = 0; j < _separators.size(); ++j) {\n if (_separators[j] == (int)i) {\n _menu->addSeparator();\n break;\n }\n }\n _menu->addAction(_actions[i]);\n }\n QAction* triggered = _menu->exec(this->mapToGlobal(QPoint(0,height())));\n for (U32 i = 0; i < _actions.size(); ++i) {\n if (triggered == _actions[i]) {\n setCurrentIndex(i);\n break;\n }\n }\n \n QImage imgC(IMAGES_PATH\"combobox.png\");\n QPixmap pixC=QPixmap::fromImage(imgC);\n pixC = pixC.scaled(10,10);\n _dropDownIcon->setPixmap(pixC);\n setPressed(false);\n style()->unpolish(this);\n style()->polish(this);\n \n}\n\nvoid ComboBox::insertItem(int index,const QString& item,QIcon icon,QKeySequence key){\n assert(index >= 0);\n QAction* action = new QAction(this);\n action->setText(item);\n if (!icon.isNull()) {\n action->setIcon(icon);\n }\n if (!key.isEmpty()) {\n action->setShortcut(key);\n }\n if (item.size() > _maximumTextSize) {\n _maximumTextSize = item.size();\n }\n _actions.insert(_actions.begin()+index, action);\n \/*if this is the first action we add, make it current*\/\n if(_actions.size() == 1){\n setCurrentText(itemText(0));\n }\n \n}\n\nvoid ComboBox::addItem(const QString& item,QIcon icon ,QKeySequence key){\n QAction* action = new QAction(this);\n action->setText(item);\n if (!icon.isNull()) {\n action->setIcon(icon);\n }\n if (!key.isEmpty()) {\n action->setShortcut(key);\n }\n \n if (item.size() > _maximumTextSize) {\n _maximumTextSize = item.size();\n }\n \n _actions.push_back(action);\n \n \/*if this is the first action we add, make it current*\/\n if(_actions.size() == 1){\n setCurrentText(itemText(0));\n }\n}\n\nvoid ComboBox::setCurrentText(const QString& text){\n QString str(text);\n str.prepend(\" \");\n str.append(\" \");\n assert(_currentText);\n _currentText->setText(str);\n for (U32 i = 0; i < _actions.size(); ++i) {\n if(_actions[i]->text() == text){\n _currentIndex = i;\n break;\n }\n }\n}\nQString ComboBox::text() const{\n return _currentText->text();\n}\n\nint ComboBox::activeIndex() const{\n return _currentIndex;\n}\n\nvoid ComboBox::setCurrentIndex(int index){\n QString str;\n QString rawStr;\n if(index >= 0){\n str = _actions[index]->text();\n rawStr = str;\n \/*before displaying,prepend and append the text by some spacing.\n This is a dirty way to do this but QLayout::addSpacing() doesn't preserve\n the same style for the label.*\/\n int dsize = _maximumTextSize - str.size();\n dsize\/=2;\n str.prepend(\" \");\n for (int i = 0; i < dsize ; ++i) {str.prepend(\" \");}\n str.append(\" \");\n for (int i = 0; i < dsize ; ++i) {str.append(\" \");}\n }else{\n str = \" \";\n }\n _currentIndex = index;\n _currentText->setText(str);\n emit currentIndexChanged(index);\n emit currentIndexChanged(rawStr);\n}\nvoid ComboBox::addSeparator(){\n _separators.push_back(_actions.size()-1);\n}\nvoid ComboBox::insertSeparator(int index){\n assert(index >= 0);\n _separators.push_back(index);\n}\n\nQString ComboBox::itemText(int index) const{\n if(0 <= index && index < (int)_actions.size()) {\n assert(_actions[index]);\n return _actions[index]->text();\n } else {\n return \"\";\n }\n}\n\nvoid ComboBox::removeItem(const QString& item){\n for (U32 i = 0; i < _actions.size(); ++i) {\n assert(_actions[i]);\n if (_actions[i]->text() == item) {\n _actions.erase(_actions.begin()+i);\n assert(_currentText);\n if (_currentText->text() == item) {\n setCurrentIndex(i-1);\n }\n \/*adjust separators that were placed after this item*\/\n for (U32 j = 0; j < _separators.size(); ++j) {\n if (_separators[j] >= (int)i) {\n --_separators[j];\n }\n }\n }\n }\n \/*we also need to re-calculate the maximum text size*\/\n _maximumTextSize = 0;\n for (U32 i = 0; i < _actions.size(); ++i) {\n assert(_actions[i]);\n if (_actions[i]->text().size() > _maximumTextSize) {\n _maximumTextSize = _actions[i]->text().size();\n }\n }\n}\n\nvoid ComboBox::setItemText(int index,const QString& item){\n assert(0 <= index && index < (int)_actions.size());\n assert(_actions[index]);\n _actions[index]->setText(item);\n \/*we also need to re-calculate the maximum text size*\/\n _maximumTextSize = 0;\n for (U32 i = 0; i < _actions.size(); ++i) {\n assert(_actions[i]);\n if (_actions[i]->text().size() > _maximumTextSize) {\n _maximumTextSize = _actions[i]->text().size();\n }\n }\n}\n\nvoid ComboBox::setItemShortcut(int index,const QKeySequence& sequence){\n assert(0 <= index && index < (int)_actions.size());\n assert(_actions[index]);\n _actions[index]->setShortcut(sequence);\n}\n\nvoid ComboBox::setItemIcon(int index,const QIcon& icon){\n assert(0 <= index && index < (int)_actions.size());\n assert(_actions[index]);\n _actions[index]->setIcon(icon);\n}\nvoid ComboBox::disableItem(int index){\n assert(0 <= index && index < (int)_actions.size());\n assert(_actions[index]);\n _actions[index]->setEnabled(false);\n}\n\nvoid ComboBox::enableItem(int index){\n assert(0 <= index && index < (int)_actions.size());\n assert(_actions[index]);\n _actions[index]->setEnabled(true);\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2012, Yahoo! Inc. All rights reserved.\n\/\/ Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms.\n\n#include <gearbox\/core\/Json.h>\n#include <gearbox\/core\/JsonGenerator.h>\n\n#include <limits>\n#include <string>\n\n#include <boost\/lexical_cast.hpp>\n\nusing std::string;\n\nnamespace Gearbox {\n\n const std::string double_format = \"%.\" + boost::lexical_cast<string>(std::numeric_limits<double>().digits10) + \"g\";\n\nstring Json::Generator::generate(const Json & json, bool beautify) {\n\n yajl_gen g = yajl_gen_alloc(NULL);\n if( beautify ) {\n yajl_gen_config(g, yajl_gen_beautify, 1);\n yajl_gen_config(g, yajl_gen_indent_string, \" \");\n }\n\n Json::Generator::generate(g, &json);\n\n const unsigned char * buf; \n size_t len; \n yajl_gen_get_buf(g, &buf, &len); \n string tmp(reinterpret_cast<const char *>(buf), len);\n yajl_gen_free(g); \n return tmp;\n}\n\nvoid Json::Generator::generate(yajl_gen g, const Json * j) {\n switch(j->impl_->type) {\n case Json::UNDEF:\n yajl_gen_null(g);\n break;\n case Json::BOOL:\n yajl_gen_bool(g, j->as<bool>());\n break;\n case Json::INT:\n yajl_gen_integer(g, j->as<int64_t>());\n break;\n case Json::DOUBLE: {\n\n \/\/ this used to work, but it seems yajl_gen_double now has precision issues\n \/\/ yajl_gen_double(g, j->as<double>());\n char i[32];\n int chars = sprintf(i, double_format.c_str(), j->as<double>());\n yajl_gen_number(g, i, chars);\n }\n break;\n case Json::STRING:\n yajl_gen_string(\n g, \n reinterpret_cast<const unsigned char *>(j->as<string>().c_str()), \n j->as<string>().size()\n );\n break;\n case Json::OBJECT:\n Json::Generator::generateObject(g,j);\n break;\n case Json::ARRAY:\n Json::Generator::generateArray(g,j);\n break;\n }\n}\n \nvoid Json::Generator::generateObject(yajl_gen g, const Json * j) {\n yajl_gen_map_open(g);\n\n Json::Object & o = j->as<Json::Object>();\n Json::Object::iterator i = o.begin();\n Json::Object::iterator e = o.end();\n for( ; i != e; ++i ) {\n yajl_gen_string(g, reinterpret_cast<const unsigned char *>(i->first.c_str()), i->first.size());\n Json::Generator::generate(g, i->second.get());\n }\n \n yajl_gen_map_close(g);\n}\n \nvoid Json::Generator::generateArray(yajl_gen g, const Json * j) {\n yajl_gen_array_open(g);\n Json::Array & a = j->as<Json::Array>();\n for( unsigned int i=0; i< a.size(); ++i ) {\n Json::Generator::generate(g, a[i].get());\n }\n yajl_gen_array_close(g);\n}\n\n} \/\/ namespace\n<commit_msg>include stdio.h in JsonGenerator<commit_after>\/\/ Copyright (c) 2012, Yahoo! Inc. All rights reserved.\n\/\/ Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms.\n\n#include <gearbox\/core\/Json.h>\n#include <gearbox\/core\/JsonGenerator.h>\n\n#include <limits>\n#include <string>\n#include <stdio.h>\n\n#include <boost\/lexical_cast.hpp>\n\nusing std::string;\n\nnamespace Gearbox {\n\n const std::string double_format = \"%.\" + boost::lexical_cast<string>(std::numeric_limits<double>().digits10) + \"g\";\n\nstring Json::Generator::generate(const Json & json, bool beautify) {\n\n yajl_gen g = yajl_gen_alloc(NULL);\n if( beautify ) {\n yajl_gen_config(g, yajl_gen_beautify, 1);\n yajl_gen_config(g, yajl_gen_indent_string, \" \");\n }\n\n Json::Generator::generate(g, &json);\n\n const unsigned char * buf; \n size_t len; \n yajl_gen_get_buf(g, &buf, &len); \n string tmp(reinterpret_cast<const char *>(buf), len);\n yajl_gen_free(g); \n return tmp;\n}\n\nvoid Json::Generator::generate(yajl_gen g, const Json * j) {\n switch(j->impl_->type) {\n case Json::UNDEF:\n yajl_gen_null(g);\n break;\n case Json::BOOL:\n yajl_gen_bool(g, j->as<bool>());\n break;\n case Json::INT:\n yajl_gen_integer(g, j->as<int64_t>());\n break;\n case Json::DOUBLE: {\n\n \/\/ this used to work, but it seems yajl_gen_double now has precision issues\n \/\/ yajl_gen_double(g, j->as<double>());\n char i[32];\n int chars = sprintf(i, double_format.c_str(), j->as<double>());\n yajl_gen_number(g, i, chars);\n }\n break;\n case Json::STRING:\n yajl_gen_string(\n g, \n reinterpret_cast<const unsigned char *>(j->as<string>().c_str()), \n j->as<string>().size()\n );\n break;\n case Json::OBJECT:\n Json::Generator::generateObject(g,j);\n break;\n case Json::ARRAY:\n Json::Generator::generateArray(g,j);\n break;\n }\n}\n \nvoid Json::Generator::generateObject(yajl_gen g, const Json * j) {\n yajl_gen_map_open(g);\n\n Json::Object & o = j->as<Json::Object>();\n Json::Object::iterator i = o.begin();\n Json::Object::iterator e = o.end();\n for( ; i != e; ++i ) {\n yajl_gen_string(g, reinterpret_cast<const unsigned char *>(i->first.c_str()), i->first.size());\n Json::Generator::generate(g, i->second.get());\n }\n \n yajl_gen_map_close(g);\n}\n \nvoid Json::Generator::generateArray(yajl_gen g, const Json * j) {\n yajl_gen_array_open(g);\n Json::Array & a = j->as<Json::Array>();\n for( unsigned int i=0; i< a.size(); ++i ) {\n Json::Generator::generate(g, a[i].get());\n }\n yajl_gen_array_close(g);\n}\n\n} \/\/ namespace\n<|endoftext|>"} {"text":"<commit_before>\/*\n *\n * Copyright 2017 gRPC authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *\/\n\n#include <grpc\/impl\/codegen\/port_platform.h>\n\n#include \"src\/core\/lib\/channel\/channel_trace.h\"\n#include \"src\/core\/lib\/channel\/channelz.h\"\n#include \"src\/core\/lib\/channel\/channelz_registry.h\"\n#include \"src\/core\/lib\/gpr\/useful.h\"\n#include \"src\/core\/lib\/gprpp\/memory.h\"\n#include \"src\/core\/lib\/gprpp\/mutex_lock.h\"\n\n#include <grpc\/support\/alloc.h>\n#include <grpc\/support\/log.h>\n#include <grpc\/support\/sync.h>\n\n#include <cstring>\n\nnamespace grpc_core {\nnamespace channelz {\nnamespace {\n\n\/\/ singleton instance of the registry.\nChannelzRegistry* g_channelz_registry = nullptr;\n\n} \/\/ anonymous namespace\n\nvoid ChannelzRegistry::Init() { g_channelz_registry = New<ChannelzRegistry>(); }\n\nvoid ChannelzRegistry::Shutdown() { Delete(g_channelz_registry); }\n\nChannelzRegistry* ChannelzRegistry::Default() {\n GPR_DEBUG_ASSERT(g_channelz_registry != nullptr);\n return g_channelz_registry;\n}\n\nChannelzRegistry::ChannelzRegistry() { gpr_mu_init(&mu_); }\n\nChannelzRegistry::~ChannelzRegistry() { gpr_mu_destroy(&mu_); }\n\nintptr_t ChannelzRegistry::InternalRegister(BaseNode* node) {\n MutexLock lock(&mu_);\n entities_.push_back(node);\n return ++uuid_generator_;\n}\n\nvoid ChannelzRegistry::MaybePerformCompaction() {\n constexpr double kEmptinessTheshold = 1 \/ 3;\n double emptiness_ratio =\n double(num_empty_slots_) \/ double(entities_.capacity());\n if (emptiness_ratio > kEmptinessTheshold) {\n int front = 0;\n for (size_t i = 0; i < entities_.size(); ++i) {\n if (entities_[i] != nullptr) {\n entities_[front++] = entities_[i];\n }\n }\n for (int i = 0; i < num_empty_slots_; ++i) {\n entities_.pop_back();\n }\n num_empty_slots_ = 0;\n }\n}\n\nint ChannelzRegistry::FindByUuid(intptr_t target_uuid) {\n int left = 0;\n int right = entities_.size() - 1;\n while (left <= right) {\n int true_middle = left + (right - left) \/ 2;\n int first_non_null = true_middle;\n while (first_non_null < right && entities_[first_non_null] == nullptr) {\n first_non_null++;\n }\n if (entities_[first_non_null] == nullptr) {\n right = true_middle - 1;\n continue;\n }\n intptr_t uuid = entities_[first_non_null]->uuid();\n if (uuid == target_uuid) {\n return first_non_null;\n }\n if (uuid < target_uuid) {\n left = first_non_null + 1;\n } else {\n right = true_middle - 1;\n }\n }\n return -1;\n}\n\nvoid ChannelzRegistry::InternalUnregister(intptr_t uuid) {\n GPR_ASSERT(uuid >= 1);\n MutexLock lock(&mu_);\n GPR_ASSERT(uuid <= uuid_generator_);\n int idx = FindByUuid(uuid);\n GPR_ASSERT(idx >= 0);\n entities_[idx] = nullptr;\n num_empty_slots_++;\n MaybePerformCompaction();\n}\n\nBaseNode* ChannelzRegistry::InternalGet(intptr_t uuid) {\n MutexLock lock(&mu_);\n if (uuid < 1 || uuid > uuid_generator_) {\n return nullptr;\n }\n int idx = FindByUuid(uuid);\n return idx < 0 ? nullptr : entities_[idx];\n}\n\nchar* ChannelzRegistry::InternalGetTopChannels(intptr_t start_channel_id) {\n grpc_json* top_level_json = grpc_json_create(GRPC_JSON_OBJECT);\n grpc_json* json = top_level_json;\n grpc_json* json_iterator = nullptr;\n InlinedVector<BaseNode*, 10> top_level_channels;\n \/\/ uuids index into entities one-off (idx 0 is really uuid 1, since 0 is\n \/\/ reserved). However, we want to support requests coming in with\n \/\/ start_channel_id=0, which signifies \"give me everything.\" Hence this\n \/\/ funky looking line below.\n size_t start_idx = start_channel_id == 0 ? 0 : start_channel_id - 1;\n for (size_t i = start_idx; i < entities_.size(); ++i) {\n if (entities_[i] != nullptr &&\n entities_[i]->type() ==\n grpc_core::channelz::BaseNode::EntityType::kTopLevelChannel) {\n top_level_channels.push_back(entities_[i]);\n }\n }\n if (!top_level_channels.empty()) {\n \/\/ create list of channels\n grpc_json* array_parent = grpc_json_create_child(\n nullptr, json, \"channel\", nullptr, GRPC_JSON_ARRAY, false);\n for (size_t i = 0; i < top_level_channels.size(); ++i) {\n grpc_json* channel_json = top_level_channels[i]->RenderJson();\n json_iterator =\n grpc_json_link_child(array_parent, channel_json, json_iterator);\n }\n }\n \/\/ For now we do not have any pagination rules. In the future we could\n \/\/ pick a constant for max_channels_sent for a GetTopChannels request.\n \/\/ Tracking: https:\/\/github.com\/grpc\/grpc\/issues\/16019.\n json_iterator = grpc_json_create_child(nullptr, json, \"end\", nullptr,\n GRPC_JSON_TRUE, false);\n char* json_str = grpc_json_dump_to_string(top_level_json, 0);\n grpc_json_destroy(top_level_json);\n return json_str;\n}\n\nchar* ChannelzRegistry::InternalGetServers(intptr_t start_server_id) {\n grpc_json* top_level_json = grpc_json_create(GRPC_JSON_OBJECT);\n grpc_json* json = top_level_json;\n grpc_json* json_iterator = nullptr;\n InlinedVector<BaseNode*, 10> servers;\n \/\/ uuids index into entities one-off (idx 0 is really uuid 1, since 0 is\n \/\/ reserved). However, we want to support requests coming in with\n \/\/ start_server_id=0, which signifies \"give me everything.\"\n size_t start_idx = start_server_id == 0 ? 0 : start_server_id - 1;\n for (size_t i = start_idx; i < entities_.size(); ++i) {\n if (entities_[i] != nullptr &&\n entities_[i]->type() ==\n grpc_core::channelz::BaseNode::EntityType::kServer) {\n servers.push_back(entities_[i]);\n }\n }\n if (!servers.empty()) {\n \/\/ create list of servers\n grpc_json* array_parent = grpc_json_create_child(\n nullptr, json, \"server\", nullptr, GRPC_JSON_ARRAY, false);\n for (size_t i = 0; i < servers.size(); ++i) {\n grpc_json* server_json = servers[i]->RenderJson();\n json_iterator =\n grpc_json_link_child(array_parent, server_json, json_iterator);\n }\n }\n \/\/ For now we do not have any pagination rules. In the future we could\n \/\/ pick a constant for max_channels_sent for a GetServers request.\n \/\/ Tracking: https:\/\/github.com\/grpc\/grpc\/issues\/16019.\n json_iterator = grpc_json_create_child(nullptr, json, \"end\", nullptr,\n GRPC_JSON_TRUE, false);\n char* json_str = grpc_json_dump_to_string(top_level_json, 0);\n grpc_json_destroy(top_level_json);\n return json_str;\n}\n\n} \/\/ namespace channelz\n} \/\/ namespace grpc_core\n\nchar* grpc_channelz_get_top_channels(intptr_t start_channel_id) {\n return grpc_core::channelz::ChannelzRegistry::GetTopChannels(\n start_channel_id);\n}\n\nchar* grpc_channelz_get_servers(intptr_t start_server_id) {\n return grpc_core::channelz::ChannelzRegistry::GetServers(start_server_id);\n}\n\nchar* grpc_channelz_get_channel(intptr_t channel_id) {\n grpc_core::channelz::BaseNode* channel_node =\n grpc_core::channelz::ChannelzRegistry::Get(channel_id);\n if (channel_node == nullptr ||\n (channel_node->type() !=\n grpc_core::channelz::BaseNode::EntityType::kTopLevelChannel &&\n channel_node->type() !=\n grpc_core::channelz::BaseNode::EntityType::kInternalChannel)) {\n return nullptr;\n }\n grpc_json* top_level_json = grpc_json_create(GRPC_JSON_OBJECT);\n grpc_json* json = top_level_json;\n grpc_json* channel_json = channel_node->RenderJson();\n channel_json->key = \"channel\";\n grpc_json_link_child(json, channel_json, nullptr);\n char* json_str = grpc_json_dump_to_string(top_level_json, 0);\n grpc_json_destroy(top_level_json);\n return json_str;\n}\n\nchar* grpc_channelz_get_subchannel(intptr_t subchannel_id) {\n grpc_core::channelz::BaseNode* subchannel_node =\n grpc_core::channelz::ChannelzRegistry::Get(subchannel_id);\n if (subchannel_node == nullptr ||\n subchannel_node->type() !=\n grpc_core::channelz::BaseNode::EntityType::kSubchannel) {\n return nullptr;\n }\n grpc_json* top_level_json = grpc_json_create(GRPC_JSON_OBJECT);\n grpc_json* json = top_level_json;\n grpc_json* subchannel_json = subchannel_node->RenderJson();\n subchannel_json->key = \"subchannel\";\n grpc_json_link_child(json, subchannel_json, nullptr);\n char* json_str = grpc_json_dump_to_string(top_level_json, 0);\n grpc_json_destroy(top_level_json);\n return json_str;\n}\n\nchar* grpc_channelz_get_socket(intptr_t socket_id) {\n grpc_core::channelz::BaseNode* socket_node =\n grpc_core::channelz::ChannelzRegistry::Get(socket_id);\n if (socket_node == nullptr ||\n socket_node->type() !=\n grpc_core::channelz::BaseNode::EntityType::kSocket) {\n return nullptr;\n }\n grpc_json* top_level_json = grpc_json_create(GRPC_JSON_OBJECT);\n grpc_json* json = top_level_json;\n grpc_json* socket_json = socket_node->RenderJson();\n socket_json->key = \"socket\";\n grpc_json_link_child(json, socket_json, nullptr);\n char* json_str = grpc_json_dump_to_string(top_level_json, 0);\n grpc_json_destroy(top_level_json);\n return json_str;\n}\n<commit_msg>Fix objc build<commit_after>\/*\n *\n * Copyright 2017 gRPC authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *\/\n\n#include <grpc\/impl\/codegen\/port_platform.h>\n\n#include \"src\/core\/lib\/channel\/channel_trace.h\"\n#include \"src\/core\/lib\/channel\/channelz.h\"\n#include \"src\/core\/lib\/channel\/channelz_registry.h\"\n#include \"src\/core\/lib\/gpr\/useful.h\"\n#include \"src\/core\/lib\/gprpp\/memory.h\"\n#include \"src\/core\/lib\/gprpp\/mutex_lock.h\"\n\n#include <grpc\/support\/alloc.h>\n#include <grpc\/support\/log.h>\n#include <grpc\/support\/sync.h>\n\n#include <cstring>\n\nnamespace grpc_core {\nnamespace channelz {\nnamespace {\n\n\/\/ singleton instance of the registry.\nChannelzRegistry* g_channelz_registry = nullptr;\n\n} \/\/ anonymous namespace\n\nvoid ChannelzRegistry::Init() { g_channelz_registry = New<ChannelzRegistry>(); }\n\nvoid ChannelzRegistry::Shutdown() { Delete(g_channelz_registry); }\n\nChannelzRegistry* ChannelzRegistry::Default() {\n GPR_DEBUG_ASSERT(g_channelz_registry != nullptr);\n return g_channelz_registry;\n}\n\nChannelzRegistry::ChannelzRegistry() { gpr_mu_init(&mu_); }\n\nChannelzRegistry::~ChannelzRegistry() { gpr_mu_destroy(&mu_); }\n\nintptr_t ChannelzRegistry::InternalRegister(BaseNode* node) {\n MutexLock lock(&mu_);\n entities_.push_back(node);\n return ++uuid_generator_;\n}\n\nvoid ChannelzRegistry::MaybePerformCompaction() {\n constexpr double kEmptinessTheshold = 1 \/ 3;\n double emptiness_ratio =\n double(num_empty_slots_) \/ double(entities_.capacity());\n if (emptiness_ratio > kEmptinessTheshold) {\n int front = 0;\n for (size_t i = 0; i < entities_.size(); ++i) {\n if (entities_[i] != nullptr) {\n entities_[front++] = entities_[i];\n }\n }\n for (int i = 0; i < num_empty_slots_; ++i) {\n entities_.pop_back();\n }\n num_empty_slots_ = 0;\n }\n}\n\nint ChannelzRegistry::FindByUuid(intptr_t target_uuid) {\n size_t left = 0;\n size_t right = entities_.size() - 1;\n while (left <= right) {\n size_t true_middle = left + (right - left) \/ 2;\n size_t first_non_null = true_middle;\n while (first_non_null < right && entities_[first_non_null] == nullptr) {\n first_non_null++;\n }\n if (entities_[first_non_null] == nullptr) {\n right = true_middle - 1;\n continue;\n }\n intptr_t uuid = entities_[first_non_null]->uuid();\n if (uuid == target_uuid) {\n return first_non_null;\n }\n if (uuid < target_uuid) {\n left = first_non_null + 1;\n } else {\n right = true_middle - 1;\n }\n }\n return -1;\n}\n\nvoid ChannelzRegistry::InternalUnregister(intptr_t uuid) {\n GPR_ASSERT(uuid >= 1);\n MutexLock lock(&mu_);\n GPR_ASSERT(uuid <= uuid_generator_);\n int idx = FindByUuid(uuid);\n GPR_ASSERT(idx >= 0);\n entities_[idx] = nullptr;\n num_empty_slots_++;\n MaybePerformCompaction();\n}\n\nBaseNode* ChannelzRegistry::InternalGet(intptr_t uuid) {\n MutexLock lock(&mu_);\n if (uuid < 1 || uuid > uuid_generator_) {\n return nullptr;\n }\n int idx = FindByUuid(uuid);\n return idx < 0 ? nullptr : entities_[idx];\n}\n\nchar* ChannelzRegistry::InternalGetTopChannels(intptr_t start_channel_id) {\n grpc_json* top_level_json = grpc_json_create(GRPC_JSON_OBJECT);\n grpc_json* json = top_level_json;\n grpc_json* json_iterator = nullptr;\n InlinedVector<BaseNode*, 10> top_level_channels;\n \/\/ uuids index into entities one-off (idx 0 is really uuid 1, since 0 is\n \/\/ reserved). However, we want to support requests coming in with\n \/\/ start_channel_id=0, which signifies \"give me everything.\" Hence this\n \/\/ funky looking line below.\n size_t start_idx = start_channel_id == 0 ? 0 : start_channel_id - 1;\n for (size_t i = start_idx; i < entities_.size(); ++i) {\n if (entities_[i] != nullptr &&\n entities_[i]->type() ==\n grpc_core::channelz::BaseNode::EntityType::kTopLevelChannel) {\n top_level_channels.push_back(entities_[i]);\n }\n }\n if (!top_level_channels.empty()) {\n \/\/ create list of channels\n grpc_json* array_parent = grpc_json_create_child(\n nullptr, json, \"channel\", nullptr, GRPC_JSON_ARRAY, false);\n for (size_t i = 0; i < top_level_channels.size(); ++i) {\n grpc_json* channel_json = top_level_channels[i]->RenderJson();\n json_iterator =\n grpc_json_link_child(array_parent, channel_json, json_iterator);\n }\n }\n \/\/ For now we do not have any pagination rules. In the future we could\n \/\/ pick a constant for max_channels_sent for a GetTopChannels request.\n \/\/ Tracking: https:\/\/github.com\/grpc\/grpc\/issues\/16019.\n json_iterator = grpc_json_create_child(nullptr, json, \"end\", nullptr,\n GRPC_JSON_TRUE, false);\n char* json_str = grpc_json_dump_to_string(top_level_json, 0);\n grpc_json_destroy(top_level_json);\n return json_str;\n}\n\nchar* ChannelzRegistry::InternalGetServers(intptr_t start_server_id) {\n grpc_json* top_level_json = grpc_json_create(GRPC_JSON_OBJECT);\n grpc_json* json = top_level_json;\n grpc_json* json_iterator = nullptr;\n InlinedVector<BaseNode*, 10> servers;\n \/\/ uuids index into entities one-off (idx 0 is really uuid 1, since 0 is\n \/\/ reserved). However, we want to support requests coming in with\n \/\/ start_server_id=0, which signifies \"give me everything.\"\n size_t start_idx = start_server_id == 0 ? 0 : start_server_id - 1;\n for (size_t i = start_idx; i < entities_.size(); ++i) {\n if (entities_[i] != nullptr &&\n entities_[i]->type() ==\n grpc_core::channelz::BaseNode::EntityType::kServer) {\n servers.push_back(entities_[i]);\n }\n }\n if (!servers.empty()) {\n \/\/ create list of servers\n grpc_json* array_parent = grpc_json_create_child(\n nullptr, json, \"server\", nullptr, GRPC_JSON_ARRAY, false);\n for (size_t i = 0; i < servers.size(); ++i) {\n grpc_json* server_json = servers[i]->RenderJson();\n json_iterator =\n grpc_json_link_child(array_parent, server_json, json_iterator);\n }\n }\n \/\/ For now we do not have any pagination rules. In the future we could\n \/\/ pick a constant for max_channels_sent for a GetServers request.\n \/\/ Tracking: https:\/\/github.com\/grpc\/grpc\/issues\/16019.\n json_iterator = grpc_json_create_child(nullptr, json, \"end\", nullptr,\n GRPC_JSON_TRUE, false);\n char* json_str = grpc_json_dump_to_string(top_level_json, 0);\n grpc_json_destroy(top_level_json);\n return json_str;\n}\n\n} \/\/ namespace channelz\n} \/\/ namespace grpc_core\n\nchar* grpc_channelz_get_top_channels(intptr_t start_channel_id) {\n return grpc_core::channelz::ChannelzRegistry::GetTopChannels(\n start_channel_id);\n}\n\nchar* grpc_channelz_get_servers(intptr_t start_server_id) {\n return grpc_core::channelz::ChannelzRegistry::GetServers(start_server_id);\n}\n\nchar* grpc_channelz_get_channel(intptr_t channel_id) {\n grpc_core::channelz::BaseNode* channel_node =\n grpc_core::channelz::ChannelzRegistry::Get(channel_id);\n if (channel_node == nullptr ||\n (channel_node->type() !=\n grpc_core::channelz::BaseNode::EntityType::kTopLevelChannel &&\n channel_node->type() !=\n grpc_core::channelz::BaseNode::EntityType::kInternalChannel)) {\n return nullptr;\n }\n grpc_json* top_level_json = grpc_json_create(GRPC_JSON_OBJECT);\n grpc_json* json = top_level_json;\n grpc_json* channel_json = channel_node->RenderJson();\n channel_json->key = \"channel\";\n grpc_json_link_child(json, channel_json, nullptr);\n char* json_str = grpc_json_dump_to_string(top_level_json, 0);\n grpc_json_destroy(top_level_json);\n return json_str;\n}\n\nchar* grpc_channelz_get_subchannel(intptr_t subchannel_id) {\n grpc_core::channelz::BaseNode* subchannel_node =\n grpc_core::channelz::ChannelzRegistry::Get(subchannel_id);\n if (subchannel_node == nullptr ||\n subchannel_node->type() !=\n grpc_core::channelz::BaseNode::EntityType::kSubchannel) {\n return nullptr;\n }\n grpc_json* top_level_json = grpc_json_create(GRPC_JSON_OBJECT);\n grpc_json* json = top_level_json;\n grpc_json* subchannel_json = subchannel_node->RenderJson();\n subchannel_json->key = \"subchannel\";\n grpc_json_link_child(json, subchannel_json, nullptr);\n char* json_str = grpc_json_dump_to_string(top_level_json, 0);\n grpc_json_destroy(top_level_json);\n return json_str;\n}\n\nchar* grpc_channelz_get_socket(intptr_t socket_id) {\n grpc_core::channelz::BaseNode* socket_node =\n grpc_core::channelz::ChannelzRegistry::Get(socket_id);\n if (socket_node == nullptr ||\n socket_node->type() !=\n grpc_core::channelz::BaseNode::EntityType::kSocket) {\n return nullptr;\n }\n grpc_json* top_level_json = grpc_json_create(GRPC_JSON_OBJECT);\n grpc_json* json = top_level_json;\n grpc_json* socket_json = socket_node->RenderJson();\n socket_json->key = \"socket\";\n grpc_json_link_child(json, socket_json, nullptr);\n char* json_str = grpc_json_dump_to_string(top_level_json, 0);\n grpc_json_destroy(top_level_json);\n return json_str;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2011 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/importer\/external_process_importer_host.h\"\n\n#include \"chrome\/browser\/bookmarks\/bookmark_model.h\"\n#include \"chrome\/browser\/importer\/external_process_importer_client.h\"\n#include \"chrome\/browser\/importer\/in_process_importer_bridge.h\"\n\nExternalProcessImporterHost::ExternalProcessImporterHost()\n : items_(0),\n cancelled_(false),\n import_process_launched_(false) {\n}\n\nvoid ExternalProcessImporterHost::Cancel() {\n cancelled_ = true;\n if (import_process_launched_)\n client_->Cancel();\n NotifyImportEnded(); \/\/ Tells the observer that we're done, and releases us.\n}\n\nvoid ExternalProcessImporterHost::StartImportSettings(\n const importer::SourceProfile& source_profile,\n Profile* target_profile,\n uint16 items,\n ProfileWriter* writer,\n bool first_run) {\n \/\/ We really only support importing from one host at a time.\n DCHECK(!profile_);\n DCHECK(target_profile);\n\n profile_ = target_profile;\n writer_ = writer;\n source_profile_ = &source_profile;\n items_ = items;\n\n ImporterHost::AddRef(); \/\/ Balanced in ImporterHost::NotifyImportEnded.\n\n CheckForFirefoxLock(source_profile, items, first_run);\n CheckForLoadedModels(items);\n\n InvokeTaskIfDone();\n}\n\nvoid ExternalProcessImporterHost::InvokeTaskIfDone() {\n if (waiting_for_bookmarkbar_model_ || !registrar_.IsEmpty() ||\n !is_source_readable_ || cancelled_)\n return;\n\n \/\/ This is the in-process half of the bridge, which catches data from the IPC\n \/\/ pipe and feeds it to the ProfileWriter. The external process half of the\n \/\/ bridge lives in the external process (see ProfileImportThread).\n \/\/ The ExternalProcessImporterClient created in the next line owns the bridge,\n \/\/ and will delete it.\n InProcessImporterBridge* bridge =\n new InProcessImporterBridge(writer_.get(), this);\n client_ = new ExternalProcessImporterClient(this, *source_profile_, items_,\n bridge);\n import_process_launched_ = true;\n client_->Start();\n}\n\nvoid ExternalProcessImporterHost::Loaded(BookmarkModel* model,\n bool ids_reassigned) {\n DCHECK(model->IsLoaded());\n model->RemoveObserver(this);\n waiting_for_bookmarkbar_model_ = false;\n installed_bookmark_observer_ = false;\n\n InvokeTaskIfDone();\n}\n<commit_msg>Coverity: No uninitialized fields in constructor. (CID 9446)<commit_after>\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/importer\/external_process_importer_host.h\"\n\n#include \"chrome\/browser\/bookmarks\/bookmark_model.h\"\n#include \"chrome\/browser\/importer\/external_process_importer_client.h\"\n#include \"chrome\/browser\/importer\/in_process_importer_bridge.h\"\n\nExternalProcessImporterHost::ExternalProcessImporterHost()\n : client_(NULL),\n source_profile_(NULL),\n items_(0),\n cancelled_(false),\n import_process_launched_(false) {\n}\n\nvoid ExternalProcessImporterHost::Cancel() {\n cancelled_ = true;\n if (import_process_launched_)\n client_->Cancel();\n NotifyImportEnded(); \/\/ Tells the observer that we're done, and releases us.\n}\n\nvoid ExternalProcessImporterHost::StartImportSettings(\n const importer::SourceProfile& source_profile,\n Profile* target_profile,\n uint16 items,\n ProfileWriter* writer,\n bool first_run) {\n \/\/ We really only support importing from one host at a time.\n DCHECK(!profile_);\n DCHECK(target_profile);\n\n profile_ = target_profile;\n writer_ = writer;\n source_profile_ = &source_profile;\n items_ = items;\n\n ImporterHost::AddRef(); \/\/ Balanced in ImporterHost::NotifyImportEnded.\n\n CheckForFirefoxLock(source_profile, items, first_run);\n CheckForLoadedModels(items);\n\n InvokeTaskIfDone();\n}\n\nvoid ExternalProcessImporterHost::InvokeTaskIfDone() {\n if (waiting_for_bookmarkbar_model_ || !registrar_.IsEmpty() ||\n !is_source_readable_ || cancelled_)\n return;\n\n \/\/ This is the in-process half of the bridge, which catches data from the IPC\n \/\/ pipe and feeds it to the ProfileWriter. The external process half of the\n \/\/ bridge lives in the external process (see ProfileImportThread).\n \/\/ The ExternalProcessImporterClient created in the next line owns the bridge,\n \/\/ and will delete it.\n InProcessImporterBridge* bridge =\n new InProcessImporterBridge(writer_.get(), this);\n client_ = new ExternalProcessImporterClient(this, *source_profile_, items_,\n bridge);\n import_process_launched_ = true;\n client_->Start();\n}\n\nvoid ExternalProcessImporterHost::Loaded(BookmarkModel* model,\n bool ids_reassigned) {\n DCHECK(model->IsLoaded());\n model->RemoveObserver(this);\n waiting_for_bookmarkbar_model_ = false;\n installed_bookmark_observer_ = false;\n\n InvokeTaskIfDone();\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Natron\n\/* This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/. *\/\n\/*\n*Created by Alexandre GAUTHIER-FOICHAT on 6\/1\/2012. \n*contact: immarespond at gmail dot com\n*\n*\/\n\n#include \"Gui\/ComboBox.h\"\n\n#include <cassert>\n#include <algorithm>\n#include <QLayout>\n#include <QLabel>\n#include <QStyle>\n#include <QFont>\n#include <QFontMetrics>\n#include <QTextDocument> \/\/ for Qt::convertFromPlainText\n#include <QMouseEvent>\n\n#include \"Gui\/GuiApplicationManager.h\"\n#include \"Gui\/MenuWithToolTips.h\"\n\nusing namespace Natron;\n\nComboBox::ComboBox(QWidget* parent)\n: QFrame(parent)\n, _currentIndex(0)\n#if IS_MAXIMUMTEXTSIZE_USEFUL\n, _maximumTextSize(0)\n#endif\n, pressed(false)\n, animation(0)\n{\n \n _mainLayout = new QHBoxLayout(this);\n _mainLayout->setSpacing(0);\n _mainLayout->setContentsMargins(0, 0, 0, 0);\n setLayout(_mainLayout);\n setFrameShape(QFrame::Box);\n \n _currentText = new QLabel(this);\n _currentText->setObjectName(\"ComboBoxLabel\");\n setCurrentIndex(-1);\n _currentText->setMinimumWidth(10);\n _mainLayout->addWidget(_currentText);\n _currentText->setFixedHeight(fontMetrics().height() + 8);\n\n \n _dropDownIcon = new QLabel(this);\n _dropDownIcon->setObjectName(\"ComboBoxDropDownLabel\");\n QPixmap pixC;\n appPTR->getIcon(NATRON_PIXMAP_COMBOBOX, &pixC);\n _dropDownIcon->setPixmap(pixC);\n _mainLayout->addWidget(_dropDownIcon);\n \n _menu = new MenuWithToolTips(this);\n \n setSizePolicy(QSizePolicy::Preferred,QSizePolicy::Fixed);\n}\n\n\n\nvoid ComboBox::paintEvent(QPaintEvent *e)\n{\n\/\/ QStyleOption opt;\n\/\/ opt.init(this);\n\/\/ QPainter p(this);\n\/\/ style()->drawPrimitive(QStyle::PE_Widget, &opt, &p, this);\n QFrame::paintEvent(e);\n}\n\nvoid ComboBox::mousePressEvent(QMouseEvent* e){\n \n if (!e->buttons().testFlag(Qt::RightButton) && e->buttons().testFlag(Qt::LeftButton)) {\n QPixmap pixC;\n appPTR->getIcon(NATRON_PIXMAP_COMBOBOX_PRESSED, &pixC);\n _dropDownIcon->setPixmap(pixC);\n setPressed(true);\n style()->unpolish(this);\n style()->polish(this);\n createMenu();\n QFrame::mousePressEvent(e);\n\n }\n}\n\nvoid ComboBox::mouseReleaseEvent(QMouseEvent* e){\n QPixmap pixC;\n appPTR->getIcon(NATRON_PIXMAP_COMBOBOX, &pixC);\n _dropDownIcon->setPixmap(pixC);\n setPressed(false);\n style()->unpolish(this);\n style()->polish(this);\n QFrame::mouseReleaseEvent(e);\n}\n\nvoid ComboBox::createMenu(){\n _menu->clear();\n for (U32 i = 0 ; i < _actions.size(); ++i) {\n for (U32 j = 0; j < _separators.size(); ++j) {\n if (_separators[j] == (int)i) {\n _menu->addSeparator();\n break;\n }\n }\n _menu->addAction(_actions[i]);\n }\n QAction* triggered = _menu->exec(this->mapToGlobal(QPoint(0,height())));\n for (U32 i = 0; i < _actions.size(); ++i) {\n if (triggered == _actions[i]) {\n setCurrentIndex(i);\n break;\n }\n }\n \n QPixmap pixC;\n appPTR->getIcon(NATRON_PIXMAP_COMBOBOX, &pixC);\n _dropDownIcon->setPixmap(pixC);\n setPressed(false);\n style()->unpolish(this);\n style()->polish(this);\n \n}\nint ComboBox::count() const{\n return (int)_actions.size();\n}\nvoid ComboBox::insertItem(int index,const QString& item,QIcon icon,QKeySequence key,const QString& toolTip){\n assert(index >= 0);\n QAction* action = new QAction(this);\n action->setText(item);\n if(!toolTip.isEmpty()){\n action->setToolTip(Qt::convertFromPlainText(toolTip, Qt::WhiteSpaceNormal));\n }\n if (!icon.isNull()) {\n action->setIcon(icon);\n }\n if (!key.isEmpty()) {\n action->setShortcut(key);\n }\n#if IS_MAXIMUMTEXTSIZE_USEFUL\n if (item.size() > _maximumTextSize) {\n _maximumTextSize = item.size();\n }\n#endif\n growMaximumWidthFromText(item);\n _actions.insert(_actions.begin()+index, action);\n \/*if this is the first action we add, make it current*\/\n if(_actions.size() == 1){\n setCurrentText_no_emit(itemText(0));\n }\n \n}\n\nvoid ComboBox::addItem(const QString& item,QIcon icon ,QKeySequence key,const QString& toolTip){\n QAction* action = new QAction(this);\n \n action->setText(item);\n if (!icon.isNull()) {\n action->setIcon(icon);\n }\n if (!key.isEmpty()) {\n action->setShortcut(key);\n }\n if(!toolTip.isEmpty()){\n action->setToolTip(Qt::convertFromPlainText(toolTip, Qt::WhiteSpaceNormal));\n }\n#if IS_MAXIMUMTEXTSIZE_USEFUL\n if (item.size() > _maximumTextSize) {\n _maximumTextSize = item.size();\n }\n#endif\n growMaximumWidthFromText(item);\n _actions.push_back(action);\n \n \/*if this is the first action we add, make it current*\/\n if(_actions.size() == 1){\n setCurrentText_no_emit(itemText(0));\n }\n}\n\nvoid ComboBox::setCurrentText_no_emit(const QString& text) {\n setCurrentText_internal(text);\n}\n\nvoid ComboBox::setCurrentText(const QString& text) {\n int index = setCurrentText_internal(text);\n if (index != -1) {\n emit currentIndexChanged(index);\n emit currentIndexChanged(getCurrentIndexText());\n }\n}\n\nint ComboBox::setCurrentText_internal(const QString& text) {\n QString str(text);\n growMaximumWidthFromText(str);\n str.prepend(\" \");\n str.append(\" \");\n assert(_currentText);\n _currentText->setText(str);\n \/\/ if no action matches this text, set the index to a dirty value\n int index = -1;\n for (U32 i = 0; i < _actions.size(); ++i) {\n if(_actions[i]->text() == text){\n index = i;\n break;\n }\n }\n if (_currentIndex != index && index != -1) {\n _currentIndex = index;\n return index;\n }\n return -1;\n}\n\nvoid ComboBox::setMaximumWidthFromText(const QString& str)\n{\n int w = _currentText->fontMetrics().width(str+\" \");\n setMaximumWidth(w);\n}\n\nvoid ComboBox::growMaximumWidthFromText(const QString& str)\n{\n int w = _currentText->fontMetrics().width(str+\" \");\n if (w > maximumWidth()) {\n setMaximumWidth(w);\n }\n}\n\nint ComboBox::activeIndex() const{\n return _currentIndex;\n}\n\nQString ComboBox::getCurrentIndexText() const {\n assert(_currentIndex < (int)_actions.size());\n return _actions[_currentIndex]->text();\n}\n\nbool ComboBox::setCurrentIndex_internal(int index) {\n QString str;\n QString text;\n if (0 <= index && index < (int)_actions.size()) {\n text = _actions[index]->text();\n }\n str = text;\n \/*before displaying,prepend and append the text by some spacing.\n This is a dirty way to do this but QLayout::addSpacing() doesn't preserve\n the same style for the label.*\/\n#if IS_MAXIMUMTEXTSIZE_USEFUL\n int dsize = _maximumTextSize - str.size();\n dsize\/=2;\n str.prepend(\" \");\n for (int i = 0; i < dsize ; ++i) {str.prepend(\" \");}\n str.append(\" \");\n for (int i = 0; i < dsize ; ++i) {str.append(\" \");}\n#endif\n str.prepend(\" \");\n str.append(\" \");\n _currentText->setText(str);\n \n if (_currentIndex != index && index != -1) {\n _currentIndex = index;\n return true;\n } else {\n return false;\n }\n\n}\n\nvoid ComboBox::setCurrentIndex(int index)\n{\n if (setCurrentIndex_internal(index)) {\n \/\/\/emit the signal only if the entry changed\n emit currentIndexChanged(_currentIndex);\n emit currentIndexChanged(getCurrentIndexText());\n }\n}\n\nvoid ComboBox::setCurrentIndex_no_emit(int index) {\n setCurrentIndex_internal(index);\n}\n\nvoid ComboBox::addSeparator(){\n _separators.push_back(_actions.size()-1);\n}\nvoid ComboBox::insertSeparator(int index){\n assert(index >= 0);\n _separators.push_back(index);\n}\n\nQString ComboBox::itemText(int index) const{\n if(0 <= index && index < (int)_actions.size()) {\n assert(_actions[index]);\n return _actions[index]->text();\n } else {\n return \"\";\n }\n}\nint ComboBox::itemIndex(const QString& str) const{\n for (U32 i = 0; i < _actions.size(); ++i) {\n if (_actions[i]->text() == str) {\n return i;\n }\n }\n return -1;\n}\n\nvoid ComboBox::removeItem(const QString& item){\n for (U32 i = 0; i < _actions.size(); ++i) {\n assert(_actions[i]);\n if (_actions[i]->text() == item) {\n _actions.erase(_actions.begin()+i);\n assert(_currentText);\n if (_currentText->text() == item) {\n setCurrentIndex(i-1);\n }\n \/*adjust separators that were placed after this item*\/\n for (U32 j = 0; j < _separators.size(); ++j) {\n if (_separators[j] >= (int)i) {\n --_separators[j];\n }\n }\n }\n }\n#if IS_MAXIMUMTEXTSIZE_USEFUL\n \/*we also need to re-calculate the maximum text size*\/\n _maximumTextSize = 0;\n for (U32 i = 0; i < _actions.size(); ++i) {\n assert(_actions[i]);\n if (_actions[i]->text().size() > _maximumTextSize) {\n _maximumTextSize = _actions[i]->text().size();\n }\n }\n#endif\n}\n\nvoid ComboBox::clear(){\n _actions.clear();\n _menu->clear();\n _separators.clear();\n _currentIndex = 0;\n#if IS_MAXIMUMTEXTSIZE_USEFUL\n _maximumTextSize = 0;\n#endif\n}\n\n\nvoid ComboBox::setItemText(int index,const QString& item){\n assert(0 <= index && index < (int)_actions.size());\n assert(_actions[index]);\n _actions[index]->setText(item);\n growMaximumWidthFromText(item);\n#if IS_MAXIMUMTEXTSIZE_USEFUL\n \/*we also need to re-calculate the maximum text size*\/\n _maximumTextSize = 0;\n for (U32 i = 0; i < _actions.size(); ++i) {\n assert(_actions[i]);\n if (_actions[i]->text().size() > _maximumTextSize) {\n _maximumTextSize = _actions[i]->text().size();\n }\n }\n#endif\n}\n\nvoid ComboBox::setItemShortcut(int index,const QKeySequence& sequence){\n assert(0 <= index && index < (int)_actions.size());\n assert(_actions[index]);\n _actions[index]->setShortcut(sequence);\n}\n\nvoid ComboBox::setItemIcon(int index,const QIcon& icon){\n assert(0 <= index && index < (int)_actions.size());\n assert(_actions[index]);\n _actions[index]->setIcon(icon);\n}\nvoid ComboBox::disableItem(int index){\n assert(0 <= index && index < (int)_actions.size());\n assert(_actions[index]);\n _actions[index]->setEnabled(false);\n}\n\nvoid ComboBox::enableItem(int index){\n assert(0 <= index && index < (int)_actions.size());\n assert(_actions[index]);\n _actions[index]->setEnabled(true);\n}\n\nvoid ComboBox::setAnimation(int i){\n animation = i;\n style()->unpolish(this);\n style()->polish(this);\n repaint();\n}\n<commit_msg>ComboBox: fix warning<commit_after>\/\/ Natron\n\/* This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/. *\/\n\/*\n*Created by Alexandre GAUTHIER-FOICHAT on 6\/1\/2012. \n*contact: immarespond at gmail dot com\n*\n*\/\n\n#include \"Gui\/ComboBox.h\"\n\n#include <cassert>\n#include <algorithm>\n#include <QLayout>\n#include <QLabel>\n#include <QStyle>\n#include <QFont>\n#include <QFontMetrics>\n#include <QTextDocument> \/\/ for Qt::convertFromPlainText\nCLANG_DIAG_OFF(unused-private-field)\n#include <QMouseEvent>\nCLANG_DIAG_ON(unused-private-field)\n\n#include \"Gui\/GuiApplicationManager.h\"\n#include \"Gui\/MenuWithToolTips.h\"\n\nusing namespace Natron;\n\nComboBox::ComboBox(QWidget* parent)\n: QFrame(parent)\n, _currentIndex(0)\n#if IS_MAXIMUMTEXTSIZE_USEFUL\n, _maximumTextSize(0)\n#endif\n, pressed(false)\n, animation(0)\n{\n \n _mainLayout = new QHBoxLayout(this);\n _mainLayout->setSpacing(0);\n _mainLayout->setContentsMargins(0, 0, 0, 0);\n setLayout(_mainLayout);\n setFrameShape(QFrame::Box);\n \n _currentText = new QLabel(this);\n _currentText->setObjectName(\"ComboBoxLabel\");\n setCurrentIndex(-1);\n _currentText->setMinimumWidth(10);\n _mainLayout->addWidget(_currentText);\n _currentText->setFixedHeight(fontMetrics().height() + 8);\n\n \n _dropDownIcon = new QLabel(this);\n _dropDownIcon->setObjectName(\"ComboBoxDropDownLabel\");\n QPixmap pixC;\n appPTR->getIcon(NATRON_PIXMAP_COMBOBOX, &pixC);\n _dropDownIcon->setPixmap(pixC);\n _mainLayout->addWidget(_dropDownIcon);\n \n _menu = new MenuWithToolTips(this);\n \n setSizePolicy(QSizePolicy::Preferred,QSizePolicy::Fixed);\n}\n\n\n\nvoid ComboBox::paintEvent(QPaintEvent *e)\n{\n\/\/ QStyleOption opt;\n\/\/ opt.init(this);\n\/\/ QPainter p(this);\n\/\/ style()->drawPrimitive(QStyle::PE_Widget, &opt, &p, this);\n QFrame::paintEvent(e);\n}\n\nvoid ComboBox::mousePressEvent(QMouseEvent* e){\n \n if (!e->buttons().testFlag(Qt::RightButton) && e->buttons().testFlag(Qt::LeftButton)) {\n QPixmap pixC;\n appPTR->getIcon(NATRON_PIXMAP_COMBOBOX_PRESSED, &pixC);\n _dropDownIcon->setPixmap(pixC);\n setPressed(true);\n style()->unpolish(this);\n style()->polish(this);\n createMenu();\n QFrame::mousePressEvent(e);\n\n }\n}\n\nvoid ComboBox::mouseReleaseEvent(QMouseEvent* e){\n QPixmap pixC;\n appPTR->getIcon(NATRON_PIXMAP_COMBOBOX, &pixC);\n _dropDownIcon->setPixmap(pixC);\n setPressed(false);\n style()->unpolish(this);\n style()->polish(this);\n QFrame::mouseReleaseEvent(e);\n}\n\nvoid ComboBox::createMenu(){\n _menu->clear();\n for (U32 i = 0 ; i < _actions.size(); ++i) {\n for (U32 j = 0; j < _separators.size(); ++j) {\n if (_separators[j] == (int)i) {\n _menu->addSeparator();\n break;\n }\n }\n _menu->addAction(_actions[i]);\n }\n QAction* triggered = _menu->exec(this->mapToGlobal(QPoint(0,height())));\n for (U32 i = 0; i < _actions.size(); ++i) {\n if (triggered == _actions[i]) {\n setCurrentIndex(i);\n break;\n }\n }\n \n QPixmap pixC;\n appPTR->getIcon(NATRON_PIXMAP_COMBOBOX, &pixC);\n _dropDownIcon->setPixmap(pixC);\n setPressed(false);\n style()->unpolish(this);\n style()->polish(this);\n \n}\nint ComboBox::count() const{\n return (int)_actions.size();\n}\nvoid ComboBox::insertItem(int index,const QString& item,QIcon icon,QKeySequence key,const QString& toolTip){\n assert(index >= 0);\n QAction* action = new QAction(this);\n action->setText(item);\n if(!toolTip.isEmpty()){\n action->setToolTip(Qt::convertFromPlainText(toolTip, Qt::WhiteSpaceNormal));\n }\n if (!icon.isNull()) {\n action->setIcon(icon);\n }\n if (!key.isEmpty()) {\n action->setShortcut(key);\n }\n#if IS_MAXIMUMTEXTSIZE_USEFUL\n if (item.size() > _maximumTextSize) {\n _maximumTextSize = item.size();\n }\n#endif\n growMaximumWidthFromText(item);\n _actions.insert(_actions.begin()+index, action);\n \/*if this is the first action we add, make it current*\/\n if(_actions.size() == 1){\n setCurrentText_no_emit(itemText(0));\n }\n \n}\n\nvoid ComboBox::addItem(const QString& item,QIcon icon ,QKeySequence key,const QString& toolTip){\n QAction* action = new QAction(this);\n \n action->setText(item);\n if (!icon.isNull()) {\n action->setIcon(icon);\n }\n if (!key.isEmpty()) {\n action->setShortcut(key);\n }\n if(!toolTip.isEmpty()){\n action->setToolTip(Qt::convertFromPlainText(toolTip, Qt::WhiteSpaceNormal));\n }\n#if IS_MAXIMUMTEXTSIZE_USEFUL\n if (item.size() > _maximumTextSize) {\n _maximumTextSize = item.size();\n }\n#endif\n growMaximumWidthFromText(item);\n _actions.push_back(action);\n \n \/*if this is the first action we add, make it current*\/\n if(_actions.size() == 1){\n setCurrentText_no_emit(itemText(0));\n }\n}\n\nvoid ComboBox::setCurrentText_no_emit(const QString& text) {\n setCurrentText_internal(text);\n}\n\nvoid ComboBox::setCurrentText(const QString& text) {\n int index = setCurrentText_internal(text);\n if (index != -1) {\n emit currentIndexChanged(index);\n emit currentIndexChanged(getCurrentIndexText());\n }\n}\n\nint ComboBox::setCurrentText_internal(const QString& text) {\n QString str(text);\n growMaximumWidthFromText(str);\n str.prepend(\" \");\n str.append(\" \");\n assert(_currentText);\n _currentText->setText(str);\n \/\/ if no action matches this text, set the index to a dirty value\n int index = -1;\n for (U32 i = 0; i < _actions.size(); ++i) {\n if(_actions[i]->text() == text){\n index = i;\n break;\n }\n }\n if (_currentIndex != index && index != -1) {\n _currentIndex = index;\n return index;\n }\n return -1;\n}\n\nvoid ComboBox::setMaximumWidthFromText(const QString& str)\n{\n int w = _currentText->fontMetrics().width(str+\" \");\n setMaximumWidth(w);\n}\n\nvoid ComboBox::growMaximumWidthFromText(const QString& str)\n{\n int w = _currentText->fontMetrics().width(str+\" \");\n if (w > maximumWidth()) {\n setMaximumWidth(w);\n }\n}\n\nint ComboBox::activeIndex() const{\n return _currentIndex;\n}\n\nQString ComboBox::getCurrentIndexText() const {\n assert(_currentIndex < (int)_actions.size());\n return _actions[_currentIndex]->text();\n}\n\nbool ComboBox::setCurrentIndex_internal(int index) {\n QString str;\n QString text;\n if (0 <= index && index < (int)_actions.size()) {\n text = _actions[index]->text();\n }\n str = text;\n \/*before displaying,prepend and append the text by some spacing.\n This is a dirty way to do this but QLayout::addSpacing() doesn't preserve\n the same style for the label.*\/\n#if IS_MAXIMUMTEXTSIZE_USEFUL\n int dsize = _maximumTextSize - str.size();\n dsize\/=2;\n str.prepend(\" \");\n for (int i = 0; i < dsize ; ++i) {str.prepend(\" \");}\n str.append(\" \");\n for (int i = 0; i < dsize ; ++i) {str.append(\" \");}\n#endif\n str.prepend(\" \");\n str.append(\" \");\n _currentText->setText(str);\n \n if (_currentIndex != index && index != -1) {\n _currentIndex = index;\n return true;\n } else {\n return false;\n }\n\n}\n\nvoid ComboBox::setCurrentIndex(int index)\n{\n if (setCurrentIndex_internal(index)) {\n \/\/\/emit the signal only if the entry changed\n emit currentIndexChanged(_currentIndex);\n emit currentIndexChanged(getCurrentIndexText());\n }\n}\n\nvoid ComboBox::setCurrentIndex_no_emit(int index) {\n setCurrentIndex_internal(index);\n}\n\nvoid ComboBox::addSeparator(){\n _separators.push_back(_actions.size()-1);\n}\nvoid ComboBox::insertSeparator(int index){\n assert(index >= 0);\n _separators.push_back(index);\n}\n\nQString ComboBox::itemText(int index) const{\n if(0 <= index && index < (int)_actions.size()) {\n assert(_actions[index]);\n return _actions[index]->text();\n } else {\n return \"\";\n }\n}\nint ComboBox::itemIndex(const QString& str) const{\n for (U32 i = 0; i < _actions.size(); ++i) {\n if (_actions[i]->text() == str) {\n return i;\n }\n }\n return -1;\n}\n\nvoid ComboBox::removeItem(const QString& item){\n for (U32 i = 0; i < _actions.size(); ++i) {\n assert(_actions[i]);\n if (_actions[i]->text() == item) {\n _actions.erase(_actions.begin()+i);\n assert(_currentText);\n if (_currentText->text() == item) {\n setCurrentIndex(i-1);\n }\n \/*adjust separators that were placed after this item*\/\n for (U32 j = 0; j < _separators.size(); ++j) {\n if (_separators[j] >= (int)i) {\n --_separators[j];\n }\n }\n }\n }\n#if IS_MAXIMUMTEXTSIZE_USEFUL\n \/*we also need to re-calculate the maximum text size*\/\n _maximumTextSize = 0;\n for (U32 i = 0; i < _actions.size(); ++i) {\n assert(_actions[i]);\n if (_actions[i]->text().size() > _maximumTextSize) {\n _maximumTextSize = _actions[i]->text().size();\n }\n }\n#endif\n}\n\nvoid ComboBox::clear(){\n _actions.clear();\n _menu->clear();\n _separators.clear();\n _currentIndex = 0;\n#if IS_MAXIMUMTEXTSIZE_USEFUL\n _maximumTextSize = 0;\n#endif\n}\n\n\nvoid ComboBox::setItemText(int index,const QString& item){\n assert(0 <= index && index < (int)_actions.size());\n assert(_actions[index]);\n _actions[index]->setText(item);\n growMaximumWidthFromText(item);\n#if IS_MAXIMUMTEXTSIZE_USEFUL\n \/*we also need to re-calculate the maximum text size*\/\n _maximumTextSize = 0;\n for (U32 i = 0; i < _actions.size(); ++i) {\n assert(_actions[i]);\n if (_actions[i]->text().size() > _maximumTextSize) {\n _maximumTextSize = _actions[i]->text().size();\n }\n }\n#endif\n}\n\nvoid ComboBox::setItemShortcut(int index,const QKeySequence& sequence){\n assert(0 <= index && index < (int)_actions.size());\n assert(_actions[index]);\n _actions[index]->setShortcut(sequence);\n}\n\nvoid ComboBox::setItemIcon(int index,const QIcon& icon){\n assert(0 <= index && index < (int)_actions.size());\n assert(_actions[index]);\n _actions[index]->setIcon(icon);\n}\nvoid ComboBox::disableItem(int index){\n assert(0 <= index && index < (int)_actions.size());\n assert(_actions[index]);\n _actions[index]->setEnabled(false);\n}\n\nvoid ComboBox::enableItem(int index){\n assert(0 <= index && index < (int)_actions.size());\n assert(_actions[index]);\n _actions[index]->setEnabled(true);\n}\n\nvoid ComboBox::setAnimation(int i){\n animation = i;\n style()->unpolish(this);\n style()->polish(this);\n repaint();\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ illarionserver - server for the game Illarion\n\/\/ Copyright 2011 Illarion e.V.\n\/\/\n\/\/ This file is part of illarionserver.\n\/\/\n\/\/ illarionserver is free software: you can redistribute it and\/or modify\n\/\/ it under the terms of the GNU Affero General Public License as published by\n\/\/ the Free Software Foundation, either version 3 of the License, or\n\/\/ (at your option) any later version.\n\/\/\n\/\/ illarionserver is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n\/\/ GNU Affero General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Affero General Public License\n\/\/ along with illarionserver. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n\n\n#include \"WaypointList.hpp\"\n#include \"World.hpp\"\n#include \"Field.hpp\"\n#include \"Logger.hpp\"\n\nWaypointList::WaypointList(Character *movechar) : _movechar(movechar) {\n\n}\n\nconst std::list<position> &WaypointList::getWaypoints() const {\n return positions;\n}\n\nvoid WaypointList::addWaypoint(const position &pos) {\n positions.push_back(pos);\n}\n\nbool WaypointList::getNextWaypoint(position &pos) const {\n if (positions.empty()) {\n return false;\n }\n\n pos = positions.front();\n return true;\n}\n\nvoid WaypointList::clear() {\n positions.clear();\n}\n\nbool WaypointList::checkPosition() {\n if (positions.empty()) {\n return false;\n }\n\n if (_movechar->getPosition() == positions.front()) {\n positions.pop_front();\n }\n\n return true;\n}\n\nbool WaypointList::recalcStepList() {\n if (!checkPosition()) {\n return false;\n }\n\n if (positions.empty()) {\n return false;\n }\n\n steplist.clear();\n _movechar->getStepList(positions.front(), steplist);\n return (!steplist.empty());\n}\n\nbool WaypointList::makeMove() {\n if (steplist.empty()) {\n if (!recalcStepList()) {\n return false;\n }\n }\n\n if (!_movechar->move(steplist.front())) {\n return recalcStepList();\n }\n\n steplist.pop_front();\n return true;\n}\n<commit_msg>Abort route if destination cannot be reached<commit_after>\/\/ illarionserver - server for the game Illarion\n\/\/ Copyright 2011 Illarion e.V.\n\/\/\n\/\/ This file is part of illarionserver.\n\/\/\n\/\/ illarionserver is free software: you can redistribute it and\/or modify\n\/\/ it under the terms of the GNU Affero General Public License as published by\n\/\/ the Free Software Foundation, either version 3 of the License, or\n\/\/ (at your option) any later version.\n\/\/\n\/\/ illarionserver is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n\/\/ GNU Affero General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Affero General Public License\n\/\/ along with illarionserver. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n\n\n#include \"WaypointList.hpp\"\n#include \"World.hpp\"\n#include \"Field.hpp\"\n#include \"Logger.hpp\"\n\nWaypointList::WaypointList(Character *movechar) : _movechar(movechar) {\n\n}\n\nconst std::list<position> &WaypointList::getWaypoints() const {\n return positions;\n}\n\nvoid WaypointList::addWaypoint(const position &pos) {\n positions.push_back(pos);\n}\n\nbool WaypointList::getNextWaypoint(position &pos) const {\n if (positions.empty()) {\n return false;\n }\n\n pos = positions.front();\n return true;\n}\n\nvoid WaypointList::clear() {\n positions.clear();\n}\n\nbool WaypointList::checkPosition() {\n if (positions.empty()) {\n return false;\n }\n\n if (_movechar->getPosition() == positions.front()) {\n positions.pop_front();\n }\n\n return true;\n}\n\nbool WaypointList::recalcStepList() {\n if (!checkPosition()) {\n return false;\n }\n\n if (positions.empty()) {\n return false;\n }\n\n steplist.clear();\n _movechar->getStepList(positions.front(), steplist);\n return (!steplist.empty());\n}\n\nbool WaypointList::makeMove() {\n if (steplist.empty()) {\n if (!recalcStepList()) {\n return false;\n }\n }\n\n if (!_movechar->move(steplist.front())) {\n return steplist.size() > 1 && recalcStepList();\n }\n\n steplist.pop_front();\n return true;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: stlsheet.hxx,v $\n *\n * $Revision: 1.4 $\n *\n * last change: $Author: rt $ $Date: 2008-03-12 11:22:55 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef _SD_STLSHEET_HXX\n#define _SD_STLSHEET_HXX\n\n#include <rtl\/ref.hxx>\n\n#include <com\/sun\/star\/style\/XStyle.hpp>\n#include <com\/sun\/star\/beans\/XPropertySet.hpp>\n#include <com\/sun\/star\/lang\/XServiceInfo.hpp>\n#include <com\/sun\/star\/beans\/XPropertyState.hpp>\n#include <com\/sun\/star\/lang\/XComponent.hpp>\n#include <com\/sun\/star\/util\/XModifyBroadcaster.hpp>\n\n#include <cppuhelper\/interfacecontainer.h>\n#include <cppuhelper\/implbase5.hxx>\n#include <cppuhelper\/basemutex.hxx>\n\n#include <svtools\/style.hxx>\n\n#include <svx\/unoipset.hxx>\n\n#include <boost\/scoped_ptr.hpp>\n\nclass ModifyListenerForewarder;\n\ntypedef cppu::ImplInheritanceHelper5< SfxUnoStyleSheet,\n ::com::sun::star::beans::XPropertySet,\n ::com::sun::star::lang::XServiceInfo,\n ::com::sun::star::beans::XPropertyState,\n ::com::sun::star::util::XModifyBroadcaster,\n ::com::sun::star::lang::XComponent > SdStyleSheetBase ;\n\nclass SdStyleSheet : public SdStyleSheetBase, private ::cppu::BaseMutex\n{\npublic:\n SdStyleSheet( const rtl::OUString& rDisplayName, SfxStyleSheetBasePool& rPool, SfxStyleFamily eFamily, USHORT nMask );\n SdStyleSheet( const SdStyleSheet& );\n\n virtual BOOL SetParent (const String& rParentName);\n virtual SfxItemSet& GetItemSet();\n virtual BOOL IsUsed() const;\n virtual BOOL HasFollowSupport() const;\n virtual BOOL HasParentSupport() const;\n virtual BOOL HasClearParentSupport() const;\n virtual BOOL SetName( const UniString& );\n virtual void SetHelpId( const String& r, ULONG nId );\n\n void AdjustToFontHeight(SfxItemSet& rSet, BOOL bOnlyMissingItems = TRUE);\n\n SdStyleSheet* GetRealStyleSheet() const;\n SdStyleSheet* GetPseudoStyleSheet() const;\n\n void SetApiName( const ::rtl::OUString& rApiName );\n rtl::OUString GetApiName() const { return msApiName; }\n\n static rtl::OUString GetFamilyString( SfxStyleFamily eFamily );\n\n static SdStyleSheet* CreateEmptyUserStyle( SfxStyleSheetBasePool& rPool, SfxStyleFamily eFamily );\n\n \/\/ XInterface\n virtual void SAL_CALL release( ) throw ();\n\n \/\/ XServiceInfo\n virtual ::rtl::OUString SAL_CALL getImplementationName() throw(::com::sun::star::uno::RuntimeException);\n virtual sal_Bool SAL_CALL supportsService( const ::rtl::OUString& ServiceName ) throw(::com::sun::star::uno::RuntimeException);\n virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames() throw(::com::sun::star::uno::RuntimeException);\n\n \/\/ XNamed\n virtual ::rtl::OUString SAL_CALL getName( ) throw(::com::sun::star::uno::RuntimeException);\n virtual void SAL_CALL setName( const ::rtl::OUString& aName ) throw(::com::sun::star::uno::RuntimeException);\n\n \/\/ XStyle\n virtual sal_Bool SAL_CALL isUserDefined( ) throw(::com::sun::star::uno::RuntimeException);\n virtual sal_Bool SAL_CALL isInUse( ) throw(::com::sun::star::uno::RuntimeException);\n virtual ::rtl::OUString SAL_CALL getParentStyle( ) throw(::com::sun::star::uno::RuntimeException);\n virtual void SAL_CALL setParentStyle( const ::rtl::OUString& aParentStyle ) throw(::com::sun::star::container::NoSuchElementException, ::com::sun::star::uno::RuntimeException);\n\n \/\/ XPropertySet\n virtual ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySetInfo > SAL_CALL getPropertySetInfo() throw(::com::sun::star::uno::RuntimeException);\n virtual void SAL_CALL setPropertyValue( const ::rtl::OUString& aPropertyName, const ::com::sun::star::uno::Any& aValue ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::beans::PropertyVetoException, ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);\n virtual ::com::sun::star::uno::Any SAL_CALL getPropertyValue( const ::rtl::OUString& PropertyName ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);\n virtual void SAL_CALL addPropertyChangeListener( const ::rtl::OUString& aPropertyName, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertyChangeListener >& xListener ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);\n virtual void SAL_CALL removePropertyChangeListener( const ::rtl::OUString& aPropertyName, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertyChangeListener >& aListener ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);\n virtual void SAL_CALL addVetoableChangeListener( const ::rtl::OUString& PropertyName, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XVetoableChangeListener >& aListener ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);\n virtual void SAL_CALL removeVetoableChangeListener( const ::rtl::OUString& PropertyName, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XVetoableChangeListener >& aListener ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);\n\n \/\/ XPropertyState\n virtual ::com::sun::star::beans::PropertyState SAL_CALL getPropertyState( const ::rtl::OUString& PropertyName ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::uno::RuntimeException);\n virtual ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyState > SAL_CALL getPropertyStates( const ::com::sun::star::uno::Sequence< ::rtl::OUString >& aPropertyName ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::uno::RuntimeException);\n virtual void SAL_CALL setPropertyToDefault( const ::rtl::OUString& PropertyName ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::uno::RuntimeException);\n virtual ::com::sun::star::uno::Any SAL_CALL getPropertyDefault( const ::rtl::OUString& aPropertyName ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);\n\n \/\/ XModifyBroadcaster\n virtual void SAL_CALL addModifyListener( const ::com::sun::star::uno::Reference< ::com::sun::star::util::XModifyListener >& aListener ) throw (::com::sun::star::uno::RuntimeException);\n virtual void SAL_CALL removeModifyListener( const ::com::sun::star::uno::Reference< ::com::sun::star::util::XModifyListener >& aListener ) throw (::com::sun::star::uno::RuntimeException);\n\n \/\/ XComponent\n virtual void SAL_CALL dispose( ) throw (::com::sun::star::uno::RuntimeException);\n virtual void SAL_CALL addEventListener( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XEventListener >& xListener ) throw (::com::sun::star::uno::RuntimeException);\n virtual void SAL_CALL removeEventListener( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XEventListener >& aListener ) throw (::com::sun::star::uno::RuntimeException);\n\n void notifyModifyListener();\n\nprotected:\n const SfxItemPropertyMap* getPropertyMapEntry( const ::rtl::OUString& rPropertyName ) const throw();\n\n virtual void Load (SvStream& rIn, USHORT nVersion);\n virtual void Store(SvStream& rOut);\n\n virtual void SFX_NOTIFY(SfxBroadcaster& rBC, const TypeId& rBCType, const SfxHint& rHint, const TypeId& rHintType);\n virtual ~SdStyleSheet();\n\n void throwIfDisposed() throw (::com::sun::star::uno::RuntimeException);\n\n virtual void disposing();\n\n rtl::OUString msApiName;\n rtl::Reference< SfxStyleSheetBasePool > mxPool;\n\n \/** boradcast helper for events *\/\n ::cppu::OBroadcastHelper mrBHelper;\n\n boost::scoped_ptr< ModifyListenerForewarder > mpModifyListenerForewarder;\n\nprivate:\n SdStyleSheet& operator=( const SdStyleSheet& ); \/\/ not implemented\n};\n\ntypedef rtl::Reference< SdStyleSheet > SdStyleSheetRef;\ntypedef std::vector< SdStyleSheetRef > SdStyleSheetVector;\n\n#endif \/\/ _SD_STLSHEET_HXX\n\n\n\n<commit_msg>INTEGRATION: CWS impress140 (1.4.18); FILE MERGED 2008\/04\/03 09:32:19 cl 1.4.18.1: #i87588# fixed empty api name problem and set parent problem<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: stlsheet.hxx,v $\n *\n * $Revision: 1.5 $\n *\n * last change: $Author: kz $ $Date: 2008-04-04 12:44:44 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef _SD_STLSHEET_HXX\n#define _SD_STLSHEET_HXX\n\n#include <rtl\/ref.hxx>\n\n#include <com\/sun\/star\/style\/XStyle.hpp>\n#include <com\/sun\/star\/beans\/XPropertySet.hpp>\n#include <com\/sun\/star\/lang\/XServiceInfo.hpp>\n#include <com\/sun\/star\/beans\/XPropertyState.hpp>\n#include <com\/sun\/star\/lang\/XComponent.hpp>\n#include <com\/sun\/star\/util\/XModifyBroadcaster.hpp>\n\n#include <cppuhelper\/interfacecontainer.h>\n#include <cppuhelper\/implbase5.hxx>\n#include <cppuhelper\/basemutex.hxx>\n\n#include <svtools\/style.hxx>\n\n#include <svx\/unoipset.hxx>\n\n#include <boost\/scoped_ptr.hpp>\n\nclass ModifyListenerForewarder;\n\ntypedef cppu::ImplInheritanceHelper5< SfxUnoStyleSheet,\n ::com::sun::star::beans::XPropertySet,\n ::com::sun::star::lang::XServiceInfo,\n ::com::sun::star::beans::XPropertyState,\n ::com::sun::star::util::XModifyBroadcaster,\n ::com::sun::star::lang::XComponent > SdStyleSheetBase ;\n\nclass SdStyleSheet : public SdStyleSheetBase, private ::cppu::BaseMutex\n{\npublic:\n SdStyleSheet( const rtl::OUString& rDisplayName, SfxStyleSheetBasePool& rPool, SfxStyleFamily eFamily, USHORT nMask );\n SdStyleSheet( const SdStyleSheet& );\n\n virtual BOOL SetParent (const String& rParentName);\n virtual SfxItemSet& GetItemSet();\n virtual BOOL IsUsed() const;\n virtual BOOL HasFollowSupport() const;\n virtual BOOL HasParentSupport() const;\n virtual BOOL HasClearParentSupport() const;\n virtual BOOL SetName( const UniString& );\n virtual void SetHelpId( const String& r, ULONG nId );\n\n void AdjustToFontHeight(SfxItemSet& rSet, BOOL bOnlyMissingItems = TRUE);\n\n SdStyleSheet* GetRealStyleSheet() const;\n SdStyleSheet* GetPseudoStyleSheet() const;\n\n void SetApiName( const ::rtl::OUString& rApiName );\n rtl::OUString GetApiName() const;\n\n static rtl::OUString GetFamilyString( SfxStyleFamily eFamily );\n\n static SdStyleSheet* CreateEmptyUserStyle( SfxStyleSheetBasePool& rPool, SfxStyleFamily eFamily );\n\n \/\/ XInterface\n virtual void SAL_CALL release( ) throw ();\n\n \/\/ XServiceInfo\n virtual ::rtl::OUString SAL_CALL getImplementationName() throw(::com::sun::star::uno::RuntimeException);\n virtual sal_Bool SAL_CALL supportsService( const ::rtl::OUString& ServiceName ) throw(::com::sun::star::uno::RuntimeException);\n virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames() throw(::com::sun::star::uno::RuntimeException);\n\n \/\/ XNamed\n virtual ::rtl::OUString SAL_CALL getName( ) throw(::com::sun::star::uno::RuntimeException);\n virtual void SAL_CALL setName( const ::rtl::OUString& aName ) throw(::com::sun::star::uno::RuntimeException);\n\n \/\/ XStyle\n virtual sal_Bool SAL_CALL isUserDefined( ) throw(::com::sun::star::uno::RuntimeException);\n virtual sal_Bool SAL_CALL isInUse( ) throw(::com::sun::star::uno::RuntimeException);\n virtual ::rtl::OUString SAL_CALL getParentStyle( ) throw(::com::sun::star::uno::RuntimeException);\n virtual void SAL_CALL setParentStyle( const ::rtl::OUString& aParentStyle ) throw(::com::sun::star::container::NoSuchElementException, ::com::sun::star::uno::RuntimeException);\n\n \/\/ XPropertySet\n virtual ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySetInfo > SAL_CALL getPropertySetInfo() throw(::com::sun::star::uno::RuntimeException);\n virtual void SAL_CALL setPropertyValue( const ::rtl::OUString& aPropertyName, const ::com::sun::star::uno::Any& aValue ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::beans::PropertyVetoException, ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);\n virtual ::com::sun::star::uno::Any SAL_CALL getPropertyValue( const ::rtl::OUString& PropertyName ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);\n virtual void SAL_CALL addPropertyChangeListener( const ::rtl::OUString& aPropertyName, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertyChangeListener >& xListener ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);\n virtual void SAL_CALL removePropertyChangeListener( const ::rtl::OUString& aPropertyName, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertyChangeListener >& aListener ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);\n virtual void SAL_CALL addVetoableChangeListener( const ::rtl::OUString& PropertyName, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XVetoableChangeListener >& aListener ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);\n virtual void SAL_CALL removeVetoableChangeListener( const ::rtl::OUString& PropertyName, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XVetoableChangeListener >& aListener ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);\n\n \/\/ XPropertyState\n virtual ::com::sun::star::beans::PropertyState SAL_CALL getPropertyState( const ::rtl::OUString& PropertyName ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::uno::RuntimeException);\n virtual ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyState > SAL_CALL getPropertyStates( const ::com::sun::star::uno::Sequence< ::rtl::OUString >& aPropertyName ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::uno::RuntimeException);\n virtual void SAL_CALL setPropertyToDefault( const ::rtl::OUString& PropertyName ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::uno::RuntimeException);\n virtual ::com::sun::star::uno::Any SAL_CALL getPropertyDefault( const ::rtl::OUString& aPropertyName ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);\n\n \/\/ XModifyBroadcaster\n virtual void SAL_CALL addModifyListener( const ::com::sun::star::uno::Reference< ::com::sun::star::util::XModifyListener >& aListener ) throw (::com::sun::star::uno::RuntimeException);\n virtual void SAL_CALL removeModifyListener( const ::com::sun::star::uno::Reference< ::com::sun::star::util::XModifyListener >& aListener ) throw (::com::sun::star::uno::RuntimeException);\n\n \/\/ XComponent\n virtual void SAL_CALL dispose( ) throw (::com::sun::star::uno::RuntimeException);\n virtual void SAL_CALL addEventListener( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XEventListener >& xListener ) throw (::com::sun::star::uno::RuntimeException);\n virtual void SAL_CALL removeEventListener( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XEventListener >& aListener ) throw (::com::sun::star::uno::RuntimeException);\n\n void notifyModifyListener();\n\nprotected:\n const SfxItemPropertyMap* getPropertyMapEntry( const ::rtl::OUString& rPropertyName ) const throw();\n\n virtual void Load (SvStream& rIn, USHORT nVersion);\n virtual void Store(SvStream& rOut);\n\n virtual void SFX_NOTIFY(SfxBroadcaster& rBC, const TypeId& rBCType, const SfxHint& rHint, const TypeId& rHintType);\n virtual ~SdStyleSheet();\n\n void throwIfDisposed() throw (::com::sun::star::uno::RuntimeException);\n\n virtual void disposing();\n\n rtl::OUString msApiName;\n rtl::Reference< SfxStyleSheetBasePool > mxPool;\n\n \/** boradcast helper for events *\/\n ::cppu::OBroadcastHelper mrBHelper;\n\n boost::scoped_ptr< ModifyListenerForewarder > mpModifyListenerForewarder;\n\nprivate:\n SdStyleSheet& operator=( const SdStyleSheet& ); \/\/ not implemented\n};\n\ntypedef rtl::Reference< SdStyleSheet > SdStyleSheetRef;\ntypedef std::vector< SdStyleSheetRef > SdStyleSheetVector;\n\n#endif \/\/ _SD_STLSHEET_HXX\n\n\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file\n\/\/ for details. All rights reserved. Use of this source code is governed by a\n\/\/ BSD-style license that can be found in the LICENSE file.\n\n#include \"include\/dart_native_api.h\"\n\n#include \"platform\/assert.h\"\n#include \"vm\/dart_api_impl.h\"\n#include \"vm\/dart_api_message.h\"\n#include \"vm\/dart_api_state.h\"\n#include \"vm\/message.h\"\n#include \"vm\/native_message_handler.h\"\n#include \"vm\/port.h\"\n\nnamespace dart {\n\n\/\/ --- Message sending\/receiving from native code ---\n\nstatic uint8_t* allocator(uint8_t* ptr, intptr_t old_size, intptr_t new_size) {\n void* new_ptr = realloc(reinterpret_cast<void*>(ptr), new_size);\n return reinterpret_cast<uint8_t*>(new_ptr);\n}\n\n\nclass IsolateSaver {\n public:\n explicit IsolateSaver(Isolate* current_isolate)\n : saved_isolate_(current_isolate) {\n if (current_isolate != NULL) {\n ASSERT(current_isolate == Isolate::Current());\n Thread::ExitIsolate();\n }\n }\n ~IsolateSaver() {\n if (saved_isolate_ != NULL) {\n Thread::EnterIsolate(saved_isolate_);\n }\n }\n private:\n Isolate* saved_isolate_;\n\n DISALLOW_COPY_AND_ASSIGN(IsolateSaver);\n};\n\n\nDART_EXPORT bool Dart_PostCObject(Dart_Port port_id, Dart_CObject* message) {\n uint8_t* buffer = NULL;\n ApiMessageWriter writer(&buffer, allocator);\n bool success = writer.WriteCMessage(message);\n\n if (!success) return success;\n\n \/\/ Post the message at the given port.\n return PortMap::PostMessage(new Message(\n port_id, buffer, writer.BytesWritten(), Message::kNormalPriority));\n}\n\n\nDART_EXPORT bool Dart_PostInteger(Dart_Port port_id, int64_t message) {\n if (Smi::IsValid(message)) {\n return PortMap::PostMessage(new Message(\n port_id, Smi::New(message), Message::kNormalPriority));\n }\n Dart_CObject cobj;\n cobj.type = Dart_CObject_kInt64;\n cobj.value.as_int64 = message;\n return Dart_PostCObject(port_id, &cobj);\n}\n\n\nDART_EXPORT Dart_Port Dart_NewNativePort(const char* name,\n Dart_NativeMessageHandler handler,\n bool handle_concurrently) {\n if (name == NULL) {\n name = \"<UnnamedNativePort>\";\n }\n if (handler == NULL) {\n OS::PrintErr(\"%s expects argument 'handler' to be non-null.\\n\",\n CURRENT_FUNC);\n return ILLEGAL_PORT;\n }\n \/\/ Start the native port without a current isolate.\n IsolateSaver saver(Isolate::Current());\n\n NativeMessageHandler* nmh = new NativeMessageHandler(name, handler);\n Dart_Port port_id = PortMap::CreatePort(nmh);\n nmh->Run(Dart::thread_pool(), NULL, NULL, 0);\n return port_id;\n}\n\n\nDART_EXPORT bool Dart_CloseNativePort(Dart_Port native_port_id) {\n \/\/ Close the native port without a current isolate.\n IsolateSaver saver(Isolate::Current());\n\n \/\/ TODO(turnidge): Check that the port is native before trying to close.\n return PortMap::ClosePort(native_port_id);\n}\n\n\n\/\/ --- Verification tools ---\n\nstatic void CompileAll(Thread* thread, Dart_Handle* result) {\n ASSERT(thread != NULL);\n const Error& error = Error::Handle(thread->zone(), Library::CompileAll());\n if (error.IsNull()) {\n *result = Api::Success();\n } else {\n *result = Api::NewHandle(thread, error.raw());\n }\n}\n\n\nDART_EXPORT Dart_Handle Dart_CompileAll() {\n DARTSCOPE(Thread::Current());\n Dart_Handle result = Api::CheckAndFinalizePendingClasses(T);\n if (::Dart_IsError(result)) {\n return result;\n }\n CHECK_CALLBACK_STATE(T);\n CompileAll(T, &result);\n return result;\n}\n\n} \/\/ namespace dart\n<commit_msg>Fix build<commit_after>\/\/ Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file\n\/\/ for details. All rights reserved. Use of this source code is governed by a\n\/\/ BSD-style license that can be found in the LICENSE file.\n\n#include \"include\/dart_native_api.h\"\n\n#include \"platform\/assert.h\"\n#include \"vm\/dart_api_impl.h\"\n#include \"vm\/dart_api_message.h\"\n#include \"vm\/dart_api_state.h\"\n#include \"vm\/message.h\"\n#include \"vm\/native_message_handler.h\"\n#include \"vm\/port.h\"\n\nnamespace dart {\n\n\/\/ --- Message sending\/receiving from native code ---\n\nstatic uint8_t* allocator(uint8_t* ptr, intptr_t old_size, intptr_t new_size) {\n void* new_ptr = realloc(reinterpret_cast<void*>(ptr), new_size);\n return reinterpret_cast<uint8_t*>(new_ptr);\n}\n\n\nclass IsolateSaver {\n public:\n explicit IsolateSaver(Isolate* current_isolate)\n : saved_isolate_(current_isolate) {\n if (current_isolate != NULL) {\n ASSERT(current_isolate == Isolate::Current());\n Thread::ExitIsolate();\n }\n }\n ~IsolateSaver() {\n if (saved_isolate_ != NULL) {\n Thread::EnterIsolate(saved_isolate_);\n }\n }\n private:\n Isolate* saved_isolate_;\n\n DISALLOW_COPY_AND_ASSIGN(IsolateSaver);\n};\n\n\nstatic bool PostCObjectHelper(Dart_Port port_id, Dart_CObject* message) {\n uint8_t* buffer = NULL;\n ApiMessageWriter writer(&buffer, allocator);\n bool success = writer.WriteCMessage(message);\n\n if (!success) return success;\n\n \/\/ Post the message at the given port.\n return PortMap::PostMessage(new Message(\n port_id, buffer, writer.BytesWritten(), Message::kNormalPriority));\n}\n\n\nDART_EXPORT bool Dart_PostCObject(Dart_Port port_id, Dart_CObject* message) {\n return PostCObjectHelper(port_id, message);\n}\n\n\nDART_EXPORT bool Dart_PostInteger(Dart_Port port_id, int64_t message) {\n if (Smi::IsValid(message)) {\n return PortMap::PostMessage(new Message(\n port_id, Smi::New(message), Message::kNormalPriority));\n }\n Dart_CObject cobj;\n cobj.type = Dart_CObject_kInt64;\n cobj.value.as_int64 = message;\n return PostCObjectHelper(port_id, &cobj);\n}\n\n\nDART_EXPORT Dart_Port Dart_NewNativePort(const char* name,\n Dart_NativeMessageHandler handler,\n bool handle_concurrently) {\n if (name == NULL) {\n name = \"<UnnamedNativePort>\";\n }\n if (handler == NULL) {\n OS::PrintErr(\"%s expects argument 'handler' to be non-null.\\n\",\n CURRENT_FUNC);\n return ILLEGAL_PORT;\n }\n \/\/ Start the native port without a current isolate.\n IsolateSaver saver(Isolate::Current());\n\n NativeMessageHandler* nmh = new NativeMessageHandler(name, handler);\n Dart_Port port_id = PortMap::CreatePort(nmh);\n nmh->Run(Dart::thread_pool(), NULL, NULL, 0);\n return port_id;\n}\n\n\nDART_EXPORT bool Dart_CloseNativePort(Dart_Port native_port_id) {\n \/\/ Close the native port without a current isolate.\n IsolateSaver saver(Isolate::Current());\n\n \/\/ TODO(turnidge): Check that the port is native before trying to close.\n return PortMap::ClosePort(native_port_id);\n}\n\n\n\/\/ --- Verification tools ---\n\nstatic void CompileAll(Thread* thread, Dart_Handle* result) {\n ASSERT(thread != NULL);\n const Error& error = Error::Handle(thread->zone(), Library::CompileAll());\n if (error.IsNull()) {\n *result = Api::Success();\n } else {\n *result = Api::NewHandle(thread, error.raw());\n }\n}\n\n\nDART_EXPORT Dart_Handle Dart_CompileAll() {\n DARTSCOPE(Thread::Current());\n Dart_Handle result = Api::CheckAndFinalizePendingClasses(T);\n if (::Dart_IsError(result)) {\n return result;\n }\n CHECK_CALLBACK_STATE(T);\n CompileAll(T, &result);\n return result;\n}\n\n} \/\/ namespace dart\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright 2016,2017 Marcus Soll\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"trainer.h\"\n\n#include <QtCore\/QtMath>\n#include <QDate>\n\nTrainer::Trainer(QObject *parent) : QObject(parent),\n _modus(GUESS_TRANSLATION),\n _index(0),\n _vocabulary(),\n _sum(0),\n _rnd(),\n _settings()\n{\n}\n\nQString Trainer::word()\n{\n if(_vocabulary.size() == 0)\n {\n return \"\";\n }\n return _vocabulary[_index].word;\n}\n\nQString Trainer::translation()\n{\n if(_vocabulary.size() == 0)\n {\n return \"\";\n }\n return _vocabulary[_index].translation;\n}\n\nTrainer::trainings_modus Trainer::modus()\n{\n return _modus;\n}\n\nint Trainer::language()\n{\n if(_vocabulary.size() == 0)\n {\n return -1;\n }\n return _vocabulary[_index].language;\n}\n\nbool Trainer::load_vocabulary(QVariantList filter_type, QVariantList filter_argv)\n{\n if(filter_type.size() != filter_argv.size())\n {\n WARNING(\"filter_type and filter_argv must have same size!\" << filter_type.size() << filter_argv.size());\n return false;\n }\n \n \/\/ Init vocabulary list\n bool first_where = true;\n QString s = \"SELECT rowid,word,translation,priority,language FROM vocabulary\";\n QSqlQuery q(database);\n\n for(int i = 0; i < filter_type.size(); ++i)\n {\n if(first_where)\n {\n s.append(\" WHERE \");\n }\n else\n {\n s.append(\" AND \");\n }\n\n if(!filter_type[i].canConvert<int>())\n {\n WARNING(QString(\"Can not convert %1 to filter\").arg(filter_type[i].typeName()));\n return false;\n }\n int int_type = filter_type[i].toInt();\n if(int_type <= 0 || int_type >= filters_after_enum)\n {\n WARNING(\"Filter type\" << int_type << \"out of range\");\n return false;\n }\n\n switch(static_cast<filters>(int_type))\n {\n case LANGUAGE:\n s.append(\"language=?\");\n break;\n case MODIFICATION_SINCE:\n s.append(\"modification >= ?\");\n break;\n case MODIFICATION_UNTIL:\n s.append(\"modification <= ?\");\n break;\n case CREATION_SINCE:\n s.append(\"creation >= ?\");\n break;\n case CREATION_UNTIL:\n s.append(\"creation <= ?\");\n break;\n case filters_after_enum:\n WARNING(\"filters_after_enum received\");\n return false;\n break;\n default:\n Q_UNREACHABLE();\n WARNING(\"Impossible filter type\");\n return false;\n break;\n }\n }\n\n DEBUG(s);\n\n q.prepare(s);\n\n for(int i = 0; i < filter_type.size(); ++i)\n {\n if(first_where)\n {\n s.append(\" WHERE \");\n }\n else\n {\n s.append(\" AND \");\n }\n\n if(!filter_type[i].canConvert<int>())\n {\n WARNING(QString(\"Can not convert %1 to filter\").arg(filter_type[i].typeName()));\n return false;\n }\n int int_type = filter_type[i].toInt();\n if(int_type <= 0 || int_type >= filters_after_enum)\n {\n WARNING(\"Filter type\" << int_type << \"out of range\");\n return false;\n }\n\n switch(static_cast<filters>(int_type))\n {\n case LANGUAGE:\n q.addBindValue(filter_argv[i].toInt());\n break;\n case MODIFICATION_SINCE:\n case MODIFICATION_UNTIL:\n case CREATION_SINCE:\n case CREATION_UNTIL:\n q.addBindValue(filter_argv[i].toDate().toJulianDay());\n break;\n case filters_after_enum:\n WARNING(\"filters_after_enum received\");\n return false;\n break;\n default:\n Q_UNREACHABLE();\n WARNING(\"Impossible filter type\");\n return false;\n break;\n }\n }\n\n if(!q.exec())\n {\n QString error = s;\n error.append(\": \").append(q.lastError().text());\n WARNING(error);\n return false;\n }\n else\n {\n if(!q.isSelect())\n {\n QString error = s;\n error.append(\": No select\");\n WARNING(error);\n return false;\n }\n else\n {\n while(q.next())\n {\n vocabulary v;\n v.id = q.value(0).toInt();\n v.word = q.value(1).toString();\n v.translation = q.value(2).toString();\n v.priority = q.value(3).toInt();\n v.language = q.value(4).toInt();\n _sum += v.priority;\n _vocabulary.append(v);\n }\n }\n }\n\n return _vocabulary.size() != 0;\n}\n\nint Trainer::count_vocabulary(QVariantList filter_type, QVariantList filter_argv)\n{\n if(filter_type.size() != filter_argv.size())\n {\n WARNING(\"filter_type and filter_argv must have same size!\" << filter_type.size() << filter_argv.size());\n return 0;\n }\n\n \/\/ Init vocabulary list\n bool first_where = true;\n QString s = \"SELECT count(*) FROM vocabulary\";\n QSqlQuery q(database);\n\n for(int i = 0; i < filter_type.size(); ++i)\n {\n if(first_where)\n {\n s.append(\" WHERE \");\n }\n else\n {\n s.append(\" AND \");\n }\n\n if(!filter_type[i].canConvert<int>())\n {\n WARNING(QString(\"Can not convert %1 to filter\").arg(filter_type[i].typeName()));\n return 0;\n }\n int int_type = filter_type[i].toInt();\n if(int_type <= 0 || int_type >= filters_after_enum)\n {\n WARNING(\"Filter type\" << int_type << \"out of range\");\n return 0;\n }\n\n switch(static_cast<filters>(int_type))\n {\n case LANGUAGE:\n s.append(\"language=?\");\n break;\n case MODIFICATION_SINCE:\n s.append(\"modification >= ?\");\n break;\n case MODIFICATION_UNTIL:\n s.append(\"modification <= ?\");\n break;\n case CREATION_SINCE:\n s.append(\"creation >= ?\");\n break;\n case CREATION_UNTIL:\n s.append(\"creation <= ?\");\n break;\n case filters_after_enum:\n WARNING(\"filters_after_enum received\");\n return 0;\n break;\n default:\n Q_UNREACHABLE();\n WARNING(\"Impossible filter type\");\n return 0;\n break;\n }\n }\n\n DEBUG(s);\n\n q.prepare(s);\n\n for(int i = 0; i < filter_type.size(); ++i)\n {\n if(first_where)\n {\n s.append(\" WHERE \");\n }\n else\n {\n s.append(\" AND \");\n }\n\n if(!filter_type[i].canConvert<int>())\n {\n WARNING(QString(\"Can not convert %1 to filter\").arg(filter_type[i].typeName()));\n return 0;\n }\n int int_type = filter_type[i].toInt();\n if(int_type <= 0 || int_type >= filters_after_enum)\n {\n WARNING(\"Filter type\" << int_type << \"out of range\");\n return 0;\n }\n\n switch(static_cast<filters>(int_type))\n {\n case LANGUAGE:\n q.addBindValue(filter_argv[i].toInt());\n break;\n case MODIFICATION_SINCE:\n case MODIFICATION_UNTIL:\n case CREATION_SINCE:\n case CREATION_UNTIL:\n q.addBindValue(filter_argv[i].toDate().toJulianDay());\n break;\n case filters_after_enum:\n WARNING(\"filters_after_enum received\");\n return 0;\n break;\n default:\n Q_UNREACHABLE();\n WARNING(\"Impossible filter type\");\n return 0;\n break;\n }\n }\n\n if(!q.exec())\n {\n QString error = s;\n error.append(\": \").append(q.lastError().text());\n WARNING(error);\n return 0;\n }\n else\n {\n if(!q.isSelect())\n {\n QString error = s;\n error.append(\": No select\");\n WARNING(error);\n return 0;\n }\n else\n {\n if(!q.next())\n {\n QString error = s;\n error.append(\" - no value: \").append(q.lastError().text());\n WARNING(error);\n return 0;\n\n }\n return q.value(0).toInt();\n }\n }\n\n return 0;\n}\n\n\nvoid Trainer::next()\n{\n std::uniform_int_distribution<int> distribution;\n if(_settings.adaptiveTrainingEnabled())\n {\n \/\/ Use adaptive mode\n distribution = std::uniform_int_distribution<int>(1, _sum);\n int selected_priority = distribution(_rnd);\n int sum = 0;\n\n for(int i = 0; i < _vocabulary.size(); ++i)\n {\n sum += _vocabulary[i].priority;\n if(sum >= selected_priority)\n {\n _index = i;\n break;\n }\n }\n }\n else\n {\n \/\/ Select random (no adaptive mode)\n distribution = std::uniform_int_distribution<int>(0, _vocabulary.size() - 1);\n _index = distribution(_rnd);\n }\n\n distribution = std::uniform_int_distribution<int>(0, 1);\n if(distribution(_rnd) == 0)\n {\n _modus = GUESS_TRANSLATION;\n }\n else\n {\n _modus = GUESS_WORD;\n }\n\n emit wordChanged(_vocabulary[_index].word);\n emit translationChanged(_vocabulary[_index].translation);\n emit modusChanged(_modus);\n emit languageChanged(_vocabulary[_index].language);\n}\n\nvoid Trainer::correct()\n{\n if(_settings.adaptiveTrainingEnabled())\n {\n _sum -= _vocabulary[_index].priority;\n _vocabulary[_index].priority = qMax(1, _vocabulary[_index].priority - _settings.adaptiveTrainingCorrectPoints());\n _sum += _vocabulary[_index].priority;\n\n QString s = \"UPDATE vocabulary SET priority=:p WHERE rowid=:id\";\n QSqlQuery q(database);\n q.prepare(s);\n q.bindValue(\":p\", _vocabulary[_index].priority);\n q.bindValue(\":id\", _vocabulary[_index].id);\n\n if(!q.exec())\n {\n QString error = s;\n error.append(\": \").append(q.lastError().text());\n WARNING(error);\n }\n }\n}\n\nvoid Trainer::wrong()\n{\n if(_settings.adaptiveTrainingEnabled())\n {\n _sum -= _vocabulary[_index].priority;\n _vocabulary[_index].priority = qMin(100, _vocabulary[_index].priority + _settings.adaptiveTrainingWrongPoints());\n _sum += _vocabulary[_index].priority;\n\n QString s = \"UPDATE vocabulary SET priority=:p WHERE rowid=:id\";\n QSqlQuery q(database);\n q.prepare(s);\n q.bindValue(\":p\", _vocabulary[_index].priority);\n q.bindValue(\":id\", _vocabulary[_index].id);\n\n if(!q.exec())\n {\n QString error = s;\n error.append(\": \").append(q.lastError().text());\n WARNING(error);\n }\n }\n}\n<commit_msg>Fixed SQL commands<commit_after>\/*\n * Copyright 2016,2017 Marcus Soll\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"trainer.h\"\n\n#include <QtCore\/QtMath>\n#include <QDate>\n\nTrainer::Trainer(QObject *parent) : QObject(parent),\n _modus(GUESS_TRANSLATION),\n _index(0),\n _vocabulary(),\n _sum(0),\n _rnd(),\n _settings()\n{\n}\n\nQString Trainer::word()\n{\n if(_vocabulary.size() == 0)\n {\n return \"\";\n }\n return _vocabulary[_index].word;\n}\n\nQString Trainer::translation()\n{\n if(_vocabulary.size() == 0)\n {\n return \"\";\n }\n return _vocabulary[_index].translation;\n}\n\nTrainer::trainings_modus Trainer::modus()\n{\n return _modus;\n}\n\nint Trainer::language()\n{\n if(_vocabulary.size() == 0)\n {\n return -1;\n }\n return _vocabulary[_index].language;\n}\n\nbool Trainer::load_vocabulary(QVariantList filter_type, QVariantList filter_argv)\n{\n if(filter_type.size() != filter_argv.size())\n {\n WARNING(\"filter_type and filter_argv must have same size!\" << filter_type.size() << filter_argv.size());\n return false;\n }\n \n \/\/ Init vocabulary list\n bool first_where = true;\n QString s = \"SELECT rowid,word,translation,priority,language FROM vocabulary\";\n QSqlQuery q(database);\n\n for(int i = 0; i < filter_type.size(); ++i)\n {\n if(first_where)\n {\n s.append(\" WHERE \");\n }\n else\n {\n s.append(\" AND \");\n }\n first_where = false;\n\n if(!filter_type[i].canConvert<int>())\n {\n WARNING(QString(\"Can not convert %1 to filter\").arg(filter_type[i].typeName()));\n return false;\n }\n int int_type = filter_type[i].toInt();\n if(int_type <= 0 || int_type >= filters_after_enum)\n {\n WARNING(\"Filter type\" << int_type << \"out of range\");\n return false;\n }\n\n switch(static_cast<filters>(int_type))\n {\n case LANGUAGE:\n s.append(\"language=?\");\n break;\n case MODIFICATION_SINCE:\n s.append(\"modification >= ?\");\n break;\n case MODIFICATION_UNTIL:\n s.append(\"modification <= ?\");\n break;\n case CREATION_SINCE:\n s.append(\"creation >= ?\");\n break;\n case CREATION_UNTIL:\n s.append(\"creation <= ?\");\n break;\n case filters_after_enum:\n WARNING(\"filters_after_enum received\");\n return false;\n break;\n default:\n Q_UNREACHABLE();\n WARNING(\"Impossible filter type\");\n return false;\n break;\n }\n }\n\n DEBUG(s);\n\n q.prepare(s);\n\n for(int i = 0; i < filter_type.size(); ++i)\n {\n if(!filter_type[i].canConvert<int>())\n {\n WARNING(QString(\"Can not convert %1 to filter\").arg(filter_type[i].typeName()));\n return false;\n }\n int int_type = filter_type[i].toInt();\n if(int_type <= 0 || int_type >= filters_after_enum)\n {\n WARNING(\"Filter type\" << int_type << \"out of range\");\n return false;\n }\n\n switch(static_cast<filters>(int_type))\n {\n case LANGUAGE:\n q.addBindValue(filter_argv[i].toInt());\n break;\n case MODIFICATION_SINCE:\n case MODIFICATION_UNTIL:\n case CREATION_SINCE:\n case CREATION_UNTIL:\n q.addBindValue(filter_argv[i].toDate().toJulianDay());\n break;\n case filters_after_enum:\n WARNING(\"filters_after_enum received\");\n return false;\n break;\n default:\n Q_UNREACHABLE();\n WARNING(\"Impossible filter type\");\n return false;\n break;\n }\n }\n\n if(!q.exec())\n {\n QString error = s;\n error.append(\": \").append(q.lastError().text());\n WARNING(error);\n return false;\n }\n else\n {\n if(!q.isSelect())\n {\n QString error = s;\n error.append(\": No select\");\n WARNING(error);\n return false;\n }\n else\n {\n while(q.next())\n {\n vocabulary v;\n v.id = q.value(0).toInt();\n v.word = q.value(1).toString();\n v.translation = q.value(2).toString();\n v.priority = q.value(3).toInt();\n v.language = q.value(4).toInt();\n _sum += v.priority;\n _vocabulary.append(v);\n }\n }\n }\n\n return _vocabulary.size() != 0;\n}\n\nint Trainer::count_vocabulary(QVariantList filter_type, QVariantList filter_argv)\n{\n if(filter_type.size() != filter_argv.size())\n {\n WARNING(\"filter_type and filter_argv must have same size!\" << filter_type.size() << filter_argv.size());\n return 0;\n }\n\n \/\/ Init vocabulary list\n bool first_where = true;\n QString s = \"SELECT count(*) FROM vocabulary\";\n QSqlQuery q(database);\n\n for(int i = 0; i < filter_type.size(); ++i)\n {\n if(first_where)\n {\n s.append(\" WHERE \");\n }\n else\n {\n s.append(\" AND \");\n }\n first_where = false;\n\n if(!filter_type[i].canConvert<int>())\n {\n WARNING(QString(\"Can not convert %1 to filter\").arg(filter_type[i].typeName()));\n return 0;\n }\n int int_type = filter_type[i].toInt();\n if(int_type <= 0 || int_type >= filters_after_enum)\n {\n WARNING(\"Filter type\" << int_type << \"out of range\");\n return 0;\n }\n\n switch(static_cast<filters>(int_type))\n {\n case LANGUAGE:\n s.append(\"language=?\");\n break;\n case MODIFICATION_SINCE:\n s.append(\"modification >= ?\");\n break;\n case MODIFICATION_UNTIL:\n s.append(\"modification <= ?\");\n break;\n case CREATION_SINCE:\n s.append(\"creation >= ?\");\n break;\n case CREATION_UNTIL:\n s.append(\"creation <= ?\");\n break;\n case filters_after_enum:\n WARNING(\"filters_after_enum received\");\n return 0;\n break;\n default:\n Q_UNREACHABLE();\n WARNING(\"Impossible filter type\");\n return 0;\n break;\n }\n }\n\n DEBUG(s);\n\n q.prepare(s);\n\n for(int i = 0; i < filter_type.size(); ++i)\n {\n if(!filter_type[i].canConvert<int>())\n {\n WARNING(QString(\"Can not convert %1 to filter\").arg(filter_type[i].typeName()));\n return 0;\n }\n int int_type = filter_type[i].toInt();\n if(int_type <= 0 || int_type >= filters_after_enum)\n {\n WARNING(\"Filter type\" << int_type << \"out of range\");\n return 0;\n }\n\n switch(static_cast<filters>(int_type))\n {\n case LANGUAGE:\n q.addBindValue(filter_argv[i].toInt());\n break;\n case MODIFICATION_SINCE:\n case MODIFICATION_UNTIL:\n case CREATION_SINCE:\n case CREATION_UNTIL:\n q.addBindValue(filter_argv[i].toDate().toJulianDay());\n break;\n case filters_after_enum:\n WARNING(\"filters_after_enum received\");\n return 0;\n break;\n default:\n Q_UNREACHABLE();\n WARNING(\"Impossible filter type\");\n return 0;\n break;\n }\n }\n\n if(!q.exec())\n {\n QString error = s;\n error.append(\": \").append(q.lastError().text());\n WARNING(error);\n return 0;\n }\n else\n {\n if(!q.isSelect())\n {\n QString error = s;\n error.append(\": No select\");\n WARNING(error);\n return 0;\n }\n else\n {\n if(!q.next())\n {\n QString error = s;\n error.append(\" - no value: \").append(q.lastError().text());\n WARNING(error);\n return 0;\n\n }\n return q.value(0).toInt();\n }\n }\n\n return 0;\n}\n\n\nvoid Trainer::next()\n{\n std::uniform_int_distribution<int> distribution;\n if(_settings.adaptiveTrainingEnabled())\n {\n \/\/ Use adaptive mode\n distribution = std::uniform_int_distribution<int>(1, _sum);\n int selected_priority = distribution(_rnd);\n int sum = 0;\n\n for(int i = 0; i < _vocabulary.size(); ++i)\n {\n sum += _vocabulary[i].priority;\n if(sum >= selected_priority)\n {\n _index = i;\n break;\n }\n }\n }\n else\n {\n \/\/ Select random (no adaptive mode)\n distribution = std::uniform_int_distribution<int>(0, _vocabulary.size() - 1);\n _index = distribution(_rnd);\n }\n\n distribution = std::uniform_int_distribution<int>(0, 1);\n if(distribution(_rnd) == 0)\n {\n _modus = GUESS_TRANSLATION;\n }\n else\n {\n _modus = GUESS_WORD;\n }\n\n emit wordChanged(_vocabulary[_index].word);\n emit translationChanged(_vocabulary[_index].translation);\n emit modusChanged(_modus);\n emit languageChanged(_vocabulary[_index].language);\n}\n\nvoid Trainer::correct()\n{\n if(_settings.adaptiveTrainingEnabled())\n {\n _sum -= _vocabulary[_index].priority;\n _vocabulary[_index].priority = qMax(1, _vocabulary[_index].priority - _settings.adaptiveTrainingCorrectPoints());\n _sum += _vocabulary[_index].priority;\n\n QString s = \"UPDATE vocabulary SET priority=:p WHERE rowid=:id\";\n QSqlQuery q(database);\n q.prepare(s);\n q.bindValue(\":p\", _vocabulary[_index].priority);\n q.bindValue(\":id\", _vocabulary[_index].id);\n\n if(!q.exec())\n {\n QString error = s;\n error.append(\": \").append(q.lastError().text());\n WARNING(error);\n }\n }\n}\n\nvoid Trainer::wrong()\n{\n if(_settings.adaptiveTrainingEnabled())\n {\n _sum -= _vocabulary[_index].priority;\n _vocabulary[_index].priority = qMin(100, _vocabulary[_index].priority + _settings.adaptiveTrainingWrongPoints());\n _sum += _vocabulary[_index].priority;\n\n QString s = \"UPDATE vocabulary SET priority=:p WHERE rowid=:id\";\n QSqlQuery q(database);\n q.prepare(s);\n q.bindValue(\":p\", _vocabulary[_index].priority);\n q.bindValue(\":id\", _vocabulary[_index].id);\n\n if(!q.exec())\n {\n QString error = s;\n error.append(\": \").append(q.lastError().text());\n WARNING(error);\n }\n }\n}\n<|endoftext|>"} {"text":"<commit_before>#ifdef HAVE_CMAKE_CONFIG\n #include \"cmake_config.h\"\n#elif defined (HAVE_CONFIG_H)\n #include <config.h>\n#endif \/\/ HAVE_CMAKE_CONFIG\n\n#include <iostream>\n\n#include <boost\/filesystem.hpp>\n\n#include <dune\/common\/exceptions.hh>\n#include <dune\/common\/shared_ptr.hh>\n#include <dune\/common\/mpihelper.hh>\n#include <dune\/common\/timer.hh>\n\n#include <dune\/stuff\/common\/parameter\/tree.hh>\n#include <dune\/stuff\/common\/logging.hh>\n#include <dune\/stuff\/common\/filesystem.hh>\n#include <dune\/stuff\/common\/string.hh>\n#include <dune\/stuff\/grid\/provider.hh>\n\nconst std::string id = \"grid.providers\";\n\n\/**\n \\brief Creates a parameter file if it does not exist.\n\n Nothing is done if the file already exists. If not, a parameter file will be created with all neccessary\n keys and values.\n \\param[in] filename\n (Relative) path to the file.\n **\/\nvoid ensureParamFile(std::string filename)\n{\n Dune::Stuff::Common::testCreateDirectory(filename);\n if (!boost::filesystem::exists(filename)) {\n std::ofstream file;\n file.open(filename);\n file << \"[\" << id << \"]\" << std::endl;\n file << \"grid = stuff.grid.provider.cube\" << std::endl;\n file << \"filename = \" << id << \".grid\"<< std::endl;\n file << \"[stuff.grid.provider.cube]\" << std::endl;\n file << \"lowerLeft = [0.0; 0.0; 0.0]\" << std::endl;\n file << \"upperRight = [1.0; 1.0; 1.0]\" << std::endl;\n file << \"numElements = [4; 4; 4]\" << std::endl;\n file << \"[stuff.grid.provider.gmsh]\" << std::endl;\n file << \"filename = curved2d.msh\" << std::endl;\n file.close();\n } \/\/ only write param file if there is none\n} \/\/ void ensureParamFile()\n\ntemplate< class GridViewType >\nunsigned int measureTiming(const GridViewType& gridView)\n{\n unsigned int elements = 0;\n for (typename GridViewType::template Codim< 0 >::Iterator it = gridView.template begin< 0 >();\n it != gridView.template end< 0 >();\n ++it)\n ++elements;\n return elements;\n} \/\/ unsigned int measureTiming(const GridViewType& gridView)\n\n\/**\n * \\todo Move gmsh into seperate examples, since it does not compile with YaspGrid and SGrid!\n *\/\nint main(int argc, char** argv)\n{\n try {\n \/\/ mpi\n Dune::MPIHelper::instance(argc, argv);\n\n \/\/ parameter\n const std::string filename = id + \".param\";\n ensureParamFile(filename);\n Dune::Stuff::Common::ExtendedParameterTree paramTree(argc, argv, filename);\n if (!paramTree.hasSub(id))\n DUNE_THROW(Dune::RangeError,\n \"\\nMissing sub '\" << id << \"' in the following Dune::ParameterTree:\\n\" << paramTree.reportString(\" \"));\n\n \/\/ logger\n Dune::Stuff::Common::Logger().create(Dune::Stuff::Common::LOG_INFO |\n Dune::Stuff::Common::LOG_CONSOLE |\n Dune::Stuff::Common::LOG_DEBUG);\n Dune::Stuff::Common::LogStream& info = Dune::Stuff::Common::Logger().info();\n\n \/\/ timer\n Dune::Timer timer;\n\n \/\/ grid\n info << \"setting up grid... \";\n typedef Dune::Stuff::Grid::Provider::Interface<> GridProviderType;\n const GridProviderType* gridProvider =\n Dune::Stuff::Grid::Provider::create<>(paramTree.get(id + \".grid\", \"stuff.grid.provider.cube\"),\n paramTree);\n typedef GridProviderType::GridType GridType;\n const Dune::shared_ptr< const GridType > grid = gridProvider->grid();\n info << \" done (has \" << grid->size(0) << \" elements, took \" << timer.elapsed() << \" sec)\" << std::endl;\n\n info << \"visualizing grid... \" << std::flush;\n timer.reset();\n gridProvider->visualize(paramTree.sub(id).get(\"filename\", id + \".grid\"));\n info << \" done (took \" << timer.elapsed() << \" sek)\" << std::endl;\n\n info << \"walking leaf grid view... \" << std::flush;\n timer.reset();\n const unsigned int leafElements = measureTiming(grid->leafView());\n info << \" done (has \" << leafElements << \" elements, took \" << timer.elapsed() << \" sek)\" << std::endl;\n\n \/\/ if we came that far we can as well be happy about it\n return 0;\n } catch(Dune::Exception& e) {\n std::cerr << \"Dune reported error: \" << e.what() << std::endl;\n } catch(std::exception& e) {\n std::cerr << e.what() << std::endl;\n } catch(...) {\n std::cerr << \"Unknown exception thrown!\" << std::endl;\n } \/\/ try\n} \/\/ main\n<commit_msg>[examples.grid.provider] added gmsh option<commit_after>#ifdef HAVE_CMAKE_CONFIG\n #include \"cmake_config.h\"\n#elif defined (HAVE_CONFIG_H)\n #include <config.h>\n#endif \/\/ HAVE_CMAKE_CONFIG\n\n#include <iostream>\n\n#include <boost\/filesystem.hpp>\n\n#include <dune\/common\/exceptions.hh>\n#include <dune\/common\/shared_ptr.hh>\n#include <dune\/common\/mpihelper.hh>\n#include <dune\/common\/timer.hh>\n\n#include <dune\/stuff\/common\/parameter\/tree.hh>\n#include <dune\/stuff\/common\/logging.hh>\n#include <dune\/stuff\/common\/filesystem.hh>\n#include <dune\/stuff\/common\/string.hh>\n#include <dune\/stuff\/grid\/provider.hh>\n\nconst std::string id = \"grid.providers\";\n\n\/**\n \\brief Creates a parameter file if it does not exist.\n\n Nothing is done if the file already exists. If not, a parameter file will be created with all neccessary\n keys and values.\n \\param[in] filename\n (Relative) path to the file.\n **\/\nvoid ensureParamFile(std::string filename)\n{\n Dune::Stuff::Common::testCreateDirectory(filename);\n if (!boost::filesystem::exists(filename)) {\n std::ofstream file;\n file.open(filename);\n file << \"[\" << id << \"]\" << std::endl;\n file << \"grid = stuff.grid.provider.cube\" << std::endl;\n file << \" stuff.grid.provider.gmsh\" << std::endl;\n file << \"filename = \" << id << \".grid\"<< std::endl;\n file << \"[stuff.grid.provider.cube]\" << std::endl;\n file << \"lowerLeft = [0.0; 0.0; 0.0]\" << std::endl;\n file << \"upperRight = [1.0; 1.0; 1.0]\" << std::endl;\n file << \"numElements = [4; 4; 4]\" << std::endl;\n file << \"[stuff.grid.provider.gmsh]\" << std::endl;\n file << \"filename = curved2d.msh\" << std::endl;\n file.close();\n } \/\/ only write param file if there is none\n} \/\/ void ensureParamFile()\n\ntemplate< class GridViewType >\nunsigned int measureTiming(const GridViewType& gridView)\n{\n unsigned int elements = 0;\n for (typename GridViewType::template Codim< 0 >::Iterator it = gridView.template begin< 0 >();\n it != gridView.template end< 0 >();\n ++it)\n ++elements;\n return elements;\n} \/\/ unsigned int measureTiming(const GridViewType& gridView)\n\nint main(int argc, char** argv)\n{\n try {\n \/\/ mpi\n Dune::MPIHelper::instance(argc, argv);\n\n \/\/ parameter\n const std::string filename = id + \".param\";\n ensureParamFile(filename);\n Dune::Stuff::Common::ExtendedParameterTree paramTree(argc, argv, filename);\n if (!paramTree.hasSub(id))\n DUNE_THROW(Dune::RangeError,\n \"\\nMissing sub '\" << id << \"' in the following Dune::ParameterTree:\\n\" << paramTree.reportString(\" \"));\n\n \/\/ logger\n Dune::Stuff::Common::Logger().create(Dune::Stuff::Common::LOG_INFO |\n Dune::Stuff::Common::LOG_CONSOLE |\n Dune::Stuff::Common::LOG_DEBUG);\n Dune::Stuff::Common::LogStream& info = Dune::Stuff::Common::Logger().info();\n\n \/\/ timer\n Dune::Timer timer;\n\n \/\/ grid\n info << \"setting up grid... \";\n typedef Dune::Stuff::Grid::Provider::Interface<> GridProviderType;\n const GridProviderType* gridProvider =\n Dune::Stuff::Grid::Provider::create<>(paramTree.get(id + \".grid\", \"stuff.grid.provider.cube\"),\n paramTree);\n typedef GridProviderType::GridType GridType;\n const Dune::shared_ptr< const GridType > grid = gridProvider->grid();\n info << \" done (has \" << grid->size(0) << \" elements, took \" << timer.elapsed() << \" sec)\" << std::endl;\n\n info << \"visualizing grid... \" << std::flush;\n timer.reset();\n gridProvider->visualize(paramTree.sub(id).get(\"filename\", id + \".grid\"));\n info << \" done (took \" << timer.elapsed() << \" sek)\" << std::endl;\n\n info << \"walking leaf grid view... \" << std::flush;\n timer.reset();\n const unsigned int leafElements = measureTiming(grid->leafView());\n info << \" done (has \" << leafElements << \" elements, took \" << timer.elapsed() << \" sek)\" << std::endl;\n\n \/\/ if we came that far we can as well be happy about it\n return 0;\n } catch(Dune::Exception& e) {\n std::cerr << \"Dune reported error: \" << e.what() << std::endl;\n } catch(std::exception& e) {\n std::cerr << e.what() << std::endl;\n } catch(...) {\n std::cerr << \"Unknown exception thrown!\" << std::endl;\n } \/\/ try\n} \/\/ main\n<|endoftext|>"} {"text":"<commit_before>\/******************************************************************************\n * Copyright 2017 The Apollo Authors. All Rights Reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *****************************************************************************\/\n\n#include \"modules\/planning\/integration_tests\/planning_test_base.h\"\n\n#include <cstdlib>\n\n#include \"cybertron\/common\/log.h\"\n\n#include \"modules\/canbus\/proto\/chassis.pb.h\"\n#include \"modules\/localization\/proto\/localization.pb.h\"\n#include \"modules\/perception\/proto\/traffic_light_detection.pb.h\"\n#include \"modules\/prediction\/proto\/prediction_obstacle.pb.h\"\n#include \"modules\/routing\/proto\/routing.pb.h\"\n\n#include \"modules\/common\/adapters\/adapter_gflags.h\"\n#include \"modules\/common\/util\/file.h\"\n#include \"modules\/planning\/common\/planning_gflags.h\"\n\nnamespace apollo {\nnamespace planning {\n\nusing apollo::canbus::Chassis;\nusing apollo::common::time::Clock;\nusing apollo::localization::LocalizationEstimate;\nusing apollo::perception::TrafficLightDetection;\nusing apollo::prediction::PredictionObstacles;\nusing apollo::routing::RoutingResponse;\n\nDEFINE_string(test_data_dir, \"\", \"the test data folder\");\nDEFINE_bool(test_update_golden_log, false,\n \"true to update decision golden log file.\");\nDEFINE_string(test_routing_response_file, \"\", \"The routing file used in test\");\nDEFINE_string(test_localization_file, \"\", \"The localization test file\");\nDEFINE_string(test_chassis_file, \"\", \"The chassis test file\");\nDEFINE_string(test_prediction_file, \"\", \"The prediction module test file\");\nDEFINE_string(test_traffic_light_file, \"\", \"The traffic light test file\");\nDEFINE_string(test_relative_map_file, \"\", \"The relative map test file\");\nDEFINE_string(test_previous_planning_file, \"\",\n \"The previous planning test file\");\n\nvoid PlanningTestBase::SetUpTestCase() {\n FLAGS_use_multi_thread_to_add_obstacles = false;\n FLAGS_enable_multi_thread_in_dp_poly_path = false;\n FLAGS_enable_multi_thread_in_dp_st_graph = false;\n FLAGS_planning_config_file =\n \"\/apollo\/modules\/planning\/conf\/planning_config.pb.txt\";\n FLAGS_traffic_rule_config_filename =\n \"\/apollo\/modules\/planning\/conf\/traffic_rule_config.pb.txt\";\n FLAGS_smoother_config_filename =\n \"modules\/planning\/conf\/qp_spline_smoother_config.pb.txt\";\n FLAGS_map_dir = \"modules\/planning\/testdata\";\n FLAGS_test_localization_file = \"\";\n FLAGS_test_chassis_file = \"\";\n FLAGS_test_routing_response_file = \"\";\n FLAGS_test_prediction_file = \"\";\n FLAGS_align_prediction_time = false;\n FLAGS_estimate_current_vehicle_state = false;\n FLAGS_enable_reference_line_provider_thread = false;\n \/\/ FLAGS_enable_trajectory_check is temporarily disabled, otherwise EMPlanner\n \/\/ and LatticePlanner can't pass the unit test.\n FLAGS_enable_trajectory_check = false;\n FLAGS_planning_test_mode = true;\n FLAGS_enable_lag_prediction = false;\n}\n\nbool PlanningTestBase::FeedTestData() {\n \/\/ chassis\n Chassis chassis;\n if (!apollo::common::util::GetProtoFromFile(\n FLAGS_test_data_dir + \"\/\" + FLAGS_test_chassis_file, &chassis)) {\n AERROR << \"failed to load file: \" << FLAGS_test_chassis_file;\n return false;\n }\n \/\/ localization\n LocalizationEstimate localization;\n if (!apollo::common::util::GetProtoFromFile(\n FLAGS_test_data_dir + \"\/\" + FLAGS_test_localization_file,\n &localization)) {\n AERROR << \"failed to load file: \" << FLAGS_test_localization_file;\n return false;\n }\n\n Clock::SetNowInSeconds(localization.header().timestamp_sec());\n\n \/\/ prediction\n PredictionObstacles prediction;\n if (!apollo::common::util::GetProtoFromFile(\n FLAGS_test_data_dir + \"\/\" + FLAGS_test_prediction_file,\n &prediction)) {\n AERROR << \"failed to load file: \" << FLAGS_test_prediction_file;\n return false;\n }\n \/\/ routing_response\n RoutingResponse routing_response;\n if (!apollo::common::util::GetProtoFromFile(\n FLAGS_test_data_dir + \"\/\" + FLAGS_test_routing_response_file,\n &routing_response)) {\n AERROR << \"failed to load file: \" << FLAGS_test_routing_response_file;\n return false;\n }\n \/\/ traffic_light_detection\n TrafficLightDetection traffic_light_detection;\n if (!apollo::common::util::GetProtoFromFile(\n FLAGS_test_data_dir + \"\/\" + FLAGS_test_traffic_light_file,\n &traffic_light_detection)) {\n AERROR << \"failed to load file: \" << FLAGS_test_traffic_light_file;\n return false;\n }\n\n local_view_.prediction_obstacles =\n std::make_shared<PredictionObstacles>(prediction);\n local_view_.chassis = std::make_shared<Chassis>(chassis);\n local_view_.localization_estimate =\n std::make_shared<LocalizationEstimate>(localization);\n local_view_.routing =\n std::make_shared<routing::RoutingResponse>(routing_response);\n local_view_.traffic_light =\n std::make_shared<TrafficLightDetection>(traffic_light_detection);\n\n AINFO << \"Successfully feed proto files.\";\n return true;\n}\n\nvoid PlanningTestBase::SetUp() {\n if (FLAGS_use_navigation_mode) {\n \/\/ TODO(all)\n \/\/ planning_ = std::unique_ptr<PlanningBase>(new NaviPlanning());\n } else {\n planning_ = std::unique_ptr<PlanningBase>(new StdPlanning());\n }\n\n CHECK(FeedTestData()) << \"Failed to feed test data\";\n\n CHECK(apollo::common::util::GetProtoFromFile(FLAGS_planning_config_file,\n &config_))\n << \"failed to load planning config file \" << FLAGS_planning_config_file;\n\n CHECK(planning_->Init(config_).ok()) << \"Failed to init planning module\";\n\n \/\/ Do not use fallback trajectory during testing\n FLAGS_use_planning_fallback = false;\n\n if (!FLAGS_test_previous_planning_file.empty()) {\n const auto prev_planning_file =\n FLAGS_test_data_dir + \"\/\" + FLAGS_test_previous_planning_file;\n ADCTrajectory prev_planning;\n CHECK(common::util::GetProtoFromFile(prev_planning_file, &prev_planning));\n planning_->last_publishable_trajectory_.reset(\n new PublishableTrajectory(prev_planning));\n }\n for (auto& config : *(planning_->traffic_rule_configs_.mutable_config())) {\n auto iter = rule_enabled_.find(config.rule_id());\n if (iter != rule_enabled_.end()) {\n config.set_enabled(iter->second);\n }\n }\n}\n\nvoid PlanningTestBase::UpdateData() {\n CHECK(FeedTestData()) << \"Failed to feed test data\";\n\n if (!FLAGS_test_previous_planning_file.empty()) {\n const auto prev_planning_file =\n FLAGS_test_data_dir + \"\/\" + FLAGS_test_previous_planning_file;\n ADCTrajectory prev_planning;\n CHECK(common::util::GetProtoFromFile(prev_planning_file, &prev_planning));\n planning_->last_publishable_trajectory_.reset(\n new PublishableTrajectory(prev_planning));\n }\n for (auto& config : *planning_->traffic_rule_configs_.mutable_config()) {\n auto iter = rule_enabled_.find(config.rule_id());\n if (iter != rule_enabled_.end()) {\n config.set_enabled(iter->second);\n }\n }\n}\n\nvoid PlanningTestBase::TrimPlanning(ADCTrajectory* origin,\n bool no_trajectory_point) {\n origin->clear_latency_stats();\n origin->clear_debug();\n origin->mutable_header()->clear_radar_timestamp();\n origin->mutable_header()->clear_lidar_timestamp();\n origin->mutable_header()->clear_timestamp_sec();\n origin->mutable_header()->clear_camera_timestamp();\n origin->mutable_header()->clear_sequence_num();\n\n if (no_trajectory_point) {\n origin->clear_total_path_length();\n origin->clear_total_path_time();\n origin->clear_trajectory_point();\n }\n}\n\nbool PlanningTestBase::RunPlanning(const std::string& test_case_name,\n int case_num, bool no_trajectory_point) {\n const std::string golden_result_file = apollo::common::util::StrCat(\n \"result_\", test_case_name, \"_\", case_num, \".pb.txt\");\n\n std::string full_golden_path = FLAGS_test_data_dir + \"\/\" + golden_result_file;\n\n ADCTrajectory adc_trajectory_pb;\n planning_->RunOnce(local_view_, &adc_trajectory_pb);\n\n if (!IsValidTrajectory(adc_trajectory_pb)) {\n AERROR << \"Fail to pass trajectory check.\";\n return false;\n }\n\n adc_trajectory_ = adc_trajectory_pb;\n TrimPlanning(&adc_trajectory_, no_trajectory_point);\n if (FLAGS_test_update_golden_log) {\n AINFO << \"The golden file is regenerated:\" << full_golden_path;\n common::util::SetProtoToASCIIFile(adc_trajectory_, full_golden_path);\n } else {\n ADCTrajectory golden_result;\n bool load_success =\n common::util::GetProtoFromASCIIFile(full_golden_path, &golden_result);\n TrimPlanning(&golden_result, no_trajectory_point);\n if (!load_success ||\n !common::util::IsProtoEqual(golden_result, adc_trajectory_)) {\n char tmp_fname[100] = \"\/tmp\/XXXXXX\";\n int fd = mkstemp(tmp_fname);\n if (!common::util::SetProtoToASCIIFile(adc_trajectory_, fd)) {\n AERROR << \"Failed to write to file \" << tmp_fname;\n }\n AERROR << \"found\\ndiff \" << tmp_fname << \" \" << full_golden_path;\n AERROR << \"visualize diff\\n\/usr\/bin\/python \"\n \"modules\/tools\/plot_trace\/plot_planning_result.py \"\n << tmp_fname << \" \" << full_golden_path;\n return false;\n }\n }\n return true;\n}\n\nbool PlanningTestBase::IsValidTrajectory(const ADCTrajectory& trajectory) {\n for (int i = 0; i < trajectory.trajectory_point_size(); ++i) {\n const auto& point = trajectory.trajectory_point(i);\n\n const double kMaxAccelThreshold =\n FLAGS_longitudinal_acceleration_upper_bound;\n const double kMinAccelThreshold =\n FLAGS_longitudinal_acceleration_lower_bound;\n if (point.a() > kMaxAccelThreshold || point.a() < kMinAccelThreshold) {\n AERROR << \"Invalid trajectory point because accel out of range: \"\n << point.DebugString();\n return false;\n }\n\n if (!point.has_path_point()) {\n AERROR << \"Invalid trajectory point because NO path_point in \"\n \"trajectory_point: \"\n << point.DebugString();\n return false;\n }\n\n if (i > 0) {\n const double kPathSEpsilon = 1e-3;\n const auto& last_point = trajectory.trajectory_point(i - 1);\n if (point.path_point().s() + kPathSEpsilon <\n last_point.path_point().s()) {\n AERROR << \"Invalid trajectory point because s value error. last point: \"\n << last_point.DebugString()\n << \", curr point: \" << point.DebugString();\n return false;\n }\n }\n }\n return true;\n}\n\nTrafficRuleConfig* PlanningTestBase::GetTrafficRuleConfig(\n const TrafficRuleConfig::RuleId& rule_id) {\n for (auto& config : *planning_->traffic_rule_configs_.mutable_config()) {\n if (config.rule_id() == rule_id) {\n return &config;\n }\n }\n return nullptr;\n}\n\n} \/\/ namespace planning\n} \/\/ namespace apollo\n<commit_msg>planning: fix a path bug (#1099)<commit_after>\/******************************************************************************\n * Copyright 2017 The Apollo Authors. All Rights Reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *****************************************************************************\/\n\n#include \"modules\/planning\/integration_tests\/planning_test_base.h\"\n\n#include <cstdlib>\n\n#include \"cybertron\/common\/log.h\"\n\n#include \"modules\/canbus\/proto\/chassis.pb.h\"\n#include \"modules\/localization\/proto\/localization.pb.h\"\n#include \"modules\/perception\/proto\/traffic_light_detection.pb.h\"\n#include \"modules\/prediction\/proto\/prediction_obstacle.pb.h\"\n#include \"modules\/routing\/proto\/routing.pb.h\"\n\n#include \"modules\/common\/adapters\/adapter_gflags.h\"\n#include \"modules\/common\/util\/file.h\"\n#include \"modules\/planning\/common\/planning_gflags.h\"\n\nnamespace apollo {\nnamespace planning {\n\nusing apollo::canbus::Chassis;\nusing apollo::common::time::Clock;\nusing apollo::localization::LocalizationEstimate;\nusing apollo::perception::TrafficLightDetection;\nusing apollo::prediction::PredictionObstacles;\nusing apollo::routing::RoutingResponse;\n\nDEFINE_string(test_data_dir, \"\", \"the test data folder\");\nDEFINE_bool(test_update_golden_log, false,\n \"true to update decision golden log file.\");\nDEFINE_string(test_routing_response_file, \"\", \"The routing file used in test\");\nDEFINE_string(test_localization_file, \"\", \"The localization test file\");\nDEFINE_string(test_chassis_file, \"\", \"The chassis test file\");\nDEFINE_string(test_prediction_file, \"\", \"The prediction module test file\");\nDEFINE_string(test_traffic_light_file, \"\", \"The traffic light test file\");\nDEFINE_string(test_relative_map_file, \"\", \"The relative map test file\");\nDEFINE_string(test_previous_planning_file, \"\",\n \"The previous planning test file\");\n\nvoid PlanningTestBase::SetUpTestCase() {\n FLAGS_use_multi_thread_to_add_obstacles = false;\n FLAGS_enable_multi_thread_in_dp_poly_path = false;\n FLAGS_enable_multi_thread_in_dp_st_graph = false;\n FLAGS_planning_config_file =\n \"\/apollo\/modules\/planning\/conf\/planning_config.pb.txt\";\n FLAGS_traffic_rule_config_filename =\n \"\/apollo\/modules\/planning\/conf\/traffic_rule_config.pb.txt\";\n FLAGS_smoother_config_filename =\n \"\/apollo\/modules\/planning\/conf\/qp_spline_smoother_config.pb.txt\";\n FLAGS_map_dir = \"\/apollo\/modules\/planning\/testdata\";\n FLAGS_test_localization_file = \"\";\n FLAGS_test_chassis_file = \"\";\n FLAGS_test_routing_response_file = \"\";\n FLAGS_test_prediction_file = \"\";\n FLAGS_align_prediction_time = false;\n FLAGS_estimate_current_vehicle_state = false;\n FLAGS_enable_reference_line_provider_thread = false;\n \/\/ FLAGS_enable_trajectory_check is temporarily disabled, otherwise EMPlanner\n \/\/ and LatticePlanner can't pass the unit test.\n FLAGS_enable_trajectory_check = false;\n FLAGS_planning_test_mode = true;\n FLAGS_enable_lag_prediction = false;\n}\n\nbool PlanningTestBase::FeedTestData() {\n \/\/ chassis\n Chassis chassis;\n if (!apollo::common::util::GetProtoFromFile(\n FLAGS_test_data_dir + \"\/\" + FLAGS_test_chassis_file, &chassis)) {\n AERROR << \"failed to load file: \" << FLAGS_test_chassis_file;\n return false;\n }\n \/\/ localization\n LocalizationEstimate localization;\n if (!apollo::common::util::GetProtoFromFile(\n FLAGS_test_data_dir + \"\/\" + FLAGS_test_localization_file,\n &localization)) {\n AERROR << \"failed to load file: \" << FLAGS_test_localization_file;\n return false;\n }\n\n Clock::SetNowInSeconds(localization.header().timestamp_sec());\n\n \/\/ prediction\n PredictionObstacles prediction;\n if (!apollo::common::util::GetProtoFromFile(\n FLAGS_test_data_dir + \"\/\" + FLAGS_test_prediction_file,\n &prediction)) {\n AERROR << \"failed to load file: \" << FLAGS_test_prediction_file;\n return false;\n }\n \/\/ routing_response\n RoutingResponse routing_response;\n if (!apollo::common::util::GetProtoFromFile(\n FLAGS_test_data_dir + \"\/\" + FLAGS_test_routing_response_file,\n &routing_response)) {\n AERROR << \"failed to load file: \" << FLAGS_test_routing_response_file;\n return false;\n }\n \/\/ traffic_light_detection\n TrafficLightDetection traffic_light_detection;\n if (!apollo::common::util::GetProtoFromFile(\n FLAGS_test_data_dir + \"\/\" + FLAGS_test_traffic_light_file,\n &traffic_light_detection)) {\n AERROR << \"failed to load file: \" << FLAGS_test_traffic_light_file;\n return false;\n }\n\n local_view_.prediction_obstacles =\n std::make_shared<PredictionObstacles>(prediction);\n local_view_.chassis = std::make_shared<Chassis>(chassis);\n local_view_.localization_estimate =\n std::make_shared<LocalizationEstimate>(localization);\n local_view_.routing =\n std::make_shared<routing::RoutingResponse>(routing_response);\n local_view_.traffic_light =\n std::make_shared<TrafficLightDetection>(traffic_light_detection);\n\n AINFO << \"Successfully feed proto files.\";\n return true;\n}\n\nvoid PlanningTestBase::SetUp() {\n if (FLAGS_use_navigation_mode) {\n \/\/ TODO(all)\n \/\/ planning_ = std::unique_ptr<PlanningBase>(new NaviPlanning());\n } else {\n planning_ = std::unique_ptr<PlanningBase>(new StdPlanning());\n }\n\n CHECK(FeedTestData()) << \"Failed to feed test data\";\n\n CHECK(apollo::common::util::GetProtoFromFile(FLAGS_planning_config_file,\n &config_))\n << \"failed to load planning config file \" << FLAGS_planning_config_file;\n\n CHECK(planning_->Init(config_).ok()) << \"Failed to init planning module\";\n\n \/\/ Do not use fallback trajectory during testing\n FLAGS_use_planning_fallback = false;\n\n if (!FLAGS_test_previous_planning_file.empty()) {\n const auto prev_planning_file =\n FLAGS_test_data_dir + \"\/\" + FLAGS_test_previous_planning_file;\n ADCTrajectory prev_planning;\n CHECK(common::util::GetProtoFromFile(prev_planning_file, &prev_planning));\n planning_->last_publishable_trajectory_.reset(\n new PublishableTrajectory(prev_planning));\n }\n for (auto& config : *(planning_->traffic_rule_configs_.mutable_config())) {\n auto iter = rule_enabled_.find(config.rule_id());\n if (iter != rule_enabled_.end()) {\n config.set_enabled(iter->second);\n }\n }\n}\n\nvoid PlanningTestBase::UpdateData() {\n CHECK(FeedTestData()) << \"Failed to feed test data\";\n\n if (!FLAGS_test_previous_planning_file.empty()) {\n const auto prev_planning_file =\n FLAGS_test_data_dir + \"\/\" + FLAGS_test_previous_planning_file;\n ADCTrajectory prev_planning;\n CHECK(common::util::GetProtoFromFile(prev_planning_file, &prev_planning));\n planning_->last_publishable_trajectory_.reset(\n new PublishableTrajectory(prev_planning));\n }\n for (auto& config : *planning_->traffic_rule_configs_.mutable_config()) {\n auto iter = rule_enabled_.find(config.rule_id());\n if (iter != rule_enabled_.end()) {\n config.set_enabled(iter->second);\n }\n }\n}\n\nvoid PlanningTestBase::TrimPlanning(ADCTrajectory* origin,\n bool no_trajectory_point) {\n origin->clear_latency_stats();\n origin->clear_debug();\n origin->mutable_header()->clear_radar_timestamp();\n origin->mutable_header()->clear_lidar_timestamp();\n origin->mutable_header()->clear_timestamp_sec();\n origin->mutable_header()->clear_camera_timestamp();\n origin->mutable_header()->clear_sequence_num();\n\n if (no_trajectory_point) {\n origin->clear_total_path_length();\n origin->clear_total_path_time();\n origin->clear_trajectory_point();\n }\n}\n\nbool PlanningTestBase::RunPlanning(const std::string& test_case_name,\n int case_num, bool no_trajectory_point) {\n const std::string golden_result_file = apollo::common::util::StrCat(\n \"result_\", test_case_name, \"_\", case_num, \".pb.txt\");\n\n std::string full_golden_path = FLAGS_test_data_dir + \"\/\" + golden_result_file;\n\n ADCTrajectory adc_trajectory_pb;\n planning_->RunOnce(local_view_, &adc_trajectory_pb);\n\n if (!IsValidTrajectory(adc_trajectory_pb)) {\n AERROR << \"Fail to pass trajectory check.\";\n return false;\n }\n\n adc_trajectory_ = adc_trajectory_pb;\n TrimPlanning(&adc_trajectory_, no_trajectory_point);\n if (FLAGS_test_update_golden_log) {\n AINFO << \"The golden file is regenerated:\" << full_golden_path;\n common::util::SetProtoToASCIIFile(adc_trajectory_, full_golden_path);\n } else {\n ADCTrajectory golden_result;\n bool load_success =\n common::util::GetProtoFromASCIIFile(full_golden_path, &golden_result);\n TrimPlanning(&golden_result, no_trajectory_point);\n if (!load_success ||\n !common::util::IsProtoEqual(golden_result, adc_trajectory_)) {\n char tmp_fname[100] = \"\/tmp\/XXXXXX\";\n int fd = mkstemp(tmp_fname);\n if (!common::util::SetProtoToASCIIFile(adc_trajectory_, fd)) {\n AERROR << \"Failed to write to file \" << tmp_fname;\n }\n AERROR << \"found\\ndiff \" << tmp_fname << \" \" << full_golden_path;\n AERROR << \"visualize diff\\n\/usr\/bin\/python \"\n \"modules\/tools\/plot_trace\/plot_planning_result.py \"\n << tmp_fname << \" \" << full_golden_path;\n return false;\n }\n }\n return true;\n}\n\nbool PlanningTestBase::IsValidTrajectory(const ADCTrajectory& trajectory) {\n for (int i = 0; i < trajectory.trajectory_point_size(); ++i) {\n const auto& point = trajectory.trajectory_point(i);\n\n const double kMaxAccelThreshold =\n FLAGS_longitudinal_acceleration_upper_bound;\n const double kMinAccelThreshold =\n FLAGS_longitudinal_acceleration_lower_bound;\n if (point.a() > kMaxAccelThreshold || point.a() < kMinAccelThreshold) {\n AERROR << \"Invalid trajectory point because accel out of range: \"\n << point.DebugString();\n return false;\n }\n\n if (!point.has_path_point()) {\n AERROR << \"Invalid trajectory point because NO path_point in \"\n \"trajectory_point: \"\n << point.DebugString();\n return false;\n }\n\n if (i > 0) {\n const double kPathSEpsilon = 1e-3;\n const auto& last_point = trajectory.trajectory_point(i - 1);\n if (point.path_point().s() + kPathSEpsilon <\n last_point.path_point().s()) {\n AERROR << \"Invalid trajectory point because s value error. last point: \"\n << last_point.DebugString()\n << \", curr point: \" << point.DebugString();\n return false;\n }\n }\n }\n return true;\n}\n\nTrafficRuleConfig* PlanningTestBase::GetTrafficRuleConfig(\n const TrafficRuleConfig::RuleId& rule_id) {\n for (auto& config : *planning_->traffic_rule_configs_.mutable_config()) {\n if (config.rule_id() == rule_id) {\n return &config;\n }\n }\n return nullptr;\n}\n\n} \/\/ namespace planning\n} \/\/ namespace apollo\n<|endoftext|>"} {"text":"<commit_before>\/******************************************************************************\n * Copyright 2017 The Apollo Authors. All Rights Reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *****************************************************************************\/\n\n#include \"modules\/planning\/integration_tests\/planning_test_base.h\"\n\n#include <cstdlib>\n\n#include \"google\/protobuf\/io\/zero_copy_stream_impl.h\"\n#include \"modules\/common\/log.h\"\n#include \"modules\/common\/vehicle_state\/vehicle_state.h\"\n#include \"modules\/planning\/common\/planning_gflags.h\"\n\nnamespace apollo {\nnamespace planning {\n\nusing common::adapter::AdapterManager;\n\nDEFINE_string(test_data_dir, \"\", \"the test data folder\");\nDEFINE_bool(test_update_golden_log, false,\n \"true to update decision golden log file.\");\nDEFINE_string(test_routing_response_file, \"garage_routing.pb.txt\",\n \"The routing file used in test\");\nDEFINE_string(test_localization_file, \"garage_localization.pb.txt\",\n \"The localization test file\");\nDEFINE_string(test_chassis_file, \"garage_chassis.pb.txt\",\n \"The chassis test file\");\nDEFINE_string(test_prediction_file, \"\", \"The prediction module test file\");\n\nvoid PlanningTestBase::SetUpTestCase() {\n FLAGS_planning_config_file = \"modules\/planning\/conf\/planning_config.pb.txt\";\n FLAGS_adapter_config_filename = \"modules\/planning\/testdata\/conf\/adapter.conf\";\n FLAGS_map_dir = \"modules\/planning\/testdata\";\n FLAGS_test_localization_file = \"garage_localization.pb.txt\";\n FLAGS_test_chassis_file = \"garage_chassis.pb.txt\";\n FLAGS_test_prediction_file = \"garage_prediction.pb.txt\";\n FLAGS_align_prediction_time = false;\n FLAGS_enable_reference_line_provider_thread = false;\n FLAGS_enable_trajectory_check = true;\n}\n\nbool PlanningTestBase::SetUpAdapters() {\n if (!AdapterManager::Initialized()) {\n AdapterManager::Init(FLAGS_adapter_config_filename);\n }\n if (!AdapterManager::GetRoutingResponse()) {\n AERROR << \"routing is not registered in adapter manager, check adapter \"\n \"config file.\"\n << FLAGS_adapter_config_filename;\n return false;\n }\n auto routing_response_file =\n FLAGS_test_data_dir + \"\/\" + FLAGS_test_routing_response_file;\n if (!AdapterManager::FeedRoutingResponseFile(routing_response_file)) {\n AERROR << \"failed to routing file: \" << routing_response_file;\n return false;\n }\n AINFO << \"Using Routing \" << routing_response_file;\n auto localization_file =\n FLAGS_test_data_dir + \"\/\" + FLAGS_test_localization_file;\n if (!AdapterManager::FeedLocalizationFile(localization_file)) {\n AERROR << \"Failed to load localization file: \" << localization_file;\n return false;\n }\n AINFO << \"Using Localization file: \" << localization_file;\n auto chassis_file = FLAGS_test_data_dir + \"\/\" + FLAGS_test_chassis_file;\n if (!AdapterManager::FeedChassisFile(chassis_file)) {\n AERROR << \"Failed to load chassis file: \" << chassis_file;\n return false;\n }\n AINFO << \"Using Chassis file: \" << chassis_file;\n auto prediction_file = FLAGS_test_data_dir + \"\/\" + FLAGS_test_prediction_file;\n if (!FLAGS_test_prediction_file.empty() &&\n !AdapterManager::FeedPredictionFile(prediction_file)) {\n AERROR << \"Failed to load prediction file: \" << prediction_file;\n return false;\n }\n AINFO << \"Using Prediction file: \" << prediction_file;\n return true;\n}\n\nvoid PlanningTestBase::SetUp() {\n planning_.Stop();\n CHECK(SetUpAdapters()) << \"Failed to setup adapters\";\n planning_.Init();\n}\n\nvoid PlanningTestBase::TrimPlanning(ADCTrajectory* origin) {\n origin->clear_latency_stats();\n origin->clear_debug();\n origin->mutable_header()->clear_radar_timestamp();\n origin->mutable_header()->clear_lidar_timestamp();\n origin->mutable_header()->clear_timestamp_sec();\n origin->mutable_header()->clear_camera_timestamp();\n origin->mutable_header()->clear_sequence_num();\n}\n\nbool PlanningTestBase::RunPlanning(const std::string& test_case_name,\n int case_num) {\n const std::string golden_result_file = apollo::common::util::StrCat(\n \"result_\", test_case_name, \"_\", case_num, \".pb.txt\");\n\n std::string full_golden_path = FLAGS_test_data_dir + \"\/\" + golden_result_file;\n planning_.RunOnce();\n\n const ADCTrajectory* trajectory_pointer =\n AdapterManager::GetPlanning()->GetLatestPublished();\n\n if (!trajectory_pointer) {\n AERROR << \" did not get latest adc trajectory\";\n return false;\n }\n\n if (!IsValidTrajectory(*trajectory_pointer)) {\n AERROR << \"Fail to pass trajectory check.\";\n return false;\n }\n\n adc_trajectory_ = *trajectory_pointer;\n TrimPlanning(&adc_trajectory_);\n if (FLAGS_test_update_golden_log) {\n AINFO << \"The golden file is regenerated:\" << full_golden_path;\n common::util::SetProtoToASCIIFile(adc_trajectory_, full_golden_path);\n } else {\n ADCTrajectory golden_result;\n bool load_success =\n common::util::GetProtoFromASCIIFile(full_golden_path, &golden_result);\n TrimPlanning(&golden_result);\n if (!load_success ||\n !common::util::IsProtoEqual(golden_result, adc_trajectory_)) {\n char tmp_fname[100] = \"\/tmp\/XXXXXX\";\n int fd = mkstemp(tmp_fname);\n if (!common::util::SetProtoToASCIIFile(adc_trajectory_, fd)) {\n AERROR << \"Failed to write to file \" << tmp_fname;\n }\n AERROR << \"found\\ndiff \" << tmp_fname << \" \" << full_golden_path;\n AERROR << \"visualize diff\\npython \"\n \"modules\/tools\/plot_trace\/plot_planning_result.py \"\n << tmp_fname << \" \" << full_golden_path;\n return false;\n }\n }\n return true;\n}\n\nbool PlanningTestBase::IsValidTrajectory(const ADCTrajectory& trajectory) {\n if (trajectory.trajectory_point().empty()) {\n AERROR << \"trajectory has NO point.\";\n return false;\n }\n\n for (int i = 0; i < trajectory.trajectory_point_size(); ++i) {\n const auto& point = trajectory.trajectory_point(i);\n\n const double kMaxAccelThreshold =\n FLAGS_longitudinal_acceleration_upper_bound;\n const double kMinAccelThreshold =\n FLAGS_longitudinal_acceleration_lower_bound;\n if (point.a() > kMaxAccelThreshold || point.a() < kMinAccelThreshold) {\n AERROR << \"Invalid trajectory point because accel out of range: \"\n << point.DebugString();\n return false;\n }\n\n if (!point.has_path_point()) {\n AERROR << \"Invalid trajectory point because NO path_point in \"\n \"trajectory_point: \"\n << point.DebugString();\n return false;\n }\n\n const double kDkappaThreshold = 0.1;\n if (point.path_point().dkappa() > kDkappaThreshold ||\n point.path_point().dkappa() < -kDkappaThreshold) {\n AERROR << \"Invalid trajectory point because dkappa out of range: \"\n << point.DebugString();\n return false;\n }\n\n if (i > 0) {\n const double kPathSEpsilon = 1e-3;\n const auto& last_point = trajectory.trajectory_point(i - 1);\n if (point.path_point().s() + kPathSEpsilon <\n last_point.path_point().s()) {\n AERROR << \"Invalid trajectory point because s value error. last point: \"\n << last_point.DebugString()\n << \", curr point: \" << point.DebugString();\n return false;\n }\n }\n }\n return true;\n}\n\n} \/\/ namespace planning\n} \/\/ namespace apollo\n<commit_msg>planning: quit integration test if failed to init<commit_after>\/******************************************************************************\n * Copyright 2017 The Apollo Authors. All Rights Reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *****************************************************************************\/\n\n#include \"modules\/planning\/integration_tests\/planning_test_base.h\"\n\n#include <cstdlib>\n\n#include \"google\/protobuf\/io\/zero_copy_stream_impl.h\"\n#include \"modules\/common\/log.h\"\n#include \"modules\/common\/vehicle_state\/vehicle_state.h\"\n#include \"modules\/planning\/common\/planning_gflags.h\"\n\nnamespace apollo {\nnamespace planning {\n\nusing common::adapter::AdapterManager;\n\nDEFINE_string(test_data_dir, \"\", \"the test data folder\");\nDEFINE_bool(test_update_golden_log, false,\n \"true to update decision golden log file.\");\nDEFINE_string(test_routing_response_file, \"garage_routing.pb.txt\",\n \"The routing file used in test\");\nDEFINE_string(test_localization_file, \"garage_localization.pb.txt\",\n \"The localization test file\");\nDEFINE_string(test_chassis_file, \"garage_chassis.pb.txt\",\n \"The chassis test file\");\nDEFINE_string(test_prediction_file, \"\", \"The prediction module test file\");\n\nvoid PlanningTestBase::SetUpTestCase() {\n FLAGS_planning_config_file = \"modules\/planning\/conf\/planning_config.pb.txt\";\n FLAGS_adapter_config_filename = \"modules\/planning\/testdata\/conf\/adapter.conf\";\n FLAGS_map_dir = \"modules\/planning\/testdata\";\n FLAGS_test_localization_file = \"garage_localization.pb.txt\";\n FLAGS_test_chassis_file = \"garage_chassis.pb.txt\";\n FLAGS_test_prediction_file = \"garage_prediction.pb.txt\";\n FLAGS_align_prediction_time = false;\n FLAGS_enable_reference_line_provider_thread = false;\n FLAGS_enable_trajectory_check = true;\n}\n\nbool PlanningTestBase::SetUpAdapters() {\n if (!AdapterManager::Initialized()) {\n AdapterManager::Init(FLAGS_adapter_config_filename);\n }\n if (!AdapterManager::GetRoutingResponse()) {\n AERROR << \"routing is not registered in adapter manager, check adapter \"\n \"config file.\"\n << FLAGS_adapter_config_filename;\n return false;\n }\n auto routing_response_file =\n FLAGS_test_data_dir + \"\/\" + FLAGS_test_routing_response_file;\n if (!AdapterManager::FeedRoutingResponseFile(routing_response_file)) {\n AERROR << \"failed to routing file: \" << routing_response_file;\n return false;\n }\n AINFO << \"Using Routing \" << routing_response_file;\n auto localization_file =\n FLAGS_test_data_dir + \"\/\" + FLAGS_test_localization_file;\n if (!AdapterManager::FeedLocalizationFile(localization_file)) {\n AERROR << \"Failed to load localization file: \" << localization_file;\n return false;\n }\n AINFO << \"Using Localization file: \" << localization_file;\n auto chassis_file = FLAGS_test_data_dir + \"\/\" + FLAGS_test_chassis_file;\n if (!AdapterManager::FeedChassisFile(chassis_file)) {\n AERROR << \"Failed to load chassis file: \" << chassis_file;\n return false;\n }\n AINFO << \"Using Chassis file: \" << chassis_file;\n auto prediction_file = FLAGS_test_data_dir + \"\/\" + FLAGS_test_prediction_file;\n if (!FLAGS_test_prediction_file.empty() &&\n !AdapterManager::FeedPredictionFile(prediction_file)) {\n AERROR << \"Failed to load prediction file: \" << prediction_file;\n return false;\n }\n AINFO << \"Using Prediction file: \" << prediction_file;\n return true;\n}\n\nvoid PlanningTestBase::SetUp() {\n planning_.Stop();\n CHECK(SetUpAdapters()) << \"Failed to setup adapters\";\n CHECK(planning_.Init().ok()) << \"Failed to init planning module\";\n}\n\nvoid PlanningTestBase::TrimPlanning(ADCTrajectory* origin) {\n origin->clear_latency_stats();\n origin->clear_debug();\n origin->mutable_header()->clear_radar_timestamp();\n origin->mutable_header()->clear_lidar_timestamp();\n origin->mutable_header()->clear_timestamp_sec();\n origin->mutable_header()->clear_camera_timestamp();\n origin->mutable_header()->clear_sequence_num();\n}\n\nbool PlanningTestBase::RunPlanning(const std::string& test_case_name,\n int case_num) {\n const std::string golden_result_file = apollo::common::util::StrCat(\n \"result_\", test_case_name, \"_\", case_num, \".pb.txt\");\n\n std::string full_golden_path = FLAGS_test_data_dir + \"\/\" + golden_result_file;\n planning_.RunOnce();\n\n const ADCTrajectory* trajectory_pointer =\n AdapterManager::GetPlanning()->GetLatestPublished();\n\n if (!trajectory_pointer) {\n AERROR << \" did not get latest adc trajectory\";\n return false;\n }\n\n if (!IsValidTrajectory(*trajectory_pointer)) {\n AERROR << \"Fail to pass trajectory check.\";\n return false;\n }\n\n adc_trajectory_ = *trajectory_pointer;\n TrimPlanning(&adc_trajectory_);\n if (FLAGS_test_update_golden_log) {\n AINFO << \"The golden file is regenerated:\" << full_golden_path;\n common::util::SetProtoToASCIIFile(adc_trajectory_, full_golden_path);\n } else {\n ADCTrajectory golden_result;\n bool load_success =\n common::util::GetProtoFromASCIIFile(full_golden_path, &golden_result);\n TrimPlanning(&golden_result);\n if (!load_success ||\n !common::util::IsProtoEqual(golden_result, adc_trajectory_)) {\n char tmp_fname[100] = \"\/tmp\/XXXXXX\";\n int fd = mkstemp(tmp_fname);\n if (!common::util::SetProtoToASCIIFile(adc_trajectory_, fd)) {\n AERROR << \"Failed to write to file \" << tmp_fname;\n }\n AERROR << \"found\\ndiff \" << tmp_fname << \" \" << full_golden_path;\n AERROR << \"visualize diff\\npython \"\n \"modules\/tools\/plot_trace\/plot_planning_result.py \"\n << tmp_fname << \" \" << full_golden_path;\n return false;\n }\n }\n return true;\n}\n\nbool PlanningTestBase::IsValidTrajectory(const ADCTrajectory& trajectory) {\n if (trajectory.trajectory_point().empty()) {\n AERROR << \"trajectory has NO point.\";\n return false;\n }\n\n for (int i = 0; i < trajectory.trajectory_point_size(); ++i) {\n const auto& point = trajectory.trajectory_point(i);\n\n const double kMaxAccelThreshold =\n FLAGS_longitudinal_acceleration_upper_bound;\n const double kMinAccelThreshold =\n FLAGS_longitudinal_acceleration_lower_bound;\n if (point.a() > kMaxAccelThreshold || point.a() < kMinAccelThreshold) {\n AERROR << \"Invalid trajectory point because accel out of range: \"\n << point.DebugString();\n return false;\n }\n\n if (!point.has_path_point()) {\n AERROR << \"Invalid trajectory point because NO path_point in \"\n \"trajectory_point: \"\n << point.DebugString();\n return false;\n }\n\n const double kDkappaThreshold = 0.1;\n if (point.path_point().dkappa() > kDkappaThreshold ||\n point.path_point().dkappa() < -kDkappaThreshold) {\n AERROR << \"Invalid trajectory point because dkappa out of range: \"\n << point.DebugString();\n return false;\n }\n\n if (i > 0) {\n const double kPathSEpsilon = 1e-3;\n const auto& last_point = trajectory.trajectory_point(i - 1);\n if (point.path_point().s() + kPathSEpsilon <\n last_point.path_point().s()) {\n AERROR << \"Invalid trajectory point because s value error. last point: \"\n << last_point.DebugString()\n << \", curr point: \" << point.DebugString();\n return false;\n }\n }\n }\n return true;\n}\n\n} \/\/ namespace planning\n} \/\/ namespace apollo\n<|endoftext|>"} {"text":"<commit_before>#include \"twister.h\"\n\nconst unsigned CYCLE = 0x100;\n\n\/\/Suggest we wrap these arrays inside an fsm or test base class \nconst unsigned C_TRANS_ = 0xff;\nint block_units[][0x10] = {\n\t0x74, 0x63, 0x69, 0x91, 0x72, 0x36, 0x6e, 0x6c, 0x61, 0x67, 0x74, 0x6c, 0x69, 0x73, 0x61, 0x61, 0x6f, 0x6d, 0x6f, 0x72, 0x6e, 0x72, 0x69, 0x6d, 0x6e, 0x6e, 0x65, 0x74, 0x72, 0x6e, 0x6b, 0x73, 0x61, 0x6f, 0x65, 0x69, 0x73, 0x64, 0x6c, 0x65, 0x69, 0x6b, 0x68, 0x68, 0x68, 0x65, 0x72, 0x64, 0x66, 0x74, 0x61, 0x73, 0x6f, 0x69, 0x65, 0x74, 0x69, 0x68, 0x6e, 0x24, 0x62, 0x74, 0x6b, 0x65\n };\nint triad_units[][0x03] = {\n\t0x31, 0xfe, 0x45, 0x74, 0x68, 0x65, 0x74, 0x68, 0x61, 0x65, 0x74, 0x68, 0x66, 0x6f, 0x72, 0x65, 0x73, 0x74, 0x69, 0x6e, 0x67, 0x65, 0x72, 0x65, 0x68, 0x61, 0x74, 0x68, 0x69, 0x73, 0x1a, 0x36, 0x49, 0x91, 0x43, 0x53, 0xa9, 0xc3, 0x37, 0xaf, 0x08, 0xf0, 0xf3, 0x45, 0x91\n};\nconst int transition_seq[] = { 0xce, 0xab, 0xdf, 0xcf, 0xee,\n 0xcf, 0xad, 0xdf, 0xff, 0xce, \n 0x32, 0x40, 0xd3, 0x27, 0x82, \n 0xda, 0xee, 0xff, 0xfc, 0xbf, \n 0x1c, 0x90, 0x13, 0x4a, 0xa5, \n 0xe0, 0x21, 0x9f, 0xe1, 0xc6, \n 0xaf, 0x05, 0x81, 0xf0, 0xee, \n 0xe4, 0x38, 0x1f, 0x60, 0x24, \n 0x0c, 0x35, 0x51, 0x32, 0xcf, \n 0x12, 0x9a, 0x30, 0x44, 0x72, \n 0x51, 0x3c, 0x61, 0x2d, 0x5f, \n 0x04, 0x1c, 0x52, 0xca, 0xdf, \n 0x12, 0x0b, 0x30, 0xa0, 0x1e, \n 0x03, 0x14, 0x09, 0x73, 0x23, \n 0xf2, 0xca, 0xa2, 0x51, 0xc6, \n 0x01, 0xdf, 0x41, 0x96, 0xa0, \n 0x51, 0x19, 0x71, 0x23, 0x47, \n 0xcb, 0xbd, 0xba, 0xac, 0xdf, \n\t\t\t 0xdf, 0xde, 0xcd, 0xfd, 0xca };\n\nint ENTRY_LINK__ = 0x05;\nint ENTRY_LINK__TEST = 0x09;\nint ENTRY_C_REF_ECM = 0x10;\nint ENTRY_C_REF_ECM_TEST = 0x03;\nint ENTRY_C_OUTER = 0x51;\nint ENTRY_C_OUTER_PROD = 0x41;\nint ENTRY_C_OUTER_PROD_TEST = 0x33;\nint ENTRY_C_OUTER_PROD_TOR_TEST = 0x57;\nint ENTRY_A_OUTER_PROD_TOR_TEST = 0xc9;\nint ENTRY_B_OUTER_PROD_EUC_TEST = 0xaf;\nint ENTRY_C_OUTER_PROD_EUC_TEST = 0xa1;\nint ENTRY_C_INNER_PROD_EUC_TEST = 0xc5;\nint ENTRY_C_INNER_PROD_ELIP_TEST = 0xa2;\nint ENTRY_C_INNER_PROD_RELAY_TEST = 0xf5;\nint ENTRY_C_BLOCK_REL_FLAG_TEST = 0x0fffffff;\nint ENTRY_C_BLOCK_REL_FLAG_VECTOR = 0x0effffff;\n\n\n\nunsigned reflect(unsigned center, unsigned (*r)(unsigned))\n{\n return (*r)(center)^center;\n}\nunsigned char base(unsigned char a, unsigned char (*s)(unsigned char), int pos)\n{\n\treturn (*s)(pos)^a;\n}\n\nvoid transHomExt(vector<unsigned char>& data, unsigned char (*f)(unsigned char), unsigned char (*g)(unsigned char))\n{\n for(unsigned i = 0; i<data.size(); i++)\n {\n unsigned char d = data[i];\n for(unsigned j=0; j<CYCLE; j++)\n {\n d = (*f)(d)^base(d, g, d);\n }\n data[i] = d;\n }\n}\nvoid transHom(vector<unsigned char>& data, unsigned char (*f)(unsigned char), unsigned char (*g)(unsigned char))\n{\n for(unsigned i = 0; i<data.size(); i++)\n {\n unsigned char d = data[i];\n for(unsigned j=0; j<CYCLE; j++)\n {\n d = (*f)(d)^(*g)(d);\n }\n data[i] = d;\n }\n}\n\nvoid trans(vector<unsigned char>& data, unsigned char (*f)(unsigned char))\n{\n for(unsigned i = 0; i<data.size(); i++)\n {\n unsigned char d = data[i];\n for(unsigned j=0; j<CYCLE; j++)\n {\n d = (*f)(d);\n }\n data[i] = d;\n }\n}\n\nvector<double> f_dist(vector<unsigned char>& in)\n{\n vector<double> fdist;\n fdist.resize(256);\n for(unsigned i = 0; i<in.size(); i++)\n {\n fdist[in[i]]++;\n }\n\n for(unsigned i=0; i<fdist.size(); i++)\n {\n fdist[i] = (fdist[i] \/ in.size()) * 100;\n }\n\n return fdist;\n}\n\ndouble s_entropy(vector<double>& v) \n{\n double entropy = 0;\n double p;\n\n for(unsigned i = 0; i < v.size(); i++) \n {\n p = v[i] \/ 100;\n if (p == 0) continue;\n entropy += p * std::log(p) \/ std::log(2);\n }\n return -entropy;\n}\nvoid rms(const string& s, string& r)\n{\n for(unsigned int i=0; i<s.size(); i++)\n {\n if(::isspace(s[i])) continue;\n r+= s[i];\n }\n}\n\/\/add extended euc \ndouble sw(double weight, int i, int j, int (*inv)(int, int))\n{\n return weight*(*inv)(i, j); \n}\n\/\/Suggest we wrap these routines in a base class in particular for testing \n\/\/and expose test api \nvoid hPerm(int s, int n, void (*p)(int), void (*inv)(int, int), void (*center)(int))\n{\n if(transition_seq[ENTRY_C_INNER_PROD_RELAY_TEST] == s) \n {\n\t (*center)(s);\n\t return;\n }\n if(transition_seq[ENTRY_C_INNER_PROD_ELIP_TEST ] == s) \n {\n\t (*p)(s);\n\t return;\n }\n if(s == 1)\n {\n (*p)(n);\n return;\n }\n for(int i=0; i< s; i++)\n {\n hPerm(s-1, n, p, inv, p);\n if(s%2 == 1)\n (*inv)(0, s-1);\n else \n (*inv)(i, s-1);\n }\n}\n\ndouble ic(const string& t)\n{\n string text; rms(t, text);\n vector<double> freq(256,0);\n for(unsigned int i=0; i<text.size(); i++)\n {\n if(text[i] == ' ') continue;\n freq[text[i]] ++;\n }\n double sum=0;\n for(unsigned int i=0; i<freq.size(); i++)\n {\n if(freq[i] != 0)\n {\n double c = freq[i];\n if(c != 0)\n sum += c * (c - 1);\n }\n }\n double ic = 26 * sum \/ (text.size() * (text.size() - 1));\n return ic;\n}\n\nint outer_sect(int (*s)(int), int (*t)(int), int r, int q)\n{\n return (*s)(r) * (*t)(q);\n}\n\/\/chain cross ref - test - \nvoid multiChan(unsigned char* (*p)(unsigned char, unsigned char), unsigned char m)\n{\n unsigned char* chanIndicator = (*p)(transition_seq[ENTRY_C_REF_ECM], m); \n unsigned char* crossCh = (*p)(transition_seq[ENTRY_C_INNER_PROD_ELIP_TEST], m); \n *chanIndicator = *chanIndicator ^ *crossCh;\n *crossCh = *chanIndicator ^ *crossCh;\n *chanIndicator = *chanIndicator ^ *crossCh;\n\n}\n\nvoid switchIO(unsigned char (*p)(unsigned char, unsigned char), unsigned char m)\n{\n \/\/test seq\n (*p)(transition_seq[ENTRY_LINK__], m); \n (*p)(transition_seq[ENTRY_LINK__TEST], m); \n \/\/stream test , suggest these tests should be moved to a state transition class\n \/\/\n \/\/\n \/\/\n (*p)(transition_seq[ENTRY_C_REF_ECM], m ^ 0xff ); \n (*p)(transition_seq[ENTRY_C_INNER_PROD_ELIP_TEST ], m); \n (*p)(transition_seq[ENTRY_LINK__TEST], m ^ transition_seq[ENTRY_LINK__TEST]); \n (*p)(transition_seq[ENTRY_LINK__TEST], m ^ transition_seq[ENTRY_C_REF_ECM]); \n (*p)(transition_seq[ENTRY_LINK__TEST], m ^ transition_seq[ENTRY_C_INNER_PROD_ELIP_TEST]); \n \n}\n\n\/\/Suggest we wrap these in util base class, abstract col cont \nstd::tuple<int, int, int> extended_gcd(int __alpha, int __beta, int (*col)(int x, int y))\n{\n if(__alpha == 0) return make_tuple(__beta,0,1);\n int __com=0; \n int x=0; \n int y=0;\n tie(__com, x, y) = extended_gcd(__beta%__alpha, __alpha, col);\n return make_tuple(__com, y-(__beta\/__alpha)*x, x);\n}\n\/\/frmwk wrapper pending nh release, util base\n\/\/\nstd::tuple<int, int, int> extended_gcd(int __alpha, int __beta)\n{\n if(__alpha == 0) return make_tuple(__beta,0,1);\n int __com=0; \n int x=0; \n int y=0;\n tie(__com, x, y) = extended_gcd(__beta%__alpha, __alpha);\n return make_tuple(__com, y-(__beta\/__alpha)*x, x);\n}\n<commit_msg>pre release ux rewrite plus bootstrap extract plus extractor qt util quazip - production test harness<commit_after>#include \"twister.h\"\n\nconst unsigned CYCLE = 0x100;\n\n\/\/Suggest we wrap these arrays inside an fsm or test base class \nconst unsigned C_TRANS_ = 0xff;\nint block_units[][0x10] = {\n\t0x74, 0x63, 0x69, 0x91, 0x72, 0x36, 0x6e, 0x6c, 0x61, 0x67, 0x74, 0x6c, 0x69, 0x73, 0x61, 0x61, 0x6f, 0x6d, 0x6f, 0x72, 0x6e, 0x72, 0x69, 0x6d, 0x6e, 0x6e, 0x65, 0x74, 0x72, 0x6e, 0x6b, 0x73, 0x61, 0x6f, 0x65, 0x69, 0x73, 0x64, 0x6c, 0x65, 0x69, 0x6b, 0x68, 0x68, 0x68, 0x65, 0x72, 0x64, 0x66, 0x74, 0x61, 0x73, 0x6f, 0x69, 0x65, 0x74, 0x69, 0x68, 0x6e, 0x24, 0x62, 0x74, 0x6b, 0x65\n };\nint triad_units[][0x03] = {\n\t0x31, 0xfe, 0x45, 0x74, 0x68, 0x65, 0x74, 0x68, 0x61, 0x65, 0x74, 0x68, 0x66, 0x6f, 0x72, 0x65, 0x73, 0x74, 0x69, 0x6e, 0x67, 0x65, 0x72, 0x65, 0x68, 0x61, 0x74, 0x68, 0x69, 0x73, 0x1a, 0x36, 0x49, 0x91, 0x43, 0x53, 0xa9, 0xc3, 0x37, 0xaf, 0x08, 0xf0, 0xf3, 0x45, 0x91\n};\nconst int transition_seq[] = { 0xce, 0xab, 0xdf, 0xcf, 0xee,\n 0xcf, 0xad, 0xdf, 0xff, 0xce, \n 0x32, 0x40, 0xd3, 0x27, 0x82, \n 0xda, 0xee, 0xff, 0xfc, 0xbf, \n 0x1c, 0x90, 0x13, 0x4a, 0xa5, \n 0xe0, 0x21, 0x9f, 0xe1, 0xc6, \n 0xaf, 0x05, 0x81, 0xf0, 0xee, \n 0xe4, 0x38, 0x1f, 0x60, 0x24, \n 0x0c, 0x35, 0x51, 0x32, 0xcf, \n 0x12, 0x9a, 0x30, 0x44, 0x72, \n 0x51, 0x3c, 0x61, 0x2d, 0x5f, \n 0x04, 0x1c, 0x52, 0xca, 0xdf, \n 0x15, 0x37, 0x12, 0xca, 0xdf, \n 0x12, 0x0b, 0x30, 0xa0, 0x1e, \n 0x03, 0x14, 0x09, 0x73, 0x23, \n 0xf2, 0xca, 0xa2, 0x51, 0xc6, \n 0x01, 0xdf, 0x41, 0x96, 0xa0, \n 0x51, 0x19, 0x71, 0x23, 0x47, \n 0xcb, 0xbd, 0xba, 0xac, 0xdf, \n\t\t\t 0xdf, 0xde, 0xcd, 0xfd, 0xca };\n\nint ENTRY_LINK__ = 0x05;\nint ENTRY_LINK__TEST = 0x09;\nint ENTRY_C_REF_ECM = 0x10;\nint ENTRY_C_REF_ECM_TEST = 0x03;\nint ENTRY_C_OUTER = 0x51;\nint ENTRY_C_OUTER_PROD = 0x41;\nint ENTRY_C_OUTER_PROD_TEST = 0x33;\nint ENTRY_C_OUTER_PROD_TOR_TEST = 0x57;\nint ENTRY_A_OUTER_PROD_TOR_TEST = 0xc9;\nint ENTRY_B_OUTER_PROD_EUC_TEST = 0xaf;\nint ENTRY_C_OUTER_PROD_EUC_TEST = 0xa1;\nint ENTRY_C_INNER_PROD_EUC_TEST = 0xc5;\nint ENTRY_C_INNER_PROD_ELIP_TEST = 0xa2;\nint ENTRY_C_INNER_PROD_RELAY_TEST = 0xf5;\nint ENTRY_C_BLOCK_REL_FLAG_TEST = 0x0fffffff;\nint ENTRY_C_BLOCK_REL_FLAG_VECTOR = 0x0effffff;\n\n\n\nunsigned reflect(unsigned center, unsigned (*r)(unsigned))\n{\n return (*r)(center)^center;\n}\nunsigned char base(unsigned char a, unsigned char (*s)(unsigned char), int pos)\n{\n\treturn (*s)(pos)^a;\n}\n\nvoid transHomExt(vector<unsigned char>& data, unsigned char (*f)(unsigned char), unsigned char (*g)(unsigned char))\n{\n for(unsigned i = 0; i<data.size(); i++)\n {\n unsigned char d = data[i];\n for(unsigned j=0; j<CYCLE; j++)\n {\n d = (*f)(d)^base(d, g, d);\n }\n data[i] = d;\n }\n}\nvoid transHom(vector<unsigned char>& data, unsigned char (*f)(unsigned char), unsigned char (*g)(unsigned char))\n{\n for(unsigned i = 0; i<data.size(); i++)\n {\n unsigned char d = data[i];\n for(unsigned j=0; j<CYCLE; j++)\n {\n d = (*f)(d)^(*g)(d);\n }\n data[i] = d;\n }\n}\n\nvoid trans(vector<unsigned char>& data, unsigned char (*f)(unsigned char))\n{\n for(unsigned i = 0; i<data.size(); i++)\n {\n unsigned char d = data[i];\n for(unsigned j=0; j<CYCLE; j++)\n {\n d = (*f)(d);\n }\n data[i] = d;\n }\n}\n\nvector<double> f_dist(vector<unsigned char>& in)\n{\n vector<double> fdist;\n fdist.resize(256);\n for(unsigned i = 0; i<in.size(); i++)\n {\n fdist[in[i]]++;\n }\n\n for(unsigned i=0; i<fdist.size(); i++)\n {\n fdist[i] = (fdist[i] \/ in.size()) * 100;\n }\n\n return fdist;\n}\n\ndouble s_entropy(vector<double>& v) \n{\n double entropy = 0;\n double p;\n\n for(unsigned i = 0; i < v.size(); i++) \n {\n p = v[i] \/ 100;\n if (p == 0) continue;\n entropy += p * std::log(p) \/ std::log(2);\n }\n return -entropy;\n}\nvoid rms(const string& s, string& r)\n{\n for(unsigned int i=0; i<s.size(); i++)\n {\n if(::isspace(s[i])) continue;\n r+= s[i];\n }\n}\n\/\/add extended euc \ndouble sw(double weight, int i, int j, int (*inv)(int, int))\n{\n return weight*(*inv)(i, j); \n}\n\/\/Suggest we wrap these routines in a base class in particular for testing \n\/\/and expose test api \nvoid hPerm(int s, int n, void (*p)(int), void (*inv)(int, int), void (*center)(int))\n{\n if(transition_seq[ENTRY_C_INNER_PROD_RELAY_TEST] == s) \n {\n\t (*center)(s);\n\t return;\n }\n if(transition_seq[ENTRY_C_INNER_PROD_ELIP_TEST ] == s) \n {\n\t (*p)(s);\n\t return;\n }\n if(s == 1)\n {\n (*p)(n);\n return;\n }\n for(int i=0; i< s; i++)\n {\n hPerm(s-1, n, p, inv, p);\n if(s%2 == 1)\n (*inv)(0, s-1);\n else \n (*inv)(i, s-1);\n }\n}\n\ndouble ic(const string& t)\n{\n string text; rms(t, text);\n vector<double> freq(256,0);\n for(unsigned int i=0; i<text.size(); i++)\n {\n if(text[i] == ' ') continue;\n freq[text[i]] ++;\n }\n double sum=0;\n for(unsigned int i=0; i<freq.size(); i++)\n {\n if(freq[i] != 0)\n {\n double c = freq[i];\n if(c != 0)\n sum += c * (c - 1);\n }\n }\n double ic = 26 * sum \/ (text.size() * (text.size() - 1));\n return ic;\n}\n\nint outer_sect(int (*s)(int), int (*t)(int), int r, int q)\n{\n return (*s)(r) * (*t)(q);\n}\n\/\/chain cross ref - test - \nvoid multiChan(unsigned char* (*p)(unsigned char, unsigned char), unsigned char m)\n{\n unsigned char* chanIndicator = (*p)(transition_seq[ENTRY_C_REF_ECM], m); \n unsigned char* crossCh = (*p)(transition_seq[ENTRY_C_INNER_PROD_ELIP_TEST], m); \n *chanIndicator = *chanIndicator ^ *crossCh;\n *crossCh = *chanIndicator ^ *crossCh;\n *chanIndicator = *chanIndicator ^ *crossCh;\n\n}\n\nvoid switchIO(unsigned char (*p)(unsigned char, unsigned char), unsigned char m)\n{\n \/\/test seq\n (*p)(transition_seq[ENTRY_LINK__], m); \n (*p)(transition_seq[ENTRY_LINK__TEST], m); \n \/\/stream test , suggest these tests should be moved to a state transition class\n \/\/\n \/\/\n \/\/\n (*p)(transition_seq[ENTRY_C_REF_ECM], m ^ 0xff ); \n (*p)(transition_seq[ENTRY_C_INNER_PROD_ELIP_TEST ], m); \n (*p)(transition_seq[ENTRY_LINK__TEST], m ^ transition_seq[ENTRY_LINK__TEST]); \n (*p)(transition_seq[ENTRY_LINK__TEST], m ^ transition_seq[ENTRY_C_REF_ECM]); \n (*p)(transition_seq[ENTRY_LINK__TEST], m ^ transition_seq[ENTRY_C_INNER_PROD_ELIP_TEST]); \n \n}\n\n\/\/Suggest we wrap these in util base class, abstract col cont \nstd::tuple<int, int, int> extended_gcd(int __alpha, int __beta, int (*col)(int x, int y))\n{\n if(__alpha == 0) return make_tuple(__beta,0,1);\n int __com=0; \n int x=0; \n int y=0;\n tie(__com, x, y) = extended_gcd(__beta%__alpha, __alpha, col);\n return make_tuple(__com, y-(__beta\/__alpha)*x, x);\n}\n\/\/frmwk wrapper pending nh release, util base\n\/\/\nstd::tuple<int, int, int> extended_gcd(int __alpha, int __beta)\n{\n if(__alpha == 0) return make_tuple(__beta,0,1);\n int __com=0; \n int x=0; \n int y=0;\n tie(__com, x, y) = extended_gcd(__beta%__alpha, __alpha);\n return make_tuple(__com, y-(__beta\/__alpha)*x, x);\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (C) 2010 The Android Open Source Project\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"SkJpegUtility.h\"\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nstatic void sk_init_source(j_decompress_ptr cinfo) {\n skjpeg_source_mgr* src = (skjpeg_source_mgr*)cinfo->src;\n src->next_input_byte = (const JOCTET*)src->fBuffer;\n src->bytes_in_buffer = 0;\n}\n\nstatic boolean sk_fill_input_buffer(j_decompress_ptr cinfo) {\n skjpeg_source_mgr* src = (skjpeg_source_mgr*)cinfo->src;\n if (src->fDecoder != NULL && src->fDecoder->shouldCancelDecode()) {\n return FALSE;\n }\n size_t bytes = src->fStream->read(src->fBuffer, skjpeg_source_mgr::kBufferSize);\n \/\/ note that JPEG is happy with less than the full read,\n \/\/ as long as the result is non-zero\n if (bytes == 0) {\n return FALSE;\n }\n\n src->next_input_byte = (const JOCTET*)src->fBuffer;\n src->bytes_in_buffer = bytes;\n return TRUE;\n}\n\nstatic void sk_skip_input_data(j_decompress_ptr cinfo, long num_bytes) {\n SkASSERT(num_bytes > 0);\n\n skjpeg_source_mgr* src = (skjpeg_source_mgr*)cinfo->src;\n\n long bytesToSkip = num_bytes - src->bytes_in_buffer;\n\n \/\/ check if the skip amount exceeds the current buffer\n if (bytesToSkip > 0) {\n size_t bytes = src->fStream->skip(bytesToSkip);\n if (bytes != (size_t)bytesToSkip) {\n\/\/ SkDebugf(\"xxxxxxxxxxxxxx failure to skip request %d actual %d\\n\", bytesToSkip, bytes);\n cinfo->err->error_exit((j_common_ptr)cinfo);\n }\n src->next_input_byte = (const JOCTET*)src->fBuffer;\n src->bytes_in_buffer = 0;\n } else {\n src->next_input_byte += num_bytes;\n src->bytes_in_buffer -= num_bytes;\n }\n}\n\nstatic boolean sk_resync_to_restart(j_decompress_ptr cinfo, int desired) {\n skjpeg_source_mgr* src = (skjpeg_source_mgr*)cinfo->src;\n\n \/\/ what is the desired param for???\n\n if (!src->fStream->rewind()) {\n SkDebugf(\"xxxxxxxxxxxxxx failure to rewind\\n\");\n cinfo->err->error_exit((j_common_ptr)cinfo);\n return FALSE;\n }\n src->next_input_byte = (const JOCTET*)src->fBuffer;\n src->bytes_in_buffer = 0;\n return TRUE;\n}\n\nstatic void sk_term_source(j_decompress_ptr \/*cinfo*\/) {}\n\n\nstatic void skmem_init_source(j_decompress_ptr cinfo) {\n skjpeg_source_mgr* src = (skjpeg_source_mgr*)cinfo->src;\n src->next_input_byte = (const JOCTET*)src->fMemoryBase;\n src->bytes_in_buffer = src->fMemoryBaseSize;\n}\n\nstatic boolean skmem_fill_input_buffer(j_decompress_ptr cinfo) {\n SkDebugf(\"xxxxxxxxxxxxxx skmem_fill_input_buffer called\\n\");\n return FALSE;\n}\n\nstatic void skmem_skip_input_data(j_decompress_ptr cinfo, long num_bytes) {\n skjpeg_source_mgr* src = (skjpeg_source_mgr*)cinfo->src;\n\/\/ SkDebugf(\"xxxxxxxxxxxxxx skmem_skip_input_data called %d\\n\", num_bytes);\n src->next_input_byte = (const JOCTET*)((const char*)src->next_input_byte + num_bytes);\n src->bytes_in_buffer -= num_bytes;\n}\n\nstatic boolean skmem_resync_to_restart(j_decompress_ptr cinfo, int desired) {\n SkDebugf(\"xxxxxxxxxxxxxx skmem_resync_to_restart called\\n\");\n return TRUE;\n}\n\nstatic void skmem_term_source(j_decompress_ptr \/*cinfo*\/) {}\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nskjpeg_source_mgr::skjpeg_source_mgr(SkStream* stream, SkImageDecoder* decoder) : fStream(stream) {\n fDecoder = decoder;\n const void* baseAddr = stream->getMemoryBase();\n if (baseAddr && false) {\n fMemoryBase = baseAddr;\n fMemoryBaseSize = stream->getLength();\n\n init_source = skmem_init_source;\n fill_input_buffer = skmem_fill_input_buffer;\n skip_input_data = skmem_skip_input_data;\n resync_to_restart = skmem_resync_to_restart;\n term_source = skmem_term_source;\n } else {\n fMemoryBase = NULL;\n fMemoryBaseSize = 0;\n\n init_source = sk_init_source;\n fill_input_buffer = sk_fill_input_buffer;\n skip_input_data = sk_skip_input_data;\n resync_to_restart = sk_resync_to_restart;\n term_source = sk_term_source;\n }\n\/\/ SkDebugf(\"**************** use memorybase %p %d\\n\", fMemoryBase, fMemoryBaseSize);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstatic void sk_init_destination(j_compress_ptr cinfo) {\n skjpeg_destination_mgr* dest = (skjpeg_destination_mgr*)cinfo->dest;\n\n dest->next_output_byte = dest->fBuffer;\n dest->free_in_buffer = skjpeg_destination_mgr::kBufferSize;\n}\n\nstatic boolean sk_empty_output_buffer(j_compress_ptr cinfo) {\n skjpeg_destination_mgr* dest = (skjpeg_destination_mgr*)cinfo->dest;\n\n\/\/ if (!dest->fStream->write(dest->fBuffer, skjpeg_destination_mgr::kBufferSize - dest->free_in_buffer))\n if (!dest->fStream->write(dest->fBuffer,\n skjpeg_destination_mgr::kBufferSize)) {\n ERREXIT(cinfo, JERR_FILE_WRITE);\n return false;\n }\n\n dest->next_output_byte = dest->fBuffer;\n dest->free_in_buffer = skjpeg_destination_mgr::kBufferSize;\n return TRUE;\n}\n\nstatic void sk_term_destination (j_compress_ptr cinfo) {\n skjpeg_destination_mgr* dest = (skjpeg_destination_mgr*)cinfo->dest;\n\n size_t size = skjpeg_destination_mgr::kBufferSize - dest->free_in_buffer;\n if (size > 0) {\n if (!dest->fStream->write(dest->fBuffer, size)) {\n ERREXIT(cinfo, JERR_FILE_WRITE);\n return;\n }\n }\n dest->fStream->flush();\n}\n\nskjpeg_destination_mgr::skjpeg_destination_mgr(SkWStream* stream)\n : fStream(stream) {\n this->init_destination = sk_init_destination;\n this->empty_output_buffer = sk_empty_output_buffer;\n this->term_destination = sk_term_destination;\n}\n\nvoid skjpeg_error_exit(j_common_ptr cinfo) {\n skjpeg_error_mgr* error = (skjpeg_error_mgr*)cinfo->err;\n\n (*error->output_message) (cinfo);\n\n \/* Let the memory manager delete any temp files before we die *\/\n jpeg_destroy(cinfo);\n\n longjmp(error->fJmpBuf, -1);\n}\n<commit_msg>call skip in a loop to handle the case where the backing stream may be network based, and will only block to fulfill the request after it has skipped its current buffer.<commit_after>\/*\n * Copyright (C) 2010 The Android Open Source Project\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"SkJpegUtility.h\"\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nstatic void sk_init_source(j_decompress_ptr cinfo) {\n skjpeg_source_mgr* src = (skjpeg_source_mgr*)cinfo->src;\n src->next_input_byte = (const JOCTET*)src->fBuffer;\n src->bytes_in_buffer = 0;\n}\n\nstatic boolean sk_fill_input_buffer(j_decompress_ptr cinfo) {\n skjpeg_source_mgr* src = (skjpeg_source_mgr*)cinfo->src;\n if (src->fDecoder != NULL && src->fDecoder->shouldCancelDecode()) {\n return FALSE;\n }\n size_t bytes = src->fStream->read(src->fBuffer, skjpeg_source_mgr::kBufferSize);\n \/\/ note that JPEG is happy with less than the full read,\n \/\/ as long as the result is non-zero\n if (bytes == 0) {\n return FALSE;\n }\n\n src->next_input_byte = (const JOCTET*)src->fBuffer;\n src->bytes_in_buffer = bytes;\n return TRUE;\n}\n\nstatic void sk_skip_input_data(j_decompress_ptr cinfo, long num_bytes) {\n skjpeg_source_mgr* src = (skjpeg_source_mgr*)cinfo->src;\n\n if (num_bytes > src->bytes_in_buffer) {\n long bytesToSkip = num_bytes - src->bytes_in_buffer;\n while (bytesToSkip > 0) {\n long bytes = (long)src->fStream->skip(bytesToSkip);\n if (bytes <= 0 || bytes > bytesToSkip) {\n\/\/ SkDebugf(\"xxxxxxxxxxxxxx failure to skip request %d returned %d\\n\", bytesToSkip, bytes);\n cinfo->err->error_exit((j_common_ptr)cinfo);\n return;\n }\n bytesToSkip -= bytes;\n }\n src->next_input_byte = (const JOCTET*)src->fBuffer;\n src->bytes_in_buffer = 0;\n } else {\n src->next_input_byte += num_bytes;\n src->bytes_in_buffer -= num_bytes;\n }\n}\n\nstatic boolean sk_resync_to_restart(j_decompress_ptr cinfo, int desired) {\n skjpeg_source_mgr* src = (skjpeg_source_mgr*)cinfo->src;\n\n \/\/ what is the desired param for???\n\n if (!src->fStream->rewind()) {\n SkDebugf(\"xxxxxxxxxxxxxx failure to rewind\\n\");\n cinfo->err->error_exit((j_common_ptr)cinfo);\n return FALSE;\n }\n src->next_input_byte = (const JOCTET*)src->fBuffer;\n src->bytes_in_buffer = 0;\n return TRUE;\n}\n\nstatic void sk_term_source(j_decompress_ptr \/*cinfo*\/) {}\n\n\nstatic void skmem_init_source(j_decompress_ptr cinfo) {\n skjpeg_source_mgr* src = (skjpeg_source_mgr*)cinfo->src;\n src->next_input_byte = (const JOCTET*)src->fMemoryBase;\n src->bytes_in_buffer = src->fMemoryBaseSize;\n}\n\nstatic boolean skmem_fill_input_buffer(j_decompress_ptr cinfo) {\n SkDebugf(\"xxxxxxxxxxxxxx skmem_fill_input_buffer called\\n\");\n return FALSE;\n}\n\nstatic void skmem_skip_input_data(j_decompress_ptr cinfo, long num_bytes) {\n skjpeg_source_mgr* src = (skjpeg_source_mgr*)cinfo->src;\n\/\/ SkDebugf(\"xxxxxxxxxxxxxx skmem_skip_input_data called %d\\n\", num_bytes);\n src->next_input_byte = (const JOCTET*)((const char*)src->next_input_byte + num_bytes);\n src->bytes_in_buffer -= num_bytes;\n}\n\nstatic boolean skmem_resync_to_restart(j_decompress_ptr cinfo, int desired) {\n SkDebugf(\"xxxxxxxxxxxxxx skmem_resync_to_restart called\\n\");\n return TRUE;\n}\n\nstatic void skmem_term_source(j_decompress_ptr \/*cinfo*\/) {}\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nskjpeg_source_mgr::skjpeg_source_mgr(SkStream* stream, SkImageDecoder* decoder) : fStream(stream) {\n fDecoder = decoder;\n const void* baseAddr = stream->getMemoryBase();\n if (baseAddr && false) {\n fMemoryBase = baseAddr;\n fMemoryBaseSize = stream->getLength();\n\n init_source = skmem_init_source;\n fill_input_buffer = skmem_fill_input_buffer;\n skip_input_data = skmem_skip_input_data;\n resync_to_restart = skmem_resync_to_restart;\n term_source = skmem_term_source;\n } else {\n fMemoryBase = NULL;\n fMemoryBaseSize = 0;\n\n init_source = sk_init_source;\n fill_input_buffer = sk_fill_input_buffer;\n skip_input_data = sk_skip_input_data;\n resync_to_restart = sk_resync_to_restart;\n term_source = sk_term_source;\n }\n\/\/ SkDebugf(\"**************** use memorybase %p %d\\n\", fMemoryBase, fMemoryBaseSize);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstatic void sk_init_destination(j_compress_ptr cinfo) {\n skjpeg_destination_mgr* dest = (skjpeg_destination_mgr*)cinfo->dest;\n\n dest->next_output_byte = dest->fBuffer;\n dest->free_in_buffer = skjpeg_destination_mgr::kBufferSize;\n}\n\nstatic boolean sk_empty_output_buffer(j_compress_ptr cinfo) {\n skjpeg_destination_mgr* dest = (skjpeg_destination_mgr*)cinfo->dest;\n\n\/\/ if (!dest->fStream->write(dest->fBuffer, skjpeg_destination_mgr::kBufferSize - dest->free_in_buffer))\n if (!dest->fStream->write(dest->fBuffer,\n skjpeg_destination_mgr::kBufferSize)) {\n ERREXIT(cinfo, JERR_FILE_WRITE);\n return false;\n }\n\n dest->next_output_byte = dest->fBuffer;\n dest->free_in_buffer = skjpeg_destination_mgr::kBufferSize;\n return TRUE;\n}\n\nstatic void sk_term_destination (j_compress_ptr cinfo) {\n skjpeg_destination_mgr* dest = (skjpeg_destination_mgr*)cinfo->dest;\n\n size_t size = skjpeg_destination_mgr::kBufferSize - dest->free_in_buffer;\n if (size > 0) {\n if (!dest->fStream->write(dest->fBuffer, size)) {\n ERREXIT(cinfo, JERR_FILE_WRITE);\n return;\n }\n }\n dest->fStream->flush();\n}\n\nskjpeg_destination_mgr::skjpeg_destination_mgr(SkWStream* stream)\n : fStream(stream) {\n this->init_destination = sk_init_destination;\n this->empty_output_buffer = sk_empty_output_buffer;\n this->term_destination = sk_term_destination;\n}\n\nvoid skjpeg_error_exit(j_common_ptr cinfo) {\n skjpeg_error_mgr* error = (skjpeg_error_mgr*)cinfo->err;\n\n (*error->output_message) (cinfo);\n\n \/* Let the memory manager delete any temp files before we die *\/\n jpeg_destroy(cinfo);\n\n longjmp(error->fJmpBuf, -1);\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"internal_declarations.hpp\"\n#include \"global_kernel_state.hpp\"\n#include \"thread_local_kernel_state.hpp\"\n#include <cgc1\/cgc1.hpp>\n#include <cstring>\n#include <cgc1\/cgc1_dll.hpp>\nnamespace cgc1\n{\n namespace details\n {\n global_kernel_state_t g_gks;\n void thread_gc_handler(int)\n {\n g_gks._collect_current_thread();\n }\n#ifdef __APPLE__\n pthread_key_t g_pkey;\n#else\n#ifndef _WIN32\n thread_local thread_local_kernel_state_t *t_tlks;\n#else\n __declspec(thread) thread_local_kernel_state_t *t_tlks;\n#endif\n#endif\n }\n namespace debug\n {\n size_t num_gc_collections() noexcept\n {\n return details::g_gks.num_collections();\n }\n\n auto _cgc_hidden_packed_marked(uintptr_t loc) -> bool\n {\n auto state = cgc1::details::get_state(cgc1::unhide_pointer(loc));\n auto index = state->get_index(cgc1::unhide_pointer(loc));\n return state->is_marked(index);\n }\n auto _cgc_hidden_packed_free(uintptr_t loc) -> bool\n {\n auto state = cgc1::details::get_state(cgc1::unhide_pointer(loc));\n auto index = state->get_index(cgc1::unhide_pointer(loc));\n return state->is_free(index);\n }\n }\n bool in_signal_handler() noexcept\n {\n auto tlks = details::get_tlks();\n if (tlks)\n return tlks->in_signal_handler();\n return false;\n }\n\n void *cgc_malloc(size_t sz)\n {\n auto &ta = details::g_gks.gc_allocator().initialize_thread();\n return ta.allocate(sz);\n }\n uintptr_t cgc_hidden_malloc(size_t sz)\n {\n void *addr = cgc_malloc(sz);\n secure_zero(addr, sz);\n return hide_pointer(addr);\n }\n void *cgc_realloc(void *v, size_t sz)\n {\n void *ret = cgc_malloc(sz);\n ::memcpy(ret, v, sz);\n return ret;\n }\n void cgc_free(void *v)\n {\n auto &ta = details::g_gks.gc_allocator().initialize_thread();\n ta.destroy(v);\n }\n bool cgc_is_cgc(void *v)\n {\n return cgc_size(v) > 0;\n }\n void *cgc_start(void *addr)\n {\n if (!addr)\n return nullptr;\n if (addr >= details::g_gks.fast_slab_begin() && addr < details::g_gks.fast_slab_end()) {\n auto state = details::get_state(addr);\n if (state->has_valid_magic_numbers())\n return state->begin() + state->get_index(addr) * state->real_entry_size();\n return nullptr;\n }\n details::object_state_t *os = details::object_state_t::from_object_start(addr);\n if (!details::g_gks.is_valid_object_state(os)) {\n os = details::g_gks.find_valid_object_state(addr);\n if (!os)\n return nullptr;\n }\n return os->object_start();\n }\n size_t cgc_size(void *addr)\n {\n if (!addr)\n return 0;\n void *start = cgc_start(addr);\n if (!start)\n return 0;\n if (start >= details::g_gks.fast_slab_begin() && start < details::g_gks.fast_slab_end()) {\n auto state = details::get_state(addr);\n if (state->has_valid_magic_numbers())\n return state->declared_entry_size();\n return 0;\n }\n details::object_state_t *os = details::object_state_t::from_object_start(start);\n if (os)\n return os->object_size();\n else\n return 0;\n }\n void cgc_add_root(void **v)\n {\n details::g_gks.add_root(v);\n }\n void cgc_remove_root(void **v)\n {\n details::g_gks.remove_root(v);\n }\n size_t cgc_heap_size()\n {\n \/\/ this cast is safe because end > begin is an invariant.\n return static_cast<size_t>(details::g_gks.gc_allocator().end() - details::g_gks.gc_allocator().begin());\n }\n size_t cgc_heap_free()\n {\n \/\/ this cast is safe because end > current_end is an invariant.\n return static_cast<size_t>(details::g_gks.gc_allocator().end() - details::g_gks.gc_allocator().current_end());\n }\n void cgc_enable()\n {\n details::g_gks.enable();\n }\n void cgc_disable()\n {\n details::g_gks.disable();\n }\n bool cgc_is_enabled()\n {\n return details::g_gks.enabled();\n }\n void cgc_register_thread(void *top_of_stack)\n {\n details::g_gks.initialize_current_thread(top_of_stack);\n }\n void cgc_collect()\n {\n details::g_gks.collect();\n }\n void cgc_force_collect()\n {\n details::g_gks.force_collect();\n }\n void cgc_unregister_thread()\n {\n details::g_gks.destroy_current_thread();\n }\n void cgc_shutdown()\n {\n details::g_gks.shutdown();\n }\n void cgc_register_finalizer(void *addr, ::std::function<void(void *)> finalizer)\n {\n if (!addr)\n return;\n void *start = cgc_start(addr);\n if (!start)\n return;\n details::object_state_t *os = details::object_state_t::from_object_start(start);\n details::gc_user_data_t *ud = static_cast<details::gc_user_data_t *>(os->user_data());\n if (ud->m_is_default) {\n ud = make_unique_allocator<details::gc_user_data_t, cgc_internal_allocator_t<void>>(*ud).release();\n ud->m_is_default = false;\n os->set_user_data(ud);\n }\n ud->m_finalizer = finalizer;\n }\n void cgc_set_uncollectable(void *addr, bool is_uncollectable)\n {\n if (!addr)\n return;\n void *start = cgc_start(addr);\n if (!start)\n return;\n details::object_state_t *os = details::object_state_t::from_object_start(start);\n details::gc_user_data_t *ud = static_cast<details::gc_user_data_t *>(os->user_data());\n if (ud->m_is_default) {\n ud = make_unique_allocator<details::gc_user_data_t, cgc_internal_allocator_t<void>>(*ud).release();\n ud->m_is_default = false;\n os->set_user_data(ud);\n }\n ud->m_uncollectable = is_uncollectable;\n set_complex(os, true);\n }\n void cgc_set_atomic(void *addr, bool is_atomic)\n {\n if (!addr)\n return;\n void *start = cgc_start(addr);\n if (!start)\n return;\n details::object_state_t *os = details::object_state_t::from_object_start(start);\n set_atomic(os, is_atomic);\n }\n}\nextern \"C\" {\nCGC1_DLL_PUBLIC void *GC_realloc(void *old_object, ::std::size_t new_size)\n{\n return cgc1::cgc_realloc(old_object, new_size);\n}\nCGC1_DLL_PUBLIC void *GC_malloc(::std::size_t size_in_bytes)\n{\n return cgc1::cgc_malloc(size_in_bytes);\n}\nCGC1_DLL_PUBLIC void *GC_malloc_atomic(::std::size_t size_in_bytes)\n{\n auto ret = cgc1::cgc_malloc(size_in_bytes);\n cgc1::cgc_set_atomic(ret, true);\n return ret;\n}\nCGC1_DLL_PUBLIC void *GC_malloc_uncollectable(::std::size_t size_in_bytes)\n{\n auto ret = cgc1::cgc_malloc(size_in_bytes);\n cgc1::cgc_set_uncollectable(ret, true);\n return ret;\n}\nCGC1_DLL_PUBLIC void GC_free(void *object_addr)\n{\n cgc1::cgc_free(object_addr);\n}\nCGC1_DLL_PUBLIC void GC_init(void *stack_addr)\n{\n cgc1::cgc_register_thread(stack_addr);\n}\nCGC1_DLL_PUBLIC void GC_gcollect()\n{\n cgc1::cgc_force_collect();\n}\nCGC1_DLL_PUBLIC void GC_register_finalizer(void *addr, void (*finalizer)(void *, void *), void *user_data, void *b, void *c)\n{\n if (b || c) {\n ::std::cerr << \"arguments to register finalizer must be null\\n\";\n abort();\n }\n auto real_finalizer = [finalizer, user_data](void *ptr) { finalizer(ptr, user_data); };\n cgc1::cgc_register_finalizer(addr, real_finalizer);\n}\nCGC1_DLL_PUBLIC int GC_get_heap_size()\n{\n return ::std::numeric_limits<int>::max();\n}\nCGC1_DLL_PUBLIC int GC_get_gc_no()\n{\n return static_cast<int>(::cgc1::debug::num_gc_collections());\n}\nCGC1_DLL_PUBLIC int GC_get_parallel()\n{\n return true;\n}\nCGC1_DLL_PUBLIC int GC_get_finalize_on_demand()\n{\n return false;\n}\nCGC1_DLL_PUBLIC int GC_get_java_finalization()\n{\n return false;\n}\nCGC1_DLL_PUBLIC int GC_get_dont_expand()\n{\n return false;\n}\nCGC1_DLL_PUBLIC int GC_get_full_freq()\n{\n return 0;\n}\nCGC1_DLL_PUBLIC int GC_get_max_retries()\n{\n return 0;\n}\nCGC1_DLL_PUBLIC unsigned long GC_get_time_limit()\n{\n return ::std::numeric_limits<unsigned long>::max();\n}\nCGC1_DLL_PUBLIC long GC_get_free_space_divisor()\n{\n return 1;\n}\nCGC1_DLL_PUBLIC long GC_get_all_interior_pointers()\n{\n return 0;\n}\nCGC1_DLL_PUBLIC void *GC_base(void *addr)\n{\n return cgc1::cgc_start(addr);\n}\nCGC1_DLL_PUBLIC int GC_is_visible(void *)\n{\n return 1;\n}\nCGC1_DLL_PUBLIC void *GC_check_annotated_obj(void *)\n{\n return nullptr;\n}\n}\n<commit_msg>realloc should correctly handle nullptr input<commit_after>#include \"internal_declarations.hpp\"\n#include \"global_kernel_state.hpp\"\n#include \"thread_local_kernel_state.hpp\"\n#include <cgc1\/cgc1.hpp>\n#include <cstring>\n#include <cgc1\/cgc1_dll.hpp>\nnamespace cgc1\n{\n namespace details\n {\n global_kernel_state_t g_gks;\n void thread_gc_handler(int)\n {\n g_gks._collect_current_thread();\n }\n#ifdef __APPLE__\n pthread_key_t g_pkey;\n#else\n#ifndef _WIN32\n thread_local thread_local_kernel_state_t *t_tlks;\n#else\n __declspec(thread) thread_local_kernel_state_t *t_tlks;\n#endif\n#endif\n }\n namespace debug\n {\n size_t num_gc_collections() noexcept\n {\n return details::g_gks.num_collections();\n }\n\n auto _cgc_hidden_packed_marked(uintptr_t loc) -> bool\n {\n auto state = cgc1::details::get_state(cgc1::unhide_pointer(loc));\n auto index = state->get_index(cgc1::unhide_pointer(loc));\n return state->is_marked(index);\n }\n auto _cgc_hidden_packed_free(uintptr_t loc) -> bool\n {\n auto state = cgc1::details::get_state(cgc1::unhide_pointer(loc));\n auto index = state->get_index(cgc1::unhide_pointer(loc));\n return state->is_free(index);\n }\n }\n bool in_signal_handler() noexcept\n {\n auto tlks = details::get_tlks();\n if (tlks)\n return tlks->in_signal_handler();\n return false;\n }\n\n void *cgc_malloc(size_t sz)\n {\n auto &ta = details::g_gks.gc_allocator().initialize_thread();\n return ta.allocate(sz);\n }\n uintptr_t cgc_hidden_malloc(size_t sz)\n {\n void *addr = cgc_malloc(sz);\n secure_zero(addr, sz);\n return hide_pointer(addr);\n }\n void *cgc_realloc(void *v, size_t sz)\n {\n void *ret = cgc_malloc(sz);\n if(v)\n ::memcpy(ret, v, sz);\n return ret;\n }\n void cgc_free(void *v)\n {\n auto &ta = details::g_gks.gc_allocator().initialize_thread();\n ta.destroy(v);\n }\n bool cgc_is_cgc(void *v)\n {\n return cgc_size(v) > 0;\n }\n void *cgc_start(void *addr)\n {\n if (!addr)\n return nullptr;\n if (addr >= details::g_gks.fast_slab_begin() && addr < details::g_gks.fast_slab_end()) {\n auto state = details::get_state(addr);\n if (state->has_valid_magic_numbers())\n return state->begin() + state->get_index(addr) * state->real_entry_size();\n return nullptr;\n }\n details::object_state_t *os = details::object_state_t::from_object_start(addr);\n if (!details::g_gks.is_valid_object_state(os)) {\n os = details::g_gks.find_valid_object_state(addr);\n if (!os)\n return nullptr;\n }\n return os->object_start();\n }\n size_t cgc_size(void *addr)\n {\n if (!addr)\n return 0;\n void *start = cgc_start(addr);\n if (!start)\n return 0;\n if (start >= details::g_gks.fast_slab_begin() && start < details::g_gks.fast_slab_end()) {\n auto state = details::get_state(addr);\n if (state->has_valid_magic_numbers())\n return state->declared_entry_size();\n return 0;\n }\n details::object_state_t *os = details::object_state_t::from_object_start(start);\n if (os)\n return os->object_size();\n else\n return 0;\n }\n void cgc_add_root(void **v)\n {\n details::g_gks.add_root(v);\n }\n void cgc_remove_root(void **v)\n {\n details::g_gks.remove_root(v);\n }\n size_t cgc_heap_size()\n {\n \/\/ this cast is safe because end > begin is an invariant.\n return static_cast<size_t>(details::g_gks.gc_allocator().end() - details::g_gks.gc_allocator().begin());\n }\n size_t cgc_heap_free()\n {\n \/\/ this cast is safe because end > current_end is an invariant.\n return static_cast<size_t>(details::g_gks.gc_allocator().end() - details::g_gks.gc_allocator().current_end());\n }\n void cgc_enable()\n {\n details::g_gks.enable();\n }\n void cgc_disable()\n {\n details::g_gks.disable();\n }\n bool cgc_is_enabled()\n {\n return details::g_gks.enabled();\n }\n void cgc_register_thread(void *top_of_stack)\n {\n details::g_gks.initialize_current_thread(top_of_stack);\n }\n void cgc_collect()\n {\n details::g_gks.collect();\n }\n void cgc_force_collect()\n {\n details::g_gks.force_collect();\n }\n void cgc_unregister_thread()\n {\n details::g_gks.destroy_current_thread();\n }\n void cgc_shutdown()\n {\n details::g_gks.shutdown();\n }\n void cgc_register_finalizer(void *addr, ::std::function<void(void *)> finalizer)\n {\n if (!addr)\n return;\n void *start = cgc_start(addr);\n if (!start)\n return;\n details::object_state_t *os = details::object_state_t::from_object_start(start);\n details::gc_user_data_t *ud = static_cast<details::gc_user_data_t *>(os->user_data());\n if (ud->m_is_default) {\n ud = make_unique_allocator<details::gc_user_data_t, cgc_internal_allocator_t<void>>(*ud).release();\n ud->m_is_default = false;\n os->set_user_data(ud);\n }\n ud->m_finalizer = finalizer;\n }\n void cgc_set_uncollectable(void *addr, bool is_uncollectable)\n {\n if (!addr)\n return;\n void *start = cgc_start(addr);\n if (!start)\n return;\n details::object_state_t *os = details::object_state_t::from_object_start(start);\n details::gc_user_data_t *ud = static_cast<details::gc_user_data_t *>(os->user_data());\n if (ud->m_is_default) {\n ud = make_unique_allocator<details::gc_user_data_t, cgc_internal_allocator_t<void>>(*ud).release();\n ud->m_is_default = false;\n os->set_user_data(ud);\n }\n ud->m_uncollectable = is_uncollectable;\n set_complex(os, true);\n }\n void cgc_set_atomic(void *addr, bool is_atomic)\n {\n if (!addr)\n return;\n void *start = cgc_start(addr);\n if (!start)\n return;\n details::object_state_t *os = details::object_state_t::from_object_start(start);\n set_atomic(os, is_atomic);\n }\n}\nextern \"C\" {\nCGC1_DLL_PUBLIC void *GC_realloc(void *old_object, ::std::size_t new_size)\n{\n return cgc1::cgc_realloc(old_object, new_size);\n}\nCGC1_DLL_PUBLIC void *GC_malloc(::std::size_t size_in_bytes)\n{\n return cgc1::cgc_malloc(size_in_bytes);\n}\nCGC1_DLL_PUBLIC void *GC_malloc_atomic(::std::size_t size_in_bytes)\n{\n auto ret = cgc1::cgc_malloc(size_in_bytes);\n cgc1::cgc_set_atomic(ret, true);\n return ret;\n}\nCGC1_DLL_PUBLIC void *GC_malloc_uncollectable(::std::size_t size_in_bytes)\n{\n auto ret = cgc1::cgc_malloc(size_in_bytes);\n cgc1::cgc_set_uncollectable(ret, true);\n return ret;\n}\nCGC1_DLL_PUBLIC void GC_free(void *object_addr)\n{\n cgc1::cgc_free(object_addr);\n}\nCGC1_DLL_PUBLIC void GC_init(void *stack_addr)\n{\n cgc1::cgc_register_thread(stack_addr);\n}\nCGC1_DLL_PUBLIC void GC_gcollect()\n{\n cgc1::cgc_force_collect();\n}\nCGC1_DLL_PUBLIC void GC_register_finalizer(void *addr, void (*finalizer)(void *, void *), void *user_data, void *b, void *c)\n{\n if (b || c) {\n ::std::cerr << \"arguments to register finalizer must be null\\n\";\n abort();\n }\n auto real_finalizer = [finalizer, user_data](void *ptr) { finalizer(ptr, user_data); };\n cgc1::cgc_register_finalizer(addr, real_finalizer);\n}\nCGC1_DLL_PUBLIC int GC_get_heap_size()\n{\n return ::std::numeric_limits<int>::max();\n}\nCGC1_DLL_PUBLIC int GC_get_gc_no()\n{\n return static_cast<int>(::cgc1::debug::num_gc_collections());\n}\nCGC1_DLL_PUBLIC int GC_get_parallel()\n{\n return true;\n}\nCGC1_DLL_PUBLIC int GC_get_finalize_on_demand()\n{\n return false;\n}\nCGC1_DLL_PUBLIC int GC_get_java_finalization()\n{\n return false;\n}\nCGC1_DLL_PUBLIC int GC_get_dont_expand()\n{\n return false;\n}\nCGC1_DLL_PUBLIC int GC_get_full_freq()\n{\n return 0;\n}\nCGC1_DLL_PUBLIC int GC_get_max_retries()\n{\n return 0;\n}\nCGC1_DLL_PUBLIC unsigned long GC_get_time_limit()\n{\n return ::std::numeric_limits<unsigned long>::max();\n}\nCGC1_DLL_PUBLIC long GC_get_free_space_divisor()\n{\n return 1;\n}\nCGC1_DLL_PUBLIC long GC_get_all_interior_pointers()\n{\n return 0;\n}\nCGC1_DLL_PUBLIC void *GC_base(void *addr)\n{\n return cgc1::cgc_start(addr);\n}\nCGC1_DLL_PUBLIC int GC_is_visible(void *)\n{\n return 1;\n}\nCGC1_DLL_PUBLIC void *GC_check_annotated_obj(void *)\n{\n return nullptr;\n}\n}\n<|endoftext|>"} {"text":"<commit_before>\/*********************************************************************\n*\n* Software License Agreement (BSD License)\n*\n* Copyright (c) 2012, Willow Garage, Inc.\n* All rights reserved.\n*\n* Redistribution and use in source and binary forms, with or without\n* modification, are permitted provided that the following conditions\n* are met:\n*\n* * Redistributions of source code must retain the above copyright\n* notice, this list of conditions and the following disclaimer.\n* * Redistributions in binary form must reproduce the above\n* copyright notice, this list of conditions and the following\n* disclaimer in the documentation and\/or other materials provided\n* with the distribution.\n* * Neither the name of Willow Garage, Inc. nor the names of its\n* contributors may be used to endorse or promote products derived\n* from this software without specific prior written permission.\n*\n* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n* \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n* POSSIBILITY OF SUCH DAMAGE.\n*\n* Author: Sachin Chitta\n*********************************************************************\/\n\n\/\/ ROS msgs\n#include <kinematics_planner\/kinematics_solver.h>\n#include <planning_models\/kinematic_model.h>\n#include <planning_scene\/planning_scene.h>\n\nnamespace kinematics_planner\n{\n\nbool KinematicsSolver::initialize(const planning_models::KinematicModelConstPtr &kinematic_model,\n const std::map<std::string, kinematics::KinematicsBasePtr> &kinematics_solver_map,\n const std::string &group_name)\n{\n group_name_ = group_name;\n if(!kinematic_model->hasJointModelGroup(group_name))\n {\n ROS_ERROR(\"Group name: %s invalid\",group_name.c_str());\n return false;\n } \n\n const planning_models::KinematicModel::JointModelGroup* joint_model_group = kinematic_model->getJointModelGroup(group_name_);\n group_names_ = joint_model_group->getSubgroupNames();\n if(group_names_.empty())\n group_names_.push_back(group_name_);\n num_groups_= group_names_.size();\n\n ROS_INFO(\"Num groups: %d\",num_groups_);\n\n for(unsigned int i=0; i < group_names_.size(); ++i)\n {\n if(kinematics_solver_map.find(group_names_[i]) == kinematics_solver_map.end())\n {\n ROS_ERROR(\"No kinematics solver found for group %s\",group_names_[i].c_str()); \n return false; \n } \n kinematics_solvers_.push_back(kinematics_solver_map.find(group_names_[i])->second); \n kinematics_base_frames_.push_back(kinematics_solvers_.back()->getBaseFrame()); \n const std::vector<std::string> joint_names = kinematic_model->getJointModelGroup(group_names_[i])->getJointModelNames();\n for(unsigned int j=0; j < joint_names.size(); ++j)\n joint_names_.push_back(joint_names[j]); \n }\n return true; \n}\n\n\nbool KinematicsSolver::solve(const geometry_msgs::PoseStamped &pose,\n const planning_scene::PlanningSceneConstPtr& planning_scene,\n double timeout,\n moveit_msgs::RobotState &robot_state,\n moveit_msgs::MoveItErrorCodes &error_code,\n const kinematic_constraints::KinematicConstraintSet& kinematic_constraint_set) const\n{\n std::map<std::string,geometry_msgs::PoseStamped> goal;\n goal[group_names_.front()] = pose;\n return solve(goal,planning_scene,timeout,robot_state,error_code,kinematic_constraint_set);\n}\n\n\nbool KinematicsSolver::solve(const std::map<std::string,geometry_msgs::PoseStamped> &poses,\n const planning_scene::PlanningSceneConstPtr& planning_scene,\n double timeout,\n moveit_msgs::RobotState &robot_state,\n moveit_msgs::MoveItErrorCodes &error_code,\n const kinematic_constraints::KinematicConstraintSet& kinematic_constraint_set) const\n{\n ros::WallTime start_time = ros::WallTime::now(); \n if(!checkRequest(poses))\n {\n error_code.val = error_code.INVALID_GROUP_NAME;\n return false; \n }\n\n planning_models::KinematicState kinematic_state = planning_scene->getCurrentState();\n std::vector<planning_models::KinematicState::JointStateGroup*> joint_state_groups(num_groups_);\n\n collision_detection::CollisionRequest collision_request;\n collision_detection::CollisionResult collision_result;\n collision_request.group_name = group_name_;\n \n for(unsigned int i=0; i < num_groups_; ++i)\n joint_state_groups[i] = kinematic_state.getJointStateGroup(group_names_[i]); \n \n std::map<std::string,geometry_msgs::PoseStamped> start = transformPoses(planning_scene,kinematic_state,poses,kinematics_base_frames_);\n\n kinematics_planner::SolutionStateMap solutions;\n for(unsigned int i=0; i < num_groups_; ++i)\n {\n solutions[group_names_[i]].resize(joint_state_groups[i]->getVariableCount()); \n }\n \n while( (ros::WallTime::now()-start_time) <= ros::WallDuration(timeout))\n {\n bool success = true; \n for(unsigned int i=0; i < num_groups_; ++i)\n joint_state_groups[i]->setToRandomValues(); \n for(unsigned int i=0; i < num_groups_; ++i)\n {\n std::vector<double> joint_state_values;\n joint_state_groups[i]->getGroupStateValues(joint_state_values); \n const kinematics::KinematicsBaseConstPtr kinematics_solver = kinematics_solvers_[i]; \n if(!kinematics_solver->getPositionIK((start.find(group_names_[i])->second).pose,\n joint_state_values,\n solutions.find(group_names_[i])->second,\n error_code))\n {\n success = false;\n break; \n }\n joint_state_groups[i]->setStateValues(solutions.find(group_names_[i])->second); \n } \n if(!success)\n continue; \n\n planning_scene->checkCollision(collision_request,collision_result,kinematic_state); \n if(collision_result.collision || !planning_scene->isStateConstrained(kinematic_state,kinematic_constraint_set))\n continue; \n\n robot_state = getRobotState(solutions); \n return true;\n }\n return false; \n}\n\nstd::map<std::string,geometry_msgs::PoseStamped> KinematicsSolver::transformPoses(const planning_scene::PlanningSceneConstPtr& planning_scene, \n const planning_models::KinematicState &kinematic_state,\n const std::map<std::string,geometry_msgs::PoseStamped> &poses,\n const std::vector<std::string> &target_frames) const\n{\n Eigen::Affine3d eigen_pose, eigen_pose_2;\n std::map<std::string,geometry_msgs::PoseStamped> result; \n for(unsigned int i=0; i < group_names_.size(); ++i)\n {\n std::string target_frame = target_frames[i]; \n bool target_frame_is_root_frame = (target_frame == kinematic_state.getKinematicModel()->getModelFrame()); \n geometry_msgs::PoseStamped pose_stamped = poses.find(group_names_[i])->second; \n planning_models::poseFromMsg(pose_stamped.pose,eigen_pose_2);\n planning_scene->getTransforms()->transformPose(kinematic_state,pose_stamped.header.frame_id,eigen_pose_2,eigen_pose);\n if(!target_frame_is_root_frame)\n {\n eigen_pose_2 = planning_scene->getTransforms()->getTransform(target_frame);\n eigen_pose = eigen_pose_2.inverse()*eigen_pose;\n } \n pose_stamped.header.frame_id = target_frame;\n planning_models::msgFromPose(eigen_pose,pose_stamped.pose); \n result[group_names_[i]] = pose_stamped; \n }\n return result; \n}\n\nstd::map<std::string,geometry_msgs::PoseStamped> KinematicsSolver::transformPoses(const planning_scene::PlanningSceneConstPtr& planning_scene, \n const planning_models::KinematicState &kinematic_state,\n const std::map<std::string,geometry_msgs::PoseStamped> &poses,\n const std::string &target_frame) const\n{\n std::vector<std::string> target_frames;\n for(unsigned int i=0; i < group_names_.size(); ++i)\n target_frames.push_back(target_frame); \n return transformPoses(planning_scene,kinematic_state,poses,target_frames); \n}\n\nmoveit_msgs::RobotState KinematicsSolver::getRobotState(const kinematics_planner::SolutionStateMap &solutions) const\n{\n moveit_msgs::RobotState robot_state;\n robot_state.joint_state.name = joint_names_;\n for(unsigned int i=0; i < num_groups_; ++i)\n {\n const std::vector<double>& group_solutions = (solutions.find(group_names_[i])->second); \n robot_state.joint_state.position.insert(robot_state.joint_state.position.end(),group_solutions.begin(),group_solutions.end()); \n } \n return robot_state; \n}\n\nbool KinematicsSolver::checkRequest(const std::map<std::string,geometry_msgs::PoseStamped> &start) const\n{\n for(unsigned int i=0; i < group_names_.size(); ++i)\n if(start.find(group_names_[i]) == start.end())\n return false;\n return true; \n}\n\nstd::vector<double> KinematicsSolver::getFloatingJointValues(const geometry_msgs::Pose &pose) const\n{\n std::vector<double> values(7);\n values[0] = pose.position.x;\n values[1] = pose.position.y;\n values[2] = pose.position.z;\n \n values[3] = pose.orientation.x;\n values[4] = pose.orientation.y;\n values[5] = pose.orientation.z;\n values[6] = pose.orientation.w;\n return values; \n}\n\ngeometry_msgs::Pose KinematicsSolver::getPose(const std::vector<double> &values) const\n{\n geometry_msgs::Pose pose;\n pose.position.x = values[0];\n pose.position.y = values[1];\n pose.position.z = values[2];\n\n pose.orientation.x = values[3];\n pose.orientation.y = values[4];\n pose.orientation.z = values[5];\n pose.orientation.w = values[6];\n \n return pose; \n}\n\n}\n<commit_msg>changing the way subgroups are interpreted<commit_after>\/*********************************************************************\n*\n* Software License Agreement (BSD License)\n*\n* Copyright (c) 2012, Willow Garage, Inc.\n* All rights reserved.\n*\n* Redistribution and use in source and binary forms, with or without\n* modification, are permitted provided that the following conditions\n* are met:\n*\n* * Redistributions of source code must retain the above copyright\n* notice, this list of conditions and the following disclaimer.\n* * Redistributions in binary form must reproduce the above\n* copyright notice, this list of conditions and the following\n* disclaimer in the documentation and\/or other materials provided\n* with the distribution.\n* * Neither the name of Willow Garage, Inc. nor the names of its\n* contributors may be used to endorse or promote products derived\n* from this software without specific prior written permission.\n*\n* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n* \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n* POSSIBILITY OF SUCH DAMAGE.\n*\n* Author: Sachin Chitta\n*********************************************************************\/\n\n\/\/ ROS msgs\n#include <kinematics_planner\/kinematics_solver.h>\n#include <planning_models\/kinematic_model.h>\n#include <planning_scene\/planning_scene.h>\n\nnamespace kinematics_planner\n{\n\nbool KinematicsSolver::initialize(const planning_models::KinematicModelConstPtr &kinematic_model,\n const std::map<std::string, kinematics::KinematicsBasePtr> &kinematics_solver_map,\n const std::string &group_name)\n{\n group_name_ = group_name;\n if(!kinematic_model->hasJointModelGroup(group_name))\n {\n ROS_ERROR(\"Group name: %s invalid\",group_name.c_str());\n return false;\n } \n\n \/*const planning_models::KinematicModel::JointModelGroup* joint_model_group = kinematic_model->getJointModelGroup(group_name_);\n group_names_ = joint_model_group->getSubgroupNames();\n for(unsigned int i=0; i < group_names_.size(); ++i)\n {\n ROS_INFO(\"Sub group names: %d %s\",i,group_names_[i].c_str());\n }*\/\n \n if(group_names_.empty())\n group_names_.push_back(group_name_);\n num_groups_= group_names_.size();\n\n ROS_INFO(\"Num groups: %d\",num_groups_);\n\n for(unsigned int i=0; i < group_names_.size(); ++i)\n {\n if(kinematics_solver_map.find(group_names_[i]) == kinematics_solver_map.end())\n {\n ROS_WARN(\"No kinematics solver found for group %s\",group_names_[i].c_str()); \n return false; \n } \n kinematics_solvers_.push_back(kinematics_solver_map.find(group_names_[i])->second); \n kinematics_base_frames_.push_back(kinematics_solvers_.back()->getBaseFrame()); \n ROS_INFO(\"Adding group %s with base frame %s\",group_names_[i].c_str(),kinematics_solvers_.back()->getBaseFrame().c_str());\n \n\n const std::vector<std::string> joint_names = kinematic_model->getJointModelGroup(group_names_[i])->getJointModelNames();\n for(unsigned int j=0; j < joint_names.size(); ++j)\n joint_names_.push_back(joint_names[j]); \n }\n return true; \n}\n\n\nbool KinematicsSolver::solve(const geometry_msgs::PoseStamped &pose,\n const planning_scene::PlanningSceneConstPtr& planning_scene,\n double timeout,\n moveit_msgs::RobotState &robot_state,\n moveit_msgs::MoveItErrorCodes &error_code,\n const kinematic_constraints::KinematicConstraintSet& kinematic_constraint_set) const\n{\n std::map<std::string,geometry_msgs::PoseStamped> goal;\n goal[group_names_.front()] = pose;\n return solve(goal,planning_scene,timeout,robot_state,error_code,kinematic_constraint_set);\n}\n\n\nbool KinematicsSolver::solve(const std::map<std::string,geometry_msgs::PoseStamped> &poses,\n const planning_scene::PlanningSceneConstPtr& planning_scene,\n double timeout,\n moveit_msgs::RobotState &robot_state,\n moveit_msgs::MoveItErrorCodes &error_code,\n const kinematic_constraints::KinematicConstraintSet& kinematic_constraint_set) const\n{\n ros::WallTime start_time = ros::WallTime::now(); \n if(!checkRequest(poses))\n {\n error_code.val = error_code.INVALID_GROUP_NAME;\n return false; \n }\n\n planning_models::KinematicState kinematic_state = planning_scene->getCurrentState();\n std::vector<planning_models::KinematicState::JointStateGroup*> joint_state_groups(num_groups_);\n\n collision_detection::CollisionRequest collision_request;\n collision_detection::CollisionResult collision_result;\n collision_request.group_name = group_name_;\n \n for(unsigned int i=0; i < num_groups_; ++i)\n joint_state_groups[i] = kinematic_state.getJointStateGroup(group_names_[i]); \n \n std::map<std::string,geometry_msgs::PoseStamped> start = transformPoses(planning_scene,kinematic_state,poses,kinematics_base_frames_);\n\n kinematics_planner::SolutionStateMap solutions;\n for(unsigned int i=0; i < num_groups_; ++i)\n {\n solutions[group_names_[i]].resize(joint_state_groups[i]->getVariableCount()); \n }\n \n while( (ros::WallTime::now()-start_time) <= ros::WallDuration(timeout))\n {\n bool success = true; \n for(unsigned int i=0; i < num_groups_; ++i)\n joint_state_groups[i]->setToRandomValues(); \n for(unsigned int i=0; i < num_groups_; ++i)\n {\n std::vector<double> joint_state_values;\n joint_state_groups[i]->getGroupStateValues(joint_state_values); \n const kinematics::KinematicsBaseConstPtr kinematics_solver = kinematics_solvers_[i]; \n if(!kinematics_solver->getPositionIK((start.find(group_names_[i])->second).pose,\n joint_state_values,\n solutions.find(group_names_[i])->second,\n error_code))\n {\n success = false;\n break; \n }\n joint_state_groups[i]->setStateValues(solutions.find(group_names_[i])->second); \n } \n if(!success)\n continue; \n\n planning_scene->checkCollision(collision_request,collision_result,kinematic_state); \n if(collision_result.collision || !planning_scene->isStateConstrained(kinematic_state,kinematic_constraint_set))\n continue; \n\n robot_state = getRobotState(solutions); \n return true;\n }\n return false; \n}\n\nstd::map<std::string,geometry_msgs::PoseStamped> KinematicsSolver::transformPoses(const planning_scene::PlanningSceneConstPtr& planning_scene, \n const planning_models::KinematicState &kinematic_state,\n const std::map<std::string,geometry_msgs::PoseStamped> &poses,\n const std::vector<std::string> &target_frames) const\n{\n Eigen::Affine3d eigen_pose, eigen_pose_2;\n std::map<std::string,geometry_msgs::PoseStamped> result; \n for(unsigned int i=0; i < group_names_.size(); ++i)\n {\n std::string target_frame = target_frames[i]; \n bool target_frame_is_root_frame = (target_frame == kinematic_state.getKinematicModel()->getModelFrame()); \n geometry_msgs::PoseStamped pose_stamped = poses.find(group_names_[i])->second; \n planning_models::poseFromMsg(pose_stamped.pose,eigen_pose_2);\n planning_scene->getTransforms()->transformPose(kinematic_state,pose_stamped.header.frame_id,eigen_pose_2,eigen_pose);\n if(!target_frame_is_root_frame)\n {\n eigen_pose_2 = planning_scene->getTransforms()->getTransform(target_frame);\n eigen_pose = eigen_pose_2.inverse()*eigen_pose;\n } \n pose_stamped.header.frame_id = target_frame;\n planning_models::msgFromPose(eigen_pose,pose_stamped.pose); \n result[group_names_[i]] = pose_stamped; \n }\n return result; \n}\n\nstd::map<std::string,geometry_msgs::PoseStamped> KinematicsSolver::transformPoses(const planning_scene::PlanningSceneConstPtr& planning_scene, \n const planning_models::KinematicState &kinematic_state,\n const std::map<std::string,geometry_msgs::PoseStamped> &poses,\n const std::string &target_frame) const\n{\n std::vector<std::string> target_frames;\n for(unsigned int i=0; i < group_names_.size(); ++i)\n target_frames.push_back(target_frame); \n return transformPoses(planning_scene,kinematic_state,poses,target_frames); \n}\n\nmoveit_msgs::RobotState KinematicsSolver::getRobotState(const kinematics_planner::SolutionStateMap &solutions) const\n{\n moveit_msgs::RobotState robot_state;\n robot_state.joint_state.name = joint_names_;\n for(unsigned int i=0; i < num_groups_; ++i)\n {\n const std::vector<double>& group_solutions = (solutions.find(group_names_[i])->second); \n robot_state.joint_state.position.insert(robot_state.joint_state.position.end(),group_solutions.begin(),group_solutions.end()); \n } \n return robot_state; \n}\n\nbool KinematicsSolver::checkRequest(const std::map<std::string,geometry_msgs::PoseStamped> &start) const\n{\n for(unsigned int i=0; i < group_names_.size(); ++i)\n if(start.find(group_names_[i]) == start.end())\n return false;\n return true; \n}\n\nstd::vector<double> KinematicsSolver::getFloatingJointValues(const geometry_msgs::Pose &pose) const\n{\n std::vector<double> values(7);\n values[0] = pose.position.x;\n values[1] = pose.position.y;\n values[2] = pose.position.z;\n \n values[3] = pose.orientation.x;\n values[4] = pose.orientation.y;\n values[5] = pose.orientation.z;\n values[6] = pose.orientation.w;\n return values; \n}\n\ngeometry_msgs::Pose KinematicsSolver::getPose(const std::vector<double> &values) const\n{\n geometry_msgs::Pose pose;\n pose.position.x = values[0];\n pose.position.y = values[1];\n pose.position.z = values[2];\n\n pose.orientation.x = values[3];\n pose.orientation.y = values[4];\n pose.orientation.z = values[5];\n pose.orientation.w = values[6];\n \n return pose; \n}\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ Created by Miguel Rentes on 30\/01\/2017.\n\/\/\n\n#include \"STL.h\"\n\nvoid printKMax(int arr[], int n, int k) {\n deque<int> mydeque;\n int greatest = 0, value = 0, index = 0, iteration = 0;\n \/*\n * pushing all the greatest values on each k-elements to the front of the deque\n *\/\n for (int i = 0; i < n; i++) {\n if (index < k) {\n \/\/value = arr[i];\n mydeque.push_front(arr[i]);\n \/*if (value > greatest)\n greatest = value;*\/\n if (index == k - 1) {\n \/\/mydeque.push_front(greatest);\n \/\/greatest = 0;\n index = 0;\n iteration++;\n i = iteration-1;\n } else index++;\n }\n }\n \/*\n * pop-ing the greatest values from the back of the deque\n *\/\n while(mydeque.size() > 0) {\n printf(\"%d \", mydeque.back());\n mydeque.pop_back();\n }\n printf(\"\\n\");\n}\n\nint main(void) {\n int t;\n cin >> t;\n while (t > 0) {\n int n, k;\n cin >> n >> k;\n int i;\n int arr[n];\n for (i = 0; i < n; i++)\n cin >> arr[i];\n printKMax(arr, n, k);\n t--;\n }\n return EXIT_SUCCESS;\n}<commit_msg>Starts solution for the Deque-STL challenge.<commit_after>\/\/\n\/\/ Created by Miguel Rentes on 30\/01\/2017.\n\/\/\n\n#include \"STL.h\"\n\nvoid printKMax(int arr[], int n, int k) {\n deque<int> mydeque;\n int greatest = 0, value = 0, index = 0, iteration = 0;\n \/\/ pushing all the values on each k-elements to the front of the deque\n for (int i = 0; i < n; i++) {\n if (index < k) {\n \/\/value = arr[i];\n mydeque.push_front(arr[i]);\n \/*if (value > greatest)\n greatest = value;*\/\n if (index == k - 1) {\n \/\/mydeque.push_front(greatest);\n \/\/greatest = 0;\n index = 0;\n iteration++;\n i = iteration--;\n } else index++;\n }\n }\n \/\/ calculating the max value on each group of k-elements\n \/\/ and placing the max value on the back of the deque\n while(mydeque.size() > 0) {\n printf(\"%d \", mydeque.back());\n mydeque.pop_back();\n }\n printf(\"\\n\");\n}\n\nint main(void) {\n int t;\n cin >> t;\n while (t > 0) {\n int n, k;\n cin >> n >> k;\n int i;\n int arr[n];\n for (i = 0; i < n; i++)\n cin >> arr[i];\n printKMax(arr, n, k);\n t--;\n }\n return EXIT_SUCCESS;\n}<|endoftext|>"} {"text":"<commit_before>#include <stdio.h>\n#include <queue>\n#include <vector>\n#include <utility>\n#include <iostream>\n\/\/#include <string>\n#include <stack>\n#include <queue>\n\nusing namespace std;\n\ntypedef char* string ;\n\nqueue<char *> lv1;\nqueue<char *> lv2;\nqueue<char *> lv3;\nqueue<char *> lv4;\n\n\nchar temp[22]={0};\nint templv;\nint temptime=0;\nint usernum;\nint users=0;\nint read(int now){\n\tif(now < temptime || users>usernum) return 0;\n\n\tdo{\n\t\t\n\t\tif(temp[0]=='\\0'){\n\n\t\t}else{\n\n\t\t\tswitch(templv){\n\t\t\t\tcase 1:\n\t\t\t\t\tlv1.push(temp);break;\n\t\t\t\tcase 2:\n\t\t\t\t\tlv2.push(temp);break;\n\t\t\t\t\tcase 3:\n\t\t\t\t\tlv3.push(temp);break;\n\t\t\t\t\tcase 4:\n\t\t\t\t\tlv4.push(temp);break;\n\t\t\t}\n\t\t}\n\t\tusers++;\n\t\tif(users<=usernum){\n\t\t\tcin >>temptime>>templv>>temp;\n\t\t}\n\t\telse\n\t\t\treturn 0;\n\t}while(temptime<=now);\n\n\n\n}\nint pop(){\n\nif(lv4.size()>0){\n\t\tcout<<lv4.front()<<endl;\n\t\tlv4.pop();\n\t\treturn 4;\n\t}\n\n\tif(lv3.size()>0){\n\t\tcout<<lv3.front()<<endl;\n\t\tlv3.pop();\n\t\treturn 3;\n\t}\n\n\tif(lv2.size()>0){\n\t\tcout<<lv2.front()<<endl;\n\t\tlv2.pop();\n\t\treturn 2;\n\t}\n\n\tif(lv1.size()>0){\n\t\tcout<<lv1.front()<<endl;\n\t\tlv1.pop();\n\t\treturn 1;\n\t}\n\treturn 0;\n}\nint main(int argc, char const *argv[])\n{\n\t\tint time;\n\t\tscanf(\"%d%d\",&usernum,&time);\n\t\tfor (int i = 0; i < time && i< usernum * 5; ++i)\n\t\t{\t\n\t\t\tread(i);\n\t\t\t\/\/cout<<i<<\"\\n\"<<lv1.size()<<lv2.size()<<lv3.size()<<endl;\n\t\t\tif(i%5==0)\n\t\t\t\tpop();\n\t\t}\n\t\t\/\/while(pop()){}\n\t\t\t\n\t\t\t\n\t\t\n\t \n\t\n\treturn 0;\n}<commit_msg>update uoj2254<commit_after>#include <stdio.h>\n#include <queue>\n#include <vector>\n#include <utility>\n#include <iostream>\n#include <string>\n#include <stack>\n#include <queue>\n\nusing namespace std;\n\nqueue<string> lv1;\nqueue<string> lv2;\nqueue<string> lv3;\nqueue<string> lv4;\n\nstring temp;\nint templv;\nint temptime=0;\nint usernum;\nint users=0;\nint read(int now){\n\tif(now < temptime || users>usernum) return 0;\n\n\tdo{\n\t\t\n\t\tif(temp.empty()){\n\n\t\t}else{\n\n\t\t\tswitch(templv){\n\t\t\t\tcase 1:\n\t\t\t\t\tlv1.push(temp);break;\n\t\t\t\tcase 2:\n\t\t\t\t\tlv2.push(temp);break;\n\t\t\t\t\tcase 3:\n\t\t\t\t\tlv3.push(temp);break;\n\t\t\t\t\tcase 4:\n\t\t\t\t\tlv4.push(temp);break;\n\t\t\t}\n\t\t}\n\t\tusers++;\n\t\tif(users<=usernum){\n\t\t\tcin >>temptime>>templv>>temp;\n\t\t}\n\t\telse\n\t\t\treturn 0;\n\t}while(temptime<=now);\n\n\n\n}\nint pop(){\n\nif(lv4.size()>0){\n\t\tcout<<lv4.front()<<endl;\n\t\tlv4.pop();\n\t\treturn 4;\n\t}\n\n\tif(lv3.size()>0){\n\t\tcout<<lv3.front()<<endl;\n\t\tlv3.pop();\n\t\treturn 3;\n\t}\n\n\tif(lv2.size()>0){\n\t\tcout<<lv2.front()<<endl;\n\t\tlv2.pop();\n\t\treturn 2;\n\t}\n\n\tif(lv1.size()>0){\n\t\tcout<<lv1.front()<<endl;\n\t\tlv1.pop();\n\t\treturn 1;\n\t}\n\treturn 0;\n}\nint main(int argc, char const *argv[])\n{\n\t\tint time;\n\t\tscanf(\"%d%d\",&usernum,&time);\n\t\tfor (int i = 0; i < time && i< usernum *5; ++i)\n\t\t{\t\n\t\t\tread(i);\n\t\t\t\/\/cout<<i<<\"\\n\"<<lv1.size()<<lv2.size()<<lv3.size()<<endl;\n\t\t\tif(i%5==0)\n\t\t\t\tpop();\n\t\t}\n\t\t\/\/while(pop()){}\n\t\t\t\n\t\t\t\n\t\t\n\t \n\t\n\treturn 0;\n}<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright 2016 Google Inc.\n *\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n *\/\n\n#include \"GrSurfaceProxy.h\"\n\n#include \"GrCaps.h\"\n#include \"GrContext.h\"\n#include \"GrContextPriv.h\"\n#include \"GrGpuResourcePriv.h\"\n#include \"GrOpList.h\"\n#include \"GrSurfaceContext.h\"\n#include \"GrTextureProvider.h\"\n#include \"GrTextureRenderTargetProxy.h\"\n\n#include \"SkMathPriv.h\"\n\nGrSurfaceProxy::GrSurfaceProxy(sk_sp<GrSurface> surface, SkBackingFit fit)\n : INHERITED(std::move(surface))\n , fDesc(fTarget->desc())\n , fFit(fit)\n , fBudgeted(fTarget->resourcePriv().isBudgeted())\n , fUniqueID(fTarget->uniqueID()) \/\/ Note: converting from unique resource ID to a proxy ID!\n , fGpuMemorySize(kInvalidGpuMemorySize)\n , fLastOpList(nullptr) {\n}\n\nGrSurfaceProxy::~GrSurfaceProxy() {\n if (fLastOpList) {\n fLastOpList->clearTarget();\n }\n SkSafeUnref(fLastOpList);\n}\n\nGrSurface* GrSurfaceProxy::instantiate(GrTextureProvider* texProvider) {\n if (fTarget) {\n return fTarget;\n }\n\n if (SkBackingFit::kApprox == fFit) {\n fTarget = texProvider->createApproxTexture(fDesc);\n } else {\n fTarget = texProvider->createTexture(fDesc, fBudgeted);\n }\n if (!fTarget) {\n return nullptr;\n }\n\n this->INHERITED::transferRefs();\n\n#ifdef SK_DEBUG\n if (kInvalidGpuMemorySize != this->getRawGpuMemorySize_debugOnly()) {\n SkASSERT(fTarget->gpuMemorySize() <= this->getRawGpuMemorySize_debugOnly());\n }\n#endif\n\n return fTarget;\n}\n\nint GrSurfaceProxy::worstCaseWidth(const GrCaps& caps) const {\n if (fTarget) {\n return fTarget->width();\n }\n\n if (SkBackingFit::kExact == fFit) {\n return fDesc.fWidth;\n }\n\n if (caps.reuseScratchTextures() || fDesc.fFlags & kRenderTarget_GrSurfaceFlag) {\n return SkTMax(GrTextureProvider::kMinScratchTextureSize, GrNextPow2(fDesc.fWidth));\n }\n\n return fDesc.fWidth;\n}\n\nint GrSurfaceProxy::worstCaseHeight(const GrCaps& caps) const {\n if (fTarget) {\n return fTarget->height();\n }\n\n if (SkBackingFit::kExact == fFit) {\n return fDesc.fHeight;\n }\n\n if (caps.reuseScratchTextures() || fDesc.fFlags & kRenderTarget_GrSurfaceFlag) {\n return SkTMax(GrTextureProvider::kMinScratchTextureSize, GrNextPow2(fDesc.fHeight));\n }\n\n return fDesc.fHeight;\n}\n\nvoid GrSurfaceProxy::setLastOpList(GrOpList* opList) {\n if (fLastOpList) {\n \/\/ The non-MDB world never closes so we can't check this condition\n#ifdef ENABLE_MDB\n SkASSERT(fLastOpList->isClosed());\n#endif\n fLastOpList->clearTarget();\n }\n\n SkRefCnt_SafeAssign(fLastOpList, opList);\n}\n\nGrRenderTargetOpList* GrSurfaceProxy::getLastRenderTargetOpList() {\n return fLastOpList ? fLastOpList->asRenderTargetOpList() : nullptr;\n}\n\nGrTextureOpList* GrSurfaceProxy::getLastTextureOpList() {\n return fLastOpList ? fLastOpList->asTextureOpList() : nullptr;\n}\n\nsk_sp<GrSurfaceProxy> GrSurfaceProxy::MakeWrapped(sk_sp<GrSurface> surf) {\n if (!surf) {\n return nullptr;\n }\n\n if (surf->asTexture()) {\n if (surf->asRenderTarget()) {\n return sk_sp<GrSurfaceProxy>(new GrTextureRenderTargetProxy(std::move(surf)));\n } else {\n return sk_sp<GrSurfaceProxy>(new GrTextureProxy(std::move(surf)));\n }\n } else {\n SkASSERT(surf->asRenderTarget());\n\n \/\/ Not texturable\n return sk_sp<GrSurfaceProxy>(new GrRenderTargetProxy(std::move(surf)));\n }\n}\n\nsk_sp<GrSurfaceProxy> GrSurfaceProxy::MakeDeferred(const GrCaps& caps,\n const GrSurfaceDesc& desc,\n SkBackingFit fit,\n SkBudgeted budgeted) {\n if (desc.fWidth > caps.maxTextureSize() || desc.fHeight > caps.maxTextureSize()) {\n return nullptr;\n }\n\n if (kRenderTarget_GrSurfaceFlag & desc.fFlags) {\n \/\/ We know anything we instantiate later from this deferred path will be\n \/\/ both texturable and renderable\n return sk_sp<GrSurfaceProxy>(new GrTextureRenderTargetProxy(caps, desc, fit, budgeted));\n }\n\n return sk_sp<GrSurfaceProxy>(new GrTextureProxy(desc, fit, budgeted, nullptr, 0));\n}\n\nsk_sp<GrSurfaceProxy> GrSurfaceProxy::MakeDeferred(const GrCaps& caps,\n GrTextureProvider* texProvider,\n const GrSurfaceDesc& desc,\n SkBudgeted budgeted,\n const void* srcData,\n size_t rowBytes) {\n if (srcData) {\n \/\/ If we have srcData, for now, we create a wrapped GrTextureProxy\n sk_sp<GrSurface> surf(texProvider->createTexture(desc, budgeted, srcData, rowBytes));\n return GrSurfaceProxy::MakeWrapped(std::move(surf));\n }\n\n return GrSurfaceProxy::MakeDeferred(caps, desc, SkBackingFit::kExact, budgeted);\n}\n\nsk_sp<GrSurfaceProxy> GrSurfaceProxy::MakeWrappedBackend(GrContext* context,\n GrBackendTextureDesc& desc,\n GrWrapOwnership ownership) {\n sk_sp<GrTexture> tex(context->textureProvider()->wrapBackendTexture(desc, ownership));\n return GrSurfaceProxy::MakeWrapped(std::move(tex));\n}\n\n#ifdef SK_DEBUG\nvoid GrSurfaceProxy::validate(GrContext* context) const {\n if (fTarget) {\n SkASSERT(fTarget->getContext() == context);\n }\n\n INHERITED::validate();\n}\n#endif\n\nsk_sp<GrSurfaceProxy> GrSurfaceProxy::Copy(GrContext* context,\n GrSurfaceProxy* src,\n SkIRect srcRect,\n SkBudgeted budgeted) {\n if (!srcRect.intersect(SkIRect::MakeWH(src->width(), src->height()))) {\n return nullptr;\n }\n\n GrSurfaceDesc dstDesc = src->desc();\n dstDesc.fWidth = srcRect.width();\n dstDesc.fHeight = srcRect.height();\n\n sk_sp<GrSurfaceContext> dstContext(context->contextPriv().makeDeferredSurfaceContext(\n dstDesc,\n SkBackingFit::kExact,\n budgeted));\n if (!dstContext) {\n return nullptr;\n }\n\n if (!dstContext->copy(src, srcRect, SkIPoint::Make(0, 0))) {\n return nullptr;\n }\n\n return dstContext->asSurfaceProxyRef();\n}\n\nsk_sp<GrSurfaceContext> GrSurfaceProxy::TestCopy(GrContext* context, const GrSurfaceDesc& dstDesc,\n GrSurfaceProxy* srcProxy) {\n\n sk_sp<GrSurfaceContext> dstContext(context->contextPriv().makeDeferredSurfaceContext(\n dstDesc,\n SkBackingFit::kExact,\n SkBudgeted::kYes));\n if (!dstContext) {\n return nullptr;\n }\n\n if (!dstContext->copy(srcProxy)) {\n return nullptr;\n }\n\n return dstContext;\n}\n<commit_msg>Add more pre-checks to surfaceProxy creation<commit_after>\/*\n * Copyright 2016 Google Inc.\n *\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n *\/\n\n#include \"GrSurfaceProxy.h\"\n\n#include \"GrCaps.h\"\n#include \"GrContext.h\"\n#include \"GrContextPriv.h\"\n#include \"GrGpuResourcePriv.h\"\n#include \"GrOpList.h\"\n#include \"GrSurfaceContext.h\"\n#include \"GrTextureProvider.h\"\n#include \"GrTextureRenderTargetProxy.h\"\n\n#include \"SkMathPriv.h\"\n\nGrSurfaceProxy::GrSurfaceProxy(sk_sp<GrSurface> surface, SkBackingFit fit)\n : INHERITED(std::move(surface))\n , fDesc(fTarget->desc())\n , fFit(fit)\n , fBudgeted(fTarget->resourcePriv().isBudgeted())\n , fUniqueID(fTarget->uniqueID()) \/\/ Note: converting from unique resource ID to a proxy ID!\n , fGpuMemorySize(kInvalidGpuMemorySize)\n , fLastOpList(nullptr) {\n}\n\nGrSurfaceProxy::~GrSurfaceProxy() {\n if (fLastOpList) {\n fLastOpList->clearTarget();\n }\n SkSafeUnref(fLastOpList);\n}\n\nGrSurface* GrSurfaceProxy::instantiate(GrTextureProvider* texProvider) {\n if (fTarget) {\n return fTarget;\n }\n\n if (SkBackingFit::kApprox == fFit) {\n fTarget = texProvider->createApproxTexture(fDesc);\n } else {\n fTarget = texProvider->createTexture(fDesc, fBudgeted);\n }\n if (!fTarget) {\n return nullptr;\n }\n\n this->INHERITED::transferRefs();\n\n#ifdef SK_DEBUG\n if (kInvalidGpuMemorySize != this->getRawGpuMemorySize_debugOnly()) {\n SkASSERT(fTarget->gpuMemorySize() <= this->getRawGpuMemorySize_debugOnly());\n }\n#endif\n\n return fTarget;\n}\n\nint GrSurfaceProxy::worstCaseWidth(const GrCaps& caps) const {\n if (fTarget) {\n return fTarget->width();\n }\n\n if (SkBackingFit::kExact == fFit) {\n return fDesc.fWidth;\n }\n\n if (caps.reuseScratchTextures() || fDesc.fFlags & kRenderTarget_GrSurfaceFlag) {\n return SkTMax(GrTextureProvider::kMinScratchTextureSize, GrNextPow2(fDesc.fWidth));\n }\n\n return fDesc.fWidth;\n}\n\nint GrSurfaceProxy::worstCaseHeight(const GrCaps& caps) const {\n if (fTarget) {\n return fTarget->height();\n }\n\n if (SkBackingFit::kExact == fFit) {\n return fDesc.fHeight;\n }\n\n if (caps.reuseScratchTextures() || fDesc.fFlags & kRenderTarget_GrSurfaceFlag) {\n return SkTMax(GrTextureProvider::kMinScratchTextureSize, GrNextPow2(fDesc.fHeight));\n }\n\n return fDesc.fHeight;\n}\n\nvoid GrSurfaceProxy::setLastOpList(GrOpList* opList) {\n if (fLastOpList) {\n \/\/ The non-MDB world never closes so we can't check this condition\n#ifdef ENABLE_MDB\n SkASSERT(fLastOpList->isClosed());\n#endif\n fLastOpList->clearTarget();\n }\n\n SkRefCnt_SafeAssign(fLastOpList, opList);\n}\n\nGrRenderTargetOpList* GrSurfaceProxy::getLastRenderTargetOpList() {\n return fLastOpList ? fLastOpList->asRenderTargetOpList() : nullptr;\n}\n\nGrTextureOpList* GrSurfaceProxy::getLastTextureOpList() {\n return fLastOpList ? fLastOpList->asTextureOpList() : nullptr;\n}\n\nsk_sp<GrSurfaceProxy> GrSurfaceProxy::MakeWrapped(sk_sp<GrSurface> surf) {\n if (!surf) {\n return nullptr;\n }\n\n if (surf->asTexture()) {\n if (surf->asRenderTarget()) {\n return sk_sp<GrSurfaceProxy>(new GrTextureRenderTargetProxy(std::move(surf)));\n } else {\n return sk_sp<GrSurfaceProxy>(new GrTextureProxy(std::move(surf)));\n }\n } else {\n SkASSERT(surf->asRenderTarget());\n\n \/\/ Not texturable\n return sk_sp<GrSurfaceProxy>(new GrRenderTargetProxy(std::move(surf)));\n }\n}\n\nsk_sp<GrSurfaceProxy> GrSurfaceProxy::MakeDeferred(const GrCaps& caps,\n const GrSurfaceDesc& desc,\n SkBackingFit fit,\n SkBudgeted budgeted) {\n \/\/ TODO: share this testing code with check_texture_creation_params\n if (SkBackingFit::kApprox == fit && GrPixelConfigIsCompressed(desc.fConfig)) {\n \/\/ we don't allow scratch compressed textures\n return nullptr;\n }\n\n if (!caps.isConfigTexturable(desc.fConfig)) {\n return nullptr;\n }\n\n bool willBeRT = SkToBool(desc.fFlags & kRenderTarget_GrSurfaceFlag);\n if (willBeRT && !caps.isConfigRenderable(desc.fConfig, desc.fSampleCnt > 0)) {\n return nullptr;\n }\n\n \/\/ We currently do not support multisampled textures\n if (!willBeRT && desc.fSampleCnt > 0) {\n return nullptr;\n }\n\n int maxSize;\n if (willBeRT) {\n maxSize = caps.maxRenderTargetSize();\n } else {\n maxSize = caps.maxTextureSize();\n }\n\n if (desc.fWidth > maxSize || desc.fHeight > maxSize) {\n return nullptr;\n }\n\n if (willBeRT) {\n \/\/ We know anything we instantiate later from this deferred path will be\n \/\/ both texturable and renderable\n return sk_sp<GrSurfaceProxy>(new GrTextureRenderTargetProxy(caps, desc, fit, budgeted));\n }\n\n return sk_sp<GrSurfaceProxy>(new GrTextureProxy(desc, fit, budgeted, nullptr, 0));\n}\n\nsk_sp<GrSurfaceProxy> GrSurfaceProxy::MakeDeferred(const GrCaps& caps,\n GrTextureProvider* texProvider,\n const GrSurfaceDesc& desc,\n SkBudgeted budgeted,\n const void* srcData,\n size_t rowBytes) {\n if (srcData) {\n \/\/ If we have srcData, for now, we create a wrapped GrTextureProxy\n sk_sp<GrSurface> surf(texProvider->createTexture(desc, budgeted, srcData, rowBytes));\n return GrSurfaceProxy::MakeWrapped(std::move(surf));\n }\n\n return GrSurfaceProxy::MakeDeferred(caps, desc, SkBackingFit::kExact, budgeted);\n}\n\nsk_sp<GrSurfaceProxy> GrSurfaceProxy::MakeWrappedBackend(GrContext* context,\n GrBackendTextureDesc& desc,\n GrWrapOwnership ownership) {\n sk_sp<GrTexture> tex(context->textureProvider()->wrapBackendTexture(desc, ownership));\n return GrSurfaceProxy::MakeWrapped(std::move(tex));\n}\n\n#ifdef SK_DEBUG\nvoid GrSurfaceProxy::validate(GrContext* context) const {\n if (fTarget) {\n SkASSERT(fTarget->getContext() == context);\n }\n\n INHERITED::validate();\n}\n#endif\n\nsk_sp<GrSurfaceProxy> GrSurfaceProxy::Copy(GrContext* context,\n GrSurfaceProxy* src,\n SkIRect srcRect,\n SkBudgeted budgeted) {\n if (!srcRect.intersect(SkIRect::MakeWH(src->width(), src->height()))) {\n return nullptr;\n }\n\n GrSurfaceDesc dstDesc = src->desc();\n dstDesc.fWidth = srcRect.width();\n dstDesc.fHeight = srcRect.height();\n\n sk_sp<GrSurfaceContext> dstContext(context->contextPriv().makeDeferredSurfaceContext(\n dstDesc,\n SkBackingFit::kExact,\n budgeted));\n if (!dstContext) {\n return nullptr;\n }\n\n if (!dstContext->copy(src, srcRect, SkIPoint::Make(0, 0))) {\n return nullptr;\n }\n\n return dstContext->asSurfaceProxyRef();\n}\n\nsk_sp<GrSurfaceContext> GrSurfaceProxy::TestCopy(GrContext* context, const GrSurfaceDesc& dstDesc,\n GrSurfaceProxy* srcProxy) {\n\n sk_sp<GrSurfaceContext> dstContext(context->contextPriv().makeDeferredSurfaceContext(\n dstDesc,\n SkBackingFit::kExact,\n SkBudgeted::kYes));\n if (!dstContext) {\n return nullptr;\n }\n\n if (!dstContext->copy(srcProxy)) {\n return nullptr;\n }\n\n return dstContext;\n}\n<|endoftext|>"} {"text":"<commit_before>#include<stdio.h>\n#include<malloc.h>\n#define ERROR 0\n#define OK 1 \n#define ElemType int\n\ntypedef int Status;\ntypedef struct LNode\n{\n int data;\n struct LNode *next;\n}LNode,*LinkList;\n\n\nint CreateLink_L(LinkList &L,int n){\n\/\/ 创建含有n个元素的单链表\n LinkList p,q;\n int i;\n ElemType e;\n L = (LinkList)malloc(sizeof(LNode));\n L->next = NULL; \n L->data=n; \/\/ 先建立一个带头结点的单链表\n q = (LinkList)malloc(sizeof(LNode));\n q = L;\n for (i=0; i<n; i++) {\n scanf(\"%d\", &e);\n p = (LinkList)malloc(sizeof(LNode));\n p->next=NULL; \/\/ 生成新结点\n q->next=p;\n p->data=e;\n q=p;\n\n }\n return OK;\n}\n\nint LoadLink_L(LinkList &L,char * name){\n\/\/ 单链表遍历\n LinkList p = L->next;\n if(p==NULL)printf(\"The List is empty!\"); \/\/ 请填空\n else\n {\n printf(\"List %s:\",name);\n while(p) \/\/ 请填空\n {\n printf(\"%d \",p->data); \n p=p->next; \/\/ 请填空\n }\n }\n printf(\"\\n\");\n return OK;\n}\n\n\n\nStatus ListInsert_L(LinkList &L, int i, ElemType e) { \/\/ 算法2.9\n \/\/ 在带头结点的单链线性表L的第i个元素之前插入元素e\n LinkList p,s;\n p = L; \n int j = 0;\n while (p && j < i-1) { \/\/ 寻找第i-1个结点\n p = p->next;\n ++j;\n } \n if (!p || j > i-1) return ERROR; \/\/ i小于1或者大于表长\n s = (LinkList)malloc(sizeof(LNode)); \/\/ 生成新结点\n s->data = e; s->next = p->next; \/\/ 插入L中\n p->next = s;\n L->data++;\n return OK;\n} \/\/ LinstInsert_L\n\nStatus ListDelete_L(LinkList &L, int i, ElemType &e) { \/\/ 算法2.10\n \/\/ 在带头结点的单链线性表L中,删除第i个元素,并由e返回其值\n LinkList p,q;\n p = L;\n int j = 0;\n while (p->next && j < i-1) { \/\/ 寻找第i个结点,并令p指向其前趋\n p = p->next;\n ++j;\n }\n if (!(p->next) || j > i-1) return ERROR; \/\/ 删除位置不合理\n q = p->next;\n p->next = q->next; \/\/ 删除并释放结点\n e = q->data;\n free(q);\n L->data--;\n return OK;\n} \/\/ ListDelete_L\n\nStatus Linkunion_L(LinkList a,LinkList b,LinkList c){\n\n LinkList pa,pb,pc;\n\n pa=a->next,pb=b->next;\n pc=c;\n int i=1;\n while(pa||pb){\n \n if(pa==NULL)\n {pc->next=pb;return OK;}\n if(pb==NULL)\n {pc->next=pa;return OK;}\n\n if((pa->data)<(pb->data)){\n \n pc->next=pa;\n pc=pa;\n pa=pa->next;\n }else\n { \n pc->next=pb;\n pc=pb;\n pb=pb->next;\n }\n }\n\n \n}\n\nStatus Linkturn(LinkList &L){\n\n LinkList out;\n\n ElemType e;\n while(L->data>0){\n ListDelete_L(L,L->data,e) ;\n\n printf(\"%d\",e);\n }\n\n\n}\nint main(int argc, char const *argv[])\n{\n int n,m;\n\n scanf(\"%d\",&n);\n LinkList A;\n CreateLink_L(A,n);\n LoadLink_L(A,\"A\");\n Linkturn(A);\n\n return 0;\n}<commit_msg>update uoj8581<commit_after>#include<stdio.h>\n#include<malloc.h>\n#define ERROR 0\n#define OK 1 \n#define ElemType int\n\ntypedef int Status;\ntypedef struct LNode\n{\n int data;\n struct LNode *next;\n}LNode,*LinkList;\n\n\nint CreateLink_L(LinkList &L,int n){\n\/\/ 创建含有n个元素的单链表\n LinkList p,q;\n int i;\n ElemType e;\n L = (LinkList)malloc(sizeof(LNode));\n L->next = NULL; \n L->data=n; \/\/ 先建立一个带头结点的单链表\n q = (LinkList)malloc(sizeof(LNode));\n q = L;\n for (i=0; i<n; i++) {\n scanf(\"%d\", &e);\n p = (LinkList)malloc(sizeof(LNode));\n p->next=NULL; \/\/ 生成新结点\n q->next=p;\n p->data=e;\n q=p;\n\n }\n return OK;\n}\n\nint LoadLink_L(LinkList &L,char * name){\n\/\/ 单链表遍历\n LinkList p = L->next;\n if(p==NULL)printf(\"The List is empty!\"); \/\/ 请填空\n else\n {\n printf(\"List %s:\",name);\n while(p) \/\/ 请填空\n {\n printf(\"%d \",p->data); \n p=p->next; \/\/ 请填空\n }\n }\n printf(\"\\n\");\n return OK;\n}\n\n\n\nStatus ListInsert_L(LinkList &L, int i, ElemType e) { \/\/ 算法2.9\n \/\/ 在带头结点的单链线性表L的第i个元素之前插入元素e\n LinkList p,s;\n p = L; \n int j = 0;\n while (p && j < i-1) { \/\/ 寻找第i-1个结点\n p = p->next;\n ++j;\n } \n if (!p || j > i-1) return ERROR; \/\/ i小于1或者大于表长\n s = (LinkList)malloc(sizeof(LNode)); \/\/ 生成新结点\n s->data = e; s->next = p->next; \/\/ 插入L中\n p->next = s;\n L->data++;\n return OK;\n} \/\/ LinstInsert_L\n\nStatus ListDelete_L(LinkList &L, int i, ElemType &e) { \/\/ 算法2.10\n \/\/ 在带头结点的单链线性表L中,删除第i个元素,并由e返回其值\n LinkList p,q;\n p = L;\n int j = 0;\n while (p->next && j < i-1) { \/\/ 寻找第i个结点,并令p指向其前趋\n p = p->next;\n ++j;\n }\n if (!(p->next) || j > i-1) return ERROR; \/\/ 删除位置不合理\n q = p->next;\n p->next = q->next; \/\/ 删除并释放结点\n e = q->data;\n free(q);\n L->data--;\n return OK;\n} \/\/ ListDelete_L\n\nStatus Linkunion_L(LinkList a,LinkList b,LinkList c){\n\n LinkList pa,pb,pc;\n\n pa=a->next,pb=b->next;\n pc=c;\n int i=1;\n while(pa||pb){\n \n if(pa==NULL)\n {pc->next=pb;return OK;}\n if(pb==NULL)\n {pc->next=pa;return OK;}\n\n if((pa->data)<(pb->data)){\n \n pc->next=pa;\n pc=pa;\n pa=pa->next;\n }else\n { \n pc->next=pb;\n pc=pb;\n pb=pb->next;\n }\n }\n\n \n}\n\nStatus Linkturn(LinkList &L){\n\n LinkList out;\n CreateLink_L(out,0);\n\n\n ElemType e;\n\n int i=1;\n while(L->data>0){\n ListDelete_L(L,L->data,e) ;\n ListInsert_L(out,i,e);\n printf(\"%d\",e);\n }\n\n L=out;\n\n\n}\nint main(int argc, char const *argv[])\n{\n int n,m;\n\n scanf(\"%d\",&n);\n LinkList A;\n CreateLink_L(A,n);\n LoadLink_L(A,\"A\");\n Linkturn(A);\n\n return 0;\n}<|endoftext|>"} {"text":"<commit_before>#ifndef VG_GRAPH_SYNCHRONIZER_H\n#define VG_GRAPH_SYNCHRONIZER_H\n\n\/**\n * \\file graph_synchronizer.hpp: define a GraphSynchronizer that can manage\n * concurrent access and updates to a VG graph.\n *\/\n\n#include \"vg.hpp\"\n#include \"path_index.hpp\"\n\n#include <thread>\n#include <mutex>\n#include <condition_variable>\n\nnamespace vg {\n\nusing namespace std;\n\n\/**\n * Let threads get exclusive locks on subgraphs of a vg graph, for reading and\n * editing. Whan a subgraph is locked, a copy is accessible through the lock\n * object and the underlying graph can be edited (through the lock) without\n * affecting any other locked subgraphs.\n *\n * A thread may only hold a lock on a single subgraph at a time. Trying to lock\n * another subgraph while you already have a subgraph locked is likely to result\n * in a deadlock.\n *\/ \nclass GraphSynchronizer {\n\npublic:\n\n \/**\n * Create a GraphSynchronizer for synchronizing on parts of the given graph.\n *\/\n GraphSynchronizer(VG& graph);\n \n \/**\n * Since internally we keep PathIndexes for paths in the graph, we expose\n * this method for getting the strings for paths.\n *\/\n const string& get_path_sequence(const string& path_name);\n \n \/**\n * We can actually let users run whatever function they want with an\n * exclusive handle on a PathIndex, with the guarantee that the graph won't\n * change while they're working.\n *\/\n void with_path_index(const string& path_name, const function<void(const PathIndex&)>& to_run);\n \n \/**\n * This represents a request to lock a particular context on a particular\n * GraphSynchronizer. It fulfils the BasicLockable concept requirements, so\n * you can wait on it with std::unique_lock.\n *\/\n class Lock {\n public:\n \n \/**\n * Create a request to lock a certain radius around a certain position\n * along a certain path in the graph controlled by the given\n * synchronizer.\n *\/\n Lock(GraphSynchronizer& synchronizer, const string& path_name, size_t path_offset, size_t context_bases, bool reflect);\n \n \/**\n * Create a request to lock a certain range of a certain path, from\n * start to end. The start and end positions must line up with the\n * boundaries of nodes in the graph. Also locks attached things that can\n * be reached by paths of the same length or shorter. Note that the\n * range must be nonempty.\n *\/\n Lock(GraphSynchronizer& synchronizer, const string& path_name, size_t start, size_t past_end);\n \n \/**\n * Block until a lock is obtained.\n *\/\n void lock();\n \n \/**\n * If a lock is held, unlock it.\n *\/\n void unlock();\n \n \/**\n * May only be called when locked. Grab the subgraph that was extracted\n * when the lock was obtained. Does not contain any path information.\n *\/\n VG& get_subgraph();\n \n \/**\n * May only be called when locked. Returns the pair of NodeSides\n * corresponding to the start and end positions used when the lock was\n * created.\n *\n * May only be called on locks that lock a start to end range.\n *\/\n pair<NodeSide, NodeSide> get_endpoints() const;\n \n \/**\n * Get the NodeSides for nodes not in the extracted subgraph but in its\n * periphery that are attached to the given NodeSide in the subgraph.\n *\/\n set<NodeSide> get_peripheral_attachments(NodeSide graph_side);\n \n \/**\n * May only be called when locked. Apply an edit against the base graph\n * and return the resulting translation. Note that this updates only the\n * underlying VG graph, not the copy of the locked subgraph stored in\n * the lock. Also note that the edit may only edit locked nodes.\n *\n * Edit operations will create new nodes, and cannot delete nodes or\n * apply changes (other than dividing and connecting) to existing nodes.\n *\n * Any new nodes created are created already locked.\n *\n * Any new nodes created on the left of the alignment (and any existing\n * nodes visited) will be attached to the given \"dangling\" NodeSides.\n * The set will be populated with the NodeSides for the ends of nodes\n * created\/visited at the end of the alignment.\n *\/\n vector<Translation> apply_edit(const Path& path, set<NodeSide>& dangling);\n \n \/**\n * May only be called when locked. Apply a path as an edit to the base\n * graph, leaving new nodes at the ends of the path unattached on their\n * outer sides.\n *\/\n vector<Translation> apply_edit(const Path& path);\n \n \/**\n * May only be called when locked. Apply a path as an edit to the base\n * graph, attaching the outer sides of any newly created nodes to the\n * sides in the periphery attached to the extraction start and end\n * sides, respectively. The lock must have been obtained on a range,\n * rather than a radius.\n *\n * The alignment must be in the local forward orientation of the graph\n * for this to make sense.\n *\/\n vector<Translation> apply_full_length_edit(const Path& path);\n \n protected:\n \n \/\/\/ This points back to the synchronizer we synchronize with when we get locked.\n GraphSynchronizer& synchronizer;\n \n \/\/ These hold the actual lock request we represent\n string path_name;\n \n \/\/ These can be set\n size_t path_offset;\n size_t context_bases;\n bool reflect; \/\/ Should we bounce off node ends?\n \n \/\/ Or these can be set\n size_t start;\n size_t past_end;\n \n \/\/\/ This is the subgraph that got extracted during the locking procedure.\n VG subgraph;\n \n \/\/\/ These are the endpoints that the subgraph was extracted between, if\n \/\/\/ applicable.\n pair<NodeSide, NodeSide> endpoints;\n \n \/\/\/ These are the nodes connected to the subgraph but not actually\n \/\/\/ available for editing. We just need no one else to edit them.\n set<id_t> periphery;\n \n \/\/\/ This connects internal NodeSides to NodeSides of nodes on the\n \/\/\/ periphery.\n map<NodeSide, set<NodeSide>> peripheral_attachments;\n \n \/\/\/ This is the set of nodes that this lock has currently locked.\n set<id_t> locked_nodes;\n };\n \nprotected:\n \n \/\/\/ The graph we manage\n VG& graph;\n \n \/\/\/ We use this to lock the whole graph, for when we're exploring and trying\n \/\/\/ to lock a context, or for when we're making an edit, or for when we're\n \/\/\/ trying to lock a context, or for when we're working with the\n \/\/\/ PathIndexes. It's only ever held during functions in this class or\n \/\/\/ internal classes (monitor-style), so we don't need it to be a recursive\n \/\/\/ mutex.\n mutex whole_graph_lock;\n \n \/\/\/ We have one condition variable where we have blocked all the threads\n \/\/\/ that are waiting to lock subgraphs but couldn't the first time because\n \/\/\/ we ran into already locked nodes. When nodes get unlocked, we wake them\n \/\/\/ all up, and they each grab the mutex and check, one at a time, to see if\n \/\/\/ they can have all their nodes this time.\n condition_variable wait_for_region;\n \n \/\/\/ We need indexes of all the paths that someone might want to use as a\n \/\/\/ basis for locking. This holds a PathIndex for each path we touch by path\n \/\/\/ name.\n map<string, PathIndex> indexes;\n \n \/**\n * Get the index for the given path name. Lock on the indexes and graph must\n * be held already.\n *\/\n PathIndex& get_path_index(const string& path_name);\n \n \/**\n * Update all the path indexes according to the given translations. Lock on\n * the indexes and graph must be held already.\n *\/\n void update_path_indexes(const vector<Translation>& translations);\n \n \/\/\/ This holds all the node IDs that are currently locked by someone\n set<id_t> locked_nodes;\n\n\n};\n\n\n}\n\n#endif\n<commit_msg>Zero-initialize unused GraphSynchronizer Lock fields<commit_after>#ifndef VG_GRAPH_SYNCHRONIZER_H\n#define VG_GRAPH_SYNCHRONIZER_H\n\n\/**\n * \\file graph_synchronizer.hpp: define a GraphSynchronizer that can manage\n * concurrent access and updates to a VG graph.\n *\/\n\n#include \"vg.hpp\"\n#include \"path_index.hpp\"\n\n#include <thread>\n#include <mutex>\n#include <condition_variable>\n\nnamespace vg {\n\nusing namespace std;\n\n\/**\n * Let threads get exclusive locks on subgraphs of a vg graph, for reading and\n * editing. Whan a subgraph is locked, a copy is accessible through the lock\n * object and the underlying graph can be edited (through the lock) without\n * affecting any other locked subgraphs.\n *\n * A thread may only hold a lock on a single subgraph at a time. Trying to lock\n * another subgraph while you already have a subgraph locked is likely to result\n * in a deadlock.\n *\/ \nclass GraphSynchronizer {\n\npublic:\n\n \/**\n * Create a GraphSynchronizer for synchronizing on parts of the given graph.\n *\/\n GraphSynchronizer(VG& graph);\n \n \/**\n * Since internally we keep PathIndexes for paths in the graph, we expose\n * this method for getting the strings for paths.\n *\/\n const string& get_path_sequence(const string& path_name);\n \n \/**\n * We can actually let users run whatever function they want with an\n * exclusive handle on a PathIndex, with the guarantee that the graph won't\n * change while they're working.\n *\/\n void with_path_index(const string& path_name, const function<void(const PathIndex&)>& to_run);\n \n \/**\n * This represents a request to lock a particular context on a particular\n * GraphSynchronizer. It fulfils the BasicLockable concept requirements, so\n * you can wait on it with std::unique_lock.\n *\/\n class Lock {\n public:\n \n \/**\n * Create a request to lock a certain radius around a certain position\n * along a certain path in the graph controlled by the given\n * synchronizer.\n *\/\n Lock(GraphSynchronizer& synchronizer, const string& path_name, size_t path_offset, size_t context_bases, bool reflect);\n \n \/**\n * Create a request to lock a certain range of a certain path, from\n * start to end. The start and end positions must line up with the\n * boundaries of nodes in the graph. Also locks attached things that can\n * be reached by paths of the same length or shorter. Note that the\n * range must be nonempty.\n *\/\n Lock(GraphSynchronizer& synchronizer, const string& path_name, size_t start, size_t past_end);\n \n \/**\n * Block until a lock is obtained.\n *\/\n void lock();\n \n \/**\n * If a lock is held, unlock it.\n *\/\n void unlock();\n \n \/**\n * May only be called when locked. Grab the subgraph that was extracted\n * when the lock was obtained. Does not contain any path information.\n *\/\n VG& get_subgraph();\n \n \/**\n * May only be called when locked. Returns the pair of NodeSides\n * corresponding to the start and end positions used when the lock was\n * created.\n *\n * May only be called on locks that lock a start to end range.\n *\/\n pair<NodeSide, NodeSide> get_endpoints() const;\n \n \/**\n * Get the NodeSides for nodes not in the extracted subgraph but in its\n * periphery that are attached to the given NodeSide in the subgraph.\n *\/\n set<NodeSide> get_peripheral_attachments(NodeSide graph_side);\n \n \/**\n * May only be called when locked. Apply an edit against the base graph\n * and return the resulting translation. Note that this updates only the\n * underlying VG graph, not the copy of the locked subgraph stored in\n * the lock. Also note that the edit may only edit locked nodes.\n *\n * Edit operations will create new nodes, and cannot delete nodes or\n * apply changes (other than dividing and connecting) to existing nodes.\n *\n * Any new nodes created are created already locked.\n *\n * Any new nodes created on the left of the alignment (and any existing\n * nodes visited) will be attached to the given \"dangling\" NodeSides.\n * The set will be populated with the NodeSides for the ends of nodes\n * created\/visited at the end of the alignment.\n *\/\n vector<Translation> apply_edit(const Path& path, set<NodeSide>& dangling);\n \n \/**\n * May only be called when locked. Apply a path as an edit to the base\n * graph, leaving new nodes at the ends of the path unattached on their\n * outer sides.\n *\/\n vector<Translation> apply_edit(const Path& path);\n \n \/**\n * May only be called when locked. Apply a path as an edit to the base\n * graph, attaching the outer sides of any newly created nodes to the\n * sides in the periphery attached to the extraction start and end\n * sides, respectively. The lock must have been obtained on a range,\n * rather than a radius.\n *\n * The alignment must be in the local forward orientation of the graph\n * for this to make sense.\n *\/\n vector<Translation> apply_full_length_edit(const Path& path);\n \n protected:\n \n \/\/\/ This points back to the synchronizer we synchronize with when we get locked.\n GraphSynchronizer& synchronizer;\n \n \/\/ These hold the actual lock request we represent\n string path_name;\n \n \/\/ These can be set\n size_t path_offset = 0;\n size_t context_bases = 0;\n bool reflect = false; \/\/ Should we bounce off node ends?\n \n \/\/ Or these can be set\n size_t start = 0;\n size_t past_end = 0;\n \n \/\/\/ This is the subgraph that got extracted during the locking procedure.\n VG subgraph;\n \n \/\/\/ These are the endpoints that the subgraph was extracted between, if\n \/\/\/ applicable.\n pair<NodeSide, NodeSide> endpoints;\n \n \/\/\/ These are the nodes connected to the subgraph but not actually\n \/\/\/ available for editing. We just need no one else to edit them.\n set<id_t> periphery;\n \n \/\/\/ This connects internal NodeSides to NodeSides of nodes on the\n \/\/\/ periphery.\n map<NodeSide, set<NodeSide>> peripheral_attachments;\n \n \/\/\/ This is the set of nodes that this lock has currently locked.\n set<id_t> locked_nodes;\n };\n \nprotected:\n \n \/\/\/ The graph we manage\n VG& graph;\n \n \/\/\/ We use this to lock the whole graph, for when we're exploring and trying\n \/\/\/ to lock a context, or for when we're making an edit, or for when we're\n \/\/\/ trying to lock a context, or for when we're working with the\n \/\/\/ PathIndexes. It's only ever held during functions in this class or\n \/\/\/ internal classes (monitor-style), so we don't need it to be a recursive\n \/\/\/ mutex.\n mutex whole_graph_lock;\n \n \/\/\/ We have one condition variable where we have blocked all the threads\n \/\/\/ that are waiting to lock subgraphs but couldn't the first time because\n \/\/\/ we ran into already locked nodes. When nodes get unlocked, we wake them\n \/\/\/ all up, and they each grab the mutex and check, one at a time, to see if\n \/\/\/ they can have all their nodes this time.\n condition_variable wait_for_region;\n \n \/\/\/ We need indexes of all the paths that someone might want to use as a\n \/\/\/ basis for locking. This holds a PathIndex for each path we touch by path\n \/\/\/ name.\n map<string, PathIndex> indexes;\n \n \/**\n * Get the index for the given path name. Lock on the indexes and graph must\n * be held already.\n *\/\n PathIndex& get_path_index(const string& path_name);\n \n \/**\n * Update all the path indexes according to the given translations. Lock on\n * the indexes and graph must be held already.\n *\/\n void update_path_indexes(const vector<Translation>& translations);\n \n \/\/\/ This holds all the node IDs that are currently locked by someone\n set<id_t> locked_nodes;\n\n\n};\n\n\n}\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/** @file gsDofMapper.hpp\n\n @brief implementation file for the gsDofMapper\n\n This file is part of the G+Smo library.\n\n This Source Code Form is subject to the terms of the Mozilla Public\n License, v. 2.0. If a copy of the MPL was not distributed with this\n file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n\n Author(s): C. Hofreither, A. Mantzaflaris\n**\/\n\n#include <gsCore\/gsMultiBasis.h>\n\nnamespace gismo\n{\n\ntemplate<class T>\nvoid gsDofMapper::init( const gsMultiBasis<T> & bases, index_t nComp)\n{\n m_curElimId = -1;\n m_numCpldDofs.assign(nComp+1, 1); m_numCpldDofs.front()=0;\n m_numElimDofs.assign(nComp+1,0);\n m_offset.clear();\n\n const size_t nPatches = bases.nBases();\n\n \/\/ Initialize offsets and dof holder\n m_offset.reserve( nPatches );\n m_offset.push_back(0);\n for (size_t k = 1; k < nPatches; ++k)\n m_offset.push_back( m_offset.back() + bases[k-1].size() );\n\n m_numFreeDofs.assign(1+nComp,m_offset.back() + bases.back().size()); m_numFreeDofs.front()=0;\n\n m_dofs.resize(nComp, std::vector<index_t>(m_numFreeDofs.back(), 0));\n}\n\ntemplate<class T>\nvoid gsDofMapper::init( std::vector<const gsMultiBasis<T> *> const & bases)\n{\n const index_t numComp = bases.size();\n m_curElimId = -1;\n m_numCpldDofs.assign(numComp+1,1); m_numCpldDofs.front()=0;\n m_offset.clear();\n\n const size_t nPatches = bases[0]->nBases();\n\n \/\/Checking if bases are same size in for components.\n std::vector<index_t> offsets(nPatches);\n for (index_t comp = 0; comp < numComp; ++comp)\n {\n for (size_t k = 0; k < nPatches; ++k)\n {\n if (comp != 0)\n {\n GISMO_ASSERT(offsets[k] == bases[comp]->basis(k).size(),\n \"The sizes of the bases are not the same for every component. Dofmapper requries this!\");\n }\n offsets[k] = bases[comp]->basis(k).size();\n }\n }\n\n \/\/ Initialize offsets and dof holder\n m_offset.reserve( nPatches );\n m_offset.push_back(0);\n for (size_t k = 1; k < nPatches; ++k)\n m_offset.push_back( m_offset.back() + bases[0]->basis(k-1).size() );\n\n if (nPatches == 1)\n {\n index_t dofsPatches = 0;\n for (index_t comp = 0; comp < numComp; ++comp)\n dofsPatches += bases[comp]->back().size();\n m_numFreeDofs.assign(numComp+1,m_offset.back() + dofsPatches);\n\tm_numFreeDofs.front()=0;\n }\n \/\/Assuming each component are of same size;\n \/\/i.e. bases[comp]->back().size() are equal for all comp\n else\n {\n m_numFreeDofs.assign(numComp+1, (m_offset.back() + bases[0]->back().size())*nPatches); m_numFreeDofs.front()=0;\n }\n\n m_numElimDofs.assign(numComp+1,0);\n m_dofs.resize(numComp, std::vector<index_t>(m_numFreeDofs.back(), 0));\n}\n\ntemplate<class T>\nvoid gsDofMapper::init(const gsMultiBasis<T> &basis,\n const gsBoundaryConditions<T> &bc, int unk)\n{\n init(basis, 1); \/\/one component\n\n \/\/\/ \\todo move this code to gsMultiBasis::getMapper\n for (typename gsBoundaryConditions<T>::const_iterator\n it = bc.dirichletBegin() ; it != bc.dirichletEnd(); ++it )\n {\n if (unk == -1 || it->unknown() == unk) \/\/ special value -1 eliminates all BCs found\n {\n GISMO_ASSERT(it->ps.patch < static_cast<index_t>(m_offset.size()),\n \"Problem: a boundary condition is set on a patch id which does not exist.\");\n\n gsMatrix<index_t> bnd = basis[it->ps.patch].boundary(it->ps.side());\n markBoundary(it->ps.patch, bnd);\n }\n }\n\n \/\/ corners\n for (typename gsBoundaryConditions<T>::const_citerator\n it = bc.cornerBegin() ; it != bc.cornerEnd(); ++it )\n {\n if (unk == -1 || it->unknown == unk)\n {\n GISMO_ASSERT(it->patch < static_cast<index_t>(m_offset.size()),\n \"Problem: a corner boundary condition is set on a patch id which does not exist.\");\n\n eliminateDof(basis[it->patch].functionAtCorner(it->corner), it->patch);\n }\n }\n}\n\ntemplate<class T>\nvoid gsDofMapper::initSingle( const gsBasis<T> & basis, index_t nComp)\n{\n m_curElimId = -1;\n m_numFreeDofs.assign(nComp+1,basis.size()); m_numFreeDofs.front()=0;\n m_numCpldDofs.assign(nComp+1,1); m_numCpldDofs.front()=0;\n m_numElimDofs.assign(nComp+1,0);\n m_offset.resize(1,0);\n m_dofs.resize(nComp, std::vector<index_t>(m_numFreeDofs.back(), 0));\n}\n\n}\/\/namespace gismo\n\n<commit_msg>bugfix to gsDofMapper (#443)<commit_after>\/** @file gsDofMapper.hpp\n\n @brief implementation file for the gsDofMapper\n\n This file is part of the G+Smo library.\n\n This Source Code Form is subject to the terms of the Mozilla Public\n License, v. 2.0. If a copy of the MPL was not distributed with this\n file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n\n Author(s): C. Hofreither, A. Mantzaflaris\n**\/\n\n#include <gsCore\/gsMultiBasis.h>\n\nnamespace gismo\n{\n\ntemplate<class T>\nvoid gsDofMapper::init( const gsMultiBasis<T> & bases, index_t nComp)\n{\n m_curElimId = -1;\n m_numCpldDofs.assign(nComp+1, 1); m_numCpldDofs.front()=0;\n m_numElimDofs.assign(nComp+1,0);\n m_offset.clear();\n\n const size_t nPatches = bases.nBases();\n\n \/\/ Initialize offsets and dof holder\n m_offset.reserve( nPatches );\n m_offset.push_back(0);\n for (size_t k = 1; k < nPatches; ++k)\n m_offset.push_back( m_offset.back() + bases[k-1].size() );\n\n m_numFreeDofs.assign(1+nComp,m_offset.back() + bases.back().size()); m_numFreeDofs.front()=0;\n\n m_dofs.resize(nComp, std::vector<index_t>(m_numFreeDofs.back(), 0));\n}\n\ntemplate<class T>\nvoid gsDofMapper::init( std::vector<const gsMultiBasis<T> *> const & bases)\n{\n const index_t numComp = bases.size();\n m_curElimId = -1;\n m_numCpldDofs.assign(numComp+1,1); m_numCpldDofs.front()=0;\n m_offset.clear();\n\n const size_t nPatches = bases[0]->nBases();\n\n \/\/Checking if bases are same size in for components.\n std::vector<index_t> offsets(nPatches);\n for (index_t comp = 0; comp < numComp; ++comp)\n {\n for (size_t k = 0; k < nPatches; ++k)\n {\n if (comp != 0)\n {\n GISMO_ASSERT(offsets[k] == bases[comp]->basis(k).size(),\n \"The sizes of the bases are not the same for every component. Dofmapper requries this!\");\n }\n offsets[k] = bases[comp]->basis(k).size();\n }\n }\n\n \/\/ Initialize offsets and dof holder\n m_offset.reserve( nPatches );\n m_offset.push_back(0);\n for (size_t k = 1; k < nPatches; ++k)\n m_offset.push_back( m_offset.back() + bases[0]->basis(k-1).size() );\n\n if (nPatches == 1)\n {\n index_t dofsPatches = 0;\n for (index_t comp = 0; comp < numComp; ++comp)\n dofsPatches += bases[comp]->back().size();\n m_numFreeDofs.assign(numComp+1,m_offset.back() + dofsPatches);\n\tm_numFreeDofs.front()=0;\n }\n \/\/Assuming each component are of same size;\n \/\/i.e. bases[comp]->back().size() are equal for all comp\n else\n {\n m_numFreeDofs.assign(numComp+1, (m_offset.back() + bases[0]->back().size())); m_numFreeDofs.front()=0;\n }\n\n m_numElimDofs.assign(numComp+1,0);\n m_dofs.resize(numComp, std::vector<index_t>(m_numFreeDofs.back(), 0));\n}\n\ntemplate<class T>\nvoid gsDofMapper::init(const gsMultiBasis<T> &basis,\n const gsBoundaryConditions<T> &bc, int unk)\n{\n init(basis, 1); \/\/one component\n\n \/\/\/ \\todo move this code to gsMultiBasis::getMapper\n for (typename gsBoundaryConditions<T>::const_iterator\n it = bc.dirichletBegin() ; it != bc.dirichletEnd(); ++it )\n {\n if (unk == -1 || it->unknown() == unk) \/\/ special value -1 eliminates all BCs found\n {\n GISMO_ASSERT(it->ps.patch < static_cast<index_t>(m_offset.size()),\n \"Problem: a boundary condition is set on a patch id which does not exist.\");\n\n gsMatrix<index_t> bnd = basis[it->ps.patch].boundary(it->ps.side());\n markBoundary(it->ps.patch, bnd);\n }\n }\n\n \/\/ corners\n for (typename gsBoundaryConditions<T>::const_citerator\n it = bc.cornerBegin() ; it != bc.cornerEnd(); ++it )\n {\n if (unk == -1 || it->unknown == unk)\n {\n GISMO_ASSERT(it->patch < static_cast<index_t>(m_offset.size()),\n \"Problem: a corner boundary condition is set on a patch id which does not exist.\");\n\n eliminateDof(basis[it->patch].functionAtCorner(it->corner), it->patch);\n }\n }\n}\n\ntemplate<class T>\nvoid gsDofMapper::initSingle( const gsBasis<T> & basis, index_t nComp)\n{\n m_curElimId = -1;\n m_numFreeDofs.assign(nComp+1,basis.size()); m_numFreeDofs.front()=0;\n m_numCpldDofs.assign(nComp+1,1); m_numCpldDofs.front()=0;\n m_numElimDofs.assign(nComp+1,0);\n m_offset.resize(1,0);\n m_dofs.resize(nComp, std::vector<index_t>(m_numFreeDofs.back(), 0));\n}\n\n}\/\/namespace gismo\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n * SchemeSmob.c\n *\n * Scheme small objects (SMOBS) for opencog atoms and truth values.\n *\n * Copyright (c) 2008 Linas Vepstas <linas@linas.org>\n *\/\n\n#ifdef HAVE_GUILE\n\n#include <libguile.h>\n#include <vector>\n\n#include \"Atom.h\"\n#include \"ClassServer.h\"\n#include \"CogServer.h\"\n#include \"Link.h\"\n#include \"Node.h\"\n#include \"SchemeSmob.h\"\n#include \"TLB.h\"\n\nusing namespace opencog;\n\n\/* ============================================================== *\/\n\/**\n * return atom->toString() for the corresponding atom.\n *\/\nstd::string SchemeSmob::to_string(SCM node)\n{\n\tif (SCM_SMOB_PREDICATE(SchemeSmob::cog_handle_tag, node))\n\t\treturn handle_to_string(node);\n\n\tif (SCM_SMOB_PREDICATE(SchemeSmob::cog_misc_tag, node))\n\t\treturn misc_to_string(node);\n\n\treturn \"\";\n}\n\nstd::string SchemeSmob::handle_to_string(Handle h, int indent)\n{\n\tif (UNDEFINED_HANDLE == h) return \"#<Undefined atom handle>\";\n\n\tif (h <= NOTYPE) return \"#<non-real atom>\";\n\n\tAtom *atom = TLB::getAtom(h);\n\tif (NULL == atom) return \"#<Invalid handle>\";\n\tNode *node = dynamic_cast<Node *>(atom);\n\tLink *link = dynamic_cast<Link *>(atom);\n\n#ifdef CRYPTIC_STYLE\n\t\/\/ output the olde-style opencog notation\n\tstd::string ret = \"#<\";\n\tret += atom->toString();\n\tret += \">\\n\";\n#endif\n\n\t\/\/ Print a scheme expression, so that the output can be saved\n\t\/\/ to file, and then restored, as needed.\n\tstd::string ret = \"\";\n\tfor (int i=0; i< indent; i++) ret += \" \";\n\tret += \"(\";\n\tret += ClassServer::getTypeName(atom->getType());\n\tif (node)\n\t{\n\t\tret += \" \\\"\";\n\t\tret += node->getName();\n\t\tret += \"\\\"\";\n\n\t\t\/\/ Print the truth value only after the node name\n\t\tconst TruthValue &tv = atom->getTruthValue();\n\t\tif (tv != TruthValue::DEFAULT_TV())\n\t\t{\n\t\t\tret += \" \";\n\t\t\tret += tv_to_string (&tv);\n\t\t}\n\t\tret += \")\";\n\t\treturn ret;\n\t}\n\telse if (link)\n\t{\n\t\t\/\/ If there's a truth value, print it before the other atoms\n\t\tconst TruthValue &tv = atom->getTruthValue();\n\t\tif (tv != TruthValue::DEFAULT_TV())\n\t\t{\n\t\t\tret += \" \";\n\t\t\tret += tv_to_string (&tv);\n\t\t}\n\n\t\t\/\/ print the outgoing link set.\n\t\tstd::vector<Handle> oset = link->getOutgoingSet();\n\t\tunsigned int arity = oset.size();\n\t\tfor (unsigned int i=0; i<arity; i++)\n\t\t{\n\t\t\tret += \" \";\n\t\t\tret += handle_to_string(oset[i], (0==i)?0:indent+1);\n\t\t\tif (i != arity-1) ret += \"\\n\";\n\t\t}\n\t\tret += \")\";\n\t\treturn ret;\n\t}\n\n\treturn ret;\n}\n\nstd::string SchemeSmob::handle_to_string(SCM node)\n{\n\tSCM shandle = SCM_SMOB_OBJECT(node);\n\tHandle h = scm_to_ulong(shandle);\n\n\treturn handle_to_string(h, 0) + \"\\n\";\n}\n\n\/* ============================================================== *\/\n\/**\n * Create a new scheme object, holding the atom handle\n *\/\nSCM SchemeSmob::ss_atom (SCM shandle)\n{\n\tif (scm_is_false(scm_integer_p(shandle)))\n\t\tscm_wrong_type_arg_msg(\"cog-atom\", 1, shandle, \"integer opencog handle\");\n\tSCM_RETURN_NEWSMOB (cog_handle_tag, shandle);\n}\n\n\/* ============================================================== *\/\n\/**\n * Return handle of atom (the handle is in integer)\n *\/\nSCM SchemeSmob::ss_handle (SCM satom)\n{\n\tif (!SCM_SMOB_PREDICATE(SchemeSmob::cog_handle_tag, satom))\n\t\tscm_wrong_type_arg_msg(\"cog-handle\", 1, satom, \"opencog atom\");\n\treturn SCM_SMOB_OBJECT(satom);\n}\n\n\/* ============================================================== *\/\n\nSCM SchemeSmob::ss_atom_p (SCM s)\n{\n\tif (SCM_SMOB_PREDICATE(SchemeSmob::cog_handle_tag, s))\n\t\treturn SCM_BOOL_T;\n\treturn SCM_BOOL_F;\n}\n\n\/* ============================================================== *\/\n\/**\n * Check that the arguments represent a value node, else throw errors.\n * Return the node type.\n *\/\nType SchemeSmob::validate_atom (SCM stype, const char *subrname)\n{\n\tif (scm_is_true(scm_symbol_p(stype)))\n\t\tstype = scm_symbol_to_string(stype);\n\n\tchar * ct = scm_to_locale_string(stype);\n\tType t = ClassServer::getType(ct);\n\tfree(ct);\n\n\t\/\/ Make sure that the type is good\n\tif (NOTYPE == t)\n\t\tscm_wrong_type_arg_msg(subrname, 1, stype, \"name of opencog atom type\");\n\n\treturn t;\n}\n\nType SchemeSmob::validate_node (SCM stype, const char *subrname)\n{\n\tType t = validate_atom(stype, subrname);\n\n\tif (false == ClassServer::isAssignableFrom(NODE, t))\n\t\tscm_wrong_type_arg_msg(subrname, 1, stype, \"name of opencog node type\");\n\n\treturn t;\n}\n\nstatic std::string decode_string (SCM sname, const char *subrname)\n{\n\tif (scm_is_false(scm_string_p(sname)))\n\t\tscm_wrong_type_arg_msg(subrname, 2, sname, \"string name for the node\");\n\n\tchar * cname = scm_to_locale_string(sname);\n\tstd::string name = cname;\n\tfree(cname);\n\treturn name;\n}\n\n\/**\n * Create a new node, of named type stype, and string name sname\n *\/\nSCM SchemeSmob::ss_new_node (SCM stype, SCM sname, SCM kv_pairs)\n{\n\tType t = validate_node(stype, \"cog-new-node\");\n\tstd::string name = decode_string (sname, \"cog-new-node\");\n\n\t\/\/ Now, create the actual node... in the actual atom space.\n\tconst TruthValue *tv = get_tv_from_list(kv_pairs);\n\tif (!tv) tv = &TruthValue::DEFAULT_TV();\n\n\tAtomSpace *as = CogServer::getAtomSpace();\n\tHandle h = as->addNode(t, name, *tv);\n\n\tSCM shandle = scm_from_ulong(h);\n\tSCM_RETURN_NEWSMOB (cog_handle_tag, shandle);\n}\n\n\/**\n * Return the indicated node, of named type stype, and string name sname\n * if it exists; else return nil if it does not exist.\n * If the node exists, *and* a truth value was specified, then change\n * the truth value.\n *\/\nSCM SchemeSmob::ss_node (SCM stype, SCM sname, SCM kv_pairs)\n{\n\tType t = validate_node(stype, \"cog-node\");\n\tstd::string name = decode_string (sname, \"cog-node\");\n\n\t\/\/ Now, look for the actual node... in the actual atom space.\n\tAtomSpace *as = CogServer::getAtomSpace();\n\tHandle h = as->getHandle(t, name);\n\tif (!TLB::isValidHandle(h)) return SCM_EOL; \/\/ NIL\n\n\t\/\/ If there was a truth value, change it.\n\tconst TruthValue *tv = get_tv_from_list(kv_pairs);\n\tif (tv)\n\t{\n\t\tAtom *atom = TLB::getAtom(h);\n\t\tatom->setTruthValue(*tv);\n\t}\n\n\tSCM shandle = scm_from_ulong(h);\n\tSCM_RETURN_NEWSMOB (cog_handle_tag, shandle);\n}\n\n\/* ============================================================== *\/\n\/**\n * Verify that the arguments are appropriate for a link\n *\/\nstatic Type verify_link (SCM stype, const char * subrname)\n{\n\tif (scm_is_true(scm_symbol_p(stype)))\n\t\tstype = scm_symbol_to_string(stype);\n\n\tchar * ct = scm_to_locale_string(stype);\n\tType t = ClassServer::getType(ct);\n\tfree(ct);\n\n\t\/\/ Make sure that the type is good\n\tif (NOTYPE == t)\n\t\tscm_wrong_type_arg_msg(subrname, 1, stype, \"name of opencog atom type\");\n\n\tif (false == ClassServer::isAssignableFrom(LINK, t))\n\t\tscm_wrong_type_arg_msg(subrname, 1, stype, \"name of opencog link type\");\n\n\treturn t;\n}\n\n\/**\n * Convert argument into a list of handles.\n *\/\nstd::vector<Handle>\nSchemeSmob::decode_handle_list (SCM satom_list, const char * subrname)\n{\n\t\/\/ Verify that second arg is an actual list\n\tif (!scm_is_pair(satom_list))\n\t\tscm_wrong_type_arg_msg(subrname, 2, satom_list, \"a list of atoms\");\n\n\tconst TruthValue *tv = NULL;\n\tstd::vector<Handle> outgoing_set;\n\tSCM sl = satom_list;\n\tint pos = 2;\n\tdo\n\t{\n\t\tSCM satom = SCM_CAR(sl);\n\n\t\t\/\/ Verify that the contents of the list are actual atoms.\n\t\tif (SCM_SMOB_PREDICATE(SchemeSmob::cog_handle_tag, satom))\n\t\t{\n\t\t\t\/\/ Get the handle ... should we check for valid handles here?\n\t\t\tSCM shandle = SCM_SMOB_OBJECT(satom);\n\t\t\tHandle h = scm_to_ulong(shandle);\n\t\t\toutgoing_set.push_back(h);\n\t\t}\n\t\telse\n\t\t{\n\t\t\t\/\/ Its legit to have enmbedded truth values, just skip them.\n\t\t\ttv = get_tv_from_list(sl);\n\t\t\tif (tv == NULL)\n\t\t\t{\n\t\t\t\t\/\/ If its not an atom, and its not a truth value, its bad\n\t\t\t\tscm_wrong_type_arg_msg(\"cog-new-link\", pos, satom, \"opencog atom\");\n\t\t\t}\n\t\t}\n\t\tsl = SCM_CDR(sl);\n\t\tpos++;\n\t}\n\twhile (scm_is_pair(sl));\n\n\treturn outgoing_set;\n}\n\n\/**\n * Create a new link, of named type stype, holding the indicated atom list\n *\/\nSCM SchemeSmob::ss_new_link (SCM stype, SCM satom_list)\n{\n\tType t = verify_link (stype, \"cog-new-link\");\n\n\tstd::vector<Handle> outgoing_set;\n\toutgoing_set = decode_handle_list (satom_list, \"cog-new-link\");\n\n\t\/\/ Fish out a truth value, if its there.\n\tconst TruthValue *tv = get_tv_from_list(satom_list);\n\tif (!tv) tv = &TruthValue::DEFAULT_TV();\n\n\t\/\/ Now, create the actual link... in the actual atom space.\n\tAtomSpace *as = CogServer::getAtomSpace();\n\tHandle h = as->addLink(t, outgoing_set, *tv);\n\n\tSCM shandle = scm_from_ulong(h);\n\n\tSCM_RETURN_NEWSMOB (cog_handle_tag, shandle);\n}\n\n\/**\n * Return the indicated link, of named type stype, holding the\n * indicated atom list, if it exists; else return nil if\n * it does not exist.\n *\/\nSCM SchemeSmob::ss_link (SCM stype, SCM satom_list)\n{\n\tType t = verify_link (stype, \"cog-link\");\n\n\tstd::vector<Handle> outgoing_set;\n\toutgoing_set = decode_handle_list (satom_list, \"cog-link\");\n\n\t\/\/ Now, look to find the actual link... in the actual atom space.\n\tAtomSpace *as = CogServer::getAtomSpace();\n\tHandle h = as->getHandle(t, outgoing_set);\n\tif (!TLB::isValidHandle(h)) return SCM_EOL; \/\/ NIL\n\n\t\/\/ If there was a truth value, change it.\n\tconst TruthValue *tv = get_tv_from_list(satom_list);\n\tif (tv)\n\t{\n\t\tAtom *atom = TLB::getAtom(h);\n\t\tatom->setTruthValue(*tv);\n\t}\n\n\tSCM shandle = scm_from_ulong(h);\n\tSCM_RETURN_NEWSMOB (cog_handle_tag, shandle);\n}\n\n\/* ============================================================== *\/\n\/**\n * delete the atom, but only if it has no incoming links.\n *\/\nSCM SchemeSmob::ss_delete (SCM satom)\n{\n\tHandle h = verify_handle(satom, \"cog-delete\");\n\n\tAtomSpace *as = CogServer::getAtomSpace();\n\tbool rc = as->removeAtom(h, false);\n\n\tif (rc) return SCM_BOOL_T;\n\treturn SCM_BOOL_F;\n}\n\n\/* ============================================================== *\/\n\/**\n * delete the atom, and everything pointing to it.\n *\/\nSCM SchemeSmob::ss_delete_recursive (SCM satom)\n{\n\tHandle h = verify_handle(satom, \"cog-delete-recursive\");\n\n\tAtomSpace *as = CogServer::getAtomSpace();\n\tbool rc = as->removeAtom(h, true);\n\n\tif (rc) return SCM_BOOL_T;\n\treturn SCM_BOOL_F;\n}\n\n#endif\n\/* ===================== END OF FILE ============================ *\/\n<commit_msg>Validate an argument as being a string.<commit_after>\/*\n * SchemeSmob.c\n *\n * Scheme small objects (SMOBS) for opencog atoms and truth values.\n *\n * Copyright (c) 2008 Linas Vepstas <linas@linas.org>\n *\/\n\n#ifdef HAVE_GUILE\n\n#include <libguile.h>\n#include <vector>\n\n#include \"Atom.h\"\n#include \"ClassServer.h\"\n#include \"CogServer.h\"\n#include \"Link.h\"\n#include \"Node.h\"\n#include \"SchemeSmob.h\"\n#include \"TLB.h\"\n\nusing namespace opencog;\n\n\/* ============================================================== *\/\n\/**\n * return atom->toString() for the corresponding atom.\n *\/\nstd::string SchemeSmob::to_string(SCM node)\n{\n\tif (SCM_SMOB_PREDICATE(SchemeSmob::cog_handle_tag, node))\n\t\treturn handle_to_string(node);\n\n\tif (SCM_SMOB_PREDICATE(SchemeSmob::cog_misc_tag, node))\n\t\treturn misc_to_string(node);\n\n\treturn \"\";\n}\n\nstd::string SchemeSmob::handle_to_string(Handle h, int indent)\n{\n\tif (UNDEFINED_HANDLE == h) return \"#<Undefined atom handle>\";\n\n\tif (h <= NOTYPE) return \"#<non-real atom>\";\n\n\tAtom *atom = TLB::getAtom(h);\n\tif (NULL == atom) return \"#<Invalid handle>\";\n\tNode *node = dynamic_cast<Node *>(atom);\n\tLink *link = dynamic_cast<Link *>(atom);\n\n#ifdef CRYPTIC_STYLE\n\t\/\/ output the olde-style opencog notation\n\tstd::string ret = \"#<\";\n\tret += atom->toString();\n\tret += \">\\n\";\n#endif\n\n\t\/\/ Print a scheme expression, so that the output can be saved\n\t\/\/ to file, and then restored, as needed.\n\tstd::string ret = \"\";\n\tfor (int i=0; i< indent; i++) ret += \" \";\n\tret += \"(\";\n\tret += ClassServer::getTypeName(atom->getType());\n\tif (node)\n\t{\n\t\tret += \" \\\"\";\n\t\tret += node->getName();\n\t\tret += \"\\\"\";\n\n\t\t\/\/ Print the truth value only after the node name\n\t\tconst TruthValue &tv = atom->getTruthValue();\n\t\tif (tv != TruthValue::DEFAULT_TV())\n\t\t{\n\t\t\tret += \" \";\n\t\t\tret += tv_to_string (&tv);\n\t\t}\n\t\tret += \")\";\n\t\treturn ret;\n\t}\n\telse if (link)\n\t{\n\t\t\/\/ If there's a truth value, print it before the other atoms\n\t\tconst TruthValue &tv = atom->getTruthValue();\n\t\tif (tv != TruthValue::DEFAULT_TV())\n\t\t{\n\t\t\tret += \" \";\n\t\t\tret += tv_to_string (&tv);\n\t\t}\n\n\t\t\/\/ print the outgoing link set.\n\t\tstd::vector<Handle> oset = link->getOutgoingSet();\n\t\tunsigned int arity = oset.size();\n\t\tfor (unsigned int i=0; i<arity; i++)\n\t\t{\n\t\t\tret += \" \";\n\t\t\tret += handle_to_string(oset[i], (0==i)?0:indent+1);\n\t\t\tif (i != arity-1) ret += \"\\n\";\n\t\t}\n\t\tret += \")\";\n\t\treturn ret;\n\t}\n\n\treturn ret;\n}\n\nstd::string SchemeSmob::handle_to_string(SCM node)\n{\n\tSCM shandle = SCM_SMOB_OBJECT(node);\n\tHandle h = scm_to_ulong(shandle);\n\n\treturn handle_to_string(h, 0) + \"\\n\";\n}\n\n\/* ============================================================== *\/\n\/**\n * Create a new scheme object, holding the atom handle\n *\/\nSCM SchemeSmob::ss_atom (SCM shandle)\n{\n\tif (scm_is_false(scm_integer_p(shandle)))\n\t\tscm_wrong_type_arg_msg(\"cog-atom\", 1, shandle, \"integer opencog handle\");\n\tSCM_RETURN_NEWSMOB (cog_handle_tag, shandle);\n}\n\n\/* ============================================================== *\/\n\/**\n * Return handle of atom (the handle is in integer)\n *\/\nSCM SchemeSmob::ss_handle (SCM satom)\n{\n\tif (!SCM_SMOB_PREDICATE(SchemeSmob::cog_handle_tag, satom))\n\t\tscm_wrong_type_arg_msg(\"cog-handle\", 1, satom, \"opencog atom\");\n\treturn SCM_SMOB_OBJECT(satom);\n}\n\n\/* ============================================================== *\/\n\nSCM SchemeSmob::ss_atom_p (SCM s)\n{\n\tif (SCM_SMOB_PREDICATE(SchemeSmob::cog_handle_tag, s))\n\t\treturn SCM_BOOL_T;\n\treturn SCM_BOOL_F;\n}\n\n\/* ============================================================== *\/\n\/**\n * Check that the arguments represent a value node, else throw errors.\n * Return the node type.\n *\/\nType SchemeSmob::validate_atom (SCM stype, const char *subrname)\n{\n\tif (scm_is_true(scm_symbol_p(stype)))\n\t\tstype = scm_symbol_to_string(stype);\n\n\tif (scm_is_false(scm_symbol_p(stype)))\n\t\tscm_wrong_type_arg_msg(subrname, 1, stype, \"name of opencog atom type\");\n\n\tchar * ct = scm_to_locale_string(stype);\n\tType t = ClassServer::getType(ct);\n\tfree(ct);\n\n\t\/\/ Make sure that the type is good\n\tif (NOTYPE == t)\n\t\tscm_wrong_type_arg_msg(subrname, 1, stype, \"name of opencog atom type\");\n\n\treturn t;\n}\n\nType SchemeSmob::validate_node (SCM stype, const char *subrname)\n{\n\tType t = validate_atom(stype, subrname);\n\n\tif (false == ClassServer::isAssignableFrom(NODE, t))\n\t\tscm_wrong_type_arg_msg(subrname, 1, stype, \"name of opencog node type\");\n\n\treturn t;\n}\n\nstatic std::string decode_string (SCM sname, const char *subrname)\n{\n\tif (scm_is_false(scm_string_p(sname)))\n\t\tscm_wrong_type_arg_msg(subrname, 2, sname, \"string name for the node\");\n\n\tchar * cname = scm_to_locale_string(sname);\n\tstd::string name = cname;\n\tfree(cname);\n\treturn name;\n}\n\n\/**\n * Create a new node, of named type stype, and string name sname\n *\/\nSCM SchemeSmob::ss_new_node (SCM stype, SCM sname, SCM kv_pairs)\n{\n\tType t = validate_node(stype, \"cog-new-node\");\n\tstd::string name = decode_string (sname, \"cog-new-node\");\n\n\t\/\/ Now, create the actual node... in the actual atom space.\n\tconst TruthValue *tv = get_tv_from_list(kv_pairs);\n\tif (!tv) tv = &TruthValue::DEFAULT_TV();\n\n\tAtomSpace *as = CogServer::getAtomSpace();\n\tHandle h = as->addNode(t, name, *tv);\n\n\tSCM shandle = scm_from_ulong(h);\n\tSCM_RETURN_NEWSMOB (cog_handle_tag, shandle);\n}\n\n\/**\n * Return the indicated node, of named type stype, and string name sname\n * if it exists; else return nil if it does not exist.\n * If the node exists, *and* a truth value was specified, then change\n * the truth value.\n *\/\nSCM SchemeSmob::ss_node (SCM stype, SCM sname, SCM kv_pairs)\n{\n\tType t = validate_node(stype, \"cog-node\");\n\tstd::string name = decode_string (sname, \"cog-node\");\n\n\t\/\/ Now, look for the actual node... in the actual atom space.\n\tAtomSpace *as = CogServer::getAtomSpace();\n\tHandle h = as->getHandle(t, name);\n\tif (!TLB::isValidHandle(h)) return SCM_EOL; \/\/ NIL\n\n\t\/\/ If there was a truth value, change it.\n\tconst TruthValue *tv = get_tv_from_list(kv_pairs);\n\tif (tv)\n\t{\n\t\tAtom *atom = TLB::getAtom(h);\n\t\tatom->setTruthValue(*tv);\n\t}\n\n\tSCM shandle = scm_from_ulong(h);\n\tSCM_RETURN_NEWSMOB (cog_handle_tag, shandle);\n}\n\n\/* ============================================================== *\/\n\/**\n * Verify that the arguments are appropriate for a link\n *\/\nstatic Type verify_link (SCM stype, const char * subrname)\n{\n\tif (scm_is_true(scm_symbol_p(stype)))\n\t\tstype = scm_symbol_to_string(stype);\n\n\tchar * ct = scm_to_locale_string(stype);\n\tType t = ClassServer::getType(ct);\n\tfree(ct);\n\n\t\/\/ Make sure that the type is good\n\tif (NOTYPE == t)\n\t\tscm_wrong_type_arg_msg(subrname, 1, stype, \"name of opencog atom type\");\n\n\tif (false == ClassServer::isAssignableFrom(LINK, t))\n\t\tscm_wrong_type_arg_msg(subrname, 1, stype, \"name of opencog link type\");\n\n\treturn t;\n}\n\n\/**\n * Convert argument into a list of handles.\n *\/\nstd::vector<Handle>\nSchemeSmob::decode_handle_list (SCM satom_list, const char * subrname)\n{\n\t\/\/ Verify that second arg is an actual list\n\tif (!scm_is_pair(satom_list))\n\t\tscm_wrong_type_arg_msg(subrname, 2, satom_list, \"a list of atoms\");\n\n\tconst TruthValue *tv = NULL;\n\tstd::vector<Handle> outgoing_set;\n\tSCM sl = satom_list;\n\tint pos = 2;\n\tdo\n\t{\n\t\tSCM satom = SCM_CAR(sl);\n\n\t\t\/\/ Verify that the contents of the list are actual atoms.\n\t\tif (SCM_SMOB_PREDICATE(SchemeSmob::cog_handle_tag, satom))\n\t\t{\n\t\t\t\/\/ Get the handle ... should we check for valid handles here?\n\t\t\tSCM shandle = SCM_SMOB_OBJECT(satom);\n\t\t\tHandle h = scm_to_ulong(shandle);\n\t\t\toutgoing_set.push_back(h);\n\t\t}\n\t\telse\n\t\t{\n\t\t\t\/\/ Its legit to have enmbedded truth values, just skip them.\n\t\t\ttv = get_tv_from_list(sl);\n\t\t\tif (tv == NULL)\n\t\t\t{\n\t\t\t\t\/\/ If its not an atom, and its not a truth value, its bad\n\t\t\t\tscm_wrong_type_arg_msg(\"cog-new-link\", pos, satom, \"opencog atom\");\n\t\t\t}\n\t\t}\n\t\tsl = SCM_CDR(sl);\n\t\tpos++;\n\t}\n\twhile (scm_is_pair(sl));\n\n\treturn outgoing_set;\n}\n\n\/**\n * Create a new link, of named type stype, holding the indicated atom list\n *\/\nSCM SchemeSmob::ss_new_link (SCM stype, SCM satom_list)\n{\n\tType t = verify_link (stype, \"cog-new-link\");\n\n\tstd::vector<Handle> outgoing_set;\n\toutgoing_set = decode_handle_list (satom_list, \"cog-new-link\");\n\n\t\/\/ Fish out a truth value, if its there.\n\tconst TruthValue *tv = get_tv_from_list(satom_list);\n\tif (!tv) tv = &TruthValue::DEFAULT_TV();\n\n\t\/\/ Now, create the actual link... in the actual atom space.\n\tAtomSpace *as = CogServer::getAtomSpace();\n\tHandle h = as->addLink(t, outgoing_set, *tv);\n\n\tSCM shandle = scm_from_ulong(h);\n\n\tSCM_RETURN_NEWSMOB (cog_handle_tag, shandle);\n}\n\n\/**\n * Return the indicated link, of named type stype, holding the\n * indicated atom list, if it exists; else return nil if\n * it does not exist.\n *\/\nSCM SchemeSmob::ss_link (SCM stype, SCM satom_list)\n{\n\tType t = verify_link (stype, \"cog-link\");\n\n\tstd::vector<Handle> outgoing_set;\n\toutgoing_set = decode_handle_list (satom_list, \"cog-link\");\n\n\t\/\/ Now, look to find the actual link... in the actual atom space.\n\tAtomSpace *as = CogServer::getAtomSpace();\n\tHandle h = as->getHandle(t, outgoing_set);\n\tif (!TLB::isValidHandle(h)) return SCM_EOL; \/\/ NIL\n\n\t\/\/ If there was a truth value, change it.\n\tconst TruthValue *tv = get_tv_from_list(satom_list);\n\tif (tv)\n\t{\n\t\tAtom *atom = TLB::getAtom(h);\n\t\tatom->setTruthValue(*tv);\n\t}\n\n\tSCM shandle = scm_from_ulong(h);\n\tSCM_RETURN_NEWSMOB (cog_handle_tag, shandle);\n}\n\n\/* ============================================================== *\/\n\/**\n * delete the atom, but only if it has no incoming links.\n *\/\nSCM SchemeSmob::ss_delete (SCM satom)\n{\n\tHandle h = verify_handle(satom, \"cog-delete\");\n\n\tAtomSpace *as = CogServer::getAtomSpace();\n\tbool rc = as->removeAtom(h, false);\n\n\tif (rc) return SCM_BOOL_T;\n\treturn SCM_BOOL_F;\n}\n\n\/* ============================================================== *\/\n\/**\n * delete the atom, and everything pointing to it.\n *\/\nSCM SchemeSmob::ss_delete_recursive (SCM satom)\n{\n\tHandle h = verify_handle(satom, \"cog-delete-recursive\");\n\n\tAtomSpace *as = CogServer::getAtomSpace();\n\tbool rc = as->removeAtom(h, true);\n\n\tif (rc) return SCM_BOOL_T;\n\treturn SCM_BOOL_F;\n}\n\n#endif\n\/* ===================== END OF FILE ============================ *\/\n<|endoftext|>"} {"text":"<commit_before>#include \"Util\/Log.hpp\"\n#include \"MainWindow.hpp\"\n#include \"Manager\/Managers.hpp\"\n#include \"Manager\/RenderManager.hpp\"\n#include <GL\/glew.h>\n#include <GLFW\/glfw3.h>\n\nMainWindow* MainWindow::instance = nullptr;\nvoid WindowSizeCallback(GLFWwindow* window, int width, int height);\n\nMainWindow::MainWindow(int width, int height, bool fullscreen, bool borderless, const char* title, bool debugContext) {\n \n if (borderless)\n glfwWindowHint(GLFW_DECORATED, GLFW_FALSE);\n \n this->debugContext = debugContext;\n if (debugContext)\n glfwWindowHint(GLFW_OPENGL_DEBUG_CONTEXT, GLFW_TRUE);\n \n GLFWmonitor* monitor = fullscreen ? glfwGetPrimaryMonitor() : nullptr;\n \n window = glfwCreateWindow(width, height, title, monitor, nullptr);\n \n if (!window) {\n glfwTerminate();\n \/\/\/ @todo Print error to log.\n }\n \n glfwMakeContextCurrent(window);\n \n \/\/ Setup error callbacks.\n glfwSetErrorCallback(ErrorCallback);\n \n input = new InputHandler(window);\n input->Update();\n input->SetActive();\n \n size = glm::vec2(width, height);\n instance = this;\n\n glfwSetWindowSizeCallback(window, WindowSizeCallback);\n\n}\n\nMainWindow::~MainWindow() {\n glfwDestroyWindow(window);\n delete input;\n}\n\nMainWindow* MainWindow::GetInstance() {\n return instance;\n}\n\nvoid MainWindow::Init(bool showNotifications) {\n glEnable(GL_DEPTH_TEST);\n glEnable(GL_CULL_FACE);\n glEnable(GL_PROGRAM_POINT_SIZE); \n \n if (debugContext)\n glDebugMessageCallback(showNotifications ? DebugMessageCallback : DebugMessageCallbackIgnoreNotifications, nullptr);\n}\n\nvoid MainWindow::SetVsync(bool vsync) {\n glfwSwapInterval(vsync ? 1 : 0);\n}\n\nvoid MainWindow::Update() {\n input->Update();\n input->SetActive();\n \n if (glfwWindowShouldClose(window) != GLFW_FALSE)\n shouldClose = true;\n}\n\nconst glm::vec2& MainWindow::GetSize() const {\n return size;\n}\n\nvoid MainWindow::SetSize(int width, int height){\n size.x = width;\n size.y = height;\n}\n\nvoid MainWindow::SetTitle(const char *title) {\n glfwSetWindowTitle(window, title);\n}\n\nbool MainWindow::ShouldClose() const {\n return shouldClose;\n}\n\nvoid MainWindow::Close() {\n shouldClose = true;\n}\n\nvoid MainWindow::SwapBuffers() {\n glfwSwapBuffers(window);\n}\n\nGLFWwindow* MainWindow::GetGLFWWindow() const {\n return window;\n}\n\nvoid WindowSizeCallback(GLFWwindow* window, int width, int height)\n{\n\n MainWindow::GetInstance()->SetSize(width, height);\n Managers().renderManager->UpdateBufferSize();\n\n}\n<commit_msg>Fix int to float conversion<commit_after>#include \"Util\/Log.hpp\"\n#include \"MainWindow.hpp\"\n#include \"Manager\/Managers.hpp\"\n#include \"Manager\/RenderManager.hpp\"\n#include <GL\/glew.h>\n#include <GLFW\/glfw3.h>\n\nMainWindow* MainWindow::instance = nullptr;\nvoid WindowSizeCallback(GLFWwindow* window, int width, int height);\n\nMainWindow::MainWindow(int width, int height, bool fullscreen, bool borderless, const char* title, bool debugContext) {\n \n if (borderless)\n glfwWindowHint(GLFW_DECORATED, GLFW_FALSE);\n \n this->debugContext = debugContext;\n if (debugContext)\n glfwWindowHint(GLFW_OPENGL_DEBUG_CONTEXT, GLFW_TRUE);\n \n GLFWmonitor* monitor = fullscreen ? glfwGetPrimaryMonitor() : nullptr;\n \n window = glfwCreateWindow(width, height, title, monitor, nullptr);\n \n if (!window) {\n glfwTerminate();\n \/\/\/ @todo Print error to log.\n }\n \n glfwMakeContextCurrent(window);\n \n \/\/ Setup error callbacks.\n glfwSetErrorCallback(ErrorCallback);\n \n input = new InputHandler(window);\n input->Update();\n input->SetActive();\n \n size = glm::vec2(width, height);\n instance = this;\n\n glfwSetWindowSizeCallback(window, WindowSizeCallback);\n\n}\n\nMainWindow::~MainWindow() {\n glfwDestroyWindow(window);\n delete input;\n}\n\nMainWindow* MainWindow::GetInstance() {\n return instance;\n}\n\nvoid MainWindow::Init(bool showNotifications) {\n glEnable(GL_DEPTH_TEST);\n glEnable(GL_CULL_FACE);\n glEnable(GL_PROGRAM_POINT_SIZE); \n \n if (debugContext)\n glDebugMessageCallback(showNotifications ? DebugMessageCallback : DebugMessageCallbackIgnoreNotifications, nullptr);\n}\n\nvoid MainWindow::SetVsync(bool vsync) {\n glfwSwapInterval(vsync ? 1 : 0);\n}\n\nvoid MainWindow::Update() {\n input->Update();\n input->SetActive();\n \n if (glfwWindowShouldClose(window) != GLFW_FALSE)\n shouldClose = true;\n}\n\nconst glm::vec2& MainWindow::GetSize() const {\n return size;\n}\n\nvoid MainWindow::SetSize(int width, int height){\n size.x = static_cast<float>(width);\n size.y = static_cast<float>(height);\n}\n\nvoid MainWindow::SetTitle(const char *title) {\n glfwSetWindowTitle(window, title);\n}\n\nbool MainWindow::ShouldClose() const {\n return shouldClose;\n}\n\nvoid MainWindow::Close() {\n shouldClose = true;\n}\n\nvoid MainWindow::SwapBuffers() {\n glfwSwapBuffers(window);\n}\n\nGLFWwindow* MainWindow::GetGLFWWindow() const {\n return window;\n}\n\nvoid WindowSizeCallback(GLFWwindow* window, int width, int height) {\n MainWindow::GetInstance()->SetSize(width, height);\n Managers().renderManager->UpdateBufferSize();\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ $Id$\n\n#include <TClonesArray.h>\n#include <TString.h>\n\n#include \"AliVCluster.h\"\n#include \"AliVTrack.h\"\n#include \"AliPicoTrack.h\"\n#include \"AliLog.h\"\n\n#include \"AliEmcalClusTrackMatcherTask.h\"\n\nClassImp(AliEmcalClusTrackMatcherTask)\n\n\/\/________________________________________________________________________\nAliEmcalClusTrackMatcherTask::AliEmcalClusTrackMatcherTask(const char *name) : \n AliAnalysisTaskSE(\"AliEmcalClusTrackMatcherTask\"),\n fTracksName(\"Tracks\"),\n fCaloName(\"CaloClusters\"),\n fDoClusTrack(1),\n fDoTrackClus(0)\n{\n \/\/ Standard constructor.\n\n if (!name)\n return;\n SetName(name);\n fBranchNames=\"ESD:AliESDRun.,AliESDHeader.,PrimaryVertex.,CaloClusters,Tracks\";\n}\n\n\/\/________________________________________________________________________\nAliEmcalClusTrackMatcherTask::~AliEmcalClusTrackMatcherTask()\n{\n \/\/ Destructor\n}\n\n\/\/________________________________________________________________________\nvoid AliEmcalClusTrackMatcherTask::UserCreateOutputObjects()\n{\n \/\/ Create user objects.\n}\n\n\/\/________________________________________________________________________\nvoid AliEmcalClusTrackMatcherTask::UserExec(Option_t *) \n{\n \/\/ Main loop, called for each event.\n\n TList *l = InputEvent()->GetList();\n if (!l) \n return;\n\n TClonesArray *tracks = dynamic_cast<TClonesArray*>(l->FindObject(fTracksName));\n if (!tracks) {\n AliError(Form(\"Pointer to tracks %s == 0\", fTracksName.Data() ));\n return;\n }\n\n TClonesArray *clus = dynamic_cast<TClonesArray*>(l->FindObject(fCaloName));\n if (!clus) {\n AliError(Form(\"Pointer to clus %s == 0\", fCaloName.Data() ));\n return;\n }\n\n const Int_t Ntrks = tracks->GetEntries();\n const Int_t Ncls = clus->GetEntries();\n\n if (fDoClusTrack) {\n for(Int_t i=0; i < Ncls; ++i) {\n AliVCluster *c = dynamic_cast<AliVCluster*>(clus->At(i));\n if (!c)\n continue;\n c->SetEmcCpvDistance(-1);\n c->SetTrackDistance(999,999);\n Double_t dEtaMin = 1e9;\n Double_t dPhiMin = 1e9;\n Int_t imin = -1;\n for(Int_t t = 0; t<Ntrks; ++t) {\n AliVTrack *track = dynamic_cast<AliVTrack*>(tracks->At(t));\n Double_t etadiff=999;\n Double_t phidiff=999;\n AliPicoTrack::GetEtaPhiDiff(track,c,phidiff,etadiff);\n Double_t dR = TMath::Sqrt(etadiff*etadiff+phidiff*phidiff);\n if(dR > 25) \n continue;\n if (TMath::Abs(etadiff)<TMath::Abs(dEtaMin) && TMath::Abs(phidiff)<TMath::Abs(dPhiMin)) {\n dEtaMin = etadiff;\n dPhiMin = phidiff;\n imin = t;\n }\n }\n c->SetEmcCpvDistance(imin);\n c->SetTrackDistance(dPhiMin, dEtaMin);\n }\n }\n\n if (fDoTrackClus) {\n for(Int_t t = 0; t<Ntrks; ++t) {\n AliVTrack *track = dynamic_cast<AliVTrack*>(tracks->At(t));\n if (!track)\n continue;\n Double_t dEtaMin = 1e9;\n Double_t dPhiMin = 1e9;\n Int_t imin = -1;\n for(Int_t i=0; i < Ncls; ++i) {\n AliVCluster *c = dynamic_cast<AliVCluster*>(clus->At(i));\n if (!c)\n continue;\n Double_t etadiff=999;\n Double_t phidiff=999;\n AliPicoTrack::GetEtaPhiDiff(track,c,phidiff,etadiff);\n Double_t dR = TMath::Sqrt(etadiff*etadiff+phidiff*phidiff);\n if(dR > 25) \n continue;\n if (TMath::Abs(etadiff)<TMath::Abs(dEtaMin) && TMath::Abs(phidiff)<TMath::Abs(dPhiMin)) {\n dEtaMin = etadiff;\n dPhiMin = phidiff;\n imin = i;\n }\n }\n track->SetEMCALcluster(imin);\n }\n }\n}\n\n\/\/________________________________________________________________________\nvoid AliEmcalClusTrackMatcherTask::Terminate(Option_t *) \n{\n \/\/ Called once at the end of the analysis.\n\n}\n<commit_msg>check if track is on emcal surface for tm. Speeds up the computation.<commit_after>\/\/ $Id$\n\n#include <TClonesArray.h>\n#include <TString.h>\n\n#include \"AliVCluster.h\"\n#include \"AliVTrack.h\"\n#include \"AliPicoTrack.h\"\n#include \"AliLog.h\"\n\n#include \"AliEmcalClusTrackMatcherTask.h\"\n\nClassImp(AliEmcalClusTrackMatcherTask)\n\n\/\/________________________________________________________________________\nAliEmcalClusTrackMatcherTask::AliEmcalClusTrackMatcherTask(const char *name) : \n AliAnalysisTaskSE(\"AliEmcalClusTrackMatcherTask\"),\n fTracksName(\"Tracks\"),\n fCaloName(\"CaloClusters\"),\n fDoClusTrack(1),\n fDoTrackClus(0)\n{\n \/\/ Standard constructor.\n\n if (!name)\n return;\n SetName(name);\n fBranchNames=\"ESD:AliESDRun.,AliESDHeader.,PrimaryVertex.,CaloClusters,Tracks\";\n}\n\n\/\/________________________________________________________________________\nAliEmcalClusTrackMatcherTask::~AliEmcalClusTrackMatcherTask()\n{\n \/\/ Destructor.\n}\n\n\/\/________________________________________________________________________\nvoid AliEmcalClusTrackMatcherTask::UserCreateOutputObjects()\n{\n \/\/ Create user objects.\n}\n\n\/\/________________________________________________________________________\nvoid AliEmcalClusTrackMatcherTask::UserExec(Option_t *) \n{\n \/\/ Main loop, called for each event.\n\n TList *l = InputEvent()->GetList();\n if (!l) \n return;\n\n TClonesArray *tracks = dynamic_cast<TClonesArray*>(l->FindObject(fTracksName));\n if (!tracks) {\n AliError(Form(\"Pointer to tracks %s == 0\", fTracksName.Data() ));\n return;\n }\n\n TClonesArray *clus = dynamic_cast<TClonesArray*>(l->FindObject(fCaloName));\n if (!clus) {\n AliError(Form(\"Pointer to clus %s == 0\", fCaloName.Data() ));\n return;\n }\n\n const Int_t Ntrks = tracks->GetEntries();\n const Int_t Ncls = clus->GetEntries();\n\n if (fDoClusTrack) {\n for(Int_t i=0; i < Ncls; ++i) {\n AliVCluster *c = dynamic_cast<AliVCluster*>(clus->At(i));\n if (!c)\n continue;\n c->SetEmcCpvDistance(-1);\n c->SetTrackDistance(999,999);\n Double_t dEtaMin = 1e9;\n Double_t dPhiMin = 1e9;\n Int_t imin = -1;\n for(Int_t t = 0; t<Ntrks; ++t) {\n AliVTrack *track = dynamic_cast<AliVTrack*>(tracks->At(t));\n if (!track)\n continue;\n if (!track->IsEMCAL())\n continue;\n Double_t etadiff=999;\n Double_t phidiff=999;\n AliPicoTrack::GetEtaPhiDiff(track,c,phidiff,etadiff);\n Double_t dR = TMath::Sqrt(etadiff*etadiff+phidiff*phidiff);\n if(dR > 25) \n continue;\n if (TMath::Abs(etadiff)<TMath::Abs(dEtaMin) && TMath::Abs(phidiff)<TMath::Abs(dPhiMin)) {\n dEtaMin = etadiff;\n dPhiMin = phidiff;\n imin = t;\n }\n }\n c->SetEmcCpvDistance(imin);\n c->SetTrackDistance(dPhiMin, dEtaMin);\n }\n }\n\n if (fDoTrackClus) {\n for(Int_t t = 0; t<Ntrks; ++t) {\n AliVTrack *track = dynamic_cast<AliVTrack*>(tracks->At(t));\n if (!track)\n continue;\n if (!track->IsEMCAL())\n continue;\n Double_t dEtaMin = 1e9;\n Double_t dPhiMin = 1e9;\n Int_t imin = -1;\n for(Int_t i=0; i < Ncls; ++i) {\n AliVCluster *c = dynamic_cast<AliVCluster*>(clus->At(i));\n if (!c)\n continue;\n Double_t etadiff=999;\n Double_t phidiff=999;\n AliPicoTrack::GetEtaPhiDiff(track,c,phidiff,etadiff);\n Double_t dR = TMath::Sqrt(etadiff*etadiff+phidiff*phidiff);\n if(dR > 25) \n continue;\n if (TMath::Abs(etadiff)<TMath::Abs(dEtaMin) && TMath::Abs(phidiff)<TMath::Abs(dPhiMin)) {\n dEtaMin = etadiff;\n dPhiMin = phidiff;\n imin = i;\n }\n }\n track->SetEMCALcluster(imin);\n }\n }\n}\n\n\/\/________________________________________________________________________\nvoid AliEmcalClusTrackMatcherTask::Terminate(Option_t *) \n{\n \/\/ Called once at the end of the analysis.\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ File:\tBlockFix.cxx\n\/\/ Created:\tTue Dec 7 11:59:05 2004\n\/\/ Author:\tPavel DURANDIN\n\/\/ Copyright:\tOpen CASCADE SA 2004\n\n\n#include <BlockFix.hxx>\n#include <TopoDS_Shape.hxx>\n#include <TopTools_DataMapOfShapeShape.hxx>\n#include <ShapeCustom.hxx>\n#include <BRepTools.hxx>\n#include <ShapeBuild_ReShape.hxx>\n#include <TopoDS_Face.hxx>\n#include <TopExp_Explorer.hxx>\n#include <TopoDS.hxx>\n#include <TopLoc_Location.hxx>\n#include <Geom_Surface.hxx>\n#include <Geom_CylindricalSurface.hxx>\n#include <Geom_ConicalSurface.hxx>\n#include <ShapeFix_Wire.hxx>\n#include <TopoDS_Wire.hxx>\n#include <BRepTools_Modifier.hxx>\n#include <Geom_SphericalSurface.hxx>\n#include <Geom_ToroidalSurface.hxx>\n#include <BRep_Tool.hxx>\n#include <TopoDS_Edge.hxx>\n#include <Geom2d_Curve.hxx>\n#include <BRep_Builder.hxx>\n#include <ShapeAnalysis_Edge.hxx>\n#include <ShapeFix_Edge.hxx>\n#include <ShapeFix.hxx>\n#include <ShapeFix_Face.hxx>\n#include <ShapeAnalysis.hxx>\n\n#include <TColgp_SequenceOfPnt2d.hxx>\n#include <ShapeAnalysis_Curve.hxx>\n#include <TopoDS_Vertex.hxx>\n#include <ShapeBuild_Edge.hxx>\n\n#include <BlockFix_SphereSpaceModifier.hxx>\n#include <TopTools_DataMapIteratorOfDataMapOfShapeShape.hxx>\n#include <TopTools_MapOfShape.hxx>\n#include <BlockFix_PeriodicSurfaceModifier.hxx>\n\n#include <TopoDS_Solid.hxx>\n\n\n\/\/=======================================================================\n\/\/function : FixResult\n\/\/purpose : auxilary\n\/\/=======================================================================\nstatic void FixResult(const TopoDS_Shape& result,\n Handle(ShapeBuild_ReShape)& Context,\n const Standard_Real Tol)\n{\n for (TopExp_Explorer ex_f(result,TopAbs_FACE); ex_f.More(); ex_f.Next()) {\n TopoDS_Shape aShape = Context->Apply(ex_f.Current().Oriented(TopAbs_FORWARD));\n \/\/ face coud not be dropped or splitted on this step\n TopoDS_Face aFace = TopoDS::Face(aShape);\n TopLoc_Location L;\n Handle(Geom_Surface) Surf = BRep_Tool::Surface(aFace,L);\n \n if (Surf->IsKind(STANDARD_TYPE(Geom_SphericalSurface)) ||\n Surf->IsKind(STANDARD_TYPE(Geom_CylindricalSurface))) {\n \n Standard_Integer nbWires = 0;\n for (TopExp_Explorer ex_w(aFace,TopAbs_WIRE); ex_w.More(); ex_w.Next()) {\n nbWires++;\n Handle(ShapeFix_Wire) sfw = new ShapeFix_Wire(TopoDS::Wire(ex_w.Current()), \n aFace, \n Precision::Confusion());\n sfw->FixReorder();\n if(sfw->StatusReorder ( ShapeExtend_FAIL ))\n continue;\n \n sfw->SetPrecision(2.*Tol);\n sfw->FixShifted();\n \n Standard_Boolean isDone = sfw->LastFixStatus ( ShapeExtend_DONE );\n isDone |= sfw->FixDegenerated();\n \n \/\/ remove degenerated edges from not degenerated points\n ShapeAnalysis_Edge sae;\n Handle(ShapeExtend_WireData) sewd = sfw->WireData();\n Standard_Integer i;\n for( i = 1; i<=sewd->NbEdges();i++) {\n TopoDS_Edge E = sewd->Edge(i);\n if(BRep_Tool::Degenerated(E)&&!sae.HasPCurve(E,aFace)) {\n sewd->Remove(i);\n isDone = Standard_True;\n i--;\n }\n }\n \n isDone |= sfw->FixLacking();\n \n \/\/ remove neighbour seam edges \n if(isDone) {\n for( i = 1; i<sewd->NbEdges();i++) {\n if(sewd->IsSeam(i) && sewd->IsSeam(i+1)) {\n isDone = Standard_True;\n sewd->Remove(i);\n sewd->Remove(i);\n i--;\n }\n }\n if(sewd->IsSeam(1) && sewd->IsSeam(sewd->NbEdges())) {\n sewd->Remove(1);\n sewd->Remove(sewd->NbEdges());\n }\n }\n \n \n if(isDone) {\n TopoDS_Wire ResWire = sfw->Wire();\n Context->Replace(ex_w.Current(), ResWire);\n };\n }\n \/\/ Implement fix orientation in case of several wires\n if(nbWires > 1) {\n TopoDS_Face aFixedFace = TopoDS::Face(Context->Apply(aFace));\n Handle(ShapeFix_Face) sff = new ShapeFix_Face(aFixedFace);\n if(sff->FixOrientation())\n Context->Replace(aFixedFace,sff->Face());\n }\n \n }\n }\n}\n\n\n\n\n\n\/\/=======================================================================\n\/\/function : ConvertToAnalytical\n\/\/purpose : \n\/\/=======================================================================\n\nTopoDS_Shape BlockFix::RotateSphereSpace (const TopoDS_Shape& S,\n const Standard_Real Tol) \n{\n\n \/\/ Create a modification description\n Handle(BlockFix_SphereSpaceModifier) SR = new BlockFix_SphereSpaceModifier;\n SR->SetTolerance(Tol);\n\n TopTools_DataMapOfShapeShape context;\n BRepTools_Modifier MD;\n TopoDS_Shape result = ShapeCustom::ApplyModifier ( S, SR, context,MD );\n \n Handle(ShapeBuild_ReShape) RS = new ShapeBuild_ReShape;\n FixResult(result,RS,Tol);\n result = RS->Apply(result);\n \n ShapeFix_Edge sfe;\n for(TopExp_Explorer exp(result,TopAbs_EDGE); exp.More(); exp.Next()) {\n TopoDS_Edge E = TopoDS::Edge(exp.Current());\n sfe.FixVertexTolerance (E);\n }\n \n ShapeFix::SameParameter(result,Standard_False);\n return result;\n}\n\n\n\/\/=======================================================================\n\/\/function : FixRanges\n\/\/purpose : \n\/\/=======================================================================\n\nTopoDS_Shape BlockFix::FixRanges (const TopoDS_Shape& S,\n const Standard_Real Tol) \n{\n \/\/ Create a modification description\n Handle(BlockFix_PeriodicSurfaceModifier) SR = new BlockFix_PeriodicSurfaceModifier;\n SR->SetTolerance(Tol);\n\n TopTools_DataMapOfShapeShape context;\n BRepTools_Modifier MD;\n TopoDS_Shape result = ShapeCustom::ApplyModifier ( S, SR, context,MD );\n \n Handle(ShapeBuild_ReShape) RS = new ShapeBuild_ReShape;\n FixResult(result,RS,Tol);\n result = RS->Apply(result);\n \n ShapeFix_Edge sfe;\n for(TopExp_Explorer exp(result,TopAbs_EDGE); exp.More(); exp.Next()) {\n TopoDS_Edge E = TopoDS::Edge(exp.Current());\n sfe.FixVertexTolerance (E);\n }\n \n ShapeFix::SameParameter(result,Standard_False);\n\n return result;\n}\n<commit_msg>PAL8395: Fix pb. with bug2extraEdges.py<commit_after>\/\/ File:\tBlockFix.cxx\n\/\/ Created:\tTue Dec 7 11:59:05 2004\n\/\/ Author:\tPavel DURANDIN\n\/\/ Copyright:\tOpen CASCADE SA 2004\n\n\n#include <BlockFix.hxx>\n#include <TopoDS_Shape.hxx>\n#include <TopTools_DataMapOfShapeShape.hxx>\n#include <ShapeCustom.hxx>\n#include <BRepTools.hxx>\n#include <ShapeBuild_ReShape.hxx>\n#include <TopoDS_Face.hxx>\n#include <TopExp_Explorer.hxx>\n#include <TopoDS.hxx>\n#include <TopLoc_Location.hxx>\n#include <Geom_Surface.hxx>\n#include <Geom_CylindricalSurface.hxx>\n#include <Geom_ConicalSurface.hxx>\n#include <ShapeFix_Wire.hxx>\n#include <TopoDS_Wire.hxx>\n#include <BRepTools_Modifier.hxx>\n#include <Geom_SphericalSurface.hxx>\n#include <Geom_ToroidalSurface.hxx>\n#include <BRep_Tool.hxx>\n#include <TopoDS_Edge.hxx>\n#include <Geom2d_Curve.hxx>\n#include <BRep_Builder.hxx>\n#include <ShapeAnalysis_Edge.hxx>\n#include <ShapeFix_Edge.hxx>\n#include <ShapeFix.hxx>\n#include <ShapeFix_Face.hxx>\n#include <ShapeAnalysis.hxx>\n\n#include <TColgp_SequenceOfPnt2d.hxx>\n#include <ShapeAnalysis_Curve.hxx>\n#include <TopoDS_Vertex.hxx>\n#include <ShapeBuild_Edge.hxx>\n\n#include <BlockFix_SphereSpaceModifier.hxx>\n#include <TopTools_DataMapIteratorOfDataMapOfShapeShape.hxx>\n#include <TopTools_MapOfShape.hxx>\n#include <BlockFix_PeriodicSurfaceModifier.hxx>\n\n#include <TopoDS_Solid.hxx>\n\n\n\/\/=======================================================================\n\/\/function : FixResult\n\/\/purpose : auxilary\n\/\/=======================================================================\nstatic void FixResult(const TopoDS_Shape& result,\n Handle(ShapeBuild_ReShape)& Context,\n const Standard_Real Tol)\n{\n for (TopExp_Explorer ex_f(result,TopAbs_FACE); ex_f.More(); ex_f.Next()) {\n TopoDS_Shape aShape = Context->Apply(ex_f.Current().Oriented(TopAbs_FORWARD));\n \/\/ face coud not be dropped or splitted on this step\n TopoDS_Face aFace = TopoDS::Face(aShape);\n TopLoc_Location L;\n Handle(Geom_Surface) Surf = BRep_Tool::Surface(aFace,L);\n \n if( Surf->IsKind(STANDARD_TYPE(Geom_SphericalSurface)) ||\n Surf->IsKind(STANDARD_TYPE(Geom_CylindricalSurface)) ) {\n \n Standard_Integer nbWires = 0;\n for (TopExp_Explorer ex_w(aFace,TopAbs_WIRE); ex_w.More(); ex_w.Next()) {\n nbWires++;\n Handle(ShapeFix_Wire) sfw = new ShapeFix_Wire(TopoDS::Wire(ex_w.Current()), \n aFace, \n Precision::Confusion());\n sfw->FixReorder();\n if(sfw->StatusReorder ( ShapeExtend_FAIL ))\n continue;\n \n sfw->SetPrecision(2.*Tol);\n sfw->FixShifted();\n \n Standard_Boolean isDone = sfw->LastFixStatus ( ShapeExtend_DONE );\n isDone |= sfw->FixDegenerated();\n \n \/\/ remove degenerated edges from not degenerated points\n ShapeAnalysis_Edge sae;\n Handle(ShapeExtend_WireData) sewd = sfw->WireData();\n Standard_Integer i;\n for( i = 1; i<=sewd->NbEdges();i++) {\n TopoDS_Edge E = sewd->Edge(i);\n if(BRep_Tool::Degenerated(E)&&!sae.HasPCurve(E,aFace)) {\n sewd->Remove(i);\n isDone = Standard_True;\n i--;\n }\n }\n \n \/\/isDone |= sfw->FixLacking(); \/\/ commented by skl 22.03.2005 (PAL8395)\n \n \/\/ remove neighbour seam edges \n if(isDone) {\n for( i = 1; i<sewd->NbEdges();i++) {\n if(sewd->IsSeam(i) && sewd->IsSeam(i+1)) {\n isDone = Standard_True;\n sewd->Remove(i);\n sewd->Remove(i);\n i--;\n }\n }\n if(sewd->IsSeam(1) && sewd->IsSeam(sewd->NbEdges())) {\n sewd->Remove(1);\n sewd->Remove(sewd->NbEdges());\n }\n }\n \n \n if(isDone) {\n TopoDS_Wire ResWire = sfw->Wire();\n Context->Replace(ex_w.Current(), ResWire);\n };\n }\n \/\/ Implement fix orientation in case of several wires\n if(nbWires > 1) {\n TopoDS_Face aFixedFace = TopoDS::Face(Context->Apply(aFace));\n Handle(ShapeFix_Face) sff = new ShapeFix_Face(aFixedFace);\n if(sff->FixOrientation())\n Context->Replace(aFixedFace,sff->Face());\n }\n \n }\n }\n}\n\n\n\n\n\n\/\/=======================================================================\n\/\/function : ConvertToAnalytical\n\/\/purpose : \n\/\/=======================================================================\n\nTopoDS_Shape BlockFix::RotateSphereSpace (const TopoDS_Shape& S,\n const Standard_Real Tol) \n{\n\n \/\/ Create a modification description\n Handle(BlockFix_SphereSpaceModifier) SR = new BlockFix_SphereSpaceModifier;\n SR->SetTolerance(Tol);\n\n TopTools_DataMapOfShapeShape context;\n BRepTools_Modifier MD;\n TopoDS_Shape result = ShapeCustom::ApplyModifier ( S, SR, context,MD );\n \n Handle(ShapeBuild_ReShape) RS = new ShapeBuild_ReShape;\n FixResult(result,RS,Tol);\n result = RS->Apply(result);\n \n ShapeFix_Edge sfe;\n for(TopExp_Explorer exp(result,TopAbs_EDGE); exp.More(); exp.Next()) {\n TopoDS_Edge E = TopoDS::Edge(exp.Current());\n sfe.FixVertexTolerance (E);\n }\n \n ShapeFix::SameParameter(result,Standard_False);\n return result;\n}\n\n\n\/\/=======================================================================\n\/\/function : FixRanges\n\/\/purpose : \n\/\/=======================================================================\n\nTopoDS_Shape BlockFix::FixRanges (const TopoDS_Shape& S,\n const Standard_Real Tol) \n{\n \/\/ Create a modification description\n Handle(BlockFix_PeriodicSurfaceModifier) SR = new BlockFix_PeriodicSurfaceModifier;\n SR->SetTolerance(Tol);\n\n TopTools_DataMapOfShapeShape context;\n BRepTools_Modifier MD;\n TopoDS_Shape result = ShapeCustom::ApplyModifier ( S, SR, context,MD );\n \n Handle(ShapeBuild_ReShape) RS = new ShapeBuild_ReShape;\n FixResult(result,RS,Tol);\n result = RS->Apply(result);\n \n ShapeFix_Edge sfe;\n for(TopExp_Explorer exp(result,TopAbs_EDGE); exp.More(); exp.Next()) {\n TopoDS_Edge E = TopoDS::Edge(exp.Current());\n sfe.FixVertexTolerance (E);\n }\n \n ShapeFix::SameParameter(result,Standard_False);\n\n return result;\n}\n<|endoftext|>"} {"text":"<commit_before>\n#ifndef SOFA_COMPONENT_CONTROLLER_LCPFORCEFEEDBACK_INL\n#define SOFA_COMPONENT_CONTROLLER_LCPFORCEFEEDBACK_INL\n\n#include <sofa\/component\/controller\/LCPForceFeedback.h>\n#include <sofa\/simulation\/common\/AnimateEndEvent.h>\n#include <sofa\/component\/constraintset\/LCPConstraintSolver.h>\n#include <sofa\/component\/constraintset\/GenericLCPConstraintSolver.h>\n\n#include <sofa\/core\/objectmodel\/BaseContext.h>\n\n#include <algorithm>\n\nnamespace\n{\ntemplate <typename DataTypes>\nbool derivVectors(const typename DataTypes::VecCoord& x0, const typename DataTypes::VecCoord& x1, typename DataTypes::VecDeriv& d)\n{\n unsigned int sz0 = x0.size();\n unsigned int szmin = std::min(sz0,(unsigned int)x1.size());\n\n d.resize(sz0);\n for(unsigned int i=0; i<szmin; ++i)\n {\n d[i]=x1[i]-x0[i];\n }\n for(unsigned int i=szmin; i<sz0; ++i)\n {\n d[i]=-x0[i];\n }\n return true;\n}\n\ntemplate <typename DataTypes>\nbool derivRigid3Vectors(const typename DataTypes::VecCoord& x0, const typename DataTypes::VecCoord& x1, typename DataTypes::VecDeriv& d)\n{\n unsigned int sz0 = x0.size();\n unsigned int szmin = std::min(sz0,(unsigned int)x1.size());\n\n d.resize(sz0);\n for(unsigned int i=0; i<szmin; ++i)\n {\n d[i].getVCenter() = x1[i].getCenter() - x0[i].getCenter();\n \/\/ Pas de prise en charge des rotations\n }\n for(unsigned int i=szmin; i<sz0; ++i)\n {\n d[i].getVCenter() = - x0[i].getCenter();\n }\n return true;\n}\n\n\ntemplate <typename DataTypes>\ndouble computeDot(const typename DataTypes::Deriv& v0, const typename DataTypes::Deriv& v1)\n{\n return v0.x()*v1.x();\n}\n\n\n#ifndef SOFA_FLOAT\nusing sofa::defaulttype::Rigid3dTypes;\ntemplate<>\nbool derivVectors<Rigid3dTypes>(const Rigid3dTypes::VecCoord& x0, const Rigid3dTypes::VecCoord& x1, Rigid3dTypes::VecDeriv& d)\n{\n return derivRigid3Vectors<Rigid3dTypes>(x0,x1,d);\n}\ntemplate <>\ndouble computeDot<Rigid3dTypes>(const Rigid3dTypes::Deriv& v0, const Rigid3dTypes::Deriv& v1)\n{\n return dot(v0.getVCenter(),v1.getVCenter());\n}\n\n#endif\n#ifndef SOFA_DOUBLE\nusing sofa::defaulttype::Rigid3fTypes;\ntemplate<>\nbool derivVectors<Rigid3fTypes>(const Rigid3fTypes::VecCoord& x0, const Rigid3fTypes::VecCoord& x1, Rigid3fTypes::VecDeriv& d)\n{\n return derivRigid3Vectors<Rigid3fTypes>(x0,x1,d);\n}\ntemplate <>\ndouble computeDot<Rigid3fTypes>(const Rigid3fTypes::Deriv& v0, const Rigid3fTypes::Deriv& v1)\n{\n return dot(v0.getVCenter(),v1.getVCenter());\n}\n\n#endif\n\n\n}\n\n\n\n\nnamespace sofa\n{\nnamespace component\n{\nnamespace controller\n{\n\ntemplate <class DataTypes>\nLCPForceFeedback<DataTypes>::LCPForceFeedback()\n : forceCoef(initData(&forceCoef, 0.03, \"forceCoef\",\"multiply haptic force by this coef.\")),\n haptic_freq(0.0)\n{\n this->f_listening.setValue(true);\n mLcp[0] = 0;\n mLcp[1] = 0;\n mLcp[2] = 0;\n mCurBufferId = 0;\n mNextBufferId = 0;\n mIsCuBufferInUse = false;\n _timer = new CTime();\n\n}\n\n\ntemplate <class DataTypes>\nvoid LCPForceFeedback<DataTypes>::init()\n{\n core::objectmodel::BaseContext* c = this->getContext();\n\n this->ForceFeedback::init();\n if(!c)\n {\n serr << \"LCPForceFeedback has no current context. Initialisation failed.\" << sendl;\n return;\n }\n\n c->get(lcpconstraintSolver);\n\n if (!lcpconstraintSolver)\n {\n serr << \"LCPForceFeedback has no binding MasterContactSolver. Initialisation failed.\" << sendl;\n return;\n }\n\n mState = dynamic_cast<core::behavior::MechanicalState<DataTypes> *> (c->getMechanicalState());\n if (!mState)\n {\n serr << \"LCPForceFeedback has no binding MechanicalState. Initialisation failed.\" << sendl;\n return;\n }\n\n \/\/sout << \"init LCPForceFeedback done \" << sendl;\n};\n\n\n\ntemplate <class DataTypes>\nvoid LCPForceFeedback<DataTypes>::computeForce(const VecCoord& state, VecDeriv& forces)\n{\n const unsigned int stateSize = state.size();\n \/\/ Resize du vecteur force. Initialization 0 ?\n forces.resize(stateSize);\n\n\n if(!lcpconstraintSolver||!mState)\n return;\n\n\n if (!f_activate.getValue())\n {\n return;\n }\n\n\n \/\/\n \/\/ Retrieve the last LCP and constraints computed by the Sofa thread.\n \/\/\n mIsCuBufferInUse = true;\n\n\n mCurBufferId = mNextBufferId;\n\n const MatrixDeriv& constraints = mConstraints[mCurBufferId];\n\/\/\tstd::vector<int> &id_buf = mId_buf[mCurBufferId];\n VecCoord &val = mVal[mCurBufferId];\n component::constraintset::LCP* lcp = mLcp[mCurBufferId];\n\n if(!lcp)\n {\n mIsCuBufferInUse = false;\n return;\n }\n\n component::constraintset::GenericLCP* glcp = dynamic_cast<component::constraintset::GenericLCP*>(lcp);\n if((lcp->getMu() > 0.0 || glcp) && (!constraints.empty()))\n {\n VecDeriv dx;\n\n derivVectors< DataTypes >(val, state, dx);\n\n \/\/ Modify Dfree\n MatrixDerivRowConstIterator rowItEnd = constraints.end();\n\n for (MatrixDerivRowConstIterator rowIt = constraints.begin(); rowIt != rowItEnd; ++rowIt)\n {\n MatrixDerivColConstIterator colItEnd = rowIt.end();\n\n for (MatrixDerivColConstIterator colIt = rowIt.begin(); colIt != colItEnd; ++colIt)\n {\n lcp->getDfree()[rowIt.index()] += computeDot<DataTypes>(colIt.val(), dx[colIt.index()]);\n }\n }\n\n double tol = lcp->getTolerance();\n int max = 100;\n\n tol *= 0.001;\n\n if(glcp != NULL)\n {\n glcp->setTolerance(tol);\n glcp->setMaxIter(max);\n glcp->gaussSeidel(0.0008);\n }\n else\n helper::nlcp_gaussseidelTimed(lcp->getNbConst(), lcp->getDfree(), lcp->getW(), lcp->getF(), lcp->getMu(), tol, max, true, 0.0008);\n\n \/\/ Restore Dfree\n for (MatrixDerivRowConstIterator rowIt = constraints.begin(); rowIt != rowItEnd; ++rowIt)\n {\n MatrixDerivColConstIterator colItEnd = rowIt.end();\n\n for (MatrixDerivColConstIterator colIt = rowIt.begin(); colIt != colItEnd; ++colIt)\n {\n lcp->getDfree()[rowIt.index()] -= computeDot<DataTypes>(colIt.val(), dx[colIt.index()]);\n }\n }\n\n VecDeriv tempForces;\n tempForces.resize(val.size());\n\n for (MatrixDerivRowConstIterator rowIt = constraints.begin(); rowIt != rowItEnd; ++rowIt)\n {\n if (lcp->getF()[rowIt.index()] != 0.0)\n {\n MatrixDerivColConstIterator colItEnd = rowIt.end();\n\n for (MatrixDerivColConstIterator colIt = rowIt.begin(); colIt != colItEnd; ++colIt)\n {\n tempForces[colIt.index()] += colIt.val() * lcp->getF()[rowIt.index()];\n }\n }\n }\n\n for(unsigned int i = 0; i < stateSize; ++i)\n {\n forces[i] = tempForces[i] * forceCoef.getValue();\n }\n }\n\n mIsCuBufferInUse = false;\n}\n\ntemplate <typename DataTypes>\nvoid LCPForceFeedback<DataTypes>::handleEvent(sofa::core::objectmodel::Event *event)\n{\n if (!dynamic_cast<sofa::simulation::AnimateEndEvent*>(event))\n return;\n\n if (!lcpconstraintSolver)\n return;\n\n if (!mState)\n return;\n\n component::constraintset::LCP* new_lcp = lcpconstraintSolver->getLCP();\n if (!new_lcp)\n return;\n\n \/\/ Find available buffer\n\n unsigned char buf_index=0;\n unsigned char cbuf_index=mCurBufferId;\n unsigned char nbuf_index=mNextBufferId;\n\n if (buf_index == cbuf_index || buf_index == nbuf_index)\n buf_index++;\n\n if (buf_index == cbuf_index || buf_index == nbuf_index)\n buf_index++;\n\n \/\/ Compute constraints, id_buf lcp and val for the current lcp.\n\n MatrixDeriv& constraints = mConstraints[buf_index];\n\n\/\/\tstd::vector<int>& id_buf = mId_buf[buf_index];\n VecCoord& val = mVal[buf_index];\n\n \/\/ Update LCP\n mLcp[buf_index] = new_lcp;\n\n \/\/ Update Val\n val = mState->read(sofa::core::VecCoordId::freePosition())->getValue();\n\n \/\/ Update constraints and id_buf\n constraints.clear();\n\/\/\tid_buf.clear();\n\n const MatrixDeriv& c = *(mState->getC());\n\n MatrixDerivRowConstIterator rowItEnd = c.end();\n\n for (MatrixDerivRowConstIterator rowIt = c.begin(); rowIt != rowItEnd; ++rowIt)\n {\n constraints.addLine(rowIt.index(), rowIt.row());\n }\n\n \/\/ valid buffer\n mNextBufferId = buf_index;\n\n \/\/ Lock lcp to prevent its use by the SOfa thread while it is used by haptic thread\n if(mIsCuBufferInUse)\n lcpconstraintSolver->lockLCP(mLcp[mCurBufferId], mLcp[mNextBufferId]);\n else\n lcpconstraintSolver->lockLCP(mLcp[mNextBufferId]);\n}\n\n\n\n\n\/\/\n\/\/ Those functions are here for compatibility with the sofa::component::controller::Forcefeedback scheme\n\/\/\n\ntemplate <typename DataTypes>\nvoid LCPForceFeedback<DataTypes>::computeForce(double , double, double, double, double, double, double, double&, double&, double&)\n{}\n\n#ifndef SOFA_DOUBLE\nusing sofa::defaulttype::Rigid3fTypes;\ntemplate <>\nvoid LCPForceFeedback<Rigid3fTypes>::computeForce(double x, double y, double z, double, double, double, double, double& fx, double& fy, double& fz)\n{\n Rigid3fTypes::VecCoord state;\n Rigid3fTypes::VecDeriv forces;\n state.resize(1);\n state[0].getCenter() = sofa::defaulttype::Vec3f((float)x,(float)y,(float)z);\n computeForce(state,forces);\n fx = forces[0].getVCenter().x();\n fy = forces[0].getVCenter().y();\n fz = forces[0].getVCenter().z();\n}\n#endif\n\n#ifndef SOFA_FLOAT\nusing sofa::defaulttype::Rigid3dTypes;\ntemplate <>\nvoid LCPForceFeedback<Rigid3dTypes>::computeForce(double x, double y, double z, double, double, double, double, double& fx, double& fy, double& fz)\n{\n Rigid3dTypes::VecCoord state;\n Rigid3dTypes::VecDeriv forces;\n state.resize(1);\n state[0].getCenter() = sofa::defaulttype::Vec3d(x,y,z);\n computeForce(state,forces);\n fx = forces[0].getVCenter().x();\n fy = forces[0].getVCenter().y();\n fz = forces[0].getVCenter().z();\n}\n#endif\n\n\/\/ 6D rendering of contacts\n#ifndef SOFA_FLOAT\nusing sofa::defaulttype::Rigid3dTypes;\ntemplate <>\nvoid LCPForceFeedback<Rigid3dTypes>::computeWrench(const SolidTypes<double>::Transform &world_H_tool,\n const SolidTypes<double>::SpatialVector &\/*V_tool_world*\/,\n SolidTypes<double>::SpatialVector &W_tool_world )\n{\n \/\/std::cerr<<\"WARNING : LCPForceFeedback::computeWrench is not implemented\"<<std::endl;\n\n if (!f_activate.getValue())\n {\n return;\n }\n\n\n\n\n\n Vec3d Force(0.0,0.0,0.0);\n\n this->computeForce(world_H_tool.getOrigin()[0], world_H_tool.getOrigin()[1],world_H_tool.getOrigin()[2],\n world_H_tool.getOrientation()[0], world_H_tool.getOrientation()[1], world_H_tool.getOrientation()[2], world_H_tool.getOrientation()[3],\n Force[0], Force[1], Force[2]);\n\n W_tool_world.setForce(Force);\n\n\n\n};\n\n\n#endif\n\n\ntemplate <typename DataTypes>\nvoid LCPForceFeedback<DataTypes>::computeWrench(const SolidTypes<double>::Transform &,\n const SolidTypes<double>::SpatialVector &,\n SolidTypes<double>::SpatialVector & )\n{}\n\n\n} \/\/ namespace controller\n} \/\/ namespace component\n} \/\/ namespace sofa\n\n#endif\n<commit_msg>r8969\/sofa-dev : FIX : should fix errors in nodev<commit_after>\n#ifndef SOFA_COMPONENT_CONTROLLER_LCPFORCEFEEDBACK_INL\n#define SOFA_COMPONENT_CONTROLLER_LCPFORCEFEEDBACK_INL\n\n#include <sofa\/component\/controller\/LCPForceFeedback.h>\n#include <sofa\/simulation\/common\/AnimateEndEvent.h>\n#include <sofa\/component\/constraintset\/LCPConstraintSolver.h>\n#ifdef SOFA_DEV\n#include <sofa\/component\/constraintset\/GenericLCPConstraintSolver.h>\n#endif \/\/ SOFA_DEV\n#include <sofa\/core\/objectmodel\/BaseContext.h>\n\n#include <algorithm>\n\nnamespace\n{\ntemplate <typename DataTypes>\nbool derivVectors(const typename DataTypes::VecCoord& x0, const typename DataTypes::VecCoord& x1, typename DataTypes::VecDeriv& d)\n{\n unsigned int sz0 = x0.size();\n unsigned int szmin = std::min(sz0,(unsigned int)x1.size());\n\n d.resize(sz0);\n for(unsigned int i=0; i<szmin; ++i)\n {\n d[i]=x1[i]-x0[i];\n }\n for(unsigned int i=szmin; i<sz0; ++i)\n {\n d[i]=-x0[i];\n }\n return true;\n}\n\ntemplate <typename DataTypes>\nbool derivRigid3Vectors(const typename DataTypes::VecCoord& x0, const typename DataTypes::VecCoord& x1, typename DataTypes::VecDeriv& d)\n{\n unsigned int sz0 = x0.size();\n unsigned int szmin = std::min(sz0,(unsigned int)x1.size());\n\n d.resize(sz0);\n for(unsigned int i=0; i<szmin; ++i)\n {\n d[i].getVCenter() = x1[i].getCenter() - x0[i].getCenter();\n \/\/ Pas de prise en charge des rotations\n }\n for(unsigned int i=szmin; i<sz0; ++i)\n {\n d[i].getVCenter() = - x0[i].getCenter();\n }\n return true;\n}\n\n\ntemplate <typename DataTypes>\ndouble computeDot(const typename DataTypes::Deriv& v0, const typename DataTypes::Deriv& v1)\n{\n return v0.x()*v1.x();\n}\n\n\n#ifndef SOFA_FLOAT\nusing sofa::defaulttype::Rigid3dTypes;\ntemplate<>\nbool derivVectors<Rigid3dTypes>(const Rigid3dTypes::VecCoord& x0, const Rigid3dTypes::VecCoord& x1, Rigid3dTypes::VecDeriv& d)\n{\n return derivRigid3Vectors<Rigid3dTypes>(x0,x1,d);\n}\ntemplate <>\ndouble computeDot<Rigid3dTypes>(const Rigid3dTypes::Deriv& v0, const Rigid3dTypes::Deriv& v1)\n{\n return dot(v0.getVCenter(),v1.getVCenter());\n}\n\n#endif\n#ifndef SOFA_DOUBLE\nusing sofa::defaulttype::Rigid3fTypes;\ntemplate<>\nbool derivVectors<Rigid3fTypes>(const Rigid3fTypes::VecCoord& x0, const Rigid3fTypes::VecCoord& x1, Rigid3fTypes::VecDeriv& d)\n{\n return derivRigid3Vectors<Rigid3fTypes>(x0,x1,d);\n}\ntemplate <>\ndouble computeDot<Rigid3fTypes>(const Rigid3fTypes::Deriv& v0, const Rigid3fTypes::Deriv& v1)\n{\n return dot(v0.getVCenter(),v1.getVCenter());\n}\n\n#endif\n\n\n}\n\n\n\n\nnamespace sofa\n{\nnamespace component\n{\nnamespace controller\n{\n\ntemplate <class DataTypes>\nLCPForceFeedback<DataTypes>::LCPForceFeedback()\n : forceCoef(initData(&forceCoef, 0.03, \"forceCoef\",\"multiply haptic force by this coef.\")),\n haptic_freq(0.0)\n{\n this->f_listening.setValue(true);\n mLcp[0] = 0;\n mLcp[1] = 0;\n mLcp[2] = 0;\n mCurBufferId = 0;\n mNextBufferId = 0;\n mIsCuBufferInUse = false;\n _timer = new CTime();\n\n}\n\n\ntemplate <class DataTypes>\nvoid LCPForceFeedback<DataTypes>::init()\n{\n core::objectmodel::BaseContext* c = this->getContext();\n\n this->ForceFeedback::init();\n if(!c)\n {\n serr << \"LCPForceFeedback has no current context. Initialisation failed.\" << sendl;\n return;\n }\n\n c->get(lcpconstraintSolver);\n\n if (!lcpconstraintSolver)\n {\n serr << \"LCPForceFeedback has no binding MasterContactSolver. Initialisation failed.\" << sendl;\n return;\n }\n\n mState = dynamic_cast<core::behavior::MechanicalState<DataTypes> *> (c->getMechanicalState());\n if (!mState)\n {\n serr << \"LCPForceFeedback has no binding MechanicalState. Initialisation failed.\" << sendl;\n return;\n }\n\n \/\/sout << \"init LCPForceFeedback done \" << sendl;\n};\n\n\n\ntemplate <class DataTypes>\nvoid LCPForceFeedback<DataTypes>::computeForce(const VecCoord& state, VecDeriv& forces)\n{\n const unsigned int stateSize = state.size();\n \/\/ Resize du vecteur force. Initialization 0 ?\n forces.resize(stateSize);\n\n\n if(!lcpconstraintSolver||!mState)\n return;\n\n\n if (!f_activate.getValue())\n {\n return;\n }\n\n\n \/\/\n \/\/ Retrieve the last LCP and constraints computed by the Sofa thread.\n \/\/\n mIsCuBufferInUse = true;\n\n\n mCurBufferId = mNextBufferId;\n\n const MatrixDeriv& constraints = mConstraints[mCurBufferId];\n\/\/\tstd::vector<int> &id_buf = mId_buf[mCurBufferId];\n VecCoord &val = mVal[mCurBufferId];\n component::constraintset::LCP* lcp = mLcp[mCurBufferId];\n\n if(!lcp)\n {\n mIsCuBufferInUse = false;\n return;\n }\n\n#ifdef SOFA_DEV\n component::constraintset::GenericLCP* glcp = dynamic_cast<component::constraintset::GenericLCP*>(lcp);\n#endif \/\/ SOFA_DEV\n if( (lcp->getMu() > 0.0\n#ifdef SOFA_DEV\n || glcp\n#endif \/\/ SOFA_DEV\n ) && (!constraints.empty()))\n {\n VecDeriv dx;\n\n derivVectors< DataTypes >(val, state, dx);\n\n \/\/ Modify Dfree\n MatrixDerivRowConstIterator rowItEnd = constraints.end();\n\n for (MatrixDerivRowConstIterator rowIt = constraints.begin(); rowIt != rowItEnd; ++rowIt)\n {\n MatrixDerivColConstIterator colItEnd = rowIt.end();\n\n for (MatrixDerivColConstIterator colIt = rowIt.begin(); colIt != colItEnd; ++colIt)\n {\n lcp->getDfree()[rowIt.index()] += computeDot<DataTypes>(colIt.val(), dx[colIt.index()]);\n }\n }\n\n double tol = lcp->getTolerance();\n int max = 100;\n\n tol *= 0.001;\n#ifdef SOFA_DEV\n if(glcp != NULL)\n {\n glcp->setTolerance(tol);\n glcp->setMaxIter(max);\n glcp->gaussSeidel(0.0008);\n }\n else\n#endif \/\/ SOFA_DEV\n helper::nlcp_gaussseidelTimed(lcp->getNbConst(), lcp->getDfree(), lcp->getW(), lcp->getF(), lcp->getMu(), tol, max, true, 0.0008);\n\n \/\/ Restore Dfree\n for (MatrixDerivRowConstIterator rowIt = constraints.begin(); rowIt != rowItEnd; ++rowIt)\n {\n MatrixDerivColConstIterator colItEnd = rowIt.end();\n\n for (MatrixDerivColConstIterator colIt = rowIt.begin(); colIt != colItEnd; ++colIt)\n {\n lcp->getDfree()[rowIt.index()] -= computeDot<DataTypes>(colIt.val(), dx[colIt.index()]);\n }\n }\n\n VecDeriv tempForces;\n tempForces.resize(val.size());\n\n for (MatrixDerivRowConstIterator rowIt = constraints.begin(); rowIt != rowItEnd; ++rowIt)\n {\n if (lcp->getF()[rowIt.index()] != 0.0)\n {\n MatrixDerivColConstIterator colItEnd = rowIt.end();\n\n for (MatrixDerivColConstIterator colIt = rowIt.begin(); colIt != colItEnd; ++colIt)\n {\n tempForces[colIt.index()] += colIt.val() * lcp->getF()[rowIt.index()];\n }\n }\n }\n\n for(unsigned int i = 0; i < stateSize; ++i)\n {\n forces[i] = tempForces[i] * forceCoef.getValue();\n }\n }\n\n mIsCuBufferInUse = false;\n}\n\ntemplate <typename DataTypes>\nvoid LCPForceFeedback<DataTypes>::handleEvent(sofa::core::objectmodel::Event *event)\n{\n if (!dynamic_cast<sofa::simulation::AnimateEndEvent*>(event))\n return;\n\n if (!lcpconstraintSolver)\n return;\n\n if (!mState)\n return;\n\n component::constraintset::LCP* new_lcp = lcpconstraintSolver->getLCP();\n if (!new_lcp)\n return;\n\n \/\/ Find available buffer\n\n unsigned char buf_index=0;\n unsigned char cbuf_index=mCurBufferId;\n unsigned char nbuf_index=mNextBufferId;\n\n if (buf_index == cbuf_index || buf_index == nbuf_index)\n buf_index++;\n\n if (buf_index == cbuf_index || buf_index == nbuf_index)\n buf_index++;\n\n \/\/ Compute constraints, id_buf lcp and val for the current lcp.\n\n MatrixDeriv& constraints = mConstraints[buf_index];\n\n\/\/\tstd::vector<int>& id_buf = mId_buf[buf_index];\n VecCoord& val = mVal[buf_index];\n\n \/\/ Update LCP\n mLcp[buf_index] = new_lcp;\n\n \/\/ Update Val\n val = mState->read(sofa::core::VecCoordId::freePosition())->getValue();\n\n \/\/ Update constraints and id_buf\n constraints.clear();\n\/\/\tid_buf.clear();\n\n const MatrixDeriv& c = *(mState->getC());\n\n MatrixDerivRowConstIterator rowItEnd = c.end();\n\n for (MatrixDerivRowConstIterator rowIt = c.begin(); rowIt != rowItEnd; ++rowIt)\n {\n constraints.addLine(rowIt.index(), rowIt.row());\n }\n\n \/\/ valid buffer\n mNextBufferId = buf_index;\n\n \/\/ Lock lcp to prevent its use by the SOfa thread while it is used by haptic thread\n if(mIsCuBufferInUse)\n lcpconstraintSolver->lockLCP(mLcp[mCurBufferId], mLcp[mNextBufferId]);\n else\n lcpconstraintSolver->lockLCP(mLcp[mNextBufferId]);\n}\n\n\n\n\n\/\/\n\/\/ Those functions are here for compatibility with the sofa::component::controller::Forcefeedback scheme\n\/\/\n\ntemplate <typename DataTypes>\nvoid LCPForceFeedback<DataTypes>::computeForce(double , double, double, double, double, double, double, double&, double&, double&)\n{}\n\n#ifndef SOFA_DOUBLE\nusing sofa::defaulttype::Rigid3fTypes;\ntemplate <>\nvoid LCPForceFeedback<Rigid3fTypes>::computeForce(double x, double y, double z, double, double, double, double, double& fx, double& fy, double& fz)\n{\n Rigid3fTypes::VecCoord state;\n Rigid3fTypes::VecDeriv forces;\n state.resize(1);\n state[0].getCenter() = sofa::defaulttype::Vec3f((float)x,(float)y,(float)z);\n computeForce(state,forces);\n fx = forces[0].getVCenter().x();\n fy = forces[0].getVCenter().y();\n fz = forces[0].getVCenter().z();\n}\n#endif\n\n#ifndef SOFA_FLOAT\nusing sofa::defaulttype::Rigid3dTypes;\ntemplate <>\nvoid LCPForceFeedback<Rigid3dTypes>::computeForce(double x, double y, double z, double, double, double, double, double& fx, double& fy, double& fz)\n{\n Rigid3dTypes::VecCoord state;\n Rigid3dTypes::VecDeriv forces;\n state.resize(1);\n state[0].getCenter() = sofa::defaulttype::Vec3d(x,y,z);\n computeForce(state,forces);\n fx = forces[0].getVCenter().x();\n fy = forces[0].getVCenter().y();\n fz = forces[0].getVCenter().z();\n}\n#endif\n\n\/\/ 6D rendering of contacts\n#ifndef SOFA_FLOAT\nusing sofa::defaulttype::Rigid3dTypes;\ntemplate <>\nvoid LCPForceFeedback<Rigid3dTypes>::computeWrench(const SolidTypes<double>::Transform &world_H_tool,\n const SolidTypes<double>::SpatialVector &\/*V_tool_world*\/,\n SolidTypes<double>::SpatialVector &W_tool_world )\n{\n \/\/std::cerr<<\"WARNING : LCPForceFeedback::computeWrench is not implemented\"<<std::endl;\n\n if (!f_activate.getValue())\n {\n return;\n }\n\n\n\n\n\n Vec3d Force(0.0,0.0,0.0);\n\n this->computeForce(world_H_tool.getOrigin()[0], world_H_tool.getOrigin()[1],world_H_tool.getOrigin()[2],\n world_H_tool.getOrientation()[0], world_H_tool.getOrientation()[1], world_H_tool.getOrientation()[2], world_H_tool.getOrientation()[3],\n Force[0], Force[1], Force[2]);\n\n W_tool_world.setForce(Force);\n\n\n\n};\n\n\n#endif\n\n\ntemplate <typename DataTypes>\nvoid LCPForceFeedback<DataTypes>::computeWrench(const SolidTypes<double>::Transform &,\n const SolidTypes<double>::SpatialVector &,\n SolidTypes<double>::SpatialVector & )\n{}\n\n\n} \/\/ namespace controller\n} \/\/ namespace component\n} \/\/ namespace sofa\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>#include \"xhp.hpp\"\n#include \"xhp_preprocess.hpp\"\n#include \"fastpath.hpp\"\n#include <sstream>\nusing namespace std;\nextern int xhpdebug;\n#include <iostream>\n\nXHPResult xhp_preprocess(istream &in, string &out, bool isEval, string &errDescription, uint32_t &errLineno) {\n\n \/\/ Read stream to string\n stringbuf sb;\n in >> noskipws >> &sb;\n string buffer = sb.str();\n return xhp_preprocess(buffer, out, isEval, errDescription, errLineno);\n}\n\nXHPResult xhp_preprocess(string &in, string &out, bool isEval, string &errDescription, uint32_t &errLineno) {\n xhp_flags_t flags;\n memset(&flags, 0, sizeof(xhp_flags_t));\n flags.eval = isEval;\n flags.short_tags = true;\n return xhp_preprocess(in, out, errDescription, errLineno, flags);\n}\n\nXHPResult xhp_preprocess(std::string &in, std::string &out, std::string &errDescription, uint32_t &errLineno, const xhp_flags_t &flags) {\n\n \/\/ Early bail if the code doesn't contain anything that looks like XHP\n char* buffer = const_cast<char*>(in.c_str());\n if (!xhp_fastpath(buffer, in.length(), flags)) {\n return XHPDidNothing;\n }\n\n \/\/ Create a flex buffer\n in.reserve(in.size() + 1);\n buffer = const_cast<char*>(in.c_str());\n buffer[in.size() + 1] = 0; \/\/ need double NULL for scan_buffer\n\n \/\/ Parse the PHP\n void* scanner;\n code_rope new_code;\n yy_extra_type extra;\n extra.idx_expr = flags.idx_expr;\n extra.insert_token = flags.eval ? T_OPEN_TAG_FAKE : 0;\n extra.short_tags = flags.short_tags;\n extra.asp_tags = flags.asp_tags;\n\n xhplex_init(&scanner);\n xhpset_extra(&extra, scanner);\n xhp_scan_buffer(buffer, in.size() + 2, scanner);\n#ifdef DEBUG\n xhpdebug = 1;\n#endif\n xhpparse(scanner, &new_code);\n xhplex_destroy(scanner);\n\n \/\/ Check to see what happened\n if (extra.terminated) {\n errDescription = extra.error;\n errLineno = extra.lineno;\n return XHPErred;\n } else if (!extra.used) {\n return XHPDidNothing;\n } else {\n out = new_code.c_str();\n return XHPRewrote;\n }\n}\n<commit_msg>Default idx_expr to true in xhp_preprocess<commit_after>#include \"xhp.hpp\"\n#include \"xhp_preprocess.hpp\"\n#include \"fastpath.hpp\"\n#include <sstream>\nusing namespace std;\nextern int xhpdebug;\n#include <iostream>\n\nXHPResult xhp_preprocess(istream &in, string &out, bool isEval, string &errDescription, uint32_t &errLineno) {\n\n \/\/ Read stream to string\n stringbuf sb;\n in >> noskipws >> &sb;\n string buffer = sb.str();\n return xhp_preprocess(buffer, out, isEval, errDescription, errLineno);\n}\n\nXHPResult xhp_preprocess(string &in, string &out, bool isEval, string &errDescription, uint32_t &errLineno) {\n xhp_flags_t flags;\n memset(&flags, 0, sizeof(xhp_flags_t));\n flags.eval = isEval;\n flags.short_tags = true;\n flags.idx_expr = true;\n return xhp_preprocess(in, out, errDescription, errLineno, flags);\n}\n\nXHPResult xhp_preprocess(std::string &in, std::string &out, std::string &errDescription, uint32_t &errLineno, const xhp_flags_t &flags) {\n\n \/\/ Early bail if the code doesn't contain anything that looks like XHP\n char* buffer = const_cast<char*>(in.c_str());\n if (!xhp_fastpath(buffer, in.length(), flags)) {\n return XHPDidNothing;\n }\n\n \/\/ Create a flex buffer\n in.reserve(in.size() + 1);\n buffer = const_cast<char*>(in.c_str());\n buffer[in.size() + 1] = 0; \/\/ need double NULL for scan_buffer\n\n \/\/ Parse the PHP\n void* scanner;\n code_rope new_code;\n yy_extra_type extra;\n extra.idx_expr = flags.idx_expr;\n extra.insert_token = flags.eval ? T_OPEN_TAG_FAKE : 0;\n extra.short_tags = flags.short_tags;\n extra.asp_tags = flags.asp_tags;\n\n xhplex_init(&scanner);\n xhpset_extra(&extra, scanner);\n xhp_scan_buffer(buffer, in.size() + 2, scanner);\n#ifdef DEBUG\n xhpdebug = 1;\n#endif\n xhpparse(scanner, &new_code);\n xhplex_destroy(scanner);\n\n \/\/ Check to see what happened\n if (extra.terminated) {\n errDescription = extra.error;\n errLineno = extra.lineno;\n return XHPErred;\n } else if (!extra.used) {\n return XHPDidNothing;\n } else {\n out = new_code.c_str();\n return XHPRewrote;\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/** \\file\n * Implements generally useful functions.\n *\/\n\n#include <type_traits> \/* std::underlying_type *\/\n#include <string>\n\n#include <cstdio> \/* snprintf() *\/\n\n#ifndef _POWERDXX_UTILITY_HPP_\n#define _POWERDXX_UTILITY_HPP_\n\n\/**\n * A collection of generally useful functions.\n *\/\nnamespace utility {\n\n\/**\n * Like sizeof(), but it returns the number of elements an array consists\n * of instead of the number of bytes.\n *\n * @tparam T,Count\n *\tThe type and number of array elements\n * @return\n *\tThe number of array entries\n *\/\ntemplate <typename T, size_t Count>\nconstexpr size_t countof(T (&)[Count]) { return Count; }\n\n\/**\n * Contains literals.\n *\/\nnamespace literals {\n\n\/**\n * A string literal operator equivalent to the `operator \"\" s` literal\n * provided by C++14 in \\<string\\>.\n *\n * @param op\n *\tThe raw string to turn into an std::string object\n * @param size\n *\tThe size of the raw string\n * @return\n *\tAn std::string instance\n *\/\ninline std::string operator \"\" _s(char const * const op, size_t const size) {\n\treturn {op, size};\n}\n\n} \/* namespace literals *\/\n\n\/**\n * This is a safeguard against accidentally using sprintf().\n *\n * Using it triggers a static_assert(), preventing compilation.\n *\n * @tparam Args\n *\tCatch all arguments\n *\/\ntemplate <typename... Args>\ninline void sprintf(Args...) {\n\t\/* Assert depends on Args so it can only be determined if\n\t * the function is actually instantiated. *\/\n\tstatic_assert(sizeof...(Args) && false,\n\t \"Use of sprintf() is unsafe, use sprintf_safe() instead\");\n}\n\n\/**\n * A wrapper around snprintf() that automatically pulls in the\n * destination buffer size.\n *\n * @tparam Size\n *\tThe destination buffer size\n * @tparam Args\n *\tThe types of the arguments\n * @param dst\n *\tA reference to the destination buffer\n * @param format\n *\tA printf style formatting string\n * @param args\n *\tThe printf arguments\n * @return\n *\tThe number of characters in the resulting string, regardless of the\n *\tavailable space\n *\/\ntemplate <size_t Size, typename... Args>\ninline int sprintf_safe(char (& dst)[Size], char const * const format,\n Args const... args) {\n\treturn snprintf(dst, Size, format, args...);\n}\n\n\/**\n * Casts an enum to its underlying value.\n *\n * @tparam ET,VT\n *\tThe enum and value type\n * @param op\n *\tThe operand to convert\n * @return\n *\tThe integer representation of the operand\n *\/\ntemplate <class ET, typename VT = typename std::underlying_type<ET>::type>\nconstexpr VT to_value(ET const op) {\n\treturn static_cast<VT>(op);\n}\n\n\/**\n * A formatting wrapper around string literals.\n *\n * Overloads operator (), which treats the string as a printf formatting\n * string, the arguments represent the data to format.\n *\n * In combination with the literal _fmt, it can be used like this:\n *\n * ~~~ c++\n * std::cout << \"%-15.15s %#018p\\n\"_fmt(\"Address:\", this);\n * ~~~\n *\n * @tparam BufSize\n *\tThe buffer size for formatting, resulting strings cannot\n *\tgrow beyond `BufSize - 1`\n *\/\ntemplate <size_t BufSize>\nclass Formatter {\n\tprivate:\n\t\/**\n\t * Pointer to the string literal.\n\t *\/\n\tchar const * const fmt;\n\n\tpublic:\n\t\/**\n\t * Construct from string literal.\n\t *\/\n\tconstexpr Formatter(char const * const fmt) : fmt{fmt} {}\n\n\t\/**\n\t * Returns a formatted string.\n\t *\n\t * @tparam ArgTs\n\t *\tVariadic argument types\n\t * @param args\n\t *\tVariadic arguments\n\t * @return\n\t *\tAn std::string formatted according to fmt\n\t *\/\n\ttemplate <typename... ArgTs>\n\tstd::string operator ()(ArgTs const &... args) const {\n\t\tchar buf[BufSize];\n\t\tauto count = sprintf_safe(buf, this->fmt, args...);\n\t\tif (count < 0) {\n\t\t\t\/* encoding error *\/\n\t\t\treturn {};\n\t\t} else if (static_cast<size_t>(count) >= BufSize) {\n\t\t\t\/* does not fit into buffer *\/\n\t\t\treturn {buf, BufSize - 1};\n\t\t}\n\t\treturn {buf, static_cast<size_t>(count)};\n\t}\n};\n\nnamespace literals {\n\/**\n * Literal to convert a string literal to a Formatter instance.\n *\n * @param fmt\n *\tA printf style format string\n * @param const\n *\tUnused\n * @return\n *\tA Formatter instance\n *\/\nconstexpr Formatter<16384> operator \"\" _fmt(char const * const fmt, size_t const) {\n\treturn {fmt};\n}\n} \/* namespace literals *\/\n\n} \/* namespace utility *\/\n\n#endif \/* _POWERDXX_UTILITY_HPP_ *\/\n<commit_msg>Add utility::Sum, an addition only value container<commit_after>\/** \\file\n * Implements generally useful functions.\n *\/\n\n#include <type_traits> \/* std::underlying_type *\/\n#include <string>\n\n#include <cstdio> \/* snprintf() *\/\n\n#ifndef _POWERDXX_UTILITY_HPP_\n#define _POWERDXX_UTILITY_HPP_\n\n\/**\n * A collection of generally useful functions.\n *\/\nnamespace utility {\n\n\/**\n * Like sizeof(), but it returns the number of elements an array consists\n * of instead of the number of bytes.\n *\n * @tparam T,Count\n *\tThe type and number of array elements\n * @return\n *\tThe number of array entries\n *\/\ntemplate <typename T, size_t Count>\nconstexpr size_t countof(T (&)[Count]) { return Count; }\n\n\/**\n * Contains literals.\n *\/\nnamespace literals {\n\n\/**\n * A string literal operator equivalent to the `operator \"\" s` literal\n * provided by C++14 in \\<string\\>.\n *\n * @param op\n *\tThe raw string to turn into an std::string object\n * @param size\n *\tThe size of the raw string\n * @return\n *\tAn std::string instance\n *\/\ninline std::string operator \"\" _s(char const * const op, size_t const size) {\n\treturn {op, size};\n}\n\n} \/* namespace literals *\/\n\n\/**\n * This is a safeguard against accidentally using sprintf().\n *\n * Using it triggers a static_assert(), preventing compilation.\n *\n * @tparam Args\n *\tCatch all arguments\n *\/\ntemplate <typename... Args>\ninline void sprintf(Args...) {\n\t\/* Assert depends on Args so it can only be determined if\n\t * the function is actually instantiated. *\/\n\tstatic_assert(sizeof...(Args) && false,\n\t \"Use of sprintf() is unsafe, use sprintf_safe() instead\");\n}\n\n\/**\n * A wrapper around snprintf() that automatically pulls in the\n * destination buffer size.\n *\n * @tparam Size\n *\tThe destination buffer size\n * @tparam Args\n *\tThe types of the arguments\n * @param dst\n *\tA reference to the destination buffer\n * @param format\n *\tA printf style formatting string\n * @param args\n *\tThe printf arguments\n * @return\n *\tThe number of characters in the resulting string, regardless of the\n *\tavailable space\n *\/\ntemplate <size_t Size, typename... Args>\ninline int sprintf_safe(char (& dst)[Size], char const * const format,\n Args const... args) {\n\treturn snprintf(dst, Size, format, args...);\n}\n\n\/**\n * Casts an enum to its underlying value.\n *\n * @tparam ET,VT\n *\tThe enum and value type\n * @param op\n *\tThe operand to convert\n * @return\n *\tThe integer representation of the operand\n *\/\ntemplate <class ET, typename VT = typename std::underlying_type<ET>::type>\nconstexpr VT to_value(ET const op) {\n\treturn static_cast<VT>(op);\n}\n\n\/**\n * A formatting wrapper around string literals.\n *\n * Overloads operator (), which treats the string as a printf formatting\n * string, the arguments represent the data to format.\n *\n * In combination with the literal _fmt, it can be used like this:\n *\n * ~~~ c++\n * std::cout << \"%-15.15s %#018p\\n\"_fmt(\"Address:\", this);\n * ~~~\n *\n * @tparam BufSize\n *\tThe buffer size for formatting, resulting strings cannot\n *\tgrow beyond `BufSize - 1`\n *\/\ntemplate <size_t BufSize>\nclass Formatter {\n\tprivate:\n\t\/**\n\t * Pointer to the string literal.\n\t *\/\n\tchar const * const fmt;\n\n\tpublic:\n\t\/**\n\t * Construct from string literal.\n\t *\/\n\tconstexpr Formatter(char const * const fmt) : fmt{fmt} {}\n\n\t\/**\n\t * Returns a formatted string.\n\t *\n\t * @tparam ArgTs\n\t *\tVariadic argument types\n\t * @param args\n\t *\tVariadic arguments\n\t * @return\n\t *\tAn std::string formatted according to fmt\n\t *\/\n\ttemplate <typename... ArgTs>\n\tstd::string operator ()(ArgTs const &... args) const {\n\t\tchar buf[BufSize];\n\t\tauto count = sprintf_safe(buf, this->fmt, args...);\n\t\tif (count < 0) {\n\t\t\t\/* encoding error *\/\n\t\t\treturn {};\n\t\t} else if (static_cast<size_t>(count) >= BufSize) {\n\t\t\t\/* does not fit into buffer *\/\n\t\t\treturn {buf, BufSize - 1};\n\t\t}\n\t\treturn {buf, static_cast<size_t>(count)};\n\t}\n};\n\nnamespace literals {\n\/**\n * Literal to convert a string literal to a Formatter instance.\n *\n * @param fmt\n *\tA printf style format string\n * @param const\n *\tUnused\n * @return\n *\tA Formatter instance\n *\/\nconstexpr Formatter<16384> operator \"\" _fmt(char const * const fmt, size_t const) {\n\treturn {fmt};\n}\n} \/* namespace literals *\/\n\n\/**\n * A simple value container only allowing += and copy assignment.\n *\n * @tparam T\n *\tThe value type\n *\/\ntemplate <typename T>\nclass Sum {\n\tprivate:\n\t\/**\n\t * The sum of values accumulated.\n\t *\/\n\tT value;\n\n\tpublic:\n\t\/**\n\t * Construct from an initial value.\n\t *\n\t * @param value\n\t *\tThe initial value\n\t *\/\n\texplicit constexpr Sum(T const & value) : value{value} {}\n\n\t\/**\n\t * Default construct.\n\t *\/\n\tconstexpr Sum() : Sum{0} {}\n\n\t\/**\n\t * Returns the current sum of values.\n\t *\n\t * @return\n\t *\tThe sum of values by const reference\n\t *\/\n\tconstexpr operator T const &() const {\n\t\treturn this->value;\n\t}\n\n\t\/**\n\t * Add a value to the sum.\n\t *\n\t * @param value\n\t *\tThe value to add to the current sum\n\t * @return\n\t *\tA self reference\n\t *\/\n\tconstexpr Sum & operator +=(T const & value) {\n\t\tthis->value += value;\n\t\treturn *this;\n\t}\n};\n\n} \/* namespace utility *\/\n\n#endif \/* _POWERDXX_UTILITY_HPP_ *\/\n<|endoftext|>"} {"text":"<commit_before>\/* SevSeg Library\n \n Copyright 2014 Dean Reading\n \n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at \n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n \n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n \n \n This library allows an arduino to easily display numbers in decimal format on\n a 4 digit 7-segment display without a separate 7-segment display controller.\n \n Direct any questions or suggestions to deanreading@hotmail.com\n \n See the included documentation file for instructions.\n \n CHANGELOG\n \n Version 3.0 - November 2014\n Library re-design. A display with any number of digits can be used.\n Floats are supported. Support for using transistors for switching.\n Much more user friendly. No backwards compatibility.\n Uploaded to GitHub to simplify any further development.\n Version 2.3; Allows for brightness control.\n Version 2.2; Allows 1, 2 or 3 digit displays to be used.\n Version 2.1; Includes a bug fix.\n Version 2.0; Now works for any digital pin arrangement.\n Supports both common anode and common cathode displays.\n *\/\n\n#include \"SevSeg.h\"\n\n#define BLANK 10 \/\/ Must match with 'digitCodeMap', defined in 'setDigitCodes' \n#define DASH 11\n\n\nconst long SevSeg::powersOf10[] = {\n 1, \/\/ 10^0\n 10,\n 100,\n 1000,\n 10000,\n 100000,\n 1000000,\n 10000000,\n 100000000,\n 1000000000}; \/\/ 10^9\n\n\n\/\/ SevSeg\n\/******************************************************************************\/\nSevSeg::SevSeg()\n{\n \/\/ Initial value\n ledOnTime = 2000; \/\/ Corresponds to a brightness of 100\n numDigits = 0;\n}\n\n\n\/\/ begin\n\/******************************************************************************\/\n\/\/ Saves the input pin numbers to the class and sets up the pins to be used.\n\nvoid SevSeg::begin(byte hardwareConfig, byte numDigitsIn, \n byte digitPinsIn[], byte segmentPinsIn[]) {\n numDigits = numDigitsIn;\n\n digitCodes = new byte[numDigits];\n digitPins = new byte[numDigits];\n\n switch (hardwareConfig){\n\n case 0: \/\/ Common cathode\n digitOn = LOW;\n segmentOn = HIGH;\n break;\n\n case 1: \/\/ Common anode\n digitOn = HIGH;\n segmentOn = LOW;\n break;\n\n case 2: \/\/ With active-high, low-side switches (most commonly N-type FETs)\n digitOn = HIGH;\n segmentOn = HIGH;\n break;\n\n case 3: \/\/ With active low, high side switches (most commonly P-type FETs)\n digitOn = LOW;\n segmentOn = LOW;\n break;\n }\n\n digitOff = !digitOn;\n segmentOff = !segmentOff;\n\n \/\/ Save the input pin numbers to library variables\n for (byte segmentNum = 0 ; segmentNum < 8 ; segmentNum++) {\n segmentPins[segmentNum] = segmentPinsIn[segmentNum];\n }\n\n for (byte digitNum = 0 ; digitNum < numDigits ; digitNum++) {\n digitPins[digitNum] = digitPinsIn[digitNum];\n }\n\n \/\/ Set the pins as outputs, and turn them off\n for (byte digit=0 ; digit < numDigits ; digit++) {\n pinMode(digitPins[digit], OUTPUT);\n digitalWrite(digitPins[digit], digitOff);\n }\n\n for (byte segmentNum=0 ; segmentNum < 8 ; segmentNum++) {\n pinMode(segmentPins[segmentNum], OUTPUT);\n digitalWrite(segmentPins[segmentNum], segmentOff);\n }\n\n setNewNum(0,0); \/\/ Initialise the number displayed to 0\n}\n\n\n\/\/ refreshDisplay\n\/******************************************************************************\/\n\/\/ Flashes the output on the seven segment display.\n\/\/ This is achieved by cycling through all segments and digits, turning the\n\/\/ required segments on as specified by the array 'digitCodes'.\n\nvoid SevSeg::refreshDisplay(){\n for (byte segmentNum=0 ; segmentNum < 8 ; segmentNum++) {\n\n \/\/ Illuminate the required digits for this segment\n digitalWrite(segmentPins[segmentNum], segmentOn);\n for (byte digitNum=0 ; digitNum < numDigits ; digitNum++){\n if (digitCodes[digitNum] & (1 << segmentNum)) { \/\/ Check a single bit\n digitalWrite(digitPins[digitNum], digitOn);\n }\n }\n\n \/\/Wait with lights on (to increase brightness)\n delayMicroseconds(ledOnTime); \n\n \/\/Turn all segments off\n for (byte digitNum=0 ; digitNum < numDigits ; digitNum++){\n digitalWrite(digitPins[digitNum], digitOff);\n }\n digitalWrite(segmentPins[segmentNum], segmentOff);\n }\n}\n\n\n\/\/ setBrightness\n\/******************************************************************************\/\n\nvoid SevSeg::setBrightness(int brightness){\n brightness = constrain(brightness, 0, 100);\n ledOnTime = map(brightness, 0, 100, 1, 2000);\n}\n\n\n\/\/ setNumber\n\/******************************************************************************\/\n\/\/ This function only receives the input and passes it to 'setNewNum'.\n\/\/ It is overloaded for all number data types, so that floats can be handled\n\/\/ correctly.\n\nvoid SevSeg::setNumber(long numToShow, byte decPlaces) \/\/long\n{\n setNewNum(numToShow, decPlaces);\n}\n\nvoid SevSeg::setNumber(unsigned long numToShow, byte decPlaces) \/\/unsigned long\n{\n setNewNum(numToShow, decPlaces);\n}\n\nvoid SevSeg::setNumber(int numToShow, byte decPlaces) \/\/int\n{\n setNewNum(numToShow, decPlaces);\n}\n\nvoid SevSeg::setNumber(unsigned int numToShow, byte decPlaces) \/\/unsigned int\n{\n setNewNum(numToShow, decPlaces);\n}\n\nvoid SevSeg::setNumber(char numToShow, byte decPlaces) \/\/char\n{\n setNewNum(numToShow, decPlaces);\n}\n\nvoid SevSeg::setNumber(byte numToShow, byte decPlaces) \/\/byte\n{\n setNewNum(numToShow, decPlaces);\n}\n\nvoid SevSeg::setNumber(float numToShow, byte decPlaces) \/\/float\n{\n numToShow = numToShow * powersOf10[decPlaces];\n \/\/ Modify the number so that it is rounded to an integer correctly\n numToShow += (numToShow >= 0) ? 0.5f : -0.5f;\n setNewNum(numToShow, decPlaces);\n}\n\n\n\/\/ setNewNum\n\/******************************************************************************\/\n\/\/ Changes the number that will be displayed.\n\nvoid SevSeg::setNewNum(long numToShow, byte decPlaces){\n byte digits[numDigits];\n findDigits(numToShow, decPlaces, digits);\n setDigitCodes(digits, decPlaces);\n}\n\n\n\/\/ findDigits\n\/******************************************************************************\/\n\/\/ Decides what each digit will display.\n\/\/ Enforces the upper and lower limits on the number to be displayed.\n\nvoid SevSeg::findDigits(long numToShow, byte decPlaces, byte digits[]) {\n static const int maxNum = powersOf10[numDigits] - 1;\n static const int minNum = -(powersOf10[numDigits - 1] - 1);\n\n \/\/ If the number is out of range, just display dashes\n if (numToShow > maxNum || numToShow < minNum) {\n for (byte digitNum = 0 ; digitNum < numDigits ; digitNum++){\n digits[digitNum] = DASH;\n }\n }\n else{\n byte digitNum = 0;\n\n \/\/ Convert all number to positive values\n if (numToShow < 0) {\n digits[0] = DASH;\n digitNum = 1; \/\/ Skip the first iteration\n numToShow = -numToShow;\n }\n\n \/\/ Find all digits for the base 10 representation, starting with the most\n \/\/ significant digit\n for ( ; digitNum < numDigits ; digitNum++){\n long factor = powersOf10[numDigits - 1 - digitNum];\n digits[digitNum] = numToShow \/ factor;\n numToShow -= digits[digitNum] * factor;\n }\n\n \/\/ Find unnnecessary leading zeros and set them to BLANK\n for (digitNum = 0 ; digitNum < (numDigits - 1 - decPlaces) ; digitNum++){\n if (digits[digitNum] == 0) {\n digits[digitNum] = BLANK;\n }\n \/\/ Exit once the first non-zero number is encountered\n else if (digits[digitNum] <= 9) {\n break;\n }\n }\n\n }\n}\n\n\n\/\/ setDigitCodes\n\/******************************************************************************\/\n\/\/ Sets the 'digitCodes' that are required to display the input numbers\n\nvoid SevSeg::setDigitCodes(byte digits[], byte decPlaces) {\n\n \/\/ The codes below indicate which segments must be illuminated to display\n \/\/ each number.\n static const byte digitCodeMap[] = {\n B00111111, \/\/ 0\n B00000110, \/\/ 1\n B01011011, \/\/ 2\n B01001111, \/\/ 3\n B01100110, \/\/ 4\n B01101101, \/\/ 5\n B01111101, \/\/ 6\n B00000111, \/\/ 7\n B01111111, \/\/ 8\n B01101111, \/\/ 9\n B00000000, \/\/ BLANK\n B01000000 }; \/\/ DASH\n\n \/\/ Set the digitCode for each digit in the display\n for (byte digitNum = 0 ; digitNum < numDigits ; digitNum++) {\n digitCodes[digitNum] = digitCodeMap[digits[digitNum]];\n }\n\n \/\/ Set the decimal place segment\n digitCodes[numDigits - 1 - decPlaces] |= B10000000;\n}\n\n\/\/\/ END \/\/\/\n<commit_msg>Minor change to deal with bad input<commit_after>\/* SevSeg Library\n \n Copyright 2014 Dean Reading\n \n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at \n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n \n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n \n \n This library allows an arduino to easily display numbers in decimal format on\n a 4 digit 7-segment display without a separate 7-segment display controller.\n \n Direct any questions or suggestions to deanreading@hotmail.com\n \n See the included documentation file for instructions.\n \n CHANGELOG\n \n Version 3.0 - November 2014\n Library re-design. A display with any number of digits can be used.\n Floats are supported. Support for using transistors for switching.\n Much more user friendly. No backwards compatibility.\n Uploaded to GitHub to simplify any further development.\n Version 2.3; Allows for brightness control.\n Version 2.2; Allows 1, 2 or 3 digit displays to be used.\n Version 2.1; Includes a bug fix.\n Version 2.0; Now works for any digital pin arrangement.\n Supports both common anode and common cathode displays.\n *\/\n\n#include \"SevSeg.h\"\n\n#define BLANK 10 \/\/ Must match with 'digitCodeMap', defined in 'setDigitCodes' \n#define DASH 11\n\n\nconst long SevSeg::powersOf10[] = {\n 1, \/\/ 10^0\n 10,\n 100,\n 1000,\n 10000,\n 100000,\n 1000000,\n 10000000,\n 100000000,\n 1000000000}; \/\/ 10^9\n\n\n\/\/ SevSeg\n\/******************************************************************************\/\nSevSeg::SevSeg()\n{\n \/\/ Initial value\n ledOnTime = 2000; \/\/ Corresponds to a brightness of 100\n numDigits = 0;\n}\n\n\n\/\/ begin\n\/******************************************************************************\/\n\/\/ Saves the input pin numbers to the class and sets up the pins to be used.\n\nvoid SevSeg::begin(byte hardwareConfig, byte numDigitsIn, \n byte digitPinsIn[], byte segmentPinsIn[]) {\n numDigits = numDigitsIn;\n\n digitCodes = new byte[numDigits];\n digitPins = new byte[numDigits];\n\n switch (hardwareConfig){\n\n case 0: \/\/ Common cathode\n digitOn = LOW;\n segmentOn = HIGH;\n break;\n\n case 1: \/\/ Common anode\n digitOn = HIGH;\n segmentOn = LOW;\n break;\n\n case 2: \/\/ With active-high, low-side switches (most commonly N-type FETs)\n digitOn = HIGH;\n segmentOn = HIGH;\n break;\n\n case 3: \/\/ With active low, high side switches (most commonly P-type FETs)\n digitOn = LOW;\n segmentOn = LOW;\n break;\n }\n\n digitOff = !digitOn;\n segmentOff = !segmentOff;\n\n \/\/ Save the input pin numbers to library variables\n for (byte segmentNum = 0 ; segmentNum < 8 ; segmentNum++) {\n segmentPins[segmentNum] = segmentPinsIn[segmentNum];\n }\n\n for (byte digitNum = 0 ; digitNum < numDigits ; digitNum++) {\n digitPins[digitNum] = digitPinsIn[digitNum];\n }\n\n \/\/ Set the pins as outputs, and turn them off\n for (byte digit=0 ; digit < numDigits ; digit++) {\n pinMode(digitPins[digit], OUTPUT);\n digitalWrite(digitPins[digit], digitOff);\n }\n\n for (byte segmentNum=0 ; segmentNum < 8 ; segmentNum++) {\n pinMode(segmentPins[segmentNum], OUTPUT);\n digitalWrite(segmentPins[segmentNum], segmentOff);\n }\n\n setNewNum(0,0); \/\/ Initialise the number displayed to 0\n}\n\n\n\/\/ refreshDisplay\n\/******************************************************************************\/\n\/\/ Flashes the output on the seven segment display.\n\/\/ This is achieved by cycling through all segments and digits, turning the\n\/\/ required segments on as specified by the array 'digitCodes'.\n\nvoid SevSeg::refreshDisplay(){\n for (byte segmentNum=0 ; segmentNum < 8 ; segmentNum++) {\n\n \/\/ Illuminate the required digits for this segment\n digitalWrite(segmentPins[segmentNum], segmentOn);\n for (byte digitNum=0 ; digitNum < numDigits ; digitNum++){\n if (digitCodes[digitNum] & (1 << segmentNum)) { \/\/ Check a single bit\n digitalWrite(digitPins[digitNum], digitOn);\n }\n }\n\n \/\/Wait with lights on (to increase brightness)\n delayMicroseconds(ledOnTime); \n\n \/\/Turn all segments off\n for (byte digitNum=0 ; digitNum < numDigits ; digitNum++){\n digitalWrite(digitPins[digitNum], digitOff);\n }\n digitalWrite(segmentPins[segmentNum], segmentOff);\n }\n}\n\n\n\/\/ setBrightness\n\/******************************************************************************\/\n\nvoid SevSeg::setBrightness(int brightness){\n brightness = constrain(brightness, 0, 100);\n ledOnTime = map(brightness, 0, 100, 1, 2000);\n}\n\n\n\/\/ setNumber\n\/******************************************************************************\/\n\/\/ This function only receives the input and passes it to 'setNewNum'.\n\/\/ It is overloaded for all number data types, so that floats can be handled\n\/\/ correctly.\n\nvoid SevSeg::setNumber(long numToShow, byte decPlaces) \/\/long\n{\n setNewNum(numToShow, decPlaces);\n}\n\nvoid SevSeg::setNumber(unsigned long numToShow, byte decPlaces) \/\/unsigned long\n{\n setNewNum(numToShow, decPlaces);\n}\n\nvoid SevSeg::setNumber(int numToShow, byte decPlaces) \/\/int\n{\n setNewNum(numToShow, decPlaces);\n}\n\nvoid SevSeg::setNumber(unsigned int numToShow, byte decPlaces) \/\/unsigned int\n{\n setNewNum(numToShow, decPlaces);\n}\n\nvoid SevSeg::setNumber(char numToShow, byte decPlaces) \/\/char\n{\n setNewNum(numToShow, decPlaces);\n}\n\nvoid SevSeg::setNumber(byte numToShow, byte decPlaces) \/\/byte\n{\n setNewNum(numToShow, decPlaces);\n}\n\nvoid SevSeg::setNumber(float numToShow, byte decPlaces) \/\/float\n{\n numToShow = numToShow * powersOf10[decPlaces];\n \/\/ Modify the number so that it is rounded to an integer correctly\n numToShow += (numToShow >= 0) ? 0.5f : -0.5f;\n setNewNum(numToShow, decPlaces);\n}\n\n\n\/\/ setNewNum\n\/******************************************************************************\/\n\/\/ Changes the number that will be displayed.\n\nvoid SevSeg::setNewNum(long numToShow, byte decPlaces){\n byte digits[numDigits];\n findDigits(numToShow, decPlaces, digits);\n setDigitCodes(digits, decPlaces);\n}\n\n\n\/\/ findDigits\n\/******************************************************************************\/\n\/\/ Decides what each digit will display.\n\/\/ Enforces the upper and lower limits on the number to be displayed.\n\nvoid SevSeg::findDigits(long numToShow, byte decPlaces, byte digits[]) {\n static const int maxNum = powersOf10[numDigits] - 1;\n static const int minNum = -(powersOf10[numDigits - 1] - 1);\n\n \/\/ If the number is out of range, just display dashes\n if (numToShow > maxNum || numToShow < minNum) {\n for (byte digitNum = 0 ; digitNum < numDigits ; digitNum++){\n digits[digitNum] = DASH;\n }\n }\n else{\n byte digitNum = 0;\n\n \/\/ Convert all number to positive values\n if (numToShow < 0) {\n digits[0] = DASH;\n digitNum = 1; \/\/ Skip the first iteration\n numToShow = -numToShow;\n }\n\n \/\/ Find all digits for the base 10 representation, starting with the most\n \/\/ significant digit\n for ( ; digitNum < numDigits ; digitNum++){\n long factor = powersOf10[numDigits - 1 - digitNum];\n digits[digitNum] = numToShow \/ factor;\n numToShow -= digits[digitNum] * factor;\n }\n\n \/\/ Find unnnecessary leading zeros and set them to BLANK\n for (digitNum = 0 ; digitNum < (numDigits - 1 - decPlaces) ; digitNum++){\n if (digits[digitNum] == 0) {\n digits[digitNum] = BLANK;\n }\n \/\/ Exit once the first non-zero number is encountered\n else if (digits[digitNum] <= 9) {\n break;\n }\n }\n\n }\n}\n\n\n\/\/ setDigitCodes\n\/******************************************************************************\/\n\/\/ Sets the 'digitCodes' that are required to display the input numbers\n\nvoid SevSeg::setDigitCodes(byte digits[], byte decPlaces) {\n\n \/\/ The codes below indicate which segments must be illuminated to display\n \/\/ each number.\n static const byte digitCodeMap[] = {\n B00111111, \/\/ 0\n B00000110, \/\/ 1\n B01011011, \/\/ 2\n B01001111, \/\/ 3\n B01100110, \/\/ 4\n B01101101, \/\/ 5\n B01111101, \/\/ 6\n B00000111, \/\/ 7\n B01111111, \/\/ 8\n B01101111, \/\/ 9\n B00000000, \/\/ BLANK\n B01000000 }; \/\/ DASH\n\n \/\/ Set the digitCode for each digit in the display\n for (byte digitNum = 0 ; digitNum < numDigits ; digitNum++) {\n digitCodes[digitNum] = digitCodeMap[digits[digitNum]];\n \/\/ Set the decimal place segment\n if (digitNum == numDigits - 1 - decPlaces) {\n digitCodes[digitNum] |= B10000000;\n }\n }\n}\n\n\/\/\/ END \/\/\/\n<|endoftext|>"} {"text":"<commit_before>\/** \\file\n * Implements generally useful functions.\n *\/\n\n#include <type_traits> \/* std::underlying_type *\/\n#include <string>\n\n#include <cstdio> \/* snprintf() *\/\n\n#ifndef _POWERDXX_UTILITY_HPP_\n#define _POWERDXX_UTILITY_HPP_\n\n\/**\n * A collection of generally useful functions.\n *\/\nnamespace utility {\n\n\/**\n * Like sizeof(), but it returns the number of elements an array consists\n * of instead of the number of bytes.\n *\n * @tparam T,Count\n *\tThe type and number of array elements\n * @return\n *\tThe number of array entries\n *\/\ntemplate <typename T, size_t Count>\nconstexpr size_t countof(T (&)[Count]) { return Count; }\n\n\/**\n * Contains literals.\n *\/\nnamespace literals {\n\n\/**\n * A string literal operator equivalent to the `operator \"\" s` literal\n * provided by C++14 in \\<string\\>.\n *\n * @param op\n *\tThe raw string to turn into an std::string object\n * @param size\n *\tThe size of the raw string\n * @return\n *\tAn std::string instance\n *\/\ninline std::string operator \"\" _s(char const * const op, size_t const size) {\n\treturn {op, size};\n}\n\n} \/* namespace literals *\/\n\n\/**\n * This is a safeguard against accidentally using sprintf().\n *\n * Using it triggers a static_assert(), preventing compilation.\n *\n * @tparam Args\n *\tCatch all arguments\n *\/\ntemplate <typename... Args>\ninline void sprintf(Args...) {\n\t\/* Assert depends on Args so it can only be determined if\n\t * the function is actually instantiated. *\/\n\tstatic_assert(sizeof...(Args) && false,\n\t \"Use of sprintf() is unsafe, use sprintf_safe() instead\");\n}\n\n\/**\n * A wrapper around snprintf() that automatically pulls in the\n * destination buffer size.\n *\n * @tparam Size\n *\tThe destination buffer size\n * @tparam Args\n *\tThe types of the arguments\n * @param dst\n *\tA reference to the destination buffer\n * @param format\n *\tA printf style formatting string\n * @param args\n *\tThe printf arguments\n * @return\n *\tThe number of characters in the resulting string, regardless of the\n *\tavailable space\n *\/\ntemplate <size_t Size, typename... Args>\ninline int sprintf_safe(char (& dst)[Size], char const * const format,\n Args const... args) {\n\treturn snprintf(dst, Size, format, args...);\n}\n\n\/**\n * Casts an enum to its underlying value.\n *\n * @tparam ET,VT\n *\tThe enum and value type\n * @param op\n *\tThe operand to convert\n * @return\n *\tThe integer representation of the operand\n *\/\ntemplate <class ET, typename VT = typename std::underlying_type<ET>::type>\nconstexpr VT to_value(ET const op) {\n\treturn static_cast<VT>(op);\n}\n\n\/**\n * A formatting wrapper around string literals.\n *\n * Overloads operator (), which treats the string as a printf formatting\n * string, the arguments represent the data to format.\n *\n * In combination with the literal _fmt, it can be used like this:\n *\n * ~~~ c++\n * std::cout << \"%-15.15s %#018p\\n\"_fmt(\"Address:\", this);\n * ~~~\n *\n * @tparam BufSize\n *\tThe buffer size for formatting, resulting strings cannot\n *\tgrow beyond `BufSize - 1`\n *\/\ntemplate <size_t BufSize>\nclass Formatter {\n\tprivate:\n\t\/**\n\t * Pointer to the string literal.\n\t *\/\n\tchar const * const fmt;\n\n\tpublic:\n\t\/**\n\t * Construct from string literal.\n\t *\/\n\tconstexpr Formatter(char const * const fmt) : fmt{fmt} {}\n\n\t\/**\n\t * Returns a formatted string.\n\t *\n\t * @tparam ArgTs\n\t *\tVariadic argument types\n\t * @param args\n\t *\tVariadic arguments\n\t * @return\n\t *\tAn std::string formatted according to fmt\n\t *\/\n\ttemplate <typename... ArgTs>\n\tstd::string operator ()(ArgTs const &... args) const {\n\t\tchar buf[BufSize];\n\t\tauto count = sprintf_safe(buf, this->fmt, args...);\n\t\tif (count < 0) {\n\t\t\t\/* encoding error *\/\n\t\t\treturn {};\n\t\t} else if (static_cast<size_t>(count) >= BufSize) {\n\t\t\t\/* does not fit into buffer *\/\n\t\t\treturn {buf, BufSize - 1};\n\t\t}\n\t\treturn {buf, static_cast<size_t>(count)};\n\t}\n};\n\nnamespace literals {\n\/**\n * Literal to convert a string literal to a Formatter instance.\n *\n * @param fmt\n *\tA printf style format string\n * @param const\n *\tUnused\n * @return\n *\tA Formatter instance\n *\/\nconstexpr Formatter<16384> operator \"\" _fmt(char const * const fmt, size_t const) {\n\treturn {fmt};\n}\n} \/* namespace literals *\/\n\n\/**\n * A simple value container only allowing += and copy assignment.\n *\n * @tparam T\n *\tThe value type\n *\/\ntemplate <typename T>\nclass Sum {\n\tprivate:\n\t\/**\n\t * The sum of values accumulated.\n\t *\/\n\tT value;\n\n\tpublic:\n\t\/**\n\t * Construct from an initial value.\n\t *\n\t * @param value\n\t *\tThe initial value\n\t *\/\n\texplicit constexpr Sum(T const & value) : value{value} {}\n\n\t\/**\n\t * Default construct.\n\t *\/\n\tconstexpr Sum() : Sum{0} {}\n\n\t\/**\n\t * Returns the current sum of values.\n\t *\n\t * @return\n\t *\tThe sum of values by const reference\n\t *\/\n\tconstexpr operator T const &() const {\n\t\treturn this->value;\n\t}\n\n\t\/**\n\t * Add a value to the sum.\n\t *\n\t * @param value\n\t *\tThe value to add to the current sum\n\t * @return\n\t *\tA self reference\n\t *\/\n\tconstexpr Sum & operator +=(T const & value) {\n\t\tthis->value += value;\n\t\treturn *this;\n\t}\n};\n\n} \/* namespace utility *\/\n\n#endif \/* _POWERDXX_UTILITY_HPP_ *\/\n<commit_msg>Remove dummy parameter documentation<commit_after>\/** \\file\n * Implements generally useful functions.\n *\/\n\n#include <type_traits> \/* std::underlying_type *\/\n#include <string>\n\n#include <cstdio> \/* snprintf() *\/\n\n#ifndef _POWERDXX_UTILITY_HPP_\n#define _POWERDXX_UTILITY_HPP_\n\n\/**\n * A collection of generally useful functions.\n *\/\nnamespace utility {\n\n\/**\n * Like sizeof(), but it returns the number of elements an array consists\n * of instead of the number of bytes.\n *\n * @tparam T,Count\n *\tThe type and number of array elements\n * @return\n *\tThe number of array entries\n *\/\ntemplate <typename T, size_t Count>\nconstexpr size_t countof(T (&)[Count]) { return Count; }\n\n\/**\n * Contains literals.\n *\/\nnamespace literals {\n\n\/**\n * A string literal operator equivalent to the `operator \"\" s` literal\n * provided by C++14 in \\<string\\>.\n *\n * @param op\n *\tThe raw string to turn into an std::string object\n * @param size\n *\tThe size of the raw string\n * @return\n *\tAn std::string instance\n *\/\ninline std::string operator \"\" _s(char const * const op, size_t const size) {\n\treturn {op, size};\n}\n\n} \/* namespace literals *\/\n\n\/**\n * This is a safeguard against accidentally using sprintf().\n *\n * Using it triggers a static_assert(), preventing compilation.\n *\n * @tparam Args\n *\tCatch all arguments\n *\/\ntemplate <typename... Args>\ninline void sprintf(Args...) {\n\t\/* Assert depends on Args so it can only be determined if\n\t * the function is actually instantiated. *\/\n\tstatic_assert(sizeof...(Args) && false,\n\t \"Use of sprintf() is unsafe, use sprintf_safe() instead\");\n}\n\n\/**\n * A wrapper around snprintf() that automatically pulls in the\n * destination buffer size.\n *\n * @tparam Size\n *\tThe destination buffer size\n * @tparam Args\n *\tThe types of the arguments\n * @param dst\n *\tA reference to the destination buffer\n * @param format\n *\tA printf style formatting string\n * @param args\n *\tThe printf arguments\n * @return\n *\tThe number of characters in the resulting string, regardless of the\n *\tavailable space\n *\/\ntemplate <size_t Size, typename... Args>\ninline int sprintf_safe(char (& dst)[Size], char const * const format,\n Args const... args) {\n\treturn snprintf(dst, Size, format, args...);\n}\n\n\/**\n * Casts an enum to its underlying value.\n *\n * @tparam ET,VT\n *\tThe enum and value type\n * @param op\n *\tThe operand to convert\n * @return\n *\tThe integer representation of the operand\n *\/\ntemplate <class ET, typename VT = typename std::underlying_type<ET>::type>\nconstexpr VT to_value(ET const op) {\n\treturn static_cast<VT>(op);\n}\n\n\/**\n * A formatting wrapper around string literals.\n *\n * Overloads operator (), which treats the string as a printf formatting\n * string, the arguments represent the data to format.\n *\n * In combination with the literal _fmt, it can be used like this:\n *\n * ~~~ c++\n * std::cout << \"%-15.15s %#018p\\n\"_fmt(\"Address:\", this);\n * ~~~\n *\n * @tparam BufSize\n *\tThe buffer size for formatting, resulting strings cannot\n *\tgrow beyond `BufSize - 1`\n *\/\ntemplate <size_t BufSize>\nclass Formatter {\n\tprivate:\n\t\/**\n\t * Pointer to the string literal.\n\t *\/\n\tchar const * const fmt;\n\n\tpublic:\n\t\/**\n\t * Construct from string literal.\n\t *\/\n\tconstexpr Formatter(char const * const fmt) : fmt{fmt} {}\n\n\t\/**\n\t * Returns a formatted string.\n\t *\n\t * @tparam ArgTs\n\t *\tVariadic argument types\n\t * @param args\n\t *\tVariadic arguments\n\t * @return\n\t *\tAn std::string formatted according to fmt\n\t *\/\n\ttemplate <typename... ArgTs>\n\tstd::string operator ()(ArgTs const &... args) const {\n\t\tchar buf[BufSize];\n\t\tauto count = sprintf_safe(buf, this->fmt, args...);\n\t\tif (count < 0) {\n\t\t\t\/* encoding error *\/\n\t\t\treturn {};\n\t\t} else if (static_cast<size_t>(count) >= BufSize) {\n\t\t\t\/* does not fit into buffer *\/\n\t\t\treturn {buf, BufSize - 1};\n\t\t}\n\t\treturn {buf, static_cast<size_t>(count)};\n\t}\n};\n\nnamespace literals {\n\/**\n * Literal to convert a string literal to a Formatter instance.\n *\n * @param fmt\n *\tA printf style format string\n * @return\n *\tA Formatter instance\n *\/\nconstexpr Formatter<16384> operator \"\" _fmt(char const * const fmt, size_t const) {\n\treturn {fmt};\n}\n} \/* namespace literals *\/\n\n\/**\n * A simple value container only allowing += and copy assignment.\n *\n * @tparam T\n *\tThe value type\n *\/\ntemplate <typename T>\nclass Sum {\n\tprivate:\n\t\/**\n\t * The sum of values accumulated.\n\t *\/\n\tT value;\n\n\tpublic:\n\t\/**\n\t * Construct from an initial value.\n\t *\n\t * @param value\n\t *\tThe initial value\n\t *\/\n\texplicit constexpr Sum(T const & value) : value{value} {}\n\n\t\/**\n\t * Default construct.\n\t *\/\n\tconstexpr Sum() : Sum{0} {}\n\n\t\/**\n\t * Returns the current sum of values.\n\t *\n\t * @return\n\t *\tThe sum of values by const reference\n\t *\/\n\tconstexpr operator T const &() const {\n\t\treturn this->value;\n\t}\n\n\t\/**\n\t * Add a value to the sum.\n\t *\n\t * @param value\n\t *\tThe value to add to the current sum\n\t * @return\n\t *\tA self reference\n\t *\/\n\tconstexpr Sum & operator +=(T const & value) {\n\t\tthis->value += value;\n\t\treturn *this;\n\t}\n};\n\n} \/* namespace utility *\/\n\n#endif \/* _POWERDXX_UTILITY_HPP_ *\/\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Funambol is a mobile platform developed by Funambol, Inc. \n * Copyright (C) 2003 - 2007 Funambol, Inc.\n * \n * This program is free software; you can redistribute it and\/or modify it under\n * the terms of the GNU Affero General Public License version 3 as published by\n * the Free Software Foundation with the addition of the following permission \n * added to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED\n * WORK IN WHICH THE COPYRIGHT IS OWNED BY FUNAMBOL, FUNAMBOL DISCLAIMS THE \n * WARRANTY OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.\n * \n * This program is distributed in the hope that it will be useful, but WITHOUT\n * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more\n * details.\n * \n * You should have received a copy of the GNU Affero General Public License \n * along with this program; if not, see http:\/\/www.gnu.org\/licenses or write to\n * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,\n * MA 02110-1301 USA.\n * \n * You can contact Funambol, Inc. headquarters at 643 Bair Island Road, Suite \n * 305, Redwood City, CA 94063, USA, or at email address info@funambol.com.\n * \n * The interactive user interfaces in modified source and object code versions\n * of this program must display Appropriate Legal Notices, as required under\n * Section 5 of the GNU Affero General Public License version 3.\n * \n * In accordance with Section 7(b) of the GNU Affero General Public License\n * version 3, these Appropriate Legal Notices must retain the display of the\n * \"Powered by Funambol\" logo. If the display of the logo is not reasonably \n * feasible for technical reasons, the Appropriate Legal Notices must display\n * the words \"Powered by Funambol\".\n *\/\n\n#include \"base\/util\/PropertyFile.h\"\n#include \"base\/globalsdef.h\"\n\n#define REMOVED \"__#REM#O#VED#__\"\n\nUSE_NAMESPACE\n\nStringBuffer escapeString(const char* val) {\n StringBuffer s(val);\n s.replaceAll(\":\", \"\\\\:\");\n return s;\n}\n\nStringBuffer unescapeString(const char* val) {\n StringBuffer s(val);\n s.replaceAll(\"\\\\:\", \":\");\n return s;\n}\n\nstatic bool existsFile(const char* fullname) {\n bool found = false;\n FILE* f = fopen(fullname, \"r\");\n if (f) {\n found = true;\n fclose(f);\n }\n return found;\n}\n\nstatic bool removeFile(const char* fullname) {\n char* p;\n\tint len;\n bool ret = false;\n \n p = strrchr((char*)fullname, '\/');\n\n if (!p) {\n \/\/ the file is in the current directory\n ret = removeFileInDir(\".\", fullname); \n } else {\n\t len = p-fullname; \n StringBuffer dir(fullname, len);\t \n\t p++; len=strlen(fullname)-len;\n StringBuffer filename(p, len);\n ret = removeFileInDir(dir, filename);\n } \t\n return ret;\n}\n\n\nint PropertyFile::read() {\n \n char line[512];\n size_t found = 0;\n FILE* f;\n f = fopen(node, \"r\");\n if (!f) {\n LOG.debug(\"PropertyFile: the file '%s' doesn't exist. Try the journal file. '%s'\", node.c_str()); \n } else {\n while(fgets(line, 511, f) != NULL) {\n StringBuffer s(line);\n StringBuffer key;\n StringBuffer value;\n\n if (separateKeyValue(s, key, value)) {\n KeyValuePair toInsert(key, value);\n data.add(toInsert);\n } \n } \n fclose(f); \n }\n \/\/ check if there is the journal file and if any, set every value in memory. After that\n \/\/ empty the journal\n f = fopen(nodeJour, \"r\");\n if (!f) {\n \/\/ LOG.debug(\"PropertyFile: there is no journal file: '%s'\", nodeJour.c_str()); \n } else {\n while(fgets(line, 511, f) != NULL) {\n StringBuffer s(line);\n StringBuffer key;\n StringBuffer value;\n if (separateKeyValue(s, key, value)) {\n if (value == REMOVED) {\n ArrayListKeyValueStore::removeProperty(key);\n } else {\n ArrayListKeyValueStore::setPropertyValue(key, value);\n }\n } \n } \n fclose(f); \n }\n return 0;\n}\n\nint PropertyFile::close() {\n\n FILE* file;\n file = fopen(node, \"w\");\n int ret = 0; \n if (file) {\n KeyValuePair* curr = NULL; \n for (curr = (KeyValuePair*)data.front(); curr;\n curr = (KeyValuePair*)data.next() ) {\n \n fprintf(file, \"%s:%s\\n\", escapeString(curr->getKey()).c_str(), escapeString(curr->getValue()).c_str()); \n } \n fclose(file); \n \n \/\/ reset the content of the journal \n if (existsFile(nodeJour) && !removeFile(nodeJour)) {\n LOG.error(\"There are problem in removing journal file\");\n }\n \n ret = 0;\n\n } else {\n LOG.error(\"PropertyFile: it is not possible to save the file: '%s'\", node.c_str());\n ret = -1;\n }\n return ret;\n}\n\nint PropertyFile::setPropertyValue(const char *prop, const char *value) {\n \n int ret = ArrayListKeyValueStore::setPropertyValue(prop, value);\n if (ret) {\n return ret;\n }\n\n FILE* file = fopen(nodeJour, \"a+\"); \n if (file) {\n fprintf(file, \"%s:%s\\n\", escapeString(prop).c_str(), escapeString(value).c_str());\n fclose(file);\n } else { \n LOG.error(\"PropertyFile setProperty: it is not possible to save the journal file: '%s'\", node.c_str());\n ret = -1;\n }\n\n return ret;\n\n}\n\nint PropertyFile::removeProperty(const char *prop) {\n \n int ret = 0;\n\n FILE* file = fopen(nodeJour, \"a+\"); \n if (file) {\n fprintf(file, \"%s:%s\\n\", escapeString(prop).c_str(), escapeString(REMOVED).c_str());\n fclose(file);\n } else { \n LOG.error(\"PropertyFile removeProperty: it is not possible to save the journal file: '%s'\", node.c_str()); \n }\n\n ret = ArrayListKeyValueStore::removeProperty(prop);\n if (ret) {\n LOG.debug(\"PropertyFile: it is not possible to remove from the ArrayList\");\n }\n\n return ret;\n\n}\n\nint PropertyFile::removeAllProperties() {\n \n int ret = ArrayListKeyValueStore::removeAllProperties();\n if (ret) {\n return ret;\n }\n \/\/ reset the content \n if (existsFile(node) && !removeFile(node)) {\n LOG.error(\"There are problem in removing the file %s\", node);\n } \n return ret;\n}\n\n\nbool PropertyFile::separateKeyValue(StringBuffer& s, StringBuffer& key, StringBuffer& value) {\n bool ret = false;\n size_t found = 0; \n \n for (unsigned int i = 0; i < s.length(); i++) {\n if (((found = s.find(\":\", found + 1)) != StringBuffer::npos) && (found > 1 && s.c_str()[found-1] != '\\\\')) {\n\n key = unescapeString(s.substr(0, found));\n value = unescapeString(s.substr(found + 1, (s.length() - (found + 2)))); \/\/ it remove the \\n at the end \n \n ret = true;\n break;\n }\n }\n \n return ret;\n}<commit_msg>Warning removed<commit_after>\/*\n * Funambol is a mobile platform developed by Funambol, Inc. \n * Copyright (C) 2003 - 2007 Funambol, Inc.\n * \n * This program is free software; you can redistribute it and\/or modify it under\n * the terms of the GNU Affero General Public License version 3 as published by\n * the Free Software Foundation with the addition of the following permission \n * added to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED\n * WORK IN WHICH THE COPYRIGHT IS OWNED BY FUNAMBOL, FUNAMBOL DISCLAIMS THE \n * WARRANTY OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.\n * \n * This program is distributed in the hope that it will be useful, but WITHOUT\n * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more\n * details.\n * \n * You should have received a copy of the GNU Affero General Public License \n * along with this program; if not, see http:\/\/www.gnu.org\/licenses or write to\n * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,\n * MA 02110-1301 USA.\n * \n * You can contact Funambol, Inc. headquarters at 643 Bair Island Road, Suite \n * 305, Redwood City, CA 94063, USA, or at email address info@funambol.com.\n * \n * The interactive user interfaces in modified source and object code versions\n * of this program must display Appropriate Legal Notices, as required under\n * Section 5 of the GNU Affero General Public License version 3.\n * \n * In accordance with Section 7(b) of the GNU Affero General Public License\n * version 3, these Appropriate Legal Notices must retain the display of the\n * \"Powered by Funambol\" logo. If the display of the logo is not reasonably \n * feasible for technical reasons, the Appropriate Legal Notices must display\n * the words \"Powered by Funambol\".\n *\/\n\n#include \"base\/util\/PropertyFile.h\"\n#include \"base\/globalsdef.h\"\n\n#define REMOVED \"__#REM#O#VED#__\"\n\nUSE_NAMESPACE\n\nStringBuffer escapeString(const char* val) {\n StringBuffer s(val);\n s.replaceAll(\":\", \"\\\\:\");\n return s;\n}\n\nStringBuffer unescapeString(const char* val) {\n StringBuffer s(val);\n s.replaceAll(\"\\\\:\", \":\");\n return s;\n}\n\nstatic bool existsFile(const char* fullname) {\n bool found = false;\n FILE* f = fopen(fullname, \"r\");\n if (f) {\n found = true;\n fclose(f);\n }\n return found;\n}\n\nstatic bool removeFile(const char* fullname) {\n char* p;\n\tint len;\n bool ret = false;\n \n p = strrchr((char*)fullname, '\/');\n\n if (!p) {\n \/\/ the file is in the current directory\n ret = removeFileInDir(\".\", fullname); \n } else {\n\t len = p-fullname; \n StringBuffer dir(fullname, len);\t \n\t p++; len=strlen(fullname)-len;\n StringBuffer filename(p, len);\n ret = removeFileInDir(dir, filename);\n } \t\n return ret;\n}\n\n\nint PropertyFile::read() {\n \n char line[512];\n size_t found = 0;\n FILE* f;\n f = fopen(node, \"r\");\n if (!f) {\n LOG.debug(\"PropertyFile: the file '%s' doesn't exist. Try the journal file. '%s'\", node.c_str()); \n } else {\n while(fgets(line, 511, f) != NULL) {\n StringBuffer s(line);\n StringBuffer key;\n StringBuffer value;\n\n if (separateKeyValue(s, key, value)) {\n KeyValuePair toInsert(key, value);\n data.add(toInsert);\n } \n } \n fclose(f); \n }\n \/\/ check if there is the journal file and if any, set every value in memory. After that\n \/\/ empty the journal\n f = fopen(nodeJour, \"r\");\n if (!f) {\n \/\/ LOG.debug(\"PropertyFile: there is no journal file: '%s'\", nodeJour.c_str()); \n } else {\n while(fgets(line, 511, f) != NULL) {\n StringBuffer s(line);\n StringBuffer key;\n StringBuffer value;\n if (separateKeyValue(s, key, value)) {\n if (value == REMOVED) {\n ArrayListKeyValueStore::removeProperty(key);\n } else {\n ArrayListKeyValueStore::setPropertyValue(key, value);\n }\n } \n } \n fclose(f); \n }\n return 0;\n}\n\nint PropertyFile::close() {\n\n FILE* file;\n file = fopen(node, \"w\");\n int ret = 0; \n if (file) {\n KeyValuePair* curr = NULL; \n for (curr = (KeyValuePair*)data.front(); curr;\n curr = (KeyValuePair*)data.next() ) {\n \n fprintf(file, \"%s:%s\\n\", escapeString(curr->getKey()).c_str(), escapeString(curr->getValue()).c_str()); \n } \n fclose(file); \n \n \/\/ reset the content of the journal \n if (existsFile(nodeJour) && !removeFile(nodeJour)) {\n LOG.error(\"There are problem in removing journal file\");\n }\n \n ret = 0;\n\n } else {\n LOG.error(\"PropertyFile: it is not possible to save the file: '%s'\", node.c_str());\n ret = -1;\n }\n return ret;\n}\n\nint PropertyFile::setPropertyValue(const char *prop, const char *value) {\n \n int ret = ArrayListKeyValueStore::setPropertyValue(prop, value);\n if (ret) {\n return ret;\n }\n\n FILE* file = fopen(nodeJour, \"a+\"); \n if (file) {\n fprintf(file, \"%s:%s\\n\", escapeString(prop).c_str(), escapeString(value).c_str());\n fclose(file);\n } else { \n LOG.error(\"PropertyFile setProperty: it is not possible to save the journal file: '%s'\", node.c_str());\n ret = -1;\n }\n\n return ret;\n\n}\n\nint PropertyFile::removeProperty(const char *prop) {\n \n int ret = 0;\n\n FILE* file = fopen(nodeJour, \"a+\"); \n if (file) {\n fprintf(file, \"%s:%s\\n\", escapeString(prop).c_str(), escapeString(REMOVED).c_str());\n fclose(file);\n } else { \n LOG.error(\"PropertyFile removeProperty: it is not possible to save the journal file: '%s'\", node.c_str()); \n }\n\n ret = ArrayListKeyValueStore::removeProperty(prop);\n if (ret) {\n LOG.debug(\"PropertyFile: it is not possible to remove from the ArrayList\");\n }\n\n return ret;\n\n}\n\nint PropertyFile::removeAllProperties() {\n \n int ret = ArrayListKeyValueStore::removeAllProperties();\n if (ret) {\n return ret;\n }\n \/\/ reset the content \n if (existsFile(node) && !removeFile(node)) {\n LOG.error(\"There are problem in removing the file %s\", node.c_str());\n } \n return ret;\n}\n\n\nbool PropertyFile::separateKeyValue(StringBuffer& s, StringBuffer& key, StringBuffer& value) {\n bool ret = false;\n size_t found = 0; \n \n for (unsigned int i = 0; i < s.length(); i++) {\n if (((found = s.find(\":\", found + 1)) != StringBuffer::npos) && (found > 1 && s.c_str()[found-1] != '\\\\')) {\n\n key = unescapeString(s.substr(0, found));\n value = unescapeString(s.substr(found + 1, (s.length() - (found + 2)))); \/\/ it remove the \\n at the end \n \n ret = true;\n break;\n }\n }\n \n return ret;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/* This file is part of the KDE project\n Copyright (C) 2008 Matthias Kretz <kretz@kde.org>\n\n This program is free software; you can redistribute it and\/or\n modify it under the terms of the GNU Library General Public\n License as published by the Free Software Foundation; either\n version 2 of the License, or (at your option) version 3.\n\n This library is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n Library General Public License for more details.\n\n You should have received a copy of the GNU Library General Public License\n along with this library; see the file COPYING.LIB. If not, write to\n the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,\n Boston, MA 02110-1301, USA.\n\n*\/\n\n#include <QtCore\/QCoreApplication>\n#include <QtCore\/QtDebug>\n#include <QtCore\/QMutableListIterator>\n#include <QtCore\/QList>\n#include \"..\/qsettingsgroup_p.h\"\n#include <kcomponentdata.h>\n#include <kconfig.h>\n#include <kconfiggroup.h>\n\nusing Phonon::QSettingsGroup;\n\nQ_DECLARE_METATYPE(QList<int>)\n\nint main(int argc, char **argv)\n{\n QCoreApplication app(argc, argv);\n KComponentData cData(\"phonon device preference update\");\n\n KConfig kconfig(\"phonondevicesrc\", KConfig::NoGlobals);\n KConfigGroup globalGroup(&kconfig, \"Globals\");\n int newIndexForZero = 0;\n\n foreach (const QString &group, kconfig.groupList()) {\n KConfigGroup configGroup(&kconfig, group);\n int index = configGroup.readEntry(\"index\", -1);\n if (index == 0) {\n newIndexForZero = globalGroup.readEntry(\"nextIndex\", 0);\n configGroup.writeEntry(\"index\", newIndexForZero);\n globalGroup.writeEntry(\"nextIndex\", newIndexForZero + 1);\n break;\n }\n }\n\n qDebug() << newIndexForZero;\n qRegisterMetaTypeStreamOperators<QList<int> >(\"QList<int>\");\n\n QSettings qconfig(QLatin1String(\"kde.org\"), QLatin1String(\"libphonon\"));\n QSettingsGroup outputGroup(&qconfig, QLatin1String(\"AudioOutputDevice\"));\n for (int i = -1; i < 10; ++i) {\n const QString oldKey = QLatin1String(\"Category\") + QString::number(i);\n const QString newKey = QLatin1String(\"Category_\") + QString::number(i);\n qDebug() << oldKey << newKey;\n if (outputGroup.hasKey(oldKey) && !outputGroup.hasKey(newKey)) {\n QList<int> deviceIndexes = outputGroup.value(oldKey, QList<int>());\n QMutableListIterator<int> index(deviceIndexes);\n while (index.hasNext()) {\n index.next();\n if (index.value() < 10000 && index.value() >= 0) {\n qDebug() << \"changing index\" << index.value();\n if (index.value() == 0) {\n Q_ASSERT(newIndexForZero);\n index.setValue(-newIndexForZero);\n } else {\n index.setValue(-index.value());\n }\n }\n }\n outputGroup.setValue(newKey, deviceIndexes);\n outputGroup.removeEntry(oldKey);\n }\n }\n\n return 0;\n}\n<commit_msg>remove debug output<commit_after>\/* This file is part of the KDE project\n Copyright (C) 2008 Matthias Kretz <kretz@kde.org>\n\n This program is free software; you can redistribute it and\/or\n modify it under the terms of the GNU Library General Public\n License as published by the Free Software Foundation; either\n version 2 of the License, or (at your option) version 3.\n\n This library is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n Library General Public License for more details.\n\n You should have received a copy of the GNU Library General Public License\n along with this library; see the file COPYING.LIB. If not, write to\n the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,\n Boston, MA 02110-1301, USA.\n\n*\/\n\n#include <QtCore\/QCoreApplication>\n#include <QtCore\/QMutableListIterator>\n#include <QtCore\/QList>\n#include \"..\/qsettingsgroup_p.h\"\n#include <kcomponentdata.h>\n#include <kconfig.h>\n#include <kconfiggroup.h>\n\nusing Phonon::QSettingsGroup;\n\nQ_DECLARE_METATYPE(QList<int>)\n\nint main(int argc, char **argv)\n{\n QCoreApplication app(argc, argv);\n KComponentData cData(\"phonon device preference update\");\n\n KConfig kconfig(\"phonondevicesrc\", KConfig::NoGlobals);\n KConfigGroup globalGroup(&kconfig, \"Globals\");\n int newIndexForZero = 0;\n\n foreach (const QString &group, kconfig.groupList()) {\n KConfigGroup configGroup(&kconfig, group);\n int index = configGroup.readEntry(\"index\", -1);\n if (index == 0) {\n newIndexForZero = globalGroup.readEntry(\"nextIndex\", 0);\n configGroup.writeEntry(\"index\", newIndexForZero);\n globalGroup.writeEntry(\"nextIndex\", newIndexForZero + 1);\n break;\n }\n }\n\n qRegisterMetaTypeStreamOperators<QList<int> >(\"QList<int>\");\n\n QSettings qconfig(QLatin1String(\"kde.org\"), QLatin1String(\"libphonon\"));\n QSettingsGroup outputGroup(&qconfig, QLatin1String(\"AudioOutputDevice\"));\n for (int i = -1; i < 10; ++i) {\n const QString oldKey = QLatin1String(\"Category\") + QString::number(i);\n const QString newKey = QLatin1String(\"Category_\") + QString::number(i);\n if (outputGroup.hasKey(oldKey) && !outputGroup.hasKey(newKey)) {\n QList<int> deviceIndexes = outputGroup.value(oldKey, QList<int>());\n QMutableListIterator<int> index(deviceIndexes);\n while (index.hasNext()) {\n index.next();\n if (index.value() < 10000 && index.value() >= 0) {\n if (index.value() == 0) {\n Q_ASSERT(newIndexForZero);\n index.setValue(-newIndexForZero);\n } else {\n index.setValue(-index.value());\n }\n }\n }\n outputGroup.setValue(newKey, deviceIndexes);\n outputGroup.removeEntry(oldKey);\n }\n }\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Funambol is a mobile platform developed by Funambol, Inc. \n * Copyright (C) 2003 - 2007 Funambol, Inc.\n * \n * This program is free software; you can redistribute it and\/or modify it under\n * the terms of the GNU Affero General Public License version 3 as published by\n * the Free Software Foundation with the addition of the following permission \n * added to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED\n * WORK IN WHICH THE COPYRIGHT IS OWNED BY FUNAMBOL, FUNAMBOL DISCLAIMS THE \n * WARRANTY OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.\n * \n * This program is distributed in the hope that it will be useful, but WITHOUT\n * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more\n * details.\n * \n * You should have received a copy of the GNU Affero General Public License \n * along with this program; if not, see http:\/\/www.gnu.org\/licenses or write to\n * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,\n * MA 02110-1301 USA.\n * \n * You can contact Funambol, Inc. headquarters at 643 Bair Island Road, Suite \n * 305, Redwood City, CA 94063, USA, or at email address info@funambol.com.\n * \n * The interactive user interfaces in modified source and object code versions\n * of this program must display Appropriate Legal Notices, as required under\n * Section 5 of the GNU Affero General Public License version 3.\n * \n * In accordance with Section 7(b) of the GNU Affero General Public License\n * version 3, these Appropriate Legal Notices must retain the display of the\n * \"Powered by Funambol\" logo. If the display of the logo is not reasonably \n * feasible for technical reasons, the Appropriate Legal Notices must display\n * the words \"Powered by Funambol\".\n *\/\n\n#include \"spds\/SyncSource.h\"\n#include \"base\/Log.h\"\n#include \"client\/SyncClient.h\"\n#include \"spds\/spdsutils.h\"\n#include \"spds\/SyncSourceConfig.h\"\n#include \"client\/CacheSyncSource.h\"\n#include \"base\/util\/KeyValuePair.h\"\n#include \"base\/util\/PropertyFile.h\"\n#include \"base\/util\/ArrayListEnumeration.h\"\n\nBEGIN_NAMESPACE\n\nCacheSyncSource::CacheSyncSource(const WCHAR* sourceName, AbstractSyncSourceConfig *sc, KeyValueStore* cache) :\n SyncSource(sourceName, sc) {\n \n allKeys = NULL;\n newKeys = NULL; \n updatedKeys = NULL; \n deletedKeys = NULL; \n\n if (cache) {\n this->cache = cache;\n } else {\n \/\/ get the default directory of the \n StringBuffer completeName = getCacheDirectory();\n completeName += \"\/\";\n completeName += CACHE_FILE_NAME; \n LOG.debug(\"PropertyFile: path to the PropertyFile %s\", completeName.c_str());\n\n this->cache = new PropertyFile(completeName);\n }\n}\n\n\/**\n * Release dynamically allocated resources\n *\/\nCacheSyncSource::~CacheSyncSource() { \n\n if (newKeys) { delete newKeys; } \n if (updatedKeys) { delete updatedKeys; } \n if (deletedKeys) { delete deletedKeys; } \n if (allKeys) { delete allKeys; }\n if (cache) { delete cache; }\n}\n\n\/**\n* Fill a key value pair object and set into the partialModification array list.\n* This is used to set the changes in the cache or in the listener based sync source.\n* If there is an error this error is reported in the saving procedure and there\n* it is decided how procede\n*\/\nvoid CacheSyncSource::setItemStatus(const WCHAR* key, int status, const char* command) {\n \n KeyValuePair vp;\n switch (status) {\n \n case 200:\n case 201:\n case 418: \n {\n LOG.info(\"[%s], Received success status code from server for %s on item with key %s - code: %d\", getName(), command, key, status);\n char* k = toMultibyte(key); \n vp.setKey(k);\n StringBuffer v(k);\n vp.setValue(getItemSignature(v)); \n delete [] k;\n } \n break;\n case 500: \n default:\n LOG.info(\"[%s], Received failed status code from server for %s on item with key %s - code: %d\", getName(), command, key, status);\n \/\/ error. it doesn't update the cache\n break;\n }\n if (vp.getKey()) {\n updateInCache(vp, command);\n }\n\n}\n\n\/**\n* Get the signature of an item given the value and the size. \n* The signature could be a crc computation or a timestamp or whatever can identify uniquely the\n* content of an item. It is used by the implementation of the ItemHandler\n* and it need the getItemContent too. The default implementation uses a \n* crc computation of the value\n*\n* @param key the value on which signature must be calculated\n* @param size the size of the value\n*\/\n\nStringBuffer CacheSyncSource::getItemSignature(StringBuffer& key) {\n\n void* content = NULL;\n size_t size = 0;\n \n if (key.length() <= 0) {\n return NULL;\n }\n \n LOG.debug(\"[%s] Getting signature for item with key %s\", getName(), key.c_str());\n \n content = getItemContent(key, &size); \n StringBuffer s;\n s.sprintf(\"%ld\", calculateCRC(content, size));\n if (content) { delete [] (char*)content; content = NULL; } \n return s;\n}\n\n\n\nSyncItem* CacheSyncSource::fillSyncItem(StringBuffer* key) {\n \n SyncItem* syncItem = NULL; \n size_t size = 0;\n void* content = NULL;\n \n if (!key) {\n return NULL;\n }\n \n LOG.debug(\"[%s] Filling item with key %s\", getName(), key->c_str());\n \n content = getItemContent((*key), &size);\n \n WCHAR* wkey = toWideChar(key->c_str());\n syncItem = new SyncItem(wkey);\n syncItem->setData(content, size);\n \n if (wkey) { delete [] wkey; wkey = NULL; }\n if (content) { delete [] (char*)content; content = NULL; }\n\n return syncItem;\n\n}\n\n\/**\n * Return the first SyncItem of all.\n * It is used in case of slow sync and retrieve the entire \n * data source content.\n *\/\nSyncItem* CacheSyncSource::getFirstItem() {\n \n allKeys = getAllItemList(); \n return getNextItem();\n\n};\n\n \/**\n * Return the next SyncItem of all.\n * It is used in case of slow sync\n * and retrieve the entire data source content.\n *\/\nSyncItem* CacheSyncSource::getNextItem() {\n \n SyncItem* syncItem = NULL;\n if (allKeys && allKeys->hasMoreElement()) {\n StringBuffer* s = (StringBuffer*)allKeys->getNextElement(); \n syncItem = fillSyncItem(s);\n }\n if (!syncItem) {\n LOG.info(\"There are no more items to be exchanged. Return NULL\"); \n }\n return syncItem;\n\n}\n\/**\n * Return the first new SyncItem. It is used in case of fast sync\n * and retrieve the new data source content.\n *\/\nSyncItem* CacheSyncSource::getFirstNewItem() { \n fillItemModifications(); \n return getNextNewItem(); \n\n}\n\n\/**\n * Return the next SyncItem of new one. It is used in case of fast sync\n * and retrieve the new data source content.\n *\/\nSyncItem* CacheSyncSource::getNextNewItem() {\n \n SyncItem* syncItem = NULL;\n if (newKeys && newKeys->hasMoreElement()) {\n StringBuffer* s = (StringBuffer*)newKeys->getNextElement(); \n syncItem = fillSyncItem(s);\n }\n if (!syncItem) {\n LOG.info(\"There are no more new items to be exchanged. Return NULL\"); \n }\n return syncItem; \n}\n\n\/**\n * Return the first SyncItem of updated one. It is used in case of fast sync\n * and retrieve the new data source content.\n *\/\nSyncItem* CacheSyncSource::getFirstUpdatedItem() {\n \n return getNextUpdatedItem();\n}\n\n\nSyncItem* CacheSyncSource::getNextUpdatedItem() {\n\n SyncItem* syncItem = NULL;\n if (updatedKeys && updatedKeys->hasMoreElement()) {\n StringBuffer* s = (StringBuffer*)updatedKeys->getNextElement(); \n syncItem = fillSyncItem(s);\n }\n if (!syncItem) {\n LOG.info(\"There are no more updated items to be exchanged. Return NULL\"); \n } \n return syncItem; \n}\n\nSyncItem* CacheSyncSource::getFirstDeletedItem() {\n \n return getNextDeletedItem();\n}\n\n\n\/**\n * Return the next SyncItem of updated one. It is used in case of fast sync\n * and retrieve the new data source content.\n *\/\nSyncItem* CacheSyncSource::getNextDeletedItem() {\n \n SyncItem* syncItem = NULL;\n if (deletedKeys && deletedKeys->hasMoreElement()) {\n StringBuffer* s = (StringBuffer*)deletedKeys->getNextElement(); \n if (!s) {\n return NULL;\n }\n WCHAR* wkey = toWideChar(s->c_str());\n syncItem = new SyncItem(wkey); \n if (wkey) { delete [] wkey; wkey = NULL; } \n }\n if (!syncItem) {\n LOG.info(\"There are no more deleted items to be exchanged. Return NULL\"); \n } \n \n return syncItem;\n}\n\nint CacheSyncSource::endSync() { \n saveCache(); \n return 0;\n}\n\n\/**\n* The way to calculate the cache is the follow:\n* loop on the current element against an array list\n* that has the cache. It is the copy of the original cache.\n* When an current element is found in the cache, it is removed\n* from the cache copy. At the end the remained element\n* in the cache are the deleted ones.\n*\/\nbool CacheSyncSource::fillItemModifications() {\n \n \/\/ all the current items keys list\n Enumeration* items = (Enumeration*)getAllItemList();\n\n if (!items) {\n LOG.error(\"Error in fillItemModification\");\n return false;\n }\n\n \/\/ all the action are done on the copy so we can delete\n \/\/ the element found. The remained are the deleted by the user. \n Enumeration& e = cache->getProperties();\n ArrayList cacheCopy;\n while(e.hasMoreElement()) {\n cacheCopy.add(*e.getNextElement());\n }\n\n StringBuffer* key;\n KeyValuePair* kvp;\n\n ArrayListEnumeration *newitems = new ArrayListEnumeration(),\n *moditems = new ArrayListEnumeration(),\n *delitems = new ArrayListEnumeration();\n\n if (items) {\n while(items->hasMoreElement()) {\n key = (StringBuffer*)items->getNextElement();\n int size = cacheCopy.size();\n bool foundnew = true;\n\n for (int i = 0; i < size; i++) {\n kvp = (KeyValuePair*)(cacheCopy[i]);\n if (strcmp(kvp->getKey(), key->c_str()) == 0) {\n foundnew = false;\n \/\/ see if it is updated.\n StringBuffer sign = getItemSignature(*key);\n if (sign != kvp->getValue()) {\n \/\/ there is an update. if equal nothing to do...\n moditems->add(*key); \n }\n cacheCopy.removeElementAt(i);\n break;\n }\n }\n if (foundnew) {\n newitems->add(*key);\n }\n }\n }\n \n for(kvp=(KeyValuePair*)cacheCopy.front();kvp;kvp=(KeyValuePair*)cacheCopy.next()){\n delitems->add((StringBuffer&)kvp->getKey());\n }\n \n newKeys = newitems;\n updatedKeys = moditems; \n deletedKeys = delitems;\n \n delete items; \n return true;\n}\n\n\/**\n* Save the current status of the cache arrayList\n* \n*\/\nint CacheSyncSource::saveCache() {\n \n LOG.debug(\"[%s] Saving cache\", getName());\n \n int ret = cache->close();\n return ret;\n\n}\n\nint CacheSyncSource::updateInCache(KeyValuePair& k, const char* action) {\n\n if (strcmp(action, ADD ) == 0 ||\n strcmp(action, REPLACE) == 0) { \n cache->setPropertyValue(k.getKey(), k.getValue());\n } else if (strcmp(action, DEL) == 0) {\n cache->removeProperty(k.getKey());\n }\n return 0;\n}\n\nvoid CacheSyncSource::getKeyAndSignature(SyncItem& item, KeyValuePair& kvp) {\n \n char* t = toMultibyte(item.getKey());\n StringBuffer s(t);\n StringBuffer sign = getItemSignature(s);\n kvp.setKey(t);\n kvp.setValue(sign);\n delete [] t;\n \n}\n\nint CacheSyncSource::addItem(SyncItem& item) {\n int ret = insertItem(item);\n switch (ret) { \n case 200:\n case 201:\n case 418: {\n LOG.info(\"[%s] Successful add of item with key %s - code %d\", getName(), item.getKey(), ret);\n KeyValuePair k;\n getKeyAndSignature(item, k);\n insertInCache(k);\n }\n break;\n default:\n LOG.error(\"[%s] Failed add of item with key %s - code %d\", getName(), item.getKey(), ret);\n break;\n }\n return ret;\n}\n\n\nint CacheSyncSource::updateItem(SyncItem& item) {\n int ret = modifyItem(item);\n switch (ret) { \n case 200:\n case 201:\n case 418: {\n LOG.info(\"[%s] Successful update of item with key %s - code %d\", getName(), item.getKey(), ret);\n KeyValuePair k;\n getKeyAndSignature(item, k);\n updateInCache(k);\n }\n break;\n default:\n LOG.error(\"[%s] Failed update of item with key %s - code %d\", getName(), item.getKey(), ret);\n break;\n }\n return ret;\n}\n\nint CacheSyncSource::deleteItem(SyncItem& item) {\n int ret = removeItem(item);\n switch (ret) { \n case 200:\n case 201:\n case 418: {\n LOG.info(\"[%s] Successful delete of item with key %s - code %d\", getName(), item.getKey(), ret); \n char* t = toMultibyte(item.getKey());\n KeyValuePair k (t, \"\");\n removeFromCache(k);\n delete [] t;\n }\n break;\n default:\n LOG.error(\"[%s] Failed delete of item with key %s - code %d\", getName(), item.getKey(), ret);\n break;\n }\n \n return ret;\n} \n\nEND_NAMESPACE\n<commit_msg>clear the cache when a slow sync starts<commit_after>\/*\n * Funambol is a mobile platform developed by Funambol, Inc. \n * Copyright (C) 2003 - 2007 Funambol, Inc.\n * \n * This program is free software; you can redistribute it and\/or modify it under\n * the terms of the GNU Affero General Public License version 3 as published by\n * the Free Software Foundation with the addition of the following permission \n * added to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED\n * WORK IN WHICH THE COPYRIGHT IS OWNED BY FUNAMBOL, FUNAMBOL DISCLAIMS THE \n * WARRANTY OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.\n * \n * This program is distributed in the hope that it will be useful, but WITHOUT\n * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more\n * details.\n * \n * You should have received a copy of the GNU Affero General Public License \n * along with this program; if not, see http:\/\/www.gnu.org\/licenses or write to\n * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,\n * MA 02110-1301 USA.\n * \n * You can contact Funambol, Inc. headquarters at 643 Bair Island Road, Suite \n * 305, Redwood City, CA 94063, USA, or at email address info@funambol.com.\n * \n * The interactive user interfaces in modified source and object code versions\n * of this program must display Appropriate Legal Notices, as required under\n * Section 5 of the GNU Affero General Public License version 3.\n * \n * In accordance with Section 7(b) of the GNU Affero General Public License\n * version 3, these Appropriate Legal Notices must retain the display of the\n * \"Powered by Funambol\" logo. If the display of the logo is not reasonably \n * feasible for technical reasons, the Appropriate Legal Notices must display\n * the words \"Powered by Funambol\".\n *\/\n\n#include \"spds\/SyncSource.h\"\n#include \"base\/Log.h\"\n#include \"client\/SyncClient.h\"\n#include \"spds\/spdsutils.h\"\n#include \"spds\/SyncSourceConfig.h\"\n#include \"client\/CacheSyncSource.h\"\n#include \"base\/util\/KeyValuePair.h\"\n#include \"base\/util\/PropertyFile.h\"\n#include \"base\/util\/ArrayListEnumeration.h\"\n\nBEGIN_NAMESPACE\n\nCacheSyncSource::CacheSyncSource(const WCHAR* sourceName, AbstractSyncSourceConfig *sc, KeyValueStore* cache) :\n SyncSource(sourceName, sc) {\n \n allKeys = NULL;\n newKeys = NULL; \n updatedKeys = NULL; \n deletedKeys = NULL; \n\n if (cache) {\n this->cache = cache;\n } else {\n \/\/ get the default directory of the \n StringBuffer completeName = getCacheDirectory();\n completeName += \"\/\";\n completeName += CACHE_FILE_NAME; \n LOG.debug(\"PropertyFile: path to the PropertyFile %s\", completeName.c_str());\n\n this->cache = new PropertyFile(completeName);\n }\n}\n\n\/**\n * Release dynamically allocated resources\n *\/\nCacheSyncSource::~CacheSyncSource() { \n\n if (newKeys) { delete newKeys; } \n if (updatedKeys) { delete updatedKeys; } \n if (deletedKeys) { delete deletedKeys; } \n if (allKeys) { delete allKeys; }\n if (cache) { delete cache; }\n}\n\n\/**\n* Fill a key value pair object and set into the partialModification array list.\n* This is used to set the changes in the cache or in the listener based sync source.\n* If there is an error this error is reported in the saving procedure and there\n* it is decided how procede\n*\/\nvoid CacheSyncSource::setItemStatus(const WCHAR* key, int status, const char* command) {\n \n KeyValuePair vp;\n switch (status) {\n \n case 200:\n case 201:\n case 418: \n {\n LOG.info(\"[%s], Received success status code from server for %s on item with key %s - code: %d\", getName(), command, key, status);\n char* k = toMultibyte(key); \n vp.setKey(k);\n StringBuffer v(k);\n vp.setValue(getItemSignature(v)); \n delete [] k;\n } \n break;\n case 500: \n default:\n LOG.info(\"[%s], Received failed status code from server for %s on item with key %s - code: %d\", getName(), command, key, status);\n \/\/ error. it doesn't update the cache\n break;\n }\n if (vp.getKey()) {\n updateInCache(vp, command);\n }\n\n}\n\n\/**\n* Get the signature of an item given the value and the size. \n* The signature could be a crc computation or a timestamp or whatever can identify uniquely the\n* content of an item. It is used by the implementation of the ItemHandler\n* and it need the getItemContent too. The default implementation uses a \n* crc computation of the value\n*\n* @param key the value on which signature must be calculated\n* @param size the size of the value\n*\/\n\nStringBuffer CacheSyncSource::getItemSignature(StringBuffer& key) {\n\n void* content = NULL;\n size_t size = 0;\n \n if (key.length() <= 0) {\n return NULL;\n }\n \n LOG.debug(\"[%s] Getting signature for item with key %s\", getName(), key.c_str());\n \n content = getItemContent(key, &size); \n StringBuffer s;\n s.sprintf(\"%ld\", calculateCRC(content, size));\n if (content) { delete [] (char*)content; content = NULL; } \n return s;\n}\n\n\n\nSyncItem* CacheSyncSource::fillSyncItem(StringBuffer* key) {\n \n SyncItem* syncItem = NULL; \n size_t size = 0;\n void* content = NULL;\n \n if (!key) {\n return NULL;\n }\n \n LOG.debug(\"[%s] Filling item with key %s\", getName(), key->c_str());\n \n content = getItemContent((*key), &size);\n \n WCHAR* wkey = toWideChar(key->c_str());\n syncItem = new SyncItem(wkey);\n syncItem->setData(content, size);\n \n if (wkey) { delete [] wkey; wkey = NULL; }\n if (content) { delete [] (char*)content; content = NULL; }\n\n return syncItem;\n\n}\n\n\/**\n * Return the first SyncItem of all.\n * It is used in case of slow sync and retrieve the entire \n * data source content.\n *\/\nSyncItem* CacheSyncSource::getFirstItem() {\n \n \/\/ A slow sync is started -> clear the cache\n clearCache();\n\n allKeys = getAllItemList(); \n return getNextItem();\n\n};\n\n \/**\n * Return the next SyncItem of all.\n * It is used in case of slow sync\n * and retrieve the entire data source content.\n *\/\nSyncItem* CacheSyncSource::getNextItem() {\n \n SyncItem* syncItem = NULL;\n if (allKeys && allKeys->hasMoreElement()) {\n StringBuffer* s = (StringBuffer*)allKeys->getNextElement(); \n syncItem = fillSyncItem(s);\n }\n if (!syncItem) {\n LOG.info(\"There are no more items to be exchanged. Return NULL\"); \n }\n return syncItem;\n\n}\n\/**\n * Return the first new SyncItem. It is used in case of fast sync\n * and retrieve the new data source content.\n *\/\nSyncItem* CacheSyncSource::getFirstNewItem() { \n fillItemModifications(); \n return getNextNewItem(); \n\n}\n\n\/**\n * Return the next SyncItem of new one. It is used in case of fast sync\n * and retrieve the new data source content.\n *\/\nSyncItem* CacheSyncSource::getNextNewItem() {\n \n SyncItem* syncItem = NULL;\n if (newKeys && newKeys->hasMoreElement()) {\n StringBuffer* s = (StringBuffer*)newKeys->getNextElement(); \n syncItem = fillSyncItem(s);\n }\n if (!syncItem) {\n LOG.info(\"There are no more new items to be exchanged. Return NULL\"); \n }\n return syncItem; \n}\n\n\/**\n * Return the first SyncItem of updated one. It is used in case of fast sync\n * and retrieve the new data source content.\n *\/\nSyncItem* CacheSyncSource::getFirstUpdatedItem() {\n \n return getNextUpdatedItem();\n}\n\n\nSyncItem* CacheSyncSource::getNextUpdatedItem() {\n\n SyncItem* syncItem = NULL;\n if (updatedKeys && updatedKeys->hasMoreElement()) {\n StringBuffer* s = (StringBuffer*)updatedKeys->getNextElement(); \n syncItem = fillSyncItem(s);\n }\n if (!syncItem) {\n LOG.info(\"There are no more updated items to be exchanged. Return NULL\"); \n } \n return syncItem; \n}\n\nSyncItem* CacheSyncSource::getFirstDeletedItem() {\n \n return getNextDeletedItem();\n}\n\n\n\/**\n * Return the next SyncItem of updated one. It is used in case of fast sync\n * and retrieve the new data source content.\n *\/\nSyncItem* CacheSyncSource::getNextDeletedItem() {\n \n SyncItem* syncItem = NULL;\n if (deletedKeys && deletedKeys->hasMoreElement()) {\n StringBuffer* s = (StringBuffer*)deletedKeys->getNextElement(); \n if (!s) {\n return NULL;\n }\n WCHAR* wkey = toWideChar(s->c_str());\n syncItem = new SyncItem(wkey); \n if (wkey) { delete [] wkey; wkey = NULL; } \n }\n if (!syncItem) {\n LOG.info(\"There are no more deleted items to be exchanged. Return NULL\"); \n } \n \n return syncItem;\n}\n\nint CacheSyncSource::endSync() { \n saveCache(); \n return 0;\n}\n\n\/**\n* The way to calculate the cache is the follow:\n* loop on the current element against an array list\n* that has the cache. It is the copy of the original cache.\n* When an current element is found in the cache, it is removed\n* from the cache copy. At the end the remained element\n* in the cache are the deleted ones.\n*\/\nbool CacheSyncSource::fillItemModifications() {\n \n \/\/ all the current items keys list\n Enumeration* items = (Enumeration*)getAllItemList();\n\n if (!items) {\n LOG.error(\"Error in fillItemModification\");\n return false;\n }\n\n \/\/ all the action are done on the copy so we can delete\n \/\/ the element found. The remained are the deleted by the user. \n Enumeration& e = cache->getProperties();\n ArrayList cacheCopy;\n while(e.hasMoreElement()) {\n cacheCopy.add(*e.getNextElement());\n }\n\n StringBuffer* key;\n KeyValuePair* kvp;\n\n ArrayListEnumeration *newitems = new ArrayListEnumeration(),\n *moditems = new ArrayListEnumeration(),\n *delitems = new ArrayListEnumeration();\n\n if (items) {\n while(items->hasMoreElement()) {\n key = (StringBuffer*)items->getNextElement();\n int size = cacheCopy.size();\n bool foundnew = true;\n\n for (int i = 0; i < size; i++) {\n kvp = (KeyValuePair*)(cacheCopy[i]);\n if (strcmp(kvp->getKey(), key->c_str()) == 0) {\n foundnew = false;\n \/\/ see if it is updated.\n StringBuffer sign = getItemSignature(*key);\n if (sign != kvp->getValue()) {\n \/\/ there is an update. if equal nothing to do...\n moditems->add(*key); \n }\n cacheCopy.removeElementAt(i);\n break;\n }\n }\n if (foundnew) {\n newitems->add(*key);\n }\n }\n }\n \n for(kvp=(KeyValuePair*)cacheCopy.front();kvp;kvp=(KeyValuePair*)cacheCopy.next()){\n delitems->add((StringBuffer&)kvp->getKey());\n }\n \n newKeys = newitems;\n updatedKeys = moditems; \n deletedKeys = delitems;\n \n delete items; \n return true;\n}\n\n\/**\n* Save the current status of the cache arrayList\n* \n*\/\nint CacheSyncSource::saveCache() {\n \n LOG.debug(\"[%s] Saving cache\", getName());\n \n int ret = cache->close();\n return ret;\n\n}\n\nint CacheSyncSource::updateInCache(KeyValuePair& k, const char* action) {\n\n if (strcmp(action, ADD ) == 0 ||\n strcmp(action, REPLACE) == 0) { \n cache->setPropertyValue(k.getKey(), k.getValue());\n } else if (strcmp(action, DEL) == 0) {\n cache->removeProperty(k.getKey());\n }\n return 0;\n}\n\nvoid CacheSyncSource::getKeyAndSignature(SyncItem& item, KeyValuePair& kvp) {\n \n char* t = toMultibyte(item.getKey());\n StringBuffer s(t);\n StringBuffer sign = getItemSignature(s);\n kvp.setKey(t);\n kvp.setValue(sign);\n delete [] t;\n \n}\n\nint CacheSyncSource::addItem(SyncItem& item) {\n int ret = insertItem(item);\n switch (ret) { \n case 200:\n case 201:\n case 418: {\n LOG.info(\"[%s] Successful add of item with key %s - code %d\", getName(), item.getKey(), ret);\n KeyValuePair k;\n getKeyAndSignature(item, k);\n insertInCache(k);\n }\n break;\n default:\n LOG.error(\"[%s] Failed add of item with key %s - code %d\", getName(), item.getKey(), ret);\n break;\n }\n return ret;\n}\n\n\nint CacheSyncSource::updateItem(SyncItem& item) {\n int ret = modifyItem(item);\n switch (ret) { \n case 200:\n case 201:\n case 418: {\n LOG.info(\"[%s] Successful update of item with key %s - code %d\", getName(), item.getKey(), ret);\n KeyValuePair k;\n getKeyAndSignature(item, k);\n updateInCache(k);\n }\n break;\n default:\n LOG.error(\"[%s] Failed update of item with key %s - code %d\", getName(), item.getKey(), ret);\n break;\n }\n return ret;\n}\n\nint CacheSyncSource::deleteItem(SyncItem& item) {\n int ret = removeItem(item);\n switch (ret) { \n case 200:\n case 201:\n case 418: {\n LOG.info(\"[%s] Successful delete of item with key %s - code %d\", getName(), item.getKey(), ret); \n char* t = toMultibyte(item.getKey());\n KeyValuePair k (t, \"\");\n removeFromCache(k);\n delete [] t;\n }\n break;\n default:\n LOG.error(\"[%s] Failed delete of item with key %s - code %d\", getName(), item.getKey(), ret);\n break;\n }\n \n return ret;\n} \n\nEND_NAMESPACE\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n * Copyright (c) 2014 eProsima. All rights reserved.\n *\n * This copy of eProsima Fast RTPS is licensed to you under the terms described in the\n * FASTRTPS_LIBRARY_LICENSE file included in this distribution.\n *\n *************************************************************************\/\n\n\/**\n * @file TimedEventImpl.cpp\n *\n *\/\n\n\n#include \"TimedEventImpl.h\"\n#include <fastrtps\/rtps\/resources\/TimedEvent.h>\n#include <fastrtps\/utils\/TimeConversion.h>\n\n#include <boost\/atomic.hpp>\n#include <cassert>\n\nnamespace eprosima\n{\n namespace fastrtps\n {\n namespace rtps\n {\n class TimerState\n {\n public:\n\n typedef enum\n {\n INACTIVE = 0,\n WAITING,\n CANCELLED,\n RUNNING,\n DESTROYED\n } StateCode;\n\n TimerState(TimedEvent::AUTODESTRUCTION_MODE autodestruction) : code_(INACTIVE),\n autodestruction_(autodestruction) {}\n\n boost::atomic<StateCode> code_;\n\n TimedEvent::AUTODESTRUCTION_MODE autodestruction_;\n };\n }\n }\n}\n\nusing namespace eprosima::fastrtps::rtps;\n\nTimedEventImpl::TimedEventImpl(TimedEvent* event, boost::asio::io_service &service, const boost::thread& event_thread, boost::posix_time::microseconds interval, TimedEvent::AUTODESTRUCTION_MODE autodestruction) :\ntimer_(service, interval), m_interval_microsec(interval), mp_event(event),\nautodestruction_(autodestruction), state_(std::make_shared<TimerState>(autodestruction)), event_thread_id_(event_thread.get_id())\n{\n\t\/\/TIME_INFINITE(m_timeInfinite);\n}\n\nTimedEventImpl::~TimedEventImpl()\n{\n boost::unique_lock<boost::mutex> lock(mutex_);\n \/\/ Exchange state to avoid race conditions. Any state will go to state TimerState::DESTROYED.\n TimerState::StateCode code = state_.get()->code_.exchange(TimerState::DESTROYED, boost::memory_order_relaxed);\n\n \/\/ code's value cannot be TimerState::DESTROYED. In this case other destructor was called.\n assert(code != TimerState::DESTROYED);\n\n \/\/ If the event is waiting, cancel it.\n if(code == TimerState::WAITING)\n timer_.cancel();\n\n \/\/ If the event is waiting or running, wait it finishes.\n \/\/ Don't wait if it is the event thread.\n if(code == TimerState::WAITING || (code == TimerState::RUNNING && event_thread_id_ != boost::this_thread::get_id()))\n cond_.wait(lock);\n}\n\nvoid TimedEventImpl::destroy()\n{\n}\n\n\n\/* In this function we don't need to exchange the state,\n * because this function try to cancel, but if the event is running\n * in the middle of the operation, it doesn't bother.\n *\/\nvoid TimedEventImpl::cancel_timer()\n{\n TimerState::StateCode code = TimerState::WAITING;\n\n \/\/ Lock timer to protect state_ and timer_ objects.\n boost::unique_lock<boost::mutex> lock(mutex_);\n\n \/\/ Exchange state to avoid race conditions. Only TimerState::WAITING state can be set to TimerState::CANCELLED.\n bool ret = state_.get()->code_.compare_exchange_strong(code, TimerState::CANCELLED, boost::memory_order_relaxed);\n\n if(ret)\n {\n \/\/ Unattach the event state from future event execution.\n state_.reset(new TimerState(autodestruction_));\n \/\/ Cancel the event.\n timer_.cancel();\n \/\/ Alert to user.\n mp_event->event(TimedEvent::EVENT_ABORT, nullptr);\n }\n}\n\nvoid TimedEventImpl::restart_timer()\n{\n \/\/ Lock timer to protect state_ and timer_ objects.\n boost::unique_lock<boost::mutex> lock(mutex_);\n\n \/\/ Get current state.\n TimerState::StateCode code = state_.get()->code_.load(boost::memory_order_relaxed);\n\n \/\/ if the code is executed in the event thread, and the event is being destroyed, don't start other event.\n \/\/ if the code indicate an event is already waiting, don't start other event.\n if(code != TimerState::DESTROYED && code != TimerState::WAITING)\n {\n state_.get()->code_.store(TimerState::WAITING, boost::memory_order_relaxed);\n\n timer_.expires_from_now(m_interval_microsec);\n timer_.async_wait(boost::bind(&TimedEventImpl::event,this,boost::asio::placeholders::error, state_));\n }\n}\n\nbool TimedEventImpl::update_interval(const Duration_t& inter)\n{\n boost::unique_lock<boost::mutex> lock(mutex_);\n\tm_interval_microsec = boost::posix_time::microseconds(TimeConv::Time_t2MicroSecondsInt64(inter));\n\treturn true;\n}\n\nbool TimedEventImpl::update_interval_millisec(double time_millisec)\n{\n boost::unique_lock<boost::mutex> lock(mutex_);\n\tm_interval_microsec = boost::posix_time::microseconds((int64_t)(time_millisec*1000));\n\treturn true;\n}\n\nvoid TimedEventImpl::event(const boost::system::error_code& ec, const std::shared_ptr<TimerState>& state)\n{\n TimerState::StateCode scode = TimerState::WAITING;\n\n \/\/ First step is exchange the state, to prevent race condition from the destruction case.\n bool ret = state.get()->code_.compare_exchange_strong(scode, TimerState::RUNNING, boost::memory_order_relaxed);\n\n \/\/ Check bad preconditions\n assert(!(ret && scode == TimerState::DESTROYED));\n\n if(scode != TimerState::WAITING || !ret || ec == boost::asio::error::operation_aborted)\n {\n \/\/ If autodestruction is TimedEvent::ALLWAYS, delete the event.\n if(scode != TimerState::DESTROYED && state.get()->autodestruction_ == TimedEvent::ALLWAYS)\n {\n delete this->mp_event;\n }\n \/\/ If code is TimerState::DESTROYED, then the destructor is waiting because this event were in state TimerState::WAITING.\n else if(scode == TimerState::DESTROYED)\n {\n boost::unique_lock<boost::mutex> lock(mutex_);\n cond_.notify_one();\n lock.unlock();\n }\n\n \n return;\n }\n\n TimedEvent::EventCode code = TimedEvent::EVENT_MSG;\n const char *message = nullptr;\n\n if(ec == boost::system::errc::success)\n code = TimedEvent::EVENT_SUCCESS;\n else\n message = ec.message().c_str();\n\n this->mp_event->event(code, message);\n\n \/\/ If the destructor is waiting, signal it.\n boost::unique_lock<boost::mutex> lock(mutex_);\n\n scode = TimerState::RUNNING;\n ret = state.get()->code_.compare_exchange_strong(scode, TimerState::INACTIVE, boost::memory_order_relaxed);\n\n if(scode == TimerState::DESTROYED)\n cond_.notify_one();\n\n \/\/Unlock mutex\n lock.unlock();\n\n if(state.get()->autodestruction_ == TimedEvent::ALLWAYS ||\n (code == TimedEvent::EVENT_SUCCESS && state.get()->autodestruction_ == TimedEvent::ON_SUCCESS))\n {\n delete this->mp_event;\n }\n}\n<commit_msg>Refs #1538. Revert code test of destroy in event.<commit_after>\/*************************************************************************\n * Copyright (c) 2014 eProsima. All rights reserved.\n *\n * This copy of eProsima Fast RTPS is licensed to you under the terms described in the\n * FASTRTPS_LIBRARY_LICENSE file included in this distribution.\n *\n *************************************************************************\/\n\n\/**\n * @file TimedEventImpl.cpp\n *\n *\/\n\n\n#include \"TimedEventImpl.h\"\n#include <fastrtps\/rtps\/resources\/TimedEvent.h>\n#include <fastrtps\/utils\/TimeConversion.h>\n\n#include <boost\/atomic.hpp>\n#include <cassert>\n\nnamespace eprosima\n{\n namespace fastrtps\n {\n namespace rtps\n {\n class TimerState\n {\n public:\n\n typedef enum\n {\n INACTIVE = 0,\n WAITING,\n CANCELLED,\n RUNNING,\n DESTROYED\n } StateCode;\n\n TimerState(TimedEvent::AUTODESTRUCTION_MODE autodestruction) : code_(INACTIVE),\n autodestruction_(autodestruction) {}\n\n boost::atomic<StateCode> code_;\n\n TimedEvent::AUTODESTRUCTION_MODE autodestruction_;\n };\n }\n }\n}\n\nusing namespace eprosima::fastrtps::rtps;\n\nTimedEventImpl::TimedEventImpl(TimedEvent* event, boost::asio::io_service &service, const boost::thread& event_thread, boost::posix_time::microseconds interval, TimedEvent::AUTODESTRUCTION_MODE autodestruction) :\ntimer_(service, interval), m_interval_microsec(interval), mp_event(event),\nautodestruction_(autodestruction), state_(std::make_shared<TimerState>(autodestruction)), event_thread_id_(event_thread.get_id())\n{\n\t\/\/TIME_INFINITE(m_timeInfinite);\n}\n\nTimedEventImpl::~TimedEventImpl()\n{\n}\n\nvoid TimedEventImpl::destroy()\n{\n boost::unique_lock<boost::mutex> lock(mutex_);\n \/\/ Exchange state to avoid race conditions. Any state will go to state TimerState::DESTROYED.\n TimerState::StateCode code = state_.get()->code_.exchange(TimerState::DESTROYED, boost::memory_order_relaxed);\n\n \/\/ code's value cannot be TimerState::DESTROYED. In this case other destructor was called.\n assert(code != TimerState::DESTROYED);\n\n \/\/ If the event is waiting, cancel it.\n if(code == TimerState::WAITING)\n timer_.cancel();\n\n \/\/ If the event is waiting or running, wait it finishes.\n \/\/ Don't wait if it is the event thread.\n if(code == TimerState::WAITING || (code == TimerState::RUNNING && event_thread_id_ != boost::this_thread::get_id()))\n cond_.wait(lock);\n}\n\n\n\/* In this function we don't need to exchange the state,\n * because this function try to cancel, but if the event is running\n * in the middle of the operation, it doesn't bother.\n *\/\nvoid TimedEventImpl::cancel_timer()\n{\n TimerState::StateCode code = TimerState::WAITING;\n\n \/\/ Lock timer to protect state_ and timer_ objects.\n boost::unique_lock<boost::mutex> lock(mutex_);\n\n \/\/ Exchange state to avoid race conditions. Only TimerState::WAITING state can be set to TimerState::CANCELLED.\n bool ret = state_.get()->code_.compare_exchange_strong(code, TimerState::CANCELLED, boost::memory_order_relaxed);\n\n if(ret)\n {\n \/\/ Unattach the event state from future event execution.\n state_.reset(new TimerState(autodestruction_));\n \/\/ Cancel the event.\n timer_.cancel();\n \/\/ Alert to user.\n mp_event->event(TimedEvent::EVENT_ABORT, nullptr);\n }\n}\n\nvoid TimedEventImpl::restart_timer()\n{\n \/\/ Lock timer to protect state_ and timer_ objects.\n boost::unique_lock<boost::mutex> lock(mutex_);\n\n \/\/ Get current state.\n TimerState::StateCode code = state_.get()->code_.load(boost::memory_order_relaxed);\n\n \/\/ if the code is executed in the event thread, and the event is being destroyed, don't start other event.\n \/\/ if the code indicate an event is already waiting, don't start other event.\n if(code != TimerState::DESTROYED && code != TimerState::WAITING)\n {\n state_.get()->code_.store(TimerState::WAITING, boost::memory_order_relaxed);\n\n timer_.expires_from_now(m_interval_microsec);\n timer_.async_wait(boost::bind(&TimedEventImpl::event,this,boost::asio::placeholders::error, state_));\n }\n}\n\nbool TimedEventImpl::update_interval(const Duration_t& inter)\n{\n boost::unique_lock<boost::mutex> lock(mutex_);\n\tm_interval_microsec = boost::posix_time::microseconds(TimeConv::Time_t2MicroSecondsInt64(inter));\n\treturn true;\n}\n\nbool TimedEventImpl::update_interval_millisec(double time_millisec)\n{\n boost::unique_lock<boost::mutex> lock(mutex_);\n\tm_interval_microsec = boost::posix_time::microseconds((int64_t)(time_millisec*1000));\n\treturn true;\n}\n\nvoid TimedEventImpl::event(const boost::system::error_code& ec, const std::shared_ptr<TimerState>& state)\n{\n TimerState::StateCode scode = TimerState::WAITING;\n\n \/\/ First step is exchange the state, to prevent race condition from the destruction case.\n bool ret = state.get()->code_.compare_exchange_strong(scode, TimerState::RUNNING, boost::memory_order_relaxed);\n\n \/\/ Check bad preconditions\n assert(!(ret && scode == TimerState::DESTROYED));\n\n if(scode != TimerState::WAITING || !ret || ec == boost::asio::error::operation_aborted)\n {\n \/\/ If autodestruction is TimedEvent::ALLWAYS, delete the event.\n if(scode != TimerState::DESTROYED && state.get()->autodestruction_ == TimedEvent::ALLWAYS)\n {\n delete this->mp_event;\n }\n \/\/ If code is TimerState::DESTROYED, then the destructor is waiting because this event were in state TimerState::WAITING.\n else if(scode == TimerState::DESTROYED)\n {\n boost::unique_lock<boost::mutex> lock(mutex_);\n cond_.notify_one();\n lock.unlock();\n }\n\n \n return;\n }\n\n TimedEvent::EventCode code = TimedEvent::EVENT_MSG;\n const char *message = nullptr;\n\n if(ec == boost::system::errc::success)\n code = TimedEvent::EVENT_SUCCESS;\n else\n message = ec.message().c_str();\n\n this->mp_event->event(code, message);\n\n \/\/ If the destructor is waiting, signal it.\n boost::unique_lock<boost::mutex> lock(mutex_);\n\n scode = TimerState::RUNNING;\n ret = state.get()->code_.compare_exchange_strong(scode, TimerState::INACTIVE, boost::memory_order_relaxed);\n\n if(scode == TimerState::DESTROYED)\n cond_.notify_one();\n\n \/\/Unlock mutex\n lock.unlock();\n\n if(state.get()->autodestruction_ == TimedEvent::ALLWAYS ||\n (code == TimedEvent::EVENT_SUCCESS && state.get()->autodestruction_ == TimedEvent::ON_SUCCESS))\n {\n delete this->mp_event;\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * SessionThemes.cpp\n *\n * Copyright (C) 2018 by RStudio, Inc.\n *\n * Unless you have received this program directly from RStudio pursuant\n * to the terms of a commercial license agreement with RStudio, then\n * this program is licensed to you under the terms of version 3 of the\n * GNU Affero General Public License. This program is distributed WITHOUT\n * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,\n * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the\n * AGPL (http:\/\/www.gnu.org\/licenses\/agpl-3.0.txt) for more details.\n *\n *\/\n\n#include \"SessionThemes.hpp\"\n\n#include <boost\/bind.hpp>\n\n#include <core\/Error.hpp>\n#include <core\/Exec.hpp>\n#include <core\/FilePath.hpp>\n#include <core\/json\/JsonRpc.hpp>\n#include <core\/system\/System.hpp>\n\n#include <core\/http\/Request.hpp>\n#include <core\/http\/Response.hpp>\n\n#include <session\/SessionModuleContext.hpp>\n\n#include <r\/RRoutines.hpp>\n#include <r\/RSexp.hpp>\n\n#include <fstream>\n#include <map>\n#include <regex>\n#include <string>\n\nusing namespace rstudio::core;\n\nnamespace rstudio {\nnamespace session {\nnamespace modules {\nnamespace themes {\n\nnamespace {\n\nconst std::string kDefaultThemeLocation = \"\/theme\/default\/\";\nconst std::string kGlobalCustomThemeLocation = \"\/theme\/custom\/global\/\";\nconst std::string kLocalCustomThemeLocation = \"\/theme\/custom\/local\/\";\n\n\/\/ A map from the name of the theme to the location of the file and a boolean representing\n\/\/ whether or not the theme is dark.\ntypedef std::map<std::string, std::tuple<std::string, std::string, bool> > ThemeMap;\n\n\/\/\/ @brief Determines whether a string can be evaluated to logical \"true\". A return value of false\n\/\/\/ does not indicate that the string can be evaluted to logical \"false\".\n\/\/\/\n\/\/\/ @param toConvert The string to convert to boolean.\n\/\/\/\n\/\/\/ @return True if the string matches 1, TRUE, true, or any case variant of true; false otherwise.\nbool strIsTrue(const std::string& toConvert)\n{\n return std::regex_match(\n std::string(toConvert),\n std::regex(\"(?:1|t(?:rue)?)\", std::regex_constants::icase));\n}\n\n\/\/\/ @brief Determines whether a string can be evaluated to logical \"false\". A return value of true\n\/\/\/ does not indicate that the string can be evaluted to logical \"true\".\n\/\/\/\n\/\/\/ @param toConvert The string to convert to boolean.\n\/\/\/\n\/\/\/ @return True if the string matches 0, FALSE, false, or any case variant of false; true\n\/\/\/ otherwise.\nbool strIsFalse(const std::string& toConvert)\n{\n return std::regex_match(\n std::string(toConvert),\n std::regex(\"(?:0|f(?:alse)?)\", std::regex_constants::icase));\n}\n\n\/**\n * @brief Gets themes in the specified location.\n *\n * @param location The location in which to look for themes.\n * @param themeMap The map which will contain all found themes after the call.\n * @param urlPrefix The URL prefix for the theme. Must end with \"\/\"\n *\/\nvoid getThemesInLocation(\n const rstudio::core::FilePath& location,\n ThemeMap& themeMap,\n const std::string& urlPrefix = \"\")\n{\n using rstudio::core::FilePath;\n if (location.isDirectory())\n {\n std::vector<FilePath> locationChildren;\n location.children(&locationChildren);\n for (const FilePath& themeFile: locationChildren)\n {\n if (themeFile.hasExtensionLowerCase(\".rstheme\"))\n {\n const std::string k_themeFileStr = themeFile.canonicalPath();\n std::ifstream themeIFStream(k_themeFileStr);\n std::string themeContents(\n (std::istreambuf_iterator<char>(themeIFStream)),\n (std::istreambuf_iterator<char>()));\n themeIFStream.close();\n\n std::smatch matches;\n std::regex_search(\n themeContents,\n matches,\n std::regex(\"rs-theme-name\\\\s*:\\\\s*([^\\\\*]+?)\\\\s*(?:\\\\*|$)\"));\n\n \/\/ If there's no name specified,use the name of the file\n std::string name;\n if (matches.size() < 2)\n {\n name = themeFile.stem();\n }\n else\n {\n \/\/ If there's at least one name specified, get the first one.\n name = matches[1];\n }\n\n \/\/ Find out if the theme is dark or not.\n std::regex_search(\n themeContents,\n matches,\n std::regex(\"rs-theme-is-dark\\\\s*:\\\\s*([^\\\\*]+?)\\\\s*(?:\\\\*|$)\"));\n\n bool isDark = false;\n if (matches.size() >= 2)\n {\n isDark = strIsTrue(matches[1]);\n }\n if ((matches.size() < 2) ||\n (!isDark &&\n !strIsFalse(matches[1])))\n {\n \/\/ TODO: warning \/ logging about using default isDark value.\n }\n\n themeMap[boost::algorithm::to_lower_copy(name)] = std::make_tuple(\n name,\n urlPrefix + themeFile.filename(),\n isDark);\n }\n }\n }\n}\n\n\/**\n * @brief Gets the location of themes that are installed with RStudio.\n *\n * @return The location of themes that are installed with RStudio.\n *\/\nFilePath getDefaultThemePath()\n{\n return session::options().rResourcesPath().childPath(\"themes\");\n}\n\n\/**\n * @brief Gets the location of custom themes that are installed for all users.\n *\n * @return The location of custom themes that are installed for all users.\n *\/\nFilePath getGlobalCustomThemePath()\n{\n using rstudio::core::FilePath;\n\n const char* kGlobalPathAlt = std::getenv(\"RS_THEME_GLOBAL_HOME\");\n if (kGlobalPathAlt)\n {\n return FilePath(kGlobalPathAlt);\n }\n\n#ifdef _WIN32\n return core::system::systemSettingsPath(\"RStudio\\\\themes\", false);\n#else\n return FilePath(\"\/etc\/rstudio\/themes\/\");\n#endif\n}\n\n\/**\n * @brief Gets the location of custom themes that are installed for the current user.\n *\n * @return The location of custom themes that are installed for the current user.\n *\/\nFilePath getLocalCustomThemePath()\n{\n using rstudio::core::FilePath;\n const char* kLocalPathAlt = std::getenv(\"RS_THEME_LOCAL_HOME\");\n if (kLocalPathAlt)\n {\n return FilePath(kLocalPathAlt);\n }\n\n#ifdef _WIN32\n return core::system::userHomePath().childPath(\".R\\\\rstudio\\\\themes\");\n#else\n return core::system::userHomePath().childPath(\".R\/rstudio\/themes\/\");\n#endif\n}\n\n\/**\n * @brief Gets a map of all available themes, keyed by the unique name of the theme. If a theme is\n * found in multiple locations, the theme in the most specific folder will be given\n * precedence.\n *\n * @return The map of all available themes.\n *\/\nThemeMap getAllThemes()\n{\n \/\/ Intentionally get global themes before getting user specific themes so that user specific\n \/\/ themes will override global ones.\n ThemeMap themeMap;\n getThemesInLocation(getDefaultThemePath(), themeMap, kDefaultThemeLocation);\n getThemesInLocation(getGlobalCustomThemePath(), themeMap, kGlobalCustomThemeLocation);\n getThemesInLocation(getLocalCustomThemePath(), themeMap, kLocalCustomThemeLocation);\n\n return themeMap;\n}\n\n\/**\n * @brief Gets the list of all RStudio editor themes.\n *\n * @return The list of all RStudio editor themes.\n *\/\nSEXP rs_getThemes()\n{\n ThemeMap themeMap = getAllThemes();\n\n \/\/ Convert to an R list.\n rstudio::r::sexp::Protect protect;\n rstudio::r::sexp::ListBuilder themeListBuilder(&protect);\n\n for (auto theme: themeMap)\n {\n rstudio::r::sexp::ListBuilder themeDetailsListBuilder(&protect);\n themeDetailsListBuilder.add(\"name\", std::get<0>(theme.second));\n themeDetailsListBuilder.add(\"url\", std::get<1>(theme.second));\n themeDetailsListBuilder.add(\"isDark\", std::get<2>(theme.second));\n\n themeListBuilder.add(theme.first, themeDetailsListBuilder);\n }\n\n return rstudio::r::sexp::create(themeListBuilder, &protect);\n}\n\n\/**\n * @brief Gets the default theme based on the request from the client.\n *\n * @param request The request from the client.\n *\n * @return The default theme. \"Tomorrow Night\" if the request is for a dark theme; \"Textmate\" if\n * the request is for a light theme.\n *\/\nFilePath getDefaultTheme(const http::Request& request)\n{\n std::string isDarkStr = request.queryParamValue(\"dark\");\n bool isDark = strIsTrue(isDarkStr);\n if (!isDark && !strIsFalse(isDarkStr))\n {\n \/\/ TODO: Error\/warning\/logging\n \/\/ Note that this should be considered an internal error, since the request is generated\n \/\/ by the client and without user input.\n }\n\n if (isDark)\n {\n return getDefaultThemePath().childPath(\"tomorrow_night.rstheme\");\n }\n else\n {\n return getDefaultThemePath().childPath(\"textmate.rstheme\");\n }\n}\n\n\/**\n * @brief Gets a theme that is installed with RStudio.\n *\n * @param request The HTTP request from the client.\n * @param pResponse The HTTP response, which will contain the theme CSS.\n *\/\nvoid handleDefaultThemeRequest(const http::Request& request,\n http::Response* pResponse)\n{\n std::string fileName = http::util::pathAfterPrefix(request, kDefaultThemeLocation);\n pResponse->setCacheableFile(getDefaultThemePath().childPath(fileName), request);\n pResponse->setContentType(\"text\/css\");\n}\n\n\/**\n * @brief Gets a custom theme that is installed for all users.\n *\n * @param request The HTTP request from the client.\n * @param pResponse The HTTP response, which will contain the theme CSS.\n *\/\nvoid handleGlobalCustomThemeRequest(const http::Request& request,\n http::Response* pResponse)\n{\n \/\/ Note: we probably want to return a warning code instead of success so the client has the\n \/\/ ability to pop up a warning dialog or something to the user.\n std::string fileName = http::util::pathAfterPrefix(request, kGlobalCustomThemeLocation);\n FilePath requestedTheme = getGlobalCustomThemePath().childPath(fileName);\n pResponse->setCacheableFile(\n requestedTheme.exists() ? requestedTheme : getDefaultTheme(request),\n request);\n pResponse->setContentType(\"text\/css\");\n}\n\n\/**\n * @brief Gets a custom theme that is installed for all users.\n *\n * @param request The HTTP request from the client.\n * @param pResponse The HTTP response, which will contain the theme CSS.\n *\/\nvoid handleLocalCustomThemeRequest(const http::Request& request,\n http::Response* pResponse)\n{\n \/\/ Note: we probably want to return a warning code instead of success so the client has the\n \/\/ ability to pop up a warning dialog or something to the user.\n std::string fileName = http::util::pathAfterPrefix(request, kLocalCustomThemeLocation);\n FilePath requestedTheme = getLocalCustomThemePath().childPath(fileName);\n pResponse->setCacheableFile(\n requestedTheme.exists() ? requestedTheme : getDefaultTheme(request),\n request);\n pResponse->setContentType(\"text\/css\");\n}\n\n\/**\n * @brief Gets the list of all the avialble themes for the client.\n *\n * @param request The JSON request from the client.\n * @param pResponse The JSON response, which will contain the list of themes.\n *\n * @return The error that occurred, if any; otherwise Success().\n *\/\nError getThemes(const json::JsonRpcRequest& request,\n json::JsonRpcResponse* pResponse)\n{\n ThemeMap themes = getAllThemes();\n\n \/\/ Convert the theme to a json array.\n json::Array jsonThemeArray;\n for (auto theme: themes)\n {\n json::Object jsonTheme;\n jsonTheme[\"name\"] = std::get<0>(theme.second);\n jsonTheme[\"url\"] = std::get<1>(theme.second);\n jsonTheme[\"isDark\"] = std::get<2>(theme.second);\n jsonThemeArray.push_back(jsonTheme);\n }\n\n pResponse->setResult(jsonThemeArray);\n return Success();\n}\n\n} \/\/ anonymous namespace\n\nError initialize()\n{\n using boost::bind;\n using namespace module_context;\n\n RS_REGISTER_CALL_METHOD(rs_getThemes, 0);\n\n ExecBlock initBlock;\n initBlock.addFunctions()\n (bind(sourceModuleRFile, \"SessionThemes.R\"))\n (bind(registerRpcMethod, \"get_themes\", getThemes))\n (bind(registerUriHandler, kDefaultThemeLocation, handleDefaultThemeRequest))\n (bind(registerUriHandler, kGlobalCustomThemeLocation, handleGlobalCustomThemeRequest))\n (bind(registerUriHandler, kLocalCustomThemeLocation, handleLocalCustomThemeRequest));\n\n return initBlock.execute();\n}\n\n} \/\/ namespace themes\n} \/\/ namespace modules\n} \/\/ namespace session\n} \/\/ namespace rstudio\n<commit_msg>switch from std::regex functions to boost::regex functions because gcc 4.8 doesn't support std::regex.<commit_after>\/*\n * SessionThemes.cpp\n *\n * Copyright (C) 2018 by RStudio, Inc.\n *\n * Unless you have received this program directly from RStudio pursuant\n * to the terms of a commercial license agreement with RStudio, then\n * this program is licensed to you under the terms of version 3 of the\n * GNU Affero General Public License. This program is distributed WITHOUT\n * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,\n * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the\n * AGPL (http:\/\/www.gnu.org\/licenses\/agpl-3.0.txt) for more details.\n *\n *\/\n\n#include \"SessionThemes.hpp\"\n\n#include <boost\/algorithm\/algorithm.hpp>\n#include <boost\/bind.hpp>\n#include <boost\/regex.hpp>\n\n#include <core\/Error.hpp>\n#include <core\/Exec.hpp>\n#include <core\/FilePath.hpp>\n#include <core\/json\/JsonRpc.hpp>\n#include <core\/system\/System.hpp>\n\n#include <core\/http\/Request.hpp>\n#include <core\/http\/Response.hpp>\n\n#include <session\/SessionModuleContext.hpp>\n\n#include <r\/RRoutines.hpp>\n#include <r\/RSexp.hpp>\n\n#include <fstream>\n#include <map>\n#include <string>\n\nusing namespace rstudio::core;\n\nnamespace rstudio {\nnamespace session {\nnamespace modules {\nnamespace themes {\n\nnamespace {\n\nconst std::string kDefaultThemeLocation = \"\/theme\/default\/\";\nconst std::string kGlobalCustomThemeLocation = \"\/theme\/custom\/global\/\";\nconst std::string kLocalCustomThemeLocation = \"\/theme\/custom\/local\/\";\n\n\/\/ A map from the name of the theme to the location of the file and a boolean representing\n\/\/ whether or not the theme is dark.\ntypedef std::map<std::string, std::tuple<std::string, std::string, bool> > ThemeMap;\n\n\/\/\/ @brief Determines whether a string can be evaluated to logical \"true\". A return value of false\n\/\/\/ does not indicate that the string can be evaluted to logical \"false\".\n\/\/\/\n\/\/\/ @param toConvert The string to convert to boolean.\n\/\/\/\n\/\/\/ @return True if the string matches 1, TRUE, true, or any case variant of true; false otherwise.\nbool strIsTrue(const std::string& toConvert)\n{\n return boost::regex_match(\n toConvert,\n boost::regex(\"(?:1|t(?:rue)?)\", boost::regex::icase));\n}\n\n\/\/\/ @brief Determines whether a string can be evaluated to logical \"false\". A return value of true\n\/\/\/ does not indicate that the string can be evaluted to logical \"true\".\n\/\/\/\n\/\/\/ @param toConvert The string to convert to boolean.\n\/\/\/\n\/\/\/ @return True if the string matches 0, FALSE, false, or any case variant of false; true\n\/\/\/ otherwise.\nbool strIsFalse(const std::string& toConvert)\n{\n return boost::regex_match(\n toConvert,\n boost::regex(\"(?:0|f(?:alse)?)\", boost::regex::icase));\n}\n\n\/**\n * @brief Gets themes in the specified location.\n *\n * @param location The location in which to look for themes.\n * @param themeMap The map which will contain all found themes after the call.\n * @param urlPrefix The URL prefix for the theme. Must end with \"\/\"\n *\/\nvoid getThemesInLocation(\n const rstudio::core::FilePath& location,\n ThemeMap& themeMap,\n const std::string& urlPrefix = \"\")\n{\n using rstudio::core::FilePath;\n if (location.isDirectory())\n {\n std::vector<FilePath> locationChildren;\n location.children(&locationChildren);\n for (const FilePath& themeFile: locationChildren)\n {\n if (themeFile.hasExtensionLowerCase(\".rstheme\"))\n {\n const std::string k_themeFileStr = themeFile.canonicalPath();\n std::ifstream themeIFStream(k_themeFileStr);\n std::string themeContents(\n (std::istreambuf_iterator<char>(themeIFStream)),\n (std::istreambuf_iterator<char>()));\n themeIFStream.close();\n\n boost::smatch matches;\n boost::regex_search(\n themeContents,\n matches,\n boost::regex(\"rs-theme-name\\\\s*:\\\\s*([^\\\\*]+?)\\\\s*(?:\\\\*|$)\"));\n\n \/\/ If there's no name specified,use the name of the file\n std::string name;\n if (matches.size() < 2)\n {\n name = themeFile.stem();\n }\n else\n {\n \/\/ If there's at least one name specified, get the first one.\n name = matches[1];\n }\n\n \/\/ Find out if the theme is dark or not.\n boost::regex_search(\n themeContents,\n matches,\n boost::regex(\"rs-theme-is-dark\\\\s*:\\\\s*([^\\\\*]+?)\\\\s*(?:\\\\*|$)\"));\n\n bool isDark = false;\n if (matches.size() >= 2)\n {\n isDark = strIsTrue(matches[1]);\n }\n if ((matches.size() < 2) ||\n (!isDark &&\n !strIsFalse(matches[1])))\n {\n LOG_WARNING_MESSAGE(\"rs-theme-is-dark is not set or not convertable to boolean for theme \\\"\" + name + \"\\\".\");\n }\n\n themeMap[boost::algorithm::to_lower_copy(name)] = std::make_tuple(\n name,\n urlPrefix + themeFile.filename(),\n isDark);\n }\n }\n }\n}\n\n\/**\n * @brief Gets the location of themes that are installed with RStudio.\n *\n * @return The location of themes that are installed with RStudio.\n *\/\nFilePath getDefaultThemePath()\n{\n return session::options().rResourcesPath().childPath(\"themes\");\n}\n\n\/**\n * @brief Gets the location of custom themes that are installed for all users.\n *\n * @return The location of custom themes that are installed for all users.\n *\/\nFilePath getGlobalCustomThemePath()\n{\n using rstudio::core::FilePath;\n\n const char* kGlobalPathAlt = std::getenv(\"RS_THEME_GLOBAL_HOME\");\n if (kGlobalPathAlt)\n {\n return FilePath(kGlobalPathAlt);\n }\n\n#ifdef _WIN32\n return core::system::systemSettingsPath(\"RStudio\\\\themes\", false);\n#else\n return FilePath(\"\/etc\/rstudio\/themes\/\");\n#endif\n}\n\n\/**\n * @brief Gets the location of custom themes that are installed for the current user.\n *\n * @return The location of custom themes that are installed for the current user.\n *\/\nFilePath getLocalCustomThemePath()\n{\n using rstudio::core::FilePath;\n const char* kLocalPathAlt = std::getenv(\"RS_THEME_LOCAL_HOME\");\n if (kLocalPathAlt)\n {\n return FilePath(kLocalPathAlt);\n }\n\n#ifdef _WIN32\n return core::system::userHomePath().childPath(\".R\\\\rstudio\\\\themes\");\n#else\n return core::system::userHomePath().childPath(\".R\/rstudio\/themes\/\");\n#endif\n}\n\n\/**\n * @brief Gets a map of all available themes, keyed by the unique name of the theme. If a theme is\n * found in multiple locations, the theme in the most specific folder will be given\n * precedence.\n *\n * @return The map of all available themes.\n *\/\nThemeMap getAllThemes()\n{\n \/\/ Intentionally get global themes before getting user specific themes so that user specific\n \/\/ themes will override global ones.\n ThemeMap themeMap;\n getThemesInLocation(getDefaultThemePath(), themeMap, kDefaultThemeLocation);\n getThemesInLocation(getGlobalCustomThemePath(), themeMap, kGlobalCustomThemeLocation);\n getThemesInLocation(getLocalCustomThemePath(), themeMap, kLocalCustomThemeLocation);\n\n return themeMap;\n}\n\n\/**\n * @brief Gets the list of all RStudio editor themes.\n *\n * @return The list of all RStudio editor themes.\n *\/\nSEXP rs_getThemes()\n{\n ThemeMap themeMap = getAllThemes();\n\n \/\/ Convert to an R list.\n rstudio::r::sexp::Protect protect;\n rstudio::r::sexp::ListBuilder themeListBuilder(&protect);\n\n for (auto theme: themeMap)\n {\n rstudio::r::sexp::ListBuilder themeDetailsListBuilder(&protect);\n themeDetailsListBuilder.add(\"name\", std::get<0>(theme.second));\n themeDetailsListBuilder.add(\"url\", std::get<1>(theme.second));\n themeDetailsListBuilder.add(\"isDark\", std::get<2>(theme.second));\n\n themeListBuilder.add(theme.first, themeDetailsListBuilder);\n }\n\n return rstudio::r::sexp::create(themeListBuilder, &protect);\n}\n\n\/**\n * @brief Gets the default theme based on the request from the client.\n *\n * @param request The request from the client.\n *\n * @return The default theme. \"Tomorrow Night\" if the request is for a dark theme; \"Textmate\" if\n * the request is for a light theme.\n *\/\nFilePath getDefaultTheme(const http::Request& request)\n{\n std::string isDarkStr = request.queryParamValue(\"dark\");\n bool isDark = strIsTrue(isDarkStr);\n if (!isDark && !strIsFalse(isDarkStr))\n {\n LOG_WARNING_MESSAGE(\"\\\"dark\\\" parameter for request is missing or not a true or false value: \" + isDarkStr);\n }\n\n if (isDark)\n {\n return getDefaultThemePath().childPath(\"tomorrow_night.rstheme\");\n }\n else\n {\n return getDefaultThemePath().childPath(\"textmate.rstheme\");\n }\n}\n\n\/**\n * @brief Gets a theme that is installed with RStudio.\n *\n * @param request The HTTP request from the client.\n * @param pResponse The HTTP response, which will contain the theme CSS.\n *\/\nvoid handleDefaultThemeRequest(const http::Request& request,\n http::Response* pResponse)\n{\n std::string fileName = http::util::pathAfterPrefix(request, kDefaultThemeLocation);\n pResponse->setCacheableFile(getDefaultThemePath().childPath(fileName), request);\n pResponse->setContentType(\"text\/css\");\n}\n\n\/**\n * @brief Gets a custom theme that is installed for all users.\n *\n * @param request The HTTP request from the client.\n * @param pResponse The HTTP response, which will contain the theme CSS.\n *\/\nvoid handleGlobalCustomThemeRequest(const http::Request& request,\n http::Response* pResponse)\n{\n \/\/ Note: we probably want to return a warning code instead of success so the client has the\n \/\/ ability to pop up a warning dialog or something to the user.\n std::string fileName = http::util::pathAfterPrefix(request, kGlobalCustomThemeLocation);\n FilePath requestedTheme = getGlobalCustomThemePath().childPath(fileName);\n pResponse->setCacheableFile(\n requestedTheme.exists() ? requestedTheme : getDefaultTheme(request),\n request);\n pResponse->setContentType(\"text\/css\");\n}\n\n\/**\n * @brief Gets a custom theme that is installed for all users.\n *\n * @param request The HTTP request from the client.\n * @param pResponse The HTTP response, which will contain the theme CSS.\n *\/\nvoid handleLocalCustomThemeRequest(const http::Request& request,\n http::Response* pResponse)\n{\n \/\/ Note: we probably want to return a warning code instead of success so the client has the\n \/\/ ability to pop up a warning dialog or something to the user.\n std::string fileName = http::util::pathAfterPrefix(request, kLocalCustomThemeLocation);\n FilePath requestedTheme = getLocalCustomThemePath().childPath(fileName);\n pResponse->setCacheableFile(\n requestedTheme.exists() ? requestedTheme : getDefaultTheme(request),\n request);\n pResponse->setContentType(\"text\/css\");\n}\n\n\/**\n * @brief Gets the list of all the avialble themes for the client.\n *\n * @param request The JSON request from the client.\n * @param pResponse The JSON response, which will contain the list of themes.\n *\n * @return The error that occurred, if any; otherwise Success().\n *\/\nError getThemes(const json::JsonRpcRequest& request,\n json::JsonRpcResponse* pResponse)\n{\n ThemeMap themes = getAllThemes();\n\n \/\/ Convert the theme to a json array.\n json::Array jsonThemeArray;\n for (auto theme: themes)\n {\n json::Object jsonTheme;\n jsonTheme[\"name\"] = std::get<0>(theme.second);\n jsonTheme[\"url\"] = std::get<1>(theme.second);\n jsonTheme[\"isDark\"] = std::get<2>(theme.second);\n jsonThemeArray.push_back(jsonTheme);\n }\n\n pResponse->setResult(jsonThemeArray);\n return Success();\n}\n\n} \/\/ anonymous namespace\n\nError initialize()\n{\n using boost::bind;\n using namespace module_context;\n\n RS_REGISTER_CALL_METHOD(rs_getThemes, 0);\n\n ExecBlock initBlock;\n initBlock.addFunctions()\n (bind(sourceModuleRFile, \"SessionThemes.R\"))\n (bind(registerRpcMethod, \"get_themes\", getThemes))\n (bind(registerUriHandler, kDefaultThemeLocation, handleDefaultThemeRequest))\n (bind(registerUriHandler, kGlobalCustomThemeLocation, handleGlobalCustomThemeRequest))\n (bind(registerUriHandler, kLocalCustomThemeLocation, handleLocalCustomThemeRequest));\n\n return initBlock.execute();\n}\n\n} \/\/ namespace themes\n} \/\/ namespace modules\n} \/\/ namespace session\n} \/\/ namespace rstudio\n<|endoftext|>"} {"text":"<commit_before><commit_msg>Removed the hand-selection logic that re-picked a previous winning hand if it was still above threshold and it now always picks the best 'left' or 'right' hand at a given moment.<commit_after><|endoftext|>"} {"text":"<commit_before>#include <stdio.h>\n#include <stdlib.h>\n\n#include \"App.h\"\n#include <Directory.h>\n#include <NodeMonitor.h>\n#include <Entry.h>\n#include <Path.h>\n#include <String.h>\n\nApp::App(void)\n : BApplication(\"application\/x-vnd.lh-MyDropboxClient\")\n{\n \/\/start watching ~\/Dropbox folder\n BDirectory dir(\"\/boot\/home\/Dropbox\");\n node_ref nref;\n status_t err;\n if(dir.InitCheck() == B_OK){\n dir.GetNodeRef(&nref);\n err = watch_node(&nref, B_WATCH_DIRECTORY, BMessenger(this));\n if(err != B_OK)\n printf(\"Watch Node: Not OK\\n\");\n }\n\n \/\/ track each file in the folder for edits\n\n \/\/ record each file in the folder so that we know the name on deletion\n BEntry entry;\n err = dir.GetNextEntry(&entry);\n while(err == B_OK){\n err = dir.GetNextEntry(&entry);\n this->tracked_files.AddItem((void*)&entry);\n }\n}\n\nint\nrun_script(const char *cmd)\n{\n char buf[BUFSIZ];\n FILE *ptr;\n\n if ((ptr = popen(cmd, \"r\")) != NULL)\n while (fgets(buf, BUFSIZ, ptr) != NULL)\n (void) printf(\"RAWR%s\", buf);\n (void) pclose(ptr);\n return 0;\n}\n\nvoid\ndelete_file_on_dropbox(char * filepath)\n{\n BString s, dbfp;\n s = BString(filepath);\n s.RemoveFirst(\"\/boot\/home\/Dropbox\");\n dbfp << \"python db_rm.py \" << s;\n run_script(dbfp);\n}\n\nBString local_to_db_filepath(const char * local_path)\n{\n BString s;\n s = BString(local_path);\n s.RemoveFirst(\"\/boot\/home\/Dropbox\/\");\n return s;\n}\n\nvoid\nadd_file_to_dropbox(const char * filepath)\n{\n BString s, dbfp;\n dbfp = local_to_db_filepath(filepath);\n s << \"python db_put.py \" << BString(filepath) << \" \" << dbfp;\n printf(\"local filepath:%s\\n\",filepath);\n printf(\"dropbox filepath:%s\\n\",dbfp.String());\n run_script(s.String());\n}\n\nvoid\nadd_folder_to_dropbox(const char * filepath)\n{\n BString s;\n s << \"python db_mkdir.py \" << local_to_db_filepath(filepath);\n printf(\"local filepath: %s\\n\", filepath);\n printf(\"db filepath: %s\\n\", local_to_db_filepath(filepath).String());\n run_script(s.String());\n}\n\n\nvoid\nmoved_file(BMessage *msg) \n{\n \/\/is this file being move into or out of ~\/Dropbox?\n run_script(\"python db_ls.py\");\n}\n\nvoid\nApp::MessageReceived(BMessage *msg)\n{\n switch(msg->what)\n {\n case B_NODE_MONITOR:\n {\n printf(\"Received Node Monitor Alert\\n\");\n status_t err;\n int32 opcode;\n err = msg->FindInt32(\"opcode\",&opcode);\n if(err == B_OK)\n {\n printf(\"what:%d\\topcode:%d\\n\",msg->what, opcode);\n switch(opcode)\n {\n case B_ENTRY_CREATED:\n {\n printf(\"NEW FILE\\n\");\n entry_ref ref;\n BPath path; \n const char * name;\n msg->FindInt32(\"device\",&ref.device);\n msg->FindInt64(\"directory\",&ref.directory);\n msg->FindString(\"name\",&name);\n printf(\"name:%s\\n\",name);\n ref.set_name(name);\n BEntry new_file = BEntry(&ref);\n new_file.GetPath(&path);\n add_file_to_dropbox(path.Path());\n break;\n }\n case B_ENTRY_MOVED:\n {\n printf(\"MOVED FILE\\n\");\n moved_file(msg);\n break;\n }\n case B_ENTRY_REMOVED:\n {\n printf(\"DELETED FILE\\n\");\n \/\/node_ref nref;\n \/\/msg->FindInt32(\"device\",&nref.device);\n \/\/msg->FindInt64(\"node\",&nref.node);\n \/\/BNode node = BNode(&nref);\n delete_file_on_dropbox(\"hi\");\n break;\n }\n default:\n {\n printf(\"default case opcode...\\n\");\n }\n }\n }\n break;\n }\n default:\n {\n printf(\"default msg\\n\");\n BApplication::MessageReceived(msg);\n break;\n }\n }\n}\n\nint\nmain(void)\n{\n \/\/Haiku make window code\n App *app = new App();\n\n app->Run();\n delete app;\n return 0;\n}\n<commit_msg>added tracking of all the file initially in the folder. Remove doesn't work and Edit isn't tested at all. It compiles.<commit_after>#include <stdio.h>\n#include <stdlib.h>\n\n#include \"App.h\"\n#include <Directory.h>\n#include <NodeMonitor.h>\n#include <Entry.h>\n#include <Path.h>\n#include <String.h>\n\nApp::App(void)\n : BApplication(\"application\/x-vnd.lh-MyDropboxClient\")\n{\n \/\/start watching ~\/Dropbox folder\n BDirectory dir(\"\/boot\/home\/Dropbox\");\n node_ref nref;\n status_t err;\n if(dir.InitCheck() == B_OK){\n dir.GetNodeRef(&nref);\n err = watch_node(&nref, B_WATCH_DIRECTORY, BMessenger(this));\n if(err != B_OK)\n printf(\"Watch Node: Not OK\\n\");\n }\n\n \/\/ track each file in the folder for edits\n\n \/\/ record each file in the folder so that we know the name on deletion\n BEntry entry;\n status_t err2;\n err = dir.GetNextEntry(&entry);\n while(err == B_OK)\n {\n err = dir.GetNextEntry(&entry);\n this->tracked_files.AddItem((void*)&entry);\n err2 = entry.GetNodeRef(&nref);\n if(err2 == B_OK)\n {\n err2 = watch_node(&nref, B_WATCH_STAT, be_app_messenger);\n if(err2 != B_OK)\n printf(\"Watch file Node: Not OK\\n\");\n }\n }\n\n \/\/watch each file for edits\n \n\n}\n\nint\nrun_script(const char *cmd)\n{\n char buf[BUFSIZ];\n FILE *ptr;\n\n if ((ptr = popen(cmd, \"r\")) != NULL)\n while (fgets(buf, BUFSIZ, ptr) != NULL)\n (void) printf(\"RAWR%s\", buf);\n (void) pclose(ptr);\n return 0;\n}\n\nvoid\ndelete_file_on_dropbox(const char * filepath)\n{\n BString s, dbfp;\n s = BString(filepath);\n s.RemoveFirst(\"\/boot\/home\/Dropbox\");\n dbfp << \"python db_rm.py \" << s;\n run_script(dbfp);\n}\n\nBString local_to_db_filepath(const char * local_path)\n{\n BString s;\n s = BString(local_path);\n s.RemoveFirst(\"\/boot\/home\/Dropbox\/\");\n return s;\n}\n\nvoid\nadd_file_to_dropbox(const char * filepath)\n{\n BString s, dbfp;\n dbfp = local_to_db_filepath(filepath);\n s << \"python db_put.py \" << BString(filepath) << \" \" << dbfp;\n printf(\"local filepath:%s\\n\",filepath);\n printf(\"dropbox filepath:%s\\n\",dbfp.String());\n run_script(s.String());\n}\n\nvoid\nadd_folder_to_dropbox(const char * filepath)\n{\n BString s;\n s << \"python db_mkdir.py \" << local_to_db_filepath(filepath);\n printf(\"local filepath: %s\\n\", filepath);\n printf(\"db filepath: %s\\n\", local_to_db_filepath(filepath).String());\n run_script(s.String());\n}\n\n\nvoid\nmoved_file(BMessage *msg) \n{\n \/\/is this file being move into or out of ~\/Dropbox?\n run_script(\"python db_ls.py\");\n}\n\nvoid\nupdate_file_in_dropbox(const char * filepath)\n{\n add_file_to_dropbox(filepath); \/\/just put it?\n}\n\nvoid\nApp::MessageReceived(BMessage *msg)\n{\n switch(msg->what)\n {\n case B_NODE_MONITOR:\n {\n printf(\"Received Node Monitor Alert\\n\");\n status_t err;\n int32 opcode;\n err = msg->FindInt32(\"opcode\",&opcode);\n if(err == B_OK)\n {\n printf(\"what:%d\\topcode:%d\\n\",msg->what, opcode);\n switch(opcode)\n {\n case B_ENTRY_CREATED:\n {\n printf(\"NEW FILE\\n\");\n entry_ref ref;\n BPath path; \n const char * name;\n msg->FindInt32(\"device\",&ref.device);\n msg->FindInt64(\"directory\",&ref.directory);\n msg->FindString(\"name\",&name);\n printf(\"name:%s\\n\",name);\n ref.set_name(name);\n BEntry new_file = BEntry(&ref);\n new_file.GetPath(&path);\n add_file_to_dropbox(path.Path());\n break;\n }\n case B_ENTRY_MOVED:\n {\n printf(\"MOVED FILE\\n\");\n moved_file(msg);\n break;\n }\n case B_ENTRY_REMOVED:\n {\n printf(\"DELETED FILE\\n\");\n node_ref nref, cref;\n msg->FindInt32(\"device\",&nref.device);\n msg->FindInt64(\"node\",&nref.node);\n BEntry *entryPtr;\n int32 ktr = 0;\n int32 limit = this->tracked_files.CountItems();\n while((entryPtr = (BEntry *)this->tracked_files.ItemAt(ktr++))&&(ktr<limit))\n {\n if(entryPtr->InitCheck() == B_OK)\n {\n entryPtr->GetNodeRef(&cref);\n }\n else\n {\n printf(\"OH NO!\\t%d\\n\",entryPtr->InitCheck());\n printf(\"OK = %d\\n\", B_OK);\n printf(\"Entry Not Found = %d\\n\",B_ENTRY_NOT_FOUND);\n printf(\"Bad Value = %d\\n\",B_BAD_VALUE);\n printf(\"No Init = %d\\n\", B_NO_INIT);\n return;\n }\n\n if(nref == cref)\n {\n BPath path;\n entryPtr->GetPath(&path);\n delete_file_on_dropbox(path.Path());\n break; \/\/break out of loop\n }\n }\n break;\n }\n case B_STAT_CHANGED:\n {\n printf(\"EDITED FILE\\n\");\n node_ref nref1,nref2;\n msg->FindInt32(\"device\",&nref1.device);\n msg->FindInt64(\"node\",&nref1.node);\n BEntry * entryPtr;\n int32 ktr = 0;\n while((entryPtr = (BEntry *)this->tracked_files.ItemAt(ktr++)))\n\n {\n entryPtr->GetNodeRef(&nref2);\n if(nref1 == nref2)\n {\n BPath path;\n entryPtr->GetPath(&path);\n update_file_in_dropbox(path.Path());\n break;\n }\n }\n break; \n }\n default:\n {\n printf(\"default case opcode...\\n\");\n }\n }\n }\n break;\n }\n default:\n {\n printf(\"default msg\\n\");\n BApplication::MessageReceived(msg);\n break;\n }\n }\n}\n\nint\nmain(void)\n{\n \/\/Haiku make window code\n App *app = new App();\n\n app->Run();\n delete app;\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"HexagonAlignLoads.h\"\n#include \"IRMutator.h\"\n#include \"IROperator.h\"\n#include \"Scope.h\"\n#include \"Bounds.h\"\n#include \"ModulusRemainder.h\"\n#include \"Simplify.h\"\nnamespace Halide {\nnamespace Internal {\nusing std::vector;\n\nclass HexagonAlignLoads : public IRMutator {\npublic:\n HexagonAlignLoads(Target t) : target(t) {}\nprivate:\n Target target;\n enum AlignCheck { Aligned, Unaligned, NoResult };\n\n \/** Alignment info for Int(32) variables in scope. *\/\n Scope<ModulusRemainder> alignment_info;\n using IRMutator::visit;\n ModulusRemainder get_alignment_info(Expr e) {\n return modulus_remainder(e, alignment_info);\n }\n\n Expr concat_and_shuffle(Expr vec_a, Expr vec_b, int start, int size) {\n Type dbl_t = vec_a.type().with_lanes(vec_a.type().lanes() * 2);\n Expr dbl_vec = Call::make(dbl_t, Call::concat_vectors, { vec_a, vec_b }, Call::PureIntrinsic);\n std::vector<Expr> args;\n args.push_back(dbl_vec);\n for (int i = start; i < start+size; i++) {\n args.push_back(i);\n }\n return Call::make(vec_a.type(), Call::shuffle_vector, args, Call::PureIntrinsic);\n }\n\n Expr concat_and_shuffle(Expr vec_a, Expr vec_b, std::vector<Expr> &indices) {\n Type dbl_t = vec_a.type().with_lanes(vec_a.type().lanes() * 2);\n Expr dbl_vec = Call::make(dbl_t, Call::concat_vectors, { vec_a, vec_b }, Call::PureIntrinsic);\n std::vector<Expr> args;\n args.push_back(dbl_vec);\n for (int i = 0; i < (int) indices.size(); i++) {\n args.push_back(indices[i]);\n }\n return Call::make(vec_a.type(), Call::shuffle_vector, args, Call::PureIntrinsic);\n }\n\n AlignCheck get_alignment_check(const Ramp *ramp, int host_alignment, int *lanes_off) {\n \/\/ We reason only in terms of lanes. Each lane is a vector element.\n \/\/ We want to know the following.\n \/\/ 1. if the base of buffer + ramp->base (i.e. the index) are aligned.\n \/\/ 2. if not, then how many lanes off an aligned address are they (returned in base_mod).\n \/\/ 3. if 2, then we create two loads and slice_vector them.\n \/\/ 4. rem_mod is used if the ramp base is 64*x + 65 and lanes is 64, then we are not\n \/\/ modulus_remainder.remainder lanes off, but we are only 1 lane off.\n int lanes = ramp->lanes;\n Expr base = ramp->base;\n \/\/ We know the base itself puts us off an aligned address by base_lanes_off\n \/\/ number of lanes.\n int base_lanes_off = mod_imp(host_alignment, lanes);\n ModulusRemainder mod_rem = get_alignment_info(base);\n if (mod_rem.modulus == 1 && mod_rem.remainder == 0) {\n \/\/ We can't reason about alignment.\n return AlignCheck::NoResult;\n }\n else {\n int base_mod = base_lanes_off + mod_imp(mod_rem.modulus, lanes);\n int rem_mod = mod_imp(mod_rem.remainder, lanes);\n if (!(base_mod + rem_mod)) return AlignCheck::Aligned;\n else {\n if (lanes_off) *lanes_off = base_mod + rem_mod;\n return AlignCheck::Unaligned;\n }\n }\n }\n void visit(const Load *op) {\n debug(4) << \"HexagonAlignLoads: Working on \" << (Expr) op << \"..\\n\";\n Expr index = mutate(op->index);\n if (op->type.is_vector()) {\n bool external = op->image.defined();\n if (external) {\n debug(4) << \"HexagonAlignLoads: Not dealing with an external image\\n\";\n debug(4) << (Expr) op << \"\\n\";\n expr = op;\n return;\n }\n else {\n const Ramp *ramp = index.as<Ramp>();\n const IntImm *stride = ramp ? ramp->stride.as<IntImm>() : NULL;\n \/\/ We will work only on natural vectors supported by the target.\n if (ramp->lanes != target.natural_vector_size(op->type)) {\n expr = op;\n return;\n }\n if (ramp && stride && stride->value == 1) {\n int lanes = ramp->lanes;\n int vec_size = target.natural_vector_size(Int(8));\n \/\/ If this is a parameter, the base_alignment should be host_alignment.\n \/\/ This cannot be an external image because we have already checked for\n \/\/ it. Otherwise, this is an internal buffers that is always aligned\n \/\/ to the natural vector width.\n int base_alignment = op->param.defined() ?\n op->param.host_alignment() : vec_size;\n int lanes_off;\n AlignCheck ac = get_alignment_check(ramp, base_alignment, &lanes_off);\n if (ac == AlignCheck::NoResult) {\n \/\/ We know nothing about alignment. Give up.\n \/\/ TODO: Fix this.\n debug(4) << \"HexagonAlignLoads: Cannot reason about alignment.\\n\";\n debug(4) << \"HexagonAlignLoads: Type: \" << op->type << \"\\n\";\n debug(4) << \"HexagonAlignLoads: Index: \" << index << \"\\n\";\n expr = op;\n return;\n }\n if (ac == AlignCheck::Aligned) {\n expr = op;\n debug(4) << \"HexagonAlignLoads: Encountered a perfectly aligned load.\\n\";\n debug(4) << \"HexagonAlignLoads: Type: \" << op->type << \"\\n\";\n debug(4) << \"HexagonAlignLoads: Index: \" << index << \"\\n\";\n return;\n } else {\n Expr base = ramp->base;\n const Add *add = base.as<Add>();\n const IntImm *b = add->b.as<IntImm>();\n if (!b) {\n \/\/ Should we be expecting the index to be in simplified\n \/\/ canonical form, i.e. expression + IntImm?\n debug(4) << \"HexagonAlignLoads: add->b is not a constant\\n\";\n debug(4) << \"HexagonAlignLoads: Type: \" << op->type << \"\\n\";\n debug(4) << \"HexagonAlignLoads: Index: \" << index << \"\\n\";\n expr = op;\n return;\n }\n Expr base_low = base - (lanes_off);\n Expr ramp_low = Ramp::make(simplify(base_low), 1, lanes);\n Expr ramp_high = Ramp::make(simplify(base_low + lanes), 1, lanes);\n Expr load_low = Load::make(op->type, op->name, ramp_low, op->image, op->param);\n Expr load_high = Load::make(op->type, op->name, ramp_high, op->image, op->param);\n \/\/ slice_vector considers the vectors in it to be concatenated and the result\n \/\/ is a vector containing as many lanes as the last argument and the vector\n \/\/ begins at lane number specified by the penultimate arg.\n \/\/ So, slice_vector(2, a, b, 126, 128) gives a vector of 128 lanes starting\n \/\/ from lanes 126 through 253 of the concatenated vector a.b.\n debug(4) << \"HexagonAlignLoads: Unaligned Load: Converting \" << (Expr) op << \" into ...\\n\";\n expr = concat_and_shuffle(load_low, load_high, lanes_off, lanes);\n debug(4) << \"... \" << expr << \"\\n\";\n return;\n }\n } else if (ramp && stride && stride->value == 2) {\n \/\/ We'll try to break this into two dense loads followed by a shuffle.\n Expr base_a = ramp->base, base_b = ramp->base + ramp->lanes;\n int b_shift = 0;\n int lanes = ramp->lanes;\n\n if (op->param.defined()) {\n \/\/ We need to be able to figure out if buffer_base + base_a is aligned. If not,\n \/\/ we may have to shift base_b left by one so as to not read beyond the end\n \/\/ of an external buffer.\n AlignCheck ac = get_alignment_check(ramp, op->param.host_alignment(), nullptr);\n\n if (ac == AlignCheck::Unaligned) {\n debug(4) << \"HexagonAlignLoads: base_a is unaligned: shifting base_b\\n\";\n debug(4) << \"HexagonAlignLoads: Type: \" << op->type << \"\\n\";\n debug(4) << \"HexagonAlignLoads: Index: \" << index << \"\\n\";\n base_b -= 1;\n b_shift = 1;\n }\n }\n\n Expr ramp_a = Ramp::make(base_a, 1, lanes);\n Expr ramp_b = Ramp::make(base_b, 1, lanes);\n Expr vec_a = mutate(Load::make(op->type, op->name, ramp_a, op->image, op->param));\n Expr vec_b = mutate(Load::make(op->type, op->name, ramp_b, op->image, op->param));\n\n std::vector<Expr> indices;\n for (int i = 0; i < lanes\/2; ++i) {\n indices.push_back(i*2);\n }\n for (int i = lanes\/2; i < lanes; ++i) {\n indices.push_back(i*2 + b_shift);\n }\n\n debug(4) << \"HexagonAlignLoads: Unaligned Load: Converting \" << (Expr) op << \" into ...\\n\";\n\n expr = concat_and_shuffle(vec_a, vec_b, indices);\n\n debug(4) << \"... \" << expr << \"\\n\";\n return;\n }else {\n expr = op;\n return;\n }\n }\n } else {\n expr = op;\n return;\n }\n }\n\n template<typename NodeType, typename LetType>\n void visit_let(NodeType &result, const LetType *op) {\n Expr value;\n if (op->value.type() == Int(32)) {\n alignment_info.push(op->name, modulus_remainder(op->value, alignment_info));\n value = op->value;\n } else {\n const Load *ld = op->value.template as<Load>();\n if (ld) value = mutate(op->value);\n else value = op->value;\n }\n\n NodeType body = mutate(op->body);\n if (op->value.type() == Int(32)) {\n alignment_info.pop(op->name);\n }\n result = LetType::make(op->name, value, body);\n }\n\n void visit(const Let *op) { visit_let(expr, op); }\n void visit(const LetStmt *op) { visit_let(stmt, op); }\n};\n\nStmt hexagon_align_loads(Stmt s, const Target &t) {\n return HexagonAlignLoads(t).mutate(s);\n }\n}\n}\n<commit_msg>Fix use of target.natural_vector_size for hexagon only and hexagon offload usage.<commit_after>#include \"HexagonAlignLoads.h\"\n#include \"IRMutator.h\"\n#include \"IROperator.h\"\n#include \"Scope.h\"\n#include \"Bounds.h\"\n#include \"ModulusRemainder.h\"\n#include \"Simplify.h\"\nnamespace Halide {\nnamespace Internal {\nusing std::vector;\n\nclass HexagonAlignLoads : public IRMutator {\npublic:\n HexagonAlignLoads(Target t, int vs) : target(t), vector_size(vs) {}\nprivate:\n Target target;\n enum AlignCheck { Aligned, Unaligned, NoResult };\n \/\/ size of a vector in bytes.\n int vector_size;\n \/** Alignment info for Int(32) variables in scope. *\/\n Scope<ModulusRemainder> alignment_info;\n using IRMutator::visit;\n ModulusRemainder get_alignment_info(Expr e) {\n return modulus_remainder(e, alignment_info);\n }\n int natural_vector_lanes(Type t) {\n return vector_size \/ t.bytes();\n }\n Expr concat_and_shuffle(Expr vec_a, Expr vec_b, int start, int size) {\n Type dbl_t = vec_a.type().with_lanes(vec_a.type().lanes() * 2);\n Expr dbl_vec = Call::make(dbl_t, Call::concat_vectors, { vec_a, vec_b }, Call::PureIntrinsic);\n std::vector<Expr> args;\n args.push_back(dbl_vec);\n for (int i = start; i < start+size; i++) {\n args.push_back(i);\n }\n return Call::make(vec_a.type(), Call::shuffle_vector, args, Call::PureIntrinsic);\n }\n\n Expr concat_and_shuffle(Expr vec_a, Expr vec_b, std::vector<Expr> &indices) {\n Type dbl_t = vec_a.type().with_lanes(vec_a.type().lanes() * 2);\n Expr dbl_vec = Call::make(dbl_t, Call::concat_vectors, { vec_a, vec_b }, Call::PureIntrinsic);\n std::vector<Expr> args;\n args.push_back(dbl_vec);\n for (int i = 0; i < (int) indices.size(); i++) {\n args.push_back(indices[i]);\n }\n return Call::make(vec_a.type(), Call::shuffle_vector, args, Call::PureIntrinsic);\n }\n\n AlignCheck get_alignment_check(const Ramp *ramp, int host_alignment, int *lanes_off) {\n \/\/ We reason only in terms of lanes. Each lane is a vector element.\n \/\/ We want to know the following.\n \/\/ 1. if the base of buffer + ramp->base (i.e. the index) are aligned.\n \/\/ 2. if not, then how many lanes off an aligned address are they (returned in base_mod).\n \/\/ 3. if 2, then we create two loads and slice_vector them.\n \/\/ 4. rem_mod is used if the ramp base is 64*x + 65 and lanes is 64, then we are not\n \/\/ modulus_remainder.remainder lanes off, but we are only 1 lane off.\n int lanes = ramp->lanes;\n Expr base = ramp->base;\n \/\/ We know the base itself puts us off an aligned address by base_lanes_off\n \/\/ number of lanes.\n int base_lanes_off = mod_imp(host_alignment, lanes);\n ModulusRemainder mod_rem = get_alignment_info(base);\n if (mod_rem.modulus == 1 && mod_rem.remainder == 0) {\n \/\/ We can't reason about alignment.\n return AlignCheck::NoResult;\n }\n else {\n int base_mod = base_lanes_off + mod_imp(mod_rem.modulus, lanes);\n int rem_mod = mod_imp(mod_rem.remainder, lanes);\n if (!(base_mod + rem_mod)) return AlignCheck::Aligned;\n else {\n if (lanes_off) *lanes_off = base_mod + rem_mod;\n return AlignCheck::Unaligned;\n }\n }\n }\n void visit(const Load *op) {\n debug(4) << \"HexagonAlignLoads: Working on \" << (Expr) op << \"..\\n\";\n Expr index = mutate(op->index);\n if (op->type.is_vector()) {\n bool external = op->image.defined();\n if (external) {\n debug(4) << \"HexagonAlignLoads: Not dealing with an external image\\n\";\n debug(4) << (Expr) op << \"\\n\";\n expr = op;\n return;\n }\n else {\n const Ramp *ramp = index.as<Ramp>();\n const IntImm *stride = ramp ? ramp->stride.as<IntImm>() : NULL;\n \/\/ We will work only on natural vectors supported by the target.\n if (ramp->lanes != natural_vector_lanes(op->type)) {\n expr = op;\n return;\n }\n if (ramp && stride && stride->value == 1) {\n int lanes = ramp->lanes;\n \/\/ If this is a parameter, the base_alignment should be host_alignment.\n \/\/ This cannot be an external image because we have already checked for\n \/\/ it. Otherwise, this is an internal buffers that is always aligned\n \/\/ to the natural vector width.\n int base_alignment = op->param.defined() ?\n op->param.host_alignment() : vector_size;\n int lanes_off;\n AlignCheck ac = get_alignment_check(ramp, base_alignment, &lanes_off);\n if (ac == AlignCheck::NoResult) {\n \/\/ We know nothing about alignment. Give up.\n \/\/ TODO: Fix this.\n debug(4) << \"HexagonAlignLoads: Cannot reason about alignment.\\n\";\n debug(4) << \"HexagonAlignLoads: Type: \" << op->type << \"\\n\";\n debug(4) << \"HexagonAlignLoads: Index: \" << index << \"\\n\";\n expr = op;\n return;\n }\n if (ac == AlignCheck::Aligned) {\n expr = op;\n debug(4) << \"HexagonAlignLoads: Encountered a perfectly aligned load.\\n\";\n debug(4) << \"HexagonAlignLoads: Type: \" << op->type << \"\\n\";\n debug(4) << \"HexagonAlignLoads: Index: \" << index << \"\\n\";\n return;\n } else {\n Expr base = ramp->base;\n const Add *add = base.as<Add>();\n const IntImm *b = add->b.as<IntImm>();\n if (!b) {\n \/\/ Should we be expecting the index to be in simplified\n \/\/ canonical form, i.e. expression + IntImm?\n debug(4) << \"HexagonAlignLoads: add->b is not a constant\\n\";\n debug(4) << \"HexagonAlignLoads: Type: \" << op->type << \"\\n\";\n debug(4) << \"HexagonAlignLoads: Index: \" << index << \"\\n\";\n expr = op;\n return;\n }\n Expr base_low = base - (lanes_off);\n Expr ramp_low = Ramp::make(simplify(base_low), 1, lanes);\n Expr ramp_high = Ramp::make(simplify(base_low + lanes), 1, lanes);\n Expr load_low = Load::make(op->type, op->name, ramp_low, op->image, op->param);\n Expr load_high = Load::make(op->type, op->name, ramp_high, op->image, op->param);\n \/\/ slice_vector considers the vectors in it to be concatenated and the result\n \/\/ is a vector containing as many lanes as the last argument and the vector\n \/\/ begins at lane number specified by the penultimate arg.\n \/\/ So, slice_vector(2, a, b, 126, 128) gives a vector of 128 lanes starting\n \/\/ from lanes 126 through 253 of the concatenated vector a.b.\n debug(4) << \"HexagonAlignLoads: Unaligned Load: Converting \" << (Expr) op << \" into ...\\n\";\n expr = concat_and_shuffle(load_low, load_high, lanes_off, lanes);\n debug(4) << \"... \" << expr << \"\\n\";\n return;\n }\n } else if (ramp && stride && stride->value == 2) {\n \/\/ We'll try to break this into two dense loads followed by a shuffle.\n Expr base_a = ramp->base, base_b = ramp->base + ramp->lanes;\n int b_shift = 0;\n int lanes = ramp->lanes;\n\n if (op->param.defined()) {\n \/\/ We need to be able to figure out if buffer_base + base_a is aligned. If not,\n \/\/ we may have to shift base_b left by one so as to not read beyond the end\n \/\/ of an external buffer.\n AlignCheck ac = get_alignment_check(ramp, op->param.host_alignment(), nullptr);\n\n if (ac == AlignCheck::Unaligned) {\n debug(4) << \"HexagonAlignLoads: base_a is unaligned: shifting base_b\\n\";\n debug(4) << \"HexagonAlignLoads: Type: \" << op->type << \"\\n\";\n debug(4) << \"HexagonAlignLoads: Index: \" << index << \"\\n\";\n base_b -= 1;\n b_shift = 1;\n }\n }\n\n Expr ramp_a = Ramp::make(base_a, 1, lanes);\n Expr ramp_b = Ramp::make(base_b, 1, lanes);\n Expr vec_a = mutate(Load::make(op->type, op->name, ramp_a, op->image, op->param));\n Expr vec_b = mutate(Load::make(op->type, op->name, ramp_b, op->image, op->param));\n\n std::vector<Expr> indices;\n for (int i = 0; i < lanes\/2; ++i) {\n indices.push_back(i*2);\n }\n for (int i = lanes\/2; i < lanes; ++i) {\n indices.push_back(i*2 + b_shift);\n }\n\n debug(4) << \"HexagonAlignLoads: Unaligned Load: Converting \" << (Expr) op << \" into ...\\n\";\n\n expr = concat_and_shuffle(vec_a, vec_b, indices);\n\n debug(4) << \"... \" << expr << \"\\n\";\n return;\n }else {\n expr = op;\n return;\n }\n }\n } else {\n expr = op;\n return;\n }\n }\n\n template<typename NodeType, typename LetType>\n void visit_let(NodeType &result, const LetType *op) {\n Expr value;\n if (op->value.type() == Int(32)) {\n alignment_info.push(op->name, modulus_remainder(op->value, alignment_info));\n value = op->value;\n } else {\n const Load *ld = op->value.template as<Load>();\n if (ld) value = mutate(op->value);\n else value = op->value;\n }\n\n NodeType body = mutate(op->body);\n if (op->value.type() == Int(32)) {\n alignment_info.pop(op->name);\n }\n result = LetType::make(op->name, value, body);\n }\n\n void visit(const Let *op) { visit_let(expr, op); }\n void visit(const LetStmt *op) { visit_let(stmt, op); }\n void visit(const For *op) {\n if (op->device_api == DeviceAPI::Hexagon) {\n if (target.has_feature(Target::HVX_128)) {\n vector_size = 128;\n }\n else if (target.has_feature(Target::HVX_64)) {\n vector_size = 64;\n } else {\n internal_error << \"Unknown HVX mode\";\n }\n }\n IRMutator::visit(op);\n return;\n }\n};\n\nStmt hexagon_align_loads(Stmt s, const Target &t) {\n return HexagonAlignLoads(t, t.natural_vector_size(Int(8))).mutate(s);\n }\n}\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ This file is part of BlueSky\n\/\/ \n\/\/ BlueSky is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU Lesser General Public License\n\/\/ as published by the Free Software Foundation; either version 3\n\/\/ of the License, or (at your option) any later version.\n\/\/ \n\/\/ BlueSky is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n\/\/ GNU General Public License for more details.\n\/\/ \n\/\/ You should have received a copy of the GNU General Public License\n\/\/ along with BlueSky; if not, see <http:\/\/www.gnu.org\/licenses\/>.\n\n#include \"bs_kernel.h\"\n#include \"bs_kernel_tools.h\"\n#include \"bs_tree.h\"\n#include \"py_bs_exports.h\"\n#include \"py_smart_ptr.h\"\n\n#include <boost\/python\/overloads.hpp>\n#include <iostream>\n\nnamespace {\nusing namespace blue_sky;\nusing namespace std;\n\nstruct kernel_handle {\n\tkernel_handle() : k_(&give_kernel::Instance()) {}\n\tkernel_handle(kernel*) : k_(&give_kernel::Instance()) {}\n\n\tkernel* k_;\n};\n\nkernel* get_pointer(const kernel_handle& kf) {\n\treturn kf.k_;\n}\n\nstruct py_kernel_tools {\n\tstatic void print_loaded_types() {\n\t\tcout << kernel_tools::print_loaded_types();\n\t}\n\n\tstatic void walk_tree() {\n\t\tcout << kernel_tools::walk_tree();\n\t}\n\n\tstatic void print_registered_instances() {\n\t\tcout << kernel_tools::print_registered_instances();\n\t}\n};\n\n}\n\nnamespace boost { namespace python {\n\ntemplate< >\nstruct pointee< kernel_handle > {\n\ttypedef blue_sky::kernel type;\n};\n\n}}\n\nnamespace blue_sky { namespace python {\n\nBOOST_PYTHON_MEMBER_FUNCTION_OVERLOADS(create_object_overl, create_object, 1, 3);\nBOOST_PYTHON_MEMBER_FUNCTION_OVERLOADS(load_plugin_overl, load_plugin, 2, 3);\nBOOST_PYTHON_MEMBER_FUNCTION_OVERLOADS(load_plugins_overl, LoadPlugins, 0, 1);\n\nvoid py_bind_kernel() {\n\t\/\/ plugin_types overloads\n\tkernel::types_enum (kernel::*plugin_types1)(const plugin_descriptor&) const = &kernel::plugin_types;\n\tkernel::types_enum (kernel::*plugin_types2)(const std::string&) const = &kernel::plugin_types;\n\t\/\/ create_object overloads\n\tsp_obj (kernel::*create_object1)(const type_descriptor&, bool, bs_type_ctor_param) const = &kernel::create_object;\n\tsp_obj (kernel::*create_object2)(const std::string&, bool, bs_type_ctor_param) const = &kernel::create_object;\n\n\t{\n\t\t\/\/ main kernel binding\n\t\tscope k_scope = class_<\n\t\t\tkernel,\n\t\t\tkernel_handle,\n\t\t\tboost::noncopyable\n\t\t\t>\n\t\t(\"kernel_iface\", no_init)\n\t\t\t.def(\"loaded_plugins\", &kernel::loaded_plugins)\n\t\t\t.def(\"plugin_types\", plugin_types1)\n\t\t\t.def(\"plugin_types\", plugin_types2)\n\t\t\t.def(\"find_type\", &kernel::find_type)\n\t\t\t.def(\"registeres_types\", &kernel::registered_types)\n\t\t\t.def(\"register_type\", &kernel::register_type)\n\t\t\t.def(\"create_type\", create_object1, create_object_overl())\n\t\t\t.def(\"create_type\", create_object2, create_object_overl())\n\t\t\t.def(\"create_object_copy\", &kernel::create_object_copy)\n\t\t\t.def(\"register_instance\", &kernel::register_instance)\n\t\t\t.def(\"free_instance\", &kernel::free_instance)\n\t\t\t.def(\"tree_gc\", &kernel::tree_gc)\n\t\t\t.def(\"objinst_cnt\", &kernel::objinst_cnt)\n\t\t\t.def(\"create_storage\", &kernel::create_storage)\n\t\t\t.def(\"close_storage\", &kernel::close_storage)\n\t\t\t.def(\"load_plugin\", &kernel::load_plugin, load_plugin_overl())\n\t\t\t.def(\"unload_lugin\", &kernel::unload_plugin)\n\t\t\t.def(\"load_plugins\", &kernel::LoadPlugins, load_plugins_overl())\n\t\t\t.def(\"unload_plugins\", &kernel::UnloadPlugins)\n\t\t\t.def(\"pert_str_dt\", &kernel::pert_str_dt)\n\t\t\t.def(\"pert_idx_dt\", &kernel::pert_idx_dt)\n\t\t\t.def(\"get_last_error\", &kernel::get_last_error)\n\t\t\t.def(\"add_task\", &kernel::add_task)\n\t\t\t.def(\"is_tq_empty\", &kernel::is_tq_empty)\n\t\t\t.def(\"wait_tq_empty\", &kernel::wait_tq_empty)\n\t\t\t.add_property(\"tree_root_link\", &kernel::bs_root)\n\t\t\t.def(\"reg_signal\", &kernel::reg_signal)\n\t\t\t.def(\"rem_signal\", &kernel::rem_signal)\n\t\t\t\/\/.def(\"get_memory_manager\", &kernel::get_memory_manager)\n\t\t\t\/\/.def(\"get_log\", &kernel::get_log)\n\t\t\t\/\/.def(\"get_tlog\", &kernel::get_tlog)\n\t\t\t.def(\"register_disconnector\", &kernel::register_disconnector)\n\t\t\t.def(\"unregister_disconnector\", &kernel::unregister_disconnector)\n\t\t;\n\n\t\t\/\/ quick access to root node\n\t\tk_scope.attr(\"tree_root\") = BS_KERNEL.bs_root()->node();\n\n\t\t\/\/ kernel_tools binding\n\t\tclass_< py_kernel_tools >(\"tools\", no_init)\n\t\t\t.def(\"print_loaded_types\", &py_kernel_tools::print_loaded_types)\n\t\t\t.def(\"walk_tree\", &py_kernel_tools::walk_tree)\n\t\t\t.def(\"print_registered_instances\", &py_kernel_tools::print_registered_instances)\n\t\t\t.staticmethod(\"print_loaded_types\")\n\t\t\t.staticmethod(\"walk_tree\")\n\t\t\t.staticmethod(\"print_registered_instances\")\n\t\t;\n\t}\n\n\t\/\/ shortcat to access kernel\n\t\/\/ function form - like in C++\n\tdef(\"give_kernel\", &give_kernel::Instance, return_value_policy< reference_existing_object >());\n\t\/\/ like global attribute - no need to write '()'\n\tscope().attr(\"kernel\") = kernel_handle();\n}\n\n}} \t\/\/ eof namespace blue_sky::python\n\n<commit_msg>python: rename create_type -> create_object in Python<commit_after>\/\/ This file is part of BlueSky\n\/\/ \n\/\/ BlueSky is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU Lesser General Public License\n\/\/ as published by the Free Software Foundation; either version 3\n\/\/ of the License, or (at your option) any later version.\n\/\/ \n\/\/ BlueSky is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n\/\/ GNU General Public License for more details.\n\/\/ \n\/\/ You should have received a copy of the GNU General Public License\n\/\/ along with BlueSky; if not, see <http:\/\/www.gnu.org\/licenses\/>.\n\n#include \"bs_kernel.h\"\n#include \"bs_kernel_tools.h\"\n#include \"bs_tree.h\"\n#include \"py_bs_exports.h\"\n#include \"py_smart_ptr.h\"\n\n#include <boost\/python\/overloads.hpp>\n#include <iostream>\n\nnamespace {\nusing namespace blue_sky;\nusing namespace std;\n\nstruct kernel_handle {\n\tkernel_handle() : k_(&give_kernel::Instance()) {}\n\tkernel_handle(kernel*) : k_(&give_kernel::Instance()) {}\n\n\tkernel* k_;\n};\n\nkernel* get_pointer(const kernel_handle& kf) {\n\treturn kf.k_;\n}\n\nstruct py_kernel_tools {\n\tstatic void print_loaded_types() {\n\t\tcout << kernel_tools::print_loaded_types();\n\t}\n\n\tstatic void walk_tree() {\n\t\tcout << kernel_tools::walk_tree();\n\t}\n\n\tstatic void print_registered_instances() {\n\t\tcout << kernel_tools::print_registered_instances();\n\t}\n};\n\n}\n\nnamespace boost { namespace python {\n\ntemplate< >\nstruct pointee< kernel_handle > {\n\ttypedef blue_sky::kernel type;\n};\n\n}}\n\nnamespace blue_sky { namespace python {\n\nBOOST_PYTHON_MEMBER_FUNCTION_OVERLOADS(create_object_overl, create_object, 1, 3);\nBOOST_PYTHON_MEMBER_FUNCTION_OVERLOADS(load_plugin_overl, load_plugin, 2, 3);\nBOOST_PYTHON_MEMBER_FUNCTION_OVERLOADS(load_plugins_overl, LoadPlugins, 0, 1);\n\nvoid py_bind_kernel() {\n\t\/\/ plugin_types overloads\n\tkernel::types_enum (kernel::*plugin_types1)(const plugin_descriptor&) const = &kernel::plugin_types;\n\tkernel::types_enum (kernel::*plugin_types2)(const std::string&) const = &kernel::plugin_types;\n\t\/\/ create_object overloads\n\tsp_obj (kernel::*create_object1)(const type_descriptor&, bool, bs_type_ctor_param) const = &kernel::create_object;\n\tsp_obj (kernel::*create_object2)(const std::string&, bool, bs_type_ctor_param) const = &kernel::create_object;\n\n\t{\n\t\t\/\/ main kernel binding\n\t\tscope k_scope = class_<\n\t\t\tkernel,\n\t\t\tkernel_handle,\n\t\t\tboost::noncopyable\n\t\t\t>\n\t\t(\"kernel_iface\", no_init)\n\t\t\t.def(\"loaded_plugins\", &kernel::loaded_plugins)\n\t\t\t.def(\"plugin_types\", plugin_types1)\n\t\t\t.def(\"plugin_types\", plugin_types2)\n\t\t\t.def(\"find_type\", &kernel::find_type)\n\t\t\t.def(\"registeres_types\", &kernel::registered_types)\n\t\t\t.def(\"register_type\", &kernel::register_type)\n\t\t\t.def(\"create_object\", create_object1, create_object_overl())\n\t\t\t.def(\"create_object\", create_object2, create_object_overl())\n\t\t\t.def(\"create_object_copy\", &kernel::create_object_copy)\n\t\t\t.def(\"register_instance\", &kernel::register_instance)\n\t\t\t.def(\"free_instance\", &kernel::free_instance)\n\t\t\t.def(\"tree_gc\", &kernel::tree_gc)\n\t\t\t.def(\"objinst_cnt\", &kernel::objinst_cnt)\n\t\t\t.def(\"create_storage\", &kernel::create_storage)\n\t\t\t.def(\"close_storage\", &kernel::close_storage)\n\t\t\t.def(\"load_plugin\", &kernel::load_plugin, load_plugin_overl())\n\t\t\t.def(\"unload_lugin\", &kernel::unload_plugin)\n\t\t\t.def(\"load_plugins\", &kernel::LoadPlugins, load_plugins_overl())\n\t\t\t.def(\"unload_plugins\", &kernel::UnloadPlugins)\n\t\t\t.def(\"pert_str_dt\", &kernel::pert_str_dt)\n\t\t\t.def(\"pert_idx_dt\", &kernel::pert_idx_dt)\n\t\t\t.def(\"get_last_error\", &kernel::get_last_error)\n\t\t\t.def(\"add_task\", &kernel::add_task)\n\t\t\t.def(\"is_tq_empty\", &kernel::is_tq_empty)\n\t\t\t.def(\"wait_tq_empty\", &kernel::wait_tq_empty)\n\t\t\t.add_property(\"tree_root_link\", &kernel::bs_root)\n\t\t\t.def(\"reg_signal\", &kernel::reg_signal)\n\t\t\t.def(\"rem_signal\", &kernel::rem_signal)\n\t\t\t\/\/.def(\"get_memory_manager\", &kernel::get_memory_manager)\n\t\t\t\/\/.def(\"get_log\", &kernel::get_log)\n\t\t\t\/\/.def(\"get_tlog\", &kernel::get_tlog)\n\t\t\t.def(\"register_disconnector\", &kernel::register_disconnector)\n\t\t\t.def(\"unregister_disconnector\", &kernel::unregister_disconnector)\n\t\t;\n\n\t\t\/\/ quick access to root node\n\t\tk_scope.attr(\"tree_root\") = BS_KERNEL.bs_root()->node();\n\n\t\t\/\/ kernel_tools binding\n\t\tclass_< py_kernel_tools >(\"tools\", no_init)\n\t\t\t.def(\"print_loaded_types\", &py_kernel_tools::print_loaded_types)\n\t\t\t.def(\"walk_tree\", &py_kernel_tools::walk_tree)\n\t\t\t.def(\"print_registered_instances\", &py_kernel_tools::print_registered_instances)\n\t\t\t.staticmethod(\"print_loaded_types\")\n\t\t\t.staticmethod(\"walk_tree\")\n\t\t\t.staticmethod(\"print_registered_instances\")\n\t\t;\n\t}\n\n\t\/\/ shortcat to access kernel\n\t\/\/ function form - like in C++\n\tdef(\"give_kernel\", &give_kernel::Instance, return_value_policy< reference_existing_object >());\n\t\/\/ like global attribute - no need to write '()'\n\tscope().attr(\"kernel\") = kernel_handle();\n}\n\n}} \t\/\/ eof namespace blue_sky::python\n\n<|endoftext|>"} {"text":"<commit_before>\/*\nCopyright 2016-2017 Nia Catlin\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\nhttp:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\n\/*\nThe targets combo box at the top of the interface.\nAlso handles creating new targets.\n*\/\n\n#include \"stdafx.h\"\n#include \"targetcombo.h\"\n#include \"maintabbox.h\"\n#include <boost\\filesystem.hpp>\n#include \"ui_rgat.h\"\n\ntargetCombo::targetCombo(QWidget *parent)\n\t: QComboBox(parent)\n{\n\n}\n\n\ntargetCombo::~targetCombo()\n{\n}\n\nvoid targetCombo::setActiveTarget(binaryTarget * target)\n{\n\tif (!targets->exists(target) || (target == clientState->activeBinary)) return;\n\n\tclientState->activeBinary = target;\n\tclientState->clearActiveGraph();\n\tclientState->activeTrace = NULL;\n\tmainTabs->changeTarget(target, eVisualiseTab);\n\n\tUi::rgatClass *ui = (Ui::rgatClass *)clientState->ui;\n\n\tui->traceGatherTab->fillAnalyseTab(target);\n}\n\nvoid targetCombo::setActiveTarget(int index)\n{\n\tif (index == -1 || paths.size() <= index) return;\n\n\tboost::filesystem::path activePath = paths.at(index);\n\tif (activePath.size() == 0) return;\n\n\tbinaryTarget * target;\n\n\ttargets->getTargetByPath(activePath, &target);\n\tif (target)\n\t\tsetActiveTarget(target);\n}\n\nvoid targetCombo::addTargetToInterface(binaryTarget *target, bool newBinary)\n{\n\tUi::rgatClass *ui = (Ui::rgatClass *)clientState->ui;\n\tboost::filesystem::path filepath = target->path();\n\tif (newBinary)\n\t{\n\n\t\tif (paths.empty())\n\t\t{\n\t\t\t\/\/get rid of the [hey you should add a target] text\n\t\t\tremoveItem(0);\n\t\t}\n\n\t\tpaths.push_back(target->path());\n\n\t\tstringstream targetSS;\n\t\ttargetSS << \"[\" << paths.size()-1 << \"]\" << \" \" << filepath.string();\n\t\tQString targetDisplayString = QString::fromStdString(targetSS.str());\n\n\n\t\taddItem(targetDisplayString);\n\t\tsetCurrentIndex(count() - 1);\n\n\t\tui->staticDynamicStack->setCurrentIndex(eDynamicTabs);\n\n\t\tui->dynamicAnalysisContentsTab->setCurrentIndex(eStartTraceTab);\n\t}\n\telse\n\t{\n\t\tauto vecpos = std::find(paths.begin(), paths.end(), filepath);\n\t\tassert(vecpos != paths.end());\n\t\tsetCurrentIndex(vecpos - paths.begin());\n\t\tui->dynamicAnalysisContentsTab->setCurrentIndex(eStartTraceTab);\n\t}\n\n\tui->traceGatherTab->fillAnalyseTab(target);\n\n}\n\n\nvoid targetCombo::addNewTarget()\n{\n\t\/\/crash when right click in this dialog https:\/\/bugreports.qt.io\/browse\/QTBUG-33119?page=com.atlassian.jira.plugin.system.issuetabpanels%3Aall-tabpanel\n\tQString fileName = QFileDialog::getOpenFileName(this,\n\t\ttr(\"Select new target\"), clientState->config.getLastPathString(),\n\t\ttr(\"Executable (*.exe);;Library (*.dll);;All Files (*.*)\"));\n\n\tboost::filesystem::path filepath(fileName.toStdString());\n\tif (!boost::filesystem::exists(filepath))\n\t\treturn;\n\n\tbinaryTarget *target;\n\n\tbool newBinary = targets->getTargetByPath(filepath, &target);\n\n\taddTargetToInterface(target, newBinary);\n\n\tclientState->config.updateLastPath(filepath);\n\n\n}<commit_msg>main part of ui disabled until a target is selected because a lot of it is uninitialised without a binary<commit_after>\/*\nCopyright 2016-2017 Nia Catlin\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\nhttp:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\n\/*\nThe targets combo box at the top of the interface.\nAlso handles creating new targets.\n*\/\n\n#include \"stdafx.h\"\n#include \"targetcombo.h\"\n#include \"maintabbox.h\"\n#include <boost\\filesystem.hpp>\n#include \"ui_rgat.h\"\n\ntargetCombo::targetCombo(QWidget *parent)\n\t: QComboBox(parent)\n{\n\n}\n\n\ntargetCombo::~targetCombo()\n{\n}\n\nvoid targetCombo::setActiveTarget(binaryTarget * target)\n{\n\tif (!targets->exists(target) || (target == clientState->activeBinary)) return;\n\n\tclientState->activeBinary = target;\n\tclientState->clearActiveGraph();\n\tclientState->activeTrace = NULL;\n\tmainTabs->changeTarget(target, eVisualiseTab);\n\n\tUi::rgatClass *ui = (Ui::rgatClass *)clientState->ui;\n\n\tui->traceGatherTab->fillAnalyseTab(target);\n}\n\nvoid targetCombo::setActiveTarget(int index)\n{\n\tif (index == -1 || paths.size() <= index) return;\n\n\tboost::filesystem::path activePath = paths.at(index);\n\tif (activePath.size() == 0) return;\n\n\tbinaryTarget * target;\n\n\ttargets->getTargetByPath(activePath, &target);\n\tif (target)\n\t\tsetActiveTarget(target);\n}\n\nvoid targetCombo::addTargetToInterface(binaryTarget *target, bool newBinary)\n{\n\tUi::rgatClass *ui = (Ui::rgatClass *)clientState->ui;\n\n\tif (!ui->staticDynamicStack->isEnabled())\n\t\tui->staticDynamicStack->setEnabled(true);\n\n\tboost::filesystem::path filepath = target->path();\n\tif (newBinary)\n\t{\n\n\t\tif (paths.empty())\n\t\t{\n\t\t\t\/\/get rid of the [hey you should add a target] text\n\t\t\tremoveItem(0);\n\t\t}\n\n\t\tpaths.push_back(target->path());\n\n\t\tstringstream targetSS;\n\t\ttargetSS << \"[\" << paths.size()-1 << \"]\" << \" \" << filepath.string();\n\t\tQString targetDisplayString = QString::fromStdString(targetSS.str());\n\n\n\t\taddItem(targetDisplayString);\n\t\tsetCurrentIndex(count() - 1);\n\n\t\tui->staticDynamicStack->setCurrentIndex(eDynamicTabs);\n\n\t\tui->dynamicAnalysisContentsTab->setCurrentIndex(eStartTraceTab);\n\t}\n\telse\n\t{\n\t\tauto vecpos = std::find(paths.begin(), paths.end(), filepath);\n\t\tassert(vecpos != paths.end());\n\t\tsetCurrentIndex(vecpos - paths.begin());\n\t\tui->dynamicAnalysisContentsTab->setCurrentIndex(eStartTraceTab);\n\t}\n\n\tui->traceGatherTab->fillAnalyseTab(target);\n\n}\n\n\nvoid targetCombo::addNewTarget()\n{\n\t\/\/crash when right click in this dialog https:\/\/bugreports.qt.io\/browse\/QTBUG-33119?page=com.atlassian.jira.plugin.system.issuetabpanels%3Aall-tabpanel\n\tQString fileName = QFileDialog::getOpenFileName(this,\n\t\ttr(\"Select new target\"), clientState->config.getLastPathString(),\n\t\ttr(\"Executable (*.exe);;Library (*.dll);;All Files (*.*)\"));\n\n\tboost::filesystem::path filepath(fileName.toStdString());\n\tif (!boost::filesystem::exists(filepath))\n\t\treturn;\n\n\tbinaryTarget *target;\n\n\tbool newBinary = targets->getTargetByPath(filepath, &target);\n\n\taddTargetToInterface(target, newBinary);\n\n\tclientState->config.updateLastPath(filepath);\n\n\n}<|endoftext|>"} {"text":"<commit_before>#include \"Fraction.h\"\n#include \"..\/Data.h\"\n#include \"..\/Ensemble.h\"\n#include \"..\/Variables\/Variable.h\"\n\nMeasureFraction::MeasureFraction(const Options& iOptions, const Data& iData) :\n Measure(iOptions, iData),\n mX(Global::MV),\n mUseMin(false),\n mUseMax(false) {\n \/\/! Use this threshold \n iOptions.getValue(\"x\", mX);\n \/\/! Set the threshold to the forecast variable's minimum value (e.g. 0 mm for preciptation)\n iOptions.getValue(\"useMin\", mUseMin);\n \/\/! Set the threshold to the forecast variable's maximum value (e.g. 100 % for RH)\n iOptions.getValue(\"useMax\", mUseMax);\n if(!Global::isValid(mX) + !mUseMin + !mUseMax != 1) {\n std::stringstream ss;\n ss << \"At least (and at most) one of 'x', 'useMin', and 'useMax', must be specified\";\n Global::logger->write(ss.str(), Logger::error);\n }\n}\n\nfloat MeasureFraction::measureCore(const Ensemble& iEnsemble) const {\n int counter = 0;\n int total = 0;\n\n \/\/ Determine where on the variable-axis the discrete point is\n float point = mX;\n if(mUseMin)\n point = Variable::get(iEnsemble.getVariable())->getMin();\n else if(mUseMax)\n point = Variable::get(iEnsemble.getVariable())->getMax();\n assert(Global::isValid(point));\n\n for(int i = 0; i < iEnsemble.size(); i++) {\n if(Global::isValid(iEnsemble[i])) {\n if(iEnsemble[i] == point) {\n counter++;\n }\n total++;\n }\n }\n float frac = Global::MV;\n if(total > 0)\n frac = (float) counter \/ total;\n return frac;\n}\n<commit_msg>Fixes the checking of options to MeasureFraction<commit_after>#include \"Fraction.h\"\n#include \"..\/Data.h\"\n#include \"..\/Ensemble.h\"\n#include \"..\/Variables\/Variable.h\"\n\nMeasureFraction::MeasureFraction(const Options& iOptions, const Data& iData) :\n Measure(iOptions, iData),\n mX(Global::MV),\n mUseMin(false),\n mUseMax(false) {\n \/\/! Use this threshold \n iOptions.getValue(\"x\", mX);\n \/\/! Set the threshold to the forecast variable's minimum value (e.g. 0 mm for preciptation)\n iOptions.getValue(\"useMin\", mUseMin);\n \/\/! Set the threshold to the forecast variable's maximum value (e.g. 100 % for RH)\n iOptions.getValue(\"useMax\", mUseMax);\n if(Global::isValid(mX) + mUseMin + mUseMax != 1) {\n std::stringstream ss;\n ss << \"At least (and at most) one of 'x', 'useMin', and 'useMax', must be specified\";\n Global::logger->write(ss.str(), Logger::error);\n }\n}\n\nfloat MeasureFraction::measureCore(const Ensemble& iEnsemble) const {\n int counter = 0;\n int total = 0;\n\n \/\/ Determine where on the variable-axis the discrete point is\n float point = mX;\n if(mUseMin)\n point = Variable::get(iEnsemble.getVariable())->getMin();\n else if(mUseMax)\n point = Variable::get(iEnsemble.getVariable())->getMax();\n assert(Global::isValid(point));\n\n for(int i = 0; i < iEnsemble.size(); i++) {\n if(Global::isValid(iEnsemble[i])) {\n if(iEnsemble[i] == point) {\n counter++;\n }\n total++;\n }\n }\n float frac = Global::MV;\n if(total > 0)\n frac = (float) counter \/ total;\n return frac;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*****************************************************************************\n *\n * This file is part of Mapnik (c++ mapping toolkit)\n *\n * Copyright (C) 2011 Artem Pavlenko\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n *\n *****************************************************************************\/\n\n\/\/ mapnik\n#include <mapnik\/debug.hpp>\n#include <mapnik\/graphics.hpp>\n#include <mapnik\/image_util.hpp>\n#include <mapnik\/global.hpp>\n#include <mapnik\/color.hpp>\n\n\/\/ agg\n#include \"agg_rendering_buffer.h\"\n#include \"agg_pixfmt_rgba.h\"\n\n\/\/ boost\n#include <boost\/scoped_array.hpp>\n\n\/\/ cairo\n#ifdef HAVE_CAIRO\n#include <mapnik\/cairo_context.hpp>\n#endif\n\nnamespace mapnik\n{\nimage_32::image_32(int width,int height)\n :width_(width),\n height_(height),\n data_(width,height),\n painted_(false),\n premultiplied_(false) {}\n\nimage_32::image_32(const image_32& rhs)\n :width_(rhs.width_),\n height_(rhs.height_),\n data_(rhs.data_),\n painted_(rhs.painted_),\n premultiplied_(rhs.premultiplied_) {}\n\n#ifdef HAVE_CAIRO\nimage_32::image_32(cairo_surface_ptr const& surface)\n :width_(cairo_image_surface_get_width(&*surface)),\n height_(cairo_image_surface_get_height(&*surface)),\n data_(width_, height_),\n premultiplied_(false)\n{\n painted_ = true;\n if ( cairo_image_surface_get_format(&*surface) != CAIRO_FORMAT_ARGB32)\n {\n MAPNIK_LOG_WARN(graphics) << \"Unable to convert this Cairo format\";\n throw;\n }\n\n int stride = cairo_image_surface_get_stride(&*surface) \/ 4;\n\n boost::scoped_array<unsigned int> out_row(new unsigned int[width_]);\n const unsigned int *in_row = (const unsigned int *)cairo_image_surface_get_data(&*surface);\n\n for (unsigned int row = 0; row < height_; row++, in_row += stride)\n {\n for (unsigned int column = 0; column < width_; column++)\n {\n unsigned int in = in_row[column];\n unsigned int a = (in >> 24) & 0xff;\n unsigned int r = (in >> 16) & 0xff;\n unsigned int g = (in >> 8) & 0xff;\n unsigned int b = (in >> 0) & 0xff;\n\n#define DE_ALPHA(x) do { \\\n if (a == 0) x = 0; \\\n else x = x * 255 \/ a; \\\n if (x > 255) x = 255; \\\n } while(0)\n\n DE_ALPHA(r);\n DE_ALPHA(g);\n DE_ALPHA(b);\n\n out_row[column] = color(r, g, b, a).rgba();\n }\n data_.setRow(row, out_row.get(), width_);\n }\n}\n#endif\n\nimage_32::~image_32() {}\n\nvoid image_32::set_grayscale_to_alpha()\n{\n for (unsigned int y = 0; y < height_; ++y)\n {\n unsigned int* row_from = data_.getRow(y);\n for (unsigned int x = 0; x < width_; ++x)\n {\n unsigned rgba = row_from[x];\n \/\/ TODO - big endian support\n unsigned r = rgba & 0xff;\n unsigned g = (rgba >> 8 ) & 0xff;\n unsigned b = (rgba >> 16) & 0xff;\n\n \/\/ magic numbers for grayscale\n unsigned a = static_cast<unsigned>(std::ceil((r * .3) + (g * .59) + (b * .11)));\n\n row_from[x] = (a << 24)| (255 << 16) | (255 << 8) | (255) ;\n }\n }\n}\n\nvoid image_32::set_color_to_alpha(const color& c)\n{\n for (unsigned y = 0; y < height_; ++y)\n {\n unsigned int* row_from = data_.getRow(y);\n for (unsigned x = 0; x < width_; ++x)\n {\n unsigned rgba = row_from[x];\n unsigned r = rgba & 0xff;\n unsigned g = (rgba >> 8 ) & 0xff;\n unsigned b = (rgba >> 16) & 0xff;\n if (r == c.red() && g == c.green() && b == c.blue())\n {\n row_from[x] = 0;\n }\n }\n }\n}\n\nvoid image_32::set_alpha(float opacity)\n{\n for (unsigned int y = 0; y < height_; ++y)\n {\n unsigned int* row_to = data_.getRow(y);\n for (unsigned int x = 0; x < width_; ++x)\n {\n unsigned rgba = row_to[x];\n\n#ifdef MAPNIK_BIG_ENDIAN\n unsigned a0 = (rgba & 0xff);\n unsigned a1 = int( (rgba & 0xff) * opacity );\n\n if (a0 == a1) continue;\n\n unsigned r = (rgba >> 24) & 0xff;\n unsigned g = (rgba >> 16 ) & 0xff;\n unsigned b = (rgba >> 8) & 0xff;\n\n row_to[x] = (a1) | (b << 8) | (g << 16) | (r << 24) ;\n\n#else\n unsigned a0 = (rgba >> 24) & 0xff;\n unsigned a1 = int( ((rgba >> 24) & 0xff) * opacity );\n \/\/unsigned a1 = opacity;\n if (a0 == a1) continue;\n\n unsigned r = rgba & 0xff;\n unsigned g = (rgba >> 8 ) & 0xff;\n unsigned b = (rgba >> 16) & 0xff;\n\n row_to[x] = (a1 << 24)| (b << 16) | (g << 8) | (r) ;\n#endif\n }\n }\n}\n\nvoid image_32::set_background(const color& c)\n{\n background_=c;\n data_.set(background_->rgba());\n}\n\nboost::optional<color> const& image_32::get_background() const\n{\n return background_;\n}\n\nvoid image_32::premultiply()\n{\n agg::rendering_buffer buffer(data_.getBytes(),width_,height_,width_ * 4);\n agg::pixfmt_rgba32 pixf(buffer);\n pixf.premultiply();\n premultiplied_ = true;\n}\n\nvoid image_32::demultiply()\n{\n agg::rendering_buffer buffer(data_.getBytes(),width_,height_,width_ * 4);\n agg::pixfmt_rgba32 pixf(buffer);\n pixf.demultiply();\n premultiplied_ = false;\n}\n\nvoid image_32::composite_pixel(unsigned op, int x,int y, unsigned c, unsigned cover, double opacity)\n{\n typedef agg::rgba8 color_type;\n typedef color_type::value_type value_type;\n typedef agg::order_rgba order_type;\n typedef agg::comp_op_adaptor_rgba<color_type,order_type> blender_type;\n\n if (checkBounds(x,y))\n {\n unsigned rgba = data_(x,y);\n unsigned ca = (unsigned)(((c >> 24) & 0xff) * opacity);\n unsigned cb = (c >> 16 ) & 0xff;\n unsigned cg = (c >> 8) & 0xff;\n unsigned cr = (c & 0xff);\n blender_type::blend_pix(op, (value_type*)&rgba, cr, cg, cb, ca, cover);\n data_(x,y) = rgba;\n }\n}\n\n}\n<commit_msg>use pixfmt pre for the sake of clarity<commit_after>\/*****************************************************************************\n *\n * This file is part of Mapnik (c++ mapping toolkit)\n *\n * Copyright (C) 2011 Artem Pavlenko\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n *\n *****************************************************************************\/\n\n\/\/ mapnik\n#include <mapnik\/debug.hpp>\n#include <mapnik\/graphics.hpp>\n#include <mapnik\/image_util.hpp>\n#include <mapnik\/global.hpp>\n#include <mapnik\/color.hpp>\n\n\/\/ agg\n#include \"agg_rendering_buffer.h\"\n#include \"agg_pixfmt_rgba.h\"\n#include \"agg_color_rgba.h\"\n\n\/\/ boost\n#include <boost\/scoped_array.hpp>\n\n\/\/ cairo\n#ifdef HAVE_CAIRO\n#include <mapnik\/cairo_context.hpp>\n#endif\n\nnamespace mapnik\n{\nimage_32::image_32(int width,int height)\n :width_(width),\n height_(height),\n data_(width,height),\n painted_(false),\n premultiplied_(false) {}\n\nimage_32::image_32(const image_32& rhs)\n :width_(rhs.width_),\n height_(rhs.height_),\n data_(rhs.data_),\n painted_(rhs.painted_),\n premultiplied_(rhs.premultiplied_) {}\n\n#ifdef HAVE_CAIRO\nimage_32::image_32(cairo_surface_ptr const& surface)\n :width_(cairo_image_surface_get_width(&*surface)),\n height_(cairo_image_surface_get_height(&*surface)),\n data_(width_, height_),\n premultiplied_(false)\n{\n painted_ = true;\n if ( cairo_image_surface_get_format(&*surface) != CAIRO_FORMAT_ARGB32)\n {\n MAPNIK_LOG_WARN(graphics) << \"Unable to convert this Cairo format\";\n throw;\n }\n\n int stride = cairo_image_surface_get_stride(&*surface) \/ 4;\n\n boost::scoped_array<unsigned int> out_row(new unsigned int[width_]);\n const unsigned int *in_row = (const unsigned int *)cairo_image_surface_get_data(&*surface);\n\n for (unsigned int row = 0; row < height_; row++, in_row += stride)\n {\n for (unsigned int column = 0; column < width_; column++)\n {\n unsigned int in = in_row[column];\n unsigned int a = (in >> 24) & 0xff;\n unsigned int r = (in >> 16) & 0xff;\n unsigned int g = (in >> 8) & 0xff;\n unsigned int b = (in >> 0) & 0xff;\n\n#define DE_ALPHA(x) do { \\\n if (a == 0) x = 0; \\\n else x = x * 255 \/ a; \\\n if (x > 255) x = 255; \\\n } while(0)\n\n DE_ALPHA(r);\n DE_ALPHA(g);\n DE_ALPHA(b);\n\n out_row[column] = color(r, g, b, a).rgba();\n }\n data_.setRow(row, out_row.get(), width_);\n }\n}\n#endif\n\nimage_32::~image_32() {}\n\nvoid image_32::set_grayscale_to_alpha()\n{\n for (unsigned int y = 0; y < height_; ++y)\n {\n unsigned int* row_from = data_.getRow(y);\n for (unsigned int x = 0; x < width_; ++x)\n {\n unsigned rgba = row_from[x];\n \/\/ TODO - big endian support\n unsigned r = rgba & 0xff;\n unsigned g = (rgba >> 8 ) & 0xff;\n unsigned b = (rgba >> 16) & 0xff;\n\n \/\/ magic numbers for grayscale\n unsigned a = static_cast<unsigned>(std::ceil((r * .3) + (g * .59) + (b * .11)));\n\n row_from[x] = (a << 24)| (255 << 16) | (255 << 8) | (255) ;\n }\n }\n}\n\nvoid image_32::set_color_to_alpha(const color& c)\n{\n for (unsigned y = 0; y < height_; ++y)\n {\n unsigned int* row_from = data_.getRow(y);\n for (unsigned x = 0; x < width_; ++x)\n {\n unsigned rgba = row_from[x];\n unsigned r = rgba & 0xff;\n unsigned g = (rgba >> 8 ) & 0xff;\n unsigned b = (rgba >> 16) & 0xff;\n if (r == c.red() && g == c.green() && b == c.blue())\n {\n row_from[x] = 0;\n }\n }\n }\n}\n\nvoid image_32::set_alpha(float opacity)\n{\n for (unsigned int y = 0; y < height_; ++y)\n {\n unsigned int* row_to = data_.getRow(y);\n for (unsigned int x = 0; x < width_; ++x)\n {\n unsigned rgba = row_to[x];\n\n#ifdef MAPNIK_BIG_ENDIAN\n unsigned a0 = (rgba & 0xff);\n unsigned a1 = int( (rgba & 0xff) * opacity );\n\n if (a0 == a1) continue;\n\n unsigned r = (rgba >> 24) & 0xff;\n unsigned g = (rgba >> 16 ) & 0xff;\n unsigned b = (rgba >> 8) & 0xff;\n\n row_to[x] = (a1) | (b << 8) | (g << 16) | (r << 24) ;\n\n#else\n unsigned a0 = (rgba >> 24) & 0xff;\n unsigned a1 = int( ((rgba >> 24) & 0xff) * opacity );\n \/\/unsigned a1 = opacity;\n if (a0 == a1) continue;\n\n unsigned r = rgba & 0xff;\n unsigned g = (rgba >> 8 ) & 0xff;\n unsigned b = (rgba >> 16) & 0xff;\n\n row_to[x] = (a1 << 24)| (b << 16) | (g << 8) | (r) ;\n#endif\n }\n }\n}\n\nvoid image_32::set_background(const color& c)\n{\n background_=c;\n data_.set(background_->rgba());\n}\n\nboost::optional<color> const& image_32::get_background() const\n{\n return background_;\n}\n\nvoid image_32::premultiply()\n{\n agg::rendering_buffer buffer(data_.getBytes(),width_,height_,width_ * 4);\n agg::pixfmt_rgba32 pixf(buffer);\n pixf.premultiply();\n premultiplied_ = true;\n}\n\nvoid image_32::demultiply()\n{\n agg::rendering_buffer buffer(data_.getBytes(),width_,height_,width_ * 4);\n agg::pixfmt_rgba32_pre pixf(buffer);\n pixf.demultiply();\n premultiplied_ = false;\n}\n\nvoid image_32::composite_pixel(unsigned op, int x,int y, unsigned c, unsigned cover, double opacity)\n{\n typedef agg::rgba8 color_type;\n typedef color_type::value_type value_type;\n typedef agg::order_rgba order_type;\n typedef agg::comp_op_adaptor_rgba<color_type,order_type> blender_type;\n\n if (checkBounds(x,y))\n {\n unsigned rgba = data_(x,y);\n unsigned ca = (unsigned)(((c >> 24) & 0xff) * opacity);\n unsigned cb = (c >> 16 ) & 0xff;\n unsigned cg = (c >> 8) & 0xff;\n unsigned cr = (c & 0xff);\n blender_type::blend_pix(op, (value_type*)&rgba, cr, cg, cb, ca, cover);\n data_(x,y) = rgba;\n }\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"k\/context.h\"\n\n#include \"etl\/array_count.h\"\n#include \"etl\/armv7m\/mpu.h\"\n#include \"etl\/armv7m\/types.h\"\n\n#include \"common\/message.h\"\n#include \"common\/descriptor.h\"\n\n#include \"k\/address_range.h\"\n#include \"k\/context_layout.h\"\n#include \"k\/object_table.h\"\n#include \"k\/registers.h\"\n#include \"k\/reply_sender.h\"\n#include \"k\/scheduler.h\"\n#include \"k\/unprivileged.h\"\n\nusing etl::armv7m::Word;\n\nnamespace k {\n\n\/*******************************************************************************\n * Context-specific stuff\n *\/\n\nContext::Context()\n : _stack{nullptr},\n _keys{},\n _ctx_item{this},\n _sender_item{this},\n _priority{0},\n _state{State::stopped},\n _saved_brand{0} {}\n\nvoid Context::nullify_exchanged_keys(unsigned preserved) {\n \/\/ Had to do this somewhere, this is as good a place as any.\n \/\/ (The fields in question are private, so this can't be at top level.)\n \/\/ (Putting it in the ctor hits the ill-defined non-trivial ctor rules.)\n static_assert(K_CONTEXT_SAVE_OFFSET == __builtin_offsetof(Context, _save),\n \"K_CONTEXT_SAVE_OFFSET is wrong\");\n\n \/\/ Right, actual implementation now:\n for (unsigned i = preserved; i < config::n_message_keys; ++i) {\n _keys[i] = Key::null();\n }\n}\n\nDescriptor Context::get_descriptor() const {\n return _save.sys.m.d0;\n}\n\nKeys & Context::get_message_keys() {\n return *reinterpret_cast<Keys *>(_keys);\n}\n\nvoid Context::do_syscall() {\n switch (get_descriptor().get_sysnum()) {\n case 0: \/\/ IPC\n do_ipc();\n break;\n\n case 1: \/\/ Copy Key\n do_copy_key();\n break;\n \n default:\n do_bad_sys();\n break;\n }\n}\n\nvoid Context::do_ipc() {\n auto d = get_descriptor();\n\n \/\/ Perform first phase of IPC.\n if (d.get_send_enabled()) {\n key(d.get_target()).deliver_from(this);\n } else if (d.get_receive_enabled()) {\n key(d.get_source()).get()->deliver_to(this);\n } else {\n \/\/ Simply return with registers unchanged.\n \/\/ (Weirdo.)\n }\n\n do_deferred_switch();\n}\n\nvoid Context::do_copy_key() {\n auto d = get_descriptor();\n key(d.get_target()) = key(d.get_source());\n}\n\nvoid Context::do_bad_sys() {\n put_message(0, Message::failure(Exception::bad_syscall));\n}\n\nvoid Context::complete_receive(BlockingSender * sender) {\n sender->on_blocked_delivery_accepted(_save.sys.m,\n _save.sys.b,\n get_message_keys());\n}\n\nvoid Context::complete_receive(Exception e, uint32_t param) {\n _save.sys.m = Message::failure(e, param);\n _save.sys.b = 0;\n nullify_exchanged_keys();\n}\n\nvoid Context::block_in_receive(List<Context> & list) {\n \/\/ TODO should we decide to permit non-blocking recieves... here's the spot.\n _ctx_item.unlink();\n list.insert(&_ctx_item);\n _state = State::receiving;\n\n pend_switch();\n}\n\nvoid Context::complete_blocked_receive(Brand brand, Sender * sender) {\n runnable.insert(&_ctx_item);\n _state = State::runnable;\n\n sender->on_delivery_accepted(_save.sys.m, get_message_keys());\n _save.sys.b = brand;\n\n pend_switch();\n}\n\nvoid Context::complete_blocked_receive(Exception e, uint32_t param) {\n runnable.insert(&_ctx_item);\n _state = State::runnable;\n\n complete_receive(e, param);\n\n pend_switch();\n}\n\nvoid Context::put_message(Brand brand, Message const & m) {\n _save.sys.m = m.sanitized();\n _save.sys.b = brand;\n}\n\nvoid Context::apply_to_mpu() {\n using etl::armv7m::mpu;\n\n for (unsigned i = 0; i < config::n_task_regions; ++i) {\n mpu.write_rnr(i);\n auto object = _memory_regions[i].get();\n if (object->is_address_range()) {\n auto range = static_cast<AddressRange *>(object);\n auto region = range->get_region_for_brand(_memory_regions[i].get_brand());\n mpu.write_rbar(region.rbar);\n mpu.write_rasr(region.rasr);\n } else {\n mpu.write_rasr(0);\n mpu.write_rbar(0);\n }\n }\n}\n\nvoid Context::make_runnable() {\n switch (_state) {\n case State::sending:\n on_blocked_delivery_failed(Exception::would_block);\n break;\n\n case State::receiving:\n complete_blocked_receive(Exception::would_block);\n break;\n\n case State::stopped:\n runnable.insert(&_ctx_item);\n _state = State::runnable;\n break;\n\n case State::runnable:\n break;\n }\n}\n\n\n\/*******************************************************************************\n * Implementation of Sender and BlockingSender\n *\/\n\nPriority Context::get_priority() const {\n return _priority;\n}\n\nvoid Context::on_delivery_accepted(Message & m, Keys & k) {\n auto d = get_descriptor();\n\n m = _save.sys.m.sanitized();\n\n k.keys[0] = d.is_call() ? make_reply_key() : Key::null();\n for (unsigned ki = 1; ki < config::n_message_keys; ++ki) {\n k.keys[ki] = key(ki);\n }\n\n if (d.get_receive_enabled()) {\n auto & source = d.is_call() ? k.keys[0]\n : key(d.get_source());\n source.get()->deliver_to(this);\n }\n}\n\nvoid Context::on_delivery_failed(Exception e, uint32_t param) {\n \/\/ Deliver the exception.\n _save.sys.m = Message::failure(e, param);\n _save.sys.b = 0;\n \/\/ Avoid looking like we delivered any pre-existing keys.\n nullify_exchanged_keys();\n}\n\nvoid Context::block_in_send(Brand brand, List<BlockingSender> & list) {\n ETL_ASSERT(this == current);\n\n if (get_descriptor().get_block()) {\n _saved_brand = brand;\n list.insert(&_sender_item);\n _ctx_item.unlink();\n _state = State::sending;\n\n pend_switch();\n } else {\n \/\/ Unprivileged code is unwilling to block for delivery.\n on_delivery_failed(Exception::would_block);\n }\n}\n\nvoid Context::on_blocked_delivery_accepted(Message & m, Brand & b, Keys & k) {\n runnable.insert(&_ctx_item);\n _state = State::runnable;\n\n b = _saved_brand;\n on_delivery_accepted(m, k);\n pend_switch();\n}\n\nvoid Context::on_blocked_delivery_failed(Exception e, uint32_t param) {\n runnable.insert(&_ctx_item);\n _state = State::runnable;\n\n on_delivery_failed(e, param);\n pend_switch();\n}\n\nKey Context::make_reply_key() const {\n auto maybe_key = object_table[_reply_gate_index].ptr->make_key(0);\n if (maybe_key) return maybe_key.ref();\n return Key::null();\n}\n\n\n\/*******************************************************************************\n * Implementation of Context protocol.\n *\/\n\nusing IpcImpl = void (Context::*)(Brand, Message const &, Keys &);\n\nvoid Context::deliver_from(Brand brand, Sender * sender) {\n Message m;\n Keys k;\n sender->on_delivery_accepted(m, k);\n\n static constexpr IpcImpl dispatch[] {\n &Context::do_read_register,\n &Context::do_write_register,\n &Context::do_read_key,\n &Context::do_write_key,\n &Context::do_read_region,\n &Context::do_write_region,\n &Context::do_make_runnable,\n &Context::do_read_priority,\n &Context::do_write_priority,\n };\n if (m.d0.get_selector() < etl::array_count(dispatch)) {\n auto fn = dispatch[m.d0.get_selector()];\n (this->*fn)(brand, m, k);\n } else {\n do_badop(m, k);\n }\n}\n\nvoid Context::do_read_register(Brand,\n Message const & arg,\n Keys & k) {\n ReplySender reply_sender;\n switch (arg.d1) {\n case 13:\n reply_sender.set_message({\n Descriptor::zero(),\n reinterpret_cast<Word>(_stack),\n });\n break;\n\n#define GP_EF(n) \\\n case n: { \\\n apply_to_mpu(); \\\n auto r = uload(&_stack->r ## n); \\\n current->apply_to_mpu(); \\\n if (r) { \\\n reply_sender.set_message({ \\\n Descriptor::zero(), \\\n r.ref(), \\\n }); \\\n } else { \\\n reply_sender.set_message(Message::failure(Exception::fault)); \\\n } \\\n break; \\\n }\n GP_EF(0);\n GP_EF(1);\n GP_EF(2);\n GP_EF(3);\n GP_EF(12);\n GP_EF(14);\n GP_EF(15);\n#undef GP_EF\n\n case 16: {\n apply_to_mpu();\n auto r = uload(&_stack->psr);\n current->apply_to_mpu();\n if (r) {\n reply_sender.set_message({\n Descriptor::zero(),\n r.ref(),\n });\n } else {\n reply_sender.set_message(Message::failure(Exception::fault));\n }\n break;\n }\n\n case 4:\n case 5:\n case 6:\n case 7:\n case 8:\n case 9:\n case 10:\n case 11:\n reply_sender.set_message({Descriptor::zero(), _save.raw[arg.d1 - 4]});\n break;\n\n default:\n reply_sender.set_message(Message::failure(Exception::index_out_of_range));\n break;\n }\n\n k.keys[0].deliver_from(&reply_sender);\n}\n\nvoid Context::do_write_register(Brand,\n Message const & arg,\n Keys & k) {\n auto r = arg.d1;\n auto v = arg.d2;\n\n ReplySender reply_sender;\n\n switch (r) {\n case 13:\n _stack = reinterpret_cast<decltype(_stack)>(v);\n break;\n\n#define GP_EF(n) \\\n case n: { \\\n if (!ustore(&_stack->r ## n, v)) { \\\n reply_sender.set_message(Message::failure(Exception::fault)); \\\n } \\\n break; \\\n }\n GP_EF(0);\n GP_EF(1);\n GP_EF(2);\n GP_EF(3);\n GP_EF(12);\n GP_EF(14);\n GP_EF(15);\n#undef GP\n\n case 16: {\n if (!ustore(&_stack->psr, v)) {\n reply_sender.set_message(Message::failure(Exception::fault));\n }\n break;\n }\n\n case 4:\n case 5:\n case 6:\n case 7:\n case 8:\n case 9:\n case 10:\n case 11:\n _save.raw[r - 4] = v;\n break;\n\n default:\n reply_sender.set_message(Message::failure(Exception::index_out_of_range));\n break;\n }\n\n k.keys[0].deliver_from(&reply_sender);\n}\n\nvoid Context::do_read_key(Brand,\n Message const & arg,\n Keys & k) {\n auto r = arg.d1;\n\n ReplySender reply_sender;\n if (r >= config::n_task_keys) {\n reply_sender.set_message(Message::failure(Exception::index_out_of_range));\n } else {\n reply_sender.set_key(1, key(r));\n }\n k.keys[0].deliver_from(&reply_sender);\n}\n\nvoid Context::do_write_key(Brand,\n Message const & arg,\n Keys & k) {\n auto r = arg.d1;\n\n auto & reply = k.keys[0];\n auto & new_key = k.keys[1];\n\n ReplySender reply_sender;\n if (r >= config::n_task_keys) {\n reply_sender.set_message(Message::failure(Exception::index_out_of_range));\n } else {\n key(r) = new_key;\n }\n reply.deliver_from(&reply_sender);\n}\n\nvoid Context::do_read_region(Brand,\n Message const & arg,\n Keys & k) {\n auto n = arg.d1;\n\n ReplySender reply_sender;\n if (n < config::n_task_regions) {\n reply_sender.set_key(1, _memory_regions[n]);\n } else {\n reply_sender.set_message(Message::failure(Exception::index_out_of_range));\n }\n k.keys[0].deliver_from(&reply_sender);\n}\n\nvoid Context::do_write_region(Brand,\n Message const & arg,\n Keys & k) {\n auto n = arg.d1;\n auto & reply = k.keys[0];\n auto & object_key = k.keys[1];\n\n ReplySender reply_sender;\n\n if (n < config::n_task_regions) {\n _memory_regions[n] = object_key;\n } else {\n reply_sender.set_message(Message::failure(Exception::index_out_of_range));\n }\n\n if (current == this) apply_to_mpu();\n\n reply.deliver_from(&reply_sender);\n}\n\nvoid Context::do_make_runnable(Brand, Message const & arg, Keys & k) {\n make_runnable();\n pend_switch();\n\n ReplySender reply_sender;\n k.keys[0].deliver_from(&reply_sender);\n}\n\nvoid Context::do_read_priority(Brand, Message const & arg, Keys & k) {\n ReplySender reply_sender;\n reply_sender.set_message({Descriptor::zero(), _priority});\n k.keys[0].deliver_from(&reply_sender);\n}\n\nvoid Context::do_write_priority(Brand, Message const & arg, Keys & k) {\n auto priority = arg.d1;\n\n ReplySender reply_sender;\n\n if (priority < config::n_priorities) {\n _priority = priority;\n \n if (_ctx_item.is_linked()) _ctx_item.reinsert();\n if (_sender_item.is_linked()) _sender_item.reinsert();\n } else {\n reply_sender.set_message(Message::failure(Exception::index_out_of_range));\n }\n\n k.keys[0].deliver_from(&reply_sender);\n}\n\n} \/\/ namespace k\n<commit_msg>k\/context: encourage tail calls.<commit_after>#include \"k\/context.h\"\n\n#include \"etl\/array_count.h\"\n#include \"etl\/armv7m\/mpu.h\"\n#include \"etl\/armv7m\/types.h\"\n\n#include \"common\/message.h\"\n#include \"common\/descriptor.h\"\n\n#include \"k\/address_range.h\"\n#include \"k\/context_layout.h\"\n#include \"k\/object_table.h\"\n#include \"k\/registers.h\"\n#include \"k\/reply_sender.h\"\n#include \"k\/scheduler.h\"\n#include \"k\/unprivileged.h\"\n\nusing etl::armv7m::Word;\n\nnamespace k {\n\n\/*******************************************************************************\n * Context-specific stuff\n *\/\n\nContext::Context()\n : _stack{nullptr},\n _keys{},\n _ctx_item{this},\n _sender_item{this},\n _priority{0},\n _state{State::stopped},\n _saved_brand{0} {}\n\nvoid Context::nullify_exchanged_keys(unsigned preserved) {\n \/\/ Had to do this somewhere, this is as good a place as any.\n \/\/ (The fields in question are private, so this can't be at top level.)\n \/\/ (Putting it in the ctor hits the ill-defined non-trivial ctor rules.)\n static_assert(K_CONTEXT_SAVE_OFFSET == __builtin_offsetof(Context, _save),\n \"K_CONTEXT_SAVE_OFFSET is wrong\");\n\n \/\/ Right, actual implementation now:\n for (unsigned i = preserved; i < config::n_message_keys; ++i) {\n _keys[i] = Key::null();\n }\n}\n\nDescriptor Context::get_descriptor() const {\n return _save.sys.m.d0;\n}\n\nKeys & Context::get_message_keys() {\n return *reinterpret_cast<Keys *>(_keys);\n}\n\nvoid Context::do_syscall() {\n switch (get_descriptor().get_sysnum()) {\n case 0: \/\/ IPC\n do_ipc();\n break;\n\n case 1: \/\/ Copy Key\n do_copy_key();\n break;\n \n default:\n do_bad_sys();\n break;\n }\n}\n\nvoid Context::do_ipc() {\n auto d = get_descriptor();\n\n \/\/ Perform first phase of IPC.\n if (d.get_send_enabled()) {\n key(d.get_target()).deliver_from(this);\n } else if (d.get_receive_enabled()) {\n key(d.get_source()).get()->deliver_to(this);\n } else {\n \/\/ Simply return with registers unchanged.\n \/\/ (Weirdo.)\n }\n\n do_deferred_switch();\n}\n\nvoid Context::do_copy_key() {\n auto d = get_descriptor();\n key(d.get_target()) = key(d.get_source());\n}\n\nvoid Context::do_bad_sys() {\n put_message(0, Message::failure(Exception::bad_syscall));\n}\n\nvoid Context::complete_receive(BlockingSender * sender) {\n sender->on_blocked_delivery_accepted(_save.sys.m,\n _save.sys.b,\n get_message_keys());\n}\n\nvoid Context::complete_receive(Exception e, uint32_t param) {\n _save.sys.m = Message::failure(e, param);\n _save.sys.b = 0;\n nullify_exchanged_keys();\n}\n\nvoid Context::block_in_receive(List<Context> & list) {\n \/\/ TODO should we decide to permit non-blocking recieves... here's the spot.\n _ctx_item.unlink();\n list.insert(&_ctx_item);\n _state = State::receiving;\n\n pend_switch();\n}\n\nvoid Context::complete_blocked_receive(Brand brand, Sender * sender) {\n runnable.insert(&_ctx_item);\n _state = State::runnable;\n _save.sys.b = brand;\n\n pend_switch();\n\n sender->on_delivery_accepted(_save.sys.m, get_message_keys());\n}\n\nvoid Context::complete_blocked_receive(Exception e, uint32_t param) {\n runnable.insert(&_ctx_item);\n _state = State::runnable;\n\n pend_switch();\n\n complete_receive(e, param);\n}\n\nvoid Context::put_message(Brand brand, Message const & m) {\n _save.sys.m = m.sanitized();\n _save.sys.b = brand;\n}\n\nvoid Context::apply_to_mpu() {\n using etl::armv7m::mpu;\n\n for (unsigned i = 0; i < config::n_task_regions; ++i) {\n mpu.write_rnr(i);\n auto object = _memory_regions[i].get();\n if (object->is_address_range()) {\n auto range = static_cast<AddressRange *>(object);\n auto region = range->get_region_for_brand(_memory_regions[i].get_brand());\n mpu.write_rbar(region.rbar);\n mpu.write_rasr(region.rasr);\n } else {\n mpu.write_rasr(0);\n mpu.write_rbar(0);\n }\n }\n}\n\nvoid Context::make_runnable() {\n switch (_state) {\n case State::sending:\n on_blocked_delivery_failed(Exception::would_block);\n break;\n\n case State::receiving:\n complete_blocked_receive(Exception::would_block);\n break;\n\n case State::stopped:\n runnable.insert(&_ctx_item);\n _state = State::runnable;\n break;\n\n case State::runnable:\n break;\n }\n}\n\n\n\/*******************************************************************************\n * Implementation of Sender and BlockingSender\n *\/\n\nPriority Context::get_priority() const {\n return _priority;\n}\n\nvoid Context::on_delivery_accepted(Message & m, Keys & k) {\n auto d = get_descriptor();\n\n m = _save.sys.m.sanitized();\n\n k.keys[0] = d.is_call() ? make_reply_key() : Key::null();\n for (unsigned ki = 1; ki < config::n_message_keys; ++ki) {\n k.keys[ki] = key(ki);\n }\n\n if (d.get_receive_enabled()) {\n auto & source = d.is_call() ? k.keys[0]\n : key(d.get_source());\n source.get()->deliver_to(this);\n }\n}\n\nvoid Context::on_delivery_failed(Exception e, uint32_t param) {\n \/\/ Deliver the exception.\n _save.sys.m = Message::failure(e, param);\n _save.sys.b = 0;\n \/\/ Avoid looking like we delivered any pre-existing keys.\n nullify_exchanged_keys();\n}\n\nvoid Context::block_in_send(Brand brand, List<BlockingSender> & list) {\n ETL_ASSERT(this == current);\n\n if (get_descriptor().get_block()) {\n _saved_brand = brand;\n list.insert(&_sender_item);\n _ctx_item.unlink();\n _state = State::sending;\n\n pend_switch();\n } else {\n \/\/ Unprivileged code is unwilling to block for delivery.\n on_delivery_failed(Exception::would_block);\n }\n}\n\nvoid Context::on_blocked_delivery_accepted(Message & m, Brand & b, Keys & k) {\n runnable.insert(&_ctx_item);\n _state = State::runnable;\n\n b = _saved_brand;\n pend_switch();\n on_delivery_accepted(m, k);\n}\n\nvoid Context::on_blocked_delivery_failed(Exception e, uint32_t param) {\n runnable.insert(&_ctx_item);\n _state = State::runnable;\n pend_switch();\n\n on_delivery_failed(e, param);\n}\n\nKey Context::make_reply_key() const {\n auto maybe_key = object_table[_reply_gate_index].ptr->make_key(0);\n if (maybe_key) return maybe_key.ref();\n return Key::null();\n}\n\n\n\/*******************************************************************************\n * Implementation of Context protocol.\n *\/\n\nusing IpcImpl = void (Context::*)(Brand, Message const &, Keys &);\n\nvoid Context::deliver_from(Brand brand, Sender * sender) {\n Message m;\n Keys k;\n sender->on_delivery_accepted(m, k);\n\n static constexpr IpcImpl dispatch[] {\n &Context::do_read_register,\n &Context::do_write_register,\n &Context::do_read_key,\n &Context::do_write_key,\n &Context::do_read_region,\n &Context::do_write_region,\n &Context::do_make_runnable,\n &Context::do_read_priority,\n &Context::do_write_priority,\n };\n if (m.d0.get_selector() < etl::array_count(dispatch)) {\n auto fn = dispatch[m.d0.get_selector()];\n (this->*fn)(brand, m, k);\n } else {\n do_badop(m, k);\n }\n}\n\nvoid Context::do_read_register(Brand,\n Message const & arg,\n Keys & k) {\n ReplySender reply_sender;\n switch (arg.d1) {\n case 13:\n reply_sender.set_message({\n Descriptor::zero(),\n reinterpret_cast<Word>(_stack),\n });\n break;\n\n#define GP_EF(n) \\\n case n: { \\\n apply_to_mpu(); \\\n auto r = uload(&_stack->r ## n); \\\n current->apply_to_mpu(); \\\n if (r) { \\\n reply_sender.set_message({ \\\n Descriptor::zero(), \\\n r.ref(), \\\n }); \\\n } else { \\\n reply_sender.set_message(Message::failure(Exception::fault)); \\\n } \\\n break; \\\n }\n GP_EF(0);\n GP_EF(1);\n GP_EF(2);\n GP_EF(3);\n GP_EF(12);\n GP_EF(14);\n GP_EF(15);\n#undef GP_EF\n\n case 16: {\n apply_to_mpu();\n auto r = uload(&_stack->psr);\n current->apply_to_mpu();\n if (r) {\n reply_sender.set_message({\n Descriptor::zero(),\n r.ref(),\n });\n } else {\n reply_sender.set_message(Message::failure(Exception::fault));\n }\n break;\n }\n\n case 4:\n case 5:\n case 6:\n case 7:\n case 8:\n case 9:\n case 10:\n case 11:\n reply_sender.set_message({Descriptor::zero(), _save.raw[arg.d1 - 4]});\n break;\n\n default:\n reply_sender.set_message(Message::failure(Exception::index_out_of_range));\n break;\n }\n\n k.keys[0].deliver_from(&reply_sender);\n}\n\nvoid Context::do_write_register(Brand,\n Message const & arg,\n Keys & k) {\n auto r = arg.d1;\n auto v = arg.d2;\n\n ReplySender reply_sender;\n\n switch (r) {\n case 13:\n _stack = reinterpret_cast<decltype(_stack)>(v);\n break;\n\n#define GP_EF(n) \\\n case n: { \\\n if (!ustore(&_stack->r ## n, v)) { \\\n reply_sender.set_message(Message::failure(Exception::fault)); \\\n } \\\n break; \\\n }\n GP_EF(0);\n GP_EF(1);\n GP_EF(2);\n GP_EF(3);\n GP_EF(12);\n GP_EF(14);\n GP_EF(15);\n#undef GP\n\n case 16: {\n if (!ustore(&_stack->psr, v)) {\n reply_sender.set_message(Message::failure(Exception::fault));\n }\n break;\n }\n\n case 4:\n case 5:\n case 6:\n case 7:\n case 8:\n case 9:\n case 10:\n case 11:\n _save.raw[r - 4] = v;\n break;\n\n default:\n reply_sender.set_message(Message::failure(Exception::index_out_of_range));\n break;\n }\n\n k.keys[0].deliver_from(&reply_sender);\n}\n\nvoid Context::do_read_key(Brand,\n Message const & arg,\n Keys & k) {\n auto r = arg.d1;\n\n ReplySender reply_sender;\n if (r >= config::n_task_keys) {\n reply_sender.set_message(Message::failure(Exception::index_out_of_range));\n } else {\n reply_sender.set_key(1, key(r));\n }\n k.keys[0].deliver_from(&reply_sender);\n}\n\nvoid Context::do_write_key(Brand,\n Message const & arg,\n Keys & k) {\n auto r = arg.d1;\n\n auto & reply = k.keys[0];\n auto & new_key = k.keys[1];\n\n ReplySender reply_sender;\n if (r >= config::n_task_keys) {\n reply_sender.set_message(Message::failure(Exception::index_out_of_range));\n } else {\n key(r) = new_key;\n }\n reply.deliver_from(&reply_sender);\n}\n\nvoid Context::do_read_region(Brand,\n Message const & arg,\n Keys & k) {\n auto n = arg.d1;\n\n ReplySender reply_sender;\n if (n < config::n_task_regions) {\n reply_sender.set_key(1, _memory_regions[n]);\n } else {\n reply_sender.set_message(Message::failure(Exception::index_out_of_range));\n }\n k.keys[0].deliver_from(&reply_sender);\n}\n\nvoid Context::do_write_region(Brand,\n Message const & arg,\n Keys & k) {\n auto n = arg.d1;\n auto & reply = k.keys[0];\n auto & object_key = k.keys[1];\n\n ReplySender reply_sender;\n\n if (n < config::n_task_regions) {\n _memory_regions[n] = object_key;\n } else {\n reply_sender.set_message(Message::failure(Exception::index_out_of_range));\n }\n\n if (current == this) apply_to_mpu();\n\n reply.deliver_from(&reply_sender);\n}\n\nvoid Context::do_make_runnable(Brand, Message const & arg, Keys & k) {\n make_runnable();\n pend_switch();\n\n ReplySender reply_sender;\n k.keys[0].deliver_from(&reply_sender);\n}\n\nvoid Context::do_read_priority(Brand, Message const & arg, Keys & k) {\n ReplySender reply_sender;\n reply_sender.set_message({Descriptor::zero(), _priority});\n k.keys[0].deliver_from(&reply_sender);\n}\n\nvoid Context::do_write_priority(Brand, Message const & arg, Keys & k) {\n auto priority = arg.d1;\n\n ReplySender reply_sender;\n\n if (priority < config::n_priorities) {\n _priority = priority;\n \n if (_ctx_item.is_linked()) _ctx_item.reinsert();\n if (_sender_item.is_linked()) _sender_item.reinsert();\n } else {\n reply_sender.set_message(Message::failure(Exception::index_out_of_range));\n }\n\n k.keys[0].deliver_from(&reply_sender);\n}\n\n} \/\/ namespace k\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2012 The Bitcoin developers\n\/\/ Distributed under the MIT\/X11 software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n#include <string>\n\n#include \"version.h\"\n\n\/\/ Name of client reported in the 'version' message. Report the same name\n\/\/ for both bitcoind and bitcoin-qt, to make it harder for attackers to\n\/\/ target servers or GUI users specifically.\nconst std::string CLIENT_NAME(\"Britcoin\");\n\n\/\/ Client version number\n#define CLIENT_VERSION_SUFFIX \"\"\n\n\n\/\/ The following part of the code determines the CLIENT_BUILD variable.\n\/\/ Several mechanisms are used for this:\n\/\/ * first, if HAVE_BUILD_INFO is defined, include build.h, a file that is\n\/\/ generated by the build environment, possibly containing the output\n\/\/ of git-describe in a macro called BUILD_DESC\n\/\/ * secondly, if this is an exported version of the code, GIT_ARCHIVE will\n\/\/ be defined (automatically using the export-subst git attribute), and\n\/\/ GIT_COMMIT will contain the commit id.\n\/\/ * then, three options exist for determining CLIENT_BUILD:\n\/\/ * if BUILD_DESC is defined, use that literally (output of git-describe)\n\/\/ * if not, but GIT_COMMIT is defined, use v[maj].[min].[rev].[build]-g[commit]\n\/\/ * otherwise, use v[maj].[min].[rev].[build]-unk\n\/\/ finally CLIENT_VERSION_SUFFIX is added\n\n\/\/ First, include build.h if requested\n#ifdef HAVE_BUILD_INFO\n# include \"build.h\"\n#endif\n\n\/\/ git will put \"#define GIT_ARCHIVE 1\" on the next line inside archives. \n#define GIT_ARCHIVE 1\n#ifdef GIT_ARCHIVE\n# define GIT_COMMIT_ID \": Experimental\"\n\/\/# define GIT_COMMIT_DATE \"$Format:%cD\"\n#endif\n\n#define BUILD_DESC_FROM_COMMIT(maj,min,rev,build,commit) \\\n \"v\" DO_STRINGIZE(maj) \".\" DO_STRINGIZE(min) \".\" DO_STRINGIZE(rev) \".\" DO_STRINGIZE(build) \"\" commit\n\n#define BUILD_DESC_FROM_UNKNOWN(maj,min,rev,build) \\\n \"v\" DO_STRINGIZE(maj) \".\" DO_STRINGIZE(min) \".\" DO_STRINGIZE(rev) \".\" DO_STRINGIZE(build) \"\"\n\n#ifndef BUILD_DESC\n# ifdef GIT_COMMIT_ID\n# define BUILD_DESC BUILD_DESC_FROM_COMMIT(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD, GIT_COMMIT_ID)\n# else\n# define BUILD_DESC BUILD_DESC_FROM_UNKNOWN(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD)\n# endif\n#endif\n\n#ifndef BUILD_DATE\n# ifdef GIT_COMMIT_DATE\n# define BUILD_DATE GIT_COMMIT_DATE\n# else\n# define BUILD_DATE __DATE__ \", \" __TIME__\n# endif\n#endif\n\nconst std::string CLIENT_BUILD(BUILD_DESC CLIENT_VERSION_SUFFIX);\nconst std::string CLIENT_DATE(BUILD_DATE);\n<commit_msg>Changed version name<commit_after>\/\/ Copyright (c) 2012 The Bitcoin developers\n\/\/ Distributed under the MIT\/X11 software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n#include <string>\n\n#include \"version.h\"\n\n\/\/ Name of client reported in the 'version' message. Report the same name\n\/\/ for both bitcoind and bitcoin-qt, to make it harder for attackers to\n\/\/ target servers or GUI users specifically.\nconst std::string CLIENT_NAME(\"BritCoin\");\n\n\/\/ Client version number\n#define CLIENT_VERSION_SUFFIX \"\"\n\n\n\/\/ The following part of the code determines the CLIENT_BUILD variable.\n\/\/ Several mechanisms are used for this:\n\/\/ * first, if HAVE_BUILD_INFO is defined, include build.h, a file that is\n\/\/ generated by the build environment, possibly containing the output\n\/\/ of git-describe in a macro called BUILD_DESC\n\/\/ * secondly, if this is an exported version of the code, GIT_ARCHIVE will\n\/\/ be defined (automatically using the export-subst git attribute), and\n\/\/ GIT_COMMIT will contain the commit id.\n\/\/ * then, three options exist for determining CLIENT_BUILD:\n\/\/ * if BUILD_DESC is defined, use that literally (output of git-describe)\n\/\/ * if not, but GIT_COMMIT is defined, use v[maj].[min].[rev].[build]-g[commit]\n\/\/ * otherwise, use v[maj].[min].[rev].[build]-unk\n\/\/ finally CLIENT_VERSION_SUFFIX is added\n\n\/\/ First, include build.h if requested\n#ifdef HAVE_BUILD_INFO\n# include \"build.h\"\n#endif\n\n\/\/ git will put \"#define GIT_ARCHIVE 1\" on the next line inside archives. \n#define GIT_ARCHIVE 1\n#ifdef GIT_ARCHIVE\n# define GIT_COMMIT_ID \": Hope\"\n\/\/# define GIT_COMMIT_DATE \"$Format:%cD\"\n#endif\n\n#define BUILD_DESC_FROM_COMMIT(maj,min,rev,build,commit) \\\n \"v\" DO_STRINGIZE(maj) \".\" DO_STRINGIZE(min) \".\" DO_STRINGIZE(rev) \".\" DO_STRINGIZE(build) \"\" commit\n\n#define BUILD_DESC_FROM_UNKNOWN(maj,min,rev,build) \\\n \"v\" DO_STRINGIZE(maj) \".\" DO_STRINGIZE(min) \".\" DO_STRINGIZE(rev) \".\" DO_STRINGIZE(build) \"\"\n\n#ifndef BUILD_DESC\n# ifdef GIT_COMMIT_ID\n# define BUILD_DESC BUILD_DESC_FROM_COMMIT(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD, GIT_COMMIT_ID)\n# else\n# define BUILD_DESC BUILD_DESC_FROM_UNKNOWN(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD)\n# endif\n#endif\n\n#ifndef BUILD_DATE\n# ifdef GIT_COMMIT_DATE\n# define BUILD_DATE GIT_COMMIT_DATE\n# else\n# define BUILD_DATE __DATE__ \", \" __TIME__\n# endif\n#endif\n\nconst std::string CLIENT_BUILD(BUILD_DESC CLIENT_VERSION_SUFFIX);\nconst std::string CLIENT_DATE(BUILD_DATE);\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2013-2014 The curecoin developers\n\/\/ Distributed under the MIT\/X11 software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n#include <string>\n\n#include \"version.h\"\n\n\/\/ Name of client reported in the 'version' message. Report the same name\n\/\/ for both curecoind and curecoin-qt, to make it harder for attackers to\n\/\/ target servers or GUI users specifically.\nconst std::string CLIENT_NAME(\"Curecoin\");\n\n\/\/ Client version number\n#define CLIENT_VERSION_SUFFIX \"-CURE\"\n\n\n\/\/ The following part of the code determines the CLIENT_BUILD variable.\n\/\/ Several mechanisms are used for this:\n\/\/ * first, if HAVE_BUILD_INFO is defined, include build.h, a file that is\n\/\/ generated by the build environment, possibly containing the output\n\/\/ of git-describe in a macro called BUILD_DESC\n\/\/ * secondly, if this is an exported version of the code, GIT_ARCHIVE will\n\/\/ be defined (automatically using the export-subst git attribute), and\n\/\/ GIT_COMMIT will contain the commit id.\n\/\/ * then, three options exist for determining CLIENT_BUILD:\n\/\/ * if BUILD_DESC is defined, use that literally (output of git-describe)\n\/\/ * if not, but GIT_COMMIT is defined, use v[maj].[min].[rev].[build]-g[commit]\n\/\/ * otherwise, use v[maj].[min].[rev].[build]-unk\n\/\/ finally CLIENT_VERSION_SUFFIX is added\n\n\/\/ First, include build.h if requested\n#ifdef HAVE_BUILD_INFO\n# include \"build.h\"\n#endif\n\n\/\/ git will put \"#define GIT_ARCHIVE 1\" on the next line inside archives. \n#define GIT_ARCHIVE 1\n#ifdef GIT_ARCHIVE\n# define GIT_COMMIT_ID \"7b123c3\"\n# define GIT_COMMIT_DATE \"$Format:%cD\"\n#endif\n\n#define BUILD_DESC_FROM_COMMIT(maj,min,rev,build,commit) \\\n \"v\" DO_STRINGIZE(maj) \".\" DO_STRINGIZE(min) \".\" DO_STRINGIZE(rev) \".\" DO_STRINGIZE(build)\n\n#define BUILD_DESC_FROM_UNKNOWN(maj,min,rev,build) \\\n \"v\" DO_STRINGIZE(maj) \".\" DO_STRINGIZE(min) \".\" DO_STRINGIZE(rev) \".\" DO_STRINGIZE(build) \"-unk\"\n\n#ifndef BUILD_DESC\n# ifdef GIT_COMMIT_ID\n# define BUILD_DESC BUILD_DESC_FROM_COMMIT(DISPLAY_VERSION_MAJOR, DISPLAY_VERSION_MINOR, DISPLAY_VERSION_REVISION, DISPLAY_VERSION_BUILD, GIT_COMMIT_ID)\n# else\n# define BUILD_DESC BUILD_DESC_FROM_UNKNOWN(DISPLAY_VERSION_MAJOR, DISPLAY_VERSION_MINOR, DISPLAY_VERSION_REVISION, DISPLAY_VERSION_BUILD)\n# endif\n#endif\n\n#ifndef BUILD_DATE\n# ifdef GIT_COMMIT_DATE\n# define BUILD_DATE \"July 4, 2013\"\n# else\n# define BUILD_DATE __DATE__ \", \" __TIME__\n# endif\n#endif\n\nconst std::string CLIENT_BUILD(BUILD_DESC CLIENT_VERSION_SUFFIX);\nconst std::string CLIENT_DATE(BUILD_DATE);\n<commit_msg>Update version.cpp<commit_after>\/\/ Copyright (c) 2013-2020 The Curecoin Developers\n\/\/ Distributed under the MIT\/X11 software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n#include <string>\n\n#include \"version.h\"\n\n\/\/ Name of client reported in the 'version' message. Report the same name\n\/\/ for both curecoind and curecoin-qt, to make it harder for attackers to\n\/\/ target servers or GUI users specifically.\nconst std::string CLIENT_NAME(\"Curecoin\");\n\n\/\/ Client version number\n#define CLIENT_VERSION_SUFFIX \"-CURE\"\n\n\n\/\/ The following part of the code determines the CLIENT_BUILD variable.\n\/\/ Several mechanisms are used for this:\n\/\/ * first, if HAVE_BUILD_INFO is defined, include build.h, a file that is\n\/\/ generated by the build environment, possibly containing the output\n\/\/ of git-describe in a macro called BUILD_DESC\n\/\/ * secondly, if this is an exported version of the code, GIT_ARCHIVE will\n\/\/ be defined (automatically using the export-subst git attribute), and\n\/\/ GIT_COMMIT will contain the commit id.\n\/\/ * then, three options exist for determining CLIENT_BUILD:\n\/\/ * if BUILD_DESC is defined, use that literally (output of git-describe)\n\/\/ * if not, but GIT_COMMIT is defined, use v[maj].[min].[rev].[build]-g[commit]\n\/\/ * otherwise, use v[maj].[min].[rev].[build]-unk\n\/\/ finally CLIENT_VERSION_SUFFIX is added\n\n\/\/ First, include build.h if requested\n#ifdef HAVE_BUILD_INFO\n# include \"build.h\"\n#endif\n\n\/\/ git will put \"#define GIT_ARCHIVE 1\" on the next line inside archives. \n#define GIT_ARCHIVE 1\n#ifdef GIT_ARCHIVE\n# define GIT_COMMIT_ID \"7b123c3\"\n# define GIT_COMMIT_DATE \"$Format:%cD\"\n#endif\n\n#define BUILD_DESC_FROM_COMMIT(maj,min,rev,build,commit) \\\n \"v\" DO_STRINGIZE(maj) \".\" DO_STRINGIZE(min) \".\" DO_STRINGIZE(rev) \".\" DO_STRINGIZE(build)\n\n#define BUILD_DESC_FROM_UNKNOWN(maj,min,rev,build) \\\n \"v\" DO_STRINGIZE(maj) \".\" DO_STRINGIZE(min) \".\" DO_STRINGIZE(rev) \".\" DO_STRINGIZE(build) \"-unk\"\n\n#ifndef BUILD_DESC\n# ifdef GIT_COMMIT_ID\n# define BUILD_DESC BUILD_DESC_FROM_COMMIT(DISPLAY_VERSION_MAJOR, DISPLAY_VERSION_MINOR, DISPLAY_VERSION_REVISION, DISPLAY_VERSION_BUILD, GIT_COMMIT_ID)\n# else\n# define BUILD_DESC BUILD_DESC_FROM_UNKNOWN(DISPLAY_VERSION_MAJOR, DISPLAY_VERSION_MINOR, DISPLAY_VERSION_REVISION, DISPLAY_VERSION_BUILD)\n# endif\n#endif\n\n#ifndef BUILD_DATE\n# ifdef GIT_COMMIT_DATE\n# define BUILD_DATE \"July 4, 2013\"\n# else\n# define BUILD_DATE __DATE__ \", \" __TIME__\n# endif\n#endif\n\nconst std::string CLIENT_BUILD(BUILD_DESC CLIENT_VERSION_SUFFIX);\nconst std::string CLIENT_DATE(BUILD_DATE);\n<|endoftext|>"} {"text":"<commit_before><commit_msg>coverity#707973 Uninitialized scalar field<commit_after><|endoftext|>"} {"text":"<commit_before>#include <oalplus\/al.hpp>\n#include <oalplus\/all.hpp>\n#include <oalplus\/alut.hpp>\n#include <chrono>\n#include <thread>\n#include <iostream>\n\n#include <boost\/multi_index_container.hpp>\n#include <boost\/multi_index\/hashed_index.hpp>\n#include <boost\/multi_index\/mem_fun.hpp>\nclass Sound\n{\n public:\n Sound():\n Sound{oalplus::ALUtilityToolkit(false).CreateBufferHelloWorld()}\n {\n }\n\n Sound(const std::string& filename):\n Sound{oalplus::ALUtilityToolkit(false).CreateBufferFromFile(filename)}\n {\n }\n\n Sound(const oalplus::Buffer& buf):\n m_source{oalplus::ObjectDesc(\"Source\")}\n {\n m_source.Buffer(buf);\n m_source.Looping(true);\n m_source.ReferenceDistance(15);\n }\n\n auto& source()\n {\n return m_source;\n }\n\n const auto& source() const\n {\n return m_source;\n }\n\n void setEnabled(bool)\n {\n\n }\n\n const std::string& name() const\n {\n return m_name;\n }\n\n void setName(const std::string &name)\n {\n m_name = name;\n }\n\n private:\n std::string m_name;\n oalplus::Source m_source;\n};\n\nnamespace bmi = boost::multi_index;\nusing SoundMap = bmi::multi_index_container<\n Sound,\n bmi::indexed_by<\n bmi::hashed_unique<\n bmi::const_mem_fun<\n Sound,\n const std::string&,\n &Sound::name\n >\n >\n >\n>;\nclass Scene\n{\n public:\n Scene()\n {\n \/\/ create a listener and set its position, velocity and orientation\n m_listener.Position(0.0f, 0.0f, 0.0f);\n m_listener.Velocity(0.0f, 0.0f, 0.0f);\n m_listener.Orientation(0.0f, 0.0f,-1.0f, 0.0f, 1.0f, 0.0f);\n\n m_sounds.insert(Sound());\n }\n\n void start()\n {\n for(auto& cst_sound : m_sounds)\n {\n auto& sound = const_cast<Sound&>(cst_sound);\n auto& source = sound.source();\n \/\/ let the source play the sound\n source.Play();\n \/*\n\n \/\/ the path of the source\n oalplus::CubicBezierLoop<oalplus::Vec3f, double> path(\n {\n oalplus::Vec3f( 0.0f, 0.0f, -9.0f),\n oalplus::Vec3f( 9.0f, 2.0f, -8.0f),\n oalplus::Vec3f( 4.0f,-3.0f, 9.0f),\n oalplus::Vec3f(-3.0f, 4.0f, 9.0f),\n oalplus::Vec3f(-9.0f,-1.0f, -7.0f)\n });\n \/\/\n\n \/\/ play the sound for a while\n typedef std::chrono::system_clock clock;\n typedef std::chrono::time_point<clock> time_point;\n time_point start = clock::now();\n while(true)\n {\n double t = double((clock::now() - start).count())*\n double(clock::period::num)\/\n double(clock::period::den);\n if(t > 10.0) break;\n source.Position(path.Position(t\/5.0));\n m_listener.Position(m_listener.Position() - oalplus::Vec3f{0.2, 0, 0});\n \/\/ wait for a while\n std::chrono::milliseconds duration(10);\n std::this_thread::sleep_for(duration);\n }\n *\/\n while(true)\n std::this_thread::sleep_for(std::chrono::seconds(10));\n }\n }\n\n oalplus::Listener& listener()\n { return m_listener; }\n\n SoundMap& sounds()\n { return m_sounds; }\n\n private:\n oalplus::Listener m_listener;\n SoundMap m_sounds;\n};\n\n#include <Network\/Device.h>\n#include <Network\/Protocol.h>\n#include <Network\/Node.h>\n\n\n\ntemplate<typename Get, typename Set>\nstruct Parameter\n{\n Get get;\n Set set;\n};\n\n\ntemplate<typename Get, typename Set>\nauto make_parameter(Get&& get, Set&& set)\n{\n return Parameter<Get, Set>{std::move(get), std::move(set)};\n}\n\ntemplate<typename Parameter_t> \/\/ a function that returns a Vec3f& to modify.\nvoid add_position(std::shared_ptr<OSSIA::Node> node, Parameter_t&& param)\n{\n auto addr = node->createAddress(OSSIA::Value::Type::TUPLE); \/\/ [ x y z ]\n auto x_node = *node->emplace(node->children().cend(), \"x\");\n auto x_addr = x_node->createAddress(OSSIA::Value::Type::FLOAT);\n auto y_node = *node->emplace(node->children().cend(), \"y\");\n auto y_addr = y_node->createAddress(OSSIA::Value::Type::FLOAT);\n auto z_node = *node->emplace(node->children().cend(), \"z\");\n auto z_addr = z_node->createAddress(OSSIA::Value::Type::FLOAT);\n\n addr->setValueCallback([=] (const OSSIA::Value* val) {\n auto tpl = dynamic_cast<const OSSIA::Tuple*>(val);\n if(tpl->value.size() != 3)\n return;\n\n auto x = dynamic_cast<const OSSIA::Float*>(tpl->value[0]);\n auto y = dynamic_cast<const OSSIA::Float*>(tpl->value[1]);\n auto z = dynamic_cast<const OSSIA::Float*>(tpl->value[2]);\n if(!x || !y || !z)\n return;\n\n param.set(oalplus::Vec3f{x->value, y->value, z->value});\n });\n\n auto modify_i = [=] (int i) {\n return [=] (const OSSIA::Value* val) {\n std::cerr << \"Got a message!\" << std::endl;\n auto float_val = dynamic_cast<const OSSIA::Float*>(val);\n if(!float_val)\n return;\n\n auto elt = param.get();\n elt[i] = float_val->value;\n param.set(elt);\n };\n };\n\n x_addr->setValueCallback(modify_i(0));\n y_addr->setValueCallback(modify_i(1));\n z_addr->setValueCallback(modify_i(2));\n}\n\ntemplate<typename VecFun> \/\/ a function that takes a Vec6f& to modify.\nvoid add_orientation(std::shared_ptr<OSSIA::Node> node, VecFun&& vecfun)\n{\n auto addr = node->createAddress(OSSIA::Value::Type::TUPLE); \/\/ [ at_x at_y at_z up_x at_y at_z ]\n auto at_node = *node->emplace(node->children().cend(), \"at\");\n add_position(at_node, [&] () { return vecfun(); } );\n auto up_node = *node->emplace(node->children().cend(), \"up\");\n}\n\nint main(int argc, char** argv)\n{\n oalplus::Device device;\n oalplus::ContextMadeCurrent context(\n device,\n oalplus::ContextAttribs().Add(oalplus::ContextAttrib::MonoSources, 1).Get());\n\n Scene s;\n\n OSSIA::Local localDeviceParameters{};\n auto local = OSSIA::Device::create(localDeviceParameters, \"3DAudioScene\");\n\n auto dev = OSSIA::Device::create(OSSIA::OSC{\"127.0.0.1\", 9997, 9996}, \"MinuitDevice\");\n {\n \/\/ Listener : position, orientation, volume ?\n\n \/\/ Sources : position, orientation, volume, enabled, sound file ?\n\n \/\/\/\/ Global settings \/\/\/\/\n auto settings_node = *dev->emplace(dev->children().cend(), \"settings\");\n auto vol_node = *settings_node->emplace(settings_node->children().cend(), \"volume\");\n auto files_node = *settings_node->emplace(settings_node->children().cend(), \"files\");\n\n auto vol_addr = vol_node->createAddress(OSSIA::Value::Type::FLOAT);\n auto files_addr = files_node->createAddress(OSSIA::Value::Type::TUPLE);\n\n vol_addr->setValueCallback([] (const OSSIA::Value* val) { });\n files_addr->setValueCallback([] (const OSSIA::Value* val) { });\n\n \/\/ updating local tree value\n \/\/OSSIA::Bool b(true);\n \/\/localTestAddress->sendValue(&b);\n\n \/\/\/\/ Listener settings \/\/\/\/\n auto listener_node = *dev->emplace(dev->children().cend(), \"listener\");\n\n auto listener_pos_node = *listener_node->emplace(listener_node->children().cend(), \"pos\");\n\n add_position(listener_pos_node,\n make_parameter(\n [&] () { return s.listener().Position(); },\n [&] (const auto& elt) { s.listener().Position(elt); }\n ));\n\n auto listener_orient_node = *listener_node->emplace(listener_node->children().cend(), \"orient\");\n\n \/\/auto addr = listener_orient_node->createAddress(OSSIA::Value::Type::TUPLE); \/\/ [ at_x at_y at_z up_x at_y at_z ]\n auto listener_orient_at_node = *listener_orient_node->emplace(listener_orient_node->children().cend(), \"at\");\n add_position(listener_orient_at_node,\n make_parameter(\n [&] () { return s.listener().OrientationAt(); },\n [&] (const auto& elt) { s.listener().Orientation(elt, s.listener().OrientationUp()); }\n ));\n auto listener_orient_up_node = *listener_orient_node->emplace(listener_orient_node->children().cend(), \"up\");\n add_position(listener_orient_up_node,\n make_parameter(\n [&] () { return s.listener().OrientationUp(); },\n [&] (const auto& elt) { s.listener().Orientation(s.listener().OrientationAt(), elt); }\n ));\n\n }\n s.start();\n\n \/\/\n return 0;\n}\n\n\n\n\n<commit_msg>all the relevant addresses should be here<commit_after>#include <oalplus\/al.hpp>\n#include <oalplus\/all.hpp>\n#include <oalplus\/alut.hpp>\n#include <chrono>\n#include <thread>\n#include <iostream>\n\n#include <boost\/range\/algorithm\/find_if.hpp>\n#include <boost\/multi_index_container.hpp>\n#include <boost\/multi_index\/hashed_index.hpp>\n#include <boost\/multi_index\/mem_fun.hpp>\nclass Sound\n{\n public:\n Sound(const std::string& name):\n Sound{name, oalplus::ALUtilityToolkit(false).CreateBufferHelloWorld()}\n {\n }\n\n Sound(const std::string& name, const std::string& filename):\n Sound{name, oalplus::ALUtilityToolkit(false).CreateBufferFromFile(filename)}\n {\n }\n\n Sound(const std::string& name, const oalplus::Buffer& buf):\n m_name{name},\n m_source{oalplus::ObjectDesc(std::string(name))}\n {\n m_source.Buffer(buf);\n m_source.Looping(true);\n m_source.ReferenceDistance(15);\n }\n\n auto& source()\n {\n return m_source;\n }\n\n const auto& source() const\n {\n return m_source;\n }\n\n void setEnabled(bool b)\n {\n m_source.Gain(b ? m_gain : 0.);\n }\n\n const std::string& name() const\n {\n return m_name;\n }\n\n void setName(const std::string &name)\n {\n m_name = name;\n }\n\n void load(const std::string& file)\n {\n m_source.Buffer(oalplus::ALUtilityToolkit(false).CreateBufferFromFile(file));\n }\n\n private:\n std::string m_name;\n oalplus::Source m_source;\n double m_gain{1.};\n};\n\nnamespace bmi = boost::multi_index;\nusing SoundMap = bmi::multi_index_container<\nSound,\nbmi::indexed_by<\nbmi::hashed_unique<\nbmi::const_mem_fun<\nSound,\nconst std::string&,\n&Sound::name\n>\n>\n>\n>;\nclass Scene\n{\n public:\n Scene()\n {\n \/\/ create a listener and set its position, velocity and orientation\n m_listener.Position(0.0f, 0.0f, 0.0f);\n m_listener.Velocity(0.0f, 0.0f, 0.0f);\n m_listener.Orientation(0.0f, 0.0f,-1.0f, 0.0f, 1.0f, 0.0f);\n\n m_sounds.insert(Sound(\"ASound\"));\n }\n\n void start()\n {\n for(auto& cst_sound : m_sounds)\n {\n const_cast<Sound&>(cst_sound).source().Play();\n\n \/*\n\n \/\/ the path of the source\n oalplus::CubicBezierLoop<oalplus::Vec3f, double> path(\n {\n oalplus::Vec3f( 0.0f, 0.0f, -9.0f),\n oalplus::Vec3f( 9.0f, 2.0f, -8.0f),\n oalplus::Vec3f( 4.0f,-3.0f, 9.0f),\n oalplus::Vec3f(-3.0f, 4.0f, 9.0f),\n oalplus::Vec3f(-9.0f,-1.0f, -7.0f)\n });\n \/\/\n\n \/\/ play the sound for a while\n typedef std::chrono::system_clock clock;\n typedef std::chrono::time_point<clock> time_point;\n time_point start = clock::now();\n while(true)\n {\n double t = double((clock::now() - start).count())*\n double(clock::period::num)\/\n double(clock::period::den);\n if(t > 10.0) break;\n source.Position(path.Position(t\/5.0));\n m_listener.Position(m_listener.Position() - oalplus::Vec3f{0.2, 0, 0});\n \/\/ wait for a while\n std::chrono::milliseconds duration(10);\n std::this_thread::sleep_for(duration);\n }\n *\/\n while(true)\n std::this_thread::sleep_for(std::chrono::seconds(10));\n }\n }\n\n oalplus::Listener& listener()\n { return m_listener; }\n\n SoundMap& sounds()\n { return m_sounds; }\n\n private:\n oalplus::Listener m_listener;\n SoundMap m_sounds;\n};\n\n#include <Network\/Device.h>\n#include <Network\/Protocol.h>\n#include <Network\/Node.h>\n\n\n\ntemplate<typename Get, typename Set>\nstruct Parameter\n{\n Get get;\n Set set;\n};\n\n\ntemplate<typename Get, typename Set>\nauto make_parameter(Get&& get, Set&& set)\n{\n return Parameter<Get, Set>{std::move(get), std::move(set)};\n}\n\ntemplate<typename Fun>\nauto add_child(std::shared_ptr<OSSIA::Node>& node,\n const std::string& name,\n OSSIA::Value::Type type,\n Fun&& callback)\n{\n auto new_node = *node->emplace(node->children().cend(), name);\n new_node->createAddress(type)->setValueCallback(callback);\n\n return new_node;\n}\n\ntemplate<typename Parameter_t> \/\/ a function that returns a Vec3f& to modify.\nvoid add_position(std::shared_ptr<OSSIA::Node> node, Parameter_t&& param)\n{\n static auto modify_i = [=] (int i) {\n return [=] (const OSSIA::Value* val) {\n auto float_val = dynamic_cast<const OSSIA::Float*>(val);\n if(!float_val)\n return;\n\n auto elt = param.get();\n elt[i] = float_val->value;\n param.set(elt);\n };\n };\n\n auto addr = node->createAddress(OSSIA::Value::Type::TUPLE); \/\/ [ x y z ]\n\n addr->setValueCallback([=] (const OSSIA::Value* val) {\n auto tpl = dynamic_cast<const OSSIA::Tuple*>(val);\n if(tpl->value.size() != 3)\n return;\n\n auto x = dynamic_cast<const OSSIA::Float*>(tpl->value[0]);\n auto y = dynamic_cast<const OSSIA::Float*>(tpl->value[1]);\n auto z = dynamic_cast<const OSSIA::Float*>(tpl->value[2]);\n if(!x || !y || !z)\n return;\n\n param.set(oalplus::Vec3f{x->value, y->value, z->value});\n });\n\n add_child(node, \"x\", OSSIA::Value::Type::FLOAT, modify_i(0));\n add_child(node, \"y\", OSSIA::Value::Type::FLOAT, modify_i(1));\n add_child(node, \"z\", OSSIA::Value::Type::FLOAT, modify_i(2));\n}\n\n\nint main(int argc, char** argv)\n{\n oalplus::Device device;\n oalplus::ContextMadeCurrent context(\n device,\n oalplus::ContextAttribs().Add(oalplus::ContextAttrib::MonoSources, 1).Get());\n\n Scene s;\n\n OSSIA::Local localDeviceParameters{};\n auto local = OSSIA::Device::create(localDeviceParameters, \"3DAudioScene\");\n\n auto dev = OSSIA::Device::create(OSSIA::OSC{\"127.0.0.1\", 9997, 9996}, \"MinuitDevice\");\n {\n \/\/ Listener : position, orientation, volume ?\n\n \/\/ Sources : position, orientation, volume, enabled, sound file ?\n\n \/\/\/\/ Global settings \/\/\/\/\n {\n auto settings_node = *dev->emplace(dev->children().cend(), \"settings\");\n auto vol_node = *settings_node->emplace(settings_node->children().cend(), \"volume\");\n auto files_node = *settings_node->emplace(settings_node->children().cend(), \"files\");\n\n auto vol_addr = vol_node->createAddress(OSSIA::Value::Type::FLOAT);\n auto files_addr = files_node->createAddress(OSSIA::Value::Type::TUPLE);\n\n vol_addr->setValueCallback([] (const OSSIA::Value* val) { });\n files_addr->setValueCallback([] (const OSSIA::Value* val) { });\n }\n \/\/\/\/ Listener settings \/\/\/\/\n {\n auto listener_node = *dev->emplace(dev->children().cend(), \"listener\");\n\n auto listener_pos_node = *listener_node->emplace(listener_node->children().cend(), \"pos\");\n\n add_position(listener_pos_node,\n make_parameter(\n [&] () { return s.listener().Position(); },\n [&] (const auto& elt) { s.listener().Position(elt); }\n ));\n\n auto listener_orient_node = *listener_node->emplace(listener_node->children().cend(), \"orientation\");\n auto listener_orient_addr = listener_orient_node->createAddress(OSSIA::Value::Type::TUPLE); \/\/ [ at_x at_y at_z up_x at_y at_z ]\n listener_orient_addr->setValueCallback([&] (const OSSIA::Value* val) {\n auto tpl = dynamic_cast<const OSSIA::Tuple*>(val);\n if(tpl->value.size() != 6)\n return;\n\n auto at_x = dynamic_cast<const OSSIA::Float*>(tpl->value[0]);\n auto at_y = dynamic_cast<const OSSIA::Float*>(tpl->value[1]);\n auto at_z = dynamic_cast<const OSSIA::Float*>(tpl->value[2]);\n auto up_x = dynamic_cast<const OSSIA::Float*>(tpl->value[3]);\n auto up_y = dynamic_cast<const OSSIA::Float*>(tpl->value[4]);\n auto up_z = dynamic_cast<const OSSIA::Float*>(tpl->value[5]);\n if(!at_x || !at_y || !at_z || !up_x || !up_y || !up_z)\n return;\n\n s.listener().Orientation(at_x->value, at_y->value, at_z->value, up_x->value, up_y->value, up_z->value);\n });\n\n auto listener_orient_at_node = *listener_orient_node->emplace(listener_orient_node->children().cend(), \"at\");\n add_position(listener_orient_at_node,\n make_parameter(\n [&] () { return s.listener().OrientationAt(); },\n [&] (const auto& elt) { s.listener().Orientation(elt, s.listener().OrientationUp()); }\n ));\n auto listener_orient_up_node = *listener_orient_node->emplace(listener_orient_node->children().cend(), \"up\");\n add_position(listener_orient_up_node,\n make_parameter(\n [&] () { return s.listener().OrientationUp(); },\n [&] (const auto& elt) { s.listener().Orientation(s.listener().OrientationAt(), elt); }\n ));\n\n }\n\n \/\/\/\/ Sources settings \/\/\/\/\n {\n auto sources_node = *dev->emplace(dev->children().cend(), \"sources\");\n auto sources_list_node = *sources_node->emplace(sources_node->children().cend(), \"sources\");\n\n add_child(sources_node, \"add\", OSSIA::Value::Type::STRING,\n [&] (const OSSIA::Value* val) {\n auto str_val = dynamic_cast<const OSSIA::String*>(val);\n if(!str_val)\n return;\n\n \/\/ Create the sound\n s.sounds().insert(Sound{str_val->value});\n auto& sound = const_cast<Sound&>(*s.sounds().get<0>().find(str_val->value));\n\n \/\/ Create the callbacks and OSC device commands\n auto src_node = *sources_list_node->emplace(sources_list_node->children().cend(), str_val->value);\n\n \/\/ Position\n auto src_pos_node = *src_node->emplace(src_node->children().cend(), \"pos\");\n add_position(src_pos_node,\n make_parameter(\n [&] () { return sound.source().Position(); },\n [&] (const auto& elt) { sound.source().Position(elt); }\n ));\n\n \/\/ Enablement\n add_child(src_node, \"enabled\", OSSIA::Value::Type::BOOL,\n [&] (const OSSIA::Value* val) {\n auto enablement_val = dynamic_cast<const OSSIA::Bool*>(val);\n if(!enablement_val)\n return;\n sound.setEnabled(enablement_val->value);\n });\n\n \/\/ Audio file\n add_child(src_node, \"file\", OSSIA::Value::Type::STRING,\n [&] (const OSSIA::Value* val) {\n auto filename_val = dynamic_cast<const OSSIA::String*>(val);\n if(!filename_val)\n return;\n sound.load(filename_val->value);\n });\n });\n\n add_child(sources_node, \"remove\", OSSIA::Value::Type::STRING, [&] (const OSSIA::Value* val) {\n auto str_val = dynamic_cast<const OSSIA::String*>(val);\n if(!str_val)\n return;\n\n \/\/ Remove from the sounds\n s.sounds().erase(str_val->value);\n\n \/\/ Remove from the OSC device\n auto& children = sources_node->children();\n auto it = boost::range::find_if(children,\n [&] (auto&& elt) { return elt->getName() == str_val->value; });\n if(it != children.end())\n children.erase(it);\n });\n }\n\n }\n s.start();\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ RUN: %clang_cc1 -emit-llvm -o - %s | FileCheck %s\n\n\/\/ PR8839\nextern \"C\" char memmove();\n\nint main() {\n \/\/ CHECK: call signext i8 @memmove()\n return memmove();\n}\n<commit_msg>Permit ABIs where the caller extends the result (test change).<commit_after>\/\/ RUN: %clang_cc1 -emit-llvm -o - %s | FileCheck %s\n\n\/\/ PR8839\nextern \"C\" char memmove();\n\nint main() {\n \/\/ CHECK: call {{signext i8|i8}} @memmove()\n return memmove();\n}\n<|endoftext|>"} {"text":"<commit_before>\/* Copyright (c) 2015 Convey Computer Corporation\n *\n * This file is part of the OpenHT toolset located at:\n *\n * https:\/\/github.com\/TonyBrewer\/OpenHT\n *\n * Use and distribution licensed under the BSD 3-clause license.\n * See the LICENSE file for the complete license text.\n *\/\n\n#include \"HtSageUtils.h\"\n#include \"IsolateModules.h\"\n\nextern bool debugHooks;\nstd::set<std::string> LockFunctionsInUse;\n\n\ninline std::string Capitalize(std::string str) {\n std::string cap = str;\n if (str.size()) {\n cap[0] = toupper(cap[0]);\n }\n return cap;\n}\n\n\/\/ Copied these from CnyHt code\ninline std::string Upper(std::string str) {\n std::string upper = str;\n for (size_t i = 0; i < upper.size(); i += 1)\n upper[i] = toupper(upper[i]);\n return upper;\n}\n\n\/\/ Insert preprocessing macros to remove original function declarations\n\/\/ and wrap each function so it can be isolated from the others by enabling\n\/\/ the specific function macro.\n\/\/\n\/\/ This is a simple-minded way to do this. Ideally, we'll eventually break\n\/\/ each module out into it's own file.\n\nclass IsolateModules : public AstSimpleProcessing {\n\npublic:\n\n virtual void visit (SgNode* astNode) {\n\n SgFunctionDeclaration *fdecl = isSgFunctionDeclaration(astNode);\n\n if (fdecl) {\n fdeclList.push_back(fdecl);\n }\n\n SgFunctionDefinition *fdef = isSgFunctionDefinition(astNode);\n if (fdef) {\n fdefList.push_back(fdef);\n }\n }\n\n void process() {\n int i;\n\n for (i = 0; i < fdefList.size(); i++) {\n SgFunctionDefinition* fndef = fdefList.at(i); \n\n if (fndef == NULL) {\n return;\n }\n\n std::string functionName = \n fndef->get_declaration()->get_name().getString();\n\n SgFunctionDeclaration *f = fndef->get_declaration();\n\n if (!debugHooks) {\n SgNode *body = fndef->get_body();\n\n \/\/ Move any preprocessing info before the function to a new\n \/\/ null statement preceding the function.\n AttachedPreprocessingInfoType save_buf;\n SageInterface::cutPreprocessingInfo(f, \n PreprocessingInfo::before, \n save_buf) ;\n if (save_buf.size()) {\n SgVariableDeclaration *dummy = \n SageBuilder::buildVariableDeclaration(\n \"___htc_dummy_decl_for_preproc_info\", \n SageBuilder::buildIntType(), 0, f->get_scope());\n SageInterface::setExtern(dummy);\n\n SageInterface::insertStatementBefore(f, dummy);\n SageInterface::pastePreprocessingInfo(\n dummy, \n PreprocessingInfo::before, \n save_buf); \n }\n\n SageInterface::addTextForUnparser(\n f, \n \"\\n#if 0\", \n AstUnparseAttribute::e_before);\n\n std::string CapFnName = Capitalize(functionName);\n std::string before_body = \"\\n#endif\\n\";\n std::string macro_name = \"HTC_KEEP_MODULE_\" + Upper(functionName);\n before_body += \n \"#ifdef \" +\n macro_name +\n \"\\n\";\n before_body += \"#include \\\"Ht.h\\\"\\n\";\n before_body += \"#include \\\"Pers\" +\n CapFnName +\n \".h\\\"\\n\";\n before_body += \"#ifndef __htc_GW_write_addr\\n\";\n before_body += \"#define __htc_GW_write_addr(v,a) v.write_addr(a)\\n\";\n before_body += \"#endif\\n\";\n before_body += \"void CPers\" +\n CapFnName +\n \"::Pers\" +\n CapFnName +\n \"()\\n\";\n SageInterface::addTextForUnparser(body, before_body,\n AstUnparseAttribute::e_before);\n std::string after_body =\n \"\\n#endif \/* \" +\n macro_name +\n \" *\/\\n\";\n SageInterface::addTextForUnparser(body, after_body,\n AstUnparseAttribute::e_after);\n \n \/\/ Write the _src.cpp file\n generate_src_cpp_file(fndef, CapFnName, macro_name); \n }\n }\n for (i = 0; i < fdeclList.size(); i++) {\n\n SgFunctionDeclaration *fdecl = fdeclList.at(i);\n\n if (!debugHooks && \n fdecl && \n fdecl->get_definingDeclaration() != fdecl) {\n\n \/\/ Move any preprocessing info before the function to a new\n \/\/ null statement preceding the function.\n AttachedPreprocessingInfoType save_buf;\n SageInterface::cutPreprocessingInfo(fdecl, \n PreprocessingInfo::before, \n save_buf) ;\n if (save_buf.size()) {\n SgVariableDeclaration *dummy2 = \n SageBuilder::buildVariableDeclaration(\n \"___htc_dummy_decl2_for_preproc_info\", \n SageBuilder::buildIntType(), \n 0, \n fdecl->get_scope());\n SageInterface::setExtern(dummy2);\n\n SageInterface::insertStatementBefore(fdecl, dummy2);\n SageInterface::pastePreprocessingInfo(\n dummy2, \n PreprocessingInfo::before, \n save_buf); \n\n }\n\n SageInterface::addTextForUnparser(fdecl, \"\\n\/* \",\n AstUnparseAttribute::e_before);\n SageInterface::addTextForUnparser(fdecl, \" *\/\",\n AstUnparseAttribute::e_after);\n \/\/ comment out function prototypes\n \/\/ fdecl->setCompilerGenerated();\n \/\/ fdecl->unsetOutputInCodeGeneration();\n }\n }\n\n }\n\n\n void generate_lock_src_cpp_files(std::string &path_name) {\n\n \/\/ Generate Pers_*_src.cpp file for Lock functions\n std::set<std::string>::iterator it;\n\n for (it = LockFunctionsInUse.begin(); it != LockFunctionsInUse.end(); it++) {\n std::string module_name = *it;\n std::string macro_name = \"HTC_KEEP_MODULE_\" + Upper(module_name);\n std::string cpp_name = path_name + \"Pers\" + \n Capitalize(module_name) + \"_src.cpp\";\n std::fstream fs;\n \n fs.open(cpp_name.c_str(), std::fstream::out | std::fstream::trunc);\n\n fs << \"#define \" << macro_name << std::endl;\n fs << \"#include \\\"rose_lock.c\\\"\" << std::endl;\n\n fs.close();\n }\n\n LockFunctionsInUse.clear();\n\n }\n\n void generate_src_cpp_file(SgFunctionDefinition *fndef,\n std::string &module_name,\n std::string ¯o_name) {\n\n std::pair<bool, std::string> fret = HtSageUtils::getFileName(fndef);\n std::string src_name = fret.second;\n std::string base_name = StringUtility::stripPathFromFileName(src_name);\n std::string path_name = StringUtility::getPathFromFileName(src_name) + \"\/\";\n std::string cpp_name= path_name + \"Pers\" + module_name + \"_src.cpp\";\n std::fstream fs;\n\n fs.open(cpp_name.c_str(), std::fstream::out | std::fstream::trunc);\n\n fs << \"#define \" << macro_name << std::endl;\n fs << \"#define CNY_HTC_COPROC\" << std::endl;\n fs << \"#include \\\"rose_\" << base_name << \"\\\"\" << std::endl;\n\n fs.close();\n\n generate_lock_src_cpp_files(path_name);\n\n }\n\nprivate:\n std::vector<SgFunctionDeclaration *> fdeclList;\n std::vector<SgFunctionDefinition *> fdefList;\n};\n\nvoid IsolateModulesToFiles(SgProject *project) {\n IsolateModules im;\n im.traverseInputFiles(project, preorder, STRICT_INPUT_FILE_TRAVERSAL);\n im.process();\n}\n<commit_msg>Add missing define<commit_after>\/* Copyright (c) 2015 Convey Computer Corporation\n *\n * This file is part of the OpenHT toolset located at:\n *\n * https:\/\/github.com\/TonyBrewer\/OpenHT\n *\n * Use and distribution licensed under the BSD 3-clause license.\n * See the LICENSE file for the complete license text.\n *\/\n\n#include \"HtSageUtils.h\"\n#include \"IsolateModules.h\"\n\nextern bool debugHooks;\nstd::set<std::string> LockFunctionsInUse;\n\n\ninline std::string Capitalize(std::string str) {\n std::string cap = str;\n if (str.size()) {\n cap[0] = toupper(cap[0]);\n }\n return cap;\n}\n\n\/\/ Copied these from CnyHt code\ninline std::string Upper(std::string str) {\n std::string upper = str;\n for (size_t i = 0; i < upper.size(); i += 1)\n upper[i] = toupper(upper[i]);\n return upper;\n}\n\n\/\/ Insert preprocessing macros to remove original function declarations\n\/\/ and wrap each function so it can be isolated from the others by enabling\n\/\/ the specific function macro.\n\/\/\n\/\/ This is a simple-minded way to do this. Ideally, we'll eventually break\n\/\/ each module out into it's own file.\n\nclass IsolateModules : public AstSimpleProcessing {\n\npublic:\n\n virtual void visit (SgNode* astNode) {\n\n SgFunctionDeclaration *fdecl = isSgFunctionDeclaration(astNode);\n\n if (fdecl) {\n fdeclList.push_back(fdecl);\n }\n\n SgFunctionDefinition *fdef = isSgFunctionDefinition(astNode);\n if (fdef) {\n fdefList.push_back(fdef);\n }\n }\n\n void process() {\n int i;\n\n for (i = 0; i < fdefList.size(); i++) {\n SgFunctionDefinition* fndef = fdefList.at(i); \n\n if (fndef == NULL) {\n return;\n }\n\n std::string functionName = \n fndef->get_declaration()->get_name().getString();\n\n SgFunctionDeclaration *f = fndef->get_declaration();\n\n if (!debugHooks) {\n SgNode *body = fndef->get_body();\n\n \/\/ Move any preprocessing info before the function to a new\n \/\/ null statement preceding the function.\n AttachedPreprocessingInfoType save_buf;\n SageInterface::cutPreprocessingInfo(f, \n PreprocessingInfo::before, \n save_buf) ;\n if (save_buf.size()) {\n SgVariableDeclaration *dummy = \n SageBuilder::buildVariableDeclaration(\n \"___htc_dummy_decl_for_preproc_info\", \n SageBuilder::buildIntType(), 0, f->get_scope());\n SageInterface::setExtern(dummy);\n\n SageInterface::insertStatementBefore(f, dummy);\n SageInterface::pastePreprocessingInfo(\n dummy, \n PreprocessingInfo::before, \n save_buf); \n }\n\n SageInterface::addTextForUnparser(\n f, \n \"\\n#if 0\", \n AstUnparseAttribute::e_before);\n\n std::string CapFnName = Capitalize(functionName);\n std::string before_body = \"\\n#endif\\n\";\n std::string macro_name = \"HTC_KEEP_MODULE_\" + Upper(functionName);\n before_body += \n \"#ifdef \" +\n macro_name +\n \"\\n\";\n before_body += \"#include \\\"Ht.h\\\"\\n\";\n before_body += \"#include \\\"Pers\" +\n CapFnName +\n \".h\\\"\\n\";\n before_body += \"#ifndef __htc_GW_write_addr\\n\";\n before_body += \"#define __htc_GW_write_addr(v,a) v.write_addr(a)\\n\";\n before_body += \"#endif\\n\";\n before_body += \"#ifndef __htc_GW_write_addr2\\n\";\n before_body += \"#define __htc_GW_write_addr2(v,a,b) v.write_addr(a,b)\\n\";\n before_body += \"#endif\\n\";\n before_body += \"void CPers\" +\n CapFnName +\n \"::Pers\" +\n CapFnName +\n \"()\\n\";\n SageInterface::addTextForUnparser(body, before_body,\n AstUnparseAttribute::e_before);\n std::string after_body =\n \"\\n#endif \/* \" +\n macro_name +\n \" *\/\\n\";\n SageInterface::addTextForUnparser(body, after_body,\n AstUnparseAttribute::e_after);\n \n \/\/ Write the _src.cpp file\n generate_src_cpp_file(fndef, CapFnName, macro_name); \n }\n }\n for (i = 0; i < fdeclList.size(); i++) {\n\n SgFunctionDeclaration *fdecl = fdeclList.at(i);\n\n if (!debugHooks && \n fdecl && \n fdecl->get_definingDeclaration() != fdecl) {\n\n \/\/ Move any preprocessing info before the function to a new\n \/\/ null statement preceding the function.\n AttachedPreprocessingInfoType save_buf;\n SageInterface::cutPreprocessingInfo(fdecl, \n PreprocessingInfo::before, \n save_buf) ;\n if (save_buf.size()) {\n SgVariableDeclaration *dummy2 = \n SageBuilder::buildVariableDeclaration(\n \"___htc_dummy_decl2_for_preproc_info\", \n SageBuilder::buildIntType(), \n 0, \n fdecl->get_scope());\n SageInterface::setExtern(dummy2);\n\n SageInterface::insertStatementBefore(fdecl, dummy2);\n SageInterface::pastePreprocessingInfo(\n dummy2, \n PreprocessingInfo::before, \n save_buf); \n\n }\n\n SageInterface::addTextForUnparser(fdecl, \"\\n\/* \",\n AstUnparseAttribute::e_before);\n SageInterface::addTextForUnparser(fdecl, \" *\/\",\n AstUnparseAttribute::e_after);\n \/\/ comment out function prototypes\n \/\/ fdecl->setCompilerGenerated();\n \/\/ fdecl->unsetOutputInCodeGeneration();\n }\n }\n\n }\n\n\n void generate_lock_src_cpp_files(std::string &path_name) {\n\n \/\/ Generate Pers_*_src.cpp file for Lock functions\n std::set<std::string>::iterator it;\n\n for (it = LockFunctionsInUse.begin(); it != LockFunctionsInUse.end(); it++) {\n std::string module_name = *it;\n std::string macro_name = \"HTC_KEEP_MODULE_\" + Upper(module_name);\n std::string cpp_name = path_name + \"Pers\" + \n Capitalize(module_name) + \"_src.cpp\";\n std::fstream fs;\n \n fs.open(cpp_name.c_str(), std::fstream::out | std::fstream::trunc);\n\n fs << \"#define \" << macro_name << std::endl;\n fs << \"#include \\\"rose_lock.c\\\"\" << std::endl;\n\n fs.close();\n }\n\n LockFunctionsInUse.clear();\n\n }\n\n void generate_src_cpp_file(SgFunctionDefinition *fndef,\n std::string &module_name,\n std::string ¯o_name) {\n\n std::pair<bool, std::string> fret = HtSageUtils::getFileName(fndef);\n std::string src_name = fret.second;\n std::string base_name = StringUtility::stripPathFromFileName(src_name);\n std::string path_name = StringUtility::getPathFromFileName(src_name) + \"\/\";\n std::string cpp_name= path_name + \"Pers\" + module_name + \"_src.cpp\";\n std::fstream fs;\n\n fs.open(cpp_name.c_str(), std::fstream::out | std::fstream::trunc);\n\n fs << \"#define \" << macro_name << std::endl;\n fs << \"#define CNY_HTC_COPROC\" << std::endl;\n fs << \"#include \\\"rose_\" << base_name << \"\\\"\" << std::endl;\n\n fs.close();\n\n generate_lock_src_cpp_files(path_name);\n\n }\n\nprivate:\n std::vector<SgFunctionDeclaration *> fdeclList;\n std::vector<SgFunctionDefinition *> fdefList;\n};\n\nvoid IsolateModulesToFiles(SgProject *project) {\n IsolateModules im;\n im.traverseInputFiles(project, preorder, STRICT_INPUT_FILE_TRAVERSAL);\n im.process();\n}\n<|endoftext|>"} {"text":"<commit_before>\/*******************************\nCopyright (c) 2016-2017 Grégoire Angerand\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n**********************************\/\n\n#include <yave\/device\/Device.h>\n#include <yave\/commands\/CmdBuffer.h>\n\nnamespace yave {\n\nstatic void check_features(const vk::PhysicalDeviceFeatures& features, const vk::PhysicalDeviceFeatures& required) {\n\tauto feats = reinterpret_cast<const vk::Bool32*>(&features);\n\tauto req = reinterpret_cast<const vk::Bool32*>(&required);\n\tfor(usize i = 0; i != sizeof(features) \/ sizeof(vk::Bool32); ++i) {\n\t\tif(req[i] && !feats[i]) {\n\t\t\tfatal(\"Required Vulkan feature not supported\");\n\t\t}\n\t}\n}\n\nstatic core::Vector<QueueFamily> compute_queue_families(vk::PhysicalDevice physical) {\n\tcore::Vector<QueueFamily> queue_families;\n\n\tauto families = physical.getQueueFamilyProperties();\n\tfor(u32 i = 0; i != families.size(); i++) {\n\t\tqueue_families << QueueFamily(i, families[i]);\n\t}\n\treturn queue_families;\n}\n\nstatic vk::Device create_device(\n\t\tvk::PhysicalDevice physical,\n\t\tconst core::Vector<QueueFamily>& queue_families,\n\t\tconst core::Vector<const char*>& extentions,\n\t\tconst DebugParams& debug) {\n\n\tauto queue_create_infos = core::vector_with_capacity<vk::DeviceQueueCreateInfo>(queue_families.size());\n\n\tfloat priorities = 1.0f;\n\tstd::transform(queue_families.begin(), queue_families.end(), std::back_inserter(queue_create_infos), [&](const auto& q) {\n\t\treturn vk::DeviceQueueCreateInfo()\n\t\t\t\t.setQueueFamilyIndex(q.index())\n\t\t\t\t.setPQueuePriorities(&priorities)\n\t\t\t\t.setQueueCount(q.count())\n\t\t\t;\n\t\t});\n\n\tauto required = vk::PhysicalDeviceFeatures();\n\trequired.multiDrawIndirect = true;\n\trequired.drawIndirectFirstInstance = true;\n\trequired.fullDrawIndexUint32 = true;\n\trequired.textureCompressionBC = true;\n\n\tif(debug.is_debug_callback_enabled()) {\n\t\trequired.robustBufferAccess = true;\n\t}\n\n\tcheck_features(physical.getFeatures(), required);\n\n\treturn physical.createDevice(vk::DeviceCreateInfo()\n\t\t\t.setEnabledExtensionCount(u32(extentions.size()))\n\t\t\t.setPpEnabledExtensionNames(extentions.begin())\n\t\t\t.setEnabledLayerCount(u32(debug.device_layers().size()))\n\t\t\t.setPpEnabledLayerNames(debug.device_layers().begin())\n\t\t\t.setQueueCreateInfoCount(queue_create_infos.size())\n\t\t\t.setPQueueCreateInfos(queue_create_infos.begin())\n\t\t\t.setPEnabledFeatures(&required)\n\t\t);\n}\n\n\nDevice::Device(Instance& instance) :\n\t\t_instance(instance),\n\t\t_physical(instance),\n\t\t_queue_families(compute_queue_families(_physical.vk_physical_device())),\n\t\t_device(create_device(_physical.vk_physical_device(), _queue_families, {VK_KHR_SWAPCHAIN_EXTENSION_NAME}, _instance.debug_params())),\n\t\t_sampler(this),\n\t\t_disposable_cmd_pool(this),\n\t\t_secondary_cmd_pool(this),\n\t\t_primary_cmd_pool(this),\n\t\t_descriptor_layout_pool(new DescriptorSetLayoutPool(this)) {\n\n\tfor(const auto& family : _queue_families) {\n\t\tauto q = family.fetch_queues(this);\n\t\t_queues.push_back(q.begin(), q.end());\n\t}\n}\n\nDevice::~Device() {\n\tfor(auto q : _queues) {\n\t\tq.waitIdle();\n\t}\n\n\tif(_disposable_cmd_pool.active_buffers()) {\n\t\tfatal(\"Buffer still active.\");\n\t}\n\n\t_sampler = Sampler();\n\n\t\/\/ we need to destroy the pools before the device\n\t_secondary_cmd_pool = CmdBufferPool<CmdBufferUsage::Secondary>();\n\t_disposable_cmd_pool = CmdBufferPool<CmdBufferUsage::Disposable>();\n\t_primary_cmd_pool = CmdBufferPool<CmdBufferUsage::Normal>();\n\n\tdelete _descriptor_layout_pool;\n\n\t_device.destroy();\n}\n\nconst PhysicalDevice& Device::physical_device() const {\n\treturn _physical;\n}\n\nconst Instance &Device::instance() const {\n\treturn _instance;\n}\n\nvk::Device Device::vk_device() const {\n\treturn _device;\n}\n\nvk::Queue Device::vk_queue(vk::QueueFlags) const {\n#warning change Device::vk_queue\n\treturn _queues.first();\n}\n\nvk::Sampler Device::vk_sampler() const {\n\treturn _sampler.vk_sampler();\n}\n\nconst QueueFamily& Device::queue_family(vk::QueueFlags flags) const {\n\tfor(const auto& q : _queue_families) {\n\t\tif((q.flags() & flags) == flags) {\n\t\t\treturn q;\n\t\t}\n\t}\n\treturn fatal(\"Unable to find queue.\");\n}\n\n}\n<commit_msg>fixed warning.<commit_after>\/*******************************\nCopyright (c) 2016-2017 Grégoire Angerand\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n**********************************\/\n\n#include <yave\/device\/Device.h>\n#include <yave\/commands\/CmdBuffer.h>\n\nnamespace yave {\n\nstatic void check_features(const vk::PhysicalDeviceFeatures& features, const vk::PhysicalDeviceFeatures& required) {\n\tauto feats = reinterpret_cast<const vk::Bool32*>(&features);\n\tauto req = reinterpret_cast<const vk::Bool32*>(&required);\n\tfor(usize i = 0; i != sizeof(features) \/ sizeof(vk::Bool32); ++i) {\n\t\tif(req[i] && !feats[i]) {\n\t\t\tfatal(\"Required Vulkan feature not supported\");\n\t\t}\n\t}\n}\n\nstatic core::Vector<QueueFamily> compute_queue_families(vk::PhysicalDevice physical) {\n\tcore::Vector<QueueFamily> queue_families;\n\n\tauto families = physical.getQueueFamilyProperties();\n\tfor(u32 i = 0; i != families.size(); i++) {\n\t\tqueue_families << QueueFamily(i, families[i]);\n\t}\n\treturn queue_families;\n}\n\nstatic vk::Device create_device(\n\t\tvk::PhysicalDevice physical,\n\t\tconst core::Vector<QueueFamily>& queue_families,\n\t\tconst core::Vector<const char*>& extentions,\n\t\tconst DebugParams& debug) {\n\n\tauto queue_create_infos = core::vector_with_capacity<vk::DeviceQueueCreateInfo>(queue_families.size());\n\n\tfloat priorities = 1.0f;\n\tstd::transform(queue_families.begin(), queue_families.end(), std::back_inserter(queue_create_infos), [&](const auto& q) {\n\t\treturn vk::DeviceQueueCreateInfo()\n\t\t\t\t.setQueueFamilyIndex(q.index())\n\t\t\t\t.setPQueuePriorities(&priorities)\n\t\t\t\t.setQueueCount(q.count())\n\t\t\t;\n\t\t});\n\n\tauto required = vk::PhysicalDeviceFeatures();\n\trequired.multiDrawIndirect = true;\n\trequired.drawIndirectFirstInstance = true;\n\trequired.fullDrawIndexUint32 = true;\n\trequired.textureCompressionBC = true;\n\n\tif(debug.is_debug_callback_enabled()) {\n\t\trequired.robustBufferAccess = true;\n\t}\n\n\tcheck_features(physical.getFeatures(), required);\n\n\treturn physical.createDevice(vk::DeviceCreateInfo()\n\t\t\t.setEnabledExtensionCount(u32(extentions.size()))\n\t\t\t.setPpEnabledExtensionNames(extentions.begin())\n\t\t\t.setEnabledLayerCount(u32(debug.device_layers().size()))\n\t\t\t.setPpEnabledLayerNames(debug.device_layers().begin())\n\t\t\t.setQueueCreateInfoCount(queue_create_infos.size())\n\t\t\t.setPQueueCreateInfos(queue_create_infos.begin())\n\t\t\t.setPEnabledFeatures(&required)\n\t\t);\n}\n\n\nDevice::Device(Instance& instance) :\n\t\t_instance(instance),\n\t\t_physical(instance),\n\t\t_queue_families(compute_queue_families(_physical.vk_physical_device())),\n\t\t_device(create_device(_physical.vk_physical_device(), _queue_families, {VK_KHR_SWAPCHAIN_EXTENSION_NAME}, _instance.debug_params())),\n\t\t_sampler(this),\n\t\t_secondary_cmd_pool(this),\n\t\t_disposable_cmd_pool(this),\n\t\t_primary_cmd_pool(this),\n\t\t_descriptor_layout_pool(new DescriptorSetLayoutPool(this)) {\n\n\tfor(const auto& family : _queue_families) {\n\t\tauto q = family.fetch_queues(this);\n\t\t_queues.push_back(q.begin(), q.end());\n\t}\n}\n\nDevice::~Device() {\n\tfor(auto q : _queues) {\n\t\tq.waitIdle();\n\t}\n\n\tif(_disposable_cmd_pool.active_buffers()) {\n\t\tfatal(\"Buffer still active.\");\n\t}\n\n\t_sampler = Sampler();\n\n\t\/\/ we need to destroy the pools before the device\n\t_secondary_cmd_pool = CmdBufferPool<CmdBufferUsage::Secondary>();\n\t_disposable_cmd_pool = CmdBufferPool<CmdBufferUsage::Disposable>();\n\t_primary_cmd_pool = CmdBufferPool<CmdBufferUsage::Normal>();\n\n\tdelete _descriptor_layout_pool;\n\n\t_device.destroy();\n}\n\nconst PhysicalDevice& Device::physical_device() const {\n\treturn _physical;\n}\n\nconst Instance &Device::instance() const {\n\treturn _instance;\n}\n\nvk::Device Device::vk_device() const {\n\treturn _device;\n}\n\nvk::Queue Device::vk_queue(vk::QueueFlags) const {\n#warning change Device::vk_queue\n\treturn _queues.first();\n}\n\nvk::Sampler Device::vk_sampler() const {\n\treturn _sampler.vk_sampler();\n}\n\nconst QueueFamily& Device::queue_family(vk::QueueFlags flags) const {\n\tfor(const auto& q : _queue_families) {\n\t\tif((q.flags() & flags) == flags) {\n\t\t\treturn q;\n\t\t}\n\t}\n\treturn fatal(\"Unable to find queue.\");\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before>#include <omp.h>\n#include <stdio.h>\n#include <opencv2\/opencv.hpp>\n#include <fstream>\n#include <iostream>\n#include <armadillo>\n#include <iomanip>\n#include <vector>\n\nusing namespace std;\nusing namespace arma;\n\n#include \"grass-def.hpp\"\n#include \"grass-impl.hpp\"\n\n\n\n\n\/\/Home\n\/\/const std::string path = \"\/media\/johanna\/HD1T\/codes\/datasets_codes\/KTH\/\"; \n\n\/\/WANDA\nconst std::string path = \"\/home\/johanna\/codes\/codes-git\/study-paper\/trunk\/features\/\";\n\n\n\nconst std::string peopleList = \"people_list.txt\";\nconst std::string actionNames = \"actionNames.txt\";\n\n\/\/\/kth\n\/\/ int ori_col = 160;\n\/\/ int ori_row = 120;\n\n\n\n\n\nint\nmain(int argc, char** argv)\n{\n \n \/\/ if(argc < 3 )\n \/\/ {\n \/\/ cout << \"usage: \" << argv[0] << \" scale_factor \" << \" shift_factor \" << endl;\n \/\/ return -1;\n \/\/ }\n \/\/ \n \/\/ \n \/\/ int scale_factor = atoi( argv[1] );\n \/\/ int shift = atoi( argv[2] );\n \n \n vec vec_shift;\n vec_shift << -25 << -20 << -15 << -10 << -5 << 5 << 10 << 15 << 20 << 25 << endr;\n int scale_factor =1;\n \n int total_scenes = 1; \/\/Try only with scenario 1\n int segment_length = 20;\n \/\/int p = 12; \/\/To obtain the optimise sub-space of order p\n int dim = 14; \n \n \/\/for (int i=0; i< vec_shift.n_elem; ++i)\n for (int p=1; p<= dim; ++p)\n {\n \n \/\/int shift = vec_shift(i);\n int shift = 0;\n cout << \"Gp for p= \" << p << endl;\n \n \n field<string> all_people;\n all_people.load(peopleList);\n \n grass_points get_gp(path, actionNames, scale_factor, shift, total_scenes, segment_length, p);\n \/\/get_gp.calculate( all_people, dim );\n get_gp.calculate_onepervideo( all_people, dim );\n }\n \n return 0;\n \n}\n<commit_msg>Get all Grassmann points for all shifts and p<commit_after>#include <omp.h>\n#include <stdio.h>\n#include <opencv2\/opencv.hpp>\n#include <fstream>\n#include <iostream>\n#include <armadillo>\n#include <iomanip>\n#include <vector>\n\nusing namespace std;\nusing namespace arma;\n\n#include \"grass-def.hpp\"\n#include \"grass-impl.hpp\"\n\n\n\n\n\/\/Home\n\/\/const std::string path = \"\/media\/johanna\/HD1T\/codes\/datasets_codes\/KTH\/\"; \n\n\/\/WANDA\nconst std::string path = \"\/home\/johanna\/codes\/codes-git\/study-paper\/trunk\/features\/\";\n\n\n\nconst std::string peopleList = \"people_list.txt\";\nconst std::string actionNames = \"actionNames.txt\";\n\n\/\/\/kth\n\/\/ int ori_col = 160;\n\/\/ int ori_row = 120;\n\n\n\n\n\nint\nmain(int argc, char** argv)\n{\n \n \/\/ if(argc < 3 )\n \/\/ {\n \/\/ cout << \"usage: \" << argv[0] << \" scale_factor \" << \" shift_factor \" << endl;\n \/\/ return -1;\n \/\/ }\n \/\/ \n \/\/ \n \/\/ int scale_factor = atoi( argv[1] );\n \/\/ int shift = atoi( argv[2] );\n \n \n vec vec_shift;\n vec_shift << -25 << -20 << -15 << -10 << -5 << 5 << 10 << 15 << 20 << 25 << endr;\n int scale_factor =1;\n \n int total_scenes = 1; \/\/Try only with scenario 1\n int segment_length = 20;\n \/\/int p = 12; \/\/To obtain the optimise sub-space of order p\n int dim = 14; \n \n for (int i=0; i< vec_shift.n_elem; ++i)\n {\n for (int p=1; p<= dim; ++p)\n {\n \n int shift = vec_shift(i);\n cout << \"Gp for shift \" << shift << \" & p= \" << p << endl;\n \n \n field<string> all_people;\n all_people.load(peopleList);\n \n grass_points get_gp(path, actionNames, scale_factor, shift, total_scenes, segment_length, p);\n \/\/get_gp.calculate( all_people, dim );\n get_gp.calculate_onepervideo( all_people, dim );\n }\n }\n \n return 0;\n \n}\n<|endoftext|>"} {"text":"<commit_before>#ifndef DUNE_STUFF_DATA_PROVIDER_SPE10_HH\n#define DUNE_STUFF_DATA_PROVIDER_SPE10_HH\n\n#ifdef HAVE_CMAKE_CONFIG\n #include \"cmake_config.h\"\n#else\n #include \"config.h\"\n#endif \/\/ ifdef HAVE_CMAKE_CONFIG\n\n\/\/ system\n#include <iostream>\n#include <sstream>\n\n\/\/ eigen\n#ifdef HAVE_EIGEN\n#include <Eigen\/Core>\n#endif \/\/ HAVE_EIGEN\n\n\/\/ dune-common\n#include <dune\/common\/exceptions.hh>\n#include <dune\/common\/shared_ptr.hh>\n#include <dune\/common\/parametertree.hh>\n#include <dune\/common\/dynmatrix.hh>\n#include <dune\/common\/densevector.hh>\n\n\/\/ dune-stuff\n#include <dune\/stuff\/common\/logging.hh>\n#include <dune\/stuff\/common\/parameter\/tree.hh>\n#include <dune\/stuff\/common\/parameter\/configcontainer.hh>\n\nnamespace Dune {\nnamespace Stuff {\nnamespace Data {\nnamespace Provider {\nnamespace Spe10 {\nnamespace Model1 {\n\ntemplate< class DomainFieldImp, int domainDimension, class RangeFieldImp, int rangeDimension >\nclass Permeability;\n\ntemplate< class DomainFieldImp, class RangeFieldImp >\nclass Permeability< DomainFieldImp, 2, RangeFieldImp, 1 >\n{\npublic:\n typedef DomainFieldImp DomainFieldType;\n\n static const int dimDomain = 2;\n\n typedef RangeFieldImp RangeFieldType;\n\n static const int dimRange = 1;\n\n typedef Permeability< DomainFieldType, dimDomain, RangeFieldType, dimRange > ThisType;\n\n static const std::string id;\n\n class Function\n {\n public:\n Function(const DomainFieldType& lowerLeftX,\n const DomainFieldType& lowerLeftY,\n const DomainFieldType& upperRightX,\n const DomainFieldType& upperRightY,\n const unsigned int& numElementsX,\n const unsigned int& numElementsY,\n const Dune::shared_ptr< const Dune::DynamicMatrix< RangeFieldType > >& data)\n : lowerLeftX_(lowerLeftX)\n , lowerLeftY_(lowerLeftY)\n , upperRightX_(upperRightX)\n , upperRightY_(upperRightY)\n , numElementsX_(numElementsX)\n , numElementsY_(numElementsY)\n , data_(data)\n {}\n\n template< class DomainVectorType, class RangeVectorType >\n void evaluate(const Dune::DenseVector< DomainVectorType >& arg, Dune::DenseVector< RangeVectorType >& ret) const\n {\n \/\/ ensure right dimensions\n assert(arg.size() == dimDomain);\n assert(ret.size() == dimRange);\n \/\/ find i and j\n unsigned int i = std::floor(numElementsX_*((arg[0] - lowerLeftX_)\/(upperRightX_ - lowerLeftX_)));\n unsigned int j = std::floor(numElementsY_*((arg[1] - lowerLeftY_)\/(upperRightY_ - lowerLeftY_)));\n \/\/ return\n ret[0] = data_->operator[](i)[j];\n }\n\n#ifdef HAVE_EIGEN\n void evaluate(const Eigen::VectorXd& arg, Eigen::VectorXd& ret) const\n {\n \/\/ ensure right dimensions\n assert(arg.rows() == dimDomain);\n assert(ret.rows() == dimRange);\n \/\/ find i and j\n unsigned int i = std::floor(numElementsX_*((arg(0) - lowerLeftX_)\/(upperRightX_ - lowerLeftX_)));\n unsigned int j = std::floor(numElementsY_*((arg(1) - lowerLeftY_)\/(upperRightY_ - lowerLeftY_)));\n \/\/ return\n ret(0) = data_->operator[](i)[j];\n }\n#endif \/\/ HAVE_EIGEN\n\n private:\n const DomainFieldType lowerLeftX_,;\n const DomainFieldType lowerLeftY_;\n const DomainFieldType upperRightX_;\n const DomainFieldType upperRightY_;\n const unsigned int numElementsX_;\n const unsigned int numElementsY_;\n const Dune::shared_ptr< const Dune::DynamicMatrix< RangeFieldType > > data_;\n }; \/\/ class Function\n\n const Dune::shared_ptr< const Function > create(const Dune::ParameterTree& paramTree,\n const std::string prefix = \"\",\n std::ostream& out = Dune::Stuff::Common::Logger().debug()) const\n {\n \/\/ preparations\n std::string filename;\n DomainFieldType lowerLeftX, lowerLeftY;\n DomainFieldType upperRightX, upperRightY;\n unsigned int numElementsX, numElementsY;\n readAndAssertParamTree(paramTree, filename,\n lowerLeftX, lowerLeftY,\n upperRightX, upperRightY,\n numElementsX, numElementsY);\n out << prefix << \"reading 'spe10.model1.permeability' from \" << filename << \"... \";\n RangeFieldType* rawData = new RangeFieldType[100*20];\n readRawDataFromFile(filename, rawData);\n Dune::shared_ptr< Dune::DynamicMatrix< RangeFieldType > >\n data = Dune::shared_ptr< Dune::DynamicMatrix< RangeFieldType > >(new Dune::DynamicMatrix< RangeFieldType >(numElementsX, numElementsY, 0.0));\n fillDataFromRaw(rawData, *data);\n out << \"done\" << std::endl;\n const Dune::shared_ptr< const Function >\n function = Dune::shared_ptr< const Function >(new Function(lowerLeftX,\n lowerLeftY,\n upperRightX,\n upperRightY,\n numElementsX,\n numElementsY,\n data));\n return function;\n } \/\/ const Dune::shared_ptr< const Function > create() const\n\nprivate:\n void readAndAssertParamTree(const Dune::ParameterTree& paramTree,\n std::string& filename,\n DomainFieldType& lowerLeftX,\n DomainFieldType& lowerLeftY,\n DomainFieldType& upperRightX,\n DomainFieldType& upperRightY,\n unsigned int& numElementsX,\n unsigned int& numElementsY) const\n {\n Dune::Stuff::Common::ExtendedParameterTree::assertKey(paramTree, \"filename\", id);\n filename = paramTree.get(\"filename\", \"..\/..\/..\/..\/..\/data\/spe10\/model1\/spe10_model1_permeability.dat\");\n Dune::Stuff::Common::ExtendedParameterTree::assertKey(paramTree, \"lowerLeft.0\", id);\n lowerLeftX = paramTree.get(\"lowerLeft.0\", 0.0);\n Dune::Stuff::Common::ExtendedParameterTree::assertKey(paramTree, \"lowerLeft.1\", id);\n lowerLeftY = paramTree.get(\"lowerLeft.1\", 0.0);\n Dune::Stuff::Common::ExtendedParameterTree::assertKey(paramTree, \"upperRight.0\", id);\n upperRightX = paramTree.get(\"upperRight.0\", 762.0);\n Dune::Stuff::Common::ExtendedParameterTree::assertKey(paramTree, \"upperRight.1\", id);\n upperRightY = paramTree.get(\"upperRight.1\", 15.24);\n Dune::Stuff::Common::ExtendedParameterTree::assertKey(paramTree, \"numElements.0\", id);\n numElementsX = paramTree.get(\"numElements.0\", 100);\n Dune::Stuff::Common::ExtendedParameterTree::assertKey(paramTree, \"numElements.1\", id);\n numElementsY = paramTree.get(\"numElements.1\", 20);\n \/\/ make sure everything is all right\n bool kaboom = false;\n std::stringstream msg;\n msg << \"Error in \" << id << \": the following errors were found while reading the Dune::ParameterTree given below!\" << std::endl;\n if (!(lowerLeftX < upperRightX)) {\n kaboom = true;\n msg << \"- !(lowerLeft.0 < upperRight.0): !(\" << lowerLeftX << \" < \" << upperRightX << \")\" << std::endl;\n }\n if (!(lowerLeftY < upperRightY)) {\n kaboom = true;\n msg << \"- !(lowerLeft.1 < upperRight.1): !(\" << lowerLeftY << \" < \" << upperRightY << \")\" << std::endl;\n }\n if (!(numElementsX > 0)) {\n kaboom = true;\n msg << \"- !(numElements.0 > 0): !(\" << numElementsX << \" > 0)\" << std::endl;\n }\n if (!(numElementsX <= 100)) {\n kaboom = true;\n msg << \"- !(numElements.0 <= 100): !(\" << numElementsX << \" <= 100)\" << std::endl;\n }\n if (!(numElementsY <= 20)) {\n kaboom = true;\n msg << \"- !(numElements.Y <= 20): !(\" << numElementsY << \" <= 20)\" << std::endl;\n }\n \/\/ test if we can open the file\n const bool can_open(std::ifstream(filename.c_str()).is_open());\n if (!can_open) {\n kaboom = true;\n msg << \"- could not open file given by 'filename': '\" << filename << \"'\" << std::endl;\n }\n \/\/ throw up if we have to\n if (kaboom) {\n msg << \"given in the following Dune::ParameterTree:\" << std::endl;\n paramTree.report(msg);\n DUNE_THROW(Dune::InvalidStateException, msg.str());\n }\n } \/\/ void readAndAssertParamTree() const\n\n void readRawDataFromFile(const std::string filename, RangeFieldType* rawData) const\n {\n std::ifstream file(filename.c_str());\n assert(file && \"After we checked before, this should really not blow up right now!\");\n RangeFieldType val;\n file >> val;\n unsigned int counter = 0;\n while (!file.eof()) {\n rawData[counter++] = val;\n file >> val;\n }\n file.close();\n } \/\/ void readRawDataFromFile(const std::string filename, DomainFieldType* rawData) const\n\n void fillDataFromRaw(RangeFieldType* rawData, Dune::DynamicMatrix< RangeFieldType >& data) const\n {\n unsigned int counter = 0;\n for (unsigned int i = 0; i < data.rows(); ++ i) {\n for (unsigned int j = 0; j < data.cols(); ++j) {\n data[i][j] = rawData[counter];\n ++counter;\n }\n }\n } \/\/ void fillDatFromRaw(RangeFieldType* rawData, Dune::DynamicMatrix< RangeFieldType >& data) const\n}; \/\/ class Permeability\n\ntemplate< class DomainFieldType, class RangeFieldType >\nconst std::string Permeability< DomainFieldType, 2, RangeFieldType, 1 >::id = \"stuff.data.provider.spe10.model1.permeability\";\n\n} \/\/ namespace Model1\n} \/\/ namespace Spe10\n} \/\/ namespace Provider\n} \/\/ namespace Data\n} \/\/ namespace Stuff\n} \/\/ namespace Dune\n\n#endif \/\/ DUNE_STUFF_DATA_PROVIDER_SPE10_HH\n<commit_msg>[data] fix c&p fail<commit_after>#ifndef DUNE_STUFF_DATA_PROVIDER_SPE10_HH\n#define DUNE_STUFF_DATA_PROVIDER_SPE10_HH\n\n#ifdef HAVE_CMAKE_CONFIG\n #include \"cmake_config.h\"\n#else\n #include \"config.h\"\n#endif \/\/ ifdef HAVE_CMAKE_CONFIG\n\n\/\/ system\n#include <iostream>\n#include <sstream>\n\n\/\/ eigen\n#ifdef HAVE_EIGEN\n#include <Eigen\/Core>\n#endif \/\/ HAVE_EIGEN\n\n\/\/ dune-common\n#include <dune\/common\/exceptions.hh>\n#include <dune\/common\/shared_ptr.hh>\n#include <dune\/common\/parametertree.hh>\n#include <dune\/common\/dynmatrix.hh>\n#include <dune\/common\/densevector.hh>\n\n\/\/ dune-stuff\n#include <dune\/stuff\/common\/logging.hh>\n#include <dune\/stuff\/common\/parameter\/tree.hh>\n#include <dune\/stuff\/common\/parameter\/configcontainer.hh>\n\nnamespace Dune {\nnamespace Stuff {\nnamespace Data {\nnamespace Provider {\nnamespace Spe10 {\nnamespace Model1 {\n\ntemplate< class DomainFieldImp, int domainDimension, class RangeFieldImp, int rangeDimension >\nclass Permeability;\n\ntemplate< class DomainFieldImp, class RangeFieldImp >\nclass Permeability< DomainFieldImp, 2, RangeFieldImp, 1 >\n{\npublic:\n typedef DomainFieldImp DomainFieldType;\n\n static const int dimDomain = 2;\n\n typedef RangeFieldImp RangeFieldType;\n\n static const int dimRange = 1;\n\n typedef Permeability< DomainFieldType, dimDomain, RangeFieldType, dimRange > ThisType;\n\n static const std::string id;\n\n class Function\n {\n public:\n Function(const DomainFieldType& lowerLeftX,\n const DomainFieldType& lowerLeftY,\n const DomainFieldType& upperRightX,\n const DomainFieldType& upperRightY,\n const unsigned int& numElementsX,\n const unsigned int& numElementsY,\n const Dune::shared_ptr< const Dune::DynamicMatrix< RangeFieldType > >& data)\n : lowerLeftX_(lowerLeftX)\n , lowerLeftY_(lowerLeftY)\n , upperRightX_(upperRightX)\n , upperRightY_(upperRightY)\n , numElementsX_(numElementsX)\n , numElementsY_(numElementsY)\n , data_(data)\n {}\n\n template< class DomainVectorType, class RangeVectorType >\n void evaluate(const Dune::DenseVector< DomainVectorType >& arg, Dune::DenseVector< RangeVectorType >& ret) const\n {\n \/\/ ensure right dimensions\n assert(arg.size() == dimDomain);\n assert(ret.size() == dimRange);\n \/\/ find i and j\n unsigned int i = std::floor(numElementsX_*((arg[0] - lowerLeftX_)\/(upperRightX_ - lowerLeftX_)));\n unsigned int j = std::floor(numElementsY_*((arg[1] - lowerLeftY_)\/(upperRightY_ - lowerLeftY_)));\n \/\/ return\n ret[0] = data_->operator[](i)[j];\n }\n\n#ifdef HAVE_EIGEN\n void evaluate(const Eigen::VectorXd& arg, Eigen::VectorXd& ret) const\n {\n \/\/ ensure right dimensions\n assert(arg.rows() == dimDomain);\n assert(ret.rows() == dimRange);\n \/\/ find i and j\n unsigned int i = std::floor(numElementsX_*((arg(0) - lowerLeftX_)\/(upperRightX_ - lowerLeftX_)));\n unsigned int j = std::floor(numElementsY_*((arg(1) - lowerLeftY_)\/(upperRightY_ - lowerLeftY_)));\n \/\/ return\n ret(0) = data_->operator[](i)[j];\n }\n#endif \/\/ HAVE_EIGEN\n\n private:\n const DomainFieldType lowerLeftX_;\n const DomainFieldType lowerLeftY_;\n const DomainFieldType upperRightX_;\n const DomainFieldType upperRightY_;\n const unsigned int numElementsX_;\n const unsigned int numElementsY_;\n const Dune::shared_ptr< const Dune::DynamicMatrix< RangeFieldType > > data_;\n }; \/\/ class Function\n\n const Dune::shared_ptr< const Function > create(const Dune::ParameterTree& paramTree,\n const std::string prefix = \"\",\n std::ostream& out = Dune::Stuff::Common::Logger().debug()) const\n {\n \/\/ preparations\n std::string filename;\n DomainFieldType lowerLeftX, lowerLeftY;\n DomainFieldType upperRightX, upperRightY;\n unsigned int numElementsX, numElementsY;\n readAndAssertParamTree(paramTree, filename,\n lowerLeftX, lowerLeftY,\n upperRightX, upperRightY,\n numElementsX, numElementsY);\n out << prefix << \"reading 'spe10.model1.permeability' from \" << filename << \"... \";\n RangeFieldType* rawData = new RangeFieldType[100*20];\n readRawDataFromFile(filename, rawData);\n Dune::shared_ptr< Dune::DynamicMatrix< RangeFieldType > >\n data = Dune::shared_ptr< Dune::DynamicMatrix< RangeFieldType > >(new Dune::DynamicMatrix< RangeFieldType >(numElementsX, numElementsY, 0.0));\n fillDataFromRaw(rawData, *data);\n out << \"done\" << std::endl;\n const Dune::shared_ptr< const Function >\n function = Dune::shared_ptr< const Function >(new Function(lowerLeftX,\n lowerLeftY,\n upperRightX,\n upperRightY,\n numElementsX,\n numElementsY,\n data));\n return function;\n } \/\/ const Dune::shared_ptr< const Function > create() const\n\nprivate:\n void readAndAssertParamTree(const Dune::ParameterTree& paramTree,\n std::string& filename,\n DomainFieldType& lowerLeftX,\n DomainFieldType& lowerLeftY,\n DomainFieldType& upperRightX,\n DomainFieldType& upperRightY,\n unsigned int& numElementsX,\n unsigned int& numElementsY) const\n {\n Dune::Stuff::Common::ExtendedParameterTree::assertKey(paramTree, \"filename\", id);\n filename = paramTree.get(\"filename\", \"..\/..\/..\/..\/..\/data\/spe10\/model1\/spe10_model1_permeability.dat\");\n Dune::Stuff::Common::ExtendedParameterTree::assertKey(paramTree, \"lowerLeft.0\", id);\n lowerLeftX = paramTree.get(\"lowerLeft.0\", 0.0);\n Dune::Stuff::Common::ExtendedParameterTree::assertKey(paramTree, \"lowerLeft.1\", id);\n lowerLeftY = paramTree.get(\"lowerLeft.1\", 0.0);\n Dune::Stuff::Common::ExtendedParameterTree::assertKey(paramTree, \"upperRight.0\", id);\n upperRightX = paramTree.get(\"upperRight.0\", 762.0);\n Dune::Stuff::Common::ExtendedParameterTree::assertKey(paramTree, \"upperRight.1\", id);\n upperRightY = paramTree.get(\"upperRight.1\", 15.24);\n Dune::Stuff::Common::ExtendedParameterTree::assertKey(paramTree, \"numElements.0\", id);\n numElementsX = paramTree.get(\"numElements.0\", 100);\n Dune::Stuff::Common::ExtendedParameterTree::assertKey(paramTree, \"numElements.1\", id);\n numElementsY = paramTree.get(\"numElements.1\", 20);\n \/\/ make sure everything is all right\n bool kaboom = false;\n std::stringstream msg;\n msg << \"Error in \" << id << \": the following errors were found while reading the Dune::ParameterTree given below!\" << std::endl;\n if (!(lowerLeftX < upperRightX)) {\n kaboom = true;\n msg << \"- !(lowerLeft.0 < upperRight.0): !(\" << lowerLeftX << \" < \" << upperRightX << \")\" << std::endl;\n }\n if (!(lowerLeftY < upperRightY)) {\n kaboom = true;\n msg << \"- !(lowerLeft.1 < upperRight.1): !(\" << lowerLeftY << \" < \" << upperRightY << \")\" << std::endl;\n }\n if (!(numElementsX > 0)) {\n kaboom = true;\n msg << \"- !(numElements.0 > 0): !(\" << numElementsX << \" > 0)\" << std::endl;\n }\n if (!(numElementsX <= 100)) {\n kaboom = true;\n msg << \"- !(numElements.0 <= 100): !(\" << numElementsX << \" <= 100)\" << std::endl;\n }\n if (!(numElementsY <= 20)) {\n kaboom = true;\n msg << \"- !(numElements.Y <= 20): !(\" << numElementsY << \" <= 20)\" << std::endl;\n }\n \/\/ test if we can open the file\n const bool can_open(std::ifstream(filename.c_str()).is_open());\n if (!can_open) {\n kaboom = true;\n msg << \"- could not open file given by 'filename': '\" << filename << \"'\" << std::endl;\n }\n \/\/ throw up if we have to\n if (kaboom) {\n msg << \"given in the following Dune::ParameterTree:\" << std::endl;\n paramTree.report(msg);\n DUNE_THROW(Dune::InvalidStateException, msg.str());\n }\n } \/\/ void readAndAssertParamTree() const\n\n void readRawDataFromFile(const std::string filename, RangeFieldType* rawData) const\n {\n std::ifstream file(filename.c_str());\n assert(file && \"After we checked before, this should really not blow up right now!\");\n RangeFieldType val;\n file >> val;\n unsigned int counter = 0;\n while (!file.eof()) {\n rawData[counter++] = val;\n file >> val;\n }\n file.close();\n } \/\/ void readRawDataFromFile(const std::string filename, DomainFieldType* rawData) const\n\n void fillDataFromRaw(RangeFieldType* rawData, Dune::DynamicMatrix< RangeFieldType >& data) const\n {\n unsigned int counter = 0;\n for (unsigned int i = 0; i < data.rows(); ++ i) {\n for (unsigned int j = 0; j < data.cols(); ++j) {\n data[i][j] = rawData[counter];\n ++counter;\n }\n }\n } \/\/ void fillDatFromRaw(RangeFieldType* rawData, Dune::DynamicMatrix< RangeFieldType >& data) const\n}; \/\/ class Permeability\n\ntemplate< class DomainFieldType, class RangeFieldType >\nconst std::string Permeability< DomainFieldType, 2, RangeFieldType, 1 >::id = \"stuff.data.provider.spe10.model1.permeability\";\n\n} \/\/ namespace Model1\n} \/\/ namespace Spe10\n} \/\/ namespace Provider\n} \/\/ namespace Data\n} \/\/ namespace Stuff\n} \/\/ namespace Dune\n\n#endif \/\/ DUNE_STUFF_DATA_PROVIDER_SPE10_HH\n<|endoftext|>"} {"text":"<commit_before>\/**\n * Definition for singly-linked list.\n * struct ListNode {\n * int val;\n * ListNode *next;\n * ListNode(int x) : val(x), next(NULL) {}\n * };\n *\/\nclass Solution {\npublic:\n ListNode *removeNthFromEnd(ListNode *head, int n) {\n \/\/ fast and slow pointer\n ListNode* fast = head;\n ListNode** slow = &head;\n\n while (n--) {\n fast = fast->next;\n }\n for (int i = 0; fast != NULL; ++i) {\n fast = fast->next;\n slow = &(*slow)->next;\n }\n *slow = (*slow)->next;\n return head;\n }\n};\n<commit_msg>Update remove-nth-node-from-end-of-list.cc<commit_after>\/**\n * Definition for singly-linked list.\n * struct ListNode {\n * int val;\n * ListNode *next;\n * ListNode(int x) : val(x), next(NULL) {}\n * };\n *\/\nclass Solution {\npublic:\n ListNode *removeNthFromEnd(ListNode *head, int n) {\n \/\/ fast and slow pointer\n ListNode* fast = head;\n ListNode** slow = &head;\n\n while (n--) {\n fast = fast->next;\n }\n\n while (fast != NULL) {\n fast = fast->next;\n slow = &(*slow)->next;\n }\n *slow = (*slow)->next;\n return head;\n }\n};\n<|endoftext|>"} {"text":"<commit_before>\/*\n * GridMapPclConverter.hpp\n *\n * Created on: Apr 14, 2016\n * Author: Dominic Jud\n * Institute: ETH Zurich, Robotic Systems Lab\n *\/\n\n#pragma once\n\n#include <grid_map_core\/grid_map_core.hpp>\n\n\/\/ PCL\n#include <pcl\/point_cloud.h>\n#include <pcl\/point_types.h>\n#include <pcl\/conversions.h>\n#include <pcl\/PolygonMesh.h>\n#include <pcl\/common\/common.h>\n\n\/\/ STD\n#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <cmath>\n\nnamespace grid_map {\n\n\/*!\n * Conversions between grid maps and PCL types.\n *\/\nclass GridMapPclConverter\n{\n public:\n \/*!\n * Default constructor.\n *\/\n GridMapPclConverter();\n\n \/*!\n * Destructor.\n *\/\n virtual ~GridMapPclConverter();\n\n \/*!\n * Initializes the geometry of a grid map from a polygon mesh. This changes\n * the geometry of the map and deletes all contents of the layers!\n * @param[in] mesh the mesh.\n * @param[in] resolution the desired resolution of the grid map [m\/cell].\n * @param[out] gridMap the grid map to be initialized.\n * @return true if successful, false otherwise.\n *\/\n static bool initializeFromPolygonMesh(const pcl::PolygonMesh& mesh, const double resolution,\n grid_map::GridMap& gridMap);\n\n \/*!\n * Adds a layer with data from a polygon mesh. The mesh is ray traced from\n * above (negative z-Direction).\n * @param[in] mesh the mesh to be added. It can only consist of triangles!\n * @param[in] layer the layer that is filled with the mesh data.\n * @param[out] gridMap the grid map to be populated.\n * @return true if successful, false otherwise.\n *\/\n static bool addLayerFromPolygonMesh(const pcl::PolygonMesh& mesh, const std::string& layer,\n grid_map::GridMap& gridMap);\n\n private:\n\/* static bool rayTriangleIntersect(const pcl::PointXYZ& point, const Eigen::Vector3f& ray,\n const pcl::Vertices& vertices,\n const pcl::PointCloud<pcl::PointXYZ>& pointCloud,\n pcl::PointXYZ& intersectionPoint);\n*\/\n static bool rayTriangleIntersect(const Eigen::Vector3f& point,\n const Eigen::Vector3f& ray,\n const Eigen::Matrix3f& triangleVertices,\n Eigen::Vector3f& intersectionPoint);\n\n \/* static void testInside(const pcl::PointCloud<pcl::PointXYZ>& pointCloud,\n const std::vector<pcl::Vertices>& polygons,\n const grid_map::Position& vertexPositionXY);*\/\n\n\n};\n\n} \/* namespace *\/\n<commit_msg>clean up.<commit_after>\/*\n * GridMapPclConverter.hpp\n *\n * Created on: Apr 14, 2016\n * Author: Dominic Jud\n * Institute: ETH Zurich, Robotic Systems Lab\n *\/\n\n#pragma once\n\n#include <grid_map_core\/grid_map_core.hpp>\n\n\/\/ PCL\n#include <pcl\/point_cloud.h>\n#include <pcl\/point_types.h>\n#include <pcl\/conversions.h>\n#include <pcl\/PolygonMesh.h>\n#include <pcl\/common\/common.h>\n\n\/\/ STD\n#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <cmath>\n\nnamespace grid_map {\n\n\/*!\n * Conversions between grid maps and PCL types.\n *\/\nclass GridMapPclConverter\n{\n public:\n \/*!\n * Default constructor.\n *\/\n GridMapPclConverter();\n\n \/*!\n * Destructor.\n *\/\n virtual ~GridMapPclConverter();\n\n \/*!\n * Initializes the geometry of a grid map from a polygon mesh. This changes\n * the geometry of the map and deletes all contents of the layers!\n * @param[in] mesh the mesh.\n * @param[in] resolution the desired resolution of the grid map [m\/cell].\n * @param[out] gridMap the grid map to be initialized.\n * @return true if successful, false otherwise.\n *\/\n static bool initializeFromPolygonMesh(const pcl::PolygonMesh& mesh, const double resolution,\n grid_map::GridMap& gridMap);\n\n \/*!\n * Adds a layer with data from a polygon mesh. The mesh is ray traced from\n * above (negative z-Direction).\n * @param[in] mesh the mesh to be added. It can only consist of triangles!\n * @param[in] layer the layer that is filled with the mesh data.\n * @param[out] gridMap the grid map to be populated.\n * @return true if successful, false otherwise.\n *\/\n static bool addLayerFromPolygonMesh(const pcl::PolygonMesh& mesh, const std::string& layer,\n grid_map::GridMap& gridMap);\n\n private:\n static bool rayTriangleIntersect(const Eigen::Vector3f& point,\n const Eigen::Vector3f& ray,\n const Eigen::Matrix3f& triangleVertices,\n Eigen::Vector3f& intersectionPoint);\n\n};\n\n} \/* namespace *\/\n<|endoftext|>"} {"text":"<commit_before>\/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- vim:set ts=4 sw=4 sts=4 noet: *\/\n#ifdef HAVE_CONFIG_H\n#include \"config.h\"\n#endif\n\n#include \"gui\/sedml.h\"\n\n#include <cstdio>\n\n#include <wx\/wx.h>\n\nnamespace flint {\nnamespace gui {\n\nnamespace {\n\nclass Writer {\npublic:\n\tWriter(const Simulation *sim, const char *file);\n\n\t~Writer();\n\n\tbool operator()();\n\nprivate:\n\tconst Simulation *sim_;\n\tFILE *fp_;\n};\n\nWriter::Writer(const Simulation *sim, const char *file)\n\t: sim_(sim)\n\t, fp_(std::fopen(file, \"wb\"))\n{\n\tif (!fp_)\n\t\twxLogError(\"failed to open %s\", file);\n}\n\nWriter::~Writer()\n{\n\tif (fp_)\n\t\tstd::fclose(fp_);\n}\n\nbool Writer::operator()()\n{\n\tif (!fp_)\n\t\treturn false;\n\n\tstd::fprintf(fp_, \"<?xml version='1.0' encoding='UTF-8'?>\\n\");\n\tstd::fprintf(fp_, \"<sedML xmlns='http:\/\/sed-ml.org\/' xmlns:m='http:\/\/www.w3.org\/1998\/Math\/MathML' xmlns:flint='http:\/\/physiodesigner.org\/namespace\/flint' version='1' level='1'>\\n\");\n\tstd::fprintf(fp_, \" <listOfSimulations>\\n\");\n\tint i = 0;\n\tfor (const auto &p : sim_->entries) {\n\t\tconst auto *doc = p.first;\n\t\tconst auto *config = p.second;\n\t\tstd::fprintf(fp_, \" <uniformTimeCourse id='sim%d' name='Simulation %d' initialTime='0' outputStartTime='%f' outputEndTime='%f' numberOfPoints='%d' flint:granularity='%d'>\\n\",\n\t\t\t\t\t i,\n\t\t\t\t\t i,\n\t\t\t\t\t config->GetOutputStartTime(doc),\n\t\t\t\t\t config->GetOutputEndTime(doc),\n\t\t\t\t\t config->GetNumberOfPoints(doc),\n\t\t\t\t\t config->granularity);\n\t\tstd::fprintf(fp_, \" <algorithm kisaoID='KISAO:%s'\/>\\n\",\n\t\t\t\t\t config->GetKisaoId());\n\t\tstd::fprintf(fp_, \" <\/uniformTimeCourse>\\n\");\n\t\t++i;\n\t}\n\tstd::fprintf(fp_, \" <\/listOfSimulations>\\n\");\n\tstd::fprintf(fp_, \" <listOfModels>\\n\");\n\ti = 0;\n\tfor (const auto &p : sim_->entries) {\n\t\tconst auto *doc = p.first;\n\t\tconst auto &path = doc->path();\n\t\tauto path_u = path.utf8_str();\n\t\tstd::fprintf(fp_,\n\t\t\t\t\t \" <model id='model%d' name='Model %d' language='urn:sedml:language:%s' source='%s'\/>\\n\",\n\t\t\t\t\t i, i, doc->GetFormat(), path_u.data());\n\t\t++i;\n\t}\n\tstd::fprintf(fp_, \" <\/listOfModels>\\n\");\n\tstd::fprintf(fp_, \" <listOfTasks>\\n\");\n\ti = 0;\n\tfor (const auto &p : sim_->entries) {\n\t\tstd::fprintf(fp_,\n\t\t\t\t\t \" <task id='task%d' name='Task %d' modelReference='model%d' simulationReference='sim%d'\/>\\n\",\n\t\t\t\t\t i, i, i, i);\n\t\t++i;\n\t}\n\tstd::fprintf(fp_, \" <\/listOfTasks>\\n\");\n\tstd::fprintf(fp_, \" <listOfDataGenerators>\\n\");\n\ti = 0;\n\tfor (const auto &p : sim_->entries) {\n\t\tconst auto *doc = p.first;\n\t\tconst auto *config = p.second;\n\t\tstd::vector<std::string> v;\n\t\tconfig->GetOutputVariables(doc, &v);\n\t\tfor (const auto &name : v) {\n\t\t\tstd::fprintf(fp_, \" <dataGenerator id='dg%d' name='%s'>\\n\",\n\t\t\t\t\t\t i, name.c_str());\n\t\t\tstd::fprintf(fp_, \" <listOfVariables>\\n\");\n\t\t\tstd::fprintf(fp_, \" <variable id='v%d' taskReference='task' target='%s'\/>\\n\",\n\t\t\t\t\t\t i, name.c_str());\n\t\t\tstd::fprintf(fp_, \" <\/listOfVariables>\\n\");\n\t\t\tstd::fprintf(fp_, \" <m:math>\\n\");\n\t\t\tstd::fprintf(fp_, \" <m:ci>v%d<\/m:ci>\\n\", i);\n\t\t\tstd::fprintf(fp_, \" <\/m:math>\\n\");\n\t\t\tstd::fprintf(fp_, \" <\/dataGenerator>\\n\");\n\t\t\t++i;\n\t\t}\n\t}\n\tstd::fprintf(fp_, \" <\/listOfDataGenerators>\\n\");\n\tstd::fprintf(fp_, \"<\/sedML>\\n\");\n\treturn true;\n}\n\n}\n\nbool WriteSedml(const Simulation *sim, const wxFileName &filename)\n{\n\tauto path = filename.GetFullPath();\n\tWriter writer(sim, path.c_str()); \/\/ TODO: check locale-dependency\n\treturn writer();\n}\n\n}\n}\n<commit_msg>Write correct taskReference<commit_after>\/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- vim:set ts=4 sw=4 sts=4 noet: *\/\n#ifdef HAVE_CONFIG_H\n#include \"config.h\"\n#endif\n\n#include \"gui\/sedml.h\"\n\n#include <cstdio>\n\n#include <wx\/wx.h>\n\nnamespace flint {\nnamespace gui {\n\nnamespace {\n\nclass Writer {\npublic:\n\tWriter(const Simulation *sim, const char *file);\n\n\t~Writer();\n\n\tbool operator()();\n\nprivate:\n\tconst Simulation *sim_;\n\tFILE *fp_;\n};\n\nWriter::Writer(const Simulation *sim, const char *file)\n\t: sim_(sim)\n\t, fp_(std::fopen(file, \"wb\"))\n{\n\tif (!fp_)\n\t\twxLogError(\"failed to open %s\", file);\n}\n\nWriter::~Writer()\n{\n\tif (fp_)\n\t\tstd::fclose(fp_);\n}\n\nbool Writer::operator()()\n{\n\tif (!fp_)\n\t\treturn false;\n\n\tstd::fprintf(fp_, \"<?xml version='1.0' encoding='UTF-8'?>\\n\");\n\tstd::fprintf(fp_, \"<sedML xmlns='http:\/\/sed-ml.org\/' xmlns:m='http:\/\/www.w3.org\/1998\/Math\/MathML' xmlns:flint='http:\/\/physiodesigner.org\/namespace\/flint' version='1' level='1'>\\n\");\n\tstd::fprintf(fp_, \" <listOfSimulations>\\n\");\n\tint i = 0;\n\tfor (const auto &p : sim_->entries) {\n\t\tconst auto *doc = p.first;\n\t\tconst auto *config = p.second;\n\t\tstd::fprintf(fp_, \" <uniformTimeCourse id='sim%d' name='Simulation %d' initialTime='0' outputStartTime='%f' outputEndTime='%f' numberOfPoints='%d' flint:granularity='%d'>\\n\",\n\t\t\t\t\t i,\n\t\t\t\t\t i,\n\t\t\t\t\t config->GetOutputStartTime(doc),\n\t\t\t\t\t config->GetOutputEndTime(doc),\n\t\t\t\t\t config->GetNumberOfPoints(doc),\n\t\t\t\t\t config->granularity);\n\t\tstd::fprintf(fp_, \" <algorithm kisaoID='KISAO:%s'\/>\\n\",\n\t\t\t\t\t config->GetKisaoId());\n\t\tstd::fprintf(fp_, \" <\/uniformTimeCourse>\\n\");\n\t\t++i;\n\t}\n\tstd::fprintf(fp_, \" <\/listOfSimulations>\\n\");\n\tstd::fprintf(fp_, \" <listOfModels>\\n\");\n\ti = 0;\n\tfor (const auto &p : sim_->entries) {\n\t\tconst auto *doc = p.first;\n\t\tconst auto &path = doc->path();\n\t\tauto path_u = path.utf8_str();\n\t\tstd::fprintf(fp_,\n\t\t\t\t\t \" <model id='model%d' name='Model %d' language='urn:sedml:language:%s' source='%s'\/>\\n\",\n\t\t\t\t\t i, i, doc->GetFormat(), path_u.data());\n\t\t++i;\n\t}\n\tstd::fprintf(fp_, \" <\/listOfModels>\\n\");\n\tstd::fprintf(fp_, \" <listOfTasks>\\n\");\n\ti = 0;\n\tfor (const auto &p : sim_->entries) {\n\t\tstd::fprintf(fp_,\n\t\t\t\t\t \" <task id='task%d' name='Task %d' modelReference='model%d' simulationReference='sim%d'\/>\\n\",\n\t\t\t\t\t i, i, i, i);\n\t\t++i;\n\t}\n\tstd::fprintf(fp_, \" <\/listOfTasks>\\n\");\n\tstd::fprintf(fp_, \" <listOfDataGenerators>\\n\");\n\ti = 0;\n\tint j = 0;\n\tfor (const auto &p : sim_->entries) {\n\t\tconst auto *doc = p.first;\n\t\tconst auto *config = p.second;\n\t\tstd::vector<std::string> v;\n\t\tconfig->GetOutputVariables(doc, &v);\n\t\tfor (const auto &name : v) {\n\t\t\tstd::fprintf(fp_, \" <dataGenerator id='dg%d' name='%s'>\\n\",\n\t\t\t\t\t\t j, name.c_str());\n\t\t\tstd::fprintf(fp_, \" <listOfVariables>\\n\");\n\t\t\tstd::fprintf(fp_, \" <variable id='v%d' taskReference='task%d' target='%s'\/>\\n\",\n\t\t\t\t\t\t j, i, name.c_str());\n\t\t\tstd::fprintf(fp_, \" <\/listOfVariables>\\n\");\n\t\t\tstd::fprintf(fp_, \" <m:math>\\n\");\n\t\t\tstd::fprintf(fp_, \" <m:ci>v%d<\/m:ci>\\n\", j);\n\t\t\tstd::fprintf(fp_, \" <\/m:math>\\n\");\n\t\t\tstd::fprintf(fp_, \" <\/dataGenerator>\\n\");\n\t\t\t++j;\n\t\t}\n\t\t++i;\n\t}\n\tstd::fprintf(fp_, \" <\/listOfDataGenerators>\\n\");\n\tstd::fprintf(fp_, \"<\/sedML>\\n\");\n\treturn true;\n}\n\n}\n\nbool WriteSedml(const Simulation *sim, const wxFileName &filename)\n{\n\tauto path = filename.GetFullPath();\n\tWriter writer(sim, path.c_str()); \/\/ TODO: check locale-dependency\n\treturn writer();\n}\n\n}\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"gtest\/gtest.h\"\n#include \"S3Operations.cpp\"\n\n#define S3HOST \"s3-us-west-2.amazonaws.com\"\n#define S3BUCKET \"metro.pivotal.io\"\n\n#define KEYID \"AKIAIAFSMJUMQWXB2PUQ\"\n#define SECRET \"oCTLHlu3qJ+lpBH\/+JcIlnNuDebFObFNFeNvzBF0\"\n\nTEST(Uploader, get_upload_id) {\n S3Credential g_cred = {KEYID, SECRET};\n const char *upload_id = GetUploadId(S3HOST, S3BUCKET, \"data1234\", g_cred);\n\n \/\/printf(\"uploadid = %s\\n\", upload_id);\n\n EXPECT_NE(upload_id, (void *)NULL);\n}\n\nTEST(Uploader, get_upload_id_directories) {\n S3Credential g_cred = {KEYID, SECRET};\n const char *upload_id = GetUploadId(S3HOST, S3BUCKET, \"test\/upload\/data1234\", g_cred);\n\n \/\/printf(\"uploadid = %s\\n\", upload_id);\n\n EXPECT_NE(upload_id, (void *)NULL);\n}\n\nTEST(Uploader, get_upload_id_long_url) {\n S3Credential g_cred = {KEYID, SECRET};\n const char *upload_id = GetUploadId(S3HOST, S3BUCKET, \"test\/upload\/data1234aaaaaaaaaaaaaaaaaaaaaaaaabbbbbbbbbbbbbbbbbbbccccccccccccccccccccccddddddddddddddddddddddddeeeeeeeeeeeeeeeeeeeffffffffffffffffgggggggggggggggggggg\", g_cred);\n\n \/\/printf(\"uploadid = %s\\n\", upload_id);\n\n EXPECT_NE(upload_id, (void *)NULL);\n}\n\nTEST(Uploader, get_upload_id_long_url_directories) {\n S3Credential g_cred = {KEYID, SECRET};\n const char *upload_id = GetUploadId(S3HOST, S3BUCKET, \"test\/upload\/data1234\/aaaaaaaaaaaaaaaaaaaaaaaaa\/bbbbbbbbbbbbbbbbbbbccccccccccccccccccccccddddddddddddddddddddddddeeeeeeeeeeeeeeeeeeeffffffffffffffffggggggggggggggggggg\/g\", g_cred);\n\n \/\/printf(\"uploadid = %s\\n\", upload_id);\n\n EXPECT_NE(upload_id, (void *)NULL);\n}\n\n\/*\nTEST(Uploader, upload) {\n S3Credential g_cred = {KEYID, SECRET};\n\n const char *upload_id = GetUploadId(S3HOST, S3BUCKET, \"test\/data1234\", g_cred);\n const char *etag_1 = PartPutS3Object(S3HOST, S3BUCKET, \"test\/data1234\", g_cred, \"content_string_lol\", 18, 1, upload_id);\n const char *etag_array[1] = { etag_1 };\n bool ret = CompleteMultiPutS3(S3HOST, S3BUCKET, \"test\/data1234\", upload_id, etag_array, 1, g_cred);\n\n EXPECT_TRUE(ret);\n}\n\n\/\/ need to convert url string to Percent-encoding\n\/\/ https:\/\/en.wikipedia.org\/wiki\/Percent-encoding\nTEST(Uploader, get_upload_id_spaces) {\n S3Credential g_cred = {KEYID, SECRET};\n const char *upload_id = GetUploadId(S3HOST, S3BUCKET, \"data 1234\", g_cred);\n\n \/\/printf(\"uploadid = %s\\n\", upload_id);\n\n EXPECT_NE(upload_id, (void *)NULL);\n}\n\nTEST(Uploader, get_upload_id_spaces_directories) {\n S3Credential g_cred = {KEYID, SECRET};\n const char *upload_id = GetUploadId(S3HOST, S3BUCKET, \"test\/ up load\/data 1234\", g_cred);\n\n \/\/printf(\"uploadid = %s\\n\", upload_id);\n\n EXPECT_NE(upload_id, (void *)NULL);\n}\n*\/\n<commit_msg>update the uploading testcase<commit_after>#include \"gtest\/gtest.h\"\n#include \"S3Operations.cpp\"\n\n#define S3HOST \"s3-us-west-2.amazonaws.com\"\n#define S3BUCKET \"metro.pivotal.io\"\n\n#define KEYID \"AKIAIAFSMJUMQWXB2PUQ\"\n#define SECRET \"oCTLHlu3qJ+lpBH\/+JcIlnNuDebFObFNFeNvzBF0\"\n\nTEST(Uploader, get_upload_id) {\n S3Credential g_cred = {KEYID, SECRET};\n const char *upload_id = GetUploadId(S3HOST, S3BUCKET, \"data1234\", g_cred);\n\n \/\/ printf(\"uploadid = %s\\n\", upload_id);\n\n EXPECT_NE(upload_id, (void *)NULL);\n}\n\nTEST(Uploader, get_upload_id_directories) {\n S3Credential g_cred = {KEYID, SECRET};\n const char *upload_id =\n GetUploadId(S3HOST, S3BUCKET, \"test\/upload\/data1234\", g_cred);\n\n \/\/ printf(\"uploadid = %s\\n\", upload_id);\n\n EXPECT_NE(upload_id, (void *)NULL);\n}\n\nTEST(Uploader, get_upload_id_long_url) {\n S3Credential g_cred = {KEYID, SECRET};\n const char *upload_id =\n GetUploadId(S3HOST, S3BUCKET,\n \"test\/upload\/\"\n \"data1234aaaaaaaaaaaaaaaaaaaaaaaaabbbbbbbbbbbbbbbbbbbcccccc\"\n \"ccccccccccccccccddddddddddddddddddddddddeeeeeeeeeeeeeeeeee\"\n \"effffffffffffffffgggggggggggggggggggg\",\n g_cred);\n\n \/\/ printf(\"uploadid = %s\\n\", upload_id);\n\n EXPECT_NE(upload_id, (void *)NULL);\n}\n\nTEST(Uploader, get_upload_id_long_url_directories) {\n S3Credential g_cred = {KEYID, SECRET};\n const char *upload_id = GetUploadId(\n S3HOST, S3BUCKET,\n \"test\/upload\/data1234\/aaaaaaaaaaaaaaaaaaaaaaaaa\/\"\n \"bbbbbbbbbbbbbbbbbbbccccccccccccccccccccccddddddddddddddddddddddddeeeee\"\n \"eeeeeeeeeeeeeeffffffffffffffffggggggggggggggggggg\/g\",\n g_cred);\n\n \/\/ printf(\"uploadid = %s\\n\", upload_id);\n\n EXPECT_NE(upload_id, (void *)NULL);\n}\n\n\/*\n#define OBJ2UPLOAD \"test\/3iun6\"\nTEST(Uploader, upload) {\n S3Credential g_cred = {KEYID, SECRET};\n\n printf(\"init, getting uploadid\\n\");\n const char *upload_id = GetUploadId(S3HOST, S3BUCKET, OBJ2UPLOAD, g_cred);\n\n printf(\"upload part1, getting etag1\\n\");\n char *upload_buf = (char *)malloc(5 * 1024 * 1024 + 1);\n memset(upload_buf, 42, 5 * 1024 * 1024 + 1);\n const char *etag_1 =\n PartPutS3Object(S3HOST, S3BUCKET, OBJ2UPLOAD, g_cred, upload_buf,\n 5 * 1024 * 1024 + 1, 1, upload_id);\n\n printf(\"upload part2, getting etag2\\n\");\n char *upload_buf_2 = (char *)malloc(1 * 1024 * 1024 + 1);\n memset(upload_buf_2, 70, 1 * 1024 * 1024 + 1);\n const char *etag_2 =\n PartPutS3Object(S3HOST, S3BUCKET, OBJ2UPLOAD, g_cred, upload_buf_2,\n 1 * 1024 * 1024 + 1, 2, upload_id);\n\n const char *etag_array[2] = {etag_1, etag_2};\n printf(\"completing multi upload\\n\");\n bool ret = CompleteMultiPutS3(S3HOST, S3BUCKET, OBJ2UPLOAD, upload_id,\n etag_array, 2, g_cred);\n\n EXPECT_TRUE(ret);\n}\n\n\/\/ need to convert url string to Percent-encoding\n\/\/ https:\/\/en.wikipedia.org\/wiki\/Percent-encoding\nTEST(Uploader, get_upload_id_spaces) {\n S3Credential g_cred = {KEYID, SECRET};\n const char *upload_id = GetUploadId(S3HOST, S3BUCKET, \"data 1234\", g_cred);\n\n \/\/ printf(\"uploadid = %s\\n\", upload_id);\n\n EXPECT_NE(upload_id, (void *)NULL);\n}\n\nTEST(Uploader, get_upload_id_spaces_directories) {\n S3Credential g_cred = {KEYID, SECRET};\n const char *upload_id = GetUploadId(S3HOST, S3BUCKET, \"test\/ up load\/data 1234\",\n g_cred);\n\n \/\/printf(\"uploadid = %s\\n\", upload_id);\n\n EXPECT_NE(upload_id, (void *)NULL);\n}\n*\/\n<|endoftext|>"} {"text":"<commit_before>\/*\n * bacteria-core, core for cellular automaton\n * Copyright (C) 2016 Pavel Dolgov\n *\n * See the LICENSE file for terms of use.\n *\/\n\n#include \"Bytecode.hpp\"\n\nnamespace Implementation {\n\n\nstatic void split(\n const std::string& str,\n char delimiter,\n Strings items\n) {\n std::stringstream s_stream(str);\n std::string item;\n while (std::getline(s_stream, item, delimiter)) {\n if (!item.empty()) {\n items.push_back(item);\n }\n }\n}\n\nToken::Token(\n Type type,\n int parameter,\n bool spec,\n int function_id\n)\n : type(type)\n , parameter(parameter)\n , spec(spec)\n , function_id(function_id)\n{\n}\n\nInstruction::Instruction(\n Token function,\n Token p1,\n Token p2,\n Token spec\n)\n : function(function)\n , p1(p1)\n , p2(p2)\n , spec(spec)\n{\n}\n\nPackedInstruction::PackedInstruction(\n int function_id,\n int p1,\n int p2,\n bool spec\n)\n : function_id(function_id)\n , p1(p1)\n , p2(p2)\n , spec(spec)\n{\n}\n\n}\n<commit_msg>Description of language syntax<commit_after>\/*\n * bacteria-core, core for cellular automaton\n * Copyright (C) 2016 Pavel Dolgov\n *\n * See the LICENSE file for terms of use.\n *\/\n\n#include \"Bytecode.hpp\"\n\nnamespace Implementation {\n\n\/\/ These two static arrays describe language: all possible\n\/\/ functions ans specifications.\n\nstatic const char* const specifications_registry[] = {\n \"r\"\n};\n\nstatic const char* const functions_registry[] = {\n \"eat\", \"go\", \"clon\", \"str\", \"left\", \"right\", \"back\", \"turn\",\n \"jg\", \"jl\", \"j\", \"je\", \"jfe\", \"jw\", \"jfw\", \"jb\", \"jfb\"\n};\n\n\/\/ These four static arrays contain IDs of functions from\n\/\/ functions_registry.\n\nstatic const int two_parameter_functions[] = {\n 8, 9\n};\n\nstatic const int one_parameter_functions[] = {\n 0, 1, 3, 4, 5, 10, 11, 12, 13, 14, 15, 16\n};\n\nstatic const int spec_functions[] = {\n 0, 1, 7\n};\n\nstatic const int non_argument_functions[] = {\n 0, 1, 2, 3, 4, 5, 6\n};\n\nstatic void split(\n const std::string& str,\n char delimiter,\n Strings items\n) {\n std::stringstream s_stream(str);\n std::string item;\n while (std::getline(s_stream, item, delimiter)) {\n if (!item.empty()) {\n items.push_back(item);\n }\n }\n}\n\nToken::Token(\n Type type,\n int parameter,\n bool spec,\n int function_id\n)\n : type(type)\n , parameter(parameter)\n , spec(spec)\n , function_id(function_id)\n{\n}\n\nInstruction::Instruction(\n Token function,\n Token p1,\n Token p2,\n Token spec\n)\n : function(function)\n , p1(p1)\n , p2(p2)\n , spec(spec)\n{\n}\n\nPackedInstruction::PackedInstruction(\n int function_id,\n int p1,\n int p2,\n bool spec\n)\n : function_id(function_id)\n , p1(p1)\n , p2(p2)\n , spec(spec)\n{\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/****************************************************************************\n**\n** Copyright (C) 2009 Nokia Corporation and\/or its subsidiary(-ies).\n** Contact: Qt Software Information (qt-info@nokia.com)\n**\n** This file is part of the QtDeclarative module of the Qt Toolkit.\n**\n** $QT_BEGIN_LICENSE:LGPL$\n** No Commercial Usage\n** This file contains pre-release code and may not be distributed.\n** You may use this file in accordance with the terms and conditions\n** contained in the either Technology Preview License Agreement or the\n** Beta Release License Agreement.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Nokia gives you certain\n** additional rights. These rights are described in the Nokia Qt LGPL\n** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this\n** package.\n**\n** GNU General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU\n** General Public License version 3.0 as published by the Free Software\n** Foundation and appearing in the file LICENSE.GPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU General Public License version 3.0 requirements will be\n** met: http:\/\/www.gnu.org\/copyleft\/gpl.html.\n**\n** If you are unsure which license is appropriate for your use, please\n** contact the sales department at qt-sales@nokia.com.\n** $QT_END_LICENSE$\n**\n****************************************************************************\/\n\n#include \"private\/qobject_p.h\"\n#include \"qmlopenmetaobject.h\"\n#include \"qmlsetproperties.h\"\n#include <QtCore\/qdebug.h>\n#include <QtDeclarative\/qmlinfo.h>\n#include <private\/qmlcustomparser_p.h>\n#include <private\/qmlparser_p.h>\n#include <QtDeclarative\/qmlexpression.h>\n\n\nQT_BEGIN_NAMESPACE\n\/*!\n \\qmlclass SetProperties QmlSetProperties\n \\brief The SetProperties element describes new property values for a state.\n\n SetProperties is a convenience element for changing many properties on a single\n object. It allows you to specify the property names and values similar to how\n you normally would specify them for the actual item:\n\n \\code\n SetProperties {\n target: myRect\n x: 52\n y: 300\n width: 48\n }\n \\endcode\n\n \\c target is a property of \\c SetProperties, so if the property you want to change\n is named \\e target you will have to use \\l SetProperty instead. You should also \n use \\l SetProperty if you want to update the binding for a property, \n as SetProperties does not support this.\n*\/\n\n\/*!\n \\internal\n \\class QmlSetProperties\n \\brief The QmlSetProperties class describes new property values for a state.\n\n \\ingroup group_states\n\n QmlSetProperties is a convenience class for changing many properties on a single\n object. It allows you to specify the property names and values similar to how\n you normally would specify them for the actual item:\n\n \\code\n SetProperties {\n target: myRect\n x: 52\n y: 300\n width: 48\n }\n \\endcode\n\n \\c target is a property of \\c SetProperties, so if the property you want to change\n is named \\e target you will have to use QmlSetProperty instead. You should also use QmlSetProperty\n if you want to update the binding for a property, as QmlSetProperties does not support this.\n\n \\sa QmlSetProperty\n*\/\n\n\/*!\n \\qmlproperty Object SetProperties::target\n This property holds the object that the properties to change belong to\n*\/\n\n\/*!\n \\property QmlSetProperties::target\n \\brief the object that the properties to change belong to\n*\/\nclass QmlSetPropertiesPrivate : public QObjectPrivate\n{\n Q_DECLARE_PUBLIC(QmlSetProperties)\npublic:\n QmlSetPropertiesPrivate() : object(0), decoded(true) {}\n\n QObject *object;\n QByteArray data;\n bool decoded;\n void decode();\n\n QList<QPair<QByteArray, QVariant> > properties;\n QList<QPair<QByteArray, QmlExpression *> > expressions;\n\n QmlMetaProperty property(const QByteArray &);\n};\n\nclass QmlSetPropertiesParser : public QmlCustomParser\n{\npublic:\n void compileList(QList<QPair<QByteArray, QVariant> > &list, const QByteArray &pre, const QmlCustomParserProperty &prop);\n\n virtual QByteArray compile(const QList<QmlCustomParserProperty> &, bool *ok);\n virtual void setCustomData(QObject *, const QByteArray &);\n};\n\nvoid \nQmlSetPropertiesParser::compileList(QList<QPair<QByteArray, QVariant> > &list, \n const QByteArray &pre, \n const QmlCustomParserProperty &prop)\n{\n QByteArray propName = pre + prop.name();\n\n QList<QVariant> values = prop.assignedValues();\n for (int ii = 0; ii < values.count(); ++ii) {\n const QVariant &value = values.at(ii);\n\n if (value.userType() == qMetaTypeId<QmlCustomParserNode>()) {\n continue;\n } else if(value.userType() == qMetaTypeId<QmlCustomParserProperty>()) {\n\n QmlCustomParserProperty prop = \n qvariant_cast<QmlCustomParserProperty>(value);\n QByteArray pre = propName + \".\";\n compileList(list, pre, prop);\n\n } else {\n list << qMakePair(propName, value);\n }\n }\n}\n\nQByteArray \nQmlSetPropertiesParser::compile(const QList<QmlCustomParserProperty> &props, \n bool *ok)\n{\n *ok = true;\n\n QList<QPair<QByteArray, QVariant> > data;\n for(int ii = 0; ii < props.count(); ++ii)\n compileList(data, QByteArray(), props.at(ii));\n\n QByteArray rv;\n QDataStream ds(&rv, QIODevice::WriteOnly);\n\n ds << data.count();\n for(int ii = 0; ii < data.count(); ++ii) {\n QmlParser::Variant v = qvariant_cast<QmlParser::Variant>(data.at(ii).second);\n QVariant var;\n bool isScript = v.isScript();\n switch(v.type()) {\n case QmlParser::Variant::Boolean:\n var = QVariant(v.asBoolean());\n break;\n case QmlParser::Variant::Number:\n var = QVariant(v.asNumber());\n break;\n case QmlParser::Variant::String:\n var = QVariant(v.asString());\n break;\n case QmlParser::Variant::Invalid:\n case QmlParser::Variant::Script:\n var = QVariant(v.asScript());\n break;\n }\n\n ds << data.at(ii).first << isScript << var;\n }\n\n return rv;\n}\n\nvoid QmlSetPropertiesPrivate::decode()\n{\n if (decoded)\n return;\n\n QDataStream ds(&data, QIODevice::ReadOnly);\n\n int count;\n ds >> count;\n for (int ii = 0; ii < count; ++ii) {\n QByteArray name;\n bool isScript;\n QVariant data;\n ds >> name;\n ds >> isScript;\n ds >> data;\n\n if (isScript) {\n QmlExpression *expression = new QmlExpression(qmlContext(object), data.toString(), object);\n expression->setTrackChange(false);\n expressions << qMakePair(name, expression);\n } else {\n properties << qMakePair(name, data);\n }\n }\n\n decoded = true;\n data.clear();\n}\n\nvoid QmlSetPropertiesParser::setCustomData(QObject *object, \n const QByteArray &data)\n{\n QmlSetPropertiesPrivate *p = \n static_cast<QmlSetPropertiesPrivate *>(QObjectPrivate::get(object));\n p->data = data;\n p->decoded = false;\n}\n\nQmlSetProperties::QmlSetProperties()\n: QmlStateOperation(*(new QmlSetPropertiesPrivate))\n{\n}\n\nQmlSetProperties::~QmlSetProperties()\n{\n Q_D(QmlSetProperties);\n for(int ii = 0; ii < d->expressions.count(); ++ii)\n delete d->expressions.at(ii).second;\n}\n\nQObject *QmlSetProperties::object() const\n{\n Q_D(const QmlSetProperties);\n return d->object;\n}\n\nvoid QmlSetProperties::setObject(QObject *o)\n{\n Q_D(QmlSetProperties);\n d->object = o;\n}\n\nQmlMetaProperty \nQmlSetPropertiesPrivate::property(const QByteArray &property) \n{\n Q_Q(QmlSetProperties);\n QList<QByteArray> path = property.split('.');\n\n QObject *obj = this->object;\n\n for (int jj = 0; jj < path.count() - 1; ++jj) {\n const QByteArray &pathName = path.at(jj);\n QmlMetaProperty prop(obj, QLatin1String(pathName));\n QObject *objVal = QmlMetaType::toQObject(prop.read());\n if (!objVal) {\n qmlInfo(q) << obj->metaObject()->className()\n << \"has no object property named\" << pathName;\n return QmlMetaProperty();\n }\n obj = objVal;\n }\n\n const QByteArray &name = path.last();\n QmlMetaProperty prop(obj, QLatin1String(name));\n if (!prop.isValid()) {\n qmlInfo(q) << obj->metaObject()->className()\n << \"has no property named\" << name;\n return QmlMetaProperty();\n } else if (!prop.isWritable()) {\n qmlInfo(q) << obj->metaObject()->className()\n << name << \"is not writable, and cannot be set.\";\n return QmlMetaProperty();\n } else {\n return prop;\n }\n}\n\nQmlSetProperties::ActionList QmlSetProperties::actions()\n{\n Q_D(QmlSetProperties);\n\n d->decode();\n\n ActionList list;\n\n for (int ii = 0; ii < d->properties.count(); ++ii) {\n\n QByteArray property = d->properties.at(ii).first;\n QmlMetaProperty prop = d->property(property);\n\n if (prop.isValid()) {\n Action a;\n a.property = prop;\n a.fromValue = a.property.read();\n a.toValue = d->properties.at(ii).second;\n\n list << a;\n }\n }\n\n for (int ii = 0; ii < d->expressions.count(); ++ii) {\n\n QByteArray property = d->expressions.at(ii).first;\n QmlMetaProperty prop = d->property(property);\n\n if (prop.isValid()) {\n Action a;\n a.property = prop;\n a.fromValue = a.property.read();\n a.toValue = d->expressions.at(ii).second->value();\n\n list << a;\n }\n\n }\n\n return list;\n}\n\nQML_DEFINE_CUSTOM_TYPE(QmlSetProperties,SetProperties,QmlSetPropertiesParser);\n\nQT_END_NAMESPACE\n#include \"qmlsetproperties.moc\"\n<commit_msg>Remove moc line<commit_after>\/****************************************************************************\n**\n** Copyright (C) 2009 Nokia Corporation and\/or its subsidiary(-ies).\n** Contact: Qt Software Information (qt-info@nokia.com)\n**\n** This file is part of the QtDeclarative module of the Qt Toolkit.\n**\n** $QT_BEGIN_LICENSE:LGPL$\n** No Commercial Usage\n** This file contains pre-release code and may not be distributed.\n** You may use this file in accordance with the terms and conditions\n** contained in the either Technology Preview License Agreement or the\n** Beta Release License Agreement.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Nokia gives you certain\n** additional rights. These rights are described in the Nokia Qt LGPL\n** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this\n** package.\n**\n** GNU General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU\n** General Public License version 3.0 as published by the Free Software\n** Foundation and appearing in the file LICENSE.GPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU General Public License version 3.0 requirements will be\n** met: http:\/\/www.gnu.org\/copyleft\/gpl.html.\n**\n** If you are unsure which license is appropriate for your use, please\n** contact the sales department at qt-sales@nokia.com.\n** $QT_END_LICENSE$\n**\n****************************************************************************\/\n\n#include \"private\/qobject_p.h\"\n#include \"qmlopenmetaobject.h\"\n#include \"qmlsetproperties.h\"\n#include <QtCore\/qdebug.h>\n#include <QtDeclarative\/qmlinfo.h>\n#include <private\/qmlcustomparser_p.h>\n#include <private\/qmlparser_p.h>\n#include <QtDeclarative\/qmlexpression.h>\n\n\nQT_BEGIN_NAMESPACE\n\/*!\n \\qmlclass SetProperties QmlSetProperties\n \\brief The SetProperties element describes new property values for a state.\n\n SetProperties is a convenience element for changing many properties on a single\n object. It allows you to specify the property names and values similar to how\n you normally would specify them for the actual item:\n\n \\code\n SetProperties {\n target: myRect\n x: 52\n y: 300\n width: 48\n }\n \\endcode\n\n \\c target is a property of \\c SetProperties, so if the property you want to change\n is named \\e target you will have to use \\l SetProperty instead. You should also \n use \\l SetProperty if you want to update the binding for a property, \n as SetProperties does not support this.\n*\/\n\n\/*!\n \\internal\n \\class QmlSetProperties\n \\brief The QmlSetProperties class describes new property values for a state.\n\n \\ingroup group_states\n\n QmlSetProperties is a convenience class for changing many properties on a single\n object. It allows you to specify the property names and values similar to how\n you normally would specify them for the actual item:\n\n \\code\n SetProperties {\n target: myRect\n x: 52\n y: 300\n width: 48\n }\n \\endcode\n\n \\c target is a property of \\c SetProperties, so if the property you want to change\n is named \\e target you will have to use QmlSetProperty instead. You should also use QmlSetProperty\n if you want to update the binding for a property, as QmlSetProperties does not support this.\n\n \\sa QmlSetProperty\n*\/\n\n\/*!\n \\qmlproperty Object SetProperties::target\n This property holds the object that the properties to change belong to\n*\/\n\n\/*!\n \\property QmlSetProperties::target\n \\brief the object that the properties to change belong to\n*\/\nclass QmlSetPropertiesPrivate : public QObjectPrivate\n{\n Q_DECLARE_PUBLIC(QmlSetProperties)\npublic:\n QmlSetPropertiesPrivate() : object(0), decoded(true) {}\n\n QObject *object;\n QByteArray data;\n bool decoded;\n void decode();\n\n QList<QPair<QByteArray, QVariant> > properties;\n QList<QPair<QByteArray, QmlExpression *> > expressions;\n\n QmlMetaProperty property(const QByteArray &);\n};\n\nclass QmlSetPropertiesParser : public QmlCustomParser\n{\npublic:\n void compileList(QList<QPair<QByteArray, QVariant> > &list, const QByteArray &pre, const QmlCustomParserProperty &prop);\n\n virtual QByteArray compile(const QList<QmlCustomParserProperty> &, bool *ok);\n virtual void setCustomData(QObject *, const QByteArray &);\n};\n\nvoid \nQmlSetPropertiesParser::compileList(QList<QPair<QByteArray, QVariant> > &list, \n const QByteArray &pre, \n const QmlCustomParserProperty &prop)\n{\n QByteArray propName = pre + prop.name();\n\n QList<QVariant> values = prop.assignedValues();\n for (int ii = 0; ii < values.count(); ++ii) {\n const QVariant &value = values.at(ii);\n\n if (value.userType() == qMetaTypeId<QmlCustomParserNode>()) {\n continue;\n } else if(value.userType() == qMetaTypeId<QmlCustomParserProperty>()) {\n\n QmlCustomParserProperty prop = \n qvariant_cast<QmlCustomParserProperty>(value);\n QByteArray pre = propName + \".\";\n compileList(list, pre, prop);\n\n } else {\n list << qMakePair(propName, value);\n }\n }\n}\n\nQByteArray \nQmlSetPropertiesParser::compile(const QList<QmlCustomParserProperty> &props, \n bool *ok)\n{\n *ok = true;\n\n QList<QPair<QByteArray, QVariant> > data;\n for(int ii = 0; ii < props.count(); ++ii)\n compileList(data, QByteArray(), props.at(ii));\n\n QByteArray rv;\n QDataStream ds(&rv, QIODevice::WriteOnly);\n\n ds << data.count();\n for(int ii = 0; ii < data.count(); ++ii) {\n QmlParser::Variant v = qvariant_cast<QmlParser::Variant>(data.at(ii).second);\n QVariant var;\n bool isScript = v.isScript();\n switch(v.type()) {\n case QmlParser::Variant::Boolean:\n var = QVariant(v.asBoolean());\n break;\n case QmlParser::Variant::Number:\n var = QVariant(v.asNumber());\n break;\n case QmlParser::Variant::String:\n var = QVariant(v.asString());\n break;\n case QmlParser::Variant::Invalid:\n case QmlParser::Variant::Script:\n var = QVariant(v.asScript());\n break;\n }\n\n ds << data.at(ii).first << isScript << var;\n }\n\n return rv;\n}\n\nvoid QmlSetPropertiesPrivate::decode()\n{\n if (decoded)\n return;\n\n QDataStream ds(&data, QIODevice::ReadOnly);\n\n int count;\n ds >> count;\n for (int ii = 0; ii < count; ++ii) {\n QByteArray name;\n bool isScript;\n QVariant data;\n ds >> name;\n ds >> isScript;\n ds >> data;\n\n if (isScript) {\n QmlExpression *expression = new QmlExpression(qmlContext(object), data.toString(), object);\n expression->setTrackChange(false);\n expressions << qMakePair(name, expression);\n } else {\n properties << qMakePair(name, data);\n }\n }\n\n decoded = true;\n data.clear();\n}\n\nvoid QmlSetPropertiesParser::setCustomData(QObject *object, \n const QByteArray &data)\n{\n QmlSetPropertiesPrivate *p = \n static_cast<QmlSetPropertiesPrivate *>(QObjectPrivate::get(object));\n p->data = data;\n p->decoded = false;\n}\n\nQmlSetProperties::QmlSetProperties()\n: QmlStateOperation(*(new QmlSetPropertiesPrivate))\n{\n}\n\nQmlSetProperties::~QmlSetProperties()\n{\n Q_D(QmlSetProperties);\n for(int ii = 0; ii < d->expressions.count(); ++ii)\n delete d->expressions.at(ii).second;\n}\n\nQObject *QmlSetProperties::object() const\n{\n Q_D(const QmlSetProperties);\n return d->object;\n}\n\nvoid QmlSetProperties::setObject(QObject *o)\n{\n Q_D(QmlSetProperties);\n d->object = o;\n}\n\nQmlMetaProperty \nQmlSetPropertiesPrivate::property(const QByteArray &property) \n{\n Q_Q(QmlSetProperties);\n QList<QByteArray> path = property.split('.');\n\n QObject *obj = this->object;\n\n for (int jj = 0; jj < path.count() - 1; ++jj) {\n const QByteArray &pathName = path.at(jj);\n QmlMetaProperty prop(obj, QLatin1String(pathName));\n QObject *objVal = QmlMetaType::toQObject(prop.read());\n if (!objVal) {\n qmlInfo(q) << obj->metaObject()->className()\n << \"has no object property named\" << pathName;\n return QmlMetaProperty();\n }\n obj = objVal;\n }\n\n const QByteArray &name = path.last();\n QmlMetaProperty prop(obj, QLatin1String(name));\n if (!prop.isValid()) {\n qmlInfo(q) << obj->metaObject()->className()\n << \"has no property named\" << name;\n return QmlMetaProperty();\n } else if (!prop.isWritable()) {\n qmlInfo(q) << obj->metaObject()->className()\n << name << \"is not writable, and cannot be set.\";\n return QmlMetaProperty();\n } else {\n return prop;\n }\n}\n\nQmlSetProperties::ActionList QmlSetProperties::actions()\n{\n Q_D(QmlSetProperties);\n\n d->decode();\n\n ActionList list;\n\n for (int ii = 0; ii < d->properties.count(); ++ii) {\n\n QByteArray property = d->properties.at(ii).first;\n QmlMetaProperty prop = d->property(property);\n\n if (prop.isValid()) {\n Action a;\n a.property = prop;\n a.fromValue = a.property.read();\n a.toValue = d->properties.at(ii).second;\n\n list << a;\n }\n }\n\n for (int ii = 0; ii < d->expressions.count(); ++ii) {\n\n QByteArray property = d->expressions.at(ii).first;\n QmlMetaProperty prop = d->property(property);\n\n if (prop.isValid()) {\n Action a;\n a.property = prop;\n a.fromValue = a.property.read();\n a.toValue = d->expressions.at(ii).second->value();\n\n list << a;\n }\n\n }\n\n return list;\n}\n\nQML_DEFINE_CUSTOM_TYPE(QmlSetProperties,SetProperties,QmlSetPropertiesParser);\n\nQT_END_NAMESPACE\n<|endoftext|>"} {"text":"<commit_before>\/*=========================================================================\n\n Program: Visualization Toolkit\n Module: vtkVolumeMapper.cxx\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n\nCopyright (c) 1993-1998 Ken Martin, Will Schroeder, Bill Lorensen.\n\nThis software is copyrighted by Ken Martin, Will Schroeder and Bill Lorensen.\nThe following terms apply to all files associated with the software unless\nexplicitly disclaimed in individual files. This copyright specifically does\nnot apply to the related textbook \"The Visualization Toolkit\" ISBN\n013199837-4 published by Prentice Hall which is covered by its own copyright.\n\nThe authors hereby grant permission to use, copy, and distribute this\nsoftware and its documentation for any purpose, provided that existing\ncopyright notices are retained in all copies and that this notice is included\nverbatim in any distributions. Additionally, the authors grant permission to\nmodify this software and its documentation for any purpose, provided that\nsuch modifications are not distributed without the explicit consent of the\nauthors and that existing copyright notices are retained in all copies. Some\nof the algorithms implemented by this software are patented, observe all\napplicable patent law.\n\nIN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR\nDIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT\nOF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF,\nEVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\nTHE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING,\nBUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\nPARTICULAR PURPOSE, AND NON-INFRINGEMENT. THIS SOFTWARE IS PROVIDED ON AN\n\"AS IS\" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE\nMAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.\n\n\n=========================================================================*\/\n#include \"vtkVolumeMapper.h\"\n\n\/\/ Construct a vtkVolumeMapper with empty scalar input and clipping off.\nvtkVolumeMapper::vtkVolumeMapper()\n{\n this->RGBTextureInput = NULL;\n this->Clipping = 0;\n this->Bounds[0] = this->Bounds[2] = this->Bounds[4] = -1.0;\n this->Bounds[1] = this->Bounds[3] = this->Bounds[5] = 1.0;\n this->Center[0] = this->Center[1] = this->Center[2] = 0.0;\n}\n\nvtkVolumeMapper::~vtkVolumeMapper()\n{\n this->SetInput((vtkStructuredPoints *)NULL);\n}\n\nvoid vtkVolumeMapper::Update()\n{\n if ( this->Input )\n {\n this->Input->Update();\n }\n\n if ( this->RGBTextureInput )\n {\n this->RGBTextureInput->Update();\n }\n}\n\nvoid vtkVolumeMapper::SetInput( vtkStructuredPoints *input )\n{\n if ( (vtkDataSet *)input != this->Input )\n {\n \/\/ If we have data already, unregister it\n if ( this->Input )\n {\n this->Input->UnRegister(this);\n }\n \/\/ Set the input data\n this->Input = (vtkDataSet *)input;\n \/\/ If this is not NULL, register it\n if ( this->Input )\n {\n this->Input->Register(this);\n }\n \/\/ We've been modified!\n this->Modified(); \n }\n}\n\nvoid vtkVolumeMapper::SetRGBTextureInput( vtkStructuredPoints *rgbTexture )\n{\n vtkPointData *pd;\n vtkScalars *scalars;\n\n if ( rgbTexture != this->RGBTextureInput )\n {\n \/\/ If we are actually setting a texture (not NULL) then\n \/\/ do some error checking to make sure it is of the right\n \/\/ type with the right number of components\n if ( rgbTexture )\n {\n rgbTexture->Update();\n pd = rgbTexture->GetPointData();\n if ( !pd )\n\t{\n\tvtkErrorMacro( << \"No PointData in texture!\" );\n\treturn;\n\t}\n scalars = pd->GetScalars();\n if ( !scalars )\n\t{\n\tvtkErrorMacro( << \"No scalars in texture!\" );\n\treturn;\n\t}\n if ( scalars->GetDataType() != VTK_UNSIGNED_CHAR )\n\t{\n\tvtkErrorMacro( << \"Scalars in texture must be unsigned char!\" );\n\treturn; \n\t}\n if ( scalars->GetNumberOfComponents() != 3 )\n\t{\n\tvtkErrorMacro( << \"Scalars must have 3 components (r, g, and b)\" );\n\treturn; \n\t}\n }\n \/\/ If we have a texture already, unregister it\n if ( this->RGBTextureInput )\n {\n this->RGBTextureInput->UnRegister(this);\n }\n \/\/ Set the texture\n this->RGBTextureInput = rgbTexture;\n \/\/ If this is not NULL, register it\n if ( this->RGBTextureInput )\n {\n this->RGBTextureInput->Register(this);\n }\n \/\/ We've been modified!\n this->Modified();\n }\n}\n\n\/\/ Print the vtkVolumeMapper\nvoid vtkVolumeMapper::PrintSelf(ostream& os, vtkIndent indent)\n{\n vtkAbstractMapper::PrintSelf(os,indent);\n\n if ( this->RGBTextureInput )\n {\n os << indent << \"RGBTextureInput: (\" << this->RGBTextureInput << \")\\n\";\n }\n else\n {\n os << indent << \"RGBTextureInput: (none)\\n\";\n }\n\n os << indent << \"Clipping: \" << (this->Clipping ? \"On\\n\" : \"Off\\n\");\n os << indent << \"Build Time: \" <<this->BuildTime.GetMTime() << \"\\n\";\n}\n\n<commit_msg>ERR: Was leaking ivar RGBTextureInput.<commit_after>\/*=========================================================================\n\n Program: Visualization Toolkit\n Module: vtkVolumeMapper.cxx\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n\nCopyright (c) 1993-1998 Ken Martin, Will Schroeder, Bill Lorensen.\n\nThis software is copyrighted by Ken Martin, Will Schroeder and Bill Lorensen.\nThe following terms apply to all files associated with the software unless\nexplicitly disclaimed in individual files. This copyright specifically does\nnot apply to the related textbook \"The Visualization Toolkit\" ISBN\n013199837-4 published by Prentice Hall which is covered by its own copyright.\n\nThe authors hereby grant permission to use, copy, and distribute this\nsoftware and its documentation for any purpose, provided that existing\ncopyright notices are retained in all copies and that this notice is included\nverbatim in any distributions. Additionally, the authors grant permission to\nmodify this software and its documentation for any purpose, provided that\nsuch modifications are not distributed without the explicit consent of the\nauthors and that existing copyright notices are retained in all copies. Some\nof the algorithms implemented by this software are patented, observe all\napplicable patent law.\n\nIN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR\nDIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT\nOF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF,\nEVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\nTHE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING,\nBUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\nPARTICULAR PURPOSE, AND NON-INFRINGEMENT. THIS SOFTWARE IS PROVIDED ON AN\n\"AS IS\" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE\nMAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.\n\n\n=========================================================================*\/\n#include \"vtkVolumeMapper.h\"\n\n\/\/ Construct a vtkVolumeMapper with empty scalar input and clipping off.\nvtkVolumeMapper::vtkVolumeMapper()\n{\n this->RGBTextureInput = NULL;\n this->Clipping = 0;\n this->Bounds[0] = this->Bounds[2] = this->Bounds[4] = -1.0;\n this->Bounds[1] = this->Bounds[3] = this->Bounds[5] = 1.0;\n this->Center[0] = this->Center[1] = this->Center[2] = 0.0;\n}\n\nvtkVolumeMapper::~vtkVolumeMapper()\n{\n this->SetInput((vtkStructuredPoints *)NULL);\n if (this->RGBTextureInput)\n {\n this->RGBTextureInput->Delete ();\n this->RGBTextureInput = NULL;\n }\n}\n\nvoid vtkVolumeMapper::Update()\n{\n if ( this->Input )\n {\n this->Input->Update();\n }\n\n if ( this->RGBTextureInput )\n {\n this->RGBTextureInput->Update();\n }\n}\n\nvoid vtkVolumeMapper::SetInput( vtkStructuredPoints *input )\n{\n if ( (vtkDataSet *)input != this->Input )\n {\n \/\/ If we have data already, unregister it\n if ( this->Input )\n {\n this->Input->UnRegister(this);\n }\n \/\/ Set the input data\n this->Input = (vtkDataSet *)input;\n \/\/ If this is not NULL, register it\n if ( this->Input )\n {\n this->Input->Register(this);\n }\n \/\/ We've been modified!\n this->Modified(); \n }\n}\n\nvoid vtkVolumeMapper::SetRGBTextureInput( vtkStructuredPoints *rgbTexture )\n{\n vtkPointData *pd;\n vtkScalars *scalars;\n\n if ( rgbTexture != this->RGBTextureInput )\n {\n \/\/ If we are actually setting a texture (not NULL) then\n \/\/ do some error checking to make sure it is of the right\n \/\/ type with the right number of components\n if ( rgbTexture )\n {\n rgbTexture->Update();\n pd = rgbTexture->GetPointData();\n if ( !pd )\n\t{\n\tvtkErrorMacro( << \"No PointData in texture!\" );\n\treturn;\n\t}\n scalars = pd->GetScalars();\n if ( !scalars )\n\t{\n\tvtkErrorMacro( << \"No scalars in texture!\" );\n\treturn;\n\t}\n if ( scalars->GetDataType() != VTK_UNSIGNED_CHAR )\n\t{\n\tvtkErrorMacro( << \"Scalars in texture must be unsigned char!\" );\n\treturn; \n\t}\n if ( scalars->GetNumberOfComponents() != 3 )\n\t{\n\tvtkErrorMacro( << \"Scalars must have 3 components (r, g, and b)\" );\n\treturn; \n\t}\n }\n \/\/ If we have a texture already, unregister it\n if ( this->RGBTextureInput )\n {\n this->RGBTextureInput->UnRegister(this);\n }\n \/\/ Set the texture\n this->RGBTextureInput = rgbTexture;\n \/\/ If this is not NULL, register it\n if ( this->RGBTextureInput )\n {\n this->RGBTextureInput->Register(this);\n }\n \/\/ We've been modified!\n this->Modified();\n }\n}\n\n\/\/ Print the vtkVolumeMapper\nvoid vtkVolumeMapper::PrintSelf(ostream& os, vtkIndent indent)\n{\n vtkAbstractMapper::PrintSelf(os,indent);\n\n if ( this->RGBTextureInput )\n {\n os << indent << \"RGBTextureInput: (\" << this->RGBTextureInput << \")\\n\";\n }\n else\n {\n os << indent << \"RGBTextureInput: (none)\\n\";\n }\n\n os << indent << \"Clipping: \" << (this->Clipping ? \"On\\n\" : \"Off\\n\");\n os << indent << \"Build Time: \" <<this->BuildTime.GetMTime() << \"\\n\";\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ This file is part of the AliceVision project.\n\/\/ Copyright (c) 2017 AliceVision contributors.\n\/\/ This Source Code Form is subject to the terms of the Mozilla Public License,\n\/\/ v. 2.0. If a copy of the MPL was not distributed with this file,\n\/\/ You can obtain one at https:\/\/mozilla.org\/MPL\/2.0\/.\n\n#include <aliceVision\/system\/cmdline.hpp>\n#include <aliceVision\/system\/Logger.hpp>\n#include <aliceVision\/system\/Timer.hpp>\n#include <aliceVision\/mvsUtils\/common.hpp>\n\n#include <EigenTypes.h>\n#include <MeshTypes.h>\n#include <SDFilter.h>\n#include <MeshNormalFilter.h>\n#include <MeshNormalDenoising.h>\n\n#include <OpenMesh\/Core\/IO\/reader\/OBJReader.hh>\n#include <OpenMesh\/Core\/IO\/writer\/OBJWriter.hh>\n#include <OpenMesh\/Core\/IO\/IOManager.hh>\n\n#include <boost\/program_options.hpp>\n#include <boost\/filesystem.hpp>\n\n\/\/ These constants define the current software version.\n\/\/ They must be updated when the command line is changed.\n#define ALICEVISION_SOFTWARE_VERSION_MAJOR 1\n#define ALICEVISION_SOFTWARE_VERSION_MINOR 0\n\nusing namespace aliceVision;\n\nnamespace bfs = boost::filesystem;\nnamespace po = boost::program_options;\n\nint main(int argc, char* argv[])\n{\n system::Timer timer;\n\n std::string verboseLevel = system::EVerboseLevel_enumToString(system::Logger::getDefaultVerboseLevel());\n std::string inputMeshPath;\n std::string outputMeshPath;\n\n int denoisingIterations = 5; \/\/ OuterIterations\n float meshUpdateClosenessWeight = 0.001;\n int meshUpdateIterations = 20;\n int meshUpdateMethod = SDFilter::MeshFilterParameters::ITERATIVE_UPDATE;\n float lambda = 2.0;\n float eta = 1.5;\n float mu = 1.5;\n float nu = 0.3;\n\n po::options_description allParams(\"AliceVision meshDenoising\");\n\n po::options_description requiredParams(\"Required parameters\");\n requiredParams.add_options()\n (\"input,i\", po::value<std::string>(&inputMeshPath)->required(),\n \"Input Mesh (OBJ file format).\")\n (\"output,o\", po::value<std::string>(&outputMeshPath)->required(),\n \"Output mesh (OBJ file format).\");\n\n po::options_description optionalParams(\"Optional parameters\");\n optionalParams.add_options()\n (\"denoisingIterations\", po::value<int>(&denoisingIterations)->default_value(denoisingIterations),\n \"Number of denoising iterations.\")\n (\"meshUpdateClosenessWeight\", po::value<float>(&meshUpdateClosenessWeight)->default_value(meshUpdateClosenessWeight),\n \"Closeness weight for mesh update, must be positive.\")\n (\"lambda\", po::value<float>(&lambda)->default_value(lambda),\n \"Regularization weight.\")\n (\"eta\", po::value<float>(&eta)->default_value(eta),\n \"Gaussian standard deviation for spatial weight, scaled by the average distance between adjacent face centroids. Must be positive.\")\n (\"mu\", po::value<float>(&mu)->default_value(mu),\n \"Gaussian standard deviation for guidance weight.\")\n (\"nu\", po::value<float>(&nu)->default_value(nu),\n \"Gaussian standard deviation for signal weight.\")\n (\"meshUpdateMethod\", po::value<int>(&meshUpdateMethod)->default_value(meshUpdateMethod),\n \"Mesh Update Method: \\n\"\n \"* ITERATIVE_UPDATE(\" BOOST_PP_STRINGIZE(SDFilter::MeshFilterParameters::ITERATIVE_UPDATE) \") (default): ShapeUp styled iterative solver\\n\"\n \"* POISSON_UPDATE(\" BOOST_PP_STRINGIZE(SDFilter::MeshFilterParameters::POISSON_UPDATE) \"): Poisson-based update from [Want et al. 2015]\\n\");\n\n po::options_description logParams(\"Log parameters\");\n logParams.add_options()\n (\"verboseLevel,v\", po::value<std::string>(&verboseLevel)->default_value(verboseLevel),\n \"verbosity level (fatal, error, warning, info, debug, trace).\");\n\n allParams.add(requiredParams).add(optionalParams).add(logParams);\n\n po::variables_map vm;\n\n try\n {\n po::store(po::parse_command_line(argc, argv, allParams), vm);\n\n if(vm.count(\"help\") || (argc == 1))\n {\n ALICEVISION_COUT(allParams);\n return EXIT_SUCCESS;\n }\n\n po::notify(vm);\n }\n catch(boost::program_options::required_option& e)\n {\n ALICEVISION_CERR(\"ERROR: \" << e.what() << std::endl);\n ALICEVISION_COUT(\"Usage:\\n\\n\" << allParams);\n return EXIT_FAILURE;\n }\n catch(boost::program_options::error& e)\n {\n ALICEVISION_CERR(\"ERROR: \" << e.what() << std::endl);\n ALICEVISION_COUT(\"Usage:\\n\\n\" << allParams);\n return EXIT_FAILURE;\n }\n\n ALICEVISION_COUT(\"Program called with the following parameters:\");\n ALICEVISION_COUT(vm);\n\n \/\/ set verbose level\n system::Logger::get()->setLogLevel(verboseLevel);\n\n bfs::path outDirectory = bfs::path(outputMeshPath).parent_path();\n if(!bfs::is_directory(outDirectory))\n bfs::create_directory(outDirectory);\n\n\n TriMesh inMesh;\n if(!OpenMesh::IO::read_mesh(inMesh, inputMeshPath.c_str()))\n {\n ALICEVISION_LOG_ERROR(\"Unable to read input mesh from the file: \" << inputMeshPath);\n return EXIT_FAILURE;\n }\n if(inMesh.n_vertices() == 0 || inMesh.n_faces() == 0)\n {\n ALICEVISION_LOG_ERROR(\"Empty mesh from the file: \" << inputMeshPath);\n ALICEVISION_LOG_ERROR(\"Input mesh: \" << inMesh.n_vertices() << \" vertices and \" << inMesh.n_faces() << \" facets.\");\n return EXIT_FAILURE;\n }\n\n\/\/ #ifdef USE_OPENMP\n Eigen::initParallel();\n\/\/ #endif\n\n \/\/ Load option file\n SDFilter::MeshDenoisingParameters param;\n param.mesh_update_method = (SDFilter::MeshFilterParameters::MeshUpdateMethod)meshUpdateMethod;\n param.mesh_update_closeness_weight = meshUpdateClosenessWeight;\n param.mesh_update_iter = meshUpdateIterations;\n param.lambda = lambda;\n param.eta = eta;\n param.mu = mu;\n param.nu = nu;\n\n\/\/ enum LinearSolverType\n\/\/ {\n\/\/ CG,\n\/\/ LDLT\n\/\/ };\n\/\/ \/\/ Parameters related to termination criteria\n\/\/ int max_iter; \/\/ Max number of iterations\n\/\/ double avg_disp_eps; \/\/ Max average per-signal displacement threshold between two iterations for determining convergence\n\/\/ bool normalize_iterates; \/\/ Normalization of the filtered normals in each iteration\n\n if(!param.valid_parameters())\n {\n ALICEVISION_LOG_ERROR(\"Invalid filter options. Aborting...\");\n return EXIT_FAILURE;\n }\n param.output();\n\n ALICEVISION_LOG_INFO(\"Mesh file: \\\"\" << inputMeshPath << \"\\\" loaded.\");\n ALICEVISION_LOG_INFO(\"Input mesh: \" << inMesh.n_vertices() << \" vertices and \" << inMesh.n_faces() << \" facets.\");\n\n TriMesh outMesh;\n ALICEVISION_LOG_INFO(\"Mesh normalization.\");\n \/\/ Normalize the input mesh\n Eigen::Vector3d original_center;\n double original_scale;\n SDFilter::normalize_mesh(inMesh, original_center, original_scale);\n if(true)\n {\n ALICEVISION_LOG_INFO(\"Start mesh denoising.\");\n \/\/ Filter the normals and construct the output mesh\n SDFilter::MeshNormalDenoising denoiser(inMesh);\n denoiser.denoise(param, outMesh);\n ALICEVISION_LOG_INFO(\"Mesh denoising done.\");\n }\n else\n {\n ALICEVISION_LOG_INFO(\"Start mesh filtering.\");\n \/\/ Filter the normals and construct the output mesh\n SDFilter::MeshNormalFilter filter(inMesh);\n filter.filter(param, outMesh);\n ALICEVISION_LOG_INFO(\"Mesh filtering done.\");\n }\n SDFilter::restore_mesh(outMesh, original_center, original_scale);\n\n ALICEVISION_LOG_INFO(\"Output mesh: \" << outMesh.n_vertices() << \" vertices and \" << outMesh.n_faces() << \" facets.\");\n\n if(outMesh.n_faces() == 0)\n {\n ALICEVISION_LOG_ERROR(\"Failed: the output mesh is empty.\");\n return EXIT_FAILURE;\n }\n\n ALICEVISION_LOG_INFO(\"Save mesh.\");\n \/\/ Save output mesh\n if(!OpenMesh::IO::write_mesh(outMesh, outputMeshPath))\n {\n ALICEVISION_LOG_ERROR(\"Failed to save mesh file: \\\"\" << outputMeshPath << \"\\\".\");\n return EXIT_FAILURE;\n }\n\n ALICEVISION_LOG_INFO(\"Mesh file: \\\"\" << outputMeshPath << \"\\\" saved.\");\n\n ALICEVISION_LOG_INFO(\"Task done in (s): \" + std::to_string(timer.elapsed()));\n return EXIT_SUCCESS;\n}\n<commit_msg>Denoising outer iteration were ignored, assign parameter<commit_after>\/\/ This file is part of the AliceVision project.\n\/\/ Copyright (c) 2017 AliceVision contributors.\n\/\/ This Source Code Form is subject to the terms of the Mozilla Public License,\n\/\/ v. 2.0. If a copy of the MPL was not distributed with this file,\n\/\/ You can obtain one at https:\/\/mozilla.org\/MPL\/2.0\/.\n\n#include <aliceVision\/system\/cmdline.hpp>\n#include <aliceVision\/system\/Logger.hpp>\n#include <aliceVision\/system\/Timer.hpp>\n#include <aliceVision\/mvsUtils\/common.hpp>\n\n#include <EigenTypes.h>\n#include <MeshTypes.h>\n#include <SDFilter.h>\n#include <MeshNormalFilter.h>\n#include <MeshNormalDenoising.h>\n\n#include <OpenMesh\/Core\/IO\/reader\/OBJReader.hh>\n#include <OpenMesh\/Core\/IO\/writer\/OBJWriter.hh>\n#include <OpenMesh\/Core\/IO\/IOManager.hh>\n\n#include <boost\/program_options.hpp>\n#include <boost\/filesystem.hpp>\n\n\/\/ These constants define the current software version.\n\/\/ They must be updated when the command line is changed.\n#define ALICEVISION_SOFTWARE_VERSION_MAJOR 1\n#define ALICEVISION_SOFTWARE_VERSION_MINOR 0\n\nusing namespace aliceVision;\n\nnamespace bfs = boost::filesystem;\nnamespace po = boost::program_options;\n\nint main(int argc, char* argv[])\n{\n system::Timer timer;\n\n std::string verboseLevel = system::EVerboseLevel_enumToString(system::Logger::getDefaultVerboseLevel());\n std::string inputMeshPath;\n std::string outputMeshPath;\n\n int denoisingIterations = 5; \/\/ OuterIterations\n float meshUpdateClosenessWeight = 0.001;\n int meshUpdateIterations = 20;\n int meshUpdateMethod = SDFilter::MeshFilterParameters::ITERATIVE_UPDATE;\n float lambda = 2.0;\n float eta = 1.5;\n float mu = 1.5;\n float nu = 0.3;\n\n po::options_description allParams(\"AliceVision meshDenoising\");\n\n po::options_description requiredParams(\"Required parameters\");\n requiredParams.add_options()\n (\"input,i\", po::value<std::string>(&inputMeshPath)->required(),\n \"Input Mesh (OBJ file format).\")\n (\"output,o\", po::value<std::string>(&outputMeshPath)->required(),\n \"Output mesh (OBJ file format).\");\n\n po::options_description optionalParams(\"Optional parameters\");\n optionalParams.add_options()\n (\"denoisingIterations\", po::value<int>(&denoisingIterations)->default_value(denoisingIterations),\n \"Number of denoising iterations.\")\n (\"meshUpdateClosenessWeight\", po::value<float>(&meshUpdateClosenessWeight)->default_value(meshUpdateClosenessWeight),\n \"Closeness weight for mesh update, must be positive.\")\n (\"lambda\", po::value<float>(&lambda)->default_value(lambda),\n \"Regularization weight.\")\n (\"eta\", po::value<float>(&eta)->default_value(eta),\n \"Gaussian standard deviation for spatial weight, scaled by the average distance between adjacent face centroids. Must be positive.\")\n (\"mu\", po::value<float>(&mu)->default_value(mu),\n \"Gaussian standard deviation for guidance weight.\")\n (\"nu\", po::value<float>(&nu)->default_value(nu),\n \"Gaussian standard deviation for signal weight.\")\n (\"meshUpdateMethod\", po::value<int>(&meshUpdateMethod)->default_value(meshUpdateMethod),\n \"Mesh Update Method: \\n\"\n \"* ITERATIVE_UPDATE(\" BOOST_PP_STRINGIZE(SDFilter::MeshFilterParameters::ITERATIVE_UPDATE) \") (default): ShapeUp styled iterative solver\\n\"\n \"* POISSON_UPDATE(\" BOOST_PP_STRINGIZE(SDFilter::MeshFilterParameters::POISSON_UPDATE) \"): Poisson-based update from [Want et al. 2015]\\n\");\n\n po::options_description logParams(\"Log parameters\");\n logParams.add_options()\n (\"verboseLevel,v\", po::value<std::string>(&verboseLevel)->default_value(verboseLevel),\n \"verbosity level (fatal, error, warning, info, debug, trace).\");\n\n allParams.add(requiredParams).add(optionalParams).add(logParams);\n\n po::variables_map vm;\n\n try\n {\n po::store(po::parse_command_line(argc, argv, allParams), vm);\n\n if(vm.count(\"help\") || (argc == 1))\n {\n ALICEVISION_COUT(allParams);\n return EXIT_SUCCESS;\n }\n\n po::notify(vm);\n }\n catch(boost::program_options::required_option& e)\n {\n ALICEVISION_CERR(\"ERROR: \" << e.what() << std::endl);\n ALICEVISION_COUT(\"Usage:\\n\\n\" << allParams);\n return EXIT_FAILURE;\n }\n catch(boost::program_options::error& e)\n {\n ALICEVISION_CERR(\"ERROR: \" << e.what() << std::endl);\n ALICEVISION_COUT(\"Usage:\\n\\n\" << allParams);\n return EXIT_FAILURE;\n }\n\n ALICEVISION_COUT(\"Program called with the following parameters:\");\n ALICEVISION_COUT(vm);\n\n \/\/ set verbose level\n system::Logger::get()->setLogLevel(verboseLevel);\n\n bfs::path outDirectory = bfs::path(outputMeshPath).parent_path();\n if(!bfs::is_directory(outDirectory))\n bfs::create_directory(outDirectory);\n\n\n TriMesh inMesh;\n if(!OpenMesh::IO::read_mesh(inMesh, inputMeshPath.c_str()))\n {\n ALICEVISION_LOG_ERROR(\"Unable to read input mesh from the file: \" << inputMeshPath);\n return EXIT_FAILURE;\n }\n if(inMesh.n_vertices() == 0 || inMesh.n_faces() == 0)\n {\n ALICEVISION_LOG_ERROR(\"Empty mesh from the file: \" << inputMeshPath);\n ALICEVISION_LOG_ERROR(\"Input mesh: \" << inMesh.n_vertices() << \" vertices and \" << inMesh.n_faces() << \" facets.\");\n return EXIT_FAILURE;\n }\n\n\/\/ #ifdef USE_OPENMP\n Eigen::initParallel();\n\/\/ #endif\n\n \/\/ Load option file\n SDFilter::MeshDenoisingParameters param;\n param.outer_iterations = denoisingIterations;\n param.mesh_update_method = (SDFilter::MeshFilterParameters::MeshUpdateMethod)meshUpdateMethod;\n param.mesh_update_closeness_weight = meshUpdateClosenessWeight;\n param.mesh_update_iter = meshUpdateIterations;\n param.lambda = lambda;\n param.eta = eta;\n param.mu = mu;\n param.nu = nu;\n\n\/\/ enum LinearSolverType\n\/\/ {\n\/\/ CG,\n\/\/ LDLT\n\/\/ };\n\/\/ \/\/ Parameters related to termination criteria\n\/\/ int max_iter; \/\/ Max number of iterations\n\/\/ double avg_disp_eps; \/\/ Max average per-signal displacement threshold between two iterations for determining convergence\n\/\/ bool normalize_iterates; \/\/ Normalization of the filtered normals in each iteration\n\n if(!param.valid_parameters())\n {\n ALICEVISION_LOG_ERROR(\"Invalid filter options. Aborting...\");\n return EXIT_FAILURE;\n }\n param.output();\n\n ALICEVISION_LOG_INFO(\"Mesh file: \\\"\" << inputMeshPath << \"\\\" loaded.\");\n ALICEVISION_LOG_INFO(\"Input mesh: \" << inMesh.n_vertices() << \" vertices and \" << inMesh.n_faces() << \" facets.\");\n\n TriMesh outMesh;\n ALICEVISION_LOG_INFO(\"Mesh normalization.\");\n \/\/ Normalize the input mesh\n Eigen::Vector3d original_center;\n double original_scale;\n SDFilter::normalize_mesh(inMesh, original_center, original_scale);\n if(true)\n {\n ALICEVISION_LOG_INFO(\"Start mesh denoising.\");\n \/\/ Filter the normals and construct the output mesh\n SDFilter::MeshNormalDenoising denoiser(inMesh);\n denoiser.denoise(param, outMesh);\n ALICEVISION_LOG_INFO(\"Mesh denoising done.\");\n }\n else\n {\n ALICEVISION_LOG_INFO(\"Start mesh filtering.\");\n \/\/ Filter the normals and construct the output mesh\n SDFilter::MeshNormalFilter filter(inMesh);\n filter.filter(param, outMesh);\n ALICEVISION_LOG_INFO(\"Mesh filtering done.\");\n }\n SDFilter::restore_mesh(outMesh, original_center, original_scale);\n\n ALICEVISION_LOG_INFO(\"Output mesh: \" << outMesh.n_vertices() << \" vertices and \" << outMesh.n_faces() << \" facets.\");\n\n if(outMesh.n_faces() == 0)\n {\n ALICEVISION_LOG_ERROR(\"Failed: the output mesh is empty.\");\n return EXIT_FAILURE;\n }\n\n ALICEVISION_LOG_INFO(\"Save mesh.\");\n \/\/ Save output mesh\n if(!OpenMesh::IO::write_mesh(outMesh, outputMeshPath))\n {\n ALICEVISION_LOG_ERROR(\"Failed to save mesh file: \\\"\" << outputMeshPath << \"\\\".\");\n return EXIT_FAILURE;\n }\n\n ALICEVISION_LOG_INFO(\"Mesh file: \\\"\" << outputMeshPath << \"\\\" saved.\");\n\n ALICEVISION_LOG_INFO(\"Task done in (s): \" + std::to_string(timer.elapsed()));\n return EXIT_SUCCESS;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: unohelp2.cxx,v $\n *\n * $Revision: 1.1 $\n *\n * last change: $Author: tbe $ $Date: 2002-03-18 17:36:18 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef _VCL_UNOHELP2_HXX\n#include <unohelp2.hxx>\n#endif\n\n#ifndef _SOT_EXCHANGE_HXX\n#include <sot\/exchange.hxx>\n#endif\n\n#ifndef _SOT_FORMATS_HXX\n#include <sot\/formats.hxx>\n#endif\n\n\nusing namespace ::com::sun::star;\n\n\nnamespace vcl { namespace unohelper {\n\n TextDataObject::TextDataObject( const String& rText ) : maText( rText )\n {\n }\n\n TextDataObject::~TextDataObject()\n {\n }\n\n \/\/ ::com::sun::star::uno::XInterface\n uno::Any TextDataObject::queryInterface( const uno::Type & rType ) throw(uno::RuntimeException)\n {\n uno::Any aRet = ::cppu::queryInterface( rType, SAL_STATIC_CAST( datatransfer::XTransferable*, this ) );\n return (aRet.hasValue() ? aRet : OWeakObject::queryInterface( rType ));\n }\n\n \/\/ ::com::sun::star::datatransfer::XTransferable\n uno::Any TextDataObject::getTransferData( const datatransfer::DataFlavor& rFlavor ) throw(datatransfer::UnsupportedFlavorException, io::IOException, uno::RuntimeException)\n {\n uno::Any aAny;\n\n ULONG nT = SotExchange::GetFormat( rFlavor );\n if ( nT == SOT_FORMAT_STRING )\n {\n aAny <<= (::rtl::OUString)GetString();\n }\n else\n {\n throw datatransfer::UnsupportedFlavorException();\n }\n return aAny;\n }\n\n uno::Sequence< datatransfer::DataFlavor > TextDataObject::getTransferDataFlavors( ) throw(uno::RuntimeException)\n {\n uno::Sequence< datatransfer::DataFlavor > aDataFlavors(1);\n SotExchange::GetFormatDataFlavor( SOT_FORMAT_STRING, aDataFlavors.getArray()[0] );\n return aDataFlavors;\n }\n\n sal_Bool TextDataObject::isDataFlavorSupported( const datatransfer::DataFlavor& rFlavor ) throw(uno::RuntimeException)\n {\n ULONG nT = SotExchange::GetFormat( rFlavor );\n return ( nT == SOT_FORMAT_STRING );\n }\n\n}} \/\/ namespace vcl::unohelper\n<commit_msg>INTEGRATION: CWS vcl35 (1.1.698); FILE MERGED 2005\/01\/13 18:37:21 pl 1.1.698.1: #i39157# thanks to fs: copy assertions from clipboard window<commit_after>\/*************************************************************************\n *\n * $RCSfile: unohelp2.cxx,v $\n *\n * $Revision: 1.2 $\n *\n * last change: $Author: rt $ $Date: 2005-01-31 13:21:42 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef _VCL_UNOHELP2_HXX\n#include <unohelp2.hxx>\n#endif\n\n#ifndef _SOT_EXCHANGE_HXX\n#include <sot\/exchange.hxx>\n#endif\n\n#ifndef _SOT_FORMATS_HXX\n#include <sot\/formats.hxx>\n#endif\n\n#ifndef _TOOLS_DEBUG_HXX\n#include <tools\/debug.hxx>\n#endif\n#ifndef _SV_SVAPP_HXX\n#include <vcl\/svapp.hxx>\n#endif\n#ifndef _COM_SUN_STAR_DATATRANSFER_CLIPBOARD_XCLIPBOARD_HPP_\n#include <com\/sun\/star\/datatransfer\/clipboard\/XClipboard.hpp>\n#endif\n#ifndef _COM_SUN_STAR_DATATRANSFER_CLIPBOARD_XFLUSHABLECLIPBOARD_HPP_\n#include <com\/sun\/star\/datatransfer\/clipboard\/XFlushableClipboard.hpp>\n#endif\n\n\nusing namespace ::com::sun::star;\n\nnamespace vcl { namespace unohelper {\n\n TextDataObject::TextDataObject( const String& rText ) : maText( rText )\n {\n }\n\n TextDataObject::~TextDataObject()\n {\n }\n\n void TextDataObject::CopyStringTo( const String& rContent,\n const uno::Reference< datatransfer::clipboard::XClipboard >& rxClipboard )\n {\n DBG_ASSERT( rxClipboard.is(), \"TextDataObject::CopyStringTo: invalid clipboard!\" );\n if ( !rxClipboard.is() )\n return;\n\n TextDataObject* pDataObj = new TextDataObject( rContent );\n\n const sal_uInt32 nRef = Application::ReleaseSolarMutex();\n try\n {\n rxClipboard->setContents( pDataObj, NULL );\n\n uno::Reference< datatransfer::clipboard::XFlushableClipboard > xFlushableClipboard( rxClipboard, uno::UNO_QUERY );\n if( xFlushableClipboard.is() )\n xFlushableClipboard->flushClipboard();\n }\n catch( const uno::Exception& )\n {\n }\n Application::AcquireSolarMutex( nRef );\n }\n\n \/\/ ::com::sun::star::uno::XInterface\n uno::Any TextDataObject::queryInterface( const uno::Type & rType ) throw(uno::RuntimeException)\n {\n uno::Any aRet = ::cppu::queryInterface( rType, SAL_STATIC_CAST( datatransfer::XTransferable*, this ) );\n return (aRet.hasValue() ? aRet : OWeakObject::queryInterface( rType ));\n }\n\n \/\/ ::com::sun::star::datatransfer::XTransferable\n uno::Any TextDataObject::getTransferData( const datatransfer::DataFlavor& rFlavor ) throw(datatransfer::UnsupportedFlavorException, io::IOException, uno::RuntimeException)\n {\n uno::Any aAny;\n\n ULONG nT = SotExchange::GetFormat( rFlavor );\n if ( nT == SOT_FORMAT_STRING )\n {\n aAny <<= (::rtl::OUString)GetString();\n }\n else\n {\n throw datatransfer::UnsupportedFlavorException();\n }\n return aAny;\n }\n\n uno::Sequence< datatransfer::DataFlavor > TextDataObject::getTransferDataFlavors( ) throw(uno::RuntimeException)\n {\n uno::Sequence< datatransfer::DataFlavor > aDataFlavors(1);\n SotExchange::GetFormatDataFlavor( SOT_FORMAT_STRING, aDataFlavors.getArray()[0] );\n return aDataFlavors;\n }\n\n sal_Bool TextDataObject::isDataFlavorSupported( const datatransfer::DataFlavor& rFlavor ) throw(uno::RuntimeException)\n {\n ULONG nT = SotExchange::GetFormat( rFlavor );\n return ( nT == SOT_FORMAT_STRING );\n }\n\n}} \/\/ namespace vcl::unohelper\n<|endoftext|>"} {"text":"<commit_before>\/*******************************************************\n * Copyright (c) 2014, ArrayFire\n * All rights reserved.\n *\n * This file is distributed under 3-clause BSD license.\n * The complete license agreement can be obtained at:\n * http:\/\/arrayfire.com\/licenses\/BSD-3-Clause\n ********************************************************\/\n\n#include <af\/dim4.hpp>\n#include <af\/defines.h>\n#include <af\/statistics.h>\n#include <af\/index.h>\n#include <af\/arith.h>\n#include <af\/data.h>\n#include <handle.hpp>\n#include <err_common.hpp>\n#include <backend.hpp>\n#include <sort.hpp>\n#include <math.hpp>\n#include <cast.hpp>\n\nusing namespace detail;\nusing af::dim4;\n\ntemplate<typename T>\nstatic double median(const af_array& in)\n{\n dim_t nElems = getInfo(in).elements();\n double mid = (nElems + 1) \/ 2;\n af_seq mdSpan[1]= {af_make_seq(mid-1, mid, 1)};\n dim4 dims(nElems, 1, 1, 1);\n\n af_array temp = 0;\n AF_CHECK(af_moddims(&temp, in, 1, dims.get()));\n const Array<T> input = getArray<T>(temp);\n\n Array<T> sortedArr = sort<T, true>(input, 0);\n\n double result;\n T resPtr[2];\n af_array res = 0;\n AF_CHECK(af_index(&res, getHandle<T>(sortedArr), 1, mdSpan));\n AF_CHECK(af_get_data_ptr((void*)&resPtr, res));\n\n if (nElems % 2 == 1) {\n result = resPtr[0];\n } else {\n if (input.isFloating()) {\n result = division(resPtr[0] + resPtr[1], 2);\n } else {\n result = division((float)resPtr[0] + (float)resPtr[1], 2);\n }\n }\n\n AF_CHECK(af_release_array(res));\n AF_CHECK(af_release_array(temp));\n\n return result;\n}\n\ntemplate<typename T>\nstatic af_array median(const af_array& in, const dim_t dim)\n{\n const Array<T> input = getArray<T>(in);\n Array<T> sortedIn = sort<T, true>(input, dim);\n\n int nElems = input.dims()[0];\n double mid = (nElems + 1) \/ 2;\n af_array left = 0;\n\n af_seq slices[4] = {af_span, af_span, af_span, af_span};\n slices[dim] = af_make_seq(mid-1.0, mid-1.0, 1.0);\n\n af_array sortedIn_handle = getHandle<T>(sortedIn);\n AF_CHECK(af_index(&left, sortedIn_handle, input.ndims(), slices));\n\n if (nElems % 2 == 1) {\n \/\/ mid-1 is our guy\n if (input.isFloating()) return left;\n\n \/\/ Return as floats for consistency\n af_array out;\n AF_CHECK(af_cast(&out, left, f32));\n AF_CHECK(af_release_array(left));\n AF_CHECK(af_release_array(sortedIn_handle));\n return out;\n } else {\n \/\/ ((mid-1)+mid)\/2 is our guy\n dim4 dims = input.dims();\n af_array right = 0;\n slices[dim] = af_make_seq(mid, mid, 1.0);\n\n AF_CHECK(af_index(&right, sortedIn_handle, dims.ndims(), slices));\n\n af_array sumarr = 0;\n af_array carr = 0;\n af_array result = 0;\n\n dim4 cdims = dim4(1, dims[1], dims[2], dims[3]);\n AF_CHECK(af_constant(&carr, 0.5, cdims.ndims(), cdims.get(), input.isDouble() ? f64 : f32));\n\n if (!input.isFloating()) {\n af_array lleft, rright;\n AF_CHECK(af_cast(&lleft, left, f32));\n AF_CHECK(af_cast(&rright, right, f32));\n AF_CHECK(af_release_array(left));\n AF_CHECK(af_release_array(right));\n left = lleft;\n right = rright;\n }\n\n AF_CHECK(af_add(&sumarr, left, right, false));\n AF_CHECK(af_mul(&result, sumarr, carr, false));\n\n AF_CHECK(af_release_array(left));\n AF_CHECK(af_release_array(right));\n AF_CHECK(af_release_array(sumarr));\n AF_CHECK(af_release_array(carr));\n AF_CHECK(af_release_array(sortedIn_handle));\n return result;\n }\n}\n\naf_err af_median_all(double *realVal, double *imagVal, const af_array in)\n{\n try {\n ArrayInfo info = getInfo(in);\n af_dtype type = info.getType();\n switch(type) {\n case f64: *realVal = median<double>(in); break;\n case f32: *realVal = median<float >(in); break;\n case s32: *realVal = median<int >(in); break;\n case u32: *realVal = median<uint >(in); break;\n case s16: *realVal = median<short >(in); break;\n case u16: *realVal = median<ushort>(in); break;\n case u8: *realVal = median<uchar >(in); break;\n default : TYPE_ERROR(1, type);\n }\n }\n CATCHALL;\n return AF_SUCCESS;\n}\n\naf_err af_median(af_array* out, const af_array in, const dim_t dim)\n{\n try {\n ARG_ASSERT(2, (dim>=0 && dim<=0));\n\n af_array output = 0;\n ArrayInfo info = getInfo(in);\n af_dtype type = info.getType();\n switch(type) {\n case f64: output = median<double>(in, dim); break;\n case f32: output = median<float >(in, dim); break;\n case s32: output = median<int >(in, dim); break;\n case u32: output = median<uint >(in, dim); break;\n case s16: output = median<short >(in, dim); break;\n case u16: output = median<ushort>(in, dim); break;\n case u8: output = median<uchar >(in, dim); break;\n default : TYPE_ERROR(1, type);\n }\n std::swap(*out, output);\n }\n CATCHALL;\n return AF_SUCCESS;\n}\n<commit_msg>Memory leak fix in af_median_all<commit_after>\/*******************************************************\n * Copyright (c) 2014, ArrayFire\n * All rights reserved.\n *\n * This file is distributed under 3-clause BSD license.\n * The complete license agreement can be obtained at:\n * http:\/\/arrayfire.com\/licenses\/BSD-3-Clause\n ********************************************************\/\n\n#include <af\/dim4.hpp>\n#include <af\/defines.h>\n#include <af\/statistics.h>\n#include <af\/index.h>\n#include <af\/arith.h>\n#include <af\/data.h>\n#include <handle.hpp>\n#include <err_common.hpp>\n#include <backend.hpp>\n#include <sort.hpp>\n#include <math.hpp>\n#include <cast.hpp>\n\nusing namespace detail;\nusing af::dim4;\n\ntemplate<typename T>\nstatic double median(const af_array& in)\n{\n dim_t nElems = getInfo(in).elements();\n double mid = (nElems + 1) \/ 2;\n af_seq mdSpan[1]= {af_make_seq(mid-1, mid, 1)};\n dim4 dims(nElems, 1, 1, 1);\n\n af_array temp = 0;\n AF_CHECK(af_moddims(&temp, in, 1, dims.get()));\n const Array<T> input = getArray<T>(temp);\n\n Array<T> sortedArr = sort<T, true>(input, 0);\n\n af_array sarrHandle = getHandle<T>(sortedArr);\n\n double result;\n T resPtr[2];\n af_array res = 0;\n AF_CHECK(af_index(&res, sarrHandle, 1, mdSpan));\n AF_CHECK(af_get_data_ptr((void*)&resPtr, res));\n\n AF_CHECK(af_release_array(res));\n AF_CHECK(af_release_array(sarrHandle));\n AF_CHECK(af_release_array(temp));\n\n if (nElems % 2 == 1) {\n result = resPtr[0];\n } else {\n if (input.isFloating()) {\n result = division(resPtr[0] + resPtr[1], 2);\n } else {\n result = division((float)resPtr[0] + (float)resPtr[1], 2);\n }\n }\n\n return result;\n}\n\ntemplate<typename T>\nstatic af_array median(const af_array& in, const dim_t dim)\n{\n const Array<T> input = getArray<T>(in);\n Array<T> sortedIn = sort<T, true>(input, dim);\n\n int nElems = input.dims()[0];\n double mid = (nElems + 1) \/ 2;\n af_array left = 0;\n\n af_seq slices[4] = {af_span, af_span, af_span, af_span};\n slices[dim] = af_make_seq(mid-1.0, mid-1.0, 1.0);\n\n af_array sortedIn_handle = getHandle<T>(sortedIn);\n AF_CHECK(af_index(&left, sortedIn_handle, input.ndims(), slices));\n\n if (nElems % 2 == 1) {\n \/\/ mid-1 is our guy\n if (input.isFloating()) return left;\n\n \/\/ Return as floats for consistency\n af_array out;\n AF_CHECK(af_cast(&out, left, f32));\n AF_CHECK(af_release_array(left));\n AF_CHECK(af_release_array(sortedIn_handle));\n return out;\n } else {\n \/\/ ((mid-1)+mid)\/2 is our guy\n dim4 dims = input.dims();\n af_array right = 0;\n slices[dim] = af_make_seq(mid, mid, 1.0);\n\n AF_CHECK(af_index(&right, sortedIn_handle, dims.ndims(), slices));\n\n af_array sumarr = 0;\n af_array carr = 0;\n af_array result = 0;\n\n dim4 cdims = dim4(1, dims[1], dims[2], dims[3]);\n AF_CHECK(af_constant(&carr, 0.5, cdims.ndims(), cdims.get(), input.isDouble() ? f64 : f32));\n\n if (!input.isFloating()) {\n af_array lleft, rright;\n AF_CHECK(af_cast(&lleft, left, f32));\n AF_CHECK(af_cast(&rright, right, f32));\n AF_CHECK(af_release_array(left));\n AF_CHECK(af_release_array(right));\n left = lleft;\n right = rright;\n }\n\n AF_CHECK(af_add(&sumarr, left, right, false));\n AF_CHECK(af_mul(&result, sumarr, carr, false));\n\n AF_CHECK(af_release_array(left));\n AF_CHECK(af_release_array(right));\n AF_CHECK(af_release_array(sumarr));\n AF_CHECK(af_release_array(carr));\n AF_CHECK(af_release_array(sortedIn_handle));\n return result;\n }\n}\n\naf_err af_median_all(double *realVal, double *imagVal, const af_array in)\n{\n try {\n ArrayInfo info = getInfo(in);\n af_dtype type = info.getType();\n switch(type) {\n case f64: *realVal = median<double>(in); break;\n case f32: *realVal = median<float >(in); break;\n case s32: *realVal = median<int >(in); break;\n case u32: *realVal = median<uint >(in); break;\n case s16: *realVal = median<short >(in); break;\n case u16: *realVal = median<ushort>(in); break;\n case u8: *realVal = median<uchar >(in); break;\n default : TYPE_ERROR(1, type);\n }\n }\n CATCHALL;\n return AF_SUCCESS;\n}\n\naf_err af_median(af_array* out, const af_array in, const dim_t dim)\n{\n try {\n ARG_ASSERT(2, (dim>=0 && dim<=0));\n\n af_array output = 0;\n ArrayInfo info = getInfo(in);\n af_dtype type = info.getType();\n switch(type) {\n case f64: output = median<double>(in, dim); break;\n case f32: output = median<float >(in, dim); break;\n case s32: output = median<int >(in, dim); break;\n case u32: output = median<uint >(in, dim); break;\n case s16: output = median<short >(in, dim); break;\n case u16: output = median<ushort>(in, dim); break;\n case u8: output = median<uchar >(in, dim); break;\n default : TYPE_ERROR(1, type);\n }\n std::swap(*out, output);\n }\n CATCHALL;\n return AF_SUCCESS;\n}\n<|endoftext|>"} {"text":"<commit_before>\/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2003 Robert Osfield \n *\n * This library is open source and may be redistributed and\/or modified under \n * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or \n * (at your option) any later version. The full license is in LICENSE file\n * included with this distribution, and on the openscenegraph.org website.\n * \n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the \n * OpenSceneGraph Public License for more details.\n*\/\n\n#include <osgUtil\/Optimizer>\n#include <osgDB\/ReadFile>\n#include <osgProducer\/Viewer>\n\n#include <osg\/Material>\n#include <osg\/Geode>\n#include <osg\/BlendFunc>\n#include <osg\/Depth>\n#include <osg\/Projection>\n#include <osg\/PolygonOffset>\n#include <osg\/MatrixTransform>\n\n#include <osgText\/Text>\n\n\nosg::Node* createHUD()\n{\n osg::Geode* geode = new osg::Geode();\n \n std::string timesFont(\"fonts\/arial.ttf\");\n\n \/\/ turn lighting off for the text and disable depth test to ensure its always ontop.\n osg::StateSet* stateset = geode->getOrCreateStateSet();\n stateset->setMode(GL_LIGHTING,osg::StateAttribute::OFF);\n\n#if 0\n \/\/ to ensure the hud appears on top we can either use osg::Depth to force the \n \/\/ depth fragments to be placed at the front of the screen.\n stateset->setAttribute(new osg::Depth(osg::Depth::LESS,0.0,0.0001));\n#else\n \/\/ or disable depth test, and make sure that the hud is drawn after everything \n \/\/ else so that it always appears ontop.\n stateset->setMode(GL_DEPTH_TEST,osg::StateAttribute::OFF);\n stateset->setRenderBinDetails(11,\"RenderBin\");\n#endif\n\n osg::Vec3 position(150.0f,800.0f,0.0f);\n osg::Vec3 delta(0.0f,-120.0f,0.0f);\n\n {\n osgText::Text* text = new osgText::Text;\n geode->addDrawable( text );\n\n text->setFont(timesFont);\n text->setPosition(position);\n text->setText(\"Head Up Displays are simple :-)\");\n \n position += delta;\n } \n\n\n {\n osgText::Text* text = new osgText::Text;\n geode->addDrawable( text );\n\n text->setFont(timesFont);\n text->setPosition(position);\n text->setText(\"All you need to do is create your text in a subgraph.\");\n \n position += delta;\n } \n\n\n {\n osgText::Text* text = new osgText::Text;\n geode->addDrawable( text );\n\n text->setFont(timesFont);\n text->setPosition(position);\n text->setText(\"Disable depth test in this subgraph to ensure its always ontop.\");\n \n position += delta;\n } \n\n {\n osgText::Text* text = new osgText::Text;\n geode->addDrawable( text );\n\n text->setFont(timesFont);\n text->setPosition(position);\n text->setText(\"Then place an osg::Projection node above the subgraph\\nto create an orthographic projection.\");\n \n position += delta;\n } \n\n {\n osgText::Text* text = new osgText::Text;\n geode->addDrawable( text );\n\n text->setFont(timesFont);\n text->setPosition(position);\n text->setText(\"And add an osg::ModelViewMatrix set to ABSOLUTE_RF to ensure\\nit remains independent from any external model view matrices.\");\n \n position += delta;\n } \n \n \n \n {\n osg::BoundingBox bb;\n for(unsigned int i=0;i<geode->getNumDrawables();++i)\n {\n bb.expandBy(geode->getDrawable(i)->getBound());\n }\n\n osg::Geometry* geom = new osg::Geometry;\n\n osg::Vec3Array* vertices = new osg::Vec3Array;\n float depth = bb.zMin()-0.1;\n vertices->push_back(osg::Vec3(bb.xMin(),bb.yMax(),depth));\n vertices->push_back(osg::Vec3(bb.xMin(),bb.yMin(),depth));\n vertices->push_back(osg::Vec3(bb.xMax(),bb.yMin(),depth));\n vertices->push_back(osg::Vec3(bb.xMax(),bb.yMax(),depth));\n geom->setVertexArray(vertices);\n\n osg::Vec3Array* normals = new osg::Vec3Array;\n normals->push_back(osg::Vec3(0.0f,0.0f,1.0f));\n geom->setNormalArray(normals);\n geom->setNormalBinding(osg::Geometry::BIND_OVERALL);\n\n osg::Vec4Array* colors = new osg::Vec4Array;\n colors->push_back(osg::Vec4(1.0f,1.0,0.8f,0.2f));\n geom->setColorArray(colors);\n geom->setColorBinding(osg::Geometry::BIND_OVERALL);\n\n geom->addPrimitiveSet(new osg::DrawArrays(GL_QUADS,0,4));\n \n osg::StateSet* stateset = geom->getOrCreateStateSet();\n stateset->setMode(GL_BLEND,osg::StateAttribute::ON);\n \/\/stateset->setAttribute(new osg::PolygonOffset(1.0f,1.0f),osg::StateAttribute::ON);\n stateset->setRenderingHint(osg::StateSet::TRANSPARENT_BIN);\n\n geode->addDrawable(geom);\n }\n\n \/\/ create the hud.\n osg::MatrixTransform* modelview_abs = new osg::MatrixTransform;\n modelview_abs->setReferenceFrame(osg::Transform::ABSOLUTE_RF);\n modelview_abs->setMatrix(osg::Matrix::identity());\n modelview_abs->addChild(geode);\n\n osg::Projection* projection = new osg::Projection;\n projection->setMatrix(osg::Matrix::ortho2D(0,1280,0,1024));\n projection->addChild(modelview_abs);\n\n return projection;\n\n}\n\nint main( int argc, char **argv )\n{\n\n \/\/ use an ArgumentParser object to manage the program arguments.\n osg::ArgumentParser arguments(&argc,argv);\n \n \/\/ set up the usage document, in case we need to print out how to use this program.\n arguments.getApplicationUsage()->setDescription(arguments.getApplicationName()+\" is the example which demonstrates how to do Head Up Displays.\");\n arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+\" [options] [filename] ...\");\n arguments.getApplicationUsage()->addCommandLineOption(\"-h or --help\",\"Display this information\");\n \n\n \/\/ construct the viewer.\n osgProducer::Viewer viewer(arguments);\n\n \/\/ set up the value with sensible default event handlers.\n viewer.setUpViewer(osgProducer::Viewer::STANDARD_SETTINGS);\n\n \/\/ get details on keyboard and mouse bindings used by the viewer.\n viewer.getUsage(*arguments.getApplicationUsage());\n\n \/\/ if user request help write it out to cout.\n if (arguments.read(\"-h\") || arguments.read(\"--help\"))\n {\n arguments.getApplicationUsage()->write(std::cout);\n return 1;\n }\n\n \/\/ any option left unread are converted into errors to write out later.\n arguments.reportRemainingOptionsAsUnrecognized();\n\n \/\/ report any errors if they have occured when parsing the program aguments.\n if (arguments.errors())\n {\n arguments.writeErrorMessages(std::cout);\n return 1;\n }\n \n \/\/ read the scene from the list of file specified commandline args.\n osg::ref_ptr<osg::Node> scene = osgDB::readNodeFiles(arguments);\n\n osg::ref_ptr<osg::Group> group = new osg::Group;\n \n \/\/ add the HUD subgraph. \n if (scene.valid()) group->addChild(scene.get());\n group->addChild(createHUD());\n\n \/\/ set the scene to render\n viewer.setSceneData(group.get());\n\n \/\/ create the windows and run the threads.\n viewer.realize();\n\n while( !viewer.done() )\n {\n \/\/ wait for all cull and draw threads to complete.\n viewer.sync();\n\n \/\/ update the scene by traversing it with the the update visitor which will\n \/\/ call all node update callbacks and animations.\n viewer.update();\n \n \/\/ fire off the cull and draw traversals of the scene.\n viewer.frame();\n \n }\n \n \/\/ wait for all cull and draw threads to complete before exit.\n viewer.sync();\n \n return 0;\n}\n<commit_msg>Disabled culling on the aboslute transform to fix bug culling of hud.<commit_after>\/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2003 Robert Osfield \n *\n * This library is open source and may be redistributed and\/or modified under \n * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or \n * (at your option) any later version. The full license is in LICENSE file\n * included with this distribution, and on the openscenegraph.org website.\n * \n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the \n * OpenSceneGraph Public License for more details.\n*\/\n\n#include <osgUtil\/Optimizer>\n#include <osgDB\/ReadFile>\n#include <osgProducer\/Viewer>\n\n#include <osg\/Material>\n#include <osg\/Geode>\n#include <osg\/BlendFunc>\n#include <osg\/Depth>\n#include <osg\/Projection>\n#include <osg\/PolygonOffset>\n#include <osg\/MatrixTransform>\n\n#include <osgText\/Text>\n\n\nosg::Node* createHUD()\n{\n osg::Geode* geode = new osg::Geode();\n \n std::string timesFont(\"fonts\/arial.ttf\");\n\n \/\/ turn lighting off for the text and disable depth test to ensure its always ontop.\n osg::StateSet* stateset = geode->getOrCreateStateSet();\n stateset->setMode(GL_LIGHTING,osg::StateAttribute::OFF);\n\n#if 0\n \/\/ to ensure the hud appears on top we can either use osg::Depth to force the \n \/\/ depth fragments to be placed at the front of the screen.\n stateset->setAttribute(new osg::Depth(osg::Depth::LESS,0.0,0.0001));\n#else\n \/\/ or disable depth test, and make sure that the hud is drawn after everything \n \/\/ else so that it always appears ontop.\n stateset->setMode(GL_DEPTH_TEST,osg::StateAttribute::OFF);\n stateset->setRenderBinDetails(11,\"RenderBin\");\n#endif\n\n osg::Vec3 position(150.0f,800.0f,0.0f);\n osg::Vec3 delta(0.0f,-120.0f,0.0f);\n\n {\n osgText::Text* text = new osgText::Text;\n geode->addDrawable( text );\n\n text->setFont(timesFont);\n text->setPosition(position);\n text->setText(\"Head Up Displays are simple :-)\");\n \n position += delta;\n } \n\n\n {\n osgText::Text* text = new osgText::Text;\n geode->addDrawable( text );\n\n text->setFont(timesFont);\n text->setPosition(position);\n text->setText(\"All you need to do is create your text in a subgraph.\");\n \n position += delta;\n } \n\n\n {\n osgText::Text* text = new osgText::Text;\n geode->addDrawable( text );\n\n text->setFont(timesFont);\n text->setPosition(position);\n text->setText(\"Disable depth test in this subgraph to ensure its always ontop.\");\n \n position += delta;\n } \n\n {\n osgText::Text* text = new osgText::Text;\n geode->addDrawable( text );\n\n text->setFont(timesFont);\n text->setPosition(position);\n text->setText(\"Then place an osg::Projection node above the subgraph\\nto create an orthographic projection.\");\n \n position += delta;\n } \n\n {\n osgText::Text* text = new osgText::Text;\n geode->addDrawable( text );\n\n text->setFont(timesFont);\n text->setPosition(position);\n text->setText(\"And add an osg::ModelViewMatrix set to ABSOLUTE_RF to ensure\\nit remains independent from any external model view matrices.\");\n \n position += delta;\n } \n \n \n \n {\n osg::BoundingBox bb;\n for(unsigned int i=0;i<geode->getNumDrawables();++i)\n {\n bb.expandBy(geode->getDrawable(i)->getBound());\n }\n\n osg::Geometry* geom = new osg::Geometry;\n\n osg::Vec3Array* vertices = new osg::Vec3Array;\n float depth = bb.zMin()-0.1;\n vertices->push_back(osg::Vec3(bb.xMin(),bb.yMax(),depth));\n vertices->push_back(osg::Vec3(bb.xMin(),bb.yMin(),depth));\n vertices->push_back(osg::Vec3(bb.xMax(),bb.yMin(),depth));\n vertices->push_back(osg::Vec3(bb.xMax(),bb.yMax(),depth));\n geom->setVertexArray(vertices);\n\n osg::Vec3Array* normals = new osg::Vec3Array;\n normals->push_back(osg::Vec3(0.0f,0.0f,1.0f));\n geom->setNormalArray(normals);\n geom->setNormalBinding(osg::Geometry::BIND_OVERALL);\n\n osg::Vec4Array* colors = new osg::Vec4Array;\n colors->push_back(osg::Vec4(1.0f,1.0,0.8f,0.2f));\n geom->setColorArray(colors);\n geom->setColorBinding(osg::Geometry::BIND_OVERALL);\n\n geom->addPrimitiveSet(new osg::DrawArrays(GL_QUADS,0,4));\n \n osg::StateSet* stateset = geom->getOrCreateStateSet();\n stateset->setMode(GL_BLEND,osg::StateAttribute::ON);\n \/\/stateset->setAttribute(new osg::PolygonOffset(1.0f,1.0f),osg::StateAttribute::ON);\n stateset->setRenderingHint(osg::StateSet::TRANSPARENT_BIN);\n\n geode->addDrawable(geom);\n }\n\n \/\/ create the hud.\n osg::MatrixTransform* modelview_abs = new osg::MatrixTransform;\n modelview_abs->setReferenceFrame(osg::Transform::ABSOLUTE_RF);\n modelview_abs->setCullingActive(false);\n modelview_abs->setMatrix(osg::Matrix::identity());\n modelview_abs->addChild(geode);\n\n osg::Projection* projection = new osg::Projection;\n projection->setMatrix(osg::Matrix::ortho2D(0,1280,0,1024));\n projection->addChild(modelview_abs);\n\n return projection;\n\n}\n\nint main( int argc, char **argv )\n{\n\n \/\/ use an ArgumentParser object to manage the program arguments.\n osg::ArgumentParser arguments(&argc,argv);\n \n \/\/ set up the usage document, in case we need to print out how to use this program.\n arguments.getApplicationUsage()->setDescription(arguments.getApplicationName()+\" is the example which demonstrates how to do Head Up Displays.\");\n arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+\" [options] [filename] ...\");\n arguments.getApplicationUsage()->addCommandLineOption(\"-h or --help\",\"Display this information\");\n \n\n \/\/ construct the viewer.\n osgProducer::Viewer viewer(arguments);\n\n \/\/ set up the value with sensible default event handlers.\n viewer.setUpViewer(osgProducer::Viewer::STANDARD_SETTINGS);\n\n \/\/ get details on keyboard and mouse bindings used by the viewer.\n viewer.getUsage(*arguments.getApplicationUsage());\n\n \/\/ if user request help write it out to cout.\n if (arguments.read(\"-h\") || arguments.read(\"--help\"))\n {\n arguments.getApplicationUsage()->write(std::cout);\n return 1;\n }\n\n \/\/ any option left unread are converted into errors to write out later.\n arguments.reportRemainingOptionsAsUnrecognized();\n\n \/\/ report any errors if they have occured when parsing the program aguments.\n if (arguments.errors())\n {\n arguments.writeErrorMessages(std::cout);\n return 1;\n }\n \n \/\/ read the scene from the list of file specified commandline args.\n osg::ref_ptr<osg::Node> scene = osgDB::readNodeFiles(arguments);\n\n osg::ref_ptr<osg::Group> group = new osg::Group;\n \n \/\/ add the HUD subgraph. \n if (scene.valid()) group->addChild(scene.get());\n group->addChild(createHUD());\n\n \/\/ set the scene to render\n viewer.setSceneData(group.get());\n\n \/\/ create the windows and run the threads.\n viewer.realize();\n\n while( !viewer.done() )\n {\n \/\/ wait for all cull and draw threads to complete.\n viewer.sync();\n\n \/\/ update the scene by traversing it with the the update visitor which will\n \/\/ call all node update callbacks and animations.\n viewer.update();\n \n \/\/ fire off the cull and draw traversals of the scene.\n viewer.frame();\n \n }\n \n \/\/ wait for all cull and draw threads to complete before exit.\n viewer.sync();\n \n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>#include <signal.h>\t\t\t\t\/\/ for signal, SIGINT\n#include <zmq.h>\n#include \"zmq_packet.h\"\n#include <uuid.h>\n#include <ctime>\n#include \"util.h\"\n#include \"timesync.h\"\n#include \"h5analogwriter.h\"\n\nbool s_interrupted = false;\n\nstatic void s_signal_handler(int)\n{\n\ts_interrupted = true;\n\tprintf(\"\\n\");\n}\n\nstatic void s_catch_signals(void)\n{\n\tstruct sigaction action;\n\taction.sa_handler = s_signal_handler;\n\taction.sa_flags = 0;\n\tsigemptyset(&action.sa_mask);\n\tsigaction(SIGINT, &action, NULL);\n\tsigaction(SIGQUIT, &action, NULL);\n\tsigaction(SIGTERM, &action, NULL);\n}\n\nint main(int argc, char *argv[])\n{\n\t\/\/ h5bbsave [zmq_sub] [filename]\n\n\tif (argc < 3) {\n\t\tprintf(\"\\nh5bbsave - save broadband data to NWB (HDF5)\\n\");\n\t\tprintf(\"usage: h5bbsave [zmq_sub] [filename]\\n\\n\");\n\t\treturn 1;\n\t}\n\n\tstd::string zin = argv[1];\n\tstd::string fn\t= argv[2];\n\n\tprintf(\"ZMQ SUB: %s\\n\", zin.c_str());\n\tprintf(\"Filename: %s\\n\", fn.c_str());\n\tprintf(\"\\n\");\n\n\ts_catch_signals();\n\n\tTimeSyncClient *tsc = new TimeSyncClient(); \/\/ translates tk and ts\n\n\tH5AnalogWriter h5;\n\n\tzmq::context_t zcontext(1);\t\/\/ single zmq thread\n\n\tzmq::socket_t po8e_query_sock(zcontext, ZMQ_REQ);\n\tpo8e_query_sock.connect(\"ipc:\/\/\/tmp\/po8e-query.zmq\");\n\n\tu64 nnc; \/\/ num neural channels\n\tzmq::message_t msg(3);\n\tmemcpy(msg.data(), \"NNC\", 3);\n\tpo8e_query_sock.send(msg);\n\tmsg.rebuild();\n\ttry {\n\t\tpo8e_query_sock.recv(&msg);\n\t} catch (zmq::error_t &e) {\n\t\texit(1);\n\t}\n\tmemcpy(&nnc, (u64 *)msg.data(), sizeof(u64));\n\n\tstd::vector <std::string> names;\n\n\tfor (u64 ch=0; ch<nnc; ch++) {\n\t\t\/\/ NC : X : NAME\n\t\tmsg.rebuild(2);\n\t\tmemcpy(msg.data(), \"NC\", 2);\n\t\tpo8e_query_sock.send(msg, ZMQ_SNDMORE);\n\t\tmsg.rebuild(sizeof(u64));\n\t\tmemcpy(msg.data(), &ch, sizeof(u64));\n\t\tpo8e_query_sock.send(msg, ZMQ_SNDMORE);\n\t\tmsg.rebuild(4);\n\t\tmemcpy(msg.data(), \"NAME\", 4);\n\t\tpo8e_query_sock.send(msg);\n\t\tmsg.rebuild();\n\t\tpo8e_query_sock.recv(&msg);\n\t\tnames.push_back(std::string((const char *)msg.data(), msg.size()));\n\t}\n\n\tsize_t max_str = 0;\n\tfor (auto &x : names) {\n\t\tmax_str = max_str > x.size() ? max_str : x.size();\n\t}\n\tauto name = new char[max_str*names.size()];\n\tfor (size_t i=0; i<names.size(); i++) {\n\t\tstrncpy(&name[i*max_str], names[i].c_str(), names[i].size());\n\t}\n\n\tuuid_t u;\n\tuuid_generate(u);\n\tchar uu[37];\n\tuuid_unparse(u, uu);\n\n\ttime_t t_create;\n\ttime(&t_create);\n\tchar create_date[sizeof(\"YYYY-MM-DDTHH:MM:SSZ\")];\n\tstrftime(create_date, sizeof(create_date), \"%FT%TZ\", gmtime(&t_create));\n\n\th5.open(fn.c_str(), nnc);\n\th5.setVersion();\n\th5.setUUID(uu);\n\th5.setFileCreateDate(create_date);\n\th5.setSessionDescription(\"broadband data\");\n\th5.setMetaData(1.0\/3276700, name, max_str);\n\n\tdelete[] name;\n\n\tzmq::socket_t socket_in(zcontext, ZMQ_SUB);\n\tsocket_in.connect(zin.c_str());\n\tsocket_in.setsockopt(ZMQ_SUBSCRIBE, \"\", 0);\t\/\/ subscribe to everything\n\n\t\/\/ init poll set\n\tzmq::pollitem_t items [] = {\n\t\t{ socket_in, \t0, ZMQ_POLLIN, 0 }\n\t};\n\n\tint waiter = 0;\n\tint counter = 0;\n\tstd::vector<const char *> spinner;\n\tspinner.emplace_back(\">>> >>>\");\n\tspinner.emplace_back(\" >>> >>\");\n\tspinner.emplace_back(\" >>> >\");\n\tspinner.emplace_back(\" >>> \");\n\tspinner.emplace_back(\" >>> \");\n\tspinner.emplace_back(\"> >>> \");\n\tspinner.emplace_back(\">> >>> \");\n\n\tsize_t zin_n = zin.find_last_of(\"\/\");\n\n\twhile (!s_interrupted) {\n\n\t\ttry {\n\t\t\tzmq::poll(&items[0], 1, -1); \/\/ -1 means block\n\t\t} catch (zmq::error_t &e) {}\n\n\t\tif (items[0].revents & ZMQ_POLLIN) {\n\n\t\t\tsocket_in.recv(&msg);\n\n\t\t\tchar *ptr = (char *)msg.data();\n\n\t\t\tu64 nc, ns;\n\n\t\t\t\/\/ parse message\n\t\t\tmemcpy(&nc, ptr+0, sizeof(u64));\n\t\t\tmemcpy(&ns, ptr+8, sizeof(u64));\n\n\t\t\tauto tk \t= new i64[ns];\n\t\t\tauto ts \t= new double[ns];\n\n\t\t\tmemcpy(tk, ptr+16, sizeof(i64));\n\n\t\t\tts[0] = tsc->getTime(tk[0]);\n\t\t\tfor (size_t i=1; i < ns; i++) {\n\t\t\t\ttk[i] = tk[i-1] + 1;\n\t\t\t\tts[i] = tsc->getTime(tk[i]);\n\t\t\t}\n\n\t\t\tauto f = new float[nc*ns];\n\t\t\tmemcpy(f, ptr+24, nc*ns*sizeof(float));\n\n\t\t\tauto x = new i16[nc*ns];\n\t\t\tfor (size_t i=0; i<nc; i++) {\n\t\t\t\tfor (size_t k=0; k<ns; k++) {\n\t\t\t\t\t\/\/ note that we transpose on the fly here to NWB format\n\t\t\t\t\tx[k*nc+i] = (i16)(f[i*ns+k] * 3276700 \/ 1e6); \/\/ pack\n\t\t\t\t}\n\t\t\t}\n\t\t\tdelete[] f;\n\n\t\t\th5.write(nc, ns, tk, ts, x); \/\/ frees memory when done\n\n\t\t\tif (waiter % 200 == 0) {\n\t\t\t\ttime_t now;\n\t\t\t\ttime(&now);\n\t\t\t\tdouble sec = difftime(now, t_create);\n\t\t\t\tint min = sec \/ 60;\n\t\t\t\tint hr = min \/ 60;\n\t\t\t\tprintf(\" [%s]%s[%s] (%02d:%02d:%02d)\\r\",\n\t\t\t\t zin.substr(zin_n+1).c_str(),\n\t\t\t\t spinner[counter % spinner.size()],\n\t\t\t\t fn.c_str(),\n\t\t\t\t hr,\n\t\t\t\t min % 60,\n\t\t\t\t int(sec) % 60);\n\t\t\t\tfflush(stdout);\n\t\t\t\tcounter++;\n\t\t\t}\n\t\t\twaiter++;\n\n\t\t}\n\n\t}\n\n\th5.close();\n\n\tdelete tsc;\n\n}<commit_msg>i think i have h5bbsave compiling etc again<commit_after>#include <signal.h>\t\t\t\t\/\/ for signal, SIGINT\n#include <zmq.h>\n#include \"zmq_packet.h\"\n#include <uuid.h>\n#include <ctime>\n#include \"util.h\"\n#include \"timesync.h\"\n#include \"h5analogwriter.h\"\n\nbool s_interrupted = false;\nstd::vector <void *> g_socks;\n\nstatic void s_signal_handler(int)\n{\n\ts_interrupted = true;\n}\n\nstatic void s_catch_signals(void)\n{\n\tstruct sigaction action;\n\taction.sa_handler = s_signal_handler;\n\taction.sa_flags = 0;\n\tsigemptyset(&action.sa_mask);\n\tsigaction(SIGINT, &action, NULL);\n\tsigaction(SIGQUIT, &action, NULL);\n\tsigaction(SIGTERM, &action, NULL);\n}\n\nstatic void die(void *ctx, int status)\n{\n\ts_interrupted = true;\n\tfor (auto &sock : g_socks) {\n\t\tzmq_close(sock);\n\t}\n\tzmq_ctx_destroy(ctx);\n\texit(status);\n}\n\nint main(int argc, char *argv[])\n{\n\t\/\/ h5bbsave [zmq_sub] [filename]\n\n\tif (argc < 3) {\n\t\tprintf(\"\\nh5bbsave - save broadband data to NWB (HDF5)\\n\");\n\t\tprintf(\"usage: h5bbsave [zmq_sub] [filename]\\n\\n\");\n\t\treturn 1;\n\t}\n\n\tstd::string zin = argv[1];\n\tstd::string fn\t= argv[2];\n\n\tdebug(\"ZMQ SUB: %s\", zin.c_str());\n\tdebug(\"Filename: %s\", fn.c_str());\n\n\ts_catch_signals();\n\n\txdgHandle xdg;\n\txdgInitHandle(&xdg);\n\tchar *confpath = xdgConfigFind(\"spk\/spk.rc\", &xdg);\n\tchar *tmp = confpath;\n\t\/\/ confpath is \"string1\\0string2\\0string3\\0\\0\"\n\n\tluaConf conf;\n\n\twhile (*tmp) {\n\t\tconf.loadConf(tmp);\n\t\ttmp += strlen(tmp) + 1;\n\t}\n\tif (confpath)\n\t\tfree(confpath);\n\txdgWipeHandle(&xdg);\n\n\tstd::string zq = \"ipc:\/\/\/tmp\/query.zmq\";\n\tconf.getString(\"spk.query_socket\", zq);\n\n\tTimeSyncClient *tsc = new TimeSyncClient(); \/\/ translates tk and ts\n\n\tH5AnalogWriter h5;\n\n\tvoid *zcontext = zmq_ctx_new();\n\tif (zcontext == NULL) {\n\t\terror(\"zmq: could not create context\");\n\t\treturn 1;\n\t}\n\n\t\/\/ we don't need 1024 sockets\n\tif (zmq_ctx_set(zcontext, ZMQ_MAX_SOCKETS, 64) != 0) {\n\t\terror(\"zmq: could not set max sockets\");\n\t\tdie(zcontext, 1);\n\t}\n\n\tvoid *query_sock = zmq_socket(zcontext, ZMQ_REQ);\n\tif (query_sock == NULL) {\n\t\terror(\"zmq: could not create socket\");\n\t\tdie(zcontext, 1);\n\t}\n\tg_socks.push_back(query_sock);\n\n\tif (zmq_connect(query_sock, zq.c_str()) != 0) {\n\t\terror(\"zmq: could not connect to socket\");\n\t\tdie(zcontext, 1);\n\t}\n\n\tu64 nnc; \/\/ num neural channels\n\tzmq_send(query_sock, \"NNC\", 3, 0);\n\tif (zmq_recv(query_sock, &nnc, sizeof(u64), 0) == -1) {\n\t\terror(\"zmq: could not recv from query sock\");\n\t\tdie(zcontext, 1);\n\t}\n\n\tstd::vector <std::string> names;\n\n\tfor (u64 ch=0; ch<nnc; ch++) {\n\t\t\/\/ NC : X : NAME\n\t\tzmq_send(query_sock, \"NC\", 2, ZMQ_SNDMORE);\n\t\tzmq_send(query_sock, &ch, sizeof(u64), ZMQ_SNDMORE);\n\t\tzmq_send(query_sock, \"NAME\", 4, 0);\n\n\t\tzmq_msg_t msg;\n\t\tzmq_msg_init(&msg);\n\t\tzmq_msg_recv(&msg, query_sock, 0);\n\n\t\tnames.push_back(std::string((const char *)zmq_msg_data(&msg), zmq_msg_size(&msg)));\n\t\tzmq_msg_close(&msg);\n\n\t}\n\n\tsize_t max_str = 0;\n\tfor (auto &x : names) {\n\t\tmax_str = max_str > x.size() ? max_str : x.size();\n\t}\n\tauto name = new char[max_str*names.size()];\n\tfor (size_t i=0; i<names.size(); i++) {\n\t\tstrncpy(&name[i*max_str], names[i].c_str(), names[i].size());\n\t}\n\n\tuuid_t u;\n\tuuid_generate(u);\n\tchar uu[37];\n\tuuid_unparse(u, uu);\n\n\ttime_t t_create;\n\ttime(&t_create);\n\tchar create_date[sizeof(\"YYYY-MM-DDTHH:MM:SSZ\")];\n\tstrftime(create_date, sizeof(create_date), \"%FT%TZ\", gmtime(&t_create));\n\n\th5.open(fn.c_str(), nnc);\n\th5.setVersion();\n\th5.setUUID(uu);\n\th5.setFileCreateDate(create_date);\n\th5.setSessionDescription(\"broadband data\");\n\th5.setMetaData(1.0\/3276700, name, max_str);\n\n\tdelete[] name;\n\n\tvoid *socket_in = zmq_socket(zcontext, ZMQ_SUB);\n\tif (socket_in == NULL) {\n\t\terror(\"zmq: could not create socket\");\n\t\tdie(zcontext, 1);\n\t}\n\tg_socks.push_back(socket_in);\n\n\tif (zmq_connect(socket_in, zin.c_str()) != 0) {\n\t\terror(\"zmq: could not connect to socket\");\n\t\tdie(zcontext, 1);\n\t}\n\t\/\/ subscribe to everything\n\tif (zmq_setsockopt(socket_in, ZMQ_SUBSCRIBE, \"\", 0) != 0) {\n\t\terror(\"zmq: could not set socket options\");\n\t\tdie(zcontext, 1);\n\t}\n\n\tzmq_pollitem_t items [] = {\n\t\t{ socket_in, \t0, ZMQ_POLLIN, 0 }\n\t};\n\n\tint waiter = 0;\n\tint counter = 0;\n\tstd::vector<const char *> spinner;\n\tspinner.emplace_back(\">>> >>>\");\n\tspinner.emplace_back(\" >>> >>\");\n\tspinner.emplace_back(\" >>> >\");\n\tspinner.emplace_back(\" >>> \");\n\tspinner.emplace_back(\" >>> \");\n\tspinner.emplace_back(\"> >>> \");\n\tspinner.emplace_back(\">> >>> \");\n\n\tsize_t zin_n = zin.find_last_of(\"\/\");\n\n\twhile (!s_interrupted) {\n\n\t\tif (zmq_poll(items, 1, -1) == -1) {\n\t\t\tbreak;\n\t\t}\n\n\t\tif (items[0].revents & ZMQ_POLLIN) {\n\n\t\t\tzmq_msg_t header;\n\t\t\tzmq_msg_init(&header);\n\t\t\tzmq_msg_recv(&header, socket_in, 0);\n\t\t\tsize_t nh = zmq_msg_size(&header);\n\t\t\tzmq_neural_header *p = (zmq_neural_header *)zmq_msg_data(&header);\n\n\t\t\tu64 nc = p->nc;\n\t\t\tu64 ns = p->ns;\n\n\t\t\tauto tk = new i64[ns];\n\t\t\tauto ts = new double[ns];\n\n\t\t\ttk[0] = p->tk;\n\t\t\tts[0] = tsc->getTime(tk[0]);\n\t\t\tfor (size_t i=1; i<ns; i++) {\n\t\t\t\ttk[i] = tk[i-1] + 1;\n\t\t\t\tts[i] = tsc->getTime(tk[i]);\n\t\t\t}\n\n\t\t\tzmq_msg_t body;\n\t\t\tzmq_msg_init(&body);\n\t\t\tzmq_msg_recv(&body, socket_in, 0);\n\t\t\tsize_t nb = zmq_msg_size(&body);\n\t\t\tfloat *f = (float*)zmq_msg_data(&body);\n\n\t\t\tauto x = new i16[nc*ns];\n\t\t\tfor (size_t i=0; i<nc; i++) {\n\t\t\t\tfor (size_t k=0; k<ns; k++) {\n\t\t\t\t\t\/\/ note that we transpose on the fly here to NWB format\n\t\t\t\t\tx[k*nc+i] = (i16)(f[i*ns+k] * 3276700 \/ 1e6); \/\/ pack\n\t\t\t\t}\n\t\t\t}\n\n\t\t\th5.write(nc, ns, tk, ts, x); \/\/ frees memory when done\n\n\t\t\tzmq_msg_close(&header);\n\t\t\tzmq_msg_close(&body);\n\n\t\t\tif (waiter % 200 == 0) {\n\t\t\t\ttime_t now;\n\t\t\t\ttime(&now);\n\t\t\t\tdouble sec = difftime(now, t_create);\n\t\t\t\tint min = sec \/ 60;\n\t\t\t\tint hr = min \/ 60;\n\t\t\t\tprintf(\" [%s]%s[%s] (%02d:%02d:%02d)\\r\",\n\t\t\t\t zin.substr(zin_n+1).c_str(),\n\t\t\t\t spinner[counter % spinner.size()],\n\t\t\t\t fn.c_str(),\n\t\t\t\t hr,\n\t\t\t\t min % 60,\n\t\t\t\t int(sec) % 60);\n\t\t\t\tfflush(stdout);\n\t\t\t\tcounter++;\n\t\t\t}\n\t\t\twaiter++;\n\n\t\t}\n\n\t}\n\n\th5.close();\n\n\tdelete tsc;\n\n\tdie(zcontext, 0);\n\n}<|endoftext|>"} {"text":"<commit_before>#ifndef ___INANITY_GRAPHICS_EDITABLE_GEOMETRY_H___\n#define ___INANITY_GRAPHICS_EDITABLE_GEOMETRY_H___\n\n#include \"Geometry.hpp\"\n#include \"GeometryFormat.hpp\"\n#include <vector>\n#include <map>\n#include <set>\n#include <algorithm>\n\nBEGIN_INANITY_GRAPHICS\n\n\/\/\/ Класс типизированной редактируемой геометрии.\n\/**\nРазличные процедуры выдвигают различные требования к шаблонным параметрам.\nОни написаны в комментариях.\n*\/\ntemplate <typename Vertex, typename Index = unsigned short>\nclass EditableGeometry : public Object\n{\nprivate:\n\tstd::vector<Vertex> vertices;\n\tstd::vector<Index> indices;\n\npublic:\n\t\/\/\/ Создать типизированную геометрию.\n\tEditableGeometry(const std::vector<Vertex>& vertices, const std::vector<Index>& indices)\n\t\t: vertices(vertices), indices(indices) {}\n\n\t\/\/\/ Создать типизированную геометрию из неиндексированных вершин.\n\tEditableGeometry(const std::vector<Vertex>& vertices) : vertices(vertices)\n\t{\n\t\tindices.resize(vertices.size());\n\t\tfor(size_t i = 0; i < indices.size(); ++i)\n\t\t\tindices[i] = i;\n\t}\n\n\t\/\/\/ Получить вершины.\n\tstd::vector<Vertex>& GetVertices()\n\t{\n\t\treturn vertices;\n\t}\n\n\t\/\/\/ Получить индексы.\n\tstd::vector<Index>& GetIndices()\n\t{\n\t\treturn indices;\n\t}\n\n\t\/\/\/ Преобразовать тип индексов.\n\ttemplate <typename ToIndex>\n\tptr<EditableGeometry<Vertex, ToIndex> > CastIndices() const\n\t{\n\t\treturn NEW(EditableGeometry<Vertex, ToIndex>(vertices, std::vector<ToIndex>(indices.begin(), indices.end())));\n\t}\n\n\t\/\/\/ Сериализовать геометрию.\n\tvoid Serialize(ptr<OutputStream> outputStream, const String& formatFileName)\n\t{\n\t\t\/\/ проверить, являются ли индексы последовательными числами\n\t\t\/\/ тогда геометрию можно будет сериализовать без индексов\n\t\tbool needIndices = false;\n\t\tfor(size_t i = 0; i < indices.size(); ++i)\n\t\t\tif(indices[i] != i)\n\t\t\t{\n\t\t\t\tneedIndices = true;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\tptr<StreamWriter> writer = NEW(StreamWriter(outputStream));\n\n\t\twriter->WriteShortly(vertices.size());\n\t\twriter->WriteShortly(sizeof(Vertex));\n\t\twriter->WriteShortly(needIndices ? indices.size() : 0);\n\t\tif(needIndices)\n\t\t\twriter->WriteShortly(sizeof(Index));\n\t\twriter->WriteString(formatFileName);\n\t\twriter->Write(&*vertices.begin(), vertices.size() * sizeof(Vertex));\n\t\tif(needIndices)\n\t\t\twriter->Write(&*indices.begin(), indices.size() * sizeof(Index));\n\t}\n\n\tptr<File> SerializeVertices() const\n\t{\n\t\tptr<File> file = NEW(MemoryFile(vertices.size() * sizeof(Vertex)));\n\t\tmemcpy(file->GetData(), &*vertices.begin(), vertices.size() * sizeof(Vertex));\n\t\treturn file;\n\t}\n\n\tptr<File> SerializeIndices() const\n\t{\n\t\tptr<File> file = NEW(MemoryFile(indices.size() * sizeof(Index)));\n\t\tmemcpy(file->GetData(), &*indices.begin(), indices.size() * sizeof(Index));\n\t\treturn file;\n\t}\n\n\t\/\/\/ Оптимизировать геометрию\n\t\/** Выполняется объединение одинаковых вершин, с заданием соответствующих индексов.\n\tДля типа Vertex требуется наличие operator< и operator==.\n\t*\/\n\tptr<EditableGeometry> Optimize() const\n\t{\n\t\t\/\/скопировать вершины в новый массив с их индексами\n\t\tstd::vector<std::pair<Vertex, size_t> > newVertices(vertices.size());\n\t\tfor(size_t i = 0; i < vertices.size(); ++i)\n\t\t\tnewVertices[i] = std::make_pair(vertices[i], i);\n\t\t\/\/отсортировать их\n\t\tstd::sort(newVertices.begin(), newVertices.end());\n\t\t\/\/выполнить объединение одинаковых вершин\n\t\t\/\/заодно построить массив преобразования индексов\n\t\tstd::vector<Vertex> resultVertices;\n\t\tstd::vector<size_t> indexMap(vertices.size());\n\t\tresultVertices.reserve(vertices.size());\n\t\tfor(size_t i = 0; i < newVertices.size(); )\n\t\t{\n\t\t\tsize_t j;\n\t\t\tfor(j = i + 1; j < newVertices.size() && newVertices[i].first == newVertices[j].first; ++j);\n\t\t\tsize_t newIndex = resultVertices.size();\n\t\t\tresultVertices.push_back(newVertices[i].first);\n\t\t\tfor(; i < j; ++i)\n\t\t\t\tindexMap[newVertices[i].second] = newIndex;\n\t\t}\n\t\t\/\/скопировать индексы в новый массив\n\t\tstd::vector<Index> resultIndices(indices.size());\n\t\t\/\/и преобразовать их\n\t\tfor(size_t i = 0; i < resultIndices.size(); ++i)\n\t\t\tresultIndices[i] = indexMap[indices[i]];\n\t\treturn NEW(EditableGeometry(resultVertices, resultIndices));\n\t}\n\n\t\/\/\/ Добавить в геометрию тангенту и бинормаль.\n\ttemplate <typename OutputVertex>\n\tptr<EditableGeometry<OutputVertex, Index> > CreateTangentAndBinormal() const\n\t{\n\t\t\/\/ликвидировать индексы\n\t\tstd::vector<OutputVertex> outputVertices(indices.size());\n\t\tfor(size_t i = 0; i < outputVertices.size(); ++i)\n\t\t{\n\t\t\tconst Vertex& vertex = vertices[indices[i]];\n\t\t\tOutputVertex& outputVertex = outputVertices[i];\n\t\t\toutputVertex.position = vertex.position;\n\t\t\toutputVertex.texcoord = vertex.texcoord;\n\t\t}\n\n\t\t\/\/обработать треугольники и вычислить для каждого нормали\n\t\tfor(size_t i = 0; i < outputVertices.size(); i += 3)\n\t\t{\n\t\t\t\/\/получить указатель на три вершины\n\t\t\tOutputVertex* v = &*(outputVertices.begin() + i);\n\n\t\t\t\/\/вычислить нормаль\n\t\t\tfloat3 temp;\n\t\t\tfloat3 normal;\n\t\t\tD3DXVec3Cross(&temp, &(v[2].position - v[0].position), &(v[1].position - v[0].position));\n\t\t\tD3DXVec3Normalize(&normal, &temp);\n\n\t\t\t\/\/вычислить касательную и бинормаль\n\t\t\tfloat3 tangent, binormal;\n\t\t\t{\n\t\t\t\t\/\/для этого делаем матрицу\n\t\t\t\tfloat4x4 m, m1;\n\t\t\t\tm._11 = v[1].position.x - v[0].position.x;\n\t\t\t\tm._12 = v[1].position.y - v[0].position.y;\n\t\t\t\tm._13 = v[1].position.z - v[0].position.z;\n\t\t\t\tm._14 = 0;\n\t\t\t\tm._21 = v[2].position.x - v[0].position.x;\n\t\t\t\tm._22 = v[2].position.y - v[0].position.y;\n\t\t\t\tm._23 = v[2].position.z - v[0].position.z;\n\t\t\t\tm._24 = 0;\n\t\t\t\tm._31 = normal.x;\n\t\t\t\tm._32 = normal.y;\n\t\t\t\tm._33 = normal.z;\n\t\t\t\tm._34 = 0;\n\t\t\t\tm._41 = 0;\n\t\t\t\tm._42 = 0;\n\t\t\t\tm._43 = 0;\n\t\t\t\tm._44 = 1;\n\t\t\t\t\/\/обращаем её\n\t\t\t\tD3DXMatrixInverse(&m1, NULL, &m);\n\t\t\t\t\/\/и умножаем её сначала на один вектор (для касательной)\n\t\t\t\tD3DXVec3TransformCoord(&tangent, &float3(v[1].texcoord.x - v[0].texcoord.x, v[2].texcoord.x - v[0].texcoord.x, 0), &m1);\n\t\t\t\t\/\/а затем на другой (для бинормали)\n\t\t\t\tD3DXVec3TransformCoord(&binormal, &float3(v[1].texcoord.y - v[0].texcoord.y, v[2].texcoord.y - v[0].texcoord.y, 0), &m1);\n\t\t\t}\n\n\t\t\t\/\/записать вектора в вершины\n\t\t\tfor(size_t j = 0; j < 3; ++j)\n\t\t\t{\n\t\t\t\tv[j].normal = normal;\n\t\t\t\tv[j].tangent = tangent;\n\t\t\t\tv[j].binormal = binormal;\n\t\t\t}\n\t\t}\n\n\t\t\/\/вернуть геометрию\n\t\treturn NEW((EditableGeometry<OutputVertex, Index>(outputVertices)));\n\t}\n\n\t\/\/\/ Добавить в геометрию трансформации для прямого bump'а.\n\ttemplate <typename OutputVertex>\n\tptr<EditableGeometry<OutputVertex, Index> > CreateBumpTransformations() const\n\t{\n\t\t\/\/ликвидировать индексы\n\t\tstd::vector<OutputVertex> outputVertices(indices.size());\n\t\tfor(size_t i = 0; i < outputVertices.size(); ++i)\n\t\t{\n\t\t\tconst Vertex& vertex = vertices[indices[i]];\n\t\t\tOutputVertex& outputVertex = outputVertices[i];\n\t\t\toutputVertex.position = vertex.position;\n\t\t\toutputVertex.texcoord = vertex.texcoord;\n\t\t}\n\n\t\t\/\/обработать треугольники\n\t\tfor(size_t i = 0; i < outputVertices.size(); i += 3)\n\t\t{\n\t\t\t\/\/получить указатель на три вершины\n\t\t\tOutputVertex* v = &*(outputVertices.begin() + i);\n\n\t\t\t\/\/вычислить нормаль\n\t\t\tfloat3 temp;\n\t\t\tfloat3 normal;\n\t\t\tD3DXVec3Cross(&temp, &(v[2].position - v[0].position), &(v[1].position - v[0].position));\n\t\t\tD3DXVec3Normalize(&normal, &temp);\n\n\t\t\t\/\/вычислить два базовых мировых вектора\n\t\t\tfloat3 Ba, Ca;\n\t\t\ttemp = v[1].position - v[0].position;\n\t\t\tD3DXVec3Normalize(&Ba, &temp);\n\t\t\ttemp = v[2].position - v[0].position;\n\t\t\tD3DXVec3Normalize(&Ca, &temp);\n\t\t\t\/\/и два базовых нормальных вектора\n\t\t\tfloat2 ba, ca;\n\t\t\tfloat2 temp2;\n\t\t\ttemp2 = v[1].texcoord - v[0].texcoord;\n\t\t\tD3DXVec2Normalize(&ba, &temp2);\n\t\t\ttemp2 = v[2].texcoord - v[0].texcoord;\n\t\t\tD3DXVec2Normalize(&ca, &temp2);\n\t\t\tfloat3 transform1, transform2, transform3;\n\t\t\t{\n\t\t\t\t\/\/для этого делаем матрицу\n\t\t\t\tfloat4x4 m, m1;\n\t\t\t\tm._11 = ba.x;\n\t\t\t\tm._12 = ba.y;\n\t\t\t\tm._13 = 0;\n\t\t\t\tm._14 = 0;\n\t\t\t\tm._21 = ca.x;\n\t\t\t\tm._22 = ca.y;\n\t\t\t\tm._23 = 0;\n\t\t\t\tm._24 = 0;\n\t\t\t\tm._31 = 0;\n\t\t\t\tm._32 = 0;\n\t\t\t\tm._33 = 1;\n\t\t\t\tm._34 = 0;\n\t\t\t\tm._41 = 0;\n\t\t\t\tm._42 = 0;\n\t\t\t\tm._43 = 0;\n\t\t\t\tm._44 = 1;\n\t\t\t\t\/\/обращаем её\n\t\t\t\tD3DXMatrixInverse(&m1, NULL, &m);\n\t\t\t\t\/\/делаем другую матрицу\n\t\t\t\tfloat4x4 m2;\n\t\t\t\tm2._11 = Ba.x;\n\t\t\t\tm2._12 = Ba.y;\n\t\t\t\tm2._13 = Ba.z;\n\t\t\t\tm2._14 = 0;\n\t\t\t\tm2._21 = Ca.x;\n\t\t\t\tm2._22 = Ca.y;\n\t\t\t\tm2._23 = Ca.z;\n\t\t\t\tm2._24 = 0;\n\t\t\t\tm2._31 = normal.x;\n\t\t\t\tm2._32 = normal.y;\n\t\t\t\tm2._33 = normal.z;\n\t\t\t\tm2._34 = 0;\n\t\t\t\tm2._41 = 0;\n\t\t\t\tm2._42 = 0;\n\t\t\t\tm2._43 = 0;\n\t\t\t\tm2._44 = 1;\n\t\t\t\t\/\/умножаем матрицы\n\t\t\t\tm = m1 * m2;\n\n\t\t\t\t\/\/получаем трансформации\n\t\t\t\ttransform1 = float3(m._11, m._21, m._31);\n\t\t\t\ttransform2 = float3(m._12, m._22, m._32);\n\t\t\t\ttransform3 = float3(m._13, m._23, m._33);\n\t\t\t}\n\n\t\t\t\/\/записать вектора в вершины\n\t\t\tfor(size_t j = 0; j < 3; ++j)\n\t\t\t{\n\t\t\t\tv[j].transform1 = transform1;\n\t\t\t\tv[j].transform2 = transform2;\n\t\t\t\tv[j].transform3 = transform3;\n\t\t\t}\n\t\t}\n\n\t\t\/\/вернуть геометрию (макрос NEW никак не хочет компилироваться)\n\t\treturn new EditableGeometry<OutputVertex, Index>(outputVertices);\n\t}\n\n\t\/\/структура из трех векторов\n\tstruct ThreeVectors\n\t{\n\t\tfloat3 a;\n\t\tfloat3 b;\n\t\tfloat3 c;\n\n\t\tThreeVectors(const float3& a = float3(0, 0, 0), const float3& b = float3(0, 0, 0), const float3& c = float3(0, 0, 0))\n\t\t\t: a(a), b(b), c(c)\n\t\t{\n\t\t}\n\n\t\tvoid operator+=(const ThreeVectors& v)\n\t\t{\n\t\t\ta += v.a;\n\t\t\tb += v.b;\n\t\t\tc += v.c;\n\t\t}\n\n\t\tvoid operator\/=(const float v)\n\t\t{\n\t\t\ta \/= v;\n\t\t\tb \/= v;\n\t\t\tc \/= v;\n\t\t}\n\t};\n\t\/\/сравниватель векторов\n\tstruct Float3Comparer\n\t{\n\t\tbool operator()(const float3& a, const float3& b) const\n\t\t{\n\t\t\tif(a.x < b.x - GraphicsMath::eps) return true;\n\t\t\tif(b.x < a.x - GraphicsMath::eps) return false;\n\t\t\tif(a.y < b.y - GraphicsMath::eps) return true;\n\t\t\tif(b.y < a.y - GraphicsMath::eps) return false;\n\t\t\treturn a.z < b.z - GraphicsMath::eps;\n\t\t}\n\t};\n\t\/\/сравниватель троек векторов; используется только для разделения различных\n\tstruct ThreeVectorsComparer\n\t{\n\t\tFloat3Comparer comparer;\n\t\tbool operator()(const ThreeVectors& a, const ThreeVectors& b) const\n\t\t{\n\t\t\tif(comparer(a.a, b.a)) return true;\n\t\t\tif(comparer(b.a, a.a)) return false;\n\t\t\tif(comparer(a.b, b.b)) return true;\n\t\t\tif(comparer(b.b, a.b)) return false;\n\t\t\treturn comparer(a.c, b.c);\n\t\t}\n\t};\n\n\t\/\/\/ Сгладить геометрию с bump'ом.\n\t\/** Выполняется усреднение нормалей, тангент и бинормалей. *\/\n\ttemplate <\n\t\tfloat3 Vertex::*transform1,\n\t\tfloat3 Vertex::*transform2,\n\t\tfloat3 Vertex::*transform3\n\t>\n\tptr<EditableGeometry> SmoothBump() const\n\t{\n\t\t\/* Алгоритм заключается в том, чтобы объединить вершины,\n\t\tнаходящиеся в одной точке, и усреднить в этих вершинах\n\t\tкомпоненты. При этом при усреднении несколько одинаковых векторов\n\t\tсчитаются за один, чтобы не допускать искажение.\n\t\t*\/\n\t\t\/\/карта по векторам, содержащая на каждый вектор сумму векторов - трансформаций\n\t\tstd::map<float3, std::set<ThreeVectors, ThreeVectorsComparer>, Float3Comparer> vectors;\n\n\t\t\/\/собрать информацию\n\t\tfor(size_t i = 0; i < indices.size(); ++i)\n\t\t{\n\t\t\tsize_t j = indices[i];\n\t\t\tvectors[vertices[j].position].insert(ThreeVectors(vertices[j].*transform1, vertices[j].*transform2, vertices[j].*transform3));\n\t\t}\n\n\t\t\/\/вычислить результирующие вектора\n\t\tstd::map<float3, ThreeVectors, Float3Comparer> results;\n\t\tfor(auto i = vectors.begin(); i != vectors.end(); ++i)\n\t\t{\n\t\t\tconst std::set<ThreeVectors, ThreeVectorsComparer>& vectorSet = i->second;\n\t\t\tThreeVectors r;\n\t\t\tfor(std::set<ThreeVectors, ThreeVectorsComparer>::const_iterator j = vectorSet.begin(); j != vectorSet.end(); ++j)\n\t\t\t\tr += *j;\n\t\t\tr \/= (float)vectorSet.size();\n\t\t\tresults[i->first] = r;\n\t\t}\n\n\t\t\/\/сформировать новые вершины\n\t\tstd::vector<Vertex> outputVertices(indices.size());\n\t\tfor(size_t i = 0; i < outputVertices.size(); ++i)\n\t\t{\n\t\t\toutputVertices[i] = vertices[indices[i]];\n\t\t\tconst ThreeVectors& t = results[outputVertices[i].position];\n\t\t\toutputVertices[i].*transform1 = t.a;\n\t\t\toutputVertices[i].*transform2 = t.b;\n\t\t\toutputVertices[i].*transform3 = t.c;\n\t\t}\n\n\t\t\/\/создать геометрию\n\t\treturn NEW(EditableGeometry(outputVertices));\n\t}\n};\n\nEND_INANITY_GRAPHICS\n\n#endif\n<commit_msg>removed unused code from EditableGeometry<commit_after>#ifndef ___INANITY_GRAPHICS_EDITABLE_GEOMETRY_H___\n#define ___INANITY_GRAPHICS_EDITABLE_GEOMETRY_H___\n\n#include \"Geometry.hpp\"\n#include \"GeometryFormat.hpp\"\n#include <vector>\n#include <map>\n#include <set>\n#include <algorithm>\n\nBEGIN_INANITY_GRAPHICS\n\n\/\/\/ Класс типизированной редактируемой геометрии.\n\/**\nРазличные процедуры выдвигают различные требования к шаблонным параметрам.\nОни написаны в комментариях.\n*\/\ntemplate <typename Vertex, typename Index = unsigned short>\nclass EditableGeometry : public Object\n{\nprivate:\n\tstd::vector<Vertex> vertices;\n\tstd::vector<Index> indices;\n\npublic:\n\t\/\/\/ Создать типизированную геометрию.\n\tEditableGeometry(const std::vector<Vertex>& vertices, const std::vector<Index>& indices)\n\t\t: vertices(vertices), indices(indices) {}\n\n\t\/\/\/ Создать типизированную геометрию из неиндексированных вершин.\n\tEditableGeometry(const std::vector<Vertex>& vertices) : vertices(vertices)\n\t{\n\t\tindices.resize(vertices.size());\n\t\tfor(size_t i = 0; i < indices.size(); ++i)\n\t\t\tindices[i] = i;\n\t}\n\n\t\/\/\/ Получить вершины.\n\tstd::vector<Vertex>& GetVertices()\n\t{\n\t\treturn vertices;\n\t}\n\n\t\/\/\/ Получить индексы.\n\tstd::vector<Index>& GetIndices()\n\t{\n\t\treturn indices;\n\t}\n\n\t\/\/\/ Преобразовать тип индексов.\n\ttemplate <typename ToIndex>\n\tptr<EditableGeometry<Vertex, ToIndex> > CastIndices() const\n\t{\n\t\treturn NEW(EditableGeometry<Vertex, ToIndex>(vertices, std::vector<ToIndex>(indices.begin(), indices.end())));\n\t}\n\n\t\/\/\/ Сериализовать геометрию.\n\tvoid Serialize(ptr<OutputStream> outputStream, const String& formatFileName)\n\t{\n\t\t\/\/ проверить, являются ли индексы последовательными числами\n\t\t\/\/ тогда геометрию можно будет сериализовать без индексов\n\t\tbool needIndices = false;\n\t\tfor(size_t i = 0; i < indices.size(); ++i)\n\t\t\tif(indices[i] != i)\n\t\t\t{\n\t\t\t\tneedIndices = true;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\tptr<StreamWriter> writer = NEW(StreamWriter(outputStream));\n\n\t\twriter->WriteShortly(vertices.size());\n\t\twriter->WriteShortly(sizeof(Vertex));\n\t\twriter->WriteShortly(needIndices ? indices.size() : 0);\n\t\tif(needIndices)\n\t\t\twriter->WriteShortly(sizeof(Index));\n\t\twriter->WriteString(formatFileName);\n\t\twriter->Write(&*vertices.begin(), vertices.size() * sizeof(Vertex));\n\t\tif(needIndices)\n\t\t\twriter->Write(&*indices.begin(), indices.size() * sizeof(Index));\n\t}\n\n\tptr<File> SerializeVertices() const\n\t{\n\t\tptr<File> file = NEW(MemoryFile(vertices.size() * sizeof(Vertex)));\n\t\tmemcpy(file->GetData(), &*vertices.begin(), vertices.size() * sizeof(Vertex));\n\t\treturn file;\n\t}\n\n\tptr<File> SerializeIndices() const\n\t{\n\t\tptr<File> file = NEW(MemoryFile(indices.size() * sizeof(Index)));\n\t\tmemcpy(file->GetData(), &*indices.begin(), indices.size() * sizeof(Index));\n\t\treturn file;\n\t}\n\n\t\/\/\/ Оптимизировать геометрию\n\t\/** Выполняется объединение одинаковых вершин, с заданием соответствующих индексов.\n\tДля типа Vertex требуется наличие operator< и operator==.\n\t*\/\n\tptr<EditableGeometry> Optimize() const\n\t{\n\t\t\/\/скопировать вершины в новый массив с их индексами\n\t\tstd::vector<std::pair<Vertex, size_t> > newVertices(vertices.size());\n\t\tfor(size_t i = 0; i < vertices.size(); ++i)\n\t\t\tnewVertices[i] = std::make_pair(vertices[i], i);\n\t\t\/\/отсортировать их\n\t\tstd::sort(newVertices.begin(), newVertices.end());\n\t\t\/\/выполнить объединение одинаковых вершин\n\t\t\/\/заодно построить массив преобразования индексов\n\t\tstd::vector<Vertex> resultVertices;\n\t\tstd::vector<size_t> indexMap(vertices.size());\n\t\tresultVertices.reserve(vertices.size());\n\t\tfor(size_t i = 0; i < newVertices.size(); )\n\t\t{\n\t\t\tsize_t j;\n\t\t\tfor(j = i + 1; j < newVertices.size() && newVertices[i].first == newVertices[j].first; ++j);\n\t\t\tsize_t newIndex = resultVertices.size();\n\t\t\tresultVertices.push_back(newVertices[i].first);\n\t\t\tfor(; i < j; ++i)\n\t\t\t\tindexMap[newVertices[i].second] = newIndex;\n\t\t}\n\t\t\/\/скопировать индексы в новый массив\n\t\tstd::vector<Index> resultIndices(indices.size());\n\t\t\/\/и преобразовать их\n\t\tfor(size_t i = 0; i < resultIndices.size(); ++i)\n\t\t\tresultIndices[i] = indexMap[indices[i]];\n\t\treturn NEW(EditableGeometry(resultVertices, resultIndices));\n\t}\n};\n\nEND_INANITY_GRAPHICS\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>#include \"TF1.h\"\n#include \"TFile.h\"\n#include \"TH1.h\"\n#include \"TH2.h\"\n#include \"TH1F.h\"\n#include \"TProfile.h\"\n#include \"TRandom3.h\"\n#include \"TTree.h\"\n#include <iostream>\n#include <fstream>\n#include <stdlib.h>\nusing namespace std;\n#define PI2 2.0*3.141592653589793\n \nconst Int_t maxnh = 20000;\nInt_t b_npg, b_n, n;\nFloat_t b_phirg;\nFloat_t b_ptg[maxnh], b_etag[maxnh], b_phig[maxnh];\n\nvoid proSTEGvn()\n{\n\n int tot_num=1000; \/\/ number of events\n double MeanMult=2000;\n double RMSMult=0;\n\n \/\/simple toy event generator\n TFile f(\"\/store\/user\/tuos\/healpy\/toyModel\/steg10_m2000_flow08\/steg10kevts_m2000_jb0_prod.root\", \"RECREATE\",\"ROOT file with histograms & tree\");\n TTree *tree = new TTree(\"tree\",\"Event tree with a few branches\");\n \/\/tree->Branch(\"npg\", &b_npg, \"npg\/I\"); \/\/ # of particles;\n tree->Branch(\"n\", &b_n, \"n\/I\"); \/\/ same as npg, # of particles;\n tree->Branch(\"phirg\", &b_phirg, \"phirg\/F\"); \/\/ RP angle;\n tree->Branch(\"ptg\", &b_ptg, \"ptg[n]\/F\"); \/\/ ;\n tree->Branch(\"etag\", &b_etag, \"etag[n]\/F\");\n tree->Branch(\"phig\", &b_phig, \"phig[n]\/F\");\n \n TF1 *EtaDistr = new TF1(\"EtaDistr\",\"exp(-(x-2.1)^2\/6.3)+exp(-(x+2.1)^2\/6.3)\",-2.4,2.4);\n TF1 *PhiDistr = new TF1(\"PhiDistr\",\"1+2*[0]*cos([1]*x)\",0,PI2);\n\n TF1 *PtDistr = new TF1(\"PtDistr\",\"exp (-(x\/0.90))+0.15*exp (-(x\/15))\", 0.2,10);\n \/\/ fixed v2=0.1 by restricting the x-axis range in the TF1\n TF1 *V2Dist = new TF1(\"V2Dist\", \"ROOT::Math::cyl_bessel_i(0,x*0.1\/0.04\/0.04)*x\/0.04\/0.04*exp(-1*(x*x+0.1*0.1)\/2\/0.04\/0.04)\", 0.08, 0.080001);\n\n\/\/ TF1 *V3vsPt = new TF1(\"V3vsPt\",\"((x\/3.2)^2.3\/(1+(x\/3.4)^2.1))*(.00005+(1\/x)^1.4)\",0.2,10);\n\/\/ TF1 *V4vsPt = new TF1(\"V4vsPt\",\"((x\/4.8)^2.1\/(1+(x\/3.4)^2.1))*(.00005+(1\/x)^1.4)\",0.2,10);\n\/\/ TF1 *V5vsPt = new TF1(\"V5vsPt\",\"((x\/6.0)^3.2\/(1+(x\/11.4)^2.1))*(.00005+(1\/x)^1.4)\",0.2,10);\n\/\/ TF1 *V6vsPt = new TF1(\"V6vsPt\",\"((x\/5.6)^2.4\/(1+(x\/4.7)^2.1))*(.00005+(1\/x)^1.4)\",0.2,10);\n \n TRandom3 *rnd;\n rnd = new TRandom3(0);\n rnd->SetSeed(0); \n\n double v1, v2, v3, v4, v5, v6, ph, myphi, mypt, myeta, phi0, Psi;\n int nnf,k;\n double neta, nphi, npt;\n int slicept;\n \n for(int i=0; i<tot_num; i++){ \n \n \/\/Psi = rnd->Uniform(0.0,PI2);\n Psi = 0;\n b_phirg = Psi; \n rnd->SetSeed(0);\n b_npg = rnd->Gaus(MeanMult,RMSMult); \n n = 0;\n\n rnd->SetSeed(0);\n v2=V2Dist->GetRandom();\n \n for(int j=0; j<b_npg;j++ ){\n\n rnd->SetSeed(0); \n mypt = PtDistr->GetRandom();\n rnd->SetSeed(0);\n myeta = EtaDistr->GetRandom();\n \/\/v1=V1vsEta->Eval(myeta);\n\n\/\/ v2=V2vsPt->Eval(mypt);\n\/\/ v2=V2Dist->GetRandom();\n\n \/\/v3=V3vsPt->Eval(mypt);\n \/\/v4=V4vsPt->Eval(mypt);\n \/\/v5=V5vsPt->Eval(mypt);\n \/\/v6=V6vsPt->Eval(mypt);\n\n b_etag[n] = myeta;\n b_ptg[n] = mypt;\n \/\/PhiDistr->SetParameters(v1,v2,v3,v4,v5,v6);\n \/\/PhiDistr->SetParameters(v2,v3,v4,v5,v6);\n PhiDistr->SetParameters(v2,2.0);\n rnd->SetSeed(0); \n myphi = PhiDistr->GetRandom(); \/\/ randon selection dn\/dphi\n myphi = myphi+Psi; \/\/ angle in lab frame -- needed for correct cumulant v2\n if (myphi>PI2) myphi=myphi-PI2; \/\/ 0 - 2*Pi\n \n b_phig[n] = myphi; \/\/ save angle in lab frame\n \n n++;\n \n } \/\/ End of loop over particles\n \n if (i%1 == 0) cout << i << \" \" << \"events processed\" << endl;\n\n b_n = n;\n tree->Fill();\n } \/\/ End of loop over events\n \n cout << \"writing tree\" << endl;\n tree->Write();\n cout << \"writing to file\" << endl;\n f.Write();\n cout << \"closing file\" << endl;\n f.Close();\n cout << \"THE END\" << endl;\n}\n\n<commit_msg>up for random number seeds<commit_after>#include \"TF1.h\"\n#include \"TFile.h\"\n#include \"TH1.h\"\n#include \"TH2.h\"\n#include \"TH1F.h\"\n#include \"TProfile.h\"\n#include \"TRandom3.h\"\n#include \"TTree.h\"\n#include <iostream>\n#include <fstream>\n#include <stdlib.h>\nusing namespace std;\n#define PI2 2.0*3.141592653589793\n \nconst Int_t maxnh = 20000;\nInt_t b_npg, b_n, n;\nFloat_t b_phirg;\nFloat_t b_ptg[maxnh], b_etag[maxnh], b_phig[maxnh];\n\nvoid proSTEGvn()\n{\n\n int tot_num=1000; \/\/ number of events\n double MeanMult=2000;\n double RMSMult=0;\n\n \/\/simple toy event generator\n TFile f(\"\/store\/user\/tuos\/healpy\/toyModel\/steg10_m2000_flow08\/steg10kevts_m2000_jb0_prod.root\", \"RECREATE\",\"ROOT file with histograms & tree\");\n TTree *tree = new TTree(\"tree\",\"Event tree with a few branches\");\n \/\/tree->Branch(\"npg\", &b_npg, \"npg\/I\"); \/\/ # of particles;\n tree->Branch(\"n\", &b_n, \"n\/I\"); \/\/ same as npg, # of particles;\n tree->Branch(\"phirg\", &b_phirg, \"phirg\/F\"); \/\/ RP angle;\n tree->Branch(\"ptg\", &b_ptg, \"ptg[n]\/F\"); \/\/ ;\n tree->Branch(\"etag\", &b_etag, \"etag[n]\/F\");\n tree->Branch(\"phig\", &b_phig, \"phig[n]\/F\");\n \n TF1 *EtaDistr = new TF1(\"EtaDistr\",\"exp(-(x-2.1)^2\/6.3)+exp(-(x+2.1)^2\/6.3)\",-2.4,2.4);\n TF1 *PhiDistr = new TF1(\"PhiDistr\",\"1+2*[0]*cos([1]*x)\",0,PI2);\n\n TF1 *PtDistr = new TF1(\"PtDistr\",\"exp (-(x\/0.90))+0.15*exp (-(x\/15))\", 0.2,10);\n \/\/ fixed v2=0.1 by restricting the x-axis range in the TF1\n TF1 *V2Dist = new TF1(\"V2Dist\", \"ROOT::Math::cyl_bessel_i(0,x*0.1\/0.04\/0.04)*x\/0.04\/0.04*exp(-1*(x*x+0.1*0.1)\/2\/0.04\/0.04)\", 0.08, 0.080001);\n\n\/\/ TF1 *V3vsPt = new TF1(\"V3vsPt\",\"((x\/3.2)^2.3\/(1+(x\/3.4)^2.1))*(.00005+(1\/x)^1.4)\",0.2,10);\n\/\/ TF1 *V4vsPt = new TF1(\"V4vsPt\",\"((x\/4.8)^2.1\/(1+(x\/3.4)^2.1))*(.00005+(1\/x)^1.4)\",0.2,10);\n\/\/ TF1 *V5vsPt = new TF1(\"V5vsPt\",\"((x\/6.0)^3.2\/(1+(x\/11.4)^2.1))*(.00005+(1\/x)^1.4)\",0.2,10);\n\/\/ TF1 *V6vsPt = new TF1(\"V6vsPt\",\"((x\/5.6)^2.4\/(1+(x\/4.7)^2.1))*(.00005+(1\/x)^1.4)\",0.2,10);\n \n TRandom3 *rnd;\n rnd = new TRandom3(0);\n rnd->SetSeed(0); \n gRandom->SetSeed(0); \n\n double v1, v2, v3, v4, v5, v6, ph, myphi, mypt, myeta, phi0, Psi;\n int nnf,k;\n double neta, nphi, npt;\n int slicept;\n \n for(int i=0; i<tot_num; i++){ \n \n \/\/Psi = rnd->Uniform(0.0,PI2);\n Psi = 0;\n b_phirg = Psi; \n b_npg = rnd->Gaus(MeanMult,RMSMult); \n n = 0;\n\n v2=V2Dist->GetRandom();\n \n for(int j=0; j<b_npg;j++ ){\n\n mypt = PtDistr->GetRandom();\n myeta = EtaDistr->GetRandom();\n \/\/v1=V1vsEta->Eval(myeta);\n\n\/\/ v2=V2vsPt->Eval(mypt);\n\/\/ v2=V2Dist->GetRandom();\n\n \/\/v3=V3vsPt->Eval(mypt);\n \/\/v4=V4vsPt->Eval(mypt);\n \/\/v5=V5vsPt->Eval(mypt);\n \/\/v6=V6vsPt->Eval(mypt);\n\n b_etag[n] = myeta;\n b_ptg[n] = mypt;\n \/\/PhiDistr->SetParameters(v1,v2,v3,v4,v5,v6);\n \/\/PhiDistr->SetParameters(v2,v3,v4,v5,v6);\n PhiDistr->SetParameters(v2,2.0);\n myphi = PhiDistr->GetRandom(); \/\/ randon selection dn\/dphi\n \/\/cout<<\"myphi = \"<<myphi<<endl;\n myphi = myphi+Psi; \/\/ angle in lab frame -- needed for correct cumulant v2\n if (myphi>PI2) myphi=myphi-PI2; \/\/ 0 - 2*Pi\n \n b_phig[n] = myphi; \/\/ save angle in lab frame\n \n n++;\n \n } \/\/ End of loop over particles\n \n if (i%1 == 0) cout << i << \" \" << \"events processed\" << endl;\n\n b_n = n;\n tree->Fill();\n } \/\/ End of loop over events\n \n cout << \"writing tree\" << endl;\n tree->Write();\n cout << \"writing to file\" << endl;\n f.Write();\n cout << \"closing file\" << endl;\n f.Close();\n cout << \"THE END\" << endl;\n}\n\n<|endoftext|>"} {"text":"<commit_before> \/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2008 by Sun Microsystems, Inc.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: NResultSetMetaData.cxx,v $\n * $Revision: 1.7 $\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * <http:\/\/www.openoffice.org\/license.html>\n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_connectivity.hxx\"\n#include \"NResultSetMetaData.hxx\"\n#include \"NDatabaseMetaData.hxx\"\n#include \"connectivity\/dbexception.hxx\"\n#include <com\/sun\/star\/sdbc\/DataType.hpp>\n#include \"NDebug.hxx\"\n\nusing namespace connectivity::evoab;\nusing namespace com::sun::star::uno;\nusing namespace com::sun::star::lang;\nusing namespace com::sun::star::sdbc;\n\nOEvoabResultSetMetaData::OEvoabResultSetMetaData(const ::rtl::OUString& _aTableName)\n : m_aTableName(_aTableName),\n m_aEvoabFields()\n{\n\n}\n\/\/ -------------------------------------------------------------------------\nOEvoabResultSetMetaData::~OEvoabResultSetMetaData()\n{\n}\n\/\/ -------------------------------------------------------------------------\nvoid OEvoabResultSetMetaData::setEvoabFields(const ::vos::ORef<connectivity::OSQLColumns> &xColumns) throw(SQLException)\n{\n OSQLColumns::const_iterator aIter;\n static const ::rtl::OUString aName(::rtl::OUString::createFromAscii(\"Name\"));\n\n for (aIter = xColumns->begin(); aIter != xColumns->end(); ++aIter)\n {\n ::rtl::OUString aFieldName;\n\n (*aIter)->getPropertyValue(aName) >>= aFieldName;\n guint nFieldNumber = findEvoabField(aFieldName);\n if (nFieldNumber == (guint)-1)\n ::dbtools::throwGenericSQLException(\n ::rtl::OUString::createFromAscii(\"Invalid column name: \") + aFieldName,\n NULL);\n m_aEvoabFields.push_back(nFieldNumber);\n }\n}\n\n\/\/ -------------------------------------------------------------------------\nvoid OEvoabResultSetMetaData::checkColumnIndex(sal_Int32 nColumnNum) throw(SQLException, RuntimeException)\n{\n if( nColumnNum <= 0 || nColumnNum > getColumnCount() )\n dbtools::throwInvalidIndexException( *this );\n}\n\/\/ -------------------------------------------------------------------------\nsal_Int32 SAL_CALL OEvoabResultSetMetaData::getColumnDisplaySize( sal_Int32 \/*nColumnNum*\/ ) throw(SQLException, RuntimeException)\n{\n return 50;\n}\n\/\/ -------------------------------------------------------------------------\nsal_Int32 SAL_CALL OEvoabResultSetMetaData::getColumnType( sal_Int32 nColumnNum ) throw(SQLException, RuntimeException)\n{\n sal_uInt32 nField = m_aEvoabFields[nColumnNum - 1];\n return evoab::getFieldType (nField);\n}\n\/\/ -------------------------------------------------------------------------\nsal_Int32 SAL_CALL OEvoabResultSetMetaData::getColumnCount( ) throw(SQLException, RuntimeException)\n{\n return m_aEvoabFields.size();\n}\n\/\/ -------------------------------------------------------------------------\nsal_Bool SAL_CALL OEvoabResultSetMetaData::isCaseSensitive( sal_Int32 \/*nColumnNum*\/ ) throw(SQLException, RuntimeException)\n{\n return sal_True;\n}\n\/\/ -------------------------------------------------------------------------\n::rtl::OUString SAL_CALL OEvoabResultSetMetaData::getSchemaName( sal_Int32 \/*nColumnNum*\/ ) throw(SQLException, RuntimeException)\n{\n return ::rtl::OUString();\n}\n\/\/ -------------------------------------------------------------------------\n::rtl::OUString SAL_CALL OEvoabResultSetMetaData::getColumnName( sal_Int32 nColumnNum ) throw(SQLException, RuntimeException)\n{\n sal_uInt32 nField = m_aEvoabFields[nColumnNum - 1];\n return evoab::getFieldName( nField );\n}\n\/\/ -------------------------------------------------------------------------\n::rtl::OUString SAL_CALL OEvoabResultSetMetaData::getColumnTypeName( sal_Int32 nColumnNum ) throw(SQLException, RuntimeException)\n{\n sal_uInt32 nField = m_aEvoabFields[nColumnNum - 1];\n return evoab::getFieldTypeName( nField );\n}\n\/\/ -------------------------------------------------------------------------\n::rtl::OUString SAL_CALL OEvoabResultSetMetaData::getColumnLabel( sal_Int32 nColumnNum ) throw(SQLException, RuntimeException)\n{\n sal_uInt32 nField = m_aEvoabFields[nColumnNum - 1];\n const ColumnProperty *pSpecs = getField(nField);\n GParamSpec *pSpec = pSpecs->pField;\n rtl::OUString aLabel;\n\n if( pSpec )\n aLabel = rtl::OStringToOUString( g_param_spec_get_nick( (GParamSpec *) pSpec ),\n RTL_TEXTENCODING_UTF8 );\n return aLabel;\n}\n\/\/ -------------------------------------------------------------------------\n::rtl::OUString SAL_CALL OEvoabResultSetMetaData::getColumnServiceName( sal_Int32 \/*nColumnNum*\/ ) throw(SQLException, RuntimeException)\n{\n return ::rtl::OUString();\n}\n\/\/ -------------------------------------------------------------------------\n::rtl::OUString SAL_CALL OEvoabResultSetMetaData::getTableName( sal_Int32 \/*nColumnNum*\/ ) throw(SQLException, RuntimeException)\n{\n return m_aTableName;\/\/::rtl::OUString::createFromAscii(\"TABLE\");\n}\n\/\/ -------------------------------------------------------------------------\n::rtl::OUString SAL_CALL OEvoabResultSetMetaData::getCatalogName( sal_Int32 \/*nColumnNum*\/ ) throw(SQLException, RuntimeException)\n{\n return ::rtl::OUString();\n}\n\/\/ -------------------------------------------------------------------------\n\nsal_Bool SAL_CALL OEvoabResultSetMetaData::isCurrency( sal_Int32 \/*nColumnNum*\/ ) throw(SQLException, RuntimeException)\n{\n return sal_False;\n}\n\/\/ -------------------------------------------------------------------------\nsal_Bool SAL_CALL OEvoabResultSetMetaData::isAutoIncrement( sal_Int32 \/*nColumnNum*\/ ) throw(SQLException, RuntimeException)\n{\n return sal_False;\n}\n\/\/ -------------------------------------------------------------------------\nsal_Bool SAL_CALL OEvoabResultSetMetaData::isSigned( sal_Int32 \/*nColumnNum*\/ ) throw(SQLException, RuntimeException)\n{\n return sal_False;\n}\n\/\/ -------------------------------------------------------------------------\nsal_Int32 SAL_CALL OEvoabResultSetMetaData::getPrecision( sal_Int32 \/*nColumnNum*\/ ) throw(SQLException, RuntimeException)\n{\n return 0;\n}\n\/\/ -----------------------------------------------------------------------------\nsal_Int32 SAL_CALL OEvoabResultSetMetaData::getScale( sal_Int32 \/*nColumnNum*\/ ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException)\n{\n return 0;\n}\n\/\/ -------------------------------------------------------------------------\nsal_Int32 SAL_CALL OEvoabResultSetMetaData::isNullable( sal_Int32 \/*nColumnNum*\/ ) throw(SQLException, RuntimeException)\n{\n return 0;\n}\n\/\/ -------------------------------------------------------------------------\nsal_Bool SAL_CALL OEvoabResultSetMetaData::isSearchable( sal_Int32 \/*nColumnNum*\/ ) throw(SQLException, RuntimeException)\n{\n return sal_False;\n}\n\/\/ -------------------------------------------------------------------------\nsal_Bool SAL_CALL OEvoabResultSetMetaData::isReadOnly( sal_Int32 \/*nColumnNum*\/ ) throw(SQLException, RuntimeException)\n{\n return sal_True;\n}\n\/\/ -------------------------------------------------------------------------\nsal_Bool SAL_CALL OEvoabResultSetMetaData::isDefinitelyWritable( sal_Int32 \/*nColumnNum*\/ ) throw(SQLException, RuntimeException)\n{\n return sal_False;\n}\n\/\/ -------------------------------------------------------------------------\nsal_Bool SAL_CALL OEvoabResultSetMetaData::isWritable( sal_Int32 \/*nColumnNum*\/ ) throw(SQLException, RuntimeException)\n{\n return sal_False;\n}\n\/\/ -------------------------------------------------------------------------\n<commit_msg>INTEGRATION: CWS dba31a (1.7.32); FILE MERGED 2008\/07\/04 15:21:25 oj 1.7.32.1: #i89558# remove unused code<commit_after> \/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2008 by Sun Microsystems, Inc.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: NResultSetMetaData.cxx,v $\n * $Revision: 1.8 $\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * <http:\/\/www.openoffice.org\/license.html>\n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_connectivity.hxx\"\n#include \"NResultSetMetaData.hxx\"\n#include \"NDatabaseMetaData.hxx\"\n#include \"connectivity\/dbexception.hxx\"\n#include <com\/sun\/star\/sdbc\/DataType.hpp>\n#include \"NDebug.hxx\"\n\nusing namespace connectivity::evoab;\nusing namespace com::sun::star::uno;\nusing namespace com::sun::star::lang;\nusing namespace com::sun::star::sdbc;\n\nOEvoabResultSetMetaData::OEvoabResultSetMetaData(const ::rtl::OUString& _aTableName)\n : m_aTableName(_aTableName),\n m_aEvoabFields()\n{\n\n}\n\/\/ -------------------------------------------------------------------------\nOEvoabResultSetMetaData::~OEvoabResultSetMetaData()\n{\n}\n\/\/ -------------------------------------------------------------------------\nvoid OEvoabResultSetMetaData::setEvoabFields(const ::vos::ORef<connectivity::OSQLColumns> &xColumns) throw(SQLException)\n{\n OSQLColumns::const_iterator aIter;\n static const ::rtl::OUString aName(::rtl::OUString::createFromAscii(\"Name\"));\n\n for (aIter = xColumns->begin(); aIter != xColumns->end(); ++aIter)\n {\n ::rtl::OUString aFieldName;\n\n (*aIter)->getPropertyValue(aName) >>= aFieldName;\n guint nFieldNumber = findEvoabField(aFieldName);\n if (nFieldNumber == (guint)-1)\n ::dbtools::throwGenericSQLException(\n ::rtl::OUString::createFromAscii(\"Invalid column name: \") + aFieldName,\n NULL);\n m_aEvoabFields.push_back(nFieldNumber);\n }\n}\n\n\/\/ -------------------------------------------------------------------------\nsal_Int32 SAL_CALL OEvoabResultSetMetaData::getColumnDisplaySize( sal_Int32 \/*nColumnNum*\/ ) throw(SQLException, RuntimeException)\n{\n return 50;\n}\n\/\/ -------------------------------------------------------------------------\nsal_Int32 SAL_CALL OEvoabResultSetMetaData::getColumnType( sal_Int32 nColumnNum ) throw(SQLException, RuntimeException)\n{\n sal_uInt32 nField = m_aEvoabFields[nColumnNum - 1];\n return evoab::getFieldType (nField);\n}\n\/\/ -------------------------------------------------------------------------\nsal_Int32 SAL_CALL OEvoabResultSetMetaData::getColumnCount( ) throw(SQLException, RuntimeException)\n{\n return m_aEvoabFields.size();\n}\n\/\/ -------------------------------------------------------------------------\nsal_Bool SAL_CALL OEvoabResultSetMetaData::isCaseSensitive( sal_Int32 \/*nColumnNum*\/ ) throw(SQLException, RuntimeException)\n{\n return sal_True;\n}\n\/\/ -------------------------------------------------------------------------\n::rtl::OUString SAL_CALL OEvoabResultSetMetaData::getSchemaName( sal_Int32 \/*nColumnNum*\/ ) throw(SQLException, RuntimeException)\n{\n return ::rtl::OUString();\n}\n\/\/ -------------------------------------------------------------------------\n::rtl::OUString SAL_CALL OEvoabResultSetMetaData::getColumnName( sal_Int32 nColumnNum ) throw(SQLException, RuntimeException)\n{\n sal_uInt32 nField = m_aEvoabFields[nColumnNum - 1];\n return evoab::getFieldName( nField );\n}\n\/\/ -------------------------------------------------------------------------\n::rtl::OUString SAL_CALL OEvoabResultSetMetaData::getColumnTypeName( sal_Int32 nColumnNum ) throw(SQLException, RuntimeException)\n{\n sal_uInt32 nField = m_aEvoabFields[nColumnNum - 1];\n return evoab::getFieldTypeName( nField );\n}\n\/\/ -------------------------------------------------------------------------\n::rtl::OUString SAL_CALL OEvoabResultSetMetaData::getColumnLabel( sal_Int32 nColumnNum ) throw(SQLException, RuntimeException)\n{\n sal_uInt32 nField = m_aEvoabFields[nColumnNum - 1];\n const ColumnProperty *pSpecs = getField(nField);\n GParamSpec *pSpec = pSpecs->pField;\n rtl::OUString aLabel;\n\n if( pSpec )\n aLabel = rtl::OStringToOUString( g_param_spec_get_nick( (GParamSpec *) pSpec ),\n RTL_TEXTENCODING_UTF8 );\n return aLabel;\n}\n\/\/ -------------------------------------------------------------------------\n::rtl::OUString SAL_CALL OEvoabResultSetMetaData::getColumnServiceName( sal_Int32 \/*nColumnNum*\/ ) throw(SQLException, RuntimeException)\n{\n return ::rtl::OUString();\n}\n\/\/ -------------------------------------------------------------------------\n::rtl::OUString SAL_CALL OEvoabResultSetMetaData::getTableName( sal_Int32 \/*nColumnNum*\/ ) throw(SQLException, RuntimeException)\n{\n return m_aTableName;\/\/::rtl::OUString::createFromAscii(\"TABLE\");\n}\n\/\/ -------------------------------------------------------------------------\n::rtl::OUString SAL_CALL OEvoabResultSetMetaData::getCatalogName( sal_Int32 \/*nColumnNum*\/ ) throw(SQLException, RuntimeException)\n{\n return ::rtl::OUString();\n}\n\/\/ -------------------------------------------------------------------------\n\nsal_Bool SAL_CALL OEvoabResultSetMetaData::isCurrency( sal_Int32 \/*nColumnNum*\/ ) throw(SQLException, RuntimeException)\n{\n return sal_False;\n}\n\/\/ -------------------------------------------------------------------------\nsal_Bool SAL_CALL OEvoabResultSetMetaData::isAutoIncrement( sal_Int32 \/*nColumnNum*\/ ) throw(SQLException, RuntimeException)\n{\n return sal_False;\n}\n\/\/ -------------------------------------------------------------------------\nsal_Bool SAL_CALL OEvoabResultSetMetaData::isSigned( sal_Int32 \/*nColumnNum*\/ ) throw(SQLException, RuntimeException)\n{\n return sal_False;\n}\n\/\/ -------------------------------------------------------------------------\nsal_Int32 SAL_CALL OEvoabResultSetMetaData::getPrecision( sal_Int32 \/*nColumnNum*\/ ) throw(SQLException, RuntimeException)\n{\n return 0;\n}\n\/\/ -----------------------------------------------------------------------------\nsal_Int32 SAL_CALL OEvoabResultSetMetaData::getScale( sal_Int32 \/*nColumnNum*\/ ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException)\n{\n return 0;\n}\n\/\/ -------------------------------------------------------------------------\nsal_Int32 SAL_CALL OEvoabResultSetMetaData::isNullable( sal_Int32 \/*nColumnNum*\/ ) throw(SQLException, RuntimeException)\n{\n return 0;\n}\n\/\/ -------------------------------------------------------------------------\nsal_Bool SAL_CALL OEvoabResultSetMetaData::isSearchable( sal_Int32 \/*nColumnNum*\/ ) throw(SQLException, RuntimeException)\n{\n return sal_False;\n}\n\/\/ -------------------------------------------------------------------------\nsal_Bool SAL_CALL OEvoabResultSetMetaData::isReadOnly( sal_Int32 \/*nColumnNum*\/ ) throw(SQLException, RuntimeException)\n{\n return sal_True;\n}\n\/\/ -------------------------------------------------------------------------\nsal_Bool SAL_CALL OEvoabResultSetMetaData::isDefinitelyWritable( sal_Int32 \/*nColumnNum*\/ ) throw(SQLException, RuntimeException)\n{\n return sal_False;\n}\n\/\/ -------------------------------------------------------------------------\nsal_Bool SAL_CALL OEvoabResultSetMetaData::isWritable( sal_Int32 \/*nColumnNum*\/ ) throw(SQLException, RuntimeException)\n{\n return sal_False;\n}\n\/\/ -------------------------------------------------------------------------\n<|endoftext|>"} {"text":"<commit_before>\/****************************************************************************\n *\n * Copyright (c) 2013, 2014 PX4 Development Team. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in\n * the documentation and\/or other materials provided with the\n * distribution.\n * 3. Neither the name PX4 nor the names of its contributors may be\n * used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS\n * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED\n * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n ****************************************************************************\/\n\n\/**\n * @file ets_airspeed.cpp\n * @author Simon Wilks\n *\n * Driver for the Eagle Tree Airspeed V3 connected via I2C.\n *\/\n\n#include <nuttx\/config.h>\n\n#include <drivers\/device\/i2c.h>\n\n#include <sys\/types.h>\n#include <stdint.h>\n#include <stdlib.h>\n#include <stdbool.h>\n#include <semaphore.h>\n#include <string.h>\n#include <fcntl.h>\n#include <poll.h>\n#include <errno.h>\n#include <stdio.h>\n#include <math.h>\n#include <unistd.h>\n\n#include <nuttx\/arch.h>\n#include <nuttx\/wqueue.h>\n#include <nuttx\/clock.h>\n\n#include <board_config.h>\n\n#include <systemlib\/airspeed.h>\n#include <systemlib\/err.h>\n#include <systemlib\/param\/param.h>\n#include <systemlib\/perf_counter.h>\n\n#include <drivers\/drv_airspeed.h>\n#include <drivers\/drv_hrt.h>\n#include <drivers\/device\/ringbuffer.h>\n\n#include <uORB\/uORB.h>\n#include <uORB\/topics\/differential_pressure.h>\n#include <uORB\/topics\/subsystem_info.h>\n#include <drivers\/airspeed\/airspeed.h>\n\n\/* I2C bus address *\/\n#define I2C_ADDRESS\t0x75\t\/* 7-bit address. 8-bit address is 0xEA *\/\n#define ETS_PATH\t\"\/dev\/ets_airspeed\"\n\n\/* Register address *\/\n#define READ_CMD\t0x07\t\/* Read the data *\/\n\n\/**\n * The Eagle Tree Airspeed V3 cannot provide accurate reading below speeds of 15km\/h.\n * You can set this value to 12 if you want a zero reading below 15km\/h.\n *\/\n#define MIN_ACCURATE_DIFF_PRES_PA 0\n\n\/* Measurement rate is 100Hz *\/\n#define CONVERSION_INTERVAL\t(1000000 \/ 100)\t\/* microseconds *\/\n\nclass ETSAirspeed : public Airspeed\n{\npublic:\n\tETSAirspeed(int bus, int address = I2C_ADDRESS, const char* path = ETS_PATH);\n\nprotected:\n\n\t\/**\n\t* Perform a poll cycle; collect from the previous measurement\n\t* and start a new one.\n\t*\/\n\tvirtual void\tcycle();\n\tvirtual int\tmeasure();\n\tvirtual int\tcollect();\n\n};\n\n\/*\n * Driver 'main' command.\n *\/\nextern \"C\" __EXPORT int ets_airspeed_main(int argc, char *argv[]);\n\nETSAirspeed::ETSAirspeed(int bus, int address, const char* path) : Airspeed(bus, address,\n\tCONVERSION_INTERVAL, path)\n{\n\n}\n\nint\nETSAirspeed::measure()\n{\n\tint ret;\n\n\t\/*\n\t * Send the command to begin a measurement.\n\t *\/\n\tuint8_t cmd = READ_CMD;\n\tret = transfer(&cmd, 1, nullptr, 0);\n\n\tif (OK != ret) {\n\t\tperf_count(_comms_errors);\n\t}\n\n\treturn ret;\n}\n\nint\nETSAirspeed::collect()\n{\n\tint\tret = -EIO;\n\n\t\/* read from the sensor *\/\n\tuint8_t val[2] = {0, 0};\n\n\tperf_begin(_sample_perf);\n\n\tret = transfer(nullptr, 0, &val[0], 2);\n\n\tif (ret < 0) {\n\t\tperf_count(_comms_errors);\n\t\treturn ret;\n\t}\n\n\tuint16_t diff_pres_pa_raw = val[1] << 8 | val[0];\n\tuint16_t diff_pres_pa;\n if (diff_pres_pa_raw == 0) {\n\t\t\/\/ a zero value means the pressure sensor cannot give us a\n\t\t\/\/ value. We need to return, and not report a value or the\n\t\t\/\/ caller could end up using this value as part of an\n\t\t\/\/ average\n\t\tperf_count(_comms_errors);\n\t\tlog(\"zero value from sensor\"); \n\t\treturn -1;\n }\n\n\tif (diff_pres_pa_raw < _diff_pres_offset + MIN_ACCURATE_DIFF_PRES_PA) {\n\t\tdiff_pres_pa = 0;\n\t} else {\n\t\tdiff_pres_pa = diff_pres_pa_raw - _diff_pres_offset;\n\t}\n\n\t\/\/ Track maximum differential pressure measured (so we can work out top speed).\n\tif (diff_pres_pa > _max_differential_pressure_pa) {\n\t\t_max_differential_pressure_pa = diff_pres_pa;\n\t}\n\n\tdifferential_pressure_s report;\n\treport.timestamp = hrt_absolute_time();\n report.error_count = perf_event_count(_comms_errors);\n\treport.differential_pressure_pa = (float)diff_pres_pa;\n\n\t\/\/ XXX we may want to smooth out the readings to remove noise.\n\treport.differential_pressure_filtered_pa = (float)diff_pres_pa;\n\treport.differential_pressure_raw_pa = (float)diff_pres_pa_raw;\n\treport.temperature = -1000.0f;\n\treport.voltage = 0;\n\treport.max_differential_pressure_pa = _max_differential_pressure_pa;\n\n\tif (_airspeed_pub > 0 && !(_pub_blocked)) {\n\t\t\/* publish it *\/\n\t\torb_publish(ORB_ID(differential_pressure), _airspeed_pub, &report);\n\t}\n\n\tnew_report(report);\n\n\t\/* notify anyone waiting for data *\/\n\tpoll_notify(POLLIN);\n\n\tret = OK;\n\n\tperf_end(_sample_perf);\n\n\treturn ret;\n}\n\nvoid\nETSAirspeed::cycle()\n{\n\tint ret;\n\n\t\/* collection phase? *\/\n\tif (_collect_phase) {\n\n\t\t\/* perform collection *\/\n\t\tret = collect();\n\t\tif (OK != ret) {\n\t\t\tperf_count(_comms_errors);\n\t\t\t\/* restart the measurement state machine *\/\n\t\t\tstart();\n\t\t\t_sensor_ok = false;\n\t\t\treturn;\n\t\t}\n\n\t\t\/* next phase is measurement *\/\n\t\t_collect_phase = false;\n\n\t\t\/*\n\t\t * Is there a collect->measure gap?\n\t\t *\/\n\t\tif (_measure_ticks > USEC2TICK(CONVERSION_INTERVAL)) {\n\n\t\t\t\/* schedule a fresh cycle call when we are ready to measure again *\/\n\t\t\twork_queue(HPWORK,\n\t\t\t\t &_work,\n\t\t\t\t (worker_t)&Airspeed::cycle_trampoline,\n\t\t\t\t this,\n\t\t\t\t _measure_ticks - USEC2TICK(CONVERSION_INTERVAL));\n\n\t\t\treturn;\n\t\t}\n\t}\n\n\t\/* measurement phase *\/\n\tret = measure();\n\tif (OK != ret) {\n\t\tdebug(\"measure error\");\n\t}\n\n\t_sensor_ok = (ret == OK);\n\n\t\/* next phase is collection *\/\n\t_collect_phase = true;\n\n\t\/* schedule a fresh cycle call when the measurement is done *\/\n\twork_queue(HPWORK,\n\t\t &_work,\n\t\t (worker_t)&Airspeed::cycle_trampoline,\n\t\t this,\n\t\t USEC2TICK(CONVERSION_INTERVAL));\n}\n\n\/**\n * Local functions in support of the shell command.\n *\/\nnamespace ets_airspeed\n{\n\n\/* oddly, ERROR is not defined for c++ *\/\n#ifdef ERROR\n# undef ERROR\n#endif\nconst int ERROR = -1;\n\nETSAirspeed\t*g_dev;\n\nvoid\tstart(int i2c_bus);\nvoid\tstop();\nvoid\ttest();\nvoid\treset();\nvoid\tinfo();\n\n\/**\n * Start the driver.\n *\/\nvoid\nstart(int i2c_bus)\n{\n\tint fd;\n\n\tif (g_dev != nullptr)\n\t\terrx(1, \"already started\");\n\n\t\/* create the driver *\/\n\tg_dev = new ETSAirspeed(i2c_bus);\n\n\tif (g_dev == nullptr)\n\t\tgoto fail;\n\n\tif (OK != g_dev->Airspeed::init())\n\t\tgoto fail;\n\n\t\/* set the poll rate to default, starts automatic data collection *\/\n\tfd = open(AIRSPEED_DEVICE_PATH, O_RDONLY);\n\n\tif (fd < 0)\n\t\tgoto fail;\n\n\tif (ioctl(fd, SENSORIOCSPOLLRATE, SENSOR_POLLRATE_DEFAULT) < 0)\n\t\tgoto fail;\n\n\texit(0);\n\nfail:\n\n\tif (g_dev != nullptr) {\n\t\tdelete g_dev;\n\t\tg_dev = nullptr;\n\t}\n\n\terrx(1, \"no ETS airspeed sensor connected\");\n}\n\n\/**\n * Stop the driver\n *\/\nvoid\nstop()\n{\n\tif (g_dev != nullptr) {\n\t\tdelete g_dev;\n\t\tg_dev = nullptr;\n\n\t} else {\n\t\terrx(1, \"driver not running\");\n\t}\n\n\texit(0);\n}\n\n\/**\n * Perform some basic functional tests on the driver;\n * make sure we can collect data from the sensor in polled\n * and automatic modes.\n *\/\nvoid\ntest()\n{\n\tstruct differential_pressure_s report;\n\tssize_t sz;\n\tint ret;\n\n\tint fd = open(AIRSPEED_DEVICE_PATH, O_RDONLY);\n\n\tif (fd < 0)\n\t\terr(1, \"%s open failed (try 'ets_airspeed start' if the driver is not running\", AIRSPEED_DEVICE_PATH);\n\n\t\/* do a simple demand read *\/\n\tsz = read(fd, &report, sizeof(report));\n\n\tif (sz != sizeof(report))\n\t\terr(1, \"immediate read failed\");\n\n\twarnx(\"single read\");\n\twarnx(\"diff pressure: %f pa\", (double)report.differential_pressure_pa);\n\n\t\/* start the sensor polling at 2Hz *\/\n\tif (OK != ioctl(fd, SENSORIOCSPOLLRATE, 2))\n\t\terrx(1, \"failed to set 2Hz poll rate\");\n\n\t\/* read the sensor 5x and report each value *\/\n\tfor (unsigned i = 0; i < 5; i++) {\n\t\tstruct pollfd fds;\n\n\t\t\/* wait for data to be ready *\/\n\t\tfds.fd = fd;\n\t\tfds.events = POLLIN;\n\t\tret = poll(&fds, 1, 2000);\n\n\t\tif (ret != 1)\n\t\t\terrx(1, \"timed out waiting for sensor data\");\n\n\t\t\/* now go get it *\/\n\t\tsz = read(fd, &report, sizeof(report));\n\n\t\tif (sz != sizeof(report))\n\t\t\terr(1, \"periodic read failed\");\n\n\t\twarnx(\"periodic read %u\", i);\n\t\twarnx(\"diff pressure: %f pa\", (double)report.differential_pressure_pa);\n\t}\n\n\t\/* reset the sensor polling to its default rate *\/\n\tif (OK != ioctl(fd, SENSORIOCSPOLLRATE, SENSOR_POLLRATE_DEFAULT))\n\t\terrx(1, \"failed to set default rate\");\n\n\terrx(0, \"PASS\");\n}\n\n\/**\n * Reset the driver.\n *\/\nvoid\nreset()\n{\n\tint fd = open(AIRSPEED_DEVICE_PATH, O_RDONLY);\n\n\tif (fd < 0)\n\t\terr(1, \"failed \");\n\n\tif (ioctl(fd, SENSORIOCRESET, 0) < 0)\n\t\terr(1, \"driver reset failed\");\n\n\tif (ioctl(fd, SENSORIOCSPOLLRATE, SENSOR_POLLRATE_DEFAULT) < 0)\n\t\terr(1, \"driver poll restart failed\");\n\n\texit(0);\n}\n\n\/**\n * Print a little info about the driver.\n *\/\nvoid\ninfo()\n{\n\tif (g_dev == nullptr)\n\t\terrx(1, \"driver not running\");\n\n\tprintf(\"state @ %p\\n\", g_dev);\n\tg_dev->print_info();\n\n\texit(0);\n}\n\n} \/\/ namespace\n\n\nstatic void\nets_airspeed_usage()\n{\n\twarnx(\"usage: ets_airspeed command [options]\");\n\twarnx(\"options:\");\n\twarnx(\"\\t-b --bus i2cbus (%d)\", PX4_I2C_BUS_DEFAULT);\n\twarnx(\"command:\");\n\twarnx(\"\\tstart|stop|reset|test|info\");\n}\n\nint\nets_airspeed_main(int argc, char *argv[])\n{\n\tint i2c_bus = PX4_I2C_BUS_DEFAULT;\n\n\tint i;\n\n\tfor (i = 1; i < argc; i++) {\n\t\tif (strcmp(argv[i], \"-b\") == 0 || strcmp(argv[i], \"--bus\") == 0) {\n\t\t\tif (argc > i + 1) {\n\t\t\t\ti2c_bus = atoi(argv[i + 1]);\n\t\t\t}\n\t\t}\n\t}\n\n\t\/*\n\t * Start\/load the driver.\n\t *\/\n\tif (!strcmp(argv[1], \"start\"))\n\t\tets_airspeed::start(i2c_bus);\n\n\t\/*\n\t * Stop the driver\n\t *\/\n\tif (!strcmp(argv[1], \"stop\"))\n\t\tets_airspeed::stop();\n\n\t\/*\n\t * Test the driver\/device.\n\t *\/\n\tif (!strcmp(argv[1], \"test\"))\n\t\tets_airspeed::test();\n\n\t\/*\n\t * Reset the driver.\n\t *\/\n\tif (!strcmp(argv[1], \"reset\"))\n\t\tets_airspeed::reset();\n\n\t\/*\n\t * Print driver information.\n\t *\/\n\tif (!strcmp(argv[1], \"info\") || !strcmp(argv[1], \"status\"))\n\t\tets_airspeed::info();\n\n\tets_airspeed_usage();\n\texit(0);\n}\n<commit_msg>Remove voltage field for digital sensors<commit_after>\/****************************************************************************\n *\n * Copyright (c) 2013, 2014 PX4 Development Team. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in\n * the documentation and\/or other materials provided with the\n * distribution.\n * 3. Neither the name PX4 nor the names of its contributors may be\n * used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS\n * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED\n * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n ****************************************************************************\/\n\n\/**\n * @file ets_airspeed.cpp\n * @author Simon Wilks\n *\n * Driver for the Eagle Tree Airspeed V3 connected via I2C.\n *\/\n\n#include <nuttx\/config.h>\n\n#include <drivers\/device\/i2c.h>\n\n#include <sys\/types.h>\n#include <stdint.h>\n#include <stdlib.h>\n#include <stdbool.h>\n#include <semaphore.h>\n#include <string.h>\n#include <fcntl.h>\n#include <poll.h>\n#include <errno.h>\n#include <stdio.h>\n#include <math.h>\n#include <unistd.h>\n\n#include <nuttx\/arch.h>\n#include <nuttx\/wqueue.h>\n#include <nuttx\/clock.h>\n\n#include <board_config.h>\n\n#include <systemlib\/airspeed.h>\n#include <systemlib\/err.h>\n#include <systemlib\/param\/param.h>\n#include <systemlib\/perf_counter.h>\n\n#include <drivers\/drv_airspeed.h>\n#include <drivers\/drv_hrt.h>\n#include <drivers\/device\/ringbuffer.h>\n\n#include <uORB\/uORB.h>\n#include <uORB\/topics\/differential_pressure.h>\n#include <uORB\/topics\/subsystem_info.h>\n#include <drivers\/airspeed\/airspeed.h>\n\n\/* I2C bus address *\/\n#define I2C_ADDRESS\t0x75\t\/* 7-bit address. 8-bit address is 0xEA *\/\n#define ETS_PATH\t\"\/dev\/ets_airspeed\"\n\n\/* Register address *\/\n#define READ_CMD\t0x07\t\/* Read the data *\/\n\n\/**\n * The Eagle Tree Airspeed V3 cannot provide accurate reading below speeds of 15km\/h.\n * You can set this value to 12 if you want a zero reading below 15km\/h.\n *\/\n#define MIN_ACCURATE_DIFF_PRES_PA 0\n\n\/* Measurement rate is 100Hz *\/\n#define CONVERSION_INTERVAL\t(1000000 \/ 100)\t\/* microseconds *\/\n\nclass ETSAirspeed : public Airspeed\n{\npublic:\n\tETSAirspeed(int bus, int address = I2C_ADDRESS, const char* path = ETS_PATH);\n\nprotected:\n\n\t\/**\n\t* Perform a poll cycle; collect from the previous measurement\n\t* and start a new one.\n\t*\/\n\tvirtual void\tcycle();\n\tvirtual int\tmeasure();\n\tvirtual int\tcollect();\n\n};\n\n\/*\n * Driver 'main' command.\n *\/\nextern \"C\" __EXPORT int ets_airspeed_main(int argc, char *argv[]);\n\nETSAirspeed::ETSAirspeed(int bus, int address, const char* path) : Airspeed(bus, address,\n\tCONVERSION_INTERVAL, path)\n{\n\n}\n\nint\nETSAirspeed::measure()\n{\n\tint ret;\n\n\t\/*\n\t * Send the command to begin a measurement.\n\t *\/\n\tuint8_t cmd = READ_CMD;\n\tret = transfer(&cmd, 1, nullptr, 0);\n\n\tif (OK != ret) {\n\t\tperf_count(_comms_errors);\n\t}\n\n\treturn ret;\n}\n\nint\nETSAirspeed::collect()\n{\n\tint\tret = -EIO;\n\n\t\/* read from the sensor *\/\n\tuint8_t val[2] = {0, 0};\n\n\tperf_begin(_sample_perf);\n\n\tret = transfer(nullptr, 0, &val[0], 2);\n\n\tif (ret < 0) {\n\t\tperf_count(_comms_errors);\n\t\treturn ret;\n\t}\n\n\tuint16_t diff_pres_pa_raw = val[1] << 8 | val[0];\n\tuint16_t diff_pres_pa;\n if (diff_pres_pa_raw == 0) {\n\t\t\/\/ a zero value means the pressure sensor cannot give us a\n\t\t\/\/ value. We need to return, and not report a value or the\n\t\t\/\/ caller could end up using this value as part of an\n\t\t\/\/ average\n\t\tperf_count(_comms_errors);\n\t\tlog(\"zero value from sensor\"); \n\t\treturn -1;\n }\n\n\tif (diff_pres_pa_raw < _diff_pres_offset + MIN_ACCURATE_DIFF_PRES_PA) {\n\t\tdiff_pres_pa = 0;\n\t} else {\n\t\tdiff_pres_pa = diff_pres_pa_raw - _diff_pres_offset;\n\t}\n\n\t\/\/ Track maximum differential pressure measured (so we can work out top speed).\n\tif (diff_pres_pa > _max_differential_pressure_pa) {\n\t\t_max_differential_pressure_pa = diff_pres_pa;\n\t}\n\n\tdifferential_pressure_s report;\n\treport.timestamp = hrt_absolute_time();\n report.error_count = perf_event_count(_comms_errors);\n\treport.differential_pressure_pa = (float)diff_pres_pa;\n\n\t\/\/ XXX we may want to smooth out the readings to remove noise.\n\treport.differential_pressure_filtered_pa = (float)diff_pres_pa;\n\treport.differential_pressure_raw_pa = (float)diff_pres_pa_raw;\n\treport.temperature = -1000.0f;\n\treport.max_differential_pressure_pa = _max_differential_pressure_pa;\n\n\tif (_airspeed_pub > 0 && !(_pub_blocked)) {\n\t\t\/* publish it *\/\n\t\torb_publish(ORB_ID(differential_pressure), _airspeed_pub, &report);\n\t}\n\n\tnew_report(report);\n\n\t\/* notify anyone waiting for data *\/\n\tpoll_notify(POLLIN);\n\n\tret = OK;\n\n\tperf_end(_sample_perf);\n\n\treturn ret;\n}\n\nvoid\nETSAirspeed::cycle()\n{\n\tint ret;\n\n\t\/* collection phase? *\/\n\tif (_collect_phase) {\n\n\t\t\/* perform collection *\/\n\t\tret = collect();\n\t\tif (OK != ret) {\n\t\t\tperf_count(_comms_errors);\n\t\t\t\/* restart the measurement state machine *\/\n\t\t\tstart();\n\t\t\t_sensor_ok = false;\n\t\t\treturn;\n\t\t}\n\n\t\t\/* next phase is measurement *\/\n\t\t_collect_phase = false;\n\n\t\t\/*\n\t\t * Is there a collect->measure gap?\n\t\t *\/\n\t\tif (_measure_ticks > USEC2TICK(CONVERSION_INTERVAL)) {\n\n\t\t\t\/* schedule a fresh cycle call when we are ready to measure again *\/\n\t\t\twork_queue(HPWORK,\n\t\t\t\t &_work,\n\t\t\t\t (worker_t)&Airspeed::cycle_trampoline,\n\t\t\t\t this,\n\t\t\t\t _measure_ticks - USEC2TICK(CONVERSION_INTERVAL));\n\n\t\t\treturn;\n\t\t}\n\t}\n\n\t\/* measurement phase *\/\n\tret = measure();\n\tif (OK != ret) {\n\t\tdebug(\"measure error\");\n\t}\n\n\t_sensor_ok = (ret == OK);\n\n\t\/* next phase is collection *\/\n\t_collect_phase = true;\n\n\t\/* schedule a fresh cycle call when the measurement is done *\/\n\twork_queue(HPWORK,\n\t\t &_work,\n\t\t (worker_t)&Airspeed::cycle_trampoline,\n\t\t this,\n\t\t USEC2TICK(CONVERSION_INTERVAL));\n}\n\n\/**\n * Local functions in support of the shell command.\n *\/\nnamespace ets_airspeed\n{\n\n\/* oddly, ERROR is not defined for c++ *\/\n#ifdef ERROR\n# undef ERROR\n#endif\nconst int ERROR = -1;\n\nETSAirspeed\t*g_dev;\n\nvoid\tstart(int i2c_bus);\nvoid\tstop();\nvoid\ttest();\nvoid\treset();\nvoid\tinfo();\n\n\/**\n * Start the driver.\n *\/\nvoid\nstart(int i2c_bus)\n{\n\tint fd;\n\n\tif (g_dev != nullptr)\n\t\terrx(1, \"already started\");\n\n\t\/* create the driver *\/\n\tg_dev = new ETSAirspeed(i2c_bus);\n\n\tif (g_dev == nullptr)\n\t\tgoto fail;\n\n\tif (OK != g_dev->Airspeed::init())\n\t\tgoto fail;\n\n\t\/* set the poll rate to default, starts automatic data collection *\/\n\tfd = open(AIRSPEED_DEVICE_PATH, O_RDONLY);\n\n\tif (fd < 0)\n\t\tgoto fail;\n\n\tif (ioctl(fd, SENSORIOCSPOLLRATE, SENSOR_POLLRATE_DEFAULT) < 0)\n\t\tgoto fail;\n\n\texit(0);\n\nfail:\n\n\tif (g_dev != nullptr) {\n\t\tdelete g_dev;\n\t\tg_dev = nullptr;\n\t}\n\n\terrx(1, \"no ETS airspeed sensor connected\");\n}\n\n\/**\n * Stop the driver\n *\/\nvoid\nstop()\n{\n\tif (g_dev != nullptr) {\n\t\tdelete g_dev;\n\t\tg_dev = nullptr;\n\n\t} else {\n\t\terrx(1, \"driver not running\");\n\t}\n\n\texit(0);\n}\n\n\/**\n * Perform some basic functional tests on the driver;\n * make sure we can collect data from the sensor in polled\n * and automatic modes.\n *\/\nvoid\ntest()\n{\n\tstruct differential_pressure_s report;\n\tssize_t sz;\n\tint ret;\n\n\tint fd = open(AIRSPEED_DEVICE_PATH, O_RDONLY);\n\n\tif (fd < 0)\n\t\terr(1, \"%s open failed (try 'ets_airspeed start' if the driver is not running\", AIRSPEED_DEVICE_PATH);\n\n\t\/* do a simple demand read *\/\n\tsz = read(fd, &report, sizeof(report));\n\n\tif (sz != sizeof(report))\n\t\terr(1, \"immediate read failed\");\n\n\twarnx(\"single read\");\n\twarnx(\"diff pressure: %f pa\", (double)report.differential_pressure_pa);\n\n\t\/* start the sensor polling at 2Hz *\/\n\tif (OK != ioctl(fd, SENSORIOCSPOLLRATE, 2))\n\t\terrx(1, \"failed to set 2Hz poll rate\");\n\n\t\/* read the sensor 5x and report each value *\/\n\tfor (unsigned i = 0; i < 5; i++) {\n\t\tstruct pollfd fds;\n\n\t\t\/* wait for data to be ready *\/\n\t\tfds.fd = fd;\n\t\tfds.events = POLLIN;\n\t\tret = poll(&fds, 1, 2000);\n\n\t\tif (ret != 1)\n\t\t\terrx(1, \"timed out waiting for sensor data\");\n\n\t\t\/* now go get it *\/\n\t\tsz = read(fd, &report, sizeof(report));\n\n\t\tif (sz != sizeof(report))\n\t\t\terr(1, \"periodic read failed\");\n\n\t\twarnx(\"periodic read %u\", i);\n\t\twarnx(\"diff pressure: %f pa\", (double)report.differential_pressure_pa);\n\t}\n\n\t\/* reset the sensor polling to its default rate *\/\n\tif (OK != ioctl(fd, SENSORIOCSPOLLRATE, SENSOR_POLLRATE_DEFAULT))\n\t\terrx(1, \"failed to set default rate\");\n\n\terrx(0, \"PASS\");\n}\n\n\/**\n * Reset the driver.\n *\/\nvoid\nreset()\n{\n\tint fd = open(AIRSPEED_DEVICE_PATH, O_RDONLY);\n\n\tif (fd < 0)\n\t\terr(1, \"failed \");\n\n\tif (ioctl(fd, SENSORIOCRESET, 0) < 0)\n\t\terr(1, \"driver reset failed\");\n\n\tif (ioctl(fd, SENSORIOCSPOLLRATE, SENSOR_POLLRATE_DEFAULT) < 0)\n\t\terr(1, \"driver poll restart failed\");\n\n\texit(0);\n}\n\n\/**\n * Print a little info about the driver.\n *\/\nvoid\ninfo()\n{\n\tif (g_dev == nullptr)\n\t\terrx(1, \"driver not running\");\n\n\tprintf(\"state @ %p\\n\", g_dev);\n\tg_dev->print_info();\n\n\texit(0);\n}\n\n} \/\/ namespace\n\n\nstatic void\nets_airspeed_usage()\n{\n\twarnx(\"usage: ets_airspeed command [options]\");\n\twarnx(\"options:\");\n\twarnx(\"\\t-b --bus i2cbus (%d)\", PX4_I2C_BUS_DEFAULT);\n\twarnx(\"command:\");\n\twarnx(\"\\tstart|stop|reset|test|info\");\n}\n\nint\nets_airspeed_main(int argc, char *argv[])\n{\n\tint i2c_bus = PX4_I2C_BUS_DEFAULT;\n\n\tint i;\n\n\tfor (i = 1; i < argc; i++) {\n\t\tif (strcmp(argv[i], \"-b\") == 0 || strcmp(argv[i], \"--bus\") == 0) {\n\t\t\tif (argc > i + 1) {\n\t\t\t\ti2c_bus = atoi(argv[i + 1]);\n\t\t\t}\n\t\t}\n\t}\n\n\t\/*\n\t * Start\/load the driver.\n\t *\/\n\tif (!strcmp(argv[1], \"start\"))\n\t\tets_airspeed::start(i2c_bus);\n\n\t\/*\n\t * Stop the driver\n\t *\/\n\tif (!strcmp(argv[1], \"stop\"))\n\t\tets_airspeed::stop();\n\n\t\/*\n\t * Test the driver\/device.\n\t *\/\n\tif (!strcmp(argv[1], \"test\"))\n\t\tets_airspeed::test();\n\n\t\/*\n\t * Reset the driver.\n\t *\/\n\tif (!strcmp(argv[1], \"reset\"))\n\t\tets_airspeed::reset();\n\n\t\/*\n\t * Print driver information.\n\t *\/\n\tif (!strcmp(argv[1], \"info\") || !strcmp(argv[1], \"status\"))\n\t\tets_airspeed::info();\n\n\tets_airspeed_usage();\n\texit(0);\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/-----------------------------------------------------------------------bl-\n\/\/--------------------------------------------------------------------------\n\/\/ \n\/\/ GRINS - General Reacting Incompressible Navier-Stokes \n\/\/\n\/\/ Copyright (C) 2010-2013 The PECOS Development Team\n\/\/\n\/\/ This library is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the Version 2.1 GNU Lesser General\n\/\/ Public License as published by the Free Software Foundation.\n\/\/\n\/\/ This library is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ Lesser General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License along with this library; if not, write to the Free Software\n\/\/ Foundation, Inc. 51 Franklin Street, Fifth Floor,\n\/\/ Boston, MA 02110-1301 USA\n\/\/\n\/\/-----------------------------------------------------------------------el-\n\n\/\/ This class\n#include \"grins\/steady_mesh_adaptive_solver.h\"\n\n\/\/ GRINS\n#include \"grins\/solver_context.h\"\n#include \"grins\/multiphysics_sys.h\"\n\n\/\/ libMesh\n#include \"libmesh\/error_vector.h\"\n#include \"libmesh\/steady_solver.h\"\n\nnamespace GRINS\n{\n\n SteadyMeshAdaptiveSolver::SteadyMeshAdaptiveSolver( const GetPot& input )\n : MeshAdaptiveSolverBase( input )\n {\n return;\n }\n\n SteadyMeshAdaptiveSolver::~SteadyMeshAdaptiveSolver()\n {\n return;\n }\n\n void SteadyMeshAdaptiveSolver::init_time_solver( MultiphysicsSystem* system )\n {\n libMesh::SteadySolver* time_solver = new libMesh::SteadySolver( *(system) );\n\n system->time_solver = libMesh::AutoPtr<libMesh::TimeSolver>( time_solver );\n\n return;\n }\n\n void SteadyMeshAdaptiveSolver::solve( SolverContext& context )\n {\n \/\/ Mesh and mesh refinement\n libMesh::MeshBase& mesh = context.equation_system->get_mesh();\n this->build_mesh_refinement( mesh );\n\n \/\/ This output cannot be toggled in the input file.\n out << \"Performing \" << this->_max_r_steps << \" adaptive refinements\" << std::endl;\n\n \/\/ GRVY timers contained in here (if enabled)\n for ( unsigned int r_step = 0; r_step < this->_max_r_steps; r_step++ )\n {\n \/\/ Solve the forward problem\n context.system->solve();\n\n libMesh::NumericVector<Number>& primal_solution = *(context.system->solution);\n if( context.output_vis )\n {\n context.vis->output( context.equation_system );\n }\n\n \/\/ Solve adjoint system\n context.system->adjoint_solve();\n\n \/\/ At the moment output data is overwritten every mesh refinement step\n if( output_vis && this->_output_adjoint_sol )\n {\n libMesh::NumericVector<Number>& dual_solution = context.system->get_adjoint_solution(0);\n\n \/\/ Swap primal and dual to write out dual solution\n primal_solution.swap( dual_solution ); \n vis->output( equation_system );\n primal_solution.swap( dual_solution ); \n }\n\n if( context.output_residual )\n {\n context.vis->output_residual( context.equation_system, context.system );\n }\n\n \/\/ Now we construct the data structures for the mesh refinement process \n libMesh::ErrorVector error;\n\n context.error_estimator->estimate_error( *context.system, error );\n\n \/\/ Plot error vector\n if( this->_plot_cell_errors )\n {\n error.plot_error( this->_error_plot_prefix+\".exo\", mesh );\n }\n \n if( this->_absolute_global_tolerance >= 0. && this->_nelem_target == 0.)\n {\n _mesh_refinement->flag_elements_by_error_tolerance( error );\n }\n \/\/ Adaptively refine based on reaching a target number of elements\n else\n {\n if( mesh.n_active_elem() >= this->_nelem_target )\n {\n std::cout<<\"We reached the target number of elements.\"<<std::endl <<std::endl;\n break;\n }\n \n _mesh_refinement->flag_elements_by_nelem_target( error );\n }\n _mesh_refinement->refine_and_coarsen_elements();\n \n \/\/ Dont forget to reinit the system after each adaptive refinement!\n equation_system->reinit();\n\n \/\/ This output cannot be toggled in the input file.\n std::cout << \"Refinement step \" << r_step+1 << \"\/\" << this->_max_r_steps\n << \": refined mesh to \" << mesh.n_active_elem() << \" elements.\"\n << std::endl << std::endl;\n }\n\n return;\n }\n\n} \/\/ end namespace GRINS\n<commit_msg>Check if we need to do the adjoint solve before actually doing the adjoint solve.<commit_after>\/\/-----------------------------------------------------------------------bl-\n\/\/--------------------------------------------------------------------------\n\/\/ \n\/\/ GRINS - General Reacting Incompressible Navier-Stokes \n\/\/\n\/\/ Copyright (C) 2010-2013 The PECOS Development Team\n\/\/\n\/\/ This library is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the Version 2.1 GNU Lesser General\n\/\/ Public License as published by the Free Software Foundation.\n\/\/\n\/\/ This library is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ Lesser General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License along with this library; if not, write to the Free Software\n\/\/ Foundation, Inc. 51 Franklin Street, Fifth Floor,\n\/\/ Boston, MA 02110-1301 USA\n\/\/\n\/\/-----------------------------------------------------------------------el-\n\n\/\/ This class\n#include \"grins\/steady_mesh_adaptive_solver.h\"\n\n\/\/ GRINS\n#include \"grins\/solver_context.h\"\n#include \"grins\/multiphysics_sys.h\"\n\n\/\/ libMesh\n#include \"libmesh\/error_vector.h\"\n#include \"libmesh\/steady_solver.h\"\n\nnamespace GRINS\n{\n\n SteadyMeshAdaptiveSolver::SteadyMeshAdaptiveSolver( const GetPot& input )\n : MeshAdaptiveSolverBase( input )\n {\n return;\n }\n\n SteadyMeshAdaptiveSolver::~SteadyMeshAdaptiveSolver()\n {\n return;\n }\n\n void SteadyMeshAdaptiveSolver::init_time_solver( MultiphysicsSystem* system )\n {\n libMesh::SteadySolver* time_solver = new libMesh::SteadySolver( *(system) );\n\n system->time_solver = libMesh::AutoPtr<libMesh::TimeSolver>( time_solver );\n\n return;\n }\n\n void SteadyMeshAdaptiveSolver::solve( SolverContext& context )\n {\n \/\/ Mesh and mesh refinement\n libMesh::MeshBase& mesh = context.equation_system->get_mesh();\n this->build_mesh_refinement( mesh );\n\n \/\/ This output cannot be toggled in the input file.\n out << \"Performing \" << this->_max_r_steps << \" adaptive refinements\" << std::endl;\n\n \/\/ GRVY timers contained in here (if enabled)\n for ( unsigned int r_step = 0; r_step < this->_max_r_steps; r_step++ )\n {\n \/\/ Solve the forward problem\n context.system->solve();\n\n libMesh::NumericVector<Number>& primal_solution = *(context.system->solution);\n if( context.output_vis )\n {\n context.vis->output( context.equation_system );\n }\n\n \/\/ Solve adjoint system\n if( _do_adjoint_solve )\n {\n context.system->adjoint_solve();\n }\n\n \/\/ At the moment output data is overwritten every mesh refinement step\n if( output_vis && this->_output_adjoint_sol && _do_adjoint_solve )\n {\n libMesh::NumericVector<Number>& dual_solution = context.system->get_adjoint_solution(0);\n\n \/\/ Swap primal and dual to write out dual solution\n primal_solution.swap( dual_solution ); \n vis->output( equation_system );\n primal_solution.swap( dual_solution ); \n }\n\n if( context.output_residual )\n {\n context.vis->output_residual( context.equation_system, context.system );\n }\n\n \/\/ Now we construct the data structures for the mesh refinement process \n libMesh::ErrorVector error;\n\n context.error_estimator->estimate_error( *context.system, error );\n\n \/\/ Plot error vector\n if( this->_plot_cell_errors )\n {\n error.plot_error( this->_error_plot_prefix+\".exo\", mesh );\n }\n \n if( this->_absolute_global_tolerance >= 0. && this->_nelem_target == 0.)\n {\n _mesh_refinement->flag_elements_by_error_tolerance( error );\n }\n \/\/ Adaptively refine based on reaching a target number of elements\n else\n {\n if( mesh.n_active_elem() >= this->_nelem_target )\n {\n std::cout<<\"We reached the target number of elements.\"<<std::endl <<std::endl;\n break;\n }\n \n _mesh_refinement->flag_elements_by_nelem_target( error );\n }\n _mesh_refinement->refine_and_coarsen_elements();\n \n \/\/ Dont forget to reinit the system after each adaptive refinement!\n equation_system->reinit();\n\n \/\/ This output cannot be toggled in the input file.\n std::cout << \"Refinement step \" << r_step+1 << \"\/\" << this->_max_r_steps\n << \": refined mesh to \" << mesh.n_active_elem() << \" elements.\"\n << std::endl << std::endl;\n\n } \/\/ r_step for-loop\n\n return;\n }\n\n} \/\/ end namespace GRINS\n<|endoftext|>"} {"text":"<commit_before>\/*=========================================================================\n\n Program: Visualization Toolkit\n Module: vtkXRenderWindow.cxx\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n\nCopyright (c) 1993-1996 Ken Martin, Will Schroeder, Bill Lorensen.\n\nThis software is copyrighted by Ken Martin, Will Schroeder and Bill Lorensen.\nThe following terms apply to all files associated with the software unless\nexplicitly disclaimed in individual files. This copyright specifically does\nnot apply to the related textbook \"The Visualization Toolkit\" ISBN\n013199837-4 published by Prentice Hall which is covered by its own copyright.\n\nThe authors hereby grant permission to use, copy, and distribute this\nsoftware and its documentation for any purpose, provided that existing\ncopyright notices are retained in all copies and that this notice is included\nverbatim in any distributions. Additionally, the authors grant permission to\nmodify this software and its documentation for any purpose, provided that\nsuch modifications are not distributed without the explicit consent of the\nauthors and that existing copyright notices are retained in all copies. Some\nof the algorithms implemented by this software are patented, observe all\napplicable patent law.\n\nIN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR\nDIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT\nOF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF,\nEVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\nTHE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING,\nBUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\nPARTICULAR PURPOSE, AND NON-INFRINGEMENT. THIS SOFTWARE IS PROVIDED ON AN\n\"AS IS\" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE\nMAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.\n\n\n=========================================================================*\/\n#include <math.h>\n#include <stdlib.h>\n#include <iostream.h>\n#include \"vtkXRenderWindow.h\"\n#include \"vtkXRenderWindowInteractor.h\"\n\nvtkXRenderWindow::vtkXRenderWindow()\n{\n this->DisplayId = (Display *)NULL;\n this->WindowId = (Window)NULL;\n this->NextWindowId = (Window)NULL;\n this->ColorMap = (Colormap)NULL;\n}\n\nvtkXRenderWindow::~vtkXRenderWindow()\n{\n if (this->Interactor) this->Interactor->Delete();\n}\n\n\/\/ Description:\n\/\/ Get the size of the screen in pixels\nint *vtkXRenderWindow::GetScreenSize()\n{\n \/\/ get the default display connection \n if (!this->DisplayId)\n {\n this->DisplayId = XOpenDisplay((char *)NULL); \n if (this->DisplayId == NULL) \n {\n vtkErrorMacro(<< \"bad X server connection.\\n\");\n }\n }\n\n this->ScreenSize[0] = \n DisplayWidth(this->DisplayId, DefaultScreen(this->DisplayId));\n this->ScreenSize[1] = \n DisplayHeight(this->DisplayId, DefaultScreen(this->DisplayId));\n\n return this->ScreenSize;\n}\n\n\/\/ Description:\n\/\/ Get the current size of the window in pixels.\nint *vtkXRenderWindow::GetSize(void)\n{\n XWindowAttributes attribs;\n\n \/\/ if we aren't mapped then just return the ivar \n if (!this->Mapped)\n {\n return(this->Size);\n }\n\n \/\/ Find the current window size \n XGetWindowAttributes(this->DisplayId, \n\t\t this->WindowId, &attribs);\n\n this->Size[0] = attribs.width;\n this->Size[1] = attribs.height;\n \n return this->Size;\n}\n\n\/\/ Description:\n\/\/ Get the position in screen coordinates (pixels) of the window.\nint *vtkXRenderWindow::GetPosition(void)\n{\n XWindowAttributes attribs;\n int x,y;\n Window child;\n \n \/\/ if we aren't mapped then just return the ivar \n if (!this->Mapped)\n {\n return(this->Position);\n }\n\n \/\/ Find the current window size \n XGetWindowAttributes(this->DisplayId, this->WindowId, &attribs);\n x = attribs.x;\n y = attribs.y;\n\n XTranslateCoordinates(this->DisplayId,this->WindowId,\n\t\t RootWindowOfScreen(ScreenOfDisplay(this->DisplayId,0)),\n\t\t\tx,y,&this->Position[0],&this->Position[1],&child);\n\n return this->Position;\n}\n\n\/\/ Description:\n\/\/ Get this RenderWindow's X display id.\nDisplay *vtkXRenderWindow::GetDisplayId()\n{\n vtkDebugMacro(<< \"Returning DisplayId of \" << (void *)this->DisplayId << \"\\n\"); \n\n return this->DisplayId;\n}\n\n\/\/ Description:\n\/\/ Get this RenderWindow's X window id.\nWindow vtkXRenderWindow::GetWindowId()\n{\n vtkDebugMacro(<< \"Returning WindowId of \" << (void *)this->WindowId << \"\\n\"); \n\n return this->WindowId;\n}\n\n\/\/ Description:\n\/\/ Set this RenderWindow's X window id to a pre-existing window.\nvoid vtkXRenderWindow::SetWindowId(Window arg)\n{\n vtkDebugMacro(<< \"Setting WindowId to \" << (void *)arg << \"\\n\"); \n\n this->WindowId = arg;\n}\nvoid vtkXRenderWindow::SetWindowId(void *arg)\n{\n this->SetWindowId((Window)arg);\n}\n\n\/\/ Description:\n\/\/ Specify the X window id to use if a WindowRemap is done.\nvoid vtkXRenderWindow::SetNextWindowId(Window arg)\n{\n vtkDebugMacro(<< \"Setting NextWindowId to \" << (void *)arg << \"\\n\"); \n\n this->NextWindowId = arg;\n}\n\n\/\/ Description:\n\/\/ Set the X display id for this RenderWindow to use to a pre-existing \n\/\/ X display id.\nvoid vtkXRenderWindow::SetDisplayId(Display *arg)\n{\n vtkDebugMacro(<< \"Setting DisplayId to \" << (void *)arg << \"\\n\"); \n\n this->DisplayId = arg;\n}\nvoid vtkXRenderWindow::SetDisplayId(void *arg)\n{\n this->SetDisplayId((Display *)arg);\n}\n\n\/\/ Description:\n\/\/ Create an interactor that will work with this renderer.\n\/\/ Since all subclasses of this class will be running on\n\/\/ machines that are running X Windows. The correct vtkRenderWindowInteractor\n\/\/ is the vtkXRenderWindowInteractor. So this object creates one, then type \n\/\/ casts it and returns a pointer to it.\nvtkRenderWindowInteractor *vtkXRenderWindow::MakeRenderWindowInteractor()\n{\n this->Interactor = (vtkRenderWindowInteractor *)new vtkXRenderWindowInteractor;\n this->Interactor->SetRenderWindow((vtkRenderWindow *)this);\n return this->Interactor;\n}\n\nvoid vtkXRenderWindow::PrintSelf(ostream& os, vtkIndent indent)\n{\n this->vtkRenderWindow::PrintSelf(os,indent);\n\n os << indent << \"Color Map: \" << this->ColorMap << \"\\n\";\n os << indent << \"Display Id: \" << this->GetDisplayId() << \"\\n\";\n os << indent << \"Next Window Id: \" << this->NextWindowId << \"\\n\";\n os << indent << \"Window Id: \" << this->GetWindowId() << \"\\n\";\n}\n\n<commit_msg>minor init fix<commit_after>\/*=========================================================================\n\n Program: Visualization Toolkit\n Module: vtkXRenderWindow.cxx\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n\nCopyright (c) 1993-1996 Ken Martin, Will Schroeder, Bill Lorensen.\n\nThis software is copyrighted by Ken Martin, Will Schroeder and Bill Lorensen.\nThe following terms apply to all files associated with the software unless\nexplicitly disclaimed in individual files. This copyright specifically does\nnot apply to the related textbook \"The Visualization Toolkit\" ISBN\n013199837-4 published by Prentice Hall which is covered by its own copyright.\n\nThe authors hereby grant permission to use, copy, and distribute this\nsoftware and its documentation for any purpose, provided that existing\ncopyright notices are retained in all copies and that this notice is included\nverbatim in any distributions. Additionally, the authors grant permission to\nmodify this software and its documentation for any purpose, provided that\nsuch modifications are not distributed without the explicit consent of the\nauthors and that existing copyright notices are retained in all copies. Some\nof the algorithms implemented by this software are patented, observe all\napplicable patent law.\n\nIN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR\nDIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT\nOF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF,\nEVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\nTHE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING,\nBUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\nPARTICULAR PURPOSE, AND NON-INFRINGEMENT. THIS SOFTWARE IS PROVIDED ON AN\n\"AS IS\" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE\nMAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.\n\n\n=========================================================================*\/\n#include <math.h>\n#include <stdlib.h>\n#include <iostream.h>\n#include \"vtkXRenderWindow.h\"\n#include \"vtkXRenderWindowInteractor.h\"\n\nvtkXRenderWindow::vtkXRenderWindow()\n{\n this->DisplayId = (Display *)NULL;\n this->WindowId = (Window)NULL;\n this->NextWindowId = (Window)NULL;\n this->ColorMap = (Colormap)NULL;\n this->ScreenSize[0] = 0;\n this->ScreenSize[1] = 0;\n}\n\nvtkXRenderWindow::~vtkXRenderWindow()\n{\n if (this->Interactor) this->Interactor->Delete();\n}\n\n\/\/ Description:\n\/\/ Get the size of the screen in pixels\nint *vtkXRenderWindow::GetScreenSize()\n{\n \/\/ get the default display connection \n if (!this->DisplayId)\n {\n this->DisplayId = XOpenDisplay((char *)NULL); \n if (this->DisplayId == NULL) \n {\n vtkErrorMacro(<< \"bad X server connection.\\n\");\n }\n }\n\n this->ScreenSize[0] = \n DisplayWidth(this->DisplayId, DefaultScreen(this->DisplayId));\n this->ScreenSize[1] = \n DisplayHeight(this->DisplayId, DefaultScreen(this->DisplayId));\n\n return this->ScreenSize;\n}\n\n\/\/ Description:\n\/\/ Get the current size of the window in pixels.\nint *vtkXRenderWindow::GetSize(void)\n{\n XWindowAttributes attribs;\n\n \/\/ if we aren't mapped then just return the ivar \n if (!this->Mapped)\n {\n return(this->Size);\n }\n\n \/\/ Find the current window size \n XGetWindowAttributes(this->DisplayId, \n\t\t this->WindowId, &attribs);\n\n this->Size[0] = attribs.width;\n this->Size[1] = attribs.height;\n \n return this->Size;\n}\n\n\/\/ Description:\n\/\/ Get the position in screen coordinates (pixels) of the window.\nint *vtkXRenderWindow::GetPosition(void)\n{\n XWindowAttributes attribs;\n int x,y;\n Window child;\n \n \/\/ if we aren't mapped then just return the ivar \n if (!this->Mapped)\n {\n return(this->Position);\n }\n\n \/\/ Find the current window size \n XGetWindowAttributes(this->DisplayId, this->WindowId, &attribs);\n x = attribs.x;\n y = attribs.y;\n\n XTranslateCoordinates(this->DisplayId,this->WindowId,\n\t\t RootWindowOfScreen(ScreenOfDisplay(this->DisplayId,0)),\n\t\t\tx,y,&this->Position[0],&this->Position[1],&child);\n\n return this->Position;\n}\n\n\/\/ Description:\n\/\/ Get this RenderWindow's X display id.\nDisplay *vtkXRenderWindow::GetDisplayId()\n{\n vtkDebugMacro(<< \"Returning DisplayId of \" << (void *)this->DisplayId << \"\\n\"); \n\n return this->DisplayId;\n}\n\n\/\/ Description:\n\/\/ Get this RenderWindow's X window id.\nWindow vtkXRenderWindow::GetWindowId()\n{\n vtkDebugMacro(<< \"Returning WindowId of \" << (void *)this->WindowId << \"\\n\"); \n\n return this->WindowId;\n}\n\n\/\/ Description:\n\/\/ Set this RenderWindow's X window id to a pre-existing window.\nvoid vtkXRenderWindow::SetWindowId(Window arg)\n{\n vtkDebugMacro(<< \"Setting WindowId to \" << (void *)arg << \"\\n\"); \n\n this->WindowId = arg;\n}\nvoid vtkXRenderWindow::SetWindowId(void *arg)\n{\n this->SetWindowId((Window)arg);\n}\n\n\/\/ Description:\n\/\/ Specify the X window id to use if a WindowRemap is done.\nvoid vtkXRenderWindow::SetNextWindowId(Window arg)\n{\n vtkDebugMacro(<< \"Setting NextWindowId to \" << (void *)arg << \"\\n\"); \n\n this->NextWindowId = arg;\n}\n\n\/\/ Description:\n\/\/ Set the X display id for this RenderWindow to use to a pre-existing \n\/\/ X display id.\nvoid vtkXRenderWindow::SetDisplayId(Display *arg)\n{\n vtkDebugMacro(<< \"Setting DisplayId to \" << (void *)arg << \"\\n\"); \n\n this->DisplayId = arg;\n}\nvoid vtkXRenderWindow::SetDisplayId(void *arg)\n{\n this->SetDisplayId((Display *)arg);\n}\n\n\/\/ Description:\n\/\/ Create an interactor that will work with this renderer.\n\/\/ Since all subclasses of this class will be running on\n\/\/ machines that are running X Windows. The correct vtkRenderWindowInteractor\n\/\/ is the vtkXRenderWindowInteractor. So this object creates one, then type \n\/\/ casts it and returns a pointer to it.\nvtkRenderWindowInteractor *vtkXRenderWindow::MakeRenderWindowInteractor()\n{\n this->Interactor = (vtkRenderWindowInteractor *)new vtkXRenderWindowInteractor;\n this->Interactor->SetRenderWindow((vtkRenderWindow *)this);\n return this->Interactor;\n}\n\nvoid vtkXRenderWindow::PrintSelf(ostream& os, vtkIndent indent)\n{\n this->vtkRenderWindow::PrintSelf(os,indent);\n\n os << indent << \"Color Map: \" << this->ColorMap << \"\\n\";\n os << indent << \"Display Id: \" << this->GetDisplayId() << \"\\n\";\n os << indent << \"Next Window Id: \" << this->NextWindowId << \"\\n\";\n os << indent << \"Window Id: \" << this->GetWindowId() << \"\\n\";\n}\n\n<|endoftext|>"} {"text":"<commit_before><commit_msg>Explicitly ask for unsigned values when comparing addresses. Not only is this code hard to understand (and possibly broken) otherwise, some versions of GCC complain about the comparison without the cast.<commit_after><|endoftext|>"} {"text":"<commit_before>\/\/ RUN: %clang_cc1 -fsyntax-only -verify -faccess-control %s\nstruct A {};\nstruct B : public A {}; \/\/ Single public base.\nstruct C1 : public virtual B {}; \/\/ Single virtual base.\nstruct C2 : public virtual B {};\nstruct D : public C1, public C2 {}; \/\/ Diamond\nstruct E : private A {}; \/\/ Single private base. expected-note 3 {{'private' inheritance specifier here}}\nstruct F : public C1 {}; \/\/ Single path to B with virtual.\nstruct G1 : public B {};\nstruct G2 : public B {};\nstruct H : public G1, public G2 {}; \/\/ Ambiguous path to B.\n\nenum Enum { En1, En2 };\nenum Onom { On1, On2 };\n\nstruct Co1 { operator int(); };\nstruct Co2 { Co2(int); };\nstruct Co3 { };\nstruct Co4 { Co4(Co3); operator Co3(); };\n\n\/\/ Explicit implicits\nvoid t_529_2()\n{\n int i = 1;\n (void)static_cast<float>(i);\n double d = 1.0;\n (void)static_cast<float>(d);\n (void)static_cast<int>(d);\n (void)static_cast<char>(i);\n (void)static_cast<unsigned long>(i);\n (void)static_cast<int>(En1);\n (void)static_cast<double>(En1);\n (void)static_cast<int&>(i);\n (void)static_cast<const int&>(i);\n\n int ar[1];\n (void)static_cast<const int*>(ar);\n (void)static_cast<void (*)()>(t_529_2);\n\n (void)static_cast<void*>(0);\n (void)static_cast<void*>((int*)0);\n (void)static_cast<volatile const void*>((const int*)0);\n (void)static_cast<A*>((B*)0);\n (void)static_cast<A&>(*((B*)0));\n (void)static_cast<const B*>((C1*)0);\n (void)static_cast<B&>(*((C1*)0));\n (void)static_cast<A*>((D*)0);\n (void)static_cast<const A&>(*((D*)0));\n (void)static_cast<int B::*>((int A::*)0);\n (void)static_cast<void (B::*)()>((void (A::*)())0);\n\n (void)static_cast<int>(Co1());\n (void)static_cast<Co2>(1);\n (void)static_cast<Co3>(static_cast<Co4>(Co3()));\n\n \/\/ Bad code below\n\n (void)static_cast<void*>((const int*)0); \/\/ expected-error {{static_cast from 'int const *' to 'void *' is not allowed}}\n (void)static_cast<A*>((E*)0); \/\/ expected-error {{inaccessible base class 'struct A'}}\n (void)static_cast<A*>((H*)0); \/\/ expected-error {{ambiguous conversion}}\n (void)static_cast<int>((int*)0); \/\/ expected-error {{static_cast from 'int *' to 'int' is not allowed}}\n (void)static_cast<A**>((B**)0); \/\/ expected-error {{static_cast from 'struct B **' to 'struct A **' is not allowed}}\n (void)static_cast<char&>(i); \/\/ expected-error {{non-const lvalue reference to type 'char' cannot be initialized with a value of type 'int'}}\n}\n\n\/\/ Anything to void\nvoid t_529_4()\n{\n static_cast<void>(1);\n static_cast<void>(t_529_4);\n}\n\n\/\/ Static downcasts\nvoid t_529_5_8()\n{\n (void)static_cast<B*>((A*)0);\n (void)static_cast<B&>(*((A*)0));\n (void)static_cast<const G1*>((A*)0);\n (void)static_cast<const G1&>(*((A*)0));\n\n \/\/ Bad code below\n\n (void)static_cast<C1*>((A*)0); \/\/ expected-error {{cannot cast 'struct A *' to 'struct C1 *' via virtual base 'struct B'}}\n (void)static_cast<C1&>(*((A*)0)); \/\/ expected-error {{cannot cast 'struct A' to 'struct C1 &' via virtual base 'struct B'}}\n (void)static_cast<D*>((A*)0); \/\/ expected-error {{cannot cast 'struct A *' to 'struct D *' via virtual base 'struct B'}}\n (void)static_cast<D&>(*((A*)0)); \/\/ expected-error {{cannot cast 'struct A' to 'struct D &' via virtual base 'struct B'}}\n (void)static_cast<B*>((const A*)0); \/\/ expected-error {{static_cast from 'struct A const *' to 'struct B *' casts away constness}}\n (void)static_cast<B&>(*((const A*)0)); \/\/ expected-error {{static_cast from 'struct A const' to 'struct B &' casts away constness}}\n (void)static_cast<E*>((A*)0); \/\/ expected-error {{cannot cast 'struct A' to 'struct E' due to inaccessible}}\n (void)static_cast<E&>(*((A*)0)); \/\/ expected-error {{cannot cast 'struct A' to 'struct E' due to inaccessible}}\n (void)static_cast<H*>((A*)0); \/\/ expected-error {{ambiguous cast from base 'struct A' to derived 'struct H':\\n struct A -> struct B -> struct G1 -> struct H\\n struct A -> struct B -> struct G2 -> struct H}}\n (void)static_cast<H&>(*((A*)0)); \/\/ expected-error {{ambiguous cast from base 'struct A' to derived 'struct H':\\n struct A -> struct B -> struct G1 -> struct H\\n struct A -> struct B -> struct G2 -> struct H}}\n (void)static_cast<E*>((B*)0); \/\/ expected-error {{static_cast from 'struct B *' to 'struct E *' is not allowed}}\n (void)static_cast<E&>(*((B*)0)); \/\/ expected-error {{non-const lvalue reference to type 'struct E' cannot be initialized with a value of type 'struct B'}}\n\n \/\/ TODO: Test inaccessible base in context where it's accessible, i.e.\n \/\/ member function and friend.\n\n \/\/ TODO: Test DR427. This requires user-defined conversions, though.\n}\n\n\/\/ Enum conversions\nvoid t_529_7()\n{\n (void)static_cast<Enum>(1);\n (void)static_cast<Enum>(1.0);\n (void)static_cast<Onom>(En1);\n\n \/\/ Bad code below\n\n (void)static_cast<Enum>((int*)0); \/\/ expected-error {{static_cast from 'int *' to 'enum Enum' is not allowed}}\n}\n\n\/\/ Void pointer to object pointer\nvoid t_529_10()\n{\n (void)static_cast<int*>((void*)0);\n (void)static_cast<const A*>((void*)0);\n\n \/\/ Bad code below\n\n (void)static_cast<int*>((const void*)0); \/\/ expected-error {{static_cast from 'void const *' to 'int *' casts away constness}}\n (void)static_cast<void (*)()>((void*)0); \/\/ expected-error {{static_cast from 'void *' to 'void (*)()' is not allowed}}\n}\n\n\/\/ Member pointer upcast.\nvoid t_529_9()\n{\n (void)static_cast<int A::*>((int B::*)0);\n\n \/\/ Bad code below\n (void)static_cast<int A::*>((int H::*)0); \/\/ expected-error {{ambiguous conversion from pointer to member of derived class 'struct H'}}\n (void)static_cast<int A::*>((int F::*)0); \/\/ expected-error {{conversion from pointer to member of class 'struct F'}}\n}\n\n\/\/ PR 5261 - static_cast should instantiate template if possible\nnamespace pr5261 {\n struct base {};\n template<typename E> struct derived : public base {};\n template<typename E> struct outer {\n base *pb;\n ~outer() { (void)static_cast<derived<E>*>(pb); }\n };\n outer<int> EntryList;\n}\n\n\n\/\/ Initialization by constructor\nstruct X0;\n\nstruct X1 {\n X1();\n X1(X1&);\n X1(const X0&);\n \n operator X0() const;\n};\n\nstruct X0 { };\n\nvoid test_ctor_init() {\n (void)static_cast<X1>(X1());\n}\n\n\/\/ Casting away constness\nstruct X2 {\n};\n\nstruct X3 : X2 {\n};\n\nstruct X4 {\n typedef const X3 X3_typedef;\n \n void f() const {\n (void)static_cast<X3_typedef*>(x2);\n }\n \n const X2 *x2;\n};\n\n\/\/ PR5897 - accept static_cast from const void* to const int (*)[1].\nvoid PR5879() { (void)static_cast<const int(*)[1]>((const void*)0); }\n<commit_msg>Fix my dyslexia.<commit_after>\/\/ RUN: %clang_cc1 -fsyntax-only -verify -faccess-control %s\nstruct A {};\nstruct B : public A {}; \/\/ Single public base.\nstruct C1 : public virtual B {}; \/\/ Single virtual base.\nstruct C2 : public virtual B {};\nstruct D : public C1, public C2 {}; \/\/ Diamond\nstruct E : private A {}; \/\/ Single private base. expected-note 3 {{'private' inheritance specifier here}}\nstruct F : public C1 {}; \/\/ Single path to B with virtual.\nstruct G1 : public B {};\nstruct G2 : public B {};\nstruct H : public G1, public G2 {}; \/\/ Ambiguous path to B.\n\nenum Enum { En1, En2 };\nenum Onom { On1, On2 };\n\nstruct Co1 { operator int(); };\nstruct Co2 { Co2(int); };\nstruct Co3 { };\nstruct Co4 { Co4(Co3); operator Co3(); };\n\n\/\/ Explicit implicits\nvoid t_529_2()\n{\n int i = 1;\n (void)static_cast<float>(i);\n double d = 1.0;\n (void)static_cast<float>(d);\n (void)static_cast<int>(d);\n (void)static_cast<char>(i);\n (void)static_cast<unsigned long>(i);\n (void)static_cast<int>(En1);\n (void)static_cast<double>(En1);\n (void)static_cast<int&>(i);\n (void)static_cast<const int&>(i);\n\n int ar[1];\n (void)static_cast<const int*>(ar);\n (void)static_cast<void (*)()>(t_529_2);\n\n (void)static_cast<void*>(0);\n (void)static_cast<void*>((int*)0);\n (void)static_cast<volatile const void*>((const int*)0);\n (void)static_cast<A*>((B*)0);\n (void)static_cast<A&>(*((B*)0));\n (void)static_cast<const B*>((C1*)0);\n (void)static_cast<B&>(*((C1*)0));\n (void)static_cast<A*>((D*)0);\n (void)static_cast<const A&>(*((D*)0));\n (void)static_cast<int B::*>((int A::*)0);\n (void)static_cast<void (B::*)()>((void (A::*)())0);\n\n (void)static_cast<int>(Co1());\n (void)static_cast<Co2>(1);\n (void)static_cast<Co3>(static_cast<Co4>(Co3()));\n\n \/\/ Bad code below\n\n (void)static_cast<void*>((const int*)0); \/\/ expected-error {{static_cast from 'int const *' to 'void *' is not allowed}}\n (void)static_cast<A*>((E*)0); \/\/ expected-error {{inaccessible base class 'struct A'}}\n (void)static_cast<A*>((H*)0); \/\/ expected-error {{ambiguous conversion}}\n (void)static_cast<int>((int*)0); \/\/ expected-error {{static_cast from 'int *' to 'int' is not allowed}}\n (void)static_cast<A**>((B**)0); \/\/ expected-error {{static_cast from 'struct B **' to 'struct A **' is not allowed}}\n (void)static_cast<char&>(i); \/\/ expected-error {{non-const lvalue reference to type 'char' cannot be initialized with a value of type 'int'}}\n}\n\n\/\/ Anything to void\nvoid t_529_4()\n{\n static_cast<void>(1);\n static_cast<void>(t_529_4);\n}\n\n\/\/ Static downcasts\nvoid t_529_5_8()\n{\n (void)static_cast<B*>((A*)0);\n (void)static_cast<B&>(*((A*)0));\n (void)static_cast<const G1*>((A*)0);\n (void)static_cast<const G1&>(*((A*)0));\n\n \/\/ Bad code below\n\n (void)static_cast<C1*>((A*)0); \/\/ expected-error {{cannot cast 'struct A *' to 'struct C1 *' via virtual base 'struct B'}}\n (void)static_cast<C1&>(*((A*)0)); \/\/ expected-error {{cannot cast 'struct A' to 'struct C1 &' via virtual base 'struct B'}}\n (void)static_cast<D*>((A*)0); \/\/ expected-error {{cannot cast 'struct A *' to 'struct D *' via virtual base 'struct B'}}\n (void)static_cast<D&>(*((A*)0)); \/\/ expected-error {{cannot cast 'struct A' to 'struct D &' via virtual base 'struct B'}}\n (void)static_cast<B*>((const A*)0); \/\/ expected-error {{static_cast from 'struct A const *' to 'struct B *' casts away constness}}\n (void)static_cast<B&>(*((const A*)0)); \/\/ expected-error {{static_cast from 'struct A const' to 'struct B &' casts away constness}}\n (void)static_cast<E*>((A*)0); \/\/ expected-error {{cannot cast 'struct A' to 'struct E' due to inaccessible}}\n (void)static_cast<E&>(*((A*)0)); \/\/ expected-error {{cannot cast 'struct A' to 'struct E' due to inaccessible}}\n (void)static_cast<H*>((A*)0); \/\/ expected-error {{ambiguous cast from base 'struct A' to derived 'struct H':\\n struct A -> struct B -> struct G1 -> struct H\\n struct A -> struct B -> struct G2 -> struct H}}\n (void)static_cast<H&>(*((A*)0)); \/\/ expected-error {{ambiguous cast from base 'struct A' to derived 'struct H':\\n struct A -> struct B -> struct G1 -> struct H\\n struct A -> struct B -> struct G2 -> struct H}}\n (void)static_cast<E*>((B*)0); \/\/ expected-error {{static_cast from 'struct B *' to 'struct E *' is not allowed}}\n (void)static_cast<E&>(*((B*)0)); \/\/ expected-error {{non-const lvalue reference to type 'struct E' cannot be initialized with a value of type 'struct B'}}\n\n \/\/ TODO: Test inaccessible base in context where it's accessible, i.e.\n \/\/ member function and friend.\n\n \/\/ TODO: Test DR427. This requires user-defined conversions, though.\n}\n\n\/\/ Enum conversions\nvoid t_529_7()\n{\n (void)static_cast<Enum>(1);\n (void)static_cast<Enum>(1.0);\n (void)static_cast<Onom>(En1);\n\n \/\/ Bad code below\n\n (void)static_cast<Enum>((int*)0); \/\/ expected-error {{static_cast from 'int *' to 'enum Enum' is not allowed}}\n}\n\n\/\/ Void pointer to object pointer\nvoid t_529_10()\n{\n (void)static_cast<int*>((void*)0);\n (void)static_cast<const A*>((void*)0);\n\n \/\/ Bad code below\n\n (void)static_cast<int*>((const void*)0); \/\/ expected-error {{static_cast from 'void const *' to 'int *' casts away constness}}\n (void)static_cast<void (*)()>((void*)0); \/\/ expected-error {{static_cast from 'void *' to 'void (*)()' is not allowed}}\n}\n\n\/\/ Member pointer upcast.\nvoid t_529_9()\n{\n (void)static_cast<int A::*>((int B::*)0);\n\n \/\/ Bad code below\n (void)static_cast<int A::*>((int H::*)0); \/\/ expected-error {{ambiguous conversion from pointer to member of derived class 'struct H'}}\n (void)static_cast<int A::*>((int F::*)0); \/\/ expected-error {{conversion from pointer to member of class 'struct F'}}\n}\n\n\/\/ PR 5261 - static_cast should instantiate template if possible\nnamespace pr5261 {\n struct base {};\n template<typename E> struct derived : public base {};\n template<typename E> struct outer {\n base *pb;\n ~outer() { (void)static_cast<derived<E>*>(pb); }\n };\n outer<int> EntryList;\n}\n\n\n\/\/ Initialization by constructor\nstruct X0;\n\nstruct X1 {\n X1();\n X1(X1&);\n X1(const X0&);\n \n operator X0() const;\n};\n\nstruct X0 { };\n\nvoid test_ctor_init() {\n (void)static_cast<X1>(X1());\n}\n\n\/\/ Casting away constness\nstruct X2 {\n};\n\nstruct X3 : X2 {\n};\n\nstruct X4 {\n typedef const X3 X3_typedef;\n \n void f() const {\n (void)static_cast<X3_typedef*>(x2);\n }\n \n const X2 *x2;\n};\n\n\/\/ PR5897 - accept static_cast from const void* to const int (*)[1].\nvoid PR5897() { (void)static_cast<const int(*)[1]>((const void*)0); }\n<|endoftext|>"} {"text":"<commit_before>#include <winsock2.h>\n#include <ws2tcpip.h>\n#include <stdio.h>\n#include <iostream>\n#include \"Game.h\"\n#include \"PinnedDownNet.h\"\n\nusing namespace std;\n\n#pragma comment(lib, \"Ws2_32.lib\")\n\n#define PINNED_DOWN_SERVER_PORT \"27015\"\n#define DEFAULT_BUFLEN 512\n\nint main()\n{\n\tWSADATA wsaData;\n\n\tint result;\n\n\t\/\/ Initialize Winsock.\n\tresult = WSAStartup(MAKEWORD(2,2), &wsaData);\n\n\tif (result != 0)\n\t{\n\t\tprintf(\"WSAStartup failed: %d\\n\", result);\n\n\t\tint i;\n\t\tcin >> i;\n\t\treturn 1;\n\t}\n\telse\n\t{\n\t\tprintf(\"Winsock initialized.\\n\");\n\t}\n\n\taddrinfo hints;\n\taddrinfo* addressInfo;\n\n\tZeroMemory(&hints, sizeof (hints));\n\thints.ai_family = AF_INET;\t\t\t\/\/ IPv4 address family\n\thints.ai_socktype = SOCK_STREAM;\t\/\/ Stream socket.\n\thints.ai_protocol = IPPROTO_TCP;\t\/\/ TCP protocol.\n\thints.ai_flags = AI_PASSIVE;\t\t\/\/ Returned socket address structure will be used in a call to the bind function.\n\n\t\/\/ Resolve the local address and port to be used by the server\n\tresult = getaddrinfo(NULL, PINNED_DOWN_SERVER_PORT, &hints, &addressInfo);\n\tif (result != 0)\n\t{\n\t\tprintf(\"getaddrinfo failed: %d\\n\", result);\n\t\tWSACleanup();\n\n\t\tint i;\n\t\tcin >> i;\n\t\treturn 1;\n\t}\n\telse\n\t{\n\t\tprintf(\"Local address resolved.\\n\");\n\t}\n\n\t\/\/ Create a SOCKET for the server to listen for client connections.\n\tSOCKET listenSocket = INVALID_SOCKET;\n\tlistenSocket = socket(addressInfo->ai_family, addressInfo->ai_socktype, addressInfo->ai_protocol);\n\n\tif (listenSocket == INVALID_SOCKET)\n\t{\n\t\tprintf(\"Error at socket(): %ld\\n\", WSAGetLastError());\n\t\tfreeaddrinfo(addressInfo);\n\t\tWSACleanup();\n\n\t\tint i;\n\t\tcin >> i;\n\t\treturn 1;\n\t}\n\n\t\/\/ Setup the TCP listening socket.\n result = bind( listenSocket, addressInfo->ai_addr, (int)addressInfo->ai_addrlen);\n\n if (result == SOCKET_ERROR)\n\t{\n printf(\"bind failed with error: %d\\n\", WSAGetLastError());\n freeaddrinfo(addressInfo);\n closesocket(listenSocket);\n WSACleanup();\n\n\t\tint i;\n\t\tcin >> i;\n\t\treturn 1;\n }\n\telse\n\t{\n\t\tprintf(\"TCP socket created.\\n\");\n\t\tfreeaddrinfo(addressInfo);\n\t}\n\n\t\/\/ Listen for maximum number of connections.\n\tresult = listen(listenSocket, SOMAXCONN);\n\n\tif (result == SOCKET_ERROR)\n\t{\n\t\tprintf(\"Listen failed with error: %ld\\n\", WSAGetLastError());\n\t\tclosesocket(listenSocket);\n\t\tWSACleanup();\n\n\t\tint i;\n\t\tcin >> i;\n\t\treturn 1;\n\t}\n\telse\n\t{\n\t\tprintf(\"Listening for %d connections.\\n\", SOMAXCONN);\n\t}\n\n\t\/\/ Accept a single client socket.\n\tSOCKET clientSocket = accept(listenSocket, NULL, NULL);\n\n\tif (clientSocket == INVALID_SOCKET)\n\t{\n\t\tprintf(\"accept failed: %d\\n\", WSAGetLastError());\n\t\tclosesocket(listenSocket);\n\t\tWSACleanup();\n\n\t\tint i;\n\t\tcin >> i;\n\t\treturn 1;\n\t}\n\n\tchar sendbuf[DEFAULT_BUFLEN];\n\tchar recvbuf[DEFAULT_BUFLEN];\n\tint sendResult;\n\tint recvbuflen = DEFAULT_BUFLEN;\n\n\t\/\/ Send three packets.\n\tfor (int i = 0; i < 3; i++)\n\t{\n\t\tServerEvent packet = ServerEvent();\n\t\tpacket.eventType = ServerEventType::LoginSuccess;\n\t\tmemcpy(&sendbuf, &packet.eventType, sizeof(ServerEventType));\n\n\t\tsendResult = send(clientSocket, sendbuf, sizeof(unsigned int), 0);\n\n\t\tif (sendResult == SOCKET_ERROR)\n\t\t{\n\t\t\tprintf(\"send failed: %d\\n\", WSAGetLastError());\n\t\t\tclosesocket(clientSocket);\n\t\t\tWSACleanup();\n\n\t\t\tint i;\n\t\t\tcin >> i;\n\t\t\treturn 1;\n\t\t}\n\t}\n\n\t\/\/ Create new game.\n\tPinnedDownCore::Game* game = new PinnedDownCore::Game();\n\n\t\/\/ Receive until the peer shuts down the connection.\n\tdo\n\t{\n\t\tresult = recv(clientSocket, recvbuf, recvbuflen, 0);\n\n\t\tif (result > 0)\n\t\t{\n\t\t\tClientEvent packet = ClientEvent();\n\t\t\tmemcpy(&packet.eventType, &recvbuf, sizeof(ClientEventType));\n\n\t\t\tswitch (packet.eventType)\n\t\t\t{\n\t\t\tcase ClientEventType::CardSelected:\n\t\t\t\tprintf(\"Card selected.\\n\");\n\t\t\t}\n\t\t}\n\t\telse if (result == 0)\n\t\t{\n\t\t\tprintf(\"Connection closing...\\n\");\n\t\t}\n\t\telse\n\t\t{\n\t\t\tprintf(\"recv failed: %d\\n\", WSAGetLastError());\n\t\t\tclosesocket(clientSocket);\n\t\t\tWSACleanup();\n\n\t\t\tint i;\n\t\t\tcin >> i;\n\t\t\treturn 1;\n\t\t}\n\t}\n\twhile (result > 0);\n\n\t\/\/ Shutdown the send half of the connection since no more data will be sent.\n\tresult = shutdown(clientSocket, SD_SEND);\n\tif (result == SOCKET_ERROR)\n\t{\n\t\tprintf(\"shutdown failed: %d\\n\", WSAGetLastError());\n\t\tclosesocket(clientSocket);\n\t\tWSACleanup();\n\n\t\tint i;\n\t\tcin >> i;\n\t\treturn 1;\n\t}\n\telse\n\t{\n\t\tprintf(\"Client socket shut down.\");\n\t\tclosesocket(clientSocket);\n\t\tWSACleanup();\n\t}\n\n\tint i;\n\tcin >> i;\n\treturn 0;\n}\n<commit_msg>CHANGED: Project - Cleaned up server stub.<commit_after>#include <winsock2.h>\n#include <ws2tcpip.h>\n#include <stdio.h>\n#include <iostream>\n#include \"Game.h\"\n#include \"PinnedDownNet.h\"\n\nusing namespace std;\n\n#pragma comment(lib, \"Ws2_32.lib\")\n\n#define PINNED_DOWN_SERVER_PORT \"27015\"\n#define DEFAULT_BUFLEN 512\n\nvoid pause()\n{\n\tint i;\n\tcin >> i;\n}\n\nint main()\n{\n\t\/\/ Initialize Winsock.\n\tWSADATA wsaData;\n\tint result;\n\n\tresult = WSAStartup(MAKEWORD(2,2), &wsaData);\n\n\tif (result != 0)\n\t{\n\t\tprintf(\"Failed to initialize Winsock: %d\\n\", result);\n\n\t\tpause();\n\t\treturn 1;\n\t}\n\telse\n\t{\n\t\tprintf(\"Winsock initialized.\\n\");\n\t}\n\n\t\/\/ Resolve the local address and port to be used by the server\n\taddrinfo hints;\n\taddrinfo* addressInfo;\n\n\tZeroMemory(&hints, sizeof (hints));\n\thints.ai_family = AF_INET;\t\t\t\/\/ IPv4 address family\n\thints.ai_socktype = SOCK_STREAM;\t\/\/ Stream socket.\n\thints.ai_protocol = IPPROTO_TCP;\t\/\/ TCP protocol.\n\thints.ai_flags = AI_PASSIVE;\t\t\/\/ Returned socket address structure will be used in a call to the bind function.\n\n\tresult = getaddrinfo(NULL, PINNED_DOWN_SERVER_PORT, &hints, &addressInfo);\n\tif (result != 0)\n\t{\n\t\tprintf(\"Failed to resolve local address and port: %d\\n\", result);\n\t\tWSACleanup();\n\n\t\tpause();\n\t\treturn 1;\n\t}\n\telse\n\t{\n\t\tprintf(\"Local address and port resolved.\\n\");\n\t}\n\n\t\/\/ Create a SOCKET for the server to listen for client connections.\n\tSOCKET listenSocket = INVALID_SOCKET;\n\tlistenSocket = socket(addressInfo->ai_family, addressInfo->ai_socktype, addressInfo->ai_protocol);\n\n\tif (listenSocket == INVALID_SOCKET)\n\t{\n\t\tprintf(\"Failed to create socket: %ld\\n\", WSAGetLastError());\n\t\tfreeaddrinfo(addressInfo);\n\t\tWSACleanup();\n\n\t\tpause();\n\t\treturn 1;\n\t}\n\telse\n\t{\n\t\tprintf(\"Socket created.\\n\");\n\t}\n\n\t\/\/ Setup the TCP listening socket.\n result = bind( listenSocket, addressInfo->ai_addr, (int)addressInfo->ai_addrlen);\n\n if (result == SOCKET_ERROR)\n\t{\n printf(\"Failed to bind TCP listening socket: %d\\n\", WSAGetLastError());\n freeaddrinfo(addressInfo);\n closesocket(listenSocket);\n WSACleanup();\n\n\t\tpause();\n\t\treturn 1;\n }\n\telse\n\t{\n\t\tprintf(\"TCP socket bound.\\n\");\n\t\tfreeaddrinfo(addressInfo);\n\t}\n\n\t\/\/ Listen for maximum number of connections.\n\tresult = listen(listenSocket, SOMAXCONN);\n\n\tif (result == SOCKET_ERROR)\n\t{\n\t\tprintf(\"Failed to listen for incoming connections: %ld\\n\", WSAGetLastError());\n\t\tclosesocket(listenSocket);\n\t\tWSACleanup();\n\n\t\tpause();\n\t\treturn 1;\n\t}\n\telse\n\t{\n\t\tprintf(\"Listening for %d connections.\\n\", SOMAXCONN);\n\t}\n\n\t\/\/ Accept a single client socket.\n\tSOCKET clientSocket = accept(listenSocket, NULL, NULL);\n\n\tif (clientSocket == INVALID_SOCKET)\n\t{\n\t\tprintf(\"Failed to accept client socket: %d\\n\", WSAGetLastError());\n\t\tclosesocket(listenSocket);\n\t\tWSACleanup();\n\n\t\tpause();\n\t\treturn 1;\n\t}\n\telse\n\t{\n\t\tprintf(\"Client connected.\\n\");\n\t}\n\n\t\/\/ Send login ACK.\n\tchar sendbuf[DEFAULT_BUFLEN];\n\tchar recvbuf[DEFAULT_BUFLEN];\n\n\tServerEvent packet = ServerEvent(ServerEventType::LoginSuccess);\n\tmemcpy(&sendbuf, &packet.eventType, sizeof(ServerEventType));\n\n\tresult = send(clientSocket, sendbuf, sizeof(ServerEventType), 0);\n\n\tif (result == SOCKET_ERROR)\n\t{\n\t\tprintf(\"Failed to send packet: %d\\n\", WSAGetLastError());\n\t\tclosesocket(clientSocket);\n\t\tWSACleanup();\n\n\t\tpause();\n\t\treturn 1;\n\t}\n\telse\n\t{\n\t\tprintf(\"Packet sent.\\n\");\n\t}\n\n\t\/\/ Create new game.\n\tPinnedDownCore::Game* game = new PinnedDownCore::Game();\n\n\t\/\/ Receive until the peer shuts down the connection.\n\tdo\n\t{\n\t\tresult = recv(clientSocket, recvbuf, DEFAULT_BUFLEN, 0);\n\n\t\tif (result > 0)\n\t\t{\n\t\t\t\/\/ Process client action.\n\t\t\tClientAction action = ClientAction();\n\t\t\tmemcpy(&action.actionType, &recvbuf, sizeof(ClientActionType));\n\n\t\t\tswitch (action.actionType)\n\t\t\t{\n\t\t\tcase ClientActionType::SelectCard:\n\t\t\t\tprintf(\"Select card.\\n\");\n\t\t\t}\n\t\t}\n\t\telse if (result == 0)\n\t\t{\n\t\t\tprintf(\"Connection closing...\\n\");\n\t\t}\n\t\telse\n\t\t{\n\t\t\tprintf(\"Failed to receive packet: %d\\n\", WSAGetLastError());\n\t\t\tclosesocket(clientSocket);\n\t\t\tWSACleanup();\n\n\t\t\tpause();\n\t\t\treturn 1;\n\t\t}\n\t}\n\twhile (result > 0);\n\n\t\/\/ Shutdown the send half of the connection since no more data will be sent.\n\tresult = shutdown(clientSocket, SD_SEND);\n\n\tif (result == SOCKET_ERROR)\n\t{\n\t\tprintf(\"Failed to shut down socket: %d\\n\", WSAGetLastError());\n\t\tclosesocket(clientSocket);\n\t\tWSACleanup();\n\n\t\tpause();\n\t\treturn 1;\n\t}\n\telse\n\t{\n\t\tprintf(\"Client socket shut down.\");\n\t\tclosesocket(clientSocket);\n\t\tWSACleanup();\n\t}\n\n\tpause();\n\treturn 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * author: Max Kellermann <mk@cm4all.com>\n *\/\n\n#include \"istream_head.hxx\"\n#include \"ForwardIstream.hxx\"\n\n#include <algorithm>\n\n#include <assert.h>\n#include <string.h>\n\nclass HeadIstream final : public ForwardIstream {\n off_t rest;\n const bool authoritative;\n\npublic:\n HeadIstream(struct pool &p, Istream &_input,\n size_t size, bool _authoritative)\n :ForwardIstream(p, _input),\n rest(size), authoritative(_authoritative) {}\n\n \/* virtual methods from class Istream *\/\n\n off_t _GetAvailable(bool partial) override;\n off_t _Skip(off_t length) override;\n void _Read() override;\n\n int _AsFd() override {\n return -1;\n }\n\n \/* virtual methods from class IstreamHandler *\/\n size_t OnData(const void *data, size_t length) override;\n ssize_t OnDirect(FdType type, int fd, size_t max_length) override;\n};\n\n\/*\n * istream handler\n *\n *\/\n\nsize_t\nHeadIstream::OnData(const void *data, size_t length)\n{\n if (rest == 0) {\n input.Close();\n DestroyEof();\n return 0;\n }\n\n if ((off_t)length > rest)\n length = rest;\n\n size_t nbytes = InvokeData(data, length);\n assert((off_t)nbytes <= rest);\n\n if (nbytes > 0) {\n rest -= nbytes;\n if (rest == 0) {\n input.Close();\n DestroyEof();\n return 0;\n }\n }\n\n return nbytes;\n}\n\nssize_t\nHeadIstream::OnDirect(FdType type, int fd, size_t max_length)\n{\n if (rest == 0) {\n input.Close();\n DestroyEof();\n return ISTREAM_RESULT_CLOSED;\n }\n\n if ((off_t)max_length > rest)\n max_length = rest;\n\n ssize_t nbytes = InvokeDirect(type, fd, max_length);\n assert(nbytes < 0 || (off_t)nbytes <= rest);\n\n if (nbytes > 0) {\n rest -= (size_t)nbytes;\n if (rest == 0) {\n input.Close();\n DestroyEof();\n return ISTREAM_RESULT_CLOSED;\n }\n }\n\n return nbytes;\n}\n\n\/*\n * istream implementation\n *\n *\/\n\noff_t\nHeadIstream::_GetAvailable(bool partial)\n{\n if (authoritative) {\n assert(partial ||\n input.GetAvailable(partial) < 0 ||\n input.GetAvailable(partial) >= (off_t)rest);\n return rest;\n }\n\n off_t available = input.GetAvailable(partial);\n return std::min(available, rest);\n}\n\noff_t\nHeadIstream::_Skip(off_t length)\n{\n if (length >= rest)\n length = rest;\n\n off_t nbytes = input.Skip(length);\n assert(nbytes <= length);\n\n if (nbytes > 0)\n rest -= nbytes;\n\n return nbytes;\n}\n\nvoid\nHeadIstream::_Read()\n{\n if (rest == 0) {\n input.Close();\n DestroyEof();\n } else {\n ForwardIstream::_Read();\n }\n}\n\n\/*\n * constructor\n *\n *\/\n\nIstream *\nistream_head_new(struct pool *pool, Istream &input,\n size_t size, bool authoritative)\n{\n return NewIstream<HeadIstream>(*pool, input, size, authoritative);\n}\n<commit_msg>istream\/head: invoke base class in _Skip()<commit_after>\/*\n * author: Max Kellermann <mk@cm4all.com>\n *\/\n\n#include \"istream_head.hxx\"\n#include \"ForwardIstream.hxx\"\n\n#include <algorithm>\n\n#include <assert.h>\n#include <string.h>\n\nclass HeadIstream final : public ForwardIstream {\n off_t rest;\n const bool authoritative;\n\npublic:\n HeadIstream(struct pool &p, Istream &_input,\n size_t size, bool _authoritative)\n :ForwardIstream(p, _input),\n rest(size), authoritative(_authoritative) {}\n\n \/* virtual methods from class Istream *\/\n\n off_t _GetAvailable(bool partial) override;\n off_t _Skip(off_t length) override;\n void _Read() override;\n\n int _AsFd() override {\n return -1;\n }\n\n \/* virtual methods from class IstreamHandler *\/\n size_t OnData(const void *data, size_t length) override;\n ssize_t OnDirect(FdType type, int fd, size_t max_length) override;\n};\n\n\/*\n * istream handler\n *\n *\/\n\nsize_t\nHeadIstream::OnData(const void *data, size_t length)\n{\n if (rest == 0) {\n input.Close();\n DestroyEof();\n return 0;\n }\n\n if ((off_t)length > rest)\n length = rest;\n\n size_t nbytes = InvokeData(data, length);\n assert((off_t)nbytes <= rest);\n\n if (nbytes > 0) {\n rest -= nbytes;\n if (rest == 0) {\n input.Close();\n DestroyEof();\n return 0;\n }\n }\n\n return nbytes;\n}\n\nssize_t\nHeadIstream::OnDirect(FdType type, int fd, size_t max_length)\n{\n if (rest == 0) {\n input.Close();\n DestroyEof();\n return ISTREAM_RESULT_CLOSED;\n }\n\n if ((off_t)max_length > rest)\n max_length = rest;\n\n ssize_t nbytes = InvokeDirect(type, fd, max_length);\n assert(nbytes < 0 || (off_t)nbytes <= rest);\n\n if (nbytes > 0) {\n rest -= (size_t)nbytes;\n if (rest == 0) {\n input.Close();\n DestroyEof();\n return ISTREAM_RESULT_CLOSED;\n }\n }\n\n return nbytes;\n}\n\n\/*\n * istream implementation\n *\n *\/\n\noff_t\nHeadIstream::_GetAvailable(bool partial)\n{\n if (authoritative) {\n assert(partial ||\n input.GetAvailable(partial) < 0 ||\n input.GetAvailable(partial) >= (off_t)rest);\n return rest;\n }\n\n off_t available = input.GetAvailable(partial);\n return std::min(available, rest);\n}\n\noff_t\nHeadIstream::_Skip(off_t length)\n{\n if (length >= rest)\n length = rest;\n\n off_t nbytes = ForwardIstream::Skip(length);\n assert(nbytes <= length);\n\n if (nbytes > 0)\n rest -= nbytes;\n\n return nbytes;\n}\n\nvoid\nHeadIstream::_Read()\n{\n if (rest == 0) {\n input.Close();\n DestroyEof();\n } else {\n ForwardIstream::_Read();\n }\n}\n\n\/*\n * constructor\n *\n *\/\n\nIstream *\nistream_head_new(struct pool *pool, Istream &input,\n size_t size, bool authoritative)\n{\n return NewIstream<HeadIstream>(*pool, input, size, authoritative);\n}\n<|endoftext|>"} {"text":"<commit_before>\/*****************************************************************************\n *\n * This file is part of Mapnik (c++ mapping toolkit)\n *\n * Copyright (C) 2015 Artem Pavlenko\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n *\n *****************************************************************************\/\n\n\/\/ mapnik\n#include <mapnik\/json\/extract_bounding_box_grammar.hpp>\n\n\/\/ boost\n#include <boost\/spirit\/include\/qi_omit.hpp>\n#include <boost\/spirit\/include\/phoenix_object.hpp>\n#include <boost\/spirit\/include\/phoenix_stl.hpp>\n#include <boost\/spirit\/include\/phoenix_operator.hpp>\n#include <boost\/spirit\/repository\/include\/qi_iter_pos.hpp>\n\/\/ stl\n#include <iostream>\n#include <string>\n\nnamespace mapnik { namespace json {\n\nnamespace repo = boost::spirit::repository;\n\ntemplate <typename Iterator, typename ErrorHandler>\nextract_bounding_box_grammar<Iterator, ErrorHandler>::extract_bounding_box_grammar()\n : extract_bounding_box_grammar::base_type(start,\"bounding boxes\")\n{\n qi::lit_type lit;\n qi::double_type double_;\n qi::_val_type _val;\n qi::_1_type _1;\n qi::_2_type _2;\n qi::_3_type _3;\n qi::_4_type _4;\n qi::omit_type omit;\n qi::_r1_type _r1;\n qi::_r2_type _r2;\n qi::_a_type _a;\n qi::_b_type _b;\n qi::eps_type eps;\n qi::raw_type raw;\n ascii::char_type char_;\n boost::spirit::repository::qi::iter_pos_type iter_pos;\n using qi::fail;\n using qi::on_error;\n\n start = features(_r1)\n ;\n features = iter_pos[_a = _1] >> -(lit('{') >> -lit(\"\\\"type\\\"\")\n >> lit(':') >> lit(\"\\\"FeatureCollection\\\"\")\n >> *(lit(',') >> (json.key_value - lit(\"\\\"features\\\"\")))\n >> lit(',') >> lit(\"\\\"features\\\"\")\n >> lit(':'))\n >> lit('[') >> (feature(_r1,_a) % lit(',')) >> lit(']')\n ;\n feature = raw[lit('{')[_a = 1] >> lit(\"\\\"type\\\"\") >> lit(':') >> lit(\"\\\"Feature\\\"\")\n >> *(eps(_a > 0) >> (lit('{')[_a += 1]\n |\n lit('}')[_a -=1]\n |\n coords[_b = _1]\n |\n char_))][push_box(_r1, _r2, _b, _1)]\n ;\n coords = lit(\"\\\"coordinates\\\"\") >> lit(':') >> (rings_array(_a) | rings (_a) | ring(_a) | pos[calculate_bounding_box(_a,_1)])[_val = _a]\n ;\n pos = lit('[') > -(double_ > lit(',') > double_) > omit[*(lit(',') > double_)] > lit(']')\n ;\n ring = lit('[') >> pos[calculate_bounding_box(_r1,_1)] % lit(',') > lit(']')\n ;\n rings = lit('[') >> ring(_r1) % lit(',') > lit(']')\n ;\n rings_array = lit('[') >> rings(_r1) % lit(',') > lit(']')\n ;\n\n \/\/ generic json types\n json.value = json.object | json.array | json.string_ | json.number\n ;\n json.pairs = json.key_value % lit(',')\n ;\n json.key_value = (json.string_ >> lit(':') >> json.value)\n ;\n json.object = lit('{') >> *json.pairs >> lit('}')\n ;\n json.array = lit('[')\n >> json.value >> *(lit(',') >> json.value)\n >> lit(']')\n ;\n json.number = json.strict_double\n | json.int__\n | lit(\"true\")\n | lit(\"false\")\n | lit(\"null\")\n ;\n coords.name(\"Coordinates\");\n pos.name(\"Position\");\n ring.name(\"Ring\");\n rings.name(\"Rings\");\n rings_array.name(\"Rings array\");\n\n \/\/ error handler\n on_error<fail>(coords, error_handler(_1, _2, _3, _4));\n}\n\n}}\n<commit_msg>fix bbox extractor<commit_after>\/*****************************************************************************\n *\n * This file is part of Mapnik (c++ mapping toolkit)\n *\n * Copyright (C) 2015 Artem Pavlenko\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n *\n *****************************************************************************\/\n\n\/\/ mapnik\n#include <mapnik\/json\/extract_bounding_box_grammar.hpp>\n\n\/\/ boost\n#include <boost\/spirit\/include\/qi_omit.hpp>\n#include <boost\/spirit\/include\/phoenix_object.hpp>\n#include <boost\/spirit\/include\/phoenix_stl.hpp>\n#include <boost\/spirit\/include\/phoenix_operator.hpp>\n#include <boost\/spirit\/repository\/include\/qi_iter_pos.hpp>\n\/\/ stl\n#include <iostream>\n#include <string>\n\nnamespace mapnik { namespace json {\n\nnamespace repo = boost::spirit::repository;\n\ntemplate <typename Iterator, typename ErrorHandler>\nextract_bounding_box_grammar<Iterator, ErrorHandler>::extract_bounding_box_grammar()\n : extract_bounding_box_grammar::base_type(start,\"bounding boxes\")\n{\n qi::lit_type lit;\n qi::double_type double_;\n qi::_val_type _val;\n qi::_1_type _1;\n qi::_2_type _2;\n qi::_3_type _3;\n qi::_4_type _4;\n qi::omit_type omit;\n qi::_r1_type _r1;\n qi::_r2_type _r2;\n qi::_a_type _a;\n qi::_b_type _b;\n qi::eps_type eps;\n qi::raw_type raw;\n boost::spirit::standard_wide::char_type char_;\n boost::spirit::repository::qi::iter_pos_type iter_pos;\n using qi::fail;\n using qi::on_error;\n\n start = features(_r1)\n ;\n features = iter_pos[_a = _1] >> -(lit('{') >> -lit(\"\\\"type\\\"\")\n >> lit(':') >> lit(\"\\\"FeatureCollection\\\"\")\n >> *(lit(',') >> (json.key_value - lit(\"\\\"features\\\"\")))\n >> lit(',') >> lit(\"\\\"features\\\"\")\n >> lit(':'))\n >> lit('[') >> (feature(_r1,_a) % lit(',')) >> lit(']')\n ;\n feature = raw[lit('{')[_a = 1] >> lit(\"\\\"type\\\"\") >> lit(':') >> lit(\"\\\"Feature\\\"\")\n >> *(eps(_a > 0) >> (lit('{')[_a += 1]\n |\n lit('}')[_a -=1]\n |\n coords[_b = _1]\n |\n char_))][push_box(_r1, _r2, _b, _1)]\n ;\n coords = lit(\"\\\"coordinates\\\"\") >> lit(':') >> (rings_array(_a) | rings (_a) | ring(_a) | pos[calculate_bounding_box(_a,_1)])[_val = _a]\n ;\n pos = lit('[') > -(double_ > lit(',') > double_) > omit[*(lit(',') > double_)] > lit(']')\n ;\n ring = lit('[') >> pos[calculate_bounding_box(_r1,_1)] % lit(',') > lit(']')\n ;\n rings = lit('[') >> ring(_r1) % lit(',') > lit(']')\n ;\n rings_array = lit('[') >> rings(_r1) % lit(',') > lit(']')\n ;\n\n \/\/ generic json types\n json.value = json.object | json.array | json.string_ | json.number\n ;\n json.pairs = json.key_value % lit(',')\n ;\n json.key_value = (json.string_ >> lit(':') >> json.value)\n ;\n json.object = lit('{') >> *json.pairs >> lit('}')\n ;\n json.array = lit('[')\n >> json.value >> *(lit(',') >> json.value)\n >> lit(']')\n ;\n json.number = json.strict_double\n | json.int__\n | lit(\"true\")\n | lit(\"false\")\n | lit(\"null\")\n ;\n coords.name(\"Coordinates\");\n pos.name(\"Position\");\n ring.name(\"Ring\");\n rings.name(\"Rings\");\n rings_array.name(\"Rings array\");\n\n \/\/ error handler\n on_error<fail>(coords, error_handler(_1, _2, _3, _4));\n}\n\n}}\n<|endoftext|>"} {"text":"<commit_before>\/\/ -*- C++ -*-\n\n\/\/ The MIT License (MIT)\n\/\/\n\/\/ Copyright (c) 2017 Alexander Samoilov\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in all\n\/\/ copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n\/\/ SOFTWARE.\n\n#include <iostream>\n#include <fstream>\n#include <string>\n#include <chrono>\n#include <boost\/program_options.hpp>\n\nstruct program_options\n{\n bool verbose = {false};\n int flow_type = {0}; \/\/ legacy Fortran constants for flow type, 50 for sphere, 51 for torus\n std::string input_data = {\"\"}; \/\/ name of the input file e.g. `sphere.dat`, `torus_trgl.dat`\n std::string asy_name = {\"\"}; \/\/ dump streamlines to vector `.asy` file if name is given\n};\n\nstd::ostream& operator<<(std::ostream& os, program_options const& popt)\n{\n os << \"program options: \" << std::boolalpha << \" verbose: \" << popt.verbose << std::endl\n << \" flow_type: \" << popt.flow_type << \" input_data: \" << popt.input_data << \" asy_name: \" << popt.asy_name << std::endl;\n\n return os;\n}\n\nprogram_options parse_command_line(int argc, char** argv)\n{\n namespace po = boost::program_options;\n po::options_description desc(\"allowed options\");\n desc.add_options()\n (\"help\", \"describe arguments\")\n (\"verbose\", \"be verbose\")\n (\"flow_type\", po::value<int>(), \"legacy Fortran constants for flow type, 50 for sphere, 51 for torus\")\n (\"input_data\", po::value<std::string>(), \"name of the input file e.g. `sphere.dat`, `torus_trgl.dat`\")\n (\"asy_name\", po::value<std::string>(), \"dump streamlines to vector `.asy` file if name is given\");\n try\n {\n po::variables_map vm;\n po::store(po::parse_command_line(argc, argv, desc), vm);\n po::notify(vm);\n program_options popt;\n\n if (vm.count(\"help\")) {\n std::cout << desc << std::endl;\n std::exit(1);\n }\n\n popt.verbose = vm.count(\"verbose\");\n if (vm.count(\"flow_type\"))\n {\n popt.flow_type = vm[\"flow_type\"].as<int>();\n }\n if (vm.count(\"input_data\"))\n {\n popt.input_data = vm[\"input_data\"].as<std::string>();\n }\n if (vm.count(\"asy_name\"))\n {\n popt.asy_name = vm[\"asy_name\"].as<std::string>();\n }\n\n return popt;\n }\n catch(const std::exception& e)\n {\n std::cerr << e.what() << std::endl;\n std::cout << desc << std::endl;\n std::exit(-1);\n }\n}\n\nint main(int argc, char **argv)\n{\n auto popt = parse_command_line(argc, argv);\n if (popt.verbose) {\n std::cout << popt;\n }\n\n}\n\n<commit_msg>cosmetic.<commit_after>\/\/ -*- C++ -*-\n\n\/\/ The MIT License (MIT)\n\/\/\n\/\/ Copyright (c) 2017 Alexander Samoilov\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in all\n\/\/ copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n\/\/ SOFTWARE.\n\n#include <iostream>\n#include <fstream>\n#include <string>\n#include <chrono>\n#include <boost\/program_options.hpp>\n\nstruct program_options\n{\n bool verbose = {false};\n int flow_type = {0}; \/\/ legacy Fortran constants for flow type, 50 for sphere, 51 for torus\n std::string input_data = {\"\"}; \/\/ name of the input file e.g. `sphere.dat`, `torus_trgl.dat`\n std::string asy_name = {\"\"}; \/\/ dump streamlines to vector `.asy` file if name is given\n};\n\nstd::ostream& operator<<(std::ostream& os, program_options const& popt)\n{\n os << \"program options: \" << std::boolalpha << \" verbose: \" << popt.verbose << std::endl\n << \" flow_type: \" << popt.flow_type << \" input_data: \" << popt.input_data << \" asy_name: \" << popt.asy_name << std::endl;\n\n return os;\n}\n\nprogram_options parse_command_line(int argc, char** argv)\n{\n namespace po = boost::program_options;\n po::options_description desc(\"allowed options\");\n desc.add_options()\n (\"help\", \"describe arguments\")\n (\"verbose\", \"be verbose\")\n (\"flow_type\", po::value<int>(), \"legacy Fortran constants for flow type, 50 for sphere, 51 for torus\")\n (\"input_data\", po::value<std::string>(), \"name of the input file e.g. `sphere.dat`, `torus_trgl.dat`\")\n (\"asy_name\", po::value<std::string>(), \"dump streamlines to vector `.asy` file if name is given\");\n try\n {\n po::variables_map vm;\n po::store(po::parse_command_line(argc, argv, desc), vm);\n po::notify(vm);\n program_options popt;\n\n if (vm.count(\"help\")) {\n std::cout << desc << std::endl;\n std::exit(1);\n }\n\n popt.verbose = vm.count(\"verbose\");\n if (vm.count(\"flow_type\")) {\n popt.flow_type = vm[\"flow_type\"].as<int>();\n }\n if (vm.count(\"input_data\")) {\n popt.input_data = vm[\"input_data\"].as<std::string>();\n }\n if (vm.count(\"asy_name\")) {\n popt.asy_name = vm[\"asy_name\"].as<std::string>();\n }\n\n return popt;\n }\n catch(const std::exception& e)\n {\n std::cerr << e.what() << std::endl;\n std::cout << desc << std::endl;\n std::exit(-1);\n }\n}\n\nint main(int argc, char **argv)\n{\n auto popt = parse_command_line(argc, argv);\n if (popt.verbose) {\n std::cout << popt;\n }\n\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n * BackwardChainer.cc\n *\n * Copyright (C) 2014-2016 OpenCog Foundation\n *\n * Authors: Misgana Bayetta <misgana.bayetta@gmail.com> October 2014\n * William Ma <https:\/\/github.com\/williampma>\n * Nil Geisweiller 2016\n *\n * This program is free software; you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License v3 as\n * published by the Free Software Foundation and including the exceptions\n * at http:\/\/opencog.org\/wiki\/Licenses\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public License\n * along with this program; if not, write to:\n * Free Software Foundation, Inc.,\n * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.\n *\/\n\n#include <opencog\/util\/random.h>\n\n#include <opencog\/atomutils\/FindUtils.h>\n#include <opencog\/atomutils\/Substitutor.h>\n#include <opencog\/atomutils\/Unify.h>\n#include <opencog\/atomutils\/TypeUtils.h>\n#include <opencog\/atoms\/pattern\/PatternLink.h>\n#include <opencog\/atoms\/pattern\/BindLink.h>\n\n#include <opencog\/query\/BindLinkAPI.h>\n\n#include \"BackwardChainer.h\"\n#include \"BackwardChainerPMCB.h\"\n#include \"UnifyPMCB.h\"\n#include \"BCLogger.h\"\n\nusing namespace opencog;\n\nBackwardChainer::BackwardChainer(AtomSpace& as, const Handle& rbs,\n const Handle& htarget,\n const Handle& vardecl,\n const Handle& hfocus_set, \/\/ TODO:\n \/\/ support\n \/\/ focus_set\n const BITFitness& fitness)\n\t: _as(as), _configReader(as, rbs),\n\t _init_target(htarget), _init_vardecl(vardecl), _init_fitness(fitness),\n\t _bit_as(&as), _iteration(0), _rules(_configReader.get_rules()) {}\n\nUREConfigReader& BackwardChainer::get_config()\n{\n\treturn _configReader;\n}\n\nconst UREConfigReader& BackwardChainer::get_config() const\n{\n\treturn _configReader;\n}\n\nvoid BackwardChainer::do_chain()\n{\n\twhile (not termination())\n\t{\n\t\tdo_step();\n\t}\n}\n\nvoid BackwardChainer::do_step()\n{\n\tbc_logger().debug(\"Iteration %d\", _iteration);\n\t_iteration++;\n\n\texpand_bit();\n\tfulfill_bit();\n\treduce_bit();\n}\n\nbool BackwardChainer::termination()\n{\n\treturn _configReader.get_maximum_iterations() <= _iteration;\n}\n\nHandle BackwardChainer::get_results() const\n{\n\tHandleSeq results(_results.begin(), _results.end());\n\treturn _as.add_link(SET_LINK, results);\n}\n\nvoid BackwardChainer::expand_bit()\n{\n\tif (_handle2bitnode.empty()) {\n\t\t\/\/ Initialize the and-BIT of the initial target\n\t\tinsert_h2b(_init_target, _init_vardecl, _init_fitness);\n\t\tinit_andbits();\n\n\t\tLAZY_BC_LOG_DEBUG << \"Initialize BIT with:\" << std::endl\n\t\t << _handle2bitnode[_init_target].to_string();\n\t} else {\n\t\t\/\/ Select an and-BIT and expand it\n\t\tconst AndBITFCMap::value_type& andbit = select_andbit();\n\t\tLAZY_BC_LOG_DEBUG << \"Selected and-BIT for expansion:\" << std::endl\n\t\t << andbit.second;\n\t\texpand_bit(andbit);\n\t}\n}\n\nvoid BackwardChainer::expand_bit(const AndBITFCMap::value_type& andbit)\n{\n\t\/\/ Select leaf\n\tBITNode& bitleaf = select_bitleaf(andbit);\n\tLAZY_BC_LOG_DEBUG << \"Selected BIT-node for expansion:\" << std::endl\n\t << bitleaf.to_string();\n\n\t\/\/ Select a valid rule\n\tRule rule = select_rule(bitleaf);\n\tif (not rule.is_valid()) {\n\t\tbc_logger().warn(\"No valid rule for the selected BIT-node, abort expansion\");\n\t\treturn;\n\t}\n\tLAZY_BC_LOG_DEBUG << \"Selected rule for BIT expansion:\" << std::endl\n\t << rule.to_string();\n\n\t\/\/ Expand the back-inference tree from this target\n\texpand_bit(andbit, bitleaf, rule);\n}\n\nvoid BackwardChainer::expand_bit(const AndBITFCMap::value_type& andbit,\n BITNode& bitleaf, const Rule& rule)\n{\n\t\/\/ Make sure that the rule is not a or-child of leaf.\n\tif (is_in(rule, bitleaf)) {\n\t\tbc_logger().debug() << \"An equivalent rule has already expanded that BIT-node, abort expansion\";\n\t\treturn;\n\t}\n\n\t\/\/ Expand the leaf\n\t\/\/ 1. Append the rule to it\n\t\/\/ 2. Instantiate the premises as BITNodes\n\tHandleSeq premises(rule.get_premises());\n\tbitleaf.rules.push_back(rule);\n\tfor (const Handle& premise : premises)\n\t\tinsert_h2b(premise, rule.get_forward_vardecl(), BITFitness());\n\n\t\/\/ Expand the associated atomese forward chaining strategy\n\tHandle fcs = expand_fcs(andbit.second, bitleaf.body, rule);\n\n\t\/\/ Define new and-BIT and associate new forward chaining strategy\n\t\/\/ to it\n\tAndBITFCMap::key_type new_leaves(andbit.first);\n\tnew_leaves.erase(bitleaf.body);\n\tfor (const Handle& premise : premises)\n\t\t\/\/ Make sure that the premise is in _bit_as\n\t\tnew_leaves.insert(_bit_as.add_atom(premise));\n\t_andbits[new_leaves] = fcs;\n}\n\nHandle BackwardChainer::expand_fcs(const Handle& fcs, const Handle& leaf,\n const Rule& rule)\n{\n\tBindLinkPtr fcs_bl(BindLinkCast(fcs));\n\tHandle fcs_vardecl = fcs_bl->get_vardecl();\n\tHandle fcs_pattern = fcs_bl->get_body();\n\tHandle fcs_rewrite = fcs_bl->get_implicand();\n\tHandle rule_vardecl = rule.get_forward_vardecl();\n\tHandleSeq premises = rule.get_premises();\n\tHandle rule_rewrite = rule.get_forward_implicand();\n\n\t\/\/ Generate new pattern term\n\tHandle npattern = expand_fcs_pattern(fcs_pattern, leaf, premises);\n\n\t\/\/ Generate new rewrite term\n\tHandle nrewrite = expand_fcs_rewrite(fcs_rewrite, leaf, rule_rewrite);\n\n\t\/\/ Generate new vardecl\n\tHandle nvardecl = filter_vardecl(merge_vardecl(fcs_vardecl,\n\t \/\/ Mkae sure it is in _bit_as\n\t _bit_as.add_atom(rule_vardecl)),\n\t {npattern, nrewrite});\n\n\t\/\/ Generate new atomese forward chaining strategy\n\tHandleSeq noutgoings({npattern, nrewrite});\n\tif (nvardecl.is_defined())\n\t\tnoutgoings.insert(noutgoings.begin(), nvardecl);\n\tHandle nfcs = _bit_as.add_link(BIND_LINK, noutgoings);\n\n\tLAZY_BC_LOG_DEBUG << \"Expand forward chainer strategy:\" << std::endl << fcs\n\t << \"to:\" << std::endl << nfcs;\n\n\treturn nfcs;\n}\n\nHandle BackwardChainer::expand_fcs_pattern(const Handle& fcs_pattern,\n const Handle& leaf,\n const HandleSeq& premises)\n{\n\tif (fcs_pattern == leaf)\n\t\treturn _bit_as.add_link(AND_LINK, premises);\n\n\tOC_ASSERT(fcs_pattern->getType() == AND_LINK);\n\tHandleSeq outgoings = fcs_pattern->getOutgoingSet();\n\tauto it = std::find(outgoings.begin(), outgoings.end(), leaf);\n\tOC_ASSERT(it != outgoings.end());\n\toutgoings.erase(it);\n\toutgoings.insert(outgoings.end(), premises.begin(), premises.end());\n\treturn _bit_as.add_link(AND_LINK, outgoings);\n}\n\nHandle BackwardChainer::expand_fcs_rewrite(const Handle& fcs_rewrite,\n const Handle& leaf,\n const Handle& rule_rewrite)\n{\n\t\/\/ Base cases\n\n\t\/\/ Replace the fcs rewrite atoms by the rule_rewrite if leaf\n\tif (fcs_rewrite == leaf)\n\t\t\/\/ rule_rewrite might possibly not be in _bit_as yet, add it\n\t\treturn _bit_as.add_atom(rule_rewrite);\n\t\/\/ If node and isn't leaf leave alone\n\tif (fcs_rewrite->isNode())\n\t\treturn fcs_rewrite;\n\n\t\/\/ Recursive case\n\n\tType t = fcs_rewrite->getType();\n\tHandleSeq outgoings;\n\tfor (const Handle& h : fcs_rewrite->getOutgoingSet())\n\t\toutgoings.push_back(expand_fcs_rewrite(h, leaf, rule_rewrite));\n\treturn _bit_as.add_link(t, outgoings);\n}\n\nvoid BackwardChainer::fulfill_bit()\n{\n\tif (_andbits.empty()) {\n\t\tbc_logger().warn(\"Cannot fulfill an empty BIT\");\n\t\treturn;\n\t}\n\n\t\/\/ Select an and-BIT for fulfillment\n\tconst AndBITFCMap::value_type& andbit = select_andbit();\n\tLAZY_BC_LOG_DEBUG << \"Selected and-BIT for fulfillment:\" << std::endl\n\t << andbit.second;\n\tfulfill_andbit(andbit);\n}\n\nvoid BackwardChainer::fulfill_andbit(const AndBITFCMap::value_type& andbit)\n{\n\tHandle hresult = bindlink(&_as, andbit.second);\n\tconst HandleSeq& results = hresult->getOutgoingSet();\n\tLAZY_BC_LOG_DEBUG << \"Results:\" << std::endl << results;\n\t_results.insert(results.begin(), results.end());\n}\n\nconst AndBITFCMap::value_type& BackwardChainer::select_andbit()\n{\n\t\/\/ For now selection is uniformly random\n\treturn rand_element(_andbits);\n}\n\nBITNode& BackwardChainer::select_bitleaf(const AndBITFCMap::value_type& andbit)\n{\n\t\/\/ For now selection is uniformly random\n\treturn _handle2bitnode[rand_element(andbit.first)];\n}\n\nBITNode* BackwardChainer::select_target()\n{\n\tif (_handle2bitnode.empty())\n\t\treturn nullptr;\n\n\t\/\/ For now selection is uniformly random\n\treturn &(rand_element(_handle2bitnode).second);\n}\n\nvoid BackwardChainer::reduce_bit()\n{\n\t\/\/ TODO: avoid having the BIT grow arbitrarily large\n}\n\nRule BackwardChainer::select_rule(const BITNode& target)\n{\n\t\/\/ For now the rule is uniformly randomly selected amongst the\n\t\/\/ valid ones\n\tRuleSeq valid_rules = get_valid_rules(target);\n\tif (valid_rules.empty())\n\t\treturn Rule();\n\treturn rand_element(valid_rules);\n}\n\nRuleSeq BackwardChainer::get_valid_rules(const BITNode& target)\n{\n\tRuleSeq valid_rules;\n\tfor (const Rule& rule : _rules) {\n\t\t\/\/ Warning: the resulting rules are not added to _bit_as, this\n\t\t\/\/ is in order to work around the fact that atomspace would\n\t\t\/\/ consider alpha equivalent rules equal and thus rename the\n\t\t\/\/ variable names, which is then inconvenient when building\n\t\t\/\/ the forward chaining strategy because we have no garanty\n\t\t\/\/ that the variable names will be unique.\n\t\t\/\/\n\t\t\/\/ It is likely that it is not the right way to do it. Instead\n\t\t\/\/ the fcs expansion code should make sure that the variable\n\t\t\/\/ names are unique while expanding.\n\t\t\/\/\n\t\t\/\/ So this might be a temporary hack.\n\t\tRuleSeq unified_rules = rule.unify_target(target.body,\n\t\t target.vardecl);\/\/, &_bit_as);\n\t\tvalid_rules.insert(valid_rules.end(),\n\t\t unified_rules.begin(), unified_rules.end());\n\t}\n\treturn valid_rules;\n}\n\nvoid BackwardChainer::insert_h2b(Handle body, Handle vardecl,\n const BITFitness& fitness)\n{\n\tif (body.is_undefined())\n\t\treturn;\n\n\t\/\/ Make sure they are in the bit atomspace\n\tbody = _bit_as.add_atom(body);\n\tvardecl = _bit_as.add_atom(vardecl);\n\n\t_handle2bitnode[body] = BITNode(body, vardecl, fitness);\n}\n\nvoid BackwardChainer::init_andbits()\n{\n\tif (_init_target.is_undefined())\n\t\treturn;\n\n\tHandleSeq bl{_init_target, _init_target};\n\tif (_init_vardecl.is_defined())\n\t\tbl.insert(bl.begin(), _init_vardecl);\n\tHandle fcs = _bit_as.add_link(BIND_LINK, bl);\n\t_andbits[{_init_target}] = fcs;\n}\n\nbool BackwardChainer::is_in(const Rule& rule, const BITNode& bitnode)\n{\n\tfor (const Rule& bnr : bitnode.rules)\n\t\tif (rule.is_alpha_equivalent(bnr))\n\t\t\treturn true;\n\treturn false;\n}\n<commit_msg>Simplify BackwardChainer rule atomspace management<commit_after>\/*\n * BackwardChainer.cc\n *\n * Copyright (C) 2014-2016 OpenCog Foundation\n *\n * Authors: Misgana Bayetta <misgana.bayetta@gmail.com> October 2014\n * William Ma <https:\/\/github.com\/williampma>\n * Nil Geisweiller 2016\n *\n * This program is free software; you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License v3 as\n * published by the Free Software Foundation and including the exceptions\n * at http:\/\/opencog.org\/wiki\/Licenses\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public License\n * along with this program; if not, write to:\n * Free Software Foundation, Inc.,\n * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.\n *\/\n\n#include <opencog\/util\/random.h>\n\n#include <opencog\/atomutils\/FindUtils.h>\n#include <opencog\/atomutils\/Substitutor.h>\n#include <opencog\/atomutils\/Unify.h>\n#include <opencog\/atomutils\/TypeUtils.h>\n#include <opencog\/atoms\/pattern\/PatternLink.h>\n#include <opencog\/atoms\/pattern\/BindLink.h>\n\n#include <opencog\/query\/BindLinkAPI.h>\n\n#include \"BackwardChainer.h\"\n#include \"BackwardChainerPMCB.h\"\n#include \"UnifyPMCB.h\"\n#include \"BCLogger.h\"\n\nusing namespace opencog;\n\nBackwardChainer::BackwardChainer(AtomSpace& as, const Handle& rbs,\n const Handle& htarget,\n const Handle& vardecl,\n const Handle& hfocus_set, \/\/ TODO:\n \/\/ support\n \/\/ focus_set\n const BITFitness& fitness)\n\t: _as(as), _configReader(as, rbs),\n\t _init_target(htarget), _init_vardecl(vardecl), _init_fitness(fitness),\n\t _bit_as(&as), _iteration(0), _rules(_configReader.get_rules()) {}\n\nUREConfigReader& BackwardChainer::get_config()\n{\n\treturn _configReader;\n}\n\nconst UREConfigReader& BackwardChainer::get_config() const\n{\n\treturn _configReader;\n}\n\nvoid BackwardChainer::do_chain()\n{\n\twhile (not termination())\n\t{\n\t\tdo_step();\n\t}\n}\n\nvoid BackwardChainer::do_step()\n{\n\tbc_logger().debug(\"Iteration %d\", _iteration);\n\t_iteration++;\n\n\texpand_bit();\n\tfulfill_bit();\n\treduce_bit();\n}\n\nbool BackwardChainer::termination()\n{\n\treturn _configReader.get_maximum_iterations() <= _iteration;\n}\n\nHandle BackwardChainer::get_results() const\n{\n\tHandleSeq results(_results.begin(), _results.end());\n\treturn _as.add_link(SET_LINK, results);\n}\n\nvoid BackwardChainer::expand_bit()\n{\n\tif (_handle2bitnode.empty()) {\n\t\t\/\/ Initialize the and-BIT of the initial target\n\t\tinsert_h2b(_init_target, _init_vardecl, _init_fitness);\n\t\tinit_andbits();\n\n\t\tLAZY_BC_LOG_DEBUG << \"Initialize BIT with:\" << std::endl\n\t\t << _handle2bitnode[_init_target].to_string();\n\t} else {\n\t\t\/\/ Select an and-BIT and expand it\n\t\tconst AndBITFCMap::value_type& andbit = select_andbit();\n\t\tLAZY_BC_LOG_DEBUG << \"Selected and-BIT for expansion:\" << std::endl\n\t\t << andbit.second;\n\t\texpand_bit(andbit);\n\t}\n}\n\nvoid BackwardChainer::expand_bit(const AndBITFCMap::value_type& andbit)\n{\n\t\/\/ Select leaf\n\tBITNode& bitleaf = select_bitleaf(andbit);\n\tLAZY_BC_LOG_DEBUG << \"Selected BIT-node for expansion:\" << std::endl\n\t << bitleaf.to_string();\n\n\t\/\/ Select a valid rule\n\tRule rule = select_rule(bitleaf);\n\trule.add(_bit_as);\n\tif (not rule.is_valid()) {\n\t\tbc_logger().warn(\"No valid rule for the selected BIT-node, abort expansion\");\n\t\treturn;\n\t}\n\tLAZY_BC_LOG_DEBUG << \"Selected rule for BIT expansion:\" << std::endl\n\t << rule.to_string();\n\n\t\/\/ Expand the back-inference tree from this target\n\texpand_bit(andbit, bitleaf, rule);\n}\n\nvoid BackwardChainer::expand_bit(const AndBITFCMap::value_type& andbit,\n BITNode& bitleaf, const Rule& rule)\n{\n\t\/\/ Make sure that the rule is not a or-child of leaf.\n\tif (is_in(rule, bitleaf)) {\n\t\tbc_logger().debug() << \"An equivalent rule has already expanded that BIT-node, abort expansion\";\n\t\treturn;\n\t}\n\n\t\/\/ Expand the leaf\n\t\/\/ 1. Append the rule to it\n\t\/\/ 2. Instantiate the premises as BITNodes\n\tHandleSeq premises(rule.get_premises());\n\tbitleaf.rules.push_back(rule);\n\tfor (const Handle& premise : premises)\n\t\tinsert_h2b(premise, rule.get_forward_vardecl(), BITFitness());\n\n\t\/\/ Expand the associated atomese forward chaining strategy\n\tHandle fcs = expand_fcs(andbit.second, bitleaf.body, rule);\n\n\t\/\/ Define new and-BIT and associate new forward chaining strategy\n\t\/\/ to it\n\tAndBITFCMap::key_type new_leaves(andbit.first);\n\tnew_leaves.erase(bitleaf.body);\n\tnew_leaves.insert(premises.begin(), premises.end());\n\t_andbits[new_leaves] = fcs;\n}\n\nHandle BackwardChainer::expand_fcs(const Handle& fcs, const Handle& leaf,\n const Rule& rule)\n{\n\tBindLinkPtr fcs_bl(BindLinkCast(fcs));\n\tHandle fcs_vardecl = fcs_bl->get_vardecl();\n\tHandle fcs_pattern = fcs_bl->get_body();\n\tHandle fcs_rewrite = fcs_bl->get_implicand();\n\tHandle rule_vardecl = rule.get_forward_vardecl();\n\tHandleSeq premises = rule.get_premises();\n\tHandle rule_rewrite = rule.get_forward_implicand();\n\n\t\/\/ Generate new pattern term\n\tHandle npattern = expand_fcs_pattern(fcs_pattern, leaf, premises);\n\n\t\/\/ Generate new rewrite term\n\tHandle nrewrite = expand_fcs_rewrite(fcs_rewrite, leaf, rule_rewrite);\n\n\t\/\/ Generate new vardecl\n\tHandle nvardecl = filter_vardecl(merge_vardecl(fcs_vardecl, rule_vardecl),\n\t {npattern, nrewrite});\n\n\t\/\/ Generate new atomese forward chaining strategy\n\tHandleSeq noutgoings({npattern, nrewrite});\n\tif (nvardecl.is_defined())\n\t\tnoutgoings.insert(noutgoings.begin(), nvardecl);\n\tHandle nfcs = _bit_as.add_link(BIND_LINK, noutgoings);\n\n\tLAZY_BC_LOG_DEBUG << \"Expanded forward chainer strategy:\" << std::endl << fcs\n\t << \"to:\" << std::endl << nfcs;\n\n\treturn nfcs;\n}\n\nHandle BackwardChainer::expand_fcs_pattern(const Handle& fcs_pattern,\n const Handle& leaf,\n const HandleSeq& premises)\n{\n\tif (fcs_pattern == leaf)\n\t\treturn _bit_as.add_link(AND_LINK, premises);\n\n\tOC_ASSERT(fcs_pattern->getType() == AND_LINK);\n\tHandleSeq outgoings = fcs_pattern->getOutgoingSet();\n\tauto it = std::find(outgoings.begin(), outgoings.end(), leaf);\n\tOC_ASSERT(it != outgoings.end());\n\toutgoings.erase(it);\n\toutgoings.insert(outgoings.end(), premises.begin(), premises.end());\n\treturn _bit_as.add_link(AND_LINK, outgoings);\n}\n\nHandle BackwardChainer::expand_fcs_rewrite(const Handle& fcs_rewrite,\n const Handle& leaf,\n const Handle& rule_rewrite)\n{\n\t\/\/ Base cases\n\n\t\/\/ Replace the fcs rewrite atoms by the rule_rewrite if leaf\n\tif (fcs_rewrite == leaf)\n\t\treturn rule_rewrite;\n\t\/\/ If node and isn't leaf leave alone\n\tif (fcs_rewrite->isNode())\n\t\treturn fcs_rewrite;\n\n\t\/\/ Recursive case\n\n\tType t = fcs_rewrite->getType();\n\tHandleSeq outgoings;\n\tfor (const Handle& h : fcs_rewrite->getOutgoingSet())\n\t\toutgoings.push_back(expand_fcs_rewrite(h, leaf, rule_rewrite));\n\treturn _bit_as.add_link(t, outgoings);\n}\n\nvoid BackwardChainer::fulfill_bit()\n{\n\tif (_andbits.empty()) {\n\t\tbc_logger().warn(\"Cannot fulfill an empty BIT\");\n\t\treturn;\n\t}\n\n\t\/\/ Select an and-BIT for fulfillment\n\tconst AndBITFCMap::value_type& andbit = select_andbit();\n\tLAZY_BC_LOG_DEBUG << \"Selected and-BIT for fulfillment:\" << std::endl\n\t << andbit.second;\n\tfulfill_andbit(andbit);\n}\n\nvoid BackwardChainer::fulfill_andbit(const AndBITFCMap::value_type& andbit)\n{\n\tHandle hresult = bindlink(&_as, andbit.second);\n\tconst HandleSeq& results = hresult->getOutgoingSet();\n\tLAZY_BC_LOG_DEBUG << \"Results:\" << std::endl << results;\n\t_results.insert(results.begin(), results.end());\n}\n\nconst AndBITFCMap::value_type& BackwardChainer::select_andbit()\n{\n\t\/\/ For now selection is uniformly random\n\treturn rand_element(_andbits);\n}\n\nBITNode& BackwardChainer::select_bitleaf(const AndBITFCMap::value_type& andbit)\n{\n\t\/\/ For now selection is uniformly random\n\treturn _handle2bitnode[rand_element(andbit.first)];\n}\n\nBITNode* BackwardChainer::select_target()\n{\n\tif (_handle2bitnode.empty())\n\t\treturn nullptr;\n\n\t\/\/ For now selection is uniformly random\n\treturn &(rand_element(_handle2bitnode).second);\n}\n\nvoid BackwardChainer::reduce_bit()\n{\n\t\/\/ TODO: avoid having the BIT grow arbitrarily large\n}\n\nRule BackwardChainer::select_rule(const BITNode& target)\n{\n\t\/\/ For now the rule is uniformly randomly selected amongst the\n\t\/\/ valid ones\n\tRuleSeq valid_rules = get_valid_rules(target);\n\tif (valid_rules.empty())\n\t\treturn Rule();\n\treturn rand_element(valid_rules);\n}\n\nRuleSeq BackwardChainer::get_valid_rules(const BITNode& target)\n{\n\tRuleSeq valid_rules;\n\tfor (const Rule& rule : _rules) {\n\t\tRuleSeq unified_rules = rule.unify_target(target.body, target.vardecl);\n\t\tvalid_rules.insert(valid_rules.end(),\n\t\t unified_rules.begin(), unified_rules.end());\n\t}\n\treturn valid_rules;\n}\n\nvoid BackwardChainer::insert_h2b(Handle body, Handle vardecl,\n const BITFitness& fitness)\n{\n\tif (body.is_undefined())\n\t\treturn;\n\n\t_handle2bitnode[body] = BITNode(body, vardecl, fitness);\n}\n\nvoid BackwardChainer::init_andbits()\n{\n\tif (_init_target.is_undefined())\n\t\treturn;\n\n\tHandleSeq bl{_init_target, _init_target};\n\tif (_init_vardecl.is_defined())\n\t\tbl.insert(bl.begin(), _init_vardecl);\n\tHandle fcs = _bit_as.add_link(BIND_LINK, bl);\n\t_andbits[{_init_target}] = fcs;\n}\n\nbool BackwardChainer::is_in(const Rule& rule, const BITNode& bitnode)\n{\n\tfor (const Rule& bnr : bitnode.rules)\n\t\tif (rule.is_alpha_equivalent(bnr))\n\t\t\treturn true;\n\treturn false;\n}\n<|endoftext|>"} {"text":"<commit_before>#ifndef ELLIPTIC_PARAMETERS\n#define ELLIPTIC_PARAMETERS\n\n\n\/\/*********************** Sets Number of subdivisions in X and Y direction *****************************************\n\n#define NSUB_X 32\n#define NSUB_Y 32\n\n\n\/\/*********************** Sets the regularization parameters *******************************************************\n#define ALPHA_CTRL_BDRY 1.e-3\n#define BETA_CTRL_BDRY 1.e-2\n\n\n#define ALPHA_CTRL_VOL 1.e-3\n#define BETA_CTRL_VOL 1.e-2\n\n\n\/\/*********************** Control box constraints *******************************************************\n#define INEQ_FLAG 1.\n#define C_COMPL 1.\n\n\n double InequalityConstraint(const std::vector<double> & dof_obj_coord, const bool upper) {\n\n double constr_value = 0.;\n double constr_value_upper = 1000.;\/\/0.3; \/\/0.2 + dof_obj_coord[0]*(1. - dof_obj_coord[0]);\n double constr_value_lower = -1000.; \/\/-3.e-13;\n assert(constr_value_lower < constr_value_upper); \n \n if (upper) constr_value = constr_value_upper;\n else constr_value = constr_value_lower; \n \n \n return constr_value;\n \n}\n \n\n\n\/\/*********************** Find volume elements that contain a Target domain element **************************************\n\nint ElementTargetFlag(const std::vector<double> & elem_center) {\n\n \/\/***** set target domain flag ******\n int target_flag = 0; \/\/set 0 to 1 to get the entire domain\n \n double target_line_sign;\n \n if (FACE_FOR_CONTROL == 3 || FACE_FOR_CONTROL == 2) { target_line_sign = -1; }\n else if (FACE_FOR_CONTROL == 1 || FACE_FOR_CONTROL == 4) { target_line_sign = 1; }\n \n const double offset_to_include_line = 1.e-5;\n const double target_line = 0.5 + target_line_sign * offset_to_include_line; \n \n if ( target_line_sign * elem_center[1-AXIS_DIRECTION_CONTROL_SIDE] < target_line_sign * target_line ) { target_flag = 1; }\n \n return target_flag;\n\n}\n\n\n\/\/******************************************* Desired Target *******************************************************\n\ndouble DesiredTarget()\n{\n return 1.;\n}\n\n\n\n\n\/\/*********************** Find volume elements that contain a Control Face element *********************************\n\nint ControlDomainFlag_bdry(const std::vector<double> & elem_center) {\n\n const double mesh_size = 1.\/NSUB_X;\n \n int control_el_flag = 0;\n \n const double offset_to_include_line = 1.e-5;\n\n double target_line_sign;\n double extreme_pos;\n \n if (FACE_FOR_CONTROL == 3 || FACE_FOR_CONTROL == 2) { target_line_sign = -1; extreme_pos = 1.; }\n else if (FACE_FOR_CONTROL == 1 || FACE_FOR_CONTROL == 4) { target_line_sign = 1; extreme_pos = 0.; }\n\n \n if ( ( target_line_sign * elem_center[1-AXIS_DIRECTION_CONTROL_SIDE] < target_line_sign * ( extreme_pos + target_line_sign * mesh_size) )\n\/* && ( elem_center[AXIS_DIRECTION_CONTROL_SIDE] > 0.25 - offset_to_include_line ) \n && ( elem_center[AXIS_DIRECTION_CONTROL_SIDE] < 0.75 + offset_to_include_line ) *\/)\n { control_el_flag = 1; }\n\n return control_el_flag;\n}\n\n\n\n\/\/*********************** Find volume elements that contain a Control domain element *********************************\n\nint ControlDomainFlag_internal_restriction(const std::vector<double> & elem_center) {\n\n \/\/***** set target domain flag ******\n \/\/ flag = 1: we are in the lifting nonzero domain\n int control_el_flag = 0.;\n \n const double offset_to_include_line = 1.e-5;\n \n double control_domain_width = 0.25;\n \n double target_line_sign;\n double extreme_pos;\n \n if (FACE_FOR_CONTROL == 3 || FACE_FOR_CONTROL == 2) { target_line_sign = -1; extreme_pos = 1.;}\n else if (FACE_FOR_CONTROL == 1 || FACE_FOR_CONTROL == 4) { target_line_sign = 1; extreme_pos = 0.;}\n \n if ( ( target_line_sign * elem_center[1-AXIS_DIRECTION_CONTROL_SIDE] < target_line_sign * ( extreme_pos + target_line_sign * control_domain_width ) )\n \/* && ( elem_center[AXIS_DIRECTION_CONTROL_SIDE] > 0.25 - offset_to_include_line ) \n && ( elem_center[AXIS_DIRECTION_CONTROL_SIDE] < 0.75 + offset_to_include_line ) *\/)\n { control_el_flag = 1; }\n \n return control_el_flag;\n\n}\n\n\n\/\/*********************** Find volume elements that contain a Control domain element *********************************\n\nint ControlDomainFlag_external_restriction(const std::vector<double> & elem_center) {\n\n \/\/***** set target domain flag ******\n \/\/ flag = 1: we are in the lifting nonzero domain\n int exterior_el_flag = 0.;\n if ( elem_center[0] > 1. - 1.e-5) { exterior_el_flag = 1; }\n\n return exterior_el_flag;\n\n}\n\n\n\n\n#endif\n<commit_msg>Changed the Target domain for the external lift restriction problem<commit_after>#ifndef ELLIPTIC_PARAMETERS\n#define ELLIPTIC_PARAMETERS\n\n\n\/\/*********************** Sets Number of subdivisions in X and Y direction *****************************************\n\n#define NSUB_X 32\n#define NSUB_Y 32\n\n\n\/\/*********************** Sets the regularization parameters *******************************************************\n#define ALPHA_CTRL_BDRY 1.e-3\n#define BETA_CTRL_BDRY 1.e-2\n\n\n#define ALPHA_CTRL_VOL 1.e-3\n#define BETA_CTRL_VOL 1.e-2\n\n\n\/\/*********************** Control box constraints *******************************************************\n#define INEQ_FLAG 1.\n#define C_COMPL 1.\n\n\n double InequalityConstraint(const std::vector<double> & dof_obj_coord, const bool upper) {\n\n double constr_value = 0.;\n double constr_value_upper = 1000.;\/\/0.3; \/\/0.2 + dof_obj_coord[0]*(1. - dof_obj_coord[0]);\n double constr_value_lower = -1000.; \/\/-3.e-13;\n assert(constr_value_lower < constr_value_upper); \n \n if (upper) constr_value = constr_value_upper;\n else constr_value = constr_value_lower; \n \n \n return constr_value;\n \n}\n \n\n\n\/\/*********************** Find volume elements that contain a Target domain element **************************************\n\nint ElementTargetFlag(const std::vector<double> & elem_center) {\n\n \/\/***** set target domain flag ******\n int target_flag = 0; \/\/set 0 to 1 to get the entire domain\n \n double target_line_sign;\n \n if (FACE_FOR_CONTROL == 3 || FACE_FOR_CONTROL == 2) { target_line_sign = -1; }\n else if (FACE_FOR_CONTROL == 1 || FACE_FOR_CONTROL == 4) { target_line_sign = 1; }\n \n const double offset_to_include_line = 1.e-5;\n const double target_line = 0.5 + target_line_sign * offset_to_include_line; \n \n if (( target_line_sign * elem_center[1-AXIS_DIRECTION_CONTROL_SIDE] < target_line_sign * target_line ) && \n ( target_line_sign * elem_center[1-AXIS_DIRECTION_CONTROL_SIDE] > - 0.5 + target_line_sign * (0.5 - target_line_sign * offset_to_include_line)))\n { target_flag = 1; }\n \n return target_flag;\n\n}\n\n\n\/\/******************************************* Desired Target *******************************************************\n\ndouble DesiredTarget()\n{\n return 1.;\n}\n\n\n\n\n\/\/*********************** Find volume elements that contain a Control Face element *********************************\n\nint ControlDomainFlag_bdry(const std::vector<double> & elem_center) {\n\n const double mesh_size = 1.\/NSUB_X;\n \n int control_el_flag = 0;\n \n const double offset_to_include_line = 1.e-5;\n\n double target_line_sign;\n double extreme_pos;\n \n if (FACE_FOR_CONTROL == 3 || FACE_FOR_CONTROL == 2) { target_line_sign = -1; extreme_pos = 1.; }\n else if (FACE_FOR_CONTROL == 1 || FACE_FOR_CONTROL == 4) { target_line_sign = 1; extreme_pos = 0.; }\n\n \n if ( ( target_line_sign * elem_center[1-AXIS_DIRECTION_CONTROL_SIDE] < target_line_sign * ( extreme_pos + target_line_sign * mesh_size) )\n\/* && ( elem_center[AXIS_DIRECTION_CONTROL_SIDE] > 0.25 - offset_to_include_line ) \n && ( elem_center[AXIS_DIRECTION_CONTROL_SIDE] < 0.75 + offset_to_include_line ) *\/)\n { control_el_flag = 1; }\n\n return control_el_flag;\n}\n\n\n\n\/\/*********************** Find volume elements that contain a Control domain element *********************************\n\nint ControlDomainFlag_internal_restriction(const std::vector<double> & elem_center) {\n\n \/\/***** set target domain flag ******\n \/\/ flag = 1: we are in the lifting nonzero domain\n int control_el_flag = 0.;\n \n const double offset_to_include_line = 1.e-5;\n \n double control_domain_width = 0.25;\n \n double target_line_sign;\n double extreme_pos;\n \n if (FACE_FOR_CONTROL == 3 || FACE_FOR_CONTROL == 2) { target_line_sign = -1; extreme_pos = 1.;}\n else if (FACE_FOR_CONTROL == 1 || FACE_FOR_CONTROL == 4) { target_line_sign = 1; extreme_pos = 0.;}\n \n if ( ( target_line_sign * elem_center[1-AXIS_DIRECTION_CONTROL_SIDE] < target_line_sign * ( extreme_pos + target_line_sign * control_domain_width ) )\n \/* && ( elem_center[AXIS_DIRECTION_CONTROL_SIDE] > 0.25 - offset_to_include_line ) \n && ( elem_center[AXIS_DIRECTION_CONTROL_SIDE] < 0.75 + offset_to_include_line ) *\/)\n { control_el_flag = 1; }\n \n return control_el_flag;\n\n}\n\n\n\/\/*********************** Find volume elements that contain a Control domain element *********************************\n\nint ControlDomainFlag_external_restriction(const std::vector<double> & elem_center) {\n\n \/\/***** set target domain flag ******\n \/\/ flag = 1: we are in the lifting nonzero domain\n int exterior_el_flag = 0.;\n if ( elem_center[0] > 1. - 1.e-5) { exterior_el_flag = 1; }\n\n return exterior_el_flag;\n\n}\n\n\n\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>#pragma ident \"$Id$\"\n\n\n\n\/\/============================================================================\n\/\/\n\/\/ This file is part of GPSTk, the GPS Toolkit.\n\/\/\n\/\/ The GPSTk is free software; you can redistribute it and\/or modify\n\/\/ it under the terms of the GNU Lesser General Public License as published\n\/\/ by the Free Software Foundation; either version 2.1 of the License, or\n\/\/ any later version.\n\/\/\n\/\/ The GPSTk is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n\/\/ GNU Lesser General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License along with GPSTk; if not, write to the Free Software Foundation,\n\/\/ Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n\/\/ \n\/\/ Copyright 2004, The University of Texas at Austin\n\/\/\n\/\/============================================================================\n\n\/\/============================================================================\n\/\/\n\/\/This software developed by Applied Research Laboratories at the University of\n\/\/Texas at Austin, under contract to an agency or agencies within the U.S. \n\/\/Department of Defense. The U.S. Government retains all rights to use,\n\/\/duplicate, distribute, disclose, or release this software. \n\/\/\n\/\/Pursuant to DoD Directive 523024 \n\/\/\n\/\/ DISTRIBUTION STATEMENT A: This software has been approved for public \n\/\/ release, distribution is unlimited.\n\/\/\n\/\/=============================================================================\n\n\n\n\n\n\n\/**\n * @file SP3EphemerisStore.cpp\n * Read & store SP3 formated ephemeris data\n *\/\n\n#include \"SP3EphemerisStore.hpp\"\n#include \"MiscMath.hpp\"\n#include \"ECEF.hpp\"\n#include \"icd_200_constants.hpp\"\n\nusing namespace gpstk::StringUtils;\n\nnamespace gpstk\n{\n \/\/-----------------------------------------------------------------------------\n \/\/-----------------------------------------------------------------------------\n void SP3EphemerisStore::loadFile(const std::string& filename)\n throw(FileMissingException)\n {\n try\n {\n SP3Stream strm(filename.c_str());\n if (!strm)\n {\n FileMissingException e(\"File \" + filename + \" could not be opened.\");\n GPSTK_THROW(e);\n }\n \n SP3Header header;\n strm >> header;\n\n addFile(filename, header);\n\n \/\/\/ If any file doesn't have the velocity data, clear the\n \/\/\/ the flag indicating that there is any velocity data\n if (tolower(header.pvFlag) != 'v')\n setHaveVelocity(false);\n\n SP3Data rec;\n while(strm >> rec)\n addEphemeris(rec);\n }\n catch (gpstk::Exception& e)\n {\n GPSTK_RETHROW(e);\n }\n } \/\/ end SP3EphemerisStore::load\n\n\n \/\/--------------------------------------------------------------------------\n \/\/--------------------------------------------------------------------------\n void SP3EphemerisStore::dump(short detail, std::ostream& s) const\n {\n s << \"Dump of SP3EphemerisStore:\" << std::endl;\n std::vector<std::string> fileNames = getFileNames();\n std::vector<std::string>::const_iterator f=fileNames.begin();\n for (f=fileNames.begin(); f!=fileNames.end(); f++)\n s << *f << std::endl;\n\/*\n Add this back in when\/if we add header info to the file store.\n while(fmi != fm.end()) {\n s << \" File \" << fmi->first << \", Times: \" << fmi->second.time\n << \" to \" << (fmi->second.time+fmi->second.epochInterval*fmi->second.numberOfEpochs)\n << \", (\" << fmi->second.numberOfEpochs\n << \" \" << fmi->second.epochInterval << \"sec intervals).\" << std::endl;\n if(detail > 0) {\n s << \" Data used as input : \" << fmi->second.dataUsed\n << \" Coordinate system : \" << fmi->second.coordSystem << std::endl;\n s << \" Orbit estimate type : \" << fmi->second.orbitType\n << \" Agency : \" << fmi->second.agency << std::endl;\n s << \" List of satellite PRN\/acc (\" << fmi->second.svList.size()\n << \" total) :\\n\";\n int i=0;\n std::map<short,short>::const_iterator it=fmi->second.svList.begin();\n while(it != fmi->second.svList.end()) {\n s << \" \" << std::setw(2) << it->first << \"\/\" << it->second;\n if(!(++i % 8)) s << std::endl;\n it++;\n }\n if(++i % 8) s << std::endl;\n s << \" Comments:\\n\";\n for(i=0; i<fmi->second.comments.size(); i++)\n s << \" \" << fmi->second.comments[i] << std::endl;\n s << std::endl;\n }\n fmi++;\n }\n*\/\n TabularEphemerisStore::dump(detail, s);\n\n } \/\/ end of SP3EphemerisStore::dump\n\n} \/\/ namespace gpstk\n<commit_msg>set data version to header version while loading SP3 file<commit_after>#pragma ident \"$Id$\"\n\n\n\n\/\/============================================================================\n\/\/\n\/\/ This file is part of GPSTk, the GPS Toolkit.\n\/\/\n\/\/ The GPSTk is free software; you can redistribute it and\/or modify\n\/\/ it under the terms of the GNU Lesser General Public License as published\n\/\/ by the Free Software Foundation; either version 2.1 of the License, or\n\/\/ any later version.\n\/\/\n\/\/ The GPSTk is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n\/\/ GNU Lesser General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License along with GPSTk; if not, write to the Free Software Foundation,\n\/\/ Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n\/\/ \n\/\/ Copyright 2004, The University of Texas at Austin\n\/\/\n\/\/============================================================================\n\n\/\/============================================================================\n\/\/\n\/\/This software developed by Applied Research Laboratories at the University of\n\/\/Texas at Austin, under contract to an agency or agencies within the U.S. \n\/\/Department of Defense. The U.S. Government retains all rights to use,\n\/\/duplicate, distribute, disclose, or release this software. \n\/\/\n\/\/Pursuant to DoD Directive 523024 \n\/\/\n\/\/ DISTRIBUTION STATEMENT A: This software has been approved for public \n\/\/ release, distribution is unlimited.\n\/\/\n\/\/=============================================================================\n\n\n\n\n\n\n\/**\n * @file SP3EphemerisStore.cpp\n * Read & store SP3 formated ephemeris data\n *\/\n\n#include \"SP3EphemerisStore.hpp\"\n#include \"MiscMath.hpp\"\n#include \"ECEF.hpp\"\n#include \"icd_200_constants.hpp\"\n\nusing namespace gpstk::StringUtils;\n\nnamespace gpstk\n{\n \/\/-----------------------------------------------------------------------------\n \/\/-----------------------------------------------------------------------------\n void SP3EphemerisStore::loadFile(const std::string& filename)\n throw(FileMissingException)\n {\n try\n {\n SP3Stream strm(filename.c_str());\n if (!strm)\n {\n FileMissingException e(\"File \" + filename + \" could not be opened.\");\n GPSTK_THROW(e);\n }\n \n SP3Header header;\n strm >> header;\n\n addFile(filename, header);\n\n \/\/\/ If any file doesn't have the velocity data, clear the\n \/\/\/ the flag indicating that there is any velocity data\n if (tolower(header.pvFlag) != 'v')\n setHaveVelocity(false);\n\n SP3Data rec;\n while(strm >> rec) {\n rec.version = header.version;\n addEphemeris(rec);\n }\n }\n catch (gpstk::Exception& e)\n {\n GPSTK_RETHROW(e);\n }\n } \/\/ end SP3EphemerisStore::load\n\n\n \/\/--------------------------------------------------------------------------\n \/\/--------------------------------------------------------------------------\n void SP3EphemerisStore::dump(short detail, std::ostream& s) const\n {\n s << \"Dump of SP3EphemerisStore:\" << std::endl;\n std::vector<std::string> fileNames = getFileNames();\n std::vector<std::string>::const_iterator f=fileNames.begin();\n for (f=fileNames.begin(); f!=fileNames.end(); f++)\n s << *f << std::endl;\n\/*\n Add this back in when\/if we add header info to the file store.\n while(fmi != fm.end()) {\n s << \" File \" << fmi->first << \", Times: \" << fmi->second.time\n << \" to \" << (fmi->second.time+fmi->second.epochInterval*fmi->second.numberOfEpochs)\n << \", (\" << fmi->second.numberOfEpochs\n << \" \" << fmi->second.epochInterval << \"sec intervals).\" << std::endl;\n if(detail > 0) {\n s << \" Data used as input : \" << fmi->second.dataUsed\n << \" Coordinate system : \" << fmi->second.coordSystem << std::endl;\n s << \" Orbit estimate type : \" << fmi->second.orbitType\n << \" Agency : \" << fmi->second.agency << std::endl;\n s << \" List of satellite PRN\/acc (\" << fmi->second.svList.size()\n << \" total) :\\n\";\n int i=0;\n std::map<short,short>::const_iterator it=fmi->second.svList.begin();\n while(it != fmi->second.svList.end()) {\n s << \" \" << std::setw(2) << it->first << \"\/\" << it->second;\n if(!(++i % 8)) s << std::endl;\n it++;\n }\n if(++i % 8) s << std::endl;\n s << \" Comments:\\n\";\n for(i=0; i<fmi->second.comments.size(); i++)\n s << \" \" << fmi->second.comments[i] << std::endl;\n s << std::endl;\n }\n fmi++;\n }\n*\/\n TabularEphemerisStore::dump(detail, s);\n\n } \/\/ end of SP3EphemerisStore::dump\n\n} \/\/ namespace gpstk\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright 2012 Google Inc.\n *\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n *\/\n\n#include \"SampleCode.h\"\n#include \"SkView.h\"\n#include \"SkCanvas.h\"\n#include \"SkPath.h\"\n#include \"SkRegion.h\"\n#include \"SkShader.h\"\n#include \"SkUtils.h\"\n#include \"SkImage.h\"\n#include \"SkSurface.h\"\n\n#define FAT_PIXEL_COLOR SK_ColorBLACK\n#define PIXEL_CENTER_SIZE 3\n#define WIRE_FRAME_COLOR 0xFFFF0000 \/*0xFF00FFFF*\/\n#define WIRE_FRAME_SIZE 1.5f\n\nstatic void erase(SkSurface* surface) {\n surface->getCanvas()->clear(0);\n}\n\nstatic SkShader* createChecker() {\n SkBitmap bm;\n bm.setConfig(SkBitmap::kARGB_8888_Config, 2, 2);\n bm.allocPixels();\n bm.lockPixels();\n *bm.getAddr32(0, 0) = *bm.getAddr32(1, 1) = SkPreMultiplyColor(0xFFFDFDFD);\n *bm.getAddr32(0, 1) = *bm.getAddr32(1, 0) = SkPreMultiplyColor(0xFFF4F4F4);\n SkShader* s = SkShader::CreateBitmapShader(bm, SkShader::kRepeat_TileMode,\n SkShader::kRepeat_TileMode);\n\n SkMatrix m;\n m.setScale(12, 12);\n s->setLocalMatrix(m);\n return s;\n}\n\nclass FatBits {\npublic:\n FatBits() : fShader(createChecker()) {\n fAA = false;\n fStyle = kHair_Style;\n fGrid = true;\n fShowSkeleton = true;\n fUseGPU = false;\n }\n\n int getZoom() const { return fZ; }\n\n bool getAA() const { return fAA; }\n void setAA(bool aa) { fAA = aa; }\n\n bool getGrid() const { return fGrid; }\n void setGrid(bool g) { fGrid = g; }\n\n bool getShowSkeleton() const { return fShowSkeleton; }\n void setShowSkeleton(bool ss) { fShowSkeleton = ss; }\n\n bool getUseGPU() const { return fUseGPU; }\n void setUseGPU(bool ug) { fUseGPU = ug; }\n\n enum Style {\n kHair_Style,\n kStroke_Style,\n };\n Style getStyle() const { return fStyle; }\n void setStyle(Style s) { fStyle = s; }\n\n void setWHZ(int width, int height, int zoom) {\n fW = width;\n fH = height;\n fZ = zoom;\n fBounds.set(0, 0, SkIntToScalar(width * zoom), SkIntToScalar(height * zoom));\n fMatrix.setScale(SkIntToScalar(zoom), SkIntToScalar(zoom));\n fInverse.setScale(SK_Scalar1 \/ zoom, SK_Scalar1 \/ zoom);\n fShader->setLocalMatrix(fMatrix);\n\n SkImage::Info info = {\n width, height, SkImage::kPMColor_ColorType, SkImage::kPremul_AlphaType\n };\n fMinSurface.reset(SkSurface::NewRaster(info, NULL));\n info.fWidth *= zoom;\n info.fHeight *= zoom;\n fMaxSurface.reset(SkSurface::NewRaster(info, NULL));\n }\n\n void drawBG(SkCanvas*);\n void drawFG(SkCanvas*);\n void drawLine(SkCanvas*, SkPoint pts[2]);\n void drawRect(SkCanvas* canvas, SkPoint pts[2]);\n\nprivate:\n bool fAA, fGrid, fShowSkeleton, fUseGPU;\n Style fStyle;\n int fW, fH, fZ;\n SkMatrix fMatrix, fInverse;\n SkRect fBounds;\n SkAutoTUnref<SkShader> fShader;\n SkAutoTUnref<SkSurface> fMinSurface;\n SkAutoTUnref<SkSurface> fMaxSurface;\n\n void setupPaint(SkPaint* paint) {\n bool aa = this->getAA();\n switch (fStyle) {\n case kHair_Style:\n paint->setStrokeWidth(0);\n break;\n case kStroke_Style:\n paint->setStrokeWidth(SK_Scalar1);\n\/\/ paint->setStrokeWidth(SK_Scalar1 + SK_Scalar1\/500);\n break;\n }\n paint->setAntiAlias(aa);\n }\n\n void setupSkeletonPaint(SkPaint* paint) {\n paint->setStyle(SkPaint::kStroke_Style);\n paint->setStrokeWidth(WIRE_FRAME_SIZE);\n paint->setColor(fShowSkeleton ? WIRE_FRAME_COLOR : 0);\n paint->setAntiAlias(true);\n }\n\n void drawLineSkeleton(SkCanvas* max, const SkPoint pts[]);\n void drawRectSkeleton(SkCanvas* max, const SkRect& r) {\n SkPaint paint;\n this->setupSkeletonPaint(&paint);\n SkPath path;\n\n if (fUseGPU && fAA) {\n SkRect rr = r;\n rr.inset(fZ\/2, fZ\/2);\n path.addRect(rr);\n path.moveTo(rr.fLeft, rr.fTop);\n path.lineTo(rr.fRight, rr.fBottom);\n rr = r;\n rr.inset(-fZ\/2, -fZ\/2);\n path.addRect(rr);\n } else {\n path.addRect(r);\n if (fUseGPU) {\n path.moveTo(r.fLeft, r.fTop);\n path.lineTo(r.fRight, r.fBottom);\n }\n }\n max->drawPath(path, paint);\n }\n\n void copyMinToMax() {\n erase(fMaxSurface);\n SkCanvas* canvas = fMaxSurface->getCanvas();\n canvas->save();\n canvas->concat(fMatrix);\n fMinSurface->draw(canvas, 0, 0, NULL);\n canvas->restore();\n\n SkPaint paint;\n paint.setXfermodeMode(SkXfermode::kClear_Mode);\n for (int iy = 1; iy < fH; ++iy) {\n SkScalar y = SkIntToScalar(iy * fZ);\n canvas->drawLine(0, y - SK_ScalarHalf, 999, y - SK_ScalarHalf, paint);\n }\n for (int ix = 1; ix < fW; ++ix) {\n SkScalar x = SkIntToScalar(ix * fZ);\n canvas->drawLine(x - SK_ScalarHalf, 0, x - SK_ScalarHalf, 999, paint);\n }\n }\n};\n\nvoid FatBits::drawBG(SkCanvas* canvas) {\n SkPaint paint;\n\n paint.setShader(fShader);\n canvas->drawRect(fBounds, paint);\n paint.setShader(NULL);\n}\n\nvoid FatBits::drawFG(SkCanvas* canvas) {\n SkPaint inner, outer;\n\n inner.setAntiAlias(true);\n inner.setColor(SK_ColorBLACK);\n inner.setStrokeWidth(PIXEL_CENTER_SIZE);\n\n outer.setAntiAlias(true);\n outer.setColor(SK_ColorWHITE);\n outer.setStrokeWidth(PIXEL_CENTER_SIZE + 2);\n\n SkScalar half = SkIntToScalar(fZ) \/ 2;\n for (int iy = 0; iy < fH; ++iy) {\n SkScalar y = SkIntToScalar(iy * fZ) + half;\n for (int ix = 0; ix < fW; ++ix) {\n SkScalar x = SkIntToScalar(ix * fZ) + half;\n\n canvas->drawPoint(x, y, outer);\n canvas->drawPoint(x, y, inner);\n }\n }\n}\n\nvoid FatBits::drawLineSkeleton(SkCanvas* max, const SkPoint pts[]) {\n SkPaint paint;\n this->setupSkeletonPaint(&paint);\n\n SkPath path;\n path.moveTo(pts[0]);\n path.lineTo(pts[1]);\n\n switch (fStyle) {\n case kHair_Style:\n if (fUseGPU) {\n SkPaint p;\n p.setStyle(SkPaint::kStroke_Style);\n p.setStrokeWidth(SK_Scalar1 * fZ);\n SkPath dst;\n p.getFillPath(path, &dst);\n path.addPath(dst);\n }\n break;\n case kStroke_Style: {\n SkPaint p;\n p.setStyle(SkPaint::kStroke_Style);\n p.setStrokeWidth(SK_Scalar1 * fZ);\n SkPath dst;\n p.getFillPath(path, &dst);\n path = dst;\n\n if (fUseGPU) {\n path.moveTo(dst.getPoint(0));\n path.lineTo(dst.getPoint(2));\n }\n } break;\n }\n max->drawPath(path, paint);\n}\n\nvoid FatBits::drawLine(SkCanvas* canvas, SkPoint pts[]) {\n SkPaint paint;\n\n fInverse.mapPoints(pts, 2);\n\n if (fGrid) {\n SkScalar dd = 0;\/\/SK_Scalar1 \/ 50;\n pts[0].set(SkScalarRoundToScalar(pts[0].fX) + dd,\n SkScalarRoundToScalar(pts[0].fY) + dd);\n pts[1].set(SkScalarRoundToScalar(pts[1].fX) + dd,\n SkScalarRoundToScalar(pts[1].fY) + dd);\n }\n\n erase(fMinSurface);\n this->setupPaint(&paint);\n paint.setColor(FAT_PIXEL_COLOR);\n fMinSurface->getCanvas()->drawLine(pts[0].fX, pts[0].fY, pts[1].fX, pts[1].fY, paint);\n this->copyMinToMax();\n\n SkCanvas* max = fMaxSurface->getCanvas();\n\n fMatrix.mapPoints(pts, 2);\n this->drawLineSkeleton(max, pts);\n\n fMaxSurface->draw(canvas, 0, 0, NULL);\n}\n\nvoid FatBits::drawRect(SkCanvas* canvas, SkPoint pts[2]) {\n SkPaint paint;\n\n fInverse.mapPoints(pts, 2);\n\n if (fGrid) {\n pts[0].set(SkScalarRoundToScalar(pts[0].fX), SkScalarRoundToScalar(pts[0].fY));\n pts[1].set(SkScalarRoundToScalar(pts[1].fX), SkScalarRoundToScalar(pts[1].fY));\n }\n\n SkRect r;\n r.set(pts, 2);\n\n erase(fMinSurface);\n this->setupPaint(&paint);\n paint.setColor(FAT_PIXEL_COLOR);\n fMinSurface->getCanvas()->drawRect(r, paint);\n this->copyMinToMax();\n\n SkCanvas* max = fMaxSurface->getCanvas();\n\n fMatrix.mapPoints(pts, 2);\n r.set(pts, 2);\n this->drawRectSkeleton(max, r);\n\n fMaxSurface->draw(canvas, 0, 0, NULL);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nclass IndexClick : public SkView::Click {\n int fIndex;\npublic:\n IndexClick(SkView* v, int index) : SkView::Click(v), fIndex(index) {}\n\n static int GetIndex(SkView::Click* click) {\n return ((IndexClick*)click)->fIndex;\n }\n};\n\nclass DrawLineView : public SampleView {\n FatBits fFB;\n SkPoint fPts[2];\n bool fIsRect;\npublic:\n DrawLineView() {\n fFB.setWHZ(24, 16, 48);\n fPts[0].set(48, 48);\n fPts[1].set(48 * 5, 48 * 4);\n fIsRect = false;\n }\n\n void setStyle(FatBits::Style s) {\n fFB.setStyle(s);\n this->inval(NULL);\n }\n\nprotected:\n virtual bool onQuery(SkEvent* evt) SK_OVERRIDE {\n if (SampleCode::TitleQ(*evt)) {\n SampleCode::TitleR(evt, \"FatBits\");\n return true;\n }\n SkUnichar uni;\n if (SampleCode::CharQ(*evt, &uni)) {\n switch (uni) {\n case 'r':\n fIsRect = !fIsRect;\n this->inval(NULL);\n return true;\n case 'x':\n fFB.setGrid(!fFB.getGrid());\n this->inval(NULL);\n return true;\n case 's':\n if (FatBits::kStroke_Style == fFB.getStyle()) {\n this->setStyle(FatBits::kHair_Style);\n } else {\n this->setStyle(FatBits::kStroke_Style);\n }\n return true;\n case 'a':\n fFB.setAA(!fFB.getAA());\n this->inval(NULL);\n return true;\n case 'w':\n fFB.setShowSkeleton(!fFB.getShowSkeleton());\n this->inval(NULL);\n return true;\n case 'g':\n fFB.setUseGPU(!fFB.getUseGPU());\n this->inval(NULL);\n return true;\n }\n }\n return this->INHERITED::onQuery(evt);\n }\n\n virtual void onDrawContent(SkCanvas* canvas) {\n fFB.drawBG(canvas);\n if (fIsRect) {\n fFB.drawRect(canvas, fPts);\n } else {\n fFB.drawLine(canvas, fPts);\n }\n fFB.drawFG(canvas);\n\n {\n SkString str;\n str.printf(\"%s %s %s\",\n fFB.getAA() ? \"AA\" : \"BW\",\n FatBits::kHair_Style == fFB.getStyle() ? \"Hair\" : \"Stroke\",\n fFB.getUseGPU() ? \"GPU\" : \"CPU\");\n SkPaint paint;\n paint.setAntiAlias(true);\n paint.setTextSize(16);\n paint.setColor(SK_ColorBLUE);\n canvas->drawText(str.c_str(), str.size(), 10, 16, paint);\n }\n }\n\n virtual SkView::Click* onFindClickHandler(SkScalar x, SkScalar y) {\n SkPoint pt = { x, y };\n int index = -1;\n SkScalar tol = 12;\n if (fPts[0].equalsWithinTolerance(pt, tol)) {\n index = 0;\n } else if (fPts[1].equalsWithinTolerance(pt, tol)) {\n index = 1;\n }\n return new IndexClick(this, index);\n }\n\n virtual bool onClick(Click* click) {\n int index = IndexClick::GetIndex(click);\n if (index >= 0 && index <= 1) {\n fPts[index] = click->fCurr;\n } else {\n SkScalar dx = click->fCurr.fX - click->fPrev.fX;\n SkScalar dy = click->fCurr.fY - click->fPrev.fY;\n fPts[0].offset(dx, dy);\n fPts[1].offset(dx, dy);\n }\n this->inval(NULL);\n return true;\n }\n\nprivate:\n\n typedef SampleView INHERITED;\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstatic SkView* MyFactory() { return new DrawLineView; }\nstatic SkViewRegister reg(MyFactory);\n\n<commit_msg>add 'c' toggle to test clipping<commit_after>\/*\n * Copyright 2012 Google Inc.\n *\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n *\/\n\n#include \"SampleCode.h\"\n#include \"SkView.h\"\n#include \"SkCanvas.h\"\n#include \"SkPath.h\"\n#include \"SkRegion.h\"\n#include \"SkShader.h\"\n#include \"SkUtils.h\"\n#include \"SkImage.h\"\n#include \"SkSurface.h\"\n\n#define FAT_PIXEL_COLOR SK_ColorBLACK\n#define PIXEL_CENTER_SIZE 3\n#define WIRE_FRAME_COLOR 0xFFFF0000 \/*0xFF00FFFF*\/\n#define WIRE_FRAME_SIZE 1.5f\n\nstatic void erase(SkSurface* surface) {\n surface->getCanvas()->clear(0);\n}\n\nstatic SkShader* createChecker() {\n\/\/ SkColor colors[] = { 0xFFFDFDFD, 0xFFF4F4F4 };\n SkColor colors[] = { 0xFFFFFFFF, 0xFFFFFFFF };\n SkBitmap bm;\n bm.setConfig(SkBitmap::kARGB_8888_Config, 2, 2);\n bm.allocPixels();\n bm.lockPixels();\n *bm.getAddr32(0, 0) = *bm.getAddr32(1, 1) = SkPreMultiplyColor(colors[0]);\n *bm.getAddr32(0, 1) = *bm.getAddr32(1, 0) = SkPreMultiplyColor(colors[1]);\n SkShader* s = SkShader::CreateBitmapShader(bm, SkShader::kRepeat_TileMode,\n SkShader::kRepeat_TileMode);\n\n SkMatrix m;\n m.setScale(12, 12);\n s->setLocalMatrix(m);\n return s;\n}\n\nclass FatBits {\npublic:\n FatBits() : fShader(createChecker()) {\n fAA = false;\n fStyle = kHair_Style;\n fGrid = true;\n fShowSkeleton = true;\n fUseGPU = false;\n fUseClip = false;\n \n fClipRect.set(2, 2, 11, 8 );\n }\n\n int getZoom() const { return fZ; }\n\n bool getAA() const { return fAA; }\n void setAA(bool aa) { fAA = aa; }\n\n bool getGrid() const { return fGrid; }\n void setGrid(bool g) { fGrid = g; }\n\n bool getShowSkeleton() const { return fShowSkeleton; }\n void setShowSkeleton(bool ss) { fShowSkeleton = ss; }\n\n bool getUseGPU() const { return fUseGPU; }\n void setUseGPU(bool ug) { fUseGPU = ug; }\n\n bool getUseClip() const { return fUseClip; }\n void setUseClip(bool uc) { fUseClip = uc; }\n\n enum Style {\n kHair_Style,\n kStroke_Style,\n };\n Style getStyle() const { return fStyle; }\n void setStyle(Style s) { fStyle = s; }\n\n void setWHZ(int width, int height, int zoom) {\n fW = width;\n fH = height;\n fZ = zoom;\n fBounds.set(0, 0, SkIntToScalar(width * zoom), SkIntToScalar(height * zoom));\n fMatrix.setScale(SkIntToScalar(zoom), SkIntToScalar(zoom));\n fInverse.setScale(SK_Scalar1 \/ zoom, SK_Scalar1 \/ zoom);\n fShader->setLocalMatrix(fMatrix);\n\n SkImage::Info info = {\n width, height, SkImage::kPMColor_ColorType, SkImage::kPremul_AlphaType\n };\n fMinSurface.reset(SkSurface::NewRaster(info, NULL));\n info.fWidth *= zoom;\n info.fHeight *= zoom;\n fMaxSurface.reset(SkSurface::NewRaster(info, NULL));\n }\n\n void drawBG(SkCanvas*);\n void drawFG(SkCanvas*);\n void drawLine(SkCanvas*, SkPoint pts[2]);\n void drawRect(SkCanvas* canvas, SkPoint pts[2]);\n\nprivate:\n bool fAA, fGrid, fShowSkeleton, fUseGPU, fUseClip;\n Style fStyle;\n int fW, fH, fZ;\n SkMatrix fMatrix, fInverse;\n SkRect fBounds, fClipRect;\n SkAutoTUnref<SkShader> fShader;\n SkAutoTUnref<SkSurface> fMinSurface;\n SkAutoTUnref<SkSurface> fMaxSurface;\n\n void setupPaint(SkPaint* paint) {\n bool aa = this->getAA();\n switch (fStyle) {\n case kHair_Style:\n paint->setStrokeWidth(0);\n break;\n case kStroke_Style:\n paint->setStrokeWidth(SK_Scalar1);\n\/\/ paint->setStrokeWidth(SK_Scalar1 + SK_Scalar1\/500);\n break;\n }\n paint->setAntiAlias(aa);\n }\n\n void setupSkeletonPaint(SkPaint* paint) {\n paint->setStyle(SkPaint::kStroke_Style);\n paint->setStrokeWidth(WIRE_FRAME_SIZE);\n paint->setColor(fShowSkeleton ? WIRE_FRAME_COLOR : 0);\n paint->setAntiAlias(true);\n }\n\n void drawLineSkeleton(SkCanvas* max, const SkPoint pts[]);\n void drawRectSkeleton(SkCanvas* max, const SkRect& r) {\n SkPaint paint;\n this->setupSkeletonPaint(&paint);\n SkPath path;\n\n if (fUseGPU && fAA) {\n SkRect rr = r;\n rr.inset(fZ\/2, fZ\/2);\n path.addRect(rr);\n path.moveTo(rr.fLeft, rr.fTop);\n path.lineTo(rr.fRight, rr.fBottom);\n rr = r;\n rr.inset(-fZ\/2, -fZ\/2);\n path.addRect(rr);\n } else {\n path.addRect(r);\n if (fUseGPU) {\n path.moveTo(r.fLeft, r.fTop);\n path.lineTo(r.fRight, r.fBottom);\n }\n }\n max->drawPath(path, paint);\n }\n\n void copyMinToMax() {\n erase(fMaxSurface);\n SkCanvas* canvas = fMaxSurface->getCanvas();\n canvas->save();\n canvas->concat(fMatrix);\n fMinSurface->draw(canvas, 0, 0, NULL);\n canvas->restore();\n\n SkPaint paint;\n paint.setXfermodeMode(SkXfermode::kClear_Mode);\n for (int iy = 1; iy < fH; ++iy) {\n SkScalar y = SkIntToScalar(iy * fZ);\n canvas->drawLine(0, y - SK_ScalarHalf, 999, y - SK_ScalarHalf, paint);\n }\n for (int ix = 1; ix < fW; ++ix) {\n SkScalar x = SkIntToScalar(ix * fZ);\n canvas->drawLine(x - SK_ScalarHalf, 0, x - SK_ScalarHalf, 999, paint);\n }\n }\n};\n\nvoid FatBits::drawBG(SkCanvas* canvas) {\n SkPaint paint;\n\n paint.setShader(fShader);\n canvas->drawRect(fBounds, paint);\n paint.setShader(NULL);\n}\n\nvoid FatBits::drawFG(SkCanvas* canvas) {\n SkPaint inner, outer;\n\n inner.setAntiAlias(true);\n inner.setColor(SK_ColorBLACK);\n inner.setStrokeWidth(PIXEL_CENTER_SIZE);\n\n outer.setAntiAlias(true);\n outer.setColor(SK_ColorWHITE);\n outer.setStrokeWidth(PIXEL_CENTER_SIZE + 2);\n\n SkScalar half = SkIntToScalar(fZ) \/ 2;\n for (int iy = 0; iy < fH; ++iy) {\n SkScalar y = SkIntToScalar(iy * fZ) + half;\n for (int ix = 0; ix < fW; ++ix) {\n SkScalar x = SkIntToScalar(ix * fZ) + half;\n\n canvas->drawPoint(x, y, outer);\n canvas->drawPoint(x, y, inner);\n }\n }\n\n if (fUseClip) {\n SkPaint p;\n p.setStyle(SkPaint::kStroke_Style);\n p.setColor(SK_ColorLTGRAY);\n SkRect r = {\n fClipRect.fLeft * fZ,\n fClipRect.fTop * fZ,\n fClipRect.fRight * fZ,\n fClipRect.fBottom * fZ\n };\n canvas->drawRect(r, p);\n }\n}\n\nvoid FatBits::drawLineSkeleton(SkCanvas* max, const SkPoint pts[]) {\n SkPaint paint;\n this->setupSkeletonPaint(&paint);\n\n SkPath path;\n path.moveTo(pts[0]);\n path.lineTo(pts[1]);\n\n switch (fStyle) {\n case kHair_Style:\n if (fUseGPU) {\n SkPaint p;\n p.setStyle(SkPaint::kStroke_Style);\n p.setStrokeWidth(SK_Scalar1 * fZ);\n SkPath dst;\n p.getFillPath(path, &dst);\n path.addPath(dst);\n }\n break;\n case kStroke_Style: {\n SkPaint p;\n p.setStyle(SkPaint::kStroke_Style);\n p.setStrokeWidth(SK_Scalar1 * fZ);\n SkPath dst;\n p.getFillPath(path, &dst);\n path = dst;\n\n if (fUseGPU) {\n path.moveTo(dst.getPoint(0));\n path.lineTo(dst.getPoint(2));\n }\n } break;\n }\n max->drawPath(path, paint);\n}\n\nvoid FatBits::drawLine(SkCanvas* canvas, SkPoint pts[]) {\n SkPaint paint;\n\n fInverse.mapPoints(pts, 2);\n\n if (fGrid) {\n SkScalar dd = 0;\/\/SK_Scalar1 \/ 50;\n pts[0].set(SkScalarRoundToScalar(pts[0].fX) + dd,\n SkScalarRoundToScalar(pts[0].fY) + dd);\n pts[1].set(SkScalarRoundToScalar(pts[1].fX) + dd,\n SkScalarRoundToScalar(pts[1].fY) + dd);\n }\n\n erase(fMinSurface);\n this->setupPaint(&paint);\n paint.setColor(FAT_PIXEL_COLOR);\n if (fUseClip) {\n fMinSurface->getCanvas()->save();\n SkRect r = fClipRect;\n r.inset(SK_Scalar1\/3, SK_Scalar1\/3);\n fMinSurface->getCanvas()->clipRect(r, SkRegion::kIntersect_Op, true);\n }\n fMinSurface->getCanvas()->drawLine(pts[0].fX, pts[0].fY, pts[1].fX, pts[1].fY, paint);\n if (fUseClip) {\n fMinSurface->getCanvas()->restore();\n }\n this->copyMinToMax();\n\n SkCanvas* max = fMaxSurface->getCanvas();\n\n fMatrix.mapPoints(pts, 2);\n this->drawLineSkeleton(max, pts);\n\n fMaxSurface->draw(canvas, 0, 0, NULL);\n}\n\nvoid FatBits::drawRect(SkCanvas* canvas, SkPoint pts[2]) {\n SkPaint paint;\n\n fInverse.mapPoints(pts, 2);\n\n if (fGrid) {\n pts[0].set(SkScalarRoundToScalar(pts[0].fX), SkScalarRoundToScalar(pts[0].fY));\n pts[1].set(SkScalarRoundToScalar(pts[1].fX), SkScalarRoundToScalar(pts[1].fY));\n }\n\n SkRect r;\n r.set(pts, 2);\n\n erase(fMinSurface);\n this->setupPaint(&paint);\n paint.setColor(FAT_PIXEL_COLOR);\n fMinSurface->getCanvas()->drawRect(r, paint);\n this->copyMinToMax();\n\n SkCanvas* max = fMaxSurface->getCanvas();\n\n fMatrix.mapPoints(pts, 2);\n r.set(pts, 2);\n this->drawRectSkeleton(max, r);\n\n fMaxSurface->draw(canvas, 0, 0, NULL);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nclass IndexClick : public SkView::Click {\n int fIndex;\npublic:\n IndexClick(SkView* v, int index) : SkView::Click(v), fIndex(index) {}\n\n static int GetIndex(SkView::Click* click) {\n return ((IndexClick*)click)->fIndex;\n }\n};\n\nclass DrawLineView : public SampleView {\n FatBits fFB;\n SkPoint fPts[2];\n bool fIsRect;\npublic:\n DrawLineView() {\n fFB.setWHZ(24, 16, 48);\n fPts[0].set(48, 48);\n fPts[1].set(48 * 5, 48 * 4);\n fIsRect = false;\n }\n\n void setStyle(FatBits::Style s) {\n fFB.setStyle(s);\n this->inval(NULL);\n }\n\nprotected:\n virtual bool onQuery(SkEvent* evt) SK_OVERRIDE {\n if (SampleCode::TitleQ(*evt)) {\n SampleCode::TitleR(evt, \"FatBits\");\n return true;\n }\n SkUnichar uni;\n if (SampleCode::CharQ(*evt, &uni)) {\n switch (uni) {\n case 'c':\n fFB.setUseClip(!fFB.getUseClip());\n this->inval(NULL);\n return true;\n case 'r':\n fIsRect = !fIsRect;\n this->inval(NULL);\n return true;\n case 'x':\n fFB.setGrid(!fFB.getGrid());\n this->inval(NULL);\n return true;\n case 's':\n if (FatBits::kStroke_Style == fFB.getStyle()) {\n this->setStyle(FatBits::kHair_Style);\n } else {\n this->setStyle(FatBits::kStroke_Style);\n }\n return true;\n case 'a':\n fFB.setAA(!fFB.getAA());\n this->inval(NULL);\n return true;\n case 'w':\n fFB.setShowSkeleton(!fFB.getShowSkeleton());\n this->inval(NULL);\n return true;\n case 'g':\n fFB.setUseGPU(!fFB.getUseGPU());\n this->inval(NULL);\n return true;\n }\n }\n return this->INHERITED::onQuery(evt);\n }\n\n virtual void onDrawContent(SkCanvas* canvas) {\n fFB.drawBG(canvas);\n if (fIsRect) {\n fFB.drawRect(canvas, fPts);\n } else {\n fFB.drawLine(canvas, fPts);\n }\n fFB.drawFG(canvas);\n\n {\n SkString str;\n str.printf(\"%s %s %s %s\",\n fFB.getAA() ? \"AA\" : \"BW\",\n FatBits::kHair_Style == fFB.getStyle() ? \"Hair\" : \"Stroke\",\n fFB.getUseGPU() ? \"GPU\" : \"CPU\",\n fFB.getUseClip() ? \"clip\" : \"noclip\");\n SkPaint paint;\n paint.setAntiAlias(true);\n paint.setTextSize(16);\n paint.setColor(SK_ColorBLUE);\n canvas->drawText(str.c_str(), str.size(), 10, 16, paint);\n }\n }\n\n virtual SkView::Click* onFindClickHandler(SkScalar x, SkScalar y) {\n SkPoint pt = { x, y };\n int index = -1;\n SkScalar tol = 12;\n if (fPts[0].equalsWithinTolerance(pt, tol)) {\n index = 0;\n } else if (fPts[1].equalsWithinTolerance(pt, tol)) {\n index = 1;\n }\n return new IndexClick(this, index);\n }\n\n virtual bool onClick(Click* click) {\n int index = IndexClick::GetIndex(click);\n if (index >= 0 && index <= 1) {\n fPts[index] = click->fCurr;\n } else {\n SkScalar dx = click->fCurr.fX - click->fPrev.fX;\n SkScalar dy = click->fCurr.fY - click->fPrev.fY;\n fPts[0].offset(dx, dy);\n fPts[1].offset(dx, dy);\n }\n this->inval(NULL);\n return true;\n }\n\nprivate:\n\n typedef SampleView INHERITED;\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstatic SkView* MyFactory() { return new DrawLineView; }\nstatic SkViewRegister reg(MyFactory);\n\n<|endoftext|>"} {"text":"<commit_before>#ifndef STAN_LANG_AST_DOUBLE_BLOCK_TYPE_HPP\n#define STAN_LANG_AST_DOUBLE_BLOCK_TYPE_HPP\n\n#include <stan\/lang\/ast\/node\/offset_multiplier.hpp>\n#include <stan\/lang\/ast\/node\/range.hpp>\n\nnamespace stan {\nnamespace lang {\n\n\/**\n * Double block var type.\n *\/\nstruct double_block_type {\n \/\/ TODO(VMatthijs): We should only allow to have either a range or a\n \/\/ offset_multiplier.\n\n \/**\n * Bounds constraints\n *\/\n range bounds_;\n\n \/**\n * Offset and multiplier\n *\/\n offset_multiplier ls_;\n\n \/**\n * Construct a block var type with default values.\n *\/\n double_block_type();\n\n \/**\n * Construct a block var type with specified values.\n *\n * @param bounds variable upper and\/or lower bounds\n * @param ls variable offset and multiplier\n *\/\n explicit double_block_type(const range &bounds, const offset_multiplier &ls);\n\n \/**\n * Construct a block var type with specified values.\n *\n * @param bounds variable upper and\/or lower bounds\n *\/\n explicit double_block_type(const range &bounds);\n\n \/**\n * Construct a block var type with specified values.\n *\n * @param ls variable offset and multiplier\n *\/\n explicit double_block_type(const offset_multiplier &ls);\n\n \/**\n * Get bounds constraints.\n *\/\n range bounds() const;\n\n \/**\n * Get offset and multiplier.\n *\/\n offset_multiplier ls() const;\n};\n\n} \/\/ namespace lang\n} \/\/ namespace stan\n#endif\n<commit_msg>Update double_block_type.hpp<commit_after>#ifndef STAN_LANG_AST_DOUBLE_BLOCK_TYPE_HPP\n#define STAN_LANG_AST_DOUBLE_BLOCK_TYPE_HPP\n\n#include <stan\/lang\/ast\/node\/offset_multiplier.hpp>\n#include <stan\/lang\/ast\/node\/range.hpp>\n\nnamespace stan {\nnamespace lang {\n\n\/**\n * Double block var type.\n *\/\nstruct double_block_type {\n\n \/**\n * Bounds constraints\n *\/\n range bounds_;\n\n \/**\n * Offset and multiplier\n *\/\n offset_multiplier ls_;\n\n \/**\n * Construct a block var type with default values.\n *\/\n double_block_type();\n\n \/**\n * Construct a block var type with specified values.\n *\n * @param bounds variable upper and\/or lower bounds\n * @param ls variable offset and multiplier\n *\/\n explicit double_block_type(const range &bounds, const offset_multiplier &ls);\n\n \/**\n * Construct a block var type with specified values.\n *\n * @param bounds variable upper and\/or lower bounds\n *\/\n explicit double_block_type(const range &bounds);\n\n \/**\n * Construct a block var type with specified values.\n *\n * @param ls variable offset and multiplier\n *\/\n explicit double_block_type(const offset_multiplier &ls);\n\n \/**\n * Get bounds constraints.\n *\/\n range bounds() const;\n\n \/**\n * Get offset and multiplier.\n *\/\n offset_multiplier ls() const;\n};\n\n} \/\/ namespace lang\n} \/\/ namespace stan\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/**\n * Copyright (c) 2014-present, Facebook, Inc.\n * All rights reserved.\n *\n * This source code is licensed in accordance with the terms specified in\n * the LICENSE file found in the root directory of this source tree.\n *\/\n\n\/\/ clang-format off\n\/\/ Keep it on top of all other includes to fix double include WinSock.h header file\n\/\/ which is windows specific boost build problem\n#include \"osquery\/remote\/transports\/tls.h\"\n\/\/ clang-format on\n\n#include <gtest\/gtest.h>\n\n#include <vector>\n\n#include <osquery\/config\/config.h>\n#include <osquery\/database.h>\n#include <osquery\/flags.h>\n#include <osquery\/sql.h>\n#include <osquery\/system.h>\n#include <osquery\/registry_factory.h>\n\n#include \"osquery\/remote\/requests.h\"\n#include \"osquery\/remote\/serializers\/json.h\"\n#include <osquery\/remote\/tests\/test_utils.h>\n#include \"osquery\/tests\/test_util.h\"\n\n#include <osquery\/remote\/enroll\/tls_enroll.h>\n\nnamespace osquery {\n\nDECLARE_string(tls_hostname);\nDECLARE_bool(disable_database);\n\nclass TLSEnrollTests : public testing::Test {\n protected:\n void SetUp() override;\n void TearDown() override;\n\n Status testReadRequests(JSON& response_tree);\n\n private:\n std::string test_read_uri_;\n};\n\nvoid TLSEnrollTests::SetUp() {\n Initializer::platformSetup();\n registryAndPluginInit();\n FLAGS_disable_database = true;\n DatabasePlugin::setAllowOpen(true);\n DatabasePlugin::initPlugin();\n\n \/\/ Start a server.\n TLSServerRunner::start();\n TLSServerRunner::setClientConfig();\n clearNodeKey();\n\n test_read_uri_ =\n \"https:\/\/\" + Flag::getValue(\"tls_hostname\") + \"\/test_read_requests\";\n}\n\nvoid TLSEnrollTests::TearDown() {\n \/\/ Stop the server.\n TLSServerRunner::unsetClientConfig();\n TLSServerRunner::stop();\n}\n\nStatus TLSEnrollTests::testReadRequests(JSON& response_tree) {\n Request<TLSTransport, JSONSerializer> request_(test_read_uri_);\n request_.setOption(\"hostname\", Flag::getValue(\"tls_hostname\"));\n auto status = request_.call(JSON());\n if (status.ok()) {\n status = request_.getResponse(response_tree);\n }\n return status;\n}\n\nTEST_F(TLSEnrollTests, test_tls_enroll) {\n auto node_key = getNodeKey(\"tls\");\n\n JSON response;\n std::string value;\n\n auto status = testReadRequests(response);\n EXPECT_TRUE(status.ok());\n EXPECT_EQ(response.doc().Size(), 1U);\n\n auto const& obj = response.doc()[0];\n EXPECT_TRUE(obj.IsObject());\n EXPECT_TRUE(obj.HasMember(\"command\"));\n EXPECT_TRUE(obj[\"command\"].IsString());\n value = obj[\"command\"].GetString();\n EXPECT_EQ(value, \"enroll\");\n\n EXPECT_TRUE(obj.HasMember(\"host_identifier\"));\n EXPECT_TRUE(obj[\"host_identifier\"].IsString());\n value = obj[\"host_identifier\"].GetString();\n EXPECT_EQ(value, getHostIdentifier());\n\n \/\/ Check that osquery_info exists in the host_details.\n ASSERT_EQ(kEnrollHostDetails.count(\"osquery_info\"), 1U);\n auto osquery_info = SQL::selectAllFrom(\"osquery_info\");\n ASSERT_EQ(osquery_info.size(), 1U);\n ASSERT_EQ(osquery_info[0].count(\"uuid\"), 1U);\n\n EXPECT_TRUE(obj.HasMember(\"host_details\"));\n EXPECT_TRUE(obj[\"host_details\"].HasMember(\"osquery_info\"));\n EXPECT_TRUE(obj[\"host_details\"][\"osquery_info\"].HasMember(\"uuid\"));\n\n EXPECT_TRUE(obj[\"host_details\"][\"osquery_info\"][\"uuid\"].IsString());\n value = obj[\"host_details\"][\"osquery_info\"][\"uuid\"].GetString();\n EXPECT_EQ(osquery_info[0][\"uuid\"], value);\n}\n}\n<commit_msg>Improve tls_enroll_tests (#5458)<commit_after>\/**\n * Copyright (c) 2014-present, Facebook, Inc.\n * All rights reserved.\n *\n * This source code is licensed in accordance with the terms specified in\n * the LICENSE file found in the root directory of this source tree.\n *\/\n\n\/\/ clang-format off\n\/\/ Keep it on top of all other includes to fix double include WinSock.h header file\n\/\/ which is windows specific boost build problem\n#include \"osquery\/remote\/transports\/tls.h\"\n\/\/ clang-format on\n\n#include <gtest\/gtest.h>\n\n#include <vector>\n\n#include <osquery\/config\/config.h>\n#include <osquery\/database.h>\n#include <osquery\/flags.h>\n#include <osquery\/sql.h>\n#include <osquery\/system.h>\n#include <osquery\/registry_factory.h>\n\n#include \"osquery\/remote\/requests.h\"\n#include \"osquery\/remote\/serializers\/json.h\"\n#include <osquery\/remote\/tests\/test_utils.h>\n#include \"osquery\/tests\/test_util.h\"\n\n#include <osquery\/remote\/enroll\/tls_enroll.h>\n\nnamespace osquery {\n\nDECLARE_string(tls_hostname);\nDECLARE_bool(disable_database);\n\nclass TLSEnrollTests : public testing::Test {\n protected:\n void SetUp() override;\n void TearDown() override;\n\n Status testReadRequests(JSON& response_tree);\n\n private:\n std::string test_read_uri_;\n};\n\nvoid TLSEnrollTests::SetUp() {\n Initializer::platformSetup();\n registryAndPluginInit();\n FLAGS_disable_database = true;\n DatabasePlugin::setAllowOpen(true);\n DatabasePlugin::initPlugin();\n\n \/\/ Start a server.\n TLSServerRunner::start();\n TLSServerRunner::setClientConfig();\n clearNodeKey();\n\n test_read_uri_ =\n \"https:\/\/\" + Flag::getValue(\"tls_hostname\") + \"\/test_read_requests\";\n}\n\nvoid TLSEnrollTests::TearDown() {\n \/\/ Stop the server.\n TLSServerRunner::unsetClientConfig();\n TLSServerRunner::stop();\n}\n\nStatus TLSEnrollTests::testReadRequests(JSON& response_tree) {\n Request<TLSTransport, JSONSerializer> request_(test_read_uri_);\n request_.setOption(\"hostname\", Flag::getValue(\"tls_hostname\"));\n auto status = request_.call(JSON());\n if (status.ok()) {\n status = request_.getResponse(response_tree);\n }\n return status;\n}\n\nTEST_F(TLSEnrollTests, test_tls_enroll) {\n auto node_key = getNodeKey(\"tls\");\n\n JSON response;\n std::string value;\n\n auto status = testReadRequests(response);\n ASSERT_TRUE(status.ok());\n ASSERT_TRUE(response.doc().IsArray());\n ASSERT_EQ(response.doc().Size(), 1U);\n\n auto const& obj = response.doc()[0];\n ASSERT_TRUE(obj.IsObject());\n\n ASSERT_TRUE(obj.HasMember(\"command\"));\n ASSERT_TRUE(obj[\"command\"].IsString());\n value = obj[\"command\"].GetString();\n EXPECT_EQ(value, \"enroll\");\n\n ASSERT_TRUE(obj.HasMember(\"host_identifier\"));\n ASSERT_TRUE(obj[\"host_identifier\"].IsString());\n value = obj[\"host_identifier\"].GetString();\n EXPECT_EQ(value, getHostIdentifier());\n\n ASSERT_EQ(kEnrollHostDetails.count(\"osquery_info\"), 1U);\n auto osquery_info = SQL::selectAllFrom(\"osquery_info\");\n ASSERT_EQ(osquery_info.size(), 1U);\n ASSERT_EQ(osquery_info[0].count(\"uuid\"), 1U);\n ASSERT_TRUE(obj.HasMember(\"host_details\"));\n ASSERT_TRUE(obj[\"host_details\"].HasMember(\"osquery_info\"));\n ASSERT_TRUE(obj[\"host_details\"][\"osquery_info\"].HasMember(\"uuid\"));\n ASSERT_TRUE(obj[\"host_details\"][\"osquery_info\"][\"uuid\"].IsString());\n value = obj[\"host_details\"][\"osquery_info\"][\"uuid\"].GetString();\n EXPECT_EQ(osquery_info[0][\"uuid\"], value);\n}\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"config.hpp\"\n\n#include \"cpptoml\/cpptoml.h\"\n#include \"file_exist.hpp\"\n#include \"file_name.hpp\"\n#include \"osal.hpp\"\n\nConfig::Config(int argc, char **argv)\n : target(fileName(getCurrentWorkingDir())),\n remoteRepository(\"https:\/\/github.com\/antonte\/coddle-repository.git\"),\n remoteVersion(\"master\"),\n cflags(\"-Wall -Wextra -march=native -gdwarf-3 -D_GLIBCXX_DEBUG -std=c++17\"),\n debug(false)\n{\n for (int i = 1; i < argc; ++i)\n if (argv[i] == std::string(\"debug\"))\n {\n debug = true;\n break;\n }\n\n loadConfig(\"\/etc\/coddle.toml\");\n loadConfig(\"~\/.coddle.toml\");\n loadConfig(\"coddle.toml\");\n}\n\nvoid Config::loadConfig(const std::string &configFileName)\n{\n if (isFileExist(configFileName))\n {\n auto &&toml = cpptoml::parse_file(configFileName);\n target = toml->get_as<std::string>(\"target\").value_or(target);\n remoteRepository = toml->get_as<std::string>(\"remoteRepository\").value_or(remoteRepository);\n remoteVersion = toml->get_as<std::string>(\"remoteVersion\").value_or(remoteVersion);\n localRepository = toml->get_as<std::string>(\"localRepository\").value_or(localRepository);\n cflags = toml->get_as<std::string>(\"cflags\").value_or(cflags);\n debug = toml->get_as<bool>(\"debug\").value_or(debug);\n multithreaded = toml->get_as<bool>(\"multithreaded\").value_or(false);\n }\n}\n<commit_msg>Point to win branch of repository on Windows machines<commit_after>#include \"config.hpp\"\n\n#include \"cpptoml\/cpptoml.h\"\n#include \"file_exist.hpp\"\n#include \"file_name.hpp\"\n#include \"osal.hpp\"\n\nConfig::Config(int argc, char **argv)\n : target(fileName(getCurrentWorkingDir())),\n remoteRepository(\"https:\/\/github.com\/antonte\/coddle-repository.git\"),\n#ifndef _WIN32\n remoteVersion(\"master\"),\n#else\n remoteVersion(\"win\"),\n#endif\n cflags(\"-Wall -Wextra -march=native -gdwarf-3 -D_GLIBCXX_DEBUG -std=c++17\"),\n debug(false)\n{\n for (int i = 1; i < argc; ++i)\n if (argv[i] == std::string(\"debug\"))\n {\n debug = true;\n break;\n }\n\n loadConfig(\"\/etc\/coddle.toml\");\n loadConfig(\"~\/.coddle.toml\");\n loadConfig(\"coddle.toml\");\n}\n\nvoid Config::loadConfig(const std::string &configFileName)\n{\n if (isFileExist(configFileName))\n {\n auto &&toml = cpptoml::parse_file(configFileName);\n target = toml->get_as<std::string>(\"target\").value_or(target);\n remoteRepository = toml->get_as<std::string>(\"remoteRepository\").value_or(remoteRepository);\n remoteVersion = toml->get_as<std::string>(\"remoteVersion\").value_or(remoteVersion);\n localRepository = toml->get_as<std::string>(\"localRepository\").value_or(localRepository);\n cflags = toml->get_as<std::string>(\"cflags\").value_or(cflags);\n debug = toml->get_as<bool>(\"debug\").value_or(debug);\n multithreaded = toml->get_as<bool>(\"multithreaded\").value_or(false);\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ File: tpm_seal.cc\n\/\/ Author: Tom Roeder <tmroeder@google.com>\n\/\/\n\/\/ Description: A test of the TrouSerS API\n\/\/\n\/\/ Copyright (c) 2013, Google Inc. All rights reserved.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include <gflags\/gflags.h>\n#include <glog\/logging.h>\n\n#include <stdio.h>\n#include <string.h>\n#include <stdlib.h>\n#include <sys\/stat.h>\n#include <sys\/types.h>\n\n#include <tss\/tss_error.h>\n#include <tss\/platform.h>\n#include <tss\/tss_defines.h>\n#include <tss\/tss_typedef.h>\n#include <tss\/tss_structs.h>\n#include <tss\/tspi.h>\n#include <trousers\/trousers.h>\n\n#include <list>\n\nusing std::list;\n\nint main(int argc, char **argv) {\n google::ParseCommandLineFlags(&argc, &argv, true);\n FLAGS_alsologtostderr = true;\n google::InitGoogleLogging(argv[0]);\n\n TSS_HCONTEXT tss_ctx;\n TSS_HTPM tpm;\n TSS_RESULT result;\n TSS_HKEY srk = 0;\n TSS_HPOLICY srk_policy = 0;\n TSS_UUID srk_uuid = {0x00000000, 0x0000, 0x0000, 0x00, 0x00, {0x00, 0x00, 0x00, 0x00, 0x00, 0x01}};\n BYTE secret[20];\n\n \/\/ Use the well-known secret of 20 zeroes.\n memset(secret, 0, 20);\n\n \/\/ Set up the TSS context and the SRK + policy (with the right secret).\n result = Tspi_Context_Create(&tss_ctx);\n CHECK_EQ(result, TSS_SUCCESS) << \"Could not create a TSS context.\";\n\n result = Tspi_Context_Connect(tss_ctx,\n NULL \/* Default TPM *\/);\n CHECK_EQ(result, TSS_SUCCESS) << \"Could not connect to the default TPM\";\n\n result = Tspi_Context_GetTpmObject(tss_ctx, &tpm);\n CHECK_EQ(result, TSS_SUCCESS) << \"Could not get a handle to the TPM\";\n\n result = Tspi_Context_LoadKeyByUUID(tss_ctx,\n TSS_PS_TYPE_SYSTEM,\n srk_uuid,\n &srk);\n CHECK_EQ(result, TSS_SUCCESS) << \"Could not load the SRK handle\";\n\n result = Tspi_GetPolicyObject(srk,\n TSS_POLICY_USAGE,\n &srk_policy);\n CHECK_EQ(result, TSS_SUCCESS) << \"Could not get the SRK policy handle\";\n\n result = Tspi_Policy_SetSecret(srk_policy,\n TSS_SECRET_MODE_SHA1,\n 20,\n secret);\n CHECK_EQ(result, TSS_SUCCESS) << \"Could not set the well-known secret\";\n\n \/\/ Create and fill the PCR information.\n TSS_HPCRS pcrs;\n result = Tspi_Context_CreateObject(tss_ctx,\n TSS_OBJECT_TYPE_PCRS,\n 0,\n &pcrs);\n CHECK_EQ(result, TSS_SUCCESS) << \"Could not create a PCRs object\";\n\n \/\/ This seal operation is meant to be used with DRTM, so the only PCRs that it\n \/\/ reads are 17 and 18. This is where you can set other PCRs to use.\n list<UINT32> pcrs_to_seal{17, 18};\n BYTE *pcr_value = NULL;\n UINT32 pcr_value_len = 0;\n for(UINT32 ui : pcrs_to_seal) {\n result = Tspi_TPM_PcrRead(tpm, ui, &pcr_value_len, &pcr_value);\n CHECK_EQ(result, TSS_SUCCESS) << \"Could not read the value of PCR \" << ui;\n\n result = Tspi_PcrComposite_SetPcrValue(pcrs, ui, pcr_value_len, pcr_value);\n CHECK_EQ(result, TSS_SUCCESS) << \"Could not set the PCR value\"\n << ui << \" for sealing\";\n }\n\n TSS_HENCDATA enc_data;\n result = Tspi_Context_CreateObject(tss_ctx,\n TSS_OBJECT_TYPE_ENCDATA,\n TSS_ENCDATA_SEAL,\n &enc_data);\n CHECK_EQ(result, TSS_SUCCESS) << \"Could not create the data for sealing\";\n\n BYTE data[16] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15};\n result = Tspi_Data_Seal(enc_data, srk, 16, data, pcrs);\n CHECK_EQ(result, TSS_SUCCESS) << \"Could not seal the test data\";\n\n \/\/ Extract the sealed data, then try to unseal it.\n BYTE *sealed_data;\n UINT32 sealed_data_len;\n result = Tspi_GetAttribData(enc_data,\n TSS_TSPATTRIB_ENCDATA_BLOB,\n TSS_TSPATTRIB_ENCDATABLOB_BLOB,\n &sealed_data_len,\n &sealed_data);\n CHECK_EQ(result, TSS_SUCCESS) << \"Could not get the sealed bits\";\n\n BYTE *unsealed_data;\n UINT32 unsealed_data_len;\n result = Tspi_Data_Unseal(enc_data, srk, &unsealed_data_len, &unsealed_data);\n CHECK_EQ(result, TSS_SUCCESS) << \"Could not unseal the data\";\n\n \/\/ Check that the data was unsealed correctly.\n CHECK_EQ(unsealed_data_len, 16U) << \"The unsealed data was the wrong length\";\n CHECK_EQ(memcmp(unsealed_data, data, 16), 0)\n << \"The unsealed data did not match the original data\";\n\n \/\/ Clean-up code.\n result = Tspi_Context_FreeMemory(tss_ctx, NULL);\n CHECK_EQ(result, TSS_SUCCESS) << \"Could not free the context\";\n\n result = Tspi_Context_Close(tss_ctx);\n CHECK_EQ(result, TSS_SUCCESS) << \"Could not clean up the context\";\n\n return 0;\n}\n<commit_msg>Load the AIK by blob. This method assumes for the moment that there is a file called aikblob in the current working directory and that this AIK blob is associated with a key in the TPM.<commit_after>\/\/ File: tpm_seal.cc\n\/\/ Author: Tom Roeder <tmroeder@google.com>\n\/\/\n\/\/ Description: A test of the TrouSerS API\n\/\/\n\/\/ Copyright (c) 2013, Google Inc. All rights reserved.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include <gflags\/gflags.h>\n#include <glog\/logging.h>\n\n#include <stdio.h>\n#include <string.h>\n#include <stdlib.h>\n#include <sys\/stat.h>\n#include <sys\/types.h>\n\n#include <tss\/tss_error.h>\n#include <tss\/platform.h>\n#include <tss\/tss_defines.h>\n#include <tss\/tss_typedef.h>\n#include <tss\/tss_structs.h>\n#include <tss\/tspi.h>\n#include <trousers\/trousers.h>\n\n#include <fstream>\n#include <list>\n#include <sstream>\n#include <string>\n\nusing std::ifstream;\nusing std::list;\nusing std::string;\nusing std::stringstream;\n\nint main(int argc, char **argv) {\n google::ParseCommandLineFlags(&argc, &argv, true);\n FLAGS_alsologtostderr = true;\n google::InitGoogleLogging(argv[0]);\n\n TSS_HCONTEXT tss_ctx;\n TSS_HTPM tpm;\n TSS_RESULT result;\n TSS_HKEY srk = 0;\n TSS_HPOLICY srk_policy = 0;\n TSS_UUID srk_uuid = {0x00000000, 0x0000, 0x0000, 0x00, 0x00, {0x00, 0x00, 0x00, 0x00, 0x00, 0x01}};\n BYTE secret[20];\n\n \/\/ Use the well-known secret of 20 zeroes.\n memset(secret, 0, 20);\n\n \/\/ Set up the TSS context and the SRK + policy (with the right secret).\n result = Tspi_Context_Create(&tss_ctx);\n CHECK_EQ(result, TSS_SUCCESS) << \"Could not create a TSS context.\";\n\n result = Tspi_Context_Connect(tss_ctx,\n NULL \/* Default TPM *\/);\n CHECK_EQ(result, TSS_SUCCESS) << \"Could not connect to the default TPM\";\n\n result = Tspi_Context_GetTpmObject(tss_ctx, &tpm);\n CHECK_EQ(result, TSS_SUCCESS) << \"Could not get a handle to the TPM\";\n\n result = Tspi_Context_LoadKeyByUUID(tss_ctx,\n TSS_PS_TYPE_SYSTEM,\n srk_uuid,\n &srk);\n CHECK_EQ(result, TSS_SUCCESS) << \"Could not load the SRK handle\";\n\n result = Tspi_GetPolicyObject(srk,\n TSS_POLICY_USAGE,\n &srk_policy);\n CHECK_EQ(result, TSS_SUCCESS) << \"Could not get the SRK policy handle\";\n\n result = Tspi_Policy_SetSecret(srk_policy,\n TSS_SECRET_MODE_SHA1,\n 20,\n secret);\n CHECK_EQ(result, TSS_SUCCESS) << \"Could not set the well-known secret\";\n\n \/\/ Create and fill the PCR information.\n TSS_HPCRS pcrs;\n result = Tspi_Context_CreateObject(tss_ctx,\n TSS_OBJECT_TYPE_PCRS,\n 0,\n &pcrs);\n CHECK_EQ(result, TSS_SUCCESS) << \"Could not create a PCRs object\";\n\n \/\/ This seal operation is meant to be used with DRTM, so the only PCRs that it\n \/\/ reads are 17 and 18. This is where you can set other PCRs to use.\n list<UINT32> pcrs_to_seal{17, 18};\n BYTE *pcr_value = NULL;\n UINT32 pcr_value_len = 0;\n for(UINT32 ui : pcrs_to_seal) {\n result = Tspi_TPM_PcrRead(tpm, ui, &pcr_value_len, &pcr_value);\n CHECK_EQ(result, TSS_SUCCESS) << \"Could not read the value of PCR \" << ui;\n\n result = Tspi_PcrComposite_SetPcrValue(pcrs, ui, pcr_value_len, pcr_value);\n CHECK_EQ(result, TSS_SUCCESS) << \"Could not set the PCR value\"\n << ui << \" for sealing\";\n }\n\n TSS_HENCDATA enc_data;\n result = Tspi_Context_CreateObject(tss_ctx,\n TSS_OBJECT_TYPE_ENCDATA,\n TSS_ENCDATA_SEAL,\n &enc_data);\n CHECK_EQ(result, TSS_SUCCESS) << \"Could not create the data for sealing\";\n\n BYTE data[16] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15};\n result = Tspi_Data_Seal(enc_data, srk, 16, data, pcrs);\n CHECK_EQ(result, TSS_SUCCESS) << \"Could not seal the test data\";\n\n \/\/ Extract the sealed data, then try to unseal it.\n BYTE *sealed_data;\n UINT32 sealed_data_len;\n result = Tspi_GetAttribData(enc_data,\n TSS_TSPATTRIB_ENCDATA_BLOB,\n TSS_TSPATTRIB_ENCDATABLOB_BLOB,\n &sealed_data_len,\n &sealed_data);\n CHECK_EQ(result, TSS_SUCCESS) << \"Could not get the sealed bits\";\n\n BYTE *unsealed_data;\n UINT32 unsealed_data_len;\n result = Tspi_Data_Unseal(enc_data, srk, &unsealed_data_len, &unsealed_data);\n CHECK_EQ(result, TSS_SUCCESS) << \"Could not unseal the data\";\n\n \/\/ Check that the data was unsealed correctly.\n CHECK_EQ(unsealed_data_len, 16U) << \"The unsealed data was the wrong length\";\n CHECK_EQ(memcmp(unsealed_data, data, 16), 0)\n << \"The unsealed data did not match the original data\";\n\n \/\/ Get the public key blob from the AIK.\n \/\/ Load the blob and try to load the AIK\n ifstream blob_stream(\"aikblob\", ifstream::in);\n stringstream blob_buf;\n blob_buf << blob_stream.rdbuf();\n string blob = blob_buf.str();\n UINT32 blob_len = (UINT32)blob.size();\n TSS_HKEY aik;\n result = Tspi_Context_LoadKeyByBlob(tss_ctx, srk, blob_len,\nreinterpret_cast<BYTE *>(const_cast<char\n*>(blob.data())), &aik);\n CHECK_EQ(result, TSS_SUCCESS) << \"Could not load the AIK\";\n\n \/\/ Clean-up code.\n result = Tspi_Context_FreeMemory(tss_ctx, NULL);\n CHECK_EQ(result, TSS_SUCCESS) << \"Could not free the context\";\n\n result = Tspi_Context_Close(tss_ctx);\n CHECK_EQ(result, TSS_SUCCESS) << \"Could not clean up the context\";\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"stdafx.h\"\n#include \"Setup.h\"\n\n#define ERRMSG_ERROR _T(\"DeviceHive\")\n#define ERRMSG_GETTEMPNAME _T(\"Failed to get temporary file name.\")\n#define ERRMSG_WRITETEMP _T(\"Failed to write to temporary file.\")\n#define ERRMSG_RUNPARAMS _T(\"Failed to define installation folder.\")\n#define MSG_NEWLINE _T(\"\\r\\n\")\n#define COMMAND_LINE _T(\"msiexec \/i %s\")\n\nvoid ShowMessage(LPCTSTR lpText, LPCTSTR lpCaption, DWORD error_code);\n\nint APIENTRY _tWinMain(_In_ HINSTANCE hInstance,\n _In_opt_ HINSTANCE hPrevInstance,\n _In_ LPTSTR lpCmdLine,\n _In_ int nCmdShow)\n{\n UNREFERENCED_PARAMETER(hPrevInstance);\n UNREFERENCED_PARAMETER(lpCmdLine);\n\n HRSRC msi = FindResource(hInstance, MAKEINTRESOURCE(IDR_MSI), _T(\"MSI\"));\n HGLOBAL global = LoadResource(hInstance, msi);\n LPVOID msiAddress = LockResource(global);\n DWORD msiSize = SizeofResource(hInstance, msi);\n\n TCHAR lpPathBuffer[MAX_PATH] = { 0 };\n GetTempPath(MAX_PATH, lpPathBuffer);\n\n TCHAR szDeviceHiveSetupMsi[MAX_PATH] = { 0 };\n if (GetTempFileName(lpPathBuffer, _T(\"NEW\"), 0, szDeviceHiveSetupMsi) == 0)\n {\n ShowMessage(ERRMSG_GETTEMPNAME, ERRMSG_ERROR, GetLastError());\n return 1;\n }\n\n HANDLE hTempFile = CreateFile((LPTSTR)szDeviceHiveSetupMsi, GENERIC_READ | GENERIC_WRITE, 0, NULL,\n CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);\n\n DWORD bytesWritten;\n TCHAR szTempName[MAX_PATH] = { 0 };\n\n WriteFile(hTempFile, msiAddress, msiSize, &bytesWritten, NULL);\n if (msiSize != bytesWritten)\n {\n CloseHandle(hTempFile);\n DeleteFile(szTempName);\n ShowMessage(ERRMSG_WRITETEMP, ERRMSG_ERROR, GetLastError());\n return 1;\n }\n\n CloseHandle(hTempFile);\n\n STARTUPINFO startInfo;\n memset(&startInfo, 0, sizeof(startInfo));\n startInfo.cb = sizeof(STARTUPINFO);\n PROCESS_INFORMATION procInfo;\n\n TCHAR cmdLine[MAX_PATH] = { 0 };\n swprintf_s(cmdLine, MAX_PATH, COMMAND_LINE, szDeviceHiveSetupMsi);\n\n if (CreateProcess(NULL, cmdLine, NULL, NULL, FALSE, 0, NULL, NULL, &startInfo, &procInfo) == FALSE)\n {\n DeleteFile(szTempName);\n ShowMessage(ERRMSG_RUNPARAMS, ERRMSG_ERROR, GetLastError());\n return 1;\n }\n\n return 0;\n}\n\nvoid ShowMessage(LPCTSTR lpText, LPCTSTR lpCaption, DWORD error_code)\n{\n TCHAR message[MAX_PATH];\n _stprintf_s(message, MAX_PATH, _T(\"Error code: %d\"), error_code);\n\n SIZE_T message_size = _tcslen(lpText) + _tcslen(MSG_NEWLINE) + _tcslen(message) + 1;\n TCHAR *lpMessage = new TCHAR[message_size];\n _tcscpy_s(lpMessage, message_size, lpText);\n _tcscat_s(lpMessage, message_size, MSG_NEWLINE);\n _tcscat_s(lpMessage, message_size, message);\n\n MessageBox(NULL, lpMessage, lpCaption, MB_OK | MB_ICONERROR);\n\n delete[] lpMessage;\n}<commit_msg>Pass command args to setup.exe<commit_after>#include \"stdafx.h\"\n#include \"Setup.h\"\n\n#define ERRMSG_ERROR _T(\"DeviceHive\")\n#define ERRMSG_GETTEMPNAME _T(\"Failed to get temporary file name.\")\n#define ERRMSG_WRITETEMP _T(\"Failed to write to temporary file.\")\n#define ERRMSG_RUNPARAMS _T(\"Failed to define installation folder.\")\n#define MSG_NEWLINE _T(\"\\r\\n\")\n#define COMMAND_LINE _T(\"msiexec \/i %s %s\")\n\nvoid ShowMessage(LPCTSTR lpText, LPCTSTR lpCaption, DWORD error_code);\n\nint APIENTRY _tWinMain(_In_ HINSTANCE hInstance,\n _In_opt_ HINSTANCE hPrevInstance,\n _In_ LPTSTR lpCmdLine,\n _In_ int nCmdShow)\n{\n UNREFERENCED_PARAMETER(hPrevInstance);\n UNREFERENCED_PARAMETER(lpCmdLine);\n\n HRSRC msi = FindResource(hInstance, MAKEINTRESOURCE(IDR_MSI), _T(\"MSI\"));\n HGLOBAL global = LoadResource(hInstance, msi);\n LPVOID msiAddress = LockResource(global);\n DWORD msiSize = SizeofResource(hInstance, msi);\n\n TCHAR lpPathBuffer[MAX_PATH] = { 0 };\n GetTempPath(MAX_PATH, lpPathBuffer);\n\n TCHAR szDeviceHiveSetupMsi[MAX_PATH] = { 0 };\n if (GetTempFileName(lpPathBuffer, _T(\"NEW\"), 0, szDeviceHiveSetupMsi) == 0)\n {\n ShowMessage(ERRMSG_GETTEMPNAME, ERRMSG_ERROR, GetLastError());\n return 1;\n }\n\n HANDLE hTempFile = CreateFile((LPTSTR)szDeviceHiveSetupMsi, GENERIC_READ | GENERIC_WRITE, 0, NULL,\n CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);\n\n DWORD bytesWritten;\n TCHAR szTempName[MAX_PATH] = { 0 };\n\n WriteFile(hTempFile, msiAddress, msiSize, &bytesWritten, NULL);\n if (msiSize != bytesWritten)\n {\n CloseHandle(hTempFile);\n DeleteFile(szTempName);\n ShowMessage(ERRMSG_WRITETEMP, ERRMSG_ERROR, GetLastError());\n return 1;\n }\n\n CloseHandle(hTempFile);\n\n STARTUPINFO startInfo;\n memset(&startInfo, 0, sizeof(startInfo));\n startInfo.cb = sizeof(STARTUPINFO);\n PROCESS_INFORMATION procInfo;\n\n TCHAR cmdLine[MAX_PATH] = { 0 };\n swprintf_s(cmdLine, MAX_PATH, COMMAND_LINE, szDeviceHiveSetupMsi, lpCmdLine);\n\n if (CreateProcess(NULL, cmdLine, NULL, NULL, FALSE, 0, NULL, NULL, &startInfo, &procInfo) == FALSE)\n {\n DeleteFile(szTempName);\n ShowMessage(ERRMSG_RUNPARAMS, ERRMSG_ERROR, GetLastError());\n return 1;\n }\n\n return 0;\n}\n\nvoid ShowMessage(LPCTSTR lpText, LPCTSTR lpCaption, DWORD error_code)\n{\n TCHAR message[MAX_PATH];\n _stprintf_s(message, MAX_PATH, _T(\"Error code: %d\"), error_code);\n\n SIZE_T message_size = _tcslen(lpText) + _tcslen(MSG_NEWLINE) + _tcslen(message) + 1;\n TCHAR *lpMessage = new TCHAR[message_size];\n _tcscpy_s(lpMessage, message_size, lpText);\n _tcscat_s(lpMessage, message_size, MSG_NEWLINE);\n _tcscat_s(lpMessage, message_size, message);\n\n MessageBox(NULL, lpMessage, lpCaption, MB_OK | MB_ICONERROR);\n\n delete[] lpMessage;\n}<|endoftext|>"} {"text":"<commit_before>\/******************************************************************************\n * SOFA, Simulation Open-Framework Architecture, version 1.0 beta 3 *\n * (c) 2006-2008 MGH, INRIA, USTL, UJF, CNRS *\n * *\n * This program is free software; you can redistribute it and\/or modify it *\n * under the terms of the GNU General Public License as published by the Free *\n * Software Foundation; either version 2 of the License, or (at your option) *\n * any later version. *\n * *\n * This program is distributed in the hope that it will be useful, but WITHOUT *\n * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or *\n * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for *\n * more details. *\n * *\n * You should have received a copy of the GNU General Public License along *\n * with this program; if not, write to the Free Software Foundation, Inc., 51 *\n * Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *\n *******************************************************************************\n * SOFA :: Applications *\n * *\n * Authors: M. Adam, J. Allard, B. Andre, P-J. Bensoussan, S. Cotin, C. Duriez,*\n * H. Delingette, F. Falipou, F. Faure, S. Fonteneau, L. Heigeas, C. Mendoza, *\n * M. Nesme, P. Neumann, J-P. de la Plata Alcade, F. Poyer and F. Roy *\n * *\n * Contact information: contact@sofa-framework.org *\n ******************************************************************************\/\n#include \"SofaPluginManager.h\"\n#include \"FileManagement.h\"\n\n#ifdef SOFA_QT4\n\/\/#include <Q3Header>\n\/\/#include <Q3PopupMenu>\n#include <QMessageBox>\n#include <QLibrary>\n#include <QSettings>\n#else\n\/\/#include <qheader.h>\n\/\/#include <qpopupmenu.h>\n#include <qmessagebox.h>\n#include <qlibrary.h>\n#include <qsettings.h>\n#endif\n\n#include <iostream>\n\n\n#ifndef SOFA_QT4\ntypedef QListViewItem Q3ListViewItem;\n#endif\n\nnamespace sofa\n{\nnamespace gui\n{\nnamespace qt\n{\n\nSofaPluginManager::SofaPluginManager()\n{\n \/\/ SIGNAL \/ SLOTS CONNECTIONS\n this->connect(buttonAdd, SIGNAL(clicked() ), this, SLOT( addLibrary() ));\n this->connect(buttonRemove, SIGNAL(clicked() ), this, SLOT( removeLibrary() ));\n this->connect(listPlugins, SIGNAL(selectionChanged(Q3ListViewItem*) ), this, SLOT(updateComponentList(Q3ListViewItem*) ));\n this->connect(listPlugins, SIGNAL(selectionChanged(Q3ListViewItem*) ), this, SLOT(updateDescription(Q3ListViewItem*) ));\n\n \/\/read the plugin list in the settings\n QSettings settings(\"SOFA-FRAMEWORK\", \"SOFA\");\n int size = settings.beginReadArray(\"plugins\");\n listPlugins->clear();\n typedef void (*componentLoader)();\n typedef char* (*componentStr)();\n\n for (int i=0 ; i<size; ++i)\n {\n settings.setArrayIndex(i);\n QString sfile = settings.value(\"location\").toString();\n\n \/\/load the plugin libs\n QLibrary lib(sfile);\n componentLoader componentLoaderFunc = (componentLoader) lib.resolve(\"initExternalModule\");\n componentStr componentNameFunc = (componentStr) lib.resolve(\"getModuleName\");\n \/\/componentStr componentDescFunc = (componentStr) lib.resolve(\"getModuleDescription\");\n \/\/fill the list view\n if (componentLoaderFunc && componentNameFunc\/* && componentDescFunc*\/)\n {\n componentLoaderFunc();\n QString sname(componentNameFunc());\n \/\/QString sdesc(componentDescFunc());\n Q3ListViewItem * item = new Q3ListViewItem(listPlugins, sname, sfile\/*, sdesc*\/);\n item->setSelectable(true);\n }\n }\n settings.endArray();\n}\n\n\n\nvoid SofaPluginManager::addLibrary()\n{\n \/\/get the lib to load\n QString sfile = getOpenFileName ( this, NULL, \"dynamic library (*.dll *.so *.dylib)\", \"load library dialog\", \"Choose the component library to load\" );\n\n \/\/try to load the lib\n QLibrary lib(sfile);\n if (!lib.load())\n std::cout<<lib.errorString().latin1()<<std::endl;\n\n \/\/get the functions\n typedef void (*componentLoader)();\n typedef char* (*componentStr)();\n componentLoader componentLoaderFunc = (componentLoader) lib.resolve(\"initExternalModule\");\n componentStr componentNameFunc = (componentStr) lib.resolve(\"getModuleName\");\n \/\/componentStr componentDescFunc = (componentStr) lib.resolve(\"getModuleDescription\");\n\n if (componentLoaderFunc && componentNameFunc\/* && componentDescFunc*\/)\n {\n \/\/fill the list view\n componentLoaderFunc();\n QString sname(componentNameFunc());\n \/\/QString sdesc(componentDescFunc());\n Q3ListViewItem * item = new Q3ListViewItem(listPlugins, sname, sfile\/*, sdesc*\/);\n item->setSelectable(true);\n\n \/\/add to the settings (to record it)\n QSettings settings(\"SOFA-FRAMEWORK\", \"SOFA\");\n int size = settings.beginReadArray(\"plugins\");\n settings.endArray();\n settings.beginWriteArray(\"plugins\");\n settings.setArrayIndex(size);\n settings.setValue(\"location\", sfile);\n settings.endArray();\n }\n else\n {\n QMessageBox * mbox = new QMessageBox(this,\"library loading error\");\n mbox->setText(\"Unable to load this library\");\n mbox->show();\n }\n}\n\n\n\nvoid SofaPluginManager::removeLibrary()\n{\n \/\/get the selected item\n Q3ListViewItem * curItem = listPlugins->selectedItem();\n QString location = curItem->text(1); \/\/get the location value\n \/\/remove it from the list view\n listPlugins->removeItem(curItem);\n\n \/\/remove it from the settings\n QSettings settings(\"SOFA-FRAMEWORK\", \"SOFA\");\n int size = settings.beginReadArray(\"plugins\");\n\n for (int i=0 ; i<size; ++i)\n {\n settings.setArrayIndex(i);\n QString sfile = settings.value(\"location\").toString();\n if (sfile == location)\n {\n settings.endArray();\n settings.beginWriteArray(\"plugins\");\n settings.setArrayIndex(i);\n settings.remove(\"location\");\n }\n }\n\n settings.endArray();\n}\n\n\n\nvoid SofaPluginManager::updateComponentList(Q3ListViewItem* curItem)\n{\n \/\/update the component list when an item is selected\n listComponents->clear();\n QString location = curItem->text(1); \/\/get the location value\n QLibrary lib(location);\n typedef char* (*componentStr)();\n componentStr componentListFunc = (componentStr) lib.resolve(\"getModuleComponentList\");\n if(componentListFunc)\n {\n QString cpts( componentListFunc() );\n cpts.replace(\", \",\"\\n\");\n cpts.replace(\",\",\"\\n\");\n listComponents->setText(cpts);\n }\n}\n\nvoid SofaPluginManager::updateDescription(Q3ListViewItem* curItem)\n{\n \/\/update the component list when an item is selected\n description->clear();\n QString location = curItem->text(1); \/\/get the location value\n QLibrary lib(location);\n typedef char* (*componentStr)();\n componentStr componentDescFunc = (componentStr) lib.resolve(\"getModuleDescription\");\n if(componentDescFunc)\n {\n description->setText(QString(componentDescFunc()));\n }\n}\n\n}\n}\n}\n\n<commit_msg>r3789\/sofa-dev : FIX : compilation with QT3<commit_after>\/******************************************************************************\n * SOFA, Simulation Open-Framework Architecture, version 1.0 beta 3 *\n * (c) 2006-2008 MGH, INRIA, USTL, UJF, CNRS *\n * *\n * This program is free software; you can redistribute it and\/or modify it *\n * under the terms of the GNU General Public License as published by the Free *\n * Software Foundation; either version 2 of the License, or (at your option) *\n * any later version. *\n * *\n * This program is distributed in the hope that it will be useful, but WITHOUT *\n * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or *\n * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for *\n * more details. *\n * *\n * You should have received a copy of the GNU General Public License along *\n * with this program; if not, write to the Free Software Foundation, Inc., 51 *\n * Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *\n *******************************************************************************\n * SOFA :: Applications *\n * *\n * Authors: M. Adam, J. Allard, B. Andre, P-J. Bensoussan, S. Cotin, C. Duriez,*\n * H. Delingette, F. Falipou, F. Faure, S. Fonteneau, L. Heigeas, C. Mendoza, *\n * M. Nesme, P. Neumann, J-P. de la Plata Alcade, F. Poyer and F. Roy *\n * *\n * Contact information: contact@sofa-framework.org *\n ******************************************************************************\/\n#include \"SofaPluginManager.h\"\n#include \"FileManagement.h\"\n\n#ifdef SOFA_QT4\n\/\/#include <Q3Header>\n\/\/#include <Q3PopupMenu>\n#include <QMessageBox>\n#include <QLibrary>\n#include <QSettings>\n#else\n\/\/#include <qheader.h>\n\/\/#include <qpopupmenu.h>\n#include <qmessagebox.h>\n#include <qlibrary.h>\n#include <qsettings.h>\n#endif\n\n#include <iostream>\n\n\n#ifndef SOFA_QT4\ntypedef QListViewItem Q3ListViewItem;\n#endif\n\nnamespace sofa\n{\nnamespace gui\n{\nnamespace qt\n{\n\nSofaPluginManager::SofaPluginManager()\n{\n#ifdef SOFA_QT4\n \/\/ SIGNAL \/ SLOTS CONNECTIONS\n this->connect(buttonAdd, SIGNAL(clicked() ), this, SLOT( addLibrary() ));\n this->connect(buttonRemove, SIGNAL(clicked() ), this, SLOT( removeLibrary() ));\n this->connect(listPlugins, SIGNAL(selectionChanged(Q3ListViewItem*) ), this, SLOT(updateComponentList(Q3ListViewItem*) ));\n this->connect(listPlugins, SIGNAL(selectionChanged(Q3ListViewItem*) ), this, SLOT(updateDescription(Q3ListViewItem*) ));\n\n \/\/read the plugin list in the settings\n QSettings settings(\"SOFA-FRAMEWORK\", \"SOFA\");\n int size = settings.beginReadArray(\"plugins\");\n listPlugins->clear();\n typedef void (*componentLoader)();\n typedef char* (*componentStr)();\n\n for (int i=0 ; i<size; ++i)\n {\n settings.setArrayIndex(i);\n QString sfile = settings.value(\"location\").toString();\n\n \/\/load the plugin libs\n QLibrary lib(sfile);\n componentLoader componentLoaderFunc = (componentLoader) lib.resolve(\"initExternalModule\");\n componentStr componentNameFunc = (componentStr) lib.resolve(\"getModuleName\");\n \/\/componentStr componentDescFunc = (componentStr) lib.resolve(\"getModuleDescription\");\n \/\/fill the list view\n if (componentLoaderFunc && componentNameFunc\/* && componentDescFunc*\/)\n {\n componentLoaderFunc();\n QString sname(componentNameFunc());\n \/\/QString sdesc(componentDescFunc());\n Q3ListViewItem * item = new Q3ListViewItem(listPlugins, sname, sfile\/*, sdesc*\/);\n item->setSelectable(true);\n }\n }\n settings.endArray();\n#endif\n}\n\n\n\nvoid SofaPluginManager::addLibrary()\n{\n#ifdef SOFA_QT4\n \/\/get the lib to load\n QString sfile = getOpenFileName ( this, NULL, \"dynamic library (*.dll *.so *.dylib)\", \"load library dialog\", \"Choose the component library to load\" );\n\n \/\/try to load the lib\n QLibrary lib(sfile);\n if (!lib.load())\n std::cout<<lib.errorString().latin1()<<std::endl;\n\n \/\/get the functions\n typedef void (*componentLoader)();\n typedef char* (*componentStr)();\n componentLoader componentLoaderFunc = (componentLoader) lib.resolve(\"initExternalModule\");\n componentStr componentNameFunc = (componentStr) lib.resolve(\"getModuleName\");\n \/\/componentStr componentDescFunc = (componentStr) lib.resolve(\"getModuleDescription\");\n\n if (componentLoaderFunc && componentNameFunc\/* && componentDescFunc*\/)\n {\n \/\/fill the list view\n componentLoaderFunc();\n QString sname(componentNameFunc());\n \/\/QString sdesc(componentDescFunc());\n Q3ListViewItem * item = new Q3ListViewItem(listPlugins, sname, sfile\/*, sdesc*\/);\n item->setSelectable(true);\n\n \/\/add to the settings (to record it)\n QSettings settings(\"SOFA-FRAMEWORK\", \"SOFA\");\n int size = settings.beginReadArray(\"plugins\");\n settings.endArray();\n settings.beginWriteArray(\"plugins\");\n settings.setArrayIndex(size);\n settings.setValue(\"location\", sfile);\n settings.endArray();\n }\n else\n {\n QMessageBox * mbox = new QMessageBox(this,\"library loading error\");\n mbox->setText(\"Unable to load this library\");\n mbox->show();\n }\n#endif\n}\n\n\n\nvoid SofaPluginManager::removeLibrary()\n{\n#ifdef SOFA_QT4\n \/\/get the selected item\n Q3ListViewItem * curItem = listPlugins->selectedItem();\n QString location = curItem->text(1); \/\/get the location value\n \/\/remove it from the list view\n listPlugins->removeItem(curItem);\n\n \/\/remove it from the settings\n QSettings settings(\"SOFA-FRAMEWORK\", \"SOFA\");\n int size = settings.beginReadArray(\"plugins\");\n\n for (int i=0 ; i<size; ++i)\n {\n settings.setArrayIndex(i);\n QString sfile = settings.value(\"location\").toString();\n if (sfile == location)\n {\n settings.endArray();\n settings.beginWriteArray(\"plugins\");\n settings.setArrayIndex(i);\n settings.remove(\"location\");\n }\n }\n\n settings.endArray();\n#endif\n}\n\n\n\nvoid SofaPluginManager::updateComponentList(Q3ListViewItem* curItem)\n{\n#ifdef SOFA_QT4\n \/\/update the component list when an item is selected\n listComponents->clear();\n QString location = curItem->text(1); \/\/get the location value\n QLibrary lib(location);\n typedef char* (*componentStr)();\n componentStr componentListFunc = (componentStr) lib.resolve(\"getModuleComponentList\");\n if(componentListFunc)\n {\n QString cpts( componentListFunc() );\n cpts.replace(\", \",\"\\n\");\n cpts.replace(\",\",\"\\n\");\n listComponents->setText(cpts);\n }\n#endif\n}\n\nvoid SofaPluginManager::updateDescription(Q3ListViewItem* curItem)\n{\n#ifdef SOFA_QT4\n \/\/update the component list when an item is selected\n description->clear();\n QString location = curItem->text(1); \/\/get the location value\n QLibrary lib(location);\n typedef char* (*componentStr)();\n componentStr componentDescFunc = (componentStr) lib.resolve(\"getModuleDescription\");\n if(componentDescFunc)\n {\n description->setText(QString(componentDescFunc()));\n }\n}\n#endif\n}\n}\n}\n\n<|endoftext|>"} {"text":"<commit_before>\n\/*\n * Copyright 2011 Google Inc.\n *\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n *\/\n#include \"SampleCode.h\"\n#include \"SkView.h\"\n#include \"SkBlurMaskFilter.h\"\n#include \"SkCanvas.h\"\n#include \"SkGradientShader.h\"\n#include \"SkGraphics.h\"\n#include \"SkImageDecoder.h\"\n#include \"SkPath.h\"\n#include \"SkRandom.h\"\n#include \"SkRegion.h\"\n#include \"SkShader.h\"\n#include \"SkUtils.h\"\n#include \"SkXfermode.h\"\n#include \"SkColorPriv.h\"\n#include \"SkColorFilter.h\"\n#include \"SkTime.h\"\n#include \"SkTypeface.h\"\n#include \"SkTextBox.h\"\n#include \"SkOSFile.h\"\n#include \"SkStream.h\"\n#include \"SkKey.h\"\n\n#ifdef SK_BUILD_FOR_WIN\nextern SkTypeface* SkCreateTypefaceFromLOGFONT(const LOGFONT&);\n#endif\n\nstatic const char gText[] =\n\t\"When in the Course of human events it becomes necessary for one people \"\n\t\"to dissolve the political bands which have connected them with another \"\n\t\"and to assume among the powers of the earth, the separate and equal \"\n\t\"station to which the Laws of Nature and of Nature's God entitle them, \"\n\t\"a decent respect to the opinions of mankind requires that they should \"\n\t\"declare the causes which impel them to the separation.\";\n\nclass TextBoxView : public SampleView {\npublic:\n\tTextBoxView() {\n#ifdef SK_BUILD_FOR_WIN\n\t\tLOGFONT lf;\n\t\tsk_bzero(&lf, sizeof(lf));\n\t\tlf.lfHeight = 9;\n\t\tSkTypeface* tf0 = SkCreateTypefaceFromLOGFONT(lf);\n\t\tlf.lfHeight = 12;\n\t\tSkTypeface* tf1 = SkCreateTypefaceFromLOGFONT(lf);\n\t\t\/\/ we assert that different sizes should not affect which face we get\n\t\tSkASSERT(tf0 == tf1);\n\t\ttf0->unref();\n\t\ttf1->unref();\n#endif\n\t}\n\nprotected:\n \/\/ overrides from SkEventSink\n virtual bool onQuery(SkEvent* evt) {\n if (SampleCode::TitleQ(*evt)) {\n SkString str(\"TextBox\");\n SampleCode::TitleR(evt, str.c_str());\n return true;\n }\n return this->INHERITED::onQuery(evt);\n }\n\n virtual void onDrawContent(SkCanvas* canvas) {\n\t\tSkScalar margin = 20;\n SkTextBox tbox;\n\t\ttbox.setMode(SkTextBox::kLineBreak_Mode);\n\t\ttbox.setBox(margin, margin,\n\t\t\t\t\tthis->width() - margin, this->height() - margin);\n\t\ttbox.setSpacing(SkIntToScalar(3)\/3, 0);\n\n\t\tSkPaint paint;\n\t\tpaint.setAntiAlias(true);\n paint.setLCDRenderText(true);\n\t\ttbox.setText(gText, strlen(gText), paint);\n\n\t\tfor (int i = 9; i < 24; i += 2) {\n\t\t\tpaint.setTextSize(SkIntToScalar(i));\n\t\t\ttbox.draw(canvas);\n\t\t\tcanvas->translate(0, tbox.getTextHeight() + paint.getFontSpacing());\n\t\t}\n }\n\nprivate:\n typedef SampleView INHERITED;\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstatic SkView* MyFactory() { return new TextBoxView; }\nstatic SkViewRegister reg(MyFactory);\n\n<commit_msg>splitscreen for black and white versions<commit_after>\n\/*\n * Copyright 2011 Google Inc.\n *\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n *\/\n#include \"SampleCode.h\"\n#include \"SkView.h\"\n#include \"SkBlurMaskFilter.h\"\n#include \"SkCanvas.h\"\n#include \"SkColorShader.h\"\n#include \"SkGradientShader.h\"\n#include \"SkGraphics.h\"\n#include \"SkImageDecoder.h\"\n#include \"SkPath.h\"\n#include \"SkRandom.h\"\n#include \"SkRegion.h\"\n#include \"SkShader.h\"\n#include \"SkUtils.h\"\n#include \"SkXfermode.h\"\n#include \"SkColorPriv.h\"\n#include \"SkColorFilter.h\"\n#include \"SkTime.h\"\n#include \"SkTypeface.h\"\n#include \"SkTextBox.h\"\n#include \"SkOSFile.h\"\n#include \"SkStream.h\"\n#include \"SkKey.h\"\n\nextern void skia_set_text_gamma(float blackGamma, float whiteGamma);\n\n#ifdef SK_BUILD_FOR_WIN\nextern SkTypeface* SkCreateTypefaceFromLOGFONT(const LOGFONT&);\n#endif\n\nstatic const char gText[] =\n\t\"When in the Course of human events it becomes necessary for one people \"\n\t\"to dissolve the political bands which have connected them with another \"\n\t\"and to assume among the powers of the earth, the separate and equal \"\n\t\"station to which the Laws of Nature and of Nature's God entitle them, \"\n\t\"a decent respect to the opinions of mankind requires that they should \"\n\t\"declare the causes which impel them to the separation.\";\n\nclass TextBoxView : public SampleView {\npublic:\n\tTextBoxView() {\n#ifdef SK_BUILD_FOR_WIN\n\t\tLOGFONT lf;\n\t\tsk_bzero(&lf, sizeof(lf));\n\t\tlf.lfHeight = 9;\n\t\tSkTypeface* tf0 = SkCreateTypefaceFromLOGFONT(lf);\n\t\tlf.lfHeight = 12;\n\t\tSkTypeface* tf1 = SkCreateTypefaceFromLOGFONT(lf);\n\t\t\/\/ we assert that different sizes should not affect which face we get\n\t\tSkASSERT(tf0 == tf1);\n\t\ttf0->unref();\n\t\ttf1->unref();\n#endif\n }\n\nprotected:\n \/\/ overrides from SkEventSink\n virtual bool onQuery(SkEvent* evt) {\n if (SampleCode::TitleQ(*evt)) {\n SkString str(\"TextBox\");\n SampleCode::TitleR(evt, str.c_str());\n return true;\n }\n return this->INHERITED::onQuery(evt);\n }\n\n void drawTest(SkCanvas* canvas, SkScalar w, SkScalar h, SkColor fg, SkColor bg) {\n SkAutoCanvasRestore acr(canvas, true);\n\n canvas->clipRect(SkRect::MakeWH(w, h));\n canvas->drawColor(bg);\n\t\tSkScalar margin = 20;\n SkTextBox tbox;\n\t\ttbox.setMode(SkTextBox::kLineBreak_Mode);\n\t\ttbox.setBox(margin, margin,\n\t\t\t\t\tw - margin, h - margin);\n\t\ttbox.setSpacing(SkIntToScalar(3)\/3, 0);\n\n\t\tSkPaint paint;\n\t\tpaint.setAntiAlias(true);\n paint.setLCDRenderText(true);\n paint.setColor(fg);\n\t\ttbox.setText(gText, strlen(gText), paint);\n\n\t\tfor (int i = 9; i < 24; i += 2) {\n\t\t\tpaint.setTextSize(SkIntToScalar(i));\n\t\t\ttbox.draw(canvas);\n\t\t\tcanvas->translate(0, tbox.getTextHeight() + paint.getFontSpacing());\n\t\t}\n }\n\n virtual void onDrawContent(SkCanvas* canvas) {\n SkScalar width = this->width() \/ 3;\n drawTest(canvas, width, this->height(), SK_ColorBLACK, SK_ColorWHITE);\n canvas->translate(width, 0);\n drawTest(canvas, width, this->height(), SK_ColorWHITE, SK_ColorBLACK);\n canvas->translate(width, 0);\n drawTest(canvas, width, this->height()\/2, SK_ColorGRAY, SK_ColorWHITE);\n canvas->translate(0, this->height()\/2);\n drawTest(canvas, width, this->height()\/2, SK_ColorGRAY, SK_ColorBLACK);\n }\n\nprivate:\n typedef SampleView INHERITED;\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstatic SkView* MyFactory() { return new TextBoxView; }\nstatic SkViewRegister reg(MyFactory);\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n * #%L\n * %%\n * Copyright (C) 2011 - 2013 BMW Car IT GmbH\n * %%\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * \n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * #L%\n *\/\n#include \"joynr\/PrivateCopyAssign.h\"\n#include <gtest\/gtest.h>\n#include <gmock\/gmock.h>\n#include \"joynr\/MessageRouter.h\"\n#include \"joynr\/JoynrMessage.h\"\n#include \"joynr\/Dispatcher.h\"\n#include \"joynr\/SubscriptionCallback.h\"\n#include \"joynr\/SubscriptionPublication.h\"\n#include \"joynr\/SubscriptionStop.h\"\n#include \"joynr\/JoynrMessageFactory.h\"\n#include \"joynr\/Request.h\"\n#include \"joynr\/Reply.h\"\n#include \"joynr\/InterfaceRegistrar.h\"\n#include \"joynr\/MetaTypeRegistrar.h\"\n#include \"joynr\/tests\/testRequestInterpreter.h\"\n#include \"tests\/utils\/MockObjects.h\"\n#include \"joynr\/QtOnChangeWithKeepAliveSubscriptionQos.h\"\n#include <QString>\n#include \"joynr\/LibjoynrSettings.h\"\n\n#include \"joynr\/types\/Localisation_QtGpsLocation.h\"\n\nusing namespace ::testing;\n\nusing namespace joynr;\n\nACTION_P(ReleaseSemaphore,semaphore)\n{\n semaphore->release(1);\n}\n\n\/**\n * Is an integration test. Tests from Dispatcher -> SubscriptionListener and RequestCaller\n *\/\nclass BroadcastSubscriptionTest : public ::testing::Test {\npublic:\n BroadcastSubscriptionTest() :\n mockMessageRouter(new MockMessageRouter()),\n mockRequestCaller(new MockTestRequestCaller()),\n mockSubscriptionListenerOne(new MockSubscriptionListenerOneType<types::Localisation::QtGpsLocation>()),\n mockSubscriptionListenerTwo(new MockSubscriptionListenerTwoTypes<types::Localisation::QtGpsLocation, double>()),\n gpsLocation1(1.1, 2.2, 3.3, types::Localisation::GpsFixEnum::MODE2D, 0.0, 0.0, 0.0, 0.0, 444, 444, 444),\n speed1(100),\n qos(2000),\n providerParticipantId(\"providerParticipantId\"),\n proxyParticipantId(\"proxyParticipantId\"),\n messageFactory(),\n messageSender(mockMessageRouter),\n dispatcher(&messageSender),\n subscriptionManager(NULL)\n {\n }\n\n void SetUp(){\n QFile::remove(LibjoynrSettings::DEFAULT_BROADCASTSUBSCRIPTIONREQUEST_STORAGE_FILENAME()); \/\/remove stored subscriptions\n subscriptionManager = new SubscriptionManager();\n dispatcher.registerSubscriptionManager(subscriptionManager);\n InterfaceRegistrar::instance().registerRequestInterpreter<tests::testRequestInterpreter>(tests::ItestBase::INTERFACE_NAME());\n MetaTypeRegistrar::instance().registerMetaType<types::Localisation::QtGpsLocation>();\n MetaTypeRegistrar::instance().registerMetaType<types::Localisation::QtGpsLocation, double>();\n }\n\n void TearDown(){\n\n }\n\nprotected:\n std::shared_ptr<MockMessageRouter> mockMessageRouter;\n std::shared_ptr<MockTestRequestCaller> mockRequestCaller;\n std::shared_ptr<MockSubscriptionListenerOneType<types::Localisation::QtGpsLocation> > mockSubscriptionListenerOne;\n std::shared_ptr<MockSubscriptionListenerTwoTypes<types::Localisation::QtGpsLocation, double> > mockSubscriptionListenerTwo;\n\n types::Localisation::GpsLocation gpsLocation1;\n double speed1;\n\n \/\/ create test data\n MessagingQos qos;\n QString providerParticipantId;\n QString proxyParticipantId;\n\n JoynrMessageFactory messageFactory;\n JoynrMessageSender messageSender;\n Dispatcher dispatcher;\n SubscriptionManager * subscriptionManager;\nprivate:\n DISALLOW_COPY_AND_ASSIGN(BroadcastSubscriptionTest);\n};\n\n\/**\n * Trigger: The dispatcher receives a Publication from a broadcast with a single output parameter.\n * Expected: The SubscriptionManager retrieves the correct SubscriptionCallback and the\n * Interpreter executes it correctly\n *\/\nTEST_F(BroadcastSubscriptionTest, receive_publication_singleOutputParameter ) {\n\n qRegisterMetaType<SubscriptionPublication>(\"SubscriptionPublication\");\n\n \/\/ Use a semaphore to count and wait on calls to the mockSubscriptionListener\n QSemaphore semaphore(0);\n EXPECT_CALL(*mockSubscriptionListenerOne, onReceive(A<const types::Localisation::QtGpsLocation&>()))\n .WillRepeatedly(ReleaseSemaphore(&semaphore));\n\n \/\/register the subscription on the consumer side\n QString subscribeToName = \"locationUpdate\";\n Variant subscriptionQos = Variant::make<OnChangeWithKeepAliveSubscriptionQos>(OnChangeWithKeepAliveSubscriptionQos(\n 80, \/\/ validity_ms\n 100, \/\/ minInterval_ms\n 200, \/\/ maxInterval_ms\n 80 \/\/ alertInterval_ms\n ));\n\n BroadcastSubscriptionRequest subscriptionRequest;\n \/\/construct a reply containing a QtGpsLocation\n SubscriptionPublication subscriptionPublication;\n subscriptionPublication.setSubscriptionId(subscriptionRequest.getSubscriptionId());\n std::vector<Variant> response;\n response.push_back(Variant::make<types::Localisation::GpsLocation>(gpsLocation1));\n subscriptionPublication.setResponse(response);\n\n std::shared_ptr<SubscriptionCallback<types::Localisation::QtGpsLocation>> subscriptionCallback(\n new SubscriptionCallback<types::Localisation::QtGpsLocation>(mockSubscriptionListenerOne));\n\n\n \/\/ subscriptionRequest is an out param\n subscriptionManager->registerSubscription(\n subscribeToName,\n subscriptionCallback,\n subscriptionQos,\n subscriptionRequest);\n \/\/ incoming publication from the provider\n JoynrMessage msg = messageFactory.createSubscriptionPublication(\n providerParticipantId,\n proxyParticipantId,\n qos,\n subscriptionPublication);\n\n dispatcher.receive(msg);\n\n \/\/ Assert that only one subscription message is received by the subscription listener\n ASSERT_TRUE(semaphore.tryAcquire(1, 1000));\n ASSERT_FALSE(semaphore.tryAcquire(1, 250));\n}\n\n\/**\n * Trigger: The dispatcher receives a Publication from a broadcast with multiple output parameters.\n * Expected: The SubscriptionManager retrieves the correct SubscriptionCallback and the\n * Interpreter executes it correctly\n *\/\nTEST_F(BroadcastSubscriptionTest, receive_publication_multipleOutputParameters ) {\n\n qRegisterMetaType<SubscriptionPublication>(\"SubscriptionPublication\");\n\n \/\/ Use a semaphore to count and wait on calls to the mockSubscriptionListener\n QSemaphore semaphore(0);\n EXPECT_CALL(*mockSubscriptionListenerTwo, onReceive(A<const types::Localisation::QtGpsLocation&>(), A<const double&>()))\n .WillRepeatedly(ReleaseSemaphore(&semaphore));\n\n \/\/register the subscription on the consumer side\n QString subscribeToName = \"locationUpdateWithSpeed\";\n Variant subscriptionQos = Variant::make<OnChangeWithKeepAliveSubscriptionQos>(OnChangeWithKeepAliveSubscriptionQos(\n 80, \/\/ validity_ms\n 100, \/\/ minInterval_ms\n 200, \/\/ maxInterval_ms\n 80 \/\/ alertInterval_ms\n ));\n\n BroadcastSubscriptionRequest subscriptionRequest;\n \/\/construct a reply containing a QtGpsLocation\n SubscriptionPublication subscriptionPublication;\n subscriptionPublication.setSubscriptionId(subscriptionRequest.getSubscriptionId());\n std::vector<Variant> response;\n response.push_back(Variant::make<types::Localisation::GpsLocation>(gpsLocation1));\n response.push_back(Variant::make<double>(speed1));\n subscriptionPublication.setResponse(response);\n\n std::shared_ptr<SubscriptionCallback<types::Localisation::QtGpsLocation, double>> subscriptionCallback(\n new SubscriptionCallback<types::Localisation::QtGpsLocation, double>(mockSubscriptionListenerTwo));\n\n \/\/ subscriptionRequest is an out param\n subscriptionManager->registerSubscription(\n subscribeToName,\n subscriptionCallback,\n subscriptionQos,\n subscriptionRequest);\n \/\/ incoming publication from the provider\n JoynrMessage msg = messageFactory.createSubscriptionPublication(\n providerParticipantId,\n proxyParticipantId,\n qos,\n subscriptionPublication);\n\n dispatcher.receive(msg);\n\n \/\/ Assert that only one subscription message is received by the subscription listener\n ASSERT_TRUE(semaphore.tryAcquire(1, 1000));\n ASSERT_FALSE(semaphore.tryAcquire(1, 250));\n}\n<commit_msg>[C++] fixed BroadcastSubscriptionTest<commit_after>\/*\n * #%L\n * %%\n * Copyright (C) 2011 - 2013 BMW Car IT GmbH\n * %%\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * \n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * #L%\n *\/\n#include \"joynr\/PrivateCopyAssign.h\"\n#include <gtest\/gtest.h>\n#include <gmock\/gmock.h>\n#include \"joynr\/MessageRouter.h\"\n#include \"joynr\/JoynrMessage.h\"\n#include \"joynr\/Dispatcher.h\"\n#include \"joynr\/SubscriptionCallback.h\"\n#include \"joynr\/SubscriptionPublication.h\"\n#include \"joynr\/SubscriptionStop.h\"\n#include \"joynr\/JoynrMessageFactory.h\"\n#include \"joynr\/Request.h\"\n#include \"joynr\/Reply.h\"\n#include \"joynr\/InterfaceRegistrar.h\"\n#include \"joynr\/MetaTypeRegistrar.h\"\n#include \"joynr\/tests\/testRequestInterpreter.h\"\n#include \"tests\/utils\/MockObjects.h\"\n#include \"joynr\/OnChangeWithKeepAliveSubscriptionQos.h\"\n#include <QString>\n#include \"joynr\/LibjoynrSettings.h\"\n\n#include \"joynr\/types\/Localisation\/GpsLocation.h\"\n\nusing namespace ::testing;\n\nusing namespace joynr;\n\nACTION_P(ReleaseSemaphore,semaphore)\n{\n semaphore->release(1);\n}\n\n\/**\n * Is an integration test. Tests from Dispatcher -> SubscriptionListener and RequestCaller\n *\/\nclass BroadcastSubscriptionTest : public ::testing::Test {\npublic:\n BroadcastSubscriptionTest() :\n mockMessageRouter(new MockMessageRouter()),\n mockRequestCaller(new MockTestRequestCaller()),\n mockSubscriptionListenerOne(new MockSubscriptionListenerOneType<types::Localisation::GpsLocation>()),\n mockSubscriptionListenerTwo(new MockSubscriptionListenerTwoTypes<types::Localisation::GpsLocation, double>()),\n gpsLocation1(1.1, 2.2, 3.3, types::Localisation::GpsFixEnum::MODE2D, 0.0, 0.0, 0.0, 0.0, 444, 444, 444),\n speed1(100),\n qos(2000),\n providerParticipantId(\"providerParticipantId\"),\n proxyParticipantId(\"proxyParticipantId\"),\n messageFactory(),\n messageSender(mockMessageRouter),\n dispatcher(&messageSender),\n subscriptionManager(NULL)\n {\n }\n\n void SetUp(){\n QFile::remove(LibjoynrSettings::DEFAULT_BROADCASTSUBSCRIPTIONREQUEST_STORAGE_FILENAME()); \/\/remove stored subscriptions\n subscriptionManager = new SubscriptionManager();\n dispatcher.registerSubscriptionManager(subscriptionManager);\n InterfaceRegistrar::instance().registerRequestInterpreter<tests::testRequestInterpreter>(tests::ItestBase::INTERFACE_NAME());\n MetaTypeRegistrar::instance().registerMetaType<types::Localisation::GpsLocation>();\n MetaTypeRegistrar::instance().registerMetaType<types::Localisation::GpsLocation, double>();\n }\n\n void TearDown(){\n\n }\n\nprotected:\n std::shared_ptr<MockMessageRouter> mockMessageRouter;\n std::shared_ptr<MockTestRequestCaller> mockRequestCaller;\n std::shared_ptr<MockSubscriptionListenerOneType<types::Localisation::GpsLocation> > mockSubscriptionListenerOne;\n std::shared_ptr<MockSubscriptionListenerTwoTypes<types::Localisation::GpsLocation, double> > mockSubscriptionListenerTwo;\n\n types::Localisation::GpsLocation gpsLocation1;\n double speed1;\n\n \/\/ create test data\n MessagingQos qos;\n QString providerParticipantId;\n QString proxyParticipantId;\n\n JoynrMessageFactory messageFactory;\n JoynrMessageSender messageSender;\n Dispatcher dispatcher;\n SubscriptionManager * subscriptionManager;\nprivate:\n DISALLOW_COPY_AND_ASSIGN(BroadcastSubscriptionTest);\n};\n\n\/**\n * Trigger: The dispatcher receives a Publication from a broadcast with a single output parameter.\n * Expected: The SubscriptionManager retrieves the correct SubscriptionCallback and the\n * Interpreter executes it correctly\n *\/\nTEST_F(BroadcastSubscriptionTest, receive_publication_singleOutputParameter ) {\n\n qRegisterMetaType<SubscriptionPublication>(\"SubscriptionPublication\");\n\n \/\/ Use a semaphore to count and wait on calls to the mockSubscriptionListener\n QSemaphore semaphore(0);\n EXPECT_CALL(*mockSubscriptionListenerOne, onReceive(A<const types::Localisation::GpsLocation&>()))\n .WillRepeatedly(ReleaseSemaphore(&semaphore));\n\n \/\/register the subscription on the consumer side\n QString subscribeToName = \"locationUpdate\";\n Variant subscriptionQos = Variant::make<OnChangeWithKeepAliveSubscriptionQos>(OnChangeWithKeepAliveSubscriptionQos(\n 80, \/\/ validity_ms\n 100, \/\/ minInterval_ms\n 200, \/\/ maxInterval_ms\n 80 \/\/ alertInterval_ms\n ));\n\n BroadcastSubscriptionRequest subscriptionRequest;\n \/\/construct a reply containing a QtGpsLocation\n SubscriptionPublication subscriptionPublication;\n subscriptionPublication.setSubscriptionId(subscriptionRequest.getSubscriptionId());\n std::vector<Variant> response;\n response.push_back(Variant::make<types::Localisation::GpsLocation>(gpsLocation1));\n subscriptionPublication.setResponse(response);\n\n std::shared_ptr<SubscriptionCallback<types::Localisation::GpsLocation>> subscriptionCallback(\n new SubscriptionCallback<types::Localisation::GpsLocation>(mockSubscriptionListenerOne));\n\n\n \/\/ subscriptionRequest is an out param\n subscriptionManager->registerSubscription(\n subscribeToName,\n subscriptionCallback,\n subscriptionQos,\n subscriptionRequest);\n \/\/ incoming publication from the provider\n JoynrMessage msg = messageFactory.createSubscriptionPublication(\n providerParticipantId,\n proxyParticipantId,\n qos,\n subscriptionPublication);\n\n dispatcher.receive(msg);\n\n \/\/ Assert that only one subscription message is received by the subscription listener\n ASSERT_TRUE(semaphore.tryAcquire(1, 1000));\n ASSERT_FALSE(semaphore.tryAcquire(1, 250));\n}\n\n\/**\n * Trigger: The dispatcher receives a Publication from a broadcast with multiple output parameters.\n * Expected: The SubscriptionManager retrieves the correct SubscriptionCallback and the\n * Interpreter executes it correctly\n *\/\nTEST_F(BroadcastSubscriptionTest, receive_publication_multipleOutputParameters ) {\n\n \/\/ Use a semaphore to count and wait on calls to the mockSubscriptionListener\n QSemaphore semaphore(0);\n EXPECT_CALL(*mockSubscriptionListenerTwo, onReceive(A<const types::Localisation::GpsLocation&>(), A<const double&>()))\n .WillRepeatedly(ReleaseSemaphore(&semaphore));\n\n \/\/register the subscription on the consumer side\n QString subscribeToName = \"locationUpdateWithSpeed\";\n Variant subscriptionQos = Variant::make<OnChangeWithKeepAliveSubscriptionQos>(OnChangeWithKeepAliveSubscriptionQos(\n 80, \/\/ validity_ms\n 100, \/\/ minInterval_ms\n 200, \/\/ maxInterval_ms\n 80 \/\/ alertInterval_ms\n ));\n\n BroadcastSubscriptionRequest subscriptionRequest;\n \/\/construct a reply containing a GpsLocation\n SubscriptionPublication subscriptionPublication;\n subscriptionPublication.setSubscriptionId(subscriptionRequest.getSubscriptionId());\n std::vector<Variant> response;\n response.push_back(Variant::make<types::Localisation::GpsLocation>(gpsLocation1));\n response.push_back(Variant::make<double>(speed1));\n subscriptionPublication.setResponse(response);\n\n std::shared_ptr<SubscriptionCallback<types::Localisation::GpsLocation, double>> subscriptionCallback(\n new SubscriptionCallback<types::Localisation::GpsLocation, double>(mockSubscriptionListenerTwo));\n\n \/\/ subscriptionRequest is an out param\n subscriptionManager->registerSubscription(\n subscribeToName,\n subscriptionCallback,\n subscriptionQos,\n subscriptionRequest);\n \/\/ incoming publication from the provider\n JoynrMessage msg = messageFactory.createSubscriptionPublication(\n providerParticipantId,\n proxyParticipantId,\n qos,\n subscriptionPublication);\n\n dispatcher.receive(msg);\n\n \/\/ Assert that only one subscription message is received by the subscription listener\n ASSERT_TRUE(semaphore.tryAcquire(1, 1000));\n ASSERT_FALSE(semaphore.tryAcquire(1, 250));\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n FILNAMN: \t\troom.cc\n PROGRAMMERARE:\thanel742, eriek984, jened502, tobgr602, niker917, davha227\n SKAPAD DATUM:\t2013-11-14\n BESKRIVNING:\n *\/\n\n#include \"room.h\"\n\nusing namespace std;\n\n\/\/ ----------------------------------\n\/\/ Constructor\n\nRoom::Room(string inName,Master* master) {\n masterPointer = master;\n name = inName;\n}\n\n\/\/ ----------------------------------------\n\/\/ Help functions\n\nvoid ifRoomRemove(Room* inRoom) {\n cout << \"IfRoomRemove: \";\n cout << inRoom->getName() << endl;\n User* userTemp = dynamic_cast<User*>(inRoom);\n \n if (userTemp == nullptr) {\n inRoom->masterPointer->removeRoom(inRoom->getName());\n }\n}\n\nvoid throwUp(Room* inRoom) {\n inRoom->chooseRoom(inRoom->parentRoom->parentRoom);\n}\n\nvoid deleteRooms(Room* inRoom) {\n \n}\n\n\/\/ ----------------------------------------\n\/\/ Destructor\n\nRoom::~Room() {\n for_each(rooms.begin(), rooms.end(), ifRoomRemove);\n \n if ( parentRoom == nullptr) {\n rooms.clear();\n }\n else {\n \n parentRoom->removeRoom(this);\n \n for_each(rooms.begin(), rooms.end(), throwUp);\n parentRoom = nullptr;\n }\n \n masterPointer = nullptr;\n \n}\n\n\/\/ ----------------------------------------\n\nunsigned int Room::getPosOfRoom(string name) const{\n for( unsigned int i = 0 ; i < rooms.size() ; i++) {\n if(rooms.at(i)->getName() == name){\n return i;\n }\n }\n throw logic_error(\"No such room in Rooms\");\n return 0;\n}\n\n\/\/ ----------------------------------------\n\/\/ Automatically called from child when child room is destroyed\nvoid Room::removeRoom(Room* inRoom) {\n unsigned int pos = getPosOfRoom(inRoom->getName());\n rooms.at(pos) = nullptr;\n rooms.erase(rooms.begin() + pos);\n}\n\n\/\/ ----------------------------------\n\nvoid Room::sendMessage(Message inMessage) {\n string to = inMessage.getTo();\n \n try {\n getRoom(to)->receiveMessage(inMessage);\n } catch (...) {\n Message errorMessage(\"No such user in this room.\",name,inMessage.getFrom());\n }\n \n}\n\n\n\/\/ ----------------------------------\n\nvoid Room::listRooms(){\n for (unsigned int it = 0; it < rooms.size() ; it++){\n User* userTemp = dynamic_cast<User*>(rooms.at(it));\n if(userTemp == nullptr ){\n cout << rooms.at(it)->getName() << endl;\n }\n }\n return;\n}\n\n\/\/ ----------------------------------\n\nvoid Room::listUsers(){\n for (unsigned int it = 0; it < rooms.size() ; it++){\n User* userTemp = dynamic_cast<User*>(rooms.at(it));\n if( userTemp == nullptr ){\n continue;\n }\n else{\n cout << rooms.at(it)->getName() << endl;\n }\n }\n return;\n}\n\nvoid Room::receiveMessage(Message inMessage) {\n string to = inMessage.getTo();\n if(to == name){\n log.push_back(inMessage);\n \n sendMessageAll(inMessage);\n \n saveToFile(inMessage);\n }\n else{\n sendMessage(inMessage);\n }\n}\n\n\/\/ ----------------------------------\n\nvoid Room::sendMessageAll(Message inMessage) {\n string to = inMessage.getTo();\n \n unsigned int pos = getPosOfRoom(to);\n \n for (unsigned int i = 0; i < rooms.size(); i++) {\n User* userTemp = dynamic_cast<User*>(rooms.at(pos));\n if ( userTemp == nullptr ) {\n continue;\n }\n rooms.at(pos)->receiveMessage(inMessage);\n }\n}\n\n\/\/ ----------------------------------\n\nvoid Room::addRoom(Room* inRoom) {\n this->rooms.push_back(inRoom);\n}\n\n\n\n\/\/ ----------------------------------\n\nvoid Room::saveToFile(Message inMessage) {\n cout << inMessage.getMessage() << endl;\n return;\n}\n\n\/\/ ------------------------------------\n\nstring Room::getName() {\n return name;\n}\n\n\/\/ ------------------------------------\n\nvoid Room::createRoom(std::string inName){\n\taddRoom(masterPointer->createRoom(inName));\n}\n\n\/\/ ------------------------------------\n\nRoom* Room::getRoom(std::string name){\n for( unsigned int i = 0 ; i < rooms.size() ; i++) {\n if(rooms.at(i)->getName() == name){\n return rooms.at(i);\n }\n }\n throw logic_error(\"No such room in Rooms\");\n \n return nullptr;\n}\n\n\/\/ -----------------------------------\n\nMessage Room::getMessage(unsigned int i){\n if (log.size() < i){\n throw logic_error{\"No message at that position!\"};\n }\n return log.at(i);\n}\n\n\/\/ -----------------------------------\n\nvoid Room::chooseRoom(Room*) {\n throw logic_error{\"You're a retard since you're trying to move a room.\"};\n}\n<commit_msg>Can't fix segfault<commit_after>\/*\n FILNAMN: \t\troom.cc\n PROGRAMMERARE:\thanel742, eriek984, jened502, tobgr602, niker917, davha227\n SKAPAD DATUM:\t2013-11-14\n BESKRIVNING:\n *\/\n\n#include \"room.h\"\n\nusing namespace std;\n\n\/\/ ----------------------------------\n\/\/ Constructor\n\nRoom::Room(string inName,Master* master) {\n masterPointer = master;\n name = inName;\n}\n\n\/\/ ----------------------------------------\n\/\/ Help functions\n\nvoid ifRoomRemove(Room* inRoom) {\n cout << \"IfRoomRemove: \";\n cout << inRoom->getName() << endl;\n User* userTemp = dynamic_cast<User*>(inRoom);\n \n if (userTemp == nullptr) {\n cout << \"nullptr\" << endl;\n inRoom->masterPointer->removeRoom(inRoom->getName());\n }\n}\n\nvoid throwUp(Room* inRoom) {\n inRoom->chooseRoom(inRoom->parentRoom->parentRoom);\n}\n\n\/\/ ----------------------------------------\n\/\/ Destructor\n\nRoom::~Room() {\n for_each(rooms.begin(), rooms.end(), ifRoomRemove);\n \n if ( parentRoom == nullptr) {\n rooms.clear();\n }\n else {\n \n parentRoom->removeRoom(this);\n \n for_each(rooms.begin(), rooms.end(), throwUp);\n parentRoom = nullptr;\n }\n \n masterPointer = nullptr;\n \n}\n\n\/\/ ----------------------------------------\n\nunsigned int Room::getPosOfRoom(string name) const{\n for( unsigned int i = 0 ; i < rooms.size() ; i++) {\n if(rooms.at(i)->getName() == name){\n return i;\n }\n }\n throw logic_error(\"No such room in Rooms\");\n return 0;\n}\n\n\/\/ ----------------------------------------\n\/\/ Automatically called from child when child room is destroyed\nvoid Room::removeRoom(Room* inRoom) {\n unsigned int pos = getPosOfRoom(inRoom->getName());\n rooms.at(pos) = nullptr;\n rooms.erase(rooms.begin() + pos);\n}\n\n\/\/ ----------------------------------\n\nvoid Room::sendMessage(Message inMessage) {\n string to = inMessage.getTo();\n \n try {\n getRoom(to)->receiveMessage(inMessage);\n } catch (...) {\n Message errorMessage(\"No such user in this room.\",name,inMessage.getFrom());\n }\n \n}\n\n\n\/\/ ----------------------------------\n\nvoid Room::listRooms(){\n for (unsigned int it = 0; it < rooms.size() ; it++){\n User* userTemp = dynamic_cast<User*>(rooms.at(it));\n if(userTemp == nullptr ){\n cout << rooms.at(it)->getName() << endl;\n }\n }\n return;\n}\n\n\/\/ ----------------------------------\n\nvoid Room::listUsers(){\n for (unsigned int it = 0; it < rooms.size() ; it++){\n User* userTemp = dynamic_cast<User*>(rooms.at(it));\n if( userTemp == nullptr ){\n continue;\n }\n else{\n cout << rooms.at(it)->getName() << endl;\n }\n }\n return;\n}\n\nvoid Room::receiveMessage(Message inMessage) {\n string to = inMessage.getTo();\n if(to == name){\n log.push_back(inMessage);\n \n sendMessageAll(inMessage);\n \n saveToFile(inMessage);\n }\n else{\n sendMessage(inMessage);\n }\n}\n\n\/\/ ----------------------------------\n\nvoid Room::sendMessageAll(Message inMessage) {\n string to = inMessage.getTo();\n \n unsigned int pos = getPosOfRoom(to);\n \n for (unsigned int i = 0; i < rooms.size(); i++) {\n User* userTemp = dynamic_cast<User*>(rooms.at(pos));\n if ( userTemp == nullptr ) {\n continue;\n }\n rooms.at(pos)->receiveMessage(inMessage);\n }\n}\n\n\/\/ ----------------------------------\n\nvoid Room::addRoom(Room* inRoom) {\n this->rooms.push_back(inRoom);\n}\n\n\n\n\/\/ ----------------------------------\n\nvoid Room::saveToFile(Message inMessage) {\n cout << inMessage.getMessage() << endl;\n return;\n}\n\n\/\/ ------------------------------------\n\nstring Room::getName() {\n return name;\n}\n\n\/\/ ------------------------------------\n\nvoid Room::createRoom(std::string inName){\n\taddRoom(masterPointer->createRoom(inName));\n}\n\n\/\/ ------------------------------------\n\nRoom* Room::getRoom(std::string name){\n for( unsigned int i = 0 ; i < rooms.size() ; i++) {\n if(rooms.at(i)->getName() == name){\n return rooms.at(i);\n }\n }\n throw logic_error(\"No such room in Rooms\");\n \n return nullptr;\n}\n\n\/\/ -----------------------------------\n\nMessage Room::getMessage(unsigned int i){\n if (log.size() < i){\n throw logic_error{\"No message at that position!\"};\n }\n return log.at(i);\n}\n\n\/\/ -----------------------------------\n\nvoid Room::chooseRoom(Room*) {\n throw logic_error{\"You're a retard since you're trying to move a room.\"};\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Sh: A GPU metaprogramming language.\n\/\/\n\/\/ Copyright 2003-2005 Serious Hack Inc.\n\/\/ \n\/\/ This library is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU Lesser General Public\n\/\/ License as published by the Free Software Foundation; either\n\/\/ version 2.1 of the License, or (at your option) any later version.\n\/\/\n\/\/ This library is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ Lesser General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License along with this library; if not, write to the Free Software\n\/\/ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, \n\/\/ MA 02110-1301, USA\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n#include \"ShLinearAllocator.hpp\"\n#include <set>\n#include <algorithm>\n#include \"ShDebug.hpp\"\n\nnamespace {\n\nstruct LifeToken {\n LifeToken(const SH::ShVariableNodePtr& var, int index, bool end)\n : var(var), index(index), end(end) \n {\n }\n \n SH::ShVariableNodePtr var;\n int index;\n bool end;\n\n \/\/ order by index, then end\n bool operator<(const LifeToken& other) const\n {\n if (index == other.index) {\n return !end;\n }\n return index < other.index;\n }\n};\n\n}\n\nnamespace SH {\n\nShLinearAllocator::ShLinearAllocator(ShBackendCodePtr backendCode)\n : m_backendCode(backendCode)\n{\n}\n\nvoid ShLinearAllocator::mark(const ShVariableNodePtr& var, int index)\n{\n if (!var) return;\n LifetimeMap::iterator I = m_lifetimes.find(var);\n\n if (I == m_lifetimes.end()) {\n m_lifetimes[var] = ShLifeTime(var, index);\n } else {\n I->second.mark(index);\n }\n}\n\nvoid ShLinearAllocator::debugDump()\n{\n#ifdef SH_DEBUG\n for (LifetimeMap::const_iterator I = m_lifetimes.begin(); I != m_lifetimes.end(); ++I) {\n SH_DEBUG_PRINT(I->first->name() << \" = {\" << I->second.first << \", \" << I->second.last << \"}\");\n }\n#endif\n}\n\nvoid ShLinearAllocator::allocate()\n{\n std::multiset<LifeToken> temps;\n\n for (LifetimeMap::const_iterator I = m_lifetimes.begin(); I != m_lifetimes.end(); ++I) {\n temps.insert(LifeToken(I->first, I->second.first, false));\n temps.insert(LifeToken(I->first, I->second.last, true));\n }\n\n for (std::multiset<LifeToken>::const_iterator I = temps.begin(); I != temps.end(); ++I) {\n if (!I->end) {\n if (!m_backendCode->allocateRegister(I->var)) {\n \/\/ TODO: Error\n SH_DEBUG_WARN(\"Error allocating a register for \" << I->var->name());\n }\n } else {\n m_backendCode->freeRegister(I->var);\n }\n }\n}\n\n}\n\n<commit_msg>Allocate: multiset requires strict weak ordering; LifeToken (operator<): if (a<b) -> !(b<a).<commit_after>\/\/ Sh: A GPU metaprogramming language.\n\/\/\n\/\/ Copyright 2003-2005 Serious Hack Inc.\n\/\/ \n\/\/ This library is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU Lesser General Public\n\/\/ License as published by the Free Software Foundation; either\n\/\/ version 2.1 of the License, or (at your option) any later version.\n\/\/\n\/\/ This library is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ Lesser General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License along with this library; if not, write to the Free Software\n\/\/ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, \n\/\/ MA 02110-1301, USA\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n#include \"ShLinearAllocator.hpp\"\n#include <set>\n#include <algorithm>\n#include \"ShDebug.hpp\"\n\nnamespace {\n\nstruct LifeToken {\n LifeToken(const SH::ShVariableNodePtr& var, int index, bool end)\n : var(var), index(index), end(end) \n {\n }\n \n SH::ShVariableNodePtr var;\n int index;\n bool end;\n\n \/**\n * Order by index, then end.\n * Strict weak ordering:\n * if (a<b) -> !(b<a).\n *\/\n bool operator<(const LifeToken& other) const\n {\n if (index == other.index) {\n return !end && other.end;\n }\n return index < other.index;\n }\n};\n\n}\n\nnamespace SH {\n\nShLinearAllocator::ShLinearAllocator(ShBackendCodePtr backendCode)\n : m_backendCode(backendCode)\n{\n}\n\nvoid ShLinearAllocator::mark(const ShVariableNodePtr& var, int index)\n{\n if (!var) return;\n LifetimeMap::iterator I = m_lifetimes.find(var);\n\n if (I == m_lifetimes.end()) {\n m_lifetimes[var] = ShLifeTime(var, index);\n } else {\n I->second.mark(index);\n }\n}\n\nvoid ShLinearAllocator::debugDump()\n{\n#ifdef SH_DEBUG\n for (LifetimeMap::const_iterator I = m_lifetimes.begin(); I != m_lifetimes.end(); ++I) {\n SH_DEBUG_PRINT(I->first->name() << \" = {\" << I->second.first << \", \" << I->second.last << \"}\");\n }\n#endif\n}\n\nvoid ShLinearAllocator::allocate()\n{\n std::multiset<LifeToken> temps;\n\n for (LifetimeMap::const_iterator I = m_lifetimes.begin(); I != m_lifetimes.end(); ++I) {\n temps.insert(LifeToken(I->first, I->second.first, false));\n temps.insert(LifeToken(I->first, I->second.last, true));\n }\n\n for (std::multiset<LifeToken>::const_iterator I = temps.begin(); I != temps.end(); ++I) {\n if (!I->end) {\n if (!m_backendCode->allocateRegister(I->var)) {\n \/\/ TODO: Error\n SH_DEBUG_WARN(\"Error allocating a register for \" << I->var->name());\n }\n } else {\n m_backendCode->freeRegister(I->var);\n }\n }\n}\n\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/\/\/ COMPONENT\n#include <csapex\/model\/node.h>\n#include <csapex\/model\/node_modifier.h>\n#include <csapex\/msg\/io.h>\n#include <csapex\/param\/parameter_factory.h>\n#include <csapex\/utility\/register_apex_plugin.h>\n#include <csapex_opencv\/cv_mat_message.h>\n\nnamespace csapex\n{\nusing namespace csapex;\nusing namespace connection_types;\n\nclass BGRToIlluminationInvariant : public csapex::Node\n{\npublic:\n BGRToIlluminationInvariant() = default;\n virtual ~BGRToIlluminationInvariant() = default;\n\n virtual void process() override\n {\n CvMatMessage::ConstPtr in = msg::getMessage<connection_types::CvMatMessage>(input_);\n if (!in->getEncoding().matches(enc::bgr))\n throw std::runtime_error(\"Image needs to be BGR for fitting conversion.\");\n\n CvMatMessage::Ptr out(new connection_types::CvMatMessage(enc::mono, in->frame_id, in->stamp_micro_seconds));\n out->value = cv::Mat(in->value.rows, in->value.cols, CV_32FC1, cv::Scalar());\n CvMatMessage::Ptr out_mask(new connection_types::CvMatMessage(enc::mono, in->frame_id, in->stamp_micro_seconds));\n out_mask->value = cv::Mat(in->value.rows, in->value.cols, CV_8UC1, cv::Scalar(0));\n\n \/\/ bool cap\n \/\/ conditional for cap (min\/max) interval param\n \/\/ mask also with capped pixels\n \/\/ ternary after norm for cap (after ill.invar)\n \/\/ labels : 0 unaltered, 1 invalid, 2 capped (or 2 for min capped 3 for max\n \/\/ capped)\n \/\/--> labels to mask <-> generate mask from label (as parameter)\n \/\/--> labels to random color <-> check examples for random colors\n\n std::pair<float, float> threshold_min_max = readParameter<std::pair<int, int>>(\"threshold range\");\n threshold_min_max.first = threshold_min_max.first \/ 100.0;\n threshold_min_max.second = threshold_min_max.second \/ 100.0;\n\n bool use_threshold = readParameter<bool>(\"threshold\");\n\n switch (method_) {\n case NewmanOriginal: {\n const cv::Vec3b* src = in->value.ptr<cv::Vec3b>();\n float* dst = out->value.ptr<float>();\n uchar* mask = out_mask->value.ptr<uchar>();\n const std::size_t size = static_cast<std::size_t>(out->value.cols * out->value.rows);\n\n for (std::size_t i = 0; i < size; ++i) {\n const cv::Vec3b& p = src[i];\n if (p[0] == 0 || p[1] == 0 || p[2] == 0) {\n mask[i] = 0;\n continue;\n }\n cv::Vec3f c(p[0] \/ 255.0, p[1] \/ 255.0, p[2] \/ 255.0);\n dst[i] = 0.5 + std::log(c[1]) - alpha_ * std::log(c[0]) - (1.0 - alpha_) * std::log(c[2]);\n }\n } break;\n case Newman: {\n \/\/ N = (0.5+log(g)) - alpha*log(b) - (1-alpha)*log(r)\n \/\/ Max= 0.5 + log(255) - alpha*log(b) - log(r) + alpha*log(r) = 0.5 +\n \/\/ log(255) (alpha,b,r = 0) Min= 0.5 + log(1) - alpha*log(b) - log(r) +\n \/\/ alpha*log(r) = 0.5 - log(255) (alpha=1,b=255, r=0)\n double min = 0.5 - std::log(255.0);\n double max = 0.5 + std::log(255.0);\n\n const cv::Vec3b* src = in->value.ptr<cv::Vec3b>();\n float* dst = out->value.ptr<float>();\n uchar* mask = out_mask->value.ptr<uchar>();\n const std::size_t size = static_cast<std::size_t>(out->value.cols * out->value.rows);\n\n auto get_thresholded = [&](int i) -> std::pair<double, double> {\n if (use_threshold) {\n if (dst[i] < threshold_min_max.first) {\n return std::make_pair(threshold_min_max.first, 2);\n } else if (dst[i] > threshold_min_max.second) {\n return std::make_pair(threshold_min_max.second, 3);\n }\n }\n return std::make_pair(dst[i], mask[i]);\n };\n\n for (std::size_t i = 0; i < size; ++i) {\n const cv::Vec3b& p = src[i];\n cv::Vec3f c(p);\n if (p[0] == 0 || p[1] == 0 || p[2] == 0) {\n mask[i] = 0;\n continue;\n }\n dst[i] = (0.5 + std::log(c[1]) - alpha_ * std::log(c[0]) - (1.0 - alpha_) * std::log(c[2]));\n dst[i] = ((dst[i] - min) \/ (max - min)); \/\/ normalize 0-1\n std::tie(dst[i], mask[i]) = get_thresholded(i); \/\/ threshold min\/max\n \/\/ vals\n dst[i] = dst[i] * 255.0; \/\/ discretize 0-255\n }\n } break;\n case SantosOriginal: {\n const cv::Vec3b* src = in->value.ptr<cv::Vec3b>();\n float* dst = out->value.ptr<float>();\n uchar* mask = out_mask->value.ptr<uchar>();\n const std::size_t size = static_cast<std::size_t>(out->value.cols * out->value.rows);\n\n const double theta = M_PI * alpha_;\n const double ct = std::cos(theta);\n const double st = std::sin(theta);\n\n const static cv::Vec3f v1(1.0 \/ std::sqrt(2.0), -1.0 \/ std::sqrt(2.0), 0.0);\n const static cv::Vec3f v2(1.0 \/ std::sqrt(6.0), 1.0 \/ std::sqrt(6.0),\n -2.0 \/ std::sqrt(6.0)); \/\/\/\/ Entropy Minimization for Shadow Removal\n\n \/\/ double min = 0.0;\n double max = std::log(1.0 \/ std::sqrt(1.0 \/ 255.0)) \/ std::sqrt(2.0);\n\n for (std::size_t i = 0; i < size; ++i) {\n const cv::Vec3b& p = src[i];\n if (p[0] == 0 && p[1] == 0 && p[2] == 0) {\n mask[i] = 0;\n dst[i] = 0;\n continue;\n }\n cv::Vec3f c(p[0] \/ 255.0, p[1] \/ 255.0, p[2] \/ 255.0);\n const double rho = std::sqrt(c.ddot(c));\n c \/= rho;\n const cv::Vec2f psi(c.ddot(v1), c.ddot(v2));\n dst[i] = (psi[0] * ct + psi[1] * st) \/ max;\n }\n\n \/\/\/ sqrt2(1) <=> sqrt2(1\/255.)\n \/\/\/ ct + st <= sqrt(2)\n } break;\n\n case Santos: {\n const cv::Vec3b* src = in->value.ptr<cv::Vec3b>();\n float* dst = out->value.ptr<float>();\n uchar* mask = out_mask->value.ptr<uchar>();\n const std::size_t size = static_cast<std::size_t>(out->value.cols * out->value.rows);\n\n const double theta = M_PI * alpha_;\n const double ct = std::cos(theta);\n const double st = std::sin(theta);\n const static cv::Vec3f v1(1.0 \/ std::sqrt(2.0), -1.0 \/ std::sqrt(2.0), 0.0);\n const static cv::Vec3f v2(1.0 \/ std::sqrt(6.0), 1.0 \/ std::sqrt(6.0),\n -2.0 \/ std::sqrt(6.0)); \/\/\/\/ Entropy Minimization for Shadow Removal\n\n \/\/ p_M = cbrt(pr*pg*pb) max=1, min=1\/255\n \/\/ chi_r,g,b = log(p_r,g,b\/p_M) max=log(255), min=log(1)\n \/\/ psi_1,2 = U x chi_r,g,b psi_1:max\/min = +\/-\n \/\/ (1\/sqrt(2)*log(255)), psi_2:max\/min = +\/- (2\/sqrt(6)*log(255)) I =\n \/\/ psi_1*cos(theta)+psi_2*sin(theta) max\/min = +\/-\n \/\/ (log(255)*(1\/2+1\/sqrt(3))\n\n double max = std::log(255.0) * (0.5 + (1.0 \/ std::sqrt(3)));\n double min = -max;\n\n auto get_thresholded = [&](int i) -> std::pair<double, double> {\n if (use_threshold) {\n if (dst[i] < threshold_min_max.first) {\n return std::make_pair(threshold_min_max.first, 2);\n } else if (dst[i] > threshold_min_max.second) {\n return std::make_pair(threshold_min_max.second, 3);\n }\n }\n return std::make_pair(dst[i], mask[i]);\n };\n\n for (std::size_t i = 0; i < size; ++i) {\n const cv::Vec3b& p = src[i];\n if (p[0] == 0 || p[1] == 0 || p[2] == 0) {\n mask[i] = 1;\n \/\/ dst[i] = 128;\n dst[i] = (p[2] > p[1] || p[2] > p[0]) ? 1 : 0;\n continue;\n }\n\n cv::Vec3f c(p[0] \/ 255.0, p[1] \/ 255.0, p[2] \/ 255.0);\n\n const double rho = std::pow((c[0] * c[1] * c[2]), 1.0 \/ 3);\n c \/= rho;\n c[0] = std::log(c[0]);\n c[1] = std::log(c[1]);\n c[2] = std::log(c[2]);\n const cv::Vec2f psi(c.ddot(v1), c.ddot(v2));\n dst[i] = ((psi[0] * ct + psi[1] * st) - min) \/ (max - min); \/\/ normalize\n\n std::tie(dst[i], mask[i]) = get_thresholded(i); \/\/ threshold min\/max\n \/\/ vals\n\n dst[i] = dst[i] * 255.0; \/\/ discretize 0-255\n }\n } break;\n default:\n break;\n }\n msg::publish(output_, out);\n msg::publish(output_mask_, out_mask);\n }\n\n virtual void setup(csapex::NodeModifier& node_modifier) override\n {\n input_ = node_modifier.addInput<CvMatMessage>(\"original\");\n output_ = node_modifier.addOutput<CvMatMessage>(\"adjusted\");\n output_mask_ = node_modifier.addOutput<CvMatMessage>(\"label mask\");\n }\n\n virtual void setupParameters(Parameterizable& parameters)\n {\n parameters.addParameter(param::ParameterFactory::declareRange(\"alpha\", 0.0, 1.0, 1.5, 0.001), alpha_);\n std::map<std::string, int> methods = { { \"Newman\", (int)Newman }, { \"NewmanOriginal\", (int)NewmanOriginal }, { \"Santos\", (int)Santos }, { \"SantosOriginal\", (int)SantosOriginal } };\n\n parameters.addParameter(param::ParameterFactory::declareParameterSet<int>(\"method\", methods, Newman), method_);\n\n param::Parameter::Ptr method = param::factory::declareBool(\"threshold\", param::ParameterDescription(\"Apply min\/max thresholding.\"), true);\n\n parameters.addParameter(method, std::bind(&BGRToIlluminationInvariant::submit, this));\n\n std::function<bool()> k_cond = (std::bind(¶m::Parameter::as<bool>, method.get()));\n parameters.addConditionalParameter(param::factory::declareInterval(\"threshold range\", param::ParameterDescription(\"Valid and acceptable range\"), 0, 100, 0, 100, 1), k_cond,\n std::bind(&BGRToIlluminationInvariant::submit, this));\n\n parameters.setParameter(\"threshold range\", std::pair<int, int>(5, 95));\n }\n void submit()\n {\n }\n\nprotected:\n csapex::Output* output_;\n csapex::Output* output_mask_;\n\n enum Type\n {\n Newman,\n NewmanOriginal,\n Santos,\n SantosOriginal\n };\n\n csapex::Input* input_;\n double alpha_;\n int method_;\n bool recover_bgr_;\n};\n} \/\/ namespace csapex\n\nCSAPEX_REGISTER_CLASS(csapex::BGRToIlluminationInvariant, csapex::Node)\n<commit_msg>illumination invariance optimizations<commit_after>\/\/\/ COMPONENT\n#include <csapex\/model\/node.h>\n#include <csapex\/model\/node_modifier.h>\n#include <csapex\/msg\/io.h>\n#include <csapex\/param\/parameter_factory.h>\n#include <csapex\/utility\/register_apex_plugin.h>\n#include <csapex_opencv\/cv_mat_message.h>\n\nnamespace csapex\n{\nusing namespace csapex;\nusing namespace connection_types;\n\nclass BGRToIlluminationInvariant : public csapex::Node\n{\npublic:\n BGRToIlluminationInvariant() = default;\n virtual ~BGRToIlluminationInvariant() = default;\n\n virtual void process() override\n {\n CvMatMessage::ConstPtr in = msg::getMessage<connection_types::CvMatMessage>(input_);\n if (!in->getEncoding().matches(enc::bgr))\n throw std::runtime_error(\"Image needs to be BGR for fitting conversion.\");\n\n CvMatMessage::Ptr out(new connection_types::CvMatMessage(enc::mono, in->frame_id, in->stamp_micro_seconds));\n out->value = cv::Mat(in->value.rows, in->value.cols, CV_32FC1, cv::Scalar());\n CvMatMessage::Ptr out_mask(new connection_types::CvMatMessage(enc::mono, in->frame_id, in->stamp_micro_seconds));\n out_mask->value = cv::Mat(in->value.rows, in->value.cols, CV_8UC1, cv::Scalar(0));\n\n \/\/ bool cap\n \/\/ conditional for cap (min\/max) interval param\n \/\/ mask also with capped pixels\n \/\/ ternary after norm for cap (after ill.invar)\n \/\/ labels : 0 unaltered, 1 invalid, 2 capped (or 2 for min capped 3 for max\n \/\/ capped)\n \/\/--> labels to mask <-> generate mask from label (as parameter)\n \/\/--> labels to random color <-> check examples for random colors\n\n std::pair<float, float> threshold_min_max = readParameter<std::pair<int, int>>(\"threshold range\");\n threshold_min_max.first = threshold_min_max.first \/ 100.0;\n threshold_min_max.second = threshold_min_max.second \/ 100.0;\n\n bool use_threshold = readParameter<bool>(\"threshold\");\n\n switch (method_) {\n case NewmanOriginal: {\n const cv::Vec3b* src = in->value.ptr<cv::Vec3b>();\n float* dst = out->value.ptr<float>();\n uchar* mask = out_mask->value.ptr<uchar>();\n const std::size_t size = static_cast<std::size_t>(out->value.cols * out->value.rows);\n\n for (std::size_t i = 0; i < size; ++i) {\n const cv::Vec3b& p = src[i];\n if (p[0] == 0 || p[1] == 0 || p[2] == 0) {\n mask[i] = 0;\n continue;\n }\n cv::Vec3f c(p[0] \/ 255.0, p[1] \/ 255.0, p[2] \/ 255.0);\n dst[i] = 0.5 + std::log(c[1]) - alpha_ * std::log(c[0]) - (1.0 - alpha_) * std::log(c[2]);\n }\n } break;\n case Newman: {\n \/\/ N = (0.5+log(g)) - alpha*log(b) - (1-alpha)*log(r)\n \/\/ Max= 0.5 + log(255) - alpha*log(b) - log(r) + alpha*log(r) = 0.5 +\n \/\/ log(255) (alpha,b,r = 0) Min= 0.5 + log(1) - alpha*log(b) - log(r) +\n \/\/ alpha*log(r) = 0.5 - log(255) (alpha=1,b=255, r=0)\n\/\/ double min = 0.5 - std::log(255.0);\n\/\/ double max = 0.5 + std::log(255.0);\n\n const cv::Vec3b* src = in->value.ptr<cv::Vec3b>();\n float* dst = out->value.ptr<float>();\n uchar* mask = out_mask->value.ptr<uchar>();\n const std::size_t size = static_cast<std::size_t>(out->value.cols * out->value.rows);\n\n\n for (std::size_t i = 0; i < size; ++i) {\n const cv::Vec3b& p = src[i];\n cv::Vec3f c(p);\n if (p[0] == 0 || p[1] == 0 || p[2] == 0) {\n mask[i] = 0;\n continue;\n }\n dst[i] = (0.5 + std::log(c[1]) - alpha_ * std::log(c[0]) - (1.0 - alpha_) * std::log(c[2]));\n dst[i] = ((dst[i] - newman_min) \/ (newman_max - newman_min)); \/\/ normalize 0-1\n\n \/\/threshold min\/max\n if (use_threshold) {\n if (dst[i] < threshold_min_max.first) {\n dst[i] = threshold_min_max.first;\n mask[i] = 2;\n } else if (dst[i] > threshold_min_max.second) {\n dst[i] = threshold_min_max.second;\n mask[i] = 3;\n }\n }\n\n dst[i] = dst[i] * 255.0; \/\/ discretize 0-255\n }\n } break;\n case SantosOriginal: {\n const cv::Vec3b* src = in->value.ptr<cv::Vec3b>();\n float* dst = out->value.ptr<float>();\n uchar* mask = out_mask->value.ptr<uchar>();\n const std::size_t size = static_cast<std::size_t>(out->value.cols * out->value.rows);\n\n const double theta = M_PI * alpha_;\n const double ct = std::cos(theta);\n const double st = std::sin(theta);\n\n const static cv::Vec3f v1(1.0 \/ std::sqrt(2.0), -1.0 \/ std::sqrt(2.0), 0.0);\n const static cv::Vec3f v2(1.0 \/ std::sqrt(6.0), 1.0 \/ std::sqrt(6.0),\n -2.0 \/ std::sqrt(6.0)); \/\/\/\/ Entropy Minimization for Shadow Removal\n\n \/\/ double min = 0.0;\n double max = std::log(1.0 \/ std::sqrt(1.0 \/ 255.0)) \/ std::sqrt(2.0);\n\n for (std::size_t i = 0; i < size; ++i) {\n const cv::Vec3b& p = src[i];\n if (p[0] == 0 && p[1] == 0 && p[2] == 0) {\n mask[i] = 0;\n dst[i] = 0;\n continue;\n }\n cv::Vec3f c(p[0] \/ 255.0, p[1] \/ 255.0, p[2] \/ 255.0);\n const double rho = std::sqrt(c.ddot(c));\n c \/= rho;\n const cv::Vec2f psi(c.ddot(v1), c.ddot(v2));\n dst[i] = (psi[0] * ct + psi[1] * st) \/ max;\n }\n\n \/\/\/ sqrt2(1) <=> sqrt2(1\/255.)\n \/\/\/ ct + st <= sqrt(2)\n } break;\n\n case Santos: {\n const cv::Vec3b* src = in->value.ptr<cv::Vec3b>();\n float* dst = out->value.ptr<float>();\n uchar* mask = out_mask->value.ptr<uchar>();\n const std::size_t size = static_cast<std::size_t>(out->value.cols * out->value.rows);\n\n const double theta = M_PI * alpha_;\n const double ct = std::cos(theta);\n const double st = std::sin(theta);\n const static cv::Vec3f v1(1.0 \/ std::sqrt(2.0), -1.0 \/ std::sqrt(2.0), 0.0);\n const static cv::Vec3f v2(1.0 \/ std::sqrt(6.0), 1.0 \/ std::sqrt(6.0),\n -2.0 \/ std::sqrt(6.0)); \/\/\/\/ Entropy Minimization for Shadow Removal\n\n \/\/ p_M = cbrt(pr*pg*pb) max=1, min=1\/255\n \/\/ chi_r,g,b = log(p_r,g,b\/p_M) max=log(255), min=log(1)\n \/\/ psi_1,2 = U x chi_r,g,b psi_1:max\/min = +\/-\n \/\/ (1\/sqrt(2)*log(255)), psi_2:max\/min = +\/- (2\/sqrt(6)*log(255)) I =\n \/\/ psi_1*cos(theta)+psi_2*sin(theta) max\/min = +\/-\n \/\/ (log(255)*(1\/2+1\/sqrt(3))\n\n\/\/ double max = std::log(255.0) * (0.5 + (1.0 \/ std::sqrt(3)));\n\/\/ double min = -max;\n\n for (std::size_t i = 0; i < size; ++i) {\n const cv::Vec3b& p = src[i];\n if (p[0] == 0 || p[1] == 0 || p[2] == 0) {\n mask[i] = 1;\n \/\/ dst[i] = 128;\n dst[i] = (p[2] > p[1] || p[2] > p[0]) ? 1 : 0;\n\/\/ dst[i] = 0;\n continue;\n }\n\n cv::Vec3f c(p[0] \/ 255.0, p[1] \/ 255.0, p[2] \/ 255.0);\n\/\/ const double rho = std::pow((c[0] * c[1] * c[2]), 1.0 \/ 3);\n const double rho = LUT_rho_cbrt[p[0]][p[1]][p[2]];\n\n c \/= rho;\n c[0] = std::log(c[0]); \/\/comment logs for optimization\n c[1] = std::log(c[1]);\n c[2] = std::log(c[2]);\n const cv::Vec2f psi(c.ddot(v1), c.ddot(v2));\n dst[i] = ((psi[0] * ct + psi[1] * st) - santos_min) \/ (santos_max - santos_min); \/\/ normalize\n\n \/\/threshold values\n if (use_threshold) {\n if (dst[i] < threshold_min_max.first) {\n dst[i] = threshold_min_max.first;\n mask[i] = 2;\n } else if (dst[i] > threshold_min_max.second) {\n dst[i] = threshold_min_max.second;\n mask[i] = 3;\n }\n }\n\n dst[i] = dst[i] * 255.0; \/\/ discretize 0-255\n }\n } break;\n default:\n break;\n }\n msg::publish(output_, out);\n msg::publish(output_mask_, out_mask);\n }\n\n virtual void setup(csapex::NodeModifier& node_modifier) override\n {\n input_ = node_modifier.addInput<CvMatMessage>(\"original\");\n output_ = node_modifier.addOutput<CvMatMessage>(\"adjusted\");\n output_mask_ = node_modifier.addOutput<CvMatMessage>(\"label mask\");\n\n for (int i = 0; i < 255; i++) {\n for (int j = 0; j < 255; j++) {\n for (int k = 0; k < 255; k++) {\n LUT_rho_cbrt[i][j][k] = std::pow((i\/255.0 * j\/255.0 * k\/255.0), 1.0\/3);\n }\n }\n }\n santos_max = std::log(255.0) * (0.5 + (1.0 \/ std::sqrt(3)));\n santos_min = -santos_max;\n\n newman_min = 0.5 - std::log(255.0);\n newman_max = 0.5 + std::log(255.0);\n\/\/ ct = std::cos(M_PI);\n\/\/ st = std::sin(M_PI);\n\n }\n\n virtual void setupParameters(Parameterizable& parameters)\n {\n parameters.addParameter(param::ParameterFactory::declareRange(\"alpha\", 0.0, 1.0, 1.5, 0.001), alpha_);\n std::map<std::string, int> methods = { { \"Newman\", (int)Newman }, { \"NewmanOriginal\", (int)NewmanOriginal }, { \"Santos\", (int)Santos }, { \"SantosOriginal\", (int)SantosOriginal } };\n\n parameters.addParameter(param::ParameterFactory::declareParameterSet<int>(\"method\", methods, Newman), method_);\n\n param::Parameter::Ptr method = param::factory::declareBool(\"threshold\", param::ParameterDescription(\"Apply min\/max thresholding.\"), true);\n\n parameters.addParameter(method, std::bind(&BGRToIlluminationInvariant::submit, this));\n\n std::function<bool()> k_cond = (std::bind(¶m::Parameter::as<bool>, method.get()));\n parameters.addConditionalParameter(param::factory::declareInterval(\"threshold range\", param::ParameterDescription(\"Valid and acceptable range\"), 0, 100, 0, 100, 1), k_cond,\n std::bind(&BGRToIlluminationInvariant::submit, this));\n\n parameters.setParameter(\"threshold range\", std::pair<int, int>(5, 95));\n }\n void submit()\n {\n }\n\nprotected:\n csapex::Output* output_;\n csapex::Output* output_mask_;\n\n enum Type\n {\n Newman,\n NewmanOriginal,\n Santos,\n SantosOriginal\n };\n\n csapex::Input* input_;\n double alpha_;\n int method_;\n bool recover_bgr_;\n float LUT_rho_cbrt[256][256][256];\n double santos_min;\n double santos_max;\n double newman_min;\n double newman_max;\n\/\/ double ct;\n\/\/ double st;\n};\n} \/\/ namespace csapex\n\nCSAPEX_REGISTER_CLASS(csapex::BGRToIlluminationInvariant, csapex::Node)\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright(c) Sophist Solutions Inc. 1990-2013. All rights reserved\n *\/\n\/\/ TEST Foundation::Memory\n#include \"Stroika\/Foundation\/StroikaPreComp.h\"\n\n#include \"Stroika\/Foundation\/Containers\/Mapping.h\"\n#include \"Stroika\/Foundation\/Debug\/Assertions.h\"\n#include \"Stroika\/Foundation\/Debug\/Trace.h\"\n\n#include \"Stroika\/Foundation\/Memory\/AnyVariantValue.h\"\n#include \"Stroika\/Foundation\/Memory\/Optional.h\"\n#include \"Stroika\/Foundation\/Memory\/SharedByValue.h\"\n#include \"Stroika\/Foundation\/Memory\/VariantValue.h\"\n\n#include \"..\/TestHarness\/SimpleClass.h\"\n#include \"..\/TestHarness\/TestHarness.h\"\n\n\n\n\nusing namespace Stroika;\nusing namespace Stroika::Foundation;\nusing namespace Stroika::Foundation::Memory;\n\n\n\/\/TODO: DOES IT EVEN NEED TO BE SAID? THese tests are a bit sparse ;-)\n\nnamespace {\n void Test1_Optional ()\n {\n {\n Optional<int> x;\n VerifyTestResult (x.empty ());\n x = 1;\n VerifyTestResult (not x.empty ());\n VerifyTestResult (*x == 1);\n }\n {\n \/\/ Careful about self-assignment\n Optional<int> x;\n x = 3;\n x = max (*x, 1);\n VerifyTestResult (x == 3);\n }\n }\n void Test2_SharedByValue ()\n {\n }\n void Test3_VariantValue ()\n {\n {\n VariantValue v;\n VerifyTestResult (v.empty ());\n v = String (L\"hi\");\n VerifyTestResult (v == L\"hi\");\n }\n }\n void Test_4_Optional_Of_Mapping_Copy_Problem_ ()\n {\n using namespace Stroika::Foundation::Memory;\n using namespace Stroika::Foundation::Containers;\n Mapping<int, float> ml1, ml2;\n ml1 = ml2;\n\n Optional<Mapping<int, float>> ol1, ol2;\n if (ol2.IsPresent ()) {\n ml1 = *ol2;\n }\n ol1 = ml1;\n Optional<Mapping<int, float>> xxxx2 (ml1);\n\n \/\/ fails to compile prior to 2013-09-09\n Optional<Mapping<int, float>> xxxx1 (ol1);\n \/\/ fails to compile prior to 2013-09-09\n ol1 = ol2;\n }\n void Test_5_AnyVariantValue_ ()\n {\n {\n VerifyTestResult (AnyVariantValue ().empty ());\n VerifyTestResult (not AnyVariantValue (1).empty ());\n VerifyTestResult (not AnyVariantValue (\"1\").empty ());\n \/\/VerifyTestResult (AnyVariantValue (\"1\").GetType () == typeid (\"1\")); \/\/ not sure why this fails but not worthy worrying about yet\n VerifyTestResult (static_cast<int> (AnyVariantValue (1)) == 1);\n }\n {\n AnyVariantValue v;\n VerifyTestResult (v.empty ());\n v = 1;\n VerifyTestResult (not v.empty ());\n VerifyTestResult (v.GetType () == typeid (1));\n VerifyTestResult (static_cast<int> (v) == 1);\n v = L\"a\";\n \/\/VerifyTestResult (v.GetType () == typeid (L\"a\")); \/\/ not sure why this fails but not worthy worrying about yet\n VerifyTestResult (not v.empty ());\n v.clear ();\n VerifyTestResult (v.empty ());\n VerifyTestResult (v.GetType () == typeid (void));\n }\n {\n struct JIM {\n int a;\n };\n AnyVariantValue v;\n VerifyTestResult (v.empty ());\n v = JIM ();\n VerifyTestResult (v.GetType () == typeid (JIM));\n }\n {\n AnyVariantValue v;\n VerifyTestResult (v.empty ());\n v = 1;\n v = v;\n VerifyTestResult (v.GetType () == typeid (1));\n VerifyTestResult (static_cast<int> (v) == 1);\n v = AnyVariantValue (v);\n VerifyTestResult (v.GetType () == typeid (1));\n VerifyTestResult (static_cast<int> (v) == 1);\n }\n }\n}\n\n\nnamespace {\n\n void DoRegressionTests_ ()\n {\n Test1_Optional ();\n Test2_SharedByValue ();\n Test3_VariantValue ();\n Test_4_Optional_Of_Mapping_Copy_Problem_ ();\n Test_5_AnyVariantValue_ ();\n }\n}\n\n\n\nint main (int argc, const char* argv[])\n{\n Stroika::TestHarness::Setup ();\n Stroika::TestHarness::PrintPassOrFail (DoRegressionTests_);\n return EXIT_SUCCESS;\n}\n\n\n\n<commit_msg>Embellished AnyVariantValue test code<commit_after>\/*\n * Copyright(c) Sophist Solutions Inc. 1990-2013. All rights reserved\n *\/\n\/\/ TEST Foundation::Memory\n#include \"Stroika\/Foundation\/StroikaPreComp.h\"\n\n#include \"Stroika\/Foundation\/Containers\/Mapping.h\"\n#include \"Stroika\/Foundation\/Debug\/Assertions.h\"\n#include \"Stroika\/Foundation\/Debug\/Trace.h\"\n\n#include \"Stroika\/Foundation\/Memory\/AnyVariantValue.h\"\n#include \"Stroika\/Foundation\/Memory\/Optional.h\"\n#include \"Stroika\/Foundation\/Memory\/SharedByValue.h\"\n#include \"Stroika\/Foundation\/Memory\/VariantValue.h\"\n\n#include \"..\/TestHarness\/SimpleClass.h\"\n#include \"..\/TestHarness\/TestHarness.h\"\n\n\n\n\nusing namespace Stroika;\nusing namespace Stroika::Foundation;\nusing namespace Stroika::Foundation::Memory;\n\n\n\/\/TODO: DOES IT EVEN NEED TO BE SAID? THese tests are a bit sparse ;-)\n\nnamespace {\n void Test1_Optional ()\n {\n {\n Optional<int> x;\n VerifyTestResult (x.empty ());\n x = 1;\n VerifyTestResult (not x.empty ());\n VerifyTestResult (*x == 1);\n }\n {\n \/\/ Careful about self-assignment\n Optional<int> x;\n x = 3;\n x = max (*x, 1);\n VerifyTestResult (x == 3);\n }\n }\n void Test2_SharedByValue ()\n {\n }\n void Test3_VariantValue ()\n {\n {\n VariantValue v;\n VerifyTestResult (v.empty ());\n v = String (L\"hi\");\n VerifyTestResult (v == L\"hi\");\n }\n }\n void Test_4_Optional_Of_Mapping_Copy_Problem_ ()\n {\n using namespace Stroika::Foundation::Memory;\n using namespace Stroika::Foundation::Containers;\n Mapping<int, float> ml1, ml2;\n ml1 = ml2;\n\n Optional<Mapping<int, float>> ol1, ol2;\n if (ol2.IsPresent ()) {\n ml1 = *ol2;\n }\n ol1 = ml1;\n Optional<Mapping<int, float>> xxxx2 (ml1);\n\n \/\/ fails to compile prior to 2013-09-09\n Optional<Mapping<int, float>> xxxx1 (ol1);\n \/\/ fails to compile prior to 2013-09-09\n ol1 = ol2;\n }\n void Test_5_AnyVariantValue_ ()\n {\n {\n VerifyTestResult (AnyVariantValue ().empty ());\n VerifyTestResult (not AnyVariantValue (1).empty ());\n VerifyTestResult (not AnyVariantValue (\"1\").empty ());\n \/\/VerifyTestResult (AnyVariantValue (\"1\").GetType () == typeid (\"1\")); \/\/ not sure why this fails but not worthy worrying about yet\n VerifyTestResult (static_cast<int> (AnyVariantValue (1)) == 1);\n }\n {\n AnyVariantValue v;\n VerifyTestResult (v.empty ());\n v = 1;\n VerifyTestResult (not v.empty ());\n VerifyTestResult (v.GetType () == typeid (1));\n VerifyTestResult (static_cast<int> (v) == 1);\n v = L\"a\";\n \/\/VerifyTestResult (v.GetType () == typeid (L\"a\")); \/\/ not sure why this fails but not worthy worrying about yet\n VerifyTestResult (not v.empty ());\n v.clear ();\n VerifyTestResult (v.empty ());\n VerifyTestResult (v.GetType () == typeid (void));\n }\n {\n struct JIM {\n int a;\n };\n AnyVariantValue v;\n VerifyTestResult (v.empty ());\n v = JIM ();\n VerifyTestResult (v.GetType () == typeid (JIM));\n }\n {\n AnyVariantValue v;\n VerifyTestResult (v.empty ());\n v = 1;\n v = v;\n VerifyTestResult (v.GetType () == typeid (1));\n VerifyTestResult (static_cast<int> (v) == 1);\n v = AnyVariantValue (v);\n VerifyTestResult (v.GetType () == typeid (1));\n VerifyTestResult (static_cast<int> (v) == 1);\n }\n {\n static int nCopies = 0;\n struct Copyable {\n Copyable () {\n ++nCopies;\n }\n Copyable (const Copyable&) {\n ++nCopies;\n }\n ~Copyable () {\n --nCopies;\n }\n NO_ASSIGNMENT_OPERATOR(Copyable);\n };\n {\n AnyVariantValue v;\n VerifyTestResult (v.empty ());\n v = Copyable ();\n v = v;\n v = AnyVariantValue (AnyVariantValue (v));\n v = AnyVariantValue (AnyVariantValue (Copyable ()));\n VerifyTestResult (v.GetType () == typeid (Copyable));\n }\n VerifyTestResult (0 == nCopies);\n }\n }\n}\n\n\nnamespace {\n\n void DoRegressionTests_ ()\n {\n Test1_Optional ();\n Test2_SharedByValue ();\n Test3_VariantValue ();\n Test_4_Optional_Of_Mapping_Copy_Problem_ ();\n Test_5_AnyVariantValue_ ();\n }\n}\n\n\n\nint main (int argc, const char* argv[])\n{\n Stroika::TestHarness::Setup ();\n Stroika::TestHarness::PrintPassOrFail (DoRegressionTests_);\n return EXIT_SUCCESS;\n}\n\n\n\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: acredlin.hxx,v $\n *\n * $Revision: 1.4 $\n *\n * last change: $Author: dr $ $Date: 2002-07-30 10:45:03 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef SC_ACREDLIN_HXX\n#define SC_ACREDLIN_HXX\n\n#ifndef _MOREBTN_HXX \/\/autogen\n#include <vcl\/morebtn.hxx>\n#endif\n#ifndef _COMBOBOX_HXX \/\/autogen\n#include <vcl\/combobox.hxx>\n#endif\n#ifndef _GROUP_HXX \/\/autogen\n#include <vcl\/group.hxx>\n#endif\n\n#ifndef _HEADBAR_HXX \/\/autogen\n#include <svtools\/headbar.hxx>\n#endif\n\n#ifndef _SVTABBX_HXX \/\/autogen\n#include <svtools\/svtabbx.hxx>\n#endif\n\n\n#ifndef SC_RANGENAM_HXX\n#include \"rangenam.hxx\"\n#endif\n\n#ifndef SC_ANYREFDG_HXX\n#include \"anyrefdg.hxx\"\n#endif\n\n#ifndef _SV_LSTBOX_HXX \/\/autogen\n#include <vcl\/lstbox.hxx>\n#endif\n\n#ifndef _SVX_ACREDLIN_HXX\n#include <svx\/ctredlin.hxx>\n#endif\n\n#ifndef _SVX_SIMPTABL_HXX\n#include <svx\/simptabl.hxx>\n#endif\n\n#ifndef _SVARRAY_HXX\n#define _SVARRAY_HXX\n#include <svtools\/svarray.hxx>\n#endif\n\n#ifndef SC_CHGTRACK_HXX\n#include \"chgtrack.hxx\"\n#endif\n\n#ifndef SC_CHGVISET_HXX\n#include \"chgviset.hxx\"\n#endif\n\n#ifndef _SV_TIMER_HXX \/\/autogen\n#include <vcl\/timer.hxx>\n#endif\n\nclass ScViewData;\nclass ScDocument;\n\n#define FLT_DATE_BEFORE 0\n#define FLT_DATE_SINCE 1\n#define FLT_DATE_EQUAL 2\n#define FLT_DATE_NOTEQUAL 3\n#define FLT_DATE_BETWEEN 4\n#define FLT_DATE_SAVE 5\n\n\nclass ScViewEntryPtr\n{\nprivate:\n String* pAction;\n String* pPos;\n String* pAuthor;\n String* pDate;\n String* pComment;\n void* pData;\n\npublic:\n\n String* GetpAction() {return pAction; }\n String* GetpPos() {return pPos; }\n String* GetpAuthor() {return pAuthor; }\n String* GetpDate() {return pDate; }\n String* GetpComment() {return pComment;}\n void* GetpData() {return pData; }\n\n void SetpAction (String* pString) {pAction= pString;}\n void SetpPos (String* pString) {pPos = pString;}\n void SetpAuthor (String* pString) {pAuthor= pString;}\n void SetpDate (String* pString) {pDate = pString;}\n void SetpComment(String* pString) {pComment=pString;}\n void SetpData (void* pdata) {pData =pdata;}\n};\n\nclass ScViewEntryPtrList\n{\n ScViewEntryPtrList* pNext;\n ScViewEntryPtrList* pLast;\n\n ScViewEntryPtr* pData;\n};\n\n\nclass ScRedlinData : public RedlinData\n{\npublic:\n\n ScRedlinData();\n ~ScRedlinData();\n USHORT nTable;\n USHORT nCol;\n USHORT nRow;\n ULONG nActionNo;\n ULONG nInfo;\n BOOL bIsRejectable;\n BOOL bIsAcceptable;\n};\n\ntypedef long LExpNum;\n\n\/\/@ Expand-Entrys nicht eindeutig, daher gestrichen\n\/\/DECLARE_TABLE( ScChgTrackExps, LExpNum)\n\/\/==================================================================\n\nclass ScAcceptChgDlg : public SfxModelessDialog\n{\nprivate:\n\n Timer aSelectionTimer;\n Timer aReOpenTimer;\n SvxAcceptChgCtr aAcceptChgCtr;\n ScViewData* pViewData;\n ScDocument* pDoc;\n ScRangeName aLocalRangeName;\n Selection theCurSel;\n SvxTPFilter* pTPFilter;\n SvxTPView* pTPView;\n SvxRedlinTable* pTheView;\n Size MinSize;\n ScRangeList aRangeList;\n ScChangeViewSettings aChangeViewSet;\n String aStrInsertCols;\n String aStrInsertRows;\n String aStrInsertTabs;\n String aStrDeleteCols;\n String aStrDeleteRows;\n String aStrDeleteTabs;\n String aStrMove;\n String aStrContent;\n String aStrReject;\n String aUnknown;\n String aStrAllAccepted;\n String aStrAllRejected;\n String aStrNoEntry;\n String aStrContentWithChild;\n String aStrChildContent;\n String aStrChildOrgContent;\n String aStrEmpty;\n ULONG nAcceptCount;\n ULONG nRejectCount;\n BOOL bAcceptEnableFlag;\n BOOL bRejectEnableFlag;\n BOOL bNeedsUpdate;\n BOOL bIgnoreMsg;\n BOOL bNoSelection;\n BOOL bHasFilterEntry;\n BOOL bUseColor;\n \/\/ScChgTrackExps aExpandArray;\n\n void Init();\n void InitFilter();\n void SetMyStaticData();\n\n DECL_LINK( FilterHandle, SvxTPFilter* );\n DECL_LINK( RefHandle, SvxTPFilter* );\n DECL_LINK( FilterModified, SvxTPFilter* );\n DECL_LINK( MinSizeHandle, SvxAcceptChgCtr*);\n DECL_LINK( RejectHandle, SvxTPView*);\n DECL_LINK( AcceptHandle, SvxTPView*);\n DECL_LINK( RejectAllHandle, SvxTPView*);\n DECL_LINK( AcceptAllHandle, SvxTPView*);\n DECL_LINK( ExpandingHandle, SvxRedlinTable*);\n DECL_LINK( SelectHandle, SvxRedlinTable*);\n DECL_LINK( RefInfoHandle, String*);\n\n DECL_LINK( UpdateSelectionHdl, Timer*);\n DECL_LINK( ChgTrackModHdl, ScChangeTrack*);\n DECL_LINK( CommandHdl, Control*);\n DECL_LINK( ReOpenTimerHdl, Timer*);\n DECL_LINK( ColCompareHdl, SvSortData*);\n\n\n\nprotected:\n\n virtual void Resize();\n virtual BOOL Close();\n\n void RejectFiltered();\n void AcceptFiltered();\n\n BOOL IsValidAction(const ScChangeAction* pScChangeAction);\n\n String* MakeTypeString(ScChangeActionType eType);\n\n SvLBoxEntry* InsertChangeAction(const ScChangeAction* pScChangeAction,ScChangeActionState eState,\n SvLBoxEntry* pParent=NULL,BOOL bDelMaster=FALSE,\n BOOL bDisabled=FALSE,ULONG nPos=LIST_APPEND);\n\n SvLBoxEntry* InsertFilteredAction(const ScChangeAction* pScChangeAction,ScChangeActionState eState,\n SvLBoxEntry* pParent=NULL,BOOL bDelMaster=FALSE,\n BOOL bDisabled=FALSE,ULONG nPos=LIST_APPEND);\n\n\n SvLBoxEntry* InsertChangeActionContent(const ScChangeActionContent* pScChangeAction,\n SvLBoxEntry* pParent,ULONG nSpecial);\n\n void GetDependents( const ScChangeAction* pScChangeAction,\n ScChangeActionTable& aActionTable,\n SvLBoxEntry* pEntry);\n\n BOOL InsertContentChilds(ScChangeActionTable* pActionTable,SvLBoxEntry* pParent);\n\n BOOL InsertAcceptedORejected(SvLBoxEntry* pParent);\n\n BOOL InsertDeletedChilds(const ScChangeAction *pChangeAction, ScChangeActionTable* pActionTable,\n SvLBoxEntry* pParent);\n\n BOOL InsertChilds(ScChangeActionTable* pActionTable,SvLBoxEntry* pParent);\n\n void AppendChanges(ScChangeTrack* pChanges,ULONG nStartAction, ULONG nEndAction,\n ULONG nPos=LIST_APPEND);\n\n void RemoveEntrys(ULONG nStartAction,ULONG nEndAction);\n void UpdateEntrys(ScChangeTrack* pChgTrack, ULONG nStartAction,ULONG nEndAction);\n\n void UpdateView();\n void ClearView();\n\n BOOL Expand(ScChangeTrack* pChanges,const ScChangeAction* pScChangeAction,\n SvLBoxEntry* pEntry, BOOL bFilter=FALSE);\n\npublic:\n ScAcceptChgDlg( SfxBindings* pB, SfxChildWindow* pCW, Window* pParent,\n ScViewData* ptrViewData);\n\n ~ScAcceptChgDlg();\n\n void ReInit(ScViewData* ptrViewData);\n\n virtual long PreNotify( NotifyEvent& rNEvt );\n\n void Initialize (SfxChildWinInfo* pInfo);\n virtual void FillInfo(SfxChildWinInfo&) const;\n\n};\n\n\n#endif \/\/ SC_NAMEDLG_HXX\n\n<commit_msg>INTEGRATION: CWS rowlimit (1.4.308); FILE MERGED 2004\/01\/13 20:04:07 er 1.4.308.1: #i1967# SCCOL,SCROW,SCTAB replace USHORT; SCsCOL,SCsROW,SCsTAB replace short<commit_after>\/*************************************************************************\n *\n * $RCSfile: acredlin.hxx,v $\n *\n * $Revision: 1.5 $\n *\n * last change: $Author: obo $ $Date: 2004-06-04 11:29:27 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef SC_ACREDLIN_HXX\n#define SC_ACREDLIN_HXX\n\n#ifndef _MOREBTN_HXX \/\/autogen\n#include <vcl\/morebtn.hxx>\n#endif\n#ifndef _COMBOBOX_HXX \/\/autogen\n#include <vcl\/combobox.hxx>\n#endif\n#ifndef _GROUP_HXX \/\/autogen\n#include <vcl\/group.hxx>\n#endif\n\n#ifndef _HEADBAR_HXX \/\/autogen\n#include <svtools\/headbar.hxx>\n#endif\n\n#ifndef _SVTABBX_HXX \/\/autogen\n#include <svtools\/svtabbx.hxx>\n#endif\n\n\n#ifndef SC_RANGENAM_HXX\n#include \"rangenam.hxx\"\n#endif\n\n#ifndef SC_ANYREFDG_HXX\n#include \"anyrefdg.hxx\"\n#endif\n\n#ifndef _SV_LSTBOX_HXX \/\/autogen\n#include <vcl\/lstbox.hxx>\n#endif\n\n#ifndef _SVX_ACREDLIN_HXX\n#include <svx\/ctredlin.hxx>\n#endif\n\n#ifndef _SVX_SIMPTABL_HXX\n#include <svx\/simptabl.hxx>\n#endif\n\n#ifndef _SVARRAY_HXX\n#define _SVARRAY_HXX\n#include <svtools\/svarray.hxx>\n#endif\n\n#ifndef SC_CHGTRACK_HXX\n#include \"chgtrack.hxx\"\n#endif\n\n#ifndef SC_CHGVISET_HXX\n#include \"chgviset.hxx\"\n#endif\n\n#ifndef _SV_TIMER_HXX \/\/autogen\n#include <vcl\/timer.hxx>\n#endif\n\nclass ScViewData;\nclass ScDocument;\n\n#define FLT_DATE_BEFORE 0\n#define FLT_DATE_SINCE 1\n#define FLT_DATE_EQUAL 2\n#define FLT_DATE_NOTEQUAL 3\n#define FLT_DATE_BETWEEN 4\n#define FLT_DATE_SAVE 5\n\n\nclass ScViewEntryPtr\n{\nprivate:\n String* pAction;\n String* pPos;\n String* pAuthor;\n String* pDate;\n String* pComment;\n void* pData;\n\npublic:\n\n String* GetpAction() {return pAction; }\n String* GetpPos() {return pPos; }\n String* GetpAuthor() {return pAuthor; }\n String* GetpDate() {return pDate; }\n String* GetpComment() {return pComment;}\n void* GetpData() {return pData; }\n\n void SetpAction (String* pString) {pAction= pString;}\n void SetpPos (String* pString) {pPos = pString;}\n void SetpAuthor (String* pString) {pAuthor= pString;}\n void SetpDate (String* pString) {pDate = pString;}\n void SetpComment(String* pString) {pComment=pString;}\n void SetpData (void* pdata) {pData =pdata;}\n};\n\nclass ScViewEntryPtrList\n{\n ScViewEntryPtrList* pNext;\n ScViewEntryPtrList* pLast;\n\n ScViewEntryPtr* pData;\n};\n\n\nclass ScRedlinData : public RedlinData\n{\npublic:\n\n ScRedlinData();\n ~ScRedlinData();\n SCTAB nTable;\n SCCOL nCol;\n SCROW nRow;\n ULONG nActionNo;\n ULONG nInfo;\n BOOL bIsRejectable;\n BOOL bIsAcceptable;\n};\n\ntypedef long LExpNum;\n\n\/\/@ Expand-Entrys nicht eindeutig, daher gestrichen\n\/\/DECLARE_TABLE( ScChgTrackExps, LExpNum)\n\/\/==================================================================\n\nclass ScAcceptChgDlg : public SfxModelessDialog\n{\nprivate:\n\n Timer aSelectionTimer;\n Timer aReOpenTimer;\n SvxAcceptChgCtr aAcceptChgCtr;\n ScViewData* pViewData;\n ScDocument* pDoc;\n ScRangeName aLocalRangeName;\n Selection theCurSel;\n SvxTPFilter* pTPFilter;\n SvxTPView* pTPView;\n SvxRedlinTable* pTheView;\n Size MinSize;\n ScRangeList aRangeList;\n ScChangeViewSettings aChangeViewSet;\n String aStrInsertCols;\n String aStrInsertRows;\n String aStrInsertTabs;\n String aStrDeleteCols;\n String aStrDeleteRows;\n String aStrDeleteTabs;\n String aStrMove;\n String aStrContent;\n String aStrReject;\n String aUnknown;\n String aStrAllAccepted;\n String aStrAllRejected;\n String aStrNoEntry;\n String aStrContentWithChild;\n String aStrChildContent;\n String aStrChildOrgContent;\n String aStrEmpty;\n ULONG nAcceptCount;\n ULONG nRejectCount;\n BOOL bAcceptEnableFlag;\n BOOL bRejectEnableFlag;\n BOOL bNeedsUpdate;\n BOOL bIgnoreMsg;\n BOOL bNoSelection;\n BOOL bHasFilterEntry;\n BOOL bUseColor;\n \/\/ScChgTrackExps aExpandArray;\n\n void Init();\n void InitFilter();\n void SetMyStaticData();\n\n DECL_LINK( FilterHandle, SvxTPFilter* );\n DECL_LINK( RefHandle, SvxTPFilter* );\n DECL_LINK( FilterModified, SvxTPFilter* );\n DECL_LINK( MinSizeHandle, SvxAcceptChgCtr*);\n DECL_LINK( RejectHandle, SvxTPView*);\n DECL_LINK( AcceptHandle, SvxTPView*);\n DECL_LINK( RejectAllHandle, SvxTPView*);\n DECL_LINK( AcceptAllHandle, SvxTPView*);\n DECL_LINK( ExpandingHandle, SvxRedlinTable*);\n DECL_LINK( SelectHandle, SvxRedlinTable*);\n DECL_LINK( RefInfoHandle, String*);\n\n DECL_LINK( UpdateSelectionHdl, Timer*);\n DECL_LINK( ChgTrackModHdl, ScChangeTrack*);\n DECL_LINK( CommandHdl, Control*);\n DECL_LINK( ReOpenTimerHdl, Timer*);\n DECL_LINK( ColCompareHdl, SvSortData*);\n\n\n\nprotected:\n\n virtual void Resize();\n virtual BOOL Close();\n\n void RejectFiltered();\n void AcceptFiltered();\n\n BOOL IsValidAction(const ScChangeAction* pScChangeAction);\n\n String* MakeTypeString(ScChangeActionType eType);\n\n SvLBoxEntry* InsertChangeAction(const ScChangeAction* pScChangeAction,ScChangeActionState eState,\n SvLBoxEntry* pParent=NULL,BOOL bDelMaster=FALSE,\n BOOL bDisabled=FALSE,ULONG nPos=LIST_APPEND);\n\n SvLBoxEntry* InsertFilteredAction(const ScChangeAction* pScChangeAction,ScChangeActionState eState,\n SvLBoxEntry* pParent=NULL,BOOL bDelMaster=FALSE,\n BOOL bDisabled=FALSE,ULONG nPos=LIST_APPEND);\n\n\n SvLBoxEntry* InsertChangeActionContent(const ScChangeActionContent* pScChangeAction,\n SvLBoxEntry* pParent,ULONG nSpecial);\n\n void GetDependents( const ScChangeAction* pScChangeAction,\n ScChangeActionTable& aActionTable,\n SvLBoxEntry* pEntry);\n\n BOOL InsertContentChilds(ScChangeActionTable* pActionTable,SvLBoxEntry* pParent);\n\n BOOL InsertAcceptedORejected(SvLBoxEntry* pParent);\n\n BOOL InsertDeletedChilds(const ScChangeAction *pChangeAction, ScChangeActionTable* pActionTable,\n SvLBoxEntry* pParent);\n\n BOOL InsertChilds(ScChangeActionTable* pActionTable,SvLBoxEntry* pParent);\n\n void AppendChanges(ScChangeTrack* pChanges,ULONG nStartAction, ULONG nEndAction,\n ULONG nPos=LIST_APPEND);\n\n void RemoveEntrys(ULONG nStartAction,ULONG nEndAction);\n void UpdateEntrys(ScChangeTrack* pChgTrack, ULONG nStartAction,ULONG nEndAction);\n\n void UpdateView();\n void ClearView();\n\n BOOL Expand(ScChangeTrack* pChanges,const ScChangeAction* pScChangeAction,\n SvLBoxEntry* pEntry, BOOL bFilter=FALSE);\n\npublic:\n ScAcceptChgDlg( SfxBindings* pB, SfxChildWindow* pCW, Window* pParent,\n ScViewData* ptrViewData);\n\n ~ScAcceptChgDlg();\n\n void ReInit(ScViewData* ptrViewData);\n\n virtual long PreNotify( NotifyEvent& rNEvt );\n\n void Initialize (SfxChildWinInfo* pInfo);\n virtual void FillInfo(SfxChildWinInfo&) const;\n\n};\n\n\n#endif \/\/ SC_NAMEDLG_HXX\n\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2008 by Sun Microsystems, Inc.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: dbnamdlg.hxx,v $\n * $Revision: 1.4 $\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * <http:\/\/www.openoffice.org\/license.html>\n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n#ifndef SC_DBNAMDLG_HXX\n#define SC_DBNAMDLG_HXX\n\n#ifndef _COMBOBOX_HXX \/\/autogen\n#include <vcl\/combobox.hxx>\n#endif\n\n#ifndef _FIXED_HXX \/\/autogen\n#include <vcl\/fixed.hxx>\n#endif\n\n#ifndef _MOREBTN_HXX \/\/autogen\n#include <vcl\/morebtn.hxx>\n#endif\n#include \"anyrefdg.hxx\"\n#include \"dbcolect.hxx\"\n#include \"expftext.hxx\"\n\nclass ScViewData;\nclass ScDocument;\n\n\n\/\/============================================================================\n\nclass ScDbNameDlg : public ScAnyRefDlg\n{\npublic:\n ScDbNameDlg( SfxBindings* pB, SfxChildWindow* pCW, Window* pParent,\n ScViewData* ptrViewData );\n ~ScDbNameDlg();\n\n virtual void SetReference( const ScRange& rRef, ScDocument* pDoc );\n\n virtual BOOL IsRefInputMode() const;\n virtual void SetActive();\n virtual BOOL Close();\n\nprivate:\n FixedLine aFlName;\n ComboBox aEdName;\n\n FixedLine aFlAssign;\n ScRefEdit aEdAssign;\n ScRefButton aRbAssign;\n\n FixedLine aFlOptions;\n CheckBox aBtnHeader;\n CheckBox aBtnDoSize;\n CheckBox aBtnKeepFmt;\n CheckBox aBtnStripData;\n ScExpandedFixedText aFTSource; \/\/@18.09.97 erweiterter FixedText\n FixedText aFTOperations;\n\n OKButton aBtnOk;\n CancelButton aBtnCancel;\n HelpButton aBtnHelp;\n PushButton aBtnAdd;\n PushButton aBtnRemove;\n MoreButton aBtnMore;\n\n BOOL bSaved;\n\n\n const String aStrAdd; \/\/ \"Hinzufuegen\"\n const String aStrModify; \/\/ \"Aendern\"\n const String aStrNoName; \/\/ \"unbenannt\"\n const String aStrInvalid;\n\n String aStrSource;\n String aStrOperations;\n\n ScViewData* pViewData;\n ScDocument* pDoc;\n BOOL bRefInputMode;\n\n ScDBCollection aLocalDbCol;\n ScRange theCurArea;\n List aRemoveList;\n\n#ifdef _DBNAMDLG_CXX\nprivate:\n void Init();\n void UpdateNames();\n void UpdateDBData( const String& rStrName );\n void SetInfoStrings( const ScDBData* pDBData );\n\n DECL_LINK( CancelBtnHdl, void * );\n DECL_LINK( OkBtnHdl, void * );\n DECL_LINK( AddBtnHdl, void * );\n DECL_LINK( RemoveBtnHdl, void * );\n DECL_LINK( NameModifyHdl, void * );\n DECL_LINK( AssModifyHdl, void * );\n#endif\n};\n\n\n\n#endif \/\/ SC_DBNAMDLG_HXX\n\n<commit_msg>INTEGRATION: CWS koheiformula01 (1.3.684); FILE MERGED 2008\/04\/23 15:07:34 kohei 1.3.684.2: RESYNC: (1.3-1.4); FILE MERGED 2008\/03\/20 04:38:05 kohei 1.3.684.1: use grammar in the database range dialog.<commit_after>\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2008 by Sun Microsystems, Inc.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: dbnamdlg.hxx,v $\n * $Revision: 1.5 $\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * <http:\/\/www.openoffice.org\/license.html>\n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n#ifndef SC_DBNAMDLG_HXX\n#define SC_DBNAMDLG_HXX\n\n#ifndef _COMBOBOX_HXX \/\/autogen\n#include <vcl\/combobox.hxx>\n#endif\n\n#ifndef _FIXED_HXX \/\/autogen\n#include <vcl\/fixed.hxx>\n#endif\n\n#ifndef _MOREBTN_HXX \/\/autogen\n#include <vcl\/morebtn.hxx>\n#endif\n#include \"anyrefdg.hxx\"\n#include \"dbcolect.hxx\"\n#include \"expftext.hxx\"\n\nclass ScViewData;\nclass ScDocument;\n\n\n\/\/============================================================================\n\nclass ScDbNameDlg : public ScAnyRefDlg\n{\npublic:\n ScDbNameDlg( SfxBindings* pB, SfxChildWindow* pCW, Window* pParent,\n ScViewData* ptrViewData );\n ~ScDbNameDlg();\n\n virtual void SetReference( const ScRange& rRef, ScDocument* pDoc );\n\n virtual BOOL IsRefInputMode() const;\n virtual void SetActive();\n virtual BOOL Close();\n\nprivate:\n FixedLine aFlName;\n ComboBox aEdName;\n\n FixedLine aFlAssign;\n ScRefEdit aEdAssign;\n ScRefButton aRbAssign;\n\n FixedLine aFlOptions;\n CheckBox aBtnHeader;\n CheckBox aBtnDoSize;\n CheckBox aBtnKeepFmt;\n CheckBox aBtnStripData;\n ScExpandedFixedText aFTSource; \/\/@18.09.97 erweiterter FixedText\n FixedText aFTOperations;\n\n OKButton aBtnOk;\n CancelButton aBtnCancel;\n HelpButton aBtnHelp;\n PushButton aBtnAdd;\n PushButton aBtnRemove;\n MoreButton aBtnMore;\n\n BOOL bSaved;\n\n\n const String aStrAdd; \/\/ \"Hinzufuegen\"\n const String aStrModify; \/\/ \"Aendern\"\n const String aStrNoName; \/\/ \"unbenannt\"\n const String aStrInvalid;\n\n String aStrSource;\n String aStrOperations;\n\n ScViewData* pViewData;\n ScDocument* pDoc;\n BOOL bRefInputMode;\n ScAddress::Details aAddrDetails;\n\n ScDBCollection aLocalDbCol;\n ScRange theCurArea;\n List aRemoveList;\n\n#ifdef _DBNAMDLG_CXX\nprivate:\n void Init();\n void UpdateNames();\n void UpdateDBData( const String& rStrName );\n void SetInfoStrings( const ScDBData* pDBData );\n\n DECL_LINK( CancelBtnHdl, void * );\n DECL_LINK( OkBtnHdl, void * );\n DECL_LINK( AddBtnHdl, void * );\n DECL_LINK( RemoveBtnHdl, void * );\n DECL_LINK( NameModifyHdl, void * );\n DECL_LINK( AssModifyHdl, void * );\n#endif\n};\n\n\n\n#endif \/\/ SC_DBNAMDLG_HXX\n\n<|endoftext|>"} {"text":"<commit_before>\/**\n * \\file arpbnf_search.cc\n *\n *\n *\n * \\author Ethan Burns\n * \\date 2008-10-29\n *\/\n\n#include <assert.h>\n#include <math.h>\n\n#include <limits>\n#include <vector>\n#include <algorithm>\n\n#include \"arpbnf_search.h\"\n#include \"search.h\"\n#include \"state.h\"\n#include \"util\/timer.h\"\n#include \"util\/sync_solution_stream.h\"\n\nusing namespace std;\nusing namespace ARPBNF;\n\nARPBNFSearch::ARPBNFThread::ARPBNFThread(NBlockGraph *graph, ARPBNFSearch *search)\n\t: graph(graph), search(search), set_hot(false)\n{\n}\n\n\nARPBNFSearch::ARPBNFThread::~ARPBNFThread(void) {}\n\n\/**\n * Run the search thread.\n *\/\nvoid ARPBNFSearch::ARPBNFThread::run(void)\n{\n\tvector<State *> *path;\n\tNBlock *n = NULL;\n\n\tdo {\n\tnext:\n\t\tif (graph->is_done())\n\t\t\tbreak;\n\t\tn = graph->next_nblock(n, !set_hot);\n\t\tset_hot = false;\n\t\tif (n) {\n\t\t\texpansions = 0;\n\t\t\tpath = search_nblock(n);\n\n\t\t\tif (path) {\n\t\t\t\tif (search->set_path(path) && !search->final_weight) {\n\t\t\t\t\tgraph->free_nblock(n);\n\t\t\t\t\tn = NULL;\n\t\t\t\t\tgraph->call_for_resort(search->final_weight, search);\n\t\t\t\t\tgoto next;\n\t\t\t\t}\n\t\t\t}\n\t\t} else if (!search->final_weight) {\n\t\t\tgraph->call_for_resort(search->final_weight, search);\n#if !defined(NDEBUG)\n\t\t\tcout << \"No solution found at weight \"\n\t\t\t << search->weights->at(search->next_weight - 1)\n\t\t\t << endl;\n#endif\t\/\/ !NDEBUG\n\t\t\tgoto next;\n\t\t} else {\n#if !defined(NDEBUG)\n\t\t\tcout << \"Done\" << endl;\n#endif\t\/\/ !NDEBUG\n\t\t}\n\t} while (n && !graph->is_done());\n\n\tgraph->set_done();\n}\n\n\/**\n * Search a single NBlock.\n *\/\nvector<State *> *ARPBNFSearch::ARPBNFThread::search_nblock(NBlock *n)\n{\n\tvector<State *> *path = NULL;\n\tOpenList *open = &n->open;\n\n\twhile (!open->empty() && !should_switch(n) && !graph->needs_resort()) {\n\n\t\tif (n->open.peek()->get_f_prime() > search->bound.read())\n\t\t\treturn NULL;\n\n\t\tState *s = open->take();\n\n#if !defined(NDEBUG)\n\t\tState *dup = n->closed.lookup(s);\n\t\tassert (!dup || dup == s);\n#endif\t\/\/ !NDEBUG\n\n\t\tif (s->get_f() >= search->bound.read())\n\t\t\tcontinue;\n\n\t\tif (s->is_goal()) {\n\t\t\tpath = s->get_path();\n\t\t\tbreak;\n\t\t}\n\n\t\texpansions += 1;\n\n\t\tvector<State *> *children = search->expand(s);\n\t\tvector<State *>::iterator iter;\n\n \t\tfor (iter = children->begin(); iter != children->end(); iter++) {\n\t\t\tState *ch = *iter;\n\t\t\tif (ch->get_f() >= search->bound.read()) {\n\t\t\t\tdelete ch;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tvector<State *> *path = process_child(ch);\n\t\t\tif (path) {\n\t\t\t\tdelete children;\n\t\t\t\treturn path;\n\t\t\t}\n\t\t}\n\t\tdelete children;\n\t}\n\n\treturn path;\n}\n\n\/**\n * Process a child state.\n *\n * \\return A path if the child was a goal state... maybe we can prune\n * more on this.\n *\/\nvector<State *> *ARPBNFSearch::ARPBNFThread::process_child(State *ch)\n{\n\tunsigned int block = search->project->project(ch);\n\tNBlock *cblock = graph->get_nblock(block);\n\tPQOpenList<State::PQOpsFPrime> *copen = &cblock->open;\n\tClosedList *cclosed = &cblock->closed;\n\tInconsList *cincons = &cblock->incons;\n\tState *dup = cclosed->lookup(ch);\n\n\tif (dup) {\n\t\tif (dup->get_g() > ch->get_g()) {\n\t\t\tdup->update(ch->get_parent(), ch->get_c(), ch->get_g());\n\t\t\tassert(!dup->is_incons() || !dup->is_open());\n\t\t\tif (dup->is_open()) {\n\t\t\t\tcopen->see_update(dup);\n\t\t\t} else {\n\t\t\t\t\/\/ Since we aren't searching in\n\t\t\t\t\/\/ strict-f' order, when the weight is\n\t\t\t\t\/\/ 1.0 we must re-open these\n\t\t\t\t\/\/ inconsistent states.\n\t\t\t\tif (search->final_weight)\n\t\t\t\t\tcopen->add(dup);\n\t\t\t\telse if (!dup->is_incons())\n\t\t\t\t\tcincons->add(dup);\n#if !defined(NDEBUG)\n\t\t\t\telse\n\t\t\t\t\tassert(cincons->lookup(dup) == dup);\n#endif \/\/ !NDEBUG\n\t\t\t}\n\t\t}\n\t\tdelete ch;\n\t} else {\n\t\tcclosed->add(ch);\n\t\tif (ch->is_goal())\n\t\t\treturn ch->get_path();\n\t\tcopen->add(ch);\n\t}\n\n\treturn NULL;\n}\n\n\n\/**\n * Test the graph to see if we should switch to a new NBlock.\n * \\param n The current NBlock.\n *\n * \\note We should make this more complex... we should also check our\n * successor NBlocks.\n *\/\nbool ARPBNFSearch::ARPBNFThread::should_switch(NBlock *n)\n{\n\tbool ret;\n\n\tif (expansions < search->min_expansions)\n\t\treturn false;\n\n\texpansions = 0;\n\n\tfp_type free = graph->best_val();\n\tfp_type cur = n->open.get_best_val();\n\tNBlock *best_scope = graph->best_in_scope(n);\n\n\tif (best_scope) {\n\t\tfp_type scope = best_scope->open.get_best_val();\n\n\t\tret = free < cur || scope < cur;\n\t\tif (!ret) {\n\t\t\tgraph->wont_release(n);\n\t\t} else if (scope < free) {\n\t\t\tgraph->set_hot(best_scope);\n\t\t\tset_hot = true;\n\t\t}\n\t} else {\n\t\tret = free < cur;\n\t}\n\n\treturn ret;\n}\n\n\n\/*****************************************************************************\/\n\/*****************************************************************************\/\n\n\nARPBNFSearch::ARPBNFSearch(unsigned int n_threads,\n\t\t\t unsigned int min_e,\n\t\t\t vector<double> *w)\n\t: n_threads(n_threads),\n\t project(NULL),\n\t bound(fp_infinity),\n\t graph(NULL),\n\t min_expansions(min_e),\n\t weights(w),\n\t next_weight(1),\n\t domain(NULL),\n\t final_weight(false)\n{\n\tpthread_mutex_init(&wmutex, NULL);\n}\n\n\nARPBNFSearch::~ARPBNFSearch(void)\n{\n\tif (graph)\n\t\tdelete graph;\n}\n\n\nvector<State *> *ARPBNFSearch::search(Timer *timer, State *initial)\n{\n\tsolutions = new SyncSolutionStream(timer, 0.0001);\n\tdomain = initial->get_domain();\n\tproject = domain->get_projection();\n\n\tvector<ARPBNFSearch::ARPBNFThread*> threads;\n\tvector<ARPBNFSearch::ARPBNFThread*>::iterator iter;\n\n\tgraph = new NBlockGraph(project, initial, &bound);\n\n\tif (domain->get_heuristic()->get_weight() == fp_one)\n\t\tfinal_weight = true;\n\tfinal_sol_weight = domain->get_heuristic()->get_weight();\n\n\tfor (unsigned int i = 0; i < n_threads; i += 1) {\n\t\tARPBNFThread *t = new ARPBNFThread(graph, this);\n\t\tthreads.push_back(t);\n\t\tt->start();\n\t}\n\n\tfor (iter = threads.begin(); iter != threads.end(); iter++) {\n\t\t(*iter)->join();\n\t\tdelete *iter;\n\t}\n\n\treturn solutions->get_best_path();\n}\n\nvoid ARPBNFSearch::move_to_next_weight(void)\n{\n\tif (next_weight < weights->size())\n\t\tfinal_sol_weight = weights->at(next_weight);\n\n\tif (weights->at(next_weight - 1) != 1.0) {\n\t\tdouble nw = 1.0;\n\t\tif (next_weight < weights->size()) {\n\t\t\tnw = weights->at(next_weight);\n\t\t\tnext_weight += 1;\n\t\t} else {\n\t\t\tcerr << \"Final weight is not 1.0, using 1.0\" << endl;\n\t\t}\n\n\t\tdomain->get_heuristic()->set_weight(nw);\n\t\tif (nw == 1.0 || next_weight == weights->size())\n\t\t\tfinal_weight = true;\n\t}\n}\n\n\/**\n * Set an incumbant solution.\n *\n * If this function returns true than the calling thread must call for\n * a resort.\n *\/\nbool ARPBNFSearch::set_path(vector<State *> *p)\n{\n\tassert(solutions);\n\n\tpthread_mutex_lock(&wmutex);\n\n\tif (bound.read() <= p->at(0)->get_g()) {\n\t\tpthread_mutex_unlock(&wmutex);\n\t\treturn false;\n\t}\n\n\tsolutions->see_solution(p, get_generated(), get_expanded());\n\tbound.set(p->at(0)->get_g());\n\tgraph->new_bound();\n\n#if !defined(NDEBUG)\n\tcout << \"Solution of cost \" << p->at(0)->get_g() \/ fp_one\n\t << \" found at weight \" << weights->at(next_weight - 1)\n\t << endl;\n#endif\t\/\/ !NDEBUG\n\n\tpthread_mutex_unlock(&wmutex);\n\n\treturn true;\n}\n\n\/**\n * Output extra \"key: value\" pairs.\n * keys should not have spaces in their names!\n *\/\nvoid ARPBNFSearch::output_stats(void)\n{\n\tcout << \"total-nblocks: \" << project->get_num_nblocks() << endl;\n\tcout << \"created-nblocks: \" << graph->get_ncreated_nblocks() << endl;\n\tcout << \"final-sol-weight: \" << final_sol_weight << endl;\n\n\tif (solutions)\n\t\tsolutions->output(cout);\n}\n<commit_msg>Turn off some debug output.<commit_after>\/**\n * \\file arpbnf_search.cc\n *\n *\n *\n * \\author Ethan Burns\n * \\date 2008-10-29\n *\/\n\n#include <assert.h>\n#include <math.h>\n\n#include <limits>\n#include <vector>\n#include <algorithm>\n\n#include \"arpbnf_search.h\"\n#include \"search.h\"\n#include \"state.h\"\n#include \"util\/timer.h\"\n#include \"util\/sync_solution_stream.h\"\n\nusing namespace std;\nusing namespace ARPBNF;\n\nARPBNFSearch::ARPBNFThread::ARPBNFThread(NBlockGraph *graph, ARPBNFSearch *search)\n\t: graph(graph), search(search), set_hot(false)\n{\n}\n\n\nARPBNFSearch::ARPBNFThread::~ARPBNFThread(void) {}\n\n\/**\n * Run the search thread.\n *\/\nvoid ARPBNFSearch::ARPBNFThread::run(void)\n{\n\tvector<State *> *path;\n\tNBlock *n = NULL;\n\n\tdo {\n\tnext:\n\t\tif (graph->is_done())\n\t\t\tbreak;\n\t\tn = graph->next_nblock(n, !set_hot);\n\t\tset_hot = false;\n\t\tif (n) {\n\t\t\texpansions = 0;\n\t\t\tpath = search_nblock(n);\n\n\t\t\tif (path) {\n\t\t\t\tif (search->set_path(path) && !search->final_weight) {\n\t\t\t\t\tgraph->free_nblock(n);\n\t\t\t\t\tn = NULL;\n\t\t\t\t\tgraph->call_for_resort(search->final_weight, search);\n\t\t\t\t\tgoto next;\n\t\t\t\t}\n\t\t\t}\n\t\t} else if (!search->final_weight) {\n\t\t\tgraph->call_for_resort(search->final_weight, search);\n#if !defined(NDEBUG) && 0\n\t\t\tcout << \"No solution found at weight \"\n\t\t\t << search->weights->at(search->next_weight - 1)\n\t\t\t << endl;\n#endif\t\/\/ !NDEBUG\n\t\t\tgoto next;\n\t\t} else {\n#if !defined(NDEBUG) && 0\n\t\t\tcout << \"Done\" << endl;\n#endif\t\/\/ !NDEBUG\n\t\t}\n\t} while (n && !graph->is_done());\n\n\tgraph->set_done();\n}\n\n\/**\n * Search a single NBlock.\n *\/\nvector<State *> *ARPBNFSearch::ARPBNFThread::search_nblock(NBlock *n)\n{\n\tvector<State *> *path = NULL;\n\tOpenList *open = &n->open;\n\n\twhile (!open->empty() && !should_switch(n) && !graph->needs_resort()) {\n\n\t\tif (n->open.peek()->get_f_prime() > search->bound.read())\n\t\t\treturn NULL;\n\n\t\tState *s = open->take();\n\n#if !defined(NDEBUG)\n\t\tState *dup = n->closed.lookup(s);\n\t\tassert (!dup || dup == s);\n#endif\t\/\/ !NDEBUG\n\n\t\tif (s->get_f() >= search->bound.read())\n\t\t\tcontinue;\n\n\t\tif (s->is_goal()) {\n\t\t\tpath = s->get_path();\n\t\t\tbreak;\n\t\t}\n\n\t\texpansions += 1;\n\n\t\tvector<State *> *children = search->expand(s);\n\t\tvector<State *>::iterator iter;\n\n \t\tfor (iter = children->begin(); iter != children->end(); iter++) {\n\t\t\tState *ch = *iter;\n\t\t\tif (ch->get_f() >= search->bound.read()) {\n\t\t\t\tdelete ch;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tvector<State *> *path = process_child(ch);\n\t\t\tif (path) {\n\t\t\t\tdelete children;\n\t\t\t\treturn path;\n\t\t\t}\n\t\t}\n\t\tdelete children;\n\t}\n\n\treturn path;\n}\n\n\/**\n * Process a child state.\n *\n * \\return A path if the child was a goal state... maybe we can prune\n * more on this.\n *\/\nvector<State *> *ARPBNFSearch::ARPBNFThread::process_child(State *ch)\n{\n\tunsigned int block = search->project->project(ch);\n\tNBlock *cblock = graph->get_nblock(block);\n\tPQOpenList<State::PQOpsFPrime> *copen = &cblock->open;\n\tClosedList *cclosed = &cblock->closed;\n\tInconsList *cincons = &cblock->incons;\n\tState *dup = cclosed->lookup(ch);\n\n\tif (dup) {\n\t\tif (dup->get_g() > ch->get_g()) {\n\t\t\tdup->update(ch->get_parent(), ch->get_c(), ch->get_g());\n\t\t\tassert(!dup->is_incons() || !dup->is_open());\n\t\t\tif (dup->is_open()) {\n\t\t\t\tcopen->see_update(dup);\n\t\t\t} else {\n\t\t\t\t\/\/ Since we aren't searching in\n\t\t\t\t\/\/ strict-f' order, when the weight is\n\t\t\t\t\/\/ 1.0 we must re-open these\n\t\t\t\t\/\/ inconsistent states.\n\t\t\t\tif (search->final_weight)\n\t\t\t\t\tcopen->add(dup);\n\t\t\t\telse if (!dup->is_incons())\n\t\t\t\t\tcincons->add(dup);\n#if !defined(NDEBUG)\n\t\t\t\telse\n\t\t\t\t\tassert(cincons->lookup(dup) == dup);\n#endif \/\/ !NDEBUG\n\t\t\t}\n\t\t}\n\t\tdelete ch;\n\t} else {\n\t\tcclosed->add(ch);\n\t\tif (ch->is_goal())\n\t\t\treturn ch->get_path();\n\t\tcopen->add(ch);\n\t}\n\n\treturn NULL;\n}\n\n\n\/**\n * Test the graph to see if we should switch to a new NBlock.\n * \\param n The current NBlock.\n *\n * \\note We should make this more complex... we should also check our\n * successor NBlocks.\n *\/\nbool ARPBNFSearch::ARPBNFThread::should_switch(NBlock *n)\n{\n\tbool ret;\n\n\tif (expansions < search->min_expansions)\n\t\treturn false;\n\n\texpansions = 0;\n\n\tfp_type free = graph->best_val();\n\tfp_type cur = n->open.get_best_val();\n\tNBlock *best_scope = graph->best_in_scope(n);\n\n\tif (best_scope) {\n\t\tfp_type scope = best_scope->open.get_best_val();\n\n\t\tret = free < cur || scope < cur;\n\t\tif (!ret) {\n\t\t\tgraph->wont_release(n);\n\t\t} else if (scope < free) {\n\t\t\tgraph->set_hot(best_scope);\n\t\t\tset_hot = true;\n\t\t}\n\t} else {\n\t\tret = free < cur;\n\t}\n\n\treturn ret;\n}\n\n\n\/*****************************************************************************\/\n\/*****************************************************************************\/\n\n\nARPBNFSearch::ARPBNFSearch(unsigned int n_threads,\n\t\t\t unsigned int min_e,\n\t\t\t vector<double> *w)\n\t: n_threads(n_threads),\n\t project(NULL),\n\t bound(fp_infinity),\n\t graph(NULL),\n\t min_expansions(min_e),\n\t weights(w),\n\t next_weight(1),\n\t domain(NULL),\n\t final_weight(false)\n{\n\tpthread_mutex_init(&wmutex, NULL);\n}\n\n\nARPBNFSearch::~ARPBNFSearch(void)\n{\n\tif (graph)\n\t\tdelete graph;\n}\n\n\nvector<State *> *ARPBNFSearch::search(Timer *timer, State *initial)\n{\n\tsolutions = new SyncSolutionStream(timer, 0.0001);\n\tdomain = initial->get_domain();\n\tproject = domain->get_projection();\n\n\tvector<ARPBNFSearch::ARPBNFThread*> threads;\n\tvector<ARPBNFSearch::ARPBNFThread*>::iterator iter;\n\n\tgraph = new NBlockGraph(project, initial, &bound);\n\n\tif (domain->get_heuristic()->get_weight() == fp_one)\n\t\tfinal_weight = true;\n\tfinal_sol_weight = domain->get_heuristic()->get_weight();\n\n\tfor (unsigned int i = 0; i < n_threads; i += 1) {\n\t\tARPBNFThread *t = new ARPBNFThread(graph, this);\n\t\tthreads.push_back(t);\n\t\tt->start();\n\t}\n\n\tfor (iter = threads.begin(); iter != threads.end(); iter++) {\n\t\t(*iter)->join();\n\t\tdelete *iter;\n\t}\n\n\treturn solutions->get_best_path();\n}\n\nvoid ARPBNFSearch::move_to_next_weight(void)\n{\n\tif (next_weight < weights->size())\n\t\tfinal_sol_weight = weights->at(next_weight);\n\n\tif (weights->at(next_weight - 1) != 1.0) {\n\t\tdouble nw = 1.0;\n\t\tif (next_weight < weights->size()) {\n\t\t\tnw = weights->at(next_weight);\n\t\t\tnext_weight += 1;\n\t\t} else {\n\t\t\tcerr << \"Final weight is not 1.0, using 1.0\" << endl;\n\t\t}\n\n\t\tdomain->get_heuristic()->set_weight(nw);\n\t\tif (nw == 1.0 || next_weight == weights->size())\n\t\t\tfinal_weight = true;\n\t}\n}\n\n\/**\n * Set an incumbant solution.\n *\n * If this function returns true than the calling thread must call for\n * a resort.\n *\/\nbool ARPBNFSearch::set_path(vector<State *> *p)\n{\n\tassert(solutions);\n\n\tpthread_mutex_lock(&wmutex);\n\n\tif (bound.read() <= p->at(0)->get_g()) {\n\t\tpthread_mutex_unlock(&wmutex);\n\t\treturn false;\n\t}\n\n\tsolutions->see_solution(p, get_generated(), get_expanded());\n\tbound.set(p->at(0)->get_g());\n\tgraph->new_bound();\n\n#if !defined(NDEBUG) && 0\n\tcout << \"Solution of cost \" << p->at(0)->get_g() \/ fp_one\n\t << \" found at weight \" << weights->at(next_weight - 1)\n\t << endl;\n#endif\t\/\/ !NDEBUG\n\n\tpthread_mutex_unlock(&wmutex);\n\n\treturn true;\n}\n\n\/**\n * Output extra \"key: value\" pairs.\n * keys should not have spaces in their names!\n *\/\nvoid ARPBNFSearch::output_stats(void)\n{\n\tcout << \"total-nblocks: \" << project->get_num_nblocks() << endl;\n\tcout << \"created-nblocks: \" << graph->get_ncreated_nblocks() << endl;\n\tcout << \"final-sol-weight: \" << final_sol_weight << endl;\n\n\tif (solutions)\n\t\tsolutions->output(cout);\n}\n<|endoftext|>"} {"text":"<commit_before>#include \".\/framework.h\"\n#include <sys\/stat.h>\n#include <string>\n#include <memory>\n#include <csignal>\n#include <sys\/types.h>\n#include <unistd.h>\n#include \"backtrace_formatter.h\"\n\nnamespace lms {\nnamespace internal {\n\nFramework::Framework(const std::string &mainConfigFilePath)\n : m_executionManager(*this), logger(\"lms.Framework\"),\n mainConfigFilePath(mainConfigFilePath), m_running(false), is_debug(false) {\n\n \/\/ start();\n}\n\nvoid Framework::addSearchPath(const std::string &path) {\n m_loader.addSearchPath(path);\n}\n\nvoid Framework::start() {\n bool firstRun = true;\n m_running = true;\n\n while (m_running) {\n \/\/ config monitor stuff\n if (firstRun || configMonitor.hasChangedFiles()) {\n logger.info() << \"Reload configs\";\n configMonitor.unwatchAll();\n RuntimeInfo runtime;\n for(const auto &f: flags) {\n logger.info(\"flag\") << f;\n }\n XmlParser parser(runtime, flags);\n parser.parseFile(mainConfigFilePath);\n\n for (auto error : parser.errors()) {\n logger.error(\"XML\") << error;\n }\n\n try {\n logger.time(\"updateSystem\");\n if(! updateSystem(runtime)) {\n m_running = false;\n }\n logger.timeEnd(\"updateSystem\");\n } catch(std::exception const &ex) {\n logger.error() << lms::typeName(ex) << \": \" << ex.what();\n m_running = false;\n }\n\n if(isDebug()) {\n printOverview();\n }\n\n for (auto file : parser.files()) {\n configMonitor.watch(file);\n }\n }\n\n if(!cycle()) {\n m_running = false;\n }\n firstRun = false;\n }\n\n logger.info() << \"Stopped\";\n}\n\nbool Framework::updateSystem(const RuntimeInfo &info) {\n if(isDebug()) {\n logger.debug() << \"updateSystem()\";\n }\n\n \/\/ Update or load services\n for (const ServiceInfo &serviceInfo : info.services) {\n if(isDebug()) {\n logger.debug() << \"Loading service \" << serviceInfo.name;\n }\n auto it = services.find(serviceInfo.name);\n if (it == services.end()) {\n \/\/ Not loaded yet\n std::shared_ptr<Service> service(m_loader.loadService(serviceInfo));\n\n service->initBase(serviceInfo);\n\n try {\n if (!service->init()) {\n logger.error() << \"Service \" << serviceInfo.name\n << \" failed to init()\";\n return false;\n }\n } catch (std::exception const &ex) {\n logger.error() << serviceInfo.name << \" throws \"\n << lms::typeName(ex) << \" : \" << ex.what();\n return false;\n }\n\n services[serviceInfo.name] = service;\n } else {\n \/\/ already loaded\n it->second->initBase(serviceInfo);\n it->second->configsChanged();\n }\n }\n\n \/\/ Update or load modules\n for (const ModuleInfo &moduleInfo : info.modules) {\n if(isDebug()) {\n logger.debug() << \"Loading module \" << moduleInfo.name;\n }\n auto it = modules.find(moduleInfo.name);\n if (it == modules.end()) {\n \/\/ Not yet loaded\n std::shared_ptr<Module> module(m_loader.loadModule(moduleInfo));\n module->initBase(moduleInfo, this);\n\n try {\n if (!module->init()) {\n logger.error() << \"Module \" << moduleInfo.name\n << \" failed to init()\";\n return false;\n }\n } catch (std::exception const &ex) {\n logger.error() << moduleInfo.name << \" throws \"\n << lms::typeName(ex) << \" : \" << ex.what();\n return false;\n }\n\n modules[moduleInfo.name] = module;\n } else {\n it->second->initBase(moduleInfo, this);\n it->second->configsChanged();\n }\n }\n\n if(isDebug()) {\n logger.debug() << \"updated system\";\n }\n\n return true;\n}\n\nFramework::~Framework() {\n \/\/ Shutdown services\n for (auto &service : services) {\n try {\n service.second->destroy();\n } catch (std::exception const &ex) {\n logger.error() << service.first << \" throws \" << lms::typeName(ex)\n << \" : \" << ex.what();\n }\n }\n\n \/\/ Shutdown modules\n for (auto &module : modules) {\n try {\n module.second->destroy();\n } catch (std::exception const &ex) {\n logger.error() << module.first << \" throws \" << lms::typeName(ex)\n << \" : \" << ex.what();\n }\n }\n}\n\nbool Framework::cycle() {\n if(modules.size() == 0) {\n logger.error() << \"No modules enabled. Check your config file. Shutting down ...\";\n return false;\n }\n\n m_clock.beforeLoopIteration();\n executionManager().validate(modules);\n m_executionManager.loop();\n return true;\n}\n\nstd::shared_ptr<Service> Framework::getService(std::string const &name) {\n return services[name];\n}\n\nbool Framework::isDebug() const {\n return is_debug; \/* TODO make this configurable *\/\n}\n\nvoid Framework::setDebug(bool debug) {\n this->is_debug = debug;\n}\n\nDataManager &Framework::dataManager() { return m_dataManager; }\n\nExecutionManager &Framework::executionManager() { return m_executionManager; }\n\nstd::string Framework::loadPath() const { return m_loadLogPath; }\n\nstd::string Framework::loadLogObject(std::string const &name, bool isDir) {\n if (!isEnableLoad()) {\n throw std::runtime_error(\n \"Command line option --enable-load was not specified\");\n }\n\n std::string logobj = m_loadLogPath + \"\/\" + name;\n\n return isDir ? logobj + \"\/\" : logobj;\n}\n\nstd::string Framework::saveLogObject(std::string const &name, bool isDir) {\n if (!isEnableSave()) {\n throw std::runtime_error(\n \"Command line option --enable-save was not specified\");\n }\n\n std::string logobj = m_saveLogPath + \"\/\" + name;\n\n if (isDir) {\n mkdir(logobj.c_str(), MODE);\n }\n\n return isDir ? logobj + \"\/\" : logobj;\n}\n\nbool Framework::isEnableLoad() const { return false; \/* TODO *\/ }\n\nbool Framework::isEnableSave() const { return false; \/* TODO *\/ }\n\nvoid Framework::addFlag(const std::string &flag) {\n flags.push_back(flag);\n}\n\nvoid Framework::signal(int signal) {\n switch(signal) {\n case SIGSEGV:\n {\n std::ofstream of(std::string(\"\/tmp\/lms-segfault-\") +\n std::to_string(getpid()) + \"-\" + std::to_string(std::time(NULL)) + \".txt\");\n printStacktrace(of);\n of.close();\n _exit(1);\n }\n break;\n case SIGINT:\n m_running = false;\n break;\n }\n}\n\nvoid Framework::printOverview() {\n logger.info(\"overview\") << \"Modules (\" << modules.size() << \")\";\n for(const auto &module : modules) {\n logger.info(\"overview\") << \" \" << module.first;\n }\n logger.info(\"overview\") << \"Services (\" << services.size() << \")\";\n for(const auto &service : services) {\n logger.info(\"overview\") << \" \" << service.first;\n }\n}\n\n} \/\/ namespace internal\n} \/\/ namespace lms\n<commit_msg>Configure clock from configs<commit_after>#include \".\/framework.h\"\n#include <sys\/stat.h>\n#include <string>\n#include <memory>\n#include <csignal>\n#include <sys\/types.h>\n#include <unistd.h>\n#include \"backtrace_formatter.h\"\n\nnamespace lms {\nnamespace internal {\n\nFramework::Framework(const std::string &mainConfigFilePath)\n : m_executionManager(*this), logger(\"lms.Framework\"),\n mainConfigFilePath(mainConfigFilePath), m_running(false), is_debug(false) {\n\n \/\/ start();\n}\n\nvoid Framework::addSearchPath(const std::string &path) {\n m_loader.addSearchPath(path);\n}\n\nvoid Framework::start() {\n bool firstRun = true;\n m_running = true;\n\n while (m_running) {\n \/\/ config monitor stuff\n if (firstRun || configMonitor.hasChangedFiles()) {\n logger.info() << \"Reload configs\";\n configMonitor.unwatchAll();\n RuntimeInfo runtime;\n for(const auto &f: flags) {\n logger.info(\"flag\") << f;\n }\n XmlParser parser(runtime, flags);\n parser.parseFile(mainConfigFilePath);\n\n for (auto error : parser.errors()) {\n logger.error(\"XML\") << error;\n }\n\n try {\n logger.time(\"updateSystem\");\n if(! updateSystem(runtime)) {\n m_running = false;\n }\n logger.timeEnd(\"updateSystem\");\n } catch(std::exception const &ex) {\n logger.error() << lms::typeName(ex) << \": \" << ex.what();\n m_running = false;\n }\n\n if(isDebug()) {\n printOverview();\n }\n\n for (auto file : parser.files()) {\n configMonitor.watch(file);\n }\n }\n\n if(!cycle()) {\n m_running = false;\n }\n firstRun = false;\n }\n\n logger.info() << \"Stopped\";\n}\n\nbool Framework::updateSystem(const RuntimeInfo &info) {\n if(isDebug()) {\n logger.debug() << \"updateSystem()\";\n }\n\n \/\/ Update clock\n m_clock.cycleTime(info.clock.cycle);\n m_clock.enabledSleep(info.clock.sleep);\n m_clock.enabledSlowWarning(info.clock.slowWarnings);\n m_clock.enabledCompensate(info.clock.sleepCompensate);\n\n \/\/ Update or load services\n for (const ServiceInfo &serviceInfo : info.services) {\n if(isDebug()) {\n logger.debug() << \"Loading service \" << serviceInfo.name;\n }\n auto it = services.find(serviceInfo.name);\n if (it == services.end()) {\n \/\/ Not loaded yet\n std::shared_ptr<Service> service(m_loader.loadService(serviceInfo));\n\n service->initBase(serviceInfo);\n\n try {\n if (!service->init()) {\n logger.error() << \"Service \" << serviceInfo.name\n << \" failed to init()\";\n return false;\n }\n } catch (std::exception const &ex) {\n logger.error() << serviceInfo.name << \" throws \"\n << lms::typeName(ex) << \" : \" << ex.what();\n return false;\n }\n\n services[serviceInfo.name] = service;\n } else {\n \/\/ already loaded\n it->second->initBase(serviceInfo);\n it->second->configsChanged();\n }\n }\n\n \/\/ Update or load modules\n for (const ModuleInfo &moduleInfo : info.modules) {\n if(isDebug()) {\n logger.debug() << \"Loading module \" << moduleInfo.name;\n }\n auto it = modules.find(moduleInfo.name);\n if (it == modules.end()) {\n \/\/ Not yet loaded\n std::shared_ptr<Module> module(m_loader.loadModule(moduleInfo));\n module->initBase(moduleInfo, this);\n\n try {\n if (!module->init()) {\n logger.error() << \"Module \" << moduleInfo.name\n << \" failed to init()\";\n return false;\n }\n } catch (std::exception const &ex) {\n logger.error() << moduleInfo.name << \" throws \"\n << lms::typeName(ex) << \" : \" << ex.what();\n return false;\n }\n\n modules[moduleInfo.name] = module;\n } else {\n it->second->initBase(moduleInfo, this);\n it->second->configsChanged();\n }\n }\n\n if(isDebug()) {\n logger.debug() << \"updated system\";\n }\n\n return true;\n}\n\nFramework::~Framework() {\n \/\/ Shutdown services\n for (auto &service : services) {\n try {\n service.second->destroy();\n } catch (std::exception const &ex) {\n logger.error() << service.first << \" throws \" << lms::typeName(ex)\n << \" : \" << ex.what();\n }\n }\n\n \/\/ Shutdown modules\n for (auto &module : modules) {\n try {\n module.second->destroy();\n } catch (std::exception const &ex) {\n logger.error() << module.first << \" throws \" << lms::typeName(ex)\n << \" : \" << ex.what();\n }\n }\n}\n\nbool Framework::cycle() {\n if(modules.size() == 0) {\n logger.error() << \"No modules enabled. Check your config file. Shutting down ...\";\n return false;\n }\n\n m_clock.beforeLoopIteration();\n executionManager().validate(modules);\n m_executionManager.loop();\n return true;\n}\n\nstd::shared_ptr<Service> Framework::getService(std::string const &name) {\n return services[name];\n}\n\nbool Framework::isDebug() const {\n return is_debug; \/* TODO make this configurable *\/\n}\n\nvoid Framework::setDebug(bool debug) {\n this->is_debug = debug;\n}\n\nDataManager &Framework::dataManager() { return m_dataManager; }\n\nExecutionManager &Framework::executionManager() { return m_executionManager; }\n\nstd::string Framework::loadPath() const { return m_loadLogPath; }\n\nstd::string Framework::loadLogObject(std::string const &name, bool isDir) {\n if (!isEnableLoad()) {\n throw std::runtime_error(\n \"Command line option --enable-load was not specified\");\n }\n\n std::string logobj = m_loadLogPath + \"\/\" + name;\n\n return isDir ? logobj + \"\/\" : logobj;\n}\n\nstd::string Framework::saveLogObject(std::string const &name, bool isDir) {\n if (!isEnableSave()) {\n throw std::runtime_error(\n \"Command line option --enable-save was not specified\");\n }\n\n std::string logobj = m_saveLogPath + \"\/\" + name;\n\n if (isDir) {\n mkdir(logobj.c_str(), MODE);\n }\n\n return isDir ? logobj + \"\/\" : logobj;\n}\n\nbool Framework::isEnableLoad() const { return false; \/* TODO *\/ }\n\nbool Framework::isEnableSave() const { return false; \/* TODO *\/ }\n\nvoid Framework::addFlag(const std::string &flag) {\n flags.push_back(flag);\n}\n\nvoid Framework::signal(int signal) {\n switch(signal) {\n case SIGSEGV:\n {\n std::ofstream of(std::string(\"\/tmp\/lms-segfault-\") +\n std::to_string(getpid()) + \"-\" + std::to_string(std::time(NULL)) + \".txt\");\n printStacktrace(of);\n of.close();\n _exit(1);\n }\n break;\n case SIGINT:\n m_running = false;\n break;\n }\n}\n\nvoid Framework::printOverview() {\n logger.info(\"overview\") << \"Modules (\" << modules.size() << \")\";\n for(const auto &module : modules) {\n logger.info(\"overview\") << \" \" << module.first;\n }\n logger.info(\"overview\") << \"Services (\" << services.size() << \")\";\n for(const auto &service : services) {\n logger.info(\"overview\") << \" \" << service.first;\n }\n}\n\n} \/\/ namespace internal\n} \/\/ namespace lms\n<|endoftext|>"} {"text":"<commit_before>\/*********************************************************************\n* Software License Agreement (BSD License)\n*\n* Copyright (c) 2008, Willow Garage, Inc.\n* All rights reserved.\n*\n* Redistribution and use in source and binary forms, with or without\n* modification, are permitted provided that the following conditions\n* are met:\n*\n* * Redistributions of source code must retain the above copyright\n* notice, this list of conditions and the following disclaimer.\n* * Redistributions in binary form must reproduce the above\n* copyright notice, this list of conditions and the following\n* disclaimer in the documentation and\/or other materials provided\n* with the distribution.\n* * Neither the name of the Willow Garage nor the names of its\n* contributors may be used to endorse or promote products derived\n* from this software without specific prior written permission.\n*\n* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n* \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n* POSSIBILITY OF SUCH DAMAGE.\n*********************************************************************\/\n\n\/* Author: Wim Meeussen *\/\n\n#include <urdf\/model.h>\n#include <kdl\/tree.hpp>\n#include <ros\/ros.h>\n#include \"robot_state_publisher\/robot_state_publisher.h\"\n#include \"robot_state_publisher\/joint_state_listener.h\"\n#include <kdl_parser\/kdl_parser.hpp>\n\n\nusing namespace std;\nusing namespace ros;\nusing namespace KDL;\nusing namespace robot_state_publisher;\n\nJointStateListener::JointStateListener(const KDL::Tree& tree, const MimicMap& m)\n : state_publisher_(tree), mimic_(m)\n{\n ros::NodeHandle n_tilde(\"~\");\n ros::NodeHandle n;\n\n \/\/ set publish frequency\n double publish_freq;\n n_tilde.param(\"publish_frequency\", publish_freq, 50.0);\n \/\/ get the tf_prefix parameter from the closest namespace\n std::string tf_prefix_key;\n n_tilde.searchParam(\"tf_prefix\", tf_prefix_key);\n n_tilde.param(tf_prefix_key, tf_prefix_, std::string(\"\"));\n publish_interval_ = ros::Duration(1.0\/max(publish_freq,1.0));\n\n \/\/ subscribe to joint state\n joint_state_sub_ = n.subscribe(\"joint_states\", 1, &JointStateListener::callbackJointState, this);\n\n \/\/ trigger to publish fixed joints\n timer_ = n_tilde.createTimer(publish_interval_, &JointStateListener::callbackFixedJoint, this);\n\n};\n\n\nJointStateListener::~JointStateListener()\n{};\n\n\nvoid JointStateListener::callbackFixedJoint(const ros::TimerEvent& e)\n{\n state_publisher_.publishFixedTransforms(tf_prefix_);\n}\n\nvoid JointStateListener::callbackJointState(const JointStateConstPtr& state)\n{\n if (state->name.size() != state->position.size()){\n ROS_ERROR(\"Robot state publisher received an invalid joint state vector\");\n return;\n }\n\n \/\/ check if we moved backwards in time (e.g. when playing a bag file)\n ros::Time now = ros::Time::now();\n if(last_callback_time_ > now) {\n \/\/ force re-publish of joint transforms\n ROS_WARN(\"Moved backwards in time (probably because ROS clock was reset), re-publishing joint transforms!\");\n last_publish_time_.clear();\n }\n last_callback_time_ = now;\n\n \/\/ determine least recently published joint\n ros::Time last_published = now;\n for (unsigned int i=0; i<state->name.size(); i++)\n {\n ros::Time t = last_publish_time_[state->name[i]];\n last_published = (t < last_published) ? t : last_published;\n }\n \/\/ note: if a joint was seen for the first time,\n \/\/ then last_published is zero.\n\n\n \/\/ check if we need to publish\n if (state->header.stamp >= last_published + publish_interval_){\n \/\/ get joint positions from state message\n map<string, double> joint_positions;\n for (unsigned int i=0; i<state->name.size(); i++)\n joint_positions.insert(make_pair(state->name[i], state->position[i]));\n\n for(MimicMap::iterator i = mimic_.begin(); i != mimic_.end(); i++){\n if(joint_positions.find(i->second->joint_name) != joint_positions.end()){\n double pos = joint_positions[i->second->joint_name] * i->second->multiplier + i->second->offset;\n joint_positions.insert(make_pair(i->first, pos));\n }\n }\n\n state_publisher_.publishTransforms(joint_positions, state->header.stamp, tf_prefix_);\n\n \/\/ store publish time in joint map\n for (unsigned int i=0; i<state->name.size(); i++)\n last_publish_time_[state->name[i]] = state->header.stamp;\n }\n}\n\n\/\/ ----------------------------------\n\/\/ ----- MAIN -----------------------\n\/\/ ----------------------------------\nint main(int argc, char** argv)\n{\n \/\/ Initialize ros\n ros::init(argc, argv, \"robot_state_publisher\");\n NodeHandle node;\n std::cout <<argv[0] << std::endl;\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ begin deprecation warning\n std::string exe_name = argv[0];\n std::size_t slash = exe_name.find_last_of(\"\/\");\n if (slash != std::string::npos)\n exe_name = exe_name.substr(slash + 1);\n if (exe_name == \"state_publisher\")\n ROS_WARN(\"The 'state_publisher' executable is deprecated. Please use 'robot_state_publisher' instead\");\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ end deprecation warning\n\n \/\/ gets the location of the robot description on the parameter server\n urdf::Model model;\n model.initParam(\"robot_description\");\n KDL::Tree tree;\n if (!kdl_parser::treeFromUrdfModel(model, tree)){\n ROS_ERROR(\"Failed to extract kdl tree from xml robot description\");\n return -1;\n }\n\n MimicMap mimic;\n\n for(std::map< std::string, boost::shared_ptr< urdf::Joint > >::iterator i = model.joints_.begin(); i != model.joints_.end(); i++){\n if(i->second->mimic){\n mimic.insert(make_pair(i->first, i->second->mimic));\n }\n }\n\n JointStateListener state_publisher(tree, mimic);\n ros::spin();\n\n return 0;\n}\n<commit_msg>get rid of argv[0] debug output on startup<commit_after>\/*********************************************************************\n* Software License Agreement (BSD License)\n*\n* Copyright (c) 2008, Willow Garage, Inc.\n* All rights reserved.\n*\n* Redistribution and use in source and binary forms, with or without\n* modification, are permitted provided that the following conditions\n* are met:\n*\n* * Redistributions of source code must retain the above copyright\n* notice, this list of conditions and the following disclaimer.\n* * Redistributions in binary form must reproduce the above\n* copyright notice, this list of conditions and the following\n* disclaimer in the documentation and\/or other materials provided\n* with the distribution.\n* * Neither the name of the Willow Garage nor the names of its\n* contributors may be used to endorse or promote products derived\n* from this software without specific prior written permission.\n*\n* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n* \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n* POSSIBILITY OF SUCH DAMAGE.\n*********************************************************************\/\n\n\/* Author: Wim Meeussen *\/\n\n#include <urdf\/model.h>\n#include <kdl\/tree.hpp>\n#include <ros\/ros.h>\n#include \"robot_state_publisher\/robot_state_publisher.h\"\n#include \"robot_state_publisher\/joint_state_listener.h\"\n#include <kdl_parser\/kdl_parser.hpp>\n\n\nusing namespace std;\nusing namespace ros;\nusing namespace KDL;\nusing namespace robot_state_publisher;\n\nJointStateListener::JointStateListener(const KDL::Tree& tree, const MimicMap& m)\n : state_publisher_(tree), mimic_(m)\n{\n ros::NodeHandle n_tilde(\"~\");\n ros::NodeHandle n;\n\n \/\/ set publish frequency\n double publish_freq;\n n_tilde.param(\"publish_frequency\", publish_freq, 50.0);\n \/\/ get the tf_prefix parameter from the closest namespace\n std::string tf_prefix_key;\n n_tilde.searchParam(\"tf_prefix\", tf_prefix_key);\n n_tilde.param(tf_prefix_key, tf_prefix_, std::string(\"\"));\n publish_interval_ = ros::Duration(1.0\/max(publish_freq,1.0));\n\n \/\/ subscribe to joint state\n joint_state_sub_ = n.subscribe(\"joint_states\", 1, &JointStateListener::callbackJointState, this);\n\n \/\/ trigger to publish fixed joints\n timer_ = n_tilde.createTimer(publish_interval_, &JointStateListener::callbackFixedJoint, this);\n\n};\n\n\nJointStateListener::~JointStateListener()\n{};\n\n\nvoid JointStateListener::callbackFixedJoint(const ros::TimerEvent& e)\n{\n state_publisher_.publishFixedTransforms(tf_prefix_);\n}\n\nvoid JointStateListener::callbackJointState(const JointStateConstPtr& state)\n{\n if (state->name.size() != state->position.size()){\n ROS_ERROR(\"Robot state publisher received an invalid joint state vector\");\n return;\n }\n\n \/\/ check if we moved backwards in time (e.g. when playing a bag file)\n ros::Time now = ros::Time::now();\n if(last_callback_time_ > now) {\n \/\/ force re-publish of joint transforms\n ROS_WARN(\"Moved backwards in time (probably because ROS clock was reset), re-publishing joint transforms!\");\n last_publish_time_.clear();\n }\n last_callback_time_ = now;\n\n \/\/ determine least recently published joint\n ros::Time last_published = now;\n for (unsigned int i=0; i<state->name.size(); i++)\n {\n ros::Time t = last_publish_time_[state->name[i]];\n last_published = (t < last_published) ? t : last_published;\n }\n \/\/ note: if a joint was seen for the first time,\n \/\/ then last_published is zero.\n\n\n \/\/ check if we need to publish\n if (state->header.stamp >= last_published + publish_interval_){\n \/\/ get joint positions from state message\n map<string, double> joint_positions;\n for (unsigned int i=0; i<state->name.size(); i++)\n joint_positions.insert(make_pair(state->name[i], state->position[i]));\n\n for(MimicMap::iterator i = mimic_.begin(); i != mimic_.end(); i++){\n if(joint_positions.find(i->second->joint_name) != joint_positions.end()){\n double pos = joint_positions[i->second->joint_name] * i->second->multiplier + i->second->offset;\n joint_positions.insert(make_pair(i->first, pos));\n }\n }\n\n state_publisher_.publishTransforms(joint_positions, state->header.stamp, tf_prefix_);\n\n \/\/ store publish time in joint map\n for (unsigned int i=0; i<state->name.size(); i++)\n last_publish_time_[state->name[i]] = state->header.stamp;\n }\n}\n\n\/\/ ----------------------------------\n\/\/ ----- MAIN -----------------------\n\/\/ ----------------------------------\nint main(int argc, char** argv)\n{\n \/\/ Initialize ros\n ros::init(argc, argv, \"robot_state_publisher\");\n NodeHandle node;\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ begin deprecation warning\n std::string exe_name = argv[0];\n std::size_t slash = exe_name.find_last_of(\"\/\");\n if (slash != std::string::npos)\n exe_name = exe_name.substr(slash + 1);\n if (exe_name == \"state_publisher\")\n ROS_WARN(\"The 'state_publisher' executable is deprecated. Please use 'robot_state_publisher' instead\");\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ end deprecation warning\n\n \/\/ gets the location of the robot description on the parameter server\n urdf::Model model;\n model.initParam(\"robot_description\");\n KDL::Tree tree;\n if (!kdl_parser::treeFromUrdfModel(model, tree)){\n ROS_ERROR(\"Failed to extract kdl tree from xml robot description\");\n return -1;\n }\n\n MimicMap mimic;\n\n for(std::map< std::string, boost::shared_ptr< urdf::Joint > >::iterator i = model.joints_.begin(); i != model.joints_.end(); i++){\n if(i->second->mimic){\n mimic.insert(make_pair(i->first, i->second->mimic));\n }\n }\n\n JointStateListener state_publisher(tree, mimic);\n ros::spin();\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: fieldwnd.hxx,v $\n *\n * $Revision: 1.12 $\n *\n * last change: $Author: rt $ $Date: 2005-09-08 21:24:46 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef SC_FIELDWND_HXX\n#define SC_FIELDWND_HXX\n\n#include <vector>\n\n#ifndef SC_ADDRESS_HXX\n#include \"address.hxx\"\n#endif\n\n#ifndef _SV_CTRL_HXX\n#include <vcl\/ctrl.hxx>\n#endif\n#ifndef _SV_FIXED_HXX\n#include <vcl\/fixed.hxx>\n#endif\n\n#ifndef _CPPUHELPER_WEAKREF_HXX_\n#include <cppuhelper\/weakref.hxx>\n#endif\n\n#define MAX_LABELS 256\n#define PAGE_SIZE 16 \/\/ count of visible fields for scrollbar\n#define LINE_SIZE 8 \/\/ count of fields per column for scrollbar\n#define MAX_FIELDS 8 \/\/ maximum count of fields for row\/col\/data area\n#define MAX_PAGEFIELDS 10 \/\/ maximum count of fields for page area\n\n#define OWIDTH PivotGlobal::nObjWidth\n#define OHEIGHT PivotGlobal::nObjHeight\n#define SSPACE PivotGlobal::nSelSpace\n\nclass ScDPLayoutDlg;\nclass ScAccessibleDataPilotControl;\n\n\/\/===================================================================\n\n\/** Type of content area. *\/\nenum ScDPFieldType\n{\n TYPE_PAGE, \/\/\/ Area for all page fields.\n TYPE_ROW, \/\/\/ Area for all row fields.\n TYPE_COL, \/\/\/ Area for all column fields.\n TYPE_DATA, \/\/\/ Area for all data fields.\n TYPE_SELECT \/\/\/ Selection area with all fields.\n};\n\n\/\/-------------------------------------------------------------------\n\n\/** Represents a field area in the DataPilot layout dialog. *\/\nclass ScDPFieldWindow : public Control\n{\nprivate:\n String aName; \/\/\/ name of the control, used in Accessibility\n ScDPLayoutDlg* pDlg; \/\/\/ Parent dialog.\n Rectangle aWndRect; \/\/\/ Area rectangle in pixels.\n FixedText* pFtCaption; \/\/\/ FixedText containing the name of the control.\n Point aTextPos; \/\/\/ Position of the caption text.\n std::vector< String > aFieldArr; \/\/\/ Pointer to string array of the field names.\n ScDPFieldType eType; \/\/\/ Type of this area.\n Color aFaceColor; \/\/\/ Color for dialog background.\n Color aWinColor; \/\/\/ Color for window background.\n Color aTextColor; \/\/\/ Color for text in buttons.\n Color aWinTextColor; \/\/\/ Color for text in field windows.\n size_t nFieldSize; \/\/\/ Maximum count of fields.\n size_t nFieldSelected; \/\/\/ Currently selected field.\n\n com::sun::star::uno::WeakReference< ::com::sun::star::accessibility::XAccessible > xAccessible;\n ScAccessibleDataPilotControl* pAccessible;\n\n \/** Initilize the object. *\/\n void Init();\n\n \/** Reads all needed style settings. *\/\n void GetStyleSettings();\n\n \/** Draws the background. *\/\n void DrawBackground( OutputDevice& rDev );\n \/** Draws a field into the specified rectangle. *\/\n void DrawField(\n OutputDevice& rDev,\n const Rectangle& rRect,\n const String& rText,\n bool bFocus );\n\n \/** @return TRUE, if the field index is inside of the control area. *\/\n bool IsValidIndex( size_t nIndex ) const;\n \/** @return TRUE, if the field with the given index exists. *\/\n bool IsExistingIndex( size_t nIndex ) const;\n \/** @return The new selection index after moving to the given direction. *\/\n size_t CalcNewFieldIndex( SCsCOL nDX, SCsROW nDY ) const;\n\n \/** Sets selection to the field with index nIndex. *\/\n void SetSelection( size_t nIndex );\n \/** Sets selection to first field. *\/\n void SetSelectionHome();\n \/** Sets selection to last field. *\/\n void SetSelectionEnd();\n \/** Sets selection to new position relative to current. *\/\n void MoveSelection( USHORT nKeyCode, SCsCOL nDX, SCsROW nDY );\n\n \/** Moves the selected field to nDestIndex. *\/\n void MoveField( size_t nDestIndex );\n \/** Moves the selected field to the given direction. *\/\n void MoveFieldRel( SCsCOL nDX, SCsROW nDY );\n\nprotected:\n virtual void Paint( const Rectangle& rRect );\n virtual void DataChanged( const DataChangedEvent& rDCEvt );\n virtual void MouseButtonDown( const MouseEvent& rMEvt );\n virtual void MouseButtonUp( const MouseEvent& rMEvt );\n virtual void MouseMove( const MouseEvent& rMEvt );\n virtual void KeyInput( const KeyEvent& rKEvt );\n virtual void GetFocus();\n virtual void LoseFocus();\n virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible > CreateAccessible();\n\npublic:\n ScDPFieldWindow(\n ScDPLayoutDlg* pDialog,\n const ResId& rResId,\n ScDPFieldType eFieldType,\n FixedText* pFtFieldCaption );\n ScDPFieldWindow(\n ScDPLayoutDlg* pDialog,\n const ResId& rResId,\n ScDPFieldType eFieldType,\n const String& aName );\n virtual ~ScDPFieldWindow();\n\n \/** Draws the complete control. *\/\n void Redraw();\n\n \/** @return The pixel position of a field (without bound check). *\/\n Point GetFieldPosition( size_t nIndex ) const;\n \/** @return The pixel size of a field. *\/\n Size GetFieldSize() const;\n\n \/** @return The index of the selected field. *\/\n inline bool IsEmpty() const { return aFieldArr.empty(); }\n \/** @return The index of the selected field. *\/\n inline size_t GetSelectedField() const { return nFieldSelected; }\n \/** @return The pixel position of the last possible field. *\/\n Point GetLastPosition() const;\n\n \/** @return The count of existing fields. *\/\n inline size_t GetFieldCount() const { return aFieldArr.size(); }\n \/** Inserts a field to the specified index. *\/\n void AddField( const String& rText, size_t nNewIndex );\n \/** Removes a field from the specified index. *\/\n void DelField( size_t nDelIndex );\n \/** Removes all fields. *\/\n void ClearFields();\n \/** Changes the text on an existing field. *\/\n void SetFieldText( const String& rText, size_t nIndex );\n \/** Returns the text of an existing field. *\/\n const String& GetFieldText( size_t nIndex ) const;\n\n \/** Inserts a field using the specified pixel position.\n @param rPos The coordinates to insert the field.\n @param rnIndex The new index of the field is returned here.\n @return TRUE, if the field has been created. *\/\n bool AddField( const String& rText, const Point& rPos, size_t& rnIndex );\n \/** Calculates the field index at a specific pixel position.\n @param rnIndex The index of the field is returned here.\n @return TRUE, if the index value is valid. *\/\n bool GetFieldIndex( const Point& rPos, size_t& rnIndex ) const;\n \/** Calculates a field index at a specific pixel position. Returns in every\n case the index of an existing field.\n @param rnIndex The index of the field is returned here.\n @return TRUE, if the index value is valid. *\/\n void GetExistingIndex( const Point& rPos, size_t& rnIndex );\n\n \/** Notifies this control that the offset of the first field has been changed.\n The control has to adjust the selection to keep the same field selected\n on scrolling with scrollbar. *\/\n void ModifySelectionOffset( long nOffsetDiff );\n \/** Selects the next field. Called i.e. after moving a field from SELECT area. *\/\n void SelectNext();\n\n \/** @return The name of the control without shortcut. *\/\n inline String GetName() const { return aName; }\n\n \/** @return The description of the control which is used for the accessibility objects. *\/\n String GetDescription() const;\n\n \/** Grabs focus and sets new selection. *\/\n void GrabFocusWithSel( size_t nIndex );\n\n \/** @return The type of the FieldWindow. *\/\n inline ScDPFieldType GetType() const { return eType; }\n};\n\n\/\/===================================================================\n\n#endif \/\/ SC_FIELDWND_HXX\n<commit_msg>INTEGRATION: CWS dr41 (1.11.440); FILE MERGED 2005\/10\/05 00:19:56 dr 1.11.440.2: RESYNC: (1.11-1.12); FILE MERGED 2005\/09\/13 18:40:43 nn 1.11.440.1: #124828# update mnemonics and tab stop style bits in StateChanged\/INITSHOW<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: fieldwnd.hxx,v $\n *\n * $Revision: 1.13 $\n *\n * last change: $Author: rt $ $Date: 2005-10-21 12:04:07 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef SC_FIELDWND_HXX\n#define SC_FIELDWND_HXX\n\n#include <vector>\n\n#ifndef SC_ADDRESS_HXX\n#include \"address.hxx\"\n#endif\n\n#ifndef _SV_CTRL_HXX\n#include <vcl\/ctrl.hxx>\n#endif\n#ifndef _SV_FIXED_HXX\n#include <vcl\/fixed.hxx>\n#endif\n\n#ifndef _CPPUHELPER_WEAKREF_HXX_\n#include <cppuhelper\/weakref.hxx>\n#endif\n\n#define MAX_LABELS 256\n#define PAGE_SIZE 16 \/\/ count of visible fields for scrollbar\n#define LINE_SIZE 8 \/\/ count of fields per column for scrollbar\n#define MAX_FIELDS 8 \/\/ maximum count of fields for row\/col\/data area\n#define MAX_PAGEFIELDS 10 \/\/ maximum count of fields for page area\n\n#define OWIDTH PivotGlobal::nObjWidth\n#define OHEIGHT PivotGlobal::nObjHeight\n#define SSPACE PivotGlobal::nSelSpace\n\nclass ScDPLayoutDlg;\nclass ScAccessibleDataPilotControl;\n\n\/\/===================================================================\n\n\/** Type of content area. *\/\nenum ScDPFieldType\n{\n TYPE_PAGE, \/\/\/ Area for all page fields.\n TYPE_ROW, \/\/\/ Area for all row fields.\n TYPE_COL, \/\/\/ Area for all column fields.\n TYPE_DATA, \/\/\/ Area for all data fields.\n TYPE_SELECT \/\/\/ Selection area with all fields.\n};\n\n\/\/-------------------------------------------------------------------\n\n\/** Represents a field area in the DataPilot layout dialog. *\/\nclass ScDPFieldWindow : public Control\n{\nprivate:\n String aName; \/\/\/ name of the control, used in Accessibility\n ScDPLayoutDlg* pDlg; \/\/\/ Parent dialog.\n Rectangle aWndRect; \/\/\/ Area rectangle in pixels.\n FixedText* pFtCaption; \/\/\/ FixedText containing the name of the control.\n Point aTextPos; \/\/\/ Position of the caption text.\n std::vector< String > aFieldArr; \/\/\/ Pointer to string array of the field names.\n ScDPFieldType eType; \/\/\/ Type of this area.\n Color aFaceColor; \/\/\/ Color for dialog background.\n Color aWinColor; \/\/\/ Color for window background.\n Color aTextColor; \/\/\/ Color for text in buttons.\n Color aWinTextColor; \/\/\/ Color for text in field windows.\n size_t nFieldSize; \/\/\/ Maximum count of fields.\n size_t nFieldSelected; \/\/\/ Currently selected field.\n\n com::sun::star::uno::WeakReference< ::com::sun::star::accessibility::XAccessible > xAccessible;\n ScAccessibleDataPilotControl* pAccessible;\n\n \/** Initilize the object. *\/\n void Init();\n\n \/** Reads all needed style settings. *\/\n void GetStyleSettings();\n\n \/** Draws the background. *\/\n void DrawBackground( OutputDevice& rDev );\n \/** Draws a field into the specified rectangle. *\/\n void DrawField(\n OutputDevice& rDev,\n const Rectangle& rRect,\n const String& rText,\n bool bFocus );\n\n \/** @return TRUE, if the field index is inside of the control area. *\/\n bool IsValidIndex( size_t nIndex ) const;\n \/** @return TRUE, if the field with the given index exists. *\/\n bool IsExistingIndex( size_t nIndex ) const;\n \/** @return The new selection index after moving to the given direction. *\/\n size_t CalcNewFieldIndex( SCsCOL nDX, SCsROW nDY ) const;\n\n \/** Sets selection to the field with index nIndex. *\/\n void SetSelection( size_t nIndex );\n \/** Sets selection to first field. *\/\n void SetSelectionHome();\n \/** Sets selection to last field. *\/\n void SetSelectionEnd();\n \/** Sets selection to new position relative to current. *\/\n void MoveSelection( USHORT nKeyCode, SCsCOL nDX, SCsROW nDY );\n\n \/** Moves the selected field to nDestIndex. *\/\n void MoveField( size_t nDestIndex );\n \/** Moves the selected field to the given direction. *\/\n void MoveFieldRel( SCsCOL nDX, SCsROW nDY );\n\n \/** Updates the tab stop style bits. *\/\n void UpdateStyle();\n\nprotected:\n virtual void Paint( const Rectangle& rRect );\n virtual void DataChanged( const DataChangedEvent& rDCEvt );\n virtual void MouseButtonDown( const MouseEvent& rMEvt );\n virtual void MouseButtonUp( const MouseEvent& rMEvt );\n virtual void MouseMove( const MouseEvent& rMEvt );\n virtual void KeyInput( const KeyEvent& rKEvt );\n virtual void GetFocus();\n virtual void LoseFocus();\n virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible > CreateAccessible();\n\npublic:\n ScDPFieldWindow(\n ScDPLayoutDlg* pDialog,\n const ResId& rResId,\n ScDPFieldType eFieldType,\n FixedText* pFtFieldCaption );\n ScDPFieldWindow(\n ScDPLayoutDlg* pDialog,\n const ResId& rResId,\n ScDPFieldType eFieldType,\n const String& aName );\n virtual ~ScDPFieldWindow();\n\n \/** Reads the FixedText's text with mnemonic and hides the FixedText. *\/\n void UseMnemonic();\n\n \/** Draws the complete control. *\/\n void Redraw();\n\n \/** @return The pixel position of a field (without bound check). *\/\n Point GetFieldPosition( size_t nIndex ) const;\n \/** @return The pixel size of a field. *\/\n Size GetFieldSize() const;\n\n \/** @return The index of the selected field. *\/\n inline bool IsEmpty() const { return aFieldArr.empty(); }\n \/** @return The index of the selected field. *\/\n inline size_t GetSelectedField() const { return nFieldSelected; }\n \/** @return The pixel position of the last possible field. *\/\n Point GetLastPosition() const;\n\n \/** @return The count of existing fields. *\/\n inline size_t GetFieldCount() const { return aFieldArr.size(); }\n \/** Inserts a field to the specified index. *\/\n void AddField( const String& rText, size_t nNewIndex );\n \/** Removes a field from the specified index. *\/\n void DelField( size_t nDelIndex );\n \/** Removes all fields. *\/\n void ClearFields();\n \/** Changes the text on an existing field. *\/\n void SetFieldText( const String& rText, size_t nIndex );\n \/** Returns the text of an existing field. *\/\n const String& GetFieldText( size_t nIndex ) const;\n\n \/** Inserts a field using the specified pixel position.\n @param rPos The coordinates to insert the field.\n @param rnIndex The new index of the field is returned here.\n @return TRUE, if the field has been created. *\/\n bool AddField( const String& rText, const Point& rPos, size_t& rnIndex );\n \/** Calculates the field index at a specific pixel position.\n @param rnIndex The index of the field is returned here.\n @return TRUE, if the index value is valid. *\/\n bool GetFieldIndex( const Point& rPos, size_t& rnIndex ) const;\n \/** Calculates a field index at a specific pixel position. Returns in every\n case the index of an existing field.\n @param rnIndex The index of the field is returned here.\n @return TRUE, if the index value is valid. *\/\n void GetExistingIndex( const Point& rPos, size_t& rnIndex );\n\n \/** Notifies this control that the offset of the first field has been changed.\n The control has to adjust the selection to keep the same field selected\n on scrolling with scrollbar. *\/\n void ModifySelectionOffset( long nOffsetDiff );\n \/** Selects the next field. Called i.e. after moving a field from SELECT area. *\/\n void SelectNext();\n\n \/** @return The name of the control without shortcut. *\/\n inline String GetName() const { return aName; }\n\n \/** @return The description of the control which is used for the accessibility objects. *\/\n String GetDescription() const;\n\n \/** Grabs focus and sets new selection. *\/\n void GrabFocusWithSel( size_t nIndex );\n\n \/** @return The type of the FieldWindow. *\/\n inline ScDPFieldType GetType() const { return eType; }\n};\n\n\/\/===================================================================\n\n#endif \/\/ SC_FIELDWND_HXX\n<|endoftext|>"} {"text":"<commit_before>\n#include <iostream>\n\n#include \"..\/..\/network\/network.h\"\n#include \"..\/..\/network\/util.h\"\n\nint main(int argc, char *argv[])\n{\n\t\/* create Data *\/\n\tint ret;\n\tFILE *fp;\n\tconst int trainingDataNum = 4;\n\tfloat *trainingData[trainingDataNum];\n\tfloat *labelData[trainingDataNum];\n\tfloat d[4][2];\n\tfloat l[4][2];\n\tint value;\n\t\n\tbool re;\n\ttrainingData[0] = d[0];\n\ttrainingData[1] = d[1];\n\ttrainingData[2] = d[2];\n\ttrainingData[3] = d[3];\n\tre = loadTrainingData(trainingData, \"dataset\/logic\/train-exor.txt\", trainingDataNum, 2);\n\tif(re == false) return 0;\n\n\tlabelData[0] = l[0];\n\tlabelData[1] = l[1];\n\tlabelData[2] = l[2];\n\tlabelData[3] = l[3];\n\tre = loadTrainingLabel(labelData, \"dataset\/logic\/train-exor-label.txt\", trainingDataNum, 2);\n\tif(re == false) return 0;\n\n\tfor(int i = 0; i < 4; i++) {\n\t\tstd::cout << trainingData[i][0] << trainingData[i][1] << \" | \";\n\t\tstd::cout << labelData[i][0] << labelData[i][1] << std::endl;\n\t}\n\n\t\/* parameters *\/\n\tint epoch = 20000;\n\tfloat lr = 0.1;\n\n\t\/* Create Network *\/\n\tNetwork *net;\n\tnet = new Network();\n\n\tFullyConnectedLayer *full1, *full2;\n\tact_T *act1t, *act2t;\n\n\tact1t = new act_T;\n\tact1t->apply = logistic_apply;\n\tact1t->diff = logistic_diff;\n\tact2t = new act_T;\n\tact2t->apply = logistic_apply;\n\tact2t->diff = logistic_diff;\n\tfull1 = new FullyConnectedLayer(2, 3, act1t, lr);\n\tfull2 = new FullyConnectedLayer(3, 2, act2t, lr);\n\n\tnet->appendLayer(full1);\n\tnet->appendLayer(full2);\n\n\tnet->setTest(trainingData, labelData, trainingDataNum, 1000);\n\tnet->train(trainingData, labelData, trainingDataNum, epoch);\n\tnet->saveParameters((char *)\"parameters\/logic\/exor_20000.param\");\n\n\tdelete net;\n\tdelete act1t;\n\tdelete act2t;\n\tdelete full1;\n\tdelete full2;\n\n\treturn 0;\n}\n<commit_msg>Delete unnecessary code<commit_after>\n#include <iostream>\n\n#include \"..\/..\/network\/network.h\"\n#include \"..\/..\/network\/util.h\"\n\nint main(int argc, char *argv[])\n{\n\t\/* create Data *\/\n\tbool re;\n\tconst int trainingDataNum = 4;\n\tconst int dataDim = 2;\n\tfloat *trainingData[trainingDataNum];\n\tfloat *labelData[trainingDataNum];\n\t\n\tfor(int i = 0; i < trainingDataNum; i++) {\n\t\ttrainingData[i] = new float(dataDim);\n\t}\n\tre = loadTrainingData(trainingData, \"dataset\/logic\/train-exor.txt\", trainingDataNum, dataDim);\n\tif(re == false) return 0;\n\n\tfor(int i = 0; i < trainingDataNum; i++) {\n\t\tlabelData[i] = new float(dataDim);\n\t}\n\tre = loadTrainingLabel(labelData, \"dataset\/logic\/train-exor-label.txt\", trainingDataNum, dataDim);\n\tif(re == false) return 0;\n\n\tfor(int i = 0; i < 4; i++) {\n\t\tstd::cout << trainingData[i][0] << trainingData[i][1] << \" | \";\n\t\tstd::cout << labelData[i][0] << labelData[i][1] << std::endl;\n\t}\n\n\t\/* parameters *\/\n\tint epoch = 20000;\n\tfloat lr = 0.1;\n\n\t\/* Create Network *\/\n\tNetwork *net;\n\tnet = new Network();\n\n\tFullyConnectedLayer *full1, *full2;\n\tact_T *act1t, *act2t;\n\n\tact1t = new act_T;\n\tact1t->apply = logistic_apply;\n\tact1t->diff = logistic_diff;\n\tact2t = new act_T;\n\tact2t->apply = logistic_apply;\n\tact2t->diff = logistic_diff;\n\tfull1 = new FullyConnectedLayer(2, 3, act1t, lr);\n\tfull2 = new FullyConnectedLayer(3, 2, act2t, lr);\n\n\tnet->appendLayer(full1);\n\tnet->appendLayer(full2);\n\n\tnet->setTest(trainingData, labelData, trainingDataNum, 1000);\n\tnet->train(trainingData, labelData, trainingDataNum, epoch);\n\tnet->saveParameters((char *)\"parameters\/logic\/exor_20000.param\");\n\n\tdelete net;\n\tdelete act1t;\n\tdelete act2t;\n\tdelete full1;\n\tdelete full2;\n\n\tfor(int i = 0; i < trainingDataNum; i++)\n\t\tdelete trainingData[i];\n\tfor(int i = 0; i < trainingDataNum; i++)\n\t\tdelete labelData[i];\n\n\treturn 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/**\n * @file dewpoint.cpp\n *\n * @date Jan 21, 2012\n * @author partio\n *\/\n\n#include \"dewpoint.h\"\n#include <iostream>\n#include \"plugin_factory.h\"\n#include \"logger_factory.h\"\n#include <boost\/lexical_cast.hpp>\n\n#define HIMAN_AUXILIARY_INCLUDE\n\n#include \"fetcher.h\"\n#include \"writer.h\"\n#include \"neons.h\"\n#include \"pcuda.h\"\n\n#undef HIMAN_AUXILIARY_INCLUDE\n\n#ifdef DEBUG\n#include \"timer_factory.h\"\n#endif\n\nusing namespace std;\nusing namespace himan::plugin;\n\n#undef HAVE_CUDA\n\n#ifdef HAVE_CUDA\nnamespace himan\n{\nnamespace plugin\n{\nnamespace dewpoint_cuda\n{\nvoid doCuda(const float* Tin, float TBase, const float* Pin, float PScale, const float* VVin, float* VVout, size_t N, float PConst, unsigned short deviceIndex);\n}\n}\n}\n#endif\n\nconst double RW = 461.5; \/\/ Vesihoyryn kaasuvakio (J \/ K kg)\nconst double L = 2.5e6; \/\/ Veden hoyrystymislampo (J \/ kg)\nconst double RW_div_L = RW \/ L;\n\ndewpoint::dewpoint() : itsUseCuda(false)\n{\n itsClearTextFormula = \"Td = T \/ (1 - (T * ln(RH)*(Rw\/L)))\";\n\n itsLogger = std::unique_ptr<logger> (logger_factory::Instance()->GetLog(\"dewpoint\"));\n\n}\n\nvoid dewpoint::Process(shared_ptr<configuration> conf)\n{\n\n shared_ptr<plugin::pcuda> c = dynamic_pointer_cast<plugin::pcuda> (plugin_factory::Instance()->Plugin(\"pcuda\"));\n\n if (c->HaveCuda())\n {\n string msg = \"I possess the powers of CUDA\";\n\n if (!conf->UseCuda())\n {\n msg += \", but I won't use them\";\n }\n else\n {\n msg += \", and I'm not afraid to use them\";\n itsUseCuda = true;\n }\n\n itsLogger->Info(msg);\n\n }\n\n \/\/ Get number of threads to use\n\n unsigned short threadCount = ThreadCount(conf->ThreadCount());\n\n boost::thread_group g;\n\n \/*\n * The target information is parsed from the configuration file.\n *\/\n\n shared_ptr<info> targetInfo = conf->Info();\n\n \/*\n * Get producer information from neons if whole_file_write is false.\n *\/\n\n if (!conf->WholeFileWrite())\n {\n shared_ptr<neons> n = dynamic_pointer_cast<neons> (plugin_factory::Instance()->Plugin(\"neons\"));\n\n map<string,string> prodInfo = n->ProducerInfo(targetInfo->Producer().Id());\n\n if (prodInfo.size())\n {\n producer prod(targetInfo->Producer().Id());\n\n prod.Process(boost::lexical_cast<long> (prodInfo[\"process\"]));\n prod.Centre(boost::lexical_cast<long> (prodInfo[\"centre\"]));\n prod.Name(prodInfo[\"name\"]);\n\n targetInfo->Producer(prod);\n }\n\n }\n\n \/*\n * Set target parameter to potential temperature\n *\n * We need to specify grib and querydata parameter information\n * since we don't know which one will be the output format.\n *\n *\/\n\n vector<param> params;\n\n param requestedParam (\"TD-K\", 10);\n\n requestedParam.GribDiscipline(0);\n requestedParam.GribCategory(0);\n requestedParam.GribParameter(6);\n\n params.push_back(requestedParam);\n\n targetInfo->Params(params);\n\n \/*\n * Create data structures.\n *\/\n\n targetInfo->Create(conf->ScanningMode(), false);\n\n \/*\n * Initialize parent class functions for dimension handling\n *\/\n\n Dimension(conf->LeadingDimension());\n FeederInfo(targetInfo->Clone());\n FeederInfo()->Param(requestedParam);\n\n \/*\n * Each thread will have a copy of the target info.\n *\/\n\n vector<shared_ptr<info> > targetInfos;\n\n targetInfos.resize(threadCount);\n\n for (size_t i = 0; i < threadCount; i++)\n {\n\n itsLogger->Info(\"Thread \" + boost::lexical_cast<string> (i + 1) + \" starting\");\n\n targetInfos[i] = targetInfo->Clone();\n\n boost::thread* t = new boost::thread(&dewpoint::Run,\n this,\n targetInfos[i],\n conf,\n i + 1);\n\n g.add_thread(t);\n\n }\n\n g.join_all();\n\n if (conf->WholeFileWrite())\n {\n\n shared_ptr<writer> theWriter = dynamic_pointer_cast <writer> (plugin_factory::Instance()->Plugin(\"writer\"));\n\n targetInfo->FirstTime();\n\n string theOutputFile = \"himan_\" + targetInfo->Param().Name() + \"_\" + targetInfo->Time().OriginDateTime()->String(\"%Y%m%d%H\");\n theWriter->ToFile(targetInfo, conf->OutputFileType(), false, theOutputFile);\n\n }\n}\n\nvoid dewpoint::Run(shared_ptr<info> myTargetInfo,\n shared_ptr<const configuration> conf,\n unsigned short threadIndex)\n{\n\n while (AdjustLeadingDimension(myTargetInfo))\n {\n Calculate(myTargetInfo, conf, threadIndex);\n }\n\n}\n\n\/*\n * Calculate()\n *\n * This function does the actual calculation.\n *\/\n\nvoid dewpoint::Calculate(shared_ptr<info> myTargetInfo,\n shared_ptr<const configuration> conf,\n unsigned short threadIndex)\n{\n\n\n shared_ptr<fetcher> f = dynamic_pointer_cast <fetcher> (plugin_factory::Instance()->Plugin(\"fetcher\"));\n\n \/\/ Required source parameters\n\n param TParam(\"T-K\");\n param RHParam(\"RH-PRCNT\");\n\n unique_ptr<logger> myThreadedLogger = std::unique_ptr<logger> (logger_factory::Instance()->GetLog(\"dewpointThread #\" + boost::lexical_cast<string> (threadIndex)));\n\n ResetNonLeadingDimension(myTargetInfo);\n\n myTargetInfo->FirstParam();\n\n while (AdjustNonLeadingDimension(myTargetInfo))\n {\n\n myThreadedLogger->Debug(\"Calculating time \" + myTargetInfo->Time().ValidDateTime()->String(\"%Y%m%d%H\") +\n \" level \" + boost::lexical_cast<string> (myTargetInfo->Level().Value()));\n\n myTargetInfo->Data()->Resize(conf->Ni(), conf->Nj());\n\n double TBase = 0;\n\n shared_ptr<info> TInfo;\n shared_ptr<info> RHInfo;\n\n try\n {\n \tTInfo = f->Fetch(conf,\n \t\t\t\t\t\tmyTargetInfo->Time(),\n \t myTargetInfo->Level(),\n \t TParam);\n\n \tRHInfo = f->Fetch(conf,\n \t\t\t\t\t\tmyTargetInfo->Time(),\n \t \t\t\tmyTargetInfo->Level(),\n \t \t\t\tRHParam);\n\n }\n catch (HPExceptionType e)\n {\n \tswitch (e)\n \t{\n\t\t\t\tcase kFileDataNotFound:\n\t\t\t\t\titsLogger->Info(\"Skipping step \" + boost::lexical_cast<string> (myTargetInfo->Time().Step()) + \", level \" + boost::lexical_cast<string> (myTargetInfo->Level().Value()));\n\t\t\t\t\tmyTargetInfo->Data()->Fill(kFloatMissing); \/\/ Fill data with missing value\n\t\t\t\t\tcontinue;\n\t\t\t\t\tbreak;\n\n\t\t\t\tdefault:\n\t\t\t\t\tthrow runtime_error(ClassName() + \": Unable to proceed\");\n\t\t\t\t\tbreak;\n\t\t\t}\n }\n\n assert(RHInfo->Param().Unit() == kPrcnt);\n\n \tif (TInfo->Param().Unit() == kC)\n \t{\n \t\tTBase = 273.15;\n \t}\n\n shared_ptr<NFmiGrid> targetGrid(myTargetInfo->Grid()->ToNewbaseGrid());\n shared_ptr<NFmiGrid> TGrid(TInfo->Grid()->ToNewbaseGrid());\n shared_ptr<NFmiGrid> RHGrid(RHInfo->Grid()->ToNewbaseGrid());\n\n int missingCount = 0;\n int count = 0;\n\n bool equalGrids = (*myTargetInfo->Grid() == *TInfo->Grid() && *myTargetInfo->Grid() == *RHInfo->Grid());\n\n#ifdef HAVE_CUDA\n\n if (itsUseCuda && equalGrids)\n {\n size_t N = TGrid->Size();\n\n float* VVout = new float[N];\n\n if (!isPressureLevel)\n {\n dewpoint_cuda::doCuda(TGrid->DataPool()->Data(), TBase, PGrid->DataPool()->Data(), PScale, VVGrid->DataPool()->Data(), VVout, N, 0, theThreadIndex-1);\n }\n else\n {\n dewpoint_cuda::doCuda(TGrid->DataPool()->Data(), TBase, 0, 0, VVGrid->DataPool()->Data(), VVout, N, 100 * myTargetInfo->Level().Value(), theThreadIndex-1);\n }\n\n double *data = new double[N];\n\n for (size_t i = 0; i < N; i++)\n {\n data[i] = static_cast<float> (VVout[i]);\n\n if (data[i] == kFloatMissing)\n {\n missingCount++;\n }\n\n count++;\n }\n\n myTargetInfo->Data()->Set(data, N);\n\n delete [] data;\n delete [] VVout;\n\n }\n else\n {\n\n#else\n if (true)\n {\n#endif\n\n assert(targetGrid->Size() == myTargetInfo->Data()->Size());\n\n myTargetInfo->ResetLocation();\n\n targetGrid->Reset();\n\n#ifdef DEBUG\n unique_ptr<timer> t = unique_ptr<timer> (timer_factory::Instance()->GetTimer());\n t->Start();\n#endif\n\n while (myTargetInfo->NextLocation() && targetGrid->Next())\n {\n count++;\n\n double T = kFloatMissing;\n double RH = kFloatMissing;\n\n InterpolateToPoint(targetGrid, TGrid, equalGrids, T);\n InterpolateToPoint(targetGrid, RHGrid, equalGrids, RH);\n\n if (T == kFloatMissing || RH == kFloatMissing)\n {\n missingCount++;\n\n myTargetInfo->Value(kFloatMissing);\n continue;\n }\n\n double TD = ((T+TBase) \/ (1 - ((T+TBase) * log(RH) * (RW_div_L)))) - 273.15 + TBase;\n\n if (!myTargetInfo->Value(TD))\n {\n throw runtime_error(ClassName() + \": Failed to set value to matrix\");\n }\n\n }\n#ifdef DEBUG\n t->Stop();\n itsLogger->Debug(\"Calculation took \" + boost::lexical_cast<string> (t->GetTime()) + \" microseconds on CPU\");\n#endif\n }\n\n \/*\n * Now we are done for this level\n *\n * Clone info-instance to writer since it might change our descriptor places\n *\/\n\n myThreadedLogger->Info(\"Missing values: \" + boost::lexical_cast<string> (missingCount) + \"\/\" + boost::lexical_cast<string> (count));\n\n if (!conf->WholeFileWrite())\n {\n shared_ptr<writer> w = dynamic_pointer_cast <writer> (plugin_factory::Instance()->Plugin(\"writer\"));\n\n w->ToFile(myTargetInfo->Clone(), conf->OutputFileType(), true);\n }\n }\n}\n<commit_msg>Parameter unit change<commit_after>\/**\n * @file dewpoint.cpp\n *\n * @date Jan 21, 2012\n * @author partio\n *\/\n\n#include \"dewpoint.h\"\n#include <iostream>\n#include \"plugin_factory.h\"\n#include \"logger_factory.h\"\n#include <boost\/lexical_cast.hpp>\n\n#define HIMAN_AUXILIARY_INCLUDE\n\n#include \"fetcher.h\"\n#include \"writer.h\"\n#include \"neons.h\"\n#include \"pcuda.h\"\n\n#undef HIMAN_AUXILIARY_INCLUDE\n\n#ifdef DEBUG\n#include \"timer_factory.h\"\n#endif\n\nusing namespace std;\nusing namespace himan::plugin;\n\n#undef HAVE_CUDA\n\n#ifdef HAVE_CUDA\nnamespace himan\n{\nnamespace plugin\n{\nnamespace dewpoint_cuda\n{\nvoid doCuda(const float* Tin, float TBase, const float* Pin, float PScale, const float* VVin, float* VVout, size_t N, float PConst, unsigned short deviceIndex);\n}\n}\n}\n#endif\n\nconst double RW = 461.5; \/\/ Vesihoyryn kaasuvakio (J \/ K kg)\nconst double L = 2.5e6; \/\/ Veden hoyrystymislampo (J \/ kg)\nconst double RW_div_L = RW \/ L;\n\ndewpoint::dewpoint() : itsUseCuda(false)\n{\n itsClearTextFormula = \"Td = T \/ (1 - (T * ln(RH)*(Rw\/L)))\";\n\n itsLogger = std::unique_ptr<logger> (logger_factory::Instance()->GetLog(\"dewpoint\"));\n\n}\n\nvoid dewpoint::Process(shared_ptr<configuration> conf)\n{\n\n shared_ptr<plugin::pcuda> c = dynamic_pointer_cast<plugin::pcuda> (plugin_factory::Instance()->Plugin(\"pcuda\"));\n\n if (c->HaveCuda())\n {\n string msg = \"I possess the powers of CUDA\";\n\n if (!conf->UseCuda())\n {\n msg += \", but I won't use them\";\n }\n else\n {\n msg += \", and I'm not afraid to use them\";\n itsUseCuda = true;\n }\n\n itsLogger->Info(msg);\n\n }\n\n \/\/ Get number of threads to use\n\n unsigned short threadCount = ThreadCount(conf->ThreadCount());\n\n boost::thread_group g;\n\n \/*\n * The target information is parsed from the configuration file.\n *\/\n\n shared_ptr<info> targetInfo = conf->Info();\n\n \/*\n * Get producer information from neons if whole_file_write is false.\n *\/\n\n if (!conf->WholeFileWrite())\n {\n shared_ptr<neons> n = dynamic_pointer_cast<neons> (plugin_factory::Instance()->Plugin(\"neons\"));\n\n map<string,string> prodInfo = n->ProducerInfo(targetInfo->Producer().Id());\n\n if (prodInfo.size())\n {\n producer prod(targetInfo->Producer().Id());\n\n prod.Process(boost::lexical_cast<long> (prodInfo[\"process\"]));\n prod.Centre(boost::lexical_cast<long> (prodInfo[\"centre\"]));\n prod.Name(prodInfo[\"name\"]);\n\n targetInfo->Producer(prod);\n }\n\n }\n\n \/*\n * Set target parameter to potential temperature\n *\n * We need to specify grib and querydata parameter information\n * since we don't know which one will be the output format.\n *\n *\/\n\n vector<param> params;\n\n param requestedParam (\"TD-C\", 10);\n\n requestedParam.GribDiscipline(0);\n requestedParam.GribCategory(0);\n requestedParam.GribParameter(6);\n\n params.push_back(requestedParam);\n\n targetInfo->Params(params);\n\n \/*\n * Create data structures.\n *\/\n\n targetInfo->Create(conf->ScanningMode(), false);\n\n \/*\n * Initialize parent class functions for dimension handling\n *\/\n\n Dimension(conf->LeadingDimension());\n FeederInfo(targetInfo->Clone());\n FeederInfo()->Param(requestedParam);\n\n \/*\n * Each thread will have a copy of the target info.\n *\/\n\n vector<shared_ptr<info> > targetInfos;\n\n targetInfos.resize(threadCount);\n\n for (size_t i = 0; i < threadCount; i++)\n {\n\n itsLogger->Info(\"Thread \" + boost::lexical_cast<string> (i + 1) + \" starting\");\n\n targetInfos[i] = targetInfo->Clone();\n\n boost::thread* t = new boost::thread(&dewpoint::Run,\n this,\n targetInfos[i],\n conf,\n i + 1);\n\n g.add_thread(t);\n\n }\n\n g.join_all();\n\n if (conf->WholeFileWrite())\n {\n\n shared_ptr<writer> theWriter = dynamic_pointer_cast <writer> (plugin_factory::Instance()->Plugin(\"writer\"));\n\n targetInfo->FirstTime();\n\n string theOutputFile = \"himan_\" + targetInfo->Param().Name() + \"_\" + targetInfo->Time().OriginDateTime()->String(\"%Y%m%d%H\");\n theWriter->ToFile(targetInfo, conf->OutputFileType(), false, theOutputFile);\n\n }\n}\n\nvoid dewpoint::Run(shared_ptr<info> myTargetInfo,\n shared_ptr<const configuration> conf,\n unsigned short threadIndex)\n{\n\n while (AdjustLeadingDimension(myTargetInfo))\n {\n Calculate(myTargetInfo, conf, threadIndex);\n }\n\n}\n\n\/*\n * Calculate()\n *\n * This function does the actual calculation.\n *\/\n\nvoid dewpoint::Calculate(shared_ptr<info> myTargetInfo,\n shared_ptr<const configuration> conf,\n unsigned short threadIndex)\n{\n\n\n shared_ptr<fetcher> f = dynamic_pointer_cast <fetcher> (plugin_factory::Instance()->Plugin(\"fetcher\"));\n\n \/\/ Required source parameters\n\n param TParam(\"T-K\");\n param RHParam(\"RH-PRCNT\");\n\n unique_ptr<logger> myThreadedLogger = std::unique_ptr<logger> (logger_factory::Instance()->GetLog(\"dewpointThread #\" + boost::lexical_cast<string> (threadIndex)));\n\n ResetNonLeadingDimension(myTargetInfo);\n\n myTargetInfo->FirstParam();\n\n while (AdjustNonLeadingDimension(myTargetInfo))\n {\n\n myThreadedLogger->Debug(\"Calculating time \" + myTargetInfo->Time().ValidDateTime()->String(\"%Y%m%d%H\") +\n \" level \" + boost::lexical_cast<string> (myTargetInfo->Level().Value()));\n\n myTargetInfo->Data()->Resize(conf->Ni(), conf->Nj());\n\n double TBase = 0;\n\n shared_ptr<info> TInfo;\n shared_ptr<info> RHInfo;\n\n try\n {\n \tTInfo = f->Fetch(conf,\n \t\t\t\t\t\tmyTargetInfo->Time(),\n \t myTargetInfo->Level(),\n \t TParam);\n\n \tRHInfo = f->Fetch(conf,\n \t\t\t\t\t\tmyTargetInfo->Time(),\n \t \t\t\tmyTargetInfo->Level(),\n \t \t\t\tRHParam);\n\n }\n catch (HPExceptionType e)\n {\n \tswitch (e)\n \t{\n\t\t\t\tcase kFileDataNotFound:\n\t\t\t\t\titsLogger->Info(\"Skipping step \" + boost::lexical_cast<string> (myTargetInfo->Time().Step()) + \", level \" + boost::lexical_cast<string> (myTargetInfo->Level().Value()));\n\t\t\t\t\tmyTargetInfo->Data()->Fill(kFloatMissing); \/\/ Fill data with missing value\n\t\t\t\t\tcontinue;\n\t\t\t\t\tbreak;\n\n\t\t\t\tdefault:\n\t\t\t\t\tthrow runtime_error(ClassName() + \": Unable to proceed\");\n\t\t\t\t\tbreak;\n\t\t\t}\n }\n\n assert(RHInfo->Param().Unit() == kPrcnt);\n\n \tif (TInfo->Param().Unit() == kC)\n \t{\n \t\tTBase = 273.15;\n \t}\n\n shared_ptr<NFmiGrid> targetGrid(myTargetInfo->Grid()->ToNewbaseGrid());\n shared_ptr<NFmiGrid> TGrid(TInfo->Grid()->ToNewbaseGrid());\n shared_ptr<NFmiGrid> RHGrid(RHInfo->Grid()->ToNewbaseGrid());\n\n int missingCount = 0;\n int count = 0;\n\n bool equalGrids = (*myTargetInfo->Grid() == *TInfo->Grid() && *myTargetInfo->Grid() == *RHInfo->Grid());\n\n#ifdef HAVE_CUDA\n\n if (itsUseCuda && equalGrids)\n {\n size_t N = TGrid->Size();\n\n float* VVout = new float[N];\n\n if (!isPressureLevel)\n {\n dewpoint_cuda::doCuda(TGrid->DataPool()->Data(), TBase, PGrid->DataPool()->Data(), PScale, VVGrid->DataPool()->Data(), VVout, N, 0, theThreadIndex-1);\n }\n else\n {\n dewpoint_cuda::doCuda(TGrid->DataPool()->Data(), TBase, 0, 0, VVGrid->DataPool()->Data(), VVout, N, 100 * myTargetInfo->Level().Value(), theThreadIndex-1);\n }\n\n double *data = new double[N];\n\n for (size_t i = 0; i < N; i++)\n {\n data[i] = static_cast<float> (VVout[i]);\n\n if (data[i] == kFloatMissing)\n {\n missingCount++;\n }\n\n count++;\n }\n\n myTargetInfo->Data()->Set(data, N);\n\n delete [] data;\n delete [] VVout;\n\n }\n else\n {\n\n#else\n if (true)\n {\n#endif\n\n assert(targetGrid->Size() == myTargetInfo->Data()->Size());\n\n myTargetInfo->ResetLocation();\n\n targetGrid->Reset();\n\n#ifdef DEBUG\n unique_ptr<timer> t = unique_ptr<timer> (timer_factory::Instance()->GetTimer());\n t->Start();\n#endif\n\n while (myTargetInfo->NextLocation() && targetGrid->Next())\n {\n count++;\n\n double T = kFloatMissing;\n double RH = kFloatMissing;\n\n InterpolateToPoint(targetGrid, TGrid, equalGrids, T);\n InterpolateToPoint(targetGrid, RHGrid, equalGrids, RH);\n\n if (T == kFloatMissing || RH == kFloatMissing)\n {\n missingCount++;\n\n myTargetInfo->Value(kFloatMissing);\n continue;\n }\n\n double TD = ((T+TBase) \/ (1 - ((T+TBase) * log(RH) * (RW_div_L)))) - 273.15 + TBase;\n\n if (!myTargetInfo->Value(TD))\n {\n throw runtime_error(ClassName() + \": Failed to set value to matrix\");\n }\n\n }\n#ifdef DEBUG\n t->Stop();\n itsLogger->Debug(\"Calculation took \" + boost::lexical_cast<string> (t->GetTime()) + \" microseconds on CPU\");\n#endif\n }\n\n \/*\n * Now we are done for this level\n *\n * Clone info-instance to writer since it might change our descriptor places\n *\/\n\n myThreadedLogger->Info(\"Missing values: \" + boost::lexical_cast<string> (missingCount) + \"\/\" + boost::lexical_cast<string> (count));\n\n if (!conf->WholeFileWrite())\n {\n shared_ptr<writer> w = dynamic_pointer_cast <writer> (plugin_factory::Instance()->Plugin(\"writer\"));\n\n w->ToFile(myTargetInfo->Clone(), conf->OutputFileType(), true);\n }\n }\n}\n<|endoftext|>"} {"text":"<commit_before>#include <sstream>\n\n#include \"StorageFlattening.h\"\n#include \"IRMutator.h\"\n#include \"IROperator.h\"\n#include \"Scope.h\"\n#include \"Bounds.h\"\n#include \"Parameter.h\"\n\nnamespace Halide {\nnamespace Internal {\n\nusing std::ostringstream;\nusing std::string;\nusing std::vector;\nusing std::map;\nusing std::pair;\nusing std::set;\n\nnamespace {\n \nclass FlattenDimensions : public IRMutator {\npublic:\n FlattenDimensions(const map<string, pair<Function, int>> &e, const Target &t)\n : env(e), target(t) {}\n Scope<int> scope;\nprivate:\n const map<string, pair<Function, int>> &env;\n const Target ⌖\n Scope<int> realizations;\n\n Expr flatten_args(const string &name, const vector<Expr> &args) {\n bool internal = realizations.contains(name);\n Expr idx = target.has_feature(Target::LargeBuffers) ? make_zero(Int(64)) : 0;\n vector<Expr> mins(args.size()), strides(args.size());\n\n for (size_t i = 0; i < args.size(); i++) {\n string dim = std::to_string(i);\n string stride_name = name + \".stride.\" + dim;\n string min_name = name + \".min.\" + dim;\n string stride_name_constrained = stride_name + \".constrained\";\n string min_name_constrained = min_name + \".constrained\";\n if (scope.contains(stride_name_constrained)) {\n stride_name = stride_name_constrained;\n }\n if (scope.contains(min_name_constrained)) {\n min_name = min_name_constrained;\n }\n strides[i] = Variable::make(Int(32), stride_name);\n mins[i] = Variable::make(Int(32), min_name);\n }\n\n if (internal) {\n \/\/ f(x, y) -> f[(x-xmin)*xstride + (y-ymin)*ystride] This\n \/\/ strategy makes sense when we expect x to cancel with\n \/\/ something in xmin. We use this for internal allocations\n for (size_t i = 0; i < args.size(); i++) {\n if (target.has_feature(Target::LargeBuffers)) {\n idx += cast<int64_t>(args[i] - mins[i]) * cast<int64_t>(strides[i]);\n } else {\n idx += (args[i] - mins[i]) * strides[i];\n }\n }\n } else {\n \/\/ f(x, y) -> f[x*stride + y*ystride - (xstride*xmin +\n \/\/ ystride*ymin)]. The idea here is that the last term\n \/\/ will be pulled outside the inner loop. We use this for\n \/\/ external buffers, where the mins and strides are likely\n \/\/ to be symbolic\n Expr base = target.has_feature(Target::LargeBuffers) ? make_zero(Int(64)) : 0;\n for (size_t i = 0; i < args.size(); i++) {\n if (target.has_feature(Target::LargeBuffers)) {\n idx += cast<int64_t>(args[i]) * cast<int64_t>(strides[i]);\n base += cast<int64_t>(mins[i]) * cast<int64_t>(strides[i]);\n } else {\n idx += args[i] * strides[i];\n base += mins[i] * strides[i];\n }\n }\n idx -= base;\n }\n\n return idx;\n }\n\n using IRMutator::visit;\n\n void visit(const Realize *op) {\n realizations.push(op->name, 0);\n\n Stmt body = mutate(op->body);\n\n \/\/ Compute the size\n std::vector<Expr> extents;\n for (size_t i = 0; i < op->bounds.size(); i++) {\n extents.push_back(op->bounds[i].extent);\n extents[i] = mutate(extents[i]);\n }\n Expr condition = mutate(op->condition);\n\n realizations.pop(op->name);\n\n vector<int> storage_permutation;\n {\n auto iter = env.find(op->name);\n Function f = iter->second.first;\n internal_assert(iter != env.end()) << \"Realize node refers to function not in environment.\\n\";\n const vector<StorageDim> &storage_dims = f.schedule().storage_dims();\n const vector<string> &args = f.args();\n for (size_t i = 0; i < storage_dims.size(); i++) {\n for (size_t j = 0; j < args.size(); j++) {\n if (args[j] == storage_dims[i].var) {\n storage_permutation.push_back((int)j);\n Expr alignment = storage_dims[i].alignment;\n if (alignment.defined()) {\n extents[j] = ((extents[j] + alignment - 1)\/alignment)*alignment;\n }\n }\n }\n internal_assert(storage_permutation.size() == i+1);\n }\n }\n\n internal_assert(storage_permutation.size() == op->bounds.size());\n\n stmt = body;\n internal_assert(op->types.size() == 1);\n\n \/\/ Make the names for the mins, extents, and strides\n int dims = op->bounds.size();\n vector<string> min_name(dims), extent_name(dims), stride_name(dims);\n for (int i = 0; i < dims; i++) {\n string d = std::to_string(i);\n min_name[i] = op->name + \".min.\" + d;\n stride_name[i] = op->name + \".stride.\" + d;\n extent_name[i] = op->name + \".extent.\" + d;\n }\n vector<Expr> min_var(dims), extent_var(dims), stride_var(dims);\n for (int i = 0; i < dims; i++) {\n min_var[i] = Variable::make(Int(32), min_name[i]);\n extent_var[i] = Variable::make(Int(32), extent_name[i]);\n stride_var[i] = Variable::make(Int(32), stride_name[i]);\n }\n\n \/\/ Create a buffer_t object for this allocation.\n vector<Expr> args(dims*3 + 2);\n Expr first_elem = Load::make(op->types[0], op->name, 0, BufferPtr(), Parameter());\n args[0] = Call::make(Handle(), Call::address_of, {first_elem}, Call::PureIntrinsic);\n args[1] = make_zero(op->types[0]);\n for (int i = 0; i < dims; i++) {\n args[3*i+2] = min_var[i];\n args[3*i+3] = extent_var[i];\n args[3*i+4] = stride_var[i];\n }\n Expr buf = Call::make(type_of<struct buffer_t *>(), Call::create_buffer_t,\n args, Call::Intrinsic);\n stmt = LetStmt::make(op->name + \".buffer\", buf, stmt);\n\n \/\/ Make the allocation node\n stmt = Allocate::make(op->name, op->types[0], extents, condition, stmt);\n\n \/\/ Compute the strides\n for (int i = (int)op->bounds.size()-1; i > 0; i--) {\n int prev_j = storage_permutation[i-1];\n int j = storage_permutation[i];\n Expr stride = stride_var[prev_j] * extent_var[prev_j];\n stmt = LetStmt::make(stride_name[j], stride, stmt);\n }\n \n \/\/ Innermost stride is one\n if (dims > 0) {\n int innermost = storage_permutation.empty() ? 0 : storage_permutation[0];\n stmt = LetStmt::make(stride_name[innermost], 1, stmt);\n }\n \n \/\/ Assign the mins and extents stored\n for (size_t i = op->bounds.size(); i > 0; i--) {\n stmt = LetStmt::make(min_name[i-1], op->bounds[i-1].min, stmt);\n stmt = LetStmt::make(extent_name[i-1], extents[i-1], stmt);\n }\n }\n\n void visit(const Provide *op) {\n internal_assert(op->values.size() == 1);\n\n Expr idx = mutate(flatten_args(op->name, op->args));\n Expr value = mutate(op->values[0]); \n stmt = Store::make(op->name, value, idx, Parameter());\n }\n\n void visit(const Call *op) {\n if (op->call_type == Call::Halide ||\n op->call_type == Call::Image) {\n internal_assert(op->value_index == 0);\n Expr idx = mutate(flatten_args(op->name, op->args));\n expr = Load::make(op->type, op->name, idx, op->image, op->param);\n } else {\n IRMutator::visit(op);\n }\n }\n\n void visit(const LetStmt *let) {\n \/\/ Discover constrained versions of things.\n bool constrained_version_exists = ends_with(let->name, \".constrained\");\n if (constrained_version_exists) {\n scope.push(let->name, 0);\n }\n\n IRMutator::visit(let);\n\n if (constrained_version_exists) {\n scope.pop(let->name);\n }\n }\n};\n\n\/\/ Realizations, stores, and loads must all be on types that are\n\/\/ multiples of 8-bits. This really only affects bools\nclass PromoteToMemoryType : public IRMutator {\n using IRMutator::visit;\n\n Type upgrade(Type t) {\n return t.with_bits(((t.bits() + 7)\/8)*8);\n }\n \n void visit(const Load *op) {\n Type t = upgrade(op->type);\n if (t != op->type) {\n expr = Cast::make(op->type, Load::make(t, op->name, mutate(op->index), op->image, op->param));\n } else {\n IRMutator::visit(op);\n }\n }\n\n void visit(const Store *op) {\n Type t = upgrade(op->value.type());\n if (t != op->value.type()) {\n stmt = Store::make(op->name, Cast::make(t, mutate(op->value)), mutate(op->index), op->param);\n } else {\n IRMutator::visit(op);\n }\n }\n\n void visit(const Allocate *op) {\n Type t = upgrade(op->type); \n if (t != op->type) {\n vector<Expr> extents;\n for (Expr e : op->extents) {\n extents.push_back(mutate(e));\n }\n stmt = Allocate::make(op->name, t, extents,\n mutate(op->condition), mutate(op->body),\n mutate(op->new_expr), op->free_function);\n } else {\n IRMutator::visit(op);\n }\n }\n};\n\n\/\/ Connect Store nodes to their output buffers\nclass ConnectOutputBuffers : public IRMutator {\n using IRMutator::visit;\n\n void visit(const Store *op) {\n Parameter output_buf;\n auto it = env.find(op->name);\n if (it != env.end()) {\n const Function &f = it->second.first;\n int idx = it->second.second;\n\n \/\/ We only want to do this for actual pipeline outputs,\n \/\/ even though every Function has an output buffer. Any\n \/\/ constraints you set on the output buffer of a Func that\n \/\/ isn't actually an output is ignored. This is a language\n \/\/ wart.\n if (outputs.count(f.name())) {\n output_buf = f.output_buffers()[idx];\n }\n } \n \n if (output_buf.defined()) {\n stmt = Store::make(op->name, op->value, op->index, output_buf);\n } else {\n stmt = op;\n }\n }\n\n const map<string, pair<Function, int>> &env;\n set<string> outputs;\n \npublic:\n ConnectOutputBuffers(const std::map<string, pair<Function, int>> &e,\n const vector<Function> &o) : env(e) {\n for (auto &f : o) {\n outputs.insert(f.name());\n }\n }\n};\n\n} \/\/ namespace\n \nStmt storage_flattening(Stmt s,\n const vector<Function> &outputs,\n const map<string, Function> &env,\n const Target &target) {\n \/\/ Make an environment that makes it easier to figure out which\n \/\/ Function corresponds to a tuple component. foo.0, foo.1, foo.2,\n \/\/ all point to the function foo.\n map<string, pair<Function, int>> tuple_env;\n for (auto p : env) {\n if (p.second.outputs() > 1) {\n for (int i = 0; i < p.second.outputs(); i++) {\n tuple_env[p.first + \".\" + std::to_string(i)] = {p.second, i};\n }\n } else {\n tuple_env[p.first] = {p.second, 0};\n }\n }\n\n s = FlattenDimensions(tuple_env, target).mutate(s);\n s = PromoteToMemoryType().mutate(s);\n s = ConnectOutputBuffers(tuple_env, outputs).mutate(s);\n return s;\n}\n\n}\n}\n<commit_msg>cuda fix<commit_after>#include <sstream>\n\n#include \"StorageFlattening.h\"\n#include \"IRMutator.h\"\n#include \"IROperator.h\"\n#include \"Scope.h\"\n#include \"Bounds.h\"\n#include \"Parameter.h\"\n\nnamespace Halide {\nnamespace Internal {\n\nusing std::ostringstream;\nusing std::string;\nusing std::vector;\nusing std::map;\nusing std::pair;\nusing std::set;\n\nnamespace {\n \nclass FlattenDimensions : public IRMutator {\npublic:\n FlattenDimensions(const map<string, pair<Function, int>> &e, const Target &t)\n : env(e), target(t) {}\n Scope<int> scope;\nprivate:\n const map<string, pair<Function, int>> &env;\n const Target ⌖\n Scope<int> realizations;\n\n Expr flatten_args(const string &name, const vector<Expr> &args) {\n bool internal = realizations.contains(name);\n Expr idx = target.has_feature(Target::LargeBuffers) ? make_zero(Int(64)) : 0;\n vector<Expr> mins(args.size()), strides(args.size());\n\n for (size_t i = 0; i < args.size(); i++) {\n string dim = std::to_string(i);\n string stride_name = name + \".stride.\" + dim;\n string min_name = name + \".min.\" + dim;\n string stride_name_constrained = stride_name + \".constrained\";\n string min_name_constrained = min_name + \".constrained\";\n if (scope.contains(stride_name_constrained)) {\n stride_name = stride_name_constrained;\n }\n if (scope.contains(min_name_constrained)) {\n min_name = min_name_constrained;\n }\n strides[i] = Variable::make(Int(32), stride_name);\n mins[i] = Variable::make(Int(32), min_name);\n }\n\n if (internal) {\n \/\/ f(x, y) -> f[(x-xmin)*xstride + (y-ymin)*ystride] This\n \/\/ strategy makes sense when we expect x to cancel with\n \/\/ something in xmin. We use this for internal allocations\n for (size_t i = 0; i < args.size(); i++) {\n if (target.has_feature(Target::LargeBuffers)) {\n idx += cast<int64_t>(args[i] - mins[i]) * cast<int64_t>(strides[i]);\n } else {\n idx += (args[i] - mins[i]) * strides[i];\n }\n }\n } else {\n \/\/ f(x, y) -> f[x*stride + y*ystride - (xstride*xmin +\n \/\/ ystride*ymin)]. The idea here is that the last term\n \/\/ will be pulled outside the inner loop. We use this for\n \/\/ external buffers, where the mins and strides are likely\n \/\/ to be symbolic\n Expr base = target.has_feature(Target::LargeBuffers) ? make_zero(Int(64)) : 0;\n for (size_t i = 0; i < args.size(); i++) {\n if (target.has_feature(Target::LargeBuffers)) {\n idx += cast<int64_t>(args[i]) * cast<int64_t>(strides[i]);\n base += cast<int64_t>(mins[i]) * cast<int64_t>(strides[i]);\n } else {\n idx += args[i] * strides[i];\n base += mins[i] * strides[i];\n }\n }\n idx -= base;\n }\n\n return idx;\n }\n\n using IRMutator::visit;\n\n void visit(const Realize *op) {\n realizations.push(op->name, 0);\n\n Stmt body = mutate(op->body);\n\n \/\/ Compute the size\n std::vector<Expr> extents;\n for (size_t i = 0; i < op->bounds.size(); i++) {\n extents.push_back(op->bounds[i].extent);\n extents[i] = mutate(extents[i]);\n }\n Expr condition = mutate(op->condition);\n\n realizations.pop(op->name);\n\n vector<int> storage_permutation;\n {\n auto iter = env.find(op->name);\n Function f = iter->second.first;\n internal_assert(iter != env.end()) << \"Realize node refers to function not in environment.\\n\";\n const vector<StorageDim> &storage_dims = f.schedule().storage_dims();\n const vector<string> &args = f.args();\n for (size_t i = 0; i < storage_dims.size(); i++) {\n for (size_t j = 0; j < args.size(); j++) {\n if (args[j] == storage_dims[i].var) {\n storage_permutation.push_back((int)j);\n Expr alignment = storage_dims[i].alignment;\n if (alignment.defined()) {\n extents[j] = ((extents[j] + alignment - 1)\/alignment)*alignment;\n }\n }\n }\n internal_assert(storage_permutation.size() == i+1);\n }\n }\n\n internal_assert(storage_permutation.size() == op->bounds.size());\n\n stmt = body;\n internal_assert(op->types.size() == 1);\n\n \/\/ Make the names for the mins, extents, and strides\n int dims = op->bounds.size();\n vector<string> min_name(dims), extent_name(dims), stride_name(dims);\n for (int i = 0; i < dims; i++) {\n string d = std::to_string(i);\n min_name[i] = op->name + \".min.\" + d;\n stride_name[i] = op->name + \".stride.\" + d;\n extent_name[i] = op->name + \".extent.\" + d;\n }\n vector<Expr> min_var(dims), extent_var(dims), stride_var(dims);\n for (int i = 0; i < dims; i++) {\n min_var[i] = Variable::make(Int(32), min_name[i]);\n extent_var[i] = Variable::make(Int(32), extent_name[i]);\n stride_var[i] = Variable::make(Int(32), stride_name[i]);\n }\n\n \/\/ Create a buffer_t object for this allocation.\n vector<Expr> args(dims*3 + 2);\n Expr first_elem = Load::make(op->types[0], op->name, 0, BufferPtr(), Parameter());\n args[0] = Call::make(Handle(), Call::address_of, {first_elem}, Call::PureIntrinsic);\n args[1] = make_zero(op->types[0]);\n for (int i = 0; i < dims; i++) {\n args[3*i+2] = min_var[i];\n args[3*i+3] = extent_var[i];\n args[3*i+4] = stride_var[i];\n }\n Expr buf = Call::make(type_of<struct buffer_t *>(), Call::create_buffer_t,\n args, Call::Intrinsic);\n stmt = LetStmt::make(op->name + \".buffer\", buf, stmt);\n\n \/\/ Make the allocation node\n stmt = Allocate::make(op->name, op->types[0], extents, condition, stmt);\n\n \/\/ Compute the strides\n for (int i = (int)op->bounds.size()-1; i > 0; i--) {\n int prev_j = storage_permutation[i-1];\n int j = storage_permutation[i];\n Expr stride = stride_var[prev_j] * extent_var[prev_j];\n stmt = LetStmt::make(stride_name[j], stride, stmt);\n }\n \n \/\/ Innermost stride is one\n if (dims > 0) {\n int innermost = storage_permutation.empty() ? 0 : storage_permutation[0];\n stmt = LetStmt::make(stride_name[innermost], 1, stmt);\n }\n \n \/\/ Assign the mins and extents stored\n for (size_t i = op->bounds.size(); i > 0; i--) {\n stmt = LetStmt::make(min_name[i-1], op->bounds[i-1].min, stmt);\n stmt = LetStmt::make(extent_name[i-1], extents[i-1], stmt);\n }\n }\n\n void visit(const Provide *op) {\n internal_assert(op->values.size() == 1);\n\n Expr idx = mutate(flatten_args(op->name, op->args));\n Expr value = mutate(op->values[0]); \n stmt = Store::make(op->name, value, idx, Parameter());\n }\n\n void visit(const Call *op) {\n if (op->call_type == Call::Halide ||\n op->call_type == Call::Image) {\n internal_assert(op->value_index == 0);\n Expr idx = mutate(flatten_args(op->name, op->args));\n expr = Load::make(op->type, op->name, idx, op->image, op->param);\n } else {\n IRMutator::visit(op);\n }\n }\n\n void visit(const LetStmt *let) {\n \/\/ Discover constrained versions of things.\n bool constrained_version_exists = ends_with(let->name, \".constrained\");\n if (constrained_version_exists) {\n scope.push(let->name, 0);\n }\n\n IRMutator::visit(let);\n\n if (constrained_version_exists) {\n scope.pop(let->name);\n }\n }\n};\n\n\/\/ Realizations, stores, and loads must all be on types that are\n\/\/ multiples of 8-bits. This really only affects bools\nclass PromoteToMemoryType : public IRMutator {\n using IRMutator::visit;\n\n Type upgrade(Type t) {\n return t.with_bits(((t.bits() + 7)\/8)*8);\n } \n \n void visit(const Call *op) {\n if (op->is_intrinsic(Call::address_of)) {\n Expr load = mutate(op->args[0]);\n if (const Cast *cast = load.as<Cast>()) {\n expr = cast->value;\n } else {\n expr = load;\n }\n } else {\n IRMutator::visit(op);\n }\n }\n\n void visit(const Load *op) {\n Type t = upgrade(op->type);\n if (t != op->type) {\n expr = Cast::make(op->type, Load::make(t, op->name, mutate(op->index), op->image, op->param));\n } else {\n IRMutator::visit(op);\n }\n }\n\n void visit(const Store *op) {\n Type t = upgrade(op->value.type());\n if (t != op->value.type()) {\n stmt = Store::make(op->name, Cast::make(t, mutate(op->value)), mutate(op->index), op->param);\n } else {\n IRMutator::visit(op);\n }\n }\n\n void visit(const Allocate *op) {\n Type t = upgrade(op->type); \n if (t != op->type) {\n vector<Expr> extents;\n for (Expr e : op->extents) {\n extents.push_back(mutate(e));\n }\n stmt = Allocate::make(op->name, t, extents,\n mutate(op->condition), mutate(op->body),\n mutate(op->new_expr), op->free_function);\n } else {\n IRMutator::visit(op);\n }\n }\n};\n\n\/\/ Connect Store nodes to their output buffers\nclass ConnectOutputBuffers : public IRMutator {\n using IRMutator::visit;\n\n void visit(const Store *op) {\n Parameter output_buf;\n auto it = env.find(op->name);\n if (it != env.end()) {\n const Function &f = it->second.first;\n int idx = it->second.second;\n\n \/\/ We only want to do this for actual pipeline outputs,\n \/\/ even though every Function has an output buffer. Any\n \/\/ constraints you set on the output buffer of a Func that\n \/\/ isn't actually an output is ignored. This is a language\n \/\/ wart.\n if (outputs.count(f.name())) {\n output_buf = f.output_buffers()[idx];\n }\n } \n \n if (output_buf.defined()) {\n stmt = Store::make(op->name, op->value, op->index, output_buf);\n } else {\n stmt = op;\n }\n }\n\n const map<string, pair<Function, int>> &env;\n set<string> outputs;\n \npublic:\n ConnectOutputBuffers(const std::map<string, pair<Function, int>> &e,\n const vector<Function> &o) : env(e) {\n for (auto &f : o) {\n outputs.insert(f.name());\n }\n }\n};\n\n} \/\/ namespace\n \nStmt storage_flattening(Stmt s,\n const vector<Function> &outputs,\n const map<string, Function> &env,\n const Target &target) {\n \/\/ Make an environment that makes it easier to figure out which\n \/\/ Function corresponds to a tuple component. foo.0, foo.1, foo.2,\n \/\/ all point to the function foo.\n map<string, pair<Function, int>> tuple_env;\n for (auto p : env) {\n if (p.second.outputs() > 1) {\n for (int i = 0; i < p.second.outputs(); i++) {\n tuple_env[p.first + \".\" + std::to_string(i)] = {p.second, i};\n }\n } else {\n tuple_env[p.first] = {p.second, 0};\n }\n }\n\n s = FlattenDimensions(tuple_env, target).mutate(s);\n s = PromoteToMemoryType().mutate(s);\n s = ConnectOutputBuffers(tuple_env, outputs).mutate(s);\n return s;\n}\n\n}\n}\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: fieldwnd.hxx,v $\n *\n * $Revision: 1.8 $\n *\n * last change: $Author: rt $ $Date: 2003-04-17 15:09:36 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef SC_FIELDWND_HXX\n#define SC_FIELDWND_HXX\n\n\n#ifndef _SV_CTRL_HXX\n#include <vcl\/ctrl.hxx>\n#endif\n#ifndef _SV_FIXED_HXX\n#include <vcl\/fixed.hxx>\n#endif\n\n#ifndef _CPPUHELPER_WEAKREF_HXX_\n#include <cppuhelper\/weakref.hxx>\n#endif\n\n#define MAX_LABELS 256\n#define PAGE_SIZE 16 \/\/ count of visible fields for scrollbar\n#define LINE_SIZE 8 \/\/ count of fields per column for scrollbar\n#define MAX_FIELDS 8 \/\/ maximum count of fields for row\/col\/data area\n\n#define OWIDTH PivotGlobal::nObjWidth\n#define OHEIGHT PivotGlobal::nObjHeight\n#define SSPACE PivotGlobal::nSelSpace\n\nclass ScDPLayoutDlg;\nclass ScAccessibleDataPilotControl;\n\n\/\/===================================================================\n\n\/** Type of content area. *\/\nenum ScDPFieldType\n{\n TYPE_ROW, \/\/\/ Area for all row fields.\n TYPE_COL, \/\/\/ Area for all column fields.\n TYPE_DATA, \/\/\/ Area for all data fields.\n TYPE_SELECT \/\/\/ Selection area with all fields.\n};\n\n\/\/-------------------------------------------------------------------\n\n\/** Represents a field area in the DataPilot layout dialog. *\/\nclass ScDPFieldWindow : public Control\n{\nprivate:\n String aName; \/\/\/ name of the control, used in Accessibility\n ScDPLayoutDlg* pDlg; \/\/\/ Parent dialog.\n Rectangle aWndRect; \/\/\/ Area rectangle in pixels.\n FixedText* pFtCaption; \/\/\/ FixedText containing the name of the control.\n Point aTextPos; \/\/\/ Position of the caption text.\n String** aFieldArr; \/\/\/ Pointer to string array of the field names.\n ScDPFieldType eType; \/\/\/ Type of this area.\n Color aFaceColor; \/\/\/ Color for dialog background.\n Color aWinColor; \/\/\/ Color for window background.\n Color aTextColor; \/\/\/ Color for text in buttons.\n Color aWinTextColor; \/\/\/ Color for text in field windows.\n long nFieldSize; \/\/\/ Maximum count of fields.\n long nFieldCount; \/\/\/ Count of existing fields.\n long nFieldSelected; \/\/\/ Currently selected field.\n\n com::sun::star::uno::WeakReference< ::drafts::com::sun::star::accessibility::XAccessible > xAccessible;\n ScAccessibleDataPilotControl* pAccessible;\n\n \/** Initilize the object. *\/\n void Init();\n\n \/** Reads all needed style settings. *\/\n void GetStyleSettings();\n\n \/** Draws the background. *\/\n void DrawBackground( OutputDevice& rDev );\n \/** Draws a field into the specified rectangle. *\/\n void DrawField(\n OutputDevice& rDev,\n const Rectangle& rRect,\n const String& rText,\n BOOL bSelected );\n\n \/** @return TRUE, if the field index is inside of the control area. *\/\n BOOL IsValidIndex( long nIndex ) const;\n \/** @return TRUE, if the field with the given index exists. *\/\n BOOL IsExistingIndex( long nIndex ) const;\n \/** @return The new selection index after moving to the given direction. *\/\n long CalcNewFieldIndex( short nDX, short nDY ) const;\n\n \/** Sets selection to the field with index nIndex. *\/\n void SetSelection( long nIndex );\n \/** Sets selection to first field. *\/\n void SetSelectionHome();\n \/** Sets selection to last field. *\/\n void SetSelectionEnd();\n \/** Sets selection to new position relative to current. *\/\n void MoveSelection( USHORT nKeyCode, short nDX, short nDY );\n\n \/** Moves the selected field to nDestIndex. *\/\n void MoveField( long nDestIndex );\n \/** Moves the selected field to the given direction. *\/\n void MoveFieldRel( short nDX, short nDY );\n\nprotected:\n virtual void Paint( const Rectangle& rRect );\n virtual void DataChanged( const DataChangedEvent& rDCEvt );\n virtual void MouseButtonDown( const MouseEvent& rMEvt );\n virtual void MouseButtonUp( const MouseEvent& rMEvt );\n virtual void MouseMove( const MouseEvent& rMEvt );\n virtual void KeyInput( const KeyEvent& rKEvt );\n virtual void GetFocus();\n virtual void LoseFocus();\n virtual ::com::sun::star::uno::Reference< ::drafts::com::sun::star::accessibility::XAccessible > CreateAccessible();\n\npublic:\n ScDPFieldWindow(\n ScDPLayoutDlg* pDialog,\n const ResId& rResId,\n ScDPFieldType eFieldType,\n FixedText* pFtFieldCaption );\n ScDPFieldWindow(\n ScDPLayoutDlg* pDialog,\n const ResId& rResId,\n ScDPFieldType eFieldType,\n const String& aName );\n virtual ~ScDPFieldWindow();\n\n \/** Draws the complete control. *\/\n void Redraw();\n\n \/** @return The pixel position of a field (without bound check). *\/\n Point GetFieldPosition( long nIndex ) const;\n \/** @return The pixel size of a field. *\/\n Size GetFieldSize() const;\n\n \/** @return The index of the selected field. *\/\n inline BOOL IsEmpty() const { return nFieldCount == 0; }\n \/** @return The index of the selected field. *\/\n inline long GetSelectedField() const { return nFieldSelected; }\n \/** @return The pixel position of the last possible field. *\/\n Point GetLastPosition() const;\n\n \/** @return The count of existing fields. *\/\n long GetFieldCount() const { return nFieldCount; }\n \/** Inserts a field to the specified index. *\/\n void AddField( const String& rText, long nNewIndex );\n \/** Removes a field from the specified index. *\/\n void DelField( long nDelIndex );\n \/** Removes all fields. *\/\n void ClearFields();\n \/** Changes the text on an existing field. *\/\n void SetFieldText( const String& rText, long nIndex );\n \/** Returns the text of an existing field. *\/\n const String& GetFieldText(long nIndex) const;\n\n \/** Inserts a field using the specified pixel position.\n @param rPos The coordinates to insert the field.\n @param rnIndex The new index of the field is returned here.\n @return TRUE, if the field has been created. *\/\n BOOL AddField( const String& rText, const Point& rPos, long& rnIndex );\n \/** Calculates the field index at a specific pixel position.\n @param rnIndex The index of the field is returned here.\n @return TRUE, if the index value is valid. *\/\n BOOL GetFieldIndex( const Point& rPos, long& rnIndex ) const;\n \/** Calculates a field index at a specific pixel position. Returns in every\n case the index of an existing field.\n @param rnIndex The index of the field is returned here.\n @return TRUE, if the index value is valid. *\/\n void GetExistingIndex( const Point& rPos, long& rnIndex );\n\n \/** Notifies this control that the offset of the first field has been changed.\n The control has to adjust the selection to keep the same field selected\n on scrolling with scrollbar. *\/\n void ModifySelectionOffset( long nOffsetDiff );\n \/** Selects the next field. Called i.e. after moving a field from SELECT area. *\/\n void SelectNext();\n\n \/** @return The name of the control without shortcut. *\/\n String GetName()const { return aName; }\n\n \/** @return The description of the control which is used for the accessibility objects. *\/\n String GetDescription()const;\n\n \/** Grabs focus and sets new selection. *\/\n void GrabFocusWithSel( long nIndex );\n\n \/** @return The type of the FieldWindow. *\/\n ScDPFieldType GetType() const { return eType; }\n};\n\n\/\/===================================================================\n\n#endif \/\/ SC_FIELDWND_HXX\n<commit_msg>INTEGRATION: CWS uaa02 (1.7.24); FILE MERGED 2003\/04\/22 08:15:03 mt 1.7.24.1: #108656# Moved Accessibility from drafts to final<commit_after>\/*************************************************************************\n *\n * $RCSfile: fieldwnd.hxx,v $\n *\n * $Revision: 1.9 $\n *\n * last change: $Author: vg $ $Date: 2003-04-24 17:16:24 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef SC_FIELDWND_HXX\n#define SC_FIELDWND_HXX\n\n\n#ifndef _SV_CTRL_HXX\n#include <vcl\/ctrl.hxx>\n#endif\n#ifndef _SV_FIXED_HXX\n#include <vcl\/fixed.hxx>\n#endif\n\n#ifndef _CPPUHELPER_WEAKREF_HXX_\n#include <cppuhelper\/weakref.hxx>\n#endif\n\n#define MAX_LABELS 256\n#define PAGE_SIZE 16 \/\/ count of visible fields for scrollbar\n#define LINE_SIZE 8 \/\/ count of fields per column for scrollbar\n#define MAX_FIELDS 8 \/\/ maximum count of fields for row\/col\/data area\n\n#define OWIDTH PivotGlobal::nObjWidth\n#define OHEIGHT PivotGlobal::nObjHeight\n#define SSPACE PivotGlobal::nSelSpace\n\nclass ScDPLayoutDlg;\nclass ScAccessibleDataPilotControl;\n\n\/\/===================================================================\n\n\/** Type of content area. *\/\nenum ScDPFieldType\n{\n TYPE_ROW, \/\/\/ Area for all row fields.\n TYPE_COL, \/\/\/ Area for all column fields.\n TYPE_DATA, \/\/\/ Area for all data fields.\n TYPE_SELECT \/\/\/ Selection area with all fields.\n};\n\n\/\/-------------------------------------------------------------------\n\n\/** Represents a field area in the DataPilot layout dialog. *\/\nclass ScDPFieldWindow : public Control\n{\nprivate:\n String aName; \/\/\/ name of the control, used in Accessibility\n ScDPLayoutDlg* pDlg; \/\/\/ Parent dialog.\n Rectangle aWndRect; \/\/\/ Area rectangle in pixels.\n FixedText* pFtCaption; \/\/\/ FixedText containing the name of the control.\n Point aTextPos; \/\/\/ Position of the caption text.\n String** aFieldArr; \/\/\/ Pointer to string array of the field names.\n ScDPFieldType eType; \/\/\/ Type of this area.\n Color aFaceColor; \/\/\/ Color for dialog background.\n Color aWinColor; \/\/\/ Color for window background.\n Color aTextColor; \/\/\/ Color for text in buttons.\n Color aWinTextColor; \/\/\/ Color for text in field windows.\n long nFieldSize; \/\/\/ Maximum count of fields.\n long nFieldCount; \/\/\/ Count of existing fields.\n long nFieldSelected; \/\/\/ Currently selected field.\n\n com::sun::star::uno::WeakReference< ::com::sun::star::accessibility::XAccessible > xAccessible;\n ScAccessibleDataPilotControl* pAccessible;\n\n \/** Initilize the object. *\/\n void Init();\n\n \/** Reads all needed style settings. *\/\n void GetStyleSettings();\n\n \/** Draws the background. *\/\n void DrawBackground( OutputDevice& rDev );\n \/** Draws a field into the specified rectangle. *\/\n void DrawField(\n OutputDevice& rDev,\n const Rectangle& rRect,\n const String& rText,\n BOOL bSelected );\n\n \/** @return TRUE, if the field index is inside of the control area. *\/\n BOOL IsValidIndex( long nIndex ) const;\n \/** @return TRUE, if the field with the given index exists. *\/\n BOOL IsExistingIndex( long nIndex ) const;\n \/** @return The new selection index after moving to the given direction. *\/\n long CalcNewFieldIndex( short nDX, short nDY ) const;\n\n \/** Sets selection to the field with index nIndex. *\/\n void SetSelection( long nIndex );\n \/** Sets selection to first field. *\/\n void SetSelectionHome();\n \/** Sets selection to last field. *\/\n void SetSelectionEnd();\n \/** Sets selection to new position relative to current. *\/\n void MoveSelection( USHORT nKeyCode, short nDX, short nDY );\n\n \/** Moves the selected field to nDestIndex. *\/\n void MoveField( long nDestIndex );\n \/** Moves the selected field to the given direction. *\/\n void MoveFieldRel( short nDX, short nDY );\n\nprotected:\n virtual void Paint( const Rectangle& rRect );\n virtual void DataChanged( const DataChangedEvent& rDCEvt );\n virtual void MouseButtonDown( const MouseEvent& rMEvt );\n virtual void MouseButtonUp( const MouseEvent& rMEvt );\n virtual void MouseMove( const MouseEvent& rMEvt );\n virtual void KeyInput( const KeyEvent& rKEvt );\n virtual void GetFocus();\n virtual void LoseFocus();\n virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible > CreateAccessible();\n\npublic:\n ScDPFieldWindow(\n ScDPLayoutDlg* pDialog,\n const ResId& rResId,\n ScDPFieldType eFieldType,\n FixedText* pFtFieldCaption );\n ScDPFieldWindow(\n ScDPLayoutDlg* pDialog,\n const ResId& rResId,\n ScDPFieldType eFieldType,\n const String& aName );\n virtual ~ScDPFieldWindow();\n\n \/** Draws the complete control. *\/\n void Redraw();\n\n \/** @return The pixel position of a field (without bound check). *\/\n Point GetFieldPosition( long nIndex ) const;\n \/** @return The pixel size of a field. *\/\n Size GetFieldSize() const;\n\n \/** @return The index of the selected field. *\/\n inline BOOL IsEmpty() const { return nFieldCount == 0; }\n \/** @return The index of the selected field. *\/\n inline long GetSelectedField() const { return nFieldSelected; }\n \/** @return The pixel position of the last possible field. *\/\n Point GetLastPosition() const;\n\n \/** @return The count of existing fields. *\/\n long GetFieldCount() const { return nFieldCount; }\n \/** Inserts a field to the specified index. *\/\n void AddField( const String& rText, long nNewIndex );\n \/** Removes a field from the specified index. *\/\n void DelField( long nDelIndex );\n \/** Removes all fields. *\/\n void ClearFields();\n \/** Changes the text on an existing field. *\/\n void SetFieldText( const String& rText, long nIndex );\n \/** Returns the text of an existing field. *\/\n const String& GetFieldText(long nIndex) const;\n\n \/** Inserts a field using the specified pixel position.\n @param rPos The coordinates to insert the field.\n @param rnIndex The new index of the field is returned here.\n @return TRUE, if the field has been created. *\/\n BOOL AddField( const String& rText, const Point& rPos, long& rnIndex );\n \/** Calculates the field index at a specific pixel position.\n @param rnIndex The index of the field is returned here.\n @return TRUE, if the index value is valid. *\/\n BOOL GetFieldIndex( const Point& rPos, long& rnIndex ) const;\n \/** Calculates a field index at a specific pixel position. Returns in every\n case the index of an existing field.\n @param rnIndex The index of the field is returned here.\n @return TRUE, if the index value is valid. *\/\n void GetExistingIndex( const Point& rPos, long& rnIndex );\n\n \/** Notifies this control that the offset of the first field has been changed.\n The control has to adjust the selection to keep the same field selected\n on scrolling with scrollbar. *\/\n void ModifySelectionOffset( long nOffsetDiff );\n \/** Selects the next field. Called i.e. after moving a field from SELECT area. *\/\n void SelectNext();\n\n \/** @return The name of the control without shortcut. *\/\n String GetName()const { return aName; }\n\n \/** @return The description of the control which is used for the accessibility objects. *\/\n String GetDescription()const;\n\n \/** Grabs focus and sets new selection. *\/\n void GrabFocusWithSel( long nIndex );\n\n \/** @return The type of the FieldWindow. *\/\n ScDPFieldType GetType() const { return eType; }\n};\n\n\/\/===================================================================\n\n#endif \/\/ SC_FIELDWND_HXX\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: tphf.cxx,v $\n *\n * $Revision: 1.1.1.1 $\n *\n * last change: $Author: hr $ $Date: 2000-09-18 16:45:04 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifdef PCH\n#include \"ui_pch.hxx\"\n#endif\n\n#pragma hdrstop\n\n\/\/------------------------------------------------------------------\n\n#define _TPHF_CXX\n#include \"scitems.hxx\"\n#include <sfx2\/basedlgs.hxx>\n#include <svtools\/style.hxx>\n#include <vcl\/svapp.hxx>\n#include <vcl\/msgbox.hxx>\n\n#include \"tphf.hxx\"\n#include \"sc.hrc\"\n#include \"globstr.hrc\"\n#include \"tabvwsh.hxx\"\n#include \"viewdata.hxx\"\n#include \"document.hxx\"\n#include \"tphfedit.hxx\"\n#include \"hfedtdlg.hxx\"\n#include \"styledlg.hxx\"\n#include \"scresid.hxx\"\n\n#undef _TPHF_CXX\n\n\n\n\/\/==================================================================\n\/\/ class ScHFPage\n\/\/==================================================================\n\nScHFPage::ScHFPage( Window* pParent, USHORT nResId,\n const SfxItemSet& rSet, USHORT nSetId )\n\n : SvxHFPage ( pParent, nResId, rSet, nSetId ),\n aBtnEdit ( this, ScResId( RID_SCBTN_HFEDIT ) ),\n aDataSet ( *rSet.GetPool(),\n ATTR_PAGE_HEADERLEFT, ATTR_PAGE_FOOTERRIGHT,\n ATTR_PAGE, ATTR_PAGE, 0 ),\n nPageUsage ( (USHORT)SVX_PAGE_ALL ),\n pStyleDlg ( NULL )\n{\n SetExchangeSupport();\n\n SfxViewShell* pSh = SfxViewShell::Current();\n ScTabViewShell* pViewSh = PTR_CAST(ScTabViewShell,pSh);\n Point aPos( aBackgroundBtn.GetPosPixel() );\n\n aPos.Y() -= 8;\n aBackgroundBtn.SetPosPixel( aPos );\n\n aPos.Y() += aBackgroundBtn.GetSizePixel().Height();\n aPos.Y() += 4;\n aBtnEdit.SetPosPixel( aPos );\n aBtnEdit.Show();\n\n aDataSet.Put( rSet );\n\n if ( pViewSh )\n {\n ScViewData* pViewData = pViewSh->GetViewData();\n ScDocument* pDoc = pViewData->GetDocument();\n\n aStrPageStyle = pDoc->GetPageStyle( pViewData->GetTabNo() );\n }\n\n aBtnEdit.SetClickHdl ( LINK( this, ScHFPage, BtnHdl ) );\n aTurnOnBox.SetClickHdl ( LINK( this, ScHFPage, TurnOnHdl ) );\n\n if ( nId == SID_ATTR_PAGE_HEADERSET )\n aBtnEdit.SetHelpId( HID_SC_HEADER_EDIT );\n else\n aBtnEdit.SetHelpId( HID_SC_FOOTER_EDIT );\n}\n\n\/\/------------------------------------------------------------------\n\n__EXPORT ScHFPage::~ScHFPage()\n{\n}\n\n\/\/------------------------------------------------------------------\n\nvoid __EXPORT ScHFPage::Reset( const SfxItemSet& rSet )\n{\n SvxHFPage::Reset( rSet );\n TurnOnHdl( 0 );\n}\n\n\/\/------------------------------------------------------------------\n\nBOOL __EXPORT ScHFPage::FillItemSet( SfxItemSet& rOutSet )\n{\n BOOL bResult = SvxHFPage::FillItemSet( rOutSet );\n\n if ( nId == SID_ATTR_PAGE_HEADERSET )\n {\n rOutSet.Put( aDataSet.Get( ATTR_PAGE_HEADERLEFT ) );\n rOutSet.Put( aDataSet.Get( ATTR_PAGE_HEADERRIGHT ) );\n }\n else\n {\n rOutSet.Put( aDataSet.Get( ATTR_PAGE_FOOTERLEFT ) );\n rOutSet.Put( aDataSet.Get( ATTR_PAGE_FOOTERRIGHT ) );\n }\n\n return bResult;\n}\n\n\/\/------------------------------------------------------------------\n\nvoid __EXPORT ScHFPage::ActivatePage( const SfxItemSet& rSet )\n{\n USHORT nPageWhich = GetWhich( SID_ATTR_PAGE );\n const SvxPageItem& rPageItem = (const SvxPageItem&)\n rSet.Get(nPageWhich);\n\n nPageUsage = rPageItem.GetPageUsage();\n\n if ( pStyleDlg )\n aStrPageStyle = pStyleDlg->GetStyleSheet().GetName();\n\n aDataSet.Put( rSet.Get(ATTR_PAGE) );\n\n SvxHFPage::ActivatePage( rSet );\n}\n\n\/\/------------------------------------------------------------------\n\nint __EXPORT ScHFPage::DeactivatePage( SfxItemSet* pSet )\n{\n if ( LEAVE_PAGE == SvxHFPage::DeactivatePage( pSet ) )\n if ( pSet )\n FillItemSet( *pSet );\n\n return LEAVE_PAGE;\n}\n\n\/\/------------------------------------------------------------------\n\/\/ Handler:\n\/\/------------------------------------------------------------------\n\nIMPL_LINK( ScHFPage, TurnOnHdl, CheckBox*, EMPTYARG )\n{\n SvxHFPage::TurnOnHdl( &aTurnOnBox );\n\n if ( aTurnOnBox.IsChecked() )\n aBtnEdit.Enable();\n else\n aBtnEdit.Disable();\n\n return NULL;\n}\n\n\n\/\/------------------------------------------------------------------\n\nIMPL_LINK( ScHFPage, BtnHdl, PushButton*, EMPTYARG )\n{\n \/\/ Wenn der Bearbeiten-Dialog direkt aus dem Click-Handler des Buttons\n \/\/ aufgerufen wird, funktioniert im Bearbeiten-Dialog unter OS\/2 das\n \/\/ GrabFocus nicht (Bug #41805#).\n \/\/ Mit dem neuen StarView sollte dieser Workaround wieder raus koennen!\n\n Application::PostUserEvent( LINK( this, ScHFPage, HFEditHdl ) );\n return 0;\n}\n\nIMPL_LINK( ScHFPage, HFEditHdl, void*, EMPTYARG )\n{\n SfxViewShell* pViewSh = SfxViewShell::Current();\n\n if ( !pViewSh )\n {\n DBG_ERROR( \"Current ViewShell not found.\" );\n return NULL;\n }\n\n if ( aCntSharedBox.IsEnabled()\n && !aCntSharedBox.IsChecked() )\n {\n USHORT nResId = ( nId == SID_ATTR_PAGE_HEADERSET )\n ? RID_SCDLG_HFED_HEADER\n : RID_SCDLG_HFED_FOOTER;\n\n ScHFEditDlg* pDlg\n = new ScHFEditDlg( pViewSh->GetViewFrame(), this,\n aDataSet, aStrPageStyle, nResId );\n\n if ( pDlg->Execute() == RET_OK )\n {\n aDataSet.Put( *pDlg->GetOutputItemSet() );\n }\n\n delete pDlg;\n }\n else\n {\n String aText;\n SfxSingleTabDialog* pDlg\n = new SfxSingleTabDialog( pViewSh->GetViewFrame(), this,\n aDataSet, 42, FALSE );\n BOOL bRightPage = aCntSharedBox.IsChecked()\n || ( SVX_PAGE_LEFT != SvxPageUsage(nPageUsage) );\n\n if ( nId == SID_ATTR_PAGE_HEADERSET )\n {\n aText = ScGlobal::GetRscString( STR_PAGEHEADER );\n if ( bRightPage )\n pDlg->SetTabPage( ScRightHeaderEditPage::Create( pDlg, aDataSet ) );\n else\n pDlg->SetTabPage( ScLeftHeaderEditPage::Create( pDlg, aDataSet ) );\n }\n else\n {\n aText = ScGlobal::GetRscString( STR_PAGEFOOTER );\n if ( bRightPage )\n pDlg->SetTabPage( ScRightFooterEditPage::Create( pDlg, aDataSet ) );\n else\n pDlg->SetTabPage( ScLeftFooterEditPage::Create( pDlg, aDataSet ) );\n }\n\n SvxNumType eNumType = ((const SvxPageItem&)aDataSet.Get(ATTR_PAGE)).GetNumType();\n ((ScHFEditPage*)pDlg->GetTabPage())->SetNumType(eNumType);\n\n aText.AppendAscii(RTL_CONSTASCII_STRINGPARAM( \" (\" ));\n aText += ScGlobal::GetRscString( STR_PAGESTYLE );\n aText.AppendAscii(RTL_CONSTASCII_STRINGPARAM( \": \" ));\n aText += aStrPageStyle;\n aText += ')';\n\n pDlg->SetText( aText );\n\n if ( pDlg->Execute() == RET_OK )\n {\n aDataSet.Put( *pDlg->GetOutputItemSet() );\n }\n\n delete pDlg;\n }\n\n return NULL;\n}\n\n\/\/==================================================================\n\/\/ class ScHeaderPage\n\/\/==================================================================\n\nScHeaderPage::ScHeaderPage( Window* pParent, const SfxItemSet& rSet )\n : ScHFPage( pParent, RID_SVXPAGE_HEADER, rSet, SID_ATTR_PAGE_HEADERSET )\n{\n}\n\n\/\/------------------------------------------------------------------\n\nSfxTabPage* __EXPORT ScHeaderPage::Create( Window* pParent, const SfxItemSet& rCoreSet )\n{\n return ( new ScHeaderPage( pParent, rCoreSet ) );\n}\n\n\/\/------------------------------------------------------------------\n\nUSHORT* __EXPORT ScHeaderPage::GetRanges()\n{\n return SvxHeaderPage::GetRanges();\n}\n\n\/\/==================================================================\n\/\/ class ScFooterPage\n\/\/==================================================================\n\nScFooterPage::ScFooterPage( Window* pParent, const SfxItemSet& rSet )\n : ScHFPage( pParent, RID_SVXPAGE_FOOTER, rSet, SID_ATTR_PAGE_FOOTERSET )\n{\n}\n\n\/\/------------------------------------------------------------------\n\nSfxTabPage* __EXPORT ScFooterPage::Create( Window* pParent, const SfxItemSet& rCoreSet )\n{\n return ( new ScFooterPage( pParent, rCoreSet ) );\n}\n\n\/\/------------------------------------------------------------------\n\nUSHORT* __EXPORT ScFooterPage::GetRanges()\n{\n return SvxHeaderPage::GetRanges();\n}\n\n\n\n\n<commit_msg>edit button is right of background button instead of below it<commit_after>\/*************************************************************************\n *\n * $RCSfile: tphf.cxx,v $\n *\n * $Revision: 1.2 $\n *\n * last change: $Author: nn $ $Date: 2001-03-01 14:10:17 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifdef PCH\n#include \"ui_pch.hxx\"\n#endif\n\n#pragma hdrstop\n\n\/\/------------------------------------------------------------------\n\n#define _TPHF_CXX\n#include \"scitems.hxx\"\n#include <sfx2\/basedlgs.hxx>\n#include <svtools\/style.hxx>\n#include <vcl\/svapp.hxx>\n#include <vcl\/msgbox.hxx>\n\n#include \"tphf.hxx\"\n#include \"sc.hrc\"\n#include \"globstr.hrc\"\n#include \"tabvwsh.hxx\"\n#include \"viewdata.hxx\"\n#include \"document.hxx\"\n#include \"tphfedit.hxx\"\n#include \"hfedtdlg.hxx\"\n#include \"styledlg.hxx\"\n#include \"scresid.hxx\"\n\n#undef _TPHF_CXX\n\n\n\n\/\/==================================================================\n\/\/ class ScHFPage\n\/\/==================================================================\n\nScHFPage::ScHFPage( Window* pParent, USHORT nResId,\n const SfxItemSet& rSet, USHORT nSetId )\n\n : SvxHFPage ( pParent, nResId, rSet, nSetId ),\n aBtnEdit ( this, ScResId( RID_SCBTN_HFEDIT ) ),\n aDataSet ( *rSet.GetPool(),\n ATTR_PAGE_HEADERLEFT, ATTR_PAGE_FOOTERRIGHT,\n ATTR_PAGE, ATTR_PAGE, 0 ),\n nPageUsage ( (USHORT)SVX_PAGE_ALL ),\n pStyleDlg ( NULL )\n{\n SetExchangeSupport();\n\n SfxViewShell* pSh = SfxViewShell::Current();\n ScTabViewShell* pViewSh = PTR_CAST(ScTabViewShell,pSh);\n Point aPos( aBackgroundBtn.GetPosPixel() );\n\n \/\/ aBackgroundBtn position not changed anymore\n\n aPos.X() += aBackgroundBtn.GetSizePixel().Width();\n aPos.X() += 6;\n aBtnEdit.SetPosPixel( aPos );\n aBtnEdit.Show();\n\n aDataSet.Put( rSet );\n\n if ( pViewSh )\n {\n ScViewData* pViewData = pViewSh->GetViewData();\n ScDocument* pDoc = pViewData->GetDocument();\n\n aStrPageStyle = pDoc->GetPageStyle( pViewData->GetTabNo() );\n }\n\n aBtnEdit.SetClickHdl ( LINK( this, ScHFPage, BtnHdl ) );\n aTurnOnBox.SetClickHdl ( LINK( this, ScHFPage, TurnOnHdl ) );\n\n if ( nId == SID_ATTR_PAGE_HEADERSET )\n aBtnEdit.SetHelpId( HID_SC_HEADER_EDIT );\n else\n aBtnEdit.SetHelpId( HID_SC_FOOTER_EDIT );\n}\n\n\/\/------------------------------------------------------------------\n\n__EXPORT ScHFPage::~ScHFPage()\n{\n}\n\n\/\/------------------------------------------------------------------\n\nvoid __EXPORT ScHFPage::Reset( const SfxItemSet& rSet )\n{\n SvxHFPage::Reset( rSet );\n TurnOnHdl( 0 );\n}\n\n\/\/------------------------------------------------------------------\n\nBOOL __EXPORT ScHFPage::FillItemSet( SfxItemSet& rOutSet )\n{\n BOOL bResult = SvxHFPage::FillItemSet( rOutSet );\n\n if ( nId == SID_ATTR_PAGE_HEADERSET )\n {\n rOutSet.Put( aDataSet.Get( ATTR_PAGE_HEADERLEFT ) );\n rOutSet.Put( aDataSet.Get( ATTR_PAGE_HEADERRIGHT ) );\n }\n else\n {\n rOutSet.Put( aDataSet.Get( ATTR_PAGE_FOOTERLEFT ) );\n rOutSet.Put( aDataSet.Get( ATTR_PAGE_FOOTERRIGHT ) );\n }\n\n return bResult;\n}\n\n\/\/------------------------------------------------------------------\n\nvoid __EXPORT ScHFPage::ActivatePage( const SfxItemSet& rSet )\n{\n USHORT nPageWhich = GetWhich( SID_ATTR_PAGE );\n const SvxPageItem& rPageItem = (const SvxPageItem&)\n rSet.Get(nPageWhich);\n\n nPageUsage = rPageItem.GetPageUsage();\n\n if ( pStyleDlg )\n aStrPageStyle = pStyleDlg->GetStyleSheet().GetName();\n\n aDataSet.Put( rSet.Get(ATTR_PAGE) );\n\n SvxHFPage::ActivatePage( rSet );\n}\n\n\/\/------------------------------------------------------------------\n\nint __EXPORT ScHFPage::DeactivatePage( SfxItemSet* pSet )\n{\n if ( LEAVE_PAGE == SvxHFPage::DeactivatePage( pSet ) )\n if ( pSet )\n FillItemSet( *pSet );\n\n return LEAVE_PAGE;\n}\n\n\/\/------------------------------------------------------------------\n\/\/ Handler:\n\/\/------------------------------------------------------------------\n\nIMPL_LINK( ScHFPage, TurnOnHdl, CheckBox*, EMPTYARG )\n{\n SvxHFPage::TurnOnHdl( &aTurnOnBox );\n\n if ( aTurnOnBox.IsChecked() )\n aBtnEdit.Enable();\n else\n aBtnEdit.Disable();\n\n return NULL;\n}\n\n\n\/\/------------------------------------------------------------------\n\nIMPL_LINK( ScHFPage, BtnHdl, PushButton*, EMPTYARG )\n{\n \/\/ Wenn der Bearbeiten-Dialog direkt aus dem Click-Handler des Buttons\n \/\/ aufgerufen wird, funktioniert im Bearbeiten-Dialog unter OS\/2 das\n \/\/ GrabFocus nicht (Bug #41805#).\n \/\/ Mit dem neuen StarView sollte dieser Workaround wieder raus koennen!\n\n Application::PostUserEvent( LINK( this, ScHFPage, HFEditHdl ) );\n return 0;\n}\n\nIMPL_LINK( ScHFPage, HFEditHdl, void*, EMPTYARG )\n{\n SfxViewShell* pViewSh = SfxViewShell::Current();\n\n if ( !pViewSh )\n {\n DBG_ERROR( \"Current ViewShell not found.\" );\n return NULL;\n }\n\n if ( aCntSharedBox.IsEnabled()\n && !aCntSharedBox.IsChecked() )\n {\n USHORT nResId = ( nId == SID_ATTR_PAGE_HEADERSET )\n ? RID_SCDLG_HFED_HEADER\n : RID_SCDLG_HFED_FOOTER;\n\n ScHFEditDlg* pDlg\n = new ScHFEditDlg( pViewSh->GetViewFrame(), this,\n aDataSet, aStrPageStyle, nResId );\n\n if ( pDlg->Execute() == RET_OK )\n {\n aDataSet.Put( *pDlg->GetOutputItemSet() );\n }\n\n delete pDlg;\n }\n else\n {\n String aText;\n SfxSingleTabDialog* pDlg\n = new SfxSingleTabDialog( pViewSh->GetViewFrame(), this,\n aDataSet, 42, FALSE );\n BOOL bRightPage = aCntSharedBox.IsChecked()\n || ( SVX_PAGE_LEFT != SvxPageUsage(nPageUsage) );\n\n if ( nId == SID_ATTR_PAGE_HEADERSET )\n {\n aText = ScGlobal::GetRscString( STR_PAGEHEADER );\n if ( bRightPage )\n pDlg->SetTabPage( ScRightHeaderEditPage::Create( pDlg, aDataSet ) );\n else\n pDlg->SetTabPage( ScLeftHeaderEditPage::Create( pDlg, aDataSet ) );\n }\n else\n {\n aText = ScGlobal::GetRscString( STR_PAGEFOOTER );\n if ( bRightPage )\n pDlg->SetTabPage( ScRightFooterEditPage::Create( pDlg, aDataSet ) );\n else\n pDlg->SetTabPage( ScLeftFooterEditPage::Create( pDlg, aDataSet ) );\n }\n\n SvxNumType eNumType = ((const SvxPageItem&)aDataSet.Get(ATTR_PAGE)).GetNumType();\n ((ScHFEditPage*)pDlg->GetTabPage())->SetNumType(eNumType);\n\n aText.AppendAscii(RTL_CONSTASCII_STRINGPARAM( \" (\" ));\n aText += ScGlobal::GetRscString( STR_PAGESTYLE );\n aText.AppendAscii(RTL_CONSTASCII_STRINGPARAM( \": \" ));\n aText += aStrPageStyle;\n aText += ')';\n\n pDlg->SetText( aText );\n\n if ( pDlg->Execute() == RET_OK )\n {\n aDataSet.Put( *pDlg->GetOutputItemSet() );\n }\n\n delete pDlg;\n }\n\n return NULL;\n}\n\n\/\/==================================================================\n\/\/ class ScHeaderPage\n\/\/==================================================================\n\nScHeaderPage::ScHeaderPage( Window* pParent, const SfxItemSet& rSet )\n : ScHFPage( pParent, RID_SVXPAGE_HEADER, rSet, SID_ATTR_PAGE_HEADERSET )\n{\n}\n\n\/\/------------------------------------------------------------------\n\nSfxTabPage* __EXPORT ScHeaderPage::Create( Window* pParent, const SfxItemSet& rCoreSet )\n{\n return ( new ScHeaderPage( pParent, rCoreSet ) );\n}\n\n\/\/------------------------------------------------------------------\n\nUSHORT* __EXPORT ScHeaderPage::GetRanges()\n{\n return SvxHeaderPage::GetRanges();\n}\n\n\/\/==================================================================\n\/\/ class ScFooterPage\n\/\/==================================================================\n\nScFooterPage::ScFooterPage( Window* pParent, const SfxItemSet& rSet )\n : ScHFPage( pParent, RID_SVXPAGE_FOOTER, rSet, SID_ATTR_PAGE_FOOTERSET )\n{\n}\n\n\/\/------------------------------------------------------------------\n\nSfxTabPage* __EXPORT ScFooterPage::Create( Window* pParent, const SfxItemSet& rCoreSet )\n{\n return ( new ScFooterPage( pParent, rCoreSet ) );\n}\n\n\/\/------------------------------------------------------------------\n\nUSHORT* __EXPORT ScFooterPage::GetRanges()\n{\n return SvxHeaderPage::GetRanges();\n}\n\n\n\n\n<|endoftext|>"} {"text":"<commit_before><commit_msg>coverity#708099 unused mTypeClass member<commit_after><|endoftext|>"} {"text":"<commit_before>#include<iostream>\n#include<fstream>\n#include<string>\n#include<vector>\n\/*to do:\n\tfinish prerequisites function: figure out every topic you need to learn before you can learn a specified topic\n\tfigure out what other functions might be useful\n\tpopulate datastructures.txt more, change name to something better like programming.txt or w\/e\n\timplement student files(just a list of known topics)\n\timplement interface for users to specify a student file so knows is automatically run with it\n*\/\nstruct rdnode {\n\tpublic:\n\tstd::string topic;\n\tstd::vector<rdnode*> parents;\n\tstd::vector<rdnode*> children;\n\tbool knows;\n};\n\nstruct database {\n\tstd::vector<rdnode*> nodes;\n};\n\nvoid learnable (database* points) {\n\trdnode* temp;\n\tstd::vector<rdnode*> learn;\n\tbool learnability = true;\n\tfor (int count = 0; count < points->nodes.size(); count++) {\n\t\tlearnability = true;\n\t\ttemp = points->nodes[count];\n\t\tif (temp->knows == false) {\n\t\t\trdnode* parent;\n\t\t\tfor (int counter = 0; counter < temp->parents.size() && learnability == true; counter++) {\n\t\t\t\tparent = temp->parents[counter];\n\t\t\t\tif (parent->knows == false) {\n\t\t\t\t\tlearnability = false;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (learnability == true) {\n\t\t\t\tlearn.push_back(temp);\n\t\t\t}\n\t\t}\n\t}\n\tstd::cout << \"You can learn: \" << learn.size() << \" topics.\" << std::endl;\n\tfor (int count = 0; count < learn.size(); count++) {\n\t\ttemp = learn[count];\n\t\tstd::cout << temp->topic << \" \" << std::endl;\n\t}\n}\n\nvoid depopulate(database* points) {\n\trdnode* delnode;\n\tfor (int count = 0; count < points->nodes.size(); count++) {\n\t\tdelnode = points->nodes[count];\n\t\tdelete delnode;\n\t}\n\tdelete points;\n}\n\nrdnode* makenode(std::string topicname, database* points) {\n\trdnode* tempnode;\n\tfor (int count = 0; count < points->nodes.size(); count++) {\n\t\ttempnode = points->nodes[count];\n\t\tif (tempnode->topic == topicname) {\n\t\t\treturn tempnode;\n\t\t}\n\t}\n\trdnode* newnode = new rdnode;\n\tnewnode->topic = topicname;\n\tnewnode->knows = false;\n\tpoints->nodes.push_back(newnode);\n\treturn newnode;\n}\n\nvoid knowsr(rdnode* temp) {\n\trdnode* thing;\n\tbool ask = true;\n\tfor (int count = 0; count < temp->children.size(); count++) {\n\t\tthing = temp->children[count];\n\t\trdnode* third;\n\t\tfor (int counter = 0; count < thing->parents.size(); count++) {\n\t\t\tthird = thing->parents[count];\n\t\t\tif (third->knows == false) {\n\t\t\t\task = false;\n\t\t\t}\n\t\t}\n\t\tif (ask == true) {\n\t\t\tstd::cout << \"Do you understand \" << thing->topic << \" (y\/n)?\" << std::endl;\n\t\t\tchar answer;\n\t\t\tstd::cin >> answer;\n\t\t\tif (answer != 'y' && answer != 'n') {\n\t\t\t\tstd::cout << \"try again\" << std::endl;\n\t\t\t}\n\t\t\tif (answer == 'y') {\n\t\t\t\tthing->knows = true;\n\t\t\t}\n\t\t}\n\t\task = false;\n\t}\n}\n\nvoid knows(database* points) {\n\trdnode* temp;\n\tchar answer;\n\tfor (int count = 0; count < points->nodes.size(); count++) {\n\t\ttemp = points->nodes[count];\n\t\tif (temp->parents.size() == 0) {\n\t\t\tstd::cout << \"Do you understand \" << temp->topic << \" (y\/n)?\" << std::endl;\n\t\t\tstd::cin >> answer;\n\t\t\tif (answer != 'y' && answer != 'n') {\n\t\t\t\tstd::cout << \"try again\" << std::endl;\n\t\t\t\tcount--;\n\t\t\t}\n\t\t\tif (answer == 'y') {\n\t\t\t\ttemp->knows = true;\n\t\t\t\tknowsr(temp);\n\t\t\t}\n\t\t}\t\t\n\t}\n}\n\nvoid populate(char filename[], database* points) {\n\tstd::vector<std::string> conf;\n\tstd::ifstream inputconf(filename);\n\tstd::string line;\n\twhile (getline (inputconf, line)) {\n\t\tconf.push_back(line);\n\t}\n\tinputconf.close();\n\tfor (int counter = 0; counter < conf.size(); counter++) {\n\t\tline = conf[counter];\n\t\trdnode* tempnode;\n\t\tstd::string currstring;\n\t\tint count = 0;\n\t\tstd::vector<rdnode*> parenting;\n\t\tfor(; count < line.size(); count++) {\n\t\t\tif (line[count] != ',' && line[count] != '#') {\n\t\t\t\tcurrstring.push_back(line[count]);\n\t\t\t}\n\t\t\tif (line[count] == ',' || line[count] == '#') {\n\t\t\t\ttempnode = makenode(currstring, points);\n\t\t\t\tcurrstring.clear();\n\t\t\t\tparenting.push_back(tempnode);\n\t\t\t}\n\t\t\tif (line[count] == '#') {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tcount++;\n\t\tfor (; count < line.size(); count++) {\n\t\t\tcurrstring.push_back(line[count]);\n\t\t}\n\t\ttempnode = makenode(currstring, points);\n\t\trdnode* currentparent;\n\t\tbool add = true;\n\t\tfor (count = 0; count < parenting.size(); count++) {\n\t\t\tcurrentparent = parenting[count];\n\t\t\tfor (int counter = 0; counter < tempnode->parents.size(); counter++) {\n\t\t\t\tif (tempnode->parents[counter] == currentparent) {\n\t\t\t\t\tadd = false;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (add == true) {\n\t\t\t\ttempnode->parents.push_back(parenting[count]);\n\t\t\t\tcurrentparent->children.push_back(tempnode);\n\t\t\t}\n\t\t}\n\t}\n}\n\nvoid printall(database* points) {\n\trdnode* temp;\n\tfor (int count = 0; count < points->nodes.size(); count++) {\n\t\ttemp = points->nodes[count];\n\t\tstd::cout << temp->topic << std::endl;\n\t}\n}\n\nvoid rmknows(database* points) {\n\trdnode* temp;\n\tfor (int count = 0; count < points->nodes.size(); count++) {\n\t\ttemp = points->nodes[count];\n\t\ttemp->knows = false;\n\t}\n}\n\nvoid student(database* points) {\n\tstd::cout << \"Enter name of student file.\" << std::endl;\n\tstd::vector<std::string> person;\n\tchar filename[30];\n\tstd::cin >> filename;\n\tstd::ifstream inputconf(filename);\n\tstd::string line;\n\twhile (getline (inputconf, line)) {\n\t\tperson.push_back(line);\n\t}\n\tinputconf.close();\n\trdnode* tempnode;\n\tbool finishloop = false;\n\tfor (int count = 0; count < person.size(); count++) {\n\t\tfor (int counter = 0; counter < points->nodes.size() && finishloop == false; counter++) {\n\t\t\ttempnode = points->nodes[counter];\n\t\t\tif (tempnode->topic == person[count]) {\n\t\t\t\ttempnode->knows = true;\n\t\t\t\tfinishloop = true;\n\t\t\t}\n\t\t}\n\t\tfinishloop = false;\n\t}\n}\n\nvoid prerequisites(database* points) {\n\tstd::string topicname;\n\tstd::cin >> topicname;\n\trdnode* node;\n\tbool assigned = false;\n\tfor (int count = 0; count < points->nodes.size() && assigned == false; count++) {\n\t\tnode = points->nodes[count];\n\t\tif (node->topic == topicname) {\n\t\t\tassigned = true;\n\t\t}\n\t}\n\tif (assigned == false) {\n\t\tstd::cout << \"That topic isn't in the database. You may have spelled or formatted it incorrectly; make sure all your letters are lowercase.\" << std::endl;\n\t}\n}\n\nint main() {\n\tchar filename[30];\n\tstd::cout << \"Enter file name for database.\" << std::endl;\n\tstd::cin >> filename;\n\tdatabase* points = new database;\n\tpopulate(filename, points);\n\t\/\/printall(points); \/\/this is useless except for debugging\n\tbool keeplooping = true;\n\tstd::cout << \"Do you have a student file? (y\/n)?\" << std::endl;\n\tchar answer;\n\tstd::cin >> answer;\n\tif (answer == 'y') {\n\t\tstudent(points);\n\t}\n\telse {\n\t\tknows(points);\n\t}\n\twhile (keeplooping) {\n\t\tstd::cout << \"Your options: Change student (a), List all learnable topics for current student (b), Find out what you need to learn before you can learn a specified topic (c)\" << std::endl;\n\t\tstd::cin >> answer;\n\t\tif (answer == 'a') {\n\t\t\trmknows(points);\n\t\t\tstd::cout << \"Do you have a student file? (y\/n)?\" << std::endl;\n\t\t\tchar answer;\n\t\t\tstd::cin >> answer;\n\t\t\tif (answer == 'y') {\n\t\t\t\tstudent(points);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tknows(points);\n\t\t\t}\n\t\t}\n\t\tif (answer == 'b') {\n\t\t\tlearnable(points);\n\t\t}\n\t\tif (answer == 'c') {\n\t\t\tprerequisites(points);\n\t\t}\n\t}\n\tdepopulate(points);\n\treturn 0;\n}\n<commit_msg>Update learning.cpp<commit_after>#include<iostream>\n#include<fstream>\n#include<string>\n#include<vector>\n\/*to do:\n\tfigure out what other functions might be useful\n\tpopulate datastructures.txt more, change name to something better like programming.txt or w\/e\n*\/\nstruct rdnode {\n\tpublic:\n\tstd::string topic;\n\tstd::vector<rdnode*> parents;\n\tstd::vector<rdnode*> children;\n\tbool knows;\n};\n\nstruct database {\n\tstd::vector<rdnode*> nodes;\n};\n\nvoid learnable (database* points) {\n\trdnode* temp;\n\tstd::vector<rdnode*> learn;\n\tbool learnability = true;\n\tfor (int count = 0; count < points->nodes.size(); count++) {\n\t\tlearnability = true;\n\t\ttemp = points->nodes[count];\n\t\tif (temp->knows == false) {\n\t\t\trdnode* parent;\n\t\t\tfor (int counter = 0; counter < temp->parents.size() && learnability == true; counter++) {\n\t\t\t\tparent = temp->parents[counter];\n\t\t\t\tif (parent->knows == false) {\n\t\t\t\t\tlearnability = false;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (learnability == true) {\n\t\t\t\tlearn.push_back(temp);\n\t\t\t}\n\t\t}\n\t}\n\tstd::cout << \"You can learn: \" << learn.size() << \" topics.\" << std::endl;\n\tfor (int count = 0; count < learn.size(); count++) {\n\t\ttemp = learn[count];\n\t\tstd::cout << temp->topic << \" \" << std::endl;\n\t}\n}\n\nvoid depopulate(database* points) {\n\trdnode* delnode;\n\tfor (int count = 0; count < points->nodes.size(); count++) {\n\t\tdelnode = points->nodes[count];\n\t\tdelete delnode;\n\t}\n\tdelete points;\n}\n\nrdnode* makenode(std::string topicname, database* points) {\n\trdnode* tempnode;\n\tfor (int count = 0; count < points->nodes.size(); count++) {\n\t\ttempnode = points->nodes[count];\n\t\tif (tempnode->topic == topicname) {\n\t\t\treturn tempnode;\n\t\t}\n\t}\n\trdnode* newnode = new rdnode;\n\tnewnode->topic = topicname;\n\tnewnode->knows = false;\n\tpoints->nodes.push_back(newnode);\n\treturn newnode;\n}\n\nvoid knowsr(rdnode* temp) {\n\trdnode* thing;\n\tbool ask = true;\n\tfor (int count = 0; count < temp->children.size(); count++) {\n\t\tthing = temp->children[count];\n\t\trdnode* third;\n\t\tfor (int counter = 0; count < thing->parents.size(); count++) {\n\t\t\tthird = thing->parents[count];\n\t\t\tif (third->knows == false) {\n\t\t\t\task = false;\n\t\t\t}\n\t\t}\n\t\tif (ask == true) {\n\t\t\tstd::cout << \"Do you understand \" << thing->topic << \" (y\/n)?\" << std::endl;\n\t\t\tchar answer;\n\t\t\tstd::cin >> answer;\n\t\t\tif (answer != 'y' && answer != 'n') {\n\t\t\t\tstd::cout << \"try again\" << std::endl;\n\t\t\t}\n\t\t\tif (answer == 'y') {\n\t\t\t\tthing->knows = true;\n\t\t\t}\n\t\t}\n\t\task = false;\n\t}\n}\n\nvoid knows(database* points) {\n\trdnode* temp;\n\tchar answer;\n\tfor (int count = 0; count < points->nodes.size(); count++) {\n\t\ttemp = points->nodes[count];\n\t\tif (temp->parents.size() == 0) {\n\t\t\tstd::cout << \"Do you understand \" << temp->topic << \" (y\/n)?\" << std::endl;\n\t\t\tstd::cin >> answer;\n\t\t\tif (answer != 'y' && answer != 'n') {\n\t\t\t\tstd::cout << \"try again\" << std::endl;\n\t\t\t\tcount--;\n\t\t\t}\n\t\t\tif (answer == 'y') {\n\t\t\t\ttemp->knows = true;\n\t\t\t\tknowsr(temp);\n\t\t\t}\n\t\t}\t\t\n\t}\n}\n\nvoid populate(char filename[], database* points) {\n\tstd::vector<std::string> conf;\n\tstd::ifstream inputconf(filename);\n\tstd::string line;\n\twhile (getline (inputconf, line)) {\n\t\tconf.push_back(line);\n\t}\n\tinputconf.close();\n\tfor (int counter = 0; counter < conf.size(); counter++) {\n\t\tline = conf[counter];\n\t\trdnode* tempnode;\n\t\tstd::string currstring;\n\t\tint count = 0;\n\t\tstd::vector<rdnode*> parenting;\n\t\tfor(; count < line.size(); count++) {\n\t\t\tif (line[count] != ',' && line[count] != '#') {\n\t\t\t\tcurrstring.push_back(line[count]);\n\t\t\t}\n\t\t\tif (line[count] == ',' || line[count] == '#') {\n\t\t\t\ttempnode = makenode(currstring, points);\n\t\t\t\tcurrstring.clear();\n\t\t\t\tparenting.push_back(tempnode);\n\t\t\t}\n\t\t\tif (line[count] == '#') {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tcount++;\n\t\tfor (; count < line.size(); count++) {\n\t\t\tcurrstring.push_back(line[count]);\n\t\t}\n\t\ttempnode = makenode(currstring, points);\n\t\trdnode* currentparent;\n\t\tbool add = true;\n\t\tfor (count = 0; count < parenting.size(); count++) {\n\t\t\tcurrentparent = parenting[count];\n\t\t\tfor (int counter = 0; counter < tempnode->parents.size(); counter++) {\n\t\t\t\tif (tempnode->parents[counter] == currentparent) {\n\t\t\t\t\tadd = false;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (add == true) {\n\t\t\t\ttempnode->parents.push_back(parenting[count]);\n\t\t\t\tcurrentparent->children.push_back(tempnode);\n\t\t\t}\n\t\t}\n\t}\n}\n\nvoid printall(database* points) {\n\trdnode* temp;\n\tfor (int count = 0; count < points->nodes.size(); count++) {\n\t\ttemp = points->nodes[count];\n\t\tstd::cout << temp->topic << std::endl;\n\t}\n}\n\nvoid rmknows(database* points) {\n\trdnode* temp;\n\tfor (int count = 0; count < points->nodes.size(); count++) {\n\t\ttemp = points->nodes[count];\n\t\ttemp->knows = false;\n\t}\n}\n\nvoid student(database* points) {\n\tstd::cout << \"Enter name of student file.\" << std::endl;\n\tstd::vector<std::string> person;\n\tchar filename[30];\n\tstd::cin >> filename;\n\tstd::ifstream inputconf(filename);\n\tstd::string line;\n\twhile (getline (inputconf, line)) {\n\t\tperson.push_back(line);\n\t}\n\tinputconf.close();\n\trdnode* tempnode;\n\tbool finishloop = false;\n\tfor (int count = 0; count < person.size(); count++) {\n\t\tfor (int counter = 0; counter < points->nodes.size() && finishloop == false; counter++) {\n\t\t\ttempnode = points->nodes[counter];\n\t\t\tif (tempnode->topic == person[count]) {\n\t\t\t\ttempnode->knows = true;\n\t\t\t\tfinishloop = true;\n\t\t\t}\n\t\t}\n\t\tfinishloop = false;\n\t}\n}\n\nstd::vector<std::string> prerequisites(rdnode* node, database* points) {\n\tstd::vector<std::string> needtoknow;\n\trdnode* parent;\n\tfor (int count = 0; count < node->parents.size(); count++) {\n\t\tparent = node->parents[count];\n\t\tif (parent->knows == false) {\n\t\t\tneedtoknow.push_back(parent->topic);\n\t\t\tstd::vector<std::string> alsoneed = prerequisites(parent, points);\n\t\t\tfor (int counter = 0; counter < alsoneed.size(); counter++) {\n\t\t\t\tneedtoknow.push_back(alsoneed[counter]);\n\t\t\t}\n\t\t}\n\t}\n\treturn needtoknow;\n}\n\nint main() {\n\tchar filename[30];\n\tstd::cout << \"Enter file name for database.\" << std::endl;\n\tstd::cin >> filename;\n\tdatabase* points = new database;\n\tpopulate(filename, points);\n\t\/\/printall(points); \/\/this is useless except for debugging\n\tbool keeplooping = true;\n\tstd::cout << \"Do you have a student file? (y\/n)?\" << std::endl;\n\tchar answer;\n\tstd::cin >> answer;\n\tif (answer == 'y') {\n\t\tstudent(points);\n\t}\n\telse {\n\t\tknows(points);\n\t}\n\twhile (keeplooping) {\n\t\tstd::cout << \"Your options: Change student (a), List all learnable topics for current student (b), Find out what you need to learn before you can learn a specified topic (c)\" << std::endl;\n\t\tstd::cin >> answer;\n\t\tif (answer == 'a') {\n\t\t\trmknows(points);\n\t\t\tstd::cout << \"Do you have a student file? (y\/n)?\" << std::endl;\n\t\t\tchar answer;\n\t\t\tstd::cin >> answer;\n\t\t\tif (answer == 'y') {\n\t\t\t\tstudent(points);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tknows(points);\n\t\t\t}\n\t\t}\n\t\tif (answer == 'b') {\n\t\t\tlearnable(points);\n\t\t}\n\t\tif (answer == 'c') {\n\t\t\tstd::string topicname;\n\t\t\tstd::cin >> topicname;\n\t\t\trdnode* node;\n\t\t\tbool assigned = false;\n\t\t\tfor (int count = 0; count < points->nodes.size() && assigned == false; count++) {\n\t\t\t\tnode = points->nodes[count];\n\t\t\t\tif (node->topic == topicname) {\n\t\t\t\t\tassigned = true;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (assigned == false) {\n\t\t\t\tstd::cout << \"That topic isn't in the database. You may have spelled or formatted it incorrectly; make sure all your letters are lowercase.\" << std::endl;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tprerequisites(node, points);\n\t\t\t}\n\t\t}\n\t}\n\tdepopulate(points);\n\treturn 0;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"lirch_plugin.h\"\n#include \"userlist_messages.h\"\n#include \"user_status.h\"\n#include \"received_messages.h\"\n\nusing namespace std;\n\nclass userlist_timer : public message_data\n{\npublic:\n\tvirtual std::unique_ptr<message_data> copy() const {return std::unique_ptr<message_data>(new userlist_timer(*this));}\n\tstatic message create(int m) {return message_create(\"userlist_timer\", new userlist_timer(m));}\n\n\tuserlist_timer(int m) : msecs(m) {}\n\n\tint msecs;\n};\n\nvoid run(plugin_pipe p, string name)\n{\n\tp.write(registration_message::create(0, name, \"userlist_request\"));\n\tp.write(registration_message::create(0, name, \"userlist_timer\"));\n\tp.write(registration_message::create(30000, name, \"received\"));\n\tp.write(registration_message::create(30000, name, \"received_me\"));\n\tunordered_map<QString, user_status> statuses;\n\twhile (true)\n\t{\n\t\tmessage m=p.blocking_read();\n\t\tif (m.type==\"shutdown\")\n\t\t{\n\t\t\treturn;\n\t\t}\n\t\telse if (m.type==\"registration_status\")\n\t\t{\n\t\t\tauto s=dynamic_cast<registration_status *>(m.getdata());\n\t\t\tif (!s)\n\t\t\t\tcontinue;\n\t\t\tif (!s->status)\n\t\t\t{\n\t\t\t\tif ((0>=s->priority && s->priority>-200) || (30000>=s->priority && s->priority>29000))\n\t\t\t\t\tp.write(registration_message::create(s->priority-1, name, s->type));\n\t\t\t\telse\n\t\t\t\t\treturn;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tif (s->type==\"userlist_timer\")\n\t\t\t\t\tp.write(userlist_timer::create(10000));\n\t\t\t}\n\t\t}\n\t\telse if (m.type==\"userlist_request\")\n\t\t{\n\t\t\tp.write(userlist_message::create(statuses));\n\t\t}\n\t\telse if (m.type==\"userlist_timer\")\n\t\t{\n\t\t\tauto s=dynamic_cast<userlist_timer *>(m.getdata());\n\t\t\tif (!s)\n\t\t\t\tcontinue;\n\t\t\ttime_t now=time(NULL);\n\t\t\t\/\/Remove all nicks that haven't been seen in 2 minutes\n\t\t\tdecltype(statuses.begin()) i;\n\t\t\twhile ((i=std::find_if(statuses.begin(), statuses.end(), [now](const std::pair<const QString &, const user_status &> &p) {return p.second.lastseen<now-2*60;}))!=statuses.end())\n\t\t\t\tstatuses.erase(i);\n\t\t\tp.write(userlist_message::create(statuses));\n\t\t\tp.write(userlist_timer::create(s->msecs));\n\t\t}\n\t\telse if (m.type==\"received\")\n\t\t{\n\t\t\tauto s=dynamic_cast<received_message *>(m.getdata());\n\t\t\tif (!s)\n\t\t\t\tcontinue;\n\t\t\tp.write(m.decrement_priority());\n\t\t\tstatuses[s->nick].nick=s->nick;\n\t\t\tstatuses[s->nick].channels.insert(s->channel);\n\t\t\tstatuses[s->nick].ip=s->ipAddress;\n\t\t\tstatuses[s->nick].lastseen=time(NULL);\n\t\t}\n\t\telse if (m.type==\"received_me\")\n\t\t{\n\t\t\tauto s=dynamic_cast<received_me_message *>(m.getdata());\n\t\t\tif (!s)\n\t\t\t\tcontinue;\n\t\t\tp.write(m.decrement_priority());\n\t\t\tstatuses[s->nick].nick=s->nick;\n\t\t\tstatuses[s->nick].channels.insert(s->channel);\n\t\t\tstatuses[s->nick].ip=s->ipAddress;\n\t\t\tstatuses[s->nick].lastseen=time(NULL);\n\t\t}\n\t\telse\n\t\t\tp.write(m.decrement_priority());\n\t}\n}\n<commit_msg>Fixed a potential crash bug<commit_after>#include <thread>\n\n#include \"lirch_plugin.h\"\n#include \"userlist_messages.h\"\n#include \"user_status.h\"\n#include \"received_messages.h\"\n\nusing namespace std;\n\nclass userlist_timer : public message_data\n{\npublic:\n\tvirtual std::unique_ptr<message_data> copy() const {return std::unique_ptr<message_data>(new userlist_timer(*this));}\n\tstatic message create(int m) {return message_create(\"userlist_timer\", new userlist_timer(m));}\n\n\tuserlist_timer(int m) : msecs(m) {}\n\n\tint msecs;\n};\n\nvoid run(plugin_pipe p, string name)\n{\n\tp.write(registration_message::create(0, name, \"userlist_request\"));\n\tp.write(registration_message::create(0, name, \"userlist_timer\"));\n\tp.write(registration_message::create(30000, name, \"received\"));\n\tp.write(registration_message::create(30000, name, \"received_me\"));\n\tunordered_map<QString, user_status> statuses;\n\twhile (true)\n\t{\n\t\tmessage m=p.blocking_read();\n\t\tif (m.type==\"shutdown\")\n\t\t{\n\t\t\treturn;\n\t\t}\n\t\telse if (m.type==\"registration_status\")\n\t\t{\n\t\t\tauto s=dynamic_cast<registration_status *>(m.getdata());\n\t\t\tif (!s)\n\t\t\t\tcontinue;\n\t\t\tif (!s->status)\n\t\t\t{\n\t\t\t\tif ((0>=s->priority && s->priority>-200) || (30000>=s->priority && s->priority>29000))\n\t\t\t\t\tp.write(registration_message::create(s->priority-1, name, s->type));\n\t\t\t\telse\n\t\t\t\t\treturn;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tif (s->type==\"userlist_timer\")\n\t\t\t\t\tp.write(userlist_timer::create(10000));\n\t\t\t}\n\t\t}\n\t\telse if (m.type==\"userlist_request\")\n\t\t{\n\t\t\tp.write(userlist_message::create(statuses));\n\t\t}\n\t\telse if (m.type==\"userlist_timer\")\n\t\t{\n\t\t\tauto s=dynamic_cast<userlist_timer *>(m.getdata());\n\t\t\tif (!s)\n\t\t\t\tcontinue;\n\t\t\ttime_t now=time(NULL);\n\t\t\t\/\/Remove all nicks that haven't been seen in 2 minutes\n\t\t\tdecltype(statuses.begin()) i;\n\t\t\twhile ((i=std::find_if(statuses.begin(), statuses.end(), [now](const std::pair<const QString &, const user_status &> &p) {return p.second.lastseen<now-2*60;}))!=statuses.end())\n\t\t\t\tstatuses.erase(i);\n\t\t\tp.write(userlist_message::create(statuses));\n\t\t\tint msecs=s->msecs;\n\t\t\tthread th([&p,msecs]()\n\t\t\t{\n\t\t\t\tplugin_pipe pp;\n\t\t\t\tthis_thread::sleep_for(chrono::milliseconds(msecs));\n\t\t\t\tpp.write(userlist_timer::create(msecs));\n\t\t\t});\n\t\t\tth.detach();\n\t\t}\n\t\telse if (m.type==\"received\")\n\t\t{\n\t\t\tauto s=dynamic_cast<received_message *>(m.getdata());\n\t\t\tif (!s)\n\t\t\t\tcontinue;\n\t\t\tp.write(m.decrement_priority());\n\t\t\tstatuses[s->nick].nick=s->nick;\n\t\t\tstatuses[s->nick].channels.insert(s->channel);\n\t\t\tstatuses[s->nick].ip=s->ipAddress;\n\t\t\tstatuses[s->nick].lastseen=time(NULL);\n\t\t}\n\t\telse if (m.type==\"received_me\")\n\t\t{\n\t\t\tauto s=dynamic_cast<received_me_message *>(m.getdata());\n\t\t\tif (!s)\n\t\t\t\tcontinue;\n\t\t\tp.write(m.decrement_priority());\n\t\t\tstatuses[s->nick].nick=s->nick;\n\t\t\tstatuses[s->nick].channels.insert(s->channel);\n\t\t\tstatuses[s->nick].ip=s->ipAddress;\n\t\t\tstatuses[s->nick].lastseen=time(NULL);\n\t\t}\n\t\telse\n\t\t\tp.write(m.decrement_priority());\n\t}\n}\n<|endoftext|>"} {"text":"<commit_before>\/******************************************************************************\n * ____ _ _____ *\n * \/ ___| \/ \\ | ___| C++ *\n * | | \/ _ \\ | |_ Actor *\n * | |___ \/ ___ \\| _| Framework *\n * \\____\/_\/ \\_|_| *\n * *\n * Copyright 2011-2018 Dominik Charousset *\n * *\n * Distributed under the terms and conditions of the BSD 3-Clause License or *\n * (at your option) under the terms and conditions of the Boost Software *\n * License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. *\n * *\n * If you did not receive a copy of the license files, see *\n * http:\/\/opensource.org\/licenses\/BSD-3-Clause and *\n * http:\/\/www.boost.org\/LICENSE_1_0.txt. *\n ******************************************************************************\/\n\n#include \"caf\/inbound_path.hpp\"\n\n#include \"caf\/send.hpp\"\n#include \"caf\/logger.hpp\"\n#include \"caf\/no_stages.hpp\"\n#include \"caf\/local_actor.hpp\"\n\nnamespace caf {\n\ninbound_path::stats_t::stats_t() : ring_iter(0) {\n measurement x{0, timespan{0}};\n measurements.resize(stats_sampling_size, x);\n}\n\nauto inbound_path::stats_t::calculate(timespan c, timespan d)\n -> calculation_result {\n \/\/ Max throughput = C * (N \/ t), where C = cycle length, N = measured items,\n \/\/ and t = measured time. Desired batch size is the same formula with D\n \/\/ instead of C.\n long total_ns = 0;\n long total_items = 0;\n for (auto& x : measurements) {\n total_ns += static_cast<long>(x.calculation_time.count());\n total_items += x.batch_size;\n }\n if (total_ns == 0)\n return {1, 1};\n \/\/ Instead of C * (N \/ t) we calculate N * (C \/ t) to avoid imprecisions due\n \/\/ to double rounding for very small numbers.\n auto ct = static_cast<double>(c.count()) \/ total_ns;\n auto dt = static_cast<double>(d.count()) \/ total_ns;\n return {std::max(static_cast<long>(total_items * ct), 1l),\n std::max(static_cast<long>(total_items * dt), 1l)};\n}\n\nvoid inbound_path::stats_t::store(measurement x) {\n measurements[ring_iter] = x;\n ring_iter = (ring_iter + 1) % stats_sampling_size;\n}\n\ninbound_path::inbound_path(stream_manager_ptr mgr_ptr, stream_slots id,\n strong_actor_ptr ptr)\n : mgr(std::move(mgr_ptr)),\n hdl(std::move(ptr)),\n slots(id),\n assigned_credit(0),\n prio(stream_priority::normal),\n last_acked_batch_id(0),\n last_batch_id(0) {\n mgr->register_input_path(this);\n}\n\ninbound_path::~inbound_path() {\n mgr->deregister_input_path(this);\n}\n\nvoid inbound_path::handle(downstream_msg::batch& x) {\n CAF_LOG_TRACE(CAF_ARG(slots) << CAF_ARG(x));\n auto batch_size = x.xs_size;\n assigned_credit -= batch_size;\n last_batch_id = x.id;\n auto& clock = mgr->self()->clock();\n auto t0 = clock.now();\n mgr->handle(this, x);\n auto t1 = clock.now();\n auto dt = clock.difference(atom(\"batch\"), batch_size, t0, t1);\n stats.store({batch_size, dt});\n mgr->push();\n}\n\nvoid inbound_path::emit_ack_open(local_actor* self, actor_addr rebind_from) {\n CAF_LOG_TRACE(CAF_ARG(slots) << CAF_ARG(rebind_from));\n assigned_credit = 50; \/\/ TODO: put constant in some header\n int32_t desired_batch_size = 50; \/\/ TODO: put constant in some header\n unsafe_send_as(self, hdl,\n make<upstream_msg::ack_open>(\n slots.invert(), self->address(), std::move(rebind_from),\n self->ctrl(), static_cast<int32_t>(assigned_credit),\n desired_batch_size));\n}\n\nvoid inbound_path::emit_ack_batch(local_actor* self, long queued_items,\n timespan cycle, timespan complexity) {\n CAF_LOG_TRACE(CAF_ARG(slots) << CAF_ARG(queued_items) << CAF_ARG(cycle)\n << CAF_ARG(complexity));\n if (last_acked_batch_id == last_batch_id)\n return;\n auto x = stats.calculate(cycle, complexity);\n \/\/ Hand out enough credit to fill our queue for 2 cycles.\n auto credit = std::max((x.max_throughput * 2)\n - (assigned_credit - queued_items),\n 0l);\n auto batch_size = static_cast<int32_t>(x.items_per_batch);\n if (credit != 0)\n assigned_credit += credit;\n CAF_LOG_DEBUG(CAF_ARG(credit) << CAF_ARG(batch_size));\n unsafe_send_as(self, hdl,\n make<upstream_msg::ack_batch>(slots.invert(), self->address(),\n static_cast<int32_t>(credit),\n batch_size, last_batch_id));\n last_acked_batch_id = last_batch_id;\n}\n\nvoid inbound_path::emit_regular_shutdown(local_actor* self) {\n CAF_LOG_TRACE(CAF_ARG(slots));\n unsafe_send_as(self, hdl, make<upstream_msg::drop>(slots, self->address()));\n}\n\nvoid inbound_path::emit_irregular_shutdown(local_actor* self, error reason) {\n CAF_LOG_TRACE(CAF_ARG(slots) << CAF_ARG(reason));\n unsafe_send_as(self, hdl,\n make<upstream_msg::forced_drop>(\n slots.invert(), self->address(), std::move(reason)));\n}\n\nvoid inbound_path::emit_irregular_shutdown(local_actor* self,\n stream_slots slots,\n const strong_actor_ptr& hdl,\n error reason) {\n unsafe_send_as(self, hdl,\n make<upstream_msg::forced_drop>(\n slots.invert(), self->address(), std::move(reason)));\n}\n\n} \/\/ namespace caf\n<commit_msg>Replace magic numbers with constants<commit_after>\/******************************************************************************\n * ____ _ _____ *\n * \/ ___| \/ \\ | ___| C++ *\n * | | \/ _ \\ | |_ Actor *\n * | |___ \/ ___ \\| _| Framework *\n * \\____\/_\/ \\_|_| *\n * *\n * Copyright 2011-2018 Dominik Charousset *\n * *\n * Distributed under the terms and conditions of the BSD 3-Clause License or *\n * (at your option) under the terms and conditions of the Boost Software *\n * License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. *\n * *\n * If you did not receive a copy of the license files, see *\n * http:\/\/opensource.org\/licenses\/BSD-3-Clause and *\n * http:\/\/www.boost.org\/LICENSE_1_0.txt. *\n ******************************************************************************\/\n\n#include \"caf\/inbound_path.hpp\"\n\n#include \"caf\/send.hpp\"\n#include \"caf\/logger.hpp\"\n#include \"caf\/no_stages.hpp\"\n#include \"caf\/local_actor.hpp\"\n\nnamespace caf {\n\ninbound_path::stats_t::stats_t() : ring_iter(0) {\n measurement x{0, timespan{0}};\n measurements.resize(stats_sampling_size, x);\n}\n\nauto inbound_path::stats_t::calculate(timespan c, timespan d)\n -> calculation_result {\n \/\/ Max throughput = C * (N \/ t), where C = cycle length, N = measured items,\n \/\/ and t = measured time. Desired batch size is the same formula with D\n \/\/ instead of C.\n long total_ns = 0;\n long total_items = 0;\n for (auto& x : measurements) {\n total_ns += static_cast<long>(x.calculation_time.count());\n total_items += x.batch_size;\n }\n if (total_ns == 0)\n return {1, 1};\n \/\/ Instead of C * (N \/ t) we calculate N * (C \/ t) to avoid imprecisions due\n \/\/ to double rounding for very small numbers.\n auto ct = static_cast<double>(c.count()) \/ total_ns;\n auto dt = static_cast<double>(d.count()) \/ total_ns;\n return {std::max(static_cast<long>(total_items * ct), 1l),\n std::max(static_cast<long>(total_items * dt), 1l)};\n}\n\nvoid inbound_path::stats_t::store(measurement x) {\n measurements[ring_iter] = x;\n ring_iter = (ring_iter + 1) % stats_sampling_size;\n}\n\ninbound_path::inbound_path(stream_manager_ptr mgr_ptr, stream_slots id,\n strong_actor_ptr ptr)\n : mgr(std::move(mgr_ptr)),\n hdl(std::move(ptr)),\n slots(id),\n assigned_credit(0),\n prio(stream_priority::normal),\n last_acked_batch_id(0),\n last_batch_id(0) {\n mgr->register_input_path(this);\n}\n\ninbound_path::~inbound_path() {\n mgr->deregister_input_path(this);\n}\n\nvoid inbound_path::handle(downstream_msg::batch& x) {\n CAF_LOG_TRACE(CAF_ARG(slots) << CAF_ARG(x));\n auto batch_size = x.xs_size;\n assigned_credit -= batch_size;\n last_batch_id = x.id;\n auto& clock = mgr->self()->clock();\n auto t0 = clock.now();\n mgr->handle(this, x);\n auto t1 = clock.now();\n auto dt = clock.difference(atom(\"batch\"), batch_size, t0, t1);\n stats.store({batch_size, dt});\n mgr->push();\n}\n\nvoid inbound_path::emit_ack_open(local_actor* self, actor_addr rebind_from) {\n CAF_LOG_TRACE(CAF_ARG(slots) << CAF_ARG(rebind_from));\n assigned_credit = initial_credit;\n int32_t desired_batch_size = initial_credit;\n unsafe_send_as(self, hdl,\n make<upstream_msg::ack_open>(\n slots.invert(), self->address(), std::move(rebind_from),\n self->ctrl(), static_cast<int32_t>(assigned_credit),\n desired_batch_size));\n}\n\nvoid inbound_path::emit_ack_batch(local_actor* self, long queued_items,\n timespan cycle, timespan complexity) {\n CAF_LOG_TRACE(CAF_ARG(slots) << CAF_ARG(queued_items) << CAF_ARG(cycle)\n << CAF_ARG(complexity));\n if (last_acked_batch_id == last_batch_id)\n return;\n auto x = stats.calculate(cycle, complexity);\n \/\/ Hand out enough credit to fill our queue for 2 cycles.\n auto credit = std::max((x.max_throughput * 2)\n - (assigned_credit - queued_items),\n 0l);\n auto batch_size = static_cast<int32_t>(x.items_per_batch);\n if (credit != 0)\n assigned_credit += credit;\n CAF_LOG_DEBUG(CAF_ARG(credit) << CAF_ARG(batch_size));\n unsafe_send_as(self, hdl,\n make<upstream_msg::ack_batch>(slots.invert(), self->address(),\n static_cast<int32_t>(credit),\n batch_size, last_batch_id));\n last_acked_batch_id = last_batch_id;\n}\n\nvoid inbound_path::emit_regular_shutdown(local_actor* self) {\n CAF_LOG_TRACE(CAF_ARG(slots));\n unsafe_send_as(self, hdl, make<upstream_msg::drop>(slots, self->address()));\n}\n\nvoid inbound_path::emit_irregular_shutdown(local_actor* self, error reason) {\n CAF_LOG_TRACE(CAF_ARG(slots) << CAF_ARG(reason));\n unsafe_send_as(self, hdl,\n make<upstream_msg::forced_drop>(\n slots.invert(), self->address(), std::move(reason)));\n}\n\nvoid inbound_path::emit_irregular_shutdown(local_actor* self,\n stream_slots slots,\n const strong_actor_ptr& hdl,\n error reason) {\n unsafe_send_as(self, hdl,\n make<upstream_msg::forced_drop>(\n slots.invert(), self->address(), std::move(reason)));\n}\n\n} \/\/ namespace caf\n<|endoftext|>"} {"text":"<commit_before>\/*****************************************************************************\n * Copyright (C) 2011-2015 Michael Ira Krufky\n *\n * Author: Michael Ira Krufky <mkrufky@linuxtv.org>\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n *\n *****************************************************************************\/\n\n#include \"table.h\"\n\nusing namespace dvbtee::decode;\n\nTableComponent::TableComponent(Decoder *parent, std::string &name)\n : Decoder(parent, name)\n , descriptors(this)\n{\n\t\/\/\n}\n\nTableComponent::~TableComponent()\n{\n\t\/\/\n}\n\n\nTableBase::TableBase(Decoder *parent, std::string &name, uint8_t tableid)\n : TableComponent(parent, name)\n , m_watcher(NULL)\n , m_tableid(tableid)\n{\n\t\/\/\n}\n\nTableBase::TableBase(Decoder *parent, std::string &name, uint8_t tableid, TableWatcher *watcher)\n : TableComponent(parent, name)\n , m_watcher(watcher)\n , m_tableid(tableid)\n{\n\n}\n\nTableBase::~TableBase()\n{\n\t\/\/\n}\n\nuint8_t TableBase::getTableid()\n{\n\treturn m_tableid;\n}\n\n\nTable::Table(Decoder *parent, std::string &name, uint8_t tableid)\n : TableBase(parent, name, tableid)\n{\n\t\/\/\n}\n\nTable::Table(Decoder *parent, std::string &name, uint8_t tableid, TableWatcher *watcher)\n : TableBase(parent, name, tableid, watcher)\n{\n\t\/\/\n}\n\nTable::~Table()\n{\n\t\/\/\n}\n\n\nbool TableRegistry::registerFactory(uint8_t tableid, TableBaseFactory *factory)\n{\n\tpthread_mutex_lock(&m_mutex);\n\n\tif (m_factories.count(tableid)) {\n\t\tpthread_mutex_unlock(&m_mutex);\n\t\treturn false;\n\t}\n\n\tm_factories.insert( std::pair<uint8_t, TableBaseFactory*>(tableid,factory) );\n\n\tfprintf(stderr, \"inserted 0x%02x, %p, %ld table decoders present\\n\", tableid, factory, m_factories.size());\n\n\tpthread_mutex_unlock(&m_mutex);\n\treturn true;\n}\n\nTableBaseFactory *TableRegistry::getFactory(uint8_t tableid)\n{\n\tpthread_mutex_lock(&m_mutex);\n\n\tif (!m_factories.count(tableid)) {\n\t\tpthread_mutex_unlock(&m_mutex);\n\t\treturn NULL;\n\t}\n\n\tTableBaseFactory* ret = m_factories[tableid];\n\n\tpthread_mutex_unlock(&m_mutex);\n\n\treturn ret;\n}\n\n\nTableRegistry::TableRegistry()\n{\n\tpthread_mutex_init(&m_mutex, 0);\n}\n\nTableRegistry::~TableRegistry()\n{\n\tpthread_mutex_destroy(&m_mutex);\n}\n\nTableRegistry &TableRegistry::instance()\n{\n\tstatic TableRegistry INSTANCE;\n\treturn INSTANCE;\n}\n\nTableStore::TableStore(Decoder *parent)\n : m_parent(parent)\n{\n\t\/\/\n}\n\nTableStore::~TableStore()\n{\n\t\/\/\n}\n\n#if PsiTable_CONSTRUCTORTEMPLATE\nbool TableStore::add(uint8_t id, PsiTable p_table)\n#else\nbool TableStore::add(uint8_t id, PsiTable &p_table)\n#endif\n{\n\tTable *t = NULL;\n\n\tTableBaseFactory* f = TableRegistry::instance().getFactory(id);\n\tif (f) t = f->create(m_parent, p_table);\n\n\tif (t) m_store.insert( std::pair<uint8_t, Table*>(t->getTableid(), t) );\n\treturn (t != NULL);\n}\n\n#if PsiTable_CONSTRUCTORTEMPLATE\nbool TableStore::add(uint8_t id, PsiTable inTable, TableWatcher *watcher)\n#else\nbool TableStore::add(uint8_t id, PsiTable &inTable, TableWatcher *watcher)\n#endif\n{\n\tTable *t = NULL;\n\n\tTableBaseFactory* f = TableRegistry::instance().getFactory(id);\n\tif (f) t = f->create(m_parent, inTable, watcher);\n\n\tif (t) m_store.insert( std::pair<uint8_t, Table*>(t->getTableid(), t) );\n\treturn (t != NULL);\n}\n\n\nstd::vector<Table *> TableStore::get(uint8_t tableid)\n{\n\tstd::vector<Table *> ret;\n\tstd::pair <std::multimap<uint8_t, Table*>::iterator, std::multimap<uint8_t, Table*>::iterator> range;\n\n\trange = m_store.equal_range(tableid);\n\n\tfor (std::multimap<uint8_t, Table*>::iterator it=range.first; it!=range.second; ++it)\n\t\tret.push_back(it->second);\n\n\treturn ret;\n}\n<commit_msg>decode\/table: always set tableId property<commit_after>\/*****************************************************************************\n * Copyright (C) 2011-2015 Michael Ira Krufky\n *\n * Author: Michael Ira Krufky <mkrufky@linuxtv.org>\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n *\n *****************************************************************************\/\n\n#include \"table.h\"\n\nusing namespace dvbtee::decode;\n\nTableComponent::TableComponent(Decoder *parent, std::string &name)\n : Decoder(parent, name)\n , descriptors(this)\n{\n\t\/\/\n}\n\nTableComponent::~TableComponent()\n{\n\t\/\/\n}\n\n\nTableBase::TableBase(Decoder *parent, std::string &name, uint8_t tableid)\n : TableComponent(parent, name)\n , m_watcher(NULL)\n , m_tableid(tableid)\n{\n\tset(\"tableId\", m_tableid);\n}\n\nTableBase::TableBase(Decoder *parent, std::string &name, uint8_t tableid, TableWatcher *watcher)\n : TableComponent(parent, name)\n , m_watcher(watcher)\n , m_tableid(tableid)\n{\n\tset(\"tableId\", m_tableid);\n}\n\nTableBase::~TableBase()\n{\n\t\/\/\n}\n\nuint8_t TableBase::getTableid()\n{\n\treturn m_tableid;\n}\n\n\nTable::Table(Decoder *parent, std::string &name, uint8_t tableid)\n : TableBase(parent, name, tableid)\n{\n\t\/\/\n}\n\nTable::Table(Decoder *parent, std::string &name, uint8_t tableid, TableWatcher *watcher)\n : TableBase(parent, name, tableid, watcher)\n{\n\t\/\/\n}\n\nTable::~Table()\n{\n\t\/\/\n}\n\n\nbool TableRegistry::registerFactory(uint8_t tableid, TableBaseFactory *factory)\n{\n\tpthread_mutex_lock(&m_mutex);\n\n\tif (m_factories.count(tableid)) {\n\t\tpthread_mutex_unlock(&m_mutex);\n\t\treturn false;\n\t}\n\n\tm_factories.insert( std::pair<uint8_t, TableBaseFactory*>(tableid,factory) );\n\n\tfprintf(stderr, \"inserted 0x%02x, %p, %ld table decoders present\\n\", tableid, factory, m_factories.size());\n\n\tpthread_mutex_unlock(&m_mutex);\n\treturn true;\n}\n\nTableBaseFactory *TableRegistry::getFactory(uint8_t tableid)\n{\n\tpthread_mutex_lock(&m_mutex);\n\n\tif (!m_factories.count(tableid)) {\n\t\tpthread_mutex_unlock(&m_mutex);\n\t\treturn NULL;\n\t}\n\n\tTableBaseFactory* ret = m_factories[tableid];\n\n\tpthread_mutex_unlock(&m_mutex);\n\n\treturn ret;\n}\n\n\nTableRegistry::TableRegistry()\n{\n\tpthread_mutex_init(&m_mutex, 0);\n}\n\nTableRegistry::~TableRegistry()\n{\n\tpthread_mutex_destroy(&m_mutex);\n}\n\nTableRegistry &TableRegistry::instance()\n{\n\tstatic TableRegistry INSTANCE;\n\treturn INSTANCE;\n}\n\nTableStore::TableStore(Decoder *parent)\n : m_parent(parent)\n{\n\t\/\/\n}\n\nTableStore::~TableStore()\n{\n\t\/\/\n}\n\n#if PsiTable_CONSTRUCTORTEMPLATE\nbool TableStore::add(uint8_t id, PsiTable p_table)\n#else\nbool TableStore::add(uint8_t id, PsiTable &p_table)\n#endif\n{\n\tTable *t = NULL;\n\n\tTableBaseFactory* f = TableRegistry::instance().getFactory(id);\n\tif (f) t = f->create(m_parent, p_table);\n\n\tif (t) m_store.insert( std::pair<uint8_t, Table*>(t->getTableid(), t) );\n\treturn (t != NULL);\n}\n\n#if PsiTable_CONSTRUCTORTEMPLATE\nbool TableStore::add(uint8_t id, PsiTable inTable, TableWatcher *watcher)\n#else\nbool TableStore::add(uint8_t id, PsiTable &inTable, TableWatcher *watcher)\n#endif\n{\n\tTable *t = NULL;\n\n\tTableBaseFactory* f = TableRegistry::instance().getFactory(id);\n\tif (f) t = f->create(m_parent, inTable, watcher);\n\n\tif (t) m_store.insert( std::pair<uint8_t, Table*>(t->getTableid(), t) );\n\treturn (t != NULL);\n}\n\n\nstd::vector<Table *> TableStore::get(uint8_t tableid)\n{\n\tstd::vector<Table *> ret;\n\tstd::pair <std::multimap<uint8_t, Table*>::iterator, std::multimap<uint8_t, Table*>::iterator> range;\n\n\trange = m_store.equal_range(tableid);\n\n\tfor (std::multimap<uint8_t, Table*>::iterator it=range.first; it!=range.second; ++it)\n\t\tret.push_back(it->second);\n\n\treturn ret;\n}\n<|endoftext|>"} {"text":"<commit_before><commit_msg>fdo#83901: Write a test for this.<commit_after><|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: cbutton.hxx,v $\n *\n * $Revision: 1.5 $\n *\n * last change: $Author: hr $ $Date: 2007-06-26 11:50:17 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\/\/------------------------------------------------------------------\n\n#ifndef SC_CBUTTON_HXX\n#define SC_CBUTTON_HXX\n\n#ifndef _GEN_HXX \/\/autogen\n#include <tools\/gen.hxx>\n#endif\n\n#ifndef _TOOLS_COLOR_HXX\n#include <tools\/color.hxx>\n#endif\n\nclass OutputDevice;\n\n\n\/\/==================================================================\n\nclass ScDDComboBoxButton\n{\npublic:\n ScDDComboBoxButton( OutputDevice* pOutputDevice );\n ~ScDDComboBoxButton();\n\n void SetOutputDevice( OutputDevice* pOutputDevice );\n\n void Draw( const Point& rAt,\n const Size& rSize,\n BOOL bState,\n BOOL bBtnIn = FALSE );\n\n void Draw( const Point& rAt,\n BOOL bState,\n BOOL bBtnIn = FALSE )\n { Draw( rAt, aBtnSize, bState, bBtnIn ); }\n\n void Draw( BOOL bState,\n BOOL bBtnIn = FALSE )\n { Draw( aBtnPos, aBtnSize, bState, bBtnIn ); }\n\n void SetOptSizePixel();\n\n void SetPosPixel( const Point& rNewPos ) { aBtnPos = rNewPos; }\n Point GetPosPixel() const { return aBtnPos; }\n\n void SetSizePixel( const Size& rNewSize ) { aBtnSize = rNewSize; }\n Size GetSizePixel() const { return aBtnSize; }\n\nprivate:\n void ImpDrawArrow( const Rectangle& rRect,\n BOOL bState );\n\nprotected:\n OutputDevice* pOut;\n Point aBtnPos;\n Size aBtnSize;\n};\n\n\n#endif \/\/ SC_CBUTTON_HXX\n\n\n<commit_msg>INTEGRATION: CWS changefileheader (1.5.244); FILE MERGED 2008\/04\/01 15:30:50 thb 1.5.244.2: #i85898# Stripping all external header guards 2008\/03\/31 17:15:39 rt 1.5.244.1: #i87441# Change license header to LPGL v3.<commit_after>\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2008 by Sun Microsystems, Inc.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: cbutton.hxx,v $\n * $Revision: 1.6 $\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * <http:\/\/www.openoffice.org\/license.html>\n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n\/\/------------------------------------------------------------------\n\n#ifndef SC_CBUTTON_HXX\n#define SC_CBUTTON_HXX\n\n#include <tools\/gen.hxx>\n#include <tools\/color.hxx>\n\nclass OutputDevice;\n\n\n\/\/==================================================================\n\nclass ScDDComboBoxButton\n{\npublic:\n ScDDComboBoxButton( OutputDevice* pOutputDevice );\n ~ScDDComboBoxButton();\n\n void SetOutputDevice( OutputDevice* pOutputDevice );\n\n void Draw( const Point& rAt,\n const Size& rSize,\n BOOL bState,\n BOOL bBtnIn = FALSE );\n\n void Draw( const Point& rAt,\n BOOL bState,\n BOOL bBtnIn = FALSE )\n { Draw( rAt, aBtnSize, bState, bBtnIn ); }\n\n void Draw( BOOL bState,\n BOOL bBtnIn = FALSE )\n { Draw( aBtnPos, aBtnSize, bState, bBtnIn ); }\n\n void SetOptSizePixel();\n\n void SetPosPixel( const Point& rNewPos ) { aBtnPos = rNewPos; }\n Point GetPosPixel() const { return aBtnPos; }\n\n void SetSizePixel( const Size& rNewSize ) { aBtnSize = rNewSize; }\n Size GetSizePixel() const { return aBtnSize; }\n\nprivate:\n void ImpDrawArrow( const Rectangle& rRect,\n BOOL bState );\n\nprotected:\n OutputDevice* pOut;\n Point aBtnPos;\n Size aBtnSize;\n};\n\n\n#endif \/\/ SC_CBUTTON_HXX\n\n\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: undotab.hxx,v $\n *\n * $Revision: 1.6 $\n *\n * last change: $Author: hr $ $Date: 2004-02-03 12:43:07 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef SC_UNDOTAB_HXX\n#define SC_UNDOTAB_HXX\n\n#ifndef SC_UNDOBASE_HXX\n#include \"undobase.hxx\"\n#endif\n#ifndef SC_MARKDATA_HXX\n#include \"markdata.hxx\"\n#endif\n\n#ifndef _SVSTDARR_USHORTS\n\n#define _SVSTDARR_USHORTS\n#include <svtools\/svstdarr.hxx>\n\n#endif\n\n#ifndef _SVSTDARR_STRINGS\n\n#define _SVSTDARR_STRINGS\n#include <svtools\/svstdarr.hxx>\n\n#endif\n\nclass ScDocShell;\nclass ScDocument;\nclass SdrUndoAction;\nclass ScPrintRangeSaver;\nclass SdrObject;\n\n\/\/----------------------------------------------------------------------------\n\nclass ScUndoInsertTab : public ScSimpleUndo\n{\npublic:\n TYPEINFO();\n ScUndoInsertTab(\n ScDocShell* pNewDocShell,\n USHORT nTabNum,\n BOOL bApp,\n const String& rNewName);\n virtual ~ScUndoInsertTab();\n\n virtual void Undo();\n virtual void Redo();\n virtual void Repeat(SfxRepeatTarget& rTarget);\n virtual BOOL CanRepeat(SfxRepeatTarget& rTarget) const;\n\n virtual String GetComment() const;\n\nprivate:\n String sNewName;\n SdrUndoAction* pDrawUndo;\n ULONG nEndChangeAction;\n USHORT nTab;\n BOOL bAppend;\n\n void SetChangeTrack();\n};\n\nclass ScUndoInsertTables : public ScSimpleUndo\n{\npublic:\n TYPEINFO();\n ScUndoInsertTables(\n ScDocShell* pNewDocShell,\n USHORT nTabNum,\n BOOL bApp,\n SvStrings *pNewNameList);\n virtual ~ScUndoInsertTables();\n\n virtual void Undo();\n virtual void Redo();\n virtual void Repeat(SfxRepeatTarget& rTarget);\n virtual BOOL CanRepeat(SfxRepeatTarget& rTarget) const;\n\n virtual String GetComment() const;\n\nprivate:\n\n SdrUndoAction* pDrawUndo;\n SvStrings* pNameList;\n ULONG nStartChangeAction;\n ULONG nEndChangeAction;\n USHORT nTab;\n BOOL bAppend;\n\n void SetChangeTrack();\n};\n\n\nclass ScUndoDeleteTab: public ScMoveUndo \/\/ Draw vom Move fuer geloeschte Tabelle\n{\npublic:\n TYPEINFO();\n ScUndoDeleteTab(\n ScDocShell* pNewDocShell,\n const SvUShorts &theTabs, \/\/USHORT nNewTab,\n ScDocument* pUndoDocument,\n ScRefUndoData* pRefData );\n virtual ~ScUndoDeleteTab();\n\n virtual void Undo();\n virtual void Redo();\n virtual void Repeat(SfxRepeatTarget& rTarget);\n virtual BOOL CanRepeat(SfxRepeatTarget& rTarget) const;\n\n virtual String GetComment() const;\n\nprivate:\n SvUShorts theTabs;\n ULONG nStartChangeAction;\n ULONG nEndChangeAction;\n\n void SetChangeTrack();\n};\n\n\nclass ScUndoRenameTab: public ScSimpleUndo\n{\npublic:\n TYPEINFO();\n ScUndoRenameTab(\n ScDocShell* pNewDocShell,\n USHORT nT,\n const String& rOldName,\n const String& rNewName);\n virtual ~ScUndoRenameTab();\n\n virtual void Undo();\n virtual void Redo();\n virtual void Repeat(SfxRepeatTarget& rTarget);\n virtual BOOL CanRepeat(SfxRepeatTarget& rTarget) const;\n\n virtual String GetComment() const;\n\nprivate:\n USHORT nTab;\n String sOldName;\n String sNewName;\n\n void DoChange( USHORT nTab, const String& rName ) const;\n};\n\n\nclass ScUndoMoveTab: public ScSimpleUndo\n{\npublic:\n TYPEINFO();\n ScUndoMoveTab( ScDocShell* pNewDocShell,\n const SvUShorts &aOldTab,\n const SvUShorts &aNewTab);\n virtual ~ScUndoMoveTab();\n\n virtual void Undo();\n virtual void Redo();\n virtual void Repeat(SfxRepeatTarget& rTarget);\n virtual BOOL CanRepeat(SfxRepeatTarget& rTarget) const;\n\n virtual String GetComment() const;\n\nprivate:\n SvUShorts theOldTabs;\n SvUShorts theNewTabs;\n\n void DoChange( BOOL bUndo ) const;\n};\n\n\nclass ScUndoCopyTab: public ScSimpleUndo\n{\npublic:\n TYPEINFO();\n ScUndoCopyTab(ScDocShell* pNewDocShell,\n const SvUShorts &aOldTab,\n const SvUShorts &aNewTab);\n\n virtual ~ScUndoCopyTab();\n\n virtual void Undo();\n virtual void Redo();\n virtual void Repeat(SfxRepeatTarget& rTarget);\n virtual BOOL CanRepeat(SfxRepeatTarget& rTarget) const;\n\n virtual String GetComment() const;\n\nprivate:\n SdrUndoAction* pDrawUndo;\n SvUShorts theOldTabs;\n SvUShorts theNewTabs;\n\n void DoChange() const;\n};\n\n\nclass ScUndoMakeScenario: public ScSimpleUndo\n{\npublic:\n TYPEINFO();\n ScUndoMakeScenario(\n ScDocShell* pNewDocShell,\n USHORT nSrc, USHORT nDest,\n ScDocument* pUndo,\n const String& rN, const String& rC,\n const Color& rCol, USHORT nF,\n const ScMarkData& rMark );\n virtual ~ScUndoMakeScenario();\n\n virtual void Undo();\n virtual void Redo();\n virtual void Repeat(SfxRepeatTarget& rTarget);\n virtual BOOL CanRepeat(SfxRepeatTarget& rTarget) const;\n\n virtual String GetComment() const;\n\nprivate:\n USHORT nSrcTab;\n USHORT nDestTab;\n ScDocument* pUndoDoc;\n String aName;\n String aComment;\n Color aColor;\n USHORT nFlags;\n ScMarkData aMarkData;\n};\n\n\nclass ScUndoImportTab : public ScSimpleUndo\n{\npublic:\n TYPEINFO();\n ScUndoImportTab(\n ScDocShell* pShell,\n USHORT nNewTab, USHORT nNewCount,\n BOOL bNewLink );\n virtual ~ScUndoImportTab();\n\n virtual void Undo();\n virtual void Redo();\n virtual void Repeat(SfxRepeatTarget& rTarget);\n virtual BOOL CanRepeat(SfxRepeatTarget& rTarget) const;\n\n virtual String GetComment() const;\n\nprivate:\n USHORT nTab;\n USHORT nCount;\n BOOL bLink;\n ScDocument* pRedoDoc;\n SdrUndoAction* pDrawUndo;\n\n void DoChange() const;\n};\n\n\nclass ScUndoRemoveLink : public ScSimpleUndo\n{\npublic:\n TYPEINFO();\n ScUndoRemoveLink( \/\/ vor dem Loeschen aufrufen!\n ScDocShell* pShell,\n const String& rDoc );\n virtual ~ScUndoRemoveLink();\n\n virtual void Undo();\n virtual void Redo();\n virtual void Repeat(SfxRepeatTarget& rTarget);\n virtual BOOL CanRepeat(SfxRepeatTarget& rTarget) const;\n\n virtual String GetComment() const;\n\nprivate:\n String aDocName;\n String aFltName;\n String aOptions;\n ULONG nRefreshDelay;\n USHORT nCount;\n USHORT* pTabs;\n BYTE* pModes;\n String* pTabNames;\n\n void DoChange( BOOL bLink ) const;\n};\n\n\nclass ScUndoShowHideTab : public ScSimpleUndo\n{\npublic:\n TYPEINFO();\n ScUndoShowHideTab(\n ScDocShell* pShell,\n USHORT nNewTab, BOOL bNewShow );\n virtual ~ScUndoShowHideTab();\n\n virtual void Undo();\n virtual void Redo();\n virtual void Repeat(SfxRepeatTarget& rTarget);\n virtual BOOL CanRepeat(SfxRepeatTarget& rTarget) const;\n\n virtual String GetComment() const;\n\nprivate:\n USHORT nTab;\n BOOL bShow;\n\n void DoChange( BOOL bShow ) const;\n};\n\n\nclass ScUndoProtect : public ScSimpleUndo\n{\npublic:\n TYPEINFO();\n ScUndoProtect( ScDocShell* pShell, USHORT nNewTab,\n BOOL bNewProtect, const com::sun::star::uno::Sequence<sal_Int8>& rNewPassword );\n virtual ~ScUndoProtect();\n\n virtual void Undo();\n virtual void Redo();\n virtual void Repeat(SfxRepeatTarget& rTarget);\n virtual BOOL CanRepeat(SfxRepeatTarget& rTarget) const;\n\n virtual String GetComment() const;\n\nprivate:\n USHORT nTab;\n BOOL bProtect;\n com::sun::star::uno::Sequence<sal_Int8> aPassword;\n\n void DoProtect( BOOL bDo );\n};\n\n\nclass ScUndoPrintRange : public ScSimpleUndo\n{\npublic:\n TYPEINFO();\n ScUndoPrintRange( ScDocShell* pShell, USHORT nNewTab,\n ScPrintRangeSaver* pOld, ScPrintRangeSaver* pNew );\n virtual ~ScUndoPrintRange();\n\n virtual void Undo();\n virtual void Redo();\n virtual void Repeat(SfxRepeatTarget& rTarget);\n virtual BOOL CanRepeat(SfxRepeatTarget& rTarget) const;\n\n virtual String GetComment() const;\n\nprivate:\n USHORT nTab;\n ScPrintRangeSaver* pOldRanges;\n ScPrintRangeSaver* pNewRanges;\n\n void DoChange( BOOL bUndo );\n};\n\n\nclass ScUndoScenarioFlags: public ScSimpleUndo\n{\npublic:\n TYPEINFO();\n ScUndoScenarioFlags(\n ScDocShell* pNewDocShell, USHORT nT,\n const String& rON, const String& rNN,\n const String& rOC, const String& rNC,\n const Color& rOCol, const Color& rNCol,\n USHORT nOF, USHORT nNF );\n\n virtual ~ScUndoScenarioFlags();\n\n virtual void Undo();\n virtual void Redo();\n virtual void Repeat(SfxRepeatTarget& rTarget);\n virtual BOOL CanRepeat(SfxRepeatTarget& rTarget) const;\n\n virtual String GetComment() const;\n\nprivate:\n USHORT nTab;\n String aOldName;\n String aNewName;\n String aOldComment;\n String aNewComment;\n Color aOldColor;\n Color aNewColor;\n USHORT nOldFlags;\n USHORT nNewFlags;\n};\n\n\nclass ScUndoRenameObject: public ScSimpleUndo\n{\npublic:\n TYPEINFO();\n ScUndoRenameObject(\n ScDocShell* pNewDocShell, const String& rPN,\n const String& rON, const String& rNN );\n\n virtual ~ScUndoRenameObject();\n\n virtual void Undo();\n virtual void Redo();\n virtual void Repeat(SfxRepeatTarget& rTarget);\n virtual BOOL CanRepeat(SfxRepeatTarget& rTarget) const;\n\n virtual String GetComment() const;\n\nprivate:\n String aPersistName; \/\/ to find object (works only for OLE objects)\n String aOldName;\n String aNewName;\n\n SdrObject* GetObject();\n};\n\n\nclass ScUndoLayoutRTL : public ScSimpleUndo\n{\npublic:\n TYPEINFO();\n ScUndoLayoutRTL( ScDocShell* pShell, USHORT nNewTab, BOOL bNewRTL );\n virtual ~ScUndoLayoutRTL();\n\n virtual void Undo();\n virtual void Redo();\n virtual void Repeat(SfxRepeatTarget& rTarget);\n virtual BOOL CanRepeat(SfxRepeatTarget& rTarget) const;\n\n virtual String GetComment() const;\n\nprivate:\n USHORT nTab;\n BOOL bRTL;\n\n void DoChange( BOOL bNew );\n};\n\n\n\n#endif\n\n<commit_msg>INTEGRATION: CWS rowlimit (1.5.320); FILE MERGED 2004\/02\/25 01:17:33 er 1.5.320.5: #i1967# type correctness 2004\/02\/13 11:33:24 er 1.5.320.4: #i1967# SCCOL,SCROW,SCTAB replace USHORT; SCsCOL,SCsROW,SCsTAB replace short 2004\/02\/11 13:55:26 er 1.5.320.3: RESYNC: (1.5-1.6); FILE MERGED 2004\/01\/13 20:04:50 er 1.5.320.2: #i1967# SCCOL,SCROW,SCTAB replace USHORT; SCsCOL,SCsROW,SCsTAB replace short 2003\/11\/28 19:48:03 er 1.5.320.1: #i1967# move ScAddress, ScRange from global.hxx to address.hxx<commit_after>\/*************************************************************************\n *\n * $RCSfile: undotab.hxx,v $\n *\n * $Revision: 1.7 $\n *\n * last change: $Author: obo $ $Date: 2004-06-04 11:45:08 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef SC_UNDOTAB_HXX\n#define SC_UNDOTAB_HXX\n\n#ifndef SC_UNDOBASE_HXX\n#include \"undobase.hxx\"\n#endif\n#ifndef SC_MARKDATA_HXX\n#include \"markdata.hxx\"\n#endif\n#ifndef _TOOLS_COLOR_HXX\n#include <tools\/color.hxx>\n#endif\n\n#ifndef _SVSTDARR_SHORTS\n\n#define _SVSTDARR_SHORTS\n#include <svtools\/svstdarr.hxx>\n\n#endif\n\n#ifndef _SVSTDARR_STRINGS\n\n#define _SVSTDARR_STRINGS\n#include <svtools\/svstdarr.hxx>\n\n#endif\n\n#ifndef _COM_SUN_STAR_UNO_SEQUENCE_HXX_\n#include <com\/sun\/star\/uno\/Sequence.hxx>\n#endif\n\nclass ScDocShell;\nclass ScDocument;\nclass SdrUndoAction;\nclass ScPrintRangeSaver;\nclass SdrObject;\n\n\/\/----------------------------------------------------------------------------\n\nclass ScUndoInsertTab : public ScSimpleUndo\n{\npublic:\n TYPEINFO();\n ScUndoInsertTab(\n ScDocShell* pNewDocShell,\n SCTAB nTabNum,\n BOOL bApp,\n const String& rNewName);\n virtual ~ScUndoInsertTab();\n\n virtual void Undo();\n virtual void Redo();\n virtual void Repeat(SfxRepeatTarget& rTarget);\n virtual BOOL CanRepeat(SfxRepeatTarget& rTarget) const;\n\n virtual String GetComment() const;\n\nprivate:\n String sNewName;\n SdrUndoAction* pDrawUndo;\n ULONG nEndChangeAction;\n SCTAB nTab;\n BOOL bAppend;\n\n void SetChangeTrack();\n};\n\nclass ScUndoInsertTables : public ScSimpleUndo\n{\npublic:\n TYPEINFO();\n ScUndoInsertTables(\n ScDocShell* pNewDocShell,\n SCTAB nTabNum,\n BOOL bApp,\n SvStrings *pNewNameList);\n virtual ~ScUndoInsertTables();\n\n virtual void Undo();\n virtual void Redo();\n virtual void Repeat(SfxRepeatTarget& rTarget);\n virtual BOOL CanRepeat(SfxRepeatTarget& rTarget) const;\n\n virtual String GetComment() const;\n\nprivate:\n\n SdrUndoAction* pDrawUndo;\n SvStrings* pNameList;\n ULONG nStartChangeAction;\n ULONG nEndChangeAction;\n SCTAB nTab;\n BOOL bAppend;\n\n void SetChangeTrack();\n};\n\n\nclass ScUndoDeleteTab: public ScMoveUndo \/\/ Draw vom Move fuer geloeschte Tabelle\n{\npublic:\n TYPEINFO();\n ScUndoDeleteTab(\n ScDocShell* pNewDocShell,\n const SvShorts &theTabs, \/\/SCTAB nNewTab,\n ScDocument* pUndoDocument,\n ScRefUndoData* pRefData );\n virtual ~ScUndoDeleteTab();\n\n virtual void Undo();\n virtual void Redo();\n virtual void Repeat(SfxRepeatTarget& rTarget);\n virtual BOOL CanRepeat(SfxRepeatTarget& rTarget) const;\n\n virtual String GetComment() const;\n\nprivate:\n SvShorts theTabs;\n ULONG nStartChangeAction;\n ULONG nEndChangeAction;\n\n void SetChangeTrack();\n};\n\n\nclass ScUndoRenameTab: public ScSimpleUndo\n{\npublic:\n TYPEINFO();\n ScUndoRenameTab(\n ScDocShell* pNewDocShell,\n SCTAB nT,\n const String& rOldName,\n const String& rNewName);\n virtual ~ScUndoRenameTab();\n\n virtual void Undo();\n virtual void Redo();\n virtual void Repeat(SfxRepeatTarget& rTarget);\n virtual BOOL CanRepeat(SfxRepeatTarget& rTarget) const;\n\n virtual String GetComment() const;\n\nprivate:\n SCTAB nTab;\n String sOldName;\n String sNewName;\n\n void DoChange( SCTAB nTab, const String& rName ) const;\n};\n\n\nclass ScUndoMoveTab: public ScSimpleUndo\n{\npublic:\n TYPEINFO();\n ScUndoMoveTab( ScDocShell* pNewDocShell,\n const SvShorts &aOldTab,\n const SvShorts &aNewTab);\n virtual ~ScUndoMoveTab();\n\n virtual void Undo();\n virtual void Redo();\n virtual void Repeat(SfxRepeatTarget& rTarget);\n virtual BOOL CanRepeat(SfxRepeatTarget& rTarget) const;\n\n virtual String GetComment() const;\n\nprivate:\n SvShorts theOldTabs;\n SvShorts theNewTabs;\n\n void DoChange( BOOL bUndo ) const;\n};\n\n\nclass ScUndoCopyTab: public ScSimpleUndo\n{\npublic:\n TYPEINFO();\n ScUndoCopyTab(ScDocShell* pNewDocShell,\n const SvShorts &aOldTab,\n const SvShorts &aNewTab);\n\n virtual ~ScUndoCopyTab();\n\n virtual void Undo();\n virtual void Redo();\n virtual void Repeat(SfxRepeatTarget& rTarget);\n virtual BOOL CanRepeat(SfxRepeatTarget& rTarget) const;\n\n virtual String GetComment() const;\n\nprivate:\n SdrUndoAction* pDrawUndo;\n SvShorts theOldTabs;\n SvShorts theNewTabs;\n\n void DoChange() const;\n};\n\n\nclass ScUndoMakeScenario: public ScSimpleUndo\n{\npublic:\n TYPEINFO();\n ScUndoMakeScenario(\n ScDocShell* pNewDocShell,\n SCTAB nSrc, SCTAB nDest,\n ScDocument* pUndo,\n const String& rN, const String& rC,\n const Color& rCol, USHORT nF,\n const ScMarkData& rMark );\n virtual ~ScUndoMakeScenario();\n\n virtual void Undo();\n virtual void Redo();\n virtual void Repeat(SfxRepeatTarget& rTarget);\n virtual BOOL CanRepeat(SfxRepeatTarget& rTarget) const;\n\n virtual String GetComment() const;\n\nprivate:\n SCTAB nSrcTab;\n SCTAB nDestTab;\n ScDocument* pUndoDoc;\n String aName;\n String aComment;\n Color aColor;\n USHORT nFlags;\n ScMarkData aMarkData;\n};\n\n\nclass ScUndoImportTab : public ScSimpleUndo\n{\npublic:\n TYPEINFO();\n ScUndoImportTab(\n ScDocShell* pShell,\n SCTAB nNewTab, SCTAB nNewCount,\n BOOL bNewLink );\n virtual ~ScUndoImportTab();\n\n virtual void Undo();\n virtual void Redo();\n virtual void Repeat(SfxRepeatTarget& rTarget);\n virtual BOOL CanRepeat(SfxRepeatTarget& rTarget) const;\n\n virtual String GetComment() const;\n\nprivate:\n SCTAB nTab;\n SCTAB nCount;\n BOOL bLink;\n ScDocument* pRedoDoc;\n SdrUndoAction* pDrawUndo;\n\n void DoChange() const;\n};\n\n\nclass ScUndoRemoveLink : public ScSimpleUndo\n{\npublic:\n TYPEINFO();\n ScUndoRemoveLink( \/\/ vor dem Loeschen aufrufen!\n ScDocShell* pShell,\n const String& rDoc );\n virtual ~ScUndoRemoveLink();\n\n virtual void Undo();\n virtual void Redo();\n virtual void Repeat(SfxRepeatTarget& rTarget);\n virtual BOOL CanRepeat(SfxRepeatTarget& rTarget) const;\n\n virtual String GetComment() const;\n\nprivate:\n String aDocName;\n String aFltName;\n String aOptions;\n ULONG nRefreshDelay;\n USHORT nCount;\n SCTAB* pTabs;\n BYTE* pModes;\n String* pTabNames;\n\n void DoChange( BOOL bLink ) const;\n};\n\n\nclass ScUndoShowHideTab : public ScSimpleUndo\n{\npublic:\n TYPEINFO();\n ScUndoShowHideTab(\n ScDocShell* pShell,\n SCTAB nNewTab, BOOL bNewShow );\n virtual ~ScUndoShowHideTab();\n\n virtual void Undo();\n virtual void Redo();\n virtual void Repeat(SfxRepeatTarget& rTarget);\n virtual BOOL CanRepeat(SfxRepeatTarget& rTarget) const;\n\n virtual String GetComment() const;\n\nprivate:\n SCTAB nTab;\n BOOL bShow;\n\n void DoChange( BOOL bShow ) const;\n};\n\n\nclass ScUndoProtect : public ScSimpleUndo\n{\npublic:\n TYPEINFO();\n ScUndoProtect( ScDocShell* pShell, SCTAB nNewTab,\n BOOL bNewProtect, const com::sun::star::uno::Sequence<sal_Int8>& rNewPassword );\n virtual ~ScUndoProtect();\n\n virtual void Undo();\n virtual void Redo();\n virtual void Repeat(SfxRepeatTarget& rTarget);\n virtual BOOL CanRepeat(SfxRepeatTarget& rTarget) const;\n\n virtual String GetComment() const;\n\nprivate:\n SCTAB nTab;\n BOOL bProtect;\n com::sun::star::uno::Sequence<sal_Int8> aPassword;\n\n void DoProtect( BOOL bDo );\n};\n\n\nclass ScUndoPrintRange : public ScSimpleUndo\n{\npublic:\n TYPEINFO();\n ScUndoPrintRange( ScDocShell* pShell, SCTAB nNewTab,\n ScPrintRangeSaver* pOld, ScPrintRangeSaver* pNew );\n virtual ~ScUndoPrintRange();\n\n virtual void Undo();\n virtual void Redo();\n virtual void Repeat(SfxRepeatTarget& rTarget);\n virtual BOOL CanRepeat(SfxRepeatTarget& rTarget) const;\n\n virtual String GetComment() const;\n\nprivate:\n SCTAB nTab;\n ScPrintRangeSaver* pOldRanges;\n ScPrintRangeSaver* pNewRanges;\n\n void DoChange( BOOL bUndo );\n};\n\n\nclass ScUndoScenarioFlags: public ScSimpleUndo\n{\npublic:\n TYPEINFO();\n ScUndoScenarioFlags(\n ScDocShell* pNewDocShell, SCTAB nT,\n const String& rON, const String& rNN,\n const String& rOC, const String& rNC,\n const Color& rOCol, const Color& rNCol,\n USHORT nOF, USHORT nNF );\n\n virtual ~ScUndoScenarioFlags();\n\n virtual void Undo();\n virtual void Redo();\n virtual void Repeat(SfxRepeatTarget& rTarget);\n virtual BOOL CanRepeat(SfxRepeatTarget& rTarget) const;\n\n virtual String GetComment() const;\n\nprivate:\n SCTAB nTab;\n String aOldName;\n String aNewName;\n String aOldComment;\n String aNewComment;\n Color aOldColor;\n Color aNewColor;\n USHORT nOldFlags;\n USHORT nNewFlags;\n};\n\n\nclass ScUndoRenameObject: public ScSimpleUndo\n{\npublic:\n TYPEINFO();\n ScUndoRenameObject(\n ScDocShell* pNewDocShell, const String& rPN,\n const String& rON, const String& rNN );\n\n virtual ~ScUndoRenameObject();\n\n virtual void Undo();\n virtual void Redo();\n virtual void Repeat(SfxRepeatTarget& rTarget);\n virtual BOOL CanRepeat(SfxRepeatTarget& rTarget) const;\n\n virtual String GetComment() const;\n\nprivate:\n String aPersistName; \/\/ to find object (works only for OLE objects)\n String aOldName;\n String aNewName;\n\n SdrObject* GetObject();\n};\n\n\nclass ScUndoLayoutRTL : public ScSimpleUndo\n{\npublic:\n TYPEINFO();\n ScUndoLayoutRTL( ScDocShell* pShell, SCTAB nNewTab, BOOL bNewRTL );\n virtual ~ScUndoLayoutRTL();\n\n virtual void Undo();\n virtual void Redo();\n virtual void Repeat(SfxRepeatTarget& rTarget);\n virtual BOOL CanRepeat(SfxRepeatTarget& rTarget) const;\n\n virtual String GetComment() const;\n\nprivate:\n SCTAB nTab;\n BOOL bRTL;\n\n void DoChange( BOOL bNew );\n};\n\n\n\n#endif\n\n<|endoftext|>"} {"text":"<commit_before>size_t sse4_strstr_long(const char* s, size_t n, const char* neddle, size_t neddle_size) {\n \n assert(neddle_size > 4);\n assert(n > 0);\n\n const __m128i prefix = _mm_loadu_si128(reinterpret_cast<const __m128i*>(neddle));\n const __m128i zeros = _mm_setzero_si128();\n\n for (size_t i = 0; i < n; i += 8) {\n \n const __m128i data = _mm_loadu_si128(reinterpret_cast<const __m128i*>(s + i));\n const __m128i result = _mm_mpsadbw_epu8(data, prefix, 0);\n\n const __m128i cmp = _mm_cmpeq_epi16(result, zeros);\n\n unsigned mask = _mm_movemask_epi8(cmp) & 0x5555;\n\n while (mask != 0) {\n\n const auto bitpos = bits::get_first_bit_set(mask)\/2;\n\n if (memcmp(s + i + bitpos + 4, neddle + 4, neddle_size - 4) == 0) {\n return i + bitpos;\n }\n\n mask = bits::clear_leftmost_set(mask);\n }\n }\n\n return std::string::npos;\n}\n\n\/\/ ------------------------------------------------------------------------\n\nsize_t sse4_strstr_max20(const char* s, size_t n, const char* neddle, size_t neddle_size) {\n \n const __m128i zeros = _mm_setzero_si128();\n const __m128i prefix = sse::load(neddle);\n const __m128i suffix = sse::load(neddle + 4);\n const __m128i suff_mask = sse::mask_lower_bytes(neddle_size - 4);\n\n for (size_t i = 0; i < n; i += 8) {\n \n const __m128i data = sse::load(s + i);\n const __m128i result = _mm_mpsadbw_epu8(data, prefix, 0);\n\n const __m128i cmp = _mm_cmpeq_epi16(result, zeros);\n\n unsigned mask = _mm_movemask_epi8(cmp) & 0x5555;\n\n while (mask != 0) {\n\n const auto bitpos = bits::get_first_bit_set(mask)\/2;\n\n const __m128i str = sse::load(s + i + bitpos + 4);\n const __m128i cmp = _mm_cmpeq_epi8(str, suffix);\n\n if (_mm_testc_si128(cmp, suff_mask)) {\n\n return i + bitpos;\n }\n\n mask = bits::clear_leftmost_set(mask);\n }\n }\n\n return std::string::npos;\n}\n\n\/\/ ------------------------------------------------------------------------\n\nsize_t sse4_strstr_max36(const char* s, size_t n, const char* neddle, size_t neddle_size) {\n \n const __m128i zeros = _mm_setzero_si128();\n const __m128i prefix = sse::load(neddle);\n const __m128i suffix1 = sse::load(neddle + 4);\n const __m128i suffix2 = sse::load(neddle + 16 + 4);\n const __m128i suff_mask = sse::mask_higher_bytes(neddle_size - (16 + 4));\n\n for (size_t i = 0; i < n; i += 8) {\n \n const __m128i data = sse::load(s + i);\n const __m128i result = _mm_mpsadbw_epu8(data, prefix, 0);\n\n const __m128i cmp = _mm_cmpeq_epi16(result, zeros);\n\n unsigned mask = _mm_movemask_epi8(cmp) & 0x5555;\n\n while (mask != 0) {\n\n const auto bitpos = bits::get_first_bit_set(mask)\/2;\n\n const __m128i c1 = _mm_cmpeq_epi8(sse::load(s + i + bitpos + 4), suffix1);\n const __m128i c2 = _mm_cmpeq_epi8(sse::load(s + i + bitpos + 16 + 4), suffix2);\n\n const __m128i c3 = _mm_or_si128(c2, suff_mask);\n const __m128i tmp = _mm_and_si128(c1, c3);\n\n if (_mm_movemask_epi8(tmp) == 0xffff) {\n\n return i + bitpos;\n }\n\n mask = bits::clear_leftmost_set(mask);\n }\n }\n\n return std::string::npos;\n}\n\n\/\/ ------------------------------------------------------------------------\n\nsize_t sse4_strstr_len3(const char* s, size_t n, const char* neddle) {\n\n const __m128i prefix = _mm_loadu_si128(reinterpret_cast<const __m128i*>(neddle));\n const __m128i zeros = _mm_setzero_si128();\n\n for (size_t i = 0; i < n; i += 8) {\n\n const __m128i data = _mm_loadu_si128(reinterpret_cast<const __m128i*>(s + i));\n const __m128i lastbyte = _mm_cvtepu8_epi16(_mm_srli_si128(data, 3));\n const __m128i result = _mm_mpsadbw_epu8(data, prefix, 0);\n\n const __m128i cmp = _mm_cmpeq_epi16(_mm_sub_epi16(result, lastbyte), zeros);\n\n unsigned mask = _mm_movemask_epi8(cmp) & 0x5555;\n\n if (mask != 0) {\n\n return i + bits::get_first_bit_set(mask)\/2;\n }\n }\n\n return std::string::npos;\n}\n\n\/\/ ------------------------------------------------------------------------\n\nsize_t sse4_strstr_len4(const char* s, size_t n, const char* neddle) {\n\n const __m128i prefix = _mm_loadu_si128(reinterpret_cast<const __m128i*>(neddle));\n const __m128i zeros = _mm_setzero_si128();\n\n for (size_t i = 0; i < n; i += 8) {\n \n const __m128i data = _mm_loadu_si128(reinterpret_cast<const __m128i*>(s + i));\n const __m128i result = _mm_mpsadbw_epu8(data, prefix, 0);\n\n const __m128i cmp = _mm_cmpeq_epi16(result, zeros);\n\n unsigned mask = _mm_movemask_epi8(cmp);\n\n if (mask != 0) {\n\n return i + bits::get_first_bit_set(mask)\/2;\n }\n }\n\n return std::string::npos;\n}\n\n\/\/ ------------------------------------------------------------------------\n\nsize_t sse4_strstr(const char* s, size_t n, const char* neddle, size_t neddle_size) {\n\n size_t result = std::string::npos;\n\n if (n < neddle_size) {\n return result;\n }\n\n\tswitch (neddle_size) {\n\t\tcase 0:\n\t\t\treturn 0;\n\n\t\tcase 1: {\n const char* res = reinterpret_cast<const char*>(strchr(s, neddle[0]));\n\n\t\t\treturn (res != nullptr) ? res - s : std::string::npos;\n }\n\t\tcase 2: {\n\t\t\tconst char* res = reinterpret_cast<const char*>(strstr(s, neddle));\n\n\t\t\treturn (res != nullptr) ? res - s : std::string::npos;\n }\n\t\tcase 3:\n\n\t\t\tresult = sse4_strstr_len3(s, n, neddle);\n break;\n\n\t\tcase 4:\n\t\t\tresult = sse4_strstr_len4(s, n, neddle);\n break;\n\n\t\tcase 5: case 6: case 7: case 8: case 9:\n\t\tcase 10: case 11: case 12: case 13: case 14:\n\t\tcase 15: case 16: case 17: case 18: case 19:\n\t\tcase 20: \/* 5..20 *\/\n\t\t result = sse4_strstr_max20(s, n, neddle, neddle_size);\n break;\n\n\t\tcase 21: case 22: case 23: case 24: case 25: \n\t\tcase 26: case 27: case 28: case 29: case 30: \n\t\tcase 31: case 32: case 33: case 34: case 35: \n\t\tcase 36: \/* 21..36 *\/\n\t\t\tresult = sse4_strstr_max36(s, n, neddle, neddle_size);\n break;\n\n\t\tdefault:\n\t\t\tresult = sse4_strstr_long(s, n, neddle, neddle_size);\n break;\n }\n\n\n if (result <= n - neddle_size) {\n return result;\n } else {\n return std::string::npos;\n }\n}\n\n\/\/ --------------------------------------------------\n\nsize_t sse4_strstr(const std::string& s, const std::string& neddle) {\n\n return sse4_strstr(s.data(), s.size(), neddle.data(), neddle.size());\n}\n\n<commit_msg>spelling<commit_after>size_t sse4_strstr_long(const char* s, size_t n, const char* needle, size_t needle_size) {\n \n assert(needle_size > 4);\n assert(n > 0);\n\n const __m128i prefix = _mm_loadu_si128(reinterpret_cast<const __m128i*>(needle));\n const __m128i zeros = _mm_setzero_si128();\n\n for (size_t i = 0; i < n; i += 8) {\n \n const __m128i data = _mm_loadu_si128(reinterpret_cast<const __m128i*>(s + i));\n const __m128i result = _mm_mpsadbw_epu8(data, prefix, 0);\n\n const __m128i cmp = _mm_cmpeq_epi16(result, zeros);\n\n unsigned mask = _mm_movemask_epi8(cmp) & 0x5555;\n\n while (mask != 0) {\n\n const auto bitpos = bits::get_first_bit_set(mask)\/2;\n\n if (memcmp(s + i + bitpos + 4, needle + 4, needle_size - 4) == 0) {\n return i + bitpos;\n }\n\n mask = bits::clear_leftmost_set(mask);\n }\n }\n\n return std::string::npos;\n}\n\n\/\/ ------------------------------------------------------------------------\n\nsize_t sse4_strstr_max20(const char* s, size_t n, const char* needle, size_t needle_size) {\n \n const __m128i zeros = _mm_setzero_si128();\n const __m128i prefix = sse::load(needle);\n const __m128i suffix = sse::load(needle + 4);\n const __m128i suff_mask = sse::mask_lower_bytes(needle_size - 4);\n\n for (size_t i = 0; i < n; i += 8) {\n \n const __m128i data = sse::load(s + i);\n const __m128i result = _mm_mpsadbw_epu8(data, prefix, 0);\n\n const __m128i cmp = _mm_cmpeq_epi16(result, zeros);\n\n unsigned mask = _mm_movemask_epi8(cmp) & 0x5555;\n\n while (mask != 0) {\n\n const auto bitpos = bits::get_first_bit_set(mask)\/2;\n\n const __m128i str = sse::load(s + i + bitpos + 4);\n const __m128i cmp = _mm_cmpeq_epi8(str, suffix);\n\n if (_mm_testc_si128(cmp, suff_mask)) {\n\n return i + bitpos;\n }\n\n mask = bits::clear_leftmost_set(mask);\n }\n }\n\n return std::string::npos;\n}\n\n\/\/ ------------------------------------------------------------------------\n\nsize_t sse4_strstr_max36(const char* s, size_t n, const char* needle, size_t needle_size) {\n \n const __m128i zeros = _mm_setzero_si128();\n const __m128i prefix = sse::load(needle);\n const __m128i suffix1 = sse::load(needle + 4);\n const __m128i suffix2 = sse::load(needle + 16 + 4);\n const __m128i suff_mask = sse::mask_higher_bytes(needle_size - (16 + 4));\n\n for (size_t i = 0; i < n; i += 8) {\n \n const __m128i data = sse::load(s + i);\n const __m128i result = _mm_mpsadbw_epu8(data, prefix, 0);\n\n const __m128i cmp = _mm_cmpeq_epi16(result, zeros);\n\n unsigned mask = _mm_movemask_epi8(cmp) & 0x5555;\n\n while (mask != 0) {\n\n const auto bitpos = bits::get_first_bit_set(mask)\/2;\n\n const __m128i c1 = _mm_cmpeq_epi8(sse::load(s + i + bitpos + 4), suffix1);\n const __m128i c2 = _mm_cmpeq_epi8(sse::load(s + i + bitpos + 16 + 4), suffix2);\n\n const __m128i c3 = _mm_or_si128(c2, suff_mask);\n const __m128i tmp = _mm_and_si128(c1, c3);\n\n if (_mm_movemask_epi8(tmp) == 0xffff) {\n\n return i + bitpos;\n }\n\n mask = bits::clear_leftmost_set(mask);\n }\n }\n\n return std::string::npos;\n}\n\n\/\/ ------------------------------------------------------------------------\n\nsize_t sse4_strstr_len3(const char* s, size_t n, const char* needle) {\n\n const __m128i prefix = _mm_loadu_si128(reinterpret_cast<const __m128i*>(needle));\n const __m128i zeros = _mm_setzero_si128();\n\n for (size_t i = 0; i < n; i += 8) {\n\n const __m128i data = _mm_loadu_si128(reinterpret_cast<const __m128i*>(s + i));\n const __m128i lastbyte = _mm_cvtepu8_epi16(_mm_srli_si128(data, 3));\n const __m128i result = _mm_mpsadbw_epu8(data, prefix, 0);\n\n const __m128i cmp = _mm_cmpeq_epi16(_mm_sub_epi16(result, lastbyte), zeros);\n\n unsigned mask = _mm_movemask_epi8(cmp) & 0x5555;\n\n if (mask != 0) {\n\n return i + bits::get_first_bit_set(mask)\/2;\n }\n }\n\n return std::string::npos;\n}\n\n\/\/ ------------------------------------------------------------------------\n\nsize_t sse4_strstr_len4(const char* s, size_t n, const char* needle) {\n\n const __m128i prefix = _mm_loadu_si128(reinterpret_cast<const __m128i*>(needle));\n const __m128i zeros = _mm_setzero_si128();\n\n for (size_t i = 0; i < n; i += 8) {\n \n const __m128i data = _mm_loadu_si128(reinterpret_cast<const __m128i*>(s + i));\n const __m128i result = _mm_mpsadbw_epu8(data, prefix, 0);\n\n const __m128i cmp = _mm_cmpeq_epi16(result, zeros);\n\n unsigned mask = _mm_movemask_epi8(cmp);\n\n if (mask != 0) {\n\n return i + bits::get_first_bit_set(mask)\/2;\n }\n }\n\n return std::string::npos;\n}\n\n\/\/ ------------------------------------------------------------------------\n\nsize_t sse4_strstr(const char* s, size_t n, const char* needle, size_t needle_size) {\n\n size_t result = std::string::npos;\n\n if (n < needle_size) {\n return result;\n }\n\n\tswitch (needle_size) {\n\t\tcase 0:\n\t\t\treturn 0;\n\n\t\tcase 1: {\n const char* res = reinterpret_cast<const char*>(strchr(s, needle[0]));\n\n\t\t\treturn (res != nullptr) ? res - s : std::string::npos;\n }\n\t\tcase 2: {\n\t\t\tconst char* res = reinterpret_cast<const char*>(strstr(s, needle));\n\n\t\t\treturn (res != nullptr) ? res - s : std::string::npos;\n }\n\t\tcase 3:\n\n\t\t\tresult = sse4_strstr_len3(s, n, needle);\n break;\n\n\t\tcase 4:\n\t\t\tresult = sse4_strstr_len4(s, n, needle);\n break;\n\n\t\tcase 5: case 6: case 7: case 8: case 9:\n\t\tcase 10: case 11: case 12: case 13: case 14:\n\t\tcase 15: case 16: case 17: case 18: case 19:\n\t\tcase 20: \/* 5..20 *\/\n\t\t result = sse4_strstr_max20(s, n, needle, needle_size);\n break;\n\n\t\tcase 21: case 22: case 23: case 24: case 25: \n\t\tcase 26: case 27: case 28: case 29: case 30: \n\t\tcase 31: case 32: case 33: case 34: case 35: \n\t\tcase 36: \/* 21..36 *\/\n\t\t\tresult = sse4_strstr_max36(s, n, needle, needle_size);\n break;\n\n\t\tdefault:\n\t\t\tresult = sse4_strstr_long(s, n, needle, needle_size);\n break;\n }\n\n\n if (result <= n - needle_size) {\n return result;\n } else {\n return std::string::npos;\n }\n}\n\n\/\/ --------------------------------------------------\n\nsize_t sse4_strstr(const std::string& s, const std::string& needle) {\n\n return sse4_strstr(s.data(), s.size(), needle.data(), needle.size());\n}\n\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n#include <thread>\n\n\nvoid called_from_thread() {\n std::cout << \"Called from spawned thread\" << std::endl;\n}\n\nint main(int argc, char* argv[])\n{\n std::thread t( &called_from_thread );\n t.detach();\n\n std::cout << \"Message from main\" << std::endl;\n\n return 0;\n}\n<commit_msg>Join spawned thread. TODO: play with timings to see difference between join and detach.<commit_after>#include <iostream>\n#include <thread>\n\n\nvoid called_from_thread() {\n std::cout << \"Called from spawned thread\" << std::endl;\n}\n\nint main(int argc, char* argv[])\n{\n std::thread t( &called_from_thread );\n\n std::cout << \"Message from main\" << std::endl;\n\n t.join();\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*=========================================================================\n\n Program: Insight Segmentation & Registration Toolkit (ITK)\n Module: itkCyclicReferences.cxx\n Language: C++\n Date: $Date$\n Version: $Revision$\n\nCopyright (c) 2001 Insight Consortium\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n * Redistributions of source code must retain the above copyright notice,\n this list of conditions and the following disclaimer.\n\n * Redistributions in binary form must reproduce the above copyright notice,\n this list of conditions and the following disclaimer in the documentation\n and\/or other materials provided with the distribution.\n\n * The name of the Insight Consortium, nor the names of any consortium members,\n nor of any contributors, may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\n * Modified source versions must be plainly marked as such, and must not be\n misrepresented as being the original software.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS ``AS IS''\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE FOR\nANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\nDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\nSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\nCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\nOR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n=========================================================================*\/\n#include <iostream>\n#include \"itkImage.h\"\n#include \"itkRandomImageSource.h\"\n#include \"itkShrinkImageFilter.h\"\n#include \"itkVTKImageWriter.h\"\n#include \"itkVTKImageReader.h\"\n#include \"itkCommand.h\"\n#include \"itkOutputWindow.h\"\n\n\/\/ this class is used to send output to stdout and not the itk window\nclass TextOutput : public itk::OutputWindow\n{\npublic:\n virtual void DisplayText(const char* s)\n {\n std::cout << s << std::endl;\n }\n};\n\n\/\/ The following class is used to support callbacks\n\/\/ on the shrink filter in the pipeline that follows later.\nclass DeleteEvent\n{\npublic:\n void Delete(const itk::LightObject *caller, unsigned long event) \n {std::cout << \"Deleting: \" << caller->GetNameOfClass() << std::endl;}\n};\n\n\/\/ Note about scoping: Lots of blocks are created here to force the order\n\/\/ of deletion of objects to insure that the output is in the correct order.\n\/\/ (Deletion of the smart pointers occurs automatically as scope is exited.)\n\/\/\nint main()\n{\n \/\/ Comment the following if you want to use the itk text output window\n itk::OutputWindow::SetInstance(new TextOutput);\n\n \/\/ Uncomment the following if you want to see each message independently\n \/\/ itk::OutputWindow::GetInstance()->PromptUserOn();\n\n \/\/ Begin by creating a simple pipeline. Use a scalar as a pixel.\n \/\/\n \/\/ Create a typedef to make the code more digestable\n typedef itk::Image<float,2> FloatImage2DType;\n\n \/\/ Test the deletion of an image with native type.\n \/\/ (scope operators cause automagic smart pointer destruction)\n {\/\/image\n itk::Image<float,2>::Pointer if2 = itk::Image<float,2>::New();\n DeleteEvent deleteEvent;\n itk::MemberCommand<DeleteEvent>::Pointer deleteCommand;\n deleteCommand = itk::MemberCommand<DeleteEvent>::New();\n deleteCommand->SetCallbackFunction(&deleteEvent, &DeleteEvent::Delete);\n if2->AddObserver(itk::Command::DeleteEvent, deleteCommand);\n\n \/\/test unregister from vector of data objects\n {\n std::vector<itk::DataObject::Pointer> v;\n v.push_back(if2.GetPointer());\n }\n }\/\/image\n\n \/\/ Create a source object (in this case a reader)\n {\/\/Reader\n itk::VTKImageReader<FloatImage2DType>::Pointer reader;\n reader = itk::VTKImageReader<FloatImage2DType>::New();\n reader->SetFileName(\"junkInput.vtk\");\n DeleteEvent deleteReader;\n itk::MemberCommand<DeleteEvent>::Pointer deleteReaderCommand;\n deleteReaderCommand = itk::MemberCommand<DeleteEvent>::New();\n deleteReaderCommand->SetCallbackFunction(&deleteReader, &DeleteEvent::Delete);\n reader->AddObserver(itk::Command::DeleteEvent, deleteReaderCommand);\n }\/\/reader\n \n \/\/ Create another source object (in this case a random image generator).\n \/\/ The source object is templated on the output type.\n \/\/\n {\/\/random\n itk::RandomImageSource<FloatImage2DType>::Pointer random;\n random = itk::RandomImageSource<FloatImage2DType>::New();\n random->SetMin(0.0);\n random->SetMax(1.0);\n DeleteEvent deleteRandom;\n itk::MemberCommand<DeleteEvent>::Pointer deleteRandomCommand;\n deleteRandomCommand = itk::MemberCommand<DeleteEvent>::New();\n deleteRandomCommand->SetCallbackFunction(&deleteRandom, &DeleteEvent::Delete);\n random->AddObserver(itk::Command::DeleteEvent, deleteRandomCommand);\n\n \/\/ Create a filter...shrink the image by an integral amount. We also \n \/\/ add some callbacks to the start, progress, and end filter execution\n \/\/ methods. The filter is templated on the input and output data types.\n \/\/\n {\/\/shrink\n itk::ShrinkImageFilter<FloatImage2DType,FloatImage2DType>::Pointer shrink;\n shrink = itk::ShrinkImageFilter<FloatImage2DType,FloatImage2DType>::New();\n shrink->SetInput(random->GetOutput());\n shrink->SetShrinkFactors(2);\n DeleteEvent deleteShrink;\n itk::MemberCommand<DeleteEvent>::Pointer deleteShrinkCommand;\n deleteShrinkCommand = itk::MemberCommand<DeleteEvent>::New();\n deleteShrinkCommand->SetCallbackFunction(&deleteShrink, &DeleteEvent::Delete);\n shrink->AddObserver(itk::Command::DeleteEvent, deleteShrinkCommand);\n \n \/\/ Create a mapper (in this case a writer). A mapper\n \/\/ is templated on the input type.\n \/\/\n {\/\/write\n itk::VTKImageWriter<FloatImage2DType>::Pointer writer;\n writer = itk::VTKImageWriter<FloatImage2DType>::New();\n writer->SetInput(shrink->GetOutput());\n writer->SetFileName(\"BasicArchitectureImage.vtk\");\n writer->SetFileTypeToASCII();\n writer->Write();\n DeleteEvent deleteWriter;\n itk::MemberCommand<DeleteEvent>::Pointer deleteWriterCommand;\n deleteWriterCommand = itk::MemberCommand<DeleteEvent>::New();\n deleteWriterCommand->SetCallbackFunction(&deleteWriter, &DeleteEvent::Delete);\n writer->AddObserver(itk::Command::DeleteEvent, deleteWriterCommand);\n }\/\/write\n }\/\/shrink\n }\/\/random\n \n return EXIT_SUCCESS;\n}\n<commit_msg>ENH: fix leak<commit_after>\/*=========================================================================\n\n Program: Insight Segmentation & Registration Toolkit (ITK)\n Module: itkCyclicReferences.cxx\n Language: C++\n Date: $Date$\n Version: $Revision$\n\nCopyright (c) 2001 Insight Consortium\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n * Redistributions of source code must retain the above copyright notice,\n this list of conditions and the following disclaimer.\n\n * Redistributions in binary form must reproduce the above copyright notice,\n this list of conditions and the following disclaimer in the documentation\n and\/or other materials provided with the distribution.\n\n * The name of the Insight Consortium, nor the names of any consortium members,\n nor of any contributors, may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\n * Modified source versions must be plainly marked as such, and must not be\n misrepresented as being the original software.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS ``AS IS''\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE FOR\nANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\nDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\nSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\nCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\nOR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n=========================================================================*\/\n#include <iostream>\n#include \"itkImage.h\"\n#include \"itkRandomImageSource.h\"\n#include \"itkShrinkImageFilter.h\"\n#include \"itkVTKImageWriter.h\"\n#include \"itkVTKImageReader.h\"\n#include \"itkCommand.h\"\n#include \"itkOutputWindow.h\"\n\n\/\/ this class is used to send output to stdout and not the itk window\nclass TextOutput : public itk::OutputWindow\n{\npublic:\n typedef itk::SmartPointer<TextOutput> Pointer;\n itkNewMacro(TextOutput);\n virtual void DisplayText(const char* s)\n {\n std::cout << s << std::endl;\n }\n};\n\n\/\/ The following class is used to support callbacks\n\/\/ on the shrink filter in the pipeline that follows later.\nclass DeleteEvent\n{\npublic:\n void Delete(const itk::LightObject *caller, unsigned long event) \n {std::cout << \"Deleting: \" << caller->GetNameOfClass() << std::endl;}\n};\n\n\/\/ Note about scoping: Lots of blocks are created here to force the order\n\/\/ of deletion of objects to insure that the output is in the correct order.\n\/\/ (Deletion of the smart pointers occurs automatically as scope is exited.)\n\/\/\nint main()\n{\n \/\/ Comment the following if you want to use the itk text output window\n itk::OutputWindow::SetInstance(new TextOutput);\n\n \/\/ Uncomment the following if you want to see each message independently\n \/\/ itk::OutputWindow::GetInstance()->PromptUserOn();\n\n \/\/ Begin by creating a simple pipeline. Use a scalar as a pixel.\n \/\/\n \/\/ Create a typedef to make the code more digestable\n typedef itk::Image<float,2> FloatImage2DType;\n\n \/\/ Test the deletion of an image with native type.\n \/\/ (scope operators cause automagic smart pointer destruction)\n {\/\/image\n itk::Image<float,2>::Pointer if2 = itk::Image<float,2>::New();\n DeleteEvent deleteEvent;\n itk::MemberCommand<DeleteEvent>::Pointer deleteCommand;\n deleteCommand = itk::MemberCommand<DeleteEvent>::New();\n deleteCommand->SetCallbackFunction(&deleteEvent, &DeleteEvent::Delete);\n if2->AddObserver(itk::Command::DeleteEvent, deleteCommand);\n\n \/\/test unregister from vector of data objects\n {\n std::vector<itk::DataObject::Pointer> v;\n v.push_back(if2.GetPointer());\n }\n }\/\/image\n\n \/\/ Create a source object (in this case a reader)\n {\/\/Reader\n itk::VTKImageReader<FloatImage2DType>::Pointer reader;\n reader = itk::VTKImageReader<FloatImage2DType>::New();\n reader->SetFileName(\"junkInput.vtk\");\n DeleteEvent deleteReader;\n itk::MemberCommand<DeleteEvent>::Pointer deleteReaderCommand;\n deleteReaderCommand = itk::MemberCommand<DeleteEvent>::New();\n deleteReaderCommand->SetCallbackFunction(&deleteReader, &DeleteEvent::Delete);\n reader->AddObserver(itk::Command::DeleteEvent, deleteReaderCommand);\n }\/\/reader\n \n \/\/ Create another source object (in this case a random image generator).\n \/\/ The source object is templated on the output type.\n \/\/\n {\/\/random\n itk::RandomImageSource<FloatImage2DType>::Pointer random;\n random = itk::RandomImageSource<FloatImage2DType>::New();\n random->SetMin(0.0);\n random->SetMax(1.0);\n DeleteEvent deleteRandom;\n itk::MemberCommand<DeleteEvent>::Pointer deleteRandomCommand;\n deleteRandomCommand = itk::MemberCommand<DeleteEvent>::New();\n deleteRandomCommand->SetCallbackFunction(&deleteRandom, &DeleteEvent::Delete);\n random->AddObserver(itk::Command::DeleteEvent, deleteRandomCommand);\n\n \/\/ Create a filter...shrink the image by an integral amount. We also \n \/\/ add some callbacks to the start, progress, and end filter execution\n \/\/ methods. The filter is templated on the input and output data types.\n \/\/\n {\/\/shrink\n itk::ShrinkImageFilter<FloatImage2DType,FloatImage2DType>::Pointer shrink;\n shrink = itk::ShrinkImageFilter<FloatImage2DType,FloatImage2DType>::New();\n shrink->SetInput(random->GetOutput());\n shrink->SetShrinkFactors(2);\n DeleteEvent deleteShrink;\n itk::MemberCommand<DeleteEvent>::Pointer deleteShrinkCommand;\n deleteShrinkCommand = itk::MemberCommand<DeleteEvent>::New();\n deleteShrinkCommand->SetCallbackFunction(&deleteShrink, &DeleteEvent::Delete);\n shrink->AddObserver(itk::Command::DeleteEvent, deleteShrinkCommand);\n \n \/\/ Create a mapper (in this case a writer). A mapper\n \/\/ is templated on the input type.\n \/\/\n {\/\/write\n itk::VTKImageWriter<FloatImage2DType>::Pointer writer;\n writer = itk::VTKImageWriter<FloatImage2DType>::New();\n writer->SetInput(shrink->GetOutput());\n writer->SetFileName(\"BasicArchitectureImage.vtk\");\n writer->SetFileTypeToASCII();\n writer->Write();\n DeleteEvent deleteWriter;\n itk::MemberCommand<DeleteEvent>::Pointer deleteWriterCommand;\n deleteWriterCommand = itk::MemberCommand<DeleteEvent>::New();\n deleteWriterCommand->SetCallbackFunction(&deleteWriter, &DeleteEvent::Delete);\n writer->AddObserver(itk::Command::DeleteEvent, deleteWriterCommand);\n }\/\/write\n }\/\/shrink\n }\/\/random\n \n return EXIT_SUCCESS;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * PathResolver.cpp\n * openc2e\n *\n * Created by Bryan Donlan\n * Copyright (c) 2005 Bryan Donlan. All rights reserved.\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n *\/\n\n#include \"PathResolver.h\"\n\n#include <boost\/filesystem\/path.hpp>\n#include <boost\/filesystem\/operations.hpp>\n#include <set>\n#include <map>\n#include <cctype>\n#include <string>\n#include <algorithm>\n#include <iostream>\n\nusing namespace std;\nusing namespace boost::filesystem;\n\nstatic map<string, std::time_t> dircache;\nstatic map<string, string> cache;\n\nstatic bool checkDirCache(path &dir);\nstatic bool doCacheDir(path &dir);\n\n\/* C++ is far too verbose for its own good *\/\nstatic string toLowerCase(string in) {\n\ttransform(in.begin(), in.end(), in.begin(), (int(*)(int))tolower);\n\treturn in;\n}\n\nstatic path lcpath(path &orig) {\n\treturn path(toLowerCase(orig.string()), native);\n}\n\nstatic path lcleaf(path &orig) {\n\tpath br, leaf;\n\tbr = orig.branch_path();\n\tleaf = path(toLowerCase(orig.leaf()), native);\n\treturn br \/ leaf;\n}\n\nbool resolveFile(path &p) {\n\tstring s = p.string();\n\tif (!resolveFile(s))\n\t\treturn false;\n\tp = path(s, native);\n\treturn true;\n}\n\nbool resolveFile_(string &srcPath) {\n\tpath orig(srcPath, native);\n\tif (exists(orig))\n\t\treturn true;\n\t\n\torig.normalize();\n\tpath dir = orig.branch_path();\n\tpath leaf = path(orig.leaf(), native);\n\n\tif (!checkDirCache(dir))\n\t\treturn false;\n\n\torig = dir \/ lcpath(leaf);\n\tstring fn = orig.string();\n\n\tif (exists(orig)) {\n\t\tsrcPath = fn;\n\t\treturn true;\n\t}\n\n\tmap<string, string>::iterator i = cache.find(fn);\n\tif (i == cache.end()) {\n\t\tassert(!exists(orig));\n\t\treturn false;\n\t}\n\tsrcPath = cache[fn];\n\treturn true;\n}\n\nbool resolveFile(std::string &path) {\n\tstd::string orig = path;\n\tbool res = resolveFile_(path);\n#if 1\n\tstd::cerr << orig << \" -> \";\n\tif (!res)\n\t\tstd::cerr << \"(nil)\";\n\telse\n\t\tstd::cerr << path;\n\tstd::cerr << std::endl;\n#endif\n\treturn res;\n}\n\n\n\/* If dir is cached, do nothing.\n * If dir exists, cache it.\n * If dir does not exist, see if there's one with different capitalization.\n *\n * If we find a dir, return true. Else, false.\n *\/\nbool checkDirCache(path &dir) {\n\tif (dircache.end() != dircache.find(dir.string())) {\n\t\tif (exists(dir) && last_write_time(dir) == dircache[dir.string()])\n\t\t\treturn true;\n\t}\n\tif (exists(dir))\n\t\treturn doCacheDir(dir);\n\tif (dir.empty())\n\t\treturn false;\n\tbool res = resolveFile(dir);\n\tif (!res)\n\t\treturn false;\n\treturn checkDirCache(dir);\n}\n\n\/* Cache a dir. Return true for success.\n *\/\nbool doCacheDir(path &dir) {\n\tdirectory_iterator it(dir);\n\tdirectory_iterator fsend;\n\twhile (it != fsend) {\n\t\tpath cur = *it++;\n\t\tstring key, val;\n\t\tkey = cur.string();\n\t\tval = lcleaf(cur).string();\n\t\tcache[val] = key;\n\t}\n\tdircache[dir.string()] = last_write_time(dir);\n\treturn true;\n}\n\/* vim: set noet: *\/\n<commit_msg>re-disable debug messages from PathResolver<commit_after>\/*\n * PathResolver.cpp\n * openc2e\n *\n * Created by Bryan Donlan\n * Copyright (c) 2005 Bryan Donlan. All rights reserved.\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n *\/\n\n#include \"PathResolver.h\"\n\n#include <boost\/filesystem\/path.hpp>\n#include <boost\/filesystem\/operations.hpp>\n#include <set>\n#include <map>\n#include <cctype>\n#include <string>\n#include <algorithm>\n#include <iostream>\n\nusing namespace std;\nusing namespace boost::filesystem;\n\nstatic map<string, std::time_t> dircache;\nstatic map<string, string> cache;\n\nstatic bool checkDirCache(path &dir);\nstatic bool doCacheDir(path &dir);\n\n\/* C++ is far too verbose for its own good *\/\nstatic string toLowerCase(string in) {\n\ttransform(in.begin(), in.end(), in.begin(), (int(*)(int))tolower);\n\treturn in;\n}\n\nstatic path lcpath(path &orig) {\n\treturn path(toLowerCase(orig.string()), native);\n}\n\nstatic path lcleaf(path &orig) {\n\tpath br, leaf;\n\tbr = orig.branch_path();\n\tleaf = path(toLowerCase(orig.leaf()), native);\n\treturn br \/ leaf;\n}\n\nbool resolveFile(path &p) {\n\tstring s = p.string();\n\tif (!resolveFile(s))\n\t\treturn false;\n\tp = path(s, native);\n\treturn true;\n}\n\nbool resolveFile_(string &srcPath) {\n\tpath orig(srcPath, native);\n\tif (exists(orig))\n\t\treturn true;\n\t\n\torig.normalize();\n\tpath dir = orig.branch_path();\n\tpath leaf = path(orig.leaf(), native);\n\n\tif (!checkDirCache(dir))\n\t\treturn false;\n\n\torig = dir \/ lcpath(leaf);\n\tstring fn = orig.string();\n\n\tif (exists(orig)) {\n\t\tsrcPath = fn;\n\t\treturn true;\n\t}\n\n\tmap<string, string>::iterator i = cache.find(fn);\n\tif (i == cache.end()) {\n\t\tassert(!exists(orig));\n\t\treturn false;\n\t}\n\tsrcPath = cache[fn];\n\treturn true;\n}\n\nbool resolveFile(std::string &path) {\n\tstd::string orig = path;\n\tbool res = resolveFile_(path);\n#if 0\n\tstd::cerr << orig << \" -> \";\n\tif (!res)\n\t\tstd::cerr << \"(nil)\";\n\telse\n\t\tstd::cerr << path;\n\tstd::cerr << std::endl;\n#endif\n\treturn res;\n}\n\n\n\/* If dir is cached, do nothing.\n * If dir exists, cache it.\n * If dir does not exist, see if there's one with different capitalization.\n *\n * If we find a dir, return true. Else, false.\n *\/\nbool checkDirCache(path &dir) {\n\tif (dircache.end() != dircache.find(dir.string())) {\n\t\tif (exists(dir) && last_write_time(dir) == dircache[dir.string()])\n\t\t\treturn true;\n\t}\n\tif (exists(dir))\n\t\treturn doCacheDir(dir);\n\tif (dir.empty())\n\t\treturn false;\n\tbool res = resolveFile(dir);\n\tif (!res)\n\t\treturn false;\n\treturn checkDirCache(dir);\n}\n\n\/* Cache a dir. Return true for success.\n *\/\nbool doCacheDir(path &dir) {\n\tdirectory_iterator it(dir);\n\tdirectory_iterator fsend;\n\twhile (it != fsend) {\n\t\tpath cur = *it++;\n\t\tstring key, val;\n\t\tkey = cur.string();\n\t\tval = lcleaf(cur).string();\n\t\tcache[val] = key;\n\t}\n\tdircache[dir.string()] = last_write_time(dir);\n\treturn true;\n}\n\/* vim: set noet: *\/\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright © 2011 Intel Corporation\n *\n * Permission is hereby granted, free of charge, to any person obtaining a\n * copy of this software and associated documentation files (the \"Software\"),\n * to deal in the Software without restriction, including without limitation\n * the rights to use, copy, modify, merge, publish, distribute, sublicense,\n * and\/or sell copies of the Software, and to permit persons to whom the\n * Software is furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice (including the next\n * paragraph) shall be included in all copies or substantial portions of the\n * Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n * DEALINGS IN THE SOFTWARE.\n *\/\n\n\/**\n * \\file ir_function_detect_recursion.cpp\n * Determine whether a shader contains static recursion.\n *\n * Consider the (possibly disjoint) graph of function calls in a shader. If a\n * program contains recursion, this graph will contain a cycle. If a function\n * is part of a cycle, it will have a caller and it will have a callee (it\n * calls another function).\n *\n * To detect recursion, the function call graph is constructed. The graph is\n * repeatedly reduced by removing any function that either has no callees\n * (leaf functions) or has no caller. Eventually the only functions that\n * remain will be the functions in the cycles.\n *\n * The GLSL spec is a bit wishy-washy about recursion.\n *\n * From page 39 (page 45 of the PDF) of the GLSL 1.10 spec:\n *\n * \"Behavior is undefined if recursion is used. Recursion means having any\n * function appearing more than once at any one time in the run-time stack\n * of function calls. That is, a function may not call itself either\n * directly or indirectly. Compilers may give diagnostic messages when\n * this is detectable at compile time, but not all such cases can be\n * detected at compile time.\"\n *\n * From page 79 (page 85 of the PDF):\n *\n * \"22) Should recursion be supported?\n *\n * DISCUSSION: Probably not necessary, but another example of limiting\n * the language based on how it would directly map to hardware. One\n * thought is that recursion would benefit ray tracing shaders. On the\n * other hand, many recursion operations can also be implemented with the\n * user managing the recursion through arrays. RenderMan doesn't support\n * recursion. This could be added at a later date, if it proved to be\n * necessary.\n *\n * RESOLVED on September 10, 2002: Implementations are not required to\n * support recursion.\n *\n * CLOSED on September 10, 2002.\"\n *\n * From page 79 (page 85 of the PDF):\n *\n * \"56) Is it an error for an implementation to support recursion if the\n * specification says recursion is not supported?\n *\n * ADDED on September 10, 2002.\n *\n * DISCUSSION: This issues is related to Issue (22). If we say that\n * recursion (or some other piece of functionality) is not supported, is\n * it an error for an implementation to support it? Perhaps the\n * specification should remain silent on these kind of things so that they\n * could be gracefully added later as an extension or as part of the\n * standard.\n *\n * RESOLUTION: Languages, in general, have programs that are not\n * well-formed in ways a compiler cannot detect. Portability is only\n * ensured for well-formed programs. Detecting recursion is an example of\n * this. The language will say a well-formed program may not recurse, but\n * compilers are not forced to detect that recursion may happen.\n *\n * CLOSED: November 29, 2002.\"\n *\n * In GLSL 1.10 the behavior of recursion is undefined. Compilers don't have\n * to reject shaders (at compile-time or link-time) that contain recursion.\n * Instead they could work, or crash, or kill a kitten.\n *\n * From page 44 (page 50 of the PDF) of the GLSL 1.20 spec:\n *\n * \"Recursion is not allowed, not even statically. Static recursion is\n * present if the static function call graph of the program contains\n * cycles.\"\n *\n * This langauge clears things up a bit, but it still leaves a lot of\n * questions unanswered.\n *\n * - Is the error generated at compile-time or link-time?\n *\n * - Is it an error to have a recursive function that is never statically\n * called by main or any function called directly or indirectly by main?\n * Technically speaking, such a function is not in the \"static function\n * call graph of the program\" at all.\n *\n * \\bug\n * If a shader has multiple cycles, this algorithm may erroneously complain\n * about functions that aren't in any cycle, but are in the part of the call\n * tree that connects them. For example, if the call graph consists of a\n * cycle between A and B, and a cycle between D and E, and B also calls C\n * which calls D, then this algorithm will report C as a function which \"has\n * static recursion\" even though it is not part of any cycle.\n *\n * A better algorithm for cycle detection that doesn't have this drawback can\n * be found here:\n *\n * http:\/\/en.wikipedia.org\/wiki\/Tarjan%E2%80%99s_strongly_connected_components_algorithm\n *\n * \\author Ian Romanick <ian.d.romanick@intel.com>\n *\/\n#include \"main\/core.h\"\n#include \"ir.h\"\n#include \"glsl_parser_extras.h\"\n#include \"linker.h\"\n#include \"program\/hash_table.h\"\n#include \"program.h\"\n\nstruct call_node : public exec_node {\n class function *func;\n};\n\nclass function {\npublic:\n function(ir_function_signature *sig)\n : sig(sig)\n {\n \/* empty *\/\n }\n\n\n \/* Callers of this ralloc-based new need not call delete. It's\n * easier to just ralloc_free 'ctx' (or any of its ancestors). *\/\n static void* operator new(size_t size, void *ctx)\n {\n void *node;\n\n node = ralloc_size(ctx, size);\n assert(node != NULL);\n\n return node;\n }\n\n \/* If the user *does* call delete, that's OK, we will just\n * ralloc_free in that case. *\/\n static void operator delete(void *node)\n {\n ralloc_free(node);\n }\n\n ir_function_signature *sig;\n\n \/** List of functions called by this function. *\/\n exec_list callees;\n\n \/** List of functions that call this function. *\/\n exec_list callers;\n};\n\nclass has_recursion_visitor : public ir_hierarchical_visitor {\npublic:\n has_recursion_visitor()\n : current(NULL)\n {\n this->mem_ctx = ralloc_context(NULL);\n this->function_hash = hash_table_ctor(0, hash_table_pointer_hash,\n\t\t\t\t\t hash_table_pointer_compare);\n }\n\n ~has_recursion_visitor()\n {\n hash_table_dtor(this->function_hash);\n ralloc_free(this->mem_ctx);\n }\n\n function *get_function(ir_function_signature *sig)\n {\n function *f = (function *) hash_table_find(this->function_hash, sig);\n if (f == NULL) {\n\t f = new(mem_ctx) function(sig);\n\t hash_table_insert(this->function_hash, f, sig);\n }\n\n return f;\n }\n\n virtual ir_visitor_status visit_enter(ir_function_signature *sig)\n {\n this->current = this->get_function(sig);\n return visit_continue;\n }\n\n virtual ir_visitor_status visit_leave(ir_function_signature *sig)\n {\n (void) sig;\n this->current = NULL;\n return visit_continue;\n }\n\n virtual ir_visitor_status visit_enter(ir_call *call)\n {\n \/* At global scope this->current will be NULL. Since there is no way to\n * call global scope, it can never be part of a cycle. Don't bother\n * adding calls from global scope to the graph.\n *\/\n if (this->current == NULL)\n\t return visit_continue;\n\n function *const target = this->get_function(call->callee);\n\n \/* Create a link from the caller to the callee.\n *\/\n call_node *node = new(mem_ctx) call_node;\n node->func = target;\n this->current->callees.push_tail(node);\n\n \/* Create a link from the callee to the caller.\n *\/\n node = new(mem_ctx) call_node;\n node->func = this->current;\n target->callers.push_tail(node);\n return visit_continue;\n }\n\n function *current;\n struct hash_table *function_hash;\n void *mem_ctx;\n bool progress;\n};\n\nstatic void\ndestroy_links(exec_list *list, function *f)\n{\n foreach_list_safe(node, list) {\n struct call_node *n = (struct call_node *) node;\n\n \/* If this is the right function, remove it. Note that the loop cannot\n * terminate now. There can be multiple links to a function if it is\n * either called multiple times or calls multiple times.\n *\/\n if (n->func == f)\n\t n->remove();\n }\n}\n\n\n\/**\n * Remove a function if it has either no in or no out links\n *\/\nstatic void\nremove_unlinked_functions(const void *key, void *data, void *closure)\n{\n has_recursion_visitor *visitor = (has_recursion_visitor *) closure;\n function *f = (function *) data;\n\n if (f->callers.is_empty() || f->callees.is_empty()) {\n while (!f->callers.is_empty()) {\n\t struct call_node *n = (struct call_node *) f->callers.pop_head();\n\t destroy_links(& n->func->callees, f);\n }\n\n while (!f->callees.is_empty()) {\n\t struct call_node *n = (struct call_node *) f->callees.pop_head();\n\t destroy_links(& n->func->callers, f);\n }\n\n hash_table_remove(visitor->function_hash, key);\n visitor->progress = true;\n }\n}\n\n\nstatic void\nemit_errors_unlinked(const void *key, void *data, void *closure)\n{\n struct _mesa_glsl_parse_state *state =\n (struct _mesa_glsl_parse_state *) closure;\n function *f = (function *) data;\n YYLTYPE loc;\n\n (void) key;\n\n char *proto = prototype_string(f->sig->return_type,\n\t\t\t\t f->sig->function_name(),\n\t\t\t\t &f->sig->parameters);\n\n memset(&loc, 0, sizeof(loc));\n _mesa_glsl_error(&loc, state,\n\t\t \"function `%s' has static recursion.\",\n\t\t proto);\n ralloc_free(proto);\n}\n\n\nstatic void\nemit_errors_linked(const void *key, void *data, void *closure)\n{\n struct gl_shader_program *prog =\n (struct gl_shader_program *) closure;\n function *f = (function *) data;\n\n (void) key;\n\n char *proto = prototype_string(f->sig->return_type,\n\t\t\t\t f->sig->function_name(),\n\t\t\t\t &f->sig->parameters);\n\n linker_error(prog, \"function `%s' has static recursion.\\n\", proto);\n ralloc_free(proto);\n prog->LinkStatus = false;\n}\n\n\nvoid\ndetect_recursion_unlinked(struct _mesa_glsl_parse_state *state,\n\t\t\t exec_list *instructions)\n{\n has_recursion_visitor v;\n\n \/* Collect all of the information about which functions call which other\n * functions.\n *\/\n v.run(instructions);\n\n \/* Remove from the set all of the functions that either have no caller or\n * call no other functions. Repeat until no functions are removed.\n *\/\n do {\n v.progress = false;\n hash_table_call_foreach(v.function_hash, remove_unlinked_functions, & v);\n } while (v.progress);\n\n\n \/* At this point any functions still in the hash must be part of a cycle.\n *\/\n hash_table_call_foreach(v.function_hash, emit_errors_unlinked, state);\n}\n\n\nvoid\ndetect_recursion_linked(struct gl_shader_program *prog,\n\t\t\texec_list *instructions)\n{\n has_recursion_visitor v;\n\n \/* Collect all of the information about which functions call which other\n * functions.\n *\/\n v.run(instructions);\n\n \/* Remove from the set all of the functions that either have no caller or\n * call no other functions. Repeat until no functions are removed.\n *\/\n do {\n v.progress = false;\n hash_table_call_foreach(v.function_hash, remove_unlinked_functions, & v);\n } while (v.progress);\n\n\n \/* At this point any functions still in the hash must be part of a cycle.\n *\/\n hash_table_call_foreach(v.function_hash, emit_errors_linked, prog);\n}\n<commit_msg>glsl: fix uninitialised variable from constructor<commit_after>\/*\n * Copyright © 2011 Intel Corporation\n *\n * Permission is hereby granted, free of charge, to any person obtaining a\n * copy of this software and associated documentation files (the \"Software\"),\n * to deal in the Software without restriction, including without limitation\n * the rights to use, copy, modify, merge, publish, distribute, sublicense,\n * and\/or sell copies of the Software, and to permit persons to whom the\n * Software is furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice (including the next\n * paragraph) shall be included in all copies or substantial portions of the\n * Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n * DEALINGS IN THE SOFTWARE.\n *\/\n\n\/**\n * \\file ir_function_detect_recursion.cpp\n * Determine whether a shader contains static recursion.\n *\n * Consider the (possibly disjoint) graph of function calls in a shader. If a\n * program contains recursion, this graph will contain a cycle. If a function\n * is part of a cycle, it will have a caller and it will have a callee (it\n * calls another function).\n *\n * To detect recursion, the function call graph is constructed. The graph is\n * repeatedly reduced by removing any function that either has no callees\n * (leaf functions) or has no caller. Eventually the only functions that\n * remain will be the functions in the cycles.\n *\n * The GLSL spec is a bit wishy-washy about recursion.\n *\n * From page 39 (page 45 of the PDF) of the GLSL 1.10 spec:\n *\n * \"Behavior is undefined if recursion is used. Recursion means having any\n * function appearing more than once at any one time in the run-time stack\n * of function calls. That is, a function may not call itself either\n * directly or indirectly. Compilers may give diagnostic messages when\n * this is detectable at compile time, but not all such cases can be\n * detected at compile time.\"\n *\n * From page 79 (page 85 of the PDF):\n *\n * \"22) Should recursion be supported?\n *\n * DISCUSSION: Probably not necessary, but another example of limiting\n * the language based on how it would directly map to hardware. One\n * thought is that recursion would benefit ray tracing shaders. On the\n * other hand, many recursion operations can also be implemented with the\n * user managing the recursion through arrays. RenderMan doesn't support\n * recursion. This could be added at a later date, if it proved to be\n * necessary.\n *\n * RESOLVED on September 10, 2002: Implementations are not required to\n * support recursion.\n *\n * CLOSED on September 10, 2002.\"\n *\n * From page 79 (page 85 of the PDF):\n *\n * \"56) Is it an error for an implementation to support recursion if the\n * specification says recursion is not supported?\n *\n * ADDED on September 10, 2002.\n *\n * DISCUSSION: This issues is related to Issue (22). If we say that\n * recursion (or some other piece of functionality) is not supported, is\n * it an error for an implementation to support it? Perhaps the\n * specification should remain silent on these kind of things so that they\n * could be gracefully added later as an extension or as part of the\n * standard.\n *\n * RESOLUTION: Languages, in general, have programs that are not\n * well-formed in ways a compiler cannot detect. Portability is only\n * ensured for well-formed programs. Detecting recursion is an example of\n * this. The language will say a well-formed program may not recurse, but\n * compilers are not forced to detect that recursion may happen.\n *\n * CLOSED: November 29, 2002.\"\n *\n * In GLSL 1.10 the behavior of recursion is undefined. Compilers don't have\n * to reject shaders (at compile-time or link-time) that contain recursion.\n * Instead they could work, or crash, or kill a kitten.\n *\n * From page 44 (page 50 of the PDF) of the GLSL 1.20 spec:\n *\n * \"Recursion is not allowed, not even statically. Static recursion is\n * present if the static function call graph of the program contains\n * cycles.\"\n *\n * This langauge clears things up a bit, but it still leaves a lot of\n * questions unanswered.\n *\n * - Is the error generated at compile-time or link-time?\n *\n * - Is it an error to have a recursive function that is never statically\n * called by main or any function called directly or indirectly by main?\n * Technically speaking, such a function is not in the \"static function\n * call graph of the program\" at all.\n *\n * \\bug\n * If a shader has multiple cycles, this algorithm may erroneously complain\n * about functions that aren't in any cycle, but are in the part of the call\n * tree that connects them. For example, if the call graph consists of a\n * cycle between A and B, and a cycle between D and E, and B also calls C\n * which calls D, then this algorithm will report C as a function which \"has\n * static recursion\" even though it is not part of any cycle.\n *\n * A better algorithm for cycle detection that doesn't have this drawback can\n * be found here:\n *\n * http:\/\/en.wikipedia.org\/wiki\/Tarjan%E2%80%99s_strongly_connected_components_algorithm\n *\n * \\author Ian Romanick <ian.d.romanick@intel.com>\n *\/\n#include \"main\/core.h\"\n#include \"ir.h\"\n#include \"glsl_parser_extras.h\"\n#include \"linker.h\"\n#include \"program\/hash_table.h\"\n#include \"program.h\"\n\nstruct call_node : public exec_node {\n class function *func;\n};\n\nclass function {\npublic:\n function(ir_function_signature *sig)\n : sig(sig)\n {\n \/* empty *\/\n }\n\n\n \/* Callers of this ralloc-based new need not call delete. It's\n * easier to just ralloc_free 'ctx' (or any of its ancestors). *\/\n static void* operator new(size_t size, void *ctx)\n {\n void *node;\n\n node = ralloc_size(ctx, size);\n assert(node != NULL);\n\n return node;\n }\n\n \/* If the user *does* call delete, that's OK, we will just\n * ralloc_free in that case. *\/\n static void operator delete(void *node)\n {\n ralloc_free(node);\n }\n\n ir_function_signature *sig;\n\n \/** List of functions called by this function. *\/\n exec_list callees;\n\n \/** List of functions that call this function. *\/\n exec_list callers;\n};\n\nclass has_recursion_visitor : public ir_hierarchical_visitor {\npublic:\n has_recursion_visitor()\n : current(NULL)\n {\n progress = false;\n this->mem_ctx = ralloc_context(NULL);\n this->function_hash = hash_table_ctor(0, hash_table_pointer_hash,\n\t\t\t\t\t hash_table_pointer_compare);\n }\n\n ~has_recursion_visitor()\n {\n hash_table_dtor(this->function_hash);\n ralloc_free(this->mem_ctx);\n }\n\n function *get_function(ir_function_signature *sig)\n {\n function *f = (function *) hash_table_find(this->function_hash, sig);\n if (f == NULL) {\n\t f = new(mem_ctx) function(sig);\n\t hash_table_insert(this->function_hash, f, sig);\n }\n\n return f;\n }\n\n virtual ir_visitor_status visit_enter(ir_function_signature *sig)\n {\n this->current = this->get_function(sig);\n return visit_continue;\n }\n\n virtual ir_visitor_status visit_leave(ir_function_signature *sig)\n {\n (void) sig;\n this->current = NULL;\n return visit_continue;\n }\n\n virtual ir_visitor_status visit_enter(ir_call *call)\n {\n \/* At global scope this->current will be NULL. Since there is no way to\n * call global scope, it can never be part of a cycle. Don't bother\n * adding calls from global scope to the graph.\n *\/\n if (this->current == NULL)\n\t return visit_continue;\n\n function *const target = this->get_function(call->callee);\n\n \/* Create a link from the caller to the callee.\n *\/\n call_node *node = new(mem_ctx) call_node;\n node->func = target;\n this->current->callees.push_tail(node);\n\n \/* Create a link from the callee to the caller.\n *\/\n node = new(mem_ctx) call_node;\n node->func = this->current;\n target->callers.push_tail(node);\n return visit_continue;\n }\n\n function *current;\n struct hash_table *function_hash;\n void *mem_ctx;\n bool progress;\n};\n\nstatic void\ndestroy_links(exec_list *list, function *f)\n{\n foreach_list_safe(node, list) {\n struct call_node *n = (struct call_node *) node;\n\n \/* If this is the right function, remove it. Note that the loop cannot\n * terminate now. There can be multiple links to a function if it is\n * either called multiple times or calls multiple times.\n *\/\n if (n->func == f)\n\t n->remove();\n }\n}\n\n\n\/**\n * Remove a function if it has either no in or no out links\n *\/\nstatic void\nremove_unlinked_functions(const void *key, void *data, void *closure)\n{\n has_recursion_visitor *visitor = (has_recursion_visitor *) closure;\n function *f = (function *) data;\n\n if (f->callers.is_empty() || f->callees.is_empty()) {\n while (!f->callers.is_empty()) {\n\t struct call_node *n = (struct call_node *) f->callers.pop_head();\n\t destroy_links(& n->func->callees, f);\n }\n\n while (!f->callees.is_empty()) {\n\t struct call_node *n = (struct call_node *) f->callees.pop_head();\n\t destroy_links(& n->func->callers, f);\n }\n\n hash_table_remove(visitor->function_hash, key);\n visitor->progress = true;\n }\n}\n\n\nstatic void\nemit_errors_unlinked(const void *key, void *data, void *closure)\n{\n struct _mesa_glsl_parse_state *state =\n (struct _mesa_glsl_parse_state *) closure;\n function *f = (function *) data;\n YYLTYPE loc;\n\n (void) key;\n\n char *proto = prototype_string(f->sig->return_type,\n\t\t\t\t f->sig->function_name(),\n\t\t\t\t &f->sig->parameters);\n\n memset(&loc, 0, sizeof(loc));\n _mesa_glsl_error(&loc, state,\n\t\t \"function `%s' has static recursion.\",\n\t\t proto);\n ralloc_free(proto);\n}\n\n\nstatic void\nemit_errors_linked(const void *key, void *data, void *closure)\n{\n struct gl_shader_program *prog =\n (struct gl_shader_program *) closure;\n function *f = (function *) data;\n\n (void) key;\n\n char *proto = prototype_string(f->sig->return_type,\n\t\t\t\t f->sig->function_name(),\n\t\t\t\t &f->sig->parameters);\n\n linker_error(prog, \"function `%s' has static recursion.\\n\", proto);\n ralloc_free(proto);\n prog->LinkStatus = false;\n}\n\n\nvoid\ndetect_recursion_unlinked(struct _mesa_glsl_parse_state *state,\n\t\t\t exec_list *instructions)\n{\n has_recursion_visitor v;\n\n \/* Collect all of the information about which functions call which other\n * functions.\n *\/\n v.run(instructions);\n\n \/* Remove from the set all of the functions that either have no caller or\n * call no other functions. Repeat until no functions are removed.\n *\/\n do {\n v.progress = false;\n hash_table_call_foreach(v.function_hash, remove_unlinked_functions, & v);\n } while (v.progress);\n\n\n \/* At this point any functions still in the hash must be part of a cycle.\n *\/\n hash_table_call_foreach(v.function_hash, emit_errors_unlinked, state);\n}\n\n\nvoid\ndetect_recursion_linked(struct gl_shader_program *prog,\n\t\t\texec_list *instructions)\n{\n has_recursion_visitor v;\n\n \/* Collect all of the information about which functions call which other\n * functions.\n *\/\n v.run(instructions);\n\n \/* Remove from the set all of the functions that either have no caller or\n * call no other functions. Repeat until no functions are removed.\n *\/\n do {\n v.progress = false;\n hash_table_call_foreach(v.function_hash, remove_unlinked_functions, & v);\n } while (v.progress);\n\n\n \/* At this point any functions still in the hash must be part of a cycle.\n *\/\n hash_table_call_foreach(v.function_hash, emit_errors_linked, prog);\n}\n<|endoftext|>"} {"text":"<commit_before>\/*******************************************************************************\n * pxgsettings - A helper binary to query gsettings\n * Copyright (C) 2006 Nathaniel McCallum <nathaniel@natemccallum.com>\n * Copyright (C) 2011 Dominique Leuenberger <dominique@leuenberger.net>\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n ******************************************************************************\/\n\n#include <cstdio>\n#include <unistd.h>\n#include <signal.h>\n#include <stdexcept>\n\n#include <glib.h>\n#include <glib-object.h>\n#include <gio\/gio.h>\n\nusing namespace std;\n\nstatic GMainLoop* loop = NULL;\n\nstatic int print_value(GVariant *value, const char *suffix) {\n\n\tif (!value) return 0;\n\tif (g_variant_is_of_type(value, G_VARIANT_TYPE_STRING)) {\n\t\treturn printf(\"%s%s\", g_variant_get_string(value, NULL), suffix);\n\t}\n\telse if(g_variant_is_of_type(value, G_VARIANT_TYPE_INT32)) {\n\t\treturn printf(\"%d%s\", g_variant_get_int32(value), suffix);\n\t}\n\telse if(g_variant_is_of_type(value, G_VARIANT_TYPE_BOOLEAN)) {\n\t\tgboolean result;\n\t\tresult = g_variant_get_boolean(value);\n\t\treturn printf(\"%s%s\", result ? \"true\" : \"false\", suffix);\n\t}\n\telse if(g_variant_is_of_type(value, G_VARIANT_TYPE_ARRAY)) {\n\t\tint count;\n\t\tconst gchar** items;\n\t\titems = g_variant_get_strv(value, NULL);\n\t\tfor (count=0; items[count]; count++) {\n\t\t\tprintf(\"%s%s\", count < 2 ? \"\" : \",\", items[count]);\n\t\t}\n\t\tprintf(\"%s\", suffix);\n\t\treturn count;\n\t}\n\telse {\n\t\tthrow exception();\n\t}\n\n\treturn 0;\n}\n\nstatic void on_value_change(GSettings *settings, const gchar *key, gpointer user_data) {\n\tprintf(\"%s\/%s\\t\", (gchar *)user_data, key);\n\tprint_value(g_settings_get_value(settings, key), \"\\n\");\n}\n\nstatic void on_sig(int \/*signal*\/) {\n\tg_main_loop_quit(loop);\n}\n\nstatic gboolean err(GIOChannel* \/*source*\/, GIOCondition \/*condition*\/, gpointer \/*data*\/) {\n\tg_main_loop_quit(loop);\n\treturn false;\n}\n\nstatic gboolean in(GIOChannel *source, GIOCondition condition, gpointer data) {\n\tgchar *key, *val;\n\tGIOStatus st = g_io_channel_read_line(source, &key, NULL, NULL, NULL);\n\n\t\/\/ Remove the trailing '\\n'\n\tfor (int i=0 ; key && key[i] ; i++)\n\t\tif (key[i] == '\\n')\n\t\t\tkey[i] = '\\0';\n\n\t\/\/ If we were successful\n\tif (key && st == G_IO_STATUS_NORMAL) {\n\t\tif (!g_strrstr(key, \"\\t\"))\n\t\t\tgoto exit;\n\n\t\tval = g_strrstr(key, \"\\t\") + 1;\n\t\t*(val-1) = '\\0';\n\n\t\tg_free(key);\n\t\treturn true;\n\t}\n\telse if (key && st == G_IO_STATUS_AGAIN) {\n\t\tg_free(key);\n\t\treturn in(source, condition, data);\n\t}\n\nexit:\n\tg_free(key);\n\treturn err(source, condition, data);\n}\n\nint main(int argc, char **argv) {\n\tif (argc < 2) return 1;\n\n\t\/\/ Register sighup handler\n\tif (signal(SIGHUP, on_sig) == SIG_ERR || signal(SIGPIPE, on_sig) == SIG_ERR || signal(SIGABRT, on_sig) == SIG_ERR) {\n\t\tfprintf(stderr, \"Unable to trap signals!\");\n\t\treturn 2;\n\t}\n\n\t\/\/ Switch stdout to line buffering\n\tif (setvbuf(stdout, NULL, _IOLBF, 0)) {\n\t\tfprintf(stderr, \"Unable to switch stdout to line buffering!\");\n\t\treturn 3;\n\t}\n\n\t\/\/ Switch stdin to line buffering\n\tif (setvbuf(stdin, NULL, _IOLBF, 0)) {\n\t\tfprintf(stderr, \"Unable to switch stdin to line buffering!\");\n\t\treturn 4;\n\t}\n\n\t\/\/ Init\n\tg_type_init();\n\n\t\/\/ Get the main loop\n\tloop = g_main_loop_new(NULL, false);\n\n\t\/\/ Setup our GIO Channels\n\tGIOChannel* inchan = g_io_channel_unix_new(fileno(stdin));\n\tGIOChannel* outchan = g_io_channel_unix_new(fileno(stdout));\n\tg_io_add_watch(inchan, G_IO_IN, in, NULL);\n\tg_io_add_watch(inchan, G_IO_PRI, in, NULL);\n\tg_io_add_watch(inchan, G_IO_ERR, err, NULL);\n\tg_io_add_watch(inchan, G_IO_HUP, err, NULL);\n\tg_io_add_watch(outchan, G_IO_ERR, err, NULL);\n\tg_io_add_watch(outchan, G_IO_HUP, err, NULL);\n\n\t\/\/ Get GConf client\n\tGSettings* client;\n\n\tfor (int i=1; i<argc; i++) {\n\t\tclient = g_settings_new(argv[i]);\n\t\tgchar** keys = g_settings_list_keys(client);\n\t\tfor (int j=0; keys[j]; on_value_change(client, keys[j++],argv[i] ));\n\t\tg_signal_connect(client, \"changed::\", (GCallback) on_value_change, argv[i]);\n\t}\n\n\n\tg_main_loop_run(loop);\n\n\t\/\/ Cleanup\n\twhile (G_IS_OBJECT(client)) {\n\t\tg_object_unref(client);\n\t}\n\tg_io_channel_shutdown(inchan, FALSE, NULL);\n\tg_io_channel_shutdown(outchan, FALSE, NULL);\n\tg_io_channel_unref(inchan);\n\tg_io_channel_unref(outchan);\n\tg_main_loop_unref(loop);\n}\n<commit_msg>pxgsettings: =\/-1.. counting can be so hard<commit_after>\/*******************************************************************************\n * pxgsettings - A helper binary to query gsettings\n * Copyright (C) 2006 Nathaniel McCallum <nathaniel@natemccallum.com>\n * Copyright (C) 2011 Dominique Leuenberger <dominique@leuenberger.net>\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n ******************************************************************************\/\n\n#include <cstdio>\n#include <unistd.h>\n#include <signal.h>\n#include <stdexcept>\n\n#include <glib.h>\n#include <glib-object.h>\n#include <gio\/gio.h>\n\nusing namespace std;\n\nstatic GMainLoop* loop = NULL;\n\nstatic int print_value(GVariant *value, const char *suffix) {\n\n\tif (!value) return 0;\n\tif (g_variant_is_of_type(value, G_VARIANT_TYPE_STRING)) {\n\t\treturn printf(\"%s%s\", g_variant_get_string(value, NULL), suffix);\n\t}\n\telse if(g_variant_is_of_type(value, G_VARIANT_TYPE_INT32)) {\n\t\treturn printf(\"%d%s\", g_variant_get_int32(value), suffix);\n\t}\n\telse if(g_variant_is_of_type(value, G_VARIANT_TYPE_BOOLEAN)) {\n\t\tgboolean result;\n\t\tresult = g_variant_get_boolean(value);\n\t\treturn printf(\"%s%s\", result ? \"true\" : \"false\", suffix);\n\t}\n\telse if(g_variant_is_of_type(value, G_VARIANT_TYPE_ARRAY)) {\n\t\tint count;\n\t\tconst gchar** items;\n\t\titems = g_variant_get_strv(value, NULL);\n\t\tfor (count=0; items[count]; count++) {\n\t\t\tprintf(\"%s%s\", count < 1 ? \"\" : \",\", items[count]);\n\t\t}\n\t\tprintf(\"%s\", suffix);\n\t\treturn count;\n\t}\n\telse {\n\t\tthrow exception();\n\t}\n\n\treturn 0;\n}\n\nstatic void on_value_change(GSettings *settings, const gchar *key, gpointer user_data) {\n\tprintf(\"%s\/%s\\t\", (gchar *)user_data, key);\n\tprint_value(g_settings_get_value(settings, key), \"\\n\");\n}\n\nstatic void on_sig(int \/*signal*\/) {\n\tg_main_loop_quit(loop);\n}\n\nstatic gboolean err(GIOChannel* \/*source*\/, GIOCondition \/*condition*\/, gpointer \/*data*\/) {\n\tg_main_loop_quit(loop);\n\treturn false;\n}\n\nstatic gboolean in(GIOChannel *source, GIOCondition condition, gpointer data) {\n\tgchar *key, *val;\n\tGIOStatus st = g_io_channel_read_line(source, &key, NULL, NULL, NULL);\n\n\t\/\/ Remove the trailing '\\n'\n\tfor (int i=0 ; key && key[i] ; i++)\n\t\tif (key[i] == '\\n')\n\t\t\tkey[i] = '\\0';\n\n\t\/\/ If we were successful\n\tif (key && st == G_IO_STATUS_NORMAL) {\n\t\tif (!g_strrstr(key, \"\\t\"))\n\t\t\tgoto exit;\n\n\t\tval = g_strrstr(key, \"\\t\") + 1;\n\t\t*(val-1) = '\\0';\n\n\t\tg_free(key);\n\t\treturn true;\n\t}\n\telse if (key && st == G_IO_STATUS_AGAIN) {\n\t\tg_free(key);\n\t\treturn in(source, condition, data);\n\t}\n\nexit:\n\tg_free(key);\n\treturn err(source, condition, data);\n}\n\nint main(int argc, char **argv) {\n\tif (argc < 2) return 1;\n\n\t\/\/ Register sighup handler\n\tif (signal(SIGHUP, on_sig) == SIG_ERR || signal(SIGPIPE, on_sig) == SIG_ERR || signal(SIGABRT, on_sig) == SIG_ERR) {\n\t\tfprintf(stderr, \"Unable to trap signals!\");\n\t\treturn 2;\n\t}\n\n\t\/\/ Switch stdout to line buffering\n\tif (setvbuf(stdout, NULL, _IOLBF, 0)) {\n\t\tfprintf(stderr, \"Unable to switch stdout to line buffering!\");\n\t\treturn 3;\n\t}\n\n\t\/\/ Switch stdin to line buffering\n\tif (setvbuf(stdin, NULL, _IOLBF, 0)) {\n\t\tfprintf(stderr, \"Unable to switch stdin to line buffering!\");\n\t\treturn 4;\n\t}\n\n\t\/\/ Init\n\tg_type_init();\n\n\t\/\/ Get the main loop\n\tloop = g_main_loop_new(NULL, false);\n\n\t\/\/ Setup our GIO Channels\n\tGIOChannel* inchan = g_io_channel_unix_new(fileno(stdin));\n\tGIOChannel* outchan = g_io_channel_unix_new(fileno(stdout));\n\tg_io_add_watch(inchan, G_IO_IN, in, NULL);\n\tg_io_add_watch(inchan, G_IO_PRI, in, NULL);\n\tg_io_add_watch(inchan, G_IO_ERR, err, NULL);\n\tg_io_add_watch(inchan, G_IO_HUP, err, NULL);\n\tg_io_add_watch(outchan, G_IO_ERR, err, NULL);\n\tg_io_add_watch(outchan, G_IO_HUP, err, NULL);\n\n\t\/\/ Get GConf client\n\tGSettings* client;\n\n\tfor (int i=1; i<argc; i++) {\n\t\tclient = g_settings_new(argv[i]);\n\t\tgchar** keys = g_settings_list_keys(client);\n\t\tfor (int j=0; keys[j]; on_value_change(client, keys[j++],argv[i] ));\n\t\tg_signal_connect(client, \"changed::\", (GCallback) on_value_change, argv[i]);\n\t}\n\n\n\tg_main_loop_run(loop);\n\n\t\/\/ Cleanup\n\twhile (G_IS_OBJECT(client)) {\n\t\tg_object_unref(client);\n\t}\n\tg_io_channel_shutdown(inchan, FALSE, NULL);\n\tg_io_channel_shutdown(outchan, FALSE, NULL);\n\tg_io_channel_unref(inchan);\n\tg_io_channel_unref(outchan);\n\tg_main_loop_unref(loop);\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2017 Kai Luo <gluokai@gmail.com>. All rights reserved.\n\/\/ Use of this source code is governed by the BSD license that can be found in\n\/\/ the LICENSE file.\n#include <sys\/time.h>\n\n#include \"logger.h\"\n\nnamespace kl {\nnamespace logging {\nconst char *kLogLevelString[5] = {\"INFO\", \"DEBUG\", \"WARN\", \"ERROR\", \"FATAL\"};\n\nLogger::Logger(std::function<void(const std::string &)> &&output)\n : log_level_(kInfo), output_(std::move(output)) {}\n\nLogger::Logger(int log_level, std::function<void(const std::string &)> &&output)\n : log_level_(log_level), output_(std::move(output)) {}\n\nstd::unique_ptr<Logger>\nLogger::default_logger_(new Logger([](const std::string &message) {\n std::fprintf(stderr, \"%s\\n\", message.c_str());\n}));\n\nvoid Logger::Logging(int log_level, const char *file, const char *func,\n int line, const char *fmt, ...) {\n if (log_level < log_level_) {\n return;\n }\n va_list ap;\n va_start(ap, fmt);\n Logging(log_level, file, func, line, fmt, ap);\n va_end(ap);\n}\n\nvoid Logger::Logging(int log_level, const char *file, const char *func,\n int line, const char *fmt, va_list ap) {\n if (log_level < log_level_) {\n return;\n }\n \/\/ [<log_level> yy\/mm\/dd-hr:min:sec.usec file:func:line]\n static const char *kPrefixFormat =\n \"[%s %04d\/%02d\/%02d-%02d:%02d:%02d.%06ld %s:%s:%d] \";\n struct timeval now;\n ::gettimeofday(&now, nullptr);\n struct tm t;\n ::localtime_r(&now.tv_sec, &t);\n int prefix_size =\n std::snprintf(nullptr, 0, kPrefixFormat, kLogLevelString[log_level],\n t.tm_year + 1900, t.tm_mon + 1, t.tm_mday, t.tm_hour,\n t.tm_min, t.tm_sec, now.tv_usec, file, func, line);\n va_list backup_ap;\n va_copy(backup_ap, ap);\n int msg_size = std::vsnprintf(nullptr, 0, fmt, backup_ap);\n va_end(backup_ap);\n\n int buf_size = prefix_size + msg_size + 1;\n char *buf = new char[buf_size];\n const char *base = buf;\n prefix_size =\n std::snprintf(buf, buf_size, kPrefixFormat, kLogLevelString[log_level],\n t.tm_year + 1900, t.tm_mon + 1, t.tm_mday, t.tm_hour,\n t.tm_min, t.tm_sec, now.tv_usec, file, func, line);\n buf += prefix_size;\n assert(buf_size >= prefix_size);\n std::vsnprintf(buf, buf_size - prefix_size, fmt, ap);\n output_(base);\n delete[] base;\n}\n\nLogger &Logger::DefaultLogger() {\n assert(default_logger_);\n return *default_logger_;\n}\n\nvoid Logger::SetDefaultLogger(Logger &&logger) {\n default_logger_ = std::make_unique<Logger>(std::move(logger));\n}\n\nvoid Logger::SetLogLevel(int log_level) { log_level_ = log_level; }\n\n} \/\/ namespace logging\n} \/\/ namespace kl\n<commit_msg>minir fix<commit_after>\/\/ Copyright (c) 2017 Kai Luo <gluokai@gmail.com>. All rights reserved.\n\/\/ Use of this source code is governed by the BSD license that can be found in\n\/\/ the LICENSE file.\n#include <sys\/time.h>\n\n#include \"logger.h\"\n\nnamespace kl {\nnamespace logging {\nconst char *kLogLevelString[5] = {\"INFO\", \"DEBUG\", \"WARN\", \"ERROR\", \"FATAL\"};\n\nLogger::Logger(std::function<void(const std::string &)> &&output)\n : log_level_(kInfo), output_(std::move(output)) {}\n\nLogger::Logger(int log_level, std::function<void(const std::string &)> &&output)\n : log_level_(log_level), output_(std::move(output)) {}\n\nstd::unique_ptr<Logger>\nLogger::default_logger_(new Logger([](const std::string &message) {\n std::fprintf(stderr, \"%s\\n\", message.c_str());\n}));\n\nvoid Logger::Logging(int log_level, const char *file, const char *func,\n int line, const char *fmt, ...) {\n if (log_level < log_level_) {\n return;\n }\n va_list ap;\n va_start(ap, fmt);\n Logging(log_level, file, func, line, fmt, ap);\n va_end(ap);\n}\n\nvoid Logger::Logging(int log_level, const char *file, const char *func,\n int line, const char *fmt, va_list ap) {\n if (log_level < log_level_) {\n return;\n }\n \/\/ [<log_level> yy\/mm\/dd-hr:min:sec.usec file:func:line]\n static const char *kPrefixFormat =\n \"[%s %04d\/%02d\/%02d-%02d:%02d:%02d.%06ld %s:%s:%d] \";\n struct timeval now;\n ::gettimeofday(&now, nullptr);\n struct tm t;\n ::localtime_r(&now.tv_sec, &t);\n int prefix_size =\n std::snprintf(nullptr, 0, kPrefixFormat, kLogLevelString[log_level],\n t.tm_year + 1900, t.tm_mon + 1, t.tm_mday, t.tm_hour,\n t.tm_min, t.tm_sec, now.tv_usec, file, func, line);\n va_list backup_ap;\n va_copy(backup_ap, ap);\n int msg_size = std::vsnprintf(nullptr, 0, fmt, backup_ap);\n va_end(backup_ap);\n\n int buf_size = prefix_size + msg_size + 1;\n char *buf = new char[buf_size + 1]; \/\/ to contain '\\n'\n const char *base = buf;\n prefix_size =\n std::snprintf(buf, buf_size, kPrefixFormat, kLogLevelString[log_level],\n t.tm_year + 1900, t.tm_mon + 1, t.tm_mday, t.tm_hour,\n t.tm_min, t.tm_sec, now.tv_usec, file, func, line);\n buf += prefix_size;\n assert(buf_size >= prefix_size);\n std::vsnprintf(buf, buf_size - prefix_size, fmt, ap);\n buf[buf_size - 1] = '\\n';\n buf[buf_size] = 0;\n output_(base);\n delete[] base;\n}\n\nLogger &Logger::DefaultLogger() {\n assert(default_logger_);\n return *default_logger_;\n}\n\nvoid Logger::SetDefaultLogger(Logger &&logger) {\n default_logger_ = std::make_unique<Logger>(std::move(logger));\n}\n\nvoid Logger::SetLogLevel(int log_level) { log_level_ = log_level; }\n\n} \/\/ namespace logging\n} \/\/ namespace kl\n<|endoftext|>"} {"text":"<commit_before>\/*\n * ChordNode.cpp\n * iPhone_p2p_engine\n *\n * Created by LogNet team 2010 - INRIA\n * Mediteranee - Sophia Antipolis - France\n *\n *\/\n\n#include \"ChordNode.h\"\n#include \"Stabilization.h\"\n#include \"CheckPred.h\"\n#include \"FixFinger.h\"\n#include \"TransportHTTP.h\"\n#include \"callbacks.h\"\n#include \"sha1.h\";\n#include <sstream>\n#include <iostream>\n#include <assert.h>\n#include <math.h>\n\n\/* Constructor *\/\nChordNode::ChordNode(const string &ip, int port, const string &overlayIdentifier, const string &rootDirectory) {\n\n\t\/\/ Define the address space size\n\tspacesize = 9;\n\n\t\/\/ Create the id\n\tstd::ostringstream oss;\n\toss << ip << port;\n\tint id = getSHA1(oss.str());\n\n\t\/\/ check if the idE[0, 2^(spacesize - 1)]\n\tassert(!(id > pow(2, spacesize)) && !(id < 0));\n\n\t\/\/create our stabilizer threads instance.\n\tstableThread = new Stabilization(this);\n\n\t\/\/Initialize the transport layer.\n\ttransport = new TransportHTTP(port, rootDirectory);\n\n\t\/\/set the overlay identifier.\n\tthis->overlayIdentifier = overlayIdentifier;\n\n\t\/\/ not yet notified\n\tnotified = false;\n\n\t\/\/Call our parent's initializer\n\tinitialise(ip, id, port);\n\n\t\/\/We start-up our stabilizer thread.\n\tcheckStable();\n}\n\n\/* Destructor *\/\nChordNode::~ChordNode() {\n\tstableThread->kill();\n\tdelete stableThread;\n\tdelete transport;\n}\n\n\/* Override from AbstractChord *\/\nvoid ChordNode::notify(Node *n) {\n\tNode *pred = predecessor;\n\t((AbstractChord *) this)->notify(n);\n\t\/\/ If the predecessor as changed, update the DHT table\n\tif (pred != predecessor) {\n\t\tnotified = true;\n\t}\n}\n\nvoid ChordNode::stabilize() {\n\t((AbstractChord *) this)->stabilize();\n\t\/\/ If the predecessor as changed, update the DHT table\n\tif (notified && predecessor->getId() != thisNode->getId()) {\n\t\tfor (dataMap::iterator it = table.begin(); it != table.end(); ++it) {\n\t\t\tRequest *request = new Request(this->getIdentifier(), PUT);\n\t\t\tint id = atoi(it->first.c_str());\n\t\t\tif (!insideRange(id, predecessor->getId(), thisNode->getId())) {\n\t\t\t\trequest->addArg(\"key\", it->first);\n\t\t\t\trequest->addArg(\"value\", it->second);\n\t\t\t\t\/\/ Send the Put request\n\t\t\t\tsendRequest(request, predecessor);\n\t\t\t\t\/\/ remove the key from my table\n\t\t\t\ttable.erase(it);\n\t\t\t}\n\t\t}\n\t\tnotified = false;\n\t}\n}\n\n\/* DHT Put *\/\nvoid ChordNode::put(string key, string value) {\n\t\/\/ Convert the key in a hash integer\n\tint hKey = getSHA1(key);\n\tif (insideRange(hKey, predecessor->getId() + 1, thisNode->getId())) {\n\t\t\/\/ I'm responsible for this key\n\t\tstringstream ss;\n\t\tss << table[key] << \"*******\";\n\t\ttable[key]=ss.str();\n\t} else {\n\t\t\/\/ Find the node responsible for this key\n\t\tNode *responsible = findSuccessor(hKey);\n\t\t\/\/ Create a Put request.\n\t\tRequest *request = new Request(this->getIdentifier(), PUT);\n\t\trequest->addArg(\"key\", key);\n\t\trequest->addArg(\"value\", value);\n\t\t\/\/ Send the Put request\n\t\tsendRequest(request, responsible);\n\t}\n}\n\n\/* DHT Get *\/\nstring ChordNode::get(string key) {\n\t\/\/ Convert the key in a hash integer\n\tint hKey = getSHA1(key);\n\tif (insideRange(hKey, predecessor->getId() + 1, thisNode->getId())) {\n\t\t\/\/ I'm responsible for this key\n\t\tdataMap::iterator it = table.find(key);\n\t\tif (it != table.end()) {\n\t\t\treturn (it->second);\n\t\t} else {\n\t\t\tstring err = \"no result\";\n\t\t\treturn err;\n\t\t}\n\t} else {\n\t\t\/\/ Find the node responsible for this key\n\t\tNode *responsible = findSuccessor(hKey);\n\t\t\/\/ Create a Put request.\n\t\tRequest *request = new Request(this->getIdentifier(), GET);\n\t\trequest->addArg(\"key\", key);\n\t\t\/\/ Send the Put request\n\t\treturn sendRequest(request, responsible);\n\t}\n}\n\n\/* DHT Remove *\/\nvoid ChordNode::removekey(string key) {\n\t\/\/ Convert the key in a hash integer\n\tint hKey = getSHA1(key);\n\tif (insideRange(hKey, predecessor->getId() + 1, thisNode->getId())) {\n\t\t\/\/ I'm responsible for this key\n\t\tdataMap::iterator it = table.find(key);\n\t\tif (it != table.end()) {\n\t\t\ttable.erase(it);\n\t\t}\n\t} else {\n\t\t\/\/ Find the node responsible for this key\n\t\tNode *responsible = findSuccessor(hKey);\n\t\t\/\/ Create a Put request.\n\t\tRequest *request = new Request(this->getIdentifier(), REMOVEKEY);\n\t\trequest->addArg(\"key\", key);\n\t\t\/\/ Send the Put request\n\t\tsendRequest(request, responsible);\n\t}\n}\n\n\/* Convert a string to an integer (using MD5) *\/\nunsigned int ChordNode::getSHA1(string str) {\n\tSHA1 *sha1 = new SHA1();\n\tsha1->addBytes( str.c_str(), strlen( str.c_str() ));\n\tunsigned char* digest = sha1->getDigest();\n\tunsigned int res = sha1->shaToInteger(digest, 20, pow(2, spacesize));\n\tdelete sha1;\n\tfree( digest );\n\treturn res;\n}\n\n\/* Forward a message to a peer, the message is in the format: \"<IP+PORT>,TRANSPORT_CODE\" *\/\nstring ChordNode::sendRequest(Request *request, Node* destination) {\n\tchar *response = transport->sendRequest(request, destination);\n\t\/\/ response received\n\tif (response) {\n\t\tstringstream ss;\n\t\tss << response;\n\t\tfree(response); \/\/ we must free the initial char* response, to avoid leaks.\n\t\treturn ss.str();\n\t} else {\n\t\t\/\/ Fix the broken pointers of the node\n\t\tfixBrokenPointers(destination);\n\t\t\/\/ time to fix the chord\n\t\tsleep(1);\n\t\t\/\/ The node is completely disconnected of the backbone\n\t\tif (isAlone()) { \/\/ there is only one response possible\n\t\t\treturn getThisNode()->toString();\n\t\t}\n\t\t\/\/ try again the request with a new destination\n\t\treturn sendRequest(request, findSuccessor(destination->getId()));\n\t}\n}\n\n\/* Fix broken pointers algorithm *\/\nvoid ChordNode::fixBrokenPointers(Node *node) {\n\tfor (int i = 0; i < fingerTable.size() - 1; i++) {\n\t\tif (fingerTable[i]->getId() == node->getId()) {\n\t\t\tfingerTable[i] = new Node(thisNode->toString());\n\t\t} \n\t}\n\tif (predecessor->getId() == node->getId()) {\n\t\tpredecessor = new Node(thisNode->toString());\n\t} \n\tif (successor->getId() == node->getId()) {\n\t\tsuccessor = new Node(thisNode->toString());\n\t}\n}\n\n\/* return true if the node is completely disconnected of the chord *\/\nbool ChordNode::isAlone(){\n\tfor (int i = 0; i < fingerTable.size() - 1; i++) {\n\t\tif (fingerTable[i]->getId() != thisNode->getId()){\n\t\t\treturn false;\n\t\t}\n\t}\n\treturn predecessor->getId() == thisNode->getId() && successor->getId() == thisNode->getId();\n}\n\n\/* Starts up the \"stabilizer thread\" for this peer. *\/\nvoid ChordNode::checkStable() {\n\tstableThread->start();\n}\n\n\/* Stop the stabilization, distribute the key and shutDown the peer *\/\nvoid ChordNode::shutDown() {\n\t\/\/ kill the stabilization Threads\n\tstableThread->kill();\n\n\n\t\/\/ notify predecessor\n\tRequest *request = new Request(this->getIdentifier(), SETSUCC);\n\trequest->addArg(\"successor\", successor->toString());\n\tsendRequest(request, predecessor);\n\n\t\/\/ notify successor\n\trequest = new Request(this->getIdentifier(), SETPRED);\n\trequest->addArg(\"predecessor\", predecessor->toString());\n\tsendRequest(request, successor);\n\n\t\/\/ give the part of the DHT to the successor\n\tfor (dataMap::iterator it = table.begin(); it != table.end(); ++it) {\n\t\trequest = new Request(this->getIdentifier(), PUT);\n\t\trequest->addArg(\"key\", it->first);\n\t\trequest->addArg(\"value\", it->second);\n\t\tsendRequest(request, successor);\n\t\t\/\/ remove the key from my table\n\t\ttable.erase(it);\n\t}\n\tcout << \"bye bye...\\n\";\n\tsleep(1);\n\texit(0);\n}\n\n\/* print node status *\/\nstring ChordNode::printTable() {\n\tstringstream ss(stringstream::in | stringstream::out);\n\tss << \"data:\\n\";\n\tfor (dataMap::const_iterator it = table.begin(); it != table.end(); ++it) {\n\t\tss << \"\\t[\" << it->first << \"]\";\n\t\tss << \" - \" << it->second << '\\n';\n\t}\n\treturn ss.str();\n}\n<commit_msg> FIX: \t- concate...<commit_after>\/*\n * ChordNode.cpp\n * iPhone_p2p_engine\n *\n * Created by LogNet team 2010 - INRIA\n * Mediteranee - Sophia Antipolis - France\n *\n *\/\n\n#include \"ChordNode.h\"\n#include \"Stabilization.h\"\n#include \"CheckPred.h\"\n#include \"FixFinger.h\"\n#include \"TransportHTTP.h\"\n#include \"callbacks.h\"\n#include \"sha1.h\";\n#include <sstream>\n#include <iostream>\n#include <assert.h>\n#include <math.h>\n\n\/* Constructor *\/\nChordNode::ChordNode(const string &ip, int port, const string &overlayIdentifier, const string &rootDirectory) {\n\n\t\/\/ Define the address space size\n\tspacesize = 9;\n\n\t\/\/ Create the id\n\tstd::ostringstream oss;\n\toss << ip << port;\n\tint id = getSHA1(oss.str());\n\n\t\/\/ check if the idE[0, 2^(spacesize - 1)]\n\tassert(!(id > pow(2, spacesize)) && !(id < 0));\n\n\t\/\/create our stabilizer threads instance.\n\tstableThread = new Stabilization(this);\n\n\t\/\/Initialize the transport layer.\n\ttransport = new TransportHTTP(port, rootDirectory);\n\n\t\/\/set the overlay identifier.\n\tthis->overlayIdentifier = overlayIdentifier;\n\n\t\/\/ not yet notified\n\tnotified = false;\n\n\t\/\/Call our parent's initializer\n\tinitialise(ip, id, port);\n\n\t\/\/We start-up our stabilizer thread.\n\tcheckStable();\n}\n\n\/* Destructor *\/\nChordNode::~ChordNode() {\n\tstableThread->kill();\n\tdelete stableThread;\n\tdelete transport;\n}\n\n\/* Override from AbstractChord *\/\nvoid ChordNode::notify(Node *n) {\n\tNode *pred = predecessor;\n\t((AbstractChord *) this)->notify(n);\n\t\/\/ If the predecessor as changed, update the DHT table\n\tif (pred != predecessor) {\n\t\tnotified = true;\n\t}\n}\n\nvoid ChordNode::stabilize() {\n\t((AbstractChord *) this)->stabilize();\n\t\/\/ If the predecessor as changed, update the DHT table\n\tif (notified && predecessor->getId() != thisNode->getId()) {\n\t\tfor (dataMap::iterator it = table.begin(); it != table.end(); ++it) {\n\t\t\tRequest *request = new Request(this->getIdentifier(), PUT);\n\t\t\tint id = atoi(it->first.c_str());\n\t\t\tif (!insideRange(id, predecessor->getId(), thisNode->getId())) {\n\t\t\t\trequest->addArg(\"key\", it->first);\n\t\t\t\trequest->addArg(\"value\", it->second);\n\t\t\t\t\/\/ Send the Put request\n\t\t\t\tsendRequest(request, predecessor);\n\t\t\t\t\/\/ remove the key from my table\n\t\t\t\ttable.erase(it);\n\t\t\t}\n\t\t}\n\t\tnotified = false;\n\t}\n}\n\n\/* DHT Put *\/\nvoid ChordNode::put(string key, string value) {\n\t\/\/ Convert the key in a hash integer\n\tint hKey = getSHA1(key);\n\tif (insideRange(hKey, predecessor->getId() + 1, thisNode->getId())) {\n\t\t\/\/ I'm responsible for this key\n\t\tstringstream ss;\n\t\tss << table[key] << value;\n\t\ttable[key]=ss.str();\n\t} else {\n\t\t\/\/ Find the node responsible for this key\n\t\tNode *responsible = findSuccessor(hKey);\n\t\t\/\/ Create a Put request.\n\t\tRequest *request = new Request(this->getIdentifier(), PUT);\n\t\trequest->addArg(\"key\", key);\n\t\trequest->addArg(\"value\", value);\n\t\t\/\/ Send the Put request\n\t\tsendRequest(request, responsible);\n\t}\n}\n\n\/* DHT Get *\/\nstring ChordNode::get(string key) {\n\t\/\/ Convert the key in a hash integer\n\tint hKey = getSHA1(key);\n\tif (insideRange(hKey, predecessor->getId() + 1, thisNode->getId())) {\n\t\t\/\/ I'm responsible for this key\n\t\tdataMap::iterator it = table.find(key);\n\t\tif (it != table.end()) {\n\t\t\treturn (it->second);\n\t\t} else {\n\t\t\tstring err = \"no result\";\n\t\t\treturn err;\n\t\t}\n\t} else {\n\t\t\/\/ Find the node responsible for this key\n\t\tNode *responsible = findSuccessor(hKey);\n\t\t\/\/ Create a Put request.\n\t\tRequest *request = new Request(this->getIdentifier(), GET);\n\t\trequest->addArg(\"key\", key);\n\t\t\/\/ Send the Put request\n\t\treturn sendRequest(request, responsible);\n\t}\n}\n\n\/* DHT Remove *\/\nvoid ChordNode::removekey(string key) {\n\t\/\/ Convert the key in a hash integer\n\tint hKey = getSHA1(key);\n\tif (insideRange(hKey, predecessor->getId() + 1, thisNode->getId())) {\n\t\t\/\/ I'm responsible for this key\n\t\tdataMap::iterator it = table.find(key);\n\t\tif (it != table.end()) {\n\t\t\ttable.erase(it);\n\t\t}\n\t} else {\n\t\t\/\/ Find the node responsible for this key\n\t\tNode *responsible = findSuccessor(hKey);\n\t\t\/\/ Create a Put request.\n\t\tRequest *request = new Request(this->getIdentifier(), REMOVEKEY);\n\t\trequest->addArg(\"key\", key);\n\t\t\/\/ Send the Put request\n\t\tsendRequest(request, responsible);\n\t}\n}\n\n\/* Convert a string to an integer (using MD5) *\/\nunsigned int ChordNode::getSHA1(string str) {\n\tSHA1 *sha1 = new SHA1();\n\tsha1->addBytes( str.c_str(), strlen( str.c_str() ));\n\tunsigned char* digest = sha1->getDigest();\n\tunsigned int res = sha1->shaToInteger(digest, 20, pow(2, spacesize));\n\tdelete sha1;\n\tfree( digest );\n\treturn res;\n}\n\n\/* Forward a message to a peer, the message is in the format: \"<IP+PORT>,TRANSPORT_CODE\" *\/\nstring ChordNode::sendRequest(Request *request, Node* destination) {\n\tchar *response = transport->sendRequest(request, destination);\n\t\/\/ response received\n\tif (response) {\n\t\tstringstream ss;\n\t\tss << response;\n\t\tfree(response); \/\/ we must free the initial char* response, to avoid leaks.\n\t\treturn ss.str();\n\t} else {\n\t\t\/\/ Fix the broken pointers of the node\n\t\tfixBrokenPointers(destination);\n\t\t\/\/ time to fix the chord\n\t\tsleep(1);\n\t\t\/\/ The node is completely disconnected of the backbone\n\t\tif (isAlone()) { \/\/ there is only one response possible\n\t\t\treturn getThisNode()->toString();\n\t\t}\n\t\t\/\/ try again the request with a new destination\n\t\treturn sendRequest(request, findSuccessor(destination->getId()));\n\t}\n}\n\n\/* Fix broken pointers algorithm *\/\nvoid ChordNode::fixBrokenPointers(Node *node) {\n\tfor (int i = 0; i < fingerTable.size() - 1; i++) {\n\t\tif (fingerTable[i]->getId() == node->getId()) {\n\t\t\tfingerTable[i] = new Node(thisNode->toString());\n\t\t} \n\t}\n\tif (predecessor->getId() == node->getId()) {\n\t\tpredecessor = new Node(thisNode->toString());\n\t} \n\tif (successor->getId() == node->getId()) {\n\t\tsuccessor = new Node(thisNode->toString());\n\t}\n}\n\n\/* return true if the node is completely disconnected of the chord *\/\nbool ChordNode::isAlone(){\n\tfor (int i = 0; i < fingerTable.size() - 1; i++) {\n\t\tif (fingerTable[i]->getId() != thisNode->getId()){\n\t\t\treturn false;\n\t\t}\n\t}\n\treturn predecessor->getId() == thisNode->getId() && successor->getId() == thisNode->getId();\n}\n\n\/* Starts up the \"stabilizer thread\" for this peer. *\/\nvoid ChordNode::checkStable() {\n\tstableThread->start();\n}\n\n\/* Stop the stabilization, distribute the key and shutDown the peer *\/\nvoid ChordNode::shutDown() {\n\t\/\/ kill the stabilization Threads\n\tstableThread->kill();\n\n\n\t\/\/ notify predecessor\n\tRequest *request = new Request(this->getIdentifier(), SETSUCC);\n\trequest->addArg(\"successor\", successor->toString());\n\tsendRequest(request, predecessor);\n\n\t\/\/ notify successor\n\trequest = new Request(this->getIdentifier(), SETPRED);\n\trequest->addArg(\"predecessor\", predecessor->toString());\n\tsendRequest(request, successor);\n\n\t\/\/ give the part of the DHT to the successor\n\tfor (dataMap::iterator it = table.begin(); it != table.end(); ++it) {\n\t\trequest = new Request(this->getIdentifier(), PUT);\n\t\trequest->addArg(\"key\", it->first);\n\t\trequest->addArg(\"value\", it->second);\n\t\tsendRequest(request, successor);\n\t\t\/\/ remove the key from my table\n\t\ttable.erase(it);\n\t}\n\tcout << \"bye bye...\\n\";\n\tsleep(1);\n\texit(0);\n}\n\n\/* print node status *\/\nstring ChordNode::printTable() {\n\tstringstream ss(stringstream::in | stringstream::out);\n\tss << \"data:\\n\";\n\tfor (dataMap::const_iterator it = table.begin(); it != table.end(); ++it) {\n\t\tss << \"\\t[\" << it->first << \"]\";\n\t\tss << \" - \" << it->second << '\\n';\n\t}\n\treturn ss.str();\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2015 GitHub, Inc.\n\/\/ Use of this source code is governed by the MIT license that can be\n\/\/ found in the LICENSE file.\n\n#include \"atom\/browser\/atom_download_manager_delegate.h\"\n\n#include <string>\n#include <vector>\n\n#include \"atom\/browser\/native_window.h\"\n#include \"base\/bind.h\"\n#include \"base\/files\/file_util.h\"\n#include \"chrome\/browser\/extensions\/api\/file_system\/file_entry_picker.h\"\n#include \"chrome\/browser\/profiles\/profile.h\"\n#include \"chrome\/common\/pref_names.h\"\n#include \"components\/prefs\/pref_service.h\"\n#include \"content\/public\/browser\/browser_context.h\"\n#include \"content\/public\/browser\/browser_thread.h\"\n#include \"content\/public\/browser\/download_manager.h\"\n#include \"net\/base\/filename_util.h\"\n#include \"net\/base\/mime_util.h\"\n#include \"vendor\/brightray\/browser\/inspectable_web_contents.h\"\n\nnamespace atom {\n\nnamespace {\n\nconst DownloadPathReservationTracker::FilenameConflictAction\n kDefaultPlatformConflictAction = DownloadPathReservationTracker::UNIQUIFY;\n\n} \/\/ namespace\n\nAtomDownloadManagerDelegate::AtomDownloadManagerDelegate(\n content::DownloadManager* manager)\n : download_manager_(manager),\n weak_ptr_factory_(this) {}\n\nAtomDownloadManagerDelegate::~AtomDownloadManagerDelegate() {\n if (download_manager_) {\n DCHECK_EQ(static_cast<content::DownloadManagerDelegate*>(this),\n download_manager_->GetDelegate());\n download_manager_->SetDelegate(nullptr);\n download_manager_ = nullptr;\n }\n}\n\nvoid AtomDownloadManagerDelegate::GetItemSavePath(content::DownloadItem* item,\n base::FilePath* path) {\n v8::Isolate* isolate = v8::Isolate::GetCurrent();\n v8::Locker locker(isolate);\n v8::HandleScope handle_scope(isolate);\n api::DownloadItem* download = api::DownloadItem::FromWrappedClass(isolate,\n item);\n if (download && !download->GetSavePath().empty())\n *path = download->GetSavePath();\n}\n\nbool AtomDownloadManagerDelegate::GetItemExtension(\n content::DownloadItem* item,\n base::FilePath::StringType* extension) {\n v8::Isolate* isolate = v8::Isolate::GetCurrent();\n v8::Locker locker(isolate);\n v8::HandleScope handle_scope(isolate);\n api::DownloadItem* download = api::DownloadItem::FromWrappedClass(isolate,\n item);\n if (download && !download->GetMimeType().empty())\n return net::GetPreferredExtensionForMimeType(\n download->GetMimeType(), extension);\n return false;\n}\n\nvoid AtomDownloadManagerDelegate:: OnDownloadItemSelected(\n const content::DownloadTargetCallback& callback,\n api::DownloadItem* download_item,\n const std::vector<base::FilePath>& paths) {\n DCHECK(!paths.empty());\n \/\/ Remember the last selected download directory.\n Profile* profile = static_cast<Profile*>(\n download_manager_->GetBrowserContext());\n profile->GetPrefs()->SetFilePath(prefs::kDownloadDefaultDirectory,\n paths[0].DirName());\n if (download_item)\n download_item->SetSavePath(paths[0]);\n\n callback.Run(paths[0],\n content::DownloadItem::TARGET_DISPOSITION_PROMPT,\n content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, paths[0],\n content::DOWNLOAD_INTERRUPT_REASON_NONE);\n}\n\nvoid AtomDownloadManagerDelegate::OnDownloadItemSelectionCancelled(\n const content::DownloadTargetCallback& callback,\n content::DownloadItem* item) {\n item->Remove();\n base::FilePath path;\n callback.Run(path,\n content::DownloadItem::TARGET_DISPOSITION_PROMPT,\n content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, path,\n content::DOWNLOAD_INTERRUPT_REASON_USER_CANCELED);\n}\n\nvoid AtomDownloadManagerDelegate::OnDownloadPathGenerated(\n int32_t download_id,\n const content::DownloadTargetCallback& callback,\n PathValidationResult result,\n const base::FilePath& target_path) {\n DCHECK_CURRENTLY_ON(content::BrowserThread::UI);\n\n auto item = download_manager_->GetDownload(download_id);\n if (!item)\n return;\n\n v8::Isolate* isolate = v8::Isolate::GetCurrent();\n v8::Locker locker(isolate);\n v8::HandleScope handle_scope(isolate);\n api::DownloadItem* download_item = api::DownloadItem::FromWrappedClass(\n isolate, item);\n\n if (!download_item)\n download_item = atom::api::DownloadItem::Create(isolate, item).get();\n\n base::FilePath path;\n if (result == PathValidationResult::SUCCESS &&\n !download_item->ShouldPrompt()) {\n path = target_path;\n }\n\n NativeWindow* window = nullptr;\n content::WebContents* web_contents = item->GetWebContents();\n auto relay = web_contents ? NativeWindowRelay::FromWebContents(web_contents)\n : nullptr;\n if (relay)\n window = relay->window.get();\n\n GetItemSavePath(item, &path);\n\n \/\/ Show save dialog if save path was not set already on item\n ui::SelectFileDialog::FileTypeInfo file_type_info;\n if (path.empty()) {\n std::vector<base::FilePath::StringType> extensions;\n base::FilePath::StringType extension;\n if (GetItemExtension(item, &extension)) {\n extensions.push_back(extension);\n file_type_info.extensions.push_back(extensions);\n }\n file_type_info.include_all_files = true;\n new extensions::FileEntryPicker(\n window->inspectable_web_contents()->GetWebContents(),\n target_path,\n file_type_info,\n ui::SelectFileDialog::SELECT_SAVEAS_FILE,\n base::Bind(&AtomDownloadManagerDelegate::OnDownloadItemSelected,\n base::Unretained(this), callback, download_item),\n base::Bind(&AtomDownloadManagerDelegate::OnDownloadItemSelectionCancelled,\n base::Unretained(this), callback, item));\n } else {\n if (download_item)\n download_item->SetSavePath(path);\n\n callback.Run(path,\n content::DownloadItem::TARGET_DISPOSITION_PROMPT,\n content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, path,\n content::DOWNLOAD_INTERRUPT_REASON_NONE);\n }\n}\n\nvoid AtomDownloadManagerDelegate::Shutdown() {\n weak_ptr_factory_.InvalidateWeakPtrs();\n download_manager_ = nullptr;\n}\n\nbool AtomDownloadManagerDelegate::DetermineDownloadTarget(\n content::DownloadItem* download,\n const content::DownloadTargetCallback& callback) {\n DCHECK_CURRENTLY_ON(content::BrowserThread::UI);\n\n Profile* browser_context = static_cast<Profile*>(\n download_manager_->GetBrowserContext());\n base::FilePath default_download_path(browser_context->GetPrefs()->GetFilePath(\n prefs::kDownloadDefaultDirectory));\n\n DownloadPathReservationTracker::FilenameConflictAction conflict_action =\n DownloadPathReservationTracker::OVERWRITE;\n base::FilePath virtual_path = download->GetForcedFilePath();\n\n if (virtual_path.empty()) {\n std::string suggested_filename(download->GetSuggestedFilename());\n if (suggested_filename.empty() &&\n download->GetMimeType() == \"application\/x-x509-user-cert\") {\n suggested_filename = \"user.crt\";\n }\n\n base::FilePath generated_filename = net::GenerateFileName(\n download->GetURL(),\n download->GetContentDisposition(),\n std::string(),\n suggested_filename,\n download->GetMimeType(),\n std::string());\n\n conflict_action = kDefaultPlatformConflictAction;\n virtual_path = default_download_path.Append(generated_filename);\n }\n\n DownloadPathReservationTracker::GetReservedPath(\n download,\n virtual_path,\n default_download_path,\n true,\n conflict_action,\n base::Bind(&AtomDownloadManagerDelegate::OnDownloadPathGenerated,\n weak_ptr_factory_.GetWeakPtr(),\n download->GetId(),\n callback));\n return true;\n}\n\nbool AtomDownloadManagerDelegate::ShouldOpenDownload(\n content::DownloadItem* download,\n const content::DownloadOpenDelayedCallback& callback) {\n return true;\n}\n\nvoid AtomDownloadManagerDelegate::GetNextId(\n const content::DownloadIdCallback& callback) {\n static uint32_t next_id = content::DownloadItem::kInvalidId + 1;\n callback.Run(next_id++);\n}\n\n} \/\/ namespace atom\n<commit_msg>Obtain extension from path when no mime type available fix https:\/\/github.com\/brave\/browser-laptop\/issues\/13230 fix https:\/\/github.com\/brave\/browser-laptop\/issues\/13228<commit_after>\/\/ Copyright (c) 2015 GitHub, Inc.\n\/\/ Use of this source code is governed by the MIT license that can be\n\/\/ found in the LICENSE file.\n\n#include \"atom\/browser\/atom_download_manager_delegate.h\"\n\n#include <string>\n#include <vector>\n\n#include \"atom\/browser\/native_window.h\"\n#include \"base\/bind.h\"\n#include \"base\/files\/file_util.h\"\n#include \"chrome\/browser\/extensions\/api\/file_system\/file_entry_picker.h\"\n#include \"chrome\/browser\/profiles\/profile.h\"\n#include \"chrome\/common\/pref_names.h\"\n#include \"components\/prefs\/pref_service.h\"\n#include \"content\/public\/browser\/browser_context.h\"\n#include \"content\/public\/browser\/browser_thread.h\"\n#include \"content\/public\/browser\/download_manager.h\"\n#include \"net\/base\/filename_util.h\"\n#include \"net\/base\/mime_util.h\"\n#include \"vendor\/brightray\/browser\/inspectable_web_contents.h\"\n\nnamespace atom {\n\nnamespace {\n\nconst DownloadPathReservationTracker::FilenameConflictAction\n kDefaultPlatformConflictAction = DownloadPathReservationTracker::UNIQUIFY;\n\n} \/\/ namespace\n\nAtomDownloadManagerDelegate::AtomDownloadManagerDelegate(\n content::DownloadManager* manager)\n : download_manager_(manager),\n weak_ptr_factory_(this) {}\n\nAtomDownloadManagerDelegate::~AtomDownloadManagerDelegate() {\n if (download_manager_) {\n DCHECK_EQ(static_cast<content::DownloadManagerDelegate*>(this),\n download_manager_->GetDelegate());\n download_manager_->SetDelegate(nullptr);\n download_manager_ = nullptr;\n }\n}\n\nvoid AtomDownloadManagerDelegate::GetItemSavePath(content::DownloadItem* item,\n base::FilePath* path) {\n v8::Isolate* isolate = v8::Isolate::GetCurrent();\n v8::Locker locker(isolate);\n v8::HandleScope handle_scope(isolate);\n api::DownloadItem* download = api::DownloadItem::FromWrappedClass(isolate,\n item);\n if (download && !download->GetSavePath().empty())\n *path = download->GetSavePath();\n}\n\nbool AtomDownloadManagerDelegate::GetItemExtension(\n content::DownloadItem* item,\n base::FilePath::StringType* extension) {\n v8::Isolate* isolate = v8::Isolate::GetCurrent();\n v8::Locker locker(isolate);\n v8::HandleScope handle_scope(isolate);\n api::DownloadItem* download = api::DownloadItem::FromWrappedClass(isolate,\n item);\n if (download && !download->GetMimeType().empty())\n return net::GetPreferredExtensionForMimeType(\n download->GetMimeType(), extension);\n return false;\n}\n\nvoid AtomDownloadManagerDelegate:: OnDownloadItemSelected(\n const content::DownloadTargetCallback& callback,\n api::DownloadItem* download_item,\n const std::vector<base::FilePath>& paths) {\n DCHECK(!paths.empty());\n \/\/ Remember the last selected download directory.\n Profile* profile = static_cast<Profile*>(\n download_manager_->GetBrowserContext());\n profile->GetPrefs()->SetFilePath(prefs::kDownloadDefaultDirectory,\n paths[0].DirName());\n if (download_item)\n download_item->SetSavePath(paths[0]);\n\n callback.Run(paths[0],\n content::DownloadItem::TARGET_DISPOSITION_PROMPT,\n content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, paths[0],\n content::DOWNLOAD_INTERRUPT_REASON_NONE);\n}\n\nvoid AtomDownloadManagerDelegate::OnDownloadItemSelectionCancelled(\n const content::DownloadTargetCallback& callback,\n content::DownloadItem* item) {\n item->Remove();\n base::FilePath path;\n callback.Run(path,\n content::DownloadItem::TARGET_DISPOSITION_PROMPT,\n content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, path,\n content::DOWNLOAD_INTERRUPT_REASON_USER_CANCELED);\n}\n\nvoid AtomDownloadManagerDelegate::OnDownloadPathGenerated(\n int32_t download_id,\n const content::DownloadTargetCallback& callback,\n PathValidationResult result,\n const base::FilePath& target_path) {\n DCHECK_CURRENTLY_ON(content::BrowserThread::UI);\n\n auto item = download_manager_->GetDownload(download_id);\n if (!item)\n return;\n\n v8::Isolate* isolate = v8::Isolate::GetCurrent();\n v8::Locker locker(isolate);\n v8::HandleScope handle_scope(isolate);\n api::DownloadItem* download_item = api::DownloadItem::FromWrappedClass(\n isolate, item);\n\n if (!download_item)\n download_item = atom::api::DownloadItem::Create(isolate, item).get();\n\n base::FilePath path;\n if (result == PathValidationResult::SUCCESS &&\n !download_item->ShouldPrompt()) {\n path = target_path;\n }\n\n NativeWindow* window = nullptr;\n content::WebContents* web_contents = item->GetWebContents();\n auto relay = web_contents ? NativeWindowRelay::FromWebContents(web_contents)\n : nullptr;\n if (relay)\n window = relay->window.get();\n\n GetItemSavePath(item, &path);\n\n \/\/ Show save dialog if save path was not set already on item\n ui::SelectFileDialog::FileTypeInfo file_type_info;\n if (path.empty()) {\n std::vector<base::FilePath::StringType> extensions;\n base::FilePath::StringType extension;\n if (!GetItemExtension(item, &extension)) {\n extension = target_path.Extension();\n if (!extension.empty())\n extension.erase(extension.begin()); \/\/ Erase preceding '.'.\n }\n if (!extension.empty()) {\n extensions.push_back(extension);\n file_type_info.extensions.push_back(extensions);\n }\n file_type_info.include_all_files = true;\n new extensions::FileEntryPicker(\n window->inspectable_web_contents()->GetWebContents(),\n target_path,\n file_type_info,\n ui::SelectFileDialog::SELECT_SAVEAS_FILE,\n base::Bind(&AtomDownloadManagerDelegate::OnDownloadItemSelected,\n base::Unretained(this), callback, download_item),\n base::Bind(&AtomDownloadManagerDelegate::OnDownloadItemSelectionCancelled,\n base::Unretained(this), callback, item));\n } else {\n if (download_item)\n download_item->SetSavePath(path);\n\n callback.Run(path,\n content::DownloadItem::TARGET_DISPOSITION_PROMPT,\n content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, path,\n content::DOWNLOAD_INTERRUPT_REASON_NONE);\n }\n}\n\nvoid AtomDownloadManagerDelegate::Shutdown() {\n weak_ptr_factory_.InvalidateWeakPtrs();\n download_manager_ = nullptr;\n}\n\nbool AtomDownloadManagerDelegate::DetermineDownloadTarget(\n content::DownloadItem* download,\n const content::DownloadTargetCallback& callback) {\n DCHECK_CURRENTLY_ON(content::BrowserThread::UI);\n\n Profile* browser_context = static_cast<Profile*>(\n download_manager_->GetBrowserContext());\n base::FilePath default_download_path(browser_context->GetPrefs()->GetFilePath(\n prefs::kDownloadDefaultDirectory));\n\n DownloadPathReservationTracker::FilenameConflictAction conflict_action =\n DownloadPathReservationTracker::OVERWRITE;\n base::FilePath virtual_path = download->GetForcedFilePath();\n\n if (virtual_path.empty()) {\n std::string suggested_filename(download->GetSuggestedFilename());\n if (suggested_filename.empty() &&\n download->GetMimeType() == \"application\/x-x509-user-cert\") {\n suggested_filename = \"user.crt\";\n }\n\n base::FilePath generated_filename = net::GenerateFileName(\n download->GetURL(),\n download->GetContentDisposition(),\n std::string(),\n suggested_filename,\n download->GetMimeType(),\n std::string());\n\n conflict_action = kDefaultPlatformConflictAction;\n virtual_path = default_download_path.Append(generated_filename);\n }\n\n DownloadPathReservationTracker::GetReservedPath(\n download,\n virtual_path,\n default_download_path,\n true,\n conflict_action,\n base::Bind(&AtomDownloadManagerDelegate::OnDownloadPathGenerated,\n weak_ptr_factory_.GetWeakPtr(),\n download->GetId(),\n callback));\n return true;\n}\n\nbool AtomDownloadManagerDelegate::ShouldOpenDownload(\n content::DownloadItem* download,\n const content::DownloadOpenDelayedCallback& callback) {\n return true;\n}\n\nvoid AtomDownloadManagerDelegate::GetNextId(\n const content::DownloadIdCallback& callback) {\n static uint32_t next_id = content::DownloadItem::kInvalidId + 1;\n callback.Run(next_id++);\n}\n\n} \/\/ namespace atom\n<|endoftext|>"} {"text":"<commit_before>#include \"Visualization.hpp\"\n#include <iostream>\nusing namespace SIPL;\n\nint Visualization::windowCounter = 0;\n\nVisualization::Visualization(BaseDataset * image) {\n if(images.size() == 3)\n throw SIPLException(\"A visualization can only contain a maximum of 3 images\/volumes.\");\n images.push_back(image);\n setLevel(0.5);\n setWindow(1.0);\n scale = 1.0f;\n isVolumeVisualization = image->isVolume;\n if(isVolumeVisualization) {\n direction = Z;\n slice = image->getSize().z \/ 2;\n }\n}\n\nVisualization::Visualization(BaseDataset * image, BaseDataset * image2) {\n\n \/\/ Check that both are either image or volume\n if(!(image->isVolume == image2->isVolume))\n throw SIPLException(\"A visualization can only contain images or volumes, not both.\");\n if(image->isVectorType && image2->isVectorType)\n throw SIPLException(\"A visualization can not contain more than one vector image\/volume.\");\n if(images.size() > 1)\n throw SIPLException(\"A visualization can only contain a maximum of 3 images\/volumes.\");\n if(!(image->getSize() == image2->getSize()))\n throw SIPLException(\"Images\/volumes must be of same size to be visualized together.\");\n\n images.push_back(image);\n images.push_back(image2);\n setLevel(0.5);\n setWindow(1.0);\n scale = 1.0f;\n isVolumeVisualization = image->isVolume;\n if(isVolumeVisualization) {\n direction = Z;\n slice = image->getSize().z \/ 2;\n }\n}\n\nVisualization::Visualization(BaseDataset * image, BaseDataset * image2, BaseDataset * image3) {\n\n \/\/ Check that both are either image or volume\n if(!(image->isVolume == image2->isVolume && image->isVolume == image3->isVolume))\n throw SIPLException(\"A visualization can only contain images or volumes, not both.\");\n if(image->isVectorType && image2->isVectorType && image3->isVectorType)\n throw SIPLException(\"A visualization can not contain more than one vector image\/volume.\");\n if(images.size() > 0)\n throw SIPLException(\"A visualization can only contain a maximum of 3 images\/volumes.\");\n if(!(image->getSize() == image2->getSize() && image->getSize() == image3->getSize()))\n throw SIPLException(\"Images\/volumes must be of same size to be visualized together.\");\n\n images.push_back(image);\n images.push_back(image2);\n images.push_back(image3);\n setLevel(0.5);\n setWindow(1.0);\n scale = 1.0f;\n isVolumeVisualization = image->isVolume;\n if(isVolumeVisualization) {\n direction = Z;\n slice = image->getSize().z \/ 2;\n }\n}\n\nuchar levelWindow(float value, float level, float window) {\n float result;\n if(value < level-window*0.5f) {\n result = 0.0f;\n } else if(value > level+window*0.5f) {\n result = 1.0f;\n } else {\n result = (float)(value-(level-window*0.5f)) \/ window;\n }\n result = SIPL::round(result*255);\n return result;\n}\n\nvoid Visualization::renderSlice(int imageNr, GdkPixbuf * pixBuf) {\n int3 size = images[0]->getSize();\n int xSize = this->width;\n int ySize = this->height;\n\n guchar * pixels = gdk_pixbuf_get_pixels(pixBuf);\n int n = gdk_pixbuf_get_n_channels(pixBuf);\n int rowstride = gdk_pixbuf_get_rowstride(pixBuf);\n float * floatData = images[imageNr]->getFloatData();\n for(int y = 0; y < ySize; y++) {\n for(int x = 0; x < xSize; x++) {\n float intensity;\n switch(direction) {\n case X:\n intensity = floatData[slice + x*size.x + (ySize-1-y)*size.x*size.y];\n break;\n case Y:\n intensity = floatData[x + slice*size.x + (ySize-1-y)*size.x*size.y];\n break;\n case Z:\n intensity = floatData[x + y*size.x + slice*size.x*size.y];\n break;\n }\n int i = x*n+y*rowstride;\n guchar * p = pixels + i;\n if(images.size() == 1) {\n p[0] = levelWindow(intensity, level[images[imageNr]], window[images[imageNr]]);\n p[1] = p[0];\n p[2] = p[0];\n } else {\n p[imageNr] = levelWindow(intensity, level[images[imageNr]], window[images[imageNr]]);\n }\n }}\n delete[] floatData;\n}\n\nvoid Visualization::renderImage(int imageNr, GdkPixbuf * pixBuf) {\n guchar * pixels = gdk_pixbuf_get_pixels(pixBuf);\n int n = gdk_pixbuf_get_n_channels(pixBuf);\n\n float * floatData = images[imageNr]->getFloatData();\n for(int i = 0; i < images[imageNr]->getTotalSize(); i++) {\n guchar * p = pixels + i * n;\n if(images.size() == 1) {\n p[0] = levelWindow(floatData[i], level[images[imageNr]], window[images[imageNr]]);\n p[1] = p[0];\n p[2] = p[0];\n } else {\n p[imageNr] = levelWindow(floatData[i], level[images[imageNr]], window[images[imageNr]]);\n }\n }\n delete[] floatData;\n}\n\nGdkPixbuf * Visualization::render() {\n int3 size = images[0]->getSize();\n int xSize = 0;\n int ySize = 0;\n if(isVolumeVisualization) {\n switch(direction) {\n case X:\n \/\/ x direction\n xSize = size.y;\n ySize = size.z;\n break;\n case Y:\n \/\/ y direction\n xSize = size.x;\n ySize = size.z;\n break;\n case Z:\n \/\/ z direction\n xSize = size.x;\n ySize = size.y;\n break;\n }\n } else {\n xSize = size.x;\n ySize = size.y;\n }\n this->width = xSize;\n this->height = ySize;\n\n gtkImage = gtk_image_new_from_pixbuf(gdk_pixbuf_new(GDK_COLORSPACE_RGB, false,\n\t\t\t8, xSize,ySize));\n\n GdkPixbuf * pixBuf = gtk_image_get_pixbuf((GtkImage *) gtkImage);\n for(int i = 0; i < images.size(); i++) {\n if(isVolumeVisualization) {\n renderSlice(i, pixBuf);\n } else {\n renderImage(i, pixBuf);\n }\n }\n return pixBuf;\n}\n\nvoid SIPL::Visualization::setLevel(float level) {\n for(int i = 0; i < images.size(); i++) {\n setLevel(images[i], level);\n }\n}\n\nvoid SIPL::Visualization::setWindow(float window) {\n for(int i = 0; i < images.size(); i++) {\n setWindow(images[i], window);\n }\n}\n\nvoid SIPL::Visualization::setLevel(BaseDataset* image, float level) {\n this->level[image] = level;\n}\n\nvoid SIPL::Visualization::setWindow(BaseDataset* image, float window) {\n this->window[image] = window;\n}\n\nvoid SIPL::Visualization::setTitle(std::string title) {\n this->title = title;\n}\n\nvoid Visualization::display() {\n \/\/ For all images, get float data and then visualize it using window and level\n \/\/ Create image widget and fill up the pixbuf\n int3 size = images[0]->getSize();\n gdk_threads_enter();\n\n GdkPixbuf * pixBuf = render();\n\n \/\/ Create GUI\n\tGtkWidget * window = gtk_window_new(GTK_WINDOW_TOPLEVEL);\n\tVisualization::windowCounter++;\n\tif(title == \"\") {\n char * title = new char[20];\n sprintf(title, \"Visualization #%d\", Visualization::windowCounter);\n gtk_window_set_title(GTK_WINDOW(window), title);\n\t} else {\n\t gtk_window_set_title(GTK_WINDOW(window), this->title.c_str());\n\t}\n\tGtkWidget * toolbar = gtk_toolbar_new();\n\tgtk_toolbar_set_orientation(GTK_TOOLBAR(toolbar), GTK_ORIENTATION_HORIZONTAL);\n\tgtk_toolbar_append_item (\n\t\t\t GTK_TOOLBAR (toolbar), \/* our toolbar *\/\n \"Save\", \/* button label *\/\n \"Save this image\", \/* this button's tooltip *\/\n NULL, \/* tooltip private info *\/\n NULL, \/* icon widget *\/\n GTK_SIGNAL_FUNC(saveDialog), \/* a signal *\/\n gtk_image_new_from_pixbuf(pixBuf));\n\tgtk_toolbar_append_item (\n\t\t\t GTK_TOOLBAR (toolbar), \/* our toolbar *\/\n \"Close\", \/* button label *\/\n \"Close this image\", \/* this button's tooltip *\/\n NULL, \/* tooltip private info *\/\n NULL, \/* icon widget *\/\n GTK_SIGNAL_FUNC (signalDestroyWindow), \/* a signal *\/\n window);\n\tgtk_toolbar_append_item (\n\t\t\t GTK_TOOLBAR (toolbar), \/* our toolbar *\/\n \"Close program\", \/* button label *\/\n \"Close this program\", \/* this button's tooltip *\/\n NULL, \/* tooltip private info *\/\n NULL, \/* icon widget *\/\n GTK_SIGNAL_FUNC (quitProgram), \/* a signal *\/\n NULL);\n\n\tgtk_window_set_default_size(\n\t\t\tGTK_WINDOW(window),\n\t\t\tsize.x,\n\t\t\tsize.y + 35\n\t);\n\tgtk_window_set_position(GTK_WINDOW(window), GTK_WIN_POS_CENTER);\n\tg_signal_connect_swapped(\n\t\t\tG_OBJECT(window),\n\t\t\t\"destroy\",\n\t\t\tG_CALLBACK(destroyWindow),\n\t\t\tNULL\n\t);\n g_signal_connect(\n G_OBJECT(window),\n \"key_press_event\",\n G_CALLBACK(Visualization::keyPressed),\n this\n );\n\n GtkWidget * vbox = gtk_vbox_new(FALSE, 1);\n\n\tgtk_container_add (GTK_CONTAINER (window), vbox);\n gtk_box_pack_start(GTK_BOX(vbox), toolbar,FALSE,FALSE,0);\n scaledImage = gtk_image_new_from_pixbuf(pixBuf);\n GtkWidget * scrolledWindow = gtk_scrolled_window_new(NULL, NULL);\n gtk_scrolled_window_set_policy (GTK_SCROLLED_WINDOW (scrolledWindow),\n GTK_POLICY_AUTOMATIC,\n GTK_POLICY_AUTOMATIC);\n gtk_scrolled_window_add_with_viewport((GtkScrolledWindow *)scrolledWindow, scaledImage);\n gtk_box_pack_start(GTK_BOX(vbox), scrolledWindow,TRUE,TRUE,0);\n\tgtk_widget_show_all(window);\n\n\tgdk_threads_leave();\n}\n\nvoid Visualization::keyPressed(GtkWidget * widget, GdkEventKey * event, gpointer user_data) {\n Visualization * v = (Visualization *)user_data;\n switch(event->keyval) {\n case GDK_KEY_plus:\n case GDK_KEY_KP_Add:\n v->zoomIn();\n return;\n break;\n case GDK_KEY_minus:\n case GDK_KEY_KP_Subtract:\n v->zoomOut();\n return;\n break;\n\n }\n\n \/*\n if(v->isVolumeVisualization) {\n switch(event->keyval) {\n case GDK_KEY_Up:\n this->currentSlice = validateSlice(this->currentSlice+1,this->currentDirection,volume->getSize());\n break;\n case GDK_KEY_Down:\n this->currentSlice = validateSlice(this->currentSlice-1,this->currentDirection,volume->getSize());\n break;\n }\n\n }\n *\/\n}\n\nvoid Visualization::draw() {\n GdkPixbuf * pixBuf = gtk_image_get_pixbuf(GTK_IMAGE(gtkImage));\n GdkPixbuf * newPixBuf = gdk_pixbuf_new(GDK_COLORSPACE_RGB, false,\n\t\t\t8, scale*width, scale*height);\n gdk_pixbuf_scale(pixBuf, newPixBuf, 0, 0, scale*width, scale*height, 0, 0, scale, scale, GDK_INTERP_BILINEAR);\n gtk_image_set_from_pixbuf(GTK_IMAGE(scaledImage), newPixBuf);\n gtk_widget_queue_draw(scaledImage);\n}\n\nvoid Visualization::zoomIn() {\n \/\/ TODO: check if image is actually displayed\n scale = scale*2;\n this->draw();\n}\n\nvoid Visualization::zoomOut() {\n \/\/ TODO: check if image is actually displayed\n scale = scale*0.5f;\n this->draw();\n}\n<commit_msg>added update function<commit_after>#include \"Visualization.hpp\"\n#include <iostream>\nusing namespace SIPL;\n\nint Visualization::windowCounter = 0;\n\nVisualization::Visualization(BaseDataset * image) {\n if(images.size() == 3)\n throw SIPLException(\"A visualization can only contain a maximum of 3 images\/volumes.\");\n images.push_back(image);\n setLevel(0.5);\n setWindow(1.0);\n scale = 1.0f;\n isVolumeVisualization = image->isVolume;\n if(isVolumeVisualization) {\n direction = Z;\n slice = image->getSize().z \/ 2;\n }\n}\n\nVisualization::Visualization(BaseDataset * image, BaseDataset * image2) {\n\n \/\/ Check that both are either image or volume\n if(!(image->isVolume == image2->isVolume))\n throw SIPLException(\"A visualization can only contain images or volumes, not both.\");\n if(image->isVectorType && image2->isVectorType)\n throw SIPLException(\"A visualization can not contain more than one vector image\/volume.\");\n if(images.size() > 1)\n throw SIPLException(\"A visualization can only contain a maximum of 3 images\/volumes.\");\n if(!(image->getSize() == image2->getSize()))\n throw SIPLException(\"Images\/volumes must be of same size to be visualized together.\");\n\n images.push_back(image);\n images.push_back(image2);\n setLevel(0.5);\n setWindow(1.0);\n scale = 1.0f;\n isVolumeVisualization = image->isVolume;\n if(isVolumeVisualization) {\n direction = Z;\n slice = image->getSize().z \/ 2;\n }\n}\n\nVisualization::Visualization(BaseDataset * image, BaseDataset * image2, BaseDataset * image3) {\n\n \/\/ Check that both are either image or volume\n if(!(image->isVolume == image2->isVolume && image->isVolume == image3->isVolume))\n throw SIPLException(\"A visualization can only contain images or volumes, not both.\");\n if(image->isVectorType && image2->isVectorType && image3->isVectorType)\n throw SIPLException(\"A visualization can not contain more than one vector image\/volume.\");\n if(images.size() > 0)\n throw SIPLException(\"A visualization can only contain a maximum of 3 images\/volumes.\");\n if(!(image->getSize() == image2->getSize() && image->getSize() == image3->getSize()))\n throw SIPLException(\"Images\/volumes must be of same size to be visualized together.\");\n\n images.push_back(image);\n images.push_back(image2);\n images.push_back(image3);\n setLevel(0.5);\n setWindow(1.0);\n scale = 1.0f;\n isVolumeVisualization = image->isVolume;\n if(isVolumeVisualization) {\n direction = Z;\n slice = image->getSize().z \/ 2;\n }\n}\n\nuchar levelWindow(float value, float level, float window) {\n float result;\n if(value < level-window*0.5f) {\n result = 0.0f;\n } else if(value > level+window*0.5f) {\n result = 1.0f;\n } else {\n result = (float)(value-(level-window*0.5f)) \/ window;\n }\n result = SIPL::round(result*255);\n return result;\n}\n\nvoid Visualization::renderSlice(int imageNr, GdkPixbuf * pixBuf) {\n int3 size = images[0]->getSize();\n int xSize = this->width;\n int ySize = this->height;\n\n guchar * pixels = gdk_pixbuf_get_pixels(pixBuf);\n int n = gdk_pixbuf_get_n_channels(pixBuf);\n int rowstride = gdk_pixbuf_get_rowstride(pixBuf);\n float * floatData = images[imageNr]->getFloatData();\n for(int y = 0; y < ySize; y++) {\n for(int x = 0; x < xSize; x++) {\n float intensity;\n switch(direction) {\n case X:\n intensity = floatData[slice + x*size.x + (ySize-1-y)*size.x*size.y];\n break;\n case Y:\n intensity = floatData[x + slice*size.x + (ySize-1-y)*size.x*size.y];\n break;\n case Z:\n intensity = floatData[x + y*size.x + slice*size.x*size.y];\n break;\n }\n int i = x*n+y*rowstride;\n guchar * p = pixels + i;\n if(images.size() == 1) {\n p[0] = levelWindow(intensity, level[images[imageNr]], window[images[imageNr]]);\n p[1] = p[0];\n p[2] = p[0];\n } else {\n p[imageNr] = levelWindow(intensity, level[images[imageNr]], window[images[imageNr]]);\n }\n }}\n delete[] floatData;\n}\n\nvoid Visualization::renderImage(int imageNr, GdkPixbuf * pixBuf) {\n guchar * pixels = gdk_pixbuf_get_pixels(pixBuf);\n int n = gdk_pixbuf_get_n_channels(pixBuf);\n\n float * floatData = images[imageNr]->getFloatData();\n for(int i = 0; i < images[imageNr]->getTotalSize(); i++) {\n guchar * p = pixels + i * n;\n if(images.size() == 1) {\n p[0] = levelWindow(floatData[i], level[images[imageNr]], window[images[imageNr]]);\n p[1] = p[0];\n p[2] = p[0];\n } else {\n p[imageNr] = levelWindow(floatData[i], level[images[imageNr]], window[images[imageNr]]);\n }\n }\n delete[] floatData;\n}\n\nGdkPixbuf * Visualization::render() {\n int3 size = images[0]->getSize();\n int xSize = 0;\n int ySize = 0;\n if(isVolumeVisualization) {\n switch(direction) {\n case X:\n \/\/ x direction\n xSize = size.y;\n ySize = size.z;\n break;\n case Y:\n \/\/ y direction\n xSize = size.x;\n ySize = size.z;\n break;\n case Z:\n \/\/ z direction\n xSize = size.x;\n ySize = size.y;\n break;\n }\n } else {\n xSize = size.x;\n ySize = size.y;\n }\n this->width = xSize;\n this->height = ySize;\n\n gtkImage = gtk_image_new_from_pixbuf(gdk_pixbuf_new(GDK_COLORSPACE_RGB, false,\n\t\t\t8, xSize,ySize));\n\n GdkPixbuf * pixBuf = gtk_image_get_pixbuf((GtkImage *) gtkImage);\n for(int i = 0; i < images.size(); i++) {\n if(isVolumeVisualization) {\n renderSlice(i, pixBuf);\n } else {\n renderImage(i, pixBuf);\n }\n }\n return pixBuf;\n}\n\nvoid SIPL::Visualization::setLevel(float level) {\n for(int i = 0; i < images.size(); i++) {\n setLevel(images[i], level);\n }\n}\n\nvoid SIPL::Visualization::setWindow(float window) {\n for(int i = 0; i < images.size(); i++) {\n setWindow(images[i], window);\n }\n}\n\nvoid SIPL::Visualization::setLevel(BaseDataset* image, float level) {\n this->level[image] = level;\n}\n\nvoid SIPL::Visualization::setWindow(BaseDataset* image, float window) {\n this->window[image] = window;\n}\n\nvoid SIPL::Visualization::setTitle(std::string title) {\n this->title = title;\n}\n\nvoid Visualization::display() {\n \/\/ For all images, get float data and then visualize it using window and level\n \/\/ Create image widget and fill up the pixbuf\n int3 size = images[0]->getSize();\n gdk_threads_enter();\n\n GdkPixbuf * pixBuf = render();\n\n \/\/ Create GUI\n\tGtkWidget * window = gtk_window_new(GTK_WINDOW_TOPLEVEL);\n\tVisualization::windowCounter++;\n\tif(title == \"\") {\n char * title = new char[20];\n sprintf(title, \"Visualization #%d\", Visualization::windowCounter);\n gtk_window_set_title(GTK_WINDOW(window), title);\n\t} else {\n\t gtk_window_set_title(GTK_WINDOW(window), this->title.c_str());\n\t}\n\tGtkWidget * toolbar = gtk_toolbar_new();\n\tgtk_toolbar_set_orientation(GTK_TOOLBAR(toolbar), GTK_ORIENTATION_HORIZONTAL);\n\tgtk_toolbar_append_item (\n\t\t\t GTK_TOOLBAR (toolbar), \/* our toolbar *\/\n \"Save\", \/* button label *\/\n \"Save this image\", \/* this button's tooltip *\/\n NULL, \/* tooltip private info *\/\n NULL, \/* icon widget *\/\n GTK_SIGNAL_FUNC(saveDialog), \/* a signal *\/\n gtk_image_new_from_pixbuf(pixBuf));\n\tgtk_toolbar_append_item (\n\t\t\t GTK_TOOLBAR (toolbar), \/* our toolbar *\/\n \"Close\", \/* button label *\/\n \"Close this image\", \/* this button's tooltip *\/\n NULL, \/* tooltip private info *\/\n NULL, \/* icon widget *\/\n GTK_SIGNAL_FUNC (signalDestroyWindow), \/* a signal *\/\n window);\n\tgtk_toolbar_append_item (\n\t\t\t GTK_TOOLBAR (toolbar), \/* our toolbar *\/\n \"Close program\", \/* button label *\/\n \"Close this program\", \/* this button's tooltip *\/\n NULL, \/* tooltip private info *\/\n NULL, \/* icon widget *\/\n GTK_SIGNAL_FUNC (quitProgram), \/* a signal *\/\n NULL);\n\n\tgtk_window_set_default_size(\n\t\t\tGTK_WINDOW(window),\n\t\t\tsize.x,\n\t\t\tsize.y + 35\n\t);\n\tgtk_window_set_position(GTK_WINDOW(window), GTK_WIN_POS_CENTER);\n\tg_signal_connect_swapped(\n\t\t\tG_OBJECT(window),\n\t\t\t\"destroy\",\n\t\t\tG_CALLBACK(destroyWindow),\n\t\t\tNULL\n\t);\n g_signal_connect(\n G_OBJECT(window),\n \"key_press_event\",\n G_CALLBACK(Visualization::keyPressed),\n this\n );\n\n GtkWidget * vbox = gtk_vbox_new(FALSE, 1);\n\n\tgtk_container_add (GTK_CONTAINER (window), vbox);\n gtk_box_pack_start(GTK_BOX(vbox), toolbar,FALSE,FALSE,0);\n scaledImage = gtk_image_new_from_pixbuf(pixBuf);\n GtkWidget * scrolledWindow = gtk_scrolled_window_new(NULL, NULL);\n gtk_scrolled_window_set_policy (GTK_SCROLLED_WINDOW (scrolledWindow),\n GTK_POLICY_AUTOMATIC,\n GTK_POLICY_AUTOMATIC);\n gtk_scrolled_window_add_with_viewport((GtkScrolledWindow *)scrolledWindow, scaledImage);\n gtk_box_pack_start(GTK_BOX(vbox), scrolledWindow,TRUE,TRUE,0);\n\tgtk_widget_show_all(window);\n\n\tgdk_threads_leave();\n}\n\nvoid Visualization::keyPressed(GtkWidget * widget, GdkEventKey * event, gpointer user_data) {\n Visualization * v = (Visualization *)user_data;\n switch(event->keyval) {\n case GDK_KEY_plus:\n case GDK_KEY_KP_Add:\n v->zoomIn();\n return;\n break;\n case GDK_KEY_minus:\n case GDK_KEY_KP_Subtract:\n v->zoomOut();\n return;\n break;\n\n }\n\n \/*\n if(v->isVolumeVisualization) {\n switch(event->keyval) {\n case GDK_KEY_Up:\n this->currentSlice = validateSlice(this->currentSlice+1,this->currentDirection,volume->getSize());\n break;\n case GDK_KEY_Down:\n this->currentSlice = validateSlice(this->currentSlice-1,this->currentDirection,volume->getSize());\n break;\n }\n\n }\n *\/\n}\n\nvoid Visualization::draw() {\n GdkPixbuf * pixBuf = gtk_image_get_pixbuf(GTK_IMAGE(gtkImage));\n GdkPixbuf * newPixBuf = gdk_pixbuf_new(GDK_COLORSPACE_RGB, false,\n\t\t\t8, scale*width, scale*height);\n gdk_pixbuf_scale(pixBuf, newPixBuf, 0, 0, scale*width, scale*height, 0, 0, scale, scale, GDK_INTERP_BILINEAR);\n gtk_image_set_from_pixbuf(GTK_IMAGE(scaledImage), newPixBuf);\n gtk_widget_queue_draw(scaledImage);\n}\n\nvoid Visualization::zoomIn() {\n \/\/ TODO: check if image is actually displayed\n scale = scale*2;\n this->draw();\n}\n\nvoid Visualization::zoomOut() {\n \/\/ TODO: check if image is actually displayed\n scale = scale*0.5f;\n this->draw();\n}\n\nvoid Visualization::update() {\n GdkPixbuf * pixBuf = render();\n gtk_image_set_from_pixbuf(GTK_IMAGE(gtkImage), pixBuf);\n draw();\n}\n<|endoftext|>"} {"text":"<commit_before>#ifndef H_EXTENSIONS_CUTEHMI_TEST_0_INCLUDE_CUTEHMI_TEST_RANDOM_HPP\n#define H_EXTENSIONS_CUTEHMI_TEST_0_INCLUDE_CUTEHMI_TEST_RANDOM_HPP\n\n#include \"IsIntType.hpp\"\n\n#include <QChar>\n#include <QString>\n#include <QList>\n#include <QMultiHash>\n\n#include <random>\n#include <chrono>\n#include <limits>\n#include <type_traits>\n\nnamespace cutehmi {\nnamespace test {\n\n\/**\n * Seeded engine. This class extends random generator class specified by @a E\n * template parameter and behaves exactly like extended class, except it seeds\n * itself within a constructor.\n * @tparam E random number generator engine.\n *\/\ntemplate <class E = std::mt19937>\nclass SeededEngine:\n\tpublic E\n{\n\tpublic:\n\t\t\/**\n\t\t * Default constructor.\n\t\t *\/\n\t\tSeededEngine();\n};\n\ntemplate <class E>\nSeededEngine<E>::SeededEngine()\n{\n\tstd::random_device randomDevice;\n\n\t\/\/ Some implementations do not have non-deterministic std::random_device.\n\t\/\/ Check out entropy of std::random_device. If it's zero, then fallback to\n\t\/\/ time-based seed.\n\t\/\/\n\t\/\/ Note that sometimes it's std::random_device::entropy(), which is not\n\t\/\/ implemented properly, accodring to _cppreference.com_. Still use\n\t\/\/ time-based fallback in such cases, as we won't do workarounds.\n\t\/\/\n\t\/\/ \"This function is not fully implemented in some standard libraries. For\n\t\/\/ example, LLVM libc++ always returns zero even though the device is\n\t\/\/ non-deterministic. In comparison, Microsoft Visual C++ implementation\n\t\/\/ always returns 32, and boost.random returns 10.\n\t\/\/ The entropy of the Linux kernel device \/dev\/urandom may be obtained\n\t\/\/ using ioctl RNDGETENTCNT - that's what std::random_device::entropy() in\n\t\/\/ GNU libstdc++ uses as of version 8.1\"\n\t\/\/ -- https:\/\/en.cppreference.com\/w\/cpp\/numeric\/random\/random_device\/entropy\n\tif (randomDevice.entropy() != 0.0)\n\t\tE::seed(randomDevice());\n\telse\n\t\tE::seed(std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::high_resolution_clock::now().time_since_epoch()).count());\n}\n\n\/**\n * Generate random integer using uniform distribution.\n * @tparam T integer type.\n * @tparam E random number generator engine.\n * @param from lower bound of a set of generated random numbers.\n * @param from upper bound of a set of generated random numbers.\n * @return randomly generated integer.\n *\/\ntemplate <typename T, typename E = SeededEngine<std::mt19937>>\ntypename std::enable_if<IsIntType<T>::value, T>::type rand(T from = std::numeric_limits<T>::lowest(), T to = std::numeric_limits<T>::max())\n{\n\tstatic E engine; \/\/ Use static variable to prevent frequent allocation\/deallocation (\"mt19937 use 5000 bytes of memory for each creation (which is bad for performance if we create it too frequently)\" -- https:\/\/github.com\/effolkronium\/random).\n\n\tstd::uniform_int_distribution<T> distribution(from, to);\n\n\treturn distribution(engine);\n}\n\n\/**\n * Generate random floating point number using uniform distribution. Fractions are generated within range [@p 0.0, @p 1.0) and then\n * multiplied by @p 2 raised to random exponent [@a fromExponent, @a toExponent]. Sign is randomly applied to the resulting value.\n * @tparam T floating point number type.\n * @tparam E random number generator engine.\n * @param fromExponent lower bound of a set of powers of base 2 exponents to be used to multiply a randomly generated fraction from\n * [@p 0.0, @p 1.0) range.\n * @param toExponent upper bound of a set of powers of base 2 exponents to be used to multiply a randomly generated fraction from\n * [@p 0.0, @p 1.0) range.\n * @return randomly generated floating point number.\n *\/\ntemplate <typename T, typename E = SeededEngine<std::mt19937>>\ntypename std::enable_if<std::is_floating_point<T>::value, T>::type rand(int fromExponent = std::numeric_limits<T>::min_exponent, int toExponent = std::numeric_limits<T>::max_exponent)\n{\n\tstatic E engine; \/\/ Use static variable to prevent frequent allocation\/deallocation (\"mt19937 use 5000 bytes of memory for each creation (which is bad for performance if we create it too frequently)\" -- https:\/\/github.com\/effolkronium\/random).\n\n\tstd::uniform_real_distribution<T> fracDistribution(0.0, 1.0);\t\/\/ A fraction within range [0.0, 1.0).\n\tstd::uniform_int_distribution<int> expDistribution(fromExponent, toExponent);\n\n\treturn rand<bool>() ? ldexp(fracDistribution(engine), expDistribution(engine)) : -ldexp(fracDistribution(engine), expDistribution(engine));\n}\n\n\/**\n * Generate random Boolean value using Bernoulli distribution.\n * @tparam T boolean type.\n * @tparam E random number generator engine.\n * @param p propbablity of generating @p true.\n * @return one of the Boolean values: @p true or @p false.\n *\/\ntemplate <typename T, typename E = SeededEngine<std::mt19937>>\ntypename std::enable_if<std::is_same<T, bool>::value, T>::type rand(double p = 0.5)\n{\n\tstatic E engine; \/\/ Use static variable to prevent frequent allocation\/deallocation (\"mt19937 use 5000 bytes of memory for each creation (which is bad for performance if we create it too frequently)\" -- https:\/\/github.com\/effolkronium\/random).\n\n\tstd::bernoulli_distribution distribution(p);\n\n\treturn distribution(engine);\n}\n\n\/**\n * Generate random character.\n * @tparam T QChar type.\n * @tparam E random number generator engine.\n * @param category character category.\n * @return random character.\n *\/\ntemplate <typename T, typename E = SeededEngine<std::mt19937>>\ntypename std::enable_if<std::is_same<T, QChar>::value, QChar>::type rand(QChar::Category category)\n{\n\tstatic E engine; \/\/ Use static variable to prevent frequent allocation\/deallocation (\"mt19937 use 5000 bytes of memory for each creation (which is bad for performance if we create it too frequently)\" -- https:\/\/github.com\/effolkronium\/random).\n\tstatic QMultiHash<int, QChar> categorySets;\t\t\/\/ Key denotes category of specific charecters.\n\n\tif (categorySets.empty()) {\n\t\t\/\/ Initialize categorized sets of characters.\n\t\tfor (char16_t c = 0; c < std::numeric_limits<char16_t>::max(); c++)\n\t\t\tcategorySets.insert(QChar::category(c), c);\n\t\tcategorySets.insert(QChar::category(std::numeric_limits<char16_t>::max()), std::numeric_limits<char16_t>::max());\n\t}\n\n\treturn categorySets.values(category).at(rand(0, categorySets.values(category).size() - 1));\n}\n\n\/**\n * Generate random string.\n * @tparam T QString type.\n * @tparam E random number generator engine.\n * @param length string length.\n * @param categories character categories of which string should be composed from.\n * @return randomly generated string.\n *\/\ntemplate <typename T, typename E = SeededEngine<std::mt19937>>\ntypename std::enable_if<std::is_same<T, QString>::value, T>::type rand(int length = rand(0, 255), QList<QChar::Category> categories = {QChar::Letter_Uppercase, QChar::Letter_Lowercase, QChar::Number_DecimalDigit})\n{\n\tstatic E engine; \/\/ Use static variable to prevent frequent allocation\/deallocation (\"mt19937 use 5000 bytes of memory for each creation (which is bad for performance if we create it too frequently)\" -- https:\/\/github.com\/effolkronium\/random).\n\n\tQString result(\"\");\n\tfor (int i = 0; i < length; i++)\n\t\tresult.append(rand<QChar>(categories.at(rand(0, categories.size() - 1))));\n\n\treturn result;\n}\n\n\/**\n * Generate random string list.\n * @tparam T QStringList type.\n * @tparam E random number generator engine.\n * @param size string list size.\n * @param length strings length.\n * @param categories character categories of which strings should be composed from.\n * @return randomly generated string list.\n *\/\ntemplate <typename T, typename E = SeededEngine<std::mt19937>>\ntypename std::enable_if<std::is_same<T, QStringList>::value, T>::type rand(int size = rand(0, 255), int length = rand(0, 255), QList<QChar::Category> categories = {QChar::Letter_Uppercase, QChar::Letter_Lowercase, QChar::Number_DecimalDigit})\n{\n\tstatic E engine; \/\/ Use static variable to prevent frequent allocation\/deallocation (\"mt19937 use 5000 bytes of memory for each creation (which is bad for performance if we create it too frequently)\" -- https:\/\/github.com\/effolkronium\/random).\n\n\tQStringList result;\n\tfor (int i = 0; i < size; i++)\n\t\tresult.append(rand<QString>(length, categories));\n\n\treturn result;\n}\n\n\/**\n * Randomize array.\n * @tparam T type of array elements.\n * @tparam E random number genererator engine.\n * @tparam ARGS arguments to be passed to underlying rand() function.\n * @param ptr array pointer.\n * @param size array size.\n * @param arguments to be passed to underlying rand() function for each array\n * element.\n *\/\ntemplate <typename T, typename E = SeededEngine<std::mt19937>, typename... ARGS>\nvoid rand(T * ptr, std::size_t size, ARGS... args)\n{\n\twhile (size > 0) {\n\t\t*ptr = rand<T, E>(args...);\n\t\tptr++;\n\t\tsize--;\n\t}\n}\n\n}\n}\n\n#endif\n\n\/\/(c)MP: Copyright © 2019, Michal Policht <michpolicht@gmail.com>. All rights reserved.\n\/\/(c)MP: This file is a part of CuteHMI.\n\/\/(c)MP: CuteHMI is free software: you can redistribute it and\/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.\n\/\/(c)MP: CuteHMI is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.\n\/\/(c)MP: You should have received a copy of the GNU Lesser General Public License along with CuteHMI. If not, see <https:\/\/www.gnu.org\/licenses\/>.\n<commit_msg>Call standard 'ldexp' with namespace name.<commit_after>#ifndef H_EXTENSIONS_CUTEHMI_TEST_0_INCLUDE_CUTEHMI_TEST_RANDOM_HPP\n#define H_EXTENSIONS_CUTEHMI_TEST_0_INCLUDE_CUTEHMI_TEST_RANDOM_HPP\n\n#include \"IsIntType.hpp\"\n\n#include <QChar>\n#include <QString>\n#include <QList>\n#include <QMultiHash>\n\n#include <random>\n#include <chrono>\n#include <limits>\n#include <type_traits>\n\nnamespace cutehmi {\nnamespace test {\n\n\/**\n * Seeded engine. This class extends random generator class specified by @a E\n * template parameter and behaves exactly like extended class, except it seeds\n * itself within a constructor.\n * @tparam E random number generator engine.\n *\/\ntemplate <class E = std::mt19937>\nclass SeededEngine:\n\tpublic E\n{\n\tpublic:\n\t\t\/**\n\t\t * Default constructor.\n\t\t *\/\n\t\tSeededEngine();\n};\n\ntemplate <class E>\nSeededEngine<E>::SeededEngine()\n{\n\tstd::random_device randomDevice;\n\n\t\/\/ Some implementations do not have non-deterministic std::random_device.\n\t\/\/ Check out entropy of std::random_device. If it's zero, then fallback to\n\t\/\/ time-based seed.\n\t\/\/\n\t\/\/ Note that sometimes it's std::random_device::entropy(), which is not\n\t\/\/ implemented properly, accodring to _cppreference.com_. Still use\n\t\/\/ time-based fallback in such cases, as we won't do workarounds.\n\t\/\/\n\t\/\/ \"This function is not fully implemented in some standard libraries. For\n\t\/\/ example, LLVM libc++ always returns zero even though the device is\n\t\/\/ non-deterministic. In comparison, Microsoft Visual C++ implementation\n\t\/\/ always returns 32, and boost.random returns 10.\n\t\/\/ The entropy of the Linux kernel device \/dev\/urandom may be obtained\n\t\/\/ using ioctl RNDGETENTCNT - that's what std::random_device::entropy() in\n\t\/\/ GNU libstdc++ uses as of version 8.1\"\n\t\/\/ -- https:\/\/en.cppreference.com\/w\/cpp\/numeric\/random\/random_device\/entropy\n\tif (randomDevice.entropy() != 0.0)\n\t\tE::seed(randomDevice());\n\telse\n\t\tE::seed(std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::high_resolution_clock::now().time_since_epoch()).count());\n}\n\n\/**\n * Generate random integer using uniform distribution.\n * @tparam T integer type.\n * @tparam E random number generator engine.\n * @param from lower bound of a set of generated random numbers.\n * @param from upper bound of a set of generated random numbers.\n * @return randomly generated integer.\n *\/\ntemplate <typename T, typename E = SeededEngine<std::mt19937>>\ntypename std::enable_if<IsIntType<T>::value, T>::type rand(T from = std::numeric_limits<T>::lowest(), T to = std::numeric_limits<T>::max())\n{\n\tstatic E engine; \/\/ Use static variable to prevent frequent allocation\/deallocation (\"mt19937 use 5000 bytes of memory for each creation (which is bad for performance if we create it too frequently)\" -- https:\/\/github.com\/effolkronium\/random).\n\n\tstd::uniform_int_distribution<T> distribution(from, to);\n\n\treturn distribution(engine);\n}\n\n\/**\n * Generate random floating point number using uniform distribution. Fractions are generated within range [@p 0.0, @p 1.0) and then\n * multiplied by @p 2 raised to random exponent [@a fromExponent, @a toExponent]. Sign is randomly applied to the resulting value.\n * @tparam T floating point number type.\n * @tparam E random number generator engine.\n * @param fromExponent lower bound of a set of powers of base 2 exponents to be used to multiply a randomly generated fraction from\n * [@p 0.0, @p 1.0) range.\n * @param toExponent upper bound of a set of powers of base 2 exponents to be used to multiply a randomly generated fraction from\n * [@p 0.0, @p 1.0) range.\n * @return randomly generated floating point number.\n *\/\ntemplate <typename T, typename E = SeededEngine<std::mt19937>>\ntypename std::enable_if<std::is_floating_point<T>::value, T>::type rand(int fromExponent = std::numeric_limits<T>::min_exponent, int toExponent = std::numeric_limits<T>::max_exponent)\n{\n\tstatic E engine; \/\/ Use static variable to prevent frequent allocation\/deallocation (\"mt19937 use 5000 bytes of memory for each creation (which is bad for performance if we create it too frequently)\" -- https:\/\/github.com\/effolkronium\/random).\n\n\tstd::uniform_real_distribution<T> fracDistribution(0.0, 1.0);\t\/\/ A fraction within range [0.0, 1.0).\n\tstd::uniform_int_distribution<int> expDistribution(fromExponent, toExponent);\n\n\treturn rand<bool>() ? std::ldexp(fracDistribution(engine), expDistribution(engine)) : -std::ldexp(fracDistribution(engine), expDistribution(engine));\n}\n\n\/**\n * Generate random Boolean value using Bernoulli distribution.\n * @tparam T boolean type.\n * @tparam E random number generator engine.\n * @param p propbablity of generating @p true.\n * @return one of the Boolean values: @p true or @p false.\n *\/\ntemplate <typename T, typename E = SeededEngine<std::mt19937>>\ntypename std::enable_if<std::is_same<T, bool>::value, T>::type rand(double p = 0.5)\n{\n\tstatic E engine; \/\/ Use static variable to prevent frequent allocation\/deallocation (\"mt19937 use 5000 bytes of memory for each creation (which is bad for performance if we create it too frequently)\" -- https:\/\/github.com\/effolkronium\/random).\n\n\tstd::bernoulli_distribution distribution(p);\n\n\treturn distribution(engine);\n}\n\n\/**\n * Generate random character.\n * @tparam T QChar type.\n * @tparam E random number generator engine.\n * @param category character category.\n * @return random character.\n *\/\ntemplate <typename T, typename E = SeededEngine<std::mt19937>>\ntypename std::enable_if<std::is_same<T, QChar>::value, QChar>::type rand(QChar::Category category)\n{\n\tstatic E engine; \/\/ Use static variable to prevent frequent allocation\/deallocation (\"mt19937 use 5000 bytes of memory for each creation (which is bad for performance if we create it too frequently)\" -- https:\/\/github.com\/effolkronium\/random).\n\tstatic QMultiHash<int, QChar> categorySets;\t\t\/\/ Key denotes category of specific charecters.\n\n\tif (categorySets.empty()) {\n\t\t\/\/ Initialize categorized sets of characters.\n\t\tfor (char16_t c = 0; c < std::numeric_limits<char16_t>::max(); c++)\n\t\t\tcategorySets.insert(QChar::category(c), c);\n\t\tcategorySets.insert(QChar::category(std::numeric_limits<char16_t>::max()), std::numeric_limits<char16_t>::max());\n\t}\n\n\treturn categorySets.values(category).at(rand(0, categorySets.values(category).size() - 1));\n}\n\n\/**\n * Generate random string.\n * @tparam T QString type.\n * @tparam E random number generator engine.\n * @param length string length.\n * @param categories character categories of which string should be composed from.\n * @return randomly generated string.\n *\/\ntemplate <typename T, typename E = SeededEngine<std::mt19937>>\ntypename std::enable_if<std::is_same<T, QString>::value, T>::type rand(int length = rand(0, 255), QList<QChar::Category> categories = {QChar::Letter_Uppercase, QChar::Letter_Lowercase, QChar::Number_DecimalDigit})\n{\n\tstatic E engine; \/\/ Use static variable to prevent frequent allocation\/deallocation (\"mt19937 use 5000 bytes of memory for each creation (which is bad for performance if we create it too frequently)\" -- https:\/\/github.com\/effolkronium\/random).\n\n\tQString result(\"\");\n\tfor (int i = 0; i < length; i++)\n\t\tresult.append(rand<QChar>(categories.at(rand(0, categories.size() - 1))));\n\n\treturn result;\n}\n\n\/**\n * Generate random string list.\n * @tparam T QStringList type.\n * @tparam E random number generator engine.\n * @param size string list size.\n * @param length strings length.\n * @param categories character categories of which strings should be composed from.\n * @return randomly generated string list.\n *\/\ntemplate <typename T, typename E = SeededEngine<std::mt19937>>\ntypename std::enable_if<std::is_same<T, QStringList>::value, T>::type rand(int size = rand(0, 255), int length = rand(0, 255), QList<QChar::Category> categories = {QChar::Letter_Uppercase, QChar::Letter_Lowercase, QChar::Number_DecimalDigit})\n{\n\tstatic E engine; \/\/ Use static variable to prevent frequent allocation\/deallocation (\"mt19937 use 5000 bytes of memory for each creation (which is bad for performance if we create it too frequently)\" -- https:\/\/github.com\/effolkronium\/random).\n\n\tQStringList result;\n\tfor (int i = 0; i < size; i++)\n\t\tresult.append(rand<QString>(length, categories));\n\n\treturn result;\n}\n\n\/**\n * Randomize array.\n * @tparam T type of array elements.\n * @tparam E random number genererator engine.\n * @tparam ARGS arguments to be passed to underlying rand() function.\n * @param ptr array pointer.\n * @param size array size.\n * @param arguments to be passed to underlying rand() function for each array\n * element.\n *\/\ntemplate <typename T, typename E = SeededEngine<std::mt19937>, typename... ARGS>\nvoid rand(T * ptr, std::size_t size, ARGS... args)\n{\n\twhile (size > 0) {\n\t\t*ptr = rand<T, E>(args...);\n\t\tptr++;\n\t\tsize--;\n\t}\n}\n\n}\n}\n\n#endif\n\n\/\/(c)MP: Copyright © 2019, Michal Policht <michpolicht@gmail.com>. All rights reserved.\n\/\/(c)MP: This file is a part of CuteHMI.\n\/\/(c)MP: CuteHMI is free software: you can redistribute it and\/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.\n\/\/(c)MP: CuteHMI is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.\n\/\/(c)MP: You should have received a copy of the GNU Lesser General Public License along with CuteHMI. If not, see <https:\/\/www.gnu.org\/licenses\/>.\n<|endoftext|>"} {"text":"<commit_before>#include \"gtest\/gtest.h\"\n#include \"ROOT\/THist.hxx\"\n#include \"ROOT\/THistBinIter.hxx\"\n#include <cmath>\n#include <limits>\n\nusing namespace ROOT::Experimental;\n\n\/\/ Test FindBin() in all its glory.\n\n\/\/ Basic binning on a Equidistant axis.\nTEST(AxisBinning, EquiDistBasic) {\n TAxisEquidistant ax(\"TITLE\", 10, -1., 1.);\n EXPECT_EQ(1, ax.FindBin(-.999));\n EXPECT_EQ(5, ax.FindBin(-.001));\n EXPECT_EQ(10, ax.FindBin(0.999));\n EXPECT_EQ(0, ax.FindBin(-2.));\n EXPECT_EQ(11, ax.FindBin(2000.));\n\n EXPECT_GE(6, ax.FindBin(std::numeric_limits<double>::min()));\n EXPECT_LE(5, ax.FindBin(std::numeric_limits<double>::min()));\n EXPECT_GE(6, ax.FindBin(-std::numeric_limits<double>::min()));\n EXPECT_LE(5, ax.FindBin(-std::numeric_limits<double>::min()));\n\n EXPECT_EQ(11, ax.FindBin(std::numeric_limits<double>::max()));\n EXPECT_EQ(0, ax.FindBin(-std::numeric_limits<double>::max()));\n}\n\n\/\/ Epsilon bin widths.\nTEST(AxisBinning, EquiDistEps) {\n static constexpr auto eps = std::numeric_limits<double>::epsilon();\n TAxisEquidistant ax(\"TITLE\", 10, 0., eps * 10.);\n EXPECT_LE(0, ax.FindBin(0.5*eps));\n EXPECT_GE(1, ax.FindBin(0.5*eps));\n\n EXPECT_LE(5, ax.FindBin(5.*eps));\n EXPECT_GE(6, ax.FindBin(5.*eps));\n\n EXPECT_LE(10, ax.FindBin(10.*eps));\n EXPECT_GE(11, ax.FindBin(10.*eps));\n\n EXPECT_EQ(0, ax.FindBin(-2000.*eps));\n EXPECT_EQ(11, ax.FindBin(2000.*eps));\n EXPECT_EQ(1, ax.FindBin(std::numeric_limits<double>::min()));\n EXPECT_EQ(0, ax.FindBin(-std::numeric_limits<double>::min()));\n EXPECT_EQ(11, ax.FindBin(std::numeric_limits<double>::max()));\n EXPECT_EQ(0, ax.FindBin(-std::numeric_limits<double>::max()));\n}\n<commit_msg>Test FindBin() for irregular binning, histograms.<commit_after>#include \"gtest\/gtest.h\"\n#include \"ROOT\/THist.hxx\"\n#include \"ROOT\/THistBinIter.hxx\"\n#include <cmath>\n#include <limits>\n\nusing namespace ROOT::Experimental;\n\n\/\/ Test FindBin() in all its glory.\n\n\/\/ Basic binning on a Equidistant axis.\nTEST(AxisBinning, EquidistBasic) {\n TAxisEquidistant ax(\"TITLE\", 10, -1., 1.);\n EXPECT_EQ(1, ax.FindBin(-.999));\n EXPECT_EQ(5, ax.FindBin(-.001));\n EXPECT_EQ(10, ax.FindBin(0.999));\n EXPECT_EQ(0, ax.FindBin(-2.));\n EXPECT_EQ(11, ax.FindBin(2000.));\n\n EXPECT_GE(6, ax.FindBin(std::numeric_limits<double>::min()));\n EXPECT_LE(5, ax.FindBin(std::numeric_limits<double>::min()));\n EXPECT_GE(6, ax.FindBin(-std::numeric_limits<double>::min()));\n EXPECT_LE(5, ax.FindBin(-std::numeric_limits<double>::min()));\n\n EXPECT_EQ(11, ax.FindBin(std::numeric_limits<double>::max()));\n EXPECT_EQ(0, ax.FindBin(-std::numeric_limits<double>::max()));\n}\n\n\n\/\/ Epsilon bin widths.\nTEST(AxisBinning, EquidistEpsBins) {\n static constexpr auto eps = std::numeric_limits<double>::min();\n TAxisEquidistant ax(\"TITLE\", 10, 0., eps * 10.);\n EXPECT_LE(0, ax.FindBin(0.5*eps));\n EXPECT_GE(1, ax.FindBin(0.5*eps));\n\n EXPECT_LE(5, ax.FindBin(5.*eps));\n EXPECT_GE(6, ax.FindBin(5.*eps));\n\n EXPECT_LE(10, ax.FindBin(10.*eps));\n EXPECT_GE(11, ax.FindBin(10.*eps));\n\n EXPECT_EQ(0, ax.FindBin(-2000.*eps));\n EXPECT_EQ(11, ax.FindBin(2000.*eps));\n EXPECT_LE(1, ax.FindBin(std::numeric_limits<double>::min()));\n EXPECT_GE(2, ax.FindBin(std::numeric_limits<double>::min()));\n EXPECT_LE(0, ax.FindBin(-std::numeric_limits<double>::min()));\n EXPECT_GE(1, ax.FindBin(-std::numeric_limits<double>::min()));\n EXPECT_EQ(11, ax.FindBin(std::numeric_limits<double>::max()));\n EXPECT_EQ(0, ax.FindBin(-std::numeric_limits<double>::max()));\n}\n\n\n\/\/ Basic binning on an Irregular axis.\nTEST(AxisBinning, IrregularBasic) {\n TAxisIrregular ax(\"TITLE\", {-5., 0., 0.1, 1., 10., 100.});\n EXPECT_EQ(2, ax.FindBin(.001));\n EXPECT_EQ(1, ax.FindBin(-.001));\n EXPECT_EQ(5, ax.FindBin(99.));\n EXPECT_EQ(0, ax.FindBin(-6.));\n EXPECT_EQ(6, ax.FindBin(2000.));\n\n EXPECT_GE(2, ax.FindBin(std::numeric_limits<double>::min()));\n EXPECT_LE(1, ax.FindBin(std::numeric_limits<double>::min()));\n EXPECT_GE(2, ax.FindBin(-std::numeric_limits<double>::min()));\n EXPECT_LE(1, ax.FindBin(-std::numeric_limits<double>::min()));\n\n EXPECT_EQ(6, ax.FindBin(std::numeric_limits<double>::max()));\n EXPECT_EQ(0, ax.FindBin(-std::numeric_limits<double>::max()));\n}\n\n\n\/\/ Limit bin widths on an Irregular axis.\nTEST(AxisBinning, IrregularEpsBins) {\n static constexpr auto eps = std::numeric_limits<double>::min();\n TAxisIrregular ax(\"TITLE\", {0., eps, 2.*eps, 3.*eps, 4.*eps, 5.*eps});\n EXPECT_LE(0, ax.FindBin(0.5*eps));\n EXPECT_GE(1, ax.FindBin(0.5*eps));\n\n EXPECT_LE(3, ax.FindBin(3.*eps));\n EXPECT_GE(4, ax.FindBin(3.*eps));\n\n EXPECT_LE(5, ax.FindBin(5.*eps));\n EXPECT_GE(6, ax.FindBin(5.*eps));\n\n EXPECT_EQ(0, ax.FindBin(-2000.*eps));\n EXPECT_EQ(6, ax.FindBin(2000.*eps));\n EXPECT_EQ(1, ax.FindBin(std::numeric_limits<double>::min()));\n EXPECT_EQ(0, ax.FindBin(-std::numeric_limits<double>::min()));\n EXPECT_EQ(6, ax.FindBin(std::numeric_limits<double>::max()));\n EXPECT_EQ(0, ax.FindBin(-std::numeric_limits<double>::max()));\n}\n\n\/\/ Histogram binning on a Equidistant axis.\nTEST(HistImplBinning, Equidist1D) {\n Detail::THistImpl<Detail::THistData<1, double, Detail::THistDataDefaultStorage, THistStatContent>,\n TAxisEquidistant> hist(TAxisEquidistant(10, 0., 1.));\n\n EXPECT_EQ(5, hist.GetBinIndex({.45}));\n EXPECT_EQ(10, hist.GetBinIndex({.999}));\n EXPECT_EQ(1, hist.GetBinIndex({.001}));\n EXPECT_EQ(0, hist.GetBinIndex({-.001}));\n EXPECT_EQ(11, hist.GetBinIndex({1.001}));\n\n EXPECT_GE(1, hist.GetBinIndex({std::numeric_limits<double>::min()}));\n EXPECT_LE(0, hist.GetBinIndex({std::numeric_limits<double>::min()}));\n EXPECT_GE(1, hist.GetBinIndex({-std::numeric_limits<double>::min()}));\n EXPECT_LE(0, hist.GetBinIndex({-std::numeric_limits<double>::min()}));\n\n EXPECT_EQ(11, hist.GetBinIndex({std::numeric_limits<double>::max()}));\n EXPECT_EQ(0, hist.GetBinIndex({-std::numeric_limits<double>::max()}));\n}\n\nTEST(HistImplBinning, EquiDist2D) {\n Detail::THistImpl<Detail::THistData<2, double, Detail::THistDataDefaultStorage, THistStatContent>,\n TAxisEquidistant, TAxisEquidistant>\n hist(TAxisEquidistant(2, 0., 2.), TAxisEquidistant(2, -1., 1.));\n\n EXPECT_EQ( 0, hist.GetBinIndex({-100., -100.}));\n EXPECT_EQ( 1, hist.GetBinIndex({0.5, -100.}));\n EXPECT_EQ( 2, hist.GetBinIndex({1.5, -100.}));\n EXPECT_EQ( 3, hist.GetBinIndex({100., -100.}));\n EXPECT_EQ( 4, hist.GetBinIndex({-100., -0.5}));\n EXPECT_EQ( 5, hist.GetBinIndex({0.5, -0.5}));\n EXPECT_EQ( 6, hist.GetBinIndex({1.5, -0.5}));\n EXPECT_EQ( 7, hist.GetBinIndex({100., -0.5}));\n EXPECT_EQ( 8, hist.GetBinIndex({-100., 0.5}));\n EXPECT_EQ( 9, hist.GetBinIndex({0.5, 0.5}));\n EXPECT_EQ(10, hist.GetBinIndex({1.5, 0.5}));\n EXPECT_EQ(11, hist.GetBinIndex({100., 0.5}));\n EXPECT_EQ(12, hist.GetBinIndex({-100., 100.}));\n EXPECT_EQ(13, hist.GetBinIndex({0.5, 100.}));\n EXPECT_EQ(14, hist.GetBinIndex({1.5, 100.}));\n EXPECT_EQ(15, hist.GetBinIndex({100., 100.}));\n\n EXPECT_EQ( 0, hist.GetBinIndex({-std::numeric_limits<double>::max(), -std::numeric_limits<double>::max()}));\n EXPECT_EQ( 3, hist.GetBinIndex({ std::numeric_limits<double>::max(), -std::numeric_limits<double>::max()}));\n EXPECT_EQ(12, hist.GetBinIndex({-std::numeric_limits<double>::max(), std::numeric_limits<double>::max()}));\n EXPECT_EQ(15, hist.GetBinIndex({ std::numeric_limits<double>::max(), std::numeric_limits<double>::max()}));\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"NeuralNetwork.h\"\n\nNeuralNetwork::NeuralNetwork()\n{\n generation = 0;\n dna = new Genome();\n}\n\nNeuralNetwork::NeuralNetwork(std::string dir)\n{\n dna = new Genome();\n generation = 0;\n\n dna -> loadFromFile(dir);\n updateStructure();\n\n}\n\nNeuralNetwork::NeuralNetwork(Genome code)\n{\n dna = new Genome();\n generation = 0;\n dna -> copyIntoGenome(code);\n updateStructure();\n}\n\nNeuralNetwork::~NeuralNetwork()\n{\n delete dna;\n\n for(auto & node : inputs)\n delete node;\n\n for(auto & vec : hiddenLayer)\n for(auto & node : vec)\n delete node;\n\n for(auto & node : outputs)\n delete node;\n}\n\nvoid NeuralNetwork::updateStructure()\n{\n \/\/Create the nodes in the network.\n \/\/Create the input layer.\n for(unsigned int i = 0; i < dna -> getInput(); ++i)\n inputs.push_back(new Node());\n\n \/\/Create the hidden layer.\n std::vector<unsigned int> topo = dna -> getHidden();\n unsigned int size = topo.size();\n\n hiddenLayer.resize(size);\n for(unsigned int i = 0; i < size; ++i)\n for(unsigned int j = 0; j < topo[i]; ++j)\n hiddenLayer[i].push_back(new Node());\n\n \/\/Create the output layer.\n for(unsigned int i = 0; i < dna -> getOutput(); ++i)\n outputs.push_back(new Node());\n\n \/\/Connect structure based on the genes in the genome and add the correct weights.\n unsigned int numConnections = dna -> getGenes().size();\n Gene currentGene;\n Node * first;\n Node * last;\n Weight * weight;\n for(unsigned int i = 0; i < numConnections; ++i)\n {\n currentGene = dna -> getGene(i);\n first = findNodeWithID(currentGene.inID);\n last = findNodeWithID(currentGene.outID);\n first -> addForward(last,first);\n weight = first -> getLastForward();\n weight -> weight() = currentGene.weight;\n last -> addBackwards(weight);\n\n }\n\n}\n\nvoid NeuralNetwork::mutate()\n{\n\n}\n\nvoid NeuralNetwork::saveNetwork(std::string name)\n{\n name += \".charzar\"; \/\/maybe dont do it this way\n dna -> saveGenome(name);\n}\n\nvoid NeuralNetwork::loadFromFile(std::string dir)\n{\n dna -> loadFromFile(dir);\n updateStructure();\n}\n\n\n\/\/There is a better way to write this code;\nNode * NeuralNetwork::findNodeWithID(unsigned int ID)\n{\n \/\/calculates the size of the hiddenLayer.\n unsigned int hiddenLayerSize = 0;\n for(auto & vec : hiddenLayer)\n hiddenLayerSize += vec.size();\n\n if(ID < inputs.size())\n {\n return inputs[ID];\n }\n else if (ID < inputs.size() + hiddenLayerSize)\n {\n ID -= inputs.size();\n unsigned int count = 0;\n\n for(auto & vec : hiddenLayer)\n {\n for(auto & node : vec)\n {\n if(count == ID)\n return node;\n ++count;\n }\n }\n }\n else\n {\n ID -= inputs.size() + hiddenLayerSize;\n return outputs[ID];\n }\n return NULL; \/\/If this works this will never execute.\n}\n<commit_msg>add new structure<commit_after>#include \"NeuralNetwork.h\"\n\nNeuralNetwork::NeuralNetwork()\n{\n generation = 0;\n dna = new Genome();\n}\n\nNeuralNetwork::NeuralNetwork(std::string dir)\n{\n dna = new Genome();\n generation = 0;\n\n dna -> loadFromFile(dir);\n updateStructure();\n\n}\n\nNeuralNetwork::NeuralNetwork(Genome code)\n{\n dna = new Genome();\n generation = 0;\n dna -> copyIntoGenome(code);\n updateStructure();\n}\n\nNeuralNetwork::~NeuralNetwork()\n{\n delete dna;\n\n for(auto & node : inputs)\n delete node;\n\n for(auto & vec : hiddenLayer)\n for(auto & node : vec)\n delete node;\n\n for(auto & node : outputs)\n delete node;\n}\n\nvoid NeuralNetwork::updateStructure()\n{\n \/\/Create the nodes in the network.\n \/\/Create the input layer.\n for(unsigned int i = 0; i < dna -> getInput(); ++i)\n inputs.push_back(new Node());\n\n \/\/Create the hidden layer.\n std::vector<unsigned int> topo = dna -> getHidden();\n unsigned int size = topo.size();\n\n hiddenLayer.resize(size);\n for(unsigned int i = 0; i < size; ++i)\n for(unsigned int j = 0; j < topo[i]; ++j)\n hiddenLayer[i].push_back(new Node());\n\n \/\/Create the output layer.\n for(unsigned int i = 0; i < dna -> getOutput(); ++i)\n outputs.push_back(new Node());\n\n \/\/Connect structure based on the genes in the genome and add the correct weights.\n unsigned int numConnections = dna -> getGenes().size();\n Gene currentGene;\n Node * first;\n Node * last;\n Weight * weight;\n for(unsigned int i = 0; i < numConnections; ++i)\n {\n currentGene = dna -> getGene(i);\n first = findNodeWithID(currentGene.inID);\n last = findNodeWithID(currentGene.outID);\n first -> addForward(last);\n last -> addBackward(first);\n last -> weight() = currentGene.weight;\n }\n\n}\n\nvoid NeuralNetwork::mutate()\n{\n\n}\n\nvoid NeuralNetwork::saveNetwork(std::string name)\n{\n name += \".charzar\"; \/\/maybe dont do it this way\n dna -> saveGenome(name);\n}\n\nvoid NeuralNetwork::loadFromFile(std::string dir)\n{\n dna -> loadFromFile(dir);\n updateStructure();\n}\n\n\n\/\/There is a better way to write this code;\nNode * NeuralNetwork::findNodeWithID(unsigned int ID)\n{\n \/\/calculates the size of the hiddenLayer.\n unsigned int hiddenLayerSize = 0;\n for(auto & vec : hiddenLayer)\n hiddenLayerSize += vec.size();\n\n if(ID < inputs.size())\n {\n return inputs[ID];\n }\n else if (ID < inputs.size() + hiddenLayerSize)\n {\n ID -= inputs.size();\n unsigned int count = 0;\n\n for(auto & vec : hiddenLayer)\n {\n for(auto & node : vec)\n {\n if(count == ID)\n return node;\n ++count;\n }\n }\n }\n else\n {\n ID -= inputs.size() + hiddenLayerSize;\n return outputs[ID];\n }\n return NULL; \/\/If this works this will never execute.\n}\n<|endoftext|>"} {"text":"<commit_before>#ifdef _WIN32\n#define S_ISDIR(mode) (((mode) & S_IFMT) == S_IFDIR)\n#endif\n\n#include <iostream>\n#include <fstream>\n#include <cctype>\n#include <sys\/stat.h>\n#include \"file.hpp\"\n#include \"context.hpp\"\n\nnamespace Sass {\n namespace File {\n using namespace std;\n\n string base_name(string path)\n {\n size_t pos = path.find_last_of('\/');\n if (pos == string::npos) return path;\n else return path.substr(pos+1);\n }\n\n string dir_name(string path)\n {\n size_t pos = path.find_last_of('\/');\n if (pos == string::npos) return \"\";\n else return path.substr(0, pos+1);\n }\n\n string join_paths(string l, string r)\n {\n if (l.empty()) return r;\n if (r.empty()) return l;\n if (is_absolute_path(r)) return r;\n\n if (l[l.length()-1] != '\/') l += '\/';\n\n while ((r.length() > 3) && (r.substr(0, 3) == \"..\/\")) {\n r = r.substr(3);\n size_t index = l.find_last_of('\/', l.length() - 2);\n l = l.substr(0, index + 1);\n }\n\n return l + r;\n }\n\n bool is_absolute_path(const string& path)\n {\n if (path[0] == '\/') return true;\n \/\/ TODO: UN-HACKIFY THIS\n #ifdef _WIN32\n if (path.length() >= 2 && isalpha(path[0]) && path[1] == ':') return true;\n #endif\n return false;\n }\n\n string make_absolute_path(const string& path, const string& cwd)\n {\n return (is_absolute_path(path) ? path : join_paths(cwd, path));\n }\n\n string resolve_relative_path(const string& uri, const string& base, const string& cwd)\n {\n string absolute_uri = make_absolute_path(uri, cwd);\n string absolute_base = make_absolute_path(base, cwd);\n\n string stripped_uri = \"\";\n string stripped_base = \"\";\n\n size_t index = 0;\n size_t minSize = min(absolute_uri.size(), absolute_base.size());\n for (size_t i = 0; i < minSize; ++i) {\n if (absolute_uri[i] != absolute_base[i]) break;\n if (absolute_uri[i] == '\/') index = i + 1;\n }\n for (size_t i = index; i < absolute_uri.size(); ++i) {\n stripped_uri += absolute_uri[i];\n }\n for (size_t i = index; i < absolute_base.size(); ++i) {\n stripped_base += absolute_base[i];\n }\n size_t directories = 0;\n for (size_t i = 0; i < stripped_base.size(); ++i) {\n if (stripped_base[i] == '\/') ++directories;\n }\n string result = \"\";\n for (size_t i = 0; i < directories; ++i) {\n result += \"..\/\";\n }\n result += stripped_uri;\n\n return result;\n }\n\n char* resolve_and_load(string path, string& real_path)\n {\n \/\/ Resolution order for ambiguous imports:\n \/\/ (1) filename as given\n \/\/ (2) underscore + given\n \/\/ (3) underscore + given + extension\n \/\/ (4) given + extension\n char* contents = 0;\n \/\/ if the file isn't found with the given filename ...\n real_path = path;\n if (!(contents = read_file(real_path))) {\n string dir(dir_name(path));\n string base(base_name(path));\n string _base(\"_\" + base);\n real_path = dir + _base;\n \/\/ if the file isn't found with '_' + filename ...\n if (!(contents = read_file(real_path))) {\n string _base_scss(_base + \".scss\");\n real_path = dir + _base_scss;\n \/\/ if the file isn't found with '_' + filename + \".scss\" ...\n if (!(contents = read_file(real_path))) {\n string base_scss(base + \".scss\");\n \/\/ try filename + \".scss\" as the last resort\n real_path = dir + base_scss;\n contents = read_file(real_path);\n }\n }\n }\n return contents;\n }\n\n char* read_file(string path)\n {\n struct stat st;\n if (stat(path.c_str(), &st) == -1 || S_ISDIR(st.st_mode)) return 0;\n ifstream file(path.c_str(), ios::in | ios::binary | ios::ate);\n char* contents = 0;\n if (file.is_open()) {\n size_t size = file.tellg();\n contents = new char[size + 1]; \/\/ extra byte for the null char\n file.seekg(0, ios::beg);\n file.read(contents, size);\n contents[size] = '\\0';\n file.close();\n }\n return contents;\n }\n\n }\n}\n<commit_msg>handling the backslash folder-separator in case we're on Windows<commit_after>#ifdef _WIN32\n#define S_ISDIR(mode) (((mode) & S_IFMT) == S_IFDIR)\n#endif\n\n#include <iostream>\n#include <fstream>\n#include <cctype>\n#include <sys\/stat.h>\n#include \"file.hpp\"\n#include \"context.hpp\"\n\nnamespace Sass {\n namespace File {\n using namespace std;\n\n string base_name(string path)\n {\n size_t pos = path.find_last_of('\/');\n #ifdef _WIN32\n if (pos == string::npos) pos = path.find_last_of('\\\\');\n #endif\n if (pos == string::npos) return path;\n else return path.substr(pos+1);\n }\n\n string dir_name(string path)\n {\n size_t pos = path.find_last_of('\/');\n #ifdef _WIN32\n if (pos == string::npos) pos = path.find_last_of('\\\\');\n #endif\n if (pos == string::npos) return \"\";\n else return path.substr(0, pos+1);\n }\n\n string join_paths(string l, string r)\n {\n if (l.empty()) return r;\n if (r.empty()) return l;\n if (is_absolute_path(r)) return r;\n\n if (l[l.length()-1] != '\/') l += '\/';\n\n while ((r.length() > 3) && ((r.substr(0, 3) == \"..\/\") || (r.substr(0, 3)) == \"..\\\\\")) {\n r = r.substr(3);\n size_t pos = l.find_last_of('\/', l.length() - 2);\n #ifdef _WIN32\n if (pos == string::npos) pos = path.find_last_of('\\\\', l.length() - 2);\n #endif\n l = l.substr(0, pos + 1);\n }\n\n return l + r;\n }\n\n bool is_absolute_path(const string& path)\n {\n if (path[0] == '\/') return true;\n \/\/ TODO: UN-HACKIFY THIS\n #ifdef _WIN32\n if (path.length() >= 2 && isalpha(path[0]) && path[1] == ':') return true;\n #endif\n return false;\n }\n\n string make_absolute_path(const string& path, const string& cwd)\n {\n return (is_absolute_path(path) ? path : join_paths(cwd, path));\n }\n\n string resolve_relative_path(const string& uri, const string& base, const string& cwd)\n {\n string absolute_uri = make_absolute_path(uri, cwd);\n string absolute_base = make_absolute_path(base, cwd);\n\n string stripped_uri = \"\";\n string stripped_base = \"\";\n\n size_t index = 0;\n size_t minSize = min(absolute_uri.size(), absolute_base.size());\n for (size_t i = 0; i < minSize; ++i) {\n if (absolute_uri[i] != absolute_base[i]) break;\n if (absolute_uri[i] == '\/') index = i + 1;\n }\n for (size_t i = index; i < absolute_uri.size(); ++i) {\n stripped_uri += absolute_uri[i];\n }\n for (size_t i = index; i < absolute_base.size(); ++i) {\n stripped_base += absolute_base[i];\n }\n size_t directories = 0;\n for (size_t i = 0; i < stripped_base.size(); ++i) {\n if (stripped_base[i] == '\/') ++directories;\n }\n string result = \"\";\n for (size_t i = 0; i < directories; ++i) {\n result += \"..\/\";\n }\n result += stripped_uri;\n\n return result;\n }\n\n char* resolve_and_load(string path, string& real_path)\n {\n \/\/ Resolution order for ambiguous imports:\n \/\/ (1) filename as given\n \/\/ (2) underscore + given\n \/\/ (3) underscore + given + extension\n \/\/ (4) given + extension\n char* contents = 0;\n real_path = path;\n \/\/ if the file isn't found with the given filename ...\n if (!(contents = read_file(real_path))) {\n string dir(dir_name(path));\n string base(base_name(path));\n string _base(\"_\" + base);\n real_path = dir + _base;\n \/\/ if the file isn't found with '_' + filename ...\n if (!(contents = read_file(real_path))) {\n string _base_scss(_base + \".scss\");\n real_path = dir + _base_scss;\n \/\/ if the file isn't found with '_' + filename + \".scss\" ...\n if (!(contents = read_file(real_path))) {\n string base_scss(base + \".scss\");\n \/\/ try filename + \".scss\" as the last resort\n real_path = dir + base_scss;\n contents = read_file(real_path);\n }\n }\n }\n return contents;\n }\n\n char* read_file(string path)\n {\n struct stat st;\n if (stat(path.c_str(), &st) == -1 || S_ISDIR(st.st_mode)) return 0;\n ifstream file(path.c_str(), ios::in | ios::binary | ios::ate);\n char* contents = 0;\n if (file.is_open()) {\n size_t size = file.tellg();\n contents = new char[size + 1]; \/\/ extra byte for the null char\n file.seekg(0, ios::beg);\n file.read(contents, size);\n contents[size] = '\\0';\n file.close();\n }\n return contents;\n }\n\n }\n}\n<|endoftext|>"} {"text":"<commit_before>#define _IRR_STATIC_LIB_\n#include <irrlicht.h>\n\n#include \"..\/3rdparty\/portable-file-dialogs\/portable-file-dialogs.h\"\n#include \"..\/..\/ext\/MitsubaLoader\/CMitsubaLoader.h\"\n\nusing namespace irr;\nusing namespace core;\n\nbool quit = false;\nclass MyEventReceiver : public IEventReceiver\n{\npublic:\n\n\tMyEventReceiver()\n\t{\n\t}\n\n\tbool OnEvent(const SEvent& event)\n\t{\n\t\tif (event.EventType == irr::EET_KEY_INPUT_EVENT && !event.KeyInput.PressedDown)\n\t\t{\n\t\t\tswitch (event.KeyInput.Key)\n\t\t\t{\n\t\t\tcase irr::KEY_ESCAPE:\n\t\t\tcase irr::KEY_KEY_Q:\n\t\t\t\tquit = true;\n\t\t\t\treturn true;\n\t\t\tdefault:\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\treturn false;\n\t}\n\nprivate:\n};\n\nclass SimpleCallBack : public video::IShaderConstantSetCallBack\n{\n\tint32_t mvpUniformLocation;\n\tint32_t cameraDirUniformLocation;\n\tint32_t texUniformLocation[4];\n\tvideo::E_SHADER_CONSTANT_TYPE mvpUniformType;\n\tvideo::E_SHADER_CONSTANT_TYPE cameraDirUniformType;\n\tvideo::E_SHADER_CONSTANT_TYPE texUniformType[4];\npublic:\n\tSimpleCallBack() : cameraDirUniformLocation(-1), cameraDirUniformType(video::ESCT_FLOAT_VEC3) {}\n\n\tvirtual void PostLink(video::IMaterialRendererServices* services, const video::E_MATERIAL_TYPE& materialType, const core::vector<video::SConstantLocationNamePair>& constants)\n\t{\n\t\tfor (size_t i = 0; i < constants.size(); i++)\n\t\t{\n\t\t\tif (constants[i].name == \"MVP\")\n\t\t\t{\n\t\t\t\tmvpUniformLocation = constants[i].location;\n\t\t\t\tmvpUniformType = constants[i].type;\n\t\t\t}\n\t\t\telse if (constants[i].name == \"cameraPos\")\n\t\t\t{\n\t\t\t\tcameraDirUniformLocation = constants[i].location;\n\t\t\t\tcameraDirUniformType = constants[i].type;\n\t\t\t}\n\t\t}\n\t}\n\n\tvirtual void OnSetConstants(video::IMaterialRendererServices* services, int32_t userData)\n\t{\n\t\tcore::vectorSIMDf modelSpaceCamPos;\n\t\tmodelSpaceCamPos.set(services->getVideoDriver()->getTransform(video::E4X3TS_WORLD_VIEW_INVERSE).getTranslation());\n\t\tservices->setShaderConstant(&modelSpaceCamPos, cameraDirUniformLocation, cameraDirUniformType, 1);\n\t\tservices->setShaderConstant(services->getVideoDriver()->getTransform(video::EPTS_PROJ_VIEW_WORLD).pointer(), mvpUniformLocation, mvpUniformType, 1);\n\t}\n\n\tvirtual void OnUnsetMaterial() {}\n};\n\nint main()\n{\n\tsrand(time(0));\n\t\/\/ create device with full flexibility over creation parameters\n\t\/\/ you can add more parameters if desired, check irr::SIrrlichtCreationParameters\n\tirr::SIrrlichtCreationParameters params;\n\tparams.Bits = 24; \/\/may have to set to 32bit for some platforms\n\tparams.ZBufferBits = 24; \/\/we'd like 32bit here\n\tparams.DriverType = video::EDT_OPENGL; \/\/! Only Well functioning driver, software renderer left for sake of 2D image drawing\n\tparams.WindowSize = dimension2d<uint32_t>(800, 600);\n\tparams.Fullscreen = false;\n\tparams.Vsync = true; \/\/! If supported by target platform\n\tparams.Doublebuffer = true;\n\tparams.Stencilbuffer = false; \/\/! This will not even be a choice soon\n\tIrrlichtDevice* device = createDeviceEx(params);\n\t\n\tvideo::IVideoDriver* driver = device->getVideoDriver();\n\n\tscene::ISceneManager* smgr = device->getSceneManager();\n\tdriver->setTextureCreationFlag(video::ETCF_ALWAYS_32_BIT, true);\n\tscene::ICameraSceneNode* camera =\n\t\tsmgr->addCameraSceneNodeFPS(0, 100.0f, 0.01f);\n\tcamera->setPosition(core::vector3df(0, 0, 3));\n\tcamera->setTarget(core::vector3df(0, 0, 0));\n\tcamera->setNearValue(0.01f);\n\tcamera->setFarValue(10000.0f);\n\tsmgr->setActiveCamera(camera);\n\tdevice->getCursorControl()->setVisible(false);\n\tMyEventReceiver receiver;\n\tdevice->setEventReceiver(&receiver);\n\n\tSimpleCallBack* cb = new SimpleCallBack();\n\tvideo::E_MATERIAL_TYPE newMaterialType = (video::E_MATERIAL_TYPE)driver->getGPUProgrammingServices()->addHighLevelShaderMaterialFromFiles(\"..\/mesh.vert\",\n\t\t\"\", \"\", \"\", \/\/! No Geometry or Tessellation Shaders\n\t\t\"..\/mesh.frag\",\n\t\t3, video::EMT_SOLID, \/\/! 3 vertices per primitive (this is tessellation shader relevant only\n\t\tcb, \/\/! Our Shader Callback\n\t\t0); \/\/! No custom user data\n\tcb->drop();\n\n\tif (device == 0)\n\t\treturn 1; \/\/ could not create selected driver.\n\n\tio::IFileSystem* fs = device->getFileSystem();\n\tasset::IAssetManager* am = device->getAssetManager();\n\n\tam.addAssetLoader(core::make_smart_refctd_ptr<irr::ext::MitsubaLoader::CMitsubaLoader>(device));\n\n#define MITSUBA_LOADER_TESTS\n\n#ifdef MITSUBA_LOADER_TESTS\n\tstd::string filePath = \"..\/..\/media\/mitsuba\/staircase2\/scene.xml\";\n#else\n\tpfd::message(\"Choose file to load\", \"Choose mitsuba XML file to load or ZIP containing an XML. \\nIf you cancel or choosen file fails to load bathroom will be loaded.\", pfd::choice::ok);\n\tpfd::open_file file(\"Choose XML file\", \"\", { \"XML files (.xml)\", \"*.xml\" });\n\tstd::string filePath = file.result().empty() ? \"C:\\\\IrrlichtBAW\\\\\/IrrlichtBAW\\\\examples_tests\\\\media\\\\mitsuba\\\\bathroom\\\\sce===\n\t\tnetest.xml\" : file.result()[0];\n#endif\n\tasset::SAssetBundle meshes = am->getAsset(filePath, {});\n\n\tfor (int i = 0; i < meshes.getSize(); i++)\n\t{\n\t\tasset::ICPUMesh* cpumesh = static_cast<asset::ICPUMesh*>((meshes.getContents().first + i)->get());\n\t\tvideo::IGPUMesh* gpumesh = driver->getGPUObjectsFromAssets(&cpumesh, (&cpumesh) + 1)[0];\n\t\tsmgr->addMeshSceneNode(gpumesh)->setMaterialType(newMaterialType);\n\t\tgpumesh->drop();\n\t}\n\n\twhile (!quit && device->run())\n\t{\n\t\tdriver->beginScene(true, true, video::SColor(255, 0, 0, 255));\n\n\t\t\/\/! This animates (moves) the camera and sets the transforms\n\t\t\/\/! Also draws the meshbuffer\n\t\tsmgr->drawAll();\n\n\t\tdriver->endScene();\n\t}\n\n\tdevice->drop();\n\treturn 0;\n}\n<commit_msg>small stuff (change PCs)<commit_after>#define _IRR_STATIC_LIB_\n#include <irrlicht.h>\n\n#include \"..\/3rdparty\/portable-file-dialogs\/portable-file-dialogs.h\"\n#include \"..\/..\/ext\/MitsubaLoader\/CMitsubaLoader.h\"\n\nusing namespace irr;\nusing namespace core;\n\nbool quit = false;\nclass MyEventReceiver : public IEventReceiver\n{\npublic:\n\n\tMyEventReceiver()\n\t{\n\t}\n\n\tbool OnEvent(const SEvent& event)\n\t{\n\t\tif (event.EventType == irr::EET_KEY_INPUT_EVENT && !event.KeyInput.PressedDown)\n\t\t{\n\t\t\tswitch (event.KeyInput.Key)\n\t\t\t{\n\t\t\tcase irr::KEY_ESCAPE:\n\t\t\tcase irr::KEY_KEY_Q:\n\t\t\t\tquit = true;\n\t\t\t\treturn true;\n\t\t\tdefault:\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\treturn false;\n\t}\n\nprivate:\n};\n\nclass SimpleCallBack : public video::IShaderConstantSetCallBack\n{\n\tint32_t mvpUniformLocation;\n\tint32_t cameraDirUniformLocation;\n\tint32_t texUniformLocation[4];\n\tvideo::E_SHADER_CONSTANT_TYPE mvpUniformType;\n\tvideo::E_SHADER_CONSTANT_TYPE cameraDirUniformType;\n\tvideo::E_SHADER_CONSTANT_TYPE texUniformType[4];\npublic:\n\tSimpleCallBack() : cameraDirUniformLocation(-1), cameraDirUniformType(video::ESCT_FLOAT_VEC3) {}\n\n\tvirtual void PostLink(video::IMaterialRendererServices* services, const video::E_MATERIAL_TYPE& materialType, const core::vector<video::SConstantLocationNamePair>& constants)\n\t{\n\t\tfor (size_t i = 0; i < constants.size(); i++)\n\t\t{\n\t\t\tif (constants[i].name == \"MVP\")\n\t\t\t{\n\t\t\t\tmvpUniformLocation = constants[i].location;\n\t\t\t\tmvpUniformType = constants[i].type;\n\t\t\t}\n\t\t\telse if (constants[i].name == \"cameraPos\")\n\t\t\t{\n\t\t\t\tcameraDirUniformLocation = constants[i].location;\n\t\t\t\tcameraDirUniformType = constants[i].type;\n\t\t\t}\n\t\t}\n\t}\n\n\tvirtual void OnSetConstants(video::IMaterialRendererServices* services, int32_t userData)\n\t{\n\t\tcore::vectorSIMDf modelSpaceCamPos;\n\t\tmodelSpaceCamPos.set(services->getVideoDriver()->getTransform(video::E4X3TS_WORLD_VIEW_INVERSE).getTranslation());\n\t\tservices->setShaderConstant(&modelSpaceCamPos, cameraDirUniformLocation, cameraDirUniformType, 1);\n\t\tservices->setShaderConstant(services->getVideoDriver()->getTransform(video::EPTS_PROJ_VIEW_WORLD).pointer(), mvpUniformLocation, mvpUniformType, 1);\n\t}\n\n\tvirtual void OnUnsetMaterial() {}\n};\n\nint main()\n{\n\tsrand(time(0));\n\t\/\/ create device with full flexibility over creation parameters\n\t\/\/ you can add more parameters if desired, check irr::SIrrlichtCreationParameters\n\tirr::SIrrlichtCreationParameters params;\n\tparams.Bits = 24; \/\/may have to set to 32bit for some platforms\n\tparams.ZBufferBits = 24; \/\/we'd like 32bit here\n\tparams.DriverType = video::EDT_OPENGL; \/\/! Only Well functioning driver, software renderer left for sake of 2D image drawing\n\tparams.WindowSize = dimension2d<uint32_t>(800, 600);\n\tparams.Fullscreen = false;\n\tparams.Vsync = true; \/\/! If supported by target platform\n\tparams.Doublebuffer = true;\n\tparams.Stencilbuffer = false; \/\/! This will not even be a choice soon\n\tIrrlichtDevice* device = createDeviceEx(params);\n\t\n\tvideo::IVideoDriver* driver = device->getVideoDriver();\n\n\tscene::ISceneManager* smgr = device->getSceneManager();\n\tdriver->setTextureCreationFlag(video::ETCF_ALWAYS_32_BIT, true);\n\tscene::ICameraSceneNode* camera =\n\t\tsmgr->addCameraSceneNodeFPS(0, 100.0f, 0.01f);\n\tcamera->setPosition(core::vector3df(0, 0, 3));\n\tcamera->setTarget(core::vector3df(0, 0, 0));\n\tcamera->setNearValue(0.01f);\n\tcamera->setFarValue(10000.0f);\n\tsmgr->setActiveCamera(camera);\n\tdevice->getCursorControl()->setVisible(false);\n\tMyEventReceiver receiver;\n\tdevice->setEventReceiver(&receiver);\n\n\tSimpleCallBack* cb = new SimpleCallBack();\n\tvideo::E_MATERIAL_TYPE newMaterialType = (video::E_MATERIAL_TYPE)driver->getGPUProgrammingServices()->addHighLevelShaderMaterialFromFiles(\"..\/mesh.vert\",\n\t\t\"\", \"\", \"\", \/\/! No Geometry or Tessellation Shaders\n\t\t\"..\/mesh.frag\",\n\t\t3, video::EMT_SOLID, \/\/! 3 vertices per primitive (this is tessellation shader relevant only\n\t\tcb, \/\/! Our Shader Callback\n\t\t0); \/\/! No custom user data\n\tcb->drop();\n\n\tif (device == 0)\n\t\treturn 1; \/\/ could not create selected driver.\n\n\tio::IFileSystem* fs = device->getFileSystem();\n\tasset::IAssetManager* am = device->getAssetManager();\n\n\tam.addAssetLoader(core::make_smart_refctd_ptr<irr::ext::MitsubaLoader::CMitsubaLoader>(device));\n\n#define MITSUBA_LOADER_TESTS\n\n#ifdef MITSUBA_LOADER_TESTS\n\tstd::string filePath = \"..\/..\/media\/mitsuba\/staircase2\/scene.xml\";\n#else\n\tpfd::message(\"Choose file to load\", \"Choose mitsuba XML file to load or ZIP containing an XML. \\nIf you cancel or choosen file fails to load bathroom will be loaded.\", pfd::choice::ok);\n\tpfd::open_file file(\"Choose XML file\", \"\", { \"XML files (.xml)\", \"*.xml\" });\n\tstd::string filePath = file.result().empty() ? \"C:\\\\IrrlichtBAW\\\\\/IrrlichtBAW\\\\examples_tests\\\\media\\\\mitsuba\\\\bathroom\\\\sce===\n\t\tnetest.xml\" : file.result()[0];\n#endif\n\tasset::SAssetBundle meshes = am->getAsset(filePath, {});\n\n\tdriver->getGPUObjectsFromAssets(meshes.getContents().first, meshes.getContents().second);\n\tfor (int i = 0; i < meshes.getSize(); i++)\n\t{\n\t\tmeshes.getContents().first\n\t\tasset::ICPUMesh* cpumesh = static_cast<asset::ICPUMesh*>((meshes.getContents().first + i)->get());\n\t\tvideo::IGPUMesh* gpumesh = driver->getGPUObjectsFromAssets(&cpumesh, (&cpumesh) + 1)[0];\n\t\tsmgr->addMeshSceneNode(gpumesh)->setMaterialType(newMaterialType);\n\t\tgpumesh->drop();\n\t}\n\n\twhile (!quit && device->run())\n\t{\n\t\tdriver->beginScene(true, true, video::SColor(255, 0, 0, 255));\n\n\t\t\/\/! This animates (moves) the camera and sets the transforms\n\t\t\/\/! Also draws the meshbuffer\n\t\tsmgr->drawAll();\n\n\t\tdriver->endScene();\n\t}\n\n\tdevice->drop();\n\treturn 0;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"stdafx.h\"\n#include <unittest.h>\n#include <matrix.h>\n\nvoid test_matrices() {\n\n\tscenario sc(\"Matrices Test\");\n\n\tsc.pass();\n}<commit_msg>[minor] Compiled which functions to test<commit_after>#include \"stdafx.h\"\n#include <unittest.h>\n#include <matrix.h>\n\nvoid test_matrices() {\n\n\tscenario sc(\"Matrices Test\");\n\/*\n\tFunctions to test:\n\ttranspose\n\tsum\n\tsubtract\n\tmultiply\n\trandom\n\t+\n\t-\n\t*\n\t\/\n\t*\/\n\tsc.pass();\n}<|endoftext|>"} {"text":"<commit_before>#define DEBUG 1\n\/**\n * File : B2.cpp\n * Author : Kazune Takahashi\n * Created : 7\/22\/2019, 3:04:34 AM\n * Powered by Visual Studio Code\n *\/\n#include <iostream>\n#include <iomanip>\n#include <algorithm>\n#include <vector>\n#include <string>\n#include <complex>\n#include <tuple>\n#include <queue>\n#include <stack>\n#include <map>\n#include <set>\n#include <unordered_map>\n#include <unordered_set>\n#include <bitset>\n#include <functional>\n#include <random>\n#include <chrono>\n#include <cctype>\n#include <cassert>\n#include <cmath>\n#include <cstdio>\n#include <cstdlib>\nusing namespace std;\n#define maxs(x, y) (x = max(x, y))\n#define mins(x, y) (x = min(x, y))\nusing ll = long long;\nclass mint\n{\npublic:\n static ll MOD;\n ll x;\n mint() : x(0) {}\n mint(ll x) : x(x % MOD) {}\n mint operator-() const { return x ? MOD - x : 0; }\n mint &operator+=(const mint &a)\n {\n if ((x += a.x) >= MOD)\n {\n x -= MOD;\n }\n return *this;\n }\n mint &operator-=(const mint &a) { return *this += -a; }\n mint &operator*=(const mint &a)\n {\n (x *= a.x) %= MOD;\n return *this;\n }\n mint &operator\/=(const mint &a)\n {\n mint b{a};\n return *this *= b.power(MOD - 2);\n }\n mint operator+(const mint &a) const { return mint(*this) += a; }\n mint operator-(const mint &a) const { return mint(*this) -= a; }\n mint operator*(const mint &a) const { return mint(*this) *= a; }\n mint operator\/(const mint &a) const { return mint(*this) \/= a; }\n bool operator<(const mint &a) const { return x < a.x; }\n bool operator==(const mint &a) const { return x == a.x; }\n const mint power(ll N)\n {\n if (N == 0)\n {\n return 1;\n }\n else if (N % 2 == 1)\n {\n return *this * power(N - 1);\n }\n else\n {\n mint half = power(N \/ 2);\n return half * half;\n }\n }\n};\nll mint::MOD = 1e9 + 7;\nistream &operator>>(istream &stream, mint &a) { return stream >> a.x; }\nostream &operator<<(ostream &stream, const mint &a) { return stream << a.x; }\nclass combination\n{\npublic:\n vector<mint> inv, fact, factinv;\n static int MAX_SIZE;\n combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE)\n {\n inv[1] = 1;\n for (auto i = 2; i < MAX_SIZE; i++)\n {\n inv[i] = (-inv[mint::MOD % i]) * (mint::MOD \/ i);\n }\n fact[0] = factinv[0] = 1;\n for (auto i = 1; i < MAX_SIZE; i++)\n {\n fact[i] = mint(i) * fact[i - 1];\n factinv[i] = inv[i] * factinv[i - 1];\n }\n }\n mint operator()(int n, int k)\n {\n if (n >= 0 && k >= 0 && n - k >= 0)\n {\n return fact[n] * factinv[k] * factinv[n - k];\n }\n return 0;\n }\n};\nint combination::MAX_SIZE = 3000010;\nll gcd(ll x, ll y) { return y ? gcd(y, x % y) : x; }\n\/\/ constexpr double epsilon = 1e-10;\n\/\/ constexpr ll infty = 1000000000000000LL;\n\/\/ constexpr int dx[4] = {1, 0, -1, 0};\n\/\/ constexpr int dy[4] = {0, 1, 0, -1};\nvoid Yes()\n{\n cout << \"Yes\" << endl;\n exit(0);\n}\nvoid No()\n{\n cout << \"No\" << endl;\n exit(0);\n}\n\nll N, K;\nll C;\nint A[200010];\nll a[60][200010];\n\nint main()\n{\n cin >> N >> K;\n C = N * K;\n for (auto i = 0; i < N; i++)\n {\n cin >> A[i];\n }\n for (auto i = 0; i < N; i++)\n {\n a[i][0] = -1;\n }\n vector<int> used(200010, -1);\n for (auto k = 0; k < 2; k++)\n {\n for (auto i = 0; i < N; i++)\n {\n if (used[A[i]] != -1)\n {\n a[0][used[A[i]]] = k * N + i - used[A[i]];\n }\n used[A[i]] = k * N + i;\n }\n }\n#if DEBUG == 1\n for (auto i = 0; i < N; i++)\n {\n cerr << \"a[0][\" << i << \"] = \" << a[0][i] << endl;\n }\n#endif\n for (auto k = 1; k < 60; k++)\n {\n for (auto i = 0; i < N; i++)\n {\n a[k][i] = a[k - 1][i] + a[k - 1][(a[k - 1][i] + 1) % N];\n#if DEBUG == 1\n if (k < 5)\n {\n cerr << \"a[\" << k << \"][\" << i << \"] = \" << a[k][i] << endl;\n }\n#endif\n }\n }\n ll sum = 0;\n int now = 0;\n while (true)\n {\n int ind = 0;\n for (auto k = 0; k < 60; k++)\n {\n if (a[k][now] + sum > C)\n {\n ind = k - 1;\n break;\n }\n }\n if (ind == -1)\n {\n break;\n }\n sum += a[ind][now];\n now = (sum + 1) % N;\n }\n#if DEBUG == 1\n cerr << \"sum = \" << sum << endl;\n cerr << \"now = \" << now << endl;\n#endif\n deque<int> D;\n vector<bool> stacked(200010, false);\n for (auto i = now; i < N; i++)\n {\n if (!stacked[A[i]])\n {\n D.push_back(A[i]);\n stacked[A[i]] = true;\n }\n else\n {\n while (true)\n {\n int x = *D.rbegin();\n D.pop_back();\n stacked[x] = false;\n if (x == A[i])\n {\n break;\n }\n }\n }\n }\n for (auto i = 0u; i < D.size(); i++)\n {\n cout << D[i];\n if (i < D.size() - 1)\n {\n cout << \" \";\n }\n }\n cout << endl;\n}<commit_msg>tried B2.cpp to 'B'<commit_after>#define DEBUG 1\n\/**\n * File : B2.cpp\n * Author : Kazune Takahashi\n * Created : 7\/22\/2019, 3:04:34 AM\n * Powered by Visual Studio Code\n *\/\n#include <iostream>\n#include <iomanip>\n#include <algorithm>\n#include <vector>\n#include <string>\n#include <complex>\n#include <tuple>\n#include <queue>\n#include <stack>\n#include <map>\n#include <set>\n#include <unordered_map>\n#include <unordered_set>\n#include <bitset>\n#include <functional>\n#include <random>\n#include <chrono>\n#include <cctype>\n#include <cassert>\n#include <cmath>\n#include <cstdio>\n#include <cstdlib>\nusing namespace std;\n#define maxs(x, y) (x = max(x, y))\n#define mins(x, y) (x = min(x, y))\nusing ll = long long;\nclass mint\n{\npublic:\n static ll MOD;\n ll x;\n mint() : x(0) {}\n mint(ll x) : x(x % MOD) {}\n mint operator-() const { return x ? MOD - x : 0; }\n mint &operator+=(const mint &a)\n {\n if ((x += a.x) >= MOD)\n {\n x -= MOD;\n }\n return *this;\n }\n mint &operator-=(const mint &a) { return *this += -a; }\n mint &operator*=(const mint &a)\n {\n (x *= a.x) %= MOD;\n return *this;\n }\n mint &operator\/=(const mint &a)\n {\n mint b{a};\n return *this *= b.power(MOD - 2);\n }\n mint operator+(const mint &a) const { return mint(*this) += a; }\n mint operator-(const mint &a) const { return mint(*this) -= a; }\n mint operator*(const mint &a) const { return mint(*this) *= a; }\n mint operator\/(const mint &a) const { return mint(*this) \/= a; }\n bool operator<(const mint &a) const { return x < a.x; }\n bool operator==(const mint &a) const { return x == a.x; }\n const mint power(ll N)\n {\n if (N == 0)\n {\n return 1;\n }\n else if (N % 2 == 1)\n {\n return *this * power(N - 1);\n }\n else\n {\n mint half = power(N \/ 2);\n return half * half;\n }\n }\n};\nll mint::MOD = 1e9 + 7;\nistream &operator>>(istream &stream, mint &a) { return stream >> a.x; }\nostream &operator<<(ostream &stream, const mint &a) { return stream << a.x; }\nclass combination\n{\npublic:\n vector<mint> inv, fact, factinv;\n static int MAX_SIZE;\n combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE)\n {\n inv[1] = 1;\n for (auto i = 2; i < MAX_SIZE; i++)\n {\n inv[i] = (-inv[mint::MOD % i]) * (mint::MOD \/ i);\n }\n fact[0] = factinv[0] = 1;\n for (auto i = 1; i < MAX_SIZE; i++)\n {\n fact[i] = mint(i) * fact[i - 1];\n factinv[i] = inv[i] * factinv[i - 1];\n }\n }\n mint operator()(int n, int k)\n {\n if (n >= 0 && k >= 0 && n - k >= 0)\n {\n return fact[n] * factinv[k] * factinv[n - k];\n }\n return 0;\n }\n};\nint combination::MAX_SIZE = 3000010;\nll gcd(ll x, ll y) { return y ? gcd(y, x % y) : x; }\n\/\/ constexpr double epsilon = 1e-10;\n\/\/ constexpr ll infty = 1000000000000000LL;\n\/\/ constexpr int dx[4] = {1, 0, -1, 0};\n\/\/ constexpr int dy[4] = {0, 1, 0, -1};\nvoid Yes()\n{\n cout << \"Yes\" << endl;\n exit(0);\n}\nvoid No()\n{\n cout << \"No\" << endl;\n exit(0);\n}\n\nll N, K;\nll C;\nint A[200010];\nll a[60][200010];\n\nint main()\n{\n cin >> N >> K;\n C = N * K;\n for (auto i = 0; i < N; i++)\n {\n cin >> A[i];\n }\n for (auto i = 0; i < N; i++)\n {\n a[i][0] = -1;\n }\n vector<int> used(200010, -1);\n for (auto k = 0; k < 2; k++)\n {\n for (auto i = 0; i < N; i++)\n {\n if (used[A[i]] != -1)\n {\n a[0][used[A[i]]] = k * N + i - used[A[i]];\n }\n used[A[i]] = k * N + i;\n }\n }\n#if DEBUG == 1\n for (auto i = 0; i < N; i++)\n {\n cerr << \"a[0][\" << i << \"] = \" << a[0][i] << endl;\n }\n#endif\n for (auto k = 1; k < 60; k++)\n {\n for (auto i = 0; i < N; i++)\n {\n a[k][i] = a[k - 1][i] + a[k - 1][(a[k - 1][i] + 1) % N] + 1;\n#if DEBUG == 1\n if (k < 5)\n {\n cerr << \"a[\" << k << \"][\" << i << \"] = \" << a[k][i] << endl;\n }\n#endif\n }\n }\n ll sum = 0;\n int now = 0;\n while (true)\n {\n int ind = 0;\n for (auto k = 0; k < 60; k++)\n {\n if (a[k][now] + sum > C)\n {\n ind = k - 1;\n break;\n }\n }\n if (ind == -1)\n {\n break;\n }\n sum += a[ind][now];\n now = (sum + 1) % N;\n }\n#if DEBUG == 1\n cerr << \"sum = \" << sum << endl;\n cerr << \"now = \" << now << endl;\n#endif\n deque<int> D;\n vector<bool> stacked(200010, false);\n for (auto i = now; i < N; i++)\n {\n if (!stacked[A[i]])\n {\n D.push_back(A[i]);\n stacked[A[i]] = true;\n }\n else\n {\n while (true)\n {\n int x = *D.rbegin();\n D.pop_back();\n stacked[x] = false;\n if (x == A[i])\n {\n break;\n }\n }\n }\n }\n for (auto i = 0u; i < D.size(); i++)\n {\n cout << D[i];\n if (i < D.size() - 1)\n {\n cout << \" \";\n }\n }\n cout << endl;\n}<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 2014 Samsung Electronics Co., Ltd.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *\/\n\n\/\/ CLASS HEADER\n#include \"native-image-source-impl.h\"\n\n\/\/ EXTERNAL INCLUDES\n#include <dali\/integration-api\/debug.h>\n#include <dali\/integration-api\/gl-defines.h>\n#include <cstring>\n\n\/\/ INTERNAL INCLUDES\n#include <gl\/egl-image-extensions.h>\n#include <gl\/egl-factory.h>\n#include <adaptor-impl.h>\n#include <render-surface.h>\n\n\/\/ Allow this to be encoded and saved:\n#include <platform-abstractions\/tizen\/resource-loader\/resource-loader.h>\n#include <bitmap-saver.h>\n\nnamespace Dali\n{\n\nnamespace Internal\n{\n\nnamespace Adaptor\n{\n\nnamespace\n{\nconst char* FRAGMENT_PREFIX = \"#extension GL_OES_EGL_image_external:require\\n\";\nconst char* SAMPLER_TYPE = \"samplerExternalOES\";\n\ntbm_format FORMATS_BLENDING_REQUIRED[] = {\n TBM_FORMAT_ARGB4444, TBM_FORMAT_ABGR4444,\n TBM_FORMAT_RGBA4444, TBM_FORMAT_BGRA4444,\n TBM_FORMAT_RGBX5551, TBM_FORMAT_BGRX5551,\n TBM_FORMAT_ARGB1555, TBM_FORMAT_ABGR1555,\n TBM_FORMAT_RGBA5551, TBM_FORMAT_BGRA5551,\n TBM_FORMAT_ARGB8888, TBM_FORMAT_ABGR8888,\n TBM_FORMAT_RGBA8888, TBM_FORMAT_BGRA8888,\n TBM_FORMAT_ARGB2101010, TBM_FORMAT_ABGR2101010,\n TBM_FORMAT_RGBA1010102, TBM_FORMAT_BGRA1010102\n};\n\nconst int NUM_FORMATS_BLENDING_REQUIRED = 18;\n\n}\n\nusing Dali::Integration::PixelBuffer;\n\nNativeImageSource* NativeImageSource::New(unsigned int width, unsigned int height, Dali::NativeImageSource::ColorDepth depth, Any nativeImageSource )\n{\n NativeImageSource* image = new NativeImageSource( width, height, depth, nativeImageSource );\n DALI_ASSERT_DEBUG( image && \"NativeImageSource allocation failed.\" );\n\n if( image )\n {\n image->Initialize();\n }\n\n return image;\n}\n\nNativeImageSource::NativeImageSource( unsigned int width, unsigned int height, Dali::NativeImageSource::ColorDepth depth, Any nativeImageSource )\n: mWidth( width ),\n mHeight( height ),\n mOwnTbmSurface( false ),\n mTbmSurface( NULL ),\n mTbmFormat( 0 ),\n mBlendingRequired( false ),\n mColorDepth( depth ),\n mEglImageKHR( NULL ),\n mEglImageExtensions( NULL ),\n mSetSource( false )\n{\n DALI_ASSERT_ALWAYS( Adaptor::IsAvailable() );\n EglFactory& eglFactory = Adaptor::GetImplementation( Adaptor::Get() ).GetEGLFactory();\n mEglImageExtensions = eglFactory.GetImageExtensions();\n DALI_ASSERT_DEBUG( mEglImageExtensions );\n\n mTbmSurface = GetSurfaceFromAny( nativeImageSource );\n\n if( mTbmSurface != NULL )\n {\n mBlendingRequired = CheckBlending( tbm_surface_get_format( mTbmSurface ) );\n mWidth = tbm_surface_get_width( mTbmSurface );\n mHeight = tbm_surface_get_height( mTbmSurface );\n }\n}\n\nvoid NativeImageSource::Initialize()\n{\n if( mTbmSurface != NULL || mWidth == 0 || mHeight == 0 )\n {\n return;\n }\n\n tbm_format format = TBM_FORMAT_RGB888;\n int depth = 0;\n\n switch( mColorDepth )\n {\n case Dali::NativeImageSource::COLOR_DEPTH_DEFAULT:\n {\n format = TBM_FORMAT_RGBA8888;\n depth = 32;\n break;\n }\n case Dali::NativeImageSource::COLOR_DEPTH_8:\n {\n format = TBM_FORMAT_C8;\n depth = 8;\n break;\n }\n case Dali::NativeImageSource::COLOR_DEPTH_16:\n {\n format = TBM_FORMAT_RGB565;\n depth = 16;\n break;\n }\n case Dali::NativeImageSource::COLOR_DEPTH_24:\n {\n format = TBM_FORMAT_RGB888;\n depth = 24;\n break;\n }\n case Dali::NativeImageSource::COLOR_DEPTH_32:\n {\n format = TBM_FORMAT_RGBA8888;\n depth = 32;\n break;\n }\n default:\n {\n DALI_LOG_WARNING( \"Wrong color depth.\\n\" );\n return;\n }\n }\n\n \/\/ set whether blending is required according to pixel format based on the depth\n \/* default pixel format is RGB888\n If depth = 8, Pixel::A8;\n If depth = 16, Pixel::RGB565;\n If depth = 32, Pixel::RGBA8888 *\/\n mBlendingRequired = ( depth == 32 || depth == 8 );\n\n mTbmSurface = tbm_surface_create( mWidth, mHeight, format );\n mOwnTbmSurface = true;\n}\n\ntbm_surface_h NativeImageSource::GetSurfaceFromAny( Any source ) const\n{\n if( source.Empty() )\n {\n return NULL;\n }\n\n if( source.GetType() == typeid( tbm_surface_h ) )\n {\n return AnyCast< tbm_surface_h >( source );\n }\n else\n {\n return NULL;\n }\n}\n\nNativeImageSource::~NativeImageSource()\n{\n if( mOwnTbmSurface && mTbmSurface != NULL )\n {\n if( tbm_surface_destroy( mTbmSurface ) != TBM_SURFACE_ERROR_NONE )\n {\n DALI_LOG_ERROR( \"Failed to destroy tbm_surface\\n\" );\n }\n }\n}\n\nAny NativeImageSource::GetNativeImageSource() const\n{\n return Any( mTbmSurface );\n}\n\nbool NativeImageSource::GetPixels(std::vector<unsigned char>& pixbuf, unsigned& width, unsigned& height, Pixel::Format& pixelFormat) const\n{\n if( mTbmSurface != NULL )\n {\n tbm_surface_info_s surface_info;\n\n if( tbm_surface_map( mTbmSurface, TBM_SURF_OPTION_READ, &surface_info) != TBM_SURFACE_ERROR_NONE )\n {\n DALI_LOG_ERROR( \"Fail to map tbm_surface\\n\" );\n\n width = 0;\n height = 0;\n\n return false;\n }\n\n tbm_format format = surface_info.format;\n uint32_t stride = surface_info.planes[0].stride;\n unsigned char* ptr = surface_info.planes[0].ptr;\n\n width = mWidth;\n height = mHeight;\n size_t lineSize;\n size_t offset;\n size_t cOffset;\n\n switch( format )\n {\n case TBM_FORMAT_RGB888:\n {\n lineSize = width*3;\n pixelFormat = Pixel::RGB888;\n pixbuf.resize( lineSize*height );\n unsigned char* bufptr = &pixbuf[0];\n\n for( unsigned int r = 0; r < height; ++r, bufptr += lineSize )\n {\n for( unsigned int c = 0; c < width; ++c )\n {\n cOffset = c*3;\n offset = cOffset + r*stride;\n *(bufptr) = ptr[offset+2];\n *(bufptr+cOffset+1) = ptr[offset+1];\n *(bufptr+cOffset+2) = ptr[offset];\n }\n }\n break;\n }\n case TBM_FORMAT_RGBA8888:\n {\n lineSize = width*4;\n pixelFormat = Pixel::RGBA8888;\n pixbuf.resize( lineSize*height );\n unsigned char* bufptr = &pixbuf[0];\n\n for( unsigned int r = 0; r < height; ++r, bufptr += lineSize )\n {\n for( unsigned int c = 0; c < width; ++c )\n {\n cOffset = c*4;\n offset = cOffset + r*stride;\n *(bufptr) = ptr[offset+3];\n *(bufptr+cOffset+1) = ptr[offset+2];\n *(bufptr+cOffset+2) = ptr[offset+1];\n *(bufptr+cOffset+3) = ptr[offset];\n }\n }\n break;\n }\n default:\n {\n DALI_LOG_WARNING( \"Tbm surface has unsupported pixel format.\\n\" );\n\n pixbuf.resize( 0 );\n width = 0;\n height = 0;\n\n return false;\n }\n }\n\n if( tbm_surface_unmap( mTbmSurface ) != TBM_SURFACE_ERROR_NONE )\n {\n DALI_LOG_ERROR( \"Fail to unmap tbm_surface\\n\" );\n }\n\n return true;\n }\n\n DALI_LOG_WARNING( \"TBM surface does not exist.\\n\" );\n\n width = 0;\n height = 0;\n\n return false;\n}\n\nbool NativeImageSource::EncodeToFile(const std::string& filename) const\n{\n std::vector< unsigned char > pixbuf;\n unsigned int width(0), height(0);\n Pixel::Format pixelFormat;\n\n if(GetPixels(pixbuf, width, height, pixelFormat))\n {\n return Dali::EncodeToFile(&pixbuf[0], filename, pixelFormat, width, height);\n }\n return false;\n}\n\nvoid NativeImageSource::SetSource( Any source )\n{\n if( mOwnTbmSurface && mTbmSurface != NULL )\n {\n if( tbm_surface_destroy( mTbmSurface ) != TBM_SURFACE_ERROR_NONE )\n {\n DALI_LOG_ERROR( \"Failed to destroy tbm_surface\\n\" );\n }\n\n mTbmSurface = NULL;\n mOwnTbmSurface = false;\n }\n\n mTbmSurface = GetSurfaceFromAny( source );\n mSetSource = true;\n\n if( mTbmSurface != NULL )\n {\n mBlendingRequired = CheckBlending( tbm_surface_get_format( mTbmSurface ) );\n mWidth = tbm_surface_get_width( mTbmSurface );\n mHeight = tbm_surface_get_height( mTbmSurface );\n }\n}\n\nbool NativeImageSource::IsColorDepthSupported( Dali::NativeImageSource::ColorDepth colorDepth )\n{\n uint32_t* formats;\n uint32_t formatNum;\n tbm_format format = TBM_FORMAT_RGB888;\n\n switch( colorDepth )\n {\n case Dali::NativeImageSource::COLOR_DEPTH_DEFAULT:\n {\n format = TBM_FORMAT_RGBA8888;\n break;\n }\n case Dali::NativeImageSource::COLOR_DEPTH_8:\n {\n format = TBM_FORMAT_C8;\n break;\n }\n case Dali::NativeImageSource::COLOR_DEPTH_16:\n {\n format = TBM_FORMAT_RGB565;\n break;\n }\n case Dali::NativeImageSource::COLOR_DEPTH_24:\n {\n format = TBM_FORMAT_RGB888;\n break;\n }\n case Dali::NativeImageSource::COLOR_DEPTH_32:\n {\n format = TBM_FORMAT_RGBA8888;\n break;\n }\n }\n\n if( tbm_surface_query_formats( &formats, &formatNum ) )\n {\n for( unsigned int i = 0; i < formatNum; i++ )\n {\n if( formats[i] == format )\n {\n free( formats );\n return true;\n }\n }\n }\n\n free( formats );\n return false;\n}\n\nbool NativeImageSource::GlExtensionCreate()\n{\n \/\/ casting from an unsigned int to a void *, which should then be cast back\n \/\/ to an unsigned int in the driver.\n EGLClientBuffer eglBuffer = reinterpret_cast< EGLClientBuffer >(mTbmSurface);\n if( !eglBuffer )\n {\n return false;\n }\n\n mEglImageKHR = mEglImageExtensions->CreateImageKHR( eglBuffer );\n\n return mEglImageKHR != NULL;\n}\n\nvoid NativeImageSource::GlExtensionDestroy()\n{\n if( mEglImageKHR )\n {\n mEglImageExtensions->DestroyImageKHR(mEglImageKHR);\n\n mEglImageKHR = NULL;\n }\n}\n\nunsigned int NativeImageSource::TargetTexture()\n{\n mEglImageExtensions->TargetTextureKHR(mEglImageKHR);\n\n return 0;\n}\n\nvoid NativeImageSource::PrepareTexture()\n{\n if( mSetSource )\n {\n void* eglImage = mEglImageKHR;\n\n if( GlExtensionCreate() )\n {\n TargetTexture();\n }\n\n mEglImageExtensions->DestroyImageKHR( eglImage );\n\n mSetSource = false;\n }\n}\n\nint NativeImageSource::GetPixelDepth(Dali::NativeImageSource::ColorDepth depth) const\n{\n switch (depth)\n {\n case Dali::NativeImageSource::COLOR_DEPTH_DEFAULT:\n {\n \/\/ ToDo: Get the default screen depth\n return 32;\n }\n case Dali::NativeImageSource::COLOR_DEPTH_8:\n {\n return 8;\n }\n case Dali::NativeImageSource::COLOR_DEPTH_16:\n {\n return 16;\n }\n case Dali::NativeImageSource::COLOR_DEPTH_24:\n {\n return 24;\n }\n case Dali::NativeImageSource::COLOR_DEPTH_32:\n {\n return 32;\n }\n default:\n {\n DALI_ASSERT_DEBUG(0 && \"unknown color enum\");\n return 0;\n }\n }\n}\n\nconst char* NativeImageSource::GetCustomFragmentPreFix()\n{\n return FRAGMENT_PREFIX;\n}\n\nconst char* NativeImageSource::GetCustomSamplerTypename()\n{\n return SAMPLER_TYPE;\n}\n\nint NativeImageSource::GetEglImageTextureTarget()\n{\n return GL_TEXTURE_EXTERNAL_OES;\n}\n\nbool NativeImageSource::CheckBlending( tbm_format format )\n{\n if( mTbmFormat != format )\n {\n for(int i = 0; i < NUM_FORMATS_BLENDING_REQUIRED; ++i)\n {\n if( format == FORMATS_BLENDING_REQUIRED[i] )\n {\n mBlendingRequired = true;\n break;\n }\n }\n mTbmFormat = format;\n }\n\n return mBlendingRequired;\n}\n\n} \/\/ namespace Adaptor\n\n} \/\/ namespace internal\n\n} \/\/ namespace Dali\n<commit_msg>Added ref\/unref tbm_surface<commit_after>\/*\n * Copyright (c) 2014 Samsung Electronics Co., Ltd.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *\/\n\n\/\/ CLASS HEADER\n#include \"native-image-source-impl.h\"\n\n\/\/ EXTERNAL INCLUDES\n#include <dali\/integration-api\/debug.h>\n#include <dali\/integration-api\/gl-defines.h>\n#include <cstring>\n#include <tbm_surface_internal.h>\n\n\/\/ INTERNAL INCLUDES\n#include <gl\/egl-image-extensions.h>\n#include <gl\/egl-factory.h>\n#include <adaptor-impl.h>\n#include <render-surface.h>\n\n\/\/ Allow this to be encoded and saved:\n#include <platform-abstractions\/tizen\/resource-loader\/resource-loader.h>\n#include <bitmap-saver.h>\n\nnamespace Dali\n{\n\nnamespace Internal\n{\n\nnamespace Adaptor\n{\n\nnamespace\n{\nconst char* FRAGMENT_PREFIX = \"#extension GL_OES_EGL_image_external:require\\n\";\nconst char* SAMPLER_TYPE = \"samplerExternalOES\";\n\ntbm_format FORMATS_BLENDING_REQUIRED[] = {\n TBM_FORMAT_ARGB4444, TBM_FORMAT_ABGR4444,\n TBM_FORMAT_RGBA4444, TBM_FORMAT_BGRA4444,\n TBM_FORMAT_RGBX5551, TBM_FORMAT_BGRX5551,\n TBM_FORMAT_ARGB1555, TBM_FORMAT_ABGR1555,\n TBM_FORMAT_RGBA5551, TBM_FORMAT_BGRA5551,\n TBM_FORMAT_ARGB8888, TBM_FORMAT_ABGR8888,\n TBM_FORMAT_RGBA8888, TBM_FORMAT_BGRA8888,\n TBM_FORMAT_ARGB2101010, TBM_FORMAT_ABGR2101010,\n TBM_FORMAT_RGBA1010102, TBM_FORMAT_BGRA1010102\n};\n\nconst int NUM_FORMATS_BLENDING_REQUIRED = 18;\n\n}\n\nusing Dali::Integration::PixelBuffer;\n\nNativeImageSource* NativeImageSource::New(unsigned int width, unsigned int height, Dali::NativeImageSource::ColorDepth depth, Any nativeImageSource )\n{\n NativeImageSource* image = new NativeImageSource( width, height, depth, nativeImageSource );\n DALI_ASSERT_DEBUG( image && \"NativeImageSource allocation failed.\" );\n\n if( image )\n {\n image->Initialize();\n }\n\n return image;\n}\n\nNativeImageSource::NativeImageSource( unsigned int width, unsigned int height, Dali::NativeImageSource::ColorDepth depth, Any nativeImageSource )\n: mWidth( width ),\n mHeight( height ),\n mOwnTbmSurface( false ),\n mTbmSurface( NULL ),\n mTbmFormat( 0 ),\n mBlendingRequired( false ),\n mColorDepth( depth ),\n mEglImageKHR( NULL ),\n mEglImageExtensions( NULL ),\n mSetSource( false )\n{\n DALI_ASSERT_ALWAYS( Adaptor::IsAvailable() );\n EglFactory& eglFactory = Adaptor::GetImplementation( Adaptor::Get() ).GetEGLFactory();\n mEglImageExtensions = eglFactory.GetImageExtensions();\n DALI_ASSERT_DEBUG( mEglImageExtensions );\n\n mTbmSurface = GetSurfaceFromAny( nativeImageSource );\n\n if( mTbmSurface != NULL )\n {\n tbm_surface_internal_ref( mTbmSurface );\n mBlendingRequired = CheckBlending( tbm_surface_get_format( mTbmSurface ) );\n mWidth = tbm_surface_get_width( mTbmSurface );\n mHeight = tbm_surface_get_height( mTbmSurface );\n }\n}\n\nvoid NativeImageSource::Initialize()\n{\n if( mTbmSurface != NULL || mWidth == 0 || mHeight == 0 )\n {\n return;\n }\n\n tbm_format format = TBM_FORMAT_RGB888;\n int depth = 0;\n\n switch( mColorDepth )\n {\n case Dali::NativeImageSource::COLOR_DEPTH_DEFAULT:\n {\n format = TBM_FORMAT_RGBA8888;\n depth = 32;\n break;\n }\n case Dali::NativeImageSource::COLOR_DEPTH_8:\n {\n format = TBM_FORMAT_C8;\n depth = 8;\n break;\n }\n case Dali::NativeImageSource::COLOR_DEPTH_16:\n {\n format = TBM_FORMAT_RGB565;\n depth = 16;\n break;\n }\n case Dali::NativeImageSource::COLOR_DEPTH_24:\n {\n format = TBM_FORMAT_RGB888;\n depth = 24;\n break;\n }\n case Dali::NativeImageSource::COLOR_DEPTH_32:\n {\n format = TBM_FORMAT_RGBA8888;\n depth = 32;\n break;\n }\n default:\n {\n DALI_LOG_WARNING( \"Wrong color depth.\\n\" );\n return;\n }\n }\n\n \/\/ set whether blending is required according to pixel format based on the depth\n \/* default pixel format is RGB888\n If depth = 8, Pixel::A8;\n If depth = 16, Pixel::RGB565;\n If depth = 32, Pixel::RGBA8888 *\/\n mBlendingRequired = ( depth == 32 || depth == 8 );\n\n mTbmSurface = tbm_surface_create( mWidth, mHeight, format );\n mOwnTbmSurface = true;\n}\n\ntbm_surface_h NativeImageSource::GetSurfaceFromAny( Any source ) const\n{\n if( source.Empty() )\n {\n return NULL;\n }\n\n if( source.GetType() == typeid( tbm_surface_h ) )\n {\n return AnyCast< tbm_surface_h >( source );\n }\n else\n {\n return NULL;\n }\n}\n\nNativeImageSource::~NativeImageSource()\n{\n if( mOwnTbmSurface )\n {\n if( mTbmSurface != NULL && tbm_surface_destroy( mTbmSurface ) != TBM_SURFACE_ERROR_NONE )\n {\n DALI_LOG_ERROR( \"Failed to destroy tbm_surface\\n\" );\n }\n }\n else\n {\n if( mTbmSurface != NULL )\n {\n tbm_surface_internal_unref( mTbmSurface );\n }\n }\n}\n\nAny NativeImageSource::GetNativeImageSource() const\n{\n return Any( mTbmSurface );\n}\n\nbool NativeImageSource::GetPixels(std::vector<unsigned char>& pixbuf, unsigned& width, unsigned& height, Pixel::Format& pixelFormat) const\n{\n if( mTbmSurface != NULL )\n {\n tbm_surface_info_s surface_info;\n\n if( tbm_surface_map( mTbmSurface, TBM_SURF_OPTION_READ, &surface_info) != TBM_SURFACE_ERROR_NONE )\n {\n DALI_LOG_ERROR( \"Fail to map tbm_surface\\n\" );\n\n width = 0;\n height = 0;\n\n return false;\n }\n\n tbm_format format = surface_info.format;\n uint32_t stride = surface_info.planes[0].stride;\n unsigned char* ptr = surface_info.planes[0].ptr;\n\n width = mWidth;\n height = mHeight;\n size_t lineSize;\n size_t offset;\n size_t cOffset;\n\n switch( format )\n {\n case TBM_FORMAT_RGB888:\n {\n lineSize = width*3;\n pixelFormat = Pixel::RGB888;\n pixbuf.resize( lineSize*height );\n unsigned char* bufptr = &pixbuf[0];\n\n for( unsigned int r = 0; r < height; ++r, bufptr += lineSize )\n {\n for( unsigned int c = 0; c < width; ++c )\n {\n cOffset = c*3;\n offset = cOffset + r*stride;\n *(bufptr) = ptr[offset+2];\n *(bufptr+cOffset+1) = ptr[offset+1];\n *(bufptr+cOffset+2) = ptr[offset];\n }\n }\n break;\n }\n case TBM_FORMAT_RGBA8888:\n {\n lineSize = width*4;\n pixelFormat = Pixel::RGBA8888;\n pixbuf.resize( lineSize*height );\n unsigned char* bufptr = &pixbuf[0];\n\n for( unsigned int r = 0; r < height; ++r, bufptr += lineSize )\n {\n for( unsigned int c = 0; c < width; ++c )\n {\n cOffset = c*4;\n offset = cOffset + r*stride;\n *(bufptr) = ptr[offset+3];\n *(bufptr+cOffset+1) = ptr[offset+2];\n *(bufptr+cOffset+2) = ptr[offset+1];\n *(bufptr+cOffset+3) = ptr[offset];\n }\n }\n break;\n }\n default:\n {\n DALI_LOG_WARNING( \"Tbm surface has unsupported pixel format.\\n\" );\n\n pixbuf.resize( 0 );\n width = 0;\n height = 0;\n\n return false;\n }\n }\n\n if( tbm_surface_unmap( mTbmSurface ) != TBM_SURFACE_ERROR_NONE )\n {\n DALI_LOG_ERROR( \"Fail to unmap tbm_surface\\n\" );\n }\n\n return true;\n }\n\n DALI_LOG_WARNING( \"TBM surface does not exist.\\n\" );\n\n width = 0;\n height = 0;\n\n return false;\n}\n\nbool NativeImageSource::EncodeToFile(const std::string& filename) const\n{\n std::vector< unsigned char > pixbuf;\n unsigned int width(0), height(0);\n Pixel::Format pixelFormat;\n\n if(GetPixels(pixbuf, width, height, pixelFormat))\n {\n return Dali::EncodeToFile(&pixbuf[0], filename, pixelFormat, width, height);\n }\n return false;\n}\n\nvoid NativeImageSource::SetSource( Any source )\n{\n if( mOwnTbmSurface )\n {\n if( mTbmSurface != NULL && tbm_surface_destroy( mTbmSurface ) != TBM_SURFACE_ERROR_NONE )\n {\n DALI_LOG_ERROR( \"Failed to destroy tbm_surface\\n\" );\n }\n\n mTbmSurface = NULL;\n mOwnTbmSurface = false;\n }\n else\n {\n if( mTbmSurface != NULL )\n {\n tbm_surface_internal_unref( mTbmSurface );\n mTbmSurface = NULL;\n }\n }\n\n mTbmSurface = GetSurfaceFromAny( source );\n\n if( mTbmSurface != NULL )\n {\n mSetSource = true;\n tbm_surface_internal_ref( mTbmSurface );\n mBlendingRequired = CheckBlending( tbm_surface_get_format( mTbmSurface ) );\n mWidth = tbm_surface_get_width( mTbmSurface );\n mHeight = tbm_surface_get_height( mTbmSurface );\n }\n}\n\nbool NativeImageSource::IsColorDepthSupported( Dali::NativeImageSource::ColorDepth colorDepth )\n{\n uint32_t* formats;\n uint32_t formatNum;\n tbm_format format = TBM_FORMAT_RGB888;\n\n switch( colorDepth )\n {\n case Dali::NativeImageSource::COLOR_DEPTH_DEFAULT:\n {\n format = TBM_FORMAT_RGBA8888;\n break;\n }\n case Dali::NativeImageSource::COLOR_DEPTH_8:\n {\n format = TBM_FORMAT_C8;\n break;\n }\n case Dali::NativeImageSource::COLOR_DEPTH_16:\n {\n format = TBM_FORMAT_RGB565;\n break;\n }\n case Dali::NativeImageSource::COLOR_DEPTH_24:\n {\n format = TBM_FORMAT_RGB888;\n break;\n }\n case Dali::NativeImageSource::COLOR_DEPTH_32:\n {\n format = TBM_FORMAT_RGBA8888;\n break;\n }\n }\n\n if( tbm_surface_query_formats( &formats, &formatNum ) )\n {\n for( unsigned int i = 0; i < formatNum; i++ )\n {\n if( formats[i] == format )\n {\n free( formats );\n return true;\n }\n }\n }\n\n free( formats );\n return false;\n}\n\nbool NativeImageSource::GlExtensionCreate()\n{\n \/\/ casting from an unsigned int to a void *, which should then be cast back\n \/\/ to an unsigned int in the driver.\n EGLClientBuffer eglBuffer = reinterpret_cast< EGLClientBuffer >(mTbmSurface);\n if( !eglBuffer )\n {\n return false;\n }\n\n mEglImageKHR = mEglImageExtensions->CreateImageKHR( eglBuffer );\n\n return mEglImageKHR != NULL;\n}\n\nvoid NativeImageSource::GlExtensionDestroy()\n{\n if( mEglImageKHR )\n {\n mEglImageExtensions->DestroyImageKHR(mEglImageKHR);\n\n mEglImageKHR = NULL;\n }\n}\n\nunsigned int NativeImageSource::TargetTexture()\n{\n mEglImageExtensions->TargetTextureKHR(mEglImageKHR);\n\n return 0;\n}\n\nvoid NativeImageSource::PrepareTexture()\n{\n if( mSetSource )\n {\n void* eglImage = mEglImageKHR;\n\n if( GlExtensionCreate() )\n {\n TargetTexture();\n }\n\n mEglImageExtensions->DestroyImageKHR( eglImage );\n\n mSetSource = false;\n }\n}\n\nint NativeImageSource::GetPixelDepth(Dali::NativeImageSource::ColorDepth depth) const\n{\n switch (depth)\n {\n case Dali::NativeImageSource::COLOR_DEPTH_DEFAULT:\n {\n \/\/ ToDo: Get the default screen depth\n return 32;\n }\n case Dali::NativeImageSource::COLOR_DEPTH_8:\n {\n return 8;\n }\n case Dali::NativeImageSource::COLOR_DEPTH_16:\n {\n return 16;\n }\n case Dali::NativeImageSource::COLOR_DEPTH_24:\n {\n return 24;\n }\n case Dali::NativeImageSource::COLOR_DEPTH_32:\n {\n return 32;\n }\n default:\n {\n DALI_ASSERT_DEBUG(0 && \"unknown color enum\");\n return 0;\n }\n }\n}\n\nconst char* NativeImageSource::GetCustomFragmentPreFix()\n{\n return FRAGMENT_PREFIX;\n}\n\nconst char* NativeImageSource::GetCustomSamplerTypename()\n{\n return SAMPLER_TYPE;\n}\n\nint NativeImageSource::GetEglImageTextureTarget()\n{\n return GL_TEXTURE_EXTERNAL_OES;\n}\n\nbool NativeImageSource::CheckBlending( tbm_format format )\n{\n if( mTbmFormat != format )\n {\n for(int i = 0; i < NUM_FORMATS_BLENDING_REQUIRED; ++i)\n {\n if( format == FORMATS_BLENDING_REQUIRED[i] )\n {\n mBlendingRequired = true;\n break;\n }\n }\n mTbmFormat = format;\n }\n\n return mBlendingRequired;\n}\n\n} \/\/ namespace Adaptor\n\n} \/\/ namespace internal\n\n} \/\/ namespace Dali\n<|endoftext|>"} {"text":"<commit_before>\/\/===- lib\/ReaderWriter\/ELF\/Reader.cpp ------------------------------------===\/\/\n\/\/\n\/\/ The LLVM Linker\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\/\n\/\/\/ \\file\n\/\/\/ \\brief Defines the ELF Reader and all helper sub classes to consume an ELF\n\/\/\/ file and produces atoms out of it.\n\/\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"lld\/ReaderWriter\/Reader.h\"\n\n#include \"Atoms.h\"\n#include \"CreateELF.h\"\n#include \"DynamicFile.h\"\n#include \"File.h\"\n\n#include \"lld\/Core\/Reference.h\"\n#include \"lld\/ReaderWriter\/ELFTargetInfo.h\"\n#include \"lld\/ReaderWriter\/ReaderArchive.h\"\n\n#include \"llvm\/ADT\/ArrayRef.h\"\n#include \"llvm\/ADT\/SmallString.h\"\n#include \"llvm\/ADT\/StringRef.h\"\n#include \"llvm\/Object\/ELF.h\"\n#include \"llvm\/Object\/ObjectFile.h\"\n#include \"llvm\/Support\/Allocator.h\"\n#include \"llvm\/Support\/Casting.h\"\n#include \"llvm\/Support\/ELF.h\"\n#include \"llvm\/Support\/Endian.h\"\n#include \"llvm\/Support\/ErrorHandling.h\"\n#include \"llvm\/Support\/ErrorOr.h\"\n#include \"llvm\/Support\/MathExtras.h\"\n#include \"llvm\/Support\/Memory.h\"\n#include \"llvm\/Support\/MemoryBuffer.h\"\n#include \"llvm\/Support\/Path.h\"\n#include \"llvm\/Support\/raw_ostream.h\"\n#include \"llvm\/Support\/system_error.h\"\n\n#include <map>\n#include <vector>\n\nusing llvm::support::endianness;\nusing namespace llvm::object;\n\nnamespace {\nstruct DynamicFileCreateELFTraits {\n typedef llvm::ErrorOr<std::unique_ptr<lld::SharedLibraryFile>> result_type;\n\n template <class ELFT>\n static result_type create(const lld::ELFTargetInfo &ti,\n std::unique_ptr<llvm::MemoryBuffer> mb) {\n return lld::elf::DynamicFile<ELFT>::create(ti, std::move(mb));\n }\n};\n\nstruct ELFFileCreateELFTraits {\n typedef std::unique_ptr<lld::File> result_type;\n\n template <class ELFT>\n static result_type create(const lld::ELFTargetInfo &ti,\n std::unique_ptr<llvm::MemoryBuffer> mb,\n lld::error_code &ec) {\n return std::unique_ptr<lld::File>(\n new lld::elf::ELFFile<ELFT>(ti, std::move(mb), ec));\n }\n};\n}\n\nnamespace lld {\nnamespace elf {\n\/\/\/ \\brief A reader object that will instantiate correct File by examining the\n\/\/\/ memory buffer for ELF class and bit width\nclass ELFReader : public Reader {\npublic:\n ELFReader(const ELFTargetInfo &ti)\n : lld::Reader(ti), _elfTargetInfo(ti), _readerArchive(ti, *this) {\n }\n\n error_code parseFile(std::unique_ptr<MemoryBuffer> &mb,\n std::vector<std::unique_ptr<File> > &result) const {\n using llvm::object::ELFType;\n llvm::sys::LLVMFileType fileType =\n llvm::sys::IdentifyFileType(mb->getBufferStart(),\n static_cast<unsigned>(mb->getBufferSize()));\n\n std::size_t MaxAlignment =\n 1ULL << llvm::countTrailingZeros(uintptr_t(mb->getBufferStart()));\n\n llvm::error_code ec;\n switch (fileType) {\n case llvm::sys::ELF_Relocatable_FileType: {\n std::unique_ptr<File> f(createELF<ELFFileCreateELFTraits>(\n getElfArchType(&*mb), MaxAlignment, _elfTargetInfo, std::move(mb),\n ec));\n if (ec)\n return ec;\n result.push_back(std::move(f));\n break;\n }\n case llvm::sys::ELF_SharedObject_FileType: {\n auto f = createELF<DynamicFileCreateELFTraits>(\n getElfArchType(&*mb), MaxAlignment, _elfTargetInfo, std::move(mb));\n if (!f)\n return f;\n result.push_back(std::move(*f));\n break;\n }\n case llvm::sys::Archive_FileType:\n ec = _readerArchive.parseFile(mb, result);\n break;\n default:\n return llvm::make_error_code(llvm::errc::executable_format_error);\n break;\n }\n\n if (ec)\n return ec;\n\n return error_code::success();\n }\n\nprivate:\n const ELFTargetInfo &_elfTargetInfo;\n ReaderArchive _readerArchive;\n};\n} \/\/ end namespace elf\n\nstd::unique_ptr<Reader> createReaderELF(const ELFTargetInfo &targetinfo) {\n return std::unique_ptr<Reader>(new elf::ELFReader(targetinfo));\n}\n} \/\/ end namespace lld\n<commit_msg>Use the StringRef version of identifyFileType.<commit_after>\/\/===- lib\/ReaderWriter\/ELF\/Reader.cpp ------------------------------------===\/\/\n\/\/\n\/\/ The LLVM Linker\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\/\n\/\/\/ \\file\n\/\/\/ \\brief Defines the ELF Reader and all helper sub classes to consume an ELF\n\/\/\/ file and produces atoms out of it.\n\/\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"lld\/ReaderWriter\/Reader.h\"\n\n#include \"Atoms.h\"\n#include \"CreateELF.h\"\n#include \"DynamicFile.h\"\n#include \"File.h\"\n\n#include \"lld\/Core\/Reference.h\"\n#include \"lld\/ReaderWriter\/ELFTargetInfo.h\"\n#include \"lld\/ReaderWriter\/ReaderArchive.h\"\n\n#include \"llvm\/ADT\/ArrayRef.h\"\n#include \"llvm\/ADT\/SmallString.h\"\n#include \"llvm\/ADT\/StringRef.h\"\n#include \"llvm\/Object\/ELF.h\"\n#include \"llvm\/Object\/ObjectFile.h\"\n#include \"llvm\/Support\/Allocator.h\"\n#include \"llvm\/Support\/Casting.h\"\n#include \"llvm\/Support\/ELF.h\"\n#include \"llvm\/Support\/Endian.h\"\n#include \"llvm\/Support\/ErrorHandling.h\"\n#include \"llvm\/Support\/ErrorOr.h\"\n#include \"llvm\/Support\/MathExtras.h\"\n#include \"llvm\/Support\/Memory.h\"\n#include \"llvm\/Support\/MemoryBuffer.h\"\n#include \"llvm\/Support\/Path.h\"\n#include \"llvm\/Support\/raw_ostream.h\"\n#include \"llvm\/Support\/system_error.h\"\n\n#include <map>\n#include <vector>\n\nusing llvm::support::endianness;\nusing namespace llvm::object;\n\nnamespace {\nstruct DynamicFileCreateELFTraits {\n typedef llvm::ErrorOr<std::unique_ptr<lld::SharedLibraryFile>> result_type;\n\n template <class ELFT>\n static result_type create(const lld::ELFTargetInfo &ti,\n std::unique_ptr<llvm::MemoryBuffer> mb) {\n return lld::elf::DynamicFile<ELFT>::create(ti, std::move(mb));\n }\n};\n\nstruct ELFFileCreateELFTraits {\n typedef std::unique_ptr<lld::File> result_type;\n\n template <class ELFT>\n static result_type create(const lld::ELFTargetInfo &ti,\n std::unique_ptr<llvm::MemoryBuffer> mb,\n lld::error_code &ec) {\n return std::unique_ptr<lld::File>(\n new lld::elf::ELFFile<ELFT>(ti, std::move(mb), ec));\n }\n};\n}\n\nnamespace lld {\nnamespace elf {\n\/\/\/ \\brief A reader object that will instantiate correct File by examining the\n\/\/\/ memory buffer for ELF class and bit width\nclass ELFReader : public Reader {\npublic:\n ELFReader(const ELFTargetInfo &ti)\n : lld::Reader(ti), _elfTargetInfo(ti), _readerArchive(ti, *this) {\n }\n\n error_code parseFile(std::unique_ptr<MemoryBuffer> &mb,\n std::vector<std::unique_ptr<File> > &result) const {\n using llvm::object::ELFType;\n llvm::sys::LLVMFileType fileType =\n llvm::sys::identifyFileType(mb->getBuffer());\n\n std::size_t MaxAlignment =\n 1ULL << llvm::countTrailingZeros(uintptr_t(mb->getBufferStart()));\n\n llvm::error_code ec;\n switch (fileType) {\n case llvm::sys::ELF_Relocatable_FileType: {\n std::unique_ptr<File> f(createELF<ELFFileCreateELFTraits>(\n getElfArchType(&*mb), MaxAlignment, _elfTargetInfo, std::move(mb),\n ec));\n if (ec)\n return ec;\n result.push_back(std::move(f));\n break;\n }\n case llvm::sys::ELF_SharedObject_FileType: {\n auto f = createELF<DynamicFileCreateELFTraits>(\n getElfArchType(&*mb), MaxAlignment, _elfTargetInfo, std::move(mb));\n if (!f)\n return f;\n result.push_back(std::move(*f));\n break;\n }\n case llvm::sys::Archive_FileType:\n ec = _readerArchive.parseFile(mb, result);\n break;\n default:\n return llvm::make_error_code(llvm::errc::executable_format_error);\n break;\n }\n\n if (ec)\n return ec;\n\n return error_code::success();\n }\n\nprivate:\n const ELFTargetInfo &_elfTargetInfo;\n ReaderArchive _readerArchive;\n};\n} \/\/ end namespace elf\n\nstd::unique_ptr<Reader> createReaderELF(const ELFTargetInfo &targetinfo) {\n return std::unique_ptr<Reader>(new elf::ELFReader(targetinfo));\n}\n} \/\/ end namespace lld\n<|endoftext|>"} {"text":"<commit_before>\/\/===-- ELFTargetAsmInfo.cpp - ELF asm properties ---------------*- C++ -*-===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This file defines target asm properties related what form asm statements\n\/\/ should take in general on ELF-based targets\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/Constants.h\"\n#include \"llvm\/DerivedTypes.h\"\n#include \"llvm\/Function.h\"\n#include \"llvm\/GlobalVariable.h\"\n#include \"llvm\/ADT\/StringExtras.h\"\n#include \"llvm\/CodeGen\/MachineConstantPool.h\"\n#include \"llvm\/Support\/ErrorHandling.h\"\n#include \"llvm\/Target\/ELFTargetAsmInfo.h\"\n#include \"llvm\/Target\/TargetMachine.h\"\n#include \"llvm\/Target\/TargetData.h\"\n\nusing namespace llvm;\n\nELFTargetAsmInfo::ELFTargetAsmInfo(const TargetMachine &TM)\n : TargetAsmInfo(TM) {\n\n BSSSection_ = getUnnamedSection(\"\\t.bss\",\n SectionFlags::Writeable | SectionFlags::BSS);\n ReadOnlySection = getNamedSection(\"\\t.rodata\", SectionFlags::None);\n TLSDataSection = getNamedSection(\"\\t.tdata\",\n SectionFlags::Writeable | SectionFlags::TLS);\n TLSBSSSection = getNamedSection(\"\\t.tbss\",\n SectionFlags::Writeable | SectionFlags::TLS | SectionFlags::BSS);\n\n DataRelSection = getNamedSection(\"\\t.data.rel\", SectionFlags::Writeable);\n DataRelLocalSection = getNamedSection(\"\\t.data.rel.local\",\n SectionFlags::Writeable);\n DataRelROSection = getNamedSection(\"\\t.data.rel.ro\",\n SectionFlags::Writeable);\n DataRelROLocalSection = getNamedSection(\"\\t.data.rel.ro.local\",\n SectionFlags::Writeable);\n}\n\nSectionKind::Kind\nELFTargetAsmInfo::SectionKindForGlobal(const GlobalValue *GV) const {\n SectionKind::Kind Kind = TargetAsmInfo::SectionKindForGlobal(GV);\n\n if (Kind != SectionKind::Data)\n return Kind;\n\n \/\/ Decide, whether we need data.rel stuff\n const GlobalVariable* GVar = dyn_cast<GlobalVariable>(GV);\n if (GVar->hasInitializer() && TM.getRelocationModel() != Reloc::Static) {\n Constant *C = GVar->getInitializer();\n bool isConstant = GVar->isConstant();\n \n \/\/ By default - all relocations in PIC mode would force symbol to be\n \/\/ placed in r\/w section.\n switch (C->getRelocationInfo()) {\n default: break;\n case 1:\n return isConstant ? SectionKind::DataRelROLocal :\n SectionKind::DataRelLocal;\n case 2:\n return isConstant ? SectionKind::DataRelRO : SectionKind::DataRel;\n }\n }\n\n return Kind;\n}\n\nconst Section*\nELFTargetAsmInfo::SelectSectionForGlobal(const GlobalValue *GV) const {\n SectionKind::Kind Kind = SectionKindForGlobal(GV);\n\n if (const Function *F = dyn_cast<Function>(GV)) {\n switch (F->getLinkage()) {\n default: llvm_unreachable(\"Unknown linkage type!\");\n case Function::PrivateLinkage:\n case Function::LinkerPrivateLinkage:\n case Function::InternalLinkage:\n case Function::DLLExportLinkage:\n case Function::ExternalLinkage:\n return TextSection;\n case Function::WeakAnyLinkage:\n case Function::WeakODRLinkage:\n case Function::LinkOnceAnyLinkage:\n case Function::LinkOnceODRLinkage:\n std::string Name = UniqueSectionForGlobal(GV, Kind);\n unsigned Flags = SectionFlagsForGlobal(GV, Name.c_str());\n return getNamedSection(Name.c_str(), Flags);\n }\n } else if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV)) {\n if (GVar->isWeakForLinker()) {\n std::string Name = UniqueSectionForGlobal(GVar, Kind);\n unsigned Flags = SectionFlagsForGlobal(GVar, Name.c_str());\n return getNamedSection(Name.c_str(), Flags);\n } else {\n switch (Kind) {\n case SectionKind::Data:\n case SectionKind::SmallData:\n return DataSection;\n case SectionKind::DataRel:\n return DataRelSection;\n case SectionKind::DataRelLocal:\n return DataRelLocalSection;\n case SectionKind::DataRelRO:\n return DataRelROSection;\n case SectionKind::DataRelROLocal:\n return DataRelROLocalSection;\n case SectionKind::BSS:\n case SectionKind::SmallBSS:\n \/\/ ELF targets usually have BSS sections\n return getBSSSection_();\n case SectionKind::ROData:\n case SectionKind::SmallROData:\n return getReadOnlySection();\n case SectionKind::RODataMergeStr:\n return MergeableStringSection(GVar);\n case SectionKind::RODataMergeConst:\n return MergeableConstSection(GVar->getInitializer()->getType());\n case SectionKind::ThreadData:\n \/\/ ELF targets usually support TLS stuff\n return TLSDataSection;\n case SectionKind::ThreadBSS:\n return TLSBSSSection;\n default:\n llvm_unreachable(\"Unsuported section kind for global\");\n }\n }\n } else\n llvm_unreachable(\"Unsupported global\");\n\n return NULL;\n}\n\n\/\/\/ getSectionForMergableConstant - Given a mergable constant with the\n\/\/\/ specified size and relocation information, return a section that it\n\/\/\/ should be placed in.\nconst Section *\nELFTargetAsmInfo::getSectionForMergableConstant(uint64_t Size,\n unsigned ReloInfo) const {\n \/\/ FIXME: IF this global requires a relocation, can we really put it in\n \/\/ rodata??? This should check ReloInfo like darwin.\n \n const char *SecName = 0;\n switch (Size) {\n default: break;\n case 4: SecName = \".rodata.cst4\"; break;\n case 8: SecName = \".rodata.cst8\"; break;\n case 16: SecName = \".rodata.cst16\"; break;\n }\n \n if (SecName)\n return getNamedSection(SecName,\n SectionFlags::setEntitySize(SectionFlags::Mergeable|\n SectionFlags::Small,\n Size));\n \n return getReadOnlySection(); \/\/ .rodata\n}\n\n\nconst Section*\nELFTargetAsmInfo::MergeableConstSection(const Type *Ty) const {\n const TargetData *TD = TM.getTargetData();\n return getSectionForMergableConstant(TD->getTypeAllocSize(Ty), 0);\n}\n\nconst Section*\nELFTargetAsmInfo::MergeableStringSection(const GlobalVariable *GV) const {\n const TargetData *TD = TM.getTargetData();\n Constant *C = cast<GlobalVariable>(GV)->getInitializer();\n const Type *Ty = cast<ArrayType>(C->getType())->getElementType();\n\n unsigned Size = TD->getTypeAllocSize(Ty);\n if (Size <= 16) {\n assert(getCStringSection() && \"Should have string section prefix\");\n\n \/\/ We also need alignment here\n unsigned Align = TD->getPrefTypeAlignment(Ty);\n if (Align < Size)\n Align = Size;\n\n std::string Name = getCStringSection() + utostr(Size) + '.' + utostr(Align);\n unsigned Flags = SectionFlags::setEntitySize(SectionFlags::Mergeable |\n SectionFlags::Strings,\n Size);\n return getNamedSection(Name.c_str(), Flags);\n }\n\n return getReadOnlySection();\n}\n\nstd::string ELFTargetAsmInfo::printSectionFlags(unsigned flags) const {\n std::string Flags = \",\\\"\";\n\n if (!(flags & SectionFlags::Debug))\n Flags += 'a';\n if (flags & SectionFlags::Code)\n Flags += 'x';\n if (flags & SectionFlags::Writeable)\n Flags += 'w';\n if (flags & SectionFlags::Mergeable)\n Flags += 'M';\n if (flags & SectionFlags::Strings)\n Flags += 'S';\n if (flags & SectionFlags::TLS)\n Flags += 'T';\n if (flags & SectionFlags::Small)\n Flags += 's';\n\n Flags += \"\\\",\";\n\n \/\/ If comment string is '@', e.g. as on ARM - use '%' instead\n if (strcmp(CommentString, \"@\") == 0)\n Flags += '%';\n else\n Flags += '@';\n\n \/\/ FIXME: There can be exceptions here\n if (flags & SectionFlags::BSS)\n Flags += \"nobits\";\n else\n Flags += \"progbits\";\n\n if (unsigned entitySize = SectionFlags::getEntitySize(flags))\n Flags += \",\" + utostr(entitySize);\n\n return Flags;\n}\n<commit_msg>don't set the small flag yet.<commit_after>\/\/===-- ELFTargetAsmInfo.cpp - ELF asm properties ---------------*- C++ -*-===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This file defines target asm properties related what form asm statements\n\/\/ should take in general on ELF-based targets\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/Constants.h\"\n#include \"llvm\/DerivedTypes.h\"\n#include \"llvm\/Function.h\"\n#include \"llvm\/GlobalVariable.h\"\n#include \"llvm\/ADT\/StringExtras.h\"\n#include \"llvm\/CodeGen\/MachineConstantPool.h\"\n#include \"llvm\/Support\/ErrorHandling.h\"\n#include \"llvm\/Target\/ELFTargetAsmInfo.h\"\n#include \"llvm\/Target\/TargetMachine.h\"\n#include \"llvm\/Target\/TargetData.h\"\n\nusing namespace llvm;\n\nELFTargetAsmInfo::ELFTargetAsmInfo(const TargetMachine &TM)\n : TargetAsmInfo(TM) {\n\n BSSSection_ = getUnnamedSection(\"\\t.bss\",\n SectionFlags::Writeable | SectionFlags::BSS);\n ReadOnlySection = getNamedSection(\"\\t.rodata\", SectionFlags::None);\n TLSDataSection = getNamedSection(\"\\t.tdata\",\n SectionFlags::Writeable | SectionFlags::TLS);\n TLSBSSSection = getNamedSection(\"\\t.tbss\",\n SectionFlags::Writeable | SectionFlags::TLS | SectionFlags::BSS);\n\n DataRelSection = getNamedSection(\"\\t.data.rel\", SectionFlags::Writeable);\n DataRelLocalSection = getNamedSection(\"\\t.data.rel.local\",\n SectionFlags::Writeable);\n DataRelROSection = getNamedSection(\"\\t.data.rel.ro\",\n SectionFlags::Writeable);\n DataRelROLocalSection = getNamedSection(\"\\t.data.rel.ro.local\",\n SectionFlags::Writeable);\n}\n\nSectionKind::Kind\nELFTargetAsmInfo::SectionKindForGlobal(const GlobalValue *GV) const {\n SectionKind::Kind Kind = TargetAsmInfo::SectionKindForGlobal(GV);\n\n if (Kind != SectionKind::Data)\n return Kind;\n\n \/\/ Decide, whether we need data.rel stuff\n const GlobalVariable* GVar = dyn_cast<GlobalVariable>(GV);\n if (GVar->hasInitializer() && TM.getRelocationModel() != Reloc::Static) {\n Constant *C = GVar->getInitializer();\n bool isConstant = GVar->isConstant();\n \n \/\/ By default - all relocations in PIC mode would force symbol to be\n \/\/ placed in r\/w section.\n switch (C->getRelocationInfo()) {\n default: break;\n case 1:\n return isConstant ? SectionKind::DataRelROLocal :\n SectionKind::DataRelLocal;\n case 2:\n return isConstant ? SectionKind::DataRelRO : SectionKind::DataRel;\n }\n }\n\n return Kind;\n}\n\nconst Section*\nELFTargetAsmInfo::SelectSectionForGlobal(const GlobalValue *GV) const {\n SectionKind::Kind Kind = SectionKindForGlobal(GV);\n\n if (const Function *F = dyn_cast<Function>(GV)) {\n switch (F->getLinkage()) {\n default: llvm_unreachable(\"Unknown linkage type!\");\n case Function::PrivateLinkage:\n case Function::LinkerPrivateLinkage:\n case Function::InternalLinkage:\n case Function::DLLExportLinkage:\n case Function::ExternalLinkage:\n return TextSection;\n case Function::WeakAnyLinkage:\n case Function::WeakODRLinkage:\n case Function::LinkOnceAnyLinkage:\n case Function::LinkOnceODRLinkage:\n std::string Name = UniqueSectionForGlobal(GV, Kind);\n unsigned Flags = SectionFlagsForGlobal(GV, Name.c_str());\n return getNamedSection(Name.c_str(), Flags);\n }\n } else if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV)) {\n if (GVar->isWeakForLinker()) {\n std::string Name = UniqueSectionForGlobal(GVar, Kind);\n unsigned Flags = SectionFlagsForGlobal(GVar, Name.c_str());\n return getNamedSection(Name.c_str(), Flags);\n } else {\n switch (Kind) {\n case SectionKind::Data:\n case SectionKind::SmallData:\n return DataSection;\n case SectionKind::DataRel:\n return DataRelSection;\n case SectionKind::DataRelLocal:\n return DataRelLocalSection;\n case SectionKind::DataRelRO:\n return DataRelROSection;\n case SectionKind::DataRelROLocal:\n return DataRelROLocalSection;\n case SectionKind::BSS:\n case SectionKind::SmallBSS:\n \/\/ ELF targets usually have BSS sections\n return getBSSSection_();\n case SectionKind::ROData:\n case SectionKind::SmallROData:\n return getReadOnlySection();\n case SectionKind::RODataMergeStr:\n return MergeableStringSection(GVar);\n case SectionKind::RODataMergeConst:\n return MergeableConstSection(GVar->getInitializer()->getType());\n case SectionKind::ThreadData:\n \/\/ ELF targets usually support TLS stuff\n return TLSDataSection;\n case SectionKind::ThreadBSS:\n return TLSBSSSection;\n default:\n llvm_unreachable(\"Unsuported section kind for global\");\n }\n }\n } else\n llvm_unreachable(\"Unsupported global\");\n\n return NULL;\n}\n\n\/\/\/ getSectionForMergableConstant - Given a mergable constant with the\n\/\/\/ specified size and relocation information, return a section that it\n\/\/\/ should be placed in.\nconst Section *\nELFTargetAsmInfo::getSectionForMergableConstant(uint64_t Size,\n unsigned ReloInfo) const {\n \/\/ FIXME: IF this global requires a relocation, can we really put it in\n \/\/ rodata??? This should check ReloInfo like darwin.\n \n const char *SecName = 0;\n switch (Size) {\n default: break;\n case 4: SecName = \".rodata.cst4\"; break;\n case 8: SecName = \".rodata.cst8\"; break;\n case 16: SecName = \".rodata.cst16\"; break;\n }\n \n if (SecName)\n return getNamedSection(SecName,\n SectionFlags::setEntitySize(SectionFlags::Mergeable,\n Size));\n \n return getReadOnlySection(); \/\/ .rodata\n}\n\n\nconst Section*\nELFTargetAsmInfo::MergeableConstSection(const Type *Ty) const {\n const TargetData *TD = TM.getTargetData();\n return getSectionForMergableConstant(TD->getTypeAllocSize(Ty), 0);\n}\n\nconst Section*\nELFTargetAsmInfo::MergeableStringSection(const GlobalVariable *GV) const {\n const TargetData *TD = TM.getTargetData();\n Constant *C = cast<GlobalVariable>(GV)->getInitializer();\n const Type *Ty = cast<ArrayType>(C->getType())->getElementType();\n\n unsigned Size = TD->getTypeAllocSize(Ty);\n if (Size <= 16) {\n assert(getCStringSection() && \"Should have string section prefix\");\n\n \/\/ We also need alignment here\n unsigned Align = TD->getPrefTypeAlignment(Ty);\n if (Align < Size)\n Align = Size;\n\n std::string Name = getCStringSection() + utostr(Size) + '.' + utostr(Align);\n unsigned Flags = SectionFlags::setEntitySize(SectionFlags::Mergeable |\n SectionFlags::Strings,\n Size);\n return getNamedSection(Name.c_str(), Flags);\n }\n\n return getReadOnlySection();\n}\n\nstd::string ELFTargetAsmInfo::printSectionFlags(unsigned flags) const {\n std::string Flags = \",\\\"\";\n\n if (!(flags & SectionFlags::Debug))\n Flags += 'a';\n if (flags & SectionFlags::Code)\n Flags += 'x';\n if (flags & SectionFlags::Writeable)\n Flags += 'w';\n if (flags & SectionFlags::Mergeable)\n Flags += 'M';\n if (flags & SectionFlags::Strings)\n Flags += 'S';\n if (flags & SectionFlags::TLS)\n Flags += 'T';\n if (flags & SectionFlags::Small)\n Flags += 's';\n\n Flags += \"\\\",\";\n\n \/\/ If comment string is '@', e.g. as on ARM - use '%' instead\n if (strcmp(CommentString, \"@\") == 0)\n Flags += '%';\n else\n Flags += '@';\n\n \/\/ FIXME: There can be exceptions here\n if (flags & SectionFlags::BSS)\n Flags += \"nobits\";\n else\n Flags += \"progbits\";\n\n if (unsigned entitySize = SectionFlags::getEntitySize(flags))\n Flags += \",\" + utostr(entitySize);\n\n return Flags;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/===- X86InstrInfo.cpp - X86 Instruction Information -----------*- C++ -*-===\/\/\n\/\/ \n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file was developed by the LLVM research group and is distributed under\n\/\/ the University of Illinois Open Source License. See LICENSE.TXT for details.\n\/\/ \n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This file contains the X86 implementation of the TargetInstrInfo class.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"X86InstrInfo.h\"\n#include \"X86.h\"\n#include \"llvm\/CodeGen\/MachineInstrBuilder.h\"\n#include \"X86GenInstrInfo.inc\"\nusing namespace llvm;\n\nX86InstrInfo::X86InstrInfo()\n : TargetInstrInfo(X86Insts, sizeof(X86Insts)\/sizeof(X86Insts[0])) {\n}\n\n\nbool X86InstrInfo::isMoveInstr(const MachineInstr& MI,\n unsigned& sourceReg,\n unsigned& destReg) const {\n MachineOpCode oc = MI.getOpcode();\n if (oc == X86::MOV8rr || oc == X86::MOV16rr || oc == X86::MOV32rr ||\n oc == X86::FpMOV) {\n assert(MI.getNumOperands() == 2 &&\n MI.getOperand(0).isRegister() &&\n MI.getOperand(1).isRegister() &&\n \"invalid register-register move instruction\");\n sourceReg = MI.getOperand(1).getReg();\n destReg = MI.getOperand(0).getReg();\n return true;\n }\n return false;\n}\n\nvoid X86InstrInfo::insertGoto(MachineBasicBlock& MBB,\n MachineBasicBlock& TMBB) const {\n BuildMI(MBB, MBB.end(), X86::JMP, 1).addMBB(&TMBB);\n}\n\nMachineBasicBlock::iterator\nX86InstrInfo::reverseBranchCondition(MachineBasicBlock::iterator MI) const {\n unsigned Opcode = MI->getOpcode();\n assert(isBranch(Opcode) && \"MachineInstr must be a branch\");\n unsigned ROpcode;\n switch (Opcode) {\n case X86::JB: ROpcode = X86::JAE;\n case X86::JAE: ROpcode = X86::JB;\n case X86::JE: ROpcode = X86::JNE;\n case X86::JNE: ROpcode = X86::JE;\n case X86::JBE: ROpcode = X86::JA;\n case X86::JA: ROpcode = X86::JBE;\n case X86::JS: ROpcode = X86::JNS;\n case X86::JNS: ROpcode = X86::JS;\n case X86::JL: ROpcode = X86::JGE;\n case X86::JGE: ROpcode = X86::JL;\n case X86::JLE: ROpcode = X86::JG;\n case X86::JG: ROpcode = X86::JLE;\n default:\n assert(0 && \"Cannot reverse unconditional branches!\");\n }\n MachineBasicBlock* MBB = MI->getParent();\n MachineBasicBlock* TMBB = MI->getOperand(0).getMachineBasicBlock();\n MachineInstrBuilder IB = BuildMI(*MBB, MBB->erase(MI), ROpcode, 1);\n IB.addMBB(TMBB);\n return IB;\n}\n<commit_msg>Simplify code a bit.<commit_after>\/\/===- X86InstrInfo.cpp - X86 Instruction Information -----------*- C++ -*-===\/\/\n\/\/ \n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file was developed by the LLVM research group and is distributed under\n\/\/ the University of Illinois Open Source License. See LICENSE.TXT for details.\n\/\/ \n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This file contains the X86 implementation of the TargetInstrInfo class.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"X86InstrInfo.h\"\n#include \"X86.h\"\n#include \"llvm\/CodeGen\/MachineInstrBuilder.h\"\n#include \"X86GenInstrInfo.inc\"\nusing namespace llvm;\n\nX86InstrInfo::X86InstrInfo()\n : TargetInstrInfo(X86Insts, sizeof(X86Insts)\/sizeof(X86Insts[0])) {\n}\n\n\nbool X86InstrInfo::isMoveInstr(const MachineInstr& MI,\n unsigned& sourceReg,\n unsigned& destReg) const {\n MachineOpCode oc = MI.getOpcode();\n if (oc == X86::MOV8rr || oc == X86::MOV16rr || oc == X86::MOV32rr ||\n oc == X86::FpMOV) {\n assert(MI.getNumOperands() == 2 &&\n MI.getOperand(0).isRegister() &&\n MI.getOperand(1).isRegister() &&\n \"invalid register-register move instruction\");\n sourceReg = MI.getOperand(1).getReg();\n destReg = MI.getOperand(0).getReg();\n return true;\n }\n return false;\n}\n\nvoid X86InstrInfo::insertGoto(MachineBasicBlock& MBB,\n MachineBasicBlock& TMBB) const {\n BuildMI(MBB, MBB.end(), X86::JMP, 1).addMBB(&TMBB);\n}\n\nMachineBasicBlock::iterator\nX86InstrInfo::reverseBranchCondition(MachineBasicBlock::iterator MI) const {\n unsigned Opcode = MI->getOpcode();\n assert(isBranch(Opcode) && \"MachineInstr must be a branch\");\n unsigned ROpcode;\n switch (Opcode) {\n case X86::JB: ROpcode = X86::JAE;\n case X86::JAE: ROpcode = X86::JB;\n case X86::JE: ROpcode = X86::JNE;\n case X86::JNE: ROpcode = X86::JE;\n case X86::JBE: ROpcode = X86::JA;\n case X86::JA: ROpcode = X86::JBE;\n case X86::JS: ROpcode = X86::JNS;\n case X86::JNS: ROpcode = X86::JS;\n case X86::JL: ROpcode = X86::JGE;\n case X86::JGE: ROpcode = X86::JL;\n case X86::JLE: ROpcode = X86::JG;\n case X86::JG: ROpcode = X86::JLE;\n default:\n assert(0 && \"Cannot reverse unconditional branches!\");\n }\n MachineBasicBlock* MBB = MI->getParent();\n MachineBasicBlock* TMBB = MI->getOperand(0).getMachineBasicBlock();\n return BuildMI(*MBB, MBB->erase(MI), ROpcode, 1).addMBB(TMBB);\n}\n<|endoftext|>"} {"text":"<commit_before>\/* -*- mode: C++; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8 -*- *\/\n\/** \n Example for Mr G. Royle :\n Compute the integer characteristic polynomial of symetric matrices with \n 0,1 coefficients\n*\/\n\n\n#include <iostream>\n\n#include \"linbox\/blackbox\/zero-one.h\"\n#include \"linbox\/field\/PID-integer.h\"\n#include \"linbox\/solutions\/charpoly.h\"\n#include \"linbox\/ring\/givaro-polynomial.h\"\n#include \"linbox\/solutions\/methods.h\"\n\nusing namespace std;\nusing namespace LinBox;\n\ntemplate <class Field, class Polynomial>\nvoid printPolynomial(const Field& F, const Polynomial& P){\n\tint n= P.size()-1;\n\tfor (int i=0;i<n;++i)\n\t\tcout<<P[i]<<\" \";\n\tcout<<endl;\n\tif (n==1){\n\t\tcout<<\"X\";\n\t\tif ( P[0] != 0)\n\t\t\tF.write(cout<<((P[0]>0)?\"+\":\"\"),P[0]);\n\t}\n\telse{\n\t\tcout<<\"X^\"<<n;\n\t\tfor ( int i=n-1; i>1; --i)\n\t\t\tif (!F.isZero(P[i]))\n\t\t\t\tF.write(cout<<((P[i]>0)?\"+\":\"\"),P[i])<<\"*X^\"<<i;\n\t\tif ( P[1] != 0)\n\t\t\tF.write(cout<<((P[1]>0)?\"+\":\"\"),P[1])<<\"*X\";\n\t\tif ( P[0] != 0)\n\t\t\tF.write(cout<<((P[0]>0)?\"+\":\"\"),P[0]);\n\t}\n}\n\n\ntypedef ZeroOne<PID_integer> Matrix;\ntypedef GivPolynomialRing<PID_integer,Dense> IntPolRing;\n\nint main (int argc, char **argv)\n{\n\tcommentator.getMessageClass (BRIEF_REPORT).setMaxDepth (2);\n\tcommentator.getMessageClass (BRIEF_REPORT).setMaxDetailLevel (Commentator::LEVEL_UNIMPORTANT);\n\t\n\n\tif (argc != 2) {\n\t\tcerr << \"Usage: graph-charpoly <matrix-file-in-SMS-format>\" <<endl;\n\t\treturn -1;\n\t}\n\n\tifstream input (argv[1]);\n\tif (!input) { \n\t cerr << \"Error opening matrix file \" << argv[1] << endl; \n\t return -1; \n\t}\n\t\n\t\/\/UnparametricField<integer> ZZ;\n\tPID_integer ZZ;\n\tMatrix A;\n\tA.read (input);\n\tcommentator.report(1, BRIEF_REPORT)<< \"A is \" << A.rowdim() << \" by \" << A.coldim() << endl;\n\t\n\tIntPolRing::Element c_A;\n\n\tcharpoly (c_A, A, Method::Blackbox(Method::Wiedemann( Specifier::SYMMETRIC)));\n\t\n\tcout<< \"Characteristic Polynomial is \";\n\tprintPolynomial (ZZ, c_A);\n\t\n\treturn 0;\n}\n<commit_msg>cstor with Field<commit_after>\/* -*- mode: C++; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8 -*- *\/\n\/** \n Example for Mr G. Royle :\n Compute the integer characteristic polynomial of symetric matrices with \n 0,1 coefficients\n*\/\n\n\n#include <iostream>\n\n#include \"linbox\/blackbox\/zero-one.h\"\n#include \"linbox\/field\/PID-integer.h\"\n#include \"linbox\/solutions\/charpoly.h\"\n#include \"linbox\/ring\/givaro-polynomial.h\"\n#include \"linbox\/solutions\/methods.h\"\n\nusing namespace std;\nusing namespace LinBox;\n\ntemplate <class Field, class Polynomial>\nvoid printPolynomial(const Field& F, const Polynomial& P){\n\tint n= P.size()-1;\n\tfor (int i=0;i<n;++i)\n\t\tcout<<P[i]<<\" \";\n\tcout<<endl;\n\tif (n==1){\n\t\tcout<<\"X\";\n\t\tif ( P[0] != 0)\n\t\t\tF.write(cout<<((P[0]>0)?\"+\":\"\"),P[0]);\n\t}\n\telse{\n\t\tcout<<\"X^\"<<n;\n\t\tfor ( int i=n-1; i>1; --i)\n\t\t\tif (!F.isZero(P[i]))\n\t\t\t\tF.write(cout<<((P[i]>0)?\"+\":\"\"),P[i])<<\"*X^\"<<i;\n\t\tif ( P[1] != 0)\n\t\t\tF.write(cout<<((P[1]>0)?\"+\":\"\"),P[1])<<\"*X\";\n\t\tif ( P[0] != 0)\n\t\t\tF.write(cout<<((P[0]>0)?\"+\":\"\"),P[0]);\n\t}\n}\n\n\ntypedef ZeroOne<PID_integer> Matrix;\ntypedef GivPolynomialRing<PID_integer,Dense> IntPolRing;\n\nint main (int argc, char **argv)\n{\n\tcommentator.getMessageClass (BRIEF_REPORT).setMaxDepth (2);\n\tcommentator.getMessageClass (BRIEF_REPORT).setMaxDetailLevel (Commentator::LEVEL_UNIMPORTANT);\n\t\n\n\tif (argc != 2) {\n\t\tcerr << \"Usage: graph-charpoly <matrix-file-in-SMS-format>\" <<endl;\n\t\treturn -1;\n\t}\n\n\tifstream input (argv[1]);\n\tif (!input) { \n\t cerr << \"Error opening matrix file \" << argv[1] << endl; \n\t return -1; \n\t}\n\t\n\t\/\/UnparametricField<integer> ZZ;\n\tPID_integer ZZ;\n\tMatrix A(ZZ);\n\tA.read (input);\n\tcommentator.report(1, BRIEF_REPORT)<< \"A is \" << A.rowdim() << \" by \" << A.coldim() << endl;\n\t\n\tIntPolRing::Element c_A;\n\n\tcharpoly (c_A, A, Method::Blackbox(Method::Wiedemann( Specifier::SYMMETRIC)));\n\t\n\tcout<< \"Characteristic Polynomial is \";\n\tprintPolynomial (ZZ, c_A);\n\t\n\treturn 0;\n}\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n\n#include \"vm.hpp\"\n\n#include \"exception.hpp\"\n#include \"exception_point.hpp\"\n#include \"arguments.hpp\"\n#include \"dispatch.hpp\"\n#include \"native_libraries.hpp\"\n#include \"primitives.hpp\"\n#include \"call_frame.hpp\"\n\n#include \"builtin\/array.hpp\"\n#include \"builtin\/exception.hpp\"\n#include \"builtin\/nativemethod.hpp\"\n#include \"builtin\/string.hpp\"\n#include \"builtin\/system.hpp\"\n#include \"builtin\/tuple.hpp\"\n#include \"builtin\/capi_handle.hpp\"\n\n#include \"instruments\/profiler.hpp\"\n\n#include \"capi\/capi.hpp\"\n#include \"capi\/handle.hpp\"\n\nnamespace rubinius {\n \/** Thread-local NativeMethodEnvironment instance. *\/\n thread::ThreadData<NativeMethodEnvironment*> native_method_environment;\n\n\/* Class methods *\/\n\n NativeMethodEnvironment* NativeMethodEnvironment::get() {\n return native_method_environment.get();\n }\n\n NativeMethodFrame::~NativeMethodFrame() {\n flush_cached_data(true);\n for(capi::HandleList::iterator i = handles_.begin();\n i != handles_.end();\n i++) {\n capi::Handle* handle = *i;\n handle->deref();\n }\n }\n\n VALUE NativeMethodFrame::get_handle(STATE, Object* obj) {\n capi::Handle* handle;\n\n Object* existing = obj->get_table_ivar(state, state->symbol(\"capi_handle\"));\n\n if(CApiHandle* wrapper = try_as<CApiHandle>(existing)) {\n handle = wrapper->handle;\n } else {\n handle = new capi::Handle(state, obj);\n state->shared.global_handles()->add(handle);\n CApiHandle* wrapper = CApiHandle::create(state, handle);\n obj->set_table_ivar(state, state->symbol(\"capi_handle\"), wrapper);\n }\n\n handle->ref();\n\n handles_.push_back(handle);\n return handle->as_value();\n }\n\n Object* NativeMethodFrame::get_object(VALUE val) {\n return capi::Handle::from(val)->object();\n }\n\n CApiStructs& NativeMethodFrame::strings() {\n if(!strings_) strings_ = new CApiStructs;\n return *strings_;\n }\n\n CApiStructs& NativeMethodFrame::arrays() {\n if(!arrays_) arrays_ = new CApiStructs;\n return *arrays_;\n }\n\n CApiStructs& NativeMethodFrame::data() {\n if(!data_) data_ = new CApiStructs;\n return *data_;\n }\n\n void NativeMethodFrame::flush_cached_data(bool release_memory) {\n NativeMethodEnvironment* env = NativeMethodEnvironment::get();\n\n for(capi::HandleList::iterator i = handles_.begin();\n i != handles_.end();\n i++) {\n capi::Handle* handle = *i;\n if(handle->is_rarray()) {\n capi::capi_get_array(env, handle->as_value());\n } else if(handle->is_rstring()) {\n capi::capi_get_string(env, handle->as_value());\n } else if(handle->is_rdata()) {\n capi::capi_rdata_flush_handle(env, handle);\n }\n\n if(release_memory) handle->free_data();\n }\n }\n\n void NativeMethodFrame::update_cached_data() {\n NativeMethodEnvironment* env = NativeMethodEnvironment::get();\n for(capi::HandleList::iterator i = handles_.begin();\n i != handles_.end();\n i++) {\n capi::Handle* handle = *i;\n if(handle->is_rarray()) {\n capi::capi_update_array(env, handle->as_value());\n } else if(handle->is_rstring()) {\n capi::capi_update_string(env, handle->as_value());\n }\n }\n }\n\n VALUE NativeMethodEnvironment::get_handle(Object* obj) {\n if(obj->reference_p()) {\n return current_native_frame_->get_handle(state_, obj);\n } else if(obj->fixnum_p() || obj->symbol_p()) {\n return reinterpret_cast<VALUE>(obj);\n } else if(obj->nil_p()) {\n return cCApiHandleQnil;\n } else if(obj->false_p()) {\n return cCApiHandleQfalse;\n } else if(obj->true_p()) {\n return cCApiHandleQtrue;\n } else if(obj->undef_p()) {\n return cCApiHandleQundef;\n }\n\n capi::capi_raise_runtime_error(\"NativeMethod handle requested for unknown object type\");\n return 0; \/\/ keep compiler happy\n }\n\n Object* NativeMethodEnvironment::get_object(VALUE val) {\n if(CAPI_REFERENCE_P(val)) {\n return capi::Handle::from(val)->object();\n \/*\n if(CAPI_GLOBAL_HANDLE_P(handle)) {\n Handles& global_handles = state_->shared.global_handles();\n size_t index = CAPI_STRIP_GLOBAL_TAG(handle);\n if(unlikely(index >= global_handles.size())) {\n capi_raise_runtime_error(\"requested Object for invalid NativeMethod global handle\");\n }\n\n RootHandle* root = global_handles[index];\n\n if(unlikely(!root)) {\n capi_raise_runtime_error(\"Attempted to use deleted NativeMethod global handle\");\n }\n\n Object* obj = root->get();\n if(unlikely(!obj)) {\n capi_raise_runtime_error(\"NativeMethod global handle refers to NULL object\");\n }\n return obj;\n } else {\n return current_native_frame_->get_object(handle);\n }\n *\/\n } else if(FIXNUM_P(val) || SYMBOL_P(val)) {\n return reinterpret_cast<Object*>(val);\n } else if(CAPI_FALSE_P(val)) {\n return Qfalse;\n } else if(CAPI_TRUE_P(val)) {\n return Qtrue;\n } else if(CAPI_NIL_P(val)) {\n return Qnil;\n } else if(CAPI_UNDEF_P(val)) {\n return Qundef;\n }\n\n capi::capi_raise_runtime_error(\"requested Object for unknown NativeMethod handle type\");\n return Qnil; \/\/ keep compiler happy\n }\n\n void NativeMethodEnvironment::delete_global(VALUE val) {\n abort();\n }\n\n Object* NativeMethodEnvironment::block() {\n return current_call_frame_->top_scope->block();\n }\n\n capi::HandleList& NativeMethodEnvironment::handles() {\n return current_native_frame_->handles();\n }\n\n CApiStructs& NativeMethodEnvironment::strings() {\n return current_native_frame_->strings();\n }\n\n CApiStructs& NativeMethodEnvironment::arrays() {\n return current_native_frame_->arrays();\n }\n\n CApiStructs& NativeMethodEnvironment::data() {\n return current_native_frame_->data();\n }\n\n void NativeMethodEnvironment::flush_cached_data(bool release_memory) {\n current_native_frame_->flush_cached_data(release_memory);\n }\n\n void NativeMethodEnvironment::update_cached_data() {\n current_native_frame_->update_cached_data();\n }\n\n void NativeMethod::init(STATE) {\n state->globals.nmethod.set(state->new_class(\"NativeMethod\", G(executable), G(rubinius)));\n state->globals.nmethod.get()->set_object_type(state, NativeMethodType);\n\n init_thread(state);\n }\n\n void NativeMethod::init_thread(STATE) {\n NativeMethodEnvironment* env = new NativeMethodEnvironment;\n env->set_state(state);\n native_method_environment.set(env);\n }\n\n NativeMethod* NativeMethod::allocate(STATE) {\n return create<GenericFunctor>(state);\n }\n\n Object* NativeMethod::executor_implementation(STATE,\n CallFrame* call_frame, Dispatch& msg, Arguments& args) {\n NativeMethod* nm = as<NativeMethod>(msg.method);\n\n int arity = nm->arity()->to_int();\n if(arity >= 0 && (size_t)arity != args.total()) {\n Exception* exc = Exception::make_argument_error(\n state, arity, args.total(), msg.name);\n exc->locations(state, System::vm_backtrace(state, Fixnum::from(1), call_frame));\n state->thread_state()->raise_exception(exc);\n\n return NULL;\n }\n\n NativeMethodEnvironment* env = native_method_environment.get();\n NativeMethodFrame nmf(env->current_native_frame());\n\n env->set_current_call_frame(call_frame);\n env->set_current_native_frame(&nmf);\n\n Object* ret;\n ExceptionPoint ep(env);\n\n PLACE_EXCEPTION_POINT(ep);\n\n if(unlikely(ep.jumped_to())) {\n ret = NULL;\n } else {\n#ifdef RBX_PROFILER\n if(unlikely(state->shared.profiling())) {\n profiler::MethodEntry method(state, msg, args);\n ret = nm->call(state, env, args);\n } else {\n ret = nm->call(state, env, args);\n }\n#else\n ret = nm->call(state, env, args);\n#endif\n }\n\n env->set_current_native_frame(nmf.previous());\n ep.pop(env);\n\n return ret;\n }\n\n NativeMethod* NativeMethod::load_extension_entry_point(STATE, String* path, String* name) {\n void* func = NativeLibrary::find_symbol(state, name, path);\n\n NativeMethod* m = NativeMethod::create(state,\n path,\n state->globals.rubinius.get(),\n name->to_sym(state),\n reinterpret_cast<GenericFunctor>(func),\n Fixnum::from(INIT_FUNCTION)\n );\n return m;\n }\n\n \/**\n * Arity -3: VALUE func(VALUE argument_array);\n * Arity -2: VALUE func(VALUE receiver, VALUE argument_array);\n * Arity -1: VALUE func(int argument_count, VALUE*, VALUE receiver);\n * Otherwise: VALUE func(VALUE receiver, VALUE arg1[, VALUE arg2, ...]);\n *\n * There is also a special-case arity, INIT_FUNCTION, which corresponds\n * to void (*)(void) and should never appear in user code.\n *\n * @note Currently supports functions with up to receiver + 5 (separate) arguments only!\n * Anything beyond that should use one of the special arities instead.\n *\n * @todo Check for inefficiencies.\n *\/\n Object* NativeMethod::call(STATE, NativeMethodEnvironment* env, Arguments& args) {\n VALUE receiver = env->get_handle(args.recv());\n\n switch(arity()->to_int()) {\n case ARGS_IN_RUBY_ARRAY: { \/* Braces required to create objects in a switch *\/\n VALUE ary = env->get_handle(args.as_array(state));\n\n VALUE ret = functor_as<OneArgFunctor>()(ary);\n\n return env->get_object(ret);\n }\n\n case RECEIVER_PLUS_ARGS_IN_RUBY_ARRAY: {\n VALUE ary = env->get_handle(args.as_array(state));\n\n VALUE ret = functor_as<TwoArgFunctor>()(receiver, ary);\n\n return env->get_object(ret);\n }\n\n case ARG_COUNT_ARGS_IN_C_ARRAY_PLUS_RECEIVER: {\n VALUE* ary = new VALUE[args.total()];\n\n for (std::size_t i = 0; i < args.total(); ++i) {\n ary[i] = env->get_handle(args.get_argument(i));\n }\n\n VALUE ret = functor_as<ArgcFunctor>()(args.total(), ary, receiver);\n\n delete[] ary;\n\n return env->get_object(ret);\n }\n\n \/*\n * Normal arg counts\n *\n * Yes, it is ugly as fuck. It is intended as an encouragement\n * to get rid of the concept of a separate VALUE and Object.\n *\/\n\n case 0: {\n OneArgFunctor functor = functor_as<OneArgFunctor>();\n\n VALUE ret = functor(receiver);\n\n return env->get_object(ret);\n }\n\n case 1: {\n TwoArgFunctor functor = functor_as<TwoArgFunctor>();\n\n VALUE a1 = env->get_handle(args.get_argument(0));\n\n VALUE ret = functor(receiver, a1);\n\n return env->get_object(ret);\n }\n\n case 2: {\n ThreeArgFunctor functor = functor_as<ThreeArgFunctor>();\n\n VALUE a1 = env->get_handle(args.get_argument(0));\n VALUE a2 = env->get_handle(args.get_argument(1));\n\n VALUE ret = functor(receiver, a1, a2);\n\n return env->get_object(ret);\n }\n\n case 3: {\n FourArgFunctor functor = functor_as<FourArgFunctor>();\n VALUE a1 = env->get_handle(args.get_argument(0));\n VALUE a2 = env->get_handle(args.get_argument(1));\n VALUE a3 = env->get_handle(args.get_argument(2));\n\n VALUE ret = functor(receiver, a1, a2, a3);\n\n return env->get_object(ret);\n }\n\n case 4: {\n FiveArgFunctor functor = functor_as<FiveArgFunctor>();\n VALUE a1 = env->get_handle(args.get_argument(0));\n VALUE a2 = env->get_handle(args.get_argument(1));\n VALUE a3 = env->get_handle(args.get_argument(2));\n VALUE a4 = env->get_handle(args.get_argument(3));\n\n VALUE ret = functor(receiver, a1, a2, a3, a4);\n\n return env->get_object(ret);\n }\n\n case 5: {\n SixArgFunctor functor = functor_as<SixArgFunctor>();\n VALUE a1 = env->get_handle(args.get_argument(0));\n VALUE a2 = env->get_handle(args.get_argument(1));\n VALUE a3 = env->get_handle(args.get_argument(2));\n VALUE a4 = env->get_handle(args.get_argument(3));\n VALUE a5 = env->get_handle(args.get_argument(4));\n\n VALUE ret = functor(receiver, a1, a2, a3, a4, a5);\n\n return env->get_object(ret);\n }\n\n \/* Extension entry point, should never occur for user code. *\/\n case INIT_FUNCTION: {\n InitFunctor functor = functor_as<InitFunctor>();\n\n functor();\n\n return Qnil;\n }\n\n default:\n capi::capi_raise_runtime_error(\"unrecognized arity for NativeMethod call\");\n return Qnil;\n }\n }\n\n}\n<commit_msg>Fixed saving call_frame through native calls (pair Evan).<commit_after>#include <iostream>\n\n#include \"vm.hpp\"\n\n#include \"exception.hpp\"\n#include \"exception_point.hpp\"\n#include \"arguments.hpp\"\n#include \"dispatch.hpp\"\n#include \"native_libraries.hpp\"\n#include \"primitives.hpp\"\n#include \"call_frame.hpp\"\n\n#include \"builtin\/array.hpp\"\n#include \"builtin\/exception.hpp\"\n#include \"builtin\/nativemethod.hpp\"\n#include \"builtin\/string.hpp\"\n#include \"builtin\/system.hpp\"\n#include \"builtin\/tuple.hpp\"\n#include \"builtin\/capi_handle.hpp\"\n\n#include \"instruments\/profiler.hpp\"\n\n#include \"capi\/capi.hpp\"\n#include \"capi\/handle.hpp\"\n\nnamespace rubinius {\n \/** Thread-local NativeMethodEnvironment instance. *\/\n thread::ThreadData<NativeMethodEnvironment*> native_method_environment;\n\n\/* Class methods *\/\n\n NativeMethodEnvironment* NativeMethodEnvironment::get() {\n return native_method_environment.get();\n }\n\n NativeMethodFrame::~NativeMethodFrame() {\n flush_cached_data(true);\n for(capi::HandleList::iterator i = handles_.begin();\n i != handles_.end();\n i++) {\n capi::Handle* handle = *i;\n handle->deref();\n }\n }\n\n VALUE NativeMethodFrame::get_handle(STATE, Object* obj) {\n capi::Handle* handle;\n\n Object* existing = obj->get_table_ivar(state, state->symbol(\"capi_handle\"));\n\n if(CApiHandle* wrapper = try_as<CApiHandle>(existing)) {\n handle = wrapper->handle;\n } else {\n handle = new capi::Handle(state, obj);\n state->shared.global_handles()->add(handle);\n CApiHandle* wrapper = CApiHandle::create(state, handle);\n obj->set_table_ivar(state, state->symbol(\"capi_handle\"), wrapper);\n }\n\n handle->ref();\n\n handles_.push_back(handle);\n return handle->as_value();\n }\n\n Object* NativeMethodFrame::get_object(VALUE val) {\n return capi::Handle::from(val)->object();\n }\n\n CApiStructs& NativeMethodFrame::strings() {\n if(!strings_) strings_ = new CApiStructs;\n return *strings_;\n }\n\n CApiStructs& NativeMethodFrame::arrays() {\n if(!arrays_) arrays_ = new CApiStructs;\n return *arrays_;\n }\n\n CApiStructs& NativeMethodFrame::data() {\n if(!data_) data_ = new CApiStructs;\n return *data_;\n }\n\n void NativeMethodFrame::flush_cached_data(bool release_memory) {\n NativeMethodEnvironment* env = NativeMethodEnvironment::get();\n\n for(capi::HandleList::iterator i = handles_.begin();\n i != handles_.end();\n i++) {\n capi::Handle* handle = *i;\n if(handle->is_rarray()) {\n capi::capi_get_array(env, handle->as_value());\n } else if(handle->is_rstring()) {\n capi::capi_get_string(env, handle->as_value());\n } else if(handle->is_rdata()) {\n capi::capi_rdata_flush_handle(env, handle);\n }\n\n if(release_memory) handle->free_data();\n }\n }\n\n void NativeMethodFrame::update_cached_data() {\n NativeMethodEnvironment* env = NativeMethodEnvironment::get();\n for(capi::HandleList::iterator i = handles_.begin();\n i != handles_.end();\n i++) {\n capi::Handle* handle = *i;\n if(handle->is_rarray()) {\n capi::capi_update_array(env, handle->as_value());\n } else if(handle->is_rstring()) {\n capi::capi_update_string(env, handle->as_value());\n }\n }\n }\n\n VALUE NativeMethodEnvironment::get_handle(Object* obj) {\n if(obj->reference_p()) {\n return current_native_frame_->get_handle(state_, obj);\n } else if(obj->fixnum_p() || obj->symbol_p()) {\n return reinterpret_cast<VALUE>(obj);\n } else if(obj->nil_p()) {\n return cCApiHandleQnil;\n } else if(obj->false_p()) {\n return cCApiHandleQfalse;\n } else if(obj->true_p()) {\n return cCApiHandleQtrue;\n } else if(obj->undef_p()) {\n return cCApiHandleQundef;\n }\n\n capi::capi_raise_runtime_error(\"NativeMethod handle requested for unknown object type\");\n return 0; \/\/ keep compiler happy\n }\n\n Object* NativeMethodEnvironment::get_object(VALUE val) {\n if(CAPI_REFERENCE_P(val)) {\n return capi::Handle::from(val)->object();\n \/*\n if(CAPI_GLOBAL_HANDLE_P(handle)) {\n Handles& global_handles = state_->shared.global_handles();\n size_t index = CAPI_STRIP_GLOBAL_TAG(handle);\n if(unlikely(index >= global_handles.size())) {\n capi_raise_runtime_error(\"requested Object for invalid NativeMethod global handle\");\n }\n\n RootHandle* root = global_handles[index];\n\n if(unlikely(!root)) {\n capi_raise_runtime_error(\"Attempted to use deleted NativeMethod global handle\");\n }\n\n Object* obj = root->get();\n if(unlikely(!obj)) {\n capi_raise_runtime_error(\"NativeMethod global handle refers to NULL object\");\n }\n return obj;\n } else {\n return current_native_frame_->get_object(handle);\n }\n *\/\n } else if(FIXNUM_P(val) || SYMBOL_P(val)) {\n return reinterpret_cast<Object*>(val);\n } else if(CAPI_FALSE_P(val)) {\n return Qfalse;\n } else if(CAPI_TRUE_P(val)) {\n return Qtrue;\n } else if(CAPI_NIL_P(val)) {\n return Qnil;\n } else if(CAPI_UNDEF_P(val)) {\n return Qundef;\n }\n\n capi::capi_raise_runtime_error(\"requested Object for unknown NativeMethod handle type\");\n return Qnil; \/\/ keep compiler happy\n }\n\n void NativeMethodEnvironment::delete_global(VALUE val) {\n abort();\n }\n\n Object* NativeMethodEnvironment::block() {\n return current_call_frame_->top_scope->block();\n }\n\n capi::HandleList& NativeMethodEnvironment::handles() {\n return current_native_frame_->handles();\n }\n\n CApiStructs& NativeMethodEnvironment::strings() {\n return current_native_frame_->strings();\n }\n\n CApiStructs& NativeMethodEnvironment::arrays() {\n return current_native_frame_->arrays();\n }\n\n CApiStructs& NativeMethodEnvironment::data() {\n return current_native_frame_->data();\n }\n\n void NativeMethodEnvironment::flush_cached_data(bool release_memory) {\n current_native_frame_->flush_cached_data(release_memory);\n }\n\n void NativeMethodEnvironment::update_cached_data() {\n current_native_frame_->update_cached_data();\n }\n\n void NativeMethod::init(STATE) {\n state->globals.nmethod.set(state->new_class(\"NativeMethod\", G(executable), G(rubinius)));\n state->globals.nmethod.get()->set_object_type(state, NativeMethodType);\n\n init_thread(state);\n }\n\n void NativeMethod::init_thread(STATE) {\n NativeMethodEnvironment* env = new NativeMethodEnvironment;\n env->set_state(state);\n native_method_environment.set(env);\n }\n\n NativeMethod* NativeMethod::allocate(STATE) {\n return create<GenericFunctor>(state);\n }\n\n Object* NativeMethod::executor_implementation(STATE,\n CallFrame* call_frame, Dispatch& msg, Arguments& args) {\n NativeMethod* nm = as<NativeMethod>(msg.method);\n\n int arity = nm->arity()->to_int();\n if(arity >= 0 && (size_t)arity != args.total()) {\n Exception* exc = Exception::make_argument_error(\n state, arity, args.total(), msg.name);\n exc->locations(state, System::vm_backtrace(state, Fixnum::from(1), call_frame));\n state->thread_state()->raise_exception(exc);\n\n return NULL;\n }\n\n NativeMethodEnvironment* env = native_method_environment.get();\n NativeMethodFrame nmf(env->current_native_frame());\n\n CallFrame* saved_frame = env->current_call_frame();\n env->set_current_call_frame(call_frame);\n env->set_current_native_frame(&nmf);\n\n Object* ret;\n ExceptionPoint ep(env);\n\n PLACE_EXCEPTION_POINT(ep);\n\n if(unlikely(ep.jumped_to())) {\n ret = NULL;\n } else {\n#ifdef RBX_PROFILER\n if(unlikely(state->shared.profiling())) {\n profiler::MethodEntry method(state, msg, args);\n ret = nm->call(state, env, args);\n } else {\n ret = nm->call(state, env, args);\n }\n#else\n ret = nm->call(state, env, args);\n#endif\n }\n\n env->set_current_call_frame(saved_frame);\n env->set_current_native_frame(nmf.previous());\n ep.pop(env);\n\n return ret;\n }\n\n NativeMethod* NativeMethod::load_extension_entry_point(STATE, String* path, String* name) {\n void* func = NativeLibrary::find_symbol(state, name, path);\n\n NativeMethod* m = NativeMethod::create(state,\n path,\n state->globals.rubinius.get(),\n name->to_sym(state),\n reinterpret_cast<GenericFunctor>(func),\n Fixnum::from(INIT_FUNCTION)\n );\n return m;\n }\n\n \/**\n * Arity -3: VALUE func(VALUE argument_array);\n * Arity -2: VALUE func(VALUE receiver, VALUE argument_array);\n * Arity -1: VALUE func(int argument_count, VALUE*, VALUE receiver);\n * Otherwise: VALUE func(VALUE receiver, VALUE arg1[, VALUE arg2, ...]);\n *\n * There is also a special-case arity, INIT_FUNCTION, which corresponds\n * to void (*)(void) and should never appear in user code.\n *\n * @note Currently supports functions with up to receiver + 5 (separate) arguments only!\n * Anything beyond that should use one of the special arities instead.\n *\n * @todo Check for inefficiencies.\n *\/\n Object* NativeMethod::call(STATE, NativeMethodEnvironment* env, Arguments& args) {\n VALUE receiver = env->get_handle(args.recv());\n\n switch(arity()->to_int()) {\n case ARGS_IN_RUBY_ARRAY: { \/* Braces required to create objects in a switch *\/\n VALUE ary = env->get_handle(args.as_array(state));\n\n VALUE ret = functor_as<OneArgFunctor>()(ary);\n\n return env->get_object(ret);\n }\n\n case RECEIVER_PLUS_ARGS_IN_RUBY_ARRAY: {\n VALUE ary = env->get_handle(args.as_array(state));\n\n VALUE ret = functor_as<TwoArgFunctor>()(receiver, ary);\n\n return env->get_object(ret);\n }\n\n case ARG_COUNT_ARGS_IN_C_ARRAY_PLUS_RECEIVER: {\n VALUE* ary = new VALUE[args.total()];\n\n for (std::size_t i = 0; i < args.total(); ++i) {\n ary[i] = env->get_handle(args.get_argument(i));\n }\n\n VALUE ret = functor_as<ArgcFunctor>()(args.total(), ary, receiver);\n\n delete[] ary;\n\n return env->get_object(ret);\n }\n\n \/*\n * Normal arg counts\n *\n * Yes, it is ugly as fuck. It is intended as an encouragement\n * to get rid of the concept of a separate VALUE and Object.\n *\/\n\n case 0: {\n OneArgFunctor functor = functor_as<OneArgFunctor>();\n\n VALUE ret = functor(receiver);\n\n return env->get_object(ret);\n }\n\n case 1: {\n TwoArgFunctor functor = functor_as<TwoArgFunctor>();\n\n VALUE a1 = env->get_handle(args.get_argument(0));\n\n VALUE ret = functor(receiver, a1);\n\n return env->get_object(ret);\n }\n\n case 2: {\n ThreeArgFunctor functor = functor_as<ThreeArgFunctor>();\n\n VALUE a1 = env->get_handle(args.get_argument(0));\n VALUE a2 = env->get_handle(args.get_argument(1));\n\n VALUE ret = functor(receiver, a1, a2);\n\n return env->get_object(ret);\n }\n\n case 3: {\n FourArgFunctor functor = functor_as<FourArgFunctor>();\n VALUE a1 = env->get_handle(args.get_argument(0));\n VALUE a2 = env->get_handle(args.get_argument(1));\n VALUE a3 = env->get_handle(args.get_argument(2));\n\n VALUE ret = functor(receiver, a1, a2, a3);\n\n return env->get_object(ret);\n }\n\n case 4: {\n FiveArgFunctor functor = functor_as<FiveArgFunctor>();\n VALUE a1 = env->get_handle(args.get_argument(0));\n VALUE a2 = env->get_handle(args.get_argument(1));\n VALUE a3 = env->get_handle(args.get_argument(2));\n VALUE a4 = env->get_handle(args.get_argument(3));\n\n VALUE ret = functor(receiver, a1, a2, a3, a4);\n\n return env->get_object(ret);\n }\n\n case 5: {\n SixArgFunctor functor = functor_as<SixArgFunctor>();\n VALUE a1 = env->get_handle(args.get_argument(0));\n VALUE a2 = env->get_handle(args.get_argument(1));\n VALUE a3 = env->get_handle(args.get_argument(2));\n VALUE a4 = env->get_handle(args.get_argument(3));\n VALUE a5 = env->get_handle(args.get_argument(4));\n\n VALUE ret = functor(receiver, a1, a2, a3, a4, a5);\n\n return env->get_object(ret);\n }\n\n \/* Extension entry point, should never occur for user code. *\/\n case INIT_FUNCTION: {\n InitFunctor functor = functor_as<InitFunctor>();\n\n functor();\n\n return Qnil;\n }\n\n default:\n capi::capi_raise_runtime_error(\"unrecognized arity for NativeMethod call\");\n return Qnil;\n }\n }\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n** Copyright 2011-2013 Centreon\n**\n** Licensed under the Apache License, Version 2.0 (the \"License\");\n** you may not use this file except in compliance with the License.\n** You may obtain a copy of the License at\n**\n** http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n**\n** Unless required by applicable law or agreed to in writing, software\n** distributed under the License is distributed on an \"AS IS\" BASIS,\n** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n** See the License for the specific language governing permissions and\n** limitations under the License.\n**\n** For more information : contact@centreon.com\n*\/\n\n#include <unistd.h>\n#include <sys\/socket.h>\n#include <set>\n#include \"com\/centreon\/broker\/exceptions\/msg.hh\"\n#include \"com\/centreon\/broker\/watchdog\/configuration_parser.hh\"\n#include \"com\/centreon\/broker\/watchdog\/application.hh\"\n#include \"com\/centreon\/broker\/logging\/logging.hh\"\n#include \"com\/centreon\/broker\/logging\/manager.hh\"\n\nusing namespace com::centreon::broker;\nusing namespace com::centreon::broker::watchdog;\n\nint application::sighup_fd[2];\nint application::sigterm_fd[2];\n\n\/**\n * Constructor.\n *\n * @param[in] config_file The config file.\n *\/\napplication::application(std::string const& config_file)\n : _config_path(config_file) {\n \/\/ Init the socketpairs used for signal handling.\n if (::socketpair(AF_UNIX, SOCK_STREAM, 0, sighup_fd) != 0\n || ::socketpair(AF_UNIX, SOCK_STREAM, 0, sigterm_fd) != 0)\n throw (exceptions::msg() << \"watchdog: couldn't init the socketpairs\");\n _sighup.reset(new QSocketNotifier(sighup_fd[1], QSocketNotifier::Read, this));\n connect(_sighup.get(), SIGNAL(activated(int)), this, SLOT(handle_sighup()));\n _sigterm.reset(new QSocketNotifier(sigterm_fd[1], QSocketNotifier::Read, this));\n connect(_sigterm.get(), SIGNAL(activated(int)), this, SLOT(handle_sigterm()));\n\n _init();\n}\n\n\/**\n * Destructor.\n *\/\napplication::~application() {\n for (std::map<std::string, instance*>::iterator\n it = _instances.begin(),\n end = _instances.end();\n it != end;\n ++it)\n delete it->second;\n\n logging::manager::unload();\n}\n\n\/**\n * Handle sighup.\n *\/\nvoid application::handle_sighup() {\n _sighup->setEnabled(false);\n char tmp;\n ::read(sighup_fd[1], &tmp, sizeof(tmp));\n\n configuration config;\n try {\n configuration_parser parser;\n config = parser.parse(_config_path);\n } catch (std::exception const& e) {\n logging::error(logging::medium)\n << \"watchdog: couldn't parse the new configuration: \" << e.what();\n _sighup->setEnabled(true);\n return;\n }\n\n _apply_new_configuration(config);\n _sighup->setEnabled(true);\n}\n\n\/**\n * Handle sigterm.\n *\/\nvoid application::handle_sigterm() {\n _sigterm->setEnabled(false);\n char tmp;\n ::read(sigterm_fd[1], &tmp, sizeof(tmp));\n\n _quit();\n\n _sigterm->setEnabled(true);\n}\n\n\/**\n * Initialize the application.\n *\/\nvoid application::_init() {\n \/\/ Parse the configuration.\n configuration_parser parser;\n configuration config = parser.parse(_config_path);\n\n \/\/ Load the log manager.\n logging::manager::load();\n\n \/\/ Apply the configuration.\n _apply_new_configuration(config);\n}\n\n\/**\n * Apply a new configuration.\n *\n * @param[in] config The new configuration.\n *\/\nvoid application::_apply_new_configuration(configuration const& config) {\n \/\/ Create the log file backend if needed.\n if (_config.get_log_filename() != config.get_log_filename()) {\n _log.reset(new logging::file(\n QString::fromStdString(config.get_log_filename())));\n logging::manager::instance().log_on(*_log);\n }\n\n std::set<std::string> to_update;\n std::set<std::string> to_delete;\n std::set<std::string> to_create;\n\n \/\/ Old configs that aren't present in the new should be deleted and recreated.\n \/\/ Old configs that are present in the new should be updated.\n for (configuration::instance_map::const_iterator\n it = _config.get_instances_configuration().begin(),\n end = _config.get_instances_configuration().end();\n it != end;\n ++it) {\n instance_configuration new_config\n = config.get_instance_configuration(it->first);\n if (new_config != it->second) {\n to_delete.insert(it->first);\n to_create.insert(it->first);\n }\n else\n to_update.insert(it->first);\n }\n\n \/\/ New configs that aren't present in the old should be created.\n for (configuration::instance_map::const_iterator\n it = config.get_instances_configuration().begin(),\n end = config.get_instances_configuration().end();\n it != end;\n ++it)\n if (!_config.instance_exists(it->first))\n to_create.insert(it->first);\n\n \/\/ Delete old processes.\n for (std::set<std::string>::const_iterator\n it = to_delete.begin(),\n end = to_delete.end();\n it != end;\n ++it) {\n std::map<std::string, instance*>::iterator found = _instances.find(*it);\n if (found != _instances.end()) {\n delete found->second;\n _instances.erase(found);\n }\n }\n\n \/\/ Update processes.\n for (std::set<std::string>::const_iterator\n it = to_update.begin(),\n end = to_update.end();\n it != end;\n ++it) {\n std::map<std::string, instance*>::iterator found = _instances.find(*it);\n if (found != _instances.end()) {\n found->second->merge_configuration(\n config.get_instance_configuration(*it));\n found->second->update_instance();\n }\n }\n\n \/\/ Start new processes.\n for (std::set<std::string>::const_iterator\n it = to_create.begin(),\n end = to_create.end();\n it != end;\n ++it) {\n std::auto_ptr<instance> ins(\n new instance(config.get_instance_configuration(*it), *this));\n _instances.insert(std::make_pair(*it, ins.release()));\n }\n\n \/\/ Save the new configuration.\n _config = config;\n}\n\n\/**\n * Quit the application and subinstances.\n *\/\nvoid application::_quit() {\n logging::info(logging::medium)\n << \"watchdog: exiting\";\n for (std::map<std::string, instance*>::iterator\n it = _instances.begin(),\n end = _instances.end();\n it != end;\n ++it)\n it->second->stop_instance();\n exit();\n}\n<commit_msg>Watchdog: fix bad logic.<commit_after>\/*\n** Copyright 2011-2013 Centreon\n**\n** Licensed under the Apache License, Version 2.0 (the \"License\");\n** you may not use this file except in compliance with the License.\n** You may obtain a copy of the License at\n**\n** http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n**\n** Unless required by applicable law or agreed to in writing, software\n** distributed under the License is distributed on an \"AS IS\" BASIS,\n** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n** See the License for the specific language governing permissions and\n** limitations under the License.\n**\n** For more information : contact@centreon.com\n*\/\n\n#include <unistd.h>\n#include <sys\/socket.h>\n#include <set>\n#include \"com\/centreon\/broker\/exceptions\/msg.hh\"\n#include \"com\/centreon\/broker\/watchdog\/configuration_parser.hh\"\n#include \"com\/centreon\/broker\/watchdog\/application.hh\"\n#include \"com\/centreon\/broker\/logging\/logging.hh\"\n#include \"com\/centreon\/broker\/logging\/manager.hh\"\n\nusing namespace com::centreon::broker;\nusing namespace com::centreon::broker::watchdog;\n\nint application::sighup_fd[2];\nint application::sigterm_fd[2];\n\n\/**\n * Constructor.\n *\n * @param[in] config_file The config file.\n *\/\napplication::application(std::string const& config_file)\n : _config_path(config_file) {\n \/\/ Init the socketpairs used for signal handling.\n if (::socketpair(AF_UNIX, SOCK_STREAM, 0, sighup_fd) != 0\n || ::socketpair(AF_UNIX, SOCK_STREAM, 0, sigterm_fd) != 0)\n throw (exceptions::msg() << \"watchdog: couldn't init the socketpairs\");\n _sighup.reset(new QSocketNotifier(sighup_fd[1], QSocketNotifier::Read, this));\n connect(_sighup.get(), SIGNAL(activated(int)), this, SLOT(handle_sighup()));\n _sigterm.reset(new QSocketNotifier(sigterm_fd[1], QSocketNotifier::Read, this));\n connect(_sigterm.get(), SIGNAL(activated(int)), this, SLOT(handle_sigterm()));\n\n _init();\n}\n\n\/**\n * Destructor.\n *\/\napplication::~application() {\n for (std::map<std::string, instance*>::iterator\n it = _instances.begin(),\n end = _instances.end();\n it != end;\n ++it)\n delete it->second;\n\n logging::manager::unload();\n}\n\n\/**\n * Handle sighup.\n *\/\nvoid application::handle_sighup() {\n _sighup->setEnabled(false);\n char tmp;\n ::read(sighup_fd[1], &tmp, sizeof(tmp));\n\n configuration config;\n try {\n configuration_parser parser;\n config = parser.parse(_config_path);\n } catch (std::exception const& e) {\n logging::error(logging::medium)\n << \"watchdog: couldn't parse the new configuration: \" << e.what();\n _sighup->setEnabled(true);\n return;\n }\n\n _apply_new_configuration(config);\n _sighup->setEnabled(true);\n}\n\n\/**\n * Handle sigterm.\n *\/\nvoid application::handle_sigterm() {\n _sigterm->setEnabled(false);\n char tmp;\n ::read(sigterm_fd[1], &tmp, sizeof(tmp));\n\n _quit();\n\n _sigterm->setEnabled(true);\n}\n\n\/**\n * Initialize the application.\n *\/\nvoid application::_init() {\n \/\/ Parse the configuration.\n configuration_parser parser;\n configuration config = parser.parse(_config_path);\n\n \/\/ Load the log manager.\n logging::manager::load();\n\n \/\/ Apply the configuration.\n _apply_new_configuration(config);\n}\n\n\/**\n * Apply a new configuration.\n *\n * @param[in] config The new configuration.\n *\/\nvoid application::_apply_new_configuration(configuration const& config) {\n \/\/ Create the log file backend if needed.\n if (_config.get_log_filename() != config.get_log_filename()) {\n _log.reset(new logging::file(\n QString::fromStdString(config.get_log_filename())));\n logging::manager::instance().log_on(*_log);\n }\n\n std::set<std::string> to_update;\n std::set<std::string> to_delete;\n std::set<std::string> to_create;\n\n \/\/ Old configs that aren't present in the new should be deleted.\n \/\/ Old configs that are present in the new should be updated\n \/\/ or deleted\/recreated.\n for (configuration::instance_map::const_iterator\n it = _config.get_instances_configuration().begin(),\n end = _config.get_instances_configuration().end();\n it != end;\n ++it) {\n instance_configuration new_config\n = config.get_instance_configuration(it->first);\n if (new_config.is_empty())\n to_delete.insert(it->first);\n else if (new_config != it->second) {\n to_delete.insert(it->first);\n to_create.insert(it->first);\n }\n else\n to_update.insert(it->first);\n }\n\n \/\/ New configs that aren't present in the old should be created.\n for (configuration::instance_map::const_iterator\n it = config.get_instances_configuration().begin(),\n end = config.get_instances_configuration().end();\n it != end;\n ++it)\n if (!_config.instance_exists(it->first))\n to_create.insert(it->first);\n\n \/\/ Delete old processes.\n for (std::set<std::string>::const_iterator\n it = to_delete.begin(),\n end = to_delete.end();\n it != end;\n ++it) {\n std::map<std::string, instance*>::iterator found = _instances.find(*it);\n if (found != _instances.end()) {\n delete found->second;\n _instances.erase(found);\n }\n }\n\n \/\/ Update processes.\n for (std::set<std::string>::const_iterator\n it = to_update.begin(),\n end = to_update.end();\n it != end;\n ++it) {\n std::map<std::string, instance*>::iterator found = _instances.find(*it);\n if (found != _instances.end()) {\n found->second->merge_configuration(\n config.get_instance_configuration(*it));\n found->second->update_instance();\n }\n }\n\n \/\/ Start new processes.\n for (std::set<std::string>::const_iterator\n it = to_create.begin(),\n end = to_create.end();\n it != end;\n ++it) {\n std::auto_ptr<instance> ins(\n new instance(config.get_instance_configuration(*it), *this));\n _instances.insert(std::make_pair(*it, ins.release()));\n }\n\n \/\/ Save the new configuration.\n _config = config;\n}\n\n\/**\n * Quit the application and subinstances.\n *\/\nvoid application::_quit() {\n logging::info(logging::medium)\n << \"watchdog: exiting\";\n for (std::map<std::string, instance*>::iterator\n it = _instances.begin(),\n end = _instances.end();\n it != end;\n ++it)\n it->second->stop_instance();\n exit();\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/--------------------------------------------------------------------*- C++ -*-\n\/\/ CLING - the C++ LLVM-based InterpreterG :)\n\/\/ version: $Id$\n\/\/ author: Axel Naumann <axel@cern.ch>\n\/\/------------------------------------------------------------------------------\n\n#include \"cling\/Interpreter\/CIFactory.h\"\n\n#include \"DeclCollector.h\"\n\n#include \"clang\/AST\/ASTContext.h\"\n#include \"clang\/Basic\/TargetInfo.h\"\n#include \"clang\/Basic\/Version.h\"\n#include \"clang\/Driver\/ArgList.h\"\n#include \"clang\/Driver\/Compilation.h\"\n#include \"clang\/Driver\/Driver.h\"\n#include \"clang\/Driver\/Job.h\"\n#include \"clang\/Driver\/Tool.h\"\n#include \"clang\/Frontend\/TextDiagnosticPrinter.h\"\n#include \"clang\/Lex\/Preprocessor.h\"\n\n#include \"llvm\/LLVMContext.h\"\n#include \"llvm\/Target\/TargetOptions.h\"\n#include \"llvm\/Support\/Host.h\"\n#include \"llvm\/Support\/TargetSelect.h\"\n#include \"llvm\/Support\/MemoryBuffer.h\"\n#include \"llvm\/Support\/Path.h\"\n\nusing namespace clang;\n\nnamespace cling {\n \/\/\n \/\/ Dummy function so we can use dladdr to find the executable path.\n \/\/\n void locate_cling_executable()\n {\n }\n\n \/\/\/ \\brief Retrieves the clang CC1 specific flags out of the compilation's\n \/\/\/ jobs. Returns NULL on error.\n static const clang::driver::ArgStringList\n *GetCC1Arguments(clang::DiagnosticsEngine *Diagnostics,\n clang::driver::Compilation *Compilation) {\n \/\/ We expect to get back exactly one Command job, if we didn't something\n \/\/ failed. Extract that job from the Compilation.\n const clang::driver::JobList &Jobs = Compilation->getJobs();\n if (!Jobs.size() || !isa<clang::driver::Command>(*Jobs.begin())) {\n \/\/ diagnose this...\n return NULL;\n }\n\n \/\/ The one job we find should be to invoke clang again.\n const clang::driver::Command *Cmd\n = cast<clang::driver::Command>(*Jobs.begin());\n if (llvm::StringRef(Cmd->getCreator().getName()) != \"clang\") {\n \/\/ diagnose this...\n return NULL;\n }\n\n return &Cmd->getArguments();\n }\n\n CompilerInstance* CIFactory::createCI(llvm::StringRef code,\n int argc,\n const char* const *argv,\n const char* llvmdir) {\n return createCI(llvm::MemoryBuffer::getMemBuffer(code), argc, argv,\n llvmdir);\n }\n\n CompilerInstance* CIFactory::createCI(llvm::MemoryBuffer* buffer,\n int argc,\n const char* const *argv,\n const char* llvmdir) {\n \/\/ Create an instance builder, passing the llvmdir and arguments.\n \/\/\n \/\/ Initialize the llvm library.\n llvm::InitializeNativeTarget();\n llvm::InitializeAllAsmPrinters();\n llvm::sys::Path resource_path;\n if (llvmdir) {\n resource_path = llvmdir;\n resource_path.appendComponent(\"lib\");\n resource_path.appendComponent(\"clang\");\n resource_path.appendComponent(CLANG_VERSION_STRING);\n } else {\n \/\/ FIXME: The first arg really does need to be argv[0] on FreeBSD.\n \/\/\n \/\/ Note: The second arg is not used for Apple, FreeBSD, Linux,\n \/\/ or cygwin, and can only be used on systems which support\n \/\/ the use of dladdr().\n \/\/\n \/\/ Note: On linux and cygwin this uses \/proc\/self\/exe to find the path.\n \/\/\n \/\/ Note: On Apple it uses _NSGetExecutablePath().\n \/\/\n \/\/ Note: On FreeBSD it uses getprogpath().\n \/\/\n \/\/ Note: Otherwise it uses dladdr().\n \/\/\n resource_path\n = CompilerInvocation::GetResourcesPath(\"cling\",\n (void*)(intptr_t) locate_cling_executable\n );\n }\n if (!resource_path.canRead()) {\n llvm::errs()\n << \"ERROR in cling::CIFactory::createCI():\\n resource directory \"\n << resource_path.str() << \" not found!\\n\";\n resource_path = \"\";\n }\n\n \/\/______________________________________\n DiagnosticOptions DefaultDiagnosticOptions;\n DefaultDiagnosticOptions.ShowColors = 1;\n TextDiagnosticPrinter* DiagnosticPrinter\n = new TextDiagnosticPrinter(llvm::errs(), DefaultDiagnosticOptions);\n llvm::IntrusiveRefCntPtr<clang::DiagnosticIDs> DiagIDs(new DiagnosticIDs());\n DiagnosticsEngine* Diagnostics\n = new DiagnosticsEngine(DiagIDs, DiagnosticPrinter,\n \/*Owns it*\/ true); \/\/ LEAKS!\n\n std::vector<const char*> argvCompile(argv, argv + argc);\n \/\/ We do C++ by default; append right after argv[0] name\n \/\/ Only insert it if there is no other \"-x\":\n bool haveMinusX = false;\n for (const char* const* iarg = argv; !haveMinusX && iarg < argv + argc;\n ++iarg) {\n haveMinusX = !strcmp(*iarg, \"-x\");\n }\n if (!haveMinusX) {\n argvCompile.insert(argvCompile.begin() + 1,\"-x\");\n argvCompile.insert(argvCompile.begin() + 2, \"c++\");\n }\n argvCompile.push_back(\"-c\");\n argvCompile.push_back(\"-\");\n\n bool IsProduction = false;\n assert(IsProduction = true && \"set IsProduction if asserts are on.\");\n clang::driver::Driver Driver(argv[0], llvm::sys::getDefaultTargetTriple(),\n \"cling.out\",\n IsProduction,\n *Diagnostics);\n \/\/Driver.setWarnMissingInput(false);\n Driver.setCheckInputsExist(false); \/\/ think foo.C(12)\n llvm::ArrayRef<const char*>RF(&(argvCompile[0]), argvCompile.size());\n llvm::OwningPtr<clang::driver::Compilation>\n Compilation(Driver.BuildCompilation(RF));\n const clang::driver::ArgStringList* CC1Args\n = GetCC1Arguments(Diagnostics, Compilation.get());\n if (CC1Args == NULL) {\n return 0;\n }\n clang::CompilerInvocation*\n Invocation = new clang::CompilerInvocation; \/\/ LEAKS!\n clang::CompilerInvocation::CreateFromArgs(*Invocation, CC1Args->data() + 1,\n CC1Args->data() + CC1Args->size(),\n *Diagnostics);\n Invocation->getFrontendOpts().DisableFree = true;\n\n if (Invocation->getHeaderSearchOpts().UseBuiltinIncludes &&\n !resource_path.empty()) {\n \/\/ Update ResourceDir\n \/\/ header search opts' entry for resource_path\/include isn't\n \/\/ updated by providing a new resource path; update it manually.\n clang::HeaderSearchOptions& Opts = Invocation->getHeaderSearchOpts();\n llvm::sys::Path oldResInc(Opts.ResourceDir);\n oldResInc.appendComponent(\"include\");\n llvm::sys::Path newResInc(resource_path);\n newResInc.appendComponent(\"include\");\n bool foundOldResInc = false;\n for (unsigned i = 0, e = Opts.UserEntries.size();\n !foundOldResInc && i != e; ++i) {\n HeaderSearchOptions::Entry &E = Opts.UserEntries[i];\n if (!E.IsUserSupplied && !E.IsFramework\n && E.Group == clang::frontend::System && E.IgnoreSysRoot\n && E.IsInternal && !E.ImplicitExternC\n && oldResInc.str() == E.Path) {\n E.Path = newResInc.str();\n foundOldResInc = true;\n }\n }\n\n Opts.ResourceDir = resource_path.str();\n }\n\n \/\/ Create and setup a compiler instance.\n CompilerInstance* CI = new CompilerInstance();\n CI->setInvocation(Invocation);\n\n CI->createDiagnostics(CC1Args->size(), CC1Args->data() + 1);\n {\n \/\/\n \/\/ Buffer the error messages while we process\n \/\/ the compiler options.\n \/\/\n\n \/\/ Set the language options, which cling needs\n SetClingCustomLangOpts(CI->getLangOpts());\n\n CI->getInvocation().getPreprocessorOpts().addMacroDef(\"__CLING__\");\n if (CI->getDiagnostics().hasErrorOccurred()) {\n delete CI;\n CI = 0;\n return 0;\n }\n }\n CI->setTarget(TargetInfo::CreateTargetInfo(CI->getDiagnostics(),\n Invocation->getTargetOpts()));\n if (!CI->hasTarget()) {\n delete CI;\n CI = 0;\n return 0;\n }\n CI->getTarget().setForcedLangOptions(CI->getLangOpts());\n SetClingTargetLangOpts(CI->getLangOpts(), CI->getTarget());\n\n \/\/ Set up source and file managers\n CI->createFileManager();\n CI->createSourceManager(CI->getFileManager());\n\n \/\/ Set up the memory buffer\n if (buffer)\n CI->getSourceManager().createMainFileIDForMemBuffer(buffer);\n\n \/\/ Set up the preprocessor\n CI->createPreprocessor();\n Preprocessor& PP = CI->getPreprocessor();\n PP.getBuiltinInfo().InitializeBuiltins(PP.getIdentifierTable(),\n PP.getLangOpts());\n\n \/\/ Set up the ASTContext\n ASTContext *Ctx = new ASTContext(CI->getLangOpts(),\n PP.getSourceManager(), &CI->getTarget(),\n PP.getIdentifierTable(),\n PP.getSelectorTable(), PP.getBuiltinInfo(),\n \/*size_reserve*\/0, \/*DelayInit*\/false);\n CI->setASTContext(Ctx);\n\n \/\/ Set up the ASTConsumers\n CI->setASTConsumer(new DeclCollector());\n\n \/\/ Set up Sema\n CodeCompleteConsumer* CCC = 0;\n CI->createSema(TU_Prefix, CCC);\n\n \/\/ Set CodeGen options\n \/\/ CI->getCodeGenOpts().DebugInfo = 1; \/\/ want debug info\n \/\/ CI->getCodeGenOpts().EmitDeclMetadata = 1; \/\/ For unloading, for later\n CI->getCodeGenOpts().OptimizationLevel = 0; \/\/ see pure SSA, that comes out\n \/\/ When asserts are on, TURN ON not compare the VerifyModule\n assert(CI->getCodeGenOpts().VerifyModule = 1);\n return CI;\n }\n\n void CIFactory::SetClingCustomLangOpts(LangOptions& Opts) {\n Opts.EmitAllDecls = 1;\n Opts.Exceptions = 1;\n Opts.CXXExceptions = 1;\n Opts.Deprecated = 1;\n }\n\n void CIFactory::SetClingTargetLangOpts(LangOptions& Opts,\n const TargetInfo& Target) {\n if (Target.getTriple().getOS() == llvm::Triple::Win32) {\n Opts.MicrosoftExt = 1;\n Opts.MSCVersion = 1300;\n \/\/ Should fix http:\/\/llvm.org\/bugs\/show_bug.cgi?id=10528\n Opts.DelayedTemplateParsing = 1;\n } else {\n Opts.MicrosoftExt = 0;\n }\n }\n} \/\/ end namespace\n<commit_msg>Enable Modules by default for cling.<commit_after>\/\/--------------------------------------------------------------------*- C++ -*-\n\/\/ CLING - the C++ LLVM-based InterpreterG :)\n\/\/ version: $Id$\n\/\/ author: Axel Naumann <axel@cern.ch>\n\/\/------------------------------------------------------------------------------\n\n#include \"cling\/Interpreter\/CIFactory.h\"\n\n#include \"DeclCollector.h\"\n\n#include \"clang\/AST\/ASTContext.h\"\n#include \"clang\/Basic\/TargetInfo.h\"\n#include \"clang\/Basic\/Version.h\"\n#include \"clang\/Driver\/ArgList.h\"\n#include \"clang\/Driver\/Compilation.h\"\n#include \"clang\/Driver\/Driver.h\"\n#include \"clang\/Driver\/Job.h\"\n#include \"clang\/Driver\/Tool.h\"\n#include \"clang\/Frontend\/TextDiagnosticPrinter.h\"\n#include \"clang\/Lex\/Preprocessor.h\"\n\n#include \"llvm\/LLVMContext.h\"\n#include \"llvm\/Target\/TargetOptions.h\"\n#include \"llvm\/Support\/Host.h\"\n#include \"llvm\/Support\/TargetSelect.h\"\n#include \"llvm\/Support\/MemoryBuffer.h\"\n#include \"llvm\/Support\/Path.h\"\n\nusing namespace clang;\n\nnamespace cling {\n \/\/\n \/\/ Dummy function so we can use dladdr to find the executable path.\n \/\/\n void locate_cling_executable()\n {\n }\n\n \/\/\/ \\brief Retrieves the clang CC1 specific flags out of the compilation's\n \/\/\/ jobs. Returns NULL on error.\n static const clang::driver::ArgStringList\n *GetCC1Arguments(clang::DiagnosticsEngine *Diagnostics,\n clang::driver::Compilation *Compilation) {\n \/\/ We expect to get back exactly one Command job, if we didn't something\n \/\/ failed. Extract that job from the Compilation.\n const clang::driver::JobList &Jobs = Compilation->getJobs();\n if (!Jobs.size() || !isa<clang::driver::Command>(*Jobs.begin())) {\n \/\/ diagnose this...\n return NULL;\n }\n\n \/\/ The one job we find should be to invoke clang again.\n const clang::driver::Command *Cmd\n = cast<clang::driver::Command>(*Jobs.begin());\n if (llvm::StringRef(Cmd->getCreator().getName()) != \"clang\") {\n \/\/ diagnose this...\n return NULL;\n }\n\n return &Cmd->getArguments();\n }\n\n CompilerInstance* CIFactory::createCI(llvm::StringRef code,\n int argc,\n const char* const *argv,\n const char* llvmdir) {\n return createCI(llvm::MemoryBuffer::getMemBuffer(code), argc, argv,\n llvmdir);\n }\n\n CompilerInstance* CIFactory::createCI(llvm::MemoryBuffer* buffer,\n int argc,\n const char* const *argv,\n const char* llvmdir) {\n \/\/ Create an instance builder, passing the llvmdir and arguments.\n \/\/\n \/\/ Initialize the llvm library.\n llvm::InitializeNativeTarget();\n llvm::InitializeAllAsmPrinters();\n llvm::sys::Path resource_path;\n if (llvmdir) {\n resource_path = llvmdir;\n resource_path.appendComponent(\"lib\");\n resource_path.appendComponent(\"clang\");\n resource_path.appendComponent(CLANG_VERSION_STRING);\n } else {\n \/\/ FIXME: The first arg really does need to be argv[0] on FreeBSD.\n \/\/\n \/\/ Note: The second arg is not used for Apple, FreeBSD, Linux,\n \/\/ or cygwin, and can only be used on systems which support\n \/\/ the use of dladdr().\n \/\/\n \/\/ Note: On linux and cygwin this uses \/proc\/self\/exe to find the path.\n \/\/\n \/\/ Note: On Apple it uses _NSGetExecutablePath().\n \/\/\n \/\/ Note: On FreeBSD it uses getprogpath().\n \/\/\n \/\/ Note: Otherwise it uses dladdr().\n \/\/\n resource_path\n = CompilerInvocation::GetResourcesPath(\"cling\",\n (void*)(intptr_t) locate_cling_executable\n );\n }\n if (!resource_path.canRead()) {\n llvm::errs()\n << \"ERROR in cling::CIFactory::createCI():\\n resource directory \"\n << resource_path.str() << \" not found!\\n\";\n resource_path = \"\";\n }\n\n \/\/______________________________________\n DiagnosticOptions DefaultDiagnosticOptions;\n DefaultDiagnosticOptions.ShowColors = 1;\n TextDiagnosticPrinter* DiagnosticPrinter\n = new TextDiagnosticPrinter(llvm::errs(), DefaultDiagnosticOptions);\n llvm::IntrusiveRefCntPtr<clang::DiagnosticIDs> DiagIDs(new DiagnosticIDs());\n DiagnosticsEngine* Diagnostics\n = new DiagnosticsEngine(DiagIDs, DiagnosticPrinter,\n \/*Owns it*\/ true); \/\/ LEAKS!\n\n std::vector<const char*> argvCompile(argv, argv + argc);\n \/\/ We do C++ by default; append right after argv[0] name\n \/\/ Only insert it if there is no other \"-x\":\n bool haveMinusX = false;\n for (const char* const* iarg = argv; !haveMinusX && iarg < argv + argc;\n ++iarg) {\n haveMinusX = !strcmp(*iarg, \"-x\");\n }\n if (!haveMinusX) {\n argvCompile.insert(argvCompile.begin() + 1,\"-x\");\n argvCompile.insert(argvCompile.begin() + 2, \"c++\");\n }\n argvCompile.push_back(\"-c\");\n argvCompile.push_back(\"-\");\n\n bool IsProduction = false;\n assert(IsProduction = true && \"set IsProduction if asserts are on.\");\n clang::driver::Driver Driver(argv[0], llvm::sys::getDefaultTargetTriple(),\n \"cling.out\",\n IsProduction,\n *Diagnostics);\n \/\/Driver.setWarnMissingInput(false);\n Driver.setCheckInputsExist(false); \/\/ think foo.C(12)\n llvm::ArrayRef<const char*>RF(&(argvCompile[0]), argvCompile.size());\n llvm::OwningPtr<clang::driver::Compilation>\n Compilation(Driver.BuildCompilation(RF));\n const clang::driver::ArgStringList* CC1Args\n = GetCC1Arguments(Diagnostics, Compilation.get());\n if (CC1Args == NULL) {\n return 0;\n }\n clang::CompilerInvocation*\n Invocation = new clang::CompilerInvocation; \/\/ LEAKS!\n clang::CompilerInvocation::CreateFromArgs(*Invocation, CC1Args->data() + 1,\n CC1Args->data() + CC1Args->size(),\n *Diagnostics);\n Invocation->getFrontendOpts().DisableFree = true;\n\n if (Invocation->getHeaderSearchOpts().UseBuiltinIncludes &&\n !resource_path.empty()) {\n \/\/ Update ResourceDir\n \/\/ header search opts' entry for resource_path\/include isn't\n \/\/ updated by providing a new resource path; update it manually.\n clang::HeaderSearchOptions& Opts = Invocation->getHeaderSearchOpts();\n llvm::sys::Path oldResInc(Opts.ResourceDir);\n oldResInc.appendComponent(\"include\");\n llvm::sys::Path newResInc(resource_path);\n newResInc.appendComponent(\"include\");\n bool foundOldResInc = false;\n for (unsigned i = 0, e = Opts.UserEntries.size();\n !foundOldResInc && i != e; ++i) {\n HeaderSearchOptions::Entry &E = Opts.UserEntries[i];\n if (!E.IsUserSupplied && !E.IsFramework\n && E.Group == clang::frontend::System && E.IgnoreSysRoot\n && E.IsInternal && !E.ImplicitExternC\n && oldResInc.str() == E.Path) {\n E.Path = newResInc.str();\n foundOldResInc = true;\n }\n }\n\n Opts.ResourceDir = resource_path.str();\n }\n\n \/\/ Create and setup a compiler instance.\n CompilerInstance* CI = new CompilerInstance();\n CI->setInvocation(Invocation);\n\n CI->createDiagnostics(CC1Args->size(), CC1Args->data() + 1);\n {\n \/\/\n \/\/ Buffer the error messages while we process\n \/\/ the compiler options.\n \/\/\n\n \/\/ Set the language options, which cling needs\n SetClingCustomLangOpts(CI->getLangOpts());\n\n CI->getInvocation().getPreprocessorOpts().addMacroDef(\"__CLING__\");\n if (CI->getDiagnostics().hasErrorOccurred()) {\n delete CI;\n CI = 0;\n return 0;\n }\n }\n CI->setTarget(TargetInfo::CreateTargetInfo(CI->getDiagnostics(),\n Invocation->getTargetOpts()));\n if (!CI->hasTarget()) {\n delete CI;\n CI = 0;\n return 0;\n }\n CI->getTarget().setForcedLangOptions(CI->getLangOpts());\n SetClingTargetLangOpts(CI->getLangOpts(), CI->getTarget());\n\n \/\/ Set up source and file managers\n CI->createFileManager();\n CI->createSourceManager(CI->getFileManager());\n\n \/\/ Set up the memory buffer\n if (buffer)\n CI->getSourceManager().createMainFileIDForMemBuffer(buffer);\n\n \/\/ Set up the preprocessor\n CI->createPreprocessor();\n Preprocessor& PP = CI->getPreprocessor();\n PP.getBuiltinInfo().InitializeBuiltins(PP.getIdentifierTable(),\n PP.getLangOpts());\n\n \/\/ Set up the ASTContext\n ASTContext *Ctx = new ASTContext(CI->getLangOpts(),\n PP.getSourceManager(), &CI->getTarget(),\n PP.getIdentifierTable(),\n PP.getSelectorTable(), PP.getBuiltinInfo(),\n \/*size_reserve*\/0, \/*DelayInit*\/false);\n CI->setASTContext(Ctx);\n\n \/\/ Set up the ASTConsumers\n CI->setASTConsumer(new DeclCollector());\n\n \/\/ Set up Sema\n CodeCompleteConsumer* CCC = 0;\n CI->createSema(TU_Prefix, CCC);\n\n \/\/ Set CodeGen options\n \/\/ CI->getCodeGenOpts().DebugInfo = 1; \/\/ want debug info\n \/\/ CI->getCodeGenOpts().EmitDeclMetadata = 1; \/\/ For unloading, for later\n CI->getCodeGenOpts().OptimizationLevel = 0; \/\/ see pure SSA, that comes out\n \/\/ When asserts are on, TURN ON not compare the VerifyModule\n assert(CI->getCodeGenOpts().VerifyModule = 1);\n return CI;\n }\n\n void CIFactory::SetClingCustomLangOpts(LangOptions& Opts) {\n Opts.EmitAllDecls = 1;\n Opts.Exceptions = 1;\n Opts.CXXExceptions = 1;\n Opts.Deprecated = 1;\n Opts.Modules = 1;\n }\n\n void CIFactory::SetClingTargetLangOpts(LangOptions& Opts,\n const TargetInfo& Target) {\n if (Target.getTriple().getOS() == llvm::Triple::Win32) {\n Opts.MicrosoftExt = 1;\n Opts.MSCVersion = 1300;\n \/\/ Should fix http:\/\/llvm.org\/bugs\/show_bug.cgi?id=10528\n Opts.DelayedTemplateParsing = 1;\n } else {\n Opts.MicrosoftExt = 0;\n }\n }\n} \/\/ end namespace\n<|endoftext|>"} {"text":"<commit_before>#ifndef K3_RUNTIME_BASETYPES_H\n#define K3_RUNTIME_BASETYPES_H\n\n#include \"boost\/functional\/hash.hpp\"\n#include \"serialization\/yaml.hpp\"\n\/\/ Basic types needed by our builtin libraries\n\nclass unit_t {\n public:\n template <class archive>\n void serialize(archive&, const unsigned int) {}\n bool operator==(const unit_t& r) const { return true; }\n bool operator!=(const unit_t& r) const { return false; }\n bool operator<(const unit_t& r) const { return false; }\n bool operator>(const unit_t& r) const { return false; }\n};\n\nnamespace YAML {\n template <>\n class convert<unit_t> {\n public:\n static Node encode(const unit_t& r) {\n Node node;\n return node;\n }\n static bool decode(const Node& node, unit_t& r) {\n return true;\n }\n };\n}\n\n\n#ifndef K3_R_addr\n#define K3_R_addr\ntemplate <class _T0>\nclass R_addr {\n public:\n R_addr() {}\n R_addr(_T0 _addr): addr(_addr) {}\n R_addr(const R_addr<_T0>& _r): addr(_r.addr) {}\n bool operator==(const R_addr& _r) const {\n if (addr == _r.addr)\n return true;\n return false;\n }\n bool operator!=(const R_addr& _r) const {\n return !(*this == _r);\n }\n bool operator<(const R_addr& _r) const {\n return addr < _r.addr;\n }\n template <class archive>\n void serialize(archive& _archive,const unsigned int) {\n _archive & addr;\n\n }\n _T0 addr;\n};\n\n#endif \/\/ K3_R_addr\n\n#ifndef K3_R_addr_hash_value\n#define K3_R_addr_hash_value\ntemplate <class T>\n std::size_t hash_value(R_addr<T> const& b) {\n boost::hash<T> hasher;\n return hasher(b.addr);\n}\n#endif \/\/ K3_R_addr_hash_value\n\n\n#ifndef K3_R_elem\n#define K3_R_elem\n\ntemplate <class _T0>\nclass R_elem {\n public:\n R_elem() {}\n R_elem(_T0 _elem): elem(_elem) {}\n R_elem(const R_elem<_T0>& _r): elem(_r.elem) {}\n bool operator==(const R_elem& _r) const {\n if (elem == _r.elem)\n return true;\n return false;\n }\n \/\/ TODO, beter implementation?\n bool operator!=(const R_elem& _r) const {\n return !(*this == _r);\n }\n bool operator<(const R_elem& _r) const {\n return elem < _r.elem;\n }\n template <class archive>\n void serialize(archive& _archive,const unsigned int) {\n _archive & elem;\n }\n _T0 elem;\n};\n#endif \/\/ K3_R_elem\n\n\n#ifndef K3_R_elem_hash_value\n#define K3_R_elem_hash_value\ntemplate <class T>\n std::size_t hash_value(R_elem<T> const& b) {\n boost::hash<T> hasher;\n return hasher(b.elem);\n}\n#endif \/\/ K3_R_elem_hash_value\n\n#ifndef K3_R_key_value\n#define K3_R_key_value\n\ntemplate <class _T0, class _T1>\nclass R_key_value {\n public:\n typedef _T0 KeyType;\n typedef _T1 ValueType;\n R_key_value(): key(), value() {}\n template <class __T0, class __T1>\n R_key_value(__T0&& _key, __T1&& _value): key(std::forward<__T0>(_key)),\n value(std::forward<__T1>(_value)) {}\n R_key_value(const R_key_value<_T0, _T1>& __other): key(__other.key), value(__other.value) {}\n R_key_value(R_key_value<_T0, _T1>&& __other): key(std::move(__other.key)),\n value(std::move(__other.value)) {}\n template <class archive>\n void serialize(archive& _archive, const unsigned int) {\n _archive & key;\n _archive & value;\n }\n R_key_value<_T0, _T1>& operator=(const R_key_value<_T0, _T1>& __other) {\n key = (__other.key);\n value = (__other.value);\n return *(this);\n }\n R_key_value<_T0, _T1>& operator=(R_key_value<_T0, _T1>&& __other) {\n key = std::move(__other.key);\n value = std::move(__other.value);\n return *(this);\n }\n bool operator==(const R_key_value<_T0, _T1>& __other) const {\n return key == (__other.key) && value == (__other.value);\n }\n bool operator!=(const R_key_value<_T0, _T1>& __other) const {\n return std::tie(key, value) != std::tie(__other.key, __other.value);\n }\n bool operator<(const R_key_value<_T0, _T1>& __other) const {\n return std::tie(key, value) < std::tie(__other.key, __other.value);\n }\n bool operator>(const R_key_value<_T0, _T1>& __other) const {\n return std::tie(key, value) > std::tie(__other.key, __other.value);\n }\n _T0 key;\n _T1 value;\n};\n\n#endif \/\/ K3_R_key_value\n\n#ifndef K3_R_key_value_hash_value\n#define K3_R_key_value_hash_value\ntemplate <class K,class V>\n std::size_t hash_value(R_key_value<K,V> const& b) {\n boost::hash<std::tuple<K,V>> hasher;\n return hasher(std::tie(b.key, b.value));\n}\n#endif \/\/ K3_R_key_value_hash_value\n\n\n#endif \/\/ K3_RUNTIME_BASETYPES_H\n<commit_msg>Warning cleanup in BaseTypes.<commit_after>#ifndef K3_RUNTIME_BASETYPES_H\n#define K3_RUNTIME_BASETYPES_H\n\n#include \"boost\/functional\/hash.hpp\"\n#include \"serialization\/yaml.hpp\"\n\/\/ Basic types needed by our builtin libraries\n\nclass unit_t {\n public:\n template <class archive>\n void serialize(archive&, const unsigned int) {}\n bool operator==(const unit_t&) const { return true; }\n bool operator!=(const unit_t&) const { return false; }\n bool operator<(const unit_t&) const { return false; }\n bool operator>(const unit_t&) const { return false; }\n};\n\nnamespace YAML {\n template <>\n struct convert<unit_t> {\n public:\n static Node encode(const unit_t&) {\n Node node;\n return node;\n }\n static bool decode(const Node&, unit_t&) {\n return true;\n }\n };\n}\n\n\n#ifndef K3_R_addr\n#define K3_R_addr\ntemplate <class _T0>\nclass R_addr {\n public:\n R_addr() {}\n R_addr(_T0 _addr): addr(_addr) {}\n R_addr(const R_addr<_T0>& _r): addr(_r.addr) {}\n bool operator==(const R_addr& _r) const {\n if (addr == _r.addr)\n return true;\n return false;\n }\n bool operator!=(const R_addr& _r) const {\n return !(*this == _r);\n }\n bool operator<(const R_addr& _r) const {\n return addr < _r.addr;\n }\n template <class archive>\n void serialize(archive& _archive,const unsigned int) {\n _archive & addr;\n\n }\n _T0 addr;\n};\n\n#endif \/\/ K3_R_addr\n\n#ifndef K3_R_addr_hash_value\n#define K3_R_addr_hash_value\ntemplate <class T>\n std::size_t hash_value(R_addr<T> const& b) {\n boost::hash<T> hasher;\n return hasher(b.addr);\n}\n#endif \/\/ K3_R_addr_hash_value\n\n\n#ifndef K3_R_elem\n#define K3_R_elem\n\ntemplate <class _T0>\nclass R_elem {\n public:\n R_elem() {}\n R_elem(_T0 _elem): elem(_elem) {}\n R_elem(const R_elem<_T0>& _r): elem(_r.elem) {}\n bool operator==(const R_elem& _r) const {\n if (elem == _r.elem)\n return true;\n return false;\n }\n \/\/ TODO, beter implementation?\n bool operator!=(const R_elem& _r) const {\n return !(*this == _r);\n }\n bool operator<(const R_elem& _r) const {\n return elem < _r.elem;\n }\n template <class archive>\n void serialize(archive& _archive,const unsigned int) {\n _archive & elem;\n }\n _T0 elem;\n};\n#endif \/\/ K3_R_elem\n\n\n#ifndef K3_R_elem_hash_value\n#define K3_R_elem_hash_value\ntemplate <class T>\n std::size_t hash_value(R_elem<T> const& b) {\n boost::hash<T> hasher;\n return hasher(b.elem);\n}\n#endif \/\/ K3_R_elem_hash_value\n\n#ifndef K3_R_key_value\n#define K3_R_key_value\n\ntemplate <class _T0, class _T1>\nclass R_key_value {\n public:\n typedef _T0 KeyType;\n typedef _T1 ValueType;\n R_key_value(): key(), value() {}\n template <class __T0, class __T1>\n R_key_value(__T0&& _key, __T1&& _value): key(std::forward<__T0>(_key)),\n value(std::forward<__T1>(_value)) {}\n R_key_value(const R_key_value<_T0, _T1>& __other): key(__other.key), value(__other.value) {}\n R_key_value(R_key_value<_T0, _T1>&& __other): key(std::move(__other.key)),\n value(std::move(__other.value)) {}\n template <class archive>\n void serialize(archive& _archive, const unsigned int) {\n _archive & key;\n _archive & value;\n }\n R_key_value<_T0, _T1>& operator=(const R_key_value<_T0, _T1>& __other) {\n key = (__other.key);\n value = (__other.value);\n return *(this);\n }\n R_key_value<_T0, _T1>& operator=(R_key_value<_T0, _T1>&& __other) {\n key = std::move(__other.key);\n value = std::move(__other.value);\n return *(this);\n }\n bool operator==(const R_key_value<_T0, _T1>& __other) const {\n return key == (__other.key) && value == (__other.value);\n }\n bool operator!=(const R_key_value<_T0, _T1>& __other) const {\n return std::tie(key, value) != std::tie(__other.key, __other.value);\n }\n bool operator<(const R_key_value<_T0, _T1>& __other) const {\n return std::tie(key, value) < std::tie(__other.key, __other.value);\n }\n bool operator>(const R_key_value<_T0, _T1>& __other) const {\n return std::tie(key, value) > std::tie(__other.key, __other.value);\n }\n _T0 key;\n _T1 value;\n};\n\n#endif \/\/ K3_R_key_value\n\n#ifndef K3_R_key_value_hash_value\n#define K3_R_key_value_hash_value\ntemplate <class K,class V>\n std::size_t hash_value(R_key_value<K,V> const& b) {\n boost::hash<std::tuple<K,V>> hasher;\n return hasher(std::tie(b.key, b.value));\n}\n#endif \/\/ K3_R_key_value_hash_value\n\n\n#endif \/\/ K3_RUNTIME_BASETYPES_H\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 2012,2017-2018 ARM Limited\n * All rights reserved\n *\n * The license below extends only to copyright in the software and shall\n * not be construed as granting a license to any other intellectual\n * property including but not limited to intellectual property relating\n * to a hardware implementation of the functionality of the software\n * licensed hereunder. You may use the software subject to the license\n * terms below provided that you ensure that this notice is replicated\n * unmodified and in its entirety in all distributions of the software,\n * modified or unmodified, in source code or in binary form.\n *\n * Copyright (c) 2006 The Regents of The University of Michigan\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met: redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer;\n * redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution;\n * neither the name of the copyright holders nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#ifndef __BASE_COMPILER_HH__\n#define __BASE_COMPILER_HH__\n\n#include <memory>\n\n#include \"config\/have_deprecated_namespace.hh\"\n\n\/\/ http:\/\/gcc.gnu.org\/onlinedocs\/gcc\/Function-Attributes.html\n\n\n\/*\n * Attributes that become standard in later versions of c++.\n *\/\n\n\/\/ When the return value of a function should not be discarded, mark it with\n\/\/ GEM5_NO_DISCARD.\n#if __has_cpp_attribute(nodiscard) \/\/ Standard in c++17, with message in c++20.\n# define GEM5_NO_DISCARD [[nodiscard]]\n#else\n\/\/ Not supported, but it's optional so we can just omit it.\n# define GEM5_NO_DISCARD\n#endif\n\n\/\/ When a variable may purposefully not be used, for instance if it's only used\n\/\/ in debug statements which might be disabled, mark it with GEM5_VAR_USED.\n#if __has_cpp_attribute(maybe_unused) \/\/ Standard in c++17.\n# define GEM5_VAR_USED [[maybe_unused]]\n#elif defined(__GNUC__)\n\/\/ gcc and clang support a custom attribute which is essentially the same\n\/\/ thing.\n# define GEM5_VAR_USED [[gnu::unused]]\n#else\n# error \"Don't know what to do for your compiler.\"\n#endif\n\n\n\/*\n * Compiler specific features.\n *\/\n\n#if defined(__GNUC__) \/\/ clang or gcc.\n\/\/ Mark a structure as packed, so that no padding is added to its layout. This\n\/\/ padding might be added to, for instance, ensure certain fields have certain\n\/\/ alignment.\n# define GEM5_PACKED [[gnu::packed]]\n\n\/\/ Prevent a function from being inlined.\n# define GEM5_NO_INLINE [[gnu::noinline]]\n\n\/\/ Set the visibility of a symbol.\n# define GEM5_PUBLIC [[gnu:visibility(\"default\")]]\n# define GEM5_LOCAL [[gnu::visibility(\"hidden\")]]\n# define GEM5_WEAK [[gnu::weak]]\n\n\/\/ Force an alignment for a variable.\n# define GEM5_ALIGNED(alignment) [[gnu::aligned(alignment)]]\n\n\/\/ Marker for what should be an unreachable point in the code.\n# define GEM5_UNREACHABLE __builtin_unreachable()\n\n\/\/ To mark a branch condition as likely taken, wrap it's condition with\n\/\/ GEM5_LIKELY. To mark it as likely not taken, wrap it's condition with\n\/\/ GEM5_UNLIKELY. These can be replaced with the standard attributes [[likely]]\n\/\/ and [[unlikely]] in c++20, although the syntax is different enough that\n\/\/ we can't do that with direct substitution.\n# define GEM5_LIKELY(cond) __builtin_expect(!!(cond), 1)\n# define GEM5_UNLIKELY(cond) __builtin_expect(!!(cond), 0)\n\n\/\/ Mark a c++ declaration as deprecated, with a message explaining what to do\n\/\/ to update to a non-deprecated alternative.\n# define GEM5_DEPRECATED(message) [[gnu::deprecated(message)]]\n\/\/ Mark a C++ emum value as deprecated, with a message explaining what to do\n\/\/ to update to a non-deprecated alternative. This wraps GEM5_DEPRECATED but\n\/\/ is guarded by a preprocessor if directive to ensure it is not included\n\/\/ when compiled in GCC < 6, as deprecation of enum values was introduced in\n\/\/ GCC 6. All supported clang compilers allow enum value deprecation.\n# if defined(__clang__) || __GNUC__ >= 6\n# define GEM5_DEPRECATED_ENUM_VAL(message) GEM5_DEPRECATED(message)\n# else\n# define GEM5_DEPRECATED_ENUM_VAL(message)\n# endif\n\/\/ Mark an expression-like macro as deprecated by wrapping it in some code\n\/\/ which declares and uses a deprecated variable with the same name as the\n\/\/ macro. The wrapping macro evaluates to the same thing as the original macro.\n\/\/ The definition must be an c++ expression and not a statement because of how\n\/\/ the original macro is wrapped.\n# define GEM5_DEPRECATED_MACRO(name, definition, message) \\\n ([](){GEM5_DEPRECATED(message) int name{}; return name;}(), (definition))\n\/\/ This version is for macros which are statement-like, which frequently use\n\/\/ \"do {} while (0)\" to make their syntax look more like normal c++ statements.\n# define GEM5_DEPRECATED_MACRO_STMT(name, definition, message) \\\n do {{definition;} GEM5_DEPRECATED_MACRO(name, {}, message);} while (0)\n\n\/\/ To mark a class as deprecated in favor of a new name, add a respective\n\/\/ instance of this macro to the file that used to declare the old name.\n\/\/ This macro should be used *after* the new class has been defined.\n# define GEM5_DEPRECATED_CLASS(old_class, new_class) \\\n using old_class \\\n GEM5_DEPRECATED(\"Please use the new class name: '\" #new_class \"'\") = \\\n new_class\n\n\/\/ These macros should be used when namespaces are deprecated in favor of\n\/\/ a new name. They should be used wherever the namespace is declared.\n\/\/ Namespace deprecation is broken for GNU < 10 [1], so there is no\n\/\/ deprecation warning in that case. Clang only supports it from C++17 on.\n\/\/ [1] https:\/\/gcc.gnu.org\/bugzilla\/show_bug.cgi?id=79817\n# if HAVE_DEPRECATED_NAMESPACE\n# define GEM5_DEPRECATED_NAMESPACE(old_namespace, new_namespace) \\\n namespace new_namespace {} \\\n namespace GEM5_DEPRECATED(\"Please use the new namespace: '\" \\\n #new_namespace \"'\") old_namespace { \\\n using namespace new_namespace; \\\n }\n# else\n# define GEM5_DEPRECATED_NAMESPACE(old_namespace, new_namespace) \\\n namespace new_namespace {} \\\n namespace old_namespace = new_namespace\n# endif\n\n\/\/ Evaluate an expanded parameter pack in order. Multiple arguments can be\n\/\/ passed in which be evaluated in order relative to each other as a group.\n\/\/ The argument(s) must include a parameter pack to expand. This works because\n\/\/ the elements of a brace inclosed initializer list are evaluated in order,\n\/\/ as are the arguments to the comma operator, which evaluates to the last\n\/\/ value. This is compiler specific because it uses variadic macros.\n#define GEM5_FOR_EACH_IN_PACK(...) \\\ndo { GEM5_VAR_USED int i[] = { 0, ((void)(__VA_ARGS__), 0)... }; } while (0)\n\n#else\n# error \"Don't know what to do for your compiler.\"\n#endif\n\n\/\/ When a member variable may be unused, mark it with GEM5_CLASS_VAR_USED. This\n\/\/ needs to be limitted to clang only since clang warns on these unused\n\/\/ variables, and g++ will actually warn if you use this attribute since it\n\/\/ won't do anything there.\n#if defined(__clang__) \/\/ clang only.\n# define GEM5_CLASS_VAR_USED GEM5_VAR_USED\n#else\n# define GEM5_CLASS_VAR_USED\n#endif\n\n\/\/ Aliases for macros using the deprecated M5 prefix.\n#define M5_VAR_USED GEM5_VAR_USED\n#define M5_NODISCARD GEM5_NO_DISCARD\n#define M5_FALLTHROUGH GEM5_FALLTHROUGH\n#define M5_ATTR_PACKED GEM5_PACKED\n#define M5_NO_INLINE GEM5_NO_INLINE\n#define M5_PUBLIC GEM5_PUBLIC\n#define M5_LOCAL GEM5_LOCAL\n#define M5_WEAK GEM5_WEAK\n#define M5_ALIGNED(x) GEM5_ALIGNED(x)\n#define M5_UNREACHABLE GEM5_UNREACHABLE\n#define M5_LIKELY(x) GEM5_LIKELY(x)\n#define M5_UNLIKELY(x) GEM5_UNLIKELY(x)\n#define M5_FOR_EACH_IN_PACK(...) GEM5_FOR_EACH_IN_PACK(__VA_ARGS__)\n#define M5_CLASS_VAR_USED GEM5_CLASS_VAR_USED\n\n#define GEM5_FALLTHROUGH GEM5_DEPRECATED_MACRO_STMT(GEM5_FALLTHROUGH,,\\\n \"Please use the [[fallthrough]] attribute directly.\"); [[fallthrough]]\n\n#endif \/\/ __BASE_COMPILER_HH__\n<commit_msg>base: Deprecate the GEM5_DEPRECATED macro.<commit_after>\/*\n * Copyright (c) 2012,2017-2018 ARM Limited\n * All rights reserved\n *\n * The license below extends only to copyright in the software and shall\n * not be construed as granting a license to any other intellectual\n * property including but not limited to intellectual property relating\n * to a hardware implementation of the functionality of the software\n * licensed hereunder. You may use the software subject to the license\n * terms below provided that you ensure that this notice is replicated\n * unmodified and in its entirety in all distributions of the software,\n * modified or unmodified, in source code or in binary form.\n *\n * Copyright (c) 2006 The Regents of The University of Michigan\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met: redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer;\n * redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution;\n * neither the name of the copyright holders nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#ifndef __BASE_COMPILER_HH__\n#define __BASE_COMPILER_HH__\n\n#include <memory>\n\n#include \"config\/have_deprecated_namespace.hh\"\n\n\/\/ http:\/\/gcc.gnu.org\/onlinedocs\/gcc\/Function-Attributes.html\n\n\n\/*\n * Attributes that become standard in later versions of c++.\n *\/\n\n\/\/ When the return value of a function should not be discarded, mark it with\n\/\/ GEM5_NO_DISCARD.\n#if __has_cpp_attribute(nodiscard) \/\/ Standard in c++17, with message in c++20.\n# define GEM5_NO_DISCARD [[nodiscard]]\n#else\n\/\/ Not supported, but it's optional so we can just omit it.\n# define GEM5_NO_DISCARD\n#endif\n\n\/\/ When a variable may purposefully not be used, for instance if it's only used\n\/\/ in debug statements which might be disabled, mark it with GEM5_VAR_USED.\n#if __has_cpp_attribute(maybe_unused) \/\/ Standard in c++17.\n# define GEM5_VAR_USED [[maybe_unused]]\n#elif defined(__GNUC__)\n\/\/ gcc and clang support a custom attribute which is essentially the same\n\/\/ thing.\n# define GEM5_VAR_USED [[gnu::unused]]\n#else\n# error \"Don't know what to do for your compiler.\"\n#endif\n\n\n\/*\n * Compiler specific features.\n *\/\n\n#if defined(__GNUC__) \/\/ clang or gcc.\n\/\/ Mark a structure as packed, so that no padding is added to its layout. This\n\/\/ padding might be added to, for instance, ensure certain fields have certain\n\/\/ alignment.\n# define GEM5_PACKED [[gnu::packed]]\n\n\/\/ Prevent a function from being inlined.\n# define GEM5_NO_INLINE [[gnu::noinline]]\n\n\/\/ Set the visibility of a symbol.\n# define GEM5_PUBLIC [[gnu:visibility(\"default\")]]\n# define GEM5_LOCAL [[gnu::visibility(\"hidden\")]]\n# define GEM5_WEAK [[gnu::weak]]\n\n\/\/ Force an alignment for a variable.\n# define GEM5_ALIGNED(alignment) [[gnu::aligned(alignment)]]\n\n\/\/ Marker for what should be an unreachable point in the code.\n# define GEM5_UNREACHABLE __builtin_unreachable()\n\n\/\/ To mark a branch condition as likely taken, wrap it's condition with\n\/\/ GEM5_LIKELY. To mark it as likely not taken, wrap it's condition with\n\/\/ GEM5_UNLIKELY. These can be replaced with the standard attributes [[likely]]\n\/\/ and [[unlikely]] in c++20, although the syntax is different enough that\n\/\/ we can't do that with direct substitution.\n# define GEM5_LIKELY(cond) __builtin_expect(!!(cond), 1)\n# define GEM5_UNLIKELY(cond) __builtin_expect(!!(cond), 0)\n\n\/\/ Mark a C++ emum value as deprecated, with a message explaining what to do\n\/\/ to update to a non-deprecated alternative. This wraps GEM5_DEPRECATED but\n\/\/ is guarded by a preprocessor if directive to ensure it is not included\n\/\/ when compiled in GCC < 6, as deprecation of enum values was introduced in\n\/\/ GCC 6. All supported clang compilers allow enum value deprecation.\n# if defined(__clang__) || __GNUC__ >= 6\n# define GEM5_DEPRECATED_ENUM_VAL(message) [[deprecated(message)]]\n# else\n# define GEM5_DEPRECATED_ENUM_VAL(message)\n# endif\n\/\/ Mark an expression-like macro as deprecated by wrapping it in some code\n\/\/ which declares and uses a deprecated variable with the same name as the\n\/\/ macro. The wrapping macro evaluates to the same thing as the original macro.\n\/\/ The definition must be an c++ expression and not a statement because of how\n\/\/ the original macro is wrapped.\n# define GEM5_DEPRECATED_MACRO(name, definition, message) \\\n ([](){[[deprecated(message)]] int name{}; return name;}(), (definition))\n\/\/ This version is for macros which are statement-like, which frequently use\n\/\/ \"do {} while (0)\" to make their syntax look more like normal c++ statements.\n# define GEM5_DEPRECATED_MACRO_STMT(name, definition, message) \\\n do {{definition;} GEM5_DEPRECATED_MACRO(name, {}, message);} while (0)\n\n\/\/ To mark a class as deprecated in favor of a new name, add a respective\n\/\/ instance of this macro to the file that used to declare the old name.\n\/\/ This macro should be used *after* the new class has been defined.\n# define GEM5_DEPRECATED_CLASS(old_class, new_class) \\\n using old_class \\\n [[deprecated(\"Please use the new class name: '\" #new_class \"'\")]] = \\\n new_class\n\n\/\/ These macros should be used when namespaces are deprecated in favor of\n\/\/ a new name. They should be used wherever the namespace is declared.\n\/\/ Namespace deprecation is broken for GNU < 10 [1], so there is no\n\/\/ deprecation warning in that case. Clang only supports it from C++17 on.\n\/\/ [1] https:\/\/gcc.gnu.org\/bugzilla\/show_bug.cgi?id=79817\n# if HAVE_DEPRECATED_NAMESPACE\n# define GEM5_DEPRECATED_NAMESPACE(old_namespace, new_namespace) \\\n namespace new_namespace {} \\\n namespace [[deprecated(\"Please use the new namespace: '\" \\\n #new_namespace \"'\")]] old_namespace { \\\n using namespace new_namespace; \\\n }\n# else\n# define GEM5_DEPRECATED_NAMESPACE(old_namespace, new_namespace) \\\n namespace new_namespace {} \\\n namespace old_namespace = new_namespace\n# endif\n\n\/\/ Evaluate an expanded parameter pack in order. Multiple arguments can be\n\/\/ passed in which be evaluated in order relative to each other as a group.\n\/\/ The argument(s) must include a parameter pack to expand. This works because\n\/\/ the elements of a brace inclosed initializer list are evaluated in order,\n\/\/ as are the arguments to the comma operator, which evaluates to the last\n\/\/ value. This is compiler specific because it uses variadic macros.\n#define GEM5_FOR_EACH_IN_PACK(...) \\\ndo { GEM5_VAR_USED int i[] = { 0, ((void)(__VA_ARGS__), 0)... }; } while (0)\n\n#else\n# error \"Don't know what to do for your compiler.\"\n#endif\n\n\/\/ When a member variable may be unused, mark it with GEM5_CLASS_VAR_USED. This\n\/\/ needs to be limitted to clang only since clang warns on these unused\n\/\/ variables, and g++ will actually warn if you use this attribute since it\n\/\/ won't do anything there.\n#if defined(__clang__) \/\/ clang only.\n# define GEM5_CLASS_VAR_USED GEM5_VAR_USED\n#else\n# define GEM5_CLASS_VAR_USED\n#endif\n\n\/\/ Aliases for macros using the deprecated M5 prefix.\n#define M5_VAR_USED GEM5_VAR_USED\n#define M5_NODISCARD GEM5_NO_DISCARD\n#define M5_FALLTHROUGH GEM5_FALLTHROUGH\n#define M5_ATTR_PACKED GEM5_PACKED\n#define M5_NO_INLINE GEM5_NO_INLINE\n#define M5_PUBLIC GEM5_PUBLIC\n#define M5_LOCAL GEM5_LOCAL\n#define M5_WEAK GEM5_WEAK\n#define M5_ALIGNED(x) GEM5_ALIGNED(x)\n#define M5_UNREACHABLE GEM5_UNREACHABLE\n#define M5_LIKELY(x) GEM5_LIKELY(x)\n#define M5_UNLIKELY(x) GEM5_UNLIKELY(x)\n#define M5_FOR_EACH_IN_PACK(...) GEM5_FOR_EACH_IN_PACK(__VA_ARGS__)\n#define M5_CLASS_VAR_USED GEM5_CLASS_VAR_USED\n\n#define GEM5_FALLTHROUGH GEM5_DEPRECATED_MACRO_STMT(GEM5_FALLTHROUGH,,\\\n \"Please use the [[fallthrough]] attribute directly.\"); [[fallthrough]]\n#define GEM5_DEPRECATED(message) \\\n [[deprecated(message \" The GEM5_DEPRECATED macro is also deprecated, \"\\\n \"please use the [[deprecated()]] attribute directly.\")]]\n\n#endif \/\/ __BASE_COMPILER_HH__\n<|endoftext|>"} {"text":"<commit_before>\/\/===-- sanitizer_allocator_testlib.cc ------------------------------------===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ Malloc replacement library based on CombinedAllocator.\n\/\/ The primary purpose of this file is an end-to-end integration test\n\/\/ for CombinedAllocator.\n\/\/===----------------------------------------------------------------------===\/\/\n\/* Usage:\nclang++ -fno-exceptions -g -fPIC -I. -I..\/include -Isanitizer \\\n sanitizer_common\/tests\/sanitizer_allocator_testlib.cc \\\n sanitizer_common\/sanitizer_*.cc -shared -lpthread -o testmalloc.so\nLD_PRELOAD=`pwd`\/testmalloc.so \/your\/app\n*\/\n#include \"sanitizer_common\/sanitizer_allocator.h\"\n#include \"sanitizer_common\/sanitizer_common.h\"\n#include <stddef.h>\n#include <stdio.h>\n#include <unistd.h>\n#include <string.h>\n#include <pthread.h>\n\n#ifndef SANITIZER_MALLOC_HOOK\n# define SANITIZER_MALLOC_HOOK(p, s)\n#endif\n\n#ifndef SANITIZER_FREE_HOOK\n# define SANITIZER_FREE_HOOK(p)\n#endif\n\nnamespace {\nstatic const uptr kAllocatorSpace = 0x600000000000ULL;\nstatic const uptr kAllocatorSize = 0x10000000000ULL; \/\/ 1T.\n\ntypedef SizeClassAllocator64<kAllocatorSpace, kAllocatorSize, 0,\n CompactSizeClassMap> PrimaryAllocator;\ntypedef SizeClassAllocatorLocalCache<PrimaryAllocator> AllocatorCache;\ntypedef LargeMmapAllocator<> SecondaryAllocator;\ntypedef CombinedAllocator<PrimaryAllocator, AllocatorCache,\n SecondaryAllocator> Allocator;\n\nstatic Allocator allocator;\nstatic THREADLOCAL AllocatorCache cache;\nstatic THREADLOCAL bool global_inited;\nstatic THREADLOCAL bool thread_inited;\nstatic pthread_key_t pkey;\n\nstatic void thread_dtor(void *v) {\n if ((long)v != 3) {\n pthread_setspecific(pkey, (void*)((long)v + 1));\n return;\n }\n allocator.SwallowCache(&cache);\n}\n\nstatic void NOINLINE thread_init() {\n if (!global_inited) {\n global_inited = true;\n allocator.Init();\n pthread_key_create(&pkey, thread_dtor);\n }\n thread_inited = true;\n pthread_setspecific(pkey, (void*)1);\n cache.Init();\n}\n} \/\/ namespace\n\nextern \"C\" {\n\nvoid *malloc(size_t size) {\n if (UNLIKELY(!thread_inited))\n thread_init();\n void *p = allocator.Allocate(&cache, size, 8);\n SANITIZER_MALLOC_HOOK(p, size);\n return p;\n}\n\nvoid free(void *p) {\n if (UNLIKELY(!thread_inited))\n thread_init();\n SANITIZER_FREE_HOOK(p);\n allocator.Deallocate(&cache, p);\n}\n\nvoid *calloc(size_t nmemb, size_t size) {\n if (UNLIKELY(!thread_inited))\n thread_init();\n size *= nmemb;\n void *p = allocator.Allocate(&cache, size, 8, false);\n memset(p, 0, size);\n SANITIZER_MALLOC_HOOK(p, size);\n return p;\n}\n\nvoid *realloc(void *p, size_t size) {\n if (UNLIKELY(!thread_inited))\n thread_init();\n if (p) {\n SANITIZER_FREE_HOOK(p);\n }\n p = allocator.Reallocate(&cache, p, size, 8);\n if (p) {\n SANITIZER_MALLOC_HOOK(p, size);\n }\n return p;\n}\n\nvoid *memalign(size_t alignment, size_t size) {\n if (UNLIKELY(!thread_inited))\n thread_init();\n void *p = allocator.Allocate(&cache, size, alignment);\n SANITIZER_MALLOC_HOOK(p, size);\n return p;\n}\n\nint posix_memalign(void **memptr, size_t alignment, size_t size) {\n if (UNLIKELY(!thread_inited))\n thread_init();\n *memptr = allocator.Allocate(&cache, size, alignment);\n SANITIZER_MALLOC_HOOK(*memptr, size);\n return 0;\n}\n\nvoid *valloc(size_t size) {\n if (UNLIKELY(!thread_inited))\n thread_init();\n if (size == 0)\n size = GetPageSizeCached();\n void *p = allocator.Allocate(&cache, size, GetPageSizeCached());\n SANITIZER_MALLOC_HOOK(p, size);\n return p;\n}\n\nvoid cfree(void *p) ALIAS(\"free\");\nvoid *pvalloc(size_t size) ALIAS(\"valloc\");\nvoid *__libc_memalign(size_t alignment, size_t size) ALIAS(\"memalign\");\n\nvoid malloc_usable_size() {\n}\n\nvoid mallinfo() {\n}\n\nvoid mallopt() {\n}\n\n} \/\/ extern \"C\"\n<commit_msg>asan: fix lint warnings<commit_after>\/\/===-- sanitizer_allocator_testlib.cc ------------------------------------===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ Malloc replacement library based on CombinedAllocator.\n\/\/ The primary purpose of this file is an end-to-end integration test\n\/\/ for CombinedAllocator.\n\/\/===----------------------------------------------------------------------===\/\/\n\/* Usage:\nclang++ -fno-exceptions -g -fPIC -I. -I..\/include -Isanitizer \\\n sanitizer_common\/tests\/sanitizer_allocator_testlib.cc \\\n sanitizer_common\/sanitizer_*.cc -shared -lpthread -o testmalloc.so\nLD_PRELOAD=`pwd`\/testmalloc.so \/your\/app\n*\/\n#include \"sanitizer_common\/sanitizer_allocator.h\"\n#include \"sanitizer_common\/sanitizer_common.h\"\n#include <stddef.h>\n#include <stdio.h>\n#include <unistd.h>\n#include <string.h>\n#include <pthread.h>\n\n#ifndef SANITIZER_MALLOC_HOOK\n# define SANITIZER_MALLOC_HOOK(p, s)\n#endif\n\n#ifndef SANITIZER_FREE_HOOK\n# define SANITIZER_FREE_HOOK(p)\n#endif\n\nnamespace {\nstatic const uptr kAllocatorSpace = 0x600000000000ULL;\nstatic const uptr kAllocatorSize = 0x10000000000ULL; \/\/ 1T.\n\ntypedef SizeClassAllocator64<kAllocatorSpace, kAllocatorSize, 0,\n CompactSizeClassMap> PrimaryAllocator;\ntypedef SizeClassAllocatorLocalCache<PrimaryAllocator> AllocatorCache;\ntypedef LargeMmapAllocator<> SecondaryAllocator;\ntypedef CombinedAllocator<PrimaryAllocator, AllocatorCache,\n SecondaryAllocator> Allocator;\n\nstatic Allocator allocator;\nstatic THREADLOCAL AllocatorCache cache;\nstatic THREADLOCAL bool global_inited;\nstatic THREADLOCAL bool thread_inited;\nstatic pthread_key_t pkey;\n\nstatic void thread_dtor(void *v) {\n if ((uptr)v != 3) {\n pthread_setspecific(pkey, (void*)((uptr)v + 1));\n return;\n }\n allocator.SwallowCache(&cache);\n}\n\nstatic void NOINLINE thread_init() {\n if (!global_inited) {\n global_inited = true;\n allocator.Init();\n pthread_key_create(&pkey, thread_dtor);\n }\n thread_inited = true;\n pthread_setspecific(pkey, (void*)1);\n cache.Init();\n}\n} \/\/ namespace\n\nextern \"C\" {\nvoid *malloc(size_t size) {\n if (UNLIKELY(!thread_inited))\n thread_init();\n void *p = allocator.Allocate(&cache, size, 8);\n SANITIZER_MALLOC_HOOK(p, size);\n return p;\n}\n\nvoid free(void *p) {\n if (UNLIKELY(!thread_inited))\n thread_init();\n SANITIZER_FREE_HOOK(p);\n allocator.Deallocate(&cache, p);\n}\n\nvoid *calloc(size_t nmemb, size_t size) {\n if (UNLIKELY(!thread_inited))\n thread_init();\n size *= nmemb;\n void *p = allocator.Allocate(&cache, size, 8, false);\n memset(p, 0, size);\n SANITIZER_MALLOC_HOOK(p, size);\n return p;\n}\n\nvoid *realloc(void *p, size_t size) {\n if (UNLIKELY(!thread_inited))\n thread_init();\n if (p) {\n SANITIZER_FREE_HOOK(p);\n }\n p = allocator.Reallocate(&cache, p, size, 8);\n if (p) {\n SANITIZER_MALLOC_HOOK(p, size);\n }\n return p;\n}\n\nvoid *memalign(size_t alignment, size_t size) {\n if (UNLIKELY(!thread_inited))\n thread_init();\n void *p = allocator.Allocate(&cache, size, alignment);\n SANITIZER_MALLOC_HOOK(p, size);\n return p;\n}\n\nint posix_memalign(void **memptr, size_t alignment, size_t size) {\n if (UNLIKELY(!thread_inited))\n thread_init();\n *memptr = allocator.Allocate(&cache, size, alignment);\n SANITIZER_MALLOC_HOOK(*memptr, size);\n return 0;\n}\n\nvoid *valloc(size_t size) {\n if (UNLIKELY(!thread_inited))\n thread_init();\n if (size == 0)\n size = GetPageSizeCached();\n void *p = allocator.Allocate(&cache, size, GetPageSizeCached());\n SANITIZER_MALLOC_HOOK(p, size);\n return p;\n}\n\nvoid cfree(void *p) ALIAS(\"free\");\nvoid *pvalloc(size_t size) ALIAS(\"valloc\");\nvoid *__libc_memalign(size_t alignment, size_t size) ALIAS(\"memalign\");\n\nvoid malloc_usable_size() {\n}\n\nvoid mallinfo() {\n}\n\nvoid mallopt() {\n}\n} \/\/ extern \"C\"\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2011 Sirikata Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can\n\/\/ be found in the LICENSE file.\n\n#ifndef _SIRIKATA_CORE_RECORD_SST_STREAM_HPP_\n#define _SIRIKATA_CORE_RECORD_SST_STREAM_HPP_\n\n#include <sirikata\/core\/util\/Platform.hpp>\n#include <sirikata\/core\/network\/Frame.hpp>\n#include <sirikata\/core\/util\/Liveness.hpp>\n#include <sirikata\/core\/util\/Time.hpp>\n\nnamespace Sirikata {\n\n\/** RecordSSTStream wraps a regular SST stream, turning it into a record-based\n * stream, i.e. performing buffering and triggering callbacks for each record\n * rather than for each set of received bytes. This is useful for reliable,\n * message-oriented protocols. The user submits individual records to be sent\n * and it uses simple framing to identify the records at the receiver.\n *\/\ntemplate<typename StreamPtrType>\nclass RecordSSTStream : public Liveness {\npublic:\n typedef std::tr1::function<void(MemoryReference)> RecordCallback;\n\n RecordSSTStream() {}\n ~RecordSSTStream() {\n destroy();\n }\n\n void initialize(StreamPtrType stream, RecordCallback cb) {\n mStream = stream;\n mCB = cb;\n\n using std::tr1::placeholders::_1;\n using std::tr1::placeholders::_2;\n\n assert(mStream);\n mStream->registerReadCallback(\n std::tr1::bind(\n &RecordSSTStream::handleRead, this,\n _1, _2\n )\n );\n }\n\n void write(const MemoryReference& data) {\n outstanding.push(Network::Frame::write(data.begin(), data.size()));\n writeSomeData(livenessToken());\n }\n\n void destroy() {\n letDie();\n\n if (!mStream) return;\n mStream->registerReadCallback(0);\n }\nprivate:\n void handleRead(uint8* data, int size) {\n partial_frame.append((const char*)data, size);\n while(true) {\n String parsed = Network::Frame::parse(partial_frame);\n if (parsed.empty()) return;\n mCB( MemoryReference(parsed) );\n }\n }\n\n void writeSomeData(Liveness::Token alive) {\n if (!alive) return;\n\n static Duration retry_rate = Duration::milliseconds((int64)1);\n\n writing = true;\n\n if (!mStream) {\n \/\/ We're still waiting on the stream. Initialization should trigger\n \/\/ writing if it gets a stream and there's data waiting.\n writing = false;\n return;\n }\n\n \/\/ Otherwise, keep sending until we run out or\n while(!outstanding.empty()) {\n std::string& framed_msg = outstanding.front();\n int bytes_written = mStream->write((const uint8*)framed_msg.data(), framed_msg.size());\n if (bytes_written < 0) {\n \/\/ FIXME\n break;\n }\n else if (bytes_written < (int)framed_msg.size()) {\n framed_msg = framed_msg.substr(bytes_written);\n break;\n }\n else {\n outstanding.pop();\n }\n }\n\n if (outstanding.empty())\n writing = false;\n else\n mStream->getContext()->mainStrand->post(\n retry_rate,\n std::tr1::bind(&RecordSSTStream::writeSomeData, this, alive),\n \"RecordSSTStream::writeSomeData\"\n );\n }\n\n StreamPtrType mStream;\n RecordCallback mCB;\n\n \/\/ Outstanding data to be sent. FIXME efficiency\n std::queue<std::string> outstanding;\n \/\/ If writing is currently in progress\n bool writing;\n\n \/\/ Backlog of data, i.e. incomplete frame\n String partial_frame;\n}; \/\/ class RecordSSTStream\n\n} \/\/ namespace Sirikata\n\n#endif \/\/_SIRIKATA_CORE_RECORD_SST_STREAM_HPP_\n<commit_msg>RecordSSTStream should be non-copyable because of how it passes its own this pointer into a callback for underlying sststream.<commit_after>\/\/ Copyright (c) 2011 Sirikata Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can\n\/\/ be found in the LICENSE file.\n\n#ifndef _SIRIKATA_CORE_RECORD_SST_STREAM_HPP_\n#define _SIRIKATA_CORE_RECORD_SST_STREAM_HPP_\n\n#include <sirikata\/core\/util\/Platform.hpp>\n#include <sirikata\/core\/network\/Frame.hpp>\n#include <sirikata\/core\/util\/Liveness.hpp>\n#include <sirikata\/core\/util\/Time.hpp>\n\nnamespace Sirikata {\n\n\/** RecordSSTStream wraps a regular SST stream, turning it into a record-based\n * stream, i.e. performing buffering and triggering callbacks for each record\n * rather than for each set of received bytes. This is useful for reliable,\n * message-oriented protocols. The user submits individual records to be sent\n * and it uses simple framing to identify the records at the receiver.\n *\/\ntemplate<typename StreamPtrType>\nclass RecordSSTStream : public Liveness, public Noncopyable {\npublic:\n typedef std::tr1::function<void(MemoryReference)> RecordCallback;\n\n RecordSSTStream() {}\n ~RecordSSTStream() {\n destroy();\n }\n\n void initialize(StreamPtrType stream, RecordCallback cb) {\n mStream = stream;\n mCB = cb;\n\n using std::tr1::placeholders::_1;\n using std::tr1::placeholders::_2;\n\n assert(mStream);\n mStream->registerReadCallback(\n std::tr1::bind(\n &RecordSSTStream::handleRead, this,\n _1, _2\n )\n );\n }\n\n void write(const MemoryReference& data) {\n outstanding.push(Network::Frame::write(data.begin(), data.size()));\n writeSomeData(livenessToken());\n }\n\n void destroy() {\n letDie();\n\n if (!mStream) return;\n mStream->registerReadCallback(0);\n }\nprivate:\n\n RecordSSTStream(const RecordSSTStream&);\n \n void handleRead(uint8* data, int size) {\n partial_frame.append((const char*)data, size);\n while(true) {\n String parsed = Network::Frame::parse(partial_frame);\n if (parsed.empty()) return;\n mCB( MemoryReference(parsed) );\n }\n }\n\n void writeSomeData(Liveness::Token alive) {\n if (!alive) return;\n\n static Duration retry_rate = Duration::milliseconds((int64)1);\n\n writing = true;\n\n if (!mStream) {\n \/\/ We're still waiting on the stream. Initialization should trigger\n \/\/ writing if it gets a stream and there's data waiting.\n writing = false;\n return;\n }\n\n \/\/ Otherwise, keep sending until we run out or\n while(!outstanding.empty()) {\n std::string& framed_msg = outstanding.front();\n int bytes_written = mStream->write((const uint8*)framed_msg.data(), framed_msg.size());\n if (bytes_written < 0) {\n \/\/ FIXME\n break;\n }\n else if (bytes_written < (int)framed_msg.size()) {\n framed_msg = framed_msg.substr(bytes_written);\n break;\n }\n else {\n outstanding.pop();\n }\n }\n\n if (outstanding.empty())\n writing = false;\n else\n mStream->getContext()->mainStrand->post(\n retry_rate,\n std::tr1::bind(&RecordSSTStream::writeSomeData, this, alive),\n \"RecordSSTStream::writeSomeData\"\n );\n }\n\n StreamPtrType mStream;\n RecordCallback mCB;\n\n \/\/ Outstanding data to be sent. FIXME efficiency\n std::queue<std::string> outstanding;\n \/\/ If writing is currently in progress\n bool writing;\n\n \/\/ Backlog of data, i.e. incomplete frame\n String partial_frame;\n}; \/\/ class RecordSSTStream\n\n} \/\/ namespace Sirikata\n\n#endif \/\/_SIRIKATA_CORE_RECORD_SST_STREAM_HPP_\n<|endoftext|>"} {"text":"<commit_before>\/* Sirikata\n * SerializationCheck.hpp\n *\n * Copyright (c) 2009, Ewen Cheslack-Postava\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in\n * the documentation and\/or other materials provided with the\n * distribution.\n * * Neither the name of Sirikata nor the names of its contributors may\n * be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS\n * IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED\n * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A\n * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER\n * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#ifndef _SIRIKATA_SERIALIZATION_CHECK_HPP_\n#define _SIRIKATA_SERIALIZATION_CHECK_HPP_\n\n#include <sirikata\/core\/util\/Platform.hpp>\n\n#include <boost\/thread\/thread.hpp>\n\nnamespace Sirikata {\n\n\/** Verifies that code blocks you expect to be handled in a serialized\n * fashion (i.e. non-concurrently) are actually handled that way.\n * Mark these sections with calls to serializedEnter() and\n * serializedExit() at the beinning and end respectively and those\n * calls will assert in debug mode if this condition is violated.\n * This can be used recursively within a thread -- multiple calls\n * to serializedEnter() from the same thread will not result in\n * an error.\n *\/\nclass SerializationCheck {\npublic:\n \/\/ Used to mark an entire scope as\n class Scoped {\n public:\n Scoped(SerializationCheck* p)\n : parent(p)\n {\n parent->serializedEnter();\n }\n\n ~Scoped() {\n parent->serializedExit();\n }\n private:\n Scoped();\n Scoped(Scoped& rhs);\n Scoped& operator=(Scoped& rhs);\n\n SerializationCheck* parent;\n };\n\n\n\n SerializationCheck()\n : mAccessors(0),\n mThreadID()\n {\n }\n\n inline void serializedEnter() const {\n int32 val = ++mAccessors;\n\n assert(val >= 1);\n\n if (val == 1) {\n \/\/ We're the first ones in here, we need to setup the thread id\n mThreadID = boost::this_thread::get_id();\n }\n else {\n \/\/ We got in here later on. This is only valid if we were in the\n \/\/ same thread, so the thread had better already be marked and\n \/\/ match ours\n assert(mThreadID == boost::this_thread::get_id());\n }\n }\n\n inline void serializedExit() const {\n if (mAccessors == (int32)1) {\n \/\/ We should be the only one left accessing this and a\n \/\/ serializedEnter should *not* be getting called, so we\n \/\/ can erase the thread ID now.\n mThreadID = boost::thread::id();\n }\n\n int32 val = --mAccessors;\n assert(val >= 0);\n }\nprivate:\n \/\/ Implementation Note: Technically this isn't all thread safe. However,\n \/\/ the core component which tracks the number of accessors and their order\n \/\/ off access is thread safe. Any thread-unsafe accesses should only result\n \/\/ in a bad comparison, which should result in an assertion anyway since the\n \/\/ whole point of this class is to verify that multiple threads are not trying\n \/\/ to access shared data (including this object) at the same time.\n mutable AtomicValue<int32> mAccessors;\n mutable boost::thread::id mThreadID;\n};\n\n} \/\/ namespace Sirikata\n\n#endif \/\/_SIRIKATA_SERIALIZATION_CHECK_HPP_\n<commit_msg>Only perform SerializationCheck in debug mode.<commit_after>\/* Sirikata\n * SerializationCheck.hpp\n *\n * Copyright (c) 2009, Ewen Cheslack-Postava\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in\n * the documentation and\/or other materials provided with the\n * distribution.\n * * Neither the name of Sirikata nor the names of its contributors may\n * be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS\n * IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED\n * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A\n * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER\n * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#ifndef _SIRIKATA_SERIALIZATION_CHECK_HPP_\n#define _SIRIKATA_SERIALIZATION_CHECK_HPP_\n\n#include <sirikata\/core\/util\/Platform.hpp>\n\n#include <boost\/thread\/thread.hpp>\n\nnamespace Sirikata {\n\n\/** Verifies that code blocks you expect to be handled in a serialized\n * fashion (i.e. non-concurrently) are actually handled that way.\n * Mark these sections with calls to serializedEnter() and\n * serializedExit() at the beinning and end respectively and those\n * calls will assert in debug mode if this condition is violated.\n * This can be used recursively within a thread -- multiple calls\n * to serializedEnter() from the same thread will not result in\n * an error.\n *\/\nclass SerializationCheck {\npublic:\n \/\/ Used to mark an entire scope as\n class Scoped {\n public:\n Scoped(SerializationCheck* p)\n : parent(p)\n {\n parent->serializedEnter();\n }\n\n ~Scoped() {\n parent->serializedExit();\n }\n private:\n Scoped();\n Scoped(Scoped& rhs);\n Scoped& operator=(Scoped& rhs);\n\n SerializationCheck* parent;\n };\n\n\n\n SerializationCheck()\n#if SIRIKATA_DEBUG\n : mAccessors(0),\n mThreadID()\n#endif \/\/SIRIKATA_DEBUG\n {\n }\n\n inline void serializedEnter() const {\n#if SIRIKATA_DEBUG\n int32 val = ++mAccessors;\n\n assert(val >= 1);\n\n if (val == 1) {\n \/\/ We're the first ones in here, we need to setup the thread id\n mThreadID = boost::this_thread::get_id();\n }\n else {\n \/\/ We got in here later on. This is only valid if we were in the\n \/\/ same thread, so the thread had better already be marked and\n \/\/ match ours\n assert(mThreadID == boost::this_thread::get_id());\n }\n#endif \/\/SIRIKATA_DEBUG\n }\n\n inline void serializedExit() const {\n#if SIRIKATA_DEBUG\n if (mAccessors == (int32)1) {\n \/\/ We should be the only one left accessing this and a\n \/\/ serializedEnter should *not* be getting called, so we\n \/\/ can erase the thread ID now.\n mThreadID = boost::thread::id();\n }\n\n int32 val = --mAccessors;\n assert(val >= 0);\n#endif \/\/SIRIKATA_DEBUG\n }\nprivate:\n#if SIRIKATA_DEBUG\n \/\/ Implementation Note: Technically this isn't all thread safe. However,\n \/\/ the core component which tracks the number of accessors and their order\n \/\/ off access is thread safe. Any thread-unsafe accesses should only result\n \/\/ in a bad comparison, which should result in an assertion anyway since the\n \/\/ whole point of this class is to verify that multiple threads are not trying\n \/\/ to access shared data (including this object) at the same time.\n mutable AtomicValue<int32> mAccessors;\n mutable boost::thread::id mThreadID;\n#endif \/\/SIRIKATA_DEBUG\n};\n\n} \/\/ namespace Sirikata\n\n#endif \/\/_SIRIKATA_SERIALIZATION_CHECK_HPP_\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n#include <windows.h>\n#include <string>\n#include <fstream>\n#include <conio.h>\n#include <Shlwapi.h>\n#include <stdlib.h>\n#include \"General.h\"\n#include \"Progress.h\"\n#pragma comment(lib, \"shlwapi.lib\")\n\n#ifdef DEBUG\n\t#define VERSION \"1.32d\"\n#endif\n#ifdef RELEASE\n\t#define VERSION \"1.32r\"\n#endif\n\nusing namespace std;\n\nint main()\n{\n\t\/\/ Initializing console.\n\tstring input = \"\";\n\tstring command = \"\";\n\tPrepareConsole(\"Tree\", VERSION, \"Please name the file which should be source of the tree.\\nType \\\"help\\\" for further information.\");\n\n\t\/\/ Loop waits for correct input.\n\twhile (true)\n\t{\n\t\tColor(INPUT_COLOR);\n\t\tcout << \"Tree.exe> \";\n\t\tgetline(cin, input, '\\n');\n\t\tcommand = ToLower(GetWord(input, 1));\n\t\tColor(OUTPUT_COLOR);\n\n\t\t\/\/ Parsing.\n\t\tif (command == \"exit\" || command == \"quit\")\n\t\t{\n\t\t\t\/\/ Leaving program when \"exit\" or \"quit\" has been typed.\n\t\t\treturn(EXIT_SUCCESS);\n\t\t}\n\t\telse if (command == \"help\")\n\t\t{\n\t\t\t\/\/ Shows a description of all available commands.\n\t\t\tcout << \" Available Commands:\" << endl;\n\t\t\tcout << \" help\\t\\tShows this page\" << endl;\n\t\t\tcout << \" info\\t\\tGeneral information\" << endl;\n\t\t\tcout << \" clear\/cls\\tClears the Screen\" << endl;\n\t\t\tcout << \" exit\\t\\tTerminates the program\" << endl << endl;\n\t\t\tcout << \" Enter any other string to designate the file containing the tree.\" << endl;\n\t\t\tcout << \" The program will create the listed files and directories,\" << endl;\n\t\t\tcout << \" until you press 'q' or the file reaches its end.\" << endl << endl;\n\t\t}\n\t\telse if (command == \"info\")\n\t\t{\n\t\t\t\/\/ Shows general info about the software.\n\t\t\tcout << \" Tree Version \" << VERSION << endl;\n\t\t\tcout << \" Compiled: \" << __DATE__ << \", \" << __TIME__ << endl;\n\t\t\tcout << \" (c) 2012 - 2015 Julian Heinzel\" << endl << endl;\n\t\t}\n\t\telse if (command == \"clear\" || command == \"cls\")\n\t\t{\n\t\t\t\/\/ Resets the terminal.\n\t\t\tPrepareConsole(\"Tree\", VERSION, \"Please name the file which should be source of the tree.\\nType \\\"help\\\" for further information.\");\n\t\t}\n\t\telse if (!PathFileExists(input.c_str()))\n\t\t{\n\t\t\t\/\/ Printing an error, if no command and no valid path has been typed.\n\t\t\tcout << \" Did not find file \\\"\" + input + \"\\\".\" << endl << endl;\n\t\t}\n\t\telse\n\t\t{\n\t\t\t\/\/ Restoring the directory and file structure.\n\t\t\tstring\t\tline;\n\t\t\tifstream\tfileIn;\n\t\t\tProgress\tprogressBar;\n\n\t\t\t\/\/ Counting the total number of lines in the specified textfile.\n\t\t\tint numberOfLines = 0;\n\t\t\tcout << \" File found, counting lines...\" << endl;\n\t\t\tfileIn.open(input);\n\t\t\twhile (getline(fileIn, line))\n\t\t\t{\n\t\t\t\tnumberOfLines += 1;\n\t\t\t}\n\t\t\tprogressBar.Reset(numberOfLines, 3);\n\n\t\t\t\/\/ Opening file and skipping the first three lines.\n\t\t\tcout << \" Processing \" << numberOfLines << \" lines of text.\" << endl << \" \";\n\t\t\tfileIn.close();\n\t\t\tfileIn.open(input);\n\t\t\tgetline(fileIn, line);\n\t\t\tgetline(fileIn, line);\n\t\t\tgetline(fileIn, line);\n\n\t\t\t\/\/ Creating directories and files.\n\t\t\tstring path[100];\n\t\t\tpath[0] = \"C\\\\\";\n\t\t\tif (!PathFileExists(\"C\\\\\"))\n\t\t\t{\n\t\t\t\tCreateDirectory(\"C\\\\\", 0);\n\t\t\t}\n\n\t\t\t\/\/ Loops through every line in the file.\n\t\t\twhile (getline(fileIn, line))\n\t\t\t{\n\t\t\t\tbool\tstart = true;\n\t\t\t\tint\t\tlevel = 0;\n\t\t\t\tint\t\tlength = strlen(line.c_str());\n\t\t\t\tint\t\tspace = 0;\n\t\t\t\tstring\tnewName = \"\";\n\n\t\t\t\t\/\/ Update the terminal, quit on 'q' and 'e'\n\t\t\t\tprogressBar.Increment();\n\t\t\t\tprogressBar.Print();\n\t\t\t\tif (_kbhit())\n\t\t\t\t{\n\t\t\t\t\tchar C = _getch();\n\t\t\t\t\tif (C == 'q' || C == 'e')\n\t\t\t\t\t{\n\t\t\t\t\t\tcout << endl << \" Program canceled. Processed \" << progressBar.GetCounter() << \" of \" << progressBar.GetMaxElements() << \" lines. (\" << progressBar.GetString() << \")\" << endl << endl;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (length == 0)\n\t\t\t\t{\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\t\/\/ Extract directory\/file name from line.\n\t\t\t\tfor (int i = 0; i < length; i++)\n\t\t\t\t{\n\t\t\t\t\tchar c = line[i];\n\t\t\t\t\tif ((c != ' ') && (c != '-') && (c != '\\\\') && (c != '|') && (c != '+') && (start = true))\n\t\t\t\t\t{\n\t\t\t\t\t\tstart = false;\n\t\t\t\t\t}\n\t\t\t\t\tif (start == true)\n\t\t\t\t\t{\n\t\t\t\t\t\tspace++;\n\t\t\t\t\t}\n\t\t\t\t\tif (start == false)\n\t\t\t\t\t{\n\t\t\t\t\t\tnewName += c;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tstart = true;\n\t\t\t\tlevel = ((space \/ 4) - 1);\n\n\t\t\t\t\/\/ If there is no valid file or directory name, the next line is beeing evaluated.\n\t\t\t\tif (newName == \"\")\n\t\t\t\t{\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\t\/\/ If there is a '+' or a '\\' in the given line, the name will be interpreted as a directory.\n\t\t\t\t\/\/ The new path is saved and the directory created.\n\t\t\t\tif ((line.find('+') != -1) || (line.find(\"\\\\\") != -1))\n\t\t\t\t{\n\t\t\t\t\tlevel += 1;\n\t\t\t\t\tpath[level] = path[level - 1] + \"\\\\\" + newName;\n\t\t\t\t\tif (PathFileExists(path[level - 1].c_str()))\n\t\t\t\t\t{\n\t\t\t\t\t\tif (!PathFileExists(path[level].c_str()))\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tCreateDirectory(path[level].c_str(), 0);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\t\/\/ Otherwise a file is listed, which will then be created.\n\t\t\t\t\tofstream fileOut;\n\t\t\t\t\tfileOut.open(path[level] + \"\\\\\" + newName);\n\t\t\t\t\tfileOut.close();\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (progressBar.GetPercent() == 100)\n\t\t\t{\n\t\t\t\t\/\/ Info if the file has been successfully processed.\n\t\t\t\tcout << endl << \" Generated files from \\\"\" + input + \"\\\" succesfully.\" << endl << endl;\n\t\t\t}\n\t\t}\n\t}\n\treturn(0);\n}<commit_msg>Changed variable names, extracted method RestoreTree(), root folder changed to match the filename.<commit_after>#include <iostream>\n#include <windows.h>\n#include <string>\n#include <fstream>\n#include <conio.h>\n#include <Shlwapi.h>\n#include <stdlib.h>\n#include <algorithm>\n#include \"General.h\"\n#include \"Progress.h\"\n#pragma comment(lib, \"shlwapi.lib\")\n\n#ifdef DEBUG\n\t#define VERSION \"1.32d\"\n#endif\n#ifdef RELEASE\n\t#define VERSION \"1.32r\"\n#endif\n\nusing namespace std;\n\nvoid RestoreTree(string filePath);\n\nint main()\n{\n\t\/\/ Initializing console.\n\tstring input = \"\";\n\tstring command = \"\";\n\tPrepareConsole(\"Tree\", VERSION, \"Please name the file which should be source of the tree.\\nType \\\"help\\\" for further information.\");\n\n\t\/\/ Loop waits for correct input.\n\twhile (true)\n\t{\n\t\tColor(INPUT_COLOR);\n\t\tcout << \"Tree.exe> \";\n\t\tgetline(cin, input, '\\n');\n\t\tcommand = ToLower(GetWord(input, 1));\n\t\tColor(OUTPUT_COLOR);\n\n\t\t\/\/ Parsing.\n\t\tif (command == \"exit\" || command == \"quit\")\n\t\t{\n\t\t\t\/\/ Leaving program when \"exit\" or \"quit\" has been typed.\n\t\t\treturn(EXIT_SUCCESS);\n\t\t}\n\t\telse if (command == \"help\")\n\t\t{\n\t\t\t\/\/ Shows a description of all available commands.\n\t\t\tcout << \" Available Commands:\" << endl;\n\t\t\tcout << \" help\\t\\tShows this page\" << endl;\n\t\t\tcout << \" info\\t\\tGeneral information\" << endl;\n\t\t\tcout << \" clear\/cls\\tClears the Screen\" << endl;\n\t\t\tcout << \" exit\\t\\tTerminates the program\" << endl << endl;\n\t\t\tcout << \" Enter any other string to designate the file containing the tree.\" << endl;\n\t\t\tcout << \" The program will create the listed files and directories,\" << endl;\n\t\t\tcout << \" until you press 'q' or the file reaches its end.\" << endl << endl;\n\t\t}\n\t\telse if (command == \"info\")\n\t\t{\n\t\t\t\/\/ Shows general info about the software.\n\t\t\tcout << \" Tree Version \" << VERSION << endl;\n\t\t\tcout << \" Compiled: \" << __DATE__ << \", \" << __TIME__ << endl;\n\t\t\tcout << \" (c) 2012 - 2015 Julian Heinzel\" << endl << endl;\n\t\t}\n\t\telse if (command == \"clear\" || command == \"cls\")\n\t\t{\n\t\t\t\/\/ Resets the terminal.\n\t\t\tPrepareConsole(\"Tree\", VERSION, \"Please name the file which should be source of the tree.\\nType \\\"help\\\" for further information.\");\n\t\t}\n\t\telse if (!PathFileExists(input.c_str()))\n\t\t{\n\t\t\t\/\/ Printing an error, if no command and no valid path has been typed.\n\t\t\tcout << \" Did not find file \\\"\" + input + \"\\\".\" << endl << endl;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tRestoreTree(input);\n\t\t}\n\t}\n\treturn(EXIT_SUCCESS);\n}\n\n\n\/\/ Restores the directory and file structure.\nvoid RestoreTree(string filePath)\n{\n\tstring\t\tline;\n\tifstream\tfileIn;\n\tProgress\tprogressBar;\n\n\t\/\/ Counting the total number of lines in the specified textfile.\n\tint numberOfLines = 0;\n\tcout << \" File found, counting lines...\" << endl;\n\tfileIn.open(filePath);\n\twhile (getline(fileIn, line))\n\t{\n\t\tnumberOfLines += 1;\n\t}\n\tprogressBar.Reset(numberOfLines, 3);\n\n\t\/\/ Opening file and skipping the first three lines.\n\tcout << \" Processing \" << numberOfLines << \" lines of text.\" << endl << \" \";\n\tfileIn.close();\n\tfileIn.open(filePath);\n\tfor (int i = 0; i < 3; i++) getline(fileIn, line);\n\n\t\/\/ Get the filename, replace '.' by '_', set the resulting string as root folder.\n\tstring path[100];\n\tstring fileName = GetFileName(filePath);\n\treplace(fileName.begin(), fileName.end(), '.', '_');\n\tpath[0] = fileName;\n\tCreateDirectory(path[0].c_str(), 0);\n\n\t\/\/ Loops through every line in the file.\n\twhile (getline(fileIn, line))\n\t{\n\t\tbool\treadingName = false;\n\t\tint\t\tlevel = 0;\n\t\tint\t\tlength = strlen(line.c_str());\n\t\tint\t\tindention = 0;\n\t\tstring\tnewName = \"\";\n\n\t\t\/\/ Update the terminal, quit on 'q' and 'e'\n\t\tprogressBar.Increment();\n\t\tprogressBar.Print();\n\t\tif (_kbhit())\n\t\t{\n\t\t\tchar C = _getch();\n\t\t\tif (C == 'q' || C == 'e')\n\t\t\t{\n\t\t\t\tcout << endl << \" Program canceled. Processed \"\n\t\t\t\t\t<< progressBar.GetCounter() << \" of \" << progressBar.GetMaxElements()\n\t\t\t\t\t<< \" lines. (\" << progressBar.GetString() << \")\" << endl << endl;\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\n\t\tif (length == 0)\n\t\t{\n\t\t\tbreak;\n\t\t}\n\n\t\t\/\/ Extract directory\/file name from line.\n\t\tfor (int i = 0; i < length; i++)\n\t\t{\n\t\t\tchar c = line[i];\n\t\t\tif ((c != ' ') && (c != '-') && (c != '\\\\') && (c != '|') && (c != '+') && (readingName == false))\n\t\t\t{\n\t\t\t\treadingName = true;\n\t\t\t}\n\n\t\t\tif (readingName == true)\n\t\t\t{\n\t\t\t\tnewName += c;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tindention++;\n\t\t\t}\n\t\t}\n\t\tlevel = ((indention \/ 4) - 1);\n\n\t\t\/\/ If there is no valid file or directory name, the next line is beeing evaluated.\n\t\tif (newName == \"\")\n\t\t{\n\t\t\tcontinue;\n\t\t}\n\n\t\t\/\/ If there is a '+' or a '\\' in the given line, the name will be interpreted as a directory.\n\t\t\/\/ The new path is saved and the directory created.\n\t\tif ((line.find('+') != -1) || (line.find(\"\\\\\") != -1))\n\t\t{\n\t\t\tlevel += 1;\n\t\t\tpath[level] = path[level - 1] + \"\\\\\" + newName;\n\t\t\tCreateDirectory(path[level].c_str(), 0);\n\t\t}\n\t\telse\n\t\t{\n\t\t\t\/\/ Otherwise a file is listed, which will then be created.\n\t\t\tofstream fileOut;\n\t\t\tfileOut.open(path[level] + \"\\\\\" + newName);\n\t\t\tfileOut.close();\n\t\t}\n\t}\n\n\tif (progressBar.GetPercent() == 100)\n\t{\n\t\t\/\/ Info if the file has been successfully processed.\n\t\tcout << endl << \" Generated files from \\\"\" + filePath + \"\\\" succesfully.\" << endl << endl;\n\t}\n}<|endoftext|>"} {"text":"<commit_before>\/*\n * This file is part of accounts-ui\n *\n * Copyright (C) 2009-2010 Nokia Corporation.\n *\n * Contact: Alberto Mardegan <alberto.mardegan@nokia.com>\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public License\n * version 2.1 as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA\n * 02110-1301 USA\n *\/\n\n#include \"service-selection-page.h\"\n#include \"account-sync-handler.h\"\n#include \"provider-plugin-process.h\"\n#include \"service-settings-widget.h\"\n#include \"accountsmanagersingleton.h\"\n#include \"account-setup-finished-page.h\"\n#include \"provider-plugin-process.h\"\n#include \"basic-header-widget.h\"\n\n\/\/Qt\n#include <QStringListModel>\n#include <QItemSelection>\n#include <QDebug>\n\n\/\/Meegotouch\n#include <MLayout>\n#include <MList>\n#include <MGridLayoutPolicy>\n#include <MLinearLayoutPolicy>\n#include <MButton>\n#include <MWidgetCreator>\n#include <MContainer>\n#include <MSeparator>\n#include <MBasicListItem>\n#include <MWidgetAction>\n#include <MImageWidget>\n#include <MLabel>\n#include <MLocale>\n#include <MPannableViewport>\n#include <MPositionIndicator>\n\n\/\/libAccounts\n#include <Accounts\/Provider>\n#include <Accounts\/Manager>\n\n\nnamespace AccountsUI {\n\nM_REGISTER_WIDGET_NO_CREATE(ServiceSelectionPage)\n\n\/\/TODO: write the service plugins\nclass ServiceSelectionPagePrivate\n{\npublic:\n ServiceSelectionPagePrivate()\n : serviceList(0),\n saveAction(0),\n cancelAction(0),\n context(0),\n syncHandler(0),\n layoutServicePolicy(0)\n {}\n ~ServiceSelectionPagePrivate() {}\n\n MList *serviceList;\n MAction *saveAction;\n MAction *cancelAction;\n AbstractAccountSetupContext *context;\n QList<AbstractServiceSetupContext*> serviceContextList;\n QList<AbstractSetupContext*> abstractContexts;\n AccountSyncHandler *syncHandler;\n MLinearLayoutPolicy *layoutServicePolicy;\n QString serviceType;\n QMap<QString, bool> serviceStatusMap;\n};\n\nServiceSelectionPage::ServiceSelectionPage(AbstractAccountSetupContext *context,\n QList<AbstractServiceSetupContext*>\n &serviceContextList,\n QGraphicsItem *parent)\n : MApplicationPage(parent),\n d_ptr(new ServiceSelectionPagePrivate())\n{\n Q_D(ServiceSelectionPage);\n setStyleName(\"AccountsUiPage\");\n d->context = context;\n d->serviceType = context->serviceType();\n d->context->account()->selectService(NULL);\n d->context->account()->setEnabled(true);\n d->serviceContextList = serviceContextList;\n d->abstractContexts.append(d->context);\n\n d->syncHandler = new AccountSyncHandler(this);\n connect(d->syncHandler, SIGNAL(syncStateChanged(const SyncState&)),\n this, SLOT(onSyncStateChanged(const SyncState&)));\n pannableViewport()->positionIndicator()->setStyleName(\"CommonPositionIndicatorInverted\");\n}\n\nvoid ServiceSelectionPage::serviceSelected(QModelIndex index)\n{\n Q_UNUSED(index);\n}\n\nServiceSelectionPage::~ServiceSelectionPage()\n{\n delete d_ptr;\n}\n\nvoid ServiceSelectionPage::createContent()\n{\n Q_D(ServiceSelectionPage);\n\n setComponentsDisplayMode(EscapeButton, MApplicationPageModel::Hide);\n\n \/\/we need a central widget to get the right layout size under the menubar\n MWidget *centralWidget = new MWidget();\n setCentralWidget(centralWidget);\n MLayout *layout = new MLayout(centralWidget);\n MLinearLayoutPolicy *layoutPolicy = new MLinearLayoutPolicy(layout, Qt::Vertical);\n layoutPolicy->setSpacing(0);\n\n if (d->context) {\n MWidget *upperWidget = new MWidget(this);\n MLayout *upperLayout = new MLayout(upperWidget);\n MLinearLayoutPolicy *upperLayoutPolicy = new MLinearLayoutPolicy(upperLayout, Qt::Vertical);\n upperLayoutPolicy->setSpacing(0);\n\n MLayout *topLayout = new MLayout();\n MLinearLayoutPolicy *topLayoutPolicy = new MLinearLayoutPolicy(topLayout, Qt::Vertical);\n topLayoutPolicy->setSpacing(0);\n\n QString providerName(d->context->account()->providerName());\n \/\/ xml file that describes the ui elements for the provider\n Accounts::Provider *provider = AccountsManager::instance()->provider(providerName);\n if (provider) {\n \/\/ loading common catalog to show device name string\n MLocale locale;\n QString catalog = \"common\";\n if (!catalog.isEmpty() && !locale.isInstalledTrCatalog(catalog)) {\n locale.installTrCatalog(catalog);\n MLocale::setDefault(locale);\n }\n\n \/\/ provider info header\n QDomElement root = provider->domDocument().documentElement();\n QDomElement providerIcon = root.firstChildElement(\"icon\");\n QString providerIconId = providerIcon.text();\n\n BasicHeaderWidget *providerInfoItem = new BasicHeaderWidget(this);\n providerInfoItem->setImage(providerIconId);\n providerInfoItem->setTitle(qtTrId(provider->displayName().toLatin1()));\n providerInfoItem->setSubtitle(qtTrId(d->context->account()->displayName().toLatin1()));\n providerInfoItem->setObjectName(\"wgServiceSelectionPageBasicListItem\");\n topLayoutPolicy->addItem(providerInfoItem, Qt::AlignLeft | Qt::AlignVCenter);\n\n\n \/\/ account connected message\n QDomElement accountConnectedMessage= root.firstChildElement(\"account-connected-message\");\n if (!accountConnectedMessage.isNull()) {\n \/\/ display a account connected message for provider\n QString accountConnectedMessageId=\n qtTrId((accountConnectedMessage.text()).toLatin1()).arg(qtTrId(\"qtn_comm_product_n9\"));\n MLabel *accountConnectedMessageLabel=\n new MLabel(accountConnectedMessageId);\n accountConnectedMessageLabel->setWordWrap(1);\n\t\taccountConnectedMessageLabel->setStyleName(\"CommonBodyTextInverted\");\n topLayoutPolicy->addItem(accountConnectedMessageLabel, Qt::AlignLeft | Qt::AlignVCenter);\n }\n }\n\n MSeparator *separatorTop = new MSeparator(this);\n separatorTop->setStyleName(\"CommonItemDividerInverted\");\n separatorTop->setOrientation(Qt::Horizontal);\n\n upperLayoutPolicy->addItem(topLayout);\n upperLayoutPolicy->addItem(separatorTop);\n\n layoutPolicy->addItem(upperWidget);\n }\n\n MWidget *serviceWidget = new MWidget();\n MLayout *serviceSettingLayout = new MLayout(serviceWidget);\n d->layoutServicePolicy = new MLinearLayoutPolicy(serviceSettingLayout, Qt::Vertical);\n d->layoutServicePolicy->setSpacing(0);\n\n for (int i = 0; i < d->serviceContextList.count(); i++) {\n \/\/ServiceSettingsWidget sets the display widget of the changing settings\n ServiceSettingsWidget *settingsWidget =\n new ServiceSettingsWidget(d->serviceContextList.at(i), serviceWidget,\n ServiceSettingsWidget::MandatorySettings |\n ServiceSettingsWidget::EnableButton,\n true);\n const Accounts::Service *service = d->serviceContextList.at(i)->service();\n emit serviceEnabled(service->name(), true);\n d->serviceStatusMap.insert(service->name(), true);\n d->abstractContexts.append(d->serviceContextList.at(i));\n d->layoutServicePolicy->addItem(settingsWidget, Qt::AlignLeft);\n connect (settingsWidget, SIGNAL(serviceEnabled(const QString&, bool)),\n this, SIGNAL(serviceEnabled(const QString&, bool)));\n connect (settingsWidget, SIGNAL(serviceEnabled(const QString&, bool)),\n this, SLOT(setEnabledService(const QString&, bool)));\n }\n\n layoutPolicy->addItem(serviceWidget, Qt::AlignLeft);\n\n \/\/% \"DONE\"\n d->saveAction = new MAction(qtTrId(\"qtn_comm_command_done\"), centralWidget);\n d->saveAction->setLocation(MAction::ToolBarLocation);\n addAction(d->saveAction);\n\n \/\/% \"CANCEL\"\n d->cancelAction = new MAction(qtTrId(\"qtn_comm_cancel\"), centralWidget);\n d->cancelAction->setLocation(MAction::ToolBarLocation);\n addAction(d->cancelAction);\n layoutPolicy->addStretch();\n\n connect(d->saveAction, SIGNAL(triggered()),\n this, SLOT(onAccountInstallButton()));\n connect(d->cancelAction, SIGNAL(triggered()),\n this, SLOT(cancel()));\n connect(d->serviceList, SIGNAL(itemClicked(QModelIndex)),\n this,SLOT(serviceSelected(QModelIndex)));\n\n connect(this, SIGNAL(backButtonClicked()),\n this, SLOT(close()));\n}\n\nvoid ServiceSelectionPage::onAccountInstallButton()\n{\n Q_D(ServiceSelectionPage);\n\n disconnect(d->saveAction, SIGNAL(triggered()),\n this, SLOT(onAccountInstallButton()));\n\n setProgressIndicatorVisible(true);\n for (int i = 0; i < d->serviceContextList.count(); i++) {\n const Accounts::Service *service = d->serviceContextList.at(i)->service();\n QMap<QString, bool>::iterator mapIterator =\n d->serviceStatusMap.find(service->name());\n if (mapIterator == d->serviceStatusMap.end())\n continue;\n d->serviceContextList.at(i)->enable(mapIterator.value());\n d->serviceStatusMap.remove(mapIterator.key());\n }\n d->syncHandler->validate(d->abstractContexts);\n}\n\nvoid ServiceSelectionPage::onSyncStateChanged(const SyncState &state)\n{\n Q_D(ServiceSelectionPage);\n\n switch (state) {\n case Validated:\n d->syncHandler->store(d->abstractContexts);\n break;\n case Stored:\n if (d->serviceType.isEmpty()) {\n connect(d->context->account(), SIGNAL(synced()),\n ProviderPluginProcess::instance(), SLOT(quit()));\n d->context->account()->sync();\n } else {\n d->context->account()->sync();\n AccountSetupFinishedPage *page = new AccountSetupFinishedPage(d->context);\n page->appear();\n }\n break;\n default:\n connect(d->saveAction, SIGNAL(triggered()),\n this, SLOT(onAccountInstallButton()));\n connect(d->cancelAction, SIGNAL(triggered()),\n this, SLOT(cancel()));\n setProgressIndicatorVisible(false);\n return;\n }\n}\n\nvoid ServiceSelectionPage::setWidget(MWidget *widget)\n{\n Q_D(ServiceSelectionPage);\n\n if (d->layoutServicePolicy && widget)\n d->layoutServicePolicy->addItem(widget);\n}\n\nvoid ServiceSelectionPage::setEnabledService(const QString &serviceName,\n bool enabled)\n{\n Q_D(ServiceSelectionPage);\n d->serviceStatusMap[serviceName] = enabled;\n}\n\nvoid ServiceSelectionPage::cancel()\n{\n ProviderPluginProcess::instance()->setReturnToAccountsList(true);\n}\n\n} \/\/namespace\n<commit_msg>Fix for Bug 216995 - Service selection view is missing a label<commit_after>\/*\n * This file is part of accounts-ui\n *\n * Copyright (C) 2009-2010 Nokia Corporation.\n *\n * Contact: Alberto Mardegan <alberto.mardegan@nokia.com>\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public License\n * version 2.1 as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA\n * 02110-1301 USA\n *\/\n\n#include \"service-selection-page.h\"\n#include \"account-sync-handler.h\"\n#include \"provider-plugin-process.h\"\n#include \"service-settings-widget.h\"\n#include \"accountsmanagersingleton.h\"\n#include \"account-setup-finished-page.h\"\n#include \"provider-plugin-process.h\"\n#include \"basic-header-widget.h\"\n\n\/\/Qt\n#include <QStringListModel>\n#include <QItemSelection>\n#include <QDebug>\n\n\/\/Meegotouch\n#include <MLayout>\n#include <MList>\n#include <MGridLayoutPolicy>\n#include <MLinearLayoutPolicy>\n#include <MButton>\n#include <MWidgetCreator>\n#include <MContainer>\n#include <MSeparator>\n#include <MBasicListItem>\n#include <MWidgetAction>\n#include <MImageWidget>\n#include <MLabel>\n#include <MLocale>\n#include <MPannableViewport>\n#include <MPositionIndicator>\n\n\/\/libAccounts\n#include <Accounts\/Provider>\n#include <Accounts\/Manager>\n\n\nnamespace AccountsUI {\n\nM_REGISTER_WIDGET_NO_CREATE(ServiceSelectionPage)\n\n\/\/TODO: write the service plugins\nclass ServiceSelectionPagePrivate\n{\npublic:\n ServiceSelectionPagePrivate()\n : serviceList(0),\n saveAction(0),\n cancelAction(0),\n context(0),\n syncHandler(0),\n layoutServicePolicy(0)\n {}\n ~ServiceSelectionPagePrivate() {}\n\n MList *serviceList;\n MAction *saveAction;\n MAction *cancelAction;\n AbstractAccountSetupContext *context;\n QList<AbstractServiceSetupContext*> serviceContextList;\n QList<AbstractSetupContext*> abstractContexts;\n AccountSyncHandler *syncHandler;\n MLinearLayoutPolicy *layoutServicePolicy;\n QString serviceType;\n QMap<QString, bool> serviceStatusMap;\n};\n\nServiceSelectionPage::ServiceSelectionPage(AbstractAccountSetupContext *context,\n QList<AbstractServiceSetupContext*>\n &serviceContextList,\n QGraphicsItem *parent)\n : MApplicationPage(parent),\n d_ptr(new ServiceSelectionPagePrivate())\n{\n Q_D(ServiceSelectionPage);\n setStyleName(\"AccountsUiPage\");\n d->context = context;\n d->serviceType = context->serviceType();\n d->context->account()->selectService(NULL);\n d->context->account()->setEnabled(true);\n d->serviceContextList = serviceContextList;\n d->abstractContexts.append(d->context);\n\n d->syncHandler = new AccountSyncHandler(this);\n connect(d->syncHandler, SIGNAL(syncStateChanged(const SyncState&)),\n this, SLOT(onSyncStateChanged(const SyncState&)));\n pannableViewport()->positionIndicator()->setStyleName(\"CommonPositionIndicatorInverted\");\n}\n\nvoid ServiceSelectionPage::serviceSelected(QModelIndex index)\n{\n Q_UNUSED(index);\n}\n\nServiceSelectionPage::~ServiceSelectionPage()\n{\n delete d_ptr;\n}\n\nvoid ServiceSelectionPage::createContent()\n{\n Q_D(ServiceSelectionPage);\n\n setComponentsDisplayMode(EscapeButton, MApplicationPageModel::Hide);\n\n \/\/we need a central widget to get the right layout size under the menubar\n MWidget *centralWidget = new MWidget();\n setCentralWidget(centralWidget);\n MLayout *layout = new MLayout(centralWidget);\n MLinearLayoutPolicy *layoutPolicy = new MLinearLayoutPolicy(layout, Qt::Vertical);\n layoutPolicy->setSpacing(0);\n\n if (d->context) {\n MWidget *upperWidget = new MWidget(this);\n MLayout *upperLayout = new MLayout(upperWidget);\n MLinearLayoutPolicy *upperLayoutPolicy = new MLinearLayoutPolicy(upperLayout, Qt::Vertical);\n upperLayoutPolicy->setSpacing(0);\n\n MLayout *topLayout = new MLayout();\n MLinearLayoutPolicy *topLayoutPolicy = new MLinearLayoutPolicy(topLayout, Qt::Vertical);\n topLayoutPolicy->setSpacing(0);\n\n QString providerName(d->context->account()->providerName());\n \/\/ xml file that describes the ui elements for the provider\n Accounts::Provider *provider = AccountsManager::instance()->provider(providerName);\n if (provider) {\n \/\/ loading common catalog to show device name string\n MLocale locale;\n QString catalog = \"common\";\n if (!catalog.isEmpty() && !locale.isInstalledTrCatalog(catalog)) {\n locale.installTrCatalog(catalog);\n MLocale::setDefault(locale);\n }\n\n \/\/ provider info header\n QDomElement root = provider->domDocument().documentElement();\n QDomElement providerIcon = root.firstChildElement(\"icon\");\n QString providerIconId = providerIcon.text();\n\n BasicHeaderWidget *providerInfoItem = new BasicHeaderWidget(this);\n providerInfoItem->setImage(providerIconId);\n providerInfoItem->setTitle(qtTrId(provider->displayName().toLatin1()));\n providerInfoItem->setSubtitle(qtTrId(d->context->account()->displayName().toLatin1()));\n providerInfoItem->setObjectName(\"wgServiceSelectionPageBasicListItem\");\n topLayoutPolicy->addItem(providerInfoItem, Qt::AlignLeft | Qt::AlignVCenter);\n\n\n \/\/ account connected message\n QString accountConnectedMessageId;\n QDomElement accountConnectedMessage= root.firstChildElement(\"account-connected-message\");\n if (!accountConnectedMessage.isNull()) {\n \/\/ display a account connected message for provider\n accountConnectedMessageId =\n qtTrId((accountConnectedMessage.text()).toLatin1()).arg(qtTrId(\"qtn_comm_product_n9\"));\n }\n else {\n \/\/ default message for service selection.\n accountConnectedMessageId = qtTrId(\"qtn_acc_enable_services_in_apps\");\n }\n MLabel *accountConnectedMessageLabel=\n new MLabel(accountConnectedMessageId);\n accountConnectedMessageLabel->setWordWrap(1);\n accountConnectedMessageLabel->setStyleName(\"CommonBodyTextInverted\");\n topLayoutPolicy->addItem(accountConnectedMessageLabel, Qt::AlignLeft | Qt::AlignVCenter);\n }\n\n MSeparator *separatorTop = new MSeparator(this);\n separatorTop->setStyleName(\"CommonItemDividerInverted\");\n separatorTop->setOrientation(Qt::Horizontal);\n\n upperLayoutPolicy->addItem(topLayout);\n upperLayoutPolicy->addItem(separatorTop);\n\n layoutPolicy->addItem(upperWidget);\n }\n\n MWidget *serviceWidget = new MWidget();\n MLayout *serviceSettingLayout = new MLayout(serviceWidget);\n d->layoutServicePolicy = new MLinearLayoutPolicy(serviceSettingLayout, Qt::Vertical);\n d->layoutServicePolicy->setSpacing(0);\n\n for (int i = 0; i < d->serviceContextList.count(); i++) {\n \/\/ServiceSettingsWidget sets the display widget of the changing settings\n ServiceSettingsWidget *settingsWidget =\n new ServiceSettingsWidget(d->serviceContextList.at(i), serviceWidget,\n ServiceSettingsWidget::MandatorySettings |\n ServiceSettingsWidget::EnableButton,\n true);\n const Accounts::Service *service = d->serviceContextList.at(i)->service();\n emit serviceEnabled(service->name(), true);\n d->serviceStatusMap.insert(service->name(), true);\n d->abstractContexts.append(d->serviceContextList.at(i));\n d->layoutServicePolicy->addItem(settingsWidget, Qt::AlignLeft);\n connect (settingsWidget, SIGNAL(serviceEnabled(const QString&, bool)),\n this, SIGNAL(serviceEnabled(const QString&, bool)));\n connect (settingsWidget, SIGNAL(serviceEnabled(const QString&, bool)),\n this, SLOT(setEnabledService(const QString&, bool)));\n }\n\n layoutPolicy->addItem(serviceWidget, Qt::AlignLeft);\n\n \/\/% \"DONE\"\n d->saveAction = new MAction(qtTrId(\"qtn_comm_command_done\"), centralWidget);\n d->saveAction->setLocation(MAction::ToolBarLocation);\n addAction(d->saveAction);\n\n \/\/% \"CANCEL\"\n d->cancelAction = new MAction(qtTrId(\"qtn_comm_cancel\"), centralWidget);\n d->cancelAction->setLocation(MAction::ToolBarLocation);\n addAction(d->cancelAction);\n layoutPolicy->addStretch();\n\n connect(d->saveAction, SIGNAL(triggered()),\n this, SLOT(onAccountInstallButton()));\n connect(d->cancelAction, SIGNAL(triggered()),\n this, SLOT(cancel()));\n connect(d->serviceList, SIGNAL(itemClicked(QModelIndex)),\n this,SLOT(serviceSelected(QModelIndex)));\n\n connect(this, SIGNAL(backButtonClicked()),\n this, SLOT(close()));\n}\n\nvoid ServiceSelectionPage::onAccountInstallButton()\n{\n Q_D(ServiceSelectionPage);\n\n disconnect(d->saveAction, SIGNAL(triggered()),\n this, SLOT(onAccountInstallButton()));\n\n setProgressIndicatorVisible(true);\n for (int i = 0; i < d->serviceContextList.count(); i++) {\n const Accounts::Service *service = d->serviceContextList.at(i)->service();\n QMap<QString, bool>::iterator mapIterator =\n d->serviceStatusMap.find(service->name());\n if (mapIterator == d->serviceStatusMap.end())\n continue;\n d->serviceContextList.at(i)->enable(mapIterator.value());\n d->serviceStatusMap.remove(mapIterator.key());\n }\n d->syncHandler->validate(d->abstractContexts);\n}\n\nvoid ServiceSelectionPage::onSyncStateChanged(const SyncState &state)\n{\n Q_D(ServiceSelectionPage);\n\n switch (state) {\n case Validated:\n d->syncHandler->store(d->abstractContexts);\n break;\n case Stored:\n if (d->serviceType.isEmpty()) {\n connect(d->context->account(), SIGNAL(synced()),\n ProviderPluginProcess::instance(), SLOT(quit()));\n d->context->account()->sync();\n } else {\n d->context->account()->sync();\n AccountSetupFinishedPage *page = new AccountSetupFinishedPage(d->context);\n page->appear();\n }\n break;\n default:\n connect(d->saveAction, SIGNAL(triggered()),\n this, SLOT(onAccountInstallButton()));\n connect(d->cancelAction, SIGNAL(triggered()),\n this, SLOT(cancel()));\n setProgressIndicatorVisible(false);\n return;\n }\n}\n\nvoid ServiceSelectionPage::setWidget(MWidget *widget)\n{\n Q_D(ServiceSelectionPage);\n\n if (d->layoutServicePolicy && widget)\n d->layoutServicePolicy->addItem(widget);\n}\n\nvoid ServiceSelectionPage::setEnabledService(const QString &serviceName,\n bool enabled)\n{\n Q_D(ServiceSelectionPage);\n d->serviceStatusMap[serviceName] = enabled;\n}\n\nvoid ServiceSelectionPage::cancel()\n{\n ProviderPluginProcess::instance()->setReturnToAccountsList(true);\n}\n\n} \/\/namespace\n<|endoftext|>"} {"text":"<commit_before>#include <stdlib.h>\n#include <stdio.h>\n#include <string.h>\n#include <vector>\n\n#include \"objc\/runtime.h\"\n#include \"visibility.h\"\n\n#include <windows.h>\n#define RtlAddGrowableFunctionTable ClangIsConfusedByTypedefReturnTypes\n#include <rtlsupportapi.h>\n\n\n#ifndef __has_builtin\n#define __has_builtin(x) 0\n#endif\n\n#if !__has_builtin(__builtin_unreachable)\n#define __builtin_unreachable abort\n#endif\n\nstruct _MSVC_TypeDescriptor\n{\n\tconst void* pVFTable;\n\tvoid* spare;\n\tchar name[0];\n};\n\nstruct _MSVC_CatchableType\n{\n\tunsigned int flags;\n\tunsigned long type;\n\tint mdisp;\n\tint pdisp;\n\tint vdisp;\n\tint size;\n\tunsigned long copyFunction;\n};\n\nstruct _MSVC_CatchableTypeArray\n{\n\tint count;\n\tunsigned long types[0];\n};\n\nstruct _MSVC_ThrowInfo\n{\n\tunsigned int attributes;\n\tunsigned long pfnUnwind;\n\tunsigned long pfnForwardCompat;\n\tunsigned long pCatchableTypeArray;\n};\n\n#if defined(_WIN64)\n#define IMAGE_RELATIVE(ptr, base) (static_cast<unsigned long>((ptr ? ((uintptr_t)ptr - (uintptr_t)base) : (uintptr_t)nullptr)))\n#else\n#define IMAGE_RELATIVE(ptr, base) reinterpret_cast<unsigned long>((ptr))\n#endif\n\nextern \"C\" void __stdcall _CxxThrowException(void*, _MSVC_ThrowInfo*);\n\nnamespace\n{\n\nstatic std::string mangleObjcObject()\n{\n#if defined(__SIZEOF_POINTER__) && __SIZEOF_POINTER__ == 8\n\treturn \".PEAU.objc_object@@\";\n#else\n\treturn \".PAU.objc_object@@\";\n#endif\n}\n\nstatic std::string mangleStructNamed(const char* className)\n{\n\t\/\/ 32-bit:\n\t\/\/ .PAUxxx@@ = ?? struct xxx * `RTTI Type Descriptor'\n\t\/\/ 64-bit:\n\t\/\/ .PEAUxxx@@ = ?? struct xxx * __ptr64 `RTTI Type Descriptor'\n\t\/\/return\n\tauto r =\n#if defined(__SIZEOF_POINTER__) && __SIZEOF_POINTER__ == 8\n\t\tstd::string(\".PEAU.objc_cls_\") +\n#else\n\t\tstd::string(\".PAU.objc_cls_\") +\n#endif\n\t\tclassName + \"@@\";\n\treturn r;\n}\n\nvoid fillCatchableType(_MSVC_CatchableType* exceptType)\n{\n\texceptType->flags = 1;\n\texceptType->mdisp = 0;\n\texceptType->pdisp = -1;\n\texceptType->vdisp = 0;\n\texceptType->size = sizeof(id);\n\texceptType->copyFunction = 0;\n}\n\n} \/\/ <anonymous-namespace>\n\nstruct X {};\nPUBLIC extern \"C\" void objc_exception_rethrow(void* exc);\n\nPUBLIC extern \"C\" void objc_exception_throw(id object)\n{\n\t\/\/ Base used for image-relative addresses.\n\tchar x;\n\t\/\/ This is the base vtable for all RTTI entries\n\tstatic const void* typeid_vtable = *(void**)&typeid(void *);\n\n\tSEL rethrow_sel = sel_registerName(\"rethrow\");\n\tif ((nil != object) &&\n\t\t(class_respondsToSelector(object_getClass(object), rethrow_sel)))\n\t{\n\t\tIMP rethrow = objc_msg_lookup(object, rethrow_sel);\n\t\trethrow(object, rethrow_sel);\n\t\t\/\/ Should not be reached! If it is, then the rethrow method actually\n\t\t\/\/ didn't, so we throw it normally.\n\t}\n\n\tSEL processException_sel = sel_registerName(\"_processException\");\n\tif ((nil != object) &&\n\t\t(class_respondsToSelector(object_getClass(object), processException_sel)))\n\t{\n\t\tIMP processException = objc_msg_lookup(object, processException_sel);\n\t\tprocessException(object, processException_sel);\n\t}\n\n\t\/\/ The 'id' base type will be taking up a spot in the list:\n\tsize_t typeCount = 1;\n\n\t\/\/ Get count of all types in exception\n\tfor (Class cls = object_getClass(object); cls != Nil; cls = class_getSuperclass(cls), ++typeCount)\n\t\t;\n\n\t\/\/ Unfortunately we can't put this in a real function since the alloca has to be in this stack frame:\n#define CREATE_TYPE_DESCRIPTOR(desc, symName) \\\n\tdesc = reinterpret_cast<_MSVC_TypeDescriptor*>(alloca(sizeof(_MSVC_TypeDescriptor) + symName.size() + 1 \/* null terminator *\/)); \\\n\tdesc->pVFTable = typeid_vtable; \\\n\tdesc->spare = nullptr; \\\n\tstrcpy_s(desc->name, symName.size() + 1, symName.c_str());\n\n\tauto exceptTypes =\n\t\t(_MSVC_CatchableTypeArray*)_alloca(sizeof(_MSVC_CatchableTypeArray) + sizeof(_MSVC_CatchableType*) * typeCount);\n\texceptTypes->count = typeCount;\n\n\t\/\/ Add exception type and all base types to throw information\n\tsize_t curTypeIndex = 0;\n\tfor (Class cls = object_getClass(object); cls != Nil; cls = class_getSuperclass(cls))\n\t{\n\t\tauto exceptType = (_MSVC_CatchableType*)_alloca(sizeof(_MSVC_CatchableType));\n\t\tfillCatchableType(exceptType);\n\n\t\tauto mangledName = mangleStructNamed(class_getName(cls));\n\t\t_MSVC_TypeDescriptor *ty;\n\t\tCREATE_TYPE_DESCRIPTOR(ty, mangledName);\n\t\texceptType->type = IMAGE_RELATIVE(ty, &x);\n\t\texceptTypes->types[curTypeIndex++] = IMAGE_RELATIVE(exceptType, &x);\n\t}\n\n\t\/\/ Add id (struct objc_object*)\n\tauto exceptType = (_MSVC_CatchableType*)_alloca(sizeof(_MSVC_CatchableType));\n\tfillCatchableType(exceptType);\n\tauto idName = mangleObjcObject();\n\t_MSVC_TypeDescriptor *ty;\n\tCREATE_TYPE_DESCRIPTOR(ty, idName);\n\texceptType->type = IMAGE_RELATIVE(ty, &x);\n\texceptTypes->types[curTypeIndex++] = IMAGE_RELATIVE(exceptType, &x);\n\n\t_MSVC_ThrowInfo ti = {\n\t\t0, \/\/ attributes\n\t\t0, \/\/ pfnUnwind\n\t\t0, \/\/ pfnForwardCompat\n\t\tIMAGE_RELATIVE(exceptTypes, &x) \/\/ pCatchableTypeArray\n\t};\n#\tdefine EH_EXCEPTION_NUMBER ('msc' | 0xE0000000)\n#\tdefine EH_MAGIC_NUMBER1 0x19930520\n#\tdefine EXCEPTION_NONCONTINUABLE 0x1\n\tEXCEPTION_RECORD exception;\n\texception.ExceptionCode = EH_EXCEPTION_NUMBER;\n\texception.ExceptionFlags = EXCEPTION_NONCONTINUABLE;\n\texception.ExceptionRecord = nullptr;\n\texception.ExceptionAddress = nullptr;\n\t\/\/ The fourth parameter is the base address of the image (for us, this stack \n\t\/\/ frame), but we only use image-relative 32-bit addresses on 64-bit\n\t\/\/ platforms. On 32-bit platforms, we use 32-bit absolute addresses.\n\texception.NumberParameters = sizeof(void*) == 4 ? 3 : 4;\n\texception.ExceptionInformation[0] = EH_MAGIC_NUMBER1;\n\texception.ExceptionInformation[1] = reinterpret_cast<ULONG_PTR>(&object);\n\texception.ExceptionInformation[2] = reinterpret_cast<ULONG_PTR>(&ti);\n\texception.ExceptionInformation[3] = reinterpret_cast<ULONG_PTR>(&x);\n\n#ifdef _WIN64\n \tRtlRaiseException(&exception);\n#else\n\tRaiseException(exception.ExceptionCode,\n\t\texception.ExceptionFlags,\n\t\texception.NumberParameters,\n\t\texception.ExceptionInformation);\n#endif\n\t__builtin_unreachable();\n}\n\n\nPUBLIC extern \"C\" void objc_exception_rethrow(void* exc)\n{\n\t_CxxThrowException(nullptr, nullptr);\n\t__builtin_unreachable();\n}\n\n<commit_msg>[windows] Handle changes to clang's EH mangling<commit_after>#include <stdlib.h>\n#include <stdio.h>\n#include <string.h>\n#include <vector>\n\n#include \"objc\/runtime.h\"\n#include \"visibility.h\"\n\n#include <windows.h>\n#define RtlAddGrowableFunctionTable ClangIsConfusedByTypedefReturnTypes\n#include <rtlsupportapi.h>\n\n\n#ifndef __has_builtin\n#define __has_builtin(x) 0\n#endif\n\n#if !__has_builtin(__builtin_unreachable)\n#define __builtin_unreachable abort\n#endif\n\nstruct _MSVC_TypeDescriptor\n{\n\tconst void* pVFTable;\n\tvoid* spare;\n\tchar name[0];\n};\n\nstruct _MSVC_CatchableType\n{\n\tunsigned int flags;\n\tunsigned long type;\n\tint mdisp;\n\tint pdisp;\n\tint vdisp;\n\tint size;\n\tunsigned long copyFunction;\n};\n\nstruct _MSVC_CatchableTypeArray\n{\n\tint count;\n\tunsigned long types[0];\n};\n\nstruct _MSVC_ThrowInfo\n{\n\tunsigned int attributes;\n\tunsigned long pfnUnwind;\n\tunsigned long pfnForwardCompat;\n\tunsigned long pCatchableTypeArray;\n};\n\n#if defined(_WIN64)\n#define IMAGE_RELATIVE(ptr, base) (static_cast<unsigned long>((ptr ? ((uintptr_t)ptr - (uintptr_t)base) : (uintptr_t)nullptr)))\n#else\n#define IMAGE_RELATIVE(ptr, base) reinterpret_cast<unsigned long>((ptr))\n#endif\n\nextern \"C\" void __stdcall _CxxThrowException(void*, _MSVC_ThrowInfo*);\n\nnamespace\n{\n\nstatic std::string mangleObjcObject()\n{\n#if defined(__SIZEOF_POINTER__) && __SIZEOF_POINTER__ == 8\n\treturn \".PEAUobjc_object@@\";\n#else\n\treturn \".PAUobjc_object@@\";\n#endif\n}\n\nstatic std::string mangleStructNamed(const char* className)\n{\n\t\/\/ 32-bit:\n\t\/\/ .PAUxxx@@ = ?? struct xxx * `RTTI Type Descriptor'\n\t\/\/ 64-bit:\n\t\/\/ .PEAUxxx@@ = ?? struct xxx * __ptr64 `RTTI Type Descriptor'\n\t\/\/return\n\tauto r =\n#if defined(__SIZEOF_POINTER__) && __SIZEOF_POINTER__ == 8\n\t\tstd::string(\".PEAU\") +\n#else\n\t\tstd::string(\".PAU\") +\n#endif\n\t\tclassName + \"@@\";\n\treturn r;\n}\n\nvoid fillCatchableType(_MSVC_CatchableType* exceptType)\n{\n\texceptType->flags = 1;\n\texceptType->mdisp = 0;\n\texceptType->pdisp = -1;\n\texceptType->vdisp = 0;\n\texceptType->size = sizeof(id);\n\texceptType->copyFunction = 0;\n}\n\n} \/\/ <anonymous-namespace>\n\nstruct X {};\nPUBLIC extern \"C\" void objc_exception_rethrow(void* exc);\n\nPUBLIC extern \"C\" void objc_exception_throw(id object)\n{\n\t\/\/ Base used for image-relative addresses.\n\tchar x;\n\t\/\/ This is the base vtable for all RTTI entries\n\tstatic const void* typeid_vtable = *(void**)&typeid(void *);\n\n\tSEL rethrow_sel = sel_registerName(\"rethrow\");\n\tif ((nil != object) &&\n\t\t(class_respondsToSelector(object_getClass(object), rethrow_sel)))\n\t{\n\t\tIMP rethrow = objc_msg_lookup(object, rethrow_sel);\n\t\trethrow(object, rethrow_sel);\n\t\t\/\/ Should not be reached! If it is, then the rethrow method actually\n\t\t\/\/ didn't, so we throw it normally.\n\t}\n\n\tSEL processException_sel = sel_registerName(\"_processException\");\n\tif ((nil != object) &&\n\t\t(class_respondsToSelector(object_getClass(object), processException_sel)))\n\t{\n\t\tIMP processException = objc_msg_lookup(object, processException_sel);\n\t\tprocessException(object, processException_sel);\n\t}\n\n\t\/\/ The 'id' base type will be taking up a spot in the list:\n\tsize_t typeCount = 1;\n\n\t\/\/ Get count of all types in exception\n\tfor (Class cls = object_getClass(object); cls != Nil; cls = class_getSuperclass(cls), ++typeCount)\n\t\t;\n\n\t\/\/ Unfortunately we can't put this in a real function since the alloca has to be in this stack frame:\n#define CREATE_TYPE_DESCRIPTOR(desc, symName) \\\n\tdesc = reinterpret_cast<_MSVC_TypeDescriptor*>(alloca(sizeof(_MSVC_TypeDescriptor) + symName.size() + 1 \/* null terminator *\/)); \\\n\tdesc->pVFTable = typeid_vtable; \\\n\tdesc->spare = nullptr; \\\n\tstrcpy_s(desc->name, symName.size() + 1, symName.c_str());\n\n\tauto exceptTypes =\n\t\t(_MSVC_CatchableTypeArray*)_alloca(sizeof(_MSVC_CatchableTypeArray) + sizeof(_MSVC_CatchableType*) * typeCount);\n\texceptTypes->count = typeCount;\n\n\t\/\/ Add exception type and all base types to throw information\n\tsize_t curTypeIndex = 0;\n\tfor (Class cls = object_getClass(object); cls != Nil; cls = class_getSuperclass(cls))\n\t{\n\t\tauto exceptType = (_MSVC_CatchableType*)_alloca(sizeof(_MSVC_CatchableType));\n\t\tfillCatchableType(exceptType);\n\n\t\tauto mangledName = mangleStructNamed(class_getName(cls));\n\t\t_MSVC_TypeDescriptor *ty;\n\t\tCREATE_TYPE_DESCRIPTOR(ty, mangledName);\n\t\texceptType->type = IMAGE_RELATIVE(ty, &x);\n\t\texceptTypes->types[curTypeIndex++] = IMAGE_RELATIVE(exceptType, &x);\n\t}\n\n\t\/\/ Add id (struct objc_object*)\n\tauto exceptType = (_MSVC_CatchableType*)_alloca(sizeof(_MSVC_CatchableType));\n\tfillCatchableType(exceptType);\n\tauto idName = mangleObjcObject();\n\t_MSVC_TypeDescriptor *ty;\n\tCREATE_TYPE_DESCRIPTOR(ty, idName);\n\texceptType->type = IMAGE_RELATIVE(ty, &x);\n\texceptTypes->types[curTypeIndex++] = IMAGE_RELATIVE(exceptType, &x);\n\n\t_MSVC_ThrowInfo ti = {\n\t\t0, \/\/ attributes\n\t\t0, \/\/ pfnUnwind\n\t\t0, \/\/ pfnForwardCompat\n\t\tIMAGE_RELATIVE(exceptTypes, &x) \/\/ pCatchableTypeArray\n\t};\n#\tdefine EH_EXCEPTION_NUMBER ('msc' | 0xE0000000)\n#\tdefine EH_MAGIC_NUMBER1 0x19930520\n#\tdefine EXCEPTION_NONCONTINUABLE 0x1\n\tEXCEPTION_RECORD exception;\n\texception.ExceptionCode = EH_EXCEPTION_NUMBER;\n\texception.ExceptionFlags = EXCEPTION_NONCONTINUABLE;\n\texception.ExceptionRecord = nullptr;\n\texception.ExceptionAddress = nullptr;\n\t\/\/ The fourth parameter is the base address of the image (for us, this stack \n\t\/\/ frame), but we only use image-relative 32-bit addresses on 64-bit\n\t\/\/ platforms. On 32-bit platforms, we use 32-bit absolute addresses.\n\texception.NumberParameters = sizeof(void*) == 4 ? 3 : 4;\n\texception.ExceptionInformation[0] = EH_MAGIC_NUMBER1;\n\texception.ExceptionInformation[1] = reinterpret_cast<ULONG_PTR>(&object);\n\texception.ExceptionInformation[2] = reinterpret_cast<ULONG_PTR>(&ti);\n\texception.ExceptionInformation[3] = reinterpret_cast<ULONG_PTR>(&x);\n\n#ifdef _WIN64\n \tRtlRaiseException(&exception);\n#else\n\tRaiseException(exception.ExceptionCode,\n\t\texception.ExceptionFlags,\n\t\texception.NumberParameters,\n\t\texception.ExceptionInformation);\n#endif\n\t__builtin_unreachable();\n}\n\n\nPUBLIC extern \"C\" void objc_exception_rethrow(void* exc)\n{\n\t_CxxThrowException(nullptr, nullptr);\n\t__builtin_unreachable();\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/\/===- MemoryDependenceAnalysis.cpp - Mem Deps Implementation --*- C++ -*-===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file was developed by the Owen Anderson and is distributed under\n\/\/ the University of Illinois Open Source License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This file implements an analysis that determines, for a given memory\n\/\/ operation, what preceding memory operations it depends on. It builds on \n\/\/ alias analysis information, and tries to provide a lazy, caching interface to\n\/\/ a common kind of alias information query.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/Analysis\/MemoryDependenceAnalysis.h\"\n#include \"llvm\/Constants.h\"\n#include \"llvm\/Instructions.h\"\n#include \"llvm\/Function.h\"\n#include \"llvm\/Analysis\/AliasAnalysis.h\"\n#include \"llvm\/Support\/CFG.h\"\n#include \"llvm\/Target\/TargetData.h\"\n\nusing namespace llvm;\n\nchar MemoryDependenceAnalysis::ID = 0;\n \nconst Instruction* MemoryDependenceAnalysis::NonLocal = (Instruction*)-3;\nconst Instruction* MemoryDependenceAnalysis::None = (Instruction*)-4;\n \n\/\/ Register this pass...\nstatic RegisterPass<MemoryDependenceAnalysis> X(\"memdep\",\n \"Memory Dependence Analysis\");\n\n\/\/\/ getAnalysisUsage - Does not modify anything. It uses Alias Analysis.\n\/\/\/\nvoid MemoryDependenceAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {\n AU.setPreservesAll();\n AU.addRequiredTransitive<AliasAnalysis>();\n AU.addRequiredTransitive<TargetData>();\n}\n\n\/\/ Find the dependency of a CallSite\nconst Instruction* MemoryDependenceAnalysis::getCallSiteDependency(CallSite C,\n Instruction* start,\n BasicBlock* block) {\n \n AliasAnalysis& AA = getAnalysis<AliasAnalysis>();\n TargetData& TD = getAnalysis<TargetData>();\n BasicBlock::iterator blockBegin = C.getInstruction()->getParent()->begin();\n BasicBlock::iterator QI = C.getInstruction();\n \n if (start) {\n QI = start;\n blockBegin = start->getParent()->end();\n } else if (!start && block) {\n QI = block->end();\n blockBegin = block->end();\n }\n \n while (QI != blockBegin) {\n --QI;\n \n \/\/ If this inst is a memory op, get the pointer it accessed\n Value* pointer = 0;\n uint64_t pointerSize = 0;\n if (StoreInst* S = dyn_cast<StoreInst>(QI)) {\n pointer = S->getPointerOperand();\n pointerSize = TD.getTypeSize(S->getOperand(0)->getType());\n } else if (LoadInst* L = dyn_cast<LoadInst>(QI)) {\n pointer = L->getPointerOperand();\n pointerSize = TD.getTypeSize(L->getType());\n } else if (AllocationInst* AI = dyn_cast<AllocationInst>(QI)) {\n pointer = AI;\n if (ConstantInt* C = dyn_cast<ConstantInt>(AI->getArraySize()))\n pointerSize = C->getZExtValue() * \\\n TD.getTypeSize(AI->getAllocatedType());\n else\n pointerSize = ~0UL;\n } else if (VAArgInst* V = dyn_cast<VAArgInst>(QI)) {\n pointer = V->getOperand(0);\n pointerSize = TD.getTypeSize(V->getType());\n } else if (FreeInst* F = dyn_cast<FreeInst>(QI)) {\n pointer = F->getPointerOperand();\n \n \/\/ FreeInsts erase the entire structure\n pointerSize = ~0UL;\n } else if (CallSite::get(QI).getInstruction() != 0) {\n if (AA.getModRefInfo(C, CallSite::get(QI)) != AliasAnalysis::NoModRef) {\n if (!start && !block) {\n depGraphLocal.insert(std::make_pair(C.getInstruction(),\n std::make_pair(QI, true)));\n reverseDep[QI].insert(C.getInstruction());\n }\n return QI;\n } else {\n continue;\n }\n } else\n continue;\n \n if (AA.getModRefInfo(C, pointer, pointerSize) != AliasAnalysis::NoModRef) {\n if (!start && !block) {\n depGraphLocal.insert(std::make_pair(C.getInstruction(),\n std::make_pair(QI, true)));\n reverseDep[QI].insert(C.getInstruction());\n }\n return QI;\n }\n }\n \n \/\/ No dependence found\n depGraphLocal.insert(std::make_pair(C.getInstruction(),\n std::make_pair(NonLocal, true)));\n reverseDep[NonLocal].insert(C.getInstruction());\n return NonLocal;\n}\n\nvoid MemoryDependenceAnalysis::nonLocalHelper(Instruction* query,\n BasicBlock* block,\n DenseMap<BasicBlock*, Value*>& resp) {\n SmallPtrSet<BasicBlock*, 4> visited;\n SmallVector<BasicBlock*, 4> stack;\n stack.push_back(block);\n \n while (!stack.empty()) {\n BasicBlock* BB = stack.back();\n \n if (visited.count(BB)) {\n stack.pop_back();\n continue;\n }\n \n if (BB != block) {\n visited.insert(BB);\n \n const Instruction* localDep = getDependency(query, 0, BB);\n if (localDep != NonLocal) {\n resp.insert(std::make_pair(BB, const_cast<Instruction*>(localDep)));\n stack.pop_back();\n \n continue;\n }\n } else if (BB == block && stack.size() > 1) {\n visited.insert(BB);\n \n const Instruction* localDep = getDependency(query, 0, BB);\n if (localDep != query)\n resp.insert(std::make_pair(BB, const_cast<Instruction*>(localDep)));\n \n stack.pop_back();\n \n continue;\n }\n \n bool predOnStack = false;\n bool inserted = false;\n for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB);\n PI != PE; ++PI)\n if (!visited.count(*PI)) {\n stack.push_back(*PI);\n inserted = true;\n } else\n predOnStack = true;\n \n if (inserted)\n continue;\n else if (!inserted && !predOnStack) {\n resp.insert(std::make_pair(BB, const_cast<Instruction*>(None)));\n } else if (!inserted && predOnStack){\n resp.insert(std::make_pair(BB, const_cast<Instruction*>(NonLocal)));\n }\n \n stack.pop_back();\n }\n}\n\n\/\/\/ getNonLocalDependency - Fills the passed-in map with the non-local \n\/\/\/ dependencies of the queries. The map will contain NonLocal for\n\/\/\/ blocks between the query and its dependencies.\nvoid MemoryDependenceAnalysis::getNonLocalDependency(Instruction* query,\n DenseMap<BasicBlock*, Value*>& resp) {\n const Instruction* localDep = getDependency(query);\n if (localDep != NonLocal) {\n resp.insert(std::make_pair(query->getParent(),\n const_cast<Instruction*>(localDep)));\n return;\n }\n \n nonLocalHelper(query, query->getParent(), resp);\n}\n\n\/\/\/ getDependency - Return the instruction on which a memory operation\n\/\/\/ depends. The local paramter indicates if the query should only\n\/\/\/ evaluate dependencies within the same basic block.\nconst Instruction* MemoryDependenceAnalysis::getDependency(Instruction* query,\n Instruction* start,\n BasicBlock* block) {\n \/\/ Start looking for dependencies with the queried inst\n BasicBlock::iterator QI = query;\n \n \/\/ Check for a cached result\n std::pair<const Instruction*, bool> cachedResult = depGraphLocal[query];\n \/\/ If we have a _confirmed_ cached entry, return it\n if (cachedResult.second)\n return cachedResult.first;\n else if (cachedResult.first && cachedResult.first != NonLocal)\n \/\/ If we have an unconfirmed cached entry, we can start our search from there\n QI = const_cast<Instruction*>(cachedResult.first);\n \n if (start)\n QI = start;\n else if (!start && block)\n QI = block->end();\n \n AliasAnalysis& AA = getAnalysis<AliasAnalysis>();\n TargetData& TD = getAnalysis<TargetData>();\n \n \/\/ Get the pointer value for which dependence will be determined\n Value* dependee = 0;\n uint64_t dependeeSize = 0;\n bool queryIsVolatile = false;\n if (StoreInst* S = dyn_cast<StoreInst>(query)) {\n dependee = S->getPointerOperand();\n dependeeSize = TD.getTypeSize(S->getOperand(0)->getType());\n queryIsVolatile = S->isVolatile();\n } else if (LoadInst* L = dyn_cast<LoadInst>(query)) {\n dependee = L->getPointerOperand();\n dependeeSize = TD.getTypeSize(L->getType());\n queryIsVolatile = L->isVolatile();\n } else if (VAArgInst* V = dyn_cast<VAArgInst>(query)) {\n dependee = V->getOperand(0);\n dependeeSize = TD.getTypeSize(V->getType());\n } else if (FreeInst* F = dyn_cast<FreeInst>(query)) {\n dependee = F->getPointerOperand();\n \n \/\/ FreeInsts erase the entire structure, not just a field\n dependeeSize = ~0UL;\n } else if (CallSite::get(query).getInstruction() != 0)\n return getCallSiteDependency(CallSite::get(query), start, block);\n else if (isa<AllocationInst>(query))\n return None;\n else\n return None;\n \n BasicBlock::iterator blockBegin = block ? block->begin()\n : query->getParent()->begin();\n \n while (QI != blockBegin) {\n --QI;\n \n \/\/ If this inst is a memory op, get the pointer it accessed\n Value* pointer = 0;\n uint64_t pointerSize = 0;\n if (StoreInst* S = dyn_cast<StoreInst>(QI)) {\n \/\/ All volatile loads\/stores depend on each other\n if (queryIsVolatile && S->isVolatile()) {\n if (!start && !block) {\n depGraphLocal.insert(std::make_pair(query, std::make_pair(S, true)));\n reverseDep[S].insert(query);\n }\n \n return S;\n }\n \n pointer = S->getPointerOperand();\n pointerSize = TD.getTypeSize(S->getOperand(0)->getType());\n } else if (LoadInst* L = dyn_cast<LoadInst>(QI)) {\n \/\/ All volatile loads\/stores depend on each other\n if (queryIsVolatile && L->isVolatile()) {\n if (!start && !block) {\n depGraphLocal.insert(std::make_pair(query, std::make_pair(L, true)));\n reverseDep[L].insert(query);\n }\n \n return L;\n }\n \n pointer = L->getPointerOperand();\n pointerSize = TD.getTypeSize(L->getType());\n } else if (AllocationInst* AI = dyn_cast<AllocationInst>(QI)) {\n pointer = AI;\n if (ConstantInt* C = dyn_cast<ConstantInt>(AI->getArraySize()))\n pointerSize = C->getZExtValue() * \\\n TD.getTypeSize(AI->getAllocatedType());\n else\n pointerSize = ~0UL;\n } else if (VAArgInst* V = dyn_cast<VAArgInst>(QI)) {\n pointer = V->getOperand(0);\n pointerSize = TD.getTypeSize(V->getType());\n } else if (FreeInst* F = dyn_cast<FreeInst>(QI)) {\n pointer = F->getPointerOperand();\n \n \/\/ FreeInsts erase the entire structure\n pointerSize = ~0UL;\n } else if (CallSite::get(QI).getInstruction() != 0) {\n \/\/ Call insts need special handling. Check if they can modify our pointer\n AliasAnalysis::ModRefResult MR = AA.getModRefInfo(CallSite::get(QI),\n dependee, dependeeSize);\n \n if (MR != AliasAnalysis::NoModRef) {\n \/\/ Loads don't depend on read-only calls\n if (isa<LoadInst>(query) && MR == AliasAnalysis::Ref)\n continue;\n \n if (!start && !block) {\n depGraphLocal.insert(std::make_pair(query,\n std::make_pair(QI, true)));\n reverseDep[QI].insert(query);\n }\n \n return QI;\n } else {\n continue;\n }\n }\n \n \/\/ If we found a pointer, check if it could be the same as our pointer\n if (pointer) {\n AliasAnalysis::AliasResult R = AA.alias(pointer, pointerSize,\n dependee, dependeeSize);\n \n if (R != AliasAnalysis::NoAlias) {\n \/\/ May-alias loads don't depend on each other\n if (isa<LoadInst>(query) && isa<LoadInst>(QI) &&\n R == AliasAnalysis::MayAlias)\n continue;\n \n if (!start && !block) {\n depGraphLocal.insert(std::make_pair(query,\n std::make_pair(QI, true)));\n reverseDep[QI].insert(query);\n }\n \n return QI;\n }\n }\n }\n \n \/\/ If we found nothing, return the non-local flag\n if (!start && !block) {\n depGraphLocal.insert(std::make_pair(query,\n std::make_pair(NonLocal, true)));\n reverseDep[NonLocal].insert(query);\n }\n \n return NonLocal;\n}\n\n\/\/\/ removeInstruction - Remove an instruction from the dependence analysis,\n\/\/\/ updating the dependence of instructions that previously depended on it.\nvoid MemoryDependenceAnalysis::removeInstruction(Instruction* rem) {\n \/\/ Figure out the new dep for things that currently depend on rem\n const Instruction* newDep = NonLocal;\n\n depMapType::iterator depGraphEntry = depGraphLocal.find(rem);\n \/\/ We assume here that it's not in the reverse map if it's not in\n \/\/ the dep map. Checking it could be expensive, so don't do it.\n\n if (depGraphEntry != depGraphLocal.end()) {\n if (depGraphEntry->second.first != NonLocal &&\n depGraphEntry->second.second) {\n \/\/ If we have dep info for rem, set them to it\n BasicBlock::iterator RI =\n const_cast<Instruction*>(depGraphEntry->second.first);\n RI++;\n newDep = RI;\n } else if (depGraphEntry->second.first == NonLocal &&\n depGraphEntry->second.second ) {\n \/\/ If we have a confirmed non-local flag, use it\n newDep = NonLocal;\n } else {\n \/\/ Otherwise, use the immediate successor of rem\n \/\/ NOTE: This is because, when getDependence is called, it will first\n \/\/ check the immediate predecessor of what is in the cache.\n BasicBlock::iterator RI = rem;\n RI++;\n newDep = RI;\n }\n \n SmallPtrSet<Instruction*, 4>& set = reverseDep[rem];\n for (SmallPtrSet<Instruction*, 4>::iterator I = set.begin(), E = set.end();\n I != E; ++I) {\n \/\/ Insert the new dependencies\n \/\/ Mark it as unconfirmed as long as it is not the non-local flag\n depGraphLocal[*I] = std::make_pair(newDep, !newDep);\n }\n reverseDep.erase(rem);\n }\n\n getAnalysis<AliasAnalysis>().deleteValue(rem);\n}\n<commit_msg>Add more comments to memdep.<commit_after>\/\/===- MemoryDependenceAnalysis.cpp - Mem Deps Implementation --*- C++ -*-===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file was developed by the Owen Anderson and is distributed under\n\/\/ the University of Illinois Open Source License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This file implements an analysis that determines, for a given memory\n\/\/ operation, what preceding memory operations it depends on. It builds on \n\/\/ alias analysis information, and tries to provide a lazy, caching interface to\n\/\/ a common kind of alias information query.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/Analysis\/MemoryDependenceAnalysis.h\"\n#include \"llvm\/Constants.h\"\n#include \"llvm\/Instructions.h\"\n#include \"llvm\/Function.h\"\n#include \"llvm\/Analysis\/AliasAnalysis.h\"\n#include \"llvm\/Support\/CFG.h\"\n#include \"llvm\/Target\/TargetData.h\"\n\nusing namespace llvm;\n\nchar MemoryDependenceAnalysis::ID = 0;\n \nconst Instruction* MemoryDependenceAnalysis::NonLocal = (Instruction*)-3;\nconst Instruction* MemoryDependenceAnalysis::None = (Instruction*)-4;\n \n\/\/ Register this pass...\nstatic RegisterPass<MemoryDependenceAnalysis> X(\"memdep\",\n \"Memory Dependence Analysis\");\n\n\/\/\/ getAnalysisUsage - Does not modify anything. It uses Alias Analysis.\n\/\/\/\nvoid MemoryDependenceAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {\n AU.setPreservesAll();\n AU.addRequiredTransitive<AliasAnalysis>();\n AU.addRequiredTransitive<TargetData>();\n}\n\n\/\/\/ getCallSiteDependency - Private helper for finding the local dependencies\n\/\/\/ of a call site.\nconst Instruction* MemoryDependenceAnalysis::getCallSiteDependency(CallSite C,\n Instruction* start,\n BasicBlock* block) {\n \n AliasAnalysis& AA = getAnalysis<AliasAnalysis>();\n TargetData& TD = getAnalysis<TargetData>();\n BasicBlock::iterator blockBegin = C.getInstruction()->getParent()->begin();\n BasicBlock::iterator QI = C.getInstruction();\n \n \/\/ If the starting point was specifiy, use it\n if (start) {\n QI = start;\n blockBegin = start->getParent()->end();\n \/\/ If the starting point wasn't specified, but the block was, use it\n } else if (!start && block) {\n QI = block->end();\n blockBegin = block->end();\n }\n \n \/\/ Walk backwards through the block, looking for dependencies\n while (QI != blockBegin) {\n --QI;\n \n \/\/ If this inst is a memory op, get the pointer it accessed\n Value* pointer = 0;\n uint64_t pointerSize = 0;\n if (StoreInst* S = dyn_cast<StoreInst>(QI)) {\n pointer = S->getPointerOperand();\n pointerSize = TD.getTypeSize(S->getOperand(0)->getType());\n } else if (LoadInst* L = dyn_cast<LoadInst>(QI)) {\n pointer = L->getPointerOperand();\n pointerSize = TD.getTypeSize(L->getType());\n } else if (AllocationInst* AI = dyn_cast<AllocationInst>(QI)) {\n pointer = AI;\n if (ConstantInt* C = dyn_cast<ConstantInt>(AI->getArraySize()))\n pointerSize = C->getZExtValue() * \\\n TD.getTypeSize(AI->getAllocatedType());\n else\n pointerSize = ~0UL;\n } else if (VAArgInst* V = dyn_cast<VAArgInst>(QI)) {\n pointer = V->getOperand(0);\n pointerSize = TD.getTypeSize(V->getType());\n } else if (FreeInst* F = dyn_cast<FreeInst>(QI)) {\n pointer = F->getPointerOperand();\n \n \/\/ FreeInsts erase the entire structure\n pointerSize = ~0UL;\n } else if (CallSite::get(QI).getInstruction() != 0) {\n if (AA.getModRefInfo(C, CallSite::get(QI)) != AliasAnalysis::NoModRef) {\n if (!start && !block) {\n depGraphLocal.insert(std::make_pair(C.getInstruction(),\n std::make_pair(QI, true)));\n reverseDep[QI].insert(C.getInstruction());\n }\n return QI;\n } else {\n continue;\n }\n } else\n continue;\n \n if (AA.getModRefInfo(C, pointer, pointerSize) != AliasAnalysis::NoModRef) {\n if (!start && !block) {\n depGraphLocal.insert(std::make_pair(C.getInstruction(),\n std::make_pair(QI, true)));\n reverseDep[QI].insert(C.getInstruction());\n }\n return QI;\n }\n }\n \n \/\/ No dependence found\n depGraphLocal.insert(std::make_pair(C.getInstruction(),\n std::make_pair(NonLocal, true)));\n reverseDep[NonLocal].insert(C.getInstruction());\n return NonLocal;\n}\n\n\/\/\/ nonLocalHelper - Private helper used to calculate non-local dependencies\n\/\/\/ by doing DFS on the predecessors of a block to find its dependencies\nvoid MemoryDependenceAnalysis::nonLocalHelper(Instruction* query,\n BasicBlock* block,\n DenseMap<BasicBlock*, Value*>& resp) {\n \/\/ Set of blocks that we've already visited in our DFS\n SmallPtrSet<BasicBlock*, 4> visited;\n \/\/ Current stack of the DFS\n SmallVector<BasicBlock*, 4> stack;\n stack.push_back(block);\n \n \/\/ Do a basic DFS\n while (!stack.empty()) {\n BasicBlock* BB = stack.back();\n \n \/\/ If we've already visited this block, no need to revist\n if (visited.count(BB)) {\n stack.pop_back();\n continue;\n }\n \n \/\/ If we find a new block with a local dependency for query,\n \/\/ then we insert the new dependency and backtrack.\n if (BB != block) {\n visited.insert(BB);\n \n const Instruction* localDep = getDependency(query, 0, BB);\n if (localDep != NonLocal) {\n resp.insert(std::make_pair(BB, const_cast<Instruction*>(localDep)));\n stack.pop_back();\n \n continue;\n }\n \/\/ If we re-encounter the starting block, we still need to search it\n \/\/ because there might be a dependency in the starting block AFTER\n \/\/ the position of the query. This is necessary to get loops right.\n } else if (BB == block && stack.size() > 1) {\n visited.insert(BB);\n \n const Instruction* localDep = getDependency(query, 0, BB);\n if (localDep != query)\n resp.insert(std::make_pair(BB, const_cast<Instruction*>(localDep)));\n \n stack.pop_back();\n \n continue;\n }\n \n \/\/ If we didn't find anything, recurse on the precessors of this block\n bool predOnStack = false;\n bool inserted = false;\n for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB);\n PI != PE; ++PI)\n if (!visited.count(*PI)) {\n stack.push_back(*PI);\n inserted = true;\n } else\n predOnStack = true;\n \n \/\/ If we inserted a new predecessor, then we'll come back to this block\n if (inserted)\n continue;\n \/\/ If we didn't insert because we have no predecessors, then this\n \/\/ query has no dependency at all.\n else if (!inserted && !predOnStack) {\n resp.insert(std::make_pair(BB, const_cast<Instruction*>(None)));\n \/\/ If we didn't insert because our predecessors are already on the stack,\n \/\/ then we might still have a dependency, but it will be discovered during\n \/\/ backtracking.\n } else if (!inserted && predOnStack){\n resp.insert(std::make_pair(BB, const_cast<Instruction*>(NonLocal)));\n }\n \n stack.pop_back();\n }\n}\n\n\/\/\/ getNonLocalDependency - Fills the passed-in map with the non-local \n\/\/\/ dependencies of the queries. The map will contain NonLocal for\n\/\/\/ blocks between the query and its dependencies.\nvoid MemoryDependenceAnalysis::getNonLocalDependency(Instruction* query,\n DenseMap<BasicBlock*, Value*>& resp) {\n \/\/ First check that we don't actually have a local dependency.\n const Instruction* localDep = getDependency(query);\n if (localDep != NonLocal) {\n resp.insert(std::make_pair(query->getParent(),\n const_cast<Instruction*>(localDep)));\n return;\n }\n \n \/\/ If not, go ahead and search for non-local ones.\n nonLocalHelper(query, query->getParent(), resp);\n}\n\n\/\/\/ getDependency - Return the instruction on which a memory operation\n\/\/\/ depends. The local paramter indicates if the query should only\n\/\/\/ evaluate dependencies within the same basic block.\nconst Instruction* MemoryDependenceAnalysis::getDependency(Instruction* query,\n Instruction* start,\n BasicBlock* block) {\n \/\/ Start looking for dependencies with the queried inst\n BasicBlock::iterator QI = query;\n \n \/\/ Check for a cached result\n std::pair<const Instruction*, bool> cachedResult = depGraphLocal[query];\n \/\/ If we have a _confirmed_ cached entry, return it\n if (cachedResult.second)\n return cachedResult.first;\n else if (cachedResult.first && cachedResult.first != NonLocal)\n \/\/ If we have an unconfirmed cached entry, we can start our search from there\n QI = const_cast<Instruction*>(cachedResult.first);\n \n if (start)\n QI = start;\n else if (!start && block)\n QI = block->end();\n \n AliasAnalysis& AA = getAnalysis<AliasAnalysis>();\n TargetData& TD = getAnalysis<TargetData>();\n \n \/\/ Get the pointer value for which dependence will be determined\n Value* dependee = 0;\n uint64_t dependeeSize = 0;\n bool queryIsVolatile = false;\n if (StoreInst* S = dyn_cast<StoreInst>(query)) {\n dependee = S->getPointerOperand();\n dependeeSize = TD.getTypeSize(S->getOperand(0)->getType());\n queryIsVolatile = S->isVolatile();\n } else if (LoadInst* L = dyn_cast<LoadInst>(query)) {\n dependee = L->getPointerOperand();\n dependeeSize = TD.getTypeSize(L->getType());\n queryIsVolatile = L->isVolatile();\n } else if (VAArgInst* V = dyn_cast<VAArgInst>(query)) {\n dependee = V->getOperand(0);\n dependeeSize = TD.getTypeSize(V->getType());\n } else if (FreeInst* F = dyn_cast<FreeInst>(query)) {\n dependee = F->getPointerOperand();\n \n \/\/ FreeInsts erase the entire structure, not just a field\n dependeeSize = ~0UL;\n } else if (CallSite::get(query).getInstruction() != 0)\n return getCallSiteDependency(CallSite::get(query), start, block);\n else if (isa<AllocationInst>(query))\n return None;\n else\n return None;\n \n BasicBlock::iterator blockBegin = block ? block->begin()\n : query->getParent()->begin();\n \n \/\/ Walk backwards through the basic block, looking for dependencies\n while (QI != blockBegin) {\n --QI;\n \n \/\/ If this inst is a memory op, get the pointer it accessed\n Value* pointer = 0;\n uint64_t pointerSize = 0;\n if (StoreInst* S = dyn_cast<StoreInst>(QI)) {\n \/\/ All volatile loads\/stores depend on each other\n if (queryIsVolatile && S->isVolatile()) {\n if (!start && !block) {\n depGraphLocal.insert(std::make_pair(query, std::make_pair(S, true)));\n reverseDep[S].insert(query);\n }\n \n return S;\n }\n \n pointer = S->getPointerOperand();\n pointerSize = TD.getTypeSize(S->getOperand(0)->getType());\n } else if (LoadInst* L = dyn_cast<LoadInst>(QI)) {\n \/\/ All volatile loads\/stores depend on each other\n if (queryIsVolatile && L->isVolatile()) {\n if (!start && !block) {\n depGraphLocal.insert(std::make_pair(query, std::make_pair(L, true)));\n reverseDep[L].insert(query);\n }\n \n return L;\n }\n \n pointer = L->getPointerOperand();\n pointerSize = TD.getTypeSize(L->getType());\n } else if (AllocationInst* AI = dyn_cast<AllocationInst>(QI)) {\n pointer = AI;\n if (ConstantInt* C = dyn_cast<ConstantInt>(AI->getArraySize()))\n pointerSize = C->getZExtValue() * \\\n TD.getTypeSize(AI->getAllocatedType());\n else\n pointerSize = ~0UL;\n } else if (VAArgInst* V = dyn_cast<VAArgInst>(QI)) {\n pointer = V->getOperand(0);\n pointerSize = TD.getTypeSize(V->getType());\n } else if (FreeInst* F = dyn_cast<FreeInst>(QI)) {\n pointer = F->getPointerOperand();\n \n \/\/ FreeInsts erase the entire structure\n pointerSize = ~0UL;\n } else if (CallSite::get(QI).getInstruction() != 0) {\n \/\/ Call insts need special handling. Check if they can modify our pointer\n AliasAnalysis::ModRefResult MR = AA.getModRefInfo(CallSite::get(QI),\n dependee, dependeeSize);\n \n if (MR != AliasAnalysis::NoModRef) {\n \/\/ Loads don't depend on read-only calls\n if (isa<LoadInst>(query) && MR == AliasAnalysis::Ref)\n continue;\n \n if (!start && !block) {\n depGraphLocal.insert(std::make_pair(query,\n std::make_pair(QI, true)));\n reverseDep[QI].insert(query);\n }\n \n return QI;\n } else {\n continue;\n }\n }\n \n \/\/ If we found a pointer, check if it could be the same as our pointer\n if (pointer) {\n AliasAnalysis::AliasResult R = AA.alias(pointer, pointerSize,\n dependee, dependeeSize);\n \n if (R != AliasAnalysis::NoAlias) {\n \/\/ May-alias loads don't depend on each other\n if (isa<LoadInst>(query) && isa<LoadInst>(QI) &&\n R == AliasAnalysis::MayAlias)\n continue;\n \n if (!start && !block) {\n depGraphLocal.insert(std::make_pair(query,\n std::make_pair(QI, true)));\n reverseDep[QI].insert(query);\n }\n \n return QI;\n }\n }\n }\n \n \/\/ If we found nothing, return the non-local flag\n if (!start && !block) {\n depGraphLocal.insert(std::make_pair(query,\n std::make_pair(NonLocal, true)));\n reverseDep[NonLocal].insert(query);\n }\n \n return NonLocal;\n}\n\n\/\/\/ removeInstruction - Remove an instruction from the dependence analysis,\n\/\/\/ updating the dependence of instructions that previously depended on it.\n\/\/\/ This method attempts to keep the cache coherent using the reverse map.\nvoid MemoryDependenceAnalysis::removeInstruction(Instruction* rem) {\n \/\/ Figure out the new dep for things that currently depend on rem\n const Instruction* newDep = NonLocal;\n\n depMapType::iterator depGraphEntry = depGraphLocal.find(rem);\n \/\/ We assume here that it's not in the reverse map if it's not in\n \/\/ the dep map. Checking it could be expensive, so don't do it.\n\n if (depGraphEntry != depGraphLocal.end()) {\n if (depGraphEntry->second.first != NonLocal &&\n depGraphEntry->second.second) {\n \/\/ If we have dep info for rem, set them to it\n BasicBlock::iterator RI =\n const_cast<Instruction*>(depGraphEntry->second.first);\n RI++;\n newDep = RI;\n } else if (depGraphEntry->second.first == NonLocal &&\n depGraphEntry->second.second ) {\n \/\/ If we have a confirmed non-local flag, use it\n newDep = NonLocal;\n } else {\n \/\/ Otherwise, use the immediate successor of rem\n \/\/ NOTE: This is because, when getDependence is called, it will first\n \/\/ check the immediate predecessor of what is in the cache.\n BasicBlock::iterator RI = rem;\n RI++;\n newDep = RI;\n }\n \n SmallPtrSet<Instruction*, 4>& set = reverseDep[rem];\n for (SmallPtrSet<Instruction*, 4>::iterator I = set.begin(), E = set.end();\n I != E; ++I) {\n \/\/ Insert the new dependencies\n \/\/ Mark it as unconfirmed as long as it is not the non-local flag\n depGraphLocal[*I] = std::make_pair(newDep, !newDep);\n }\n reverseDep.erase(rem);\n }\n\n getAnalysis<AliasAnalysis>().deleteValue(rem);\n}\n<|endoftext|>"} {"text":"<commit_before>\/****************************************************************************\r\n*\r\n* NAME: smbPitchShift.cpp\r\n* VERSION: 1.2\r\n* HOME URL: http:\/\/blogs.zynaptiq.com\/bernsee\r\n* KNOWN BUGS: none\r\n*\r\n* SYNOPSIS: Routine for doing pitch shifting while maintaining\r\n* duration using the Short Time Fourier Transform.\r\n*\r\n* DESCRIPTION: The routine takes a pitchShift factor value which is between 0.5\r\n* (one octave down) and 2. (one octave up). A value of exactly 1 does not change\r\n* the pitch. numSampsToProcess tells the routine how many samples in indata[0...\r\n* numSampsToProcess-1] should be pitch shifted and moved to outdata[0 ...\r\n* numSampsToProcess-1]. The two buffers can be identical (ie. it can process the\r\n* data in-place). fftFrameSize defines the FFT frame size used for the\r\n* processing. Typical values are 1024, 2048 and 4096. It MUST be a power of 2.\r\n* oversamp is the STFT oversampling factor which also determines the overlap\r\n* between adjacent STFT frames. It should at least be 4 for moderate scaling\r\n* ratios. A value of 32 is recommended for best quality. sampleRate takes the\r\n* sample rate for the signal in unit Hz, ie. 44100 for 44.1 kHz audio. The data\r\n* passed to the routine in indata[] should be in the range [-1.0, 1.0), which is\r\n* also the output range for the data, make sure you scale the data accordingly\r\n* (for 16bit signed integers you would have to divide (and multiply) by 32768).\r\n*\r\n* COPYRIGHT 1999-2015 Stephan M. Bernsee <s.bernsee [AT] zynaptiq [DOT] com>\r\n*\r\n* \t\t\t\t\t\tThe Wide Open License (WOL)\r\n*\r\n* Permission to use, copy, modify, distribute and sell this software and its\r\n* documentation for any purpose is hereby granted without fee, provided that\r\n* the above copyright notice and this license appear in all source copies. \r\n* THIS SOFTWARE IS PROVIDED \"AS IS\" WITHOUT EXPRESS OR IMPLIED WARRANTY OF\r\n* ANY KIND. See http:\/\/www.dspguru.com\/wol.htm for more information.\r\n*\r\n*****************************************************************************\/\r\n\r\n#ifndef SMBPITCHSHIFT_HPP\r\n#define SMBPITCHSHIFT_HPP\r\n\r\n#include <algorithm>\r\n#include <cmath>\r\n#include <cstdint>\r\n\r\nnamespace smb\r\n{\r\n namespace\r\n {\r\n constexpr float pi = 3.14159265358979323846F;\r\n\r\n \/\/ Use own implementation because std::complex has a poor performance\r\n template <class T>\r\n struct Complex final\r\n {\r\n constexpr Complex<T> operator+(const Complex& other) const noexcept\r\n {\r\n return Complex{real + other.real, imag + other.imag};\r\n }\r\n\r\n constexpr Complex<T>& operator+=(const Complex& other)\r\n {\r\n real += other.real;\r\n imag += other.imag;\r\n return *this;\r\n }\r\n\r\n constexpr Complex<T> operator-(const Complex& other) const noexcept\r\n {\r\n return Complex{real - other.real, imag - other.imag};\r\n }\r\n\r\n constexpr Complex<T> operator-() const noexcept\r\n {\r\n return Complex{-real, -imag};\r\n }\r\n\r\n constexpr Complex<T>& operator-=(const Complex& other) noexcept\r\n {\r\n real -= other.real;\r\n imag -= other.imag;\r\n return *this;\r\n }\r\n\r\n constexpr Complex<T> operator*(const Complex& other) const noexcept\r\n {\r\n return Complex{real * other.real - imag * other.imag, real * other.imag + imag * other.real};\r\n }\r\n\r\n constexpr Complex<T>& operator*=(const Complex& other) noexcept\r\n {\r\n float tempReal = real;\r\n real = tempReal * other.real - imag * other.imag;\r\n imag = tempReal * other.imag + imag * other.real;\r\n return *this;\r\n }\r\n\r\n inline T magnitude() const noexcept\r\n {\r\n return sqrt(real * real + imag * imag);\r\n }\r\n\r\n T real;\r\n T imag;\r\n };\r\n\r\n template <int32_t sign, uint32_t fftFrameSize>\r\n void fft(Complex<float>* fftBuffer) noexcept\r\n {\r\n \/\/ Bit-reversal permutation applied to a sequence of fftFrameSize items\r\n for (uint32_t i = 1; i < fftFrameSize - 1; i++)\r\n {\r\n uint32_t j = 0;\r\n\r\n for (uint32_t bitm = 1; bitm < fftFrameSize; bitm <<= 1)\r\n {\r\n if (i & bitm) j++;\r\n j <<= 1;\r\n }\r\n j >>= 1;\r\n\r\n if (i < j)\r\n std::swap(fftBuffer[i], fftBuffer[j]);\r\n }\r\n\r\n \/\/ Iterative form of Danielson–-Lanczos lemma\r\n uint32_t step = 2;\r\n for (uint32_t i = 1; i < fftFrameSize; i <<= 1, step <<= 1)\r\n {\r\n const uint32_t step2 = step >> 1;\r\n const float arg = pi \/ step2;\r\n\r\n const Complex<float> w{std::cos(arg), std::sin(arg) * sign};\r\n Complex<float> u{1.0F, 0.0F};\r\n for (uint32_t j = 0; j < step2; j++)\r\n {\r\n for (uint32_t k = j; k < fftFrameSize; k += step)\r\n {\r\n const Complex<float> temp = fftBuffer[k + step2] * u;\r\n fftBuffer[k + step2] = fftBuffer[k] - temp;\r\n fftBuffer[k] += temp;\r\n }\r\n\r\n u *= w;\r\n }\r\n }\r\n }\r\n }\r\n\r\n template <uint32_t fftFrameSize, uint32_t oversamp>\r\n class PitchShift final\r\n {\r\n public:\r\n PitchShift()\r\n {\r\n \/\/ Hann window\r\n for (uint32_t k = 0; k < fftFrameSize; k++)\r\n window[k] = 0.5F * (1.0F + std::cos(2.0F * pi * static_cast<float>(k) \/ static_cast<float>(fftFrameSize)));\r\n }\r\n\r\n \/*\r\n Routine process(). See top of file for explanation\r\n Purpose: doing pitch shifting while maintaining duration using the Short\r\n Time Fourier Transform.\r\n Author: (c)1999-2015 Stephan M. Bernsee <s.bernsee [AT] zynaptiq [DOT] com>\r\n *\/\r\n void process(const float pitchShift, const uint32_t numSampsToProcess,\r\n const uint32_t sampleRate, const float* indata, float* outdata) noexcept\r\n {\r\n \/\/ set up some handy variables\r\n const uint32_t fftFrameSizeHalf = fftFrameSize \/ 2;\r\n const uint32_t stepSize = fftFrameSize \/ oversamp;\r\n const float freqPerBin = static_cast<float>(sampleRate) \/ static_cast<float>(fftFrameSize);\r\n const float expected = 2.0F * pi * static_cast<float>(stepSize) \/ static_cast<float>(fftFrameSize);\r\n const uint32_t inFifoLatency = fftFrameSize - stepSize;\r\n if (rover == 0) rover = inFifoLatency;\r\n\r\n \/\/ main processing loop\r\n for (uint32_t i = 0; i < numSampsToProcess; i++)\r\n {\r\n \/\/ As long as we have not yet collected enough data just read in\r\n inFifo[rover] = indata[i];\r\n outdata[i] = outFifo[rover - inFifoLatency];\r\n rover++;\r\n\r\n \/\/ now we have enough data for processing\r\n if (rover >= fftFrameSize)\r\n {\r\n rover = inFifoLatency;\r\n\r\n \/\/ do windowing\r\n for (uint32_t k = 0; k < fftFrameSize; k++)\r\n {\r\n fftWorksp[k].real = inFifo[k] * window[k];\r\n fftWorksp[k].imag = 0.0F;\r\n }\r\n\r\n \/\/ ***************** ANALYSIS *******************\r\n \/\/ do transform\r\n fft<-1, fftFrameSize>(fftWorksp);\r\n\r\n \/\/ this is the analysis step\r\n for (uint32_t k = 0; k <= fftFrameSizeHalf; k++)\r\n {\r\n const Complex<float>& current = fftWorksp[k];\r\n\r\n \/\/ compute magnitude and phase\r\n const float magn = 2.0F * current.magnitude();\r\n const float signx = (current.imag > 0.0F) ? 1.0F : -1.0F;\r\n const float phase = (current.imag == 0.0F) ? 0.0F :\r\n (current.real == 0.0F) ? signx * pi \/ 2.0F :\r\n std::atan2(current.imag, current.real);\r\n\r\n \/\/ compute phase difference\r\n float tmp = phase - lastPhase[k];\r\n lastPhase[k] = phase;\r\n\r\n \/\/ subtract expected phase difference\r\n tmp -= static_cast<float>(k) * expected;\r\n\r\n \/\/ map delta phase into +\/- Pi interval\r\n int32_t qpd = static_cast<int32_t>(tmp \/ pi);\r\n if (qpd >= 0) qpd += qpd & 1;\r\n else qpd -= qpd & 1;\r\n tmp -= pi * static_cast<float>(qpd);\r\n\r\n \/\/ get deviation from bin frequency from the +\/- Pi interval\r\n tmp = oversamp * tmp \/ (2.0F * pi);\r\n\r\n \/\/ compute the k-th partials' true frequency\r\n tmp = static_cast<float>(k) * freqPerBin + tmp * freqPerBin;\r\n\r\n \/\/ store magnitude and true frequency in analysis arrays\r\n anaMagn[k] = magn;\r\n anaFreq[k] = tmp;\r\n }\r\n\r\n \/\/ ***************** PROCESSING *******************\r\n \/\/ this does the actual pitch shifting\r\n std::fill(std::begin(synMagn), std::begin(synMagn) + fftFrameSize, 0.0F);\r\n std::fill(std::begin(synFreq), std::begin(synFreq) + fftFrameSize, 0.0F);\r\n for (uint32_t k = 0; k <= fftFrameSizeHalf; k++)\r\n {\r\n const uint32_t index = static_cast<uint32_t>(k * pitchShift);\r\n if (index > fftFrameSizeHalf) break;\r\n synMagn[index] += anaMagn[k];\r\n synFreq[index] = anaFreq[k] * pitchShift;\r\n }\r\n\r\n \/\/ ***************** SYNTHESIS *******************\r\n \/\/ this is the synthesis step\r\n for (uint32_t k = 0; k <= fftFrameSizeHalf; k++)\r\n {\r\n \/\/ get magnitude and true frequency from synthesis arrays\r\n const float magn = synMagn[k];\r\n float tmp = synFreq[k];\r\n\r\n \/\/ subtract bin mid frequency\r\n tmp -= static_cast<float>(k) * freqPerBin;\r\n\r\n \/\/ get bin deviation from freq deviation\r\n tmp \/= freqPerBin;\r\n\r\n \/\/ take oversampling factor into account\r\n tmp = 2.0F * pi * tmp \/ oversamp;\r\n\r\n \/\/ add the overlap phase advance back in\r\n tmp += static_cast<float>(k) * expected;\r\n\r\n \/\/ accumulate delta phase to get bin phase\r\n sumPhase[k] += tmp;\r\n const float phase = sumPhase[k];\r\n\r\n \/\/ get real and imag part and re-interleave\r\n fftWorksp[k].real = magn * std::cos(phase);\r\n fftWorksp[k].imag = magn * std::sin(phase);\r\n }\r\n\r\n \/\/ zero negative frequencies\r\n for (uint32_t k = fftFrameSize + 1; k < fftFrameSize; k++)\r\n fftWorksp[k] = {0.0F, 0.0F};\r\n\r\n \/\/ do inverse transform\r\n fft<1, fftFrameSize>(fftWorksp);\r\n\r\n \/\/ do windowing and add to output accumulator\r\n for (uint32_t k = 0; k < fftFrameSize; k++)\r\n outputAccum[k] += 2.0F * window[k] * fftWorksp[k].real \/ (fftFrameSizeHalf * oversamp);\r\n\r\n uint32_t k;\r\n for (k = 0 ; k < stepSize; k++)\r\n outFifo[k] = outputAccum[k];\r\n \/\/ shift accumulator\r\n uint32_t j;\r\n for (j = 0; k < fftFrameSize; k++, j++)\r\n outputAccum[j] = outputAccum[k];\r\n for (; j < fftFrameSize; j++)\r\n outputAccum[j] = 0.0;\r\n\r\n \/\/ move input FIFO\r\n for (k = 0; k < inFifoLatency; k++)\r\n inFifo[k] = inFifo[k + stepSize];\r\n }\r\n }\r\n }\r\n\r\n private:\r\n float window[fftFrameSize]; \/\/ the windowing function\r\n float inFifo[fftFrameSize]{0.0F};\r\n float outFifo[fftFrameSize]{0.0F};\r\n Complex<float> fftWorksp[fftFrameSize]{{0.0F, 0.0F}};\r\n float lastPhase[fftFrameSize \/ 2 + 1]{0.0F};\r\n float sumPhase[fftFrameSize \/ 2 + 1]{0.0F};\r\n float outputAccum[2 * fftFrameSize]{0.0F};\r\n float anaFreq[fftFrameSize]{0.0F};\r\n float anaMagn[fftFrameSize]{0.0F};\r\n float synFreq[fftFrameSize]{0.0F};\r\n float synMagn[fftFrameSize]{0.0F};\r\n uint32_t rover = 0;\r\n };\r\n}\r\n\r\n#endif\r\n<commit_msg>Refactor the for loops to indicate that iteration is being done to fftFrameSizeHalf + 1<commit_after>\/****************************************************************************\r\n*\r\n* NAME: smbPitchShift.cpp\r\n* VERSION: 1.2\r\n* HOME URL: http:\/\/blogs.zynaptiq.com\/bernsee\r\n* KNOWN BUGS: none\r\n*\r\n* SYNOPSIS: Routine for doing pitch shifting while maintaining\r\n* duration using the Short Time Fourier Transform.\r\n*\r\n* DESCRIPTION: The routine takes a pitchShift factor value which is between 0.5\r\n* (one octave down) and 2. (one octave up). A value of exactly 1 does not change\r\n* the pitch. numSampsToProcess tells the routine how many samples in indata[0...\r\n* numSampsToProcess-1] should be pitch shifted and moved to outdata[0 ...\r\n* numSampsToProcess-1]. The two buffers can be identical (ie. it can process the\r\n* data in-place). fftFrameSize defines the FFT frame size used for the\r\n* processing. Typical values are 1024, 2048 and 4096. It MUST be a power of 2.\r\n* oversamp is the STFT oversampling factor which also determines the overlap\r\n* between adjacent STFT frames. It should at least be 4 for moderate scaling\r\n* ratios. A value of 32 is recommended for best quality. sampleRate takes the\r\n* sample rate for the signal in unit Hz, ie. 44100 for 44.1 kHz audio. The data\r\n* passed to the routine in indata[] should be in the range [-1.0, 1.0), which is\r\n* also the output range for the data, make sure you scale the data accordingly\r\n* (for 16bit signed integers you would have to divide (and multiply) by 32768).\r\n*\r\n* COPYRIGHT 1999-2015 Stephan M. Bernsee <s.bernsee [AT] zynaptiq [DOT] com>\r\n*\r\n* \t\t\t\t\t\tThe Wide Open License (WOL)\r\n*\r\n* Permission to use, copy, modify, distribute and sell this software and its\r\n* documentation for any purpose is hereby granted without fee, provided that\r\n* the above copyright notice and this license appear in all source copies. \r\n* THIS SOFTWARE IS PROVIDED \"AS IS\" WITHOUT EXPRESS OR IMPLIED WARRANTY OF\r\n* ANY KIND. See http:\/\/www.dspguru.com\/wol.htm for more information.\r\n*\r\n*****************************************************************************\/\r\n\r\n#ifndef SMBPITCHSHIFT_HPP\r\n#define SMBPITCHSHIFT_HPP\r\n\r\n#include <algorithm>\r\n#include <cmath>\r\n#include <cstdint>\r\n\r\nnamespace smb\r\n{\r\n namespace\r\n {\r\n constexpr float pi = 3.14159265358979323846F;\r\n\r\n \/\/ Use own implementation because std::complex has a poor performance\r\n template <class T>\r\n struct Complex final\r\n {\r\n constexpr Complex<T> operator+(const Complex& other) const noexcept\r\n {\r\n return Complex{real + other.real, imag + other.imag};\r\n }\r\n\r\n constexpr Complex<T>& operator+=(const Complex& other)\r\n {\r\n real += other.real;\r\n imag += other.imag;\r\n return *this;\r\n }\r\n\r\n constexpr Complex<T> operator-(const Complex& other) const noexcept\r\n {\r\n return Complex{real - other.real, imag - other.imag};\r\n }\r\n\r\n constexpr Complex<T> operator-() const noexcept\r\n {\r\n return Complex{-real, -imag};\r\n }\r\n\r\n constexpr Complex<T>& operator-=(const Complex& other) noexcept\r\n {\r\n real -= other.real;\r\n imag -= other.imag;\r\n return *this;\r\n }\r\n\r\n constexpr Complex<T> operator*(const Complex& other) const noexcept\r\n {\r\n return Complex{real * other.real - imag * other.imag, real * other.imag + imag * other.real};\r\n }\r\n\r\n constexpr Complex<T>& operator*=(const Complex& other) noexcept\r\n {\r\n float tempReal = real;\r\n real = tempReal * other.real - imag * other.imag;\r\n imag = tempReal * other.imag + imag * other.real;\r\n return *this;\r\n }\r\n\r\n inline T magnitude() const noexcept\r\n {\r\n return sqrt(real * real + imag * imag);\r\n }\r\n\r\n T real;\r\n T imag;\r\n };\r\n\r\n template <int32_t sign, uint32_t fftFrameSize>\r\n void fft(Complex<float>* fftBuffer) noexcept\r\n {\r\n \/\/ Bit-reversal permutation applied to a sequence of fftFrameSize items\r\n for (uint32_t i = 1; i < fftFrameSize - 1; i++)\r\n {\r\n uint32_t j = 0;\r\n\r\n for (uint32_t bitm = 1; bitm < fftFrameSize; bitm <<= 1)\r\n {\r\n if (i & bitm) j++;\r\n j <<= 1;\r\n }\r\n j >>= 1;\r\n\r\n if (i < j)\r\n std::swap(fftBuffer[i], fftBuffer[j]);\r\n }\r\n\r\n \/\/ Iterative form of Danielson–-Lanczos lemma\r\n uint32_t step = 2;\r\n for (uint32_t i = 1; i < fftFrameSize; i <<= 1, step <<= 1)\r\n {\r\n const uint32_t step2 = step >> 1;\r\n const float arg = pi \/ step2;\r\n\r\n const Complex<float> w{std::cos(arg), std::sin(arg) * sign};\r\n Complex<float> u{1.0F, 0.0F};\r\n for (uint32_t j = 0; j < step2; j++)\r\n {\r\n for (uint32_t k = j; k < fftFrameSize; k += step)\r\n {\r\n const Complex<float> temp = fftBuffer[k + step2] * u;\r\n fftBuffer[k + step2] = fftBuffer[k] - temp;\r\n fftBuffer[k] += temp;\r\n }\r\n\r\n u *= w;\r\n }\r\n }\r\n }\r\n }\r\n\r\n template <uint32_t fftFrameSize, uint32_t oversamp>\r\n class PitchShift final\r\n {\r\n public:\r\n PitchShift()\r\n {\r\n \/\/ Hann window\r\n for (uint32_t k = 0; k < fftFrameSize; k++)\r\n window[k] = 0.5F * (1.0F + std::cos(2.0F * pi * static_cast<float>(k) \/ static_cast<float>(fftFrameSize)));\r\n }\r\n\r\n \/*\r\n Routine process(). See top of file for explanation\r\n Purpose: doing pitch shifting while maintaining duration using the Short\r\n Time Fourier Transform.\r\n Author: (c)1999-2015 Stephan M. Bernsee <s.bernsee [AT] zynaptiq [DOT] com>\r\n *\/\r\n void process(const float pitchShift, const uint32_t numSampsToProcess,\r\n const uint32_t sampleRate, const float* indata, float* outdata) noexcept\r\n {\r\n \/\/ set up some handy variables\r\n const uint32_t fftFrameSizeHalf = fftFrameSize \/ 2;\r\n const uint32_t stepSize = fftFrameSize \/ oversamp;\r\n const float freqPerBin = static_cast<float>(sampleRate) \/ static_cast<float>(fftFrameSize);\r\n const float expected = 2.0F * pi * static_cast<float>(stepSize) \/ static_cast<float>(fftFrameSize);\r\n const uint32_t inFifoLatency = fftFrameSize - stepSize;\r\n if (rover == 0) rover = inFifoLatency;\r\n\r\n \/\/ main processing loop\r\n for (uint32_t i = 0; i < numSampsToProcess; i++)\r\n {\r\n \/\/ As long as we have not yet collected enough data just read in\r\n inFifo[rover] = indata[i];\r\n outdata[i] = outFifo[rover - inFifoLatency];\r\n rover++;\r\n\r\n \/\/ now we have enough data for processing\r\n if (rover >= fftFrameSize)\r\n {\r\n rover = inFifoLatency;\r\n\r\n \/\/ do windowing\r\n for (uint32_t k = 0; k < fftFrameSize; k++)\r\n {\r\n fftWorksp[k].real = inFifo[k] * window[k];\r\n fftWorksp[k].imag = 0.0F;\r\n }\r\n\r\n \/\/ ***************** ANALYSIS *******************\r\n \/\/ do transform\r\n fft<-1, fftFrameSize>(fftWorksp);\r\n\r\n \/\/ this is the analysis step\r\n for (uint32_t k = 0; k < fftFrameSizeHalf + 1; k++)\r\n {\r\n const Complex<float>& current = fftWorksp[k];\r\n\r\n \/\/ compute magnitude and phase\r\n const float magn = 2.0F * current.magnitude();\r\n const float signx = (current.imag > 0.0F) ? 1.0F : -1.0F;\r\n const float phase = (current.imag == 0.0F) ? 0.0F :\r\n (current.real == 0.0F) ? signx * pi \/ 2.0F :\r\n std::atan2(current.imag, current.real);\r\n\r\n \/\/ compute phase difference\r\n float tmp = phase - lastPhase[k];\r\n lastPhase[k] = phase;\r\n\r\n \/\/ subtract expected phase difference\r\n tmp -= static_cast<float>(k) * expected;\r\n\r\n \/\/ map delta phase into +\/- Pi interval\r\n int32_t qpd = static_cast<int32_t>(tmp \/ pi);\r\n if (qpd >= 0) qpd += qpd & 1;\r\n else qpd -= qpd & 1;\r\n tmp -= pi * static_cast<float>(qpd);\r\n\r\n \/\/ get deviation from bin frequency from the +\/- Pi interval\r\n tmp = oversamp * tmp \/ (2.0F * pi);\r\n\r\n \/\/ compute the k-th partials' true frequency\r\n tmp = static_cast<float>(k) * freqPerBin + tmp * freqPerBin;\r\n\r\n \/\/ store magnitude and true frequency in analysis arrays\r\n anaMagn[k] = magn;\r\n anaFreq[k] = tmp;\r\n }\r\n\r\n \/\/ ***************** PROCESSING *******************\r\n \/\/ this does the actual pitch shifting\r\n std::fill(std::begin(synMagn), std::begin(synMagn) + fftFrameSize, 0.0F);\r\n std::fill(std::begin(synFreq), std::begin(synFreq) + fftFrameSize, 0.0F);\r\n for (uint32_t k = 0; k < fftFrameSizeHalf + 1; k++)\r\n {\r\n const uint32_t index = static_cast<uint32_t>(k * pitchShift);\r\n if (index > fftFrameSizeHalf) break;\r\n synMagn[index] += anaMagn[k];\r\n synFreq[index] = anaFreq[k] * pitchShift;\r\n }\r\n\r\n \/\/ ***************** SYNTHESIS *******************\r\n \/\/ this is the synthesis step\r\n for (uint32_t k = 0; k < fftFrameSizeHalf + 1; k++)\r\n {\r\n \/\/ get magnitude and true frequency from synthesis arrays\r\n const float magn = synMagn[k];\r\n float tmp = synFreq[k];\r\n\r\n \/\/ subtract bin mid frequency\r\n tmp -= static_cast<float>(k) * freqPerBin;\r\n\r\n \/\/ get bin deviation from freq deviation\r\n tmp \/= freqPerBin;\r\n\r\n \/\/ take oversampling factor into account\r\n tmp = 2.0F * pi * tmp \/ oversamp;\r\n\r\n \/\/ add the overlap phase advance back in\r\n tmp += static_cast<float>(k) * expected;\r\n\r\n \/\/ accumulate delta phase to get bin phase\r\n sumPhase[k] += tmp;\r\n const float phase = sumPhase[k];\r\n\r\n \/\/ get real and imag part and re-interleave\r\n fftWorksp[k].real = magn * std::cos(phase);\r\n fftWorksp[k].imag = magn * std::sin(phase);\r\n }\r\n\r\n \/\/ zero negative frequencies\r\n for (uint32_t k = fftFrameSize + 1; k < fftFrameSize; k++)\r\n fftWorksp[k] = {0.0F, 0.0F};\r\n\r\n \/\/ do inverse transform\r\n fft<1, fftFrameSize>(fftWorksp);\r\n\r\n \/\/ do windowing and add to output accumulator\r\n for (uint32_t k = 0; k < fftFrameSize; k++)\r\n outputAccum[k] += 2.0F * window[k] * fftWorksp[k].real \/ (fftFrameSizeHalf * oversamp);\r\n\r\n uint32_t k;\r\n for (k = 0 ; k < stepSize; k++)\r\n outFifo[k] = outputAccum[k];\r\n \/\/ shift accumulator\r\n uint32_t j;\r\n for (j = 0; k < fftFrameSize; k++, j++)\r\n outputAccum[j] = outputAccum[k];\r\n for (; j < fftFrameSize; j++)\r\n outputAccum[j] = 0.0;\r\n\r\n \/\/ move input FIFO\r\n for (k = 0; k < inFifoLatency; k++)\r\n inFifo[k] = inFifo[k + stepSize];\r\n }\r\n }\r\n }\r\n\r\n private:\r\n float window[fftFrameSize]; \/\/ the windowing function\r\n float inFifo[fftFrameSize]{0.0F};\r\n float outFifo[fftFrameSize]{0.0F};\r\n Complex<float> fftWorksp[fftFrameSize]{{0.0F, 0.0F}};\r\n float lastPhase[fftFrameSize \/ 2 + 1]{0.0F};\r\n float sumPhase[fftFrameSize \/ 2 + 1]{0.0F};\r\n float outputAccum[2 * fftFrameSize]{0.0F};\r\n float anaFreq[fftFrameSize]{0.0F};\r\n float anaMagn[fftFrameSize]{0.0F};\r\n float synFreq[fftFrameSize]{0.0F};\r\n float synMagn[fftFrameSize]{0.0F};\r\n uint32_t rover = 0;\r\n };\r\n}\r\n\r\n#endif\r\n<|endoftext|>"} {"text":"<commit_before>\/* Copyright 2017 R. Thomas\n * Copyright 2017 Quarkslab\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n#include <iterator>\n#include <iostream>\n#include \"LIEF\/iostream.hpp\"\n\nnamespace LIEF {\nvector_iostream::vector_iostream(bool endian_swap) : endian_swap_{endian_swap} {}\n\nsize_t vector_iostream::uleb128_size(uint64_t value) {\n size_t size = 0;\n do {\n value >>= 7;\n size += sizeof(int8_t);\n } while(value);\n return size;\n}\n\nsize_t vector_iostream::sleb128_size(int64_t value) {\n size_t size = 0;\n int sign = value >> (8 * sizeof(value) - 1);\n bool is_more;\n do {\n size_t byte = value & 0x7F;\n value >>= 7;\n is_more = value != sign or ((byte ^ sign) & 0x40) != 0;\n size += sizeof(int8_t);\n } while (is_more);\n return size;\n}\n\n\nvoid vector_iostream::reserve(size_t size) {\n this->raw_.reserve(size);\n}\nvector_iostream& vector_iostream::put(uint8_t c) {\n\n if (this->raw_.size() < (static_cast<size_t>(this->tellp()) + 1)) {\n this->raw_.resize(static_cast<size_t>(this->tellp()) + 1);\n }\n this->raw_[this->tellp()] = c;\n this->current_pos_ += 1;\n return *this;\n}\nvector_iostream& vector_iostream::write(const uint8_t* s, std::streamsize n) {\n if (this->raw_.size() < (static_cast<size_t>(this->tellp()) + n)) {\n this->raw_.resize(static_cast<size_t>(this->tellp()) + n);\n }\n\n auto&& it = std::begin(this->raw_);\n std::advance(it, static_cast<size_t>(this->tellp()));\n std::copy(s, s + n, it);\n\n this->current_pos_ += n;\n return *this;\n}\n\nvector_iostream& vector_iostream::write(const std::vector<uint8_t>& s) {\n if (this->raw_.size() < (static_cast<size_t>(this->tellp()) + s.size())) {\n this->raw_.resize(static_cast<size_t>(this->tellp()) + s.size());\n }\n auto&& it = std::begin(this->raw_);\n std::advance(it, static_cast<size_t>(this->tellp()));\n std::copy(std::begin(s), std::end(s), it);\n\n this->current_pos_ += s.size();\n return *this;\n}\n\n\nvector_iostream& vector_iostream::write(std::vector<uint8_t>&& s) {\n if (this->raw_.size() < (static_cast<size_t>(this->tellp()) + s.size())) {\n this->raw_.resize(static_cast<size_t>(this->tellp()) + s.size());\n }\n auto&& it = std::begin(this->raw_);\n std::advance(it, static_cast<size_t>(this->tellp()));\n std::move(\n std::begin(s),\n std::end(s), it);\n\n this->current_pos_ += s.size();\n return *this;\n}\n\nvector_iostream& vector_iostream::write(const std::string& s) {\n if (this->raw_.size() < (static_cast<size_t>(this->tellp()) + s.size() + 1)) {\n this->raw_.resize(static_cast<size_t>(this->tellp()) + s.size() + 1);\n }\n\n auto&& it = std::begin(this->raw_);\n std::advance(it, static_cast<size_t>(this->tellp()));\n std::copy(std::begin(s), std::end(s), it);\n\n this->current_pos_ += s.size() + 1;\n return *this;\n}\n\n\nvector_iostream& vector_iostream::write_uleb128(uint64_t value) {\n uint8_t byte;\n\tdo {\n byte = value & 0x7F;\n\t\tvalue &= ~0x7F;\n\t\tif (value != 0) {\n\t\t byte |= 0x80;\n }\n this->write<uint8_t>(byte);\n\t\tvalue = value >> 7;\n\t} while (byte >= 0x80);\n\n return *this;\n}\n\nvector_iostream& vector_iostream::write_sleb128(int64_t value) {\n\n bool is_neg = (value < 0);\n\tuint8_t byte;\n\tbool more;\n\tdo {\n\t byte = value & 0x7F;\n\t\tvalue = value >> 7;\n\n if (is_neg) {\n\t\t more = ((value != -1) || ((byte & 0x40) == 0));\n } else {\n\t\t more = ((value != 0) || ((byte & 0x40) != 0));\n }\n\t\tif (more) {\n\t\t byte |= 0x80;\n this->write<uint8_t>(byte);\n }\n\t} while (more);\n\n return *this;\n}\n\n\nvector_iostream& vector_iostream::get(std::vector<uint8_t>& c) {\n c = this->raw_;\n return *this;\n}\n\nvector_iostream& vector_iostream::flush() {\n return *this;\n}\n\nconst std::vector<uint8_t>& vector_iostream::raw(void) const {\n return this->raw_;\n}\n\nsize_t vector_iostream::size(void) const {\n return this->raw_.size();\n}\n\n\/\/ seeks:\nvector_iostream::pos_type vector_iostream::tellp(void) {\n return this->current_pos_;\n}\nvector_iostream& vector_iostream::seekp(vector_iostream::pos_type p) {\n this->current_pos_ = p;\n return *this;\n}\nvector_iostream& vector_iostream::seekp(vector_iostream::off_type p, std::ios_base::seekdir dir) {\n switch (dir) {\n case std::ios_base::beg:\n {\n this->current_pos_ = p;\n break;\n }\n\n\n case std::ios_base::end:\n {\n \/\/this->current_pos_ = p;\n break;\n }\n\n\n case std::ios_base::cur:\n {\n this->current_pos_ += p;\n break;\n }\n\n default:\n {\n break;\n }\n }\n\n return *this;\n}\n\nvector_iostream& vector_iostream::align(size_t alignment, uint8_t fill) {\n if (this->raw_.size() % alignment == 0) {\n return *this;\n }\n\n while (this->raw_.size() % alignment != 0) {\n this->write<uint8_t>(fill);\n }\n\n return *this;\n}\n\n\nvoid vector_iostream::set_endian_swap(bool swap) {\n this->endian_swap_ = swap;\n}\n\n\n\/\/ Prefixbuf\nprefixbuf::prefixbuf(std::string const& prefix, std::streambuf* sbuf) :\n prefix{prefix},\n sbuf{sbuf},\n need_prefix{true}\n{}\n\nint prefixbuf::sync() {\n return this->sbuf->pubsync();\n}\nint prefixbuf::overflow(int c) {\n if (c != std::char_traits<char>::eof()) {\n if (this->need_prefix and not this->prefix.empty() and\n this->prefix.size() != this->sbuf->sputn(&this->prefix[0], this->prefix.size())) {\n return std::char_traits<char>::eof();\n }\n\n this->need_prefix = c == '\\n';\n }\n\n return this->sbuf->sputc(c);\n}\n\n\noprefixstream::oprefixstream(std::string const& prefix, std::ostream& out) :\n prefixbuf(prefix, out.rdbuf()),\n std::ios(static_cast<std::streambuf*>(this)),\n std::ostream(static_cast<std::streambuf*>(this))\n{}\n\n\n\n}\n\n<commit_msg>Fix bug<commit_after>\/* Copyright 2017 R. Thomas\n * Copyright 2017 Quarkslab\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n#include <iterator>\n#include <iostream>\n#include \"LIEF\/iostream.hpp\"\n\nnamespace LIEF {\nvector_iostream::vector_iostream(bool endian_swap) : endian_swap_{endian_swap} {}\n\nsize_t vector_iostream::uleb128_size(uint64_t value) {\n size_t size = 0;\n do {\n value >>= 7;\n size += sizeof(int8_t);\n } while(value);\n return size;\n}\n\nsize_t vector_iostream::sleb128_size(int64_t value) {\n size_t size = 0;\n int sign = value >> (8 * sizeof(value) - 1);\n bool is_more;\n do {\n size_t byte = value & 0x7F;\n value >>= 7;\n is_more = value != sign or ((byte ^ sign) & 0x40) != 0;\n size += sizeof(int8_t);\n } while (is_more);\n return size;\n}\n\n\nvoid vector_iostream::reserve(size_t size) {\n this->raw_.reserve(size);\n}\nvector_iostream& vector_iostream::put(uint8_t c) {\n\n if (this->raw_.size() < (static_cast<size_t>(this->tellp()) + 1)) {\n this->raw_.resize(static_cast<size_t>(this->tellp()) + 1);\n }\n this->raw_[this->tellp()] = c;\n this->current_pos_ += 1;\n return *this;\n}\nvector_iostream& vector_iostream::write(const uint8_t* s, std::streamsize n) {\n if (this->raw_.size() < (static_cast<size_t>(this->tellp()) + n)) {\n this->raw_.resize(static_cast<size_t>(this->tellp()) + n);\n }\n\n auto&& it = std::begin(this->raw_);\n std::advance(it, static_cast<size_t>(this->tellp()));\n std::copy(s, s + n, it);\n\n this->current_pos_ += n;\n return *this;\n}\n\nvector_iostream& vector_iostream::write(const std::vector<uint8_t>& s) {\n if (this->raw_.size() < (static_cast<size_t>(this->tellp()) + s.size())) {\n this->raw_.resize(static_cast<size_t>(this->tellp()) + s.size());\n }\n auto&& it = std::begin(this->raw_);\n std::advance(it, static_cast<size_t>(this->tellp()));\n std::copy(std::begin(s), std::end(s), it);\n\n this->current_pos_ += s.size();\n return *this;\n}\n\n\nvector_iostream& vector_iostream::write(std::vector<uint8_t>&& s) {\n if (this->raw_.size() < (static_cast<size_t>(this->tellp()) + s.size())) {\n this->raw_.resize(static_cast<size_t>(this->tellp()) + s.size());\n }\n auto&& it = std::begin(this->raw_);\n std::advance(it, static_cast<size_t>(this->tellp()));\n std::move(\n std::begin(s),\n std::end(s), it);\n\n this->current_pos_ += s.size();\n return *this;\n}\n\nvector_iostream& vector_iostream::write(const std::string& s) {\n if (this->raw_.size() < (static_cast<size_t>(this->tellp()) + s.size() + 1)) {\n this->raw_.resize(static_cast<size_t>(this->tellp()) + s.size() + 1);\n }\n\n auto&& it = std::begin(this->raw_);\n std::advance(it, static_cast<size_t>(this->tellp()));\n std::copy(std::begin(s), std::end(s), it);\n\n this->current_pos_ += s.size() + 1;\n return *this;\n}\n\n\nvector_iostream& vector_iostream::write_uleb128(uint64_t value) {\n uint8_t byte;\n\tdo {\n byte = value & 0x7F;\n\t\tvalue &= ~0x7F;\n\t\tif (value != 0) {\n\t\t byte |= 0x80;\n }\n this->write<uint8_t>(byte);\n\t\tvalue = value >> 7;\n\t} while (byte >= 0x80);\n\n return *this;\n}\n\nvector_iostream& vector_iostream::write_sleb128(int64_t value) {\n\n bool is_neg = (value < 0);\n\tuint8_t byte;\n\tbool more;\n\tdo {\n\t byte = value & 0x7F;\n\t\tvalue = value >> 7;\n\n if (is_neg) {\n\t\t more = ((value != -1) || ((byte & 0x40) == 0));\n } else {\n\t\t more = ((value != 0) || ((byte & 0x40) != 0));\n }\n\t\tif (more) {\n\t\t byte |= 0x80;\n }\n this->write<uint8_t>(byte);\n\t} while (more);\n\n return *this;\n}\n\n\nvector_iostream& vector_iostream::get(std::vector<uint8_t>& c) {\n c = this->raw_;\n return *this;\n}\n\nvector_iostream& vector_iostream::flush() {\n return *this;\n}\n\nconst std::vector<uint8_t>& vector_iostream::raw(void) const {\n return this->raw_;\n}\n\nsize_t vector_iostream::size(void) const {\n return this->raw_.size();\n}\n\n\/\/ seeks:\nvector_iostream::pos_type vector_iostream::tellp(void) {\n return this->current_pos_;\n}\nvector_iostream& vector_iostream::seekp(vector_iostream::pos_type p) {\n this->current_pos_ = p;\n return *this;\n}\nvector_iostream& vector_iostream::seekp(vector_iostream::off_type p, std::ios_base::seekdir dir) {\n switch (dir) {\n case std::ios_base::beg:\n {\n this->current_pos_ = p;\n break;\n }\n\n\n case std::ios_base::end:\n {\n \/\/this->current_pos_ = p;\n break;\n }\n\n\n case std::ios_base::cur:\n {\n this->current_pos_ += p;\n break;\n }\n\n default:\n {\n break;\n }\n }\n\n return *this;\n}\n\nvector_iostream& vector_iostream::align(size_t alignment, uint8_t fill) {\n if (this->raw_.size() % alignment == 0) {\n return *this;\n }\n\n while (this->raw_.size() % alignment != 0) {\n this->write<uint8_t>(fill);\n }\n\n return *this;\n}\n\n\nvoid vector_iostream::set_endian_swap(bool swap) {\n this->endian_swap_ = swap;\n}\n\n\n\/\/ Prefixbuf\nprefixbuf::prefixbuf(std::string const& prefix, std::streambuf* sbuf) :\n prefix{prefix},\n sbuf{sbuf},\n need_prefix{true}\n{}\n\nint prefixbuf::sync() {\n return this->sbuf->pubsync();\n}\nint prefixbuf::overflow(int c) {\n if (c != std::char_traits<char>::eof()) {\n if (this->need_prefix and not this->prefix.empty() and\n this->prefix.size() != this->sbuf->sputn(&this->prefix[0], this->prefix.size())) {\n return std::char_traits<char>::eof();\n }\n\n this->need_prefix = c == '\\n';\n }\n\n return this->sbuf->sputc(c);\n}\n\n\noprefixstream::oprefixstream(std::string const& prefix, std::ostream& out) :\n prefixbuf(prefix, out.rdbuf()),\n std::ios(static_cast<std::streambuf*>(this)),\n std::ostream(static_cast<std::streambuf*>(this))\n{}\n\n\n\n}\n\n<|endoftext|>"} {"text":"<commit_before>#include \"CartoOfflineVectorTileLayer.h\"\n#include \"datasources\/PackageManagerTileDataSource.h\"\n#include \"packagemanager\/CartoPackageManager.h\"\n#include \"utils\/AssetPackage.h\"\n#include \"utils\/Log.h\"\n\nnamespace carto {\n \n CartoOfflineVectorTileLayer::CartoOfflineVectorTileLayer(const std::shared_ptr<CartoPackageManager>& packageManager, CartoBaseMapStyle::CartoBaseMapStyle style) :\n CartoVectorTileLayer(std::make_shared<PackageManagerTileDataSource>(packageManager), style)\n {\n }\n\n CartoOfflineVectorTileLayer::CartoOfflineVectorTileLayer(const std::shared_ptr<CartoPackageManager>& packageManager, const std::shared_ptr<AssetPackage>& styleAssetPackage) :\n CartoVectorTileLayer(std::make_shared<PackageManagerTileDataSource>(packageManager), styleAssetPackage)\n {\n }\n \n CartoOfflineVectorTileLayer::~CartoOfflineVectorTileLayer() {\n }\n \n}\n<commit_msg>Enable tile preloading by default for CartoOfflineVectorTileLayer<commit_after>#include \"CartoOfflineVectorTileLayer.h\"\n#include \"datasources\/PackageManagerTileDataSource.h\"\n#include \"packagemanager\/CartoPackageManager.h\"\n#include \"utils\/AssetPackage.h\"\n#include \"utils\/Log.h\"\n\nnamespace carto {\n \n CartoOfflineVectorTileLayer::CartoOfflineVectorTileLayer(const std::shared_ptr<CartoPackageManager>& packageManager, CartoBaseMapStyle::CartoBaseMapStyle style) :\n CartoVectorTileLayer(std::make_shared<PackageManagerTileDataSource>(packageManager), style)\n {\n _preloading = true; \/\/ turn preloading on by default\n }\n\n CartoOfflineVectorTileLayer::CartoOfflineVectorTileLayer(const std::shared_ptr<CartoPackageManager>& packageManager, const std::shared_ptr<AssetPackage>& styleAssetPackage) :\n CartoVectorTileLayer(std::make_shared<PackageManagerTileDataSource>(packageManager), styleAssetPackage)\n {\n _preloading = true; \/\/ turn preloading on by default\n }\n \n CartoOfflineVectorTileLayer::~CartoOfflineVectorTileLayer() {\n }\n \n}\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: breakiterator_th.hxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: khong $ $Date: 2002-05-03 19:09:09 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n#ifndef _I18N_BREAKITERATOR_TH_HXX_\n#define _I18N_BREAKITERATOR_TH_HXX_\n\n#include <breakiterator_ctl.hxx>\n#include <xdictionary.hxx>\n\nnamespace com { namespace sun { namespace star { namespace i18n {\n\n\/\/ ----------------------------------------------------\n\/\/ class BreakIterator_th\n\/\/ ----------------------------------------------------\nclass BreakIterator_th : public BreakIterator_CTL\n{\npublic:\n BreakIterator_th();\n ~BreakIterator_th();\n\nprotected:\n void SAL_CALL makeIndex(const rtl::OUString& text, sal_Int32 pos) throw(com::sun::star::uno::RuntimeException);\n};\n\n} } } }\n\n#endif \/\/ _I18N_BREAKITERATOR_TH_HXX_\n<commit_msg>INTEGRATION: CWS i18n13 (1.3.164); FILE MERGED 2004\/06\/08 21:08:43 khong 1.3.164.1: #i29548# Fix Thai word breakiterator problem<commit_after>\/*************************************************************************\n *\n * $RCSfile: breakiterator_th.hxx,v $\n *\n * $Revision: 1.4 $\n *\n * last change: $Author: kz $ $Date: 2004-07-30 14:36:54 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n#ifndef _I18N_BREAKITERATOR_TH_HXX_\n#define _I18N_BREAKITERATOR_TH_HXX_\n\n#include <breakiterator_ctl.hxx>\n\nnamespace com { namespace sun { namespace star { namespace i18n {\n\n\/\/ ----------------------------------------------------\n\/\/ class BreakIterator_th\n\/\/ ----------------------------------------------------\nclass BreakIterator_th : public BreakIterator_CTL\n{\npublic:\n BreakIterator_th();\n ~BreakIterator_th();\n\nprotected:\n void SAL_CALL makeIndex(const rtl::OUString& text, sal_Int32 pos) throw(com::sun::star::uno::RuntimeException);\n icu::BreakIterator* SAL_CALL loadICUWordBreakIterator(const rtl::OUString& Text, sal_Int32 nStartPos, const com::sun::star::lang::Locale& rLocale,\n sal_Int16 rWordType) throw( com::sun::star::uno::RuntimeException);\n};\n\n} } } }\n\n#endif \/\/ _I18N_BREAKITERATOR_TH_HXX_\n<|endoftext|>"} {"text":"<commit_before>#include \"Renderer.hpp\"\n\nstatic const char* defaultVertShader = AL_STRINGIFY\n(\n void main(void)\n {\n gl_TexCoord[0] = gl_MultiTexCoord0;\n gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex;\n }\n);\n\nstatic const char* yuvGammaFragShader = AL_STRINGIFY\n(\n uniform sampler2D yTexture;\n uniform sampler2D uTexture;\n uniform sampler2D vTexture;\n \n uniform float gamma_pow;\n uniform float gamma_min;\n uniform float gamma_max;\n \n void main(void)\n {\n float y = texture2D(yTexture, gl_TexCoord[0].st).r;\n float u = texture2D(uTexture, gl_TexCoord[0].st).r;\n float v = texture2D(vTexture, gl_TexCoord[0].st).r;\n \n \/\/ YUV -> RGB\n vec4 color;\n color.r = 1.164 * (y - 16.0\/255.0) + 2.018 * (v - 128.0\/255.0);\n color.g = 1.164 * (y - 16.0\/255.0) - 0.813 * (u - 128.0\/255.0) - 0.391 * (v - 128.0\/255.0);\n color.b = 1.164 * (y - 16.0\/255.0) + 1.596 * (u - 128.0\/255.0);\n \n \/\/ Gamma\n color.r = pow(clamp(color.r, gamma_min, gamma_max), gamma_pow);\n color.g = pow(clamp(color.g, gamma_min, gamma_max), gamma_pow);\n color.b = pow(clamp(color.b, gamma_min, gamma_max), gamma_pow);\n gl_FragColor = color;\n }\n);\n\nRenderer::Renderer()\n :\n al::OmniApp(\"AlloPlayer\", false, 2048), gammaMin(0.0f), gammaMax(1.0f), gammaPow(1.0f),\n forRotation(0, 0, 0), forAngle(M_PI*2.0), rotation(0, 0, 0), rotationSpeed(0.01)\n{\n nav().smooth(0.8);\n \n for (int i = 0; i < 1; i++)\n {\n cubemapPool.push(nullptr);\n }\n \n for (int i = 0; i < StereoCubemap::MAX_EYES_COUNT * Cubemap::MAX_FACES_COUNT; i++)\n {\n textures.push_back(YUV420PTexture());\n }\n}\n\nRenderer::~Renderer()\n{\n}\n\nbool Renderer::onCreate()\n{\n std::cout << \"OpenGL version: \" << glGetString(GL_VERSION) << \", GLSL version \" << glGetString(GL_SHADING_LANGUAGE_VERSION) << std::endl;\n \n \n al::Shader vert, frag;\n vert.source(defaultVertShader, al::Shader::VERTEX).compile();\n vert.printLog();\n frag.source(yuvGammaFragShader, al::Shader::FRAGMENT).compile();\n frag.printLog();\n yuvGammaShader.attach(vert).attach(frag).link();\n yuvGammaShader.printLog();\n \n return OmniApp::onCreate();\n}\n\nbool Renderer::onFrame()\n{\n now = al::MainLoop::now();\n \n StereoCubemap* cubemap;\n if (cubemapBuffer.try_pop(cubemap))\n {\n for (int j = 0; j < cubemap->getEyesCount(); j++)\n {\n Cubemap* eye = cubemap->getEye(j);\n for (int i = 0; i < eye->getFacesCount(); i++)\n {\n CubemapFace* face = eye->getFace(i);\n \n \/\/ Reorder faces so that they are displayed correctly in the AlloSphere\n int texI;\n if (i == 0)\n {\n texI = 1;\n }\n else if (i == 1)\n {\n texI = 0;\n }\n else if (i == 2)\n {\n texI = 4;\n }\n else if (i == 3)\n {\n texI = 5;\n }\n else if (i == 4)\n {\n texI = 2;\n }\n else if (i == 5)\n {\n texI = 3;\n }\n else\n {\n texI = i;\n }\n YUV420PTexture& tex = textures[texI + j * Cubemap::MAX_FACES_COUNT];\n \n if (face)\n {\n \/\/ create texture if not already created\n if (!tex.yTexture)\n {\n tex.yTexture = new al::Texture(face->getContent()->getWidth(),\n face->getContent()->getHeight(),\n al::Graphics::LUMINANCE,\n al::Graphics::UBYTE);\n tex.uTexture = new al::Texture(face->getContent()->getWidth()\/2,\n face->getContent()->getHeight()\/2,\n al::Graphics::LUMINANCE,\n al::Graphics::UBYTE);\n tex.vTexture = new al::Texture(face->getContent()->getWidth()\/2,\n face->getContent()->getHeight()\/2,\n al::Graphics::LUMINANCE,\n al::Graphics::UBYTE);\n textures[texI + j * Cubemap::MAX_FACES_COUNT] = tex;\n \n \/\/ In case a face is mono use the same the texture for left and right.\n \/\/ By doing so, image will become twice as bright in the AlloSphere.\n if (j == 0 && cubemap->getEyesCount() > 1 && cubemap->getEye(1)->getFacesCount() <= i)\n {\n textures[texI + Cubemap::MAX_FACES_COUNT] = tex;\n }\n }\n \n tex.yTexture->bind();\n glTexSubImage2D(tex.yTexture->target(), 0,\n 0, 0,\n tex.yTexture->width(),\n tex.yTexture->height(),\n tex.yTexture->format(),\n tex.yTexture->type(),\n face->getContent()->getPixels());\n tex.vTexture->bind();\n glTexSubImage2D(tex.vTexture->target(), 0,\n 0, 0,\n tex.vTexture->width(),\n tex.vTexture->height(),\n tex.vTexture->format(),\n tex.vTexture->type(),\n (char*)face->getContent()->getPixels() +\n face->getContent()->getWidth() * face->getContent()->getHeight());\n tex.uTexture->bind();\n glTexSubImage2D(tex.uTexture->target(), 0,\n 0, 0,\n tex.uTexture->width(),\n tex.uTexture->height(),\n tex.uTexture->format(),\n tex.uTexture->type(),\n (char*)face->getContent()->getPixels() +\n face->getContent()->getWidth() * face->getContent()->getHeight() +\n (face->getContent()->getWidth()\/2) * (face->getContent()->getHeight()\/2));\n tex.uTexture->unbind();\n \n if (onDisplayedCubemapFace) onDisplayedCubemapFace(this, i + j * Cubemap::MAX_FACES_COUNT);\n }\n }\n }\n \n cubemapPool.push(cubemap);\n }\n \n \/\/ Set uniforms\n {\n boost::mutex::scoped_lock(uniformsMutex);\n yuvGammaShader.begin();\n yuvGammaShader.uniform(\"gamma_min\", gammaMin);\n yuvGammaShader.uniform(\"gamma_max\", gammaMax);\n yuvGammaShader.uniform(\"gamma_pow\", gammaPow);\n yuvGammaShader.end();\n mOmni.forRotation(forRotation);\n mOmni.forAngle(forAngle);\n mOmni.rotation(rotation);\n }\n \n bool result = OmniApp::onFrame();\n \n if (onDisplayedFrame) onDisplayedFrame(this);\n return result;\n}\n\nStereoCubemap* Renderer::onNextCubemap(CubemapSource* source, StereoCubemap* cubemap)\n{\n StereoCubemap* oldCubemap;\n if (!cubemapPool.try_pop(oldCubemap))\n {\n if (cubemapPool.closed())\n {\n abort();\n }\n else\n {\n return cubemap;\n }\n }\n \n cubemapBuffer.push(cubemap);\n return oldCubemap;\n}\n\nvoid Renderer::onDraw(al::Graphics& gl)\n{\n int faceIndex = mOmni.face();\n int eyeIndex = (mOmni.eye() <= 0.0f) ? 0 : 1;\n YUV420PTexture& tex = textures[faceIndex + eyeIndex * Cubemap::MAX_FACES_COUNT];\n \n \/\/ render cubemap\n if (tex.yTexture)\n {\n \/\/ Configure gamma to make backdrop more visible in the AlloSphere\n yuvGammaShader.begin();\n \n \/\/ Borrow a temporary Mesh from Graphics\n al::Mesh& m = gl.mesh();\n \n m.reset();\n \n \/\/ Generate geometry\n m.primitive(al::Graphics::TRIANGLE_STRIP);\n m.vertex(-1, 1);\n m.vertex(-1, -1);\n m.vertex( 1, 1);\n m.vertex( 1, -1);\n \n \/\/ Add texture coordinates and flip cubemap\n m.texCoord(1,1);\n m.texCoord(1,0);\n m.texCoord(0,1);\n m.texCoord(0,0);\n \n \/\/ We must tell the GPU to use the texture when rendering primitives\n tex.yTexture->bind(0);\n tex.vTexture->bind(1);\n tex.uTexture->bind(2);\n \n yuvGammaShader.uniform(\"yTexture\", 0);\n yuvGammaShader.uniform(\"uTexture\", 1);\n yuvGammaShader.uniform(\"vTexture\", 2);\n \n gl.draw(m);\n \n tex.yTexture->unbind(0);\n tex.vTexture->unbind(1);\n tex.uTexture->unbind(2);\n \n yuvGammaShader.end();\n }\n}\n\nvoid Renderer::onMessage(al::osc::Message& m)\n{\n OmniApp::onMessage(m);\n \n m.resetStream();\n if (m.addressPattern() == \"\/ty\")\n {\n float x;\n m >> x;\n setRotation(al::Vec3f(0, rotation[1]-x\/rotationSpeed, 0));\n }\n}\n\nbool Renderer::onKeyDown(const al::Keyboard& k)\n{\n return true;\n}\n\nvoid Renderer::setOnDisplayedFrame(const std::function<void (Renderer*)>& callback)\n{\n onDisplayedFrame = callback;\n}\n\nvoid Renderer::setOnDisplayedCubemapFace(const std::function<void (Renderer*, int)>& callback)\n{\n onDisplayedCubemapFace = callback;\n}\n\nvoid Renderer::setGammaMin(float gammaMin)\n{\n boost::mutex::scoped_lock(uniformsMutex);\n this->gammaMin = gammaMin;\n}\n\nvoid Renderer::setGammaMax(float gammaMax)\n{\n boost::mutex::scoped_lock(uniformsMutex);\n this->gammaMax = gammaMax;\n}\n\nvoid Renderer::setGammaPow(float gammaPow)\n{\n boost::mutex::scoped_lock(uniformsMutex);\n this->gammaPow = gammaPow;\n}\n\nvoid Renderer::setFORRotation(const al::Vec3f& forRotation)\n{\n boost::mutex::scoped_lock(uniformsMutex);\n this->forRotation = forRotation;\n}\n\nvoid Renderer::setFORAngle(float forAngle)\n{\n boost::mutex::scoped_lock(uniformsMutex);\n this->forAngle = forAngle;\n}\n\nvoid Renderer::setRotation(const al::Vec3f& rotation)\n{\n boost::mutex::scoped_lock(uniformsMutex);\n this->rotation = rotation;\n}\n\nvoid Renderer::setRotationSpeed(float speed)\n{\n boost::mutex::scoped_lock(uniformsMutex);\n this->rotationSpeed = speed;\n}\n\nvoid Renderer::setCubemapSource(CubemapSource* cubemapSource)\n{\n cubemapSource->setOnNextCubemap(boost::bind(&Renderer::onNextCubemap,\n this,\n _1,\n _2));\n}\n\nfloat Renderer::getGammaMin()\n{\n boost::mutex::scoped_lock(uniformsMutex);\n return gammaMin;\n}\n\nfloat Renderer::getGammaMax()\n{\n boost::mutex::scoped_lock(uniformsMutex);\n return gammaMax;\n}\n\nfloat Renderer::getGammaPow()\n{\n boost::mutex::scoped_lock(uniformsMutex);\n return gammaPow;\n}\n\nconst al::Vec3f& Renderer::getFORRotation()\n{\n boost::mutex::scoped_lock(uniformsMutex);\n return forRotation;\n}\n\nfloat Renderer::getFORAngle()\n{\n boost::mutex::scoped_lock(uniformsMutex);\n return forAngle;\n}\n\nconst al::Vec3f& Renderer::getRotation()\n{\n boost::mutex::scoped_lock(uniformsMutex);\n return rotation;\n}\n\nfloat Renderer::getRotationSpeed()\n{\n boost::mutex::scoped_lock(uniformsMutex);\n return rotationSpeed;\n}\n<commit_msg>Improved rotation speed.<commit_after>#include \"Renderer.hpp\"\n\nstatic const char* defaultVertShader = AL_STRINGIFY\n(\n void main(void)\n {\n gl_TexCoord[0] = gl_MultiTexCoord0;\n gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex;\n }\n);\n\nstatic const char* yuvGammaFragShader = AL_STRINGIFY\n(\n uniform sampler2D yTexture;\n uniform sampler2D uTexture;\n uniform sampler2D vTexture;\n \n uniform float gamma_pow;\n uniform float gamma_min;\n uniform float gamma_max;\n \n void main(void)\n {\n float y = texture2D(yTexture, gl_TexCoord[0].st).r;\n float u = texture2D(uTexture, gl_TexCoord[0].st).r;\n float v = texture2D(vTexture, gl_TexCoord[0].st).r;\n \n \/\/ YUV -> RGB\n vec4 color;\n color.r = 1.164 * (y - 16.0\/255.0) + 2.018 * (v - 128.0\/255.0);\n color.g = 1.164 * (y - 16.0\/255.0) - 0.813 * (u - 128.0\/255.0) - 0.391 * (v - 128.0\/255.0);\n color.b = 1.164 * (y - 16.0\/255.0) + 1.596 * (u - 128.0\/255.0);\n \n \/\/ Gamma\n color.r = pow(clamp(color.r, gamma_min, gamma_max), gamma_pow);\n color.g = pow(clamp(color.g, gamma_min, gamma_max), gamma_pow);\n color.b = pow(clamp(color.b, gamma_min, gamma_max), gamma_pow);\n gl_FragColor = color;\n }\n);\n\nRenderer::Renderer()\n :\n al::OmniApp(\"AlloPlayer\", false, 2048), gammaMin(0.0f), gammaMax(1.0f), gammaPow(1.0f),\n forRotation(0, 0, 0), forAngle(M_PI*2.0), rotation(0, 0, 0), rotationSpeed(0.5)\n{\n nav().smooth(0.8);\n \n for (int i = 0; i < 1; i++)\n {\n cubemapPool.push(nullptr);\n }\n \n for (int i = 0; i < StereoCubemap::MAX_EYES_COUNT * Cubemap::MAX_FACES_COUNT; i++)\n {\n textures.push_back(YUV420PTexture());\n }\n}\n\nRenderer::~Renderer()\n{\n}\n\nbool Renderer::onCreate()\n{\n std::cout << \"OpenGL version: \" << glGetString(GL_VERSION) << \", GLSL version \" << glGetString(GL_SHADING_LANGUAGE_VERSION) << std::endl;\n \n \n al::Shader vert, frag;\n vert.source(defaultVertShader, al::Shader::VERTEX).compile();\n vert.printLog();\n frag.source(yuvGammaFragShader, al::Shader::FRAGMENT).compile();\n frag.printLog();\n yuvGammaShader.attach(vert).attach(frag).link();\n yuvGammaShader.printLog();\n \n return OmniApp::onCreate();\n}\n\nbool Renderer::onFrame()\n{\n now = al::MainLoop::now();\n \n StereoCubemap* cubemap;\n if (cubemapBuffer.try_pop(cubemap))\n {\n for (int j = 0; j < cubemap->getEyesCount(); j++)\n {\n Cubemap* eye = cubemap->getEye(j);\n for (int i = 0; i < eye->getFacesCount(); i++)\n {\n CubemapFace* face = eye->getFace(i);\n \n \/\/ Reorder faces so that they are displayed correctly in the AlloSphere\n int texI;\n if (i == 0)\n {\n texI = 1;\n }\n else if (i == 1)\n {\n texI = 0;\n }\n else if (i == 2)\n {\n texI = 4;\n }\n else if (i == 3)\n {\n texI = 5;\n }\n else if (i == 4)\n {\n texI = 2;\n }\n else if (i == 5)\n {\n texI = 3;\n }\n else\n {\n texI = i;\n }\n YUV420PTexture& tex = textures[texI + j * Cubemap::MAX_FACES_COUNT];\n \n if (face)\n {\n \/\/ create texture if not already created\n if (!tex.yTexture)\n {\n tex.yTexture = new al::Texture(face->getContent()->getWidth(),\n face->getContent()->getHeight(),\n al::Graphics::LUMINANCE,\n al::Graphics::UBYTE);\n tex.uTexture = new al::Texture(face->getContent()->getWidth()\/2,\n face->getContent()->getHeight()\/2,\n al::Graphics::LUMINANCE,\n al::Graphics::UBYTE);\n tex.vTexture = new al::Texture(face->getContent()->getWidth()\/2,\n face->getContent()->getHeight()\/2,\n al::Graphics::LUMINANCE,\n al::Graphics::UBYTE);\n textures[texI + j * Cubemap::MAX_FACES_COUNT] = tex;\n \n \/\/ In case a face is mono use the same the texture for left and right.\n \/\/ By doing so, image will become twice as bright in the AlloSphere.\n if (j == 0 && cubemap->getEyesCount() > 1 && cubemap->getEye(1)->getFacesCount() <= i)\n {\n textures[texI + Cubemap::MAX_FACES_COUNT] = tex;\n }\n }\n \n tex.yTexture->bind();\n glTexSubImage2D(tex.yTexture->target(), 0,\n 0, 0,\n tex.yTexture->width(),\n tex.yTexture->height(),\n tex.yTexture->format(),\n tex.yTexture->type(),\n face->getContent()->getPixels());\n tex.vTexture->bind();\n glTexSubImage2D(tex.vTexture->target(), 0,\n 0, 0,\n tex.vTexture->width(),\n tex.vTexture->height(),\n tex.vTexture->format(),\n tex.vTexture->type(),\n (char*)face->getContent()->getPixels() +\n face->getContent()->getWidth() * face->getContent()->getHeight());\n tex.uTexture->bind();\n glTexSubImage2D(tex.uTexture->target(), 0,\n 0, 0,\n tex.uTexture->width(),\n tex.uTexture->height(),\n tex.uTexture->format(),\n tex.uTexture->type(),\n (char*)face->getContent()->getPixels() +\n face->getContent()->getWidth() * face->getContent()->getHeight() +\n (face->getContent()->getWidth()\/2) * (face->getContent()->getHeight()\/2));\n tex.uTexture->unbind();\n \n if (onDisplayedCubemapFace) onDisplayedCubemapFace(this, i + j * Cubemap::MAX_FACES_COUNT);\n }\n }\n }\n \n cubemapPool.push(cubemap);\n }\n \n \/\/ Set uniforms\n {\n boost::mutex::scoped_lock(uniformsMutex);\n yuvGammaShader.begin();\n yuvGammaShader.uniform(\"gamma_min\", gammaMin);\n yuvGammaShader.uniform(\"gamma_max\", gammaMax);\n yuvGammaShader.uniform(\"gamma_pow\", gammaPow);\n yuvGammaShader.end();\n mOmni.forRotation(forRotation);\n mOmni.forAngle(forAngle);\n mOmni.rotation(rotation);\n }\n \n bool result = OmniApp::onFrame();\n \n if (onDisplayedFrame) onDisplayedFrame(this);\n return result;\n}\n\nStereoCubemap* Renderer::onNextCubemap(CubemapSource* source, StereoCubemap* cubemap)\n{\n StereoCubemap* oldCubemap;\n if (!cubemapPool.try_pop(oldCubemap))\n {\n if (cubemapPool.closed())\n {\n abort();\n }\n else\n {\n return cubemap;\n }\n }\n \n cubemapBuffer.push(cubemap);\n return oldCubemap;\n}\n\nvoid Renderer::onDraw(al::Graphics& gl)\n{\n int faceIndex = mOmni.face();\n int eyeIndex = (mOmni.eye() <= 0.0f) ? 0 : 1;\n YUV420PTexture& tex = textures[faceIndex + eyeIndex * Cubemap::MAX_FACES_COUNT];\n \n \/\/ render cubemap\n if (tex.yTexture)\n {\n \/\/ Configure gamma to make backdrop more visible in the AlloSphere\n yuvGammaShader.begin();\n \n \/\/ Borrow a temporary Mesh from Graphics\n al::Mesh& m = gl.mesh();\n \n m.reset();\n \n \/\/ Generate geometry\n m.primitive(al::Graphics::TRIANGLE_STRIP);\n m.vertex(-1, 1);\n m.vertex(-1, -1);\n m.vertex( 1, 1);\n m.vertex( 1, -1);\n \n \/\/ Add texture coordinates and flip cubemap\n m.texCoord(1,1);\n m.texCoord(1,0);\n m.texCoord(0,1);\n m.texCoord(0,0);\n \n \/\/ We must tell the GPU to use the texture when rendering primitives\n tex.yTexture->bind(0);\n tex.vTexture->bind(1);\n tex.uTexture->bind(2);\n \n yuvGammaShader.uniform(\"yTexture\", 0);\n yuvGammaShader.uniform(\"uTexture\", 1);\n yuvGammaShader.uniform(\"vTexture\", 2);\n \n gl.draw(m);\n \n tex.yTexture->unbind(0);\n tex.vTexture->unbind(1);\n tex.uTexture->unbind(2);\n \n yuvGammaShader.end();\n }\n}\n\nvoid Renderer::onMessage(al::osc::Message& m)\n{\n OmniApp::onMessage(m);\n \n m.resetStream();\n if (m.addressPattern() == \"\/ty\")\n {\n float x;\n m >> x;\n setRotation(al::Vec3f(0, rotation[1]-x*rotationSpeed*0.01, 0));\n }\n}\n\nbool Renderer::onKeyDown(const al::Keyboard& k)\n{\n return true;\n}\n\nvoid Renderer::setOnDisplayedFrame(const std::function<void (Renderer*)>& callback)\n{\n onDisplayedFrame = callback;\n}\n\nvoid Renderer::setOnDisplayedCubemapFace(const std::function<void (Renderer*, int)>& callback)\n{\n onDisplayedCubemapFace = callback;\n}\n\nvoid Renderer::setGammaMin(float gammaMin)\n{\n boost::mutex::scoped_lock(uniformsMutex);\n this->gammaMin = gammaMin;\n}\n\nvoid Renderer::setGammaMax(float gammaMax)\n{\n boost::mutex::scoped_lock(uniformsMutex);\n this->gammaMax = gammaMax;\n}\n\nvoid Renderer::setGammaPow(float gammaPow)\n{\n boost::mutex::scoped_lock(uniformsMutex);\n this->gammaPow = gammaPow;\n}\n\nvoid Renderer::setFORRotation(const al::Vec3f& forRotation)\n{\n boost::mutex::scoped_lock(uniformsMutex);\n this->forRotation = forRotation;\n}\n\nvoid Renderer::setFORAngle(float forAngle)\n{\n boost::mutex::scoped_lock(uniformsMutex);\n this->forAngle = forAngle;\n}\n\nvoid Renderer::setRotation(const al::Vec3f& rotation)\n{\n boost::mutex::scoped_lock(uniformsMutex);\n this->rotation = rotation;\n}\n\nvoid Renderer::setRotationSpeed(float speed)\n{\n boost::mutex::scoped_lock(uniformsMutex);\n this->rotationSpeed = speed;\n}\n\nvoid Renderer::setCubemapSource(CubemapSource* cubemapSource)\n{\n cubemapSource->setOnNextCubemap(boost::bind(&Renderer::onNextCubemap,\n this,\n _1,\n _2));\n}\n\nfloat Renderer::getGammaMin()\n{\n boost::mutex::scoped_lock(uniformsMutex);\n return gammaMin;\n}\n\nfloat Renderer::getGammaMax()\n{\n boost::mutex::scoped_lock(uniformsMutex);\n return gammaMax;\n}\n\nfloat Renderer::getGammaPow()\n{\n boost::mutex::scoped_lock(uniformsMutex);\n return gammaPow;\n}\n\nconst al::Vec3f& Renderer::getFORRotation()\n{\n boost::mutex::scoped_lock(uniformsMutex);\n return forRotation;\n}\n\nfloat Renderer::getFORAngle()\n{\n boost::mutex::scoped_lock(uniformsMutex);\n return forAngle;\n}\n\nconst al::Vec3f& Renderer::getRotation()\n{\n boost::mutex::scoped_lock(uniformsMutex);\n return rotation;\n}\n\nfloat Renderer::getRotationSpeed()\n{\n boost::mutex::scoped_lock(uniformsMutex);\n return rotationSpeed;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: collator_unicode.hxx,v $\n *\n * $Revision: 1.11 $\n *\n * last change: $Author: kz $ $Date: 2006-12-12 16:12:21 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n#ifndef _I18N_COLLATOR_UNICODE_HXX_\n#define _I18N_COLLATOR_UNICODE_HXX_\n\n#include <com\/sun\/star\/uno\/Reference.h>\n#include <com\/sun\/star\/i18n\/XCollator.hpp>\n#include <cppuhelper\/implbase1.hxx>\n#include <osl\/module.h>\n\n#include \"warnings_guard_unicode_tblcoll.h\"\n\n\/\/ ----------------------------------------------------\n\/\/ class Collator_Unicode\n\/\/ ----------------------------------------------------\n\nnamespace com { namespace sun { namespace star { namespace i18n {\n\nclass Collator_Unicode : public cppu::WeakImplHelper1 < XCollator >\n{\npublic:\n \/\/ Constructors\n Collator_Unicode();\n \/\/ Destructor\n ~Collator_Unicode();\n\n sal_Int32 SAL_CALL compareSubstring( const rtl::OUString& s1, sal_Int32 off1, sal_Int32 len1,\n const rtl::OUString& s2, sal_Int32 off2, sal_Int32 len2) throw(com::sun::star::uno::RuntimeException);\n\n sal_Int32 SAL_CALL compareString( const rtl::OUString& s1, const rtl::OUString& s2)\n throw(com::sun::star::uno::RuntimeException);\n\n sal_Int32 SAL_CALL loadCollatorAlgorithm( const rtl::OUString& impl, const lang::Locale& rLocale,\n sal_Int32 collatorOptions) throw(com::sun::star::uno::RuntimeException);\n\n\n \/\/ following 4 methods are implemented in collatorImpl.\n sal_Int32 SAL_CALL loadDefaultCollator( const lang::Locale&, sal_Int32)\n throw(com::sun::star::uno::RuntimeException) {throw com::sun::star::uno::RuntimeException();}\n void SAL_CALL loadCollatorAlgorithmWithEndUserOption( const rtl::OUString&, const lang::Locale&,\n const com::sun::star::uno::Sequence< sal_Int32 >&) throw(com::sun::star::uno::RuntimeException) {throw com::sun::star::uno::RuntimeException();}\n com::sun::star::uno::Sequence< rtl::OUString > SAL_CALL listCollatorAlgorithms( const lang::Locale&)\n throw(com::sun::star::uno::RuntimeException) {throw com::sun::star::uno::RuntimeException();}\n com::sun::star::uno::Sequence< sal_Int32 > SAL_CALL listCollatorOptions( const rtl::OUString& )\n throw(com::sun::star::uno::RuntimeException) {throw com::sun::star::uno::RuntimeException();}\n\n \/\/XServiceInfo\n virtual rtl::OUString SAL_CALL getImplementationName() throw( com::sun::star::uno::RuntimeException );\n virtual sal_Bool SAL_CALL supportsService(const rtl::OUString& ServiceName) throw( com::sun::star::uno::RuntimeException );\n virtual com::sun::star::uno::Sequence< rtl::OUString > SAL_CALL getSupportedServiceNames() throw( com::sun::star::uno::RuntimeException );\n\nprotected:\n const sal_Char *implementationName;\nprivate:\n RuleBasedCollator *collator;\n oslModule hModule;\n};\n\n} } } }\n\n#endif\n<commit_msg>INTEGRATION: CWS i18n39 (1.11.78); FILE MERGED 2008\/01\/11 07:39:15 khong 1.11.78.1: i78055 provide UCA as base for ICU collator constructor from image rule<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: collator_unicode.hxx,v $\n *\n * $Revision: 1.12 $\n *\n * last change: $Author: vg $ $Date: 2008-01-28 15:33:02 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n#ifndef _I18N_COLLATOR_UNICODE_HXX_\n#define _I18N_COLLATOR_UNICODE_HXX_\n\n#include <com\/sun\/star\/uno\/Reference.h>\n#include <com\/sun\/star\/i18n\/XCollator.hpp>\n#include <cppuhelper\/implbase1.hxx>\n#include <osl\/module.h>\n\n#include \"warnings_guard_unicode_tblcoll.h\"\n\n\/\/ ----------------------------------------------------\n\/\/ class Collator_Unicode\n\/\/ ----------------------------------------------------\n\nnamespace com { namespace sun { namespace star { namespace i18n {\n\nclass Collator_Unicode : public cppu::WeakImplHelper1 < XCollator >\n{\npublic:\n \/\/ Constructors\n Collator_Unicode();\n \/\/ Destructor\n ~Collator_Unicode();\n\n sal_Int32 SAL_CALL compareSubstring( const rtl::OUString& s1, sal_Int32 off1, sal_Int32 len1,\n const rtl::OUString& s2, sal_Int32 off2, sal_Int32 len2) throw(com::sun::star::uno::RuntimeException);\n\n sal_Int32 SAL_CALL compareString( const rtl::OUString& s1, const rtl::OUString& s2)\n throw(com::sun::star::uno::RuntimeException);\n\n sal_Int32 SAL_CALL loadCollatorAlgorithm( const rtl::OUString& impl, const lang::Locale& rLocale,\n sal_Int32 collatorOptions) throw(com::sun::star::uno::RuntimeException);\n\n\n \/\/ following 4 methods are implemented in collatorImpl.\n sal_Int32 SAL_CALL loadDefaultCollator( const lang::Locale&, sal_Int32)\n throw(com::sun::star::uno::RuntimeException) {throw com::sun::star::uno::RuntimeException();}\n void SAL_CALL loadCollatorAlgorithmWithEndUserOption( const rtl::OUString&, const lang::Locale&,\n const com::sun::star::uno::Sequence< sal_Int32 >&) throw(com::sun::star::uno::RuntimeException) {throw com::sun::star::uno::RuntimeException();}\n com::sun::star::uno::Sequence< rtl::OUString > SAL_CALL listCollatorAlgorithms( const lang::Locale&)\n throw(com::sun::star::uno::RuntimeException) {throw com::sun::star::uno::RuntimeException();}\n com::sun::star::uno::Sequence< sal_Int32 > SAL_CALL listCollatorOptions( const rtl::OUString& )\n throw(com::sun::star::uno::RuntimeException) {throw com::sun::star::uno::RuntimeException();}\n\n \/\/XServiceInfo\n virtual rtl::OUString SAL_CALL getImplementationName() throw( com::sun::star::uno::RuntimeException );\n virtual sal_Bool SAL_CALL supportsService(const rtl::OUString& ServiceName) throw( com::sun::star::uno::RuntimeException );\n virtual com::sun::star::uno::Sequence< rtl::OUString > SAL_CALL getSupportedServiceNames() throw( com::sun::star::uno::RuntimeException );\n\nprotected:\n const sal_Char *implementationName;\nprivate:\n RuleBasedCollator *uca_base, *collator;\n oslModule hModule;\n};\n\n} } } }\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2013 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"android_webview\/native\/skia_java_output_stream.h\"\n\n#include \"base\/logging.h\"\n\n\/\/ Disable \"Warnings treated as errors\" for input_stream_jni as it's a Java\n\/\/ system class and we have to generate C++ hooks for all methods in the class\n\/\/ even if they're unused.\n#pragma GCC diagnostic push\n#pragma GCC diagnostic ignored \"-Wunused-function\"\n#include \"jni\/OutputStream_jni.h\"\n#include \"jni\/CancellationSignal_jni.h\"\n#pragma GCC diagnostic pop\nusing base::android::ClearException;\nusing base::android::JavaRef;\nusing JNI_OutputStream::Java_OutputStream_writeV_AB_I_I;\nusing JNI_OutputStream::Java_OutputStream_flush;\nusing JNI_CancellationSignal::Java_CancellationSignal_isCanceled;\n\nnamespace android_webview {\n\nconst size_t SkiaJavaOutputStream::kBufferSize = 4096;\n\nSkiaJavaOutputStream::SkiaJavaOutputStream(\n JNIEnv* env,\n const JavaRef<jobject>& stream,\n const JavaRef<jobject>& cancel_signal)\n : env_(env),\n stream_(stream),\n cancel_signal_(cancel_signal) {\n}\n\nSkiaJavaOutputStream::~SkiaJavaOutputStream() { }\n\n\/\/ TODO(sgurun) make sure shutdown while writing\/flush is handled properly\n\/\/ potentially via a cancel API in webview.\nbool SkiaJavaOutputStream::write(const void* buffer, size_t size) {\n if (!buffer_.obj()) {\n \/\/ Allocate transfer buffer.\n base::android::ScopedJavaLocalRef<jbyteArray> temp(\n env_, env_->NewByteArray(kBufferSize));\n buffer_.Reset(temp);\n if (ClearException(env_))\n return false;\n }\n const jbyte* bufptr = reinterpret_cast<const jbyte*>(buffer);\n while (size > 0) {\n if (cancel_signal_.obj() != NULL &&\n Java_CancellationSignal_isCanceled(env_, cancel_signal_.obj())) {\n return false;\n }\n size_t requested = size;\n if (requested > kBufferSize) {\n requested = kBufferSize;\n }\n\n env_->SetByteArrayRegion(buffer_.obj(), 0, requested, bufptr);\n if (ClearException(env_)) {\n LOG(WARNING) << \"write:SetByteArrayRegion threw an exception\";\n return false;\n }\n\n Java_OutputStream_writeV_AB_I_I(\n env_, stream_.obj(), buffer_.obj(), 0, requested);\n if (ClearException(env_)) {\n LOG(WARNING) << \"write:write threw an exception\";\n return false;\n }\n bufptr += requested;\n size -= requested;\n }\n\n return true;\n}\n\nvoid SkiaJavaOutputStream::flush() {\n Java_OutputStream_flush(env_, stream_.obj());\n if (ClearException(env_)) {\n LOG(WARNING) << \"flush threw an exception\";\n }\n}\n\n\nbool RegisterSkiaJavaOutputStream(JNIEnv* env) {\n return JNI_OutputStream::RegisterNativesImpl(env) &&\n JNI_CancellationSignal::RegisterNativesImpl(env);\n}\n\n} \/\/ namespace android_webview\n<commit_msg>Fix crash due to a null pointer.<commit_after>\/\/ Copyright 2013 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"android_webview\/native\/skia_java_output_stream.h\"\n\n#include \"base\/logging.h\"\n\n\/\/ Disable \"Warnings treated as errors\" for input_stream_jni as it's a Java\n\/\/ system class and we have to generate C++ hooks for all methods in the class\n\/\/ even if they're unused.\n#pragma GCC diagnostic push\n#pragma GCC diagnostic ignored \"-Wunused-function\"\n#include \"jni\/OutputStream_jni.h\"\n#include \"jni\/CancellationSignal_jni.h\"\n#pragma GCC diagnostic pop\nusing base::android::ClearException;\nusing base::android::JavaRef;\nusing JNI_OutputStream::Java_OutputStream_writeV_AB_I_I;\nusing JNI_OutputStream::Java_OutputStream_flush;\nusing JNI_CancellationSignal::Java_CancellationSignal_isCanceled;\n\nnamespace android_webview {\n\nconst size_t SkiaJavaOutputStream::kBufferSize = 4096;\n\nSkiaJavaOutputStream::SkiaJavaOutputStream(\n JNIEnv* env,\n const JavaRef<jobject>& stream,\n const JavaRef<jobject>& cancel_signal)\n : env_(env),\n stream_(stream),\n cancel_signal_(cancel_signal) {\n}\n\nSkiaJavaOutputStream::~SkiaJavaOutputStream() { }\n\nbool SkiaJavaOutputStream::write(const void* buffer, size_t size) {\n\n if (buffer == NULL) {\n LOG(WARNING) << \"write: buffer pointer is NULL\";\n return false;\n }\n\n if (!buffer_.obj()) {\n \/\/ Allocate transfer buffer.\n base::android::ScopedJavaLocalRef<jbyteArray> temp(\n env_, env_->NewByteArray(kBufferSize));\n buffer_.Reset(temp);\n if (ClearException(env_))\n return false;\n }\n const jbyte* bufptr = reinterpret_cast<const jbyte*>(buffer);\n while (size > 0) {\n if (cancel_signal_.obj() != NULL &&\n Java_CancellationSignal_isCanceled(env_, cancel_signal_.obj())) {\n return false;\n }\n size_t requested = size;\n if (requested > kBufferSize) {\n requested = kBufferSize;\n }\n\n env_->SetByteArrayRegion(buffer_.obj(), 0, requested, bufptr);\n if (ClearException(env_)) {\n LOG(WARNING) << \"write:SetByteArrayRegion threw an exception\";\n return false;\n }\n\n Java_OutputStream_writeV_AB_I_I(\n env_, stream_.obj(), buffer_.obj(), 0, requested);\n if (ClearException(env_)) {\n LOG(WARNING) << \"write:write threw an exception\";\n return false;\n }\n bufptr += requested;\n size -= requested;\n }\n\n return true;\n}\n\nvoid SkiaJavaOutputStream::flush() {\n Java_OutputStream_flush(env_, stream_.obj());\n if (ClearException(env_)) {\n LOG(WARNING) << \"flush threw an exception\";\n }\n}\n\n\nbool RegisterSkiaJavaOutputStream(JNIEnv* env) {\n return JNI_OutputStream::RegisterNativesImpl(env) &&\n JNI_CancellationSignal::RegisterNativesImpl(env);\n}\n\n} \/\/ namespace android_webview\n<|endoftext|>"} {"text":"<commit_before>#include <pcl\/point_cloud.h>\n#include <pcl_ros\/point_cloud.h>\n#include <ros\/publisher.h>\n#include <ros\/ros.h>\n#include <stdlib.h>\n#include <Eigen\/Core>\n#include <opencv2\/opencv.hpp>\n\nros::Publisher pointcloud_pub;\ncv::Mat published_map; \/\/ get to work\nEigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic> global_map;\ndouble resolution;\ndouble position [2] = {0, 0};\nint length;\nint width;\n\nvoid frame_callback(const pcl::PointCloud<pcl::PointXYZ>::ConstPtr &msg, const std::string &topic)\n{\n \/\/transform pointcloud into the occupancy grid, no filtering right now\n bool offMap = false;\n \/\/for(pcl::PointXYZRGB point : msg) \/\/ how to iterate through all points??\n \/\/cv::Mat frame(msg->points);\n pcl::PointCloud<pcl::PointXYZ>::const_iterator point;\n for (point = msg->points.begin(); point < msg->points.end(); point++)\n {\n \/\/assuming is meters from robot origin\n \/\/transform coordinates\n double x = point->x \/ resolution;\n double y = point->y \/ resolution;\n\n x += position[0];\n y += position[1];\n if(x > 0 && y > 0 && x < length && y < width)\n {\n global_map(x, y) = 1.0;\n } else if(!offMap){\n ROS_WARN_STREAM(\"Some points out of range, won't be put on map.\");\n offMap = true;\n }\n }\n\n\n pointcloud_pub.publish(published_map);\n}\n\nint main(int argc, char **argv)\n{\n\n ros::init(argc, argv, \"new_mapper\");\n ros::NodeHandle nh;\n\n std::string topics;\n std::list<ros::Subscriber> subs;\n\n ros::NodeHandle pNh(\"~\");\n\n double start_x;\n double start_y;\n\n pNh.getParam(\"topics\", topics);\n pNh.getParam(\"occupancy_grid_length\", length);\n pNh.getParam(\"occupancy_grid_width\", width);\n pNh.getParam(\"qoccupancy_grid_resolution\", resolution);\n pNh.getParam(\"start_X\", start_x);\n pNh.getParam(\"start_Y\", start_y);\n\n length = (int) (length \/ resolution);\n width = (int) (width \/ resolution);\n position[0] = start_x \/ resolution;\n position[1] = start_y \/ resolution;\n \/\/global_map = Eigen::Matrix<float, Dynamic, Dynamic>(length, width);\n\n published_map(length, width, 2.0, cv::Scalar(0,0,0)); \/\/ I cant instatiate this\n \/\/https:\/\/docs.opencv.org\/2.4\/doc\/tutorials\/core\/mat_the_basic_image_container\/mat_the_basic_image_container.html\n global_map(published_map.data()); \/\/ i can't instantiate this either\n \/\/https:\/\/stackoverflow.com\/questions\/14783329\/opencv-cvmat-and-eigenmatrix\n\n \/\/will need to change when subscribe to multiple topics\n std::list<std::string> tokens = {topics};\n for (std:: string t : tokens)\n {\n ROS_INFO_STREAM(\"Mapper subscribing to \" << t);\n subs.push_back(nh.subscribe<pcl::PointCloud<pcl::PointXYZ>>(t, 1,boost::bind(frame_callback, _1, t)));\n }\n pointcloud_pub = nh.advertise<pcl::PointCloud<pcl::PointXYZRGB>>(\"\/map\", 1);\n\n ros::spin();\n}\n<commit_msg>Not much is working, have a basic framework<commit_after>#include <pcl\/point_cloud.h>\n#include <pcl_ros\/point_cloud.h>\n#include <ros\/publisher.h>\n#include <ros\/ros.h>\n#include <stdlib.h>\n#include <Eigen\/Core>\n#include <opencv2\/opencv.hpp>\n\nros::Publisher pointcloud_pub;\ncv::Mat published_map; \/\/ get to work\nEigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic> global_map;\ntf::StampedTransform lidar_trans;\ntf::StampedTransform cam_trans;\n\n\ndouble resolution;\ndouble position [2] = {0, 0};\nint length;\nint width;\n\nvoid frame_callback(const pcl::PointCloud<pcl::PointXYZ>::ConstPtr &msg, const std::string &topic)\n{\n \/\/transform pointcloud into the occupancy grid, no filtering right now\n bool offMap = false;\n \/\/for(pcl::PointXYZRGB point : msg) \/\/ how to iterate through all points??\n \/\/cv::Mat frame(msg->points);\n pcl::PointCloud<pcl::PointXYZ>::const_iterator point;\n for (point = msg->points.begin(); point < msg->points.end(); point++)\n {\n \/\/assuming is meters from robot origin\n \/\/transform coordinates\n double x = point->x \/ resolution;\n double y = point->y \/ resolution;\n\n x += position[0];\n y += position[1];\n if(x > 0 && y > 0 && x < length && y < width)\n {\n global_map(x, y) = 1.0;\n } else if(!offMap){\n ROS_WARN_STREAM(\"Some points out of range, won't be put on map.\");\n offMap = true;\n }\n }\n\n\n pointcloud_pub.publish(published_map);\n}\n\nint main(int argc, char **argv)\n{\n\n ros::init(argc, argv, \"new_mapper\");\n ros::NodeHandle nh;\n\n std::string topics;\n std::list<ros::Subscriber> subs;\n\n ros::NodeHandle pNh(\"~\");\n\n tf_listener = new tf::TransformListener();\n\n\n double start_x;\n double start_y;\n\n pNh.getParam(\"topics\", topics);\n pNh.getParam(\"occupancy_grid_length\", length);\n pNh.getParam(\"occupancy_grid_width\", width);\n pNh.getParam(\"qoccupancy_grid_resolution\", resolution);\n pNh.getParam(\"start_X\", start_x);\n pNh.getParam(\"start_Y\", start_y);\n\n length = (int) (length \/ resolution);\n width = (int) (width \/ resolution);\n position[0] = start_x \/ resolution;\n position[1] = start_y \/ resolution;\n \/\/global_map = Eigen::Matrix<float, Dynamic, Dynamic>(length, width);\n\n published_map(length, width, CV_32FC1, const cv::Scalar(0,0,0)); \/\/ I cant instatiate this\n \/\/https:\/\/docs.opencv.org\/2.4\/doc\/tutorials\/core\/mat_the_basic_image_container\/mat_the_basic_image_container.html\n global_map(published_map.data()); \/\/ I can't instantiate this either\n \/\/https:\/\/stackoverflow.com\/questions\/14783329\/opencv-cvmat-and-eigenmatrix\n\n \/\/will need to change when subscribe to multiple topics\n std::list<std::string> tokens = {topics};\n for (std:: string t : tokens)\n {\n ROS_INFO_STREAM(\"Mapper subscribing to \" << t);\n subs.push_back(nh.subscribe<pcl::PointCloud<pcl::PointXYZ>>(t, 1,boost::bind(frame_callback, _1, t)));\n }\n pointcloud_pub = nh.advertise<pcl::PointCloud<pcl::PointXYZRGB>>(\"\/map\", 1);\n\n ros::spin();\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2003 Daniel Wallin and Arvid Norberg\n\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a\n\/\/ copy of this software and associated documentation files (the \"Software\"),\n\/\/ to deal in the Software without restriction, including without limitation\n\/\/ the rights to use, copy, modify, merge, publish, distribute, sublicense,\n\/\/ and\/or sell copies of the Software, and to permit persons to whom the\n\/\/ Software is furnished to do so, subject to the following conditions:\n\n\/\/ The above copyright notice and this permission notice shall be included\n\/\/ in all copies or substantial portions of the Software.\n\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF\n\/\/ ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED\n\/\/ TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n\/\/ PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT\n\/\/ SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR\n\/\/ ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN\n\/\/ ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE\n\/\/ OR OTHER DEALINGS IN THE SOFTWARE.\n\n#ifndef LUABIND_CALL_FUNCTION_HPP_INCLUDED\n#define LUABIND_CALL_FUNCTION_HPP_INCLUDED\n\n#include <luabind\/config.hpp>\n\n#include <luabind\/error.hpp>\n#include <luabind\/detail\/convert_to_lua.hpp>\n#include <luabind\/detail\/pcall.hpp>\n#include <luabind\/detail\/call_shared.hpp>\n#include <luabind\/detail\/stack_utils.hpp>\n\nnamespace luabind\n{\n\tnamespace adl {\n\t\tclass object;\n\t}\n\n\tusing adl::object;\n\n\tnamespace detail {\n\n\t\ttemplate< typename PolicyList, unsigned int pos >\n void push_arguments(lua_State* \/*L*\/) {};\n\n\t\ttemplate< typename PolicyList, unsigned int Pos, typename Arg0, typename... Args >\n\t\tvoid push_arguments(lua_State* L, Arg0&& arg0, Args&&... args)\n\t\t{\n\t\t\tusing converter_type = specialized_converter_policy< fetched_converter_policy<Pos, PolicyList>, Arg0, cpp_to_lua >;\n\t\t\tconverter_type().to_lua(L, unwrapped<Arg0>::get(std::forward<Arg0>(arg0)));\n\t\t\tpush_arguments<PolicyList, Pos+1>(L, std::forward<Args>(args)...);\n\t\t}\n\n#ifndef LUABIND_NO_INTERNAL_TAG_ARGUMENTS\n\t\ttemplate<typename Ret, typename PolicyList, typename... Args, unsigned int... Indices, typename Fn>\n\t\tvoid call_function_impl(lua_State* L, int m_params, Fn fn, std::true_type \/* void *\/, meta::index_list<Indices...>, Args&&... args)\n\t\t{\n\t\t\tint top = lua_gettop(L);\n\n\t\t\tpush_arguments<PolicyList, 1>(L, std::forward<Args>(args)...);\n\n\t\t\tif (fn(L, sizeof...(Args), 0)) {\n\t\t\t\tassert(lua_gettop(L) == top - m_params + 1);\n\t\t\t\tcall_error(L);\n\t\t\t}\n\t\t\t\/\/ pops the return values from the function call\n\t\t\tstack_pop pop(L, lua_gettop(L) - top + m_params);\n\t\t}\n\n\t\ttemplate<typename Ret, typename PolicyList, typename... Args, unsigned int... Indices, typename Fn>\n\t\tRet call_function_impl(lua_State* L, int m_params, Fn fn, std::false_type \/* void *\/ , meta::index_list<Indices...>, Args&&... args)\n\t\t{\n\t\t\tint top = lua_gettop(L);\n\t\t\t\n\t\t\tpush_arguments<PolicyList, 1>(L, std::forward<Args>(args)...);\n\n\t\t\tif (fn(L, sizeof...(Args), 1)) {\n\t\t\t\tassert(lua_gettop(L) == top - m_params + 1);\n\t\t\t\tcall_error(L);\n\t\t\t}\n\t\t\t\/\/ pops the return values from the function call\n\t\t\tstack_pop pop(L, lua_gettop(L) - top + m_params);\n\n\t\t\tspecialized_converter_policy_n<0, PolicyList, Ret, lua_to_cpp> converter;\n\t\t\tif (converter.match(L, decorated_type<Ret>(), -1) < 0) {\n\t\t\t\tcast_error<Ret>(L);\n\t\t\t}\n\n\t\t\treturn converter.to_cpp(L, decorated_type<Ret>(), -1);\n\t\t}\n#else\n\t\ttemplate<typename Ret, typename PolicyList, typename IndexList, unsigned int NumParams, int(*Function)(lua_State*, int, int), bool IsVoid = std::is_void<Ret>::value>\n\t\tstruct call_function_struct;\n\n\t\ttemplate<typename Ret, typename PolicyList, unsigned int NumParams, int(*Function)(lua_State*, int, int), unsigned int... Indices >\n\t\tstruct call_function_struct< Ret, PolicyList, meta::index_list<Indices...>, NumParams, Function, true \/* void *\/ >\n\t\t{\n\t\t\ttemplate< typename... Args >\n\t\t\tstatic void call(lua_State* L, Args&&... args) {\n\t\t\t\tint top = lua_gettop(L);\n\t\t\t\t\n\t\t\t\tpush_arguments<PolicyList, 1>(L, std::forward<Args>(args)...);\n\n\t\t\t\tif(Function(L, sizeof...(Args), 0)) {\n\t\t\t\t\tassert(lua_gettop(L)==top-NumParams+1);\n\t\t\t\t\tcall_error(L);\n\t\t\t\t}\n\t\t\t\t\/\/ pops the return values from the function call\n\t\t\t\tstack_pop pop(L, lua_gettop(L)-top+NumParams);\n\t\t\t}\n\t\t};\n\n\t\ttemplate<typename Ret, typename PolicyList, unsigned int NumParams, int(*Function)(lua_State*, int, int), unsigned int... Indices >\n\t\tstruct call_function_struct< Ret, PolicyList, meta::index_list<Indices...>, NumParams, Function, false \/* void *\/ >\n\t\t{\n\t\t\ttemplate< typename... Args >\n\t\t\tstatic Ret call(lua_State* L, Args&&... args) {\n\t\t\t\tint top = lua_gettop(L);\n\t\t\t\t\n\t\t\t\tpush_arguments<PolicyList, 1>(L, std::forward<Args>(args)...);\n\n\t\t\t\tif(Function(L, sizeof...(Args), 1)) {\n\t\t\t\t\tassert(lua_gettop(L)==top-NumParams+1);\n\t\t\t\t\tcall_error(L);\n\t\t\t\t}\n\t\t\t\t\/\/ pops the return values from the function call\n\t\t\t\tstack_pop pop(L, lua_gettop(L)-top+NumParams);\n\n\t\t\t\tspecialized_converter_policy_n<0, PolicyList, Ret, lua_to_cpp> converter;\n\t\t\t\tif(converter.match(L, decorated_type<Ret>(), -1)<0) {\n\t\t\t\t\tcast_error<Ret>(L);\n\t\t\t\t}\n\n\t\t\t\treturn converter.to_cpp(L, decorated_type<Ret>(), -1);\n\t\t\t}\n\t\t};\n#endif\n\t}\n\n\ttemplate<class R, typename PolicyList = no_policies, typename... Args>\n\tR call_pushed_function(lua_State* L, Args&&... args)\n\t{\n#ifndef LUABIND_NO_INTERNAL_TAG_ARGUMENTS\n\t\treturn detail::call_function_impl<R, PolicyList>(L, 1, &detail::pcall, std::is_void<R>(), meta::index_range<1, sizeof...(Args) +1>(), std::forward<Args>(args)...);\n#else\n\t\treturn detail::call_function_struct<R, PolicyList, meta::index_range<1, sizeof...(Args)+1>, 1, &detail::pcall >::call(L, std::forward<Args>(args)...);\n#endif\n\t}\n\n\ttemplate<class R, typename PolicyList = no_policies, typename... Args>\n\tR call_function(lua_State* L, const char* name, Args&&... args )\n\t{\n\t\tassert(name && \"luabind::call_function() expects a function name\");\n\t\tlua_getglobal(L, name);\n\t\treturn call_pushed_function<R, PolicyList>(L, std::forward<Args>(args)...);\n\t}\n\n\ttemplate<class R, typename PolicyList = no_policies, typename... Args>\n\tR resume_pushed_function(lua_State* L, Args&&... args)\n\t{\n#ifndef LUABIND_NO_INTERNAL_TAG_ARGUMENTS\n\t\treturn detail::call_function_impl<R, PolicyList>(L, 1, &detail::resume_impl, std::is_void<R>(), meta::index_range<1, sizeof...(Args) +1>(), std::forward<Args>(args)...);\n#else\n\t\treturn detail::call_function_struct<R, PolicyList, meta::index_range<1, sizeof...(Args)+1>, 1, &detail::resume_impl >::call(L, std::forward<Args>(args)...);\n#endif\n\t}\n\n\ttemplate<class R, typename PolicyList = no_policies, typename... Args>\n\tR resume_function(lua_State* L, const char* name, Args&&... args)\n\t{\n\t\tassert(name && \"luabind::resume_function() expects a function name\");\n\t\tlua_getglobal(L, name);\n\t\treturn resume_pushed_function<R, PolicyList>(L, std::forward<Args>(args)...);\n\t}\n\n\ttemplate<class R, typename PolicyList = no_policies, typename... Args>\n\tR resume(lua_State* L, Args&&... args)\n\t{\n#ifndef LUABIND_NO_INTERNAL_TAG_ARGUMENTS\n\t\treturn detail::call_function_impl<R, PolicyList>(L, 0, &detail::resume_impl, std::is_void<R>(), meta::index_range<1, sizeof...(Args) +1>(), std::forward<Args>(args)...);\n#else\n\t\treturn detail::call_function_struct<R, PolicyList, meta::index_range<1, sizeof...(Args)+1>, 0, &detail::resume_impl >::call(L, std::forward<Args>(args)...);\n#endif\n\t}\n\n}\n\n#endif \/\/ LUABIND_CALL_FUNCTION_HPP_INCLUDED\n\n<commit_msg>Fix signed\/unsigned mismatch warning.<commit_after>\/\/ Copyright (c) 2003 Daniel Wallin and Arvid Norberg\n\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a\n\/\/ copy of this software and associated documentation files (the \"Software\"),\n\/\/ to deal in the Software without restriction, including without limitation\n\/\/ the rights to use, copy, modify, merge, publish, distribute, sublicense,\n\/\/ and\/or sell copies of the Software, and to permit persons to whom the\n\/\/ Software is furnished to do so, subject to the following conditions:\n\n\/\/ The above copyright notice and this permission notice shall be included\n\/\/ in all copies or substantial portions of the Software.\n\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF\n\/\/ ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED\n\/\/ TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n\/\/ PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT\n\/\/ SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR\n\/\/ ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN\n\/\/ ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE\n\/\/ OR OTHER DEALINGS IN THE SOFTWARE.\n\n#ifndef LUABIND_CALL_FUNCTION_HPP_INCLUDED\n#define LUABIND_CALL_FUNCTION_HPP_INCLUDED\n\n#include <luabind\/config.hpp>\n\n#include <luabind\/error.hpp>\n#include <luabind\/detail\/convert_to_lua.hpp>\n#include <luabind\/detail\/pcall.hpp>\n#include <luabind\/detail\/call_shared.hpp>\n#include <luabind\/detail\/stack_utils.hpp>\n\nnamespace luabind\n{\n\tnamespace adl {\n\t\tclass object;\n\t}\n\n\tusing adl::object;\n\n\tnamespace detail {\n\n\t\ttemplate< typename PolicyList, unsigned int pos >\n void push_arguments(lua_State* \/*L*\/) {};\n\n\t\ttemplate< typename PolicyList, unsigned int Pos, typename Arg0, typename... Args >\n\t\tvoid push_arguments(lua_State* L, Arg0&& arg0, Args&&... args)\n\t\t{\n\t\t\tusing converter_type = specialized_converter_policy< fetched_converter_policy<Pos, PolicyList>, Arg0, cpp_to_lua >;\n\t\t\tconverter_type().to_lua(L, unwrapped<Arg0>::get(std::forward<Arg0>(arg0)));\n\t\t\tpush_arguments<PolicyList, Pos+1>(L, std::forward<Args>(args)...);\n\t\t}\n\n#ifndef LUABIND_NO_INTERNAL_TAG_ARGUMENTS\n\t\ttemplate<typename Ret, typename PolicyList, typename... Args, unsigned int... Indices, typename Fn>\n\t\tvoid call_function_impl(lua_State* L, int m_params, Fn fn, std::true_type \/* void *\/, meta::index_list<Indices...>, Args&&... args)\n\t\t{\n\t\t\tint top = lua_gettop(L);\n\n\t\t\tpush_arguments<PolicyList, 1>(L, std::forward<Args>(args)...);\n\n\t\t\tif (fn(L, sizeof...(Args), 0)) {\n\t\t\t\tassert(lua_gettop(L) == top - m_params + 1);\n\t\t\t\tcall_error(L);\n\t\t\t}\n\t\t\t\/\/ pops the return values from the function call\n\t\t\tstack_pop pop(L, lua_gettop(L) - top + m_params);\n\t\t}\n\n\t\ttemplate<typename Ret, typename PolicyList, typename... Args, unsigned int... Indices, typename Fn>\n\t\tRet call_function_impl(lua_State* L, int m_params, Fn fn, std::false_type \/* void *\/ , meta::index_list<Indices...>, Args&&... args)\n\t\t{\n\t\t\tint top = lua_gettop(L);\n\t\t\t\n\t\t\tpush_arguments<PolicyList, 1>(L, std::forward<Args>(args)...);\n\n\t\t\tif (fn(L, sizeof...(Args), 1)) {\n\t\t\t\tassert(lua_gettop(L) == top - m_params + 1);\n\t\t\t\tcall_error(L);\n\t\t\t}\n\t\t\t\/\/ pops the return values from the function call\n\t\t\tstack_pop pop(L, lua_gettop(L) - top + m_params);\n\n\t\t\tspecialized_converter_policy_n<0, PolicyList, Ret, lua_to_cpp> converter;\n\t\t\tif (converter.match(L, decorated_type<Ret>(), -1) < 0) {\n\t\t\t\tcast_error<Ret>(L);\n\t\t\t}\n\n\t\t\treturn converter.to_cpp(L, decorated_type<Ret>(), -1);\n\t\t}\n#else\n\t\ttemplate<typename Ret, typename PolicyList, typename IndexList, unsigned int NumParams, int(*Function)(lua_State*, int, int), bool IsVoid = std::is_void<Ret>::value>\n\t\tstruct call_function_struct;\n\n\t\ttemplate<typename Ret, typename PolicyList, unsigned int NumParams, int(*Function)(lua_State*, int, int), unsigned int... Indices >\n\t\tstruct call_function_struct< Ret, PolicyList, meta::index_list<Indices...>, NumParams, Function, true \/* void *\/ >\n\t\t{\n\t\t\ttemplate< typename... Args >\n\t\t\tstatic void call(lua_State* L, Args&&... args) {\n\t\t\t\tint top = lua_gettop(L);\n\t\t\t\t\n\t\t\t\tpush_arguments<PolicyList, 1>(L, std::forward<Args>(args)...);\n\n\t\t\t\tif(Function(L, sizeof...(Args), 0)) {\n\t\t\t\t\tassert(lua_gettop(L)==int(top-NumParams+1));\n\t\t\t\t\tcall_error(L);\n\t\t\t\t}\n\t\t\t\t\/\/ pops the return values from the function call\n\t\t\t\tstack_pop pop(L, lua_gettop(L)-top+NumParams);\n\t\t\t}\n\t\t};\n\n\t\ttemplate<typename Ret, typename PolicyList, unsigned int NumParams, int(*Function)(lua_State*, int, int), unsigned int... Indices >\n\t\tstruct call_function_struct< Ret, PolicyList, meta::index_list<Indices...>, NumParams, Function, false \/* void *\/ >\n\t\t{\n\t\t\ttemplate< typename... Args >\n\t\t\tstatic Ret call(lua_State* L, Args&&... args) {\n\t\t\t\tint top = lua_gettop(L);\n\t\t\t\t\n\t\t\t\tpush_arguments<PolicyList, 1>(L, std::forward<Args>(args)...);\n\n\t\t\t\tif(Function(L, sizeof...(Args), 1)) {\n\t\t\t\t\tassert(lua_gettop(L)==top-NumParams+1);\n\t\t\t\t\tcall_error(L);\n\t\t\t\t}\n\t\t\t\t\/\/ pops the return values from the function call\n\t\t\t\tstack_pop pop(L, lua_gettop(L)-top+NumParams);\n\n\t\t\t\tspecialized_converter_policy_n<0, PolicyList, Ret, lua_to_cpp> converter;\n\t\t\t\tif(converter.match(L, decorated_type<Ret>(), -1)<0) {\n\t\t\t\t\tcast_error<Ret>(L);\n\t\t\t\t}\n\n\t\t\t\treturn converter.to_cpp(L, decorated_type<Ret>(), -1);\n\t\t\t}\n\t\t};\n#endif\n\t}\n\n\ttemplate<class R, typename PolicyList = no_policies, typename... Args>\n\tR call_pushed_function(lua_State* L, Args&&... args)\n\t{\n#ifndef LUABIND_NO_INTERNAL_TAG_ARGUMENTS\n\t\treturn detail::call_function_impl<R, PolicyList>(L, 1, &detail::pcall, std::is_void<R>(), meta::index_range<1, sizeof...(Args) +1>(), std::forward<Args>(args)...);\n#else\n\t\treturn detail::call_function_struct<R, PolicyList, meta::index_range<1, sizeof...(Args)+1>, 1, &detail::pcall >::call(L, std::forward<Args>(args)...);\n#endif\n\t}\n\n\ttemplate<class R, typename PolicyList = no_policies, typename... Args>\n\tR call_function(lua_State* L, const char* name, Args&&... args )\n\t{\n\t\tassert(name && \"luabind::call_function() expects a function name\");\n\t\tlua_getglobal(L, name);\n\t\treturn call_pushed_function<R, PolicyList>(L, std::forward<Args>(args)...);\n\t}\n\n\ttemplate<class R, typename PolicyList = no_policies, typename... Args>\n\tR resume_pushed_function(lua_State* L, Args&&... args)\n\t{\n#ifndef LUABIND_NO_INTERNAL_TAG_ARGUMENTS\n\t\treturn detail::call_function_impl<R, PolicyList>(L, 1, &detail::resume_impl, std::is_void<R>(), meta::index_range<1, sizeof...(Args) +1>(), std::forward<Args>(args)...);\n#else\n\t\treturn detail::call_function_struct<R, PolicyList, meta::index_range<1, sizeof...(Args)+1>, 1, &detail::resume_impl >::call(L, std::forward<Args>(args)...);\n#endif\n\t}\n\n\ttemplate<class R, typename PolicyList = no_policies, typename... Args>\n\tR resume_function(lua_State* L, const char* name, Args&&... args)\n\t{\n\t\tassert(name && \"luabind::resume_function() expects a function name\");\n\t\tlua_getglobal(L, name);\n\t\treturn resume_pushed_function<R, PolicyList>(L, std::forward<Args>(args)...);\n\t}\n\n\ttemplate<class R, typename PolicyList = no_policies, typename... Args>\n\tR resume(lua_State* L, Args&&... args)\n\t{\n#ifndef LUABIND_NO_INTERNAL_TAG_ARGUMENTS\n\t\treturn detail::call_function_impl<R, PolicyList>(L, 0, &detail::resume_impl, std::is_void<R>(), meta::index_range<1, sizeof...(Args) +1>(), std::forward<Args>(args)...);\n#else\n\t\treturn detail::call_function_struct<R, PolicyList, meta::index_range<1, sizeof...(Args)+1>, 0, &detail::resume_impl >::call(L, std::forward<Args>(args)...);\n#endif\n\t}\n\n}\n\n#endif \/\/ LUABIND_CALL_FUNCTION_HPP_INCLUDED\n\n<|endoftext|>"} {"text":"<commit_before>\/\/===- Support\/FileUtilities.cpp - File System Utilities ------------------===\/\/\n\/\/ \n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file was developed by the LLVM research group and is distributed under\n\/\/ the University of Illinois Open Source License. See LICENSE.TXT for details.\n\/\/ \n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This file implements a family of utility functions which are useful for doing\n\/\/ various things with files.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/Support\/FileUtilities.h\"\n#include \"llvm\/Support\/DataTypes.h\"\n#include \"llvm\/Config\/unistd.h\"\n#include \"llvm\/Config\/fcntl.h\"\n#include \"llvm\/Config\/sys\/types.h\"\n#include \"llvm\/Config\/sys\/stat.h\"\n#include \"llvm\/Config\/sys\/mman.h\"\n#include \"llvm\/Config\/alloca.h\"\n#include <cerrno>\n#include <cstdio>\n#include <fstream>\n#include <iostream>\nusing namespace llvm;\n\n\/\/\/ CheckMagic - Returns true IFF the file named FN begins with Magic. FN must\n\/\/\/ name a readable file.\n\/\/\/\nbool llvm::CheckMagic(const std::string &FN, const std::string &Magic) {\n char *buf = (char*)alloca(1 + Magic.size());\n std::ifstream f(FN.c_str());\n f.read(buf, Magic.size());\n buf[Magic.size()] = '\\0';\n return Magic == buf;\n}\n\n\/\/\/ IsArchive - Returns true IFF the file named FN appears to be a \"ar\" library\n\/\/\/ archive. The file named FN must exist.\n\/\/\/\nbool llvm::IsArchive(const std::string &FN) {\n \/\/ Inspect the beginning of the file to see if it contains the \"ar\"\n \/\/ library archive format magic string.\n return CheckMagic(FN, \"!<arch>\\012\");\n}\n\n\/\/\/ IsBytecode - Returns true IFF the file named FN appears to be an LLVM\n\/\/\/ bytecode file. The file named FN must exist.\n\/\/\/\nbool llvm::IsBytecode(const std::string &FN) {\n \/\/ Inspect the beginning of the file to see if it contains the LLVM\n \/\/ bytecode format magic string.\n return CheckMagic (FN, \"llvm\");\n}\n\n\/\/\/ IsSharedObject - Returns trus IFF the file named FN appears to be a shared\n\/\/\/ object with an ELF header. The file named FN must exist.\n\/\/\/\nbool llvm::IsSharedObject(const std::string &FN) {\n \/\/ Inspect the beginning of the file to see if it contains the ELF shared\n \/\/ object magic string.\n static const char elfMagic[] = { 0x7f, 'E', 'L', 'F', '\\0' };\n return CheckMagic(FN, elfMagic);\n}\n\n\/\/\/ FileOpenable - Returns true IFF Filename names an existing regular\n\/\/\/ file which we can successfully open.\n\/\/\/\nbool llvm::FileOpenable(const std::string &Filename) {\n struct stat s;\n if (stat (Filename.c_str (), &s) == -1)\n return false; \/\/ Cannot stat file\n if (!S_ISREG (s.st_mode))\n return false; \/\/ File is not a regular file\n std::ifstream FileStream (Filename.c_str ());\n if (!FileStream)\n return false; \/\/ File is not openable\n return true;\n}\n\n\/\/\/ DiffFiles - Compare the two files specified, returning true if they are\n\/\/\/ different or if there is a file error. If you specify a string to fill in\n\/\/\/ for the error option, it will set the string to an error message if an error\n\/\/\/ occurs, allowing the caller to distinguish between a failed diff and a file\n\/\/\/ system error.\n\/\/\/\nbool llvm::DiffFiles(const std::string &FileA, const std::string &FileB,\n std::string *Error) {\n std::ifstream FileAStream(FileA.c_str());\n if (!FileAStream) {\n if (Error) *Error = \"Couldn't open file '\" + FileA + \"'\";\n return true;\n }\n\n std::ifstream FileBStream(FileB.c_str());\n if (!FileBStream) {\n if (Error) *Error = \"Couldn't open file '\" + FileB + \"'\";\n return true;\n }\n\n \/\/ Compare the two files...\n int C1, C2;\n do {\n C1 = FileAStream.get();\n C2 = FileBStream.get();\n if (C1 != C2) return true;\n } while (C1 != EOF);\n\n return false;\n}\n\n\n\/\/\/ CopyFile - Copy the specified source file to the specified destination,\n\/\/\/ overwriting destination if it exists. This returns true on failure.\n\/\/\/\nbool llvm::CopyFile(const std::string &Dest, const std::string &Src) {\n FDHandle InFD(open(Src.c_str(), O_RDONLY));\n if (InFD == -1) return true;\n\n FileRemover FR(Dest);\n\n FDHandle OutFD(open(Dest.c_str(), O_WRONLY|O_CREAT, 0666));\n if (OutFD == -1) return true;\n\n char Buffer[16*1024];\n while (ssize_t Amt = read(InFD, Buffer, 16*1024)) {\n if (Amt == -1) {\n if (errno != EINTR) return true; \/\/ Error reading the file.\n } else {\n char *BufPtr = Buffer;\n while (Amt) {\n ssize_t AmtWritten = write(OutFD, BufPtr, Amt);\n if (AmtWritten == -1) {\n if (errno != EINTR) return true; \/\/ Error writing the file.\n } else {\n Amt -= AmtWritten;\n BufPtr += AmtWritten;\n }\n }\n }\n }\n\n FR.releaseFile(); \/\/ Success!\n return false;\n}\n\n\n\/\/\/ MoveFileOverIfUpdated - If the file specified by New is different than Old,\n\/\/\/ or if Old does not exist, move the New file over the Old file. Otherwise,\n\/\/\/ remove the New file.\n\/\/\/\nvoid llvm::MoveFileOverIfUpdated(const std::string &New,\n const std::string &Old) {\n if (DiffFiles(New, Old)) {\n if (std::rename(New.c_str(), Old.c_str()))\n std::cerr << \"Error renaming '\" << New << \"' to '\" << Old << \"'!\\n\";\n } else {\n std::remove(New.c_str());\n } \n}\n\n\/\/\/ removeFile - Delete the specified file\n\/\/\/\nvoid llvm::removeFile(const std::string &Filename) {\n std::remove(Filename.c_str());\n}\n\n\/\/\/ getUniqueFilename - Return a filename with the specified prefix. If the\n\/\/\/ file does not exist yet, return it, otherwise add a suffix to make it\n\/\/\/ unique.\n\/\/\/\nstd::string llvm::getUniqueFilename(const std::string &FilenameBase) {\n if (!std::ifstream(FilenameBase.c_str()))\n return FilenameBase; \/\/ Couldn't open the file? Use it!\n\n \/\/ Create a pattern for mkstemp...\n char *FNBuffer = new char[FilenameBase.size()+8];\n strcpy(FNBuffer, FilenameBase.c_str());\n strcpy(FNBuffer+FilenameBase.size(), \"-XXXXXX\");\n\n \/\/ Agree on a temporary file name to use....\n#if defined(HAVE_MKSTEMP) && !defined(_MSC_VER)\n int TempFD;\n if ((TempFD = mkstemp(FNBuffer)) == -1) {\n \/\/ FIXME: this should return an emtpy string or something and allow the\n \/\/ caller to deal with the error!\n std::cerr << \"bugpoint: ERROR: Cannot create temporary file in the current \"\n\t << \" directory!\\n\";\n exit(1);\n }\n\n \/\/ We don't need to hold the temp file descriptor... we will trust that no one\n \/\/ will overwrite\/delete the file while we are working on it...\n close(TempFD);\n#else\n \/\/ If we don't have mkstemp, use the old and obsolete mktemp function.\n if (mktemp(FNBuffer) == 0) {\n \/\/ FIXME: this should return an emtpy string or something and allow the\n \/\/ caller to deal with the error!\n std::cerr << \"bugpoint: ERROR: Cannot create temporary file in the current \"\n << \" directory!\\n\";\n exit(1);\n }\n#endif\n\n std::string Result(FNBuffer);\n delete[] FNBuffer;\n return Result;\n}\n\nstatic bool AddPermissionsBits (const std::string &Filename, int bits) {\n \/\/ Get the umask value from the operating system. We want to use it\n \/\/ when changing the file's permissions. Since calling umask() sets\n \/\/ the umask and returns its old value, we must call it a second\n \/\/ time to reset it to the user's preference.\n int mask = umask(0777); \/\/ The arg. to umask is arbitrary.\n umask(mask); \/\/ Restore the umask.\n\n \/\/ Get the file's current mode.\n struct stat st;\n if ((stat(Filename.c_str(), &st)) == -1)\n return false;\n\n \/\/ Change the file to have whichever permissions bits from 'bits'\n \/\/ that the umask would not disable.\n if ((chmod(Filename.c_str(), (st.st_mode | (bits & ~mask)))) == -1)\n return false;\n\n return true;\n}\n\n\/\/\/ MakeFileExecutable - Make the file named Filename executable by\n\/\/\/ setting whichever execute permissions bits the process's current\n\/\/\/ umask would allow. Filename must name an existing file or\n\/\/\/ directory. Returns true on success, false on error.\n\/\/\/\nbool llvm::MakeFileExecutable(const std::string &Filename) {\n return AddPermissionsBits(Filename, 0111);\n}\n\n\/\/\/ MakeFileReadable - Make the file named Filename readable by\n\/\/\/ setting whichever read permissions bits the process's current\n\/\/\/ umask would allow. Filename must name an existing file or\n\/\/\/ directory. Returns true on success, false on error.\n\/\/\/\nbool llvm::MakeFileReadable(const std::string &Filename) {\n return AddPermissionsBits(Filename, 0444);\n}\n\n\/\/\/ getFileSize - Return the size of the specified file in bytes, or -1 if the\n\/\/\/ file cannot be read or does not exist.\nlong long llvm::getFileSize(const std::string &Filename) {\n struct stat StatBuf;\n if (stat(Filename.c_str(), &StatBuf) == -1)\n return -1;\n return StatBuf.st_size; \n}\n\n\/\/\/ getFileTimestamp - Get the last modified time for the specified file in an\n\/\/\/ unspecified format. This is useful to allow checking to see if a file was\n\/\/\/ updated since that last time the timestampt was aquired. If the file does\n\/\/\/ not exist or there is an error getting the time-stamp, zero is returned.\nunsigned long long llvm::getFileTimestamp(const std::string &Filename) {\n struct stat StatBuf;\n if (stat(Filename.c_str(), &StatBuf) == -1)\n return 0;\n return StatBuf.st_mtime; \n}\n\n\/\/\/ ReadFileIntoAddressSpace - Attempt to map the specific file into the\n\/\/\/ address space of the current process for reading. If this succeeds,\n\/\/\/ return the address of the buffer and the length of the file mapped. On\n\/\/\/ failure, return null.\nvoid *llvm::ReadFileIntoAddressSpace(const std::string &Filename, \n unsigned &Length) {\n#if defined(HAVE_MMAP_FILE) && !defined(_MSC_VER)\n Length = (unsigned)getFileSize(Filename);\n if ((int)Length == -1) return 0;\n\n FDHandle FD(open(Filename.c_str(), O_RDONLY));\n if (FD == -1) return 0;\n\n \/\/ If the file has a length of zero, mmap might return a null pointer. In \n \/\/ this case, allocate a single byte of memory and return it instead.\n if (Length == 0)\n return malloc(1);\n\n \/\/ mmap in the file all at once...\n void *Buffer = (void*)mmap(0, Length, PROT_READ, MAP_PRIVATE, FD, 0);\n\n if (Buffer == (void*)MAP_FAILED)\n return 0;\n\n return Buffer;\n#else\n \/\/ FIXME: implement with read\/write\n#error Unimplemented ReadFileIntoAddressSpace - need to use read\/write.\n return 0;\n#endif\n}\n\n\/\/\/ UnmapFileFromAddressSpace - Remove the specified file from the current\n\/\/\/ address space.\nvoid llvm::UnmapFileFromAddressSpace(void *Buffer, unsigned Length) {\n#if defined(HAVE_MMAP_FILE) && !defined(_MSC_VER)\n if (Length)\n munmap((char*)Buffer, Length);\n else\n free(Buffer); \/\/ Zero byte files are malloc(1)'s.\n#else\n free(Buffer);\n#endif\n}\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ FDHandle class implementation\n\/\/\n\nFDHandle::~FDHandle() throw() {\n if (FD != -1) close(FD);\n}\n\nFDHandle &FDHandle::operator=(int fd) throw() {\n if (FD != -1) close(FD);\n FD = fd;\n return *this;\n}\n\n<commit_msg>Handle headers for compressed bytecode files<commit_after>\/\/===- Support\/FileUtilities.cpp - File System Utilities ------------------===\/\/\n\/\/ \n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file was developed by the LLVM research group and is distributed under\n\/\/ the University of Illinois Open Source License. See LICENSE.TXT for details.\n\/\/ \n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This file implements a family of utility functions which are useful for doing\n\/\/ various things with files.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/Support\/FileUtilities.h\"\n#include \"llvm\/Support\/DataTypes.h\"\n#include \"llvm\/Config\/unistd.h\"\n#include \"llvm\/Config\/fcntl.h\"\n#include \"llvm\/Config\/sys\/types.h\"\n#include \"llvm\/Config\/sys\/stat.h\"\n#include \"llvm\/Config\/sys\/mman.h\"\n#include \"llvm\/Config\/alloca.h\"\n#include <cerrno>\n#include <cstdio>\n#include <fstream>\n#include <iostream>\nusing namespace llvm;\n\n\/\/\/ CheckMagic - Returns true IFF the file named FN begins with Magic. FN must\n\/\/\/ name a readable file.\n\/\/\/\nbool llvm::CheckMagic(const std::string &FN, const std::string &Magic) {\n char *buf = (char*)alloca(1 + Magic.size());\n std::ifstream f(FN.c_str());\n f.read(buf, Magic.size());\n buf[Magic.size()] = '\\0';\n return Magic == buf;\n}\n\n\/\/\/ IsArchive - Returns true IFF the file named FN appears to be a \"ar\" library\n\/\/\/ archive. The file named FN must exist.\n\/\/\/\nbool llvm::IsArchive(const std::string &FN) {\n \/\/ Inspect the beginning of the file to see if it contains the \"ar\"\n \/\/ library archive format magic string.\n return CheckMagic(FN, \"!<arch>\\012\");\n}\n\n\/\/\/ IsBytecode - Returns true IFF the file named FN appears to be an LLVM\n\/\/\/ bytecode file. The file named FN must exist.\n\/\/\/\nbool llvm::IsBytecode(const std::string &FN) {\n \/\/ Inspect the beginning of the file to see if it contains the LLVM\n \/\/ bytecode format magic string.\n return CheckMagic(FN, \"llvm\") || CheckMagic(FN, \"llvc\");\n}\n\n\/\/\/ IsSharedObject - Returns trus IFF the file named FN appears to be a shared\n\/\/\/ object with an ELF header. The file named FN must exist.\n\/\/\/\nbool llvm::IsSharedObject(const std::string &FN) {\n \/\/ Inspect the beginning of the file to see if it contains the ELF shared\n \/\/ object magic string.\n static const char elfMagic[] = { 0x7f, 'E', 'L', 'F', '\\0' };\n return CheckMagic(FN, elfMagic);\n}\n\n\/\/\/ FileOpenable - Returns true IFF Filename names an existing regular\n\/\/\/ file which we can successfully open.\n\/\/\/\nbool llvm::FileOpenable(const std::string &Filename) {\n struct stat s;\n if (stat (Filename.c_str (), &s) == -1)\n return false; \/\/ Cannot stat file\n if (!S_ISREG (s.st_mode))\n return false; \/\/ File is not a regular file\n std::ifstream FileStream (Filename.c_str ());\n if (!FileStream)\n return false; \/\/ File is not openable\n return true;\n}\n\n\/\/\/ DiffFiles - Compare the two files specified, returning true if they are\n\/\/\/ different or if there is a file error. If you specify a string to fill in\n\/\/\/ for the error option, it will set the string to an error message if an error\n\/\/\/ occurs, allowing the caller to distinguish between a failed diff and a file\n\/\/\/ system error.\n\/\/\/\nbool llvm::DiffFiles(const std::string &FileA, const std::string &FileB,\n std::string *Error) {\n std::ifstream FileAStream(FileA.c_str());\n if (!FileAStream) {\n if (Error) *Error = \"Couldn't open file '\" + FileA + \"'\";\n return true;\n }\n\n std::ifstream FileBStream(FileB.c_str());\n if (!FileBStream) {\n if (Error) *Error = \"Couldn't open file '\" + FileB + \"'\";\n return true;\n }\n\n \/\/ Compare the two files...\n int C1, C2;\n do {\n C1 = FileAStream.get();\n C2 = FileBStream.get();\n if (C1 != C2) return true;\n } while (C1 != EOF);\n\n return false;\n}\n\n\n\/\/\/ CopyFile - Copy the specified source file to the specified destination,\n\/\/\/ overwriting destination if it exists. This returns true on failure.\n\/\/\/\nbool llvm::CopyFile(const std::string &Dest, const std::string &Src) {\n FDHandle InFD(open(Src.c_str(), O_RDONLY));\n if (InFD == -1) return true;\n\n FileRemover FR(Dest);\n\n FDHandle OutFD(open(Dest.c_str(), O_WRONLY|O_CREAT, 0666));\n if (OutFD == -1) return true;\n\n char Buffer[16*1024];\n while (ssize_t Amt = read(InFD, Buffer, 16*1024)) {\n if (Amt == -1) {\n if (errno != EINTR) return true; \/\/ Error reading the file.\n } else {\n char *BufPtr = Buffer;\n while (Amt) {\n ssize_t AmtWritten = write(OutFD, BufPtr, Amt);\n if (AmtWritten == -1) {\n if (errno != EINTR) return true; \/\/ Error writing the file.\n } else {\n Amt -= AmtWritten;\n BufPtr += AmtWritten;\n }\n }\n }\n }\n\n FR.releaseFile(); \/\/ Success!\n return false;\n}\n\n\n\/\/\/ MoveFileOverIfUpdated - If the file specified by New is different than Old,\n\/\/\/ or if Old does not exist, move the New file over the Old file. Otherwise,\n\/\/\/ remove the New file.\n\/\/\/\nvoid llvm::MoveFileOverIfUpdated(const std::string &New,\n const std::string &Old) {\n if (DiffFiles(New, Old)) {\n if (std::rename(New.c_str(), Old.c_str()))\n std::cerr << \"Error renaming '\" << New << \"' to '\" << Old << \"'!\\n\";\n } else {\n std::remove(New.c_str());\n } \n}\n\n\/\/\/ removeFile - Delete the specified file\n\/\/\/\nvoid llvm::removeFile(const std::string &Filename) {\n std::remove(Filename.c_str());\n}\n\n\/\/\/ getUniqueFilename - Return a filename with the specified prefix. If the\n\/\/\/ file does not exist yet, return it, otherwise add a suffix to make it\n\/\/\/ unique.\n\/\/\/\nstd::string llvm::getUniqueFilename(const std::string &FilenameBase) {\n if (!std::ifstream(FilenameBase.c_str()))\n return FilenameBase; \/\/ Couldn't open the file? Use it!\n\n \/\/ Create a pattern for mkstemp...\n char *FNBuffer = new char[FilenameBase.size()+8];\n strcpy(FNBuffer, FilenameBase.c_str());\n strcpy(FNBuffer+FilenameBase.size(), \"-XXXXXX\");\n\n \/\/ Agree on a temporary file name to use....\n#if defined(HAVE_MKSTEMP) && !defined(_MSC_VER)\n int TempFD;\n if ((TempFD = mkstemp(FNBuffer)) == -1) {\n \/\/ FIXME: this should return an emtpy string or something and allow the\n \/\/ caller to deal with the error!\n std::cerr << \"bugpoint: ERROR: Cannot create temporary file in the current \"\n\t << \" directory!\\n\";\n exit(1);\n }\n\n \/\/ We don't need to hold the temp file descriptor... we will trust that no one\n \/\/ will overwrite\/delete the file while we are working on it...\n close(TempFD);\n#else\n \/\/ If we don't have mkstemp, use the old and obsolete mktemp function.\n if (mktemp(FNBuffer) == 0) {\n \/\/ FIXME: this should return an emtpy string or something and allow the\n \/\/ caller to deal with the error!\n std::cerr << \"bugpoint: ERROR: Cannot create temporary file in the current \"\n << \" directory!\\n\";\n exit(1);\n }\n#endif\n\n std::string Result(FNBuffer);\n delete[] FNBuffer;\n return Result;\n}\n\nstatic bool AddPermissionsBits (const std::string &Filename, int bits) {\n \/\/ Get the umask value from the operating system. We want to use it\n \/\/ when changing the file's permissions. Since calling umask() sets\n \/\/ the umask and returns its old value, we must call it a second\n \/\/ time to reset it to the user's preference.\n int mask = umask(0777); \/\/ The arg. to umask is arbitrary.\n umask(mask); \/\/ Restore the umask.\n\n \/\/ Get the file's current mode.\n struct stat st;\n if ((stat(Filename.c_str(), &st)) == -1)\n return false;\n\n \/\/ Change the file to have whichever permissions bits from 'bits'\n \/\/ that the umask would not disable.\n if ((chmod(Filename.c_str(), (st.st_mode | (bits & ~mask)))) == -1)\n return false;\n\n return true;\n}\n\n\/\/\/ MakeFileExecutable - Make the file named Filename executable by\n\/\/\/ setting whichever execute permissions bits the process's current\n\/\/\/ umask would allow. Filename must name an existing file or\n\/\/\/ directory. Returns true on success, false on error.\n\/\/\/\nbool llvm::MakeFileExecutable(const std::string &Filename) {\n return AddPermissionsBits(Filename, 0111);\n}\n\n\/\/\/ MakeFileReadable - Make the file named Filename readable by\n\/\/\/ setting whichever read permissions bits the process's current\n\/\/\/ umask would allow. Filename must name an existing file or\n\/\/\/ directory. Returns true on success, false on error.\n\/\/\/\nbool llvm::MakeFileReadable(const std::string &Filename) {\n return AddPermissionsBits(Filename, 0444);\n}\n\n\/\/\/ getFileSize - Return the size of the specified file in bytes, or -1 if the\n\/\/\/ file cannot be read or does not exist.\nlong long llvm::getFileSize(const std::string &Filename) {\n struct stat StatBuf;\n if (stat(Filename.c_str(), &StatBuf) == -1)\n return -1;\n return StatBuf.st_size; \n}\n\n\/\/\/ getFileTimestamp - Get the last modified time for the specified file in an\n\/\/\/ unspecified format. This is useful to allow checking to see if a file was\n\/\/\/ updated since that last time the timestampt was aquired. If the file does\n\/\/\/ not exist or there is an error getting the time-stamp, zero is returned.\nunsigned long long llvm::getFileTimestamp(const std::string &Filename) {\n struct stat StatBuf;\n if (stat(Filename.c_str(), &StatBuf) == -1)\n return 0;\n return StatBuf.st_mtime; \n}\n\n\/\/\/ ReadFileIntoAddressSpace - Attempt to map the specific file into the\n\/\/\/ address space of the current process for reading. If this succeeds,\n\/\/\/ return the address of the buffer and the length of the file mapped. On\n\/\/\/ failure, return null.\nvoid *llvm::ReadFileIntoAddressSpace(const std::string &Filename, \n unsigned &Length) {\n#if defined(HAVE_MMAP_FILE) && !defined(_MSC_VER)\n Length = (unsigned)getFileSize(Filename);\n if ((int)Length == -1) return 0;\n\n FDHandle FD(open(Filename.c_str(), O_RDONLY));\n if (FD == -1) return 0;\n\n \/\/ If the file has a length of zero, mmap might return a null pointer. In \n \/\/ this case, allocate a single byte of memory and return it instead.\n if (Length == 0)\n return malloc(1);\n\n \/\/ mmap in the file all at once...\n void *Buffer = (void*)mmap(0, Length, PROT_READ, MAP_PRIVATE, FD, 0);\n\n if (Buffer == (void*)MAP_FAILED)\n return 0;\n\n return Buffer;\n#else\n \/\/ FIXME: implement with read\/write\n#error Unimplemented ReadFileIntoAddressSpace - need to use read\/write.\n return 0;\n#endif\n}\n\n\/\/\/ UnmapFileFromAddressSpace - Remove the specified file from the current\n\/\/\/ address space.\nvoid llvm::UnmapFileFromAddressSpace(void *Buffer, unsigned Length) {\n#if defined(HAVE_MMAP_FILE) && !defined(_MSC_VER)\n if (Length)\n munmap((char*)Buffer, Length);\n else\n free(Buffer); \/\/ Zero byte files are malloc(1)'s.\n#else\n free(Buffer);\n#endif\n}\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ FDHandle class implementation\n\/\/\n\nFDHandle::~FDHandle() throw() {\n if (FD != -1) close(FD);\n}\n\nFDHandle &FDHandle::operator=(int fd) throw() {\n if (FD != -1) close(FD);\n FD = fd;\n return *this;\n}\n\n<|endoftext|>"} {"text":"<commit_before>#include \"ExpertSystem\/CLIPSFunctionBuilder.h\"\n\nCLIPSFunctionBuilder::CLIPSFunctionBuilder(std::string nm, \n FunctionNamer& namer) : CLIPSGlobalValueBuilder(nm, \"Function\", namer) { \n}\n\nvoid CLIPSFunctionBuilder::build(Function* fn, KnowledgeConstructor* kc, bool traverseFields) {\n open();\n addFields(fn, kc, traverseFields);\n close();\n std::string str = getCompletedString();\n kc->addToKnowledgeBase((PointerAddress)arg, str);\n}\n\nvoid CLIPSFunctionBuilder::setCallingConvention(CallingConv::ID id) {\n const char* selection;\n switch(id) {\n case CallingConv::C:\n selection = \"C\";\n break;\n case CallingConv::Fast:\n selection = \"Fast\";\n break;\n case CallingConv::Cold:\n selection = \"Cold\";\n break;\n case CallingConv::GHC:\n selection = \"GHC\";\n break;\n case CallingConv::HiPE:\n selection = \"HiPE\";\n break;\n case CallingConv::FirstTargetCC:\n selection = \"FirstTargetCC\";\n break;\n case CallingConv::X86_StdCall:\n selection = \"x86-stdcall\";\n break;\n case CallingConv::X86_FastCall:\n selection = \"x86-fastcall\";\n break;\n case CallingConv::ARM_APCS:\n selection = \"arm-apcs\";\n break;\n case CallingConv::ARM_AAPCS:\n selection = \"arm-aapcs\";\n break;\n case CallingConv::ARM_AAPCS_VFB:\n selection = \"arm-aapcs-vfb\";\n break;\n case CallingConv::MSP430_INTR:\n selection = \"msp430-intr\";\n break;\n case CallingConv::X86_ThisCall:\n selection = \"x86-thiscall\";\n break;\n case CallingConv::PTX_Kernel:\n selection = \"ptx-kernel\";\n break;\n case CallingConv::PTX_Device:\n selection = \"ptx-device\";\n break;\n case CallingConv::MBLAZE_INTR:\n selection = \"mblaze-intr\";\n break;\n case CallingConv::MBLAZE_SVOL:\n selection = \"mblaze-svol\";\n break;\n case CallingConv::SPIR_FUNC:\n selection = \"spir-func\";\n break;\n case CallingConv::SPIR_KERNEL:\n selection = \"spir-kernel\";\n break;\n case CallingConv::Intel_OCL_BI:\n selection = \"intel-ocl-bi\";\n break;\n default:\n selection = \"Unknown\";\n break;\n }\n addField(\"CallingConvention\", selection);\n}\n\nvoid CLIPSFunctionBuilder::addFields(Function* func, KnowledgeConstructor* kc, bool traverseFields) {\n CLIPSGlobalValueBuilder::addFields(func, kc);\n \/\/this part contains the code for building the function itself\n FunctionNamer& namer = getNamer();\n addField(\"ReturnType\", kc->route(fn->getReturnType(), namer));\n addField(\"FunctionType\", kc->route(fn->getFunctionType(), namer));\n if(fn.isVarArg()) {\n addTrueField(\"IsVarArg\");\n }\n addField(\"IntrinsicID\", fn->getIntrinsicID());\n if(fn.isIntrinsic()) {\n addTrueField(\"IsIntrinsic\");\n }\n setCallingConvention(func->getCallingConv(), kc);\n\n if(traverseFields) {\n\n }\n}\n\n<commit_msg>Continuing to implement CLIPSFunctionBuilder<commit_after>#include \"ExpertSystem\/CLIPSFunctionBuilder.h\"\n\nCLIPSFunctionBuilder::CLIPSFunctionBuilder(std::string nm, \n FunctionNamer& namer) : CLIPSGlobalValueBuilder(nm, \"Function\", namer) { \n}\n\nvoid CLIPSFunctionBuilder::build(Function* fn, KnowledgeConstructor* kc) {\n open();\n addFields(fn, kc);\n close();\n std::string str = getCompletedString();\n kc->addToKnowledgeBase((PointerAddress)arg, str);\n}\n\nvoid CLIPSFunctionBuilder::setCallingConvention(CallingConv::ID id) {\n const char* selection;\n switch(id) {\n case CallingConv::C:\n selection = \"C\";\n break;\n case CallingConv::Fast:\n selection = \"Fast\";\n break;\n case CallingConv::Cold:\n selection = \"Cold\";\n break;\n case CallingConv::GHC:\n selection = \"GHC\";\n break;\n case CallingConv::HiPE:\n selection = \"HiPE\";\n break;\n case CallingConv::FirstTargetCC:\n selection = \"FirstTargetCC\";\n break;\n case CallingConv::X86_StdCall:\n selection = \"x86-stdcall\";\n break;\n case CallingConv::X86_FastCall:\n selection = \"x86-fastcall\";\n break;\n case CallingConv::ARM_APCS:\n selection = \"arm-apcs\";\n break;\n case CallingConv::ARM_AAPCS:\n selection = \"arm-aapcs\";\n break;\n case CallingConv::ARM_AAPCS_VFB:\n selection = \"arm-aapcs-vfb\";\n break;\n case CallingConv::MSP430_INTR:\n selection = \"msp430-intr\";\n break;\n case CallingConv::X86_ThisCall:\n selection = \"x86-thiscall\";\n break;\n case CallingConv::PTX_Kernel:\n selection = \"ptx-kernel\";\n break;\n case CallingConv::PTX_Device:\n selection = \"ptx-device\";\n break;\n case CallingConv::MBLAZE_INTR:\n selection = \"mblaze-intr\";\n break;\n case CallingConv::MBLAZE_SVOL:\n selection = \"mblaze-svol\";\n break;\n case CallingConv::SPIR_FUNC:\n selection = \"spir-func\";\n break;\n case CallingConv::SPIR_KERNEL:\n selection = \"spir-kernel\";\n break;\n case CallingConv::Intel_OCL_BI:\n selection = \"intel-ocl-bi\";\n break;\n default:\n selection = \"Unknown\";\n break;\n }\n addField(\"CallingConvention\", selection);\n}\nvoid CLIPSFunctionBuilder::setAttributes(const AttributeSet& attr) {\n\n}\nvoid CLIPSFunctionBuilder::addFields(Function* func, \n KnowledgeConstructor* kc) {\n\n CLIPSGlobalValueBuilder::addFields(func, kc);\n \/\/this part contains the code for building the function itself\n FunctionNamer& namer = getNamer();\n addField(\"ReturnType\", kc->route(fn->getReturnType(), namer));\n addField(\"FunctionType\", kc->route(fn->getFunctionType(), namer));\n if(fn.isVarArg()) {\n addTrueField(\"IsVarArg\");\n }\n addField(\"IntrinsicID\", fn->getIntrinsicID());\n if(fn.isIntrinsic()) {\n addTrueField(\"IsIntrinsic\");\n }\n setCallingConvention(func->getCallingConv());\n setAttributes(func->getAttributes());\n if(fn.hasGC()) {\n addTrueField(\"HasGC\");\n }\n if(fn.doesNotAccessMemory()) {\n addTrueField(\"DoesNotAccessMemory\");\n }\n if(fn.onlyReadsMemory()) {\n addTrueField(\"OnlyReadsMemory\");\n }\n if(fn.doesNotReturn()) {\n addTrueField(\"DoesNotReturn\");\n }\n if(fn.cannotDuplicate()) {\n addTrueField(\"CannotDuplicate\");\n }\n if(fn.hasUWTable()) {\n addTrueField(\"HasUWTable\");\n }\n if(fn.needsUnwindTableEntry()) {\n addTrueField(\"NeedsUnwindTableEntry\");\n }\n if(fn.hasStructRetAttr()) {\n addTrueField(\"HasStructRetAttr\");\n }\n \/\/TODO: Expose doesNotAlias, doesNotCapture, and getParamAttributes to \n \/\/CLIPS as functions\n char* fnName = (char*)fn.getName().data();\n FunctionNamer& namer = getNamer();\n addField(\"EntryBlock\", kc->route(fn.getEntryBlock(), fnName, namer));\n\n if(traverseFields) {\n\n }\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n-------------------------------------------------------------------------\n This file is part of BayesOpt, an efficient C++ library for \n Bayesian optimization.\n\n Copyright (C) 2011-2015 Ruben Martinez-Cantin <rmcantin@unizar.es>\n \n BayesOpt is free software: you can redistribute it and\/or modify it \n under the terms of the GNU Affero General Public License as published by\n the Free Software Foundation, either version 3 of the License, or\n (at your option) any later version.\n\n BayesOpt is distributed in the hope that it will be useful, but \n WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU Affero General Public License for more details.\n\n You should have received a copy of the GNU Affero General Public License\n along with BayesOpt. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n------------------------------------------------------------------------\n*\/\n\n#include <ctime>\n#include \"bayesopt\/bayesoptbase.hpp\"\n#include \"bayesopt\/parameters.hpp\"\n\n#include \"log.hpp\"\n#include \"posteriormodel.hpp\"\n#include \"specialtypes.hpp\"\n#include \"bopt_state.hpp\"\n\n\nnamespace bayesopt\n{\n BayesOptBase::BayesOptBase(size_t dim, Parameters parameters):\n mParameters(parameters), mDims(dim)\n {\n \/\/ Random seed\n if (mParameters.random_seed < 0) mParameters.random_seed = std::time(0); \n mEngine.seed(mParameters.random_seed);\n \n \/\/ Setting verbose stuff (files, levels, etc.)\n int verbose = mParameters.verbose_level;\n if (verbose>=3)\n {\n\tFILE* log_fd = fopen( mParameters.log_filename.c_str() , \"w\" );\n\tOutput2FILE::Stream() = log_fd; \n\tverbose -= 3;\n }\n\n switch(verbose)\n {\n case 0: FILELog::ReportingLevel() = logWARNING; break;\n case 1: FILELog::ReportingLevel() = logINFO; break;\n case 2: FILELog::ReportingLevel() = logDEBUG4; break;\n default:\n\tFILELog::ReportingLevel() = logERROR; break;\n }\n }\n\n BayesOptBase::~BayesOptBase()\n { } \/\/ Default destructor\n\n\n \/\/ OPTIMIZATION INTERFACE\n void BayesOptBase::optimize(vectord &bestPoint)\n {\n assert(mDims == bestPoint.size());\n \n \/\/ Restore state from file\n if(mParameters.load_save_flag == 1 || mParameters.load_save_flag == 3)\n {\n BOptState state;\n bool load_succeed = state.loadFromFile(mParameters.load_filename, \n\t\t\t\t\t mParameters);\n if(load_succeed)\n\t {\n restoreOptimization(state);\n FILE_LOG(logINFO) << \"State succesfully restored from file \\\"\" \n\t\t\t << mParameters.load_filename << \"\\\"\";\n\t }\n else\n\t {\n\t \/\/ If load not succeed, print info message and then\n\t \/\/ initialize a new optimization\n FILE_LOG(logINFO) << \"File \\\"\" << mParameters.load_filename \n\t\t\t << \"\\\" does not exist,\"\n\t\t\t << \" starting a new optimization\";\n initializeOptimization();\n\t }\n }\n else\n {\n\t\/\/ Initialize a new state\n initializeOptimization();\n }\n \n for (size_t ii = mCurrentIter; ii < mParameters.n_iterations; ++ii)\n { \n stepOptimization();\n }\n \n bestPoint = getFinalResult();\n } \/\/ optimize\n\n\n void BayesOptBase::stepOptimization()\n {\n \/\/ Find what is the next point.\n vectord xNext = nextPoint(); \n double yNext = evaluateSampleInternal(xNext);\n\n \/\/ If we are stuck in the same point for several iterations, try a random jump!\n if (mParameters.force_jump)\n {\n if (std::pow(mYPrev - yNext,2) < mParameters.noise)\n {\n mCounterStuck++;\n FILE_LOG(logDEBUG) << \"Stuck for \"<< mCounterStuck << \" steps\";\n }\n else\n {\n mCounterStuck = 0;\n }\n mYPrev = yNext;\n\n if (mCounterStuck > mParameters.force_jump)\n {\n FILE_LOG(logINFO) << \"Forced random query!\";\n xNext = samplePoint();\n yNext = evaluateSampleInternal(xNext);\n mCounterStuck = 0;\n }\n }\n\n mModel->addSample(xNext,yNext);\n\n \/\/ Update surrogate model\n bool retrain = ((mParameters.n_iter_relearn > 0) && \n\t\t ((mCurrentIter + 1) % mParameters.n_iter_relearn == 0));\n\n if (retrain) \/\/ Full update\n {\n mModel->updateHyperParameters();\n mModel->fitSurrogateModel();\n }\n else \/\/ Incremental update\n {\n mModel->updateSurrogateModel();\n } \n\n plotStepData(mCurrentIter,xNext,yNext);\n mModel->updateCriteria(xNext);\n mCurrentIter++;\n \n \/\/ Save state if required\n if(mParameters.load_save_flag == 2 || mParameters.load_save_flag == 3)\n {\n BOptState state;\n saveOptimization(state);\n state.saveToFile(mParameters.save_filename);\n }\n }\n \n\n void BayesOptBase::initializeOptimization()\n {\n \/\/ Posterior surrogate model\n mModel.reset(PosteriorModel::create(mDims,mParameters,mEngine));\n \n \/\/ Configure iteration parameters\n if (mParameters.n_init_samples <= 0)\n {\n mParameters.n_init_samples = \n static_cast<size_t>(ceil(0.1*mParameters.n_iterations));\t\n }\n \n size_t nSamples = mParameters.n_init_samples;\n\n \/\/ Generate xPoints for initial sampling\n matrixd xPoints(nSamples,mDims);\n vectord yPoints(nSamples,0);\n\n \/\/ Save generated xPoints before its evaluation\n generateInitialPoints(xPoints);\n saveInitialSamples(xPoints);\n \n \/\/ Save on each evaluation for safety reasons\n for(size_t i=0; i<yPoints.size(); i++)\n {\n yPoints[i] = evaluateSample(row(xPoints,i));\n\t\/\/We clear the vector in the first iteration\n saveResponse(yPoints[i], i==0);\n }\n \n \/\/ Put samples into model\n mModel->setSamples(xPoints,yPoints);\n \n if(mParameters.verbose_level > 0)\n {\n mModel->plotDataset(logDEBUG);\n }\n \n mModel->updateHyperParameters();\n mModel->fitSurrogateModel();\n mCurrentIter = 0;\n\n mCounterStuck = 0;\n mYPrev = 0.0;\n }\n\n vectord BayesOptBase::getFinalResult()\n {\n return remapPoint(getPointAtMinimum());\n }\n\n\n \/\/ SAVE-RESTORE INTERFACE\n void BayesOptBase::saveOptimization(BOptState &state)\n { \n \/\/ BayesOptBase members\n state.mCurrentIter = mCurrentIter;\n state.mCounterStuck = mCounterStuck;\n state.mYPrev = mYPrev;\n\n state.mParameters = mParameters;\n\n \/\/ Samples\n state.mX = mModel->getData()->mX;\n state.mY = mModel->getData()->mY;\n }\n\n void BayesOptBase::restoreOptimization(BOptState state)\n {\n \/\/ Restore parameters\n mParameters = state.mParameters; \n \n \/\/ Posterior surrogate model\n mModel.reset(PosteriorModel::create(mDims, mParameters, mEngine));\n \n \/\/ Load samples, putting mX vecOfvec into a matrixd\n matrixd xPoints(state.mX.size(),state.mX[0].size());\n vectord yPoints(state.mX.size(),0);\n for(size_t i=0; i<state.mX.size(); i++)\n {\n row(xPoints, i) = state.mX[i];\n if(i < state.mY.size())\n\t {\n yPoints[i] = state.mY[i];\n\t }\n\telse\n\t {\n\t \/\/ Generate remaining initial samples saving in each evaluation\t \n\t yPoints[i] = evaluateSample(row(xPoints,i));\n\t saveResponse(yPoints[i], false);\n\t }\n }\n \n \/\/ Set loaded and generated samples\n mModel->setSamples(xPoints,yPoints);\n \n if(mParameters.verbose_level > 0)\n {\n mModel->plotDataset(logDEBUG);\n }\n \n \/\/ Calculate the posterior model\n mModel->updateHyperParameters();\n mModel->fitSurrogateModel();\n \n mCurrentIter = state.mCurrentIter;\n mCounterStuck = state.mCounterStuck;\n mYPrev = state.mYPrev;\n \n \/\/ Check if optimization has already finished\n if(mCurrentIter >= mParameters.n_iterations)\n {\n FILE_LOG(logINFO) << \"Optimization has already finished, delete \\\"\" \n\t\t\t << mParameters.load_filename \n\t\t\t << \"\\\" or give more n_iterations in parameters.\"; \n }\n }\n\n \n \/\/ GETTERS AND SETTERS\n \/\/ Potential inline functions. Moved here to simplify API and header\n \/\/ structure.\n ProbabilityDistribution* BayesOptBase::getPrediction(const vectord& query)\n { return mModel->getPrediction(query); };\n \n const Dataset* BayesOptBase::getData()\n { return mModel->getData(); };\n\n Parameters* BayesOptBase::getParameters() \n {return &mParameters;};\n\n double BayesOptBase::getValueAtMinimum()\n { return mModel->getValueAtMinimum(); };\n\n double BayesOptBase::evaluateCriteria(const vectord& query)\n {\n if (checkReachability(query)) return mModel->evaluateCriteria(query);\n else return 0.0;\n }\n\n size_t BayesOptBase::getCurrentIter()\n {return mCurrentIter;};\n\n \n\n \/\/ PROTECTED\n vectord BayesOptBase::getPointAtMinimum() \n { return mModel->getPointAtMinimum(); };\n\n double BayesOptBase::evaluateSampleInternal( const vectord &query )\n { \n const double yNext = evaluateSample(remapPoint(query)); \n if (yNext == HUGE_VAL)\n {\n\tthrow std::runtime_error(\"Function evaluation out of range\");\n }\n return yNext;\n }; \n\n\n\n \n \n void BayesOptBase::plotStepData(size_t iteration, const vectord& xNext,\n\t\t\t\t double yNext)\n {\n if(mParameters.verbose_level >0)\n { \n\tFILE_LOG(logINFO) << \"Iteration: \" << iteration+1 << \" of \" \n\t\t\t << mParameters.n_iterations << \" | Total samples: \" \n\t\t\t << iteration+1+mParameters.n_init_samples ;\n\tFILE_LOG(logINFO) << \"Query: \" << remapPoint(xNext); ;\n\tFILE_LOG(logINFO) << \"Query outcome: \" << yNext ;\n\tFILE_LOG(logINFO) << \"Best query: \" << getFinalResult(); \n\tFILE_LOG(logINFO) << \"Best outcome: \" << getValueAtMinimum();\n }\n } \/\/plotStepData\n\n\n void BayesOptBase::saveInitialSamples(matrixd xPoints)\n {\n \/\/ Save state if required\n if(mParameters.load_save_flag == 2 || mParameters.load_save_flag == 3)\n {\n BOptState state;\n saveOptimization(state);\n \n \/\/ Overwrite the state with initial samples so far\n state.mX.clear();\n for(size_t i=0; i<xPoints.size1(); i++)\n\t {\n state.mX.push_back(row(xPoints,i));\n\t }\n state.saveToFile(mParameters.save_filename);\n }\n }\n\n\n void BayesOptBase::saveResponse(double yPoint, bool clear)\n {\n \/\/ Save state if required\n if(mParameters.load_save_flag == 2 || mParameters.load_save_flag == 3)\n {\n BOptState state;\n saveOptimization(state);\n\tif (clear)\n\t {\n\t state.mY.clear();\n\t }\n\tutils::append(state.mY,yPoint);\n state.saveToFile(mParameters.save_filename);\n }\n }\n\n\n\n\n\n\n \/\/ PRIVATE MEMBERS\n vectord BayesOptBase::nextPoint()\n {\n \/\/Epsilon-Greedy exploration (see Bull 2011)\n if ((mParameters.epsilon > 0.0) && (mParameters.epsilon < 1.0))\n {\n\trandFloat drawSample(mEngine,realUniformDist(0,1));\n\tdouble result = drawSample();\n\tFILE_LOG(logINFO) << \"Trying random jump with prob:\" << result;\n\tif (mParameters.epsilon > result)\n\t {\n\t FILE_LOG(logINFO) << \"Epsilon-greedy random query!\";\n\t return samplePoint();\n\t }\n }\n\n vectord Xnext(mDims); \n\n \/\/ GP-Hedge and related algorithms\n if (mModel->criteriaRequiresComparison())\n {\n\tbool changed = true;\n\n\tmModel->setFirstCriterium();\n\twhile (changed)\n\t {\n\t findOptimal(Xnext);\n\t changed = mModel->setNextCriterium(Xnext);\n\t }\n\tstd::string name = mModel->getBestCriteria(Xnext);\n\tFILE_LOG(logINFO) << name << \" was selected.\";\n }\n else \/\/ Standard \"Bayesian optimization\"\n {\n\tFILE_LOG(logDEBUG) << \"------ Optimizing criteria ------\";\n\tfindOptimal(Xnext);\n }\n return Xnext;\n }\n\n\n\n} \/\/namespace bayesopt\n\n<commit_msg>Fixed bug in initial values not being rescaled properly<commit_after>\/*\n-------------------------------------------------------------------------\n This file is part of BayesOpt, an efficient C++ library for \n Bayesian optimization.\n\n Copyright (C) 2011-2015 Ruben Martinez-Cantin <rmcantin@unizar.es>\n \n BayesOpt is free software: you can redistribute it and\/or modify it \n under the terms of the GNU Affero General Public License as published by\n the Free Software Foundation, either version 3 of the License, or\n (at your option) any later version.\n\n BayesOpt is distributed in the hope that it will be useful, but \n WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU Affero General Public License for more details.\n\n You should have received a copy of the GNU Affero General Public License\n along with BayesOpt. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n------------------------------------------------------------------------\n*\/\n\n#include <ctime>\n#include \"bayesopt\/bayesoptbase.hpp\"\n#include \"bayesopt\/parameters.hpp\"\n\n#include \"log.hpp\"\n#include \"posteriormodel.hpp\"\n#include \"specialtypes.hpp\"\n#include \"bopt_state.hpp\"\n\n\nnamespace bayesopt\n{\n BayesOptBase::BayesOptBase(size_t dim, Parameters parameters):\n mParameters(parameters), mDims(dim)\n {\n \/\/ Random seed\n if (mParameters.random_seed < 0) mParameters.random_seed = std::time(0); \n mEngine.seed(mParameters.random_seed);\n \n \/\/ Setting verbose stuff (files, levels, etc.)\n int verbose = mParameters.verbose_level;\n if (verbose>=3)\n {\n\tFILE* log_fd = fopen( mParameters.log_filename.c_str() , \"w\" );\n\tOutput2FILE::Stream() = log_fd; \n\tverbose -= 3;\n }\n\n switch(verbose)\n {\n case 0: FILELog::ReportingLevel() = logWARNING; break;\n case 1: FILELog::ReportingLevel() = logINFO; break;\n case 2: FILELog::ReportingLevel() = logDEBUG4; break;\n default:\n\tFILELog::ReportingLevel() = logERROR; break;\n }\n }\n\n BayesOptBase::~BayesOptBase()\n { } \/\/ Default destructor\n\n\n \/\/ OPTIMIZATION INTERFACE\n void BayesOptBase::optimize(vectord &bestPoint)\n {\n assert(mDims == bestPoint.size());\n \n \/\/ Restore state from file\n if(mParameters.load_save_flag == 1 || mParameters.load_save_flag == 3)\n {\n BOptState state;\n bool load_succeed = state.loadFromFile(mParameters.load_filename, \n\t\t\t\t\t mParameters);\n if(load_succeed)\n\t {\n restoreOptimization(state);\n FILE_LOG(logINFO) << \"State succesfully restored from file \\\"\" \n\t\t\t << mParameters.load_filename << \"\\\"\";\n\t }\n else\n\t {\n\t \/\/ If load not succeed, print info message and then\n\t \/\/ initialize a new optimization\n FILE_LOG(logINFO) << \"File \\\"\" << mParameters.load_filename \n\t\t\t << \"\\\" does not exist,\"\n\t\t\t << \" starting a new optimization\";\n initializeOptimization();\n\t }\n }\n else\n {\n\t\/\/ Initialize a new state\n initializeOptimization();\n }\n \n for (size_t ii = mCurrentIter; ii < mParameters.n_iterations; ++ii)\n { \n stepOptimization();\n }\n \n bestPoint = getFinalResult();\n } \/\/ optimize\n\n\n void BayesOptBase::stepOptimization()\n {\n \/\/ Find what is the next point.\n vectord xNext = nextPoint(); \n double yNext = evaluateSampleInternal(xNext);\n\n \/\/ If we are stuck in the same point for several iterations, try a random jump!\n if (mParameters.force_jump)\n {\n if (std::pow(mYPrev - yNext,2) < mParameters.noise)\n {\n mCounterStuck++;\n FILE_LOG(logDEBUG) << \"Stuck for \"<< mCounterStuck << \" steps\";\n }\n else\n {\n mCounterStuck = 0;\n }\n mYPrev = yNext;\n\n if (mCounterStuck > mParameters.force_jump)\n {\n FILE_LOG(logINFO) << \"Forced random query!\";\n xNext = samplePoint();\n yNext = evaluateSampleInternal(xNext);\n mCounterStuck = 0;\n }\n }\n\n mModel->addSample(xNext,yNext);\n\n \/\/ Update surrogate model\n bool retrain = ((mParameters.n_iter_relearn > 0) && \n\t\t ((mCurrentIter + 1) % mParameters.n_iter_relearn == 0));\n\n if (retrain) \/\/ Full update\n {\n mModel->updateHyperParameters();\n mModel->fitSurrogateModel();\n }\n else \/\/ Incremental update\n {\n mModel->updateSurrogateModel();\n } \n\n plotStepData(mCurrentIter,xNext,yNext);\n mModel->updateCriteria(xNext);\n mCurrentIter++;\n \n \/\/ Save state if required\n if(mParameters.load_save_flag == 2 || mParameters.load_save_flag == 3)\n {\n BOptState state;\n saveOptimization(state);\n state.saveToFile(mParameters.save_filename);\n }\n }\n \n\n void BayesOptBase::initializeOptimization()\n {\n \/\/ Posterior surrogate model\n mModel.reset(PosteriorModel::create(mDims,mParameters,mEngine));\n \n \/\/ Configure iteration parameters\n if (mParameters.n_init_samples <= 0)\n {\n mParameters.n_init_samples = \n static_cast<size_t>(ceil(0.1*mParameters.n_iterations));\t\n }\n \n size_t nSamples = mParameters.n_init_samples;\n\n \/\/ Generate xPoints for initial sampling\n matrixd xPoints(nSamples,mDims);\n vectord yPoints(nSamples,0);\n\n \/\/ Save generated xPoints before its evaluation\n generateInitialPoints(xPoints);\n saveInitialSamples(xPoints);\n \n \/\/ Save on each evaluation for safety reasons\n for(size_t i=0; i<yPoints.size(); i++)\n {\n yPoints[i] = evaluateSampleInternal(row(xPoints,i));\n\t\/\/We clear the vector in the first iteration\n saveResponse(yPoints[i], i==0);\n }\n \n \/\/ Put samples into model\n mModel->setSamples(xPoints,yPoints);\n \n if(mParameters.verbose_level > 0)\n {\n mModel->plotDataset(logDEBUG);\n }\n \n mModel->updateHyperParameters();\n mModel->fitSurrogateModel();\n mCurrentIter = 0;\n\n mCounterStuck = 0;\n mYPrev = 0.0;\n }\n\n vectord BayesOptBase::getFinalResult()\n {\n return remapPoint(getPointAtMinimum());\n }\n\n\n \/\/ SAVE-RESTORE INTERFACE\n void BayesOptBase::saveOptimization(BOptState &state)\n { \n \/\/ BayesOptBase members\n state.mCurrentIter = mCurrentIter;\n state.mCounterStuck = mCounterStuck;\n state.mYPrev = mYPrev;\n\n state.mParameters = mParameters;\n\n \/\/ Samples\n state.mX = mModel->getData()->mX;\n state.mY = mModel->getData()->mY;\n }\n\n void BayesOptBase::restoreOptimization(BOptState state)\n {\n \/\/ Restore parameters\n mParameters = state.mParameters; \n \n \/\/ Posterior surrogate model\n mModel.reset(PosteriorModel::create(mDims, mParameters, mEngine));\n \n \/\/ Load samples, putting mX vecOfvec into a matrixd\n matrixd xPoints(state.mX.size(),state.mX[0].size());\n vectord yPoints(state.mX.size(),0);\n for(size_t i=0; i<state.mX.size(); i++)\n {\n row(xPoints, i) = state.mX[i];\n if(i < state.mY.size())\n\t {\n yPoints[i] = state.mY[i];\n\t }\n\telse\n\t {\n\t \/\/ Generate remaining initial samples saving in each evaluation\t \n\t yPoints[i] = evaluateSampleInternal(row(xPoints,i));\n\t saveResponse(yPoints[i], false);\n\t }\n }\n \n \/\/ Set loaded and generated samples\n mModel->setSamples(xPoints,yPoints);\n \n if(mParameters.verbose_level > 0)\n {\n mModel->plotDataset(logDEBUG);\n }\n \n \/\/ Calculate the posterior model\n mModel->updateHyperParameters();\n mModel->fitSurrogateModel();\n \n mCurrentIter = state.mCurrentIter;\n mCounterStuck = state.mCounterStuck;\n mYPrev = state.mYPrev;\n \n \/\/ Check if optimization has already finished\n if(mCurrentIter >= mParameters.n_iterations)\n {\n FILE_LOG(logINFO) << \"Optimization has already finished, delete \\\"\" \n\t\t\t << mParameters.load_filename \n\t\t\t << \"\\\" or give more n_iterations in parameters.\"; \n }\n }\n\n \n \/\/ GETTERS AND SETTERS\n \/\/ Potential inline functions. Moved here to simplify API and header\n \/\/ structure.\n ProbabilityDistribution* BayesOptBase::getPrediction(const vectord& query)\n { return mModel->getPrediction(query); };\n \n const Dataset* BayesOptBase::getData()\n { return mModel->getData(); };\n\n Parameters* BayesOptBase::getParameters() \n {return &mParameters;};\n\n double BayesOptBase::getValueAtMinimum()\n { return mModel->getValueAtMinimum(); };\n\n double BayesOptBase::evaluateCriteria(const vectord& query)\n {\n if (checkReachability(query)) return mModel->evaluateCriteria(query);\n else return 0.0;\n }\n\n size_t BayesOptBase::getCurrentIter()\n {return mCurrentIter;};\n\n \n\n \/\/ PROTECTED\n vectord BayesOptBase::getPointAtMinimum() \n { return mModel->getPointAtMinimum(); };\n\n double BayesOptBase::evaluateSampleInternal( const vectord &query )\n { \n const double yNext = evaluateSample(remapPoint(query)); \n if (yNext == HUGE_VAL)\n {\n\tthrow std::runtime_error(\"Function evaluation out of range\");\n }\n return yNext;\n }; \n\n\n\n \n \n void BayesOptBase::plotStepData(size_t iteration, const vectord& xNext,\n\t\t\t\t double yNext)\n {\n if(mParameters.verbose_level >0)\n { \n\tFILE_LOG(logINFO) << \"Iteration: \" << iteration+1 << \" of \" \n\t\t\t << mParameters.n_iterations << \" | Total samples: \" \n\t\t\t << iteration+1+mParameters.n_init_samples ;\n\tFILE_LOG(logINFO) << \"Query: \" << remapPoint(xNext); ;\n\tFILE_LOG(logINFO) << \"Query outcome: \" << yNext ;\n\tFILE_LOG(logINFO) << \"Best query: \" << getFinalResult(); \n\tFILE_LOG(logINFO) << \"Best outcome: \" << getValueAtMinimum();\n }\n } \/\/plotStepData\n\n\n void BayesOptBase::saveInitialSamples(matrixd xPoints)\n {\n \/\/ Save state if required\n if(mParameters.load_save_flag == 2 || mParameters.load_save_flag == 3)\n {\n BOptState state;\n saveOptimization(state);\n \n \/\/ Overwrite the state with initial samples so far\n state.mX.clear();\n for(size_t i=0; i<xPoints.size1(); i++)\n\t {\n state.mX.push_back(row(xPoints,i));\n\t }\n state.saveToFile(mParameters.save_filename);\n }\n }\n\n\n void BayesOptBase::saveResponse(double yPoint, bool clear)\n {\n \/\/ Save state if required\n if(mParameters.load_save_flag == 2 || mParameters.load_save_flag == 3)\n {\n BOptState state;\n saveOptimization(state);\n\tif (clear)\n\t {\n\t state.mY.clear();\n\t }\n\tutils::append(state.mY,yPoint);\n state.saveToFile(mParameters.save_filename);\n }\n }\n\n\n\n\n\n\n \/\/ PRIVATE MEMBERS\n vectord BayesOptBase::nextPoint()\n {\n \/\/Epsilon-Greedy exploration (see Bull 2011)\n if ((mParameters.epsilon > 0.0) && (mParameters.epsilon < 1.0))\n {\n\trandFloat drawSample(mEngine,realUniformDist(0,1));\n\tdouble result = drawSample();\n\tFILE_LOG(logINFO) << \"Trying random jump with prob:\" << result;\n\tif (mParameters.epsilon > result)\n\t {\n\t FILE_LOG(logINFO) << \"Epsilon-greedy random query!\";\n\t return samplePoint();\n\t }\n }\n\n vectord Xnext(mDims); \n\n \/\/ GP-Hedge and related algorithms\n if (mModel->criteriaRequiresComparison())\n {\n\tbool changed = true;\n\n\tmModel->setFirstCriterium();\n\twhile (changed)\n\t {\n\t findOptimal(Xnext);\n\t changed = mModel->setNextCriterium(Xnext);\n\t }\n\tstd::string name = mModel->getBestCriteria(Xnext);\n\tFILE_LOG(logINFO) << name << \" was selected.\";\n }\n else \/\/ Standard \"Bayesian optimization\"\n {\n\tFILE_LOG(logDEBUG) << \"------ Optimizing criteria ------\";\n\tfindOptimal(Xnext);\n }\n return Xnext;\n }\n\n\n\n} \/\/namespace bayesopt\n\n<|endoftext|>"} {"text":"<commit_before>\/* IBM_PROLOG_BEGIN_TAG *\/\n\/* This is an automatically generated prolog. *\/\n\/* *\/\n\/* $Source: src\/usr\/isteps\/istep07\/call_mss_eff_config.C $ *\/\n\/* *\/\n\/* OpenPOWER HostBoot Project *\/\n\/* *\/\n\/* Contributors Listed Below - COPYRIGHT 2015,2016 *\/\n\/* [+] International Business Machines Corp. *\/\n\/* *\/\n\/* *\/\n\/* Licensed under the Apache License, Version 2.0 (the \"License\"); *\/\n\/* you may not use this file except in compliance with the License. *\/\n\/* You may obtain a copy of the License at *\/\n\/* *\/\n\/* http:\/\/www.apache.org\/licenses\/LICENSE-2.0 *\/\n\/* *\/\n\/* Unless required by applicable law or agreed to in writing, software *\/\n\/* distributed under the License is distributed on an \"AS IS\" BASIS, *\/\n\/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or *\/\n\/* implied. See the License for the specific language governing *\/\n\/* permissions and limitations under the License. *\/\n\/* *\/\n\/* IBM_PROLOG_END_TAG *\/\n\/**\n * @file call_mss_eff_config.C\n * Contains the wrapper for mss_eff_config istep\n *\/\n\n\/******************************************************************************\/\n\/\/ Includes\n\/******************************************************************************\/\n#include <stdint.h>\n#include <map>\n\n#include <trace\/interface.H>\n#include <initservice\/taskargs.H>\n#include <errl\/errlentry.H>\n\n#include <isteps\/hwpisteperror.H>\n#include <errl\/errludtarget.H>\n\n#include <initservice\/isteps_trace.H>\n\n\/\/ targeting support\n#include <targeting\/common\/commontargeting.H>\n#include <targeting\/common\/utilFilter.H>\n\n#include <config.h>\n#include <fapi2.H>\n#include <fapi2\/plat_hwp_invoker.H>\n\n\/\/ HWP\n#include <p9_mss_eff_config.H>\n#include <p9_mss_eff_config_thermal.H>\n#include <p9_mss_eff_grouping.H>\n\nnamespace ISTEP_07\n{\n\nusing namespace ISTEP;\nusing namespace ISTEP_ERROR;\nusing namespace ERRORLOG;\nusing namespace TARGETING;\n\nerrlHndl_t call_mss_eff_grouping(IStepError & io_istepErr)\n{\n errlHndl_t l_err = NULL;\n\n TARGETING::TargetHandleList l_procsList;\n getAllChips(l_procsList, TYPE_PROC);\n\n for (const auto & l_cpu_target : l_procsList)\n {\n \/\/ print call to hwp and write HUID of the target(s)\n TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace,\n \"p9_mss_eff_grouping HWP cpu target HUID %.8X\",\n TARGETING::get_huid(l_cpu_target));\n\n \/\/ cast OUR type of target to a FAPI type of target.\n const fapi2::Target <fapi2::TARGET_TYPE_PROC_CHIP> l_fapi_cpu_target\n (l_cpu_target);\n\n FAPI_INVOKE_HWP(l_err, p9_mss_eff_grouping, l_fapi_cpu_target);\n\n \/\/ process return code.\n if ( l_err )\n {\n TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace,\n \"ERROR 0x%.8X: p9_mss_eff_grouping HWP on target %.8x\",\n l_err->reasonCode(), TARGETING::get_huid(l_cpu_target));\n\n \/\/ capture the target data in the elog\n ErrlUserDetailsTarget(l_cpu_target).addToLog(l_err);\n io_istepErr.addErrorDetails(l_err);\n errlCommit(l_err, HWPF_COMP_ID);\n }\n else\n {\n TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace,\n \"SUCCESS : p9_mss_eff_grouping HWP on target %.8x\",\n TARGETING::get_huid(l_cpu_target));\n }\n } \/\/ end processor list processing\n\n return l_err;\n}\n\n\nerrlHndl_t call_mss_eff_mb_interleave()\n{\n errlHndl_t l_err = NULL;\n\/* TOOD RTC: 144076 --- cumulus only ---\n TARGETING::TargetHandleList l_membufTargetList;\n getAllChips(l_membufTargetList, TYPE_MEMBUF);\n\n for (const auto & l_membuf_target : l_membufTargetList)\n {\n TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace,\n \"===== Running mss_eff_mb_interleave HWP on HUID %.8X\",\n TARGETING::get_huid(l_membuf_target));\n fapi::Target l_membuf_fapi_target(fapi::TARGET_TYPE_MEMBUF_CHIP,\n (const_cast<TARGETING::Target*>(l_membuf_target)) );\n FAPI_INVOKE_HWP(l_err, mss_eff_mb_interleave, l_membuf_fapi_target);\n if (l_err)\n {\n TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace,\n \"ERROR 0x%.8X: mss_eff_mb_interleave HWP returns error\",\n l_err->reasonCode());\n ErrlUserDetailsTarget(l_membuf_target).addToLog(l_err);\n }\n else\n {\n TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace,\n \"Successfully ran mss_eff_mb_interleave HWP on HUID %.8X\",\n TARGETING::get_huid(l_membuf_target));\n }\n }\n*\/\n return l_err;\n}\n\n\n\/\/\n\/\/ Wrapper function to call mss_eff_config\n\/\/\nvoid* call_mss_eff_config( void *io_pArgs )\n{\n IStepError l_StepError;\n errlHndl_t l_err = NULL;\n\n TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace, \"call_mss_eff_config entry\" );\n\n TARGETING::Target* l_sys = NULL;\n targetService().getTopLevelTarget(l_sys);\n assert( l_sys != NULL );\n\n \/\/ The attribute ATTR_MEM_MIRROR_PLACEMENT_POLICY should already be\n \/\/ correctly set by default for all platforms except for sapphire.\n \/\/ Don't allow mirroring on sapphire yet @todo-RTC:108314\n \/\/\n \/\/ATTR_PAYLOAD_IN_MIRROR_MEM_type l_mirrored =\n \/\/ l_sys->getAttr<ATTR_PAYLOAD_IN_MIRROR_MEM>();\n \/\/\n \/\/if(l_mirrored && is_sapphire_load())\n \/\/{\n \/\/ TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace, \"Mirroring is enabled\");\n\n \/\/ uint8_t l_mmPolicy =\n \/\/ fapi::ENUM_ATTR_MEM_MIRROR_PLACEMENT_POLICY_FLIPPED;\n \/\/ l_sys->\n \/\/ setAttr<TARGETING::ATTR_MEM_MIRROR_PLACEMENT_POLICY>(l_mmPolicy);\n \/\/}\n\n \/\/ Get all functional MCS chiplets\n TARGETING::TargetHandleList l_mcsTargetList;\n getAllChiplets(l_mcsTargetList, TYPE_MCS);\n\n \/\/ Iterate over all MCS, calling mss_eff_config and mss_eff_config_thermal\n for (const auto & l_mcs_target : l_mcsTargetList)\n {\n \/\/ Get the TARGETING::Target pointer and its HUID\n uint32_t l_huid = TARGETING::get_huid(l_mcs_target);\n\n \/\/ Create a FAPI target representing the MCS\n const fapi2::Target <fapi2::TARGET_TYPE_MCS> l_fapi_mcs_target\n (l_mcs_target);\n\n \/\/ Call the mss_eff_config HWP\n TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace,\n \"p9_mss_eff_config HWP. MCS HUID %.8X\", l_huid);\n FAPI_INVOKE_HWP(l_err, p9_mss_eff_config, l_fapi_mcs_target);\n\n if (l_err)\n {\n TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace,\n \"ERROR 0x%.8X: p9_mss_eff_config HWP \", l_err->reasonCode());\n\n \/\/ Ensure istep error created and has same plid as this error\n ErrlUserDetailsTarget(l_mcs_target).addToLog(l_err);\n l_StepError.addErrorDetails(l_err);\n errlCommit(l_err, HWPF_COMP_ID);\n continue;\n }\n\n TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace,\n \"SUCCESS : p9_mss_eff_config HWP\");\n } \/\/ end membuf loop\n\n std::map<ATTR_VDDR_ID_type,TARGETING::TargetHandleList> l_domainIdGroups;\n TARGETING::TargetHandleList l_mcbistTargetList;\n getAllChiplets(l_mcsTargetList, TYPE_MCBIST);\n\n \/\/ Iterate over all MCBIST, calling mss_eff_config_thermal\n for (const auto & l_mcbist_target : l_mcbistTargetList)\n {\n TARGETING::TargetHandleList l_mcsChildren;\n getChildChiplets(l_mcsChildren,l_mcbist_target, TARGETING::TYPE_MCS);\n\n ATTR_VDDR_ID_type l_vddr_id = l_mcbist_target->getAttr<ATTR_VDDR_ID>();\n if(l_domainIdGroups.find(l_vddr_id) == l_domainIdGroups.end())\n {\n std::pair<ATTR_VDDR_ID_type, TARGETING::TargetHandleList> tuple(l_vddr_id, l_mcsChildren);\n l_domainIdGroups.insert(tuple);\n }\n else\n {\n l_domainIdGroups[l_vddr_id].insert(l_domainIdGroups[l_vddr_id].end(), l_mcsChildren.begin(), l_mcsChildren.end());\n }\n }\n\n for (auto & l_tuple : l_domainIdGroups)\n {\n std::vector<fapi2::Target<fapi2::TARGET_TYPE_MCS>> l_fapi_mcs_targs;\n for(const auto & l_mcs_target : l_tuple.second)\n {\n \/\/ Create a FAPI target representing the MCS\n const fapi2::Target <fapi2::TARGET_TYPE_MCS> l_fapi_mcs_target\n (l_mcs_target);\n l_fapi_mcs_targs.push_back(l_fapi_mcs_target);\n }\n \/\/ Call the mss_eff_config_thermal HWP\n TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace,\n \"p9_mss_eff_config_thermal HWP. \");\n FAPI_INVOKE_HWP(l_err, p9_mss_eff_config_thermal,l_fapi_mcs_targs);\n\n if (l_err)\n {\n TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace,\n \"ERROR 0x%.8X: p9_mss_eff_config_thermal HWP \",\n l_err->reasonCode());\n\n \/\/ Ensure istep error created and has same plid as this error\n l_StepError.addErrorDetails(l_err);\n errlCommit(l_err, HWPF_COMP_ID);\n }\n else\n {\n TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace,\n \"SUCCESS : p9_mss_eff_config_thermal HWP\");\n }\n }\n\n\n if (l_StepError.isNull())\n {\n \/\/ Stack the memory on each chip\n l_err = call_mss_eff_grouping(l_StepError);\n\n \/\/ TODO RTC: 144076\n \/\/if(!l_err) \/\/Cumulus only\n \/\/{\n \/\/ l_err = call_mss_eff_mb_interleave();\n \/\/}\n\n if (l_err)\n {\n \/\/ Ensure istep error created and has same plid as this error\n l_StepError.addErrorDetails( l_err );\n errlCommit( l_err, HWPF_COMP_ID );\n }\n }\n\n TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace, \"call_mss_eff_config exit\" );\n return l_StepError.getErrorHandle();\n}\n}; \/\/ end namespace\n<commit_msg>Fix bugs to allow p9_mss_eff_config_thermal to be executed<commit_after>\/* IBM_PROLOG_BEGIN_TAG *\/\n\/* This is an automatically generated prolog. *\/\n\/* *\/\n\/* $Source: src\/usr\/isteps\/istep07\/call_mss_eff_config.C $ *\/\n\/* *\/\n\/* OpenPOWER HostBoot Project *\/\n\/* *\/\n\/* Contributors Listed Below - COPYRIGHT 2015,2017 *\/\n\/* [+] International Business Machines Corp. *\/\n\/* *\/\n\/* *\/\n\/* Licensed under the Apache License, Version 2.0 (the \"License\"); *\/\n\/* you may not use this file except in compliance with the License. *\/\n\/* You may obtain a copy of the License at *\/\n\/* *\/\n\/* http:\/\/www.apache.org\/licenses\/LICENSE-2.0 *\/\n\/* *\/\n\/* Unless required by applicable law or agreed to in writing, software *\/\n\/* distributed under the License is distributed on an \"AS IS\" BASIS, *\/\n\/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or *\/\n\/* implied. See the License for the specific language governing *\/\n\/* permissions and limitations under the License. *\/\n\/* *\/\n\/* IBM_PROLOG_END_TAG *\/\n\/**\n * @file call_mss_eff_config.C\n * Contains the wrapper for mss_eff_config istep\n *\/\n\n\/******************************************************************************\/\n\/\/ Includes\n\/******************************************************************************\/\n#include <stdint.h>\n#include <map>\n\n#include <trace\/interface.H>\n#include <initservice\/taskargs.H>\n#include <errl\/errlentry.H>\n\n#include <isteps\/hwpisteperror.H>\n#include <errl\/errludtarget.H>\n\n#include <initservice\/isteps_trace.H>\n\n\/\/ targeting support\n#include <targeting\/common\/commontargeting.H>\n#include <targeting\/common\/utilFilter.H>\n\n#include <config.h>\n#include <fapi2.H>\n#include <fapi2\/plat_hwp_invoker.H>\n\n\/\/ HWP\n#include <p9_mss_eff_config.H>\n#include <p9_mss_eff_config_thermal.H>\n#include <p9_mss_eff_grouping.H>\n\nnamespace ISTEP_07\n{\n\nusing namespace ISTEP;\nusing namespace ISTEP_ERROR;\nusing namespace ERRORLOG;\nusing namespace TARGETING;\n\nerrlHndl_t call_mss_eff_grouping(IStepError & io_istepErr)\n{\n errlHndl_t l_err = NULL;\n\n TARGETING::TargetHandleList l_procsList;\n getAllChips(l_procsList, TYPE_PROC);\n\n for (const auto & l_cpu_target : l_procsList)\n {\n \/\/ print call to hwp and write HUID of the target(s)\n TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace,\n \"p9_mss_eff_grouping HWP cpu target HUID %.8X\",\n TARGETING::get_huid(l_cpu_target));\n\n \/\/ cast OUR type of target to a FAPI type of target.\n const fapi2::Target <fapi2::TARGET_TYPE_PROC_CHIP> l_fapi_cpu_target\n (l_cpu_target);\n\n FAPI_INVOKE_HWP(l_err, p9_mss_eff_grouping, l_fapi_cpu_target);\n\n \/\/ process return code.\n if ( l_err )\n {\n TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace,\n \"ERROR 0x%.8X: p9_mss_eff_grouping HWP on target %.8x\",\n l_err->reasonCode(), TARGETING::get_huid(l_cpu_target));\n\n \/\/ capture the target data in the elog\n ErrlUserDetailsTarget(l_cpu_target).addToLog(l_err);\n io_istepErr.addErrorDetails(l_err);\n errlCommit(l_err, HWPF_COMP_ID);\n }\n else\n {\n TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace,\n \"SUCCESS : p9_mss_eff_grouping HWP on target %.8x\",\n TARGETING::get_huid(l_cpu_target));\n }\n } \/\/ end processor list processing\n\n return l_err;\n}\n\n\nerrlHndl_t call_mss_eff_mb_interleave()\n{\n errlHndl_t l_err = NULL;\n\/* TOOD RTC: 144076 --- cumulus only ---\n TARGETING::TargetHandleList l_membufTargetList;\n getAllChips(l_membufTargetList, TYPE_MEMBUF);\n\n for (const auto & l_membuf_target : l_membufTargetList)\n {\n TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace,\n \"===== Running mss_eff_mb_interleave HWP on HUID %.8X\",\n TARGETING::get_huid(l_membuf_target));\n fapi::Target l_membuf_fapi_target(fapi::TARGET_TYPE_MEMBUF_CHIP,\n (const_cast<TARGETING::Target*>(l_membuf_target)) );\n FAPI_INVOKE_HWP(l_err, mss_eff_mb_interleave, l_membuf_fapi_target);\n if (l_err)\n {\n TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace,\n \"ERROR 0x%.8X: mss_eff_mb_interleave HWP returns error\",\n l_err->reasonCode());\n ErrlUserDetailsTarget(l_membuf_target).addToLog(l_err);\n }\n else\n {\n TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace,\n \"Successfully ran mss_eff_mb_interleave HWP on HUID %.8X\",\n TARGETING::get_huid(l_membuf_target));\n }\n }\n*\/\n return l_err;\n}\n\n\n\/\/\n\/\/ Wrapper function to call mss_eff_config\n\/\/\nvoid* call_mss_eff_config( void *io_pArgs )\n{\n IStepError l_StepError;\n errlHndl_t l_err = NULL;\n\n TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace, \"call_mss_eff_config entry\" );\n\n TARGETING::Target* l_sys = NULL;\n targetService().getTopLevelTarget(l_sys);\n assert( l_sys != NULL );\n\n \/\/ The attribute ATTR_MEM_MIRROR_PLACEMENT_POLICY should already be\n \/\/ correctly set by default for all platforms except for sapphire.\n \/\/ Don't allow mirroring on sapphire yet @todo-RTC:108314\n \/\/\n \/\/ATTR_PAYLOAD_IN_MIRROR_MEM_type l_mirrored =\n \/\/ l_sys->getAttr<ATTR_PAYLOAD_IN_MIRROR_MEM>();\n \/\/\n \/\/if(l_mirrored && is_sapphire_load())\n \/\/{\n \/\/ TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace, \"Mirroring is enabled\");\n\n \/\/ uint8_t l_mmPolicy =\n \/\/ fapi::ENUM_ATTR_MEM_MIRROR_PLACEMENT_POLICY_FLIPPED;\n \/\/ l_sys->\n \/\/ setAttr<TARGETING::ATTR_MEM_MIRROR_PLACEMENT_POLICY>(l_mmPolicy);\n \/\/}\n\n \/\/ Get all functional MCS chiplets\n TARGETING::TargetHandleList l_mcsTargetList;\n getAllChiplets(l_mcsTargetList, TYPE_MCS);\n\n \/\/ Iterate over all MCS, calling mss_eff_config and mss_eff_config_thermal\n for (const auto & l_mcs_target : l_mcsTargetList)\n {\n \/\/ Get the TARGETING::Target pointer and its HUID\n uint32_t l_huid = TARGETING::get_huid(l_mcs_target);\n\n \/\/ Create a FAPI target representing the MCS\n const fapi2::Target <fapi2::TARGET_TYPE_MCS> l_fapi_mcs_target\n (l_mcs_target);\n\n \/\/ Call the mss_eff_config HWP\n TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace,\n \"p9_mss_eff_config HWP. MCS HUID %.8X\", l_huid);\n FAPI_INVOKE_HWP(l_err, p9_mss_eff_config, l_fapi_mcs_target);\n\n if (l_err)\n {\n TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace,\n \"ERROR 0x%.8X: p9_mss_eff_config HWP \", l_err->reasonCode());\n\n \/\/ Ensure istep error created and has same plid as this error\n ErrlUserDetailsTarget(l_mcs_target).addToLog(l_err);\n l_StepError.addErrorDetails(l_err);\n errlCommit(l_err, HWPF_COMP_ID);\n continue;\n }\n\n TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace,\n \"SUCCESS : p9_mss_eff_config HWP\");\n } \/\/ end membuf loop\n\n std::map<ATTR_VDDR_ID_type,TARGETING::TargetHandleList> l_domainIdGroups;\n TARGETING::TargetHandleList l_mcbistTargetList;\n getAllChiplets(l_mcbistTargetList, TYPE_MCBIST);\n\n \/\/ Iterate over all MCBIST, calling mss_eff_config_thermal\n for (const auto & l_mcbist_target : l_mcbistTargetList)\n {\n TARGETING::TargetHandleList l_mcsChildren;\n getChildChiplets(l_mcsChildren,l_mcbist_target, TARGETING::TYPE_MCS);\n\n ATTR_VDDR_ID_type l_vddr_id = l_mcbist_target->getAttr<ATTR_VDDR_ID>();\n if(l_domainIdGroups.find(l_vddr_id) == l_domainIdGroups.end())\n {\n std::pair<ATTR_VDDR_ID_type, TARGETING::TargetHandleList> tuple(l_vddr_id, l_mcsChildren);\n l_domainIdGroups.insert(tuple);\n }\n else\n {\n l_domainIdGroups[l_vddr_id].insert(l_domainIdGroups[l_vddr_id].end(), l_mcsChildren.begin(), l_mcsChildren.end());\n }\n }\n\n for (auto & l_tuple : l_domainIdGroups)\n {\n std::vector<fapi2::Target<fapi2::TARGET_TYPE_MCS>> l_fapi_mcs_targs;\n for(const auto & l_mcs_target : l_tuple.second)\n {\n \/\/ Create a FAPI target representing the MCS\n const fapi2::Target <fapi2::TARGET_TYPE_MCS> l_fapi_mcs_target\n (l_mcs_target);\n l_fapi_mcs_targs.push_back(l_fapi_mcs_target);\n }\n \/\/ Call the mss_eff_config_thermal HWP\n TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace,\n \"p9_mss_eff_config_thermal HWP. \");\n FAPI_INVOKE_HWP(l_err, p9_mss_eff_config_thermal,l_fapi_mcs_targs);\n\n if (l_err)\n {\n TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace,\n \"ERROR 0x%.8X: p9_mss_eff_config_thermal HWP \",\n l_err->reasonCode());\n\n \/\/ Ensure istep error created and has same plid as this error\n l_StepError.addErrorDetails(l_err);\n errlCommit(l_err, HWPF_COMP_ID);\n }\n else\n {\n TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace,\n \"SUCCESS : p9_mss_eff_config_thermal HWP\");\n }\n }\n\n\n if (l_StepError.isNull())\n {\n \/\/ Stack the memory on each chip\n l_err = call_mss_eff_grouping(l_StepError);\n\n \/\/ TODO RTC: 144076\n \/\/if(!l_err) \/\/Cumulus only\n \/\/{\n \/\/ l_err = call_mss_eff_mb_interleave();\n \/\/}\n\n if (l_err)\n {\n \/\/ Ensure istep error created and has same plid as this error\n l_StepError.addErrorDetails( l_err );\n errlCommit( l_err, HWPF_COMP_ID );\n }\n }\n\n TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace, \"call_mss_eff_config exit\" );\n return l_StepError.getErrorHandle();\n}\n}; \/\/ end namespace\n<|endoftext|>"} {"text":"<commit_before>\/* IBM_PROLOG_BEGIN_TAG *\/\n\/* This is an automatically generated prolog. *\/\n\/* *\/\n\/* $Source: src\/usr\/isteps\/istep08\/call_host_setup_sbe.C $ *\/\n\/* *\/\n\/* OpenPOWER HostBoot Project *\/\n\/* *\/\n\/* Contributors Listed Below - COPYRIGHT 2015,2016 *\/\n\/* [+] International Business Machines Corp. *\/\n\/* *\/\n\/* *\/\n\/* Licensed under the Apache License, Version 2.0 (the \"License\"); *\/\n\/* you may not use this file except in compliance with the License. *\/\n\/* You may obtain a copy of the License at *\/\n\/* *\/\n\/* http:\/\/www.apache.org\/licenses\/LICENSE-2.0 *\/\n\/* *\/\n\/* Unless required by applicable law or agreed to in writing, software *\/\n\/* distributed under the License is distributed on an \"AS IS\" BASIS, *\/\n\/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or *\/\n\/* implied. See the License for the specific language governing *\/\n\/* permissions and limitations under the License. *\/\n\/* *\/\n\/* IBM_PROLOG_END_TAG *\/\n\/**\n * @file call_host_setup_sbe.C\n *\n * Support file for IStep: slave_sbe\n * Slave SBE\n *\n * HWP_IGNORE_VERSION_CHECK\n *\/\n\n\/******************************************************************************\/\n\/\/ Includes\n\/******************************************************************************\/\n#include <stdint.h>\n#include <trace\/interface.H>\n#include <initservice\/taskargs.H>\n#include <errl\/errlentry.H>\n#include <initservice\/isteps_trace.H>\n#include <initservice\/initserviceif.H>\n#include <initservice\/initsvcreasoncodes.H>\n#include <sys\/time.h>\n#include <devicefw\/userif.H>\n#include <i2c\/i2cif.H>\n\n\/\/ targeting support\n#include <targeting\/common\/commontargeting.H>\n#include <targeting\/common\/utilFilter.H>\n#include <targeting\/namedtarget.H>\n#include <targeting\/attrsync.H>\n\n#include <fapi2\/target.H>\n#include <fapi2\/plat_hwp_invoker.H>\n\n#include <errl\/errlmanager.H>\n\n#include <isteps\/hwpisteperror.H>\n\n#include <errl\/errludtarget.H>\n\n#include <p9_set_fsi_gp_shadow.H>\n\nusing namespace ISTEP;\nusing namespace ISTEP_ERROR;\nusing namespace ERRORLOG;\nusing namespace TARGETING;\n\nnamespace ISTEP_08\n{\n\n\/\/******************************************************************************\n\/\/ call_host_setup_sbe()\n\/\/******************************************************************************\nvoid* call_host_setup_sbe(void *io_pArgs)\n{\n errlHndl_t l_errl = NULL;\n IStepError l_stepError;\n TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace,\n \"call_host_setup_sbe entry\" );\n\n \/\/\n \/\/ get a list of all the procs in the system\n \/\/\n TARGETING::TargetHandleList l_cpuTargetList;\n getAllChips(l_cpuTargetList, TYPE_PROC);\n\n \/\/\n \/\/ identify master processor target\n \/\/\n TARGETING::Target* l_pMasterProcTarget = NULL;\n TARGETING::targetService().masterProcChipTargetHandle(l_pMasterProcTarget);\n\n for (const auto & l_procChip: l_cpuTargetList)\n {\n \/\/ call only on non-master processor chips\n if (l_procChip != l_pMasterProcTarget)\n {\n const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>\n l_fapi2_proc_target (l_procChip);\n\n \/\/call p9_set_fsi_gp_shadow on non-master processors\n TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace,\n \"Running p9_set_fsi_gp_shadow HWP on processor target %.8X\",\n TARGETING::get_huid(l_procChip) );\n\n FAPI_INVOKE_HWP(l_errl,p9_set_fsi_gp_shadow, l_fapi2_proc_target);\n if(l_errl)\n {\n l_stepError.addErrorDetails(l_errl);\n TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace,\n \"ERROR : call p9_set_fsi_gp_shadow, PLID=0x%x\",\n l_errl->plid() );\n errlCommit(l_errl, HWPF_COMP_ID);\n }\n }\n\n } \/\/ end of cycling through all processor chips\n\n TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace,\n \"call_host_setup_sbe exit\" );\n return l_stepError.getErrorHandle();\n}\n};\n<commit_msg>Temp workaround to setup slave sbe scratch registers<commit_after>\/* IBM_PROLOG_BEGIN_TAG *\/\n\/* This is an automatically generated prolog. *\/\n\/* *\/\n\/* $Source: src\/usr\/isteps\/istep08\/call_host_setup_sbe.C $ *\/\n\/* *\/\n\/* OpenPOWER HostBoot Project *\/\n\/* *\/\n\/* Contributors Listed Below - COPYRIGHT 2015,2016 *\/\n\/* [+] International Business Machines Corp. *\/\n\/* *\/\n\/* *\/\n\/* Licensed under the Apache License, Version 2.0 (the \"License\"); *\/\n\/* you may not use this file except in compliance with the License. *\/\n\/* You may obtain a copy of the License at *\/\n\/* *\/\n\/* http:\/\/www.apache.org\/licenses\/LICENSE-2.0 *\/\n\/* *\/\n\/* Unless required by applicable law or agreed to in writing, software *\/\n\/* distributed under the License is distributed on an \"AS IS\" BASIS, *\/\n\/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or *\/\n\/* implied. See the License for the specific language governing *\/\n\/* permissions and limitations under the License. *\/\n\/* *\/\n\/* IBM_PROLOG_END_TAG *\/\n\/**\n * @file call_host_setup_sbe.C\n *\n * Support file for IStep: slave_sbe\n * Slave SBE\n *\n * HWP_IGNORE_VERSION_CHECK\n *\/\n\n\/******************************************************************************\/\n\/\/ Includes\n\/******************************************************************************\/\n#include <stdint.h>\n#include <trace\/interface.H>\n#include <initservice\/taskargs.H>\n#include <errl\/errlentry.H>\n#include <initservice\/isteps_trace.H>\n#include <initservice\/initserviceif.H>\n#include <initservice\/initsvcreasoncodes.H>\n#include <sys\/time.h>\n#include <devicefw\/userif.H>\n#include <i2c\/i2cif.H>\n\n\/\/ targeting support\n#include <targeting\/common\/commontargeting.H>\n#include <targeting\/common\/utilFilter.H>\n#include <targeting\/namedtarget.H>\n#include <targeting\/attrsync.H>\n\n#include <fapi2\/target.H>\n#include <fapi2\/plat_hwp_invoker.H>\n\n#include <errl\/errlmanager.H>\n\n#include <isteps\/hwpisteperror.H>\n\n#include <errl\/errludtarget.H>\n\n#include <p9_set_fsi_gp_shadow.H>\n\nusing namespace ISTEP;\nusing namespace ISTEP_ERROR;\nusing namespace ERRORLOG;\nusing namespace TARGETING;\n\nnamespace ISTEP_08\n{\n\n\/\/******************************************************************************\n\/\/ call_host_setup_sbe()\n\/\/******************************************************************************\nvoid* call_host_setup_sbe(void *io_pArgs)\n{\n errlHndl_t l_errl = NULL;\n IStepError l_stepError;\n TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace,\n \"call_host_setup_sbe entry\" );\n\n \/\/\n \/\/ get a list of all the procs in the system\n \/\/\n TARGETING::TargetHandleList l_cpuTargetList;\n getAllChips(l_cpuTargetList, TYPE_PROC);\n\n \/\/\n \/\/ identify master processor target\n \/\/\n TARGETING::Target* l_pMasterProcTarget = NULL;\n TARGETING::targetService().masterProcChipTargetHandle(l_pMasterProcTarget);\n\n for (const auto & l_procChip: l_cpuTargetList)\n {\n \/\/ call only on non-master processor chips\n if (l_procChip != l_pMasterProcTarget)\n {\n const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>\n l_fapi2_proc_target (l_procChip);\n\n \/\/call p9_set_fsi_gp_shadow on non-master processors\n TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace,\n \"Running p9_set_fsi_gp_shadow HWP on processor target %.8X\",\n TARGETING::get_huid(l_procChip) );\n\n FAPI_INVOKE_HWP(l_errl,p9_set_fsi_gp_shadow, l_fapi2_proc_target);\n if(l_errl)\n {\n l_stepError.addErrorDetails(l_errl);\n TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace,\n \"ERROR : call p9_set_fsi_gp_shadow, PLID=0x%x\",\n l_errl->plid() );\n errlCommit(l_errl, HWPF_COMP_ID);\n }\n\n \/\/ TODO-RTC:152203 BEGIN\n \/\/ Configure slave sbe to be in slave SBE, continuous IPL mode\n \/\/ All this code gets deleted once host_slave_sbe_config.C is in\n TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace,\n \"WORKAROUND:RTC:152203 - Setup slave sbe scratch \"\n \"registers for proc 0x%.8X\",\n TARGETING::get_huid(l_procChip));\n\n \/\/ Bits 7-15 are address portion\n const uint32_t CFAM_ADDRESS_MASK = 0x1FF;\n\n \/\/ Bits 0-6 are engine offset\n const uint32_t CFAM_ENGINE_OFFSET = 0xFE00;\n\n\n uint64_t l_addr = 0x283A;\n l_addr = ((l_addr & CFAM_ADDRESS_MASK) << 2) |\n (l_addr & CFAM_ENGINE_OFFSET);\n uint32_t l_data = 0x10000000;\n size_t l_size = sizeof(uint32_t);\n l_errl = deviceWrite(l_procChip,\n &l_data,\n l_size,\n DEVICE_FSI_ADDRESS(l_addr));\n if (l_errl)\n {\n TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace,\n ERR_MRK\"WORKAROUND:RTC:152203 - FAIL to setup \"\n \"slave sbe scratch registers for proc 0x%.8X \"\n \"scratch 0x3A\",\n TARGETING::get_huid(l_procChip));\n delete l_errl;\n l_errl = NULL;\n }\n\n l_addr = 0x283D;\n l_addr = ((l_addr & CFAM_ADDRESS_MASK) << 2) |\n (l_addr & CFAM_ENGINE_OFFSET);\n l_data = 0x00000080;\n l_errl = deviceWrite(l_procChip,\n &l_data,\n l_size,\n DEVICE_FSI_ADDRESS(l_addr));\n if (l_errl)\n {\n TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace,\n ERR_MRK\"WORKAROUND:RTC:152203 - FAIL to setup \"\n \"slave sbe scratch registers for proc 0x%.8X \"\n \"scratch 0x3D\",\n TARGETING::get_huid(l_procChip));\n delete l_errl;\n l_errl = NULL;\n }\n l_addr = 0x283F;\n l_addr = ((l_addr & CFAM_ADDRESS_MASK) << 2) |\n (l_addr & CFAM_ENGINE_OFFSET);\n l_data = 0x24000000;\n l_errl = deviceWrite(l_procChip,\n &l_data,\n l_size,\n DEVICE_FSI_ADDRESS(l_addr));\n if (l_errl)\n {\n TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace,\n ERR_MRK\"WORKAROUND:RTC:152203 - FAIL to setup \"\n \"slave sbe scratch \"\n \"registers for proc 0x%.8X scratch 0x3F\",\n TARGETING::get_huid(l_procChip));\n delete l_errl;\n l_errl = NULL;\n }\n \/\/ TODO-RTC:152203 END\n }\n\n } \/\/ end of cycling through all processor chips\n\n TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace,\n \"call_host_setup_sbe exit\" );\n return l_stepError.getErrorHandle();\n}\n};\n<|endoftext|>"} {"text":"<commit_before>\/\/===-- X86JITInfo.cpp - Implement the JIT interfaces for the X86 target --===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file was developed by the LLVM research group and is distributed under\n\/\/ the University of Illinois Open Source License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This file implements the JIT interfaces for the X86 target.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#define DEBUG_TYPE \"jit\"\n#include \"X86JITInfo.h\"\n#include \"X86Relocations.h\"\n#include \"llvm\/CodeGen\/MachineCodeEmitter.h\"\n#include \"llvm\/Config\/alloca.h\"\nusing namespace llvm;\n\nvoid X86JITInfo::replaceMachineCodeForFunction(void *Old, void *New) {\n unsigned char *OldByte = (unsigned char *)Old;\n *OldByte++ = 0xE9; \/\/ Emit JMP opcode.\n unsigned *OldWord = (unsigned *)OldByte;\n unsigned NewAddr = (intptr_t)New;\n unsigned OldAddr = (intptr_t)OldWord;\n *OldWord = NewAddr - OldAddr - 4; \/\/ Emit PC-relative addr of New code.\n}\n\n\n#ifdef _MSC_VER\n#pragma optimize(\"y\", off)\n#endif\n\n\/\/\/ JITCompilerFunction - This contains the address of the JIT function used to\n\/\/\/ compile a function lazily.\nstatic TargetJITInfo::JITCompilerFn JITCompilerFunction;\n\n\/\/ Provide a wrapper for X86CompilationCallback2 that saves non-traditional\n\/\/ callee saved registers, for the fastcc calling convention.\nextern \"C\" void X86CompilationCallback(void);\n\n#if defined(__i386__) || defined(i386)\n#ifndef _MSC_VER\nasm(\n \".text\\n\"\n \".align 8\\n\"\n \".globl X86CompilationCallback\\n\"\n\"X86CompilationCallback:\\n\"\n \"pushl %ebp\\n\"\n \"movl %esp, %ebp\\n\" \/\/ Standard prologue\n \"pushl %eax\\n\"\n \"pushl %edx\\n\" \/\/ save EAX\/EDX\n \"call X86CompilationCallback2\\n\"\n \"popl %edx\\n\"\n \"popl %eax\\n\"\n \"popl %ebp\\n\"\n \"ret\\n\");\n#else\n\/\/ FIXME: implement this for VC++\n#endif\n\n#else\n\/\/ Not an i386 host\nvoid X86CompilationCallback() {\n assert(0 && \"This is not a X86, you can't execute this!\");\n abort();\n}\n#endif\n\n\/\/\/ X86CompilationCallback - This is the target-specific function invoked by the\n\/\/\/ function stub when we did not know the real target of a call. This function\n\/\/\/ must locate the start of the stub or call site and pass it into the JIT\n\/\/\/ compiler function.\nextern \"C\" void X86CompilationCallback2() {\n#ifdef _MSC_VER\n \/\/ FIXME: This needs to go up one more level!\n unsigned *StackPtr, RetAddr;\n __asm mov StackPtr, ebp;\n __asm mov eax, DWORD PTR [ebp + 4];\n __asm mov RetAddr, eax;\n#else\n unsigned *StackPtr = (unsigned*)__builtin_frame_address(1);\n unsigned RetAddr = (unsigned)(intptr_t)__builtin_return_address(1);\n\n \/\/ NOTE: __builtin_frame_address doesn't work if frame pointer elimination has\n \/\/ been performed. Having a variable sized alloca disables frame pointer\n \/\/ elimination currently, even if it's dead. This is a gross hack.\n alloca(10+(RetAddr >> 31));\n\n#endif\n assert(StackPtr[1] == RetAddr &&\n \"Could not find return address on the stack!\");\n\n \/\/ It's a stub if there is an interrupt marker after the call.\n bool isStub = ((unsigned char*)(intptr_t)RetAddr)[0] == 0xCD;\n\n \/\/ The call instruction should have pushed the return value onto the stack...\n RetAddr -= 4; \/\/ Backtrack to the reference itself...\n\n#if 0\n DEBUG(std::cerr << \"In callback! Addr=\" << (void*)RetAddr\n << \" ESP=\" << (void*)StackPtr\n << \": Resolving call to function: \"\n << TheVM->getFunctionReferencedName((void*)RetAddr) << \"\\n\");\n#endif\n\n \/\/ Sanity check to make sure this really is a call instruction.\n assert(((unsigned char*)(intptr_t)RetAddr)[-1] == 0xE8 &&\"Not a call instr!\");\n\n unsigned NewVal = (intptr_t)JITCompilerFunction((void*)(intptr_t)RetAddr);\n\n \/\/ Rewrite the call target... so that we don't end up here every time we\n \/\/ execute the call.\n *(unsigned*)(intptr_t)RetAddr = NewVal-RetAddr-4;\n\n if (isStub) {\n \/\/ If this is a stub, rewrite the call into an unconditional branch\n \/\/ instruction so that two return addresses are not pushed onto the stack\n \/\/ when the requested function finally gets called. This also makes the\n \/\/ 0xCD byte (interrupt) dead, so the marker doesn't effect anything.\n ((unsigned char*)(intptr_t)RetAddr)[-1] = 0xE9;\n }\n\n \/\/ Change the return address to reexecute the call instruction...\n StackPtr[1] -= 5;\n}\n\n#ifdef _MSC_VER\n#pragma optimize( \"\", on )\n#endif\n\nTargetJITInfo::LazyResolverFn\nX86JITInfo::getLazyResolverFunction(JITCompilerFn F) {\n JITCompilerFunction = F;\n return X86CompilationCallback;\n}\n\nvoid *X86JITInfo::emitFunctionStub(void *Fn, MachineCodeEmitter &MCE) {\n if (Fn != X86CompilationCallback) {\n MCE.startFunctionStub(5);\n MCE.emitByte(0xE9);\n MCE.emitWord((intptr_t)Fn-MCE.getCurrentPCValue()-4);\n return MCE.finishFunctionStub(0);\n }\n\n MCE.startFunctionStub(6);\n MCE.emitByte(0xE8); \/\/ Call with 32 bit pc-rel destination...\n\n MCE.emitWord((intptr_t)Fn-MCE.getCurrentPCValue()-4);\n\n MCE.emitByte(0xCD); \/\/ Interrupt - Just a marker identifying the stub!\n return MCE.finishFunctionStub(0);\n}\n\n\/\/\/ relocate - Before the JIT can run a block of code that has been emitted,\n\/\/\/ it must rewrite the code to contain the actual addresses of any\n\/\/\/ referenced global symbols.\nvoid X86JITInfo::relocate(void *Function, MachineRelocation *MR,\n unsigned NumRelocs) {\n for (unsigned i = 0; i != NumRelocs; ++i, ++MR) {\n void *RelocPos = (char*)Function + MR->getMachineCodeOffset();\n intptr_t ResultPtr = (intptr_t)MR->getResultPointer();\n switch ((X86::RelocationType)MR->getRelocationType()) {\n case X86::reloc_pcrel_word:\n \/\/ PC relative relocation, add the relocated value to the value already in\n \/\/ memory, after we adjust it for where the PC is.\n ResultPtr = ResultPtr-(intptr_t)RelocPos-4;\n *((intptr_t*)RelocPos) += ResultPtr;\n break;\n case X86::reloc_absolute_word:\n \/\/ Absolute relocation, just add the relocated value to the value already\n \/\/ in memory.\n *((intptr_t*)RelocPos) += ResultPtr;\n break;\n }\n }\n}\n<commit_msg>Fix tail call support in VC++ builds<commit_after>\/\/===-- X86JITInfo.cpp - Implement the JIT interfaces for the X86 target --===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file was developed by the LLVM research group and is distributed under\n\/\/ the University of Illinois Open Source License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This file implements the JIT interfaces for the X86 target.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#define DEBUG_TYPE \"jit\"\n#include \"X86JITInfo.h\"\n#include \"X86Relocations.h\"\n#include \"llvm\/CodeGen\/MachineCodeEmitter.h\"\n#include \"llvm\/Config\/alloca.h\"\nusing namespace llvm;\n\nvoid X86JITInfo::replaceMachineCodeForFunction(void *Old, void *New) {\n unsigned char *OldByte = (unsigned char *)Old;\n *OldByte++ = 0xE9; \/\/ Emit JMP opcode.\n unsigned *OldWord = (unsigned *)OldByte;\n unsigned NewAddr = (intptr_t)New;\n unsigned OldAddr = (intptr_t)OldWord;\n *OldWord = NewAddr - OldAddr - 4; \/\/ Emit PC-relative addr of New code.\n}\n\n\n\/\/\/ JITCompilerFunction - This contains the address of the JIT function used to\n\/\/\/ compile a function lazily.\nstatic TargetJITInfo::JITCompilerFn JITCompilerFunction;\n\n\/\/ Provide a wrapper for X86CompilationCallback2 that saves non-traditional\n\/\/ callee saved registers, for the fastcc calling convention.\nextern \"C\" {\n#if defined(__i386__) || defined(i386) || defined(_M_IX86)\n#ifndef _MSC_VER\n void X86CompilationCallback(void);\n asm(\n \".text\\n\"\n \".align 8\\n\"\n \".globl X86CompilationCallback\\n\"\n \"X86CompilationCallback:\\n\"\n \"pushl %ebp\\n\"\n \"movl %esp, %ebp\\n\" \/\/ Standard prologue\n \"pushl %eax\\n\"\n \"pushl %edx\\n\" \/\/ save EAX\/EDX\n \"call X86CompilationCallback2\\n\"\n \"popl %edx\\n\"\n \"popl %eax\\n\"\n \"popl %ebp\\n\"\n \"ret\\n\");\n#else\n extern \"C\" void *_AddressOfReturnAddress(void);\n #pragma intrinsic(_AddressOfReturnAddress)\n\n void X86CompilationCallback2(void);\n\n _declspec(naked) void X86CompilationCallback(void) {\n __asm {\n push eax\n push edx\n call X86CompilationCallback2\n pop edx\n pop eax\n ret\n }\n }\n#endif\n\n#else\n \/\/ Not an i386 host\n void X86CompilationCallback() {\n assert(0 && \"This is not a X86, you can't execute this!\");\n abort();\n }\n#endif\n}\n\n\/\/\/ X86CompilationCallback - This is the target-specific function invoked by the\n\/\/\/ function stub when we did not know the real target of a call. This function\n\/\/\/ must locate the start of the stub or call site and pass it into the JIT\n\/\/\/ compiler function.\nextern \"C\" void X86CompilationCallback2() {\n#ifdef _MSC_VER\n assert(sizeof(size_t) == 4); \/\/ FIXME: handle Win64\n unsigned *RetAddrLoc = (unsigned *)_AddressOfReturnAddress();\n RetAddrLoc += 3; \/\/ skip over ret addr, edx, eax\n unsigned RetAddr = *RetAddrLoc;\n#else\n unsigned *StackPtr = (unsigned*)__builtin_frame_address(1);\n unsigned RetAddr = (unsigned)(intptr_t)__builtin_return_address(1);\n unsigned *RetAddrLoc = &StackPtr[1];\n\n \/\/ NOTE: __builtin_frame_address doesn't work if frame pointer elimination has\n \/\/ been performed. Having a variable sized alloca disables frame pointer\n \/\/ elimination currently, even if it's dead. This is a gross hack.\n alloca(10+(RetAddr >> 31));\n\n#endif\n assert(*RetAddrLoc == RetAddr &&\n \"Could not find return address on the stack!\");\n\n \/\/ It's a stub if there is an interrupt marker after the call.\n bool isStub = ((unsigned char*)(intptr_t)RetAddr)[0] == 0xCD;\n\n \/\/ The call instruction should have pushed the return value onto the stack...\n RetAddr -= 4; \/\/ Backtrack to the reference itself...\n\n#if 0\n DEBUG(std::cerr << \"In callback! Addr=\" << (void*)RetAddr\n << \" ESP=\" << (void*)StackPtr\n << \": Resolving call to function: \"\n << TheVM->getFunctionReferencedName((void*)RetAddr) << \"\\n\");\n#endif\n\n \/\/ Sanity check to make sure this really is a call instruction.\n assert(((unsigned char*)(intptr_t)RetAddr)[-1] == 0xE8 &&\"Not a call instr!\");\n\n unsigned NewVal = (intptr_t)JITCompilerFunction((void*)(intptr_t)RetAddr);\n\n \/\/ Rewrite the call target... so that we don't end up here every time we\n \/\/ execute the call.\n *(unsigned*)(intptr_t)RetAddr = NewVal-RetAddr-4;\n\n if (isStub) {\n \/\/ If this is a stub, rewrite the call into an unconditional branch\n \/\/ instruction so that two return addresses are not pushed onto the stack\n \/\/ when the requested function finally gets called. This also makes the\n \/\/ 0xCD byte (interrupt) dead, so the marker doesn't effect anything.\n ((unsigned char*)(intptr_t)RetAddr)[-1] = 0xE9;\n }\n\n \/\/ Change the return address to reexecute the call instruction...\n *RetAddrLoc -= 5;\n}\n\nTargetJITInfo::LazyResolverFn\nX86JITInfo::getLazyResolverFunction(JITCompilerFn F) {\n JITCompilerFunction = F;\n return X86CompilationCallback;\n}\n\nvoid *X86JITInfo::emitFunctionStub(void *Fn, MachineCodeEmitter &MCE) {\n if (Fn != X86CompilationCallback) {\n MCE.startFunctionStub(5);\n MCE.emitByte(0xE9);\n MCE.emitWord((intptr_t)Fn-MCE.getCurrentPCValue()-4);\n return MCE.finishFunctionStub(0);\n }\n\n MCE.startFunctionStub(6);\n MCE.emitByte(0xE8); \/\/ Call with 32 bit pc-rel destination...\n\n MCE.emitWord((intptr_t)Fn-MCE.getCurrentPCValue()-4);\n\n MCE.emitByte(0xCD); \/\/ Interrupt - Just a marker identifying the stub!\n return MCE.finishFunctionStub(0);\n}\n\n\/\/\/ relocate - Before the JIT can run a block of code that has been emitted,\n\/\/\/ it must rewrite the code to contain the actual addresses of any\n\/\/\/ referenced global symbols.\nvoid X86JITInfo::relocate(void *Function, MachineRelocation *MR,\n unsigned NumRelocs) {\n for (unsigned i = 0; i != NumRelocs; ++i, ++MR) {\n void *RelocPos = (char*)Function + MR->getMachineCodeOffset();\n intptr_t ResultPtr = (intptr_t)MR->getResultPointer();\n switch ((X86::RelocationType)MR->getRelocationType()) {\n case X86::reloc_pcrel_word:\n \/\/ PC relative relocation, add the relocated value to the value already in\n \/\/ memory, after we adjust it for where the PC is.\n ResultPtr = ResultPtr-(intptr_t)RelocPos-4;\n *((intptr_t*)RelocPos) += ResultPtr;\n break;\n case X86::reloc_absolute_word:\n \/\/ Absolute relocation, just add the relocated value to the value already\n \/\/ in memory.\n *((intptr_t*)RelocPos) += ResultPtr;\n break;\n }\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/* ************************************************************************** *\/\n\/* *\/\n\/* *\/\n\/* VertexArray.hpp oooooo oooooo *\/\n\/* oooooooooo oooooooooo *\/\n\/* o%%%%%o *\/\n\/* %:::::% *\/\n\/* %:::::::% *\/\n\/* This file is part of the %:::::% *\/\n\/* Lums library. %%%%% *\/\n\/* *\/\n\/* ************************************************************************** *\/\n\n#ifndef LUMS_VERTEX_ARRAY_HPP\n#define LUMS_VERTEX_ARRAY_HPP\n\n#include <type_traits>\n#include <Lums\/GL.hpp>\n\nnamespace lm\n{\n\tenum class Vertex\n\t{\n\t\tColor,\n\t\tTexture\n\t};\n\n\tnamespace internal\n\t{\n\t\ttemplate <Vertex Base, Vertex...>\n\t\tstruct _VertexOfType\n\t\t{\n\t\t\tenum { value = false };\n\t\t};\n\n\t\ttemplate <Vertex Base, Vertex Head, Vertex... Queue>\n\t\tstruct _VertexOfType<Base, Head, Queue...>\n\t\t{\n\t\t\tenum { value = (Base == Head) ? true : _VertexOfType<Base, Queue...>::value };\n\t\t};\n\n\t\ttemplate <Vertex...>\n\t\tstruct _VertexLen\n\t\t{\n\t\t\tenum { value = 2 };\n\t\t};\n\n\t\ttemplate <Vertex Head, Vertex... Queue>\n\t\tstruct _VertexLen<Head, Queue...>\n\t\t{\n\n\t\t};\n\n\t\ttemplate <Vertex... Queue>\n\t\tstruct _VertexLen<Vertex::Color, Queue...>\n\t\t{\n\t\t\tenum { value = 3 + _VertexLen<Queue...>::value };\n\t\t};\n\n\t\ttemplate <Vertex... Queue>\n\t\tstruct _VertexLen<Vertex::Texture, Queue...>\n\t\t{\n\t\t\tenum { value = 2 + _VertexLen<Queue...>::value };\n\t\t};\n\n\t\ttemplate <size_t N, Vertex Base, Vertex...>\n\t\tstruct _VertexOffsetHelper\n\t\t{\n enum { value = 0 };\n\t\t};\n\n\t\ttemplate <size_t N, Vertex Base, Vertex Head, Vertex... Queue>\n\t\tstruct _VertexOffsetHelper<N, Base, Head, Queue...>\n\t\t{\n\t\t\tenum { value = (Base == Head) ? N : _VertexOffsetHelper<N + (_VertexLen<Head>::value - 2), Base, Queue...>::value };\n\t\t};\n\n\t\ttemplate <Vertex Base, Vertex Head, Vertex... Queue>\n\t\tstruct _VertexOffset\n\t\t{\n\t\t\tenum { value = _VertexOffsetHelper<2, Base, Head, Queue...>::value };\n\t\t};\n\n\t\ttemplate <Vertex Head, Vertex... Opt>\n\t\tstruct _VertexPush\n\t\t{\n\t\t\ttemplate <Vertex V = Head, typename... T>\n\t\t\tstatic typename std::enable_if<V == Vertex::Color>::type\n\t\t\tapply(float* buffer, float r, float g, float b, T... Args)\n\t\t\t{\n\t\t\t\tbuffer[0] = r;\n\t\t\t\tbuffer[1] = g;\n\t\t\t\tbuffer[2] = b;\n\t\t\t\tforward<sizeof...(Opt)>(buffer + 3, Args...);\n\t\t\t}\n\n\t\t\ttemplate <Vertex V = Head, typename... T>\n\t\t\tstatic typename std::enable_if<V == Vertex::Texture>::type\n\t\t\tapply(float* buffer, float x, float y, T... Args)\n\t\t\t{\n\t\t\t\tbuffer[0] = x;\n\t\t\t\tbuffer[1] = y;\n\t\t\t\tforward<sizeof...(Opt)>(buffer + 2, Args...);\n\t\t\t}\n\n\t\t\ttemplate <int N, typename... T>\n\t\t\tstatic typename std::enable_if<N != 0>::type\n\t\t\tforward(float *buffer, T... Args)\n\t\t\t{\n\t\t\t\t_VertexPush<Opt...>::apply(buffer, Args...);\n\t\t\t}\n\n\t\t\ttemplate <int N, typename... T>\n\t\t\tstatic typename std::enable_if<N == 0>::type\n\t\t\tforward(float* buffer)\n\t\t\t{\n\n\t\t\t}\n\t\t};\n\t}\n\n\ttemplate <size_t N, Vertex... Options>\n\tclass VertexArray\n\t{\n\tpublic:\n\t\tVertexArray()\n\t\t: _count(0)\n , _vertices(0)\n\t\t{\n \n\t\t}\n\n\t\tvoid\n\t\tclear()\n\t\t{\n\t\t\t_count = 0;\n _vertices = 0;\n\t\t}\n\n\t\ttemplate <typename ...T>\n\t\tvoid\n\t\tpush(float x, float y, T ...Args)\n\t\t{\n\t\t\t_buffer[_count] = x;\n\t\t\t_buffer[_count + 1] = y;\n\t\t\tforward<sizeof...(Options)>(_buffer + _count + 2, Args...);\n\t\t\t_count += internal::_VertexLen<Options...>::value;\n _vertices++;\n\t\t}\n\n\t\ttemplate <int Len, typename ...T>\n\t\ttypename std::enable_if<Len != 0>::type\n\t\tforward(float* buffer, T... Args)\n\t\t{\n\t\t\tinternal::_VertexPush<Options...>::apply(buffer, Args...);\n\t\t}\n\n\t\ttemplate <int Len, typename ...T>\n\t\ttypename std::enable_if<Len == 0>::type\n\t\tforward(float* buffer)\n\t\t{\n\n\t\t}\n\n\t\tvoid\n\t\tdraw(GLenum mode) const\n\t\t{\n\t\t\tglEnableClientState(GL_VERTEX_ARRAY);\n glVertexPointer(2, GL_FLOAT, internal::_VertexLen<Options...>::value * sizeof(float), _buffer);\n\t\t\tenableColor<Options...>();\n\t\t\tenableTexture<Options...>();\n glDrawArrays(mode, 0, _vertices);\n\t\t\tdisableTexture<Options...>();\n\t\t\tdisableColor<Options...>();\n\t\t\tglDisableClientState(GL_VERTEX_ARRAY);\n\t\t}\n\n\tprotected:\n\t\tfloat \t_buffer[N * internal::_VertexLen<Options...>::value];\n\t\tsize_t\t_count;\n size_t _vertices;\n\n\tprivate:\n\t\ttemplate <Vertex... V>\n\t\ttypename std::enable_if<internal::_VertexOfType<Vertex::Color, V...>::value == true>::type\n\t\tenableColor() const\n\t\t{\n\t\t\tglEnableClientState(GL_COLOR_ARRAY);\n glColorPointer(\n 3,\n GL_FLOAT,\n internal::_VertexLen<Options...>::value * sizeof(float),\n _buffer + internal::_VertexOffset<Vertex::Color, Options...>::value\n );\n\t\t}\n\n\t\ttemplate <Vertex... V>\n\t\ttypename std::enable_if<internal::_VertexOfType<Vertex::Color, V...>::value == false>::type\n\t\tenableColor() const\n\t\t{\n\t\t\n\t\t}\n\n\t\ttemplate <Vertex... V>\n\t\ttypename std::enable_if<internal::_VertexOfType<Vertex::Texture, V...>::value == true>::type\n\t\tenableTexture() const\n\t\t{\n\t\t\tglEnableClientState(GL_TEXTURE_COORD_ARRAY);\n\t\t\tglEnable(GL_TEXTURE_2D);\n glTexCoordPointer(\n 2,\n GL_FLOAT,\n internal::_VertexLen<Options...>::value * sizeof(float),\n _buffer + internal::_VertexOffset<Vertex::Texture, Options...>::value\n );\n\t\t}\n\n\t\ttemplate <Vertex... V>\n\t\ttypename std::enable_if<internal::_VertexOfType<Vertex::Texture, V...>::value == false>::type\n\t\tenableTexture() const\n\t\t{\n\t\t\tglDisable(GL_TEXTURE_2D);\n\t\t}\n\n\t\ttemplate <Vertex... V>\n\t\ttypename std::enable_if<internal::_VertexOfType<Vertex::Color, V...>::value == true>::type\n\t\tdisableColor() const\n\t\t{\n\t\t\tglDisableClientState(GL_COLOR_ARRAY);\n\t\t}\n\n\t\ttemplate <Vertex... V>\n\t\ttypename std::enable_if<internal::_VertexOfType<Vertex::Color, V...>::value == false>::type\n\t\tdisableColor() const\n\t\t{\n\t\t\n\t\t}\n\n\t\ttemplate <Vertex... V>\n\t\ttypename std::enable_if<internal::_VertexOfType<Vertex::Texture, V...>::value == true>::type\n\t\tdisableTexture() const\n\t\t{\n\t\t\tglDisableClientState(GL_TEXTURE_COORD_ARRAY);\n\t\t}\n\n\t\ttemplate <Vertex... V>\n\t\ttypename std::enable_if<internal::_VertexOfType<Vertex::Texture, V...>::value == false>::type\n\t\tdisableTexture() const\n\t\t{\n\t\t\n\t\t}\n\t};\n\n\ttemplate <size_t N>\n\tusing VertexArrayc = VertexArray<N, Vertex::Color>;\n\t\n\ttemplate <size_t N>\n\tusing VertexArrayt = VertexArray<N, Vertex::Texture>;\n\t\n\ttemplate <size_t N>\n\tusing VertexArrayct = VertexArray<N, Vertex::Color, Vertex::Texture>;\n}\n\n#endif\n<commit_msg>2.9 prev<commit_after>\/* ************************************************************************** *\/\n\/* *\/\n\/* *\/\n\/* VertexArray.hpp oooooo oooooo *\/\n\/* oooooooooo oooooooooo *\/\n\/* o%%%%%o *\/\n\/* %:::::% *\/\n\/* %:::::::% *\/\n\/* This file is part of the %:::::% *\/\n\/* Lums library. %%%%% *\/\n\/* *\/\n\/* ************************************************************************** *\/\n\n#ifndef LUMS_VERTEX_ARRAY_HPP\n#define LUMS_VERTEX_ARRAY_HPP\n\n#include <type_traits>\n#include <Lums\/GL.hpp>\n#include <Lums\/Image.hpp>\n\nnamespace lm\n{\n\tenum class Vertex\n\t{\n\t\tColor,\n\t\tTexture\n\t};\n\n\tnamespace internal\n\t{\n\t\ttemplate <Vertex Base, Vertex...>\n\t\tstruct _VertexOfType\n\t\t{\n\t\t\tenum { value = false };\n\t\t};\n\n\t\ttemplate <Vertex Base, Vertex Head, Vertex... Queue>\n\t\tstruct _VertexOfType<Base, Head, Queue...>\n\t\t{\n\t\t\tenum { value = (Base == Head) ? true : _VertexOfType<Base, Queue...>::value };\n\t\t};\n\n\t\ttemplate <Vertex...>\n\t\tstruct _VertexLen\n\t\t{\n\t\t\tenum { value = 2 };\n\t\t};\n\n\t\ttemplate <Vertex Head, Vertex... Queue>\n\t\tstruct _VertexLen<Head, Queue...>\n\t\t{\n\n\t\t};\n\n\t\ttemplate <Vertex... Queue>\n\t\tstruct _VertexLen<Vertex::Color, Queue...>\n\t\t{\n\t\t\tenum { value = 3 + _VertexLen<Queue...>::value };\n\t\t};\n\n\t\ttemplate <Vertex... Queue>\n\t\tstruct _VertexLen<Vertex::Texture, Queue...>\n\t\t{\n\t\t\tenum { value = 2 + _VertexLen<Queue...>::value };\n\t\t};\n\n\t\ttemplate <size_t N, Vertex Base, Vertex...>\n\t\tstruct _VertexOffsetHelper\n\t\t{\n enum { value = 0 };\n\t\t};\n\n\t\ttemplate <size_t N, Vertex Base, Vertex Head, Vertex... Queue>\n\t\tstruct _VertexOffsetHelper<N, Base, Head, Queue...>\n\t\t{\n\t\t\tenum { value = (Base == Head) ? N : _VertexOffsetHelper<N + (_VertexLen<Head>::value - 2), Base, Queue...>::value };\n\t\t};\n\n\t\ttemplate <Vertex Base, Vertex Head, Vertex... Queue>\n\t\tstruct _VertexOffset\n\t\t{\n\t\t\tenum { value = _VertexOffsetHelper<2, Base, Head, Queue...>::value };\n\t\t};\n\n\t\ttemplate <Vertex Head, Vertex... Opt>\n\t\tstruct _VertexPush\n\t\t{\n\t\t\ttemplate <Vertex V = Head, typename... T>\n\t\t\tstatic typename std::enable_if<V == Vertex::Color>::type\n\t\t\tapply(float* buffer, float r, float g, float b, T... Args)\n\t\t\t{\n\t\t\t\tbuffer[0] = r;\n\t\t\t\tbuffer[1] = g;\n\t\t\t\tbuffer[2] = b;\n\t\t\t\tforward<sizeof...(Opt)>(buffer + 3, Args...);\n\t\t\t}\n\n\t\t\ttemplate <Vertex V = Head, typename... T>\n\t\t\tstatic typename std::enable_if<V == Vertex::Texture>::type\n\t\t\tapply(float* buffer, float x, float y, T... Args)\n\t\t\t{\n\t\t\t\tbuffer[0] = x;\n\t\t\t\tbuffer[1] = y;\n\t\t\t\tforward<sizeof...(Opt)>(buffer + 2, Args...);\n\t\t\t}\n\n\t\t\ttemplate <int N, typename... T>\n\t\t\tstatic typename std::enable_if<N != 0>::type\n\t\t\tforward(float *buffer, T... Args)\n\t\t\t{\n\t\t\t\t_VertexPush<Opt...>::apply(buffer, Args...);\n\t\t\t}\n\n\t\t\ttemplate <int N, typename... T>\n\t\t\tstatic typename std::enable_if<N == 0>::type\n\t\t\tforward(float* buffer)\n\t\t\t{\n\n\t\t\t}\n\t\t};\n\t}\n\n\ttemplate <size_t N, Vertex... Options>\n\tclass VertexArray\n\t{\n\tpublic:\n\t\tVertexArray()\n\t\t: _count(0)\n , _vertices(0)\n\t\t{\n \n\t\t}\n\n\t\tvoid\n\t\tclear()\n\t\t{\n\t\t\t_count = 0;\n _vertices = 0;\n\t\t}\n\n\t\ttemplate <typename ...T>\n\t\tvoid\n\t\tpush(float x, float y, T ...Args)\n\t\t{\n\t\t\t_buffer[_count] = x;\n\t\t\t_buffer[_count + 1] = y;\n\t\t\tforward<sizeof...(Options)>(_buffer + _count + 2, Args...);\n\t\t\t_count += internal::_VertexLen<Options...>::value;\n _vertices++;\n\t\t}\n\n\t\ttemplate <int Len, typename ...T>\n\t\ttypename std::enable_if<Len != 0>::type\n\t\tforward(float* buffer, T... Args)\n\t\t{\n\t\t\tinternal::_VertexPush<Options...>::apply(buffer, Args...);\n\t\t}\n\n\t\ttemplate <int Len, typename ...T>\n\t\ttypename std::enable_if<Len == 0>::type\n\t\tforward(float* buffer)\n\t\t{\n\n\t\t}\n\n\t\tvoid\n\t\tdraw(GLenum mode) const\n\t\t{\n\t\t\tglEnableClientState(GL_VERTEX_ARRAY);\n glVertexPointer(2, GL_FLOAT, internal::_VertexLen<Options...>::value * sizeof(float), _buffer);\n\t\t\tenableColor<Options...>();\n\t\t\tenableTexture<Options...>();\n glDrawArrays(mode, 0, _vertices);\n\t\t\tdisableTexture<Options...>();\n\t\t\tdisableColor<Options...>();\n\t\t\tglDisableClientState(GL_VERTEX_ARRAY);\n\t\t}\n\n\tprotected:\n\t\tfloat \t_buffer[N * internal::_VertexLen<Options...>::value];\n\t\tsize_t\t_count;\n size_t _vertices;\n\n\tprivate:\n\t\ttemplate <Vertex... V>\n\t\ttypename std::enable_if<internal::_VertexOfType<Vertex::Color, V...>::value == true>::type\n\t\tenableColor() const\n\t\t{\n\t\t\tglEnableClientState(GL_COLOR_ARRAY);\n glColorPointer(\n 3,\n GL_FLOAT,\n internal::_VertexLen<Options...>::value * sizeof(float),\n _buffer + internal::_VertexOffset<Vertex::Color, Options...>::value\n );\n\t\t}\n\n\t\ttemplate <Vertex... V>\n\t\ttypename std::enable_if<internal::_VertexOfType<Vertex::Color, V...>::value == false>::type\n\t\tenableColor() const\n\t\t{\n\t\t\n\t\t}\n\n\t\ttemplate <Vertex... V>\n\t\ttypename std::enable_if<internal::_VertexOfType<Vertex::Texture, V...>::value == true>::type\n\t\tenableTexture() const\n\t\t{\n\t\t\tglEnableClientState(GL_TEXTURE_COORD_ARRAY);\n glTexCoordPointer(\n 2,\n GL_FLOAT,\n internal::_VertexLen<Options...>::value * sizeof(float),\n _buffer + internal::_VertexOffset<Vertex::Texture, Options...>::value\n );\n\t\t}\n\n\t\ttemplate <Vertex... V>\n\t\ttypename std::enable_if<internal::_VertexOfType<Vertex::Texture, V...>::value == false>::type\n\t\tenableTexture() const\n\t\t{\n\t\t\tlm::Image::none().bind();\n\t\t}\n\n\t\ttemplate <Vertex... V>\n\t\ttypename std::enable_if<internal::_VertexOfType<Vertex::Color, V...>::value == true>::type\n\t\tdisableColor() const\n\t\t{\n\t\t\tglDisableClientState(GL_COLOR_ARRAY);\n\t\t}\n\n\t\ttemplate <Vertex... V>\n\t\ttypename std::enable_if<internal::_VertexOfType<Vertex::Color, V...>::value == false>::type\n\t\tdisableColor() const\n\t\t{\n\t\t\n\t\t}\n\n\t\ttemplate <Vertex... V>\n\t\ttypename std::enable_if<internal::_VertexOfType<Vertex::Texture, V...>::value == true>::type\n\t\tdisableTexture() const\n\t\t{\n\t\t\tglDisableClientState(GL_TEXTURE_COORD_ARRAY);\n\t\t}\n\n\t\ttemplate <Vertex... V>\n\t\ttypename std::enable_if<internal::_VertexOfType<Vertex::Texture, V...>::value == false>::type\n\t\tdisableTexture() const\n\t\t{\n\t\t\n\t\t}\n\t};\n\n\ttemplate <size_t N>\n\tusing VertexArrayc = VertexArray<N, Vertex::Color>;\n\t\n\ttemplate <size_t N>\n\tusing VertexArrayt = VertexArray<N, Vertex::Texture>;\n\t\n\ttemplate <size_t N>\n\tusing VertexArrayct = VertexArray<N, Vertex::Color, Vertex::Texture>;\n}\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Eos - A 3D Morphable Model fitting library written in modern C++11\/14.\n *\n * File: include\/eos\/render\/utils.hpp\n *\n * Copyright 2014, 2015 Patrik Huber\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n#pragma once\n\n#ifndef RENDER_UTILS_HPP_\n#define RENDER_UTILS_HPP_\n\n#include \"opencv2\/core\/core.hpp\"\n#include \"opencv2\/imgproc\/imgproc.hpp\"\n\nnamespace eos {\n\tnamespace render {\n\n\/**\n * Transforms a point from clip space ([-1, 1] x [-1, 1]) to\n * image (screen) coordinates, i.e. the window transform.\n * Note that the y-coordinate is flipped because the image origin\n * is top-left while in clip space top is +1 and bottom is -1.\n * No z-division is performed.\n * Note: It should rather be called from NDC to screen space?\n *\n * Exactly conforming to the OpenGL viewport transform, except that\n * we flip y at the end.\n * Qt: Origin top-left. OpenGL: bottom-left. OCV: top-left.\n *\n * @param[in] clip_coordinates A point in clip coordinates.\n * @param[in] screen_width Width of the screen or window.\n * @param[in] screen_height Height of the screen or window.\n * @return A vector with x and y coordinates transformed to screen space.\n *\/\ninline cv::Vec2f clip_to_screen_space(const cv::Vec2f& clip_coordinates, int screen_width, int screen_height)\n{\n\t\/\/ Window transform:\n\tconst float x_ss = (clip_coordinates[0] + 1.0f) * (screen_width \/ 2.0f);\n\tconst float y_ss = screen_height - (clip_coordinates[1] + 1.0f) * (screen_height \/ 2.0f); \/\/ also flip y; Qt: Origin top-left. OpenGL: bottom-left.\n\treturn cv::Vec2f(x_ss, y_ss);\n\t\/* Note: What we do here is equivalent to\n\t x_w = (x * vW\/2) + vW\/2;\n\t However, Shirley says we should do:\n\t x_w = (x * vW\/2) + (vW-1)\/2;\n\t (analogous for y)\n\t Todo: Check the consequences.\n\t*\/\n};\n\n\/**\n * Transforms a point from image (screen) coordinates to\n * clip space ([-1, 1] x [-1, 1]).\n * Note that the y-coordinate is flipped because the image origin\n * is top-left while in clip space top is +1 and bottom is -1.\n *\n * @param[in] screen_coordinates A point in screen coordinates.\n * @param[in] screen_width Width of the screen or window.\n * @param[in] screen_height Height of the screen or window.\n * @return A vector with x and y coordinates transformed to clip space.\n *\/\ninline cv::Vec2f screen_to_clip_space(const cv::Vec2f& screen_coordinates, int screen_width, int screen_height)\n{\n\tconst float x_cs = screen_coordinates[0] \/ (screen_width \/ 2.0f) - 1.0f;\n\tfloat y_cs = screen_coordinates[1] \/ (screen_height \/ 2.0f) - 1.0f;\n\ty_cs *= -1.0f;\n\treturn cv::Vec2f(x_cs, y_cs);\n};\n\n\/\/ TODO: Should go to detail:: namespace, or texturing\/utils or whatever.\nunsigned int get_max_possible_mipmaps_num(unsigned int width, unsigned int height)\n{\n\tunsigned int mipmapsNum = 1;\n\tunsigned int size = std::max(width, height);\n\n\tif (size == 1)\n\t\treturn 1;\n\n\tdo {\n\t\tsize >>= 1;\n\t\tmipmapsNum++;\n\t} while (size != 1);\n\n\treturn mipmapsNum;\n};\n\ninline bool is_power_of_two(int x)\n{\n\treturn !(x & (x - 1));\n};\n\nclass Texture\n{\npublic:\n\t\/\/ Todo: This whole class needs a major overhaul and documentation.\n\n\t\/\/ throws: ocv exc, runtime_ex\n\tvoid create_mipmapped_texture(cv::Mat image, unsigned int mipmapsNum = 0) {\n\n\t\tthis->mipmaps_num = (mipmapsNum == 0 ? get_max_possible_mipmaps_num(image.cols, image.rows) : mipmapsNum);\n\t\t\/*if (mipmapsNum == 0)\n\t\t{\n\t\tuchar mmn = render::utils::MatrixUtils::getMaxPossibleMipmapsNum(image.cols, image.rows);\n\t\tthis->mipmapsNum = mmn;\n\t\t} else\n\t\t{\n\t\tthis->mipmapsNum = mipmapsNum;\n\t\t}*\/\n\n\t\tif (this->mipmaps_num > 1)\n\t\t{\n\t\t\tif (!is_power_of_two(image.cols) || !is_power_of_two(image.rows))\n\t\t\t{\n\t\t\t\tthrow std::runtime_error(\"Error: Couldn't generate mipmaps, width or height not power of two.\");\n\t\t\t}\n\t\t}\n\t\timage.convertTo(image, CV_8UC4);\t\/\/ Most often, the input img is CV_8UC3. Img is BGR. Add an alpha channel\n\t\tcv::cvtColor(image, image, CV_BGR2BGRA);\n\n\t\tint currWidth = image.cols;\n\t\tint currHeight = image.rows;\n\t\tfor (int i = 0; i < this->mipmaps_num; i++)\n\t\t{\n\t\t\tif (i == 0) {\n\t\t\t\tmipmaps.push_back(image);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tcv::Mat currMipMap(currHeight, currWidth, CV_8UC4);\n\t\t\t\tcv::resize(mipmaps[i - 1], currMipMap, currMipMap.size());\n\t\t\t\tmipmaps.push_back(currMipMap);\n\t\t\t}\n\n\t\t\tif (currWidth > 1)\n\t\t\t\tcurrWidth >>= 1;\n\t\t\tif (currHeight > 1)\n\t\t\t\tcurrHeight >>= 1;\n\t\t}\n\t\tthis->widthLog = (uchar)(std::log(mipmaps[0].cols) \/ CV_LOG2 + 0.0001f); \/\/ std::epsilon or something? or why 0.0001f here?\n\t\tthis->heightLog = (uchar)(std::log(mipmaps[0].rows) \/ CV_LOG2 + 0.0001f); \/\/ Changed std::logf to std::log because it doesnt compile in linux (gcc 4.8). CHECK THAT\n\t};\n\n\tstd::vector<cv::Mat> mipmaps;\t\/\/ make Texture a friend class of renderer, then move this to private?\n\tunsigned char widthLog, heightLog; \/\/ log2 of width and height of the base mip-level\n\nprivate:\n\t\/\/std::string filename;\n\tunsigned int mipmaps_num;\n};\n\t} \/* namespace render *\/\n} \/* namespace eos *\/\n\n#endif \/* RENDER_UTILS_HPP_ *\/\n<commit_msg>Added a function to draw the texture coordinate triangles<commit_after>\/*\n * Eos - A 3D Morphable Model fitting library written in modern C++11\/14.\n *\n * File: include\/eos\/render\/utils.hpp\n *\n * Copyright 2014, 2015 Patrik Huber\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n#pragma once\n\n#ifndef RENDER_UTILS_HPP_\n#define RENDER_UTILS_HPP_\n\n#include \"opencv2\/core\/core.hpp\"\n#include \"opencv2\/imgproc\/imgproc.hpp\"\n\nnamespace eos {\n\tnamespace render {\n\n\/**\n * Transforms a point from clip space ([-1, 1] x [-1, 1]) to\n * image (screen) coordinates, i.e. the window transform.\n * Note that the y-coordinate is flipped because the image origin\n * is top-left while in clip space top is +1 and bottom is -1.\n * No z-division is performed.\n * Note: It should rather be called from NDC to screen space?\n *\n * Exactly conforming to the OpenGL viewport transform, except that\n * we flip y at the end.\n * Qt: Origin top-left. OpenGL: bottom-left. OCV: top-left.\n *\n * @param[in] clip_coordinates A point in clip coordinates.\n * @param[in] screen_width Width of the screen or window.\n * @param[in] screen_height Height of the screen or window.\n * @return A vector with x and y coordinates transformed to screen space.\n *\/\ninline cv::Vec2f clip_to_screen_space(const cv::Vec2f& clip_coordinates, int screen_width, int screen_height)\n{\n\t\/\/ Window transform:\n\tconst float x_ss = (clip_coordinates[0] + 1.0f) * (screen_width \/ 2.0f);\n\tconst float y_ss = screen_height - (clip_coordinates[1] + 1.0f) * (screen_height \/ 2.0f); \/\/ also flip y; Qt: Origin top-left. OpenGL: bottom-left.\n\treturn cv::Vec2f(x_ss, y_ss);\n\t\/* Note: What we do here is equivalent to\n\t x_w = (x * vW\/2) + vW\/2;\n\t However, Shirley says we should do:\n\t x_w = (x * vW\/2) + (vW-1)\/2;\n\t (analogous for y)\n\t Todo: Check the consequences.\n\t*\/\n};\n\n\/**\n * Transforms a point from image (screen) coordinates to\n * clip space ([-1, 1] x [-1, 1]).\n * Note that the y-coordinate is flipped because the image origin\n * is top-left while in clip space top is +1 and bottom is -1.\n *\n * @param[in] screen_coordinates A point in screen coordinates.\n * @param[in] screen_width Width of the screen or window.\n * @param[in] screen_height Height of the screen or window.\n * @return A vector with x and y coordinates transformed to clip space.\n *\/\ninline cv::Vec2f screen_to_clip_space(const cv::Vec2f& screen_coordinates, int screen_width, int screen_height)\n{\n\tconst float x_cs = screen_coordinates[0] \/ (screen_width \/ 2.0f) - 1.0f;\n\tfloat y_cs = screen_coordinates[1] \/ (screen_height \/ 2.0f) - 1.0f;\n\ty_cs *= -1.0f;\n\treturn cv::Vec2f(x_cs, y_cs);\n};\n\n\/**\n * Draws the texture coordinates (uv-coords) of the given mesh\n * into an image by looping over the triangles and drawing each\n * triangle's texcoords.\n *\n * @param[in] mesh A mesh with texture coordinates.\n * @param[in] image An optional image to draw onto.\n * @return An image with the texture coordinate triangles drawn in it, 512x512 if no image is given.\n *\/\ncv::Mat draw_texcoords(Mesh mesh, cv::Mat image = cv::Mat())\n{\n\tusing cv::Point2f;\n\tusing cv::Scalar;\n\tif (image.empty())\n\t{\n\t\timage = cv::Mat(512, 512, CV_8UC4, Scalar(0.0f, 0.0f, 0.0f, 255.0f));\n\t}\n\n\tfor (const auto& triIdx : mesh.tvi) {\n\t\tcv::line(image, Point2f(mesh.texcoords[triIdx[0]][0] * image.cols, mesh.texcoords[triIdx[0]][1] * image.rows), Point2f(mesh.texcoords[triIdx[1]][0] * image.cols, mesh.texcoords[triIdx[1]][1] * image.rows), Scalar(255.0f, 0.0f, 0.0f));\n\t\tcv::line(image, Point2f(mesh.texcoords[triIdx[1]][0] * image.cols, mesh.texcoords[triIdx[1]][1] * image.rows), Point2f(mesh.texcoords[triIdx[2]][0] * image.cols, mesh.texcoords[triIdx[2]][1] * image.rows), Scalar(255.0f, 0.0f, 0.0f));\n\t\tcv::line(image, Point2f(mesh.texcoords[triIdx[2]][0] * image.cols, mesh.texcoords[triIdx[2]][1] * image.rows), Point2f(mesh.texcoords[triIdx[0]][0] * image.cols, mesh.texcoords[triIdx[0]][1] * image.rows), Scalar(255.0f, 0.0f, 0.0f));\n\t}\n\treturn image;\n};\n\n\/\/ TODO: Should go to detail:: namespace, or texturing\/utils or whatever.\nunsigned int get_max_possible_mipmaps_num(unsigned int width, unsigned int height)\n{\n\tunsigned int mipmapsNum = 1;\n\tunsigned int size = std::max(width, height);\n\n\tif (size == 1)\n\t\treturn 1;\n\n\tdo {\n\t\tsize >>= 1;\n\t\tmipmapsNum++;\n\t} while (size != 1);\n\n\treturn mipmapsNum;\n};\n\ninline bool is_power_of_two(int x)\n{\n\treturn !(x & (x - 1));\n};\n\nclass Texture\n{\npublic:\n\t\/\/ Todo: This whole class needs a major overhaul and documentation.\n\n\t\/\/ throws: ocv exc, runtime_ex\n\tvoid create_mipmapped_texture(cv::Mat image, unsigned int mipmapsNum = 0) {\n\n\t\tthis->mipmaps_num = (mipmapsNum == 0 ? get_max_possible_mipmaps_num(image.cols, image.rows) : mipmapsNum);\n\t\t\/*if (mipmapsNum == 0)\n\t\t{\n\t\tuchar mmn = render::utils::MatrixUtils::getMaxPossibleMipmapsNum(image.cols, image.rows);\n\t\tthis->mipmapsNum = mmn;\n\t\t} else\n\t\t{\n\t\tthis->mipmapsNum = mipmapsNum;\n\t\t}*\/\n\n\t\tif (this->mipmaps_num > 1)\n\t\t{\n\t\t\tif (!is_power_of_two(image.cols) || !is_power_of_two(image.rows))\n\t\t\t{\n\t\t\t\tthrow std::runtime_error(\"Error: Couldn't generate mipmaps, width or height not power of two.\");\n\t\t\t}\n\t\t}\n\t\timage.convertTo(image, CV_8UC4);\t\/\/ Most often, the input img is CV_8UC3. Img is BGR. Add an alpha channel\n\t\tcv::cvtColor(image, image, CV_BGR2BGRA);\n\n\t\tint currWidth = image.cols;\n\t\tint currHeight = image.rows;\n\t\tfor (int i = 0; i < this->mipmaps_num; i++)\n\t\t{\n\t\t\tif (i == 0) {\n\t\t\t\tmipmaps.push_back(image);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tcv::Mat currMipMap(currHeight, currWidth, CV_8UC4);\n\t\t\t\tcv::resize(mipmaps[i - 1], currMipMap, currMipMap.size());\n\t\t\t\tmipmaps.push_back(currMipMap);\n\t\t\t}\n\n\t\t\tif (currWidth > 1)\n\t\t\t\tcurrWidth >>= 1;\n\t\t\tif (currHeight > 1)\n\t\t\t\tcurrHeight >>= 1;\n\t\t}\n\t\tthis->widthLog = (uchar)(std::log(mipmaps[0].cols) \/ CV_LOG2 + 0.0001f); \/\/ std::epsilon or something? or why 0.0001f here?\n\t\tthis->heightLog = (uchar)(std::log(mipmaps[0].rows) \/ CV_LOG2 + 0.0001f); \/\/ Changed std::logf to std::log because it doesnt compile in linux (gcc 4.8). CHECK THAT\n\t};\n\n\tstd::vector<cv::Mat> mipmaps;\t\/\/ make Texture a friend class of renderer, then move this to private?\n\tunsigned char widthLog, heightLog; \/\/ log2 of width and height of the base mip-level\n\nprivate:\n\t\/\/std::string filename;\n\tunsigned int mipmaps_num;\n};\n\t} \/* namespace render *\/\n} \/* namespace eos *\/\n\n#endif \/* RENDER_UTILS_HPP_ *\/\n<|endoftext|>"} {"text":"<commit_before>\/*\n Copyright 2011 Joe Hermaszewski. All rights reserved.\n\n Redistribution and use in source and binary forms, with or without modification, are\n permitted provided that the following conditions are met:\n\n 1. Redistributions of source code must retain the above copyright notice, this list of\n conditions and the following disclaimer.\n\n 2. Redistributions in binary form must reproduce the above copyright notice, this list\n of conditions and the following disclaimer in the documentation and\/or other materials\n provided with the distribution.\n\n THIS SOFTWARE IS PROVIDED BY Joe Hermaszewski \"AS IS\" AND ANY EXPRESS OR IMPLIED\n WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND\n FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL Joe Hermaszewski OR\n CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON\n ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF\n ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n The views and conclusions contained in the software and documentation are those of the\n authors and should not be interpreted as representing official policies, either expressed\n or implied, of Joe Hermaszewski.\n*\/\n\n#pragma once\n\n#include <config.h>\n#include <cstdint>\n\ntypedef uint8_t \tu8;\ntypedef uint16_t \tu16;\ntypedef uint32_t \tu32;\ntypedef uint64_t \tu64;\n\ntypedef int8_t\t\ts8;\ntypedef int16_t \ts16;\ntypedef int32_t \ts32;\ntypedef int64_t \ts64;\n<commit_msg>including config.hpp instead of config.h<commit_after>\/*\n Copyright 2011 Joe Hermaszewski. All rights reserved.\n\n Redistribution and use in source and binary forms, with or without modification, are\n permitted provided that the following conditions are met:\n\n 1. Redistributions of source code must retain the above copyright notice, this list of\n conditions and the following disclaimer.\n\n 2. Redistributions in binary form must reproduce the above copyright notice, this list\n of conditions and the following disclaimer in the documentation and\/or other materials\n provided with the distribution.\n\n THIS SOFTWARE IS PROVIDED BY Joe Hermaszewski \"AS IS\" AND ANY EXPRESS OR IMPLIED\n WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND\n FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL Joe Hermaszewski OR\n CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON\n ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF\n ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n The views and conclusions contained in the software and documentation are those of the\n authors and should not be interpreted as representing official policies, either expressed\n or implied, of Joe Hermaszewski.\n*\/\n\n#pragma once\n\n#include <joemath\/config.hpp>\n#include <cstdint>\n\ntypedef uint8_t \tu8;\ntypedef uint16_t \tu16;\ntypedef uint32_t \tu32;\ntypedef uint64_t \tu64;\n\ntypedef int8_t\t\ts8;\ntypedef int16_t \ts16;\ntypedef int32_t \ts32;\ntypedef int64_t \ts64;\n<|endoftext|>"} {"text":"<commit_before>#ifndef LIBPORT_LOCKABLE_HXX\n# define LIBPORT_LOCKABLE_HXX\n\n#include <libport\/assert.hh>\n\n\/*--------------------------.\n| Implementation: Windows. |\n`--------------------------*\/\n\n# if defined WIN32\n\nnamespace libport\n{\n inline void initLock(Lock& l)\n {\n l = CreateMutex(0, false, 0);\n if (!l)\n errabort(\"CreateMutex\");\n }\n\n inline void lockLock(Lock& l)\n {\n if (WaitForSingleObject(l, INFINITE) == WAIT_FAILED)\n errabort(\"WaitForSingleObject\");\n }\n\n inline void lockUnlock(Lock& l)\n {\n if (!ReleaseMutex(l))\n errabort(\"ReleaseMutex\");\n }\n\n inline void deleteLock(Lock& l)\n {\n CloseHandle(l);\n }\n\n inline bool lockTryLock(Lock& l)\n {\n DWORD ret = WaitForSingleObject(l, 0);\n if (ret == WAIT_FAILED)\n errabort(\"WaitForSingleObject\");\n return ret != WAIT_TIMEOUT;\n }\n} \/\/ namespace libport\n\n\n\/*---------------------------.\n| Implementation: pthreads. |\n`---------------------------*\/\n\n# else\n\nnamespace libport\n{\n\n inline void initLock(Lock& l)\n {\n pthread_mutexattr_t ma;\n pthread_mutexattr_init(&ma);\n \/* See\n * http:\/\/www.nabble.com\/Compiling-on-MacOS-10.4-Tiger-t284385.html\n * for more about this code. Yes, the second #if is very\n * suspicious, I don't know why it's like this. *\/\n# if defined __APPLE__ || defined __FreeBSD__\n pthread_mutexattr_settype(&ma, PTHREAD_MUTEX_RECURSIVE);\n# elif defined PTHREAD_MUTEX_RECURSIVE_NP\n \/\/ cygwin\n pthread_mutexattr_setkind_np(&ma, PTHREAD_MUTEX_RECURSIVE);\n# else\n \/\/ deprecated according to man page and fails to compile\n \/\/ pthread_mutexattr_setkind_np(&ma, PTHREAD_MUTEX_RECURSIVE_NP);\n pthread_mutexattr_settype(&ma, PTHREAD_MUTEX_RECURSIVE_NP);\n# endif\n pthread_mutex_init(&l, &ma);\n }\n\n inline void lockLock(Lock& l)\n {\n pthread_mutex_lock(&l);\n }\n\n inline void lockUnlock(Lock& l)\n {\n pthread_mutex_unlock(&l);\n }\n\n inline void deleteLock(Lock& l)\n {\n pthread_mutex_destroy(&l);\n }\n\n inline bool lockTryLock(Lock& l)\n {\n return !pthread_mutex_trylock(&l);\n }\n\n} \/\/ namespace libport\n# endif\n\n\nnamespace libport\n{\n\n \/*-----------.\n | Lockable. |\n `-----------*\/\n inline\n Lockable::Lockable()\n {\n initLock(lock_);\n }\n\n inline\n Lockable::~Lockable()\n {\n deleteLock(lock_);\n }\n\n inline\n void Lockable::lock()\n {\n lockLock(lock_);\n }\n\n inline\n void Lockable::unlock()\n {\n lockUnlock(lock_);\n }\n\n inline\n bool Lockable::tryLock()\n {\n return lockTryLock(lock_);\n }\n\n\n \/*------------.\n | BlockLock. |\n `------------*\/\n\n inline\n BlockLock::BlockLock(Lockable& l)\n : lockable_(l)\n {\n lockable_.lock();\n }\n\n inline\n BlockLock::BlockLock(Lockable* l)\n : lockable_(*l)\n {\n \/\/std::cerr <<\"lock \"<<l<<std::endl;\n lockable_.lock();\n }\n\n inline\n BlockLock::~BlockLock()\n {\n \/\/std::cerr <<\"unlock \"<<&l<<std::endl;\n lockable_.unlock();\n }\n\n} \/\/ namespace libport\n\n#endif \/\/ !LIBPORT_LOCKABLE_HXX\n<commit_msg>lockable: more assertions.<commit_after>#ifndef LIBPORT_LOCKABLE_HXX\n# define LIBPORT_LOCKABLE_HXX\n\n# include <libport\/cerrno>\n# include <libport\/assert.hh>\n\n\/*--------------------------.\n| Implementation: Windows. |\n`--------------------------*\/\n\n# if defined WIN32\n\nnamespace libport\n{\n inline void initLock(Lock& l)\n {\n l = CreateMutex(0, false, 0);\n if (!l)\n errabort(\"CreateMutex\");\n }\n\n inline void lockLock(Lock& l)\n {\n if (WaitForSingleObject(l, INFINITE) == WAIT_FAILED)\n errabort(\"WaitForSingleObject\");\n }\n\n inline void lockUnlock(Lock& l)\n {\n if (!ReleaseMutex(l))\n errabort(\"ReleaseMutex\");\n }\n\n inline void deleteLock(Lock& l)\n {\n CloseHandle(l);\n }\n\n inline bool lockTryLock(Lock& l)\n {\n DWORD ret = WaitForSingleObject(l, 0);\n if (ret == WAIT_FAILED)\n errabort(\"WaitForSingleObject\");\n return ret != WAIT_TIMEOUT;\n }\n} \/\/ namespace libport\n\n\n\/*---------------------------.\n| Implementation: pthreads. |\n`---------------------------*\/\n\n# else\n\nnamespace libport\n{\n\n inline void initLock(Lock& l)\n {\n pthread_mutexattr_t ma;\n if (pthread_mutexattr_init(&ma))\n errabort(\"pthread_mutexattr_init\");\n \/* See\n * http:\/\/www.nabble.com\/Compiling-on-MacOS-10.4-Tiger-t284385.html\n * for more about this code. Yes, the second #if is very\n * suspicious, I don't know why it's like this. *\/\n# if defined __APPLE__ || defined __FreeBSD__\n if (pthread_mutexattr_settype(&ma, PTHREAD_MUTEX_RECURSIVE))\n errabort(\"pthread_mutexattr_settype\");\n# elif defined PTHREAD_MUTEX_RECURSIVE_NP\n \/\/ cygwin\n if (pthread_mutexattr_setkind_np(&ma, PTHREAD_MUTEX_RECURSIVE))\n errabort(\"pthread_mutexattr_setkind_np\");\n# else\n \/\/ deprecated according to man page and fails to compile\n \/\/ pthread_mutexattr_setkind_np(&ma, PTHREAD_MUTEX_RECURSIVE_NP);\n if (pthread_mutexattr_settype(&ma, PTHREAD_MUTEX_RECURSIVE_NP))\n errabort(\"pthread_mutexattr_settype\");\n# endif\n if (pthread_mutex_init(&l, &ma))\n errabort(\"pthread_mutex_init\");\n }\n\n inline void lockLock(Lock& l)\n {\n if (pthread_mutex_lock(&l))\n errabort(\"pthread_mutex_lock\");\n }\n\n inline void lockUnlock(Lock& l)\n {\n if (pthread_mutex_unlock(&l))\n errabort(\"pthread_mutex_unlock\");\n }\n\n inline void deleteLock(Lock& l)\n {\n if (pthread_mutex_destroy(&l))\n errabort(\"pthread_mutex_destroy\");\n }\n\n inline bool lockTryLock(Lock& l)\n {\n if (pthread_mutex_trylock(&l))\n {\n if (errno == EBUSY)\n return false;\n else\n errabort(\"pthread_mutex_trylock\");\n }\n else\n return true;\n }\n\n} \/\/ namespace libport\n# endif\n\n\nnamespace libport\n{\n\n \/*-----------.\n | Lockable. |\n `-----------*\/\n inline\n Lockable::Lockable()\n {\n initLock(lock_);\n }\n\n inline\n Lockable::~Lockable()\n {\n deleteLock(lock_);\n }\n\n inline\n void Lockable::lock()\n {\n lockLock(lock_);\n }\n\n inline\n void Lockable::unlock()\n {\n lockUnlock(lock_);\n }\n\n inline\n bool Lockable::tryLock()\n {\n return lockTryLock(lock_);\n }\n\n\n \/*------------.\n | BlockLock. |\n `------------*\/\n\n inline\n BlockLock::BlockLock(Lockable& l)\n : lockable_(l)\n {\n lockable_.lock();\n }\n\n inline\n BlockLock::BlockLock(Lockable* l)\n : lockable_(*l)\n {\n \/\/std::cerr <<\"lock \"<<l<<std::endl;\n lockable_.lock();\n }\n\n inline\n BlockLock::~BlockLock()\n {\n \/\/std::cerr <<\"unlock \"<<&l<<std::endl;\n lockable_.unlock();\n }\n\n} \/\/ namespace libport\n\n#endif \/\/ !LIBPORT_LOCKABLE_HXX\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (C) 2009, Gostai S.A.S.\n *\n * This software is provided \"as is\" without warranty of any kind,\n * either expressed or implied, including but not limited to the\n * implied warranties of fitness for a particular purpose.\n *\n * See the LICENSE file for more information.\n *\/\n#ifdef WIN32\n\nint\nmkdir(const char *path, mode_t)\n{\n return _mkdir(path);\n}\n\n#endif\n<commit_msg>Do not redefine mkdir under mingw, only under vcxx.<commit_after>\/*\n * Copyright (C) 2009, Gostai S.A.S.\n *\n * This software is provided \"as is\" without warranty of any kind,\n * either expressed or implied, including but not limited to the\n * implied warranties of fitness for a particular purpose.\n *\n * See the LICENSE file for more information.\n *\/\n#ifdef MSVC_VERSION\n\nint\nmkdir(const char *path, mode_t)\n{\n return _mkdir(path);\n}\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/\/===- FunctionResolution.cpp - Resolve declarations to implementations ---===\/\/\n\/\/\n\/\/ Loop over the functions that are in the module and look for functions that\n\/\/ have the same name. More often than not, there will be things like:\n\/\/\n\/\/ declare void %foo(...)\n\/\/ void %foo(int, int) { ... }\n\/\/\n\/\/ because of the way things are declared in C. If this is the case, patch\n\/\/ things up.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/Transforms\/IPO.h\"\n#include \"llvm\/Module.h\"\n#include \"llvm\/SymbolTable.h\"\n#include \"llvm\/DerivedTypes.h\"\n#include \"llvm\/Pass.h\"\n#include \"llvm\/iOther.h\"\n#include \"llvm\/Constants.h\"\n#include \"llvm\/Assembly\/Writer.h\" \/\/ FIXME: remove when varargs implemented\n#include \"Support\/Statistic.h\"\n#include <algorithm>\n\nnamespace {\n Statistic<>NumResolved(\"funcresolve\", \"Number of varargs functions resolved\");\n Statistic<> NumGlobals(\"funcresolve\", \"Number of global variables resolved\");\n\n struct FunctionResolvingPass : public Pass {\n bool run(Module &M);\n };\n RegisterOpt<FunctionResolvingPass> X(\"funcresolve\", \"Resolve Functions\");\n}\n\nPass *createFunctionResolvingPass() {\n return new FunctionResolvingPass();\n}\n\nstatic bool ResolveFunctions(Module &M, std::vector<GlobalValue*> &Globals,\n Function *Concrete) {\n bool Changed = false;\n for (unsigned i = 0; i != Globals.size(); ++i)\n if (Globals[i] != Concrete) {\n Function *Old = cast<Function>(Globals[i]);\n const FunctionType *OldMT = Old->getFunctionType();\n const FunctionType *ConcreteMT = Concrete->getFunctionType();\n \n if (OldMT->getParamTypes().size() > ConcreteMT->getParamTypes().size() &&\n !ConcreteMT->isVarArg())\n if (!Old->use_empty()) {\n std::cerr << \"WARNING: Linking function '\" << Old->getName()\n << \"' is causing arguments to be dropped.\\n\";\n std::cerr << \"WARNING: Prototype: \";\n WriteAsOperand(std::cerr, Old);\n std::cerr << \" resolved to \";\n WriteAsOperand(std::cerr, Concrete);\n std::cerr << \"\\n\";\n }\n \n \/\/ Check to make sure that if there are specified types, that they\n \/\/ match...\n \/\/\n unsigned NumArguments = std::min(OldMT->getParamTypes().size(),\n ConcreteMT->getParamTypes().size());\n\n if (!Old->use_empty() && !Concrete->use_empty())\n for (unsigned i = 0; i < NumArguments; ++i)\n if (OldMT->getParamTypes()[i] != ConcreteMT->getParamTypes()[i]) {\n std::cerr << \"WARNING: Function [\" << Old->getName()\n << \"]: Parameter types conflict for: '\" << OldMT\n << \"' and '\" << ConcreteMT << \"'\\n\";\n return Changed;\n }\n \n \/\/ Attempt to convert all of the uses of the old function to the concrete\n \/\/ form of the function. If there is a use of the fn that we don't\n \/\/ understand here we punt to avoid making a bad transformation.\n \/\/\n \/\/ At this point, we know that the return values are the same for our two\n \/\/ functions and that the Old function has no varargs fns specified. In\n \/\/ otherwords it's just <retty> (...)\n \/\/\n Value *Replacement = Concrete;\n if (Concrete->getType() != Old->getType())\n Replacement = ConstantExpr::getCast(ConstantPointerRef::get(Concrete),\n Old->getType());\n NumResolved += Old->use_size();\n Old->replaceAllUsesWith(Replacement);\n\n \/\/ Since there are no uses of Old anymore, remove it from the module.\n M.getFunctionList().erase(Old);\n }\n return Changed;\n}\n\n\nstatic bool ResolveGlobalVariables(Module &M,\n std::vector<GlobalValue*> &Globals,\n GlobalVariable *Concrete) {\n bool Changed = false;\n assert(isa<ArrayType>(Concrete->getType()->getElementType()) &&\n \"Concrete version should be an array type!\");\n\n \/\/ Get the type of the things that may be resolved to us...\n const ArrayType *CATy =cast<ArrayType>(Concrete->getType()->getElementType());\n const Type *AETy = CATy->getElementType();\n\n Constant *CCPR = ConstantPointerRef::get(Concrete);\n\n for (unsigned i = 0; i != Globals.size(); ++i)\n if (Globals[i] != Concrete) {\n GlobalVariable *Old = cast<GlobalVariable>(Globals[i]);\n const ArrayType *OATy = cast<ArrayType>(Old->getType()->getElementType());\n if (OATy->getElementType() != AETy || OATy->getNumElements() != 0) {\n std::cerr << \"WARNING: Two global variables exist with the same name \"\n << \"that cannot be resolved!\\n\";\n return false;\n }\n\n Old->replaceAllUsesWith(ConstantExpr::getCast(CCPR, Old->getType()));\n\n \/\/ Since there are no uses of Old anymore, remove it from the module.\n M.getGlobalList().erase(Old);\n\n ++NumGlobals;\n Changed = true;\n }\n return Changed;\n}\n\nstatic bool ProcessGlobalsWithSameName(Module &M,\n std::vector<GlobalValue*> &Globals) {\n assert(!Globals.empty() && \"Globals list shouldn't be empty here!\");\n\n bool isFunction = isa<Function>(Globals[0]); \/\/ Is this group all functions?\n GlobalValue *Concrete = 0; \/\/ The most concrete implementation to resolve to\n\n assert((isFunction ^ isa<GlobalVariable>(Globals[0])) &&\n \"Should either be function or gvar!\");\n\n for (unsigned i = 0; i != Globals.size(); ) {\n if (isa<Function>(Globals[i]) != isFunction) {\n std::cerr << \"WARNING: Found function and global variable with the \"\n << \"same name: '\" << Globals[i]->getName() << \"'.\\n\";\n return false; \/\/ Don't know how to handle this, bail out!\n }\n\n if (isFunction) {\n \/\/ For functions, we look to merge functions definitions of \"int (...)\"\n \/\/ to 'int (int)' or 'int ()' or whatever else is not completely generic.\n \/\/\n Function *F = cast<Function>(Globals[i]);\n if (!F->isExternal()) {\n if (Concrete && !Concrete->isExternal())\n return false; \/\/ Found two different functions types. Can't choose!\n \n Concrete = Globals[i];\n } else if (Concrete) {\n if (Concrete->isExternal()) \/\/ If we have multiple external symbols...x\n if (F->getFunctionType()->getNumParams() > \n cast<Function>(Concrete)->getFunctionType()->getNumParams())\n Concrete = F; \/\/ We are more concrete than \"Concrete\"!\n\n } else {\n Concrete = F;\n }\n } else {\n \/\/ For global variables, we have to merge C definitions int A[][4] with\n \/\/ int[6][4]. A[][4] is represented as A[0][4] by the CFE.\n GlobalVariable *GV = cast<GlobalVariable>(Globals[i]);\n if (!isa<ArrayType>(GV->getType()->getElementType())) {\n Concrete = 0;\n break; \/\/ Non array's cannot be compatible with other types.\n } else if (Concrete == 0) {\n Concrete = GV;\n } else {\n \/\/ Must have different types... allow merging A[0][4] w\/ A[6][4] if\n \/\/ A[0][4] is external.\n const ArrayType *NAT = cast<ArrayType>(GV->getType()->getElementType());\n const ArrayType *CAT =\n cast<ArrayType>(Concrete->getType()->getElementType());\n\n if (NAT->getElementType() != CAT->getElementType()) {\n Concrete = 0; \/\/ Non-compatible types\n break;\n } else if (NAT->getNumElements() == 0 && GV->isExternal()) {\n \/\/ Concrete remains the same\n } else if (CAT->getNumElements() == 0 && Concrete->isExternal()) {\n Concrete = GV; \/\/ Concrete becomes GV\n } else {\n Concrete = 0; \/\/ Cannot merge these types...\n break;\n }\n }\n }\n ++i;\n }\n\n if (Globals.size() > 1) { \/\/ Found a multiply defined global...\n \/\/ If there are no external declarations, and there is at most one\n \/\/ externally visible instance of the global, then there is nothing to do.\n \/\/\n bool HasExternal = false;\n unsigned NumInstancesWithExternalLinkage = 0;\n\n for (unsigned i = 0, e = Globals.size(); i != e; ++i) {\n if (Globals[i]->isExternal())\n HasExternal = true;\n else if (!Globals[i]->hasInternalLinkage())\n NumInstancesWithExternalLinkage++;\n }\n \n if (!HasExternal && NumInstancesWithExternalLinkage <= 1)\n return false; \/\/ Nothing to do? Must have multiple internal definitions.\n\n\n \/\/ We should find exactly one concrete function definition, which is\n \/\/ probably the implementation. Change all of the function definitions and\n \/\/ uses to use it instead.\n \/\/\n if (!Concrete) {\n std::cerr << \"WARNING: Found global types that are not compatible:\\n\";\n for (unsigned i = 0; i < Globals.size(); ++i) {\n std::cerr << \"\\t\" << Globals[i]->getType()->getDescription() << \" %\"\n << Globals[i]->getName() << \"\\n\";\n }\n std::cerr << \" No linkage of globals named '\" << Globals[0]->getName()\n << \"' performed!\\n\";\n return false;\n }\n\n if (isFunction)\n return ResolveFunctions(M, Globals, cast<Function>(Concrete));\n else\n return ResolveGlobalVariables(M, Globals,\n cast<GlobalVariable>(Concrete));\n }\n return false;\n}\n\nbool FunctionResolvingPass::run(Module &M) {\n SymbolTable &ST = M.getSymbolTable();\n\n std::map<std::string, std::vector<GlobalValue*> > Globals;\n\n \/\/ Loop over the entries in the symbol table. If an entry is a func pointer,\n \/\/ then add it to the Functions map. We do a two pass algorithm here to avoid\n \/\/ problems with iterators getting invalidated if we did a one pass scheme.\n \/\/\n for (SymbolTable::iterator I = ST.begin(), E = ST.end(); I != E; ++I)\n if (const PointerType *PT = dyn_cast<PointerType>(I->first)) {\n SymbolTable::VarMap &Plane = I->second;\n for (SymbolTable::type_iterator PI = Plane.begin(), PE = Plane.end();\n PI != PE; ++PI) {\n GlobalValue *GV = cast<GlobalValue>(PI->second);\n assert(PI->first == GV->getName() &&\n \"Global name and symbol table do not agree!\");\n Globals[PI->first].push_back(GV);\n }\n }\n\n bool Changed = false;\n\n \/\/ Now we have a list of all functions with a particular name. If there is\n \/\/ more than one entry in a list, merge the functions together.\n \/\/\n for (std::map<std::string, std::vector<GlobalValue*> >::iterator\n I = Globals.begin(), E = Globals.end(); I != E; ++I)\n Changed |= ProcessGlobalsWithSameName(M, I->second);\n\n \/\/ Now loop over all of the globals, checking to see if any are trivially\n \/\/ dead. If so, remove them now.\n\n for (Module::iterator I = M.begin(), E = M.end(); I != E; )\n if (I->isExternal() && I->use_empty()) {\n Function *F = I;\n ++I;\n M.getFunctionList().erase(F);\n ++NumResolved;\n Changed = true;\n } else {\n ++I;\n }\n\n for (Module::giterator I = M.gbegin(), E = M.gend(); I != E; )\n if (I->isExternal() && I->use_empty()) {\n GlobalVariable *GV = I;\n ++I;\n M.getGlobalList().erase(GV);\n ++NumGlobals;\n Changed = true;\n } else {\n ++I;\n }\n\n return Changed;\n}\n<commit_msg>Fix bug: FunctionResolve\/2003-07-23-CPR-Reference.ll<commit_after>\/\/===- FunctionResolution.cpp - Resolve declarations to implementations ---===\/\/\n\/\/\n\/\/ Loop over the functions that are in the module and look for functions that\n\/\/ have the same name. More often than not, there will be things like:\n\/\/\n\/\/ declare void %foo(...)\n\/\/ void %foo(int, int) { ... }\n\/\/\n\/\/ because of the way things are declared in C. If this is the case, patch\n\/\/ things up.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/Transforms\/IPO.h\"\n#include \"llvm\/Module.h\"\n#include \"llvm\/SymbolTable.h\"\n#include \"llvm\/DerivedTypes.h\"\n#include \"llvm\/Pass.h\"\n#include \"llvm\/iOther.h\"\n#include \"llvm\/Constants.h\"\n#include \"llvm\/Assembly\/Writer.h\" \/\/ FIXME: remove when varargs implemented\n#include \"Support\/Statistic.h\"\n#include <algorithm>\n\nnamespace {\n Statistic<>NumResolved(\"funcresolve\", \"Number of varargs functions resolved\");\n Statistic<> NumGlobals(\"funcresolve\", \"Number of global variables resolved\");\n\n struct FunctionResolvingPass : public Pass {\n bool run(Module &M);\n };\n RegisterOpt<FunctionResolvingPass> X(\"funcresolve\", \"Resolve Functions\");\n}\n\nPass *createFunctionResolvingPass() {\n return new FunctionResolvingPass();\n}\n\nstatic bool ResolveFunctions(Module &M, std::vector<GlobalValue*> &Globals,\n Function *Concrete) {\n bool Changed = false;\n for (unsigned i = 0; i != Globals.size(); ++i)\n if (Globals[i] != Concrete) {\n Function *Old = cast<Function>(Globals[i]);\n const FunctionType *OldMT = Old->getFunctionType();\n const FunctionType *ConcreteMT = Concrete->getFunctionType();\n \n if (OldMT->getParamTypes().size() > ConcreteMT->getParamTypes().size() &&\n !ConcreteMT->isVarArg())\n if (!Old->use_empty()) {\n std::cerr << \"WARNING: Linking function '\" << Old->getName()\n << \"' is causing arguments to be dropped.\\n\";\n std::cerr << \"WARNING: Prototype: \";\n WriteAsOperand(std::cerr, Old);\n std::cerr << \" resolved to \";\n WriteAsOperand(std::cerr, Concrete);\n std::cerr << \"\\n\";\n }\n \n \/\/ Check to make sure that if there are specified types, that they\n \/\/ match...\n \/\/\n unsigned NumArguments = std::min(OldMT->getParamTypes().size(),\n ConcreteMT->getParamTypes().size());\n\n if (!Old->use_empty() && !Concrete->use_empty())\n for (unsigned i = 0; i < NumArguments; ++i)\n if (OldMT->getParamTypes()[i] != ConcreteMT->getParamTypes()[i]) {\n std::cerr << \"WARNING: Function [\" << Old->getName()\n << \"]: Parameter types conflict for: '\" << OldMT\n << \"' and '\" << ConcreteMT << \"'\\n\";\n return Changed;\n }\n \n \/\/ Attempt to convert all of the uses of the old function to the concrete\n \/\/ form of the function. If there is a use of the fn that we don't\n \/\/ understand here we punt to avoid making a bad transformation.\n \/\/\n \/\/ At this point, we know that the return values are the same for our two\n \/\/ functions and that the Old function has no varargs fns specified. In\n \/\/ otherwords it's just <retty> (...)\n \/\/\n if (!Old->use_empty()) { \/\/ Avoid making the CPR unless we really need it\n Value *Replacement = Concrete;\n if (Concrete->getType() != Old->getType())\n Replacement = ConstantExpr::getCast(ConstantPointerRef::get(Concrete),\n Old->getType());\n NumResolved += Old->use_size();\n Old->replaceAllUsesWith(Replacement);\n }\n\n \/\/ Since there are no uses of Old anymore, remove it from the module.\n M.getFunctionList().erase(Old);\n }\n return Changed;\n}\n\n\nstatic bool ResolveGlobalVariables(Module &M,\n std::vector<GlobalValue*> &Globals,\n GlobalVariable *Concrete) {\n bool Changed = false;\n assert(isa<ArrayType>(Concrete->getType()->getElementType()) &&\n \"Concrete version should be an array type!\");\n\n \/\/ Get the type of the things that may be resolved to us...\n const ArrayType *CATy =cast<ArrayType>(Concrete->getType()->getElementType());\n const Type *AETy = CATy->getElementType();\n\n Constant *CCPR = ConstantPointerRef::get(Concrete);\n\n for (unsigned i = 0; i != Globals.size(); ++i)\n if (Globals[i] != Concrete) {\n GlobalVariable *Old = cast<GlobalVariable>(Globals[i]);\n const ArrayType *OATy = cast<ArrayType>(Old->getType()->getElementType());\n if (OATy->getElementType() != AETy || OATy->getNumElements() != 0) {\n std::cerr << \"WARNING: Two global variables exist with the same name \"\n << \"that cannot be resolved!\\n\";\n return false;\n }\n\n Old->replaceAllUsesWith(ConstantExpr::getCast(CCPR, Old->getType()));\n\n \/\/ Since there are no uses of Old anymore, remove it from the module.\n M.getGlobalList().erase(Old);\n\n ++NumGlobals;\n Changed = true;\n }\n return Changed;\n}\n\nstatic bool ProcessGlobalsWithSameName(Module &M,\n std::vector<GlobalValue*> &Globals) {\n assert(!Globals.empty() && \"Globals list shouldn't be empty here!\");\n\n bool isFunction = isa<Function>(Globals[0]); \/\/ Is this group all functions?\n GlobalValue *Concrete = 0; \/\/ The most concrete implementation to resolve to\n\n assert((isFunction ^ isa<GlobalVariable>(Globals[0])) &&\n \"Should either be function or gvar!\");\n\n for (unsigned i = 0; i != Globals.size(); ) {\n if (isa<Function>(Globals[i]) != isFunction) {\n std::cerr << \"WARNING: Found function and global variable with the \"\n << \"same name: '\" << Globals[i]->getName() << \"'.\\n\";\n return false; \/\/ Don't know how to handle this, bail out!\n }\n\n if (isFunction) {\n \/\/ For functions, we look to merge functions definitions of \"int (...)\"\n \/\/ to 'int (int)' or 'int ()' or whatever else is not completely generic.\n \/\/\n Function *F = cast<Function>(Globals[i]);\n if (!F->isExternal()) {\n if (Concrete && !Concrete->isExternal())\n return false; \/\/ Found two different functions types. Can't choose!\n \n Concrete = Globals[i];\n } else if (Concrete) {\n if (Concrete->isExternal()) \/\/ If we have multiple external symbols...x\n if (F->getFunctionType()->getNumParams() > \n cast<Function>(Concrete)->getFunctionType()->getNumParams())\n Concrete = F; \/\/ We are more concrete than \"Concrete\"!\n\n } else {\n Concrete = F;\n }\n } else {\n \/\/ For global variables, we have to merge C definitions int A[][4] with\n \/\/ int[6][4]. A[][4] is represented as A[0][4] by the CFE.\n GlobalVariable *GV = cast<GlobalVariable>(Globals[i]);\n if (!isa<ArrayType>(GV->getType()->getElementType())) {\n Concrete = 0;\n break; \/\/ Non array's cannot be compatible with other types.\n } else if (Concrete == 0) {\n Concrete = GV;\n } else {\n \/\/ Must have different types... allow merging A[0][4] w\/ A[6][4] if\n \/\/ A[0][4] is external.\n const ArrayType *NAT = cast<ArrayType>(GV->getType()->getElementType());\n const ArrayType *CAT =\n cast<ArrayType>(Concrete->getType()->getElementType());\n\n if (NAT->getElementType() != CAT->getElementType()) {\n Concrete = 0; \/\/ Non-compatible types\n break;\n } else if (NAT->getNumElements() == 0 && GV->isExternal()) {\n \/\/ Concrete remains the same\n } else if (CAT->getNumElements() == 0 && Concrete->isExternal()) {\n Concrete = GV; \/\/ Concrete becomes GV\n } else {\n Concrete = 0; \/\/ Cannot merge these types...\n break;\n }\n }\n }\n ++i;\n }\n\n if (Globals.size() > 1) { \/\/ Found a multiply defined global...\n \/\/ If there are no external declarations, and there is at most one\n \/\/ externally visible instance of the global, then there is nothing to do.\n \/\/\n bool HasExternal = false;\n unsigned NumInstancesWithExternalLinkage = 0;\n\n for (unsigned i = 0, e = Globals.size(); i != e; ++i) {\n if (Globals[i]->isExternal())\n HasExternal = true;\n else if (!Globals[i]->hasInternalLinkage())\n NumInstancesWithExternalLinkage++;\n }\n \n if (!HasExternal && NumInstancesWithExternalLinkage <= 1)\n return false; \/\/ Nothing to do? Must have multiple internal definitions.\n\n\n \/\/ We should find exactly one concrete function definition, which is\n \/\/ probably the implementation. Change all of the function definitions and\n \/\/ uses to use it instead.\n \/\/\n if (!Concrete) {\n std::cerr << \"WARNING: Found global types that are not compatible:\\n\";\n for (unsigned i = 0; i < Globals.size(); ++i) {\n std::cerr << \"\\t\" << Globals[i]->getType()->getDescription() << \" %\"\n << Globals[i]->getName() << \"\\n\";\n }\n std::cerr << \" No linkage of globals named '\" << Globals[0]->getName()\n << \"' performed!\\n\";\n return false;\n }\n\n if (isFunction)\n return ResolveFunctions(M, Globals, cast<Function>(Concrete));\n else\n return ResolveGlobalVariables(M, Globals,\n cast<GlobalVariable>(Concrete));\n }\n return false;\n}\n\nbool FunctionResolvingPass::run(Module &M) {\n SymbolTable &ST = M.getSymbolTable();\n\n std::map<std::string, std::vector<GlobalValue*> > Globals;\n\n \/\/ Loop over the entries in the symbol table. If an entry is a func pointer,\n \/\/ then add it to the Functions map. We do a two pass algorithm here to avoid\n \/\/ problems with iterators getting invalidated if we did a one pass scheme.\n \/\/\n for (SymbolTable::iterator I = ST.begin(), E = ST.end(); I != E; ++I)\n if (const PointerType *PT = dyn_cast<PointerType>(I->first)) {\n SymbolTable::VarMap &Plane = I->second;\n for (SymbolTable::type_iterator PI = Plane.begin(), PE = Plane.end();\n PI != PE; ++PI) {\n GlobalValue *GV = cast<GlobalValue>(PI->second);\n assert(PI->first == GV->getName() &&\n \"Global name and symbol table do not agree!\");\n Globals[PI->first].push_back(GV);\n }\n }\n\n bool Changed = false;\n\n \/\/ Now we have a list of all functions with a particular name. If there is\n \/\/ more than one entry in a list, merge the functions together.\n \/\/\n for (std::map<std::string, std::vector<GlobalValue*> >::iterator\n I = Globals.begin(), E = Globals.end(); I != E; ++I)\n Changed |= ProcessGlobalsWithSameName(M, I->second);\n\n \/\/ Now loop over all of the globals, checking to see if any are trivially\n \/\/ dead. If so, remove them now.\n\n for (Module::iterator I = M.begin(), E = M.end(); I != E; )\n if (I->isExternal() && I->use_empty()) {\n Function *F = I;\n ++I;\n M.getFunctionList().erase(F);\n ++NumResolved;\n Changed = true;\n } else {\n ++I;\n }\n\n for (Module::giterator I = M.gbegin(), E = M.gend(); I != E; )\n if (I->isExternal() && I->use_empty()) {\n GlobalVariable *GV = I;\n ++I;\n M.getGlobalList().erase(GV);\n ++NumGlobals;\n Changed = true;\n } else {\n ++I;\n }\n\n return Changed;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/===- FunctionResolution.cpp - Resolve declarations to implementations ---===\/\/\n\/\/ \n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file was developed by the LLVM research group and is distributed under\n\/\/ the University of Illinois Open Source License. See LICENSE.TXT for details.\n\/\/ \n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ Loop over the functions that are in the module and look for functions that\n\/\/ have the same name. More often than not, there will be things like:\n\/\/\n\/\/ declare void %foo(...)\n\/\/ void %foo(int, int) { ... }\n\/\/\n\/\/ because of the way things are declared in C. If this is the case, patch\n\/\/ things up.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/Transforms\/IPO.h\"\n#include \"llvm\/Module.h\"\n#include \"llvm\/SymbolTable.h\"\n#include \"llvm\/DerivedTypes.h\"\n#include \"llvm\/Pass.h\"\n#include \"llvm\/iOther.h\"\n#include \"llvm\/Constants.h\"\n#include \"llvm\/Assembly\/Writer.h\"\n#include \"Support\/Statistic.h\"\n#include <algorithm>\n\nnamespace {\n Statistic<>NumResolved(\"funcresolve\", \"Number of varargs functions resolved\");\n Statistic<> NumGlobals(\"funcresolve\", \"Number of global variables resolved\");\n\n struct FunctionResolvingPass : public Pass {\n bool run(Module &M);\n };\n RegisterOpt<FunctionResolvingPass> X(\"funcresolve\", \"Resolve Functions\");\n}\n\nPass *createFunctionResolvingPass() {\n return new FunctionResolvingPass();\n}\n\nstatic bool ResolveFunctions(Module &M, std::vector<GlobalValue*> &Globals,\n Function *Concrete) {\n bool Changed = false;\n for (unsigned i = 0; i != Globals.size(); ++i)\n if (Globals[i] != Concrete) {\n Function *Old = cast<Function>(Globals[i]);\n const FunctionType *OldMT = Old->getFunctionType();\n const FunctionType *ConcreteMT = Concrete->getFunctionType();\n \n if (OldMT->getParamTypes().size() > ConcreteMT->getParamTypes().size() &&\n !ConcreteMT->isVarArg())\n if (!Old->use_empty()) {\n std::cerr << \"WARNING: Linking function '\" << Old->getName()\n << \"' is causing arguments to be dropped.\\n\";\n std::cerr << \"WARNING: Prototype: \";\n WriteAsOperand(std::cerr, Old);\n std::cerr << \" resolved to \";\n WriteAsOperand(std::cerr, Concrete);\n std::cerr << \"\\n\";\n }\n \n \/\/ Check to make sure that if there are specified types, that they\n \/\/ match...\n \/\/\n unsigned NumArguments = std::min(OldMT->getParamTypes().size(),\n ConcreteMT->getParamTypes().size());\n\n if (!Old->use_empty() && !Concrete->use_empty())\n for (unsigned i = 0; i < NumArguments; ++i)\n if (OldMT->getParamTypes()[i] != ConcreteMT->getParamTypes()[i])\n if (OldMT->getParamTypes()[i]->getPrimitiveID() != \n ConcreteMT->getParamTypes()[i]->getPrimitiveID()) {\n std::cerr << \"WARNING: Function [\" << Old->getName()\n << \"]: Parameter types conflict for: '\" << OldMT\n << \"' and '\" << ConcreteMT << \"'\\n\";\n return Changed;\n }\n \n \/\/ Attempt to convert all of the uses of the old function to the concrete\n \/\/ form of the function. If there is a use of the fn that we don't\n \/\/ understand here we punt to avoid making a bad transformation.\n \/\/\n \/\/ At this point, we know that the return values are the same for our two\n \/\/ functions and that the Old function has no varargs fns specified. In\n \/\/ otherwords it's just <retty> (...)\n \/\/\n if (!Old->use_empty()) { \/\/ Avoid making the CPR unless we really need it\n Value *Replacement = Concrete;\n if (Concrete->getType() != Old->getType())\n Replacement = ConstantExpr::getCast(ConstantPointerRef::get(Concrete),\n Old->getType());\n NumResolved += Old->use_size();\n Old->replaceAllUsesWith(Replacement);\n }\n\n \/\/ Since there are no uses of Old anymore, remove it from the module.\n M.getFunctionList().erase(Old);\n }\n return Changed;\n}\n\n\nstatic bool ResolveGlobalVariables(Module &M,\n std::vector<GlobalValue*> &Globals,\n GlobalVariable *Concrete) {\n bool Changed = false;\n assert(isa<ArrayType>(Concrete->getType()->getElementType()) &&\n \"Concrete version should be an array type!\");\n\n \/\/ Get the type of the things that may be resolved to us...\n const ArrayType *CATy =cast<ArrayType>(Concrete->getType()->getElementType());\n const Type *AETy = CATy->getElementType();\n\n Constant *CCPR = ConstantPointerRef::get(Concrete);\n\n for (unsigned i = 0; i != Globals.size(); ++i)\n if (Globals[i] != Concrete) {\n GlobalVariable *Old = cast<GlobalVariable>(Globals[i]);\n const ArrayType *OATy = cast<ArrayType>(Old->getType()->getElementType());\n if (OATy->getElementType() != AETy || OATy->getNumElements() != 0) {\n std::cerr << \"WARNING: Two global variables exist with the same name \"\n << \"that cannot be resolved!\\n\";\n return false;\n }\n\n Old->replaceAllUsesWith(ConstantExpr::getCast(CCPR, Old->getType()));\n\n \/\/ Since there are no uses of Old anymore, remove it from the module.\n M.getGlobalList().erase(Old);\n\n ++NumGlobals;\n Changed = true;\n }\n return Changed;\n}\n\nstatic bool ProcessGlobalsWithSameName(Module &M,\n std::vector<GlobalValue*> &Globals) {\n assert(!Globals.empty() && \"Globals list shouldn't be empty here!\");\n\n bool isFunction = isa<Function>(Globals[0]); \/\/ Is this group all functions?\n GlobalValue *Concrete = 0; \/\/ The most concrete implementation to resolve to\n\n assert((isFunction ^ isa<GlobalVariable>(Globals[0])) &&\n \"Should either be function or gvar!\");\n\n for (unsigned i = 0; i != Globals.size(); ) {\n if (isa<Function>(Globals[i]) != isFunction) {\n std::cerr << \"WARNING: Found function and global variable with the \"\n << \"same name: '\" << Globals[i]->getName() << \"'.\\n\";\n return false; \/\/ Don't know how to handle this, bail out!\n }\n\n if (isFunction) {\n \/\/ For functions, we look to merge functions definitions of \"int (...)\"\n \/\/ to 'int (int)' or 'int ()' or whatever else is not completely generic.\n \/\/\n Function *F = cast<Function>(Globals[i]);\n if (!F->isExternal()) {\n if (Concrete && !Concrete->isExternal())\n return false; \/\/ Found two different functions types. Can't choose!\n \n Concrete = Globals[i];\n } else if (Concrete) {\n if (Concrete->isExternal()) \/\/ If we have multiple external symbols...x\n if (F->getFunctionType()->getNumParams() > \n cast<Function>(Concrete)->getFunctionType()->getNumParams())\n Concrete = F; \/\/ We are more concrete than \"Concrete\"!\n\n } else {\n Concrete = F;\n }\n } else {\n \/\/ For global variables, we have to merge C definitions int A[][4] with\n \/\/ int[6][4]. A[][4] is represented as A[0][4] by the CFE.\n GlobalVariable *GV = cast<GlobalVariable>(Globals[i]);\n if (!isa<ArrayType>(GV->getType()->getElementType())) {\n Concrete = 0;\n break; \/\/ Non array's cannot be compatible with other types.\n } else if (Concrete == 0) {\n Concrete = GV;\n } else {\n \/\/ Must have different types... allow merging A[0][4] w\/ A[6][4] if\n \/\/ A[0][4] is external.\n const ArrayType *NAT = cast<ArrayType>(GV->getType()->getElementType());\n const ArrayType *CAT =\n cast<ArrayType>(Concrete->getType()->getElementType());\n\n if (NAT->getElementType() != CAT->getElementType()) {\n Concrete = 0; \/\/ Non-compatible types\n break;\n } else if (NAT->getNumElements() == 0 && GV->isExternal()) {\n \/\/ Concrete remains the same\n } else if (CAT->getNumElements() == 0 && Concrete->isExternal()) {\n Concrete = GV; \/\/ Concrete becomes GV\n } else {\n Concrete = 0; \/\/ Cannot merge these types...\n break;\n }\n }\n }\n ++i;\n }\n\n if (Globals.size() > 1) { \/\/ Found a multiply defined global...\n \/\/ If there are no external declarations, and there is at most one\n \/\/ externally visible instance of the global, then there is nothing to do.\n \/\/\n bool HasExternal = false;\n unsigned NumInstancesWithExternalLinkage = 0;\n\n for (unsigned i = 0, e = Globals.size(); i != e; ++i) {\n if (Globals[i]->isExternal())\n HasExternal = true;\n else if (!Globals[i]->hasInternalLinkage())\n NumInstancesWithExternalLinkage++;\n }\n \n if (!HasExternal && NumInstancesWithExternalLinkage <= 1)\n return false; \/\/ Nothing to do? Must have multiple internal definitions.\n\n\n \/\/ We should find exactly one concrete function definition, which is\n \/\/ probably the implementation. Change all of the function definitions and\n \/\/ uses to use it instead.\n \/\/\n if (!Concrete) {\n std::cerr << \"WARNING: Found global types that are not compatible:\\n\";\n for (unsigned i = 0; i < Globals.size(); ++i) {\n std::cerr << \"\\t\" << Globals[i]->getType()->getDescription() << \" %\"\n << Globals[i]->getName() << \"\\n\";\n }\n std::cerr << \" No linkage of globals named '\" << Globals[0]->getName()\n << \"' performed!\\n\";\n return false;\n }\n\n if (isFunction)\n return ResolveFunctions(M, Globals, cast<Function>(Concrete));\n else\n return ResolveGlobalVariables(M, Globals,\n cast<GlobalVariable>(Concrete));\n }\n return false;\n}\n\nbool FunctionResolvingPass::run(Module &M) {\n SymbolTable &ST = M.getSymbolTable();\n\n std::map<std::string, std::vector<GlobalValue*> > Globals;\n\n \/\/ Loop over the entries in the symbol table. If an entry is a func pointer,\n \/\/ then add it to the Functions map. We do a two pass algorithm here to avoid\n \/\/ problems with iterators getting invalidated if we did a one pass scheme.\n \/\/\n for (SymbolTable::iterator I = ST.begin(), E = ST.end(); I != E; ++I)\n if (const PointerType *PT = dyn_cast<PointerType>(I->first)) {\n SymbolTable::VarMap &Plane = I->second;\n for (SymbolTable::type_iterator PI = Plane.begin(), PE = Plane.end();\n PI != PE; ++PI) {\n GlobalValue *GV = cast<GlobalValue>(PI->second);\n assert(PI->first == GV->getName() &&\n \"Global name and symbol table do not agree!\");\n Globals[PI->first].push_back(GV);\n }\n }\n\n bool Changed = false;\n\n \/\/ Now we have a list of all functions with a particular name. If there is\n \/\/ more than one entry in a list, merge the functions together.\n \/\/\n for (std::map<std::string, std::vector<GlobalValue*> >::iterator\n I = Globals.begin(), E = Globals.end(); I != E; ++I)\n Changed |= ProcessGlobalsWithSameName(M, I->second);\n\n \/\/ Now loop over all of the globals, checking to see if any are trivially\n \/\/ dead. If so, remove them now.\n\n for (Module::iterator I = M.begin(), E = M.end(); I != E; )\n if (I->isExternal() && I->use_empty()) {\n Function *F = I;\n ++I;\n M.getFunctionList().erase(F);\n ++NumResolved;\n Changed = true;\n } else {\n ++I;\n }\n\n for (Module::giterator I = M.gbegin(), E = M.gend(); I != E; )\n if (I->isExternal() && I->use_empty()) {\n GlobalVariable *GV = I;\n ++I;\n M.getGlobalList().erase(GV);\n ++NumGlobals;\n Changed = true;\n } else {\n ++I;\n }\n\n return Changed;\n}\n<commit_msg>Fix bug: FunctionResolve\/2003-10-21-GlobalTypeDifference.ll<commit_after>\/\/===- FunctionResolution.cpp - Resolve declarations to implementations ---===\/\/\n\/\/ \n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file was developed by the LLVM research group and is distributed under\n\/\/ the University of Illinois Open Source License. See LICENSE.TXT for details.\n\/\/ \n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ Loop over the functions that are in the module and look for functions that\n\/\/ have the same name. More often than not, there will be things like:\n\/\/\n\/\/ declare void %foo(...)\n\/\/ void %foo(int, int) { ... }\n\/\/\n\/\/ because of the way things are declared in C. If this is the case, patch\n\/\/ things up.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/Transforms\/IPO.h\"\n#include \"llvm\/Module.h\"\n#include \"llvm\/SymbolTable.h\"\n#include \"llvm\/DerivedTypes.h\"\n#include \"llvm\/Pass.h\"\n#include \"llvm\/iOther.h\"\n#include \"llvm\/Constants.h\"\n#include \"llvm\/Assembly\/Writer.h\"\n#include \"Support\/Statistic.h\"\n#include <algorithm>\n\nnamespace {\n Statistic<>NumResolved(\"funcresolve\", \"Number of varargs functions resolved\");\n Statistic<> NumGlobals(\"funcresolve\", \"Number of global variables resolved\");\n\n struct FunctionResolvingPass : public Pass {\n bool run(Module &M);\n };\n RegisterOpt<FunctionResolvingPass> X(\"funcresolve\", \"Resolve Functions\");\n}\n\nPass *createFunctionResolvingPass() {\n return new FunctionResolvingPass();\n}\n\nstatic bool ResolveFunctions(Module &M, std::vector<GlobalValue*> &Globals,\n Function *Concrete) {\n bool Changed = false;\n for (unsigned i = 0; i != Globals.size(); ++i)\n if (Globals[i] != Concrete) {\n Function *Old = cast<Function>(Globals[i]);\n const FunctionType *OldMT = Old->getFunctionType();\n const FunctionType *ConcreteMT = Concrete->getFunctionType();\n \n if (OldMT->getParamTypes().size() > ConcreteMT->getParamTypes().size() &&\n !ConcreteMT->isVarArg())\n if (!Old->use_empty()) {\n std::cerr << \"WARNING: Linking function '\" << Old->getName()\n << \"' is causing arguments to be dropped.\\n\";\n std::cerr << \"WARNING: Prototype: \";\n WriteAsOperand(std::cerr, Old);\n std::cerr << \" resolved to \";\n WriteAsOperand(std::cerr, Concrete);\n std::cerr << \"\\n\";\n }\n \n \/\/ Check to make sure that if there are specified types, that they\n \/\/ match...\n \/\/\n unsigned NumArguments = std::min(OldMT->getParamTypes().size(),\n ConcreteMT->getParamTypes().size());\n\n if (!Old->use_empty() && !Concrete->use_empty())\n for (unsigned i = 0; i < NumArguments; ++i)\n if (OldMT->getParamTypes()[i] != ConcreteMT->getParamTypes()[i])\n if (OldMT->getParamTypes()[i]->getPrimitiveID() != \n ConcreteMT->getParamTypes()[i]->getPrimitiveID()) {\n std::cerr << \"WARNING: Function [\" << Old->getName()\n << \"]: Parameter types conflict for: '\" << OldMT\n << \"' and '\" << ConcreteMT << \"'\\n\";\n return Changed;\n }\n \n \/\/ Attempt to convert all of the uses of the old function to the concrete\n \/\/ form of the function. If there is a use of the fn that we don't\n \/\/ understand here we punt to avoid making a bad transformation.\n \/\/\n \/\/ At this point, we know that the return values are the same for our two\n \/\/ functions and that the Old function has no varargs fns specified. In\n \/\/ otherwords it's just <retty> (...)\n \/\/\n if (!Old->use_empty()) { \/\/ Avoid making the CPR unless we really need it\n Value *Replacement = Concrete;\n if (Concrete->getType() != Old->getType())\n Replacement = ConstantExpr::getCast(ConstantPointerRef::get(Concrete),\n Old->getType());\n NumResolved += Old->use_size();\n Old->replaceAllUsesWith(Replacement);\n }\n\n \/\/ Since there are no uses of Old anymore, remove it from the module.\n M.getFunctionList().erase(Old);\n }\n return Changed;\n}\n\n\nstatic bool ResolveGlobalVariables(Module &M,\n std::vector<GlobalValue*> &Globals,\n GlobalVariable *Concrete) {\n bool Changed = false;\n Constant *CCPR = ConstantPointerRef::get(Concrete);\n\n for (unsigned i = 0; i != Globals.size(); ++i)\n if (Globals[i] != Concrete) {\n Constant *Cast = ConstantExpr::getCast(CCPR, Globals[i]->getType());\n Globals[i]->replaceAllUsesWith(Cast);\n\n \/\/ Since there are no uses of Old anymore, remove it from the module.\n M.getGlobalList().erase(cast<GlobalVariable>(Globals[i]));\n\n ++NumGlobals;\n Changed = true;\n }\n return Changed;\n}\n\nstatic bool ProcessGlobalsWithSameName(Module &M,\n std::vector<GlobalValue*> &Globals) {\n assert(!Globals.empty() && \"Globals list shouldn't be empty here!\");\n\n bool isFunction = isa<Function>(Globals[0]); \/\/ Is this group all functions?\n GlobalValue *Concrete = 0; \/\/ The most concrete implementation to resolve to\n\n assert((isFunction ^ isa<GlobalVariable>(Globals[0])) &&\n \"Should either be function or gvar!\");\n\n for (unsigned i = 0; i != Globals.size(); ) {\n if (isa<Function>(Globals[i]) != isFunction) {\n std::cerr << \"WARNING: Found function and global variable with the \"\n << \"same name: '\" << Globals[i]->getName() << \"'.\\n\";\n return false; \/\/ Don't know how to handle this, bail out!\n }\n\n if (isFunction) {\n \/\/ For functions, we look to merge functions definitions of \"int (...)\"\n \/\/ to 'int (int)' or 'int ()' or whatever else is not completely generic.\n \/\/\n Function *F = cast<Function>(Globals[i]);\n if (!F->isExternal()) {\n if (Concrete && !Concrete->isExternal())\n return false; \/\/ Found two different functions types. Can't choose!\n \n Concrete = Globals[i];\n } else if (Concrete) {\n if (Concrete->isExternal()) \/\/ If we have multiple external symbols...x\n if (F->getFunctionType()->getNumParams() > \n cast<Function>(Concrete)->getFunctionType()->getNumParams())\n Concrete = F; \/\/ We are more concrete than \"Concrete\"!\n\n } else {\n Concrete = F;\n }\n } else {\n GlobalVariable *GV = cast<GlobalVariable>(Globals[i]);\n if (!GV->isExternal()) {\n if (Concrete) {\n std::cerr << \"WARNING: Two global variables with external linkage\"\n << \" exist with the same name: '\" << GV->getName()\n << \"'!\\n\";\n return false;\n }\n Concrete = GV;\n }\n }\n ++i;\n }\n\n if (Globals.size() > 1) { \/\/ Found a multiply defined global...\n \/\/ If there are no external declarations, and there is at most one\n \/\/ externally visible instance of the global, then there is nothing to do.\n \/\/\n bool HasExternal = false;\n unsigned NumInstancesWithExternalLinkage = 0;\n\n for (unsigned i = 0, e = Globals.size(); i != e; ++i) {\n if (Globals[i]->isExternal())\n HasExternal = true;\n else if (!Globals[i]->hasInternalLinkage())\n NumInstancesWithExternalLinkage++;\n }\n \n if (!HasExternal && NumInstancesWithExternalLinkage <= 1)\n return false; \/\/ Nothing to do? Must have multiple internal definitions.\n\n\n std::cerr << \"WARNING: Found global types that are not compatible:\\n\";\n for (unsigned i = 0; i < Globals.size(); ++i) {\n std::cerr << \"\\t\" << *Globals[i]->getType() << \" %\"\n << Globals[i]->getName() << \"\\n\";\n }\n\n if (!Concrete)\n Concrete = Globals[0];\n\n if (isFunction)\n return ResolveFunctions(M, Globals, cast<Function>(Concrete));\n else\n return ResolveGlobalVariables(M, Globals,\n cast<GlobalVariable>(Concrete));\n }\n return false;\n}\n\nbool FunctionResolvingPass::run(Module &M) {\n SymbolTable &ST = M.getSymbolTable();\n\n std::map<std::string, std::vector<GlobalValue*> > Globals;\n\n \/\/ Loop over the entries in the symbol table. If an entry is a func pointer,\n \/\/ then add it to the Functions map. We do a two pass algorithm here to avoid\n \/\/ problems with iterators getting invalidated if we did a one pass scheme.\n \/\/\n for (SymbolTable::iterator I = ST.begin(), E = ST.end(); I != E; ++I)\n if (const PointerType *PT = dyn_cast<PointerType>(I->first)) {\n SymbolTable::VarMap &Plane = I->second;\n for (SymbolTable::type_iterator PI = Plane.begin(), PE = Plane.end();\n PI != PE; ++PI) {\n GlobalValue *GV = cast<GlobalValue>(PI->second);\n assert(PI->first == GV->getName() &&\n \"Global name and symbol table do not agree!\");\n if (!GV->hasInternalLinkage())\n Globals[PI->first].push_back(GV);\n }\n }\n\n bool Changed = false;\n\n \/\/ Now we have a list of all functions with a particular name. If there is\n \/\/ more than one entry in a list, merge the functions together.\n \/\/\n for (std::map<std::string, std::vector<GlobalValue*> >::iterator\n I = Globals.begin(), E = Globals.end(); I != E; ++I)\n Changed |= ProcessGlobalsWithSameName(M, I->second);\n\n \/\/ Now loop over all of the globals, checking to see if any are trivially\n \/\/ dead. If so, remove them now.\n\n for (Module::iterator I = M.begin(), E = M.end(); I != E; )\n if (I->isExternal() && I->use_empty()) {\n Function *F = I;\n ++I;\n M.getFunctionList().erase(F);\n ++NumResolved;\n Changed = true;\n } else {\n ++I;\n }\n\n for (Module::giterator I = M.gbegin(), E = M.gend(); I != E; )\n if (I->isExternal() && I->use_empty()) {\n GlobalVariable *GV = I;\n ++I;\n M.getGlobalList().erase(GV);\n ++NumGlobals;\n Changed = true;\n } else {\n ++I;\n }\n\n return Changed;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*===================================================================\n\nThe Medical Imaging Interaction Toolkit (MITK)\n\nCopyright (c) German Cancer Research Center,\nDivision of Medical and Biological Informatics.\nAll rights reserved.\n\nThis software is distributed WITHOUT ANY WARRANTY; without\neven the implied warranty of MERCHANTABILITY or FITNESS FOR\nA PARTICULAR PURPOSE.\n\nSee LICENSE.txt or http:\/\/www.mitk.org for details.\n\n===================================================================*\/\n\n\n#ifndef MITKDIFFUSIONIMAGETODIFFUSIONIMAGEFILTER_CPP\n#define MITKDIFFUSIONIMAGETODIFFUSIONIMAGEFILTER_CPP\n\n#include \"mitkDWIHeadMotionCorrectionFilter.h\"\n\n#include \"itkSplitDWImageFilter.h\"\n#include \"itkB0ImageExtractionToSeparateImageFilter.h\"\n\n#include \"mitkImageTimeSelector.h\"\n\n#include \"mitkPyramidImageRegistrationMethod.h\"\n#include \"mitkImageToDiffusionImageSource.h\"\n\n#include \"mitkIOUtil.h\"\n\ntemplate< typename DiffusionPixelType>\nmitk::DWIHeadMotionCorrectionFilter<DiffusionPixelType>\n::DWIHeadMotionCorrectionFilter()\n{\n\n}\n\ntemplate< typename DiffusionPixelType>\nvoid mitk::DWIHeadMotionCorrectionFilter<DiffusionPixelType>\n::GenerateData()\n{\n typedef itk::SplitDWImageFilter< DiffusionPixelType, DiffusionPixelType> SplitFilterType;\n\n DiffusionImageType* input = const_cast<DiffusionImageType*>(this->GetInput(0));\n\n \/\/\n \/\/ (1) Extract the b-zero images to a 3d+t image, register them by NCorr metric and\n \/\/ rigid registration : they will then be used are reference image for registering\n \/\/ the gradient images\n \/\/\n typedef itk::B0ImageExtractionToSeparateImageFilter< DiffusionPixelType, DiffusionPixelType> B0ExtractorType;\n typename B0ExtractorType::Pointer b0_extractor = B0ExtractorType::New();\n b0_extractor->SetInput( input->GetVectorImage() );\n b0_extractor->SetDirections( input->GetDirections() );\n b0_extractor->Update();\n\n mitk::Image::Pointer b0Image = mitk::Image::New();\n b0Image->InitializeByItk( b0_extractor->GetOutput() );\n b0Image->SetImportChannel( b0_extractor->GetOutput()->GetBufferPointer(),\n mitk::Image::CopyMemory );\n\n \/\/ (2.1) Use the extractor to access the extracted b0 volumes\n mitk::ImageTimeSelector::Pointer t_selector =\n mitk::ImageTimeSelector::New();\n\n t_selector->SetInput( b0Image );\n t_selector->SetTimeNr(0);\n t_selector->Update();\n\n \/\/ first unweighted image as reference space for the registration\n mitk::Image::Pointer b0referenceImage = t_selector->GetOutput();\n\n mitk::PyramidImageRegistrationMethod::Pointer registrationMethod = mitk::PyramidImageRegistrationMethod::New();\n registrationMethod->SetFixedImage( b0referenceImage );\n registrationMethod->SetTransformToRigid();\n\n \/\/ the unweighted images are of same modality\n registrationMethod->SetCrossModalityOff();\n\n \/\/ Initialize the temporary output image\n mitk::Image::Pointer registeredB0Image = b0Image->Clone();\n const unsigned int numberOfb0Images = b0Image->GetTimeSteps();\n\n mitk::ImageTimeSelector::Pointer t_selector2 =\n mitk::ImageTimeSelector::New();\n\n t_selector2->SetInput( b0Image );\n\n for( unsigned int i=1; i<numberOfb0Images; i++)\n {\n\n t_selector2->SetTimeNr(i);\n t_selector2->Update();\n\n registrationMethod->SetMovingImage( t_selector2->GetOutput() );\n\n try\n {\n MITK_INFO << \" === (\" << i <<\"\/\"<< numberOfb0Images-1 << \") :: Starting registration\";\n registrationMethod->Update();\n }\n catch( const itk::ExceptionObject& e)\n {\n mitkThrow() << \"Failed to register the b0 images, the PyramidRegistration threw an exception: \\n\" << e.what();\n }\n\n \/\/ import volume to the inter-results\n registeredB0Image->SetImportVolume( registrationMethod->GetResampledMovingImage()->GetData(),\n i, 0, mitk::Image::ReferenceMemory );\n\n }\n\n\n \/\/\n \/\/ (2) Split the diffusion image into a 3d+t regular image, extract only the weighted images\n \/\/\n typename SplitFilterType::Pointer split_filter = SplitFilterType::New();\n split_filter->SetInput (input->GetVectorImage() );\n split_filter->SetExtractAllAboveThreshold(20, input->GetB_ValueMap() );\n\n try\n {\n split_filter->Update();\n }\n catch( const itk::ExceptionObject &e)\n {\n mitkThrow() << \" Caught exception from SplitImageFilter : \" << e.what();\n }\n\n mitk::Image::Pointer splittedImage = mitk::Image::New();\n splittedImage->InitializeByItk( split_filter->GetOutput() );\n splittedImage->SetImportChannel( split_filter->GetOutput()->GetBufferPointer(),\n mitk::Image::CopyMemory );\n\n\n \/\/\n \/\/ (3) Use again the time-selector to access the components separately in order\n \/\/ to perform the registration of Image -> unweighted reference\n \/\/\n\n mitk::PyramidImageRegistrationMethod::Pointer weightedRegistrationMethod\n = mitk::PyramidImageRegistrationMethod::New();\n\n weightedRegistrationMethod->SetTransformToAffine();\n weightedRegistrationMethod->SetCrossModalityOn();\n \/\/\n \/\/ - (3.1) Create a reference image by averaging the aligned b0 images\n \/\/\n \/\/ !!!FIXME: For rapid prototyping using the first one\n \/\/\n\n weightedRegistrationMethod->SetFixedImage( b0referenceImage );\n\n \/\/\n \/\/ - (3.2) Register all timesteps in the splitted image onto the first reference\n \/\/\n unsigned int maxImageIdx = splittedImage->GetTimeSteps();\n mitk::TimeSlicedGeometry* tsg = splittedImage->GetTimeSlicedGeometry();\n tsg->ExpandToNumberOfTimeSteps( maxImageIdx+1 );\n\n mitk::Image::Pointer registeredWeighted = mitk::Image::New();\n registeredWeighted->Initialize( splittedImage->GetPixelType(0), *tsg );\n\n \/\/ insert the first unweighted reference as the first volume\n registeredWeighted->SetImportVolume( b0referenceImage->GetData(),\n 0,0, mitk::Image::CopyMemory );\n\n\n \/\/ mitk::Image::Pointer registeredWeighted = splittedImage->Clone();\n \/\/ this time start at 0, we have only gradient images in the 3d+t file\n \/\/ the reference image comes form an other image\n mitk::ImageTimeSelector::Pointer t_selector_w =\n mitk::ImageTimeSelector::New();\n\n t_selector_w->SetInput( splittedImage );\n\n for( unsigned int i=0; i<maxImageIdx; i++)\n {\n t_selector_w->SetTimeNr(i);\n t_selector_w->Update();\n\n weightedRegistrationMethod->SetMovingImage( t_selector_w->GetOutput() );\n\n try\n {\n MITK_INFO << \" === (\" << i+1 <<\"\/\"<< maxImageIdx << \") :: Starting registration\";\n weightedRegistrationMethod->Update();\n }\n catch( const itk::ExceptionObject& e)\n {\n mitkThrow() << \"Failed to register the b0 images, the PyramidRegistration threw an exception: \\n\" << e.what();\n }\n\n \/\/ allow expansion\n registeredWeighted->SetImportVolume( weightedRegistrationMethod->GetResampledMovingImage()->GetData(),\n i+1, 0, mitk::Image::CopyMemory);\n }\n\n\n \/\/\n \/\/ (4) Cast the resulting image back to an diffusion weighted image\n \/\/\n\n typename DiffusionImageType::GradientDirectionContainerType *gradients = input->GetDirections();\n typename DiffusionImageType::GradientDirectionContainerType::Pointer gradients_new =\n DiffusionImageType::GradientDirectionContainerType::New();\n typename DiffusionImageType::GradientDirectionType bzero_vector;\n bzero_vector.fill(0);\n \/\/ compose the direction vector\n \/\/ - no direction for the first image\n \/\/ - correct ordering of the directions based on the index list\n gradients_new->push_back( bzero_vector );\n\n typename SplitFilterType::IndexListType index_list = split_filter->GetIndexList();\n typename SplitFilterType::IndexListType::const_iterator lIter = index_list.begin();\n\n while( lIter != index_list.end() )\n {\n gradients_new->push_back( gradients->at( *lIter ) );\n ++lIter;\n }\n\n typename mitk::ImageToDiffusionImageSource< DiffusionPixelType >::Pointer caster =\n mitk::ImageToDiffusionImageSource< DiffusionPixelType >::New();\n\n caster->SetImage( registeredWeighted );\n caster->SetBValue( input->GetB_Value() );\n caster->SetGradientDirections( gradients_new );\n\n try\n {\n caster->Update();\n this->itk::ProcessObject::SetOutput(0 , caster->GetOutput() );\n }\n catch( const itk::ExceptionObject& e)\n {\n MITK_ERROR << \"Casting back to diffusion image failed: \";\n mitkThrow() << \"Subprocess failed with exception: \" << e.what();\n }\n\n\n}\n\ntemplate< typename DiffusionPixelType>\nvoid mitk::DWIHeadMotionCorrectionFilter<DiffusionPixelType>\n::GenerateOutputInformation()\n{\n if( ! this->GetInput(0) )\n {\n mitkThrow() << \"No input specified!\";\n }\n}\n\n#endif \/\/ MITKDIFFUSIONIMAGETODIFFUSIONIMAGEFILTER_CPP\n<commit_msg>WIP(unstable) Finalizing the head motion correction<commit_after>\/*===================================================================\n\nThe Medical Imaging Interaction Toolkit (MITK)\n\nCopyright (c) German Cancer Research Center,\nDivision of Medical and Biological Informatics.\nAll rights reserved.\n\nThis software is distributed WITHOUT ANY WARRANTY; without\neven the implied warranty of MERCHANTABILITY or FITNESS FOR\nA PARTICULAR PURPOSE.\n\nSee LICENSE.txt or http:\/\/www.mitk.org for details.\n\n===================================================================*\/\n\n\n#ifndef MITKDIFFUSIONIMAGETODIFFUSIONIMAGEFILTER_CPP\n#define MITKDIFFUSIONIMAGETODIFFUSIONIMAGEFILTER_CPP\n\n#include \"mitkDWIHeadMotionCorrectionFilter.h\"\n\n#include \"itkSplitDWImageFilter.h\"\n#include \"itkB0ImageExtractionToSeparateImageFilter.h\"\n\n#include \"mitkImageTimeSelector.h\"\n\n#include \"mitkPyramidImageRegistrationMethod.h\"\n#include \"mitkImageToDiffusionImageSource.h\"\n\n#include \"mitkIOUtil.h\"\n\ntemplate< typename DiffusionPixelType>\nmitk::DWIHeadMotionCorrectionFilter<DiffusionPixelType>\n::DWIHeadMotionCorrectionFilter()\n{\n\n}\n\ntemplate< typename DiffusionPixelType>\nvoid mitk::DWIHeadMotionCorrectionFilter<DiffusionPixelType>\n::GenerateData()\n{\n typedef itk::SplitDWImageFilter< DiffusionPixelType, DiffusionPixelType> SplitFilterType;\n\n DiffusionImageType* input = const_cast<DiffusionImageType*>(this->GetInput(0));\n\n \/\/\n \/\/ (1) Extract the b-zero images to a 3d+t image, register them by NCorr metric and\n \/\/ rigid registration : they will then be used are reference image for registering\n \/\/ the gradient images\n \/\/\n typedef itk::B0ImageExtractionToSeparateImageFilter< DiffusionPixelType, DiffusionPixelType> B0ExtractorType;\n typename B0ExtractorType::Pointer b0_extractor = B0ExtractorType::New();\n b0_extractor->SetInput( input->GetVectorImage() );\n b0_extractor->SetDirections( input->GetDirections() );\n b0_extractor->Update();\n\n mitk::Image::Pointer b0Image = mitk::Image::New();\n b0Image->InitializeByItk( b0_extractor->GetOutput() );\n b0Image->SetImportChannel( b0_extractor->GetOutput()->GetBufferPointer(),\n mitk::Image::CopyMemory );\n\n \/\/ (2.1) Use the extractor to access the extracted b0 volumes\n mitk::ImageTimeSelector::Pointer t_selector =\n mitk::ImageTimeSelector::New();\n\n t_selector->SetInput( b0Image );\n t_selector->SetTimeNr(0);\n t_selector->Update();\n\n \/\/ first unweighted image as reference space for the registration\n mitk::Image::Pointer b0referenceImage = t_selector->GetOutput();\n\n mitk::PyramidImageRegistrationMethod::Pointer registrationMethod = mitk::PyramidImageRegistrationMethod::New();\n registrationMethod->SetFixedImage( b0referenceImage );\n registrationMethod->SetTransformToRigid();\n\n \/\/ the unweighted images are of same modality\n registrationMethod->SetCrossModalityOff();\n\n \/\/ Initialize the temporary output image\n mitk::Image::Pointer registeredB0Image = b0Image->Clone();\n const unsigned int numberOfb0Images = b0Image->GetTimeSteps();\n\n mitk::ImageTimeSelector::Pointer t_selector2 =\n mitk::ImageTimeSelector::New();\n\n t_selector2->SetInput( b0Image );\n\n for( unsigned int i=1; i<numberOfb0Images; i++)\n {\n\n t_selector2->SetTimeNr(i);\n t_selector2->Update();\n\n registrationMethod->SetMovingImage( t_selector2->GetOutput() );\n\n try\n {\n MITK_INFO << \" === (\" << i <<\"\/\"<< numberOfb0Images-1 << \") :: Starting registration\";\n registrationMethod->Update();\n }\n catch( const itk::ExceptionObject& e)\n {\n mitkThrow() << \"Failed to register the b0 images, the PyramidRegistration threw an exception: \\n\" << e.what();\n }\n\n \/\/ import volume to the inter-results\n registeredB0Image->SetImportVolume( registrationMethod->GetResampledMovingImage()->GetData(),\n i, 0, mitk::Image::ReferenceMemory );\n\n }\n\n\n \/\/\n \/\/ (2) Split the diffusion image into a 3d+t regular image, extract only the weighted images\n \/\/\n typename SplitFilterType::Pointer split_filter = SplitFilterType::New();\n split_filter->SetInput (input->GetVectorImage() );\n split_filter->SetExtractAllAboveThreshold(20, input->GetB_ValueMap() );\n\n try\n {\n split_filter->Update();\n }\n catch( const itk::ExceptionObject &e)\n {\n mitkThrow() << \" Caught exception from SplitImageFilter : \" << e.what();\n }\n\n mitk::Image::Pointer splittedImage = mitk::Image::New();\n splittedImage->InitializeByItk( split_filter->GetOutput() );\n splittedImage->SetImportChannel( split_filter->GetOutput()->GetBufferPointer(),\n mitk::Image::CopyMemory );\n\n\n \/\/\n \/\/ (3) Use again the time-selector to access the components separately in order\n \/\/ to perform the registration of Image -> unweighted reference\n \/\/\n\n mitk::PyramidImageRegistrationMethod::Pointer weightedRegistrationMethod\n = mitk::PyramidImageRegistrationMethod::New();\n\n weightedRegistrationMethod->SetTransformToAffine();\n weightedRegistrationMethod->SetCrossModalityOn();\n \/\/\n \/\/ - (3.1) Create a reference image by averaging the aligned b0 images\n \/\/\n \/\/ !!!FIXME: For rapid prototyping using the first one\n \/\/\n\n weightedRegistrationMethod->SetFixedImage( b0referenceImage );\n\n \/\/\n \/\/ - (3.2) Register all timesteps in the splitted image onto the first reference\n \/\/\n unsigned int maxImageIdx = splittedImage->GetTimeSteps();\n mitk::TimeSlicedGeometry* tsg = splittedImage->GetTimeSlicedGeometry();\n tsg->ExpandToNumberOfTimeSteps( maxImageIdx+1 );\n\n mitk::Image::Pointer registeredWeighted = mitk::Image::New();\n registeredWeighted->Initialize( splittedImage->GetPixelType(0), *tsg );\n\n \/\/ insert the first unweighted reference as the first volume\n registeredWeighted->SetImportVolume( b0referenceImage->GetData(),\n 0,0, mitk::Image::CopyMemory );\n\n\n \/\/ mitk::Image::Pointer registeredWeighted = splittedImage->Clone();\n \/\/ this time start at 0, we have only gradient images in the 3d+t file\n \/\/ the reference image comes form an other image\n mitk::ImageTimeSelector::Pointer t_selector_w =\n mitk::ImageTimeSelector::New();\n\n t_selector_w->SetInput( splittedImage );\n\n for( unsigned int i=0; i<maxImageIdx; i++)\n {\n t_selector_w->SetTimeNr(i);\n t_selector_w->Update();\n\n weightedRegistrationMethod->SetMovingImage( t_selector_w->GetOutput() );\n\n try\n {\n MITK_INFO << \" === (\" << i+1 <<\"\/\"<< maxImageIdx << \") :: Starting registration\";\n weightedRegistrationMethod->Update();\n }\n catch( const itk::ExceptionObject& e)\n {\n mitkThrow() << \"Failed to register the b0 images, the PyramidRegistration threw an exception: \\n\" << e.what();\n }\n\n \/\/ allow expansion\n registeredWeighted->SetImportVolume( weightedRegistrationMethod->GetResampledMovingImage()->GetData(),\n i+1, 0, mitk::Image::CopyMemory);\n }\n\n\n \/\/\n \/\/ (4) Cast the resulting image back to an diffusion weighted image\n \/\/\n\n typename DiffusionImageType::GradientDirectionContainerType *gradients = input->GetDirections();\n typename DiffusionImageType::GradientDirectionContainerType::Pointer gradients_new =\n DiffusionImageType::GradientDirectionContainerType::New();\n typename DiffusionImageType::GradientDirectionType bzero_vector;\n bzero_vector.fill(0);\n \/\/ compose the direction vector\n \/\/ - no direction for the first image\n \/\/ - correct ordering of the directions based on the index list\n gradients_new->push_back( bzero_vector );\n\n typename SplitFilterType::IndexListType index_list = split_filter->GetIndexList();\n typename SplitFilterType::IndexListType::const_iterator lIter = index_list.begin();\n\n while( lIter != index_list.end() )\n {\n gradients_new->push_back( gradients->at( *lIter ) );\n ++lIter;\n }\n\n typename mitk::ImageToDiffusionImageSource< DiffusionPixelType >::Pointer caster =\n mitk::ImageToDiffusionImageSource< DiffusionPixelType >::New();\n\n caster->SetImage( registeredWeighted );\n caster->SetBValue( input->GetB_Value() );\n caster->SetGradientDirections( gradients_new.GetPointer() );\n\n try\n {\n caster->Update();\n }\n catch( const itk::ExceptionObject& e)\n {\n MITK_ERROR << \"Casting back to diffusion image failed: \";\n mitkThrow() << \"Subprocess failed with exception: \" << e.what();\n }\n\n \/\/\n \/\/ FIXME!!! EXTREME QUICK-HACK\n\n typedef typename mitk::DiffusionImageSource< DiffusionPixelType>::OutputType OutputType;\n\n DiffusionImageType* dwimageout =\n static_cast<DiffusionImageType*>( caster->GetOutput() );\n\n static_cast<OutputType*>(this->GetOutput())\n ->SetVectorImage(dwimageout->GetVectorImage());\n static_cast<OutputType*>(this->GetOutput())\n ->SetB_Value(dwimageout->GetB_Value());\n static_cast<OutputType*>(this->GetOutput())\n ->SetDirections(dwimageout->GetDirections());\n static_cast<OutputType*>(this->GetOutput())\n ->SetMeasurementFrame(dwimageout->GetMeasurementFrame());\n static_cast<OutputType*>(this->GetOutput())->InitializeFromVectorImage();\n\n\n}\n\ntemplate< typename DiffusionPixelType>\nvoid mitk::DWIHeadMotionCorrectionFilter<DiffusionPixelType>\n::GenerateOutputInformation()\n{\n if( ! this->GetInput(0) )\n {\n mitkThrow() << \"No input specified!\";\n }\n}\n\n#endif \/\/ MITKDIFFUSIONIMAGETODIFFUSIONIMAGEFILTER_CPP\n<|endoftext|>"} {"text":"<commit_before>\/*****************************************************************************\n *\n * This file is part of Mapnik (c++ mapping toolkit)\n *\n * Copyright (C) 2014 Artem Pavlenko\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n *\n *****************************************************************************\/\n\n#ifndef MAPNIK_IMAGE_ANY_HPP\n#define MAPNIK_IMAGE_ANY_HPP\n\n#include <mapnik\/image.hpp>\n#include <mapnik\/image_null.hpp>\n#include <mapnik\/util\/variant.hpp>\n\nnamespace mapnik {\n\nusing image_base = util::variant<image_null, \n image_rgba8, \n image_gray8, \n image_gray8s, \n image_gray16, \n image_gray16s, \n image_gray32, \n image_gray32s, \n image_gray32f,\n image_gray64, \n image_gray64s, \n image_gray64f>;\n\n\nstruct MAPNIK_DECL image_any : image_base\n{\n image_any() = default;\n\n image_any(int width,\n int height,\n image_dtype type = image_dtype_rgba8,\n bool initialize = true, \n bool premultiplied = false, \n bool painted = false);\n\n template <typename T>\n image_any(T && data) noexcept\n : image_base(std::move(data)) {}\n\n unsigned char const* getBytes() const;\n unsigned char* getBytes();\n std::size_t width() const;\n std::size_t height() const;\n bool get_premultiplied() const;\n bool painted() const;\n unsigned getSize() const;\n unsigned getRowSize() const;\n double get_offset() const;\n double get_scaling() const;\n image_dtype get_dtype() const;\n void set_offset(double val);\n void set_scaling(double val);\n};\n\nimage_any create_image_any(int width, \n int height, \n image_dtype type = image_dtype_rgba8,\n bool initialize = true, \n bool premultiplied = false, \n bool painted = false);\n\n} \/\/ end mapnik ns\n\n#endif \/\/ MAPNIK_IMAGE_ANY_HPP\n<commit_msg>Possibly fixing windows issues<commit_after>\/*****************************************************************************\n *\n * This file is part of Mapnik (c++ mapping toolkit)\n *\n * Copyright (C) 2014 Artem Pavlenko\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n *\n *****************************************************************************\/\n\n#ifndef MAPNIK_IMAGE_ANY_HPP\n#define MAPNIK_IMAGE_ANY_HPP\n\n#include <mapnik\/image.hpp>\n#include <mapnik\/image_null.hpp>\n#include <mapnik\/util\/variant.hpp>\n\nnamespace mapnik {\n\nusing image_base = util::variant<image_null, \n image_rgba8, \n image_gray8, \n image_gray8s, \n image_gray16, \n image_gray16s, \n image_gray32, \n image_gray32s, \n image_gray32f,\n image_gray64, \n image_gray64s, \n image_gray64f>;\n\n\nstruct MAPNIK_DECL image_any : image_base\n{\n image_any() = default;\n\n image_any(int width,\n int height,\n image_dtype type = image_dtype_rgba8,\n bool initialize = true, \n bool premultiplied = false, \n bool painted = false);\n\n template <typename T>\n image_any(T && data) noexcept\n : image_base(std::move(data)) {}\n\n unsigned char const* getBytes() const;\n unsigned char* getBytes();\n std::size_t width() const;\n std::size_t height() const;\n bool get_premultiplied() const;\n bool painted() const;\n unsigned getSize() const;\n unsigned getRowSize() const;\n double get_offset() const;\n double get_scaling() const;\n image_dtype get_dtype() const;\n void set_offset(double val);\n void set_scaling(double val);\n};\n\nMAPNIK_DECL image_any create_image_any(int width, \n int height, \n image_dtype type = image_dtype_rgba8,\n bool initialize = true, \n bool premultiplied = false, \n bool painted = false);\n\n} \/\/ end mapnik ns\n\n#endif \/\/ MAPNIK_IMAGE_ANY_HPP\n<|endoftext|>"} {"text":"<commit_before>\/*\n * MyManageType.cpp\n *\n * Created on: 2015年12月27日\n * Author: moss\n *\/\n\n#include \"MyManageType.h\"\n#include \"MyParseKey.h\"\nMyManageType::MyManageType() {\n\n\n}\n\nMyManageType::~MyManageType() {\n\n}\nconst std::string& MyManageType::getObjectTypeName() {\n\tstatic std::string typeStr(MY_MANAGE_TYPE);\n\treturn typeStr;\n}\nbool MyManageType::onGetIDByType(khala::InfoNodePtr& infoNodePtr,\n\t\tJson::Value& msg, khala::Timestamp time) {\n\tstd::vector<uint> v = this->getNodeManager()->getNodeIDs(\n\t\t\tinfoNodePtr->getNodeType());\n\tstd::stringstream ss;\n\tss << \"Get ID By Type:Ask type:\" << infoNodePtr->getNodeType()\n\t\t\t<< \" . Get ID:\";\n\tfor (std::vector<uint>::iterator it = v.begin(); it != v.end(); ++it) {\n\t\tss << *it << \" \";\n\t}\n\tinfoNodePtr->send(ss.str());\n\treturn true;\n}\nbool MyManageType::onGetIDByObject(khala::InfoNodePtr& infoNodePtr,\n\t\tJson::Value& msg, khala::Timestamp time) {\n\tMyManageType* tmp = new MyManageType();\n\tstd::vector<uint> v = this->getNodeManager()->getNodeIDs(tmp);\n\tstd::stringstream ss;\n\tss << \"Get ID By Object:Ask Object type:\" << tmp->getObjectTypeName()\n\t\t\t<< \" . Get ID:\";\n\tfor (std::vector<uint>::iterator it = v.begin(); it != v.end(); ++it) {\n\t\tss << *it << \" \";\n\t}\n\tinfoNodePtr->send(ss.str());\n\tdelete tmp;\n\treturn true;\n}\nbool MyManageType::onGetAllIDByObject(khala::InfoNodePtr& infoNodePtr,\n\t\tJson::Value& msg, khala::Timestamp time) {\n\tNodeType* tmp = new NodeType();\n\t\/\/parameter is NodeType Object\n\tstd::vector<uint> v = this->getNodeManager()->getAllNodeIDs(*tmp);\n\tstd::stringstream ss;\n\tss << \"Get All ID By Object:Ask Object type:\" << tmp->getObjectTypeName()\n\t\t\t<< \" . Get ID:\";\n\tfor (std::vector<uint>::iterator it = v.begin(); it != v.end(); ++it) {\n\t\tss << *it << \" \";\n\t}\n\tinfoNodePtr->send(ss.str());\n\tdelete tmp;\n\treturn true;\n}\nbool MyManageType::onGetAllIDByObjectPtr(khala::InfoNodePtr& infoNodePtr,\n\t\tJson::Value& msg, khala::Timestamp time) {\n\tNodeType* tmp = new NodeType();\n\t\/\/parameter is NodeType Object pointor\n\tstd::vector<uint> v = this->getNodeManager()->getAllNodeIDs(tmp);\n\tstd::stringstream ss;\n\tss << \"Get All ID By Object ptr:Ask Object type:\"\n\t\t\t<< tmp->getObjectTypeName() << \" . Get ID:\";\n\tfor (std::vector<uint>::iterator it = v.begin(); it != v.end(); ++it) {\n\t\tss << *it << \" \";\n\t}\n\tinfoNodePtr->send(ss.str());\n\tdelete tmp;\n\treturn true;\n}\nbool MyManageType::onAskLogin(khala::InfoNodePtr& infoNodePtr, Json::Value& msg,\n\t\tkhala::Timestamp time){\n\tuint friendId = msg[KEY_FRIEND_ID].asUInt();\n\tstd::stringstream ss;\n\tss<<\"Node ID:\"<<friendId;\n\tif(this->getNodeManager()->hasNode(friendId)){\n\t\tss<<\" is login!\";\n\t}else{\n\t\tss<<\" is not login!\";\n\t}\n\tinfoNodePtr->send(ss.str());\n\treturn true;\n}\nbool MyManageType::onSendtoNode(khala::InfoNodePtr& infoNodePtr,\n\t\tJson::Value& msg, khala::Timestamp time){\n\tuint myId = infoNodePtr->getId();\n\tkhala::InfoNodePtr myInfoNodePtr;\n\tif(this->getNodeManager()->find(myId, myInfoNodePtr)){\n\t\tmyInfoNodePtr->send(\"test manager find success\");\n\t}\n\treturn true;\n}\nvoid MyManageType::setRegisterMsg(khala::RegisterHandler& handler){\n\tNodeType::setRegisterMsg(handler);\n\thandler.setRegisterMsg(ID_BY_TYPE,\n\t\t\t\t\tboost::bind(&MyManageType::onGetIDByType, this, _1, _2, _3));\n\thandler.setRegisterMsg(ID_BY_OBJECT,\n\t\t\tboost::bind(&MyManageType::onGetIDByObject, this, _1, _2, _3));\n\thandler.setRegisterMsg(ALL_ID_BY_OBJECT,\n\t\t\t\tboost::bind(&MyManageType::onGetAllIDByObject, this, _1, _2, _3));\n\thandler.setRegisterMsg(ALL_ID_BY_OBJECT_PTR,\n\t\t\t\tboost::bind(&MyManageType::onGetAllIDByObjectPtr, this, _1, _2, _3));\n\thandler.setRegisterMsg(ASK_LOGIN,\n\t\t\t\tboost::bind(&MyManageType::onAskLogin, this, _1, _2, _3));\n\thandler.setRegisterMsg(SEND_MSG,\n\t\t\t\t\tboost::bind(&MyManageType::onSendtoNode, this, _1, _2, _3));\n}\n<commit_msg>添加<sstream>头文件<commit_after>\/*\n * MyManageType.cpp\n *\n * Created on: 2015年12月27日\n * Author: moss\n *\/\n\n#include \"MyManageType.h\"\n#include \"MyParseKey.h\"\n#include <sstream>\nMyManageType::MyManageType() {\n\n\n}\n\nMyManageType::~MyManageType() {\n\n}\nconst std::string& MyManageType::getObjectTypeName() {\n\tstatic std::string typeStr(MY_MANAGE_TYPE);\n\treturn typeStr;\n}\nbool MyManageType::onGetIDByType(khala::InfoNodePtr& infoNodePtr,\n\t\tJson::Value& msg, khala::Timestamp time) {\n\tstd::vector<uint> v = this->getNodeManager()->getNodeIDs(\n\t\t\tinfoNodePtr->getNodeType());\n\tstd::stringstream ss;\n\tss << \"Get ID By Type:Ask type:\" << infoNodePtr->getNodeType()\n\t\t\t<< \" . Get ID:\";\n\tfor (std::vector<uint>::iterator it = v.begin(); it != v.end(); ++it) {\n\t\tss << *it << \" \";\n\t}\n\tinfoNodePtr->send(ss.str());\n\treturn true;\n}\nbool MyManageType::onGetIDByObject(khala::InfoNodePtr& infoNodePtr,\n\t\tJson::Value& msg, khala::Timestamp time) {\n\tMyManageType* tmp = new MyManageType();\n\tstd::vector<uint> v = this->getNodeManager()->getNodeIDs(tmp);\n\tstd::stringstream ss;\n\tss << \"Get ID By Object:Ask Object type:\" << tmp->getObjectTypeName()\n\t\t\t<< \" . Get ID:\";\n\tfor (std::vector<uint>::iterator it = v.begin(); it != v.end(); ++it) {\n\t\tss << *it << \" \";\n\t}\n\tinfoNodePtr->send(ss.str());\n\tdelete tmp;\n\treturn true;\n}\nbool MyManageType::onGetAllIDByObject(khala::InfoNodePtr& infoNodePtr,\n\t\tJson::Value& msg, khala::Timestamp time) {\n\tNodeType* tmp = new NodeType();\n\t\/\/parameter is NodeType Object\n\tstd::vector<uint> v = this->getNodeManager()->getAllNodeIDs(*tmp);\n\tstd::stringstream ss;\n\tss << \"Get All ID By Object:Ask Object type:\" << tmp->getObjectTypeName()\n\t\t\t<< \" . Get ID:\";\n\tfor (std::vector<uint>::iterator it = v.begin(); it != v.end(); ++it) {\n\t\tss << *it << \" \";\n\t}\n\tinfoNodePtr->send(ss.str());\n\tdelete tmp;\n\treturn true;\n}\nbool MyManageType::onGetAllIDByObjectPtr(khala::InfoNodePtr& infoNodePtr,\n\t\tJson::Value& msg, khala::Timestamp time) {\n\tNodeType* tmp = new NodeType();\n\t\/\/parameter is NodeType Object pointor\n\tstd::vector<uint> v = this->getNodeManager()->getAllNodeIDs(tmp);\n\tstd::stringstream ss;\n\tss << \"Get All ID By Object ptr:Ask Object type:\"\n\t\t\t<< tmp->getObjectTypeName() << \" . Get ID:\";\n\tfor (std::vector<uint>::iterator it = v.begin(); it != v.end(); ++it) {\n\t\tss << *it << \" \";\n\t}\n\tinfoNodePtr->send(ss.str());\n\tdelete tmp;\n\treturn true;\n}\nbool MyManageType::onAskLogin(khala::InfoNodePtr& infoNodePtr, Json::Value& msg,\n\t\tkhala::Timestamp time){\n\tuint friendId = msg[KEY_FRIEND_ID].asUInt();\n\tstd::stringstream ss;\n\tss<<\"Node ID:\"<<friendId;\n\tif(this->getNodeManager()->hasNode(friendId)){\n\t\tss<<\" is login!\";\n\t}else{\n\t\tss<<\" is not login!\";\n\t}\n\tinfoNodePtr->send(ss.str());\n\treturn true;\n}\nbool MyManageType::onSendtoNode(khala::InfoNodePtr& infoNodePtr,\n\t\tJson::Value& msg, khala::Timestamp time){\n\tuint myId = infoNodePtr->getId();\n\tkhala::InfoNodePtr myInfoNodePtr;\n\tif(this->getNodeManager()->find(myId, myInfoNodePtr)){\n\t\tmyInfoNodePtr->send(\"test manager find success\");\n\t}\n\treturn true;\n}\nvoid MyManageType::setRegisterMsg(khala::RegisterHandler& handler){\n\tNodeType::setRegisterMsg(handler);\n\thandler.setRegisterMsg(ID_BY_TYPE,\n\t\t\t\t\tboost::bind(&MyManageType::onGetIDByType, this, _1, _2, _3));\n\thandler.setRegisterMsg(ID_BY_OBJECT,\n\t\t\tboost::bind(&MyManageType::onGetIDByObject, this, _1, _2, _3));\n\thandler.setRegisterMsg(ALL_ID_BY_OBJECT,\n\t\t\t\tboost::bind(&MyManageType::onGetAllIDByObject, this, _1, _2, _3));\n\thandler.setRegisterMsg(ALL_ID_BY_OBJECT_PTR,\n\t\t\t\tboost::bind(&MyManageType::onGetAllIDByObjectPtr, this, _1, _2, _3));\n\thandler.setRegisterMsg(ASK_LOGIN,\n\t\t\t\tboost::bind(&MyManageType::onAskLogin, this, _1, _2, _3));\n\thandler.setRegisterMsg(SEND_MSG,\n\t\t\t\t\tboost::bind(&MyManageType::onSendtoNode, this, _1, _2, _3));\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2016-2017 Francesco Biscani (bluescarni@gmail.com)\n\/\/\n\/\/ This file is part of the mp++ library.\n\/\/\n\/\/ This Source Code Form is subject to the terms of the Mozilla\n\/\/ Public License v. 2.0. If a copy of the MPL was not distributed\n\/\/ with this file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n\n#ifndef MPPP_DETAIL_MPFR_HPP\n#define MPPP_DETAIL_MPFR_HPP\n\n#include <mp++\/config.hpp>\n\n#if defined(MPPP_WITH_MPFR)\n\n#include <limits>\n#include <mpfr.h>\n#include <type_traits>\n\n#include <mp++\/detail\/gmp.hpp>\n\n#if MPFR_VERSION_MAJOR < 3\n\n#error Minimum supported MPFR version is 3.\n\n#endif\n\nnamespace mppp\n{\n\ninline namespace detail\n{\n\n\/\/ mpfr_t is an array of some struct.\nusing mpfr_struct_t = std::remove_extent<::mpfr_t>::type;\n\n\/\/ Simple RAII holder for MPFR floats.\nstruct mpfr_raii {\n mpfr_raii(::mpfr_prec_t prec)\n {\n ::mpfr_init2(&m_mpfr, prec);\n }\n ~mpfr_raii()\n {\n ::mpfr_clear(&m_mpfr);\n }\n mpfr_struct_t m_mpfr;\n};\n}\n\n\/\/ A couple of sanity checks when constructing temporary mpfrs\/mpfs from long double.\nstatic_assert(std::numeric_limits<long double>::digits10 < std::numeric_limits<int>::max() \/ 4, \"Overflow error.\");\nstatic_assert(std::numeric_limits<long double>::digits10 * 4 < std::numeric_limits<::mpfr_prec_t>::max(),\n \"Overflow error.\");\nstatic_assert(std::numeric_limits<long double>::digits10 * 4 < std::numeric_limits<::mp_bitcnt_t>::max(),\n \"Overflow error.\");\n}\n\n#else\n\n#error The 'mpfr.hpp' header was included but mp++ was not installed with MPFR support.\n\n#endif\n\n#endif\n<commit_msg>Implement the auto-cleanup mechanism for MPFR.<commit_after>\/\/ Copyright 2016-2017 Francesco Biscani (bluescarni@gmail.com)\n\/\/\n\/\/ This file is part of the mp++ library.\n\/\/\n\/\/ This Source Code Form is subject to the terms of the Mozilla\n\/\/ Public License v. 2.0. If a copy of the MPL was not distributed\n\/\/ with this file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n\n#ifndef MPPP_DETAIL_MPFR_HPP\n#define MPPP_DETAIL_MPFR_HPP\n\n#include <cstdlib>\n#include <limits>\n#include <memory>\n#include <mpfr.h>\n#include <type_traits>\n\n#include <mp++\/detail\/gmp.hpp>\n\n#if MPFR_VERSION_MAJOR < 3\n\n#error Minimum supported MPFR version is 3.\n\n#endif\n\nnamespace mppp\n{\n\ninline namespace detail\n{\n\n\/\/ mpfr_t is an array of some struct.\nusing mpfr_struct_t = std::remove_extent<::mpfr_t>::type;\n\n\/\/ Simple RAII holder for MPFR floats.\nstruct mpfr_raii {\n mpfr_raii(::mpfr_prec_t prec)\n {\n ::mpfr_init2(&m_mpfr, prec);\n }\n ~mpfr_raii()\n {\n ::mpfr_clear(&m_mpfr);\n }\n mpfr_struct_t m_mpfr;\n};\n\n\/\/ Smart pointer to handle the string output from mpfr.\nusing smart_mpfr_str = std::unique_ptr<char, void (*)(char *)>;\n\n\/\/ A couple of sanity checks when constructing temporary mpfrs\/mpfs from long double.\nstatic_assert(std::numeric_limits<long double>::digits10 < std::numeric_limits<int>::max() \/ 4, \"Overflow error.\");\nstatic_assert(std::numeric_limits<long double>::digits10 * 4 < std::numeric_limits<::mpfr_prec_t>::max(),\n \"Overflow error.\");\nstatic_assert(std::numeric_limits<long double>::digits10 * 4 < std::numeric_limits<::mp_bitcnt_t>::max(),\n \"Overflow error.\");\n\n\/\/ Machinery to call automatically mpfr_free_cache() at program shutdown,\n\/\/ if this header is included.\nstruct mpfr_cleanup {\n mpfr_cleanup()\n {\n std::atexit(::mpfr_free_cache);\n }\n};\n\ntemplate <typename = void>\nstruct mpfr_cleanup_holder {\n static mpfr_cleanup s_cleanup;\n};\n\ntemplate <typename T>\nmpfr_cleanup mpfr_cleanup_holder<T>::s_cleanup;\n\ninline void inst_mpfr_cleanup()\n{\n auto ptr = &mpfr_cleanup_holder<>::s_cleanup;\n (void)ptr;\n}\n}\n}\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/* Definition of the pqxx::stream_from class.\n *\n * pqxx::stream_from enables optimized batch reads from a database table.\n *\n * DO NOT INCLUDE THIS FILE DIRECTLY; include pqxx\/stream_from instead.\n *\n * Copyright (c) 2000-2020, Jeroen T. Vermeulen.\n *\n * See COPYING for copyright license. If you did not receive a file called\n * COPYING with this source code, please notify the distributor of this\n * mistake, or contact the author.\n *\/\n#ifndef PQXX_H_STREAM_FROM\n#define PQXX_H_STREAM_FROM\n\n#include \"pqxx\/compiler-public.hxx\"\n#include \"pqxx\/internal\/compiler-internal-pre.hxx\"\n\n#include <cassert>\n#include <functional>\n#include <variant>\n\n#include \"pqxx\/except.hxx\"\n#include \"pqxx\/internal\/encoding_group.hxx\"\n#include \"pqxx\/internal\/stream_iterator.hxx\"\n#include \"pqxx\/internal\/transaction_focus.hxx\"\n#include \"pqxx\/separated_list.hxx\"\n#include \"pqxx\/transaction_base.hxx\"\n\n\nnamespace pqxx\n{\n\/\/\/ Pass this to a @c stream_from constructor to stream table contents.\nconstexpr from_table_t from_table;\n\/\/\/ Pass this to a @c stream_from constructor to stream query results.\nconstexpr from_query_t from_query;\n\n\n\/\/\/ Stream data from the database.\n\/** Retrieving data this way is likely to be faster than executing a query and\n * then iterating and converting the rows fields. You will also be able to\n * start processing before all of the data has come in.\n *\n * There are also downsides. If there's an error, it may leave the entire\n * connection in an unusable state, so you'll have to give the whole thing up.\n * Also, your connection to the database may break before you've received all\n * the data, so you may end up processing only part of the data. Finally,\n * opening a stream puts the connection in a special state, so you won't be\n * able to do many other things with the connection or the transaction while\n * the stream is open.\n *\n * There are two ways of starting a stream: you stream either all rows in a\n * table (in which case, use a constructor which accepts @c pqxx::from_table),\n * or the results of a query (in which case, use a concstructor which accepts\n * @c pqxx::from_query).\n *\n * Usually you'll want the @c stream convenience wrapper in transaction_base,\n * so you don't need to deal with this class directly.\n *\/\nclass PQXX_LIBEXPORT stream_from : internal::transactionfocus\n{\npublic:\n using raw_line =\n std::pair<std::unique_ptr<char, std::function<void(char *)>>, std::size_t>;\n\n \/\/\/ Execute query, and stream over the results.\n \/** The query can be a SELECT query or a VALUES query; or it can be an\n * UPDATE, INSERT, or DELETE with a RETURNING clause.\n *\n * The query is executed as part of a COPY statement, so there are additional\n * restrictions on what kind of query you can use here. See the PostgreSQL\n * documentation for the COPY command:\n *\n * https:\/\/www.postgresql.org\/docs\/current\/sql-copy.html\n *\/\n stream_from(transaction_base &, from_query_t, std::string_view query);\n\n \/\/\/ Stream all rows in table, all columns.\n stream_from(transaction_base &, from_table_t, std::string_view table);\n\n \/\/\/ Stream given columns from all rows in table.\n template<typename Iter>\n stream_from(\n transaction_base &, from_table_t, std::string_view table,\n Iter columns_begin, Iter columns_end);\n\n \/\/\/ Stream given columns from all rows in table.\n template<typename Columns>\n stream_from(\n transaction_base &tx, from_table_t, std::string_view table,\n Columns const &columns);\n\n \/\/\/ @deprecated Use the @c from_table_t overload instead.\n stream_from(transaction_base &tx, std::string_view table) :\n stream_from{tx, from_table, table}\n {}\n\n \/\/\/ @deprecated Use the @c from_table_t overload instead.\n template<typename Columns>\n stream_from(\n transaction_base &tx, std::string_view table, Columns const &columns) :\n stream_from{tx, from_table, table, columns}\n {}\n\n \/\/\/ @deprecated Use the @c from_table_t overload instead.\n template<typename Iter>\n stream_from(\n transaction_base &, std::string_view table, Iter columns_begin,\n Iter columns_end);\n\n ~stream_from() noexcept;\n\n [[nodiscard]] operator bool() const noexcept { return not m_finished; }\n [[nodiscard]] bool operator!() const noexcept { return m_finished; }\n\n \/\/\/ Finish this stream. Call this before continuing to use the connection.\n \/** Consumes all remaining lines, and closes the stream.\n *\n * This may take a while if you're abandoning the stream before it's done, so\n * skip it in error scenarios where you're not planning to use the connection\n * again afterwards.\n *\/\n void complete();\n\n \/\/\/ Read one row into a tuple.\n \/** Converts the row's fields into the fields making up the tuple.\n *\n * For a column which can contain nulls, be sure to give the corresponding\n * tuple field a type which can be null. For example, to read a field as\n * @c int when it may contain nulls, read it as @c std::optional<int>.\n * Using @c std::shared_ptr or @c std::unique_ptr will also work.\n *\/\n raw_line get_raw_line();\n template<typename Tuple> stream_from &operator>>(Tuple &);\n\n \/\/\/ Doing this with a @c std::variant is going to be horrifically borked.\n template<typename... Vs>\n stream_from &operator>>(std::variant<Vs...> &) = delete;\n\n \/\/\/ Iterate over this stream. Supports range-based \"for\" loops.\n \/** Produces an input iterator over the stream.\n *\n * Do not call this yourself. Use it like \"for (auto data : stream.iter())\".\n *\/\n template<typename... TYPE>[[nodiscard]] auto iter()\n {\n return pqxx::internal::stream_input_iteration<TYPE...>{*this};\n }\n\nprivate:\n stream_from(\n transaction_base &tx, std::string_view table, std::string &&columns,\n from_table_t);\n\n \/\/ XXX: Can we make template args implicit?\n template<typename Tuple, std::size_t... indexes>\n void extract_fields(Tuple &t, std::index_sequence<indexes...>) const\n {\n (extract_value<Tuple, indexes>(t), ...);\n }\n\n static std::string compose_query(\n transaction_base const &tx, std::string_view table,\n std::string const &columns);\n\n pqxx::internal::glyph_scanner_func *m_glyph_scanner;\n\n \/\/\/ Current row's fields' text, combined into one reusable string.\n std::string m_row;\n\n \/\/\/ The current row's fields.\n std::vector<zview> m_fields;\n\n bool m_finished = false;\n\n void close();\n\n template<typename Tuple, std::size_t index>\n void extract_value(Tuple &) const;\n\n \/\/\/ Read a line of COPY data, write @c m_row and @c m_fields.\n void parse_line();\n};\n\n\ntemplate<typename Columns>\ninline stream_from::stream_from(\n transaction_base &tb, from_table_t, std::string_view table_name,\n Columns const &columns) :\n stream_from{tb, from_table, table_name, std::begin(columns),\n std::end(columns)}\n{}\n\n\ntemplate<typename Iter>\ninline stream_from::stream_from(\n transaction_base &tx, from_table_t, std::string_view table,\n Iter columns_begin, Iter columns_end) :\n stream_from{tx, table, separated_list(\",\", columns_begin, columns_end),\n from_table}\n{}\n\n\ntemplate<typename Tuple> inline stream_from &stream_from::operator>>(Tuple &t)\n{\n if (m_finished)\n return *this;\n constexpr auto tup_size{std::tuple_size_v<Tuple>};\n m_fields.reserve(tup_size);\n parse_line();\n if (m_finished)\n return *this;\n\n if (m_fields.size() != tup_size)\n throw usage_error{\"Tried to extract \" + to_string(tup_size) +\n \" field(s) from a stream of \" +\n to_string(m_fields.size()) + \".\"};\n\n extract_fields(t, std::make_index_sequence<tup_size>{});\n return *this;\n}\n\n\ntemplate<typename Tuple, std::size_t index>\ninline void stream_from::extract_value(Tuple &t) const\n{\n using field_type = std::remove_reference_t<decltype(std::get<index>(t))>;\n assert(index < m_fields.size());\n if constexpr (std::is_same_v<field_type, std::nullptr_t>)\n {\n if (m_fields[index].data() != nullptr)\n throw conversion_error{\"Streaming non-null value into nullptr_t field.\"};\n }\n else if (m_fields[index].data() == nullptr)\n {\n if constexpr (nullness<field_type>::has_null)\n std::get<index>(t) = nullness<field_type>::null();\n else\n internal::throw_null_conversion(type_name<field_type>);\n }\n else\n {\n \/\/ Don't ever try to convert a non-null value to nullptr_t!\n std::get<index>(t) = from_string<field_type>(m_fields[index]);\n }\n}\n} \/\/ namespace pqxx\n\n#include \"pqxx\/internal\/compiler-internal-post.hxx\"\n#endif\n<commit_msg>Generalise a `nullptr_t` to `always_null`.<commit_after>\/* Definition of the pqxx::stream_from class.\n *\n * pqxx::stream_from enables optimized batch reads from a database table.\n *\n * DO NOT INCLUDE THIS FILE DIRECTLY; include pqxx\/stream_from instead.\n *\n * Copyright (c) 2000-2020, Jeroen T. Vermeulen.\n *\n * See COPYING for copyright license. If you did not receive a file called\n * COPYING with this source code, please notify the distributor of this\n * mistake, or contact the author.\n *\/\n#ifndef PQXX_H_STREAM_FROM\n#define PQXX_H_STREAM_FROM\n\n#include \"pqxx\/compiler-public.hxx\"\n#include \"pqxx\/internal\/compiler-internal-pre.hxx\"\n\n#include <cassert>\n#include <functional>\n#include <variant>\n\n#include \"pqxx\/except.hxx\"\n#include \"pqxx\/internal\/encoding_group.hxx\"\n#include \"pqxx\/internal\/stream_iterator.hxx\"\n#include \"pqxx\/internal\/transaction_focus.hxx\"\n#include \"pqxx\/separated_list.hxx\"\n#include \"pqxx\/transaction_base.hxx\"\n\n\nnamespace pqxx\n{\n\/\/\/ Pass this to a @c stream_from constructor to stream table contents.\nconstexpr from_table_t from_table;\n\/\/\/ Pass this to a @c stream_from constructor to stream query results.\nconstexpr from_query_t from_query;\n\n\n\/\/\/ Stream data from the database.\n\/** Retrieving data this way is likely to be faster than executing a query and\n * then iterating and converting the rows fields. You will also be able to\n * start processing before all of the data has come in.\n *\n * There are also downsides. If there's an error, it may leave the entire\n * connection in an unusable state, so you'll have to give the whole thing up.\n * Also, your connection to the database may break before you've received all\n * the data, so you may end up processing only part of the data. Finally,\n * opening a stream puts the connection in a special state, so you won't be\n * able to do many other things with the connection or the transaction while\n * the stream is open.\n *\n * There are two ways of starting a stream: you stream either all rows in a\n * table (in which case, use a constructor which accepts @c pqxx::from_table),\n * or the results of a query (in which case, use a concstructor which accepts\n * @c pqxx::from_query).\n *\n * Usually you'll want the @c stream convenience wrapper in transaction_base,\n * so you don't need to deal with this class directly.\n *\/\nclass PQXX_LIBEXPORT stream_from : internal::transactionfocus\n{\npublic:\n using raw_line =\n std::pair<std::unique_ptr<char, std::function<void(char *)>>, std::size_t>;\n\n \/\/\/ Execute query, and stream over the results.\n \/** The query can be a SELECT query or a VALUES query; or it can be an\n * UPDATE, INSERT, or DELETE with a RETURNING clause.\n *\n * The query is executed as part of a COPY statement, so there are additional\n * restrictions on what kind of query you can use here. See the PostgreSQL\n * documentation for the COPY command:\n *\n * https:\/\/www.postgresql.org\/docs\/current\/sql-copy.html\n *\/\n stream_from(transaction_base &, from_query_t, std::string_view query);\n\n \/\/\/ Stream all rows in table, all columns.\n stream_from(transaction_base &, from_table_t, std::string_view table);\n\n \/\/\/ Stream given columns from all rows in table.\n template<typename Iter>\n stream_from(\n transaction_base &, from_table_t, std::string_view table,\n Iter columns_begin, Iter columns_end);\n\n \/\/\/ Stream given columns from all rows in table.\n template<typename Columns>\n stream_from(\n transaction_base &tx, from_table_t, std::string_view table,\n Columns const &columns);\n\n \/\/\/ @deprecated Use the @c from_table_t overload instead.\n stream_from(transaction_base &tx, std::string_view table) :\n stream_from{tx, from_table, table}\n {}\n\n \/\/\/ @deprecated Use the @c from_table_t overload instead.\n template<typename Columns>\n stream_from(\n transaction_base &tx, std::string_view table, Columns const &columns) :\n stream_from{tx, from_table, table, columns}\n {}\n\n \/\/\/ @deprecated Use the @c from_table_t overload instead.\n template<typename Iter>\n stream_from(\n transaction_base &, std::string_view table, Iter columns_begin,\n Iter columns_end);\n\n ~stream_from() noexcept;\n\n [[nodiscard]] operator bool() const noexcept { return not m_finished; }\n [[nodiscard]] bool operator!() const noexcept { return m_finished; }\n\n \/\/\/ Finish this stream. Call this before continuing to use the connection.\n \/** Consumes all remaining lines, and closes the stream.\n *\n * This may take a while if you're abandoning the stream before it's done, so\n * skip it in error scenarios where you're not planning to use the connection\n * again afterwards.\n *\/\n void complete();\n\n \/\/\/ Read one row into a tuple.\n \/** Converts the row's fields into the fields making up the tuple.\n *\n * For a column which can contain nulls, be sure to give the corresponding\n * tuple field a type which can be null. For example, to read a field as\n * @c int when it may contain nulls, read it as @c std::optional<int>.\n * Using @c std::shared_ptr or @c std::unique_ptr will also work.\n *\/\n raw_line get_raw_line();\n template<typename Tuple> stream_from &operator>>(Tuple &);\n\n \/\/\/ Doing this with a @c std::variant is going to be horrifically borked.\n template<typename... Vs>\n stream_from &operator>>(std::variant<Vs...> &) = delete;\n\n \/\/\/ Iterate over this stream. Supports range-based \"for\" loops.\n \/** Produces an input iterator over the stream.\n *\n * Do not call this yourself. Use it like \"for (auto data : stream.iter())\".\n *\/\n template<typename... TYPE>[[nodiscard]] auto iter()\n {\n return pqxx::internal::stream_input_iteration<TYPE...>{*this};\n }\n\nprivate:\n stream_from(\n transaction_base &tx, std::string_view table, std::string &&columns,\n from_table_t);\n\n \/\/ XXX: Can we make template args implicit?\n template<typename Tuple, std::size_t... indexes>\n void extract_fields(Tuple &t, std::index_sequence<indexes...>) const\n {\n (extract_value<Tuple, indexes>(t), ...);\n }\n\n static std::string compose_query(\n transaction_base const &tx, std::string_view table,\n std::string const &columns);\n\n pqxx::internal::glyph_scanner_func *m_glyph_scanner;\n\n \/\/\/ Current row's fields' text, combined into one reusable string.\n std::string m_row;\n\n \/\/\/ The current row's fields.\n std::vector<zview> m_fields;\n\n bool m_finished = false;\n\n void close();\n\n template<typename Tuple, std::size_t index>\n void extract_value(Tuple &) const;\n\n \/\/\/ Read a line of COPY data, write @c m_row and @c m_fields.\n void parse_line();\n};\n\n\ntemplate<typename Columns>\ninline stream_from::stream_from(\n transaction_base &tb, from_table_t, std::string_view table_name,\n Columns const &columns) :\n stream_from{tb, from_table, table_name, std::begin(columns),\n std::end(columns)}\n{}\n\n\ntemplate<typename Iter>\ninline stream_from::stream_from(\n transaction_base &tx, from_table_t, std::string_view table,\n Iter columns_begin, Iter columns_end) :\n stream_from{tx, table, separated_list(\",\", columns_begin, columns_end),\n from_table}\n{}\n\n\ntemplate<typename Tuple> inline stream_from &stream_from::operator>>(Tuple &t)\n{\n if (m_finished)\n return *this;\n constexpr auto tup_size{std::tuple_size_v<Tuple>};\n m_fields.reserve(tup_size);\n parse_line();\n if (m_finished)\n return *this;\n\n if (m_fields.size() != tup_size)\n throw usage_error{\"Tried to extract \" + to_string(tup_size) +\n \" field(s) from a stream of \" +\n to_string(m_fields.size()) + \".\"};\n\n extract_fields(t, std::make_index_sequence<tup_size>{});\n return *this;\n}\n\n\ntemplate<typename Tuple, std::size_t index>\ninline void stream_from::extract_value(Tuple &t) const\n{\n using field_type = std::remove_reference_t<decltype(std::get<index>(t))>;\n assert(index < m_fields.size());\n if constexpr (nullness<field_type>::always_null)\n {\n if (m_fields[index].data() != nullptr)\n throw conversion_error{\"Streaming non-null value into null field.\"};\n }\n else if (m_fields[index].data() == nullptr)\n {\n if constexpr (nullness<field_type>::has_null)\n std::get<index>(t) = nullness<field_type>::null();\n else\n internal::throw_null_conversion(type_name<field_type>);\n }\n else\n {\n \/\/ Don't ever try to convert a non-null value to nullptr_t!\n std::get<index>(t) = from_string<field_type>(m_fields[index]);\n }\n}\n} \/\/ namespace pqxx\n\n#include \"pqxx\/internal\/compiler-internal-post.hxx\"\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/***************************************************************************\n* Copyright (c) 2017, Sylvain Corlay and Johan Mabille *\n* *\n* Distributed under the terms of the BSD 3-Clause License. *\n* *\n* The full license is in the file LICENSE, distributed with this software. *\n****************************************************************************\/\n\n#ifndef XWIDGETS_SLIDER_HPP\n#define XWIDGETS_SLIDER_HPP\n\n#include <string>\n\n#include \"xtl\/xoptional.hpp\"\n\n#include \"xcolor.hpp\"\n#include \"xeither.hpp\"\n#include \"xmaterialize.hpp\"\n#include \"xnumber.hpp\"\n#include \"xstyle.hpp\"\n\nnamespace xw\n{\n \/****************************\n * slider_style declaration *\n ****************************\/\n\n template <class D>\n class xslider_style : public xstyle<D>\n {\n public:\n\n using base_type = xstyle<D>;\n using derived_type = D;\n\n xeus::xjson get_state() const;\n void apply_patch(const xeus::xjson&);\n\n XPROPERTY(std::string, derived_type, description_width);\n XPROPERTY(xtl::xoptional<html_color>, derived_type, handle_color);\n\n protected:\n\n xslider_style();\n using base_type::base_type;\n\n private:\n\n void set_defaults();\n };\n\n using slider_style = xmaterialize<xslider_style>;\n\n using slider_style_generator = xgenerator<xslider_style>;\n\n \/**********************\n * slider declaration *\n **********************\/\n\n template <class D>\n class xslider : public xnumber<D>\n {\n public:\n\n using base_type = xnumber<D>;\n using derived_type = D;\n\n using value_type = typename base_type::value_type;\n\n xeus::xjson get_state() const;\n void apply_patch(const xeus::xjson&);\n\n XPROPERTY(value_type, derived_type, step, value_type(1));\n XPROPERTY(std::string, derived_type, orientation, \"horizontal\", XEITHER(\"horizontal\", \"vertical\"));\n XPROPERTY(bool, derived_type, readout, true);\n XPROPERTY(std::string, derived_type, readout_format, \".2f\");\n XPROPERTY(bool, derived_type, continuous_update, true);\n XPROPERTY(bool, derived_type, disabled);\n XPROPERTY(::xw::slider_style, derived_type, style);\n\n protected:\n\n xslider();\n using base_type::base_type;\n\n private:\n\n void set_defaults();\n };\n\n template <class T>\n using slider = xmaterialize<xslider, T>;\n\n template <class T>\n using slider_generator = xgenerator<xslider, T>;\n\n template <class T>\n struct xnumber_traits<slider<T>>\n {\n using value_type = T;\n };\n\n template <class T>\n struct xnumber_traits<slider_generator<T>>\n {\n using value_type = T;\n };\n\n \/********************************\n * xslider_style implementation *\n ********************************\/\n\n template <class D>\n inline xeus::xjson xslider_style<D>::get_state() const\n {\n xeus::xjson state = base_type::get_state();\n\n XOBJECT_SET_PATCH_FROM_PROPERTY(description_width, state);\n XOBJECT_SET_PATCH_FROM_PROPERTY(handle_color, state);\n\n return state;\n }\n\n template <class D>\n inline void xslider_style<D>::apply_patch(const xeus::xjson& patch)\n {\n base_type::apply_patch(patch);\n\n XOBJECT_SET_PROPERTY_FROM_PATCH(description_width, patch);\n XOBJECT_SET_PROPERTY_FROM_PATCH(handle_color, patch);\n }\n\n template <class D>\n inline xslider_style<D>::xslider_style()\n : base_type()\n {\n set_defaults();\n }\n\n template <class D>\n inline void xslider_style<D>::set_defaults()\n {\n this->_model_module() = \"@jupyter-widgets\/controls\";\n this->_model_name() = \"SliderStyleModel\";\n }\n\n \/**************************\n * xslider implementation *\n **************************\/\n\n template <class D>\n inline xeus::xjson xslider<D>::get_state() const\n {\n xeus::xjson state = base_type::get_state();\n\n XOBJECT_SET_PATCH_FROM_PROPERTY(step, state);\n XOBJECT_SET_PATCH_FROM_PROPERTY(orientation, state);\n XOBJECT_SET_PATCH_FROM_PROPERTY(readout, state);\n XOBJECT_SET_PATCH_FROM_PROPERTY(readout_format, state);\n XOBJECT_SET_PATCH_FROM_PROPERTY(continuous_update, state);\n XOBJECT_SET_PATCH_FROM_PROPERTY(disabled, state);\n XOBJECT_SET_PATCH_FROM_PROPERTY(style, state);\n\n return state;\n }\n\n template <class D>\n inline void xslider<D>::apply_patch(const xeus::xjson& patch)\n {\n base_type::apply_patch(patch);\n\n XOBJECT_SET_PROPERTY_FROM_PATCH(step, patch);\n XOBJECT_SET_PROPERTY_FROM_PATCH(orientation, patch);\n XOBJECT_SET_PROPERTY_FROM_PATCH(readout, patch);\n XOBJECT_SET_PROPERTY_FROM_PATCH(readout_format, patch);\n XOBJECT_SET_PROPERTY_FROM_PATCH(continuous_update, patch);\n XOBJECT_SET_PROPERTY_FROM_PATCH(disabled, patch);\n XOBJECT_SET_PROPERTY_FROM_PATCH(style, patch);\n }\n\n template <class D>\n inline xslider<D>::xslider()\n : base_type()\n {\n set_defaults();\n\n this->template validate<decltype(this->value)>([this](auto& proposal) {\n if (proposal > this->max())\n {\n proposal = this->max();\n }\n if (proposal < this->min())\n {\n proposal = this->min();\n }\n });\n\n this->template validate<decltype(this->min)>([this](auto& proposal) {\n if (proposal > this->max())\n {\n throw std::runtime_error(\"setting min > max\");\n }\n if (proposal > this->value())\n {\n this->value = proposal;\n }\n });\n\n this->template validate<decltype(this->max)>([this](auto& proposal) {\n if (proposal < this->min())\n {\n throw std::runtime_error(\"setting max < min\");\n }\n if (proposal < this->value())\n {\n this->value = proposal;\n }\n });\n }\n\n template <class D>\n inline void xslider<D>::set_defaults()\n {\n this->_model_name() = \"FloatSliderModel\";\n this->_view_name() = \"FloatSliderView\";\n }\n}\n\n#endif\n<commit_msg>separate setup-properties in slider constructor<commit_after>\/***************************************************************************\n* Copyright (c) 2017, Sylvain Corlay and Johan Mabille *\n* *\n* Distributed under the terms of the BSD 3-Clause License. *\n* *\n* The full license is in the file LICENSE, distributed with this software. *\n****************************************************************************\/\n\n#ifndef XWIDGETS_SLIDER_HPP\n#define XWIDGETS_SLIDER_HPP\n\n#include <string>\n\n#include \"xtl\/xoptional.hpp\"\n\n#include \"xcolor.hpp\"\n#include \"xeither.hpp\"\n#include \"xmaterialize.hpp\"\n#include \"xnumber.hpp\"\n#include \"xstyle.hpp\"\n\nnamespace xw\n{\n \/****************************\n * slider_style declaration *\n ****************************\/\n\n template <class D>\n class xslider_style : public xstyle<D>\n {\n public:\n\n using base_type = xstyle<D>;\n using derived_type = D;\n\n xeus::xjson get_state() const;\n void apply_patch(const xeus::xjson&);\n\n XPROPERTY(std::string, derived_type, description_width);\n XPROPERTY(xtl::xoptional<html_color>, derived_type, handle_color);\n\n protected:\n\n xslider_style();\n using base_type::base_type;\n\n private:\n\n void set_defaults();\n };\n\n using slider_style = xmaterialize<xslider_style>;\n\n using slider_style_generator = xgenerator<xslider_style>;\n\n \/**********************\n * slider declaration *\n **********************\/\n\n template <class D>\n class xslider : public xnumber<D>\n {\n public:\n\n using base_type = xnumber<D>;\n using derived_type = D;\n\n using value_type = typename base_type::value_type;\n\n xeus::xjson get_state() const;\n void apply_patch(const xeus::xjson&);\n\n XPROPERTY(value_type, derived_type, step, value_type(1));\n XPROPERTY(std::string, derived_type, orientation, \"horizontal\", XEITHER(\"horizontal\", \"vertical\"));\n XPROPERTY(bool, derived_type, readout, true);\n XPROPERTY(std::string, derived_type, readout_format, \".2f\");\n XPROPERTY(bool, derived_type, continuous_update, true);\n XPROPERTY(bool, derived_type, disabled);\n XPROPERTY(::xw::slider_style, derived_type, style);\n\n protected:\n\n xslider();\n using base_type::base_type;\n\n private:\n\n void set_defaults();\n\n void setup_properties();\n };\n\n template <class T>\n using slider = xmaterialize<xslider, T>;\n\n template <class T>\n using slider_generator = xgenerator<xslider, T>;\n\n template <class T>\n struct xnumber_traits<slider<T>>\n {\n using value_type = T;\n };\n\n template <class T>\n struct xnumber_traits<slider_generator<T>>\n {\n using value_type = T;\n };\n\n \/********************************\n * xslider_style implementation *\n ********************************\/\n\n template <class D>\n inline xeus::xjson xslider_style<D>::get_state() const\n {\n xeus::xjson state = base_type::get_state();\n\n XOBJECT_SET_PATCH_FROM_PROPERTY(description_width, state);\n XOBJECT_SET_PATCH_FROM_PROPERTY(handle_color, state);\n\n return state;\n }\n\n template <class D>\n inline void xslider_style<D>::apply_patch(const xeus::xjson& patch)\n {\n base_type::apply_patch(patch);\n\n XOBJECT_SET_PROPERTY_FROM_PATCH(description_width, patch);\n XOBJECT_SET_PROPERTY_FROM_PATCH(handle_color, patch);\n }\n\n template <class D>\n inline xslider_style<D>::xslider_style()\n : base_type()\n {\n set_defaults();\n }\n\n template <class D>\n inline void xslider_style<D>::set_defaults()\n {\n this->_model_module() = \"@jupyter-widgets\/controls\";\n this->_model_name() = \"SliderStyleModel\";\n }\n\n \/**************************\n * xslider implementation *\n **************************\/\n\n template <class D>\n inline xeus::xjson xslider<D>::get_state() const\n {\n xeus::xjson state = base_type::get_state();\n\n XOBJECT_SET_PATCH_FROM_PROPERTY(step, state);\n XOBJECT_SET_PATCH_FROM_PROPERTY(orientation, state);\n XOBJECT_SET_PATCH_FROM_PROPERTY(readout, state);\n XOBJECT_SET_PATCH_FROM_PROPERTY(readout_format, state);\n XOBJECT_SET_PATCH_FROM_PROPERTY(continuous_update, state);\n XOBJECT_SET_PATCH_FROM_PROPERTY(disabled, state);\n XOBJECT_SET_PATCH_FROM_PROPERTY(style, state);\n\n return state;\n }\n\n template <class D>\n inline void xslider<D>::apply_patch(const xeus::xjson& patch)\n {\n base_type::apply_patch(patch);\n\n XOBJECT_SET_PROPERTY_FROM_PATCH(step, patch);\n XOBJECT_SET_PROPERTY_FROM_PATCH(orientation, patch);\n XOBJECT_SET_PROPERTY_FROM_PATCH(readout, patch);\n XOBJECT_SET_PROPERTY_FROM_PATCH(readout_format, patch);\n XOBJECT_SET_PROPERTY_FROM_PATCH(continuous_update, patch);\n XOBJECT_SET_PROPERTY_FROM_PATCH(disabled, patch);\n XOBJECT_SET_PROPERTY_FROM_PATCH(style, patch);\n }\n\n template <class D>\n inline xslider<D>::xslider()\n : base_type()\n {\n set_defaults();\n\n this->setup_properties();\n }\n\n template <class D>\n inline void xslider<D>::setup_properties()\n {\n this->template validate<decltype(this->value)>([this](auto& proposal) {\n if (proposal > this->max())\n {\n proposal = this->max();\n }\n if (proposal < this->min())\n {\n proposal = this->min();\n }\n });\n\n this->template validate<decltype(this->min)>([this](auto& proposal) {\n if (proposal > this->max())\n {\n throw std::runtime_error(\"setting min > max\");\n }\n if (proposal > this->value())\n {\n this->value = proposal;\n }\n });\n\n this->template validate<decltype(this->max)>([this](auto& proposal) {\n if (proposal < this->min())\n {\n throw std::runtime_error(\"setting max < min\");\n }\n if (proposal < this->value())\n {\n this->value = proposal;\n }\n });\n }\n\n template <class D>\n inline void xslider<D>::set_defaults()\n {\n this->_model_name() = \"FloatSliderModel\";\n this->_view_name() = \"FloatSliderView\";\n }\n}\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/\/ -*- mode: C++; indent-tabs-mode: nil; c-basic-offset: 2; -*-\n\/\/ Color.cc for Blackbox - an X11 Window manager\n\/\/ Copyright (c) 2001 - 2005 Sean 'Shaleh' Perry <shaleh at debian.org>\n\/\/ Copyright (c) 1997 - 2000, 2002 - 2005\n\/\/ Bradley T Hughes <bhughes at trolltech.com>\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a\n\/\/ copy of this software and associated documentation files (the \"Software\"),\n\/\/ to deal in the Software without restriction, including without limitation\n\/\/ the rights to use, copy, modify, merge, publish, distribute, sublicense,\n\/\/ and\/or sell copies of the Software, and to permit persons to whom the\n\/\/ Software is furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n\/\/ THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n\/\/ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n\/\/ DEALINGS IN THE SOFTWARE.\n\n#include \"Color.hh\"\n#include \"Display.hh\"\n\n#include <map>\n\n#include <X11\/Xlib.h>\n\n#include <assert.h>\n#include <stdio.h>\n\n\/\/ #define COLORCACHE_DEBUG\n\n\nnamespace bt {\n\n class ColorCache {\n public:\n ColorCache(const Display &display);\n ~ColorCache(void);\n\n \/*\n Finds a color matching the specified rgb on the given screen.\n\n The color is allocated if needed; otherwise it is reference\n counted and freed when no more references for the color exist.\n *\/\n unsigned long find(unsigned int screen, int r, int g, int b);\n \/*\n Releases the specified rgb on the given screen.\n\n If the reference count for a particular color is zero, it will\n be freed by calling clear().\n *\/\n void release(unsigned int screen, int r, int g, int b);\n\n \/*\n Clears the color cache. All colors with a zero reference count\n are freed.\n\n If force is true, then all colors are freed, regardless of the\n reference count. This is done when destroying the cache.\n *\/\n void clear(bool force);\n\n private:\n const Display &_display;\n\n struct RGB {\n const unsigned int screen;\n const int r, g, b;\n\n inline RGB(void)\n : screen(~0u), r(-1), g(-1), b(-1)\n { }\n inline RGB(const unsigned int s, const int x, const int y, const int z)\n : screen(s), r(x), g(y), b(z)\n { }\n inline RGB(const RGB &x)\n : screen(x.screen), r(x.r), g(x.g), b(x.b)\n { }\n\n inline bool operator==(const RGB &x) const\n { return screen == x.screen && r == x.r && g == x.g && b == x.b; }\n\n inline bool operator<(const RGB &x) const {\n const unsigned long p1 =\n (screen << 24 | r << 16 | g << 8 | b) & 0xffffffff;\n const unsigned long p2 =\n (x.screen << 24 | x.r << 16 | x.g << 8 | x.b) & 0xffffffff;\n return p1 < p2;\n }\n };\n struct PixelRef {\n const unsigned long pixel;\n unsigned int count;\n inline PixelRef(void)\n : pixel(0ul), count(0u)\n { }\n inline PixelRef(const unsigned long x)\n : pixel(x), count(1u)\n { }\n };\n\n typedef std::map<RGB,PixelRef> Cache;\n typedef Cache::value_type CacheItem;\n Cache cache;\n };\n\n\n static ColorCache *colorcache = 0;\n\n\n void createColorCache(const Display &display) {\n assert(colorcache == 0);\n colorcache = new ColorCache(display);\n }\n\n\n void destroyColorCache(void) {\n delete colorcache;\n colorcache = 0;\n }\n\n} \/\/ namespace bt\n\n\nbt::ColorCache::ColorCache(const Display &display)\n : _display(display)\n{ }\n\n\nbt::ColorCache::~ColorCache(void)\n{ clear(true); }\n\n\nunsigned long bt::ColorCache::find(unsigned int screen, int r, int g, int b) {\n if (r < 0 && r > 255)\n r = 0;\n if (g < 0 && g > 255)\n g = 0;\n if (b < 0 && b > 255)\n b = 0;\n\n \/\/ see if we have allocated this color before\n RGB rgb(screen, r, g, b);\n Cache::iterator it = cache.find(rgb);\n if (it != cache.end()) {\n \/\/ found a cached color, use it\n ++it->second.count;\n\n#ifdef COLORCACHE_DEBUG\n fprintf(stderr, \"bt::ColorCache: use %02x\/%02x\/%02x, count %4u\\n\",\n r, g, b, it->second.count);\n#endif \/\/ COLORCACHE_DEBUG\n\n return it->second.pixel;\n }\n\n XColor xcol;\n xcol.red = r | r << 8;\n xcol.green = g | g << 8;\n xcol.blue = b | b << 8;\n xcol.pixel = 0;\n xcol.flags = DoRed | DoGreen | DoBlue;\n\n Colormap colormap = _display.screenInfo(screen).colormap();\n if (!XAllocColor(_display.XDisplay(), colormap, &xcol)) {\n fprintf(stderr,\n \"bt::Color::pixel: cannot allocate color 'rgb:%02x\/%02x\/%02x'\\n\",\n r, g, b);\n xcol.pixel = BlackPixel(_display.XDisplay(), screen);\n }\n\n#ifdef COLORCACHE_DEBUG\n fprintf(stderr, \"bt::ColorCache: add %02x\/%02x\/%02x, pixel %08lx\\n\",\n r, g, b, xcol.pixel);\n#endif \/\/ COLORCACHE_DEBUG\n\n cache.insert(CacheItem(rgb, PixelRef(xcol.pixel)));\n\n return xcol.pixel;\n}\n\n\nvoid bt::ColorCache::release(unsigned int screen, int r, int g, int b) {\n if (r < 0 && r > 255)\n r = 0;\n if (g < 0 && g > 255)\n g = 0;\n if (b < 0 && b > 255)\n b = 0;\n\n RGB rgb(screen, r, g, b);\n Cache::iterator it = cache.find(rgb);\n\n assert(it != cache.end() && it->second.count > 0);\n --it->second.count;\n\n#ifdef COLORCACHE_DEBUG\n fprintf(stderr, \"bt::ColorCache: rel %02x\/%02x\/%02x, count %4u\\n\",\n r, g, b, it->second.count);\n#endif \/\/ COLORCACHE_DEBUG\n}\n\n\nvoid bt::ColorCache::clear(bool force) {\n Cache::iterator it = cache.begin();\n if (it == cache.end())\n return; \/\/ nothing to do\n\n#ifdef COLORCACHE_DEBUG\n fprintf(stderr, \"bt::ColorCache: clearing cache, %u entries\\n\",\n cache.size());\n#endif \/\/ COLORCACHE_DEBUG\n\n unsigned long *pixels = new unsigned long[ cache.size() ];\n unsigned int screen, count;\n\n for (screen = 0; screen < _display.screenCount(); ++screen) {\n count = 0;\n it = cache.begin();\n while (it != cache.end()) {\n if (it->second.count != 0 && !force) {\n ++it;\n continue;\n }\n\n#ifdef COLORCACHE_DEBUG\n fprintf(stderr, \"bt::ColorCache: fre %02x\/%02x\/%02x, pixel %08lx\\n\",\n it->first.r, it->first.g, it->first.b, it->second.pixel);\n#endif \/\/ COLORCACHE_DEBUG\n\n pixels[count++] = it->second.pixel;\n\n Cache::iterator r = it++;\n cache.erase(r);\n }\n\n if (count > 0u) {\n XFreeColors(_display.XDisplay(),\n _display.screenInfo(screen).colormap(),\n pixels, count, 0);\n }\n }\n\n delete [] pixels;\n\n#ifdef COLORCACHE_DEBUG\n fprintf(stderr, \"bt::ColorCache: cleared, %u entries remain\\n\",\n cache.size());\n#endif \/\/ COLORCACHE_DEBUG\n}\n\n\nvoid bt::Color::clearCache(void)\n{\n if (colorcache)\n colorcache->clear(false);\n}\n\n\nbt::Color bt::Color::namedColor(const Display &display, unsigned int screen,\n const std::string &colorname) {\n if (colorname.empty()) {\n fprintf(stderr, \"bt::Color::namedColor: empty colorname\\n\");\n return Color();\n }\n\n \/\/ get rgb values from colorname\n XColor xcol;\n xcol.red = 0;\n xcol.green = 0;\n xcol.blue = 0;\n xcol.pixel = 0;\n\n Colormap colormap = display.screenInfo(screen).colormap();\n if (!XParseColor(display.XDisplay(), colormap, colorname.c_str(), &xcol)) {\n fprintf(stderr, \"bt::Color::namedColor: invalid color '%s'\\n\",\n colorname.c_str());\n return Color();\n }\n\n return Color(xcol.red >> 8, xcol.green >> 8, xcol.blue >> 8);\n}\n\n\nunsigned long bt::Color::pixel(unsigned int screen) const {\n if (_screen == screen)\n return _pixel; \/\/ already allocated on this screen\n\n assert(colorcache != 0);\n \/\/ deallocate() isn't const, so we can't call it from here\n if (_screen != ~0u)\n colorcache->release(_screen, _red, _green, _blue);\n\n _screen = screen;\n _pixel = colorcache->find(_screen, _red, _green, _blue);\n return _pixel;\n}\n\n\nvoid bt::Color::deallocate(void) {\n if (_screen == ~0u)\n return; \/\/ not allocated\n\n assert(colorcache != 0);\n colorcache->release(_screen, _red, _green, _blue);\n\n _screen = ~0u;\n _pixel = 0ul;\n}\n<commit_msg>Updated Documentation for the Color operations.<commit_after>\/*\n * ZebX - Display Management System.\n * Utilizes the tools under the BlackBox system.\n *\n * Color.cc for ZebX - Display Management System\n * Copyright (c) 2018 David Kroell <kroelld.96@gmail.com>\n *\n * Color.cc for Blackbox - an X11 Window manager\n * Copyright (c) 2001 - 2005 Sean 'Shaleh' Perry <shaleh at debian.org>\n * Copyright (c) 1997 - 2000, 2002 - 2005\n * Bradley T Hughes <bhughes at trolltech.com>\n *\/\n\n#include \"Color.hh\"\n#include \"Display.hh\"\n\n#include <map>\n\n#include <X11\/Xlib.h>\n\n#include <assert.h>\n#include <stdio.h>\n\n\/\/#define COLORCACHE_DEBUG \/* Define this to enable debugging for the build. *\/\n\nnamespace bt {\n\n class ColorCache {\n public:\n\n\t \/**\n\t * Serialized cache record of the Color object\n\t * associated with the application.\n\t *\n\t * The Display object is used to\n\t *\/\n\t ColorCache(const Display &display);\n\t ~ColorCache(void);\n\n \/*\n * Finds a color matching the specified rgb on the given screen.\n\t *\n\t * The color is allocated if needed; otherwise it is reference\n\t * counted and freed when no more references for the color exist.\n *\/\n\t unsigned long find(unsigned int screen, int r, int g, int b);\n\n\t \/*\n * Releases the specified rgb on the given screen.\n\t *\n * If the reference count for a particular color is zero, it will\n * be freed by calling clear().\n\t *\/\n\t void release(unsigned int screen, int r, int g, int b);\n\n \/*\n * Clears the color cache. All colors with a zero reference count\n * are freed.\n\t *\n * If force is true, then all colors are freed, regardless of the\n * reference count. This is done when destroying the cache.\n *\/\n void clear(bool force);\n\n private:\n\n \/** Display object to reference the screen display. *\/\n const Display &_display;\n\n \/**\n * Display object used to handle the color cache\n *\n * Params:\n * \tscreen: Screen id to use for the display reference.\n * \tr: Red hex level.\n * \tg: Green hex level.\n * \tb: Blue hex level.\n *\/\n struct RGB {\n \t const unsigned int screen;\n \t const int r, g, b;\n\n \t inline RGB(void) : screen(~0u), r(-1), g(-1), b(-1) { }\n\n \t inline RGB(const unsigned int s, const int x, const int y, const int z) : screen(s), r(x), g(y), b(z) { }\n\n \t inline RGB(const RGB &x) : screen(x.screen), r(x.r), g(x.g), b(x.b) { }\n\n \t inline bool operator==(const RGB &x) const { return screen == x.screen && r == x.r && g == x.g && b == x.b; }\n\n \t inline bool operator<(const RGB &x) const {\n \t\t const unsigned long p1 = (screen << 24 | r << 16 | g << 8 | b) & 0xffffffff;\n \t\t const unsigned long p2 = (x.screen << 24 | x.r << 16 | x.g << 8 | x.b) & 0xffffffff; return p1 < p2;\n \t }\n };\n\n \/**\n * Pixel reference to extend the X11 pixel display.\n *\n * Params:\n * \tpixel: pixel id to use as a reference.\n * \tcount: Count of the pixel usage to order properly in the Map.\n *\/\n struct PixelRef {\n \t const unsigned long pixel;\n \t unsigned int count;\n\n \t inline PixelRef(void) : pixel(0ul), count(0u) { }\n\n \t inline PixelRef(const unsigned long x) : pixel(x), count(1u) { }\n };\n\n \/** Cache maps Pixel ref to RGB. *\/\n typedef std::map<RGB,PixelRef> Cache;\n\n \/** Item for the cache map. *\/\n typedef Cache::value_type CacheItem;\n\n Cache cache;\n };\n\n\n static ColorCache *colorcache = 0;\n\n\n \/**\n * Method to construct ColorCache object\n *\n * Params:\n * \tdisplay: Object for the ScreenInfo placeholder.\n *\/\n void createColorCache(const Display &display) {\n\t assert(colorcache == 0);\n\t colorcache = new ColorCache(display);\n }\n\n\n \/**\n * Destroy function for the ColorCache object.\n * Mainly used for garbage collection.\n *\/\n void destroyColorCache(void) {\n\t delete colorcache;\n\t colorcache = 0;\n }\n\n} \/\/ namespace bt\n\n\/**\n * Constructor for the ColorCache object.\n *\n * Params:\n * \tdisplay: Display placeholder to access ScreenInfo.\n *\/\nbt::ColorCache::ColorCache(const Display &display) : _display(display) { }\n\n\/**\n * Destructor for the ColorCache Object.\n *\/\nbt::ColorCache::~ColorCache(void) { clear(true); }\n\n\/**\n * Method to find a Screen reference with the given RGB code tagged to it.\n *\n * Params:\n * \t\tscreen: Screen ID to use for the display reference.\n * \t\tr: Red hex level.\n * \t\tg: Green hex level.\n * \t\tb: Blue hex level.\n *\/\nunsigned long bt::ColorCache::find(unsigned int screen, int r, int g, int b) {\n\tif (r < 0 && r > 255)\n\t\tr = 0;\n\n\tif (g < 0 && g > 255)\n\t\tg = 0;\n\n\tif (b < 0 && b > 255)\n\t\tb = 0;\n\n\t\/\/ see if we have allocated this color before\n\tRGB rgb(screen, r, g, b);\n\n\t\/\/ iterator to loop through the entire Map.\n\tCache::iterator it = cache.find(rgb);\n\n\t\/\/ loop and basecase.\n\tif (it != cache.end()) {\n\n\t\t\/\/ found a cached color, use it\n\t\t++it->second.count;\n\n\t\t\/\/ Debugging statement.\n\t\t#ifdef COLORCACHE_DEBUG\n\t\t\tfprintf(stderr, \"bt::ColorCache: use %02x\/%02x\/%02x, count %4u\\n\",\n\t\t\t\t\tr, g, b, it->second.count);\n\t\t#endif \/\/ COLORCACHE_DEBUG\n\n\t\treturn it->second.pixel;\n\t}\n\n\t\/\/ We haven't found the Color in the Map.\n\t\/\/ We need to\n\n\tXColor xcol;\n\txcol.red = r | r << 8;\n\txcol.green = g | g << 8;\n\txcol.blue = b | b << 8;\n\txcol.pixel = 0;\n\txcol.flags = DoRed | DoGreen | DoBlue;\n\n\t\/\/ Get the color map.\n\tColormap colormap = _display.screenInfo(screen).colormap();\n\n\t\/\/ If we can't allocate the color with the display, then display a black pixel.\n\tif (!XAllocColor(_display.XDisplay(), colormap, &xcol)) {\n\t\tfprintf(stderr,\n\t\t\t\t\"bt::Color::pixel: cannot allocate color 'rgb:%02x\/%02x\/%02x'\\n\",\n\t\t\t\tr, g, b);\n\n\t\txcol.pixel = BlackPixel(_display.XDisplay(), screen);\n\t}\n\n#ifdef COLORCACHE_DEBUG\n fprintf(stderr, \"bt::ColorCache: add %02x\/%02x\/%02x, pixel %08lx\\n\",\n r, g, b, xcol.pixel);\n#endif \/\/ COLORCACHE_DEBUG\n\n \t\/\/ Insert the Pixel Reference to the cache.\n cache.insert(CacheItem(rgb, PixelRef(xcol.pixel)));\n\n \/\/ Return the pixel.\n return xcol.pixel;\n}\n\n\nvoid bt::ColorCache::release(unsigned int screen, int r, int g, int b) {\n\tif (r < 0 && r > 255)\n\t\tr = 0;\n\n\tif (g < 0 && g > 255)\n\t\tg = 0;\n\n\tif (b < 0 && b > 255)\n\t\tb = 0;\n\n\n\tRGB rgb(screen, r, g, b);\n\n\t\/\/ Iterator to look through and release the Color object.\n\tCache::iterator it = cache.find(rgb);\n\n\tassert(it != cache.end() && it->second.count > 0);\n\n\t\/\/ Decrement the count of the pixel usage.\n\t--it->second.count;\n\n#ifdef COLORCACHE_DEBUG\n fprintf(stderr, \"bt::ColorCache: rel %02x\/%02x\/%02x, count %4u\\n\",\n r, g, b, it->second.count);\n#endif \/\/ COLORCACHE_DEBUG\n\n}\n\n\/**\n * Clear the color cache for garbage collection.\n *\n * Params:\n * \t\tforce: Force the object to destruct?\n *\/\nvoid bt::ColorCache::clear(bool force) {\n\n\t\/\/ Iterator to loop through cache.\n\tCache::iterator it = cache.begin();\n\n\t\/\/ End loop.\n\tif (it == cache.end())\n\t\treturn; \/\/ nothing to do\n\n#ifdef COLORCACHE_DEBUG\n fprintf(stderr, \"bt::ColorCache: clearing cache, %u entries\\n\",\n cache.size());\n#endif \/\/ COLORCACHE_DEBUG\n\n \/\/ Array of pixels to hold.\n \tunsigned long *pixels = new unsigned long[ cache.size() ];\n\n \tunsigned int screen, count;\n\n \t\/\/ loop through the screens.\n \tfor (screen = 0; screen < _display.screenCount(); ++screen) {\n\n \t\t\/\/ Begin iterator for the cache.\n \t\tcount = 0;\n \t\tit = cache.begin();\n\n \t\t\/\/ Loop through and increment the count.\n \t\twhile (it != cache.end()) {\n \t\t\tif (it->second.count != 0 && !force) {\n \t\t\t\t++it;\n \t\t\t\tcontinue;\n \t\t\t}\n\n#ifdef COLORCACHE_DEBUG\n fprintf(stderr, \"bt::ColorCache: fre %02x\/%02x\/%02x, pixel %08lx\\n\",\n it->first.r, it->first.g, it->first.b, it->second.pixel);\n#endif \/\/ COLORCACHE_DEBUG\n\n \t \/\/ Populate pixel index.\n \t pixels[count++] = it->second.pixel;\n\n \t \/\/ erase the ColorCache object and increment the iterator.\n \t Cache::iterator r = it++;\n \t cache.erase(r);\n \t\t}\n\n \t\t\/\/ If the count is greater than the referenced pixel count.\n \t\t\/\/ Free the cells represented by the pixels\n \t\tif (count > 0u) {\n\n \t\t\tXFreeColors(\n \t\t\t\t\t_display.XDisplay(),\n \t\t\t\t\t_display.screenInfo(screen).colormap(),\n\t\t\t\t\tpixels, count, 0\n\t\t\t\t);\n \t\t}\n \t}\n\n \t\/\/ Get rid of the pixels array.\n \tdelete [] pixels;\n\n#ifdef COLORCACHE_DEBUG\n fprintf(stderr, \"bt::ColorCache: cleared, %u entries remain\\n\",\n cache.size());\n#endif \/\/ COLORCACHE_DEBUG\n}\n\n\/\/ Clear the ColorCache\nvoid bt::Color::clearCache(void) {\n\tif (colorcache)\n\t\tcolorcache->clear(false);\n}\n\n\/**\n * Get a Color object from the named Object.\n *\n * Params:\n * \t\tdisplay: Display object to reference.\n * \t\tscreen: Screen to reference.\n * \t\tcolorname: name of color to convert from.\n *\n * See:\n * \t\tXParseColor(...)\n *\/\nbt::Color bt::Color::namedColor(const Display &display, unsigned int screen,\n const std::string &colorname) {\n\n\n\n\t\/\/ Make sure there's no empty Color.\n\tif (colorname.empty()) {\n\t\tfprintf(stderr, \"bt::Color::namedColor: empty colorname\\n\");\n\t\treturn Color();\n\t}\n\n\t\/\/ get rgb values from colorname\n\tXColor xcol;\n\txcol.red = 0;\n\txcol.green = 0;\n\txcol.blue = 0;\n\txcol.pixel = 0;\n\n\t\/\/ Color map to parse from.\n\tColormap colormap = display.screenInfo(screen).colormap();\n\n\t\/\/ If we can't parse the color name then don't return a specific color.\n\tif (!XParseColor(display.XDisplay(), colormap, colorname.c_str(), &xcol)) {\n\t\tfprintf(stderr, \"bt::Color::namedColor: invalid color '%s'\\n\",\n\t\t\t\tcolorname.c_str());\n\n\t\treturn Color();\n\t}\n\n\t\/\/ Return a color from the referenced map.\n\treturn Color(xcol.red >> 8, xcol.green >> 8, xcol.blue >> 8);\n}\n\n\/**\n * Get the Pixel associated with the preset RGB values.\n *\n * params:\n * \t\tscreen: Which screen ID to look at.\n *\n *\/\nunsigned long bt::Color::pixel(unsigned int screen) const {\n\n\n\tif (_screen == screen)\n\t\treturn _pixel; \/\/ already allocated on this screen\n\n\n\tassert(colorcache != 0);\n\n\t\/\/ deallocate() isn't const, so we can't call it from here\n\tif (_screen != ~0u)\n\t\tcolorcache->release(_screen, _red, _green, _blue); \/\/ But... Deallocate...\n\n\t\/\/Assign the screen value to the preset.\n\t_screen = screen;\n\n\t\/\/ Find the correct pixel and return it.\n\t_pixel = colorcache->find(_screen, _red, _green, _blue);\n\treturn _pixel;\n}\n\n\/**\n * deallocate the screen and pixel values for the object.\n * Bring back to normal use.\n *\n *\/\nvoid bt::Color::deallocate(void) {\n\tif (_screen == ~0u)\n\t\treturn; \/\/ not allocated\n\n\tassert(colorcache != 0);\n\n\t\/\/ Release a pixel of the screen associated with the RGB\n\tcolorcache->release(_screen, _red, _green, _blue);\n\n\t\/\/ Reset the screen and pixel values.\n\t_screen = ~0u;\n\t_pixel = 0ul;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"clustering\/administration\/main\/directory_lock.hpp\"\n\n#ifndef _MSC_VER\n#include <dirent.h>\n#include <sys\/file.h>\n#else\n#include <filesystem>\n#include <direct.h>\n#endif\n\n#include <sys\/stat.h>\n#include <sys\/types.h>\n#include <unistd.h>\n#include <fcntl.h>\n\n#include <stdexcept>\n\n#include \"arch\/io\/disk.hpp\"\n\nbool check_existence(const base_path_t& base_path) {\n return 0 == access(base_path.path().c_str(), F_OK);\n}\n\nbool check_dir_emptiness(const base_path_t& base_path) {\n#ifdef _MSC_VER\n for (auto it : std::tr2::sys::directory_iterator(base_path.path())) {\n return false;\n }\n return true;\n#else\n DIR *dp;\n struct dirent *ep;\n\n dp = opendir(base_path.path().c_str());\n if (dp == NULL) {\n throw directory_open_failed_exc_t(get_errno(), base_path);\n }\n\n set_errno(0);\n\n \/\/ cpplint is wrong about readdir here, because POSIX guarantees we're not\n \/\/ sharing a static buffer with other threads on the system. Even better, OS X\n \/\/ and Linux glibc both allocate per-directory buffers. readdir_r is unsafe\n \/\/ because you can't specify the length of the struct dirent buffer you pass in\n \/\/ to it. See http:\/\/elliotth.blogspot.com\/2012\/10\/how-not-to-use-readdirr3.html\n while ((ep = readdir(dp)) != NULL) { \/\/ NOLINT(runtime\/threadsafe_fn)\n if (strcmp(ep->d_name, \".\") != 0 && strcmp(ep->d_name, \"..\") != 0) {\n closedir(dp);\n return false;\n }\n }\n guarantee_err(get_errno() == 0, \"Error while reading directory\");\n\n closedir(dp);\n return true;\n#endif\n}\n\ndirectory_lock_t::directory_lock_t(const base_path_t &path, bool create, bool *created_out) :\n directory_path(path),\n created(false),\n initialize_done(false) {\n\n *created_out = false;\n bool dir_exists = check_existence(directory_path);\n\n if (!dir_exists) {\n if (!create) {\n throw directory_missing_exc_t(directory_path);\n }\n int mkdir_res;\n do {\n#if defined(__MINGW32__)\n mkdir_res = mkdir(directory_path.path().c_str());\n#elif defined(_WIN32)\n mkdir_res = _mkdir(directory_path.path().c_str());\n#else\n mkdir_res = mkdir(directory_path.path().c_str(), 0755);\n#endif\n } while (mkdir_res == -1 && get_errno() == EINTR);\n if (mkdir_res != 0) {\n throw directory_create_failed_exc_t(get_errno(), directory_path);\n }\n created = true;\n *created_out = true;\n\n \/\/ Call fsync() on the parent directory to guarantee that the newly\n \/\/ created directory's directory entry is persisted to disk.\n warn_fsync_parent_directory(directory_path.path().c_str());\n } else if (create && check_dir_emptiness(directory_path)) {\n created = true;\n *created_out = true;\n }\n\n#ifdef _WIN32\n \/\/ TODO WINDOWS: issue #5165\n directory_fd.reset(CreateFile(directory_path.path().c_str(), GENERIC_READ, 0, NULL,\n OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_BACKUP_SEMANTICS, NULL));\n if (directory_fd.get() == INVALID_FD) {\n logERR(\"CreateFile failed: %s\", winerr_string(GetLastError()).c_str());\n throw directory_open_failed_exc_t(EIO, directory_path);\n }\n#else\n directory_fd.reset(::open(directory_path.path().c_str(), O_RDONLY));\n if (directory_fd.get() == INVALID_FD) {\n throw directory_open_failed_exc_t(get_errno(), directory_path);\n }\n if (flock(directory_fd.get(), LOCK_EX | LOCK_NB) != 0) {\n throw directory_locked_exc_t(directory_path);\n }\n#endif\n}\n\ndirectory_lock_t::~directory_lock_t() {\n \/\/ Only delete the directory if we created it and haven't finished initialization\n if (created && !initialize_done) {\n remove_directory_recursive(directory_path.path().c_str());\n }\n}\n\nvoid directory_lock_t::directory_initialized() {\n guarantee(directory_fd.get() != INVALID_FD);\n initialize_done = true;\n}\n\n#ifndef _WIN32\nvoid directory_lock_t::change_ownership(gid_t group_id, const std::string &group_name,\n uid_t user_id, const std::string &user_name) {\n if (group_id != INVALID_GID || user_id != INVALID_UID) {\n if (fchown(directory_fd.get(), user_id, group_id) != 0) {\n throw std::runtime_error(strprintf(\"Failed to change ownership of data \"\n \"directory '%s' to '%s:%s': %s\",\n directory_path.path().c_str(),\n user_name.c_str(),\n group_name.c_str(),\n errno_string(get_errno()).c_str()));\n }\n }\n}\n#endif\n<commit_msg>improve directory locking<commit_after>#include \"clustering\/administration\/main\/directory_lock.hpp\"\n\n#ifndef _MSC_VER\n#include <dirent.h>\n#include <sys\/file.h>\n#else\n#include <filesystem>\n#include <direct.h>\n#endif\n\n#include <sys\/stat.h>\n#include <sys\/types.h>\n#include <unistd.h>\n#include <fcntl.h>\n\n#include <stdexcept>\n\n#include \"arch\/io\/disk.hpp\"\n\n#ifdef _WIN32\n#define LOCK_FILE_NAME \"dirlock\"\n#endif\n\nbool check_existence(const base_path_t& base_path) {\n return 0 == access(base_path.path().c_str(), F_OK);\n}\n\nbool check_dir_emptiness(const base_path_t& base_path) {\n#ifdef _MSC_VER\n for (auto it : std::tr2::sys::directory_iterator(base_path.path())) {\n return false;\n }\n return true;\n#else\n DIR *dp;\n struct dirent *ep;\n\n dp = opendir(base_path.path().c_str());\n if (dp == NULL) {\n throw directory_open_failed_exc_t(get_errno(), base_path);\n }\n\n set_errno(0);\n\n \/\/ cpplint is wrong about readdir here, because POSIX guarantees we're not\n \/\/ sharing a static buffer with other threads on the system. Even better, OS X\n \/\/ and Linux glibc both allocate per-directory buffers. readdir_r is unsafe\n \/\/ because you can't specify the length of the struct dirent buffer you pass in\n \/\/ to it. See http:\/\/elliotth.blogspot.com\/2012\/10\/how-not-to-use-readdirr3.html\n while ((ep = readdir(dp)) != NULL) { \/\/ NOLINT(runtime\/threadsafe_fn)\n if (strcmp(ep->d_name, \".\") != 0 && strcmp(ep->d_name, \"..\") != 0) {\n closedir(dp);\n return false;\n }\n }\n guarantee_err(get_errno() == 0, \"Error while reading directory\");\n\n closedir(dp);\n return true;\n#endif\n}\n\ndirectory_lock_t::directory_lock_t(const base_path_t &path, bool create, bool *created_out) :\n directory_path(path),\n created(false),\n initialize_done(false) {\n\n *created_out = false;\n bool dir_exists = check_existence(directory_path);\n\n if (!dir_exists) {\n if (!create) {\n throw directory_missing_exc_t(directory_path);\n }\n int mkdir_res;\n do {\n#if defined(__MINGW32__)\n mkdir_res = mkdir(directory_path.path().c_str());\n#elif defined(_WIN32)\n mkdir_res = _mkdir(directory_path.path().c_str());\n#else\n mkdir_res = mkdir(directory_path.path().c_str(), 0755);\n#endif\n } while (mkdir_res == -1 && get_errno() == EINTR);\n if (mkdir_res != 0) {\n throw directory_create_failed_exc_t(get_errno(), directory_path);\n }\n created = true;\n *created_out = true;\n\n \/\/ Call fsync() on the parent directory to guarantee that the newly\n \/\/ created directory's directory entry is persisted to disk.\n warn_fsync_parent_directory(directory_path.path().c_str());\n } else if (create && check_dir_emptiness(directory_path)) {\n created = true;\n *created_out = true;\n }\n\n#ifdef _WIN32\n directory_fd.reset(CreateFile((directory_path.path() + \"\\\\\" LOCK_FILE_NAME).c_str(),\n GENERIC_READ | GENERIC_WRITE, 0, NULL,\n CREATE_ALWAYS, FILE_ATTRIBUTE_HIDDEN | FILE_FLAG_DELETE_ON_CLOSE, NULL));\n if (directory_fd.get() == INVALID_FD) {\n logERR(\"CreateFile failed: %s\", winerr_string(GetLastError()).c_str());\n throw directory_open_failed_exc_t(EIO, directory_path);\n }\n#else\n directory_fd.reset(::open(directory_path.path().c_str(), O_RDONLY));\n if (directory_fd.get() == INVALID_FD) {\n throw directory_open_failed_exc_t(get_errno(), directory_path);\n }\n if (flock(directory_fd.get(), LOCK_EX | LOCK_NB) != 0) {\n throw directory_locked_exc_t(directory_path);\n }\n#endif\n}\n\ndirectory_lock_t::~directory_lock_t() {\n \/\/ Only delete the directory if we created it and haven't finished initialization\n if (created && !initialize_done) {\n#ifdef _WIN32\n \/\/ On windows, the directory lock is a file inside the directory\n \/\/ TODO ATN: but this unlocks the directory!\n directory_fd.reset();\n#endif\n remove_directory_recursive(directory_path.path().c_str());\n }\n}\n\nvoid directory_lock_t::directory_initialized() {\n guarantee(directory_fd.get() != INVALID_FD);\n initialize_done = true;\n}\n\n#ifndef _WIN32\nvoid directory_lock_t::change_ownership(gid_t group_id, const std::string &group_name,\n uid_t user_id, const std::string &user_name) {\n if (group_id != INVALID_GID || user_id != INVALID_UID) {\n if (fchown(directory_fd.get(), user_id, group_id) != 0) {\n throw std::runtime_error(strprintf(\"Failed to change ownership of data \"\n \"directory '%s' to '%s:%s': %s\",\n directory_path.path().c_str(),\n user_name.c_str(),\n group_name.c_str(),\n errno_string(get_errno()).c_str()));\n }\n }\n}\n#endif\n<|endoftext|>"} {"text":"<commit_before>\n#include <EagleLib\/rcc\/shared_ptr.hpp>\n#include <EagleLib\/nodes\/NodeManager.h>\n#include \"EagleLib\/nodes\/Node.h\"\n#include \"EagleLib\/Plugins.h\"\n#include <EagleLib\/DataStreamManager.h>\n#include <EagleLib\/Logging.h>\n#include <signal.h>\n#include <signals\/logging.hpp>\n\n#include <boost\/program_options.hpp>\n#include <boost\/log\/core.hpp>\n#include <boost\/log\/trivial.hpp>\n#include <boost\/log\/expressions.hpp>\n#include <boost\/log\/sinks.hpp>\n#include <boost\/log\/attributes.hpp>\n#include <boost\/log\/common.hpp>\n#include <boost\/log\/exceptions.hpp>\n#include <boost\/log\/utility\/setup\/file.hpp>\n#include <boost\/filesystem.hpp>\n#include <boost\/version.hpp>\n#include <boost\/tokenizer.hpp>\n\n#include <parameters\/Persistence\/TextSerializer.hpp>\n\nvoid PrintNodeTree(EagleLib::Nodes::Node* node, int depth)\n{\n for(int i = 0; i < depth; ++i)\n {\n std::cout << \"=\";\n }\n std::cout << node->getFullTreeName() << std::endl;\n for(int i = 0; i < node->children.size(); ++i)\n {\n PrintNodeTree(node->children[i].get(), depth + 1);\n }\n}\nstatic volatile bool quit;\nvoid sig_handler(int s)\n{\n \/\/std::cout << \"Caught signal \" << s << std::endl;\n\tBOOST_LOG_TRIVIAL(error) << \"Caught signal \" << s;\n quit = true;\n}\n\nint main(int argc, char* argv[])\n{\n\tsignal(SIGINT, sig_handler);\n\tsignal(SIGILL, sig_handler);\n\tsignal(SIGTERM, sig_handler);\n \n boost::program_options::options_description desc(\"Allowed options\");\n\t\n \/\/boost::log::add_file_log(boost::log::keywords::file_name = \"SimpleConsole%N.log\", boost::log::keywords::rotation_size = 10 * 1024 * 1024);\n EagleLib::SetupLogging();\n \n \n desc.add_options()\n (\"file\", boost::program_options::value<std::string>(), \"Required - File to load for processing\")\n (\"config\", boost::program_options::value<std::string>(), \"Required - File containing node structure\")\n (\"plugins\", boost::program_options::value<boost::filesystem::path>(), \"Path to additional plugins to load\")\n\t\t(\"log\", boost::program_options::value<std::string>()->default_value(\"info\"), \"Logging verbosity. trace, debug, info, warning, error, fatal\")\n (\"mode\", boost::program_options::value<std::string>()->default_value(\"batch\"), \"Processing mode, options are interactive or batch\")\n ;\n\n boost::program_options::variables_map vm;\n boost::program_options::store(boost::program_options::parse_command_line(argc, argv, desc), vm);\n \n if((!vm.count(\"config\") || !vm.count(\"file\")) && vm[\"mode\"].as<std::string>() == \"batch\")\n {\n LOG(info) << \"Batch mode selected but \\\"file\\\" and \\\"config\\\" options not set\";\n std::cout << desc;\n return 1;\n }\n\tif (vm.count(\"log\"))\n\t{\n\t\tstd::string verbosity = vm[\"log\"].as<std::string>();\n\t\tif (verbosity == \"trace\")\n\t\t\tboost::log::core::get()->set_filter(boost::log::trivial::severity >= boost::log::trivial::trace);\n\t\tif (verbosity == \"debug\")\n\t\t\tboost::log::core::get()->set_filter(boost::log::trivial::severity >= boost::log::trivial::debug);\n\t\tif (verbosity == \"info\")\n\t\t\tboost::log::core::get()->set_filter(boost::log::trivial::severity >= boost::log::trivial::info);\n\t\tif (verbosity == \"warning\")\n\t\t\tboost::log::core::get()->set_filter(boost::log::trivial::severity >= boost::log::trivial::warning);\n\t\tif (verbosity == \"error\")\n\t\t\tboost::log::core::get()->set_filter(boost::log::trivial::severity >= boost::log::trivial::error);\n\t\tif (verbosity == \"fatal\")\n\t\t\tboost::log::core::get()->set_filter(boost::log::trivial::severity >= boost::log::trivial::fatal);\n\t}else\n {\n \tboost::log::core::get()->set_filter(boost::log::trivial::severity >= boost::log::trivial::info);\n }\n\tboost::filesystem::path currentDir = boost::filesystem::current_path();\n#ifdef _DEBUG\n currentDir.append(\"..\/Debug\");\n#else\n currentDir.append(\"..\/RelWithDebInfo\");\n#endif\n boost::filesystem::directory_iterator end_itr;\n\n for(boost::filesystem::directory_iterator itr(currentDir); itr != end_itr; ++itr)\n {\n if(boost::filesystem::is_regular_file(itr->path()))\n {\n#ifdef _MSC_VER\n if(itr->path().extension() == \".dll\")\n#else\n if(itr->path().extension() == \".so\")\n#endif\n {\n std::string file = itr->path().string();\n EagleLib::loadPlugin(file);\n }else\n {\n std::cout << itr->path().extension() << std::endl;\n }\n }\n }\n\n if(vm.count(\"plugins\"))\n {\n currentDir = boost::filesystem::path(vm[\"plugins\"].as<boost::filesystem::path>());\n for (boost::filesystem::directory_iterator itr(currentDir); itr != end_itr; ++itr)\n {\n if (boost::filesystem::is_regular_file(itr->path()))\n {\n#ifdef _MSC_VER\n if (itr->path().extension() == \".dll\")\n#else\n if (itr->path().extension() == \".so\")\n#endif\n {\n std::string file = itr->path().string();\n EagleLib::loadPlugin(file);\n }\n else\n {\n std::cout << itr->path().extension() << std::endl;\n }\n }\n }\n }\n\n if(vm[\"mode\"].as<std::string>() == \"batch\")\n {\n quit = false;\n std::string document = vm[\"file\"].as<std::string>();\n LOG(info) << \"Loading file: \" << document;\n std::string configFile = vm[\"config\"].as<std::string>();\n LOG(info) << \"Loading config file \" << configFile;\n \n\n auto stream = EagleLib::DataStreamManager::instance()->create_stream();\n stream->LoadDocument(document);\n \n auto nodes = EagleLib::NodeManager::getInstance().loadNodes(configFile);\n stream->AddNode(nodes);\n\n LOG(info) << \"Loaded \" << nodes.size() << \" top level nodes\";\n for(int i = 0; i < nodes.size(); ++i)\n {\n PrintNodeTree(nodes[i].get(), 1);\n }\n stream->process();\n }else\n {\n std::vector<std::shared_ptr<EagleLib::DataStream>> _dataStreams;\n EagleLib::DataStream* current_stream = nullptr;\n EagleLib::Nodes::Node* current_node = nullptr;\n\n auto print_options = []()->void\n {\n std::cout << \n \"- Options: \\n \"\n \" - LoadFile {document} -- Create a frame grabber for a document \\n\"\n \" - Add {node} -- Add a node to the current selected object\\n\"\n \" - List {nodes} -- List all possible nodes that can be constructed\\n\"\n \" - Print {streams,nodes,parameters, current} -- Prints the current streams, nodes in current stream, \\n\"\n \" or parameters of current node\\n\"\n \" - Select {node,stream} -- Select a node by name (relative to current selection\\n\"\n \" or absolute, or a stream by index)\\n\"\n \" - Save -- Save node configuration\\n\"\n \" - Load -- Load node configuration\\n\"\n \" - Help -- Print this help\\n\"\n \" - Quit -- Close program and cleanup\\n\";\n };\n\n std::map<std::string, std::function<void(std::string)>> function_map;\n function_map[\"LoadFile\"] = [&_dataStreams](std::string doc)->void\n {\n if(EagleLib::DataStream::CanLoadDocument(doc))\n {\n LOG(debug) << \"Found a frame grabber which can load \" << doc;\n auto stream = EagleLib::DataStreamManager::instance()->create_stream();\n if(stream->LoadDocument(doc))\n {\n _dataStreams.push_back(stream);\n }else\n {\n LOG(warning) << \"Unable to load document\";\n }\n }else\n {\n LOG(warning) << \"Unable to find a frame grabber which can load \" << doc;\n }\n };\n function_map[\"Quit\"] = [](std::string)->void\n {\n quit = true;\n };\n function_map[\"Print\"] = [&_dataStreams, ¤t_stream, ¤t_node](std::string what)->void\n {\n if(what == \"streams\")\n {\n for(auto& itr : _dataStreams)\n {\n std::cout << \" - \" << itr->get_stream_id() << \" - \" << itr->GetFrameGrabber()->GetSourceFilename() << \"\\n\";\n }\n }\n if(what == \"nodes\")\n {\n if(current_stream)\n {\n auto nodes = current_stream->GetNodes();\n for(auto& node : nodes)\n {\n PrintNodeTree(node.get(), 0);\n }\n }\n else if(current_node)\n {\n PrintNodeTree(current_node, 0);\n }\n }\n if(what == \"parameters\")\n {\n std::vector<std::shared_ptr<Parameters::Parameter>> parameters;\n if(current_node)\n {\n parameters = current_node->getParameters();\n }\n if(current_stream)\n {\n parameters = current_stream->GetFrameGrabber()->getParameters();\n }\n for(auto& itr : parameters)\n {\n std::stringstream ss;\n try\n {\n Parameters::Persistence::Text::Serialize(&ss, itr.get()); \n std::cout << \" - \" << itr->GetTreeName() << \": \" << ss.str() << \"\\n\";\n }catch(...)\n {\n std::cout << \" - \" << itr->GetTreeName() << \"\\n\";\n }\n }\n }\n if(what == \"current\")\n {\n if(current_stream)\n {\n std::cout << \" - Current stream: \" << current_stream->GetFrameGrabber()->GetSourceFilename() << \"\\n\";\n return;\n }\n if(current_node)\n {\n std::cout << \" - Current node: \" << current_node->getFullTreeName() << \"\\n\";\n return;\n }\n std::cout << \"Nothing currently selected\\n\";\n }\n };\n function_map[\"Select\"] = [&_dataStreams,¤t_stream, ¤t_node](std::string what)\n {\n int idx = -1;\n std::string name;\n \n try\n {\n idx = boost::lexical_cast<int>(what);\n }catch(...)\n {\n idx = -1;\n }\n if(idx == -1)\n {\n name = what;\n }\n if(idx != -1)\n {\n LOG(info) << \"Selecting stream \" << idx;\n for(auto& itr : _dataStreams)\n {\n if(itr->get_stream_id() == idx)\n {\n current_stream = itr.get();\n current_node = nullptr;\n return;\n }\n }\n }\n if(current_stream)\n {\n \/\/ look for a node with this name, relative then look absolute\n auto nodes = current_stream->GetNodes();\n for(auto& node : nodes)\n {\n if(node->getTreeName() == what)\n {\n current_stream = nullptr;\n current_node = node.get();\n return;\n }\n }\n \/\/ parse name and try to find absolute path to node\n\n }\n \n };\n function_map[\"Help\"] = [&print_options](std::string)->void{print_options();};\n function_map[\"List\"] = [](std::string)->void\n {\n auto nodes = EagleLib::NodeManager::getInstance().getConstructableNodes();\n for(auto& node : nodes)\n {\n std::cout << \" - \" << node << \"\\n\";\n }\n };\n function_map[\"Add\"] = [¤t_node, ¤t_stream](std::string name)->void\n {\n auto node = EagleLib::NodeManager::getInstance().addNode(name);\n if(!node)\n {\n return;\n }\n if(current_node)\n {\n current_node->addChild(node);\n return;\n }\n if(current_stream)\n {\n current_stream->AddNode(node);\n return;\n }\n };\n \n print_options();\n \n while(!quit)\n {\n std::string command_line;\n std::getline(std::cin, command_line);\n int count = 0;\n\t std::stringstream ss;\n ss << command_line;\n std::string command;\n std::getline(ss, command, ' ');\n if(function_map.count(command))\n {\n std::string rest;\n ss >> rest;\n LOG(debug) << \"Executing command (\" << command << \") with arguments: \" << rest;\n function_map[command](rest);\n }else\n {\n LOG(warning) << \"Invalid command: \" << command_line;\n print_options();\n }\n }\n LOG(info) << \"Shutting down\";\n }\n \n \n return 0;\n}\n<commit_msg>Linux fixes.<commit_after>\n#include <EagleLib\/rcc\/shared_ptr.hpp>\n#include <EagleLib\/nodes\/NodeManager.h>\n#include \"EagleLib\/nodes\/Node.h\"\n#include \"EagleLib\/Plugins.h\"\n#include <EagleLib\/DataStreamManager.h>\n#include <EagleLib\/Logging.h>\n#include <signal.h>\n#include <signals\/logging.hpp>\n\n#include <boost\/program_options.hpp>\n#include <boost\/log\/core.hpp>\n#include <boost\/log\/trivial.hpp>\n#include <boost\/log\/expressions.hpp>\n#include <boost\/log\/sinks.hpp>\n#include <boost\/log\/attributes.hpp>\n#include <boost\/log\/common.hpp>\n#include <boost\/log\/exceptions.hpp>\n#include <boost\/log\/utility\/setup\/file.hpp>\n#include <boost\/filesystem.hpp>\n#include <boost\/version.hpp>\n#include <boost\/tokenizer.hpp>\n\n#include <parameters\/Persistence\/TextSerializer.hpp>\n\nvoid PrintNodeTree(EagleLib::Nodes::Node* node, int depth)\n{\n for(int i = 0; i < depth; ++i)\n {\n std::cout << \"=\";\n }\n std::cout << node->getFullTreeName() << std::endl;\n for(int i = 0; i < node->children.size(); ++i)\n {\n PrintNodeTree(node->children[i].get(), depth + 1);\n }\n}\nstatic volatile bool quit;\nvoid sig_handler(int s)\n{\n \/\/std::cout << \"Caught signal \" << s << std::endl;\n\tBOOST_LOG_TRIVIAL(error) << \"Caught signal \" << s;\n quit = true;\n}\n\nint main(int argc, char* argv[])\n{\n\tsignal(SIGINT, sig_handler);\n\tsignal(SIGILL, sig_handler);\n\tsignal(SIGTERM, sig_handler);\n \n boost::program_options::options_description desc(\"Allowed options\");\n\t\n \/\/boost::log::add_file_log(boost::log::keywords::file_name = \"SimpleConsole%N.log\", boost::log::keywords::rotation_size = 10 * 1024 * 1024);\n EagleLib::SetupLogging();\n \n \n desc.add_options()\n (\"file\", boost::program_options::value<std::string>(), \"Required - File to load for processing\")\n (\"config\", boost::program_options::value<std::string>(), \"Required - File containing node structure\")\n (\"plugins\", boost::program_options::value<boost::filesystem::path>(), \"Path to additional plugins to load\")\n\t\t(\"log\", boost::program_options::value<std::string>()->default_value(\"info\"), \"Logging verbosity. trace, debug, info, warning, error, fatal\")\n (\"mode\", boost::program_options::value<std::string>()->default_value(\"batch\"), \"Processing mode, options are interactive or batch\")\n ;\n\n boost::program_options::variables_map vm;\n boost::program_options::store(boost::program_options::parse_command_line(argc, argv, desc), vm);\n \n if((!vm.count(\"config\") || !vm.count(\"file\")) && vm[\"mode\"].as<std::string>() == \"batch\")\n {\n LOG(info) << \"Batch mode selected but \\\"file\\\" and \\\"config\\\" options not set\";\n std::cout << desc;\n return 1;\n }\n\tif (vm.count(\"log\"))\n\t{\n\t\tstd::string verbosity = vm[\"log\"].as<std::string>();\n\t\tif (verbosity == \"trace\")\n\t\t\tboost::log::core::get()->set_filter(boost::log::trivial::severity >= boost::log::trivial::trace);\n\t\tif (verbosity == \"debug\")\n\t\t\tboost::log::core::get()->set_filter(boost::log::trivial::severity >= boost::log::trivial::debug);\n\t\tif (verbosity == \"info\")\n\t\t\tboost::log::core::get()->set_filter(boost::log::trivial::severity >= boost::log::trivial::info);\n\t\tif (verbosity == \"warning\")\n\t\t\tboost::log::core::get()->set_filter(boost::log::trivial::severity >= boost::log::trivial::warning);\n\t\tif (verbosity == \"error\")\n\t\t\tboost::log::core::get()->set_filter(boost::log::trivial::severity >= boost::log::trivial::error);\n\t\tif (verbosity == \"fatal\")\n\t\t\tboost::log::core::get()->set_filter(boost::log::trivial::severity >= boost::log::trivial::fatal);\n\t}else\n {\n \tboost::log::core::get()->set_filter(boost::log::trivial::severity >= boost::log::trivial::info);\n }\n\tboost::filesystem::path currentDir = boost::filesystem::current_path();\n#ifdef _MSC_VER\n#ifdef _DEBUG\n currentDir = boost::filesystem::path(currentDir.string() + \"..\/Debug\");\n#else\n currentDir = boost::filesystem::path(currentDir.string() + \"..\/RelWithDebInfo\");\n#endif\n#else\n currentDir = boost::filesystem::path(currentDir.string() + \"\/Plugins\");\n#endif\n boost::filesystem::directory_iterator end_itr;\n\n for(boost::filesystem::directory_iterator itr(currentDir); itr != end_itr; ++itr)\n {\n if(boost::filesystem::is_regular_file(itr->path()))\n {\n#ifdef _MSC_VER\n if(itr->path().extension() == \".dll\")\n#else\n if(itr->path().extension() == \".so\")\n#endif\n {\n std::string file = itr->path().string();\n EagleLib::loadPlugin(file);\n }else\n {\n std::cout << itr->path().extension() << std::endl;\n }\n }\n }\n\n if(vm.count(\"plugins\"))\n {\n currentDir = boost::filesystem::path(vm[\"plugins\"].as<boost::filesystem::path>());\n for (boost::filesystem::directory_iterator itr(currentDir); itr != end_itr; ++itr)\n {\n if (boost::filesystem::is_regular_file(itr->path()))\n {\n#ifdef _MSC_VER\n if (itr->path().extension() == \".dll\")\n#else\n if (itr->path().extension() == \".so\")\n#endif\n {\n std::string file = itr->path().string();\n EagleLib::loadPlugin(file);\n }\n else\n {\n std::cout << itr->path().extension() << std::endl;\n }\n }\n }\n }\n\n if(vm[\"mode\"].as<std::string>() == \"batch\")\n {\n quit = false;\n std::string document = vm[\"file\"].as<std::string>();\n LOG(info) << \"Loading file: \" << document;\n std::string configFile = vm[\"config\"].as<std::string>();\n LOG(info) << \"Loading config file \" << configFile;\n \n\n auto stream = EagleLib::DataStreamManager::instance()->create_stream();\n stream->LoadDocument(document);\n \n auto nodes = EagleLib::NodeManager::getInstance().loadNodes(configFile);\n stream->AddNode(nodes);\n\n LOG(info) << \"Loaded \" << nodes.size() << \" top level nodes\";\n for(int i = 0; i < nodes.size(); ++i)\n {\n PrintNodeTree(nodes[i].get(), 1);\n }\n stream->process();\n }else\n {\n std::vector<std::shared_ptr<EagleLib::DataStream>> _dataStreams;\n EagleLib::DataStream* current_stream = nullptr;\n EagleLib::Nodes::Node* current_node = nullptr;\n\n auto print_options = []()->void\n {\n std::cout << \n \"- Options: \\n \"\n \" - LoadFile {document} -- Create a frame grabber for a document \\n\"\n \" - Add {node} -- Add a node to the current selected object\\n\"\n \" - List {nodes} -- List all possible nodes that can be constructed\\n\"\n \" - Print {streams,nodes,parameters, current} -- Prints the current streams, nodes in current stream, \\n\"\n \" or parameters of current node\\n\"\n \" - Select {node,stream} -- Select a node by name (relative to current selection\\n\"\n \" or absolute, or a stream by index)\\n\"\n \" - Save -- Save node configuration\\n\"\n \" - Load -- Load node configuration\\n\"\n \" - Help -- Print this help\\n\"\n \" - Quit -- Close program and cleanup\\n\";\n };\n\n std::map<std::string, std::function<void(std::string)>> function_map;\n function_map[\"LoadFile\"] = [&_dataStreams](std::string doc)->void\n {\n if(EagleLib::DataStream::CanLoadDocument(doc))\n {\n LOG(debug) << \"Found a frame grabber which can load \" << doc;\n auto stream = EagleLib::DataStreamManager::instance()->create_stream();\n if(stream->LoadDocument(doc))\n {\n _dataStreams.push_back(stream);\n }else\n {\n LOG(warning) << \"Unable to load document\";\n }\n }else\n {\n LOG(warning) << \"Unable to find a frame grabber which can load \" << doc;\n }\n };\n function_map[\"Quit\"] = [](std::string)->void\n {\n quit = true;\n };\n function_map[\"Print\"] = [&_dataStreams, ¤t_stream, ¤t_node](std::string what)->void\n {\n if(what == \"streams\")\n {\n for(auto& itr : _dataStreams)\n {\n std::cout << \" - \" << itr->get_stream_id() << \" - \" << itr->GetFrameGrabber()->GetSourceFilename() << \"\\n\";\n }\n }\n if(what == \"nodes\")\n {\n if(current_stream)\n {\n auto nodes = current_stream->GetNodes();\n for(auto& node : nodes)\n {\n PrintNodeTree(node.get(), 0);\n }\n }\n else if(current_node)\n {\n PrintNodeTree(current_node, 0);\n }\n }\n if(what == \"parameters\")\n {\n std::vector<std::shared_ptr<Parameters::Parameter>> parameters;\n if(current_node)\n {\n parameters = current_node->getParameters();\n }\n if(current_stream)\n {\n parameters = current_stream->GetFrameGrabber()->getParameters();\n }\n for(auto& itr : parameters)\n {\n std::stringstream ss;\n try\n {\n Parameters::Persistence::Text::Serialize(&ss, itr.get()); \n std::cout << \" - \" << itr->GetTreeName() << \": \" << ss.str() << \"\\n\";\n }catch(...)\n {\n std::cout << \" - \" << itr->GetTreeName() << \"\\n\";\n }\n }\n }\n if(what == \"current\")\n {\n if(current_stream)\n {\n std::cout << \" - Current stream: \" << current_stream->GetFrameGrabber()->GetSourceFilename() << \"\\n\";\n return;\n }\n if(current_node)\n {\n std::cout << \" - Current node: \" << current_node->getFullTreeName() << \"\\n\";\n return;\n }\n std::cout << \"Nothing currently selected\\n\";\n }\n };\n function_map[\"Select\"] = [&_dataStreams,¤t_stream, ¤t_node](std::string what)\n {\n int idx = -1;\n std::string name;\n \n try\n {\n idx = boost::lexical_cast<int>(what);\n }catch(...)\n {\n idx = -1;\n }\n if(idx == -1)\n {\n name = what;\n }\n if(idx != -1)\n {\n LOG(info) << \"Selecting stream \" << idx;\n for(auto& itr : _dataStreams)\n {\n if(itr->get_stream_id() == idx)\n {\n current_stream = itr.get();\n current_node = nullptr;\n return;\n }\n }\n }\n if(current_stream)\n {\n \/\/ look for a node with this name, relative then look absolute\n auto nodes = current_stream->GetNodes();\n for(auto& node : nodes)\n {\n if(node->getTreeName() == what)\n {\n current_stream = nullptr;\n current_node = node.get();\n return;\n }\n }\n \/\/ parse name and try to find absolute path to node\n\n }\n \n };\n function_map[\"Help\"] = [&print_options](std::string)->void{print_options();};\n function_map[\"List\"] = [](std::string)->void\n {\n auto nodes = EagleLib::NodeManager::getInstance().getConstructableNodes();\n for(auto& node : nodes)\n {\n std::cout << \" - \" << node << \"\\n\";\n }\n };\n function_map[\"Add\"] = [¤t_node, ¤t_stream](std::string name)->void\n {\n auto node = EagleLib::NodeManager::getInstance().addNode(name);\n if(!node)\n {\n return;\n }\n if(current_node)\n {\n current_node->addChild(node);\n return;\n }\n if(current_stream)\n {\n current_stream->AddNode(node);\n return;\n }\n };\n \n print_options();\n \n while(!quit)\n {\n std::string command_line;\n std::getline(std::cin, command_line);\n int count = 0;\n\t std::stringstream ss;\n ss << command_line;\n std::string command;\n std::getline(ss, command, ' ');\n if(function_map.count(command))\n {\n std::string rest;\n ss >> rest;\n LOG(debug) << \"Executing command (\" << command << \") with arguments: \" << rest;\n function_map[command](rest);\n }else\n {\n LOG(warning) << \"Invalid command: \" << command_line;\n print_options();\n }\n }\n LOG(info) << \"Shutting down\";\n }\n \n \n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*=========================================================================\n\n Program: Visualization Toolkit\n Module: vtkImageMirrorPad.cxx\n Language: C++\n Date: $Date$\n Version: $Revision$\n Thanks: Thanks to C. Charles Law who developed this class.\n\nCopyright (c) 1993-1995 Ken Martin, Will Schroeder, Bill Lorensen.\n\nThis software is copyrighted by Ken Martin, Will Schroeder and Bill Lorensen.\nThe following terms apply to all files associated with the software unless\nexplicitly disclaimed in individual files. This copyright specifically does\nnot apply to the related textbook \"The Visualization Toolkit\" ISBN\n013199837-4 published by Prentice Hall which is covered by its own copyright.\n\nThe authors hereby grant permission to use, copy, and distribute this\nsoftware and its documentation for any purpose, provided that existing\ncopyright notices are retained in all copies and that this notice is included\nverbatim in any distributions. Additionally, the authors grant permission to\nmodify this software and its documentation for any purpose, provided that\nsuch modifications are not distributed without the explicit consent of the\nauthors and that existing copyright notices are retained in all copies. Some\nof the algorithms implemented by this software are patented, observe all\napplicable patent law.\n\nIN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR\nDIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT\nOF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF,\nEVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\nTHE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING,\nBUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\nPARTICULAR PURPOSE, AND NON-INFRINGEMENT. THIS SOFTWARE IS PROVIDED ON AN\n\"AS IS\" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE\nMAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.\n\n\n=========================================================================*\/\n\n#include \"vtkImageMirrorPad.h\"\n\n\n\n\/\/----------------------------------------------------------------------------\n\/\/ Just clip the request.\nvoid vtkImageMirrorPad::ComputeRequiredInputUpdateExtent(int inExt[6], \n\t\t\t\t\t\t\t int outExt[6])\n{\n int *wExtent = this->GetInput()->GetWholeExtent();\n int idx;\n \n \/\/ initialize inExt\n memcpy(inExt,wExtent,6*sizeof(int));\n\n \/\/ a simple approximation to the required extent\n \/\/ basically get the whole extent for an axis unless a fully\n \/\/ contained subset is being requested. If so then use that.\n for (idx = 0; idx < 3; idx++)\n {\n if (outExt[idx*2] >= wExtent[idx*2] &&\n\toutExt[idx*2+1] <= wExtent[idx*2+1])\n {\n inExt[idx*2] = outExt[idx*2];\n inExt[idx*2+1] = outExt[idx*2+1];\n }\n }\n}\n\n\n\/\/----------------------------------------------------------------------------\ntemplate <class T>\nstatic void vtkImageMirrorPadExecute(vtkImageMirrorPad *self,\n\t\t\t\t vtkImageData *inData,\n\t\t\t\t vtkImageData *outData, T *outPtr,\n\t\t\t\t int outExt[6], int id)\n{\n int idxC, idxX, idxY, idxZ;\n int maxX, maxY, maxZ;\n int inInc[3];\n int inIncStart[3];\n int inIncX, inIncY, inIncZ;\n int outIncX, outIncY, outIncZ;\n unsigned long count = 0;\n unsigned long target;\n int *wExtent = self->GetInput()->GetWholeExtent();\n int pad[6], idx;\n int inIdxStart[3];\n int inIdx[3];\n T *inPtr, *inPtrX, *inPtrY, *inPtrZ;\n int maxC, inMaxC;\n \n \/\/ find the region to loop over\n inMaxC = inData->GetNumberOfScalarComponents();\n maxC = outData->GetNumberOfScalarComponents();\n maxX = outExt[1] - outExt[0]; \n maxY = outExt[3] - outExt[2]; \n maxZ = outExt[5] - outExt[4];\n target = (unsigned long)((maxZ+1)*(maxY+1)\/50.0);\n target++;\n \n \/\/ Get increments to march through data \n inData->GetIncrements(inIncX, inIncY, inIncZ);\n outData->GetContinuousIncrements(outExt, outIncX, outIncY, outIncZ);\n\n \/\/ how much padding is required ?\n \/\/ if padding is required on a boundary then we know we need the whole extent\n \/\/ for that boundary. The following code handles the cases where the outputextent\n \/\/ is all inside or outside of the whole extent\n for (idx = 0; idx < 3; idx++)\n {\n pad[idx*2] = 0;\n pad[idx*2+1] = 0;\n if (outExt[idx*2] < wExtent[idx*2])\n {\n pad[idx*2] = wExtent[idx*2] - outExt[idx*2];\n }\n if (outExt[idx*2+1] > wExtent[idx*2+1])\n {\n pad[idx*2+1] = outExt[idx*2+1] - wExtent[idx*2+1];\n }\n }\n \n \/\/ find the starting point\n for (idx = 0; idx < 3; idx++)\n {\n inIdxStart[idx] = outExt[idx*2];\n inIncStart[idx] = 1;\n while (inIdxStart[idx] < wExtent[idx*2])\n {\n inIncStart[idx] = -inIncStart[idx];\n inIdxStart[idx] = inIdxStart[idx] + (wExtent[idx*2+1] - wExtent[idx*2] + 1);\n }\n while (inIdxStart[idx] > wExtent[idx*2+1])\n {\n inIncStart[idx] = -inIncStart[idx];\n inIdxStart[idx] = inIdxStart[idx] - (wExtent[idx*2+1] - wExtent[idx*2] + 1);\n }\n \/\/ if we are heading negative then we need to mirror the offset\n if (inIncStart[idx] < 0)\n {\n inIdxStart[idx] = wExtent[idx*2+1] - inIdxStart[idx] + wExtent[idx*2];\n }\n }\n inPtr = (T *)inData->GetScalarPointer(inIdxStart[0], inIdxStart[1], inIdxStart[2]);\n \n \/\/ Loop through ouput pixels\n inPtrZ = inPtr;\n inIdx[2] = inIdxStart[2];\n inInc[2] = inIncStart[2];\n for (idxZ = 0; idxZ <= maxZ; idxZ++)\n {\n inPtrY = inPtrZ;\n inIdx[1] = inIdxStart[1];\n inInc[1] = inIncStart[1];\n for (idxY = 0; !self->AbortExecute && idxY <= maxY; idxY++)\n {\n inPtrX = inPtrY;\n inIdx[0] = inIdxStart[0];\n inInc[0] = inIncStart[0];\n if (!id) \n\t{\n\tif (!(count%target))\n\t {\n\t self->UpdateProgress(count\/(50.0*target));\n\t }\n\tcount++;\n\t}\n\n \/\/ if components are same much faster\n if ((maxC == inMaxC) && (maxC == 1))\n\t{\n\tfor (idxX = 0; idxX <= maxX; idxX++)\n\t {\n\t \/\/ Pixel operation\n\t *outPtr = *inPtrX;\n\t outPtr++;\n\t inIdx[0] += inInc[0];\n\t inPtrX = inPtrX + inInc[0]*inIncX;\n\t if (inIdx[0] < wExtent[0] || inIdx[0] > wExtent[1])\n\t {\n\t inInc[0] *= -1;\n\t inIdx[0] += inInc[0];\n\t inPtrX = inPtrX + inInc[0]*inIncX;\n\t }\n\t }\n\t}\n else \/\/ components are not the same\n\t{\n\tfor (idxX = 0; idxX <= maxX; idxX++)\n\t {\n\t for (idxC = 0; idxC < maxC; idxC++)\n\t {\n\t \/\/ Pixel operation\n\t if (idxC < inMaxC)\n\t {\n\t *outPtr = *(inPtrX + idxC);\n\t }\n\t else\n\t {\n\t *outPtr = *(inPtrX + idxC%inMaxC);\n\t }\n\t outPtr++;\n\t }\n\t inIdx[0] += inInc[0];\n\t inPtrX = inPtrX + inInc[0]*inIncX;\n\t if (inIdx[0] < wExtent[0] || inIdx[0] > wExtent[1])\n\t {\n\t inInc[0] *= -1;\n\t inIdx[0] += inInc[0];\n\t inPtrX = inPtrX + inInc[0]*inIncX;\n\t }\n\t }\n\t}\n \n outPtr += outIncY;\n inIdx[1] += inInc[1];\n inPtrY = inPtrY + inInc[1]*inIncY;\n if (inIdx[1] < wExtent[2] || inIdx[1] > wExtent[3])\n\t{\n\tinInc[1] *= -1;\n\tinIdx[1] += inInc[1];\n\tinPtrY = inPtrY + inInc[1]*inIncY;\n\t}\n }\n outPtr += outIncZ;\n inIdx[2] += inInc[2];\n inPtrZ = inPtrZ + inInc[2]*inIncZ;\n if (inIdx[2] < wExtent[4] || inIdx[2] > wExtent[5])\n {\n inInc[2] *= -1;\n inIdx[2] += inInc[2];\n inPtrZ = inPtrZ + inInc[2]*inIncZ;\n }\n }\n}\n\n\n\n\/\/----------------------------------------------------------------------------\n\/\/ This method is passed a input and output data, and executes the filter\n\/\/ algorithm to fill the output from the input.\n\/\/ It just executes a switch statement to call the correct function for\n\/\/ the regions data types.\nvoid vtkImageMirrorPad::ThreadedExecute(vtkImageData *inData, \n\t\t\t\t\tvtkImageData *outData,\n\t\t\t\t\tint outExt[6], int id)\n{\n void *outPtr = outData->GetScalarPointerForExtent(outExt);\n \n vtkDebugMacro(<< \"Execute: inData = \" << inData \n\t\t<< \", outData = \" << outData);\n \n \/\/ this filter expects that input is the same type as output.\n if (inData->GetScalarType() != outData->GetScalarType())\n {\n vtkErrorMacro(<< \"Execute: input ScalarType, \" << inData->GetScalarType()\n << \", must match out ScalarType \" << outData->GetScalarType());\n return;\n }\n \n switch (inData->GetScalarType())\n {\n case VTK_DOUBLE:\n vtkImageMirrorPadExecute(this, inData, outData, \n\t\t\t (double *)(outPtr), outExt, id);\n break;\n case VTK_FLOAT:\n vtkImageMirrorPadExecute(this, inData, outData, \n\t\t\t (float *)(outPtr), outExt, id);\n break;\n case VTK_LONG:\n vtkImageMirrorPadExecute(this, inData, outData, \n\t\t\t (long *)(outPtr), outExt, id);\n break;\n case VTK_UNSIGNED_LONG:\n vtkImageMirrorPadExecute(this, inData, outData, \n\t\t\t (unsigned long *)(outPtr), outExt, id);\n break;\n case VTK_INT:\n vtkImageMirrorPadExecute(this, inData, outData, \n\t\t\t (int *)(outPtr), outExt, id);\n break;\n case VTK_UNSIGNED_INT:\n vtkImageMirrorPadExecute(this, inData, outData, \n\t\t\t (unsigned int *)(outPtr), outExt, id);\n break;\n case VTK_SHORT:\n vtkImageMirrorPadExecute(this, inData, outData, \n\t\t\t (short *)(outPtr), outExt, id);\n break;\n case VTK_UNSIGNED_SHORT:\n vtkImageMirrorPadExecute(this, inData, outData, \n\t\t\t (unsigned short *)(outPtr), outExt, id);\n break;\n case VTK_CHAR:\n vtkImageMirrorPadExecute(this, inData, outData, \n\t\t\t (char *)(outPtr), outExt, id);\n break;\n case VTK_UNSIGNED_CHAR:\n vtkImageMirrorPadExecute(this, inData, outData, \n\t\t\t (unsigned char *)(outPtr), outExt, id);\n break;\n default:\n vtkErrorMacro(<< \"Execute: Unknown ScalarType\");\n return;\n }\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n<commit_msg>ERR: removed warnings.<commit_after>\/*=========================================================================\n\n Program: Visualization Toolkit\n Module: vtkImageMirrorPad.cxx\n Language: C++\n Date: $Date$\n Version: $Revision$\n Thanks: Thanks to C. Charles Law who developed this class.\n\nCopyright (c) 1993-1995 Ken Martin, Will Schroeder, Bill Lorensen.\n\nThis software is copyrighted by Ken Martin, Will Schroeder and Bill Lorensen.\nThe following terms apply to all files associated with the software unless\nexplicitly disclaimed in individual files. This copyright specifically does\nnot apply to the related textbook \"The Visualization Toolkit\" ISBN\n013199837-4 published by Prentice Hall which is covered by its own copyright.\n\nThe authors hereby grant permission to use, copy, and distribute this\nsoftware and its documentation for any purpose, provided that existing\ncopyright notices are retained in all copies and that this notice is included\nverbatim in any distributions. Additionally, the authors grant permission to\nmodify this software and its documentation for any purpose, provided that\nsuch modifications are not distributed without the explicit consent of the\nauthors and that existing copyright notices are retained in all copies. Some\nof the algorithms implemented by this software are patented, observe all\napplicable patent law.\n\nIN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR\nDIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT\nOF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF,\nEVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\nTHE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING,\nBUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\nPARTICULAR PURPOSE, AND NON-INFRINGEMENT. THIS SOFTWARE IS PROVIDED ON AN\n\"AS IS\" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE\nMAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.\n\n\n=========================================================================*\/\n\n#include \"vtkImageMirrorPad.h\"\n\n\n\n\/\/----------------------------------------------------------------------------\n\/\/ Just clip the request.\nvoid vtkImageMirrorPad::ComputeRequiredInputUpdateExtent(int inExt[6], \n\t\t\t\t\t\t\t int outExt[6])\n{\n int *wExtent = this->GetInput()->GetWholeExtent();\n int idx;\n \n \/\/ initialize inExt\n memcpy(inExt,wExtent,6*sizeof(int));\n\n \/\/ a simple approximation to the required extent\n \/\/ basically get the whole extent for an axis unless a fully\n \/\/ contained subset is being requested. If so then use that.\n for (idx = 0; idx < 3; idx++)\n {\n if (outExt[idx*2] >= wExtent[idx*2] &&\n\toutExt[idx*2+1] <= wExtent[idx*2+1])\n {\n inExt[idx*2] = outExt[idx*2];\n inExt[idx*2+1] = outExt[idx*2+1];\n }\n }\n}\n\n\n\/\/----------------------------------------------------------------------------\ntemplate <class T>\nstatic void vtkImageMirrorPadExecute(vtkImageMirrorPad *self,\n\t\t\t\t vtkImageData *inData,\n\t\t\t\t vtkImageData *outData, T *outPtr,\n\t\t\t\t int outExt[6], int id)\n{\n int idxC, idxX, idxY, idxZ;\n int maxX, maxY, maxZ;\n int inInc[3];\n int inIncStart[3];\n int inIncX, inIncY, inIncZ;\n int outIncX, outIncY, outIncZ;\n unsigned long count = 0;\n unsigned long target;\n int *wExtent = self->GetInput()->GetWholeExtent();\n int idx;\n int inIdxStart[3];\n int inIdx[3];\n T *inPtr, *inPtrX, *inPtrY, *inPtrZ;\n int maxC, inMaxC;\n \n \/\/ find the region to loop over\n inMaxC = inData->GetNumberOfScalarComponents();\n maxC = outData->GetNumberOfScalarComponents();\n maxX = outExt[1] - outExt[0]; \n maxY = outExt[3] - outExt[2]; \n maxZ = outExt[5] - outExt[4];\n target = (unsigned long)((maxZ+1)*(maxY+1)\/50.0);\n target++;\n \n \/\/ Get increments to march through data \n inData->GetIncrements(inIncX, inIncY, inIncZ);\n outData->GetContinuousIncrements(outExt, outIncX, outIncY, outIncZ);\n\n \/\/ find the starting point\n for (idx = 0; idx < 3; idx++)\n {\n inIdxStart[idx] = outExt[idx*2];\n inIncStart[idx] = 1;\n while (inIdxStart[idx] < wExtent[idx*2])\n {\n inIncStart[idx] = -inIncStart[idx];\n inIdxStart[idx] = inIdxStart[idx] + (wExtent[idx*2+1] - wExtent[idx*2] + 1);\n }\n while (inIdxStart[idx] > wExtent[idx*2+1])\n {\n inIncStart[idx] = -inIncStart[idx];\n inIdxStart[idx] = inIdxStart[idx] - (wExtent[idx*2+1] - wExtent[idx*2] + 1);\n }\n \/\/ if we are heading negative then we need to mirror the offset\n if (inIncStart[idx] < 0)\n {\n inIdxStart[idx] = wExtent[idx*2+1] - inIdxStart[idx] + wExtent[idx*2];\n }\n }\n inPtr = (T *)inData->GetScalarPointer(inIdxStart[0], inIdxStart[1], inIdxStart[2]);\n \n \/\/ Loop through ouput pixels\n inPtrZ = inPtr;\n inIdx[2] = inIdxStart[2];\n inInc[2] = inIncStart[2];\n for (idxZ = 0; idxZ <= maxZ; idxZ++)\n {\n inPtrY = inPtrZ;\n inIdx[1] = inIdxStart[1];\n inInc[1] = inIncStart[1];\n for (idxY = 0; !self->AbortExecute && idxY <= maxY; idxY++)\n {\n inPtrX = inPtrY;\n inIdx[0] = inIdxStart[0];\n inInc[0] = inIncStart[0];\n if (!id) \n\t{\n\tif (!(count%target))\n\t {\n\t self->UpdateProgress(count\/(50.0*target));\n\t }\n\tcount++;\n\t}\n\n \/\/ if components are same much faster\n if ((maxC == inMaxC) && (maxC == 1))\n\t{\n\tfor (idxX = 0; idxX <= maxX; idxX++)\n\t {\n\t \/\/ Pixel operation\n\t *outPtr = *inPtrX;\n\t outPtr++;\n\t inIdx[0] += inInc[0];\n\t inPtrX = inPtrX + inInc[0]*inIncX;\n\t if (inIdx[0] < wExtent[0] || inIdx[0] > wExtent[1])\n\t {\n\t inInc[0] *= -1;\n\t inIdx[0] += inInc[0];\n\t inPtrX = inPtrX + inInc[0]*inIncX;\n\t }\n\t }\n\t}\n else \/\/ components are not the same\n\t{\n\tfor (idxX = 0; idxX <= maxX; idxX++)\n\t {\n\t for (idxC = 0; idxC < maxC; idxC++)\n\t {\n\t \/\/ Pixel operation\n\t if (idxC < inMaxC)\n\t {\n\t *outPtr = *(inPtrX + idxC);\n\t }\n\t else\n\t {\n\t *outPtr = *(inPtrX + idxC%inMaxC);\n\t }\n\t outPtr++;\n\t }\n\t inIdx[0] += inInc[0];\n\t inPtrX = inPtrX + inInc[0]*inIncX;\n\t if (inIdx[0] < wExtent[0] || inIdx[0] > wExtent[1])\n\t {\n\t inInc[0] *= -1;\n\t inIdx[0] += inInc[0];\n\t inPtrX = inPtrX + inInc[0]*inIncX;\n\t }\n\t }\n\t}\n \n outPtr += outIncY;\n inIdx[1] += inInc[1];\n inPtrY = inPtrY + inInc[1]*inIncY;\n if (inIdx[1] < wExtent[2] || inIdx[1] > wExtent[3])\n\t{\n\tinInc[1] *= -1;\n\tinIdx[1] += inInc[1];\n\tinPtrY = inPtrY + inInc[1]*inIncY;\n\t}\n }\n outPtr += outIncZ;\n inIdx[2] += inInc[2];\n inPtrZ = inPtrZ + inInc[2]*inIncZ;\n if (inIdx[2] < wExtent[4] || inIdx[2] > wExtent[5])\n {\n inInc[2] *= -1;\n inIdx[2] += inInc[2];\n inPtrZ = inPtrZ + inInc[2]*inIncZ;\n }\n }\n}\n\n\n\n\/\/----------------------------------------------------------------------------\n\/\/ This method is passed a input and output data, and executes the filter\n\/\/ algorithm to fill the output from the input.\n\/\/ It just executes a switch statement to call the correct function for\n\/\/ the regions data types.\nvoid vtkImageMirrorPad::ThreadedExecute(vtkImageData *inData, \n\t\t\t\t\tvtkImageData *outData,\n\t\t\t\t\tint outExt[6], int id)\n{\n void *outPtr = outData->GetScalarPointerForExtent(outExt);\n \n vtkDebugMacro(<< \"Execute: inData = \" << inData \n\t\t<< \", outData = \" << outData);\n \n \/\/ this filter expects that input is the same type as output.\n if (inData->GetScalarType() != outData->GetScalarType())\n {\n vtkErrorMacro(<< \"Execute: input ScalarType, \" << inData->GetScalarType()\n << \", must match out ScalarType \" << outData->GetScalarType());\n return;\n }\n \n switch (inData->GetScalarType())\n {\n case VTK_DOUBLE:\n vtkImageMirrorPadExecute(this, inData, outData, \n\t\t\t (double *)(outPtr), outExt, id);\n break;\n case VTK_FLOAT:\n vtkImageMirrorPadExecute(this, inData, outData, \n\t\t\t (float *)(outPtr), outExt, id);\n break;\n case VTK_LONG:\n vtkImageMirrorPadExecute(this, inData, outData, \n\t\t\t (long *)(outPtr), outExt, id);\n break;\n case VTK_UNSIGNED_LONG:\n vtkImageMirrorPadExecute(this, inData, outData, \n\t\t\t (unsigned long *)(outPtr), outExt, id);\n break;\n case VTK_INT:\n vtkImageMirrorPadExecute(this, inData, outData, \n\t\t\t (int *)(outPtr), outExt, id);\n break;\n case VTK_UNSIGNED_INT:\n vtkImageMirrorPadExecute(this, inData, outData, \n\t\t\t (unsigned int *)(outPtr), outExt, id);\n break;\n case VTK_SHORT:\n vtkImageMirrorPadExecute(this, inData, outData, \n\t\t\t (short *)(outPtr), outExt, id);\n break;\n case VTK_UNSIGNED_SHORT:\n vtkImageMirrorPadExecute(this, inData, outData, \n\t\t\t (unsigned short *)(outPtr), outExt, id);\n break;\n case VTK_CHAR:\n vtkImageMirrorPadExecute(this, inData, outData, \n\t\t\t (char *)(outPtr), outExt, id);\n break;\n case VTK_UNSIGNED_CHAR:\n vtkImageMirrorPadExecute(this, inData, outData, \n\t\t\t (unsigned char *)(outPtr), outExt, id);\n break;\n default:\n vtkErrorMacro(<< \"Execute: Unknown ScalarType\");\n return;\n }\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n<|endoftext|>"} {"text":"<commit_before>#include \"opencv2\/imgproc\/imgproc.hpp\"\n#include \"opencv2\/highgui\/highgui.hpp\"\n\n#include <cstdio>\n#include <iostream>\n\nusing namespace cv;\nusing namespace std;\n\nMat markerMask, img;\nPoint prevPt(-1, -1);\n\nvoid onMouse( int event, int x, int y, int flags, void* )\n{\n if( x < 0 || x >= img.cols || y < 0 || y >= img.rows )\n return;\n if( event == CV_EVENT_LBUTTONUP || !(flags & CV_EVENT_FLAG_LBUTTON) )\n prevPt = Point(-1,-1);\n else if( event == CV_EVENT_LBUTTONDOWN )\n prevPt = Point(x,y);\n else if( event == CV_EVENT_MOUSEMOVE && (flags & CV_EVENT_FLAG_LBUTTON) )\n {\n Point pt(x, y);\n if( prevPt.x < 0 )\n prevPt = pt;\n line( markerMask, prevPt, pt, Scalar::all(255), 5, 8, 0 );\n line( img, prevPt, pt, Scalar::all(255), 5, 8, 0 );\n prevPt = pt;\n imshow(\"image\", img);\n }\n}\n\n\nint main( int argc, char** argv )\n{\n char* filename = argc >= 2 ? argv[1] : (char*)\"fruits.jpg\";\n Mat img0 = imread(filename, 1), imgGray;\n \n if( img0.empty() )\n {\n cout << \"Usage: watershed <image_name>\\n\";\n return 0;\n }\n\n cout << \"Hot keys: \\n\"\n \"\\tESC - quit the program\\n\"\n \"\\tr - restore the original image\\n\"\n \"\\tw or SPACE - run watershed algorithm\\n\"\n \"\\t\\t(before running it, roughly mark the areas on the image)\\n\"\n \"\\t (before that, roughly outline several markers on the image)\\n\";\n \n namedWindow( \"image\", 1 );\n\n img0.copyTo(img);\n cvtColor(img, markerMask, CV_BGR2GRAY);\n cvtColor(markerMask, imgGray, CV_GRAY2BGR);\n markerMask = Scalar::all(0);\n imshow( \"image\", img );\n setMouseCallback( \"image\", onMouse, 0 );\n\n for(;;)\n {\n int c = waitKey(0);\n\n if( (char)c == 27 )\n break;\n\n if( (char)c == 'r' )\n {\n markerMask = Scalar::all(0);\n img0.copyTo(img);\n imshow( \"image\", img );\n }\n\n if( (char)c == 'w' || (char)c == ' ' )\n {\n int i, j, compCount = 0;\n vector<vector<Point> > contours;\n vector<Vec4i> hierarchy;\n \n findContours(markerMask, contours, hierarchy, CV_RETR_CCOMP, CV_CHAIN_APPROX_SIMPLE);\n \n Mat markers(markerMask.size(), CV_32S);\n markers = Scalar::all(0);\n int idx = 0;\n for( ; idx >= 0; idx = hierarchy[idx][0], compCount++ )\n drawContours(markers, contours, idx, Scalar::all(compCount+1), -1, 8, hierarchy, INT_MAX);\n\n if( compCount == 0 )\n continue;\n \n vector<Vec3b> colorTab;\n for( i = 0; i < compCount; i++ )\n {\n int b = theRNG().uniform(0, 255);\n int g = theRNG().uniform(0, 255);\n int r = theRNG().uniform(0, 255);\n \n colorTab.push_back(Vec3b((uchar)b, (uchar)g, (uchar)r));\n }\n\n double t = (double)getTickCount();\n watershed( img0, markers );\n t = (double)getTickCount() - t;\n printf( \"execution time = %gms\\n\", t*1000.\/getTickFrequency() );\n\n Mat wshed(markers.size(), CV_8UC3);\n \n \/\/ paint the watershed image\n for( i = 0; i < markers.rows; i++ )\n for( j = 0; j < markers.cols; j++ )\n {\n int idx = markers.at<int>(i,j);\n if( idx == -1 )\n wshed.at<Vec3b>(i,j) = Vec3b(255,255,255);\n else if( idx <= 0 || idx > compCount )\n wshed.at<Vec3b>(i,j) = Vec3b(0,0,0);\n else\n wshed.at<Vec3b>(i,j) = colorTab[idx - 1];\n }\n\n wshed = wshed*0.5 + imgGray*0.5;\n imshow( \"watershed transform\", wshed );\n }\n }\n\n return 0;\n}\n<commit_msg>revamped<commit_after>#include \"opencv2\/imgproc\/imgproc.hpp\"\n#include \"opencv2\/highgui\/highgui.hpp\"\n\n#include <cstdio>\n#include <iostream>\n\nusing namespace cv;\nusing namespace std;\n\nvoid help()\n{\n\tcout << \"\\nThis program demonstrates the famous watershed segmentation algorithm in OpenCV: watershed()\\n\"\n\t\t\t\"Usage:\\n\"\n\t\t\t\".\/watershed [image_name -- default is fruits.jpg]\\n\" << endl;\n\n\n\tcout << \"Hot keys: \\n\"\n\t\t\"\\tESC - quit the program\\n\"\n\t\t\"\\tr - restore the original image\\n\"\n\t\t\"\\tw or SPACE - run watershed segmentation algorithm\\n\"\n\t\t\"\\t\\t(before running it, *roughly* mark the areas to segment on the image)\\n\"\n\t\t\"\\t (before that, roughly outline several markers on the image)\\n\";\n}\nMat markerMask, img;\nPoint prevPt(-1, -1);\n\nvoid onMouse( int event, int x, int y, int flags, void* )\n{\n if( x < 0 || x >= img.cols || y < 0 || y >= img.rows )\n return;\n if( event == CV_EVENT_LBUTTONUP || !(flags & CV_EVENT_FLAG_LBUTTON) )\n prevPt = Point(-1,-1);\n else if( event == CV_EVENT_LBUTTONDOWN )\n prevPt = Point(x,y);\n else if( event == CV_EVENT_MOUSEMOVE && (flags & CV_EVENT_FLAG_LBUTTON) )\n {\n Point pt(x, y);\n if( prevPt.x < 0 )\n prevPt = pt;\n line( markerMask, prevPt, pt, Scalar::all(255), 5, 8, 0 );\n line( img, prevPt, pt, Scalar::all(255), 5, 8, 0 );\n prevPt = pt;\n imshow(\"image\", img);\n }\n}\n\nint main( int argc, char** argv )\n{\n char* filename = argc >= 2 ? argv[1] : (char*)\"fruits.jpg\";\n Mat img0 = imread(filename, 1), imgGray;\n \n if( img0.empty() )\n {\n cout << \"Couldn'g open image \" << filename << \". Usage: watershed <image_name>\\n\";\n return 0;\n }\n help();\n namedWindow( \"image\", 1 );\n\n img0.copyTo(img);\n cvtColor(img, markerMask, CV_BGR2GRAY);\n cvtColor(markerMask, imgGray, CV_GRAY2BGR);\n markerMask = Scalar::all(0);\n imshow( \"image\", img );\n setMouseCallback( \"image\", onMouse, 0 );\n\n for(;;)\n {\n int c = waitKey(0);\n\n if( (char)c == 27 )\n break;\n\n if( (char)c == 'r' )\n {\n markerMask = Scalar::all(0);\n img0.copyTo(img);\n imshow( \"image\", img );\n }\n\n if( (char)c == 'w' || (char)c == ' ' )\n {\n int i, j, compCount = 0;\n vector<vector<Point> > contours;\n vector<Vec4i> hierarchy;\n \n findContours(markerMask, contours, hierarchy, CV_RETR_CCOMP, CV_CHAIN_APPROX_SIMPLE);\n \n Mat markers(markerMask.size(), CV_32S);\n markers = Scalar::all(0);\n int idx = 0;\n for( ; idx >= 0; idx = hierarchy[idx][0], compCount++ )\n drawContours(markers, contours, idx, Scalar::all(compCount+1), -1, 8, hierarchy, INT_MAX);\n\n if( compCount == 0 )\n continue;\n \n vector<Vec3b> colorTab;\n for( i = 0; i < compCount; i++ )\n {\n int b = theRNG().uniform(0, 255);\n int g = theRNG().uniform(0, 255);\n int r = theRNG().uniform(0, 255);\n \n colorTab.push_back(Vec3b((uchar)b, (uchar)g, (uchar)r));\n }\n\n double t = (double)getTickCount();\n watershed( img0, markers );\n t = (double)getTickCount() - t;\n printf( \"execution time = %gms\\n\", t*1000.\/getTickFrequency() );\n\n Mat wshed(markers.size(), CV_8UC3);\n \n \/\/ paint the watershed image\n for( i = 0; i < markers.rows; i++ )\n for( j = 0; j < markers.cols; j++ )\n {\n int idx = markers.at<int>(i,j);\n if( idx == -1 )\n wshed.at<Vec3b>(i,j) = Vec3b(255,255,255);\n else if( idx <= 0 || idx > compCount )\n wshed.at<Vec3b>(i,j) = Vec3b(0,0,0);\n else\n wshed.at<Vec3b>(i,j) = colorTab[idx - 1];\n }\n\n wshed = wshed*0.5 + imgGray*0.5;\n imshow( \"watershed transform\", wshed );\n }\n }\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>#ifndef IMPORTER_NODESTORESPARSE_HPP\n#define IMPORTER_NODESTORESPARSE_HPP\n\n#include <google\/sparsetable>\n#include <memory>\n\nclass NodestoreSparse : public Nodestore {\nprivate:\n \/**\n * Size of one allocated memory block\n *\/\n const static size_t BLOCK_SIZE = 512*1024*1024;\n\n typedef std::vector< char* > memoryBlocks_t;\n typedef std::vector< char* >::const_iterator memoryBlocks_cit;\n\n \/**\n * list of all allocated memory blocks\n *\/\n memoryBlocks_t memoryBlocks;\n\n \/**\n * pointer to the first byte of the currently used memory block\n *\/\n char* currentMemoryBlock;\n\n \/**\n * number of bytes already used in the currentMemoryBlock\n *\/\n size_t currentMemoryBlockPosition;\n\n\n char* allocateNewMemoryBlock() {\n currentMemoryBlock = static_cast< char* >(malloc(BLOCK_SIZE));\n currentMemoryBlockPosition = 0;\n memoryBlocks.push_back(currentMemoryBlock);\n return currentMemoryBlock;\n }\n\n void freeAllMemoryBlocks() {\n memoryBlocks_cit end = memoryBlocks.end();\n for(memoryBlocks_cit it = memoryBlocks.begin(); it != end; ++it) {\n free(*it);\n }\n memoryBlocks.clear();\n }\n\n \/**\n * the information stored for each node, packed into ints\n *\/\n struct PackedNodeTimeinfo {\n \/**\n * osmium gives us a time_t which is a signed int\n * on 32 bit platformsm time_t is 4 bytes wide and it will overflow on year 2038\n * on 64 bit platforms, time_t is 8 bytes wide and will not overflow during the next decades\n * we know that osm did not exists before 1970, so there is no need to encode times prior to that point\n * using this knowledge we can extend the reach of our unix timestamp by ~60 years by using an unsigned\n * 8 byte int. this gives us best of both worlds: a smaller memory footprint and enough time to buy more ram\n * (as of today's 2013: 93 years. should be enough for everybody.)\n *\/\n uint32_t t;\n\n \/**\n * the version is not really required and only required for debugging output\n *\/\n uint32_t v;\n\n \/**\n * osmium handles lat\/lon either as double (8 bytes) or as int32_t (4 byted). So we choose the smaller one.\n *\/\n int32_t lat;\n\n \/**\n * same as for lat\n *\/\n int32_t lon;\n };\n\n static const int nodeSeparatorSite = sizeof(((PackedNodeTimeinfo *)0)->t);\n\n \/**\n * sparse table, mapping node ids to their positions in a memory block\n *\/\n google::sparsetable< PackedNodeTimeinfo* > idMap;\n\n osm_object_id_t lastNodeId;\n\n\npublic:\n NodestoreSparse() : Nodestore(), memoryBlocks(), idMap(), lastNodeId() {\n allocateNewMemoryBlock();\n }\n ~NodestoreSparse() {\n freeAllMemoryBlocks();\n }\n\n void record(osm_object_id_t id, osm_version_t v, time_t t, double lon, double lat) {\n \/\/ remember: sorting is guaranteed nodes, ways relations in ascending id and then version order\n PackedNodeTimeinfo *infoPtr;\n\n \/\/ test if there is enough space for another PackedNodeTimeinfo\n if(currentMemoryBlockPosition + sizeof(PackedNodeTimeinfo) >= BLOCK_SIZE) {\n std::cerr << \"memory block is full, repaging is nyi\" << std::endl;\n throw new std::runtime_error(\"nyi\");\n }\n\n if(lastNodeId != id) {\n \/\/ new node\n if(currentMemoryBlockPosition > 0) {\n if(isPrintingDebugMessages()) {\n std::cerr << \"adding 0-separator of \" << nodeSeparatorSite << \" bytes after memory position \" << currentMemoryBlockPosition << std::endl;\n }\n currentMemoryBlockPosition += nodeSeparatorSite;\n\n }\n\n \/\/ no memory segment for this node yet\n infoPtr = reinterpret_cast< PackedNodeTimeinfo* >(currentMemoryBlock + currentMemoryBlockPosition);\n\n if(isPrintingDebugMessages()) {\n std::cerr << \"assigning memory position \" << infoPtr << \" (offset: \" << currentMemoryBlockPosition << \") to node id #\" << id << std::endl;\n }\n\n idMap.resize(id+1);\n idMap[id] = infoPtr;\n }\n else {\n \/\/ no memory segment for this node yet\n infoPtr = reinterpret_cast< PackedNodeTimeinfo* >(currentMemoryBlock + currentMemoryBlockPosition);\n }\n\n if(isPrintingDebugMessages()) {\n std::cerr << \"storing node id #\" << id << \"v\" << v << \" at memory position \" << infoPtr << \" (offset: \" << currentMemoryBlockPosition << \")\" << std::endl;\n }\n\n infoPtr->t = t;\n infoPtr->v = v;\n infoPtr->lat = Osmium::OSM::double_to_fix(lat);\n infoPtr->lon = Osmium::OSM::double_to_fix(lon);\n\n\n \/\/ mark end of memory for this node\n infoPtr++;\n infoPtr->t = 0;\n\n currentMemoryBlockPosition += sizeof(PackedNodeTimeinfo);\n lastNodeId = id;\n }\n\n \/\/ actually we don't need the coordinates here, only the time stamps\n \/\/ so we could return a simple time vector. it actually is only a timemap\n \/\/ because this was more easy to implement in the stl store, but once we\n \/\/ change the default from stl to sparse, we can change the return value, too\n timemap_ptr lookup(osm_object_id_t id, bool &found) {\n if(!idMap.test(id)) {\n if(isPrintingStoreErrors()) {\n std::cerr << \"no timemap for node #\" << id << \", skipping node\" << std::endl;\n }\n\n found = false;\n return timemap_ptr();\n }\n\n PackedNodeTimeinfo *infoPtr = idMap[id];\n timemap_ptr tMap(new timemap());\n\n if(isPrintingDebugMessages()) {\n std::cerr << \"acessing node id #\" << id << \" starting from memory position \" << infoPtr << std::endl;\n }\n\n Nodeinfo info;\n do {\n if(isPrintingDebugMessages()) {\n std::cerr << \"found node id #\" << id << \"v\" << infoPtr->v << \" at memory position \" << infoPtr << std::endl;\n }\n info.lat = Osmium::OSM::fix_to_double(infoPtr->lat);\n info.lon = Osmium::OSM::fix_to_double(infoPtr->lon);\n tMap->insert(timepair(infoPtr->t, info));\n } while((++infoPtr)->t != 0);\n\n found = true;\n return tMap;\n }\n\n Nodeinfo lookup(osm_object_id_t id, time_t t, bool &found) {\n if(!idMap.test(id)) {\n if(isPrintingStoreErrors()) {\n std::cerr << \"no timemap for node #\" << id << \", skipping node\" << std::endl;\n }\n\n found = false;\n return nullinfo;\n }\n\n PackedNodeTimeinfo *infoPtr = idMap[id];\n if(isPrintingDebugMessages()) {\n std::cerr << \"acessing node id #\" << id << \" starting from memory position \" << infoPtr << std::endl;\n }\n\n Nodeinfo info = nullinfo;\n time_t infoTime = 0;\n\n \/\/ find the oldest node-version younger then t\n do {\n if(infoPtr->t <= t && infoPtr->t >= infoTime) {\n info.lat = Osmium::OSM::fix_to_double(infoPtr->lat);\n info.lon = Osmium::OSM::fix_to_double(infoPtr->lon);\n infoTime = infoPtr->t;\n }\n } while((++infoPtr)->t != 0);\n\n if(isPrintingDebugMessages()) {\n std::cerr << \"found node-info from t=\" << infoTime << std::endl;\n }\n\n found = (infoTime > 0);\n return info;\n }\n};\n\n#endif \/\/ IMPORTER_NODESTORESPARSE_HPP\n<commit_msg>use bigger steps to increment map size<commit_after>#ifndef IMPORTER_NODESTORESPARSE_HPP\n#define IMPORTER_NODESTORESPARSE_HPP\n\n#include <google\/sparsetable>\n#include <memory>\n\nclass NodestoreSparse : public Nodestore {\nprivate:\n \/**\n * Size of one allocated memory block\n *\/\n const static size_t BLOCK_SIZE = 512*1024*1024;\n const static osm_object_id_t EST_MAX_NODE_ID = 2^31; \/\/ soon 2^32\n const static osm_object_id_t NODE_BUFFER_STEPS = 2^16; \/\/ soon 2^32\n\n typedef std::vector< char* > memoryBlocks_t;\n typedef std::vector< char* >::const_iterator memoryBlocks_cit;\n\n \/**\n * list of all allocated memory blocks\n *\/\n memoryBlocks_t memoryBlocks;\n\n \/**\n * pointer to the first byte of the currently used memory block\n *\/\n char* currentMemoryBlock;\n\n \/**\n * number of bytes already used in the currentMemoryBlock\n *\/\n size_t currentMemoryBlockPosition;\n\n\n char* allocateNewMemoryBlock() {\n currentMemoryBlock = static_cast< char* >(malloc(BLOCK_SIZE));\n currentMemoryBlockPosition = 0;\n memoryBlocks.push_back(currentMemoryBlock);\n return currentMemoryBlock;\n }\n\n void freeAllMemoryBlocks() {\n memoryBlocks_cit end = memoryBlocks.end();\n for(memoryBlocks_cit it = memoryBlocks.begin(); it != end; ++it) {\n free(*it);\n }\n memoryBlocks.clear();\n }\n\n \/**\n * the information stored for each node, packed into ints\n *\/\n struct PackedNodeTimeinfo {\n \/**\n * osmium gives us a time_t which is a signed int\n * on 32 bit platformsm time_t is 4 bytes wide and it will overflow on year 2038\n * on 64 bit platforms, time_t is 8 bytes wide and will not overflow during the next decades\n * we know that osm did not exists before 1970, so there is no need to encode times prior to that point\n * using this knowledge we can extend the reach of our unix timestamp by ~60 years by using an unsigned\n * 8 byte int. this gives us best of both worlds: a smaller memory footprint and enough time to buy more ram\n * (as of today's 2013: 93 years. should be enough for everybody.)\n *\/\n uint32_t t;\n\n \/**\n * the version is not really required and only required for debugging output\n *\/\n uint32_t v;\n\n \/**\n * osmium handles lat\/lon either as double (8 bytes) or as int32_t (4 byted). So we choose the smaller one.\n *\/\n int32_t lat;\n\n \/**\n * same as for lat\n *\/\n int32_t lon;\n };\n\n static const int nodeSeparatorSite = sizeof(((PackedNodeTimeinfo *)0)->t);\n\n \/**\n * sparse table, mapping node ids to their positions in a memory block\n *\/\n google::sparsetable< PackedNodeTimeinfo* > idMap;\n\n osm_object_id_t maxNodeId;\n osm_object_id_t lastNodeId;\n\n\npublic:\n NodestoreSparse() : Nodestore(), memoryBlocks(), idMap(EST_MAX_NODE_ID), maxNodeId(EST_MAX_NODE_ID), lastNodeId() {\n allocateNewMemoryBlock();\n }\n ~NodestoreSparse() {\n freeAllMemoryBlocks();\n }\n\n void record(osm_object_id_t id, osm_version_t v, time_t t, double lon, double lat) {\n \/\/ remember: sorting is guaranteed nodes, ways relations in ascending id and then version order\n PackedNodeTimeinfo *infoPtr;\n\n \/\/ test if there is enough space for another PackedNodeTimeinfo\n if(currentMemoryBlockPosition + sizeof(PackedNodeTimeinfo) >= BLOCK_SIZE) {\n std::cerr << \"memory block is full, repaging is nyi\" << std::endl;\n throw new std::runtime_error(\"nyi\");\n }\n\n if(lastNodeId != id) {\n \/\/ new node\n if(currentMemoryBlockPosition > 0) {\n if(isPrintingDebugMessages()) {\n std::cerr << \"adding 0-separator of \" << nodeSeparatorSite << \" bytes after memory position \" << currentMemoryBlockPosition << std::endl;\n }\n currentMemoryBlockPosition += nodeSeparatorSite;\n\n }\n\n \/\/ no memory segment for this node yet\n infoPtr = reinterpret_cast< PackedNodeTimeinfo* >(currentMemoryBlock + currentMemoryBlockPosition);\n\n if(isPrintingDebugMessages()) {\n std::cerr << \"assigning memory position \" << infoPtr << \" (offset: \" << currentMemoryBlockPosition << \") to node id #\" << id << std::endl;\n }\n\n if(id > maxNodeId) {\n idMap.resize(id + NODE_BUFFER_STEPS + 1);\n maxNodeId = id + NODE_BUFFER_STEPS;\n }\n idMap[id] = infoPtr;\n }\n else {\n \/\/ no memory segment for this node yet\n infoPtr = reinterpret_cast< PackedNodeTimeinfo* >(currentMemoryBlock + currentMemoryBlockPosition);\n }\n\n if(isPrintingDebugMessages()) {\n std::cerr << \"storing node id #\" << id << \"v\" << v << \" at memory position \" << infoPtr << \" (offset: \" << currentMemoryBlockPosition << \")\" << std::endl;\n }\n\n infoPtr->t = t;\n infoPtr->v = v;\n infoPtr->lat = Osmium::OSM::double_to_fix(lat);\n infoPtr->lon = Osmium::OSM::double_to_fix(lon);\n\n\n \/\/ mark end of memory for this node\n infoPtr++;\n infoPtr->t = 0;\n\n currentMemoryBlockPosition += sizeof(PackedNodeTimeinfo);\n lastNodeId = id;\n }\n\n \/\/ actually we don't need the coordinates here, only the time stamps\n \/\/ so we could return a simple time vector. it actually is only a timemap\n \/\/ because this was more easy to implement in the stl store, but once we\n \/\/ change the default from stl to sparse, we can change the return value, too\n timemap_ptr lookup(osm_object_id_t id, bool &found) {\n if(!idMap.test(id)) {\n if(isPrintingStoreErrors()) {\n std::cerr << \"no timemap for node #\" << id << \", skipping node\" << std::endl;\n }\n\n found = false;\n return timemap_ptr();\n }\n\n PackedNodeTimeinfo *infoPtr = idMap[id];\n timemap_ptr tMap(new timemap());\n\n if(isPrintingDebugMessages()) {\n std::cerr << \"acessing node id #\" << id << \" starting from memory position \" << infoPtr << std::endl;\n }\n\n Nodeinfo info;\n do {\n if(isPrintingDebugMessages()) {\n std::cerr << \"found node id #\" << id << \"v\" << infoPtr->v << \" at memory position \" << infoPtr << std::endl;\n }\n info.lat = Osmium::OSM::fix_to_double(infoPtr->lat);\n info.lon = Osmium::OSM::fix_to_double(infoPtr->lon);\n tMap->insert(timepair(infoPtr->t, info));\n } while((++infoPtr)->t != 0);\n\n found = true;\n return tMap;\n }\n\n Nodeinfo lookup(osm_object_id_t id, time_t t, bool &found) {\n if(!idMap.test(id)) {\n if(isPrintingStoreErrors()) {\n std::cerr << \"no timemap for node #\" << id << \", skipping node\" << std::endl;\n }\n\n found = false;\n return nullinfo;\n }\n\n PackedNodeTimeinfo *infoPtr = idMap[id];\n if(isPrintingDebugMessages()) {\n std::cerr << \"acessing node id #\" << id << \" starting from memory position \" << infoPtr << std::endl;\n }\n\n Nodeinfo info = nullinfo;\n time_t infoTime = 0;\n\n \/\/ find the oldest node-version younger then t\n do {\n if(infoPtr->t <= t && infoPtr->t >= infoTime) {\n info.lat = Osmium::OSM::fix_to_double(infoPtr->lat);\n info.lon = Osmium::OSM::fix_to_double(infoPtr->lon);\n infoTime = infoPtr->t;\n }\n } while((++infoPtr)->t != 0);\n\n if(isPrintingDebugMessages()) {\n std::cerr << \"found node-info from t=\" << infoTime << std::endl;\n }\n\n found = (infoTime > 0);\n return info;\n }\n};\n\n#endif \/\/ IMPORTER_NODESTORESPARSE_HPP\n<|endoftext|>"} {"text":"<commit_before>\/**************************************************************************\n * celestialBody.cxx\n * Written by Durk Talsma. Originally started October 1997, for distribution \n * with the FlightGear project. Version 2 was written in August and \n * September 1998. This code is based upon algorithms and data kindly \n * provided by Mr. Paul Schlyter. (pausch@saaf.se). \n *\n * This program is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU General Public License as\n * published by the Free Software Foundation; either version 2 of the\n * License, or (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n *\n * $Id$\n * (Log is kept at end of this file)\n **************************************************************************\/\n\n#include \"celestialBody.hxx\"\n#include \"star.hxx\"\n#include <Debug\/logstream.hxx>\n\n#ifdef __BORLANDC__\n# define exception c_exception\n#endif\n#include <math.h>\n\n\/**************************************************************************\n * void CelestialBody::updatePosition(fgTIME *t, Star *ourSun)\n *\n * Basically, this member function provides a general interface for \n * calculating the right ascension and declinaion. This function is \n * used for calculating the planetary positions. For the planets, an \n * overloaded member function is provided to additionally calculate the\n * planet's magnitude. \n * The sun and moon have their own overloaded updatePosition member, as their\n * position is calculated an a slightly different manner. \n *\n * arguments:\n * fgTIME t: provides the current time.\n * Star *ourSun: the sun's position is needed to convert heliocentric \n * coordinates into geocentric coordinates.\n *\n * return value: none\n *\n *************************************************************************\/\nvoid CelestialBody::updatePosition(fgTIME *t, Star *ourSun)\n{\n double eccAnom, v, ecl, actTime, \n xv, yv, xh, yh, zh, xg, yg, zg, xe, ye, ze;\n\n updateOrbElements(t);\n actTime = fgCalcActTime(t);\n\n \/\/ calcualate the angle bewteen ecliptic and equatorial coordinate system\n ecl = DEG_TO_RAD * (23.4393 - 3.563E-7 *actTime);\n \n eccAnom = fgCalcEccAnom(M, e); \/\/calculate the eccentric anomaly\n xv = a * (cos(eccAnom) - e);\n yv = a * (sqrt (1.0 - e*e) * sin(eccAnom));\n v = atan2(yv, xv); \/\/ the planet's true anomaly\n r = sqrt (xv*xv + yv*yv); \/\/ the planet's distance\n \n \/\/ calculate the planet's position in 3D space\n xh = r * (cos(N) * cos(v+w) - sin(N) * sin(v+w) * cos(i));\n yh = r * (sin(N) * cos(v+w) + cos(N) * sin(v+w) * cos(i));\n zh = r * (sin(v+w) * sin(i));\n\n \/\/ calculate the ecliptic longitude and latitude\n xg = xh + ourSun->getxs();\n yg = yh + ourSun->getys();\n zg = zh;\n \n xe = xg;\n ye = yg * cos(ecl) - zg * sin(ecl);\n ze = yg * sin(ecl) + zg * cos(ecl);\n rightAscension = atan2(ye, xe);\n declination = atan2(ze, sqrt(xe*xe + ye*ye));\n FG_LOG(FG_GENERAL, FG_INFO, \"Planet found at : \" \n\t << rightAscension << \" (ra), \" << declination << \" (dec)\" );\n\n \/\/calculate some variables specific to calculating the magnitude \n \/\/of the planet\n R = sqrt (xg*xg + yg*yg + zg*zg);\n s = ourSun->getDistance();\n FV = RAD_TO_DEG * acos( (r*r + R*R - s*s) \/ (2*r*R));\n};\n\n\/****************************************************************************\n * double CelestialBody::fgCalcEccAnom(double M, double e)\n * this private member calculates the eccentric anomaly of a celestial body, \n * given its mean anomaly and eccentricity.\n * \n * -Mean anomaly: the approximate angle between the perihelion and the current\n * position. this angle increases uniformly with time.\n *\n * True anomaly: the actual angle between perihelion and current position.\n *\n * Eccentric anomaly: this is an auxilary angle, used in calculating the true\n * anomaly from the mean anomaly.\n * \n * -eccentricity. Indicates the amount in which the orbit deviates from a \n * circle (0 = circle, 0-1, is ellipse, 1 = parabola, > 1 = hyperbola).\n *\n * This function is also known as solveKeplersEquation()\n *\n * arguments: \n * M: the mean anomaly\n * e: the eccentricity\n *\n * return value:\n * the eccentric anomaly\n *\n ****************************************************************************\/\ndouble CelestialBody::fgCalcEccAnom(double M, double e)\n{\n double \n eccAnom, E0, E1, diff;\n \n eccAnom = M + e * sin(M) * (1.0 + e * cos (M));\n \/\/ iterate to achieve a greater precision for larger eccentricities \n if (e > 0.05)\n {\n E0 = eccAnom;\n do\n\t{\n\t E1 = E0 - (E0 - e * sin(E0) - M) \/ (1 - e *cos(E0));\n\t diff = fabs(E0 - E1);\n\t E0 = E1;\n\t}\n while (diff > (DEG_TO_RAD * 0.001));\n return E0;\n }\n return eccAnom;\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n<commit_msg>math domain error fix from Charlie Hotchkiss.<commit_after>\/**************************************************************************\n * celestialBody.cxx\n * Written by Durk Talsma. Originally started October 1997, for distribution \n * with the FlightGear project. Version 2 was written in August and \n * September 1998. This code is based upon algorithms and data kindly \n * provided by Mr. Paul Schlyter. (pausch@saaf.se). \n *\n * This program is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU General Public License as\n * published by the Free Software Foundation; either version 2 of the\n * License, or (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n *\n * $Id$\n * (Log is kept at end of this file)\n **************************************************************************\/\n\n#include \"celestialBody.hxx\"\n#include \"star.hxx\"\n#include <Debug\/logstream.hxx>\n\n#ifdef FG_MATH_EXCEPTION_CLASH\n# define exception c_exception\n#endif\n#include <math.h>\n\n\/**************************************************************************\n * void CelestialBody::updatePosition(fgTIME *t, Star *ourSun)\n *\n * Basically, this member function provides a general interface for \n * calculating the right ascension and declinaion. This function is \n * used for calculating the planetary positions. For the planets, an \n * overloaded member function is provided to additionally calculate the\n * planet's magnitude. \n * The sun and moon have their own overloaded updatePosition member, as their\n * position is calculated an a slightly different manner. \n *\n * arguments:\n * fgTIME t: provides the current time.\n * Star *ourSun: the sun's position is needed to convert heliocentric \n * coordinates into geocentric coordinates.\n *\n * return value: none\n *\n *************************************************************************\/\nvoid CelestialBody::updatePosition(fgTIME *t, Star *ourSun)\n{\n double eccAnom, v, ecl, actTime, \n xv, yv, xh, yh, zh, xg, yg, zg, xe, ye, ze;\n\n updateOrbElements(t);\n actTime = fgCalcActTime(t);\n\n \/\/ calcualate the angle bewteen ecliptic and equatorial coordinate system\n ecl = DEG_TO_RAD * (23.4393 - 3.563E-7 *actTime);\n \n eccAnom = fgCalcEccAnom(M, e); \/\/calculate the eccentric anomaly\n xv = a * (cos(eccAnom) - e);\n yv = a * (sqrt (1.0 - e*e) * sin(eccAnom));\n v = atan2(yv, xv); \/\/ the planet's true anomaly\n r = sqrt (xv*xv + yv*yv); \/\/ the planet's distance\n \n \/\/ calculate the planet's position in 3D space\n xh = r * (cos(N) * cos(v+w) - sin(N) * sin(v+w) * cos(i));\n yh = r * (sin(N) * cos(v+w) + cos(N) * sin(v+w) * cos(i));\n zh = r * (sin(v+w) * sin(i));\n\n \/\/ calculate the ecliptic longitude and latitude\n xg = xh + ourSun->getxs();\n yg = yh + ourSun->getys();\n zg = zh;\n \n xe = xg;\n ye = yg * cos(ecl) - zg * sin(ecl);\n ze = yg * sin(ecl) + zg * cos(ecl);\n rightAscension = atan2(ye, xe);\n declination = atan2(ze, sqrt(xe*xe + ye*ye));\n FG_LOG(FG_GENERAL, FG_INFO, \"Planet found at : \" \n\t << rightAscension << \" (ra), \" << declination << \" (dec)\" );\n\n \/\/calculate some variables specific to calculating the magnitude \n \/\/of the planet\n R = sqrt (xg*xg + yg*yg + zg*zg);\n s = ourSun->getDistance();\n\n \/\/ It is possible from these calculations for the argument to acos\n \/\/ to exceed the valid range for acos(). So we do a little extra\n \/\/ checking.\n\n double tmp = (r*r + R*R - s*s) \/ (2*r*R);\n if ( tmp > 1.0) { \n tmp = 1.0;\n } else if ( tmp < -1.0) {\n tmp = -1.0;\n }\n\n FV = RAD_TO_DEG * acos( tmp );\n};\n\n\/****************************************************************************\n * double CelestialBody::fgCalcEccAnom(double M, double e)\n * this private member calculates the eccentric anomaly of a celestial body, \n * given its mean anomaly and eccentricity.\n * \n * -Mean anomaly: the approximate angle between the perihelion and the current\n * position. this angle increases uniformly with time.\n *\n * True anomaly: the actual angle between perihelion and current position.\n *\n * Eccentric anomaly: this is an auxilary angle, used in calculating the true\n * anomaly from the mean anomaly.\n * \n * -eccentricity. Indicates the amount in which the orbit deviates from a \n * circle (0 = circle, 0-1, is ellipse, 1 = parabola, > 1 = hyperbola).\n *\n * This function is also known as solveKeplersEquation()\n *\n * arguments: \n * M: the mean anomaly\n * e: the eccentricity\n *\n * return value:\n * the eccentric anomaly\n *\n ****************************************************************************\/\ndouble CelestialBody::fgCalcEccAnom(double M, double e)\n{\n double \n eccAnom, E0, E1, diff;\n \n eccAnom = M + e * sin(M) * (1.0 + e * cos (M));\n \/\/ iterate to achieve a greater precision for larger eccentricities \n if (e > 0.05)\n {\n E0 = eccAnom;\n do\n\t{\n\t E1 = E0 - (E0 - e * sin(E0) - M) \/ (1 - e *cos(E0));\n\t diff = fabs(E0 - E1);\n\t E0 = E1;\n\t}\n while (diff > (DEG_TO_RAD * 0.001));\n return E0;\n }\n return eccAnom;\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n<|endoftext|>"} {"text":"<commit_before>#include \"hackypassabilityagent.h\"\n\n#include <QQuickItem>\n#include <QQuickWindow>\n\n#include \"quickentity.h\"\n#include \"utils.h\"\n\nHackyPassabilityAgent::HackyPassabilityAgent() :\n mGridItem(nullptr)\n{\n}\n\nbool HackyPassabilityAgent::isPassable(const QPointF &pos, AbstractEntity *entity)\n{\n if (!mGridItem)\n return false;\n\n QuickEntity *quickEntity = dynamic_cast<QuickEntity*>(entity);\n Q_ASSERT(quickEntity);\n\n \/\/ very basic, hacky check that doesn't take into account a radius.\n QQuickItem *child = mGridItem->childAt(pos.x(), pos.y());\n if (child->property(\"blocksMovement\").toBool()) {\n return false;\n }\n\n return true;\n}\n\nQQuickItem *HackyPassabilityAgent::gridItem() const\n{\n return mGridItem;\n}\n\nvoid HackyPassabilityAgent::setGridItem(QQuickItem *gridItem)\n{\n if (gridItem == mGridItem)\n return;\n\n mGridItem = gridItem;\n emit gridItemChanged();\n}\n<commit_msg>Fix null pointer access in HackyPassabilityAgent<commit_after>#include \"hackypassabilityagent.h\"\n\n#include <QQuickItem>\n#include <QQuickWindow>\n\n#include \"quickentity.h\"\n#include \"utils.h\"\n\nHackyPassabilityAgent::HackyPassabilityAgent() :\n mGridItem(nullptr)\n{\n}\n\nbool HackyPassabilityAgent::isPassable(const QPointF &pos, AbstractEntity *entity)\n{\n if (!mGridItem)\n return false;\n\n QuickEntity *quickEntity = dynamic_cast<QuickEntity*>(entity);\n Q_ASSERT(quickEntity);\n\n \/\/ very basic, hacky check that doesn't take into account a radius.\n QQuickItem *child = mGridItem->childAt(pos.x(), pos.y());\n if (child && child->property(\"blocksMovement\").toBool()) {\n return false;\n }\n\n return true;\n}\n\nQQuickItem *HackyPassabilityAgent::gridItem() const\n{\n return mGridItem;\n}\n\nvoid HackyPassabilityAgent::setGridItem(QQuickItem *gridItem)\n{\n if (gridItem == mGridItem)\n return;\n\n mGridItem = gridItem;\n emit gridItemChanged();\n}\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: fuline.cxx,v $\n *\n * $Revision: 1.5 $\n *\n * last change: $Author: rt $ $Date: 2004-07-12 15:03:16 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#pragma hdrstop\n\n#include \"fuline.hxx\"\n\n#include <svx\/svxids.hrc>\n#ifndef _SVX_TAB_LINE_HXX \/\/autogen\n#include <svx\/tabline.hxx>\n#endif\n#ifndef _XENUM_HXX \/\/autogen\n#include <svx\/xenum.hxx>\n#endif\n#ifndef _SV_MSGBOX_HXX \/\/autogen\n#include <vcl\/msgbox.hxx>\n#endif\n#ifndef _SFXINTITEM_HXX \/\/autogen\n#include <svtools\/intitem.hxx>\n#endif\n#ifndef _SFXSTRITEM_HXX \/\/autogen\n#include <svtools\/stritem.hxx>\n#endif\n#ifndef _SFXREQUEST_HXX \/\/autogen\n#include <sfx2\/request.hxx>\n#endif\n#ifndef _XDEF_HXX \/\/autogen\n#include <svx\/xdef.hxx>\n#endif\n#ifndef _SFX_BINDINGS_HXX \/\/autogen\n#include <sfx2\/bindings.hxx>\n#endif\n#ifndef _SFXVIEWFRM_HXX\n#include <sfx2\/viewfrm.hxx>\n#endif\n\n#ifndef SD_VIEW_SHELL_HXX\n#include \"ViewShell.hxx\"\n#endif\n#ifndef SD_VIEW_HXX\n#include \"View.hxx\"\n#endif\n#ifndef SD_WINDOW_SHELL_HXX\n#include \"Window.hxx\"\n#endif\n#include \"drawdoc.hxx\"\n#include \"app.hrc\"\n#include <svx\/svxdlg.hxx> \/\/CHINA001\n#include <svx\/dialogs.hrc> \/\/CHINA001\n\nnamespace sd {\n\nTYPEINIT1( FuLine, FuPoor );\n\n\/*************************************************************************\n|*\n|* Konstruktor\n|*\n\\************************************************************************\/\n\nFuLine::FuLine (\n ViewShell* pViewSh,\n ::sd::Window* pWin,\n ::sd::View* pView,\n SdDrawDocument* pDoc,\n SfxRequest& rReq)\n : FuPoor(pViewSh, pWin, pView, pDoc, rReq)\n{\n BOOL bHasMarked = pView->AreObjectsMarked();\n\n const SfxItemSet* pArgs = rReq.GetArgs();\n\n if( !pArgs )\n {\n \/\/ erst einmal alle eingabeparameter fuer den dialog retten\n SfxItemSet aInputAttr( pDoc->GetPool() );\n pView->GetAttributes( aInputAttr );\n\n const XLineStyleItem &rILineStyleItem = (const XLineStyleItem &) aInputAttr.Get (XATTR_LINESTYLE);\n XLineStyle eILineStyle = rILineStyleItem.GetValue ();\n\n const XLineDashItem &rILineDashItem = (const XLineDashItem &) aInputAttr.Get (XATTR_LINEDASH);\n const XDash &rIDash = rILineDashItem.GetValue ();\n\n const XLineWidthItem &rILineWidthItem = (const XLineWidthItem &) aInputAttr.Get (XATTR_LINEWIDTH);\n long nILineWidth = rILineWidthItem.GetValue ();\n\n const XLineColorItem &rILineColorItem = (const XLineColorItem &) aInputAttr.Get (XATTR_LINECOLOR);\n const Color &rIColor = rILineColorItem.GetValue ();\n\n const SdrObject* pObj = NULL;\n const SdrMarkList& rMarkList = pView->GetMarkedObjectList();\n if( rMarkList.GetMarkCount() == 1 )\n pObj = rMarkList.GetMark(0)->GetObj();\n\n SfxItemSet* pNewAttr = new SfxItemSet( pDoc->GetPool() );\n pView->GetAttributes( *pNewAttr );\n\n \/\/CHINA001 SvxLineTabDialog* pDlg = new SvxLineTabDialog( NULL, pNewAttr, pDoc, pObj, bHasMarked );\n SvxAbstractDialogFactory* pFact = SvxAbstractDialogFactory::Create();\n DBG_ASSERT(pFact, \"Dialogdiet Factory fail!\");\/\/CHINA001\n SfxAbstractTabDialog * pDlg = pFact->CreateSvxLineTabDialog(NULL,\n pNewAttr,\n pDoc,\n ResId(RID_SVXDLG_LINE),\n pObj,\n bHasMarked);\n DBG_ASSERT(pDlg, \"Dialogdiet fail!\");\/\/CHINA001\n if ( pDlg->Execute() == RET_OK )\n {\n \/\/ die ausgabeparameter des dialogs bestimmen\n SfxItemSet *pOutputAttr = (SfxItemSet *) pDlg->GetOutputItemSet();\n\n const XLineStyleItem &rOLineStyleItem = (const XLineStyleItem &) pOutputAttr->Get (XATTR_LINESTYLE);\n XLineStyle eOLineStyle = rOLineStyleItem.GetValue ();\n\n const XLineDashItem &rOLineDashItem = (const XLineDashItem &) pOutputAttr->Get (XATTR_LINEDASH);\n const XDash &rODash = rOLineDashItem.GetValue ();\n\n const XLineWidthItem &rOLineWidthItem = (const XLineWidthItem &) pOutputAttr->Get (XATTR_LINEWIDTH);\n long nOLineWidth = rOLineWidthItem.GetValue ();\n\n const XLineColorItem &rOLineColorItem = (const XLineColorItem &) pOutputAttr->Get (XATTR_LINECOLOR);\n const Color &rOColor = rOLineColorItem.GetValue ();\n\n pView->SetAttributes (*(pDlg->GetOutputItemSet ()));\n }\n\n \/\/ Attribute wurden geaendert, Listboxes in Objectbars muessen aktualisiert werden\n static USHORT SidArray[] = {\n SID_ATTR_LINE_STYLE,\n SID_ATTR_LINE_DASH,\n SID_ATTR_LINE_WIDTH,\n SID_ATTR_LINE_COLOR,\n 0 };\n\n pViewShell->GetViewFrame()->GetBindings().Invalidate( SidArray );\n\n delete pDlg;\n delete pNewAttr;\n }\n\n rReq.Ignore ();\n}\n\n} \/\/ end of namespace sd\n<commit_msg>INTEGRATION: CWS ooo19126 (1.5.428); FILE MERGED 2005\/09\/05 13:22:17 rt 1.5.428.1: #i54170# Change license header: remove SISSL<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: fuline.cxx,v $\n *\n * $Revision: 1.6 $\n *\n * last change: $Author: rt $ $Date: 2005-09-09 04:43:57 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#pragma hdrstop\n\n#include \"fuline.hxx\"\n\n#include <svx\/svxids.hrc>\n#ifndef _SVX_TAB_LINE_HXX \/\/autogen\n#include <svx\/tabline.hxx>\n#endif\n#ifndef _XENUM_HXX \/\/autogen\n#include <svx\/xenum.hxx>\n#endif\n#ifndef _SV_MSGBOX_HXX \/\/autogen\n#include <vcl\/msgbox.hxx>\n#endif\n#ifndef _SFXINTITEM_HXX \/\/autogen\n#include <svtools\/intitem.hxx>\n#endif\n#ifndef _SFXSTRITEM_HXX \/\/autogen\n#include <svtools\/stritem.hxx>\n#endif\n#ifndef _SFXREQUEST_HXX \/\/autogen\n#include <sfx2\/request.hxx>\n#endif\n#ifndef _XDEF_HXX \/\/autogen\n#include <svx\/xdef.hxx>\n#endif\n#ifndef _SFX_BINDINGS_HXX \/\/autogen\n#include <sfx2\/bindings.hxx>\n#endif\n#ifndef _SFXVIEWFRM_HXX\n#include <sfx2\/viewfrm.hxx>\n#endif\n\n#ifndef SD_VIEW_SHELL_HXX\n#include \"ViewShell.hxx\"\n#endif\n#ifndef SD_VIEW_HXX\n#include \"View.hxx\"\n#endif\n#ifndef SD_WINDOW_SHELL_HXX\n#include \"Window.hxx\"\n#endif\n#include \"drawdoc.hxx\"\n#include \"app.hrc\"\n#include <svx\/svxdlg.hxx> \/\/CHINA001\n#include <svx\/dialogs.hrc> \/\/CHINA001\n\nnamespace sd {\n\nTYPEINIT1( FuLine, FuPoor );\n\n\/*************************************************************************\n|*\n|* Konstruktor\n|*\n\\************************************************************************\/\n\nFuLine::FuLine (\n ViewShell* pViewSh,\n ::sd::Window* pWin,\n ::sd::View* pView,\n SdDrawDocument* pDoc,\n SfxRequest& rReq)\n : FuPoor(pViewSh, pWin, pView, pDoc, rReq)\n{\n BOOL bHasMarked = pView->AreObjectsMarked();\n\n const SfxItemSet* pArgs = rReq.GetArgs();\n\n if( !pArgs )\n {\n \/\/ erst einmal alle eingabeparameter fuer den dialog retten\n SfxItemSet aInputAttr( pDoc->GetPool() );\n pView->GetAttributes( aInputAttr );\n\n const XLineStyleItem &rILineStyleItem = (const XLineStyleItem &) aInputAttr.Get (XATTR_LINESTYLE);\n XLineStyle eILineStyle = rILineStyleItem.GetValue ();\n\n const XLineDashItem &rILineDashItem = (const XLineDashItem &) aInputAttr.Get (XATTR_LINEDASH);\n const XDash &rIDash = rILineDashItem.GetValue ();\n\n const XLineWidthItem &rILineWidthItem = (const XLineWidthItem &) aInputAttr.Get (XATTR_LINEWIDTH);\n long nILineWidth = rILineWidthItem.GetValue ();\n\n const XLineColorItem &rILineColorItem = (const XLineColorItem &) aInputAttr.Get (XATTR_LINECOLOR);\n const Color &rIColor = rILineColorItem.GetValue ();\n\n const SdrObject* pObj = NULL;\n const SdrMarkList& rMarkList = pView->GetMarkedObjectList();\n if( rMarkList.GetMarkCount() == 1 )\n pObj = rMarkList.GetMark(0)->GetObj();\n\n SfxItemSet* pNewAttr = new SfxItemSet( pDoc->GetPool() );\n pView->GetAttributes( *pNewAttr );\n\n \/\/CHINA001 SvxLineTabDialog* pDlg = new SvxLineTabDialog( NULL, pNewAttr, pDoc, pObj, bHasMarked );\n SvxAbstractDialogFactory* pFact = SvxAbstractDialogFactory::Create();\n DBG_ASSERT(pFact, \"Dialogdiet Factory fail!\");\/\/CHINA001\n SfxAbstractTabDialog * pDlg = pFact->CreateSvxLineTabDialog(NULL,\n pNewAttr,\n pDoc,\n ResId(RID_SVXDLG_LINE),\n pObj,\n bHasMarked);\n DBG_ASSERT(pDlg, \"Dialogdiet fail!\");\/\/CHINA001\n if ( pDlg->Execute() == RET_OK )\n {\n \/\/ die ausgabeparameter des dialogs bestimmen\n SfxItemSet *pOutputAttr = (SfxItemSet *) pDlg->GetOutputItemSet();\n\n const XLineStyleItem &rOLineStyleItem = (const XLineStyleItem &) pOutputAttr->Get (XATTR_LINESTYLE);\n XLineStyle eOLineStyle = rOLineStyleItem.GetValue ();\n\n const XLineDashItem &rOLineDashItem = (const XLineDashItem &) pOutputAttr->Get (XATTR_LINEDASH);\n const XDash &rODash = rOLineDashItem.GetValue ();\n\n const XLineWidthItem &rOLineWidthItem = (const XLineWidthItem &) pOutputAttr->Get (XATTR_LINEWIDTH);\n long nOLineWidth = rOLineWidthItem.GetValue ();\n\n const XLineColorItem &rOLineColorItem = (const XLineColorItem &) pOutputAttr->Get (XATTR_LINECOLOR);\n const Color &rOColor = rOLineColorItem.GetValue ();\n\n pView->SetAttributes (*(pDlg->GetOutputItemSet ()));\n }\n\n \/\/ Attribute wurden geaendert, Listboxes in Objectbars muessen aktualisiert werden\n static USHORT SidArray[] = {\n SID_ATTR_LINE_STYLE,\n SID_ATTR_LINE_DASH,\n SID_ATTR_LINE_WIDTH,\n SID_ATTR_LINE_COLOR,\n 0 };\n\n pViewShell->GetViewFrame()->GetBindings().Invalidate( SidArray );\n\n delete pDlg;\n delete pNewAttr;\n }\n\n rReq.Ignore ();\n}\n\n} \/\/ end of namespace sd\n<|endoftext|>"} {"text":"<commit_before>\/* Copyright (c) 2014 Quanta Research Cambridge, Inc\n *\n * Permission is hereby granted, free of charge, to any person obtaining a\n * copy of this software and associated documentation files (the \"Software\"),\n * to deal in the Software without restriction, including without limitation\n * the rights to use, copy, modify, merge, publish, distribute, sublicense,\n * and\/or sell copies of the Software, and to permit persons to whom the\n * Software is furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included\n * in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n * DEALINGS IN THE SOFTWARE.\n *\/\n\n#include \"DmaConfigProxy.h\"\n#include \"DmaIndicationWrapper.h\"\n#include \"StdDmaIndication.h\"\n#include \"GeneratedTypes.h\"\n#include \"HdmiDisplayRequestProxy.h\"\n#include \"HdmiDisplayIndicationWrapper.h\"\n#include \"HdmiInternalIndicationWrapper.h\"\n#include \"HdmiInternalRequestProxy.h\"\n#include \"portal.h\"\n#include <stdio.h>\n#include <sys\/mman.h>\n#include <ctype.h>\n#include \"i2chdmi.h\"\n#include \"edid.h\"\n\n#define FRAME_COUNT 2\n#define MAX_PIXEL 256\n#define INCREMENT_PIXEL 2\n\nstatic HdmiInternalRequestProxy *hdmiInternal;\nstatic HdmiDisplayRequestProxy *device;\nstatic DmaConfigProxy *dma;\nstatic PortalAlloc *portalAlloc[FRAME_COUNT];\nstatic unsigned int ref_srcAlloc[FRAME_COUNT];\nstatic int *dataptr[FRAME_COUNT];\nstatic int frame_index;\nstatic int nlines = 1080;\nstatic int npixels = 1920;\nstatic int fbsize = nlines*npixels*4;\n\nvoid dump(const char *prefix, char *buf, size_t len)\n{\n fprintf(stderr, \"%s: \", prefix);\n for (int i = 0; i < 16; i++)\n\tfprintf(stderr, \"%02x\", (unsigned char)buf[i]);\n fprintf(stderr, \"\\n\");\n}\n\nstatic void *thread_routine(void *data)\n{\n fprintf(stderr, \"Calling portalExec\\n\");\n portalExec(0);\n fprintf(stderr, \"portalExec returned ???\\n\");\n return data;\n}\n\nstatic int corner[] = {0, -1, 0xf00f, 0x0fff};\nstatic int corner_index;\nstatic void fill_pixels(int offset)\n{\n int *ptr = dataptr[frame_index];\n for (int line = 0; line < nlines; line++)\n for (int pixel = 0; pixel < npixels; pixel++) {\n\tint v = ((((MAX_PIXEL * line) \/ nlines)+offset) % MAX_PIXEL) << 16\n\t | ((((MAX_PIXEL * pixel) \/ npixels)+offset) % MAX_PIXEL);\n if (!v)\n v = 1;\n if (line < 20 && pixel < 20)\n v = corner[(corner_index+0) % 4];\n if (line < 30 && pixel > npixels - 40)\n v = corner[(corner_index+1) % 4];\n if (line > nlines - 20 && pixel < 20)\n v = corner[(corner_index+2) % 4];\n if (line > nlines - 30 && pixel > npixels - 40)\n v = corner[(corner_index+3) % 4];\n if (line < 20 && pixel % 20 < 2)\n v = corner[(corner_index+0) % 4];\n if (line % 30 < 2 && pixel > npixels - 40)\n v = corner[(corner_index+1) % 4];\n\tptr[line * npixels + pixel] = v;\n }\n corner_index = offset\/16;\n dma->dCacheFlushInval(portalAlloc[frame_index], dataptr[frame_index]);\n device->startFrameBuffer(ref_srcAlloc[frame_index], fbsize);\n hdmiInternal->setTestPattern(0);\n hdmiInternal->waitForVsync(0);\n frame_index = 1 - frame_index;\n}\n\nstatic int synccount = 0;\nstatic long long totalcount;\nstatic int number;\nclass HdmiIndication : public HdmiInternalIndicationWrapper {\npublic:\n HdmiIndication(int id) : HdmiInternalIndicationWrapper(id) {}\n virtual void vsync ( uint64_t v, uint32_t w ) {\n static int base = 0;\n\ntotalcount += v;\nnumber += w;\n fill_pixels(base);\nbase += INCREMENT_PIXEL;\n if (synccount++ >= 20) {\n synccount = 0;\nuint32_t zeros = v & 0xffffffff, pix = v >> 32;\n fprintf(stderr, \"[%s] v %llx pix=%x:%d. zero=%x:%d. w=%x:%d.\\n\", __FUNCTION__,v,pix,pix,zeros,zeros,w,w);\n }\n }\n};\nclass DisplayIndication : public HdmiDisplayIndicationWrapper {\npublic:\n DisplayIndication(int id) : HdmiDisplayIndicationWrapper(id) {}\n virtual void transferStarted ( uint32_t v ) {\n fprintf(stderr, \"[%s:%d] v=%d\\n\", __FUNCTION__, __LINE__, v);\n }\n virtual void transferFinished ( uint32_t v ) {\n fprintf(stderr, \"[%s:%d] v=%d\\n\", __FUNCTION__, __LINE__, v);\n }\n virtual void transferStats ( uint32_t count, uint32_t cycles, uint64_t sumcycles ) {\n\tfprintf(stderr, \"[%s:%d] count=%d cycles=%d sumcycles=%lld avgcycles=%f\\n\", __FUNCTION__, __LINE__, count, cycles, sumcycles, (double)sumcycles \/ count);\n }\n};\n\nint main(int argc, const char **argv)\n{\n PortalPoller *poller = 0;\n DmaIndicationWrapper *dmaIndication;\n\n poller = new PortalPoller();\n device = new HdmiDisplayRequestProxy(IfcNames_HdmiDisplayRequest, poller);\n dma = new DmaConfigProxy(IfcNames_DmaConfig);\n dmaIndication = new DmaIndication(dma, IfcNames_DmaIndication);\n HdmiInternalIndicationWrapper *hdmiIndication = new HdmiIndication(IfcNames_HdmiInternalIndication);\n HdmiDisplayIndicationWrapper *displayIndication = new DisplayIndication(IfcNames_HdmiDisplayIndication);\n hdmiInternal = new HdmiInternalRequestProxy(IfcNames_HdmiInternalRequest);\n\n \/\/ read out monitor EDID from ADV7511\n struct edid edid;\n init_i2c_hdmi();\n int i2cfd = open(\"\/dev\/i2c-0\", O_RDWR);\n fprintf(stderr, \"Monitor EDID:\\n\");\n for (int i = 0; i < 256; i++) {\n edid.raw[i] = i2c_read_reg(i2cfd, 0x3f, i);\n fprintf(stderr, \" %02x\", edid.raw[i]);\n if ((i % 16) == 15) {\n\tfprintf(stderr, \" \");\n\tfor (int j = i-15; j <= i; j++) {\n\t unsigned char c = edid.raw[j];\n\t fprintf(stderr, \"%c\", (isprint(c) && isascii(c)) ? c : '.');\n\t}\n\tfprintf(stderr, \"\\n\");\n }\n }\n close(i2cfd);\n parseEdid(edid);\n\n device->stopFrameBuffer();\n\n pthread_t thread;\n pthread_attr_t attr;\n pthread_attr_init(&attr);\n pthread_create(&thread, &attr, thread_routine, 0);\n\n int status;\n status = poller->setClockFrequency(0, 100000000, 0);\n\n for (int i = 0; i < 4; i++) {\n int pixclk = (long)edid.timing[i].pixclk * 10000;\n if ((pixclk > 0) && (pixclk < 148000000)) {\n\tnlines = edid.timing[i].nlines; \/\/ number of visible lines\n\tnpixels = edid.timing[i].npixels;\n\tint vblank = edid.timing[i].blines; \/\/ number of blanking lines\n\tint hblank = edid.timing[i].bpixels;\n\tint vsyncoff = edid.timing[i].vsyncoff; \/\/ number of lines in FrontPorch (within blanking)\n\tint hsyncoff = edid.timing[i].hsyncoff;\n\tint vsyncwidth = edid.timing[i].vsyncwidth; \/\/ width of Sync (within blanking)\n\tint hsyncwidth = edid.timing[i].hsyncwidth;\n\n\tfprintf(stderr, \"lines %d, pixels %d, vblank %d, hblank %d, vwidth %d, hwidth %d\\n\",\n nlines, npixels, vblank, hblank, vsyncwidth, hsyncwidth);\n\tfprintf(stderr, \"Using pixclk %d calc_pixclk %d npixels %d nlines %d\\n\",\n\t\tpixclk,\n\t\t60l * (long)(hblank + npixels) * (long)(vblank + nlines),\n\t\tnpixels, nlines);\n\tstatus = poller->setClockFrequency(1, pixclk, 0);\n\n\thdmiInternal->setDeLine(vsyncoff, \/\/ End of FrontPorch\n vsyncoff+vsyncwidth,\/\/ End of Sync\n vblank, \/\/ Start of Visible (start of BackPorch)\n vblank + nlines, vblank + nlines \/ 2); \/\/ End\n hdmiInternal->setDePixel(hsyncoff,\n hsyncoff+hsyncwidth, hblank,\n hblank + npixels, hblank + npixels \/ 2);\n\tbreak;\n }\n }\n\n fbsize = nlines*npixels*4;\n\n for (int i = 0; i < FRAME_COUNT; i++) {\n int err = dma->alloc(fbsize, &portalAlloc[i]);\n dataptr[i] = (int*)mmap(0, fbsize, PROT_READ|PROT_WRITE, MAP_SHARED, portalAlloc[i]->header.fd, 0);\n memset(dataptr[i], i ? 0xff : 0, fbsize);\n fprintf(stderr, \"calling dma->reference\\n\");\n ref_srcAlloc[i] = dma->reference(portalAlloc[i]);\n }\n\n fprintf(stderr, \"first mem_stats=%10u\\n\", dma->show_mem_stats(ChannelType_Read));\n sleep(3);\n fprintf(stderr, \"Starting frame buffer ref=%d...\", ref_srcAlloc[0]);\n fill_pixels(0);\n fprintf(stderr, \"done\\n\");\n while (1) {\n fprintf(stderr, \"mem_stats=%10u\\n\", dma->show_mem_stats(ChannelType_Read));\n sleep(1);\n }\n}\n<commit_msg>hdmidisplay now works on both zedboard and zc702<commit_after>\/* Copyright (c) 2014 Quanta Research Cambridge, Inc\n *\n * Permission is hereby granted, free of charge, to any person obtaining a\n * copy of this software and associated documentation files (the \"Software\"),\n * to deal in the Software without restriction, including without limitation\n * the rights to use, copy, modify, merge, publish, distribute, sublicense,\n * and\/or sell copies of the Software, and to permit persons to whom the\n * Software is furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included\n * in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n * DEALINGS IN THE SOFTWARE.\n *\/\n\n#include \"DmaConfigProxy.h\"\n#include \"DmaIndicationWrapper.h\"\n#include \"StdDmaIndication.h\"\n#include \"GeneratedTypes.h\"\n#include \"HdmiDisplayRequestProxy.h\"\n#include \"HdmiDisplayIndicationWrapper.h\"\n#include \"HdmiInternalIndicationWrapper.h\"\n#include \"HdmiInternalRequestProxy.h\"\n#include \"portal.h\"\n#include <stdio.h>\n#include <sys\/mman.h>\n#include <ctype.h>\n#include \"i2chdmi.h\"\n#include \"edid.h\"\n\n#define FRAME_COUNT 2\n#define MAX_PIXEL 256\n#define INCREMENT_PIXEL 2\n\nstatic HdmiInternalRequestProxy *hdmiInternal;\nstatic HdmiDisplayRequestProxy *device;\nstatic DmaConfigProxy *dma;\nstatic PortalAlloc *portalAlloc[FRAME_COUNT];\nstatic unsigned int ref_srcAlloc[FRAME_COUNT];\nstatic int *dataptr[FRAME_COUNT];\nstatic int frame_index;\nstatic int nlines = 1080;\nstatic int npixels = 1920;\nstatic int fbsize = nlines*npixels*4;\n\nvoid dump(const char *prefix, char *buf, size_t len)\n{\n fprintf(stderr, \"%s: \", prefix);\n for (int i = 0; i < 16; i++)\n\tfprintf(stderr, \"%02x\", (unsigned char)buf[i]);\n fprintf(stderr, \"\\n\");\n}\n\nstatic void *thread_routine(void *data)\n{\n fprintf(stderr, \"Calling portalExec\\n\");\n portalExec(0);\n fprintf(stderr, \"portalExec returned ???\\n\");\n return data;\n}\n\nstatic int corner[] = {0, -1, 0xf00f, 0x0fff};\nstatic int corner_index;\nstatic void fill_pixels(int offset)\n{\n int *ptr = dataptr[frame_index];\n for (int line = 0; line < nlines; line++)\n for (int pixel = 0; pixel < npixels; pixel++) {\n\tint v = ((((MAX_PIXEL * line) \/ nlines)+offset) % MAX_PIXEL) << 16\n\t | ((((MAX_PIXEL * pixel) \/ npixels)+offset) % MAX_PIXEL);\n if (!v)\n v = 1;\n if (line < 20 && pixel < 20)\n v = corner[(corner_index+0) % 4];\n if (line < 30 && pixel > npixels - 40)\n v = corner[(corner_index+1) % 4];\n if (line > nlines - 20 && pixel < 20)\n v = corner[(corner_index+2) % 4];\n if (line > nlines - 30 && pixel > npixels - 40)\n v = corner[(corner_index+3) % 4];\n if (line < 20 && pixel % 20 < 2)\n v = corner[(corner_index+0) % 4];\n if (line % 30 < 2 && pixel > npixels - 40)\n v = corner[(corner_index+1) % 4];\n\tptr[line * npixels + pixel] = v;\n }\n corner_index = offset\/16;\n dma->dCacheFlushInval(portalAlloc[frame_index], dataptr[frame_index]);\n device->startFrameBuffer(ref_srcAlloc[frame_index], fbsize);\n hdmiInternal->setTestPattern(0);\n hdmiInternal->waitForVsync(0);\n frame_index = 1 - frame_index;\n}\n\nstatic int synccount = 0;\nstatic long long totalcount;\nstatic int number;\nclass HdmiIndication : public HdmiInternalIndicationWrapper {\npublic:\n HdmiIndication(int id) : HdmiInternalIndicationWrapper(id) {}\n virtual void vsync ( uint64_t v, uint32_t w ) {\n static int base = 0;\n\ntotalcount += v;\nnumber += w;\n fill_pixels(base);\nbase += INCREMENT_PIXEL;\n if (synccount++ >= 20) {\n synccount = 0;\nuint32_t zeros = v & 0xffffffff, pix = v >> 32;\n fprintf(stderr, \"[%s] v %llx pix=%x:%d. zero=%x:%d. w=%x:%d.\\n\", __FUNCTION__,v,pix,pix,zeros,zeros,w,w);\n }\n }\n};\nclass DisplayIndication : public HdmiDisplayIndicationWrapper {\npublic:\n DisplayIndication(int id) : HdmiDisplayIndicationWrapper(id) {}\n virtual void transferStarted ( uint32_t v ) {\n fprintf(stderr, \"[%s:%d] v=%d\\n\", __FUNCTION__, __LINE__, v);\n }\n virtual void transferFinished ( uint32_t v ) {\n fprintf(stderr, \"[%s:%d] v=%d\\n\", __FUNCTION__, __LINE__, v);\n }\n virtual void transferStats ( uint32_t count, uint32_t cycles, uint64_t sumcycles ) {\n\tfprintf(stderr, \"[%s:%d] count=%d cycles=%d sumcycles=%lld avgcycles=%f\\n\", __FUNCTION__, __LINE__, count, cycles, sumcycles, (double)sumcycles \/ count);\n }\n};\n\nint main(int argc, const char **argv)\n{\n PortalPoller *poller = 0;\n DmaIndicationWrapper *dmaIndication;\n\n poller = new PortalPoller();\n device = new HdmiDisplayRequestProxy(IfcNames_HdmiDisplayRequest, poller);\n dma = new DmaConfigProxy(IfcNames_DmaConfig);\n dmaIndication = new DmaIndication(dma, IfcNames_DmaIndication);\n HdmiInternalIndicationWrapper *hdmiIndication = new HdmiIndication(IfcNames_HdmiInternalIndication);\n HdmiDisplayIndicationWrapper *displayIndication = new DisplayIndication(IfcNames_HdmiDisplayIndication);\n hdmiInternal = new HdmiInternalRequestProxy(IfcNames_HdmiInternalRequest);\n\n \/\/ read out monitor EDID from ADV7511\n struct edid edid;\n init_i2c_hdmi();\n int i2cfd = open(\"\/dev\/i2c-0\", O_RDWR);\n fprintf(stderr, \"Monitor EDID:\\n\");\n for (int i = 0; i < 256; i++) {\n edid.raw[i] = i2c_read_reg(i2cfd, 0x3f, i);\n fprintf(stderr, \" %02x\", edid.raw[i]);\n if ((i % 16) == 15) {\n\tfprintf(stderr, \" \");\n\tfor (int j = i-15; j <= i; j++) {\n\t unsigned char c = edid.raw[j];\n\t fprintf(stderr, \"%c\", (isprint(c) && isascii(c)) ? c : '.');\n\t}\n\tfprintf(stderr, \"\\n\");\n }\n }\n close(i2cfd);\n parseEdid(edid);\n\n device->stopFrameBuffer();\n\n pthread_t thread;\n pthread_attr_t attr;\n pthread_attr_init(&attr);\n pthread_create(&thread, &attr, thread_routine, 0);\n\n int status;\n status = poller->setClockFrequency(0, 100000000, 0);\n\n for (int i = 0; i < 4; i++) {\n int pixclk = (long)edid.timing[i].pixclk * 10000;\n if ((pixclk > 0) && (pixclk < 170000000)) {\n\tnlines = edid.timing[i].nlines; \/\/ number of visible lines\n\tnpixels = edid.timing[i].npixels;\n\tint vblank = edid.timing[i].blines; \/\/ number of blanking lines\n\tint hblank = edid.timing[i].bpixels;\n\tint vsyncoff = edid.timing[i].vsyncoff; \/\/ number of lines in FrontPorch (within blanking)\n\tint hsyncoff = edid.timing[i].hsyncoff;\n\tint vsyncwidth = edid.timing[i].vsyncwidth; \/\/ width of Sync (within blanking)\n\tint hsyncwidth = edid.timing[i].hsyncwidth;\n\n\tfprintf(stderr, \"lines %d, pixels %d, vblank %d, hblank %d, vwidth %d, hwidth %d\\n\",\n nlines, npixels, vblank, hblank, vsyncwidth, hsyncwidth);\n\tfprintf(stderr, \"Using pixclk %d calc_pixclk %d npixels %d nlines %d\\n\",\n\t\tpixclk,\n\t\t60l * (long)(hblank + npixels) * (long)(vblank + nlines),\n\t\tnpixels, nlines);\n\tstatus = poller->setClockFrequency(1, pixclk, 0);\nhblank--; \/\/ needed on zc702\n\thdmiInternal->setDeLine(vsyncoff, \/\/ End of FrontPorch\n vsyncoff+vsyncwidth,\/\/ End of Sync\n vblank, \/\/ Start of Visible (start of BackPorch)\n vblank + nlines, vblank + nlines \/ 2); \/\/ End\n hdmiInternal->setDePixel(hsyncoff,\n hsyncoff+hsyncwidth, hblank,\n hblank + npixels, hblank + npixels \/ 2);\n\tbreak;\n }\n }\n\n fbsize = nlines*npixels*4;\n\n for (int i = 0; i < FRAME_COUNT; i++) {\n int err = dma->alloc(fbsize, &portalAlloc[i]);\n dataptr[i] = (int*)mmap(0, fbsize, PROT_READ|PROT_WRITE, MAP_SHARED, portalAlloc[i]->header.fd, 0);\n memset(dataptr[i], i ? 0xff : 0, fbsize);\n fprintf(stderr, \"calling dma->reference\\n\");\n ref_srcAlloc[i] = dma->reference(portalAlloc[i]);\n }\n\n fprintf(stderr, \"first mem_stats=%10u\\n\", dma->show_mem_stats(ChannelType_Read));\n sleep(3);\n fprintf(stderr, \"Starting frame buffer ref=%d...\", ref_srcAlloc[0]);\n fill_pixels(0);\n fprintf(stderr, \"done\\n\");\n while (1) {\n fprintf(stderr, \"mem_stats=%10u\\n\", dma->show_mem_stats(ChannelType_Read));\n sleep(1);\n }\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"indexer\/feature_covering.hpp\"\n#include \"indexer\/cell_coverer.hpp\"\n#include \"indexer\/cell_id.hpp\"\n#include \"indexer\/feature.hpp\"\n#include \"indexer\/scales.hpp\"\n\n#include \"geometry\/covering_utils.hpp\"\n\n#include \"std\/vector.hpp\"\n\n\nnamespace\n{\n\n\/\/ This class should only be used with covering::CoverObject()!\nclass FeatureIntersector\n{\npublic:\n struct Trg\n {\n m2::PointD m_a, m_b, m_c;\n Trg(m2::PointD const & a, m2::PointD const & b, m2::PointD const & c)\n : m_a(a), m_b(b), m_c(c) {}\n };\n\n vector<m2::PointD> m_polyline;\n vector<Trg> m_trg;\n m2::RectD m_rect;\n\n \/\/ Note:\n \/\/ 1. Here we don't need to differentiate between CELL_OBJECT_INTERSECT and OBJECT_INSIDE_CELL.\n \/\/ 2. We can return CELL_OBJECT_INTERSECT instead of CELL_INSIDE_OBJECT - it's just\n \/\/ a performance penalty.\n covering::CellObjectIntersection operator() (RectId const & cell) const\n {\n using namespace covering;\n\n m2::RectD cellRect;\n {\n \/\/ Check for limit rect intersection.\n pair<uint32_t, uint32_t> const xy = cell.XY();\n uint32_t const r = cell.Radius();\n ASSERT_GREATER_OR_EQUAL(xy.first, r, ());\n ASSERT_GREATER_OR_EQUAL(xy.second, r, ());\n\n cellRect = m2::RectD(xy.first - r, xy.second - r, xy.first + r, xy.second + r);\n if (!cellRect.IsIntersect(m_rect))\n return CELL_OBJECT_NO_INTERSECTION;\n }\n\n for (size_t i = 0; i < m_trg.size(); ++i)\n {\n m2::RectD r;\n r.Add(m_trg[i].m_a);\n r.Add(m_trg[i].m_b);\n r.Add(m_trg[i].m_c);\n if (!cellRect.IsIntersect(r))\n continue;\n\n CellObjectIntersection const res =\n IntersectCellWithTriangle(cell, m_trg[i].m_a, m_trg[i].m_b, m_trg[i].m_c);\n\n switch (res)\n {\n case CELL_OBJECT_NO_INTERSECTION:\n break;\n case CELL_INSIDE_OBJECT:\n return CELL_INSIDE_OBJECT;\n case CELL_OBJECT_INTERSECT:\n case OBJECT_INSIDE_CELL:\n return CELL_OBJECT_INTERSECT;\n }\n }\n\n for (size_t i = 1; i < m_polyline.size(); ++i)\n {\n CellObjectIntersection const res =\n IntersectCellWithLine(cell, m_polyline[i], m_polyline[i-1]);\n switch (res)\n {\n case CELL_OBJECT_NO_INTERSECTION:\n break;\n case CELL_INSIDE_OBJECT:\n ASSERT(false, (cell, i, m_polyline));\n return CELL_OBJECT_INTERSECT;\n case CELL_OBJECT_INTERSECT:\n case OBJECT_INSIDE_CELL:\n return CELL_OBJECT_INTERSECT;\n }\n }\n\n return CELL_OBJECT_NO_INTERSECTION;\n }\n\n typedef CellIdConverter<MercatorBounds, RectId> CellIdConverterType;\n\n m2::PointD ConvertPoint(m2::PointD const & p)\n {\n m2::PointD const pt(CellIdConverterType::XToCellIdX(p.x),\n CellIdConverterType::YToCellIdY(p.y));\n m_rect.Add(pt);\n return pt;\n }\n\n void operator() (m2::PointD const & pt)\n {\n m_polyline.push_back(ConvertPoint(pt));\n }\n\n void operator() (m2::PointD const & a, m2::PointD const & b, m2::PointD const & c)\n {\n m_trg.emplace_back(ConvertPoint(a), ConvertPoint(b), ConvertPoint(c));\n }\n};\n\n}\n\nnamespace covering\n{\n\nvector<int64_t> CoverFeature(FeatureType const & f, int cellDepth, uint64_t cellPenaltyArea)\n{\n \/\/ We need to cover feature for the best geometry, because it's indexed once for the\n \/\/ first top level scale. Do reset current cached geometry first.\n f.ResetGeometry();\n int const scale = FeatureType::BEST_GEOMETRY;\n\n FeatureIntersector fIsect;\n f.ForEachPointRef(fIsect, scale);\n f.ForEachTriangleRef(fIsect, scale);\n\n CHECK(!(fIsect.m_trg.empty() && fIsect.m_polyline.empty()) &&\n f.GetLimitRect(scale).IsValid(), (f.DebugString(scale)));\n\n if (fIsect.m_trg.empty() && fIsect.m_polyline.size() == 1)\n {\n m2::PointD const pt = fIsect.m_polyline[0];\n return vector<int64_t>(\n 1, RectId::FromXY(static_cast<uint32_t>(pt.x), static_cast<uint32_t>(pt.y),\n RectId::DEPTH_LEVELS - 1).ToInt64(cellDepth));\n }\n\n vector<RectId> cells;\n covering::CoverObject(fIsect, cellPenaltyArea, cells, cellDepth, RectId::Root());\n\n vector<int64_t> res(cells.size());\n for (size_t i = 0; i < cells.size(); ++i)\n res[i] = cells[i].ToInt64(cellDepth);\n\n return res;\n}\n\nvoid SortAndMergeIntervals(IntervalsT v, IntervalsT & res)\n{\n#ifdef DEBUG\n ASSERT ( res.empty(), () );\n for (size_t i = 0; i < v.size(); ++i)\n ASSERT_LESS(v[i].first, v[i].second, (i));\n#endif\n\n sort(v.begin(), v.end());\n\n res.reserve(v.size());\n for (size_t i = 0; i < v.size(); ++i)\n {\n if (i == 0 || res.back().second < v[i].first)\n res.push_back(v[i]);\n else\n res.back().second = max(res.back().second, v[i].second);\n }\n}\n\nIntervalsT SortAndMergeIntervals(IntervalsT const & v)\n{\n IntervalsT res;\n SortAndMergeIntervals(v, res);\n return res;\n}\n\nvoid AppendLowerLevels(RectId id, int cellDepth, IntervalsT & intervals)\n{\n int64_t idInt64 = id.ToInt64(cellDepth);\n intervals.push_back(make_pair(idInt64, idInt64 + id.SubTreeSize(cellDepth)));\n while (id.Level() > 0)\n {\n id = id.Parent();\n idInt64 = id.ToInt64(cellDepth);\n intervals.push_back(make_pair(idInt64, idInt64 + 1));\n }\n}\n\nvoid CoverViewportAndAppendLowerLevels(m2::RectD const & r, int cellDepth, IntervalsT & res)\n{\n vector<RectId> ids;\n CoverRect<MercatorBounds, RectId>(r.minX(), r.minY(), r.maxX(), r.maxY(), 8, cellDepth, ids);\n\n IntervalsT intervals;\n intervals.reserve(ids.size() * 4);\n\n for (size_t i = 0; i < ids.size(); ++i)\n AppendLowerLevels(ids[i], cellDepth, intervals);\n\n SortAndMergeIntervals(intervals, res);\n}\n\nRectId GetRectIdAsIs(m2::RectD const & r)\n{\n double const eps = MercatorBounds::GetCellID2PointAbsEpsilon();\n\n typedef CellIdConverter<MercatorBounds, RectId> TConverter;\n RectId const id = TConverter::Cover2PointsWithCell(\n MercatorBounds::ClampX(r.minX() + eps),\n MercatorBounds::ClampY(r.minY() + eps),\n MercatorBounds::ClampX(r.maxX() - eps),\n MercatorBounds::ClampY(r.maxY() - eps));\n\n \/\/ Calling this function make sence only for rects that are equal with index cells.\n \/\/ Check it here ...\n#ifdef DEBUG\n double minX, minY, maxX, maxY;\n TConverter::GetCellBounds(id, minX, minY, maxX, maxY);\n m2::RectD dbgR(minX, minY, maxX, maxY);\n ASSERT(m2::IsEqual(dbgR, r, eps, eps), (r, dbgR));\n#endif\n\n return id;\n}\n\nint GetCodingDepth(int scale)\n{\n int const delta = scales::GetUpperScale() - scale;\n ASSERT_GREATER_OR_EQUAL ( delta, 0, () );\n\n return (RectId::DEPTH_LEVELS - delta);\n}\n\nIntervalsT const & CoveringGetter::Get(int scale)\n{\n int const cellDepth = GetCodingDepth(scale);\n int const ind = (cellDepth == RectId::DEPTH_LEVELS ? 0 : 1);\n\n if (m_res[ind].empty())\n {\n switch (m_mode)\n {\n case ViewportWithLowLevels:\n CoverViewportAndAppendLowerLevels(m_rect, cellDepth, m_res[ind]);\n break;\n\n case LowLevelsOnly:\n {\n RectId id = GetRectIdAsIs(m_rect);\n while (id.Level() >= cellDepth)\n id = id.Parent();\n AppendLowerLevels(id, cellDepth, m_res[ind]);\n\/*\n#ifdef DEBUG\n size_t oldSize = m_res[ind].size();\n IntervalsT res;\n SortAndMergeIntervals(m_res[ind], res);\n if (res.size() != oldSize)\n LOG(LDEBUG, (\"Old =\", oldSize, \"; New =\", res.size()));\n res.swap(m_res[ind]);\n#endif\n*\/\n break;\n }\n\n case FullCover:\n m_res[ind].push_back(IntervalsT::value_type(0, static_cast<int64_t>((1ULL << 63) - 1)));\n break;\n }\n }\n\n return m_res[ind];\n}\n\n}\n<commit_msg>Review fixes.<commit_after>#include \"indexer\/feature_covering.hpp\"\n#include \"indexer\/cell_coverer.hpp\"\n#include \"indexer\/cell_id.hpp\"\n#include \"indexer\/feature.hpp\"\n#include \"indexer\/scales.hpp\"\n\n#include \"geometry\/covering_utils.hpp\"\n\n#include \"std\/vector.hpp\"\n\n\nnamespace\n{\n\n\/\/ This class should only be used with covering::CoverObject()!\nclass FeatureIntersector\n{\npublic:\n struct Trg\n {\n m2::PointD m_a, m_b, m_c;\n Trg(m2::PointD const & a, m2::PointD const & b, m2::PointD const & c)\n : m_a(a), m_b(b), m_c(c) {}\n };\n\n vector<m2::PointD> m_polyline;\n vector<Trg> m_trg;\n m2::RectD m_rect;\n\n \/\/ Note:\n \/\/ 1. Here we don't need to differentiate between CELL_OBJECT_INTERSECT and OBJECT_INSIDE_CELL.\n \/\/ 2. We can return CELL_OBJECT_INTERSECT instead of CELL_INSIDE_OBJECT - it's just\n \/\/ a performance penalty.\n covering::CellObjectIntersection operator() (RectId const & cell) const\n {\n using namespace covering;\n\n m2::RectD cellRect;\n {\n \/\/ Check for limit rect intersection.\n pair<uint32_t, uint32_t> const xy = cell.XY();\n uint32_t const r = cell.Radius();\n ASSERT_GREATER_OR_EQUAL(xy.first, r, ());\n ASSERT_GREATER_OR_EQUAL(xy.second, r, ());\n\n cellRect = m2::RectD(xy.first - r, xy.second - r, xy.first + r, xy.second + r);\n if (!cellRect.IsIntersect(m_rect))\n return CELL_OBJECT_NO_INTERSECTION;\n }\n\n for (size_t i = 0; i < m_trg.size(); ++i)\n {\n m2::RectD r;\n r.Add(m_trg[i].m_a);\n r.Add(m_trg[i].m_b);\n r.Add(m_trg[i].m_c);\n if (!cellRect.IsIntersect(r))\n continue;\n\n CellObjectIntersection const res =\n IntersectCellWithTriangle(cell, m_trg[i].m_a, m_trg[i].m_b, m_trg[i].m_c);\n\n switch (res)\n {\n case CELL_OBJECT_NO_INTERSECTION:\n break;\n case CELL_INSIDE_OBJECT:\n return CELL_INSIDE_OBJECT;\n case CELL_OBJECT_INTERSECT:\n case OBJECT_INSIDE_CELL:\n return CELL_OBJECT_INTERSECT;\n }\n }\n\n for (size_t i = 1; i < m_polyline.size(); ++i)\n {\n CellObjectIntersection const res =\n IntersectCellWithLine(cell, m_polyline[i], m_polyline[i-1]);\n switch (res)\n {\n case CELL_OBJECT_NO_INTERSECTION:\n break;\n case CELL_INSIDE_OBJECT:\n ASSERT(false, (cell, i, m_polyline));\n return CELL_OBJECT_INTERSECT;\n case CELL_OBJECT_INTERSECT:\n case OBJECT_INSIDE_CELL:\n return CELL_OBJECT_INTERSECT;\n }\n }\n\n return CELL_OBJECT_NO_INTERSECTION;\n }\n\n typedef CellIdConverter<MercatorBounds, RectId> CellIdConverterType;\n\n m2::PointD ConvertPoint(m2::PointD const & p)\n {\n m2::PointD const pt(CellIdConverterType::XToCellIdX(p.x),\n CellIdConverterType::YToCellIdY(p.y));\n m_rect.Add(pt);\n return pt;\n }\n\n void operator() (m2::PointD const & pt)\n {\n m_polyline.push_back(ConvertPoint(pt));\n }\n\n void operator() (m2::PointD const & a, m2::PointD const & b, m2::PointD const & c)\n {\n m_trg.emplace_back(ConvertPoint(a), ConvertPoint(b), ConvertPoint(c));\n }\n};\n\n}\n\nnamespace covering\n{\n\nvector<int64_t> CoverFeature(FeatureType const & f, int cellDepth, uint64_t cellPenaltyArea)\n{\n \/\/ We need to cover feature for the best geometry, because it's indexed once for the\n \/\/ first top level scale. Do reset current cached geometry first.\n f.ResetGeometry();\n int const scale = FeatureType::BEST_GEOMETRY;\n\n FeatureIntersector fIsect;\n f.ForEachPointRef(fIsect, scale);\n f.ForEachTriangleRef(fIsect, scale);\n\n CHECK(!(fIsect.m_trg.empty() && fIsect.m_polyline.empty()) &&\n f.GetLimitRect(scale).IsValid(), (f.DebugString(scale)));\n\n if (fIsect.m_trg.empty() && fIsect.m_polyline.size() == 1)\n {\n m2::PointD const pt = fIsect.m_polyline[0];\n return vector<int64_t>(\n 1, RectId::FromXY(static_cast<uint32_t>(pt.x), static_cast<uint32_t>(pt.y),\n RectId::DEPTH_LEVELS - 1).ToInt64(cellDepth));\n }\n\n vector<RectId> cells;\n covering::CoverObject(fIsect, cellPenaltyArea, cells, cellDepth, RectId::Root());\n\n vector<int64_t> res(cells.size());\n for (size_t i = 0; i < cells.size(); ++i)\n res[i] = cells[i].ToInt64(cellDepth);\n\n return res;\n}\n\nvoid SortAndMergeIntervals(IntervalsT v, IntervalsT & res)\n{\n#ifdef DEBUG\n ASSERT ( res.empty(), () );\n for (size_t i = 0; i < v.size(); ++i)\n ASSERT_LESS(v[i].first, v[i].second, (i));\n#endif\n\n sort(v.begin(), v.end());\n\n res.reserve(v.size());\n for (size_t i = 0; i < v.size(); ++i)\n {\n if (i == 0 || res.back().second < v[i].first)\n res.push_back(v[i]);\n else\n res.back().second = max(res.back().second, v[i].second);\n }\n}\n\nIntervalsT SortAndMergeIntervals(IntervalsT const & v)\n{\n IntervalsT res;\n SortAndMergeIntervals(v, res);\n return res;\n}\n\nvoid AppendLowerLevels(RectId id, int cellDepth, IntervalsT & intervals)\n{\n int64_t idInt64 = id.ToInt64(cellDepth);\n intervals.push_back(make_pair(idInt64, idInt64 + id.SubTreeSize(cellDepth)));\n while (id.Level() > 0)\n {\n id = id.Parent();\n idInt64 = id.ToInt64(cellDepth);\n intervals.push_back(make_pair(idInt64, idInt64 + 1));\n }\n}\n\nvoid CoverViewportAndAppendLowerLevels(m2::RectD const & r, int cellDepth, IntervalsT & res)\n{\n vector<RectId> ids;\n CoverRect<MercatorBounds, RectId>(r.minX(), r.minY(), r.maxX(), r.maxY(), 8, cellDepth, ids);\n\n IntervalsT intervals;\n intervals.reserve(ids.size() * 4);\n\n for (size_t i = 0; i < ids.size(); ++i)\n AppendLowerLevels(ids[i], cellDepth, intervals);\n\n SortAndMergeIntervals(intervals, res);\n}\n\nRectId GetRectIdAsIs(m2::RectD const & r)\n{\n double const eps = MercatorBounds::GetCellID2PointAbsEpsilon();\n using TConverter = CellIdConverter<MercatorBounds, RectId>;\n\n RectId const id = TConverter::Cover2PointsWithCell(\n MercatorBounds::ClampX(r.minX() + eps),\n MercatorBounds::ClampY(r.minY() + eps),\n MercatorBounds::ClampX(r.maxX() - eps),\n MercatorBounds::ClampY(r.maxY() - eps));\n\n \/\/ Calling this function makes sence only for rects that are equal with index cells.\n \/\/ Check it here ...\n#ifdef DEBUG\n double minX, minY, maxX, maxY;\n TConverter::GetCellBounds(id, minX, minY, maxX, maxY);\n m2::RectD dbgR(minX, minY, maxX, maxY);\n ASSERT(m2::IsEqual(dbgR, r, eps, eps), (r, dbgR));\n#endif\n\n return id;\n}\n\nint GetCodingDepth(int scale)\n{\n int const delta = scales::GetUpperScale() - scale;\n ASSERT_GREATER_OR_EQUAL ( delta, 0, () );\n\n return (RectId::DEPTH_LEVELS - delta);\n}\n\nIntervalsT const & CoveringGetter::Get(int scale)\n{\n int const cellDepth = GetCodingDepth(scale);\n int const ind = (cellDepth == RectId::DEPTH_LEVELS ? 0 : 1);\n\n if (m_res[ind].empty())\n {\n switch (m_mode)\n {\n case ViewportWithLowLevels:\n CoverViewportAndAppendLowerLevels(m_rect, cellDepth, m_res[ind]);\n break;\n\n case LowLevelsOnly:\n {\n RectId id = GetRectIdAsIs(m_rect);\n while (id.Level() >= cellDepth)\n id = id.Parent();\n AppendLowerLevels(id, cellDepth, m_res[ind]);\n\n \/\/ Check for optimal result intervals.\n#if 0\n size_t oldSize = m_res[ind].size();\n IntervalsT res;\n SortAndMergeIntervals(m_res[ind], res);\n if (res.size() != oldSize)\n LOG(LINFO, (\"Old =\", oldSize, \"; New =\", res.size()));\n res.swap(m_res[ind]);\n#endif\n break;\n }\n\n case FullCover:\n m_res[ind].push_back(IntervalsT::value_type(0, static_cast<int64_t>((1ULL << 63) - 1)));\n break;\n }\n }\n\n return m_res[ind];\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/**\n * This file is part of the \"FnordMetric\" project\n * Copyright (c) 2014 Paul Asmuth, Google Inc.\n *\n * FnordMetric is free software: you can redistribute it and\/or modify it under\n * the terms of the GNU General Public License v3.0. You should have received a\n * copy of the GNU General Public License along with this program. If not, see\n * <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n#include <fnord\/base\/stringutil.h>\n#include <fnordmetric\/environment.h>\n#include <fnordmetric\/metricdb\/httpapi.h>\n#include <fnordmetric\/query\/queryservice.h>\n#include <fnordmetric\/metricdb\/metricrepository.h>\n#include <fnordmetric\/metricdb\/metrictablerepository.h>\n#include <fnordmetric\/sql\/backends\/csv\/csvbackend.h>\n#include <fnordmetric\/sql\/backends\/mysql\/mysqlbackend.h>\n\nnamespace fnordmetric {\nnamespace metricdb {\n\nstatic const char kMetricsUrl[] = \"\/metrics\";\nstatic const char kMetricsUrlPrefix[] = \"\/metrics\/\";\nstatic const char kQueryUrl[] = \"\/query\";\nstatic const char kLabelParamPrefix[] = \"label[\";\n\nHTTPAPI::HTTPAPI(IMetricRepository* metric_repo) : metric_repo_(metric_repo) {}\n\nbool HTTPAPI::handleHTTPRequest(\n http::HTTPRequest* request,\n http::HTTPResponse* response) {\n fnord::URI uri(request->getUrl());\n auto path = uri.path();\n fnord::StringUtil::stripTrailingSlashes(&path);\n\n response->addHeader(\"Access-Control-Allow-Origin\", \"*\");\n\n \/\/ PATH: ^\/metrics\/?$\n if (path == kMetricsUrl) {\n switch (request->method()) {\n case http::HTTPRequest::M_GET:\n renderMetricList(request, response, &uri);\n return true;\n case http::HTTPRequest::M_POST:\n insertSample(request, response, &uri);\n return true;\n default:\n return false;\n }\n }\n\n \/\/ PATH: ^\/metrics\/.*\n if (path.compare(0, sizeof(kMetricsUrlPrefix) - 1, kMetricsUrlPrefix) == 0) {\n \/\/ PATH: ^\/metrics\/(.*)$\n switch (request->method()) {\n case http::HTTPRequest::M_GET:\n renderMetricSampleScan(request, response, &uri);\n return true;\n default:\n return false;\n }\n }\n\n \/\/ PATH: ^\/query\/?*\n if (path == kQueryUrl) {\n switch (request->method()) {\n case http::HTTPRequest::M_GET:\n case http::HTTPRequest::M_POST:\n executeQuery(request, response, &uri);\n return true;\n default:\n return false;\n }\n return true;\n }\n\n return false;\n}\n\nvoid HTTPAPI::renderMetricList(\n http::HTTPRequest* request,\n http::HTTPResponse* response,\n fnord::URI* uri) {\n response->setStatus(http::kStatusOK);\n response->addHeader(\"Content-Type\", \"application\/json; charset=utf-8\");\n util::JSONOutputStream json(response->getBodyOutputStream());\n\n json.beginObject();\n json.addObjectEntry(\"metrics\");\n json.beginArray();\n\n int i = 0;\n for (const auto& metric : metric_repo_->listMetrics()) {\n if (i++ > 0) { json.addComma(); }\n renderMetricJSON(metric, &json);\n }\n\n json.endArray();\n json.endObject();\n}\n\nvoid HTTPAPI::insertSample(\n http::HTTPRequest* request,\n http::HTTPResponse* response,\n fnord::URI* uri) {\n const auto& postbody = request->getBody();\n fnord::URI::ParamList params;\n\n if (postbody.size() > 0) {\n fnord::URI::parseQueryString(postbody, ¶ms);\n } else {\n params = uri->queryParams();\n }\n\n std::string metric_key;\n if (!fnord::URI::getParam(params, \"metric\", &metric_key)) {\n response->addBody(\"error: invalid metric key: \" + metric_key);\n response->setStatus(http::kStatusBadRequest);\n return;\n }\n\n std::string value_str;\n if (!fnord::URI::getParam(params, \"value\", &value_str)) {\n response->addBody(\"error: missing ?value=... parameter\");\n response->setStatus(http::kStatusBadRequest);\n return;\n }\n\n std::vector<std::pair<std::string, std::string>> labels;\n for (const auto& param : params) {\n const auto& key = param.first;\n const auto& value = param.second;\n\n if (key.compare(0, sizeof(kLabelParamPrefix) - 1, kLabelParamPrefix) == 0 &&\n key.back() == ']') {\n auto label_key = key.substr(\n sizeof(kLabelParamPrefix) - 1,\n key.size() - sizeof(kLabelParamPrefix));\n\n labels.emplace_back(label_key, value);\n }\n }\n\n double sample_value;\n try {\n sample_value = std::stod(value_str);\n } catch (std::exception& e) {\n response->addBody(\"error: invalid value: \" + value_str);\n response->setStatus(http::kStatusBadRequest);\n return;\n }\n\n auto metric = metric_repo_->findOrCreateMetric(metric_key);\n metric->insertSample(sample_value, labels);\n response->setStatus(http::kStatusCreated);\n}\n\nvoid HTTPAPI::renderMetricSampleScan(\n http::HTTPRequest* request,\n http::HTTPResponse* response,\n fnord::URI* uri) {\n auto metric_key = uri->path().substr(sizeof(kMetricsUrlPrefix) - 1);\n if (metric_key.size() < 3) {\n response->addBody(\"error: invalid metric key: \" + metric_key);\n response->setStatus(http::kStatusBadRequest);\n return;\n }\n\n auto metric = metric_repo_->findMetric(metric_key);\n if (metric == nullptr) {\n response->addBody(\"metric not found: \" + metric_key);\n response->setStatus(http::kStatusNotFound);\n return;\n }\n\n response->setStatus(http::kStatusOK);\n response->addHeader(\"Content-Type\", \"application\/json; charset=utf-8\");\n util::JSONOutputStream json(response->getBodyOutputStream());\n\n json.beginObject();\n\n json.addObjectEntry(\"metric\");\n renderMetricJSON(metric, &json);\n json.addComma();\n\n json.addObjectEntry(\"samples\");\n json.beginArray();\n\n int i = 0;\n metric->scanSamples(\n fnord::util::DateTime::epoch(),\n fnord::util::DateTime::now(),\n [&json, &i] (Sample* sample) -> bool {\n if (i++ > 0) { json.addComma(); }\n json.beginObject();\n\n json.addObjectEntry(\"time\");\n json.addLiteral<uint64_t>(static_cast<uint64_t>(sample->time()));\n json.addComma();\n\n json.addObjectEntry(\"value\");\n json.addLiteral<double>(sample->value());\n json.addComma();\n\n json.addObjectEntry(\"labels\");\n json.beginObject();\n auto labels = sample->labels();\n for (int n = 0; n < labels.size(); n++) {\n if (n > 0) {\n json.addComma();\n }\n\n json.addObjectEntry(labels[n].first);\n json.addString(labels[n].second);\n }\n json.endObject();\n\n json.endObject();\n return true;\n });\n\n json.endArray();\n json.endObject();\n}\n\nvoid HTTPAPI::executeQuery(\n http::HTTPRequest* request,\n http::HTTPResponse* response,\n fnord::URI* uri) {\n auto params = uri->queryParams();\n\n std::shared_ptr<util::InputStream> input_stream;\n std::string get_query;\n if (fnord::URI::getParam(params, \"q\", &get_query)) {\n input_stream.reset(new util::StringInputStream(get_query));\n } else {\n input_stream = request->getBodyInputStream();\n }\n\n std::shared_ptr<util::OutputStream> output_stream =\n response->getBodyOutputStream();\n\n query::QueryService query_service;\n std::unique_ptr<query::TableRepository> table_repo(\n new MetricTableRepository(metric_repo_));\n\n\n if (!env()->flags()->isSet(\"disable_external_sources\")) {\n query_service.registerBackend(\n std::unique_ptr<fnordmetric::query::Backend>(\n new fnordmetric::query::mysql_backend::MySQLBackend));\n\n query_service.registerBackend(\n std::unique_ptr<fnordmetric::query::Backend>(\n new fnordmetric::query::csv_backend::CSVBackend));\n }\n\n query::QueryService::kFormat resp_format = query::QueryService::FORMAT_JSON;\n std::string format_param;\n if (fnord::URI::getParam(params, \"format\", &format_param)) {\n if (format_param == \"svg\") {\n resp_format = query::QueryService::FORMAT_SVG;\n }\n }\n\n response->setStatus(http::kStatusOK);\n\n switch (resp_format) {\n case query::QueryService::FORMAT_JSON:\n response->addHeader(\"Content-Type\", \"application\/json; charset=utf-8\");\n break;\n case query::QueryService::FORMAT_SVG:\n response->addHeader(\"Content-Type\", \"text\/html; charset=utf-8\");\n break;\n default:\n break;\n }\n\n int width = -1;\n std::string width_param;\n if (fnord::URI::getParam(params, \"width\", &width_param)) {\n width = std::stoi(width_param);\n }\n\n int height = -1;\n std::string height_param;\n if (fnord::URI::getParam(params, \"height\", &height_param)) {\n height = std::stoi(height_param);\n }\n\n try {\n query_service.executeQuery(\n input_stream,\n resp_format,\n output_stream,\n std::move(table_repo),\n width,\n height);\n\n } catch (fnord::Exception e) {\n response->clearBody();\n\n util::JSONOutputStream json(std::move(output_stream));\n json.beginObject();\n json.addObjectEntry(\"status\");\n json.addString(\"error\");\n json.addComma();\n json.addObjectEntry(\"error\");\n json.addString(e.getMessage());\n json.endObject();\n }\n}\n\nvoid HTTPAPI::renderMetricJSON(\n IMetric* metric,\n util::JSONOutputStream* json) const {\n json->beginObject();\n\n json->addObjectEntry(\"key\");\n json->addString(metric->key());\n json->addComma();\n\n json->addObjectEntry(\"total_bytes\");\n json->addLiteral<size_t>(metric->totalBytes());\n json->addComma();\n\n json->addObjectEntry(\"last_insert\");\n json->addLiteral<uint64_t>(static_cast<uint64_t>(metric->lastInsertTime()));\n json->addComma();\n\n json->addObjectEntry(\"labels\");\n json->beginArray();\n auto labels = metric->labels();\n for (auto cur = labels.begin(); cur != labels.end(); ++cur) {\n if (cur != labels.begin()) {\n json->addComma();\n }\n json->addString(*cur);\n }\n json->endArray();\n\n json->endObject();\n}\n\n}\n}\n<commit_msg>filter renderMetricJSON<commit_after>\/**\n * This file is part of the \"FnordMetric\" project\n * Copyright (c) 2014 Paul Asmuth, Google Inc.\n *\n * FnordMetric is free software: you can redistribute it and\/or modify it under\n * the terms of the GNU General Public License v3.0. You should have received a\n * copy of the GNU General Public License along with this program. If not, see\n * <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n#include <fnord\/base\/stringutil.h>\n#include <fnordmetric\/environment.h>\n#include <fnordmetric\/metricdb\/httpapi.h>\n#include <fnordmetric\/query\/queryservice.h>\n#include <fnordmetric\/metricdb\/metricrepository.h>\n#include <fnordmetric\/metricdb\/metrictablerepository.h>\n#include <fnordmetric\/sql\/backends\/csv\/csvbackend.h>\n#include <fnordmetric\/sql\/backends\/mysql\/mysqlbackend.h>\n\nnamespace fnordmetric {\nnamespace metricdb {\n\nstatic const char kMetricsUrl[] = \"\/metrics\";\nstatic const char kMetricsUrlPrefix[] = \"\/metrics\/\";\nstatic const char kQueryUrl[] = \"\/query\";\nstatic const char kLabelParamPrefix[] = \"label[\";\n\nHTTPAPI::HTTPAPI(IMetricRepository* metric_repo) : metric_repo_(metric_repo) {}\n\nbool HTTPAPI::handleHTTPRequest(\n http::HTTPRequest* request,\n http::HTTPResponse* response) {\n fnord::URI uri(request->getUrl());\n auto path = uri.path();\n fnord::StringUtil::stripTrailingSlashes(&path);\n\n response->addHeader(\"Access-Control-Allow-Origin\", \"*\");\n\n \/\/ PATH: ^\/metrics\/?$\n if (path == kMetricsUrl) {\n switch (request->method()) {\n case http::HTTPRequest::M_GET:\n renderMetricList(request, response, &uri);\n return true;\n case http::HTTPRequest::M_POST:\n insertSample(request, response, &uri);\n return true;\n default:\n return false;\n }\n }\n\n \/\/ PATH: ^\/metrics\/.*\n if (path.compare(0, sizeof(kMetricsUrlPrefix) - 1, kMetricsUrlPrefix) == 0) {\n \/\/ PATH: ^\/metrics\/(.*)$\n switch (request->method()) {\n case http::HTTPRequest::M_GET:\n renderMetricSampleScan(request, response, &uri);\n return true;\n default:\n return false;\n }\n }\n\n \/\/ PATH: ^\/query\/?*\n if (path == kQueryUrl) {\n switch (request->method()) {\n case http::HTTPRequest::M_GET:\n case http::HTTPRequest::M_POST:\n executeQuery(request, response, &uri);\n return true;\n default:\n return false;\n }\n return true;\n }\n\n return false;\n}\n\nvoid HTTPAPI::renderMetricList(\n http::HTTPRequest* request,\n http::HTTPResponse* response,\n fnord::URI* uri) {\n response->setStatus(http::kStatusOK);\n response->addHeader(\"Content-Type\", \"application\/json; charset=utf-8\");\n util::JSONOutputStream json(response->getBodyOutputStream());\n\n json.beginObject();\n json.addObjectEntry(\"metrics\");\n json.beginArray();\n\n fnord::URI::ParamList params = uri->queryParams();\n\n\n \/*const std::string& filter;\n const std::string& limit;\n if (fnord::URI::getParam(params, \"filter\", &metric_key)) {\n for (const auto& param : params) {\n if (param.first == \"filter\") {\n filter = param.second;\n } else if (param.first == \"limit\") {\n limit = param.second;\n }\n }\n }*\/\n\n\n int i = 0;\n std::string metric_key;\n for (const auto& metric : metric_repo_->listMetrics()) {\n if (fnord::URI::getParam(params, \"filter\", &metric_key)) {\n for (const auto& param : params) {\n const auto& key = param.first;\n const auto& value = param.second;\n\n if (key == \"filter\") {\n if ((metric->key()).find(value) != std::string::npos) {\n if (i++ > 0) { json.addComma(); }\n renderMetricJSON(metric, &json);\n }\n }\n }\n\n } else {\n if (i++ > 0) { json.addComma(); }\n renderMetricJSON(metric, &json);\n }\n }\n\n\n json.endArray();\n json.endObject();\n}\n\nvoid HTTPAPI::insertSample(\n http::HTTPRequest* request,\n http::HTTPResponse* response,\n fnord::URI* uri) {\n const auto& postbody = request->getBody();\n fnord::URI::ParamList params;\n\n if (postbody.size() > 0) {\n fnord::URI::parseQueryString(postbody, ¶ms);\n } else {\n params = uri->queryParams();\n }\n\n std::string metric_key;\n if (!fnord::URI::getParam(params, \"metric\", &metric_key)) {\n response->addBody(\"error: invalid metric key: \" + metric_key);\n response->setStatus(http::kStatusBadRequest);\n return;\n }\n\n std::string value_str;\n if (!fnord::URI::getParam(params, \"value\", &value_str)) {\n response->addBody(\"error: missing ?value=... parameter\");\n response->setStatus(http::kStatusBadRequest);\n return;\n }\n\n std::vector<std::pair<std::string, std::string>> labels;\n for (const auto& param : params) {\n const auto& key = param.first;\n const auto& value = param.second;\n\n if (key.compare(0, sizeof(kLabelParamPrefix) - 1, kLabelParamPrefix) == 0 &&\n key.back() == ']') {\n auto label_key = key.substr(\n sizeof(kLabelParamPrefix) - 1,\n key.size() - sizeof(kLabelParamPrefix));\n\n labels.emplace_back(label_key, value);\n }\n }\n\n double sample_value;\n try {\n sample_value = std::stod(value_str);\n } catch (std::exception& e) {\n response->addBody(\"error: invalid value: \" + value_str);\n response->setStatus(http::kStatusBadRequest);\n return;\n }\n\n auto metric = metric_repo_->findOrCreateMetric(metric_key);\n metric->insertSample(sample_value, labels);\n response->setStatus(http::kStatusCreated);\n}\n\nvoid HTTPAPI::renderMetricSampleScan(\n http::HTTPRequest* request,\n http::HTTPResponse* response,\n fnord::URI* uri) {\n auto metric_key = uri->path().substr(sizeof(kMetricsUrlPrefix) - 1);\n if (metric_key.size() < 3) {\n response->addBody(\"error: invalid metric key: \" + metric_key);\n response->setStatus(http::kStatusBadRequest);\n return;\n }\n\n auto metric = metric_repo_->findMetric(metric_key);\n if (metric == nullptr) {\n response->addBody(\"metric not found: \" + metric_key);\n response->setStatus(http::kStatusNotFound);\n return;\n }\n\n response->setStatus(http::kStatusOK);\n response->addHeader(\"Content-Type\", \"application\/json; charset=utf-8\");\n util::JSONOutputStream json(response->getBodyOutputStream());\n\n json.beginObject();\n\n json.addObjectEntry(\"metric\");\n renderMetricJSON(metric, &json);\n json.addComma();\n\n json.addObjectEntry(\"samples\");\n json.beginArray();\n\n int i = 0;\n metric->scanSamples(\n fnord::util::DateTime::epoch(),\n fnord::util::DateTime::now(),\n [&json, &i] (Sample* sample) -> bool {\n if (i++ > 0) { json.addComma(); }\n json.beginObject();\n\n json.addObjectEntry(\"time\");\n json.addLiteral<uint64_t>(static_cast<uint64_t>(sample->time()));\n json.addComma();\n\n json.addObjectEntry(\"value\");\n json.addLiteral<double>(sample->value());\n json.addComma();\n\n json.addObjectEntry(\"labels\");\n json.beginObject();\n auto labels = sample->labels();\n for (int n = 0; n < labels.size(); n++) {\n if (n > 0) {\n json.addComma();\n }\n\n json.addObjectEntry(labels[n].first);\n json.addString(labels[n].second);\n }\n json.endObject();\n\n json.endObject();\n return true;\n });\n\n json.endArray();\n json.endObject();\n}\n\nvoid HTTPAPI::executeQuery(\n http::HTTPRequest* request,\n http::HTTPResponse* response,\n fnord::URI* uri) {\n auto params = uri->queryParams();\n\n std::shared_ptr<util::InputStream> input_stream;\n std::string get_query;\n if (fnord::URI::getParam(params, \"q\", &get_query)) {\n input_stream.reset(new util::StringInputStream(get_query));\n } else {\n input_stream = request->getBodyInputStream();\n }\n\n std::shared_ptr<util::OutputStream> output_stream =\n response->getBodyOutputStream();\n\n query::QueryService query_service;\n std::unique_ptr<query::TableRepository> table_repo(\n new MetricTableRepository(metric_repo_));\n\n\n if (!env()->flags()->isSet(\"disable_external_sources\")) {\n query_service.registerBackend(\n std::unique_ptr<fnordmetric::query::Backend>(\n new fnordmetric::query::mysql_backend::MySQLBackend));\n\n query_service.registerBackend(\n std::unique_ptr<fnordmetric::query::Backend>(\n new fnordmetric::query::csv_backend::CSVBackend));\n }\n\n query::QueryService::kFormat resp_format = query::QueryService::FORMAT_JSON;\n std::string format_param;\n if (fnord::URI::getParam(params, \"format\", &format_param)) {\n if (format_param == \"svg\") {\n resp_format = query::QueryService::FORMAT_SVG;\n }\n }\n\n response->setStatus(http::kStatusOK);\n\n switch (resp_format) {\n case query::QueryService::FORMAT_JSON:\n response->addHeader(\"Content-Type\", \"application\/json; charset=utf-8\");\n break;\n case query::QueryService::FORMAT_SVG:\n response->addHeader(\"Content-Type\", \"text\/html; charset=utf-8\");\n break;\n default:\n break;\n }\n\n int width = -1;\n std::string width_param;\n if (fnord::URI::getParam(params, \"width\", &width_param)) {\n width = std::stoi(width_param);\n }\n\n int height = -1;\n std::string height_param;\n if (fnord::URI::getParam(params, \"height\", &height_param)) {\n height = std::stoi(height_param);\n }\n\n try {\n query_service.executeQuery(\n input_stream,\n resp_format,\n output_stream,\n std::move(table_repo),\n width,\n height);\n\n } catch (fnord::Exception e) {\n response->clearBody();\n\n util::JSONOutputStream json(std::move(output_stream));\n json.beginObject();\n json.addObjectEntry(\"status\");\n json.addString(\"error\");\n json.addComma();\n json.addObjectEntry(\"error\");\n json.addString(e.getMessage());\n json.endObject();\n }\n}\n\nvoid HTTPAPI::renderMetricJSON(\n IMetric* metric,\n util::JSONOutputStream* json) const {\n json->beginObject();\n\n json->addObjectEntry(\"key\");\n json->addString(metric->key());\n json->addComma();\n\n json->addObjectEntry(\"total_bytes\");\n json->addLiteral<size_t>(metric->totalBytes());\n json->addComma();\n\n json->addObjectEntry(\"last_insert\");\n json->addLiteral<uint64_t>(static_cast<uint64_t>(metric->lastInsertTime()));\n json->addComma();\n\n json->addObjectEntry(\"labels\");\n json->beginArray();\n auto labels = metric->labels();\n for (auto cur = labels.begin(); cur != labels.end(); ++cur) {\n if (cur != labels.begin()) {\n json->addComma();\n }\n json->addString(*cur);\n }\n json->endArray();\n\n json->endObject();\n}\n\n}\n}\n<|endoftext|>"} {"text":"<commit_before>\/******************************************************************************\n\n This source file is part of the Avogadro project.\n\n Copyright 2012 Kitware, Inc.\n\n This source code is released under the New BSD License, (the \"License\").\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n\n******************************************************************************\/\n\n#include \"mainwindow.h\"\n#include \"ui_mainwindow.h\"\n\n#include <avogadro\/qtgui\/molecule.h>\n#include <avogadro\/core\/elements.h>\n#include <avogadro\/io\/cmlformat.h>\n#include <avogadro\/io\/cjsonformat.h>\n#include <avogadro\/qtopengl\/editor.h>\n#include <avogadro\/qtopengl\/glwidget.h>\n#include <avogadro\/qtplugins\/pluginmanager.h>\n#include <avogadro\/qtgui\/sceneplugin.h>\n#include <avogadro\/qtgui\/scenepluginmodel.h>\n#include <avogadro\/qtgui\/extensionplugin.h>\n#include <avogadro\/rendering\/glrenderer.h>\n#include <avogadro\/rendering\/scene.h>\n\n#include <QtCore\/QCoreApplication>\n#include <QtCore\/QString>\n#include <QtCore\/QDebug>\n#include <QtCore\/QFileInfo>\n#include <QtCore\/QSettings>\n#include <QtGui\/QCloseEvent>\n#include <QtGui\/QMenu>\n#include <QtGui\/QMenuBar>\n#include <QtGui\/QFileDialog>\n#include <QtGui\/QStatusBar>\n#include <QtGui\/QToolBar>\n\n#include <QtGui\/QDockWidget>\n#include <QtGui\/QTreeView>\n#include <QtGui\/QHeaderView>\n\nnamespace Avogadro {\n\nusing QtGui::Molecule;\n\nMainWindow::MainWindow(const QString &fileName)\n : m_ui(new Ui::MainWindow),\n m_molecule(0),\n m_scenePluginModel(0)\n{\n m_ui->setupUi(this);\n\n QIcon icon(\":\/icons\/avogadro.png\");\n setWindowIcon(icon);\n\n \/\/ Create the scene plugin model\n m_scenePluginModel = new QtGui::ScenePluginModel(m_ui->scenePluginTreeView);\n m_ui->scenePluginTreeView->setModel(m_scenePluginModel);\n m_ui->scenePluginTreeView->setAlternatingRowColors(true);\n m_ui->scenePluginTreeView->header()->stretchLastSection();\n m_ui->scenePluginTreeView->header()->setVisible(false);\n connect(m_scenePluginModel,\n SIGNAL(pluginStateChanged(Avogadro::QtGui::ScenePlugin*)),\n SLOT(updateScenePlugins()));\n \/\/\/ @todo HACK the molecule should trigger the update\n connect(&m_ui->glWidget->editor(), SIGNAL(moleculeChanged()),\n SLOT(updateScenePlugins()));\n connect(&m_ui->glWidget->manipulator(), SIGNAL(moleculeChanged()),\n SLOT(updateScenePlugins()));\n\n \/\/ Connect the menu actions\n connect(m_ui->actionNewMolecule, SIGNAL(triggered()), SLOT(newMolecule()));\n connect(m_ui->actionOpen, SIGNAL(triggered()), SLOT(openFile()));\n connect(m_ui->actionQuit, SIGNAL(triggered()), qApp, SLOT(quit()));\n\n \/\/ Connect the temporary tool\/element selectors\n updateTool();\n buildElements();\n updateElement();\n connect(m_ui->toolComboBox, SIGNAL(currentIndexChanged(int)),\n SLOT(updateTool()));\n connect(m_ui->elementComboBox, SIGNAL(currentIndexChanged(int)),\n SLOT(updateElement()));\n\n readSettings();\n\n QtGui::PluginManager *plugin = QtGui::PluginManager::instance();\n plugin->load();\n QList<QtGui::ScenePluginFactory *> scenePluginFactories =\n plugin->pluginFactories<QtGui::ScenePluginFactory>();\n foreach (QtGui::ScenePluginFactory *factory, scenePluginFactories) {\n QtGui::ScenePlugin *scenePlugin = factory->createInstance();\n if (scenePlugin) {\n scenePlugin->setParent(this);\n m_scenePluginModel->addItem(scenePlugin);\n }\n }\n\n \/\/ Call this a second time, not needed but ensures plugins only load once.\n plugin->load();\n\n QList<QtGui::ExtensionPluginFactory *> extensions =\n plugin->pluginFactories<QtGui::ExtensionPluginFactory>();\n qDebug() << \"Extension plugins dynamically found...\" << extensions.size();\n foreach (QtGui::ExtensionPluginFactory *factory, extensions) {\n QtGui::ExtensionPlugin *extension = factory->createInstance();\n if (extension) {\n extension->setParent(this);\n qDebug() << \"extension:\" << extension->name() << extension->menuPath();\n connect(this, SIGNAL(moleculeChanged(QtGui::Molecule*)),\n extension, SLOT(setMolecule(QtGui::Molecule*)));\n connect(extension, SIGNAL(moleculeReady(int)), SLOT(moleculeReady(int)));\n buildMenu(extension);\n }\n }\n\n \/\/ try to open the file passed in. If opening fails, create a new molecule.\n openFile(fileName);\n if (!m_molecule)\n newMolecule();\n statusBar()->showMessage(tr(\"Ready...\"), 2000);\n}\n\nMainWindow::~MainWindow()\n{\n writeSettings();\n delete m_molecule;\n}\n\nvoid MainWindow::closeEvent(QCloseEvent *e)\n{\n writeSettings();\n QMainWindow::closeEvent(e);\n}\n\nvoid MainWindow::moleculeReady(int)\n{\n QtGui::ExtensionPlugin *extension =\n qobject_cast<QtGui::ExtensionPlugin *>(sender());\n if (extension) {\n QtGui::Molecule *mol = new QtGui::Molecule(this);\n if (extension->readMolecule(*mol))\n setMolecule(mol);\n }\n}\n\nvoid MainWindow::newMolecule()\n{\n setMolecule(new QtGui::Molecule);\n}\n\nvoid MainWindow::setMolecule(QtGui::Molecule *mol)\n{\n if (m_molecule == mol)\n return;\n\n \/\/ Clear the scene to prevent dangling identifiers:\n m_ui->glWidget->renderer().scene().clear();\n\n \/\/ Set molecule\n if (m_molecule)\n delete m_molecule;\n m_molecule = mol;\n\n emit moleculeChanged(m_molecule);\n\n connect(m_molecule, SIGNAL(changed(unsigned int)),\n SLOT(updateScenePlugins()));\n\n m_ui->glWidget->editor().setMolecule(mol);\n m_ui->glWidget->manipulator().setMolecule(mol);\n updateScenePlugins();\n m_ui->glWidget->resetCamera();\n}\n\nvoid MainWindow::writeSettings()\n{\n QSettings settings;\n settings.beginGroup(\"MainWindow\");\n settings.setValue(\"size\", size());\n settings.setValue(\"pos\", pos());\n settings.endGroup();\n settings.setValue(\"recentFiles\", m_recentFiles);\n}\n\nvoid MainWindow::readSettings()\n{\n QSettings settings;\n settings.beginGroup(\"MainWindow\");\n resize(settings.value(\"size\", QSize(400, 300)).toSize());\n move(settings.value(\"pos\", QPoint(20, 20)).toPoint());\n settings.endGroup();\n m_recentFiles = settings.value(\"recentFiles\", QStringList()).toStringList();\n updateRecentFiles();\n}\n\nvoid MainWindow::openFile()\n{\n QString fileName = QFileDialog::getOpenFileName(this, tr(\"Open chemical file\"),\n \"\", tr(\"Chemical files (*.cml *.cjson)\"));\n openFile(fileName);\n}\n\nvoid MainWindow::openFile(const QString &fileName)\n{\n if (fileName.isEmpty())\n return;\n\n QFileInfo info(fileName);\n Molecule *molecule_(NULL);\n bool success(false);\n if (info.suffix() == \"cml\") {\n Io::CmlFormat cml;\n molecule_ = new Molecule;\n success = cml.readFile(fileName.toStdString(), *molecule_);\n }\n else if (info.suffix() == \"cjson\") {\n Io::CjsonFormat cjson;\n molecule_ = new Molecule;\n success = cjson.readFile(fileName.toStdString(), *molecule_);\n }\n if (success) {\n m_recentFiles.prepend(fileName);\n updateRecentFiles();\n setMolecule(molecule_);\n statusBar()->showMessage(tr(\"Molecule loaded (%1 atoms, %2 bonds)\")\n .arg(molecule_->atomCount())\n .arg(molecule_->bondCount()), 2500);\n setWindowTitle(tr(\"Avogadro - %1\").arg(fileName));\n }\n else {\n statusBar()->showMessage(tr(\"Failed to read %1\").arg(fileName), 2500);\n delete molecule_;\n }\n}\n\nvoid MainWindow::openRecentFile()\n{\n QAction *action = qobject_cast<QAction *>(sender());\n if (action)\n openFile(action->data().toString());\n}\n\nvoid MainWindow::updateRecentFiles()\n{\n m_recentFiles.removeDuplicates();\n while (m_recentFiles.size() > 10)\n m_recentFiles.removeLast();\n\n \/\/ Populate the recent file actions list if necessary.\n if (m_actionRecentFiles.isEmpty()) {\n for (int i = 0; i < 10; ++i) {\n m_actionRecentFiles.push_back(m_ui->menuRecentFiles->addAction(\"\"));\n m_actionRecentFiles.back()->setVisible(false);\n connect(m_actionRecentFiles.back(), SIGNAL(triggered()),\n SLOT(openRecentFile()));\n }\n m_actionRecentFiles[0]->setText(tr(\"No recent files\"));\n m_actionRecentFiles[0]->setVisible(true);\n m_actionRecentFiles[0]->setEnabled(false);\n }\n int i = 0;\n foreach (const QString &file, m_recentFiles) {\n QFileInfo fileInfo(file);\n QAction *recentFile = m_actionRecentFiles[i++];\n recentFile->setText(fileInfo.fileName());\n recentFile->setData(file);\n recentFile->setVisible(true);\n recentFile->setEnabled(true);\n }\n for (; i < 10; ++i)\n m_actionRecentFiles[i]->setVisible(false);\n}\n\nvoid MainWindow::updateScenePlugins()\n{\n Rendering::Scene &scene = m_ui->glWidget->renderer().scene();\n scene.clear();\n if (m_molecule) {\n foreach (QtGui::ScenePlugin *scenePlugin,\n m_scenePluginModel->activeScenePlugins()) {\n scenePlugin->process(*m_molecule, scene);\n }\n }\n m_ui->glWidget->update();\n}\n\nvoid MainWindow::updateTool()\n{\n m_ui->glWidget->setActiveTool(static_cast<QtOpenGL::GLWidget::Tool>(\n m_ui->toolComboBox->currentIndex()));\n m_ui->elementComboBox->setEnabled(\n m_ui->glWidget->activeTool() == QtOpenGL::GLWidget::EditTool);\n}\n\nvoid MainWindow::updateElement()\n{\n m_ui->glWidget->editor().setAtomicNumber(\n m_elementLookup.at(m_ui->elementComboBox->currentIndex()));\n}\n\nvoid MainWindow::buildMenu(QtGui::ExtensionPlugin *extension)\n{\n foreach (QAction *action, extension->actions()) {\n QStringList path = extension->menuPath(action);\n qDebug() << \"Menu:\" << extension->name() << path;\n if (path.size() < 1)\n continue;\n \/\/ First ensure the top-level menu is present (create it if needed).\n QMenu *menu(NULL);\n foreach (QAction *topMenu, menuBar()->actions()) {\n if (topMenu->text() == path.at(0)) {\n menu = topMenu->menu();\n break;\n }\n }\n if (!menu)\n menu = menuBar()->addMenu(path.at(0));\n\n \/\/ Build up submenus if necessary.\n QMenu *nextMenu(NULL);\n for (int i = 1; i < path.size(); ++i) {\n if (nextMenu) {\n menu = nextMenu;\n nextMenu = NULL;\n }\n const QString menuText = path[i];\n foreach (QAction *menuAction, menu->actions()) {\n if (menuAction->text() == menuText) {\n nextMenu = menuAction->menu();\n break;\n }\n }\n if (!nextMenu)\n nextMenu = menu->addMenu(path.at(i));\n menu = nextMenu;\n nextMenu = NULL;\n }\n \/\/ Now we actually add the action we got (it should have set the text etc).\n menu->addAction(action);\n }\n\n}\n\nvoid MainWindow::buildElements()\n{\n m_ui->elementComboBox->clear();\n m_elementLookup.clear();\n\n \/\/ Add common elements to the top.\n addElement(1); \/\/ Hydrogen\n addElement(5); \/\/ Boron\n addElement(6); \/\/ Carbon\n addElement(7); \/\/ Nitrogen\n addElement(8); \/\/ Oxygen\n addElement(9); \/\/ Fluorine\n addElement(15); \/\/ Phosphorus\n addElement(16); \/\/ Sulfur\n addElement(17); \/\/ Chlorine\n addElement(35); \/\/ Bromine\n\n m_ui->elementComboBox->insertSeparator(m_ui->elementComboBox->count());\n\n \/\/ And the rest...\n for (unsigned char i = 1; i < Core::Elements::elementCount(); ++i)\n addElement(i);\n}\n\nvoid MainWindow::addElement(unsigned char atomicNum)\n{\n m_ui->elementComboBox->addItem(QString(\"%1 (%2)\")\n .arg(Core::Elements::name(atomicNum))\n .arg(QString::number(atomicNum)));\n m_elementLookup.push_back(atomicNum);\n}\n\n} \/\/ End of Avogadro namespace\n<commit_msg>Fix bug in editor atom-type lookup.<commit_after>\/******************************************************************************\n\n This source file is part of the Avogadro project.\n\n Copyright 2012 Kitware, Inc.\n\n This source code is released under the New BSD License, (the \"License\").\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n\n******************************************************************************\/\n\n#include \"mainwindow.h\"\n#include \"ui_mainwindow.h\"\n\n#include <avogadro\/qtgui\/molecule.h>\n#include <avogadro\/core\/elements.h>\n#include <avogadro\/io\/cmlformat.h>\n#include <avogadro\/io\/cjsonformat.h>\n#include <avogadro\/qtopengl\/editor.h>\n#include <avogadro\/qtopengl\/glwidget.h>\n#include <avogadro\/qtplugins\/pluginmanager.h>\n#include <avogadro\/qtgui\/sceneplugin.h>\n#include <avogadro\/qtgui\/scenepluginmodel.h>\n#include <avogadro\/qtgui\/extensionplugin.h>\n#include <avogadro\/rendering\/glrenderer.h>\n#include <avogadro\/rendering\/scene.h>\n\n#include <QtCore\/QCoreApplication>\n#include <QtCore\/QString>\n#include <QtCore\/QDebug>\n#include <QtCore\/QFileInfo>\n#include <QtCore\/QSettings>\n#include <QtGui\/QCloseEvent>\n#include <QtGui\/QMenu>\n#include <QtGui\/QMenuBar>\n#include <QtGui\/QFileDialog>\n#include <QtGui\/QStatusBar>\n#include <QtGui\/QToolBar>\n\n#include <QtGui\/QDockWidget>\n#include <QtGui\/QTreeView>\n#include <QtGui\/QHeaderView>\n\nnamespace Avogadro {\n\nusing QtGui::Molecule;\n\nMainWindow::MainWindow(const QString &fileName)\n : m_ui(new Ui::MainWindow),\n m_molecule(0),\n m_scenePluginModel(0)\n{\n m_ui->setupUi(this);\n\n QIcon icon(\":\/icons\/avogadro.png\");\n setWindowIcon(icon);\n\n \/\/ Create the scene plugin model\n m_scenePluginModel = new QtGui::ScenePluginModel(m_ui->scenePluginTreeView);\n m_ui->scenePluginTreeView->setModel(m_scenePluginModel);\n m_ui->scenePluginTreeView->setAlternatingRowColors(true);\n m_ui->scenePluginTreeView->header()->stretchLastSection();\n m_ui->scenePluginTreeView->header()->setVisible(false);\n connect(m_scenePluginModel,\n SIGNAL(pluginStateChanged(Avogadro::QtGui::ScenePlugin*)),\n SLOT(updateScenePlugins()));\n \/\/\/ @todo HACK the molecule should trigger the update\n connect(&m_ui->glWidget->editor(), SIGNAL(moleculeChanged()),\n SLOT(updateScenePlugins()));\n connect(&m_ui->glWidget->manipulator(), SIGNAL(moleculeChanged()),\n SLOT(updateScenePlugins()));\n\n \/\/ Connect the menu actions\n connect(m_ui->actionNewMolecule, SIGNAL(triggered()), SLOT(newMolecule()));\n connect(m_ui->actionOpen, SIGNAL(triggered()), SLOT(openFile()));\n connect(m_ui->actionQuit, SIGNAL(triggered()), qApp, SLOT(quit()));\n\n \/\/ Connect the temporary tool\/element selectors\n updateTool();\n buildElements();\n updateElement();\n connect(m_ui->toolComboBox, SIGNAL(currentIndexChanged(int)),\n SLOT(updateTool()));\n connect(m_ui->elementComboBox, SIGNAL(currentIndexChanged(int)),\n SLOT(updateElement()));\n\n readSettings();\n\n QtGui::PluginManager *plugin = QtGui::PluginManager::instance();\n plugin->load();\n QList<QtGui::ScenePluginFactory *> scenePluginFactories =\n plugin->pluginFactories<QtGui::ScenePluginFactory>();\n foreach (QtGui::ScenePluginFactory *factory, scenePluginFactories) {\n QtGui::ScenePlugin *scenePlugin = factory->createInstance();\n if (scenePlugin) {\n scenePlugin->setParent(this);\n m_scenePluginModel->addItem(scenePlugin);\n }\n }\n\n \/\/ Call this a second time, not needed but ensures plugins only load once.\n plugin->load();\n\n QList<QtGui::ExtensionPluginFactory *> extensions =\n plugin->pluginFactories<QtGui::ExtensionPluginFactory>();\n qDebug() << \"Extension plugins dynamically found...\" << extensions.size();\n foreach (QtGui::ExtensionPluginFactory *factory, extensions) {\n QtGui::ExtensionPlugin *extension = factory->createInstance();\n if (extension) {\n extension->setParent(this);\n qDebug() << \"extension:\" << extension->name() << extension->menuPath();\n connect(this, SIGNAL(moleculeChanged(QtGui::Molecule*)),\n extension, SLOT(setMolecule(QtGui::Molecule*)));\n connect(extension, SIGNAL(moleculeReady(int)), SLOT(moleculeReady(int)));\n buildMenu(extension);\n }\n }\n\n \/\/ try to open the file passed in. If opening fails, create a new molecule.\n openFile(fileName);\n if (!m_molecule)\n newMolecule();\n statusBar()->showMessage(tr(\"Ready...\"), 2000);\n}\n\nMainWindow::~MainWindow()\n{\n writeSettings();\n delete m_molecule;\n}\n\nvoid MainWindow::closeEvent(QCloseEvent *e)\n{\n writeSettings();\n QMainWindow::closeEvent(e);\n}\n\nvoid MainWindow::moleculeReady(int)\n{\n QtGui::ExtensionPlugin *extension =\n qobject_cast<QtGui::ExtensionPlugin *>(sender());\n if (extension) {\n QtGui::Molecule *mol = new QtGui::Molecule(this);\n if (extension->readMolecule(*mol))\n setMolecule(mol);\n }\n}\n\nvoid MainWindow::newMolecule()\n{\n setMolecule(new QtGui::Molecule);\n}\n\nvoid MainWindow::setMolecule(QtGui::Molecule *mol)\n{\n if (m_molecule == mol)\n return;\n\n \/\/ Clear the scene to prevent dangling identifiers:\n m_ui->glWidget->renderer().scene().clear();\n\n \/\/ Set molecule\n if (m_molecule)\n delete m_molecule;\n m_molecule = mol;\n\n emit moleculeChanged(m_molecule);\n\n connect(m_molecule, SIGNAL(changed(unsigned int)),\n SLOT(updateScenePlugins()));\n\n m_ui->glWidget->editor().setMolecule(mol);\n m_ui->glWidget->manipulator().setMolecule(mol);\n updateScenePlugins();\n m_ui->glWidget->resetCamera();\n}\n\nvoid MainWindow::writeSettings()\n{\n QSettings settings;\n settings.beginGroup(\"MainWindow\");\n settings.setValue(\"size\", size());\n settings.setValue(\"pos\", pos());\n settings.endGroup();\n settings.setValue(\"recentFiles\", m_recentFiles);\n}\n\nvoid MainWindow::readSettings()\n{\n QSettings settings;\n settings.beginGroup(\"MainWindow\");\n resize(settings.value(\"size\", QSize(400, 300)).toSize());\n move(settings.value(\"pos\", QPoint(20, 20)).toPoint());\n settings.endGroup();\n m_recentFiles = settings.value(\"recentFiles\", QStringList()).toStringList();\n updateRecentFiles();\n}\n\nvoid MainWindow::openFile()\n{\n QString fileName = QFileDialog::getOpenFileName(this, tr(\"Open chemical file\"),\n \"\", tr(\"Chemical files (*.cml *.cjson)\"));\n openFile(fileName);\n}\n\nvoid MainWindow::openFile(const QString &fileName)\n{\n if (fileName.isEmpty())\n return;\n\n QFileInfo info(fileName);\n Molecule *molecule_(NULL);\n bool success(false);\n if (info.suffix() == \"cml\") {\n Io::CmlFormat cml;\n molecule_ = new Molecule;\n success = cml.readFile(fileName.toStdString(), *molecule_);\n }\n else if (info.suffix() == \"cjson\") {\n Io::CjsonFormat cjson;\n molecule_ = new Molecule;\n success = cjson.readFile(fileName.toStdString(), *molecule_);\n }\n if (success) {\n m_recentFiles.prepend(fileName);\n updateRecentFiles();\n setMolecule(molecule_);\n statusBar()->showMessage(tr(\"Molecule loaded (%1 atoms, %2 bonds)\")\n .arg(molecule_->atomCount())\n .arg(molecule_->bondCount()), 2500);\n setWindowTitle(tr(\"Avogadro - %1\").arg(fileName));\n }\n else {\n statusBar()->showMessage(tr(\"Failed to read %1\").arg(fileName), 2500);\n delete molecule_;\n }\n}\n\nvoid MainWindow::openRecentFile()\n{\n QAction *action = qobject_cast<QAction *>(sender());\n if (action)\n openFile(action->data().toString());\n}\n\nvoid MainWindow::updateRecentFiles()\n{\n m_recentFiles.removeDuplicates();\n while (m_recentFiles.size() > 10)\n m_recentFiles.removeLast();\n\n \/\/ Populate the recent file actions list if necessary.\n if (m_actionRecentFiles.isEmpty()) {\n for (int i = 0; i < 10; ++i) {\n m_actionRecentFiles.push_back(m_ui->menuRecentFiles->addAction(\"\"));\n m_actionRecentFiles.back()->setVisible(false);\n connect(m_actionRecentFiles.back(), SIGNAL(triggered()),\n SLOT(openRecentFile()));\n }\n m_actionRecentFiles[0]->setText(tr(\"No recent files\"));\n m_actionRecentFiles[0]->setVisible(true);\n m_actionRecentFiles[0]->setEnabled(false);\n }\n int i = 0;\n foreach (const QString &file, m_recentFiles) {\n QFileInfo fileInfo(file);\n QAction *recentFile = m_actionRecentFiles[i++];\n recentFile->setText(fileInfo.fileName());\n recentFile->setData(file);\n recentFile->setVisible(true);\n recentFile->setEnabled(true);\n }\n for (; i < 10; ++i)\n m_actionRecentFiles[i]->setVisible(false);\n}\n\nvoid MainWindow::updateScenePlugins()\n{\n Rendering::Scene &scene = m_ui->glWidget->renderer().scene();\n scene.clear();\n if (m_molecule) {\n foreach (QtGui::ScenePlugin *scenePlugin,\n m_scenePluginModel->activeScenePlugins()) {\n scenePlugin->process(*m_molecule, scene);\n }\n }\n m_ui->glWidget->update();\n}\n\nvoid MainWindow::updateTool()\n{\n m_ui->glWidget->setActiveTool(static_cast<QtOpenGL::GLWidget::Tool>(\n m_ui->toolComboBox->currentIndex()));\n m_ui->elementComboBox->setEnabled(\n m_ui->glWidget->activeTool() == QtOpenGL::GLWidget::EditTool);\n}\n\nvoid MainWindow::updateElement()\n{\n m_ui->glWidget->editor().setAtomicNumber(\n m_elementLookup.at(m_ui->elementComboBox->currentIndex()));\n}\n\nvoid MainWindow::buildMenu(QtGui::ExtensionPlugin *extension)\n{\n foreach (QAction *action, extension->actions()) {\n QStringList path = extension->menuPath(action);\n qDebug() << \"Menu:\" << extension->name() << path;\n if (path.size() < 1)\n continue;\n \/\/ First ensure the top-level menu is present (create it if needed).\n QMenu *menu(NULL);\n foreach (QAction *topMenu, menuBar()->actions()) {\n if (topMenu->text() == path.at(0)) {\n menu = topMenu->menu();\n break;\n }\n }\n if (!menu)\n menu = menuBar()->addMenu(path.at(0));\n\n \/\/ Build up submenus if necessary.\n QMenu *nextMenu(NULL);\n for (int i = 1; i < path.size(); ++i) {\n if (nextMenu) {\n menu = nextMenu;\n nextMenu = NULL;\n }\n const QString menuText = path[i];\n foreach (QAction *menuAction, menu->actions()) {\n if (menuAction->text() == menuText) {\n nextMenu = menuAction->menu();\n break;\n }\n }\n if (!nextMenu)\n nextMenu = menu->addMenu(path.at(i));\n menu = nextMenu;\n nextMenu = NULL;\n }\n \/\/ Now we actually add the action we got (it should have set the text etc).\n menu->addAction(action);\n }\n\n}\n\nvoid MainWindow::buildElements()\n{\n m_ui->elementComboBox->clear();\n m_elementLookup.clear();\n\n \/\/ Add common elements to the top.\n addElement(1); \/\/ Hydrogen\n addElement(5); \/\/ Boron\n addElement(6); \/\/ Carbon\n addElement(7); \/\/ Nitrogen\n addElement(8); \/\/ Oxygen\n addElement(9); \/\/ Fluorine\n addElement(15); \/\/ Phosphorus\n addElement(16); \/\/ Sulfur\n addElement(17); \/\/ Chlorine\n addElement(35); \/\/ Bromine\n\n m_ui->elementComboBox->insertSeparator(m_ui->elementComboBox->count());\n m_elementLookup.push_back(0); \/\/ for the separator\n\n \/\/ And the rest...\n for (unsigned char i = 1; i < Core::Elements::elementCount(); ++i)\n addElement(i);\n}\n\nvoid MainWindow::addElement(unsigned char atomicNum)\n{\n m_ui->elementComboBox->addItem(QString(\"%1 (%2)\")\n .arg(Core::Elements::name(atomicNum))\n .arg(QString::number(atomicNum)));\n m_elementLookup.push_back(atomicNum);\n}\n\n} \/\/ End of Avogadro namespace\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2015, Galaxy Authors. All Rights Reserved\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\/\/\n\/\/ Author: wangtaize@baidu.com\n\n#include \"agent\/task_manager.h\"\n\n#include \"common\/logging.h\"\n#include \"agent\/cgroup.h\"\n\nextern std::string FLAGS_container;\nnamespace galaxy {\nint TaskManager::Add(const ::galaxy::TaskInfo& task_info,\n DefaultWorkspace * workspace) {\n MutexLock lock(m_mutex);\n LOG(INFO, \"add task with id %d\", task_info.task_id());\n if (m_task_runner_map.find(task_info.task_id()) != m_task_runner_map.end()) {\n LOG(WARNING, \"task with id %d has exist\", task_info.task_id());\n return 0;\n }\n \/\/ do download\n\n TaskRunner* runner = NULL;\n if(FLAGS_container.compare(\"cgroup\") == 0){\n LOG(INFO,\"use cgroup task runner for task %d\",task_info.task_id());\n runner = new ContainerTaskRunner(task_info,\"\/cgroup\", workspace);\n }else{\n LOG(INFO,\"use command task runner for task %d\",task_info.task_id());\n runner = new CommandTaskRunner(task_info,workspace);\n }\n int ret = runner->Prepare();\n if(ret != 0 ){\n LOG(INFO,\"fail to prepare runner ,ret is %d\",ret);\n return ret;\n }\n m_task_runner_map[task_info.task_id()] = runner;\n \/\/ret = runner->Start();\n \/\/if (ret == 0) {\n \/\/ LOG(INFO, \"add task with id %d successfully\", task_info.task_id());\n \/\/ m_task_runner_map[task_info.task_id()] = runner;\n \/\/} else {\n \/\/ LOG(FATAL, \"fail to add task with %d\", task_info.task_id());\n \/\/}\n return ret;\n}\n\nint TaskManager::Remove(const int64_t& task_info_id) {\n MutexLock lock(m_mutex);\n if (m_task_runner_map.find(task_info_id) == m_task_runner_map.end()) {\n LOG(WARNING, \"task with id %d does not exist\", task_info_id);\n return 0;\n }\n TaskRunner* runner = m_task_runner_map[task_info_id];\n if(NULL == runner){\n return 0;\n }\n int status = runner->Stop();\n if(status == 0){\n LOG(INFO,\"stop task %d successfully\",task_info_id);\n }\n m_task_runner_map.erase(task_info_id);\n delete runner;\n return status;\n}\n\nint TaskManager::Status(std::vector< TaskStatus >& task_status_vector) {\n MutexLock lock(m_mutex);\n std::map<int64_t, TaskRunner*>::iterator it = m_task_runner_map.begin();\n for (; it != m_task_runner_map.end(); ++it) {\n TaskStatus status;\n status.set_task_id(it->first);\n int ret = it->second->IsRunning();\n if(ret == 0){\n status.set_status(RUNNING);\n }else if(ret == 1){\n status.set_status(COMPLETE);\n Remove(it->first);\n }else{\n if (it->second->ReStart() == 0) {\n status.set_status(RESTART);\n } else {\n \/\/ if restart failed,\n \/\/ 1. retry times more than limit, no need retry any more.\n \/\/ 2. stop failed\n \/\/ 3. start failed\n status.set_status(ERROR);\n }\n }\n\n task_status_vector.push_back(status);\n }\n return 0;\n}\n}\n\n\n\n<commit_msg>remove Remove Functiont<commit_after>\/\/ Copyright (c) 2015, Galaxy Authors. All Rights Reserved\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\/\/\n\/\/ Author: wangtaize@baidu.com\n\n#include \"agent\/task_manager.h\"\n\n#include \"common\/logging.h\"\n#include \"agent\/cgroup.h\"\n\nextern std::string FLAGS_container;\nnamespace galaxy {\nint TaskManager::Add(const ::galaxy::TaskInfo& task_info,\n DefaultWorkspace * workspace) {\n MutexLock lock(m_mutex);\n LOG(INFO, \"add task with id %d\", task_info.task_id());\n if (m_task_runner_map.find(task_info.task_id()) != m_task_runner_map.end()) {\n LOG(WARNING, \"task with id %d has exist\", task_info.task_id());\n return 0;\n }\n \/\/ do download\n\n TaskRunner* runner = NULL;\n if(FLAGS_container.compare(\"cgroup\") == 0){\n LOG(INFO,\"use cgroup task runner for task %d\",task_info.task_id());\n runner = new ContainerTaskRunner(task_info,\"\/cgroup\", workspace);\n }else{\n LOG(INFO,\"use command task runner for task %d\",task_info.task_id());\n runner = new CommandTaskRunner(task_info,workspace);\n }\n int ret = runner->Prepare();\n if(ret != 0 ){\n LOG(INFO,\"fail to prepare runner ,ret is %d\",ret);\n return ret;\n }\n m_task_runner_map[task_info.task_id()] = runner;\n \/\/ret = runner->Start();\n \/\/if (ret == 0) {\n \/\/ LOG(INFO, \"add task with id %d successfully\", task_info.task_id());\n \/\/ m_task_runner_map[task_info.task_id()] = runner;\n \/\/} else {\n \/\/ LOG(FATAL, \"fail to add task with %d\", task_info.task_id());\n \/\/}\n return ret;\n}\n\nint TaskManager::Remove(const int64_t& task_info_id) {\n MutexLock lock(m_mutex);\n if (m_task_runner_map.find(task_info_id) == m_task_runner_map.end()) {\n LOG(WARNING, \"task with id %d does not exist\", task_info_id);\n return 0;\n }\n TaskRunner* runner = m_task_runner_map[task_info_id];\n if(NULL == runner){\n return 0;\n }\n int status = runner->Stop();\n if(status == 0){\n LOG(INFO,\"stop task %d successfully\",task_info_id);\n }\n m_task_runner_map.erase(task_info_id);\n delete runner;\n return status;\n}\n\nint TaskManager::Status(std::vector< TaskStatus >& task_status_vector) {\n MutexLock lock(m_mutex);\n std::map<int64_t, TaskRunner*>::iterator it = m_task_runner_map.begin();\n for (; it != m_task_runner_map.end(); ++it) {\n TaskStatus status;\n status.set_task_id(it->first);\n int ret = it->second->IsRunning();\n if(ret == 0){\n status.set_status(RUNNING);\n }else if(ret == 1){\n status.set_status(COMPLETE);\n }else{\n if (it->second->ReStart() == 0) {\n status.set_status(RESTART);\n } else {\n \/\/ if restart failed,\n \/\/ 1. retry times more than limit, no need retry any more.\n \/\/ 2. stop failed\n \/\/ 3. start failed\n status.set_status(ERROR);\n }\n }\n\n task_status_vector.push_back(status);\n }\n return 0;\n}\n}\n\n\n\n<|endoftext|>"} {"text":"<commit_before>\/\/\/\n\/\/\/ @file calculator.hpp\n\/\/\/ @brief calculator::eval(const std::string&) evaluates an integer\n\/\/\/ arithmetic expression and returns the result. If an error\n\/\/\/ occurs a calculator::error exception is thrown.\n\/\/\/ <https:\/\/github.com\/kimwalisch\/calculator>\n\/\/\/ @author Kim Walisch, <kim.walisch@gmail.com>\n\/\/\/ @copyright Copyright (C) 2013-2018 Kim Walisch\n\/\/\/ @license BSD 2-Clause, https:\/\/opensource.org\/licenses\/BSD-2-Clause\n\/\/\/ @version 1.2 patched: `^' is raise to power instead of XOR.\n\/\/\/\n\/\/\/ == Supported operators ==\n\/\/\/\n\/\/\/ OPERATOR NAME ASSOCIATIVITY PRECEDENCE\n\/\/\/\n\/\/\/ | Bitwise Inclusive OR Left 4\n\/\/\/ & Bitwise AND Left 6\n\/\/\/ << Shift Left Left 9\n\/\/\/ >> Shift Right Left 9\n\/\/\/ + Addition Left 10\n\/\/\/ - Subtraction Left 10\n\/\/\/ * Multiplication Left 20\n\/\/\/ \/ Division Left 20\n\/\/\/ % Modulo Left 20\n\/\/\/ ^, ** Raise to power Right 30\n\/\/\/ e, E Scientific notation Right 40\n\/\/\/ ~ Unary complement Left 99\n\/\/\/\n\/\/\/ The operator precedence has been set according to (uses the C and\n\/\/\/ C++ operator precedence): https:\/\/en.wikipedia.org\/wiki\/Order_of_operations\n\/\/\/ Operators with higher precedence are evaluated before operators\n\/\/\/ with relatively lower precedence. Unary operators are set to have\n\/\/\/ the highest precedence, this is not strictly correct for the power\n\/\/\/ operator e.g. \"-3**2\" = 9 but a lot of software tools (Bash shell,\n\/\/\/ Microsoft Excel, GNU bc, ...) use the same convention.\n\/\/\/\n\/\/\/ == Examples of valid expressions ==\n\/\/\/\n\/\/\/ \"65536 >> 15\" = 2\n\/\/\/ \"2**16\" = 65536\n\/\/\/ \"(0 + 0xDf234 - 1000)*3\/2%999\" = 828\n\/\/\/ \"-(2**2**2**2)\" = -65536\n\/\/\/ \"(0 + ~(0xDF234 & 1000) *3) \/-2\" = 817\n\/\/\/ \"(2**16) + (1 << 16) >> 0X5\" = 4096\n\/\/\/ \"5*-(2**(9+7))\/3+5*(1 & 0xFf123)\" = -109221\n\/\/\/\n\/\/\/ == About the algorithm used ==\n\/\/\/\n\/\/\/ calculator::eval(std::string&) relies on the ExpressionParser\n\/\/\/ class which is a simple C++ operator precedence parser with infix\n\/\/\/ notation for integer arithmetic expressions.\n\/\/\/ ExpressionParser has its roots in a JavaScript parser published\n\/\/\/ at: http:\/\/stackoverflow.com\/questions\/28256\/equation-expression-parser-with-precedence\/114961#114961\n\/\/\/ The same author has also published an article about his operator\n\/\/\/ precedence algorithm at PerlMonks:\n\/\/\/ http:\/\/www.perlmonks.org\/?node_id=554516\n\/\/\/\n\n#ifndef CALCULATOR_HPP\n#define CALCULATOR_HPP\n\n#include <stdexcept>\n#include <string>\n#include <sstream>\n#include <stack>\n#include <cstddef>\n#include <cctype>\n\nnamespace calculator\n{\n\n\/\/\/ calculator::eval() throws a calculator::error if it fails\n\/\/\/ to evaluate the expression string.\n\/\/\/\nclass error : public std::runtime_error\n{\npublic:\n error(const std::string& expr, const std::string& message)\n : std::runtime_error(message),\n expr_(expr)\n { }\n#if __cplusplus >= 201103L\n ~error() { }\n#else\n ~error() throw() { }\n#endif\n std::string expression() const\n {\n return expr_;\n }\nprivate:\n std::string expr_;\n};\n\ntemplate <typename T>\nclass ExpressionParser\n{\npublic:\n \/\/\/ Evaluate an integer arithmetic expression and return its result.\n \/\/\/ @throw error if parsing fails.\n \/\/\/\n T eval(const std::string& expr)\n {\n T result = 0;\n index_ = 0;\n expr_ = expr;\n try\n {\n result = parseExpr();\n if (!isEnd())\n unexpected();\n }\n catch (const calculator::error&)\n {\n while(!stack_.empty())\n stack_.pop();\n throw;\n }\n return result;\n }\n\n \/\/\/ Get the integer value of a character.\n T eval(char c)\n {\n std::string expr(1, c);\n return eval(expr);\n }\n\nprivate:\n enum\n {\n OPERATOR_NULL,\n OPERATOR_BITWISE_OR, \/\/\/ |\n OPERATOR_BITWISE_XOR, \/\/\/ ^\n OPERATOR_BITWISE_AND, \/\/\/ &\n OPERATOR_BITWISE_SHL, \/\/\/ <<\n OPERATOR_BITWISE_SHR, \/\/\/ >>\n OPERATOR_ADDITION, \/\/\/ +\n OPERATOR_SUBTRACTION, \/\/\/ -\n OPERATOR_MULTIPLICATION, \/\/\/ *\n OPERATOR_DIVISION, \/\/\/ \/\n OPERATOR_MODULO, \/\/\/ %\n OPERATOR_POWER, \/\/\/ **\n OPERATOR_EXPONENT \/\/\/ e, E\n };\n\n struct Operator\n {\n \/\/\/ Operator, one of the OPERATOR_* enum definitions\n int op;\n int precedence;\n \/\/\/ 'L' = left or 'R' = right\n int associativity;\n Operator(int opr, int prec, int assoc) :\n op(opr),\n precedence(prec),\n associativity(assoc)\n { }\n };\n\n struct OperatorValue\n {\n Operator op;\n T value;\n OperatorValue(const Operator& opr, T val) :\n op(opr),\n value(val)\n { }\n int getPrecedence() const\n {\n return op.precedence;\n }\n bool isNull() const\n {\n return op.op == OPERATOR_NULL;\n }\n };\n\n \/\/\/ Expression string\n std::string expr_;\n \/\/\/ Current expression index, incremented whilst parsing\n std::size_t index_;\n \/\/\/ The current operator and its left value\n \/\/\/ are pushed onto the stack if the operator on\n \/\/\/ top of the stack has lower precedence.\n std::stack<OperatorValue> stack_;\n\n \/\/\/ Exponentiation by squaring, x^n.\n static T pow(T x, T n)\n {\n T res = 1;\n\n while (n > 0)\n {\n if (n % 2 != 0)\n {\n res *= x;\n n -= 1;\n }\n n \/= 2;\n\n if (n > 0)\n x *= x;\n }\n\n return res;\n }\n\n T checkZero(T value) const\n {\n if (value == 0)\n {\n std::string divOperators(\"\/%\");\n std::size_t division = expr_.find_last_of(divOperators, index_ - 2);\n std::ostringstream msg;\n msg << \"Parser error: division by 0\";\n if (division != std::string::npos)\n msg << \" (error token is \\\"\"\n << expr_.substr(division, expr_.size() - division)\n << \"\\\")\";\n throw calculator::error(expr_, msg.str());\n }\n return value;\n }\n\n T calculate(T v1, T v2, const Operator& op) const\n {\n switch (op.op)\n {\n case OPERATOR_BITWISE_OR: return v1 | v2;\n case OPERATOR_BITWISE_XOR: return v1 ^ v2;\n case OPERATOR_BITWISE_AND: return v1 & v2;\n case OPERATOR_BITWISE_SHL: return v1 << v2;\n case OPERATOR_BITWISE_SHR: return v1 >> v2;\n case OPERATOR_ADDITION: return v1 + v2;\n case OPERATOR_SUBTRACTION: return v1 - v2;\n case OPERATOR_MULTIPLICATION: return v1 * v2;\n case OPERATOR_DIVISION: return v1 \/ checkZero(v2);\n case OPERATOR_MODULO: return v1 % checkZero(v2);\n case OPERATOR_POWER: return pow(v1, v2);\n case OPERATOR_EXPONENT: return v1 * pow(10, v2);\n default: return 0;\n }\n }\n\n bool isEnd() const\n {\n return index_ >= expr_.size();\n }\n\n \/\/\/ Returns the character at the current expression index or\n \/\/\/ 0 if the end of the expression is reached.\n \/\/\/\n char getCharacter() const\n {\n if (!isEnd())\n return expr_[index_];\n return 0;\n }\n\n \/\/\/ Parse str at the current expression index.\n \/\/\/ @throw error if parsing fails.\n \/\/\/\n void expect(const std::string& str)\n {\n if (expr_.compare(index_, str.size(), str) != 0)\n unexpected();\n index_ += str.size();\n }\n\n void unexpected() const\n {\n std::ostringstream msg;\n msg << \"Syntax error: unexpected token \\\"\"\n << expr_.substr(index_, expr_.size() - index_)\n << \"\\\" at index \"\n << index_;\n throw calculator::error(expr_, msg.str());\n }\n\n \/\/\/ Eat all white space characters at the\n \/\/\/ current expression index.\n \/\/\/\n void eatSpaces()\n {\n while (std::isspace(getCharacter()) != 0)\n index_++;\n }\n\n \/\/\/ Parse a binary operator at the current expression index.\n \/\/\/ @return Operator with precedence and associativity.\n \/\/\/\n Operator parseOp()\n {\n eatSpaces();\n switch (getCharacter())\n {\n case '|': index_++; return Operator(OPERATOR_BITWISE_OR, 4, 'L');\n case '&': index_++; return Operator(OPERATOR_BITWISE_AND, 6, 'L');\n case '<': expect(\"<<\"); return Operator(OPERATOR_BITWISE_SHL, 9, 'L');\n case '>': expect(\">>\"); return Operator(OPERATOR_BITWISE_SHR, 9, 'L');\n case '+': index_++; return Operator(OPERATOR_ADDITION, 10, 'L');\n case '-': index_++; return Operator(OPERATOR_SUBTRACTION, 10, 'L');\n case '\/': index_++; return Operator(OPERATOR_DIVISION, 20, 'L');\n case '%': index_++; return Operator(OPERATOR_MODULO, 20, 'L');\n case '*': index_++; if (getCharacter() != '*')\n return Operator(OPERATOR_MULTIPLICATION, 20, 'L');\n index_++; return Operator(OPERATOR_POWER, 30, 'R');\n case '^': index_++; return Operator(OPERATOR_POWER, 30, 'R');\n case 'e': index_++; return Operator(OPERATOR_EXPONENT, 40, 'R');\n case 'E': index_++; return Operator(OPERATOR_EXPONENT, 40, 'R');\n default : return Operator(OPERATOR_NULL, 0, 'L');\n }\n }\n\n static T toInteger(char c)\n {\n if (c >= '0' && c <= '9') return c -'0';\n if (c >= 'a' && c <= 'f') return c -'a' + 0xa;\n if (c >= 'A' && c <= 'F') return c -'A' + 0xa;\n T noDigit = 0xf + 1;\n return noDigit;\n }\n\n T getInteger() const\n {\n return toInteger(getCharacter());\n }\n\n T parseDecimal()\n {\n T value = 0;\n for (T d; (d = getInteger()) <= 9; index_++)\n value = value * 10 + d;\n return value;\n }\n\n T parseHex()\n {\n index_ = index_ + 2;\n T value = 0;\n for (T h; (h = getInteger()) <= 0xf; index_++)\n value = value * 0x10 + h;\n return value;\n }\n\n bool isHex() const\n {\n if (index_ + 2 < expr_.size())\n {\n char x = expr_[index_ + 1];\n char h = expr_[index_ + 2];\n return (std::tolower(x) == 'x' && toInteger(h) <= 0xf);\n }\n return false;\n }\n\n \/\/\/ Parse an integer value at the current expression index.\n \/\/\/ The unary `+', `-' and `~' operators and opening\n \/\/\/ parentheses `(' cause recursion.\n \/\/\/\n T parseValue()\n {\n T val = 0;\n eatSpaces();\n switch (getCharacter())\n {\n case '0': if (isHex())\n val = parseHex();\n else\n val = parseDecimal();\n break;\n case '1': case '2': case '3': case '4': case '5':\n case '6': case '7': case '8': case '9':\n val = parseDecimal();\n break;\n case '(': index_++;\n val = parseExpr();\n eatSpaces();\n if (getCharacter() != ')')\n {\n if (!isEnd())\n unexpected();\n throw calculator::error(expr_, \"Syntax error: `)' expected at end of expression\");\n }\n index_++; break;\n case '~': index_++; val = ~parseValue(); break;\n case '+': index_++; val = parseValue(); break;\n case '-': index_++; val = parseValue() * static_cast<T>(-1);\n break;\n default : if (!isEnd())\n unexpected();\n throw calculator::error(expr_, \"Syntax error: value expected at end of expression\");\n }\n return val;\n }\n\n \/\/\/ Parse all operations of the current parenthesis\n \/\/\/ level and the levels above, when done\n \/\/\/ return the result (value).\n \/\/\/\n T parseExpr()\n {\n stack_.push(OperatorValue(Operator(OPERATOR_NULL, 0, 'L'), 0));\n \/\/ first parse value on the left\n T value = parseValue();\n\n while (!stack_.empty())\n {\n \/\/ parse an operator (+, -, *, ...)\n Operator op(parseOp());\n while (op.precedence < stack_.top().getPrecedence() || (\n op.precedence == stack_.top().getPrecedence() &&\n op.associativity == 'L'))\n {\n \/\/ end reached\n if (stack_.top().isNull())\n {\n stack_.pop();\n return value;\n }\n \/\/ do the calculation (\"reduce\"), producing a new value\n value = calculate(stack_.top().value, value, stack_.top().op);\n stack_.pop();\n }\n\n \/\/ store on stack_ and continue parsing (\"shift\")\n stack_.push(OperatorValue(op, value));\n \/\/ parse value on the right\n value = parseValue();\n }\n return 0;\n }\n};\n\ntemplate <typename T>\ninline T eval(const std::string& expression)\n{\n ExpressionParser<T> parser;\n return parser.eval(expression);\n}\n\ntemplate <typename T>\ninline T eval(char c)\n{\n ExpressionParser<T> parser;\n return parser.eval(c);\n}\n\ninline int eval(const std::string& expression)\n{\n return eval<int>(expression);\n}\n\ninline int eval(char c)\n{\n return eval<int>(c);\n}\n\n} \/\/ namespace calculator\n\n#endif\n<commit_msg>Workaround for MSVC bug<commit_after>\/\/\/\n\/\/\/ @file calculator.hpp\n\/\/\/ @brief calculator::eval(const std::string&) evaluates an integer\n\/\/\/ arithmetic expression and returns the result. If an error\n\/\/\/ occurs a calculator::error exception is thrown.\n\/\/\/ <https:\/\/github.com\/kimwalisch\/calculator>\n\/\/\/ @author Kim Walisch, <kim.walisch@gmail.com>\n\/\/\/ @copyright Copyright (C) 2013-2018 Kim Walisch\n\/\/\/ @license BSD 2-Clause, https:\/\/opensource.org\/licenses\/BSD-2-Clause\n\/\/\/ @version 1.3 patched: `^' is raise to power instead of XOR.\n\/\/\/\n\/\/\/ == Supported operators ==\n\/\/\/\n\/\/\/ OPERATOR NAME ASSOCIATIVITY PRECEDENCE\n\/\/\/\n\/\/\/ | Bitwise Inclusive OR Left 4\n\/\/\/ & Bitwise AND Left 6\n\/\/\/ << Shift Left Left 9\n\/\/\/ >> Shift Right Left 9\n\/\/\/ + Addition Left 10\n\/\/\/ - Subtraction Left 10\n\/\/\/ * Multiplication Left 20\n\/\/\/ \/ Division Left 20\n\/\/\/ % Modulo Left 20\n\/\/\/ ^, ** Raise to power Right 30\n\/\/\/ e, E Scientific notation Right 40\n\/\/\/ ~ Unary complement Left 99\n\/\/\/\n\/\/\/ The operator precedence has been set according to (uses the C and\n\/\/\/ C++ operator precedence): https:\/\/en.wikipedia.org\/wiki\/Order_of_operations\n\/\/\/ Operators with higher precedence are evaluated before operators\n\/\/\/ with relatively lower precedence. Unary operators are set to have\n\/\/\/ the highest precedence, this is not strictly correct for the power\n\/\/\/ operator e.g. \"-3**2\" = 9 but a lot of software tools (Bash shell,\n\/\/\/ Microsoft Excel, GNU bc, ...) use the same convention.\n\/\/\/\n\/\/\/ == Examples of valid expressions ==\n\/\/\/\n\/\/\/ \"65536 >> 15\" = 2\n\/\/\/ \"2**16\" = 65536\n\/\/\/ \"(0 + 0xDf234 - 1000)*3\/2%999\" = 828\n\/\/\/ \"-(2**2**2**2)\" = -65536\n\/\/\/ \"(0 + ~(0xDF234 & 1000) *3) \/-2\" = 817\n\/\/\/ \"(2**16) + (1 << 16) >> 0X5\" = 4096\n\/\/\/ \"5*-(2**(9+7))\/3+5*(1 & 0xFf123)\" = -109221\n\/\/\/\n\/\/\/ == About the algorithm used ==\n\/\/\/\n\/\/\/ calculator::eval(std::string&) relies on the ExpressionParser\n\/\/\/ class which is a simple C++ operator precedence parser with infix\n\/\/\/ notation for integer arithmetic expressions.\n\/\/\/ ExpressionParser has its roots in a JavaScript parser published\n\/\/\/ at: http:\/\/stackoverflow.com\/questions\/28256\/equation-expression-parser-with-precedence\/114961#114961\n\/\/\/ The same author has also published an article about his operator\n\/\/\/ precedence algorithm at PerlMonks:\n\/\/\/ http:\/\/www.perlmonks.org\/?node_id=554516\n\/\/\/\n\n#ifndef CALCULATOR_HPP\n#define CALCULATOR_HPP\n\n#include <stdexcept>\n#include <string>\n#include <sstream>\n#include <stack>\n#include <cstddef>\n#include <cctype>\n\nnamespace calculator\n{\n\n\/\/\/ calculator::eval() throws a calculator::error if it fails\n\/\/\/ to evaluate the expression string.\n\/\/\/\nclass error : public std::runtime_error\n{\npublic:\n error(const std::string& expr, const std::string& message)\n : std::runtime_error(message),\n expr_(expr)\n { }\n#if __cplusplus >= 201103L || \\\n (defined(_MSC_VER) && _MSC_VER >= 1800)\n ~error() { }\n#else\n ~error() throw() { }\n#endif\n std::string expression() const\n {\n return expr_;\n }\nprivate:\n std::string expr_;\n};\n\ntemplate <typename T>\nclass ExpressionParser\n{\npublic:\n \/\/\/ Evaluate an integer arithmetic expression and return its result.\n \/\/\/ @throw error if parsing fails.\n \/\/\/\n T eval(const std::string& expr)\n {\n T result = 0;\n index_ = 0;\n expr_ = expr;\n try\n {\n result = parseExpr();\n if (!isEnd())\n unexpected();\n }\n catch (const calculator::error&)\n {\n while(!stack_.empty())\n stack_.pop();\n throw;\n }\n return result;\n }\n\n \/\/\/ Get the integer value of a character.\n T eval(char c)\n {\n std::string expr(1, c);\n return eval(expr);\n }\n\nprivate:\n enum\n {\n OPERATOR_NULL,\n OPERATOR_BITWISE_OR, \/\/\/ |\n OPERATOR_BITWISE_XOR, \/\/\/ ^\n OPERATOR_BITWISE_AND, \/\/\/ &\n OPERATOR_BITWISE_SHL, \/\/\/ <<\n OPERATOR_BITWISE_SHR, \/\/\/ >>\n OPERATOR_ADDITION, \/\/\/ +\n OPERATOR_SUBTRACTION, \/\/\/ -\n OPERATOR_MULTIPLICATION, \/\/\/ *\n OPERATOR_DIVISION, \/\/\/ \/\n OPERATOR_MODULO, \/\/\/ %\n OPERATOR_POWER, \/\/\/ **\n OPERATOR_EXPONENT \/\/\/ e, E\n };\n\n struct Operator\n {\n \/\/\/ Operator, one of the OPERATOR_* enum definitions\n int op;\n int precedence;\n \/\/\/ 'L' = left or 'R' = right\n int associativity;\n Operator(int opr, int prec, int assoc) :\n op(opr),\n precedence(prec),\n associativity(assoc)\n { }\n };\n\n struct OperatorValue\n {\n Operator op;\n T value;\n OperatorValue(const Operator& opr, T val) :\n op(opr),\n value(val)\n { }\n int getPrecedence() const\n {\n return op.precedence;\n }\n bool isNull() const\n {\n return op.op == OPERATOR_NULL;\n }\n };\n\n \/\/\/ Expression string\n std::string expr_;\n \/\/\/ Current expression index, incremented whilst parsing\n std::size_t index_;\n \/\/\/ The current operator and its left value\n \/\/\/ are pushed onto the stack if the operator on\n \/\/\/ top of the stack has lower precedence.\n std::stack<OperatorValue> stack_;\n\n \/\/\/ Exponentiation by squaring, x^n.\n static T pow(T x, T n)\n {\n T res = 1;\n\n while (n > 0)\n {\n if (n % 2 != 0)\n {\n res *= x;\n n -= 1;\n }\n n \/= 2;\n\n if (n > 0)\n x *= x;\n }\n\n return res;\n }\n\n T checkZero(T value) const\n {\n if (value == 0)\n {\n std::string divOperators(\"\/%\");\n std::size_t division = expr_.find_last_of(divOperators, index_ - 2);\n std::ostringstream msg;\n msg << \"Parser error: division by 0\";\n if (division != std::string::npos)\n msg << \" (error token is \\\"\"\n << expr_.substr(division, expr_.size() - division)\n << \"\\\")\";\n throw calculator::error(expr_, msg.str());\n }\n return value;\n }\n\n T calculate(T v1, T v2, const Operator& op) const\n {\n switch (op.op)\n {\n case OPERATOR_BITWISE_OR: return v1 | v2;\n case OPERATOR_BITWISE_XOR: return v1 ^ v2;\n case OPERATOR_BITWISE_AND: return v1 & v2;\n case OPERATOR_BITWISE_SHL: return v1 << v2;\n case OPERATOR_BITWISE_SHR: return v1 >> v2;\n case OPERATOR_ADDITION: return v1 + v2;\n case OPERATOR_SUBTRACTION: return v1 - v2;\n case OPERATOR_MULTIPLICATION: return v1 * v2;\n case OPERATOR_DIVISION: return v1 \/ checkZero(v2);\n case OPERATOR_MODULO: return v1 % checkZero(v2);\n case OPERATOR_POWER: return pow(v1, v2);\n case OPERATOR_EXPONENT: return v1 * pow(10, v2);\n default: return 0;\n }\n }\n\n bool isEnd() const\n {\n return index_ >= expr_.size();\n }\n\n \/\/\/ Returns the character at the current expression index or\n \/\/\/ 0 if the end of the expression is reached.\n \/\/\/\n char getCharacter() const\n {\n if (!isEnd())\n return expr_[index_];\n return 0;\n }\n\n \/\/\/ Parse str at the current expression index.\n \/\/\/ @throw error if parsing fails.\n \/\/\/\n void expect(const std::string& str)\n {\n if (expr_.compare(index_, str.size(), str) != 0)\n unexpected();\n index_ += str.size();\n }\n\n void unexpected() const\n {\n std::ostringstream msg;\n msg << \"Syntax error: unexpected token \\\"\"\n << expr_.substr(index_, expr_.size() - index_)\n << \"\\\" at index \"\n << index_;\n throw calculator::error(expr_, msg.str());\n }\n\n \/\/\/ Eat all white space characters at the\n \/\/\/ current expression index.\n \/\/\/\n void eatSpaces()\n {\n while (std::isspace(getCharacter()) != 0)\n index_++;\n }\n\n \/\/\/ Parse a binary operator at the current expression index.\n \/\/\/ @return Operator with precedence and associativity.\n \/\/\/\n Operator parseOp()\n {\n eatSpaces();\n switch (getCharacter())\n {\n case '|': index_++; return Operator(OPERATOR_BITWISE_OR, 4, 'L');\n case '&': index_++; return Operator(OPERATOR_BITWISE_AND, 6, 'L');\n case '<': expect(\"<<\"); return Operator(OPERATOR_BITWISE_SHL, 9, 'L');\n case '>': expect(\">>\"); return Operator(OPERATOR_BITWISE_SHR, 9, 'L');\n case '+': index_++; return Operator(OPERATOR_ADDITION, 10, 'L');\n case '-': index_++; return Operator(OPERATOR_SUBTRACTION, 10, 'L');\n case '\/': index_++; return Operator(OPERATOR_DIVISION, 20, 'L');\n case '%': index_++; return Operator(OPERATOR_MODULO, 20, 'L');\n case '*': index_++; if (getCharacter() != '*')\n return Operator(OPERATOR_MULTIPLICATION, 20, 'L');\n index_++; return Operator(OPERATOR_POWER, 30, 'R');\n case '^': index_++; return Operator(OPERATOR_POWER, 30, 'R');\n case 'e': index_++; return Operator(OPERATOR_EXPONENT, 40, 'R');\n case 'E': index_++; return Operator(OPERATOR_EXPONENT, 40, 'R');\n default : return Operator(OPERATOR_NULL, 0, 'L');\n }\n }\n\n static T toInteger(char c)\n {\n if (c >= '0' && c <= '9') return c -'0';\n if (c >= 'a' && c <= 'f') return c -'a' + 0xa;\n if (c >= 'A' && c <= 'F') return c -'A' + 0xa;\n T noDigit = 0xf + 1;\n return noDigit;\n }\n\n T getInteger() const\n {\n return toInteger(getCharacter());\n }\n\n T parseDecimal()\n {\n T value = 0;\n for (T d; (d = getInteger()) <= 9; index_++)\n value = value * 10 + d;\n return value;\n }\n\n T parseHex()\n {\n index_ = index_ + 2;\n T value = 0;\n for (T h; (h = getInteger()) <= 0xf; index_++)\n value = value * 0x10 + h;\n return value;\n }\n\n bool isHex() const\n {\n if (index_ + 2 < expr_.size())\n {\n char x = expr_[index_ + 1];\n char h = expr_[index_ + 2];\n return (std::tolower(x) == 'x' && toInteger(h) <= 0xf);\n }\n return false;\n }\n\n \/\/\/ Parse an integer value at the current expression index.\n \/\/\/ The unary `+', `-' and `~' operators and opening\n \/\/\/ parentheses `(' cause recursion.\n \/\/\/\n T parseValue()\n {\n T val = 0;\n eatSpaces();\n switch (getCharacter())\n {\n case '0': if (isHex())\n val = parseHex();\n else\n val = parseDecimal();\n break;\n case '1': case '2': case '3': case '4': case '5':\n case '6': case '7': case '8': case '9':\n val = parseDecimal();\n break;\n case '(': index_++;\n val = parseExpr();\n eatSpaces();\n if (getCharacter() != ')')\n {\n if (!isEnd())\n unexpected();\n throw calculator::error(expr_, \"Syntax error: `)' expected at end of expression\");\n }\n index_++; break;\n case '~': index_++; val = ~parseValue(); break;\n case '+': index_++; val = parseValue(); break;\n case '-': index_++; val = parseValue() * static_cast<T>(-1);\n break;\n default : if (!isEnd())\n unexpected();\n throw calculator::error(expr_, \"Syntax error: value expected at end of expression\");\n }\n return val;\n }\n\n \/\/\/ Parse all operations of the current parenthesis\n \/\/\/ level and the levels above, when done\n \/\/\/ return the result (value).\n \/\/\/\n T parseExpr()\n {\n stack_.push(OperatorValue(Operator(OPERATOR_NULL, 0, 'L'), 0));\n \/\/ first parse value on the left\n T value = parseValue();\n\n while (!stack_.empty())\n {\n \/\/ parse an operator (+, -, *, ...)\n Operator op(parseOp());\n while (op.precedence < stack_.top().getPrecedence() || (\n op.precedence == stack_.top().getPrecedence() &&\n op.associativity == 'L'))\n {\n \/\/ end reached\n if (stack_.top().isNull())\n {\n stack_.pop();\n return value;\n }\n \/\/ do the calculation (\"reduce\"), producing a new value\n value = calculate(stack_.top().value, value, stack_.top().op);\n stack_.pop();\n }\n\n \/\/ store on stack_ and continue parsing (\"shift\")\n stack_.push(OperatorValue(op, value));\n \/\/ parse value on the right\n value = parseValue();\n }\n return 0;\n }\n};\n\ntemplate <typename T>\ninline T eval(const std::string& expression)\n{\n ExpressionParser<T> parser;\n return parser.eval(expression);\n}\n\ntemplate <typename T>\ninline T eval(char c)\n{\n ExpressionParser<T> parser;\n return parser.eval(c);\n}\n\ninline int eval(const std::string& expression)\n{\n return eval<int>(expression);\n}\n\ninline int eval(char c)\n{\n return eval<int>(c);\n}\n\n} \/\/ namespace calculator\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/**\n@file IO\/Datastore.hpp\n@brief Datastore class.\n\n@author Tim Howard\n@copyright 2013 Tim Howard under the MIT license;\nsee @ref index or the accompanying LICENSE file for full text.\n*\/\n\n#ifndef HORD_IO_DATASTORE_HPP_\n#define HORD_IO_DATASTORE_HPP_\n\n#include <Hord\/config.hpp>\n#include <Hord\/traits.hpp>\n#include <Hord\/String.hpp>\n#include <Hord\/System\/IDGenerator.hpp>\n#include <Hord\/IO\/Defs.hpp>\n#include <Hord\/IO\/Prop.hpp>\n#include <Hord\/Object\/Defs.hpp>\n\n#include <duct\/StateStore.hpp>\n\n#include <cassert>\n#include <functional>\n#include <iosfwd>\n\nnamespace Hord {\nnamespace IO {\n\n\/\/ Forward declarations\nclass Datastore;\n\n\/**\n\t@addtogroup io\n\t@{\n*\/\n\/**\n\t@addtogroup datastore\n\t@{\n*\/\n\n\/**\n\tBase datastore.\n\n\tThis is the data interface for hives.\n\n\t@note %Datastores must be locked when a single prop stream is\n\tactive.\n*\/\nclass Datastore {\npublic:\n\t\/**\n\t\tType info.\n\t*\/\n\tstruct type_info final {\n\t\/** @name Operations *\/ \/\/\/ @{\n\t\t\/**\n\t\t\tConstruct a datastore of this type.\n\n\t\t\t@returns\n\t\t\t- The constructed datastore; or\n\t\t\t- @c nullptr if construction failed.\n\t\t\t@param root_path Root path.\n\t\t*\/\n\t\tDatastore*\n\t\t(&construct)(\n\t\t\tString root_path\n\t\t) noexcept;\n\t\/\/\/ @}\n\t};\n\n\t\/**\n\t\tEnsure traits for deriving classes.\n\n\t\t@remarks All constructors should be hidden or deleted.\n\n\t\t@tparam D Deriving class.\n\t*\/\n\ttemplate<\n\t\ttypename D\n\t>\n\tstruct ensure_traits :\n\t\ttraits::require_t<\n\t\t\tD,\n\t\t\ttw::capture_post<std::is_base_of, Datastore>::type,\n\t\t\tstd::is_nothrow_destructible\n\t\t>,\n\t\ttraits::disallow_t<\n\t\t\tD,\n\t\t\tstd::is_default_constructible,\n\t\t\ttw::capture<std::is_constructible, String>::type,\n\t\t\ttw::is_fully_copyable,\n\t\t\ttw::is_fully_moveable\n\t\t>\n\t{};\n\nprotected:\n\/** @name Implementation *\/ \/\/\/ @{\n\t\/**\n\t\topen() implementation.\n\n\t\t@throws Error{ErrorCode::datastore_open_failed}\n\t*\/\n\tvirtual void\n\topen_impl() = 0;\n\n\t\/**\n\t\tclose() implementation.\n\n\t\t@remarks This is not called if @c is_open()==false.\n\t*\/\n\tvirtual void\n\tclose_impl() = 0;\n\n\t\/**\n\t\tacquire_input_stream() implementation.\n\n\t\t@throws Error{ErrorCode::datastore_object_not_found}\n\t\t@throws Error{ErrorCode::datastore_prop_void}\n\t\t@throws Error{ErrorCode::datastore_prop_unsupplied}\n\t\t@throws Error{..}\n\t*\/\n\tvirtual std::istream&\n\tacquire_input_stream_impl(\n\t\tIO::PropInfo const& prop_info\n\t) = 0;\n\n\t\/**\n\t\tacquire_output_stream() implementation.\n\n\t\t@throws Error{ErrorCode::datastore_object_not_found}\n\t\t@throws Error{ErrorCode::datastore_prop_void}\n\t\t@throws Error{ErrorCode::datastore_prop_unsupplied}\n\t\t@throws Error{..}\n\t*\/\n\tvirtual std::ostream&\n\tacquire_output_stream_impl(\n\t\tIO::PropInfo const& prop_info\n\t) = 0;\n\n\t\/**\n\t\trelease_input_stream() implementation.\n\n\t\t@throws Error{ErrorCode::datastore_prop_not_locked}\n\t\t@throws Error{ErrorCode::datastore_object_not_found}\n\t\t@throws Error{ErrorCode::datastore_prop_unsupplied}\n\t\t@throws Error{..}\n\t*\/\n\tvirtual void\n\trelease_input_stream_impl(\n\t\tIO::PropInfo const& prop_info\n\t) = 0;\n\n\t\/**\n\t\trelease_output_stream() implementation.\n\n\t\t@throws Error{ErrorCode::datastore_prop_not_locked}\n\t\t@throws Error{ErrorCode::datastore_object_not_found}\n\t\t@throws Error{ErrorCode::datastore_prop_unsupplied}\n\t\t@throws Error{..}\n\t*\/\n\tvirtual void\n\trelease_output_stream_impl(\n\t\tIO::PropInfo const& prop_info\n\t) = 0;\n\n\t\/**\n\t\tgenerate_id() implementation.\n\n\t\t@remarks The implementation should generate a unique ID\n\t\twithin the entire ID set of the datastore -- i.e., including\n\t\torphaned objects (such as trash).\n\t*\/\n\tvirtual Object::ID\n\tgenerate_id_impl(\n\t\tSystem::IDGenerator& generator\n\t) const noexcept = 0;\n\n\t\/**\n\t\tcreate_object() implementation.\n\n\t\t@throws Error{ErrorCode::datastore_object_already_exists}\n\t\t@throws Error{..}\n\t*\/\n\tvirtual void\n\tcreate_object_impl(\n\t\tObject::ID const object_id,\n\t\tObject::Type const object_type\n\t) = 0;\n\n\t\/**\n\t\tdestroy_object() implementation.\n\n\t\t@throws Error{ErrorCode::datastore_object_not_found}\n\t\t@throws Error{..}\n\t*\/\n\tvirtual void\n\tdestroy_object_impl(\n\t\tObject::ID const object_id\n\t) = 0;\n\/\/\/ @}\n\n\/** @name Internal state *\/ \/\/\/ @{\n\t\/**\n\t\tStates.\n\n\t\tImplementations are permitted to define states @c 1<<8\n\t\tto @c 1<<31.\n\t*\/\n\tenum class State : uint32_t {\n\t\t\/** %Datastore is open. *\/\n\t\topened = 1 << 0,\n\t\t\/** %Datastore is locked. *\/\n\t\tlocked = 1 << 1,\n\n\t\t\/** First reserved state. *\/\n\t\tRESERVED_FIRST = 1 << 2,\n\t\t\/** Last reserved state. *\/\n\t\tRESERVED_LAST = 1 << 7\n\t};\n\n\/** @cond INTERNAL *\/\n#define HORD_STATE_ASSERT_VALID__(x__)\t\\\n\tassert(\t\t\t\t\t\t\t\t\\\n\t\tState::RESERVED_FIRST > x__ &&\t\\\n\t\tState::RESERVED_LAST < x__\t\t\\\n\t);\n\/** @endcond *\/\n\n\t\/**\n\t\tEnable state.\n\n\t\t@param state %State to enable.\n\t*\/\n\t\/*constexpr*\/ void\n\tenable_state(\n\t\tState const state\n\t) noexcept {\n\t\tHORD_STATE_ASSERT_VALID__(state);\n\t\tm_states.enable(state);\n\t}\n\n\t\/**\n\t\tDisable state.\n\n\t\t@param state %State to disable.\n\t*\/\n\t\/*constexpr*\/ void\n\tdisable_state(\n\t\tState const state\n\t) noexcept {\n\t\tHORD_STATE_ASSERT_VALID__(state);\n\t\tm_states.disable(state);\n\t}\n\n\t\/**\n\t\tEnable or disable state.\n\n\t\t@param state %State to enable or disable.\n\t\t@param enable Whether to enable or disable the state.\n\t*\/\n\t\/*constexpr*\/ void\n\tset_state(\n\t\tState const state,\n\t\tbool const enable\n\t) noexcept {\n\t\tHORD_STATE_ASSERT_VALID__(state);\n\t\tm_states.set(state, enable);\n\t}\n\n\t\/**\n\t\tTest value of state.\n\n\t\t@returns\n\t\t- @c true if the state is enabled;\n\t\t- @c false if the state is disabled.\n\t\t@param state State to test.\n\t*\/\n\t\/*constexpr*\/ bool\n\ttest_state(\n\t\tState const state\n\t) const noexcept {\n\t\tHORD_STATE_ASSERT_VALID__(state);\n\t\treturn m_states.test(state);\n\t}\n#undef HORD_STATE_ASSERT_VALID__\n\/\/\/ @}\n\nprivate:\n\tduct::StateStore<State> m_states;\n\tString m_root_path;\n\n\tDatastore() = delete;\n\tDatastore(Datastore const&) = delete;\n\tDatastore(Datastore&&) = delete;\n\tDatastore& operator=(Datastore const&) = delete;\n\tDatastore& operator=(Datastore&&) = delete;\n\nprotected:\n\/** @name Constructors and destructor *\/ \/\/\/ @{\n\t\/**\n\t\tConstructor with root path.\n\n\t\t@param root_path Root path.\n\t*\/\n\tDatastore(\n\t\tString root_path\n\t) noexcept;\npublic:\n\t\/** Destructor. *\/\n\tvirtual\n\t~Datastore() = 0;\n\/\/\/ @}\n\npublic:\n\/** @name Properties *\/ \/\/\/ @{\n\t\/**\n\t\tSet root path.\n\n\t\t@throws Error{ErrorCode::datastore_property_immutable}\n\t\tIf the datastore is open.\n\n\t\t@param root_path New root path.\n\t*\/\n\tvoid\n\tset_root_path(\n\t\tString root_path\n\t);\n\n\t\/**\n\t\tGet root path.\n\t*\/\n\tString const&\n\tget_root_path() const noexcept {\n\t\treturn m_root_path;\n\t}\n\n\t\/**\n\t\tCheck if the datastore is open.\n\t*\/\n\tbool\n\tis_open() const noexcept {\n\t\treturn test_state(State::opened);\n\t}\n\n\t\/**\n\t\tCheck if the datastore is locked.\n\t*\/\n\tbool\n\tis_locked() const noexcept {\n\t\treturn test_state(State::locked);\n\t}\n\/\/\/ @}\n\n\/** @name Operations *\/ \/\/\/ @{\n\t\/**\n\t\tOpen the datastore.\n\n\t\t@throws Error{ErrorCode::datastore_open_already}\n\t\tIf the datastore is already open.\n\n\t\t@throws Error{ErrorCode::datastore_open_failed}\n\t\tIf the datastore failed to open.\n\t*\/\n\tvoid\n\topen();\n\n\t\/**\n\t\tClose the datastore.\n\n\t\t@throws Error{ErrorCode::datastore_locked}\n\t\tIf the datastore is locked.\n\t*\/\n\tvoid\n\tclose();\n\n\t\/**\n\t\tAcquire raw stream for prop.\n\n\t\t@throws Error{ErrorCode::datastore_closed}\n\t\tIf the datastore is closed.\n\n\t\t@throws Error{ErrorCode::datastore_locked}\n\t\tIf the datastore is locked.\n\n\t\t@throws Error{ErrorCode::datastore_object_not_found}\n\t\tIf @c prop_info.object_id does not exist in the datastore.\n\n\t\t@throws Error{ErrorCode::datastore_prop_void}\n\t\tIf the object for @c prop_info.object_id has not yet created\n\t\tthe prop (but it is otherwise valid). This can only occur\n\t\twhen acquiring an input stream.\n\n\t\t@throws Error{ErrorCode::datastore_prop_unsupplied}\n\t\tIf the object for @c prop_info.object_id does not supply the\n\t\trequested prop.\n\n\t\t@throws Error{..}\n\t\t<em>Implementation-defined exceptions.<\/em>\n\n\t\t@returns Raw prop stream.\n\t\t@param prop_info Prop info.\n\n\t\t@sa IO::PropInfo,\n\t\t\tIO::InputPropStream,\n\t\t\tIO::OutputPropStream\n\t*\/\n\tstd::istream&\n\tacquire_input_stream(\n\t\tIO::PropInfo const& prop_info\n\t);\n\n\t\/** @copydoc acquire_input_stream(IO::PropInfo const&) *\/\n\tstd::ostream&\n\tacquire_output_stream(\n\t\tIO::PropInfo const& prop_info\n\t);\n\n\t\/**\n\t\tRelease raw stream for prop.\n\n\t\t@throws Error{ErrorCode::datastore_closed}\n\t\tIf the datastore is closed.\n\n\t\t@throws Error{ErrorCode::datastore_prop_not_locked}\n\t\tIf either @a prop_info does not match the currently locked\n\t\tprop stream or there is no currently locked prop stream.\n\n\t\t@throws Error{ErrorCode::datastore_object_not_found}\n\t\tIf @c prop_info.object_id does not exist in the datastore.\n\n\t\t@throws Error{ErrorCode::datastore_prop_unsupplied}\n\t\tIf the object for @c prop_info.object_id does not supply\n\t\tthe requested prop.\n\n\t\t@throws Error{..}\n\t\t<em>Implementation-defined exceptions.<\/em>\n\n\t\t@param prop_info Prop info.\n\n\t\t@sa IO::PropInfo,\n\t\t\tIO::InputPropStream,\n\t\t\tIO::OutputPropStream\n\t*\/\n\tvoid\n\trelease_input_stream(\n\t\tIO::PropInfo const& prop_info\n\t);\n\n\t\/** @copydoc release_input_stream(IO::PropInfo const&) *\/\n\tvoid\n\trelease_output_stream(\n\t\tIO::PropInfo const& prop_info\n\t);\n\/\/\/ @}\n\n\/** @name Objects *\/ \/\/\/ @{\n\t\/**\n\t\tGenerate a %Hive-unique ID.\n\n\t\t@throws Error{ErrorCode::datastore_closed}\n\t\tIf the datastore is closed.\n\n\t\t@returns The generated object ID.\n\t\t@param generator ID generator.\n\t*\/\n\tObject::ID\n\tgenerate_id(\n\t\tSystem::IDGenerator& generator\n\t) const;\n\n\t\/**\n\t\tCreate an object in the datastore.\n\n\t\t@throws Error{ErrorCode::datastore_object_type_prohibited}\n\t\tIf @c object_type!=Object::Type::Node, which is\n\t\tcurrently the only object type that can be created.\n\n\t\t@throws Error{ErrorCode::datastore_closed}\n\t\tIf the datastore is closed.\n\n\t\t@throws Error{ErrorCode::datastore_locked}\n\t\tIf the datastore is locked.\n\n\t\t@throws Error{ErrorCode::datastore_object_already_exists}\n\t\tIf @a object_id already exists in the datastore.\n\n\t\t@throws Error{..}\n\t\t<em>Implementation-defined exceptions.<\/em>\n\n\t\t@param object_id ID of object.\n\t\t@param object_type Type of object.\n\t*\/\n\tvoid\n\tcreate_object(\n\t\tObject::ID const object_id,\n\t\tObject::Type const object_type\n\t);\n\n\t\/**\n\t\tDestroy an object in the datastore.\n\n\t\t@throws Error{ErrorCode::datastore_closed}\n\t\tIf the datastore is closed.\n\n\t\t@throws Error{ErrorCode::datastore_locked}\n\t\tIf the datastore is locked.\n\n\t\t@throws Error{ErrorCode::datastore_object_not_found}\n\t\tIf @a object_id does not exist in the datastore.\n\n\t\t@throws Error{..}\n\t\t<em>Implementation-defined exceptions.<\/em>\n\n\t\t@param object_id ID of object.\n\t*\/\n\tvoid\n\tdestroy_object(\n\t\tObject::ID const object_id\n\t);\n\/\/\/ @}\n};\n\n\/** @} *\/ \/\/ end of doc-group datastore\n\/** @} *\/ \/\/ end of doc-group io\n\n} \/\/ namespace IO\n\ntemplate struct traits::require_t<\n\tIO::Datastore,\n\tstd::has_virtual_destructor\n>;\n\n} \/\/ namespace Hord\n\n#endif \/\/ HORD_IO_DATASTORE_HPP_\n<commit_msg>IO::Datastore: removed ErrorCode::datastore_prop_unsupplied from stream release.<commit_after>\/**\n@file IO\/Datastore.hpp\n@brief Datastore class.\n\n@author Tim Howard\n@copyright 2013 Tim Howard under the MIT license;\nsee @ref index or the accompanying LICENSE file for full text.\n*\/\n\n#ifndef HORD_IO_DATASTORE_HPP_\n#define HORD_IO_DATASTORE_HPP_\n\n#include <Hord\/config.hpp>\n#include <Hord\/traits.hpp>\n#include <Hord\/String.hpp>\n#include <Hord\/System\/IDGenerator.hpp>\n#include <Hord\/IO\/Defs.hpp>\n#include <Hord\/IO\/Prop.hpp>\n#include <Hord\/Object\/Defs.hpp>\n\n#include <duct\/StateStore.hpp>\n\n#include <cassert>\n#include <functional>\n#include <iosfwd>\n\nnamespace Hord {\nnamespace IO {\n\n\/\/ Forward declarations\nclass Datastore;\n\n\/**\n\t@addtogroup io\n\t@{\n*\/\n\/**\n\t@addtogroup datastore\n\t@{\n*\/\n\n\/**\n\tBase datastore.\n\n\tThis is the data interface for hives.\n\n\t@note %Datastores must be locked when a single prop stream is\n\tactive.\n*\/\nclass Datastore {\npublic:\n\t\/**\n\t\tType info.\n\t*\/\n\tstruct type_info final {\n\t\/** @name Operations *\/ \/\/\/ @{\n\t\t\/**\n\t\t\tConstruct a datastore of this type.\n\n\t\t\t@returns\n\t\t\t- The constructed datastore; or\n\t\t\t- @c nullptr if construction failed.\n\t\t\t@param root_path Root path.\n\t\t*\/\n\t\tDatastore*\n\t\t(&construct)(\n\t\t\tString root_path\n\t\t) noexcept;\n\t\/\/\/ @}\n\t};\n\n\t\/**\n\t\tEnsure traits for deriving classes.\n\n\t\t@remarks All constructors should be hidden or deleted.\n\n\t\t@tparam D Deriving class.\n\t*\/\n\ttemplate<\n\t\ttypename D\n\t>\n\tstruct ensure_traits :\n\t\ttraits::require_t<\n\t\t\tD,\n\t\t\ttw::capture_post<std::is_base_of, Datastore>::type,\n\t\t\tstd::is_nothrow_destructible\n\t\t>,\n\t\ttraits::disallow_t<\n\t\t\tD,\n\t\t\tstd::is_default_constructible,\n\t\t\ttw::capture<std::is_constructible, String>::type,\n\t\t\ttw::is_fully_copyable,\n\t\t\ttw::is_fully_moveable\n\t\t>\n\t{};\n\nprotected:\n\/** @name Implementation *\/ \/\/\/ @{\n\t\/**\n\t\topen() implementation.\n\n\t\t@throws Error{ErrorCode::datastore_open_failed}\n\t*\/\n\tvirtual void\n\topen_impl() = 0;\n\n\t\/**\n\t\tclose() implementation.\n\n\t\t@remarks This is not called if @c is_open()==false.\n\t*\/\n\tvirtual void\n\tclose_impl() = 0;\n\n\t\/**\n\t\tacquire_input_stream() implementation.\n\n\t\t@throws Error{ErrorCode::datastore_object_not_found}\n\t\t@throws Error{ErrorCode::datastore_prop_void}\n\t\t@throws Error{ErrorCode::datastore_prop_unsupplied}\n\t\t@throws Error{..}\n\t*\/\n\tvirtual std::istream&\n\tacquire_input_stream_impl(\n\t\tIO::PropInfo const& prop_info\n\t) = 0;\n\n\t\/**\n\t\tacquire_output_stream() implementation.\n\n\t\t@throws Error{ErrorCode::datastore_object_not_found}\n\t\t@throws Error{ErrorCode::datastore_prop_void}\n\t\t@throws Error{ErrorCode::datastore_prop_unsupplied}\n\t\t@throws Error{..}\n\t*\/\n\tvirtual std::ostream&\n\tacquire_output_stream_impl(\n\t\tIO::PropInfo const& prop_info\n\t) = 0;\n\n\t\/**\n\t\trelease_input_stream() implementation.\n\n\t\t@throws Error{ErrorCode::datastore_prop_not_locked}\n\t\t@throws Error{ErrorCode::datastore_object_not_found}\n\t\t@throws Error{..}\n\t*\/\n\tvirtual void\n\trelease_input_stream_impl(\n\t\tIO::PropInfo const& prop_info\n\t) = 0;\n\n\t\/**\n\t\trelease_output_stream() implementation.\n\n\t\t@throws Error{ErrorCode::datastore_prop_not_locked}\n\t\t@throws Error{ErrorCode::datastore_object_not_found}\n\t\t@throws Error{..}\n\t*\/\n\tvirtual void\n\trelease_output_stream_impl(\n\t\tIO::PropInfo const& prop_info\n\t) = 0;\n\n\t\/**\n\t\tgenerate_id() implementation.\n\n\t\t@remarks The implementation should generate a unique ID\n\t\twithin the entire ID set of the datastore -- i.e., including\n\t\torphaned objects (such as trash).\n\t*\/\n\tvirtual Object::ID\n\tgenerate_id_impl(\n\t\tSystem::IDGenerator& generator\n\t) const noexcept = 0;\n\n\t\/**\n\t\tcreate_object() implementation.\n\n\t\t@throws Error{ErrorCode::datastore_object_already_exists}\n\t\t@throws Error{..}\n\t*\/\n\tvirtual void\n\tcreate_object_impl(\n\t\tObject::ID const object_id,\n\t\tObject::Type const object_type\n\t) = 0;\n\n\t\/**\n\t\tdestroy_object() implementation.\n\n\t\t@throws Error{ErrorCode::datastore_object_not_found}\n\t\t@throws Error{..}\n\t*\/\n\tvirtual void\n\tdestroy_object_impl(\n\t\tObject::ID const object_id\n\t) = 0;\n\/\/\/ @}\n\n\/** @name Internal state *\/ \/\/\/ @{\n\t\/**\n\t\tStates.\n\n\t\tImplementations are permitted to define states @c 1<<8\n\t\tto @c 1<<31.\n\t*\/\n\tenum class State : uint32_t {\n\t\t\/** %Datastore is open. *\/\n\t\topened = 1 << 0,\n\t\t\/** %Datastore is locked. *\/\n\t\tlocked = 1 << 1,\n\n\t\t\/** First reserved state. *\/\n\t\tRESERVED_FIRST = 1 << 2,\n\t\t\/** Last reserved state. *\/\n\t\tRESERVED_LAST = 1 << 7\n\t};\n\n\/** @cond INTERNAL *\/\n#define HORD_STATE_ASSERT_VALID__(x__)\t\\\n\tassert(\t\t\t\t\t\t\t\t\\\n\t\tState::RESERVED_FIRST > x__ &&\t\\\n\t\tState::RESERVED_LAST < x__\t\t\\\n\t);\n\/** @endcond *\/\n\n\t\/**\n\t\tEnable state.\n\n\t\t@param state %State to enable.\n\t*\/\n\t\/*constexpr*\/ void\n\tenable_state(\n\t\tState const state\n\t) noexcept {\n\t\tHORD_STATE_ASSERT_VALID__(state);\n\t\tm_states.enable(state);\n\t}\n\n\t\/**\n\t\tDisable state.\n\n\t\t@param state %State to disable.\n\t*\/\n\t\/*constexpr*\/ void\n\tdisable_state(\n\t\tState const state\n\t) noexcept {\n\t\tHORD_STATE_ASSERT_VALID__(state);\n\t\tm_states.disable(state);\n\t}\n\n\t\/**\n\t\tEnable or disable state.\n\n\t\t@param state %State to enable or disable.\n\t\t@param enable Whether to enable or disable the state.\n\t*\/\n\t\/*constexpr*\/ void\n\tset_state(\n\t\tState const state,\n\t\tbool const enable\n\t) noexcept {\n\t\tHORD_STATE_ASSERT_VALID__(state);\n\t\tm_states.set(state, enable);\n\t}\n\n\t\/**\n\t\tTest value of state.\n\n\t\t@returns\n\t\t- @c true if the state is enabled;\n\t\t- @c false if the state is disabled.\n\t\t@param state State to test.\n\t*\/\n\t\/*constexpr*\/ bool\n\ttest_state(\n\t\tState const state\n\t) const noexcept {\n\t\tHORD_STATE_ASSERT_VALID__(state);\n\t\treturn m_states.test(state);\n\t}\n#undef HORD_STATE_ASSERT_VALID__\n\/\/\/ @}\n\nprivate:\n\tduct::StateStore<State> m_states;\n\tString m_root_path;\n\n\tDatastore() = delete;\n\tDatastore(Datastore const&) = delete;\n\tDatastore(Datastore&&) = delete;\n\tDatastore& operator=(Datastore const&) = delete;\n\tDatastore& operator=(Datastore&&) = delete;\n\nprotected:\n\/** @name Constructors and destructor *\/ \/\/\/ @{\n\t\/**\n\t\tConstructor with root path.\n\n\t\t@param root_path Root path.\n\t*\/\n\tDatastore(\n\t\tString root_path\n\t) noexcept;\npublic:\n\t\/** Destructor. *\/\n\tvirtual\n\t~Datastore() = 0;\n\/\/\/ @}\n\npublic:\n\/** @name Properties *\/ \/\/\/ @{\n\t\/**\n\t\tSet root path.\n\n\t\t@throws Error{ErrorCode::datastore_property_immutable}\n\t\tIf the datastore is open.\n\n\t\t@param root_path New root path.\n\t*\/\n\tvoid\n\tset_root_path(\n\t\tString root_path\n\t);\n\n\t\/**\n\t\tGet root path.\n\t*\/\n\tString const&\n\tget_root_path() const noexcept {\n\t\treturn m_root_path;\n\t}\n\n\t\/**\n\t\tCheck if the datastore is open.\n\t*\/\n\tbool\n\tis_open() const noexcept {\n\t\treturn test_state(State::opened);\n\t}\n\n\t\/**\n\t\tCheck if the datastore is locked.\n\t*\/\n\tbool\n\tis_locked() const noexcept {\n\t\treturn test_state(State::locked);\n\t}\n\/\/\/ @}\n\n\/** @name Operations *\/ \/\/\/ @{\n\t\/**\n\t\tOpen the datastore.\n\n\t\t@throws Error{ErrorCode::datastore_open_already}\n\t\tIf the datastore is already open.\n\n\t\t@throws Error{ErrorCode::datastore_open_failed}\n\t\tIf the datastore failed to open.\n\t*\/\n\tvoid\n\topen();\n\n\t\/**\n\t\tClose the datastore.\n\n\t\t@throws Error{ErrorCode::datastore_locked}\n\t\tIf the datastore is locked.\n\t*\/\n\tvoid\n\tclose();\n\n\t\/**\n\t\tAcquire raw stream for prop.\n\n\t\t@throws Error{ErrorCode::datastore_closed}\n\t\tIf the datastore is closed.\n\n\t\t@throws Error{ErrorCode::datastore_locked}\n\t\tIf the datastore is locked.\n\n\t\t@throws Error{ErrorCode::datastore_object_not_found}\n\t\tIf @c prop_info.object_id does not exist in the datastore.\n\n\t\t@throws Error{ErrorCode::datastore_prop_void}\n\t\tIf the object for @c prop_info.object_id has not yet created\n\t\tthe prop (but it is otherwise valid). This can only occur\n\t\twhen acquiring an input stream.\n\n\t\t@throws Error{ErrorCode::datastore_prop_unsupplied}\n\t\tIf the object for @c prop_info.object_id does not supply the\n\t\trequested prop.\n\n\t\t@throws Error{..}\n\t\t<em>Implementation-defined exceptions.<\/em>\n\n\t\t@returns Raw prop stream.\n\t\t@param prop_info Prop info.\n\n\t\t@sa IO::PropInfo,\n\t\t\tIO::InputPropStream,\n\t\t\tIO::OutputPropStream\n\t*\/\n\tstd::istream&\n\tacquire_input_stream(\n\t\tIO::PropInfo const& prop_info\n\t);\n\n\t\/** @copydoc acquire_input_stream(IO::PropInfo const&) *\/\n\tstd::ostream&\n\tacquire_output_stream(\n\t\tIO::PropInfo const& prop_info\n\t);\n\n\t\/**\n\t\tRelease raw stream for prop.\n\n\t\t@throws Error{ErrorCode::datastore_closed}\n\t\tIf the datastore is closed.\n\n\t\t@throws Error{ErrorCode::datastore_prop_not_locked}\n\t\tIf either @a prop_info does not match the currently locked\n\t\tprop stream or there is no currently locked prop stream.\n\n\t\t@throws Error{ErrorCode::datastore_object_not_found}\n\t\tIf @c prop_info.object_id does not exist in the datastore.\n\n\t\t@throws Error{..}\n\t\t<em>Implementation-defined exceptions.<\/em>\n\n\t\t@param prop_info Prop info.\n\n\t\t@sa IO::PropInfo,\n\t\t\tIO::InputPropStream,\n\t\t\tIO::OutputPropStream\n\t*\/\n\tvoid\n\trelease_input_stream(\n\t\tIO::PropInfo const& prop_info\n\t);\n\n\t\/** @copydoc release_input_stream(IO::PropInfo const&) *\/\n\tvoid\n\trelease_output_stream(\n\t\tIO::PropInfo const& prop_info\n\t);\n\/\/\/ @}\n\n\/** @name Objects *\/ \/\/\/ @{\n\t\/**\n\t\tGenerate a %Hive-unique ID.\n\n\t\t@throws Error{ErrorCode::datastore_closed}\n\t\tIf the datastore is closed.\n\n\t\t@returns The generated object ID.\n\t\t@param generator ID generator.\n\t*\/\n\tObject::ID\n\tgenerate_id(\n\t\tSystem::IDGenerator& generator\n\t) const;\n\n\t\/**\n\t\tCreate an object in the datastore.\n\n\t\t@throws Error{ErrorCode::datastore_object_type_prohibited}\n\t\tIf @c object_type!=Object::Type::Node, which is\n\t\tcurrently the only object type that can be created.\n\n\t\t@throws Error{ErrorCode::datastore_closed}\n\t\tIf the datastore is closed.\n\n\t\t@throws Error{ErrorCode::datastore_locked}\n\t\tIf the datastore is locked.\n\n\t\t@throws Error{ErrorCode::datastore_object_already_exists}\n\t\tIf @a object_id already exists in the datastore.\n\n\t\t@throws Error{..}\n\t\t<em>Implementation-defined exceptions.<\/em>\n\n\t\t@param object_id ID of object.\n\t\t@param object_type Type of object.\n\t*\/\n\tvoid\n\tcreate_object(\n\t\tObject::ID const object_id,\n\t\tObject::Type const object_type\n\t);\n\n\t\/**\n\t\tDestroy an object in the datastore.\n\n\t\t@throws Error{ErrorCode::datastore_closed}\n\t\tIf the datastore is closed.\n\n\t\t@throws Error{ErrorCode::datastore_locked}\n\t\tIf the datastore is locked.\n\n\t\t@throws Error{ErrorCode::datastore_object_not_found}\n\t\tIf @a object_id does not exist in the datastore.\n\n\t\t@throws Error{..}\n\t\t<em>Implementation-defined exceptions.<\/em>\n\n\t\t@param object_id ID of object.\n\t*\/\n\tvoid\n\tdestroy_object(\n\t\tObject::ID const object_id\n\t);\n\/\/\/ @}\n};\n\n\/** @} *\/ \/\/ end of doc-group datastore\n\/** @} *\/ \/\/ end of doc-group io\n\n} \/\/ namespace IO\n\ntemplate struct traits::require_t<\n\tIO::Datastore,\n\tstd::has_virtual_destructor\n>;\n\n} \/\/ namespace Hord\n\n#endif \/\/ HORD_IO_DATASTORE_HPP_\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (C) 2017 Jérôme Leclercq\n\/\/ This file is part of the \"Nazara Engine - Core module\"\n\/\/ For conditions of distribution and use, see copyright notice in Config.hpp\n\n#include <Nazara\/Core\/Flags.hpp>\n#include <Nazara\/Core\/Debug.hpp>\n\nnamespace Nz\n{\n\t\/*!\n\t* \\ingroup core\n\t* \\class Nz::Flags\n\t* \\brief Core class used to combine enumeration values into flags bitfield\n\t*\/\n\n\t\/*!\n\t* \\brief Constructs a Flags object using a bitfield\n\t*\n\t* \\param value Bitfield to be used\n\t*\n\t* Uses a bitfield to builds the flag value. (e.g. if bit 0 is active, then Enum value 0 will be set as active).\n\t*\/\n\ttemplate<typename E>\n\tconstexpr Flags<E>::Flags(BitField value) :\n\tm_value(value)\n\t{\n\t}\n\n\t\/*!\n\t* \\brief Constructs a Flags object using an Enum value\n\t*\n\t* \\param enumVal enumVal\n\t*\n\t* Setup a Flags object with only one flag active (corresponding to the enum value passed as argument).\n\t*\/\n\ttemplate<typename E>\n\tconstexpr Flags<E>::Flags(E enumVal) :\n\tFlags(GetFlagValue(enumVal))\n\t{\n\t}\n\n\t\/*!\n\t* \\brief Tests if all flags from a Flags object are enabled\n\t* \\return True if all tested flags are enabled.\n\t*\/\n\ttemplate<typename E>\n\tconstexpr bool Flags<E>::Test(const Flags& flags) const\n\t{\n\t\treturn (m_value & flags.m_value) == flags.m_value;\n\t}\n\n\t\/*!\n\t* \\brief Tests any flag\n\t* \\return True if any flag is enabled.\n\t*\n\t* This will convert to a boolean value allowing to check if any flag is set.\n\t*\/\n\ttemplate<typename E>\n\tconstexpr Flags<E>::operator bool() const\n\t{\n\t\treturn m_value != 0;\n\t}\n\n\t\/*!\n\t* \\brief Converts to an integer\n\t* \\return Enabled flags as a integer\n\t*\n\t* This will only works if the integer type is large enough to store all flags states\n\t*\/\n\ttemplate<typename E>\n\ttemplate<typename T, typename>\n\tconstexpr Flags<E>::operator T() const\n\t{\n\t\treturn m_value;\n\t}\n\n\t\/*!\n\t* \\brief Reverse flag states\n\t* \\return Opposite enabled flags\n\t*\n\t* This will returns a copy of the Flags object with reversed flags states.\n\t*\/\n\ttemplate<typename E>\n\tconstexpr Flags<E> Flags<E>::operator~() const\n\t{\n\t\treturn Flags((~m_value) & ValueMask);\n\t}\n\n\t\/*!\n\t* \\brief Compare flag states\n\t* \\return Shared flags\n\t*\n\t* \\param rhs Flags to compare with.\n\t*\n\t* This will returns a copy of the Flags object with only enabled flags in common with the parameter\n\t*\/\n\ttemplate<typename E>\n\tconstexpr Flags<E> Flags<E>::operator&(const Flags& rhs) const\n\t{\n\t\treturn Flags(m_value & rhs.m_value);\n\t}\n\n\t\/*!\n\t* \\brief Combine flag states\n\t* \\return Combined flags\n\t*\n\t* This will returns a copy of the Flags object with combined flags from the parameter.\n\t*\n\t* \\param rhs Flags to combine with.\n\t*\/\n\ttemplate<typename E>\n\tconstexpr Flags<E> Flags<E>::operator|(const Flags& rhs) const\n\t{\n\t\treturn Flags(m_value | rhs.m_value);\n\t}\n\n\t\/*!\n\t* \\brief XOR flag states\n\t* \\return XORed flags.\n\t*\n\t* \\param rhs Flags to XOR with.\n\t*\n\t* This performs a XOR (Exclusive OR) on a copy of the flag object.\n\t* This will returns a copy of the object with disabled common flags and enabled unique ones.\n\t*\/\n\ttemplate<typename E>\n\tconstexpr Flags<E> Flags<E>::operator^(const Flags& rhs) const\n\t{\n\t\treturn Flags((m_value ^ rhs.m_value) & ValueMask);\n\t}\n\n\t\/*!\n\t* \\brief Check equality with flag object\n\t* \\return True if both flags objects have the same states.\n\t*\n\t* \\param rhs Flags to compare with.\n\t*\n\t* Compare two Flags object and returns true if the flag states are identical.\n\t*\/\n\ttemplate<typename E>\n\tconstexpr bool Flags<E>::operator==(const Flags& rhs) const\n\t{\n\t\treturn m_value == rhs.m_value;\n\t}\n\n\t\/*!\n\t* \\brief Check inequality with flag object\n\t* \\return True if both flags objects have different states.\n\t*\n\t* \\param rhs Flags to compare with.\n\t*\n\t* Compare two Flags object and returns true if the flag states are identical.\n\t*\/\n\ttemplate<typename E>\n\tconstexpr bool Flags<E>::operator!=(const Flags& rhs) const\n\t{\n\t\treturn !operator==(rhs);\n\t}\n\n\t\/*!\n\t* \\brief Combine flag states\n\t* \\return A reference to the object.\n\t*\n\t* \\param rhs Flags to combine with.\n\t*\n\t* This will enable flags which are enabled in parameter object and not in Flag object.\n\t*\/\n\ttemplate<typename E>\n\t\/*constexpr*\/ Flags<E>& Flags<E>::operator|=(const Flags& rhs)\n\t{\n\t\tm_value |= rhs.m_value;\n\n\t\treturn *this;\n\t}\n\n\t\/*!\n\t* \\brief Compare flag states\n\t* \\return A reference to the object.\n\t*\n\t* \\param rhs Flags to compare with.\n\t*\n\t* This will disable flags which are disabled in parameter object and enabled in Flag object (and vice-versa).\n\t*\/\n\ttemplate<typename E>\n\t\/*constexpr*\/ Flags<E>& Flags<E>::operator&=(const Flags& rhs)\n\t{\n\t\tm_value &= rhs.m_value;\n\n\t\treturn *this;\n\t}\n\n\t\/*!\n\t* \\brief XOR flag states\n\t* \\return A reference to the object.\n\t*\n\t* \\param rhs Flags to XOR with.\n\t*\n\t* This performs a XOR (Exclusive OR) on the flag object.\n\t* This will disable flags enabled in both Flags objects and enable those enabled in only one of the Flags objects.\n\t*\/\n\ttemplate<typename E>\n\t\/*constexpr*\/ Flags<E>& Flags<E>::operator^=(const Flags& rhs)\n\t{\n\t\tm_value ^= rhs.m_value;\n\t\tm_value &= ValueMask;\n\n\t\treturn *this;\n\t}\n\n\t\/*!\n\t* \\brief Returns a bitfield corresponding to an enum value.\n\t* \\return Bitfield representation of the enum value\n\t*\n\t* \\param enumValue Enumeration value to get as a bitfield.\n\t*\n\t* Internally, every enum option is turned into a bit, this function allows to get a bitfield with only the bit of the enumeration value enabled.\n\t*\/\n\ttemplate<typename E>\n\tconstexpr typename Flags<E>::BitField Flags<E>::GetFlagValue(E enumValue)\n\t{\n\t\tassert(enumValue < sizeof(BitField) * CHAR_BIT);\n\t\treturn 1U << static_cast<BitField>(enumValue);\n\t}\n\n\t\/*!\n\t* \\brief Compare flag states\n\t* \\return Compared flags\n\t*\n\t* This will returns a copy of the Flags object compared with the enum state.\n\t*\n\t* \\param lhs Enum to compare with flags.\n\t* \\param rhs Flags object.\n\t*\/\n\ttemplate<typename E>\n\tconstexpr Flags<E> operator&(E lhs, Flags<E> rhs)\n\t{\n\t\treturn rhs & lhs;\n\t}\n\n\t\/*!\n\t* \\brief Combine flag states\n\t* \\return Combined flags\n\t*\n\t* This will returns a copy of the Flags object combined with the enum state.\n\t*\n\t* \\param lhs Enum to combine with flags.\n\t* \\param rhs Flags object.\n\t*\/\n\ttemplate<typename E>\n\tconstexpr Flags<E> operator|(E lhs, Flags<E> rhs)\n\t{\n\t\treturn rhs | lhs;\n\t}\n\n\t\/*!\n\t* \\brief XOR flag states\n\t* \\return XORed flags\n\t*\n\t* This will returns a copy of the Flags object XORed with the enum state.\n\t*\n\t* \\param lhs Enum to XOR with flags.\n\t* \\param rhs Flags object.\n\t*\/\n\ttemplate<typename E>\n\tconstexpr Flags<E> operator^(E lhs, Flags<E> rhs)\n\t{\n\t\treturn rhs ^ lhs;\n\t}\n\n\n\tnamespace FlagsOperators\n\t{\n\t\t\/*!\n\t\t* \\brief Override binary NOT operator on enum to turns into a Flags object.\n\t\t* \\return A Flags object with reversed bits.\n\t\t*\n\t\t* \\param lhs Enumeration value to reverse.\n\t\t*\n\t\t* Returns a Flags object with all state enabled except for the enum one.\n\t\t*\/\n\t\ttemplate<typename E>\n\t\tconstexpr std::enable_if_t<IsEnumFlag<E>::value, Flags<E>> operator~(E lhs)\n\t\t{\n\t\t\treturn ~Flags<E>(lhs);\n\t\t}\n\n\t\t\/*!\n\t\t* \\brief Override binary AND operator on enum to turns into a Flags object.\n\t\t* \\return A Flags object with compare enum states.\n\t\t*\n\t\t* \\param lhs First enumeration value to compare.\n\t\t* \\param rhs Second enumeration value to compare.\n\t\t*\n\t\t* Returns a Flags object with compared states from the two enumeration values.\n\t\t* In this case, only one flag will be enabled if both enumeration values are the same.\n\t\t*\/\n\t\ttemplate<typename E>\n\t\tconstexpr std::enable_if_t<IsEnumFlag<E>::value, Flags<E>> operator&(E lhs, E rhs)\n\t\t{\n\t\t\treturn Flags<E>(lhs) & rhs;\n\t\t}\n\n\t\t\/*!\n\t\t* \\brief Override binary OR operator on enum to turns into a Flags object.\n\t\t* \\return A Flags object with combined enum states.\n\t\t*\n\t\t* \\param lhs First enumeration value to combine.\n\t\t* \\param rhs Second enumeration value to combine.\n\t\t*\n\t\t* Returns a Flags object with combined states from the two enumeration values.\n\t\t*\/\n\t\ttemplate<typename E>\n\t\tconstexpr std::enable_if_t<IsEnumFlag<E>::value, Flags<E>> operator|(E lhs, E rhs)\n\t\t{\n\t\t\treturn Flags<E>(lhs) | rhs;\n\t\t}\n\n\t\t\/*!\n\t\t* \\brief Override binary XOR operator on enum to turns into a Flags object.\n\t\t* \\return A Flags object with XORed enum states.\n\t\t*\n\t\t* \\param lhs First enumeration value to compare.\n\t\t* \\param rhs Second enumeration value to compare.\n\t\t*\n\t\t* Returns a Flags object with XORed states from the two enumeration values.\n\t\t* In this case, two flags will be enabled if both the enumeration values are different.\n\t\t*\/\n\t\ttemplate<typename E>\n\t\tconstexpr std::enable_if_t<IsEnumFlag<E>::value, Flags<E>> operator^(E lhs, E rhs)\n\t\t{\n\t\t\treturn Flags<E>(lhs) ^ rhs;\n\t\t}\n\t}\n}\n\n#include <Nazara\/Core\/DebugOff.hpp>\n<commit_msg>Update Flags.inl<commit_after>\/\/ Copyright (C) 2017 Jérôme Leclercq\n\/\/ This file is part of the \"Nazara Engine - Core module\"\n\/\/ For conditions of distribution and use, see copyright notice in Config.hpp\n\n#include <Nazara\/Core\/Flags.hpp>\n#include <Nazara\/Core\/Debug.hpp>\n\nnamespace Nz\n{\n\t\/*!\n\t* \\ingroup core\n\t* \\class Nz::Flags\n\t* \\brief Core class used to combine enumeration values into flags bitfield\n\t*\/\n\n\t\/*!\n\t* \\brief Constructs a Flags object using a bitfield\n\t*\n\t* \\param value Bitfield to be used\n\t*\n\t* Uses a bitfield to builds the flag value. (e.g. if bit 0 is active, then Enum value 0 will be set as active).\n\t*\/\n\ttemplate<typename E>\n\tconstexpr Flags<E>::Flags(BitField value) :\n\tm_value(value)\n\t{\n\t}\n\n\t\/*!\n\t* \\brief Constructs a Flags object using an Enum value\n\t*\n\t* \\param enumVal enumVal\n\t*\n\t* Setup a Flags object with only one flag active (corresponding to the enum value passed as argument).\n\t*\/\n\ttemplate<typename E>\n\tconstexpr Flags<E>::Flags(E enumVal) :\n\tFlags(GetFlagValue(enumVal))\n\t{\n\t}\n\n\t\/*!\n\t* \\brief Tests if all flags from a Flags object are enabled\n\t* \\return True if all tested flags are enabled.\n\t*\/\n\ttemplate<typename E>\n\tconstexpr bool Flags<E>::Test(const Flags& flags) const\n\t{\n\t\treturn (m_value & flags.m_value) == flags.m_value;\n\t}\n\n\t\/*!\n\t* \\brief Tests any flag\n\t* \\return True if any flag is enabled.\n\t*\n\t* This will convert to a boolean value allowing to check if any flag is set.\n\t*\/\n\ttemplate<typename E>\n\tconstexpr Flags<E>::operator bool() const\n\t{\n\t\treturn m_value != 0;\n\t}\n\n\t\/*!\n\t* \\brief Converts to an integer\n\t* \\return Enabled flags as a integer\n\t*\n\t* This will only works if the integer type is large enough to store all flags states\n\t*\/\n\ttemplate<typename E>\n\ttemplate<typename T, typename>\n\tconstexpr Flags<E>::operator T() const\n\t{\n\t\treturn m_value;\n\t}\n\n\t\/*!\n\t* \\brief Reverse flag states\n\t* \\return Opposite enabled flags\n\t*\n\t* This will returns a copy of the Flags object with reversed flags states.\n\t*\/\n\ttemplate<typename E>\n\tconstexpr Flags<E> Flags<E>::operator~() const\n\t{\n\t\treturn Flags((~m_value) & ValueMask);\n\t}\n\n\t\/*!\n\t* \\brief Compare flag states\n\t* \\return Shared flags\n\t*\n\t* \\param rhs Flags to compare with.\n\t*\n\t* This will returns a copy of the Flags object with only enabled flags in common with the parameter\n\t*\/\n\ttemplate<typename E>\n\tconstexpr Flags<E> Flags<E>::operator&(const Flags& rhs) const\n\t{\n\t\treturn Flags(m_value & rhs.m_value);\n\t}\n\n\t\/*!\n\t* \\brief Combine flag states\n\t* \\return Combined flags\n\t*\n\t* This will returns a copy of the Flags object with combined flags from the parameter.\n\t*\n\t* \\param rhs Flags to combine with.\n\t*\/\n\ttemplate<typename E>\n\tconstexpr Flags<E> Flags<E>::operator|(const Flags& rhs) const\n\t{\n\t\treturn Flags(m_value | rhs.m_value);\n\t}\n\n\t\/*!\n\t* \\brief XOR flag states\n\t* \\return XORed flags.\n\t*\n\t* \\param rhs Flags to XOR with.\n\t*\n\t* This performs a XOR (Exclusive OR) on a copy of the flag object.\n\t* This will returns a copy of the object with disabled common flags and enabled unique ones.\n\t*\/\n\ttemplate<typename E>\n\tconstexpr Flags<E> Flags<E>::operator^(const Flags& rhs) const\n\t{\n\t\treturn Flags((m_value ^ rhs.m_value) & ValueMask);\n\t}\n\n\t\/*!\n\t* \\brief Check equality with flag object\n\t* \\return True if both flags objects have the same states.\n\t*\n\t* \\param rhs Flags to compare with.\n\t*\n\t* Compare two Flags object and returns true if the flag states are identical.\n\t*\/\n\ttemplate<typename E>\n\tconstexpr bool Flags<E>::operator==(const Flags& rhs) const\n\t{\n\t\treturn m_value == rhs.m_value;\n\t}\n\n\t\/*!\n\t* \\brief Check inequality with flag object\n\t* \\return True if both flags objects have different states.\n\t*\n\t* \\param rhs Flags to compare with.\n\t*\n\t* Compare two Flags object and returns true if the flag states are identical.\n\t*\/\n\ttemplate<typename E>\n\tconstexpr bool Flags<E>::operator!=(const Flags& rhs) const\n\t{\n\t\treturn !operator==(rhs);\n\t}\n\n\t\/*!\n\t* \\brief Combine flag states\n\t* \\return A reference to the object.\n\t*\n\t* \\param rhs Flags to combine with.\n\t*\n\t* This will enable flags which are enabled in parameter object and not in Flag object.\n\t*\/\n\ttemplate<typename E>\n\t\/*constexpr*\/ Flags<E>& Flags<E>::operator|=(const Flags& rhs)\n\t{\n\t\tm_value |= rhs.m_value;\n\n\t\treturn *this;\n\t}\n\n\t\/*!\n\t* \\brief Compare flag states\n\t* \\return A reference to the object.\n\t*\n\t* \\param rhs Flags to compare with.\n\t*\n\t* This will disable flags which are disabled in parameter object and enabled in Flag object (and vice-versa).\n\t*\/\n\ttemplate<typename E>\n\t\/*constexpr*\/ Flags<E>& Flags<E>::operator&=(const Flags& rhs)\n\t{\n\t\tm_value &= rhs.m_value;\n\n\t\treturn *this;\n\t}\n\n\t\/*!\n\t* \\brief XOR flag states\n\t* \\return A reference to the object.\n\t*\n\t* \\param rhs Flags to XOR with.\n\t*\n\t* This performs a XOR (Exclusive OR) on the flag object.\n\t* This will disable flags enabled in both Flags objects and enable those enabled in only one of the Flags objects.\n\t*\/\n\ttemplate<typename E>\n\t\/*constexpr*\/ Flags<E>& Flags<E>::operator^=(const Flags& rhs)\n\t{\n\t\tm_value ^= rhs.m_value;\n\t\tm_value &= ValueMask;\n\n\t\treturn *this;\n\t}\n\n\t\/*!\n\t* \\brief Returns a bitfield corresponding to an enum value.\n\t* \\return Bitfield representation of the enum value\n\t*\n\t* \\param enumValue Enumeration value to get as a bitfield.\n\t*\n\t* Internally, every enum option is turned into a bit, this function allows to get a bitfield with only the bit of the enumeration value enabled.\n\t*\/\n\ttemplate<typename E>\n\tconstexpr typename Flags<E>::BitField Flags<E>::GetFlagValue(E enumValue)\n\t{\n\t\treturn 1U << static_cast<BitField>(enumValue);\n\t}\n\n\t\/*!\n\t* \\brief Compare flag states\n\t* \\return Compared flags\n\t*\n\t* This will returns a copy of the Flags object compared with the enum state.\n\t*\n\t* \\param lhs Enum to compare with flags.\n\t* \\param rhs Flags object.\n\t*\/\n\ttemplate<typename E>\n\tconstexpr Flags<E> operator&(E lhs, Flags<E> rhs)\n\t{\n\t\treturn rhs & lhs;\n\t}\n\n\t\/*!\n\t* \\brief Combine flag states\n\t* \\return Combined flags\n\t*\n\t* This will returns a copy of the Flags object combined with the enum state.\n\t*\n\t* \\param lhs Enum to combine with flags.\n\t* \\param rhs Flags object.\n\t*\/\n\ttemplate<typename E>\n\tconstexpr Flags<E> operator|(E lhs, Flags<E> rhs)\n\t{\n\t\treturn rhs | lhs;\n\t}\n\n\t\/*!\n\t* \\brief XOR flag states\n\t* \\return XORed flags\n\t*\n\t* This will returns a copy of the Flags object XORed with the enum state.\n\t*\n\t* \\param lhs Enum to XOR with flags.\n\t* \\param rhs Flags object.\n\t*\/\n\ttemplate<typename E>\n\tconstexpr Flags<E> operator^(E lhs, Flags<E> rhs)\n\t{\n\t\treturn rhs ^ lhs;\n\t}\n\n\n\tnamespace FlagsOperators\n\t{\n\t\t\/*!\n\t\t* \\brief Override binary NOT operator on enum to turns into a Flags object.\n\t\t* \\return A Flags object with reversed bits.\n\t\t*\n\t\t* \\param lhs Enumeration value to reverse.\n\t\t*\n\t\t* Returns a Flags object with all state enabled except for the enum one.\n\t\t*\/\n\t\ttemplate<typename E>\n\t\tconstexpr std::enable_if_t<IsEnumFlag<E>::value, Flags<E>> operator~(E lhs)\n\t\t{\n\t\t\treturn ~Flags<E>(lhs);\n\t\t}\n\n\t\t\/*!\n\t\t* \\brief Override binary AND operator on enum to turns into a Flags object.\n\t\t* \\return A Flags object with compare enum states.\n\t\t*\n\t\t* \\param lhs First enumeration value to compare.\n\t\t* \\param rhs Second enumeration value to compare.\n\t\t*\n\t\t* Returns a Flags object with compared states from the two enumeration values.\n\t\t* In this case, only one flag will be enabled if both enumeration values are the same.\n\t\t*\/\n\t\ttemplate<typename E>\n\t\tconstexpr std::enable_if_t<IsEnumFlag<E>::value, Flags<E>> operator&(E lhs, E rhs)\n\t\t{\n\t\t\treturn Flags<E>(lhs) & rhs;\n\t\t}\n\n\t\t\/*!\n\t\t* \\brief Override binary OR operator on enum to turns into a Flags object.\n\t\t* \\return A Flags object with combined enum states.\n\t\t*\n\t\t* \\param lhs First enumeration value to combine.\n\t\t* \\param rhs Second enumeration value to combine.\n\t\t*\n\t\t* Returns a Flags object with combined states from the two enumeration values.\n\t\t*\/\n\t\ttemplate<typename E>\n\t\tconstexpr std::enable_if_t<IsEnumFlag<E>::value, Flags<E>> operator|(E lhs, E rhs)\n\t\t{\n\t\t\treturn Flags<E>(lhs) | rhs;\n\t\t}\n\n\t\t\/*!\n\t\t* \\brief Override binary XOR operator on enum to turns into a Flags object.\n\t\t* \\return A Flags object with XORed enum states.\n\t\t*\n\t\t* \\param lhs First enumeration value to compare.\n\t\t* \\param rhs Second enumeration value to compare.\n\t\t*\n\t\t* Returns a Flags object with XORed states from the two enumeration values.\n\t\t* In this case, two flags will be enabled if both the enumeration values are different.\n\t\t*\/\n\t\ttemplate<typename E>\n\t\tconstexpr std::enable_if_t<IsEnumFlag<E>::value, Flags<E>> operator^(E lhs, E rhs)\n\t\t{\n\t\t\treturn Flags<E>(lhs) ^ rhs;\n\t\t}\n\t}\n}\n\n#include <Nazara\/Core\/DebugOff.hpp>\n<|endoftext|>"} {"text":"<commit_before>\/\/ Time: ctor: O(n),\n\/\/ query: O(logn),\n\/\/ modify: O(logn)\n\/\/ Space: O(n)\n\n\/**\n * Definition of Interval:\n * classs Interval {\n * int start, end;\n * Interval(int start, int end) {\n * this->start = start;\n * this->end = end;\n * }\n *\/\n\n\/\/ Segment Tree solution.\nclass SegmentTreeSumNode {\npublic:\n int start, end;\n long long sum;\n SegmentTreeSumNode *left, *right;\n SegmentTreeSumNode(int start, int end, long long sum) {\n this->start = start;\n this->end = end;\n this->sum = sum;\n this->left = this->right = NULL;\n }\n};\n\nclass Solution {\npublic:\n \/* you may need to use some attributes here *\/\n SegmentTreeSumNode *root_;\n\n \/**\n * @param A: An integer vector\n *\/\n Solution(vector<int> A) {\n root_ = build(A, 0, A.size() - 1);\n }\n\n \/**\n * @param start, end: Indices\n * @return: The sum from start to end\n *\/\n long long query(int start, int end) {\n queryTree(root_, start, end);\n }\n\n \/**\n * @param index, value: modify A[index] to value.\n *\/\n void modify(int index, int value) {\n modifyTree(root_, index, value);\n }\n\n \/\/ Query Sum in given range.\n long long queryTree(SegmentTreeSumNode *root, int start, int end) {\n \/\/ Out of range.\n if (root == nullptr || root->start > end || root->end < start) {\n return 0;\n }\n\n \/\/ Current segment is totally within range [start, end]\n if (root->start >= start && root->end <= end) {\n return root->sum;\n }\n\n long long left = queryTree(root->left, start, end);\n long long right = queryTree(root->right, start, end);\n\n \/\/ Find sum in the children.\n return left + right;\n }\n\n\n void modifyTree(SegmentTreeSumNode *root, int index, int value) {\n \/\/ Out of range.\n if (root == nullptr || root->start > index || root->end < index) {\n return;\n }\n\n \/\/ Change the node's value with [index, index] to the new given value.\n if (root->start == index && root->end == index) {\n root->sum = value;\n return;\n }\n\n modifyTree(root->left, index, value);\n modifyTree(root->right, index, value);\n\n int left_sum = root->left != nullptr? root->left->sum : 0;\n int right_sum = root->right != nullptr? root->right->sum : 0;\n\n \/\/ Update sum.\n root->sum = left_sum + right_sum;\n }\n\n \/\/ Build segment tree.\n SegmentTreeSumNode *build(vector<int> &A, int start, int end) {\n if (start > end) {\n return nullptr;\n }\n\n \/\/ The root's start and end is given by build method.\n SegmentTreeSumNode *root = new SegmentTreeSumNode(start, end, 0);\n\n \/\/ If start equals to end, there will be no children for this node.\n if (start == end) {\n root->sum = A[start];\n return root;\n }\n\n \/\/ Left child: start=A.left, end=(A.left + A.right) \/ 2.\n root->left = build(A, start, (start + end) \/ 2);\n\n \/\/ Right child: start=(A.left + A.right) \/ 2 + 1, end=A.right.\n root->right = build(A, (start + end) \/ 2 + 1, end);\n\n long long left_sum = root->left != nullptr? root->left->sum : 0;\n long long right_sum = root->right != nullptr? root->right->sum : 0;\n\n \/\/ Update sum.\n root->sum = left_sum + right_sum;\n return root;\n }\n};\n\n\/\/ Time: ctor: O(n),\n\/\/ query: O(logn),\n\/\/ modify: O(logn)\n\/\/ Space: O(n)\n\/\/ Binary Indexed Tree (BIT) solution.\nclass Solution2 {\npublic:\n \/* you may need to use some attributes here *\/\n \n\n \/**\n * @param A: An integer vector\n *\/\n Solution(vector<int> A) : nums_(A) {\n bit_ = vector<int>(nums_.size() + 1);\n for (int i = 1; i < bit_.size(); ++i) {\n bit_[i] = A[i - 1] + bit_[i - 1];\n }\n for (int i = bit_.size() - 1; i >= 1; --i) {\n int last_i = i - (i & -i);\n bit_[i] -= bit_[last_i];\n }\n }\n \n \/**\n * @param start, end: Indices\n * @return: The sum from start to end\n *\/\n long long query(int start, int end) {\n int sum = sumRegion_bit(end);\n if (start > 0) {\n sum -= sumRegion_bit(start - 1);\n }\n return sum;\n }\n \n \/**\n * @param index, value: modify A[index] to value.\n *\/\n void modify(int index, int value) {\n if (value - nums_[index]) {\n add(index, value - nums_[index]);\n nums_[index] = value;\n }\n }\n\nprivate:\n vector<int> nums_;\n vector<int> bit_;\n\n int sumRegion_bit(int i) {\n ++i;\n int sum = 0;\n for (; i > 0; i -= lower_bit(i)) {\n sum += bit_[i];\n }\n return sum;\n }\n\n void add(int i, int val) {\n ++i;\n for (; i <= nums_.size(); i += lower_bit(i)) {\n bit_[i] += val;\n }\n }\n\n int lower_bit(int i) {\n return i & -i;\n }\n};\n\n\n<commit_msg>Update interval-sum-ii.cpp<commit_after>\/\/ Time: ctor: O(n),\n\/\/ query: O(logn),\n\/\/ modify: O(logn)\n\/\/ Space: O(n)\n\n\/**\n * Definition of Interval:\n * classs Interval {\n * int start, end;\n * Interval(int start, int end) {\n * this->start = start;\n * this->end = end;\n * }\n *\/\n\n\/\/ Segment Tree solution.\nclass SegmentTreeSumNode {\npublic:\n int start, end;\n long long sum;\n SegmentTreeSumNode *left, *right;\n SegmentTreeSumNode(int start, int end, long long sum) {\n this->start = start;\n this->end = end;\n this->sum = sum;\n this->left = this->right = NULL;\n }\n};\n\nclass Solution {\npublic:\n \/* you may need to use some attributes here *\/\n SegmentTreeSumNode *root_;\n\n \/**\n * @param A: An integer vector\n *\/\n Solution(vector<int> A) {\n root_ = build(A, 0, A.size() - 1);\n }\n\n \/**\n * @param start, end: Indices\n * @return: The sum from start to end\n *\/\n long long query(int start, int end) {\n queryTree(root_, start, end);\n }\n\n \/**\n * @param index, value: modify A[index] to value.\n *\/\n void modify(int index, int value) {\n modifyTree(root_, index, value);\n }\n\n \/\/ Query Sum in given range.\n long long queryTree(SegmentTreeSumNode *root, int start, int end) {\n \/\/ Out of range.\n if (root == nullptr || root->start > end || root->end < start) {\n return 0;\n }\n\n \/\/ Current segment is totally within range [start, end]\n if (root->start >= start && root->end <= end) {\n return root->sum;\n }\n\n long long left = queryTree(root->left, start, end);\n long long right = queryTree(root->right, start, end);\n\n \/\/ Find sum in the children.\n return left + right;\n }\n\n\n void modifyTree(SegmentTreeSumNode *root, int index, int value) {\n \/\/ Out of range.\n if (root == nullptr || root->start > index || root->end < index) {\n return;\n }\n\n \/\/ Change the node's value with [index, index] to the new given value.\n if (root->start == index && root->end == index) {\n root->sum = value;\n return;\n }\n\n modifyTree(root->left, index, value);\n modifyTree(root->right, index, value);\n\n int left_sum = root->left != nullptr? root->left->sum : 0;\n int right_sum = root->right != nullptr? root->right->sum : 0;\n\n \/\/ Update sum.\n root->sum = left_sum + right_sum;\n }\n\n \/\/ Build segment tree.\n SegmentTreeSumNode *build(vector<int> &A, int start, int end) {\n if (start > end) {\n return nullptr;\n }\n\n \/\/ The root's start and end is given by build method.\n SegmentTreeSumNode *root = new SegmentTreeSumNode(start, end, 0);\n\n \/\/ If start equals to end, there will be no children for this node.\n if (start == end) {\n root->sum = A[start];\n return root;\n }\n\n \/\/ Left child: start=A.left, end=(A.left + A.right) \/ 2.\n root->left = build(A, start, (start + end) \/ 2);\n\n \/\/ Right child: start=(A.left + A.right) \/ 2 + 1, end=A.right.\n root->right = build(A, (start + end) \/ 2 + 1, end);\n\n long long left_sum = root->left != nullptr? root->left->sum : 0;\n long long right_sum = root->right != nullptr? root->right->sum : 0;\n\n \/\/ Update sum.\n root->sum = left_sum + right_sum;\n return root;\n }\n};\n\n\/\/ Time: ctor: O(n),\n\/\/ query: O(logn),\n\/\/ modify: O(logn)\n\/\/ Space: O(n)\n\/\/ Binary Indexed Tree (BIT) solution.\nclass Solution2 {\npublic:\n \/* you may need to use some attributes here *\/\n \n\n \/**\n * @param A: An integer vector\n *\/\n Solution(vector<int> A) : nums_(A) {\n bit_ = vector<int>(nums_.size() + 1);\n for (int i = 1; i < bit_.size(); ++i) {\n bit_[i] = A[i - 1] + bit_[i - 1];\n }\n for (int i = bit_.size() - 1; i >= 1; --i) {\n int last_i = i - lower_bit(i);\n bit_[i] -= bit_[last_i];\n }\n }\n \n \/**\n * @param start, end: Indices\n * @return: The sum from start to end\n *\/\n long long query(int start, int end) {\n int sum = sumRegion_bit(end);\n if (start > 0) {\n sum -= sumRegion_bit(start - 1);\n }\n return sum;\n }\n \n \/**\n * @param index, value: modify A[index] to value.\n *\/\n void modify(int index, int value) {\n if (value - nums_[index]) {\n add(index, value - nums_[index]);\n nums_[index] = value;\n }\n }\n\nprivate:\n vector<int> nums_;\n vector<int> bit_;\n\n int sumRegion_bit(int i) {\n ++i;\n int sum = 0;\n for (; i > 0; i -= lower_bit(i)) {\n sum += bit_[i];\n }\n return sum;\n }\n\n void add(int i, int val) {\n ++i;\n for (; i <= nums_.size(); i += lower_bit(i)) {\n bit_[i] += val;\n }\n }\n\n int lower_bit(int i) {\n return i & -i;\n }\n};\n\n\n<|endoftext|>"} {"text":"<commit_before>#pragma once\n\n#include <atomic>\n#include <brynet\/base\/Noexcept.hpp>\n#include <chrono>\n#include <functional>\n#include <memory>\n#include <mutex>\n#include <queue>\n#include <vector>\n\nnamespace brynet { namespace base {\n\nclass TimerMgr;\n\nclass Timer final\n{\npublic:\n using Ptr = std::shared_ptr<Timer>;\n using WeakPtr = std::weak_ptr<Timer>;\n using Callback = std::function<void(void)>;\n\n Timer(std::chrono::steady_clock::time_point startTime,\n std::chrono::nanoseconds lastTime,\n Callback&& callback) BRYNET_NOEXCEPT\n : mCallback(std::move(callback)),\n mStartTime(startTime),\n mLastTime(lastTime)\n {\n }\n\n const std::chrono::steady_clock::time_point& getStartTime() const\n {\n return mStartTime;\n }\n\n const std::chrono::nanoseconds& getLastTime() const\n {\n return mLastTime;\n }\n\n std::chrono::nanoseconds getLeftTime() const\n {\n const auto now = std::chrono::steady_clock::now();\n return getLastTime() - (now - getStartTime());\n }\n\n void cancel()\n {\n std::call_once(mExecuteOnceFlag, [this]() {\n mCallback = nullptr;\n });\n }\n\nprivate:\n void operator()()\n {\n Callback callback;\n std::call_once(mExecuteOnceFlag, [&callback, this]() {\n callback = std::move(mCallback);\n mCallback = nullptr;\n });\n\n if (callback != nullptr)\n {\n callback();\n }\n }\n\nprivate:\n std::once_flag mExecuteOnceFlag;\n Callback mCallback;\n const std::chrono::steady_clock::time_point mStartTime;\n const std::chrono::nanoseconds mLastTime;\n\n friend class TimerMgr;\n};\n\nclass RepeatTimer\n{\npublic:\n using Ptr = std::shared_ptr<RepeatTimer>;\n\n void cancel()\n {\n mCancel.store(true);\n }\n\n bool isCancel() const\n {\n return mCancel.load();\n }\n\nprivate:\n std::atomic_bool mCancel = {false};\n};\n\nclass TimerMgr final : public std::enable_shared_from_this<TimerMgr>\n{\npublic:\n using Ptr = std::shared_ptr<TimerMgr>;\n\n template<typename F, typename... TArgs>\n Timer::WeakPtr addTimer(\n std::chrono::nanoseconds timeout,\n F&& callback,\n TArgs&&... args)\n {\n auto timer = std::make_shared<Timer>(\n std::chrono::steady_clock::now(),\n std::chrono::nanoseconds(timeout),\n std::bind(std::forward<F>(callback), std::forward<TArgs>(args)...));\n mTimers.push(timer);\n\n return timer;\n }\n\n template<typename F, typename... TArgs>\n RepeatTimer::Ptr addIntervalTimer(\n std::chrono::nanoseconds interval,\n F&& callback,\n TArgs&&... args)\n {\n auto sharedThis = shared_from_this();\n auto repeatTimer = std::make_shared<RepeatTimer>();\n auto wrapperCallback = std::bind(std::forward<F>(callback), std::forward<TArgs>(args)...);\n addTimer(interval, [sharedThis, interval, wrapperCallback, repeatTimer]() {\n stubRepeatTimerCallback(sharedThis, interval, wrapperCallback, repeatTimer);\n });\n\n return repeatTimer;\n }\n\n void addTimer(const Timer::Ptr& timer)\n {\n mTimers.push(timer);\n }\n\n void schedule()\n {\n while (!mTimers.empty())\n {\n auto tmp = mTimers.top();\n if (tmp->getLeftTime() > std::chrono::nanoseconds::zero())\n {\n break;\n }\n\n mTimers.pop();\n (*tmp)();\n }\n }\n\n bool isEmpty() const\n {\n return mTimers.empty();\n }\n\n \/\/ if timer empty, return zero\n std::chrono::nanoseconds nearLeftTime() const\n {\n if (mTimers.empty())\n {\n return std::chrono::nanoseconds::zero();\n }\n\n auto result = mTimers.top()->getLeftTime();\n if (result < std::chrono::nanoseconds::zero())\n {\n return std::chrono::nanoseconds::zero();\n }\n\n return result;\n }\n\n void clear()\n {\n while (!mTimers.empty())\n {\n mTimers.pop();\n }\n }\n\nprivate:\n static void stubRepeatTimerCallback(TimerMgr::Ptr timerMgr,\n std::chrono::nanoseconds interval,\n std::function<void()> callback,\n RepeatTimer::Ptr repeatTimer)\n {\n if (repeatTimer->isCancel())\n {\n return;\n }\n callback();\n timerMgr->addTimer(interval, [timerMgr, interval, callback, repeatTimer]() {\n stubRepeatTimerCallback(timerMgr, interval, callback, repeatTimer);\n });\n }\n\nprivate:\n class CompareTimer\n {\n public:\n bool operator()(const Timer::Ptr& left,\n const Timer::Ptr& right) const\n {\n const auto startDiff = left->getStartTime() - right->getStartTime();\n const auto lastDiff = left->getLastTime() - right->getLastTime();\n const auto diff = startDiff.count() + lastDiff.count();\n return diff > 0;\n }\n };\n\n std::priority_queue<Timer::Ptr, std::vector<Timer::Ptr>, CompareTimer> mTimers;\n};\n\n}}\/\/ namespace brynet::base\n<commit_msg>fix compiler in C++ 11<commit_after>#pragma once\n\n#include <atomic>\n#include <brynet\/base\/Noexcept.hpp>\n#include <chrono>\n#include <functional>\n#include <memory>\n#include <mutex>\n#include <queue>\n#include <vector>\n\nnamespace brynet { namespace base {\n\nclass TimerMgr;\n\nclass Timer final\n{\npublic:\n using Ptr = std::shared_ptr<Timer>;\n using WeakPtr = std::weak_ptr<Timer>;\n using Callback = std::function<void(void)>;\n\n Timer(std::chrono::steady_clock::time_point startTime,\n std::chrono::nanoseconds lastTime,\n Callback&& callback) BRYNET_NOEXCEPT\n : mCallback(std::move(callback)),\n mStartTime(startTime),\n mLastTime(lastTime)\n {\n }\n\n const std::chrono::steady_clock::time_point& getStartTime() const\n {\n return mStartTime;\n }\n\n const std::chrono::nanoseconds& getLastTime() const\n {\n return mLastTime;\n }\n\n std::chrono::nanoseconds getLeftTime() const\n {\n const auto now = std::chrono::steady_clock::now();\n return getLastTime() - (now - getStartTime());\n }\n\n void cancel()\n {\n std::call_once(mExecuteOnceFlag, [this]() {\n mCallback = nullptr;\n });\n }\n\nprivate:\n void operator()()\n {\n Callback callback;\n std::call_once(mExecuteOnceFlag, [&callback, this]() {\n callback = std::move(mCallback);\n mCallback = nullptr;\n });\n\n if (callback != nullptr)\n {\n callback();\n }\n }\n\nprivate:\n std::once_flag mExecuteOnceFlag;\n Callback mCallback;\n const std::chrono::steady_clock::time_point mStartTime;\n const std::chrono::nanoseconds mLastTime;\n\n friend class TimerMgr;\n};\n\nclass RepeatTimer\n{\npublic:\n using Ptr = std::shared_ptr<RepeatTimer>;\n\n RepeatTimer()\n {\n mCancel.store(false);\n }\n\n void cancel()\n {\n mCancel.store(true);\n }\n\n bool isCancel() const\n {\n return mCancel.load();\n }\n\nprivate:\n std::atomic_bool mCancel;\n};\n\nclass TimerMgr final : public std::enable_shared_from_this<TimerMgr>\n{\npublic:\n using Ptr = std::shared_ptr<TimerMgr>;\n\n template<typename F, typename... TArgs>\n Timer::WeakPtr addTimer(\n std::chrono::nanoseconds timeout,\n F&& callback,\n TArgs&&... args)\n {\n auto timer = std::make_shared<Timer>(\n std::chrono::steady_clock::now(),\n std::chrono::nanoseconds(timeout),\n std::bind(std::forward<F>(callback), std::forward<TArgs>(args)...));\n mTimers.push(timer);\n\n return timer;\n }\n\n template<typename F, typename... TArgs>\n RepeatTimer::Ptr addIntervalTimer(\n std::chrono::nanoseconds interval,\n F&& callback,\n TArgs&&... args)\n {\n auto sharedThis = shared_from_this();\n auto repeatTimer = std::make_shared<RepeatTimer>();\n auto wrapperCallback = std::bind(std::forward<F>(callback), std::forward<TArgs>(args)...);\n addTimer(interval, [sharedThis, interval, wrapperCallback, repeatTimer]() {\n stubRepeatTimerCallback(sharedThis, interval, wrapperCallback, repeatTimer);\n });\n\n return repeatTimer;\n }\n\n void addTimer(const Timer::Ptr& timer)\n {\n mTimers.push(timer);\n }\n\n void schedule()\n {\n while (!mTimers.empty())\n {\n auto tmp = mTimers.top();\n if (tmp->getLeftTime() > std::chrono::nanoseconds::zero())\n {\n break;\n }\n\n mTimers.pop();\n (*tmp)();\n }\n }\n\n bool isEmpty() const\n {\n return mTimers.empty();\n }\n\n \/\/ if timer empty, return zero\n std::chrono::nanoseconds nearLeftTime() const\n {\n if (mTimers.empty())\n {\n return std::chrono::nanoseconds::zero();\n }\n\n auto result = mTimers.top()->getLeftTime();\n if (result < std::chrono::nanoseconds::zero())\n {\n return std::chrono::nanoseconds::zero();\n }\n\n return result;\n }\n\n void clear()\n {\n while (!mTimers.empty())\n {\n mTimers.pop();\n }\n }\n\nprivate:\n static void stubRepeatTimerCallback(TimerMgr::Ptr timerMgr,\n std::chrono::nanoseconds interval,\n std::function<void()> callback,\n RepeatTimer::Ptr repeatTimer)\n {\n if (repeatTimer->isCancel())\n {\n return;\n }\n callback();\n timerMgr->addTimer(interval, [timerMgr, interval, callback, repeatTimer]() {\n stubRepeatTimerCallback(timerMgr, interval, callback, repeatTimer);\n });\n }\n\nprivate:\n class CompareTimer\n {\n public:\n bool operator()(const Timer::Ptr& left,\n const Timer::Ptr& right) const\n {\n const auto startDiff = left->getStartTime() - right->getStartTime();\n const auto lastDiff = left->getLastTime() - right->getLastTime();\n const auto diff = startDiff.count() + lastDiff.count();\n return diff > 0;\n }\n };\n\n std::priority_queue<Timer::Ptr, std::vector<Timer::Ptr>, CompareTimer> mTimers;\n};\n\n}}\/\/ namespace brynet::base\n<|endoftext|>"} {"text":"<commit_before>\/*\n * eos - A 3D Morphable Model fitting library written in modern C++11\/14.\n *\n * File: include\/eos\/core\/read_obj.hpp\n *\n * Copyright 2017, 2018 Patrik Huber\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n#pragma once\n\n#ifndef EOS_READ_OBJ_HPP\n#define EOS_READ_OBJ_HPP\n\n#include \"eos\/core\/Mesh.hpp\"\n#include \"eos\/cpp17\/optional.hpp\"\n\n#include \"Eigen\/Core\"\n\n#include <cassert>\n#include <fstream>\n#include <string>\n#include <tuple>\n#include <utility>\n#include <vector>\n\nnamespace eos {\nnamespace core {\n\nnamespace detail {\n\n\/**\n * @brief Splits a string into a list of tokens.\n *\n * Taken from: https:\/\/stackoverflow.com\/a\/1493195\/1345959\n *\/\ntemplate <class ContainerType>\nvoid tokenize(const std::string& str, ContainerType& tokens, const std::string& delimiters = \" \",\n bool trim_empty = false)\n{\n std::string::size_type pos, last_pos = 0;\n const auto length = str.length();\n\n using value_type = typename ContainerType::value_type;\n using size_type = typename ContainerType::size_type;\n\n while (last_pos < length + 1)\n {\n pos = str.find_first_of(delimiters, last_pos);\n if (pos == std::string::npos)\n {\n pos = length;\n }\n\n if (pos != last_pos || !trim_empty)\n tokens.push_back(value_type(str.data() + last_pos, (size_type)pos - last_pos));\n\n last_pos = pos + 1;\n }\n};\n\n\/**\n * @brief Parse a line starting with 'v ' from an obj file.\n *\n * Can contain either 3 ('x y z') or 6 ('x y z r g b') numbers.\n * The 'v ' should have already been stripped from \\p line.\n *\n * Notes:\n * Could actually potentially consist of 3, 4, 6 or 7 elements? (xyz, xyzw,\n * xyzrgb, xyzwrgb)\n * assimp only deals with 3, 4 or 6 elements:\n * https:\/\/github.com\/assimp\/assimp\/blob\/master\/code\/ObjFileParser.cpp#L138\n *\n * For now, we don't support obj's containing homogeneous coordinates.\n * What we could do is that if we do encounter homogeneous coords, we could just divide by 'w', like assimp\n * does.\n *\n * Another obj parser we can check: https:\/\/github.com\/qnzhou\/PyMesh\/blob\/master\/src\/IO\/OBJParser.cpp (and\n * same file with .h)\n *\/\ninline std::pair<Eigen::Vector3f, cpp17::optional<Eigen::Vector3f>> parse_vertex(const std::string& line)\n{\n std::vector<std::string> tokens;\n tokenize(line, tokens, \" \");\n if (tokens.size() != 3 && tokens.size() != 6)\n {\n throw std::runtime_error(\n \"Encountered a vertex ('v') line that does not consist of either 3 ('x y z') \"\n \"or 6 ('x y z r g b') numbers.\");\n }\n const Eigen::Vector3f vertex(std::stof(tokens[0]), std::stof(tokens[1]), std::stof(tokens[2]));\n cpp17::optional<Eigen::Vector3f> vertex_color;\n if (tokens.size() == 6)\n {\n vertex_color = Eigen::Vector3f(std::stof(tokens[3]), std::stof(tokens[4]), std::stof(tokens[5]));\n }\n return {vertex, vertex_color};\n};\n\n\/**\n * @brief Parse a line starting with 'vt ' from an obj file.\n *\n * A 'vt' line can contain either two ('u v') or three ('u v w') numbers. This parser currently only supports\n * 'u v'.\n *\/\ninline Eigen::Vector2f parse_texcoords(const std::string& line)\n{\n std::vector<std::string> tokens;\n tokenize(line, tokens, \" \");\n if (tokens.size() != 2)\n {\n throw std::runtime_error(\"Encountered a texture coordinates ('vt') line that does not consist of two \"\n \"('u v') numbers. 'u v w' is not supported.\");\n }\n const Eigen::Vector2f texcoords(std::stof(tokens[0]), std::stof(tokens[1]));\n return texcoords;\n};\n\n\/**\n * @brief Parse a line starting with 'vn ' from an obj file.\n *\n * This is currently not implemented yet, as eos::core::Mesh doesn't store vertex normals anyway.\n *\/\ninline void parse_vertex_normal(const std::string& line)\n{\n throw std::runtime_error(\"Parsing \\\"vn\\\" is not yet implemented.\");\n};\n\n\/**\n * @brief Parse a line starting with 'f ' from an obj file.\n *\n * Note: Indices in obj's start at 1, not at 0.\n *\n * A face line contains 3 entries for triangles, but can be quads (=4 entries), and potentially more.\n * They're triplets of: vertex, texture and normal indices. Some of them can be missing. E.g.:\n * f 1 2 3\n * f 3\/1 4\/2 5\/3\n * f 6\/4\/1 3\/5\/3 7\/6\/5\n * f 7\/\/1 8\/\/2 9\/\/3\n *\/\ninline auto parse_face(const std::string& line)\n{\n using std::string;\n using std::vector;\n\n \/\/ Obj indices are 1-based.\n vector<int> vertex_indices; \/\/ size() = 3 or 4\n vector<int> texture_indices; \/\/ size() = 3 or 4\n vector<int> normal_indices; \/\/ size() = 3 or 4\n\n vector<string> tokens;\n tokenize(line, tokens, \" \");\n if (tokens.size() != 3 && tokens.size() != 4)\n {\n \/\/ For now we need this to be 3 (triangles) or 4 (quads)\n throw std::runtime_error(\"Encountered a faces ('f') line that does not consist of three or four \"\n \"blocks of numbers. We currently only support 3 blocks (triangle meshes) \"\n \"and 4 blocks (quad meshes).\");\n }\n \/\/ Now for each of these tokens, we want to split on \"\/\":\n for (const auto& token : tokens)\n {\n vector<string> subtokens;\n tokenize(token, subtokens, \"\/\", false); \/\/ don't trim empty -if we do, we lose positional information.\n assert(subtokens.size() > 0 && subtokens.size() <= 3);\n\n \/\/ There should always be a vertex index:\n vertex_indices.push_back(std::stoi(subtokens[0]) - 1); \/\/ obj indices are 1-based, so we subtract one.\n\n if (subtokens.size() == 2)\n {\n \/\/ We've got texture coordinate indices as well:\n texture_indices.push_back(std::stoi(subtokens[1]) - 1);\n }\n\n if (subtokens.size() == 3)\n {\n \/\/ We've got either texcoord indices *and* normal indices, or just normal indices:\n if (!subtokens[1].empty())\n {\n \/\/ We do have texcoord indices\n texture_indices.push_back(std::stoi(subtokens[1]) - 1);\n }\n \/\/ And push_back the normal indices:\n normal_indices.push_back(std::stoi(subtokens[2]) - 1);\n \/\/ Note if we use normal indices in the future: It looked like they can be zero in some cases?\n }\n }\n\n return std::make_tuple(vertex_indices, texture_indices, normal_indices);\n};\n\n} \/* namespace detail *\/\n\n\/**\n * @brief Reads the given Wavefront .obj file into a \\c Mesh.\n *\n * https:\/\/en.wikipedia.org\/wiki\/Wavefront_.obj_file as of 22 August 2017.\n *\n * @param[in] filename Input filename (ending in \".obj\").\n * @return A Mesh with the data read from the obj file.\n *\/\ninline Mesh read_obj(std::string filename)\n{\n std::ifstream file(filename);\n if (!file)\n {\n throw std::runtime_error(std::string(\"Could not open obj file: \" + filename));\n }\n\n \/\/ We'll need these helper functions for the parsing:\n const auto starts_with = [](const std::string& input, const std::string& match) {\n return input.size() >= match.size() && std::equal(match.begin(), match.end(), input.begin());\n };\n\n \/* auto trim_left = [](const std::string& input, std::string pattern = \" \\t\") {\n auto first = input.find_first_not_of(pattern);\n if (first == std::string::npos)\n {\n return input;\n }\n return input.substr(first, input.size());\n }; *\/\n\n Mesh mesh;\n\n std::string line;\n while (getline(file, line))\n {\n if (starts_with(line, \"#\"))\n {\n continue;\n }\n\n if (starts_with(line, \"v \"))\n { \/\/ matching with a space so that it doesn't match 'vt'\n auto vertex_data =\n detail::parse_vertex(line.substr(2)); \/\/ pass the string without the first two characters\n mesh.vertices.push_back(\n Eigen::Vector3f(vertex_data.first[0], vertex_data.first[1], vertex_data.first[2]));\n if (vertex_data.second)\n { \/\/ there are vertex colours:\n mesh.colors.push_back(vertex_data.second.value());\n }\n }\n if (starts_with(line, \"vt \"))\n {\n const auto texcoords = detail::parse_texcoords(line.substr(3));\n mesh.texcoords.push_back(texcoords);\n }\n if (starts_with(line, \"vn \"))\n {\n \/\/ detail::parse_vertex_normal(line.substr(3));\n \/\/ Not handled yet, our Mesh class doesn't contain normals right now anyway.\n }\n \/\/ There's other things like \"vp \", which we don't handle\n if (starts_with(line, \"f \"))\n {\n auto face_data = detail::parse_face(line.substr(2));\n if (std::get<0>(face_data).size() == 3) \/\/ 3 triangle indices, nothing to do:\n {\n mesh.tvi.push_back(\n {std::get<0>(face_data)[0], std::get<0>(face_data)[1], std::get<0>(face_data)[2]});\n }\n \/\/ If their sizes are 4, we convert the quad to two triangles:\n \/\/ Actually I think MeshLab does the same, it shows the FaceWarehouse number of \"Faces\" as twice the \"f\" entries in the obj.\n else if (std::get<0>(face_data).size() == 4)\n {\n \/\/ Just create two faces with (quad[0], quad[1], quad[2]) and (quad[0], quad[2], quad[3]).\n mesh.tvi.push_back(\n {std::get<0>(face_data)[0], std::get<0>(face_data)[1], std::get<0>(face_data)[2]});\n mesh.tvi.push_back(\n {std::get<0>(face_data)[0], std::get<0>(face_data)[2], std::get<0>(face_data)[3]});\n }\n \/\/ We don't handle normal_indices for now.\n }\n \/\/ There can be other stuff in obj's like materials, named objects, etc., which are not handled here.\n }\n return mesh;\n}\n\n} \/* namespace core *\/\n} \/* namespace eos *\/\n\n#endif \/* EOS_READ_OBJ_HPP *\/\n<commit_msg>Simplify push_back<commit_after>\/*\n * eos - A 3D Morphable Model fitting library written in modern C++11\/14.\n *\n * File: include\/eos\/core\/read_obj.hpp\n *\n * Copyright 2017, 2018 Patrik Huber\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n#pragma once\n\n#ifndef EOS_READ_OBJ_HPP\n#define EOS_READ_OBJ_HPP\n\n#include \"eos\/core\/Mesh.hpp\"\n#include \"eos\/cpp17\/optional.hpp\"\n\n#include \"Eigen\/Core\"\n\n#include <cassert>\n#include <fstream>\n#include <string>\n#include <tuple>\n#include <utility>\n#include <vector>\n\nnamespace eos {\nnamespace core {\n\nnamespace detail {\n\n\/**\n * @brief Splits a string into a list of tokens.\n *\n * Taken from: https:\/\/stackoverflow.com\/a\/1493195\/1345959\n *\/\ntemplate <class ContainerType>\nvoid tokenize(const std::string& str, ContainerType& tokens, const std::string& delimiters = \" \",\n bool trim_empty = false)\n{\n std::string::size_type pos, last_pos = 0;\n const auto length = str.length();\n\n using value_type = typename ContainerType::value_type;\n using size_type = typename ContainerType::size_type;\n\n while (last_pos < length + 1)\n {\n pos = str.find_first_of(delimiters, last_pos);\n if (pos == std::string::npos)\n {\n pos = length;\n }\n\n if (pos != last_pos || !trim_empty)\n tokens.push_back(value_type(str.data() + last_pos, (size_type)pos - last_pos));\n\n last_pos = pos + 1;\n }\n};\n\n\/**\n * @brief Parse a line starting with 'v ' from an obj file.\n *\n * Can contain either 3 ('x y z') or 6 ('x y z r g b') numbers.\n * The 'v ' should have already been stripped from \\p line.\n *\n * Notes:\n * Could actually potentially consist of 3, 4, 6 or 7 elements? (xyz, xyzw,\n * xyzrgb, xyzwrgb)\n * assimp only deals with 3, 4 or 6 elements:\n * https:\/\/github.com\/assimp\/assimp\/blob\/master\/code\/ObjFileParser.cpp#L138\n *\n * For now, we don't support obj's containing homogeneous coordinates.\n * What we could do is that if we do encounter homogeneous coords, we could just divide by 'w', like assimp\n * does.\n *\n * Another obj parser we can check: https:\/\/github.com\/qnzhou\/PyMesh\/blob\/master\/src\/IO\/OBJParser.cpp (and\n * same file with .h)\n *\/\ninline std::pair<Eigen::Vector3f, cpp17::optional<Eigen::Vector3f>> parse_vertex(const std::string& line)\n{\n std::vector<std::string> tokens;\n tokenize(line, tokens, \" \");\n if (tokens.size() != 3 && tokens.size() != 6)\n {\n throw std::runtime_error(\n \"Encountered a vertex ('v') line that does not consist of either 3 ('x y z') \"\n \"or 6 ('x y z r g b') numbers.\");\n }\n const Eigen::Vector3f vertex(std::stof(tokens[0]), std::stof(tokens[1]), std::stof(tokens[2]));\n cpp17::optional<Eigen::Vector3f> vertex_color;\n if (tokens.size() == 6)\n {\n vertex_color = Eigen::Vector3f(std::stof(tokens[3]), std::stof(tokens[4]), std::stof(tokens[5]));\n }\n return {vertex, vertex_color};\n};\n\n\/**\n * @brief Parse a line starting with 'vt ' from an obj file.\n *\n * A 'vt' line can contain either two ('u v') or three ('u v w') numbers. This parser currently only supports\n * 'u v'.\n *\/\ninline Eigen::Vector2f parse_texcoords(const std::string& line)\n{\n std::vector<std::string> tokens;\n tokenize(line, tokens, \" \");\n if (tokens.size() != 2)\n {\n throw std::runtime_error(\"Encountered a texture coordinates ('vt') line that does not consist of two \"\n \"('u v') numbers. 'u v w' is not supported.\");\n }\n const Eigen::Vector2f texcoords(std::stof(tokens[0]), std::stof(tokens[1]));\n return texcoords;\n};\n\n\/**\n * @brief Parse a line starting with 'vn ' from an obj file.\n *\n * This is currently not implemented yet, as eos::core::Mesh doesn't store vertex normals anyway.\n *\/\ninline void parse_vertex_normal(const std::string& line)\n{\n throw std::runtime_error(\"Parsing \\\"vn\\\" is not yet implemented.\");\n};\n\n\/**\n * @brief Parse a line starting with 'f ' from an obj file.\n *\n * Note: Indices in obj's start at 1, not at 0.\n *\n * A face line contains 3 entries for triangles, but can be quads (=4 entries), and potentially more.\n * They're triplets of: vertex, texture and normal indices. Some of them can be missing. E.g.:\n * f 1 2 3\n * f 3\/1 4\/2 5\/3\n * f 6\/4\/1 3\/5\/3 7\/6\/5\n * f 7\/\/1 8\/\/2 9\/\/3\n *\/\ninline auto parse_face(const std::string& line)\n{\n using std::string;\n using std::vector;\n\n \/\/ Obj indices are 1-based.\n vector<int> vertex_indices; \/\/ size() = 3 or 4\n vector<int> texture_indices; \/\/ size() = 3 or 4\n vector<int> normal_indices; \/\/ size() = 3 or 4\n\n vector<string> tokens;\n tokenize(line, tokens, \" \");\n if (tokens.size() != 3 && tokens.size() != 4)\n {\n \/\/ For now we need this to be 3 (triangles) or 4 (quads)\n throw std::runtime_error(\"Encountered a faces ('f') line that does not consist of three or four \"\n \"blocks of numbers. We currently only support 3 blocks (triangle meshes) \"\n \"and 4 blocks (quad meshes).\");\n }\n \/\/ Now for each of these tokens, we want to split on \"\/\":\n for (const auto& token : tokens)\n {\n vector<string> subtokens;\n tokenize(token, subtokens, \"\/\", false); \/\/ don't trim empty -if we do, we lose positional information.\n assert(subtokens.size() > 0 && subtokens.size() <= 3);\n\n \/\/ There should always be a vertex index:\n vertex_indices.push_back(std::stoi(subtokens[0]) - 1); \/\/ obj indices are 1-based, so we subtract one.\n\n if (subtokens.size() == 2)\n {\n \/\/ We've got texture coordinate indices as well:\n texture_indices.push_back(std::stoi(subtokens[1]) - 1);\n }\n\n if (subtokens.size() == 3)\n {\n \/\/ We've got either texcoord indices *and* normal indices, or just normal indices:\n if (!subtokens[1].empty())\n {\n \/\/ We do have texcoord indices\n texture_indices.push_back(std::stoi(subtokens[1]) - 1);\n }\n \/\/ And push_back the normal indices:\n normal_indices.push_back(std::stoi(subtokens[2]) - 1);\n \/\/ Note if we use normal indices in the future: It looked like they can be zero in some cases?\n }\n }\n\n return std::make_tuple(vertex_indices, texture_indices, normal_indices);\n};\n\n} \/* namespace detail *\/\n\n\/**\n * @brief Reads the given Wavefront .obj file into a \\c Mesh.\n *\n * https:\/\/en.wikipedia.org\/wiki\/Wavefront_.obj_file as of 22 August 2017.\n *\n * @param[in] filename Input filename (ending in \".obj\").\n * @return A Mesh with the data read from the obj file.\n *\/\ninline Mesh read_obj(std::string filename)\n{\n std::ifstream file(filename);\n if (!file)\n {\n throw std::runtime_error(std::string(\"Could not open obj file: \" + filename));\n }\n\n \/\/ We'll need these helper functions for the parsing:\n const auto starts_with = [](const std::string& input, const std::string& match) {\n return input.size() >= match.size() && std::equal(match.begin(), match.end(), input.begin());\n };\n\n \/* auto trim_left = [](const std::string& input, std::string pattern = \" \\t\") {\n auto first = input.find_first_not_of(pattern);\n if (first == std::string::npos)\n {\n return input;\n }\n return input.substr(first, input.size());\n }; *\/\n\n Mesh mesh;\n\n std::string line;\n while (getline(file, line))\n {\n if (starts_with(line, \"#\"))\n {\n continue;\n }\n\n if (starts_with(line, \"v \"))\n { \/\/ matching with a space so that it doesn't match 'vt'\n auto vertex_data =\n detail::parse_vertex(line.substr(2)); \/\/ pass the string without the first two characters\n mesh.vertices.push_back(vertex_data.first);\n if (vertex_data.second)\n { \/\/ there are vertex colours:\n mesh.colors.push_back(vertex_data.second.value());\n }\n }\n if (starts_with(line, \"vt \"))\n {\n const auto texcoords = detail::parse_texcoords(line.substr(3));\n mesh.texcoords.push_back(texcoords);\n }\n if (starts_with(line, \"vn \"))\n {\n \/\/ detail::parse_vertex_normal(line.substr(3));\n \/\/ Not handled yet, our Mesh class doesn't contain normals right now anyway.\n }\n \/\/ There's other things like \"vp \", which we don't handle\n if (starts_with(line, \"f \"))\n {\n auto face_data = detail::parse_face(line.substr(2));\n if (std::get<0>(face_data).size() == 3) \/\/ 3 triangle indices, nothing to do:\n {\n mesh.tvi.push_back(\n {std::get<0>(face_data)[0], std::get<0>(face_data)[1], std::get<0>(face_data)[2]});\n }\n \/\/ If their sizes are 4, we convert the quad to two triangles:\n \/\/ Actually I think MeshLab does the same, it shows the FaceWarehouse number of \"Faces\" as twice the \"f\" entries in the obj.\n else if (std::get<0>(face_data).size() == 4)\n {\n \/\/ Just create two faces with (quad[0], quad[1], quad[2]) and (quad[0], quad[2], quad[3]).\n mesh.tvi.push_back(\n {std::get<0>(face_data)[0], std::get<0>(face_data)[1], std::get<0>(face_data)[2]});\n mesh.tvi.push_back(\n {std::get<0>(face_data)[0], std::get<0>(face_data)[2], std::get<0>(face_data)[3]});\n }\n \/\/ We don't handle normal_indices for now.\n }\n \/\/ There can be other stuff in obj's like materials, named objects, etc., which are not handled here.\n }\n return mesh;\n}\n\n} \/* namespace core *\/\n} \/* namespace eos *\/\n\n#endif \/* EOS_READ_OBJ_HPP *\/\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: cachedprimitivebase.hxx,v $\n *\n * $Revision: 1.2 $\n *\n * last change: $Author: kz $ $Date: 2005-11-02 12:41:56 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef INCLUDED_CANVAS_CACHEDPRIMITIVEBASE_HXX\n#define INCLUDED_CANVAS_CACHEDPRIMITIVEBASE_HXX\n\n#ifndef _COM_SUN_STAR_UNO_REFERENCE_HXX_\n#include <com\/sun\/star\/uno\/Reference.hxx>\n#endif\n#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_\n#include <com\/sun\/star\/lang\/XServiceInfo.hpp>\n#endif\n#ifndef _COM_SUN_STAR_RENDERING_XCANVAS_HPP_\n#include <com\/sun\/star\/rendering\/XCanvas.hpp>\n#endif\n#ifndef _COM_SUN_STAR_RENDERING_XCACHEDPRIMITIVE_HPP_\n#include <com\/sun\/star\/rendering\/XCachedPrimitive.hpp>\n#endif\n#ifndef _COM_SUN_STAR_RENDERING_VIEWSTATE_HPP__\n#include <com\/sun\/star\/rendering\/ViewState.hpp>\n#endif\n\n#ifndef _CPPUHELPER_COMPBASE2_HXX_\n#include <cppuhelper\/compbase2.hxx>\n#endif\n#ifndef _COMPHELPER_BROADCASTHELPER_HXX_\n#include <comphelper\/broadcasthelper.hxx>\n#endif\n\n\n\/* Definition of CachedPrimitiveBase class *\/\n\nnamespace canvas\n{\n typedef ::cppu::WeakComponentImplHelper2< ::com::sun::star::rendering::XCachedPrimitive,\n ::com::sun::star::lang::XServiceInfo > CachedPrimitiveBase_Base;\n\n \/** Base class, providing common functionality for implementers of\n the XCachedPrimitive interface.\n *\/\n class CachedPrimitiveBase : public CachedPrimitiveBase_Base,\n public ::comphelper::OBaseMutex\n {\n public:\n\n \/** Create an XCachedPrimitive for given target canvas\n\n @param rUsedViewState\n The viewstate the original object was rendered with\n\n @param rTarget\n The target canvas the repaint should happen on.\n\n @param bFailForChangedViewTransform\n When true, derived classes will never receive doRedraw()\n calls with dissimilar view transformations and\n bSameViewTransform set to false. This is useful for cached\n objects where re-transforming the generated output is not\n desirable, e.g. for hinted font output.\n *\/\n CachedPrimitiveBase( const ::com::sun::star::rendering::ViewState& rUsedViewState,\n const ::com::sun::star::uno::Reference<\n ::com::sun::star::rendering::XCanvas >& rTarget,\n bool bFailForChangedViewTransform );\n\n \/\/\/ Dispose all internal references\n virtual void SAL_CALL disposing();\n\n \/\/ XCachedPrimitive\n virtual ::sal_Int8 SAL_CALL redraw( const ::com::sun::star::rendering::ViewState& aState ) throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException);\n\n \/\/ XServiceInfo\n virtual ::rtl::OUString SAL_CALL getImplementationName( ) throw (::com::sun::star::uno::RuntimeException);\n virtual sal_Bool SAL_CALL supportsService( const ::rtl::OUString& ServiceName ) throw (::com::sun::star::uno::RuntimeException);\n virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames( ) throw (::com::sun::star::uno::RuntimeException);\n\n protected:\n ~CachedPrimitiveBase(); \/\/ we're a ref-counted UNO class. _We_ destroy ourselves.\n\n private:\n CachedPrimitiveBase( const CachedPrimitiveBase& );\n CachedPrimitiveBase& operator=( const CachedPrimitiveBase& );\n\n \/** Actually perform the requested redraw.\n\n Clients must override this method, instead of the public\n redraw() one.\n\n @param rNewState\n The viewstate to redraw with\n\n @param rOldState\n The viewstate this cache object was created with.\n\n @param rTargetCanvas\n Target canvas to render to.\n\n @param bSameViewTransform\n When true, rNewState and rOldState have the same transformation.\n *\/\n virtual ::sal_Int8 doRedraw( const ::com::sun::star::rendering::ViewState& rNewState,\n const ::com::sun::star::rendering::ViewState& rOldState,\n const ::com::sun::star::uno::Reference<\n ::com::sun::star::rendering::XCanvas >& rTargetCanvas,\n bool bSameViewTransform ) = 0;\n\n ::com::sun::star::rendering::ViewState maUsedViewState;\n ::com::sun::star::uno::Reference< ::com::sun::star::rendering::XCanvas > mxTarget;\n const bool mbFailForChangedViewTransform;\n };\n}\n\n#endif \/* INCLUDED_CANVAS_CACHEDPRIMITIVEBASE_HXX *\/\n<commit_msg>INTEGRATION: CWS changefileheader (1.2.136); FILE MERGED 2008\/04\/01 15:03:02 thb 1.2.136.3: #i85898# Stripping all external header guards 2008\/04\/01 10:49:25 thb 1.2.136.2: #i85898# Stripping all external header guards 2008\/03\/28 16:34:52 rt 1.2.136.1: #i87441# Change license header to LPGL v3.<commit_after>\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2008 by Sun Microsystems, Inc.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: cachedprimitivebase.hxx,v $\n * $Revision: 1.3 $\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * <http:\/\/www.openoffice.org\/license.html>\n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n#ifndef INCLUDED_CANVAS_CACHEDPRIMITIVEBASE_HXX\n#define INCLUDED_CANVAS_CACHEDPRIMITIVEBASE_HXX\n\n#include <com\/sun\/star\/uno\/Reference.hxx>\n#include <com\/sun\/star\/lang\/XServiceInfo.hpp>\n#include <com\/sun\/star\/rendering\/XCanvas.hpp>\n#include <com\/sun\/star\/rendering\/XCachedPrimitive.hpp>\n#include <com\/sun\/star\/rendering\/ViewState.hpp>\n#include <cppuhelper\/compbase2.hxx>\n#include <comphelper\/broadcasthelper.hxx>\n\n\n\/* Definition of CachedPrimitiveBase class *\/\n\nnamespace canvas\n{\n typedef ::cppu::WeakComponentImplHelper2< ::com::sun::star::rendering::XCachedPrimitive,\n ::com::sun::star::lang::XServiceInfo > CachedPrimitiveBase_Base;\n\n \/** Base class, providing common functionality for implementers of\n the XCachedPrimitive interface.\n *\/\n class CachedPrimitiveBase : public CachedPrimitiveBase_Base,\n public ::comphelper::OBaseMutex\n {\n public:\n\n \/** Create an XCachedPrimitive for given target canvas\n\n @param rUsedViewState\n The viewstate the original object was rendered with\n\n @param rTarget\n The target canvas the repaint should happen on.\n\n @param bFailForChangedViewTransform\n When true, derived classes will never receive doRedraw()\n calls with dissimilar view transformations and\n bSameViewTransform set to false. This is useful for cached\n objects where re-transforming the generated output is not\n desirable, e.g. for hinted font output.\n *\/\n CachedPrimitiveBase( const ::com::sun::star::rendering::ViewState& rUsedViewState,\n const ::com::sun::star::uno::Reference<\n ::com::sun::star::rendering::XCanvas >& rTarget,\n bool bFailForChangedViewTransform );\n\n \/\/\/ Dispose all internal references\n virtual void SAL_CALL disposing();\n\n \/\/ XCachedPrimitive\n virtual ::sal_Int8 SAL_CALL redraw( const ::com::sun::star::rendering::ViewState& aState ) throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException);\n\n \/\/ XServiceInfo\n virtual ::rtl::OUString SAL_CALL getImplementationName( ) throw (::com::sun::star::uno::RuntimeException);\n virtual sal_Bool SAL_CALL supportsService( const ::rtl::OUString& ServiceName ) throw (::com::sun::star::uno::RuntimeException);\n virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames( ) throw (::com::sun::star::uno::RuntimeException);\n\n protected:\n ~CachedPrimitiveBase(); \/\/ we're a ref-counted UNO class. _We_ destroy ourselves.\n\n private:\n CachedPrimitiveBase( const CachedPrimitiveBase& );\n CachedPrimitiveBase& operator=( const CachedPrimitiveBase& );\n\n \/** Actually perform the requested redraw.\n\n Clients must override this method, instead of the public\n redraw() one.\n\n @param rNewState\n The viewstate to redraw with\n\n @param rOldState\n The viewstate this cache object was created with.\n\n @param rTargetCanvas\n Target canvas to render to.\n\n @param bSameViewTransform\n When true, rNewState and rOldState have the same transformation.\n *\/\n virtual ::sal_Int8 doRedraw( const ::com::sun::star::rendering::ViewState& rNewState,\n const ::com::sun::star::rendering::ViewState& rOldState,\n const ::com::sun::star::uno::Reference<\n ::com::sun::star::rendering::XCanvas >& rTargetCanvas,\n bool bSameViewTransform ) = 0;\n\n ::com::sun::star::rendering::ViewState maUsedViewState;\n ::com::sun::star::uno::Reference< ::com::sun::star::rendering::XCanvas > mxTarget;\n const bool mbFailForChangedViewTransform;\n };\n}\n\n#endif \/* INCLUDED_CANVAS_CACHEDPRIMITIVEBASE_HXX *\/\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2015 ASMlover. All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions\n\/\/ are met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright\n\/\/ notice, this list ofconditions and the following disclaimer.\n\/\/\n\/\/ * Redistributions in binary form must reproduce the above copyright\n\/\/ notice, this list of conditions and the following disclaimer in\n\/\/ the documentation and\/or other materialsprovided with the\n\/\/ distribution.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\/\/ \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n\/\/ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n\/\/ FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n\/\/ COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n\/\/ INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n\/\/ BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n\/\/ LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n\/\/ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n\/\/ LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n\/\/ ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n\/\/ POSSIBILITY OF SUCH DAMAGE.\n#include \"..\/el_poll.h\"\n#include \"..\/el_internal.h\"\n#include \"el_linux_epoll.h\"\n\nnamespace el {\n\nEpoll::Epoll(void)\n : epoll_fd_(EL_NETINVAL)\n , event_count_(EVENT_COUNT)\n , events_(nullptr) {\n EL_ASSERT(Init(), \"linux epoll init failed ...\");\n}\n\nEpoll::~Epoll(void) {\n Destroy();\n}\n\nbool Epoll::Init(void) {\n if (EL_NETINVAL == (epoll_fd_ = epoll_create(EPOLL_COUNT)))\n return false;\n\n event_count_ = EVENT_COUNT;\n size_t size = sizeof(struct epoll_event) * event_count_;\n\n do {\n if (nullptr == (events_ = (struct epoll_event*)malloc(size)))\n break;\n\n return true;\n } while (0);\n\n Destroy();\n return false;\n}\n\nvoid Epoll::Destroy(void) {\n if (nullptr != events_) {\n free(events_);\n events_ = nullptr;\n }\n event_count_ = EVENT_COUNT;\n\n if (EL_NETINVAL != epoll_fd_) {\n close(epoll_fd_);\n epoll_fd_ = EL_NETINVAL;\n }\n}\n\nbool Epoll::Regrow(void) {\n uint32_t new_event_count = (0 != event_count_ ?\n 2 * event_count_ : EVENT_COUNT);\n size_t size = sizeof(struct epoll_event) * new_event_count;\n\n events_ = (struct epoll_event*)realloc(events_, size);\n EL_ASSERT(nullptr != events_, \"epoll regrow failed ...\");\n\n event_count_ = new_event_count;\n return true;\n}\n\nbool Epoll::Insert(Connector& c) {\n return true;\n}\n\nvoid Epoll::Remove(Connector& c) {\n}\n\nbool Epoll::AddEvent(Connector& c, EventType event) {\n return true;\n}\n\nbool Epoll::DelEvent(Connector& c, EventType event) {\n return true;\n}\n\nbool Epoll::Dispatch(Dispatcher& dispatcher, uint32_t timeout) {\n return true;\n}\n\n}\n<commit_msg>implementation of the epoll module for linux platform<commit_after>\/\/ Copyright (c) 2015 ASMlover. All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions\n\/\/ are met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright\n\/\/ notice, this list ofconditions and the following disclaimer.\n\/\/\n\/\/ * Redistributions in binary form must reproduce the above copyright\n\/\/ notice, this list of conditions and the following disclaimer in\n\/\/ the documentation and\/or other materialsprovided with the\n\/\/ distribution.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\/\/ \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n\/\/ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n\/\/ FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n\/\/ COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n\/\/ INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n\/\/ BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n\/\/ LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n\/\/ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n\/\/ LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n\/\/ ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n\/\/ POSSIBILITY OF SUCH DAMAGE.\n#include \"..\/el_poll.h\"\n#include \"..\/el_internal.h\"\n#include \"el_linux_epoll.h\"\n\nnamespace el {\n\nEpoll::Epoll(void)\n : epoll_fd_(EL_NETINVAL)\n , event_count_(EVENT_COUNT)\n , events_(nullptr) {\n EL_ASSERT(Init(), \"linux epoll init failed ...\");\n}\n\nEpoll::~Epoll(void) {\n Destroy();\n}\n\nbool Epoll::Init(void) {\n if (EL_NETINVAL == (epoll_fd_ = epoll_create(EPOLL_COUNT)))\n return false;\n\n event_count_ = EVENT_COUNT;\n size_t size = sizeof(struct epoll_event) * event_count_;\n\n do {\n if (nullptr == (events_ = (struct epoll_event*)malloc(size)))\n break;\n\n return true;\n } while (0);\n\n Destroy();\n return false;\n}\n\nvoid Epoll::Destroy(void) {\n if (nullptr != events_) {\n free(events_);\n events_ = nullptr;\n }\n event_count_ = EVENT_COUNT;\n\n if (EL_NETINVAL != epoll_fd_) {\n close(epoll_fd_);\n epoll_fd_ = EL_NETINVAL;\n }\n}\n\nbool Epoll::Regrow(void) {\n uint32_t new_event_count = (0 != event_count_ ?\n 2 * event_count_ : EVENT_COUNT);\n size_t size = sizeof(struct epoll_event) * new_event_count;\n\n events_ = (struct epoll_event*)realloc(events_, size);\n EL_ASSERT(nullptr != events_, \"epoll regrow failed ...\");\n\n event_count_ = new_event_count;\n return true;\n}\n\nbool Epoll::Insert(Connector& c) {\n struct epoll_event event;\n event.events = 0;\n event.data.ptr = &c;\n\n if (EL_NETERR == epoll_ctl(epoll_fd_,\n EPOLL_CTL_ADD, c.fd(), &event))\n return false;\n\n \/\/ add EPOLLET into connector\n \/\/ TODO:\n return true;\n}\n\nvoid Epoll::Remove(Connector& c) {\n struct epoll_event event;\n event.events = c.events();\n event.data.ptr = &c;\n\n epoll_ctl(epoll_fd_, EPOLL_CTL_DEL, c.fd(), &event);\n}\n\nbool Epoll::AddEvent(Connector& c, EventType event) {\n struct epoll_event add_event;\n add_event.events = c.events();\n add_event.data.ptr = &c;\n\n if (event == EventType::EVENTTYPE_READ)\n add_event.events |= EPOLLIN;\n if (event == EventType::EVENTTYPE_WRITE)\n add_event.events |= EPOLLOUT;\n\n if (EL_NETERR == epoll_ctl(epoll_fd_,\n EPOLL_CTL_MOD, c.fd(), &add_event))\n return false;\n\n \/\/ add add_event.events into connector\n \/\/ TODO:\n return true;\n}\n\nbool Epoll::DelEvent(Connector& c, EventType event) {\n struct epoll_event del_event;\n del_event.events = c.events();\n del_event.data.ptr = &c;\n\n if (event == EventType::EVENTTYPE_READ)\n del_event.events &= ~EPOLLIN;\n if (event == EventType::EVENTTYPE_WRITE)\n del_event.events &= ~EPOLLOUT;\n\n if (EL_NETERR == epoll_ctl(epoll_fd_,\n EPOLL_CTL_MOD, c.fd(), &del_event))\n return false;\n\n \/\/ add del_event.events into connector\n \/\/ TODO:\n return true;\n}\n\nbool Epoll::Dispatch(Dispatcher& dispatcher, uint32_t timeout) {\n int num = epoll_wait(epoll_fd_, events_, event_count_, timeout);\n if (EL_NETERR == num || 0 == num)\n return false;\n\n Connector* c;\n for (auto i = 0; i < num; ++i) {\n c = static_cast<Connector*>(events_[i].data.ptr);\n if (nullptr == c)\n continue;\n\n if (EL_NETINVAL == c->fd())\n continue;\n if (events_[i].events & EPOLLIN)\n dispather.DispatchReader(*this, *c);\n\n if (EL_NETINVAL == c->fd())\n continue;\n if (events_[i].events & EPOLLOUT)\n dispatcher.DispatchWriter(*this, *c);\n }\n\n if (static_cast<uint32_t>(num) == event_count_)\n Regrow();\n\n return true;\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/** \n * @file llfloatersearch.cpp\n * @author Martin Reddy\n * @brief Search floater - uses an embedded web browser control\n *\n * $LicenseInfo:firstyear=2009&license=viewerlgpl$\n * Second Life Viewer Source Code\n * Copyright (C) 2010, Linden Research, Inc.\n * \n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation;\n * version 2.1 of the License only.\n * \n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n * \n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n * \n * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA\n * $\/LicenseInfo$\n *\/\n\n#include \"llviewerprecompiledheaders.h\"\n\n#include \"llcommandhandler.h\"\n#include \"llfloaterreg.h\"\n#include \"llfloatersearch.h\"\n#include \"llmediactrl.h\"\n#include \"lllogininstance.h\"\n#include \"lluri.h\"\n#include \"llagent.h\"\n#include \"llui.h\"\n#include \"llviewercontrol.h\"\n#include \"llweb.h\"\n\n\/\/ support secondlife:\/\/\/app\/search\/{CATEGORY}\/{QUERY} SLapps\nclass LLSearchHandler : public LLCommandHandler\n{\npublic:\n\t\/\/ requires trusted browser to trigger\n\tLLSearchHandler() : LLCommandHandler(\"search\", UNTRUSTED_THROTTLE) { }\n\tbool handle(const LLSD& tokens, const LLSD& query_map, LLMediaCtrl* web)\n\t{\n\t\tconst size_t parts = tokens.size();\n\n\t\t\/\/ get the (optional) category for the search\n\t\tstd::string category;\n\t\tif (parts > 0)\n\t\t{\n\t\t\tcategory = tokens[0].asString();\n\t\t}\n\n\t\t\/\/ get the (optional) search string\n\t\tstd::string search_text;\n\t\tif (parts > 1)\n\t\t{\n\t\t\tsearch_text = tokens[1].asString();\n\t\t}\n\n\t\t\/\/ create the LLSD arguments for the search floater\n\t\tLLSD args;\n\t\targs[\"category\"] = category;\n\t\targs[\"id\"] = LLURI::unescape(search_text);\n\n\t\t\/\/ open the search floater and perform the requested search\n\t\tLLFloaterReg::showInstance(\"search\", args);\n\t\treturn true;\n\t}\n};\nLLSearchHandler gSearchHandler;\n\nLLFloaterSearch::LLFloaterSearch(const LLSD& key) :\n\tLLFloater(key),\n\tLLViewerMediaObserver(),\n\tmBrowser(NULL),\n\tmSearchGodLevel(0)\n{\n\t\/\/ declare a map that transforms a category name into\n\t\/\/ the URL suffix that is used to search that category\n\tmCategoryPaths = LLSD::emptyMap();\n\tmCategoryPaths[\"all\"] = \"search\";\n\tmCategoryPaths[\"people\"] = \"search\/people\";\n\tmCategoryPaths[\"places\"] = \"search\/places\";\n\tmCategoryPaths[\"events\"] = \"search\/events\";\n\tmCategoryPaths[\"groups\"] = \"search\/groups\";\n\tmCategoryPaths[\"wiki\"] = \"search\/wiki\";\n\tmCategoryPaths[\"destinations\"] = \"destinations\";\n\tmCategoryPaths[\"classifieds\"] = \"classifieds\";\n}\n\nBOOL LLFloaterSearch::postBuild()\n{\n\tmBrowser = getChild<LLMediaCtrl>(\"browser\");\n\tmBrowser->addObserver(this);\n\n\treturn TRUE;\n}\n\nvoid LLFloaterSearch::onOpen(const LLSD& key)\n{\n\tsearch(key);\n}\n\nvoid LLFloaterSearch::onClose(bool app_quitting)\n{\n\t\/\/ tear down the web view so we don't show the previous search\n\t\/\/ result when the floater is opened next time\n\tdestroy();\n}\n\nvoid LLFloaterSearch::handleMediaEvent(LLPluginClassMedia *self, EMediaEvent event)\n{\n\tswitch (event) \n\t{\n\tcase MEDIA_EVENT_NAVIGATE_BEGIN:\n\t\tgetChild<LLUICtrl>(\"status_text\")->setValue(getString(\"loading_text\"));\n\t\tbreak;\n\t\t\n\tcase MEDIA_EVENT_NAVIGATE_COMPLETE:\n\t\tgetChild<LLUICtrl>(\"status_text\")->setValue(getString(\"done_text\"));\n\t\tbreak;\n\n\tdefault:\n\t\tbreak;\n\t}\n}\n\nvoid LLFloaterSearch::godLevelChanged(U8 godlevel)\n{\n\t\/\/ search results can change based upon god level - if the user\n\t\/\/ changes god level, then give them a warning (we don't refresh\n\t\/\/ the search as this might undo any page navigation or\n\t\/\/ AJAX-driven changes since the last search).\n\tgetChildView(\"refresh_search\")->setVisible( (godlevel != mSearchGodLevel));\n}\n\nvoid LLFloaterSearch::search(const LLSD &key)\n{\n\tif (! mBrowser)\n\t{\n\t\treturn;\n\t}\n\n\t\/\/ reset the god level warning as we're sending the latest state\n\tgetChildView(\"refresh_search\")->setVisible(FALSE);\n\tmSearchGodLevel = gAgent.getGodLevel();\n\n\t\/\/ work out the subdir to use based on the requested category\n\tLLSD subs;\n\tstd::string category = key.has(\"category\") ? key[\"category\"].asString() : \"\";\n\tif (mCategoryPaths.has(category))\n\t{\n\t\tsubs[\"CATEGORY\"] = mCategoryPaths[category].asString();\n\t}\n\telse\n\t{\n\t\tsubs[\"CATEGORY\"] = mCategoryPaths[\"all\"].asString();\n\t}\n\n\t\/\/ add the search query string\n\tstd::string search_text = key.has(\"id\") ? key[\"id\"].asString() : \"\";\n\tsubs[\"QUERY\"] = LLURI::escape(search_text);\n\n\t\/\/ add the permissions token that login.cgi gave us\n\t\/\/ We use \"search_token\", and fallback to \"auth_token\" if not present.\n\tLLSD search_token = LLLoginInstance::getInstance()->getResponse(\"search_token\");\n\tif (search_token.asString().empty())\n\t{\n\t\tsearch_token = LLLoginInstance::getInstance()->getResponse(\"auth_token\");\n\t}\n\tsubs[\"AUTH_TOKEN\"] = search_token.asString();\n\n\t\/\/ add the user's preferred maturity (can be changed via prefs)\n\tstd::string maturity;\n\tif (gAgent.prefersAdult())\n\t{\n\t\tmaturity = \"42\"; \/\/ PG,Mature,Adult\n\t}\n\telse if (gAgent.prefersMature())\n\t{\n\t\tmaturity = \"21\"; \/\/ PG,Mature\n\t}\n\telse\n\t{\n\t\tmaturity = \"13\"; \/\/ PG\n\t}\n\tsubs[\"MATURITY\"] = maturity;\n\n\t\/\/ add the user's god status\n\tsubs[\"GODLIKE\"] = gAgent.isGodlike() ? \"1\" : \"0\";\n\n\t\/\/ get the search URL and expand all of the substitutions\n\t\/\/ (also adds things like [LANGUAGE], [VERSION], [OS], etc.)\n\tstd::string url = gSavedSettings.getString(\"SearchURL\");\n\turl = LLWeb::expandURLSubstitutions(url, subs);\n\n\t\/\/ and load the URL in the web view\n\tmBrowser->navigateTo(url);\n}\n<commit_msg>SOCIAL-269 FIX Search floater in client should bypass the usual media MIME type detection<commit_after>\/** \n * @file llfloatersearch.cpp\n * @author Martin Reddy\n * @brief Search floater - uses an embedded web browser control\n *\n * $LicenseInfo:firstyear=2009&license=viewerlgpl$\n * Second Life Viewer Source Code\n * Copyright (C) 2010, Linden Research, Inc.\n * \n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation;\n * version 2.1 of the License only.\n * \n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n * \n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n * \n * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA\n * $\/LicenseInfo$\n *\/\n\n#include \"llviewerprecompiledheaders.h\"\n\n#include \"llcommandhandler.h\"\n#include \"llfloaterreg.h\"\n#include \"llfloatersearch.h\"\n#include \"llmediactrl.h\"\n#include \"lllogininstance.h\"\n#include \"lluri.h\"\n#include \"llagent.h\"\n#include \"llui.h\"\n#include \"llviewercontrol.h\"\n#include \"llweb.h\"\n\n\/\/ support secondlife:\/\/\/app\/search\/{CATEGORY}\/{QUERY} SLapps\nclass LLSearchHandler : public LLCommandHandler\n{\npublic:\n\t\/\/ requires trusted browser to trigger\n\tLLSearchHandler() : LLCommandHandler(\"search\", UNTRUSTED_THROTTLE) { }\n\tbool handle(const LLSD& tokens, const LLSD& query_map, LLMediaCtrl* web)\n\t{\n\t\tconst size_t parts = tokens.size();\n\n\t\t\/\/ get the (optional) category for the search\n\t\tstd::string category;\n\t\tif (parts > 0)\n\t\t{\n\t\t\tcategory = tokens[0].asString();\n\t\t}\n\n\t\t\/\/ get the (optional) search string\n\t\tstd::string search_text;\n\t\tif (parts > 1)\n\t\t{\n\t\t\tsearch_text = tokens[1].asString();\n\t\t}\n\n\t\t\/\/ create the LLSD arguments for the search floater\n\t\tLLSD args;\n\t\targs[\"category\"] = category;\n\t\targs[\"id\"] = LLURI::unescape(search_text);\n\n\t\t\/\/ open the search floater and perform the requested search\n\t\tLLFloaterReg::showInstance(\"search\", args);\n\t\treturn true;\n\t}\n};\nLLSearchHandler gSearchHandler;\n\nLLFloaterSearch::LLFloaterSearch(const LLSD& key) :\n\tLLFloater(key),\n\tLLViewerMediaObserver(),\n\tmBrowser(NULL),\n\tmSearchGodLevel(0)\n{\n\t\/\/ declare a map that transforms a category name into\n\t\/\/ the URL suffix that is used to search that category\n\tmCategoryPaths = LLSD::emptyMap();\n\tmCategoryPaths[\"all\"] = \"search\";\n\tmCategoryPaths[\"people\"] = \"search\/people\";\n\tmCategoryPaths[\"places\"] = \"search\/places\";\n\tmCategoryPaths[\"events\"] = \"search\/events\";\n\tmCategoryPaths[\"groups\"] = \"search\/groups\";\n\tmCategoryPaths[\"wiki\"] = \"search\/wiki\";\n\tmCategoryPaths[\"destinations\"] = \"destinations\";\n\tmCategoryPaths[\"classifieds\"] = \"classifieds\";\n}\n\nBOOL LLFloaterSearch::postBuild()\n{\n\tmBrowser = getChild<LLMediaCtrl>(\"browser\");\n\tmBrowser->addObserver(this);\n\n\treturn TRUE;\n}\n\nvoid LLFloaterSearch::onOpen(const LLSD& key)\n{\n\tsearch(key);\n}\n\nvoid LLFloaterSearch::onClose(bool app_quitting)\n{\n\t\/\/ tear down the web view so we don't show the previous search\n\t\/\/ result when the floater is opened next time\n\tdestroy();\n}\n\nvoid LLFloaterSearch::handleMediaEvent(LLPluginClassMedia *self, EMediaEvent event)\n{\n\tswitch (event) \n\t{\n\tcase MEDIA_EVENT_NAVIGATE_BEGIN:\n\t\tgetChild<LLUICtrl>(\"status_text\")->setValue(getString(\"loading_text\"));\n\t\tbreak;\n\t\t\n\tcase MEDIA_EVENT_NAVIGATE_COMPLETE:\n\t\tgetChild<LLUICtrl>(\"status_text\")->setValue(getString(\"done_text\"));\n\t\tbreak;\n\n\tdefault:\n\t\tbreak;\n\t}\n}\n\nvoid LLFloaterSearch::godLevelChanged(U8 godlevel)\n{\n\t\/\/ search results can change based upon god level - if the user\n\t\/\/ changes god level, then give them a warning (we don't refresh\n\t\/\/ the search as this might undo any page navigation or\n\t\/\/ AJAX-driven changes since the last search).\n\tgetChildView(\"refresh_search\")->setVisible( (godlevel != mSearchGodLevel));\n}\n\nvoid LLFloaterSearch::search(const LLSD &key)\n{\n\tif (! mBrowser)\n\t{\n\t\treturn;\n\t}\n\n\t\/\/ reset the god level warning as we're sending the latest state\n\tgetChildView(\"refresh_search\")->setVisible(FALSE);\n\tmSearchGodLevel = gAgent.getGodLevel();\n\n\t\/\/ work out the subdir to use based on the requested category\n\tLLSD subs;\n\tstd::string category = key.has(\"category\") ? key[\"category\"].asString() : \"\";\n\tif (mCategoryPaths.has(category))\n\t{\n\t\tsubs[\"CATEGORY\"] = mCategoryPaths[category].asString();\n\t}\n\telse\n\t{\n\t\tsubs[\"CATEGORY\"] = mCategoryPaths[\"all\"].asString();\n\t}\n\n\t\/\/ add the search query string\n\tstd::string search_text = key.has(\"id\") ? key[\"id\"].asString() : \"\";\n\tsubs[\"QUERY\"] = LLURI::escape(search_text);\n\n\t\/\/ add the permissions token that login.cgi gave us\n\t\/\/ We use \"search_token\", and fallback to \"auth_token\" if not present.\n\tLLSD search_token = LLLoginInstance::getInstance()->getResponse(\"search_token\");\n\tif (search_token.asString().empty())\n\t{\n\t\tsearch_token = LLLoginInstance::getInstance()->getResponse(\"auth_token\");\n\t}\n\tsubs[\"AUTH_TOKEN\"] = search_token.asString();\n\n\t\/\/ add the user's preferred maturity (can be changed via prefs)\n\tstd::string maturity;\n\tif (gAgent.prefersAdult())\n\t{\n\t\tmaturity = \"42\"; \/\/ PG,Mature,Adult\n\t}\n\telse if (gAgent.prefersMature())\n\t{\n\t\tmaturity = \"21\"; \/\/ PG,Mature\n\t}\n\telse\n\t{\n\t\tmaturity = \"13\"; \/\/ PG\n\t}\n\tsubs[\"MATURITY\"] = maturity;\n\n\t\/\/ add the user's god status\n\tsubs[\"GODLIKE\"] = gAgent.isGodlike() ? \"1\" : \"0\";\n\n\t\/\/ get the search URL and expand all of the substitutions\n\t\/\/ (also adds things like [LANGUAGE], [VERSION], [OS], etc.)\n\tstd::string url = gSavedSettings.getString(\"SearchURL\");\n\turl = LLWeb::expandURLSubstitutions(url, subs);\n\n\t\/\/ and load the URL in the web view\n\tmBrowser->navigateTo(url, \"text\/html\");\n}\n<|endoftext|>"} {"text":"<commit_before>#ifndef KGR_KANGARU_INCLUDE_KANGARU_PREDICATE_HPP\n#define KGR_KANGARU_INCLUDE_KANGARU_PREDICATE_HPP\n\n#include \"type_id.hpp\"\n\nnamespace kgr {\n\n\/*\n * This predicate always returns true.\n * \n * This is the default predicate used by the container.\n *\/\nstruct All {\n\tconstexpr inline bool operator()(type_id_t) const {\n\t\treturn true;\n\t}\n};\n\n\/*\n * This predicate returns true for all services except those specified.\n *\/\ntemplate<typename First, typename... Ts>\nstruct NoneOf {\n\tconstexpr bool operator()(type_id_t id) const {\n\t\treturn !compare<First, Ts...>(id);\n\t}\n\t\nprivate:\n\ttemplate<typename Compared, typename Second, typename... Rest>\n\tconstexpr bool compare(type_id_t id) const {\n\t\treturn id == type_id<Compared>() && compare<Second, Rest...>(id);\n\t}\n\t\n\ttemplate<typename Compared>\n\tconstexpr bool compare(type_id_t id) const {\n\t\treturn id == type_id<Compared>();\n\t}\n};\n\n\/*\n * Predicate that returns false for all services, except those passed as argument.\n *\/\ntemplate<typename First, typename... Ts>\nstruct AnyOf {\n\tconstexpr bool operator()(type_id_t id) const {\n\t\treturn compare<First, Ts...>(id);\n\t}\n\t\nprivate:\n\ttemplate<typename Compared, typename Second, typename... Rest>\n\tconstexpr bool compare(type_id_t id) const {\n\t\treturn id == type_id<Compared>() && compare<Second, Rest...>(id);\n\t}\n\t\n\ttemplate<typename Compared>\n\tconstexpr bool compare(type_id_t id) const {\n\t\treturn id == type_id<Compared>();\n\t}\n};\n\n} \/\/ namespace kgr\n\n#endif \/\/ KGR_KANGARU_INCLUDE_KANGARU_PREDICATE_HPP\n<commit_msg>Added noexcept in predicates<commit_after>#ifndef KGR_KANGARU_INCLUDE_KANGARU_PREDICATE_HPP\n#define KGR_KANGARU_INCLUDE_KANGARU_PREDICATE_HPP\n\n#include \"type_id.hpp\"\n\nnamespace kgr {\n\n\/*\n * This predicate always returns true.\n * \n * This is the default predicate used by the container.\n *\/\nstruct All {\n\tconstexpr inline bool operator()(type_id_t) const noexcept {\n\t\treturn true;\n\t}\n};\n\n\/*\n * This predicate returns true for all services except those specified.\n *\/\ntemplate<typename First, typename... Ts>\nstruct NoneOf {\n\tconstexpr bool operator()(type_id_t id) const noexcept {\n\t\treturn !compare<First, Ts...>(id);\n\t}\n\t\nprivate:\n\ttemplate<typename Compared, typename Second, typename... Rest>\n\tconstexpr bool compare(type_id_t id) const noexcept {\n\t\treturn id == type_id<Compared>() && compare<Second, Rest...>(id);\n\t}\n\t\n\ttemplate<typename Compared>\n\tconstexpr bool compare(type_id_t id) const noexcept {\n\t\treturn id == type_id<Compared>();\n\t}\n};\n\n\/*\n * Predicate that returns false for all services, except those passed as argument.\n *\/\ntemplate<typename First, typename... Ts>\nstruct AnyOf {\n\tconstexpr bool operator()(type_id_t id) const noexcept {\n\t\treturn compare<First, Ts...>(id);\n\t}\n\t\nprivate:\n\ttemplate<typename Compared, typename Second, typename... Rest>\n\tconstexpr bool compare(type_id_t id) const noexcept {\n\t\treturn id == type_id<Compared>() && compare<Second, Rest...>(id);\n\t}\n\t\n\ttemplate<typename Compared>\n\tconstexpr bool compare(type_id_t id) const noexcept {\n\t\treturn id == type_id<Compared>();\n\t}\n};\n\n} \/\/ namespace kgr\n\n#endif \/\/ KGR_KANGARU_INCLUDE_KANGARU_PREDICATE_HPP\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2016-2021 Francesco Biscani (bluescarni@gmail.com)\n\/\/\n\/\/ This file is part of the mp++ library.\n\/\/\n\/\/ This Source Code Form is subject to the terms of the Mozilla\n\/\/ Public License v. 2.0. If a copy of the MPL was not distributed\n\/\/ with this file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n\n#ifndef MPPP_DETAIL_UTILS_HPP\n#define MPPP_DETAIL_UTILS_HPP\n\n#include <cassert>\n#include <limits>\n#include <stdexcept>\n#include <string>\n#include <type_traits>\n#include <utility>\n\n#include <mp++\/config.hpp>\n#include <mp++\/detail\/type_traits.hpp>\n#include <mp++\/detail\/visibility.hpp>\n#include <mp++\/type_name.hpp>\n\nnamespace mppp\n{\n\nnamespace detail\n{\n\n#if defined(_MSC_VER)\n\n\/\/ Disable some warnings for MSVC.\n#pragma warning(push)\n#pragma warning(disable : 4146)\n\n#endif\n\n\/\/ These are overloads useful to treat in a generic way mppp classes and standard numeric types.\n\n\/\/ Sign function for integral types.\ntemplate <typename T, enable_if_t<is_integral<T>::value, int> = 0>\nconstexpr int sgn(const T &n)\n{\n return n ? (n > T(0) ? 1 : -1) : 0;\n}\n\n\/\/ Zero detection for integral types.\ntemplate <typename T, enable_if_t<is_integral<T>::value, int> = 0>\nconstexpr bool is_zero(const T &n)\n{\n return n == T(0);\n}\n\n\/\/ Small helper to convert the non-negative signed integer n\n\/\/ into its unsigned counterpart.\ntemplate <typename T>\nconstexpr make_unsigned_t<T> make_unsigned(T n) noexcept\n{\n static_assert(is_integral<T>::value && is_signed<T>::value, \"Invalid type.\");\n#if MPPP_CPLUSPLUS >= 201703L\n \/\/ LCOV_EXCL_START\n assert(n >= T(0));\n \/\/ LCOV_EXCL_STOP\n#endif\n return static_cast<make_unsigned_t<T>>(n);\n}\n\n\/\/ Generic string conversion utility - will use std::to_string() for arithmetic types,\n\/\/ x.to_string() otherwise.\ntemplate <typename T, enable_if_t<std::is_arithmetic<T>::value, int> = 0>\ninline std::string to_string(const T &x)\n{\n return std::to_string(x);\n}\n\ntemplate <typename T, enable_if_t<!std::is_arithmetic<T>::value, int> = 0>\ninline std::string to_string(const T &x)\n{\n return x.to_string();\n}\n\n#if defined(MPPP_HAVE_GCC_INT128)\n\nMPPP_DLL_PUBLIC std::string to_string(__uint128_t);\nMPPP_DLL_PUBLIC std::string to_string(__int128_t);\n\n#endif\n\n\/\/ Compute the absolute value of a negative integer, returning the result as an instance\n\/\/ of the corresponding unsigned type. Requires T to be a signed integral type and n\n\/\/ to be negative.\n\/\/ NOTE: here we are using cast to unsigned + unary minus to extract the abs value of a signed negative\n\/\/ integral. See:\n\/\/ http:\/\/stackoverflow.com\/questions\/4536095\/unary-minus-and-signed-to-unsigned-conversion\n\/\/ This technique is not 100% portable in C++ < 20: it requires an implementation\n\/\/ of signed integers such that the absolute value of the minimum (negative) value is not greater than\n\/\/ the maximum value of the unsigned counterpart. This is guaranteed on all computer architectures in use today,\n\/\/ but in theory there could be architectures where the assumption is not respected. See for instance the\n\/\/ discussion here:\n\/\/ http:\/\/stackoverflow.com\/questions\/11372044\/unsigned-vs-signed-range-guarantees\n\/\/ Note that in any case we never run into UB, the only consequence is that for very large negative values\n\/\/ we could init the integer with the wrong value, and we should be able to detect this in the unit tests.\n\/\/ Let's keep this in mind in the remote case this ever becomes a problem.\n\/\/ Since C++20, integers are guaranteed to be represented via two's complement, and thus\n\/\/ this function is portable.\ntemplate <typename T>\nconstexpr make_unsigned_t<T> nint_abs(T n) noexcept\n{\n \/\/ NOTE: we should assert about negative n, but this is guaranteed to work properly in\n \/\/ constexpr functions only from C++17:\n \/\/ https:\/\/stackoverflow.com\/questions\/26072709\/alternative-to-asserts-for-constexpr-functions\n#if MPPP_CPLUSPLUS >= 201703L\n \/\/ LCOV_EXCL_START\n assert(n < T(0));\n \/\/ LCOV_EXCL_STOP\n#endif\n static_assert(is_integral<T>::value && is_signed<T>::value,\n \"The sint_abs() function can be used only with signed integral types.\");\n using uT = make_unsigned_t<T>;\n \/\/ NOTE: the potential cast to \"unsigned\", rather than uT, is for when uT is a short integral type.\n \/\/ In such a case, the unary minus will trigger integral promotion to int\/unsigned\n \/\/ int, and I am *not* 100% sure in this case the technique still works. Written like this, the cast\n \/\/ is never to a type narrower than \"unsigned\".\n return static_cast<uT>(\n -static_cast<typename std::conditional<(nl_max<uT>() <= nl_max<unsigned>()), unsigned, uT>::type>(n));\n}\n\n\/\/ constexpr max\/min implementations with copy semantics.\ntemplate <typename T>\nconstexpr T c_max(T a, T b) noexcept\n{\n return a > b ? a : b;\n}\n\ntemplate <typename T>\nconstexpr T c_min(T a, T b) noexcept\n{\n return a < b ? a : b;\n}\n\n\/\/ A small helper to convert the input unsigned n to -n, represented as the signed T.\ntemplate <typename T, typename U>\n\/\/ NOTE: C++17 because we are using assert().\n#if MPPP_CPLUSPLUS >= 201703L\nconstexpr\n#else\ninline\n#endif\n std::pair<bool, T>\n unsigned_to_nsigned(U n)\n{\n static_assert(is_integral<T>::value && is_signed<T>::value, \"Invalid type.\");\n static_assert(is_integral<U>::value && is_unsigned<U>::value, \"Invalid type.\");\n \/\/ Cache a couple of quantities.\n constexpr auto Tmax = make_unsigned(nl_max<T>());\n constexpr auto Tmin_abs = nint_abs(nl_min<T>());\n if (mppp_likely(n <= c_min(Tmax, Tmin_abs))) {\n \/\/ Optimise the case in which n fits both Tmax and Tmin_abs. This means\n \/\/ we can convert and negate safely.\n return std::make_pair(true, static_cast<T>(-static_cast<T>(n)));\n }\n \/\/ n needs to fit within the abs of min().\n if (n > Tmin_abs) {\n return std::make_pair(false, T(0));\n }\n \/\/ LCOV_EXCL_START\n if (Tmin_abs <= Tmax) {\n \/\/ The negative range of T is leq than the positive one: we can convert to T and negate safely.\n \/\/ NOTE: this is never hit on current architectures.\n return std::make_pair(true, static_cast<T>(-static_cast<T>(n)));\n }\n \/\/ LCOV_EXCL_STOP\n \/\/ NOTE: double check this, since:\n \/\/ - Tmin_abs > Tmax (as checked just above),\n \/\/ - n > c_min(Tmax, Tmin_abs) (as checked earlier).\n assert(n > Tmax);\n \/\/ The negative range is greater than the positive one and n larger than Tmax:\n \/\/ we cannot directly convert n to T. The idea then is to init retval to -Tmax\n \/\/ and then to subtract from it Tmax as many times as needed.\n auto retval = static_cast<T>(-static_cast<T>(Tmax));\n const auto q = static_cast<U>(n \/ Tmax), r = static_cast<U>(n % Tmax);\n for (U i = 0; i < q - 1u; ++i) {\n \/\/ LCOV_EXCL_START\n \/\/ NOTE: this is never hit on current archs, as Tmax differs from Tmin_abs\n \/\/ by just 1: we will use only the remainder r.\n retval = static_cast<T>(retval - static_cast<T>(Tmax));\n \/\/ LCOV_EXCL_STOP\n }\n retval = static_cast<T>(retval - static_cast<T>(r));\n return std::make_pair(true, retval);\n}\n\n\/\/ Like above, but throw on failure.\ntemplate <typename T, typename U>\n#if MPPP_CPLUSPLUS >= 201703L\nconstexpr\n#else\ninline\n#endif\n T\n negate_unsigned(U n)\n{\n const auto retval = unsigned_to_nsigned<T>(n);\n \/\/ LCOV_EXCL_START\n return retval.first ? retval.second\n : throw std::overflow_error(\n \"Error while trying to negate the unsigned integral value \" + to_string(n)\n + \": the result does not fit in the range of the target type '\" + type_name<T>() + \"'\");\n \/\/ LCOV_EXCL_STOP\n}\n\n\/\/ Safe casting functionality between integral types. It will throw if the conversion overflows the range\n\/\/ of the target type T.\ntemplate <typename T, typename U,\n enable_if_t<conjunction<is_integral<T>, is_integral<U>, is_unsigned<T>, is_unsigned<U>>::value, int> = 0>\nconstexpr T safe_cast(const U &n)\n{\n return n <= nl_max<T>()\n ? static_cast<T>(n)\n : throw std::overflow_error(\n \"Error in the safe conversion between unsigned integral types: the input value \" + to_string(n)\n + \" does not fit in the range of the target type '\" + type_name<T>() + \"'\");\n}\n\ntemplate <typename T, typename U,\n enable_if_t<conjunction<is_integral<T>, is_integral<U>, is_signed<T>, is_signed<U>>::value, int> = 0>\nconstexpr T safe_cast(const U &n)\n{\n return (n <= nl_max<T>() && n >= nl_min<T>())\n ? static_cast<T>(n)\n : throw std::overflow_error(\n \"Error in the safe conversion between signed integral types: the input value \" + to_string(n)\n + \" does not fit in the range of the target type '\" + type_name<T>() + \"'\");\n}\n\ntemplate <typename T, typename U,\n enable_if_t<conjunction<is_integral<T>, is_integral<U>, is_unsigned<T>, is_signed<U>>::value, int> = 0>\nconstexpr T safe_cast(const U &n)\n{\n return (n >= U(0) && make_unsigned(n) <= nl_max<T>())\n ? static_cast<T>(n)\n : throw std::overflow_error(\"Error in the safe conversion from a signed integral type to an unsigned \"\n \"integral type: the input value \"\n + to_string(n) + \" does not fit in the range of the target type '\"\n + type_name<T>() + \"'\");\n}\n\ntemplate <typename T, typename U,\n enable_if_t<conjunction<is_integral<T>, is_integral<U>, is_signed<T>, is_unsigned<U>>::value, int> = 0>\nconstexpr T safe_cast(const U &n)\n{\n return n <= make_unsigned(nl_max<T>())\n ? static_cast<T>(n)\n : throw std::overflow_error(\"Error in the safe conversion from an unsigned integral type to a signed \"\n \"integral type: the input value \"\n + to_string(n) + \" does not fit in the range of the target type '\"\n + type_name<T>() + \"'\");\n}\n\n\/\/ Helper to ignore unused variables.\n\/\/ NOTE: the return type has to be int, rather than void, for compatibility\n\/\/ with C++11 constexpr.\ntemplate <typename... Args>\nconstexpr int ignore(Args &&...)\n{\n return 0;\n}\n\n\/\/ Given an input unsigned integer n, this function will return\n\/\/ a signed integer whose absolute value is n and whose sign is\n\/\/ s (following the usual convention: s = 0 means zero,\n\/\/ s = 1 means positive, s = -1 means negative).\n\/\/ No overflow check is performed: if the value of the result\n\/\/ does not fit in the return type, the behaviour will be undefined.\ntemplate <typename T>\ninline make_signed_t<T> make_signed(const T &n, int s)\n{\n static_assert(is_unsigned<T>::value, \"make_signed() can be invoked only on unsigned integral types.\");\n \/\/ NOTE: avoid integral promotion bullshit.\n static_assert(std::is_same<T, decltype(n + n)>::value, \"make_signed() cannot be used with short integral types.\");\n\n \/\/ Consistency checks: s must be one of [0, -1, 1], and, if s is zero,\n \/\/ then n must also be zero.\n assert(s == 0 || s == -1 || s == 1);\n assert(s != 0 || n == 0u);\n\n \/\/ NOTE: s_ex will be:\n \/\/ - 0 if s is 0 or 1,\n \/\/ - the max value representable by T if s is -1 (this is because the\n \/\/ right shift produces the int -1, which is then converted to the\n \/\/ unsigned T).\n \/\/ NOTE: the right shift behaviour for signed operands is standardised\n \/\/ only since C++20, but in practice it should work everywhere.\n const auto s_ex = static_cast<T>(s >> (std::numeric_limits<int>::digits - 1));\n\n \/\/ (n ^ s_ex) - s_ex returns n if s_ex is 0, -n (still represented\n \/\/ as an unsigned) otherwise.\n return static_cast<make_signed_t<T>>((n ^ s_ex) - s_ex);\n}\n\n#if defined(_MSC_VER)\n\n#pragma warning(pop)\n\n#endif\n} \/\/ namespace detail\n} \/\/ namespace mppp\n\n#endif\n<commit_msg>Add a hash combiner.<commit_after>\/\/ Copyright 2016-2021 Francesco Biscani (bluescarni@gmail.com)\n\/\/\n\/\/ This file is part of the mp++ library.\n\/\/\n\/\/ This Source Code Form is subject to the terms of the Mozilla\n\/\/ Public License v. 2.0. If a copy of the MPL was not distributed\n\/\/ with this file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n\n#ifndef MPPP_DETAIL_UTILS_HPP\n#define MPPP_DETAIL_UTILS_HPP\n\n#include <cassert>\n#include <cstddef>\n#include <functional>\n#include <limits>\n#include <stdexcept>\n#include <string>\n#include <type_traits>\n#include <utility>\n\n#include <mp++\/config.hpp>\n#include <mp++\/detail\/type_traits.hpp>\n#include <mp++\/detail\/visibility.hpp>\n#include <mp++\/type_name.hpp>\n\nnamespace mppp\n{\n\nnamespace detail\n{\n\n#if defined(_MSC_VER)\n\n\/\/ Disable some warnings for MSVC.\n#pragma warning(push)\n#pragma warning(disable : 4146)\n\n#endif\n\n\/\/ These are overloads useful to treat in a generic way mppp classes and standard numeric types.\n\n\/\/ Sign function for integral types.\ntemplate <typename T, enable_if_t<is_integral<T>::value, int> = 0>\nconstexpr int sgn(const T &n)\n{\n return n ? (n > T(0) ? 1 : -1) : 0;\n}\n\n\/\/ Zero detection for integral types.\ntemplate <typename T, enable_if_t<is_integral<T>::value, int> = 0>\nconstexpr bool is_zero(const T &n)\n{\n return n == T(0);\n}\n\n\/\/ Small helper to convert the non-negative signed integer n\n\/\/ into its unsigned counterpart.\ntemplate <typename T>\nconstexpr make_unsigned_t<T> make_unsigned(T n) noexcept\n{\n static_assert(is_integral<T>::value && is_signed<T>::value, \"Invalid type.\");\n#if MPPP_CPLUSPLUS >= 201703L\n \/\/ LCOV_EXCL_START\n assert(n >= T(0));\n \/\/ LCOV_EXCL_STOP\n#endif\n return static_cast<make_unsigned_t<T>>(n);\n}\n\n\/\/ Generic string conversion utility - will use std::to_string() for arithmetic types,\n\/\/ x.to_string() otherwise.\ntemplate <typename T, enable_if_t<std::is_arithmetic<T>::value, int> = 0>\ninline std::string to_string(const T &x)\n{\n return std::to_string(x);\n}\n\ntemplate <typename T, enable_if_t<!std::is_arithmetic<T>::value, int> = 0>\ninline std::string to_string(const T &x)\n{\n return x.to_string();\n}\n\n#if defined(MPPP_HAVE_GCC_INT128)\n\nMPPP_DLL_PUBLIC std::string to_string(__uint128_t);\nMPPP_DLL_PUBLIC std::string to_string(__int128_t);\n\n#endif\n\n\/\/ Compute the absolute value of a negative integer, returning the result as an instance\n\/\/ of the corresponding unsigned type. Requires T to be a signed integral type and n\n\/\/ to be negative.\n\/\/ NOTE: here we are using cast to unsigned + unary minus to extract the abs value of a signed negative\n\/\/ integral. See:\n\/\/ http:\/\/stackoverflow.com\/questions\/4536095\/unary-minus-and-signed-to-unsigned-conversion\n\/\/ This technique is not 100% portable in C++ < 20: it requires an implementation\n\/\/ of signed integers such that the absolute value of the minimum (negative) value is not greater than\n\/\/ the maximum value of the unsigned counterpart. This is guaranteed on all computer architectures in use today,\n\/\/ but in theory there could be architectures where the assumption is not respected. See for instance the\n\/\/ discussion here:\n\/\/ http:\/\/stackoverflow.com\/questions\/11372044\/unsigned-vs-signed-range-guarantees\n\/\/ Note that in any case we never run into UB, the only consequence is that for very large negative values\n\/\/ we could init the integer with the wrong value, and we should be able to detect this in the unit tests.\n\/\/ Let's keep this in mind in the remote case this ever becomes a problem.\n\/\/ Since C++20, integers are guaranteed to be represented via two's complement, and thus\n\/\/ this function is portable.\ntemplate <typename T>\nconstexpr make_unsigned_t<T> nint_abs(T n) noexcept\n{\n \/\/ NOTE: we should assert about negative n, but this is guaranteed to work properly in\n \/\/ constexpr functions only from C++17:\n \/\/ https:\/\/stackoverflow.com\/questions\/26072709\/alternative-to-asserts-for-constexpr-functions\n#if MPPP_CPLUSPLUS >= 201703L\n \/\/ LCOV_EXCL_START\n assert(n < T(0));\n \/\/ LCOV_EXCL_STOP\n#endif\n static_assert(is_integral<T>::value && is_signed<T>::value,\n \"The sint_abs() function can be used only with signed integral types.\");\n using uT = make_unsigned_t<T>;\n \/\/ NOTE: the potential cast to \"unsigned\", rather than uT, is for when uT is a short integral type.\n \/\/ In such a case, the unary minus will trigger integral promotion to int\/unsigned\n \/\/ int, and I am *not* 100% sure in this case the technique still works. Written like this, the cast\n \/\/ is never to a type narrower than \"unsigned\".\n return static_cast<uT>(\n -static_cast<typename std::conditional<(nl_max<uT>() <= nl_max<unsigned>()), unsigned, uT>::type>(n));\n}\n\n\/\/ constexpr max\/min implementations with copy semantics.\ntemplate <typename T>\nconstexpr T c_max(T a, T b) noexcept\n{\n return a > b ? a : b;\n}\n\ntemplate <typename T>\nconstexpr T c_min(T a, T b) noexcept\n{\n return a < b ? a : b;\n}\n\n\/\/ A small helper to convert the input unsigned n to -n, represented as the signed T.\ntemplate <typename T, typename U>\n\/\/ NOTE: C++17 because we are using assert().\n#if MPPP_CPLUSPLUS >= 201703L\nconstexpr\n#else\ninline\n#endif\n std::pair<bool, T>\n unsigned_to_nsigned(U n)\n{\n static_assert(is_integral<T>::value && is_signed<T>::value, \"Invalid type.\");\n static_assert(is_integral<U>::value && is_unsigned<U>::value, \"Invalid type.\");\n \/\/ Cache a couple of quantities.\n constexpr auto Tmax = make_unsigned(nl_max<T>());\n constexpr auto Tmin_abs = nint_abs(nl_min<T>());\n if (mppp_likely(n <= c_min(Tmax, Tmin_abs))) {\n \/\/ Optimise the case in which n fits both Tmax and Tmin_abs. This means\n \/\/ we can convert and negate safely.\n return std::make_pair(true, static_cast<T>(-static_cast<T>(n)));\n }\n \/\/ n needs to fit within the abs of min().\n if (n > Tmin_abs) {\n return std::make_pair(false, T(0));\n }\n \/\/ LCOV_EXCL_START\n if (Tmin_abs <= Tmax) {\n \/\/ The negative range of T is leq than the positive one: we can convert to T and negate safely.\n \/\/ NOTE: this is never hit on current architectures.\n return std::make_pair(true, static_cast<T>(-static_cast<T>(n)));\n }\n \/\/ LCOV_EXCL_STOP\n \/\/ NOTE: double check this, since:\n \/\/ - Tmin_abs > Tmax (as checked just above),\n \/\/ - n > c_min(Tmax, Tmin_abs) (as checked earlier).\n assert(n > Tmax);\n \/\/ The negative range is greater than the positive one and n larger than Tmax:\n \/\/ we cannot directly convert n to T. The idea then is to init retval to -Tmax\n \/\/ and then to subtract from it Tmax as many times as needed.\n auto retval = static_cast<T>(-static_cast<T>(Tmax));\n const auto q = static_cast<U>(n \/ Tmax), r = static_cast<U>(n % Tmax);\n for (U i = 0; i < q - 1u; ++i) {\n \/\/ LCOV_EXCL_START\n \/\/ NOTE: this is never hit on current archs, as Tmax differs from Tmin_abs\n \/\/ by just 1: we will use only the remainder r.\n retval = static_cast<T>(retval - static_cast<T>(Tmax));\n \/\/ LCOV_EXCL_STOP\n }\n retval = static_cast<T>(retval - static_cast<T>(r));\n return std::make_pair(true, retval);\n}\n\n\/\/ Like above, but throw on failure.\ntemplate <typename T, typename U>\n#if MPPP_CPLUSPLUS >= 201703L\nconstexpr\n#else\ninline\n#endif\n T\n negate_unsigned(U n)\n{\n const auto retval = unsigned_to_nsigned<T>(n);\n \/\/ LCOV_EXCL_START\n return retval.first ? retval.second\n : throw std::overflow_error(\n \"Error while trying to negate the unsigned integral value \" + to_string(n)\n + \": the result does not fit in the range of the target type '\" + type_name<T>() + \"'\");\n \/\/ LCOV_EXCL_STOP\n}\n\n\/\/ Safe casting functionality between integral types. It will throw if the conversion overflows the range\n\/\/ of the target type T.\ntemplate <typename T, typename U,\n enable_if_t<conjunction<is_integral<T>, is_integral<U>, is_unsigned<T>, is_unsigned<U>>::value, int> = 0>\nconstexpr T safe_cast(const U &n)\n{\n return n <= nl_max<T>()\n ? static_cast<T>(n)\n : throw std::overflow_error(\n \"Error in the safe conversion between unsigned integral types: the input value \" + to_string(n)\n + \" does not fit in the range of the target type '\" + type_name<T>() + \"'\");\n}\n\ntemplate <typename T, typename U,\n enable_if_t<conjunction<is_integral<T>, is_integral<U>, is_signed<T>, is_signed<U>>::value, int> = 0>\nconstexpr T safe_cast(const U &n)\n{\n return (n <= nl_max<T>() && n >= nl_min<T>())\n ? static_cast<T>(n)\n : throw std::overflow_error(\n \"Error in the safe conversion between signed integral types: the input value \" + to_string(n)\n + \" does not fit in the range of the target type '\" + type_name<T>() + \"'\");\n}\n\ntemplate <typename T, typename U,\n enable_if_t<conjunction<is_integral<T>, is_integral<U>, is_unsigned<T>, is_signed<U>>::value, int> = 0>\nconstexpr T safe_cast(const U &n)\n{\n return (n >= U(0) && make_unsigned(n) <= nl_max<T>())\n ? static_cast<T>(n)\n : throw std::overflow_error(\"Error in the safe conversion from a signed integral type to an unsigned \"\n \"integral type: the input value \"\n + to_string(n) + \" does not fit in the range of the target type '\"\n + type_name<T>() + \"'\");\n}\n\ntemplate <typename T, typename U,\n enable_if_t<conjunction<is_integral<T>, is_integral<U>, is_signed<T>, is_unsigned<U>>::value, int> = 0>\nconstexpr T safe_cast(const U &n)\n{\n return n <= make_unsigned(nl_max<T>())\n ? static_cast<T>(n)\n : throw std::overflow_error(\"Error in the safe conversion from an unsigned integral type to a signed \"\n \"integral type: the input value \"\n + to_string(n) + \" does not fit in the range of the target type '\"\n + type_name<T>() + \"'\");\n}\n\n\/\/ Helper to ignore unused variables.\n\/\/ NOTE: the return type has to be int, rather than void, for compatibility\n\/\/ with C++11 constexpr.\ntemplate <typename... Args>\nconstexpr int ignore(Args &&...)\n{\n return 0;\n}\n\n\/\/ Given an input unsigned integer n, this function will return\n\/\/ a signed integer whose absolute value is n and whose sign is\n\/\/ s (following the usual convention: s = 0 means zero,\n\/\/ s = 1 means positive, s = -1 means negative).\n\/\/ No overflow check is performed: if the value of the result\n\/\/ does not fit in the return type, the behaviour will be undefined.\ntemplate <typename T>\ninline make_signed_t<T> make_signed(const T &n, int s)\n{\n static_assert(is_unsigned<T>::value, \"make_signed() can be invoked only on unsigned integral types.\");\n \/\/ NOTE: avoid integral promotion bullshit.\n static_assert(std::is_same<T, decltype(n + n)>::value, \"make_signed() cannot be used with short integral types.\");\n\n \/\/ Consistency checks: s must be one of [0, -1, 1], and, if s is zero,\n \/\/ then n must also be zero.\n assert(s == 0 || s == -1 || s == 1);\n assert(s != 0 || n == 0u);\n\n \/\/ NOTE: s_ex will be:\n \/\/ - 0 if s is 0 or 1,\n \/\/ - the max value representable by T if s is -1 (this is because the\n \/\/ right shift produces the int -1, which is then converted to the\n \/\/ unsigned T).\n \/\/ NOTE: the right shift behaviour for signed operands is standardised\n \/\/ only since C++20, but in practice it should work everywhere.\n const auto s_ex = static_cast<T>(s >> (std::numeric_limits<int>::digits - 1));\n\n \/\/ (n ^ s_ex) - s_ex returns n if s_ex is 0, -n (still represented\n \/\/ as an unsigned) otherwise.\n return static_cast<make_signed_t<T>>((n ^ s_ex) - s_ex);\n}\n\n\/\/ The hash combiner. This is lifted directly from Boost. See also:\n\/\/ http:\/\/www.open-std.org\/jtc1\/sc22\/wg21\/docs\/papers\/2014\/n3876.pdf\ntemplate <typename T>\ninline void hash_combine(std::size_t &seed, const T &val)\n{\n seed ^= std::hash<T>{}(val) + static_cast<std::size_t>(0x9e3779b9ull) + (seed << 6) + (seed >> 2);\n}\n\n#if defined(_MSC_VER)\n\n#pragma warning(pop)\n\n#endif\n} \/\/ namespace detail\n} \/\/ namespace mppp\n\n#endif\n<|endoftext|>"} {"text":"<commit_before><commit_msg>print error when loading<commit_after><|endoftext|>"} {"text":"<commit_before>#line 2 \"togo\/game\/resource\/types.hpp\"\n\/**\n@copyright MIT license; see @ref index or the accompanying LICENSE file.\n\n@file\n@brief Resource types.\n@ingroup lib_game_types\n@ingroup lib_game_resource\n*\/\n\n#pragma once\n\n#include <togo\/game\/config.hpp>\n#include <togo\/core\/types.hpp>\n#include <togo\/core\/utility\/traits.hpp>\n#include <togo\/core\/memory\/types.hpp>\n#include <togo\/core\/collection\/types.hpp>\n#include <togo\/core\/string\/types.hpp>\n#include <togo\/core\/hash\/types.hpp>\n#include <togo\/core\/hash\/hash.hpp>\n#include <togo\/core\/io\/types.hpp>\n#include <togo\/core\/io\/file_stream.hpp>\n\nnamespace togo {\n\n\/**\n\t@addtogroup lib_game_resource\n\t@{\n*\/\n\n\/\/\/ Format versions.\nenum : u32 {\n\t\/\/\/ ResourcePackage manifest format version.\n\tSER_FORMAT_VERSION_PKG_MANIFEST = 3,\n};\n\n\/\/\/ Resource type.\nusing ResourceType = hash32;\n\n\/\/\/ Resource name hash.\nusing ResourceNameHash = hash64;\n\n\/\/\/ Combined resource tags hash.\nusing ResourceTagsHash = hash64;\n\n\/\/\/ Combined resource tags hash combiner.\nusing ResourceTagsHashCombiner = HashCombiner64;\n\n\/\/\/ Package name hash.\nusing ResourcePackageNameHash = hash32;\n\n\/** @cond INTERNAL *\/\nstatic_assert(\n\tis_same<ResourceType, hash32>::value,\n\t\"changed ResourceType type breaks binary formats,\"\n\t\" hash functions, and likely other things\"\n);\nstatic_assert(\n\tis_same<ResourceNameHash, hash64>::value,\n\t\"changed ResourceNameHash type breaks binary formats,\"\n\t\" hash functions, and likely other things\"\n);\nstatic_assert(\n\tis_same<ResourceTagsHash, hash64>::value,\n\t\"changed ResourceTagsHash type breaks binary formats,\"\n\t\" hash functions, and likely other things\"\n);\n\/** @endcond *\/ \/\/ INTERNAL\n\n\/\/\/ Resource type hash literal.\ninline constexpr ResourceType\noperator\"\" _resource_type(\n\tchar const* const data,\n\tstd::size_t const size\n) {\n\treturn hash::calc32_ce(data, size);\n}\n\n\/\/\/ Resource name hash literal.\ninline constexpr ResourceNameHash\noperator\"\" _resource_name(\n\tchar const* const data,\n\tstd::size_t const size\n) {\n\treturn hash::calc64_ce(data, size);\n}\n\n\/\/\/ Combined resource tags hash literal.\n\/\/\/\n\/\/\/ Note that this only takes a single string. Tags should be sorted\n\/\/\/ and separator-less for the return value of this literal to be\n\/\/\/ compatible with the runtime combiner-based hash function.\ninline constexpr ResourceTagsHash\noperator\"\" _resource_tags(\n\tchar const* const data,\n\tstd::size_t const size\n) {\n\treturn hash::calc64_ce(data, size);\n}\n\n\/\/\/ Package name hash literal.\ninline constexpr ResourcePackageNameHash\noperator\"\" _resource_package_name(\n\tchar const* const data,\n\tstd::size_t const size\n) {\n\treturn hash::calc32_ce(data, size);\n}\n\n\/\/\/ Resource types.\nenum : ResourceType {\n\t\/\/\/ Non-type.\n\tRES_TYPE_NULL = \"\"_resource_type,\n\n\t\/\/\/ TestResource.\n\tRES_TYPE_TEST = \"test\"_resource_type,\n\n\t\/\/\/ gfx::ShaderDef.\n\tRES_TYPE_SHADER_PRELUDE = \"shader_prelude\"_resource_type,\n\n\t\/\/\/ gfx::ShaderID.\n\tRES_TYPE_SHADER = \"shader\"_resource_type,\n\n\t\/\/\/ gfx::RenderConfig.\n\tRES_TYPE_RENDER_CONFIG = \"render_config\"_resource_type,\n};\n\n\/\/\/ Resource names.\nenum : ResourceNameHash {\n\t\/\/\/ Null name.\n\tRES_NAME_NULL = \"\"_resource_name,\n\n\t\/\/\/ Shared shader configuration shader_prelude.\n\tRES_NAME_SHADER_CONFIG = \"togo\/game\/gfx\/shader-config\"_resource_name,\n};\n\n\/\/\/ Combined resource tags.\nenum : ResourceTagsHash {\n\t\/\/\/ Null tags.\n\tRES_TAGS_NULL = \"\"_resource_tags,\n};\n\n\/\/\/ Resource package names.\nenum : ResourcePackageNameHash {\n\t\/\/\/ Null name.\n\tPKG_NAME_NULL = \"\"_resource_package_name,\n};\n\n\/\/\/ Resource path parts.\nstruct ResourcePathParts {\n\tstruct Tag {\n\t\tStringRef name{};\n\t\thash32 hash;\n\t};\n\n\tResourceType type_hash;\n\tResourceNameHash name_hash;\n\tResourceTagsHash tags_hash;\n\tStringRef type{};\n\tStringRef name{};\n\tFixedArray<Tag, 8> tags;\n};\n\n\/\/\/ Path to compiled resource.\nstruct ResourceCompiledPath {\n\tu32 id;\n\tFixedArray<char, 24> _data{};\n\n\t~ResourceCompiledPath() = default;\n\n\tResourceCompiledPath(ResourceCompiledPath const&) = delete;\n\tResourceCompiledPath(ResourceCompiledPath&&) = delete;\n\tResourceCompiledPath& operator=(ResourceCompiledPath const&) = delete;\n\tResourceCompiledPath& operator=(ResourceCompiledPath&&) = delete;\n\n\tResourceCompiledPath();\n\n\toperator StringRef() const;\n\n\tu32 size() const;\n\tchar const* data() const;\n};\n\n\/\/\/ Resource metadata.\nstruct ResourceMetadata {\n\tu32 id;\n\n\t\/\/ Serial\n\tResourceNameHash name_hash;\n\tResourceTagsHash tags_hash;\n\tResourceType type;\n\tu32 data_format_version;\n\tu32 data_offset;\n\tu32 data_size;\n};\n\n\/\/\/ Resource value.\nunion ResourceValue {\n\tvoid* pointer;\n\tu32 uinteger;\n\n\t~ResourceValue() = default;\n\tResourceValue() = default;\n\tResourceValue(ResourceValue const&) = default;\n\tResourceValue(ResourceValue&&) = default;\n\tResourceValue& operator=(ResourceValue const&) = default;\n\tResourceValue& operator=(ResourceValue&&) = default;\n\n\t\/\/\/ Construct with pointer.\n\tResourceValue(void* const pointer) : pointer(pointer) {}\n\n\t\/\/\/ Construct with 32-bit unsigned integer.\n\tResourceValue(u32 const uinteger) : uinteger(uinteger) {}\n\n\t\/\/\/ Whether pointer is valid.\n\tbool valid() const {\n\t\treturn pointer != nullptr;\n\t}\n};\n\n\/\/\/ Test resource.\nstruct TestResource {\n\ts64 x;\n};\n\n\/\/ Forward declarations\nstruct ResourceHandler;\nstruct ResourcePackage;\nstruct ResourceManager;\n\n\/\/\/ Resource stream lock.\n\/\/\/\n\/\/\/ This class opens a resource stream from a package on\n\/\/\/ initialization and closes it on deinitialization.\nstruct ResourceStreamLock {\n\tResourcePackage& _package;\n\tIReader* _stream;\n\n\tResourceStreamLock() = delete;\n\tResourceStreamLock(ResourceStreamLock const&) = delete;\n\tResourceStreamLock(ResourceStreamLock&&) = delete;\n\tResourceStreamLock& operator=(ResourceStreamLock const&) = delete;\n\tResourceStreamLock& operator=(ResourceStreamLock&&) = delete;\n\n\t\/\/\/ Close resource stream.\n\t~ResourceStreamLock();\n\n\t\/\/\/ Open resource stream.\n\tResourceStreamLock(\n\t\tResourcePackage& package,\n\t\tu32 id\n\t);\n\n\t\/\/\/ Resource stream.\n\tIReader& stream();\n};\n\n\/**\n\t@addtogroup lib_game_resource_handler\n\t@{\n*\/\n\n\/\/\/ Resource handler.\nstruct ResourceHandler {\n\t\/\/\/ Load a resource.\n\t\/\/\/\n\t\/\/\/ Returns pointer to resource, or nullptr on error.\n\tusing load_func_type = ResourceValue (\n\t\tvoid* const type_data,\n\t\tResourceManager& manager,\n\t\tResourcePackage& package,\n\t\tResourceMetadata const& metadata\n\t);\n\n\t\/\/\/ Unload a resource.\n\tusing unload_func_type = void (\n\t\tvoid* const type_data,\n\t\tResourceManager& manager,\n\t\tResourceValue const resource\n\t);\n\n\tResourceType type;\n\tu32 format_version;\n\tvoid* type_data;\n\tload_func_type* func_load;\n\tunload_func_type* func_unload;\n};\n\n\/** @} *\/ \/\/ end of doc-group lib_game_resource_handler\n\n\/**\n\t@addtogroup lib_game_resource_package\n\t@{\n*\/\n\n\/\/\/ Resource package.\nstruct ResourcePackage {\n\tusing LookupNode = HashMapNode<ResourceNameHash, u32>;\n\n\tResourcePackageNameHash _name_hash;\n\tu32 _open_resource_id;\n\tFileReader _stream;\n\tHashMap<ResourceNameHash, u32> _lookup;\n\tArray<ResourceMetadata> _manifest;\n\tFixedArray<char, 48> _name;\n\tFixedArray<char, 256> _path;\n\n\tResourcePackage() = delete;\n\tResourcePackage(ResourcePackage const&) = delete;\n\tResourcePackage(ResourcePackage&&) = delete;\n\tResourcePackage& operator=(ResourcePackage const&) = delete;\n\tResourcePackage& operator=(ResourcePackage&&) = delete;\n\n\t~ResourcePackage() = default;\n\n\tResourcePackage(\n\t\tStringRef const& name,\n\t\tStringRef const& path,\n\t\tAllocator& allocator\n\t);\n};\n\n\/** @} *\/ \/\/ end of doc-group lib_game_resource_package\n\n\/**\n\t@addtogroup lib_game_resource_manager\n\t@{\n*\/\n\n\/\/\/ Resource manager.\nstruct ResourceManager {\n\tstruct TypedResourceValue {\n\t\tResourceValue value;\n\t\tResourceType type;\n\t};\n\n\tusing ActiveNode = HashMapNode<ResourceNameHash, TypedResourceValue>;\n\n\tHashMap<ResourceType, ResourceHandler> _handlers;\n\tHashMap<ResourceNameHash, TypedResourceValue> _resources;\n\tArray<ResourcePackage*> _packages;\n\tFixedArray<char, 128> _base_path;\n\n\tResourceManager() = delete;\n\tResourceManager(ResourceManager const&) = delete;\n\tResourceManager(ResourceManager&&) = delete;\n\tResourceManager& operator=(ResourceManager const&) = delete;\n\tResourceManager& operator=(ResourceManager&&) = delete;\n\n\t~ResourceManager();\n\tResourceManager(\n\t\tStringRef const base_path,\n\t\tAllocator& allocator\n\t);\n};\n\n\/** @} *\/ \/\/ end of doc-group lib_game_resource_manager\n\n\/** @} *\/ \/\/ end of doc-group lib_game_resource\n\n} \/\/ namespace togo\n<commit_msg>lib\/game\/resource: corrected RES_NAME_SHADER_CONFIG.¹<commit_after>#line 2 \"togo\/game\/resource\/types.hpp\"\n\/**\n@copyright MIT license; see @ref index or the accompanying LICENSE file.\n\n@file\n@brief Resource types.\n@ingroup lib_game_types\n@ingroup lib_game_resource\n*\/\n\n#pragma once\n\n#include <togo\/game\/config.hpp>\n#include <togo\/core\/types.hpp>\n#include <togo\/core\/utility\/traits.hpp>\n#include <togo\/core\/memory\/types.hpp>\n#include <togo\/core\/collection\/types.hpp>\n#include <togo\/core\/string\/types.hpp>\n#include <togo\/core\/hash\/types.hpp>\n#include <togo\/core\/hash\/hash.hpp>\n#include <togo\/core\/io\/types.hpp>\n#include <togo\/core\/io\/file_stream.hpp>\n\nnamespace togo {\n\n\/**\n\t@addtogroup lib_game_resource\n\t@{\n*\/\n\n\/\/\/ Format versions.\nenum : u32 {\n\t\/\/\/ ResourcePackage manifest format version.\n\tSER_FORMAT_VERSION_PKG_MANIFEST = 3,\n};\n\n\/\/\/ Resource type.\nusing ResourceType = hash32;\n\n\/\/\/ Resource name hash.\nusing ResourceNameHash = hash64;\n\n\/\/\/ Combined resource tags hash.\nusing ResourceTagsHash = hash64;\n\n\/\/\/ Combined resource tags hash combiner.\nusing ResourceTagsHashCombiner = HashCombiner64;\n\n\/\/\/ Package name hash.\nusing ResourcePackageNameHash = hash32;\n\n\/** @cond INTERNAL *\/\nstatic_assert(\n\tis_same<ResourceType, hash32>::value,\n\t\"changed ResourceType type breaks binary formats,\"\n\t\" hash functions, and likely other things\"\n);\nstatic_assert(\n\tis_same<ResourceNameHash, hash64>::value,\n\t\"changed ResourceNameHash type breaks binary formats,\"\n\t\" hash functions, and likely other things\"\n);\nstatic_assert(\n\tis_same<ResourceTagsHash, hash64>::value,\n\t\"changed ResourceTagsHash type breaks binary formats,\"\n\t\" hash functions, and likely other things\"\n);\n\/** @endcond *\/ \/\/ INTERNAL\n\n\/\/\/ Resource type hash literal.\ninline constexpr ResourceType\noperator\"\" _resource_type(\n\tchar const* const data,\n\tstd::size_t const size\n) {\n\treturn hash::calc32_ce(data, size);\n}\n\n\/\/\/ Resource name hash literal.\ninline constexpr ResourceNameHash\noperator\"\" _resource_name(\n\tchar const* const data,\n\tstd::size_t const size\n) {\n\treturn hash::calc64_ce(data, size);\n}\n\n\/\/\/ Combined resource tags hash literal.\n\/\/\/\n\/\/\/ Note that this only takes a single string. Tags should be sorted\n\/\/\/ and separator-less for the return value of this literal to be\n\/\/\/ compatible with the runtime combiner-based hash function.\ninline constexpr ResourceTagsHash\noperator\"\" _resource_tags(\n\tchar const* const data,\n\tstd::size_t const size\n) {\n\treturn hash::calc64_ce(data, size);\n}\n\n\/\/\/ Package name hash literal.\ninline constexpr ResourcePackageNameHash\noperator\"\" _resource_package_name(\n\tchar const* const data,\n\tstd::size_t const size\n) {\n\treturn hash::calc32_ce(data, size);\n}\n\n\/\/\/ Resource types.\nenum : ResourceType {\n\t\/\/\/ Non-type.\n\tRES_TYPE_NULL = \"\"_resource_type,\n\n\t\/\/\/ TestResource.\n\tRES_TYPE_TEST = \"test\"_resource_type,\n\n\t\/\/\/ gfx::ShaderDef.\n\tRES_TYPE_SHADER_PRELUDE = \"shader_prelude\"_resource_type,\n\n\t\/\/\/ gfx::ShaderID.\n\tRES_TYPE_SHADER = \"shader\"_resource_type,\n\n\t\/\/\/ gfx::RenderConfig.\n\tRES_TYPE_RENDER_CONFIG = \"render_config\"_resource_type,\n};\n\n\/\/\/ Resource names.\nenum : ResourceNameHash {\n\t\/\/\/ Null name.\n\tRES_NAME_NULL = \"\"_resource_name,\n\n\t\/\/\/ Shared shader configuration shader_prelude.\n\tRES_NAME_SHADER_CONFIG = \"togo\/gfx\/shader-config\"_resource_name,\n};\n\n\/\/\/ Combined resource tags.\nenum : ResourceTagsHash {\n\t\/\/\/ Null tags.\n\tRES_TAGS_NULL = \"\"_resource_tags,\n};\n\n\/\/\/ Resource package names.\nenum : ResourcePackageNameHash {\n\t\/\/\/ Null name.\n\tPKG_NAME_NULL = \"\"_resource_package_name,\n};\n\n\/\/\/ Resource path parts.\nstruct ResourcePathParts {\n\tstruct Tag {\n\t\tStringRef name{};\n\t\thash32 hash;\n\t};\n\n\tResourceType type_hash;\n\tResourceNameHash name_hash;\n\tResourceTagsHash tags_hash;\n\tStringRef type{};\n\tStringRef name{};\n\tFixedArray<Tag, 8> tags;\n};\n\n\/\/\/ Path to compiled resource.\nstruct ResourceCompiledPath {\n\tu32 id;\n\tFixedArray<char, 24> _data{};\n\n\t~ResourceCompiledPath() = default;\n\n\tResourceCompiledPath(ResourceCompiledPath const&) = delete;\n\tResourceCompiledPath(ResourceCompiledPath&&) = delete;\n\tResourceCompiledPath& operator=(ResourceCompiledPath const&) = delete;\n\tResourceCompiledPath& operator=(ResourceCompiledPath&&) = delete;\n\n\tResourceCompiledPath();\n\n\toperator StringRef() const;\n\n\tu32 size() const;\n\tchar const* data() const;\n};\n\n\/\/\/ Resource metadata.\nstruct ResourceMetadata {\n\tu32 id;\n\n\t\/\/ Serial\n\tResourceNameHash name_hash;\n\tResourceTagsHash tags_hash;\n\tResourceType type;\n\tu32 data_format_version;\n\tu32 data_offset;\n\tu32 data_size;\n};\n\n\/\/\/ Resource value.\nunion ResourceValue {\n\tvoid* pointer;\n\tu32 uinteger;\n\n\t~ResourceValue() = default;\n\tResourceValue() = default;\n\tResourceValue(ResourceValue const&) = default;\n\tResourceValue(ResourceValue&&) = default;\n\tResourceValue& operator=(ResourceValue const&) = default;\n\tResourceValue& operator=(ResourceValue&&) = default;\n\n\t\/\/\/ Construct with pointer.\n\tResourceValue(void* const pointer) : pointer(pointer) {}\n\n\t\/\/\/ Construct with 32-bit unsigned integer.\n\tResourceValue(u32 const uinteger) : uinteger(uinteger) {}\n\n\t\/\/\/ Whether pointer is valid.\n\tbool valid() const {\n\t\treturn pointer != nullptr;\n\t}\n};\n\n\/\/\/ Test resource.\nstruct TestResource {\n\ts64 x;\n};\n\n\/\/ Forward declarations\nstruct ResourceHandler;\nstruct ResourcePackage;\nstruct ResourceManager;\n\n\/\/\/ Resource stream lock.\n\/\/\/\n\/\/\/ This class opens a resource stream from a package on\n\/\/\/ initialization and closes it on deinitialization.\nstruct ResourceStreamLock {\n\tResourcePackage& _package;\n\tIReader* _stream;\n\n\tResourceStreamLock() = delete;\n\tResourceStreamLock(ResourceStreamLock const&) = delete;\n\tResourceStreamLock(ResourceStreamLock&&) = delete;\n\tResourceStreamLock& operator=(ResourceStreamLock const&) = delete;\n\tResourceStreamLock& operator=(ResourceStreamLock&&) = delete;\n\n\t\/\/\/ Close resource stream.\n\t~ResourceStreamLock();\n\n\t\/\/\/ Open resource stream.\n\tResourceStreamLock(\n\t\tResourcePackage& package,\n\t\tu32 id\n\t);\n\n\t\/\/\/ Resource stream.\n\tIReader& stream();\n};\n\n\/**\n\t@addtogroup lib_game_resource_handler\n\t@{\n*\/\n\n\/\/\/ Resource handler.\nstruct ResourceHandler {\n\t\/\/\/ Load a resource.\n\t\/\/\/\n\t\/\/\/ Returns pointer to resource, or nullptr on error.\n\tusing load_func_type = ResourceValue (\n\t\tvoid* const type_data,\n\t\tResourceManager& manager,\n\t\tResourcePackage& package,\n\t\tResourceMetadata const& metadata\n\t);\n\n\t\/\/\/ Unload a resource.\n\tusing unload_func_type = void (\n\t\tvoid* const type_data,\n\t\tResourceManager& manager,\n\t\tResourceValue const resource\n\t);\n\n\tResourceType type;\n\tu32 format_version;\n\tvoid* type_data;\n\tload_func_type* func_load;\n\tunload_func_type* func_unload;\n};\n\n\/** @} *\/ \/\/ end of doc-group lib_game_resource_handler\n\n\/**\n\t@addtogroup lib_game_resource_package\n\t@{\n*\/\n\n\/\/\/ Resource package.\nstruct ResourcePackage {\n\tusing LookupNode = HashMapNode<ResourceNameHash, u32>;\n\n\tResourcePackageNameHash _name_hash;\n\tu32 _open_resource_id;\n\tFileReader _stream;\n\tHashMap<ResourceNameHash, u32> _lookup;\n\tArray<ResourceMetadata> _manifest;\n\tFixedArray<char, 48> _name;\n\tFixedArray<char, 256> _path;\n\n\tResourcePackage() = delete;\n\tResourcePackage(ResourcePackage const&) = delete;\n\tResourcePackage(ResourcePackage&&) = delete;\n\tResourcePackage& operator=(ResourcePackage const&) = delete;\n\tResourcePackage& operator=(ResourcePackage&&) = delete;\n\n\t~ResourcePackage() = default;\n\n\tResourcePackage(\n\t\tStringRef const& name,\n\t\tStringRef const& path,\n\t\tAllocator& allocator\n\t);\n};\n\n\/** @} *\/ \/\/ end of doc-group lib_game_resource_package\n\n\/**\n\t@addtogroup lib_game_resource_manager\n\t@{\n*\/\n\n\/\/\/ Resource manager.\nstruct ResourceManager {\n\tstruct TypedResourceValue {\n\t\tResourceValue value;\n\t\tResourceType type;\n\t};\n\n\tusing ActiveNode = HashMapNode<ResourceNameHash, TypedResourceValue>;\n\n\tHashMap<ResourceType, ResourceHandler> _handlers;\n\tHashMap<ResourceNameHash, TypedResourceValue> _resources;\n\tArray<ResourcePackage*> _packages;\n\tFixedArray<char, 128> _base_path;\n\n\tResourceManager() = delete;\n\tResourceManager(ResourceManager const&) = delete;\n\tResourceManager(ResourceManager&&) = delete;\n\tResourceManager& operator=(ResourceManager const&) = delete;\n\tResourceManager& operator=(ResourceManager&&) = delete;\n\n\t~ResourceManager();\n\tResourceManager(\n\t\tStringRef const base_path,\n\t\tAllocator& allocator\n\t);\n};\n\n\/** @} *\/ \/\/ end of doc-group lib_game_resource_manager\n\n\/** @} *\/ \/\/ end of doc-group lib_game_resource\n\n} \/\/ namespace togo\n<|endoftext|>"} {"text":"<commit_before>\/* bzflag\n* Copyright (c) 1993 - 2005 Tim Riker\n*\n* This package is free software; you can redistribute it and\/or\n* modify it under the terms of the license found in the file\n* named COPYING that should have accompanied this file.\n*\n* THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR\n* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED\n* WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.\n*\/\n\n\/\/ implementation wrapers for all the bza_ API functions\n#include \"bzfsAPI.h\"\n\n#include \"common.h\"\n#include \"bzfs.h\"\n#include \"WorldWeapons.h\"\n#include \"WorldEventManager.h\"\n#include \"GameKeeper.h\"\n#include \"FlagInfo.h\"\n\n#include \"commands.h\"\n#include \"SpawnPosition.h\"\n#include \"WorldInfo.h\"\n\n#include \"BzMaterial.h\"\n\nTimeKeeper synct = TimeKeeper::getCurrent();\n\nextern void sendMessage(int playerIndex, PlayerId dstPlayer, const char *message);\nextern void removePlayer(int playerIndex, const char *reason, bool notify);\nextern void zapFlagByPlayer(int playerIndex);\n\nextern CmdLineOptions *clOptions;\nextern uint16_t curMaxPlayers;\nextern WorldInfo *world;\nextern float pluginWorldSize;\nextern float pluginWorldHeight;\nextern float pluginMaxWait;\n\n\/\/ utility\nvoid setBZMatFromAPIMat (BzMaterial &bzmat, bz_MaterialInfo* material )\n{\n\tif (!material)\n\t\treturn;\n\n\tbzmat.setName(material->name);\n\tbzmat.setAmbient(material->ambient);\n\tbzmat.setDiffuse(material->diffuse);\n\tbzmat.setSpecular(material->specular);\n\tbzmat.setEmission(material->emisive);\n\tbzmat.setShininess(material->shine);\n\n\tbzmat.setNoCulling(!material->culling);\n\tbzmat.setNoSorting(!material->sorting);\n\tbzmat.setAlphaThreshold(material->alphaThresh);\n\n\tfor( unsigned int i = 0; i < material->textures.size();i++ )\n\t{\n\t\tbzmat.addTexture(material->textures[i].texture);\n\t\tbzmat.setCombineMode(material->textures[i].combineMode);\n\t\tbzmat.setUseTextureAlpha(material->textures[i].useAlpha);\n\t\tbzmat.setUseColorOnTexture(material->textures[i].useColorOnTexture);\n\t\tbzmat.setUseSphereMap(material->textures[i].useSphereMap);\n\t}\n}\n\n\n\/\/ versioning\nBZF_API int bz_APIVersion ( void )\n{\n\treturn BZ_API_VERSION;\n}\n\nBZF_API bool bz_registerEvent ( bz_teEventType eventType, int team, bz_EventHandler* eventHandler )\n{\n\tif (!eventHandler)\n\t\treturn false;\n\t\n\tworldEventManager.addEvent((teEventType)eventType,team,(BaseEventHandler*)eventHandler);\n\treturn true;\n}\n\nBZF_API bool bz_registerGeneralEvent ( bz_teEventType eventType, bz_EventHandler* eventHandler )\n{\n\treturn bz_registerEvent(eventType,-1,eventHandler);\n}\n\nBZF_API bool bz_removeEvent ( bz_teEventType eventType, int team, bz_EventHandler* eventHandler )\n{\n\tif (!eventHandler)\n\t\treturn false;\n\n\tworldEventManager.removeEvent((teEventType)eventType,team,(BaseEventHandler*)eventHandler);\n\treturn true;\n}\n\nBZF_API bool bz_updatePlayerData ( bz_PlayerRecord *playerRecord )\n{\n\tif (!playerRecord)\n\t\treturn false;\n\n\tGameKeeper::Player *player = GameKeeper::Player::getPlayerByIndex(playerRecord->playerID);\n\tif (!player)\n\t\treturn false;\n\n\tmemcpy(playerRecord->pos,player->lastState->pos,sizeof(float)*3);\n\n\tplayerRecord->rot = player->lastState->azimuth;\n\n\tint flagid = player->player.getFlag();\n\tFlagInfo *flagInfo = FlagInfo::get(flagid);\n\n\tplayerRecord->currentFlag = flagInfo->flag.type->label();\n\n\tstd::vector<FlagType*>\tflagHistoryList = player->flagHistory.get();\n\n\tplayerRecord->flagHistory.clear();\n\tfor ( unsigned int i = 0; i < flagHistoryList.size(); i ++)\n\t\tplayerRecord->flagHistory.push_back(flagHistoryList[i]->label());\n\n\tplayerRecord->groups.clear();\n\tplayerRecord->groups = player->accessInfo.groups;\n\n\tplayerRecord->admin = player->accessInfo.isVerified();\n\n\tplayerRecord->wins = player->score.getWins();\n\tplayerRecord->losses = player->score.getLosses();\n\n\treturn true;\n}\n\nBZF_API bool bz_getPlayerIndexList ( std::vector<int> *playerList )\n{\n\tplayerList->clear();\n\n\tfor (int i = 0; i < curMaxPlayers; i++)\n\t{\n\t\tGameKeeper::Player *p = GameKeeper::Player::getPlayerByIndex(i);\n\t\tif ((p == NULL))\n\t\t\tcontinue;\n\n\t\tplayerList->push_back(i);\n\t}\n\treturn playerList->size() > 0;\n}\n\nBZF_API bool bz_getPlayerByIndex ( int index, bz_PlayerRecord *playerRecord )\n{\n\tGameKeeper::Player *player = GameKeeper::Player::getPlayerByIndex(index);\n\n\tif (!player || !playerRecord)\n\t\treturn false;\n\n\tplayerRecord->callsign = player->player.getCallSign();\n\tplayerRecord->playerID = index;\n\tplayerRecord->team = player->player.getTeam();\n\n\tplayerRecord->spawned = player->player.isAlive();\n\tplayerRecord->verified = player->accessInfo.isVerified();\n\tplayerRecord->globalUser = player->authentication.isGlobal();\n\n\tplayerRecord->ipAddress = player->netHandler->getTargetIP();\n\tplayerRecord->update();\n\treturn true;\n}\n\nBZF_API bool bz_sendTextMessage(int from, int to, const char* message)\n{\n\tif (!message)\n\t\treturn false;\n\n\tint playerIndex;\n\tPlayerId dstPlayer;\n\n\tif (to == BZ_ALL_USERS)\n\t\tdstPlayer = AllPlayers;\n\telse\n\t\tdstPlayer = (PlayerId)to;\n\n\tif (from == BZ_SERVER)\n\t\tplayerIndex = ServerPlayer;\n\telse\n\t\tplayerIndex = from;\n\n\tsendMessage(playerIndex, dstPlayer, message);\n\treturn true;\n}\n\nBZF_API bool bz_fireWorldWep ( std::string flagType, float lifetime, int fromPlayer, float *pos, float tilt, float direction, int shotID, float dt )\n{\n\tif (!pos || !flagType.size())\n\t\treturn false;\n\n\tFlagTypeMap &flagMap = FlagType::getFlagMap();\n\tif (flagMap.find(flagType) == flagMap.end())\n\t\treturn false;\n\n\tFlagType *flag = flagMap.find(flagType)->second;\n\n\tPlayerId player;\n\tif ( fromPlayer == BZ_SERVER )\n\t\tplayer = ServerPlayer;\n\telse\n\t\tplayer = fromPlayer;\n\n\treturn fireWorldWep(flag,lifetime,player,pos,tilt,direction,shotID,dt) == shotID;\n}\n\n\/\/ time API\nBZF_API double bz_getCurrentTime ( void )\n{\n\treturn TimeKeeper::getCurrent().getSeconds();\n}\n\nBZF_API float bz_getMaxWaitTime ( void )\n{\n\treturn pluginMaxWait;\n}\n\nBZF_API void bz_setMaxWaitTime ( float time )\n{\n\tif ( pluginMaxWait > time)\n\t\tpluginMaxWait = time;\n}\n\n\n\/\/ info\nBZF_API double bz_getBZDBDouble ( const char* variable )\n{\n\tif (!variable)\n\t\treturn 0.0;\n\n\treturn BZDB.eval(std::string(variable));\n}\n\nBZF_API std::string bz_getBZDString( const char* variable )\n{\n\tif (!variable)\n\t\treturn std::string(\"\");\n\n\treturn BZDB.get(std::string(variable));\n}\n\nBZF_API bool bz_getBZDBool( const char* variable )\n{\n\tif (!variable)\n\t\treturn false;\n\n\treturn BZDB.eval(std::string(variable)) > 0.0;\n}\n\nBZF_API int bz_getBZDInt( const char* variable )\n{\n\treturn (int)BZDB.eval(std::string(variable));\n}\n\n\/\/ loging\nBZF_API void bz_debugMessage ( int _debugLevel, const char* message )\n{\n\tif (!message)\n\t\treturn;\n\n\tif (debugLevel >= _debugLevel)\n\t\tformatDebug(\"%s\\n\",message);\n}\n\n\/\/ admin\nBZF_API bool bz_kickUser ( int playerIndex, const char* reason, bool notify )\n{\n\tGameKeeper::Player *player = GameKeeper::Player::getPlayerByIndex(playerIndex);\n\tif (!player || !reason)\n\t\treturn false;\n\n\tremovePlayer(playerIndex,reason,notify);\n\treturn true;\n}\n\nBZF_API bool bz_IPBanUser ( int playerIndex, const char* ip, int time, const char* reason )\n{\n\tGameKeeper::Player *player = GameKeeper::Player::getPlayerByIndex(playerIndex);\n\tif (!player || !reason || !ip)\n\t\treturn false;\n\n\t\/\/ reload the banlist in case anyone else has added\n\tclOptions->acl.load();\n\n\tif (clOptions->acl.ban(ip, player->player.getCallSign(), time,reason))\n\t\tclOptions->acl.save();\n\telse\n\t\treturn false;\n\n\treturn true;\n}\n\nBZF_API bool bz_registerCustomSlashCommand ( const char* command, bz_CustomSlashCommandHandler *handler )\n{\n\tif (!command || !handler)\n\t\treturn false;\n\n\tregisterCustomSlashCommand(std::string(command),(CustomSlashCommandHandler*)handler);\n\treturn true;\n}\n\nBZF_API bool bz_removeCustomSlashCommand ( const char* command )\n{\n\tif (!command)\n\t\treturn false;\n\n\tremoveCustomSlashCommand(std::string(command));\n\treturn true;\n}\n\nBZF_API bool bz_getStandardSpawn ( int playeID, float pos[3], float *rot )\n{\n\tGameKeeper::Player *player = GameKeeper::Player::getPlayerByIndex(playeID);\n\tif (!player)\n\t\treturn false;\n\n\t\/\/ get the spawn position\n\tSpawnPosition* spawnPosition = new SpawnPosition(playeID,\n\t\t(!clOptions->respawnOnBuildings) || (player->player.isBot()),\n\t\tclOptions->gameStyle & TeamFlagGameStyle);\n\n\tpos[0] = spawnPosition->getX();\n\tpos[1] = spawnPosition->getY();\n\tpos[2] = spawnPosition->getZ();\n\tif (rot)\n\t\t*rot = spawnPosition->getAzimuth();\n\n\treturn true;\n}\n\nBZF_API bool bz_killPlayer ( int playeID, bool spawnOnBase )\n{\n\tGameKeeper::Player *player = GameKeeper::Player::getPlayerByIndex(playeID);\n\tif (!player)\n\t\treturn false;\n\n\tif (!player->player.isAlive())\n\t\treturn false;\n\n\tplayer->player.setDead();\n\tplayer->player.setRestartOnBase(spawnOnBase);\n\tzapFlagByPlayer(playeID);\n\n\treturn true;\n}\n\nBZF_API bool bz_removePlayerFlag ( int playeID )\n{\n\tGameKeeper::Player *player = GameKeeper::Player::getPlayerByIndex(playeID);\n\tif (!player)\n\t\treturn false;\n\n\tif (!player->player.isAlive())\n\t\treturn false;\n\n\tzapFlagByPlayer(playeID);\n\n\treturn true;\n}\n\nBZF_API bool bz_addWorldBox ( float *pos, float rot, float* scale, bz_WorldObjectOptions options )\n{\n\tif (!world || world->isFinisihed() || !pos || !scale)\n\t\treturn false;\n\n\tworld->addBox(pos[0],pos[1],pos[2],rot,scale[0],scale[1],scale[2],options.driveThru,options.shootThru);\n\treturn true;\n}\n\nBZF_API bool bz_addWorldPyramid ( float *pos, float rot, float* scale, bool fliped, bz_WorldObjectOptions options )\n{\n\tif (!world || world->isFinisihed() || !pos || !scale)\n\t\treturn false;\n\n\tworld->addPyramid(pos[0],pos[1],pos[2],rot,scale[0],scale[1],scale[2],options.driveThru,options.shootThru,fliped);\n\treturn true;\n}\n\nBZF_API bool bz_addWorldBase( float *pos, float rot, float* scale, int team, bz_WorldObjectOptions options )\n{\n\tif (!world || world->isFinisihed() || !pos || !scale)\n\t\treturn false;\n\n\tworld->addBase(pos,rot,scale,team,options.driveThru,options.shootThru);\n\treturn true;\n}\n\nBZF_API bool bz_addWorldTeleporter ( float *pos, float rot, float* scale, float border, bz_WorldObjectOptions options )\n{\n\tif (!world || world->isFinisihed() || !pos || !scale)\n\t\treturn false;\n\n\tworld->addTeleporter(pos[0],pos[1],pos[2],rot,scale[0],scale[1],scale[2],border,false,options.driveThru,options.shootThru);\n\treturn true;\n}\n\nBZF_API bool bz_addWorldLink( int from, int to )\n{\n\tif (!world || world->isFinisihed() )\n\t\treturn false;\n\n\tworld->addLink(from,to);\n\treturn true;\n}\n\nBZF_API bool bz_addWorldWaterLevel( float level, bz_MaterialInfo *material )\n{\n\tif (!world || world->isFinisihed() )\n\t\treturn false;\n\n\tif (!material)\n\t{\n\t\tworld->addWaterLevel(level,NULL);\n\t\treturn true;\n\t}\n\n\tBzMaterial\tbzmat;\n\tsetBZMatFromAPIMat(bzmat,material);\n\tworld->addWaterLevel(level,MATERIALMGR.addMaterial(&bzmat));\n\treturn true;\n}\n\nBZF_API bool bz_addWorldWeapon( std::string flagType, float *pos, float rot, float tilt, float initDelay, std::vector<float> delays )\n{\n\tif (!world || world->isFinisihed() )\n\t\treturn false;\n\n\tFlagTypeMap &flagMap = FlagType::getFlagMap();\n\tif (flagMap.find(flagType) == flagMap.end())\n\t\treturn false;\n\n\tFlagType *flag = flagMap.find(flagType)->second;\n\n\tworld->addWeapon(flag, pos, rot, tilt, initDelay, delays, synct);\n\treturn true;\n}\n\n\nBZF_API bool bz_setWorldSize( float size, float wallHeight )\n{\n\tpluginWorldHeight = wallHeight;\n\tpluginWorldSize = size;\n\n\treturn true;\n}\n\n\n\n\/\/ Local Variables: ***\n\/\/ mode:C++ ***\n\/\/ tab-width: 8 ***\n\/\/ c-basic-offset: 2 ***\n\/\/ indent-tabs-mode: t ***\n\/\/ End: ***\n\/\/ ex: shiftwidth=2 tabstop=8\n<commit_msg>less crashy<commit_after>\/* bzflag\n* Copyright (c) 1993 - 2005 Tim Riker\n*\n* This package is free software; you can redistribute it and\/or\n* modify it under the terms of the license found in the file\n* named COPYING that should have accompanied this file.\n*\n* THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR\n* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED\n* WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.\n*\/\n\n\/\/ implementation wrapers for all the bza_ API functions\n#include \"bzfsAPI.h\"\n\n#include \"common.h\"\n#include \"bzfs.h\"\n#include \"WorldWeapons.h\"\n#include \"WorldEventManager.h\"\n#include \"GameKeeper.h\"\n#include \"FlagInfo.h\"\n\n#include \"commands.h\"\n#include \"SpawnPosition.h\"\n#include \"WorldInfo.h\"\n\n#include \"BzMaterial.h\"\n\nTimeKeeper synct = TimeKeeper::getCurrent();\n\nextern void sendMessage(int playerIndex, PlayerId dstPlayer, const char *message);\nextern void removePlayer(int playerIndex, const char *reason, bool notify);\nextern void zapFlagByPlayer(int playerIndex);\n\nextern CmdLineOptions *clOptions;\nextern uint16_t curMaxPlayers;\nextern WorldInfo *world;\nextern float pluginWorldSize;\nextern float pluginWorldHeight;\nextern float pluginMaxWait;\n\n\/\/ utility\nvoid setBZMatFromAPIMat (BzMaterial &bzmat, bz_MaterialInfo* material )\n{\n\tif (!material)\n\t\treturn;\n\n\tbzmat.setName(material->name);\n\tbzmat.setAmbient(material->ambient);\n\tbzmat.setDiffuse(material->diffuse);\n\tbzmat.setSpecular(material->specular);\n\tbzmat.setEmission(material->emisive);\n\tbzmat.setShininess(material->shine);\n\n\tbzmat.setNoCulling(!material->culling);\n\tbzmat.setNoSorting(!material->sorting);\n\tbzmat.setAlphaThreshold(material->alphaThresh);\n\n\tfor( unsigned int i = 0; i < material->textures.size();i++ )\n\t{\n\t\tbzmat.addTexture(material->textures[i].texture);\n\t\tbzmat.setCombineMode(material->textures[i].combineMode);\n\t\tbzmat.setUseTextureAlpha(material->textures[i].useAlpha);\n\t\tbzmat.setUseColorOnTexture(material->textures[i].useColorOnTexture);\n\t\tbzmat.setUseSphereMap(material->textures[i].useSphereMap);\n\t}\n}\n\n\n\/\/ versioning\nBZF_API int bz_APIVersion ( void )\n{\n\treturn BZ_API_VERSION;\n}\n\nBZF_API bool bz_registerEvent ( bz_teEventType eventType, int team, bz_EventHandler* eventHandler )\n{\n\tif (!eventHandler)\n\t\treturn false;\n\t\n\tworldEventManager.addEvent((teEventType)eventType,team,(BaseEventHandler*)eventHandler);\n\treturn true;\n}\n\nBZF_API bool bz_registerGeneralEvent ( bz_teEventType eventType, bz_EventHandler* eventHandler )\n{\n\treturn bz_registerEvent(eventType,-1,eventHandler);\n}\n\nBZF_API bool bz_removeEvent ( bz_teEventType eventType, int team, bz_EventHandler* eventHandler )\n{\n\tif (!eventHandler)\n\t\treturn false;\n\n\tworldEventManager.removeEvent((teEventType)eventType,team,(BaseEventHandler*)eventHandler);\n\treturn true;\n}\n\nBZF_API bool bz_updatePlayerData ( bz_PlayerRecord *playerRecord )\n{\n\tif (!playerRecord)\n\t\treturn false;\n\n\tGameKeeper::Player *player = GameKeeper::Player::getPlayerByIndex(playerRecord->playerID);\n\tif (!player)\n\t\treturn false;\n\n\tmemcpy(playerRecord->pos,player->lastState->pos,sizeof(float)*3);\n\n\tplayerRecord->rot = player->lastState->azimuth;\n\n\tint flagid = player->player.getFlag();\n\tFlagInfo *flagInfo = FlagInfo::get(flagid);\n\n\tif (flagInfo != NULL)\n\t\tplayerRecord->currentFlag = flagInfo->flag.type->label();\n\telse\n\t\tplayerRecord->currentFlag = std::string(\"\");\n\n\tstd::vector<FlagType*>\tflagHistoryList = player->flagHistory.get();\n\n\tplayerRecord->flagHistory.clear();\n\tfor ( unsigned int i = 0; i < flagHistoryList.size(); i ++)\n\t\tplayerRecord->flagHistory.push_back(flagHistoryList[i]->label());\n\n\tplayerRecord->groups.clear();\n\tplayerRecord->groups = player->accessInfo.groups;\n\n\tplayerRecord->admin = player->accessInfo.isVerified();\n\n\tplayerRecord->wins = player->score.getWins();\n\tplayerRecord->losses = player->score.getLosses();\n\n\treturn true;\n}\n\nBZF_API bool bz_getPlayerIndexList ( std::vector<int> *playerList )\n{\n\tplayerList->clear();\n\n\tfor (int i = 0; i < curMaxPlayers; i++)\n\t{\n\t\tGameKeeper::Player *p = GameKeeper::Player::getPlayerByIndex(i);\n\t\tif ((p == NULL))\n\t\t\tcontinue;\n\n\t\tplayerList->push_back(i);\n\t}\n\treturn playerList->size() > 0;\n}\n\nBZF_API bool bz_getPlayerByIndex ( int index, bz_PlayerRecord *playerRecord )\n{\n\tGameKeeper::Player *player = GameKeeper::Player::getPlayerByIndex(index);\n\n\tif (!player || !playerRecord)\n\t\treturn false;\n\n\tplayerRecord->callsign = player->player.getCallSign();\n\tplayerRecord->playerID = index;\n\tplayerRecord->team = player->player.getTeam();\n\n\tplayerRecord->spawned = player->player.isAlive();\n\tplayerRecord->verified = player->accessInfo.isVerified();\n\tplayerRecord->globalUser = player->authentication.isGlobal();\n\n\tplayerRecord->ipAddress = player->netHandler->getTargetIP();\n\tplayerRecord->update();\n\treturn true;\n}\n\nBZF_API bool bz_sendTextMessage(int from, int to, const char* message)\n{\n\tif (!message)\n\t\treturn false;\n\n\tint playerIndex;\n\tPlayerId dstPlayer;\n\n\tif (to == BZ_ALL_USERS)\n\t\tdstPlayer = AllPlayers;\n\telse\n\t\tdstPlayer = (PlayerId)to;\n\n\tif (from == BZ_SERVER)\n\t\tplayerIndex = ServerPlayer;\n\telse\n\t\tplayerIndex = from;\n\n\tsendMessage(playerIndex, dstPlayer, message);\n\treturn true;\n}\n\nBZF_API bool bz_fireWorldWep ( std::string flagType, float lifetime, int fromPlayer, float *pos, float tilt, float direction, int shotID, float dt )\n{\n\tif (!pos || !flagType.size())\n\t\treturn false;\n\n\tFlagTypeMap &flagMap = FlagType::getFlagMap();\n\tif (flagMap.find(flagType) == flagMap.end())\n\t\treturn false;\n\n\tFlagType *flag = flagMap.find(flagType)->second;\n\n\tPlayerId player;\n\tif ( fromPlayer == BZ_SERVER )\n\t\tplayer = ServerPlayer;\n\telse\n\t\tplayer = fromPlayer;\n\n\treturn fireWorldWep(flag,lifetime,player,pos,tilt,direction,shotID,dt) == shotID;\n}\n\n\/\/ time API\nBZF_API double bz_getCurrentTime ( void )\n{\n\treturn TimeKeeper::getCurrent().getSeconds();\n}\n\nBZF_API float bz_getMaxWaitTime ( void )\n{\n\treturn pluginMaxWait;\n}\n\nBZF_API void bz_setMaxWaitTime ( float time )\n{\n\tif ( pluginMaxWait > time)\n\t\tpluginMaxWait = time;\n}\n\n\n\/\/ info\nBZF_API double bz_getBZDBDouble ( const char* variable )\n{\n\tif (!variable)\n\t\treturn 0.0;\n\n\treturn BZDB.eval(std::string(variable));\n}\n\nBZF_API std::string bz_getBZDString( const char* variable )\n{\n\tif (!variable)\n\t\treturn std::string(\"\");\n\n\treturn BZDB.get(std::string(variable));\n}\n\nBZF_API bool bz_getBZDBool( const char* variable )\n{\n\tif (!variable)\n\t\treturn false;\n\n\treturn BZDB.eval(std::string(variable)) > 0.0;\n}\n\nBZF_API int bz_getBZDInt( const char* variable )\n{\n\treturn (int)BZDB.eval(std::string(variable));\n}\n\n\/\/ loging\nBZF_API void bz_debugMessage ( int _debugLevel, const char* message )\n{\n\tif (!message)\n\t\treturn;\n\n\tif (debugLevel >= _debugLevel)\n\t\tformatDebug(\"%s\\n\",message);\n}\n\n\/\/ admin\nBZF_API bool bz_kickUser ( int playerIndex, const char* reason, bool notify )\n{\n\tGameKeeper::Player *player = GameKeeper::Player::getPlayerByIndex(playerIndex);\n\tif (!player || !reason)\n\t\treturn false;\n\n\tremovePlayer(playerIndex,reason,notify);\n\treturn true;\n}\n\nBZF_API bool bz_IPBanUser ( int playerIndex, const char* ip, int time, const char* reason )\n{\n\tGameKeeper::Player *player = GameKeeper::Player::getPlayerByIndex(playerIndex);\n\tif (!player || !reason || !ip)\n\t\treturn false;\n\n\t\/\/ reload the banlist in case anyone else has added\n\tclOptions->acl.load();\n\n\tif (clOptions->acl.ban(ip, player->player.getCallSign(), time,reason))\n\t\tclOptions->acl.save();\n\telse\n\t\treturn false;\n\n\treturn true;\n}\n\nBZF_API bool bz_registerCustomSlashCommand ( const char* command, bz_CustomSlashCommandHandler *handler )\n{\n\tif (!command || !handler)\n\t\treturn false;\n\n\tregisterCustomSlashCommand(std::string(command),(CustomSlashCommandHandler*)handler);\n\treturn true;\n}\n\nBZF_API bool bz_removeCustomSlashCommand ( const char* command )\n{\n\tif (!command)\n\t\treturn false;\n\n\tremoveCustomSlashCommand(std::string(command));\n\treturn true;\n}\n\nBZF_API bool bz_getStandardSpawn ( int playeID, float pos[3], float *rot )\n{\n\tGameKeeper::Player *player = GameKeeper::Player::getPlayerByIndex(playeID);\n\tif (!player)\n\t\treturn false;\n\n\t\/\/ get the spawn position\n\tSpawnPosition* spawnPosition = new SpawnPosition(playeID,\n\t\t(!clOptions->respawnOnBuildings) || (player->player.isBot()),\n\t\tclOptions->gameStyle & TeamFlagGameStyle);\n\n\tpos[0] = spawnPosition->getX();\n\tpos[1] = spawnPosition->getY();\n\tpos[2] = spawnPosition->getZ();\n\tif (rot)\n\t\t*rot = spawnPosition->getAzimuth();\n\n\treturn true;\n}\n\nBZF_API bool bz_killPlayer ( int playeID, bool spawnOnBase )\n{\n\tGameKeeper::Player *player = GameKeeper::Player::getPlayerByIndex(playeID);\n\tif (!player)\n\t\treturn false;\n\n\tif (!player->player.isAlive())\n\t\treturn false;\n\n\tplayer->player.setDead();\n\tplayer->player.setRestartOnBase(spawnOnBase);\n\tzapFlagByPlayer(playeID);\n\n\treturn true;\n}\n\nBZF_API bool bz_removePlayerFlag ( int playeID )\n{\n\tGameKeeper::Player *player = GameKeeper::Player::getPlayerByIndex(playeID);\n\tif (!player)\n\t\treturn false;\n\n\tif (!player->player.isAlive())\n\t\treturn false;\n\n\tzapFlagByPlayer(playeID);\n\n\treturn true;\n}\n\nBZF_API bool bz_addWorldBox ( float *pos, float rot, float* scale, bz_WorldObjectOptions options )\n{\n\tif (!world || world->isFinisihed() || !pos || !scale)\n\t\treturn false;\n\n\tworld->addBox(pos[0],pos[1],pos[2],rot,scale[0],scale[1],scale[2],options.driveThru,options.shootThru);\n\treturn true;\n}\n\nBZF_API bool bz_addWorldPyramid ( float *pos, float rot, float* scale, bool fliped, bz_WorldObjectOptions options )\n{\n\tif (!world || world->isFinisihed() || !pos || !scale)\n\t\treturn false;\n\n\tworld->addPyramid(pos[0],pos[1],pos[2],rot,scale[0],scale[1],scale[2],options.driveThru,options.shootThru,fliped);\n\treturn true;\n}\n\nBZF_API bool bz_addWorldBase( float *pos, float rot, float* scale, int team, bz_WorldObjectOptions options )\n{\n\tif (!world || world->isFinisihed() || !pos || !scale)\n\t\treturn false;\n\n\tworld->addBase(pos,rot,scale,team,options.driveThru,options.shootThru);\n\treturn true;\n}\n\nBZF_API bool bz_addWorldTeleporter ( float *pos, float rot, float* scale, float border, bz_WorldObjectOptions options )\n{\n\tif (!world || world->isFinisihed() || !pos || !scale)\n\t\treturn false;\n\n\tworld->addTeleporter(pos[0],pos[1],pos[2],rot,scale[0],scale[1],scale[2],border,false,options.driveThru,options.shootThru);\n\treturn true;\n}\n\nBZF_API bool bz_addWorldLink( int from, int to )\n{\n\tif (!world || world->isFinisihed() )\n\t\treturn false;\n\n\tworld->addLink(from,to);\n\treturn true;\n}\n\nBZF_API bool bz_addWorldWaterLevel( float level, bz_MaterialInfo *material )\n{\n\tif (!world || world->isFinisihed() )\n\t\treturn false;\n\n\tif (!material)\n\t{\n\t\tworld->addWaterLevel(level,NULL);\n\t\treturn true;\n\t}\n\n\tBzMaterial\tbzmat;\n\tsetBZMatFromAPIMat(bzmat,material);\n\tworld->addWaterLevel(level,MATERIALMGR.addMaterial(&bzmat));\n\treturn true;\n}\n\nBZF_API bool bz_addWorldWeapon( std::string flagType, float *pos, float rot, float tilt, float initDelay, std::vector<float> delays )\n{\n\tif (!world || world->isFinisihed() )\n\t\treturn false;\n\n\tFlagTypeMap &flagMap = FlagType::getFlagMap();\n\tif (flagMap.find(flagType) == flagMap.end())\n\t\treturn false;\n\n\tFlagType *flag = flagMap.find(flagType)->second;\n\n\tworld->addWeapon(flag, pos, rot, tilt, initDelay, delays, synct);\n\treturn true;\n}\n\n\nBZF_API bool bz_setWorldSize( float size, float wallHeight )\n{\n\tpluginWorldHeight = wallHeight;\n\tpluginWorldSize = size;\n\n\treturn true;\n}\n\n\n\n\/\/ Local Variables: ***\n\/\/ mode:C++ ***\n\/\/ tab-width: 8 ***\n\/\/ c-basic-offset: 2 ***\n\/\/ indent-tabs-mode: t ***\n\/\/ End: ***\n\/\/ ex: shiftwidth=2 tabstop=8\n<|endoftext|>"} {"text":"<commit_before>\/* http_bidder_interface.cc\n Eric Robert, 2 April 2014\n Copyright (c) 2011 Datacratic. All rights reserved.\n*\/\n\n#include \"http_bidder_interface.h\"\n#include \"jml\/db\/persistent.h\"\n#include \"soa\/service\/http_client.h\"\n#include \"rtbkit\/common\/messages.h\"\n#include \"rtbkit\/plugins\/bid_request\/openrtb_bid_request.h\"\n#include \"rtbkit\/openrtb\/openrtb_parsing.h\"\n#include \"rtbkit\/core\/router\/router.h\"\n\nusing namespace Datacratic;\nusing namespace RTBKIT;\n\nnamespace {\n DefaultDescription<OpenRTB::BidRequest> desc;\n}\n\nHttpBidderInterface::HttpBidderInterface(std::string name,\n std::shared_ptr<ServiceProxies> proxies,\n Json::Value const & json) {\n host = json[\"host\"].asString();\n path = json[\"path\"].asString();\n httpClient.reset(new HttpClient(host));\n loop.addSource(\"HttpBidderInterface::httpClient\", httpClient);\n}\n\nvoid HttpBidderInterface::sendAuctionMessage(std::shared_ptr<Auction> const & auction,\n double timeLeftMs,\n std::map<std::string, BidInfo> const & bidders) {\n for(auto & item : bidders) {\n auto & agent = item.first;\n auto & info = router->agents[agent];\n WinCostModel wcm = auction->exchangeConnector->getWinCostModel(*auction, *info.config);\n\n OpenRTB::BidRequest openRtbRequest = toOpenRtb(*auction->request);\n StructuredJsonPrintingContext context;\n desc.printJson(&openRtbRequest, context);\n auto requestStr = context.output.toString();\n\n auto callbacks = std::make_shared<HttpClientSimpleCallbacks>(\n [&](const HttpRequest &, HttpClientError errorCode,\n int, const std::string &, const std::string &body)\n {\n if (errorCode != HttpClientError::NONE) {\n auto toErrorString = [](HttpClientError code) -> std::string {\n switch (code) {\n #define CASE(code) \\\n case code: \\\n return #code;\n CASE(HttpClientError::NONE)\n CASE(HttpClientError::UNKNOWN)\n CASE(HttpClientError::TIMEOUT)\n CASE(HttpClientError::HOST_NOT_FOUND)\n CASE(HttpClientError::COULD_NOT_CONNECT)\n #undef CASE\n }\n ExcCheck(false, \"Invalid code path\");\n return \"\";\n };\n std::cerr << \"Error requesting \" << host\n << \": \" << toErrorString(errorCode);\n }\n else {\n std::cerr << \"Response: \" << body << std::endl;\n }\n });\n\n HttpRequest::Content reqContent { requestStr, \"application\/json\" };\n RestParams headers { { \"x-openrtb-version\", \"2.1\" } };\n std::cerr << \"Sending HTTP POST to: \" << host << \" \" << path << std::endl;\n std::cerr << \"Content \" << reqContent.str << std::endl;\n\n httpClient->post(path, callbacks, reqContent,\n { } \/* queryParams *\/, headers);\n }\n}\n\nvoid HttpBidderInterface::sendWinMessage(std::string const & agent,\n std::string const & id,\n Amount price) {\n}\n\nvoid HttpBidderInterface::sendLossMessage(std::string const & agent,\n std::string const & id) {\n}\n\nvoid HttpBidderInterface::sendBidLostMessage(std::string const & agent,\n std::shared_ptr<Auction> const & auction) {\n}\n\nvoid HttpBidderInterface::sendBidDroppedMessage(std::string const & agent,\n std::shared_ptr<Auction> const & auction) {\n}\n\nvoid HttpBidderInterface::sendBidInvalidMessage(std::string const & agent,\n std::string const & reason,\n std::shared_ptr<Auction> const & auction) {\n}\n\nvoid HttpBidderInterface::sendNoBudgetMessage(std::string const & agent,\n std::shared_ptr<Auction> const & auction) {\n}\n\nvoid HttpBidderInterface::sendTooLateMessage(std::string const & agent,\n std::shared_ptr<Auction> const & auction) {\n}\n\nvoid HttpBidderInterface::sendMessage(std::string const & agent,\n std::string const & message) {\n}\n\nvoid HttpBidderInterface::sendErrorMessage(std::string const & agent,\n std::string const & error,\n std::vector<std::string> const & payload) {\n}\n\nvoid HttpBidderInterface::sendPingMessage(std::string const & agent,\n int ping) {\n}\n\nvoid HttpBidderInterface::send(std::shared_ptr<PostAuctionEvent> const & event) {\n}\n\n\/\/\n\/\/ factory\n\/\/\n\nstruct AtInit {\n AtInit()\n {\n BidderInterface::registerFactory(\"http\", [](std::string const & name , std::shared_ptr<ServiceProxies> const & proxies, Json::Value const & json) {\n return new HttpBidderInterface(name, proxies, json);\n });\n }\n} atInit;\n\n<commit_msg>Added an extension field per-impression representing the allowed bidders<commit_after>\/* http_bidder_interface.cc\n Eric Robert, 2 April 2014\n Copyright (c) 2011 Datacratic. All rights reserved.\n*\/\n\n#include \"http_bidder_interface.h\"\n#include \"jml\/db\/persistent.h\"\n#include \"soa\/service\/http_client.h\"\n#include \"rtbkit\/common\/messages.h\"\n#include \"rtbkit\/plugins\/bid_request\/openrtb_bid_request.h\"\n#include \"rtbkit\/openrtb\/openrtb_parsing.h\"\n#include \"rtbkit\/core\/router\/router.h\"\n\nusing namespace Datacratic;\nusing namespace RTBKIT;\n\nnamespace {\n DefaultDescription<OpenRTB::BidRequest> desc;\n\n void tagRequest(OpenRTB::BidRequest &request,\n const std::map<std::string, BidInfo> &bidders)\n {\n\n for (const auto &bidder: bidders) {\n const auto &agentConfig = bidder.second.agentConfig;\n const auto &spots = bidder.second.imp;\n const auto &creatives = agentConfig->creatives;\n\n Json::Value creativesValue(Json::arrayValue);\n for (const auto &spot: spots) {\n const int adSpotIndex = spot.first;\n ExcCheck(adSpotIndex >= 0 && adSpotIndex < request.imp.size(),\n \"adSpotIndex out of range\");\n auto &imp = request.imp[adSpotIndex];\n auto &ext = imp.ext;\n for (int creativeIndex: spot.second) {\n ExcCheck(creativeIndex >= 0 && creativeIndex < creatives.size(),\n \"creativeIndex out of range\");\n const int creativeId = creatives[creativeIndex].id;\n creativesValue.append(creativeId);\n }\n\n ext[\"allowed_ids\"][std::to_string(agentConfig->externalId)] =\n std::move(creativesValue);\n\n }\n\n }\n\n }\n}\n\nHttpBidderInterface::HttpBidderInterface(std::string name,\n std::shared_ptr<ServiceProxies> proxies,\n Json::Value const & json) {\n host = json[\"host\"].asString();\n path = json[\"path\"].asString();\n httpClient.reset(new HttpClient(host));\n loop.addSource(\"HttpBidderInterface::httpClient\", httpClient);\n}\n\nvoid HttpBidderInterface::sendAuctionMessage(std::shared_ptr<Auction> const & auction,\n double timeLeftMs,\n std::map<std::string, BidInfo> const & bidders) {\n for(auto & item : bidders) {\n auto & agent = item.first;\n auto & info = router->agents[agent];\n WinCostModel wcm = auction->exchangeConnector->getWinCostModel(*auction, *info.config);\n\n OpenRTB::BidRequest openRtbRequest = toOpenRtb(*auction->request);\n StructuredJsonPrintingContext context;\n desc.printJson(&openRtbRequest, context);\n auto requestStr = context.output.toString();\n\n auto callbacks = std::make_shared<HttpClientSimpleCallbacks>(\n [&](const HttpRequest &, HttpClientError errorCode,\n int, const std::string &, const std::string &body)\n {\n if (errorCode != HttpClientError::NONE) {\n auto toErrorString = [](HttpClientError code) -> std::string {\n switch (code) {\n #define CASE(code) \\\n case code: \\\n return #code;\n CASE(HttpClientError::NONE)\n CASE(HttpClientError::UNKNOWN)\n CASE(HttpClientError::TIMEOUT)\n CASE(HttpClientError::HOST_NOT_FOUND)\n CASE(HttpClientError::COULD_NOT_CONNECT)\n #undef CASE\n }\n ExcCheck(false, \"Invalid code path\");\n return \"\";\n };\n std::cerr << \"Error requesting \" << host\n << \": \" << toErrorString(errorCode);\n }\n else {\n std::cerr << \"Response: \" << body << std::endl;\n }\n });\n\n HttpRequest::Content reqContent { requestStr, \"application\/json\" };\n RestParams headers { { \"x-openrtb-version\", \"2.1\" } };\n std::cerr << \"Sending HTTP POST to: \" << host << \" \" << path << std::endl;\n std::cerr << \"Content \" << reqContent.str << std::endl;\n\n httpClient->post(path, callbacks, reqContent,\n { } \/* queryParams *\/, headers);\n }\n}\n\nvoid HttpBidderInterface::sendWinMessage(std::string const & agent,\n std::string const & id,\n Amount price) {\n}\n\nvoid HttpBidderInterface::sendLossMessage(std::string const & agent,\n std::string const & id) {\n}\n\nvoid HttpBidderInterface::sendBidLostMessage(std::string const & agent,\n std::shared_ptr<Auction> const & auction) {\n}\n\nvoid HttpBidderInterface::sendBidDroppedMessage(std::string const & agent,\n std::shared_ptr<Auction> const & auction) {\n}\n\nvoid HttpBidderInterface::sendBidInvalidMessage(std::string const & agent,\n std::string const & reason,\n std::shared_ptr<Auction> const & auction) {\n}\n\nvoid HttpBidderInterface::sendNoBudgetMessage(std::string const & agent,\n std::shared_ptr<Auction> const & auction) {\n}\n\nvoid HttpBidderInterface::sendTooLateMessage(std::string const & agent,\n std::shared_ptr<Auction> const & auction) {\n}\n\nvoid HttpBidderInterface::sendMessage(std::string const & agent,\n std::string const & message) {\n}\n\nvoid HttpBidderInterface::sendErrorMessage(std::string const & agent,\n std::string const & error,\n std::vector<std::string> const & payload) {\n}\n\nvoid HttpBidderInterface::sendPingMessage(std::string const & agent,\n int ping) {\n}\n\nvoid HttpBidderInterface::send(std::shared_ptr<PostAuctionEvent> const & event) {\n}\n\n\/\/\n\/\/ factory\n\/\/\n\nstruct AtInit {\n AtInit()\n {\n BidderInterface::registerFactory(\"http\", [](std::string const & name , std::shared_ptr<ServiceProxies> const & proxies, Json::Value const & json) {\n return new HttpBidderInterface(name, proxies, json);\n });\n }\n} atInit;\n\n<|endoftext|>"} {"text":"<commit_before>\/*\r\n * The NewReality Blockchain Project.\r\n * Copyright (C) 2013, 2016 Swirly Cloud Limited.\r\n *\r\n * This program is free software; you can redistribute it and\/or modify it under the terms of the\r\n * GNU General Public License as published by the Free Software Foundation; either version 2 of the\r\n * License, or (at your option) any later version.\r\n *\r\n * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without\r\n * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\r\n * General Public License for more details.\r\n *\r\n * You should have received a copy of the GNU General Public License along with this program; if\r\n * not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA\r\n * 02110-1301, USA.\r\n *\/\r\n#ifndef MVSD_MONGOOSE_HPP\r\n#define MVSD_MONGOOSE_HPP\r\n\r\n#include <bitcoin\/explorer\/dispatch.hpp>\r\n#include \"mongoose\/mongoose.h\"\r\n\r\n#include <mvs\/http\/String.hpp>\r\n#include <mvs\/http\/Exception_error.hpp>\r\n\r\n\/**\r\n * @addtogroup Web\r\n * @{\r\n *\/\r\n\r\nnamespace http {\r\nnamespace mg {\r\n\r\n#define SESSION_COOKIE_NAME \"mvss\"\r\n\r\ninline std::string_view operator+(const mg_str& str) noexcept\r\n{\r\n return {str.p, str.len};\r\n}\r\n\r\ninline std::string_view operator+(const websocket_message& msg) noexcept\r\n{\r\n return {reinterpret_cast<char*>(msg.data), msg.size};\r\n}\r\n\r\nclass ToCommandArg{\r\npublic:\r\n auto argv() const noexcept { return argv_; }\r\n auto argc() const noexcept { return argc_; }\r\n void setargv0(std::string&& outside);\r\n\r\n static const int max_paramters{24};\r\nprotected:\r\n\r\n virtual void data_to_arg() noexcept = 0;\r\n const char* argv_[max_paramters]{{nullptr}};\r\n int argc_{0};\r\n\r\n std::vector<std::string> vargv_;\r\n};\r\n\r\n\r\nclass HttpMessage : public ToCommandArg{\r\npublic:\r\n HttpMessage(http_message* impl) noexcept : impl_{impl} {}\r\n ~HttpMessage() noexcept = default;\r\n \r\n \/\/ Copy.\r\n \/\/ http:\/\/www.open-std.org\/jtc1\/sc22\/wg21\/docs\/cwg_defects.html#1778\r\n HttpMessage(const HttpMessage&) noexcept = default;\r\n HttpMessage& operator=(const HttpMessage&) noexcept = default;\r\n \r\n \/\/ Move.\r\n HttpMessage(HttpMessage&&) noexcept = default;\r\n HttpMessage& operator=(HttpMessage&&) noexcept = default;\r\n \r\n auto get() const noexcept { return impl_; }\r\n auto method() const noexcept { return +impl_->method; }\r\n auto uri() const noexcept { return +impl_->uri; }\r\n auto proto() const noexcept { return +impl_->proto; }\r\n auto queryString() const noexcept { return +impl_->query_string; }\r\n auto header(const char* name) const noexcept\r\n {\r\n auto* val = mg_get_http_header(impl_, name);\r\n return val ? +*val : std::string_view{};\r\n }\r\n auto body() const noexcept { return +impl_->body; }\r\n\r\n void data_to_arg() noexcept override;\r\n \r\nprivate:\r\n\r\n http_message* impl_;\r\n};\r\n\r\nclass WebsocketMessage:public ToCommandArg { \/\/ connect to bx command-tool\r\npublic:\r\n WebsocketMessage(websocket_message* impl) noexcept : impl_{impl} {}\r\n ~WebsocketMessage() noexcept = default;\r\n \r\n \/\/ Copy.\r\n WebsocketMessage(const WebsocketMessage&) noexcept = default;\r\n WebsocketMessage& operator=(const WebsocketMessage&) noexcept = default;\r\n \r\n \/\/ Move.\r\n WebsocketMessage(WebsocketMessage&&) noexcept = default;\r\n WebsocketMessage& operator=(WebsocketMessage&&) noexcept = default;\r\n \r\n auto get() const noexcept { return impl_; }\r\n auto data() const noexcept { return reinterpret_cast<char*>(impl_->data); }\r\n auto size() const noexcept { return impl_->size; }\r\n \r\n void data_to_arg() noexcept override;\r\nprivate:\r\n websocket_message* impl_;\r\n};\r\n\r\nstruct Session{\r\n Session() = default;\r\n Session(uint64_t a1, double a2, double a3, \r\n std::string&& a4, uint16_t a5):\r\n id(a1), created(a2), last_used(a3), user(a4), state(a5){}\r\n ~Session() = default;\r\n\r\n uint64_t id;\r\n double created;\r\n double last_used;\r\n std::string user;\r\n uint16_t state;\r\n};\r\n\r\ntemplate <typename DerivedT>\r\nclass Mgr {\r\npublic:\r\n \/\/ Copy.\r\n Mgr(const Mgr&) = delete;\r\n Mgr& operator=(const Mgr&) = delete;\r\n\r\n \/\/ Move.\r\n Mgr(Mgr&&) = delete;\r\n Mgr& operator=(Mgr&&) = delete;\r\n\r\n mg_connection& bind(const char* addr)\r\n {\r\n auto* conn = mg_bind(&mgr_, addr, handler);\r\n if (!conn)\r\n throw Error{\"mg_bind() failed\"};\r\n conn->user_data = this;\r\n return *conn;\r\n }\r\n time_t poll(int milli) { return mg_mgr_poll(&mgr_, milli); }\r\n\r\n \/\/ session control\r\n static void login_handler(mg_connection* conn, int ev, void* data){\r\n http_message* hm = static_cast<http_message*>(data);\r\n auto* self = static_cast<DerivedT*>(conn->user_data);\r\n\r\n if (mg_vcmp(&hm->method, \"POST\") != 0) {\r\n mg_serve_http(conn, hm, self->get_httpoptions());\r\n }else{\r\n char user[50], pass[50];\r\n auto ul = mg_get_http_var(&hm->body, \"user\", user, sizeof(user));\r\n auto pl = mg_get_http_var(&hm->body, \"pass\", pass, sizeof(pass));\r\n if (ul > 0 && pl > 0) {\r\n if(!self->user_auth({user, std::strlen(user)}, {pass, std::strlen(pass)})){\r\n mg_printf(conn, \"HTTP\/1.0 403 Unauthorized\\r\\n\\r\\nWrong password.\\r\\n\");\r\n }\r\n\r\n auto ret = self->push_session({user, std::strlen(user)}, hm);\r\n std::ostringstream shead;\r\n shead<<\"Set-Cookie: \" SESSION_COOKIE_NAME \"=\"<<ret->id<<\"; path=\/\";\r\n mg_http_send_redirect(conn, 302, mg_mk_str(\"\/\"), mg_mk_str(shead.str().c_str()));\r\n\r\n } else {\r\n mg_printf(conn, \"HTTP\/1.0 400 Bad Request\\r\\n\\r\\nuser, pass required.\\r\\n\");\r\n }\r\n }\r\n conn->flags |= MG_F_SEND_AND_CLOSE;\r\n }\r\n\r\n static void logout_handler(mg_connection* conn, int ev, void* data){\r\n http_message* hm = static_cast<http_message*>(data);\r\n auto* self = static_cast<DerivedT*>(conn->user_data);\r\n }\r\n\r\n constexpr static const double session_check_interval = 5.0;\r\n\r\nprotected:\r\n Mgr() noexcept { mg_mgr_init(&mgr_, this); }\r\n ~Mgr() noexcept { mg_mgr_free(&mgr_); }\r\n\r\nprivate:\r\n\r\n static void handler(mg_connection* conn, int event, void* data)\r\n {\r\n http_message* hm = static_cast<http_message*>(data);\r\n websocket_message* ws = static_cast<websocket_message*>(data);\r\n auto* self = static_cast<DerivedT*>(conn->user_data);\r\n\r\n switch (event) {\r\n case MG_EV_CLOSE:{\r\n if (conn->flags & MG_F_IS_WEBSOCKET) {\r\n \/\/self->websocketBroadcast(*conn, \"left\", 4);\r\n }else{\r\n conn->user_data = nullptr;\r\n }\r\n break;\r\n }\r\n case MG_EV_HTTP_REQUEST:{\r\n \/\/ rpc call\r\n if (mg_ncasecmp((&hm->uri)->p, \"\/rpc\", 4u) == 0){\r\n self->httpRpcRequest(*conn, hm);\r\n break;\r\n }\r\n \/\/ register call\r\n if (mg_ncasecmp((&hm->uri)->p, \"\/api\/getnewaccount\", 18u) == 0) {\r\n self->httpRequest(*conn, hm);\r\n break;\r\n }\r\n\r\n \/\/ login required for other calls\r\n if (!self->get_from_session_list(hm)) {\r\n mg_http_send_redirect(conn, 302, mg_mk_str(\"\/login.html\"),\r\n mg_mk_str(nullptr));\r\n conn->flags |= MG_F_SEND_AND_CLOSE;\r\n break;\r\n }\r\n\r\n \/\/ logined, http request process\r\n if (mg_ncasecmp((&hm->uri)->p, \"\/api\", 4u) == 0) {\r\n self->httpRequest(*conn, hm);\r\n }else{\r\n self->httpStatic(*conn, hm);\r\n conn->flags |= MG_F_SEND_AND_CLOSE;\r\n }\r\n break;\r\n }\r\n case MG_EV_WEBSOCKET_HANDSHAKE_DONE:{\r\n self->websocketSend(conn, \"connected\", 9);\r\n break;\r\n }\r\n case MG_EV_WEBSOCKET_FRAME:{\r\n self->websocketSend(*conn, ws);\r\n break;\r\n }\r\n case MG_EV_SSI_CALL:{\r\n }\r\n case MG_EV_TIMER:{\r\n self->check_sessions();\r\n mg_set_timer(conn, mg_time() + self->session_check_interval);\r\n break;\r\n }\r\n }\/\/ switch\r\n }\/\/ handler\r\n\r\n mg_mgr mgr_;\r\n};\r\n\r\n} \/\/ mg\r\n} \/\/ http\r\n\r\n\/** @} *\/\r\n\r\n#endif \/\/ MVSD_MONGOOSE_HPP\r\n<commit_msg>fix bugs for paramters input<commit_after>\/*\r\n * The NewReality Blockchain Project.\r\n * Copyright (C) 2013, 2016 Swirly Cloud Limited.\r\n *\r\n * This program is free software; you can redistribute it and\/or modify it under the terms of the\r\n * GNU General Public License as published by the Free Software Foundation; either version 2 of the\r\n * License, or (at your option) any later version.\r\n *\r\n * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without\r\n * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\r\n * General Public License for more details.\r\n *\r\n * You should have received a copy of the GNU General Public License along with this program; if\r\n * not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA\r\n * 02110-1301, USA.\r\n *\/\r\n#ifndef MVSD_MONGOOSE_HPP\r\n#define MVSD_MONGOOSE_HPP\r\n\r\n#include <bitcoin\/explorer\/dispatch.hpp>\r\n#include \"mongoose\/mongoose.h\"\r\n\r\n#include <mvs\/http\/String.hpp>\r\n#include <mvs\/http\/Exception_error.hpp>\r\n\r\n\/**\r\n * @addtogroup Web\r\n * @{\r\n *\/\r\n\r\nnamespace http {\r\nnamespace mg {\r\n\r\n#define SESSION_COOKIE_NAME \"mvss\"\r\n\r\ninline std::string_view operator+(const mg_str& str) noexcept\r\n{\r\n return {str.p, str.len};\r\n}\r\n\r\ninline std::string_view operator+(const websocket_message& msg) noexcept\r\n{\r\n return {reinterpret_cast<char*>(msg.data), msg.size};\r\n}\r\n\r\nclass ToCommandArg{\r\npublic:\r\n auto argv() const noexcept { return argv_; }\r\n auto argc() const noexcept { return argc_; }\r\n void setargv0(std::string&& outside);\r\n\r\n static const int max_paramters{32};\r\nprotected:\r\n\r\n virtual void data_to_arg() noexcept = 0;\r\n const char* argv_[max_paramters]{{nullptr}};\r\n int argc_{0};\r\n\r\n std::vector<std::string> vargv_;\r\n};\r\n\r\n\r\nclass HttpMessage : public ToCommandArg{\r\npublic:\r\n HttpMessage(http_message* impl) noexcept : impl_{impl} {}\r\n ~HttpMessage() noexcept = default;\r\n \r\n \/\/ Copy.\r\n \/\/ http:\/\/www.open-std.org\/jtc1\/sc22\/wg21\/docs\/cwg_defects.html#1778\r\n HttpMessage(const HttpMessage&) noexcept = default;\r\n HttpMessage& operator=(const HttpMessage&) noexcept = default;\r\n \r\n \/\/ Move.\r\n HttpMessage(HttpMessage&&) noexcept = default;\r\n HttpMessage& operator=(HttpMessage&&) noexcept = default;\r\n \r\n auto get() const noexcept { return impl_; }\r\n auto method() const noexcept { return +impl_->method; }\r\n auto uri() const noexcept { return +impl_->uri; }\r\n auto proto() const noexcept { return +impl_->proto; }\r\n auto queryString() const noexcept { return +impl_->query_string; }\r\n auto header(const char* name) const noexcept\r\n {\r\n auto* val = mg_get_http_header(impl_, name);\r\n return val ? +*val : std::string_view{};\r\n }\r\n auto body() const noexcept { return +impl_->body; }\r\n\r\n void data_to_arg() noexcept override;\r\n \r\nprivate:\r\n\r\n http_message* impl_;\r\n};\r\n\r\nclass WebsocketMessage:public ToCommandArg { \/\/ connect to bx command-tool\r\npublic:\r\n WebsocketMessage(websocket_message* impl) noexcept : impl_{impl} {}\r\n ~WebsocketMessage() noexcept = default;\r\n \r\n \/\/ Copy.\r\n WebsocketMessage(const WebsocketMessage&) noexcept = default;\r\n WebsocketMessage& operator=(const WebsocketMessage&) noexcept = default;\r\n \r\n \/\/ Move.\r\n WebsocketMessage(WebsocketMessage&&) noexcept = default;\r\n WebsocketMessage& operator=(WebsocketMessage&&) noexcept = default;\r\n \r\n auto get() const noexcept { return impl_; }\r\n auto data() const noexcept { return reinterpret_cast<char*>(impl_->data); }\r\n auto size() const noexcept { return impl_->size; }\r\n \r\n void data_to_arg() noexcept override;\r\nprivate:\r\n websocket_message* impl_;\r\n};\r\n\r\nstruct Session{\r\n Session() = default;\r\n Session(uint64_t a1, double a2, double a3, \r\n std::string&& a4, uint16_t a5):\r\n id(a1), created(a2), last_used(a3), user(a4), state(a5){}\r\n ~Session() = default;\r\n\r\n uint64_t id;\r\n double created;\r\n double last_used;\r\n std::string user;\r\n uint16_t state;\r\n};\r\n\r\ntemplate <typename DerivedT>\r\nclass Mgr {\r\npublic:\r\n \/\/ Copy.\r\n Mgr(const Mgr&) = delete;\r\n Mgr& operator=(const Mgr&) = delete;\r\n\r\n \/\/ Move.\r\n Mgr(Mgr&&) = delete;\r\n Mgr& operator=(Mgr&&) = delete;\r\n\r\n mg_connection& bind(const char* addr)\r\n {\r\n auto* conn = mg_bind(&mgr_, addr, handler);\r\n if (!conn)\r\n throw Error{\"mg_bind() failed\"};\r\n conn->user_data = this;\r\n return *conn;\r\n }\r\n time_t poll(int milli) { return mg_mgr_poll(&mgr_, milli); }\r\n\r\n \/\/ session control\r\n static void login_handler(mg_connection* conn, int ev, void* data){\r\n http_message* hm = static_cast<http_message*>(data);\r\n auto* self = static_cast<DerivedT*>(conn->user_data);\r\n\r\n if (mg_vcmp(&hm->method, \"POST\") != 0) {\r\n mg_serve_http(conn, hm, self->get_httpoptions());\r\n }else{\r\n char user[50], pass[50];\r\n auto ul = mg_get_http_var(&hm->body, \"user\", user, sizeof(user));\r\n auto pl = mg_get_http_var(&hm->body, \"pass\", pass, sizeof(pass));\r\n if (ul > 0 && pl > 0) {\r\n if(!self->user_auth({user, std::strlen(user)}, {pass, std::strlen(pass)})){\r\n mg_printf(conn, \"HTTP\/1.0 403 Unauthorized\\r\\n\\r\\nWrong password.\\r\\n\");\r\n }\r\n\r\n auto ret = self->push_session({user, std::strlen(user)}, hm);\r\n std::ostringstream shead;\r\n shead<<\"Set-Cookie: \" SESSION_COOKIE_NAME \"=\"<<ret->id<<\"; path=\/\";\r\n mg_http_send_redirect(conn, 302, mg_mk_str(\"\/\"), mg_mk_str(shead.str().c_str()));\r\n\r\n } else {\r\n mg_printf(conn, \"HTTP\/1.0 400 Bad Request\\r\\n\\r\\nuser, pass required.\\r\\n\");\r\n }\r\n }\r\n conn->flags |= MG_F_SEND_AND_CLOSE;\r\n }\r\n\r\n static void logout_handler(mg_connection* conn, int ev, void* data){\r\n http_message* hm = static_cast<http_message*>(data);\r\n auto* self = static_cast<DerivedT*>(conn->user_data);\r\n }\r\n\r\n constexpr static const double session_check_interval = 5.0;\r\n\r\nprotected:\r\n Mgr() noexcept { mg_mgr_init(&mgr_, this); }\r\n ~Mgr() noexcept { mg_mgr_free(&mgr_); }\r\n\r\nprivate:\r\n\r\n static void handler(mg_connection* conn, int event, void* data)\r\n {\r\n http_message* hm = static_cast<http_message*>(data);\r\n websocket_message* ws = static_cast<websocket_message*>(data);\r\n auto* self = static_cast<DerivedT*>(conn->user_data);\r\n\r\n switch (event) {\r\n case MG_EV_CLOSE:{\r\n if (conn->flags & MG_F_IS_WEBSOCKET) {\r\n \/\/self->websocketBroadcast(*conn, \"left\", 4);\r\n }else{\r\n conn->user_data = nullptr;\r\n }\r\n break;\r\n }\r\n case MG_EV_HTTP_REQUEST:{\r\n \/\/ rpc call\r\n if (mg_ncasecmp((&hm->uri)->p, \"\/rpc\", 4u) == 0){\r\n self->httpRpcRequest(*conn, hm);\r\n break;\r\n }\r\n \/\/ register call\r\n if (mg_ncasecmp((&hm->uri)->p, \"\/api\/getnewaccount\", 18u) == 0) {\r\n self->httpRequest(*conn, hm);\r\n break;\r\n }\r\n\r\n \/\/ login required for other calls\r\n if (!self->get_from_session_list(hm)) {\r\n mg_http_send_redirect(conn, 302, mg_mk_str(\"\/login.html\"),\r\n mg_mk_str(nullptr));\r\n conn->flags |= MG_F_SEND_AND_CLOSE;\r\n break;\r\n }\r\n\r\n \/\/ logined, http request process\r\n if (mg_ncasecmp((&hm->uri)->p, \"\/api\", 4u) == 0) {\r\n self->httpRequest(*conn, hm);\r\n }else{\r\n self->httpStatic(*conn, hm);\r\n conn->flags |= MG_F_SEND_AND_CLOSE;\r\n }\r\n break;\r\n }\r\n case MG_EV_WEBSOCKET_HANDSHAKE_DONE:{\r\n self->websocketSend(conn, \"connected\", 9);\r\n break;\r\n }\r\n case MG_EV_WEBSOCKET_FRAME:{\r\n self->websocketSend(*conn, ws);\r\n break;\r\n }\r\n case MG_EV_SSI_CALL:{\r\n }\r\n case MG_EV_TIMER:{\r\n self->check_sessions();\r\n mg_set_timer(conn, mg_time() + self->session_check_interval);\r\n break;\r\n }\r\n }\/\/ switch\r\n }\/\/ handler\r\n\r\n mg_mgr mgr_;\r\n};\r\n\r\n} \/\/ mg\r\n} \/\/ http\r\n\r\n\/** @} *\/\r\n\r\n#endif \/\/ MVSD_MONGOOSE_HPP\r\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2014 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/chrome_elf_init_win.h\"\n\n#include \"base\/basictypes.h\"\n#include \"base\/memory\/scoped_ptr.h\"\n#include \"base\/metrics\/field_trial.h\"\n#include \"base\/strings\/string16.h\"\n#include \"base\/strings\/utf_string_conversions.h\"\n#include \"base\/test\/test_reg_util_win.h\"\n#include \"chrome\/common\/chrome_version_info.h\"\n#include \"chrome_elf\/chrome_elf_constants.h\"\n#include \"components\/variations\/entropy_provider.h\"\n#include \"components\/variations\/variations_associated_data.h\"\n#include \"testing\/gtest\/include\/gtest\/gtest.h\"\n#include \"version.h\" \/\/ NOLINT\n\nnamespace {\n\nconst char kBrowserBlacklistTrialEnabledGroupName[] = \"Enabled\";\n\nclass ChromeBlacklistTrialTest : public testing::Test {\n protected:\n ChromeBlacklistTrialTest() {}\n ~ChromeBlacklistTrialTest() override {}\n\n void SetUp() override {\n testing::Test::SetUp();\n\n override_manager_.OverrideRegistry(HKEY_CURRENT_USER);\n\n blacklist_registry_key_.reset(\n new base::win::RegKey(HKEY_CURRENT_USER,\n blacklist::kRegistryBeaconPath,\n KEY_QUERY_VALUE | KEY_SET_VALUE));\n }\n\n DWORD GetBlacklistState() {\n DWORD blacklist_state = blacklist::BLACKLIST_STATE_MAX;\n blacklist_registry_key_->ReadValueDW(blacklist::kBeaconState,\n &blacklist_state);\n\n return blacklist_state;\n }\n\n base::string16 GetBlacklistVersion() {\n base::string16 blacklist_version;\n blacklist_registry_key_->ReadValue(blacklist::kBeaconVersion,\n &blacklist_version);\n\n return blacklist_version;\n }\n\n scoped_ptr<base::win::RegKey> blacklist_registry_key_;\n registry_util::RegistryOverrideManager override_manager_;\n\n private:\n DISALLOW_COPY_AND_ASSIGN(ChromeBlacklistTrialTest);\n};\n\n\/\/ Ensure that the default trial sets up the blacklist beacons.\nTEST_F(ChromeBlacklistTrialTest, DefaultRun) {\n \/\/ Set some dummy values as beacons.\n blacklist_registry_key_->WriteValue(blacklist::kBeaconState,\n blacklist::BLACKLIST_DISABLED);\n blacklist_registry_key_->WriteValue(blacklist::kBeaconVersion, L\"Data\");\n\n \/\/ This setup code should result in the default group, which should have\n \/\/ the blacklist set up.\n InitializeChromeElf();\n\n \/\/ Ensure the beacon values are now correct, indicating the\n \/\/ blacklist beacon was setup.\n ASSERT_EQ(blacklist::BLACKLIST_ENABLED, GetBlacklistState());\n chrome::VersionInfo version_info;\n base::string16 version(base::UTF8ToUTF16(version_info.Version()));\n ASSERT_EQ(version, GetBlacklistVersion());\n}\n\n\/\/ Ensure that the blacklist is disabled for any users in the\n\/\/ \"BlacklistDisabled\" finch group.\nTEST_F(ChromeBlacklistTrialTest, BlacklistDisabledRun) {\n \/\/ Set the beacons to enabled values.\n blacklist_registry_key_->WriteValue(blacklist::kBeaconState,\n blacklist::BLACKLIST_ENABLED);\n blacklist_registry_key_->WriteValue(blacklist::kBeaconVersion, L\"Data\");\n\n \/\/ Create the field trial with the blacklist disabled group.\n base::FieldTrialList field_trial_list(\n new metrics::SHA1EntropyProvider(\"test\"));\n\n scoped_refptr<base::FieldTrial> trial(\n base::FieldTrialList::CreateFieldTrial(\n kBrowserBlacklistTrialName, kBrowserBlacklistTrialDisabledGroupName));\n\n \/\/ This setup code should now delete any existing blacklist beacons.\n InitializeChromeElf();\n\n \/\/ Ensure invalid values are returned to indicate that the beacon\n \/\/ values are indeed gone.\n ASSERT_EQ(blacklist::BLACKLIST_STATE_MAX, GetBlacklistState());\n ASSERT_EQ(base::string16(), GetBlacklistVersion());\n}\n\nTEST_F(ChromeBlacklistTrialTest, VerifyFirstRun) {\n BrowserBlacklistBeaconSetup();\n\n \/\/ Verify the state is properly set after the first run.\n ASSERT_EQ(blacklist::BLACKLIST_ENABLED, GetBlacklistState());\n\n chrome::VersionInfo version_info;\n base::string16 version(base::UTF8ToUTF16(version_info.Version()));\n ASSERT_EQ(version, GetBlacklistVersion());\n}\n\nTEST_F(ChromeBlacklistTrialTest, BlacklistFailed) {\n \/\/ Ensure when the blacklist set up failed we set the state to disabled for\n \/\/ future runs.\n blacklist_registry_key_->WriteValue(blacklist::kBeaconVersion,\n TEXT(CHROME_VERSION_STRING));\n blacklist_registry_key_->WriteValue(blacklist::kBeaconState,\n blacklist::BLACKLIST_SETUP_FAILED);\n\n BrowserBlacklistBeaconSetup();\n\n ASSERT_EQ(blacklist::BLACKLIST_DISABLED, GetBlacklistState());\n}\n\nTEST_F(ChromeBlacklistTrialTest, VersionChanged) {\n \/\/ Mark the blacklist as disabled for an older version, it should\n \/\/ get enabled for this new version. Also record a non-zero number of\n \/\/ setup failures, which should be reset to zero.\n blacklist_registry_key_->WriteValue(blacklist::kBeaconVersion,\n L\"old_version\");\n blacklist_registry_key_->WriteValue(blacklist::kBeaconState,\n blacklist::BLACKLIST_DISABLED);\n blacklist_registry_key_->WriteValue(blacklist::kBeaconAttemptCount,\n blacklist::kBeaconMaxAttempts);\n\n BrowserBlacklistBeaconSetup();\n\n \/\/ The beacon should now be marked as enabled for the current version.\n ASSERT_EQ(blacklist::BLACKLIST_ENABLED, GetBlacklistState());\n\n chrome::VersionInfo version_info;\n base::string16 expected_version(base::UTF8ToUTF16(version_info.Version()));\n ASSERT_EQ(expected_version, GetBlacklistVersion());\n\n \/\/ The counter should be reset.\n DWORD attempt_count = blacklist::kBeaconMaxAttempts;\n blacklist_registry_key_->ReadValueDW(blacklist::kBeaconAttemptCount,\n &attempt_count);\n ASSERT_EQ(static_cast<DWORD>(0), attempt_count);\n}\n\nTEST_F(ChromeBlacklistTrialTest, AddFinchBlacklistToRegistry) {\n \/\/ Create the field trial with the blacklist enabled group.\n base::FieldTrialList field_trial_list(\n new metrics::SHA1EntropyProvider(\"test\"));\n\n scoped_refptr<base::FieldTrial> trial(base::FieldTrialList::CreateFieldTrial(\n kBrowserBlacklistTrialName, kBrowserBlacklistTrialEnabledGroupName));\n\n \/\/ Set up the trial with the desired parameters.\n std::map<std::string, std::string> desired_params;\n desired_params[\"TestDllName1\"] = \"TestDll1.dll\";\n desired_params[\"TestDllName2\"] = \"TestDll2.dll\";\n\n variations::AssociateVariationParams(\n kBrowserBlacklistTrialName,\n kBrowserBlacklistTrialEnabledGroupName,\n desired_params);\n\n \/\/ This should add the dlls in those parameters to the registry.\n AddFinchBlacklistToRegistry();\n\n \/\/ Check that all the values in desired_params were added to the registry.\n base::win::RegKey finch_blacklist_registry_key(\n HKEY_CURRENT_USER,\n blacklist::kRegistryFinchListPath,\n KEY_QUERY_VALUE | KEY_SET_VALUE);\n\n ASSERT_EQ(desired_params.size(),\n finch_blacklist_registry_key.GetValueCount());\n\n for (std::map<std::string, std::string>::iterator it = desired_params.begin();\n it != desired_params.end();\n ++it) {\n std::wstring name = base::UTF8ToWide(it->first);\n ASSERT_TRUE(finch_blacklist_registry_key.HasValue(name.c_str()));\n }\n}\n\n} \/\/ namespace\n<commit_msg>Add TestBrowserThreadBundle to ChromeBlacklistTrialTest.<commit_after>\/\/ Copyright 2014 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/chrome_elf_init_win.h\"\n\n#include \"base\/basictypes.h\"\n#include \"base\/memory\/scoped_ptr.h\"\n#include \"base\/metrics\/field_trial.h\"\n#include \"base\/strings\/string16.h\"\n#include \"base\/strings\/utf_string_conversions.h\"\n#include \"base\/test\/test_reg_util_win.h\"\n#include \"chrome\/common\/chrome_version_info.h\"\n#include \"chrome_elf\/chrome_elf_constants.h\"\n#include \"components\/variations\/entropy_provider.h\"\n#include \"components\/variations\/variations_associated_data.h\"\n#include \"content\/public\/test\/test_browser_thread_bundle.h\"\n#include \"testing\/gtest\/include\/gtest\/gtest.h\"\n#include \"version.h\" \/\/ NOLINT\n\nnamespace {\n\nconst char kBrowserBlacklistTrialEnabledGroupName[] = \"Enabled\";\n\nclass ChromeBlacklistTrialTest : public testing::Test {\n protected:\n ChromeBlacklistTrialTest() {}\n ~ChromeBlacklistTrialTest() override {}\n\n void SetUp() override {\n testing::Test::SetUp();\n\n override_manager_.OverrideRegistry(HKEY_CURRENT_USER);\n\n blacklist_registry_key_.reset(\n new base::win::RegKey(HKEY_CURRENT_USER,\n blacklist::kRegistryBeaconPath,\n KEY_QUERY_VALUE | KEY_SET_VALUE));\n }\n\n DWORD GetBlacklistState() {\n DWORD blacklist_state = blacklist::BLACKLIST_STATE_MAX;\n blacklist_registry_key_->ReadValueDW(blacklist::kBeaconState,\n &blacklist_state);\n\n return blacklist_state;\n }\n\n base::string16 GetBlacklistVersion() {\n base::string16 blacklist_version;\n blacklist_registry_key_->ReadValue(blacklist::kBeaconVersion,\n &blacklist_version);\n\n return blacklist_version;\n }\n\n scoped_ptr<base::win::RegKey> blacklist_registry_key_;\n registry_util::RegistryOverrideManager override_manager_;\n content::TestBrowserThreadBundle test_browser_thread_bundle_;\n\n private:\n DISALLOW_COPY_AND_ASSIGN(ChromeBlacklistTrialTest);\n};\n\n\/\/ Ensure that the default trial sets up the blacklist beacons.\nTEST_F(ChromeBlacklistTrialTest, DefaultRun) {\n \/\/ Set some dummy values as beacons.\n blacklist_registry_key_->WriteValue(blacklist::kBeaconState,\n blacklist::BLACKLIST_DISABLED);\n blacklist_registry_key_->WriteValue(blacklist::kBeaconVersion, L\"Data\");\n\n \/\/ This setup code should result in the default group, which should have\n \/\/ the blacklist set up.\n InitializeChromeElf();\n\n \/\/ Ensure the beacon values are now correct, indicating the\n \/\/ blacklist beacon was setup.\n ASSERT_EQ(blacklist::BLACKLIST_ENABLED, GetBlacklistState());\n chrome::VersionInfo version_info;\n base::string16 version(base::UTF8ToUTF16(version_info.Version()));\n ASSERT_EQ(version, GetBlacklistVersion());\n}\n\n\/\/ Ensure that the blacklist is disabled for any users in the\n\/\/ \"BlacklistDisabled\" finch group.\nTEST_F(ChromeBlacklistTrialTest, BlacklistDisabledRun) {\n \/\/ Set the beacons to enabled values.\n blacklist_registry_key_->WriteValue(blacklist::kBeaconState,\n blacklist::BLACKLIST_ENABLED);\n blacklist_registry_key_->WriteValue(blacklist::kBeaconVersion, L\"Data\");\n\n \/\/ Create the field trial with the blacklist disabled group.\n base::FieldTrialList field_trial_list(\n new metrics::SHA1EntropyProvider(\"test\"));\n\n scoped_refptr<base::FieldTrial> trial(\n base::FieldTrialList::CreateFieldTrial(\n kBrowserBlacklistTrialName, kBrowserBlacklistTrialDisabledGroupName));\n\n \/\/ This setup code should now delete any existing blacklist beacons.\n InitializeChromeElf();\n\n \/\/ Ensure invalid values are returned to indicate that the beacon\n \/\/ values are indeed gone.\n ASSERT_EQ(blacklist::BLACKLIST_STATE_MAX, GetBlacklistState());\n ASSERT_EQ(base::string16(), GetBlacklistVersion());\n}\n\nTEST_F(ChromeBlacklistTrialTest, VerifyFirstRun) {\n BrowserBlacklistBeaconSetup();\n\n \/\/ Verify the state is properly set after the first run.\n ASSERT_EQ(blacklist::BLACKLIST_ENABLED, GetBlacklistState());\n\n chrome::VersionInfo version_info;\n base::string16 version(base::UTF8ToUTF16(version_info.Version()));\n ASSERT_EQ(version, GetBlacklistVersion());\n}\n\nTEST_F(ChromeBlacklistTrialTest, BlacklistFailed) {\n \/\/ Ensure when the blacklist set up failed we set the state to disabled for\n \/\/ future runs.\n blacklist_registry_key_->WriteValue(blacklist::kBeaconVersion,\n TEXT(CHROME_VERSION_STRING));\n blacklist_registry_key_->WriteValue(blacklist::kBeaconState,\n blacklist::BLACKLIST_SETUP_FAILED);\n\n BrowserBlacklistBeaconSetup();\n\n ASSERT_EQ(blacklist::BLACKLIST_DISABLED, GetBlacklistState());\n}\n\nTEST_F(ChromeBlacklistTrialTest, VersionChanged) {\n \/\/ Mark the blacklist as disabled for an older version, it should\n \/\/ get enabled for this new version. Also record a non-zero number of\n \/\/ setup failures, which should be reset to zero.\n blacklist_registry_key_->WriteValue(blacklist::kBeaconVersion,\n L\"old_version\");\n blacklist_registry_key_->WriteValue(blacklist::kBeaconState,\n blacklist::BLACKLIST_DISABLED);\n blacklist_registry_key_->WriteValue(blacklist::kBeaconAttemptCount,\n blacklist::kBeaconMaxAttempts);\n\n BrowserBlacklistBeaconSetup();\n\n \/\/ The beacon should now be marked as enabled for the current version.\n ASSERT_EQ(blacklist::BLACKLIST_ENABLED, GetBlacklistState());\n\n chrome::VersionInfo version_info;\n base::string16 expected_version(base::UTF8ToUTF16(version_info.Version()));\n ASSERT_EQ(expected_version, GetBlacklistVersion());\n\n \/\/ The counter should be reset.\n DWORD attempt_count = blacklist::kBeaconMaxAttempts;\n blacklist_registry_key_->ReadValueDW(blacklist::kBeaconAttemptCount,\n &attempt_count);\n ASSERT_EQ(static_cast<DWORD>(0), attempt_count);\n}\n\nTEST_F(ChromeBlacklistTrialTest, AddFinchBlacklistToRegistry) {\n \/\/ Create the field trial with the blacklist enabled group.\n base::FieldTrialList field_trial_list(\n new metrics::SHA1EntropyProvider(\"test\"));\n\n scoped_refptr<base::FieldTrial> trial(base::FieldTrialList::CreateFieldTrial(\n kBrowserBlacklistTrialName, kBrowserBlacklistTrialEnabledGroupName));\n\n \/\/ Set up the trial with the desired parameters.\n std::map<std::string, std::string> desired_params;\n desired_params[\"TestDllName1\"] = \"TestDll1.dll\";\n desired_params[\"TestDllName2\"] = \"TestDll2.dll\";\n\n variations::AssociateVariationParams(\n kBrowserBlacklistTrialName,\n kBrowserBlacklistTrialEnabledGroupName,\n desired_params);\n\n \/\/ This should add the dlls in those parameters to the registry.\n AddFinchBlacklistToRegistry();\n\n \/\/ Check that all the values in desired_params were added to the registry.\n base::win::RegKey finch_blacklist_registry_key(\n HKEY_CURRENT_USER,\n blacklist::kRegistryFinchListPath,\n KEY_QUERY_VALUE | KEY_SET_VALUE);\n\n ASSERT_EQ(desired_params.size(),\n finch_blacklist_registry_key.GetValueCount());\n\n for (std::map<std::string, std::string>::iterator it = desired_params.begin();\n it != desired_params.end();\n ++it) {\n std::wstring name = base::UTF8ToWide(it->first);\n ASSERT_TRUE(finch_blacklist_registry_key.HasValue(name.c_str()));\n }\n}\n\n} \/\/ namespace\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright 2009-2011 Red Hat, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n\/\/ condor includes\n#include \"condor_common.h\"\n#include \"condor_qmgr.h\"\n#include \"condor_config.h\"\n\n\/\/ local includes\n#include \"AviaryScheddPlugin.h\"\n#include \"Axis2SoapProvider.h\"\n#include \"SchedulerObject.h\"\n\n\/\/ Global from the condor_schedd, it's name\nextern char * Name;\n\n\/\/ Any key that begins with the '0' char is either the\n\/\/ header or a cluster, i.e. not a job\n#define IS_JOB(key) ((key) && '0' != (key)[0])\n\nusing namespace std;\nusing namespace aviary::job;\nusing namespace aviary::soap;\n\n\/\/ global SchedulerObject\n\/\/ TODO: convert to singleton\nAxis2SoapProvider* provider = NULL;\nSchedulerObject* schedulerObj = NULL;\n\nvoid\nAviaryScheddPlugin::earlyInitialize()\n{\n\n \/\/ Since this plugin is registered with multiple\n \/\/ PluginManagers it may be initialized more than once,\n \/\/ and we don't want that\n\tstatic bool skip = false;\n\tif (skip) return; skip = true;\n\n\t\/\/ config then env for our all-important axis2 repo dir\n const char* log_file = \".\/aviary_job.axis2.log\";\n\tstring repo_path;\n\tchar *tmp = NULL;\n\tif (tmp = param(\"WSFCPP_HOME\")) {\n\t\trepo_path = tmp;\n\t\tfree(tmp);\n\t}\n\telse if (tmp = getenv(\"WSFCPP_HOME\")) {\n\t\trepo_path = tmp;\n\t}\n\telse {\n\t\tEXCEPT(\"No WSFCPP_HOME in config or env\");\n\t}\n\n\tint port = param_integer(\"HTTP_PORT\",9090);\n\tint level = param_integer(\"AXIS2_DEBUG_LEVEL\",AXIS2_LOG_LEVEL_CRITICAL);\n\n \/\/ init transport here\n provider = new Axis2SoapProvider(level,log_file,repo_path.c_str());\n string axis_error;\n if (!provider->init(9090,AXIS2_HTTP_DEFAULT_SO_TIMEOUT,axis_error)) {\n\t\tdprintf(D_ALWAYS, \"%s\\n\",axis_error.c_str());\n EXCEPT(\"Failed to initialize Axis2SoapProvider\");\n }\n\n\tschedulerObj = SchedulerObject::getInstance();\n\n\tdirtyJobs = new DirtyJobsType();\n\n\tisHandlerRegistered = false;\n\n\tReliSock *sock = new ReliSock;\n\tif (!sock) {\n\t\tEXCEPT(\"Failed to allocate transport socket\");\n\t}\n\tif (!sock->assign(provider->getHttpListenerSocket())) {\n\t\tEXCEPT(\"Failed to bind transport socket\");\n\t}\n\tint index;\n\tif (-1 == (index =\n\t\t\t daemonCore->Register_Socket((Stream *) sock,\n\t\t\t\t\t\t\t\t\t\t \"Aviary Method Socket\",\n\t\t\t\t\t\t\t\t\t\t (SocketHandlercpp) ( &AviaryScheddPlugin::HandleTransportSocket ),\n\t\t\t\t\t\t\t\t\t\t \"Handler for Aviary Methods.\",\n\t\t\t\t\t\t\t\t\t\t this))) {\n\t\tEXCEPT(\"Failed to register transport socket\");\n\t}\n\n\tdprintf(D_ALWAYS,\"Axis2 listener on http port: %d\\n\",port);\n\n\tm_initialized = false;\n}\n\nvoid\nAviaryScheddPlugin::initialize()\n{\n\t\t\/\/ Since this plugin is registered with multiple\n\t\t\/\/ PluginManagers it may be initialized more than once,\n\t\t\/\/ and we don't want that\n\tstatic bool skip = false;\n\tif (skip) return; skip = true;\n\n\t\t\/\/ WalkJobQueue(int (*func)(ClassAd *))\n\tClassAd *ad = GetNextJob(1);\n\twhile (ad != NULL) {\n\t\tMyString key;\n\t\tPROC_ID id;\n\t\tint value;\n\n\t\tif (!ad->LookupInteger(ATTR_CLUSTER_ID, id.cluster)) {\n\t\t\tEXCEPT(\"%s on job is missing or not an integer\", ATTR_CLUSTER_ID);\n\t\t}\n\t\tif (!ad->LookupInteger(ATTR_PROC_ID, id.proc)) {\n\t\t\tEXCEPT(\"%s on job is missing or not an integer\", ATTR_PROC_ID);\n\t\t}\n\t\tif (!ad->LookupInteger(ATTR_JOB_STATUS, value)) {\n\t\t\tEXCEPT(\"%s on job is missing or not an integer\", ATTR_JOB_STATUS);\n\t\t}\n\n\t\tkey.sprintf(\"%d.%d\", id.cluster, id.proc);\n\n\t\tprocessJob(key.Value(), ATTR_JOB_STATUS, value);\n\n\t\tFreeJobAd(ad);\n\t\tad = GetNextJob(0);\n\t}\n \n\tm_initialized = true;\n}\n\n\nvoid\nAviaryScheddPlugin::shutdown()\n{\n\t\t\/\/ Since this plugin is registered with multiple\n\t\t\/\/ PluginManagers (eg, shadow) it may be shutdown\n\t\t\/\/ more than once, and we don't want that\n\tstatic bool skip = false;\n\tif (skip) return; skip = true;\n\n\tdprintf(D_FULLDEBUG, \"AviaryScheddPlugin: shutting down...\\n\");\n\n\tif (schedulerObj) {\n\t\tdelete schedulerObj;\n\t\tschedulerObj = NULL;\n\t}\n}\n\n\nvoid\nAviaryScheddPlugin::update(int cmd, const ClassAd *ad)\n{\n\tMyString hashKey;\n\n\tswitch (cmd) {\n\tcase UPDATE_SCHEDD_AD:\n\t\tdprintf(D_FULLDEBUG, \"Received UPDATE_SCHEDD_AD\\n\");\n\t\tschedulerObj->update(*ad);\n\t\tbreak;\n\tdefault:\n\t\tdprintf(D_FULLDEBUG, \"Unsupported command: %s\\n\",\n\t\t\t\tgetCollectorCommandString(cmd));\n\t}\n}\n\n\nvoid\nAviaryScheddPlugin::archive(const ClassAd *\/*ad*\/) { };\n\n\nvoid\nAviaryScheddPlugin::newClassAd(const char *\/*key*\/) { };\n\n\nvoid\nAviaryScheddPlugin::setAttribute(const char *key,\n\t\t\t\t\t\t\t const char *name,\n\t\t\t\t\t\t\t const char *value)\n{\n\tif (!m_initialized) return;\n\n\/\/\tdprintf(D_FULLDEBUG, \"setAttribute: %s[%s] = %s\\n\", key, name, value);\n\n\tmarkDirty(key, name, value);\n}\n\n\nvoid\nAviaryScheddPlugin::destroyClassAd(const char *_key)\n{\n\tif (!m_initialized) return;\n\n\/\/\tdprintf(D_FULLDEBUG, \"destroyClassAd: %s\\n\", key);\n\n\tif (!IS_JOB(_key)) return;\n\n\t\t\/\/ If we wait to process the deletion the job ad will be gone\n\t\t\/\/ and we won't be able to lookup the Submission. So, we must\n\t\t\/\/ process the job immediately, but that also means we need to\n\t\t\/\/ process all pending changes for the job as well.\n\tDirtyJobsType::iterator entry = dirtyJobs->begin();\n\twhile (dirtyJobs->end() != entry) {\n\t\tstring key = (*entry).first;\n\t\tstring name = (*entry).second.first;\n\t\tint value = (*entry).second.second;\n\n\t\tif (key == _key) {\n\t\t\tprocessJob(key.c_str(), name.c_str(), value);\n\n\t\t\t\t\/\/ No need to process this entry again later\n\t\t\tentry = dirtyJobs->erase(entry);\n\t\t} else {\n\t\t\tentry++;\n\t\t}\n\t}\n}\n\n\nvoid\nAviaryScheddPlugin::deleteAttribute(const char *\/*key*\/,\n\t\t\t\t\t\t\t\t const char *\/*name*\/) { }\n\nint\nAviaryScheddPlugin::HandleTransportSocket(Stream *)\n{\n \/\/ TODO: respond to a transport callback here?\n string provider_error;\n if (!provider->processHttpRequest(provider_error)) {\n dprintf (D_ALWAYS,\"Error processing request: %s\\n\",provider_error.c_str());\n }\n\n return KEEP_STREAM;\n}\n\nvoid\nAviaryScheddPlugin::processDirtyJobs()\n{\n\tBeginTransaction();\n\n\twhile (!dirtyJobs->empty()) {\n\t\tDirtyJobEntry entry = dirtyJobs->front(); dirtyJobs->pop_front();\n\t\tstring key = entry.first;\n\t\tstring name = entry.second.first;\n\t\tint value = entry.second.second;\n\n\t\tprocessJob(key.c_str(), name.c_str(), value);\n\t}\n\n\tCommitTransaction();\n\n\tisHandlerRegistered = false;\n}\n\n\nbool\nAviaryScheddPlugin::processJob(const char *key,\n\t\t\t\t\t\t\t const char *name,\n\t\t\t\t\t\t\t int value)\n{\n\tPROC_ID id;\n\tClassAd *jobAd;\n\n\t\t\/\/ Skip any key that doesn't point to an actual job\n\tif (!IS_JOB(key)) return false;\n\n\/\/\tdprintf(D_FULLDEBUG, \"Processing: %s\\n\", key);\n\n\tid = getProcByString(key);\n\tif (id.cluster < 0 || id.proc < 0) {\n\t\tdprintf(D_FULLDEBUG, \"Failed to parse key: %s - skipping\\n\", key);\n\t\treturn false;\n\t}\n\n\t\t\/\/ Lookup the job ad assocaited with the key. If it is not\n\t\t\/\/ present, skip the key\n\tif (NULL == (jobAd = ::GetJobAd(id.cluster, id.proc, false))) {\n\t\tdprintf(D_ALWAYS,\n\t\t\t\t\"NOTICE: Failed to lookup ad for %s - maybe deleted\\n\",\n\t\t\t\tkey);\n\t\treturn false;\n\t}\n\n\t\t\/\/ Store two pieces of information in the Job, 1. the\n\t\t\/\/ Submission's name, 2. the Submission's id\n\t\t\/\/\n\t\t\/\/ Submissions indexed on their name, the id is present\n\t\t\/\/ for reconstruction of the Submission\n\n\t\t\/\/ XXX: Use the jobAd instead of GetAttribute below, gets us $$() expansion\n\n\tMyString submissionName;\n\tif (GetAttributeString(id.cluster, id.proc,\n\t\t\t\t\t\t ATTR_JOB_SUBMISSION,\n\t\t\t\t\t\t submissionName) < 0) {\n\t\t\t\/\/ Provide a default name for the Submission\n\n\t\t\t\/\/ If we are a DAG node, we default to our DAG group\n\t\tPROC_ID dagman;\n\t\tif (GetAttributeInt(id.cluster, id.proc,\n\t\t\t\t\t\t\tATTR_DAGMAN_JOB_ID,\n\t\t\t\t\t\t\t&dagman.cluster) >= 0) {\n\t\t\tdagman.proc = 0;\n\n\t\t\tif (GetAttributeString(dagman.cluster, dagman.proc,\n\t\t\t\t\t\t\t\t ATTR_JOB_SUBMISSION,\n\t\t\t\t\t\t\t\t submissionName) < 0) {\n\t\t\t\t\t\/\/ This can only happen if the DAGMan job was\n\t\t\t\t\t\/\/ removed, and we remained, which should not\n\t\t\t\t\t\/\/ happen, but could. In such a case we are\n\t\t\t\t\t\/\/ orphaned, and we'll make a guess. We'll be\n\t\t\t\t\t\/\/ wrong if the DAGMan job didn't use the\n\t\t\t\t\t\/\/ default, but it is better to be wrong than\n\t\t\t\t\t\/\/ to fail entirely, which is the alternative.\n\t\t\t\tsubmissionName.sprintf(\"%s#%d\", Name, dagman.cluster);\n\t\t\t}\n\t\t} else {\n\t\t\tsubmissionName.sprintf(\"%s#%d\", Name, id.cluster);\n\t\t}\n\n\t\tMyString tmp;\n\t\ttmp += \"\\\"\";\n\t\ttmp += submissionName;\n\t\ttmp += \"\\\"\";\n\t\tSetAttribute(id.cluster, id.proc,\n\t\t\t\t\t ATTR_JOB_SUBMISSION,\n\t\t\t\t\t tmp.Value());\n\t}\n}\n\nvoid\nAviaryScheddPlugin::markDirty(const char *key,\n\t\t\t\t\t\t\tconst char *name,\n\t\t\t\t\t\t\tconst char *value)\n{\n\tif (!IS_JOB(key)) return;\n\tif (!(strcasecmp(name, ATTR_JOB_STATUS) == 0 ||\n\t\t strcasecmp(name, ATTR_LAST_JOB_STATUS) == 0)) return;\n\n\tDirtyJobStatus status(name, atoi(value));\n\tDirtyJobEntry entry(key, status);\n\tdirtyJobs->push_back(DirtyJobEntry(key, DirtyJobStatus(name, atoi(value))));\n\n\tif (!isHandlerRegistered) {\n\t\t\t\/\/ To test destroyClassAd, set the timeout here to a few\n\t\t\t\/\/ seconds, submit a job and immediately delete it.\n\t\tdaemonCore->Register_Timer(0,\n\t\t\t\t\t\t\t\t (TimerHandlercpp)\n\t\t\t\t\t\t\t\t &AviaryScheddPlugin::processDirtyJobs,\n\t\t\t\t\t\t\t\t \"Process Dirty\",\n\t\t\t\t\t\t\t\t this);\n\t\tisHandlerRegistered = true;\n\t}\n}\n<commit_msg>Fixed a minor bug where the axis2 port was hardcoded in the aviary init()<commit_after>\/*\n * Copyright 2009-2011 Red Hat, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n\/\/ condor includes\n#include \"condor_common.h\"\n#include \"condor_qmgr.h\"\n#include \"condor_config.h\"\n\n\/\/ local includes\n#include \"AviaryScheddPlugin.h\"\n#include \"Axis2SoapProvider.h\"\n#include \"SchedulerObject.h\"\n\n\/\/ Global from the condor_schedd, it's name\nextern char * Name;\n\n\/\/ Any key that begins with the '0' char is either the\n\/\/ header or a cluster, i.e. not a job\n#define IS_JOB(key) ((key) && '0' != (key)[0])\n\nusing namespace std;\nusing namespace aviary::job;\nusing namespace aviary::soap;\n\n\/\/ global SchedulerObject\n\/\/ TODO: convert to singleton\nAxis2SoapProvider* provider = NULL;\nSchedulerObject* schedulerObj = NULL;\n\nvoid\nAviaryScheddPlugin::earlyInitialize()\n{\n\n \/\/ Since this plugin is registered with multiple\n \/\/ PluginManagers it may be initialized more than once,\n \/\/ and we don't want that\n\tstatic bool skip = false;\n\tif (skip) return; skip = true;\n\n\t\/\/ config then env for our all-important axis2 repo dir\n const char* log_file = \".\/aviary_job.axis2.log\";\n\tstring repo_path;\n\tchar *tmp = NULL;\n\tif (tmp = param(\"WSFCPP_HOME\")) {\n\t\trepo_path = tmp;\n\t\tfree(tmp);\n\t}\n\telse if (tmp = getenv(\"WSFCPP_HOME\")) {\n\t\trepo_path = tmp;\n\t}\n\telse {\n\t\tEXCEPT(\"No WSFCPP_HOME in config or env\");\n\t}\n\n\tint port = param_integer(\"HTTP_PORT\",9090);\n\tint level = param_integer(\"AXIS2_DEBUG_LEVEL\",AXIS2_LOG_LEVEL_CRITICAL);\n\n \/\/ init transport here\n provider = new Axis2SoapProvider(level,log_file,repo_path.c_str());\n string axis_error;\n if (!provider->init(port,AXIS2_HTTP_DEFAULT_SO_TIMEOUT,axis_error)) {\n\t\tdprintf(D_ALWAYS, \"%s\\n\",axis_error.c_str());\n EXCEPT(\"Failed to initialize Axis2SoapProvider\");\n }\n\n\tschedulerObj = SchedulerObject::getInstance();\n\n\tdirtyJobs = new DirtyJobsType();\n\n\tisHandlerRegistered = false;\n\n\tReliSock *sock = new ReliSock;\n\tif (!sock) {\n\t\tEXCEPT(\"Failed to allocate transport socket\");\n\t}\n\tif (!sock->assign(provider->getHttpListenerSocket())) {\n\t\tEXCEPT(\"Failed to bind transport socket\");\n\t}\n\tint index;\n\tif (-1 == (index =\n\t\t\t daemonCore->Register_Socket((Stream *) sock,\n\t\t\t\t\t\t\t\t\t\t \"Aviary Method Socket\",\n\t\t\t\t\t\t\t\t\t\t (SocketHandlercpp) ( &AviaryScheddPlugin::HandleTransportSocket ),\n\t\t\t\t\t\t\t\t\t\t \"Handler for Aviary Methods.\",\n\t\t\t\t\t\t\t\t\t\t this))) {\n\t\tEXCEPT(\"Failed to register transport socket\");\n\t}\n\n\tdprintf(D_ALWAYS,\"Axis2 listener on http port: %d\\n\",port);\n\n\tm_initialized = false;\n}\n\nvoid\nAviaryScheddPlugin::initialize()\n{\n\t\t\/\/ Since this plugin is registered with multiple\n\t\t\/\/ PluginManagers it may be initialized more than once,\n\t\t\/\/ and we don't want that\n\tstatic bool skip = false;\n\tif (skip) return; skip = true;\n\n\t\t\/\/ WalkJobQueue(int (*func)(ClassAd *))\n\tClassAd *ad = GetNextJob(1);\n\twhile (ad != NULL) {\n\t\tMyString key;\n\t\tPROC_ID id;\n\t\tint value;\n\n\t\tif (!ad->LookupInteger(ATTR_CLUSTER_ID, id.cluster)) {\n\t\t\tEXCEPT(\"%s on job is missing or not an integer\", ATTR_CLUSTER_ID);\n\t\t}\n\t\tif (!ad->LookupInteger(ATTR_PROC_ID, id.proc)) {\n\t\t\tEXCEPT(\"%s on job is missing or not an integer\", ATTR_PROC_ID);\n\t\t}\n\t\tif (!ad->LookupInteger(ATTR_JOB_STATUS, value)) {\n\t\t\tEXCEPT(\"%s on job is missing or not an integer\", ATTR_JOB_STATUS);\n\t\t}\n\n\t\tkey.sprintf(\"%d.%d\", id.cluster, id.proc);\n\n\t\tprocessJob(key.Value(), ATTR_JOB_STATUS, value);\n\n\t\tFreeJobAd(ad);\n\t\tad = GetNextJob(0);\n\t}\n \n\tm_initialized = true;\n}\n\n\nvoid\nAviaryScheddPlugin::shutdown()\n{\n\t\t\/\/ Since this plugin is registered with multiple\n\t\t\/\/ PluginManagers (eg, shadow) it may be shutdown\n\t\t\/\/ more than once, and we don't want that\n\tstatic bool skip = false;\n\tif (skip) return; skip = true;\n\n\tdprintf(D_FULLDEBUG, \"AviaryScheddPlugin: shutting down...\\n\");\n\n\tif (schedulerObj) {\n\t\tdelete schedulerObj;\n\t\tschedulerObj = NULL;\n\t}\n}\n\n\nvoid\nAviaryScheddPlugin::update(int cmd, const ClassAd *ad)\n{\n\tMyString hashKey;\n\n\tswitch (cmd) {\n\tcase UPDATE_SCHEDD_AD:\n\t\tdprintf(D_FULLDEBUG, \"Received UPDATE_SCHEDD_AD\\n\");\n\t\tschedulerObj->update(*ad);\n\t\tbreak;\n\tdefault:\n\t\tdprintf(D_FULLDEBUG, \"Unsupported command: %s\\n\",\n\t\t\t\tgetCollectorCommandString(cmd));\n\t}\n}\n\n\nvoid\nAviaryScheddPlugin::archive(const ClassAd *\/*ad*\/) { };\n\n\nvoid\nAviaryScheddPlugin::newClassAd(const char *\/*key*\/) { };\n\n\nvoid\nAviaryScheddPlugin::setAttribute(const char *key,\n\t\t\t\t\t\t\t const char *name,\n\t\t\t\t\t\t\t const char *value)\n{\n\tif (!m_initialized) return;\n\n\/\/\tdprintf(D_FULLDEBUG, \"setAttribute: %s[%s] = %s\\n\", key, name, value);\n\n\tmarkDirty(key, name, value);\n}\n\n\nvoid\nAviaryScheddPlugin::destroyClassAd(const char *_key)\n{\n\tif (!m_initialized) return;\n\n\/\/\tdprintf(D_FULLDEBUG, \"destroyClassAd: %s\\n\", key);\n\n\tif (!IS_JOB(_key)) return;\n\n\t\t\/\/ If we wait to process the deletion the job ad will be gone\n\t\t\/\/ and we won't be able to lookup the Submission. So, we must\n\t\t\/\/ process the job immediately, but that also means we need to\n\t\t\/\/ process all pending changes for the job as well.\n\tDirtyJobsType::iterator entry = dirtyJobs->begin();\n\twhile (dirtyJobs->end() != entry) {\n\t\tstring key = (*entry).first;\n\t\tstring name = (*entry).second.first;\n\t\tint value = (*entry).second.second;\n\n\t\tif (key == _key) {\n\t\t\tprocessJob(key.c_str(), name.c_str(), value);\n\n\t\t\t\t\/\/ No need to process this entry again later\n\t\t\tentry = dirtyJobs->erase(entry);\n\t\t} else {\n\t\t\tentry++;\n\t\t}\n\t}\n}\n\n\nvoid\nAviaryScheddPlugin::deleteAttribute(const char *\/*key*\/,\n\t\t\t\t\t\t\t\t const char *\/*name*\/) { }\n\nint\nAviaryScheddPlugin::HandleTransportSocket(Stream *)\n{\n \/\/ TODO: respond to a transport callback here?\n string provider_error;\n if (!provider->processHttpRequest(provider_error)) {\n dprintf (D_ALWAYS,\"Error processing request: %s\\n\",provider_error.c_str());\n }\n\n return KEEP_STREAM;\n}\n\nvoid\nAviaryScheddPlugin::processDirtyJobs()\n{\n\tBeginTransaction();\n\n\twhile (!dirtyJobs->empty()) {\n\t\tDirtyJobEntry entry = dirtyJobs->front(); dirtyJobs->pop_front();\n\t\tstring key = entry.first;\n\t\tstring name = entry.second.first;\n\t\tint value = entry.second.second;\n\n\t\tprocessJob(key.c_str(), name.c_str(), value);\n\t}\n\n\tCommitTransaction();\n\n\tisHandlerRegistered = false;\n}\n\n\nbool\nAviaryScheddPlugin::processJob(const char *key,\n\t\t\t\t\t\t\t const char *name,\n\t\t\t\t\t\t\t int value)\n{\n\tPROC_ID id;\n\tClassAd *jobAd;\n\n\t\t\/\/ Skip any key that doesn't point to an actual job\n\tif (!IS_JOB(key)) return false;\n\n\/\/\tdprintf(D_FULLDEBUG, \"Processing: %s\\n\", key);\n\n\tid = getProcByString(key);\n\tif (id.cluster < 0 || id.proc < 0) {\n\t\tdprintf(D_FULLDEBUG, \"Failed to parse key: %s - skipping\\n\", key);\n\t\treturn false;\n\t}\n\n\t\t\/\/ Lookup the job ad assocaited with the key. If it is not\n\t\t\/\/ present, skip the key\n\tif (NULL == (jobAd = ::GetJobAd(id.cluster, id.proc, false))) {\n\t\tdprintf(D_ALWAYS,\n\t\t\t\t\"NOTICE: Failed to lookup ad for %s - maybe deleted\\n\",\n\t\t\t\tkey);\n\t\treturn false;\n\t}\n\n\t\t\/\/ Store two pieces of information in the Job, 1. the\n\t\t\/\/ Submission's name, 2. the Submission's id\n\t\t\/\/\n\t\t\/\/ Submissions indexed on their name, the id is present\n\t\t\/\/ for reconstruction of the Submission\n\n\t\t\/\/ XXX: Use the jobAd instead of GetAttribute below, gets us $$() expansion\n\n\tMyString submissionName;\n\tif (GetAttributeString(id.cluster, id.proc,\n\t\t\t\t\t\t ATTR_JOB_SUBMISSION,\n\t\t\t\t\t\t submissionName) < 0) {\n\t\t\t\/\/ Provide a default name for the Submission\n\n\t\t\t\/\/ If we are a DAG node, we default to our DAG group\n\t\tPROC_ID dagman;\n\t\tif (GetAttributeInt(id.cluster, id.proc,\n\t\t\t\t\t\t\tATTR_DAGMAN_JOB_ID,\n\t\t\t\t\t\t\t&dagman.cluster) >= 0) {\n\t\t\tdagman.proc = 0;\n\n\t\t\tif (GetAttributeString(dagman.cluster, dagman.proc,\n\t\t\t\t\t\t\t\t ATTR_JOB_SUBMISSION,\n\t\t\t\t\t\t\t\t submissionName) < 0) {\n\t\t\t\t\t\/\/ This can only happen if the DAGMan job was\n\t\t\t\t\t\/\/ removed, and we remained, which should not\n\t\t\t\t\t\/\/ happen, but could. In such a case we are\n\t\t\t\t\t\/\/ orphaned, and we'll make a guess. We'll be\n\t\t\t\t\t\/\/ wrong if the DAGMan job didn't use the\n\t\t\t\t\t\/\/ default, but it is better to be wrong than\n\t\t\t\t\t\/\/ to fail entirely, which is the alternative.\n\t\t\t\tsubmissionName.sprintf(\"%s#%d\", Name, dagman.cluster);\n\t\t\t}\n\t\t} else {\n\t\t\tsubmissionName.sprintf(\"%s#%d\", Name, id.cluster);\n\t\t}\n\n\t\tMyString tmp;\n\t\ttmp += \"\\\"\";\n\t\ttmp += submissionName;\n\t\ttmp += \"\\\"\";\n\t\tSetAttribute(id.cluster, id.proc,\n\t\t\t\t\t ATTR_JOB_SUBMISSION,\n\t\t\t\t\t tmp.Value());\n\t}\n}\n\nvoid\nAviaryScheddPlugin::markDirty(const char *key,\n\t\t\t\t\t\t\tconst char *name,\n\t\t\t\t\t\t\tconst char *value)\n{\n\tif (!IS_JOB(key)) return;\n\tif (!(strcasecmp(name, ATTR_JOB_STATUS) == 0 ||\n\t\t strcasecmp(name, ATTR_LAST_JOB_STATUS) == 0)) return;\n\n\tDirtyJobStatus status(name, atoi(value));\n\tDirtyJobEntry entry(key, status);\n\tdirtyJobs->push_back(DirtyJobEntry(key, DirtyJobStatus(name, atoi(value))));\n\n\tif (!isHandlerRegistered) {\n\t\t\t\/\/ To test destroyClassAd, set the timeout here to a few\n\t\t\t\/\/ seconds, submit a job and immediately delete it.\n\t\tdaemonCore->Register_Timer(0,\n\t\t\t\t\t\t\t\t (TimerHandlercpp)\n\t\t\t\t\t\t\t\t &AviaryScheddPlugin::processDirtyJobs,\n\t\t\t\t\t\t\t\t \"Process Dirty\",\n\t\t\t\t\t\t\t\t this);\n\t\tisHandlerRegistered = true;\n\t}\n}\n<|endoftext|>"} {"text":"<commit_before>#ifndef PROTOCOL_MESSAGES_HPP_\n#define PROTOCOL_MESSAGES_HPP_\n\n#include <cstdint>\n\nnamespace protocol {\nnamespace message {\n\nstruct heartbeat_message_t {\n enum { ID = 0x00 };\n\n std::uint8_t seq;\n} __attribute__((packed));\n\nstruct log_message_t {\n enum { ID = 0x01 };\n\n char data[255];\n} __attribute__((packed));\n\nstruct attitude_message_t {\n enum { ID = 0x02 };\n\n float dcm[9];\n} __attribute__((packed));\n\nstruct set_arm_state_message_t {\n enum { ID = 0x03 };\n\n bool armed;\n} __attribute__((packed));\n\nstruct set_control_mode_message_t {\n enum { ID = 0x04 };\n\n enum class ControlMode {\n MANUAL,\n OFFBOARD\n };\n\n ControlMode mode;\n} __attribute__((packed));\n\nstruct offboard_attitude_control_message_t {\n enum { ID = 0x05 };\n\n float roll;\n float pitch;\n float yaw;\n float throttle;\n uint16_t buttons; \/\/ Bitfield of buttons\n uint8_t mode;\n} __attribute__((packed));\n\nstruct motor_throttle_message_t {\n enum { ID = 0x06 };\n\n float throttles[4];\n} __attribute__((packed));\n\ninline std::uint16_t length(int id) {\n \/\/ TODO(kyle): sizeof(empty struct) is 1 in C++...\n switch(id) {\n case heartbeat_message_t::ID:\n return sizeof(heartbeat_message_t);\n case log_message_t::ID:\n return sizeof(log_message_t);\n case attitude_message_t::ID:\n return sizeof(attitude_message_t);\n case set_arm_state_message_t::ID:\n return sizeof(set_arm_state_message_t);\n case set_control_mode_message_t::ID:\n return sizeof(set_control_mode_message_t);\n case offboard_attitude_control_message_t::ID:\n return sizeof(offboard_attitude_control_message_t);\n case motor_throttle_message_t::ID:\n return sizeof(motor_throttle_message_t);\n }\n\n return 0; \/\/ TODO(kyle): Return something more meaningful?\n}\n\n}\n}\n\n#endif \/\/ MESSAGES_HPP_\n\n<commit_msg>Add sensor calibration messages.<commit_after>#ifndef PROTOCOL_MESSAGES_HPP_\n#define PROTOCOL_MESSAGES_HPP_\n\n#include <cstdint>\n\nnamespace protocol {\nnamespace message {\n\nstruct heartbeat_message_t {\n enum { ID = 0x00 };\n\n std::uint8_t seq;\n} __attribute__((packed));\n\nstruct log_message_t {\n enum { ID = 0x01 };\n\n char data[255];\n} __attribute__((packed));\n\nstruct attitude_message_t {\n enum { ID = 0x02 };\n\n float dcm[9];\n} __attribute__((packed));\n\nstruct set_arm_state_message_t {\n enum { ID = 0x03 };\n\n bool armed;\n} __attribute__((packed));\n\nstruct set_control_mode_message_t {\n enum { ID = 0x04 };\n\n enum class ControlMode {\n MANUAL,\n OFFBOARD\n };\n\n ControlMode mode;\n} __attribute__((packed));\n\nstruct offboard_attitude_control_message_t {\n enum { ID = 0x05 };\n\n float roll;\n float pitch;\n float yaw;\n float throttle;\n uint16_t buttons; \/\/ Bitfield of buttons\n uint8_t mode;\n} __attribute__((packed));\n\nstruct motor_throttle_message_t {\n enum { ID = 0x06 };\n\n float throttles[4];\n} __attribute__((packed));\n\nstruct sensor_calibration_request_message_t {\n enum { ID = 0x07 };\n} __attribute__((packed));\n\nstruct sensor_calibration_response_message_t {\n enum { ID = 0x08 };\n\n enum class SensorType {\n ACCEL,\n GYRO,\n MAG\n };\n\n SensorType type;\n float offsets[3];\n} __attribute__((packed));\n\ninline std::uint16_t length(int id) {\n \/\/ TODO(kyle): sizeof(empty struct) is 1 in C++...\n switch(id) {\n case heartbeat_message_t::ID:\n return sizeof(heartbeat_message_t);\n case log_message_t::ID:\n return sizeof(log_message_t);\n case attitude_message_t::ID:\n return sizeof(attitude_message_t);\n case set_arm_state_message_t::ID:\n return sizeof(set_arm_state_message_t);\n case set_control_mode_message_t::ID:\n return sizeof(set_control_mode_message_t);\n case offboard_attitude_control_message_t::ID:\n return sizeof(offboard_attitude_control_message_t);\n case motor_throttle_message_t::ID:\n return sizeof(motor_throttle_message_t);\n case sensor_calibration_request_message_t::ID:\n return sizeof(sensor_calibration_request_message_t);\n case sensor_calibration_response_message_t::ID:\n return sizeof(sensor_calibration_response_message_t);\n }\n\n return 0; \/\/ TODO(kyle): Return something more meaningful?\n}\n\n}\n}\n\n#endif \/\/ MESSAGES_HPP_\n\n<|endoftext|>"} {"text":"<commit_before>\/****************************************************************************\n**\n** Copyright (C) 2014 Digia Plc and\/or its subsidiary(-ies).\n** Contact: http:\/\/www.qt-project.org\/legal\n**\n** This file is part of Qt Creator.\n**\n** Commercial License Usage\n** Licensees holding valid commercial Qt licenses may use this file in\n** accordance with the commercial license agreement provided with the\n** Software or, alternatively, in accordance with the terms contained in\n** a written agreement between you and Digia. For licensing terms and\n** conditions see http:\/\/qt.digia.com\/licensing. For further information\n** use the contact form at http:\/\/qt.digia.com\/contact-us.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Digia gives you certain additional\n** rights. These rights are described in the Digia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n****************************************************************************\/\n\n#include \"timelinezoomcontrol.h\"\n\nnamespace Timeline {\n\nTimelineZoomControl::TimelineZoomControl(QObject *parent) : QObject(parent), m_traceStart(-1), m_traceEnd(-1),\n m_windowStart(-1), m_windowEnd(-1), m_rangeStart(-1), m_rangeEnd(-1), m_windowLocked(false)\n{\n connect(&m_timer, &QTimer::timeout, this, &TimelineZoomControl::moveWindow);\n}\n\nvoid TimelineZoomControl::clear()\n{\n m_timer.stop();\n setWindowLocked(false);\n setRange(-1, -1);\n setTrace(-1, -1);\n}\n\nvoid TimelineZoomControl::setTraceStart(qint64 start)\n{\n if (start != m_traceStart) {\n if (m_traceEnd < start)\n m_traceEnd = start;\n m_traceStart = start;\n emit traceChanged(start, m_traceEnd);\n rebuildWindow();\n }\n}\n\nvoid TimelineZoomControl::setTraceEnd(qint64 end)\n{\n if (end != m_traceEnd) {\n if (m_traceStart > end)\n m_traceStart = end;\n m_traceEnd = end;\n emit traceChanged(m_traceStart, end);\n rebuildWindow();\n }\n}\n\nvoid TimelineZoomControl::setTrace(qint64 start, qint64 end)\n{\n Q_ASSERT(start <= end);\n if (start != m_traceStart || end != m_traceEnd) {\n m_traceStart = start;\n m_traceEnd = end;\n emit traceChanged(start, end);\n rebuildWindow();\n }\n}\n\nvoid TimelineZoomControl::setRange(qint64 start, qint64 end)\n{\n Q_ASSERT(start <= end);\n if (m_rangeStart != start || m_rangeEnd != end) {\n m_timer.stop();\n m_rangeStart = start;\n m_rangeEnd = end;\n rebuildWindow();\n emit rangeChanged(start, end);\n }\n}\n\nvoid TimelineZoomControl::setWindowLocked(bool windowLocked)\n{\n if (windowLocked != m_windowLocked) {\n m_windowLocked = windowLocked;\n emit windowLockedChanged(windowLocked);\n }\n}\n\nvoid TimelineZoomControl::rebuildWindow()\n{\n qint64 minDuration = 1; \/\/ qMax needs equal data types, so literal 1 won't do\n qint64 shownDuration = qMax(rangeDuration(), minDuration);\n\n qint64 oldWindowStart = m_windowStart;\n qint64 oldWindowEnd = m_windowEnd;\n if (traceDuration() \/ shownDuration < MAX_ZOOM_FACTOR) {\n m_windowStart = m_traceStart;\n m_windowEnd = m_traceEnd;\n } else if (windowDuration() \/ shownDuration > MAX_ZOOM_FACTOR ||\n windowDuration() \/ shownDuration * 2 < MAX_ZOOM_FACTOR) {\n qint64 keep = shownDuration * MAX_ZOOM_FACTOR \/ 2 - shownDuration;\n m_windowStart = m_rangeStart - keep;\n if (m_windowStart < m_traceStart) {\n keep += m_traceStart - m_windowStart;\n m_windowStart = m_traceStart;\n }\n\n m_windowEnd = m_rangeEnd + keep;\n if (m_windowEnd > m_traceEnd) {\n m_windowStart = qMax(m_traceStart, m_windowStart - m_windowEnd - m_traceEnd);\n m_windowEnd = m_traceEnd;\n }\n } else {\n m_timer.start(500);\n }\n if (oldWindowStart != m_windowStart || oldWindowEnd != m_windowEnd) {\n clampRangeToWindow();\n emit windowChanged(m_windowStart, m_windowEnd);\n }\n}\n\nvoid TimelineZoomControl::moveWindow()\n{\n if (m_windowLocked)\n return;\n m_timer.stop();\n\n qint64 offset = (m_rangeEnd - m_windowEnd + m_rangeStart - m_windowStart) \/ 2;\n if (offset == 0 || (offset < 0 && m_windowStart == m_traceStart) ||\n (offset > 0 && m_windowEnd == m_traceEnd)) {\n return;\n } else if (offset > rangeDuration()) {\n offset = (offset + rangeDuration()) \/ 2;\n } else if (offset < -rangeDuration()) {\n offset = (offset - rangeDuration()) \/ 2;\n }\n m_windowStart += offset;\n if (m_windowStart < m_traceStart) {\n m_windowEnd += m_traceStart - m_windowStart;\n m_windowStart = m_traceStart;\n }\n m_windowEnd += offset;\n if (m_windowEnd > m_traceEnd) {\n m_windowStart -= m_windowEnd - m_traceEnd;\n m_windowEnd = m_traceEnd;\n }\n\n clampRangeToWindow();\n emit windowChanged(m_windowStart, m_windowEnd);\n m_timer.start(100);\n}\n\nvoid TimelineZoomControl::clampRangeToWindow()\n{\n qint64 rangeStart = qMin(qMax(m_rangeStart, m_windowStart), m_windowEnd);\n qint64 rangeEnd = qMin(qMax(rangeStart, m_rangeEnd), m_windowEnd);\n if (rangeStart != m_rangeStart || rangeEnd != m_rangeEnd)\n setRange(rangeStart, rangeEnd);\n}\n\n} \/\/ namespace Timeline\n<commit_msg>Timeline: Add some forgotten braces<commit_after>\/****************************************************************************\n**\n** Copyright (C) 2014 Digia Plc and\/or its subsidiary(-ies).\n** Contact: http:\/\/www.qt-project.org\/legal\n**\n** This file is part of Qt Creator.\n**\n** Commercial License Usage\n** Licensees holding valid commercial Qt licenses may use this file in\n** accordance with the commercial license agreement provided with the\n** Software or, alternatively, in accordance with the terms contained in\n** a written agreement between you and Digia. For licensing terms and\n** conditions see http:\/\/qt.digia.com\/licensing. For further information\n** use the contact form at http:\/\/qt.digia.com\/contact-us.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Digia gives you certain additional\n** rights. These rights are described in the Digia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n****************************************************************************\/\n\n#include \"timelinezoomcontrol.h\"\n\nnamespace Timeline {\n\nTimelineZoomControl::TimelineZoomControl(QObject *parent) : QObject(parent), m_traceStart(-1), m_traceEnd(-1),\n m_windowStart(-1), m_windowEnd(-1), m_rangeStart(-1), m_rangeEnd(-1), m_windowLocked(false)\n{\n connect(&m_timer, &QTimer::timeout, this, &TimelineZoomControl::moveWindow);\n}\n\nvoid TimelineZoomControl::clear()\n{\n m_timer.stop();\n setWindowLocked(false);\n setRange(-1, -1);\n setTrace(-1, -1);\n}\n\nvoid TimelineZoomControl::setTraceStart(qint64 start)\n{\n if (start != m_traceStart) {\n if (m_traceEnd < start)\n m_traceEnd = start;\n m_traceStart = start;\n emit traceChanged(start, m_traceEnd);\n rebuildWindow();\n }\n}\n\nvoid TimelineZoomControl::setTraceEnd(qint64 end)\n{\n if (end != m_traceEnd) {\n if (m_traceStart > end)\n m_traceStart = end;\n m_traceEnd = end;\n emit traceChanged(m_traceStart, end);\n rebuildWindow();\n }\n}\n\nvoid TimelineZoomControl::setTrace(qint64 start, qint64 end)\n{\n Q_ASSERT(start <= end);\n if (start != m_traceStart || end != m_traceEnd) {\n m_traceStart = start;\n m_traceEnd = end;\n emit traceChanged(start, end);\n rebuildWindow();\n }\n}\n\nvoid TimelineZoomControl::setRange(qint64 start, qint64 end)\n{\n Q_ASSERT(start <= end);\n if (m_rangeStart != start || m_rangeEnd != end) {\n m_timer.stop();\n m_rangeStart = start;\n m_rangeEnd = end;\n rebuildWindow();\n emit rangeChanged(start, end);\n }\n}\n\nvoid TimelineZoomControl::setWindowLocked(bool windowLocked)\n{\n if (windowLocked != m_windowLocked) {\n m_windowLocked = windowLocked;\n emit windowLockedChanged(windowLocked);\n }\n}\n\nvoid TimelineZoomControl::rebuildWindow()\n{\n qint64 minDuration = 1; \/\/ qMax needs equal data types, so literal 1 won't do\n qint64 shownDuration = qMax(rangeDuration(), minDuration);\n\n qint64 oldWindowStart = m_windowStart;\n qint64 oldWindowEnd = m_windowEnd;\n if (traceDuration() \/ shownDuration < MAX_ZOOM_FACTOR) {\n m_windowStart = m_traceStart;\n m_windowEnd = m_traceEnd;\n } else if (windowDuration() \/ shownDuration > MAX_ZOOM_FACTOR ||\n windowDuration() \/ shownDuration * 2 < MAX_ZOOM_FACTOR) {\n qint64 keep = shownDuration * MAX_ZOOM_FACTOR \/ 2 - shownDuration;\n m_windowStart = m_rangeStart - keep;\n if (m_windowStart < m_traceStart) {\n keep += m_traceStart - m_windowStart;\n m_windowStart = m_traceStart;\n }\n\n m_windowEnd = m_rangeEnd + keep;\n if (m_windowEnd > m_traceEnd) {\n m_windowStart = qMax(m_traceStart, m_windowStart - (m_windowEnd - m_traceEnd));\n m_windowEnd = m_traceEnd;\n }\n } else {\n m_timer.start(500);\n }\n if (oldWindowStart != m_windowStart || oldWindowEnd != m_windowEnd) {\n clampRangeToWindow();\n emit windowChanged(m_windowStart, m_windowEnd);\n }\n}\n\nvoid TimelineZoomControl::moveWindow()\n{\n if (m_windowLocked)\n return;\n m_timer.stop();\n\n qint64 offset = (m_rangeEnd - m_windowEnd + m_rangeStart - m_windowStart) \/ 2;\n if (offset == 0 || (offset < 0 && m_windowStart == m_traceStart) ||\n (offset > 0 && m_windowEnd == m_traceEnd)) {\n return;\n } else if (offset > rangeDuration()) {\n offset = (offset + rangeDuration()) \/ 2;\n } else if (offset < -rangeDuration()) {\n offset = (offset - rangeDuration()) \/ 2;\n }\n m_windowStart += offset;\n if (m_windowStart < m_traceStart) {\n m_windowEnd += m_traceStart - m_windowStart;\n m_windowStart = m_traceStart;\n }\n m_windowEnd += offset;\n if (m_windowEnd > m_traceEnd) {\n m_windowStart -= m_windowEnd - m_traceEnd;\n m_windowEnd = m_traceEnd;\n }\n\n clampRangeToWindow();\n emit windowChanged(m_windowStart, m_windowEnd);\n m_timer.start(100);\n}\n\nvoid TimelineZoomControl::clampRangeToWindow()\n{\n qint64 rangeStart = qMin(qMax(m_rangeStart, m_windowStart), m_windowEnd);\n qint64 rangeEnd = qMin(qMax(rangeStart, m_rangeEnd), m_windowEnd);\n if (rangeStart != m_rangeStart || rangeEnd != m_rangeEnd)\n setRange(rangeStart, rangeEnd);\n}\n\n} \/\/ namespace Timeline\n<|endoftext|>"} {"text":"<commit_before>#include \"camerafilter.h\"\n\n#include \"cameraframegrabber.h\"\n\n\/\/#include <QCameraViewfinder>\n#include <QCameraInfo>\n\n#include <QtDebug>\n\nCameraFilter::CameraFilter(QSize resolution):camera_(),\n cameraFrameGrabber_(),\n resolution_(resolution)\n{\n name_ = \"CamF\";\n camera_ = new QCamera(QCameraInfo::defaultCamera());\n cameraFrameGrabber_ = new CameraFrameGrabber();\n\n Q_ASSERT(camera_ && cameraFrameGrabber_);\n\n camera_->setViewfinder(cameraFrameGrabber_);\n\n connect(cameraFrameGrabber_, SIGNAL(frameAvailable(QVideoFrame)), this, SLOT(handleFrame(QVideoFrame)));\n\n camera_->start();\n}\n\nCameraFilter::~CameraFilter()\n{\n delete camera_;\n delete cameraFrameGrabber_;\n}\n\nvoid CameraFilter::process()\n{\n \/\/ do nothing because camera input is handled via camera signal\n}\n\n\nvoid CameraFilter::stop()\n{\n camera_->stop();\n Filter::stop();\n}\n\nvoid CameraFilter::handleFrame(const QVideoFrame &frame)\n{\n QVideoFrame cloneFrame(frame);\n cloneFrame.map(QAbstractVideoBuffer::ReadOnly);\n\n QVideoFrame::PixelFormat pf = cloneFrame.pixelFormat();\n\n Q_ASSERT(pf == QVideoFrame::Format_RGB32);\n\n Data * newImage = new Data;\n\n newImage->type = RGB32VIDEO;\n std::unique_ptr<uchar> uu(new uchar[cloneFrame.mappedBytes()]);\n newImage->data = std::unique_ptr<uchar[]>(new uchar[cloneFrame.mappedBytes()]);\n\n uchar *bits = cloneFrame.bits();\n\n memcpy(newImage->data.get(), bits, cloneFrame.mappedBytes());\n newImage->data_size = cloneFrame.mappedBytes();\n newImage->width = cloneFrame.width();\n newImage->height = cloneFrame.height();\n\n QImage image(\n newImage->data.get(),\n newImage->width,\n newImage->height,\n QImage::Format_RGB32);\n\n QImage image2 = image.scaled(resolution_);\n memcpy(newImage->data.get(), image2.bits(), image2.byteCount());\n newImage->width = resolution_.width();\n newImage->height = resolution_.height();\n newImage->data_size = image2.byteCount();\n \/\/qDebug() << \"Frame generated. Format: \" << pf\n \/\/ << \" width: \" << newImage->width << \", height: \" << newImage->height;\n\n std::unique_ptr<Data> u_newImage( newImage );\n cloneFrame.unmap();\n\n Q_ASSERT(u_newImage->data);\n sendOutput(std::move(u_newImage));\n}\n<commit_msg>Fixed a scaling crash when scaling image upwards.<commit_after>#include \"camerafilter.h\"\n\n#include \"cameraframegrabber.h\"\n\n\/\/#include <QCameraViewfinder>\n#include <QCameraInfo>\n\n#include <QtDebug>\n\nCameraFilter::CameraFilter(QSize resolution):camera_(),\n cameraFrameGrabber_(),\n resolution_(resolution)\n{\n name_ = \"CamF\";\n camera_ = new QCamera(QCameraInfo::defaultCamera());\n cameraFrameGrabber_ = new CameraFrameGrabber();\n\n Q_ASSERT(camera_ && cameraFrameGrabber_);\n\n camera_->setViewfinder(cameraFrameGrabber_);\n\n connect(cameraFrameGrabber_, SIGNAL(frameAvailable(QVideoFrame)), this, SLOT(handleFrame(QVideoFrame)));\n\n camera_->start();\n}\n\nCameraFilter::~CameraFilter()\n{\n delete camera_;\n delete cameraFrameGrabber_;\n}\n\nvoid CameraFilter::process()\n{\n \/\/ do nothing because camera input is handled via camera signal\n}\n\n\nvoid CameraFilter::stop()\n{\n camera_->stop();\n Filter::stop();\n}\n\nvoid CameraFilter::handleFrame(const QVideoFrame &frame)\n{\n QVideoFrame cloneFrame(frame);\n cloneFrame.map(QAbstractVideoBuffer::ReadOnly);\n\n QVideoFrame::PixelFormat pf = cloneFrame.pixelFormat();\n\n Q_ASSERT(pf == QVideoFrame::Format_RGB32);\n\n \/\/ capture the frame data\n Data * newImage = new Data;\n newImage->type = RGB32VIDEO;\n std::unique_ptr<uchar> uu(new uchar[cloneFrame.mappedBytes()]);\n newImage->data = std::unique_ptr<uchar[]>(new uchar[cloneFrame.mappedBytes()]);\n\n uchar *bits = cloneFrame.bits();\n\n memcpy(newImage->data.get(), bits, cloneFrame.mappedBytes());\n newImage->data_size = cloneFrame.mappedBytes();\n newImage->width = cloneFrame.width();\n newImage->height = cloneFrame.height();\n\n \/\/ scale the image and copy to new data\n if(resolution_ != cloneFrame.size())\n {\n QImage image(\n newImage->data.get(),\n newImage->width,\n newImage->height,\n QImage::Format_RGB32);\n\n QImage image2 = image.scaled(resolution_);\n if(resolution_.width() * resolution_.height()\n > cloneFrame.size().width() * cloneFrame.size().height())\n {\n newImage->data = std::unique_ptr<uchar[]>(new uchar[image2.byteCount()]);\n }\n memcpy(newImage->data.get(), image2.bits(), image2.byteCount());\n newImage->width = resolution_.width();\n newImage->height = resolution_.height();\n newImage->data_size = image2.byteCount();\n }\n\n \/\/qDebug() << \"Frame generated. Format: \" << pf\n \/\/ << \" width: \" << newImage->width << \", height: \" << newImage->height;\n\n std::unique_ptr<Data> u_newImage( newImage );\n cloneFrame.unmap();\n\n Q_ASSERT(u_newImage->data);\n sendOutput(std::move(u_newImage));\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/diagnostics\/diagnostics_main.h\"\n\n#include \"app\/app_paths.h\"\n#include \"base\/basictypes.h\"\n#include \"base\/command_line.h\"\n#include \"base\/i18n\/icu_util.h\"\n#include \"base\/string_util.h\"\n#include \"base\/time.h\"\n#include \"chrome\/browser\/diagnostics\/diagnostics_model.h\"\n#include \"chrome\/common\/chrome_paths.h\"\n\n#if defined(OS_WIN)\n#include \"base\/win_util.h\"\n\nnamespace {\n\/\/ This is a minimalistic class to wrap the windows console operating\n\/\/ in high-level IO mode. This will be eventually replaced by a view\n\/\/ that can be subclassed for each platform and that the approved look\n\/\/ and feel.\nclass SimpleConsole {\n public:\n \/\/ The ctor allocates a console always. This avoids having to ask\n \/\/ the user to start chrome from a command prompt.\n SimpleConsole()\n : std_out_(INVALID_HANDLE_VALUE),\n std_in_(INVALID_HANDLE_VALUE) {\n }\n\n ~SimpleConsole() {\n ::FreeConsole();\n }\n \/\/ Init must be called before using any other method. If it returns\n \/\/ false there would be no console output.\n bool Init() {\n ::AllocConsole();\n return SetIOHandles();\n }\n\n \/\/ Writes a string to the console with the current color.\n bool Write(const std::wstring& txt) {\n DWORD sz = txt.size();\n return (TRUE == ::WriteConsoleW(std_out_, txt.c_str(), sz, &sz, NULL));\n }\n\n \/\/ Reads a string from the console. Internally it is limited to 256\n \/\/ characters.\n bool Read(std::wstring* txt) {\n wchar_t buf[256];\n DWORD read = sizeof(buf) - sizeof(buf[0]);\n if (!::ReadConsoleW(std_in_, buf, read, &read, NULL))\n return false;\n \/\/ Note that |read| is in bytes.\n txt->assign(buf, read\/2);\n return true;\n }\n\n \/\/ Sets the foreground and backgroudn color. See |kRedFG| or |kGreenFG|\n \/\/ below for examples how to combine colors.\n bool SetColor(uint16 color_combo) {\n return (TRUE == ::SetConsoleTextAttribute(std_out_, color_combo));\n }\n\n private:\n bool SetIOHandles() {\n std_out_ = ::GetStdHandle(STD_OUTPUT_HANDLE);\n std_in_ = ::GetStdHandle(STD_INPUT_HANDLE);\n return ((std_out_ != INVALID_HANDLE_VALUE) &&\n (std_in_ != INVALID_HANDLE_VALUE));\n }\n\n \/\/ The input and output handles to the screen. They seem to be\n \/\/ implemented as pipes but they have non-documented protocol.\n HANDLE std_out_;\n HANDLE std_in_;\n\n DISALLOW_COPY_AND_ASSIGN(SimpleConsole);\n};\n\n\/\/ This class wraps a SimpleConsole for the specific use case of\n\/\/ writing the results of the diagnostic tests.\n\/\/ TODO(cpu) figure out the localization strategy.\nclass TestWriter {\n public:\n \/\/ The |console| must be valid and properly initialized. This\n \/\/ class does not own it.\n explicit TestWriter(SimpleConsole* console) : console_(console) {\n }\n\n \/\/ Write an informational line of text in white over black.\n bool WriteInfoText(const std::wstring& txt) {\n console_->SetColor(kWhiteFG);\n return console_->Write(txt);\n }\n\n \/\/ Write a result block. It consist of two lines. The first line\n \/\/ has [PASS] or [FAIL] with |name| and the second line has\n \/\/ the text in |extra|.\n bool WriteResult(bool success, const std::wstring& name,\n const std::wstring& extra) {\n if (success) {\n console_->SetColor(kGreenFG);\n console_->Write(L\"[PASS] \");\n } else {\n console_->SetColor(kRedFG);\n console_->Write(L\"[FAIL] \");\n }\n WriteInfoText(name + L\"\\n\");\n std::wstring second_line(L\" \");\n second_line.append(extra);\n return WriteInfoText(second_line + L\"\\n\\n\");\n }\n\n private:\n \/\/ constants for the colors we use.\n static const uint16 kRedFG = FOREGROUND_RED|FOREGROUND_INTENSITY;\n static const uint16 kGreenFG = FOREGROUND_GREEN|FOREGROUND_INTENSITY;\n static const uint16 kWhiteFG = kRedFG | kGreenFG | FOREGROUND_BLUE;\n\n SimpleConsole* console_;\n\n DISALLOW_COPY_AND_ASSIGN(TestWriter);\n};\n\nstd::wstring PrintableUSCurrentTime() {\n base::Time::Exploded exploded = {0};\n base::Time::Now().UTCExplode(&exploded);\n return StringPrintf(L\"%d:%d:%d.%d:%d:%d\",\n exploded.year, exploded.month, exploded.day_of_month,\n exploded.hour, exploded.minute, exploded.second);\n}\n\n\/\/ This class is a basic test controller. In this design the view (TestWriter)\n\/\/ and the model (DiagnosticsModel) do not talk to each other directly but they\n\/\/ are mediated by the controller. This has a name: 'passive view'.\n\/\/ More info at http:\/\/martinfowler.com\/eaaDev\/PassiveScreen.html\nclass TestController : public DiagnosticsModel::Observer {\n public:\n explicit TestController(TestWriter* writer) : writer_(writer) {\n }\n\n \/\/ Run all the diagnostics of |model| and invoke the view as the model\n \/\/ callbacks arrive.\n void Run(DiagnosticsModel* model) {\n std::wstring title(L\"Chrome Diagnostics Mode (\");\n writer_->WriteInfoText(title.append(PrintableUSCurrentTime()) + L\")\\n\");\n if (!model) {\n writer_->WriteResult(false, L\"Diagnostics start\", L\"model is null\");\n return;\n }\n bool icu_result = icu_util::Initialize();\n if (!icu_result) {\n writer_->WriteResult(false, L\"Diagnostics start\", L\"ICU failure\");\n return;\n }\n int count = model->GetTestAvailableCount();\n writer_->WriteInfoText(StringPrintf(L\"%d available test(s)\\n\\n\", count));\n model->RunAll(this);\n }\n\n \/\/ Next four are overriden from DiagnosticsModel::Observer\n virtual void OnProgress(int id, int percent, DiagnosticsModel* model) {\n }\n\n virtual void OnSkipped(int id, DiagnosticsModel* model) {\n \/\/ TODO(cpu): display skipped tests.\n }\n\n virtual void OnFinished(int id, DiagnosticsModel* model) {\n \/\/ As each test completes we output the results.\n ShowResult(model->GetTest(id));\n }\n\n virtual void OnDoneAll(DiagnosticsModel* model) {\n writer_->WriteInfoText(L\"DONE\\n\\n\");\n }\n\n private:\n void ShowResult(DiagnosticsModel::TestInfo& test_info) {\n bool success = (DiagnosticsModel::TEST_OK == test_info.GetResult());\n writer_->WriteResult(success, test_info.GetTitle(),\n test_info.GetAdditionalInfo());\n }\n\n DiagnosticsModel* model_;\n TestWriter* writer_;\n\n DISALLOW_COPY_AND_ASSIGN(TestController);\n};\n} \/\/ namespace\n\n\/\/ This entry point is called from ChromeMain() when very few things\n\/\/ have been initialized. To wit:\n\/\/ -(win) Breakpad\n\/\/ -(macOS) base::EnableTerminationOnHeapCorruption()\n\/\/ -(macOS) base::EnableTerminationOnOutOfMemory()\n\/\/ -(all) RegisterInvalidParamHandler()\n\/\/ -(all) base::AtExitManager::AtExitManager()\n\/\/ -(macOS) base::ScopedNSAutoreleasePool\n\/\/ -(posix) Singleton<base::GlobalDescriptors>::Set(kPrimaryIPCChannel)\n\/\/ -(linux) Singleton<base::GlobalDescriptors>::Set(kCrashDumpSignal)\n\/\/ -(posix) setlocale(LC_ALL,..)\n\/\/ -(all) CommandLine::Init();\n\nint DiagnosticsMain(const CommandLine& command_line) {\n \/\/ If we can't initialize the console exit right away.\n SimpleConsole console;\n if (!console.Init())\n return 1;\n\n \/\/ We need to have the path providers registered. They both\n \/\/ return void so there is no early error signal that we can use.\n app::RegisterPathProvider();\n chrome::RegisterPathProvider();\n\n TestWriter writer(&console);\n DiagnosticsModel* model = MakeDiagnosticsModel(command_line);\n TestController controller(&writer);\n\n \/\/ Run all the diagnostic tests.\n controller.Run(model);\n delete model;\n\n \/\/ Block here so the user can see the results.\n writer.WriteInfoText(L\"Press [enter] to continue\\n\");\n std::wstring txt;\n console.Read(&txt);\n return 0;\n}\n\n#else \/\/ defined(OS_WIN)\n\nint DiagnosticsMain(const CommandLine& command_line) {\n return 0;\n}\n\n#endif\n<commit_msg>Posix: implement diagnostics mode console output.<commit_after>\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/diagnostics\/diagnostics_main.h\"\n\n#if defined(OS_POSIX)\n#include <stdio.h>\n#include <unistd.h>\n#endif\n\n#include \"app\/app_paths.h\"\n#include \"base\/basictypes.h\"\n#include \"base\/command_line.h\"\n#include \"base\/i18n\/icu_util.h\"\n#include \"base\/string_util.h\"\n#include \"base\/sys_string_conversions.h\"\n#include \"base\/time.h\"\n#include \"base\/utf_string_conversions.h\"\n#include \"chrome\/browser\/diagnostics\/diagnostics_model.h\"\n#include \"chrome\/common\/chrome_paths.h\"\n\n#if defined(OS_WIN)\n#include \"base\/win_util.h\"\n#endif\n\nnamespace {\n\/\/ This is a minimalistic interface to wrap the platform console. This will be\n\/\/ eventually replaced by a view that can be subclassed for each platform and\n\/\/ that the approved look and feel.\nclass SimpleConsole {\n public:\n enum Color {\n DEFAULT,\n RED,\n GREEN,\n };\n\n virtual ~SimpleConsole() { }\n\n \/\/ Init must be called before using any other method. If it returns\n \/\/ false there would be no console output.\n virtual bool Init() = 0;\n\n \/\/ Writes a string to the console with the current color.\n virtual bool Write(const std::wstring& text) = 0;\n\n \/\/ Reads a string from the console. Internally it may be limited to 256\n \/\/ characters.\n virtual bool Read(std::wstring* txt) = 0;\n\n \/\/ Sets the foreground and background color.\n virtual bool SetColor(Color color) = 0;\n\n \/\/ Create an appropriate SimpleConsole instance. May return NULL if there is\n \/\/ no implementation for the current platform.\n static SimpleConsole* Create();\n};\n\n#if defined(OS_WIN)\n\/\/ Wrapper for the windows console operating in high-level IO mode.\nclass WinConsole : public SimpleConsole {\n public:\n \/\/ The ctor allocates a console always. This avoids having to ask\n \/\/ the user to start chrome from a command prompt.\n WinConsole()\n : std_out_(INVALID_HANDLE_VALUE),\n std_in_(INVALID_HANDLE_VALUE) {\n }\n\n virtual ~WinConsole() {\n ::FreeConsole();\n }\n\n virtual bool Init() {\n ::AllocConsole();\n return SetIOHandles();\n }\n\n virtual bool Write(const std::wstring& txt) {\n DWORD sz = txt.size();\n return (TRUE == ::WriteConsoleW(std_out_, txt.c_str(), sz, &sz, NULL));\n }\n\n \/\/ Reads a string from the console. Internally it is limited to 256\n \/\/ characters.\n virtual bool Read(std::wstring* txt) {\n wchar_t buf[256];\n DWORD read = sizeof(buf) - sizeof(buf[0]);\n if (!::ReadConsoleW(std_in_, buf, read, &read, NULL))\n return false;\n \/\/ Note that |read| is in bytes.\n txt->assign(buf, read\/2);\n return true;\n }\n\n \/\/ Sets the foreground and background color.\n virtual bool SetColor(Color color) {\n uint16 color_combo =\n FOREGROUND_RED|FOREGROUND_GREEN|FOREGROUND_BLUE|FOREGROUND_INTENSITY;\n switch (color) {\n case RED:\n color_combo = FOREGROUND_RED|FOREGROUND_INTENSITY;\n break;\n case GREEN:\n color_combo = FOREGROUND_GREEN|FOREGROUND_INTENSITY;\n break;\n case DEFAULT:\n break;\n default:\n NOTREACHED();\n }\n return (TRUE == ::SetConsoleTextAttribute(std_out_, color_combo));\n }\n\n private:\n bool SetIOHandles() {\n std_out_ = ::GetStdHandle(STD_OUTPUT_HANDLE);\n std_in_ = ::GetStdHandle(STD_INPUT_HANDLE);\n return ((std_out_ != INVALID_HANDLE_VALUE) &&\n (std_in_ != INVALID_HANDLE_VALUE));\n }\n\n \/\/ The input and output handles to the screen. They seem to be\n \/\/ implemented as pipes but they have non-documented protocol.\n HANDLE std_out_;\n HANDLE std_in_;\n\n DISALLOW_COPY_AND_ASSIGN(WinConsole);\n};\n\nSimpleConsole* SimpleConsole::Create() {\n return new WinConsole();\n}\n\n#elif defined(OS_POSIX)\n\nclass PosixConsole : public SimpleConsole {\n public:\n PosixConsole() { }\n\n virtual bool Init() {\n \/\/ Technically, we should also check the terminal capabilities before using\n \/\/ color, but in practice this is unlikely to be an issue.\n use_color_ = isatty(STDOUT_FILENO);\n return true;\n }\n\n virtual bool Write(const std::wstring& text) {\n printf(\"%s\", base::SysWideToNativeMB(text).c_str());\n return true;\n }\n\n virtual bool Read(std::wstring* txt) {\n \/\/ TODO(mattm): implement this.\n return false;\n }\n\n virtual bool SetColor(Color color) {\n if (!use_color_)\n return false;\n\n const char* code = \"\\033[m\";\n switch (color) {\n case RED:\n code = \"\\033[1;31m\";\n break;\n case GREEN:\n code = \"\\033[1;32m\";\n break;\n case DEFAULT:\n break;\n default:\n NOTREACHED();\n }\n printf(\"%s\", code);\n return true;\n }\n\n private:\n bool use_color_;\n\n DISALLOW_COPY_AND_ASSIGN(PosixConsole);\n};\n\nSimpleConsole* SimpleConsole::Create() {\n return new PosixConsole();\n}\n\n#else \/\/ !defined(OS_WIN) && !defined(OS_POSIX)\n\nSimpleConsole* SimpleConsole::Create() {\n return NULL;\n}\n#endif\n\n\/\/ This class wraps a SimpleConsole for the specific use case of\n\/\/ writing the results of the diagnostic tests.\n\/\/ TODO(cpu) figure out the localization strategy.\nclass TestWriter {\n public:\n \/\/ The |console| must be valid and properly initialized. This\n \/\/ class does not own it.\n explicit TestWriter(SimpleConsole* console) : console_(console) {\n }\n\n \/\/ Write an informational line of text in white over black.\n bool WriteInfoText(const std::wstring& txt) {\n console_->SetColor(SimpleConsole::DEFAULT);\n return console_->Write(txt);\n }\n\n \/\/ Write a result block. It consist of two lines. The first line\n \/\/ has [PASS] or [FAIL] with |name| and the second line has\n \/\/ the text in |extra|.\n bool WriteResult(bool success, const std::wstring& name,\n const std::wstring& extra) {\n if (success) {\n console_->SetColor(SimpleConsole::GREEN);\n console_->Write(L\"[PASS] \");\n } else {\n console_->SetColor(SimpleConsole::RED);\n console_->Write(L\"[FAIL] \");\n }\n WriteInfoText(name + L\"\\n\");\n std::wstring second_line(L\" \");\n second_line.append(extra);\n return WriteInfoText(second_line + L\"\\n\\n\");\n }\n\n private:\n\n SimpleConsole* console_;\n\n DISALLOW_COPY_AND_ASSIGN(TestWriter);\n};\n\nstd::wstring PrintableUSCurrentTime() {\n base::Time::Exploded exploded = {0};\n base::Time::Now().UTCExplode(&exploded);\n return StringPrintf(L\"%d:%d:%d.%d:%d:%d\",\n exploded.year, exploded.month, exploded.day_of_month,\n exploded.hour, exploded.minute, exploded.second);\n}\n\n\/\/ This class is a basic test controller. In this design the view (TestWriter)\n\/\/ and the model (DiagnosticsModel) do not talk to each other directly but they\n\/\/ are mediated by the controller. This has a name: 'passive view'.\n\/\/ More info at http:\/\/martinfowler.com\/eaaDev\/PassiveScreen.html\nclass TestController : public DiagnosticsModel::Observer {\n public:\n explicit TestController(TestWriter* writer) : writer_(writer) {\n }\n\n \/\/ Run all the diagnostics of |model| and invoke the view as the model\n \/\/ callbacks arrive.\n void Run(DiagnosticsModel* model) {\n std::wstring title(L\"Chrome Diagnostics Mode (\");\n writer_->WriteInfoText(title.append(PrintableUSCurrentTime()) + L\")\\n\");\n if (!model) {\n writer_->WriteResult(false, L\"Diagnostics start\", L\"model is null\");\n return;\n }\n bool icu_result = icu_util::Initialize();\n if (!icu_result) {\n writer_->WriteResult(false, L\"Diagnostics start\", L\"ICU failure\");\n return;\n }\n int count = model->GetTestAvailableCount();\n writer_->WriteInfoText(StringPrintf(L\"%d available test(s)\\n\\n\", count));\n model->RunAll(this);\n }\n\n \/\/ Next four are overriden from DiagnosticsModel::Observer\n virtual void OnProgress(int id, int percent, DiagnosticsModel* model) {\n }\n\n virtual void OnSkipped(int id, DiagnosticsModel* model) {\n \/\/ TODO(cpu): display skipped tests.\n }\n\n virtual void OnFinished(int id, DiagnosticsModel* model) {\n \/\/ As each test completes we output the results.\n ShowResult(model->GetTest(id));\n }\n\n virtual void OnDoneAll(DiagnosticsModel* model) {\n writer_->WriteInfoText(L\"DONE\\n\\n\");\n }\n\n private:\n void ShowResult(DiagnosticsModel::TestInfo& test_info) {\n bool success = (DiagnosticsModel::TEST_OK == test_info.GetResult());\n writer_->WriteResult(success, UTF16ToWide(test_info.GetTitle()),\n UTF16ToWide(test_info.GetAdditionalInfo()));\n }\n\n DiagnosticsModel* model_;\n TestWriter* writer_;\n\n DISALLOW_COPY_AND_ASSIGN(TestController);\n};\n} \/\/ namespace\n\n\/\/ This entry point is called from ChromeMain() when very few things\n\/\/ have been initialized. To wit:\n\/\/ -(win) Breakpad\n\/\/ -(macOS) base::EnableTerminationOnHeapCorruption()\n\/\/ -(macOS) base::EnableTerminationOnOutOfMemory()\n\/\/ -(all) RegisterInvalidParamHandler()\n\/\/ -(all) base::AtExitManager::AtExitManager()\n\/\/ -(macOS) base::ScopedNSAutoreleasePool\n\/\/ -(posix) Singleton<base::GlobalDescriptors>::Set(kPrimaryIPCChannel)\n\/\/ -(linux) Singleton<base::GlobalDescriptors>::Set(kCrashDumpSignal)\n\/\/ -(posix) setlocale(LC_ALL,..)\n\/\/ -(all) CommandLine::Init();\n\nint DiagnosticsMain(const CommandLine& command_line) {\n \/\/ If we can't initialize the console exit right away.\n SimpleConsole* console = SimpleConsole::Create();\n if (!console || !console->Init())\n return 1;\n\n \/\/ We need to have the path providers registered. They both\n \/\/ return void so there is no early error signal that we can use.\n app::RegisterPathProvider();\n chrome::RegisterPathProvider();\n\n TestWriter writer(console);\n DiagnosticsModel* model = MakeDiagnosticsModel(command_line);\n TestController controller(&writer);\n\n \/\/ Run all the diagnostic tests.\n controller.Run(model);\n delete model;\n\n \/\/ The \"press enter to continue\" prompt isn't very unixy, so only do that on\n \/\/ Windows.\n#if defined(OS_WIN)\n \/\/ Block here so the user can see the results.\n writer.WriteInfoText(L\"Press [enter] to continue\\n\");\n std::wstring txt;\n console->Read(&txt);\n#endif\n delete console;\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>#ifndef MESSAGES_HPP_\n#define MESSAGES_HPP_\n\n#include <cstdint>\n\nnamespace protocol {\nnamespace message {\n\nstruct heartbeat_message_t {\n enum { ID = 0x00 };\n\n std::uint8_t seq;\n} __attribute__((packed));\n\nstruct log_message_t {\n enum { ID = 0x01 };\n\n char data[255];\n} __attribute__((packed));\n\nstruct attitude_message_t {\n enum { ID = 0x02 };\n\n float roll;\n float pitch;\n float yaw;\n} __attribute__((packed));\n\nstd::uint16_t length(int id) {\n \/\/ TODO(kyle): sizeof(empty struct) is 1 in C++...\n switch(id) {\n case heartbeat_message_t::ID:\n return sizeof(heartbeat_message_t);\n case log_message_t::ID:\n return sizeof(log_message_t);\n case attitude_message_t::ID:\n return sizeof(attitude_message_t);\n }\n\n return 0; \/\/ TODO(kyle): Return something more meaningful?\n}\n\n}\n}\n\n#endif \/\/ MESSAGES_HPP_\n\n<commit_msg>Add control mode message.<commit_after>#ifndef MESSAGES_HPP_\n#define MESSAGES_HPP_\n\n#include <cstdint>\n\nnamespace protocol {\nnamespace message {\n\nstruct heartbeat_message_t {\n enum { ID = 0x00 };\n\n std::uint8_t seq;\n} __attribute__((packed));\n\nstruct log_message_t {\n enum { ID = 0x01 };\n\n char data[255];\n} __attribute__((packed));\n\nstruct attitude_message_t {\n enum { ID = 0x02 };\n\n float roll;\n float pitch;\n float yaw;\n} __attribute__((packed));\n\nstruct set_control_mode_message_t {\n enum { ID = 0x03 };\n\n enum class ControlMode {\n MANUAL,\n OFFBOARD\n };\n\n ControlMode mode;\n} __attribute__((packed));\n\nstd::uint16_t length(int id) {\n \/\/ TODO(kyle): sizeof(empty struct) is 1 in C++...\n switch(id) {\n case heartbeat_message_t::ID:\n return sizeof(heartbeat_message_t);\n case log_message_t::ID:\n return sizeof(log_message_t);\n case attitude_message_t::ID:\n return sizeof(attitude_message_t);\n case set_control_mode_message_t::ID:\n return sizeof(set_control_mode_message_t);\n }\n\n return 0; \/\/ TODO(kyle): Return something more meaningful?\n}\n\n}\n}\n\n#endif \/\/ MESSAGES_HPP_\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/hung_renderer_dialog.h\"\n\n#include <gtk\/gtk.h>\n\n#include \"app\/l10n_util.h\"\n#include \"app\/resource_bundle.h\"\n#include \"base\/process_util.h\"\n#include \"base\/utf_string_conversions.h\"\n#include \"chrome\/browser\/browser_list.h\"\n#include \"chrome\/browser\/gtk\/gtk_util.h\"\n#include \"chrome\/browser\/renderer_host\/render_process_host.h\"\n#include \"chrome\/browser\/renderer_host\/render_view_host.h\"\n#include \"chrome\/browser\/tab_contents\/tab_contents.h\"\n#include \"chrome\/common\/logging_chrome.h\"\n#include \"chrome\/common\/result_codes.h\"\n#include \"gfx\/gtk_util.h\"\n#include \"grit\/chromium_strings.h\"\n#include \"grit\/generated_resources.h\"\n#include \"grit\/theme_resources.h\"\n\nnamespace {\n\n\/\/ A wrapper class that represents the Gtk dialog.\nclass HungRendererDialogGtk {\n public:\n HungRendererDialogGtk();\n void ShowForTabContents(TabContents* hung_contents);\n void EndForTabContents(TabContents* hung_contents);\n\n private:\n \/\/ The GtkTreeView column ids.\n enum {\n COL_FAVICON,\n COL_TITLE,\n COL_COUNT,\n };\n\n \/\/ Create the gtk dialog and add the widgets.\n void Init();\n\n static void OnDialogResponseThunk(GtkDialog* dialog, gint response_id,\n HungRendererDialogGtk* dialog_gtk) {\n dialog_gtk->OnDialogResponse(response_id);\n }\n void OnDialogResponse(gint response_id);\n\n GtkDialog* dialog_;\n GtkListStore* model_;\n TabContents* contents_;\n\n DISALLOW_COPY_AND_ASSIGN(HungRendererDialogGtk);\n};\n\n\/\/ We only support showing one of these at a time per app.\nHungRendererDialogGtk* g_instance = NULL;\n\n\/\/ The response ID for the \"Kill pages\" button. Anything positive should be\n\/\/ fine (the built in GtkResponseTypes are negative numbers).\nconst int kKillPagesButtonResponse = 1;\n\nHungRendererDialogGtk::HungRendererDialogGtk()\n : dialog_(NULL), model_(NULL), contents_(NULL) {\n Init();\n}\n\nvoid HungRendererDialogGtk::Init() {\n dialog_ = GTK_DIALOG(gtk_dialog_new_with_buttons(\n l10n_util::GetStringUTF8(IDS_BROWSER_HANGMONITOR_RENDERER_TITLE).c_str(),\n NULL, \/\/ No parent because tabs can span multiple windows.\n GTK_DIALOG_NO_SEPARATOR,\n l10n_util::GetStringUTF8(IDS_BROWSER_HANGMONITOR_RENDERER_END).c_str(),\n kKillPagesButtonResponse,\n l10n_util::GetStringUTF8(IDS_BROWSER_HANGMONITOR_RENDERER_WAIT).c_str(),\n GTK_RESPONSE_OK,\n NULL));\n gtk_dialog_set_default_response(dialog_, GTK_RESPONSE_OK);\n g_signal_connect(dialog_, \"response\", G_CALLBACK(OnDialogResponseThunk),\n this);\n\n \/\/ We have an hbox with the frozen icon on the left. On the right,\n \/\/ we have a vbox with the unresponsive text on top and a table of\n \/\/ tabs on bottom.\n \/\/ ·-----------------------------------·\n \/\/ |·---------------------------------·|\n \/\/ ||·----·|·------------------------·||\n \/\/ |||icon||| |||\n \/\/ ||·----·|| The folowing page(s).. |||\n \/\/ || || |||\n \/\/ || ||------------------------|||\n \/\/ || || table of tabs |||\n \/\/ || |·------------------------·||\n \/\/ |·---------------------------------·|\n \/\/ | |\n \/\/ | kill button wait button|\n \/\/ ·-----------------------------------·\n GtkWidget* contents_vbox = dialog_->vbox;\n gtk_box_set_spacing(GTK_BOX(contents_vbox), gtk_util::kContentAreaSpacing);\n\n GtkWidget* hbox = gtk_hbox_new(FALSE, 12);\n gtk_box_pack_start(GTK_BOX(contents_vbox), hbox, TRUE, TRUE, 0);\n\n \/\/ Wrap the icon in a vbox so it stays top aligned.\n GtkWidget* icon_vbox = gtk_vbox_new(FALSE, 0);\n gtk_box_pack_start(GTK_BOX(hbox), icon_vbox, FALSE, FALSE, 0);\n ResourceBundle& rb = ResourceBundle::GetSharedInstance();\n GdkPixbuf* icon_pixbuf = rb.GetPixbufNamed(IDR_FROZEN_TAB_ICON);\n GtkWidget* icon = gtk_image_new_from_pixbuf(icon_pixbuf);\n gtk_box_pack_start(GTK_BOX(icon_vbox), icon, FALSE, FALSE, 0);\n\n GtkWidget* vbox = gtk_vbox_new(FALSE, gtk_util::kControlSpacing);\n gtk_box_pack_start(GTK_BOX(hbox), vbox, TRUE, TRUE, 0);\n\n GtkWidget* text = gtk_label_new(\n l10n_util::GetStringUTF8(IDS_BROWSER_HANGMONITOR_RENDERER).c_str());\n gtk_label_set_line_wrap(GTK_LABEL(text), TRUE);\n gtk_box_pack_start(GTK_BOX(vbox), text, FALSE, FALSE, 0);\n\n GtkWidget* scroll_list = gtk_scrolled_window_new(NULL, NULL);\n gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(scroll_list),\n GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC);\n gtk_scrolled_window_set_shadow_type(GTK_SCROLLED_WINDOW(scroll_list),\n GTK_SHADOW_ETCHED_IN);\n gtk_box_pack_start(GTK_BOX(vbox), scroll_list, TRUE, TRUE, 0);\n\n \/\/ The list of hung tabs is GtkTreeView with a GtkListStore as the model.\n model_ = gtk_list_store_new(COL_COUNT, GDK_TYPE_PIXBUF, G_TYPE_STRING);\n GtkWidget* tree_view = gtk_tree_view_new_with_model(\n GTK_TREE_MODEL(model_));\n g_object_unref(model_);\n gtk_tree_view_set_headers_visible(GTK_TREE_VIEW(tree_view), FALSE);\n GtkTreeViewColumn* column = gtk_tree_view_column_new();\n GtkCellRenderer* renderer = gtk_cell_renderer_pixbuf_new();\n gtk_tree_view_column_pack_start(column, renderer, FALSE);\n gtk_tree_view_column_add_attribute(column, renderer, \"pixbuf\", COL_FAVICON);\n renderer = gtk_cell_renderer_text_new();\n gtk_tree_view_column_pack_start(column, renderer, TRUE);\n gtk_tree_view_column_add_attribute(column, renderer, \"text\", COL_TITLE);\n\n gtk_tree_view_append_column(GTK_TREE_VIEW(tree_view), column);\n gtk_container_add(GTK_CONTAINER(scroll_list), tree_view);\n}\n\nvoid HungRendererDialogGtk::ShowForTabContents(TabContents* hung_contents) {\n DCHECK(hung_contents && dialog_);\n contents_ = hung_contents;\n gtk_list_store_clear(model_);\n\n GtkTreeIter tree_iter;\n for (TabContentsIterator it; !it.done(); ++it) {\n if (it->GetRenderProcessHost() == hung_contents->GetRenderProcessHost()) {\n gtk_list_store_append(model_, &tree_iter);\n std::string title = UTF16ToUTF8(it->GetTitle());\n if (title.empty())\n title = UTF16ToUTF8(TabContents::GetDefaultTitle());\n SkBitmap favicon = it->GetFavIcon();\n\n GdkPixbuf* pixbuf = NULL;\n if (favicon.width() > 0)\n pixbuf = gfx::GdkPixbufFromSkBitmap(&favicon);\n gtk_list_store_set(model_, &tree_iter,\n COL_FAVICON, pixbuf,\n COL_TITLE, title.c_str(),\n -1);\n if (pixbuf)\n g_object_unref(pixbuf);\n }\n }\n gtk_util::ShowDialog(GTK_WIDGET(dialog_));\n}\n\nvoid HungRendererDialogGtk::EndForTabContents(TabContents* contents) {\n DCHECK(contents);\n if (contents_ && contents_->GetRenderProcessHost() ==\n contents->GetRenderProcessHost()) {\n gtk_widget_hide(GTK_WIDGET(dialog_));\n \/\/ Since we're closing, we no longer need this TabContents.\n contents_ = NULL;\n }\n}\n\n\/\/ When the user clicks a button on the dialog or closes the dialog, this\n\/\/ callback is called.\nvoid HungRendererDialogGtk::OnDialogResponse(gint response_id) {\n DCHECK(g_instance == this);\n switch (response_id) {\n case kKillPagesButtonResponse:\n \/\/ Kill the process.\n base::KillProcess(contents_->GetRenderProcessHost()->GetHandle(),\n ResultCodes::HUNG, false);\n break;\n\n case GTK_RESPONSE_OK:\n case GTK_RESPONSE_DELETE_EVENT:\n \/\/ Start waiting again for responsiveness.\n if (contents_ && contents_->render_view_host())\n contents_->render_view_host()->RestartHangMonitorTimeout();\n break;\n default:\n NOTREACHED();\n }\n\n gtk_widget_destroy(GTK_WIDGET(dialog_));\n delete g_instance;\n g_instance = NULL;\n}\n\n} \/\/ namespace\n\nnamespace hung_renderer_dialog {\n\nvoid ShowForTabContents(TabContents* contents) {\n if (!logging::DialogsAreSuppressed()) {\n if (!g_instance)\n g_instance = new HungRendererDialogGtk();\n g_instance->ShowForTabContents(contents);\n }\n}\n\n\/\/ static\nvoid HideForTabContents(TabContents* contents) {\n if (!logging::DialogsAreSuppressed() && g_instance)\n g_instance->EndForTabContents(contents);\n}\n\n} \/\/ namespace hung_renderer_dialog\n<commit_msg>Fix crash in HungRendererDialogGtk when contents_ == NULL.<commit_after>\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/hung_renderer_dialog.h\"\n\n#include <gtk\/gtk.h>\n\n#include \"app\/l10n_util.h\"\n#include \"app\/resource_bundle.h\"\n#include \"base\/process_util.h\"\n#include \"base\/utf_string_conversions.h\"\n#include \"chrome\/browser\/browser_list.h\"\n#include \"chrome\/browser\/gtk\/gtk_util.h\"\n#include \"chrome\/browser\/renderer_host\/render_process_host.h\"\n#include \"chrome\/browser\/renderer_host\/render_view_host.h\"\n#include \"chrome\/browser\/tab_contents\/tab_contents.h\"\n#include \"chrome\/common\/logging_chrome.h\"\n#include \"chrome\/common\/result_codes.h\"\n#include \"gfx\/gtk_util.h\"\n#include \"grit\/chromium_strings.h\"\n#include \"grit\/generated_resources.h\"\n#include \"grit\/theme_resources.h\"\n\nnamespace {\n\n\/\/ A wrapper class that represents the Gtk dialog.\nclass HungRendererDialogGtk {\n public:\n HungRendererDialogGtk();\n void ShowForTabContents(TabContents* hung_contents);\n void EndForTabContents(TabContents* hung_contents);\n\n private:\n \/\/ The GtkTreeView column ids.\n enum {\n COL_FAVICON,\n COL_TITLE,\n COL_COUNT,\n };\n\n \/\/ Create the gtk dialog and add the widgets.\n void Init();\n\n static void OnDialogResponseThunk(GtkDialog* dialog, gint response_id,\n HungRendererDialogGtk* dialog_gtk) {\n dialog_gtk->OnDialogResponse(response_id);\n }\n void OnDialogResponse(gint response_id);\n\n GtkDialog* dialog_;\n GtkListStore* model_;\n TabContents* contents_;\n\n DISALLOW_COPY_AND_ASSIGN(HungRendererDialogGtk);\n};\n\n\/\/ We only support showing one of these at a time per app.\nHungRendererDialogGtk* g_instance = NULL;\n\n\/\/ The response ID for the \"Kill pages\" button. Anything positive should be\n\/\/ fine (the built in GtkResponseTypes are negative numbers).\nconst int kKillPagesButtonResponse = 1;\n\nHungRendererDialogGtk::HungRendererDialogGtk()\n : dialog_(NULL), model_(NULL), contents_(NULL) {\n Init();\n}\n\nvoid HungRendererDialogGtk::Init() {\n dialog_ = GTK_DIALOG(gtk_dialog_new_with_buttons(\n l10n_util::GetStringUTF8(IDS_BROWSER_HANGMONITOR_RENDERER_TITLE).c_str(),\n NULL, \/\/ No parent because tabs can span multiple windows.\n GTK_DIALOG_NO_SEPARATOR,\n l10n_util::GetStringUTF8(IDS_BROWSER_HANGMONITOR_RENDERER_END).c_str(),\n kKillPagesButtonResponse,\n l10n_util::GetStringUTF8(IDS_BROWSER_HANGMONITOR_RENDERER_WAIT).c_str(),\n GTK_RESPONSE_OK,\n NULL));\n gtk_dialog_set_default_response(dialog_, GTK_RESPONSE_OK);\n g_signal_connect(dialog_, \"response\", G_CALLBACK(OnDialogResponseThunk),\n this);\n\n \/\/ We have an hbox with the frozen icon on the left. On the right,\n \/\/ we have a vbox with the unresponsive text on top and a table of\n \/\/ tabs on bottom.\n \/\/ ·-----------------------------------·\n \/\/ |·---------------------------------·|\n \/\/ ||·----·|·------------------------·||\n \/\/ |||icon||| |||\n \/\/ ||·----·|| The folowing page(s).. |||\n \/\/ || || |||\n \/\/ || ||------------------------|||\n \/\/ || || table of tabs |||\n \/\/ || |·------------------------·||\n \/\/ |·---------------------------------·|\n \/\/ | |\n \/\/ | kill button wait button|\n \/\/ ·-----------------------------------·\n GtkWidget* contents_vbox = dialog_->vbox;\n gtk_box_set_spacing(GTK_BOX(contents_vbox), gtk_util::kContentAreaSpacing);\n\n GtkWidget* hbox = gtk_hbox_new(FALSE, 12);\n gtk_box_pack_start(GTK_BOX(contents_vbox), hbox, TRUE, TRUE, 0);\n\n \/\/ Wrap the icon in a vbox so it stays top aligned.\n GtkWidget* icon_vbox = gtk_vbox_new(FALSE, 0);\n gtk_box_pack_start(GTK_BOX(hbox), icon_vbox, FALSE, FALSE, 0);\n ResourceBundle& rb = ResourceBundle::GetSharedInstance();\n GdkPixbuf* icon_pixbuf = rb.GetPixbufNamed(IDR_FROZEN_TAB_ICON);\n GtkWidget* icon = gtk_image_new_from_pixbuf(icon_pixbuf);\n gtk_box_pack_start(GTK_BOX(icon_vbox), icon, FALSE, FALSE, 0);\n\n GtkWidget* vbox = gtk_vbox_new(FALSE, gtk_util::kControlSpacing);\n gtk_box_pack_start(GTK_BOX(hbox), vbox, TRUE, TRUE, 0);\n\n GtkWidget* text = gtk_label_new(\n l10n_util::GetStringUTF8(IDS_BROWSER_HANGMONITOR_RENDERER).c_str());\n gtk_label_set_line_wrap(GTK_LABEL(text), TRUE);\n gtk_box_pack_start(GTK_BOX(vbox), text, FALSE, FALSE, 0);\n\n GtkWidget* scroll_list = gtk_scrolled_window_new(NULL, NULL);\n gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(scroll_list),\n GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC);\n gtk_scrolled_window_set_shadow_type(GTK_SCROLLED_WINDOW(scroll_list),\n GTK_SHADOW_ETCHED_IN);\n gtk_box_pack_start(GTK_BOX(vbox), scroll_list, TRUE, TRUE, 0);\n\n \/\/ The list of hung tabs is GtkTreeView with a GtkListStore as the model.\n model_ = gtk_list_store_new(COL_COUNT, GDK_TYPE_PIXBUF, G_TYPE_STRING);\n GtkWidget* tree_view = gtk_tree_view_new_with_model(\n GTK_TREE_MODEL(model_));\n g_object_unref(model_);\n gtk_tree_view_set_headers_visible(GTK_TREE_VIEW(tree_view), FALSE);\n GtkTreeViewColumn* column = gtk_tree_view_column_new();\n GtkCellRenderer* renderer = gtk_cell_renderer_pixbuf_new();\n gtk_tree_view_column_pack_start(column, renderer, FALSE);\n gtk_tree_view_column_add_attribute(column, renderer, \"pixbuf\", COL_FAVICON);\n renderer = gtk_cell_renderer_text_new();\n gtk_tree_view_column_pack_start(column, renderer, TRUE);\n gtk_tree_view_column_add_attribute(column, renderer, \"text\", COL_TITLE);\n\n gtk_tree_view_append_column(GTK_TREE_VIEW(tree_view), column);\n gtk_container_add(GTK_CONTAINER(scroll_list), tree_view);\n}\n\nvoid HungRendererDialogGtk::ShowForTabContents(TabContents* hung_contents) {\n DCHECK(hung_contents && dialog_);\n contents_ = hung_contents;\n gtk_list_store_clear(model_);\n\n GtkTreeIter tree_iter;\n for (TabContentsIterator it; !it.done(); ++it) {\n if (it->GetRenderProcessHost() == hung_contents->GetRenderProcessHost()) {\n gtk_list_store_append(model_, &tree_iter);\n std::string title = UTF16ToUTF8(it->GetTitle());\n if (title.empty())\n title = UTF16ToUTF8(TabContents::GetDefaultTitle());\n SkBitmap favicon = it->GetFavIcon();\n\n GdkPixbuf* pixbuf = NULL;\n if (favicon.width() > 0)\n pixbuf = gfx::GdkPixbufFromSkBitmap(&favicon);\n gtk_list_store_set(model_, &tree_iter,\n COL_FAVICON, pixbuf,\n COL_TITLE, title.c_str(),\n -1);\n if (pixbuf)\n g_object_unref(pixbuf);\n }\n }\n gtk_util::ShowDialog(GTK_WIDGET(dialog_));\n}\n\nvoid HungRendererDialogGtk::EndForTabContents(TabContents* contents) {\n DCHECK(contents);\n if (contents_ && contents_->GetRenderProcessHost() ==\n contents->GetRenderProcessHost()) {\n gtk_widget_hide(GTK_WIDGET(dialog_));\n \/\/ Since we're closing, we no longer need this TabContents.\n contents_ = NULL;\n }\n}\n\n\/\/ When the user clicks a button on the dialog or closes the dialog, this\n\/\/ callback is called.\nvoid HungRendererDialogGtk::OnDialogResponse(gint response_id) {\n DCHECK(g_instance == this);\n switch (response_id) {\n case kKillPagesButtonResponse:\n \/\/ Kill the process.\n if (contents_ && contents_->GetRenderProcessHost()) {\n base::KillProcess(contents_->GetRenderProcessHost()->GetHandle(),\n ResultCodes::HUNG, false);\n }\n break;\n\n case GTK_RESPONSE_OK:\n case GTK_RESPONSE_DELETE_EVENT:\n \/\/ Start waiting again for responsiveness.\n if (contents_ && contents_->render_view_host())\n contents_->render_view_host()->RestartHangMonitorTimeout();\n break;\n default:\n NOTREACHED();\n }\n\n gtk_widget_destroy(GTK_WIDGET(dialog_));\n delete g_instance;\n g_instance = NULL;\n}\n\n} \/\/ namespace\n\nnamespace hung_renderer_dialog {\n\nvoid ShowForTabContents(TabContents* contents) {\n if (!logging::DialogsAreSuppressed()) {\n if (!g_instance)\n g_instance = new HungRendererDialogGtk();\n g_instance->ShowForTabContents(contents);\n }\n}\n\n\/\/ static\nvoid HideForTabContents(TabContents* contents) {\n if (!logging::DialogsAreSuppressed() && g_instance)\n g_instance->EndForTabContents(contents);\n}\n\n} \/\/ namespace hung_renderer_dialog\n<|endoftext|>"} {"text":"<commit_before>\/***************************************************************************\n * Copyright (C) 2006-2008 by Rajko Albrecht *\n * ral@alwins-world.de *\n * *\n * This program is free software; you can redistribute it and\/or modify *\n * it under the terms of the GNU General Public License as published by *\n * the Free Software Foundation; either version 2 of the License, or *\n * (at your option) any later version. *\n * *\n * This program is distributed in the hope that it will be useful, *\n * but WITHOUT ANY WARRANTY; without even the implied warranty of *\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *\n * GNU General Public License for more details. *\n * *\n * You should have received a copy of the GNU General Public License *\n * along with this program; if not, write to the *\n * Free Software Foundation, Inc., *\n * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *\n ***************************************************************************\/\n\n#include \"svnqt\/stringarray.hpp\"\n#include \"svnqt\/pool.hpp\"\n\n#include <svn_types.h>\n\/\/ apr api\n#include <apr_pools.h>\n#include <apr_strings.h>\n\n\/*!\n \\fn svn::StringArray::StringArray()\n *\/\n svn::StringArray::StringArray()\n :m_content()\n{\n setNull(true);\n}\n\n\n\/*!\n \\fn svn::StringArray::StringArray(const QStringList&)\n *\/\nsvn::StringArray::StringArray(const QStringList&aList)\n :m_content(aList)\n{\n setNull(false);\n}\n\n\/*!\n \\fn svn::StringArray::StringArray(const apr_array_header_t * apr_targets)\n *\/\nsvn::StringArray::StringArray(const apr_array_header_t * apr_targets)\n :m_content()\n{\n int i;\n for (i = 0; i < apr_targets->nelts; i++)\n {\n const char ** target =\n &APR_ARRAY_IDX (apr_targets, i, const char *);\n\n m_content.push_back (QString::FROMUTF8(*target));\n }\n}\n\n\n\/*!\n \\fn svn::StringArray::size()const\n *\/\nsize_t svn::StringArray::size()const\n{\n if (isNull()) {\n return 0;\n }\n return m_content.size ();\n}\n\n\n\/*!\n \\fn svn::StringArray::operator[](size_t which)\n *\/\nconst QString& svn::StringArray::operator[](size_t which)\n{\n return m_content[which];\n}\n\n\n\/*!\n \\fn svn::StringArray::array (const Pool & pool) const\n *\/\napr_array_header_t * svn::StringArray::array (const Pool & pool) const\n{\n if (isNull()) {\n return 0;\n }\n QStringList::const_iterator it;\n\n apr_pool_t *apr_pool = pool.pool ();\n apr_array_header_t *apr_targets =\n apr_array_make (apr_pool,m_content.size(),sizeof (const char *));\n\n for (it = m_content.begin (); it != m_content.end (); it++)\n {\n QByteArray s = (*it).TOUTF8();\n char * t2 = apr_pstrndup (apr_pool,s,s.size());\n\n (*((const char **) apr_array_push (apr_targets))) = t2;\n }\n return apr_targets;\n}\n\nbool svn::StringArray::isNull()const\n{\n return m_isNull;\n}\n\nvoid svn::StringArray::setNull(bool _n)\n{\n if (_n) {\n m_content.clear();\n }\n m_isNull = _n;\n}\n<commit_msg>- fix a crash on svn::diff. svn_client_diff4 doesn't accept a 0 as *diff_options<commit_after>\/***************************************************************************\n * Copyright (C) 2006-2008 by Rajko Albrecht *\n * ral@alwins-world.de *\n * *\n * This program is free software; you can redistribute it and\/or modify *\n * it under the terms of the GNU General Public License as published by *\n * the Free Software Foundation; either version 2 of the License, or *\n * (at your option) any later version. *\n * *\n * This program is distributed in the hope that it will be useful, *\n * but WITHOUT ANY WARRANTY; without even the implied warranty of *\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *\n * GNU General Public License for more details. *\n * *\n * You should have received a copy of the GNU General Public License *\n * along with this program; if not, write to the *\n * Free Software Foundation, Inc., *\n * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *\n ***************************************************************************\/\n\n#include \"svnqt\/stringarray.hpp\"\n#include \"svnqt\/pool.hpp\"\n\n#include <svn_types.h>\n\/\/ apr api\n#include <apr_pools.h>\n#include <apr_strings.h>\n\n\/*!\n \\fn svn::StringArray::StringArray()\n *\/\n svn::StringArray::StringArray()\n :m_content()\n{\n setNull(true);\n}\n\n\n\/*!\n \\fn svn::StringArray::StringArray(const QStringList&)\n *\/\nsvn::StringArray::StringArray(const QStringList&aList)\n :m_content(aList)\n{\n setNull(false);\n}\n\n\/*!\n \\fn svn::StringArray::StringArray(const apr_array_header_t * apr_targets)\n *\/\nsvn::StringArray::StringArray(const apr_array_header_t * apr_targets)\n :m_content()\n{\n int i;\n for (i = 0; i < apr_targets->nelts; i++)\n {\n const char ** target =\n &APR_ARRAY_IDX (apr_targets, i, const char *);\n\n m_content.push_back (QString::FROMUTF8(*target));\n }\n}\n\n\n\/*!\n \\fn svn::StringArray::size()const\n *\/\nsize_t svn::StringArray::size()const\n{\n if (isNull()) {\n return 0;\n }\n return m_content.size ();\n}\n\n\n\/*!\n \\fn svn::StringArray::operator[](size_t which)\n *\/\nconst QString& svn::StringArray::operator[](size_t which)\n{\n return m_content[which];\n}\n\n\n\/*!\n \\fn svn::StringArray::array (const Pool & pool) const\n *\/\napr_array_header_t * svn::StringArray::array (const Pool & pool) const\n{\n apr_pool_t *apr_pool = pool.pool();\n apr_array_header_t *apr_targets;\n if (isNull()) {\n apr_targets = apr_array_make(apr_pool, 0, 0);\n } else {\n QStringList::const_iterator it;\n\n apr_targets =\n apr_array_make (apr_pool,m_content.size(),sizeof (const char *));\n\n for (it = m_content.begin (); it != m_content.end (); it++)\n {\n QByteArray s = (*it).TOUTF8();\n char * t2 = apr_pstrndup (apr_pool,s,s.size());\n\n (*((const char **) apr_array_push (apr_targets))) = t2;\n }\n }\n return apr_targets;\n}\n\nbool svn::StringArray::isNull()const\n{\n return m_isNull;\n}\n\nvoid svn::StringArray::setNull(bool _n)\n{\n if (_n) {\n m_content.clear();\n }\n m_isNull = _n;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 2013 Sacha Refshauge\n *\n *\/\n\/\/ Blackberry implementation of the framework.\n\n#include <pwd.h>\n#include <unistd.h>\n#include <string>\n\n#include <bps\/locale.h> \/\/ Get locale\n#include \"BlackberryMain.h\"\n#include \"Core\/Config.h\"\n#include \"base\/NKCodeFromBlackberry.h\"\n\n\/\/ Simple implementations of System functions\n\nstd::string System_GetProperty(SystemProperty prop) {\n\tswitch (prop) {\n\tcase SYSPROP_NAME: {\n\t\tstd::string name = \"Blackberry10:\";\n\t\treturn name + ((pixel_xres != pixel_yres) ? \"Touch\" : \"QWERTY\");\n\t}\n\tcase SYSPROP_LANGREGION: {\n\t\tchar *locale = 0;\n\t\tlocale_get_locale(&locale);\n\t\treturn std::string(locale);\n\t}\n\tdefault:\n\t\treturn \"\";\n\t}\n}\n\nvoid SystemToast(const char *text) {\n\tdialog_instance_t dialog = 0;\n\tdialog_create_toast(&dialog);\n\tdialog_set_toast_message_text(dialog, text);\n\tdialog_set_toast_position(dialog, DIALOG_POSITION_TOP_CENTER);\n\tdialog_show(dialog);\n}\n\nvoid ShowAd(int x, int y, bool center_x) {\n}\n\nvoid ShowKeyboard() {\n\tvirtualkeyboard_show();\n}\n\nvoid Vibrate(int length_ms) {\n\t\/\/ Vibration: intensity strength(1-100), duration ms(0-5000)\n\t\/\/ Intensity: LOW = 1, MEDIUM = 10, HIGH = 100\n\tswitch (length_ms) {\n\tcase -1: \/\/ Keyboard Tap\n\t\tvibration_request(VIBRATION_INTENSITY_LOW, 50);\n\t\tbreak;\n\tcase -2: \/\/ Virtual Key\n\t\tvibration_request(VIBRATION_INTENSITY_LOW, 25);\n\t\tbreak;\n\tcase -3: \/\/ Long Press\n\t\tvibration_request(VIBRATION_INTENSITY_LOW, 50);\n\t\tbreak;\n\tdefault:\n\t\tvibration_request(VIBRATION_INTENSITY_LOW, length_ms);\n\t\tbreak;\n\t}\n}\n\nvoid LaunchBrowser(const char *url)\n{\n\tchar* error;\n\tnavigator_invoke(url, &error);\n}\n\nvoid LaunchMarket(const char *url)\n{\n\tchar* error;\n\tnavigator_invoke(url, &error);\n}\n\nvoid LaunchEmail(const char *email_address)\n{\n\tchar* error;\n\tnavigator_invoke((std::string(\"mailto:\") + email_address).c_str(), &error);\n}\n\nInputState input_state;\n\nvoid BlackberryMain::handleInput(screen_event_t screen_event)\n{\n\tTouchInput input;\n\tKeyInput key;\n\tint val, buttons, pointerId;\n\tint pair[2];\n\tscreen_get_event_property_iv(screen_event, SCREEN_PROPERTY_TYPE, &val);\n\tscreen_get_event_property_iv(screen_event, SCREEN_PROPERTY_SOURCE_POSITION, pair);\n\tscreen_get_event_property_iv(screen_event, SCREEN_PROPERTY_TOUCH_ID, &pointerId);\n\n\tinput_state.mouse_valid = true;\n\tswitch(val)\n\t{\n\t\/\/ Touchscreen\n\tcase SCREEN_EVENT_MTOUCH_TOUCH:\n\tcase SCREEN_EVENT_MTOUCH_RELEASE: \t\/\/ Up, down\n\t\tinput_state.pointer_down[pointerId] = (val == SCREEN_EVENT_MTOUCH_TOUCH);\n\t\tinput_state.pointer_x[pointerId] = pair[0] * g_dpi_scale;\n\t\tinput_state.pointer_y[pointerId] = pair[1] * g_dpi_scale;\n\n\t\tinput.x = pair[0] * g_dpi_scale;\n\t\tinput.y = pair[1] * g_dpi_scale;\n\t\tinput.flags = (val == SCREEN_EVENT_MTOUCH_TOUCH) ? TOUCH_DOWN : TOUCH_UP;\n\t\tinput.id = pointerId;\n\t\tNativeTouch(input);\n\t\tbreak;\n\tcase SCREEN_EVENT_MTOUCH_MOVE:\n\t\tinput_state.pointer_x[pointerId] = pair[0] * g_dpi_scale;\n\t\tinput_state.pointer_y[pointerId] = pair[1] * g_dpi_scale;\n\n\t\tinput.x = pair[0] * g_dpi_scale;\n\t\tinput.y = pair[1] * g_dpi_scale;\n\t\tinput.flags = TOUCH_MOVE;\n\t\tinput.id = pointerId;\n\t\tNativeTouch(input);\n\t\tbreak;\n\t\/\/ Mouse, Simulator\n case SCREEN_EVENT_POINTER:\n\t\tscreen_get_event_property_iv(screen_event, SCREEN_PROPERTY_BUTTONS,\n\t\t\t&buttons);\n\t\tif (buttons == SCREEN_LEFT_MOUSE_BUTTON) { \t\t\t\/\/ Down\n\t\t\tinput_state.pointer_x[pointerId] = pair[0] * g_dpi_scale;\n\t\t\tinput_state.pointer_y[pointerId] = pair[1] * g_dpi_scale;\n\t\t\tinput_state.pointer_down[pointerId] = true;\n\n\t\t\tinput.x = pair[0] * g_dpi_scale;\n\t\t\tinput.y = pair[1] * g_dpi_scale;\n\t\t\tinput.flags = TOUCH_DOWN;\n\t\t\tinput.id = pointerId;\n\t\t\tNativeTouch(input);\n\t\t} else if (input_state.pointer_down[pointerId]) {\t\/\/ Up\n\t\t\tinput_state.pointer_x[pointerId] = pair[0] * g_dpi_scale;\n\t\t\tinput_state.pointer_y[pointerId] = pair[1] * g_dpi_scale;\n\t\t\tinput_state.pointer_down[pointerId] = false;\n\n\t\t\tinput.x = pair[0] * g_dpi_scale;\n\t\t\tinput.y = pair[1] * g_dpi_scale;\n\t\t\tinput.flags = TOUCH_UP;\n\t\t\tinput.id = pointerId;\n\t\t\tNativeTouch(input);\n\t\t}\n\t\tbreak;\n\t\/\/ Keyboard\n\tcase SCREEN_EVENT_KEYBOARD:\n\t\tint flags, value;\n\t\tscreen_get_event_property_iv(screen_event, SCREEN_PROPERTY_KEY_FLAGS, &flags);\n\t\tscreen_get_event_property_iv(screen_event, SCREEN_PROPERTY_KEY_SYM, &value);\n\t\tNativeKey(KeyInput(DEVICE_ID_KEYBOARD, KeyMapRawBlackberrytoNative.find(value)->second, (flags & KEY_DOWN) ? KEY_DOWN : KEY_UP));\n\t\tbreak;\n\t\/\/ Gamepad\n\tcase SCREEN_EVENT_GAMEPAD:\n\tcase SCREEN_EVENT_JOYSTICK:\n\t\tint analog0[3];\n\t\tscreen_get_event_property_iv(screen_event, SCREEN_PROPERTY_BUTTONS, &buttons);\n\t\tfor (int i = 0; i < 32; i++) {\n\t\t\tint mask = 1 << i;\n\t\t\tif ((old_buttons & mask) != (buttons & mask))\n\t\t\t\tNativeKey(KeyInput(DEVICE_ID_PAD_0, KeyMapPadBlackberrytoNative.find(mask)->second, (buttons & mask) ? KEY_DOWN : KEY_UP));\n\t\t}\n\t\tif (!screen_get_event_property_iv(screen_event, SCREEN_PROPERTY_ANALOG0, analog0)) {\n\t\t\tfor (int i = 0; i < 2; i++) {\n\t\t\t\tAxisInput axis;\n\t\t\t\taxis.axisId = JOYSTICK_AXIS_X + i;\n\t\t\t\t\/\/ 1.2 to try to approximate the PSP's clamped rectangular range.\n\t\t\t\taxis.value = 1.2 * analog0[i] \/ 128.0f;\n\t\t\t\tif (axis.value > 1.0f) axis.value = 1.0f;\n\t\t\t\tif (axis.value < -1.0f) axis.value = -1.0f;\n\t\t\t\taxis.deviceId = DEVICE_ID_PAD_0;\n\t\t\t\taxis.flags = 0;\n\t\t\t\tNativeAxis(axis);\n\t\t\t}\n\t\t}\n\t\told_buttons = buttons;\n\t\tbreak;\n\tcase SCREEN_EVENT_DISPLAY:\n\t\tscreen_display_t new_dpy = NULL;\n\t\tscreen_get_event_property_pv(screen_event, SCREEN_PROPERTY_DISPLAY, (void **)&new_dpy);\n\t\tfor (int i = 0; i < ndisplays; i++) {\n\t\t\tif (new_dpy != screen_dpy[i])\n\t\t\t\tcontinue;\n\t\t\tint active = 0;\n\t\t\tscreen_get_event_property_iv(screen_event, SCREEN_PROPERTY_ATTACHED, &active);\n\t\t\tif (active) {\n\t\t\t\tint size[2];\n\t\t\t\tscreen_get_display_property_iv(screen_dpy[i], SCREEN_PROPERTY_SIZE, size);\n\t\t\t\tif (size[0] == 0 || size[1] == 0)\n\t\t\t\t\tactive = 0;\n\t\t\t}\n\t\t\tif (active && !displays[i].attached)\n\t\t\t\trealiseDisplay(i);\n\t\t\telse if (!active && displays[i].attached && displays[i].realised)\n\t\t\t\tunrealiseDisplay(i);\n\t\t\tdisplays[i].attached = active;\n\t\t}\n\t\tbreak;\n\t}\n}\n\nvoid BlackberryMain::startMain(int argc, char *argv[]) {\n\t\/\/ Receive events from window manager\n\tscreen_create_context(&screen_cxt, 0);\n\t\/\/ Initialise Blackberry Platform Services\n\tbps_initialize();\n\t\/\/ TODO: Enable\/disable based on setting\n\tsensor_set_rate(SENSOR_TYPE_ACCELEROMETER, 25000);\n\tsensor_request_events(SENSOR_TYPE_ACCELEROMETER);\n\n\tnet::Init();\n\tstartDisplays();\n\tscreen_request_events(screen_cxt);\n\tnavigator_request_events(0);\n\tdialog_request_events(0);\n\tvibration_request_events(0);\n\tNativeInit(argc, (const char **)argv, \"\/accounts\/1000\/shared\/misc\/\", \"app\/native\/assets\/\", \"BADCOFFEE\");\n\tNativeInitGraphics();\n\taudio = new BlackberryAudio();\n\trunMain();\n}\n\nvoid BlackberryMain::runMain() {\n\tbool running = true;\n\twhile (running) {\n\t\tinput_state.mouse_valid = false;\n\t\tinput_state.accelerometer_valid = false;\n\t\twhile (true) {\n\t\t\t\/\/ Handle Blackberry events\n\t\t\tbps_event_t *event = NULL;\n\t\t\tbps_get_event(&event, 0);\n\t\t\tif (event == NULL)\n\t\t\t\tbreak; \/\/ Ran out of events\n\t\t\tint domain = bps_event_get_domain(event);\n\t\t\tif (domain == screen_get_domain()) {\n\t\t\t\thandleInput(screen_event_get_event(event));\n\t\t\t} else if (domain == navigator_get_domain()) {\n\t\t\t\tswitch(bps_event_get_code(event))\n\t\t\t\t{\n\t\t\t\tcase NAVIGATOR_BACK:\n\t\t\t\tcase NAVIGATOR_SWIPE_DOWN:\n\t\t\t\t\tNativeKey(KeyInput(DEVICE_ID_KEYBOARD, NKCODE_ESCAPE, KEY_DOWN));\n\t\t\t\t\tbreak;\n\t\t\t\tcase NAVIGATOR_EXIT:\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t} else if (domain == sensor_get_domain()) {\n\t\t\t\tif (SENSOR_ACCELEROMETER_READING == bps_event_get_code(event)) {\n\t\t\t\t\tfloat x, y, z;\n\t\t\t\t\tsensor_event_get_xyz(event, &x, &y, &z);\n\t\t\t\t\tif (pixel_xres == 1024 || pixel_xres == 720) \/\/ Q10 has this negative and reversed\n\t\t\t\t\t{\n\t\t\t\t\t\tinput_state.acc.x = -y;\n\t\t\t\t\t\tinput_state.acc.y = -x;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tinput_state.acc.x = x;\n\t\t\t\t\t\tinput_state.acc.y = y;\n\t\t\t\t\t}\n\t\t\t\t\tinput_state.acc.z = z;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tUpdateInputState(&input_state);\n\t\tNativeUpdate(input_state);\n\t\t\/\/ Work in Progress\n\t\t\/\/ Currently: Render to HDMI port (eg. 1080p) when in game. Render to device when in menu.\n\t\t\/\/ Idea: Render to all displays. Controls go to internal, game goes to external(s).\n\t\tif (globalUIState == UISTATE_INGAME && !emulating)\n\t\t{\n\t\t\temulating = true;\n\t\t\tswitchDisplay(screen_emu);\n\t\t\tif (g_Config.iShowFPSCounter == 4) {\n\t\t\t\tint options = SCREEN_DEBUG_STATISTICS;\n\t\t\t\tscreen_set_window_property_iv(screen_win[0], SCREEN_PROPERTY_DEBUG, &options);\n\t\t\t}\n\t\t} else if (globalUIState != UISTATE_INGAME && emulating) {\n\t\t\temulating = false;\n\t\t\tswitchDisplay(screen_ui);\n\t\t}\n\t\tNativeRender();\n\t\tEndInputState(&input_state);\n\t\ttime_update();\n\t\t\/\/ This handles VSync\n\t\tif (emulating)\n\t\t\teglSwapBuffers(egl_disp[screen_emu], egl_surf[screen_emu]);\n\t\telse\n\t\t\teglSwapBuffers(egl_disp[screen_ui], egl_surf[screen_ui]);\n\t}\n}\n\nvoid BlackberryMain::endMain() {\n\tscreen_stop_events(screen_cxt);\n\tbps_shutdown();\n\tNativeShutdownGraphics();\n\tdelete audio;\n\tNativeShutdown();\n\tkillDisplays();\n\tnet::Shutdown();\n\tscreen_destroy_context(screen_cxt);\n}\n\n\/\/ Entry Point\nint main(int argc, char *argv[]) {\n\tdelete new BlackberryMain(argc, argv);\n\treturn 0;\n}\n<commit_msg>Check for Blackberry invocation in native instead of in NativeApp. Much cleaner.<commit_after>\/*\n * Copyright (c) 2013 Sacha Refshauge\n *\n *\/\n\/\/ Blackberry implementation of the framework.\n\n#include <pwd.h>\n#include <unistd.h>\n#include <string>\n\n#include <bps\/locale.h> \/\/ Get locale\n#include <bps\/navigator_invoke.h> \/\/ Receive invocation messages\n#include \"BlackberryMain.h\"\n#include \"Core\/Config.h\"\n#include \"base\/NKCodeFromBlackberry.h\"\n\n#include \"UI\/MiscScreens.h\"\n\n\/\/ Simple implementations of System functions\n\nstd::string System_GetProperty(SystemProperty prop) {\n\tswitch (prop) {\n\tcase SYSPROP_NAME: {\n\t\tstd::string name = \"Blackberry10:\";\n\t\treturn name + ((pixel_xres != pixel_yres) ? \"Touch\" : \"QWERTY\");\n\t}\n\tcase SYSPROP_LANGREGION: {\n\t\tchar *locale = 0;\n\t\tlocale_get_locale(&locale);\n\t\treturn std::string(locale);\n\t}\n\tdefault:\n\t\treturn \"\";\n\t}\n}\n\nvoid SystemToast(const char *text) {\n\tdialog_instance_t dialog = 0;\n\tdialog_create_toast(&dialog);\n\tdialog_set_toast_message_text(dialog, text);\n\tdialog_set_toast_position(dialog, DIALOG_POSITION_TOP_CENTER);\n\tdialog_show(dialog);\n}\n\nvoid ShowAd(int x, int y, bool center_x) {\n}\n\nvoid ShowKeyboard() {\n\tvirtualkeyboard_show();\n}\n\nvoid Vibrate(int length_ms) {\n\t\/\/ Vibration: intensity strength(1-100), duration ms(0-5000)\n\t\/\/ Intensity: LOW = 1, MEDIUM = 10, HIGH = 100\n\tswitch (length_ms) {\n\tcase -1: \/\/ Keyboard Tap\n\t\tvibration_request(VIBRATION_INTENSITY_LOW, 50);\n\t\tbreak;\n\tcase -2: \/\/ Virtual Key\n\t\tvibration_request(VIBRATION_INTENSITY_LOW, 25);\n\t\tbreak;\n\tcase -3: \/\/ Long Press\n\t\tvibration_request(VIBRATION_INTENSITY_LOW, 50);\n\t\tbreak;\n\tdefault:\n\t\tvibration_request(VIBRATION_INTENSITY_LOW, length_ms);\n\t\tbreak;\n\t}\n}\n\nvoid LaunchBrowser(const char *url)\n{\n\tchar* error;\n\tnavigator_invoke(url, &error);\n}\n\nvoid LaunchMarket(const char *url)\n{\n\tchar* error;\n\tnavigator_invoke(url, &error);\n}\n\nvoid LaunchEmail(const char *email_address)\n{\n\tchar* error;\n\tnavigator_invoke((std::string(\"mailto:\") + email_address).c_str(), &error);\n}\n\nInputState input_state;\n\nvoid BlackberryMain::handleInput(screen_event_t screen_event)\n{\n\tTouchInput input;\n\tKeyInput key;\n\tint val, buttons, pointerId;\n\tint pair[2];\n\tscreen_get_event_property_iv(screen_event, SCREEN_PROPERTY_TYPE, &val);\n\tscreen_get_event_property_iv(screen_event, SCREEN_PROPERTY_SOURCE_POSITION, pair);\n\tscreen_get_event_property_iv(screen_event, SCREEN_PROPERTY_TOUCH_ID, &pointerId);\n\n\tinput_state.mouse_valid = true;\n\tswitch(val)\n\t{\n\t\/\/ Touchscreen\n\tcase SCREEN_EVENT_MTOUCH_TOUCH:\n\tcase SCREEN_EVENT_MTOUCH_RELEASE: \t\/\/ Up, down\n\t\tinput_state.pointer_down[pointerId] = (val == SCREEN_EVENT_MTOUCH_TOUCH);\n\t\tinput_state.pointer_x[pointerId] = pair[0] * g_dpi_scale;\n\t\tinput_state.pointer_y[pointerId] = pair[1] * g_dpi_scale;\n\n\t\tinput.x = pair[0] * g_dpi_scale;\n\t\tinput.y = pair[1] * g_dpi_scale;\n\t\tinput.flags = (val == SCREEN_EVENT_MTOUCH_TOUCH) ? TOUCH_DOWN : TOUCH_UP;\n\t\tinput.id = pointerId;\n\t\tNativeTouch(input);\n\t\tbreak;\n\tcase SCREEN_EVENT_MTOUCH_MOVE:\n\t\tinput_state.pointer_x[pointerId] = pair[0] * g_dpi_scale;\n\t\tinput_state.pointer_y[pointerId] = pair[1] * g_dpi_scale;\n\n\t\tinput.x = pair[0] * g_dpi_scale;\n\t\tinput.y = pair[1] * g_dpi_scale;\n\t\tinput.flags = TOUCH_MOVE;\n\t\tinput.id = pointerId;\n\t\tNativeTouch(input);\n\t\tbreak;\n\t\/\/ Mouse, Simulator\n case SCREEN_EVENT_POINTER:\n\t\tscreen_get_event_property_iv(screen_event, SCREEN_PROPERTY_BUTTONS,\n\t\t\t&buttons);\n\t\tif (buttons == SCREEN_LEFT_MOUSE_BUTTON) { \t\t\t\/\/ Down\n\t\t\tinput_state.pointer_x[pointerId] = pair[0] * g_dpi_scale;\n\t\t\tinput_state.pointer_y[pointerId] = pair[1] * g_dpi_scale;\n\t\t\tinput_state.pointer_down[pointerId] = true;\n\n\t\t\tinput.x = pair[0] * g_dpi_scale;\n\t\t\tinput.y = pair[1] * g_dpi_scale;\n\t\t\tinput.flags = TOUCH_DOWN;\n\t\t\tinput.id = pointerId;\n\t\t\tNativeTouch(input);\n\t\t} else if (input_state.pointer_down[pointerId]) {\t\/\/ Up\n\t\t\tinput_state.pointer_x[pointerId] = pair[0] * g_dpi_scale;\n\t\t\tinput_state.pointer_y[pointerId] = pair[1] * g_dpi_scale;\n\t\t\tinput_state.pointer_down[pointerId] = false;\n\n\t\t\tinput.x = pair[0] * g_dpi_scale;\n\t\t\tinput.y = pair[1] * g_dpi_scale;\n\t\t\tinput.flags = TOUCH_UP;\n\t\t\tinput.id = pointerId;\n\t\t\tNativeTouch(input);\n\t\t}\n\t\tbreak;\n\t\/\/ Keyboard\n\tcase SCREEN_EVENT_KEYBOARD:\n\t\tint flags, value;\n\t\tscreen_get_event_property_iv(screen_event, SCREEN_PROPERTY_KEY_FLAGS, &flags);\n\t\tscreen_get_event_property_iv(screen_event, SCREEN_PROPERTY_KEY_SYM, &value);\n\t\tNativeKey(KeyInput(DEVICE_ID_KEYBOARD, KeyMapRawBlackberrytoNative.find(value)->second, (flags & KEY_DOWN) ? KEY_DOWN : KEY_UP));\n\t\tbreak;\n\t\/\/ Gamepad\n\tcase SCREEN_EVENT_GAMEPAD:\n\tcase SCREEN_EVENT_JOYSTICK:\n\t\tint analog0[3];\n\t\tscreen_get_event_property_iv(screen_event, SCREEN_PROPERTY_BUTTONS, &buttons);\n\t\tfor (int i = 0; i < 32; i++) {\n\t\t\tint mask = 1 << i;\n\t\t\tif ((old_buttons & mask) != (buttons & mask))\n\t\t\t\tNativeKey(KeyInput(DEVICE_ID_PAD_0, KeyMapPadBlackberrytoNative.find(mask)->second, (buttons & mask) ? KEY_DOWN : KEY_UP));\n\t\t}\n\t\tif (!screen_get_event_property_iv(screen_event, SCREEN_PROPERTY_ANALOG0, analog0)) {\n\t\t\tfor (int i = 0; i < 2; i++) {\n\t\t\t\tAxisInput axis;\n\t\t\t\taxis.axisId = JOYSTICK_AXIS_X + i;\n\t\t\t\t\/\/ 1.2 to try to approximate the PSP's clamped rectangular range.\n\t\t\t\taxis.value = 1.2 * analog0[i] \/ 128.0f;\n\t\t\t\tif (axis.value > 1.0f) axis.value = 1.0f;\n\t\t\t\tif (axis.value < -1.0f) axis.value = -1.0f;\n\t\t\t\taxis.deviceId = DEVICE_ID_PAD_0;\n\t\t\t\taxis.flags = 0;\n\t\t\t\tNativeAxis(axis);\n\t\t\t}\n\t\t}\n\t\told_buttons = buttons;\n\t\tbreak;\n\tcase SCREEN_EVENT_DISPLAY:\n\t\tscreen_display_t new_dpy = NULL;\n\t\tscreen_get_event_property_pv(screen_event, SCREEN_PROPERTY_DISPLAY, (void **)&new_dpy);\n\t\tfor (int i = 0; i < ndisplays; i++) {\n\t\t\tif (new_dpy != screen_dpy[i])\n\t\t\t\tcontinue;\n\t\t\tint active = 0;\n\t\t\tscreen_get_event_property_iv(screen_event, SCREEN_PROPERTY_ATTACHED, &active);\n\t\t\tif (active) {\n\t\t\t\tint size[2];\n\t\t\t\tscreen_get_display_property_iv(screen_dpy[i], SCREEN_PROPERTY_SIZE, size);\n\t\t\t\tif (size[0] == 0 || size[1] == 0)\n\t\t\t\t\tactive = 0;\n\t\t\t}\n\t\t\tif (active && !displays[i].attached)\n\t\t\t\trealiseDisplay(i);\n\t\t\telse if (!active && displays[i].attached && displays[i].realised)\n\t\t\t\tunrealiseDisplay(i);\n\t\t\tdisplays[i].attached = active;\n\t\t}\n\t\tbreak;\n\t}\n}\n\nvoid BlackberryMain::startMain(int argc, char *argv[]) {\n\t\/\/ Receive events from window manager\n\tscreen_create_context(&screen_cxt, 0);\n\t\/\/ Initialise Blackberry Platform Services\n\tbps_initialize();\n\t\/\/ TODO: Enable\/disable based on setting\n\tsensor_set_rate(SENSOR_TYPE_ACCELEROMETER, 25000);\n\tsensor_request_events(SENSOR_TYPE_ACCELEROMETER);\n\n\tnet::Init();\n\tstartDisplays();\n\tscreen_request_events(screen_cxt);\n\tnavigator_request_events(0);\n\tdialog_request_events(0);\n\tvibration_request_events(0);\n\tNativeInit(argc, (const char **)argv, \"\/accounts\/1000\/shared\/misc\/\", \"app\/native\/assets\/\", \"BADCOFFEE\");\n\tNativeInitGraphics();\n\taudio = new BlackberryAudio();\n\trunMain();\n}\n\nvoid BlackberryMain::runMain() {\n\tbool running = true;\n\twhile (running) {\n\t\tinput_state.mouse_valid = false;\n\t\tinput_state.accelerometer_valid = false;\n\t\twhile (true) {\n\t\t\t\/\/ Handle Blackberry events\n\t\t\tbps_event_t *event = NULL;\n\t\t\tbps_get_event(&event, 0);\n\t\t\tif (event == NULL)\n\t\t\t\tbreak; \/\/ Ran out of events\n\t\t\tint domain = bps_event_get_domain(event);\n\t\t\tif (domain == screen_get_domain()) {\n\t\t\t\thandleInput(screen_event_get_event(event));\n\t\t\t} else if (domain == navigator_get_domain()) {\n\t\t\t\tswitch(bps_event_get_code(event))\n\t\t\t\t{\n\t\t\t\tcase NAVIGATOR_INVOKE_TARGET:\n\t\t\t\t\t{\n\t\t\t\t\t\tconst navigator_invoke_invocation_t *invoke = navigator_invoke_event_get_invocation(event);\n\t\t\t\t\t\tif(invoke) {\n\t\t\t\t\t\t\tboot_filename = navigator_invoke_invocation_get_uri(invoke)+7; \/\/ Remove file:\/\/\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tcase NAVIGATOR_BACK:\n\t\t\t\tcase NAVIGATOR_SWIPE_DOWN:\n\t\t\t\t\tNativeKey(KeyInput(DEVICE_ID_KEYBOARD, NKCODE_ESCAPE, KEY_DOWN));\n\t\t\t\t\tbreak;\n\t\t\t\tcase NAVIGATOR_EXIT:\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t} else if (domain == sensor_get_domain()) {\n\t\t\t\tif (SENSOR_ACCELEROMETER_READING == bps_event_get_code(event)) {\n\t\t\t\t\tfloat x, y, z;\n\t\t\t\t\tsensor_event_get_xyz(event, &x, &y, &z);\n\t\t\t\t\tif (pixel_xres == 1024 || pixel_xres == 720) \/\/ Q10 has this negative and reversed\n\t\t\t\t\t{\n\t\t\t\t\t\tinput_state.acc.x = -y;\n\t\t\t\t\t\tinput_state.acc.y = -x;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tinput_state.acc.x = x;\n\t\t\t\t\t\tinput_state.acc.y = y;\n\t\t\t\t\t}\n\t\t\t\t\tinput_state.acc.z = z;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tUpdateInputState(&input_state);\n\t\tNativeUpdate(input_state);\n\t\t\/\/ Work in Progress\n\t\t\/\/ Currently: Render to HDMI port (eg. 1080p) when in game. Render to device when in menu.\n\t\t\/\/ Idea: Render to all displays. Controls go to internal, game goes to external(s).\n\t\tif (globalUIState == UISTATE_INGAME && !emulating)\n\t\t{\n\t\t\temulating = true;\n\t\t\tswitchDisplay(screen_emu);\n\t\t\tif (g_Config.iShowFPSCounter == 4) {\n\t\t\t\tint options = SCREEN_DEBUG_STATISTICS;\n\t\t\t\tscreen_set_window_property_iv(screen_win[0], SCREEN_PROPERTY_DEBUG, &options);\n\t\t\t}\n\t\t} else if (globalUIState != UISTATE_INGAME && emulating) {\n\t\t\temulating = false;\n\t\t\tswitchDisplay(screen_ui);\n\t\t}\n\t\tNativeRender();\n\t\tEndInputState(&input_state);\n\t\ttime_update();\n\t\t\/\/ This handles VSync\n\t\tif (emulating)\n\t\t\teglSwapBuffers(egl_disp[screen_emu], egl_surf[screen_emu]);\n\t\telse\n\t\t\teglSwapBuffers(egl_disp[screen_ui], egl_surf[screen_ui]);\n\t}\n}\n\nvoid BlackberryMain::endMain() {\n\tscreen_stop_events(screen_cxt);\n\tbps_shutdown();\n\tNativeShutdownGraphics();\n\tdelete audio;\n\tNativeShutdown();\n\tkillDisplays();\n\tnet::Shutdown();\n\tscreen_destroy_context(screen_cxt);\n}\n\n\/\/ Entry Point\nint main(int argc, char *argv[]) {\n\tdelete new BlackberryMain(argc, argv);\n\treturn 0;\n}\n<|endoftext|>"} {"text":"<commit_before>#ifndef _INCLUDED_INPUT_HPP\n#define _INCLUDED_INPUT_HPP\n\n#include <cstddef>\n#include <cstdint>\n#include <fstream>\n#include <iostream>\n#include <string>\n#include <utility>\n#include <vector>\n\n#include <tudocomp\/util.h>\n\n#include <tudocomp\/io\/IOUtil.hpp>\n#include <tudocomp\/io\/ViewStream.hpp>\n\nnamespace tudocomp {\nnamespace io {\n\n struct InputView;\n struct InputStream;\n\n \/\/\/ Represents the input of an algorithm.\n \/\/\/\n \/\/\/ Can be used as either a istream or a memory buffer\n \/\/\/ with the as_stream or as_view methods.\n class Input {\n struct Variant {\n virtual std::unique_ptr<Variant> virtual_copy() = 0;\n virtual InputView as_view() = 0;\n virtual InputStream as_stream() = 0;\n virtual size_t size() = 0;\n };\n\n struct Memory: Variant {\n const uint8_t* ptr;\n size_t m_size;\n\n Memory(const uint8_t* ptr, size_t size): m_size(size) {\n this->ptr = ptr;\n }\n\n std::unique_ptr<Variant> virtual_copy() override {\n return std::make_unique<Memory>(ptr, m_size);\n }\n\n inline InputView as_view() override;\n inline InputStream as_stream() override;\n inline size_t size() override;\n };\n struct File: Variant {\n std::string path;\n size_t offset;\n\n File(std::string path, size_t offset) {\n this->path = path;\n this->offset = offset;\n }\n\n std::unique_ptr<Variant> virtual_copy() override {\n return std::make_unique<File>(path, offset);\n }\n\n inline InputView as_view() override;\n inline InputStream as_stream() override;\n inline size_t size() override;\n };\n\n friend class InputStream;\n friend class InputStreamInternal;\n friend class InputView;\n\n std::unique_ptr<Variant> m_data;\n\n public:\n struct Path { std::string path; };\n\n \/\/\/ An empty Input\n inline Input():\n m_data(std::make_unique<Memory>(nullptr, 0)) {}\n\n \/\/\/ Create an copy of the Input, with internal cursors\n \/\/\/ set to the current position\n inline Input(const Input& other):\n m_data(std::move(other.m_data->virtual_copy())) {}\n\n \/\/\/ Move constructor\n inline Input(Input&& other):\n m_data(std::move(other.m_data)) {}\n\n \/\/\/ An Input referring to the contents of a file\n Input(Input::Path&& path):\n m_data(std::make_unique<File>(std::move(path.path), 0)) {}\n\n \/\/\/ An Input referring to the contents of an vector\n Input(const std::vector<uint8_t>& buf):\n m_data(std::make_unique<Memory>(&buf[0], buf.size())) {}\n\n \/\/\/ An Input referring to the contents of an string\n Input(const string_ref buf):\n m_data(std::make_unique<Memory>(\n (const uint8_t*) &buf[0], buf.size())) {}\n\n Input& operator=(Input&& other) {\n m_data = std::move(other.m_data);\n return *this;\n }\n\n \/\/\/ DEPRECATED\n static Input from_path(std::string path) {\n return Input(Path { path });\n }\n\n \/\/\/ DEPRECATED\n static Input from_memory(const std::vector<uint8_t>& buf) {\n return Input(buf);\n }\n\n \/\/\/ DEPRECATED\n static Input from_memory(const string_ref buf) {\n return Input(buf);\n }\n\n inline InputView as_view();\n inline InputStream as_stream();\n\n inline size_t size() {\n return m_data->size();\n }\n };\n\n class InputViewInternal {\n struct Variant {\n virtual string_ref view() = 0;\n };\n\n struct Memory: Variant {\n const uint8_t* ptr;\n size_t size;\n\n Memory(const uint8_t* ptr, size_t size) {\n this->ptr = ptr;\n this->size = size;\n }\n\n string_ref view() override {\n return string_ref {\n (char*) ptr,\n size\n };\n }\n };\n struct File: Variant {\n std::vector<uint8_t> buffer;\n\n File(std::vector<uint8_t>&& buffer_):\n buffer(std::move(buffer_)) {}\n\n string_ref view() override {\n return string_ref {\n (char*) buffer.data(),\n buffer.size()\n };\n }\n };\n\n std::unique_ptr<Variant> m_variant;\n\n friend class InputView;\n friend class Input;\n\n InputViewInternal(const InputViewInternal& other) = delete;\n InputViewInternal() = delete;\n\n InputViewInternal(InputViewInternal::Memory&& mem):\n m_variant(std::make_unique<Memory>(std::move(mem))) {}\n InputViewInternal(InputViewInternal::File&& s):\n m_variant(std::make_unique<File>(std::move(s))) {}\n InputViewInternal(InputViewInternal&& s):\n m_variant(std::move(s.m_variant)) {}\n };\n\n class InputView: InputViewInternal, public View {\n friend class Input;\n\n InputView(InputViewInternal&& mem):\n InputViewInternal(std::move(mem)),\n View(m_variant->view()) {}\n public:\n InputView(InputView&& mem):\n InputViewInternal(std::move(mem)),\n View(std::move(mem)) {}\n\n InputView(const InputView& other) = delete;\n InputView() = delete;\n };\n\n inline InputView Input::Memory::as_view() {\n Input::Memory mem2 = *this;\n\n \/\/ advance view into memory by its whole length\n ptr += m_size;\n m_size = 0;\n\n return InputView {\n InputView::Memory { mem2.ptr, mem2.m_size }\n };\n }\n\n inline InputView Input::File::as_view() {\n \/\/ read file into buffer starting at current offset\n auto buf = read_file_to_stl_byte_container<\n std::vector<uint8_t>>(path, offset);\n\n \/\/ We read the whole file, so skip it on next read.\n offset += buf.size();\n\n return InputView {\n InputView::File {\n std::move(buf)\n }\n };\n }\n\n inline InputView Input::as_view() {\n return m_data->as_view();\n }\n\n class InputStreamInternal {\n class Variant {\n public:\n virtual std::istream& stream() = 0;\n virtual ~Variant() {}\n };\n\n class Memory: public InputStreamInternal::Variant {\n ViewStream m_stream;\n\n Input::Memory* m_offset_back_ref;\n size_t m_start_pos;\n\n bool m_is_empty = false;\n\n friend class InputStreamInternal;\n\n public:\n Memory(const Memory& other) = delete;\n Memory() = delete;\n\n Memory(Memory&& other):\n m_stream(std::move(other.m_stream)),\n m_offset_back_ref(other.m_offset_back_ref),\n m_start_pos(other.m_start_pos) {\n other.m_is_empty = true;\n }\n\n Memory(ViewStream&& stream, Input::Memory* offset_back_ref):\n m_stream(std::move(stream))\n {\n m_offset_back_ref = offset_back_ref;\n m_start_pos = m_stream.stream().tellg();\n }\n virtual ~Memory() {\n if (!m_is_empty) {\n size_t len = size_t(m_stream.stream().tellg()) - m_start_pos;\n m_offset_back_ref->ptr += len;\n m_offset_back_ref->m_size -= len;\n }\n }\n std::istream& stream() override {\n return m_stream.stream();\n }\n };\n class File: public InputStreamInternal::Variant {\n std::string m_path;\n std::unique_ptr<std::ifstream> m_stream;\n\n Input::File* m_offset_back_ref;\n size_t m_start_pos;\n\n friend class InputStreamInternal;\n public:\n File(const File& other) = delete;\n File() = delete;\n\n File(std::string&& path,\n Input::File* offset_back_ref,\n size_t offset)\n {\n m_path = path;\n m_stream = std::make_unique<std::ifstream>(\n m_path, std::ios::in | std::ios::binary);\n m_stream->seekg(offset, std::ios::beg);\n m_start_pos = m_stream->tellg();\n m_offset_back_ref = offset_back_ref;\n }\n\n File(File&& other) {\n m_stream = std::move(other.m_stream);\n m_offset_back_ref = other.m_offset_back_ref;\n m_path = other.m_path;\n m_start_pos = other.m_start_pos;\n }\n\n virtual ~File() {\n if (m_stream != nullptr) {\n auto len = size_t(m_stream->tellg()) - m_start_pos;\n m_offset_back_ref->offset += len;\n }\n }\n\n std::istream& stream() override {\n return *m_stream;\n }\n };\n\n std::unique_ptr<InputStreamInternal::Variant> m_variant;\n\n friend class InputStream;\n friend class Input;\n\n InputStreamInternal(const InputStreamInternal& other) = delete;\n InputStreamInternal() = delete;\n\n InputStreamInternal(InputStreamInternal::Memory&& mem):\n m_variant(std::move(std::make_unique<InputStreamInternal::Memory>(std::move(mem)))) {}\n InputStreamInternal(InputStreamInternal::File&& f):\n m_variant(std::move(std::make_unique<InputStreamInternal::File>(std::move(f)))) {}\n InputStreamInternal(InputStreamInternal&& s):\n m_variant(std::move(s.m_variant)) {}\n\n };\n\n class InputStream: InputStreamInternal, public std::istream {\n friend class Input;\n\n InputStream(InputStreamInternal&& mem):\n InputStreamInternal(std::move(mem)),\n std::istream(m_variant->stream().rdbuf()) {}\n public:\n InputStream(InputStream&& mem):\n InputStreamInternal(std::move(mem)),\n std::istream(mem.rdbuf()) {}\n\n InputStream(const InputStream& other) = delete;\n InputStream() = delete;\n };\n\n inline InputStream Input::Memory::as_stream() {\n return InputStream {\n InputStream::Memory {\n ViewStream {\n (char*)ptr,\n m_size\n },\n this\n }\n };\n }\n\n inline InputStream Input::File::as_stream() {\n return InputStream {\n InputStream::File {\n std::string(path),\n this,\n offset,\n }\n };\n }\n\n inline InputStream Input::as_stream() {\n return m_data->as_stream();\n }\n\n inline size_t Input::Memory::size() {\n return m_size;\n }\n\n inline size_t Input::File::size() {\n return read_file_size(path) - offset;\n }\n\n}}\n\n#endif\n\n<commit_msg>Doxygen for Input.hpp #17468<commit_after>#ifndef _INCLUDED_INPUT_HPP\n#define _INCLUDED_INPUT_HPP\n\n#include <cstddef>\n#include <cstdint>\n#include <fstream>\n#include <iostream>\n#include <string>\n#include <utility>\n#include <vector>\n\n#include <tudocomp\/util.h>\n\n#include <tudocomp\/io\/IOUtil.hpp>\n#include <tudocomp\/io\/ViewStream.hpp>\n\nnamespace tudocomp {\nnamespace io {\n\n struct InputView;\n struct InputStream;\n\n \/\/\/ \\brief An abstraction layer for algorithm input.\n \/\/\/\n \/\/\/ This class serves as a generic abstraction over different sources of\n \/\/\/ input: memory, files or streams. It provides two ways of handling the\n \/\/\/ input: \\e streams or \\e views. While a view allows random access on all\n \/\/\/ of the input, it requires the entire input to be stored in memory.\n \/\/\/ Streaming, on the other hand, is used for character-wise reading\n \/\/\/ without the ability to rewind (online).\n class Input {\n struct Variant {\n virtual std::unique_ptr<Variant> virtual_copy() = 0;\n virtual InputView as_view() = 0;\n virtual InputStream as_stream() = 0;\n virtual size_t size() = 0;\n };\n\n struct Memory: Variant {\n const uint8_t* ptr;\n size_t m_size;\n\n Memory(const uint8_t* ptr, size_t size): m_size(size) {\n this->ptr = ptr;\n }\n\n std::unique_ptr<Variant> virtual_copy() override {\n return std::make_unique<Memory>(ptr, m_size);\n }\n\n inline InputView as_view() override;\n inline InputStream as_stream() override;\n inline size_t size() override;\n };\n struct File: Variant {\n std::string path;\n size_t offset;\n\n File(std::string path, size_t offset) {\n this->path = path;\n this->offset = offset;\n }\n\n std::unique_ptr<Variant> virtual_copy() override {\n return std::make_unique<File>(path, offset);\n }\n\n inline InputView as_view() override;\n inline InputStream as_stream() override;\n inline size_t size() override;\n };\n\n friend class InputStream;\n friend class InputStreamInternal;\n friend class InputView;\n\n std::unique_ptr<Variant> m_data;\n\n public:\n \/\/\/ \\brief Represents a file path.\n \/\/\/\n \/\/\/ Pass a Path instance to the respective constructor in order to\n \/\/\/ create an input from the file pointed to by the path.\n struct Path {\n \/\/\/ The path string.\n std::string path;\n };\n\n \/\/\/ \\brief Constructs an empty input.\n inline Input():\n m_data(std::make_unique<Memory>(nullptr, 0)) {}\n\n \/\/\/ \\brief Constructs an input from another input, retaining its\n \/\/\/ internal state (\"cursor\").\n \/\/\/\n \/\/\/ Use this in combination with streams to store a rewind point.\n \/\/\/\n \/\/\/ \\param other The input to copy.\n inline Input(const Input& other):\n m_data(std::move(other.m_data->virtual_copy())) {}\n\n \/\/\/ \\brief Move constructor.\n inline Input(Input&& other):\n m_data(std::move(other.m_data)) {}\n\n \/\/\/ \\brief Constructs a file input reading from the file at the given\n \/\/\/ path.\n \/\/\/\n \/\/\/ \\param path The path to the input file.\n Input(Input::Path&& path):\n m_data(std::make_unique<File>(std::move(path.path), 0)) {}\n\n \/\/\/ \\brief Constructs an input reading from the specified byte buffer.\n \/\/\/\n \/\/\/ \\param buf The input byte buffer.\n Input(const std::vector<uint8_t>& buf):\n m_data(std::make_unique<Memory>(&buf[0], buf.size())) {}\n\n \/\/\/ \\brief Constructs an input reading from a string in memory.\n \/\/\/\n \/\/\/ \\param buf The input string.\n Input(const string_ref buf):\n m_data(std::make_unique<Memory>(\n (const uint8_t*) &buf[0], buf.size())) {}\n\n \/\/\/ \\brief Move operator.\n Input& operator=(Input&& other) {\n m_data = std::move(other.m_data);\n return *this;\n }\n\n \/\/\/ \\deprecated Use the respective constructor instead.\n \/\/\/ \\brief Constructs a file input reading from the file at the given\n \/\/\/ path.\n \/\/\/\n \/\/\/ \\param path The path to the input file.\n static Input from_path(std::string path) {\n return Input(Path { path });\n }\n\n \/\/\/ \\deprecated Use the respective constructor instead.\n \/\/\/ \\brief Constructs a file input reading from a byte buffer.\n \/\/\/\n \/\/\/ \\param buf The input byte buffer.\n static Input from_memory(const std::vector<uint8_t>& buf) {\n return Input(buf);\n }\n\n \/\/\/ \\deprecated Use the respective constructor instead.\n \/\/\/ \\brief Constructs a file input reading from a string in memory.\n \/\/\/\n \/\/\/ \\param buf The input string.\n static Input from_memory(const string_ref buf) {\n return Input(buf);\n }\n\n \/\/\/ \\brief Provides a view on the input that allows for random access.\n \/\/\/\n \/\/\/ This will store the entire input in memory, ie a file or stream\n \/\/\/ will be fully read in order to provide the view.\n \/\/\/\n \/\/\/ \\return A random access view on the input.\n inline InputView as_view();\n\n \/\/\/ \\brief Creates a stream that allows for character-wise reading of\n \/\/\/ the input.\n \/\/\/\n \/\/\/ \\return A character stream for the input.\n inline InputStream as_stream();\n\n \/\/\/ \\brief Yields the total amount of characters in the input.\n \/\/\/\n \/\/\/ \\return The total amount of characters in the input.\n inline size_t size() {\n return m_data->size();\n }\n };\n\n \/\/\/ \\cond INTERNAL\n class InputViewInternal {\n struct Variant {\n virtual string_ref view() = 0;\n };\n\n struct Memory: Variant {\n const uint8_t* ptr;\n size_t size;\n\n Memory(const uint8_t* ptr, size_t size) {\n this->ptr = ptr;\n this->size = size;\n }\n\n string_ref view() override {\n return string_ref {\n (char*) ptr,\n size\n };\n }\n };\n struct File: Variant {\n std::vector<uint8_t> buffer;\n\n File(std::vector<uint8_t>&& buffer_):\n buffer(std::move(buffer_)) {}\n\n string_ref view() override {\n return string_ref {\n (char*) buffer.data(),\n buffer.size()\n };\n }\n };\n\n std::unique_ptr<Variant> m_variant;\n\n friend class InputView;\n friend class Input;\n\n InputViewInternal(const InputViewInternal& other) = delete;\n InputViewInternal() = delete;\n\n InputViewInternal(InputViewInternal::Memory&& mem):\n m_variant(std::make_unique<Memory>(std::move(mem))) {}\n InputViewInternal(InputViewInternal::File&& s):\n m_variant(std::make_unique<File>(std::move(s))) {}\n InputViewInternal(InputViewInternal&& s):\n m_variant(std::move(s.m_variant)) {}\n };\n \/\/\/ \\endcond\n\n\n \/\/\/ \\brief Provides a view on the input that allows for random access.\n \/\/\/\n \/\/\/ \\sa View.\n class InputView: InputViewInternal, public View {\n friend class Input;\n\n InputView(InputViewInternal&& mem):\n InputViewInternal(std::move(mem)),\n View(m_variant->view()) {}\n public:\n \/\/\/ Move constructor.\n InputView(InputView&& mem):\n InputViewInternal(std::move(mem)),\n View(std::move(mem)) {}\n\n \/\/\/ Copy constructor (deleted).\n InputView(const InputView& other) = delete;\n\n \/\/\/ Default constructor (deleted).\n InputView() = delete;\n };\n\n inline InputView Input::Memory::as_view() {\n Input::Memory mem2 = *this;\n\n \/\/ advance view into memory by its whole length\n ptr += m_size;\n m_size = 0;\n\n return InputView {\n InputView::Memory { mem2.ptr, mem2.m_size }\n };\n }\n\n inline InputView Input::File::as_view() {\n \/\/ read file into buffer starting at current offset\n auto buf = read_file_to_stl_byte_container<\n std::vector<uint8_t>>(path, offset);\n\n \/\/ We read the whole file, so skip it on next read.\n offset += buf.size();\n\n return InputView {\n InputView::File {\n std::move(buf)\n }\n };\n }\n\n inline InputView Input::as_view() {\n return m_data->as_view();\n }\n\n \/\/\/ \\cond INTERNAL\n class InputStreamInternal {\n class Variant {\n public:\n virtual std::istream& stream() = 0;\n virtual ~Variant() {}\n };\n\n class Memory: public InputStreamInternal::Variant {\n ViewStream m_stream;\n\n Input::Memory* m_offset_back_ref;\n size_t m_start_pos;\n\n bool m_is_empty = false;\n\n friend class InputStreamInternal;\n\n public:\n Memory(const Memory& other) = delete;\n Memory() = delete;\n\n Memory(Memory&& other):\n m_stream(std::move(other.m_stream)),\n m_offset_back_ref(other.m_offset_back_ref),\n m_start_pos(other.m_start_pos) {\n other.m_is_empty = true;\n }\n\n Memory(ViewStream&& stream, Input::Memory* offset_back_ref):\n m_stream(std::move(stream))\n {\n m_offset_back_ref = offset_back_ref;\n m_start_pos = m_stream.stream().tellg();\n }\n virtual ~Memory() {\n if (!m_is_empty) {\n size_t len = size_t(m_stream.stream().tellg()) - m_start_pos;\n m_offset_back_ref->ptr += len;\n m_offset_back_ref->m_size -= len;\n }\n }\n std::istream& stream() override {\n return m_stream.stream();\n }\n };\n class File: public InputStreamInternal::Variant {\n std::string m_path;\n std::unique_ptr<std::ifstream> m_stream;\n\n Input::File* m_offset_back_ref;\n size_t m_start_pos;\n\n friend class InputStreamInternal;\n public:\n File(const File& other) = delete;\n File() = delete;\n\n File(std::string&& path,\n Input::File* offset_back_ref,\n size_t offset)\n {\n m_path = path;\n m_stream = std::make_unique<std::ifstream>(\n m_path, std::ios::in | std::ios::binary);\n m_stream->seekg(offset, std::ios::beg);\n m_start_pos = m_stream->tellg();\n m_offset_back_ref = offset_back_ref;\n }\n\n File(File&& other) {\n m_stream = std::move(other.m_stream);\n m_offset_back_ref = other.m_offset_back_ref;\n m_path = other.m_path;\n m_start_pos = other.m_start_pos;\n }\n\n virtual ~File() {\n if (m_stream != nullptr) {\n auto len = size_t(m_stream->tellg()) - m_start_pos;\n m_offset_back_ref->offset += len;\n }\n }\n\n std::istream& stream() override {\n return *m_stream;\n }\n };\n\n std::unique_ptr<InputStreamInternal::Variant> m_variant;\n\n friend class InputStream;\n friend class Input;\n\n InputStreamInternal(const InputStreamInternal& other) = delete;\n InputStreamInternal() = delete;\n\n InputStreamInternal(InputStreamInternal::Memory&& mem):\n m_variant(std::move(std::make_unique<InputStreamInternal::Memory>(std::move(mem)))) {}\n InputStreamInternal(InputStreamInternal::File&& f):\n m_variant(std::move(std::make_unique<InputStreamInternal::File>(std::move(f)))) {}\n InputStreamInternal(InputStreamInternal&& s):\n m_variant(std::move(s.m_variant)) {}\n\n };\n \/\/\/ \\endcond\n\n \/\/\/ \\brief Provides a character stream of the underlying input.\n class InputStream: InputStreamInternal, public std::istream {\n friend class Input;\n\n InputStream(InputStreamInternal&& mem):\n InputStreamInternal(std::move(mem)),\n std::istream(m_variant->stream().rdbuf()) {}\n public:\n \/\/\/ Move constructor.\n InputStream(InputStream&& mem):\n InputStreamInternal(std::move(mem)),\n std::istream(mem.rdbuf()) {}\n\n \/\/\/ Copy constructor (deleted).\n InputStream(const InputStream& other) = delete;\n\n \/\/\/ Default constructor (deleted).\n InputStream() = delete;\n };\n\n inline InputStream Input::Memory::as_stream() {\n return InputStream {\n InputStream::Memory {\n ViewStream {\n (char*)ptr,\n m_size\n },\n this\n }\n };\n }\n\n inline InputStream Input::File::as_stream() {\n return InputStream {\n InputStream::File {\n std::string(path),\n this,\n offset,\n }\n };\n }\n\n inline InputStream Input::as_stream() {\n return m_data->as_stream();\n }\n\n inline size_t Input::Memory::size() {\n return m_size;\n }\n\n inline size_t Input::File::size() {\n return read_file_size(path) - offset;\n }\n\n}}\n\n#endif\n\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n\n#include <SFML\/Graphics.hpp>\n#include \"game.h\"\n\n\n\nGame::Game():\n playing(true),\n screen(sf::VideoMode(800, 600), \"Dune 2 - The Maker\", sf::Style::Close),\n map(nullptr)\n \/\/map_camera(nullptr),\n \/\/unitRepository(nullptr)\n{\n screen.setFramerateLimit(IDEAL_FPS);\n screen.setMouseCursorVisible(false);\n\n if (!init()){\n std::cerr << \"Failed to initialized game.\";\n playing = false;\n }\n}\n\nint Game::execute() {\n\n while(playing) {\n sf::Event event;\n while(screen.pollEvent(event)) {\n onEvent(event);\n }\n\n updateState();\n render();\n }\n\n return 0;\n}\n\nbool Game::init() {\n if (!terrain.loadFromFile(\"graphics\/terrain.png\")) {\n std::cout << \"Failed to read graphics\/terrain.png data\" << std::endl;\n return false;\n }\n\n sf::Image temp;\n if (!temp.loadFromFile(\"graphics\/shroud_edges.bmp\")) {\n std::cout << \"Failed to read graphics\/shroud_edges.bmp data\" << std::endl;\n return false;\n }\n\n temp.createMaskFromColor(sf::Color(255, 0, 255));\n shroud_edges.loadFromImage(temp);\n\n map.reset(new Map(terrain, shroud_edges));\n map->load(\"maps\/4PL_Mountains.ini\");\n\n camera.reset({0,0,800,600});\n screen.setView(camera);\n\n \/\/init a trike\n sf::Image trikeImage;\n trikeImage.loadFromFile(\"graphics\/Unit_Trike.bmp\");\n trikeImage.createMaskFromColor(sf::Color(0,0,0));\n sf::Texture* trikeTexture = new sf::Texture; \/\/yes we are leaking! Player should own this\n trikeTexture->loadFromImage(trikeImage);\n\n sf::Image trikeShadowImage;\n trikeShadowImage.loadFromFile(\"graphics\/Unit_Trike_s.bmp\");\n trikeShadowImage.createMaskFromColor(sf::Color(255,0,255));\n sf::Texture* trikeShadowTexture = new sf::Texture; \/\/yes we are leaking! Player should own this\n trikeShadowTexture->loadFromImage(trikeShadowImage);\n\n sf::Image selectedImage;\n selectedImage.loadFromFile(\"graphics\/selected.bmp\");\n selectedImage.createMaskFromColor(sf::Color(255, 0, 255));\n sf::Texture* selectedTexture = new sf::Texture; \/\/more leaks!\n selectedTexture->loadFromImage(selectedImage);\n units.emplace_back(new Unit(*trikeTexture, *trikeShadowTexture, *selectedTexture, 256, 256, 0));\n\n \/\/remove shroud here\n map->removeShroud(static_cast<sf::Vector2i>(units[0]->getPosition()), 10);\n\n \/\/shroud_edges_shadow = Surface::load(\"graphics\/shroud_edges_shadow.bmp\");\n\n \/\/if (shroud_edges_shadow == NULL) {\n \/\/cout << \"Failed to read graphics\/shroud_edges_shadow.bmp data\" << endl;\n \/\/return false;\n \/\/}\n\n \/\/mouse.init(screen);\n\n \/\/map_camera.reset(new MapCamera(0, 0, screen, &map));\n \/\/map.load(\"maps\/4PL_Mountains.ini\");\n \/\/unitRepository.reset(new UnitRepository(&map));\n\n \/\/\/\/init two players\n \/\/int idCount = 0;\n \/\/players.emplace_back(House::Sardaukar, idCount++);\n \/\/players.emplace_back(House::Harkonnen, idCount++);\n\n \/\/units.emplace_back(unitRepository->create(UNIT_FRIGATE, House::Sardaukar, 3, 3, 10, SUBCELL_CENTER, players[0]));\n \/\/units.emplace_back(unitRepository->create(UNIT_TRIKE, House::Sardaukar, 8, 8, 3, SUBCELL_CENTER, players[0]));\n\n \/\/\/\/ soldiers\n \/\/units.emplace_back(unitRepository->create(UNIT_SOLDIER, House::Sardaukar, 14, 14, 3, SUBCELL_CENTER, players[0]));\n \/\/units.emplace_back(unitRepository->create(UNIT_SOLDIER, House::Sardaukar, 14, 14, 3, SUBCELL_UPLEFT, players[0]));\n \/\/units.emplace_back(unitRepository->create(UNIT_SOLDIER, House::Sardaukar, 14, 14, 3, SUBCELL_UPRIGHT, players[0]));\n \/\/units.emplace_back(unitRepository->create(UNIT_SOLDIER, House::Sardaukar, 14, 14, 3, SUBCELL_DOWNLEFT, players[0]));\n \/\/units.emplace_back(unitRepository->create(UNIT_SOLDIER, House::Sardaukar, 14, 14, 3, SUBCELL_DOWNRIGHT, players[0]));\n\n \/\/units.emplace_back(unitRepository->create(UNIT_SOLDIER, House::Harkonnen, 18, 8, 3, SUBCELL_CENTER, players[1]));\n \/\/units.emplace_back(unitRepository->create(UNIT_SOLDIER, House::Harkonnen, 18, 8, 3, SUBCELL_UPLEFT, players[1]));\n \/\/units.emplace_back(unitRepository->create(UNIT_SOLDIER, House::Harkonnen, 18, 8, 3, SUBCELL_UPRIGHT, players[1]));\n \/\/units.emplace_back(unitRepository->create(UNIT_SOLDIER, House::Harkonnen, 18, 8, 3, SUBCELL_DOWNLEFT, players[1]));\n \/\/units.emplace_back(unitRepository->create(UNIT_SOLDIER, House::Harkonnen, 18, 8, 3, SUBCELL_DOWNRIGHT, players[1]));\n\n return true;\n}\n\nvoid Game::onEvent(sf::Event event) {\n\n switch (event.type){\n case sf::Event::Closed:\n playing = false; break;\n case sf::Event::KeyPressed:\n switch (event.key.code) {\n case sf::Keyboard::Q:\n playing = false; break;\n default:\n break;\n }\n break;\n case sf::Event::MouseButtonPressed:\n switch (event.mouseButton.button){\n case sf::Mouse::Left:{\n sf::Vector2f toSet = screen.mapPixelToCoords(sf::Vector2i(event.mouseButton.x, event.mouseButton.y));\n box.setTopLeft(toSet);\n break;\n }\n default:\n break;\n }\n break;\n case sf::Event::MouseButtonReleased:\n switch (event.mouseButton.button){\n case sf::Mouse::Left:\n for (auto& unit : units){\n if (box.intersects(unit->getBounds())){\n unit->select();\n mouse.setType(Mouse::Type::Move); \/\/at least one unit selected...\n } \n }\n for (auto& unit : units){\n if (unit->is_selected()) unit->order_move(screen.mapPixelToCoords(static_cast<sf::Vector2i>(mouse.getPosition())));\n }\n box.clear();\n break;\n case sf::Mouse::Right:\n \/\/deselect all units\n for (auto& unit : units){\n unit->unselect();\n mouse.setType(Mouse::Type::Default);\n }\n default:\n break;\n }\n default:\n break;\n }\n\n \/\/mouse.onEvent(event);\n \/\/keyboard.onEvent(event);\n\n \/\/map_camera->onEvent(event);\n\n \/\/if (event->type == SDL_USEREVENT) {\n \/\/if (event->user.code == D2TM_SELECT) {\n \/\/std::unique_ptr<D2TMSelectStruct> s(static_cast<D2TMSelectStruct*>(event->user.data1));\n\n \/\/Point p = map_camera->toWorldCoordinates(s->screen_position);\n\n \/\/if (mouse.is_pointing()) {\n \/\/Unit* selected_unit = NULL;\n \/\/for (auto& unit : units){\n \/\/if (unit->is_point_within(p)){\n \/\/selected_unit = unit.get();\n \/\/break;\n \/\/}\n\n \/\/}\n \/\/if (selected_unit != NULL) {\n \/\/deselectAllUnits();\n \/\/selected_unit->select();\n \/\/mouse.state_order_move();\n \/\/}\n \/\/}\n \/\/} else if (event->user.code == D2TM_DESELECT) {\n \/\/mouse.state_pointing();\n \/\/deselectAllUnits();\n \/\/} else if (event->user.code == D2TM_BOX_SELECT) {\n \/\/std::unique_ptr<D2TMBoxSelectStruct> s(static_cast<D2TMBoxSelectStruct*>(event->user.data1));\n\n \/\/Rectangle rectangle = map_camera->toWorldCoordinates(s->rectangle);\n\n \/\/if (mouse.is_pointing()) {\n \/\/mouse.state_pointing();\n\n \/\/deselectAllUnits();\n \/\/for (auto& unit : units){\n \/\/if (unit->is_within(rectangle)){\n \/\/unit->select();\n \/\/mouse.state_order_move();\n \/\/}\n \/\/}\n \/\/}\n \/\/} else if (event->user.code == D2TM_MOVE_UNIT) {\n \/\/std::unique_ptr<D2TMMoveUnitStruct> s(static_cast<D2TMMoveUnitStruct*>(event->user.data1));\n \/\/Point p = map_camera->toWorldCoordinates(s->screen_position);\n\n \/\/for (auto& unit : units){\n \/\/if (unit->is_selected())\n \/\/unit->order_move(p);\n \/\/}\n \/\/}\n\n \/\/}\n\n}\n\nvoid Game::render() {\n screen.clear();\n\n screen.draw(*map);\n\n for (const auto& unit : units)\n screen.draw(*unit);\n\n map->drawShrouded(screen, sf::RenderStates::Default);\n\n screen.draw(box);\n\n screen.draw(mouse);\n\n screen.display();\n}\n\nvoid Game::updateState() {\n static const float cameraSpeed = 10.f;\n float vec_x = 0.f, vec_y = 0.f;\n if (sf::Keyboard::isKeyPressed(sf::Keyboard::Up)) vec_y -= cameraSpeed;\n if (sf::Keyboard::isKeyPressed(sf::Keyboard::Down)) vec_y += cameraSpeed;\n if (sf::Keyboard::isKeyPressed(sf::Keyboard::Left)) vec_x -= cameraSpeed;\n if (sf::Keyboard::isKeyPressed(sf::Keyboard::Right)) vec_x += cameraSpeed;\n\n camera.move(vec_x, vec_y);\n screen.setView(camera);\n\n if (sf::Mouse::isButtonPressed(sf::Mouse::Left))\n box.setBottomRight(screen.mapPixelToCoords(sf::Mouse::getPosition(screen)));\n\n mouse.setPosition(screen.mapPixelToCoords(sf::Mouse::getPosition(screen)));\n\n \/\/keyboard.updateState();\n \/\/mouse.updateState();\n \/\/map_camera->updateState();\n\n for (auto& unit: units){\n unit->updateState();\n }\n}\n\n\/\/void Game::deselectAllUnits() {\n \/\/for (auto& unit : units)\n \/\/unit->unselect();\n\/\/}\n\n\/\/bool Game::playerHasUnits(const Player &player) const\n\/\/{\n \/\/for (const auto& unit : units){\n \/\/if (unit->getOwner()==player)\n \/\/return true; \/\/unit belonging to player found\n \/\/}\n \/\/return false;\n\/\/}\n\n<commit_msg>request antialising level 8<commit_after>#include <iostream>\n\n#include <SFML\/Graphics.hpp>\n#include \"game.h\"\n\n\n\nGame::Game():\n playing(true),\n screen(),\n map(nullptr)\n \/\/map_camera(nullptr),\n \/\/unitRepository(nullptr)\n{\n sf::ContextSettings settings;\n settings.antialiasingLevel = 8;\n screen.create(sf::VideoMode(800, 600), \"Dune 2 - The Maker\", sf::Style::Close, settings);\n screen.setFramerateLimit(IDEAL_FPS);\n screen.setMouseCursorVisible(false);\n\n if (!init()){\n std::cerr << \"Failed to initialized game.\";\n playing = false;\n }\n}\n\nint Game::execute() {\n\n while(playing) {\n sf::Event event;\n while(screen.pollEvent(event)) {\n onEvent(event);\n }\n\n updateState();\n render();\n }\n\n return 0;\n}\n\nbool Game::init() {\n if (!terrain.loadFromFile(\"graphics\/terrain.png\")) {\n std::cout << \"Failed to read graphics\/terrain.png data\" << std::endl;\n return false;\n }\n\n sf::Image temp;\n if (!temp.loadFromFile(\"graphics\/shroud_edges.bmp\")) {\n std::cout << \"Failed to read graphics\/shroud_edges.bmp data\" << std::endl;\n return false;\n }\n\n temp.createMaskFromColor(sf::Color(255, 0, 255));\n shroud_edges.loadFromImage(temp);\n\n map.reset(new Map(terrain, shroud_edges));\n map->load(\"maps\/4PL_Mountains.ini\");\n\n camera.reset({0,0,800,600});\n screen.setView(camera);\n\n \/\/init a trike\n sf::Image trikeImage;\n trikeImage.loadFromFile(\"graphics\/Unit_Trike.bmp\");\n trikeImage.createMaskFromColor(sf::Color(0,0,0));\n sf::Texture* trikeTexture = new sf::Texture; \/\/yes we are leaking! Player should own this\n trikeTexture->loadFromImage(trikeImage);\n\n sf::Image trikeShadowImage;\n trikeShadowImage.loadFromFile(\"graphics\/Unit_Trike_s.bmp\");\n trikeShadowImage.createMaskFromColor(sf::Color(255,0,255));\n sf::Texture* trikeShadowTexture = new sf::Texture; \/\/yes we are leaking! Player should own this\n trikeShadowTexture->loadFromImage(trikeShadowImage);\n\n sf::Image selectedImage;\n selectedImage.loadFromFile(\"graphics\/selected.bmp\");\n selectedImage.createMaskFromColor(sf::Color(255, 0, 255));\n sf::Texture* selectedTexture = new sf::Texture; \/\/more leaks!\n selectedTexture->loadFromImage(selectedImage);\n units.emplace_back(new Unit(*trikeTexture, *trikeShadowTexture, *selectedTexture, 256, 256, 0));\n\n \/\/remove shroud here\n map->removeShroud(static_cast<sf::Vector2i>(units[0]->getPosition()), 10);\n\n \/\/shroud_edges_shadow = Surface::load(\"graphics\/shroud_edges_shadow.bmp\");\n\n \/\/if (shroud_edges_shadow == NULL) {\n \/\/cout << \"Failed to read graphics\/shroud_edges_shadow.bmp data\" << endl;\n \/\/return false;\n \/\/}\n\n \/\/mouse.init(screen);\n\n \/\/map_camera.reset(new MapCamera(0, 0, screen, &map));\n \/\/map.load(\"maps\/4PL_Mountains.ini\");\n \/\/unitRepository.reset(new UnitRepository(&map));\n\n \/\/\/\/init two players\n \/\/int idCount = 0;\n \/\/players.emplace_back(House::Sardaukar, idCount++);\n \/\/players.emplace_back(House::Harkonnen, idCount++);\n\n \/\/units.emplace_back(unitRepository->create(UNIT_FRIGATE, House::Sardaukar, 3, 3, 10, SUBCELL_CENTER, players[0]));\n \/\/units.emplace_back(unitRepository->create(UNIT_TRIKE, House::Sardaukar, 8, 8, 3, SUBCELL_CENTER, players[0]));\n\n \/\/\/\/ soldiers\n \/\/units.emplace_back(unitRepository->create(UNIT_SOLDIER, House::Sardaukar, 14, 14, 3, SUBCELL_CENTER, players[0]));\n \/\/units.emplace_back(unitRepository->create(UNIT_SOLDIER, House::Sardaukar, 14, 14, 3, SUBCELL_UPLEFT, players[0]));\n \/\/units.emplace_back(unitRepository->create(UNIT_SOLDIER, House::Sardaukar, 14, 14, 3, SUBCELL_UPRIGHT, players[0]));\n \/\/units.emplace_back(unitRepository->create(UNIT_SOLDIER, House::Sardaukar, 14, 14, 3, SUBCELL_DOWNLEFT, players[0]));\n \/\/units.emplace_back(unitRepository->create(UNIT_SOLDIER, House::Sardaukar, 14, 14, 3, SUBCELL_DOWNRIGHT, players[0]));\n\n \/\/units.emplace_back(unitRepository->create(UNIT_SOLDIER, House::Harkonnen, 18, 8, 3, SUBCELL_CENTER, players[1]));\n \/\/units.emplace_back(unitRepository->create(UNIT_SOLDIER, House::Harkonnen, 18, 8, 3, SUBCELL_UPLEFT, players[1]));\n \/\/units.emplace_back(unitRepository->create(UNIT_SOLDIER, House::Harkonnen, 18, 8, 3, SUBCELL_UPRIGHT, players[1]));\n \/\/units.emplace_back(unitRepository->create(UNIT_SOLDIER, House::Harkonnen, 18, 8, 3, SUBCELL_DOWNLEFT, players[1]));\n \/\/units.emplace_back(unitRepository->create(UNIT_SOLDIER, House::Harkonnen, 18, 8, 3, SUBCELL_DOWNRIGHT, players[1]));\n\n return true;\n}\n\nvoid Game::onEvent(sf::Event event) {\n\n switch (event.type){\n case sf::Event::Closed:\n playing = false; break;\n case sf::Event::KeyPressed:\n switch (event.key.code) {\n case sf::Keyboard::Q:\n playing = false; break;\n default:\n break;\n }\n break;\n case sf::Event::MouseButtonPressed:\n switch (event.mouseButton.button){\n case sf::Mouse::Left:{\n sf::Vector2f toSet = screen.mapPixelToCoords(sf::Vector2i(event.mouseButton.x, event.mouseButton.y));\n box.setTopLeft(toSet);\n break;\n }\n default:\n break;\n }\n break;\n case sf::Event::MouseButtonReleased:\n switch (event.mouseButton.button){\n case sf::Mouse::Left:\n for (auto& unit : units){\n if (box.intersects(unit->getBounds())){\n unit->select();\n mouse.setType(Mouse::Type::Move); \/\/at least one unit selected...\n } \n }\n for (auto& unit : units){\n if (unit->is_selected()) unit->order_move(screen.mapPixelToCoords(static_cast<sf::Vector2i>(mouse.getPosition())));\n }\n box.clear();\n break;\n case sf::Mouse::Right:\n \/\/deselect all units\n for (auto& unit : units){\n unit->unselect();\n mouse.setType(Mouse::Type::Default);\n }\n default:\n break;\n }\n default:\n break;\n }\n\n \/\/mouse.onEvent(event);\n \/\/keyboard.onEvent(event);\n\n \/\/map_camera->onEvent(event);\n\n \/\/if (event->type == SDL_USEREVENT) {\n \/\/if (event->user.code == D2TM_SELECT) {\n \/\/std::unique_ptr<D2TMSelectStruct> s(static_cast<D2TMSelectStruct*>(event->user.data1));\n\n \/\/Point p = map_camera->toWorldCoordinates(s->screen_position);\n\n \/\/if (mouse.is_pointing()) {\n \/\/Unit* selected_unit = NULL;\n \/\/for (auto& unit : units){\n \/\/if (unit->is_point_within(p)){\n \/\/selected_unit = unit.get();\n \/\/break;\n \/\/}\n\n \/\/}\n \/\/if (selected_unit != NULL) {\n \/\/deselectAllUnits();\n \/\/selected_unit->select();\n \/\/mouse.state_order_move();\n \/\/}\n \/\/}\n \/\/} else if (event->user.code == D2TM_DESELECT) {\n \/\/mouse.state_pointing();\n \/\/deselectAllUnits();\n \/\/} else if (event->user.code == D2TM_BOX_SELECT) {\n \/\/std::unique_ptr<D2TMBoxSelectStruct> s(static_cast<D2TMBoxSelectStruct*>(event->user.data1));\n\n \/\/Rectangle rectangle = map_camera->toWorldCoordinates(s->rectangle);\n\n \/\/if (mouse.is_pointing()) {\n \/\/mouse.state_pointing();\n\n \/\/deselectAllUnits();\n \/\/for (auto& unit : units){\n \/\/if (unit->is_within(rectangle)){\n \/\/unit->select();\n \/\/mouse.state_order_move();\n \/\/}\n \/\/}\n \/\/}\n \/\/} else if (event->user.code == D2TM_MOVE_UNIT) {\n \/\/std::unique_ptr<D2TMMoveUnitStruct> s(static_cast<D2TMMoveUnitStruct*>(event->user.data1));\n \/\/Point p = map_camera->toWorldCoordinates(s->screen_position);\n\n \/\/for (auto& unit : units){\n \/\/if (unit->is_selected())\n \/\/unit->order_move(p);\n \/\/}\n \/\/}\n\n \/\/}\n\n}\n\nvoid Game::render() {\n screen.clear();\n\n screen.draw(*map);\n\n for (const auto& unit : units)\n screen.draw(*unit);\n\n map->drawShrouded(screen, sf::RenderStates::Default);\n\n screen.draw(box);\n\n screen.draw(mouse);\n\n screen.display();\n}\n\nvoid Game::updateState() {\n static const float cameraSpeed = 10.f;\n float vec_x = 0.f, vec_y = 0.f;\n if (sf::Keyboard::isKeyPressed(sf::Keyboard::Up)) vec_y -= cameraSpeed;\n if (sf::Keyboard::isKeyPressed(sf::Keyboard::Down)) vec_y += cameraSpeed;\n if (sf::Keyboard::isKeyPressed(sf::Keyboard::Left)) vec_x -= cameraSpeed;\n if (sf::Keyboard::isKeyPressed(sf::Keyboard::Right)) vec_x += cameraSpeed;\n\n camera.move(vec_x, vec_y);\n screen.setView(camera);\n\n if (sf::Mouse::isButtonPressed(sf::Mouse::Left))\n box.setBottomRight(screen.mapPixelToCoords(sf::Mouse::getPosition(screen)));\n\n mouse.setPosition(screen.mapPixelToCoords(sf::Mouse::getPosition(screen)));\n\n \/\/keyboard.updateState();\n \/\/mouse.updateState();\n \/\/map_camera->updateState();\n\n for (auto& unit: units){\n unit->updateState();\n }\n}\n\n\/\/void Game::deselectAllUnits() {\n \/\/for (auto& unit : units)\n \/\/unit->unselect();\n\/\/}\n\n\/\/bool Game::playerHasUnits(const Player &player) const\n\/\/{\n \/\/for (const auto& unit : units){\n \/\/if (unit->getOwner()==player)\n \/\/return true; \/\/unit belonging to player found\n \/\/}\n \/\/return false;\n\/\/}\n\n<|endoftext|>"} {"text":"<commit_before>#undef DEBUG\n#include <iostream>\n#include <cstdlib>\n#include <cstdio>\n#include <cmath>\n#include <unistd.h>\n#include <signal.h>\n#include <sys\/types.h>\n#include <sys\/wait.h>\n#include <sys\/epoll.h>\n\n\/\/for connection to server\nbool ready4data = false;\/\/set to true when streaming starts\nbool inited = false;\nbool stopparsing = false;\ntimeval lastrec;\n\nint CONN_fd = 0;\n#include \"..\/util\/ddv_socket.cpp\" \/\/DDVTech Socket wrapper\n#include \"..\/util\/flv_sock.cpp\" \/\/FLV parsing with SocketW\n#include \"parsechunks.cpp\" \/\/chunkstream parsing\n#include \"handshake.cpp\" \/\/handshaking\n\n\n\nint server_socket = 0;\n\nvoid termination_handler (int signum){\n if (server_socket == 0) return;\n close(server_socket);\n server_socket = 0;\n}\n\nint main(int argc, char ** argv){\n \/\/setup signal handler\n struct sigaction new_action;\n new_action.sa_handler = termination_handler;\n sigemptyset (&new_action.sa_mask);\n new_action.sa_flags = 0;\n sigaction (SIGINT, &new_action, NULL);\n sigaction (SIGHUP, &new_action, NULL);\n sigaction (SIGTERM, &new_action, NULL);\n \n server_socket = DDV_Listen(1935);\n if ((argc < 2) || (argv[1] == \"nd\")){\n if (server_socket > 0){daemon(1, 0);}else{return 1;}\n }\n int status;\n while (server_socket > 0){\n waitpid((pid_t)-1, &status, WNOHANG);\n CONN_fd = DDV_Accept(server_socket);\n if (CONN_fd > 0){\n pid_t myid = fork();\n if (myid == 0){\n break;\n }else{\n printf(\"Spawned new process %i for handling socket %i\\n\", (int)myid, CONN_fd);\n }\n }\n }\n if (server_socket <= 0){\n return 0;\n }\n\n unsigned int ts;\n unsigned int fts = 0;\n unsigned int ftst;\n int ss;\n FLV_Pack * tag = 0;\n\n \/\/first timestamp set\n firsttime = getNowMS();\n\n #ifdef DEBUG\n fprintf(stderr, \"Doing handshake...\\n\");\n #endif\n if (doHandshake()){\n #ifdef DEBUG\n fprintf(stderr, \"Handshake succcess!\\n\");\n #endif\n }else{\n #ifdef DEBUG\n fprintf(stderr, \"Handshake fail!\\n\");\n #endif\n return 0;\n }\n #ifdef DEBUG\n fprintf(stderr, \"Starting processing...\\n\");\n #endif\n\n\n int retval;\n int poller = epoll_create(1);\n int sspoller = epoll_create(1);\n struct epoll_event ev;\n ev.events = EPOLLIN;\n ev.data.fd = CONN_fd;\n epoll_ctl(poller, EPOLL_CTL_ADD, CONN_fd, &ev);\n struct epoll_event events[1];\n\n\n\n\n while (!socketError && !All_Hell_Broke_Loose){\n \/\/only parse input if available or not yet init'ed\n \/\/rightnow = getNowMS();\n retval = epoll_wait(poller, events, 1, 0);\n if ((retval > 0) || !ready4data || (snd_cnt - snd_window_at >= snd_window_size)){\n if (DDV_ready(CONN_fd)){\n parseChunk();\n }\n }\n if (ready4data){\n if (!inited){\n \/\/we are ready, connect the socket!\n ss = DDV_OpenUnix(streamname);\n if (ss <= 0){\n #ifdef DEBUG\n fprintf(stderr, \"Could not connect to server!\\n\");\n #endif\n return 0;\n }\n ev.events = EPOLLIN;\n ev.data.fd = ss;\n epoll_ctl(sspoller, EPOLL_CTL_ADD, ss, &ev);\n #ifdef DEBUG\n fprintf(stderr, \"Everything connected, starting to send video data...\\n\");\n #endif\n inited = true;\n }\n\n retval = epoll_wait(poller, events, 1, 50);\n if ((retval > 0) && (DDV_ready(ss))){\n if (FLV_GetPacket(tag, ss)){\/\/able to read a full packet?\n ts = tag->data[7] * 256*256*256;\n ts += tag->data[4] * 256*256;\n ts += tag->data[5] * 256;\n ts += tag->data[6];\n if (ts != 0){\n if (fts == 0){fts = ts;ftst = getNowMS();}\n ts -= fts;\n tag->data[7] = ts \/ (256*256*256);\n tag->data[4] = ts \/ (256*256);\n tag->data[5] = ts \/ 256;\n tag->data[6] = ts % 256;\n ts += ftst;\n }else{\n ftst = getNowMS();\n tag->data[7] = ftst \/ (256*256*256);\n tag->data[4] = ftst \/ (256*256);\n tag->data[5] = ftst \/ 256;\n tag->data[6] = ftst % 256;\n }\n SendMedia((unsigned char)tag->data[0], (unsigned char *)tag->data+11, tag->len-15, ts);\n #ifdef DEBUG\n fprintf(stderr, \"Sent a tag to %i\\n\", CONN_fd);\n #endif\n }\n }\n }\n \/\/send ACK if we received a whole window\n if (rec_cnt - rec_window_at > rec_window_size){\n rec_window_at = rec_cnt;\n SendCTL(3, rec_cnt);\/\/send ack (msg 3)\n }\n }\n \/\/#ifdef DEBUG\n if (socketError){fprintf(stderr, \"socketError\\n\");}\n if (All_Hell_Broke_Loose){fprintf(stderr, \"All Hell Broke Loose\\n\");}\n fprintf(stderr, \"User %i disconnected.\\n\", CONN_fd);\n \/\/#endif\n return 0;\n}\/\/main\n<commit_msg>Minder debugging<commit_after>#undef DEBUG\n#include <iostream>\n#include <cstdlib>\n#include <cstdio>\n#include <cmath>\n#include <unistd.h>\n#include <signal.h>\n#include <sys\/types.h>\n#include <sys\/wait.h>\n#include <sys\/epoll.h>\n\n\/\/for connection to server\nbool ready4data = false;\/\/set to true when streaming starts\nbool inited = false;\nbool stopparsing = false;\ntimeval lastrec;\n\nint CONN_fd = 0;\n#include \"..\/util\/ddv_socket.cpp\" \/\/DDVTech Socket wrapper\n#include \"..\/util\/flv_sock.cpp\" \/\/FLV parsing with SocketW\n#include \"parsechunks.cpp\" \/\/chunkstream parsing\n#include \"handshake.cpp\" \/\/handshaking\n\n\n\nint server_socket = 0;\n\nvoid termination_handler (int signum){\n if (server_socket == 0) return;\n close(server_socket);\n server_socket = 0;\n}\n\nint main(int argc, char ** argv){\n \/\/setup signal handler\n struct sigaction new_action;\n new_action.sa_handler = termination_handler;\n sigemptyset (&new_action.sa_mask);\n new_action.sa_flags = 0;\n sigaction (SIGINT, &new_action, NULL);\n sigaction (SIGHUP, &new_action, NULL);\n sigaction (SIGTERM, &new_action, NULL);\n \n server_socket = DDV_Listen(1935);\n if ((argc < 2) || (argv[1] == \"nd\")){\n if (server_socket > 0){daemon(1, 0);}else{return 1;}\n }\n int status;\n while (server_socket > 0){\n waitpid((pid_t)-1, &status, WNOHANG);\n CONN_fd = DDV_Accept(server_socket);\n if (CONN_fd > 0){\n pid_t myid = fork();\n if (myid == 0){\n break;\n }else{\n printf(\"Spawned new process %i for handling socket %i\\n\", (int)myid, CONN_fd);\n }\n }\n }\n if (server_socket <= 0){\n return 0;\n }\n\n unsigned int ts;\n unsigned int fts = 0;\n unsigned int ftst;\n int ss;\n FLV_Pack * tag = 0;\n\n \/\/first timestamp set\n firsttime = getNowMS();\n\n #ifdef DEBUG\n fprintf(stderr, \"Doing handshake...\\n\");\n #endif\n if (doHandshake()){\n #ifdef DEBUG\n fprintf(stderr, \"Handshake succcess!\\n\");\n #endif\n }else{\n #ifdef DEBUG\n fprintf(stderr, \"Handshake fail!\\n\");\n #endif\n return 0;\n }\n #ifdef DEBUG\n fprintf(stderr, \"Starting processing...\\n\");\n #endif\n\n\n int retval;\n int poller = epoll_create(1);\n int sspoller = epoll_create(1);\n struct epoll_event ev;\n ev.events = EPOLLIN;\n ev.data.fd = CONN_fd;\n epoll_ctl(poller, EPOLL_CTL_ADD, CONN_fd, &ev);\n struct epoll_event events[1];\n\n\n\n\n while (!socketError && !All_Hell_Broke_Loose){\n \/\/only parse input if available or not yet init'ed\n \/\/rightnow = getNowMS();\n retval = epoll_wait(poller, events, 1, 0);\n if ((retval > 0) || !ready4data || (snd_cnt - snd_window_at >= snd_window_size)){\n if (DDV_ready(CONN_fd)){\n parseChunk();\n }\n }\n if (ready4data){\n if (!inited){\n \/\/we are ready, connect the socket!\n ss = DDV_OpenUnix(streamname);\n if (ss <= 0){\n #ifdef DEBUG\n fprintf(stderr, \"Could not connect to server!\\n\");\n #endif\n return 0;\n }\n ev.events = EPOLLIN;\n ev.data.fd = ss;\n epoll_ctl(sspoller, EPOLL_CTL_ADD, ss, &ev);\n #ifdef DEBUG\n fprintf(stderr, \"Everything connected, starting to send video data...\\n\");\n #endif\n inited = true;\n }\n\n retval = epoll_wait(poller, events, 1, 50);\n if (DDV_ready(ss)){\n if (FLV_GetPacket(tag, ss)){\/\/able to read a full packet?\n ts = tag->data[7] * 256*256*256;\n ts += tag->data[4] * 256*256;\n ts += tag->data[5] * 256;\n ts += tag->data[6];\n if (ts != 0){\n if (fts == 0){fts = ts;ftst = getNowMS();}\n ts -= fts;\n tag->data[7] = ts \/ (256*256*256);\n tag->data[4] = ts \/ (256*256);\n tag->data[5] = ts \/ 256;\n tag->data[6] = ts % 256;\n ts += ftst;\n }else{\n ftst = getNowMS();\n tag->data[7] = ftst \/ (256*256*256);\n tag->data[4] = ftst \/ (256*256);\n tag->data[5] = ftst \/ 256;\n tag->data[6] = ftst % 256;\n }\n SendMedia((unsigned char)tag->data[0], (unsigned char *)tag->data+11, tag->len-15, ts);\n #ifdef DEBUG\n fprintf(stderr, \"Sent a tag to %i\\n\", CONN_fd);\n #endif\n }\n }\n }\n \/\/send ACK if we received a whole window\n if (rec_cnt - rec_window_at > rec_window_size){\n rec_window_at = rec_cnt;\n SendCTL(3, rec_cnt);\/\/send ack (msg 3)\n }\n }\n \/\/#ifdef DEBUG\n if (socketError){fprintf(stderr, \"socketError\\n\");}\n if (All_Hell_Broke_Loose){fprintf(stderr, \"All Hell Broke Loose\\n\");}\n fprintf(stderr, \"User %i disconnected.\\n\", CONN_fd);\n \/\/#endif\n return 0;\n}\/\/main\n<|endoftext|>"} {"text":"<commit_before>#include \"nse_sequential.h\"\n\n\/\/ Include <gtest\/gtest.h> _after_ \"nse_sequential.h.h\"\n#include \"gtest\/gtest.h\"\n\nusing namespace crv;\n\nTEST(NseSequentialTest, SequentialDfsChecker)\n{\n SequentialDfsChecker checker;\n\n \/\/ if (a < 7) { skip } ; if (a < 4) { skip }\n Internal<int> a;\n EXPECT_FALSE(checker.branch(a < 7));\n EXPECT_FALSE(checker.branch(a < 4));\n EXPECT_TRUE(checker.find_next_path());\n\n EXPECT_FALSE(checker.branch(a < 7));\n EXPECT_TRUE(checker.branch(a < 4));\n\n \/\/ ignored because \"a >= 7 and a < 4\" is unsat\n EXPECT_FALSE(checker.branch(a < 1));\n EXPECT_FALSE(checker.branch(a < 2));\n EXPECT_FALSE(checker.branch(a < 3));\n EXPECT_TRUE(checker.find_next_path());\n\n EXPECT_TRUE(checker.branch(a < 7));\n EXPECT_FALSE(checker.branch(a < 4));\n EXPECT_TRUE(checker.find_next_path());\n\n EXPECT_TRUE(checker.branch(a < 7));\n EXPECT_TRUE(checker.branch(a < 4));\n EXPECT_FALSE(checker.find_next_path());\n\n checker.reset();\n\n Internal<int> b;\n checker.add_assertion(b < 7);\n EXPECT_TRUE(checker.branch(b < 7));\n EXPECT_FALSE(checker.branch(b < 4));\n EXPECT_TRUE(checker.find_next_path());\n\n checker.add_assertion(b < 7);\n EXPECT_TRUE(checker.branch(b < 7));\n EXPECT_TRUE(checker.branch(b < 4));\n EXPECT_FALSE(checker.find_next_path());\n\n checker.reset();\n\n Internal<int> c;\n checker.add_assertion(c < 4);\n EXPECT_TRUE(checker.branch(c < 7));\n EXPECT_TRUE(checker.branch(c < 4));\n EXPECT_FALSE(checker.find_next_path());\n}\n\nTEST(NseSequentialTest, Backtrack)\n{\n BacktrackDfsChecker checker;\n\n \/\/ if (a < 7) { skip } ; if (a < 4) { skip }\n Internal<int> a;\n EXPECT_FALSE(checker.branch(a < 7));\n EXPECT_FALSE(checker.branch(a < 4));\n EXPECT_TRUE(checker.find_next_path());\n\n EXPECT_FALSE(checker.branch(a < 7));\n EXPECT_TRUE(checker.branch(a < 4));\n\n \/\/ ignored because \"a >= 7 and a < 4\" is unsat\n EXPECT_FALSE(checker.branch(a < 1));\n EXPECT_FALSE(checker.branch(a < 2));\n EXPECT_FALSE(checker.branch(a < 3));\n EXPECT_TRUE(checker.find_next_path());\n\n EXPECT_TRUE(checker.branch(a < 7));\n EXPECT_FALSE(checker.branch(a < 4));\n EXPECT_TRUE(checker.find_next_path());\n\n EXPECT_TRUE(checker.branch(a < 7));\n EXPECT_TRUE(checker.branch(a < 4));\n EXPECT_FALSE(checker.find_next_path());\n\n checker.reset();\n\n \/\/ BacktrackDfsChecker may not prune as\n \/\/ many paths as SequentialDfsChecker\n Internal<int> b;\n checker.add_assertion(b < 7);\n EXPECT_FALSE(checker.branch(b < 7));\n EXPECT_FALSE(checker.branch(b < 4));\n EXPECT_TRUE(checker.find_next_path());\n\n checker.add_assertion(b < 7);\n EXPECT_TRUE(checker.branch(b < 7));\n EXPECT_FALSE(checker.branch(b < 4));\n EXPECT_TRUE(checker.find_next_path());\n\n checker.add_assertion(b < 7);\n EXPECT_TRUE(checker.branch(b < 7));\n EXPECT_TRUE(checker.branch(b < 4));\n EXPECT_FALSE(checker.find_next_path());\n}\n<commit_msg>Add test case for non-chronological symbolic execution<commit_after>#include \"nse_sequential.h\"\n\n\/\/ Include <gtest\/gtest.h> _after_ \"nse_sequential.h.h\"\n#include \"gtest\/gtest.h\"\n\nusing namespace crv;\n\nTEST(NseSequentialTest, SequentialDfsChecker)\n{\n SequentialDfsChecker checker;\n\n \/\/ if (a < 7) { skip } ; if (a < 4) { skip }\n Internal<int> a;\n EXPECT_FALSE(checker.branch(a < 7));\n EXPECT_FALSE(checker.branch(a < 4));\n EXPECT_TRUE(checker.find_next_path());\n\n EXPECT_FALSE(checker.branch(a < 7));\n EXPECT_TRUE(checker.branch(a < 4));\n\n \/\/ ignored because \"a >= 7 and a < 4\" is unsat\n EXPECT_FALSE(checker.branch(a < 1));\n EXPECT_FALSE(checker.branch(a < 2));\n EXPECT_FALSE(checker.branch(a < 3));\n EXPECT_TRUE(checker.find_next_path());\n\n EXPECT_TRUE(checker.branch(a < 7));\n EXPECT_FALSE(checker.branch(a < 4));\n EXPECT_TRUE(checker.find_next_path());\n\n EXPECT_TRUE(checker.branch(a < 7));\n EXPECT_TRUE(checker.branch(a < 4));\n EXPECT_FALSE(checker.find_next_path());\n\n checker.reset();\n\n Internal<int> b;\n checker.add_assertion(b < 7);\n EXPECT_TRUE(checker.branch(b < 7));\n EXPECT_FALSE(checker.branch(b < 4));\n EXPECT_TRUE(checker.find_next_path());\n\n checker.add_assertion(b < 7);\n EXPECT_TRUE(checker.branch(b < 7));\n EXPECT_TRUE(checker.branch(b < 4));\n EXPECT_FALSE(checker.find_next_path());\n\n checker.reset();\n\n Internal<int> c;\n checker.add_assertion(c < 4);\n EXPECT_TRUE(checker.branch(c < 7));\n EXPECT_TRUE(checker.branch(c < 4));\n EXPECT_FALSE(checker.find_next_path());\n}\n\nTEST(NseSequentialTest, Backtrack)\n{\n BacktrackDfsChecker checker;\n\n \/\/ if (a < 7) { skip } ; if (a < 4) { skip }\n Internal<int> a;\n EXPECT_FALSE(checker.branch(a < 7));\n EXPECT_FALSE(checker.branch(a < 4));\n EXPECT_TRUE(checker.find_next_path());\n\n EXPECT_FALSE(checker.branch(a < 7));\n EXPECT_TRUE(checker.branch(a < 4));\n\n \/\/ ignored because \"a >= 7 and a < 4\" is unsat\n EXPECT_FALSE(checker.branch(a < 1));\n EXPECT_FALSE(checker.branch(a < 2));\n EXPECT_FALSE(checker.branch(a < 3));\n EXPECT_TRUE(checker.find_next_path());\n\n EXPECT_TRUE(checker.branch(a < 7));\n EXPECT_FALSE(checker.branch(a < 4));\n EXPECT_TRUE(checker.find_next_path());\n\n EXPECT_TRUE(checker.branch(a < 7));\n EXPECT_TRUE(checker.branch(a < 4));\n EXPECT_FALSE(checker.find_next_path());\n\n checker.reset();\n\n \/\/ BacktrackDfsChecker may not prune as\n \/\/ many paths as SequentialDfsChecker\n Internal<int> b;\n checker.add_assertion(b < 7);\n EXPECT_FALSE(checker.branch(b < 7));\n EXPECT_FALSE(checker.branch(b < 4));\n EXPECT_TRUE(checker.find_next_path());\n\n checker.add_assertion(b < 7);\n EXPECT_TRUE(checker.branch(b < 7));\n EXPECT_FALSE(checker.branch(b < 4));\n EXPECT_TRUE(checker.find_next_path());\n\n checker.add_assertion(b < 7);\n EXPECT_TRUE(checker.branch(b < 7));\n EXPECT_TRUE(checker.branch(b < 4));\n EXPECT_FALSE(checker.find_next_path());\n\n checker.reset();\n\n \/\/ assertion at the end\n EXPECT_FALSE(checker.branch(b < 7));\n EXPECT_FALSE(checker.branch(b < 4));\n checker.add_assertion(a < 7);\n checker.add_assertion(b < 7);\n EXPECT_TRUE(checker.find_next_path());\n\n EXPECT_TRUE(checker.branch(b < 7));\n EXPECT_FALSE(checker.branch(b < 4));\n checker.add_assertion(a < 7);\n checker.add_assertion(b < 7);\n EXPECT_TRUE(checker.find_next_path());\n\n EXPECT_TRUE(checker.branch(b < 7));\n EXPECT_TRUE(checker.branch(b < 4));\n checker.add_assertion(a < 7);\n checker.add_assertion(b < 7);\n EXPECT_FALSE(checker.find_next_path());\n}\n<|endoftext|>"} {"text":"<commit_before>#ifndef UNESCAPE_COPY_ROW_HPP\n#define UNESCAPE_COPY_ROW_HPP\n\n#include <boost\/noncopyable.hpp>\n#include <boost\/fusion\/include\/size.hpp>\n#include <boost\/date_time\/posix_time\/posix_time.hpp>\n#include <boost\/algorithm\/string.hpp>\n#include <boost\/optional.hpp>\n#include <boost\/fusion\/include\/for_each.hpp>\n\n#include \"types.hpp\"\n\ntemplate <typename S, typename T>\nstruct unescape_copy_row \n : public boost::noncopyable {\n static const size_t s_num_columns = boost::fusion::result_of::size<T>::value;\n\n explicit unescape_copy_row(S &source) \n : m_source(source),\n m_reorder(calculate_reorder(m_source.column_names())) {\n }\n\n ~unescape_copy_row() {\n }\n\n size_t read(T &row) {\n std::string line;\n size_t num = m_source.read(line);\n if (num > 0) {\n unpack(line, row);\n }\n return num;\n }\n\nprivate:\n void unpack(std::string &line, T &row) {\n const size_t sz = s_num_columns;\n std::vector<std::pair<char *, size_t> > columns, old_columns;\n {\n char *prev_ptr = &line[0];\n char * const end_ptr = &line[line.size()];\n char *ptr = &line[0];\n for (; ptr != end_ptr; ++ptr) {\n if (*ptr == '\\t') {\n *ptr = '\\0';\n old_columns.push_back(std::make_pair(prev_ptr, std::distance(prev_ptr, ptr)));\n prev_ptr = ptr + 1;\n }\n }\n old_columns.push_back(std::make_pair(prev_ptr, std::distance(prev_ptr, ptr)));\n }\n\n columns.reserve(sz);\n for (size_t i = 0; i < sz; ++i) {\n if (i >= m_reorder.size()) {\n throw std::runtime_error(\"Index exceeds m_reorder.size(), this is a bug.\");\n }\n size_t j = m_reorder[i];\n if (j >= old_columns.size()) {\n throw std::runtime_error(\"Reordered index exceeds old_columns.size(), this is a bug.\");\n }\n columns.push_back(old_columns[j]);\n }\n\n if (columns.size() != sz) {\n throw std::runtime_error((boost::format(\"Wrong number of columns: expecting %1%, got %2% in line `%3%'.\") \n % sz % columns.size() % line).str());\n }\n try {\n set_values(row, columns);\n } catch (const std::exception &e) {\n throw std::runtime_error((boost::format(\"%1%: in line `%2%'.\") % e.what() % line).str());\n }\n }\n\n inline void set_values(T &t, std::vector<std::pair<char *, size_t> > &vs) {\n boost::fusion::for_each(t, set_value(vs.begin()));\n }\n\n struct set_value {\n explicit set_value(std::vector<std::pair<char *, size_t> >::iterator i) : itr(i) {}\n\n void operator()(bool &b) const {\n std::pair<char *, size_t> str = *itr++;\n switch (str.first[0]) {\n case 't':\n b = true;\n break;\n case 'f':\n b = false;\n break;\n default:\n throw std::runtime_error((boost::format(\"Unrecognised value for bool: `%1%'\") % str.first).str());\n }\n }\n\n void operator()(int16_t &i) const {\n std::pair<char *, size_t> str = *itr++;\n unescape(str);\n i = int16_t(strtol(str.first, NULL, 10));\n }\n \n void operator()(int32_t &i) const {\n std::pair<char *, size_t> str = *itr++;\n unescape(str);\n i = int32_t(strtol(str.first, NULL, 10));\n }\n \n void operator()(int64_t &i) const {\n std::pair<char *, size_t> str = *itr++;\n unescape(str);\n i = int64_t(strtoll(str.first, NULL, 10));\n }\n\n void operator()(double &d) const {\n std::pair<char *, size_t> str = *itr++;\n unescape(str);\n d = strtod(str.first, NULL);\n }\n\n void operator()(std::string &v) const {\n std::pair<char *, size_t> str = *itr++;\n v.assign(str.first, str.second);\n }\n\n void operator()(boost::posix_time::ptime &t) const {\n std::pair<char *, size_t> str = *itr++;\n unescape(str);\n \/\/ 11111111112\n \/\/ 12345678901234567890\n \/\/ format is 2013-09-11 13:39:52.742365\n if (str.second < 19) { \n throw std::runtime_error((boost::format(\"Unexpected format for timestamp: `%1%'.\") \n % str.first).str());\n }\n int year = ((str.first[0] - '0') * 1000 +\n (str.first[1] - '0') * 100 +\n (str.first[2] - '0') * 10 +\n (str.first[3] - '0'));\n int month = ((str.first[5] - '0') * 10 + (str.first[6] - '0'));\n int day = ((str.first[8] - '0') * 10 + (str.first[9] - '0'));\n int hour = ((str.first[11] - '0') * 10 + (str.first[12] - '0'));\n int min = ((str.first[14] - '0') * 10 + (str.first[15] - '0'));\n int sec = ((str.first[17] - '0') * 10 + (str.first[19] - '0'));\n t = boost::posix_time::ptime(boost::gregorian::date(year, month, day),\n boost::posix_time::time_duration(hour, min, sec));\n }\n\n template <typename V>\n void operator()(boost::optional<V> &o) const {\n std::pair<char *, size_t> s = *itr;\n if (strncmp(s.first, \"\\\\N\", s.second) == 0) {\n o = boost::none;\n ++itr;\n } else {\n V v;\n operator()(v);\n o = v;\n }\n }\n\n void operator()(user_status_enum &e) const {\n std::pair<char *, size_t> str = *itr++;\n unescape(str);\n if (strncmp(str.first, \"pending\", str.second) == 0) {\n e = user_status_pending;\n } else if (strncmp(str.first, \"active\", str.second) == 0) {\n e = user_status_active;\n } else if (strncmp(str.first, \"confirmed\", str.second) == 0) {\n e = user_status_confirmed;\n } else if (strncmp(str.first, \"suspended\", str.second) == 0) {\n e = user_status_suspended;\n } else if (strncmp(str.first, \"deleted\", str.second) == 0) {\n e = user_status_deleted;\n } else {\n throw std::runtime_error((boost::format(\"Unrecognised value for user_status_enum: `%1%'.\") % str.first).str());\n }\n }\n\n void operator()(format_enum &e) const {\n std::pair<char *, size_t> str = *itr++;\n unescape(str);\n if (strncmp(str.first, \"html\", str.second) == 0) {\n e = format_html;\n } else if (strncmp(str.first, \"markdown\", str.second) == 0) {\n e = format_markdown;\n } else if (strncmp(str.first, \"text\", str.second) == 0) {\n e = format_text;\n } else {\n throw std::runtime_error((boost::format(\"Unrecognised value for format_enum: `%1%'.\") % str.first).str());\n }\n }\n\n void operator()(nwr_enum &e) const {\n std::pair<char *, size_t> str = *itr++;\n unescape(str);\n if (strncmp(str.first, \"Node\", str.second) == 0) {\n e = nwr_node;\n } else if (strncmp(str.first, \"Way\", str.second) == 0) {\n e = nwr_way;\n } else if (strncmp(str.first, \"Relation\", str.second) == 0) {\n e = nwr_relation;\n } else {\n throw std::runtime_error((boost::format(\"Unrecognised value for nwr_enum: `%1%'.\") % str.first).str());\n }\n }\n\n inline int hex2digit(char ch) const {\n switch (ch) {\n case '0':\n case '1':\n case '2':\n case '3':\n case '4':\n case '5':\n case '6':\n case '7':\n case '8':\n case '9':\n return int(ch - '0');\n\n case 'a':\n case 'b':\n case 'c':\n case 'd':\n case 'e':\n case 'f':\n return 10 + int(ch - 'a');\n\n case 'A':\n case 'B':\n case 'C':\n case 'D':\n case 'E':\n case 'F':\n return 10 + int(ch - 'A');\n\n default:\n throw std::runtime_error(\"Invalid hex digit.\");\n }\n }\n\n inline int oct2digit(char ch) const {\n if ((ch >= '0') && (ch <= '7')) {\n return int(ch - '0');\n } else {\n throw std::runtime_error(\"Invalid octal digit.\");\n }\n }\n\n void unescape(std::pair<char *, size_t> &s) const {\n const size_t end = s.second;\n char *str = s.first;\n size_t j = 0;\n\n for (size_t i = 0; i < end; ++i) {\n switch (str[i]) {\n case '\\\\':\n ++i;\n if (i < end) {\n switch (str[i]) {\n case 'b':\n str[j] = '\\b';\n break;\n\n case 'f':\n str[j] = '\\f';\n break;\n\n case 'n':\n str[j] = '\\n';\n break;\n\n case 'r':\n str[j] = '\\r';\n break;\n\n case 't':\n str[j] = '\\t';\n break;\n\n case 'v':\n str[j] = '\\v';\n break;\n\n case 'x':\n i += 2;\n if (i < end) {\n } else {\n str[j] = char(hex2digit(str[i-1]) * 16 + hex2digit(str[i]));\n throw std::runtime_error(\"Unterminated hex escape sequence.\");\n }\n break;\n\n case '0':\n case '1':\n case '2':\n case '3':\n case '4':\n case '5':\n case '6':\n case '7':\n i += 2;\n if (i < end) {\n str[j] = char(oct2digit(str[i-2]) * 64 + oct2digit(str[i-1]) * 8 + oct2digit(str[i]));\n } else {\n throw std::runtime_error(\"Unterminated octal escape sequence.\");\n }\n break;\n\n default:\n \/\/ an unnecessary escape\n str[j] = str[i];\n }\n \n } else {\n throw std::runtime_error(\"Unterminated escape sequence.\");\n }\n break;\n \n default:\n if (i != j) {\n str[j] = str[i];\n }\n }\n\n ++j;\n }\n\n str[j] = '\\0';\n s.second = j;\n }\n\n mutable std::vector<std::pair<char *, size_t> >::iterator itr;\n };\n\n static std::vector<size_t> calculate_reorder(const std::vector<std::string> &names) {\n std::vector<size_t> indexes;\n const std::vector<std::string> &wanted_names = T::column_names();\n\n const size_t num_columns = wanted_names.size();\n indexes.reserve(num_columns);\n for (size_t i = 0; i < num_columns; ++i) {\n const std::string &wanted_name = wanted_names[i];\n size_t j = i;\n\n if (wanted_name != \"*\") {\n std::vector<std::string>::const_iterator itr = std::find(names.begin(), names.end(), wanted_name);\n if (itr == names.end()) {\n std::ostringstream ostr;\n ostr << \"Unable to find wanted column name \\\"\" << wanted_name << \"\\\" in available names: \";\n for (std::vector<std::string>::const_iterator jtr = names.begin(); itr != names.end(); ++itr) {\n ostr << \"\\\"\" << *jtr << \"\\\", \";\n }\n throw std::runtime_error(ostr.str());\n }\n j = std::distance(names.begin(), itr);\n }\n\n indexes.push_back(j);\n }\n\n return indexes;\n }\n\n S &m_source;\n std::vector<size_t> m_reorder;\n};\n\n#endif \/* UNESCAPE_COPY_ROW_HPP *\/\n<commit_msg>Fixed bug in reporting of copy header problems.<commit_after>#ifndef UNESCAPE_COPY_ROW_HPP\n#define UNESCAPE_COPY_ROW_HPP\n\n#include <boost\/noncopyable.hpp>\n#include <boost\/fusion\/include\/size.hpp>\n#include <boost\/date_time\/posix_time\/posix_time.hpp>\n#include <boost\/algorithm\/string.hpp>\n#include <boost\/optional.hpp>\n#include <boost\/fusion\/include\/for_each.hpp>\n\n#include \"types.hpp\"\n\ntemplate <typename S, typename T>\nstruct unescape_copy_row \n : public boost::noncopyable {\n static const size_t s_num_columns = boost::fusion::result_of::size<T>::value;\n\n explicit unescape_copy_row(S &source) \n : m_source(source),\n m_reorder(calculate_reorder(m_source.column_names())) {\n }\n\n ~unescape_copy_row() {\n }\n\n size_t read(T &row) {\n std::string line;\n size_t num = m_source.read(line);\n if (num > 0) {\n unpack(line, row);\n }\n return num;\n }\n\nprivate:\n void unpack(std::string &line, T &row) {\n const size_t sz = s_num_columns;\n std::vector<std::pair<char *, size_t> > columns, old_columns;\n {\n char *prev_ptr = &line[0];\n char * const end_ptr = &line[line.size()];\n char *ptr = &line[0];\n for (; ptr != end_ptr; ++ptr) {\n if (*ptr == '\\t') {\n *ptr = '\\0';\n old_columns.push_back(std::make_pair(prev_ptr, std::distance(prev_ptr, ptr)));\n prev_ptr = ptr + 1;\n }\n }\n old_columns.push_back(std::make_pair(prev_ptr, std::distance(prev_ptr, ptr)));\n }\n\n columns.reserve(sz);\n for (size_t i = 0; i < sz; ++i) {\n if (i >= m_reorder.size()) {\n throw std::runtime_error(\"Index exceeds m_reorder.size(), this is a bug.\");\n }\n size_t j = m_reorder[i];\n if (j >= old_columns.size()) {\n throw std::runtime_error(\"Reordered index exceeds old_columns.size(), this is a bug.\");\n }\n columns.push_back(old_columns[j]);\n }\n\n if (columns.size() != sz) {\n throw std::runtime_error((boost::format(\"Wrong number of columns: expecting %1%, got %2% in line `%3%'.\") \n % sz % columns.size() % line).str());\n }\n try {\n set_values(row, columns);\n } catch (const std::exception &e) {\n throw std::runtime_error((boost::format(\"%1%: in line `%2%'.\") % e.what() % line).str());\n }\n }\n\n inline void set_values(T &t, std::vector<std::pair<char *, size_t> > &vs) {\n boost::fusion::for_each(t, set_value(vs.begin()));\n }\n\n struct set_value {\n explicit set_value(std::vector<std::pair<char *, size_t> >::iterator i) : itr(i) {}\n\n void operator()(bool &b) const {\n std::pair<char *, size_t> str = *itr++;\n switch (str.first[0]) {\n case 't':\n b = true;\n break;\n case 'f':\n b = false;\n break;\n default:\n throw std::runtime_error((boost::format(\"Unrecognised value for bool: `%1%'\") % str.first).str());\n }\n }\n\n void operator()(int16_t &i) const {\n std::pair<char *, size_t> str = *itr++;\n unescape(str);\n i = int16_t(strtol(str.first, NULL, 10));\n }\n \n void operator()(int32_t &i) const {\n std::pair<char *, size_t> str = *itr++;\n unescape(str);\n i = int32_t(strtol(str.first, NULL, 10));\n }\n \n void operator()(int64_t &i) const {\n std::pair<char *, size_t> str = *itr++;\n unescape(str);\n i = int64_t(strtoll(str.first, NULL, 10));\n }\n\n void operator()(double &d) const {\n std::pair<char *, size_t> str = *itr++;\n unescape(str);\n d = strtod(str.first, NULL);\n }\n\n void operator()(std::string &v) const {\n std::pair<char *, size_t> str = *itr++;\n v.assign(str.first, str.second);\n }\n\n void operator()(boost::posix_time::ptime &t) const {\n std::pair<char *, size_t> str = *itr++;\n unescape(str);\n \/\/ 11111111112\n \/\/ 12345678901234567890\n \/\/ format is 2013-09-11 13:39:52.742365\n if (str.second < 19) { \n throw std::runtime_error((boost::format(\"Unexpected format for timestamp: `%1%'.\") \n % str.first).str());\n }\n int year = ((str.first[0] - '0') * 1000 +\n (str.first[1] - '0') * 100 +\n (str.first[2] - '0') * 10 +\n (str.first[3] - '0'));\n int month = ((str.first[5] - '0') * 10 + (str.first[6] - '0'));\n int day = ((str.first[8] - '0') * 10 + (str.first[9] - '0'));\n int hour = ((str.first[11] - '0') * 10 + (str.first[12] - '0'));\n int min = ((str.first[14] - '0') * 10 + (str.first[15] - '0'));\n int sec = ((str.first[17] - '0') * 10 + (str.first[19] - '0'));\n t = boost::posix_time::ptime(boost::gregorian::date(year, month, day),\n boost::posix_time::time_duration(hour, min, sec));\n }\n\n template <typename V>\n void operator()(boost::optional<V> &o) const {\n std::pair<char *, size_t> s = *itr;\n if (strncmp(s.first, \"\\\\N\", s.second) == 0) {\n o = boost::none;\n ++itr;\n } else {\n V v;\n operator()(v);\n o = v;\n }\n }\n\n void operator()(user_status_enum &e) const {\n std::pair<char *, size_t> str = *itr++;\n unescape(str);\n if (strncmp(str.first, \"pending\", str.second) == 0) {\n e = user_status_pending;\n } else if (strncmp(str.first, \"active\", str.second) == 0) {\n e = user_status_active;\n } else if (strncmp(str.first, \"confirmed\", str.second) == 0) {\n e = user_status_confirmed;\n } else if (strncmp(str.first, \"suspended\", str.second) == 0) {\n e = user_status_suspended;\n } else if (strncmp(str.first, \"deleted\", str.second) == 0) {\n e = user_status_deleted;\n } else {\n throw std::runtime_error((boost::format(\"Unrecognised value for user_status_enum: `%1%'.\") % str.first).str());\n }\n }\n\n void operator()(format_enum &e) const {\n std::pair<char *, size_t> str = *itr++;\n unescape(str);\n if (strncmp(str.first, \"html\", str.second) == 0) {\n e = format_html;\n } else if (strncmp(str.first, \"markdown\", str.second) == 0) {\n e = format_markdown;\n } else if (strncmp(str.first, \"text\", str.second) == 0) {\n e = format_text;\n } else {\n throw std::runtime_error((boost::format(\"Unrecognised value for format_enum: `%1%'.\") % str.first).str());\n }\n }\n\n void operator()(nwr_enum &e) const {\n std::pair<char *, size_t> str = *itr++;\n unescape(str);\n if (strncmp(str.first, \"Node\", str.second) == 0) {\n e = nwr_node;\n } else if (strncmp(str.first, \"Way\", str.second) == 0) {\n e = nwr_way;\n } else if (strncmp(str.first, \"Relation\", str.second) == 0) {\n e = nwr_relation;\n } else {\n throw std::runtime_error((boost::format(\"Unrecognised value for nwr_enum: `%1%'.\") % str.first).str());\n }\n }\n\n inline int hex2digit(char ch) const {\n switch (ch) {\n case '0':\n case '1':\n case '2':\n case '3':\n case '4':\n case '5':\n case '6':\n case '7':\n case '8':\n case '9':\n return int(ch - '0');\n\n case 'a':\n case 'b':\n case 'c':\n case 'd':\n case 'e':\n case 'f':\n return 10 + int(ch - 'a');\n\n case 'A':\n case 'B':\n case 'C':\n case 'D':\n case 'E':\n case 'F':\n return 10 + int(ch - 'A');\n\n default:\n throw std::runtime_error(\"Invalid hex digit.\");\n }\n }\n\n inline int oct2digit(char ch) const {\n if ((ch >= '0') && (ch <= '7')) {\n return int(ch - '0');\n } else {\n throw std::runtime_error(\"Invalid octal digit.\");\n }\n }\n\n void unescape(std::pair<char *, size_t> &s) const {\n const size_t end = s.second;\n char *str = s.first;\n size_t j = 0;\n\n for (size_t i = 0; i < end; ++i) {\n switch (str[i]) {\n case '\\\\':\n ++i;\n if (i < end) {\n switch (str[i]) {\n case 'b':\n str[j] = '\\b';\n break;\n\n case 'f':\n str[j] = '\\f';\n break;\n\n case 'n':\n str[j] = '\\n';\n break;\n\n case 'r':\n str[j] = '\\r';\n break;\n\n case 't':\n str[j] = '\\t';\n break;\n\n case 'v':\n str[j] = '\\v';\n break;\n\n case 'x':\n i += 2;\n if (i < end) {\n } else {\n str[j] = char(hex2digit(str[i-1]) * 16 + hex2digit(str[i]));\n throw std::runtime_error(\"Unterminated hex escape sequence.\");\n }\n break;\n\n case '0':\n case '1':\n case '2':\n case '3':\n case '4':\n case '5':\n case '6':\n case '7':\n i += 2;\n if (i < end) {\n str[j] = char(oct2digit(str[i-2]) * 64 + oct2digit(str[i-1]) * 8 + oct2digit(str[i]));\n } else {\n throw std::runtime_error(\"Unterminated octal escape sequence.\");\n }\n break;\n\n default:\n \/\/ an unnecessary escape\n str[j] = str[i];\n }\n \n } else {\n throw std::runtime_error(\"Unterminated escape sequence.\");\n }\n break;\n \n default:\n if (i != j) {\n str[j] = str[i];\n }\n }\n\n ++j;\n }\n\n str[j] = '\\0';\n s.second = j;\n }\n\n mutable std::vector<std::pair<char *, size_t> >::iterator itr;\n };\n\n static std::vector<size_t> calculate_reorder(const std::vector<std::string> &names) {\n std::vector<size_t> indexes;\n const std::vector<std::string> &wanted_names = T::column_names();\n\n const size_t num_columns = wanted_names.size();\n indexes.reserve(num_columns);\n for (size_t i = 0; i < num_columns; ++i) {\n const std::string &wanted_name = wanted_names[i];\n size_t j = i;\n\n if (wanted_name != \"*\") {\n std::vector<std::string>::const_iterator itr = std::find(names.begin(), names.end(), wanted_name);\n if (itr == names.end()) {\n std::ostringstream ostr;\n ostr << \"Unable to find wanted column name \\\"\" << wanted_name << \"\\\" in available names: \";\n for (std::vector<std::string>::const_iterator jtr = names.begin(); jtr != names.end(); ++jtr) {\n ostr << \"\\\"\" << *jtr << \"\\\", \";\n }\n throw std::runtime_error(ostr.str());\n }\n j = std::distance(names.begin(), itr);\n }\n\n indexes.push_back(j);\n }\n\n return indexes;\n }\n\n S &m_source;\n std::vector<size_t> m_reorder;\n};\n\n#endif \/* UNESCAPE_COPY_ROW_HPP *\/\n<|endoftext|>"} {"text":"<commit_before>#undef DEBUG\n#include <iostream>\n#include <cstdlib>\n#include <cstdio>\n#include <cmath>\n\n\/\/needed for select\n#include <stdio.h>\n#include <stdlib.h>\n#include <sys\/time.h>\n#include <sys\/types.h>\n#include <unistd.h>\n\n\/\/needed for poll\n\/\/#include <poll.h>\n\n\/\/for connection to server\n#include \"..\/sockets\/SocketW.h\"\nbool ready4data = false;\/\/set to true when streaming starts\nbool inited = false;\nbool stopparsing = false;\ntimeval lastrec;\n\n#include \"parsechunks.cpp\" \/\/chunkstream parsing\n#include \"handshake.cpp\" \/\/handshaking\n#include \"..\/util\/flv_sock.cpp\" \/\/FLV parsing with SocketW\n\nint main(){\n unsigned int ts;\n unsigned int fts = 0;\n unsigned int ftst;\n SWUnixSocket ss;\n\n fd_set pollset;\n struct timeval timeout;\n \/\/0 timeout - return immediately after select call\n timeout.tv_sec = 1; timeout.tv_usec = 0;\n\n \/\/pollfd cinfd[1];\n \/\/cinfd[0].fd = fileno(stdin);\n \/\/cinfd[0].events = POLLIN;\n\n \/\/first timestamp set\n firsttime = getNowMS();\n\n #ifdef DEBUG\n fprintf(stderr, \"Doing handshake...\\n\");\n #endif\n if (doHandshake()){\n #ifdef DEBUG\n fprintf(stderr, \"Handshake succcess!\\n\");\n #endif\n }else{\n #ifdef DEBUG\n fprintf(stderr, \"Handshake fail!\\n\");\n #endif\n return 0;\n }\n #ifdef DEBUG\n fprintf(stderr, \"Starting processing...\\n\");\n #endif\n while (std::cin.good() && std::cout.good()){\n FD_ZERO(&pollset);\/\/clear the polling set\n FD_SET(fileno(stdin), &pollset);\/\/add stdin to polling set\n select(1, &pollset, 0, 0, &timeout);\n \/\/only parse input from stdin if available or not yet init'ed\n if ((!ready4data || (snd_cnt - snd_window_at >= snd_window_size)) && FD_ISSET(0, &pollset)){parseChunk();fflush(stdout);}\n if (ready4data){\n if (!inited){\n \/\/we are ready, connect the socket!\n if (!ss.connect(streamname.c_str())){\n #ifdef DEBUG\n fprintf(stderr, \"Could not connect to server!\\n\");\n #endif\n return 0;\n }\n FLV_Readheader(ss);\/\/read the header, we don't want it\n #ifdef DEBUG\n fprintf(stderr, \"Header read, starting to send video data...\\n\");\n #endif\n inited = true;\n }\n \/\/only send data if previous data has been ACK'ed...\n if (snd_cnt - snd_window_at < snd_window_size){\n if (FLV_GetPacket(ss)){\/\/able to read a full packet?\n ts = FLVbuffer[7] * 256*256*256;\n ts += FLVbuffer[4] * 256*256;\n ts += FLVbuffer[5] * 256;\n ts += FLVbuffer[6];\n if (ts != 0){\n if (fts == 0){fts = ts;ftst = getNowMS();}\n ts -= fts;\n FLVbuffer[7] = ts \/ (256*256*256);\n FLVbuffer[4] = ts \/ (256*256);\n FLVbuffer[5] = ts \/ 256;\n FLVbuffer[6] = ts % 256;\n ts += ftst;\n }else{\n ftst = getNowMS();\n FLVbuffer[7] = ftst \/ (256*256*256);\n FLVbuffer[4] = ftst \/ (256*256);\n FLVbuffer[5] = ftst \/ 256;\n FLVbuffer[6] = ftst % 256;\n }\n SendMedia((unsigned char)FLVbuffer[0], (unsigned char *)FLVbuffer+11, FLV_len-15, ts);\n FLV_Dump();\/\/dump packet and get ready for next\n }\n if ((SWBerr != SWBaseSocket::ok) && (SWBerr != SWBaseSocket::notReady)){\n #ifdef DEBUG\n fprintf(stderr, \"No more data! :-( (%s)\\n\", SWBerr.get_error().c_str());\n #endif\n return 0;\/\/no more input possible! Fail immediately.\n }\n }\n }\n \/\/send ACK if we received a whole window\n if (rec_cnt - rec_window_at > rec_window_size){\n rec_window_at = rec_cnt;\n SendCTL(3, rec_cnt);\/\/send ack (msg 3)\n }\n }\n #ifdef DEBUG\n fprintf(stderr, \"User disconnected.\\n\");\n #endif\n return 0;\n}\/\/main\n<commit_msg>Select poging nummer 2<commit_after>#undef DEBUG\n#include <iostream>\n#include <cstdlib>\n#include <cstdio>\n#include <cmath>\n\n\/\/needed for select\n#include <stdio.h>\n#include <stdlib.h>\n#include <sys\/time.h>\n#include <sys\/types.h>\n#include <unistd.h>\n\n\/\/needed for poll\n\/\/#include <poll.h>\n\n\/\/for connection to server\n#include \"..\/sockets\/SocketW.h\"\nbool ready4data = false;\/\/set to true when streaming starts\nbool inited = false;\nbool stopparsing = false;\ntimeval lastrec;\n\n#include \"parsechunks.cpp\" \/\/chunkstream parsing\n#include \"handshake.cpp\" \/\/handshaking\n#include \"..\/util\/flv_sock.cpp\" \/\/FLV parsing with SocketW\n\nint main(){\n unsigned int ts;\n unsigned int fts = 0;\n unsigned int ftst;\n SWUnixSocket ss;\n\n fd_set pollset;\n struct timeval timeout;\n\n \/\/pollfd cinfd[1];\n \/\/cinfd[0].fd = fileno(stdin);\n \/\/cinfd[0].events = POLLIN;\n\n \/\/first timestamp set\n firsttime = getNowMS();\n\n #ifdef DEBUG\n fprintf(stderr, \"Doing handshake...\\n\");\n #endif\n if (doHandshake()){\n #ifdef DEBUG\n fprintf(stderr, \"Handshake succcess!\\n\");\n #endif\n }else{\n #ifdef DEBUG\n fprintf(stderr, \"Handshake fail!\\n\");\n #endif\n return 0;\n }\n #ifdef DEBUG\n fprintf(stderr, \"Starting processing...\\n\");\n #endif\n while (std::cin.good() && std::cout.good()){\n FD_ZERO(&pollset);\/\/clear the polling set\n FD_SET(fileno(stdin), &pollset);\/\/add stdin to polling set\n timeout.tv_sec = 1; timeout.tv_usec = 0;\n select(1, &pollset, 0, 0, &timeout);\n \/\/only parse input from stdin if available or not yet init'ed\n if ((!ready4data || (snd_cnt - snd_window_at >= snd_window_size)) && FD_ISSET(0, &pollset)){parseChunk();fflush(stdout);}\n if (ready4data){\n if (!inited){\n \/\/we are ready, connect the socket!\n if (!ss.connect(streamname.c_str())){\n #ifdef DEBUG\n fprintf(stderr, \"Could not connect to server!\\n\");\n #endif\n return 0;\n }\n FLV_Readheader(ss);\/\/read the header, we don't want it\n #ifdef DEBUG\n fprintf(stderr, \"Header read, starting to send video data...\\n\");\n #endif\n inited = true;\n }\n \/\/only send data if previous data has been ACK'ed...\n if (snd_cnt - snd_window_at < snd_window_size){\n if (FLV_GetPacket(ss)){\/\/able to read a full packet?\n ts = FLVbuffer[7] * 256*256*256;\n ts += FLVbuffer[4] * 256*256;\n ts += FLVbuffer[5] * 256;\n ts += FLVbuffer[6];\n if (ts != 0){\n if (fts == 0){fts = ts;ftst = getNowMS();}\n ts -= fts;\n FLVbuffer[7] = ts \/ (256*256*256);\n FLVbuffer[4] = ts \/ (256*256);\n FLVbuffer[5] = ts \/ 256;\n FLVbuffer[6] = ts % 256;\n ts += ftst;\n }else{\n ftst = getNowMS();\n FLVbuffer[7] = ftst \/ (256*256*256);\n FLVbuffer[4] = ftst \/ (256*256);\n FLVbuffer[5] = ftst \/ 256;\n FLVbuffer[6] = ftst % 256;\n }\n SendMedia((unsigned char)FLVbuffer[0], (unsigned char *)FLVbuffer+11, FLV_len-15, ts);\n FLV_Dump();\/\/dump packet and get ready for next\n }\n if ((SWBerr != SWBaseSocket::ok) && (SWBerr != SWBaseSocket::notReady)){\n #ifdef DEBUG\n fprintf(stderr, \"No more data! :-( (%s)\\n\", SWBerr.get_error().c_str());\n #endif\n return 0;\/\/no more input possible! Fail immediately.\n }\n }\n }\n \/\/send ACK if we received a whole window\n if (rec_cnt - rec_window_at > rec_window_size){\n rec_window_at = rec_cnt;\n SendCTL(3, rec_cnt);\/\/send ack (msg 3)\n }\n }\n #ifdef DEBUG\n fprintf(stderr, \"User disconnected.\\n\");\n #endif\n return 0;\n}\/\/main\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Software License Agreement (BSD License)\n *\n * Point Cloud Library (PCL) - www.pointclouds.org\n * Copyright (c) 2010-2011, Willow Garage, Inc.\n *\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following\n * disclaimer in the documentation and\/or other materials provided\n * with the distribution.\n * * Neither the name of Willow Garage, Inc. nor the names of its\n * contributors may be used to endorse or promote products derived\n * from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n * $Id$\n *\n *\/\n\n#ifndef PCL_IO_PCD_IO_IMPL_H_\n#define PCL_IO_PCD_IO_IMPL_H_\n\n#include <fstream>\n#include <fcntl.h>\n#include <string>\n#include <stdlib.h>\n\n#ifdef _WIN32\n# include <io.h>\n# include <windows.h>\n# define pcl_open _open\n# define pcl_close(fd) _close(fd)\n# define pcl_lseek(fd,offset,origin) _lseek(fd,offset,origin)\n#else\n# include <sys\/mman.h>\n# define pcl_open open\n# define pcl_close(fd) close(fd)\n# define pcl_lseek(fd,offset,origin) lseek(fd,offset,origin)\n#endif\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate <typename PointT> std::string\npcl::PCDWriter::generateHeaderBinary (const pcl::PointCloud<PointT> &cloud, const int nr_points)\n{\n std::ostringstream oss;\n\n oss << \"# .PCD v0.7 - Point Cloud Data file format\"\n \"\\nVERSION 0.7\"\n \"\\nFIELDS\";\n\n std::vector<sensor_msgs::PointField> fields;\n pcl::getFields (cloud, fields);\n \n std::stringstream field_names, field_types, field_sizes, field_counts;\n for (size_t i = 0; i < fields.size (); ++i)\n {\n if (fields[i].name == \"_\")\n continue;\n \/\/ Add the regular dimension\n field_names << \" \" << fields[i].name;\n field_sizes << \" \" << pcl::getFieldSize (fields[i].datatype);\n field_types << \" \" << pcl::getFieldType (fields[i].datatype);\n int count = abs ((int)fields[i].count);\n if (count == 0) count = 1; \/\/ check for 0 counts (coming from older converter code)\n field_counts << \" \" << count;\n }\n oss << field_names.str ();\n oss << \"\\nSIZE\" << field_sizes.str () \n << \"\\nTYPE\" << field_types.str () \n << \"\\nCOUNT\" << field_counts.str ();\n \/\/ If the user passes in a number of points value, use that instead\n if (nr_points != std::numeric_limits<int>::max ())\n oss << \"\\nWIDTH \" << nr_points << \"\\nHEIGHT \" << 1 << \"\\n\";\n else\n oss << \"\\nWIDTH \" << cloud.width << \"\\nHEIGHT \" << cloud.height << \"\\n\";\n\n oss << \"VIEWPOINT \" << cloud.sensor_origin_[0] << \" \" << cloud.sensor_origin_[1] << \" \" << cloud.sensor_origin_[2] << \" \" << \n cloud.sensor_orientation_.w () << \" \" << \n cloud.sensor_orientation_.x () << \" \" << \n cloud.sensor_orientation_.y () << \" \" << \n cloud.sensor_orientation_.z () << \"\\n\";\n \n \/\/ If the user passes in a number of points value, use that instead\n if (nr_points != std::numeric_limits<int>::max ())\n oss << \"POINTS \" << nr_points << \"\\n\";\n else\n oss << \"POINTS \" << cloud.points.size () << \"\\n\";\n\n return (oss.str ());\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate <typename PointT> int\npcl::PCDWriter::writeBinary (const std::string &file_name, \n const pcl::PointCloud<PointT> &cloud)\n{\n if (cloud.points.empty ())\n {\n throw pcl::IOException (\"[pcl::PCDWriter::writeBinary] Input point cloud has no data!\");\n return (-1);\n }\n int data_idx = 0;\n std::ostringstream oss;\n oss << generateHeaderBinary<PointT> (cloud) << \"DATA binary\\n\";\n oss.flush ();\n data_idx = oss.tellp ();\n\n#if _WIN32\n HANDLE h_native_file = CreateFile (file_name.c_str (), GENERIC_READ | GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);\n if(h_native_file == INVALID_HANDLE_VALUE)\n {\n throw pcl::IOException (\"[pcl::PCDWriter::writeBinary] Error during CreateFile!\");\n return (-1);\n }\n#else\n int fd = pcl_open (file_name.c_str (), O_RDWR | O_CREAT | O_TRUNC, (mode_t)0600);\n if (fd < 0)\n {\n throw pcl::IOException (\"[pcl::PCDWriter::writeBinary] Error during open!\");\n return (-1);\n }\n\n std::vector<sensor_msgs::PointField> fields;\n std::vector<int> fields_sizes;\n size_t fsize = 0;\n size_t data_size = 0;\n size_t nri = 0;\n pcl::getFields (cloud, fields);\n \/\/ Compute the total size of the fields\n for (size_t i = 0; i < fields.size (); ++i)\n {\n if (fields[i].name == \"_\")\n continue;\n \n int fs = fields[i].count * getFieldSize (fields[i].datatype);\n fsize += fs;\n fields_sizes.push_back (fs);\n fields[nri++] = fields[i];\n }\n fields.resize (nri);\n \n data_size = cloud.points.size () * fsize;\n\n \/\/ Stretch the file size to the size of the data\n int result = pcl_lseek (fd, getpagesize () + data_size - 1, SEEK_SET);\n if (result < 0)\n {\n pcl_close (fd);\n throw pcl::IOException (\"[pcl::PCDWriter::writeBinary] Error during lseek ()!\");\n return (-1);\n }\n \/\/ Write a bogus entry so that the new file size comes in effect\n result = ::write (fd, \"\", 1);\n if (result != 1)\n {\n pcl_close (fd);\n throw pcl::IOException (\"[pcl::PCDWriter::writeBinary] Error during write ()!\");\n return (-1);\n }\n#endif\n \/\/ Prepare the map\n#if _WIN32\n HANDLE fm = CreateFileMapping (h_native_file, NULL, PAGE_READWRITE, 0, data_idx + cloud.data.size (), NULL);\n char *map = static_cast<char*>(MapViewOfFile (fm, FILE_MAP_READ | FILE_MAP_WRITE, 0, 0, data_idx + cloud.data.size ()));\n CloseHandle (fm);\n\n#else\n char *map = (char*)mmap (0, data_idx + data_size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);\n if (map == MAP_FAILED)\n {\n pcl_close (fd);\n throw pcl::IOException (\"[pcl::PCDWriter::writeBinary] Error during mmap ()!\");\n return (-1);\n }\n#endif\n\n \/\/ Copy the header\n memcpy (&map[0], oss.str ().c_str (), data_idx);\n\n \/\/ Copy the data\n char *out = &map[0] + data_idx;\n for (size_t i = 0; i < cloud.points.size (); ++i)\n {\n int nrj = 0;\n for (size_t j = 0; j < fields.size (); ++j)\n {\n memcpy (out, (const char*)&cloud.points[i] + fields[j].offset, fields_sizes[nrj]);\n out += fields_sizes[nrj++];\n }\n }\n\n \/\/ Unmap the pages of memory\n#if _WIN32\n UnmapViewOfFile (map);\n#else\n if (munmap (map, (data_idx + data_size)) == -1)\n {\n pcl_close (fd);\n throw pcl::IOException (\"[pcl::PCDWriter::writeBinary] Error during munmap ()!\");\n return (-1);\n }\n#endif\n \/\/ Close file\n#if _WIN32\n CloseHandle(h_native_file);\n#else\n pcl_close (fd);\n#endif\n return (0);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate <typename PointT> int\npcl::PCDWriter::writeBinary (const std::string &file_name, \n const pcl::PointCloud<PointT> &cloud, \n const std::vector<int> &indices)\n{\n if (cloud.points.empty () || indices.empty ())\n {\n throw pcl::IOException (\"[pcl::PCDWriter::writeBinary] Input point cloud has no data or empty indices given!\");\n return (-1);\n }\n int data_idx = 0;\n std::ostringstream oss;\n oss << generateHeaderBinary<PointT> (cloud, indices.size ()) << \"DATA binary\\n\";\n oss.flush ();\n data_idx = oss.tellp ();\n\n#if _WIN32\n HANDLE h_native_file = CreateFile (file_name.c_str (), GENERIC_READ | GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);\n if(h_native_file == INVALID_HANDLE_VALUE)\n {\n throw pcl::IOException (\"[pcl::PCDWriter::writeBinary] Error during CreateFile!\");\n return (-1);\n }\n#else\n int fd = pcl_open (file_name.c_str (), O_RDWR | O_CREAT | O_TRUNC, (mode_t)0600);\n if (fd < 0)\n {\n throw pcl::IOException (\"[pcl::PCDWriter::writeBinary] Error during open!\");\n return (-1);\n }\n\n std::vector<sensor_msgs::PointField> fields;\n std::vector<int> fields_sizes;\n size_t fsize = 0;\n size_t data_size = 0;\n size_t nri = 0;\n pcl::getFields (cloud, fields);\n \/\/ Compute the total size of the fields\n for (size_t i = 0; i < fields.size (); ++i)\n {\n if (fields[i].name == \"_\")\n continue;\n \n int fs = fields[i].count * getFieldSize (fields[i].datatype);\n fsize += fs;\n fields_sizes.push_back (fs);\n fields[nri++] = fields[i];\n }\n fields.resize (nri);\n \n data_size = indices.size () * fsize;\n\n \/\/ Stretch the file size to the size of the data\n int result = pcl_lseek (fd, getpagesize () + data_size - 1, SEEK_SET);\n if (result < 0)\n {\n pcl_close (fd);\n throw pcl::IOException (\"[pcl::PCDWriter::writeBinary] Error during lseek ()!\");\n return (-1);\n }\n \/\/ Write a bogus entry so that the new file size comes in effect\n result = ::write (fd, \"\", 1);\n if (result != 1)\n {\n pcl_close (fd);\n throw pcl::IOException (\"[pcl::PCDWriter::writeBinary] Error during write ()!\");\n return (-1);\n }\n#endif\n \/\/ Prepare the map\n#if _WIN32\n HANDLE fm = CreateFileMapping (h_native_file, NULL, PAGE_READWRITE, 0, data_idx + cloud.data.size (), NULL);\n char *map = static_cast<char*>(MapViewOfFile (fm, FILE_MAP_READ | FILE_MAP_WRITE, 0, 0, data_idx + cloud.data.size ()));\n CloseHandle (fm);\n\n#else\n char *map = (char*)mmap (0, data_idx + data_size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);\n if (map == MAP_FAILED)\n {\n pcl_close (fd);\n throw pcl::IOException (\"[pcl::PCDWriter::writeBinary] Error during mmap ()!\");\n return (-1);\n }\n#endif\n\n \/\/ Copy the header\n memcpy (&map[0], oss.str ().c_str (), data_idx);\n\n char *out = &map[0] + data_idx;\n \/\/ Copy the data\n for (size_t i = 0; i < indices.size (); ++i)\n {\n int nrj = 0;\n for (size_t j = 0; j < fields.size (); ++j)\n {\n memcpy (out, (const char*)&cloud.points[indices[i]] + fields[j].offset, fields_sizes[nrj]);\n out += fields_sizes[nrj++];\n }\n }\n\n \/\/ Unmap the pages of memory\n#if _WIN32\n UnmapViewOfFile (map);\n#else\n if (munmap (map, (data_idx + data_size)) == -1)\n {\n pcl_close (fd);\n throw pcl::IOException (\"[pcl::PCDWriter::writeBinary] Error during munmap ()!\");\n return (-1);\n }\n#endif\n \/\/ Close file\n#if _WIN32\n CloseHandle(h_native_file);\n#else\n pcl_close (fd);\n#endif\n return (0);\n}\n\n#endif \/\/#ifndef PCL_IO_PCD_IO_H_\n\n<commit_msg>fiw the windows path in pcd_io.hpp<commit_after>\/*\n * Software License Agreement (BSD License)\n *\n * Point Cloud Library (PCL) - www.pointclouds.org\n * Copyright (c) 2010-2011, Willow Garage, Inc.\n *\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following\n * disclaimer in the documentation and\/or other materials provided\n * with the distribution.\n * * Neither the name of Willow Garage, Inc. nor the names of its\n * contributors may be used to endorse or promote products derived\n * from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n * $Id$\n *\n *\/\n\n#ifndef PCL_IO_PCD_IO_IMPL_H_\n#define PCL_IO_PCD_IO_IMPL_H_\n\n#include <fstream>\n#include <fcntl.h>\n#include <string>\n#include <stdlib.h>\n\n#ifdef _WIN32\n# include <io.h>\n# include <windows.h>\n# define pcl_open _open\n# define pcl_close(fd) _close(fd)\n# define pcl_lseek(fd,offset,origin) _lseek(fd,offset,origin)\n#else\n# include <sys\/mman.h>\n# define pcl_open open\n# define pcl_close(fd) close(fd)\n# define pcl_lseek(fd,offset,origin) lseek(fd,offset,origin)\n#endif\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate <typename PointT> std::string\npcl::PCDWriter::generateHeaderBinary (const pcl::PointCloud<PointT> &cloud, const int nr_points)\n{\n std::ostringstream oss;\n\n oss << \"# .PCD v0.7 - Point Cloud Data file format\"\n \"\\nVERSION 0.7\"\n \"\\nFIELDS\";\n\n std::vector<sensor_msgs::PointField> fields;\n pcl::getFields (cloud, fields);\n \n std::stringstream field_names, field_types, field_sizes, field_counts;\n for (size_t i = 0; i < fields.size (); ++i)\n {\n if (fields[i].name == \"_\")\n continue;\n \/\/ Add the regular dimension\n field_names << \" \" << fields[i].name;\n field_sizes << \" \" << pcl::getFieldSize (fields[i].datatype);\n field_types << \" \" << pcl::getFieldType (fields[i].datatype);\n int count = abs ((int)fields[i].count);\n if (count == 0) count = 1; \/\/ check for 0 counts (coming from older converter code)\n field_counts << \" \" << count;\n }\n oss << field_names.str ();\n oss << \"\\nSIZE\" << field_sizes.str () \n << \"\\nTYPE\" << field_types.str () \n << \"\\nCOUNT\" << field_counts.str ();\n \/\/ If the user passes in a number of points value, use that instead\n if (nr_points != std::numeric_limits<int>::max ())\n oss << \"\\nWIDTH \" << nr_points << \"\\nHEIGHT \" << 1 << \"\\n\";\n else\n oss << \"\\nWIDTH \" << cloud.width << \"\\nHEIGHT \" << cloud.height << \"\\n\";\n\n oss << \"VIEWPOINT \" << cloud.sensor_origin_[0] << \" \" << cloud.sensor_origin_[1] << \" \" << cloud.sensor_origin_[2] << \" \" << \n cloud.sensor_orientation_.w () << \" \" << \n cloud.sensor_orientation_.x () << \" \" << \n cloud.sensor_orientation_.y () << \" \" << \n cloud.sensor_orientation_.z () << \"\\n\";\n \n \/\/ If the user passes in a number of points value, use that instead\n if (nr_points != std::numeric_limits<int>::max ())\n oss << \"POINTS \" << nr_points << \"\\n\";\n else\n oss << \"POINTS \" << cloud.points.size () << \"\\n\";\n\n return (oss.str ());\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate <typename PointT> int\npcl::PCDWriter::writeBinary (const std::string &file_name, \n const pcl::PointCloud<PointT> &cloud)\n{\n if (cloud.points.empty ())\n {\n throw pcl::IOException (\"[pcl::PCDWriter::writeBinary] Input point cloud has no data!\");\n return (-1);\n }\n int data_idx = 0;\n std::ostringstream oss;\n oss << generateHeaderBinary<PointT> (cloud) << \"DATA binary\\n\";\n oss.flush ();\n data_idx = oss.tellp ();\n\n#if _WIN32\n HANDLE h_native_file = CreateFile (file_name.c_str (), GENERIC_READ | GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);\n if(h_native_file == INVALID_HANDLE_VALUE)\n {\n throw pcl::IOException (\"[pcl::PCDWriter::writeBinary] Error during CreateFile!\");\n return (-1);\n }\n#else\n int fd = pcl_open (file_name.c_str (), O_RDWR | O_CREAT | O_TRUNC, (mode_t)0600);\n if (fd < 0)\n {\n throw pcl::IOException (\"[pcl::PCDWriter::writeBinary] Error during open!\");\n return (-1);\n }\n#endif\n\n std::vector<sensor_msgs::PointField> fields;\n std::vector<int> fields_sizes;\n size_t fsize = 0;\n size_t data_size = 0;\n size_t nri = 0;\n pcl::getFields (cloud, fields);\n \/\/ Compute the total size of the fields\n for (size_t i = 0; i < fields.size (); ++i)\n {\n if (fields[i].name == \"_\")\n continue;\n \n int fs = fields[i].count * getFieldSize (fields[i].datatype);\n fsize += fs;\n fields_sizes.push_back (fs);\n fields[nri++] = fields[i];\n }\n fields.resize (nri);\n \n data_size = cloud.points.size () * fsize;\n\n \/\/ Prepare the map\n#if _WIN32\n HANDLE fm = CreateFileMapping (h_native_file, NULL, PAGE_READWRITE, 0, data_idx + data_size, NULL);\n char *map = static_cast<char*>(MapViewOfFile (fm, FILE_MAP_READ | FILE_MAP_WRITE, 0, 0, data_idx + data_size));\n CloseHandle (fm);\n\n#else\n \/\/ Stretch the file size to the size of the data\n int result = pcl_lseek (fd, getpagesize () + data_size - 1, SEEK_SET);\n if (result < 0)\n {\n pcl_close (fd);\n throw pcl::IOException (\"[pcl::PCDWriter::writeBinary] Error during lseek ()!\");\n return (-1);\n }\n \/\/ Write a bogus entry so that the new file size comes in effect\n result = ::write (fd, \"\", 1);\n if (result != 1)\n {\n pcl_close (fd);\n throw pcl::IOException (\"[pcl::PCDWriter::writeBinary] Error during write ()!\");\n return (-1);\n }\n\n char *map = (char*)mmap (0, data_idx + data_size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);\n if (map == MAP_FAILED)\n {\n pcl_close (fd);\n throw pcl::IOException (\"[pcl::PCDWriter::writeBinary] Error during mmap ()!\");\n return (-1);\n }\n#endif\n\n \/\/ Copy the header\n memcpy (&map[0], oss.str ().c_str (), data_idx);\n\n \/\/ Copy the data\n char *out = &map[0] + data_idx;\n for (size_t i = 0; i < cloud.points.size (); ++i)\n {\n int nrj = 0;\n for (size_t j = 0; j < fields.size (); ++j)\n {\n memcpy (out, (const char*)&cloud.points[i] + fields[j].offset, fields_sizes[nrj]);\n out += fields_sizes[nrj++];\n }\n }\n\n \/\/ Unmap the pages of memory\n#if _WIN32\n UnmapViewOfFile (map);\n#else\n if (munmap (map, (data_idx + data_size)) == -1)\n {\n pcl_close (fd);\n throw pcl::IOException (\"[pcl::PCDWriter::writeBinary] Error during munmap ()!\");\n return (-1);\n }\n#endif\n \/\/ Close file\n#if _WIN32\n CloseHandle(h_native_file);\n#else\n pcl_close (fd);\n#endif\n return (0);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate <typename PointT> int\npcl::PCDWriter::writeBinary (const std::string &file_name, \n const pcl::PointCloud<PointT> &cloud, \n const std::vector<int> &indices)\n{\n if (cloud.points.empty () || indices.empty ())\n {\n throw pcl::IOException (\"[pcl::PCDWriter::writeBinary] Input point cloud has no data or empty indices given!\");\n return (-1);\n }\n int data_idx = 0;\n std::ostringstream oss;\n oss << generateHeaderBinary<PointT> (cloud, indices.size ()) << \"DATA binary\\n\";\n oss.flush ();\n data_idx = oss.tellp ();\n\n#if _WIN32\n HANDLE h_native_file = CreateFile (file_name.c_str (), GENERIC_READ | GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);\n if(h_native_file == INVALID_HANDLE_VALUE)\n {\n throw pcl::IOException (\"[pcl::PCDWriter::writeBinary] Error during CreateFile!\");\n return (-1);\n }\n#else\n int fd = pcl_open (file_name.c_str (), O_RDWR | O_CREAT | O_TRUNC, (mode_t)0600);\n if (fd < 0)\n {\n throw pcl::IOException (\"[pcl::PCDWriter::writeBinary] Error during open!\");\n return (-1);\n }\n#endif\n\n std::vector<sensor_msgs::PointField> fields;\n std::vector<int> fields_sizes;\n size_t fsize = 0;\n size_t data_size = 0;\n size_t nri = 0;\n pcl::getFields (cloud, fields);\n \/\/ Compute the total size of the fields\n for (size_t i = 0; i < fields.size (); ++i)\n {\n if (fields[i].name == \"_\")\n continue;\n \n int fs = fields[i].count * getFieldSize (fields[i].datatype);\n fsize += fs;\n fields_sizes.push_back (fs);\n fields[nri++] = fields[i];\n }\n fields.resize (nri);\n \n data_size = indices.size () * fsize;\n\n \/\/ Prepare the map\n#if _WIN32\n HANDLE fm = CreateFileMapping (h_native_file, NULL, PAGE_READWRITE, 0, data_idx + data_size, NULL);\n char *map = static_cast<char*>(MapViewOfFile (fm, FILE_MAP_READ | FILE_MAP_WRITE, 0, 0, data_idx + data_size));\n CloseHandle (fm);\n\n#else\n \/\/ Stretch the file size to the size of the data\n int result = pcl_lseek (fd, getpagesize () + data_size - 1, SEEK_SET);\n if (result < 0)\n {\n pcl_close (fd);\n throw pcl::IOException (\"[pcl::PCDWriter::writeBinary] Error during lseek ()!\");\n return (-1);\n }\n \/\/ Write a bogus entry so that the new file size comes in effect\n result = ::write (fd, \"\", 1);\n if (result != 1)\n {\n pcl_close (fd);\n throw pcl::IOException (\"[pcl::PCDWriter::writeBinary] Error during write ()!\");\n return (-1);\n }\n\n char *map = (char*)mmap (0, data_idx + data_size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);\n if (map == MAP_FAILED)\n {\n pcl_close (fd);\n throw pcl::IOException (\"[pcl::PCDWriter::writeBinary] Error during mmap ()!\");\n return (-1);\n }\n#endif\n\n \/\/ Copy the header\n memcpy (&map[0], oss.str ().c_str (), data_idx);\n\n char *out = &map[0] + data_idx;\n \/\/ Copy the data\n for (size_t i = 0; i < indices.size (); ++i)\n {\n int nrj = 0;\n for (size_t j = 0; j < fields.size (); ++j)\n {\n memcpy (out, (const char*)&cloud.points[indices[i]] + fields[j].offset, fields_sizes[nrj]);\n out += fields_sizes[nrj++];\n }\n }\n\n \/\/ Unmap the pages of memory\n#if _WIN32\n UnmapViewOfFile (map);\n#else\n if (munmap (map, (data_idx + data_size)) == -1)\n {\n pcl_close (fd);\n throw pcl::IOException (\"[pcl::PCDWriter::writeBinary] Error during munmap ()!\");\n return (-1);\n }\n#endif\n \/\/ Close file\n#if _WIN32\n CloseHandle(h_native_file);\n#else\n pcl_close (fd);\n#endif\n return (0);\n}\n\n#endif \/\/#ifndef PCL_IO_PCD_IO_H_\n\n<|endoftext|>"} {"text":"<commit_before>#pragma once\n\n#include \"vfs\/platform.hpp\"\n#include \"vfs\/file.h\"\n\n\nnamespace vfs {\n\n \/\/----------------------------------------------------------------------------------------------\n using file_view_impl = class win_file_view;\n \/\/----------------------------------------------------------------------------------------------\n\n\n \/\/----------------------------------------------------------------------------------------------\n class win_file_view\n {\n\tprotected:\n\t\t\/\/------------------------------------------------------------------------------------------\n win_file_view(file_sptr spFile, int64_t viewSize)\n : spFile_(std::move(spFile))\n , name_(spFile_->fileName())\n , fileMappingHandle_(nullptr)\n , pData_(nullptr)\n , pCursor_(nullptr)\n , mappedTotalSize_(viewSize)\n {\n\t\t\tvfs_check(spFile_->isValid());\n map(viewSize, false);\n }\n\n \/\/------------------------------------------------------------------------------------------\n win_file_view(const path &name, int64_t size, bool openExistent)\n : name_(name)\n , fileMappingHandle_(nullptr)\n , pData_(nullptr)\n , pCursor_(nullptr)\n , mappedTotalSize_(size)\n {\n map(size, openExistent);\n }\n\n\t\t\/\/------------------------------------------------------------------------------------------\n ~win_file_view()\n {\n flush();\n unmap();\n\n if (fileMappingHandle_ != nullptr)\n {\n CloseHandle(fileMappingHandle_);\n }\n }\n\n\t\t\/\/------------------------------------------------------------------------------------------\n bool map(int64_t viewSize, bool openExistent)\n {\n const auto access = spFile_ ? spFile_->fileAccess() : file_access::read_write;\n\n if (spFile_)\n {\n if (!spFile_->createMapping(viewSize))\n {\n return false;\n }\n\n fileMappingHandle_ = spFile_->nativeFileMappingHandle();\n fileTotalSize_ = spFile_->size();\n }\n else\n {\n if (openExistent)\n {\n fileMappingHandle_ = OpenFileMapping(FILE_MAP_ALL_ACCESS, FALSE, name_.c_str());\n }\n else\n {\n fileMappingHandle_ = CreateFileMapping\n (\n INVALID_HANDLE_VALUE,\n nullptr,\n PAGE_READWRITE,\n DWORD(viewSize >> 32), DWORD((viewSize << 32) >> 32),\n name_.c_str()\n );\n }\n\n if (fileMappingHandle_ == nullptr)\n {\n const auto errorCode = GetLastError();\n vfs_errorf(\"%sFileMapping(%ws) failed with error: %s\", openExistent ? \"Open\" : \"Create\", name_.c_str(), get_last_error_as_string(errorCode).c_str());\n return false;\n }\n\n fileTotalSize_ = viewSize;\n }\n\n const auto fileMapAccess = (\n (access == file_access::read_only)\n ? FILE_MAP_READ\n : ((access == file_access::write_only)\n ? FILE_MAP_WRITE\n : FILE_MAP_ALL_ACCESS\n )\n );\n\n pData_ = reinterpret_cast<uint8_t*>(MapViewOfFile(fileMappingHandle_, fileMapAccess, 0, 0, 0));\n pCursor_ = pData_;\n\n if (pData_ == nullptr)\n {\n const auto errorCode = GetLastError();\n vfs_errorf(\"MapViewOfFile(%ws) failed with error: %s\", name_.c_str(), get_last_error_as_string(errorCode).c_str());\n return false;\n }\n\n MEMORY_BASIC_INFORMATION memInfo;\n const auto dwInfoBytesCount = VirtualQuery(pData_, &memInfo, sizeof(memInfo));\n if (dwInfoBytesCount != 0)\n {\n mappedTotalSize_ = memInfo.RegionSize;\n }\n\n return true;\n }\n\n\t\t\/\/------------------------------------------------------------------------------------------\n bool unmap()\n {\n if (pData_ && !UnmapViewOfFile(pData_))\n {\n return false;\n }\n return true;\n }\n\n\t\t\/\/------------------------------------------------------------------------------------------\n bool flush()\n {\n if (!FlushViewOfFile(pData_, 0))\n {\n return false;\n }\n return true;\n }\n\n\t\t\/\/------------------------------------------------------------------------------------------\n int64_t read(uint8_t *dst, int64_t sizeInBytes)\n {\n if (canMoveCursor(sizeInBytes))\n {\n memcpy(dst, pCursor_, sizeInBytes);\n pCursor_ += sizeInBytes;\n return sizeInBytes;\n }\n return 0;\n }\n\n\t\t\/\/------------------------------------------------------------------------------------------\n int64_t write(const uint8_t *src, int64_t sizeInBytes)\n {\n if (canMoveCursor(sizeInBytes))\n {\n memcpy(pCursor_, src, sizeInBytes);\n pCursor_ += sizeInBytes;\n return sizeInBytes;\n }\n return 0;\n }\n\n\t\t\/\/------------------------------------------------------------------------------------------\n bool isValid() const\n {\n return pData_ != nullptr;\n }\n\n\t\t\/\/------------------------------------------------------------------------------------------\n int64_t totalSize() const\n {\n return fileTotalSize_;\n }\n\n\t\t\/\/------------------------------------------------------------------------------------------\n bool canMoveCursor(int64_t offsetInBytes) const\n {\n return isValid() && (pCursor_ - pData_ + offsetInBytes) <= mappedTotalSize_;\n }\n\n\t\t\/\/------------------------------------------------------------------------------------------\n template<typename T = uint8_t>\n T* data()\n {\n return reinterpret_cast<T*>(pData_);\n }\n\n\t\t\/\/------------------------------------------------------------------------------------------\n uint8_t* data()\n {\n return data<>();\n }\n\n\t\t\/\/------------------------------------------------------------------------------------------\n template<typename T = uint8_t>\n T* cursor()\n {\n return reinterpret_cast<T*>(pCursor_);\n }\n\n\t\t\/\/------------------------------------------------------------------------------------------\n bool skip(int64_t offsetInBytes)\n {\n if (canMoveCursor(offsetInBytes))\n {\n pCursor_ += offsetInBytes;\n return true;\n }\n return false;\n }\n\n\tprivate:\n\t\t\/\/------------------------------------------------------------------------------------------\n file_sptr spFile_;\n path name_;\n HANDLE fileMappingHandle_;\n uint8_t *pData_;\n uint8_t *pCursor_;\n int64_t fileTotalSize_;\n int64_t mappedTotalSize_;\n };\n \/\/----------------------------------------------------------------------------------------------\n\n} \/*vfs*\/\n<commit_msg>Removed deleted included file<commit_after>#pragma once\n\n#include \"vfs\/platform.hpp\"\n\n\nnamespace vfs {\n\n \/\/----------------------------------------------------------------------------------------------\n using file_view_impl = class win_file_view;\n \/\/----------------------------------------------------------------------------------------------\n\n\n \/\/----------------------------------------------------------------------------------------------\n class win_file_view\n {\n\tprotected:\n\t\t\/\/------------------------------------------------------------------------------------------\n win_file_view(file_sptr spFile, int64_t viewSize)\n : spFile_(std::move(spFile))\n , name_(spFile_->fileName())\n , fileMappingHandle_(nullptr)\n , pData_(nullptr)\n , pCursor_(nullptr)\n , mappedTotalSize_(viewSize)\n {\n\t\t\tvfs_check(spFile_->isValid());\n map(viewSize, false);\n }\n\n \/\/------------------------------------------------------------------------------------------\n win_file_view(const path &name, int64_t size, bool openExistent)\n : name_(name)\n , fileMappingHandle_(nullptr)\n , pData_(nullptr)\n , pCursor_(nullptr)\n , mappedTotalSize_(size)\n {\n map(size, openExistent);\n }\n\n\t\t\/\/------------------------------------------------------------------------------------------\n ~win_file_view()\n {\n flush();\n unmap();\n\n if (fileMappingHandle_ != nullptr)\n {\n CloseHandle(fileMappingHandle_);\n }\n }\n\n\t\t\/\/------------------------------------------------------------------------------------------\n bool map(int64_t viewSize, bool openExistent)\n {\n const auto access = spFile_ ? spFile_->fileAccess() : file_access::read_write;\n\n if (spFile_)\n {\n if (!spFile_->createMapping(viewSize))\n {\n return false;\n }\n\n fileMappingHandle_ = spFile_->nativeFileMappingHandle();\n fileTotalSize_ = spFile_->size();\n }\n else\n {\n if (openExistent)\n {\n fileMappingHandle_ = OpenFileMapping(FILE_MAP_ALL_ACCESS, FALSE, name_.c_str());\n }\n else\n {\n fileMappingHandle_ = CreateFileMapping\n (\n INVALID_HANDLE_VALUE,\n nullptr,\n PAGE_READWRITE,\n DWORD(viewSize >> 32), DWORD((viewSize << 32) >> 32),\n name_.c_str()\n );\n }\n\n if (fileMappingHandle_ == nullptr)\n {\n const auto errorCode = GetLastError();\n vfs_errorf(\"%sFileMapping(%ws) failed with error: %s\", openExistent ? \"Open\" : \"Create\", name_.c_str(), get_last_error_as_string(errorCode).c_str());\n return false;\n }\n\n fileTotalSize_ = viewSize;\n }\n\n const auto fileMapAccess = (\n (access == file_access::read_only)\n ? FILE_MAP_READ\n : ((access == file_access::write_only)\n ? FILE_MAP_WRITE\n : FILE_MAP_ALL_ACCESS\n )\n );\n\n pData_ = reinterpret_cast<uint8_t*>(MapViewOfFile(fileMappingHandle_, fileMapAccess, 0, 0, 0));\n pCursor_ = pData_;\n\n if (pData_ == nullptr)\n {\n const auto errorCode = GetLastError();\n vfs_errorf(\"MapViewOfFile(%ws) failed with error: %s\", name_.c_str(), get_last_error_as_string(errorCode).c_str());\n return false;\n }\n\n MEMORY_BASIC_INFORMATION memInfo;\n const auto dwInfoBytesCount = VirtualQuery(pData_, &memInfo, sizeof(memInfo));\n if (dwInfoBytesCount != 0)\n {\n mappedTotalSize_ = memInfo.RegionSize;\n }\n\n return true;\n }\n\n\t\t\/\/------------------------------------------------------------------------------------------\n bool unmap()\n {\n if (pData_ && !UnmapViewOfFile(pData_))\n {\n return false;\n }\n return true;\n }\n\n\t\t\/\/------------------------------------------------------------------------------------------\n bool flush()\n {\n if (!FlushViewOfFile(pData_, 0))\n {\n return false;\n }\n return true;\n }\n\n\t\t\/\/------------------------------------------------------------------------------------------\n int64_t read(uint8_t *dst, int64_t sizeInBytes)\n {\n if (canMoveCursor(sizeInBytes))\n {\n memcpy(dst, pCursor_, sizeInBytes);\n pCursor_ += sizeInBytes;\n return sizeInBytes;\n }\n return 0;\n }\n\n\t\t\/\/------------------------------------------------------------------------------------------\n int64_t write(const uint8_t *src, int64_t sizeInBytes)\n {\n if (canMoveCursor(sizeInBytes))\n {\n memcpy(pCursor_, src, sizeInBytes);\n pCursor_ += sizeInBytes;\n return sizeInBytes;\n }\n return 0;\n }\n\n\t\t\/\/------------------------------------------------------------------------------------------\n bool isValid() const\n {\n return pData_ != nullptr;\n }\n\n\t\t\/\/------------------------------------------------------------------------------------------\n int64_t totalSize() const\n {\n return fileTotalSize_;\n }\n\n\t\t\/\/------------------------------------------------------------------------------------------\n bool canMoveCursor(int64_t offsetInBytes) const\n {\n return isValid() && (pCursor_ - pData_ + offsetInBytes) <= mappedTotalSize_;\n }\n\n\t\t\/\/------------------------------------------------------------------------------------------\n template<typename T = uint8_t>\n T* data()\n {\n return reinterpret_cast<T*>(pData_);\n }\n\n\t\t\/\/------------------------------------------------------------------------------------------\n uint8_t* data()\n {\n return data<>();\n }\n\n\t\t\/\/------------------------------------------------------------------------------------------\n template<typename T = uint8_t>\n T* cursor()\n {\n return reinterpret_cast<T*>(pCursor_);\n }\n\n\t\t\/\/------------------------------------------------------------------------------------------\n bool skip(int64_t offsetInBytes)\n {\n if (canMoveCursor(offsetInBytes))\n {\n pCursor_ += offsetInBytes;\n return true;\n }\n return false;\n }\n\n\tprivate:\n\t\t\/\/------------------------------------------------------------------------------------------\n file_sptr spFile_;\n path name_;\n HANDLE fileMappingHandle_;\n uint8_t *pData_;\n uint8_t *pCursor_;\n int64_t fileTotalSize_;\n int64_t mappedTotalSize_;\n };\n \/\/----------------------------------------------------------------------------------------------\n\n} \/*vfs*\/\n<|endoftext|>"} {"text":"<commit_before>#pragma once\r\n\/\/=====================================================================\/\/\r\n\/*!\t@file\r\n\t@brief\tRX64M グループ・ポート・マッピング @n\r\n\t\t\t・ペリフェラル型に従って、ポートの設定をグループ化 \r\n @author 平松邦仁 (hira@rvf-rc45.net)\r\n\t@copyright\tCopyright (C) 2016, 2017 Kunihito Hiramatsu @n\r\n\t\t\t\tReleased under the MIT license @n\r\n\t\t\t\thttps:\/\/github.com\/hirakuni45\/RX\/blob\/master\/LICENSE\r\n*\/\r\n\/\/=====================================================================\/\/\r\n#include \"RX600\/port.hpp\"\r\n#include \"RX64M\/mpc.hpp\"\r\n#include \"RX64M\/peripheral.hpp\"\r\n\r\nnamespace device {\r\n\r\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\r\n\t\/*!\r\n\t\t@brief ポート・マッピング・ユーティリティー\r\n\t*\/\r\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\r\n\tclass port_map {\r\n\r\n\t\tstatic void sub_(peripheral t, bool enable) {\r\n\t\t\tswitch(t) {\r\n\t\t\t\/\/ ※シリアルポートの MPC 設定では、PDR を制御する必要は無いが、\r\n\t\t\t\/\/ 出力ポートのインピーダンス制御の一環として入れてある。\r\n\t\t\tcase peripheral::SCI0:\r\n\t\t\t\t{\r\n\t\t\t\t\tuint8_t sel = enable ? 0b001010 : 0;\r\n\t\t\t\t\tPORT2::PDR.B0 = enable; \/\/ TXD0\r\n\t\t\t\t\tPORT2::PDR.B1 = 0; \t\/\/ RXD0\r\n\t\t\t\t\tMPC::P20PFS.PSEL = sel;\r\n\t\t\t\t\tMPC::P21PFS.PSEL = sel;\r\n\t\t\t\t\tPORT2::PMR.B0 = enable;\r\n\t\t\t\t\tPORT2::PMR.B1 = enable;\r\n\t\t\t\t}\r\n\t\t\t\tbreak;\r\n\t\t\tcase peripheral::SCI1:\r\n\t\t\t\t{\r\n\t\t\t\t\tuint8_t sel = enable ? 0b001010 : 0;\r\n\t\t\t\t\tPORTF::PDR.B0 = enable; \/\/ TXD1\r\n\t\t\t\t\tPORTF::PDR.B2 = 0; \t\/\/ RXD1\r\n\t\t\t\t\tMPC::PF0PFS.PSEL = sel;\r\n\t\t\t\t\tMPC::PF2PFS.PSEL = sel;\r\n\t\t\t\t\tPORTF::PMR.B0 = enable;\r\n\t\t\t\t\tPORTF::PMR.B2 = enable;\r\n\t\t\t\t}\r\n\t\t\t\tbreak;\r\n\t\t\tcase peripheral::SCI2:\r\n\t\t\t\t{\r\n\t\t\t\t\tuint8_t sel = enable ? 0b001010 : 0;\r\n\t\t\t\t\tPORT1::PDR.B3 = enable; \/\/ TXD2\r\n\t\t\t\t\tPORT1::PDR.B2 = 0; \t\/\/ RXD2\r\n\t\t\t\t\tMPC::P13PFS.PSEL = sel;\r\n\t\t\t\t\tMPC::P12PFS.PSEL = sel;\r\n\t\t\t\t\tPORT1::PMR.B3 = enable;\r\n\t\t\t\t\tPORT1::PMR.B2 = enable;\r\n\t\t\t\t}\r\n\t\t\t\tbreak;\r\n\t\t\tcase peripheral::SCI3:\r\n\t\t\t\t{\r\n\t\t\t\t\tuint8_t sel = enable ? 0b001010 : 0;\r\n\t\t\t\t\tPORT2::PDR.B3 = enable; \/\/ TXD3\r\n\t\t\t\t\tPORT2::PDR.B5 = 0; \t\/\/ RXD3\r\n\t\t\t\t\tMPC::P23PFS.PSEL = sel;\r\n\t\t\t\t\tMPC::P25PFS.PSEL = sel;\r\n\t\t\t\t\tPORT2::PMR.B3 = enable;\r\n\t\t\t\t\tPORT2::PMR.B5 = enable;\r\n\t\t\t\t}\r\n\t\t\t\tbreak;\r\n\t\t\tcase peripheral::SCI4:\r\n\t\t\t\t{\r\n\t\t\t\t\tuint8_t sel = enable ? 0b001010 : 0;\r\n\t\t\t\t\tPORTB::PDR.B1 = enable; \/\/ TXD4\r\n\t\t\t\t\tPORTB::PDR.B0 = 0; \t\/\/ RXD4\r\n\t\t\t\t\tMPC::PB1PFS.PSEL = sel;\r\n\t\t\t\t\tMPC::PB0PFS.PSEL = sel;\r\n\t\t\t\t\tPORTB::PMR.B1 = enable;\r\n\t\t\t\t\tPORTB::PMR.B0 = enable;\r\n\t\t\t\t}\r\n\t\t\t\tbreak;\r\n\t\t\tcase peripheral::SCI5:\r\n\t\t\t\t{\r\n\t\t\t\t\tuint8_t sel = enable ? 0b001010 : 0;\r\n\t\t\t\t\tPORTA::PDR.B4 = enable; \/\/ TXD5\r\n\t\t\t\t\tPORTA::PDR.B3 = 0; \t\/\/ RXD5\r\n\t\t\t\t\tMPC::PA4PFS.PSEL = sel;\r\n\t\t\t\t\tMPC::PA3PFS.PSEL = sel;\r\n\t\t\t\t\tPORTA::PMR.B4 = enable;\r\n\t\t\t\t\tPORTA::PMR.B3 = enable;\r\n\t\t\t\t}\r\n\t\t\t\tbreak;\r\n\t\t\tcase peripheral::SCI6:\r\n\t\t\t\t{\r\n\t\t\t\t\tuint8_t sel = enable ? 0b001010 : 0;\r\n\t\t\t\t\tPORT0::PDR.B0 = enable; \/\/ TXD6\r\n\t\t\t\t\tPORT0::PDR.B1 = 0; \t\/\/ RXD6\r\n\t\t\t\t\tMPC::P00PFS.PSEL = sel;\r\n\t\t\t\t\tMPC::P01PFS.PSEL = sel;\r\n\t\t\t\t\tPORT0::PMR.B0 = enable;\r\n\t\t\t\t\tPORT0::PMR.B1 = enable;\r\n\t\t\t\t}\r\n\t\t\t\tbreak;\r\n\t\t\tcase peripheral::SCI7:\r\n\t\t\t\t{\r\n\t\t\t\t\tuint8_t sel = enable ? 0b001010 : 0;\r\n\t\t\t\t\tPORT9::PDR.B0 = enable; \/\/ TXD7\r\n\t\t\t\t\tPORT9::PDR.B2 = 0; \t\/\/ RXD7\r\n\t\t\t\t\tMPC::P90PFS.PSEL = sel;\r\n\t\t\t\t\tMPC::P92PFS.PSEL = sel;\r\n\t\t\t\t\tPORT9::PMR.B0 = enable;\r\n\t\t\t\t\tPORT9::PMR.B2 = enable;\r\n\t\t\t\t}\r\n\t\t\t\tbreak;\r\n\r\n\t\t\tcase peripheral::SCI12:\r\n\t\t\t\t{\r\n\t\t\t\t\tuint8_t sel = enable ? 0b001100 : 0;\r\n\t\t\t\t\tPORTE::PDR.B2 = enable; \/\/ TXD12\r\n\t\t\t\t\tPORTE::PDR.B1 = 0; \t\/\/ RXD12\r\n\t\t\t\t\tMPC::PE2PFS.PSEL = sel;\r\n\t\t\t\t\tMPC::PE1PFS.PSEL = sel;\r\n\t\t\t\t\tPORTE::PMR.B2 = enable;\r\n\t\t\t\t\tPORTE::PMR.B1 = enable;\r\n\t\t\t\t}\r\n\t\t\t\tbreak;\r\n\r\n\t\t\tcase peripheral::RSPI:\r\n\t\t\t\t{\r\n\t\t\t\t\tuint8_t sel = enable ? 0b001101 : 0;\r\n\/\/\t\t\t\t\tPORTC::PCR.B7 = 1;\t\t\/\/ pull-up\r\n\/\/\t\t\t\t\tPORTC::PDR.B7 = 0;\t\t\/\/ MISOA\r\n\/\/\t\t\t\t\tPORTC::PDR.B6 = 1;\t\t\/\/ MOSIA\r\n\/\/\t\t\t\t\tPORTC::PDR.B5 = 1;\t\t\/\/ RSPCKA\r\n\t\t\t\t\tMPC::PC7PFS.PSEL = sel; \/\/ MISOA\r\n\t\t\t\t\tMPC::PC6PFS.PSEL = sel; \/\/ MOSIA\r\n\t\t\t\t\tMPC::PC5PFS.PSEL = sel; \/\/ RSPCKA\r\n\t\t\t\t\tPORTC::PMR.B7 = enable;\r\n\t\t\t\t\tPORTC::PMR.B6 = enable;\r\n\t\t\t\t\tPORTC::PMR.B5 = enable;\r\n\t\t\t\t}\r\n\t\t\t\tbreak;\r\n\r\n\t\t\tcase peripheral::SDHI:\r\n\t\t\t\t{\r\n\t\t\t\t\tuint8_t sel = enable ? 0b011010 : 0;\r\n\t\t\t\t\tMPC::P80PFS.PSEL = sel; \/\/ SDHI_WP\r\n\t\t\t\t\tMPC::P81PFS.PSEL = sel; \/\/ SDHI_CD\r\n\t\t\t\t\tPORT8::PMR.B0 = enable;\r\n\t\t\t\t\tPORT8::PMR.B2 = enable;\r\n\t\t\t\t\tMPC::PC2PFS.PSEL = sel; \/\/ SDHI_D3\r\n\t\t\t\t\tMPC::PC3PFS.PSEL = sel; \/\/ SDHI_D0\r\n\t\t\t\t\tMPC::PC4PFS.PSEL = sel; \/\/ SDHI_D1\r\n\t\t\t\t\tPORTC::PMR.B2 = enable;\r\n\t\t\t\t\tPORTC::PMR.B3 = enable;\r\n\t\t\t\t\tPORTC::PMR.B4 = enable;\r\n \t\t\t\t\tMPC::P75PFS.PSEL = sel; \/\/ SDHI_D2\r\n\t\t\t\t\tMPC::P76PFS.PSEL = sel; \/\/ SDHI_CMD\r\n\t\t\t\t\tMPC::P77PFS.PSEL = sel; \/\/ SDHI_CLK\r\n\t\t\t\t\tPORT7::PMR.B5 = enable;\r\n\t\t\t\t\tPORT7::PMR.B6 = enable;\r\n\t\t\t\t\tPORT7::PMR.B7 = enable;\r\n\t\t\t\t}\r\n\t\t\t\tbreak;\r\n\r\n\t\t\tcase peripheral::ETHERC0: \/\/ only RMII mode, not use link status interrupt\r\n\t\t\t\t{\r\n\t\t\t\t\tuint8_t mii = enable ? 0b010001 : 0;\r\n\t\t\t\t\tuint8_t rmii = enable ? 0b010010 : 0;\r\n\/\/\t\t\t\t\tMPC::P34PFS.PSEL = mii; \/\/ ET0_LINKSTA\r\n\/\/\t\t\t\t\tPORT3::PMR.B4 = enable;\r\n\t\t\t\t\tMPC::P71PFS.PSEL = mii; \/\/ ET0_MDIO\r\n\t\t\t\t\tMPC::P72PFS.PSEL = mii; \/\/ ET0_MDC\r\n\/\/\t\t\t\t\tMPC::P73PFS.PSEL = mii; \/\/ ET0_WOL\r\n\t\t\t\t\tMPC::P74PFS.PSEL = rmii; \/\/ RMII0_RXD1\r\n\t\t\t\t\tMPC::P75PFS.PSEL = rmii; \/\/ RMII0_RXD0\r\n\t\t\t\t\tMPC::P76PFS.PSEL = rmii; \/\/ REF50CK0\r\n\t\t\t\t\tMPC::P77PFS.PSEL = rmii; \/\/ RMII0_RX_ER\r\n\t\t\t\t\tPORT7::PMR.B1 = enable;\r\n\t\t\t\t\tPORT7::PMR.B2 = enable;\r\n\/\/\t\t\t\t\tPORT7::PMR.B3 = enable;\r\n\t\t\t\t\tPORT7::PMR.B4 = enable;\r\n\t\t\t\t\tPORT7::PMR.B5 = enable;\r\n\t\t\t\t\tPORT7::PMR.B6 = enable;\r\n\t\t\t\t\tPORT7::PMR.B7 = enable;\r\n\t\t\t\t\tMPC::P80PFS.PSEL = rmii; \/\/ RMII0_TXD_EN\r\n\t\t\t\t\tMPC::P81PFS.PSEL = rmii; \/\/ RMII0_TXD0\r\n\t\t\t\t\tMPC::P82PFS.PSEL = rmii; \/\/ RMII0_TXD1\r\n\t\t\t\t\tMPC::P83PFS.PSEL = rmii; \/\/ RMII0_CRS_DV\r\n\t\t\t\t\tPORT8::PMR.B0 = enable;\r\n\t\t\t\t\tPORT8::PMR.B1 = enable;\r\n\t\t\t\t\tPORT8::PMR.B2 = enable;\r\n\t\t\t\t\tPORT8::PMR.B3 = enable;\r\n\t\t\t\t\tMPC::PFENET.PHYMODE0 = 0; \/\/ for RMII mode chanel 0\r\n\t\t\t\t}\r\n\t\t\t\tbreak;\r\n\r\n\t\t\tcase peripheral::ETHERCA: \/\/ only RMII mode, not use link status interrupt\r\n\t\t\t\t{\r\n\t\t\t\t\tuint8_t mii = enable ? 0b010001 : 0;\r\n\t\t\t\t\tuint8_t rmii = enable ? 0b010010 : 0;\r\n\/\/\/\t\t\t\t\tMPC::P73PFS.PSEL = mii; \/\/ ET0_WOL (144LQFP: 77)\r\n\t\t\t\t\tMPC::P72PFS.PSEL = mii; \/\/ ET0_MDC (144LQFP: 85)\r\n\t\t\t\t\tMPC::P71PFS.PSEL = mii; \/\/ ET0_MDIO (144LQFP: 86)\r\n\/\/\/\t\t\t\t\tPORT7::PMR.B3 = enable;\r\n\t\t\t\t\tPORT7::PMR.B2 = enable;\r\n\t\t\t\t\tPORT7::PMR.B1 = enable;\r\n\t\t\t\t\tMPC::PB7PFS.PSEL = rmii; \/\/ RMII0_CRS_DV (144LQFP: 78)\r\n\t\t\t\t\tMPC::PB6PFS.PSEL = rmii; \/\/ RMII0_TXD1 (144LQFP: 79)\r\n\t\t\t\t\tMPC::PB5PFS.PSEL = rmii; \/\/ RMII0_TXD0 (144LQFP: 80)\r\n\t\t\t\t\tMPC::PB4PFS.PSEL = rmii; \/\/ RMII0_TXD_EN (144LQFP: 81)\r\n\t\t\t\t\tMPC::PB3PFS.PSEL = rmii; \/\/ RMII0_RX_ER (144LQFP: 82)\r\n\t\t\t\t\tMPC::PB2PFS.PSEL = rmii; \/\/ REF50CK0 (144LQFP: 83)\r\n\t\t\t\t\tMPC::PB1PFS.PSEL = rmii; \/\/ RMII0_RXD0 (144LQFP: 84)\r\n\t\t\t\t\tMPC::PB0PFS.PSEL = rmii; \/\/ RMII0_RXD1 (144LQFP: 87)\r\n\t\t\t\t\tPORTB::PMR.B7 = enable;\r\n\t\t\t\t\tPORTB::PMR.B6 = enable;\r\n\t\t\t\t\tPORTB::PMR.B5 = enable;\r\n\t\t\t\t\tPORTB::PMR.B4 = enable;\r\n\t\t\t\t\tPORTB::PMR.B3 = enable;\r\n\t\t\t\t\tPORTB::PMR.B2 = enable;\r\n\t\t\t\t\tPORTB::PMR.B1 = enable;\r\n\t\t\t\t\tPORTB::PMR.B0 = enable;\r\n\t\t\t\t\tMPC::PFENET.PHYMODE0 = 0; \/\/ for RMII mode chanel 0\r\n\t\t\t\t}\r\n\t\t\t\tbreak;\r\n\r\n\t\t\tdefault:\r\n\/\/\t\t\t\tutils::format(\"Fail port map: %d\\n\") % static_cast<int>(t);\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\tpublic:\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brief 周辺機器に切り替える\r\n\t\t\t@param[in]\tt\t周辺機器タイプ\r\n\t\t\t@param[in]\tena\t無効にする場合「false」\r\n\t\t*\/\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\tstatic void turn(peripheral t, bool ena = true)\r\n\t\t{\r\n\t\t\tMPC::PWPR.B0WI = 0;\t\t\/\/ PWPR 書き込み許可\r\n\t\t\tMPC::PWPR.PFSWE = 1;\t\/\/ PxxPFS 書き込み許可\r\n\r\n\t\t\tsub_(t, ena);\r\n\r\n\t\t\tMPC::PWPR = device::MPC::PWPR.B0WI.b();\r\n\t\t}\r\n\t};\r\n}\r\n\r\n<commit_msg>fix port NO for SDHI<commit_after>#pragma once\r\n\/\/=====================================================================\/\/\r\n\/*!\t@file\r\n\t@brief\tRX64M グループ・ポート・マッピング @n\r\n\t\t\t・ペリフェラル型に従って、ポートの設定をグループ化 \r\n @author 平松邦仁 (hira@rvf-rc45.net)\r\n\t@copyright\tCopyright (C) 2016, 2017 Kunihito Hiramatsu @n\r\n\t\t\t\tReleased under the MIT license @n\r\n\t\t\t\thttps:\/\/github.com\/hirakuni45\/RX\/blob\/master\/LICENSE\r\n*\/\r\n\/\/=====================================================================\/\/\r\n#include \"RX600\/port.hpp\"\r\n#include \"RX64M\/mpc.hpp\"\r\n#include \"RX64M\/peripheral.hpp\"\r\n\r\nnamespace device {\r\n\r\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\r\n\t\/*!\r\n\t\t@brief ポート・マッピング・ユーティリティー\r\n\t*\/\r\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\r\n\tclass port_map {\r\n\r\n\t\tstatic bool sub_(peripheral t, bool enable) {\r\n\t\t\tbool ret = true;\r\n\t\t\tswitch(t) {\r\n\t\t\t\/\/ ※シリアルポートの MPC 設定では、PDR を制御する必要は無いが、\r\n\t\t\t\/\/ 出力ポートのインピーダンス制御の一環として入れてある。\r\n\t\t\tcase peripheral::SCI0:\r\n\t\t\t\t{\r\n\t\t\t\t\tuint8_t sel = enable ? 0b001010 : 0;\r\n\t\t\t\t\tPORT2::PDR.B0 = enable; \/\/ TXD0\r\n\t\t\t\t\tPORT2::PDR.B1 = 0; \t\/\/ RXD0\r\n\t\t\t\t\tMPC::P20PFS.PSEL = sel;\r\n\t\t\t\t\tMPC::P21PFS.PSEL = sel;\r\n\t\t\t\t\tPORT2::PMR.B0 = enable;\r\n\t\t\t\t\tPORT2::PMR.B1 = enable;\r\n\t\t\t\t}\r\n\t\t\t\tbreak;\r\n\t\t\tcase peripheral::SCI1:\r\n\t\t\t\t{\r\n\t\t\t\t\tuint8_t sel = enable ? 0b001010 : 0;\r\n\t\t\t\t\tPORTF::PDR.B0 = enable; \/\/ TXD1\r\n\t\t\t\t\tPORTF::PDR.B2 = 0; \t\/\/ RXD1\r\n\t\t\t\t\tMPC::PF0PFS.PSEL = sel;\r\n\t\t\t\t\tMPC::PF2PFS.PSEL = sel;\r\n\t\t\t\t\tPORTF::PMR.B0 = enable;\r\n\t\t\t\t\tPORTF::PMR.B2 = enable;\r\n\t\t\t\t}\r\n\t\t\t\tbreak;\r\n\t\t\tcase peripheral::SCI2:\r\n\t\t\t\t{\r\n\t\t\t\t\tuint8_t sel = enable ? 0b001010 : 0;\r\n\t\t\t\t\tPORT1::PDR.B3 = enable; \/\/ TXD2\r\n\t\t\t\t\tPORT1::PDR.B2 = 0; \t\/\/ RXD2\r\n\t\t\t\t\tMPC::P13PFS.PSEL = sel;\r\n\t\t\t\t\tMPC::P12PFS.PSEL = sel;\r\n\t\t\t\t\tPORT1::PMR.B3 = enable;\r\n\t\t\t\t\tPORT1::PMR.B2 = enable;\r\n\t\t\t\t}\r\n\t\t\t\tbreak;\r\n\t\t\tcase peripheral::SCI3:\r\n\t\t\t\t{\r\n\t\t\t\t\tuint8_t sel = enable ? 0b001010 : 0;\r\n\t\t\t\t\tPORT2::PDR.B3 = enable; \/\/ TXD3\r\n\t\t\t\t\tPORT2::PDR.B5 = 0; \t\/\/ RXD3\r\n\t\t\t\t\tMPC::P23PFS.PSEL = sel;\r\n\t\t\t\t\tMPC::P25PFS.PSEL = sel;\r\n\t\t\t\t\tPORT2::PMR.B3 = enable;\r\n\t\t\t\t\tPORT2::PMR.B5 = enable;\r\n\t\t\t\t}\r\n\t\t\t\tbreak;\r\n\t\t\tcase peripheral::SCI4:\r\n\t\t\t\t{\r\n\t\t\t\t\tuint8_t sel = enable ? 0b001010 : 0;\r\n\t\t\t\t\tPORTB::PDR.B1 = enable; \/\/ TXD4\r\n\t\t\t\t\tPORTB::PDR.B0 = 0; \t\/\/ RXD4\r\n\t\t\t\t\tMPC::PB1PFS.PSEL = sel;\r\n\t\t\t\t\tMPC::PB0PFS.PSEL = sel;\r\n\t\t\t\t\tPORTB::PMR.B1 = enable;\r\n\t\t\t\t\tPORTB::PMR.B0 = enable;\r\n\t\t\t\t}\r\n\t\t\t\tbreak;\r\n\t\t\tcase peripheral::SCI5:\r\n\t\t\t\t{\r\n\t\t\t\t\tuint8_t sel = enable ? 0b001010 : 0;\r\n\t\t\t\t\tPORTA::PDR.B4 = enable; \/\/ TXD5\r\n\t\t\t\t\tPORTA::PDR.B3 = 0; \t\/\/ RXD5\r\n\t\t\t\t\tMPC::PA4PFS.PSEL = sel;\r\n\t\t\t\t\tMPC::PA3PFS.PSEL = sel;\r\n\t\t\t\t\tPORTA::PMR.B4 = enable;\r\n\t\t\t\t\tPORTA::PMR.B3 = enable;\r\n\t\t\t\t}\r\n\t\t\t\tbreak;\r\n\t\t\tcase peripheral::SCI6:\r\n\t\t\t\t{\r\n\t\t\t\t\tuint8_t sel = enable ? 0b001010 : 0;\r\n\t\t\t\t\tPORT0::PDR.B0 = enable; \/\/ TXD6\r\n\t\t\t\t\tPORT0::PDR.B1 = 0; \t\/\/ RXD6\r\n\t\t\t\t\tMPC::P00PFS.PSEL = sel;\r\n\t\t\t\t\tMPC::P01PFS.PSEL = sel;\r\n\t\t\t\t\tPORT0::PMR.B0 = enable;\r\n\t\t\t\t\tPORT0::PMR.B1 = enable;\r\n\t\t\t\t}\r\n\t\t\t\tbreak;\r\n\t\t\tcase peripheral::SCI7:\r\n\t\t\t\t{\r\n\t\t\t\t\tuint8_t sel = enable ? 0b001010 : 0;\r\n\t\t\t\t\tPORT9::PDR.B0 = enable; \/\/ TXD7\r\n\t\t\t\t\tPORT9::PDR.B2 = 0; \t\/\/ RXD7\r\n\t\t\t\t\tMPC::P90PFS.PSEL = sel;\r\n\t\t\t\t\tMPC::P92PFS.PSEL = sel;\r\n\t\t\t\t\tPORT9::PMR.B0 = enable;\r\n\t\t\t\t\tPORT9::PMR.B2 = enable;\r\n\t\t\t\t}\r\n\t\t\t\tbreak;\r\n\r\n\t\t\tcase peripheral::SCI12:\r\n\t\t\t\t{\r\n\t\t\t\t\tuint8_t sel = enable ? 0b001100 : 0;\r\n\t\t\t\t\tPORTE::PDR.B2 = enable; \/\/ TXD12\r\n\t\t\t\t\tPORTE::PDR.B1 = 0; \t\/\/ RXD12\r\n\t\t\t\t\tMPC::PE2PFS.PSEL = sel;\r\n\t\t\t\t\tMPC::PE1PFS.PSEL = sel;\r\n\t\t\t\t\tPORTE::PMR.B2 = enable;\r\n\t\t\t\t\tPORTE::PMR.B1 = enable;\r\n\t\t\t\t}\r\n\t\t\t\tbreak;\r\n\r\n\t\t\tcase peripheral::RSPI:\r\n\t\t\t\t{\r\n\t\t\t\t\tuint8_t sel = enable ? 0b001101 : 0;\r\n\/\/\t\t\t\t\tPORTC::PCR.B7 = 1;\t\t\/\/ pull-up\r\n\/\/\t\t\t\t\tPORTC::PDR.B7 = 0;\t\t\/\/ MISOA\r\n\/\/\t\t\t\t\tPORTC::PDR.B6 = 1;\t\t\/\/ MOSIA\r\n\/\/\t\t\t\t\tPORTC::PDR.B5 = 1;\t\t\/\/ RSPCKA\r\n\t\t\t\t\tMPC::PC7PFS.PSEL = sel; \/\/ MISOA\r\n\t\t\t\t\tMPC::PC6PFS.PSEL = sel; \/\/ MOSIA\r\n\t\t\t\t\tMPC::PC5PFS.PSEL = sel; \/\/ RSPCKA\r\n\t\t\t\t\tPORTC::PMR.B7 = enable;\r\n\t\t\t\t\tPORTC::PMR.B6 = enable;\r\n\t\t\t\t\tPORTC::PMR.B5 = enable;\r\n\t\t\t\t}\r\n\t\t\t\tbreak;\r\n\r\n\t\t\tcase peripheral::SDHI:\r\n\t\t\t\t{\r\n\t\t\t\t\tuint8_t sel = enable ? 0b011010 : 0;\r\n\t\t\t\t\tMPC::P80PFS.PSEL = sel; \/\/ SDHI_WP\r\n\t\t\t\t\tMPC::P81PFS.PSEL = sel; \/\/ SDHI_CD\r\n\t\t\t\t\tPORT8::PMR.B0 = enable;\r\n\t\t\t\t\tPORT8::PMR.B1 = enable;\r\n\t\t\t\t\tMPC::PC2PFS.PSEL = sel; \/\/ SDHI_D3\r\n\t\t\t\t\tMPC::PC3PFS.PSEL = sel; \/\/ SDHI_D0\r\n\t\t\t\t\tMPC::PC4PFS.PSEL = sel; \/\/ SDHI_D1\r\n\t\t\t\t\tPORTC::PMR.B2 = enable;\r\n\t\t\t\t\tPORTC::PMR.B3 = enable;\r\n\t\t\t\t\tPORTC::PMR.B4 = enable;\r\n \t\t\t\t\tMPC::P75PFS.PSEL = sel; \/\/ SDHI_D2\r\n\t\t\t\t\tMPC::P76PFS.PSEL = sel; \/\/ SDHI_CMD\r\n\t\t\t\t\tMPC::P77PFS.PSEL = sel; \/\/ SDHI_CLK\r\n\t\t\t\t\tPORT7::PMR.B5 = enable;\r\n\t\t\t\t\tPORT7::PMR.B6 = enable;\r\n\t\t\t\t\tPORT7::PMR.B7 = enable;\r\n\t\t\t\t}\r\n\t\t\t\tbreak;\r\n\r\n\t\t\tcase peripheral::ETHERC0: \/\/ only RMII mode, not use link status interrupt\r\n\t\t\t\t{\r\n\t\t\t\t\tuint8_t mii = enable ? 0b010001 : 0;\r\n\t\t\t\t\tuint8_t rmii = enable ? 0b010010 : 0;\r\n\/\/\t\t\t\t\tMPC::P34PFS.PSEL = mii; \/\/ ET0_LINKSTA\r\n\/\/\t\t\t\t\tPORT3::PMR.B4 = enable;\r\n\t\t\t\t\tMPC::P71PFS.PSEL = mii; \/\/ ET0_MDIO\r\n\t\t\t\t\tMPC::P72PFS.PSEL = mii; \/\/ ET0_MDC\r\n\/\/\t\t\t\t\tMPC::P73PFS.PSEL = mii; \/\/ ET0_WOL\r\n\t\t\t\t\tMPC::P74PFS.PSEL = rmii; \/\/ RMII0_RXD1\r\n\t\t\t\t\tMPC::P75PFS.PSEL = rmii; \/\/ RMII0_RXD0\r\n\t\t\t\t\tMPC::P76PFS.PSEL = rmii; \/\/ REF50CK0\r\n\t\t\t\t\tMPC::P77PFS.PSEL = rmii; \/\/ RMII0_RX_ER\r\n\t\t\t\t\tPORT7::PMR.B1 = enable;\r\n\t\t\t\t\tPORT7::PMR.B2 = enable;\r\n\/\/\t\t\t\t\tPORT7::PMR.B3 = enable;\r\n\t\t\t\t\tPORT7::PMR.B4 = enable;\r\n\t\t\t\t\tPORT7::PMR.B5 = enable;\r\n\t\t\t\t\tPORT7::PMR.B6 = enable;\r\n\t\t\t\t\tPORT7::PMR.B7 = enable;\r\n\t\t\t\t\tMPC::P80PFS.PSEL = rmii; \/\/ RMII0_TXD_EN\r\n\t\t\t\t\tMPC::P81PFS.PSEL = rmii; \/\/ RMII0_TXD0\r\n\t\t\t\t\tMPC::P82PFS.PSEL = rmii; \/\/ RMII0_TXD1\r\n\t\t\t\t\tMPC::P83PFS.PSEL = rmii; \/\/ RMII0_CRS_DV\r\n\t\t\t\t\tPORT8::PMR.B0 = enable;\r\n\t\t\t\t\tPORT8::PMR.B1 = enable;\r\n\t\t\t\t\tPORT8::PMR.B2 = enable;\r\n\t\t\t\t\tPORT8::PMR.B3 = enable;\r\n\t\t\t\t\tMPC::PFENET.PHYMODE0 = 0; \/\/ for RMII mode chanel 0\r\n\t\t\t\t}\r\n\t\t\t\tbreak;\r\n\r\n\t\t\tcase peripheral::ETHERCA: \/\/ only RMII mode, not use link status interrupt\r\n\t\t\t\t{\r\n\t\t\t\t\tuint8_t mii = enable ? 0b010001 : 0;\r\n\t\t\t\t\tuint8_t rmii = enable ? 0b010010 : 0;\r\n\/\/\/\t\t\t\t\tMPC::P73PFS.PSEL = mii; \/\/ ET0_WOL (144LQFP: 77)\r\n\t\t\t\t\tMPC::P72PFS.PSEL = mii; \/\/ ET0_MDC (144LQFP: 85)\r\n\t\t\t\t\tMPC::P71PFS.PSEL = mii; \/\/ ET0_MDIO (144LQFP: 86)\r\n\/\/\/\t\t\t\t\tPORT7::PMR.B3 = enable;\r\n\t\t\t\t\tPORT7::PMR.B2 = enable;\r\n\t\t\t\t\tPORT7::PMR.B1 = enable;\r\n\t\t\t\t\tMPC::PB7PFS.PSEL = rmii; \/\/ RMII0_CRS_DV (144LQFP: 78)\r\n\t\t\t\t\tMPC::PB6PFS.PSEL = rmii; \/\/ RMII0_TXD1 (144LQFP: 79)\r\n\t\t\t\t\tMPC::PB5PFS.PSEL = rmii; \/\/ RMII0_TXD0 (144LQFP: 80)\r\n\t\t\t\t\tMPC::PB4PFS.PSEL = rmii; \/\/ RMII0_TXD_EN (144LQFP: 81)\r\n\t\t\t\t\tMPC::PB3PFS.PSEL = rmii; \/\/ RMII0_RX_ER (144LQFP: 82)\r\n\t\t\t\t\tMPC::PB2PFS.PSEL = rmii; \/\/ REF50CK0 (144LQFP: 83)\r\n\t\t\t\t\tMPC::PB1PFS.PSEL = rmii; \/\/ RMII0_RXD0 (144LQFP: 84)\r\n\t\t\t\t\tMPC::PB0PFS.PSEL = rmii; \/\/ RMII0_RXD1 (144LQFP: 87)\r\n\t\t\t\t\tPORTB::PMR.B7 = enable;\r\n\t\t\t\t\tPORTB::PMR.B6 = enable;\r\n\t\t\t\t\tPORTB::PMR.B5 = enable;\r\n\t\t\t\t\tPORTB::PMR.B4 = enable;\r\n\t\t\t\t\tPORTB::PMR.B3 = enable;\r\n\t\t\t\t\tPORTB::PMR.B2 = enable;\r\n\t\t\t\t\tPORTB::PMR.B1 = enable;\r\n\t\t\t\t\tPORTB::PMR.B0 = enable;\r\n\t\t\t\t\tMPC::PFENET.PHYMODE0 = 0; \/\/ for RMII mode chanel 0\r\n\t\t\t\t}\r\n\t\t\t\tbreak;\r\n\r\n\t\t\tdefault:\r\n\t\t\t\tret = false;\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t\treturn ret;\r\n\t\t}\r\n\r\n\tpublic:\r\n\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brief 周辺機器に切り替える\r\n\t\t\t@param[in]\tt\t周辺機器タイプ\r\n\t\t\t@param[in]\tena\t無効にする場合「false」\r\n\t\t*\/\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\tstatic bool turn(peripheral t, bool ena = true) noexcept\r\n\t\t{\r\n\t\t\tMPC::PWPR.B0WI = 0;\t\t\/\/ PWPR 書き込み許可\r\n\t\t\tMPC::PWPR.PFSWE = 1;\t\/\/ PxxPFS 書き込み許可\r\n\r\n\t\t\tauto ret = sub_(t, ena);\r\n\r\n\t\t\tMPC::PWPR = device::MPC::PWPR.B0WI.b();\r\n\r\n\t\t\treturn ret;\r\n\t\t}\r\n\r\n\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\t\/*!\r\n\t\t\t@brief SDHI クロック端子のソフト制御\r\n\t\t\t@param[in]\tt\t周辺機器タイプ\r\n\t\t*\/\r\n\t\t\/\/-----------------------------------------------------------------\/\/\r\n\t\tstatic bool turn_sdhi_clk(peripheral t)\r\n\t\t{\r\n\t\t\tMPC::PWPR.B0WI = 0;\t\t\/\/ PWPR 書き込み許可\r\n\t\t\tMPC::PWPR.PFSWE = 1;\t\/\/ PxxPFS 書き込み許可\r\n\r\n\t\t\tbool ret = false;\r\n\t\t\tif(t == peripheral::SDHI) {\r\n\t\t\t\tMPC::P77PFS.PSEL = 0; \/\/ SDHI_CLK\r\n\t\t\t\tPORT7::PMR.B7 = 0;\r\n\t\t\t\tret = true;\r\n\t\t\t}\r\n\t\t\tMPC::PWPR = device::MPC::PWPR.B0WI.b();\r\n\r\n\t\t\treturn ret;\r\n\t\t}\r\n\t};\r\n}\r\n\r\n<|endoftext|>"} {"text":"<commit_before>\/\/ \n\/\/ \n\/\/ Copyright (C) 2005 Jason Fischl, Dan Petrie\n\/\/\n\/\/ Copyright (C) 2005 SIPfoundry Inc.\n\/\/ Licensed by SIPfoundry under the LGPL license.\n\/\/ \n\/\/ Copyright (C) 2005 Pingtel Corp.\n\/\/ Licensed to SIPfoundry under a Contributor Agreement.\n\/\/ \n\/\/ $$\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/ SYSTEM INCLUDES\n#include <stdio.h>\n#include <signal.h>\n#include <unistd.h>\n\n\/\/ APPLICATION INCLUDES\n#include <os\/OsFS.h>\n#include <os\/OsSysLog.h>\n#include <os\/OsConfigDb.h>\n#include <net\/NameValueTokenizer.h>\n#include \"resip\/stack\/NameAddr.hxx\"\n#include \"ConferenceUserAgent.h\"\n\n\/\/ DEFINES\n#ifndef SIPX_VERSION\n# define SIPXCHANGE_VERSION SipXpbxVersion\n# define SIPXCHANGE_VERSION_COMMENT SipXpbxBuildStamp\n#else\n# define SIPXCHANGE_VERSION SIPX_VERSION\n# define SIPXCHANGE_VERSION_COMMENT \"\"\n#endif\n\n#define CONFIG_SETTINGS_FILE \"bbridge.conf\"\n#define CONFIG_ETC_DIR SIPX_CONFDIR\n\n#define CONFIG_LOG_FILE \"bbridge.log\"\n#define CONFIG_LOG_DIR SIPX_LOGDIR\n\n#define LOG_FACILITY FAC_CONFERENCE\n\n#define CONFIG_SETTING_LOG_DIR \"BOSTON_BRIDGE_LOG_DIR\"\n#define CONFIG_SETTING_LOG_LEVEL \"BOSTON_BRIDGE_LOG_LEVEL\"\n#define CONFIG_SETTING_LOG_CONSOLE \"BOSTON_BRIDGE_LOG_CONSOLE\"\n#define CONFIG_SETTING_UDP_PORT \"BOSTON_BRIDGE_UDP_PORT\"\n#define CONFIG_SETTING_TCP_PORT \"BOSTON_BRIDGE_TCP_PORT\"\n#define CONFIG_SETTING_RTP_START \"BOSTON_BRIDGE_RTP_START\"\n#define CONFIG_SETTING_RTP_END \"BOSTON_BRIDGE_RTP_END\"\n\n#define DEFAULT_UDP_PORT 5060 \/\/ Default UDP port\n#define DEFAULT_TCP_PORT 5060 \/\/ Default TCP port\n#define DEFAULT_TLS_PORT 5061 \/\/ Default TLS port\n#define DEFAULT_RTP_START 15000\n#define DEFAULT_RTP_END 20000\n\n\/\/ MACROS\n\/\/ EXTERNAL FUNCTIONS\n\/\/ EXTERNAL VARIABLES\n\/\/ CONSTANTS\n\/\/ STRUCTSCONFIG_SETTING_RTP_START\n\/\/ TYPEDEFS\ntypedef void (*sighandler_t)(int);\n\n\/\/ FUNCTIONS\nextern \"C\" {\n void sigHandler( int sig_num );\n sighandler_t pt_signal( int sig_num, sighandler_t handler );\n}\n\n\/\/ FORWARD DECLARATIONS\n\/\/ EXTERNAL VARIABLES\n\/\/ CONSTANTS\n\/\/ STATIC VARIABLE INITIALIZATIONS\n\/\/ GLOBAL VARIABLE INITIALIZATIONS\nUtlBoolean gShutdownFlag = FALSE;\n\n\n\/* ============================ FUNCTIONS ================================= *\/\n\n\/**\n * Description:\n * This is a replacement for signal() which registers a signal handler but sets\n * a flag causing system calls ( namely read() or getchar() ) not to bail out\n * upon recepit of that signal. We need this behavior, so we must call\n * sigaction() manually.\n *\/\nsighandler_t pt_signal( int sig_num, sighandler_t handler)\n{\n#if defined(__pingtel_on_posix__)\n struct sigaction action[2];\n action[0].sa_handler = handler;\n sigemptyset(&action[0].sa_mask);\n action[0].sa_flags = 0;\n sigaction ( sig_num, &action[0], &action[1] );\n return action[1].sa_handler;\n#else\n return signal( sig_num, handler );\n#endif\n}\n\n\n\/**\n * Description:\n * This is the signal handler, When called this sets the\n * global gShutdownFlag allowing the main processing\n * loop to exit cleanly.\n *\/\nvoid sigHandler( int sig_num )\n{\n \/\/ set a global shutdown flag\n gShutdownFlag = TRUE;\n\n \/\/ Unregister interest in the signal to prevent recursive callbacks\n pt_signal( sig_num, SIG_DFL );\n\n \/\/ Minimize the chance that we loose log data configDb.loadFromFile(fileName);\n \n OsSysLog::flush();\n OsSysLog::add(LOG_FACILITY, PRI_CRIT, \"sigHandler: caught signal: %d\", sig_num);\n OsSysLog::flush();\n}\n\n\n\/\/ Initialize the OsSysLog\nvoid initSysLog(OsConfigDb* pConfig)\n{\n UtlString logLevel; \/\/ Controls Log Verbosity\n UtlString consoleLogging; \/\/ Enable console logging by default?\n UtlString fileTarget; \/\/ Path to store log file.\n UtlBoolean bSpecifiedDirError ; \/\/ Set if the specified log dir does not\n \/\/ exist\n struct tagPrioriotyLookupTable\n {\n const char* pIdentity;\n OsSysLogPriority ePriority;\n };\n\n struct tagPrioriotyLookupTable lkupTable[] =\n {\n { \"DEBUG\", PRI_DEBUG},\n { \"INFO\", PRI_INFO},\n { \"NOTICE\", PRI_NOTICE},\n { \"WARNING\", PRI_WARNING},\n { \"ERR\", PRI_ERR},\n { \"CRIT\", PRI_CRIT},\n { \"ALERT\", PRI_ALERT},\n { \"EMERG\", PRI_EMERG},\n };\n\n OsSysLog::initialize(0, \"bbridge\");\n\n\n \/\/\n \/\/ Get\/Apply Log Filename\n \/\/\n fileTarget.remove(0);\n if ((pConfig->get(CONFIG_SETTING_LOG_DIR, fileTarget) != OS_SUCCESS) ||\n fileTarget.isNull() || !OsFileSystem::exists(fileTarget))\n {\n bSpecifiedDirError = !fileTarget.isNull();\n\n \/\/ If the log file directory exists use that, otherwise place the log\n \/\/ in the current directory\n OsPath workingDirectory;\n if (OsFileSystem::exists(CONFIG_LOG_DIR))\n {\n fileTarget = CONFIG_LOG_DIR;\n OsPath path(fileTarget);\n path.getNativePath(workingDirectory);\n\n osPrintf(\"%s : %s\\n\", CONFIG_SETTING_LOG_DIR, workingDirectory.data());\n OsSysLog::add(LOG_FACILITY, PRI_INFO, \"%s : %s\"DEFAULT_UDP_PORT, CONFIG_SETTING_LOG_DIR, workingDirectory.data());\n }\n else\n {\n OsPath path;\n OsFileSystem::getWorkingDirectory(path);\n path.getNativePath(workingDirectory);\n\n osPrintf(\"%s : %s\\n\", CONFIG_SETTING_LOG_DIR, workingDirectory.data());\n OsSysLog::add(LOG_FACILITY, PRI_INFO, \"%s : %s\", CONFIG_SETTING_LOG_DIR, workingDirectory.data());\n }\n\n fileTarget = workingDirectory +\n OsPathBase::separator +\n CONFIG_LOG_FILE;\n }\n else\n {\n bSpecifiedDirError = false;\n osPrintf(\"%s : %s\\n\", CONFIG_SETTING_LOG_DIR, fileTarget.data());\n OsSysLog::add(LOG_FACILITY, PRI_INFO, \"%s : %s\", CONFIG_SETTING_LOG_DIR, fileTarget.data());\n\n fileTarget = fileTarget +\n OsPathBase::separator +\n CONFIG_LOG_FILE;\n }\n OsSysLog::setOutputFile(0, fileTarget);\n\n\n \/\/\n \/\/ Get\/Apply Log Level\n \/\/\n if ((pConfig->get(CONFIG_SETTING_LOG_LEVEL, logLevel) != OS_SUCCESS) ||\n logLevel.isNull())\n {\n logLevel = \"ERR\";\n }\n logLevel.toUpper();\n OsSysLogPriority priority = PRI_ERR;\n int iEntries = sizeof(lkupTable) \/ sizeof(struct tagPrioriotyLookupTable);\n for (int i = 0; i < iEntries; i++)\n {\n if (logLevel == lkupTable[i].pIdentity)\n {\n priority = lkupTable[i].ePriority;\n osPrintf(\"%s : %s\\n\", CONFIG_SETTING_LOG_LEVEL, lkupTable[i].pIdentity);\n OsSysLog::add(LOG_FACILITY, PRI_INFO, \"%s : %s\", CONFIG_SETTING_LOG_LEVEL, lkupTable[i].pIdentity);\n break;\n }\n }\n OsSysLog::setLoggingPriority(priority);\n\n \/\/\n \/\/ Get\/Apply console logging\n \/\/\n UtlBoolean bConsoleLoggingEnabled = false;\n if ((pConfig->get(CONFIG_SETTING_LOG_CONSOLE, consoleLogging) == OS_SUCCESS))\n {\n consoleLogging.toUpper();\n if (consoleLogging == \"ENABLE\")\n {\n OsSysLog::enableConsoleOutput(true);\n bConsoleLoggingEnabled = true;5140\n }\n }\n\n osPrintf(\"%s : %s\\n\", CONFIG_SETTING_LOG_CONSOLE, bConsoleLoggingEnabled ? \"ENABLE\" : \"DISABLE\") ;\n OsSysLog::add(LOG_FACILITY, PRI_INFO, \"%s : %s\", CONFIG_SETTING_LOG_CONSOLE, bConsoleLoggingEnabled ? \"ENABLE\" : \"DISABLE\") ;\n\n if (bSpecifiedDirError)\n {\n OsSysLog::add(FAC_LOG, PRI_CRIT, \"Cannot access %s directory; please check configuration.\", CONFIG_SETTING_LOG_DIR);\n }\n}\n\n\n\/\/\n\/\/ The main entry point to the sipXpark\n\/\/\nint main(int argc, char* argv[])\n{\n \/\/ Configuration Database (used for OsSysLog)\n OsConfigDb configDb;\n\n \/\/ Register Signal handlers so we can perform graceful shutdown\n pt_signal(SIGINT, sigHandler); \/\/ Trap Ctrl-C on NT\n pt_signal(SIGILL, sigHandler);\n pt_signal(SIGABRT, sigHandler); \/\/ Abort signal 6\n pt_signal(SIGFPE, sigHandler); \/\/ Floading Point Exception\n pt_signal(SIGSEGV, sigHandler); \/\/ Address access violations signal 11\n pt_signal(SIGTERM, sigHandler); \/\/ Trap kill -15 on UNIX\n#if defined(__pingtel_on_posix__)\n pt_signal(SIGHUP, sigHandler); \/\/ Hangup\n pt_signal(SIGQUIT, sigHandler);\n pt_signal(SIGPIPE, sigHandler); \/\/ Handle TCP Failure\n pt_signal(SIGBUS, sigHandler);\n pt_signal(SIGSYS, sigHandler);\n pt_signal(SIGXCPU, sigHandler);\n pt_signal(SIGXFSZ, sigHandler);\n pt_signal(SIGUSR1, sigHandler);\n pt_signal(SIGUSR2, sigHandler);\n#endif\n\n UtlString argString;5140\n for(int argIndex = 1; argIndex < argc; argIndex++)\n {\n osPrintf(\"arg[%d]: %s\\n\", argIndex, argv[argIndex]);\n argString = argv[argIndex];\n NameValueTokenizer::frontBackTrim(&argString, \"\\t \");\n if(argString.compareTo(\"-v\") == 0)\n {\n osPrintf(\"Version: %s (%s)\\n\", SIPXCHANGE_VERSION, SIPXCHANGE_VERSION_COMMENT);\n return(1);\n }\n else\n {\n osPrintf(\"usage: %s [-v]\\nwhere:\\n -v provides the software version\\n\",\n argv[0]);\n return(1);\n }\n }\n\n \/\/ Load configuration file file\n OsPath workingDirectory;\n if (OsFileSystem::exists(CONFIG_ETC_DIR))\n {\n workingDirectory = CONFIG_ETC_DIR;\n OsPath path(workingDirectory);\n path.getNativePath(workingDirectory);\n }\n else\n {\n OsPath path;\n OsFileSystem::getWorkingDirectory(path);\n path.getNativePath(workingDirectory);\n }\n\n UtlString fileName = workingDirectory +\n OsPathBase::separator +\n CONFIG_SETTINGS_FILE;\n\n if (configDb.loadFromFile(fileName) != SUCCESS)\n {\n configDb.set(CONFIG_SETTING_LOG_DIR, \"\");\n configDb.set(CONFIG_SETTING_LOG_LEVEL, \"INFO\");\n configDb.set(CONFIG_SETTING_LOG_CONSOLE, \"\");\n configDb.set(CONFIG_SETTING_UDP_PORT, DEFAULT_UDP_PORT);\n configDb.set(CONFIG_SETTING_TCP_PORT, DEFAULT_TCP_PORT);\n configDb.set(CONFIG_SETTING_TLS_PORT, DEFAULT_TLS_PORT);\n configDb.set(CONFIG_SETTING_RTP_START, DEFAULT_RTP_START);\n configDb.set(CONFIG_SETTING_RTP_END, DEFAULT_RTP_END);\n configDb.storeToFile(filename);\n }\n \n \/\/ Initialize log file\n initSysLog(&configDb);\n\n \/\/ Read the user agent parameters from the config file.\n int UdpPort;\n if (configDb.get(CONFIG_SETTING_UDP_PORT, UdpPort) != OS_SUCCESS)\n {\n configDb.set(CONFIG_SETTING_UDP_PORT, DEFAULT_UDP_PORT);;\n }\n \n int TcpPort;\n if (configDb.get(CONFIG_SETTING_TCP_PORT, TcpPort) != OS_SUCCESS)\n {\n configDb.set(CONFIG_SETTING_TCP_PORT, DEFAULT_TCP_PORT);;\n }\n\n int TlsPort;\n if (configDb.get(CONFIG_SETTING_TLS_PORT, TlsPort) != OS_SUCCESS)\n {\n configDb.set(CONFIG_SETTING_TLS_PORT, DEFAULT_TLS_PORT);;\n }\n\n int RtpStart;\n if (configDb.get(CONFIG_SETTING_RTP_START, RtpStart) != OS_SUCCESS)\n {\n configDb.set(CONFIG_SETTING_RTP_START, DEFAULT_RTP_START);;\n }\n\n int RtpEnd;\n if (configDb.get(CONFIG_SETTING_RTP_END, RtpEnd) != OS_SUCCESS)\n {\n configDb.set(CONFIG_SETTING_RTP_END, DEFAULT_RTP_END);;\n }\n \n NameAddr myAor;\n ConferenceUserAgent ua(configDb, myAor);\n \n while (!gShutdownFlag)\n {\n OsTask::delay(1000);\n }\n\n \/\/ Flush the log file\n OsSysLog::flush();\n\n \/\/ Say goodnight Gracie...\n return 0;\n}\n\n\n<commit_msg>resip namespace<commit_after>\/\/ \n\/\/ \n\/\/ Copyright (C) 2005 Jason Fischl, Dan Petrie\n\/\/\n\/\/ Copyright (C) 2005 SIPfoundry Inc.\n\/\/ Licensed by SIPfoundry under the LGPL license.\n\/\/ \n\/\/ Copyright (C) 2005 Pingtel Corp.\n\/\/ Licensed to SIPfoundry under a Contributor Agreement.\n\/\/ \n\/\/ $$\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/ SYSTEM INCLUDES\n#include <stdio.h>\n#include <signal.h>\n#include <unistd.h>\n\n\/\/ APPLICATION INCLUDES\n#include <os\/OsFS.h>\n#include <os\/OsSysLog.h>\n#include <os\/OsConfigDb.h>\n#include <net\/NameValueTokenizer.h>\n#include \"resip\/stack\/NameAddr.hxx\"\n#include \"ConferenceUserAgent.h\"\n\n\/\/ DEFINES\n#ifndef SIPX_VERSION\n# define SIPXCHANGE_VERSION SipXpbxVersion\n# define SIPXCHANGE_VERSION_COMMENT SipXpbxBuildStamp\n#else\n# define SIPXCHANGE_VERSION SIPX_VERSION\n# define SIPXCHANGE_VERSION_COMMENT \"\"\n#endif\n\n#define CONFIG_SETTINGS_FILE \"bbridge.conf\"\n#define CONFIG_ETC_DIR SIPX_CONFDIR\n\n#define CONFIG_LOG_FILE \"bbridge.log\"\n#define CONFIG_LOG_DIR SIPX_LOGDIR\n\n#define LOG_FACILITY FAC_CONFERENCE\n\n#define CONFIG_SETTING_LOG_DIR \"BOSTON_BRIDGE_LOG_DIR\"\n#define CONFIG_SETTING_LOG_LEVEL \"BOSTON_BRIDGE_LOG_LEVEL\"\n#define CONFIG_SETTING_LOG_CONSOLE \"BOSTON_BRIDGE_LOG_CONSOLE\"\n#define CONFIG_SETTING_UDP_PORT \"BOSTON_BRIDGE_UDP_PORT\"\n#define CONFIG_SETTING_TCP_PORT \"BOSTON_BRIDGE_TCP_PORT\"\n#define CONFIG_SETTING_RTP_START \"BOSTON_BRIDGE_RTP_START\"\n#define CONFIG_SETTING_RTP_END \"BOSTON_BRIDGE_RTP_END\"\n\n#define DEFAULT_UDP_PORT 5060 \/\/ Default UDP port\n#define DEFAULT_TCP_PORT 5060 \/\/ Default TCP port\n#define DEFAULT_TLS_PORT 5061 \/\/ Default TLS port\n#define DEFAULT_RTP_START 15000\n#define DEFAULT_RTP_END 20000\n\n\/\/ MACROS\n\/\/ EXTERNAL FUNCTIONS\n\/\/ EXTERNAL VARIABLES\n\/\/ CONSTANTS\n\/\/ STRUCTSCONFIG_SETTING_RTP_START\n\/\/ TYPEDEFS\ntypedef void (*sighandler_t)(int);\n\n\/\/ FUNCTIONS\nextern \"C\" {\n void sigHandler( int sig_num );\n sighandler_t pt_signal( int sig_num, sighandler_t handler );\n}\n\n\/\/ FORWARD DECLARATIONS\n\/\/ EXTERNAL VARIABLES\n\/\/ CONSTANTS\n\/\/ STATIC VARIABLE INITIALIZATIONS\n\/\/ GLOBAL VARIABLE INITIALIZATIONS\nUtlBoolean gShutdownFlag = FALSE;\n\n\n\/* ============================ FUNCTIONS ================================= *\/\n\n\/**\n * Description:\n * This is a replacement for signal() which registers a signal handler but sets\n * a flag causing system calls ( namely read() or getchar() ) not to bail out\n * upon recepit of that signal. We need this behavior, so we must call\n * sigaction() manually.\n *\/\nsighandler_t pt_signal( int sig_num, sighandler_t handler)\n{\n#if defined(__pingtel_on_posix__)\n struct sigaction action[2];\n action[0].sa_handler = handler;\n sigemptyset(&action[0].sa_mask);\n action[0].sa_flags = 0;\n sigaction ( sig_num, &action[0], &action[1] );\n return action[1].sa_handler;\n#else\n return signal( sig_num, handler );\n#endif\n}\n\n\n\/**\n * Description:\n * This is the signal handler, When called this sets the\n * global gShutdownFlag allowing the main processing\n * loop to exit cleanly.\n *\/\nvoid sigHandler( int sig_num )\n{\n \/\/ set a global shutdown flag\n gShutdownFlag = TRUE;\n\n \/\/ Unregister interest in the signal to prevent recursive callbacks\n pt_signal( sig_num, SIG_DFL );\n\n \/\/ Minimize the chance that we loose log data configDb.loadFromFile(fileName);\n \n OsSysLog::flush();\n OsSysLog::add(LOG_FACILITY, PRI_CRIT, \"sigHandler: caught signal: %d\", sig_num);\n OsSysLog::flush();\n}\n\n\n\/\/ Initialize the OsSysLog\nvoid initSysLog(OsConfigDb* pConfig)\n{\n UtlString logLevel; \/\/ Controls Log Verbosity\n UtlString consoleLogging; \/\/ Enable console logging by default?\n UtlString fileTarget; \/\/ Path to store log file.\n UtlBoolean bSpecifiedDirError ; \/\/ Set if the specified log dir does not\n \/\/ exist\n struct tagPrioriotyLookupTable\n {\n const char* pIdentity;\n OsSysLogPriority ePriority;\n };\n\n struct tagPrioriotyLookupTable lkupTable[] =\n {\n { \"DEBUG\", PRI_DEBUG},\n { \"INFO\", PRI_INFO},\n { \"NOTICE\", PRI_NOTICE},\n { \"WARNING\", PRI_WARNING},\n { \"ERR\", PRI_ERR},\n { \"CRIT\", PRI_CRIT},\n { \"ALERT\", PRI_ALERT},\n { \"EMERG\", PRI_EMERG},\n };\n\n OsSysLog::initialize(0, \"bbridge\");\n\n\n \/\/\n \/\/ Get\/Apply Log Filename\n \/\/\n fileTarget.remove(0);\n if ((pConfig->get(CONFIG_SETTING_LOG_DIR, fileTarget) != OS_SUCCESS) ||\n fileTarget.isNull() || !OsFileSystem::exists(fileTarget))\n {\n bSpecifiedDirError = !fileTarget.isNull();\n\n \/\/ If the log file directory exists use that, otherwise place the log\n \/\/ in the current directory\n OsPath workingDirectory;\n if (OsFileSystem::exists(CONFIG_LOG_DIR))\n {\n fileTarget = CONFIG_LOG_DIR;\n OsPath path(fileTarget);\n path.getNativePath(workingDirectory);\n\n osPrintf(\"%s : %s\\n\", CONFIG_SETTING_LOG_DIR, workingDirectory.data());\n OsSysLog::add(LOG_FACILITY, PRI_INFO, \"%s : %s\"DEFAULT_UDP_PORT, CONFIG_SETTING_LOG_DIR, workingDirectory.data());\n }\n else\n {\n OsPath path;\n OsFileSystem::getWorkingDirectory(path);\n path.getNativePath(workingDirectory);\n\n osPrintf(\"%s : %s\\n\", CONFIG_SETTING_LOG_DIR, workingDirectory.data());\n OsSysLog::add(LOG_FACILITY, PRI_INFO, \"%s : %s\", CONFIG_SETTING_LOG_DIR, workingDirectory.data());\n }\n\n fileTarget = workingDirectory +\n OsPathBase::separator +\n CONFIG_LOG_FILE;\n }\n else\n {\n bSpecifiedDirError = false;\n osPrintf(\"%s : %s\\n\", CONFIG_SETTING_LOG_DIR, fileTarget.data());\n OsSysLog::add(LOG_FACILITY, PRI_INFO, \"%s : %s\", CONFIG_SETTING_LOG_DIR, fileTarget.data());\n\n fileTarget = fileTarget +\n OsPathBase::separator +\n CONFIG_LOG_FILE;\n }\n OsSysLog::setOutputFile(0, fileTarget);\n\n\n \/\/\n \/\/ Get\/Apply Log Level\n \/\/\n if ((pConfig->get(CONFIG_SETTING_LOG_LEVEL, logLevel) != OS_SUCCESS) ||\n logLevel.isNull())\n {\n logLevel = \"ERR\";\n }\n logLevel.toUpper();\n OsSysLogPriority priority = PRI_ERR;\n int iEntries = sizeof(lkupTable) \/ sizeof(struct tagPrioriotyLookupTable);\n for (int i = 0; i < iEntries; i++)\n {\n if (logLevel == lkupTable[i].pIdentity)\n {\n priority = lkupTable[i].ePriority;\n osPrintf(\"%s : %s\\n\", CONFIG_SETTING_LOG_LEVEL, lkupTable[i].pIdentity);\n OsSysLog::add(LOG_FACILITY, PRI_INFO, \"%s : %s\", CONFIG_SETTING_LOG_LEVEL, lkupTable[i].pIdentity);\n break;\n }\n }\n OsSysLog::setLoggingPriority(priority);\n\n \/\/\n \/\/ Get\/Apply console logging\n \/\/\n UtlBoolean bConsoleLoggingEnabled = false;\n if ((pConfig->get(CONFIG_SETTING_LOG_CONSOLE, consoleLogging) == OS_SUCCESS))\n {\n consoleLogging.toUpper();\n if (consoleLogging == \"ENABLE\")\n {\n OsSysLog::enableConsoleOutput(true);\n bConsoleLoggingEnabled = true;5140\n }\n }\n\n osPrintf(\"%s : %s\\n\", CONFIG_SETTING_LOG_CONSOLE, bConsoleLoggingEnabled ? \"ENABLE\" : \"DISABLE\") ;\n OsSysLog::add(LOG_FACILITY, PRI_INFO, \"%s : %s\", CONFIG_SETTING_LOG_CONSOLE, bConsoleLoggingEnabled ? \"ENABLE\" : \"DISABLE\") ;\n\n if (bSpecifiedDirError)\n {\n OsSysLog::add(FAC_LOG, PRI_CRIT, \"Cannot access %s directory; please check configuration.\", CONFIG_SETTING_LOG_DIR);\n }\n}\n\n\n\/\/\n\/\/ The main entry point to the sipXpark\n\/\/\nint main(int argc, char* argv[])\n{\n \/\/ Configuration Database (used for OsSysLog)\n OsConfigDb configDb;\n\n \/\/ Register Signal handlers so we can perform graceful shutdown\n pt_signal(SIGINT, sigHandler); \/\/ Trap Ctrl-C on NT\n pt_signal(SIGILL, sigHandler);\n pt_signal(SIGABRT, sigHandler); \/\/ Abort signal 6\n pt_signal(SIGFPE, sigHandler); \/\/ Floading Point Exception\n pt_signal(SIGSEGV, sigHandler); \/\/ Address access violations signal 11\n pt_signal(SIGTERM, sigHandler); \/\/ Trap kill -15 on UNIX\n#if defined(__pingtel_on_posix__)\n pt_signal(SIGHUP, sigHandler); \/\/ Hangup\n pt_signal(SIGQUIT, sigHandler);\n pt_signal(SIGPIPE, sigHandler); \/\/ Handle TCP Failure\n pt_signal(SIGBUS, sigHandler);\n pt_signal(SIGSYS, sigHandler);\n pt_signal(SIGXCPU, sigHandler);\n pt_signal(SIGXFSZ, sigHandler);\n pt_signal(SIGUSR1, sigHandler);\n pt_signal(SIGUSR2, sigHandler);\n#endif\n\n UtlString argString;5140\n for(int argIndex = 1; argIndex < argc; argIndex++)\n {\n osPrintf(\"arg[%d]: %s\\n\", argIndex, argv[argIndex]);\n argString = argv[argIndex];\n NameValueTokenizer::frontBackTrim(&argString, \"\\t \");\n if(argString.compareTo(\"-v\") == 0)\n {\n osPrintf(\"Version: %s (%s)\\n\", SIPXCHANGE_VERSION, SIPXCHANGE_VERSION_COMMENT);\n return(1);\n }\n else\n {\n osPrintf(\"usage: %s [-v]\\nwhere:\\n -v provides the software version\\n\",\n argv[0]);\n return(1);\n }\n }\n\n \/\/ Load configuration file file\n OsPath workingDirectory;\n if (OsFileSystem::exists(CONFIG_ETC_DIR))\n {\n workingDirectory = CONFIG_ETC_DIR;\n OsPath path(workingDirectory);\n path.getNativePath(workingDirectory);\n }\n else\n {\n OsPath path;\n OsFileSystem::getWorkingDirectory(path);\n path.getNativePath(workingDirectory);\n }\n\n UtlString fileName = workingDirectory +\n OsPathBase::separator +\n CONFIG_SETTINGS_FILE;\n\n if (configDb.loadFromFile(fileName) != SUCCESS)\n {\n configDb.set(CONFIG_SETTING_LOG_DIR, \"\");\n configDb.set(CONFIG_SETTING_LOG_LEVEL, \"INFO\");\n configDb.set(CONFIG_SETTING_LOG_CONSOLE, \"\");\n configDb.set(CONFIG_SETTING_UDP_PORT, DEFAULT_UDP_PORT);\n configDb.set(CONFIG_SETTING_TCP_PORT, DEFAULT_TCP_PORT);\n configDb.set(CONFIG_SETTING_TLS_PORT, DEFAULT_TLS_PORT);\n configDb.set(CONFIG_SETTING_RTP_START, DEFAULT_RTP_START);\n configDb.set(CONFIG_SETTING_RTP_END, DEFAULT_RTP_END);\n configDb.storeToFile(filename);\n }\n \n \/\/ Initialize log file\n initSysLog(&configDb);\n\n \/\/ Read the user agent parameters from the config file.\n int UdpPort;\n if (configDb.get(CONFIG_SETTING_UDP_PORT, UdpPort) != OS_SUCCESS)\n {\n configDb.set(CONFIG_SETTING_UDP_PORT, DEFAULT_UDP_PORT);;\n }\n \n int TcpPort;\n if (configDb.get(CONFIG_SETTING_TCP_PORT, TcpPort) != OS_SUCCESS)\n {\n configDb.set(CONFIG_SETTING_TCP_PORT, DEFAULT_TCP_PORT);;\n }\n\n int TlsPort;\n if (configDb.get(CONFIG_SETTING_TLS_PORT, TlsPort) != OS_SUCCESS)\n {\n configDb.set(CONFIG_SETTING_TLS_PORT, DEFAULT_TLS_PORT);;\n }\n\n int RtpStart;\n if (configDb.get(CONFIG_SETTING_RTP_START, RtpStart) != OS_SUCCESS)\n {\n configDb.set(CONFIG_SETTING_RTP_START, DEFAULT_RTP_START);;\n }\n\n int RtpEnd;\n if (configDb.get(CONFIG_SETTING_RTP_END, RtpEnd) != OS_SUCCESS)\n {\n configDb.set(CONFIG_SETTING_RTP_END, DEFAULT_RTP_END);;\n }\n \n resip::NameAddr myAor;\n ConferenceUserAgent ua(configDb, myAor);\n \n while (!gShutdownFlag)\n {\n OsTask::delay(1000);\n }\n\n \/\/ Flush the log file\n OsSysLog::flush();\n\n \/\/ Say goodnight Gracie...\n return 0;\n}\n\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright 2013 Google Inc.\n *\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n *\/\n\n#include \"SkBenchmark.h\"\n#include \"SkCanvas.h\"\n#include \"SkPaint.h\"\n#include \"SkRandom.h\"\n#include \"SkShader.h\"\n#include \"SkString.h\"\n#include \"SkBlurMask.h\"\n\n#define SMALL SkIntToScalar(2)\n#define REAL SkFloatToScalar(1.5f)\n#define BIG SkIntToScalar(10)\n#define REALBIG SkFloatToScalar(30.5f)\n\nclass BlurRectBench: public SkBenchmark {\n SkScalar fRadius;\n SkString fName;\n\npublic:\n BlurRectBench(void *param, SkScalar rad) : INHERITED(param) {\n fRadius = rad;\n }\n\nprotected:\n virtual const char* onGetName() {\n return fName.c_str();\n }\n\n SkScalar radius() const {\n return fRadius;\n }\n\n void setName(const SkString& name) {\n fName = name;\n }\n\n virtual void onDraw(SkCanvas* canvas) {\n SkPaint paint;\n this->setupPaint(&paint);\n\n paint.setAntiAlias(true);\n\n SkScalar pad = fRadius*3\/2 + SK_Scalar1;\n SkRect r = SkRect::MakeWH(2 * pad + SK_Scalar1, 2 * pad + SK_Scalar1);\n\n int loop_count;\n\n if (fRadius > SkIntToScalar(50)) {\n loop_count = 10;\n } else if (fRadius > SkIntToScalar(5)) {\n loop_count = 1000;\n } else {\n loop_count = 10000;\n }\n\n preBenchSetup(r);\n\n for (int i = 0; i < SkBENCHLOOP(loop_count); i++) {\n makeBlurryRect(r);\n }\n }\n\n virtual void makeBlurryRect(const SkRect&) = 0;\n virtual void preBenchSetup(const SkRect&) {}\nprivate:\n typedef SkBenchmark INHERITED;\n};\n\n\nclass BlurRectDirectBench: public BlurRectBench {\n public:\n BlurRectDirectBench(void *param, SkScalar rad) : BlurRectBench(param, rad) {\n SkString name;\n\n if (SkScalarFraction(rad) != 0) {\n name.printf(\"blurrect_direct_%.2f\", SkScalarToFloat(rad));\n } else {\n name.printf(\"blurrect_direct_%d\", SkScalarRound(rad));\n }\n\n setName(name);\n }\nprotected:\n virtual void makeBlurryRect(const SkRect& r) SK_OVERRIDE {\n SkMask mask;\n SkBlurMask::BlurRect(&mask, r, radius(), SkBlurMask::kNormal_Style,\n SkBlurMask::kHigh_Quality);\n }\n};\n\nclass BlurRectSeparableBench: public BlurRectBench {\n SkMask fSrcMask;\npublic:\n BlurRectSeparableBench(void *param, SkScalar rad) : BlurRectBench(param, rad) {\n SkString name;\n if (SkScalarFraction(rad) != 0) {\n name.printf(\"blurrect_separable_%.2f\", SkScalarToFloat(rad));\n } else {\n name.printf(\"blurrect_separable_%d\", SkScalarRound(rad));\n }\n\n setName(name);\n }\n\nprotected:\n virtual void preBenchSetup(const SkRect& r) SK_OVERRIDE {\n r.roundOut(&fSrcMask.fBounds);\n fSrcMask.fFormat = SkMask::kA8_Format;\n fSrcMask.fRowBytes = fSrcMask.fBounds.width();\n fSrcMask.fImage = SkMask::AllocImage(fSrcMask.computeTotalImageSize());\n\n memset(fSrcMask.fImage, 0xff, fSrcMask.computeTotalImageSize());\n }\n\n virtual void makeBlurryRect(const SkRect& r) SK_OVERRIDE {\n SkMask mask;\n SkBlurMask::BlurSeparable(&mask, fSrcMask, radius(),\n SkBlurMask::kNormal_Style,\n SkBlurMask::kHigh_Quality);\n }\n};\n\nDEF_BENCH(return new BlurRectSeparableBench(p, SMALL);)\nDEF_BENCH(return new BlurRectSeparableBench(p, BIG);)\nDEF_BENCH(return new BlurRectSeparableBench(p, REALBIG);)\nDEF_BENCH(return new BlurRectSeparableBench(p, REAL);)\nDEF_BENCH(return new BlurRectDirectBench(p, SMALL);)\nDEF_BENCH(return new BlurRectDirectBench(p, BIG);)\nDEF_BENCH(return new BlurRectDirectBench(p, REALBIG);)\nDEF_BENCH(return new BlurRectDirectBench(p, REAL);)\n<commit_msg>speculative change to speedup blurrect bench for large radius, to see if the bots are timing out<commit_after>\/*\n * Copyright 2013 Google Inc.\n *\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n *\/\n\n#include \"SkBenchmark.h\"\n#include \"SkCanvas.h\"\n#include \"SkPaint.h\"\n#include \"SkRandom.h\"\n#include \"SkShader.h\"\n#include \"SkString.h\"\n#include \"SkBlurMask.h\"\n\n#define SMALL SkIntToScalar(2)\n#define REAL SkFloatToScalar(1.5f)\n#define BIG SkIntToScalar(10)\n#define REALBIG SkFloatToScalar(30.5f)\n\nclass BlurRectBench: public SkBenchmark {\n SkScalar fRadius;\n SkString fName;\n\npublic:\n BlurRectBench(void *param, SkScalar rad) : INHERITED(param) {\n fRadius = rad;\n }\n\nprotected:\n virtual const char* onGetName() {\n return fName.c_str();\n }\n\n SkScalar radius() const {\n return fRadius;\n }\n\n void setName(const SkString& name) {\n fName = name;\n }\n\n virtual void onDraw(SkCanvas* canvas) {\n SkPaint paint;\n this->setupPaint(&paint);\n\n paint.setAntiAlias(true);\n\n SkScalar pad = fRadius*3\/2 + SK_Scalar1;\n SkRect r = SkRect::MakeWH(2 * pad + SK_Scalar1, 2 * pad + SK_Scalar1);\n\n int loop_count;\n\n if (fRadius > SkIntToScalar(25)) {\n loop_count = 100;\n } else if (fRadius > SkIntToScalar(5)) {\n loop_count = 1000;\n } else {\n loop_count = 10000;\n }\n\n preBenchSetup(r);\n\n for (int i = 0; i < SkBENCHLOOP(loop_count); i++) {\n makeBlurryRect(r);\n }\n }\n\n virtual void makeBlurryRect(const SkRect&) = 0;\n virtual void preBenchSetup(const SkRect&) {}\nprivate:\n typedef SkBenchmark INHERITED;\n};\n\n\nclass BlurRectDirectBench: public BlurRectBench {\n public:\n BlurRectDirectBench(void *param, SkScalar rad) : BlurRectBench(param, rad) {\n SkString name;\n\n if (SkScalarFraction(rad) != 0) {\n name.printf(\"blurrect_direct_%.2f\", SkScalarToFloat(rad));\n } else {\n name.printf(\"blurrect_direct_%d\", SkScalarRound(rad));\n }\n\n setName(name);\n }\nprotected:\n virtual void makeBlurryRect(const SkRect& r) SK_OVERRIDE {\n SkMask mask;\n SkBlurMask::BlurRect(&mask, r, radius(), SkBlurMask::kNormal_Style,\n SkBlurMask::kHigh_Quality);\n }\n};\n\nclass BlurRectSeparableBench: public BlurRectBench {\n SkMask fSrcMask;\npublic:\n BlurRectSeparableBench(void *param, SkScalar rad) : BlurRectBench(param, rad) {\n SkString name;\n if (SkScalarFraction(rad) != 0) {\n name.printf(\"blurrect_separable_%.2f\", SkScalarToFloat(rad));\n } else {\n name.printf(\"blurrect_separable_%d\", SkScalarRound(rad));\n }\n\n setName(name);\n }\n\nprotected:\n virtual void preBenchSetup(const SkRect& r) SK_OVERRIDE {\n r.roundOut(&fSrcMask.fBounds);\n fSrcMask.fFormat = SkMask::kA8_Format;\n fSrcMask.fRowBytes = fSrcMask.fBounds.width();\n fSrcMask.fImage = SkMask::AllocImage(fSrcMask.computeTotalImageSize());\n\n memset(fSrcMask.fImage, 0xff, fSrcMask.computeTotalImageSize());\n }\n\n virtual void makeBlurryRect(const SkRect& r) SK_OVERRIDE {\n SkMask mask;\n SkBlurMask::BlurSeparable(&mask, fSrcMask, radius(),\n SkBlurMask::kNormal_Style,\n SkBlurMask::kHigh_Quality);\n }\n};\n\nDEF_BENCH(return new BlurRectSeparableBench(p, SMALL);)\nDEF_BENCH(return new BlurRectSeparableBench(p, BIG);)\nDEF_BENCH(return new BlurRectSeparableBench(p, REALBIG);)\nDEF_BENCH(return new BlurRectSeparableBench(p, REAL);)\nDEF_BENCH(return new BlurRectDirectBench(p, SMALL);)\nDEF_BENCH(return new BlurRectDirectBench(p, BIG);)\nDEF_BENCH(return new BlurRectDirectBench(p, REALBIG);)\nDEF_BENCH(return new BlurRectDirectBench(p, REAL);)\n<|endoftext|>"} {"text":"<commit_before>\/\/--------------------------------------------------------------------*- C++ -*-\n\/\/ CLING - the C++ LLVM-based InterpreterG :)\n\/\/ author: Axel Naumann <axel@cern.ch>\n\/\/\n\/\/ This file is dual-licensed: you can choose to license it under the University\n\/\/ of Illinois Open Source License or the GNU Lesser General Public License. See\n\/\/ LICENSE.TXT for details.\n\/\/------------------------------------------------------------------------------\n\n#include \"IncrementalExecutor.h\"\n#include \"IncrementalJIT.h\"\n#include \"Threading.h\"\n\n#include \"cling\/Interpreter\/Value.h\"\n#include \"cling\/Interpreter\/Transaction.h\"\n#include \"cling\/Utils\/AST.h\"\n#include \"cling\/Utils\/Output.h\"\n#include \"cling\/Utils\/Platform.h\"\n\n#include \"clang\/Basic\/Diagnostic.h\"\n#include \"clang\/Basic\/TargetOptions.h\"\n#include \"clang\/Frontend\/CodeGenOptions.h\"\n#include \"clang\/Frontend\/CompilerInstance.h\"\n\n#include \"llvm\/IR\/Constants.h\"\n#include \"llvm\/IR\/Instructions.h\"\n#include \"llvm\/IR\/LLVMContext.h\"\n#include \"llvm\/IR\/Module.h\"\n#include \"llvm\/IR\/LegacyPassManager.h\"\n#include \"llvm\/ADT\/SmallPtrSet.h\"\n#include \"llvm\/ADT\/Triple.h\"\n#include \"llvm\/Support\/Host.h\"\n#include \"llvm\/Support\/TargetRegistry.h\"\n#include \"llvm\/Target\/TargetMachine.h\"\n\nusing namespace llvm;\n\nnamespace cling {\n\nnamespace {\n\nstatic std::unique_ptr<TargetMachine>\nCreateHostTargetMachine(const clang::CompilerInstance& CI) {\n const clang::TargetOptions& TargetOpts = CI.getTargetOpts();\n const clang::CodeGenOptions& CGOpt = CI.getCodeGenOpts();\n const std::string& Triple = TargetOpts.Triple;\n\n std::string Error;\n const Target *TheTarget = TargetRegistry::lookupTarget(Triple, Error);\n if (!TheTarget) {\n cling::errs() << \"cling::IncrementalExecutor: unable to find target:\\n\"\n << Error;\n return std::unique_ptr<TargetMachine>();\n }\n\n\/\/ We have to use large code model for PowerPC64 because TOC and text sections\n\/\/ can be more than 2GB apart.\n#if defined(__powerpc64__) || defined(__PPC64__)\n CodeModel::Model CMModel = CodeModel::Large;\n#else\n CodeModel::Model CMModel = CodeModel::JITDefault;\n#endif\n CodeGenOpt::Level OptLevel = CodeGenOpt::Default;\n switch (CGOpt.OptimizationLevel) {\n case 0: OptLevel = CodeGenOpt::None; break;\n case 1: OptLevel = CodeGenOpt::Less; break;\n case 2: OptLevel = CodeGenOpt::Default; break;\n case 3: OptLevel = CodeGenOpt::Aggressive; break;\n default: OptLevel = CodeGenOpt::Default;\n }\n\n std::string MCPU;\n std::string FeaturesStr;\n\n return std::unique_ptr<TargetMachine>(TheTarget->createTargetMachine(Triple,\n MCPU, FeaturesStr,\n llvm::TargetOptions(),\n Optional<Reloc::Model>(), CMModel,\n OptLevel));\n}\n\n} \/\/ anonymous namespace\n\nIncrementalExecutor::IncrementalExecutor(clang::DiagnosticsEngine& diags,\n const clang::CompilerInstance& CI):\n m_Callbacks(nullptr), m_externalIncrementalExecutor(nullptr)\n#if 0\n : m_Diags(diags)\n#endif\n{\n\n \/\/ MSVC doesn't support m_AtExitFuncsSpinLock=ATOMIC_FLAG_INIT; in the class definition\n std::atomic_flag_clear( &m_AtExitFuncsSpinLock );\n\n std::unique_ptr<TargetMachine> TM(CreateHostTargetMachine(CI));\n m_BackendPasses.reset(new BackendPasses(CI.getCodeGenOpts(),\n CI.getTargetOpts(),\n CI.getLangOpts(),\n *TM));\n m_JIT.reset(new IncrementalJIT(*this, std::move(TM)));\n}\n\n\/\/ Keep in source: ~unique_ptr<ClingJIT> needs ClingJIT\nIncrementalExecutor::~IncrementalExecutor() {}\n\nvoid IncrementalExecutor::shuttingDown() {\n \/\/ It is legal to register an atexit handler from within another atexit\n \/\/ handler and furthor-more the standard says they need to run in reverse\n \/\/ order, so this function must be recursion safe.\n AtExitFunctions Local;\n {\n cling::internal::SpinLockGuard slg(m_AtExitFuncsSpinLock);\n \/\/ Check this case first, to avoid the swap all-together.\n if (m_AtExitFuncs.empty())\n return;\n Local.swap(m_AtExitFuncs);\n }\n for (auto&& Ordered : llvm::reverse(Local.ordered())) {\n for (auto&& AtExit : llvm::reverse(Ordered->second))\n AtExit();\n \/\/ The standard says that they need to run in reverse order, which means\n \/\/ anything added from 'AtExit()' must now be run!\n shuttingDown();\n }\n}\n\nvoid IncrementalExecutor::AddAtExitFunc(void (*func)(void*), void* arg,\n const std::shared_ptr<llvm::Module>& M) {\n \/\/ Register a CXAAtExit function\n cling::internal::SpinLockGuard slg(m_AtExitFuncsSpinLock);\n m_AtExitFuncs[M].emplace_back(func, arg);\n}\n\nvoid unresolvedSymbol()\n{\n \/\/ This might get called recursively, or a billion of times. Do not generate\n \/\/ useless output; unresolvedSymbol() is always handed out with an error\n \/\/ message - that's enough.\n \/\/cling::errs() << \"IncrementalExecutor: calling unresolved symbol, \"\n \/\/ \"see previous error message!\\n\";\n\n \/\/ throw exception instead?\n}\n\nvoid* IncrementalExecutor::HandleMissingFunction(const std::string& mangled_name)\n{\n \/\/ Not found in the map, add the symbol in the list of unresolved symbols\n if (m_unresolvedSymbols.insert(mangled_name).second) {\n \/\/cling::errs() << \"IncrementalExecutor: use of undefined symbol '\"\n \/\/ << mangled_name << \"'!\\n\";\n }\n\n return utils::FunctionToVoidPtr(&unresolvedSymbol);\n}\n\nvoid* IncrementalExecutor::NotifyLazyFunctionCreators(const std::string& mangled_name)\n{\n for (std::vector<LazyFunctionCreatorFunc_t>::iterator it\n = m_lazyFuncCreator.begin(), et = m_lazyFuncCreator.end();\n it != et; ++it) {\n void* ret = (void*)((LazyFunctionCreatorFunc_t)*it)(mangled_name);\n if (ret)\n return ret;\n }\n void *address = nullptr;\n if (m_externalIncrementalExecutor)\n address = m_externalIncrementalExecutor->getAddressOfGlobal(mangled_name);\n\n return (address ? address : HandleMissingFunction(mangled_name));\n}\n\n#if 0\n\/\/ FIXME: employ to empty module dependencies *within* the *current* module.\nstatic void\nfreeCallersOfUnresolvedSymbols(llvm::SmallVectorImpl<llvm::Function*>&\n funcsToFree, llvm::ExecutionEngine* engine) {\n llvm::SmallPtrSet<llvm::Function*, 40> funcsToFreeUnique;\n for (size_t i = 0; i < funcsToFree.size(); ++i) {\n llvm::Function* func = funcsToFree[i];\n assert(func && \"Cannot free NULL function\");\n if (funcsToFreeUnique.insert(func).second) {\n for (llvm::Value::use_iterator IU = func->use_begin(),\n EU = func->use_end(); IU != EU; ++IU) {\n llvm::Instruction* instUser = llvm::dyn_cast<llvm::Instruction>(*IU);\n if (!instUser) continue;\n if (!instUser->getParent()) continue;\n if (llvm::Function* userFunc = instUser->getParent()->getParent())\n funcsToFree.push_back(userFunc);\n }\n }\n }\n for (llvm::SmallPtrSet<llvm::Function*, 40>::iterator\n I = funcsToFreeUnique.begin(), E = funcsToFreeUnique.end();\n I != E; ++I) {\n \/\/ This should force the JIT to recompile the function. But the stubs stay,\n \/\/ and the JIT reuses the stubs now pointing nowhere, i.e. without updating\n \/\/ the machine code address. Fix the JIT, or hope that MCJIT helps.\n \/\/engine->freeMachineCodeForFunction(*I);\n engine->updateGlobalMapping(*I, 0);\n }\n}\n#endif\n\nIncrementalExecutor::ExecutionResult\nIncrementalExecutor::runStaticInitializersOnce(const Transaction& T) {\n auto m = T.getModule();\n assert(m.get() && \"Module must not be null\");\n\n \/\/ We don't care whether something was unresolved before.\n m_unresolvedSymbols.clear();\n\n \/\/ check if there is any unresolved symbol in the list\n if (diagnoseUnresolvedSymbols(\"static initializers\"))\n return kExeUnresolvedSymbols;\n\n llvm::GlobalVariable* GV\n = m->getGlobalVariable(\"llvm.global_ctors\", true);\n \/\/ Nothing to do is good, too.\n if (!GV) return kExeSuccess;\n\n \/\/ Close similarity to\n \/\/ m_engine->runStaticConstructorsDestructors(false) aka\n \/\/ llvm::ExecutionEngine::runStaticConstructorsDestructors()\n \/\/ is intentional; we do an extra pass to check whether the JIT\n \/\/ managed to collect all the symbols needed by the niitializers.\n \/\/ Should be an array of '{ i32, void ()* }' structs. The first value is\n \/\/ the init priority, which we ignore.\n llvm::ConstantArray *InitList\n = llvm::dyn_cast<llvm::ConstantArray>(GV->getInitializer());\n\n \/\/ We need to delete it here just in case we have recursive inits, otherwise\n \/\/ it will call inits multiple times.\n GV->eraseFromParent();\n\n if (InitList == 0)\n return kExeSuccess;\n\n \/\/SmallVector<Function*, 2> initFuncs;\n\n for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {\n llvm::ConstantStruct *CS\n = llvm::dyn_cast<llvm::ConstantStruct>(InitList->getOperand(i));\n if (CS == 0) continue;\n\n llvm::Constant *FP = CS->getOperand(1);\n if (FP->isNullValue())\n continue; \/\/ Found a sentinal value, ignore.\n\n \/\/ Strip off constant expression casts.\n if (llvm::ConstantExpr *CE = llvm::dyn_cast<llvm::ConstantExpr>(FP))\n if (CE->isCast())\n FP = CE->getOperand(0);\n\n \/\/ Execute the ctor\/dtor function!\n if (llvm::Function *F = llvm::dyn_cast<llvm::Function>(FP)) {\n const llvm::StringRef fName = F->getName();\n executeInit(fName);\n\/*\n initFuncs.push_back(F);\n if (fName.startswith(\"_GLOBAL__sub_I_\")) {\n BasicBlock& BB = F->getEntryBlock();\n for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E; ++I)\n if (CallInst* call = dyn_cast<CallInst>(I))\n initFuncs.push_back(call->getCalledFunction());\n }\n*\/\n }\n }\n\n\/*\n for (SmallVector<Function*,2>::iterator I = initFuncs.begin(),\n E = initFuncs.end(); I != E; ++I) {\n \/\/ Cleanup also the dangling init functions. They are in the form:\n \/\/ define internal void @_GLOBAL__I_aN() section \"...\"{\n \/\/ entry:\n \/\/ call void @__cxx_global_var_init(N-1)()\n \/\/ call void @__cxx_global_var_initM()\n \/\/ ret void\n \/\/ }\n \/\/\n \/\/ define internal void @__cxx_global_var_init(N-1)() section \"...\" {\n \/\/ entry:\n \/\/ call void @_ZN7MyClassC1Ev(%struct.MyClass* @n)\n \/\/ ret void\n \/\/ }\n\n \/\/ Erase __cxx_global_var_init(N-1)() first.\n (*I)->removeDeadConstantUsers();\n (*I)->eraseFromParent();\n }\n*\/\n\n return kExeSuccess;\n}\n\nvoid IncrementalExecutor::runAndRemoveStaticDestructors(Transaction* T) {\n assert(T && \"Must be set\");\n \/\/ Collect all the dtors bound to this transaction.\n AtExitFunctions::mapped_type Local;\n {\n cling::internal::SpinLockGuard slg(m_AtExitFuncsSpinLock);\n auto Itr = m_AtExitFuncs.find(T->getModule());\n if (Itr == m_AtExitFuncs.end()) return;\n m_AtExitFuncs.erase(Itr, &Local);\n } \/\/ end of spin lock lifetime block.\n\n \/\/ 'Unload' the cxa_atexit, atexit entities.\n for (auto&& AtExit : llvm::reverse(Local)) {\n AtExit();\n \/\/ Run anything that was just registered in 'AtExit()'\n runAndRemoveStaticDestructors(T);\n }\n}\n\nvoid\nIncrementalExecutor::installLazyFunctionCreator(LazyFunctionCreatorFunc_t fp)\n{\n m_lazyFuncCreator.push_back(fp);\n}\n\nbool\nIncrementalExecutor::addSymbol(const char* Name, void* Addr,\n bool Jit) {\n return m_JIT->lookupSymbol(Name, Addr, Jit).second;\n}\n\nvoid* IncrementalExecutor::getAddressOfGlobal(llvm::StringRef symbolName,\n bool* fromJIT \/*=0*\/) {\n \/\/ Return a symbol's address, and whether it was jitted.\n void* address = m_JIT->lookupSymbol(symbolName).first;\n\n \/\/ It's not from the JIT if it's in a dylib.\n if (fromJIT)\n *fromJIT = !address;\n\n if (!address)\n return (void*)m_JIT->getSymbolAddress(symbolName, false \/*no dlsym*\/);\n\n return address;\n}\n\nvoid*\nIncrementalExecutor::getPointerToGlobalFromJIT(const llvm::GlobalValue& GV) {\n \/\/ Get the function \/ variable pointer referenced by GV.\n\n \/\/ We don't care whether something was unresolved before.\n m_unresolvedSymbols.clear();\n\n void* addr = (void*)m_JIT->getSymbolAddress(GV.getName(),\n false \/*no dlsym*\/);\n\n if (diagnoseUnresolvedSymbols(GV.getName(), \"symbol\"))\n return 0;\n return addr;\n}\n\nbool IncrementalExecutor::diagnoseUnresolvedSymbols(llvm::StringRef trigger,\n llvm::StringRef title) {\n if (m_unresolvedSymbols.empty())\n return false;\n\n llvm::SmallVector<llvm::Function*, 128> funcsToFree;\n for (const std::string& sym : m_unresolvedSymbols) {\n#if 0\n \/\/ FIXME: This causes a lot of test failures, for some reason it causes\n \/\/ the call to HandleMissingFunction to be elided.\n unsigned diagID = m_Diags.getCustomDiagID(clang::DiagnosticsEngine::Error,\n \"%0 unresolved while jitting %1\");\n (void)diagID;\n \/\/m_Diags.Report(diagID) << sym << funcname; \/\/ TODO: demangle the names.\n#endif\n\n cling::errs() << \"IncrementalExecutor::executeFunction: symbol '\" << sym\n << \"' unresolved while linking \";\n if (trigger.find(utils::Synthesize::UniquePrefix) != llvm::StringRef::npos)\n cling::errs() << \"[cling interface function]\";\n else {\n if (!title.empty())\n cling::errs() << title << \" '\";\n cling::errs() << trigger;\n if (!title.empty())\n cling::errs() << \"'\";\n }\n cling::errs() << \"!\\n\";\n\n \/\/ Be helpful, demangle!\n std::string demangledName = platform::Demangle(sym);\n if (!demangledName.empty()) {\n cling::errs()\n << \"You are probably missing the definition of \"\n << demangledName << \"\\n\"\n << \"Maybe you need to load the corresponding shared library?\\n\";\n }\n\n \/\/llvm::Function *ff = m_engine->FindFunctionNamed(i->c_str());\n \/\/ i could also reference a global variable, in which case ff == 0.\n \/\/if (ff)\n \/\/ funcsToFree.push_back(ff);\n }\n \/\/freeCallersOfUnresolvedSymbols(funcsToFree, m_engine.get());\n m_unresolvedSymbols.clear();\n return true;\n}\n\n}\/\/ end namespace cling\n<commit_msg>[cling] Fix thread local storage in the cling JIT<commit_after>\/\/--------------------------------------------------------------------*- C++ -*-\n\/\/ CLING - the C++ LLVM-based InterpreterG :)\n\/\/ author: Axel Naumann <axel@cern.ch>\n\/\/\n\/\/ This file is dual-licensed: you can choose to license it under the University\n\/\/ of Illinois Open Source License or the GNU Lesser General Public License. See\n\/\/ LICENSE.TXT for details.\n\/\/------------------------------------------------------------------------------\n\n#include \"IncrementalExecutor.h\"\n#include \"IncrementalJIT.h\"\n#include \"Threading.h\"\n\n#include \"cling\/Interpreter\/Value.h\"\n#include \"cling\/Interpreter\/Transaction.h\"\n#include \"cling\/Utils\/AST.h\"\n#include \"cling\/Utils\/Output.h\"\n#include \"cling\/Utils\/Platform.h\"\n\n#include \"clang\/Basic\/Diagnostic.h\"\n#include \"clang\/Basic\/TargetOptions.h\"\n#include \"clang\/Frontend\/CodeGenOptions.h\"\n#include \"clang\/Frontend\/CompilerInstance.h\"\n\n#include \"llvm\/IR\/Constants.h\"\n#include \"llvm\/IR\/Instructions.h\"\n#include \"llvm\/IR\/LLVMContext.h\"\n#include \"llvm\/IR\/Module.h\"\n#include \"llvm\/IR\/LegacyPassManager.h\"\n#include \"llvm\/ADT\/SmallPtrSet.h\"\n#include \"llvm\/ADT\/Triple.h\"\n#include \"llvm\/Support\/Host.h\"\n#include \"llvm\/Support\/TargetRegistry.h\"\n#include \"llvm\/Target\/TargetMachine.h\"\n\nusing namespace llvm;\n\nnamespace cling {\n\nnamespace {\n\nstatic std::unique_ptr<TargetMachine>\nCreateHostTargetMachine(const clang::CompilerInstance& CI) {\n const clang::TargetOptions& TargetOpts = CI.getTargetOpts();\n const clang::CodeGenOptions& CGOpt = CI.getCodeGenOpts();\n const std::string& Triple = TargetOpts.Triple;\n\n std::string Error;\n const Target *TheTarget = TargetRegistry::lookupTarget(Triple, Error);\n if (!TheTarget) {\n cling::errs() << \"cling::IncrementalExecutor: unable to find target:\\n\"\n << Error;\n return std::unique_ptr<TargetMachine>();\n }\n\n\/\/ We have to use large code model for PowerPC64 because TOC and text sections\n\/\/ can be more than 2GB apart.\n#if defined(__powerpc64__) || defined(__PPC64__)\n CodeModel::Model CMModel = CodeModel::Large;\n#else\n CodeModel::Model CMModel = CodeModel::JITDefault;\n#endif\n CodeGenOpt::Level OptLevel = CodeGenOpt::Default;\n switch (CGOpt.OptimizationLevel) {\n case 0: OptLevel = CodeGenOpt::None; break;\n case 1: OptLevel = CodeGenOpt::Less; break;\n case 2: OptLevel = CodeGenOpt::Default; break;\n case 3: OptLevel = CodeGenOpt::Aggressive; break;\n default: OptLevel = CodeGenOpt::Default;\n }\n\n std::string MCPU;\n std::string FeaturesStr;\n\n auto TM = std::unique_ptr<TargetMachine>(TheTarget->createTargetMachine(Triple,\n MCPU, FeaturesStr,\n llvm::TargetOptions(),\n Optional<Reloc::Model>(), CMModel,\n OptLevel));\n TM->Options.EmulatedTLS = true;\n return TM;\n}\n\n} \/\/ anonymous namespace\n\nIncrementalExecutor::IncrementalExecutor(clang::DiagnosticsEngine& diags,\n const clang::CompilerInstance& CI):\n m_Callbacks(nullptr), m_externalIncrementalExecutor(nullptr)\n#if 0\n : m_Diags(diags)\n#endif\n{\n\n \/\/ MSVC doesn't support m_AtExitFuncsSpinLock=ATOMIC_FLAG_INIT; in the class definition\n std::atomic_flag_clear( &m_AtExitFuncsSpinLock );\n\n std::unique_ptr<TargetMachine> TM(CreateHostTargetMachine(CI));\n m_BackendPasses.reset(new BackendPasses(CI.getCodeGenOpts(),\n CI.getTargetOpts(),\n CI.getLangOpts(),\n *TM));\n m_JIT.reset(new IncrementalJIT(*this, std::move(TM)));\n}\n\n\/\/ Keep in source: ~unique_ptr<ClingJIT> needs ClingJIT\nIncrementalExecutor::~IncrementalExecutor() {}\n\nvoid IncrementalExecutor::shuttingDown() {\n \/\/ It is legal to register an atexit handler from within another atexit\n \/\/ handler and furthor-more the standard says they need to run in reverse\n \/\/ order, so this function must be recursion safe.\n AtExitFunctions Local;\n {\n cling::internal::SpinLockGuard slg(m_AtExitFuncsSpinLock);\n \/\/ Check this case first, to avoid the swap all-together.\n if (m_AtExitFuncs.empty())\n return;\n Local.swap(m_AtExitFuncs);\n }\n for (auto&& Ordered : llvm::reverse(Local.ordered())) {\n for (auto&& AtExit : llvm::reverse(Ordered->second))\n AtExit();\n \/\/ The standard says that they need to run in reverse order, which means\n \/\/ anything added from 'AtExit()' must now be run!\n shuttingDown();\n }\n}\n\nvoid IncrementalExecutor::AddAtExitFunc(void (*func)(void*), void* arg,\n const std::shared_ptr<llvm::Module>& M) {\n \/\/ Register a CXAAtExit function\n cling::internal::SpinLockGuard slg(m_AtExitFuncsSpinLock);\n m_AtExitFuncs[M].emplace_back(func, arg);\n}\n\nvoid unresolvedSymbol()\n{\n \/\/ This might get called recursively, or a billion of times. Do not generate\n \/\/ useless output; unresolvedSymbol() is always handed out with an error\n \/\/ message - that's enough.\n \/\/cling::errs() << \"IncrementalExecutor: calling unresolved symbol, \"\n \/\/ \"see previous error message!\\n\";\n\n \/\/ throw exception instead?\n}\n\nvoid* IncrementalExecutor::HandleMissingFunction(const std::string& mangled_name)\n{\n \/\/ Not found in the map, add the symbol in the list of unresolved symbols\n if (m_unresolvedSymbols.insert(mangled_name).second) {\n \/\/cling::errs() << \"IncrementalExecutor: use of undefined symbol '\"\n \/\/ << mangled_name << \"'!\\n\";\n }\n\n return utils::FunctionToVoidPtr(&unresolvedSymbol);\n}\n\nvoid* IncrementalExecutor::NotifyLazyFunctionCreators(const std::string& mangled_name)\n{\n for (std::vector<LazyFunctionCreatorFunc_t>::iterator it\n = m_lazyFuncCreator.begin(), et = m_lazyFuncCreator.end();\n it != et; ++it) {\n void* ret = (void*)((LazyFunctionCreatorFunc_t)*it)(mangled_name);\n if (ret)\n return ret;\n }\n void *address = nullptr;\n if (m_externalIncrementalExecutor)\n address = m_externalIncrementalExecutor->getAddressOfGlobal(mangled_name);\n\n return (address ? address : HandleMissingFunction(mangled_name));\n}\n\n#if 0\n\/\/ FIXME: employ to empty module dependencies *within* the *current* module.\nstatic void\nfreeCallersOfUnresolvedSymbols(llvm::SmallVectorImpl<llvm::Function*>&\n funcsToFree, llvm::ExecutionEngine* engine) {\n llvm::SmallPtrSet<llvm::Function*, 40> funcsToFreeUnique;\n for (size_t i = 0; i < funcsToFree.size(); ++i) {\n llvm::Function* func = funcsToFree[i];\n assert(func && \"Cannot free NULL function\");\n if (funcsToFreeUnique.insert(func).second) {\n for (llvm::Value::use_iterator IU = func->use_begin(),\n EU = func->use_end(); IU != EU; ++IU) {\n llvm::Instruction* instUser = llvm::dyn_cast<llvm::Instruction>(*IU);\n if (!instUser) continue;\n if (!instUser->getParent()) continue;\n if (llvm::Function* userFunc = instUser->getParent()->getParent())\n funcsToFree.push_back(userFunc);\n }\n }\n }\n for (llvm::SmallPtrSet<llvm::Function*, 40>::iterator\n I = funcsToFreeUnique.begin(), E = funcsToFreeUnique.end();\n I != E; ++I) {\n \/\/ This should force the JIT to recompile the function. But the stubs stay,\n \/\/ and the JIT reuses the stubs now pointing nowhere, i.e. without updating\n \/\/ the machine code address. Fix the JIT, or hope that MCJIT helps.\n \/\/engine->freeMachineCodeForFunction(*I);\n engine->updateGlobalMapping(*I, 0);\n }\n}\n#endif\n\nIncrementalExecutor::ExecutionResult\nIncrementalExecutor::runStaticInitializersOnce(const Transaction& T) {\n auto m = T.getModule();\n assert(m.get() && \"Module must not be null\");\n\n \/\/ We don't care whether something was unresolved before.\n m_unresolvedSymbols.clear();\n\n \/\/ check if there is any unresolved symbol in the list\n if (diagnoseUnresolvedSymbols(\"static initializers\"))\n return kExeUnresolvedSymbols;\n\n llvm::GlobalVariable* GV\n = m->getGlobalVariable(\"llvm.global_ctors\", true);\n \/\/ Nothing to do is good, too.\n if (!GV) return kExeSuccess;\n\n \/\/ Close similarity to\n \/\/ m_engine->runStaticConstructorsDestructors(false) aka\n \/\/ llvm::ExecutionEngine::runStaticConstructorsDestructors()\n \/\/ is intentional; we do an extra pass to check whether the JIT\n \/\/ managed to collect all the symbols needed by the niitializers.\n \/\/ Should be an array of '{ i32, void ()* }' structs. The first value is\n \/\/ the init priority, which we ignore.\n llvm::ConstantArray *InitList\n = llvm::dyn_cast<llvm::ConstantArray>(GV->getInitializer());\n\n \/\/ We need to delete it here just in case we have recursive inits, otherwise\n \/\/ it will call inits multiple times.\n GV->eraseFromParent();\n\n if (InitList == 0)\n return kExeSuccess;\n\n \/\/SmallVector<Function*, 2> initFuncs;\n\n for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {\n llvm::ConstantStruct *CS\n = llvm::dyn_cast<llvm::ConstantStruct>(InitList->getOperand(i));\n if (CS == 0) continue;\n\n llvm::Constant *FP = CS->getOperand(1);\n if (FP->isNullValue())\n continue; \/\/ Found a sentinal value, ignore.\n\n \/\/ Strip off constant expression casts.\n if (llvm::ConstantExpr *CE = llvm::dyn_cast<llvm::ConstantExpr>(FP))\n if (CE->isCast())\n FP = CE->getOperand(0);\n\n \/\/ Execute the ctor\/dtor function!\n if (llvm::Function *F = llvm::dyn_cast<llvm::Function>(FP)) {\n const llvm::StringRef fName = F->getName();\n executeInit(fName);\n\/*\n initFuncs.push_back(F);\n if (fName.startswith(\"_GLOBAL__sub_I_\")) {\n BasicBlock& BB = F->getEntryBlock();\n for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E; ++I)\n if (CallInst* call = dyn_cast<CallInst>(I))\n initFuncs.push_back(call->getCalledFunction());\n }\n*\/\n }\n }\n\n\/*\n for (SmallVector<Function*,2>::iterator I = initFuncs.begin(),\n E = initFuncs.end(); I != E; ++I) {\n \/\/ Cleanup also the dangling init functions. They are in the form:\n \/\/ define internal void @_GLOBAL__I_aN() section \"...\"{\n \/\/ entry:\n \/\/ call void @__cxx_global_var_init(N-1)()\n \/\/ call void @__cxx_global_var_initM()\n \/\/ ret void\n \/\/ }\n \/\/\n \/\/ define internal void @__cxx_global_var_init(N-1)() section \"...\" {\n \/\/ entry:\n \/\/ call void @_ZN7MyClassC1Ev(%struct.MyClass* @n)\n \/\/ ret void\n \/\/ }\n\n \/\/ Erase __cxx_global_var_init(N-1)() first.\n (*I)->removeDeadConstantUsers();\n (*I)->eraseFromParent();\n }\n*\/\n\n return kExeSuccess;\n}\n\nvoid IncrementalExecutor::runAndRemoveStaticDestructors(Transaction* T) {\n assert(T && \"Must be set\");\n \/\/ Collect all the dtors bound to this transaction.\n AtExitFunctions::mapped_type Local;\n {\n cling::internal::SpinLockGuard slg(m_AtExitFuncsSpinLock);\n auto Itr = m_AtExitFuncs.find(T->getModule());\n if (Itr == m_AtExitFuncs.end()) return;\n m_AtExitFuncs.erase(Itr, &Local);\n } \/\/ end of spin lock lifetime block.\n\n \/\/ 'Unload' the cxa_atexit, atexit entities.\n for (auto&& AtExit : llvm::reverse(Local)) {\n AtExit();\n \/\/ Run anything that was just registered in 'AtExit()'\n runAndRemoveStaticDestructors(T);\n }\n}\n\nvoid\nIncrementalExecutor::installLazyFunctionCreator(LazyFunctionCreatorFunc_t fp)\n{\n m_lazyFuncCreator.push_back(fp);\n}\n\nbool\nIncrementalExecutor::addSymbol(const char* Name, void* Addr,\n bool Jit) {\n return m_JIT->lookupSymbol(Name, Addr, Jit).second;\n}\n\nvoid* IncrementalExecutor::getAddressOfGlobal(llvm::StringRef symbolName,\n bool* fromJIT \/*=0*\/) {\n \/\/ Return a symbol's address, and whether it was jitted.\n void* address = m_JIT->lookupSymbol(symbolName).first;\n\n \/\/ It's not from the JIT if it's in a dylib.\n if (fromJIT)\n *fromJIT = !address;\n\n if (!address)\n return (void*)m_JIT->getSymbolAddress(symbolName, false \/*no dlsym*\/);\n\n return address;\n}\n\nvoid*\nIncrementalExecutor::getPointerToGlobalFromJIT(const llvm::GlobalValue& GV) {\n \/\/ Get the function \/ variable pointer referenced by GV.\n\n \/\/ We don't care whether something was unresolved before.\n m_unresolvedSymbols.clear();\n\n void* addr = (void*)m_JIT->getSymbolAddress(GV.getName(),\n false \/*no dlsym*\/);\n\n if (diagnoseUnresolvedSymbols(GV.getName(), \"symbol\"))\n return 0;\n return addr;\n}\n\nbool IncrementalExecutor::diagnoseUnresolvedSymbols(llvm::StringRef trigger,\n llvm::StringRef title) {\n if (m_unresolvedSymbols.empty())\n return false;\n\n llvm::SmallVector<llvm::Function*, 128> funcsToFree;\n for (const std::string& sym : m_unresolvedSymbols) {\n#if 0\n \/\/ FIXME: This causes a lot of test failures, for some reason it causes\n \/\/ the call to HandleMissingFunction to be elided.\n unsigned diagID = m_Diags.getCustomDiagID(clang::DiagnosticsEngine::Error,\n \"%0 unresolved while jitting %1\");\n (void)diagID;\n \/\/m_Diags.Report(diagID) << sym << funcname; \/\/ TODO: demangle the names.\n#endif\n\n cling::errs() << \"IncrementalExecutor::executeFunction: symbol '\" << sym\n << \"' unresolved while linking \";\n if (trigger.find(utils::Synthesize::UniquePrefix) != llvm::StringRef::npos)\n cling::errs() << \"[cling interface function]\";\n else {\n if (!title.empty())\n cling::errs() << title << \" '\";\n cling::errs() << trigger;\n if (!title.empty())\n cling::errs() << \"'\";\n }\n cling::errs() << \"!\\n\";\n\n \/\/ Be helpful, demangle!\n std::string demangledName = platform::Demangle(sym);\n if (!demangledName.empty()) {\n cling::errs()\n << \"You are probably missing the definition of \"\n << demangledName << \"\\n\"\n << \"Maybe you need to load the corresponding shared library?\\n\";\n }\n\n \/\/llvm::Function *ff = m_engine->FindFunctionNamed(i->c_str());\n \/\/ i could also reference a global variable, in which case ff == 0.\n \/\/if (ff)\n \/\/ funcsToFree.push_back(ff);\n }\n \/\/freeCallersOfUnresolvedSymbols(funcsToFree, m_engine.get());\n m_unresolvedSymbols.clear();\n return true;\n}\n\n}\/\/ end namespace cling\n<|endoftext|>"} {"text":"<commit_before>#include <FAST\/Visualization\/DualViewWindow.hpp>\n#include <FAST\/Visualization\/HeatmapRenderer\/HeatmapRenderer.hpp>\n#include <FAST\/Algorithms\/ImageResampler\/ImageResampler.hpp>\n#include \"FAST\/Testing.hpp\"\n#include \"FAST\/Streamers\/ImageFileStreamer.hpp\"\n#include \"FAST\/Visualization\/SimpleWindow.hpp\"\n#include \"FAST\/Visualization\/ImageRenderer\/ImageRenderer.hpp\"\n#include \"FAST\/Visualization\/MeshRenderer\/MeshRenderer.hpp\"\n#include \"FAST\/Algorithms\/NeuralNetwork\/PixelClassifier.hpp\"\n\nusing namespace fast;\n\nint main() {\n Reporter::setGlobalReportMethod(Reporter::COUT);\n ImageFileStreamer::pointer streamer = ImageFileStreamer::New();\n streamer->setFilenameFormats({\n \"\/home\/smistad\/data\/eyeguide\/axillary_nerve_block\/17\/2017Feb13_150433\/#.png\",\n \"\/home\/smistad\/data\/eyeguide\/axillary_nerve_block\/17\/2017Feb13_150648\/#.png\",\n \"\/home\/smistad\/data\/eyeguide\/axillary_nerve_block\/17\/2017Feb13_150824\/#.png\",\n \"\/home\/smistad\/data\/eyeguide\/axillary_nerve_block\/5\/2016Dec30_082009\/#.png\",\n \"\/home\/smistad\/data\/eyeguide\/axillary_nerve_block\/5\/2016Dec30_082046\/#.png\",\n \"\/home\/smistad\/data\/eyeguide\/axillary_nerve_block\/5\/2016Dec30_082110\/#.png\",\n });\n streamer->enableLooping();\n streamer->setStartNumber(1);\n streamer->setSleepTime(50);\n streamer->setStreamingMode(STREAMING_MODE_PROCESS_ALL_FRAMES);\n\n PixelClassifier::pointer segmentation = PixelClassifier::New();\n segmentation->setNrOfClasses(6);\n segmentation->load(\"\/home\/smistad\/workspace\/eyeguide_keras\/models\/network_graph.pb\");\n segmentation->setInputSize(256, 256);\n segmentation->setScaleFactor(1.0f\/255.0f);\n segmentation->setOutputParameters({\"Reshape_18\"});\n segmentation->setInputConnection(streamer->getOutputPort());\n segmentation->setHeatmapOutput();\n segmentation->enableRuntimeMeasurements();\n\n HeatmapRenderer::pointer renderer = HeatmapRenderer::New();\n renderer->addInputConnection(segmentation->getOutputPort(1), Color::Red());\n renderer->addInputConnection(segmentation->getOutputPort(2), Color::Yellow());\n renderer->addInputConnection(segmentation->getOutputPort(3), Color::Green());\n renderer->addInputConnection(segmentation->getOutputPort(4), Color::Purple());\n renderer->addInputConnection(segmentation->getOutputPort(5), Color::Cyan());\n renderer->setMaxOpacity(0.2);\n renderer->setMinConfidence(0.25);\n renderer->enableRuntimeMeasurements();\n\n ImageRenderer::pointer renderer2 = ImageRenderer::New();\n renderer2->setInputConnection(streamer->getOutputPort());\n\n SimpleWindow::pointer window = SimpleWindow::New();\n\n window->addRenderer(renderer2);\n window->addRenderer(renderer);\n window->getView()->enableRuntimeMeasurements();\n window->setSize(1920, 1080);\n \/\/window->enableFullscreen();\n window->getView()->set2DPixelSpacing(0.3);\n window->set2DMode();\n window->getView()->setBackgroundColor(Color::Black());\n window->start();\n\n segmentation->getAllRuntimes()->printAll();\n renderer->getAllRuntimes()->printAll();\n window->getView()->getAllRuntimes()->printAll();\n}\n<commit_msg>Small changes in ax heatmap<commit_after>#include <FAST\/Visualization\/DualViewWindow.hpp>\n#include <FAST\/Visualization\/HeatmapRenderer\/HeatmapRenderer.hpp>\n#include <FAST\/Algorithms\/ImageResampler\/ImageResampler.hpp>\n#include \"FAST\/Testing.hpp\"\n#include \"FAST\/Streamers\/ImageFileStreamer.hpp\"\n#include \"FAST\/Visualization\/SimpleWindow.hpp\"\n#include \"FAST\/Visualization\/ImageRenderer\/ImageRenderer.hpp\"\n#include \"FAST\/Visualization\/MeshRenderer\/MeshRenderer.hpp\"\n#include \"FAST\/Algorithms\/NeuralNetwork\/PixelClassifier.hpp\"\n\nusing namespace fast;\n\nint main() {\n Reporter::setGlobalReportMethod(Reporter::COUT);\n ImageFileStreamer::pointer streamer = ImageFileStreamer::New();\n streamer->setFilenameFormats({\n \/\/\"\/home\/smistad\/data\/eyeguide\/axillary_nerve_block\/1\/2016-10-07-135630\/US-2D_#.mhd\",\n \"\/home\/smistad\/data\/eyeguide\/axillary_nerve_block\/16\/2017Feb13_114646\/#.png\",\n \"\/home\/smistad\/data\/eyeguide\/axillary_nerve_block\/17\/2017Feb13_150433\/#.png\",\n \"\/home\/smistad\/data\/eyeguide\/axillary_nerve_block\/17\/2017Feb13_150648\/#.png\",\n \"\/home\/smistad\/data\/eyeguide\/axillary_nerve_block\/17\/2017Feb13_150824\/#.png\",\n \"\/home\/smistad\/data\/eyeguide\/axillary_nerve_block\/5\/2016Dec30_082009\/#.png\",\n \"\/home\/smistad\/data\/eyeguide\/axillary_nerve_block\/5\/2016Dec30_082046\/#.png\",\n \"\/home\/smistad\/data\/eyeguide\/axillary_nerve_block\/5\/2016Dec30_082110\/#.png\",\n });\n streamer->enableLooping();\n streamer->setStartNumber(1);\n streamer->setSleepTime(25);\n streamer->setStreamingMode(STREAMING_MODE_PROCESS_ALL_FRAMES);\n\n PixelClassifier::pointer segmentation = PixelClassifier::New();\n segmentation->setNrOfClasses(6);\n segmentation->load(\"\/home\/smistad\/workspace\/eyeguide_keras\/models\/network_graph.pb\");\n segmentation->setInputSize(256, 256);\n segmentation->setScaleFactor(1.0f\/255.0f);\n segmentation->setOutputParameters({\"Reshape_18\"});\n segmentation->setInputConnection(streamer->getOutputPort());\n segmentation->setHeatmapOutput();\n segmentation->enableRuntimeMeasurements();\n\n HeatmapRenderer::pointer renderer = HeatmapRenderer::New();\n renderer->addInputConnection(segmentation->getOutputPort(1), Color::Red());\n renderer->addInputConnection(segmentation->getOutputPort(2), Color::Yellow());\n renderer->addInputConnection(segmentation->getOutputPort(3), Color::Green());\n renderer->addInputConnection(segmentation->getOutputPort(4), Color::Purple());\n renderer->addInputConnection(segmentation->getOutputPort(5), Color::Cyan());\n renderer->setMaxOpacity(0.2);\n renderer->setMinConfidence(0.4);\n renderer->enableRuntimeMeasurements();\n\n ImageRenderer::pointer renderer2 = ImageRenderer::New();\n renderer2->setInputConnection(streamer->getOutputPort());\n\n SimpleWindow::pointer window = SimpleWindow::New();\n\n window->addRenderer(renderer2);\n window->addRenderer(renderer);\n window->getView()->enableRuntimeMeasurements();\n window->setSize(1920, 1080);\n \/\/window->enableFullscreen();\n window->getView()->set2DPixelSpacing(0.3);\n window->set2DMode();\n window->getView()->setBackgroundColor(Color::Black());\n window->start();\n\n segmentation->getAllRuntimes()->printAll();\n renderer->getAllRuntimes()->printAll();\n window->getView()->getAllRuntimes()->printAll();\n}\n<|endoftext|>"} {"text":"<commit_before>\/** \n *\n * Copyright (c) 2009-2011, Kitty Barnett\n * \n * The source code in this file is provided to you under the terms of the \n * GNU Lesser General Public License, version 2.1, but WITHOUT ANY WARRANTY;\n * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A \n * PARTICULAR PURPOSE. Terms of the LGPL can be found in doc\/LGPL-licence.txt \n * in this distribution, or online at http:\/\/www.gnu.org\/licenses\/lgpl-2.1.txt\n * \n * By copying, modifying or distributing this software, you acknowledge that\n * you have read and understood your obligations described above, and agree to \n * abide by those obligations.\n * \n *\/\n\n#include \"llviewerprecompiledheaders.h\"\n#include \"llavatarnamecache.h\"\n#include \"llscrolllistctrl.h\"\n#include \"llviewerjointattachment.h\"\n#include \"llviewerobjectlist.h\"\n#include \"llvoavatarself.h\"\n\n#include \"rlvfloaters.h\"\n#include \"rlvhelper.h\"\n#include \"rlvhandler.h\"\n#include \"rlvlocks.h\"\n\n\/\/ ============================================================================\n\/\/ Helper functions\n\/\/\n\n\/\/ Checked: 2010-03-11 (RLVa-1.2.0a) | Modified: RLVa-1.2.0g\nstd::string rlvGetItemNameFromObjID(const LLUUID& idObj, bool fIncludeAttachPt = true)\n{\n\tconst LLViewerObject* pObj = gObjectList.findObject(idObj);\n\tconst LLViewerObject* pObjRoot = (pObj) ? pObj->getRootEdit() : NULL;\n\tconst LLViewerInventoryItem* pItem = ((pObjRoot) && (pObjRoot->isAttachment())) ? gInventory.getItem(pObjRoot->getAttachmentItemID()) : NULL;\n\n\tstd::string strItemName = (pItem) ? pItem->getName() : idObj.asString();\n\tif ( (!fIncludeAttachPt) || (!pObj) || (!pObj->isAttachment()) || (!isAgentAvatarValid()) )\n\t\treturn strItemName;\n\n\tconst LLViewerJointAttachment* pAttachPt = \n\t\tget_if_there(gAgentAvatarp->mAttachmentPoints, RlvAttachPtLookup::getAttachPointIndex(pObjRoot), (LLViewerJointAttachment*)NULL);\n\tstd::string strAttachPtName = (pAttachPt) ? pAttachPt->getName() : std::string(\"Unknown\");\n\treturn llformat(\"%s (%s, %s)\", strItemName.c_str(), strAttachPtName.c_str(), (pObj == pObjRoot) ? \"root\" : \"child\");\n}\n\n\/\/ Checked: 2011-05-23 (RLVa-1.3.0c) | Added: RLVa-1.3.0c\nbool rlvGetShowException(ERlvBehaviour eBhvr)\n{\n\tswitch (eBhvr)\n\t{\n\t\tcase RLV_BHVR_RECVCHAT:\n\t\tcase RLV_BHVR_RECVEMOTE:\n\t\tcase RLV_BHVR_SENDIM:\n\t\tcase RLV_BHVR_RECVIM:\n\t\tcase RLV_BHVR_STARTIM:\n\t\tcase RLV_BHVR_TPLURE:\n\t\tcase RLV_BHVR_ACCEPTTP:\n\t\t\treturn true;\n\t\tdefault:\n\t\t\treturn false;\n\t}\n}\n\n\/\/ ============================================================================\n\/\/ RlvFloaterBehaviours member functions\n\/\/\n\n\/\/ Checked: 2010-04-18 (RLVa-1.3.1c) | Modified: RLVa-1.2.0e\nvoid RlvFloaterBehaviours::onOpen(const LLSD& sdKey)\n{\n\tm_ConnRlvCommand = gRlvHandler.setCommandCallback(boost::bind(&RlvFloaterBehaviours::onCommand, this, _1, _2));\n\n\trefreshAll();\n}\n\n\/\/ Checked: 2010-04-18 (RLVa-1.3.1c) | Modified: RLVa-1.2.0e\nvoid RlvFloaterBehaviours::onClose(bool fQuitting)\n{\n\tm_ConnRlvCommand.disconnect();\n}\n\n\/\/ Checked: 2010-04-18 (RLVa-1.3.1c) | Modified: RLVa-1.2.0e\nvoid RlvFloaterBehaviours::onAvatarNameLookup(const LLUUID& idAgent, const LLAvatarName& avName)\n{\n\tuuid_vec_t::iterator itLookup = std::find(m_PendingLookup.begin(), m_PendingLookup.end(), idAgent);\n\tif (itLookup != m_PendingLookup.end())\n\t\tm_PendingLookup.erase(itLookup);\n\tif (getVisible())\n\t\trefreshAll();\n}\n\n\/\/ Checked: 2011-05-23 (RLVa-1.3.1c) | Modified: RLVa-1.3.1c\nvoid RlvFloaterBehaviours::onCommand(const RlvCommand& rlvCmd, ERlvCmdRet eRet)\n{\n\tif ( (RLV_TYPE_ADD == rlvCmd.getParamType()) || (RLV_TYPE_REMOVE == rlvCmd.getParamType()) )\n\t\trefreshAll();\n}\n\n\/\/ Checked: 2011-05-23 (RLVa-1.3.1c) | Modified: RLVa-1.3.1c\nvoid RlvFloaterBehaviours::refreshAll()\n{\n\tLLCtrlListInterface* pBhvrList = childGetListInterface(\"behaviour_list\");\n\tLLCtrlListInterface* pExceptList = childGetListInterface(\"exception_list\");\n\tif ( (!pBhvrList) || (!pExceptList) )\n\t\treturn;\n\tpBhvrList->operateOnAll(LLCtrlListInterface::OP_DELETE);\n\tpExceptList->operateOnAll(LLCtrlListInterface::OP_DELETE);\n\n\tif (!isAgentAvatarValid())\n\t\treturn;\n\n\t\/\/\n\t\/\/ Set-up a row we can just reuse\n\t\/\/\n\tLLSD sdBhrRow; LLSD& sdBhvrColumns = sdBhrRow[\"columns\"];\n\tsdBhvrColumns[0] = LLSD().with(\"column\", \"behaviour\").with(\"type\", \"text\");\n\tsdBhvrColumns[1] = LLSD().with(\"column\", \"issuer\").with(\"type\", \"text\");\n\n\tLLSD sdExceptRow; LLSD& sdExceptColumns = sdExceptRow[\"columns\"];\n\tsdExceptColumns[0] = LLSD().with(\"column\", \"behaviour\").with(\"type\", \"text\");\n\tsdExceptColumns[1] = LLSD().with(\"column\", \"option\").with(\"type\", \"text\");\n\tsdExceptColumns[2] = LLSD().with(\"column\", \"issuer\").with(\"type\", \"text\");\n\n\t\/\/\n\t\/\/ List behaviours\n\t\/\/\n\tconst RlvHandler::rlv_object_map_t* pObjects = gRlvHandler.getObjectMap();\n\tfor (RlvHandler::rlv_object_map_t::const_iterator itObj = pObjects->begin(), endObj = pObjects->end(); itObj != endObj; ++itObj)\n\t{\n\t\tconst std::string strIssuer = rlvGetItemNameFromObjID(itObj->first);\n\n\t\tconst rlv_command_list_t* pCommands = itObj->second.getCommandList();\n\t\tfor (rlv_command_list_t::const_iterator itCmd = pCommands->begin(), endCmd = pCommands->end(); itCmd != endCmd; ++itCmd)\n\t\t{\n\t\t\tLLUUID idOption;\n\t\t\tif ( (itCmd->hasOption()) && (idOption.set(itCmd->getOption(), FALSE)) && (rlvGetShowException(itCmd->getBehaviourType())) )\n\t\t\t{\n\t\t\t\tstd::string strOption; LLAvatarName avName;\n\t\t\t\tif (LLAvatarNameCache::get(idOption, &avName))\n\t\t\t\t{\n\t\t\t\t\tstrOption = (!avName.mUsername.empty()) ? avName.mUsername : avName.mDisplayName;\n\t\t\t\t}\n\t\t\t\telse if (!gCacheName->getGroupName(idOption, strOption))\n\t\t\t\t{\n\t\t\t\t\tif (m_PendingLookup.end() == std::find(m_PendingLookup.begin(), m_PendingLookup.end(), idOption))\n\t\t\t\t\t{\n\t\t\t\t\t\tLLAvatarNameCache::get(idOption, boost::bind(&RlvFloaterBehaviours::onAvatarNameLookup, this, _1, _2));\n\t\t\t\t\t\tm_PendingLookup.push_back(idOption);\n\t\t\t\t\t}\n\t\t\t\t\tstrOption = itCmd->getOption();\n\t\t\t\t}\n\n\t\t\t\t\/\/ List under the \"Exception\" tab\n\t\t\t\tsdExceptColumns[0][\"value\"] = itCmd->getBehaviour();\n\t\t\t\tsdExceptColumns[1][\"value\"] = strOption;\n\t\t\t\tsdExceptColumns[2][\"value\"] = strIssuer;\n\t\t\t\tpExceptList->addElement(sdExceptRow, ADD_BOTTOM);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\t\/\/ List under the \"Restrictions\" tab\n\t\t\t\tsdBhvrColumns[0][\"value\"] = itCmd->asString();\n\t\t\t\tsdBhvrColumns[1][\"value\"] = strIssuer;\n\t\t\t\tpBhvrList->addElement(sdBhrRow, ADD_BOTTOM);\n\t\t\t}\n\t\t}\n\t}\n}\n\n\/\/ ============================================================================\n\/\/ RlvFloaterLocks member functions\n\/\/\n\n\/\/ Checked: 2010-03-11 (RLVa-1.2.0a) | Added: RLVa-1.2.0a\nvoid RlvFloaterLocks::onOpen(const LLSD& sdKey)\n{\n\tm_ConnRlvCommand = gRlvHandler.setCommandCallback(boost::bind(&RlvFloaterLocks::onRlvCommand, this, _1, _2));\n\n\trefreshAll();\n}\n\n\/\/ Checked: 2010-03-11 (RLVa-1.2.0a) | Added: RLVa-1.2.0a\nvoid RlvFloaterLocks::onClose(bool fQuitting)\n{\n\tm_ConnRlvCommand.disconnect();\n}\n\n\/\/ Checked: 2010-03-11 (RLVa-1.2.0a) | Added: RLVa-1.2.0a\nvoid RlvFloaterLocks::onRlvCommand(const RlvCommand& rlvCmd, ERlvCmdRet eRet)\n{\n\t\/\/ Refresh on any successful @XXX=y|n command where XXX is any of the attachment or wearable locking behaviours\n\tif ( (RLV_RET_SUCCESS == eRet) && ((RLV_TYPE_ADD == rlvCmd.getParamType()) || (RLV_TYPE_REMOVE == rlvCmd.getParamType())) )\n\t{\n\t\tswitch (rlvCmd.getBehaviourType())\n\t\t{\n\t\t\tcase RLV_BHVR_DETACH:\n\t\t\tcase RLV_BHVR_ADDATTACH:\n\t\t\tcase RLV_BHVR_REMATTACH:\n\t\t\tcase RLV_BHVR_ADDOUTFIT:\n\t\t\tcase RLV_BHVR_REMOUTFIT:\n\t\t\t\trefreshAll();\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tbreak;\n\t\t}\n\t}\n}\n\n\/\/ Checked: 2010-03-18 (RLVa-1.2.0a) | Added: RLVa-1.2.0a\nvoid RlvFloaterLocks::refreshAll()\n{\n\tLLCtrlListInterface* pLockList = childGetListInterface(\"lock_list\");\n\tif (!pLockList)\n\t\treturn;\n\tpLockList->operateOnAll(LLCtrlListInterface::OP_DELETE);\n\n\tif (!isAgentAvatarValid())\n\t\treturn;\n\n\t\/\/\n\t\/\/ Set-up a row we can just reuse\n\t\/\/\n\tLLSD sdRow;\n\tLLSD& sdColumns = sdRow[\"columns\"];\n\tsdColumns[0][\"column\"] = \"lock_type\"; sdColumns[0][\"type\"] = \"text\";\n\tsdColumns[1][\"column\"] = \"lock_addrem\"; sdColumns[1][\"type\"] = \"text\";\n\tsdColumns[2][\"column\"] = \"lock_target\"; sdColumns[2][\"type\"] = \"text\";\n\tsdColumns[3][\"column\"] = \"lock_origin\"; sdColumns[3][\"type\"] = \"text\";\n\n\t\/\/\n\t\/\/ List attachment locks\n\t\/\/\n\tsdColumns[0][\"value\"] = \"Attachment\";\n\tsdColumns[1][\"value\"] = \"rem\";\n\n\tconst RlvAttachmentLocks::rlv_attachobjlock_map_t& attachObjRem = gRlvAttachmentLocks.getAttachObjLocks();\n\tfor (RlvAttachmentLocks::rlv_attachobjlock_map_t::const_iterator itAttachObj = attachObjRem.begin(); \n\t\t\titAttachObj != attachObjRem.end(); ++itAttachObj)\n\t{\n\t\tsdColumns[2][\"value\"] = rlvGetItemNameFromObjID(itAttachObj->first);\n\t\tsdColumns[3][\"value\"] = rlvGetItemNameFromObjID(itAttachObj->second);\n\n\t\tpLockList->addElement(sdRow, ADD_BOTTOM);\n\t}\n\n\t\/\/\n\t\/\/ List attachment point locks\n\t\/\/\n\tsdColumns[0][\"value\"] = \"Attachment Point\";\n\n\tsdColumns[1][\"value\"] = \"add\";\n\tconst RlvAttachmentLocks::rlv_attachptlock_map_t& attachPtAdd = gRlvAttachmentLocks.getAttachPtLocks(RLV_LOCK_ADD);\n\tfor (RlvAttachmentLocks::rlv_attachptlock_map_t::const_iterator itAttachPt = attachPtAdd.begin(); \n\t\t\titAttachPt != attachPtAdd.end(); ++itAttachPt)\n\t{\n\t\tconst LLViewerJointAttachment* pAttachPt = \n\t\t\tget_if_there(gAgentAvatarp->mAttachmentPoints, itAttachPt->first, (LLViewerJointAttachment*)NULL);\n\t\tsdColumns[2][\"value\"] = pAttachPt->getName();\n\t\tsdColumns[3][\"value\"] = rlvGetItemNameFromObjID(itAttachPt->second);\n\n\t\tpLockList->addElement(sdRow, ADD_BOTTOM);\n\t}\n\n\tsdColumns[1][\"value\"] = \"rem\";\n\tconst RlvAttachmentLocks::rlv_attachptlock_map_t& attachPtRem = gRlvAttachmentLocks.getAttachPtLocks(RLV_LOCK_REMOVE);\n\tfor (RlvAttachmentLocks::rlv_attachptlock_map_t::const_iterator itAttachPt = attachPtRem.begin(); \n\t\t\titAttachPt != attachPtRem.end(); ++itAttachPt)\n\t{\n\t\tconst LLViewerJointAttachment* pAttachPt = \n\t\t\tget_if_there(gAgentAvatarp->mAttachmentPoints, itAttachPt->first, (LLViewerJointAttachment*)NULL);\n\t\tsdColumns[2][\"value\"] = pAttachPt->getName();\n\t\tsdColumns[3][\"value\"] = rlvGetItemNameFromObjID(itAttachPt->second);\n\n\t\tpLockList->addElement(sdRow, ADD_BOTTOM);\n\t}\n\n\t\/\/\n\t\/\/ List wearable type locks\n\t\/\/\n\tsdColumns[0][\"value\"] = \"Wearable Type\";\n\n\tsdColumns[1][\"value\"] = \"add\";\n\tconst RlvWearableLocks::rlv_wearabletypelock_map_t& wearableTypeAdd = gRlvWearableLocks.getWearableTypeLocks(RLV_LOCK_ADD);\n\tfor (RlvWearableLocks::rlv_wearabletypelock_map_t::const_iterator itWearableType = wearableTypeAdd.begin(); \n\t\t\titWearableType != wearableTypeAdd.end(); ++itWearableType)\n\t{\n\t\tsdColumns[2][\"value\"] = LLWearableType::getTypeLabel(itWearableType->first);\n\t\tsdColumns[3][\"value\"] = rlvGetItemNameFromObjID(itWearableType->second);\n\n\t\tpLockList->addElement(sdRow, ADD_BOTTOM);\n\t}\n\n\tsdColumns[1][\"value\"] = \"rem\";\n\tconst RlvWearableLocks::rlv_wearabletypelock_map_t& wearableTypeRem = gRlvWearableLocks.getWearableTypeLocks(RLV_LOCK_REMOVE);\n\tfor (RlvWearableLocks::rlv_wearabletypelock_map_t::const_iterator itWearableType = wearableTypeRem.begin(); \n\t\t\titWearableType != wearableTypeRem.end(); ++itWearableType)\n\t{\n\t\tsdColumns[2][\"value\"] = LLWearableType::getTypeName(itWearableType->first);\n\t\tsdColumns[3][\"value\"] = rlvGetItemNameFromObjID(itWearableType->second);\n\n\t\tpLockList->addElement(sdRow, ADD_BOTTOM);\n\t}\n}\n\n\/\/ ============================================================================\n<commit_msg>- changed : split the \"restrictions floater\" into one tan for restrictions and one tab for exceptions<commit_after>\/** \n *\n * Copyright (c) 2009-2011, Kitty Barnett\n * \n * The source code in this file is provided to you under the terms of the \n * GNU Lesser General Public License, version 2.1, but WITHOUT ANY WARRANTY;\n * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A \n * PARTICULAR PURPOSE. Terms of the LGPL can be found in doc\/LGPL-licence.txt \n * in this distribution, or online at http:\/\/www.gnu.org\/licenses\/lgpl-2.1.txt\n * \n * By copying, modifying or distributing this software, you acknowledge that\n * you have read and understood your obligations described above, and agree to \n * abide by those obligations.\n * \n *\/\n\n#include \"llviewerprecompiledheaders.h\"\n#include \"llavatarnamecache.h\"\n#include \"llscrolllistctrl.h\"\n#include \"llviewerjointattachment.h\"\n#include \"llviewerobjectlist.h\"\n#include \"llvoavatarself.h\"\n\n#include \"rlvfloaters.h\"\n#include \"rlvhelper.h\"\n#include \"rlvhandler.h\"\n#include \"rlvlocks.h\"\n\n\/\/ ============================================================================\n\/\/ Helper functions\n\/\/\n\n\/\/ Checked: 2010-03-11 (RLVa-1.2.0a) | Modified: RLVa-1.2.0g\nstd::string rlvGetItemNameFromObjID(const LLUUID& idObj, bool fIncludeAttachPt = true)\n{\n\tconst LLViewerObject* pObj = gObjectList.findObject(idObj);\n\tconst LLViewerObject* pObjRoot = (pObj) ? pObj->getRootEdit() : NULL;\n\tconst LLViewerInventoryItem* pItem = ((pObjRoot) && (pObjRoot->isAttachment())) ? gInventory.getItem(pObjRoot->getAttachmentItemID()) : NULL;\n\n\tstd::string strItemName = (pItem) ? pItem->getName() : idObj.asString();\n\tif ( (!fIncludeAttachPt) || (!pObj) || (!pObj->isAttachment()) || (!isAgentAvatarValid()) )\n\t\treturn strItemName;\n\n\tconst LLViewerJointAttachment* pAttachPt = \n\t\tget_if_there(gAgentAvatarp->mAttachmentPoints, RlvAttachPtLookup::getAttachPointIndex(pObjRoot), (LLViewerJointAttachment*)NULL);\n\tstd::string strAttachPtName = (pAttachPt) ? pAttachPt->getName() : std::string(\"Unknown\");\n\treturn llformat(\"%s (%s, %s)\", strItemName.c_str(), strAttachPtName.c_str(), (pObj == pObjRoot) ? \"root\" : \"child\");\n}\n\n\/\/ Checked: 2011-05-23 (RLVa-1.3.0c) | Added: RLVa-1.3.0c\nbool rlvGetShowException(ERlvBehaviour eBhvr)\n{\n\tswitch (eBhvr)\n\t{\n\t\tcase RLV_BHVR_RECVCHAT:\n\t\tcase RLV_BHVR_RECVEMOTE:\n\t\tcase RLV_BHVR_SENDIM:\n\t\tcase RLV_BHVR_RECVIM:\n\t\tcase RLV_BHVR_STARTIM:\n\t\tcase RLV_BHVR_TPLURE:\n\t\tcase RLV_BHVR_ACCEPTTP:\n\t\t\treturn true;\n\t\tdefault:\n\t\t\treturn false;\n\t}\n}\n\n\/\/ ============================================================================\n\/\/ RlvFloaterBehaviours member functions\n\/\/\n\n\/\/ Checked: 2010-04-18 (RLVa-1.3.1c) | Modified: RLVa-1.2.0e\nvoid RlvFloaterBehaviours::onOpen(const LLSD& sdKey)\n{\n\tm_ConnRlvCommand = gRlvHandler.setCommandCallback(boost::bind(&RlvFloaterBehaviours::onCommand, this, _1, _2));\n\n\trefreshAll();\n}\n\n\/\/ Checked: 2010-04-18 (RLVa-1.3.1c) | Modified: RLVa-1.2.0e\nvoid RlvFloaterBehaviours::onClose(bool fQuitting)\n{\n\tm_ConnRlvCommand.disconnect();\n}\n\n\/\/ Checked: 2010-04-18 (RLVa-1.3.1c) | Modified: RLVa-1.2.0e\nvoid RlvFloaterBehaviours::onAvatarNameLookup(const LLUUID& idAgent, const LLAvatarName& avName)\n{\n\tuuid_vec_t::iterator itLookup = std::find(m_PendingLookup.begin(), m_PendingLookup.end(), idAgent);\n\tif (itLookup != m_PendingLookup.end())\n\t\tm_PendingLookup.erase(itLookup);\n\tif (getVisible())\n\t\trefreshAll();\n}\n\n\/\/ Checked: 2011-05-23 (RLVa-1.3.1c) | Modified: RLVa-1.3.1c\nvoid RlvFloaterBehaviours::onCommand(const RlvCommand& rlvCmd, ERlvCmdRet eRet)\n{\n\tif ( (RLV_TYPE_ADD == rlvCmd.getParamType()) || (RLV_TYPE_REMOVE == rlvCmd.getParamType()) )\n\t\trefreshAll();\n}\n\n\/\/ Checked: 2011-05-23 (RLVa-1.3.1c) | Modified: RLVa-1.3.1c\nvoid RlvFloaterBehaviours::refreshAll()\n{\n\tLLCtrlListInterface* pBhvrList = childGetListInterface(\"behaviour_list\");\n\tLLCtrlListInterface* pExceptList = childGetListInterface(\"exception_list\");\n\tif ( (!pBhvrList) || (!pExceptList) )\n\t\treturn;\n\tpBhvrList->operateOnAll(LLCtrlListInterface::OP_DELETE);\n\tpExceptList->operateOnAll(LLCtrlListInterface::OP_DELETE);\n\n\tif (!isAgentAvatarValid())\n\t\treturn;\n\n\t\/\/\n\t\/\/ Set-up a row we can just reuse\n\t\/\/\n\tLLSD sdBhrRow; LLSD& sdBhvrColumns = sdBhrRow[\"columns\"];\n\tsdBhvrColumns[0] = LLSD().with(\"column\", \"behaviour\").with(\"type\", \"text\");\n\tsdBhvrColumns[1] = LLSD().with(\"column\", \"issuer\").with(\"type\", \"text\");\n\n\tLLSD sdExceptRow; LLSD& sdExceptColumns = sdExceptRow[\"columns\"];\n\tsdExceptColumns[0] = LLSD().with(\"column\", \"behaviour\").with(\"type\", \"text\");\n\tsdExceptColumns[1] = LLSD().with(\"column\", \"option\").with(\"type\", \"text\");\n\tsdExceptColumns[2] = LLSD().with(\"column\", \"issuer\").with(\"type\", \"text\");\n\n\t\/\/\n\t\/\/ List behaviours\n\t\/\/\n\tconst RlvHandler::rlv_object_map_t* pObjects = gRlvHandler.getObjectMap();\n\tfor (RlvHandler::rlv_object_map_t::const_iterator itObj = pObjects->begin(), endObj = pObjects->end(); itObj != endObj; ++itObj)\n\t{\n\t\tconst std::string strIssuer = rlvGetItemNameFromObjID(itObj->first);\n\n\t\tconst rlv_command_list_t* pCommands = itObj->second.getCommandList();\n\t\tfor (rlv_command_list_t::const_iterator itCmd = pCommands->begin(), endCmd = pCommands->end(); itCmd != endCmd; ++itCmd)\n\t\t{\n\t\t\tstd::string strOption; LLUUID idOption;\n\t\t\tif ( (itCmd->hasOption()) && (idOption.set(itCmd->getOption(), FALSE)) )\n\t\t\t{\n\t\t\t\tLLAvatarName avName;\n\t\t\t\tif (gObjectList.findObject(idOption))\n\t\t\t\t{\n\t\t\t\t\tstrOption = rlvGetItemNameFromObjID(idOption, false);\n\t\t\t\t}\n\t\t\t\telse if (LLAvatarNameCache::get(idOption, &avName))\n\t\t\t\t{\n\t\t\t\t\tstrOption = (!avName.mUsername.empty()) ? avName.mUsername : avName.mDisplayName;\n\t\t\t\t}\n\t\t\t\telse if (!gCacheName->getGroupName(idOption, strOption))\n\t\t\t\t{\n\t\t\t\t\tif (m_PendingLookup.end() == std::find(m_PendingLookup.begin(), m_PendingLookup.end(), idOption))\n\t\t\t\t\t{\n\t\t\t\t\t\tLLAvatarNameCache::get(idOption, boost::bind(&RlvFloaterBehaviours::onAvatarNameLookup, this, _1, _2));\n\t\t\t\t\t\tm_PendingLookup.push_back(idOption);\n\t\t\t\t\t}\n\t\t\t\t\tstrOption = itCmd->getOption();\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif ( (itCmd->hasOption()) && (rlvGetShowException(itCmd->getBehaviourType())) )\n\t\t\t{\n\t\t\t\t\/\/ List under the \"Exception\" tab\n\t\t\t\tsdExceptColumns[0][\"value\"] = itCmd->getBehaviour();\n\t\t\t\tsdExceptColumns[1][\"value\"] = strOption;\n\t\t\t\tsdExceptColumns[2][\"value\"] = strIssuer;\n\t\t\t\tpExceptList->addElement(sdExceptRow, ADD_BOTTOM);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\t\/\/ List under the \"Restrictions\" tab\n\t\t\t\tsdBhvrColumns[0][\"value\"] = itCmd->asString();\n\t\t\t\tsdBhvrColumns[1][\"value\"] = strIssuer;\n\t\t\t\tpBhvrList->addElement(sdBhrRow, ADD_BOTTOM);\n\t\t\t}\n\t\t}\n\t}\n}\n\n\/\/ ============================================================================\n\/\/ RlvFloaterLocks member functions\n\/\/\n\n\/\/ Checked: 2010-03-11 (RLVa-1.2.0a) | Added: RLVa-1.2.0a\nvoid RlvFloaterLocks::onOpen(const LLSD& sdKey)\n{\n\tm_ConnRlvCommand = gRlvHandler.setCommandCallback(boost::bind(&RlvFloaterLocks::onRlvCommand, this, _1, _2));\n\n\trefreshAll();\n}\n\n\/\/ Checked: 2010-03-11 (RLVa-1.2.0a) | Added: RLVa-1.2.0a\nvoid RlvFloaterLocks::onClose(bool fQuitting)\n{\n\tm_ConnRlvCommand.disconnect();\n}\n\n\/\/ Checked: 2010-03-11 (RLVa-1.2.0a) | Added: RLVa-1.2.0a\nvoid RlvFloaterLocks::onRlvCommand(const RlvCommand& rlvCmd, ERlvCmdRet eRet)\n{\n\t\/\/ Refresh on any successful @XXX=y|n command where XXX is any of the attachment or wearable locking behaviours\n\tif ( (RLV_RET_SUCCESS == eRet) && ((RLV_TYPE_ADD == rlvCmd.getParamType()) || (RLV_TYPE_REMOVE == rlvCmd.getParamType())) )\n\t{\n\t\tswitch (rlvCmd.getBehaviourType())\n\t\t{\n\t\t\tcase RLV_BHVR_DETACH:\n\t\t\tcase RLV_BHVR_ADDATTACH:\n\t\t\tcase RLV_BHVR_REMATTACH:\n\t\t\tcase RLV_BHVR_ADDOUTFIT:\n\t\t\tcase RLV_BHVR_REMOUTFIT:\n\t\t\t\trefreshAll();\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tbreak;\n\t\t}\n\t}\n}\n\n\/\/ Checked: 2010-03-18 (RLVa-1.2.0a) | Added: RLVa-1.2.0a\nvoid RlvFloaterLocks::refreshAll()\n{\n\tLLCtrlListInterface* pLockList = childGetListInterface(\"lock_list\");\n\tif (!pLockList)\n\t\treturn;\n\tpLockList->operateOnAll(LLCtrlListInterface::OP_DELETE);\n\n\tif (!isAgentAvatarValid())\n\t\treturn;\n\n\t\/\/\n\t\/\/ Set-up a row we can just reuse\n\t\/\/\n\tLLSD sdRow;\n\tLLSD& sdColumns = sdRow[\"columns\"];\n\tsdColumns[0][\"column\"] = \"lock_type\"; sdColumns[0][\"type\"] = \"text\";\n\tsdColumns[1][\"column\"] = \"lock_addrem\"; sdColumns[1][\"type\"] = \"text\";\n\tsdColumns[2][\"column\"] = \"lock_target\"; sdColumns[2][\"type\"] = \"text\";\n\tsdColumns[3][\"column\"] = \"lock_origin\"; sdColumns[3][\"type\"] = \"text\";\n\n\t\/\/\n\t\/\/ List attachment locks\n\t\/\/\n\tsdColumns[0][\"value\"] = \"Attachment\";\n\tsdColumns[1][\"value\"] = \"rem\";\n\n\tconst RlvAttachmentLocks::rlv_attachobjlock_map_t& attachObjRem = gRlvAttachmentLocks.getAttachObjLocks();\n\tfor (RlvAttachmentLocks::rlv_attachobjlock_map_t::const_iterator itAttachObj = attachObjRem.begin(); \n\t\t\titAttachObj != attachObjRem.end(); ++itAttachObj)\n\t{\n\t\tsdColumns[2][\"value\"] = rlvGetItemNameFromObjID(itAttachObj->first);\n\t\tsdColumns[3][\"value\"] = rlvGetItemNameFromObjID(itAttachObj->second);\n\n\t\tpLockList->addElement(sdRow, ADD_BOTTOM);\n\t}\n\n\t\/\/\n\t\/\/ List attachment point locks\n\t\/\/\n\tsdColumns[0][\"value\"] = \"Attachment Point\";\n\n\tsdColumns[1][\"value\"] = \"add\";\n\tconst RlvAttachmentLocks::rlv_attachptlock_map_t& attachPtAdd = gRlvAttachmentLocks.getAttachPtLocks(RLV_LOCK_ADD);\n\tfor (RlvAttachmentLocks::rlv_attachptlock_map_t::const_iterator itAttachPt = attachPtAdd.begin(); \n\t\t\titAttachPt != attachPtAdd.end(); ++itAttachPt)\n\t{\n\t\tconst LLViewerJointAttachment* pAttachPt = \n\t\t\tget_if_there(gAgentAvatarp->mAttachmentPoints, itAttachPt->first, (LLViewerJointAttachment*)NULL);\n\t\tsdColumns[2][\"value\"] = pAttachPt->getName();\n\t\tsdColumns[3][\"value\"] = rlvGetItemNameFromObjID(itAttachPt->second);\n\n\t\tpLockList->addElement(sdRow, ADD_BOTTOM);\n\t}\n\n\tsdColumns[1][\"value\"] = \"rem\";\n\tconst RlvAttachmentLocks::rlv_attachptlock_map_t& attachPtRem = gRlvAttachmentLocks.getAttachPtLocks(RLV_LOCK_REMOVE);\n\tfor (RlvAttachmentLocks::rlv_attachptlock_map_t::const_iterator itAttachPt = attachPtRem.begin(); \n\t\t\titAttachPt != attachPtRem.end(); ++itAttachPt)\n\t{\n\t\tconst LLViewerJointAttachment* pAttachPt = \n\t\t\tget_if_there(gAgentAvatarp->mAttachmentPoints, itAttachPt->first, (LLViewerJointAttachment*)NULL);\n\t\tsdColumns[2][\"value\"] = pAttachPt->getName();\n\t\tsdColumns[3][\"value\"] = rlvGetItemNameFromObjID(itAttachPt->second);\n\n\t\tpLockList->addElement(sdRow, ADD_BOTTOM);\n\t}\n\n\t\/\/\n\t\/\/ List wearable type locks\n\t\/\/\n\tsdColumns[0][\"value\"] = \"Wearable Type\";\n\n\tsdColumns[1][\"value\"] = \"add\";\n\tconst RlvWearableLocks::rlv_wearabletypelock_map_t& wearableTypeAdd = gRlvWearableLocks.getWearableTypeLocks(RLV_LOCK_ADD);\n\tfor (RlvWearableLocks::rlv_wearabletypelock_map_t::const_iterator itWearableType = wearableTypeAdd.begin(); \n\t\t\titWearableType != wearableTypeAdd.end(); ++itWearableType)\n\t{\n\t\tsdColumns[2][\"value\"] = LLWearableType::getTypeLabel(itWearableType->first);\n\t\tsdColumns[3][\"value\"] = rlvGetItemNameFromObjID(itWearableType->second);\n\n\t\tpLockList->addElement(sdRow, ADD_BOTTOM);\n\t}\n\n\tsdColumns[1][\"value\"] = \"rem\";\n\tconst RlvWearableLocks::rlv_wearabletypelock_map_t& wearableTypeRem = gRlvWearableLocks.getWearableTypeLocks(RLV_LOCK_REMOVE);\n\tfor (RlvWearableLocks::rlv_wearabletypelock_map_t::const_iterator itWearableType = wearableTypeRem.begin(); \n\t\t\titWearableType != wearableTypeRem.end(); ++itWearableType)\n\t{\n\t\tsdColumns[2][\"value\"] = LLWearableType::getTypeName(itWearableType->first);\n\t\tsdColumns[3][\"value\"] = rlvGetItemNameFromObjID(itWearableType->second);\n\n\t\tpLockList->addElement(sdRow, ADD_BOTTOM);\n\t}\n}\n\n\/\/ ============================================================================\n<|endoftext|>"} {"text":"<commit_before>\/\/ https:\/\/leetcode.com\/problems\/word-break\/\n\n\/*\n\n Given a string s and a dictionary of words dict, determine if s can be segmented into a \n space-separated sequence of one or more dictionary words.\n\n For example, given\n s = \"leetcode\",\n dict = [\"leet\", \"code\"].\n\n Return true because \"leetcode\" can be segmented as \"leet code\".\n*\/\n\n#include <string>\n#include <vector>\n#include <utility>\n#include <unordered_set>\n#include <unordered_map>\n\nusing std::pair;\nusing std::string;\nusing std::vector;\nusing std::unordered_set;\n\nclass Solution {\npublic:\n bool wordBreak(string s, unordered_set<string>& wordDict) {\n return backTrack(s, 0, 0, wordDict, s.length());\n }\nprivate:\n vector<pair<unsigned, unsigned>> m_words;\n\n bool backTrack(string s, unsigned offset, unsigned pos, unordered_set<string>& d, size_t len) {\n if (pos == len) {\n if (m_words.size() > offset) {\n auto const& p = m_words.back(); m_words.pop_back();\n return backTrack(s, p.first, p.second + 1, d, len);\n } else {\n return false;\n }\n }\n\n string sub = s.substr(offset, pos + 1 - offset);\n if (d.find(sub) != d.end()) {\n if (pos == len - 1) return true;\n else {\n m_words.push_back(std::make_pair(offset, pos));\n return backTrack(s, pos + 1, pos + 1, d, len);\n }\n }\n\n return backTrack(s, offset, pos + 1, d, len);\n }\n};\n<commit_msg>:new: finish word break<commit_after>\/\/ https:\/\/leetcode.com\/problems\/word-break\/\n\n\/*\n\n Given a string s and a dictionary of words dict, determine if s can be segmented into a \n space-separated sequence of one or more dictionary words.\n\n For example, given\n s = \"leetcode\",\n dict = [\"leet\", \"code\"].\n\n Return true because \"leetcode\" can be segmented as \"leet code\".\n*\/\n\n#include <string>\n#include <vector>\n#include <unordered_set>\n\nusing std::string;\nusing std::vector;\nusing std::unordered_set;\n\n\/\/ leet\n\/\/ false false false true\n\nclass Solution {\npublic:\n bool wordBreak(string s, unordered_set<string>& wordDict) {\n vector<bool> dp(s.length() + 1, false);\n dp.back() = true;\n\n \/\/ Start at the second to last letter of the word\n for (int offset = s.length() - 1; offset >= 0; offset--) {\n \n \/\/ Start at the offset, and increase substring length\n for (size_t pos = offset, len = s.length(); pos < len; pos++) {\n \n \/\/ When you reach a previous word boundary, check if current substring is also a word\n if (dp[pos + 1] == true && wordDict.find(s.substr(offset, pos + 1 - offset)) != wordDict.end()) {\n \n \/\/ Set position of first letter of word to true\n dp[offset] = true;\n break;\n }\n }\n }\n\n \/\/ If the first entry is true\n \/\/ It means that there was a word before it (and a word before that word and so one)\n return dp[0];\n }\n};\n<|endoftext|>"} {"text":"<commit_before>#include \"main.h\"\n\n\/* example constructor, sets some options *\/\nRail::Rail()\n{\n \/\/ declare options, keep options as uppercase\n vector<string> temp;\n temp.push_back(\"INPUTFILE\");\n temp.push_back(\"OUTPUTFILE\");\n temp.push_back(\"NUMRAILS\");\n temp.push_back(\"DECRYPT\");\n set_opts(temp);\n\n \/\/ set default values, option must exist or error will printed\n set_opt_value(\"OUTPUTFILE\", \"encr_rail.txt\");\n set_opt_value(\"DECRYPT\", \"0\");\n\tset_opt_value(\"NUMRAILS\", \"5\");\n\t\/\/ delete before merge\n\tset_opt_value(\"INPUTFILE\", \"makefile\");\n}\n\n\/* I am overriding the default module function\n * for displaying the description text\n *\/\nvoid Rail::disp_desc()\n{\n cout << \"Module: ciphers\/rail\\n\\tEncrypts (or decrypts, if number of rails known) a text file with the rail fence cipher.\\n\\tPlease define the following required options:\\n\\t\\tINPUTFILE\\tinput filename\" << endl;\n cout << endl;\n}\n\n\/* overrides the virtual function from Module\n * this is where the real meaty stuff happens\n *\/\nint Rail::run()\n{\n\tifstream in;\n\tofstream out;\n\tstring ibuff, obuff;\n\tbool shouldDecrypt = false;\n\n\t\/\/ perform error checking on options first\n\tif (options[\"INPUTFILE\"].empty()) {\n\t\tcout << \"[-] Please specify an input file\" << endl;\n\t\treturn 1;\n\t}\n\n\tif (options[\"OUTPUTFILE\"].empty()) {\n\t\tcout << \"[-] Please specify an output file\" << endl;\n\t\treturn 2;\n\t}\n\n\tif (options[\"NUMRAILS\"].empty()) {\n\t\tcout << \"[-] Please specify the number of rails\" << endl;\n\t\treturn 3;\n\t}\n\n\tif (options[\"DECRYPT\"] == \"1\"){\n\t\tshouldDecrypt = true;\n\t}\n\n cout << \"[*] Opening input file: \" << options[\"INPUTFILE\"] << endl;\n in.open(options[\"INPUTFILE\"]);\n\n if (!in.good()) {\n cout << \"[-] Input file error\" << endl;\n return 5;\n }\n\n cout << \"[*] Opening output file: \" << options[\"OUTPUTFILE\"] << endl;\n out.open(options[\"OUTPUTFILE\"]);\n\n\tif (!shouldDecrypt) {\n\t\tcout << \"[*] Encrypting...\" << endl;\n\t\tencrypt(&in, &out, stoi(options[\"NUMRAILS\"]));\n\t}\n\telse {\n\t\tcout << \"[*] Decrypting...\" << endl;\n\t\tdecrypt(&in, &out, stoi(options[\"NUMRAILS\"]));\n\t}\n\n cout << \"[*] Closing files\" << endl;\n in.close();\n out.close();\n\n return 0;\n}\n\nvoid Rail::encrypt(ifstream* in, ostream* out, int numRails)\n{\n\tvector< vector<char> > rails;\n\trails.resize(numRails);\n\tchar inChar;\n\tint currRail = 0;\n\tbool ascend = true;\n\twhile (in->get(inChar)) {\n\t\trails[currRail].push_back(inChar);\n\t\tif (ascend) { \n\t\t\tcurrRail++;\n\t\t\tif (currRail == numRails-1)\n\t\t\t\tascend = false;\n\t\t}\n\t\telse {\n\t\t\tcurrRail--;\n\t\t\tif (currRail == 0) \n\t\t\t\tascend = true;\n\t\t}\n\t}\n\n\t\/\/Just pad for easier decryption honestly\n\tif (!ascend) {\n\t\twhile (currRail > 0) {\n\t\t\trails[currRail].push_back('\\n');\n\t\t\tif (currRail > 0) currRail--;\n\t\t}\n\t}\n\twhile (currRail < numRails) {\n\t\trails[currRail].push_back('\\n');\n\t\tcurrRail++;\n\t}\n\n\tfor (vector<char> vec : rails) {\n\t\tfor (char output : vec) {\n\t\t\t(*out) << output;\n\t\t}\n\t}\n}\n\n\nvoid Rail::decrypt(ifstream* in, ostream* out, int numRails)\n{\n\tvector< vector<char> > rails;\n\trails.resize(numRails);\n\tchar inChar;\n\n\tstring inLine;\n\tint length = 0;\n\twhile (getline(*in, inLine)) {\n\t\tlength += inLine.length();\n\t}\n\t(*in).clear();\n\t(*in).seekg(0, ios::beg);\n\n\tint numOnEdges = length \/ ((numRails * 2) - 2);\n\tint numInside = numOnEdges * 2 - 1;\n\n\tfor (int numInLine = 0; numInLine < numOnEdges; numInLine++) {\n\t\tif (in->get(inChar)) {\n\t\t\trails[0].push_back(inChar);\n\t\t}\n\t}\n\tfor (int rail = 1; rail < numRails - 1; rail++) {\n\t\tfor (int numInLine = 0; numInLine < numInside; numInLine++) {\n\t\t\tif (in->get(inChar)) {\n\t\t\t\trails[rail].push_back(inChar);\n\t\t\t}\n\t\t}\n\t}\n\tfor (int numInLine = 0; numInLine < numOnEdges; numInLine++) {\n\t\tif (in->get(inChar)) {\n\t\t\trails[numRails-1].push_back(inChar);\n\t\t}\n\t}\n\n\tint edgeIndex = 0;\n\tint middleIndex = 0;\n\tint railIndex = 0;\n\tbool ascend = true;\n\n\twhile (edgeIndex < numOnEdges) {\n\t\tif (railIndex == 0 || railIndex == numRails - 1) {\n\t\t\t(*out) << rails[edgeIndex][railIndex];\n\t\t}\n\t\telse {\n\t\t\t(*out) << rails[middleIndex][railIndex];\n\t\t}\n\n\t\tif (ascend) {\n\t\t\trailIndex++;\n\t\t\tif (railIndex == numRails - 1) {\n\t\t\t\tascend = false;\n\t\t\t\tmiddleIndex++;\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\trailIndex--;\n\t\t\tif (railIndex == 0) {\n\t\t\t\tascend = true;\n\t\t\t\tedgeIndex++;\n\t\t\t\tmiddleIndex++;\n\t\t\t}\n\t\t}\n\t}\n}<commit_msg>further cleanup<commit_after>#include \"main.h\"\n\n\/* example constructor, sets some options *\/\nRail::Rail()\n{\n \/\/ declare options, keep options as uppercase\n vector<string> temp;\n temp.push_back(\"INPUTFILE\");\n temp.push_back(\"OUTPUTFILE\");\n temp.push_back(\"NUMRAILS\");\n temp.push_back(\"DECRYPT\");\n set_opts(temp);\n\n \/\/ set default values, option must exist or error will printed\n set_opt_value(\"OUTPUTFILE\", \"encr_rail.txt\");\n set_opt_value(\"DECRYPT\", \"0\");\n\tset_opt_value(\"NUMRAILS\", \"5\");\n}\n\n\/* I am overriding the default module function\n * for displaying the description text\n *\/\nvoid Rail::disp_desc()\n{\n cout << \"Module: ciphers\/rail\\n\\tEncrypts (or decrypts, if number of rails known) a text file with the rail fence cipher.\\n\\tPlease define the following required options:\\n\\t\\tINPUTFILE\\tinput filename\" << endl;\n cout << endl;\n}\n\n\/* overrides the virtual function from Module\n * this is where the real meaty stuff happens\n *\/\nint Rail::run()\n{\n\tifstream in;\n\tofstream out;\n\tstring ibuff, obuff;\n\tbool shouldDecrypt = false;\n\n\t\/\/ perform error checking on options first\n\tif (options[\"INPUTFILE\"].empty()) {\n\t\tcout << \"[-] Please specify an input file\" << endl;\n\t\treturn 1;\n\t}\n\n\tif (options[\"OUTPUTFILE\"].empty()) {\n\t\tcout << \"[-] Please specify an output file\" << endl;\n\t\treturn 2;\n\t}\n\n\tif (options[\"NUMRAILS\"].empty()) {\n\t\tcout << \"[-] Please specify the number of rails\" << endl;\n\t\treturn 3;\n\t}\n\n\tif (options[\"DECRYPT\"] == \"1\"){\n\t\tshouldDecrypt = true;\n\t}\n\n cout << \"[*] Opening input file: \" << options[\"INPUTFILE\"] << endl;\n in.open(options[\"INPUTFILE\"]);\n\n if (!in.good()) {\n cout << \"[-] Input file error\" << endl;\n return 5;\n }\n\n cout << \"[*] Opening output file: \" << options[\"OUTPUTFILE\"] << endl;\n out.open(options[\"OUTPUTFILE\"]);\n\n\tif (!shouldDecrypt) {\n\t\tcout << \"[*] Encrypting...\" << endl;\n\t\tencrypt(&in, &out, stoi(options[\"NUMRAILS\"]));\n\t}\n\telse {\n\t\tcout << \"[*] Decrypting...\" << endl;\n\t\tdecrypt(&in, &out, stoi(options[\"NUMRAILS\"]));\n\t}\n\n cout << \"[*] Closing files\" << endl;\n in.close();\n out.close();\n\n return 0;\n}\n\nvoid Rail::encrypt(ifstream* in, ostream* out, int numRails)\n{\n\tvector< vector<char> > rails;\n\trails.resize(numRails);\n\tchar inChar;\n\tint currRail = 0;\n\tbool ascend = true;\n\twhile (in->get(inChar)) {\n\t\trails[currRail].push_back(inChar);\n\t\tif (ascend) { \n\t\t\tcurrRail++;\n\t\t\tif (currRail == numRails-1)\n\t\t\t\tascend = false;\n\t\t}\n\t\telse {\n\t\t\tcurrRail--;\n\t\t\tif (currRail == 0) \n\t\t\t\tascend = true;\n\t\t}\n\t}\n\n\t\/\/Just pad for easier decryption honestly\n\tif (!ascend) {\n\t\twhile (currRail > 0) {\n\t\t\trails[currRail].push_back('\\n');\n\t\t\tif (currRail > 0) currRail--;\n\t\t}\n\t}\n\twhile (currRail < numRails) {\n\t\trails[currRail].push_back('\\n');\n\t\tcurrRail++;\n\t}\n\n\tfor (vector<char> vec : rails) {\n\t\tfor (char output : vec) {\n\t\t\t(*out) << output;\n\t\t}\n\t}\n}\n\n\nvoid Rail::decrypt(ifstream* in, ostream* out, int numRails)\n{\n\tvector< vector<char> > rails;\n\trails.resize(numRails);\n\tchar inChar;\n\n\tstring inLine;\n\tint length = 0;\n\twhile (getline(*in, inLine)) {\n\t\tlength += inLine.length();\n\t}\n\t(*in).clear();\n\t(*in).seekg(0, ios::beg);\n\n\tint numOnEdges = length \/ ((numRails * 2) - 2);\n\tint numInside = numOnEdges * 2 - 1;\n\n\tfor (int numInLine = 0; numInLine < numOnEdges; numInLine++) {\n\t\tif (in->get(inChar)) {\n\t\t\trails[0].push_back(inChar);\n\t\t}\n\t}\n\tfor (int rail = 1; rail < numRails - 1; rail++) {\n\t\tfor (int numInLine = 0; numInLine < numInside; numInLine++) {\n\t\t\tif (in->get(inChar)) {\n\t\t\t\trails[rail].push_back(inChar);\n\t\t\t}\n\t\t}\n\t}\n\tfor (int numInLine = 0; numInLine < numOnEdges; numInLine++) {\n\t\tif (in->get(inChar)) {\n\t\t\trails[numRails-1].push_back(inChar);\n\t\t}\n\t}\n\n\tint edgeIndex = 0;\n\tint middleIndex = 0;\n\tint railIndex = 0;\n\tbool ascend = true;\n\n\twhile (edgeIndex < numOnEdges) {\n\t\tif (railIndex == 0 || railIndex == numRails - 1) {\n\t\t\t(*out) << rails[edgeIndex][railIndex];\n\t\t}\n\t\telse {\n\t\t\t(*out) << rails[middleIndex][railIndex];\n\t\t}\n\n\t\tif (ascend) {\n\t\t\trailIndex++;\n\t\t\tif (railIndex == numRails - 1) {\n\t\t\t\tascend = false;\n\t\t\t\tmiddleIndex++;\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\trailIndex--;\n\t\t\tif (railIndex == 0) {\n\t\t\t\tascend = true;\n\t\t\t\tedgeIndex++;\n\t\t\t\tmiddleIndex++;\n\t\t\t}\n\t\t}\n\t}\n}<|endoftext|>"} {"text":"<commit_before>#include <algorithm>\n#include <utility>\n#include <cmath>\n\n\nnamespace maths\n{\n\t\/\/ These are not always defined in cmath nor with 128 bit precision\n\tconstexpr auto e = 2.718281828459045235360287471352662498L;\n\tconstexpr auto ln2 = 0.693147180559945309417232121458176568L;\n\tconstexpr auto ln10 = 2.302585092994045684017991454684364208L;\n\tconstexpr auto log2e = 1.442695040888963407359924681001892137L;\n\tconstexpr auto log10e = 0.434294481903251827651128918916605082L;\n\tconstexpr auto pi = 3.141592653589793238462643383279502884L;\n\tconstexpr auto pi_2 = 1.570796326794896619231321691639751442L;\n\tconstexpr auto pi_4 = 0.785398163397448309615660845819875721L;\n\tconstexpr auto pi2_6 = 1.644934066848226436472415166646025189L;\n\tconstexpr auto sqrt2pi = 2.506628274631000502415765284811045253L;\n\tconstexpr auto sqrt2 = 1.414213562373095048801688724209698079L;\n\tconstexpr auto ngamma = 0.577215664901532860606512090082402431L;\n\t\n\t\/\/\/ The greatest common divisor, so that m|gcd(m, n) and n|gcd(m, n)\n\ttemplate <typename int_t> int_t gcd(int_t m, int_t n)\n\t{\n\t\tif (n < m) std::swap(m, n);\n\t\tint_t r;\n\t\twhile (m) r = n % m, n = m, m = r;\n\t\treturn n;\n\t}\n\n\t\/\/\/ The lowest common multiple, so that gcd(m, n)*lcm(m, n) = m*n\n\ttemplate <typename int_t> int_t lcm(int_t m, int_t n)\n\t{\n\t\treturn m * (n \/ gcd(m, n));\n\t}\n\n\t\/\/\/ The factorial of n, n! = n(n - 1)(n - 2)...\n\ttemplate <typename int_t> int_t fact(int_t n)\n\t{\n\t\tint_t m = 1;\n\t\twhile (n) m *= n--;\n\t\treturn m;\n\t}\n\n\t\/\/\/ The primorial of n, the product of primes up to n\n\ttemplate <typename int_t> int_t prim(int_t n)\n\t{\n\t\tint_t p = 1, q = 1;\n\t\twhile (q++ < n) if (gcd(p, q) < 2) p *= q;\n\t\treturn p;\n\t}\n\n\t\/\/\/ The k permutations of n elements, n!\/(n - k)!\n\ttemplate <typename int_t> int_t perm(int_t n, int_t k)\n\t{\n\t\tk = n - k;\n\t\tint_t m = 1;\n\t\twhile (k--) m *= n--;\n\t\treturn m;\n\t}\n\n\t\/\/\/ The k combinations of n elements, n!\/k!(n - k)!\n\ttemplate <typename int_t> int_t comb(int_t n, int_t k)\n\t{\n\t\tk = std::min(k, n - k);\n\t\tint_t m = 1, r = 1;\n\t\twhile (k) m *= n--, r *= k--;\n\t\treturn m\/r;\n\t}\n\t\n\t\/\/\/ Extends factorials into the real numbers, tgamma(n) = (n - 1)!\n\ttemplate <typename float_t> inline float_t tgamma(float_t x)\n\t{\n\t\treturn std::tgamma(x);\n\t}\n\n\t\/\/\/ The natural logarithm of the gamma function\n\ttemplate <typename float_t> inline float_t lgamma(float_t x)\n\t{\n\t\treturn std::lgamma(x);\n\t}\n\n\t\/\/\/ The lower incomplete gamma function\n\ttemplate <typename float_t> float_t igamma(float_t a, float_t x)\n\t{\n\t\tfloat_t s = 0, t = std::pow(x, a)\/a;\n\t\tdo s += t, t *= x, t \/= ++a;\n\t\twhile (t);\n\t\ts \/= std::exp(x);\n\t\treturn s;\n\t}\n\n\t\/\/\/ The upper incomplete gamma function (lower's complement)\n\ttemplate <typename float_t> float_t igammac(float_t a, float_t x)\n\t{\n\t\treturn std::tgamma(a) - igamma(a, x);\n\t}\n\t\n\t\/\/\/ Extends combinations into the field of real numbers\n\ttemplate <typename float_t> float_t beta(float_t a, float_t b)\n\t{\n\t\treturn std::tgamma(a + b)\/std::tgamma(a)\/std::tgamma(b);\n\t}\n\t\n\t\/\/\/ The lower incomplete beta function\n\ttemplate <typename float_t> float_t ibeta(float_t a, float_t b, float_t p)\n\t{\n\t\tfloat_t t = std::pow(p, a);\n\t\tfloat_t s = 0, n = 1, u = 1 - b;\n\t\tdo s += t\/a++, t *= u++, t \/= n++, t *= p;\n\t\twhile (t);\n\t\treturn s;\n\t}\n\n\t\/\/\/ The upper incomplete beta function (lower's complement)\n\ttemplate <typename float_t> float_t ibetac(float_t a, float_t b, float_t p)\n\t{\n\t\treturn beta(a, b) - ibeta(a, b, p);\n\t}\n\n\t\/\/\/ The generalized Reimann zeta function for real x > 1\n\ttemplate <typename float_t> float_t zeta(float_t x, float_t eps = 1e-9)\n\t{\n\t\tfloat_t r, s = 1, t, n = 1;\n\t\tdo r = std::pow(++n, x), t = 1\/r, s += t;\n\t\twhile (eps < t);\n\t\treturn s;\n\t}\n\n\t\/\/\/ Measures the area under the bell curve for errors of size x\n\ttemplate <typename float_t> inline float_t erf(float_t x)\n\t{\n\t\treturn std::erf(x);\n\t}\n\n\t\/\/\/ Measures the complement of the error function\n\ttemplate <typename float_t> inline float_t erfc(float_t x)\n\t{\n\t\treturn std::erfc(x);\n\t}\n\t\n\t\/\/\/ The power of x raised to the exponent p\n\ttemplate <typename float_t> inline float_t pow(float_t x, float_t p)\n\t{\n\t\treturn std::pow(x, p);\n\t}\n\n\t\/\/\/ The square root of x\n\ttemplate <typename float_t> inline float_t sqrt(float_t x)\n\t{\n\t\treturn std::sqrt(x);\n\t}\n\n\t\/\/\/ The cube root of x\n\ttemplate <typename float_t> inline float_t cbrt(float_t x)\n\t{\n\t\treturn std::cbrt(x);\n\t}\n\n\t\/\/\/ The square root of the sum of the squares of x and y\n\ttemplate <typename float_t> inline float_t hypot(float_t x, float_t y)\n\t{\n\t\treturn std::hypot(x, y);\n\t}\n\n\t\/\/\/ Equivalent to x*y + z but more precise\n\ttemplate <typename float_t> inline float_t fma(float_t x, float_t y, float_t z)\n\t{\n\t\treturn std::fma(x, y, z);\n\t}\n\n\t\/\/\/ Euler's number raised to the exponent x\n\ttemplate <typename float_t> inline float_t exp(float_t x)\n\t{\n\t\treturn std::exp(x);\n\t}\n\n\t\/\/\/ The number 2 raised to the exponent x\n\ttemplate <typename float_t> inline float_t exp2(float_t x)\n\t{\n\t\treturn std::exp2(x);\n\t}\n\n\t\/\/\/ Equivalent to x*exp2(p) but more precise\n\ttemplate <typename float_t> inline float_t ldexp(float_t x, int p)\n\t{\n\t\treturn std::ldexp(x, p);\n\t}\n\n\t\/\/\/ The natural logarithm of x, so exp(log(x)) = x\n\ttemplate <typename float_t> inline float_t log(float_t x)\n\t{\n\t\treturn std::log(x);\n\t}\n\n\t\/\/\/ The logarithm of x expressed in base b, so pow(b, log(x, b)) = x\n\ttemplate <typename float_t> inline float_t logb(float_t x, float_t b)\n\t{\n\t\treturn std::log(x)\/std::log(b);\n\t}\n\n\t\/\/\/ The logarithm of x expressed in base 2, so log2(x) = log(x, 2)\n\ttemplate <typename float_t> inline float_t log2(float_t x)\n\t{\n\t\treturn std::log2(x);\n\t}\n\n\t\/\/\/ The logarithm of x expressed in base 10, so log10(x) = log(x, 10)\n\ttemplate <typename float_t> inline float_t log10(float_t x)\n\t{\n\t\treturn std::log10(x);\n\t}\t\n\n\ttemplate <typename float_t> inline float_t sin(float_t x)\n\t{\n\t\treturn std::sin(x);\n\t}\n\n\ttemplate <typename float_t> inline float_t cos(float_t x)\n\t{\n\t\treturn std::cos(x);\n\t}\n\n\ttemplate <typename float_t> inline float_t tan(float_t x)\n\t{\n\t\treturn std::tan(x);\n\t}\n\n\ttemplate <typename float_t> inline float_t asin(float_t x)\n\t{\n\t\treturn std::asin(x);\n\t}\n\n\ttemplate <typename float_t> inline float_t acos(float_t x)\n\t{\n\t\treturn std::acos(x);\n\t}\n\n\ttemplate <typename float_t> inline float_t atan(float_t x)\n\t{\n\t\treturn std::atan(x);\n\t}\n\n\ttemplate <typename float_t> inline float_t atan2(float_t y, float_t x)\n\t{\n\t\treturn std::atan2(y, x);\n\t}\n\n\ttemplate <typename float_t> inline float_t sinh(float_t x)\n\t{\n\t\treturn std::sinh(x);\n\t}\n\n\ttemplate <typename float_t> inline float_t cosh(float_t x)\n\t{\n\t\treturn std::cosh(x);\n\t}\n\n\ttemplate <typename float_t> inline float_t tanh(float_t x)\n\t{\n\t\treturn std::tanh(x);\n\t}\n\n\ttemplate <typename float_t> inline float_t asinh(float_t x)\n\t{\n\t\treturn std::asinh(x);\n\t}\n\n\ttemplate <typename float_t> inline float_t acosh(float_t x)\n\t{\n\t\treturn std::acosh(x);\n\t}\n\n\ttemplate <typename float_t> inline float_t atanh(float_t x)\n\t{\n\t\treturn std::atanh(x);\n\t}\n\t\n}; \/\/ namespace maths\n\n\t\n<commit_msg>New primorial function<commit_after>#include <algorithm>\n#include <utility>\n#include <cmath>\n\n\nnamespace maths\n{\n\t\/\/ These are not always defined in cmath nor with 128 bit precision\n\tconstexpr auto e = 2.718281828459045235360287471352662498L;\n\tconstexpr auto ln2 = 0.693147180559945309417232121458176568L;\n\tconstexpr auto ln10 = 2.302585092994045684017991454684364208L;\n\tconstexpr auto log2e = 1.442695040888963407359924681001892137L;\n\tconstexpr auto log10e = 0.434294481903251827651128918916605082L;\n\tconstexpr auto pi = 3.141592653589793238462643383279502884L;\n\tconstexpr auto pi_2 = 1.570796326794896619231321691639751442L;\n\tconstexpr auto pi_4 = 0.785398163397448309615660845819875721L;\n\tconstexpr auto pi2_6 = 1.644934066848226436472415166646025189L;\n\tconstexpr auto sqrt2pi = 2.506628274631000502415765284811045253L;\n\tconstexpr auto sqrt2 = 1.414213562373095048801688724209698079L;\n\tconstexpr auto ngamma = 0.577215664901532860606512090082402431L;\n\t\n\t\/\/\/ The greatest common divisor, so that m|gcd(m, n) and n|gcd(m, n)\n\ttemplate <typename int_t> int_t gcd(int_t m, int_t n)\n\t{\n\t\tif (n < m) std::swap(m, n);\n\t\tint_t r;\n\t\twhile (m) r = n % m, n = m, m = r;\n\t\treturn n;\n\t}\n\n\t\/\/\/ The lowest common multiple, so that gcd(m, n)*lcm(m, n) = m*n\n\ttemplate <typename int_t> int_t lcm(int_t m, int_t n)\n\t{\n\t\treturn m * (n \/ gcd(m, n));\n\t}\n\n\t\/\/\/ The factorial of n, n! = n(n - 1)(n - 2)...\n\ttemplate <typename int_t> int_t fact(int_t n)\n\t{\n\t\tint_t m = 1;\n\t\twhile (n) m *= n--;\n\t\treturn m;\n\t}\n\n\t\/\/\/ The primorial of n, the product of primes up to n\n\ttemplate <typename int_t> int_t prim(int_t n)\n\t{\n\t\tif (n < 2) return 1;\n\t\tint_t p = 2, q = 3;\n\t\twhile (q <= n) {\n\t\t if (gcd(p, q) < 2) p *= q;\n\t\t q += 2;\n\t\t};\n\t\treturn p;\n\t}\n\n\t\/\/\/ The k permutations of n elements, n!\/(n - k)!\n\ttemplate <typename int_t> int_t perm(int_t n, int_t k)\n\t{\n\t\tk = n - k;\n\t\tint_t m = 1;\n\t\twhile (k--) m *= n--;\n\t\treturn m;\n\t}\n\n\t\/\/\/ The k combinations of n elements, n!\/k!(n - k)!\n\ttemplate <typename int_t> int_t comb(int_t n, int_t k)\n\t{\n\t\tk = std::min(k, n - k);\n\t\tint_t m = 1, r = 1;\n\t\twhile (k) m *= n--, r *= k--;\n\t\treturn m\/r;\n\t}\n\t\n\t\/\/\/ Extends factorials into the real numbers, tgamma(n) = (n - 1)!\n\ttemplate <typename float_t> inline float_t tgamma(float_t x)\n\t{\n\t\treturn std::tgamma(x);\n\t}\n\n\t\/\/\/ The natural logarithm of the gamma function\n\ttemplate <typename float_t> inline float_t lgamma(float_t x)\n\t{\n\t\treturn std::lgamma(x);\n\t}\n\n\t\/\/\/ The lower incomplete gamma function\n\ttemplate <typename float_t> float_t igamma(float_t a, float_t x)\n\t{\n\t\tfloat_t s = 0, t = std::pow(x, a)\/a;\n\t\tdo s += t, t *= x, t \/= ++a;\n\t\twhile (t);\n\t\ts \/= std::exp(x);\n\t\treturn s;\n\t}\n\n\t\/\/\/ The upper incomplete gamma function (lower's complement)\n\ttemplate <typename float_t> float_t igammac(float_t a, float_t x)\n\t{\n\t\treturn std::tgamma(a) - igamma(a, x);\n\t}\n\t\n\t\/\/\/ Extends combinations into the field of real numbers\n\ttemplate <typename float_t> float_t beta(float_t a, float_t b)\n\t{\n\t\treturn std::tgamma(a + b)\/std::tgamma(a)\/std::tgamma(b);\n\t}\n\t\n\t\/\/\/ The lower incomplete beta function\n\ttemplate <typename float_t> float_t ibeta(float_t a, float_t b, float_t p)\n\t{\n\t\tfloat_t t = std::pow(p, a);\n\t\tfloat_t s = 0, n = 1, u = 1 - b;\n\t\tdo s += t\/a++, t *= u++, t \/= n++, t *= p;\n\t\twhile (t);\n\t\treturn s;\n\t}\n\n\t\/\/\/ The upper incomplete beta function (lower's complement)\n\ttemplate <typename float_t> float_t ibetac(float_t a, float_t b, float_t p)\n\t{\n\t\treturn beta(a, b) - ibeta(a, b, p);\n\t}\n\n\t\/\/\/ The generalized Reimann zeta function for real x > 1\n\ttemplate <typename float_t> float_t zeta(float_t x, float_t eps = 1e-9)\n\t{\n\t\tfloat_t r, s = 1, t, n = 1;\n\t\tdo r = std::pow(++n, x), t = 1\/r, s += t;\n\t\twhile (eps < t);\n\t\treturn s;\n\t}\n\n\t\/\/\/ Measures the area under the bell curve for errors of size x\n\ttemplate <typename float_t> inline float_t erf(float_t x)\n\t{\n\t\treturn std::erf(x);\n\t}\n\n\t\/\/\/ Measures the complement of the error function\n\ttemplate <typename float_t> inline float_t erfc(float_t x)\n\t{\n\t\treturn std::erfc(x);\n\t}\n\t\n\t\/\/\/ The power of x raised to the exponent p\n\ttemplate <typename float_t> inline float_t pow(float_t x, float_t p)\n\t{\n\t\treturn std::pow(x, p);\n\t}\n\n\t\/\/\/ The square root of x\n\ttemplate <typename float_t> inline float_t sqrt(float_t x)\n\t{\n\t\treturn std::sqrt(x);\n\t}\n\n\t\/\/\/ The cube root of x\n\ttemplate <typename float_t> inline float_t cbrt(float_t x)\n\t{\n\t\treturn std::cbrt(x);\n\t}\n\n\t\/\/\/ The square root of the sum of the squares of x and y\n\ttemplate <typename float_t> inline float_t hypot(float_t x, float_t y)\n\t{\n\t\treturn std::hypot(x, y);\n\t}\n\n\t\/\/\/ Equivalent to x*y + z but more precise\n\ttemplate <typename float_t> inline float_t fma(float_t x, float_t y, float_t z)\n\t{\n\t\treturn std::fma(x, y, z);\n\t}\n\n\t\/\/\/ Euler's number raised to the exponent x\n\ttemplate <typename float_t> inline float_t exp(float_t x)\n\t{\n\t\treturn std::exp(x);\n\t}\n\n\t\/\/\/ The number 2 raised to the exponent x\n\ttemplate <typename float_t> inline float_t exp2(float_t x)\n\t{\n\t\treturn std::exp2(x);\n\t}\n\n\t\/\/\/ Equivalent to x*exp2(p) but more precise\n\ttemplate <typename float_t> inline float_t ldexp(float_t x, int p)\n\t{\n\t\treturn std::ldexp(x, p);\n\t}\n\n\t\/\/\/ The natural logarithm of x, so exp(log(x)) = x\n\ttemplate <typename float_t> inline float_t log(float_t x)\n\t{\n\t\treturn std::log(x);\n\t}\n\n\t\/\/\/ The logarithm of x expressed in base b, so pow(b, log(x, b)) = x\n\ttemplate <typename float_t> inline float_t logb(float_t x, float_t b)\n\t{\n\t\treturn std::log(x)\/std::log(b);\n\t}\n\n\t\/\/\/ The logarithm of x expressed in base 2, so log2(x) = log(x, 2)\n\ttemplate <typename float_t> inline float_t log2(float_t x)\n\t{\n\t\treturn std::log2(x);\n\t}\n\n\t\/\/\/ The logarithm of x expressed in base 10, so log10(x) = log(x, 10)\n\ttemplate <typename float_t> inline float_t log10(float_t x)\n\t{\n\t\treturn std::log10(x);\n\t}\t\n\n\ttemplate <typename float_t> inline float_t sin(float_t x)\n\t{\n\t\treturn std::sin(x);\n\t}\n\n\ttemplate <typename float_t> inline float_t cos(float_t x)\n\t{\n\t\treturn std::cos(x);\n\t}\n\n\ttemplate <typename float_t> inline float_t tan(float_t x)\n\t{\n\t\treturn std::tan(x);\n\t}\n\n\ttemplate <typename float_t> inline float_t asin(float_t x)\n\t{\n\t\treturn std::asin(x);\n\t}\n\n\ttemplate <typename float_t> inline float_t acos(float_t x)\n\t{\n\t\treturn std::acos(x);\n\t}\n\n\ttemplate <typename float_t> inline float_t atan(float_t x)\n\t{\n\t\treturn std::atan(x);\n\t}\n\n\ttemplate <typename float_t> inline float_t atan2(float_t y, float_t x)\n\t{\n\t\treturn std::atan2(y, x);\n\t}\n\n\ttemplate <typename float_t> inline float_t sinh(float_t x)\n\t{\n\t\treturn std::sinh(x);\n\t}\n\n\ttemplate <typename float_t> inline float_t cosh(float_t x)\n\t{\n\t\treturn std::cosh(x);\n\t}\n\n\ttemplate <typename float_t> inline float_t tanh(float_t x)\n\t{\n\t\treturn std::tanh(x);\n\t}\n\n\ttemplate <typename float_t> inline float_t asinh(float_t x)\n\t{\n\t\treturn std::asinh(x);\n\t}\n\n\ttemplate <typename float_t> inline float_t acosh(float_t x)\n\t{\n\t\treturn std::acosh(x);\n\t}\n\n\ttemplate <typename float_t> inline float_t atanh(float_t x)\n\t{\n\t\treturn std::atanh(x);\n\t}\n\t\n}; \/\/ namespace maths\n\n\t\n<|endoftext|>"} {"text":"<commit_before>#include \"Client.hh\"\n\n#include <string>\n#include \"Socket.hh\"\n#include \"http\/Response.hh\"\n#include \"http\/Request.hh\"\n#include \"methods\/Get.hh\"\n#include \"Config.hh\"\n\nss::Client::Client(Socket* socket) : socket(socket)\n{\n\tauto request = get_request();\n\thttp::Response response;\n\tresponse.headers[\"protocol\"] = \"HTTP\/1.1\";\n\n\tif (request.headers[\"method\"] == \"GET\")\n\t{\n\t\tmethods::Get(request, &response);\n\t}\n\n\tsend_response(response);\n}\n\nss::http::Request ss::Client::get_request()\n{\n\tstd::string response;\n\n\t\/\/ An endless wait may happen if the last response is the same size as buffer.\n\twhile (true)\n\t{\n\t\tchar buffer[1024];\n\t\tint received;\n\t\tsocket->receive(&buffer, sizeof(buffer), &received);\n\t\tresponse.append(buffer, received);\n\n\t\tif (received < sizeof(buffer))\n\t\t{\n\t\t\tbreak;\n\t\t}\n\t}\n\n\treturn http::Request(response);\n}\n\nvoid ss::Client::send_response(const http::Response& response)\n{\n\tconst auto response_string = response.as_string();\n\tsocket->send(response_string.data(), response_string.size());\n\tsocket->disconnect();\n}\n<commit_msg>Make while loop more compact<commit_after>#include \"Client.hh\"\n\n#include <string>\n#include \"Socket.hh\"\n#include \"http\/Response.hh\"\n#include \"http\/Request.hh\"\n#include \"methods\/Get.hh\"\n#include \"Config.hh\"\n\nss::Client::Client(Socket* socket) : socket(socket)\n{\n\tauto request = get_request();\n\thttp::Response response;\n\tresponse.headers[\"protocol\"] = \"HTTP\/1.1\";\n\n\tif (request.headers[\"method\"] == \"GET\")\n\t{\n\t\tmethods::Get(request, &response);\n\t}\n\n\tsend_response(response);\n}\n\nss::http::Request ss::Client::get_request()\n{\n\tstd::string response;\n\n char buffer[1024];\n\tint received = sizeof(buffer);\n\t\/\/ An endless wait may happen if the last response is the same size as buffer.\n while (received == sizeof(buffer)) {\n\t\tsocket->receive(&buffer, sizeof(buffer), &received);\n\t\tresponse.append(buffer, received);\n\t}\n\n\treturn http::Request(response);\n}\n\nvoid ss::Client::send_response(const http::Response& response)\n{\n\tconst auto response_string = response.as_string();\n\tsocket->send(response_string.data(), response_string.size());\n\tsocket->disconnect();\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * DataHandlerCallback.cpp\n *\n * DataHandlerCallback.cpp - file I\/O for libebml.\n *\n *\n * Copyright (c) 2006 David Conrad\n *\n * This program is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; \n * version 2.1 of the License.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n *\n *\/\n\n#include \"DataHandlerCallback.h\"\n#include <QuickTime\/QuickTime.h>\n\n#include \"ebml\/Debug.h\"\n#include \"ebml\/EbmlConfig.h\"\n#include \"ebml\/StdIOCallback.h\"\n\nusing namespace std;\n\nDataHBuffer::DataHBuffer(size_t bufferSize)\n{\n\tbuffer = new uint8_t[bufferSize];\n\tallocatedSize = bufferSize;\n\tfileOffset = -1;\n\tdataSize = 0;\n}\n\nDataHBuffer::~DataHBuffer()\n{\n\tif (buffer)\n\t\tdelete[] buffer;\n}\n\nvoid DataHBuffer::Realloc(size_t bufferSize)\n{\n\tif (buffer)\n\t\tdelete[] buffer;\n\t\n\tbuffer = new uint8_t[bufferSize];\n\tallocatedSize = bufferSize;\n\tfileOffset = -1;\n\tdataSize = 0;\n}\n\nbool DataHBuffer::ContainsOffset(uint64_t offset)\n{\n\treturn offset >= fileOffset && offset < fileOffset + dataSize;\n}\n\nuint8_t * DataHBuffer::GetBuffer(uint64_t offset, size_t size)\n{\n\tif (size > allocatedSize)\n\t\tRealloc(size);\n\t\n\tfileOffset = offset;\n\tdataSize = size;\n\treturn buffer;\n}\n\nsize_t DataHBuffer::Read(uint64_t offset, size_t size, uint8_t *store)\n{\n\tif (!ContainsOffset(offset))\n\t\treturn 0;\n\t\n\tuint8_t *dataStart = buffer + (offset - fileOffset);\n\tsize_t amountToRead = MIN(fileOffset + dataSize - offset, size);\n\tmemcpy(store, dataStart, amountToRead);\n\treturn amountToRead;\n}\n\n\nDataHandlerCallback::DataHandlerCallback(ComponentInstance dataHandler, const open_mode aMode)\n{\t\n\tInitialize(aMode);\n\t\n\tswitch (aMode)\n\t{\n\t\tcase MODE_READ:\n\t\tcase MODE_WRITE:\n\t\t\tthis->dataHandler = dataHandler;\n\t\t\tbreak;\n\t\t\t\n\t\tdefault:\n\t\t\tthrow 0;\n\t\t\tbreak;\n\t}\n\t\n\t\/\/ figure out if we support wide offesets\n\tgetFileSize();\n}\n\nDataHandlerCallback::DataHandlerCallback(Handle dataRef, OSType dataRefType, const open_mode aMode)\n{\n ComponentResult err = noErr;\n\tComponent dataHComponent = NULL;\n\t\n\tInitialize(aMode);\n\t\n\tif (aMode == MODE_READ)\n\t\tdataHComponent = GetDataHandler(dataRef, dataRefType, kDataHCanRead);\n\telse if (aMode == MODE_WRITE)\n\t\tdataHComponent = GetDataHandler(dataRef, dataRefType, kDataHCanWrite);\n\telse\n\t\tthrow 0;\n\t\n\terr = OpenAComponent(dataHComponent, &dataHandler);\n\tif (err) {\n\t\tthrow CRTError(\"Error opening data handler component\", err);\n\t}\n\t\n\terr = DataHSetDataRef(dataHandler, dataRef);\n\tif (err) {\n\t\tthrow CRTError(\"Error setting data handler ref\", err);\n\t}\n\t\n\tif (aMode == MODE_READ) {\n\t\terr = DataHOpenForRead(dataHandler);\n if (err) {\n throw CRTError(\"Error opening data handler for read\", err);\n }\n\t} else if (aMode == MODE_WRITE) {\n\t\terr = DataHOpenForWrite(dataHandler);\n if (err) {\n throw CRTError(\"Error opening data handler for write\", err);\n }\n\t} else {\n\t\tthrow 0;\n\t}\n\t\n\tcloseHandler = true;\n\t\n\t\/\/ figure out if we support wide offesets\n\tgetFileSize();\n}\n\nvoid DataHandlerCallback::Initialize(const open_mode aMode)\n{\n\tcloseHandler = false;\n\tsupportsWideOffsets = true;\n\tthis->dataHandler = NULL;\n\tmCurrentPosition = 0;\n\tfilesize = 0;\n\tthis->aMode = aMode;\n}\n\nDataHandlerCallback::~DataHandlerCallback() throw()\n{\n\tclose();\n}\n\nuint32 DataHandlerCallback::read(void *buffer, size_t size)\n{\n\tComponentResult err = noErr;\n\tsize_t amountRead = 0;\n\tuint64_t oldPos = mCurrentPosition;\n\tuint8_t *internalBuffer, *myBuffer = (uint8_t *)buffer;\n\t\n if (size < 1 || mCurrentPosition > filesize)\n return 0;\n\t\n\tif (mCurrentPosition + size > filesize)\n\t\tsize = filesize - mCurrentPosition;\n\t\n\twhile (size > 0) {\n\t\tif (dataBuffer.ContainsOffset(mCurrentPosition)) {\n\t\t\tamountRead = dataBuffer.Read(mCurrentPosition, size, myBuffer);\n\t\t\tmyBuffer += amountRead;\n\t\t\tmCurrentPosition += amountRead;\n\t\t\tsize -= amountRead;\n\t\t}\n\t\t\n\t\tif (size <= 0)\n\t\t\tbreak;\n\t\t\n\t\tinternalBuffer = dataBuffer.GetBuffer(mCurrentPosition, READ_SIZE);\n\t\t\n\t\tif (supportsWideOffsets) {\n\t\t\twide wideOffset = SInt64ToWide(mCurrentPosition);\n\t\t\t\n\t\t\terr = DataHScheduleData64(dataHandler, (Ptr)internalBuffer, &wideOffset, \n\t\t\t\t\t\t\t\t\t READ_SIZE, 0, NULL, NULL);\n\t\t} else {\n\t\t\terr = DataHScheduleData(dataHandler, (Ptr)internalBuffer, mCurrentPosition, \n\t\t\t\t\t\t\t\t\tREAD_SIZE, 0, NULL, NULL);\n\t\t}\n\t\n\t\tif (err) {\n\t\t\tthrow CRTError(\"Error reading data\", err);\n\t\t}\n\t}\n\t\n\treturn mCurrentPosition - oldPos;\n}\n\nvoid DataHandlerCallback::setFilePointer(int64 Offset, seek_mode Mode)\n{\n\tswitch ( Mode )\n\t{\n\t\tcase SEEK_CUR:\n\t\t\tmCurrentPosition += Offset;\n\t\t\tbreak;\n\t\tcase SEEK_END:\n\t\t\t\/\/ I think this is what seeking this way does (was ftell(File))\n\t\t\tmCurrentPosition = getFileSize() + Offset;\n\t\t\tbreak;\n\t\tcase SEEK_SET:\n\t\t\tmCurrentPosition = Offset;\n\t\t\tbreak;\n\t}\n}\n\nsize_t DataHandlerCallback::write(const void *Buffer, size_t Size)\n{\n\tComponentResult err = noErr;\n\t\n\tif (supportsWideOffsets) {\n\t\twide wideOffset = SInt64ToWide(mCurrentPosition);\n\t\t\n\t\terr = DataHWrite64(dataHandler, (Ptr)Buffer, &wideOffset, Size, NULL, 0);\n\t} else {\n\t\terr = DataHWrite(dataHandler, (Ptr)Buffer, mCurrentPosition, Size, NULL, 0);\n\t}\n\t\n\tif (err) {\n\t\tthrow CRTError(\"Error writing data\", err);\n\t}\n\tmCurrentPosition += Size;\n\t\n\t\/\/ does QT tell us how much it writes?\n\treturn Size;\n}\n\nuint64 DataHandlerCallback::getFilePointer()\n{\n\treturn mCurrentPosition;\n}\n\nvoid DataHandlerCallback::close()\n{\n\tif (closeHandler) {\n\t\tif (aMode == MODE_READ)\n\t\t\tDataHCloseForRead(dataHandler);\n\t\telse if (aMode == MODE_WRITE)\n\t\t\tDataHCloseForWrite(dataHandler);\n\t\tdataHandler = NULL;\n\t}\n}\n\nSInt64 DataHandlerCallback::getFileSize()\n{\n\tComponentResult err = noErr;\n\twide wideFilesize;\n\t\n\tif (filesize > 0) \n\t\treturn filesize;\n\t\n\terr = DataHGetFileSize64(dataHandler, &wideFilesize);\n\tif (err == noErr) {\n\t\tsupportsWideOffsets = true;\n\t\tfilesize = WideToSInt64(wideFilesize);\n\t} else {\n\t\tlong size32;\n\t\tsupportsWideOffsets = false;\n\t\tDataHGetFileSize(dataHandler, &size32);\n\t\tfilesize = size32;\n\t}\n\t\n\treturn filesize;\n}\n<commit_msg>Changed data handler to not read past the end of the file. Also, check the file size when it may read past it.<commit_after>\/*\n * DataHandlerCallback.cpp\n *\n * DataHandlerCallback.cpp - file I\/O for libebml.\n *\n *\n * Copyright (c) 2006 David Conrad\n *\n * This program is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; \n * version 2.1 of the License.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n *\n *\/\n\n#include \"DataHandlerCallback.h\"\n#include <QuickTime\/QuickTime.h>\n\n#include \"ebml\/Debug.h\"\n#include \"ebml\/EbmlConfig.h\"\n#include \"ebml\/StdIOCallback.h\"\n\nusing namespace std;\n\nDataHBuffer::DataHBuffer(size_t bufferSize)\n{\n\tbuffer = new uint8_t[bufferSize];\n\tallocatedSize = bufferSize;\n\tfileOffset = -1;\n\tdataSize = 0;\n}\n\nDataHBuffer::~DataHBuffer()\n{\n\tif (buffer)\n\t\tdelete[] buffer;\n}\n\nvoid DataHBuffer::Realloc(size_t bufferSize)\n{\n\tif (buffer)\n\t\tdelete[] buffer;\n\t\n\tbuffer = new uint8_t[bufferSize];\n\tallocatedSize = bufferSize;\n\tfileOffset = -1;\n\tdataSize = 0;\n}\n\nbool DataHBuffer::ContainsOffset(uint64_t offset)\n{\n\treturn offset >= fileOffset && offset < fileOffset + dataSize;\n}\n\nuint8_t * DataHBuffer::GetBuffer(uint64_t offset, size_t size)\n{\n\tif (size > allocatedSize)\n\t\tRealloc(size);\n\t\n\tfileOffset = offset;\n\tdataSize = size;\n\treturn buffer;\n}\n\nsize_t DataHBuffer::Read(uint64_t offset, size_t size, uint8_t *store)\n{\n\tif (!ContainsOffset(offset))\n\t\treturn 0;\n\t\n\tuint8_t *dataStart = buffer + (offset - fileOffset);\n\tsize_t amountToRead = MIN(fileOffset + dataSize - offset, size);\n\tmemcpy(store, dataStart, amountToRead);\n\treturn amountToRead;\n}\n\n\nDataHandlerCallback::DataHandlerCallback(ComponentInstance dataHandler, const open_mode aMode)\n{\t\n\tInitialize(aMode);\n\t\n\tswitch (aMode)\n\t{\n\t\tcase MODE_READ:\n\t\tcase MODE_WRITE:\n\t\t\tthis->dataHandler = dataHandler;\n\t\t\tbreak;\n\t\t\t\n\t\tdefault:\n\t\t\tthrow 0;\n\t\t\tbreak;\n\t}\n\t\n\t\/\/ figure out if we support wide offesets\n\tgetFileSize();\n}\n\nDataHandlerCallback::DataHandlerCallback(Handle dataRef, OSType dataRefType, const open_mode aMode)\n{\n ComponentResult err = noErr;\n\tComponent dataHComponent = NULL;\n\t\n\tInitialize(aMode);\n\t\n\tif (aMode == MODE_READ)\n\t\tdataHComponent = GetDataHandler(dataRef, dataRefType, kDataHCanRead);\n\telse if (aMode == MODE_WRITE)\n\t\tdataHComponent = GetDataHandler(dataRef, dataRefType, kDataHCanWrite);\n\telse\n\t\tthrow 0;\n\t\n\terr = OpenAComponent(dataHComponent, &dataHandler);\n\tif (err) {\n\t\tthrow CRTError(\"Error opening data handler component\", err);\n\t}\n\t\n\terr = DataHSetDataRef(dataHandler, dataRef);\n\tif (err) {\n\t\tthrow CRTError(\"Error setting data handler ref\", err);\n\t}\n\t\n\tif (aMode == MODE_READ) {\n\t\terr = DataHOpenForRead(dataHandler);\n if (err) {\n throw CRTError(\"Error opening data handler for read\", err);\n }\n\t} else if (aMode == MODE_WRITE) {\n\t\terr = DataHOpenForWrite(dataHandler);\n if (err) {\n throw CRTError(\"Error opening data handler for write\", err);\n }\n\t} else {\n\t\tthrow 0;\n\t}\n\t\n\tcloseHandler = true;\n\t\n\t\/\/ figure out if we support wide offesets\n\tgetFileSize();\n}\n\nvoid DataHandlerCallback::Initialize(const open_mode aMode)\n{\n\tcloseHandler = false;\n\tsupportsWideOffsets = true;\n\tthis->dataHandler = NULL;\n\tmCurrentPosition = 0;\n\tfilesize = 0;\n\tthis->aMode = aMode;\n}\n\nDataHandlerCallback::~DataHandlerCallback() throw()\n{\n\tclose();\n}\n\nuint32 DataHandlerCallback::read(void *buffer, size_t size)\n{\n\tComponentResult err = noErr;\n\tsize_t amountRead = 0;\n\tuint64_t oldPos = mCurrentPosition;\n\tuint8_t *internalBuffer, *myBuffer = (uint8_t *)buffer;\n\t\n\tif (mCurrentPosition + size > filesize)\n\t\tgetFileSize();\n\t\n if (size < 1 || mCurrentPosition > filesize)\n return 0;\n\t\n\tif (mCurrentPosition + size > filesize)\n\t\tsize = filesize - mCurrentPosition;\n\t\n\twhile (size > 0) {\n\t\tif (dataBuffer.ContainsOffset(mCurrentPosition)) {\n\t\t\tamountRead = dataBuffer.Read(mCurrentPosition, size, myBuffer);\n\t\t\tmyBuffer += amountRead;\n\t\t\tmCurrentPosition += amountRead;\n\t\t\tsize -= amountRead;\n\t\t}\n\t\t\n\t\tif (size <= 0)\n\t\t\tbreak;\n\t\t\n\t\tsize_t readSize = MIN(READ_SIZE, filesize - mCurrentPosition);\n\t\t\n\t\tinternalBuffer = dataBuffer.GetBuffer(mCurrentPosition, readSize);\n\t\t\n\t\tif (supportsWideOffsets) {\n\t\t\twide wideOffset = SInt64ToWide(mCurrentPosition);\n\t\t\t\n\t\t\terr = DataHScheduleData64(dataHandler, (Ptr)internalBuffer, &wideOffset, \n\t\t\t\t\t\t\t\t\t readSize, 0, NULL, NULL);\n\t\t} else {\n\t\t\terr = DataHScheduleData(dataHandler, (Ptr)internalBuffer, mCurrentPosition, \n\t\t\t\t\t\t\t\t\treadSize, 0, NULL, NULL);\n\t\t}\n\t\n\t\tif (err) {\n\t\t\tthrow CRTError(\"Error reading data\", err);\n\t\t}\n\t}\n\t\n\treturn mCurrentPosition - oldPos;\n}\n\nvoid DataHandlerCallback::setFilePointer(int64 Offset, seek_mode Mode)\n{\n\tswitch ( Mode )\n\t{\n\t\tcase SEEK_CUR:\n\t\t\tmCurrentPosition += Offset;\n\t\t\tbreak;\n\t\tcase SEEK_END:\n\t\t\t\/\/ I think this is what seeking this way does (was ftell(File))\n\t\t\tmCurrentPosition = getFileSize() + Offset;\n\t\t\tbreak;\n\t\tcase SEEK_SET:\n\t\t\tmCurrentPosition = Offset;\n\t\t\tbreak;\n\t}\n}\n\nsize_t DataHandlerCallback::write(const void *Buffer, size_t Size)\n{\n\tComponentResult err = noErr;\n\t\n\tif (supportsWideOffsets) {\n\t\twide wideOffset = SInt64ToWide(mCurrentPosition);\n\t\t\n\t\terr = DataHWrite64(dataHandler, (Ptr)Buffer, &wideOffset, Size, NULL, 0);\n\t} else {\n\t\terr = DataHWrite(dataHandler, (Ptr)Buffer, mCurrentPosition, Size, NULL, 0);\n\t}\n\t\n\tif (err) {\n\t\tthrow CRTError(\"Error writing data\", err);\n\t}\n\tmCurrentPosition += Size;\n\t\n\t\/\/ does QT tell us how much it writes?\n\treturn Size;\n}\n\nuint64 DataHandlerCallback::getFilePointer()\n{\n\treturn mCurrentPosition;\n}\n\nvoid DataHandlerCallback::close()\n{\n\tif (closeHandler) {\n\t\tif (aMode == MODE_READ)\n\t\t\tDataHCloseForRead(dataHandler);\n\t\telse if (aMode == MODE_WRITE)\n\t\t\tDataHCloseForWrite(dataHandler);\n\t\tdataHandler = NULL;\n\t}\n}\n\nSInt64 DataHandlerCallback::getFileSize()\n{\n\tComponentResult err = noErr;\n\twide wideFilesize;\n\t\n\terr = DataHGetFileSize64(dataHandler, &wideFilesize);\n\tif (err == noErr) {\n\t\tsupportsWideOffsets = true;\n\t\tfilesize = WideToSInt64(wideFilesize);\n\t} else {\n\t\tlong size32;\n\t\tsupportsWideOffsets = false;\n\t\tDataHGetFileSize(dataHandler, &size32);\n\t\tfilesize = size32;\n\t}\n\t\n\treturn filesize;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2012-2015, Robert Escriva\n\/\/ All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright notice,\n\/\/ this list of conditions and the following disclaimer.\n\/\/ * Redistributions in binary form must reproduce the above copyright\n\/\/ notice, this list of conditions and the following disclaimer in the\n\/\/ documentation and\/or other materials provided with the distribution.\n\/\/ * Neither the name of Replicant nor the names of its contributors may be\n\/\/ used to endorse or promote products derived from this software without\n\/\/ specific prior written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n\/\/ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\/\/ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\/\/ ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\n\/\/ LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n\/\/ CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n\/\/ SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n\/\/ INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n\/\/ CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n\/\/ ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n\/\/ POSSIBILITY OF SUCH DAMAGE.\n\n\/\/ POSIX\n#include <poll.h>\n\n\/\/ STL\n#include <memory>\n\n\/\/ po6\n#include <po6\/time.h>\n\n\/\/ BusyBee\n#include <busybee_constants.h>\n#include <busybee_single.h>\n\n\/\/ Replicant\n#include \"common\/bootstrap.h\"\n#include \"common\/configuration.h\"\n#include \"common\/network_msgtype.h\"\n\nusing replicant::bootstrap;\n\nbool\nbootstrap :: parse_hosts(const char* conn_str,\n std::vector<po6::net::hostname>* hosts)\n{\n const size_t conn_str_sz = strlen(conn_str);\n std::vector<char> cs(conn_str, conn_str + conn_str_sz + 1);\n char* ptr = &cs[0];\n char* const end = ptr + conn_str_sz;\n\n while (ptr < end)\n {\n char* eoh = strchr(ptr, ',');\n eoh = eoh ? eoh : end;\n *eoh = '\\0';\n char* colon = strrchr(ptr, ':');\n\n if (colon == NULL)\n {\n hosts->push_back(po6::net::hostname(ptr, 1982));\n ptr = eoh + 1;\n continue;\n }\n\n char* tmp = NULL;\n errno = 0;\n unsigned long port = strtoul(colon + 1, &tmp, 10);\n\n if (errno != 0)\n {\n return false;\n }\n\n std::string host;\n\n if (*ptr == '[' && colon > ptr && *(colon - 1) == ']')\n {\n host.assign(ptr + 1, colon - 1);\n }\n else\n {\n host.assign(ptr, colon);\n }\n\n hosts->push_back(po6::net::hostname(host.c_str(), port));\n ptr = eoh + 1;\n }\n\n return true;\n}\n\nstd::string\nbootstrap :: conn_str(const po6::net::hostname* hns, size_t hns_sz)\n{\n std::ostringstream ostr;\n\n for (size_t i = 0; i < hns_sz; ++i)\n {\n if (i > 0)\n {\n ostr << \",\";\n }\n\n ostr << hns[i];\n }\n\n return ostr.str();\n}\n\nbootstrap :: bootstrap()\n : m_hosts()\n , m_valid(true)\n{\n}\n\nbootstrap :: bootstrap(const char* host, uint16_t port)\n : m_hosts()\n , m_valid(true)\n{\n m_hosts.push_back(po6::net::hostname(host, port));\n}\n\nbootstrap :: bootstrap(const char* cs)\n : m_hosts()\n , m_valid(true)\n{\n m_valid = parse_hosts(cs, &m_hosts);\n}\n\nbootstrap :: bootstrap(const char* host, uint16_t port, const char* cs)\n : m_hosts()\n , m_valid(true)\n{\n m_valid = parse_hosts(cs, &m_hosts);\n m_hosts.push_back(po6::net::hostname(host, port));\n}\n\nbootstrap :: bootstrap(const std::vector<po6::net::hostname>& h)\n : m_hosts(h)\n , m_valid(true)\n{\n}\n\nbootstrap :: bootstrap(const bootstrap& other)\n : m_hosts(other.m_hosts)\n , m_valid(other.m_valid)\n{\n}\n\nbootstrap :: ~bootstrap() throw ()\n{\n}\n\nbool\nbootstrap :: valid() const\n{\n if (!m_valid)\n {\n return false;\n }\n\n for (size_t i = 0; i < m_hosts.size(); ++i)\n {\n if (m_hosts[i].port <= 0 || m_hosts[i].port >= (1 << 16))\n {\n return false;\n }\n }\n\n return true;\n}\n\n#define MILLIS (1000ULL * 1000ULL)\n\nreplicant_returncode\nbootstrap :: do_it(int timeout, configuration* config, e::error* err) const\n{\n if (!m_valid)\n {\n err->set_loc(__FILE__, __LINE__);\n err->set_msg() << \"invalid bootstrap connection string\";\n return REPLICANT_COMM_FAILED;\n }\n\n if (m_hosts.empty())\n {\n err->set_loc(__FILE__, __LINE__);\n err->set_msg() << \"no hosts to bootstrap from\";\n return REPLICANT_COMM_FAILED;\n }\n\n std::vector<e::compat::shared_ptr<busybee_single> > conns;\n conns.resize(m_hosts.size());\n\n int64_t now = po6::monotonic_time();\n const int64_t target = now + timeout * MILLIS;\n replicant_returncode rc;\n\n while (timeout < 0 || now < target)\n {\n for (size_t i = 0; i < m_hosts.size(); ++i)\n {\n if (conns[i].get())\n {\n continue;\n }\n\n conns[i].reset(new busybee_single(m_hosts[i]));\n const size_t sz = BUSYBEE_HEADER_SIZE\n + pack_size(REPLNET_BOOTSTRAP);\n std::auto_ptr<e::buffer> msg(e::buffer::create(sz));\n msg->pack_at(BUSYBEE_HEADER_SIZE) << REPLNET_BOOTSTRAP;\n\n switch (conns[i]->send(msg))\n {\n case BUSYBEE_SUCCESS:\n break;\n case BUSYBEE_TIMEOUT:\n err->set_loc(__FILE__, __LINE__);\n err->set_msg() << \"timed out connecting to \" << m_hosts[i];\n rc = REPLICANT_TIMEOUT;\n conns[i].reset();\n break;\n case BUSYBEE_SHUTDOWN:\n case BUSYBEE_POLLFAILED:\n case BUSYBEE_DISRUPTED:\n case BUSYBEE_ADDFDFAIL:\n case BUSYBEE_EXTERNAL:\n case BUSYBEE_INTERRUPTED:\n err->set_loc(__FILE__, __LINE__);\n err->set_msg() << \"communication error with \" << m_hosts[i];\n rc = REPLICANT_COMM_FAILED;\n conns[i].reset();\n break;\n default:\n abort();\n }\n }\n\n bool failures = false;\n std::vector<pollfd> pfds;\n pfds.resize(m_hosts.size());\n\n for (size_t i = 0; i < m_hosts.size(); ++i)\n {\n if (!conns[i].get())\n {\n failures = true;\n pfds[i].fd = -1;\n }\n else\n {\n pfds[i].fd = conns[i]->poll_fd();\n pfds[i].events = POLLIN|POLLOUT|POLLHUP|POLLERR;\n pfds[i].revents = 0;\n }\n }\n\n const int64_t remain = (target - now) \/ MILLIS;\n const int this_timeout = timeout < 0 ? -1 : remain;\n int ret = poll(&pfds[0], pfds.size(), failures ? std::min(this_timeout, 100) : this_timeout);\n now = po6::monotonic_time();\n\n if (ret < 0)\n {\n int e = errno;\n err->set_loc(__FILE__, __LINE__);\n err->set_msg() << \"poll failed: \" << po6::strerror(e) << \" [\" << po6::strerrno(e) << \"]\";\n errno = e;\n return REPLICANT_SEE_ERRNO;\n }\n else if (ret == 0)\n {\n continue;\n }\n\n assert(ret > 0);\n size_t idx = m_hosts.size();\n\n for (size_t i = 0; i < m_hosts.size(); ++i)\n {\n if (pfds[i].revents != 0)\n {\n idx = i;\n break;\n }\n }\n\n std::auto_ptr<e::buffer> msg;\n conns[idx]->set_timeout(0);\n\n switch (conns[idx]->recv(&msg))\n {\n case BUSYBEE_SUCCESS:\n break;\n case BUSYBEE_TIMEOUT:\n break;\n case BUSYBEE_SHUTDOWN:\n case BUSYBEE_POLLFAILED:\n case BUSYBEE_DISRUPTED:\n case BUSYBEE_ADDFDFAIL:\n case BUSYBEE_EXTERNAL:\n case BUSYBEE_INTERRUPTED:\n err->set_loc(__FILE__, __LINE__);\n err->set_msg() << \"communication error with \" << m_hosts[idx];\n rc = REPLICANT_COMM_FAILED;\n conns[idx].reset();\n break;\n default:\n abort();\n }\n\n if (!msg.get())\n {\n continue;\n }\n\n network_msgtype mt = REPLNET_NOP;\n e::unpacker up = msg->unpack_from(BUSYBEE_HEADER_SIZE);\n up >> mt >> *config;\n\n if (up.error() || mt != REPLNET_BOOTSTRAP || !config->validate())\n {\n err->set_loc(__FILE__, __LINE__);\n err->set_msg() << \"received a malformed bootstrap message from \" << m_hosts[idx];\n rc = REPLICANT_COMM_FAILED;\n conns[idx].reset();\n continue;\n }\n\n return REPLICANT_SUCCESS;\n }\n\n \/\/ return the error corresponding to the last failure\n return rc;\n}\n\nstd::string\nbootstrap :: conn_str() const\n{\n return conn_str(&m_hosts[0], m_hosts.size());\n}\n\nbootstrap&\nbootstrap :: operator = (const bootstrap& rhs)\n{\n if (this != &rhs)\n {\n m_hosts = rhs.m_hosts;\n m_valid = rhs.m_valid;\n }\n\n return *this;\n}\n\nstd::ostream&\nreplicant :: operator << (std::ostream& lhs, const bootstrap& rhs)\n{\n return lhs << rhs.conn_str();\n}\n<commit_msg>Fix an uninitialized returncode in bootstrap.<commit_after>\/\/ Copyright (c) 2012-2015, Robert Escriva\n\/\/ All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright notice,\n\/\/ this list of conditions and the following disclaimer.\n\/\/ * Redistributions in binary form must reproduce the above copyright\n\/\/ notice, this list of conditions and the following disclaimer in the\n\/\/ documentation and\/or other materials provided with the distribution.\n\/\/ * Neither the name of Replicant nor the names of its contributors may be\n\/\/ used to endorse or promote products derived from this software without\n\/\/ specific prior written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n\/\/ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\/\/ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\/\/ ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\n\/\/ LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n\/\/ CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n\/\/ SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n\/\/ INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n\/\/ CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n\/\/ ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n\/\/ POSSIBILITY OF SUCH DAMAGE.\n\n\/\/ POSIX\n#include <poll.h>\n\n\/\/ STL\n#include <memory>\n\n\/\/ po6\n#include <po6\/time.h>\n\n\/\/ BusyBee\n#include <busybee_constants.h>\n#include <busybee_single.h>\n\n\/\/ Replicant\n#include \"common\/bootstrap.h\"\n#include \"common\/configuration.h\"\n#include \"common\/network_msgtype.h\"\n\nusing replicant::bootstrap;\n\nbool\nbootstrap :: parse_hosts(const char* conn_str,\n std::vector<po6::net::hostname>* hosts)\n{\n const size_t conn_str_sz = strlen(conn_str);\n std::vector<char> cs(conn_str, conn_str + conn_str_sz + 1);\n char* ptr = &cs[0];\n char* const end = ptr + conn_str_sz;\n\n while (ptr < end)\n {\n char* eoh = strchr(ptr, ',');\n eoh = eoh ? eoh : end;\n *eoh = '\\0';\n char* colon = strrchr(ptr, ':');\n\n if (colon == NULL)\n {\n hosts->push_back(po6::net::hostname(ptr, 1982));\n ptr = eoh + 1;\n continue;\n }\n\n char* tmp = NULL;\n errno = 0;\n unsigned long port = strtoul(colon + 1, &tmp, 10);\n\n if (errno != 0)\n {\n return false;\n }\n\n std::string host;\n\n if (*ptr == '[' && colon > ptr && *(colon - 1) == ']')\n {\n host.assign(ptr + 1, colon - 1);\n }\n else\n {\n host.assign(ptr, colon);\n }\n\n hosts->push_back(po6::net::hostname(host.c_str(), port));\n ptr = eoh + 1;\n }\n\n return true;\n}\n\nstd::string\nbootstrap :: conn_str(const po6::net::hostname* hns, size_t hns_sz)\n{\n std::ostringstream ostr;\n\n for (size_t i = 0; i < hns_sz; ++i)\n {\n if (i > 0)\n {\n ostr << \",\";\n }\n\n ostr << hns[i];\n }\n\n return ostr.str();\n}\n\nbootstrap :: bootstrap()\n : m_hosts()\n , m_valid(true)\n{\n}\n\nbootstrap :: bootstrap(const char* host, uint16_t port)\n : m_hosts()\n , m_valid(true)\n{\n m_hosts.push_back(po6::net::hostname(host, port));\n}\n\nbootstrap :: bootstrap(const char* cs)\n : m_hosts()\n , m_valid(true)\n{\n m_valid = parse_hosts(cs, &m_hosts);\n}\n\nbootstrap :: bootstrap(const char* host, uint16_t port, const char* cs)\n : m_hosts()\n , m_valid(true)\n{\n m_valid = parse_hosts(cs, &m_hosts);\n m_hosts.push_back(po6::net::hostname(host, port));\n}\n\nbootstrap :: bootstrap(const std::vector<po6::net::hostname>& h)\n : m_hosts(h)\n , m_valid(true)\n{\n}\n\nbootstrap :: bootstrap(const bootstrap& other)\n : m_hosts(other.m_hosts)\n , m_valid(other.m_valid)\n{\n}\n\nbootstrap :: ~bootstrap() throw ()\n{\n}\n\nbool\nbootstrap :: valid() const\n{\n if (!m_valid)\n {\n return false;\n }\n\n for (size_t i = 0; i < m_hosts.size(); ++i)\n {\n if (m_hosts[i].port <= 0 || m_hosts[i].port >= (1 << 16))\n {\n return false;\n }\n }\n\n return true;\n}\n\n#define MILLIS (1000ULL * 1000ULL)\n\nreplicant_returncode\nbootstrap :: do_it(int timeout, configuration* config, e::error* err) const\n{\n if (!m_valid)\n {\n err->set_loc(__FILE__, __LINE__);\n err->set_msg() << \"invalid bootstrap connection string\";\n return REPLICANT_COMM_FAILED;\n }\n\n if (m_hosts.empty())\n {\n err->set_loc(__FILE__, __LINE__);\n err->set_msg() << \"no hosts to bootstrap from\";\n return REPLICANT_COMM_FAILED;\n }\n\n std::vector<e::compat::shared_ptr<busybee_single> > conns;\n conns.resize(m_hosts.size());\n\n int64_t now = po6::monotonic_time();\n const int64_t target = now + timeout * MILLIS;\n replicant_returncode rc = REPLICANT_TIMEOUT;\n err->set_loc(__FILE__, __LINE__);\n err->set_msg() << \"timed out connecting to the cluster\";\n\n while (timeout < 0 || now < target)\n {\n for (size_t i = 0; i < m_hosts.size(); ++i)\n {\n if (conns[i].get())\n {\n continue;\n }\n\n conns[i].reset(new busybee_single(m_hosts[i]));\n const size_t sz = BUSYBEE_HEADER_SIZE\n + pack_size(REPLNET_BOOTSTRAP);\n std::auto_ptr<e::buffer> msg(e::buffer::create(sz));\n msg->pack_at(BUSYBEE_HEADER_SIZE) << REPLNET_BOOTSTRAP;\n\n switch (conns[i]->send(msg))\n {\n case BUSYBEE_SUCCESS:\n break;\n case BUSYBEE_TIMEOUT:\n err->set_loc(__FILE__, __LINE__);\n err->set_msg() << \"timed out connecting to \" << m_hosts[i];\n rc = REPLICANT_TIMEOUT;\n conns[i].reset();\n break;\n case BUSYBEE_SHUTDOWN:\n case BUSYBEE_POLLFAILED:\n case BUSYBEE_DISRUPTED:\n case BUSYBEE_ADDFDFAIL:\n case BUSYBEE_EXTERNAL:\n case BUSYBEE_INTERRUPTED:\n err->set_loc(__FILE__, __LINE__);\n err->set_msg() << \"communication error with \" << m_hosts[i];\n rc = REPLICANT_COMM_FAILED;\n conns[i].reset();\n break;\n default:\n abort();\n }\n }\n\n bool failures = false;\n std::vector<pollfd> pfds;\n pfds.resize(m_hosts.size());\n\n for (size_t i = 0; i < m_hosts.size(); ++i)\n {\n if (!conns[i].get())\n {\n failures = true;\n pfds[i].fd = -1;\n }\n else\n {\n pfds[i].fd = conns[i]->poll_fd();\n pfds[i].events = POLLIN|POLLOUT|POLLHUP|POLLERR;\n pfds[i].revents = 0;\n }\n }\n\n const int64_t remain = (target - now) \/ MILLIS;\n const int this_timeout = timeout < 0 ? -1 : remain;\n int ret = poll(&pfds[0], pfds.size(), failures ? std::min(this_timeout, 100) : this_timeout);\n now = po6::monotonic_time();\n\n if (ret < 0)\n {\n int e = errno;\n err->set_loc(__FILE__, __LINE__);\n err->set_msg() << \"poll failed: \" << po6::strerror(e) << \" [\" << po6::strerrno(e) << \"]\";\n errno = e;\n return REPLICANT_SEE_ERRNO;\n }\n else if (ret == 0)\n {\n continue;\n }\n\n assert(ret > 0);\n size_t idx = m_hosts.size();\n\n for (size_t i = 0; i < m_hosts.size(); ++i)\n {\n if (pfds[i].revents != 0)\n {\n idx = i;\n break;\n }\n }\n\n std::auto_ptr<e::buffer> msg;\n conns[idx]->set_timeout(0);\n\n switch (conns[idx]->recv(&msg))\n {\n case BUSYBEE_SUCCESS:\n break;\n case BUSYBEE_TIMEOUT:\n break;\n case BUSYBEE_SHUTDOWN:\n case BUSYBEE_POLLFAILED:\n case BUSYBEE_DISRUPTED:\n case BUSYBEE_ADDFDFAIL:\n case BUSYBEE_EXTERNAL:\n case BUSYBEE_INTERRUPTED:\n err->set_loc(__FILE__, __LINE__);\n err->set_msg() << \"communication error with \" << m_hosts[idx];\n rc = REPLICANT_COMM_FAILED;\n conns[idx].reset();\n break;\n default:\n abort();\n }\n\n if (!msg.get())\n {\n continue;\n }\n\n network_msgtype mt = REPLNET_NOP;\n e::unpacker up = msg->unpack_from(BUSYBEE_HEADER_SIZE);\n up >> mt >> *config;\n\n if (up.error() || mt != REPLNET_BOOTSTRAP || !config->validate())\n {\n err->set_loc(__FILE__, __LINE__);\n err->set_msg() << \"received a malformed bootstrap message from \" << m_hosts[idx];\n rc = REPLICANT_COMM_FAILED;\n conns[idx].reset();\n continue;\n }\n\n return REPLICANT_SUCCESS;\n }\n\n \/\/ return the error corresponding to the last failure\n return rc;\n}\n\nstd::string\nbootstrap :: conn_str() const\n{\n return conn_str(&m_hosts[0], m_hosts.size());\n}\n\nbootstrap&\nbootstrap :: operator = (const bootstrap& rhs)\n{\n if (this != &rhs)\n {\n m_hosts = rhs.m_hosts;\n m_valid = rhs.m_valid;\n }\n\n return *this;\n}\n\nstd::ostream&\nreplicant :: operator << (std::ostream& lhs, const bootstrap& rhs)\n{\n return lhs << rhs.conn_str();\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/------------------------------------------------------------------------------------------------------------\r\n\/\/* Copyright 2010-2013 Immersive and Creative Technologies Lab, Cyprus University of Technology *\r\n\/\/* Link: http:\/\/ict.cut.ac.cy *\r\n\/\/* Software developer(s): Kyriakos Herakleous *\r\n\/\/* Researcher(s): Kyriakos Herakleous, Charalambos Poullis *\r\n\/\/* *\r\n\/\/* This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License.*\r\n\/\/* Link: http:\/\/creativecommons.org\/licenses\/by-nc-sa\/3.0\/deed.en_US *\r\n\/\/------------------------------------------------------------------------------------------------------------\r\n\r\n#include \"StdAfx.h\"\r\n#include \"PointCloudImage.h\"\r\n\r\n\r\n\r\nPointCloudImage::PointCloudImage(int imageW,int imageH, bool colorFlag_)\r\n{\r\n\tw=imageW;\r\n\th=imageH;\r\n\tcolorFlag = colorFlag_;\r\n\t\r\n\tpoints = cv::Mat(h,w,CV_32FC3);\r\n\r\n\tif(colorFlag==true)\r\n\t{\r\n\t\t\r\n\t\tcolor = cv::Mat(h,w,CV_32FC3,cv::Scalar(0));\r\n\t}\r\n\telse\r\n\t\tcolor = NULL;\r\n\r\n\tnumOfPointsForPixel = cv::Mat(h,w,CV_8U,cv::Scalar(0));\r\n}\r\n\r\nPointCloudImage::~PointCloudImage(void)\r\n{\r\n\t\r\n}\r\n\r\nbool PointCloudImage::hasColor()\r\n{\r\n\treturn colorFlag;\r\n}\r\n\r\nbool PointCloudImage::setPoint(int i_w, int j_h, cv::Point3f point, cv::Vec3f colorBGR)\r\n{\r\n\tif(i_w>w || j_h>h)\r\n\t\treturn false;\r\n\r\n\tsetPoint(i_w,j_h,point);\r\n\r\n\tUtilities::matSet3D(color,i_w,j_h,colorBGR);\r\n\r\n\treturn true;\r\n}\r\n\r\nbool PointCloudImage::setPoint(int i_w, int j_h, cv::Point3f point)\r\n{\r\n\tif(i_w>w || j_h>h)\r\n\t\treturn false;\r\n\r\n\tUtilities::matSet3D(points,i_w,j_h,(cv::Vec3f)point);\r\n\tUtilities::matSet2D(numOfPointsForPixel,i_w,j_h,1);\r\n\r\n\treturn true;\r\n}\r\n\r\nbool PointCloudImage::getPoint(int i_w, int j_h, cv::Point3f &pointOut, cv::Vec3f &colorOut)\r\n{\r\n\tif(i_w>w || j_h>h)\r\n\t\treturn false;\r\n\r\n\tuchar num = numOfPointsForPixel.at<uchar>(j_h,i_w);\r\n\r\n\tif(num > 0)\r\n\t{\r\n\t\t\r\n\t\tpointOut = (cv::Point3f) (Utilities::matGet3D(points,i_w,j_h) \/ (float) num);\r\n\r\n\t\t\r\n\t\tif(!color.empty())\r\n\t\t{\r\n\t\t\tcolorOut = (cv::Point3f) (Utilities::matGet3D(color,i_w,j_h) \/ (float) num);\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\treturn false;\r\n\t\t}\r\n\t\t\r\n\r\n\t\treturn true;\r\n\t}\r\n\telse\r\n\t{\r\n\t\treturn false;\r\n\t}\r\n\t\r\n}\r\n\r\nbool PointCloudImage::getPoint(int i_w, int j_h, cv::Point3f &pointOut)\r\n{\r\n\tif(i_w>w || j_h>h)\r\n\t\treturn false;\r\n\r\n\tuchar num = numOfPointsForPixel.at<uchar>(j_h,i_w);\r\n\r\n\tif(num > 0)\r\n\t{\r\n\t\tpointOut = (cv::Point3f) (Utilities::matGet3D(points,i_w,j_h) \/ (float) num);\r\n\t\treturn true;\r\n\t}\r\n\telse\r\n\t{\r\n\t\treturn false;\r\n\t}\r\n\t\r\n}\r\n\r\nbool PointCloudImage::addPoint(int i_w, int j_h, cv::Point3f point, cv::Vec3f colorBGR)\r\n{\r\n\tif(i_w>w || j_h>h)\r\n\t\treturn false;\r\n\r\n\tuchar num = numOfPointsForPixel.at<uchar>(j_h,i_w);\r\n\r\n\tif(num == 0)\r\n\t\treturn setPoint(i_w,j_h,point,colorBGR);\r\n\r\n\taddPoint(i_w,j_h,point);\r\n\r\n\tif(!color.empty())\r\n\t{\r\n\t\tcv::Vec3f c = Utilities::matGet3D(color,i_w,j_h);\r\n\r\n\t\tUtilities::matSet3D(color,i_w,j_h,colorBGR + c);\r\n\t}\r\n\telse\r\n\t{\r\n\t\treturn false;\r\n\t}\r\n\r\n\treturn true;\r\n}\r\n\r\nbool PointCloudImage::addPoint(int i_w, int j_h, cv::Point3f point)\r\n{\r\n\tif(i_w>w || j_h>h)\r\n\t\treturn false;\r\n\r\n\tuchar num = numOfPointsForPixel.at<uchar>(j_h,i_w);\r\n\r\n\tif(num == 0)\r\n\t\treturn setPoint(i_w,j_h,point);\r\n\r\n\tcv::Point3f p = Utilities::matGet3D(points,i_w,j_h);\r\n\tUtilities::matSet3D(points,i_w,j_h,(cv::Vec3f)(point + p));\r\n\r\n\tnumOfPointsForPixel.at<uchar>(j_h,i_w) = num + 1;\r\n\r\n\treturn true;\r\n}\r\n\r\n\r\n\r\nvoid PointCloudImage::exportXYZ(char path[], bool exportOffPixels, bool colorFlag)\r\n{\r\n\r\n\tstd::ofstream out; \r\n\tout.open(path);\r\n\r\n\tint load;\r\n\r\n\tcv::Point3f p;\r\n\tcv::Vec3f c;\r\n\r\n\tstd::cout<<\"Export \"<< path << \"...\";\r\n\r\n\tfor(int i = 0; i<w; i++)\r\n\t{\r\n\t\tfor(int j = 0; j<h; j++)\r\n\t\t{\r\n\t\t\tuchar num = numOfPointsForPixel.at<uchar>(j,i);\r\n\r\n\t\t\tif(!exportOffPixels && num == 0)\r\n\t\t\t\tcontinue;\t\t\t\r\n\t\t\t\r\n\t\t\tgetPoint(i,j,p,c);\r\n\r\n\t\t\tif(exportOffPixels && num == 0)\r\n\t\t\t{\r\n\t\t\t\tp = cv::Point3f(0,0,0);\r\n\t\t\t\tc = cv::Point3f(0,0,0);\r\n\t\t\t}\r\n\r\n\t\t\tout<<p.x<<\" \"<<p.y<<\" \"<<p.z;\r\n\r\n\t\t\tif(colorFlag && !color.empty())\r\n\t\t\t{\r\n\t\t\t\tout<<\" \"<<c[2]<<\" \"<<c[1]<<\" \"<<c[0]<<\"\\n\";\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\tout<<\"\\n\";\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\tout.close();\r\n\tstd::cout<<\"done\\n\";\r\n}\r\n\r\nvoid PointCloudImage::exportNumOfPointsPerPixelImg(char path[])\r\n{\r\n\t\r\n\tcv::Mat projToCamRays(cvSize(w, h), CV_8U);\r\n\r\n\tfloat max=0;\r\n\r\n\tint maxX,maxY;\r\n\r\n\tfor(int i=0; i<w; i++)\r\n\t{\r\n\t\tfor(int j=0; j<h; j++)\r\n\t\t{\r\n\t\t\tuchar num = numOfPointsForPixel.at<uchar>(j,i);\r\n\r\n\t\t\tif(num > max)\r\n\t\t\t{\r\n\t\t\t\tmax = num;\r\n\t\t\t\tmaxX=i;\r\n\t\t\t\tmaxY=j;\r\n\t\t\t}\r\n\t\t}\r\n\t} \r\n\r\n\tfor(int i=0; i<w; i++)\r\n\t{\r\n\t\tfor(int j=0; j<h; j++)\r\n\t\t{\r\n\r\n\t\t\tuchar num = numOfPointsForPixel.at<uchar>(j,i);\r\n\t\t\tUtilities::matSet2D(projToCamRays,i,j, num\/(float)(max*255.0));\r\n\r\n\t\t}\r\n\t}\r\n\r\n\tcv::imwrite(\"reconstruction\/projToCamRays.png\",projToCamRays);\r\n\r\n\tstd::ofstream out1;\r\n\tstd::stringstream txt;\r\n\ttxt<<path<<\".txt\";\r\n\tout1.open(txt.str().c_str() );\r\n\r\n\tout1<< \"black color = 0\\nwhite color = \"<< max <<\"\\nmax Pixel: (\"<<maxX<<\",\"<<maxY<<\")\";\r\n\r\n\tout1.close();\r\n\r\n}\r\n\r\nint PointCloudImage::getWidth()\r\n{\r\n\treturn w;\r\n}\r\n\r\nint PointCloudImage::getHeight()\r\n{\r\n\treturn h;\r\n}\r\n\r\n<commit_msg>Update PointCloudImage.cpp<commit_after>\/\/------------------------------------------------------------------------------------------------------------\r\n\/\/* Copyright © 2010-2015 Immersive and Creative Technologies Lab, Cyprus University of Technology *\r\n\/\/* Link: http:\/\/www.theICTlab.org *\r\n\/\/* Software developer(s): Kyriakos Herakleous *\r\n\/\/* Researcher(s): Kyriakos Herakleous, Charalambos Poullis *\r\n\/\/* *\r\n\/\/* License: Check the file License.md *\r\n\/\/------------------------------------------------------------------------------------------------------------\r\n\r\n#include \"StdAfx.h\"\r\n#include \"PointCloudImage.h\"\r\n\r\n\r\n\r\nPointCloudImage::PointCloudImage(int imageW,int imageH, bool colorFlag_)\r\n{\r\n\tw=imageW;\r\n\th=imageH;\r\n\tcolorFlag = colorFlag_;\r\n\t\r\n\tpoints = cv::Mat(h,w,CV_32FC3);\r\n\r\n\tif(colorFlag==true)\r\n\t{\r\n\t\t\r\n\t\tcolor = cv::Mat(h,w,CV_32FC3,cv::Scalar(0));\r\n\t}\r\n\telse\r\n\t\tcolor = NULL;\r\n\r\n\tnumOfPointsForPixel = cv::Mat(h,w,CV_8U,cv::Scalar(0));\r\n}\r\n\r\nPointCloudImage::~PointCloudImage(void)\r\n{\r\n\t\r\n}\r\n\r\nbool PointCloudImage::hasColor()\r\n{\r\n\treturn colorFlag;\r\n}\r\n\r\nbool PointCloudImage::setPoint(int i_w, int j_h, cv::Point3f point, cv::Vec3f colorBGR)\r\n{\r\n\tif(i_w>w || j_h>h)\r\n\t\treturn false;\r\n\r\n\tsetPoint(i_w,j_h,point);\r\n\r\n\tUtilities::matSet3D(color,i_w,j_h,colorBGR);\r\n\r\n\treturn true;\r\n}\r\n\r\nbool PointCloudImage::setPoint(int i_w, int j_h, cv::Point3f point)\r\n{\r\n\tif(i_w>w || j_h>h)\r\n\t\treturn false;\r\n\r\n\tUtilities::matSet3D(points,i_w,j_h,(cv::Vec3f)point);\r\n\tUtilities::matSet2D(numOfPointsForPixel,i_w,j_h,1);\r\n\r\n\treturn true;\r\n}\r\n\r\nbool PointCloudImage::getPoint(int i_w, int j_h, cv::Point3f &pointOut, cv::Vec3f &colorOut)\r\n{\r\n\tif(i_w>w || j_h>h)\r\n\t\treturn false;\r\n\r\n\tuchar num = numOfPointsForPixel.at<uchar>(j_h,i_w);\r\n\r\n\tif(num > 0)\r\n\t{\r\n\t\t\r\n\t\tpointOut = (cv::Point3f) (Utilities::matGet3D(points,i_w,j_h) \/ (float) num);\r\n\r\n\t\t\r\n\t\tif(!color.empty())\r\n\t\t{\r\n\t\t\tcolorOut = (cv::Point3f) (Utilities::matGet3D(color,i_w,j_h) \/ (float) num);\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\treturn false;\r\n\t\t}\r\n\t\t\r\n\r\n\t\treturn true;\r\n\t}\r\n\telse\r\n\t{\r\n\t\treturn false;\r\n\t}\r\n\t\r\n}\r\n\r\nbool PointCloudImage::getPoint(int i_w, int j_h, cv::Point3f &pointOut)\r\n{\r\n\tif(i_w>w || j_h>h)\r\n\t\treturn false;\r\n\r\n\tuchar num = numOfPointsForPixel.at<uchar>(j_h,i_w);\r\n\r\n\tif(num > 0)\r\n\t{\r\n\t\tpointOut = (cv::Point3f) (Utilities::matGet3D(points,i_w,j_h) \/ (float) num);\r\n\t\treturn true;\r\n\t}\r\n\telse\r\n\t{\r\n\t\treturn false;\r\n\t}\r\n\t\r\n}\r\n\r\nbool PointCloudImage::addPoint(int i_w, int j_h, cv::Point3f point, cv::Vec3f colorBGR)\r\n{\r\n\tif(i_w>w || j_h>h)\r\n\t\treturn false;\r\n\r\n\tuchar num = numOfPointsForPixel.at<uchar>(j_h,i_w);\r\n\r\n\tif(num == 0)\r\n\t\treturn setPoint(i_w,j_h,point,colorBGR);\r\n\r\n\taddPoint(i_w,j_h,point);\r\n\r\n\tif(!color.empty())\r\n\t{\r\n\t\tcv::Vec3f c = Utilities::matGet3D(color,i_w,j_h);\r\n\r\n\t\tUtilities::matSet3D(color,i_w,j_h,colorBGR + c);\r\n\t}\r\n\telse\r\n\t{\r\n\t\treturn false;\r\n\t}\r\n\r\n\treturn true;\r\n}\r\n\r\nbool PointCloudImage::addPoint(int i_w, int j_h, cv::Point3f point)\r\n{\r\n\tif(i_w>w || j_h>h)\r\n\t\treturn false;\r\n\r\n\tuchar num = numOfPointsForPixel.at<uchar>(j_h,i_w);\r\n\r\n\tif(num == 0)\r\n\t\treturn setPoint(i_w,j_h,point);\r\n\r\n\tcv::Point3f p = Utilities::matGet3D(points,i_w,j_h);\r\n\tUtilities::matSet3D(points,i_w,j_h,(cv::Vec3f)(point + p));\r\n\r\n\tnumOfPointsForPixel.at<uchar>(j_h,i_w) = num + 1;\r\n\r\n\treturn true;\r\n}\r\n\r\n\r\n\r\nvoid PointCloudImage::exportXYZ(char path[], bool exportOffPixels, bool colorFlag)\r\n{\r\n\r\n\tstd::ofstream out; \r\n\tout.open(path);\r\n\r\n\tint load;\r\n\r\n\tcv::Point3f p;\r\n\tcv::Vec3f c;\r\n\r\n\tstd::cout<<\"Export \"<< path << \"...\";\r\n\r\n\tfor(int i = 0; i<w; i++)\r\n\t{\r\n\t\tfor(int j = 0; j<h; j++)\r\n\t\t{\r\n\t\t\tuchar num = numOfPointsForPixel.at<uchar>(j,i);\r\n\r\n\t\t\tif(!exportOffPixels && num == 0)\r\n\t\t\t\tcontinue;\t\t\t\r\n\t\t\t\r\n\t\t\tgetPoint(i,j,p,c);\r\n\r\n\t\t\tif(exportOffPixels && num == 0)\r\n\t\t\t{\r\n\t\t\t\tp = cv::Point3f(0,0,0);\r\n\t\t\t\tc = cv::Point3f(0,0,0);\r\n\t\t\t}\r\n\r\n\t\t\tout<<p.x<<\" \"<<p.y<<\" \"<<p.z;\r\n\r\n\t\t\tif(colorFlag && !color.empty())\r\n\t\t\t{\r\n\t\t\t\tout<<\" \"<<c[2]<<\" \"<<c[1]<<\" \"<<c[0]<<\"\\n\";\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\tout<<\"\\n\";\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\tout.close();\r\n\tstd::cout<<\"done\\n\";\r\n}\r\n\r\nvoid PointCloudImage::exportNumOfPointsPerPixelImg(char path[])\r\n{\r\n\t\r\n\tcv::Mat projToCamRays(cvSize(w, h), CV_8U);\r\n\r\n\tfloat max=0;\r\n\r\n\tint maxX,maxY;\r\n\r\n\tfor(int i=0; i<w; i++)\r\n\t{\r\n\t\tfor(int j=0; j<h; j++)\r\n\t\t{\r\n\t\t\tuchar num = numOfPointsForPixel.at<uchar>(j,i);\r\n\r\n\t\t\tif(num > max)\r\n\t\t\t{\r\n\t\t\t\tmax = num;\r\n\t\t\t\tmaxX=i;\r\n\t\t\t\tmaxY=j;\r\n\t\t\t}\r\n\t\t}\r\n\t} \r\n\r\n\tfor(int i=0; i<w; i++)\r\n\t{\r\n\t\tfor(int j=0; j<h; j++)\r\n\t\t{\r\n\r\n\t\t\tuchar num = numOfPointsForPixel.at<uchar>(j,i);\r\n\t\t\tUtilities::matSet2D(projToCamRays,i,j, num\/(float)(max*255.0));\r\n\r\n\t\t}\r\n\t}\r\n\r\n\tcv::imwrite(\"reconstruction\/projToCamRays.png\",projToCamRays);\r\n\r\n\tstd::ofstream out1;\r\n\tstd::stringstream txt;\r\n\ttxt<<path<<\".txt\";\r\n\tout1.open(txt.str().c_str() );\r\n\r\n\tout1<< \"black color = 0\\nwhite color = \"<< max <<\"\\nmax Pixel: (\"<<maxX<<\",\"<<maxY<<\")\";\r\n\r\n\tout1.close();\r\n\r\n}\r\n\r\nint PointCloudImage::getWidth()\r\n{\r\n\treturn w;\r\n}\r\n\r\nint PointCloudImage::getHeight()\r\n{\r\n\treturn h;\r\n}\r\n\r\n<|endoftext|>"} {"text":"<commit_before>\/\/ C\/C++ File\n\/\/ AUTHOR: cxd\n\/\/ FILE: genW.cpp\n\/\/ ROLE: TODO (some explanation)\n\/\/ CREATED: 2014-06-30 14:05:48\n\/\/ MODIFIED: 2014-06-30 14:27:15\n\n#include <iostream>\n#include <random>\n\nusing namespace std;\n\nint main()\n{\n const int MAX = 50;\n\n for (int i = 0; i < MAX; ++i)\n {\n\tcout << 25.0 << endl;\n }\n\n for (int i = 0; i < MAX; ++i)\n {\n\tcout << double(i+1) << endl;\n }\n\n for (int i = MAX; i >=0; --i)\n {\n\tcout << double(i+1) << endl;\n }\n\n std::random_device rd;\n std::mt19937 gen(rd());\n std::uniform_real_distribution<> dis(1, MAX);\n for (int i = 0; i < MAX; ++i)\n {\n std::cout << dis(gen) << endl;\n }\n\n return 0;\n}\n\n<commit_msg>Fixed cut\/paste bug<commit_after>\/\/ C\/C++ File\n\/\/ AUTHOR: cxd\n\/\/ FILE: genW.cpp\n\/\/ ROLE: TODO (some explanation)\n\/\/ CREATED: 2014-06-30 14:05:48\n\/\/ MODIFIED: 2014-07-06 14:24:39\n\n#include <iostream>\n#include <random>\n\nusing namespace std;\n\nint main()\n{\n const int MAX = 50;\n\n for (int i = 0; i < MAX; ++i)\n {\n\tcout << 25.0 << endl;\n }\n\n for (int i = 0; i < MAX; ++i)\n {\n\tcout << double(i+1) << endl;\n }\n\n for (int i = MAX; i > 0; --i)\n {\n\tcout << double(i) << endl;\n }\n\n std::random_device rd;\n std::mt19937 gen(rd());\n std::uniform_real_distribution<> dis(1, MAX);\n for (int i = 0; i < MAX; ++i)\n {\n std::cout << dis(gen) << endl;\n }\n\n return 0;\n}\n\n<|endoftext|>"} {"text":"<commit_before>#pragma once\n\/\/=====================================================================\/\/\n\/*!\t@file\n\t@brief\tI\/O ユーティリティー @n\n\t\t\tCopyright 2013 Kunihito Hiramatsu\n\t@author\t平松邦仁 (hira@rvf-rc45.net)\n*\/\n\/\/=====================================================================\/\/\n#include <cstdint>\n\nnamespace device {\n\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\t\/*!\n\t\t@brief 8ビット書き込み\n\t\t@param[in]\tadr\t\t書き込みアドレス\n\t\t@param[in]\tdata\t書き込みデータ\n\t*\/\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\tstatic inline void wr8_(uint32_t adr, uint8_t data) {\n\t\t*reinterpret_cast<volatile uint8_t*>(adr) = data;\n\t}\n\n\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\t\/*!\n\t\t@brief 8ビット読み込み\n\t\t@param[in]\tadr\t\t読み込みアドレス\n\t\t@param[in]\tdata\t読み込みデータ\n\t*\/\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\tstatic inline uint8_t rd8_(uint32_t adr) {\n\t\treturn *reinterpret_cast<volatile uint8_t*>(adr);\n\t}\n\n\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\t\/*!\n\t\t@brief 16ビット書き込み\n\t\t@param[in]\tadr\t\t書き込みアドレス\n\t\t@param[in]\tdata\t書き込みデータ\n\t*\/\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\tstatic inline void wr16_(uint32_t adr, uint16_t data) {\n\t\t*reinterpret_cast<volatile uint16_t*>(adr) = data;\n\t}\n\n\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\t\/*!\n\t\t@brief 16ビット読み込み\n\t\t@param[in]\tadr\t\t読み込みアドレス\n\t\t@param[in]\tdata\t読み込みデータ\n\t*\/\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\tstatic inline uint16_t rd16_(uint32_t adr) {\n\t\treturn *reinterpret_cast<volatile uint16_t*>(adr);\n\t}\n\n\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\t\/*!\n\t\t@brief 32ビット書き込み\n\t\t@param[in]\tadr\t\t書き込みアドレス\n\t\t@param[in]\tdata\t書き込みデータ\n\t*\/\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\tstatic inline void wr32_(uint32_t adr, uint32_t data) {\n\t\t*reinterpret_cast<volatile uint32_t*>(adr) = data;\n\t}\n\n\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\t\/*!\n\t\t@brief 32ビット読み込み\n\t\t@param[in]\tadr\t\t読み込みアドレス\n\t\t@param[in]\tdata\t読み込みデータ\n\t*\/\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\tstatic inline uint32_t rd32_(uint32_t adr) {\n\t\treturn *reinterpret_cast<volatile uint32_t*>(adr);\n\t}\n\n\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\t\/*!\n\t\t@brief 8 bits アクセス・テンプレート\n\t\t@param[in]\tadr\tアドレス\n\t*\/\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\ttemplate <uint32_t adr>\n\tstruct io8 {\n\t\ttypedef uint8_t value_type;\n\n\t\tstatic void write(uint8_t data) { wr8_(adr, data); }\n\t\tstatic uint8_t read() { return rd8_(adr); }\n\n\t\tvoid operator = (value_type data) const { write(data); }\n\t\tvalue_type operator () () const { return read(); }\n\t\tvoid operator |= (value_type data) const { write(read() | data); }\n\t\tvoid operator &= (value_type data) const { write(read() & data); }\n\t};\n\n\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\t\/*!\n\t\t@brief 8 bits アクセス・テンプレート(RO)\n\t\t@param[in]\tadr\tアドレス\n\t*\/\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\ttemplate <uint32_t adr>\n\tstruct io8_ro {\n\t\ttypedef uint8_t value_type;\n\n\t\tstatic uint8_t read() { return rd8_(adr); }\n\n\t\tvalue_type operator () () const { return read(); }\n\t};\n\n\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\t\/*!\n\t\t@brief 16 bits アクセス・テンプレート\n\t\t@param[in]\tadr\tアドレス\n\t*\/\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\ttemplate <uint32_t adr>\n\tstruct io16 {\n\t\ttypedef uint16_t value_type;\n\n\t\tstatic void write(uint16_t data) { wr16_(adr, data); }\n\t\tstatic uint16_t read() { return rd16_(adr); }\n\n\t\tvoid operator = (value_type data) const { write(data); }\n\t\tvalue_type operator () () const { return read(); }\n\t\tvoid operator |= (value_type data) const { write(read() | data); }\n\t\tvoid operator &= (value_type data) const { write(read() & data); }\n\t};\n\n\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\t\/*!\n\t\t@brief 32 bits アクセス・テンプレート\n\t\t@param[in]\tadr\tアドレス\n\t*\/\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\ttemplate <uint32_t adr>\n\tstruct io32 {\n\t\ttypedef uint32_t\tvalue_type;\n\n\t\tstatic void write(uint32_t data) { wr32_(adr, data); }\n\t\tstatic uint32_t read() { return rd32_(adr); }\n\n\t\tvoid operator = (value_type data) const { write(data); }\n\t\tvalue_type operator () () const { return read(); }\n\t\tvoid operator |= (value_type data) const { write(read() | data); }\n\t\tvoid operator &= (value_type data) const { write(read() & data); }\n\t};\n\n\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\t\/*!\n\t\t@brief 1ビット・アクセス・テンプレート(R\/W direct)\n\t\t@param[in]\tT\tアクセス・クラス\n\t\t@param[in]\tpos\tビット位置\n\t*\/\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\ttemplate <class T, uint8_t pos>\n\tstruct bit {\n\t\tstatic bool get() {\n\t\t\treturn (T::read() & (1 << pos)) != 0;\n\t\t}\n\t\tstatic void set(bool v) {\n\t\t\tT::write(v << pos);\n\t\t}\n\n\t typename T::value_type b(bool f = true) const {\n\t\t\treturn f << pos;\n\t\t}\n\n\t\tvoid operator = (bool v) const { set(v); }\n\t\tbool operator () () const { return get(); }\n\t};\n\n\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\t\/*!\n\t\t@brief 1ビット・アクセス・テンプレート(R\/W)\n\t\t@param[in]\tT\tアクセス・クラス\n\t\t@param[in]\tpos\tビット位置\n\t*\/\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\ttemplate <class T, uint8_t pos>\n\tstruct bit_t {\n\t\tstatic bool get() {\n\t\t\treturn (T::read() & (1 << pos)) != 0;\n\t\t}\n\t\tstatic void set(bool v) {\n\t\t\tT::write((T::read() & ~(1 << pos)) | (v << pos));\n\t\t}\n\n\t typename T::value_type b(bool v = true) const {\n\t\t\treturn v << pos;\n\t\t}\n\n\t\tvoid operator = (bool v) const { set(v); }\n\t\tbool operator () () const { return get(); }\n\t};\n\n\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\t\/*!\n\t\t@brief ビット・アクセス・テンプレート(R\/W direct)\n\t\t@param[in]\tT\tアクセス・クラス\n\t\t@param[in]\tpos\t初期位置\n\t\t@param[in]\tlen\tビット幅\n\t*\/\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\ttemplate <class T, uint8_t pos, uint8_t len>\n\tstruct bits {\n\t\tstatic typename T::value_type get() {\n\t\t\treturn (T::read() >> pos) & ((1 << len) - 1);\n\t\t}\n\t\tstatic void set(typename T::value_type v) {\n\t\t\tT::write(v << pos);\n\t\t}\n\n\t typename T::value_type b(typename T::value_type v) const { return v << pos; }\n\n\t\tvoid operator = (typename T::value_type v) const { set(v); }\n\t\ttypename T::value_type operator () () const { return get(); }\n\t};\n\n\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\t\/*!\n\t\t@brief ビット・アクセス・テンプレート(R\/W)\n\t\t@param[in]\tT\tアクセス・クラス\n\t\t@param[in]\tpos\t初期位置\n\t\t@param[in]\tlen\tビット幅\n\t*\/\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\ttemplate <class T, uint8_t pos, uint8_t len>\n\tstruct bits_t {\n\t\tstatic typename T::value_type get() {\n\t\t\treturn (T::read() >> pos) & ((1 << len) - 1);\n\t\t}\n\t\tstatic void set(typename T::value_type v) {\n\t\t\ttypename T::value_type m = ((1 << static_cast<typename T::value_type>(len)) - 1) << pos;\n\t\t\tT::write((T::read() & ~m) | (v << pos));\n\t\t}\n\n\t typename T::value_type b(typename T::value_type v) const { return v << pos; }\n\n\t\tvoid operator = (typename T::value_type v) const { set(v); }\n\t\ttypename T::value_type operator () () const { return get(); }\n\t};\n\n\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\t\/*!\n\t\t@brief 1ビット・アクセス・テンプレート(RO)\n\t\t@param[in]\tT\tアクセス・クラス\n\t\t@param[in]\tpos\tビット位置\n\t*\/\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\ttemplate <class T, uint8_t pos>\n\tstruct bit_ro_t {\n\t\tstatic bool get() {\n\t\t\treturn T::read() & (1 << pos);\n\t\t}\n\n\t\tbool operator () () const { return get(); }\n\t};\n\n\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\t\/*!\n\t\t@brief ビット・アクセス・テンプレート(RO)\n\t\t@param[in]\tT\tアクセス・クラス\n\t\t@param[in]\tpos\t初期位置\n\t\t@param[in]\tlen\tビット幅\n\t*\/\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\ttemplate <class T, uint8_t pos, uint8_t len>\n\tstruct bits_ro_t {\n\t\tstatic typename T::value_type get() {\n\t\t\treturn (T::read() >> pos) & ((1 << len) - 1);\n\t\t}\n\t\ttypename T::value_type operator () () const { return get(); }\n\t};\n}\n<commit_msg>update I\/O template<commit_after>#pragma once\n\/\/=====================================================================\/\/\n\/*!\t@file\n\t@brief\tI\/O ユーティリティー @n\n\t\t\tCopyright 2013,2016 Kunihito Hiramatsu\n\t@author\t平松邦仁 (hira@rvf-rc45.net)\n*\/\n\/\/=====================================================================\/\/\n#include <cstdint>\n\nnamespace device {\n\n\ttypedef uint32_t address_type;\n\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\t\/*!\n\t\t@brief 8ビット書き込み\n\t\t@param[in]\tadr\t\t書き込みアドレス\n\t\t@param[in]\tdata\t書き込みデータ\n\t*\/\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\tstatic inline void wr8_(address_type adr, uint8_t data) {\n\t\t*reinterpret_cast<volatile uint8_t*>(adr) = data;\n\t}\n\n\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\t\/*!\n\t\t@brief 8ビット読み込み\n\t\t@param[in]\tadr\t\t読み込みアドレス\n\t\t@param[in]\tdata\t読み込みデータ\n\t*\/\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\tstatic inline uint8_t rd8_(address_type adr) {\n\t\treturn *reinterpret_cast<volatile uint8_t*>(adr);\n\t}\n\n\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\t\/*!\n\t\t@brief 16ビット書き込み\n\t\t@param[in]\tadr\t\t書き込みアドレス\n\t\t@param[in]\tdata\t書き込みデータ\n\t*\/\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\tstatic inline void wr16_(address_type adr, uint16_t data) {\n\t\t*reinterpret_cast<volatile uint16_t*>(adr) = data;\n\t}\n\n\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\t\/*!\n\t\t@brief 16ビット読み込み\n\t\t@param[in]\tadr\t\t読み込みアドレス\n\t\t@param[in]\tdata\t読み込みデータ\n\t*\/\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\tstatic inline uint16_t rd16_(address_type adr) {\n\t\treturn *reinterpret_cast<volatile uint16_t*>(adr);\n\t}\n\n\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\t\/*!\n\t\t@brief 32ビット書き込み\n\t\t@param[in]\tadr\t\t書き込みアドレス\n\t\t@param[in]\tdata\t書き込みデータ\n\t*\/\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\tstatic inline void wr32_(address_type adr, uint32_t data) {\n\t\t*reinterpret_cast<volatile uint32_t*>(adr) = data;\n\t}\n\n\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\t\/*!\n\t\t@brief 32ビット読み込み\n\t\t@param[in]\tadr\t\t読み込みアドレス\n\t\t@param[in]\tdata\t読み込みデータ\n\t*\/\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\tstatic inline uint32_t rd32_(address_type adr) {\n\t\treturn *reinterpret_cast<volatile uint32_t*>(adr);\n\t}\n\n\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\t\/*!\n\t\t@brief Read\/Write 8 bits アクセス・テンプレート\n\t\t@param[in]\tadr\tアドレス\n\t*\/\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\ttemplate <address_type adr>\n\tstruct rw8_t {\n\t\ttypedef uint8_t value_type;\n\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\t\/*!\n\t\t\t@brief 書き込み\n\t\t\t@param[in]\tdata\t書き込み値\n\t\t*\/\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\tstatic void write(value_type data) { wr8_(adr, data); }\n\n\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\t\/*!\n\t\t\t@brief 読み出し\n\t\t\t@return 読み出し値\n\t\t*\/\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\tstatic value_type read() { return rd8_(adr); }\n\n\t\tvoid operator = (value_type data) const { write(data); }\n\t\tvalue_type operator () () const { return read(); }\n\t\tvoid operator |= (value_type data) const { write(read() | data); }\n\t\tvoid operator &= (value_type data) const { write(read() & data); }\n\t};\n\n\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\t\/*!\n\t\t@brief Read Only 8 bits アクセス・テンプレート\n\t\t@param[in]\tadr\tアドレス\n\t*\/\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\ttemplate <address_type adr>\n\tstruct ro8_t {\n\t\ttypedef uint8_t value_type;\n\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\t\/*!\n\t\t\t@brief 読み出し\n\t\t\t@return 読み出し値\n\t\t*\/\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\tstatic value_type read() { return rd8_(adr); }\n\n\t\tvalue_type operator () () const { return read(); }\n\t};\n\n\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\t\/*!\n\t\t@brief Write Only 8 bits アクセス・テンプレート\n\t\t@param[in]\tadr\tアドレス\n\t*\/\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\ttemplate <address_type adr>\n\tstruct wo8_t {\n\t\ttypedef uint8_t value_type;\n\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\t\/*!\n\t\t\t@brief 書き込み\n\t\t\t@param[in]\tdata\t書き込み値\n\t\t*\/\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\tstatic void write(value_type data) { wr8_(adr, data); }\n\n\t\tvoid operator = (value_type data) const { write(data); }\n\t};\n\n\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\t\/*!\n\t\t@brief Read\/Write 16 bits アクセス・テンプレート\n\t\t@param[in]\tadr\tアドレス\n\t*\/\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\ttemplate <address_type adr>\n\tstruct rw16_t {\n\t\ttypedef uint16_t value_type;\n\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\t\/*!\n\t\t\t@brief 書き込み\n\t\t\t@param[in]\tdata\t書き込み値\n\t\t*\/\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\tstatic void write(value_type data) { wr16_(adr, data); }\n\n\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\t\/*!\n\t\t\t@brief 読み出し\n\t\t\t@return 読み出し値\n\t\t*\/\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\tstatic value_type read() { return rd16_(adr); }\n\n\t\tvoid operator = (value_type data) const { write(data); }\n\t\tvalue_type operator () () const { return read(); }\n\t\tvoid operator |= (value_type data) const { write(read() | data); }\n\t\tvoid operator &= (value_type data) const { write(read() & data); }\n\t};\n\n\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\t\/*!\n\t\t@brief Read Only 16 bits アクセス・テンプレート\n\t\t@param[in]\tadr\tアドレス\n\t*\/\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\ttemplate <address_type adr>\n\tstruct ro16_t {\n\t\ttypedef uint16_t value_type;\n\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\t\/*!\n\t\t\t@brief 読み出し\n\t\t\t@return 読み出し値\n\t\t*\/\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\tstatic value_type read() { return rd16_(adr); }\n\n\t\tvalue_type operator () () const { return read(); }\n\t};\n\n\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\t\/*!\n\t\t@brief Write Only 16 bits アクセス・テンプレート\n\t\t@param[in]\tadr\tアドレス\n\t*\/\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\ttemplate <address_type adr>\n\tstruct wo16_t {\n\t\ttypedef uint16_t value_type;\n\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\t\/*!\n\t\t\t@brief 書き込み\n\t\t\t@param[in]\tdata\t書き込み値\n\t\t*\/\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\tstatic void write(value_type data) { wr16_(adr, data); }\n\n\t\tvoid operator = (value_type data) const { write(data); }\n\t};\n\n\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\t\/*!\n\t\t@brief Read\/Write 32 bits アクセス・テンプレート\n\t\t@param[in]\tadr\tアドレス\n\t*\/\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\ttemplate <address_type adr>\n\tstruct rw32_t {\n\t\ttypedef uint32_t value_type;\n\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\t\/*!\n\t\t\t@brief 書き込み\n\t\t\t@param[in]\tdata\t書き込み値\n\t\t*\/\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\tstatic void write(value_type data) { wr32_(adr, data); }\n\n\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\t\/*!\n\t\t\t@brief 読み出し\n\t\t\t@return 読み出し値\n\t\t*\/\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\tstatic value_type read() { return rd32_(adr); }\n\n\t\tvoid operator = (value_type data) const { write(data); }\n\t\tvalue_type operator () () const { return read(); }\n\t\tvoid operator |= (value_type data) const { write(read() | data); }\n\t\tvoid operator &= (value_type data) const { write(read() & data); }\n\t};\n\n\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\t\/*!\n\t\t@brief Read Only 32 bits アクセス・テンプレート\n\t\t@param[in]\tadr\tアドレス\n\t*\/\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\ttemplate <address_type adr>\n\tstruct ro32_t {\n\t\ttypedef uint32_t value_type;\n\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\t\/*!\n\t\t\t@brief 読み出し\n\t\t\t@return 読み出し値\n\t\t*\/\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\tstatic value_type read() { return rd32_(adr); }\n\n\t\tvalue_type operator () () const { return read(); }\n\t};\n\n\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\t\/*!\n\t\t@brief Write Only 32 bits アクセス・テンプレート\n\t\t@param[in]\tadr\tアドレス\n\t*\/\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\ttemplate <address_type adr>\n\tstruct wo32_t {\n\t\ttypedef uint32_t value_type;\n\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\t\/*!\n\t\t\t@brief 書き込み\n\t\t\t@param[in]\tdata\t書き込み値\n\t\t*\/\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\tstatic void write(value_type data) { wr32_(adr, data); }\n\n\t\tvoid operator = (value_type data) const { write(data); }\n\t};\n\n\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\t\/*!\n\t\t@brief ビット位置定義\n\t*\/\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\tenum class bitpos : uint8_t {\n\t\tB0,\t\t\/\/\/< ビット0\n\t\tB1,\t\t\/\/\/< ビット1\n\t\tB2,\t\t\/\/\/< ビット2\n\t\tB3,\t\t\/\/\/< ビット3\n\t\tB4,\t\t\/\/\/< ビット4\n\t\tB5,\t\t\/\/\/< ビット5\n\t\tB6,\t\t\/\/\/< ビット6\n\t\tB7,\t\t\/\/\/< ビット7\n\t\tB8,\t\t\/\/\/< ビット8\n\t\tB9,\t\t\/\/\/< ビット9\n\t\tB10,\t\/\/\/< ビット10\n\t\tB11,\t\/\/\/< ビット11\n\t\tB12,\t\/\/\/< ビット12\n\t\tB13,\t\/\/\/< ビット13\n\t\tB14,\t\/\/\/< ビット14\n\t\tB15,\t\/\/\/< ビット15\n\t\tB16,\t\/\/\/< ビット16\n\t\tB17,\t\/\/\/< ビット17\n\t\tB18,\t\/\/\/< ビット18\n\t\tB19,\t\/\/\/< ビット19\n\t\tB20,\t\/\/\/< ビット20\n\t\tB21,\t\/\/\/< ビット21\n\t\tB22,\t\/\/\/< ビット22\n\t\tB23,\t\/\/\/< ビット23\n\t\tB24,\t\/\/\/< ビット24\n\t\tB25,\t\/\/\/< ビット25\n\t\tB26,\t\/\/\/< ビット26\n\t\tB27,\t\/\/\/< ビット27\n\t\tB28,\t\/\/\/< ビット28\n\t\tB29,\t\/\/\/< ビット29\n\t\tB30,\t\/\/\/< ビット30\n\t\tB31,\t\/\/\/< ビット31\n\t};\n\n\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\t\/*!\n\t\t@brief Read\/Write ビット・アクセス・テンプレート\n\t\t@param[in]\tT\tアクセス・クラス\n\t\t@param[in]\tpos\tビット位置\n\t*\/\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\ttemplate <class T, bitpos pos>\n\tstruct bit_rw_t {\n\t\tstatic bool get() {\n\t\t\treturn (T::read() >> static_cast<typename T::value_type>(pos)) & 1;\n\t\t}\n\t\tstatic void set(bool v) {\n\t\t\tif(v) {\n\t\t\t\tT::write(T::read() | (1 << static_cast<typename T::value_type>(pos)));\n\t\t\t} else {\n\t\t\t\tT::write(T::read() & ~(1 << static_cast<typename T::value_type>(pos)));\n\t\t\t}\n\t\t}\n\n\t typename T::value_type b() const {\n\t\t\treturn 1 << static_cast<typename T::value_type>(pos);\n\t\t}\n\n\t\tvoid operator = (bool v) { set(v); }\n\t\tbool operator () () { return get(); }\n\t};\n\n\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\t\/*!\n\t\t@brief Read\/Write ビット・アクセス・テンプレート\n\t\t@param[in]\tT\tアクセス・クラス\n\t\t@param[in]\tpos\t初期ビット位置\n\t\t@param[in]\tlen\tビット幅\n\t*\/\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\ttemplate <class T, bitpos pos, uint8_t len>\n\tstruct bits_rw_t {\n\t\tstatic typename T::value_type get() {\n\t\t\treturn (T::read() >> static_cast<typename T::value_type>(pos)) & ((1 << len) - 1);\n\t\t}\n\t\tstatic void set(typename T::value_type v) {\n\t\t\tauto m = static_cast<typename T::value_type>(((1 << len) - 1) << static_cast<typename T::value_type>(pos));\n\t\t\tT::write((T::read() & ~m) | (static_cast<typename T::value_type>(v) << static_cast<typename T::value_type>(pos)));\n\t\t}\n\n\t typename T::value_type b(typename T::value_type v) const {\n\t\t\treturn (((1 << len) - 1) & v) << static_cast<typename T::value_type>(pos);\n\t\t}\n\n\t\tvoid operator = (typename T::value_type v) const { set(v); }\n\t\ttypename T::value_type operator () () const { return get(); }\n\t};\n\n\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\t\/*!\n\t\t@brief Read ビット・アクセス・テンプレート\n\t\t@param[in]\tT\tアクセス・クラス\n\t\t@param[in]\tpos\tビット位置\n\t\t@param[in]\tlen\tビット幅\n\t*\/\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\ttemplate <class T, bitpos pos>\n\tstruct bit_ro_t {\n\t\tstatic bool get() {\n\t\t\treturn (T::read() >> static_cast<typename T::value_type>(pos)) & 1;\n\t\t}\n\n\t typename T::value_type b() const {\n\t\t\treturn 1 << static_cast<typename T::value_type>(pos);\n\t\t}\n\n\t\tbool operator () () const { return get(); }\n\t};\n\n\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\t\/*!\n\t\t@brief 標準 Read\/Write アクセス・テンプレート\n\t\t@param[in]\tT\tアクセステンプレート\n\t*\/\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\ttemplate <class T>\n\tstruct basic_rw_t : public T {\n\n\t\tusing T::operator =;\n\t\tusing T::operator ();\n\t\tusing T::operator |=;\n\t\tusing T::operator &=;\n\n\t\tbit_rw_t<T, bitpos::B7> B7;\t\/\/\/< B7 アクセス\n\t\tbit_rw_t<T, bitpos::B6> B6;\t\/\/\/< B6 アクセス\n\t\tbit_rw_t<T, bitpos::B5> B5;\t\/\/\/< B5 アクセス\n\t\tbit_rw_t<T, bitpos::B4> B4;\t\/\/\/< B4 アクセス\n\t\tbit_rw_t<T, bitpos::B3> B3;\t\/\/\/< B3 アクセス\n\t\tbit_rw_t<T, bitpos::B2> B2;\t\/\/\/< B2 アクセス\n\t\tbit_rw_t<T, bitpos::B1> B1;\t\/\/\/< B1 アクセス\n\t\tbit_rw_t<T, bitpos::B0> B0;\t\/\/\/< B0 アクセス\n\t};\n\n\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\t\/*!\n\t\t@brief 標準 Read アクセス・テンプレート\n\t\t@param[in]\tT\tアクセステンプレート\n\t*\/\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\ttemplate <class T>\n\tstruct basic_ro_t : public T {\n\n\t\tusing T::operator =;\n\t\tusing T::operator ();\n\t\tusing T::operator |=;\n\t\tusing T::operator &=;\n\n\t\tbit_ro_t<T, bitpos::B7> B7;\t\/\/\/< B7 アクセス\n\t\tbit_ro_t<T, bitpos::B6> B6;\t\/\/\/< B6 アクセス\n\t\tbit_ro_t<T, bitpos::B5> B5;\t\/\/\/< B5 アクセス\n\t\tbit_ro_t<T, bitpos::B4> B4;\t\/\/\/< B4 アクセス\n\t\tbit_ro_t<T, bitpos::B3> B3;\t\/\/\/< B3 アクセス\n\t\tbit_ro_t<T, bitpos::B2> B2;\t\/\/\/< B2 アクセス\n\t\tbit_ro_t<T, bitpos::B1> B1;\t\/\/\/< B1 アクセス\n\t\tbit_ro_t<T, bitpos::B0> B0;\t\/\/\/< B0 アクセス\n\t};\n}\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: ring.hxx,v $\n *\n * $Revision: 1.2 $\n *\n * last change: $Author: rt $ $Date: 2005-09-09 02:07:20 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n#ifndef _RING_HXX\n#define _RING_HXX\n\nclass Ring\n{\n Ring *pNext;\n Ring* pPrev; \/\/ zur Optimierung, damit das ein\/ausketten schneller geht!\n\nprotected:\n Ring() { pNext = this; pPrev = this; }\n Ring( Ring * );\npublic:\n virtual ~Ring();\n void MoveTo( Ring *pDestRing );\n void MoveRingTo( Ring *pDestRing );\n\n Ring* GetNext() const { return pNext; }\n Ring* GetPrev() const { return pPrev; }\n};\n\n\n#endif\n<commit_msg>INTEGRATION: CWS swcolsel (1.2.708); FILE MERGED 2007\/04\/13 13:06:03 ama 1.2.708.1: Fix #1596#: Rectangular selection<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: ring.hxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: ihi $ $Date: 2007-11-22 15:28:11 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n#ifndef _RING_HXX\n#define _RING_HXX\n\n#include <swtypes.hxx>\n\nclass Ring\n{\n Ring *pNext;\n Ring* pPrev; \/\/ zur Optimierung, damit das ein\/ausketten schneller geht!\n\nprotected:\n Ring() { pNext = this; pPrev = this; }\n Ring( Ring * );\npublic:\n virtual ~Ring();\n void MoveTo( Ring *pDestRing );\n void MoveRingTo( Ring *pDestRing );\n\n Ring* GetNext() const { return pNext; }\n Ring* GetPrev() const { return pPrev; }\n\n sal_uInt32 numberOf() const;\n};\n\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/\/******************************************************************************************************\r\n\/\/ SignalIndexCache.cpp - Gbtc\r\n\/\/\r\n\/\/ Copyright 2010, Grid Protection Alliance. All Rights Reserved.\r\n\/\/\r\n\/\/ Licensed to the Grid Protection Alliance (GPA) under one or more contributor license agreements. See\r\n\/\/ the NOTICE file distributed with this work for additional information regarding copyright ownership.\r\n\/\/ The GPA licenses this file to you under the Eclipse Public License -v 1.0 (the \"License\"); you may\r\n\/\/ not use this file except in compliance with the License. You may obtain a copy of the License at:\r\n\/\/\r\n\/\/ http:\/\/www.opensource.org\/licenses\/eclipse-1.0.php\r\n\/\/\r\n\/\/ Unless agreed to in writing, the subject software distributed under the License is distributed on an\r\n\/\/ \"AS-IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. Refer to the\r\n\/\/ License for the specific language governing permissions and limitations.\r\n\/\/\r\n\/\/ Code Modification History:\r\n\/\/ ----------------------------------------------------------------------------------------------------\r\n\/\/ 03\/09\/2012 - Stephen C. Wills\r\n\/\/ Generated original version of source code.\r\n\/\/\r\n\/\/******************************************************************************************************\r\n\r\n#include \"SignalIndexCache.h\"\r\n\r\nnamespace tsf = TimeSeriesFramework;\r\n\r\n\/\/ Adds a measurement key to the cache.\r\nvoid tsf::Transport::SignalIndexCache::AddMeasurementKey(\r\n\tuint16_t signalIndex,\r\n\ttsf::Guid signalID,\r\n\tstd::string source,\r\n\tuint32_t id)\r\n{\r\n\tstd::size_t vectorIndex = m_signalIDList.size();\r\n\r\n\tm_reference[signalIndex] = vectorIndex;\r\n\tm_signalIDList.push_back(signalID);\r\n\tm_sourceList.push_back(source);\r\n\tm_idList.push_back(id);\r\n\r\n\tm_signalIDCache[signalID] = signalIndex;\r\n}\r\n\r\n\/\/ Empties the cache.\r\nvoid tsf::Transport::SignalIndexCache::Clear()\r\n{\r\n\tm_reference.clear();\r\n\tm_signalIDList.clear();\r\n\tm_sourceList.clear();\r\n\tm_idList.clear();\r\n\r\n\tm_signalIDCache.clear();\r\n}\r\n\r\n\/\/ Gets the globally unique signal ID associated with the given 16-bit runtime ID.\r\ntsf::Guid tsf::Transport::SignalIndexCache::GetSignalID(uint16_t signalIndex) const\r\n{\r\n\tstd::size_t vectorIndex = m_reference.find(signalIndex)->second;\r\n\treturn m_signalIDList[vectorIndex];\r\n}\r\n\r\n\/\/ Gets the first half of the human-readable measurement\r\n\/\/ key associated with the given 16-bit runtime ID.\r\nstd::string tsf::Transport::SignalIndexCache::GetSource(uint16_t signalIndex) const\r\n{\r\n\tstd::size_t vectorIndex = m_reference.find(signalIndex)->second;\r\n\treturn m_sourceList[vectorIndex];\r\n}\r\n\r\n\/\/ Gets the second half of the human-readable measurement\r\n\/\/ key associated with the given 16-bit runtime ID.\r\nuint32_t tsf::Transport::SignalIndexCache::GetID(uint16_t signalIndex) const\r\n{\r\n\tstd::size_t vectorIndex = m_reference.find(signalIndex)->second;\r\n\treturn m_idList[vectorIndex];\r\n}\r\n\r\n\/\/ Gets the globally unique signal ID as well as the human-readable\r\n\/\/ measurement key associated with the given 16-bit runtime ID.\r\nvoid tsf::Transport::SignalIndexCache::GetMeasurementKey(\r\n\tuint16_t signalIndex,\r\n\ttsf::Guid& signalID,\r\n\tstd::string& source,\r\n\tuint32_t& id) const\r\n{\r\n\tstd::size_t vectorIndex = m_reference.find(signalIndex)->second;\r\n\r\n\tsignalID = m_signalIDList[vectorIndex];\r\n\tsource = m_sourceList[vectorIndex];\r\n\tid = m_idList[vectorIndex];\r\n}\r\n\r\n\/\/ Gets the 16-bit runtime ID associated with the given globally unique signal ID.\r\nunsigned short TimeSeriesFramework::Transport::SignalIndexCache::GetSignalIndex(tsf::Guid signalID) const\r\n{\r\n\tstd::map<tsf::Guid, uint16_t>::iterator it;\r\n\tuint16_t signalIndex = 0xFFFF;\r\n\r\n\tit = m_signalIDCache.find(signalID);\r\n\r\n\tif(it != m_signalIDCache.end())\r\n\t\tsignalIndex = it->second;\r\n\r\n\treturn signalIndex;\r\n}<commit_msg>TSFPlatformLibrary: Modified type of iterator to const_iterator in SignalIndexCache::GetSignalIndex.<commit_after>\/\/******************************************************************************************************\r\n\/\/ SignalIndexCache.cpp - Gbtc\r\n\/\/\r\n\/\/ Copyright 2010, Grid Protection Alliance. All Rights Reserved.\r\n\/\/\r\n\/\/ Licensed to the Grid Protection Alliance (GPA) under one or more contributor license agreements. See\r\n\/\/ the NOTICE file distributed with this work for additional information regarding copyright ownership.\r\n\/\/ The GPA licenses this file to you under the Eclipse Public License -v 1.0 (the \"License\"); you may\r\n\/\/ not use this file except in compliance with the License. You may obtain a copy of the License at:\r\n\/\/\r\n\/\/ http:\/\/www.opensource.org\/licenses\/eclipse-1.0.php\r\n\/\/\r\n\/\/ Unless agreed to in writing, the subject software distributed under the License is distributed on an\r\n\/\/ \"AS-IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. Refer to the\r\n\/\/ License for the specific language governing permissions and limitations.\r\n\/\/\r\n\/\/ Code Modification History:\r\n\/\/ ----------------------------------------------------------------------------------------------------\r\n\/\/ 03\/09\/2012 - Stephen C. Wills\r\n\/\/ Generated original version of source code.\r\n\/\/\r\n\/\/******************************************************************************************************\r\n\r\n#include \"SignalIndexCache.h\"\r\n\r\nnamespace tsf = TimeSeriesFramework;\r\n\r\n\/\/ Adds a measurement key to the cache.\r\nvoid tsf::Transport::SignalIndexCache::AddMeasurementKey(\r\n\tuint16_t signalIndex,\r\n\ttsf::Guid signalID,\r\n\tstd::string source,\r\n\tuint32_t id)\r\n{\r\n\tstd::size_t vectorIndex = m_signalIDList.size();\r\n\r\n\tm_reference[signalIndex] = vectorIndex;\r\n\tm_signalIDList.push_back(signalID);\r\n\tm_sourceList.push_back(source);\r\n\tm_idList.push_back(id);\r\n\r\n\tm_signalIDCache[signalID] = signalIndex;\r\n}\r\n\r\n\/\/ Empties the cache.\r\nvoid tsf::Transport::SignalIndexCache::Clear()\r\n{\r\n\tm_reference.clear();\r\n\tm_signalIDList.clear();\r\n\tm_sourceList.clear();\r\n\tm_idList.clear();\r\n\r\n\tm_signalIDCache.clear();\r\n}\r\n\r\n\/\/ Gets the globally unique signal ID associated with the given 16-bit runtime ID.\r\ntsf::Guid tsf::Transport::SignalIndexCache::GetSignalID(uint16_t signalIndex) const\r\n{\r\n\tstd::size_t vectorIndex = m_reference.find(signalIndex)->second;\r\n\treturn m_signalIDList[vectorIndex];\r\n}\r\n\r\n\/\/ Gets the first half of the human-readable measurement\r\n\/\/ key associated with the given 16-bit runtime ID.\r\nstd::string tsf::Transport::SignalIndexCache::GetSource(uint16_t signalIndex) const\r\n{\r\n\tstd::size_t vectorIndex = m_reference.find(signalIndex)->second;\r\n\treturn m_sourceList[vectorIndex];\r\n}\r\n\r\n\/\/ Gets the second half of the human-readable measurement\r\n\/\/ key associated with the given 16-bit runtime ID.\r\nuint32_t tsf::Transport::SignalIndexCache::GetID(uint16_t signalIndex) const\r\n{\r\n\tstd::size_t vectorIndex = m_reference.find(signalIndex)->second;\r\n\treturn m_idList[vectorIndex];\r\n}\r\n\r\n\/\/ Gets the globally unique signal ID as well as the human-readable\r\n\/\/ measurement key associated with the given 16-bit runtime ID.\r\nvoid tsf::Transport::SignalIndexCache::GetMeasurementKey(\r\n\tuint16_t signalIndex,\r\n\ttsf::Guid& signalID,\r\n\tstd::string& source,\r\n\tuint32_t& id) const\r\n{\r\n\tstd::size_t vectorIndex = m_reference.find(signalIndex)->second;\r\n\r\n\tsignalID = m_signalIDList[vectorIndex];\r\n\tsource = m_sourceList[vectorIndex];\r\n\tid = m_idList[vectorIndex];\r\n}\r\n\r\n\/\/ Gets the 16-bit runtime ID associated with the given globally unique signal ID.\r\nunsigned short TimeSeriesFramework::Transport::SignalIndexCache::GetSignalIndex(tsf::Guid signalID) const\r\n{\r\n\tstd::map<tsf::Guid, uint16_t>::const_iterator it;\r\n\tuint16_t signalIndex = 0xFFFF;\r\n\r\n\tit = m_signalIDCache.find(signalID);\r\n\r\n\tif(it != m_signalIDCache.end())\r\n\t\tsignalIndex = it->second;\r\n\r\n\treturn signalIndex;\r\n}<|endoftext|>"} {"text":"<commit_before>#pragma once\n\n#include <array>\n#include <cstddef>\n#include <cstdint>\n\nclass CallbackQueue\n{\nprivate:\n using u8 = std::uint8_t;\n using u32 = std::uint32_t;\n u32 mFlags = 0u;\n\npublic:\n bool Empty() const { return mFlags == 0u; }\n \n u8 Size() const { return __builtin_popcount(mFlags); }\n \n void Push(u8 x)\n {\n assert(x < 27u);\n mFlags |= 1u << x;\n }\n\n void PushFlags(u32 flags) { mFlags |= flags; }\n \n u8 Pop()\n {\n if (Empty())\n return u8(255);\n\n u8 ret = __builtin_ctz(mFlags);\n PopElement(ret);\n \n return ret;\n }\n\n void PopElement(u8 element)\n {\n mFlags &= ~(1u << element);\n }\n};\n<commit_msg>CallbackQueue now 128 bits instead of 32 bits in preparation for cell-based processing instead of group-based processing.<commit_after>#pragma once\n\n#include <array>\n#include <cstddef>\n#include <cstdint>\n\nclass CallbackQueue\n{\nprivate:\n using u8 = std::uint8_t;\n using u64 = std::uint64_t;\n std::array<u64, 2> mFlags = {{0u, 0u}};\n\npublic:\n bool Empty() const { return mFlags[0] == 0u && mFlags[1] == 0u; }\n \n u8 Size() const { return __builtin_popcountll(mFlags[0]) + __builtin_popcountll(mFlags[1]); }\n \n void Push(u8 x)\n {\n assert(x < 81u);\n bool first = x < 64u;\n u64 bit = 1u << (x % 64u);\n mFlags[0] |= first * bit;\n mFlags[1] |= !first * bit;\n }\n\n void PushFlags(std::array<u64, 2> flags) { mFlags[0] |= flags[0]; mFlags[1] |= flags[1]; }\n void PushFlags(u64 flags) { mFlags[0] |= flags; } \/\/ TODO: remove\n \n u8 Pop()\n {\n if (mFlags[0] != 0u)\n {\n u8 ret = __builtin_ctzll(mFlags[0]);\n mFlags[0] &= ~(1u << ret);\n return u8(ret);\n }\n else if (mFlags[1] != 0u)\n {\n u8 ret = __builtin_ctzll(mFlags[1]);\n mFlags[1] &= ~(1u << ret);\n return u8(64u + ret);\n }\n\n return u8(255);\n }\n\n void PopElement(u8 element)\n {\n if (element < 64u)\n {\n mFlags[0] &= ~(1u << element);\n }\n else\n {\n element -= 64u;\n mFlags[1] &= ~(1u << element);\n }\n }\n};\n<|endoftext|>"} {"text":"<commit_before>\/*\n * template.cpp\n *\n * Just some boilerplate stuff to use for each file.\n *\/\n\n#include <iostream>\n#include <complex>\nusing namespace std;\n\nstruct Vector {\n int size;\n double *elem;\n};\n\nvoid vector_init(Vector & v, int s)\n{\n v.elem = new double[s];\n v.size = s;\n}\n\n\/* Fill values in a Vector. Assume an already initialized vector is passed in *\/\nvoid read_vector(Vector & v)\n{\n cout << \"Please give me \" << v.size << \" floating point numbers.\\n\";\n\n for (auto i=0; i!=v.size; ++i)\n cin >> v.elem[i];\n}\n\n\/* Sum values in a Vector. *\/\ndouble sum_vector(Vector & v)\n{\n double sum = 0;\n for (auto i=0; i!=v.size; ++i)\n sum += v.elem[i];\n \n return sum;\n}\n\nint main()\n{\n int num_vals;\n\n cout << \"How many elements in the vector? \";\n cin >> num_vals;\n\n Vector v;\n vector_init(v, num_vals);\n read_vector(v);\n\n \/\/ double sum = read_and_sum(num_vals);\n cout << \"The sum is: \" << sum_vector(v) << \"\\n\";\n}\n\n\/\/ vim: set ai sw=4 et sm:\n<commit_msg>Add cVector class implementation to user_types.cpp.<commit_after>\/*\n * template.cpp\n *\n * Just some boilerplate stuff to use for each file.\n *\/\n\n#include <iostream>\n#include <complex>\nusing namespace std;\n\nstruct sVector {\n int size;\n double *elem;\n};\n\nvoid vector_init(sVector & v, int s)\n{\n v.elem = new double[s];\n v.size = s;\n}\n\n\/* Fill values in a sVector. Assume an already initialized vector is passed in *\/\nvoid read_vector(sVector & v)\n{\n cout << \"Please give me \" << v.size << \" floating point numbers.\\n\";\n\n for (auto i=0; i!=v.size; ++i)\n cin >> v.elem[i];\n}\n\n\/* Sum values in a sVector. *\/\ndouble sum_vector(sVector & v)\n{\n double sum = 0;\n for (auto i=0; i!=v.size; ++i)\n sum += v.elem[i];\n \n return sum;\n}\n\nvoid svector_access(sVector v, sVector & rv, sVector *pv)\n{\n int i1 = v.size; \/\/ Access to pass-by-value vector\n int i2 = rv.size; \/\/ Access to pass-by-reference vector\n int i3 = pv->size; \/\/ Access by pointer to vector\n}\n\nvoid handle_svector()\n{\n int num_vals;\n\n cout << \"How many elements in the sVector? \";\n cin >> num_vals;\n\n sVector v;\n vector_init(v, num_vals);\n read_vector(v);\n\n \/\/ double sum = read_and_sum(num_vals);\n cout << \"The sum is: \" << sum_vector(v) << \"\\n\";\n}\n\n\/* Use a class instead of a struct *\/\n\nclass cVector {\npublic:\n cVector(int s): elem{new double[s]}, sz{s} {} \/\/ construct a cVector\n double& operator[](int i) { return elem[i]; } \/\/ [] element access: subscripting\n int size() { return sz; } \/\/ Let's see how this name overloading works!\nprivate:\n double* elem;\n int sz;\n};\n\ndouble cvector_read_and_sum(int s)\n{\n cVector v(s);\n\n cout << \"Please give me \" << s << \" floating point numbers.\\n\";\n for (auto i=0; i!=v.size(); ++i)\n cin >> v[i];\n\n double sum = 0;\n for (auto i=0; i!=v.size(); ++i)\n sum += v[i];\n \n return sum;\n}\n\nvoid handle_cvector()\n{\n int num_vals;\n\n cout << \"How many elements in the cVector? \";\n cin >> num_vals;\n\n auto sum = cvector_read_and_sum(num_vals);\n\n \/\/ double sum = read_and_sum(num_vals);\n cout << \"The sum is: \" << sum << \"\\n\";\n}\n\nint main()\n{\n handle_svector();\n handle_cvector();\n}\n\n\/\/ vim: set ai sw=4 et sm:\n<|endoftext|>"} {"text":"<commit_before>\/*\nCopyright(c) 2016 Panos Karabelas\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and \/ or sell\ncopies of the Software, and to permit persons to whom the Software is furnished\nto do so, subject to the following conditions :\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS\nFOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR\nCOPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\nIN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\nCONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n*\/\n\n\/\/= INCLUDES =================\n#include \"DirectusCore.h\"\n#include \"Logging\/Log.h\"\n#include <QStyleOption>\n#include \"Core\/Settings.h\"\n#include \"Core\/Context.h\"\n#include \"Core\/Scene.h\"\n#include \"Components\/Camera.h\"\n#include \"Math\/Vector3.h\"\n#include \"Math\/Vector2.h\"\n#include \"DirectusInspector.h\"\n\/\/============================\n\n\/\/= NAMESPACES ================\nusing namespace Directus;\nusing namespace Directus::Math;\n\/\/=============================\n\n\/\/ CONSTRUCTOR\/DECONSTRUCTOR =========================\nDirectusCore::DirectusCore(QWidget* parent) : QWidget(parent)\n{\n setAttribute(Qt::WA_MSWindowsUseDirect3D, true);\n setAttribute(Qt::WA_PaintOnScreen, true);\n setAttribute(Qt::WA_NativeWindow, true);\n\n \/\/ This will make Qt update this widget as fast as possible.\n \/\/ Yes, paintEvent(QPaintEvent*) will be called also.\n \/\/ NOTE: I tested this technique and it yields thousands\n \/\/ of FPS, so it should do.\n m_timerUpdate = new QTimer(this);\n connect(m_timerUpdate, SIGNAL(timeout()), this, SLOT(update()));\n\n \/\/ stats\n m_timer500Mil = new QTimer(this);\n connect(m_timer500Mil, SIGNAL(timeout()), this, SLOT(Update500Mil()));\n\n \/\/ light update\n m_timer60FPS = new QTimer(this);\n connect(m_timer60FPS, SIGNAL(timeout()), this, SLOT(Update60FPS()));\n m_timer60FPS->start(16);\n\n m_locked = false;\n m_isRunning = false;\n}\n\nDirectusCore::~DirectusCore()\n{\n m_engine->Shutdown();\n delete m_engine;\n}\n\nSocket* DirectusCore::GetEngineSocket()\n{\n return m_socket;\n}\n\nvoid DirectusCore::Initialize(void* mainWindowHandle, void* hInstance, DirectusStatsLabel* directusStatsLabel)\n{\n \/\/ Initialize the engine\n m_engine = new Engine(new Context());\n m_engine->SetHandles(hInstance, mainWindowHandle, (void*)this->winId());\n m_engine->Initialize();\n\n m_socket = m_engine->GetContext()->GetSubsystem<Socket>();\n m_directusStatsLabel = directusStatsLabel;\n}\n\nvoid DirectusCore::SetInspector(DirectusInspector* inspector)\n{\n m_inspector = inspector;\n}\n\nbool DirectusCore::IsRunning()\n{\n return m_isRunning;\n}\n\n\/\/ Runs when the play button is pressed\nvoid DirectusCore::Start()\n{\n if (m_locked)\n return;\n\n m_socket->Start();\n m_timerUpdate->start(0);\n m_timer500Mil->start(500);\n m_timer60FPS->stop();\n m_isRunning = true;\n\n emit EngineStarting();\n}\n\n\/\/ Runs when the play button is released\nvoid DirectusCore::Stop()\n{\n if (m_locked)\n return;\n\n m_socket->OnDisable();\n m_timerUpdate->stop();\n m_timer500Mil->stop();\n m_timer60FPS->start(16);\n m_isRunning = false;\n\n emit EngineStopping();\n}\n\n\/\/ Runs as fast as possible, performs a full simulation cycle.\nvoid DirectusCore::Update()\n{\n if (m_locked)\n return;\n\n m_socket->Update();\n}\n\n\/\/ Runs every second\nvoid DirectusCore::Update500Mil()\n{\n if (m_locked)\n return;\n\n m_directusStatsLabel->UpdateStats(this);\n}\n\n\/\/ Runs 30 times per second\n\/\/ Updates engine's subsystems and propagates data, it doesn't simulate\nvoid DirectusCore::Update60FPS()\n{\n if (m_locked)\n return;\n\n m_socket->LightUpdate();\n}\n\n\/\/ Prevents any engine update to execute\nvoid DirectusCore::LockUpdate()\n{\n m_locked = true;\n}\n\n\/\/ Allows any engine update function to execute\nvoid DirectusCore::UnlockUpdate()\n{\n m_locked = false;\n}\n\/\/====================================================\n\n\/\/= OVERRIDDEN FUNCTIONS =============================\nvoid DirectusCore::resizeEvent(QResizeEvent* evt)\n{\n if (evt->oldSize() == evt->size())\n return;\n\n int width = this->size().width();\n int height = this->size().height();\n\n height = width \/ (16.0f\/9.0f);\n\n if (width % 2 != 0)\n width++;\n\n if (height % 2 != 0)\n height++;\n\n \/\/ Change the size of the widget\n setGeometry(QRect(0, 0, width, height));\n\n \/\/ Change the rendering resolution of the engine\n SetResolution(width, height);\n}\n\n\/\/ Invoked by QT itself, Update() let's the engine do the rendering\nvoid DirectusCore::paintEvent(QPaintEvent* evt)\n{\n Update();\n}\n\n\/\/ Temporary\nvoid DirectusCore::mousePressEvent(QMouseEvent* event)\n{\n \/*QPoint mousePos = event->pos();\n auto picked = m_socket->GetContext()->GetSubsystem<Scene>()->MousePick(Vector2(mousePos.x(), mousePos.y()));\n\n if (picked)\n LOG_INFO(picked->GetName());\n\n m_inspector->Inspect(picked);*\/\n}\n\/\/===================================================\n\n\/\/= Engine functions ================================\n\/\/ Changes the rendering resolution of the engine\nvoid DirectusCore::SetResolution(float width, float height)\n{\n if (!m_socket)\n return;\n\n m_socket->SetResolution(width, height);\n m_socket->SetViewport(width, height);\n}\n\/\/===================================================\n<commit_msg>Editor game view is no longer locked to an aspect ratio of 16:9<commit_after>\/*\nCopyright(c) 2016 Panos Karabelas\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and \/ or sell\ncopies of the Software, and to permit persons to whom the Software is furnished\nto do so, subject to the following conditions :\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS\nFOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR\nCOPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\nIN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\nCONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n*\/\n\n\/\/= INCLUDES =================\n#include \"DirectusCore.h\"\n#include \"Logging\/Log.h\"\n#include <QStyleOption>\n#include \"Core\/Settings.h\"\n#include \"Core\/Context.h\"\n#include \"Core\/Scene.h\"\n#include \"Components\/Camera.h\"\n#include \"Math\/Vector3.h\"\n#include \"Math\/Vector2.h\"\n#include \"DirectusInspector.h\"\n\/\/============================\n\n\/\/= NAMESPACES ================\nusing namespace Directus;\nusing namespace Directus::Math;\n\/\/=============================\n\n\/\/ CONSTRUCTOR\/DECONSTRUCTOR =========================\nDirectusCore::DirectusCore(QWidget* parent) : QWidget(parent)\n{\n setAttribute(Qt::WA_MSWindowsUseDirect3D, true);\n setAttribute(Qt::WA_PaintOnScreen, true);\n setAttribute(Qt::WA_NativeWindow, true);\n\n \/\/ This will make Qt update this widget as fast as possible.\n \/\/ Yes, paintEvent(QPaintEvent*) will be called also.\n \/\/ NOTE: I tested this technique and it yields thousands\n \/\/ of FPS, so it should do.\n m_timerUpdate = new QTimer(this);\n connect(m_timerUpdate, SIGNAL(timeout()), this, SLOT(update()));\n\n \/\/ stats\n m_timer500Mil = new QTimer(this);\n connect(m_timer500Mil, SIGNAL(timeout()), this, SLOT(Update500Mil()));\n\n \/\/ light update\n m_timer60FPS = new QTimer(this);\n connect(m_timer60FPS, SIGNAL(timeout()), this, SLOT(Update60FPS()));\n m_timer60FPS->start(16);\n\n m_locked = false;\n m_isRunning = false;\n}\n\nDirectusCore::~DirectusCore()\n{\n m_engine->Shutdown();\n delete m_engine;\n}\n\nSocket* DirectusCore::GetEngineSocket()\n{\n return m_socket;\n}\n\nvoid DirectusCore::Initialize(void* mainWindowHandle, void* hInstance, DirectusStatsLabel* directusStatsLabel)\n{\n \/\/ Initialize the engine\n m_engine = new Engine(new Context());\n m_engine->SetHandles(hInstance, mainWindowHandle, (void*)this->winId());\n m_engine->Initialize();\n\n m_socket = m_engine->GetContext()->GetSubsystem<Socket>();\n m_directusStatsLabel = directusStatsLabel;\n}\n\nvoid DirectusCore::SetInspector(DirectusInspector* inspector)\n{\n m_inspector = inspector;\n}\n\nbool DirectusCore::IsRunning()\n{\n return m_isRunning;\n}\n\n\/\/ Runs when the play button is pressed\nvoid DirectusCore::Start()\n{\n if (m_locked)\n return;\n\n m_socket->Start();\n m_timerUpdate->start(0);\n m_timer500Mil->start(500);\n m_timer60FPS->stop();\n m_isRunning = true;\n\n emit EngineStarting();\n}\n\n\/\/ Runs when the play button is released\nvoid DirectusCore::Stop()\n{\n if (m_locked)\n return;\n\n m_socket->OnDisable();\n m_timerUpdate->stop();\n m_timer500Mil->stop();\n m_timer60FPS->start(16);\n m_isRunning = false;\n\n emit EngineStopping();\n}\n\n\/\/ Runs as fast as possible, performs a full simulation cycle.\nvoid DirectusCore::Update()\n{\n if (m_locked)\n return;\n\n m_socket->Update();\n}\n\n\/\/ Runs every second\nvoid DirectusCore::Update500Mil()\n{\n if (m_locked)\n return;\n\n m_directusStatsLabel->UpdateStats(this);\n}\n\n\/\/ Runs 30 times per second\n\/\/ Updates engine's subsystems and propagates data, it doesn't simulate\nvoid DirectusCore::Update60FPS()\n{\n if (m_locked)\n return;\n\n m_socket->LightUpdate();\n}\n\n\/\/ Prevents any engine update to execute\nvoid DirectusCore::LockUpdate()\n{\n m_locked = true;\n}\n\n\/\/ Allows any engine update function to execute\nvoid DirectusCore::UnlockUpdate()\n{\n m_locked = false;\n}\n\/\/====================================================\n\n\/\/= OVERRIDDEN FUNCTIONS =============================\nvoid DirectusCore::resizeEvent(QResizeEvent* evt)\n{\n if (evt->oldSize() == evt->size())\n return;\n\n int width = this->size().width();\n int height = this->size().height();\n\n if (width % 2 != 0)\n width++;\n\n if (height % 2 != 0)\n height++;\n\n \/\/ Change the size of the widget\n setGeometry(QRect(0, 0, width, height));\n\n \/\/ Change the resolution of the engine\n SetResolution(width, height);\n}\n\n\/\/ Invoked by QT itself, Update() let's the engine do the rendering\nvoid DirectusCore::paintEvent(QPaintEvent* evt)\n{\n Update();\n}\n\n\/\/ Temporary\nvoid DirectusCore::mousePressEvent(QMouseEvent* event)\n{\n \/*QPoint mousePos = event->pos();\n auto picked = m_socket->GetContext()->GetSubsystem<Scene>()->MousePick(Vector2(mousePos.x(), mousePos.y()));\n\n if (picked)\n LOG_INFO(picked->GetName());\n\n m_inspector->Inspect(picked);*\/\n}\n\/\/===================================================\n\n\/\/= Engine functions ================================\n\/\/ Changes the rendering resolution of the engine\nvoid DirectusCore::SetResolution(float width, float height)\n{\n if (!m_socket)\n return;\n\n m_socket->SetResolution(width, height);\n m_socket->SetViewport(width, height);\n}\n\/\/===================================================\n<|endoftext|>"} {"text":"<commit_before> \/\/ Natron\n\/* This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/. *\/\n\n\n#include \"HistogramCPU.h\"\n\n#include <algorithm>\n#include <QMutex>\n#include <QWaitCondition>\n\n#include \"Engine\/Image.h\"\n\n\nstruct HistogramRequest {\n int binsCount;\n int mode;\n boost::shared_ptr<Natron::Image> image;\n RectI rect;\n double vmin;\n double vmax;\n int smoothingKernelSize;\n \n HistogramRequest()\n : binsCount(0)\n , mode(0)\n , image()\n , rect()\n , vmin(0)\n , vmax(0)\n , smoothingKernelSize(0)\n {\n \n }\n \n HistogramRequest(int binsCount,\n int mode,\n const boost::shared_ptr<Natron::Image>& image,\n const RectI& rect,\n double vmin,\n double vmax,\n int smoothingKernelSize)\n : binsCount(binsCount)\n , mode(mode)\n , image(image)\n , rect(rect)\n , vmin(vmin)\n , vmax(vmax)\n , smoothingKernelSize(smoothingKernelSize)\n {\n }\n};\n\nstruct FinishedHistogram {\n std::vector<float> histogram1;\n std::vector<float> histogram2;\n std::vector<float> histogram3;\n int mode;\n int binsCount;\n int pixelsCount;\n double vmin,vmax;\n \n FinishedHistogram()\n : histogram1()\n , histogram2()\n , histogram3()\n , mode(0)\n , binsCount(0)\n , pixelsCount(0)\n , vmin(0)\n , vmax(0)\n {\n \n }\n};\n\nstruct HistogramCPUPrivate\n{\n \n QWaitCondition requestCond;\n QMutex requestMutex;\n std::list<HistogramRequest> requests;\n \n QMutex producedMutex;\n std::list<boost::shared_ptr<FinishedHistogram> > produced;\n \n QWaitCondition mustQuitCond;\n QMutex mustQuitMutex;\n bool mustQuit;\n\n HistogramCPUPrivate()\n : requestCond()\n , requestMutex()\n , requests()\n , producedMutex()\n , produced()\n , mustQuitCond()\n , mustQuitMutex()\n , mustQuit(false)\n {\n \n }\n};\n\nHistogramCPU::HistogramCPU()\n: QThread()\n, _imp(new HistogramCPUPrivate())\n{\n}\n\nHistogramCPU::~HistogramCPU()\n{\n quitAnyComputation();\n}\n\nvoid HistogramCPU::computeHistogram(int mode, \/\/< corresponds to the enum Histogram::DisplayMode\n const boost::shared_ptr<Natron::Image>& image,\n const RectI& rect,\n int binsCount,\n double vmin,\n double vmax,\n int smoothingKernelSize)\n{\n \/*Starting or waking-up the thread*\/\n QMutexLocker quitLocker(&_imp->mustQuitMutex);\n QMutexLocker locker(&_imp->requestMutex);\n _imp->requests.push_back(HistogramRequest(binsCount,mode,image,rect,vmin,vmax,smoothingKernelSize));\n if (!isRunning() && !_imp->mustQuit) {\n quitLocker.unlock();\n start(HighestPriority);\n } else {\n quitLocker.unlock();\n _imp->requestCond.wakeOne();\n }\n\n}\n\nvoid HistogramCPU::quitAnyComputation()\n{\n if (isRunning()) {\n QMutexLocker l(&_imp->mustQuitMutex);\n _imp->mustQuit = true;\n \n \/\/\/post a fake request to wakeup the thread\n l.unlock();\n computeHistogram(0, boost::shared_ptr<Natron::Image>(), RectI(), 0,0,0,0);\n l.relock();\n while (_imp->mustQuit) {\n _imp->mustQuitCond.wait(&_imp->mustQuitMutex);\n }\n }\n}\n\nbool\nHistogramCPU::hasProducedHistogram() const\n{\n QMutexLocker l(&_imp->producedMutex);\n return !_imp->produced.empty();\n}\n\nbool\nHistogramCPU::getMostRecentlyProducedHistogram(std::vector<float>* histogram1,\n std::vector<float>* histogram2,\n std::vector<float>* histogram3,\n unsigned int* binsCount,\n unsigned int* pixelsCount,\n int* mode,\n double* vmin,\n double* vmax)\n{\n assert(histogram1 && histogram2 && histogram3 && binsCount && pixelsCount && mode && vmin && vmax);\n\n QMutexLocker l(&_imp->producedMutex);\n if (_imp->produced.empty()) {\n return false;\n }\n \n#pragma message WARN(\"this is not the most recent! the most recent is back(), since we push_back() below\")\n boost::shared_ptr<FinishedHistogram> h = _imp->produced.front();\n\n *histogram1 = h->histogram1;\n *histogram2 = h->histogram2;\n *histogram3 = h->histogram3;\n *binsCount = h->binsCount;\n *pixelsCount = h->pixelsCount;\n *mode = h->mode;\n *vmin = h->vmin;\n *vmax = h->vmax;\n _imp->produced.pop_front();\n\n return true;\n}\n\nstatic inline float\npix_red(float *pix)\n{\n return pix[0];\n}\n\nstatic inline float\npix_green(float *pix)\n{\n return pix[1];\n}\n\nstatic inline float\npix_blue(float *pix)\n{\n return pix[2];\n}\n\nstatic inline float\npix_alpha(float *pix)\n{\n return pix[3];\n}\n\nstatic inline float\npix_lum(float *pix)\n{\n return 0.299 * pix[0] + 0.587 * pix[1] + 0.114 * pix[2];\n}\n\ntemplate <float pix_func(float*)>\nvoid\ncomputeHisto(const HistogramRequest& request, std::vector<float> *histo)\n{\n assert(histo);\n histo->resize(request.binsCount);\n std::fill(histo->begin(), histo->end(), 0.f);\n\n double binSize = (request.vmax - request.vmin) \/ request.binsCount;\n\n\n for (int y = request.rect.bottom() ; y < request.rect.top(); ++y) {\n for (int x = request.rect.left(); x < request.rect.right(); ++x) {\n float *pix = request.image->pixelAt(x, y) ;\n float v = pix_func(pix);\n if (request.vmin <= v && v < request.vmax) {\n int index = (int)((v - request.vmin) \/ binSize);\n assert(0 <= index && index < (int)histo->size());\n (*histo)[index] += 1.f;\n }\n }\n }\n}\n\n\nstatic void\ncomputeHistogramStatic(const HistogramRequest& request, boost::shared_ptr<FinishedHistogram> ret, int histogramIndex)\n{\n std::vector<float> *histo = 0;\n switch (histogramIndex) {\n case 1:\n histo = &ret->histogram1;\n break;\n case 2:\n histo = &ret->histogram2;\n break;\n case 3:\n histo = &ret->histogram3;\n break;\n default:\n break;\n }\n assert(histo);\n\n \/\/\/ keep the mode parameter in sync with Histogram::DisplayMode\n\n int mode = request.mode;\n\n \/\/\/if the mode is RGB, adjust the mode to either R,G or B depending on the histogram index\n if (mode == 0) {\n mode = histogramIndex + 2;\n }\n\n ret->pixelsCount = request.rect.area();\n\n switch (mode) {\n case 1: \/\/< A\n computeHisto<pix_alpha>(request, histo);\n break;\n case 2: \/\/<Y\n computeHisto<pix_lum>(request, histo);\n break;\n case 3: \/\/< R\n computeHisto<pix_red>(request, histo);\n break;\n case 4: \/\/< G\n computeHisto<pix_green>(request, histo);\n break;\n case 5: \/\/< B\n computeHisto<pix_blue>(request, histo);\n break;\n\n default:\n assert(false);\n break;\n }\n\n \/\/\/Apply the binomial filter if any (the filter size has to be an odd number)\n assert(request.smoothingKernelSize >= 0);\n assert((request.smoothingKernelSize == 0) || (request.smoothingKernelSize & 1));\n\n for (int k = request.smoothingKernelSize; k > 1; k -=2) {\n const std::vector<float> histogramCopy = *histo;\n\n for (int i = 1; i < ((int)histo->size() - 1); ++i) {\n (*histo)[i] = (histogramCopy[i-1] + 2*histogramCopy[i] + histogramCopy[i+1]) \/ 4;\n }\n }\n}\n\nvoid\nHistogramCPU::run()\n{\n for (;;) {\n HistogramRequest request;\n {\n QMutexLocker l(&_imp->requestMutex);\n while (_imp->requests.empty()) {\n _imp->requestCond.wait(&_imp->requestMutex);\n }\n \n \/\/\/get the last request\n request = _imp->requests.back();\n _imp->requests.pop_back();\n \n \/\/\/ignore all other requests pending\n _imp->requests.clear();\n }\n \n {\n QMutexLocker l(&_imp->mustQuitMutex);\n if (_imp->mustQuit) {\n _imp->mustQuit = false;\n _imp->mustQuitCond.wakeOne();\n return;\n }\n }\n \n \n boost::shared_ptr<FinishedHistogram> ret(new FinishedHistogram);\n ret->binsCount = request.binsCount;\n ret->mode = request.mode;\n ret->vmin = request.vmin;\n ret->vmax = request.vmax;\n \n\n switch (request.mode) {\n case 0: \/\/< RGB\n computeHistogramStatic(request, ret, 1);\n computeHistogramStatic(request, ret, 2);\n computeHistogramStatic(request, ret, 3);\n break;\n case 1:\n case 2:\n case 3:\n case 4:\n case 5:\n computeHistogramStatic(request, ret, 1);\n break;\n default:\n assert(false); \/\/< unknown case.\n break;\n }\n \n \n {\n QMutexLocker l(&_imp->producedMutex);\n _imp->produced.push_back(ret);\n }\n emit histogramProduced();\n }\n}<commit_msg>HistogramCPU: try to fix the build<commit_after> \/\/ Natron\n\/* This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/. *\/\n\n\n#include \"HistogramCPU.h\"\n\n#include <algorithm>\n#include <QMutex>\n#include <QWaitCondition>\n\n#include \"Engine\/Image.h\"\n\n\nstruct HistogramRequest {\n int binsCount;\n int mode;\n boost::shared_ptr<Natron::Image> image;\n RectI rect;\n double vmin;\n double vmax;\n int smoothingKernelSize;\n \n HistogramRequest()\n : binsCount(0)\n , mode(0)\n , image()\n , rect()\n , vmin(0)\n , vmax(0)\n , smoothingKernelSize(0)\n {\n \n }\n \n HistogramRequest(int binsCount,\n int mode,\n const boost::shared_ptr<Natron::Image>& image,\n const RectI& rect,\n double vmin,\n double vmax,\n int smoothingKernelSize)\n : binsCount(binsCount)\n , mode(mode)\n , image(image)\n , rect(rect)\n , vmin(vmin)\n , vmax(vmax)\n , smoothingKernelSize(smoothingKernelSize)\n {\n }\n};\n\nstruct FinishedHistogram {\n std::vector<float> histogram1;\n std::vector<float> histogram2;\n std::vector<float> histogram3;\n int mode;\n int binsCount;\n int pixelsCount;\n double vmin,vmax;\n \n FinishedHistogram()\n : histogram1()\n , histogram2()\n , histogram3()\n , mode(0)\n , binsCount(0)\n , pixelsCount(0)\n , vmin(0)\n , vmax(0)\n {\n \n }\n};\n\nstruct HistogramCPUPrivate\n{\n \n QWaitCondition requestCond;\n QMutex requestMutex;\n std::list<HistogramRequest> requests;\n \n QMutex producedMutex;\n std::list<boost::shared_ptr<FinishedHistogram> > produced;\n \n QWaitCondition mustQuitCond;\n QMutex mustQuitMutex;\n bool mustQuit;\n\n HistogramCPUPrivate()\n : requestCond()\n , requestMutex()\n , requests()\n , producedMutex()\n , produced()\n , mustQuitCond()\n , mustQuitMutex()\n , mustQuit(false)\n {\n \n }\n};\n\nHistogramCPU::HistogramCPU()\n: QThread()\n, _imp(new HistogramCPUPrivate())\n{\n}\n\nHistogramCPU::~HistogramCPU()\n{\n quitAnyComputation();\n}\n\nvoid HistogramCPU::computeHistogram(int mode, \/\/< corresponds to the enum Histogram::DisplayMode\n const boost::shared_ptr<Natron::Image>& image,\n const RectI& rect,\n int binsCount,\n double vmin,\n double vmax,\n int smoothingKernelSize)\n{\n \/*Starting or waking-up the thread*\/\n QMutexLocker quitLocker(&_imp->mustQuitMutex);\n QMutexLocker locker(&_imp->requestMutex);\n _imp->requests.push_back(HistogramRequest(binsCount,mode,image,rect,vmin,vmax,smoothingKernelSize));\n if (!isRunning() && !_imp->mustQuit) {\n quitLocker.unlock();\n start(HighestPriority);\n } else {\n quitLocker.unlock();\n _imp->requestCond.wakeOne();\n }\n\n}\n\nvoid HistogramCPU::quitAnyComputation()\n{\n if (isRunning()) {\n QMutexLocker l(&_imp->mustQuitMutex);\n _imp->mustQuit = true;\n \n \/\/\/post a fake request to wakeup the thread\n l.unlock();\n computeHistogram(0, boost::shared_ptr<Natron::Image>(), RectI(), 0,0,0,0);\n l.relock();\n while (_imp->mustQuit) {\n _imp->mustQuitCond.wait(&_imp->mustQuitMutex);\n }\n }\n}\n\nbool\nHistogramCPU::hasProducedHistogram() const\n{\n QMutexLocker l(&_imp->producedMutex);\n return !_imp->produced.empty();\n}\n\nbool\nHistogramCPU::getMostRecentlyProducedHistogram(std::vector<float>* histogram1,\n std::vector<float>* histogram2,\n std::vector<float>* histogram3,\n unsigned int* binsCount,\n unsigned int* pixelsCount,\n int* mode,\n double* vmin,\n double* vmax)\n{\n assert(histogram1 && histogram2 && histogram3 && binsCount && pixelsCount && mode && vmin && vmax);\n\n QMutexLocker l(&_imp->producedMutex);\n if (_imp->produced.empty()) {\n return false;\n }\n \n#pragma message WARN(\"this is not the most recent! the most recent is back(), since we push_back() below\")\n boost::shared_ptr<FinishedHistogram> h = _imp->produced.front();\n\n *histogram1 = h->histogram1;\n *histogram2 = h->histogram2;\n *histogram3 = h->histogram3;\n *binsCount = h->binsCount;\n *pixelsCount = h->pixelsCount;\n *mode = h->mode;\n *vmin = h->vmin;\n *vmax = h->vmax;\n _imp->produced.pop_front();\n\n return true;\n}\n\nnamespace {\nstruct pix_red {\n static float\n val(float *pix)\n {\n return pix[0];\n }\n};\n\nstruct pix_green {\n static float\n val(float *pix)\n {\n return pix[1];\n }\n};\n\nstruct pix_blue {\n static float\n val(float *pix)\n {\n return pix[2];\n }\n};\n\nstruct pix_alpha {\n static float\n val(float *pix)\n {\n return pix[3];\n }\n};\n\nstruct pix_lum {\n static float\n val(float *pix)\n {\n return 0.299 * pix[0] + 0.587 * pix[1] + 0.114 * pix[2];\n }\n};\n}\n\ntemplate <float pix_func(float*)>\nvoid\ncomputeHisto(const HistogramRequest& request, std::vector<float> *histo)\n{\n assert(histo);\n histo->resize(request.binsCount);\n std::fill(histo->begin(), histo->end(), 0.f);\n\n double binSize = (request.vmax - request.vmin) \/ request.binsCount;\n\n\n for (int y = request.rect.bottom() ; y < request.rect.top(); ++y) {\n for (int x = request.rect.left(); x < request.rect.right(); ++x) {\n float *pix = request.image->pixelAt(x, y) ;\n float v = pix_func(pix);\n if (request.vmin <= v && v < request.vmax) {\n int index = (int)((v - request.vmin) \/ binSize);\n assert(0 <= index && index < (int)histo->size());\n (*histo)[index] += 1.f;\n }\n }\n }\n}\n\n\nstatic void\ncomputeHistogramStatic(const HistogramRequest& request, boost::shared_ptr<FinishedHistogram> ret, int histogramIndex)\n{\n std::vector<float> *histo = 0;\n switch (histogramIndex) {\n case 1:\n histo = &ret->histogram1;\n break;\n case 2:\n histo = &ret->histogram2;\n break;\n case 3:\n histo = &ret->histogram3;\n break;\n default:\n break;\n }\n assert(histo);\n\n \/\/\/ keep the mode parameter in sync with Histogram::DisplayMode\n\n int mode = request.mode;\n\n \/\/\/if the mode is RGB, adjust the mode to either R,G or B depending on the histogram index\n if (mode == 0) {\n mode = histogramIndex + 2;\n }\n\n ret->pixelsCount = request.rect.area();\n\n switch (mode) {\n case 1: \/\/< A\n computeHisto<&pix_alpha::val>(request, histo);\n break;\n case 2: \/\/<Y\n computeHisto<&pix_lum::val>(request, histo);\n break;\n case 3: \/\/< R\n computeHisto<&pix_red::val>(request, histo);\n break;\n case 4: \/\/< G\n computeHisto<&pix_green::val>(request, histo);\n break;\n case 5: \/\/< B\n computeHisto<&pix_blue::val>(request, histo);\n break;\n\n default:\n assert(false);\n break;\n }\n\n \/\/\/Apply the binomial filter if any (the filter size has to be an odd number)\n assert(request.smoothingKernelSize >= 0);\n assert((request.smoothingKernelSize == 0) || (request.smoothingKernelSize & 1));\n\n for (int k = request.smoothingKernelSize; k > 1; k -=2) {\n const std::vector<float> histogramCopy = *histo;\n\n for (int i = 1; i < ((int)histo->size() - 1); ++i) {\n (*histo)[i] = (histogramCopy[i-1] + 2*histogramCopy[i] + histogramCopy[i+1]) \/ 4;\n }\n }\n}\n\nvoid\nHistogramCPU::run()\n{\n for (;;) {\n HistogramRequest request;\n {\n QMutexLocker l(&_imp->requestMutex);\n while (_imp->requests.empty()) {\n _imp->requestCond.wait(&_imp->requestMutex);\n }\n \n \/\/\/get the last request\n request = _imp->requests.back();\n _imp->requests.pop_back();\n \n \/\/\/ignore all other requests pending\n _imp->requests.clear();\n }\n \n {\n QMutexLocker l(&_imp->mustQuitMutex);\n if (_imp->mustQuit) {\n _imp->mustQuit = false;\n _imp->mustQuitCond.wakeOne();\n return;\n }\n }\n \n \n boost::shared_ptr<FinishedHistogram> ret(new FinishedHistogram);\n ret->binsCount = request.binsCount;\n ret->mode = request.mode;\n ret->vmin = request.vmin;\n ret->vmax = request.vmax;\n \n\n switch (request.mode) {\n case 0: \/\/< RGB\n computeHistogramStatic(request, ret, 1);\n computeHistogramStatic(request, ret, 2);\n computeHistogramStatic(request, ret, 3);\n break;\n case 1:\n case 2:\n case 3:\n case 4:\n case 5:\n computeHistogramStatic(request, ret, 1);\n break;\n default:\n assert(false); \/\/< unknown case.\n break;\n }\n \n \n {\n QMutexLocker l(&_imp->producedMutex);\n _imp->produced.push_back(ret);\n }\n emit histogramProduced();\n }\n}<|endoftext|>"} {"text":"<commit_before>\/*$Id$\n *\n * This source file is a part of the Berlin Project.\n * Copyright (C) 2000 Stefan Seefeld <stefan@berlin-consortium.org> \n * Copyright (C) 2001 Philip Philonenko <philonenko@orgacom.ru> \n * http:\/\/www.berlin-consortium.org\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Library General Public\n * License as published by the Free Software Foundation; either\n * version 2 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Library General Public License for more details.\n *\n * You should have received a copy of the GNU Library General Public\n * License along with this library; if not, write to the\n * Free Software Foundation, Inc., 675 Mass Ave, Cambridge,\n * MA 02139, USA.\n *\/\n\n#include <Prague\/Sys\/Memory.hh>\n#include <Prague\/Sys\/FdSet.hh>\n#include <Prague\/Sys\/Tracer.hh>\n#include <Prague\/Sys\/Path.hh>\n#include <Berlin\/RCManager.hh>\n#include <Berlin\/Logger.hh>\n\n#include <Console\/SDL\/Console.hh>\n#include <Console\/SDL\/Extension.hh>\n#include <Console\/SDL\/Drawable.hh>\n#include <Console\/SDL\/Pointer.hh>\n\nusing namespace Warsaw;\n\nnamespace\n{\n static void readEvent(SDL_Event &e)\n {\n Prague::Trace trace(\"readEvent()\");\n unsigned int t;\n std::cin >> t;\n e.type = static_cast<char>(t);\n switch (e.type)\n {\n case SDL_KEYDOWN:\n\t{\n\t std::cin >> t;\n\t e.key.keysym.sym = static_cast<SDLKey>(t);\n\t break;\n\t}\n case SDL_MOUSEMOTION:\n\t{\n\t std::cin >> e.motion.x\n\t\t >> e.motion.y;\n\t break;\n\t}\n case SDL_MOUSEBUTTONDOWN:\n case SDL_MOUSEBUTTONUP:\n\t{\n\t break;\n }\n }\n }\n \n static void writeEvent(SDL_Event &e)\n {\n Prague::Trace trace(\"writeEvent()\");\n std::cout << static_cast<unsigned int>(e.type) << ' ';\n switch (e.type)\n {\n case SDL_KEYDOWN:\n\t{\n\t std::cout << static_cast<unsigned int>(e.key.keysym.sym);\n\t break;\n\t}\n case SDL_MOUSEMOTION:\n\t{\n\t std::cout << e.motion.x << ' '\n\t\t << e.motion.y;\n\t break;\n\t}\n case SDL_MOUSEBUTTONDOWN:\n case SDL_MOUSEBUTTONUP:\n\t{\n\t break;\n\t}\n }\n std::cout << endl;\n }\n}; \/\/ namespace\n\n\n\n\n\n\/\/ ---------------------------------------------------------------\n\/\/ class SDL::Console (implementation)\n\/\/ ---------------------------------------------------------------\n\nSDL::Console::Console(int &argc, char **argv) :\n _autoplay(false),\n _is_gl(false),\n _pointer_mgr(new PointerManagerT<nonGLPointer>)\n{\n Prague::Trace trace(\"SDL::Console::Console\");\n Logger::log(Logger::loader) << \"trying to open SDL console\" << endl;\n\n SDL_Init(SDL_INIT_VIDEO);\n SDL_ShowCursor(SDL_DISABLE);\n\n \/\/ FIXME: Get some 'real' values!\n _resolution[0] = 0.1;\n _resolution[1] = 0.1;\n\n _size[0] = 640;\n _size[1] = 480;\n\n _vsize[0] = 640;\n _vsize[1] = 480;\n\n pipe(_wakeupPipe);\n}\n\nSDL::Console::~Console()\n{\n Prague::Trace trace(\"SDL::Console::~Console\");\n\n for (dlist_t::iterator i = _drawables.begin();\n i != _drawables.end();\n i++) delete *i;\n close(_wakeupPipe[0]);\n close(_wakeupPipe[1]);\n SDL_Quit();\n}\n\nConsole::Pointer *SDL::Console::pointer(Raster_ptr raster)\n{\n Prague::Trace trace(\"SDL::Console::pointer\");\n return _pointer_mgr->create_pointer(raster);\n}\n\nConsole::Drawable *SDL::Console::drawable()\n{\n Prague::Trace trace(\"SDL::Console::drawable\");\n\n if (_drawables.empty())\n _drawables.push_back(new SDL::Drawable(0));\n \n return _drawables.front();\n}\n\nConsole::Drawable *\nSDL::Console::create_drawable(Warsaw::PixelCoord w,\n\t\t\t Warsaw::PixelCoord h, Warsaw::PixelCoord d)\n{\n Prague::Trace trace(\"SDL::Console::create_drawable\");\n\n _drawables.push_back(new SDL::Drawable(\"display-memory\", w, h, d));\n return _drawables.back();\n}\n\nConsole::Drawable *SDL::Console::reference_to_servant(Warsaw::Drawable_ptr drawable)\n{\n Prague::Trace trace(\"SDL::Console::reference_to_servant()\");\n \n PortableServer::Servant servant = Console::reference_to_servant(drawable);\n for (dlist_t::iterator i = _drawables.begin(); i != _drawables.end(); ++i)\n if (*i == servant) return *i;\n return 0;\n}\n\nvoid SDL::Console::activate_autoplay()\n{\n Prague::Trace trace(\"SDL::Console::activate_autoplay()\");\n\n \/\/ FIXME: This should do something.\n}\n\nvoid SDL::Console::device_info(std::ostream &os)\n{\n Prague::Trace trace(\"SDL::Console::device_info()\");\n\n os << \"sorry, device info isn't available for SDL at this time\" << std::endl;\n}\n\nInput::Event *SDL::Console::next_event()\n{\n Prague::Trace trace(\"SDL::Console::next_event()\");\n \n SDL_Event event;\n SDL_WaitEvent(&event);\n return synthesize(event);\n}\n\nvoid SDL::Console::wakeup()\n{\n Prague::Trace trace(\"SDL::Console::wakeup()\");\n\n char c = 'z'; write(_wakeupPipe[1],&c,1);\n}\n\nInput::Event *SDL::Console::synthesize(const SDL_Event &e)\n{\n Prague::Trace trace(\"SDL::Console::synthesize()\");\n\n Input::Event_var event = new Input::Event;\n switch (e.type)\n {\n case SDL_KEYDOWN:\n {\n\tInput::Toggle toggle;\n\ttoggle.actuation = Input::Toggle::press;\n\ttoggle.number = e.key.keysym.sym;\n\tevent->length(1);\n\tevent[0].dev = 0;\n\tevent[0].attr.selection(toggle); event[0].attr._d(Input::key);\n\tbreak;\n }\n case SDL_MOUSEMOTION:\n {\n\t\/\/ grab waiting mouse events and skip to the last one\n\tSDL_Event move_events[64];\n\tSDL_PumpEvents();\n\tint num = SDL_PeepEvents(move_events, 64, SDL_GETEVENT, SDL_MOUSEMOTIONMASK);\n\tif (num > 0)\n\t {\n\t \/\/ Use last known position of mouse\n\t _position[0] = move_events[num-1].motion.x;\n\t _position[1] = move_events[num-1].motion.y;\n\t }\n\telse\n\t {\n\t \/\/ Use position from original event \n\t _position[0] = e.motion.x;\n\t _position[1] = e.motion.y;\n\t }\n\tInput::Position position;\n\tposition.x = _position[0]\/_resolution[0];\n\tposition.y = _position[1]\/_resolution[1];\n\tposition.z = 0;\n\tevent->length(1);\n\tevent[0].dev = 1;\n\tevent[0].attr.location(position);\n\tbreak;\n }\n case SDL_MOUSEBUTTONDOWN:\n case SDL_MOUSEBUTTONUP:\n {\n\tInput::Toggle toggle;\n\tif (e.type == SDL_MOUSEBUTTONDOWN)\n\t toggle.actuation = Input::Toggle::press;\n\telse\n\t toggle.actuation = Input::Toggle::release;\n\ttoggle.number = e.button.button; \n\tInput::Position position;\n\tposition.x = _position[0]\/_resolution[0];\n\tposition.y = _position[1]\/_resolution[1];\n\tposition.z = 0;\n\tevent->length(2);\n\tevent[0].dev = 1;\n\tevent[0].attr.selection(toggle); event[0].attr._d(Input::button);\n\tevent[1].dev = 1;\n\tevent[1].attr.location(position);\n\tbreak;\n }\n case SDL_QUIT:\n {\n\t\/\/ this is a CTRL+C sent to the controlling terminal. Berlin may be\n\t\/\/ already crashed, so terminate forcibly.\n\texit(0);\n\tbreak;\n }\n }\n\n return event._retn();\n}\n\n\nvoid SDL::Console::set_PointerManager(PointerManager * pm) {\n _pointer_mgr = pm;\n}\n\n\nConsole::Extension * SDL::Console::create_extension(const std::string & id)\n{\n Prague::Trace trace(\"SDL::Console::create_extension()\");\n\n if (id == \"Renderer\")\n return new SDL::Renderer();\n if (id == \"GLContext\") {\n Prague::Path path = RCManager::get_path(\"modulepath\");\n std::string name = path.lookup_file(\"Console\/SDLGL.so\");\n Prague::Plugin<Extension> * plugin = 0;\n if (name.empty())\n {\n\tstd::string msg =\n\t \"GLContext extension for SDL console not found in modulepath.\";\n\tthrow std::runtime_error(msg);\n }\n else {\n plugin = new Prague::Plugin<Extension>(name);\n _modules.push_back(plugin);\n _is_gl = 1;\n return plugin->get();\n }\n }\n if (id == \"DirectBuffer\")\n return new SDL::DirectBuffer();\n return 0;\n}\n\n\n\n\n\n\/\/ ---------------------------------------------------------------\n\/\/ externs\n\/\/ ---------------------------------------------------------------\n\nextern \"C\" ::Console::LoaderT<SDL::Console> *load() { return new Console::LoaderT<SDL::Console>(); }\n<commit_msg>Minor change, prevents SDLConsole from doing screwy things like treating 'shift' as a foreign-language character.<commit_after>\/*$Id$\n *\n * This source file is a part of the Berlin Project.\n * Copyright (C) 2000 Stefan Seefeld <stefan@berlin-consortium.org> \n * Copyright (C) 2001 Philip Philonenko <philonenko@orgacom.ru> \n * http:\/\/www.berlin-consortium.org\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Library General Public\n * License as published by the Free Software Foundation; either\n * version 2 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Library General Public License for more details.\n *\n * You should have received a copy of the GNU Library General Public\n * License along with this library; if not, write to the\n * Free Software Foundation, Inc., 675 Mass Ave, Cambridge,\n * MA 02139, USA.\n *\/\n\n#include <Prague\/Sys\/Memory.hh>\n#include <Prague\/Sys\/FdSet.hh>\n#include <Prague\/Sys\/Tracer.hh>\n#include <Prague\/Sys\/Path.hh>\n#include <Berlin\/RCManager.hh>\n#include <Berlin\/Logger.hh>\n\n#include <Console\/SDL\/Console.hh>\n#include <Console\/SDL\/Extension.hh>\n#include <Console\/SDL\/Drawable.hh>\n#include <Console\/SDL\/Pointer.hh>\n\nusing namespace Warsaw;\n\nnamespace\n{\n static void readEvent(SDL_Event &e)\n {\n Prague::Trace trace(\"readEvent()\");\n unsigned int t;\n std::cin >> t;\n e.type = static_cast<char>(t);\n switch (e.type)\n {\n case SDL_KEYDOWN:\n\t{\n\t std::cin >> t;\n\t e.key.keysym.sym = static_cast<SDLKey>(t);\n\t break;\n\t}\n case SDL_MOUSEMOTION:\n\t{\n\t std::cin >> e.motion.x\n\t\t >> e.motion.y;\n\t break;\n\t}\n case SDL_MOUSEBUTTONDOWN:\n case SDL_MOUSEBUTTONUP:\n\t{\n\t break;\n }\n }\n }\n \n static void writeEvent(SDL_Event &e)\n {\n Prague::Trace trace(\"writeEvent()\");\n std::cout << static_cast<unsigned int>(e.type) << ' ';\n switch (e.type)\n {\n case SDL_KEYDOWN:\n\t{\n\t std::cout << static_cast<unsigned int>(e.key.keysym.sym);\n\t break;\n\t}\n case SDL_MOUSEMOTION:\n\t{\n\t std::cout << e.motion.x << ' '\n\t\t << e.motion.y;\n\t break;\n\t}\n case SDL_MOUSEBUTTONDOWN:\n case SDL_MOUSEBUTTONUP:\n\t{\n\t break;\n\t}\n }\n std::cout << endl;\n }\n}; \/\/ namespace\n\n\n\n\n\n\/\/ ---------------------------------------------------------------\n\/\/ class SDL::Console (implementation)\n\/\/ ---------------------------------------------------------------\n\nSDL::Console::Console(int &argc, char **argv) :\n _autoplay(false),\n _is_gl(false),\n _pointer_mgr(new PointerManagerT<nonGLPointer>)\n{\n Prague::Trace trace(\"SDL::Console::Console\");\n Logger::log(Logger::loader) << \"trying to open SDL console\" << endl;\n\n SDL_Init(SDL_INIT_VIDEO);\n SDL_ShowCursor(SDL_DISABLE);\n SDL_EnableUNICODE(SDL_ENABLE);\n\n \/\/ FIXME: Get some 'real' values!\n _resolution[0] = 0.1;\n _resolution[1] = 0.1;\n\n _size[0] = 640;\n _size[1] = 480;\n\n _vsize[0] = 640;\n _vsize[1] = 480;\n\n pipe(_wakeupPipe);\n}\n\nSDL::Console::~Console()\n{\n Prague::Trace trace(\"SDL::Console::~Console\");\n\n for (dlist_t::iterator i = _drawables.begin();\n i != _drawables.end();\n i++) delete *i;\n close(_wakeupPipe[0]);\n close(_wakeupPipe[1]);\n SDL_Quit();\n}\n\nConsole::Pointer *SDL::Console::pointer(Raster_ptr raster)\n{\n Prague::Trace trace(\"SDL::Console::pointer\");\n return _pointer_mgr->create_pointer(raster);\n}\n\nConsole::Drawable *SDL::Console::drawable()\n{\n Prague::Trace trace(\"SDL::Console::drawable\");\n\n if (_drawables.empty())\n _drawables.push_back(new SDL::Drawable(0));\n \n return _drawables.front();\n}\n\nConsole::Drawable *\nSDL::Console::create_drawable(Warsaw::PixelCoord w,\n\t\t\t Warsaw::PixelCoord h, Warsaw::PixelCoord d)\n{\n Prague::Trace trace(\"SDL::Console::create_drawable\");\n\n _drawables.push_back(new SDL::Drawable(\"display-memory\", w, h, d));\n return _drawables.back();\n}\n\nConsole::Drawable *SDL::Console::reference_to_servant(Warsaw::Drawable_ptr drawable)\n{\n Prague::Trace trace(\"SDL::Console::reference_to_servant()\");\n \n PortableServer::Servant servant = Console::reference_to_servant(drawable);\n for (dlist_t::iterator i = _drawables.begin(); i != _drawables.end(); ++i)\n if (*i == servant) return *i;\n return 0;\n}\n\nvoid SDL::Console::activate_autoplay()\n{\n Prague::Trace trace(\"SDL::Console::activate_autoplay()\");\n\n \/\/ FIXME: This should do something.\n}\n\nvoid SDL::Console::device_info(std::ostream &os)\n{\n Prague::Trace trace(\"SDL::Console::device_info()\");\n\n os << \"sorry, device info isn't available for SDL at this time\" << std::endl;\n}\n\nInput::Event *SDL::Console::next_event()\n{\n Prague::Trace trace(\"SDL::Console::next_event()\");\n \n SDL_Event event;\n SDL_WaitEvent(&event);\n return synthesize(event);\n}\n\nvoid SDL::Console::wakeup()\n{\n Prague::Trace trace(\"SDL::Console::wakeup()\");\n\n char c = 'z'; write(_wakeupPipe[1],&c,1);\n}\n\nInput::Event *SDL::Console::synthesize(const SDL_Event &e)\n{\n Prague::Trace trace(\"SDL::Console::synthesize()\");\n\n Input::Event_var event = new Input::Event;\n switch (e.type)\n {\n case SDL_KEYDOWN:\n {\n\tInput::Toggle toggle;\n\ttoggle.actuation = Input::Toggle::press;\n\ttoggle.number = e.key.keysym.unicode;\n\tevent->length(1);\n\tevent[0].dev = 0;\n\tevent[0].attr.selection(toggle); event[0].attr._d(Input::key);\n\tbreak;\n }\n case SDL_MOUSEMOTION:\n {\n\t\/\/ grab waiting mouse events and skip to the last one\n\tSDL_Event move_events[64];\n\tSDL_PumpEvents();\n\tint num = SDL_PeepEvents(move_events, 64, SDL_GETEVENT, SDL_MOUSEMOTIONMASK);\n\tif (num > 0)\n\t {\n\t \/\/ Use last known position of mouse\n\t _position[0] = move_events[num-1].motion.x;\n\t _position[1] = move_events[num-1].motion.y;\n\t }\n\telse\n\t {\n\t \/\/ Use position from original event \n\t _position[0] = e.motion.x;\n\t _position[1] = e.motion.y;\n\t }\n\tInput::Position position;\n\tposition.x = _position[0]\/_resolution[0];\n\tposition.y = _position[1]\/_resolution[1];\n\tposition.z = 0;\n\tevent->length(1);\n\tevent[0].dev = 1;\n\tevent[0].attr.location(position);\n\tbreak;\n }\n case SDL_MOUSEBUTTONDOWN:\n case SDL_MOUSEBUTTONUP:\n {\n\tInput::Toggle toggle;\n\tif (e.type == SDL_MOUSEBUTTONDOWN)\n\t toggle.actuation = Input::Toggle::press;\n\telse\n\t toggle.actuation = Input::Toggle::release;\n\ttoggle.number = e.button.button; \n\tInput::Position position;\n\tposition.x = _position[0]\/_resolution[0];\n\tposition.y = _position[1]\/_resolution[1];\n\tposition.z = 0;\n\tevent->length(2);\n\tevent[0].dev = 1;\n\tevent[0].attr.selection(toggle); event[0].attr._d(Input::button);\n\tevent[1].dev = 1;\n\tevent[1].attr.location(position);\n\tbreak;\n }\n case SDL_QUIT:\n {\n\t\/\/ this is a CTRL+C sent to the controlling terminal. Berlin may be\n\t\/\/ already crashed, so terminate forcibly.\n\texit(0);\n\tbreak;\n }\n }\n\n return event._retn();\n}\n\n\nvoid SDL::Console::set_PointerManager(PointerManager * pm) {\n _pointer_mgr = pm;\n}\n\n\nConsole::Extension * SDL::Console::create_extension(const std::string & id)\n{\n Prague::Trace trace(\"SDL::Console::create_extension()\");\n\n if (id == \"Renderer\")\n return new SDL::Renderer();\n if (id == \"GLContext\") {\n Prague::Path path = RCManager::get_path(\"modulepath\");\n std::string name = path.lookup_file(\"Console\/SDLGL.so\");\n Prague::Plugin<Extension> * plugin = 0;\n if (name.empty())\n {\n\tstd::string msg =\n\t \"GLContext extension for SDL console not found in modulepath.\";\n\tthrow std::runtime_error(msg);\n }\n else {\n plugin = new Prague::Plugin<Extension>(name);\n _modules.push_back(plugin);\n _is_gl = 1;\n return plugin->get();\n }\n }\n if (id == \"DirectBuffer\")\n return new SDL::DirectBuffer();\n return 0;\n}\n\n\n\n\n\n\/\/ ---------------------------------------------------------------\n\/\/ externs\n\/\/ ---------------------------------------------------------------\n\nextern \"C\" ::Console::LoaderT<SDL::Console> *load() { return new Console::LoaderT<SDL::Console>(); }\n<|endoftext|>"} {"text":"<commit_before>#include \"Codec_repetition.hpp\"\n\nusing namespace aff3ct;\nusing namespace aff3ct::factory;\n\nconst std::string aff3ct::factory::Codec_repetition::name = \"Codec Repetition\";\nconst std::string aff3ct::factory::Codec_repetition::prefix = \"cdc\";\n\nCodec_repetition::parameters\n::parameters(const std::string prefix)\n: Codec ::parameters(Codec_repetition::name, prefix),\n Codec_SIHO::parameters(Codec_repetition::name, prefix),\n enc(new Encoder_repetition::parameters(\"enc\")),\n dec(new Decoder_repetition::parameters(\"dec\"))\n{\n\tCodec::parameters::enc = enc;\n\tCodec::parameters::dec = dec;\n}\n\nCodec_repetition::parameters\n::~parameters()\n{\n\tif (enc != nullptr) { delete enc; enc = nullptr; }\n\tif (dec != nullptr) { delete dec; dec = nullptr; }\n\n\tCodec::parameters::enc = nullptr;\n\tCodec::parameters::dec = nullptr;\n}\n\nCodec_repetition::parameters* Codec_repetition::parameters\n::clone() const\n{\n\tauto clone = new Codec_repetition::parameters(*this);\n\n\tif (enc != nullptr) { clone->enc = enc->clone(); }\n\tif (dec != nullptr) { clone->dec = dec->clone(); }\n\n\tclone->set_enc(clone->enc);\n\tclone->set_dec(clone->dec);\n\n\treturn clone;\n}\n\nvoid Codec_repetition::parameters\n::get_description(arg_map &req_args, arg_map &opt_args) const\n{\n\tCodec_SIHO::parameters::get_description(req_args, opt_args);\n\n\tenc->get_description(req_args, opt_args);\n\tdec->get_description(req_args, opt_args);\n\n\tauto pdec = dec->get_prefix();\n\n\treq_args.erase({pdec+\"-cw-size\", \"N\"});\n\treq_args.erase({pdec+\"-info-bits\", \"K\"});\n\topt_args.erase({pdec+\"-fra\", \"F\"});\n}\n\nvoid Codec_repetition::parameters\n::store(const arg_val_map &vals)\n{\n\tCodec_SIHO::parameters::store(vals);\n\n\tenc->store(vals);\n\n\tthis->dec->K = this->enc->K;\n\tthis->dec->N_cw = this->enc->N_cw;\n\tthis->dec->n_frames = this->enc->n_frames;\n\n\tdec->store(vals);\n\n\tthis->K = this->enc->K;\n\tthis->N_cw = this->enc->N_cw;\n\tthis->N = this->enc->N_cw;\n}\n\nvoid Codec_repetition::parameters\n::get_headers(std::map<std::string,header_list>& headers, const bool full) const\n{\n\tCodec_SIHO::parameters::get_headers(headers, full);\n\n\tenc->get_headers(headers, full);\n\tdec->get_headers(headers, full);\n}\n\ntemplate <typename B, typename Q>\nmodule::Codec_repetition<B,Q>* Codec_repetition::parameters\n::build(module::CRC<B> *crc) const\n{\n\treturn new module::Codec_repetition<B,Q>(*enc, *dec);\n\n\tthrow tools::cannot_allocate(__FILE__, __LINE__, __func__);\n}\n\ntemplate <typename B, typename Q>\nmodule::Codec_repetition<B,Q>* Codec_repetition\n::build(const parameters ¶ms, module::CRC<B> *crc)\n{\n\treturn params.template build<B,Q>();\n}\n\n\/\/ ==================================================================================== explicit template instantiation\n#include \"Tools\/types.h\"\n#ifdef MULTI_PREC\ntemplate aff3ct::module::Codec_repetition<B_8 ,Q_8 >* aff3ct::factory::Codec_repetition::parameters::build<B_8 ,Q_8 >(aff3ct::module::CRC<B_8 >*) const;\ntemplate aff3ct::module::Codec_repetition<B_16,Q_16>* aff3ct::factory::Codec_repetition::parameters::build<B_16,Q_16>(aff3ct::module::CRC<B_16>*) const;\ntemplate aff3ct::module::Codec_repetition<B_32,Q_32>* aff3ct::factory::Codec_repetition::parameters::build<B_32,Q_32>(aff3ct::module::CRC<B_32>*) const;\ntemplate aff3ct::module::Codec_repetition<B_64,Q_64>* aff3ct::factory::Codec_repetition::parameters::build<B_64,Q_64>(aff3ct::module::CRC<B_64>*) const;\ntemplate aff3ct::module::Codec_repetition<B_8 ,Q_8 >* aff3ct::factory::Codec_repetition::build<B_8 ,Q_8 >(const aff3ct::factory::Codec_repetition::parameters&, aff3ct::module::CRC<B_8 >*);\ntemplate aff3ct::module::Codec_repetition<B_16,Q_16>* aff3ct::factory::Codec_repetition::build<B_16,Q_16>(const aff3ct::factory::Codec_repetition::parameters&, aff3ct::module::CRC<B_16>*);\ntemplate aff3ct::module::Codec_repetition<B_32,Q_32>* aff3ct::factory::Codec_repetition::build<B_32,Q_32>(const aff3ct::factory::Codec_repetition::parameters&, aff3ct::module::CRC<B_32>*);\ntemplate aff3ct::module::Codec_repetition<B_64,Q_64>* aff3ct::factory::Codec_repetition::build<B_64,Q_64>(const aff3ct::factory::Codec_repetition::parameters&, aff3ct::module::CRC<B_64>*);\n#else\ntemplate aff3ct::module::Codec_repetition<B,Q>* aff3ct::factory::Codec_repetition::parameters::build<B,Q>(aff3ct::module::CRC<B>*) const;\ntemplate aff3ct::module::Codec_repetition<B,Q>* aff3ct::factory::Codec_repetition::build<B,Q>(const aff3ct::factory::Codec_repetition::parameters&, aff3ct::module::CRC<B>*);\n#endif\n\/\/ ==================================================================================== explicit template instantiation\n<commit_msg>Fix rep buffered param.<commit_after>#include \"Codec_repetition.hpp\"\n\nusing namespace aff3ct;\nusing namespace aff3ct::factory;\n\nconst std::string aff3ct::factory::Codec_repetition::name = \"Codec Repetition\";\nconst std::string aff3ct::factory::Codec_repetition::prefix = \"cdc\";\n\nCodec_repetition::parameters\n::parameters(const std::string prefix)\n: Codec ::parameters(Codec_repetition::name, prefix),\n Codec_SIHO::parameters(Codec_repetition::name, prefix),\n enc(new Encoder_repetition::parameters(\"enc\")),\n dec(new Decoder_repetition::parameters(\"dec\"))\n{\n\tCodec::parameters::enc = enc;\n\tCodec::parameters::dec = dec;\n}\n\nCodec_repetition::parameters\n::~parameters()\n{\n\tif (enc != nullptr) { delete enc; enc = nullptr; }\n\tif (dec != nullptr) { delete dec; dec = nullptr; }\n\n\tCodec::parameters::enc = nullptr;\n\tCodec::parameters::dec = nullptr;\n}\n\nCodec_repetition::parameters* Codec_repetition::parameters\n::clone() const\n{\n\tauto clone = new Codec_repetition::parameters(*this);\n\n\tif (enc != nullptr) { clone->enc = enc->clone(); }\n\tif (dec != nullptr) { clone->dec = dec->clone(); }\n\n\tclone->set_enc(clone->enc);\n\tclone->set_dec(clone->dec);\n\n\treturn clone;\n}\n\nvoid Codec_repetition::parameters\n::get_description(arg_map &req_args, arg_map &opt_args) const\n{\n\tCodec_SIHO::parameters::get_description(req_args, opt_args);\n\n\tenc->get_description(req_args, opt_args);\n\tdec->get_description(req_args, opt_args);\n\n\tauto pdec = dec->get_prefix();\n\n\treq_args.erase({pdec+\"-cw-size\", \"N\"});\n\treq_args.erase({pdec+\"-info-bits\", \"K\"});\n\topt_args.erase({pdec+\"-no-buff\" });\n\topt_args.erase({pdec+\"-fra\", \"F\"});\n}\n\nvoid Codec_repetition::parameters\n::store(const arg_val_map &vals)\n{\n\tCodec_SIHO::parameters::store(vals);\n\n\tenc->store(vals);\n\n\tthis->dec->K = this->enc->K;\n\tthis->dec->N_cw = this->enc->N_cw;\n\tthis->dec->buffered = this->enc->buffered;\n\tthis->dec->n_frames = this->enc->n_frames;\n\n\tdec->store(vals);\n\n\tthis->K = this->enc->K;\n\tthis->N_cw = this->enc->N_cw;\n\tthis->N = this->enc->N_cw;\n}\n\nvoid Codec_repetition::parameters\n::get_headers(std::map<std::string,header_list>& headers, const bool full) const\n{\n\tCodec_SIHO::parameters::get_headers(headers, full);\n\n\tenc->get_headers(headers, full);\n\tdec->get_headers(headers, full);\n}\n\ntemplate <typename B, typename Q>\nmodule::Codec_repetition<B,Q>* Codec_repetition::parameters\n::build(module::CRC<B> *crc) const\n{\n\treturn new module::Codec_repetition<B,Q>(*enc, *dec);\n\n\tthrow tools::cannot_allocate(__FILE__, __LINE__, __func__);\n}\n\ntemplate <typename B, typename Q>\nmodule::Codec_repetition<B,Q>* Codec_repetition\n::build(const parameters ¶ms, module::CRC<B> *crc)\n{\n\treturn params.template build<B,Q>();\n}\n\n\/\/ ==================================================================================== explicit template instantiation\n#include \"Tools\/types.h\"\n#ifdef MULTI_PREC\ntemplate aff3ct::module::Codec_repetition<B_8 ,Q_8 >* aff3ct::factory::Codec_repetition::parameters::build<B_8 ,Q_8 >(aff3ct::module::CRC<B_8 >*) const;\ntemplate aff3ct::module::Codec_repetition<B_16,Q_16>* aff3ct::factory::Codec_repetition::parameters::build<B_16,Q_16>(aff3ct::module::CRC<B_16>*) const;\ntemplate aff3ct::module::Codec_repetition<B_32,Q_32>* aff3ct::factory::Codec_repetition::parameters::build<B_32,Q_32>(aff3ct::module::CRC<B_32>*) const;\ntemplate aff3ct::module::Codec_repetition<B_64,Q_64>* aff3ct::factory::Codec_repetition::parameters::build<B_64,Q_64>(aff3ct::module::CRC<B_64>*) const;\ntemplate aff3ct::module::Codec_repetition<B_8 ,Q_8 >* aff3ct::factory::Codec_repetition::build<B_8 ,Q_8 >(const aff3ct::factory::Codec_repetition::parameters&, aff3ct::module::CRC<B_8 >*);\ntemplate aff3ct::module::Codec_repetition<B_16,Q_16>* aff3ct::factory::Codec_repetition::build<B_16,Q_16>(const aff3ct::factory::Codec_repetition::parameters&, aff3ct::module::CRC<B_16>*);\ntemplate aff3ct::module::Codec_repetition<B_32,Q_32>* aff3ct::factory::Codec_repetition::build<B_32,Q_32>(const aff3ct::factory::Codec_repetition::parameters&, aff3ct::module::CRC<B_32>*);\ntemplate aff3ct::module::Codec_repetition<B_64,Q_64>* aff3ct::factory::Codec_repetition::build<B_64,Q_64>(const aff3ct::factory::Codec_repetition::parameters&, aff3ct::module::CRC<B_64>*);\n#else\ntemplate aff3ct::module::Codec_repetition<B,Q>* aff3ct::factory::Codec_repetition::parameters::build<B,Q>(aff3ct::module::CRC<B>*) const;\ntemplate aff3ct::module::Codec_repetition<B,Q>* aff3ct::factory::Codec_repetition::build<B,Q>(const aff3ct::factory::Codec_repetition::parameters&, aff3ct::module::CRC<B>*);\n#endif\n\/\/ ==================================================================================== explicit template instantiation\n<|endoftext|>"} {"text":"<commit_before>\/* logs.cc\n Eric Robert, 9 October 2013\n Copyright (c) 2013 Datacratic. All rights reserved.\n\n Basic logs\n*\/\n\n#include \"soa\/service\/logs.h\"\n#include \"jml\/utils\/exc_check.h\"\n\n#include <iostream>\n#include <mutex>\n#include <unordered_map>\n#include <vector>\n\nnamespace Datacratic {\n\nvoid Logging::ConsoleWriter::head(char const * timestamp,\n char const * name,\n char const * function,\n char const * file,\n int line) {\n if(color) {\n stream << timestamp << \" \" << \"\\033[1;32m\" << name << \" \";\n }\n else {\n stream << timestamp << \" \" << name << \" \";\n }\n}\n\nvoid Logging::ConsoleWriter::body(std::string const & content) {\n if(color) {\n stream << \"\\033[1;34m\";\n stream.write(content.c_str(), content.size() - 1);\n stream << \"\\033[0m\\n\";\n }\n else {\n stream << content;\n }\n\n std::cerr << stream.str();\n stream.str(\"\");\n}\n\nvoid Logging::FileWriter::head(char const * timestamp,\n char const * name,\n char const * function,\n char const * file,\n int line) {\n stream << timestamp << \" \" << name << \" \";\n}\n\nvoid Logging::FileWriter::body(std::string const & content) {\n file << stream.str() << content;\n stream.str(\"\");\n}\n\nvoid Logging::FileWriter::open(char const * filename, char const mode) {\n if(mode == 'a')\n file.open(filename, std::ofstream::app);\n else if (mode == 'w')\n file.open(filename);\n else\n throw ML::Exception(\"File mode not recognized\");\n\n if(!file) {\n std::cerr << \"unable to open log file '\" << filename << \"'\" << std::endl;\n }\n}\n\nvoid Logging::JsonWriter::head(char const * timestamp,\n char const * name,\n char const * function,\n char const * file,\n int line) {\n stream << \"{\\\"time\\\":\\\"\" << timestamp\n << \"\\\",\\\"name\\\":\\\"\" << name\n << \"\\\",\\\"call\\\":\\\"\" << function\n << \"\\\",\\\"file\\\":\\\"\" << file\n << \"\\\",\\\"line\\\":\" << line\n << \",\\\"text\\\":\\\"\";\n}\n\nvoid Logging::JsonWriter::body(std::string const & content) {\n stream.write(content.c_str(), content.size() - 1);\n stream << \"\\\"}\\n\";\n if(!writer) {\n std::cerr << stream.str();\n }\n else {\n writer->body(stream.str());\n }\n\n stream.str(\"\");\n}\n\nnamespace {\n\nstruct Registry {\n std::mutex lock;\n std::unordered_map<std::string, std::unique_ptr<Logging::CategoryData> > categories;\n};\n\nRegistry& getRegistry() {\n \/\/ Will leak but that's on program exit so who cares.\n static Registry* registry = new Registry;\n\n return *registry;\n}\n\n} \/\/ namespace anonymous\n\nstruct Logging::CategoryData {\n bool initialized;\n bool enabled;\n char const * name;\n std::shared_ptr<Writer> writer;\n std::stringstream stream;\n\n CategoryData * parent;\n std::vector<CategoryData *> children;\n\n static CategoryData * getRoot();\n static CategoryData * get(char const * name);\n\n static CategoryData * create(char const * name, char const * super, bool enabled);\n static void destroy(CategoryData * name);\n\n void activate(bool recurse = true);\n void deactivate(bool recurse = true);\n void writeTo(std::shared_ptr<Writer> output, bool recurse = true);\n\nprivate:\n\n CategoryData(char const * name, bool enabled) :\n initialized(false),\n enabled(enabled),\n name(name),\n parent(nullptr) {\n }\n\n};\n\nLogging::CategoryData * Logging::CategoryData::get(char const * name) {\n Registry& registry = getRegistry();\n\n auto it = registry.categories.find(name);\n return it != registry.categories.end() ? it->second.get() : nullptr;\n}\n\nLogging::CategoryData * Logging::CategoryData::getRoot() {\n CategoryData * root = get(\"*\");\n if (root) return root;\n\n getRegistry().categories[\"*\"].reset(root = new CategoryData(\"*\", true \/* enabled *\/));\n root->parent = root;\n root->writer = std::make_shared<ConsoleWriter>();\n\n return root;\n}\n\nLogging::CategoryData * Logging::CategoryData::create(char const * name, char const * super, bool enabled) {\n Registry& registry = getRegistry();\n std::lock_guard<std::mutex> guard(registry.lock);\n\n CategoryData * root = getRoot();\n CategoryData * data = get(name);\n\n if (!data) {\n registry.categories[name].reset(data = new CategoryData(name, enabled));\n }\n else {\n ExcCheck(!data->initialized,\n \"making duplicate category: \" + std::string(name));\n }\n\n data->initialized = true;\n\n data->parent = get(super);\n if (!data->parent) {\n registry.categories[super].reset(data->parent = new CategoryData(super, enabled));\n }\n\n data->parent->children.push_back(data);\n\n if (data->parent->initialized) {\n data->writer = data->parent->writer;\n }\n else {\n data->writer = root->writer;\n }\n\n return data;\n}\n\nvoid Logging::CategoryData::destroy(CategoryData * data) {\n if (data->parent == data) return;\n\n Registry& registry = getRegistry();\n std::string name = data->name;\n\n std::lock_guard<std::mutex> guard(registry.lock);\n\n auto dataIt = registry.categories.find(name);\n ExcCheck(dataIt != registry.categories.end(),\n \"double destroy of a category: \" + name);\n\n auto& children = data->parent->children;\n\n auto childIt = std::find(children.begin(), children.end(), data);\n if (childIt != children.end()) {\n children.erase(childIt);\n }\n\n CategoryData* root = getRoot();\n for (auto& child : data->children) {\n child->parent = root;\n }\n\n registry.categories.erase(dataIt);\n}\n\n\nvoid Logging::CategoryData::activate(bool recurse) {\n enabled = true;\n if(recurse) {\n for(auto item : children) {\n item->activate(recurse);\n }\n }\n}\n\nvoid Logging::CategoryData::deactivate(bool recurse) {\n enabled = false;\n if(recurse) {\n for(auto item : children) {\n item->deactivate(recurse);\n }\n }\n}\n\nvoid Logging::CategoryData::writeTo(std::shared_ptr<Writer> output, bool recurse) {\n writer = output;\n if(recurse) {\n for(auto item : children) {\n item->writeTo(output, recurse);\n }\n }\n}\n\nLogging::Category& Logging::Category::root() {\n static Category root(CategoryData::getRoot());\n return root;\n}\n\nLogging::Category::Category(CategoryData * data) :\n data(data) {\n}\n\nLogging::Category::Category(char const * name, Category & super, bool enabled) :\n data(CategoryData::create(name, super.name(), enabled)) {\n}\n\nLogging::Category::Category(char const * name, char const * super, bool enabled) :\n data(CategoryData::create(name, super, enabled)) {\n}\n\nLogging::Category::Category(char const * name, bool enabled) :\n data(CategoryData::create(name, \"*\", enabled)) {\n}\n\nLogging::Category::~Category()\n{\n CategoryData::destroy(data);\n}\n\nchar const * Logging::Category::name() const {\n return data->name;\n}\n\nbool Logging::Category::isEnabled() const {\n return data->enabled;\n}\n\nbool Logging::Category::isDisabled() const {\n return !data->enabled;\n}\n\nauto Logging::Category::getWriter() const -> std::shared_ptr<Writer> const &\n{\n return data->writer;\n}\n\nvoid Logging::Category::activate(bool recurse) {\n data->activate(recurse);\n}\n\nvoid Logging::Category::deactivate(bool recurse) {\n data->deactivate(recurse);\n}\n\nvoid Logging::Category::writeTo(std::shared_ptr<Writer> output, bool recurse) {\n data->writeTo(output, recurse);\n}\n\nstd::ostream & Logging::Category::beginWrite(char const * fct, char const * file, int line) {\n timeval now;\n gettimeofday(&now, 0);\n char text[64];\n auto count = strftime(text, sizeof(text), \"%Y-%m-%d %H:%M:%S\", localtime(&now.tv_sec));\n int ms = now.tv_usec \/ 1000;\n sprintf(text + count, \".%03d\", ms);\n data->writer->head(text, data->name, fct, file, line);\n return data->stream;\n}\n\nvoid Logging::Printer::operator&(std::ostream & stream) {\n std::stringstream & text = (std::stringstream &) stream;\n category.getWriter()->body(text.str());\n text.str(\"\");\n}\n\nvoid Logging::Thrower::operator&(std::ostream & stream) {\n std::stringstream & text = (std::stringstream &) stream;\n std::string message(text.str());\n text.str(\"\");\n throw ML::Exception(message);\n}\n\n} \/\/ namespace Datacratic\n<commit_msg>hotfix for memory corruption caused by using a logging category from multiple threads.<commit_after>\/* logs.cc\n Eric Robert, 9 October 2013\n Copyright (c) 2013 Datacratic. All rights reserved.\n\n Basic logs\n*\/\n\n#include \"soa\/service\/logs.h\"\n#include \"jml\/utils\/exc_check.h\"\n\n#include <iostream>\n#include <mutex>\n#include <unordered_map>\n#include <vector>\n\nnamespace Datacratic {\n\nvoid Logging::ConsoleWriter::head(char const * timestamp,\n char const * name,\n char const * function,\n char const * file,\n int line) {\n if(color) {\n stream << timestamp << \" \" << \"\\033[1;32m\" << name << \" \";\n }\n else {\n stream << timestamp << \" \" << name << \" \";\n }\n}\n\nvoid Logging::ConsoleWriter::body(std::string const & content) {\n if(color) {\n stream << \"\\033[1;34m\";\n stream.write(content.c_str(), content.size() - 1);\n stream << \"\\033[0m\\n\";\n }\n else {\n stream << content;\n }\n\n std::cerr << stream.str();\n stream.str(\"\");\n}\n\nvoid Logging::FileWriter::head(char const * timestamp,\n char const * name,\n char const * function,\n char const * file,\n int line) {\n stream << timestamp << \" \" << name << \" \";\n}\n\nvoid Logging::FileWriter::body(std::string const & content) {\n file << stream.str() << content;\n stream.str(\"\");\n}\n\nvoid Logging::FileWriter::open(char const * filename, char const mode) {\n if(mode == 'a')\n file.open(filename, std::ofstream::app);\n else if (mode == 'w')\n file.open(filename);\n else\n throw ML::Exception(\"File mode not recognized\");\n\n if(!file) {\n std::cerr << \"unable to open log file '\" << filename << \"'\" << std::endl;\n }\n}\n\nvoid Logging::JsonWriter::head(char const * timestamp,\n char const * name,\n char const * function,\n char const * file,\n int line) {\n stream << \"{\\\"time\\\":\\\"\" << timestamp\n << \"\\\",\\\"name\\\":\\\"\" << name\n << \"\\\",\\\"call\\\":\\\"\" << function\n << \"\\\",\\\"file\\\":\\\"\" << file\n << \"\\\",\\\"line\\\":\" << line\n << \",\\\"text\\\":\\\"\";\n}\n\nvoid Logging::JsonWriter::body(std::string const & content) {\n stream.write(content.c_str(), content.size() - 1);\n stream << \"\\\"}\\n\";\n if(!writer) {\n std::cerr << stream.str();\n }\n else {\n writer->body(stream.str());\n }\n\n stream.str(\"\");\n}\n\nnamespace {\n\nstruct Registry {\n std::mutex lock;\n std::unordered_map<std::string, std::unique_ptr<Logging::CategoryData> > categories;\n};\n\nRegistry& getRegistry() {\n \/\/ Will leak but that's on program exit so who cares.\n static Registry* registry = new Registry;\n\n return *registry;\n}\n\n} \/\/ namespace anonymous\n\nstruct Logging::CategoryData {\n bool initialized;\n bool enabled;\n char const * name;\n std::shared_ptr<Writer> writer;\n std::stringstream stream;\n\n CategoryData * parent;\n std::vector<CategoryData *> children;\n\n static CategoryData * getRoot();\n static CategoryData * get(char const * name);\n\n static CategoryData * create(char const * name, char const * super, bool enabled);\n static void destroy(CategoryData * name);\n\n void activate(bool recurse = true);\n void deactivate(bool recurse = true);\n void writeTo(std::shared_ptr<Writer> output, bool recurse = true);\n\nprivate:\n\n CategoryData(char const * name, bool enabled) :\n initialized(false),\n enabled(enabled),\n name(name),\n parent(nullptr) {\n }\n\n};\n\nLogging::CategoryData * Logging::CategoryData::get(char const * name) {\n Registry& registry = getRegistry();\n\n auto it = registry.categories.find(name);\n return it != registry.categories.end() ? it->second.get() : nullptr;\n}\n\nLogging::CategoryData * Logging::CategoryData::getRoot() {\n CategoryData * root = get(\"*\");\n if (root) return root;\n\n getRegistry().categories[\"*\"].reset(root = new CategoryData(\"*\", true \/* enabled *\/));\n root->parent = root;\n root->writer = std::make_shared<ConsoleWriter>();\n\n return root;\n}\n\nLogging::CategoryData * Logging::CategoryData::create(char const * name, char const * super, bool enabled) {\n Registry& registry = getRegistry();\n std::lock_guard<std::mutex> guard(registry.lock);\n\n CategoryData * root = getRoot();\n CategoryData * data = get(name);\n\n if (!data) {\n registry.categories[name].reset(data = new CategoryData(name, enabled));\n }\n else {\n ExcCheck(!data->initialized,\n \"making duplicate category: \" + std::string(name));\n }\n\n data->initialized = true;\n\n data->parent = get(super);\n if (!data->parent) {\n registry.categories[super].reset(data->parent = new CategoryData(super, enabled));\n }\n\n data->parent->children.push_back(data);\n\n if (data->parent->initialized) {\n data->writer = data->parent->writer;\n }\n else {\n data->writer = root->writer;\n }\n\n return data;\n}\n\nvoid Logging::CategoryData::destroy(CategoryData * data) {\n if (data->parent == data) return;\n\n Registry& registry = getRegistry();\n std::string name = data->name;\n\n std::lock_guard<std::mutex> guard(registry.lock);\n\n auto dataIt = registry.categories.find(name);\n ExcCheck(dataIt != registry.categories.end(),\n \"double destroy of a category: \" + name);\n\n auto& children = data->parent->children;\n\n auto childIt = std::find(children.begin(), children.end(), data);\n if (childIt != children.end()) {\n children.erase(childIt);\n }\n\n CategoryData* root = getRoot();\n for (auto& child : data->children) {\n child->parent = root;\n }\n\n registry.categories.erase(dataIt);\n}\n\n\nvoid Logging::CategoryData::activate(bool recurse) {\n enabled = true;\n if(recurse) {\n for(auto item : children) {\n item->activate(recurse);\n }\n }\n}\n\nvoid Logging::CategoryData::deactivate(bool recurse) {\n enabled = false;\n if(recurse) {\n for(auto item : children) {\n item->deactivate(recurse);\n }\n }\n}\n\nvoid Logging::CategoryData::writeTo(std::shared_ptr<Writer> output, bool recurse) {\n writer = output;\n if(recurse) {\n for(auto item : children) {\n item->writeTo(output, recurse);\n }\n }\n}\n\nLogging::Category& Logging::Category::root() {\n static Category root(CategoryData::getRoot());\n return root;\n}\n\nLogging::Category::Category(CategoryData * data) :\n data(data) {\n}\n\nLogging::Category::Category(char const * name, Category & super, bool enabled) :\n data(CategoryData::create(name, super.name(), enabled)) {\n}\n\nLogging::Category::Category(char const * name, char const * super, bool enabled) :\n data(CategoryData::create(name, super, enabled)) {\n}\n\nLogging::Category::Category(char const * name, bool enabled) :\n data(CategoryData::create(name, \"*\", enabled)) {\n}\n\nLogging::Category::~Category()\n{\n CategoryData::destroy(data);\n}\n\nchar const * Logging::Category::name() const {\n return data->name;\n}\n\nbool Logging::Category::isEnabled() const {\n return data->enabled;\n}\n\nbool Logging::Category::isDisabled() const {\n return !data->enabled;\n}\n\nauto Logging::Category::getWriter() const -> std::shared_ptr<Writer> const &\n{\n return data->writer;\n}\n\nvoid Logging::Category::activate(bool recurse) {\n data->activate(recurse);\n}\n\nvoid Logging::Category::deactivate(bool recurse) {\n data->deactivate(recurse);\n}\n\nvoid Logging::Category::writeTo(std::shared_ptr<Writer> output, bool recurse) {\n data->writeTo(output, recurse);\n}\n\n\/\/ This lock is a quick-fix for the case where a category is used by multiple\n\/\/ threads. Note that this lock should either eventually be removed or replaced\n\/\/ by a per category lock. Unfortunately the current setup makes it very\n\/\/ difficult to pass the header information to the operator& so that everything\n\/\/ can be dumped in the stream in one go.\nnamespace { std::mutex loggingMutex; }\n\nstd::ostream & Logging::Category::beginWrite(char const * fct, char const * file, int line) {\n loggingMutex.lock();\n\n timeval now;\n gettimeofday(&now, 0);\n char text[64];\n auto count = strftime(text, sizeof(text), \"%Y-%m-%d %H:%M:%S\", localtime(&now.tv_sec));\n int ms = now.tv_usec \/ 1000;\n sprintf(text + count, \".%03d\", ms);\n data->writer->head(text, data->name, fct, file, line);\n return data->stream;\n}\n\nvoid Logging::Printer::operator&(std::ostream & stream) {\n std::stringstream & text = (std::stringstream &) stream;\n category.getWriter()->body(text.str());\n text.str(\"\");\n\n loggingMutex.unlock();\n}\n\nvoid Logging::Thrower::operator&(std::ostream & stream) {\n std::stringstream & text = (std::stringstream &) stream;\n std::string message(text.str());\n text.str(\"\");\n loggingMutex.unlock();\n\n throw ML::Exception(message);\n}\n\n} \/\/ namespace Datacratic\n<|endoftext|>"} {"text":"<commit_before>\/******************************************************************************\n * Copyright 2017 The Apollo Authors. All Rights Reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *****************************************************************************\/\n\n\/**\n * @file qp_spline_st_graph.cc\n **\/\n\n#include \"modules\/planning\/optimizer\/qp_spline_st_speed\/qp_spline_st_graph.h\"\n\n#include <algorithm>\n#include <string>\n#include <utility>\n\n#include \"modules\/common\/log.h\"\n\nnamespace apollo {\nnamespace planning {\n\nusing apollo::common::ErrorCode;\nusing apollo::common::Status;\nusing apollo::common::VehicleParam;\n\nQpSplineStGraph::QpSplineStGraph(\n const QpSplineStSpeedConfig& qp_spline_st_speed_config,\n const apollo::common::VehicleParam& veh_param)\n : qp_spline_st_speed_config_(qp_spline_st_speed_config),\n time_resolution_(\n qp_spline_st_speed_config_.total_time() \/\n qp_spline_st_speed_config_.number_of_discrete_graph_t()) {}\n\nvoid QpSplineStGraph::Init() {\n double curr_t = 0.0;\n for (uint32_t i = 0;\n i <= qp_spline_st_speed_config_.number_of_discrete_graph_t(); ++i) {\n t_knots_.push_back(curr_t);\n curr_t += time_resolution_;\n }\n spline_generator_.reset(new Spline1dGenerator(\n t_knots_, qp_spline_st_speed_config_.spline_order()));\n}\n\nStatus QpSplineStGraph::Search(const StGraphData& st_graph_data,\n const PathData& path_data,\n SpeedData* const speed_data) {\n init_point_ = st_graph_data.init_point();\n if (st_graph_data.path_data_length() <\n qp_spline_st_speed_config_.total_path_length()) {\n qp_spline_st_speed_config_.set_total_path_length(\n st_graph_data.path_data_length());\n }\n\n \/\/ TODO(all): update speed limit here\n \/\/ TODO(all): update config through veh physical limit here generate knots\n\n \/\/ initialize time resolution and\n Init();\n\n if (!ApplyConstraint(st_graph_data.obs_boundary()).ok()) {\n const std::string msg = \"Apply constraint failed!\";\n AERROR << msg;\n return Status(ErrorCode::PLANNING_ERROR, msg);\n }\n\n if (!ApplyKernel(st_graph_data.speed_limit()).ok()) {\n const std::string msg = \"Apply kernel failed!\";\n AERROR << msg;\n return Status(ErrorCode::PLANNING_ERROR, msg);\n }\n\n if (!Solve().ok()) {\n const std::string msg = \"Solve qp problem failed!\";\n AERROR << msg;\n return Status(ErrorCode::PLANNING_ERROR, msg);\n }\n\n \/\/ extract output\n speed_data->Clear();\n const Spline1d& spline = spline_generator_->spline();\n\n double time_resolution = qp_spline_st_speed_config_.output_time_resolution();\n double time = 0.0;\n while (time < qp_spline_st_speed_config_.total_time() + time_resolution) {\n double s = spline(time);\n double v = spline.derivative(time);\n double a = spline.second_order_derivative(time);\n double da = spline.third_order_derivative(time);\n speed_data->add_speed_point(s, time, v, a, da);\n time += time_resolution;\n }\n\n return Status::OK();\n}\n\nStatus QpSplineStGraph::ApplyConstraint(\n const std::vector<StGraphBoundary>& boundaries) {\n Spline1dConstraint* constraint =\n spline_generator_->mutable_spline_constraint();\n \/\/ position, velocity, acceleration\n\n if (!constraint->add_point_fx_constraint(0.0, 0.0)) {\n const std::string msg = \"add st start point constraint failed\";\n AERROR << msg;\n return Status(ErrorCode::PLANNING_ERROR, msg);\n }\n\n if (!constraint->add_point_derivative_constraint(0.0, init_point_.v())) {\n const std::string msg = \"add st start point velocity constraint failed!\";\n AERROR << msg;\n return Status(ErrorCode::PLANNING_ERROR, msg);\n }\n\n if (!constraint->add_point_second_derivative_constraint(0.0,\n init_point_.a())) {\n const std::string msg =\n \"add st start point acceleration constraint failed!\";\n AERROR << msg;\n return Status(ErrorCode::PLANNING_ERROR, msg);\n }\n\n if (!constraint->add_point_second_derivative_constraint(\n spline_generator_->spline().x_knots().back(), 0.0)) {\n const std::string msg = \"add st end point acceleration constraint failed!\";\n AERROR << msg;\n return Status(ErrorCode::PLANNING_ERROR, msg);\n }\n\n \/\/ monotone constraint\n if (!constraint->add_monotone_fx_inequality_constraint_at_knots()) {\n const std::string msg = \"add monotonicity constraint failed!\";\n AERROR << msg;\n return Status(ErrorCode::PLANNING_ERROR, msg);\n }\n\n \/\/ smoothness constraint\n if (!constraint->add_third_derivative_smooth_constraint()) {\n const std::string msg = \"add smoothness joint constraint failed!\";\n AERROR << msg;\n return Status(ErrorCode::PLANNING_ERROR, msg);\n }\n\n \/\/ boundary constraint\n std::vector<double> s_upper_bound;\n std::vector<double> s_lower_bound;\n\n for (const double curr_t : t_knots_) {\n double lower_s = 0.0;\n double upper_s = 0.0;\n GetSConstraintByTime(boundaries, curr_t,\n qp_spline_st_speed_config_.total_path_length(),\n &upper_s, &lower_s);\n s_upper_bound.push_back(upper_s);\n s_lower_bound.push_back(lower_s);\n }\n if (!constraint->add_fx_boundary(t_knots_, s_lower_bound, s_upper_bound)) {\n const std::string msg = \"Fail to apply obstacle constraint\";\n AERROR << msg;\n return Status(ErrorCode::PLANNING_ERROR, msg);\n }\n \/\/ TODO(Liangliang):\n \/\/ add speed constraint and other limits according to adu\/planning\n return Status::OK();\n}\n\nStatus QpSplineStGraph::ApplyKernel(const SpeedLimit& speed_limit) {\n Spline1dKernel* spline_kernel = spline_generator_->mutable_spline_kernel();\n\n if (qp_spline_st_speed_config_.speed_kernel_weight() > 0) {\n spline_kernel->add_derivative_kernel_matrix(\n qp_spline_st_speed_config_.speed_kernel_weight());\n }\n\n if (qp_spline_st_speed_config_.accel_kernel_weight() > 0) {\n spline_kernel->add_second_order_derivative_matrix(\n qp_spline_st_speed_config_.accel_kernel_weight());\n }\n\n if (qp_spline_st_speed_config_.jerk_kernel_weight() > 0) {\n spline_kernel->add_third_order_derivative_matrix(\n qp_spline_st_speed_config_.jerk_kernel_weight());\n }\n\n \/\/ TODO(all): add reference speed profile for different main decision\n std::vector<double> s_vec;\n if (speed_limit.speed_limits().size() == 0) {\n return Status(ErrorCode::PLANNING_ERROR,\n \"Fail to apply_kernel due to empty speed limits.\");\n }\n double dist_ref = 0.0;\n for (uint32_t i = 0;\n i <= qp_spline_st_speed_config_.number_of_discrete_graph_t(); ++i) {\n s_vec.push_back(dist_ref);\n dist_ref += time_resolution_ * speed_limit.get_speed_limit(dist_ref);\n }\n \/\/ TODO: change reference line kernel to configurable version\n spline_kernel->add_reference_line_kernel_matrix(t_knots_, s_vec, 1);\n return Status::OK();\n}\n\nStatus QpSplineStGraph::Solve() {\n return spline_generator_->solve()\n ? Status::OK()\n : Status(ErrorCode::PLANNING_ERROR, \"QpSplineStGraph::solve\");\n}\n\nStatus QpSplineStGraph::AddFollowReferenceLineKernel(\n const StGraphBoundary& follow_boundary) {\n if (follow_boundary.boundary_type() !=\n StGraphBoundary::BoundaryType::FOLLOW) {\n std::string msg = common::util::StrCat(\n \"Fail to add follow reference line kernel because boundary type is \",\n \"incorrect. type: \", static_cast<int>(follow_boundary.boundary_type()),\n \".\");\n return Status(ErrorCode::PLANNING_ERROR, msg);\n }\n\n auto* spline_kernel = spline_generator_->mutable_spline_kernel();\n std::vector<double> ref_s;\n for (const double curr_t : t_knots_) {\n double s_upper = 0.0;\n double s_lower = 0.0;\n if (follow_boundary.get_s_boundary_position(curr_t, &s_upper, &s_lower)) {\n ref_s.push_back(s_upper - follow_boundary.characteristic_length());\n }\n ref_s.push_back(s_upper);\n }\n\n spline_kernel->add_reference_line_kernel_matrix(t_knots_, ref_s, 1.0);\n return Status::OK();\n}\n\nStatus QpSplineStGraph::GetSConstraintByTime(\n const std::vector<StGraphBoundary>& boundaries, const double time,\n const double total_path_s, double* const s_upper_bound,\n double* const s_lower_bound) const {\n *s_upper_bound =\n std::min(total_path_s, time * qp_spline_st_speed_config_.max_speed());\n\n for (const StGraphBoundary& boundary : boundaries) {\n double s_upper = 0.0;\n double s_lower = 0.0;\n\n if (!boundary.get_s_boundary_position(time, &s_upper, &s_lower)) {\n continue;\n }\n\n if (boundary.boundary_type() == StGraphBoundary::BoundaryType::STOP ||\n boundary.boundary_type() == StGraphBoundary::BoundaryType::FOLLOW ||\n boundary.boundary_type() == StGraphBoundary::BoundaryType::YIELD) {\n *s_upper_bound = std::fmin(*s_upper_bound, s_upper);\n } else {\n *s_lower_bound = std::fmax(*s_lower_bound, s_lower);\n }\n }\n\n return Status::OK();\n}\n} \/\/ namespace planning\n} \/\/ namespace apollo\n<commit_msg>used follow boundary reference line<commit_after>\/******************************************************************************\n * Copyright 2017 The Apollo Authors. All Rights Reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *****************************************************************************\/\n\n\/**\n * @file qp_spline_st_graph.cc\n **\/\n\n#include \"modules\/planning\/optimizer\/qp_spline_st_speed\/qp_spline_st_graph.h\"\n\n#include <algorithm>\n#include <string>\n#include <utility>\n\n#include \"modules\/common\/log.h\"\n\nnamespace apollo {\nnamespace planning {\n\nusing apollo::common::ErrorCode;\nusing apollo::common::Status;\nusing apollo::common::VehicleParam;\n\nQpSplineStGraph::QpSplineStGraph(\n const QpSplineStSpeedConfig& qp_spline_st_speed_config,\n const apollo::common::VehicleParam& veh_param)\n : qp_spline_st_speed_config_(qp_spline_st_speed_config),\n time_resolution_(\n qp_spline_st_speed_config_.total_time() \/\n qp_spline_st_speed_config_.number_of_discrete_graph_t()) {}\n\nvoid QpSplineStGraph::Init() {\n double curr_t = 0.0;\n for (uint32_t i = 0;\n i <= qp_spline_st_speed_config_.number_of_discrete_graph_t(); ++i) {\n t_knots_.push_back(curr_t);\n curr_t += time_resolution_;\n }\n spline_generator_.reset(new Spline1dGenerator(\n t_knots_, qp_spline_st_speed_config_.spline_order()));\n}\n\nStatus QpSplineStGraph::Search(const StGraphData& st_graph_data,\n const PathData& path_data,\n SpeedData* const speed_data) {\n init_point_ = st_graph_data.init_point();\n if (st_graph_data.path_data_length() <\n qp_spline_st_speed_config_.total_path_length()) {\n qp_spline_st_speed_config_.set_total_path_length(\n st_graph_data.path_data_length());\n }\n\n \/\/ TODO(all): update speed limit here\n \/\/ TODO(all): update config through veh physical limit here generate knots\n\n \/\/ initialize time resolution and\n Init();\n\n if (!ApplyConstraint(st_graph_data.obs_boundary()).ok()) {\n const std::string msg = \"Apply constraint failed!\";\n AERROR << msg;\n return Status(ErrorCode::PLANNING_ERROR, msg);\n }\n\n if (!ApplyKernel(st_graph_data.speed_limit()).ok()) {\n const std::string msg = \"Apply kernel failed!\";\n AERROR << msg;\n return Status(ErrorCode::PLANNING_ERROR, msg);\n }\n\n if (!Solve().ok()) {\n const std::string msg = \"Solve qp problem failed!\";\n AERROR << msg;\n return Status(ErrorCode::PLANNING_ERROR, msg);\n }\n\n \/\/ extract output\n speed_data->Clear();\n const Spline1d& spline = spline_generator_->spline();\n\n double time_resolution = qp_spline_st_speed_config_.output_time_resolution();\n double time = 0.0;\n while (time < qp_spline_st_speed_config_.total_time() + time_resolution) {\n double s = spline(time);\n double v = spline.derivative(time);\n double a = spline.second_order_derivative(time);\n double da = spline.third_order_derivative(time);\n speed_data->add_speed_point(s, time, v, a, da);\n time += time_resolution;\n }\n\n return Status::OK();\n}\n\nStatus QpSplineStGraph::ApplyConstraint(\n const std::vector<StGraphBoundary>& boundaries) {\n Spline1dConstraint* constraint =\n spline_generator_->mutable_spline_constraint();\n \/\/ position, velocity, acceleration\n\n if (!constraint->add_point_fx_constraint(0.0, 0.0)) {\n const std::string msg = \"add st start point constraint failed\";\n AERROR << msg;\n return Status(ErrorCode::PLANNING_ERROR, msg);\n }\n\n if (!constraint->add_point_derivative_constraint(0.0, init_point_.v())) {\n const std::string msg = \"add st start point velocity constraint failed!\";\n AERROR << msg;\n return Status(ErrorCode::PLANNING_ERROR, msg);\n }\n\n if (!constraint->add_point_second_derivative_constraint(0.0,\n init_point_.a())) {\n const std::string msg =\n \"add st start point acceleration constraint failed!\";\n AERROR << msg;\n return Status(ErrorCode::PLANNING_ERROR, msg);\n }\n\n if (!constraint->add_point_second_derivative_constraint(\n spline_generator_->spline().x_knots().back(), 0.0)) {\n const std::string msg = \"add st end point acceleration constraint failed!\";\n AERROR << msg;\n return Status(ErrorCode::PLANNING_ERROR, msg);\n }\n\n \/\/ monotone constraint\n if (!constraint->add_monotone_fx_inequality_constraint_at_knots()) {\n const std::string msg = \"add monotonicity constraint failed!\";\n AERROR << msg;\n return Status(ErrorCode::PLANNING_ERROR, msg);\n }\n\n \/\/ smoothness constraint\n if (!constraint->add_third_derivative_smooth_constraint()) {\n const std::string msg = \"add smoothness joint constraint failed!\";\n AERROR << msg;\n return Status(ErrorCode::PLANNING_ERROR, msg);\n }\n\n \/\/ boundary constraint\n std::vector<double> s_upper_bound;\n std::vector<double> s_lower_bound;\n\n for (const double curr_t : t_knots_) {\n double lower_s = 0.0;\n double upper_s = 0.0;\n GetSConstraintByTime(boundaries, curr_t,\n qp_spline_st_speed_config_.total_path_length(),\n &upper_s, &lower_s);\n s_upper_bound.push_back(upper_s);\n s_lower_bound.push_back(lower_s);\n }\n if (!constraint->add_fx_boundary(t_knots_, s_lower_bound, s_upper_bound)) {\n const std::string msg = \"Fail to apply obstacle constraint\";\n AERROR << msg;\n return Status(ErrorCode::PLANNING_ERROR, msg);\n }\n \/\/ TODO(Liangliang):\n \/\/ add speed constraint and other limits according to adu\/planning\n return Status::OK();\n}\n\nStatus QpSplineStGraph::ApplyKernel(\n const std::vector<StGraphBoundary>& boundaries,\n const SpeedLimit& speed_limit) {\n Spline1dKernel* spline_kernel = spline_generator_->mutable_spline_kernel();\n\n if (qp_spline_st_speed_config_.speed_kernel_weight() > 0) {\n spline_kernel->add_derivative_kernel_matrix(\n qp_spline_st_speed_config_.speed_kernel_weight());\n }\n\n if (qp_spline_st_speed_config_.accel_kernel_weight() > 0) {\n spline_kernel->add_second_order_derivative_matrix(\n qp_spline_st_speed_config_.accel_kernel_weight());\n }\n\n if (qp_spline_st_speed_config_.jerk_kernel_weight() > 0) {\n spline_kernel->add_third_order_derivative_matrix(\n qp_spline_st_speed_config_.jerk_kernel_weight());\n }\n\n \/\/ add reference line for follow\n for (const auto& boundary : boundaries) {\n if (boundary.boundary_type() == StGraphBoundary::BoundaryType::FOLLOW) {\n AddFollowReferenceLineKernel(boundary);\n }\n }\n\n \/\/ TODO(all): add reference speed profile for different main decision\n std::vector<double> s_vec;\n if (speed_limit.speed_limits().size() == 0) {\n return Status(ErrorCode::PLANNING_ERROR,\n \"Fail to apply_kernel due to empty speed limits.\");\n }\n double dist_ref = 0.0;\n for (uint32_t i = 0;\n i <= qp_spline_st_speed_config_.number_of_discrete_graph_t(); ++i) {\n s_vec.push_back(dist_ref);\n dist_ref += time_resolution_ * speed_limit.get_speed_limit(dist_ref);\n }\n \/\/ TODO: change reference line kernel to configurable version\n spline_kernel->add_reference_line_kernel_matrix(t_knots_, s_vec, 1);\n\n return Status::OK();\n}\n\nStatus QpSplineStGraph::Solve() {\n return spline_generator_->solve()\n ? Status::OK()\n : Status(ErrorCode::PLANNING_ERROR, \"QpSplineStGraph::solve\");\n}\n\nStatus QpSplineStGraph::AddFollowReferenceLineKernel(\n const StGraphBoundary& follow_boundary) {\n if (follow_boundary.boundary_type() !=\n StGraphBoundary::BoundaryType::FOLLOW) {\n std::string msg = common::util::StrCat(\n \"Fail to add follow reference line kernel because boundary type is \",\n \"incorrect. type: \", static_cast<int>(follow_boundary.boundary_type()),\n \".\");\n return Status(ErrorCode::PLANNING_ERROR, msg);\n }\n\n auto* spline_kernel = spline_generator_->mutable_spline_kernel();\n std::vector<double> ref_s;\n for (const double curr_t : t_knots_) {\n double s_upper = 0.0;\n double s_lower = 0.0;\n if (follow_boundary.get_s_boundary_position(curr_t, &s_upper, &s_lower)) {\n ref_s.push_back(s_upper - follow_boundary.characteristic_length());\n }\n ref_s.push_back(s_upper);\n }\n\n spline_kernel->add_reference_line_kernel_matrix(t_knots_, ref_s, 1.0);\n return Status::OK();\n}\n\nStatus QpSplineStGraph::GetSConstraintByTime(\n const std::vector<StGraphBoundary>& boundaries, const double time,\n const double total_path_s, double* const s_upper_bound,\n double* const s_lower_bound) const {\n *s_upper_bound =\n std::min(total_path_s, time * qp_spline_st_speed_config_.max_speed());\n\n for (const StGraphBoundary& boundary : boundaries) {\n double s_upper = 0.0;\n double s_lower = 0.0;\n\n if (!boundary.get_s_boundary_position(time, &s_upper, &s_lower)) {\n continue;\n }\n\n if (boundary.boundary_type() == StGraphBoundary::BoundaryType::STOP ||\n boundary.boundary_type() == StGraphBoundary::BoundaryType::FOLLOW ||\n boundary.boundary_type() == StGraphBoundary::BoundaryType::YIELD) {\n *s_upper_bound = std::fmin(*s_upper_bound, s_upper);\n } else {\n *s_lower_bound = std::fmax(*s_lower_bound, s_lower);\n }\n }\n\n return Status::OK();\n}\n} \/\/ namespace planning\n} \/\/ namespace apollo\n<|endoftext|>"} {"text":"<commit_before><commit_msg>Refactoring: move Runfile out of unnamed namespace<commit_after><|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: dlgeps.hxx,v $\n *\n * $Revision: 1.6 $\n *\n * last change: $Author: sj $ $Date: 2002-08-15 09:23:15 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef _DLGEPS_HXX_\n#define _DLGEPS_HXX_\n#include <svtools\/fltcall.hxx>\n#include <vcl\/dialog.hxx>\n#include <vcl\/button.hxx>\n#include <vcl\/fixed.hxx>\n#include <vcl\/field.hxx>\n#include <vcl\/lstbox.hxx>\n#include <svtools\/stdctrl.hxx>\n\n\n\/*************************************************************************\n|*\n|* Dialog zum Einstellen von Filteroptionen\n|*\n\\************************************************************************\/\n\nclass FilterConfigItem;\nclass ResMgr;\n\nclass DlgExportEPS : public ModalDialog\n{\nprivate:\n\n FltCallDialogParameter& rFltCallPara;\n\n FixedLine aGrpPreview;\n CheckBox aCBPreviewTiff;\n CheckBox aCBPreviewEPSI;\n FixedLine aGrpVersion;\n RadioButton aRBLevel1;\n RadioButton aRBLevel2;\n FixedLine aGrpColor;\n RadioButton aRBColor;\n RadioButton aRBGrayscale;\n FixedLine aGrpCompression;\n RadioButton aRBCompressionLZW;\n RadioButton aRBCompressionNone;\n OKButton aBtnOK;\n CancelButton aBtnCancel;\n HelpButton aBtnHelp;\n\n FilterConfigItem* pConfigItem;\n ResMgr* pMgr;\n\n DECL_LINK( OK, void * );\n DECL_LINK( LEVEL1, void* );\n DECL_LINK( LEVEL2, void* );\n\npublic:\n DlgExportEPS( FltCallDialogParameter& rPara );\n ~DlgExportEPS();\n};\n\n#endif \/\/ _DLGEPS_HXX_\n<commit_msg>INTEGRATION: CWS ooo19126 (1.6.286); FILE MERGED 2005\/09\/05 15:12:35 rt 1.6.286.1: #i54170# Change license header: remove SISSL<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: dlgeps.hxx,v $\n *\n * $Revision: 1.7 $\n *\n * last change: $Author: rt $ $Date: 2005-09-09 02:44:20 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef _DLGEPS_HXX_\n#define _DLGEPS_HXX_\n#include <svtools\/fltcall.hxx>\n#include <vcl\/dialog.hxx>\n#include <vcl\/button.hxx>\n#include <vcl\/fixed.hxx>\n#include <vcl\/field.hxx>\n#include <vcl\/lstbox.hxx>\n#include <svtools\/stdctrl.hxx>\n\n\n\/*************************************************************************\n|*\n|* Dialog zum Einstellen von Filteroptionen\n|*\n\\************************************************************************\/\n\nclass FilterConfigItem;\nclass ResMgr;\n\nclass DlgExportEPS : public ModalDialog\n{\nprivate:\n\n FltCallDialogParameter& rFltCallPara;\n\n FixedLine aGrpPreview;\n CheckBox aCBPreviewTiff;\n CheckBox aCBPreviewEPSI;\n FixedLine aGrpVersion;\n RadioButton aRBLevel1;\n RadioButton aRBLevel2;\n FixedLine aGrpColor;\n RadioButton aRBColor;\n RadioButton aRBGrayscale;\n FixedLine aGrpCompression;\n RadioButton aRBCompressionLZW;\n RadioButton aRBCompressionNone;\n OKButton aBtnOK;\n CancelButton aBtnCancel;\n HelpButton aBtnHelp;\n\n FilterConfigItem* pConfigItem;\n ResMgr* pMgr;\n\n DECL_LINK( OK, void * );\n DECL_LINK( LEVEL1, void* );\n DECL_LINK( LEVEL2, void* );\n\npublic:\n DlgExportEPS( FltCallDialogParameter& rPara );\n ~DlgExportEPS();\n};\n\n#endif \/\/ _DLGEPS_HXX_\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n#include <cstdlib>\n#include <QtCore\/QBasicTimer>\n#include <QtCore\/QMetaType>\n#include <QtCore\/QMutexLocker>\n#include <QtCore\/QThread>\n#ifdef Q_OS_MAC\n#include <pthread.h>\n#endif\n\n#include \"Manager.h\"\n#include \"Object.h\"\n\n\/\/ Declarations for part of Qt's internal API\nQ_DECL_IMPORT const QVariant::Handler* qcoreVariantHandler();\nnamespace QVariantPrivate {\nQ_DECL_IMPORT void registerHandler(\n const int name, const QVariant::Handler *handler);\n}\n\nstatic const char* cCounterNames[] = {\n \"ClassCounter\",\n \"ObjectCounter\",\n \"QObjectCounter\",\n \"VariantCounter\",\n \"ClassSerial\",\n \"ObjectSerial\"\n};\n\nextern \"C\" void hsqml_dump_counters()\n{\n Q_ASSERT (gManager);\n if (gManager->checkLogLevel(1)) {\n for (int i=0; i<HsQMLManager::TotalCounters; i++) {\n gManager->log(QString().sprintf(\"%s = %d.\",\n cCounterNames[i], gManager->updateCounter(\n static_cast<HsQMLManager::CounterId>(i), 0)));\n }\n }\n}\n\nstatic void hooked_construct(QVariant::Private* p, const void* copy)\n{\n gManager->hookedConstruct(p, copy);\n}\n\nstatic void hooked_clear(QVariant::Private* p)\n{\n gManager->hookedClear(p);\n}\n\nManagerPointer gManager;\n\nHsQMLManager::HsQMLManager(\n void (*freeFun)(HsFunPtr),\n void (*freeStable)(HsStablePtr))\n : mLogLevel(0)\n , mAtExit(false)\n , mFreeFun(freeFun)\n , mFreeStable(freeStable)\n , mOriginalHandler(qcoreVariantHandler())\n , mHookedHandler(*mOriginalHandler)\n , mApp(NULL)\n , mLock(QMutex::Recursive)\n , mRunning(false)\n , mRunCount(0)\n , mStackBase(NULL)\n , mStartCb(NULL)\n , mJobsCb(NULL)\n , mYieldCb(NULL)\n , mActiveEngine(NULL)\n{\n \/\/ Get log level from environment\n const char* env = std::getenv(\"HSQML_DEBUG_LOG_LEVEL\");\n if (env) {\n setLogLevel(QString(env).toInt());\n }\n\n \/\/ Set hooked handler functions\n mHookedHandler.construct = &hooked_construct;\n mHookedHandler.clear = &hooked_clear;\n}\n\nvoid HsQMLManager::setLogLevel(int ll)\n{\n mLogLevel = ll;\n if (ll > 0 && !mAtExit) {\n if (atexit(&hsqml_dump_counters) == 0) {\n mAtExit = true;\n }\n else {\n log(\"Failed to register callback with atexit().\");\n }\n }\n}\n\nbool HsQMLManager::checkLogLevel(int ll)\n{\n return mLogLevel >= ll;\n}\n\nvoid HsQMLManager::log(const QString& msg)\n{\n std::cerr << \"HsQML: \" << msg.toStdString() << std::endl;\n}\n\nint HsQMLManager::updateCounter(CounterId id, int delta)\n{\n return mCounters[id].fetchAndAddRelaxed(delta);\n}\n\nvoid HsQMLManager::freeFun(HsFunPtr funPtr)\n{\n mFreeFun(funPtr);\n}\n\nvoid HsQMLManager::freeStable(HsStablePtr stablePtr)\n{\n mFreeStable(stablePtr);\n}\n\nvoid HsQMLManager::hookedConstruct(QVariant::Private* p, const void* copy)\n{\n char guard;\n mOriginalHandler->construct(p, copy);\n void* pp = reinterpret_cast<void*>(p);\n \/\/ The QVariant internals sometimes use a special code path for pointer\n \/\/ values which avoids calling the handler functions. This makes it\n \/\/ difficult to use them to keep a reference count. However, it's my\n \/\/ observation that this only affects transient QVariants created on the\n \/\/ stack inside the JavaScript engine's marshalling code. The persistent\n \/\/ QVariants stored in the heap are manipulated using a more restricted set\n \/\/ of operations which always use the handler functions. Hence, by assuming\n \/\/ that the stack can be discounted, it's possible to keep an accurate\n \/\/ count of heap references using these hooks.\n if ((pp < &guard || pp > mStackBase) && p->type == QMetaType::QObjectStar) {\n if (HsQMLObject* obj = dynamic_cast<HsQMLObject*>(p->data.o)) {\n HsQMLObjectProxy* proxy = obj->proxy();\n proxy->ref(HsQMLObjectProxy::Variant);\n proxy->tryGCLock();\n updateCounter(VariantCount, 1);\n }\n }\n}\n\nvoid HsQMLManager::hookedClear(QVariant::Private* p)\n{\n char guard;\n void* pp = reinterpret_cast<void*>(p);\n if ((pp < &guard || pp > mStackBase) && p->type == QMetaType::QObjectStar) {\n if (HsQMLObject* obj = dynamic_cast<HsQMLObject*>(p->data.o)) {\n obj->proxy()->deref(HsQMLObjectProxy::Variant);\n updateCounter(VariantCount, -1);\n }\n }\n mOriginalHandler->clear(p);\n}\n\nbool HsQMLManager::isEventThread()\n{\n return mApp && mApp->thread() == QThread::currentThread();\n}\n\nHsQMLManager::EventLoopStatus HsQMLManager::runEventLoop(\n HsQMLTrivialCb startCb,\n HsQMLTrivialCb jobsCb,\n HsQMLTrivialCb yieldCb)\n{\n QMutexLocker locker(&mLock);\n\n \/\/ Check if already running\n if (mRunning) {\n return HSQML_EVLOOP_ALREADY_RUNNING;\n }\n\n \/\/ Check if event loop bound to a different thread\n if (mApp && !isEventThread()) {\n return HSQML_EVLOOP_WRONG_THREAD;\n }\n\n#ifdef Q_OS_MAC\n if (!pthread_main_np()) {\n \/\/ Cocoa can only be run on the primordial thread and exec() doesn't\n \/\/ check this.\n return HSQML_EVLOOP_WRONG_THREAD;\n }\n#endif\n\n \/\/ Check for non-threaded RTS\n if (yieldCb) {\n HSQML_LOG(0,\n \"Warning: CPU cannot idle when using the non-threaded RTS.\");\n }\n\n \/\/ Perform one-time initialisation\n if (!mApp) {\n \/\/ Install hooked handler for QVariants\n QVariantPrivate::registerHandler(0, &mHookedHandler);\n\n \/\/ Register custom type\n qRegisterMetaType<HsQMLEngineConfig>(\"HsQMLEngineConfig\");\n\n \/\/ Create application object\n mApp = new HsQMLManagerApp();\n }\n\n \/\/ Save stack base and callbacks\n mStackBase = &locker;\n mStartCb = startCb;\n mJobsCb = jobsCb;\n mYieldCb = yieldCb;\n\n \/\/ Setup events\n QCoreApplication::postEvent(\n mApp, new QEvent(HsQMLManagerApp::StartedLoopEvent),\n Qt::HighEventPriority);\n QBasicTimer idleTimer;\n if (yieldCb) {\n idleTimer.start(0, mApp);\n }\n\n \/\/ Run loop\n int ret = mApp->exec();\n\n \/\/ Remove redundant events\n QCoreApplication::removePostedEvents(\n mApp, HsQMLManagerApp::RemoveGCLockEvent);\n\n \/\/ Cleanup callbacks\n freeFun(startCb);\n mStartCb = NULL;\n freeFun(jobsCb);\n mJobsCb = NULL;\n if (yieldCb) {\n freeFun(yieldCb);\n mYieldCb = NULL;\n }\n\n \/\/ Return\n if (ret == 0) {\n return HSQML_EVLOOP_OK;\n }\n else {\n QCoreApplication::removePostedEvents(\n mApp, HsQMLManagerApp::StartedLoopEvent);\n return HSQML_EVLOOP_OTHER_ERROR;\n }\n}\n\nHsQMLManager::EventLoopStatus HsQMLManager::requireEventLoop()\n{\n QMutexLocker locker(&mLock);\n if (mRunCount > 0) {\n mRunCount++;\n return HSQML_EVLOOP_OK;\n }\n else {\n return HSQML_EVLOOP_NOT_RUNNING;\n }\n}\n\nvoid HsQMLManager::releaseEventLoop()\n{\n QMutexLocker locker(&mLock);\n if (--mRunCount == 0) {\n QCoreApplication::postEvent(\n mApp, new QEvent(HsQMLManagerApp::StopLoopEvent),\n Qt::LowEventPriority);\n }\n}\n\nvoid HsQMLManager::notifyJobs()\n{\n QMutexLocker locker(&mLock);\n if (mRunCount > 0) {\n QCoreApplication::postEvent(\n mApp, new QEvent(HsQMLManagerApp::PendingJobsEvent));\n }\n}\n\nvoid HsQMLManager::createEngine(const HsQMLEngineConfig& config)\n{\n Q_ASSERT (mApp);\n QMetaObject::invokeMethod(\n mApp, \"createEngine\", Q_ARG(HsQMLEngineConfig, config));\n}\n\nvoid HsQMLManager::setActiveEngine(HsQMLEngine* engine)\n{\n Q_ASSERT(!mActiveEngine || !engine);\n mActiveEngine = engine;\n}\n\nHsQMLEngine* HsQMLManager::activeEngine()\n{\n return mActiveEngine;\n}\n\nvoid HsQMLManager::postObjectEvent(HsQMLObjectEvent* ev)\n{\n QCoreApplication::postEvent(mApp, ev);\n}\n\nHsQMLManagerApp::HsQMLManagerApp()\n : mArgC(1)\n , mArg0(0)\n , mArgV(&mArg0)\n , mApp(mArgC, &mArgV)\n{\n mApp.setQuitOnLastWindowClosed(false);\n}\n\nHsQMLManagerApp::~HsQMLManagerApp()\n{}\n\nvoid HsQMLManagerApp::customEvent(QEvent* ev)\n{\n switch (ev->type()) {\n case HsQMLManagerApp::StartedLoopEvent: {\n gManager->mRunning = true;\n gManager->mRunCount++;\n gManager->mLock.unlock();\n gManager->mStartCb();\n gManager->mJobsCb();\n break;}\n case HsQMLManagerApp::StopLoopEvent: {\n gManager->mLock.lock();\n const QObjectList& cs = gManager->mApp->children();\n while (!cs.empty()) {\n delete cs.front();\n }\n gManager->mRunning = false;\n gManager->mApp->mApp.quit();\n break;}\n case HsQMLManagerApp::PendingJobsEvent: {\n gManager->mJobsCb();\n break;}\n case HsQMLManagerApp::RemoveGCLockEvent: {\n static_cast<HsQMLObjectEvent*>(ev)->process();\n break;}\n }\n}\n\nvoid HsQMLManagerApp::timerEvent(QTimerEvent*)\n{\n Q_ASSERT(gManager->mYieldCb);\n gManager->mYieldCb();\n}\n\nvoid HsQMLManagerApp::createEngine(HsQMLEngineConfig config)\n{\n HsQMLEngine* engine = new HsQMLEngine(config);\n engine->setParent(this);\n}\n\nint HsQMLManagerApp::exec()\n{\n return mApp.exec();\n}\n\nextern \"C\" void hsqml_init(\n void (*freeFun)(HsFunPtr),\n void (*freeStable)(HsStablePtr))\n{\n if (gManager == NULL) {\n HsQMLManager* manager = new HsQMLManager(freeFun, freeStable);\n if (!gManager.testAndSetOrdered(NULL, manager)) {\n delete manager;\n }\n }\n}\n\nextern \"C\" HsQMLEventLoopStatus hsqml_evloop_run(\n HsQMLTrivialCb startCb,\n HsQMLTrivialCb jobsCb,\n HsQMLTrivialCb yieldCb)\n{\n return gManager->runEventLoop(startCb, jobsCb, yieldCb);\n}\n\nextern \"C\" HsQMLEventLoopStatus hsqml_evloop_require()\n{\n return gManager->requireEventLoop();\n}\n\nextern \"C\" void hsqml_evloop_release()\n{\n gManager->releaseEventLoop();\n}\n\nextern \"C\" void hsqml_evloop_notify_jobs()\n{\n gManager->notifyJobs();\n}\n\nextern \"C\" void hsqml_set_debug_loglevel(int ll)\n{\n Q_ASSERT (gManager);\n gManager->setLogLevel(ll);\n}\n<commit_msg>Fix crash when using Cmd-Q to exit program on MacOS.<commit_after>#include <iostream>\n#include <cstdlib>\n#include <QtCore\/QBasicTimer>\n#include <QtCore\/QMetaType>\n#include <QtCore\/QMutexLocker>\n#include <QtCore\/QThread>\n#ifdef Q_OS_MAC\n#include <pthread.h>\n#endif\n\n#include \"Manager.h\"\n#include \"Object.h\"\n\n\/\/ Declarations for part of Qt's internal API\nQ_DECL_IMPORT const QVariant::Handler* qcoreVariantHandler();\nnamespace QVariantPrivate {\nQ_DECL_IMPORT void registerHandler(\n const int name, const QVariant::Handler *handler);\n}\n\nstatic const char* cCounterNames[] = {\n \"ClassCounter\",\n \"ObjectCounter\",\n \"QObjectCounter\",\n \"VariantCounter\",\n \"ClassSerial\",\n \"ObjectSerial\"\n};\n\nextern \"C\" void hsqml_dump_counters()\n{\n Q_ASSERT (gManager);\n if (gManager->checkLogLevel(1)) {\n for (int i=0; i<HsQMLManager::TotalCounters; i++) {\n gManager->log(QString().sprintf(\"%s = %d.\",\n cCounterNames[i], gManager->updateCounter(\n static_cast<HsQMLManager::CounterId>(i), 0)));\n }\n }\n}\n\nstatic void hooked_construct(QVariant::Private* p, const void* copy)\n{\n gManager->hookedConstruct(p, copy);\n}\n\nstatic void hooked_clear(QVariant::Private* p)\n{\n gManager->hookedClear(p);\n}\n\nManagerPointer gManager;\n\nHsQMLManager::HsQMLManager(\n void (*freeFun)(HsFunPtr),\n void (*freeStable)(HsStablePtr))\n : mLogLevel(0)\n , mAtExit(false)\n , mFreeFun(freeFun)\n , mFreeStable(freeStable)\n , mOriginalHandler(qcoreVariantHandler())\n , mHookedHandler(*mOriginalHandler)\n , mApp(NULL)\n , mLock(QMutex::Recursive)\n , mRunning(false)\n , mRunCount(0)\n , mStackBase(NULL)\n , mStartCb(NULL)\n , mJobsCb(NULL)\n , mYieldCb(NULL)\n , mActiveEngine(NULL)\n{\n \/\/ Get log level from environment\n const char* env = std::getenv(\"HSQML_DEBUG_LOG_LEVEL\");\n if (env) {\n setLogLevel(QString(env).toInt());\n }\n\n \/\/ Set hooked handler functions\n mHookedHandler.construct = &hooked_construct;\n mHookedHandler.clear = &hooked_clear;\n}\n\nvoid HsQMLManager::setLogLevel(int ll)\n{\n mLogLevel = ll;\n if (ll > 0 && !mAtExit) {\n if (atexit(&hsqml_dump_counters) == 0) {\n mAtExit = true;\n }\n else {\n log(\"Failed to register callback with atexit().\");\n }\n }\n}\n\nbool HsQMLManager::checkLogLevel(int ll)\n{\n return mLogLevel >= ll;\n}\n\nvoid HsQMLManager::log(const QString& msg)\n{\n std::cerr << \"HsQML: \" << msg.toStdString() << std::endl;\n}\n\nint HsQMLManager::updateCounter(CounterId id, int delta)\n{\n return mCounters[id].fetchAndAddRelaxed(delta);\n}\n\nvoid HsQMLManager::freeFun(HsFunPtr funPtr)\n{\n mFreeFun(funPtr);\n}\n\nvoid HsQMLManager::freeStable(HsStablePtr stablePtr)\n{\n mFreeStable(stablePtr);\n}\n\nvoid HsQMLManager::hookedConstruct(QVariant::Private* p, const void* copy)\n{\n char guard;\n mOriginalHandler->construct(p, copy);\n void* pp = reinterpret_cast<void*>(p);\n \/\/ The QVariant internals sometimes use a special code path for pointer\n \/\/ values which avoids calling the handler functions. This makes it\n \/\/ difficult to use them to keep a reference count. However, it's my\n \/\/ observation that this only affects transient QVariants created on the\n \/\/ stack inside the JavaScript engine's marshalling code. The persistent\n \/\/ QVariants stored in the heap are manipulated using a more restricted set\n \/\/ of operations which always use the handler functions. Hence, by assuming\n \/\/ that the stack can be discounted, it's possible to keep an accurate\n \/\/ count of heap references using these hooks.\n if ((pp < &guard || pp > mStackBase) && p->type == QMetaType::QObjectStar) {\n if (HsQMLObject* obj = dynamic_cast<HsQMLObject*>(p->data.o)) {\n HsQMLObjectProxy* proxy = obj->proxy();\n proxy->ref(HsQMLObjectProxy::Variant);\n proxy->tryGCLock();\n updateCounter(VariantCount, 1);\n }\n }\n}\n\nvoid HsQMLManager::hookedClear(QVariant::Private* p)\n{\n char guard;\n void* pp = reinterpret_cast<void*>(p);\n if ((pp < &guard || pp > mStackBase) && p->type == QMetaType::QObjectStar) {\n if (HsQMLObject* obj = dynamic_cast<HsQMLObject*>(p->data.o)) {\n obj->proxy()->deref(HsQMLObjectProxy::Variant);\n updateCounter(VariantCount, -1);\n }\n }\n mOriginalHandler->clear(p);\n}\n\nbool HsQMLManager::isEventThread()\n{\n return mApp && mApp->thread() == QThread::currentThread();\n}\n\nHsQMLManager::EventLoopStatus HsQMLManager::runEventLoop(\n HsQMLTrivialCb startCb,\n HsQMLTrivialCb jobsCb,\n HsQMLTrivialCb yieldCb)\n{\n QMutexLocker locker(&mLock);\n\n \/\/ Check if already running\n if (mRunning) {\n return HSQML_EVLOOP_ALREADY_RUNNING;\n }\n\n \/\/ Check if event loop bound to a different thread\n if (mApp && !isEventThread()) {\n return HSQML_EVLOOP_WRONG_THREAD;\n }\n\n#ifdef Q_OS_MAC\n if (!pthread_main_np()) {\n \/\/ Cocoa can only be run on the primordial thread and exec() doesn't\n \/\/ check this.\n return HSQML_EVLOOP_WRONG_THREAD;\n }\n#endif\n\n \/\/ Check for non-threaded RTS\n if (yieldCb) {\n HSQML_LOG(0,\n \"Warning: CPU cannot idle when using the non-threaded RTS.\");\n }\n\n \/\/ Perform one-time initialisation\n if (!mApp) {\n \/\/ Install hooked handler for QVariants\n QVariantPrivate::registerHandler(0, &mHookedHandler);\n\n \/\/ Register custom type\n qRegisterMetaType<HsQMLEngineConfig>(\"HsQMLEngineConfig\");\n\n \/\/ Create application object\n mApp = new HsQMLManagerApp();\n }\n\n \/\/ Save stack base and callbacks\n mStackBase = &locker;\n mStartCb = startCb;\n mJobsCb = jobsCb;\n mYieldCb = yieldCb;\n\n \/\/ Setup events\n QCoreApplication::postEvent(\n mApp, new QEvent(HsQMLManagerApp::StartedLoopEvent),\n Qt::HighEventPriority);\n QBasicTimer idleTimer;\n if (yieldCb) {\n idleTimer.start(0, mApp);\n }\n\n \/\/ Run loop\n int ret;\n do {\n ret = mApp->exec();\n\n \/\/ Kill all engines\n const QObjectList& cs = gManager->mApp->children();\n while (!cs.empty()) {\n delete cs.front();\n }\n\n \/\/ Cmd-Q on MacOS can kill the event loop before we're ready\n \/\/ Keep it running until a StopLoopEvent is received\n } while (ret == 0 && mRunning);\n\n \/\/ Remove redundant events\n QCoreApplication::removePostedEvents(\n mApp, HsQMLManagerApp::RemoveGCLockEvent);\n\n \/\/ Cleanup callbacks\n freeFun(startCb);\n mStartCb = NULL;\n freeFun(jobsCb);\n mJobsCb = NULL;\n if (yieldCb) {\n freeFun(yieldCb);\n mYieldCb = NULL;\n }\n\n \/\/ Return\n if (ret == 0) {\n return HSQML_EVLOOP_OK;\n }\n else {\n QCoreApplication::removePostedEvents(\n mApp, HsQMLManagerApp::StartedLoopEvent);\n return HSQML_EVLOOP_OTHER_ERROR;\n }\n}\n\nHsQMLManager::EventLoopStatus HsQMLManager::requireEventLoop()\n{\n QMutexLocker locker(&mLock);\n if (mRunCount > 0) {\n mRunCount++;\n return HSQML_EVLOOP_OK;\n }\n else {\n return HSQML_EVLOOP_NOT_RUNNING;\n }\n}\n\nvoid HsQMLManager::releaseEventLoop()\n{\n QMutexLocker locker(&mLock);\n if (--mRunCount == 0) {\n QCoreApplication::postEvent(\n mApp, new QEvent(HsQMLManagerApp::StopLoopEvent),\n Qt::LowEventPriority);\n }\n}\n\nvoid HsQMLManager::notifyJobs()\n{\n QMutexLocker locker(&mLock);\n if (mRunCount > 0) {\n QCoreApplication::postEvent(\n mApp, new QEvent(HsQMLManagerApp::PendingJobsEvent));\n }\n}\n\nvoid HsQMLManager::createEngine(const HsQMLEngineConfig& config)\n{\n Q_ASSERT (mApp);\n QMetaObject::invokeMethod(\n mApp, \"createEngine\", Q_ARG(HsQMLEngineConfig, config));\n}\n\nvoid HsQMLManager::setActiveEngine(HsQMLEngine* engine)\n{\n Q_ASSERT(!mActiveEngine || !engine);\n mActiveEngine = engine;\n}\n\nHsQMLEngine* HsQMLManager::activeEngine()\n{\n return mActiveEngine;\n}\n\nvoid HsQMLManager::postObjectEvent(HsQMLObjectEvent* ev)\n{\n QCoreApplication::postEvent(mApp, ev);\n}\n\nHsQMLManagerApp::HsQMLManagerApp()\n : mArgC(1)\n , mArg0(0)\n , mArgV(&mArg0)\n , mApp(mArgC, &mArgV)\n{\n mApp.setQuitOnLastWindowClosed(false);\n}\n\nHsQMLManagerApp::~HsQMLManagerApp()\n{}\n\nvoid HsQMLManagerApp::customEvent(QEvent* ev)\n{\n switch (ev->type()) {\n case HsQMLManagerApp::StartedLoopEvent: {\n gManager->mRunning = true;\n gManager->mRunCount++;\n gManager->mLock.unlock();\n gManager->mStartCb();\n gManager->mJobsCb();\n break;}\n case HsQMLManagerApp::StopLoopEvent: {\n gManager->mLock.lock();\n gManager->mRunning = false;\n gManager->mApp->mApp.quit();\n break;}\n case HsQMLManagerApp::PendingJobsEvent: {\n gManager->mJobsCb();\n break;}\n case HsQMLManagerApp::RemoveGCLockEvent: {\n static_cast<HsQMLObjectEvent*>(ev)->process();\n break;}\n }\n}\n\nvoid HsQMLManagerApp::timerEvent(QTimerEvent*)\n{\n Q_ASSERT(gManager->mYieldCb);\n gManager->mYieldCb();\n}\n\nvoid HsQMLManagerApp::createEngine(HsQMLEngineConfig config)\n{\n HsQMLEngine* engine = new HsQMLEngine(config);\n engine->setParent(this);\n}\n\nint HsQMLManagerApp::exec()\n{\n return mApp.exec();\n}\n\nextern \"C\" void hsqml_init(\n void (*freeFun)(HsFunPtr),\n void (*freeStable)(HsStablePtr))\n{\n if (gManager == NULL) {\n HsQMLManager* manager = new HsQMLManager(freeFun, freeStable);\n if (!gManager.testAndSetOrdered(NULL, manager)) {\n delete manager;\n }\n }\n}\n\nextern \"C\" HsQMLEventLoopStatus hsqml_evloop_run(\n HsQMLTrivialCb startCb,\n HsQMLTrivialCb jobsCb,\n HsQMLTrivialCb yieldCb)\n{\n return gManager->runEventLoop(startCb, jobsCb, yieldCb);\n}\n\nextern \"C\" HsQMLEventLoopStatus hsqml_evloop_require()\n{\n return gManager->requireEventLoop();\n}\n\nextern \"C\" void hsqml_evloop_release()\n{\n gManager->releaseEventLoop();\n}\n\nextern \"C\" void hsqml_evloop_notify_jobs()\n{\n gManager->notifyJobs();\n}\n\nextern \"C\" void hsqml_set_debug_loglevel(int ll)\n{\n Q_ASSERT (gManager);\n gManager->setLogLevel(ll);\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * This file is part of SmartLamp application.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *\/\n\n\/*\n * Built for Attiny84 8Mhz, using AVR USBasp programmer.\n * VERSION 0.1\n *\/\n\n#include <avr\/io.h>\n#include <avr\/sleep.h>\n#include <time.h>\n\n#include <Arduino.h>\n\n#include <DS3232RTC.h>\n\/\/#include <USIWire.h>\n\n\/\/ Input\/output defines\n#define LED_BLUE 5\n#define LED_GR 3\n#define LED_RED 2\n\n#define BLU_STATE 1\n#define BLU_RESET 0\n\n#define RTC_INT_SQW 10\n\n\/\/ Serial defines\n#define SERIAL_BAUD 9600 \/\/ For at mode and for data mode (CC41, HM-10 and MLT-BT05)\n\n\/\/ I2C defines\n#define SDA 4\n#define SCL 6\n\n#define SLEEP_TIMEOUT 5000L \/\/ Timeout before sleep\n#define LENGTH 80 \/\/ Command buffer length\n\n\n\/\/ Global variables\nUSI_TWI bus; \/\/ TinyWireM instance (I2C bus)\n\/\/USIWire bus; \/\/ USIWire instance (I2C bus)\nDS3232RTC RTC(bus);\n\nboolean data = false;\nunsigned long prevMillis = 0;\nbool rtcInitOk = false;\n\n\ntime_t timeProvider() {\n return RTC.get();\n}\n\n\/\/ Put the micro to sleep\nvoid system_sleep() {\n set_sleep_mode(SLEEP_MODE_PWR_DOWN);\n sleep_enable();\n sleep_mode();\n\n \/\/ sleeping ...\n sleep_disable(); \/\/ wake up fully\n}\n\nvoid printDigits(int digits) {\n \/\/ Utility function for digital clock display: prints preceding colon and leading 0\n Serial.print(':');\n if (digits < 10)\n Serial.print('0');\n Serial.print(digits);\n}\n\nvoid digitalClockDisplay(void) {\n time_t now = timeProvider();\n\n \/\/ Digital clock display of the time\n Serial.print(hour(now));\n printDigits(minute(now));\n printDigits(second(now));\n Serial.print(' ');\n Serial.print(day(now));\n Serial.print('\/');\n Serial.print(month(now));\n Serial.print('\/');\n Serial.println(year(now));\n}\n\n\/\/ PCINT Interrupt Service Routine (unused)\nISR(PCINT0_vect) {\n \/\/ Don't do anything here but we must include this\n \/\/ block of code otherwise the interrupt calls an\n \/\/ uninitialized interrupt handler.\n}\n\nvoid setup() {\n OSCCAL = 0x86; \/\/ Calibrated OSSCAL value with TinyTuner\n\n Serial.begin(SERIAL_BAUD);\n bus.begin();\n\n \/\/ Pinmode set\n pinMode(LED_BLUE, OUTPUT);\n pinMode(LED_GR, OUTPUT);\n pinMode(LED_RED, OUTPUT);\n pinMode(BLU_STATE, INPUT);\n pinMode(BLU_RESET, OUTPUT);\n pinMode(RTC_INT_SQW, INPUT);\n\n Serial.println(F(\"START SERIAL\"));\n Serial.print(F(\"Initial value of OSCCAL is 0x\"));\n Serial.println(OSCCAL, HEX);\n\n \/\/setSyncProvider(RTC.get); \/\/ The function to get the time from the RTC\n \/\/ Real time clock\n setSyncProvider(timeProvider); \/\/ Pointer to function to get the time from the RTC\n\n if (timeStatus() != timeSet) {\n Serial.println(F(\"Unable to sync with the RTC\"));\n }\n else {\n Serial.println(F(\"RTC has set the system time\"));\n rtcInitOk = true;\n }\n\n if (rtcInitOk) {\n time_t t;\n tmElements_t tm;\n \n tm.Year = 47;\n tm.Month = 10;\n tm.Day = 18;\n tm.Hour = 21;\n tm.Minute = 45;\n tm.Second = 00;\n t = makeTime(tm);\n RTC.set(t); \/\/use the time_t value to ensure correct weekday is set\n setTime(t);\n Serial.print(F(\"RTC set to: \"));\n digitalClockDisplay();\n }\n\n ADCSRA = 0; \/\/ Disable ADC to save power\n MCUCR |= _BV(BODS); \/\/ BOD disabled\n\n PCMSK0 |= _BV(PCINT0); \/\/ Pin change mask: listen to portA bit 0 (D10)\n PCMSK0 |= _BV(PCINT2); \/\/ Pin change mask: listen to portA bit 2 (D8)\n GIMSK |= _BV(PCIE0); \/\/ Enable PCINT interrupt on portA\n}\n\n\nvoid loop() {\n size_t count = 0;\n char buffer[LENGTH];\n\n \/\/ FIXME Wake from sleep with new CORE can't read first serial bytes....\n\n if (millis() - prevMillis >= SLEEP_TIMEOUT) {\n prevMillis = millis();\n Serial.println(F(\"Sleeping...\"));\n system_sleep();\n Serial.println(F(\"Waking up...\"));\n digitalClockDisplay();\n\n \/\/ Necessary to reset the alarm flag on RTC!\n if (RTC.alarm(ALARM_1)) {\n Serial.println(F(\"From alarm...\"));\n }\n }\n\n while (Serial.available() && count < LENGTH - 1) {\n delay(2);\n char c = (char) Serial.read();\n\n prevMillis = millis(); \/\/ Update prevMillis to reset sleep timeout\n\n if (c == '\\r' || c == '\\n') {\n if (c == '\\n') {\n data = true;\n Serial.flush();\n break;\n }\n continue;\n }\n\n buffer[count] = c;\n count++;\n }\n\n if (data) {\n buffer[count] = '\\0';\n \/\/Serial.print(\"COUNT = \");\n \/\/Serial.println(count);\n \/\/Serial.println(buffer);\n\n count = 0;\n data = false;\n\n if (strcmp(buffer, \"ON\") == 0) {\n digitalWrite(LED_BLUE, HIGH);\n\n RTC.setAlarm(ALM1_MATCH_MINUTES, 45, 45, 21, 0);\n RTC.alarmInterrupt(ALARM_1, true);\n\n\/\/ for(int fadeValue = 0 ; fadeValue <= 255; fadeValue +=5) {\n\/\/ analogWrite(LED_BLUE, fadeValue);\n\/\/ delay(100);\n\/\/ }\n\/\/ delay(1000);\n\/\/ digitalWrite(LED_BLUE, LOW);\n\/\/\n\/\/ for(int fadeValue = 0 ; fadeValue <= 255; fadeValue +=5) {\n\/\/ analogWrite(LED_RED, fadeValue);\n\/\/ delay(100);\n\/\/ }\n\/\/ delay(1000);\n\/\/ digitalWrite(LED_RED, LOW);\n\/\/\n\/\/ for(int fadeValue = 0 ; fadeValue <= 255; fadeValue +=5) {\n\/\/ analogWrite(LED_GR, fadeValue);\n\/\/ delay(100);\n\/\/ }\n\/\/ delay(1000);\n\/\/ digitalWrite(LED_GR, LOW);\n }\n\n if (strcmp(buffer, \"OFF\") == 0) {\n digitalWrite(LED_BLUE, LOW);\n digitalWrite(LED_RED, LOW);\n digitalWrite(LED_GR, LOW);\n }\n\n digitalClockDisplay();\n }\n}\n<commit_msg>Converted RTc lib to use time.h from avr-libc.<commit_after>\/*\n * This file is part of SmartLamp application.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *\/\n\n\/*\n * Built for Attiny84 8Mhz, using AVR USBasp programmer.\n * VERSION 0.1\n *\/\n\n#include <avr\/io.h>\n#include <avr\/sleep.h>\n#include <time.h>\n\n#include <Arduino.h>\n\n#include <DS3232RTC.h>\n\/\/#include <USIWire.h>\n\n\/\/ Input\/output defines\n#define LED_BLUE 5\n#define LED_GR 3\n#define LED_RED 2\n\n#define BLU_STATE 1\n#define BLU_RESET 0\n\n#define RTC_INT_SQW 10\n\n\/\/ Serial defines\n#define SERIAL_BAUD 9600 \/\/ For at mode and for data mode (CC41, HM-10 and MLT-BT05)\n\n\/\/ I2C defines\n#define SDA 4\n#define SCL 6\n\n#define SLEEP_TIMEOUT 5000L \/\/ Timeout before sleep\n#define LENGTH 80 \/\/ Command buffer length\n\n\n\/\/ Global variables\nUSI_TWI bus; \/\/ TinyWireM instance (I2C bus)\n\/\/USIWire bus; \/\/ USIWire instance (I2C bus)\nDS3232RTC RTC(bus);\n\nboolean data = false;\nunsigned long prevMillis = 0;\nbool rtcInitOk = false;\n\n\/\/ Put the micro to sleep\nvoid system_sleep() {\n set_sleep_mode(SLEEP_MODE_PWR_DOWN);\n sleep_enable();\n sleep_mode();\n\n \/\/ sleeping ...\n sleep_disable(); \/\/ wake up fully\n}\n\ntime_t tmConvert_t(int16_t YYYY, int8_t MM, int8_t DD, int8_t hh, int8_t mm, int8_t ss) {\n struct tm tm;\n tm.tm_year = YYYY - 1900 + 30; \/\/ avr-libc time.h: years since 1900 + y2k epoch difference (2000 - 1970)\n tm.tm_mon = MM - 1; \/\/ avr-libc time.h: months in [0, 11]\n tm.tm_mday = DD;\n tm.tm_hour = hh;\n tm.tm_min = mm;\n tm.tm_sec = ss;\n return mk_gmtime(&tm);\n}\n\nvoid printDigits(int digits) {\n Serial.print(':');\n if (digits < 10)\n Serial.print('0');\n Serial.print(digits);\n}\n\nvoid digitalClockDisplay(time_t time) {\n struct tm tm;\n\n gmtime_r(&time, &tm);\n\n \/\/ Digital clock display of the time\n Serial.print(tm.tm_hour);\n printDigits(tm.tm_min);\n printDigits(tm.tm_sec);\n Serial.print(' ');\n Serial.print(tm.tm_mday);\n Serial.print('\/');\n Serial.print(tm.tm_mon + 1); \/\/ avr-libc time.h: months in [0, 11]\n Serial.print('\/');\n Serial.println(tm.tm_year + 1900 - 30); \/\/ avr-libc time.h: years since 1900 + y2k epoch difference (2000 - 1970)\n}\n\n\/\/ PCINT Interrupt Service Routine (unused)\nISR(PCINT0_vect) {\n \/\/ Don't do anything here but we must include this\n \/\/ block of code otherwise the interrupt calls an\n \/\/ uninitialized interrupt handler.\n}\n\nvoid setup() {\n byte retcode;\n time_t ts;\n\n OSCCAL = 0x86; \/\/ Calibrated OSSCAL value with TinyTuner\n\n Serial.begin(SERIAL_BAUD);\n bus.begin();\n\n \/\/ Pinmode set\n pinMode(LED_BLUE, OUTPUT);\n pinMode(LED_GR, OUTPUT);\n pinMode(LED_RED, OUTPUT);\n pinMode(BLU_STATE, INPUT);\n pinMode(BLU_RESET, OUTPUT);\n pinMode(RTC_INT_SQW, INPUT);\n\n Serial.println(F(\"START SERIAL\"));\n Serial.print(F(\"Initial value of OSCCAL is 0x\"));\n Serial.println(OSCCAL, HEX);\n\n ts = tmConvert_t(2017, 10, 20, 23, 05, 00);\n\n if ((retcode = RTC.set(ts)) == 0)\n rtcInitOk = true;\n else {\n Serial.print(F(\"RTC Set error: \"));\n Serial.print(retcode);\n }\n\n Serial.print(F(\"TS: \"));\n Serial.println(ts);\n digitalClockDisplay(ts);\n\n Serial.print(F(\"RTC set to: \"));\n Serial.println(RTC.get());\n digitalClockDisplay(RTC.get());\n\n ADCSRA = 0; \/\/ Disable ADC to save power\n MCUCR |= _BV(BODS); \/\/ BOD disabled\n\n PCMSK0 |= _BV(PCINT0); \/\/ Pin change mask: listen to portA bit 0 (D10)\n PCMSK0 |= _BV(PCINT2); \/\/ Pin change mask: listen to portA bit 2 (D8)\n GIMSK |= _BV(PCIE0); \/\/ Enable PCINT interrupt on portA\n}\n\nvoid loop() {\n size_t count = 0;\n char buffer[LENGTH];\n\n \/\/ FIXME Wake from sleep with new CORE can't read first serial bytes....\n\n if (millis() - prevMillis >= SLEEP_TIMEOUT) {\n prevMillis = millis();\n Serial.println(F(\"Sleeping...\"));\n system_sleep();\n Serial.println(F(\"Waking up...\"));\n digitalClockDisplay(RTC.get());\n\n \/\/ Necessary to reset the alarm flag on RTC!\n if (RTC.alarm(ALARM_1)) {\n Serial.println(F(\"From alarm...\"));\n }\n }\n\n while (Serial.available() && count < LENGTH - 1) {\n delay(2);\n char c = (char) Serial.read();\n\n prevMillis = millis(); \/\/ Update prevMillis to reset sleep timeout\n\n if (c == '\\r' || c == '\\n') {\n if (c == '\\n') {\n data = true;\n Serial.flush();\n break;\n }\n continue;\n }\n\n buffer[count] = c;\n count++;\n }\n\n if (data) {\n buffer[count] = '\\0';\n \/\/Serial.print(\"COUNT = \");\n \/\/Serial.println(count);\n Serial.println(buffer);\n\n count = 0;\n data = false;\n\n if (strcmp(buffer, \"ON\") == 0) {\n digitalWrite(LED_BLUE, HIGH);\n\n RTC.setAlarm(ALM1_MATCH_MINUTES, 00, 10, 23, 0);\n RTC.alarmInterrupt(ALARM_1, true);\n\n\/\/ for(int fadeValue = 0 ; fadeValue <= 255; fadeValue +=5) {\n\/\/ analogWrite(LED_BLUE, fadeValue);\n\/\/ delay(100);\n\/\/ }\n\/\/ delay(1000);\n\/\/ digitalWrite(LED_BLUE, LOW);\n\/\/\n\/\/ for(int fadeValue = 0 ; fadeValue <= 255; fadeValue +=5) {\n\/\/ analogWrite(LED_RED, fadeValue);\n\/\/ delay(100);\n\/\/ }\n\/\/ delay(1000);\n\/\/ digitalWrite(LED_RED, LOW);\n\/\/\n\/\/ for(int fadeValue = 0 ; fadeValue <= 255; fadeValue +=5) {\n\/\/ analogWrite(LED_GR, fadeValue);\n\/\/ delay(100);\n\/\/ }\n\/\/ delay(1000);\n\/\/ digitalWrite(LED_GR, LOW);\n }\n\n if (strcmp(buffer, \"OFF\") == 0) {\n digitalWrite(LED_BLUE, LOW);\n digitalWrite(LED_RED, LOW);\n digitalWrite(LED_GR, LOW);\n }\n\n digitalClockDisplay(RTC.get());\n }\n}\n<|endoftext|>"} {"text":"<commit_before>#include <deal.II\/base\/conditional_ostream.h>\n#include <deal.II\/base\/quadrature_lib.h>\n\n#include <deal.II\/dofs\/dof_handler.h>\n#include <deal.II\/dofs\/dof_tools.h>\n\n#include <deal.II\/fe\/fe_q.h>\n\n#include <deal.II\/grid\/grid_generator.h>\n#include <deal.II\/grid\/manifold_lib.h>\n\n#include <deal.II\/lac\/dynamic_sparsity_pattern.h>\n#include <deal.II\/lac\/constraint_matrix.h>\n\n#include <deal.II\/numerics\/error_estimator.h>\n\n\/\/ These headers are for distributed computations:\n#include <deal.II\/base\/utilities.h>\n#include <deal.II\/base\/index_set.h>\n#include <deal.II\/distributed\/tria.h>\n#include <deal.II\/distributed\/grid_refinement.h>\n#include <deal.II\/distributed\/solution_transfer.h>\n#include <deal.II\/lac\/sparsity_tools.h>\n\n#include <deal.II\/lac\/trilinos_solver.h>\n#include <deal.II\/lac\/trilinos_sparse_matrix.h>\n#include <deal.II\/lac\/trilinos_precondition.h>\n#include <deal.II\/lac\/trilinos_vector.h>\n\n#include <chrono>\n#include <functional>\n#include <iostream>\n\n#include <deal.II-cdr\/system_matrix.h>\n#include <deal.II-cdr\/system_rhs.h>\n#include <deal.II-cdr\/parameters.h>\n#include <deal.II-cdr\/write_pvtu_output.h>\n\nusing namespace dealii;\n\nconstexpr int manifold_id {0};\n\n\/\/ This is the actual solver class which performs time iteration and calls the\n\/\/ appropriate library functions to do it.\ntemplate<int dim>\nclass CDRProblem\n{\npublic:\n CDRProblem(const CDR::Parameters ¶meters);\n void run();\nprivate:\n const CDR::Parameters parameters;\n const double time_step;\n double current_time;\n\n MPI_Comm mpi_communicator;\n const unsigned int n_mpi_processes;\n const unsigned int this_mpi_process;\n\n FE_Q<dim> fe;\n QGauss<dim> quad;\n const SphericalManifold<dim> boundary_description;\n parallel::distributed::Triangulation<dim> triangulation;\n DoFHandler<dim> dof_handler;\n\n const std::function<Tensor<1, dim>(const Point<dim>)> convection_function;\n const std::function<double(double, const Point<dim>)> forcing_function;\n\n IndexSet locally_owned_dofs;\n IndexSet locally_relevant_dofs;\n\n ConstraintMatrix constraints;\n bool first_run;\n\n \/\/ As is usual in parallel programs, I keep two copies of parts of the\n \/\/ complete solution: <code>locally_relevant_solution<\/code> contains both\n \/\/ the locally calculated solution as well as the layer of cells at its\n \/\/ boundary (the @ref GlossGhostCells \"ghost cells\") while\n \/\/ <code>completely_distributed_solution<\/code> only contains the parts of\n \/\/ the solution computed on the current @ref GlossMPIProcess \"MPI process\".\n TrilinosWrappers::MPI::Vector locally_relevant_solution;\n TrilinosWrappers::MPI::Vector completely_distributed_solution;\n TrilinosWrappers::MPI::Vector system_rhs;\n TrilinosWrappers::SparseMatrix system_matrix;\n TrilinosWrappers::PreconditionAMG preconditioner;\n\n ConditionalOStream pcout;\n\n void setup_geometry();\n void setup_system();\n void setup_dofs();\n void refine_mesh();\n void time_iterate();\n};\n\n\ntemplate<int dim>\nCDRProblem<dim>::CDRProblem(const CDR::Parameters ¶meters) :\n parameters(parameters),\n time_step {(parameters.stop_time - parameters.start_time)\n \/parameters.n_time_steps},\n current_time {parameters.start_time},\n mpi_communicator (MPI_COMM_WORLD),\n n_mpi_processes {Utilities::MPI::n_mpi_processes(mpi_communicator)},\n this_mpi_process {Utilities::MPI::this_mpi_process(mpi_communicator)},\n fe(parameters.fe_order),\n quad(3*(2 + parameters.fe_order)\/2),\n boundary_description(Point<dim>()),\n triangulation(mpi_communicator, typename Triangulation<dim>::MeshSmoothing\n (Triangulation<dim>::smoothing_on_refinement |\n Triangulation<dim>::smoothing_on_coarsening)),\n dof_handler(triangulation),\n convection_function\n {\n [](const Point<dim> p) -> Tensor<1, dim>\n {Tensor<1, dim> v; v[0] = -p[1]; v[1] = p[0]; return v;}\n },\n forcing_function\n {\n [](double t, const Point<dim> p) -> double\n {\n return std::exp(-8*t)*std::exp(-40*Utilities::fixed_power<6>(p[0] - 1.5))\n *std::exp(-40*Utilities::fixed_power<6>(p[1]));\n }\n },\n first_run {true},\n pcout (std::cout, this_mpi_process == 0)\n{\n Assert(dim == 2, ExcNotImplemented());\n}\n\n\ntemplate<int dim>\nvoid CDRProblem<dim>::setup_geometry()\n{\n const Point<dim> center;\n GridGenerator::hyper_shell(triangulation, center, parameters.inner_radius,\n parameters.outer_radius);\n triangulation.set_manifold(manifold_id, boundary_description);\n for (const auto &cell : triangulation.active_cell_iterators())\n {\n cell->set_all_manifold_ids(0);\n }\n triangulation.refine_global(parameters.initial_refinement_level);\n}\n\n\ntemplate<int dim>\nvoid CDRProblem<dim>::setup_dofs()\n{\n dof_handler.distribute_dofs(fe);\n pcout << \"Number of degrees of freedom: \"\n << dof_handler.n_dofs()\n << std::endl;\n locally_owned_dofs = dof_handler.locally_owned_dofs();\n DoFTools::extract_locally_relevant_dofs(dof_handler, locally_relevant_dofs);\n\n constraints.clear();\n constraints.reinit(locally_relevant_dofs);\n DoFTools::make_hanging_node_constraints(dof_handler, constraints);\n DoFTools::make_zero_boundary_constraints(dof_handler, manifold_id, constraints);\n constraints.close();\n\n completely_distributed_solution.reinit\n (locally_owned_dofs, mpi_communicator);\n\n locally_relevant_solution.reinit(locally_owned_dofs, locally_relevant_dofs,\n mpi_communicator);\n}\n\n\ntemplate<int dim>\nvoid CDRProblem<dim>::setup_system()\n{\n DynamicSparsityPattern dynamic_sparsity_pattern(dof_handler.n_dofs());\n DoFTools::make_sparsity_pattern(dof_handler, dynamic_sparsity_pattern,\n constraints, \/*keep_constrained_dofs*\/true);\n SparsityTools::distribute_sparsity_pattern\n (dynamic_sparsity_pattern, dof_handler.n_locally_owned_dofs_per_processor(),\n mpi_communicator, locally_relevant_dofs);\n\n system_rhs.reinit(locally_owned_dofs, mpi_communicator);\n system_matrix.reinit(locally_owned_dofs, dynamic_sparsity_pattern,\n mpi_communicator);\n\n CDR::create_system_matrix<dim>\n (dof_handler, quad, convection_function, parameters, time_step, constraints,\n system_matrix);\n system_matrix.compress(VectorOperation::add);\n preconditioner.initialize(system_matrix);\n}\n\n\ntemplate<int dim>\nvoid CDRProblem<dim>::time_iterate()\n{\n double current_time = parameters.start_time;\n CDR::WritePVTUOutput pvtu_output(parameters.patch_level);\n for (unsigned int time_step_n = 0; time_step_n < parameters.n_time_steps;\n ++time_step_n)\n {\n current_time += time_step;\n\n system_rhs = 0.0;\n CDR::create_system_rhs<dim>\n (dof_handler, quad, convection_function, forcing_function, parameters,\n locally_relevant_solution, constraints, current_time, system_rhs);\n system_rhs.compress(VectorOperation::add);\n\n SolverControl solver_control(dof_handler.n_dofs(),\n 1e-6*system_rhs.l2_norm(),\n \/*log_history = *\/ false,\n \/*log_result = *\/ false);\n TrilinosWrappers::SolverGMRES solver(solver_control);\n solver.solve(system_matrix, completely_distributed_solution, system_rhs,\n preconditioner);\n constraints.distribute(completely_distributed_solution);\n locally_relevant_solution = completely_distributed_solution;\n\n if (time_step_n % parameters.save_interval == 0)\n {\n pvtu_output.write_output(dof_handler, locally_relevant_solution,\n time_step_n, current_time);\n }\n\n refine_mesh();\n }\n}\n\n\ntemplate<int dim>\nvoid CDRProblem<dim>::refine_mesh()\n{\n parallel::distributed::SolutionTransfer<dim, TrilinosWrappers::MPI::Vector>\n solution_transfer(dof_handler);\n\n Vector<float> estimated_error_per_cell(triangulation.n_active_cells());\n KellyErrorEstimator<dim>::estimate\n (dof_handler, QGauss<dim - 1>(fe.degree + 1), typename FunctionMap<dim>::type(),\n locally_relevant_solution, estimated_error_per_cell);\n\n \/\/ Poor man's version of refine and coarsen\n for (const auto &cell : triangulation.active_cell_iterators())\n {\n if (std::abs(estimated_error_per_cell[cell->active_cell_index()]) >= 1e-3)\n {\n cell->set_refine_flag();\n }\n else if (std::abs(estimated_error_per_cell[cell->active_cell_index()]) <= 1e-5)\n {\n cell->set_coarsen_flag();\n }\n }\n\n if (triangulation.n_levels() > parameters.max_refinement_level)\n {\n for (const auto &cell :\n triangulation.cell_iterators_on_level(parameters.max_refinement_level))\n {\n cell->clear_refine_flag();\n }\n }\n\n triangulation.prepare_coarsening_and_refinement();\n solution_transfer.prepare_for_coarsening_and_refinement\n (locally_relevant_solution);\n triangulation.execute_coarsening_and_refinement();\n\n setup_dofs();\n\n TrilinosWrappers::MPI::Vector temporary\n (locally_owned_dofs, mpi_communicator);\n solution_transfer.interpolate(temporary);\n locally_relevant_solution = temporary;\n constraints.distribute(locally_relevant_solution);\n setup_system();\n}\n\n\ntemplate<int dim>\nvoid CDRProblem<dim>::run()\n{\n setup_geometry();\n setup_dofs();\n setup_system();\n time_iterate();\n}\n\n\nconstexpr int dim {2};\n\n\nint main(int argc, char *argv[])\n{\n \/\/ One of the new features in C++11 is the <code>chrono<\/code> component of\n \/\/ the standard library. This gives us an easy way to time the output.\n auto t0 = std::chrono::high_resolution_clock::now();\n\n Utilities::MPI::MPI_InitFinalize mpi_initialization(argc, argv, 1);\n CDR::Parameters parameters;\n parameters.read_parameter_file(\"parameters.prm\");\n CDRProblem<dim> cdr_problem(parameters);\n cdr_problem.run();\n\n auto t1 = std::chrono::high_resolution_clock::now();\n if (Utilities::MPI::this_mpi_process(MPI_COMM_WORLD) == 0)\n {\n std::cout << \"time elapsed: \"\n << std::chrono::duration_cast<std::chrono::milliseconds>(t1 - t0).count()\n << \" milliseconds.\"\n << std::endl;\n }\n\n return 0;\n}\n<commit_msg>Use a more reasonable quadrature order.<commit_after>#include <deal.II\/base\/conditional_ostream.h>\n#include <deal.II\/base\/quadrature_lib.h>\n\n#include <deal.II\/dofs\/dof_handler.h>\n#include <deal.II\/dofs\/dof_tools.h>\n\n#include <deal.II\/fe\/fe_q.h>\n\n#include <deal.II\/grid\/grid_generator.h>\n#include <deal.II\/grid\/manifold_lib.h>\n\n#include <deal.II\/lac\/dynamic_sparsity_pattern.h>\n#include <deal.II\/lac\/constraint_matrix.h>\n\n#include <deal.II\/numerics\/error_estimator.h>\n\n\/\/ These headers are for distributed computations:\n#include <deal.II\/base\/utilities.h>\n#include <deal.II\/base\/index_set.h>\n#include <deal.II\/distributed\/tria.h>\n#include <deal.II\/distributed\/grid_refinement.h>\n#include <deal.II\/distributed\/solution_transfer.h>\n#include <deal.II\/lac\/sparsity_tools.h>\n\n#include <deal.II\/lac\/trilinos_solver.h>\n#include <deal.II\/lac\/trilinos_sparse_matrix.h>\n#include <deal.II\/lac\/trilinos_precondition.h>\n#include <deal.II\/lac\/trilinos_vector.h>\n\n#include <chrono>\n#include <functional>\n#include <iostream>\n\n#include <deal.II-cdr\/system_matrix.h>\n#include <deal.II-cdr\/system_rhs.h>\n#include <deal.II-cdr\/parameters.h>\n#include <deal.II-cdr\/write_pvtu_output.h>\n\nusing namespace dealii;\n\nconstexpr int manifold_id {0};\n\n\/\/ This is the actual solver class which performs time iteration and calls the\n\/\/ appropriate library functions to do it.\ntemplate<int dim>\nclass CDRProblem\n{\npublic:\n CDRProblem(const CDR::Parameters ¶meters);\n void run();\nprivate:\n const CDR::Parameters parameters;\n const double time_step;\n double current_time;\n\n MPI_Comm mpi_communicator;\n const unsigned int n_mpi_processes;\n const unsigned int this_mpi_process;\n\n FE_Q<dim> fe;\n QGauss<dim> quad;\n const SphericalManifold<dim> boundary_description;\n parallel::distributed::Triangulation<dim> triangulation;\n DoFHandler<dim> dof_handler;\n\n const std::function<Tensor<1, dim>(const Point<dim>)> convection_function;\n const std::function<double(double, const Point<dim>)> forcing_function;\n\n IndexSet locally_owned_dofs;\n IndexSet locally_relevant_dofs;\n\n ConstraintMatrix constraints;\n bool first_run;\n\n \/\/ As is usual in parallel programs, I keep two copies of parts of the\n \/\/ complete solution: <code>locally_relevant_solution<\/code> contains both\n \/\/ the locally calculated solution as well as the layer of cells at its\n \/\/ boundary (the @ref GlossGhostCells \"ghost cells\") while\n \/\/ <code>completely_distributed_solution<\/code> only contains the parts of\n \/\/ the solution computed on the current @ref GlossMPIProcess \"MPI process\".\n TrilinosWrappers::MPI::Vector locally_relevant_solution;\n TrilinosWrappers::MPI::Vector completely_distributed_solution;\n TrilinosWrappers::MPI::Vector system_rhs;\n TrilinosWrappers::SparseMatrix system_matrix;\n TrilinosWrappers::PreconditionAMG preconditioner;\n\n ConditionalOStream pcout;\n\n void setup_geometry();\n void setup_system();\n void setup_dofs();\n void refine_mesh();\n void time_iterate();\n};\n\n\ntemplate<int dim>\nCDRProblem<dim>::CDRProblem(const CDR::Parameters ¶meters) :\n parameters(parameters),\n time_step {(parameters.stop_time - parameters.start_time)\n \/parameters.n_time_steps},\n current_time {parameters.start_time},\n mpi_communicator (MPI_COMM_WORLD),\n n_mpi_processes {Utilities::MPI::n_mpi_processes(mpi_communicator)},\n this_mpi_process {Utilities::MPI::this_mpi_process(mpi_communicator)},\n fe(parameters.fe_order),\n quad(parameters.fe_order + 2),\n boundary_description(Point<dim>()),\n triangulation(mpi_communicator, typename Triangulation<dim>::MeshSmoothing\n (Triangulation<dim>::smoothing_on_refinement |\n Triangulation<dim>::smoothing_on_coarsening)),\n dof_handler(triangulation),\n convection_function\n {\n [](const Point<dim> p) -> Tensor<1, dim>\n {Tensor<1, dim> v; v[0] = -p[1]; v[1] = p[0]; return v;}\n },\n forcing_function\n {\n [](double t, const Point<dim> p) -> double\n {\n return std::exp(-8*t)*std::exp(-40*Utilities::fixed_power<6>(p[0] - 1.5))\n *std::exp(-40*Utilities::fixed_power<6>(p[1]));\n }\n },\n first_run {true},\n pcout (std::cout, this_mpi_process == 0)\n{\n Assert(dim == 2, ExcNotImplemented());\n}\n\n\ntemplate<int dim>\nvoid CDRProblem<dim>::setup_geometry()\n{\n const Point<dim> center;\n GridGenerator::hyper_shell(triangulation, center, parameters.inner_radius,\n parameters.outer_radius);\n triangulation.set_manifold(manifold_id, boundary_description);\n for (const auto &cell : triangulation.active_cell_iterators())\n {\n cell->set_all_manifold_ids(0);\n }\n triangulation.refine_global(parameters.initial_refinement_level);\n}\n\n\ntemplate<int dim>\nvoid CDRProblem<dim>::setup_dofs()\n{\n dof_handler.distribute_dofs(fe);\n pcout << \"Number of degrees of freedom: \"\n << dof_handler.n_dofs()\n << std::endl;\n locally_owned_dofs = dof_handler.locally_owned_dofs();\n DoFTools::extract_locally_relevant_dofs(dof_handler, locally_relevant_dofs);\n\n constraints.clear();\n constraints.reinit(locally_relevant_dofs);\n DoFTools::make_hanging_node_constraints(dof_handler, constraints);\n DoFTools::make_zero_boundary_constraints(dof_handler, manifold_id, constraints);\n constraints.close();\n\n completely_distributed_solution.reinit\n (locally_owned_dofs, mpi_communicator);\n\n locally_relevant_solution.reinit(locally_owned_dofs, locally_relevant_dofs,\n mpi_communicator);\n}\n\n\ntemplate<int dim>\nvoid CDRProblem<dim>::setup_system()\n{\n DynamicSparsityPattern dynamic_sparsity_pattern(dof_handler.n_dofs());\n DoFTools::make_sparsity_pattern(dof_handler, dynamic_sparsity_pattern,\n constraints, \/*keep_constrained_dofs*\/true);\n SparsityTools::distribute_sparsity_pattern\n (dynamic_sparsity_pattern, dof_handler.n_locally_owned_dofs_per_processor(),\n mpi_communicator, locally_relevant_dofs);\n\n system_rhs.reinit(locally_owned_dofs, mpi_communicator);\n system_matrix.reinit(locally_owned_dofs, dynamic_sparsity_pattern,\n mpi_communicator);\n\n CDR::create_system_matrix<dim>\n (dof_handler, quad, convection_function, parameters, time_step, constraints,\n system_matrix);\n system_matrix.compress(VectorOperation::add);\n preconditioner.initialize(system_matrix);\n}\n\n\ntemplate<int dim>\nvoid CDRProblem<dim>::time_iterate()\n{\n double current_time = parameters.start_time;\n CDR::WritePVTUOutput pvtu_output(parameters.patch_level);\n for (unsigned int time_step_n = 0; time_step_n < parameters.n_time_steps;\n ++time_step_n)\n {\n current_time += time_step;\n\n system_rhs = 0.0;\n CDR::create_system_rhs<dim>\n (dof_handler, quad, convection_function, forcing_function, parameters,\n locally_relevant_solution, constraints, current_time, system_rhs);\n system_rhs.compress(VectorOperation::add);\n\n SolverControl solver_control(dof_handler.n_dofs(),\n 1e-6*system_rhs.l2_norm(),\n \/*log_history = *\/ false,\n \/*log_result = *\/ false);\n TrilinosWrappers::SolverGMRES solver(solver_control);\n solver.solve(system_matrix, completely_distributed_solution, system_rhs,\n preconditioner);\n constraints.distribute(completely_distributed_solution);\n locally_relevant_solution = completely_distributed_solution;\n\n if (time_step_n % parameters.save_interval == 0)\n {\n pvtu_output.write_output(dof_handler, locally_relevant_solution,\n time_step_n, current_time);\n }\n\n refine_mesh();\n }\n}\n\n\ntemplate<int dim>\nvoid CDRProblem<dim>::refine_mesh()\n{\n parallel::distributed::SolutionTransfer<dim, TrilinosWrappers::MPI::Vector>\n solution_transfer(dof_handler);\n\n Vector<float> estimated_error_per_cell(triangulation.n_active_cells());\n KellyErrorEstimator<dim>::estimate\n (dof_handler, QGauss<dim - 1>(fe.degree + 1), typename FunctionMap<dim>::type(),\n locally_relevant_solution, estimated_error_per_cell);\n\n \/\/ Poor man's version of refine and coarsen\n for (const auto &cell : triangulation.active_cell_iterators())\n {\n if (std::abs(estimated_error_per_cell[cell->active_cell_index()]) >= 1e-3)\n {\n cell->set_refine_flag();\n }\n else if (std::abs(estimated_error_per_cell[cell->active_cell_index()]) <= 1e-5)\n {\n cell->set_coarsen_flag();\n }\n }\n\n if (triangulation.n_levels() > parameters.max_refinement_level)\n {\n for (const auto &cell :\n triangulation.cell_iterators_on_level(parameters.max_refinement_level))\n {\n cell->clear_refine_flag();\n }\n }\n\n triangulation.prepare_coarsening_and_refinement();\n solution_transfer.prepare_for_coarsening_and_refinement\n (locally_relevant_solution);\n triangulation.execute_coarsening_and_refinement();\n\n setup_dofs();\n\n TrilinosWrappers::MPI::Vector temporary\n (locally_owned_dofs, mpi_communicator);\n solution_transfer.interpolate(temporary);\n locally_relevant_solution = temporary;\n constraints.distribute(locally_relevant_solution);\n setup_system();\n}\n\n\ntemplate<int dim>\nvoid CDRProblem<dim>::run()\n{\n setup_geometry();\n setup_dofs();\n setup_system();\n time_iterate();\n}\n\n\nconstexpr int dim {2};\n\n\nint main(int argc, char *argv[])\n{\n \/\/ One of the new features in C++11 is the <code>chrono<\/code> component of\n \/\/ the standard library. This gives us an easy way to time the output.\n auto t0 = std::chrono::high_resolution_clock::now();\n\n Utilities::MPI::MPI_InitFinalize mpi_initialization(argc, argv, 1);\n CDR::Parameters parameters;\n parameters.read_parameter_file(\"parameters.prm\");\n CDRProblem<dim> cdr_problem(parameters);\n cdr_problem.run();\n\n auto t1 = std::chrono::high_resolution_clock::now();\n if (Utilities::MPI::this_mpi_process(MPI_COMM_WORLD) == 0)\n {\n std::cout << \"time elapsed: \"\n << std::chrono::duration_cast<std::chrono::milliseconds>(t1 - t0).count()\n << \" milliseconds.\"\n << std::endl;\n }\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/**\n * Copyright 2008 Matthew Graham\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"server_message.h\"\n#include \"connection_test.h\"\n#include <testpp\/test.h>\n\n\n\/**\n * Test that the constructor for the server message sets fields\n * into the correct state.\n *\/\nTESTPP( test_server_message_constructor )\n{\n\tmock_client_server_connection_c cs( 3 );\n\tserver_message_c msg( \"create dog cat\", cs.server() );\n\n\tassertpp( msg.request_type() ) == \"create\";\n\t\/\/ assertpp( msg.request().extra_argc() ) == 3;\n\tassertpp( msg.port() ) == 3;\n}\n\n<commit_msg>fixed the server_message test to take connection *<commit_after>\/**\n * Copyright 2008 Matthew Graham\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"server_message.h\"\n#include \"connection_test.h\"\n#include <testpp\/test.h>\n\n\n\/**\n * Test that the constructor for the server message sets fields\n * into the correct state.\n *\/\nTESTPP( test_server_message_constructor )\n{\n\tmock_client_server_connection_c cs( 3 );\n\tserver_message_c msg( \"create dog cat\", &cs.server() );\n\n\tassertpp( msg.request_type() ) == \"create\";\n\t\/\/ assertpp( msg.request().extra_argc() ) == 3;\n\tassertpp( msg.port() ) == 3;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Software License Agreement (BSD License)\n *\n * Copyright (c) 2010, Willow Garage, Inc.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following\n * disclaimer in the documentation and\/or other materials provided\n * with the distribution.\n * * Neither the name of Willow Garage, Inc. nor the names of its\n * contributors may be used to endorse or promote products derived\n * from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n *\/\n\n#ifndef PCL_SURFACE_IMPL_POISSON_H_\n#define PCL_SURFACE_IMPL_POISSON_H_\n\n#include \"pcl\/surface\/poisson.h\"\n#include <pcl\/common\/common.h>\n#include <pcl\/common\/vector_average.h>\n#include <pcl\/Vertices.h>\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <float.h>\n#include \"pcl\/surface\/poisson\/octree.h\"\n#include \"pcl\/surface\/poisson\/sparse_matrix.h\"\n#include \"pcl\/surface\/poisson\/function_data.h\"\n#include \"pcl\/surface\/poisson\/ppolynomial.h\"\n#include \"pcl\/surface\/poisson\/multi_grid_octree_data.h\"\n\n#define MEMORY_ALLOCATOR_BLOCK_SIZE 1<<12\n\n#include <stdarg.h>\n#include <string>\n\nusing namespace pcl::surface::poisson;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate <typename PointNT>\npcl::surface::Poisson<PointNT>::Poisson ()\n : no_reset_samples_(false),\n no_clip_tree_(false),\n confidence_(false),\n manifold_(false),\n depth_(10),\n solver_divide_(8),\n iso_divide_(8),\n refine_(3),\n kernel_depth_(8),\n degree_ (2),\n samples_per_node_(1.0),\n scale_(1.25)\n{\n}\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate <typename PointNT>\npcl::surface::Poisson<PointNT>::~Poisson ()\n{\n}\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate <typename PointNT> template <int Degree> void\npcl::surface::Poisson<PointNT>::execute (CoredMeshData &mesh,\n Point3D<float> ¢er)\n{\n float scale = 1;\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ Fix courtesy of David Gallup \/\/\n \/\/ TreeNodeData::UseIndex = 1; \/\/\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n Octree<Degree> tree;\n PPolynomial<Degree> ReconstructionFunction=PPolynomial<Degree>::GaussianApproximation();\n\n center.coords[0]=center.coords[1]=center.coords[2]=0;\n\n TreeOctNode::SetAllocator(MEMORY_ALLOCATOR_BLOCK_SIZE);\n\n int kernel_depth=depth_-2;\n if(kernel_depth_){kernel_depth=kernel_depth_;}\n\n tree.setFunctionData(ReconstructionFunction,depth_,0,float(1.0)\/(1<<depth_));\n if (kernel_depth > depth_)\n {\n PCL_ERROR (\"KernelDepth can't be greater than Depth: %d <= %d\\n\",kernel_depth,depth_);\n return;\n }\n\n\n tree.setTree (depth_, kernel_depth, float(samples_per_node_), scale_, center, scale, !no_reset_samples_, confidence_, input_);\n\n if(!no_clip_tree_)\n tree.ClipTree();\n\n tree.finalize1(refine_);\n\n\n tree.SetLaplacianWeights();\n\n tree.finalize2(refine_);\n\n tree.LaplacianMatrixIteration(solver_divide_);\n\n float isoValue=tree.GetIsoValue();\n\n if (iso_divide_)\n tree.GetMCIsoTriangles (isoValue, iso_divide_, &mesh, 0, 1, manifold_);\n else\n tree.GetMCIsoTriangles (isoValue, &mesh, 0, 1, manifold_);\n}\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate <typename PointNT> void\npcl::surface::Poisson<PointNT>::performReconstruction (PolygonMesh &output)\n{\n CoredVectorMeshData mesh;\n Point3D<float> center;\n\n switch(degree_)\n {\n case 1:\n execute<1> (mesh, center);\n break;\n case 2:\n execute<2> (mesh, center);\n break;\n case 3:\n execute<3> (mesh, center);\n break;\n case 4:\n execute<4> (mesh, center);\n break;\n case 5:\n execute<5> (mesh, center);\n break;\n default:\n PCL_ERROR (stderr,\"Degree %d not supported\\n\", degree_);\n }\n\n \/\/\/ Write output PolygonMesh\n float scale = 1;\n \/\/ write vertices\n pcl::PointCloud < pcl::PointXYZ > cloud;\n cloud.points.resize (int (mesh.outOfCorePointCount()+mesh.inCorePoints.size ()) );\n Point3D<float> p;\n for (int i = 0; i < int(mesh.inCorePoints.size()); i++)\n {\n p = mesh.inCorePoints[i];\n cloud.points[i].x = p.coords[0]*scale+center.coords[0];\n cloud.points[i].y = p.coords[1]*scale+center.coords[1];\n cloud.points[i].z = p.coords[2]*scale+center.coords[2];\n }\n for (int i = int(mesh.inCorePoints.size()); i < int (mesh.outOfCorePointCount() + mesh.inCorePoints.size ()); i++)\n {\n mesh.nextOutOfCorePoint(p);\n cloud.points[i].x = p.coords[0]*scale+center.coords[0];\n cloud.points[i].y = p.coords[1]*scale+center.coords[1];\n cloud.points[i].z = p.coords[2]*scale+center.coords[2];\n }\n pcl::toROSMsg (cloud, output.cloud);\n output.polygons.resize (mesh.triangleCount ());\n\n \/\/ write faces\n TriangleIndex tIndex;\n int inCoreFlag;\n for (int i = 0; i < mesh.triangleCount(); i++)\n {\n \/\/ create and fill a struct that the ply code can handle\n pcl::Vertices v;\n v.vertices.resize (3);\n\n mesh.nextTriangle(tIndex,inCoreFlag);\n if (!(inCoreFlag & CoredMeshData::IN_CORE_FLAG[0])) { tIndex.idx[0] += int(mesh.inCorePoints.size()); }\n if (!(inCoreFlag & CoredMeshData::IN_CORE_FLAG[1])) { tIndex.idx[1] += int(mesh.inCorePoints.size()); }\n if (!(inCoreFlag & CoredMeshData::IN_CORE_FLAG[2])) { tIndex.idx[2] += int(mesh.inCorePoints.size()); }\n for (int j = 0; j < 3; j++) {v.vertices[j] = tIndex.idx[j];}\n output.polygons[i] = v;\n } \/\/ for, write faces\n}\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate <typename PointNT> void\npcl::surface::Poisson<PointNT>::performReconstruction (pcl::PointCloud<PointNT> &points,\n std::vector<pcl::Vertices> &polygons)\n{\n CoredVectorMeshData mesh;\n Point3D<float> center;\n\n switch(degree_)\n {\n case 1:\n execute<1> (mesh, center);\n break;\n case 2:\n execute<2> (mesh, center);\n break;\n case 3:\n execute<3> (mesh, center);\n break;\n case 4:\n execute<4> (mesh, center);\n break;\n case 5:\n execute<5> (mesh, center);\n break;\n default:\n PCL_ERROR (stderr,\"Degree %d not supported\\n\", degree_);\n }\n\n \/\/\/ Write output PolygonMesh\n float scale = 1;\n \/\/ write vertices\n points.points.resize (int (mesh.outOfCorePointCount()+mesh.inCorePoints.size ()) );\n Point3D<float> p;\n for (int i = 0; i < int(mesh.inCorePoints.size()); i++)\n {\n p = mesh.inCorePoints[i];\n points.points[i].x = p.coords[0]*scale+center.coords[0];\n points.points[i].y = p.coords[1]*scale+center.coords[1];\n points.points[i].z = p.coords[2]*scale+center.coords[2];\n }\n for (int i = int(mesh.inCorePoints.size()); i < int (mesh.outOfCorePointCount() + mesh.inCorePoints.size ()); i++)\n {\n mesh.nextOutOfCorePoint(p);\n points.points[i].x = p.coords[0]*scale+center.coords[0];\n points.points[i].y = p.coords[1]*scale+center.coords[1];\n points.points[i].z = p.coords[2]*scale+center.coords[2];\n }\n\n polygons.resize (mesh.triangleCount ());\n\n \/\/ write faces\n TriangleIndex tIndex;\n int inCoreFlag;\n for (int i = 0; i < mesh.triangleCount(); i++)\n {\n \/\/ create and fill a struct that the ply code can handle\n pcl::Vertices v;\n v.vertices.resize (3);\n\n mesh.nextTriangle(tIndex,inCoreFlag);\n if (!(inCoreFlag & CoredMeshData::IN_CORE_FLAG[0])) { tIndex.idx[0] += int(mesh.inCorePoints.size()); }\n if (!(inCoreFlag & CoredMeshData::IN_CORE_FLAG[1])) { tIndex.idx[1] += int(mesh.inCorePoints.size()); }\n if (!(inCoreFlag & CoredMeshData::IN_CORE_FLAG[2])) { tIndex.idx[2] += int(mesh.inCorePoints.size()); }\n for (int j = 0; j < 3; j++) {v.vertices[j] = tIndex.idx[j];}\n polygons[i] = v;\n } \/\/ for, write faces\n\n}\n\n\n#define PCL_INSTANTIATE_Poisson(T) template class PCL_EXPORTS pcl::surface::Poisson<T>;\n\n#endif \/\/ PCL_SURFACE_IMPL_POISSON_H_\n\n<commit_msg>poisson beautification<commit_after>\/*\n * Software License Agreement (BSD License)\n *\n * Copyright (c) 2010, Willow Garage, Inc.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following\n * disclaimer in the documentation and\/or other materials provided\n * with the distribution.\n * * Neither the name of Willow Garage, Inc. nor the names of its\n * contributors may be used to endorse or promote products derived\n * from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n *\/\n\n#ifndef PCL_SURFACE_IMPL_POISSON_H_\n#define PCL_SURFACE_IMPL_POISSON_H_\n\n#include \"pcl\/surface\/poisson.h\"\n#include <pcl\/common\/common.h>\n#include <pcl\/common\/vector_average.h>\n#include <pcl\/Vertices.h>\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <float.h>\n#include \"pcl\/surface\/poisson\/octree.h\"\n#include \"pcl\/surface\/poisson\/sparse_matrix.h\"\n#include \"pcl\/surface\/poisson\/function_data.h\"\n#include \"pcl\/surface\/poisson\/ppolynomial.h\"\n#include \"pcl\/surface\/poisson\/multi_grid_octree_data.h\"\n\n#define MEMORY_ALLOCATOR_BLOCK_SIZE 1<<12\n\n#include <stdarg.h>\n#include <string>\n\nusing namespace pcl::surface::poisson;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate <typename PointNT>\npcl::surface::Poisson<PointNT>::Poisson ()\n : no_reset_samples_ (false),\n no_clip_tree_ (false),\n confidence_ (false),\n manifold_ (false),\n depth_ (10),\n solver_divide_ (8),\n iso_divide_ (8),\n refine_ (3),\n kernel_depth_ (8),\n degree_ (2),\n samples_per_node_ (1.0),\n scale_ (1.25)\n{\n}\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate <typename PointNT>\npcl::surface::Poisson<PointNT>::~Poisson ()\n{\n}\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate <typename PointNT> template <int Degree> void\npcl::surface::Poisson<PointNT>::execute (CoredMeshData &mesh,\n Point3D<float> ¢er)\n{\n float scale = 1;\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ Fix courtesy of David Gallup \/\/\n \/\/ TreeNodeData::UseIndex = 1; \/\/\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n Octree<Degree> tree;\n PPolynomial<Degree> ReconstructionFunction = PPolynomial<Degree>::GaussianApproximation ();\n\n center.coords[0] = center.coords[1] = center.coords[2] = 0;\n\n TreeOctNode::SetAllocator(MEMORY_ALLOCATOR_BLOCK_SIZE);\n\n int kernel_depth=depth_-2;\n if (kernel_depth_)\n kernel_depth=kernel_depth_;\n\n tree.setFunctionData (ReconstructionFunction,depth_, 0, float (1.0) \/ (1<<depth_));\n if (kernel_depth > depth_)\n {\n PCL_ERROR (\"KernelDepth can't be greater than Depth: %d <= %d\\n\", kernel_depth, depth_);\n return;\n }\n\n\n tree.setTree (depth_, kernel_depth, float (samples_per_node_), scale_, center, scale, !no_reset_samples_, confidence_, input_);\n\n if(!no_clip_tree_)\n tree.ClipTree ();\n\n tree.finalize1 (refine_);\n tree.SetLaplacianWeights ();\n tree.finalize2 (refine_);\n\n tree.LaplacianMatrixIteration (solver_divide_);\n\n float isoValue=tree.GetIsoValue ();\n\n if (iso_divide_)\n tree.GetMCIsoTriangles (isoValue, iso_divide_, &mesh, 0, 1, manifold_);\n else\n tree.GetMCIsoTriangles (isoValue, &mesh, 0, 1, manifold_);\n}\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate <typename PointNT> void\npcl::surface::Poisson<PointNT>::performReconstruction (PolygonMesh &output)\n{\n CoredVectorMeshData mesh;\n Point3D<float> center;\n\n printf (\"Before execution\\n\");\n switch (degree_)\n {\n case 1:\n execute<1> (mesh, center);\n break;\n case 2:\n execute<2> (mesh, center);\n break;\n case 3:\n execute<3> (mesh, center);\n break;\n case 4:\n execute<4> (mesh, center);\n break;\n case 5:\n execute<5> (mesh, center);\n break;\n default:\n PCL_ERROR (stderr,\"Degree %d not supported\\n\", degree_);\n }\n\n printf (\"Done execution \\n\");\n\n \/\/\/ Write output PolygonMesh\n float scale = 1;\n \/\/ write vertices\n pcl::PointCloud < pcl::PointXYZ > cloud;\n cloud.points.resize (int (mesh.outOfCorePointCount()+mesh.inCorePoints.size ()));\n Point3D<float> p;\n for (int i = 0; i < int (mesh.inCorePoints.size()); i++)\n {\n p = mesh.inCorePoints[i];\n cloud.points[i].x = p.coords[0]*scale+center.coords[0];\n cloud.points[i].y = p.coords[1]*scale+center.coords[1];\n cloud.points[i].z = p.coords[2]*scale+center.coords[2];\n }\n for (int i = int (mesh.inCorePoints.size ()); i < int (mesh.outOfCorePointCount () + mesh.inCorePoints.size ()); i++)\n {\n mesh.nextOutOfCorePoint (p);\n cloud.points[i].x = p.coords[0]*scale+center.coords[0];\n cloud.points[i].y = p.coords[1]*scale+center.coords[1];\n cloud.points[i].z = p.coords[2]*scale+center.coords[2];\n }\n pcl::toROSMsg (cloud, output.cloud);\n output.polygons.resize (mesh.triangleCount ());\n\n \/\/ Write faces\n TriangleIndex tIndex;\n int inCoreFlag;\n for (int i = 0; i < mesh.triangleCount(); i++)\n {\n \/\/ Create and fill a struct that the ply code can handle\n pcl::Vertices v;\n v.vertices.resize (3);\n\n mesh.nextTriangle(tIndex,inCoreFlag);\n if (!(inCoreFlag & CoredMeshData::IN_CORE_FLAG[0]))\n tIndex.idx[0] += int(mesh.inCorePoints.size());\n if (!(inCoreFlag & CoredMeshData::IN_CORE_FLAG[1]))\n tIndex.idx[1] += int(mesh.inCorePoints.size());\n if (!(inCoreFlag & CoredMeshData::IN_CORE_FLAG[2]))\n tIndex.idx[2] += int(mesh.inCorePoints.size());\n\n for (int j = 0; j < 3; j++)\n v.vertices[j] = tIndex.idx[j];\n output.polygons[i] = v;\n }\n}\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate <typename PointNT> void\npcl::surface::Poisson<PointNT>::performReconstruction (pcl::PointCloud<PointNT> &points,\n std::vector<pcl::Vertices> &polygons)\n{\n CoredVectorMeshData mesh;\n Point3D<float> center;\n\n switch(degree_)\n {\n case 1:\n execute<1> (mesh, center);\n break;\n case 2:\n execute<2> (mesh, center);\n break;\n case 3:\n execute<3> (mesh, center);\n break;\n case 4:\n execute<4> (mesh, center);\n break;\n case 5:\n execute<5> (mesh, center);\n break;\n default:\n PCL_ERROR (stderr,\"Degree %d not supported\\n\", degree_);\n }\n\n \/\/\/ Write output PolygonMesh\n float scale = 1;\n \/\/ write vertices\n points.points.resize (int (mesh.outOfCorePointCount ()+mesh.inCorePoints.size ()));\n Point3D<float> p;\n for (int i = 0; i < int(mesh.inCorePoints.size()); i++)\n {\n p = mesh.inCorePoints[i];\n points.points[i].x = p.coords[0]*scale+center.coords[0];\n points.points[i].y = p.coords[1]*scale+center.coords[1];\n points.points[i].z = p.coords[2]*scale+center.coords[2];\n }\n for (int i = int(mesh.inCorePoints.size()); i < int (mesh.outOfCorePointCount() + mesh.inCorePoints.size ()); i++)\n {\n mesh.nextOutOfCorePoint(p);\n points.points[i].x = p.coords[0]*scale+center.coords[0];\n points.points[i].y = p.coords[1]*scale+center.coords[1];\n points.points[i].z = p.coords[2]*scale+center.coords[2];\n }\n\n polygons.resize (mesh.triangleCount ());\n\n \/\/ write faces\n TriangleIndex tIndex;\n int inCoreFlag;\n for (int i = 0; i < mesh.triangleCount (); i++)\n {\n \/\/ create and fill a struct that the ply code can handle\n pcl::Vertices v;\n v.vertices.resize (3);\n\n mesh.nextTriangle(tIndex,inCoreFlag);\n if (!(inCoreFlag & CoredMeshData::IN_CORE_FLAG[0]))\n tIndex.idx[0] += int(mesh.inCorePoints.size());\n if (!(inCoreFlag & CoredMeshData::IN_CORE_FLAG[1]))\n tIndex.idx[1] += int(mesh.inCorePoints.size());\n if (!(inCoreFlag & CoredMeshData::IN_CORE_FLAG[2]))\n tIndex.idx[2] += int(mesh.inCorePoints.size());\n for (int j = 0; j < 3; j++)\n v.vertices[j] = tIndex.idx[j];\n polygons[i] = v;\n }\n}\n\n\n#define PCL_INSTANTIATE_Poisson(T) template class PCL_EXPORTS pcl::surface::Poisson<T>;\n\n#endif \/\/ PCL_SURFACE_IMPL_POISSON_H_\n\n<|endoftext|>"} {"text":"<commit_before>\/*\"name\": \"sensorflare\",\nAuthor: \"LPFraile <lidiapf0@gmail.com>\",\nLicense: \"BSD\",\nVersion: \"0.0.1\",\nDescription: \"Include your Particle Core on Sensorflare\"\nFile: Examplo:Publish on sensorflare different variables of the code upload on Particle core\n*\/\n\/\/Include the SensorFlare library \n#include \"sensorflare\/sensorflare.h\"\n\n\/\/Initialize objects from the library\n\n\/\/One object of the class \"PWMOut\" is initialized for \n\/\/every PWM output that will be remote control\nSensorFlare::PWMOut pwm(A0);\n\n\/\/One object of the class \"VarPublish\" is initialized for every variable\n\/\/that will be published in order to access remotly from the cloud\n\/\/The argument that name the varible has a maximum of 12 characters\n\/\/Both methods initialized the variable that will be published as PUBLIC \nSensorFlare::VarPublish varTem(\"temperature\");\nSensorFlare::VarPublish varPir(\"pir\",\"PUBLIC\");\n\/\/Initialized the variable that will be published as PRIVATE\nSensorFlare::VarPublish varLight(\"light\",\"PRIVATE\");\n\n\/\/ Initialize the different variables that will be used in the program\nint tem_pin=A3;\nint light_pin=A4;\nint pir_pin=D0;\nint status;\nint new_status;\nbool change;\n\nvoid setup() {\n \n\/\/ Call the begin() functions for every object of the classes \"DigitalOut\" and \n\/\/\"PWMout\" to be wired up correct and available.\n\n pwm.begin();\n \n\/\/Set the extra pins that are used on the program, but are not controlled remotely\n pinMode(pir_pin,INPUT);\n\n}\n\nvoid loop() {\n \n \/\/ Temperature sensor\n float tem= analogRead(tem_pin); \/\/ read value from the sensor\n \/\/ The returned value from the Core is going to be in the range from 0 to 4095\n \/\/ Calculate the voltage from the sensor reading\n float voltage = (tem * 3.3) \/ 4095;\n float deg =voltage* 100; \/\/ multiply by 100 to get degrees in K\n float temperature = deg - 273.15; \/\/ subtract absolute zero to get degrees Celsius\n \n \/\/Luminosity\n float photocell= analogRead(light_pin); \/\/ read value from the sensor\n \/\/ The returned value from the Core is going to be in the range from 0 to 4095\n \/\/ Calculate the voltage from the sensor reading\n float Vphotocell = ((photocell * 3.3) \/ 4095);\n float rl=(Vphotocell*10)\/(3.3-Vphotocell);\/\/Photoresistor value in KΩ\n float value=500\/rl;\/\/luminosity \n int light= (int) value; \n \n \/\/Find the change of state of the PIR sensor. Recognize move\n new_status=digitalRead(pir_pin);\n if (status!=new_status){\n status=new_status;\n change=TRUE;\n }\n \n \/\/Publish every time that exist a change in the pin on which is connect the output of the PIR\n if (change==TRUE) {\n varPir.Publish(status,0);\/\/Publish the variable at the called method time \n change=FALSE;\n }\n \n \/\/Publish the variables every 15 seconds.\n varTem.Publish(temperature,15);\n varLight.Publish(light,15);\n\n}\n<commit_msg>Update senorflare-publish.cpp<commit_after>\/*\"name\": \"sensorflare\",\nAuthor: \"LPFraile <lidiapf0@gmail.com>\",\nLicense: \"BSD\",\nVersion: \"0.0.1\",\nDescription: \"Include your Particle Core on Sensorflare\"\nFile: Examplo:Publish on your Sensorflare account some variables of the code upload on your Particle core.\n*\/\n\/\/Include the SensorFlare library \n#include \"sensorflare\/sensorflare.h\"\n\n\/\/Initialize objects from the library\n\n\/\/One object of the class \"PWMOut\" is initialized for \n\/\/every PWM output that will be remote control\nSensorFlare::PWMOut pwm(A0);\n\n\/\/One object of the class \"VarPublish\" is initialized for every variable\n\/\/that will be published in order to access remotly from the cloud\n\/\/The argument that name the varible has a maximum of 12 characters\n\/\/Both methods initialized the variable that will be published as PUBLIC \nSensorFlare::VarPublish varTem(\"temperature\");\nSensorFlare::VarPublish varPir(\"pir\",\"PUBLIC\");\n\/\/Initialized the variable that will be published as PRIVATE\nSensorFlare::VarPublish varLight(\"light\",\"PRIVATE\");\n\n\/\/ Initialize the different variables that will be used in the program\nint tem_pin=A3;\nint light_pin=A4;\nint pir_pin=D0;\nint status;\nint new_status;\nbool change;\n\nvoid setup() {\n \n\/\/ Call the begin() functions for every object of the classes \"DigitalOut\" and \n\/\/\"PWMout\" to be wired up correct and available.\n\n pwm.begin();\n \n\/\/Set the extra pins that are used on the program, but are not controlled remotely\n pinMode(pir_pin,INPUT);\n\n}\n\nvoid loop() {\n \n \/\/ Temperature sensor\n float tem= analogRead(tem_pin); \/\/ read value from the sensor\n \/\/ The returned value from the Core is going to be in the range from 0 to 4095\n \/\/ Calculate the voltage from the sensor reading\n float voltage = (tem * 3.3) \/ 4095;\n float deg =voltage* 100; \/\/ multiply by 100 to get degrees in K\n float temperature = deg - 273.15; \/\/ subtract absolute zero to get degrees Celsius\n \n \/\/Luminosity\n float photocell= analogRead(light_pin); \/\/ read value from the sensor\n \/\/ The returned value from the Core is going to be in the range from 0 to 4095\n \/\/ Calculate the voltage from the sensor reading\n float Vphotocell = ((photocell * 3.3) \/ 4095);\n float rl=(Vphotocell*10)\/(3.3-Vphotocell);\/\/Photoresistor value in KΩ\n float value=500\/rl;\/\/luminosity \n int light= (int) value; \n \n \/\/Find the change of state of the PIR sensor. Recognize move\n new_status=digitalRead(pir_pin);\n if (status!=new_status){\n status=new_status;\n change=TRUE;\n }\n \n \/\/Publish every time that exist a change in the pin on which is connect the output of the PIR\n if (change==TRUE) {\n varPir.Publish(status,0);\/\/Publish the variable at the called method time \n change=FALSE;\n }\n \n \/\/Publish the variables every 15 seconds.\n varTem.Publish(temperature,15);\n varLight.Publish(light,15);\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\r\n*\tExtraWork - Allows PvPGN clients to load this DLL and executes code for specific clients\r\n*\tCopyright (C) 2014 xboi209 (xboi209@gmail.com)\r\n*\r\n*\tThis program is free software: you can redistribute it and\/or modify\r\n*\tit under the terms of the GNU General Public License as published by\r\n*\tthe Free Software Foundation, either version 3 of the License, or\r\n*\t(at your option) any later version.\r\n*\r\n*\tThis program is distributed in the hope that it will be useful,\r\n*\tbut WITHOUT ANY WARRANTY; without even the implied warranty of\r\n*\tMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\r\n*\tGNU General Public License for more details.\r\n*\r\n*\tYou should have received a copy of the GNU General Public License\r\n*\talong with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\r\n*\/\r\n\r\n#define WIN32_LEAN_AND_MEAN\r\n\r\n#include <Windows.h>\r\n#include <TlHelp32.h>\r\n#include \"ExtraWork.h\"\r\n\r\n\r\nBOOL __fastcall ExtraWork(EXTRAWORK *inStruct, int \/*unused*\/ )\r\n{\r\n\tif (inStruct)\r\n\t\tstrcpy_s(inStruct->OutBuffer, sizeof(inStruct->OutBuffer), \"IX86ExtraWork v1.0 by xboi209\");\r\n\telse\r\n\t\treturn FALSE;\r\n\r\n\tgame.pid = GetCurrentProcessId();\r\n\tgame.handle = OpenProcess(PROCESS_CREATE_THREAD | PROCESS_DUP_HANDLE | PROCESS_QUERY_INFORMATION | PROCESS_SET_INFORMATION | PROCESS_SUSPEND_RESUME | PROCESS_TERMINATE | PROCESS_VM_OPERATION | PROCESS_VM_READ | PROCESS_VM_WRITE, FALSE, game.pid);\r\n\tEnumWindows((WNDENUMPROC)enumWindowsProc, NULL);\r\n\tGetClassName(game.hWnd, (LPTSTR)game.classname, 256\/*number of characters, not bytes*\/);\r\n\r\n\t\/\/Check what the game is and call a function specifically for that game\r\n\tif (strcmp(game.classname, SEXP) == 0)\r\n\t\tsexp();\r\n\telse if (strcmp(game.classname, W3XP) == 0)\r\n\t\tw3xp();\r\n\telse if (strcmp(game.classname, D2XP) == 0)\r\n\t\td2xp();\r\n\telse\r\n\t\treturn FALSE;\r\n\r\n\treturn TRUE;\r\n}\r\n\r\n\r\nvoid sexp()\r\n{\r\n\treturn;\r\n}\r\n\r\nvoid w3xp()\r\n{\r\n\treturn;\r\n}\r\n\r\nvoid d2xp()\r\n{\r\n\treturn;\r\n}\r\n\r\nBOOL CALLBACK enumWindowsProc(HWND hWnd, LPARAM \/*lParam*\/)\r\n{\r\n\tDWORD tempPID;\r\n\tchar className[256];\r\n\r\n\tGetWindowThreadProcessId(hWnd, &tempPID);\r\n\r\n\tif (tempPID == game.pid)\r\n\t{\r\n\t\tGetClassName(hWnd, className, 256\/*number of characters, not bytes*\/);\r\n\r\n\t\tfor (int i = 0; i < classNameElementSize; ++i)\r\n\t\t{\r\n\t\t\tif (strcmp(classNames[i], className) == 0)\r\n\t\t\t{\r\n\t\t\t\tgame.hWnd = hWnd;\r\n\t\t\t\treturn FALSE;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\treturn TRUE;\r\n}\r\n<commit_msg>Update ExtraWork.cpp<commit_after>\/*\r\n*\tExtraWork - Allows PvPGN clients to load this DLL and executes code for specific clients\r\n*\tCopyright (C) 2014 xboi209 (xboi209@gmail.com)\r\n*\r\n*\tThis program is free software: you can redistribute it and\/or modify\r\n*\tit under the terms of the GNU General Public License as published by\r\n*\tthe Free Software Foundation, either version 3 of the License, or\r\n*\t(at your option) any later version.\r\n*\r\n*\tThis program is distributed in the hope that it will be useful,\r\n*\tbut WITHOUT ANY WARRANTY; without even the implied warranty of\r\n*\tMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\r\n*\tGNU General Public License for more details.\r\n*\r\n*\tYou should have received a copy of the GNU General Public License\r\n*\talong with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\r\n*\/\r\n\r\n#define WIN32_LEAN_AND_MEAN\r\n\r\n#include <Windows.h>\r\n#include <TlHelp32.h>\r\n#include \"ExtraWork.h\"\r\n\r\n\r\n__declspec(dllexport) BOOL __fastcall ExtraWork(EXTRAWORK *inStruct, int \/*unused*\/ )\r\n{\r\n\tif (inStruct)\r\n\t\tstrcpy_s(inStruct->OutBuffer, sizeof(inStruct->OutBuffer), \"IX86ExtraWork v1.0 by xboi209\");\r\n\telse\r\n\t\treturn FALSE;\r\n\r\n\tgame.pid = GetCurrentProcessId();\r\n\tgame.handle = OpenProcess(PROCESS_CREATE_THREAD | PROCESS_DUP_HANDLE | PROCESS_QUERY_INFORMATION | PROCESS_SET_INFORMATION | PROCESS_SUSPEND_RESUME | PROCESS_TERMINATE | PROCESS_VM_OPERATION | PROCESS_VM_READ | PROCESS_VM_WRITE, FALSE, game.pid);\r\n\tEnumWindows((WNDENUMPROC)enumWindowsProc, NULL);\r\n\tGetClassName(game.hWnd, (LPTSTR)game.classname, 256\/*number of characters, not bytes*\/);\r\n\r\n\t\/\/Check what the game is and call a function specifically for that game\r\n\tif (strcmp(game.classname, SEXP) == 0)\r\n\t\tsexp();\r\n\telse if (strcmp(game.classname, W3XP) == 0)\r\n\t\tw3xp();\r\n\telse if (strcmp(game.classname, D2XP) == 0)\r\n\t\td2xp();\r\n\telse\r\n\t\treturn FALSE;\r\n\r\n\treturn TRUE;\r\n}\r\n\r\n\r\nvoid sexp()\r\n{\r\n\treturn;\r\n}\r\n\r\nvoid w3xp()\r\n{\r\n\treturn;\r\n}\r\n\r\nvoid d2xp()\r\n{\r\n\treturn;\r\n}\r\n\r\nBOOL CALLBACK enumWindowsProc(HWND hWnd, LPARAM \/*lParam*\/)\r\n{\r\n\tDWORD tempPID;\r\n\tchar className[256];\r\n\r\n\tGetWindowThreadProcessId(hWnd, &tempPID);\r\n\r\n\tif (tempPID == game.pid)\r\n\t{\r\n\t\tGetClassName(hWnd, className, 256\/*number of characters, not bytes*\/);\r\n\r\n\t\tfor (int i = 0; i < classNameElementSize; ++i)\r\n\t\t{\r\n\t\t\tif (strcmp(classNames[i], className) == 0)\r\n\t\t\t{\r\n\t\t\t\tgame.hWnd = hWnd;\r\n\t\t\t\treturn FALSE;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\treturn TRUE;\r\n}\r\n<|endoftext|>"} {"text":"<commit_before>#include \"stdafx.h\"\n#include \"DataCache.h\"\n\nCDataCache::CDataCache(CFxQueue& queue)\n : m_queue(queue)\n , m_isEventGenerated(false)\n , m_isSessionInfoInitialized(false)\n{\n}\n\nCFxSessionInfo CDataCache::GetSessionInfo() const\n{\n\tCSharedLocker lock(m_synchronizer);\n\treturn m_sessionInfo;\n}\n\nvoid CDataCache::UpdateSessionInfo(const CFxSessionInfo& sessionInfo)\n{\n\tCExclusiveLocker lock(m_synchronizer);\n\tm_sessionInfo = sessionInfo;\n\tm_isSessionInfoInitialized = true;\n}\n\nvoid CDataCache::Clear()\n{\n\tm_sessionInfo = CFxSessionInfo();\n\tm_isSessionInfoInitialized = false;\n\tm_isEventGenerated = false;\n}\n\nvoid CDataCache::Update(bool isInitialized)\n{\n\tconst bool isCacheInitialized = isInitialized && m_isSessionInfoInitialized;\n\n\tif (!isCacheInitialized)\n\t{\n\t\treturn;\n\t}\n\n\tif (!m_isEventGenerated)\n\t{\n\t\tCFxEventInfo eventInfo;\n\t\tCFxMessage message(FX_MSG_CACHE_UPDATED, eventInfo);\n\t\tm_queue.ProcessMessage(message);\n\t\tm_isEventGenerated = true;\n\t}\n\t\n}\n<commit_msg>Bugfix problem with deadlock in cache initializaion<commit_after>#include \"stdafx.h\"\n#include \"DataCache.h\"\n\nCDataCache::CDataCache(CFxQueue& queue)\n : m_queue(queue)\n , m_isEventGenerated(false)\n , m_isSessionInfoInitialized(false)\n{\n}\n\nCFxSessionInfo CDataCache::GetSessionInfo() const\n{\n CSharedLocker lock(m_synchronizer);\n return m_sessionInfo;\n}\n\nvoid CDataCache::UpdateSessionInfo(const CFxSessionInfo& sessionInfo)\n{\n CExclusiveLocker lock(m_synchronizer);\n m_sessionInfo = sessionInfo;\n m_isSessionInfoInitialized = true;\n}\n\nvoid CDataCache::Clear()\n{\n m_sessionInfo = CFxSessionInfo();\n m_isSessionInfoInitialized = false;\n m_isEventGenerated = false;\n}\n\nvoid CDataCache::Update(bool isInitialized)\n{\n \/\/ Bugfix problem with deadlock in cache initializaion\n \/\/ const bool isCacheInitialized = isInitialized && m_isSessionInfoInitialized;\n const bool isCacheInitialized = isInitialized;\n\n if (!isCacheInitialized)\n {\n return;\n }\n\n if (!m_isEventGenerated)\n {\n CFxEventInfo eventInfo;\n CFxMessage message(FX_MSG_CACHE_UPDATED, eventInfo);\n m_queue.ProcessMessage(message);\n m_isEventGenerated = true;\n }\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/* Copyright 2021 The TensorFlow Authors. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*\/\n\n#include \"tensorflow\/lite\/c\/common.h\"\n#include \"tensorflow\/lite\/kernels\/internal\/tensor_ctypes.h\"\n#include \"tensorflow\/lite\/kernels\/kernel_util.h\"\n#include \"tensorflow\/lite\/micro\/kernels\/kernel_util.h\"\n#include \"tensorflow\/lite\/micro\/micro_utils.h\"\n\nnamespace tflite {\nnamespace {\n\nconstexpr int kInputTensor = 0;\nconstexpr int kAxisTensor = 1;\nconstexpr int kOutputTensor = 0;\n\nTfLiteStatus ExpandTensorDim(TfLiteContext* context,\n const TfLiteEvalTensor* input, int axis,\n TfLiteEvalTensor* output) {\n const TfLiteIntArray* input_dims = input->dims;\n TfLiteIntArray* output_dims = output->dims;\n if (axis < 0) {\n axis = output_dims->size + axis;\n }\n TF_LITE_ENSURE(context, axis <= input_dims->size);\n\n for (int i = 0; i < output_dims->size; ++i) {\n if (i < axis) {\n output_dims->data[i] = input_dims->data[i];\n } else if (i == axis) {\n output_dims->data[i] = 1;\n } else {\n output_dims->data[i] = input_dims->data[i - 1];\n }\n }\n return kTfLiteOk;\n}\n\nTfLiteStatus GetAxisValueFromTensor(TfLiteContext* context,\n const TfLiteEvalTensor* axis,\n int32_t* axis_value) {\n const int axis_dims = (tflite::micro::GetTensorShape(axis)).DimensionsCount();\n if (axis_dims > 1) {\n TF_LITE_KERNEL_LOG(context, \"Axis has only one element for Expand_Dims.\",\n axis_dims);\n return kTfLiteError;\n }\n\n if (kTfLiteInt32 == (axis->type)) {\n const int32_t* axis_ptr = tflite::micro::GetTensorData<int32_t>(axis);\n *axis_value = axis_ptr[0];\n return kTfLiteOk;\n } else {\n TF_LITE_KERNEL_LOG(context,\n \"Axis type %s (%d) not supported by Expand_Dims.\",\n TfLiteTypeGetName(axis->type), axis->type);\n return kTfLiteError;\n }\n}\n\nTfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {\n TF_LITE_ENSURE_EQ(context, NumInputs(node), 2);\n TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1);\n const TfLiteTensor* input;\n TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kInputTensor, &input));\n const TfLiteTensor* axis;\n TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kAxisTensor, &axis));\n TfLiteTensor* output;\n TF_LITE_ENSURE_OK(context,\n GetOutputSafe(context, node, kOutputTensor, &output));\n output->type = input->type;\n if (IsDynamicTensor(axis)) {\n TF_LITE_KERNEL_LOG(context,\n \"DynamicTensor is not yet supported by Expand_Dims.\");\n return kTfLiteError;\n }\n return kTfLiteOk;\n}\n\ntemplate <typename Tin, typename Tout>\nvoid memCopyN(Tout* out, Tin* in, const int num_elements) {\n for (int i = 0; i < num_elements; ++i) {\n out[i] = static_cast<Tout>(in[i]);\n }\n}\n\nTfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) {\n const TfLiteEvalTensor* input =\n tflite::micro::GetEvalInput(context, node, kInputTensor);\n const TfLiteEvalTensor* axis =\n tflite::micro::GetEvalInput(context, node, kAxisTensor);\n TfLiteEvalTensor* output =\n tflite::micro::GetEvalOutput(context, node, kOutputTensor);\n const int flat_size = ElementCount(*input->dims);\n const int input_dims = input->dims->size;\n\n int axis_value;\n TF_LITE_ENSURE_OK(context,\n GetAxisValueFromTensor(context, axis, &axis_value));\n if ((axis_value > static_cast<int32_t>(input_dims)) ||\n (axis_value < static_cast<int32_t>(-(input_dims + 1)))) {\n TF_LITE_KERNEL_LOG(context, \"Invalid Expand_Dims axis value (%d).\",\n axis_value);\n return kTfLiteError;\n }\n ExpandTensorDim(context, input, axis_value, output);\n\n switch (input->type) {\n case kTfLiteFloat32: {\n memCopyN(tflite::micro::GetTensorData<float>(output),\n tflite::micro::GetTensorData<float>(input), flat_size);\n } break;\n case kTfLiteInt8: {\n memCopyN(tflite::micro::GetTensorData<int8_t>(output),\n tflite::micro::GetTensorData<int8_t>(input), flat_size);\n } break;\n default:\n TF_LITE_KERNEL_LOG(\n context,\n \"Expand_Dims only currently supports int8 and float32, got %d.\",\n input->type);\n return kTfLiteError;\n }\n return kTfLiteOk;\n}\n} \/\/ namespace\n\nTfLiteRegistration Register_EXPAND_DIMS() {\n return {\/*init=*\/nullptr,\n \/*free=*\/nullptr,\n \/*prepare=*\/Prepare,\n \/*invoke=*\/Eval,\n \/*profiling_string=*\/nullptr,\n \/*builtin_code=*\/0,\n \/*custom_name=*\/nullptr,\n \/*version=*\/0};\n}\n\n} \/\/ namespace tflite\n<commit_msg>Consolidate int32_t axis to int for micro o EXPAND_DIMS<commit_after>\/* Copyright 2021 The TensorFlow Authors. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*\/\n\n#include \"tensorflow\/lite\/c\/common.h\"\n#include \"tensorflow\/lite\/kernels\/internal\/tensor_ctypes.h\"\n#include \"tensorflow\/lite\/kernels\/kernel_util.h\"\n#include \"tensorflow\/lite\/micro\/kernels\/kernel_util.h\"\n#include \"tensorflow\/lite\/micro\/micro_utils.h\"\n\nnamespace tflite {\nnamespace {\n\nconstexpr int kInputTensor = 0;\nconstexpr int kAxisTensor = 1;\nconstexpr int kOutputTensor = 0;\n\nTfLiteStatus ExpandTensorDim(TfLiteContext* context,\n const TfLiteEvalTensor* input, int axis,\n TfLiteEvalTensor* output) {\n const TfLiteIntArray* input_dims = input->dims;\n TfLiteIntArray* output_dims = output->dims;\n if (axis < 0) {\n axis = output_dims->size + axis;\n }\n TF_LITE_ENSURE(context, axis <= input_dims->size);\n\n for (int i = 0; i < output_dims->size; ++i) {\n if (i < axis) {\n output_dims->data[i] = input_dims->data[i];\n } else if (i == axis) {\n output_dims->data[i] = 1;\n } else {\n output_dims->data[i] = input_dims->data[i - 1];\n }\n }\n return kTfLiteOk;\n}\n\nTfLiteStatus GetAxisValueFromTensor(TfLiteContext* context,\n const TfLiteEvalTensor* axis,\n int* axis_value) {\n const int axis_dims = (tflite::micro::GetTensorShape(axis)).DimensionsCount();\n if (axis_dims > 1) {\n TF_LITE_KERNEL_LOG(context, \"Axis has only one element for Expand_Dims.\",\n axis_dims);\n return kTfLiteError;\n }\n\n if (kTfLiteInt32 == (axis->type)) {\n const int* axis_ptr = tflite::micro::GetTensorData<int>(axis);\n *axis_value = axis_ptr[0];\n return kTfLiteOk;\n } else {\n TF_LITE_KERNEL_LOG(context,\n \"Axis type %s (%d) not supported by Expand_Dims.\",\n TfLiteTypeGetName(axis->type), axis->type);\n return kTfLiteError;\n }\n}\n\nTfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {\n TF_LITE_ENSURE_EQ(context, NumInputs(node), 2);\n TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1);\n const TfLiteTensor* input;\n TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kInputTensor, &input));\n const TfLiteTensor* axis;\n TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kAxisTensor, &axis));\n TfLiteTensor* output;\n TF_LITE_ENSURE_OK(context,\n GetOutputSafe(context, node, kOutputTensor, &output));\n output->type = input->type;\n if (IsDynamicTensor(axis)) {\n TF_LITE_KERNEL_LOG(context,\n \"DynamicTensor is not yet supported by Expand_Dims.\");\n return kTfLiteError;\n }\n return kTfLiteOk;\n}\n\ntemplate <typename Tin, typename Tout>\nvoid memCopyN(Tout* out, Tin* in, const int num_elements) {\n for (int i = 0; i < num_elements; ++i) {\n out[i] = static_cast<Tout>(in[i]);\n }\n}\n\nTfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) {\n const TfLiteEvalTensor* input =\n tflite::micro::GetEvalInput(context, node, kInputTensor);\n const TfLiteEvalTensor* axis =\n tflite::micro::GetEvalInput(context, node, kAxisTensor);\n TfLiteEvalTensor* output =\n tflite::micro::GetEvalOutput(context, node, kOutputTensor);\n const int flat_size = ElementCount(*input->dims);\n const int input_dims = input->dims->size;\n\n int axis_value;\n TF_LITE_ENSURE_OK(context,\n GetAxisValueFromTensor(context, axis, &axis_value));\n if ((axis_value > static_cast<int>(input_dims)) ||\n (axis_value < static_cast<int>(-(input_dims + 1)))) {\n TF_LITE_KERNEL_LOG(context, \"Invalid Expand_Dims axis value (%d).\",\n axis_value);\n return kTfLiteError;\n }\n ExpandTensorDim(context, input, axis_value, output);\n\n switch (input->type) {\n case kTfLiteFloat32: {\n memCopyN(tflite::micro::GetTensorData<float>(output),\n tflite::micro::GetTensorData<float>(input), flat_size);\n } break;\n case kTfLiteInt8: {\n memCopyN(tflite::micro::GetTensorData<int8_t>(output),\n tflite::micro::GetTensorData<int8_t>(input), flat_size);\n } break;\n default:\n TF_LITE_KERNEL_LOG(\n context,\n \"Expand_Dims only currently supports int8 and float32, got %d.\",\n input->type);\n return kTfLiteError;\n }\n return kTfLiteOk;\n}\n} \/\/ namespace\n\nTfLiteRegistration Register_EXPAND_DIMS() {\n return {\/*init=*\/nullptr,\n \/*free=*\/nullptr,\n \/*prepare=*\/Prepare,\n \/*invoke=*\/Eval,\n \/*profiling_string=*\/nullptr,\n \/*builtin_code=*\/0,\n \/*custom_name=*\/nullptr,\n \/*version=*\/0};\n}\n\n} \/\/ namespace tflite\n<|endoftext|>"} {"text":"<commit_before>#include \"ParticleSystem.h\"\n#include <vector>\n\n#define BUFFER_OFFSET(i) ((char *)nullptr + (i))\n\nParticleSystem::ParticleSystem(ShaderProgram* shaderProgram, Texture* texture, glm::vec3 origin, int maxParticleCount, int chanceToEmit, float maxVelocity, float maxLifeTime) {\n\tthis->shaderProgram = shaderProgram;\n\tthis->texture = texture;\n\n\tparticleOrigin = origin;\n\tthis->maxParticleCount = maxParticleCount;\n\tthis->chanceToEmit = chanceToEmit;\n\tthis->maxVelocity = maxVelocity;\n\tthis->maxLifeTime = maxLifeTime;\n\tparticleCount = 0;\n\n\tbindPointData();\n}\n\nParticleSystem::~ParticleSystem() {\n\tglDeleteBuffers(1, &vertexBuffer);\n}\n\nunsigned int ParticleSystem::getParticleCount() {\n\treturn particleCount;\n}\n\nunsigned int ParticleSystem::getMaxParticleCount() {\n\treturn maxParticleCount;\n}\n\nvoid ParticleSystem::update(double time) {\n\tif (!this->particlePositions.empty()) {\n\t\tfor (std::vector<int>::size_type i = 0; i != particleProperties.size(); i++) {\n\t\t\tif (particleProperties[i].lifetime > maxLifeTime) {\n\t\t\t\tparticlePositions.erase(particlePositions.begin() + i);\n\t\t\t\tparticleProperties.erase(particleProperties.begin() + i);\n\t\t\t\tparticleCount--;\n\t\t\t\ti--;\n\t\t\t} else {\n\t\t\t\tparticlePositions[i].worldPos += static_cast<float>(time)* particleProperties[i].velocity;\n\t\t\t\tparticleProperties[i].lifetime += static_cast<float>(time);\n\t\t\t}\n\t\t}\n\t}\n\temitParticle();\n\n\tif (particleCount > 0)\n\t\tglBufferSubData(GL_ARRAY_BUFFER, 0, particleCount * sizeof(ParticleSystem::ParticlePosition), &this->particlePositions[0]);\n}\n\nvoid ParticleSystem::render(int width, int height, const Camera* camera) {\n\tshaderProgram->use();\n\n\tglUniform1i(shaderProgram->uniformLocation(\"baseImage\"), 0);\n\n\tglActiveTexture(GL_TEXTURE0 + 0);\n\tglBindTexture(GL_TEXTURE_2D, texture->textureID());\n\n\tglBindVertexArray(vertexAttribute);\n\n\t\/\/ Base image texture\n\tglActiveTexture(GL_TEXTURE0 + 0);\n\tglBindTexture(GL_TEXTURE_2D, texture->textureID());\n\n\t\/\/ Send the matrices to the shader.\n\tglm::mat4 view = camera->view();\n\n\tglUniformMatrix4fv(shaderProgram->uniformLocation(\"viewMatrix\"), 1, GL_FALSE, &view[0][0]);\n\tglUniformMatrix4fv(shaderProgram->uniformLocation(\"projectionMatrix\"), 1, GL_FALSE, &camera->projection(width, height)[0][0]);\n\n\t\/\/ Draw the triangles\n\tglDrawArrays(GL_POINTS, 0, getParticleCount());\n}\n\nvoid ParticleSystem::bindPointData() {\n\t\/\/ Vertex buffer\n\tglGenBuffers(1, &vertexBuffer);\n\tglBindBuffer(GL_ARRAY_BUFFER, vertexBuffer);\n\tglBufferData(GL_ARRAY_BUFFER, maxParticleCount * sizeof(ParticleSystem::ParticlePosition), NULL, GL_DYNAMIC_DRAW);\n\n\t\/\/ Define vertex data layout\n\tglGenVertexArrays(1, &vertexAttribute);\n\tglBindVertexArray(vertexAttribute);\n\tglEnableVertexAttribArray(0);\n\n\tGLuint vertexPos = shaderProgram->attributeLocation(\"vertex_position\");\n\tglVertexAttribPointer(vertexPos, 3, GL_FLOAT, GL_FALSE, sizeof(ParticleSystem::ParticlePosition), BUFFER_OFFSET(0));\n}\n\nvoid ParticleSystem::emitParticle() {\n\tif ((rand() % 1000 < chanceToEmit) && (particleCount < maxParticleCount)) {\n\t\tParticlePosition newPosition;\n\t\tParticleProperty newProperty;\n\n\t\tnewPosition.worldPos = particleOrigin;\n\t\tnewProperty.lifetime = 0.f - static_cast<float>(rand() % static_cast<int>(maxLifeTime * 2));\n\t\tnewProperty.velocity.x = static_cast<float>(rand() % (2 * static_cast<int>(maxVelocity)) - static_cast<int>(maxVelocity));\n\t\tnewProperty.velocity.y = static_cast<float>(rand() % (2 * static_cast<int>(maxVelocity)) - static_cast<int>(maxVelocity));\n\t\tnewProperty.velocity.z = static_cast<float>(rand() % (2 * static_cast<int>(maxVelocity)) - static_cast<int>(maxVelocity));\n\n\t\tparticlePositions.push_back(newPosition);\n\t\tparticleProperties.push_back(newProperty);\n\n\t\tparticleCount++;\n\t}\n}<commit_msg>Additive particle blending<commit_after>#include \"ParticleSystem.h\"\n#include <vector>\n\n#define BUFFER_OFFSET(i) ((char *)nullptr + (i))\n\nParticleSystem::ParticleSystem(ShaderProgram* shaderProgram, Texture* texture, glm::vec3 origin, int maxParticleCount, int chanceToEmit, float maxVelocity, float maxLifeTime) {\n\tthis->shaderProgram = shaderProgram;\n\tthis->texture = texture;\n\n\tparticleOrigin = origin;\n\tthis->maxParticleCount = maxParticleCount;\n\tthis->chanceToEmit = chanceToEmit;\n\tthis->maxVelocity = maxVelocity;\n\tthis->maxLifeTime = maxLifeTime;\n\tparticleCount = 0;\n\n\tbindPointData();\n}\n\nParticleSystem::~ParticleSystem() {\n\tglDeleteBuffers(1, &vertexBuffer);\n}\n\nunsigned int ParticleSystem::getParticleCount() {\n\treturn particleCount;\n}\n\nunsigned int ParticleSystem::getMaxParticleCount() {\n\treturn maxParticleCount;\n}\n\nvoid ParticleSystem::update(double time) {\n\tif (!this->particlePositions.empty()) {\n\t\tfor (std::vector<int>::size_type i = 0; i != particleProperties.size(); i++) {\n\t\t\tif (particleProperties[i].lifetime > maxLifeTime) {\n\t\t\t\tparticlePositions.erase(particlePositions.begin() + i);\n\t\t\t\tparticleProperties.erase(particleProperties.begin() + i);\n\t\t\t\tparticleCount--;\n\t\t\t\ti--;\n\t\t\t} else {\n\t\t\t\tparticlePositions[i].worldPos += static_cast<float>(time)* particleProperties[i].velocity;\n\t\t\t\tparticleProperties[i].lifetime += static_cast<float>(time);\n\t\t\t}\n\t\t}\n\t}\n\temitParticle();\n\n\tif (particleCount > 0)\n\t\tglBufferSubData(GL_ARRAY_BUFFER, 0, particleCount * sizeof(ParticleSystem::ParticlePosition), &this->particlePositions[0]);\n}\n\nvoid ParticleSystem::render(int width, int height, const Camera* camera) {\n\t\/\/ Don't write to depth buffer.\n\tGLboolean depthWriting;\n\tglGetBooleanv(GL_DEPTH_WRITEMASK, &depthWriting);\n\tglDepthMask(GL_FALSE);\n\n\t\/\/ Blending\n\tGLboolean blending;\n\tglGetBooleanv(GL_BLEND, &blending);\n\tglEnable(GL_BLEND);\n\tglBlendFunc(GL_ONE, GL_ONE);\n\n\tshaderProgram->use();\n\n\tglUniform1i(shaderProgram->uniformLocation(\"baseImage\"), 0);\n\n\tglActiveTexture(GL_TEXTURE0 + 0);\n\tglBindTexture(GL_TEXTURE_2D, texture->textureID());\n\n\tglBindVertexArray(vertexAttribute);\n\n\t\/\/ Base image texture\n\tglActiveTexture(GL_TEXTURE0 + 0);\n\tglBindTexture(GL_TEXTURE_2D, texture->textureID());\n\n\t\/\/ Send the matrices to the shader.\n\tglm::mat4 view = camera->view();\n\n\tglUniformMatrix4fv(shaderProgram->uniformLocation(\"viewMatrix\"), 1, GL_FALSE, &view[0][0]);\n\tglUniformMatrix4fv(shaderProgram->uniformLocation(\"projectionMatrix\"), 1, GL_FALSE, &camera->projection(width, height)[0][0]);\n\n\t\/\/ Draw the triangles\n\tglDrawArrays(GL_POINTS, 0, getParticleCount());\n\n\t\/\/ Reset state values we've changed.\n\tglDepthMask(depthWriting);\n\tif (!blending)\n\t\tglDisable(GL_BLEND);\n}\n\nvoid ParticleSystem::bindPointData() {\n\t\/\/ Vertex buffer\n\tglGenBuffers(1, &vertexBuffer);\n\tglBindBuffer(GL_ARRAY_BUFFER, vertexBuffer);\n\tglBufferData(GL_ARRAY_BUFFER, maxParticleCount * sizeof(ParticleSystem::ParticlePosition), NULL, GL_DYNAMIC_DRAW);\n\n\t\/\/ Define vertex data layout\n\tglGenVertexArrays(1, &vertexAttribute);\n\tglBindVertexArray(vertexAttribute);\n\tglEnableVertexAttribArray(0);\n\n\tGLuint vertexPos = shaderProgram->attributeLocation(\"vertex_position\");\n\tglVertexAttribPointer(vertexPos, 3, GL_FLOAT, GL_FALSE, sizeof(ParticleSystem::ParticlePosition), BUFFER_OFFSET(0));\n}\n\nvoid ParticleSystem::emitParticle() {\n\tif ((rand() % 1000 < chanceToEmit) && (particleCount < maxParticleCount)) {\n\t\tParticlePosition newPosition;\n\t\tParticleProperty newProperty;\n\n\t\tnewPosition.worldPos = particleOrigin;\n\t\tnewProperty.lifetime = 0.f - static_cast<float>(rand() % static_cast<int>(maxLifeTime * 2));\n\t\tnewProperty.velocity.x = static_cast<float>(rand() % (2 * static_cast<int>(maxVelocity)) - static_cast<int>(maxVelocity));\n\t\tnewProperty.velocity.y = static_cast<float>(rand() % (2 * static_cast<int>(maxVelocity)) - static_cast<int>(maxVelocity));\n\t\tnewProperty.velocity.z = static_cast<float>(rand() % (2 * static_cast<int>(maxVelocity)) - static_cast<int>(maxVelocity));\n\n\t\tparticlePositions.push_back(newPosition);\n\t\tparticleProperties.push_back(newProperty);\n\n\t\tparticleCount++;\n\t}\n}<|endoftext|>"} {"text":"<commit_before>#include \"stdafx.h\"\n#include \"cartrige.h\"\n\nstruct rom_header\n{\n\tu8 start_vector[4]; \n\tu8 nintendo_logo[48];\n\tu8 game_title[11];\n\tu8 manufacturer_code[4];\n\tu8 cgb_flag;\n\tu8 new_license_code[2];\n\tu8 sgb_flag;\n\tu8 cartrige_type;\n\tu8 rom_size;\n\tu8 ram_size;\n\tu8 destination_code;\n\tu8 old_license_code;\n\tu8 rom_version;\n\tu8 checksum;\n\tu8 global_checksum[2];\n};\n\nbool in_range(u32 value, u32 begin, u32 end)\n{\n\treturn (value >= begin) && (value <= end);\n}\n\nu32 get_ram_size(u8 val)\n{\n\tassert(val < 6);\n\n\tstatic const u32 sizes[] = { 0, 0x800, 0x2000, 0x8000, 0x20000, 0x10000 };\n\n\treturn sizes[val];\n}\n\nCartrige::~Cartrige()\n{\n\tif (battery_ram)\n\t{\n\t\tstd::ofstream ram_file(file_name + \"_ram\", std::ios::trunc | std::ios::binary);\n\t\trom_header* header = reinterpret_cast<rom_header*>(&rom[0x100]);\n\n\t\tif (in_range(header->rom_version, 0x0F, 0x10))\n\t\t\tram_file.write(reinterpret_cast<char*>(rtc_regs), 5);\n\n\t\tram_file.write(reinterpret_cast<char*>(ram.get()), ram_size);\n\t}\n}\n\nvoid Cartrige::load_ram()\n{\n\trom_header* header = reinterpret_cast<rom_header*>(&rom[0x100]);\n\n\t\/\/MBC2 has always header->ram_size == 0, but it has 512 bytes actually!\n\tif (in_range(header->cartrige_type, 0x05, 0x06))\n\t\tram_size = 512;\n\n\telse\n\t\tram_size = get_ram_size(header->ram_size);\n\n\tram = ram_size ? std::make_unique<u8[]>(ram_size) : nullptr;\n\n\tswitch (header->cartrige_type)\n\t{\n\t\tcase 0x03:\n\t\tcase 0x06:\n\t\tcase 0x09:\n\t\tcase 0x0D:\n\t\tcase 0x0F:\n\t\tcase 0x10:\n\t\tcase 0x13:\n\t\tcase 0x1B:\n\t\tcase 0x1E:\n\t\t\tbattery_ram = true;\n\t\t\tbreak;\n\n\t\tdefault:\n\t\t\tbattery_ram = false;\n\t\t\tbreak;\n\t}\n\n\tif (battery_ram)\n\t{\n\t\tstd::ifstream ram_file(file_name + \"_ram\", std::ios::binary);\n\n\t\tif (ram_file.is_open())\n\t\t{\n\t\t\t\/\/if this is mbc3 cart, we need to read additional time registers\n\t\t\tif (in_range(header->cartrige_type, 0x0F, 0x10))\n\t\t\t\tram_file.read(reinterpret_cast<char*>(rtc_regs), 5); \n\n\t\t\tram_file.read(reinterpret_cast<char*>(ram.get()), ram_size);\n\t\t}\n\t}\n}\n\nbool Cartrige::load_cartrige(const std::string& name)\n{\n\tstd::ifstream cart_file(name, std::ios::binary | std::ios::ate);\n\n\tif (!cart_file.is_open())\n\t\treturn false;\n\n\tsize_t size = cart_file.tellg();\n\tcart_file.seekg(0, std::ios_base::beg);\n\n\trom = std::make_unique<u8[]>(size);\n\tcart_file.read(reinterpret_cast<char*>(rom.get()), size);\n\n\tfile_name = name;\n\tload_ram();\n\tdispatch();\n\n\treturn true;\n}\n\nIMemory* Cartrige::get_memory_controller() const\n{\n\treturn memory_interface.get();\n}\n\nIDmaMemory* Cartrige::get_dma_controller() const\n{\n\treturn dma_interface;\n}\n\nbool Cartrige::is_cgb_ready() const\n{\n\tconst rom_header* header = reinterpret_cast<rom_header*>(&rom[0x100]);\n\n\treturn (header->cgb_flag == 0x80) || (header->cgb_flag == 0xC0);\n}\n\nvoid Cartrige::dispatch()\n{\n\trom_header* header = reinterpret_cast<rom_header*>(&rom[0x100]);\n\tu8 type = header->cartrige_type;\n\n\tif (type == 0x00 || type == 0x08 || type == 0x09)\n\t{\n\t\tauto tmp = std::make_unique<NoMBC>(NoMBC(rom.get(), ram.get()));\n\t\tdma_interface = tmp.get();\n\t\tmemory_interface = std::move(tmp);\n\t}\n\n\telse if (in_range(type, 0x01, 0x03))\n\t{\n\t\tauto tmp = std::make_unique<MBC1>(MBC1(rom.get(), ram.get()));\n\t\tdma_interface = tmp.get();\n\t\tmemory_interface = std::move(tmp);\n\t}\n\n\telse if (in_range(type, 0x05, 0x06))\n\t{\n\t\tauto tmp = std::make_unique<MBC2>(MBC2(rom.get(), ram.get()));\n\t\tdma_interface = tmp.get();\n\t\tmemory_interface = std::move(tmp);\n\t}\n\n\telse if (in_range(type, 0x0F, 0x13))\n\t{\n\t\tauto tmp = std::make_unique<MBC3>(MBC3(rom.get(), ram.get(), (type <= 0x10 ? rtc_regs : nullptr)));\n\t\tdma_interface = tmp.get();\n\t\tmemory_interface = std::move(tmp);\n\t}\n\n\telse if (in_range(type, 0x1A, 0x1E))\n\t{\n\t\tauto tmp = std::make_unique<MBC5>(MBC5(rom.get(), ram.get()));\n\t\tdma_interface = tmp.get();\n\t\tmemory_interface = std::move(tmp);\n\t}\n\n\telse\n\t\tmemory_interface = nullptr;\n}\n<commit_msg>added sving rtc regs to file with time passing<commit_after>#include \"stdafx.h\"\n#include \"cartrige.h\"\n\nstruct rom_header\n{\n\tu8 start_vector[4]; \n\tu8 nintendo_logo[48];\n\tu8 game_title[11];\n\tu8 manufacturer_code[4];\n\tu8 cgb_flag;\n\tu8 new_license_code[2];\n\tu8 sgb_flag;\n\tu8 cartrige_type;\n\tu8 rom_size;\n\tu8 ram_size;\n\tu8 destination_code;\n\tu8 old_license_code;\n\tu8 rom_version;\n\tu8 checksum;\n\tu8 global_checksum[2];\n};\n\nbool in_range(u32 value, u32 begin, u32 end)\n{\n\treturn (value >= begin) && (value <= end);\n}\n\nu32 get_ram_size(u8 val)\n{\n\tassert(val < 6);\n\n\tstatic const u32 sizes[] = { 0, 0x800, 0x2000, 0x8000, 0x20000, 0x10000 };\n\n\treturn sizes[val];\n}\n\nCartrige::~Cartrige()\n{\n\tconst rom_header* header = reinterpret_cast<rom_header*>(&rom[0x100]);\n\n\tif (battery_ram)\n\t{\n\t\tstd::ofstream ram_file(file_name + \"_ram\", std::ios::trunc | std::ios::binary);\n\t\tram_file.write(reinterpret_cast<char*>(ram.get()), ram_size);\n\t}\n\n\tif (in_range(header->rom_version, 0x0F, 0x10))\n\t{\n\t\tstd::ofstream rtc_file(file_name + \"_rtc\", std::ios::trunc);\n\n\t\tmemory_interface.reset(); \/\/make sure that MBC3 update rtc_regs\n\n\t\tauto epoch = std::chrono::system_clock::now().time_since_epoch();\n\t\tauto cur_timestamp = std::chrono::duration_cast<std::chrono::seconds>(epoch);\n\n\t\trtc_file << cur_timestamp.count();\n\t\trtc_file.write(reinterpret_cast<char*>(rtc_regs), sizeof(u8) * 5);\n\t}\n}\n\nvoid Cartrige::load_ram()\n{\n\trom_header* header = reinterpret_cast<rom_header*>(&rom[0x100]);\n\n\t\/\/MBC2 has always header->ram_size == 0, but it has 512 bytes actually!\n\tif (in_range(header->cartrige_type, 0x05, 0x06))\n\t\tram_size = 512;\n\n\telse\n\t\tram_size = get_ram_size(header->ram_size);\n\n\tram = ram_size ? std::make_unique<u8[]>(ram_size) : nullptr;\n\n\tswitch (header->cartrige_type)\n\t{\n\t\tcase 0x03:\n\t\tcase 0x06:\n\t\tcase 0x09:\n\t\tcase 0x0D:\n\t\tcase 0x0F:\n\t\tcase 0x10:\n\t\tcase 0x13:\n\t\tcase 0x1B:\n\t\tcase 0x1E:\n\t\t\tbattery_ram = true;\n\t\t\tbreak;\n\n\t\tdefault:\n\t\t\tbattery_ram = false;\n\t\t\tbreak;\n\t}\n\n\tif (battery_ram)\n\t{\n\t\tstd::ifstream ram_file(file_name + \"_ram\", std::ios::binary);\n\n\t\tif (ram_file.is_open())\n\t\t\tram_file.read(reinterpret_cast<char*>(ram.get()), ram_size);\n\t}\n\n\tif (in_range(header->cartrige_type, 0x0F, 0x10))\n\t{\n\t\tstd::ifstream rtc_file(file_name + \"_rtc\");\n\n\t\tif (rtc_file.is_open())\n\t\t{\n\t\t\ti64 saved_timestamp;\n\t\t\trtc_file >> saved_timestamp;\n\t\t\trtc_file.read(reinterpret_cast<char*>(rtc_regs), sizeof(u8) * 5);\n\n\t\t\tauto epoch = std::chrono::system_clock::now().time_since_epoch();\n\t\t\tauto cur_timestamp = std::chrono::duration_cast<std::chrono::seconds>(epoch);\n\t\t\tauto delta = cur_timestamp.count() - saved_timestamp;\n\n\t\t\tif (delta <= 0 || !check_bit(rtc_regs[4], 6))\n\t\t\t\treturn;\n\n\t\t\tauto ns = rtc_regs[0] + delta;\n\t\t\tauto nm = rtc_regs[1] + ns \/ 60;\n\t\t\tauto nh = rtc_regs[2] + nm \/ 60;\n\t\t\tauto nd = (((rtc_regs[4] & 1) << 8) | rtc_regs[3]) + nh \/ 24;\n\n\t\t\trtc_regs[0] = ns % 60;\n\t\t\trtc_regs[1] = nm % 60;\n\t\t\trtc_regs[2] = nh % 24;\n\t\t\trtc_regs[3] = (nd % 512) & 0xFF;\n\t\t\trtc_regs[4] = change_bit(rtc_regs[4], (nd % 512) > 255, 0);\n\t\t\trtc_regs[4] = change_bit(rtc_regs[4], nd > 511, 7);\n\t\t}\n\t}\n}\n\nbool Cartrige::load_cartrige(const std::string& name)\n{\n\tstd::ifstream cart_file(name, std::ios::binary | std::ios::ate);\n\n\tif (!cart_file.is_open())\n\t\treturn false;\n\n\tsize_t size = cart_file.tellg();\n\tcart_file.seekg(0, std::ios_base::beg);\n\n\trom = std::make_unique<u8[]>(size);\n\tcart_file.read(reinterpret_cast<char*>(rom.get()), size);\n\n\tfile_name = name;\n\tload_ram();\n\tdispatch();\n\n\treturn true;\n}\n\nIMemory* Cartrige::get_memory_controller() const\n{\n\treturn memory_interface.get();\n}\n\nIDmaMemory* Cartrige::get_dma_controller() const\n{\n\treturn dma_interface;\n}\n\nbool Cartrige::is_cgb_ready() const\n{\n\tconst rom_header* header = reinterpret_cast<rom_header*>(&rom[0x100]);\n\n\treturn (header->cgb_flag == 0x80) || (header->cgb_flag == 0xC0);\n}\n\nvoid Cartrige::dispatch()\n{\n\trom_header* header = reinterpret_cast<rom_header*>(&rom[0x100]);\n\tu8 type = header->cartrige_type;\n\n\tif (type == 0x00 || type == 0x08 || type == 0x09)\n\t{\n\t\tauto tmp = std::make_unique<NoMBC>(NoMBC(rom.get(), ram.get()));\n\t\tdma_interface = tmp.get();\n\t\tmemory_interface = std::move(tmp);\n\t}\n\n\telse if (in_range(type, 0x01, 0x03))\n\t{\n\t\tauto tmp = std::make_unique<MBC1>(MBC1(rom.get(), ram.get()));\n\t\tdma_interface = tmp.get();\n\t\tmemory_interface = std::move(tmp);\n\t}\n\n\telse if (in_range(type, 0x05, 0x06))\n\t{\n\t\tauto tmp = std::make_unique<MBC2>(MBC2(rom.get(), ram.get()));\n\t\tdma_interface = tmp.get();\n\t\tmemory_interface = std::move(tmp);\n\t}\n\n\telse if (in_range(type, 0x0F, 0x13))\n\t{\n\t\tauto tmp = std::make_unique<MBC3>(MBC3(rom.get(), ram.get(), (type <= 0x10 ? rtc_regs : nullptr)));\n\t\tdma_interface = tmp.get();\n\t\tmemory_interface = std::move(tmp);\n\t}\n\n\telse if (in_range(type, 0x1A, 0x1E))\n\t{\n\t\tauto tmp = std::make_unique<MBC5>(MBC5(rom.get(), ram.get()));\n\t\tdma_interface = tmp.get();\n\t\tmemory_interface = std::move(tmp);\n\t}\n\n\telse\n\t\tmemory_interface = nullptr;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n Copyright (C) 2015 Martin Klapetek <mklapetek@kde.org>\n\n This library is free software; you can redistribute it and\/or\n modify it under the terms of the GNU Lesser General Public\n License as published by the Free Software Foundation; either\n version 2.1 of the License, or (at your option) any later version.\n\n This library is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n Lesser General Public License for more details.\n\n You should have received a copy of the GNU Lesser General Public\n License along with this library; if not, write to the Free Software\n Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n *\/\n\n#include \"carddav-plugin.h\"\n#include \"carddav_p.h\"\n#include \"syncer_p.h\"\n\n#include <KJob>\n#include <KConfigCore\/KSharedConfig>\n#include <KConfigCore\/KConfigGroup>\n\n#include <Accounts\/Service>\n#include <Accounts\/Manager>\n#include <Accounts\/Account>\n#include <Accounts\/AccountService>\n#include <QTimer>\n\n#include \"getcredentialsjob.h\"\n#include \"core.h\"\n\nclass KAccountsCardDavPlugin::Private {\npublic:\n Private(KAccountsCardDavPlugin *qq) { q = qq; };\n\n KAccountsCardDavPlugin *q;\n KSharedConfig::Ptr config;\n QTimer *syncTimer;\n};\n\n\n\/\/---------------------------------------------------------------------------------------\n\nKAccountsCardDavPlugin::KAccountsCardDavPlugin(QObject *parent)\n : KAccountsDPlugin(parent),\n d(new Private(this))\n{\n d->config = KSharedConfig::openConfig(QStringLiteral(\"kaccounts-carddavrc\"));\n d->syncTimer = new QTimer(this);\n d->syncTimer->setInterval(1000 * 60 *30);\n\n connect(d->syncTimer, &QTimer::timeout, this, &KAccountsCardDavPlugin::syncAllAccounts);\n\n syncAllAccounts();\n}\n\nKAccountsCardDavPlugin::~KAccountsCardDavPlugin()\n{\n}\n\nvoid KAccountsCardDavPlugin::syncAllAccounts()\n{\n KConfigGroup global = d->config->group(\"Global\");\n QList<quint32> syncedAccounts = global.readEntry(\"syncedAccounts\", QList<quint32>());\n\n Q_FOREACH (const quint32 accountId, syncedAccounts) {\n KConfigGroup currentAccount = d->config->group(\"account\" + accountId);\n QDateTime lastSync = QDateTime::fromString(currentAccount.readEntry(\"lastSync\", QString()), Qt::ISODate);\n if (QDateTime::currentDateTime() > lastSync) {\n getCredentials(accountId);\n }\n }\n}\n\nvoid KAccountsCardDavPlugin::onAccountCreated(const Accounts::AccountId accountId, const Accounts::ServiceList &serviceList)\n{\n Accounts::Account *account = KAccounts::accountsManager()->account(accountId);\n\n if (!account) {\n qWarning() << \"Invalid account for id\" << accountId;\n return;\n }\n\n Q_FOREACH (const Accounts::Service &service, serviceList) {\n account->selectService(service);\n if (service.serviceType() == QLatin1String(\"dav-contacts\") && account->isEnabled()) {\n qDebug() << \"Starting carddav contacts import for account\" << accountId << \"and service\" << service.serviceType();\n getCredentials(accountId);\n }\n }\n}\n\nvoid KAccountsCardDavPlugin::onAccountRemoved(const Accounts::AccountId accountId)\n{\n}\n\nvoid KAccountsCardDavPlugin::onServiceEnabled(const Accounts::AccountId accountId, const Accounts::Service &service)\n{\n}\n\nvoid KAccountsCardDavPlugin::onServiceDisabled(const Accounts::AccountId accountId, const Accounts::Service &service)\n{\n}\n\nvoid KAccountsCardDavPlugin::getCredentials(const Accounts::AccountId accountId)\n{\n GetCredentialsJob *credentialsJob = new GetCredentialsJob(accountId, this);\n connect(credentialsJob, &GetCredentialsJob::finished, this, &KAccountsCardDavPlugin::importContacts);\n credentialsJob->start();\n}\n\nvoid KAccountsCardDavPlugin::importContacts(KJob *job)\n{\n GetCredentialsJob *credentialsJob = qobject_cast<GetCredentialsJob*>(job);\n job->deleteLater();\n\n if (!credentialsJob) {\n return;\n }\n\n const QVariantMap &data = credentialsJob->credentialsData();\n Accounts::Account *account = KAccounts::accountsManager()->account(credentialsJob->accountId());\n\n if (!account) {\n return;\n }\n\n QUrl carddavUrl = account->value(\"carddavUrl\").toUrl();\n\n qDebug() << \"Using: host:\" << carddavUrl.host() << \"path:\" << carddavUrl.path();\n\n Syncer *s = new Syncer(0);\n s->setProperty(\"accountId\", credentialsJob->accountId());\n\n const QString &userName = data.value(\"AccountUsername\").toString();\n\n CardDav *m_cardDav = new CardDav(s,\n carddavUrl.host(),\n carddavUrl.path(),\n userName,\n data.value(\"Secret\").toString());\n\n QObject::connect(m_cardDav, SIGNAL(remoteChanges(QList<KContacts::Addressee>,QList<KContacts::Addressee>,QList<KContacts::Addressee>)),\n s, SLOT(continueSync(QList<KContacts::Addressee>,QList<KContacts::Addressee>,QList<KContacts::Addressee>)));\n QObject::connect(m_cardDav, SIGNAL(upsyncCompleted()),\n s, SLOT(syncFinished()));\n QObject::connect(m_cardDav, SIGNAL(error(int)),\n s, SLOT(cardDavError(int)));\n\n QObject::connect(s, &Syncer::syncSucceeded, [=] {\n d->syncTimer->start();\n quint32 accountId = s->property(\"accountId\").toUInt();\n\n KConfigGroup global = d->config->group(\"Global\");\n QList<quint32> syncedAccounts = global.readEntry(\"syncedAccounts\", QList<quint32>());\n if (!syncedAccounts.contains(accountId)) {\n syncedAccounts.append(accountId);\n }\n global.writeEntry(\"syncedAccounts\", syncedAccounts);\n global.sync();\n\n KConfigGroup currentAccount = d->config->group(\"account\" + accountId);\n currentAccount.writeEntry(\"lastSync\", QDateTime::currentDateTime().toString(Qt::ISODate));\n currentAccount.sync();\n });\n\n m_cardDav->determineRemoteAMR();\n}\n<commit_msg>[carddav] Make extra sure the carddav accounts are synced<commit_after>\/*\n Copyright (C) 2015 Martin Klapetek <mklapetek@kde.org>\n\n This library is free software; you can redistribute it and\/or\n modify it under the terms of the GNU Lesser General Public\n License as published by the Free Software Foundation; either\n version 2.1 of the License, or (at your option) any later version.\n\n This library is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n Lesser General Public License for more details.\n\n You should have received a copy of the GNU Lesser General Public\n License along with this library; if not, write to the Free Software\n Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n *\/\n\n#include \"carddav-plugin.h\"\n#include \"carddav_p.h\"\n#include \"syncer_p.h\"\n\n#include <KJob>\n#include <KConfigCore\/KSharedConfig>\n#include <KConfigCore\/KConfigGroup>\n\n#include <Accounts\/Service>\n#include <Accounts\/Manager>\n#include <Accounts\/Account>\n#include <Accounts\/AccountService>\n#include <QTimer>\n\n#include \"getcredentialsjob.h\"\n#include \"core.h\"\n\nclass KAccountsCardDavPlugin::Private {\npublic:\n Private(KAccountsCardDavPlugin *qq) { q = qq; };\n\n KAccountsCardDavPlugin *q;\n KSharedConfig::Ptr config;\n QTimer *syncTimer;\n};\n\n\n\/\/---------------------------------------------------------------------------------------\n\nKAccountsCardDavPlugin::KAccountsCardDavPlugin(QObject *parent)\n : KAccountsDPlugin(parent),\n d(new Private(this))\n{\n d->config = KSharedConfig::openConfig(QStringLiteral(\"kaccounts-carddavrc\"));\n d->syncTimer = new QTimer(this);\n d->syncTimer->setInterval(1000 * 60 *30);\n\n connect(d->syncTimer, &QTimer::timeout, this, &KAccountsCardDavPlugin::syncAllAccounts);\n\n syncAllAccounts();\n}\n\nKAccountsCardDavPlugin::~KAccountsCardDavPlugin()\n{\n}\n\nvoid KAccountsCardDavPlugin::syncAllAccounts()\n{\n KConfigGroup global = d->config->group(\"Global\");\n QList<quint32> syncedAccounts = global.readEntry(\"syncedAccounts\", QList<quint32>());\n\n if (syncedAccounts.isEmpty()) {\n Accounts::AccountIdList accounts = KAccounts::accountsManager()->accountListEnabled(QStringLiteral(\"dav-contacts\"));\n syncedAccounts << accounts;\n }\n\n Q_FOREACH (const quint32 accountId, syncedAccounts) {\n KConfigGroup currentAccount = d->config->group(\"account\" + accountId);\n QDateTime lastSync = QDateTime::fromString(currentAccount.readEntry(\"lastSync\", QString()), Qt::ISODate);\n if (QDateTime::currentDateTime() > lastSync) {\n getCredentials(accountId);\n }\n }\n}\n\nvoid KAccountsCardDavPlugin::onAccountCreated(const Accounts::AccountId accountId, const Accounts::ServiceList &serviceList)\n{\n Accounts::Account *account = KAccounts::accountsManager()->account(accountId);\n\n if (!account) {\n qWarning() << \"Invalid account for id\" << accountId;\n return;\n }\n\n Q_FOREACH (const Accounts::Service &service, serviceList) {\n account->selectService(service);\n if (service.serviceType() == QLatin1String(\"dav-contacts\") && account->isEnabled()) {\n qDebug() << \"Starting carddav contacts import for account\" << accountId << \"and service\" << service.serviceType();\n getCredentials(accountId);\n }\n }\n}\n\nvoid KAccountsCardDavPlugin::onAccountRemoved(const Accounts::AccountId accountId)\n{\n}\n\nvoid KAccountsCardDavPlugin::onServiceEnabled(const Accounts::AccountId accountId, const Accounts::Service &service)\n{\n}\n\nvoid KAccountsCardDavPlugin::onServiceDisabled(const Accounts::AccountId accountId, const Accounts::Service &service)\n{\n}\n\nvoid KAccountsCardDavPlugin::getCredentials(const Accounts::AccountId accountId)\n{\n GetCredentialsJob *credentialsJob = new GetCredentialsJob(accountId, this);\n connect(credentialsJob, &GetCredentialsJob::finished, this, &KAccountsCardDavPlugin::importContacts);\n credentialsJob->start();\n}\n\nvoid KAccountsCardDavPlugin::importContacts(KJob *job)\n{\n GetCredentialsJob *credentialsJob = qobject_cast<GetCredentialsJob*>(job);\n job->deleteLater();\n\n if (!credentialsJob) {\n return;\n }\n\n const QVariantMap &data = credentialsJob->credentialsData();\n Accounts::Account *account = KAccounts::accountsManager()->account(credentialsJob->accountId());\n\n if (!account) {\n return;\n }\n\n QUrl carddavUrl = account->value(\"carddavUrl\").toUrl();\n\n qDebug() << \"Using: host:\" << carddavUrl.host() << \"path:\" << carddavUrl.path();\n\n Syncer *s = new Syncer(0);\n s->setProperty(\"accountId\", credentialsJob->accountId());\n\n const QString &userName = data.value(\"AccountUsername\").toString();\n\n CardDav *m_cardDav = new CardDav(s,\n carddavUrl.host(),\n carddavUrl.path(),\n userName,\n data.value(\"Secret\").toString());\n\n QObject::connect(m_cardDav, SIGNAL(remoteChanges(QList<KContacts::Addressee>,QList<KContacts::Addressee>,QList<KContacts::Addressee>)),\n s, SLOT(continueSync(QList<KContacts::Addressee>,QList<KContacts::Addressee>,QList<KContacts::Addressee>)));\n QObject::connect(m_cardDav, SIGNAL(upsyncCompleted()),\n s, SLOT(syncFinished()));\n QObject::connect(m_cardDav, SIGNAL(error(int)),\n s, SLOT(cardDavError(int)));\n\n QObject::connect(s, &Syncer::syncSucceeded, [=] {\n d->syncTimer->start();\n quint32 accountId = s->property(\"accountId\").toUInt();\n\n KConfigGroup global = d->config->group(\"Global\");\n QList<quint32> syncedAccounts = global.readEntry(\"syncedAccounts\", QList<quint32>());\n if (!syncedAccounts.contains(accountId)) {\n syncedAccounts.append(accountId);\n }\n global.writeEntry(\"syncedAccounts\", syncedAccounts);\n global.sync();\n\n KConfigGroup currentAccount = d->config->group(\"account\" + accountId);\n currentAccount.writeEntry(\"lastSync\", QDateTime::currentDateTime().toString(Qt::ISODate));\n currentAccount.sync();\n });\n\n m_cardDav->determineRemoteAMR();\n}\n<|endoftext|>"} {"text":"<commit_before>#include <imap.hpp>\n\n#include \"helpers.hpp\"\n\n#include <vector>\n#include <list>\n#include <string>\n#include <iterator>\n\n#include \"catch.hpp\"\n\nusing iter::starmap;\n\nnamespace {\n long f(long d, int i) {\n return d * i;\n }\n\n std::string g(const std::string& s, int i, char c) {\n std::stringstream ss;\n ss << s << ' ' << i << ' ' << c;\n return ss.str();\n }\n\n struct Callable {\n int operator()(int a, int b, int c) {\n return a + b + c;\n }\n\n int operator()(int a) {\n return a;\n }\n };\n}\n\nTEST_CASE(\"starmap: works with function pointer and lambda\", \"[starmap]\") {\n using Vec = const std::vector<int>;\n const std::vector<std::pair<double, int>> v1 =\n {{1l, 2}, {3l, 11}, {6l, 7}};\n Vec vc = {2l, 33l, 42l};\n\n SECTION(\"with function\") {\n auto sm = starmap(f, v1);\n Vec v(std::begin(sm), std::end(sm));\n REQUIRE( v == vc );\n }\n\n SECTION(\"with lambda\") {\n auto sm = starmap([](long a, int b) { return a * b; }, v1);\n Vec v(std::begin(sm), std::end(sm));\n REQUIRE( v == vc );\n }\n}\n\nTEST_CASE(\"starmap: list of tuples\", \"[starmap]\") {\n using Vec = const std::vector<std::string>;\n using T = std::tuple<std::string, int, double>;\n std::list<T> li =\n {T{\"hey\", 42, 'a'}, T{\"there\", 3, 'b'}, T{\"yall\", 5, 'c'}};\n\n auto sm = starmap(g, li);\n Vec v(std::begin(sm), std::end(sm));\n Vec vc = {\"hey 42 a\", \"there 3 b\", \"yall 5 c\"};\n\n REQUIRE( v == vc );\n}\n\nTEST_CASE(\"starmap: tuple of tuples\", \"[starmap]\") {\n using Vec = const std::vector<int>;\n auto tup = std::make_tuple(std::make_tuple(10, 19, 60),std::make_tuple(7));\n auto sm = starmap(Callable{}, tup);\n Vec v(std::begin(sm), std::end(sm));\n Vec vc = {89, 7};\n\n REQUIRE( v == vc );\n}\n\nTEST_CASE(\"starmap: tuple of pairs\", \"[starmap]\") {\n using Vec = const std::vector<int>;\n auto p = std::make_pair(std::array<int, 3>{{15, 100, 2000}},\n std::make_tuple(16));\n Callable c;\n auto sm = starmap(c, p);\n\n Vec v(std::begin(sm), std::end(sm));\n Vec vc = {2115, 16};\n\n REQUIRE( v == vc );\n}\n<commit_msg>tests that starmap moves and binds correctly<commit_after>#include <imap.hpp>\n\n#include \"helpers.hpp\"\n\n#include <vector>\n#include <list>\n#include <string>\n#include <iterator>\n\n#include \"catch.hpp\"\n\nusing iter::starmap;\n\nnamespace {\n long f(long d, int i) {\n return d * i;\n }\n\n std::string g(const std::string& s, int i, char c) {\n std::stringstream ss;\n ss << s << ' ' << i << ' ' << c;\n return ss.str();\n }\n\n struct Callable {\n int operator()(int a, int b, int c) {\n return a + b + c;\n }\n\n int operator()(int a) {\n return a;\n }\n };\n}\n\nTEST_CASE(\"starmap: works with function pointer and lambda\", \"[starmap]\") {\n using Vec = const std::vector<int>;\n const std::vector<std::pair<double, int>> v1 =\n {{1l, 2}, {3l, 11}, {6l, 7}};\n Vec vc = {2l, 33l, 42l};\n\n SECTION(\"with function\") {\n auto sm = starmap(f, v1);\n Vec v(std::begin(sm), std::end(sm));\n REQUIRE( v == vc );\n }\n\n SECTION(\"with lambda\") {\n auto sm = starmap([](long a, int b) { return a * b; }, v1);\n Vec v(std::begin(sm), std::end(sm));\n REQUIRE( v == vc );\n }\n}\n\nTEST_CASE(\"starmap: list of tuples\", \"[starmap]\") {\n using Vec = const std::vector<std::string>;\n using T = std::tuple<std::string, int, double>;\n std::list<T> li =\n {T{\"hey\", 42, 'a'}, T{\"there\", 3, 'b'}, T{\"yall\", 5, 'c'}};\n\n auto sm = starmap(g, li);\n Vec v(std::begin(sm), std::end(sm));\n Vec vc = {\"hey 42 a\", \"there 3 b\", \"yall 5 c\"};\n\n REQUIRE( v == vc );\n}\n\nTEST_CASE(\"starmap: tuple of tuples\", \"[starmap]\") {\n using Vec = const std::vector<int>;\n auto tup = std::make_tuple(std::make_tuple(10, 19, 60),std::make_tuple(7));\n auto sm = starmap(Callable{}, tup);\n Vec v(std::begin(sm), std::end(sm));\n Vec vc = {89, 7};\n\n REQUIRE( v == vc );\n}\n\nTEST_CASE(\"starmap: tuple of pairs\", \"[starmap]\") {\n using Vec = const std::vector<int>;\n auto p = std::make_pair(std::array<int, 3>{{15, 100, 2000}},\n std::make_tuple(16));\n Callable c;\n auto sm = starmap(c, p);\n\n Vec v(std::begin(sm), std::end(sm));\n Vec vc = {2115, 16};\n\n REQUIRE( v == vc );\n}\n\nTEST_CASE(\"starmap: moves rvalues, binds to lvalues\", \"[starmap]\") {\n itertest::BasicIterable<std::tuple<int>> bi{};\n starmap(Callable{}, bi);\n REQUIRE_FALSE( bi.was_moved_from() );\n starmap(Callable{}, std::move(bi));\n REQUIRE( bi.was_moved_from() );\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \"paddle\/fluid\/framework\/ir\/conv_bias_mkldnn_fuse_pass.h\"\n#include <functional>\n#include <string>\n#include <vector>\n#include \"paddle\/fluid\/framework\/lod_tensor.h\"\n#include \"paddle\/fluid\/platform\/enforce.h\"\n\nnamespace paddle {\nnamespace framework {\nnamespace ir {\n\ntemplate <typename BinaryOperation>\nLoDTensor tensor_apply_eltwise(const LoDTensor& vec_a, const LoDTensor& vec_b,\n BinaryOperation f) {\n PADDLE_ENFORCE_EQ(vec_a.dims(), vec_b.dims());\n LoDTensor vec_y;\n vec_y.Resize(vec_a.dims());\n const float* a = vec_a.data<float>();\n const float* b = vec_b.data<float>();\n float* y = vec_y.mutable_data<float>(platform::CPUPlace());\n for (int i = 0; i < vec_a.numel(); i++) {\n y[i] = f(a[i], b[i]);\n }\n return vec_y;\n}\n\nstd::unique_ptr<ir::Graph> ConvBiasFusePass::ApplyImpl(\n std::unique_ptr<ir::Graph> graph) const {\n PADDLE_ENFORCE(graph.get());\n FusePassBase::Init(name_scope_, graph.get());\n\n auto* scope = param_scope();\n PADDLE_ENFORCE(scope);\n\n GraphPatternDetector gpd;\n auto* conv_input =\n gpd.mutable_pattern()\n ->NewNode(patterns::PDNodeName(name_scope_, \"conv_input\"))\n ->AsInput()\n ->assert_is_op_input(\"conv2d\", \"Input\");\n patterns::ConvBias conv_bias_pattern(gpd.mutable_pattern(), name_scope_);\n conv_bias_pattern(conv_input);\n int found_conv_bias_count = 0;\n auto handler = [&](const GraphPatternDetector::subgraph_t& subgraph,\n Graph* g) {\n VLOG(4) << \"handle ConvBias fuse\";\n GET_IR_NODE_FROM_SUBGRAPH(conv_weight, conv_weight,\n conv_bias_pattern); \/\/ Filter\n GET_IR_NODE_FROM_SUBGRAPH(conv_out, conv_out, conv_bias_pattern); \/\/ tmp\n GET_IR_NODE_FROM_SUBGRAPH(conv, conv, conv_bias_pattern); \/\/ CONV op\n \/\/ bias\n GET_IR_NODE_FROM_SUBGRAPH(eltwise_bias, eltwise_bias, conv_bias_pattern);\n \/\/ output\n GET_IR_NODE_FROM_SUBGRAPH(eltwise_out, eltwise_out, conv_bias_pattern);\n \/\/ elementwise_add op\n GET_IR_NODE_FROM_SUBGRAPH(eltwise, eltwise, conv_bias_pattern);\n\n PADDLE_ENFORCE(subgraph.count(conv_input));\n\n auto* eltwise_bias_tensor =\n scope->FindVar(eltwise_bias->Name())->GetMutable<LoDTensor>();\n\n auto input_names = conv->Op()->InputNames();\n bool has_bias = std::find(input_names.begin(), input_names.end(), \"Bias\") !=\n input_names.end();\n if (has_bias && conv->Op()->Input(\"Bias\").size() > 0) {\n auto conv_bias_names = conv->Op()->Input(\"Bias\");\n \/\/ add eltwise bias to existing conv bias\n PADDLE_ENFORCE_EQ(conv_bias_names.size(), 1);\n auto* conv_bias_var = scope->FindVar(conv_bias_names[0]);\n auto* conv_bias_tensor = conv_bias_var->GetMutable<LoDTensor>();\n PADDLE_ENFORCE_EQ(conv_bias_tensor->dims(), eltwise_bias_tensor->dims());\n *conv_bias_tensor = tensor_apply_eltwise(\n *conv_bias_tensor, *eltwise_bias_tensor, std::plus<float>());\n\n conv->Op()->SetOutput(\"Output\",\n std::vector<std::string>({eltwise_out->Name()}));\n\n GraphSafeRemoveNodes(graph.get(), {eltwise, conv_out});\n\n IR_NODE_LINK_TO(conv, eltwise_out);\n } else {\n \/\/ take eltwise bias as conv bias\n OpDesc desc;\n\n desc.SetInput(\n \"Input\", std::vector<std::string>({subgraph.at(conv_input)->Name()}));\n desc.SetInput(\"Filter\", std::vector<std::string>({conv_weight->Name()}));\n desc.SetInput(\"Bias\", std::vector<std::string>({eltwise_bias->Name()}));\n desc.SetOutput(\"Output\", std::vector<std::string>({eltwise_out->Name()}));\n desc.SetType(\"conv2d\");\n\n for (auto& attr : conv->Op()->GetAttrMap()) {\n desc.SetAttr(attr.first, attr.second);\n }\n auto conv_bias_node = g->CreateOpNode(&desc);\n\n IR_NODE_LINK_TO(subgraph.at(conv_input), conv_bias_node);\n IR_NODE_LINK_TO(conv_weight, conv_bias_node);\n IR_NODE_LINK_TO(eltwise_bias, conv_bias_node);\n IR_NODE_LINK_TO(conv_bias_node, eltwise_out);\n\n GraphSafeRemoveNodes(graph.get(), {conv, eltwise, conv_out});\n }\n\n found_conv_bias_count++;\n };\n gpd(graph.get(), handler);\n AddStatis(found_conv_bias_count);\n return graph;\n}\n} \/\/ namespace ir\n} \/\/ namespace framework\n} \/\/ namespace paddle\nREGISTER_PASS(conv_bias_mkldnn_fuse_pass,\n paddle::framework::ir::ConvBiasFusePass);\n<commit_msg>Adjust Conv+bias to placement pass<commit_after>\/\/ Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \"paddle\/fluid\/framework\/ir\/conv_bias_mkldnn_fuse_pass.h\"\n#include <functional>\n#include <string>\n#include <vector>\n#include \"paddle\/fluid\/framework\/lod_tensor.h\"\n#include \"paddle\/fluid\/platform\/enforce.h\"\n\nnamespace paddle {\nnamespace framework {\nnamespace ir {\n\ntemplate <typename BinaryOperation>\nLoDTensor tensor_apply_eltwise(const LoDTensor& vec_a, const LoDTensor& vec_b,\n BinaryOperation f) {\n PADDLE_ENFORCE_EQ(vec_a.dims(), vec_b.dims());\n LoDTensor vec_y;\n vec_y.Resize(vec_a.dims());\n const float* a = vec_a.data<float>();\n const float* b = vec_b.data<float>();\n float* y = vec_y.mutable_data<float>(platform::CPUPlace());\n for (int i = 0; i < vec_a.numel(); i++) {\n y[i] = f(a[i], b[i]);\n }\n return vec_y;\n}\n\nstd::unique_ptr<ir::Graph> ConvBiasFusePass::ApplyImpl(\n std::unique_ptr<ir::Graph> graph) const {\n PADDLE_ENFORCE(graph.get());\n FusePassBase::Init(name_scope_, graph.get());\n\n auto* scope = param_scope();\n PADDLE_ENFORCE(scope);\n\n GraphPatternDetector gpd;\n auto* conv_input =\n gpd.mutable_pattern()\n ->NewNode(patterns::PDNodeName(name_scope_, \"conv_input\"))\n ->AsInput()\n ->assert_is_op_input(\"conv2d\", \"Input\");\n patterns::ConvBias conv_bias_pattern(gpd.mutable_pattern(), name_scope_);\n conv_bias_pattern(conv_input);\n int found_conv_bias_count = 0;\n auto handler = [&](const GraphPatternDetector::subgraph_t& subgraph,\n Graph* g) {\n VLOG(4) << \"handle ConvBias fuse\";\n GET_IR_NODE_FROM_SUBGRAPH(conv_weight, conv_weight,\n conv_bias_pattern); \/\/ Filter\n GET_IR_NODE_FROM_SUBGRAPH(conv_out, conv_out, conv_bias_pattern); \/\/ tmp\n GET_IR_NODE_FROM_SUBGRAPH(conv, conv, conv_bias_pattern); \/\/ CONV op\n \/\/ bias\n GET_IR_NODE_FROM_SUBGRAPH(eltwise_bias, eltwise_bias, conv_bias_pattern);\n \/\/ output\n GET_IR_NODE_FROM_SUBGRAPH(eltwise_out, eltwise_out, conv_bias_pattern);\n \/\/ elementwise_add op\n GET_IR_NODE_FROM_SUBGRAPH(eltwise, eltwise, conv_bias_pattern);\n\n PADDLE_ENFORCE(subgraph.count(conv_input));\n\n \/\/ check if fuse can be done and if MKL-DNN should be used\n FuseOptions fuse_option = FindFuseOption(*conv, *eltwise);\n if (fuse_option == DO_NOT_FUSE || fuse_option == FUSE_NATIVE) {\n VLOG(3) << \"do not perform conv+bias fuse\";\n return;\n }\n\n auto* eltwise_bias_tensor =\n scope->FindVar(eltwise_bias->Name())->GetMutable<LoDTensor>();\n\n auto input_names = conv->Op()->InputNames();\n bool has_bias = std::find(input_names.begin(), input_names.end(), \"Bias\") !=\n input_names.end();\n if (has_bias && conv->Op()->Input(\"Bias\").size() > 0) {\n auto conv_bias_names = conv->Op()->Input(\"Bias\");\n \/\/ add eltwise bias to existing conv bias\n PADDLE_ENFORCE_EQ(conv_bias_names.size(), 1);\n auto* conv_bias_var = scope->FindVar(conv_bias_names[0]);\n auto* conv_bias_tensor = conv_bias_var->GetMutable<LoDTensor>();\n PADDLE_ENFORCE_EQ(conv_bias_tensor->dims(), eltwise_bias_tensor->dims());\n *conv_bias_tensor = tensor_apply_eltwise(\n *conv_bias_tensor, *eltwise_bias_tensor, std::plus<float>());\n\n conv->Op()->SetOutput(\"Output\",\n std::vector<std::string>({eltwise_out->Name()}));\n\n GraphSafeRemoveNodes(graph.get(), {eltwise, conv_out});\n\n IR_NODE_LINK_TO(conv, eltwise_out);\n } else {\n \/\/ take eltwise bias as conv bias\n OpDesc desc;\n\n desc.SetInput(\n \"Input\", std::vector<std::string>({subgraph.at(conv_input)->Name()}));\n desc.SetInput(\"Filter\", std::vector<std::string>({conv_weight->Name()}));\n desc.SetInput(\"Bias\", std::vector<std::string>({eltwise_bias->Name()}));\n desc.SetOutput(\"Output\", std::vector<std::string>({eltwise_out->Name()}));\n desc.SetType(\"conv2d\");\n\n for (auto& attr : conv->Op()->GetAttrMap()) {\n desc.SetAttr(attr.first, attr.second);\n }\n auto conv_bias_node = g->CreateOpNode(&desc);\n\n IR_NODE_LINK_TO(subgraph.at(conv_input), conv_bias_node);\n IR_NODE_LINK_TO(conv_weight, conv_bias_node);\n IR_NODE_LINK_TO(eltwise_bias, conv_bias_node);\n IR_NODE_LINK_TO(conv_bias_node, eltwise_out);\n\n GraphSafeRemoveNodes(graph.get(), {conv, eltwise, conv_out});\n }\n\n found_conv_bias_count++;\n };\n gpd(graph.get(), handler);\n AddStatis(found_conv_bias_count);\n return graph;\n}\n} \/\/ namespace ir\n} \/\/ namespace framework\n} \/\/ namespace paddle\nREGISTER_PASS(conv_bias_mkldnn_fuse_pass,\n paddle::framework::ir::ConvBiasFusePass);\n<|endoftext|>"} {"text":"<commit_before>\/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License. *\/\n\n#include \"paddle\/fluid\/operators\/sequence_ops\/sequence_pool_op.h\"\n#include <memory>\n#include <string>\n\nnamespace paddle {\nnamespace operators {\n\nclass SequencePoolOp : public framework::OperatorWithKernel {\n public:\n using framework::OperatorWithKernel::OperatorWithKernel;\n\n void InferShape(framework::InferShapeContext* ctx) const override {\n PADDLE_ENFORCE_EQ(ctx->HasInput(\"X\"), true,\n \"Input(X) of SequencePoolOp should not be null.\");\n PADDLE_ENFORCE_EQ(ctx->HasOutput(\"Out\"), true,\n \"Output(Out) of SequencePoolOp should not be null.\");\n\n if (!ctx->IsRuntime()) {\n \/\/ Check the lod_level for compile-time.\n PADDLE_ENFORCE_GT(\n ctx->GetLoDLevel(\"X\"), 0,\n \"The LoD level Input(X) of sequence_pool should be larger than 0.\");\n }\n\n ctx->SetOutputDim(\"Out\", ctx->GetInputDim(\"X\"));\n if (ctx->Attrs().Get<std::string>(\"pooltype\") == \"MAX\") {\n PADDLE_ENFORCE_EQ(\n ctx->HasOutput(\"MaxIndex\"), true,\n \"Output(MaxIndex) of SequencePoolOp should not be null.\");\n ctx->SetOutputDim(\"MaxIndex\", ctx->GetInputDim(\"X\"));\n }\n }\n};\n\nclass SequencePoolOpMaker : public framework::OpProtoAndCheckerMaker {\n public:\n void Make() override {\n AddInput(\"X\", \"(LoDTensor) The variable-length input of SequencePoolOp\");\n AddOutput(\"Out\",\n \"(Tensor) The output of SequencePoolOp does not contain LoD \"\n \"infomation.\");\n AddOutput(\"MaxIndex\",\n \"(Tensor<int>) This tensor is used for the sequence max-pooling \"\n \"to record the max indexes.\")\n .AsIntermediate();\n AddAttr<bool>(\"is_test\",\n \"(bool, default false) Set to true for inference only, false \"\n \"for training. Some layers may run faster when this is true.\")\n .SetDefault(false);\n AddAttr<std::string>(\n \"pooltype\",\n \"(string, default 'AVERAGE') the pooling pooltype of SequencePoolOp.\")\n .SetDefault(\"AVERAGE\")\n .InEnum({\"AVERAGE\", \"SUM\", \"SQRT\", \"LAST\", \"FIRST\", \"MAX\"});\n AddAttr<float>(\"pad_value\",\n \"(float, default 0.0) The value to pad for empty sequence.\")\n .SetDefault(0.0);\n AddComment(R\"DOC(\nSequence Pool Operator.\n\nThe SequencePoolOp pools features of all time-steps of each instance.\nIt supports six pooling types:\n1. AVERAGE: $$Out[i] = \\frac{\\sum_i X_i}{N}$$\n2. SUM: $$Out[i] = \\sum_jX_{ij}$$\n3. SQRT: $$Out[i] = \\frac{\\sum_jX_{ij}}{\\sqrt{len(X_i)}}$$\n4. LAST: Out[i] = last instance in i-th sequence X[i]\n5. FIRST: Out[i] = first instance in i-th sequence X[i]\n6. MAX: $$Out[i] = max(X_i)$$\n\nand for the empty sequence Out[i] = attr(pad_value).\n\nThe following example explains how this works:\nFor a mini-batch of 3 variable-length sentences,\ncontaining 2, 3, and 2 time-steps:\n\nAssume X is a [7,M,N] LoDTensor, and X->lod()[0] = [0, 2, 5, 7], 7=2+3+2.\nBesides, for the sake of simplicity, we assume M=1 and N=1,\nand the value of X = [[1, 3], [2, 4, 6], [5, 1]].\n\nThus, Out is a [3,1,1] Tensor without LoD infomation.\nAnd for different pooltype, the value of Out is as follows:\n\n- AVERAGE: [2, 4, 3], where 2=(1+3)\/2, 4=(2+4+6)\/3, 3=(5+1)\/2\n- SUM: [4, 12, 6], where 4=1+3, 12=2+4+6, 6=5+1\n- SQRT: [2.82, 6.93, 4.24], where 2.82=(1+3)\/sqrt(2),\n 6.93=(2+4+6)\/sqrt(3), 4.24=(5+1)\/sqrt(2)\n- MAX: [3, 6, 5], where 3=max(1,3), 6=max(2,4,6), 5=max(5,1)\n- LAST: [3, 6, 1], where 3=last(1,3), 6=last(2,4,6), 1=last(5,1)\n- FIRST: [1, 2, 5], where 1=first(1,3), 2=first(2,4,6), 5=first(5,1)\n\n )DOC\");\n }\n};\n\nclass SequencePoolGradOp : public framework::OperatorWithKernel {\n public:\n using framework::OperatorWithKernel::OperatorWithKernel;\n\n void InferShape(framework::InferShapeContext* ctx) const override {\n PADDLE_ENFORCE_EQ(ctx->HasInput(framework::GradVarName(\"Out\")), true,\n \"Gradient of Out should not be null.\");\n PADDLE_ENFORCE_EQ(ctx->HasInput(\"X\"), true,\n \"The input X should not be null.\");\n auto og_dims = ctx->GetInputDim(framework::GradVarName(\"Out\"));\n auto x_dims = ctx->GetInputDim(\"X\");\n PADDLE_ENFORCE_EQ(og_dims.size(), x_dims.size(),\n \"The rank of output grad must equal to Input(X).\");\n for (int64_t i = 1; i < og_dims.size(); ++i) {\n PADDLE_ENFORCE_EQ(og_dims[i], x_dims[i], \"The dimension mismatch.\");\n }\n\n ctx->ShareDim(\"X\", \/*->*\/ framework::GradVarName(\"X\"));\n ctx->ShareLoD(\"X\", \/*->*\/ framework::GradVarName(\"X\"));\n }\n\n protected:\n framework::OpKernelType GetExpectedKernelType(\n const framework::ExecutionContext& ctx) const override {\n return framework::OpKernelType(OperatorWithKernel::IndicateVarDataType(\n ctx, framework::GradVarName(\"Out\")),\n ctx.device_context());\n }\n};\n\ntemplate <typename T>\nclass SequencePoolGradOpMaker : public framework::SingleGradOpMaker<T> {\n public:\n using framework::SingleGradOpMaker<T>::SingleGradOpMaker;\n\n protected:\n std::unique_ptr<T> Apply() const override {\n auto* op_desc_ptr = new T();\n op_desc_ptr->SetType(\"sequence_pool_grad\");\n op_desc_ptr->SetInput(\"X\", this->Input(\"X\"));\n if (boost::get<std::string>(this->GetAttr(\"pooltype\")) == \"MAX\") {\n op_desc_ptr->SetInput(\"MaxIndex\", this->Output(\"MaxIndex\"));\n }\n op_desc_ptr->SetInput(framework::GradVarName(\"Out\"),\n this->OutputGrad(\"Out\"));\n op_desc_ptr->SetOutput(framework::GradVarName(\"X\"), this->InputGrad(\"X\"));\n op_desc_ptr->SetAttrMap(this->Attrs());\n return std::unique_ptr<T>(op_desc_ptr);\n }\n};\n\nDECLARE_NO_NEED_BUFFER_VARS_INFERENCE(\n SequencePoolGradOpNoNeedBufferVarsInference, \"X\");\n\n} \/\/ namespace operators\n} \/\/ namespace paddle\n\nnamespace ops = paddle::operators;\nREGISTER_OPERATOR(sequence_pool, ops::SequencePoolOp, ops::SequencePoolOpMaker,\n ops::SequencePoolGradOpMaker<paddle::framework::OpDesc>,\n ops::SequencePoolGradOpMaker<paddle::imperative::OpBase>);\nREGISTER_OPERATOR(sequence_pool_grad, ops::SequencePoolGradOp,\n ops::SequencePoolGradOpNoNeedBufferVarsInference);\nREGISTER_OP_CPU_KERNEL(\n sequence_pool,\n ops::SequencePoolKernel<paddle::platform::CPUDeviceContext, float>);\nREGISTER_OP_CPU_KERNEL(\n sequence_pool_grad,\n ops::SequencePoolGradKernel<paddle::platform::CPUDeviceContext, float>);\n<commit_msg>Set lod_level of Out in compile time of sequence_pool_op (#21604)<commit_after>\/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License. *\/\n\n#include \"paddle\/fluid\/operators\/sequence_ops\/sequence_pool_op.h\"\n#include <memory>\n#include <string>\n\nnamespace paddle {\nnamespace operators {\n\nclass SequencePoolOp : public framework::OperatorWithKernel {\n public:\n using framework::OperatorWithKernel::OperatorWithKernel;\n\n void InferShape(framework::InferShapeContext* ctx) const override {\n PADDLE_ENFORCE_EQ(ctx->HasInput(\"X\"), true,\n \"Input(X) of SequencePoolOp should not be null.\");\n PADDLE_ENFORCE_EQ(ctx->HasOutput(\"Out\"), true,\n \"Output(Out) of SequencePoolOp should not be null.\");\n\n if (!ctx->IsRuntime()) {\n \/\/ Check the lod_level for compile-time.\n auto in_lod_level = ctx->GetLoDLevel(\"X\");\n PADDLE_ENFORCE_GT(\n in_lod_level, 0,\n \"The LoD level Input(X) of sequence_pool should be larger than 0.\");\n ctx->SetLoDLevel(\"Out\", in_lod_level - 1);\n }\n\n ctx->SetOutputDim(\"Out\", ctx->GetInputDim(\"X\"));\n if (ctx->Attrs().Get<std::string>(\"pooltype\") == \"MAX\") {\n PADDLE_ENFORCE_EQ(\n ctx->HasOutput(\"MaxIndex\"), true,\n \"Output(MaxIndex) of SequencePoolOp should not be null.\");\n ctx->SetOutputDim(\"MaxIndex\", ctx->GetInputDim(\"X\"));\n }\n }\n};\n\nclass SequencePoolOpMaker : public framework::OpProtoAndCheckerMaker {\n public:\n void Make() override {\n AddInput(\"X\", \"(LoDTensor) The variable-length input of SequencePoolOp\");\n AddOutput(\"Out\",\n \"(Tensor) The output of SequencePoolOp does not contain LoD \"\n \"infomation.\");\n AddOutput(\"MaxIndex\",\n \"(Tensor<int>) This tensor is used for the sequence max-pooling \"\n \"to record the max indexes.\")\n .AsIntermediate();\n AddAttr<bool>(\"is_test\",\n \"(bool, default false) Set to true for inference only, false \"\n \"for training. Some layers may run faster when this is true.\")\n .SetDefault(false);\n AddAttr<std::string>(\n \"pooltype\",\n \"(string, default 'AVERAGE') the pooling pooltype of SequencePoolOp.\")\n .SetDefault(\"AVERAGE\")\n .InEnum({\"AVERAGE\", \"SUM\", \"SQRT\", \"LAST\", \"FIRST\", \"MAX\"});\n AddAttr<float>(\"pad_value\",\n \"(float, default 0.0) The value to pad for empty sequence.\")\n .SetDefault(0.0);\n AddComment(R\"DOC(\nSequence Pool Operator.\n\nThe SequencePoolOp pools features of all time-steps of each instance.\nIt supports six pooling types:\n1. AVERAGE: $$Out[i] = \\frac{\\sum_i X_i}{N}$$\n2. SUM: $$Out[i] = \\sum_jX_{ij}$$\n3. SQRT: $$Out[i] = \\frac{\\sum_jX_{ij}}{\\sqrt{len(X_i)}}$$\n4. LAST: Out[i] = last instance in i-th sequence X[i]\n5. FIRST: Out[i] = first instance in i-th sequence X[i]\n6. MAX: $$Out[i] = max(X_i)$$\n\nand for the empty sequence Out[i] = attr(pad_value).\n\nThe following example explains how this works:\nFor a mini-batch of 3 variable-length sentences,\ncontaining 2, 3, and 2 time-steps:\n\nAssume X is a [7,M,N] LoDTensor, and X->lod()[0] = [0, 2, 5, 7], 7=2+3+2.\nBesides, for the sake of simplicity, we assume M=1 and N=1,\nand the value of X = [[1, 3], [2, 4, 6], [5, 1]].\n\nThus, Out is a [3,1,1] Tensor without LoD infomation.\nAnd for different pooltype, the value of Out is as follows:\n\n- AVERAGE: [2, 4, 3], where 2=(1+3)\/2, 4=(2+4+6)\/3, 3=(5+1)\/2\n- SUM: [4, 12, 6], where 4=1+3, 12=2+4+6, 6=5+1\n- SQRT: [2.82, 6.93, 4.24], where 2.82=(1+3)\/sqrt(2),\n 6.93=(2+4+6)\/sqrt(3), 4.24=(5+1)\/sqrt(2)\n- MAX: [3, 6, 5], where 3=max(1,3), 6=max(2,4,6), 5=max(5,1)\n- LAST: [3, 6, 1], where 3=last(1,3), 6=last(2,4,6), 1=last(5,1)\n- FIRST: [1, 2, 5], where 1=first(1,3), 2=first(2,4,6), 5=first(5,1)\n\n )DOC\");\n }\n};\n\nclass SequencePoolGradOp : public framework::OperatorWithKernel {\n public:\n using framework::OperatorWithKernel::OperatorWithKernel;\n\n void InferShape(framework::InferShapeContext* ctx) const override {\n PADDLE_ENFORCE_EQ(ctx->HasInput(framework::GradVarName(\"Out\")), true,\n \"Gradient of Out should not be null.\");\n PADDLE_ENFORCE_EQ(ctx->HasInput(\"X\"), true,\n \"The input X should not be null.\");\n auto og_dims = ctx->GetInputDim(framework::GradVarName(\"Out\"));\n auto x_dims = ctx->GetInputDim(\"X\");\n PADDLE_ENFORCE_EQ(og_dims.size(), x_dims.size(),\n \"The rank of output grad must equal to Input(X).\");\n for (int64_t i = 1; i < og_dims.size(); ++i) {\n PADDLE_ENFORCE_EQ(og_dims[i], x_dims[i], \"The dimension mismatch.\");\n }\n\n ctx->ShareDim(\"X\", \/*->*\/ framework::GradVarName(\"X\"));\n ctx->ShareLoD(\"X\", \/*->*\/ framework::GradVarName(\"X\"));\n }\n\n protected:\n framework::OpKernelType GetExpectedKernelType(\n const framework::ExecutionContext& ctx) const override {\n return framework::OpKernelType(OperatorWithKernel::IndicateVarDataType(\n ctx, framework::GradVarName(\"Out\")),\n ctx.device_context());\n }\n};\n\ntemplate <typename T>\nclass SequencePoolGradOpMaker : public framework::SingleGradOpMaker<T> {\n public:\n using framework::SingleGradOpMaker<T>::SingleGradOpMaker;\n\n protected:\n std::unique_ptr<T> Apply() const override {\n auto* op_desc_ptr = new T();\n op_desc_ptr->SetType(\"sequence_pool_grad\");\n op_desc_ptr->SetInput(\"X\", this->Input(\"X\"));\n if (boost::get<std::string>(this->GetAttr(\"pooltype\")) == \"MAX\") {\n op_desc_ptr->SetInput(\"MaxIndex\", this->Output(\"MaxIndex\"));\n }\n op_desc_ptr->SetInput(framework::GradVarName(\"Out\"),\n this->OutputGrad(\"Out\"));\n op_desc_ptr->SetOutput(framework::GradVarName(\"X\"), this->InputGrad(\"X\"));\n op_desc_ptr->SetAttrMap(this->Attrs());\n return std::unique_ptr<T>(op_desc_ptr);\n }\n};\n\nDECLARE_NO_NEED_BUFFER_VARS_INFERENCE(\n SequencePoolGradOpNoNeedBufferVarsInference, \"X\");\n\n} \/\/ namespace operators\n} \/\/ namespace paddle\n\nnamespace ops = paddle::operators;\nREGISTER_OPERATOR(sequence_pool, ops::SequencePoolOp, ops::SequencePoolOpMaker,\n ops::SequencePoolGradOpMaker<paddle::framework::OpDesc>,\n ops::SequencePoolGradOpMaker<paddle::imperative::OpBase>);\nREGISTER_OPERATOR(sequence_pool_grad, ops::SequencePoolGradOp,\n ops::SequencePoolGradOpNoNeedBufferVarsInference);\nREGISTER_OP_CPU_KERNEL(\n sequence_pool,\n ops::SequencePoolKernel<paddle::platform::CPUDeviceContext, float>);\nREGISTER_OP_CPU_KERNEL(\n sequence_pool_grad,\n ops::SequencePoolGradKernel<paddle::platform::CPUDeviceContext, float>);\n<|endoftext|>"} {"text":"<commit_before>#ifndef LUCE_HEADER_UTILITY_HH\n#define LUCE_HEADER_UTILITY_HH\n\n#include <Luce\/Utility\/Blank.hh>\n#include <Luce\/Utility\/Integer.hh>\n#include <Luce\/Utility\/LabledLoop.hh>\n#include <Luce\/Utility\/NonComparable.hh>\n#include <Luce\/Utility\/NonCopyable.hh>\n#include <Luce\/Utility\/Property.hh>\n#include <Luce\/Utility\/Real.hh>\n\n#endif<commit_msg>Update Luce-Utility<commit_after>#ifndef LUCE_HEADER_UTILITY_HH\n#define LUCE_HEADER_UTILITY_HH\n\n#include <Luce\/Utility\/AlwaysInline.hh>\n#include <Luce\/Utility\/Blank.hh>\n#include <Luce\/Utility\/Integer.hh>\n#include <Luce\/Utility\/LabledLoop.hh>\n#include <Luce\/Utility\/NonComparable.hh>\n#include <Luce\/Utility\/NonCopyable.hh>\n#include <Luce\/Utility\/Property.hh>\n#include <Luce\/Utility\/Real.hh>\n\n#endif<|endoftext|>"} {"text":"<commit_before>\/\/ MathPresso - Mathematical Expression Parser and JIT Compiler.\n\n\/\/ Copyright (c) 2008-2010, Petr Kobalicek <kobalicek.petr@gmail.com>\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person\n\/\/ obtaining a copy of this software and associated documentation\n\/\/ files (the \"Software\"), to deal in the Software without\n\/\/ restriction, including without limitation the rights to use,\n\/\/ copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the\n\/\/ Software is furnished to do so, subject to the following\n\/\/ conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be\n\/\/ included in all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n\/\/ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES\n\/\/ OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n\/\/ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n\/\/ HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,\n\/\/ WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n\/\/ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\n\/\/ OTHER DEALINGS IN THE SOFTWARE.\n\n#include <MathPresso\/MathPresso.h>\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n\nstruct TestExpression\n{\n const char* expression;\n MathPresso::mreal_t expected;\n};\n\n#define TABLE_SIZE(table) \\\n (sizeof(table) \/ sizeof(table[0]))\n\n#define TEST_EXPRESSION(expression) \\\n { #expression, (MathPresso::mreal_t)(expression) }\n\nint main(int argc, char* argv[])\n{\n MathPresso::mreal_t x = 5.1f;\n MathPresso::mreal_t y = 6.7f;\n MathPresso::mreal_t z = 9.9f;\n MathPresso::mreal_t PI = 3.14159265358979323846f;\n\n MathPresso::Context ctx;\n MathPresso::Expression e0;\n MathPresso::Expression e1;\n\n ctx.addEnvironment(MathPresso::MENVIRONMENT_ALL);\n ctx.addVariable(\"x\", 0 * sizeof(MathPresso::mreal_t));\n ctx.addVariable(\"y\", 1 * sizeof(MathPresso::mreal_t));\n ctx.addVariable(\"z\", 2 * sizeof(MathPresso::mreal_t));\n\n MathPresso::mreal_t variables[] = { x, y, z };\n\n TestExpression tests[] = {\n TEST_EXPRESSION( (x+y) ),\n TEST_EXPRESSION( -x ),\n TEST_EXPRESSION( -(x+y) ),\n TEST_EXPRESSION( -x ),\n TEST_EXPRESSION( -1 + x ),\n TEST_EXPRESSION( -(-(-1)) ),\n TEST_EXPRESSION( -(-(-x)) ),\n TEST_EXPRESSION( (x+y)*x ),\n TEST_EXPRESSION( (x+y)*y ),\n TEST_EXPRESSION( (x+y)*(1.19+z) ),\n TEST_EXPRESSION( ((x+(x+2.13))*y) ),\n TEST_EXPRESSION( (x+y+z*2+(x*z+z*1.5)) ),\n TEST_EXPRESSION( (((((((x-0.28)+y)+x)+x)*x)\/1.12)*y) ),\n TEST_EXPRESSION( ((((x*((((y-1.50)+1.82)-x)\/PI))\/x)*x)+z) ),\n TEST_EXPRESSION( (((((((((x+1.35)+PI)\/PI)-y)+z)-z)+y)\/x)+0.81) )\n };\n\n for (int i = 0; i < TABLE_SIZE(tests); i++)\n {\n printf(\"EXP: %s\\n\", tests[i].expression);\n\n if (e0.create(ctx, tests[i].expression, MathPresso::MOPTION_NO_JIT) != MathPresso::MRESULT_OK)\n {\n printf(\" Failure: Compilation error (no-jit).\\n\");\n continue;\n }\n\n if (e1.create(ctx, tests[i].expression, MathPresso::MOPTION_NONE) != MathPresso::MRESULT_OK)\n {\n printf(\" Failure: Compilation error (use-jit).\\n\");\n continue;\n }\n\n MathPresso::mreal_t res0 = e0.evaluate(variables);\n MathPresso::mreal_t res1 = e1.evaluate(variables);\n MathPresso::mreal_t expected = tests[i].expected;\n\n const char* msg0 = fabs((double)res0 - (double)expected) < 0.001 ? \"Ok\" : \"Failure\";\n const char* msg1 = fabs((double)res1 - (double)expected) < 0.001 ? \"Ok\" : \"Failure\";\n\n printf(\n \" expected=%f\\n\"\n \" eval =%f (%s)\\n\"\n \" jit =%f (%s)\\n\"\n \"\\n\",\n (double)expected,\n (double)res0, msg0,\n (double)res1, msg1);\n }\n\n return 0;\n}\n<commit_msg>more tests, more output<commit_after>\/\/ MathPresso - Mathematical Expression Parser and JIT Compiler.\n\n\/\/ Copyright (c) 2008-2010, Petr Kobalicek <kobalicek.petr@gmail.com>\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person\n\/\/ obtaining a copy of this software and associated documentation\n\/\/ files (the \"Software\"), to deal in the Software without\n\/\/ restriction, including without limitation the rights to use,\n\/\/ copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the\n\/\/ Software is furnished to do so, subject to the following\n\/\/ conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be\n\/\/ included in all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n\/\/ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES\n\/\/ OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n\/\/ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n\/\/ HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,\n\/\/ WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n\/\/ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\n\/\/ OTHER DEALINGS IN THE SOFTWARE.\n\n#include <MathPresso\/MathPresso.h>\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n\nstruct TestExpression\n{\n const char* expression;\n MathPresso::mreal_t expected;\n};\n\n\/\/ Some test values\n#define INITVARS (x = 5.1f, y = 6.7f, z = 9.9f, t = 0)\n\n#define TABLE_SIZE(table) \\\n (sizeof(table) \/ sizeof(table[0]))\n\n#define TEST_EXPRESSION(expression) \\\n { #expression, (INITVARS, expression) }\n\n#define ADDCONST(c) addConstant(#c, (c))\n\n\nint main(int argc, char* argv[])\n{\n MathPresso::mreal_t x = 5.1f;\n MathPresso::mreal_t y = 6.7f;\n MathPresso::mreal_t z = 9.9f;\n MathPresso::mreal_t t = 0;\n\n const double PI = 3.14159265358979323846;\n\n MathPresso::mreal_t cx = cos(PI\/3);\n MathPresso::mreal_t cy = sin(PI\/3);\n MathPresso::mreal_t ox = 0.5;\n MathPresso::mreal_t oy = 1.75;\n\n MathPresso::Context ctx;\n MathPresso::Expression e0, e1, e2;\n\n ctx.addEnvironment(MathPresso::MENVIRONMENT_ALL);\n ctx.addVariable(\"x\", 0 * sizeof(MathPresso::mreal_t));\n ctx.addVariable(\"y\", 1 * sizeof(MathPresso::mreal_t));\n ctx.addVariable(\"z\", 2 * sizeof(MathPresso::mreal_t));\n ctx.addVariable(\"t\", 3 * sizeof(MathPresso::mreal_t));\n\n ctx.ADDCONST(cx);\n ctx.ADDCONST(cy);\n ctx.ADDCONST(ox);\n ctx.ADDCONST(oy);\n\n MathPresso::mreal_t variables[] = { x, y, z, t };\n\n TestExpression tests[] = {\n TEST_EXPRESSION( (x+y) ),\n TEST_EXPRESSION( -(x-y) ),\n TEST_EXPRESSION( -1 + x ),\n TEST_EXPRESSION( -(-(-1)) ),\n TEST_EXPRESSION( -(-(-x)) ),\n TEST_EXPRESSION( (x+y)*x ),\n TEST_EXPRESSION( (x+y)*y ),\n TEST_EXPRESSION( (x+y)*(1.19+z) ),\n TEST_EXPRESSION( ((x+(x+2.13))*y) ),\n TEST_EXPRESSION( (x+y+z*2+(x*z+z*1.5)) ),\n TEST_EXPRESSION( (((((((x-0.28)+y)+x)+x)*x)\/1.12)*y) ),\n TEST_EXPRESSION( ((((x*((((y-1.50)+1.82)-x)\/PI))\/x)*x)+z) ),\n TEST_EXPRESSION( (((((((((x+1.35)+PI)\/PI)-y)+z)-z)+y)\/x)+0.81) ),\n TEST_EXPRESSION( 1+(x+2)+3 ),\n TEST_EXPRESSION( 1+(x+y)+z ),\n TEST_EXPRESSION( x=2*3+1 ),\n TEST_EXPRESSION( (x+y)*z ),\n TEST_EXPRESSION( (x=y)*x ),\n TEST_EXPRESSION( x=y=z ),\n TEST_EXPRESSION( x=(y+(z=5)) ),\n \/\/ functions\n TEST_EXPRESSION( log(exp(x * PI\/2)) ),\n TEST_EXPRESSION( hypot(x, y) ),\n TEST_EXPRESSION( cos(PI\/4)*x - sin(PI\/4)*y ),\n TEST_EXPRESSION( sqrt(x*x + y*y + z*z) ),\n \/\/ operator ^\n { \"sqrt(x^2 + y^2 + z^2)\", (INITVARS, sqrt(x*x + y*y + z*z)) },\n { \"x^-2 + y^-3\", (INITVARS, 1\/(x*x) + pow(y, -3)) },\n \/\/ semicolon is comma in C++\n { \"z=x;x=3*x+1*y;y=1*x-3*z\", (INITVARS, z=x,x=3*x+1*y,y=1*x-3*z) },\n { \"t = cx*x - cy*y + ox; y = cy*x + cx*y + oy; x = t\", (INITVARS, t=cx*x - cy*y + ox, y = cy*x + cx*y + oy, x = t) },\n { \"x=cx;y=cy;t=z;z=t;\", (INITVARS, x=cx,y=cy,t=z,z=t) },\n \/\/ assignment\n { \"z = 1*z - 0*z + 1\", (INITVARS, z = 1*z - 0*z + 1) },\n { \"t = cx*x - cy*y + ox\", (INITVARS, t=cx*x - cy*y + ox) },\n { \"t = (cx*x - cy*y + ox)\", (INITVARS, t=cx*x - cy*y + ox) },\n \/\/ unary operators\n TEST_EXPRESSION( 2 * + x ),\n TEST_EXPRESSION( 2 * + + y ),\n TEST_EXPRESSION( -x * -z ),\n TEST_EXPRESSION( 2 * - -t ),\n TEST_EXPRESSION( -2 * - - -3.5 ),\n \/\/ optimization tests\n TEST_EXPRESSION( x = 2 * - - - + + - 2 + 0*y + z\/1 ),\n { \"1*x - 0*y + z^1 - t\/-1 + 0\", (INITVARS, 1*x - 0*y + pow(z, 1) - t\/-1 + 0) },\n { \"sin(x*1^t) - cos(0*y + PI) + z^(-4\/(-2-2))\", (INITVARS, sin(x*pow(1,t)) - cos(0*y + PI) + pow(z, -4\/(-2-2)) ) }\n };\n\n int numok0 = 0,\n numok1 = 0,\n numok2 = 0;\n\n int n = TABLE_SIZE(tests);\n for (int i = 0; i < n; ++i)\n {\n printf(\"EXP #%d: %s\\n\", i+1, tests[i].expression);\n\n if (e0.create(ctx, tests[i].expression, MathPresso::MOPTION_NO_JIT | MathPresso::MOPTION_NO_OPTIMIZE\n | MathPresso::MOPTION_VERBOSE) != MathPresso::MRESULT_OK)\n {\n printf(\" Failure: Compilation error (no JIT).\\n\");\n\t getchar();\n continue;\n }\n printf(\"\\nUnoptimized RPN : %s\\n\", e0.getRPN().c_str());\n\n if (e1.create(ctx, tests[i].expression, MathPresso::MOPTION_NO_OPTIMIZE) != MathPresso::MRESULT_OK)\n {\n printf(\" Failure: Compilation error (JIT).\\n\");\n\t getchar();\n continue;\n }\n\n if (e2.create(ctx, tests[i].expression, MathPresso::MOPTION_VERBOSE) != MathPresso::MRESULT_OK)\n {\n printf(\" Failure: Compilation error (optimized JIT).\\n\");\n\t getchar();\n continue;\n }\n printf(\"\\nOptimized RPN : %s\\n\", e2.getRPN().c_str());\n\n INITVARS;\n printf(\"\\nBefore: x= %f y= %f z= %f t= %f\\n\", x, y, z, t);\n variables[0] = x; variables[1] = y; variables[2] = z; variables[3] = t;\n MathPresso::mreal_t res0 = e0.evaluate(variables);\n\n INITVARS;\n variables[0] = x; variables[1] = y; variables[2] = z; variables[3] = t;\n MathPresso::mreal_t res1 = e1.evaluate(variables);\n\n INITVARS;\n variables[0] = x; variables[1] = y; variables[2] = z; variables[3] = t;\n MathPresso::mreal_t res2 = e2.evaluate(variables);\n\n printf(\"\\nAfter: x= %f y= %f z= %f t= %f\\n\", variables[0], variables[1], variables[2], variables[3]);\n\n MathPresso::mreal_t expected = tests[i].expected;\n\n bool ok0 = fabs((double)res0 - (double)expected) < 0.0000001;\n bool ok1 = fabs((double)res1 - (double)expected) < 0.0000001;\n bool ok2 = fabs((double)res2 - (double)expected) < 0.0000001;\n if (ok0) numok0++;\n if (ok1) numok1++;\n if (ok2) numok2++;\n\n printf(\"\\n\"\n \" expected = %f\\n\"\n \" eval = %f (%s)\\n\"\n \" JIT = %f (%s)\\n\"\n \" optimized JIT = %f (%s)\\n\"\n \"\\n\",\n (double)expected,\n (double)res0, ok0 ? \"Ok\" : \"Failure\",\n (double)res1, ok1 ? \"Ok\" : \"Failure\",\n (double)res2, ok2 ? \"Ok\" : \"Failure\");\n \/\/getchar();\n }\n\n printf(\"eval: %d of %d ok\\n\"\n \"jit: %d of %d ok\\n\"\n \"op_jit: %d of %d ok\\n\", numok0, n, numok1, n, numok2, n);\n \/\/getchar();\n\n MathPresso::mresult_t result;\n do {\n char buffer[4096];\n fgets(buffer, 4095, stdin);\n if (buffer[0] == 0) break;\n\n MathPresso::Expression e;\n result = e.create(ctx, buffer, MathPresso::MOPTION_VERBOSE);\n if (result == MathPresso::MRESULT_NO_EXPRESSION)\n printf(\"No expression\\n\");\n\n if (result != MathPresso::MRESULT_OK)\n {\n \/\/printf(\"%s\\n\", buffer);\n int errorPos = e.getErrorPos();\n for (int j = 0; j < errorPos; ++j) printf(\" \");\n printf(\"^\\n\");\n printf(\"Error: %s at pos=%d\\n\", e.getErrorMessage(), errorPos);\n }\n else\n {\n printf(\"\\nOptimized RPN : %s\\n\", e.getRPN().c_str());\n printf(\"\\n%s\\n\", e.getJitLog().c_str());\n printf(\"Result = %9.20g\\n\", e.evaluate(&variables));\n }\n } while(result != MathPresso::MRESULT_NO_EXPRESSION);\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ Copyright (C) 2017 University of Amsterdam\n\/\/\n\/\/ This program is free software: you can redistribute it and\/or modify\n\/\/ it under the terms of the GNU General Public License as published by\n\/\/ the Free Software Foundation, either version 2 of the License, or\n\/\/ (at your option) any later version.\n\/\/\n\/\/ This program is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n\/\/ GNU General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU General Public License\n\/\/ along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n\/\/\n\n#include \"appinfo.h\"\n\nconst Version AppInfo::version = Version(0, 8, 5, 255);\nconst std::string AppInfo::name = \"JASP\";\nconst std::string AppInfo::builddate = __DATE__ \" \" __TIME__ \" (Netherlands)\" ;\n\nstd::string AppInfo::getShortDesc()\n{\n\treturn AppInfo::name + \" \" + AppInfo::version.asString();\n}\n\nstd::string AppInfo::getBuildYear()\n{\n\tstd::string datum = __DATE__;\n\treturn datum.substr(datum.length() - 4);\n}\n\n<commit_msg>Set version to 0.8.5.1<commit_after>\/\/\n\/\/ Copyright (C) 2017 University of Amsterdam\n\/\/\n\/\/ This program is free software: you can redistribute it and\/or modify\n\/\/ it under the terms of the GNU General Public License as published by\n\/\/ the Free Software Foundation, either version 2 of the License, or\n\/\/ (at your option) any later version.\n\/\/\n\/\/ This program is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n\/\/ GNU General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU General Public License\n\/\/ along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n\/\/\n\n#include \"appinfo.h\"\n\nconst Version AppInfo::version = Version(0, 8, 5, 256);\nconst std::string AppInfo::name = \"JASP\";\nconst std::string AppInfo::builddate = __DATE__ \" \" __TIME__ \" (Netherlands)\" ;\n\nstd::string AppInfo::getShortDesc()\n{\n\treturn AppInfo::name + \" \" + AppInfo::version.asString();\n}\n\nstd::string AppInfo::getBuildYear()\n{\n\tstd::string datum = __DATE__;\n\treturn datum.substr(datum.length() - 4);\n}\n\n<|endoftext|>"} {"text":"<commit_before>\n\/*!\n\t\\file\n\n\t\\author Igor Mironchik (igor.mironchik at gmail dot com).\n\n\tCopyright (c) 2017 Igor Mironchik\n\n\tPermission is hereby granted, free of charge, to any person\n\tobtaining a copy of this software and associated documentation\n\tfiles (the \"Software\"), to deal in the Software without\n\trestriction, including without limitation the rights to use,\n\tcopy, modify, merge, publish, distribute, sublicense, and\/or sell\n\tcopies of the Software, and to permit persons to whom the\n\tSoftware is furnished to do so, subject to the following\n\tconditions:\n\n\tThe above copyright notice and this permission notice shall be\n\tincluded in all copies or substantial portions of the Software.\n\n\tTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n\tEXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES\n\tOF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n\tNONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n\tHOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,\n\tWHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n\tFROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\n\tOTHER DEALINGS IN THE SOFTWARE.\n*\/\n\n#ifndef CFGFILE__TYPES_HPP__INCLUDED\n#define CFGFILE__TYPES_HPP__INCLUDED\n\n\/\/ C++ include.\n#include <string>\n#include <iostream>\n#include <cwctype>\n#include <cctype>\n\n#ifdef CFGFILE_QT_SUPPORT\n\/\/ Qt include.\n#include <QString>\n#include <QTextStream>\n#endif \/\/ CFGFILE_QT_SUPPORT\n\n\nnamespace cfgfile {\n\n\/\/\n\/\/ wstring_trait_t\n\/\/\n\n\/\/! Trait for std::wstring support.\nstruct wstring_trait_t final {\n\t\/\/! String type.\n\tusing string_t = std::wstring;\n\n\t\/\/! Char type.\n\tusing char_t = string_t::value_type;\n\n\t\/\/! Out stream type.\n\tusing ostream_t = std::wostream;\n\n\t\/\/! In stream type.\n\tusing istream_t = std::wistream;\n\n\t\/\/! Type of pos in stream.\n\tusing pos_t = std::streamoff;\n\n\tstatic inline string_t to_string( pos_t pos )\n\t{\n\t\treturn std::to_wstring( pos );\n\t}\n\n\tstatic inline string_t from_ascii( const std::string & str )\n\t{\n\t\tstd::wstring res;\n\t\tres.assign( str.cbegin(), str.cend() );\n\n\t\treturn res;\n\t}\n\n\tstatic inline char_t from_ascii( char ch )\n\t{\n\t\treturn (char_t) ch;\n\t}\n\n\tstatic inline void noskipws( istream_t & stream )\n\t{\n\t\tstream >> std::noskipws;\n\t}\n\n\tstatic inline bool is_at_end( istream_t & stream )\n\t{\n\t\tchar_t tmp = 0;\n\n\t\tstream >> tmp;\n\n\t\tif( tmp )\n\t\t{\n\t\t\tstream.putback( tmp );\n\n\t\t\treturn false;\n\t\t}\n\t\telse\n\t\t\treturn true;\n\t}\n\n\tstatic inline bool is_space( char_t ch )\n\t{\n\t\treturn std::iswspace( ch );\n\t}\n\n\tstatic inline void to_begin( istream_t & stream )\n\t{\n\t\tstream.seekg( 0 );\n\t}\n}; \/\/ struct wstring_trait_t\n\n\n\/\/\n\/\/ string_trait_t\n\/\/\n\n\/\/! Trait for std::string support.\nstruct string_trait_t final {\n\t\/\/! String type.\n\tusing string_t = std::string;\n\n\t\/\/! Char type.\n\tusing char_t = string_t::value_type;\n\n\t\/\/! Input stream type.\n\tusing istream_t = std::istream;\n\n\t\/\/! Type of pos in stream.\n\tusing pos_t = std::streamoff;\n\n\t\/\/! Output stream type.\n\tusing ostream_t = std::ostream;\n\n\tstatic inline string_t to_string( pos_t pos )\n\t{\n\t\treturn std::to_string( pos );\n\t}\n\n\tstatic inline string_t from_ascii( const std::string & str )\n\t{\n\t\treturn str;\n\t}\n\n\tstatic inline char_t from_ascii( char ch )\n\t{\n\t\treturn ch;\n\t}\n\n\tstatic inline void noskipws( istream_t & stream )\n\t{\n\t\tstream >> std::noskipws;\n\t}\n\n\tstatic inline bool is_at_end( istream_t & stream )\n\t{\n\t\tchar_t tmp = 0;\n\n\t\tstream >> tmp;\n\n\t\tif( tmp )\n\t\t{\n\t\t\tstream.putback( tmp );\n\n\t\t\treturn false;\n\t\t}\n\t\telse\n\t\t\treturn true;\n\t}\n\n\tstatic inline bool is_space( char_t ch )\n\t{\n\t\treturn std::isspace( (unsigned char) ch );\n\t}\n\n\tstatic inline void to_begin( istream_t & stream )\n\t{\n\t\tstream.seekg( 0 );\n\t}\n}; \/\/ struct string_trait_t\n\n\n#ifdef CFGFILE_QT_SUPPORT\n\n\/\/\n\/\/ qstring_wrapper_t\n\/\/\n\n\/\/! QString wrapper.\nclass qstring_wrapper_t {\npublic:\n\tusing size_type = int;\n\n\tqstring_wrapper_t()\n\t{\n\t}\n\n\tqstring_wrapper_t( size_type size, QChar ch )\n\t\t:\tm_str( size, ch )\n\t{\n\t}\n\n\tqstring_wrapper_t( const char * str )\n\t\t:\tm_str( str )\n\t{\n\t}\n\n\tqstring_wrapper_t( const QString & other )\n\t\t:\tm_str( other )\n\t{\n\t}\n\n\n\tqstring_wrapper_t( const QChar * unicode, size_type size = -1 )\n\t\t:\tm_str( unicode, size )\n\t{\n\t}\n\n\tqstring_wrapper_t( QChar ch )\n\t\t:\tm_str( ch )\n\t{\n\t}\n\n\tqstring_wrapper_t( QLatin1String str )\n\t\t:\tm_str( str )\n\t{\n\t}\n\n\tqstring_wrapper_t( const QByteArray & ba )\n\t\t:\tm_str( ba )\n\t{\n\t}\n\n\toperator QString ()\n\t{\n\t\treturn m_str;\n\t}\n\n\toperator QString () const\n\t{\n\t\treturn m_str;\n\t}\n\n\tinline bool empty() const\n\t{\n\t\treturn m_str.isEmpty();\n\t}\n\n\tstatic const int npos = -1;\n\n\tinline int find( QChar ch ) const\n\t{\n\t\treturn m_str.indexOf( ch );\n\t}\n\n\tinline int find( const qstring_wrapper_t & str ) const\n\t{\n\t\treturn m_str.indexOf( str.m_str );\n\t}\n\n\tinline int rfind( const qstring_wrapper_t & str ) const\n\t{\n\t\treturn m_str.lastIndexOf( str.m_str );\n\t}\n\n\tinline int rfind( QChar ch ) const\n\t{\n\t\treturn m_str.lastIndexOf( ch );\n\t}\n\n\tqstring_wrapper_t & replace( size_type pos, size_type count,\n\t\tconst qstring_wrapper_t & v )\n\t{\n\t\tm_str.replace( pos, count, v.m_str );\n\n\t\treturn *this;\n\t}\n\n\tinline QString::iterator begin()\n\t{\n\t\treturn m_str.begin();\n\t}\n\n\tinline QString::iterator end()\n\t{\n\t\treturn m_str.end();\n\t}\n\n\tinline QString::const_iterator begin() const\n\t{\n\t\treturn m_str.begin();\n\t}\n\n\tinline QString::const_iterator end() const\n\t{\n\t\treturn m_str.end();\n\t}\n\n\tinline QString::const_iterator cbegin() const\n\t{\n\t\treturn m_str.begin();\n\t}\n\n\tinline QString::const_iterator cend() const\n\t{\n\t\treturn m_str.end();\n\t}\n\n\tinline size_type length() const\n\t{\n\t\treturn m_str.length();\n\t}\n\n\n\tinline const QChar at( int position ) const\n\t{\n\t\treturn m_str.at( position );\n\t}\n\n\n\tinline qstring_wrapper_t substr( size_type pos, size_type count = npos ) const\n\t{\n\t\treturn m_str.mid( pos, count );\n\t}\n\n\tfriend bool operator == ( const qstring_wrapper_t & s1,\n\t\tconst qstring_wrapper_t & s2 )\n\t{\n\t\treturn ( s1.m_str == s2.m_str );\n\t}\n\n\tfriend qstring_wrapper_t operator + ( const qstring_wrapper_t & s1,\n\t\tconst qstring_wrapper_t & s2 )\n\t{\n\t\treturn qstring_wrapper_t( s1.m_str + s2.m_str );\n\t}\n\n\tfriend qstring_wrapper_t operator + ( const qstring_wrapper_t & s1,\n\t\tconst char * s2 )\n\t{\n\t\treturn qstring_wrapper_t( s1.m_str + s2 );\n\t}\n\n\tfriend qstring_wrapper_t operator + ( const char * s1,\n\t\tconst qstring_wrapper_t & s2 )\n\t{\n\t\treturn qstring_wrapper_t( s1 + s2.m_str );\n\t}\n\n\tfriend qstring_wrapper_t operator + ( const qstring_wrapper_t & s1,\n\t\tconst char ch )\n\t{\n\t\treturn qstring_wrapper_t( s1.m_str + ch );\n\t}\n\n\tfriend qstring_wrapper_t operator + ( const char ch,\n\t\tconst qstring_wrapper_t & s2 )\n\t{\n\t\treturn qstring_wrapper_t( ch + s2.m_str );\n\t}\n\n\tfriend QTextStream & operator << ( QTextStream & to,\n\t\tconst qstring_wrapper_t & what )\n\t{\n\t\tto << what.m_str;\n\n\t\treturn to;\n\t}\n\n\tinline const QChar operator [] ( size_type pos ) const\n\t{\n\t\treturn m_str[ pos ];\n\t}\n\n\tinline qstring_wrapper_t & append( const qstring_wrapper_t & other )\n\t{\n\t\tm_str.append( other.m_str );\n\n\t\treturn *this;\n\t}\n\n\tinline qstring_wrapper_t & append( size_type count, QChar ch )\n\t{\n\t\tm_str.append( QString( count, ch ) );\n\n\t\treturn *this;\n\t}\n\n\tinline void clear()\n\t{\n\t\tm_str.clear();\n\t}\n\n\tinline void push_back( QChar ch )\n\t{\n\t\tm_str.append( ch );\n\t}\n\nprivate:\n\t\/\/! Actual string.\n\tQString m_str;\n}; \/\/ class qstring_wrapper_t\n\n\n\/\/\n\/\/ qstring_trait_t\n\/\/\n\n\/\/! Trait for QString support.\nstruct qstring_trait_t final {\n\t\/\/! String type.\n\tusing string_t = qstring_wrapper_t;\n\n\t\/\/! Char type.\n\tusing char_t = QChar;\n\n\t\/\/! Out stream type.\n\tusing ostream_t = QTextStream;\n\n\t\/\/! In stream type.\n\tusing istream_t = QTextStream;\n\n\t\/\/! Type of pos in stream.\n\tusing pos_t = qint64;\n\n\tstatic inline string_t to_string( pos_t pos )\n\t{\n\t\treturn QString::number( pos );\n\t}\n\n\tstatic inline string_t from_ascii( const std::string & str )\n\t{\n\t\treturn qstring_wrapper_t( QString( str.c_str() ) );\n\t}\n\n\tstatic inline char_t from_ascii( char ch )\n\t{\n\t\treturn QLatin1Char( ch );\n\t}\n\n\tstatic inline void noskipws( istream_t & )\n\t{\n\t}\n\n\tstatic inline bool is_at_end( istream_t & stream )\n\t{\n\t\treturn stream.atEnd();\n\t}\n\n\tstatic inline bool is_space( char_t ch )\n\t{\n\t\treturn ch.isSpace();\n\t}\n\n\tstatic inline void to_begin( istream_t & stream )\n\t{\n\t\tstream.seek( 0 );\n\t}\n}; \/\/ struct qstring_trait_t\n\n#endif \/\/ CFGFILE_QT_SUPPORT\n\n\n\/\/\n\/\/ DISABLE_COPY\n\/\/\n\n\/\/! Macro for disabling copy.\n#define DISABLE_COPY( Class ) \\\n\tClass( const Class & ) = delete; \\\n\tClass & operator= ( const Class & ) = delete;\n\n} \/* namespace cfgfile *\/\n\n#endif \/\/ CFGFILE__TYPES_HPP__INCLUDED\n<commit_msg>Supressed warnings.<commit_after>\n\/*!\n\t\\file\n\n\t\\author Igor Mironchik (igor.mironchik at gmail dot com).\n\n\tCopyright (c) 2017 Igor Mironchik\n\n\tPermission is hereby granted, free of charge, to any person\n\tobtaining a copy of this software and associated documentation\n\tfiles (the \"Software\"), to deal in the Software without\n\trestriction, including without limitation the rights to use,\n\tcopy, modify, merge, publish, distribute, sublicense, and\/or sell\n\tcopies of the Software, and to permit persons to whom the\n\tSoftware is furnished to do so, subject to the following\n\tconditions:\n\n\tThe above copyright notice and this permission notice shall be\n\tincluded in all copies or substantial portions of the Software.\n\n\tTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n\tEXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES\n\tOF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n\tNONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n\tHOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,\n\tWHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n\tFROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\n\tOTHER DEALINGS IN THE SOFTWARE.\n*\/\n\n#ifndef CFGFILE__TYPES_HPP__INCLUDED\n#define CFGFILE__TYPES_HPP__INCLUDED\n\n\/\/ C++ include.\n#include <string>\n#include <iostream>\n#include <cwctype>\n#include <cctype>\n\n#ifdef CFGFILE_QT_SUPPORT\n\/\/ Qt include.\n#include <QString>\n#include <QTextStream>\n#endif \/\/ CFGFILE_QT_SUPPORT\n\n\nnamespace cfgfile {\n\n\/\/\n\/\/ wstring_trait_t\n\/\/\n\n\/\/! Trait for std::wstring support.\nstruct wstring_trait_t final {\n\t\/\/! String type.\n\tusing string_t = std::wstring;\n\n\t\/\/! Char type.\n\tusing char_t = string_t::value_type;\n\n\t\/\/! Out stream type.\n\tusing ostream_t = std::wostream;\n\n\t\/\/! In stream type.\n\tusing istream_t = std::wistream;\n\n\t\/\/! Type of pos in stream.\n\tusing pos_t = std::streamoff;\n\n\tstatic inline string_t to_string( pos_t pos )\n\t{\n\t\treturn std::to_wstring( pos );\n\t}\n\n\tstatic inline string_t from_ascii( const std::string & str )\n\t{\n\t\tstd::wstring res;\n\t\tres.assign( str.cbegin(), str.cend() );\n\n\t\treturn res;\n\t}\n\n\tstatic inline char_t from_ascii( char ch )\n\t{\n\t\treturn (char_t) ch;\n\t}\n\n\tstatic inline void noskipws( istream_t & stream )\n\t{\n\t\tstream >> std::noskipws;\n\t}\n\n\tstatic inline bool is_at_end( istream_t & stream )\n\t{\n\t\tchar_t tmp = 0;\n\n\t\tstream >> tmp;\n\n\t\tif( tmp )\n\t\t{\n\t\t\tstream.putback( tmp );\n\n\t\t\treturn false;\n\t\t}\n\t\telse\n\t\t\treturn true;\n\t}\n\n\tstatic inline bool is_space( char_t ch )\n\t{\n\t\treturn ( std::iswspace( ch ) != 0 );\n\t}\n\n\tstatic inline void to_begin( istream_t & stream )\n\t{\n\t\tstream.seekg( 0 );\n\t}\n}; \/\/ struct wstring_trait_t\n\n\n\/\/\n\/\/ string_trait_t\n\/\/\n\n\/\/! Trait for std::string support.\nstruct string_trait_t final {\n\t\/\/! String type.\n\tusing string_t = std::string;\n\n\t\/\/! Char type.\n\tusing char_t = string_t::value_type;\n\n\t\/\/! Input stream type.\n\tusing istream_t = std::istream;\n\n\t\/\/! Type of pos in stream.\n\tusing pos_t = std::streamoff;\n\n\t\/\/! Output stream type.\n\tusing ostream_t = std::ostream;\n\n\tstatic inline string_t to_string( pos_t pos )\n\t{\n\t\treturn std::to_string( pos );\n\t}\n\n\tstatic inline string_t from_ascii( const std::string & str )\n\t{\n\t\treturn str;\n\t}\n\n\tstatic inline char_t from_ascii( char ch )\n\t{\n\t\treturn ch;\n\t}\n\n\tstatic inline void noskipws( istream_t & stream )\n\t{\n\t\tstream >> std::noskipws;\n\t}\n\n\tstatic inline bool is_at_end( istream_t & stream )\n\t{\n\t\tchar_t tmp = 0;\n\n\t\tstream >> tmp;\n\n\t\tif( tmp )\n\t\t{\n\t\t\tstream.putback( tmp );\n\n\t\t\treturn false;\n\t\t}\n\t\telse\n\t\t\treturn true;\n\t}\n\n\tstatic inline bool is_space( char_t ch )\n\t{\n\t\treturn ( std::isspace( (int) ch ) != 0 );\n\t}\n\n\tstatic inline void to_begin( istream_t & stream )\n\t{\n\t\tstream.seekg( 0 );\n\t}\n}; \/\/ struct string_trait_t\n\n\n#ifdef CFGFILE_QT_SUPPORT\n\n\/\/\n\/\/ qstring_wrapper_t\n\/\/\n\n\/\/! QString wrapper.\nclass qstring_wrapper_t {\npublic:\n\tusing size_type = int;\n\n\tqstring_wrapper_t()\n\t{\n\t}\n\n\tqstring_wrapper_t( size_type size, QChar ch )\n\t\t:\tm_str( size, ch )\n\t{\n\t}\n\n\tqstring_wrapper_t( const char * str )\n\t\t:\tm_str( str )\n\t{\n\t}\n\n\tqstring_wrapper_t( const QString & other )\n\t\t:\tm_str( other )\n\t{\n\t}\n\n\n\tqstring_wrapper_t( const QChar * unicode, size_type size = -1 )\n\t\t:\tm_str( unicode, size )\n\t{\n\t}\n\n\tqstring_wrapper_t( QChar ch )\n\t\t:\tm_str( ch )\n\t{\n\t}\n\n\tqstring_wrapper_t( QLatin1String str )\n\t\t:\tm_str( str )\n\t{\n\t}\n\n\tqstring_wrapper_t( const QByteArray & ba )\n\t\t:\tm_str( ba )\n\t{\n\t}\n\n\toperator QString ()\n\t{\n\t\treturn m_str;\n\t}\n\n\toperator QString () const\n\t{\n\t\treturn m_str;\n\t}\n\n\tinline bool empty() const\n\t{\n\t\treturn m_str.isEmpty();\n\t}\n\n\tstatic const int npos = -1;\n\n\tinline int find( QChar ch ) const\n\t{\n\t\treturn m_str.indexOf( ch );\n\t}\n\n\tinline int find( const qstring_wrapper_t & str ) const\n\t{\n\t\treturn m_str.indexOf( str.m_str );\n\t}\n\n\tinline int rfind( const qstring_wrapper_t & str ) const\n\t{\n\t\treturn m_str.lastIndexOf( str.m_str );\n\t}\n\n\tinline int rfind( QChar ch ) const\n\t{\n\t\treturn m_str.lastIndexOf( ch );\n\t}\n\n\tqstring_wrapper_t & replace( size_type pos, size_type count,\n\t\tconst qstring_wrapper_t & v )\n\t{\n\t\tm_str.replace( pos, count, v.m_str );\n\n\t\treturn *this;\n\t}\n\n\tinline QString::iterator begin()\n\t{\n\t\treturn m_str.begin();\n\t}\n\n\tinline QString::iterator end()\n\t{\n\t\treturn m_str.end();\n\t}\n\n\tinline QString::const_iterator begin() const\n\t{\n\t\treturn m_str.begin();\n\t}\n\n\tinline QString::const_iterator end() const\n\t{\n\t\treturn m_str.end();\n\t}\n\n\tinline QString::const_iterator cbegin() const\n\t{\n\t\treturn m_str.begin();\n\t}\n\n\tinline QString::const_iterator cend() const\n\t{\n\t\treturn m_str.end();\n\t}\n\n\tinline size_type length() const\n\t{\n\t\treturn m_str.length();\n\t}\n\n\n\tinline const QChar at( int position ) const\n\t{\n\t\treturn m_str.at( position );\n\t}\n\n\n\tinline qstring_wrapper_t substr( size_type pos, size_type count = npos ) const\n\t{\n\t\treturn m_str.mid( pos, count );\n\t}\n\n\tfriend bool operator == ( const qstring_wrapper_t & s1,\n\t\tconst qstring_wrapper_t & s2 )\n\t{\n\t\treturn ( s1.m_str == s2.m_str );\n\t}\n\n\tfriend qstring_wrapper_t operator + ( const qstring_wrapper_t & s1,\n\t\tconst qstring_wrapper_t & s2 )\n\t{\n\t\treturn qstring_wrapper_t( s1.m_str + s2.m_str );\n\t}\n\n\tfriend qstring_wrapper_t operator + ( const qstring_wrapper_t & s1,\n\t\tconst char * s2 )\n\t{\n\t\treturn qstring_wrapper_t( s1.m_str + s2 );\n\t}\n\n\tfriend qstring_wrapper_t operator + ( const char * s1,\n\t\tconst qstring_wrapper_t & s2 )\n\t{\n\t\treturn qstring_wrapper_t( s1 + s2.m_str );\n\t}\n\n\tfriend qstring_wrapper_t operator + ( const qstring_wrapper_t & s1,\n\t\tconst char ch )\n\t{\n\t\treturn qstring_wrapper_t( s1.m_str + ch );\n\t}\n\n\tfriend qstring_wrapper_t operator + ( const char ch,\n\t\tconst qstring_wrapper_t & s2 )\n\t{\n\t\treturn qstring_wrapper_t( ch + s2.m_str );\n\t}\n\n\tfriend QTextStream & operator << ( QTextStream & to,\n\t\tconst qstring_wrapper_t & what )\n\t{\n\t\tto << what.m_str;\n\n\t\treturn to;\n\t}\n\n\tinline const QChar operator [] ( size_type pos ) const\n\t{\n\t\treturn m_str[ pos ];\n\t}\n\n\tinline qstring_wrapper_t & append( const qstring_wrapper_t & other )\n\t{\n\t\tm_str.append( other.m_str );\n\n\t\treturn *this;\n\t}\n\n\tinline qstring_wrapper_t & append( size_type count, QChar ch )\n\t{\n\t\tm_str.append( QString( count, ch ) );\n\n\t\treturn *this;\n\t}\n\n\tinline void clear()\n\t{\n\t\tm_str.clear();\n\t}\n\n\tinline void push_back( QChar ch )\n\t{\n\t\tm_str.append( ch );\n\t}\n\nprivate:\n\t\/\/! Actual string.\n\tQString m_str;\n}; \/\/ class qstring_wrapper_t\n\n\n\/\/\n\/\/ qstring_trait_t\n\/\/\n\n\/\/! Trait for QString support.\nstruct qstring_trait_t final {\n\t\/\/! String type.\n\tusing string_t = qstring_wrapper_t;\n\n\t\/\/! Char type.\n\tusing char_t = QChar;\n\n\t\/\/! Out stream type.\n\tusing ostream_t = QTextStream;\n\n\t\/\/! In stream type.\n\tusing istream_t = QTextStream;\n\n\t\/\/! Type of pos in stream.\n\tusing pos_t = qint64;\n\n\tstatic inline string_t to_string( pos_t pos )\n\t{\n\t\treturn QString::number( pos );\n\t}\n\n\tstatic inline string_t from_ascii( const std::string & str )\n\t{\n\t\treturn qstring_wrapper_t( QString( str.c_str() ) );\n\t}\n\n\tstatic inline char_t from_ascii( char ch )\n\t{\n\t\treturn QLatin1Char( ch );\n\t}\n\n\tstatic inline void noskipws( istream_t & )\n\t{\n\t}\n\n\tstatic inline bool is_at_end( istream_t & stream )\n\t{\n\t\treturn stream.atEnd();\n\t}\n\n\tstatic inline bool is_space( char_t ch )\n\t{\n\t\treturn ch.isSpace();\n\t}\n\n\tstatic inline void to_begin( istream_t & stream )\n\t{\n\t\tstream.seek( 0 );\n\t}\n}; \/\/ struct qstring_trait_t\n\n#endif \/\/ CFGFILE_QT_SUPPORT\n\n\n\/\/\n\/\/ DISABLE_COPY\n\/\/\n\n\/\/! Macro for disabling copy.\n#define DISABLE_COPY( Class ) \\\n\tClass( const Class & ) = delete; \\\n\tClass & operator= ( const Class & ) = delete;\n\n} \/* namespace cfgfile *\/\n\n#endif \/\/ CFGFILE__TYPES_HPP__INCLUDED\n<|endoftext|>"} {"text":"<commit_before>#include <vector>\n#include <string>\n#include <ncurses.h>\n#include <iostream>\n#include <stdexcept>\n\nusing std::string;\n\nvoid die(const string& msg);\n\nclass Marquee\n{\nprivate:\n\tint row;\n\tstring text;\n\tunsigned int position;\npublic:\n\tMarquee(int row, const string& text) : row(row), text(text), position(0) {\n\t\tif(this->text.empty()) {\n\t\t\tthrow std::length_error(\"Text was empty\");\n\t\t}\n\t}\n\tvoid Draw();\n};\n\nvoid Marquee::Draw()\n{\n\tif (this->position==this->text.length()) {\n\t\tthis->position=0;\n\t}\n\tmvdelch(this->row, 0);\n\tmvinsch(this->row, COLS-1, this->text[this->position]);\n\t++this->position;\n}\n\nint main(void)\n{\n\tinitscr();\n\tconst string text(\"WARNING * \");\n\n\tstd::vector<Marquee> marquees;\n\tfor (int i=0; i < 10; i++)\n\t\tmarquees.push_back(Marquee(i, text));\n\n\twhile(true) {\n\t\trefresh();\n\t\tfor (std::vector<Marquee>::iterator it=marquees.begin(); it != marquees.end(); ++it) {\n\t\t\t(*it).Draw();\n\t\t}\n\t\tnapms(100);\n\t}\n\n\tendwin();\n\treturn 0;\n}\n\nvoid die(const string& v)\n{\n\tendwin();\n\tstd::cerr << v << std::endl;\n\texit(1);\n}\n<commit_msg>Interesting 'Main Menu'<commit_after>#include <vector>\n#include <cmath>\n#include <string>\n#include <ncurses.h>\n#include <iostream>\n#include <stdexcept>\n\nusing std::string;\nusing std::vector;\n\nvoid die(const string& msg);\n\nint main(void)\n{\n\tinitscr();\n\n\tvector<string> options;\n\toptions.push_back(\"Read the News\");\n\toptions.push_back(\"Fill the Bucket\");\n\toptions.push_back(\"Save the Options\");\n\toptions.push_back(\"Exit\");\n\n\tmvaddstr(0, 0, \"Main Menu\");\n\n\tfor (unsigned int i = 0; i < options.size(); i++) {\n\t\tmvprintw(4+(i*2), 10, \"%d. %s\", i+1, options[i].c_str());\n\t}\n\n\tmvprintw(4+(options.size()*2)+1, 10, \"Use arrow keys to move; Enter to select:\");\n\n\tkeypad(stdscr, TRUE);\n\tnodelay(stdscr, TRUE);\n\tnoecho();\n\n\tint selection = 0;\n\twhile(true) {\n\t\tint ch = getch();\n\t\tmvchgat(4+(selection*2), 10+3, options[selection].length(), 0, 0, NULL);\n\t\tswitch(ch) {\n\t\t\tcase KEY_DOWN:\n\t\t\t\tselection++;\n\t\t\t\tbreak;\n\t\t\tcase KEY_UP:\n\t\t\t\tselection--;\n\t\t\t\tbreak;\n\t\t}\n\t\tselection=std::min(std::max(selection, 0), (int)(options.size()-1));\n\t\tmvchgat(4+(selection*2), 10+3, options[selection].length(), A_REVERSE, 0, NULL);\n\t}\n\n\tendwin();\n\treturn 0;\n}\n\nvoid die(const string& v)\n{\n\tendwin();\n\tstd::cerr << v << std::endl;\n\texit(1);\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n Copyright (c) 2005 Olivier Goffart <ogoffart@kde.org>\n\n Kopete (c) 2005-2007 by the Kopete developers <kopete-devel@kde.org>\n\n *************************************************************************\n * *\n * This library is free software; you can redistribute it and\/or *\n * modify it under the terms of the GNU Lesser General Public *\n * License as published by the Free Software Foundation; either *\n * version 2 of the License, or (at your option) any later version. *\n * *\n *************************************************************************\n*\/\n\n#include \"contactaddednotifydialog.h\"\n\n\n#include <qlabel.h>\n#include <qcheckbox.h>\n#include <qapplication.h>\n\n#include <klocale.h>\n#include <kcombobox.h>\n#include <klineedit.h>\n#include <kpushbutton.h>\n#include <kiconloader.h>\n\n#include <kabc\/addressee.h>\n\n#include \"kopetegroup.h\"\n#include \"kopeteaccount.h\"\n#include \"kopeteuiglobal.h\"\n#include \"kopeteprotocol.h\"\n#include \"kopetecontactlist.h\"\n#include \"kopetemetacontact.h\"\n#include \"addressbooklinkwidget.h\"\n#include \"addressbookselectordialog.h\"\n#include \"ui_contactaddednotifywidget.h\"\n\nnamespace Kopete {\n\nnamespace UI {\n\nstruct ContactAddedNotifyDialog::Private\n{\n\tUi::ContactAddedNotifyWidget *widget;\n\tAccount *account;\n\tQString contactId;\n\tQString addressbookId;\n};\n\n\nContactAddedNotifyDialog::ContactAddedNotifyDialog(const QString& contactId,\n\t\tconst QString& contactNick, Kopete::Account *account, const HideWidgetOptions &hide)\n\t: KDialog( Global::mainWidget() ), d(new Private())\n{\n\tsetCaption( i18n(\"Someone Has Added You\") );\n\tsetButtons( KDialog::Ok | KDialog::Cancel );\n setAttribute( Qt::WA_DeleteOnClose );\n\n\td->widget=new Ui::ContactAddedNotifyWidget;\n\tQWidget* w = new QWidget(this);\n\td->widget->setupUi(w);\n\tsetMainWidget(w);\n\n\td->account=account;\n\td->contactId=contactId;\n\td->widget->m_label->setText(i18n(\"<qt><img src=\\\"kopete-account-icon:%1\\\" \/> The contact <b>%2<\/b> has added you to his\/her contact list. (Account %3)<\/qt>\",\n\t\t\tQString(QUrl::toPercentEncoding( account->protocol()->pluginId() )) + QString::fromLatin1(\":\")\n\t\t\t + QString(QUrl::toPercentEncoding( account->accountId() )) ,\n\t\t\t\t contactNick.isEmpty() ? contactId : contactNick + QString::fromLatin1(\" < \") + contactId + QString::fromLatin1(\" >\") ,\n\t\t\t\t account->accountLabel() \t) );\n\tif( hide & InfoButton)\n\t\td->widget->m_infoButton->hide() ;\n\tif( hide & AuthorizeCheckBox )\n\t{\n\t\td->widget->m_authorizeCb->hide();\n\t\td->widget->m_authorizeCb->setChecked(false);\n\t}\n\tif( hide & AddCheckBox )\n\t{\n\t\td->widget->m_addCb->hide();\n\t\td->widget->m_addCb->setChecked(false);\n\t}\n\tif( hide & AddGroupBox )\n\t\td->widget->m_contactInfoBox->hide();\n\n\t\/\/ Populate the groups list\n\tQListIterator<Group *> it(Kopete::ContactList::self()->groups());\n\twhile ( it.hasNext() )\n\t{\n\t\tGroup *g = it.next();\n\t\tQString groupname = g->displayName();\n\t\tif ( g->type() == Group::Normal && !groupname.isEmpty() )\n\t\t{\n\t\t\td->widget->m_groupList->addItem(groupname);\n\t\t}\n\t}\n\td->widget->m_groupList->setEditText(QString()); \/\/default to top-level\n\n\tconnect( d->widget->widAddresseeLink, SIGNAL( addresseeChanged( const KABC::Addressee& ) ), this, SLOT( slotAddresseeSelected( const KABC::Addressee& ) ) );\n\tconnect( d->widget->m_infoButton, SIGNAL( clicked() ), this, SLOT( slotInfoClicked() ) );\n\n\tconnect( this, SIGNAL(okClicked()) , this , SLOT(slotFinished()));\n\n}\n\n\nContactAddedNotifyDialog::~ContactAddedNotifyDialog()\n{\n\/\/ deleting the widget is not needed because it has a parent\n\/\/ which takes care of them\n\/\/\tdelete d->widget;\n\tdelete d;\n}\n\nbool ContactAddedNotifyDialog::added() const\n{\n\treturn d->widget->m_addCb->isChecked();\n}\n\nbool ContactAddedNotifyDialog::authorized() const\n{\n\treturn d->widget->m_authorizeCb->isChecked();\n}\n\nQString ContactAddedNotifyDialog::displayName() const\n{\n\treturn d->widget->m_displayNameEdit->text();\n}\n\nGroup *ContactAddedNotifyDialog::group() const\n{\n\tQString grpName=d->widget->m_groupList->currentText();\n\tif(grpName.isEmpty())\n\t\treturn Group::topLevel();\n\n\treturn ContactList::self()->findGroup( grpName );\n}\n\nMetaContact *ContactAddedNotifyDialog::addContact() const\n{\n\tif(!added() || !d->account)\n\t\treturn 0L;\n\n\tMetaContact *metacontact=d->account->addContact(d->contactId, displayName(), group());\n\tif(!metacontact)\n\t\treturn 0L;\n\n\tmetacontact->setKabcId(d->addressbookId);\n\n\treturn metacontact;\n}\n\nvoid ContactAddedNotifyDialog::slotAddresseeSelected( const KABC::Addressee & addr )\n{\n\tif ( !addr.isEmpty() )\n\t{\n\t\td->addressbookId = addr.uid();\n\t}\n}\n\nvoid ContactAddedNotifyDialog::slotInfoClicked()\n{\n\temit infoClicked(d->contactId);\n}\n\nvoid ContactAddedNotifyDialog::slotFinished()\n{\n\temit applyClicked(d->contactId);\n}\n\n\n\n} \/\/ namespace UI\n} \/\/ namespace Kopete\n#include \"contactaddednotifydialog.moc\"\n<commit_msg>We must delete it<commit_after>\/*\n Copyright (c) 2005 Olivier Goffart <ogoffart@kde.org>\n\n Kopete (c) 2005-2007 by the Kopete developers <kopete-devel@kde.org>\n\n *************************************************************************\n * *\n * This library is free software; you can redistribute it and\/or *\n * modify it under the terms of the GNU Lesser General Public *\n * License as published by the Free Software Foundation; either *\n * version 2 of the License, or (at your option) any later version. *\n * *\n *************************************************************************\n*\/\n\n#include \"contactaddednotifydialog.h\"\n\n\n#include <qlabel.h>\n#include <qcheckbox.h>\n#include <qapplication.h>\n\n#include <klocale.h>\n#include <kcombobox.h>\n#include <klineedit.h>\n#include <kpushbutton.h>\n#include <kiconloader.h>\n\n#include <kabc\/addressee.h>\n\n#include \"kopetegroup.h\"\n#include \"kopeteaccount.h\"\n#include \"kopeteuiglobal.h\"\n#include \"kopeteprotocol.h\"\n#include \"kopetecontactlist.h\"\n#include \"kopetemetacontact.h\"\n#include \"addressbooklinkwidget.h\"\n#include \"addressbookselectordialog.h\"\n#include \"ui_contactaddednotifywidget.h\"\n\nnamespace Kopete {\n\nnamespace UI {\n\nstruct ContactAddedNotifyDialog::Private\n{\n\tUi::ContactAddedNotifyWidget *widget;\n\tAccount *account;\n\tQString contactId;\n\tQString addressbookId;\n};\n\n\nContactAddedNotifyDialog::ContactAddedNotifyDialog(const QString& contactId,\n\t\tconst QString& contactNick, Kopete::Account *account, const HideWidgetOptions &hide)\n\t: KDialog( Global::mainWidget() ), d(new Private())\n{\n\tsetCaption( i18n(\"Someone Has Added You\") );\n\tsetButtons( KDialog::Ok | KDialog::Cancel );\n setAttribute( Qt::WA_DeleteOnClose );\n\n\td->widget=new Ui::ContactAddedNotifyWidget;\n\tQWidget* w = new QWidget(this);\n\td->widget->setupUi(w);\n\tsetMainWidget(w);\n\n\td->account=account;\n\td->contactId=contactId;\n\td->widget->m_label->setText(i18n(\"<qt><img src=\\\"kopete-account-icon:%1\\\" \/> The contact <b>%2<\/b> has added you to his\/her contact list. (Account %3)<\/qt>\",\n\t\t\tQString(QUrl::toPercentEncoding( account->protocol()->pluginId() )) + QString::fromLatin1(\":\")\n\t\t\t + QString(QUrl::toPercentEncoding( account->accountId() )) ,\n\t\t\t\t contactNick.isEmpty() ? contactId : contactNick + QString::fromLatin1(\" < \") + contactId + QString::fromLatin1(\" >\") ,\n\t\t\t\t account->accountLabel() \t) );\n\tif( hide & InfoButton)\n\t\td->widget->m_infoButton->hide() ;\n\tif( hide & AuthorizeCheckBox )\n\t{\n\t\td->widget->m_authorizeCb->hide();\n\t\td->widget->m_authorizeCb->setChecked(false);\n\t}\n\tif( hide & AddCheckBox )\n\t{\n\t\td->widget->m_addCb->hide();\n\t\td->widget->m_addCb->setChecked(false);\n\t}\n\tif( hide & AddGroupBox )\n\t\td->widget->m_contactInfoBox->hide();\n\n\t\/\/ Populate the groups list\n\tQListIterator<Group *> it(Kopete::ContactList::self()->groups());\n\twhile ( it.hasNext() )\n\t{\n\t\tGroup *g = it.next();\n\t\tQString groupname = g->displayName();\n\t\tif ( g->type() == Group::Normal && !groupname.isEmpty() )\n\t\t{\n\t\t\td->widget->m_groupList->addItem(groupname);\n\t\t}\n\t}\n\td->widget->m_groupList->setEditText(QString()); \/\/default to top-level\n\n\tconnect( d->widget->widAddresseeLink, SIGNAL( addresseeChanged( const KABC::Addressee& ) ), this, SLOT( slotAddresseeSelected( const KABC::Addressee& ) ) );\n\tconnect( d->widget->m_infoButton, SIGNAL( clicked() ), this, SLOT( slotInfoClicked() ) );\n\n\tconnect( this, SIGNAL(okClicked()) , this , SLOT(slotFinished()));\n\n}\n\n\nContactAddedNotifyDialog::~ContactAddedNotifyDialog()\n{\n\tdelete d->widget;\n\tdelete d;\n}\n\nbool ContactAddedNotifyDialog::added() const\n{\n\treturn d->widget->m_addCb->isChecked();\n}\n\nbool ContactAddedNotifyDialog::authorized() const\n{\n\treturn d->widget->m_authorizeCb->isChecked();\n}\n\nQString ContactAddedNotifyDialog::displayName() const\n{\n\treturn d->widget->m_displayNameEdit->text();\n}\n\nGroup *ContactAddedNotifyDialog::group() const\n{\n\tQString grpName=d->widget->m_groupList->currentText();\n\tif(grpName.isEmpty())\n\t\treturn Group::topLevel();\n\n\treturn ContactList::self()->findGroup( grpName );\n}\n\nMetaContact *ContactAddedNotifyDialog::addContact() const\n{\n\tif(!added() || !d->account)\n\t\treturn 0L;\n\n\tMetaContact *metacontact=d->account->addContact(d->contactId, displayName(), group());\n\tif(!metacontact)\n\t\treturn 0L;\n\n\tmetacontact->setKabcId(d->addressbookId);\n\n\treturn metacontact;\n}\n\nvoid ContactAddedNotifyDialog::slotAddresseeSelected( const KABC::Addressee & addr )\n{\n\tif ( !addr.isEmpty() )\n\t{\n\t\td->addressbookId = addr.uid();\n\t}\n}\n\nvoid ContactAddedNotifyDialog::slotInfoClicked()\n{\n\temit infoClicked(d->contactId);\n}\n\nvoid ContactAddedNotifyDialog::slotFinished()\n{\n\temit applyClicked(d->contactId);\n}\n\n\n\n} \/\/ namespace UI\n} \/\/ namespace Kopete\n#include \"contactaddednotifydialog.moc\"\n<|endoftext|>"} {"text":"<commit_before>\/** @file\n @brief Implementation for class that tracks and identifies LEDs.\n\n @date 2015\n\n @author\n Sensics, Inc.\n <http:\/\/sensics.com\/osvr>\n*\/\n\n\/\/ Copyright 2015 Sensics, Inc.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n\/\/ Internal Includes\n#include \"BeaconBasedPoseEstimator.h\"\n\n\/\/ Library\/third-party includes\n#include <osvr\/Util\/QuatlibInteropC.h>\n\n\/\/ Standard includes\n\/\/ - none\n\nnamespace osvr {\nnamespace vbtracker {\n\n \/\/ clang-format off\n \/\/ Default 3D locations for the beacons on an OSVR HDK face plate, in\n \/\/ millimeters\n const DoubleVecVec OsvrHdkLedLocations_SENSOR0 = {\n {-85, 3, 24.09},\n { -83.2, -14.01, 13.89 },\n { -47, 51, 24.09 },\n { 47, 51, 24.09 },\n { 86.6, 2.65, 24.09 },\n { 85.5, -14.31, 13.89 },\n { 85.2, 19.68, 13.89 },\n { 21, 51, 13.09 },\n { -21, 51, 13.09 },\n { -84.2, 19.99, 13.89 },\n { -60.41, 47.55, 44.6 },\n { -80.42, 20.48, 42.9 },\n { -82.01, 2.74, 42.4 },\n { -80.42, -14.99, 42.9 },\n { -60.41, -10.25, 48.1 },\n { -60.41, 15.75, 48.1 },\n { -30.41, 32.75, 50.5 },\n { -31.41, 47.34, 47 },\n { -0.41, -15.25, 51.3 },\n { -30.41, -27.25, 50.5 },\n { -60.44, -41.65, 45.1 },\n { -22.41, -41.65, 47.8 },\n { 21.59, -41.65, 47.8 },\n { 59.59, -41.65, 45.1 },\n { 79.63, -14.98, 42.9 },\n { 29.59, -27.25, 50.5 },\n { 81.19, 2.74, 42.4 },\n { 79.61, 20.48, 42.9 },\n { 59.59, 47.55, 44.6 },\n { 30.59, 47.55, 47 },\n { 29.59, 32.75, 50.5 },\n { -0.41, 20.75, 51.3 },\n { 59.59, 15.75, 48.1 },\n { 59.59, -10.25, 48.1 }\n };\n\n \/\/ Default 3D locations for the beacons on an OSVR HDK back plate, in\n \/\/ millimeters\n const DoubleVecVec OsvrHdkLedLocations_SENSOR1 = {\n {1, 23.8, 0},\n { 11, 5.8, 0 },\n { 9, -23.8, 0 },\n { 0, -8.8, 0 },\n { -9, -23.8, 0 },\n { -12, 5.8, 0 }\n };\n \/\/ clang-format on\n\n BeaconBasedPoseEstimator::BeaconBasedPoseEstimator(\n const DoubleVecVec &cameraMatrix, const std::vector<double> &distCoeffs,\n const DoubleVecVec &beacons) {\n SetBeacons(beacons);\n SetCameraMatrix(cameraMatrix);\n SetDistCoeffs(distCoeffs);\n m_gotPose = false;\n }\n\n bool BeaconBasedPoseEstimator::SetBeacons(const DoubleVecVec &beacons) {\n \/\/ Our existing pose won't match anymore.\n m_gotPose = false;\n\n for (int i = 0; i < beacons.size(); i++) {\n if (beacons[i].size() != 3) {\n m_beacons.clear();\n return false;\n }\n cv::Point3f p(static_cast<float>(beacons[i][0]),\n static_cast<float>(beacons[i][1]),\n static_cast<float>(beacons[i][2]));\n m_beacons.push_back(p);\n }\n\n return true;\n }\n\n bool BeaconBasedPoseEstimator::SetCameraMatrix(\n const DoubleVecVec &cameraMatrix) {\n \/\/ Our existing pose won't match anymore.\n m_gotPose = false;\n\n \/\/ Construct the camera matrix from the vectors we received.\n if (cameraMatrix.size() != 3) {\n return false;\n }\n for (size_t i = 0; i < cameraMatrix.size(); i++) {\n if (cameraMatrix[i].size() != 3) {\n return false;\n }\n }\n cv::Mat newCameraMatrix(static_cast<int>(cameraMatrix.size()),\n static_cast<int>(cameraMatrix[0].size()),\n CV_64F);\n for (int i = 0; i < cameraMatrix.size(); i++) {\n for (int j = 0; j < cameraMatrix[i].size(); j++) {\n newCameraMatrix.at<double>(i, j) = cameraMatrix[i][j];\n }\n }\n\n m_cameraMatrix = newCameraMatrix;\n \/\/ std::cout << \"XXX cameraMatrix =\" << std::endl << m_cameraMatrix\n \/\/ << std::endl;\n return true;\n }\n\n bool BeaconBasedPoseEstimator::SetDistCoeffs(\n const std::vector<double> &distCoeffs) {\n \/\/ Our existing pose won't match anymore.\n m_gotPose = false;\n\n \/\/ Construct the distortion matrix from the vectors we received.\n if (distCoeffs.size() < 5) {\n return false;\n }\n cv::Mat newDistCoeffs(static_cast<int>(distCoeffs.size()), 1, CV_64F);\n for (int i = 0; i < distCoeffs.size(); i++) {\n newDistCoeffs.at<double>(i, 0) = distCoeffs[i];\n }\n\n m_distCoeffs = newDistCoeffs;\n \/\/ std::cout << \"XXX distCoeffs =\" << std::endl << m_distCoeffs <<\n \/\/ std::endl;\n return true;\n }\n\n static const int OUTLIERS_PERMITTED = 2;\n \/\/\/ We want at least five corresponding points (this is somewhat arbitrary,\n \/\/\/ but must be at least 5 to allow for 2 outliers below).\n static const int MIN_OBJECT_POINTS = OUTLIERS_PERMITTED + 3;\n\n bool\n BeaconBasedPoseEstimator::EstimatePoseFromLeds(const LedGroup &leds,\n OSVR_PoseState &outPose) {\n auto ret = m_estimatePoseFromLeds(leds, outPose);\n m_gotPose = ret;\n return ret;\n }\n\n bool\n BeaconBasedPoseEstimator::m_estimatePoseFromLeds(const LedGroup &leds,\n OSVR_PoseState &outPose) {\n \/\/ We need to get a pair of matched vectors of points: 2D locations\n \/\/ with in the image and 3D locations in model space. There needs to\n \/\/ be a correspondence between the points in these vectors, such that\n \/\/ the ith element in one matches the ith element in the other. We\n \/\/ make these by looking up the locations of LEDs with known identifiers\n \/\/ and pushing both onto the vectors at the same time.\n\n std::vector<cv::Point3f> objectPoints;\n std::vector<cv::Point2f> imagePoints;\n auto const beaconsSize = m_beacons.size();\n for (auto const &led : leds) {\n if (!led.identified()) {\n continue;\n }\n auto id = led.getID();\n if (id < beaconsSize) {\n imagePoints.push_back(led.getLocation());\n objectPoints.push_back(m_beacons[id]);\n }\n }\n\n \/\/ Make sure we have enough points to do our estimation.\n if (objectPoints.size() < MIN_OBJECT_POINTS) {\n return false;\n }\n\n \/\/ Produce an estimate of the translation and rotation needed to take\n \/\/ points from model space into camera space. We allow for at most\n \/\/ OUTLIERS_PERMITTED outliers. Even in simulation data, we sometimes\n \/\/ find duplicate IDs for LEDs, indicating that we are getting\n \/\/ mis-identified ones sometimes.\n cv::solvePnPRansac(\n objectPoints, imagePoints, m_cameraMatrix, m_distCoeffs, m_rvec,\n m_tvec, false, 100, 8.0f,\n static_cast<int>(objectPoints.size() - OUTLIERS_PERMITTED));\n\n \/\/ std::cout << \"XXX tvec = \" << m_tvec << std::endl;\n \/\/ std::cout << \"XXX rvec = \" << m_rvec << std::endl;\n\n \/\/==========================================================================\n \/\/ Convert this into an OSVR representation of the transformation that\n \/\/ gives the pose of the HDK origin in the camera coordinate system,\n \/\/ switching units to meters and encoding the angle in a unit\n \/\/ quaternion.\n \/\/ The matrix described by rvec and tvec takes points in model space\n \/\/ (the space where the LEDs are defined, which is in mm away from an\n \/\/ implied origin) into a coordinate system where the center is at the\n \/\/ camera's origin, with X to the right, Y down, and Z in the direction\n \/\/ that the camera is facing (but still in the original units of mm):\n \/\/ |Xc| |r11 r12 r13 t1| |Xm|\n \/\/ |Yc| = |r21 r22 r23 t2|*|Ym|\n \/\/ |Zc| |r31 r32 r33 t3| |Zm|\n \/\/ |1 |\n \/\/ That is, it rotates into the camera coordinate system and then adds\n \/\/ the translation, which is in the camera coordinate system.\n \/\/ We want the tranformation that takes points in the coordinate system\n \/\/ of the tracker's \"source\" (the camera) and moves them into the\n \/\/ coordinate system of the tracker's \"sensor\" (the HDK), which is the\n \/\/ inverse of the transformation described above scaled to move from mm\n \/\/ to meters.\n\n \/\/ Compose the transform that we will invert, in original units.\n \/\/ We start by making a 3x3 rotation matrix out of the rvec, which\n \/\/ is done by a function that for some reason is named Rodrigues.\n cv::Mat rot;\n cv::Rodrigues(m_rvec, rot);\n\n \/\/ TODO: Replace this code with Eigen code.\n\n if (rot.type() != CV_64F) {\n return false;\n }\n\n \/\/ Get the forward transform\n q_xyz_quat_type forward;\n forward.xyz[Q_X] = m_tvec.at<double>(0);\n forward.xyz[Q_Y] = m_tvec.at<double>(1);\n forward.xyz[Q_Z] = m_tvec.at<double>(2);\n\n \/\/ Fill in a 4x4 matrix that starts as the identity\n \/\/ matrix with the 3x3 part from the rotation matrix.\n q_matrix_type rot4x4;\n for (int i = 0; i < 4; i++) {\n for (int j = 0; j < 4; j++) {\n if ((i < 3) && (j < 3)) {\n rot4x4[i][j] = rot.at<double>(i, j);\n } else {\n if (i == j) {\n rot4x4[i][j] = 1;\n } else {\n rot4x4[i][j] = 0;\n }\n }\n }\n }\n q_from_row_matrix(forward.quat, rot4x4);\n\n \/\/ Invert it.\n q_xyz_quat_type inverse;\n q_xyz_quat_invert(&inverse, &forward);\n\n \/\/ Scale to meters\n q_vec_scale(inverse.xyz, 1e-3, inverse.xyz);\n\n \/\/==============================================================\n \/\/ Put into OSVR format.\n osvrPose3FromQuatlib(&outPose, &inverse);\n return true;\n }\n\n bool BeaconBasedPoseEstimator::ProjectBeaconsToImage(\n std::vector<cv::Point2f> &out) {\n \/\/ Make sure we have a pose. Otherwise, we can't do anything.\n if (!m_gotPose) {\n return false;\n }\n\n cv::projectPoints(m_beacons, m_rvec, m_tvec, m_cameraMatrix,\n m_distCoeffs, out);\n return true;\n }\n\n} \/\/ End namespace vbtracker\n} \/\/ End namespace osvr\n<commit_msg>Removing the transformation inversion in the original code, so we produce estimates of the sensor in camera space. We still convert to meters. Issue: The Y axis is inverted; we seem to be in a left-handed space with OpenCV.<commit_after>\/** @file\n @brief Implementation for class that tracks and identifies LEDs.\n\n @date 2015\n\n @author\n Sensics, Inc.\n <http:\/\/sensics.com\/osvr>\n*\/\n\n\/\/ Copyright 2015 Sensics, Inc.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n\/\/ Internal Includes\n#include \"BeaconBasedPoseEstimator.h\"\n\n\/\/ Library\/third-party includes\n#include <osvr\/Util\/QuatlibInteropC.h>\n\n\/\/ Standard includes\n\/\/ - none\n\nnamespace osvr {\nnamespace vbtracker {\n\n \/\/ clang-format off\n \/\/ Default 3D locations for the beacons on an OSVR HDK face plate, in\n \/\/ millimeters\n const DoubleVecVec OsvrHdkLedLocations_SENSOR0 = {\n {-85, 3, 24.09},\n { -83.2, -14.01, 13.89 },\n { -47, 51, 24.09 },\n { 47, 51, 24.09 },\n { 86.6, 2.65, 24.09 },\n { 85.5, -14.31, 13.89 },\n { 85.2, 19.68, 13.89 },\n { 21, 51, 13.09 },\n { -21, 51, 13.09 },\n { -84.2, 19.99, 13.89 },\n { -60.41, 47.55, 44.6 },\n { -80.42, 20.48, 42.9 },\n { -82.01, 2.74, 42.4 },\n { -80.42, -14.99, 42.9 },\n { -60.41, -10.25, 48.1 },\n { -60.41, 15.75, 48.1 },\n { -30.41, 32.75, 50.5 },\n { -31.41, 47.34, 47 },\n { -0.41, -15.25, 51.3 },\n { -30.41, -27.25, 50.5 },\n { -60.44, -41.65, 45.1 },\n { -22.41, -41.65, 47.8 },\n { 21.59, -41.65, 47.8 },\n { 59.59, -41.65, 45.1 },\n { 79.63, -14.98, 42.9 },\n { 29.59, -27.25, 50.5 },\n { 81.19, 2.74, 42.4 },\n { 79.61, 20.48, 42.9 },\n { 59.59, 47.55, 44.6 },\n { 30.59, 47.55, 47 },\n { 29.59, 32.75, 50.5 },\n { -0.41, 20.75, 51.3 },\n { 59.59, 15.75, 48.1 },\n { 59.59, -10.25, 48.1 }\n };\n\n \/\/ Default 3D locations for the beacons on an OSVR HDK back plate, in\n \/\/ millimeters\n const DoubleVecVec OsvrHdkLedLocations_SENSOR1 = {\n {1, 23.8, 0},\n { 11, 5.8, 0 },\n { 9, -23.8, 0 },\n { 0, -8.8, 0 },\n { -9, -23.8, 0 },\n { -12, 5.8, 0 }\n };\n \/\/ clang-format on\n\n BeaconBasedPoseEstimator::BeaconBasedPoseEstimator(\n const DoubleVecVec &cameraMatrix, const std::vector<double> &distCoeffs,\n const DoubleVecVec &beacons) {\n SetBeacons(beacons);\n SetCameraMatrix(cameraMatrix);\n SetDistCoeffs(distCoeffs);\n m_gotPose = false;\n }\n\n bool BeaconBasedPoseEstimator::SetBeacons(const DoubleVecVec &beacons) {\n \/\/ Our existing pose won't match anymore.\n m_gotPose = false;\n\n for (int i = 0; i < beacons.size(); i++) {\n if (beacons[i].size() != 3) {\n m_beacons.clear();\n return false;\n }\n cv::Point3f p(static_cast<float>(beacons[i][0]),\n static_cast<float>(beacons[i][1]),\n static_cast<float>(beacons[i][2]));\n m_beacons.push_back(p);\n }\n\n return true;\n }\n\n bool BeaconBasedPoseEstimator::SetCameraMatrix(\n const DoubleVecVec &cameraMatrix) {\n \/\/ Our existing pose won't match anymore.\n m_gotPose = false;\n\n \/\/ Construct the camera matrix from the vectors we received.\n if (cameraMatrix.size() != 3) {\n return false;\n }\n for (size_t i = 0; i < cameraMatrix.size(); i++) {\n if (cameraMatrix[i].size() != 3) {\n return false;\n }\n }\n cv::Mat newCameraMatrix(static_cast<int>(cameraMatrix.size()),\n static_cast<int>(cameraMatrix[0].size()),\n CV_64F);\n for (int i = 0; i < cameraMatrix.size(); i++) {\n for (int j = 0; j < cameraMatrix[i].size(); j++) {\n newCameraMatrix.at<double>(i, j) = cameraMatrix[i][j];\n }\n }\n\n m_cameraMatrix = newCameraMatrix;\n \/\/ std::cout << \"XXX cameraMatrix =\" << std::endl << m_cameraMatrix\n \/\/ << std::endl;\n return true;\n }\n\n bool BeaconBasedPoseEstimator::SetDistCoeffs(\n const std::vector<double> &distCoeffs) {\n \/\/ Our existing pose won't match anymore.\n m_gotPose = false;\n\n \/\/ Construct the distortion matrix from the vectors we received.\n if (distCoeffs.size() < 5) {\n return false;\n }\n cv::Mat newDistCoeffs(static_cast<int>(distCoeffs.size()), 1, CV_64F);\n for (int i = 0; i < distCoeffs.size(); i++) {\n newDistCoeffs.at<double>(i, 0) = distCoeffs[i];\n }\n\n m_distCoeffs = newDistCoeffs;\n \/\/ std::cout << \"XXX distCoeffs =\" << std::endl << m_distCoeffs <<\n \/\/ std::endl;\n return true;\n }\n\n static const int OUTLIERS_PERMITTED = 2;\n \/\/\/ We want at least five corresponding points (this is somewhat arbitrary,\n \/\/\/ but must be at least 5 to allow for 2 outliers below).\n static const int MIN_OBJECT_POINTS = OUTLIERS_PERMITTED + 3;\n\n bool\n BeaconBasedPoseEstimator::EstimatePoseFromLeds(const LedGroup &leds,\n OSVR_PoseState &outPose) {\n auto ret = m_estimatePoseFromLeds(leds, outPose);\n m_gotPose = ret;\n return ret;\n }\n\n bool\n BeaconBasedPoseEstimator::m_estimatePoseFromLeds(const LedGroup &leds,\n OSVR_PoseState &outPose) {\n \/\/ We need to get a pair of matched vectors of points: 2D locations\n \/\/ with in the image and 3D locations in model space. There needs to\n \/\/ be a correspondence between the points in these vectors, such that\n \/\/ the ith element in one matches the ith element in the other. We\n \/\/ make these by looking up the locations of LEDs with known identifiers\n \/\/ and pushing both onto the vectors at the same time.\n\n std::vector<cv::Point3f> objectPoints;\n std::vector<cv::Point2f> imagePoints;\n auto const beaconsSize = m_beacons.size();\n for (auto const &led : leds) {\n if (!led.identified()) {\n continue;\n }\n auto id = led.getID();\n if (id < beaconsSize) {\n imagePoints.push_back(led.getLocation());\n objectPoints.push_back(m_beacons[id]);\n }\n }\n\n \/\/ Make sure we have enough points to do our estimation.\n if (objectPoints.size() < MIN_OBJECT_POINTS) {\n return false;\n }\n\n \/\/ Produce an estimate of the translation and rotation needed to take\n \/\/ points from model space into camera space. We allow for at most\n \/\/ OUTLIERS_PERMITTED outliers. Even in simulation data, we sometimes\n \/\/ find duplicate IDs for LEDs, indicating that we are getting\n \/\/ mis-identified ones sometimes.\n cv::solvePnPRansac(\n objectPoints, imagePoints, m_cameraMatrix, m_distCoeffs, m_rvec,\n m_tvec, false, 100, 8.0f,\n static_cast<int>(objectPoints.size() - OUTLIERS_PERMITTED));\n\n \/\/ std::cout << \"XXX tvec = \" << m_tvec << std::endl;\n \/\/ std::cout << \"XXX rvec = \" << m_rvec << std::endl;\n\n \/\/==========================================================================\n \/\/ Convert this into an OSVR representation of the transformation that\n \/\/ gives the pose of the HDK origin in the camera coordinate system,\n \/\/ switching units to meters and encoding the angle in a unit\n \/\/ quaternion.\n \/\/ The matrix described by rvec and tvec takes points in model space\n \/\/ (the space where the LEDs are defined, which is in mm away from an\n \/\/ implied origin) into a coordinate system where the center is at the\n \/\/ camera's origin, with X to the right, Y down, and Z in the direction\n \/\/ that the camera is facing (but still in the original units of mm):\n \/\/ |Xc| |r11 r12 r13 t1| |Xm|\n \/\/ |Yc| = |r21 r22 r23 t2|*|Ym|\n \/\/ |Zc| |r31 r32 r33 t3| |Zm|\n \/\/ |1 |\n \/\/ That is, it rotates into the camera coordinate system and then adds\n \/\/ the translation, which is in the camera coordinate system.\n \/\/ This is the transformation we want, since it reports the sensor's\n \/\/ position and orientation in camera space, except that we want to convert\n \/\/ the units into meters and the orientation into a Quaternion.\n\n \/\/ Compose the transform in original units.\n \/\/ We start by making a 3x3 rotation matrix out of the rvec, which\n \/\/ is done by a function that for some reason is named Rodrigues.\n cv::Mat rot;\n cv::Rodrigues(m_rvec, rot);\n\n \/\/ TODO: Replace this code with Eigen code.\n\n if (rot.type() != CV_64F) {\n return false;\n }\n\n \/\/ Get the forward transform\n q_xyz_quat_type forward;\n forward.xyz[Q_X] = m_tvec.at<double>(0);\n forward.xyz[Q_Y] = m_tvec.at<double>(1);\n forward.xyz[Q_Z] = m_tvec.at<double>(2);\n\n \/\/ Fill in a 4x4 matrix that starts as the identity\n \/\/ matrix with the 3x3 part from the rotation matrix.\n q_matrix_type rot4x4;\n for (int i = 0; i < 4; i++) {\n for (int j = 0; j < 4; j++) {\n if ((i < 3) && (j < 3)) {\n rot4x4[i][j] = rot.at<double>(i, j);\n } else {\n if (i == j) {\n rot4x4[i][j] = 1;\n } else {\n rot4x4[i][j] = 0;\n }\n }\n }\n }\n q_from_row_matrix(forward.quat, rot4x4);\n\n \/\/ Scale to meters\n q_vec_scale(forward.xyz, 1e-3, forward.xyz);\n\n \/\/==============================================================\n \/\/ Put into OSVR format.\n osvrPose3FromQuatlib(&outPose, &forward);\n return true;\n }\n\n bool BeaconBasedPoseEstimator::ProjectBeaconsToImage(\n std::vector<cv::Point2f> &out) {\n \/\/ Make sure we have a pose. Otherwise, we can't do anything.\n if (!m_gotPose) {\n return false;\n }\n\n cv::projectPoints(m_beacons, m_rvec, m_tvec, m_cameraMatrix,\n m_distCoeffs, out);\n return true;\n }\n\n} \/\/ End namespace vbtracker\n} \/\/ End namespace osvr\n<|endoftext|>"} {"text":"<commit_before>\/* Copyright (C) 2005-2011 Fabio Riccardi *\/\n\n\/\/ standard\n#include <cstdio>\n#include <sys\/types.h>\n#ifdef DEBUG\n#include <iostream>\n#endif\n\nextern \"C\" {\n# include <jpeglib.h>\n}\n\n\/\/ local\n#include \"LC_JNIUtils.h\"\n#include \"LC_JPEGException.h\"\n#include \"LC_JPEGReader.h\"\n#include \"util.h\"\n\n#define MAX(a,b) ( (a) > (b) ? (a) : (b) )\n\nusing namespace std;\n\n\/**\n * Construct an LC_JPEGReader.\n *\/\nLC_JPEGReader::LC_JPEGReader() {\n m_file = 0;\n m_src = 0;\n m_startedDecompress = false;\n\n jpeg_create_decompress( &cinfo );\n \/\/\n \/\/ Change things so we're handling errors in our own way.\n \/\/\n cinfo.err = jpeg_std_error( &m_errMgr );\n m_errMgr.error_exit = &LC_error_exit;\n}\n\n\/**\n * Destruct an LC_JPEGReader.\n *\/\nLC_JPEGReader::~LC_JPEGReader() {\n#ifdef DEBUG\n cerr << \"~LC_JPEGReader()\" << endl;\n#endif\n try {\n if ( m_startedDecompress )\n jpeg_finish_decompress( &cinfo );\n jpeg_destroy_decompress( &cinfo );\n }\n catch ( LC_JPEGException const& ) {\n \/\/\n \/\/ We will have thrown a Java exception by this point, but we want to\n \/\/ finish our clean-up, so keep going.\n \/\/\n }\n if ( m_file )\n ::fclose( m_file );\n delete m_src;\n}\n\n\/**\n * Set the width, height, and colorsPerPixel fields in the LCJPEGReader Java\n * object.\n *\/\nvoid LC_JPEGReader::setFields( JNIEnv *env, jobject jLCJPEGReader ) {\n#ifdef DEBUG\n cerr << \"LC_JPEGReader::setFields(): width=\" << cinfo.output_width\n << \", height=\" << cinfo.output_height\n << \", colorsPerPixel=\" << cinfo.output_components\n << \", colorSpace=\" << cinfo.out_color_space\n << endl;\n#endif\n LC_setIntField( env, jLCJPEGReader, \"m_width\" , cinfo.output_width );\n LC_setIntField( env, jLCJPEGReader, \"m_height\", cinfo.output_height );\n LC_setIntField(\n env, jLCJPEGReader, \"m_colorsPerPixel\", cinfo.output_components\n );\n LC_setIntField( env, jLCJPEGReader, \"m_colorSpace\", cinfo.out_color_space );\n}\n\n\/**\n * Read the JPEG header and start decompression.\n *\/\nvoid LC_JPEGReader::start_decompress( int maxWidth, int maxHeight ) {\n jpeg_read_header( &cinfo, TRUE );\n\n if ( maxWidth > 0 && maxHeight > 0 ) {\n jpeg_calc_output_dimensions( &cinfo );\n\n int scale =\n MAX( cinfo.output_width\/maxWidth, cinfo.output_height\/maxHeight );\n\n if ( scale >= 8 )\n scale = 8;\n else if ( scale >= 4 )\n scale = 4;\n else if ( scale >= 2 )\n scale = 2;\n else\n scale = 1;\n\n if ( scale != 1 ) {\n cinfo.scale_num = 1;\n cinfo.scale_denom = scale;\n jpeg_calc_output_dimensions( &cinfo );\n }\n }\n jpeg_start_decompress( &cinfo );\n m_startedDecompress = true;\n}\n\n\/* vim:set et sw=4 ts=4: *\/\n<commit_msg>Avoid huge memory usage on progressive JPEGs<commit_after>\/* Copyright (C) 2005-2011 Fabio Riccardi *\/\n\n\/\/ standard\n#include <cstdio>\n#include <sys\/types.h>\n#ifdef DEBUG\n#include <iostream>\n#endif\n\nextern \"C\" {\n# include <jpeglib.h>\n}\n\n\/\/ local\n#include \"LC_JNIUtils.h\"\n#include \"LC_JPEGException.h\"\n#include \"LC_JPEGReader.h\"\n#include \"util.h\"\n\n#define MAX(a,b) ( (a) > (b) ? (a) : (b) )\n\nusing namespace std;\n\n\/**\n * Construct an LC_JPEGReader.\n *\/\nLC_JPEGReader::LC_JPEGReader() {\n m_file = 0;\n m_src = 0;\n m_startedDecompress = false;\n\n jpeg_create_decompress( &cinfo );\n \/\/\n \/\/ Change things so we're handling errors in our own way.\n \/\/\n cinfo.err = jpeg_std_error( &m_errMgr );\n m_errMgr.error_exit = &LC_error_exit;\n}\n\n\/**\n * Destruct an LC_JPEGReader.\n *\/\nLC_JPEGReader::~LC_JPEGReader() {\n#ifdef DEBUG\n cerr << \"~LC_JPEGReader()\" << endl;\n#endif\n if ( m_startedDecompress ) {\n try {\n jpeg_finish_decompress( &cinfo );\n }\n catch ( LC_JPEGException const& ) {\n \/\/\n \/\/ We will have thrown a Java exception by this point, but we want to\n \/\/ finish our clean-up, so keep going.\n \/\/\n }\n }\n jpeg_destroy_decompress( &cinfo );\n if ( m_file )\n ::fclose( m_file );\n delete m_src;\n}\n\n\/**\n * Set the width, height, and colorsPerPixel fields in the LCJPEGReader Java\n * object.\n *\/\nvoid LC_JPEGReader::setFields( JNIEnv *env, jobject jLCJPEGReader ) {\n#ifdef DEBUG\n cerr << \"LC_JPEGReader::setFields(): width=\" << cinfo.output_width\n << \", height=\" << cinfo.output_height\n << \", colorsPerPixel=\" << cinfo.output_components\n << \", colorSpace=\" << cinfo.out_color_space\n << endl;\n#endif\n LC_setIntField( env, jLCJPEGReader, \"m_width\" , cinfo.output_width );\n LC_setIntField( env, jLCJPEGReader, \"m_height\", cinfo.output_height );\n LC_setIntField(\n env, jLCJPEGReader, \"m_colorsPerPixel\", cinfo.output_components\n );\n LC_setIntField( env, jLCJPEGReader, \"m_colorSpace\", cinfo.out_color_space );\n}\n\n\/**\n * Read the JPEG header and start decompression.\n *\/\nvoid LC_JPEGReader::start_decompress( int maxWidth, int maxHeight ) {\n jpeg_read_header( &cinfo, TRUE );\n\n if ( maxWidth > 0 && maxHeight > 0 ) {\n jpeg_calc_output_dimensions( &cinfo );\n\n int scale =\n MAX( cinfo.output_width\/maxWidth, cinfo.output_height\/maxHeight );\n\n if ( scale >= 8 )\n scale = 8;\n else if ( scale >= 4 )\n scale = 4;\n else if ( scale >= 2 )\n scale = 2;\n else\n scale = 1;\n\n if ( scale != 1 ) {\n cinfo.scale_num = 1;\n cinfo.scale_denom = scale;\n jpeg_calc_output_dimensions( &cinfo );\n }\n }\n jpeg_start_decompress( &cinfo );\n m_startedDecompress = true;\n}\n\n\/* vim:set et sw=4 ts=4: *\/\n<|endoftext|>"} {"text":"<commit_before>\n#include \"astutil.h\"\n#include \"bb.h\"\n#include \"expr.h\"\n#include \"optimizations.h\"\n#include \"passes.h\"\n#include \"stmt.h\"\n#include \"view.h\"\n\n\n\/\/\n\/\/ Static function declarations.\n\/\/\nstatic bool deadBlockElimination(FnSymbol* fn);\n\/\/ static void deadGotoElimination(FnSymbol* fn);\n\n\/\/ Static variables.\nstatic unsigned deadBlockCount;\n\n\n\/\/\n\/\/ Removes local variables that are only targets for moves, but are\n\/\/ never used anywhere.\n\/\/\nstatic bool isDeadVariable(Symbol* var,\n Map<Symbol*,Vec<SymExpr*>*>& defMap,\n Map<Symbol*,Vec<SymExpr*>*>& useMap) {\n if (var->type->symbol->hasFlag(FLAG_REF)) {\n Vec<SymExpr*>* uses = useMap.get(var);\n Vec<SymExpr*>* defs = defMap.get(var);\n return (!uses || uses->n == 0) && (!defs || defs->n <= 1);\n } else {\n Vec<SymExpr*>* uses = useMap.get(var);\n return !uses || uses->n == 0;\n }\n}\n\nvoid deadVariableElimination(FnSymbol* fn) {\n Vec<Symbol*> symSet;\n Vec<SymExpr*> symExprs;\n collectSymbolSetSymExprVec(fn, symSet, symExprs);\n\n Map<Symbol*,Vec<SymExpr*>*> defMap;\n Map<Symbol*,Vec<SymExpr*>*> useMap;\n buildDefUseMaps(symSet, symExprs, defMap, useMap);\n\n forv_Vec(Symbol, sym, symSet) if (isVarSymbol(sym)) {\n if (isDeadVariable(sym, defMap, useMap)) {\n for_defs(se, defMap, sym) {\n CallExpr* call = toCallExpr(se->parentExpr);\n INT_ASSERT(call && call->isPrimitive(PRIM_MOVE));\n Expr* rhs = call->get(2)->remove();\n if (!isSymExpr(rhs))\n call->replace(rhs);\n else\n call->remove();\n }\n sym->defPoint->remove();\n }\n }\n\n freeDefUseMaps(defMap, useMap);\n}\n\n\/\/\n\/\/ Removes expression statements that have no effect.\n\/\/\nvoid deadExpressionElimination(FnSymbol* fn) {\n Vec<BaseAST*> asts;\n collect_asts(fn, asts);\n forv_Vec(BaseAST, ast, asts) {\n Expr *expr = toExpr(ast);\n if (expr && expr->parentExpr == NULL) \/\/ expression already removed\n continue;\n if (SymExpr* expr = toSymExpr(ast)) {\n if (expr == expr->getStmtExpr())\n expr->remove();\n } else if (CallExpr* expr = toCallExpr(ast)) {\n if (expr->isPrimitive(PRIM_CAST) ||\n expr->isPrimitive(PRIM_GET_MEMBER_VALUE) ||\n expr->isPrimitive(PRIM_GET_MEMBER) ||\n expr->isPrimitive(PRIM_GET_REF) ||\n expr->isPrimitive(PRIM_SET_REF))\n if (expr == expr->getStmtExpr())\n expr->remove();\n if (expr->isPrimitive(PRIM_MOVE))\n if (SymExpr* lhs = toSymExpr(expr->get(1)))\n if (SymExpr* rhs = toSymExpr(expr->get(2)))\n if (lhs->var == rhs->var)\n expr->remove();\n } else if (CondStmt* cond = toCondStmt(ast)) {\n cond->fold_cond_stmt();\n }\n }\n}\n\nvoid deadCodeElimination(FnSymbol* fn)\n{\n buildBasicBlocks(fn);\n\n Map<SymExpr*,Vec<SymExpr*>*> DU;\n Map<SymExpr*,Vec<SymExpr*>*> UD;\n buildDefUseChains(fn, DU, UD);\n\n Map<Expr*,Expr*> exprMap;\n Vec<Expr*> liveCode;\n Vec<Expr*> workSet;\n forv_Vec(BasicBlock, bb, *fn->basicBlocks) {\n forv_Vec(Expr, expr, bb->exprs) {\n bool essential = false;\n Vec<BaseAST*> asts;\n collect_asts(expr, asts);\n forv_Vec(BaseAST, ast, asts) {\n if (CallExpr* call = toCallExpr(ast)) {\n \/\/ mark function calls and essential primitives as essential\n if (call->isResolved() ||\n (call->primitive && call->primitive->isEssential))\n essential = true;\n \/\/ mark assignments to global variables as essential\n if (call->isPrimitive(PRIM_MOVE))\n if (SymExpr* se = toSymExpr(call->get(1)))\n if (!DU.get(se) || \/\/ DU chain only contains locals\n !se->var->type->refType) \/\/ reference issue\n essential = true;\n }\n if (Expr* sub = toExpr(ast)) {\n exprMap.put(sub, expr);\n if (BlockStmt* block = toBlockStmt(sub->parentExpr))\n if (block->blockInfo == sub)\n essential = true;\n if (CondStmt* cond = toCondStmt(sub->parentExpr))\n if (cond->condExpr == sub)\n essential = true;\n }\n }\n if (essential) {\n liveCode.set_add(expr);\n workSet.add(expr);\n }\n }\n }\n\n forv_Vec(Expr, expr, workSet) {\n Vec<SymExpr*> symExprs;\n collectSymExprs(expr, symExprs);\n forv_Vec(SymExpr, se, symExprs) {\n if (Vec<SymExpr*>* defs = UD.get(se)) {\n forv_Vec(SymExpr, def, *defs) {\n Expr* expr = exprMap.get(def);\n if (!liveCode.set_in(expr)) {\n liveCode.set_add(expr);\n workSet.add(expr);\n }\n }\n }\n }\n }\n\n \/\/ This removes dead expressions from each block.\n forv_Vec(BasicBlock, bb, *fn->basicBlocks) {\n forv_Vec(Expr, expr, bb->exprs) {\n if (isSymExpr(expr) || isCallExpr(expr))\n if (!liveCode.set_in(expr))\n expr->remove();\n }\n }\n\n freeDefUseChains(DU, UD);\n}\n\nvoid deadCodeElimination() {\n if (!fNoDeadCodeElimination) {\n deadBlockCount = 0;\n forv_Vec(FnSymbol, fn, gFnSymbols) {\n bool change = false;\n do {\n change = deadBlockElimination(fn);\n } while (change);\n\/\/ deadGotoElimination(fn);\n deadCodeElimination(fn);\n deadVariableElimination(fn);\n deadExpressionElimination(fn);\n }\n\n if (fReportDeadBlocks)\n printf(\"\\tRemoved %d dead blocks.\\n\", deadBlockCount);\n }\n}\n\n\/\/ Look for and remove unreachable blocks.\nstatic bool deadBlockElimination(FnSymbol* fn)\n{\n \/\/ We need the basic block information to be right here.\n buildBasicBlocks(fn);\n\n bool change = false;\n forv_Vec(BasicBlock, bb, *fn->basicBlocks)\n {\n \/\/ Ignore the first block.\n if (bb == fn->basicBlocks->v[0])\n continue;\n\n \/\/ If this block has no predecessors, then it is dead.\n if (bb->ins.count() == 0)\n {\n if (bb->exprs.n > 0)\n {\n change = true;\n ++deadBlockCount;\n\n \/\/ Remove all of its expressions.\n forv_Vec(Expr, expr, bb->exprs)\n {\n if (! expr->parentExpr)\n continue;\t\/\/ This node is no longer in the tree.\n\n CondStmt* cond = toCondStmt(expr->parentExpr);\n if (cond && cond->condExpr == expr)\n \/\/ If expr is the condition expression in an if statement,\n \/\/ then remove the entire if.\n cond->remove();\n else\n expr->remove();\n }\n }\n\n \/\/ Get more out of one pass by removing this BB from the predecessor\n \/\/ lists of its successors.\n forv_Vec(BasicBlock, succ, bb->outs)\n succ->ins.set_remove(bb); \n\n \/\/ We leave the \"dead\" bb structure in place.\n \/\/ The next time we construct basic blocks for this fn, it should be gone.\n }\n }\n\n return change;\n}\n\n\/\/ Look for pointless gotos and remove them.\n\/\/ Probably the best way to do this is to scan the AST and remove gotos\n\/\/ whose target labels follow immediately.\n#if 0\nstatic void deadGotoElimination(FnSymbol* fn)\n{\n \/\/ We recompute basic blocks because deadBlockElimination may cause them\n \/\/ to be out of sequence.\n buildBasicBlocks(fn);\n forv_Vec(BasicBlock, bb, *fn->basicBlocks)\n {\n \/\/ Get the last expression in the block as a goto.\n int last = bb->exprs.length() - 1;\n if (last < 0)\n continue;\n\n Expr* e = bb->exprs.v[last];\n GotoStmt* s = toGotoStmt(e);\n if (!s)\n continue;\n\n \/\/ If there is only one successor to this block and it is the next block,\n \/\/ then the goto must point to it and is therefore pointless [sts].\n \/\/ This test should be more foolproof using the structure of the AST.\n if (bb->outs.n == 1 && bb->outs.v[0]->id == bb->id + 1)\n e->remove();\n }\n}\n#endif\n<commit_msg>Remove a TAB.<commit_after>\n#include \"astutil.h\"\n#include \"bb.h\"\n#include \"expr.h\"\n#include \"optimizations.h\"\n#include \"passes.h\"\n#include \"stmt.h\"\n#include \"view.h\"\n\n\n\/\/\n\/\/ Static function declarations.\n\/\/\nstatic bool deadBlockElimination(FnSymbol* fn);\n\/\/ static void deadGotoElimination(FnSymbol* fn);\n\n\/\/ Static variables.\nstatic unsigned deadBlockCount;\n\n\n\/\/\n\/\/ Removes local variables that are only targets for moves, but are\n\/\/ never used anywhere.\n\/\/\nstatic bool isDeadVariable(Symbol* var,\n Map<Symbol*,Vec<SymExpr*>*>& defMap,\n Map<Symbol*,Vec<SymExpr*>*>& useMap) {\n if (var->type->symbol->hasFlag(FLAG_REF)) {\n Vec<SymExpr*>* uses = useMap.get(var);\n Vec<SymExpr*>* defs = defMap.get(var);\n return (!uses || uses->n == 0) && (!defs || defs->n <= 1);\n } else {\n Vec<SymExpr*>* uses = useMap.get(var);\n return !uses || uses->n == 0;\n }\n}\n\nvoid deadVariableElimination(FnSymbol* fn) {\n Vec<Symbol*> symSet;\n Vec<SymExpr*> symExprs;\n collectSymbolSetSymExprVec(fn, symSet, symExprs);\n\n Map<Symbol*,Vec<SymExpr*>*> defMap;\n Map<Symbol*,Vec<SymExpr*>*> useMap;\n buildDefUseMaps(symSet, symExprs, defMap, useMap);\n\n forv_Vec(Symbol, sym, symSet) if (isVarSymbol(sym)) {\n if (isDeadVariable(sym, defMap, useMap)) {\n for_defs(se, defMap, sym) {\n CallExpr* call = toCallExpr(se->parentExpr);\n INT_ASSERT(call && call->isPrimitive(PRIM_MOVE));\n Expr* rhs = call->get(2)->remove();\n if (!isSymExpr(rhs))\n call->replace(rhs);\n else\n call->remove();\n }\n sym->defPoint->remove();\n }\n }\n\n freeDefUseMaps(defMap, useMap);\n}\n\n\/\/\n\/\/ Removes expression statements that have no effect.\n\/\/\nvoid deadExpressionElimination(FnSymbol* fn) {\n Vec<BaseAST*> asts;\n collect_asts(fn, asts);\n forv_Vec(BaseAST, ast, asts) {\n Expr *expr = toExpr(ast);\n if (expr && expr->parentExpr == NULL) \/\/ expression already removed\n continue;\n if (SymExpr* expr = toSymExpr(ast)) {\n if (expr == expr->getStmtExpr())\n expr->remove();\n } else if (CallExpr* expr = toCallExpr(ast)) {\n if (expr->isPrimitive(PRIM_CAST) ||\n expr->isPrimitive(PRIM_GET_MEMBER_VALUE) ||\n expr->isPrimitive(PRIM_GET_MEMBER) ||\n expr->isPrimitive(PRIM_GET_REF) ||\n expr->isPrimitive(PRIM_SET_REF))\n if (expr == expr->getStmtExpr())\n expr->remove();\n if (expr->isPrimitive(PRIM_MOVE))\n if (SymExpr* lhs = toSymExpr(expr->get(1)))\n if (SymExpr* rhs = toSymExpr(expr->get(2)))\n if (lhs->var == rhs->var)\n expr->remove();\n } else if (CondStmt* cond = toCondStmt(ast)) {\n cond->fold_cond_stmt();\n }\n }\n}\n\nvoid deadCodeElimination(FnSymbol* fn)\n{\n buildBasicBlocks(fn);\n\n Map<SymExpr*,Vec<SymExpr*>*> DU;\n Map<SymExpr*,Vec<SymExpr*>*> UD;\n buildDefUseChains(fn, DU, UD);\n\n Map<Expr*,Expr*> exprMap;\n Vec<Expr*> liveCode;\n Vec<Expr*> workSet;\n forv_Vec(BasicBlock, bb, *fn->basicBlocks) {\n forv_Vec(Expr, expr, bb->exprs) {\n bool essential = false;\n Vec<BaseAST*> asts;\n collect_asts(expr, asts);\n forv_Vec(BaseAST, ast, asts) {\n if (CallExpr* call = toCallExpr(ast)) {\n \/\/ mark function calls and essential primitives as essential\n if (call->isResolved() ||\n (call->primitive && call->primitive->isEssential))\n essential = true;\n \/\/ mark assignments to global variables as essential\n if (call->isPrimitive(PRIM_MOVE))\n if (SymExpr* se = toSymExpr(call->get(1)))\n if (!DU.get(se) || \/\/ DU chain only contains locals\n !se->var->type->refType) \/\/ reference issue\n essential = true;\n }\n if (Expr* sub = toExpr(ast)) {\n exprMap.put(sub, expr);\n if (BlockStmt* block = toBlockStmt(sub->parentExpr))\n if (block->blockInfo == sub)\n essential = true;\n if (CondStmt* cond = toCondStmt(sub->parentExpr))\n if (cond->condExpr == sub)\n essential = true;\n }\n }\n if (essential) {\n liveCode.set_add(expr);\n workSet.add(expr);\n }\n }\n }\n\n forv_Vec(Expr, expr, workSet) {\n Vec<SymExpr*> symExprs;\n collectSymExprs(expr, symExprs);\n forv_Vec(SymExpr, se, symExprs) {\n if (Vec<SymExpr*>* defs = UD.get(se)) {\n forv_Vec(SymExpr, def, *defs) {\n Expr* expr = exprMap.get(def);\n if (!liveCode.set_in(expr)) {\n liveCode.set_add(expr);\n workSet.add(expr);\n }\n }\n }\n }\n }\n\n \/\/ This removes dead expressions from each block.\n forv_Vec(BasicBlock, bb, *fn->basicBlocks) {\n forv_Vec(Expr, expr, bb->exprs) {\n if (isSymExpr(expr) || isCallExpr(expr))\n if (!liveCode.set_in(expr))\n expr->remove();\n }\n }\n\n freeDefUseChains(DU, UD);\n}\n\nvoid deadCodeElimination() {\n if (!fNoDeadCodeElimination) {\n deadBlockCount = 0;\n forv_Vec(FnSymbol, fn, gFnSymbols) {\n bool change = false;\n do {\n change = deadBlockElimination(fn);\n } while (change);\n\/\/ deadGotoElimination(fn);\n deadCodeElimination(fn);\n deadVariableElimination(fn);\n deadExpressionElimination(fn);\n }\n\n if (fReportDeadBlocks)\n printf(\"\\tRemoved %d dead blocks.\\n\", deadBlockCount);\n }\n}\n\n\/\/ Look for and remove unreachable blocks.\nstatic bool deadBlockElimination(FnSymbol* fn)\n{\n \/\/ We need the basic block information to be right here.\n buildBasicBlocks(fn);\n\n bool change = false;\n forv_Vec(BasicBlock, bb, *fn->basicBlocks)\n {\n \/\/ Ignore the first block.\n if (bb == fn->basicBlocks->v[0])\n continue;\n\n \/\/ If this block has no predecessors, then it is dead.\n if (bb->ins.count() == 0)\n {\n if (bb->exprs.n > 0)\n {\n change = true;\n ++deadBlockCount;\n\n \/\/ Remove all of its expressions.\n forv_Vec(Expr, expr, bb->exprs)\n {\n if (! expr->parentExpr)\n continue; \/\/ This node is no longer in the tree.\n\n CondStmt* cond = toCondStmt(expr->parentExpr);\n if (cond && cond->condExpr == expr)\n \/\/ If expr is the condition expression in an if statement,\n \/\/ then remove the entire if.\n cond->remove();\n else\n expr->remove();\n }\n }\n\n \/\/ Get more out of one pass by removing this BB from the predecessor\n \/\/ lists of its successors.\n forv_Vec(BasicBlock, succ, bb->outs)\n succ->ins.set_remove(bb); \n\n \/\/ We leave the \"dead\" bb structure in place.\n \/\/ The next time we construct basic blocks for this fn, it should be gone.\n }\n }\n\n return change;\n}\n\n\/\/ Look for pointless gotos and remove them.\n\/\/ Probably the best way to do this is to scan the AST and remove gotos\n\/\/ whose target labels follow immediately.\n#if 0\nstatic void deadGotoElimination(FnSymbol* fn)\n{\n \/\/ We recompute basic blocks because deadBlockElimination may cause them\n \/\/ to be out of sequence.\n buildBasicBlocks(fn);\n forv_Vec(BasicBlock, bb, *fn->basicBlocks)\n {\n \/\/ Get the last expression in the block as a goto.\n int last = bb->exprs.length() - 1;\n if (last < 0)\n continue;\n\n Expr* e = bb->exprs.v[last];\n GotoStmt* s = toGotoStmt(e);\n if (!s)\n continue;\n\n \/\/ If there is only one successor to this block and it is the next block,\n \/\/ then the goto must point to it and is therefore pointless [sts].\n \/\/ This test should be more foolproof using the structure of the AST.\n if (bb->outs.n == 1 && bb->outs.v[0]->id == bb->id + 1)\n e->remove();\n }\n}\n#endif\n<|endoftext|>"} {"text":"<commit_before>#include <stdio.h>\n#include <stdlib.h>\n#include <iostream>\n#include <cmath>\n\n#include \"nativeCode.h\" \/\/ generated by javah via maven-native-plugin\n\n#include \"JwMat.h\"\n#include \"jni_helper.h\"\n#include \"cv_helper.h\"\n\nusing namespace std;\n\nJNIEXPORT void JNICALL Java_de_serviceflow_frankenstein_plugin_opencv_jni_ExternalSample_init\n (JNIEnv* env, jobject obj)\n{\n JwMat* mat = JwMat::matptr;\n if (mat == NULL) {\n\t JwMat::matptr = new JwMat(env);\n }\n}\n\nvoid CircleRowT1(int x, int y, int radius, long rowptr, int xmid, int channels, int frameId);\n\n\/\/ draw row of circle at \"ymid + y\" from -x to +x at xmid offset\nvoid CircleRowT1(int x, int y, int radius, long rowptr, int xmid, int channels, int frameId) {\n\n int keyHue = ((frameId - 1) % 256);\n\n jbyte * data = (jbyte *)rowptr;\n int i = (xmid-x) * channels;\n for (int xx=-x; xx<=x; xx++, i+= channels) {\n \/\/ \n \n int h = atan2(xx, y) * 128 \/ 3.141592653589793238462643383279 + 128;\n int v = 255 - 255 * (xx * xx + y * y) \/ (radius * radius);\n int s = 2 * (CLAMP(v, 0, 255) - 128);\n if (s<0)\n s = 255 + s;\n else {\n s = 255 - s;\n v = 255 - v;\n }\n\n int range = 3;\n int hlower = keyHue - range;\n int hupper = keyHue + range;\n\n \/\/ if ( (h > hlower && h < hupper) || (hlower<0 && h>255+hlower) || (hupper>255 && h<hupper-255))\n {\n int distance = keyHue - h;\n if (distance<0)\n distance = -distance;\n if (distance>127)\n distance = 255 - distance;\n \n v = v * range * 255 \/ (range + distance) \/ 255;\n }\n \/\/else\n \/\/{\n\/\/ v = 0;\n \/\/}\n \n data[i+0] = CLAMP(h, 0, 255);\n data[i+1] = CLAMP(s, 0, 255);\n data[i+2] = CLAMP(v, 0, 255);\n }\n \n}\n\nvoid CircleRow(int x, int y, int radius, long rowptr, int xmid, int channels, int frameId);\n\n\/\/ draw row of circle at \"ymid + y\" from -x to +x at xmid offset\nvoid CircleRow(int x, int y, int radius, long rowptr, int xmid, int channels, int frameId) {\n\n jbyte * data = (jbyte *)rowptr;\n int i = (xmid-x) * channels;\n for (int xx=-x; xx<=x; xx++, i+= channels) {\n \/\/ \n \n int h = atan2(xx, y) * 128 \/ 3.141592653589793238462643383279 + 128;\n int v = 255 - 255 * (xx * xx + y * y) \/ (radius * radius);\n int s = 2 * (CLAMP(v, 0, 255) - 128);\n if (s<0)\n s = 255 + s;\n else\n s = 255 - s;\n data[i+0] = CLAMP(h, 0, 255);\n data[i+1] = CLAMP(s, 0, 255);\n data[i+2] = CLAMP(v, 0, 255);\n }\n \n}\n\nJNIEXPORT void JNICALL Java_de_serviceflow_frankenstein_plugin_opencv_jni_ExternalSample_process\n (JNIEnv* env, jobject obj,\n jobject matobj, jint frameId, jobject context)\n{\n JwMat* mat = JwMat::matptr;\n int cols = mat->cols(env, matobj);\n int rows = mat->rows(env, matobj);\n\/\/ cout << \"rows=\" << rows << \", cols=\" << cols << endl;\n\n int channels = mat->channels(env, matobj);\n if (channels<3) {\n\t J_THROW(\"java\/lang\/Error\", \"Expecting HSV Mat. channels < 3: \"+mat->channels(env, matobj));\n return;\n }\n\n long dataAddr = mat->dataAddr(env, matobj);\n long step1 = mat->step1(env, matobj);\n\n \/\/ Black background\n long rowPtr = dataAddr;\n for(int y = 0; y < rows; y++)\n {\n jbyte * data = (jbyte *)rowPtr;\n for (int x = 0; x < cols; x++)\n {\n int i = x * channels;\n data[i+2] = 0; \/\/ value -> black\n }\n rowPtr += step1;\n }\n \n int radius = cols > rows ? (rows>>1) - 1 : (cols>>1) - 1;\n \n \/\/ midpoint circle\n int x = 0;\n int y = radius;\n long rowPtr1 = dataAddr + step1 * (rows>>1);\n long rowPtr2 = rowPtr1;\n long rowPtr3 = rowPtr1;\n long rowPtr4 = rowPtr1;\n rowPtr1 -= step1 * y;\n rowPtr2 += step1 * y;\n int d = 1 - radius;\n CircleRowT1(x, y, radius, rowPtr1, cols>>1, channels, frameId);\n CircleRowT1(x, -y, radius, rowPtr2, cols>>1, channels, frameId);\n CircleRowT1(y, x, radius, rowPtr3, cols>>1, channels, frameId);\n CircleRowT1(y, -x, radius, rowPtr4, cols>>1, channels, frameId);\n while (y > x) {\n if (d<0) {\n d+=2*x+3;\n x++;\n rowPtr3 -= step1;\n rowPtr4 += step1;\n }\n else {\n d+=2*(x-y)+5;\n x++;\n rowPtr3 -= step1;\n rowPtr4 += step1;\n y--;\n rowPtr1 += step1;\n rowPtr2 -= step1;\n }\n CircleRowT1(x, y, radius, rowPtr1, cols>>1, channels, frameId);\n CircleRowT1(x, -y, radius, rowPtr2, cols>>1, channels, frameId);\n CircleRowT1(y, x, radius, rowPtr3, cols>>1, channels, frameId);\n CircleRowT1(y, -x, radius, rowPtr4, cols>>1, channels, frameId);\n }\n}\n\n\n<commit_msg>color space example recovered<commit_after>#include <stdio.h>\n#include <stdlib.h>\n#include <iostream>\n#include <cmath>\n\n#include \"nativeCode.h\" \/\/ generated by javah via maven-native-plugin\n\n#include \"JwMat.h\"\n#include \"jni_helper.h\"\n#include \"cv_helper.h\"\n\nusing namespace std;\n\nJNIEXPORT void JNICALL Java_de_serviceflow_frankenstein_plugin_opencv_jni_ExternalSample_init\n (JNIEnv* env, jobject obj)\n{\n JwMat* mat = JwMat::matptr;\n if (mat == NULL) {\n\t JwMat::matptr = new JwMat(env);\n }\n}\n\nvoid CircleRow(int x, int y, int radius, long rowptr, int xmid, int channels, int frameId);\n\n\/\/ draw row of circle at \"ymid + y\" from -x to +x at xmid offset\nvoid CircleRow(int x, int y, int radius, long rowptr, int xmid, int channels, int frameId) {\n\n jbyte * data = (jbyte *)rowptr;\n int i = (xmid-x) * channels;\n for (int xx=-x; xx<=x; xx++, i+= channels) {\n \/\/ \n \n int h = atan2(xx, y) * 128 \/ 3.141592653589793238462643383279 + 128;\n int v = 255 - 255 * (xx * xx + y * y) \/ (radius * radius);\n int s = 2 * (CLAMP(v, 0, 255) - 128);\n if (s<0)\n s = 255 + s;\n else\n s = 255 - s;\n data[i+0] = CLAMP(h, 0, 255);\n data[i+1] = CLAMP(s, 0, 255);\n data[i+2] = CLAMP(v, 0, 255);\n }\n \n}\n\nJNIEXPORT void JNICALL Java_de_serviceflow_frankenstein_plugin_opencv_jni_ExternalSample_process\n (JNIEnv* env, jobject obj,\n jobject matobj, jint frameId, jobject context)\n{\n JwMat* mat = JwMat::matptr;\n int cols = mat->cols(env, matobj);\n int rows = mat->rows(env, matobj);\n\/\/ cout << \"rows=\" << rows << \", cols=\" << cols << endl;\n\n int channels = mat->channels(env, matobj);\n if (channels<3) {\n\t J_THROW(\"java\/lang\/Error\", \"Expecting HSV Mat. channels < 3: \"+mat->channels(env, matobj));\n return;\n }\n\n long dataAddr = mat->dataAddr(env, matobj);\n long step1 = mat->step1(env, matobj);\n\n \/\/ Black background\n long rowPtr = dataAddr;\n for(int y = 0; y < rows; y++)\n {\n jbyte * data = (jbyte *)rowPtr;\n for (int x = 0; x < cols; x++)\n {\n int i = x * channels;\n data[i+2] = 0; \/\/ value -> black\n }\n rowPtr += step1;\n }\n \n int radius = cols > rows ? (rows>>1) - 1 : (cols>>1) - 1;\n \n \/\/ midpoint circle\n int x = 0;\n int y = radius;\n long rowPtr1 = dataAddr + step1 * (rows>>1);\n long rowPtr2 = rowPtr1;\n long rowPtr3 = rowPtr1;\n long rowPtr4 = rowPtr1;\n rowPtr1 -= step1 * y;\n rowPtr2 += step1 * y;\n int d = 1 - radius;\n CircleRow(x, y, radius, rowPtr1, cols>>1, channels, frameId);\n CircleRow(x, -y, radius, rowPtr2, cols>>1, channels, frameId);\n CircleRow(y, x, radius, rowPtr3, cols>>1, channels, frameId);\n CircleRow(y, -x, radius, rowPtr4, cols>>1, channels, frameId);\n while (y > x) {\n if (d<0) {\n d+=2*x+3;\n x++;\n rowPtr3 -= step1;\n rowPtr4 += step1;\n }\n else {\n d+=2*(x-y)+5;\n x++;\n rowPtr3 -= step1;\n rowPtr4 += step1;\n y--;\n rowPtr1 += step1;\n rowPtr2 -= step1;\n }\n CircleRow(x, y, radius, rowPtr1, cols>>1, channels, frameId);\n CircleRow(x, -y, radius, rowPtr2, cols>>1, channels, frameId);\n CircleRow(y, x, radius, rowPtr3, cols>>1, channels, frameId);\n CircleRow(y, -x, radius, rowPtr4, cols>>1, channels, frameId);\n }\n}\n\n\n<|endoftext|>"} {"text":"<commit_before>\/\/! \\file\n\/*\n** Copyright (C) - Triton\n**\n** This program is under the terms of the Apache License 2.0.\n*\/\n\n#ifndef TRITON_SYMBOLICEXPRESSION_H\n#define TRITON_SYMBOLICEXPRESSION_H\n\n#include <memory>\n#include <string>\n\n#include <triton\/ast.hpp>\n#include <triton\/dllexport.hpp>\n#include <triton\/memoryAccess.hpp>\n#include <triton\/register.hpp>\n#include <triton\/symbolicEnums.hpp>\n#include <triton\/tritonTypes.hpp>\n\n\n\n\/\/! The Triton namespace\nnamespace triton {\n\/*!\n * \\addtogroup triton\n * @{\n *\/\n\n \/\/! The Engines namespace\n namespace engines {\n \/*!\n * \\ingroup triton\n * \\addtogroup engines\n * @{\n *\/\n\n \/\/! The Symbolic Execution namespace\n namespace symbolic {\n \/*!\n * \\ingroup engines\n * \\addtogroup symbolic\n * @{\n *\/\n\n \/\/! \\class SymbolicExpression\n \/*! \\brief The symbolic expression class *\/\n class SymbolicExpression {\n protected:\n \/\/! The type of the symbolic expression assignment.\n triton::engines::symbolic::expression_e type;\n\n \/\/! The root node (AST) of the symbolic expression.\n triton::ast::SharedAbstractNode ast;\n\n \/\/! The comment of the symbolic expression.\n std::string comment;\n\n \/\/! The address of the instruction behind the symbolic expression. 0 if empty.\n uint64_t address;\n\n \/\/! The instruction disassembly where the symbolic expression comes from.\n std::string disassembly;\n\n \/\/! The symbolic expression id. This id is unique.\n triton::usize id;\n\n \/\/! The origin memory address if `type` is equal to `triton::engines::symbolic::MEM`, invalid memory otherwise.\n triton::arch::MemoryAccess originMemory;\n\n \/\/! The origin register if `type` is equal to `triton::engines::symbolic::REG`, `REG_INVALID` otherwise.\n triton::arch::Register originRegister;\n\n private:\n \/\/! Returns the syntax of a bitvector define\n TRITON_EXPORT std::string getBitvectorDefine(void) const;\n\n \/\/! Returns the syntax of an array define\n TRITON_EXPORT std::string getArrayDefine(void) const;\n\n public:\n \/\/! True if the symbolic expression is tainted.\n bool isTainted;\n\n \/\/! Constructor.\n TRITON_EXPORT SymbolicExpression(const triton::ast::SharedAbstractNode& node,\n triton::usize id,\n triton::engines::symbolic::expression_e type,\n const std::string& comment=\"\");\n\n \/\/! Constructor by copy.\n TRITON_EXPORT SymbolicExpression(const SymbolicExpression& other);\n\n \/\/! Operator.\n TRITON_EXPORT SymbolicExpression& operator=(const SymbolicExpression& other);\n\n \/\/! Returns the symbolic expression id.\n TRITON_EXPORT triton::usize getId(void) const;\n\n \/\/! Returns true if the symbolic expression is assigned to a memory.\n TRITON_EXPORT bool isMemory(void) const;\n\n \/\/! Returns true if the symbolic expression is assigned to a register.\n TRITON_EXPORT bool isRegister(void) const;\n\n \/\/! Returns true if the expression contains a symbolic variable.\n TRITON_EXPORT bool isSymbolized(void) const;\n\n \/\/! Returns the type of the symbolic expression assignment.\n TRITON_EXPORT triton::engines::symbolic::expression_e getType(void) const;\n\n \/\/! Returns the SMT AST root node of the symbolic expression. This is the semantics.\n TRITON_EXPORT const triton::ast::SharedAbstractNode& getAst(void) const;\n\n \/\/! Returns a new SMT AST root node of the symbolic expression. This new instance is a duplicate of the original node and may be changed without changing the original semantics.\n TRITON_EXPORT triton::ast::SharedAbstractNode getNewAst(void) const;\n\n \/\/! Returns the comment of the symbolic expression.\n TRITON_EXPORT const std::string& getComment(void) const;\n\n \/\/! Returns the id as string of the symbolic expression according the mode of the AST representation.\n TRITON_EXPORT std::string getFormattedId(void) const;\n\n \/\/! Returns the comment as string of the symbolic expression according the mode of the AST representation.\n TRITON_EXPORT std::string getFormattedComment(void) const;\n\n \/\/! Returns the symbolic expression representation as string according the mode of the AST representation.\n TRITON_EXPORT std::string getFormattedExpression(void) const;\n\n \/\/! Returns the origin memory access if `kind` is equal to `triton::engines::symbolic::MEMORY_EXPRESSION`, invalid memory otherwise.\n TRITON_EXPORT const triton::arch::MemoryAccess& getOriginMemory(void) const;\n\n \/\/! Returns the origin register if `kind` is equal to `triton::engines::symbolic::REGISTER_EXPRESSION`, invalid register otherwise.\n TRITON_EXPORT const triton::arch::Register& getOriginRegister(void) const;\n\n \/\/! Sets a root node.\n TRITON_EXPORT void setAst(const triton::ast::SharedAbstractNode& node);\n\n \/\/! Sets a comment to the symbolic expression.\n TRITON_EXPORT void setComment(const std::string& comment);\n\n \/\/! Sets the kind of the symbolic expression.\n TRITON_EXPORT void setType(triton::engines::symbolic::expression_e type);\n\n \/\/! Sets the symbolic expression address.\n TRITON_EXPORT void setAddress(triton::uint64 address);\n\n \/\/! Get the address of the symbolic expression, if any.\n TRITON_EXPORT triton::uint64 getAddress(void) const;\n\n \/\/! Sets the origin memory acccess.\n TRITON_EXPORT void setOriginMemory(const triton::arch::MemoryAccess& mem);\n\n \/\/! Sets the origin register.\n TRITON_EXPORT void setOriginRegister(const triton::arch::Register& reg);\n\n \/\/! Writes back the instruction disassembly where the symbolic expression comes from.\n TRITON_EXPORT void writeBackDisassembly(const std::string& disassembly);\n\n \/\/! Gets the instruction disassembly where the symbolic expression comes from.\n TRITON_EXPORT const std::string& getDisassembly(void);\n };\n\n \/\/! Shared Symbolic Expression.\n using SharedSymbolicExpression = std::shared_ptr<triton::engines::symbolic::SymbolicExpression>;\n\n \/\/! Weak Symbolic Expression.\n using WeakSymbolicExpression = std::weak_ptr<triton::engines::symbolic::SymbolicExpression>;\n\n \/\/! Displays a symbolic expression.\n TRITON_EXPORT std::ostream& operator<<(std::ostream& stream, const SymbolicExpression& symExpr);\n\n \/\/! Displays a symbolic expression.\n TRITON_EXPORT std::ostream& operator<<(std::ostream& stream, const SymbolicExpression* symExpr);\n\n \/*! @} End of symbolic namespace *\/\n };\n \/*! @} End of engines namespace *\/\n };\n\/*! @} End of triton namespace *\/\n};\n\n#endif \/* TRITON_SYMBOLICEXPRESSION_H *\/\n<commit_msg>Fix type<commit_after>\/\/! \\file\n\/*\n** Copyright (C) - Triton\n**\n** This program is under the terms of the Apache License 2.0.\n*\/\n\n#ifndef TRITON_SYMBOLICEXPRESSION_H\n#define TRITON_SYMBOLICEXPRESSION_H\n\n#include <memory>\n#include <string>\n\n#include <triton\/ast.hpp>\n#include <triton\/dllexport.hpp>\n#include <triton\/memoryAccess.hpp>\n#include <triton\/register.hpp>\n#include <triton\/symbolicEnums.hpp>\n#include <triton\/tritonTypes.hpp>\n\n\n\n\/\/! The Triton namespace\nnamespace triton {\n\/*!\n * \\addtogroup triton\n * @{\n *\/\n\n \/\/! The Engines namespace\n namespace engines {\n \/*!\n * \\ingroup triton\n * \\addtogroup engines\n * @{\n *\/\n\n \/\/! The Symbolic Execution namespace\n namespace symbolic {\n \/*!\n * \\ingroup engines\n * \\addtogroup symbolic\n * @{\n *\/\n\n \/\/! \\class SymbolicExpression\n \/*! \\brief The symbolic expression class *\/\n class SymbolicExpression {\n protected:\n \/\/! The type of the symbolic expression assignment.\n triton::engines::symbolic::expression_e type;\n\n \/\/! The root node (AST) of the symbolic expression.\n triton::ast::SharedAbstractNode ast;\n\n \/\/! The comment of the symbolic expression.\n std::string comment;\n\n \/\/! The address of the instruction behind the symbolic expression. -1 if not defined.\n triton::uint64 address;\n\n \/\/! The instruction disassembly where the symbolic expression comes from.\n std::string disassembly;\n\n \/\/! The symbolic expression id. This id is unique.\n triton::usize id;\n\n \/\/! The origin memory address if `type` is equal to `triton::engines::symbolic::MEM`, invalid memory otherwise.\n triton::arch::MemoryAccess originMemory;\n\n \/\/! The origin register if `type` is equal to `triton::engines::symbolic::REG`, `REG_INVALID` otherwise.\n triton::arch::Register originRegister;\n\n private:\n \/\/! Returns the syntax of a bitvector define\n TRITON_EXPORT std::string getBitvectorDefine(void) const;\n\n \/\/! Returns the syntax of an array define\n TRITON_EXPORT std::string getArrayDefine(void) const;\n\n public:\n \/\/! True if the symbolic expression is tainted.\n bool isTainted;\n\n \/\/! Constructor.\n TRITON_EXPORT SymbolicExpression(const triton::ast::SharedAbstractNode& node,\n triton::usize id,\n triton::engines::symbolic::expression_e type,\n const std::string& comment=\"\");\n\n \/\/! Constructor by copy.\n TRITON_EXPORT SymbolicExpression(const SymbolicExpression& other);\n\n \/\/! Operator.\n TRITON_EXPORT SymbolicExpression& operator=(const SymbolicExpression& other);\n\n \/\/! Returns the symbolic expression id.\n TRITON_EXPORT triton::usize getId(void) const;\n\n \/\/! Returns true if the symbolic expression is assigned to a memory.\n TRITON_EXPORT bool isMemory(void) const;\n\n \/\/! Returns true if the symbolic expression is assigned to a register.\n TRITON_EXPORT bool isRegister(void) const;\n\n \/\/! Returns true if the expression contains a symbolic variable.\n TRITON_EXPORT bool isSymbolized(void) const;\n\n \/\/! Returns the type of the symbolic expression assignment.\n TRITON_EXPORT triton::engines::symbolic::expression_e getType(void) const;\n\n \/\/! Returns the SMT AST root node of the symbolic expression. This is the semantics.\n TRITON_EXPORT const triton::ast::SharedAbstractNode& getAst(void) const;\n\n \/\/! Returns a new SMT AST root node of the symbolic expression. This new instance is a duplicate of the original node and may be changed without changing the original semantics.\n TRITON_EXPORT triton::ast::SharedAbstractNode getNewAst(void) const;\n\n \/\/! Returns the comment of the symbolic expression.\n TRITON_EXPORT const std::string& getComment(void) const;\n\n \/\/! Returns the id as string of the symbolic expression according the mode of the AST representation.\n TRITON_EXPORT std::string getFormattedId(void) const;\n\n \/\/! Returns the comment as string of the symbolic expression according the mode of the AST representation.\n TRITON_EXPORT std::string getFormattedComment(void) const;\n\n \/\/! Returns the symbolic expression representation as string according the mode of the AST representation.\n TRITON_EXPORT std::string getFormattedExpression(void) const;\n\n \/\/! Returns the origin memory access if `kind` is equal to `triton::engines::symbolic::MEMORY_EXPRESSION`, invalid memory otherwise.\n TRITON_EXPORT const triton::arch::MemoryAccess& getOriginMemory(void) const;\n\n \/\/! Returns the origin register if `kind` is equal to `triton::engines::symbolic::REGISTER_EXPRESSION`, invalid register otherwise.\n TRITON_EXPORT const triton::arch::Register& getOriginRegister(void) const;\n\n \/\/! Sets a root node.\n TRITON_EXPORT void setAst(const triton::ast::SharedAbstractNode& node);\n\n \/\/! Sets a comment to the symbolic expression.\n TRITON_EXPORT void setComment(const std::string& comment);\n\n \/\/! Sets the kind of the symbolic expression.\n TRITON_EXPORT void setType(triton::engines::symbolic::expression_e type);\n\n \/\/! Sets the symbolic expression address.\n TRITON_EXPORT void setAddress(triton::uint64 address);\n\n \/\/! Get the address of the symbolic expression, if any.\n TRITON_EXPORT triton::uint64 getAddress(void) const;\n\n \/\/! Sets the origin memory acccess.\n TRITON_EXPORT void setOriginMemory(const triton::arch::MemoryAccess& mem);\n\n \/\/! Sets the origin register.\n TRITON_EXPORT void setOriginRegister(const triton::arch::Register& reg);\n\n \/\/! Writes back the instruction disassembly where the symbolic expression comes from.\n TRITON_EXPORT void writeBackDisassembly(const std::string& disassembly);\n\n \/\/! Gets the instruction disassembly where the symbolic expression comes from.\n TRITON_EXPORT const std::string& getDisassembly(void);\n };\n\n \/\/! Shared Symbolic Expression.\n using SharedSymbolicExpression = std::shared_ptr<triton::engines::symbolic::SymbolicExpression>;\n\n \/\/! Weak Symbolic Expression.\n using WeakSymbolicExpression = std::weak_ptr<triton::engines::symbolic::SymbolicExpression>;\n\n \/\/! Displays a symbolic expression.\n TRITON_EXPORT std::ostream& operator<<(std::ostream& stream, const SymbolicExpression& symExpr);\n\n \/\/! Displays a symbolic expression.\n TRITON_EXPORT std::ostream& operator<<(std::ostream& stream, const SymbolicExpression* symExpr);\n\n \/*! @} End of symbolic namespace *\/\n };\n \/*! @} End of engines namespace *\/\n };\n\/*! @} End of triton namespace *\/\n};\n\n#endif \/* TRITON_SYMBOLICEXPRESSION_H *\/\n<|endoftext|>"} {"text":"<commit_before>\/****************************************************************************\n**\n** Copyright (C) 2010 Nokia Corporation and\/or its subsidiary(-ies).\n** All rights reserved.\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n** This file is part of the Qt Mobility Components.\n**\n** $QT_BEGIN_LICENSE:LGPL$\n** No Commercial Usage\n** This file contains pre-release code and may not be distributed.\n** You may use this file in accordance with the terms and conditions\n** contained in the Technology Preview License Agreement accompanying\n** this package.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Nokia gives you certain additional\n** rights. These rights are described in the Nokia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at qt-info@nokia.com.\n**\n**\n**\n**\n**\n**\n**\n**\n** $QT_END_LICENSE$\n**\n****************************************************************************\/\n\n#include \"qgeotiledmapobjectinfo_p.h\"\n\n#include \"qgeotiledmapdata.h\"\n#include \"qgeotiledmapdata_p.h\"\n\n#include <QGraphicsScene>\n\n#include <QPolygonF>\n\n#include <QDebug>\n\nQTM_BEGIN_NAMESPACE\n\nQGeoTiledMapObjectInfo::QGeoTiledMapObjectInfo(QGeoMapData *mapData, QGeoMapObject *mapObject)\n : QGeoMapObjectInfo(mapData, mapObject),\n graphicsItem(0)\n{\n tiledMapData = static_cast<QGeoTiledMapData*>(mapData);\n tiledMapDataPrivate = static_cast<QGeoTiledMapDataPrivate*>(tiledMapData->d_ptr);\n}\n\nQGeoTiledMapObjectInfo::~QGeoTiledMapObjectInfo()\n{\n if (graphicsItem)\n delete graphicsItem;\n}\n\nvoid QGeoTiledMapObjectInfo::addToParent()\n{\n if (graphicsItem) {\n QGeoTiledMapObjectInfo *parentInfo\n = static_cast<QGeoTiledMapObjectInfo*>(parentObjectInfo());\n\n if (parentInfo)\n graphicsItem->setParentItem(parentInfo->graphicsItem);\n else\n tiledMapDataPrivate->scene->addItem(graphicsItem);\n\n tiledMapDataPrivate->itemMap.insert(graphicsItem, mapObject());\n graphicsItem->setVisible(mapObject()->isVisible());\n graphicsItem->setFlag(QGraphicsItem::ItemIsSelectable);\n graphicsItem->setSelected(mapObject()->isSelected());\n }\n}\n\nvoid QGeoTiledMapObjectInfo::removeFromParent()\n{\n if (graphicsItem) {\n tiledMapDataPrivate->scene->removeItem(graphicsItem);\n tiledMapDataPrivate->itemMap.remove(graphicsItem);\n }\n}\n\nvoid QGeoTiledMapObjectInfo::visibleChanged(bool visible)\n{\n if (graphicsItem) {\n graphicsItem->setVisible(visible);\n updateItem();\n }\n}\n\nvoid QGeoTiledMapObjectInfo::selectedChanged(bool selected)\n{\n if (graphicsItem) {\n graphicsItem->setSelected(selected);\n updateItem();\n }\n}\n\nQGeoBoundingBox QGeoTiledMapObjectInfo::boundingBox() const\n{\n if (!graphicsItem)\n return QGeoBoundingBox();\n\n QRectF rect1 = graphicsItem->boundingRect();\n QGeoCoordinate topLeft1 = tiledMapData->worldPixelToCoordinate(rect1.topLeft().toPoint());\n QGeoCoordinate bottomRight1 = tiledMapData->worldPixelToCoordinate(rect1.bottomRight().toPoint());\n\n QGeoBoundingBox box1 = QGeoBoundingBox(topLeft1, bottomRight1);\n\n return box1;\n}\n\nbool QGeoTiledMapObjectInfo::contains(const QGeoCoordinate &coord) const\n{\n QPoint point = tiledMapData->coordinateToWorldPixel(coord);\n\n if (graphicsItem && graphicsItem->contains(point))\n return true;\n\n return false;\n}\n\nvoid QGeoTiledMapObjectInfo::updateItem()\n{\n \/\/ TODO use bounding rectangle of graphics items\n if (graphicsItem)\n tiledMapData->geoMap()->update();\n}\n\nQPolygonF QGeoTiledMapObjectInfo::createPolygon(const QList<QGeoCoordinate> &path,\n QGeoTiledMapData *tiledMapData,\n bool closedPath,\n qreal ypole)\n{\n QPolygonF points;\n\n QGeoCoordinate lastCoord = closedPath ? path.last() : path.first();\n QPointF lastPoint = tiledMapData->coordinateToWorldPixel(lastCoord);\n\n int width = tiledMapData->maxZoomSize().width();\n\n for (int i = 0; i < path.size(); ++i) {\n const QGeoCoordinate &coord = path.at(i);\n\n if (!coord.isValid())\n continue;\n\n const qreal lng = coord.longitude();\n const qreal lastLng = lastCoord.longitude();\n\n \/\/ is the dateline crossed = different sign AND gap is large enough\n const bool crossesDateline = lastLng * lng < 0 && abs(lastLng - lng) > 180;\n\n \/\/ calculate base point\n QPointF point = tiledMapData->coordinateToWorldPixel(coord);\n\n \/\/ if the dateline is crossed, draw \"around\" the map over the chosen pole\n if (crossesDateline) {\n \/\/ is the shortest route east = dateline crossed XOR longitude is east by simple comparison\n const bool goesEast = crossesDateline != (lng > lastLng);\n \/\/ direction = positive if east, negative otherwise\n const qreal dir = goesEast ? 1 : -1;\n\n \/\/ lastPoint on this side\n const QPointF & L = lastPoint;\n\n \/\/ point on the other side\n const QPointF & P = point;\n\n \/\/ lastPoint on the other side\n QPointF L_ = L - QPointF(width * dir, 0);\n\n \/\/ point on this side\n QPointF P_ = P + QPointF(width * dir, 0);\n\n \/\/ TODO: make a better algorithm to make sure the off-screen points P' and L' are far enough from the dateline so the lines to the poles don't flicker through.\n \/\/ this works for now :)\n L_ += (L_ - P) * 7;\n P_ += (P_ - L) * 7;\n\n \/\/ pole point on this side\n QPointF O1 = QPointF(P_.x(), ypole);\n \/\/ pole point on the other side\n QPointF O2 = QPointF(L_.x(), ypole);\n\n \/\/points.append(L); \/\/ implicit\n points.append(P_); \/\/ P'\n points.append(O1);\n points.append(O2);\n points.append(L_); \/\/ L'\n points.append(P);\n } else {\n \/\/ add point to polygon\n points.append(point);\n }\n\n lastCoord = coord;\n lastPoint = point;\n }\n\n return points;\n}\n\nQTM_END_NAMESPACE\n\n<commit_msg>Fixed problem with pixmap and text map object selection.<commit_after>\/****************************************************************************\n**\n** Copyright (C) 2010 Nokia Corporation and\/or its subsidiary(-ies).\n** All rights reserved.\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n** This file is part of the Qt Mobility Components.\n**\n** $QT_BEGIN_LICENSE:LGPL$\n** No Commercial Usage\n** This file contains pre-release code and may not be distributed.\n** You may use this file in accordance with the terms and conditions\n** contained in the Technology Preview License Agreement accompanying\n** this package.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Nokia gives you certain additional\n** rights. These rights are described in the Nokia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at qt-info@nokia.com.\n**\n**\n**\n**\n**\n**\n**\n**\n** $QT_END_LICENSE$\n**\n****************************************************************************\/\n\n#include \"qgeotiledmapobjectinfo_p.h\"\n\n#include \"qgeotiledmapdata.h\"\n#include \"qgeotiledmapdata_p.h\"\n\n#include <QGraphicsScene>\n\n#include <QPolygonF>\n\n#include <QDebug>\n\nQTM_BEGIN_NAMESPACE\n\nQGeoTiledMapObjectInfo::QGeoTiledMapObjectInfo(QGeoMapData *mapData, QGeoMapObject *mapObject)\n : QGeoMapObjectInfo(mapData, mapObject),\n graphicsItem(0)\n{\n tiledMapData = static_cast<QGeoTiledMapData*>(mapData);\n tiledMapDataPrivate = static_cast<QGeoTiledMapDataPrivate*>(tiledMapData->d_ptr);\n}\n\nQGeoTiledMapObjectInfo::~QGeoTiledMapObjectInfo()\n{\n if (graphicsItem)\n delete graphicsItem;\n}\n\nvoid QGeoTiledMapObjectInfo::addToParent()\n{\n if (graphicsItem) {\n QGeoTiledMapObjectInfo *parentInfo\n = static_cast<QGeoTiledMapObjectInfo*>(parentObjectInfo());\n\n if (parentInfo)\n graphicsItem->setParentItem(parentInfo->graphicsItem);\n else\n tiledMapDataPrivate->scene->addItem(graphicsItem);\n\n tiledMapDataPrivate->itemMap.insert(graphicsItem, mapObject());\n graphicsItem->setVisible(mapObject()->isVisible());\n graphicsItem->setFlag(QGraphicsItem::ItemIsSelectable);\n graphicsItem->setSelected(mapObject()->isSelected());\n }\n}\n\nvoid QGeoTiledMapObjectInfo::removeFromParent()\n{\n if (graphicsItem) {\n tiledMapDataPrivate->scene->removeItem(graphicsItem);\n tiledMapDataPrivate->itemMap.remove(graphicsItem);\n }\n}\n\nvoid QGeoTiledMapObjectInfo::visibleChanged(bool visible)\n{\n if (graphicsItem) {\n graphicsItem->setVisible(visible);\n updateItem();\n }\n}\n\nvoid QGeoTiledMapObjectInfo::selectedChanged(bool selected)\n{\n if (graphicsItem) {\n graphicsItem->setSelected(selected);\n updateItem();\n }\n}\n\nQGeoBoundingBox QGeoTiledMapObjectInfo::boundingBox() const\n{\n if (!graphicsItem)\n return QGeoBoundingBox();\n\n QRectF rect1 = graphicsItem->boundingRect();\n QGeoCoordinate topLeft1 = tiledMapData->worldPixelToCoordinate(rect1.topLeft().toPoint());\n QGeoCoordinate bottomRight1 = tiledMapData->worldPixelToCoordinate(rect1.bottomRight().toPoint());\n\n QGeoBoundingBox box1 = QGeoBoundingBox(topLeft1, bottomRight1);\n\n return box1;\n}\n\nbool QGeoTiledMapObjectInfo::contains(const QGeoCoordinate &coord) const\n{\n QPoint point = tiledMapData->coordinateToWorldPixel(coord);\n\n \/\/if (graphicsItem && graphicsItem->contains(point))\n if (graphicsItem && graphicsItem->mapToParent(graphicsItem->shape()).contains(point))\n return true;\n\n return false;\n}\n\nvoid QGeoTiledMapObjectInfo::updateItem()\n{\n \/\/ TODO use bounding rectangle of graphics items\n if (graphicsItem)\n tiledMapData->geoMap()->update();\n}\n\nQPolygonF QGeoTiledMapObjectInfo::createPolygon(const QList<QGeoCoordinate> &path,\n QGeoTiledMapData *tiledMapData,\n bool closedPath,\n qreal ypole)\n{\n QPolygonF points;\n\n QGeoCoordinate lastCoord = closedPath ? path.last() : path.first();\n QPointF lastPoint = tiledMapData->coordinateToWorldPixel(lastCoord);\n\n int width = tiledMapData->maxZoomSize().width();\n\n for (int i = 0; i < path.size(); ++i) {\n const QGeoCoordinate &coord = path.at(i);\n\n if (!coord.isValid())\n continue;\n\n const qreal lng = coord.longitude();\n const qreal lastLng = lastCoord.longitude();\n\n \/\/ is the dateline crossed = different sign AND gap is large enough\n const bool crossesDateline = lastLng * lng < 0 && abs(lastLng - lng) > 180;\n\n \/\/ calculate base point\n QPointF point = tiledMapData->coordinateToWorldPixel(coord);\n\n \/\/ if the dateline is crossed, draw \"around\" the map over the chosen pole\n if (crossesDateline) {\n \/\/ is the shortest route east = dateline crossed XOR longitude is east by simple comparison\n const bool goesEast = crossesDateline != (lng > lastLng);\n \/\/ direction = positive if east, negative otherwise\n const qreal dir = goesEast ? 1 : -1;\n\n \/\/ lastPoint on this side\n const QPointF & L = lastPoint;\n\n \/\/ point on the other side\n const QPointF & P = point;\n\n \/\/ lastPoint on the other side\n QPointF L_ = L - QPointF(width * dir, 0);\n\n \/\/ point on this side\n QPointF P_ = P + QPointF(width * dir, 0);\n\n \/\/ TODO: make a better algorithm to make sure the off-screen points P' and L' are far enough from the dateline so the lines to the poles don't flicker through.\n \/\/ this works for now :)\n L_ += (L_ - P) * 7;\n P_ += (P_ - L) * 7;\n\n \/\/ pole point on this side\n QPointF O1 = QPointF(P_.x(), ypole);\n \/\/ pole point on the other side\n QPointF O2 = QPointF(L_.x(), ypole);\n\n \/\/points.append(L); \/\/ implicit\n points.append(P_); \/\/ P'\n points.append(O1);\n points.append(O2);\n points.append(L_); \/\/ L'\n points.append(P);\n } else {\n \/\/ add point to polygon\n points.append(point);\n }\n\n lastCoord = coord;\n lastPoint = point;\n }\n\n return points;\n}\n\nQTM_END_NAMESPACE\n\n<|endoftext|>"} {"text":"<commit_before>#define CATCH_CONFIG_RUNNER\n#include <catch.hpp>\n#include <cmath>\n#include <algorithm>\n#include <vector>\n#include <set>\n#include \"circle.hpp\"\n\n\tbool is_odd(int i){\n\t\treturn (i % 2) != 0;\n\t}\n\n\tbool is_even(int i){\n\t\treturn (i % 2) == 0;\n\t}\n\n\n\nTEST_CASE(\"describe_factorial\", \"[aufgbae3]\")\n{\n\t\/\/ihre Loesung :\n\n\tstd::set<Circle> set0;\n\n\tfor (int i = 0; i < 5; ++i) {\n\n\t\tfloat rad= std::rand() % 10;\n\t\tCircle c(rad, 0.0f, 0.0f);\n\t\tset0.insert(c);\n\t}\n\n\tstd::set<Circle> set1;\n\n\tCircle c1(6.0f, 0.0f, 0.0f);\n\tCircle c2(5.0f, 0.0f, 0.0f);\n\tCircle c3(7.0f, 0.0f, 0.0f);\n\tCircle c4(2.0f, 0.0f, 0.0f);\n\n\tset1.insert(c1);\n\tset1.insert(c2);\n\tset1.insert(c3);\n\tset1.insert(c4);\n\nREQUIRE(std::is_sorted(set0.begin(), set0.end()));\nREQUIRE(std::is_sorted(set1.begin(), set1.end()));\n\n}\n\ntemplate<typename T>\nvoid swap(T& a, T& b) {\n\tT c(a);\n\ta = b;\n\tb = c;\n}\n\nTEST_CASE(\"describe_swap\", \"[aufgabe3.8]\"){\n\n\tCircle c1(6.0f, 0.0f, 0.0f);\n\tCircle c2(5.0f, 0.0f, 0.0f);\n\n\n\tswap(c1, c2);\n\n\tREQUIRE(c1.get_r()==5.0f);\n\tREQUIRE(c2.get_r()==6.0f);\n\n\n\n}\n\n\n\n\nint main (int argc, char* argv[])\n{\n\treturn Catch::Session().run (argc, argv);\n}<commit_msg>3.9 finished<commit_after>#define CATCH_CONFIG_RUNNER\n#include <catch.hpp>\n#include <cmath>\n#include <algorithm>\n#include <vector>\n#include <set>\n#include <list>\n#include \"circle.hpp\"\n\n\tbool is_odd(int i){\n\t\treturn (i % 2) != 0;\n\t}\n\n\tbool is_even(int i){\n\t\treturn (i % 2) == 0;\n\t}\n\n\n\nTEST_CASE(\"describe_sort\", \"[sort]\")\n{\n\t\/\/ihre Loesung :\n\n\tstd::set<Circle> set0;\n\n\tfor (int i = 0; i < 5; ++i) {\n\n\t\tfloat rad= std::rand() % 10;\n\t\tCircle c(rad, 0.0f, 0.0f);\n\t\tset0.insert(c);\n\t}\n\n\tstd::set<Circle> set1;\n\n\tCircle c1(6.0f, 0.0f, 0.0f);\n\tCircle c2(5.0f, 0.0f, 0.0f);\n\tCircle c3(7.0f, 0.0f, 0.0f);\n\tCircle c4(2.0f, 0.0f, 0.0f);\n\n\tset1.insert(c1);\n\tset1.insert(c2);\n\tset1.insert(c3);\n\tset1.insert(c4);\n\nREQUIRE(std::is_sorted(set0.begin(), set0.end()));\nREQUIRE(std::is_sorted(set1.begin(), set1.end()));\n\n}\n\ntemplate<typename T>\nvoid swap(T& a, T& b) {\n\tT c(a);\n\ta = b;\n\tb = c;\n}\n\nTEST_CASE(\"describe_swap\", \"[aufgabe3.8]\"){\n\n\tCircle c1(6.0f, 0.0f, 0.0f);\n\tCircle c2(5.0f, 0.0f, 0.0f);\n\tint a = 0;\n\tint b = 1;\n\n\tswap(c1, c2);\n\tswap(a, b);\n\n\tREQUIRE(c1.get_r()==5.0f);\n\tREQUIRE(c2.get_r()==6.0f);\n\n\tREQUIRE(a == 1);\n\tREQUIRE(b == 0);\n\n}\n\n\nTEST_CASE(\"describe_sort2\", \"[sort2]\"){\n\n\tstd::list<Circle> list0(5);\n\tfor (int i = 0; i < 5; ++i) {\n\n\t\tfloat rad = std::rand() % 10;\n\t\tCircle c(rad, 0.0f, 0.0f);\n\t\tlist0.push_back(c);\n\t}\n\n\tlist0.sort([](Circle a, Circle b) {\n\t\treturn a.get_r() < b.get_r();\n\t});\n\n\n\tREQUIRE(std::is_sorted(list0.begin(), list0.end()));\n}\n\n\n\n\nint main (int argc, char* argv[])\n{\n\treturn Catch::Session().run (argc, argv);\n}<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright 2014 Facebook, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"folly\/wangle\/bootstrap\/ServerBootstrap.h\"\n#include \"folly\/wangle\/bootstrap\/ClientBootstrap.h\"\n#include \"folly\/wangle\/channel\/ChannelHandler.h\"\n\n#include <glog\/logging.h>\n#include <gtest\/gtest.h>\n\nusing namespace folly::wangle;\nusing namespace folly;\n\ntypedef ChannelPipeline<IOBufQueue&, std::unique_ptr<IOBuf>> Pipeline;\n\nclass TestServer : public ServerBootstrap<Pipeline> {\n Pipeline* newPipeline(std::shared_ptr<AsyncSocket>) {\n return nullptr;\n }\n};\n\nclass TestClient : public ClientBootstrap<Pipeline> {\n Pipeline* newPipeline(std::shared_ptr<AsyncSocket> sock) {\n CHECK(sock->good());\n\n \/\/ We probably aren't connected immedately, check after a small delay\n EventBaseManager::get()->getEventBase()->runAfterDelay([sock](){\n CHECK(sock->readable());\n }, 100);\n return nullptr;\n }\n};\n\nclass TestPipelineFactory : public PipelineFactory<Pipeline> {\n public:\n Pipeline* newPipeline(std::shared_ptr<AsyncSocket> sock) {\n pipelines++;\n return new Pipeline();\n }\n std::atomic<int> pipelines{0};\n};\n\nTEST(Bootstrap, Basic) {\n TestServer server;\n TestClient client;\n}\n\nTEST(Bootstrap, ServerWithPipeline) {\n TestServer server;\n server.childPipeline(std::make_shared<TestPipelineFactory>());\n server.bind(0);\n server.stop();\n}\n\nTEST(Bootstrap, ClientServerTest) {\n TestServer server;\n auto factory = std::make_shared<TestPipelineFactory>();\n server.childPipeline(factory);\n server.bind(0);\n auto base = EventBaseManager::get()->getEventBase();\n\n SocketAddress address;\n server.getSockets()[0]->getAddress(&address);\n\n TestClient client;\n client.connect(address);\n base->loop();\n server.stop();\n\n CHECK(factory->pipelines == 1);\n}\n\nTEST(Bootstrap, ClientConnectionManagerTest) {\n \/\/ Create a single IO thread, and verify that\n \/\/ client connections are pooled properly\n\n TestServer server;\n auto factory = std::make_shared<TestPipelineFactory>();\n server.childPipeline(factory);\n server.group(std::make_shared<IOThreadPoolExecutor>(1));\n server.bind(0);\n auto base = EventBaseManager::get()->getEventBase();\n\n SocketAddress address;\n server.getSockets()[0]->getAddress(&address);\n\n TestClient client;\n client.connect(address);\n\n TestClient client2;\n client2.connect(address);\n\n base->loop();\n server.stop();\n\n CHECK(factory->pipelines == 2);\n}\n\nTEST(Bootstrap, ServerAcceptGroupTest) {\n \/\/ Verify that server is using the accept IO group\n\n TestServer server;\n auto factory = std::make_shared<TestPipelineFactory>();\n server.childPipeline(factory);\n server.group(std::make_shared<IOThreadPoolExecutor>(1), nullptr);\n server.bind(0);\n\n SocketAddress address;\n server.getSockets()[0]->getAddress(&address);\n\n boost::barrier barrier(2);\n auto thread = std::thread([&](){\n TestClient client;\n client.connect(address);\n EventBaseManager::get()->getEventBase()->loop();\n barrier.wait();\n });\n barrier.wait();\n server.stop();\n thread.join();\n\n CHECK(factory->pipelines == 1);\n}\n\nTEST(Bootstrap, ServerAcceptGroup2Test) {\n \/\/ Verify that server is using the accept IO group\n\n \/\/ Check if reuse port is supported, if not, don't run this test\n try {\n EventBase base;\n auto serverSocket = AsyncServerSocket::newSocket(&base);\n serverSocket->bind(0);\n serverSocket->listen(0);\n serverSocket->startAccepting();\n serverSocket->setReusePortEnabled(true);\n serverSocket->stopAccepting();\n } catch(...) {\n LOG(INFO) << \"Reuse port probably not supported\";\n return;\n }\n\n TestServer server;\n auto factory = std::make_shared<TestPipelineFactory>();\n server.childPipeline(factory);\n server.group(std::make_shared<IOThreadPoolExecutor>(4), nullptr);\n server.bind(0);\n\n SocketAddress address;\n server.getSockets()[0]->getAddress(&address);\n\n TestClient client;\n client.connect(address);\n EventBaseManager::get()->getEventBase()->loop();\n\n server.stop();\n\n CHECK(factory->pipelines == 1);\n}\n\nTEST(Bootstrap, SharedThreadPool) {\n auto pool = std::make_shared<IOThreadPoolExecutor>(2);\n\n TestServer server;\n auto factory = std::make_shared<TestPipelineFactory>();\n server.childPipeline(factory);\n server.group(pool, pool);\n\n server.bind(0);\n\n SocketAddress address;\n server.getSockets()[0]->getAddress(&address);\n\n TestClient client;\n client.connect(address);\n\n TestClient client2;\n client2.connect(address);\n\n TestClient client3;\n client3.connect(address);\n\n TestClient client4;\n client4.connect(address);\n\n TestClient client5;\n client5.connect(address);\n\n EventBaseManager::get()->getEventBase()->loop();\n\n server.stop();\n CHECK(factory->pipelines == 5);\n}\n<commit_msg>fix bootstrap test on older kernels<commit_after>\/*\n * Copyright 2014 Facebook, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"folly\/wangle\/bootstrap\/ServerBootstrap.h\"\n#include \"folly\/wangle\/bootstrap\/ClientBootstrap.h\"\n#include \"folly\/wangle\/channel\/ChannelHandler.h\"\n\n#include <glog\/logging.h>\n#include <gtest\/gtest.h>\n\nusing namespace folly::wangle;\nusing namespace folly;\n\ntypedef ChannelPipeline<IOBufQueue&, std::unique_ptr<IOBuf>> Pipeline;\n\nclass TestServer : public ServerBootstrap<Pipeline> {\n Pipeline* newPipeline(std::shared_ptr<AsyncSocket>) {\n return nullptr;\n }\n};\n\nclass TestClient : public ClientBootstrap<Pipeline> {\n Pipeline* newPipeline(std::shared_ptr<AsyncSocket> sock) {\n CHECK(sock->good());\n\n \/\/ We probably aren't connected immedately, check after a small delay\n EventBaseManager::get()->getEventBase()->runAfterDelay([sock](){\n CHECK(sock->readable());\n }, 100);\n return nullptr;\n }\n};\n\nclass TestPipelineFactory : public PipelineFactory<Pipeline> {\n public:\n Pipeline* newPipeline(std::shared_ptr<AsyncSocket> sock) {\n pipelines++;\n return new Pipeline();\n }\n std::atomic<int> pipelines{0};\n};\n\nTEST(Bootstrap, Basic) {\n TestServer server;\n TestClient client;\n}\n\nTEST(Bootstrap, ServerWithPipeline) {\n TestServer server;\n server.childPipeline(std::make_shared<TestPipelineFactory>());\n server.bind(0);\n server.stop();\n}\n\nTEST(Bootstrap, ClientServerTest) {\n TestServer server;\n auto factory = std::make_shared<TestPipelineFactory>();\n server.childPipeline(factory);\n server.bind(0);\n auto base = EventBaseManager::get()->getEventBase();\n\n SocketAddress address;\n server.getSockets()[0]->getAddress(&address);\n\n TestClient client;\n client.connect(address);\n base->loop();\n server.stop();\n\n CHECK(factory->pipelines == 1);\n}\n\nTEST(Bootstrap, ClientConnectionManagerTest) {\n \/\/ Create a single IO thread, and verify that\n \/\/ client connections are pooled properly\n\n TestServer server;\n auto factory = std::make_shared<TestPipelineFactory>();\n server.childPipeline(factory);\n server.group(std::make_shared<IOThreadPoolExecutor>(1));\n server.bind(0);\n auto base = EventBaseManager::get()->getEventBase();\n\n SocketAddress address;\n server.getSockets()[0]->getAddress(&address);\n\n TestClient client;\n client.connect(address);\n\n TestClient client2;\n client2.connect(address);\n\n base->loop();\n server.stop();\n\n CHECK(factory->pipelines == 2);\n}\n\nTEST(Bootstrap, ServerAcceptGroupTest) {\n \/\/ Verify that server is using the accept IO group\n\n TestServer server;\n auto factory = std::make_shared<TestPipelineFactory>();\n server.childPipeline(factory);\n server.group(std::make_shared<IOThreadPoolExecutor>(1), nullptr);\n server.bind(0);\n\n SocketAddress address;\n server.getSockets()[0]->getAddress(&address);\n\n boost::barrier barrier(2);\n auto thread = std::thread([&](){\n TestClient client;\n client.connect(address);\n EventBaseManager::get()->getEventBase()->loop();\n barrier.wait();\n });\n barrier.wait();\n server.stop();\n thread.join();\n\n CHECK(factory->pipelines == 1);\n}\n\nTEST(Bootstrap, ServerAcceptGroup2Test) {\n \/\/ Verify that server is using the accept IO group\n\n \/\/ Check if reuse port is supported, if not, don't run this test\n try {\n EventBase base;\n auto serverSocket = AsyncServerSocket::newSocket(&base);\n serverSocket->bind(0);\n serverSocket->listen(0);\n serverSocket->startAccepting();\n serverSocket->setReusePortEnabled(true);\n serverSocket->stopAccepting();\n } catch(...) {\n LOG(INFO) << \"Reuse port probably not supported\";\n return;\n }\n\n TestServer server;\n auto factory = std::make_shared<TestPipelineFactory>();\n server.childPipeline(factory);\n server.group(std::make_shared<IOThreadPoolExecutor>(4), nullptr);\n server.bind(0);\n\n SocketAddress address;\n server.getSockets()[0]->getAddress(&address);\n\n TestClient client;\n client.connect(address);\n EventBaseManager::get()->getEventBase()->loop();\n\n server.stop();\n\n CHECK(factory->pipelines == 1);\n}\n\nTEST(Bootstrap, SharedThreadPool) {\n \/\/ Check if reuse port is supported, if not, don't run this test\n try {\n EventBase base;\n auto serverSocket = AsyncServerSocket::newSocket(&base);\n serverSocket->bind(0);\n serverSocket->listen(0);\n serverSocket->startAccepting();\n serverSocket->setReusePortEnabled(true);\n serverSocket->stopAccepting();\n } catch(...) {\n LOG(INFO) << \"Reuse port probably not supported\";\n return;\n }\n\n auto pool = std::make_shared<IOThreadPoolExecutor>(2);\n\n TestServer server;\n auto factory = std::make_shared<TestPipelineFactory>();\n server.childPipeline(factory);\n server.group(pool, pool);\n\n server.bind(0);\n\n SocketAddress address;\n server.getSockets()[0]->getAddress(&address);\n\n TestClient client;\n client.connect(address);\n\n TestClient client2;\n client2.connect(address);\n\n TestClient client3;\n client3.connect(address);\n\n TestClient client4;\n client4.connect(address);\n\n TestClient client5;\n client5.connect(address);\n\n EventBaseManager::get()->getEventBase()->loop();\n\n server.stop();\n CHECK(factory->pipelines == 5);\n}\n<|endoftext|>"} {"text":"<commit_before>\/****************************************************************\/\n\/* DO NOT MODIFY THIS HEADER *\/\n\/* MOOSE - Multiphysics Object Oriented Simulation Environment *\/\n\/* *\/\n\/* (c) 2010 Battelle Energy Alliance, LLC *\/\n\/* ALL RIGHTS RESERVED *\/\n\/* *\/\n\/* Prepared by Battelle Energy Alliance, LLC *\/\n\/* Under Contract No. DE-AC07-05ID14517 *\/\n\/* With the U. S. Department of Energy *\/\n\/* *\/\n\/* See COPYRIGHT for full restrictions *\/\n\/****************************************************************\/\n\n#include \"AdaptivityAction.h\"\n\n#ifdef LIBMESH_ENABLE_AMR\n\n#include \"FEProblem.h\"\n#include \"NonlinearSystem.h\"\n#include \"Adaptivity.h\"\n#include \"Executioner.h\"\n#include \"MooseEnum.h\"\n\n\/\/ libMesh includes\n#include \"libmesh\/transient_system.h\"\n\ntemplate<>\nInputParameters validParams<AdaptivityAction>()\n{\n InputParameters params = validParams<Action>();\n MooseEnum estimators(\"KellyErrorEstimator LaplacianErrorEstimator PatchRecoveryErrorEstimator\", \"KellyErrorEstimator\");\n\n params.addParam<unsigned int>(\"steps\", 0, \"The number of adaptivity steps to perform at any one time for steady state\");\n params.addParam<unsigned int>(\"initial_adaptivity\", 0, \"The number of adaptivity steps to perform using the initial conditions\");\n params.addParam<Real> (\"refine_fraction\", 0.0, \"The fraction of elements or error to refine. Should be between 0 and 1.\");\n params.addParam<Real> (\"coarsen_fraction\", 0.0, \"The fraction of elements or error to coarsen. Should be between 0 and 1.\");\n params.addParam<unsigned int> (\"max_h_level\", 0, \"Maximum number of times a single element can be refined. If 0 then infinite.\");\n params.addParam<MooseEnum> (\"error_estimator\", estimators, \"The class name of the error estimator you want to use.\");\n params.addDeprecatedParam<bool> (\"print_changed_info\", false,\n \"Determines whether information about the mesh is printed when adaptivity occurs\",\n \"Use the Console output parameter 'print_mesh_changed_info'\");\n params.addParam<Real>(\"start_time\", -std::numeric_limits<Real>::max(), \"The time that adaptivity will be active after.\");\n params.addParam<Real>(\"stop_time\", std::numeric_limits<Real>::max(), \"The time after which adaptivity will no longer be active.\");\n params.addParam<std::vector<std::string> > (\"weight_names\", \"List of names of variables that will be associated with weight_values\");\n params.addParam<std::vector<Real> > (\"weight_values\", \"List of values between 0 and 1 to weight the associated weight_names error by\");\n params.addParam<unsigned int>(\"cycles_per_step\", 1, \"The number of adaptivity cycles per step\");\n\n params.addParam<bool>(\"show_initial_progress\", true, \"Show the progress of the initial adaptivity\");\n return params;\n}\n\nAdaptivityAction::AdaptivityAction(InputParameters params) :\n Action(params)\n{\n}\n\nvoid\nAdaptivityAction::act()\n{\n NonlinearSystem & system = _problem->getNonlinearSystem();\n\n Adaptivity & adapt = _problem->adaptivity();\n\n adapt.init(getParam<unsigned int>(\"steps\"), getParam<unsigned int>(\"initial_adaptivity\"));\n\n adapt.setErrorEstimator(getParam<MooseEnum>(\"error_estimator\"));\n\n adapt.setParam(\"cycles_per_step\", getParam<unsigned int>(\"cycles_per_step\"));\n adapt.setParam(\"refine fraction\", getParam<Real>(\"refine_fraction\"));\n adapt.setParam(\"coarsen fraction\", getParam<Real>(\"coarsen_fraction\"));\n adapt.setParam(\"max h-level\", getParam<unsigned int>(\"max_h_level\"));\n\n adapt.setPrintMeshChanged(getParam<bool>(\"print_changed_info\"));\n\n const std::vector<std::string> & weight_names = getParam<std::vector<std::string> >(\"weight_names\");\n const std::vector<Real> & weight_values = getParam<std::vector<Real> >(\"weight_values\");\n\n int num_weight_names = weight_names.size();\n int num_weight_values = weight_values.size();\n\n if (num_weight_names)\n {\n if (num_weight_names != num_weight_values)\n mooseError(\"Number of weight_names must be equal to number of weight_values in Execution\/Adaptivity\");\n\n \/\/ If weights have been specified then set the default weight to zero\n std::vector<Real> weights(system.nVariables(),0);\n\n for (int i=0;i<num_weight_names;i++)\n {\n std::string name = weight_names[i];\n double value = weight_values[i];\n\n weights[system.getVariable(0, name).number()] = value;\n }\n\n std::vector<FEMNormType> norms(system.nVariables(), H1_SEMINORM);\n\n SystemNorm sys_norm(norms, weights);\n\n adapt.setErrorNorm(sys_norm);\n }\n\n adapt.setTimeActive(getParam<Real>(\"start_time\"), getParam<Real>(\"stop_time\"));\n}\n\n#endif \/\/LIBMESH_ENABLE_AMR\n<commit_msg>AdaptivityAction didn't get a deprecated constructor.<commit_after>\/****************************************************************\/\n\/* DO NOT MODIFY THIS HEADER *\/\n\/* MOOSE - Multiphysics Object Oriented Simulation Environment *\/\n\/* *\/\n\/* (c) 2010 Battelle Energy Alliance, LLC *\/\n\/* ALL RIGHTS RESERVED *\/\n\/* *\/\n\/* Prepared by Battelle Energy Alliance, LLC *\/\n\/* Under Contract No. DE-AC07-05ID14517 *\/\n\/* With the U. S. Department of Energy *\/\n\/* *\/\n\/* See COPYRIGHT for full restrictions *\/\n\/****************************************************************\/\n\n#include \"AdaptivityAction.h\"\n\n#ifdef LIBMESH_ENABLE_AMR\n\n#include \"FEProblem.h\"\n#include \"NonlinearSystem.h\"\n#include \"Adaptivity.h\"\n#include \"Executioner.h\"\n#include \"MooseEnum.h\"\n\n\/\/ libMesh includes\n#include \"libmesh\/transient_system.h\"\n\ntemplate<>\nInputParameters validParams<AdaptivityAction>()\n{\n InputParameters params = validParams<Action>();\n MooseEnum estimators(\"KellyErrorEstimator LaplacianErrorEstimator PatchRecoveryErrorEstimator\", \"KellyErrorEstimator\");\n\n params.addParam<unsigned int>(\"steps\", 0, \"The number of adaptivity steps to perform at any one time for steady state\");\n params.addParam<unsigned int>(\"initial_adaptivity\", 0, \"The number of adaptivity steps to perform using the initial conditions\");\n params.addParam<Real> (\"refine_fraction\", 0.0, \"The fraction of elements or error to refine. Should be between 0 and 1.\");\n params.addParam<Real> (\"coarsen_fraction\", 0.0, \"The fraction of elements or error to coarsen. Should be between 0 and 1.\");\n params.addParam<unsigned int> (\"max_h_level\", 0, \"Maximum number of times a single element can be refined. If 0 then infinite.\");\n params.addParam<MooseEnum> (\"error_estimator\", estimators, \"The class name of the error estimator you want to use.\");\n params.addDeprecatedParam<bool> (\"print_changed_info\", false,\n \"Determines whether information about the mesh is printed when adaptivity occurs\",\n \"Use the Console output parameter 'print_mesh_changed_info'\");\n params.addParam<Real>(\"start_time\", -std::numeric_limits<Real>::max(), \"The time that adaptivity will be active after.\");\n params.addParam<Real>(\"stop_time\", std::numeric_limits<Real>::max(), \"The time after which adaptivity will no longer be active.\");\n params.addParam<std::vector<std::string> > (\"weight_names\", \"List of names of variables that will be associated with weight_values\");\n params.addParam<std::vector<Real> > (\"weight_values\", \"List of values between 0 and 1 to weight the associated weight_names error by\");\n params.addParam<unsigned int>(\"cycles_per_step\", 1, \"The number of adaptivity cycles per step\");\n\n params.addParam<bool>(\"show_initial_progress\", true, \"Show the progress of the initial adaptivity\");\n return params;\n}\n\nAdaptivityAction::AdaptivityAction(InputParameters params) :\n Action(params)\n{\n}\n\nvoid\nAdaptivityAction::act()\n{\n NonlinearSystem & system = _problem->getNonlinearSystem();\n\n Adaptivity & adapt = _problem->adaptivity();\n\n adapt.init(getParam<unsigned int>(\"steps\"), getParam<unsigned int>(\"initial_adaptivity\"));\n\n adapt.setErrorEstimator(getParam<MooseEnum>(\"error_estimator\"));\n\n adapt.setParam(\"cycles_per_step\", getParam<unsigned int>(\"cycles_per_step\"));\n adapt.setParam(\"refine fraction\", getParam<Real>(\"refine_fraction\"));\n adapt.setParam(\"coarsen fraction\", getParam<Real>(\"coarsen_fraction\"));\n adapt.setParam(\"max h-level\", getParam<unsigned int>(\"max_h_level\"));\n\n adapt.setPrintMeshChanged(getParam<bool>(\"print_changed_info\"));\n\n const std::vector<std::string> & weight_names = getParam<std::vector<std::string> >(\"weight_names\");\n const std::vector<Real> & weight_values = getParam<std::vector<Real> >(\"weight_values\");\n\n int num_weight_names = weight_names.size();\n int num_weight_values = weight_values.size();\n\n if (num_weight_names)\n {\n if (num_weight_names != num_weight_values)\n mooseError(\"Number of weight_names must be equal to number of weight_values in Execution\/Adaptivity\");\n\n \/\/ If weights have been specified then set the default weight to zero\n std::vector<Real> weights(system.nVariables(),0);\n\n for (int i=0;i<num_weight_names;i++)\n {\n std::string name = weight_names[i];\n double value = weight_values[i];\n\n weights[system.getVariable(0, name).number()] = value;\n }\n\n std::vector<FEMNormType> norms(system.nVariables(), H1_SEMINORM);\n\n SystemNorm sys_norm(norms, weights);\n\n adapt.setErrorNorm(sys_norm);\n }\n\n adapt.setTimeActive(getParam<Real>(\"start_time\"), getParam<Real>(\"stop_time\"));\n}\n\n\/\/ DEPRECATED CONSTRUCTOR\nAdaptivityAction::AdaptivityAction(const std::string & deprecated_name, InputParameters params) :\n Action(deprecated_name, params)\n{\n}\n\n#endif \/\/LIBMESH_ENABLE_AMR\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright(c) 2016 Jounayd Id Salah\n\/\/ Distributed under the MIT License (See accompanying file LICENSE.md file or copy at http:\/\/opensource.org\/licenses\/MIT).\n#include \"memory\/pch.h\"\n#include \"memory\/allocator\/coLocalAllocator.h\"\n#include \"debug\/log\/coAssert.h\"\n#include \"debug\/log\/coLog.h\"\n\ncoLocalAllocator::coLocalAllocator(coUint32 _maxStackAlloc)\n\t: stackBuffer(nullptr)\n\t, allocatedStackSize8(0)\n\t, maxStackAlloc(_maxStackAlloc)\n{\n\tcoASSERT(maxStackAlloc < 16 * 1024); \/\/ safety\n\tcoAllocator* stackAllocator = coAllocator::GetStack();\n\tcoASSERT(stackAllocator);\n\tstackBuffer = static_cast<coByte*>(stackAllocator->Allocate(_maxStackAlloc));\n\tcoASSERT(stackBuffer);\n\n\tcoTODO(\"Check for memory leaks\");\n}\n\ncoLocalAllocator::~coLocalAllocator()\n{\n\tcoAllocator* stackAllocator = coAllocator::GetStack();\n\tstackAllocator->Free(stackBuffer);\n}\n\nvoid* coLocalAllocator::Allocate(coUint32 _size8)\n{\n\tconst coUint32 newStackAllocated = allocatedStackSize8 + _size8;\n\tif (newStackAllocated <= maxStackAlloc)\n\t{\n\t\tvoid* p = stackBuffer + allocatedStackSize8;\n\t\tallocatedStackSize8 = newStackAllocated;\n\t\treturn p;\n\t}\n\telse\n\t{\n\t\tcoAllocator* defaultAllocator = coAllocator::GetHeap();\n\t\tcoASSERT(defaultAllocator);\n\t\treturn defaultAllocator->Allocate(_size8);\n\t}\n}\n\nvoid* coLocalAllocator::AllocateAligned(coUint32 \/*_size8*\/, coUint \/*_alignment*\/)\n{\n\tcoWARN_NOT_AVAILABLE();\n\treturn nullptr;\n}\n\nvoid coLocalAllocator::Free(void* _p)\n{\n\tif (_p < stackBuffer || _p >= (stackBuffer + maxStackAlloc))\n\t{\n\t\tcoAllocator* defaultAllocator = coAllocator::GetHeap();\n\t\tcoASSERT(defaultAllocator);\n\t\tdefaultAllocator->Free(_p);\n\t}\n}\n\nvoid coLocalAllocator::FreeAligned(void* _p)\n{\n\tif (_p < stackBuffer || _p >= (stackBuffer + maxStackAlloc))\n\t{\n\t\tcoAllocator* defaultAllocator = coAllocator::GetHeap();\n\t\tcoASSERT(defaultAllocator);\n\t\tdefaultAllocator->FreeAligned(_p);\n\t}\n}\n<commit_msg>Added aligned local alloc implementation.<commit_after>\/\/ Copyright(c) 2016 Jounayd Id Salah\n\/\/ Distributed under the MIT License (See accompanying file LICENSE.md file or copy at http:\/\/opensource.org\/licenses\/MIT).\n#include \"memory\/pch.h\"\n#include \"memory\/allocator\/coLocalAllocator.h\"\n#include \"debug\/log\/coAssert.h\"\n#include \"debug\/log\/coLog.h\"\n\ncoLocalAllocator::coLocalAllocator(coUint32 _maxStackAlloc)\n\t: stackBuffer(nullptr)\n\t, allocatedStackSize8(0)\n\t, maxStackAlloc(_maxStackAlloc)\n{\n\tcoASSERT(maxStackAlloc < 16 * 1024); \/\/ safety\n\tcoAllocator* stackAllocator = coAllocator::GetStack();\n\tcoASSERT(stackAllocator);\n\tstackBuffer = static_cast<coByte*>(stackAllocator->Allocate(_maxStackAlloc));\n\tcoASSERT(stackBuffer);\n\n\tcoTODO(\"Check for memory leaks\");\n}\n\ncoLocalAllocator::~coLocalAllocator()\n{\n\tcoAllocator* stackAllocator = coAllocator::GetStack();\n\tstackAllocator->Free(stackBuffer);\n}\n\nvoid* coLocalAllocator::Allocate(coUint32 _size8)\n{\n\tconst coUint32 newStackAllocated = allocatedStackSize8 + _size8;\n\tif (newStackAllocated <= maxStackAlloc)\n\t{\n\t\tvoid* p = stackBuffer + allocatedStackSize8;\n\t\tallocatedStackSize8 = newStackAllocated;\n\t\treturn p;\n\t}\n\telse\n\t{\n\t\tcoAllocator* defaultAllocator = coAllocator::GetHeap();\n\t\tcoASSERT(defaultAllocator);\n\t\treturn defaultAllocator->Allocate(_size8);\n\t}\n}\n\nvoid* coLocalAllocator::AllocateAligned(coUint32 _size8, coUint _alignment)\n{\n\tconst coUint32 newStackAllocated = allocatedStackSize8 + _size8 + _alignment;\n\tif (newStackAllocated <= maxStackAlloc)\n\t{\n\t\tvoid* buffer = stackBuffer + allocatedStackSize8;\n\t\tvoid* p = reinterpret_cast<void*>((reinterpret_cast<coIntPtr>(buffer) & ~(coIntPtr(_alignment - 1))) + _alignment);\n\t\t\/\/*(reinterpret_cast<void**>(p) - 1) = buffer;\n\t\tallocatedStackSize8 = newStackAllocated;\n\t\treturn p;\n\t}\n\telse\n\t{\n\t\tcoAllocator* defaultAllocator = coAllocator::GetHeap();\n\t\tcoASSERT(defaultAllocator);\n\t\treturn defaultAllocator->AllocateAligned(_size8, _alignment);\n\t}\n}\n\nvoid coLocalAllocator::Free(void* _p)\n{\n\tif (_p < stackBuffer || _p >= (stackBuffer + maxStackAlloc))\n\t{\n\t\tcoAllocator* defaultAllocator = coAllocator::GetHeap();\n\t\tcoASSERT(defaultAllocator);\n\t\tdefaultAllocator->Free(_p);\n\t}\n}\n\nvoid coLocalAllocator::FreeAligned(void* _p)\n{\n\tif (_p < stackBuffer || _p >= (stackBuffer + maxStackAlloc))\n\t{\n\t\tcoAllocator* defaultAllocator = coAllocator::GetHeap();\n\t\tcoASSERT(defaultAllocator);\n\t\tdefaultAllocator->FreeAligned(_p);\n\t}\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n *\n * Copyright 2015-2016, Google Inc.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following disclaimer\n * in the documentation and\/or other materials provided with the\n * distribution.\n * * Neither the name of Google Inc. nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n *\/\n\n#include <mutex>\n#include <thread>\n\n#include <grpc++\/channel.h>\n#include <grpc++\/client_context.h>\n#include <grpc++\/create_channel.h>\n#include <grpc++\/server.h>\n#include <grpc++\/server_builder.h>\n#include <grpc++\/server_context.h>\n#include <grpc\/grpc.h>\n#include <grpc\/support\/thd.h>\n#include <grpc\/support\/time.h>\n#include <gtest\/gtest.h>\n\n#include \"src\/proto\/grpc\/testing\/duplicate\/echo_duplicate.grpc.pb.h\"\n#include \"src\/proto\/grpc\/testing\/echo.grpc.pb.h\"\n#include \"test\/core\/util\/port.h\"\n#include \"test\/core\/util\/test_config.h\"\n\nusing grpc::testing::EchoRequest;\nusing grpc::testing::EchoResponse;\nusing std::chrono::system_clock;\n\nnamespace grpc {\nnamespace testing {\n\nnamespace {\n\n\/\/ When echo_deadline is requested, deadline seen in the ServerContext is set in\n\/\/ the response in seconds.\nvoid MaybeEchoDeadline(ServerContext* context, const EchoRequest* request,\n EchoResponse* response) {\n if (request->has_param() && request->param().echo_deadline()) {\n gpr_timespec deadline = gpr_inf_future(GPR_CLOCK_REALTIME);\n if (context->deadline() != system_clock::time_point::max()) {\n Timepoint2Timespec(context->deadline(), &deadline);\n }\n response->mutable_param()->set_request_deadline(deadline.tv_sec);\n }\n}\n\n} \/\/ namespace\n\nclass TestServiceImpl : public ::grpc::testing::EchoTestService::Service {\n public:\n TestServiceImpl() : signal_client_(false) {}\n\n Status Echo(ServerContext* context, const EchoRequest* request,\n EchoResponse* response) GRPC_OVERRIDE {\n response->set_message(request->message());\n MaybeEchoDeadline(context, request, response);\n if (request->has_param() && request->param().client_cancel_after_us()) {\n {\n std::unique_lock<std::mutex> lock(mu_);\n signal_client_ = true;\n }\n while (!context->IsCancelled()) {\n gpr_sleep_until(gpr_time_add(\n gpr_now(GPR_CLOCK_REALTIME),\n gpr_time_from_micros(request->param().client_cancel_after_us(),\n GPR_TIMESPAN)));\n }\n return Status::CANCELLED;\n } else if (request->has_param() &&\n request->param().server_cancel_after_us()) {\n gpr_sleep_until(gpr_time_add(\n gpr_now(GPR_CLOCK_REALTIME),\n gpr_time_from_micros(request->param().server_cancel_after_us(),\n GPR_TIMESPAN)));\n return Status::CANCELLED;\n } else {\n EXPECT_FALSE(context->IsCancelled());\n }\n return Status::OK;\n }\n\n \/\/ Unimplemented is left unimplemented to test the returned error.\n\n Status RequestStream(ServerContext* context,\n ServerReader<EchoRequest>* reader,\n EchoResponse* response) GRPC_OVERRIDE {\n EchoRequest request;\n response->set_message(\"\");\n while (reader->Read(&request)) {\n response->mutable_message()->append(request.message());\n }\n return Status::OK;\n }\n\n \/\/ Return 3 messages.\n \/\/ TODO(yangg) make it generic by adding a parameter into EchoRequest\n Status ResponseStream(ServerContext* context, const EchoRequest* request,\n ServerWriter<EchoResponse>* writer) GRPC_OVERRIDE {\n EchoResponse response;\n response.set_message(request->message() + \"0\");\n writer->Write(response);\n response.set_message(request->message() + \"1\");\n writer->Write(response);\n response.set_message(request->message() + \"2\");\n writer->Write(response);\n\n return Status::OK;\n }\n\n Status BidiStream(ServerContext* context,\n ServerReaderWriter<EchoResponse, EchoRequest>* stream)\n GRPC_OVERRIDE {\n EchoRequest request;\n EchoResponse response;\n while (stream->Read(&request)) {\n gpr_log(GPR_INFO, \"recv msg %s\", request.message().c_str());\n response.set_message(request.message());\n stream->Write(response);\n }\n return Status::OK;\n }\n\n bool signal_client() {\n std::unique_lock<std::mutex> lock(mu_);\n return signal_client_;\n }\n\n private:\n bool signal_client_;\n std::mutex mu_;\n};\n\nclass TestServiceImplDupPkg\n : public ::grpc::testing::duplicate::EchoTestService::Service {\n public:\n Status Echo(ServerContext* context, const EchoRequest* request,\n EchoResponse* response) GRPC_OVERRIDE {\n response->set_message(\"no package\");\n return Status::OK;\n }\n};\n\nclass AsyncClientEnd2endTest : public ::testing::Test {\n protected:\n AsyncClientEnd2endTest() : kMaxMessageSize_(8192), rpcs_outstanding_(0) {}\n\n void SetUp() GRPC_OVERRIDE {\n int port = grpc_pick_unused_port_or_die();\n server_address_ << \"localhost:\" << port;\n \/\/ Setup server\n ServerBuilder builder;\n builder.AddListeningPort(server_address_.str(),\n InsecureServerCredentials());\n builder.RegisterService(&service_);\n builder.SetMaxMessageSize(\n kMaxMessageSize_); \/\/ For testing max message size.\n server_ = builder.BuildAndStart();\n }\n\n void TearDown() GRPC_OVERRIDE { server_->Shutdown(); }\n\n void ResetStub() {\n std::shared_ptr<Channel> channel =\n CreateChannel(server_address_.str(), InsecureChannelCredentials());\n stub_ = grpc::testing::EchoTestService::NewStub(channel);\n }\n\n void Wait() {\n std::unique_lock<std::mutex> l(mu_);\n while (rpcs_outstanding_ != 0) {\n cv_.wait(l);\n }\n\n cq_.Shutdown();\n }\n\n struct AsyncClientCall {\n EchoResponse response;\n ClientContext context;\n Status status;\n std::unique_ptr<ClientAsyncResponseReader<EchoResponse>> response_reader;\n };\n\n void AsyncSendRpc(int num_rpcs) {\n for (int i = 0; i < num_rpcs; ++i) {\n AsyncClientCall* call = new AsyncClientCall;\n EchoRequest request;\n request.set_message(std::to_string(i));\n call->response_reader = stub_->AsyncEcho(&call->context, request, &cq_);\n call->response_reader->Finish(&call->response, &call->status,\n (void*)call);\n\n std::unique_lock<std::mutex> l(mu_);\n rpcs_outstanding_++;\n }\n }\n\n void AsyncCompleteRpc() {\n while (true) {\n void* got_tag;\n bool ok = false;\n if (!cq_.Next(&got_tag, &ok)) break;\n Call* call = static_cast<Call*>(got_tag);\n GPR_ASSERT(ok);\n delete call;\n\n bool notify;\n {\n std::unique_lock<std::mutex> l(mu_);\n rpcs_outstanding_--;\n notify = (rpcs_outstanding_ == 0);\n }\n if (notify) {\n cv_.notify_all();\n }\n }\n }\n\n std::unique_ptr<grpc::testing::EchoTestService::Stub> stub_;\n std::unique_ptr<Server> server_;\n std::ostringstream server_address_;\n const int kMaxMessageSize_;\n TestServiceImpl service_;\n\n CompletionQueue cq_;\n std::mutex mu_;\n std::condition_variable cv_;\n int rpcs_outstanding_;\n};\n\nTEST_F(AsyncClientEnd2endTest, ThreadStress) {\n ResetStub();\n std::vector<std::thread*> threads;\n for (int i = 0; i < 100; ++i) {\n threads.push_back(new std::thread(\n &AsyncClientEnd2endTest_ThreadStress_Test::AsyncSendRpc, this, 1000));\n }\n for (int i = 0; i < 100; ++i) {\n threads[i]->join();\n delete threads[i];\n }\n\n threads.clear();\n\n for (int i = 0; i < 100; ++i) {\n threads.push_back(new std::thread(\n &AsyncClientEnd2endTest_ThreadStress_Test::AsyncCompleteRpc, this));\n }\n Wait();\n for (int i = 0; i < 100; ++i) {\n threads[i]->join();\n delete threads[i];\n }\n}\n\n} \/\/ namespace testing\n} \/\/ namespace grpc\n\nint main(int argc, char** argv) {\n grpc_test_init(argc, argv);\n ::testing::InitGoogleTest(&argc, argv);\n return RUN_ALL_TESTS();\n}\n<commit_msg>Trim some unused code copied from another test.<commit_after>\/*\n *\n * Copyright 2015-2016, Google Inc.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following disclaimer\n * in the documentation and\/or other materials provided with the\n * distribution.\n * * Neither the name of Google Inc. nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n *\/\n\n#include <mutex>\n#include <thread>\n\n#include <grpc++\/channel.h>\n#include <grpc++\/client_context.h>\n#include <grpc++\/create_channel.h>\n#include <grpc++\/server.h>\n#include <grpc++\/server_builder.h>\n#include <grpc++\/server_context.h>\n#include <grpc\/grpc.h>\n#include <grpc\/support\/thd.h>\n#include <grpc\/support\/time.h>\n#include <gtest\/gtest.h>\n\n#include \"src\/proto\/grpc\/testing\/duplicate\/echo_duplicate.grpc.pb.h\"\n#include \"src\/proto\/grpc\/testing\/echo.grpc.pb.h\"\n#include \"test\/core\/util\/port.h\"\n#include \"test\/core\/util\/test_config.h\"\n\nusing grpc::testing::EchoRequest;\nusing grpc::testing::EchoResponse;\nusing std::chrono::system_clock;\n\nnamespace grpc {\nnamespace testing {\n\nnamespace {\n\n\/\/ When echo_deadline is requested, deadline seen in the ServerContext is set in\n\/\/ the response in seconds.\nvoid MaybeEchoDeadline(ServerContext* context, const EchoRequest* request,\n EchoResponse* response) {\n if (request->has_param() && request->param().echo_deadline()) {\n gpr_timespec deadline = gpr_inf_future(GPR_CLOCK_REALTIME);\n if (context->deadline() != system_clock::time_point::max()) {\n Timepoint2Timespec(context->deadline(), &deadline);\n }\n response->mutable_param()->set_request_deadline(deadline.tv_sec);\n }\n}\n\n} \/\/ namespace\n\nclass TestServiceImpl : public ::grpc::testing::EchoTestService::Service {\n public:\n TestServiceImpl() : signal_client_(false) {}\n\n Status Echo(ServerContext* context, const EchoRequest* request,\n EchoResponse* response) GRPC_OVERRIDE {\n response->set_message(request->message());\n MaybeEchoDeadline(context, request, response);\n if (request->has_param() && request->param().client_cancel_after_us()) {\n {\n std::unique_lock<std::mutex> lock(mu_);\n signal_client_ = true;\n }\n while (!context->IsCancelled()) {\n gpr_sleep_until(gpr_time_add(\n gpr_now(GPR_CLOCK_REALTIME),\n gpr_time_from_micros(request->param().client_cancel_after_us(),\n GPR_TIMESPAN)));\n }\n return Status::CANCELLED;\n } else if (request->has_param() &&\n request->param().server_cancel_after_us()) {\n gpr_sleep_until(gpr_time_add(\n gpr_now(GPR_CLOCK_REALTIME),\n gpr_time_from_micros(request->param().server_cancel_after_us(),\n GPR_TIMESPAN)));\n return Status::CANCELLED;\n } else {\n EXPECT_FALSE(context->IsCancelled());\n }\n return Status::OK;\n }\n\n bool signal_client() {\n std::unique_lock<std::mutex> lock(mu_);\n return signal_client_;\n }\n\n private:\n bool signal_client_;\n std::mutex mu_;\n};\n\nclass AsyncClientEnd2endTest : public ::testing::Test {\n protected:\n AsyncClientEnd2endTest() : kMaxMessageSize_(8192), rpcs_outstanding_(0) {}\n\n void SetUp() GRPC_OVERRIDE {\n int port = grpc_pick_unused_port_or_die();\n server_address_ << \"localhost:\" << port;\n \/\/ Setup server\n ServerBuilder builder;\n builder.AddListeningPort(server_address_.str(),\n InsecureServerCredentials());\n builder.RegisterService(&service_);\n builder.SetMaxMessageSize(\n kMaxMessageSize_); \/\/ For testing max message size.\n server_ = builder.BuildAndStart();\n }\n\n void TearDown() GRPC_OVERRIDE { server_->Shutdown(); }\n\n void ResetStub() {\n std::shared_ptr<Channel> channel =\n CreateChannel(server_address_.str(), InsecureChannelCredentials());\n stub_ = grpc::testing::EchoTestService::NewStub(channel);\n }\n\n void Wait() {\n std::unique_lock<std::mutex> l(mu_);\n while (rpcs_outstanding_ != 0) {\n cv_.wait(l);\n }\n\n cq_.Shutdown();\n }\n\n struct AsyncClientCall {\n EchoResponse response;\n ClientContext context;\n Status status;\n std::unique_ptr<ClientAsyncResponseReader<EchoResponse>> response_reader;\n };\n\n void AsyncSendRpc(int num_rpcs) {\n for (int i = 0; i < num_rpcs; ++i) {\n AsyncClientCall* call = new AsyncClientCall;\n EchoRequest request;\n request.set_message(std::to_string(i));\n call->response_reader = stub_->AsyncEcho(&call->context, request, &cq_);\n call->response_reader->Finish(&call->response, &call->status,\n (void*)call);\n\n std::unique_lock<std::mutex> l(mu_);\n rpcs_outstanding_++;\n }\n }\n\n void AsyncCompleteRpc() {\n while (true) {\n void* got_tag;\n bool ok = false;\n if (!cq_.Next(&got_tag, &ok)) break;\n Call* call = static_cast<Call*>(got_tag);\n GPR_ASSERT(ok);\n delete call;\n\n bool notify;\n {\n std::unique_lock<std::mutex> l(mu_);\n rpcs_outstanding_--;\n notify = (rpcs_outstanding_ == 0);\n }\n if (notify) {\n cv_.notify_all();\n }\n }\n }\n\n std::unique_ptr<grpc::testing::EchoTestService::Stub> stub_;\n std::unique_ptr<Server> server_;\n std::ostringstream server_address_;\n const int kMaxMessageSize_;\n TestServiceImpl service_;\n\n CompletionQueue cq_;\n std::mutex mu_;\n std::condition_variable cv_;\n int rpcs_outstanding_;\n};\n\nTEST_F(AsyncClientEnd2endTest, ThreadStress) {\n ResetStub();\n std::vector<std::thread*> threads;\n for (int i = 0; i < 100; ++i) {\n threads.push_back(new std::thread(\n &AsyncClientEnd2endTest_ThreadStress_Test::AsyncSendRpc, this, 1000));\n }\n for (int i = 0; i < 100; ++i) {\n threads[i]->join();\n delete threads[i];\n }\n\n threads.clear();\n\n for (int i = 0; i < 100; ++i) {\n threads.push_back(new std::thread(\n &AsyncClientEnd2endTest_ThreadStress_Test::AsyncCompleteRpc, this));\n }\n Wait();\n for (int i = 0; i < 100; ++i) {\n threads[i]->join();\n delete threads[i];\n }\n}\n\n} \/\/ namespace testing\n} \/\/ namespace grpc\n\nint main(int argc, char** argv) {\n grpc_test_init(argc, argv);\n ::testing::InitGoogleTest(&argc, argv);\n return RUN_ALL_TESTS();\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * iapitest - test pluggable apis\n*\/\n#include \"irods_client_api_table.hpp\"\n#include \"irods_pack_table.hpp\"\n#include \"rodsClient.hpp\"\n#include \"parseCommandLine.hpp\"\n#include \"rodsPath.hpp\"\n#include \"lsUtil.hpp\"\n#include \"irods_buffer_encryption.hpp\"\n#include <string>\n#include <iostream>\n\n\n\/\/ =-=-=-=-=-=-=-\n\/\/ NOTE:: these track the same structs in\n\/\/ :: the api example libhelloworld.cpp\ntypedef struct {\n int _this;\n char _that [64];\n} helloInp_t;\n\ntypedef struct {\n double _value;\n} otherOut_t;\n\ntypedef struct {\n int _this;\n char _that [64];\n otherOut_t _other;\n} helloOut_t;\n\nvoid usage();\n\nint\nmain( int argc, char **argv ) {\n\n rodsEnv myEnv;\n int status = getRodsEnv( &myEnv );\n if ( status < 0 ) {\n rodsLogError( LOG_ERROR, status, \"main: getRodsEnv error. \" );\n exit( 1 );\n }\n\n rErrMsg_t errMsg;\n rcComm_t *conn;\n conn = rcConnect(\n myEnv.rodsHost,\n myEnv.rodsPort,\n myEnv.rodsUserName,\n myEnv.rodsZone,\n 0, &errMsg );\n\n if ( conn == NULL ) {\n exit( 2 );\n }\n\n \/\/ =-=-=-=-=-=-=-\n \/\/ initialize pluggable api table\n irods::pack_entry_table& pk_tbl = irods::get_pack_table();\n irods::api_entry_table& api_tbl = irods::get_client_api_table();\n init_api_table( api_tbl, pk_tbl );\n\n if ( strcmp( myEnv.rodsUserName, PUBLIC_USER_NAME ) != 0 ) {\n status = clientLogin( conn );\n if ( status != 0 ) {\n rcDisconnect( conn );\n exit( 7 );\n }\n }\n\n helloInp_t inp;\n memset( &inp, 0, sizeof( inp ) );\n inp._this = 42;\n strncpy( inp._that, \"hello, world.\", 64 );\n\n helloOut_t* out = 0;\n void* tmp_out = static_cast< void* >( out );\n status = procApiRequest( conn, 1300, &inp, NULL,\n &tmp_out, NULL );\n if ( status < 0 ) {\n printf( \"\\n\\nERROR - failed to call our api\\n\\n\\n\" );\n return 0;\n }\n else {\n if ( out != NULL ) {\n printf( \"\\n\\nthis [%d] that [%s] other [%f]\\n\", out->_this, out->_that, out->_other._value );\n }\n }\n\n rcDisconnect( conn );\n}\n\n<commit_msg>[#2014] additional updates to iapitest<commit_after>\/*\n * iapitest - test pluggable apis\n*\/\n#include \"irods_client_api_table.hpp\"\n#include \"irods_pack_table.hpp\"\n#include \"rodsClient.hpp\"\n#include \"parseCommandLine.hpp\"\n#include \"rodsPath.hpp\"\n#include \"lsUtil.hpp\"\n#include \"irods_buffer_encryption.hpp\"\n#include <string>\n#include <iostream>\n\n\n\/\/ =-=-=-=-=-=-=-\n\/\/ NOTE:: these track the same structs in\n\/\/ :: the api example libhelloworld.cpp\ntypedef struct {\n int _this;\n char _that [64];\n} helloInp_t;\n\ntypedef struct {\n double _value;\n} otherOut_t;\n\ntypedef struct {\n int _this;\n char _that [64];\n otherOut_t _other;\n} helloOut_t;\n\nvoid usage();\n\nint\nmain( int argc, char **argv ) {\n\n rodsEnv myEnv;\n int status = getRodsEnv( &myEnv );\n if ( status < 0 ) {\n rodsLogError( LOG_ERROR, status, \"main: getRodsEnv error. \" );\n exit( 1 );\n }\n\n rErrMsg_t errMsg;\n rcComm_t *conn;\n conn = rcConnect(\n myEnv.rodsHost,\n myEnv.rodsPort,\n myEnv.rodsUserName,\n myEnv.rodsZone,\n 0, &errMsg );\n\n if ( conn == NULL ) {\n exit( 2 );\n }\n\n \/\/ =-=-=-=-=-=-=-\n \/\/ initialize pluggable api table\n irods::pack_entry_table& pk_tbl = irods::get_pack_table();\n irods::api_entry_table& api_tbl = irods::get_client_api_table();\n init_api_table( api_tbl, pk_tbl );\n\n if ( strcmp( myEnv.rodsUserName, PUBLIC_USER_NAME ) != 0 ) {\n status = clientLogin( conn );\n if ( status != 0 ) {\n rcDisconnect( conn );\n exit( 7 );\n }\n }\n\n helloInp_t inp;\n memset( &inp, 0, sizeof( inp ) );\n inp._this = 42;\n strncpy( inp._that, \"hello, world.\", 64 );\n\n helloOut_t* out = 0;\n void* tmp_out = static_cast< void* >( out );\n status = procApiRequest( conn, 1300, &inp, NULL,\n &( tmp_out ), NULL );\n if ( status < 0 ) {\n printf( \"\\n\\nERROR - failed to call our api\\n\\n\\n\" );\n return 0;\n }\n else {\n if ( out != NULL ) {\n printf( \"\\n\\nthis [%d] that [%s] other [%f]\\n\", out->_this, out->_that, out->_other._value );\n }\n }\n\n rcDisconnect( conn );\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n Kopete Yahoo Protocol\n Notifies about incoming filetransfers\n\n Copyright (c) 2006 André Duffeck <andre.duffeck@kdemail.net>\n\n *************************************************************************\n * *\n * This library is free software; you can redistribute it and\/or *\n * modify it under the terms of the GNU Lesser General Public *\n * License as published by the Free Software Foundation; either *\n * version 2 of the License, or (at your option) any later version. *\n * *\n *************************************************************************\n*\/\n\n#include \"filetransfernotifiertask.h\"\n#include \"transfer.h\"\n#include \"ymsgtransfer.h\"\n#include \"yahootypes.h\"\n#include \"client.h\"\n#include <QString>\n#include <QFile>\n#include <QPixmap>\n#include <kdebug.h>\n#include <kcodecs.h>\n\nFileTransferNotifierTask::FileTransferNotifierTask(Task* parent) : Task(parent)\n{\n\tkDebug(YAHOO_RAW_DEBUG) << k_funcinfo << endl;\n}\n\nFileTransferNotifierTask::~FileTransferNotifierTask()\n{\n\n}\n\nbool FileTransferNotifierTask::take( Transfer* transfer )\n{\n\tkDebug(YAHOO_RAW_DEBUG) << k_funcinfo << endl;\n\t\n\tif ( !forMe( transfer ) )\n\t\treturn false;\n\t\n\tYMSGTransfer *t = static_cast<YMSGTransfer*>(transfer);\n\n\tif( t->service() == Yahoo::ServiceFileTransfer )\n\t\tparseFileTransfer( t );\n\telse if( t->service() == Yahoo::ServiceFileTransfer7 )\n\t\tparseFileTransfer7( t );\n\telse if( t->service() == Yahoo::ServicePeerToPeer )\n\t\tacceptFileTransfer( t );\n\t\t\n\n\treturn true;\n}\n\nbool FileTransferNotifierTask::forMe( const Transfer *transfer ) const\n{\n\tkDebug(YAHOO_RAW_DEBUG) << k_funcinfo << endl;\n\tconst YMSGTransfer *t = 0L;\n\tt = dynamic_cast<const YMSGTransfer*>(transfer);\n\tif (!t)\n\t\treturn false;\n\n\n\tif( t->service() == Yahoo::ServiceP2PFileXfer ||\n\t\tt->service() == Yahoo::ServicePeerToPeer ||\n\t\tt->service() == Yahoo::ServiceFileTransfer ||\n\t\tt->service() == Yahoo::ServiceFileTransfer7\n\t)\n\t\treturn true;\n\telse\n\t\treturn false;\n}\n\nvoid FileTransferNotifierTask::parseFileTransfer( YMSGTransfer *t )\n{\n\tkDebug(YAHOO_RAW_DEBUG) << k_funcinfo << endl;\n\n\tQString from;\t\t\/* key = 4 *\/\n\tQString to;\t\t\/* key = 5 *\/\n\tQString url;\t\t\/* key = 20 *\/\n\tlong expires;\t\t\/* key = 38 *\/\n\tQString msg;\t\t\/* key = 14 *\/\n\tQString filename;\t\/* key = 27 *\/\n\tunsigned long size;\t\/* key = 28 *\/\n\n\tfrom = t->firstParam( 4 );\n\tto = t->firstParam( 5 );\n\turl = t->firstParam( 20 );\n\texpires = t->firstParam( 38 ).toLong();\n\tmsg = t->firstParam( 14 );\n\tfilename = t->firstParam( 27 );\n\tsize = t->firstParam( 28 ).toULong();\n\n\n\n\tif( from.startsWith( \"FILE_TRANSFER_SYSTEM\" ) )\n\t{\n\t\tclient()->notifyError( \"Fileupload result received.\", msg, Client::Notice );\n\t\treturn;\n\t}\t\n\t\n\tif( url.isEmpty() )\n\t\treturn;\n\t\n\n\tunsigned int left = url.findRev( '\/' ) + 1;\n\tunsigned int right = url.findRev( '?' );\n\tfilename = url.mid( left, right - left );\n\n\temit incomingFileTransfer( from, url, expires, msg, filename, size, QPixmap() );\n}\n\nvoid FileTransferNotifierTask::parseFileTransfer7( YMSGTransfer *t )\n{ \n\tkDebug(YAHOO_RAW_DEBUG) << k_funcinfo << endl;\n\n\tQString from;\t\t\/* key = 4 *\/\n\tQString to;\t\t\/* key = 5 *\/\n\tQString url;\t\t\/* key = 20 *\/\n\tlong expires;\t\t\/* key = 38 *\/\n\tQString msg;\t\t\/* key = 14 *\/\n\tQString filename;\t\/* key = 27 *\/\n\tunsigned long size;\t\/* key = 28 *\/\n\tQByteArray preview;\t\/* key = 267 *\/\n\tQPixmap previewPixmap;\n\t\n\tif( t->firstParam( 222 ).toInt() == 2 )\n\t\treturn;\t\t\t\t\t\/\/ user cancelled the file transfer\n\n\tfrom = t->firstParam( 4 );\n\tto = t->firstParam( 5 );\n\turl = t->firstParam( 265 );\n\tmsg = t->firstParam( 14 );\n\texpires = t->firstParam( 38 ).toLong();\n\tfilename = t->firstParam( 27 );\n\tsize = t->firstParam( 28 ).toULong();\n\tpreview = KCodecs::base64Decode( t->firstParam( 267 ) );\n\n\tif( preview.size() > 0 )\n\t{\n\t\tpreviewPixmap.loadFromData( preview );\n\t}\n\n\temit incomingFileTransfer( from, url, expires, msg, filename, size, previewPixmap );\n}\n\nvoid FileTransferNotifierTask::acceptFileTransfer( YMSGTransfer *transfer )\n{\n\tkDebug(YAHOO_RAW_DEBUG) << k_funcinfo << endl;\n\t\n\tYMSGTransfer *t = new YMSGTransfer(Yahoo::ServicePeerToPeer);\n\tt->setId( client()->sessionID() );\n\tt->setParam( 4, client()->userId().toLocal8Bit() );\n\tt->setParam( 5, transfer->firstParam( 4 ) );\n\tt->setParam( 11, transfer->firstParam( 11 ) );\n\n\tsend( t );\n}\n\n#include \"filetransfernotifiertask.moc\"\n<commit_msg>deprecated--<commit_after>\/*\n Kopete Yahoo Protocol\n Notifies about incoming filetransfers\n\n Copyright (c) 2006 André Duffeck <andre.duffeck@kdemail.net>\n\n *************************************************************************\n * *\n * This library is free software; you can redistribute it and\/or *\n * modify it under the terms of the GNU Lesser General Public *\n * License as published by the Free Software Foundation; either *\n * version 2 of the License, or (at your option) any later version. *\n * *\n *************************************************************************\n*\/\n\n#include \"filetransfernotifiertask.h\"\n#include \"transfer.h\"\n#include \"ymsgtransfer.h\"\n#include \"yahootypes.h\"\n#include \"client.h\"\n#include <QString>\n#include <QFile>\n#include <QPixmap>\n#include <kdebug.h>\n#include <kcodecs.h>\n\nFileTransferNotifierTask::FileTransferNotifierTask(Task* parent) : Task(parent)\n{\n\tkDebug(YAHOO_RAW_DEBUG) << k_funcinfo << endl;\n}\n\nFileTransferNotifierTask::~FileTransferNotifierTask()\n{\n\n}\n\nbool FileTransferNotifierTask::take( Transfer* transfer )\n{\n\tkDebug(YAHOO_RAW_DEBUG) << k_funcinfo << endl;\n\t\n\tif ( !forMe( transfer ) )\n\t\treturn false;\n\t\n\tYMSGTransfer *t = static_cast<YMSGTransfer*>(transfer);\n\n\tif( t->service() == Yahoo::ServiceFileTransfer )\n\t\tparseFileTransfer( t );\n\telse if( t->service() == Yahoo::ServiceFileTransfer7 )\n\t\tparseFileTransfer7( t );\n\telse if( t->service() == Yahoo::ServicePeerToPeer )\n\t\tacceptFileTransfer( t );\n\t\t\n\n\treturn true;\n}\n\nbool FileTransferNotifierTask::forMe( const Transfer *transfer ) const\n{\n\tkDebug(YAHOO_RAW_DEBUG) << k_funcinfo << endl;\n\tconst YMSGTransfer *t = 0L;\n\tt = dynamic_cast<const YMSGTransfer*>(transfer);\n\tif (!t)\n\t\treturn false;\n\n\n\tif( t->service() == Yahoo::ServiceP2PFileXfer ||\n\t\tt->service() == Yahoo::ServicePeerToPeer ||\n\t\tt->service() == Yahoo::ServiceFileTransfer ||\n\t\tt->service() == Yahoo::ServiceFileTransfer7\n\t)\n\t\treturn true;\n\telse\n\t\treturn false;\n}\n\nvoid FileTransferNotifierTask::parseFileTransfer( YMSGTransfer *t )\n{\n\tkDebug(YAHOO_RAW_DEBUG) << k_funcinfo << endl;\n\n\tQString from;\t\t\/* key = 4 *\/\n\tQString to;\t\t\/* key = 5 *\/\n\tQString url;\t\t\/* key = 20 *\/\n\tlong expires;\t\t\/* key = 38 *\/\n\tQString msg;\t\t\/* key = 14 *\/\n\tQString filename;\t\/* key = 27 *\/\n\tunsigned long size;\t\/* key = 28 *\/\n\n\tfrom = t->firstParam( 4 );\n\tto = t->firstParam( 5 );\n\turl = t->firstParam( 20 );\n\texpires = t->firstParam( 38 ).toLong();\n\tmsg = t->firstParam( 14 );\n\tfilename = t->firstParam( 27 );\n\tsize = t->firstParam( 28 ).toULong();\n\n\n\n\tif( from.startsWith( \"FILE_TRANSFER_SYSTEM\" ) )\n\t{\n\t\tclient()->notifyError( \"Fileupload result received.\", msg, Client::Notice );\n\t\treturn;\n\t}\t\n\t\n\tif( url.isEmpty() )\n\t\treturn;\n\t\n\n\tunsigned int left = url.lastIndexOf( '\/' ) + 1;\n\tunsigned int right = url.lastIndexOf( '?' );\n\tfilename = url.mid( left, right - left );\n\n\temit incomingFileTransfer( from, url, expires, msg, filename, size, QPixmap() );\n}\n\nvoid FileTransferNotifierTask::parseFileTransfer7( YMSGTransfer *t )\n{ \n\tkDebug(YAHOO_RAW_DEBUG) << k_funcinfo << endl;\n\n\tQString from;\t\t\/* key = 4 *\/\n\tQString to;\t\t\/* key = 5 *\/\n\tQString url;\t\t\/* key = 20 *\/\n\tlong expires;\t\t\/* key = 38 *\/\n\tQString msg;\t\t\/* key = 14 *\/\n\tQString filename;\t\/* key = 27 *\/\n\tunsigned long size;\t\/* key = 28 *\/\n\tQByteArray preview;\t\/* key = 267 *\/\n\tQPixmap previewPixmap;\n\t\n\tif( t->firstParam( 222 ).toInt() == 2 )\n\t\treturn;\t\t\t\t\t\/\/ user cancelled the file transfer\n\n\tfrom = t->firstParam( 4 );\n\tto = t->firstParam( 5 );\n\turl = t->firstParam( 265 );\n\tmsg = t->firstParam( 14 );\n\texpires = t->firstParam( 38 ).toLong();\n\tfilename = t->firstParam( 27 );\n\tsize = t->firstParam( 28 ).toULong();\n\tpreview = KCodecs::base64Decode( t->firstParam( 267 ) );\n\n\tif( preview.size() > 0 )\n\t{\n\t\tpreviewPixmap.loadFromData( preview );\n\t}\n\n\temit incomingFileTransfer( from, url, expires, msg, filename, size, previewPixmap );\n}\n\nvoid FileTransferNotifierTask::acceptFileTransfer( YMSGTransfer *transfer )\n{\n\tkDebug(YAHOO_RAW_DEBUG) << k_funcinfo << endl;\n\t\n\tYMSGTransfer *t = new YMSGTransfer(Yahoo::ServicePeerToPeer);\n\tt->setId( client()->sessionID() );\n\tt->setParam( 4, client()->userId().toLocal8Bit() );\n\tt->setParam( 5, transfer->firstParam( 4 ) );\n\tt->setParam( 11, transfer->firstParam( 11 ) );\n\n\tsend( t );\n}\n\n#include \"filetransfernotifiertask.moc\"\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Author:\n * Guido Tack <guido.tack@monash.edu>\n *\n * Copyright:\n * NICTA 2013\n *\/\n\n\/* This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/. *\/\n\n#include \"project.h\"\n#include \"moocsubmission.h\"\n#include \"solverdialog.h\"\n#include \"process.h\"\n\n#include <QFileInfo>\n#include <QDir>\n#include <QDebug>\n#include <QMessageBox>\n#include <QSortFilterProxyModel>\n#include <QJsonDocument>\n#include <QJsonArray>\n\nProject::Project(const QList<SolverConfiguration*>& configs, QObject* parent) : QObject(parent), solverConfigs(configs)\n{\n itemModel = new QStandardItemModel(this);\n itemModel->setColumnCount(1);\n\n connect(itemModel, &QStandardItemModel::itemChanged, this, &Project::on_itemChanged);\n\n rootItem = new QStandardItem(QIcon(\":\/images\/mznicon.png\"), \"Untitled Project\");\n rootItem->setData(NodeType::ProjectFile, Role::Type);\n rootItem->setData(\"Untitled Project\", Role::OriginalLabel);\n rootItem->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled | Qt::ItemIsEditable);\n\n auto font = rootItem->font();\n font.setBold(true);\n\n modelsItem = new QStandardItem(\"Models\");\n modelsItem->setData(NodeType::Group, Role::Type);\n modelsItem->setFlags(Qt::NoItemFlags);\n modelsItem->setFont(font);\n\n dataItem = new QStandardItem(\"Data (right click to run)\");\n dataItem->setData(NodeType::Group, Role::Type);\n dataItem->setFlags(Qt::NoItemFlags);\n dataItem->setFont(font);\n\n checkersItem = new QStandardItem(\"Checkers (right click to run)\");\n checkersItem->setData(NodeType::Group, Role::Type);\n checkersItem->setFlags(Qt::NoItemFlags);\n checkersItem->setFont(font);\n\n configsItem = new QStandardItem(\"Solver configurations\");\n configsItem->setData(NodeType::Group, Role::Type);\n configsItem->setFlags(Qt::NoItemFlags);\n configsItem->setFont(font);\n\n otherItem = new QStandardItem(\"Other files\");\n otherItem->setData(NodeType::Group, Role::Type);\n otherItem->setFlags(Qt::NoItemFlags);\n otherItem->setFont(font);\n\n rootItem->appendRow(modelsItem);\n rootItem->appendRow(dataItem);\n rootItem->appendRow(checkersItem);\n rootItem->appendRow(configsItem);\n rootItem->appendRow(otherItem);\n itemModel->appendRow(rootItem);\n}\n\nQStringList Project::loadProject(const QString& file, ConfigWindow* configWindow)\n{\n clear();\n\n projectFile(file);\n\n QStringList warnings;\n\n QFile f(file);\n QFileInfo fi(f);\n if (!f.open(QFile::ReadOnly)) {\n throw FileError(\"Failed to open project file\");\n }\n\n auto doc = QJsonDocument::fromJson(f.readAll());\n\n if (doc.isObject()) {\n loadJSON(doc.object(), fi, configWindow, warnings);\n } else {\n f.reset();\n QDataStream in(&f);\n loadLegacy(in, fi, configWindow, warnings);\n }\n\n f.close();\n\n for (auto& sc : solverConfigurationFiles()) {\n configWindow->addConfig(sc);\n }\n\n if (!selectedBuiltinConfigId.isEmpty() && !selectedBuiltinConfigVersion.isEmpty()) {\n int index = configWindow->findBuiltinConfig(selectedBuiltinConfigId, selectedBuiltinConfigVersion);\n if (index == -1) {\n warnings << \"Could not find solver \" + selectedBuiltinConfigId + \"@\" + selectedBuiltinConfigVersion;\n } else {\n configWindow->setCurrentIndex(index);\n }\n } else if (!selectedSolverConfigFile.isEmpty()) {\n int index = configWindow->findConfigFile(rootDir().absolutePath() + \"\/\" + selectedSolverConfigFile);\n configWindow->setCurrentIndex(index);\n }\n\n setModified(false);\n\n return warnings;\n}\n\nvoid Project::loadJSON(const QJsonObject& obj, const QFileInfo& fi, ConfigWindow* configWindow, QStringList& warnings)\n{\n int version = obj[\"version\"].toInt();\n\n QString basePath = fi.absolutePath() + \"\/\";\n\n auto of = obj[\"openFiles\"].toArray();\n for (auto file : of) {\n auto path = basePath + file.toString();\n if (QFileInfo(path).exists()) {\n openTabs << path;\n } else {\n warnings << \"The file \" + file.toString() + \" could not be found\";\n }\n }\n\n openTabIndex = obj[\"openTab\"].toInt();\n\n QList<SolverConfiguration*> configs;\n if (obj[\"builtinSolverConfigs\"].isArray()) {\n for (auto config : obj[\"builtinSolverConfigs\"].toArray()) {\n if (!config.isObject()) {\n warnings << \"Failed to read solver builtin solver config\";\n continue;\n }\n SolverConfiguration* loaded;\n if (version >= 106) {\n loaded = new (SolverConfiguration) (SolverConfiguration::loadJSON(QJsonDocument(config.toObject())));\n } else {\n loaded = new (SolverConfiguration) (SolverConfiguration::loadLegacy(QJsonDocument(config.toObject())));\n }\n loaded->isBuiltin = true;\n configs << loaded;\n }\n }\n\n if (obj[\"projectSolverConfigs\"].isArray()) {\n for (auto config : obj[\"projectSolverConfigs\"].toArray()) {\n if (!config.isObject()) {\n warnings << \"Failed to read solver project solver config\";\n continue;\n }\n auto loaded = new (SolverConfiguration) (SolverConfiguration::loadLegacy(QJsonDocument(config.toObject())));\n loaded->modified = true;\n configs << loaded;\n }\n }\n\n configWindow->mergeConfigs(configs);\n\n if (obj[\"selectedBuiltinConfigId\"].isString() && obj[\"selectedBuiltinConfigVersion\"].isString()) {\n selectedBuiltinConfigId = obj[\"selectedBuiltinConfigId\"].toString();\n selectedBuiltinConfigVersion = obj[\"selectedBuiltinConfigVersion\"].toString();\n selectedSolverConfigFile = \"\";\n\n } else if (obj[\"selectedSolverConfigFile\"].isString()) {\n selectedSolverConfigFile = obj[\"selectedSolverConfigFile\"].toString();\n selectedBuiltinConfigId = \"\";\n selectedBuiltinConfigVersion = \"\";\n } else {\n warnings << \"No selected solver config in project\";\n }\n\n for (auto file : obj[\"projectFiles\"].toArray()) {\n auto path = basePath + file.toString();\n if (QFileInfo(path).exists()) {\n add(path);\n } else {\n warnings << \"The file \" + file.toString() + \" could not be found\";\n }\n }\n}\n\nvoid Project::loadLegacy(QDataStream& in, const QFileInfo& fi, ConfigWindow* configWindow, QStringList& warnings)\n{\n \/\/ Load old binary format of project\n throw InternalError(\"This project format is no longer supported. Please use MiniZinc IDE version 2.4 to upgrade it.\");\n}\n\nvoid Project::saveProject()\n{\n QJsonObject confObject;\n confObject[\"version\"] = 106;\n\n \/\/ Save the currently open tabs\n QStringList of;\n for (auto& f: openTabs) {\n of << relativeToProject(f);\n }\n confObject[\"openFiles\"] = QJsonArray::fromStringList(of);\n confObject[\"openTab\"] = openTabIndex;\n\n \/\/ Save paths of all project files\n QStringList relativeFilePaths;\n for (auto& file : files()) {\n relativeFilePaths << relativeToProject(file);\n }\n confObject[\"projectFiles\"] = QJsonArray::fromStringList(relativeFilePaths);\n\n \/\/ Save which config is currently selected\n if (!selectedBuiltinConfigId.isEmpty() && !selectedBuiltinConfigVersion.isEmpty()) {\n confObject[\"selectedBuiltinConfigId\"] = selectedBuiltinConfigId;\n confObject[\"selectedBuiltinConfigVersion\"] = selectedBuiltinConfigVersion;\n } else if (!selectedSolverConfigFile.isEmpty()){\n confObject[\"selectedSolverConfigFile\"] = selectedSolverConfigFile;\n }\n\n \/\/ Save modified built-in configs\n QJsonArray builtinSolverConfigs;\n for (auto sc : solverConfigs) {\n if (!sc->isBuiltin || *sc == SolverConfiguration(sc->solverDefinition, true)) {\n continue;\n }\n builtinSolverConfigs << sc->toJSONObject();\n }\n if (solverConfigs.count()) {\n confObject[\"builtinSolverConfigs\"] = builtinSolverConfigs;\n }\n\n \/\/ Write project file\n QJsonDocument doc(confObject);\n QFile file(projectFile());\n if (!file.open(QFile::WriteOnly)) {\n throw FileError(\"Failed to write file\");\n }\n file.write(doc.toJson());\n file.close();\n\n setModified(false);\n}\n\nvoid Project::add(const QString& fileName)\n{\n auto abs = QFileInfo(fileName).absoluteFilePath();\n auto path = relativeToProject(fileName);\n if (contains(abs)) {\n return;\n }\n\n auto parts = path.split(\"\/\", QString::SkipEmptyParts); \/\/ Qt always uses \/ as the path separator\n auto file = parts.takeLast();\n\n QStandardItem* node = otherItem;\n QString icon;\n NodeType type = NodeType::Other;\n if (file.endsWith(\".mzc.mzn\") || file.endsWith(\".mzc\")) {\n node = checkersItem;\n icon = \":\/images\/mznicon.png\";\n type = NodeType::Checker;\n } else if (file.endsWith(\".mzn\")) {\n node = modelsItem;\n icon = \":\/images\/mznicon.png\";\n type = NodeType::Model;\n } else if (file.endsWith(\".dzn\") || file.endsWith(\".json\")) {\n node = dataItem;\n icon = \":\/images\/mznicon.png\";\n type = NodeType::Data;\n } else if (file.endsWith(\".mpc\")) {\n node = configsItem;\n icon = \":\/images\/mznicon.png\";\n type = NodeType::SolverConfig;\n } else if (file == \"_mooc\" || file == \"_coursera\") {\n if (mooc) {\n delete mooc;\n }\n mooc = new MOOCAssignment(fileName);\n emit moocChanged(mooc);\n }\n\n node->setFlags(Qt::ItemIsEnabled);\n\n \/\/ Traverse existing path items\n int i = 0;\n while (!parts.empty() && i < node->rowCount()) {\n if (getType(node->child(i)->index()) == NodeType::Dir &&\n node->child(i)->text() == parts.first()) {\n parts.pop_front();\n node = node->child(i);\n i = 0;\n } else {\n i++;\n }\n }\n \/\/ Create new path items\n for (auto& part : parts) {\n auto dir = new QStandardItem(QIcon(\":\/icons\/images\/folder.png\"), part);\n dir->setData(NodeType::Dir, Role::Type);\n dir->setFlags(Qt::ItemIsEnabled);\n node->appendRow(dir);\n node->sortChildren(0);\n node = dir;\n }\n \/\/ Add file item\n auto item = new QStandardItem(QIcon(icon), file);\n item->setData(type, Role::Type);\n item->setData(abs, Role::Path);\n item->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled | Qt::ItemIsEditable);\n node->appendRow(item);\n node->sortChildren(0);\n\n entries.insert(abs, item);\n setModified(true);\n}\n\nvoid Project::add(const QStringList& fileNames)\n{\n for (auto& fileName : fileNames) {\n add(fileName);\n }\n}\n\nvoid Project::remove(const QString &fileName)\n{\n auto path = QFileInfo(fileName).absoluteFilePath();\n if (!contains(path)) {\n return;\n }\n\n \/\/ Make sure we also remove any unused dirs\n auto node = entries[path];\n if (node->text() == \"_mooc\" || node->text() == \"_coursera\") {\n delete mooc;\n mooc = nullptr;\n emit moocChanged(mooc);\n }\n while (getType(node->parent()->index()) == NodeType::Dir && node->parent()->rowCount() <= 1) {\n node = node->parent();\n }\n auto parent = node->parent();\n parent->removeRow(node->row());\n if (parent->data(Role::Type) == \"group\" && !parent->hasChildren()) {\n parent->setFlags(Qt::NoItemFlags);\n }\n entries.remove(path);\n setModified(true);\n}\n\nvoid Project::remove(const QStringList &fileNames)\n{\n for (auto& fileName : fileNames) {\n remove(fileName);\n }\n}\n\nvoid Project::remove(const QModelIndex& index)\n{\n remove(getFileName(index));\n}\n\nvoid Project::remove(const QModelIndexList& indexes)\n{\n for (auto& index : indexes) {\n remove(index);\n }\n}\n\nvoid Project::clear()\n{\n modelsItem->removeRows(0, modelsItem->rowCount());\n dataItem->removeRows(0, dataItem->rowCount());\n checkersItem->removeRows(0, checkersItem->rowCount());\n otherItem->removeRows(0, otherItem->rowCount());\n entries.clear();\n setModified(true);\n}\n\nQStringList Project::files(void) const {\n return entries.keys();\n}\n\nQStringList Project::modelFiles(void) const {\n return getFiles(NodeType::Model);\n}\n\nQStringList Project::solverConfigurationFiles(void) const {\n return getFiles(NodeType::SolverConfig);\n}\n\nQStringList Project::dataFiles(void) const {\n return getFiles(NodeType::Data);\n}\n\nbool Project::contains(const QString &fileName)\n{\n QFileInfo fi(fileName);\n return entries.contains(fi.absoluteFilePath());\n}\n\nvoid Project::setModified(bool m)\n{\n modified = m;\n auto label = rootItem->data(Role::OriginalLabel).toString();\n if (modified) {\n rootItem->setText(label + \" *\");\n } else {\n rootItem->setText(label);\n }\n}\n\nvoid Project::projectFile(const QString& fileName)\n{\n QStringList files = entries.keys();\n clear();\n if (fileName.isEmpty()) {\n rootItem->setText(\"Untitled Project\");\n rootItem->setData(\"Untitled Project\", Role::OriginalLabel);\n projFile = \"\";\n } else {\n QFileInfo fi(fileName);\n projFile = fi.absoluteFilePath();\n rootItem->setText(fi.fileName());\n rootItem->setData(fi.fileName(), Role::OriginalLabel);\n }\n add(files);\n}\n\nQDir Project::rootDir()\n{\n QFileInfo fi(projectFile());\n return QDir(fi.absolutePath());\n}\n\nbool Project::hasProjectFile()\n{\n return !projectFile().isEmpty();\n}\n\nProject::NodeType Project::getType(const QModelIndex& index)\n{\n return static_cast<Project::NodeType>(model()->data(index, Role::Type).toInt());\n}\n\nQString Project::getFileName(const QModelIndex& index)\n{\n return model()->data(index, Role::Path).toString();\n}\n\nQStringList Project::getFileNames(const QModelIndexList& indices)\n{\n QStringList result;\n for (auto& index : indices) {\n result << getFileName(index);\n }\n return result;\n}\n\nQStringList Project::getFiles(NodeType type) const\n{\n QStringList ret;\n for (auto it = entries.begin(); it != entries.end(); it++) {\n auto t = static_cast<NodeType>(it.value()->data(Role::Type).toInt());\n if (t == type) {\n ret << it.key();\n }\n }\n return ret;\n}\n\nQString Project::relativeToProject(const QString& fileName)\n{\n QFileInfo fi(fileName);\n auto abs = fi.absoluteFilePath();\n return hasProjectFile() ? rootDir().relativeFilePath(abs) : abs;\n}\n\nvoid Project::openTabsChanged(const QStringList& files, int currentTab)\n{\n openTabs.clear();\n for (auto& file : files) {\n auto abs = QFileInfo(file).absoluteFilePath();\n if (contains(abs)) {\n openTabs << abs;\n }\n }\n\n if (currentTab >= 0) {\n openTabIndex = openTabs.indexOf(QFileInfo(files[currentTab]).absoluteFilePath());\n } else {\n openTabIndex = -1;\n }\n\n\/\/ setModified(true);\n}\n\nvoid Project::activeSolverConfigChanged(const SolverConfiguration* sc)\n{\n if (!sc) {\n selectedSolverConfigFile = \"\";\n selectedBuiltinConfigId = \"\";\n selectedBuiltinConfigVersion = \"\";\n }\n if (sc->isBuiltin) {\n selectedSolverConfigFile = \"\";\n selectedBuiltinConfigId = sc->solverDefinition.id;\n selectedBuiltinConfigVersion = sc->solverDefinition.version;\n } else {\n selectedBuiltinConfigId = \"\";\n selectedBuiltinConfigVersion = \"\";\n selectedSolverConfigFile = relativeToProject(sc->paramFile);\n }\n\/\/ setModified(true);\n}\n\nvoid Project::on_itemChanged(QStandardItem* item)\n{\n auto oldPath = item->data(Qt::UserRole + 1).toString();\n auto newName = item->text();\n if (oldPath.isEmpty() || oldPath.endsWith(newName)) {\n return;\n }\n QFileInfo fi(oldPath);\n auto target = fi.path() + \"\/\" + item->text();\n if (QFile::rename(oldPath, target)) {\n remove(oldPath);\n add(target);\n emit fileRenamed(oldPath, target);\n } else {\n item->setText(fi.fileName());\n }\n}\n<commit_msg>Don't save modified builtin configs in project<commit_after>\/*\n * Author:\n * Guido Tack <guido.tack@monash.edu>\n *\n * Copyright:\n * NICTA 2013\n *\/\n\n\/* This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/. *\/\n\n#include \"project.h\"\n#include \"moocsubmission.h\"\n#include \"solverdialog.h\"\n#include \"process.h\"\n\n#include <QFileInfo>\n#include <QDir>\n#include <QDebug>\n#include <QMessageBox>\n#include <QSortFilterProxyModel>\n#include <QJsonDocument>\n#include <QJsonArray>\n\nProject::Project(const QList<SolverConfiguration*>& configs, QObject* parent) : QObject(parent), solverConfigs(configs)\n{\n itemModel = new QStandardItemModel(this);\n itemModel->setColumnCount(1);\n\n connect(itemModel, &QStandardItemModel::itemChanged, this, &Project::on_itemChanged);\n\n rootItem = new QStandardItem(QIcon(\":\/images\/mznicon.png\"), \"Untitled Project\");\n rootItem->setData(NodeType::ProjectFile, Role::Type);\n rootItem->setData(\"Untitled Project\", Role::OriginalLabel);\n rootItem->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled | Qt::ItemIsEditable);\n\n auto font = rootItem->font();\n font.setBold(true);\n\n modelsItem = new QStandardItem(\"Models\");\n modelsItem->setData(NodeType::Group, Role::Type);\n modelsItem->setFlags(Qt::NoItemFlags);\n modelsItem->setFont(font);\n\n dataItem = new QStandardItem(\"Data (right click to run)\");\n dataItem->setData(NodeType::Group, Role::Type);\n dataItem->setFlags(Qt::NoItemFlags);\n dataItem->setFont(font);\n\n checkersItem = new QStandardItem(\"Checkers (right click to run)\");\n checkersItem->setData(NodeType::Group, Role::Type);\n checkersItem->setFlags(Qt::NoItemFlags);\n checkersItem->setFont(font);\n\n configsItem = new QStandardItem(\"Solver configurations\");\n configsItem->setData(NodeType::Group, Role::Type);\n configsItem->setFlags(Qt::NoItemFlags);\n configsItem->setFont(font);\n\n otherItem = new QStandardItem(\"Other files\");\n otherItem->setData(NodeType::Group, Role::Type);\n otherItem->setFlags(Qt::NoItemFlags);\n otherItem->setFont(font);\n\n rootItem->appendRow(modelsItem);\n rootItem->appendRow(dataItem);\n rootItem->appendRow(checkersItem);\n rootItem->appendRow(configsItem);\n rootItem->appendRow(otherItem);\n itemModel->appendRow(rootItem);\n}\n\nQStringList Project::loadProject(const QString& file, ConfigWindow* configWindow)\n{\n clear();\n\n projectFile(file);\n\n QStringList warnings;\n\n QFile f(file);\n QFileInfo fi(f);\n if (!f.open(QFile::ReadOnly)) {\n throw FileError(\"Failed to open project file\");\n }\n\n auto doc = QJsonDocument::fromJson(f.readAll());\n\n if (doc.isObject()) {\n loadJSON(doc.object(), fi, configWindow, warnings);\n } else {\n f.reset();\n QDataStream in(&f);\n loadLegacy(in, fi, configWindow, warnings);\n }\n\n f.close();\n\n for (auto& sc : solverConfigurationFiles()) {\n configWindow->addConfig(sc);\n }\n\n if (!selectedBuiltinConfigId.isEmpty() && !selectedBuiltinConfigVersion.isEmpty()) {\n int index = configWindow->findBuiltinConfig(selectedBuiltinConfigId, selectedBuiltinConfigVersion);\n if (index == -1) {\n warnings << \"Could not find solver \" + selectedBuiltinConfigId + \"@\" + selectedBuiltinConfigVersion;\n } else {\n configWindow->setCurrentIndex(index);\n }\n } else if (!selectedSolverConfigFile.isEmpty()) {\n int index = configWindow->findConfigFile(rootDir().absolutePath() + \"\/\" + selectedSolverConfigFile);\n configWindow->setCurrentIndex(index);\n }\n\n setModified(false);\n\n return warnings;\n}\n\nvoid Project::loadJSON(const QJsonObject& obj, const QFileInfo& fi, ConfigWindow* configWindow, QStringList& warnings)\n{\n int version = obj[\"version\"].toInt();\n\n QString basePath = fi.absolutePath() + \"\/\";\n\n auto of = obj[\"openFiles\"].toArray();\n for (auto file : of) {\n auto path = basePath + file.toString();\n if (QFileInfo(path).exists()) {\n openTabs << path;\n } else {\n warnings << \"The file \" + file.toString() + \" could not be found\";\n }\n }\n\n openTabIndex = obj[\"openTab\"].toInt();\n\n QList<SolverConfiguration*> configs;\n if (obj[\"builtinSolverConfigs\"].isArray()) {\n for (auto config : obj[\"builtinSolverConfigs\"].toArray()) {\n if (!config.isObject()) {\n warnings << \"Failed to read solver builtin solver config\";\n continue;\n }\n SolverConfiguration* loaded;\n if (version >= 106) {\n loaded = new (SolverConfiguration) (SolverConfiguration::loadJSON(QJsonDocument(config.toObject())));\n } else {\n loaded = new (SolverConfiguration) (SolverConfiguration::loadLegacy(QJsonDocument(config.toObject())));\n }\n loaded->isBuiltin = true;\n configs << loaded;\n }\n }\n\n if (obj[\"projectSolverConfigs\"].isArray()) {\n for (auto config : obj[\"projectSolverConfigs\"].toArray()) {\n if (!config.isObject()) {\n warnings << \"Failed to read solver project solver config\";\n continue;\n }\n auto loaded = new (SolverConfiguration) (SolverConfiguration::loadLegacy(QJsonDocument(config.toObject())));\n loaded->modified = true;\n configs << loaded;\n }\n }\n\n configWindow->mergeConfigs(configs);\n\n if (obj[\"selectedBuiltinConfigId\"].isString() && obj[\"selectedBuiltinConfigVersion\"].isString()) {\n selectedBuiltinConfigId = obj[\"selectedBuiltinConfigId\"].toString();\n selectedBuiltinConfigVersion = obj[\"selectedBuiltinConfigVersion\"].toString();\n selectedSolverConfigFile = \"\";\n\n } else if (obj[\"selectedSolverConfigFile\"].isString()) {\n selectedSolverConfigFile = obj[\"selectedSolverConfigFile\"].toString();\n selectedBuiltinConfigId = \"\";\n selectedBuiltinConfigVersion = \"\";\n } else {\n warnings << \"No selected solver config in project\";\n }\n\n for (auto file : obj[\"projectFiles\"].toArray()) {\n auto path = basePath + file.toString();\n if (QFileInfo(path).exists()) {\n add(path);\n } else {\n warnings << \"The file \" + file.toString() + \" could not be found\";\n }\n }\n}\n\nvoid Project::loadLegacy(QDataStream& in, const QFileInfo& fi, ConfigWindow* configWindow, QStringList& warnings)\n{\n \/\/ Load old binary format of project\n throw InternalError(\"This project format is no longer supported. Please use MiniZinc IDE version 2.4 to upgrade it.\");\n}\n\nvoid Project::saveProject()\n{\n QJsonObject confObject;\n confObject[\"version\"] = 106;\n\n \/\/ Save the currently open tabs\n QStringList of;\n for (auto& f: openTabs) {\n of << relativeToProject(f);\n }\n confObject[\"openFiles\"] = QJsonArray::fromStringList(of);\n confObject[\"openTab\"] = openTabIndex;\n\n \/\/ Save paths of all project files\n QStringList relativeFilePaths;\n for (auto& file : files()) {\n relativeFilePaths << relativeToProject(file);\n }\n confObject[\"projectFiles\"] = QJsonArray::fromStringList(relativeFilePaths);\n\n \/\/ Save which config is currently selected\n if (!selectedBuiltinConfigId.isEmpty() && !selectedBuiltinConfigVersion.isEmpty()) {\n confObject[\"selectedBuiltinConfigId\"] = selectedBuiltinConfigId;\n confObject[\"selectedBuiltinConfigVersion\"] = selectedBuiltinConfigVersion;\n } else if (!selectedSolverConfigFile.isEmpty()){\n confObject[\"selectedSolverConfigFile\"] = selectedSolverConfigFile;\n }\n\n \/\/ Write project file\n QJsonDocument doc(confObject);\n QFile file(projectFile());\n if (!file.open(QFile::WriteOnly)) {\n throw FileError(\"Failed to write file\");\n }\n file.write(doc.toJson());\n file.close();\n\n setModified(false);\n}\n\nvoid Project::add(const QString& fileName)\n{\n auto abs = QFileInfo(fileName).absoluteFilePath();\n auto path = relativeToProject(fileName);\n if (contains(abs)) {\n return;\n }\n\n auto parts = path.split(\"\/\", QString::SkipEmptyParts); \/\/ Qt always uses \/ as the path separator\n auto file = parts.takeLast();\n\n QStandardItem* node = otherItem;\n QString icon;\n NodeType type = NodeType::Other;\n if (file.endsWith(\".mzc.mzn\") || file.endsWith(\".mzc\")) {\n node = checkersItem;\n icon = \":\/images\/mznicon.png\";\n type = NodeType::Checker;\n } else if (file.endsWith(\".mzn\")) {\n node = modelsItem;\n icon = \":\/images\/mznicon.png\";\n type = NodeType::Model;\n } else if (file.endsWith(\".dzn\") || file.endsWith(\".json\")) {\n node = dataItem;\n icon = \":\/images\/mznicon.png\";\n type = NodeType::Data;\n } else if (file.endsWith(\".mpc\")) {\n node = configsItem;\n icon = \":\/images\/mznicon.png\";\n type = NodeType::SolverConfig;\n } else if (file == \"_mooc\" || file == \"_coursera\") {\n if (mooc) {\n delete mooc;\n }\n mooc = new MOOCAssignment(fileName);\n emit moocChanged(mooc);\n }\n\n node->setFlags(Qt::ItemIsEnabled);\n\n \/\/ Traverse existing path items\n int i = 0;\n while (!parts.empty() && i < node->rowCount()) {\n if (getType(node->child(i)->index()) == NodeType::Dir &&\n node->child(i)->text() == parts.first()) {\n parts.pop_front();\n node = node->child(i);\n i = 0;\n } else {\n i++;\n }\n }\n \/\/ Create new path items\n for (auto& part : parts) {\n auto dir = new QStandardItem(QIcon(\":\/icons\/images\/folder.png\"), part);\n dir->setData(NodeType::Dir, Role::Type);\n dir->setFlags(Qt::ItemIsEnabled);\n node->appendRow(dir);\n node->sortChildren(0);\n node = dir;\n }\n \/\/ Add file item\n auto item = new QStandardItem(QIcon(icon), file);\n item->setData(type, Role::Type);\n item->setData(abs, Role::Path);\n item->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled | Qt::ItemIsEditable);\n node->appendRow(item);\n node->sortChildren(0);\n\n entries.insert(abs, item);\n setModified(true);\n}\n\nvoid Project::add(const QStringList& fileNames)\n{\n for (auto& fileName : fileNames) {\n add(fileName);\n }\n}\n\nvoid Project::remove(const QString &fileName)\n{\n auto path = QFileInfo(fileName).absoluteFilePath();\n if (!contains(path)) {\n return;\n }\n\n \/\/ Make sure we also remove any unused dirs\n auto node = entries[path];\n if (node->text() == \"_mooc\" || node->text() == \"_coursera\") {\n delete mooc;\n mooc = nullptr;\n emit moocChanged(mooc);\n }\n while (getType(node->parent()->index()) == NodeType::Dir && node->parent()->rowCount() <= 1) {\n node = node->parent();\n }\n auto parent = node->parent();\n parent->removeRow(node->row());\n if (parent->data(Role::Type) == \"group\" && !parent->hasChildren()) {\n parent->setFlags(Qt::NoItemFlags);\n }\n entries.remove(path);\n setModified(true);\n}\n\nvoid Project::remove(const QStringList &fileNames)\n{\n for (auto& fileName : fileNames) {\n remove(fileName);\n }\n}\n\nvoid Project::remove(const QModelIndex& index)\n{\n remove(getFileName(index));\n}\n\nvoid Project::remove(const QModelIndexList& indexes)\n{\n for (auto& index : indexes) {\n remove(index);\n }\n}\n\nvoid Project::clear()\n{\n modelsItem->removeRows(0, modelsItem->rowCount());\n dataItem->removeRows(0, dataItem->rowCount());\n checkersItem->removeRows(0, checkersItem->rowCount());\n otherItem->removeRows(0, otherItem->rowCount());\n entries.clear();\n setModified(true);\n}\n\nQStringList Project::files(void) const {\n return entries.keys();\n}\n\nQStringList Project::modelFiles(void) const {\n return getFiles(NodeType::Model);\n}\n\nQStringList Project::solverConfigurationFiles(void) const {\n return getFiles(NodeType::SolverConfig);\n}\n\nQStringList Project::dataFiles(void) const {\n return getFiles(NodeType::Data);\n}\n\nbool Project::contains(const QString &fileName)\n{\n QFileInfo fi(fileName);\n return entries.contains(fi.absoluteFilePath());\n}\n\nvoid Project::setModified(bool m)\n{\n modified = m;\n auto label = rootItem->data(Role::OriginalLabel).toString();\n if (modified) {\n rootItem->setText(label + \" *\");\n } else {\n rootItem->setText(label);\n }\n}\n\nvoid Project::projectFile(const QString& fileName)\n{\n QStringList files = entries.keys();\n clear();\n if (fileName.isEmpty()) {\n rootItem->setText(\"Untitled Project\");\n rootItem->setData(\"Untitled Project\", Role::OriginalLabel);\n projFile = \"\";\n } else {\n QFileInfo fi(fileName);\n projFile = fi.absoluteFilePath();\n rootItem->setText(fi.fileName());\n rootItem->setData(fi.fileName(), Role::OriginalLabel);\n }\n add(files);\n}\n\nQDir Project::rootDir()\n{\n QFileInfo fi(projectFile());\n return QDir(fi.absolutePath());\n}\n\nbool Project::hasProjectFile()\n{\n return !projectFile().isEmpty();\n}\n\nProject::NodeType Project::getType(const QModelIndex& index)\n{\n return static_cast<Project::NodeType>(model()->data(index, Role::Type).toInt());\n}\n\nQString Project::getFileName(const QModelIndex& index)\n{\n return model()->data(index, Role::Path).toString();\n}\n\nQStringList Project::getFileNames(const QModelIndexList& indices)\n{\n QStringList result;\n for (auto& index : indices) {\n result << getFileName(index);\n }\n return result;\n}\n\nQStringList Project::getFiles(NodeType type) const\n{\n QStringList ret;\n for (auto it = entries.begin(); it != entries.end(); it++) {\n auto t = static_cast<NodeType>(it.value()->data(Role::Type).toInt());\n if (t == type) {\n ret << it.key();\n }\n }\n return ret;\n}\n\nQString Project::relativeToProject(const QString& fileName)\n{\n QFileInfo fi(fileName);\n auto abs = fi.absoluteFilePath();\n return hasProjectFile() ? rootDir().relativeFilePath(abs) : abs;\n}\n\nvoid Project::openTabsChanged(const QStringList& files, int currentTab)\n{\n openTabs.clear();\n for (auto& file : files) {\n auto abs = QFileInfo(file).absoluteFilePath();\n if (contains(abs)) {\n openTabs << abs;\n }\n }\n\n if (currentTab >= 0) {\n openTabIndex = openTabs.indexOf(QFileInfo(files[currentTab]).absoluteFilePath());\n } else {\n openTabIndex = -1;\n }\n\n\/\/ setModified(true);\n}\n\nvoid Project::activeSolverConfigChanged(const SolverConfiguration* sc)\n{\n if (!sc) {\n selectedSolverConfigFile = \"\";\n selectedBuiltinConfigId = \"\";\n selectedBuiltinConfigVersion = \"\";\n }\n if (sc->isBuiltin) {\n selectedSolverConfigFile = \"\";\n selectedBuiltinConfigId = sc->solverDefinition.id;\n selectedBuiltinConfigVersion = sc->solverDefinition.version;\n } else {\n selectedBuiltinConfigId = \"\";\n selectedBuiltinConfigVersion = \"\";\n selectedSolverConfigFile = relativeToProject(sc->paramFile);\n }\n\/\/ setModified(true);\n}\n\nvoid Project::on_itemChanged(QStandardItem* item)\n{\n auto oldPath = item->data(Qt::UserRole + 1).toString();\n auto newName = item->text();\n if (oldPath.isEmpty() || oldPath.endsWith(newName)) {\n return;\n }\n QFileInfo fi(oldPath);\n auto target = fi.path() + \"\/\" + item->text();\n if (QFile::rename(oldPath, target)) {\n remove(oldPath);\n add(target);\n emit fileRenamed(oldPath, target);\n } else {\n item->setText(fi.fileName());\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ This file is part of the Marble Desktop Globe.\n\/\/\n\/\/ This program is free software licensed under the GNU LGPL. You can\n\/\/ find a copy of this license in LICENSE.txt in the top directory of\n\/\/ the source code.\n\/\/\n\/\/ Copyright 2011 Niko Sams <niko.sams@gmail.com>\n\/\/\n\n#include \"ElevationModel.h\"\n#include \"GeoSceneHead.h\"\n#include \"GeoSceneMap.h\"\n#include \"GeoSceneDocument.h\"\n#include \"GeoSceneTexture.h\"\n#include \"TextureTile.h\"\n#include \"TileLoader.h\"\n#include \"TileLoaderHelper.h\"\n#include \"MarbleModel.h\"\n#include \"MarbleDebug.h\"\n#include \"MapThemeManager.h\"\n\n#include <QtGui\/QLabel>\n#include <QtCore\/qmath.h>\n\nnamespace Marble\n{\n\nclass ElevationModelPrivate\n{\npublic:\n ElevationModelPrivate( ElevationModel *_q, MarbleModel *const model )\n : q( _q ),\n m_tileLoader( model->downloadManager() ),\n m_textureLayer( 0 )\n {\n m_cache.setMaxCost( 10 ); \/\/keep 10 tiles in memory (~17MB)\n\n const GeoSceneDocument *srtmTheme = model->mapThemeManager()->loadMapTheme( \"earth\/srtm2\/srtm2.dgml\" );\n Q_ASSERT( srtmTheme );\n\n const GeoSceneHead *head = srtmTheme->head();\n Q_ASSERT( head );\n\n const GeoSceneMap *map = srtmTheme->map();\n Q_ASSERT( map );\n\n const GeoSceneLayer *sceneLayer = map->layer( head->theme() );\n Q_ASSERT( sceneLayer );\n\n m_textureLayer = dynamic_cast<GeoSceneTexture*>( sceneLayer->datasets().first() );\n Q_ASSERT( m_textureLayer );\n\n QVector<const GeoSceneTexture*> textureLayers;\n textureLayers << m_textureLayer;\n\n m_tileLoader.setTextureLayers( textureLayers );\n }\n\n void tileCompleted( const TileId & tileId, const QImage &image )\n {\n m_cache.insert( tileId, new QImage( image ) );\n emit q->updateAvailable();\n }\n\npublic:\n ElevationModel *q;\n\n TileLoader m_tileLoader;\n const GeoSceneTexture *m_textureLayer;\n QCache<TileId, const QImage> m_cache;\n};\n\nElevationModel::ElevationModel( MarbleModel *const model )\n : QObject( 0 ),\n d( new ElevationModelPrivate( this, model ) )\n{\n connect( &d->m_tileLoader, SIGNAL( tileCompleted( TileId, QImage ) ),\n this, SLOT( tileCompleted( TileId, QImage ) ) );\n}\n\n\nqreal ElevationModel::height( qreal lon, qreal lat ) const\n{\n const int tileZoomLevel = d->m_tileLoader.maximumTileLevel( *( d->m_textureLayer ) );\n Q_ASSERT( tileZoomLevel == 9 );\n\n const int width = d->m_textureLayer->tileSize().width();\n const int height = d->m_textureLayer->tileSize().height();\n\n const int numTilesX = TileLoaderHelper::levelToColumn( d->m_textureLayer->levelZeroColumns(), tileZoomLevel );\n const int numTilesY = TileLoaderHelper::levelToRow( d->m_textureLayer->levelZeroRows(), tileZoomLevel );\n Q_ASSERT( numTilesX > 0 );\n Q_ASSERT( numTilesY > 0 );\n\n qreal textureX = 180 + lon;\n textureX *= numTilesX * width \/ 360;\n\n qreal textureY = 90 - lat;\n textureY *= numTilesY * height \/ 180;\n\n qreal ret = 0;\n bool hasHeight = false;\n qreal noData = 0;\n\n for ( int i = 0; i < 4; ++i ) {\n const int x = static_cast<int>( textureX + ( i % 2 ) );\n const int y = static_cast<int>( textureY + ( i \/ 2 ) );\n\n \/\/mDebug() << \"x\" << x << ( x \/ width );\n \/\/mDebug() << \"y\" << y << ( y \/ height );\n\n const TileId id( \"earth\/srtm2\", tileZoomLevel, ( x % ( numTilesX * width ) ) \/ width, ( y % ( numTilesY * height ) ) \/ height );\n \/\/mDebug() << \"LAT\" << lat << \"LON\" << lon << \"tile\" << ( x % ( numTilesX * width ) ) \/ width << ( y % ( numTilesY * height ) ) \/ height;\n\n const QImage *image = d->m_cache[id];\n if ( image == 0 ) {\n image = new QImage( d->m_tileLoader.loadTile( id, DownloadBrowse ) );\n d->m_cache.insert( id, image );\n }\n Q_ASSERT( image );\n Q_ASSERT( !image->isNull() );\n Q_ASSERT( width == image->width() );\n Q_ASSERT( height == image->height() );\n\n const qreal dx = ( textureX > ( qreal )x ) ? textureX - ( qreal )x : ( qreal )x - textureX;\n const qreal dy = ( textureY > ( qreal )y ) ? textureY - ( qreal )y : ( qreal )y - textureY;\n\n Q_ASSERT( 0 <= dx && dx <= 1 );\n Q_ASSERT( 0 <= dy && dy <= 1 );\n unsigned int pixel;\n pixel = image->pixel( x % width, y % height );\n pixel -= 0xFF000000; \/\/fully opaque\n \/\/mDebug() << \"(1-dx)\" << (1-dx) << \"(1-dy)\" << (1-dy);\n if ( pixel != 32768 ) { \/\/no data?\n \/\/mDebug() << \"got at x\" << x % width << \"y\" << y % height << \"a height of\" << pixel << \"** RGB\" << qRed(pixel) << qGreen(pixel) << qBlue(pixel);\n ret += ( qreal )pixel * ( 1 - dx ) * ( 1 - dy );\n hasHeight = true;\n } else {\n \/\/mDebug() << \"no data at\" << x % width << \"y\" << y % height;\n noData += ( 1 - dx ) * ( 1 - dy );\n }\n }\n\n if ( !hasHeight ) {\n ret = 32768; \/\/no data\n } else {\n if ( noData ) {\n \/\/mDebug() << \"NO DATA\" << noData;\n ret += ( ret \/ ( 1 - noData ) ) * noData;\n }\n }\n\n \/\/mDebug() << \">>>\" << lat << lon << \"returning an elevation of\" << ret;\n return ret;\n}\n\nQList<GeoDataCoordinates> ElevationModel::heightProfile( qreal fromLon, qreal fromLat, qreal toLon, qreal toLat ) const\n{\n const int tileZoomLevel = d->m_tileLoader.maximumTileLevel( *( d->m_textureLayer ) );\n const int width = d->m_textureLayer->tileSize().width();\n const int numTilesX = TileLoaderHelper::levelToColumn( d->m_textureLayer->levelZeroColumns(), tileZoomLevel );\n\n qreal distPerPixel = ( qreal )360 \/ ( width * numTilesX );\n \/\/mDebug() << \"heightProfile\" << fromLat << fromLon << toLat << toLon << \"distPerPixel\" << distPerPixel;\n\n qreal lat = fromLat;\n qreal lon = fromLon;\n char dirLat = fromLat < toLat ? 1 : -1;\n char dirLon = fromLon < toLon ? 1 : -1;\n qreal k = qAbs( ( fromLat - toLat ) \/ ( fromLon - toLon ) );\n \/\/mDebug() << \"fromLon\" << fromLon << \"fromLat\" << fromLat;\n \/\/mDebug() << \"diff lon\" << ( fromLon - toLon ) << \"diff lat\" << ( fromLat - toLat );\n \/\/mDebug() << \"dirLon\" << QString::number(dirLon) << \"dirLat\" << QString::number(dirLat) << \"k\" << k;\n QList<GeoDataCoordinates> ret;\n while ( lat*dirLat <= toLat*dirLat && lon*dirLon <= toLon * dirLon ) {\n \/\/mDebug() << lat << lon;\n qreal h = height( lon, lat );\n if ( h < 32000 ) {\n ret << GeoDataCoordinates( lon, lat, h, GeoDataCoordinates::Degree );\n }\n if ( k < 0.5 ) {\n \/\/mDebug() << \"lon(x) += distPerPixel\";\n lat += distPerPixel * k * dirLat;\n lon += distPerPixel * dirLon;\n } else {\n \/\/mDebug() << \"lat(y) += distPerPixel\";\n lat += distPerPixel * dirLat;\n lon += distPerPixel \/ k * dirLon;\n }\n }\n \/\/mDebug() << ret;\n return ret;\n}\n\n}\n\n\n\n#include \"ElevationModel.moc\"\n<commit_msg>Don't crash when the srtm2 map theme is missing.<commit_after>\/\/\n\/\/ This file is part of the Marble Desktop Globe.\n\/\/\n\/\/ This program is free software licensed under the GNU LGPL. You can\n\/\/ find a copy of this license in LICENSE.txt in the top directory of\n\/\/ the source code.\n\/\/\n\/\/ Copyright 2011 Niko Sams <niko.sams@gmail.com>\n\/\/\n\n#include \"ElevationModel.h\"\n#include \"GeoSceneHead.h\"\n#include \"GeoSceneMap.h\"\n#include \"GeoSceneDocument.h\"\n#include \"GeoSceneTexture.h\"\n#include \"TextureTile.h\"\n#include \"TileLoader.h\"\n#include \"TileLoaderHelper.h\"\n#include \"MarbleModel.h\"\n#include \"MarbleDebug.h\"\n#include \"MapThemeManager.h\"\n\n#include <QtGui\/QLabel>\n#include <QtCore\/qmath.h>\n\nnamespace Marble\n{\n\nnamespace {\n unsigned int const invalidElevationData = 32768;\n}\n\nclass ElevationModelPrivate\n{\npublic:\n ElevationModelPrivate( ElevationModel *_q, MarbleModel *const model )\n : q( _q ),\n m_tileLoader( model->downloadManager() ),\n m_textureLayer( 0 )\n {\n m_cache.setMaxCost( 10 ); \/\/keep 10 tiles in memory (~17MB)\n\n const GeoSceneDocument *srtmTheme = model->mapThemeManager()->loadMapTheme( \"earth\/srtm2\/srtm2.dgml\" );\n if ( !srtmTheme ) {\n mDebug() << \"Failed to load map theme earth\/srtm2\/srtm2.dgml. Check your installation. No elevation will be returned.\";\n return;\n }\n\n const GeoSceneHead *head = srtmTheme->head();\n Q_ASSERT( head );\n\n const GeoSceneMap *map = srtmTheme->map();\n Q_ASSERT( map );\n\n const GeoSceneLayer *sceneLayer = map->layer( head->theme() );\n Q_ASSERT( sceneLayer );\n\n m_textureLayer = dynamic_cast<GeoSceneTexture*>( sceneLayer->datasets().first() );\n Q_ASSERT( m_textureLayer );\n\n QVector<const GeoSceneTexture*> textureLayers;\n textureLayers << m_textureLayer;\n\n m_tileLoader.setTextureLayers( textureLayers );\n }\n\n void tileCompleted( const TileId & tileId, const QImage &image )\n {\n m_cache.insert( tileId, new QImage( image ) );\n emit q->updateAvailable();\n }\n\npublic:\n ElevationModel *q;\n\n TileLoader m_tileLoader;\n const GeoSceneTexture *m_textureLayer;\n QCache<TileId, const QImage> m_cache;\n};\n\nElevationModel::ElevationModel( MarbleModel *const model )\n : QObject( 0 ),\n d( new ElevationModelPrivate( this, model ) )\n{\n connect( &d->m_tileLoader, SIGNAL( tileCompleted( TileId, QImage ) ),\n this, SLOT( tileCompleted( TileId, QImage ) ) );\n}\n\n\nqreal ElevationModel::height( qreal lon, qreal lat ) const\n{\n if ( !d->m_textureLayer ) {\n return invalidElevationData;\n }\n\n const int tileZoomLevel = d->m_tileLoader.maximumTileLevel( *( d->m_textureLayer ) );\n Q_ASSERT( tileZoomLevel == 9 );\n\n const int width = d->m_textureLayer->tileSize().width();\n const int height = d->m_textureLayer->tileSize().height();\n\n const int numTilesX = TileLoaderHelper::levelToColumn( d->m_textureLayer->levelZeroColumns(), tileZoomLevel );\n const int numTilesY = TileLoaderHelper::levelToRow( d->m_textureLayer->levelZeroRows(), tileZoomLevel );\n Q_ASSERT( numTilesX > 0 );\n Q_ASSERT( numTilesY > 0 );\n\n qreal textureX = 180 + lon;\n textureX *= numTilesX * width \/ 360;\n\n qreal textureY = 90 - lat;\n textureY *= numTilesY * height \/ 180;\n\n qreal ret = 0;\n bool hasHeight = false;\n qreal noData = 0;\n\n for ( int i = 0; i < 4; ++i ) {\n const int x = static_cast<int>( textureX + ( i % 2 ) );\n const int y = static_cast<int>( textureY + ( i \/ 2 ) );\n\n \/\/mDebug() << \"x\" << x << ( x \/ width );\n \/\/mDebug() << \"y\" << y << ( y \/ height );\n\n const TileId id( \"earth\/srtm2\", tileZoomLevel, ( x % ( numTilesX * width ) ) \/ width, ( y % ( numTilesY * height ) ) \/ height );\n \/\/mDebug() << \"LAT\" << lat << \"LON\" << lon << \"tile\" << ( x % ( numTilesX * width ) ) \/ width << ( y % ( numTilesY * height ) ) \/ height;\n\n const QImage *image = d->m_cache[id];\n if ( image == 0 ) {\n image = new QImage( d->m_tileLoader.loadTile( id, DownloadBrowse ) );\n d->m_cache.insert( id, image );\n }\n Q_ASSERT( image );\n Q_ASSERT( !image->isNull() );\n Q_ASSERT( width == image->width() );\n Q_ASSERT( height == image->height() );\n\n const qreal dx = ( textureX > ( qreal )x ) ? textureX - ( qreal )x : ( qreal )x - textureX;\n const qreal dy = ( textureY > ( qreal )y ) ? textureY - ( qreal )y : ( qreal )y - textureY;\n\n Q_ASSERT( 0 <= dx && dx <= 1 );\n Q_ASSERT( 0 <= dy && dy <= 1 );\n unsigned int pixel;\n pixel = image->pixel( x % width, y % height );\n pixel -= 0xFF000000; \/\/fully opaque\n \/\/mDebug() << \"(1-dx)\" << (1-dx) << \"(1-dy)\" << (1-dy);\n if ( pixel != invalidElevationData ) { \/\/no data?\n \/\/mDebug() << \"got at x\" << x % width << \"y\" << y % height << \"a height of\" << pixel << \"** RGB\" << qRed(pixel) << qGreen(pixel) << qBlue(pixel);\n ret += ( qreal )pixel * ( 1 - dx ) * ( 1 - dy );\n hasHeight = true;\n } else {\n \/\/mDebug() << \"no data at\" << x % width << \"y\" << y % height;\n noData += ( 1 - dx ) * ( 1 - dy );\n }\n }\n\n if ( !hasHeight ) {\n ret = invalidElevationData; \/\/no data\n } else {\n if ( noData ) {\n \/\/mDebug() << \"NO DATA\" << noData;\n ret += ( ret \/ ( 1 - noData ) ) * noData;\n }\n }\n\n \/\/mDebug() << \">>>\" << lat << lon << \"returning an elevation of\" << ret;\n return ret;\n}\n\nQList<GeoDataCoordinates> ElevationModel::heightProfile( qreal fromLon, qreal fromLat, qreal toLon, qreal toLat ) const\n{\n if ( !d->m_textureLayer ) {\n return QList<GeoDataCoordinates>();\n }\n\n const int tileZoomLevel = d->m_tileLoader.maximumTileLevel( *( d->m_textureLayer ) );\n const int width = d->m_textureLayer->tileSize().width();\n const int numTilesX = TileLoaderHelper::levelToColumn( d->m_textureLayer->levelZeroColumns(), tileZoomLevel );\n\n qreal distPerPixel = ( qreal )360 \/ ( width * numTilesX );\n \/\/mDebug() << \"heightProfile\" << fromLat << fromLon << toLat << toLon << \"distPerPixel\" << distPerPixel;\n\n qreal lat = fromLat;\n qreal lon = fromLon;\n char dirLat = fromLat < toLat ? 1 : -1;\n char dirLon = fromLon < toLon ? 1 : -1;\n qreal k = qAbs( ( fromLat - toLat ) \/ ( fromLon - toLon ) );\n \/\/mDebug() << \"fromLon\" << fromLon << \"fromLat\" << fromLat;\n \/\/mDebug() << \"diff lon\" << ( fromLon - toLon ) << \"diff lat\" << ( fromLat - toLat );\n \/\/mDebug() << \"dirLon\" << QString::number(dirLon) << \"dirLat\" << QString::number(dirLat) << \"k\" << k;\n QList<GeoDataCoordinates> ret;\n while ( lat*dirLat <= toLat*dirLat && lon*dirLon <= toLon * dirLon ) {\n \/\/mDebug() << lat << lon;\n qreal h = height( lon, lat );\n if ( h < 32000 ) {\n ret << GeoDataCoordinates( lon, lat, h, GeoDataCoordinates::Degree );\n }\n if ( k < 0.5 ) {\n \/\/mDebug() << \"lon(x) += distPerPixel\";\n lat += distPerPixel * k * dirLat;\n lon += distPerPixel * dirLon;\n } else {\n \/\/mDebug() << \"lat(y) += distPerPixel\";\n lat += distPerPixel * dirLat;\n lon += distPerPixel \/ k * dirLon;\n }\n }\n \/\/mDebug() << ret;\n return ret;\n}\n\n}\n\n\n\n#include \"ElevationModel.moc\"\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"base\/stl_util.h\"\n\n#include <set>\n\n#include \"testing\/gtest\/include\/gtest\/gtest.h\"\n\nnamespace {\n\n\/\/ Used as test case to ensure the various base::STLXxx functions don't require\n\/\/ more than operators \"<\" and \"==\" on values stored in containers.\nclass ComparableValue {\n public:\n explicit ComparableValue(int value) : value_(value) {}\n\n bool operator==(const ComparableValue& rhs) const {\n return value_ == rhs.value_;\n }\n\n bool operator<(const ComparableValue& rhs) const {\n return value_ < rhs.value_;\n }\n\n private:\n int value_;\n};\n\n}\n\nnamespace base {\nnamespace {\n\nTEST(STLUtilTest, STLIsSorted) {\n {\n std::set<int> set;\n set.insert(24);\n set.insert(1);\n set.insert(12);\n EXPECT_TRUE(STLIsSorted(set));\n }\n\n {\n std::set<ComparableValue> set;\n set.insert(ComparableValue(24));\n set.insert(ComparableValue(1));\n set.insert(ComparableValue(12));\n EXPECT_TRUE(STLIsSorted(set));\n }\n\n {\n std::vector<int> vector;\n vector.push_back(1);\n vector.push_back(1);\n vector.push_back(4);\n vector.push_back(64);\n vector.push_back(12432);\n EXPECT_TRUE(STLIsSorted(vector));\n vector.back() = 1;\n EXPECT_FALSE(STLIsSorted(vector));\n }\n}\n\nTEST(STLUtilTest, STLSetDifference) {\n std::set<int> a1;\n a1.insert(1);\n a1.insert(2);\n a1.insert(3);\n a1.insert(4);\n\n std::set<int> a2;\n a2.insert(3);\n a2.insert(4);\n a2.insert(5);\n a2.insert(6);\n a2.insert(7);\n\n {\n std::set<int> difference;\n difference.insert(1);\n difference.insert(2);\n EXPECT_EQ(difference, STLSetDifference<std::set<int> >(a1, a2));\n }\n\n {\n std::set<int> difference;\n difference.insert(5);\n difference.insert(6);\n difference.insert(7);\n EXPECT_EQ(difference, STLSetDifference<std::set<int> >(a2, a1));\n }\n\n {\n std::vector<int> difference;\n difference.push_back(1);\n difference.push_back(2);\n EXPECT_EQ(difference, STLSetDifference<std::vector<int> >(a1, a2));\n }\n\n {\n std::vector<int> difference;\n difference.push_back(5);\n difference.push_back(6);\n difference.push_back(7);\n EXPECT_EQ(difference, STLSetDifference<std::vector<int> >(a2, a1));\n }\n}\n\nTEST(STLUtilTest, STLSetUnion) {\n std::set<int> a1;\n a1.insert(1);\n a1.insert(2);\n a1.insert(3);\n a1.insert(4);\n\n std::set<int> a2;\n a2.insert(3);\n a2.insert(4);\n a2.insert(5);\n a2.insert(6);\n a2.insert(7);\n\n {\n std::set<int> result;\n result.insert(1);\n result.insert(2);\n result.insert(3);\n result.insert(4);\n result.insert(5);\n result.insert(6);\n result.insert(7);\n EXPECT_EQ(result, STLSetUnion<std::set<int> >(a1, a2));\n }\n\n {\n std::set<int> result;\n result.insert(1);\n result.insert(2);\n result.insert(3);\n result.insert(4);\n result.insert(5);\n result.insert(6);\n result.insert(7);\n EXPECT_EQ(result, STLSetUnion<std::set<int> >(a2, a1));\n }\n\n {\n std::vector<int> result;\n result.push_back(1);\n result.push_back(2);\n result.push_back(3);\n result.push_back(4);\n result.push_back(5);\n result.push_back(6);\n result.push_back(7);\n EXPECT_EQ(result, STLSetUnion<std::vector<int> >(a1, a2));\n }\n\n {\n std::vector<int> result;\n result.push_back(1);\n result.push_back(2);\n result.push_back(3);\n result.push_back(4);\n result.push_back(5);\n result.push_back(6);\n result.push_back(7);\n EXPECT_EQ(result, STLSetUnion<std::vector<int> >(a2, a1));\n }\n}\n\nTEST(STLUtilTest, STLSetIntersection) {\n std::set<int> a1;\n a1.insert(1);\n a1.insert(2);\n a1.insert(3);\n a1.insert(4);\n\n std::set<int> a2;\n a2.insert(3);\n a2.insert(4);\n a2.insert(5);\n a2.insert(6);\n a2.insert(7);\n\n {\n std::set<int> result;\n result.insert(3);\n result.insert(4);\n EXPECT_EQ(result, STLSetIntersection<std::set<int> >(a1, a2));\n }\n\n {\n std::set<int> result;\n result.insert(3);\n result.insert(4);\n EXPECT_EQ(result, STLSetIntersection<std::set<int> >(a2, a1));\n }\n\n {\n std::vector<int> result;\n result.push_back(3);\n result.push_back(4);\n EXPECT_EQ(result, STLSetIntersection<std::vector<int> >(a1, a2));\n }\n\n {\n std::vector<int> result;\n result.push_back(3);\n result.push_back(4);\n EXPECT_EQ(result, STLSetIntersection<std::vector<int> >(a2, a1));\n }\n}\n\nTEST(STLUtilTest, STLIncludes) {\n std::set<int> a1;\n a1.insert(1);\n a1.insert(2);\n a1.insert(3);\n a1.insert(4);\n\n std::set<int> a2;\n a2.insert(3);\n a2.insert(4);\n\n std::set<int> a3;\n a3.insert(3);\n a3.insert(4);\n a3.insert(5);\n\n EXPECT_TRUE(STLIncludes<std::set<int> >(a1, a2));\n EXPECT_FALSE(STLIncludes<std::set<int> >(a1, a3));\n EXPECT_FALSE(STLIncludes<std::set<int> >(a2, a1));\n EXPECT_FALSE(STLIncludes<std::set<int> >(a2, a3));\n EXPECT_FALSE(STLIncludes<std::set<int> >(a3, a1));\n EXPECT_TRUE(STLIncludes<std::set<int> >(a3, a2));\n}\n\n} \/\/ namespace\n} \/\/ namespace base\n<commit_msg>Add unit tests for string_as_array().<commit_after>\/\/ Copyright 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"base\/stl_util.h\"\n\n#include <set>\n\n#include \"testing\/gtest\/include\/gtest\/gtest.h\"\n\nnamespace {\n\n\/\/ Used as test case to ensure the various base::STLXxx functions don't require\n\/\/ more than operators \"<\" and \"==\" on values stored in containers.\nclass ComparableValue {\n public:\n explicit ComparableValue(int value) : value_(value) {}\n\n bool operator==(const ComparableValue& rhs) const {\n return value_ == rhs.value_;\n }\n\n bool operator<(const ComparableValue& rhs) const {\n return value_ < rhs.value_;\n }\n\n private:\n int value_;\n};\n\n}\n\nnamespace base {\nnamespace {\n\nTEST(STLUtilTest, STLIsSorted) {\n {\n std::set<int> set;\n set.insert(24);\n set.insert(1);\n set.insert(12);\n EXPECT_TRUE(STLIsSorted(set));\n }\n\n {\n std::set<ComparableValue> set;\n set.insert(ComparableValue(24));\n set.insert(ComparableValue(1));\n set.insert(ComparableValue(12));\n EXPECT_TRUE(STLIsSorted(set));\n }\n\n {\n std::vector<int> vector;\n vector.push_back(1);\n vector.push_back(1);\n vector.push_back(4);\n vector.push_back(64);\n vector.push_back(12432);\n EXPECT_TRUE(STLIsSorted(vector));\n vector.back() = 1;\n EXPECT_FALSE(STLIsSorted(vector));\n }\n}\n\nTEST(STLUtilTest, STLSetDifference) {\n std::set<int> a1;\n a1.insert(1);\n a1.insert(2);\n a1.insert(3);\n a1.insert(4);\n\n std::set<int> a2;\n a2.insert(3);\n a2.insert(4);\n a2.insert(5);\n a2.insert(6);\n a2.insert(7);\n\n {\n std::set<int> difference;\n difference.insert(1);\n difference.insert(2);\n EXPECT_EQ(difference, STLSetDifference<std::set<int> >(a1, a2));\n }\n\n {\n std::set<int> difference;\n difference.insert(5);\n difference.insert(6);\n difference.insert(7);\n EXPECT_EQ(difference, STLSetDifference<std::set<int> >(a2, a1));\n }\n\n {\n std::vector<int> difference;\n difference.push_back(1);\n difference.push_back(2);\n EXPECT_EQ(difference, STLSetDifference<std::vector<int> >(a1, a2));\n }\n\n {\n std::vector<int> difference;\n difference.push_back(5);\n difference.push_back(6);\n difference.push_back(7);\n EXPECT_EQ(difference, STLSetDifference<std::vector<int> >(a2, a1));\n }\n}\n\nTEST(STLUtilTest, STLSetUnion) {\n std::set<int> a1;\n a1.insert(1);\n a1.insert(2);\n a1.insert(3);\n a1.insert(4);\n\n std::set<int> a2;\n a2.insert(3);\n a2.insert(4);\n a2.insert(5);\n a2.insert(6);\n a2.insert(7);\n\n {\n std::set<int> result;\n result.insert(1);\n result.insert(2);\n result.insert(3);\n result.insert(4);\n result.insert(5);\n result.insert(6);\n result.insert(7);\n EXPECT_EQ(result, STLSetUnion<std::set<int> >(a1, a2));\n }\n\n {\n std::set<int> result;\n result.insert(1);\n result.insert(2);\n result.insert(3);\n result.insert(4);\n result.insert(5);\n result.insert(6);\n result.insert(7);\n EXPECT_EQ(result, STLSetUnion<std::set<int> >(a2, a1));\n }\n\n {\n std::vector<int> result;\n result.push_back(1);\n result.push_back(2);\n result.push_back(3);\n result.push_back(4);\n result.push_back(5);\n result.push_back(6);\n result.push_back(7);\n EXPECT_EQ(result, STLSetUnion<std::vector<int> >(a1, a2));\n }\n\n {\n std::vector<int> result;\n result.push_back(1);\n result.push_back(2);\n result.push_back(3);\n result.push_back(4);\n result.push_back(5);\n result.push_back(6);\n result.push_back(7);\n EXPECT_EQ(result, STLSetUnion<std::vector<int> >(a2, a1));\n }\n}\n\nTEST(STLUtilTest, STLSetIntersection) {\n std::set<int> a1;\n a1.insert(1);\n a1.insert(2);\n a1.insert(3);\n a1.insert(4);\n\n std::set<int> a2;\n a2.insert(3);\n a2.insert(4);\n a2.insert(5);\n a2.insert(6);\n a2.insert(7);\n\n {\n std::set<int> result;\n result.insert(3);\n result.insert(4);\n EXPECT_EQ(result, STLSetIntersection<std::set<int> >(a1, a2));\n }\n\n {\n std::set<int> result;\n result.insert(3);\n result.insert(4);\n EXPECT_EQ(result, STLSetIntersection<std::set<int> >(a2, a1));\n }\n\n {\n std::vector<int> result;\n result.push_back(3);\n result.push_back(4);\n EXPECT_EQ(result, STLSetIntersection<std::vector<int> >(a1, a2));\n }\n\n {\n std::vector<int> result;\n result.push_back(3);\n result.push_back(4);\n EXPECT_EQ(result, STLSetIntersection<std::vector<int> >(a2, a1));\n }\n}\n\nTEST(STLUtilTest, STLIncludes) {\n std::set<int> a1;\n a1.insert(1);\n a1.insert(2);\n a1.insert(3);\n a1.insert(4);\n\n std::set<int> a2;\n a2.insert(3);\n a2.insert(4);\n\n std::set<int> a3;\n a3.insert(3);\n a3.insert(4);\n a3.insert(5);\n\n EXPECT_TRUE(STLIncludes<std::set<int> >(a1, a2));\n EXPECT_FALSE(STLIncludes<std::set<int> >(a1, a3));\n EXPECT_FALSE(STLIncludes<std::set<int> >(a2, a1));\n EXPECT_FALSE(STLIncludes<std::set<int> >(a2, a3));\n EXPECT_FALSE(STLIncludes<std::set<int> >(a3, a1));\n EXPECT_TRUE(STLIncludes<std::set<int> >(a3, a2));\n}\n\nTEST(StringAsArrayTest, Empty) {\n std::string empty;\n EXPECT_EQ(nullptr, string_as_array(&empty));\n}\n\nTEST(StringAsArrayTest, NullTerminated) {\n \/\/ If any std::string implementation is not null-terminated, this should\n \/\/ fail. All compilers we use return a null-terminated buffer, but please do\n \/\/ not rely on this fact in your code.\n std::string str(\"abcde\");\n str.resize(3);\n EXPECT_STREQ(\"abc\", string_as_array(&str));\n}\n\nTEST(StringAsArrayTest, WriteCopy) {\n \/\/ With a COW implementation, this test will fail if\n \/\/ string_as_array(&str) is implemented as\n \/\/ const_cast<char*>(str->data()).\n std::string s1(\"abc\");\n const std::string s2(s1);\n string_as_array(&s1)[1] = 'x';\n EXPECT_EQ(\"axc\", s1);\n EXPECT_EQ(\"abc\", s2);\n}\n\n} \/\/ namespace\n} \/\/ namespace base\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: morphdlg.cxx,v $\n *\n * $Revision: 1.6 $\n *\n * last change: $Author: vg $ $Date: 2004-01-06 18:44:12 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n\n#include \"strings.hrc\"\n#include \"sdresid.hxx\"\n#include \"sdmod.hxx\"\n#include \"sdiocmpt.hxx\"\n#include \"morphdlg.hxx\"\n#include \"morphdlg.hrc\"\n\n#ifndef _CONFIG_HXX\n#include <tools\/config.hxx>\n#endif\n#ifndef SVX_XFILLIT0_HXX \/\/autogen\n#include <svx\/xfillit0.hxx>\n#endif\n#ifndef _SVX_XLINEIT0_HXX \/\/autogen\n#include <svx\/xlineit0.hxx>\n#endif\n#ifndef _XENUM_HXX \/\/autogen\n#include <svx\/xenum.hxx>\n#endif\n#ifndef _SVDOBJ_HXX \/\/autogen\n#include <svx\/svdobj.hxx>\n#endif\n#ifndef _SFXITEMSET_HXX \/\/autogen\n#include <svtools\/itemset.hxx>\n#endif\n#ifndef _SFXITEMPOOL_HXX \/\/autogen\n#include <svtools\/itempool.hxx>\n#endif\n\n\n\/******************************************************************************\/\n\n\n#define FADE_STEP \"FadeSteps\"\n#define FADE_ATTRIB \"FadeAttributes\"\n#define FADE_ORIENT \"FadeOrientation\"\n#define FADE_TRUE \"true\"\n#define FADE_FALSE \"false\"\n\n\n\/******************************************************************************\/\n\n\n\/******************************************************************************\n|*\n|*\n|*\n\\******************************************************************************\/\n\nSdMorphDlg::SdMorphDlg( Window* pParent, const SdrObject* pObj1, const SdrObject* pObj2 ) :\n ModalDialog ( pParent, SdResId( DLG_MORPH ) ),\n aBtnOK ( this, SdResId( BTN_OK ) ),\n aBtnCancel ( this, SdResId( BTN_CANCEL ) ),\n aBtnHelp ( this, SdResId( BTN_HELP ) ),\n aGrpPreset ( this, SdResId( GRP_PRESET ) ),\n aFtSteps ( this, SdResId( FT_STEPS ) ),\n aMtfSteps ( this, SdResId( MTF_STEPS ) ),\n aCbxAttributes ( this, SdResId( CBX_ATTRIBUTES ) ),\n aCbxOrientation ( this, SdResId( CBX_ORIENTATION ) )\n{\n FreeResource();\n LoadSettings();\n\n SfxItemPool* pPool = (SfxItemPool*) pObj1->GetItemPool();\n SfxItemSet aSet1( *pPool );\n SfxItemSet aSet2( *pPool );\n\n aSet1.Put(pObj1->GetMergedItemSet());\n aSet2.Put(pObj2->GetMergedItemSet());\n\n const XLineStyle eLineStyle1 = ( (const XLineStyleItem&) aSet1.Get( XATTR_LINESTYLE ) ).GetValue();\n const XLineStyle eLineStyle2 = ( (const XLineStyleItem&) aSet2.Get( XATTR_LINESTYLE ) ).GetValue();\n const XFillStyle eFillStyle1 = ( (const XFillStyleItem&) aSet1.Get( XATTR_FILLSTYLE ) ).GetValue();\n const XFillStyle eFillStyle2 = ( (const XFillStyleItem&) aSet2.Get( XATTR_FILLSTYLE ) ).GetValue();\n\n if ( ( ( eLineStyle1 == XLINE_NONE ) || ( eLineStyle2 == XLINE_NONE ) ) &&\n ( ( eFillStyle1 != XFILL_SOLID ) || ( eFillStyle2 != XFILL_SOLID ) ) )\n {\n aCbxAttributes.Disable();\n }\n}\n\n\n\/******************************************************************************\n|*\n|*\n|*\n\\******************************************************************************\/\n\nSdMorphDlg::~SdMorphDlg()\n{\n}\n\n\n\/******************************************************************************\n|*\n|*\n|*\n\\******************************************************************************\/\n\nvoid SdMorphDlg::LoadSettings()\n{\n SvStorageStreamRef xIStm( SD_MOD()->GetOptionStream( UniString::CreateFromAscii(\n RTL_CONSTASCII_STRINGPARAM( SD_OPTION_MORPHING ) ),\n SD_OPTION_LOAD ) );\n UINT16 nSteps;\n BOOL bOrient, bAttrib;\n\n if( xIStm.Is() )\n {\n SdIOCompat aCompat( *xIStm, STREAM_READ );\n\n *xIStm >> nSteps >> bOrient >> bAttrib;\n }\n else\n {\n nSteps = 16;\n bOrient = bAttrib = TRUE;\n }\n\n aMtfSteps.SetValue( nSteps );\n aCbxOrientation.Check( bOrient );\n aCbxAttributes.Check( bAttrib );\n}\n\n\/\/ -----------------------------------------------------------------------------\n\nvoid SdMorphDlg::SaveSettings() const\n{\n SvStorageStreamRef xOStm( SD_MOD()->GetOptionStream( UniString::CreateFromAscii(\n RTL_CONSTASCII_STRINGPARAM( SD_OPTION_MORPHING ) ),\n SD_OPTION_STORE ) );\n\n if( xOStm.Is() )\n {\n SdIOCompat aCompat( *xOStm, STREAM_WRITE, 1 );\n\n *xOStm << (UINT16) aMtfSteps.GetValue()\n << aCbxOrientation.IsChecked()\n << aCbxAttributes.IsChecked();\n }\n}\n\n<commit_msg>INTEGRATION: CWS impress1 (1.4.218); FILE MERGED 2003\/11\/27 15:08:36 af 1.4.218.3: RESYNC: (1.4-1.5); FILE MERGED 2003\/10\/01 11:52:34 af 1.4.218.2: #111996# Renamed some include files. 2003\/09\/17 09:24:35 af 1.4.218.1: #111996# Transition to stacked sub-shells. Introduction of namespace sd.<commit_after>\/*************************************************************************\n *\n * $RCSfile: morphdlg.cxx,v $\n *\n * $Revision: 1.7 $\n *\n * last change: $Author: obo $ $Date: 2004-01-20 10:46:33 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#include \"morphdlg.hxx\"\n\n#include \"strings.hrc\"\n#include \"sdresid.hxx\"\n#include \"sdmod.hxx\"\n#include \"sdiocmpt.hxx\"\n#include \"morphdlg.hrc\"\n\n#ifndef _CONFIG_HXX\n#include <tools\/config.hxx>\n#endif\n#ifndef SVX_XFILLIT0_HXX \/\/autogen\n#include <svx\/xfillit0.hxx>\n#endif\n#ifndef _SVX_XLINEIT0_HXX \/\/autogen\n#include <svx\/xlineit0.hxx>\n#endif\n#ifndef _XENUM_HXX \/\/autogen\n#include <svx\/xenum.hxx>\n#endif\n#ifndef _SVDOBJ_HXX \/\/autogen\n#include <svx\/svdobj.hxx>\n#endif\n#ifndef _SFXITEMSET_HXX \/\/autogen\n#include <svtools\/itemset.hxx>\n#endif\n#ifndef _SFXITEMPOOL_HXX \/\/autogen\n#include <svtools\/itempool.hxx>\n#endif\n\nnamespace sd {\n\n\n\/******************************************************************************\/\n\n\n#define FADE_STEP \"FadeSteps\"\n#define FADE_ATTRIB \"FadeAttributes\"\n#define FADE_ORIENT \"FadeOrientation\"\n#define FADE_TRUE \"true\"\n#define FADE_FALSE \"false\"\n\n\n\/******************************************************************************\/\n\n\n\/******************************************************************************\n|*\n|*\n|*\n\\******************************************************************************\/\n\nMorphDlg::MorphDlg( ::Window* pParent, const SdrObject* pObj1, const SdrObject* pObj2 ) :\n ModalDialog ( pParent, SdResId( DLG_MORPH ) ),\n aBtnOK ( this, SdResId( BTN_OK ) ),\n aBtnCancel ( this, SdResId( BTN_CANCEL ) ),\n aBtnHelp ( this, SdResId( BTN_HELP ) ),\n aGrpPreset ( this, SdResId( GRP_PRESET ) ),\n aFtSteps ( this, SdResId( FT_STEPS ) ),\n aMtfSteps ( this, SdResId( MTF_STEPS ) ),\n aCbxAttributes ( this, SdResId( CBX_ATTRIBUTES ) ),\n aCbxOrientation ( this, SdResId( CBX_ORIENTATION ) )\n{\n FreeResource();\n LoadSettings();\n\n SfxItemPool* pPool = (SfxItemPool*) pObj1->GetItemPool();\n SfxItemSet aSet1( *pPool );\n SfxItemSet aSet2( *pPool );\n\n aSet1.Put(pObj1->GetMergedItemSet());\n aSet2.Put(pObj2->GetMergedItemSet());\n\n const XLineStyle eLineStyle1 = ( (const XLineStyleItem&) aSet1.Get( XATTR_LINESTYLE ) ).GetValue();\n const XLineStyle eLineStyle2 = ( (const XLineStyleItem&) aSet2.Get( XATTR_LINESTYLE ) ).GetValue();\n const XFillStyle eFillStyle1 = ( (const XFillStyleItem&) aSet1.Get( XATTR_FILLSTYLE ) ).GetValue();\n const XFillStyle eFillStyle2 = ( (const XFillStyleItem&) aSet2.Get( XATTR_FILLSTYLE ) ).GetValue();\n\n if ( ( ( eLineStyle1 == XLINE_NONE ) || ( eLineStyle2 == XLINE_NONE ) ) &&\n ( ( eFillStyle1 != XFILL_SOLID ) || ( eFillStyle2 != XFILL_SOLID ) ) )\n {\n aCbxAttributes.Disable();\n }\n}\n\n\n\/******************************************************************************\n|*\n|*\n|*\n\\******************************************************************************\/\n\nMorphDlg::~MorphDlg()\n{\n}\n\n\n\/******************************************************************************\n|*\n|*\n|*\n\\******************************************************************************\/\n\nvoid MorphDlg::LoadSettings()\n{\n SvStorageStreamRef xIStm( SD_MOD()->GetOptionStream( UniString::CreateFromAscii(\n RTL_CONSTASCII_STRINGPARAM( SD_OPTION_MORPHING ) ),\n SD_OPTION_LOAD ) );\n UINT16 nSteps;\n BOOL bOrient, bAttrib;\n\n if( xIStm.Is() )\n {\n SdIOCompat aCompat( *xIStm, STREAM_READ );\n\n *xIStm >> nSteps >> bOrient >> bAttrib;\n }\n else\n {\n nSteps = 16;\n bOrient = bAttrib = TRUE;\n }\n\n aMtfSteps.SetValue( nSteps );\n aCbxOrientation.Check( bOrient );\n aCbxAttributes.Check( bAttrib );\n}\n\n\/\/ -----------------------------------------------------------------------------\n\nvoid MorphDlg::SaveSettings() const\n{\n SvStorageStreamRef xOStm( SD_MOD()->GetOptionStream( UniString::CreateFromAscii(\n RTL_CONSTASCII_STRINGPARAM( SD_OPTION_MORPHING ) ),\n SD_OPTION_STORE ) );\n\n if( xOStm.Is() )\n {\n SdIOCompat aCompat( *xOStm, STREAM_WRITE, 1 );\n\n *xOStm << (UINT16) aMtfSteps.GetValue()\n << aCbxOrientation.IsChecked()\n << aCbxAttributes.IsChecked();\n }\n}\n\n} \/\/ end of namespace sd\n<|endoftext|>"} {"text":"<commit_before>#ifndef _SDD_VALUES_UNIQUE_FLAT_SET_HH_\n#define _SDD_VALUES_UNIQUE_FLAT_SET_HH_\n\n#include <algorithm> \/\/ copy, set_difference, set_intersection, set_union\n#include <functional> \/\/ hash\n#include <initializer_list>\n#include <iosfwd>\n#include <iterator> \/\/ inserter\n#include <utility> \/\/ pair\n\n#include <boost\/container\/flat_set.hpp>\n#include <boost\/intrusive\/unordered_set.hpp>\n\n#include \"sdd\/internal\/util\/hash.hh\"\n\nnamespace sdd { namespace values {\n\n\/*------------------------------------------------------------------------------------------------*\/\n\n\/\/\/ @brief A unified set of values, implemented with a sorted vector.\ntemplate <typename Value>\nclass unique_flat_set\n{\npublic:\n\n \/\/\/ @brief The type of the real container.\n typedef boost::container::flat_set<Value> flat_set_type;\n\n \/\/\/ @brief The type of the contained value.\n typedef Value value_type;\n\nprivate:\n\n \/\/\/ @brief Faster, unsafe mode for Boost.Intrusive.\n typedef boost::intrusive::link_mode<boost::intrusive::normal_link> link_mode;\n\n \/\/\/ @brief An entry in the unique table of set of values.\n struct entry\n : public boost::intrusive::unordered_set_base_hook<link_mode>\n {\n \/\/ Can't copy an entry.\n entry(const entry&) = delete;\n entry& operator=(const entry&) = delete;\n\n \/\/\/ @brief The unified flat set.\n const flat_set_type data;\n\n \/\/\/ @brief Constructor.\n template <typename... Args>\n entry(Args&&... args)\n : data(std::forward<Args>(args)...)\n {\n }\n\n \/\/\/ @brief Comparison.\n bool\n operator==(const entry& other)\n const noexcept\n {\n return data == other.data;\n }\n };\n\n \/\/\/ @brief Hash an entry.\n struct hash\n {\n std::size_t\n operator()(const entry& e)\n const noexcept\n {\n std::size_t seed = 0;\n for (const auto& v : e.data)\n {\n internal::util::hash_combine(seed, v);\n }\n return seed;\n }\n };\n\n \/\/\/ @brief The type of the set of flat sets.\n typedef typename boost::intrusive::make_unordered_set<entry, boost::intrusive::hash<hash>>::type\n set_type;\n typedef typename set_type::bucket_type bucket_type;\n typedef typename set_type::bucket_traits bucket_traits;\n\n \/\/\/ @brief A pointer to the unified set of values.\n const flat_set_type* data_;\n\npublic:\n\n \/\/\/ @brief The type of an iterator on a flat set of values.\n typedef typename flat_set_type::const_iterator const_iterator;\n\n \/\/\/ @brief Default constructor.\n unique_flat_set()\n : data_(empty_set())\n {\n }\n\n \/\/\/ @brief Constructor with a range.\n template <typename InputIterator>\n unique_flat_set(InputIterator begin, InputIterator end)\n : data_(unify(begin, end))\n {\n }\n\n \/\/\/ @brief Constructor with a initializer_list.\n unique_flat_set(std::initializer_list<Value> values)\n : unique_flat_set(values.begin(), values.end())\n {\n }\n\n \/\/\/ @brief Constructor from a temporary flat_set_type.\n unique_flat_set(flat_set_type&& fs)\n : data_(unify(std::move(fs)))\n {\n }\n\n unique_flat_set(const unique_flat_set&) = default;\n unique_flat_set& operator=(const unique_flat_set&) = default;\n unique_flat_set(unique_flat_set&&) = default;\n unique_flat_set& operator=(unique_flat_set&&) = default;\n\n \/\/\/ @brief Insert a value.\n void\n insert(const Value& x)\n {\n flat_set_type s(*data_);\n const auto insertion = s.insert(x);\n if (insertion.second)\n {\n data_ = unify(std::move(s));\n }\n }\n\n \/\/\/ @brief Get the beginning of this set of values.\n const_iterator\n cbegin()\n const noexcept\n {\n return data_->cbegin();\n }\n\n \/\/\/ @brief Get the end of this set of values.\n const_iterator\n cend()\n const noexcept\n {\n return data_->cend();\n }\n\n \/\/\/ @brief Tell if this set of values is empty.\n bool\n empty()\n const noexcept\n {\n return data_->empty();\n }\n\n \/\/\/ @brief Get the number of contained values.\n std::size_t\n size()\n const noexcept\n {\n return data_->size();\n }\n\n \/\/\/ @brief Find a value.\n const_iterator\n find(const Value& x)\n const\n {\n return data_->find(x);\n }\n\n \/\/\/ @brief Erase a value.\n std::size_t\n erase(const Value& x)\n {\n flat_set_type fs(*data_);\n const std::size_t nb_erased = fs.erase(x);\n unify(std::move(fs));\n return nb_erased;\n }\n\n\/\/\/ @cond INTERNAL_DOC\n\n const flat_set_type* const\n data()\n const noexcept\n {\n return data_;\n }\n\n\/\/\/ @endcond\n\nprivate:\n\n \/\/\/ @brief Get the static set of flat sets.\n static\n set_type&\n set()\n {\n static bucket_type buckets[32000];\n static set_type set(bucket_traits(buckets, 32000));\n return set;\n }\n\n \/\/\/ @brief Get the static empty flat set.\n static\n const flat_set_type*\n empty_set()\n {\n static auto e = unify(flat_set_type());\n return e;\n }\n\n \/\/\/ @brief Unify a flat_set_type using a unique table.\n template <typename... Args>\n static\n const flat_set_type*\n unify(Args&&... args)\n {\n entry* ptr = new entry(std::forward<Args>(args)...);\n const auto insertion = set().insert(*ptr);\n if (not insertion.second)\n {\n delete ptr;\n }\n return &(insertion.first->data);\n }\n};\n\n\/*------------------------------------------------------------------------------------------------*\/\n\n\/\/\/ @brief Equality of unique_flat_set\n\/\/\/ @related unique_flat_set\ntemplate <typename Value>\ninline\nbool\noperator==(const unique_flat_set<Value>& lhs, const unique_flat_set<Value>& rhs)\nnoexcept\n{\n \/\/ Pointer comparison.\n return lhs.data() == rhs.data();\n}\n\n\/*------------------------------------------------------------------------------------------------*\/\n\n\/\/\/ @brief Comparison of unique_flat_set\n\/\/\/ @related unique_flat_set\ntemplate <typename Value>\ninline\nbool\noperator<(const unique_flat_set<Value>& lhs, const unique_flat_set<Value>& rhs)\nnoexcept\n{\n \/\/ Pointer comparison.\n return lhs.data() < rhs.data();\n}\n\n\/*------------------------------------------------------------------------------------------------*\/\n\n\/\/\/ @brief Textual output of a unique_flat_set\n\/\/\/ @related unique_flat_set\ntemplate <typename Value>\nstd::ostream&\noperator<<(std::ostream& os, const unique_flat_set<Value>& fs)\n{\n os << \"{\";\n if (not fs.empty())\n {\n std::copy(fs.cbegin(), std::prev(fs.cend()), std::ostream_iterator<Value>(os, \",\"));\n os << *std::prev(fs.cend());\n }\n return os << \"}\";\n}\n\n\/*------------------------------------------------------------------------------------------------*\/\n\n\/\/\/ @related unique_flat_set\ntemplate <typename Value>\ninline\nunique_flat_set<Value>\ndifference(const unique_flat_set<Value>& lhs, const unique_flat_set<Value>& rhs)\nnoexcept\n{\n typename unique_flat_set<Value>::flat_set_type res;\n std::set_difference( lhs.cbegin(), lhs.cend(), rhs.cbegin(), rhs.cend()\n , std::inserter(res, res.begin()));\n return unique_flat_set<Value>(std::move(res));\n}\n\n\/*------------------------------------------------------------------------------------------------*\/\n\n\/\/\/ @related unique_flat_set\ntemplate <typename Value>\ninline\nunique_flat_set<Value>\nintersection(const unique_flat_set<Value>& lhs, const unique_flat_set<Value>& rhs)\nnoexcept\n{\n typename unique_flat_set<Value>::flat_set_type res;\n std::set_intersection( lhs.cbegin(), lhs.cend(), rhs.cbegin(), rhs.cend()\n , std::inserter(res, res.begin()));\n return unique_flat_set<Value>(std::move(res));\n}\n\n\/*------------------------------------------------------------------------------------------------*\/\n\n\/\/\/ @related unique_flat_set\ntemplate <typename Value>\ninline\nunique_flat_set<Value>\nsum(const unique_flat_set<Value>& lhs, const unique_flat_set<Value>& rhs)\nnoexcept\n{\n typename unique_flat_set<Value>::flat_set_type res;\n std::set_union( lhs.cbegin(), lhs.cend(), rhs.cbegin(), rhs.cend()\n , std::inserter(res, res.begin()));\n return unique_flat_set<Value>(std::move(res));\n}\n\n\/*------------------------------------------------------------------------------------------------*\/\n\n}} \/\/ namespace sdd::values\n\nnamespace std {\n\n\/\/\/ @brief Hash specialization for sdd::values::flat_set\ntemplate <typename Value>\nstruct hash<sdd::values::unique_flat_set<Value>>\n{\n std::size_t\n operator()(const sdd::values::unique_flat_set<Value>& fs)\n const noexcept\n {\n return std::hash<decltype(fs.data())>()(fs.data());\n }\n};\n\n} \/\/ namespace std\n\n#endif \/\/ _SDD_VALUES_UNIQUE_FLAT_SET_HH_\n<commit_msg>Avoid memory leak report of static member.<commit_after>#ifndef _SDD_VALUES_UNIQUE_FLAT_SET_HH_\n#define _SDD_VALUES_UNIQUE_FLAT_SET_HH_\n\n#include <algorithm> \/\/ copy, set_difference, set_intersection, set_union\n#include <functional> \/\/ hash\n#include <initializer_list>\n#include <iosfwd>\n#include <iterator> \/\/ inserter\n#include <utility> \/\/ pair\n\n#include <boost\/container\/flat_set.hpp>\n#include <boost\/intrusive\/unordered_set.hpp>\n\n#include \"sdd\/internal\/util\/hash.hh\"\n\nnamespace sdd { namespace values {\n\n\/*------------------------------------------------------------------------------------------------*\/\n\n\/\/\/ @brief A unified set of values, implemented with a sorted vector.\ntemplate <typename Value>\nclass unique_flat_set\n{\npublic:\n\n \/\/\/ @brief The type of the real container.\n typedef boost::container::flat_set<Value> flat_set_type;\n\n \/\/\/ @brief The type of the contained value.\n typedef Value value_type;\n\nprivate:\n\n \/\/\/ @brief Faster, unsafe mode for Boost.Intrusive.\n typedef boost::intrusive::link_mode<boost::intrusive::normal_link> link_mode;\n\n \/\/\/ @brief An entry in the unique table of set of values.\n struct entry\n : public boost::intrusive::unordered_set_base_hook<link_mode>\n {\n \/\/ Can't copy an entry.\n entry(const entry&) = delete;\n entry& operator=(const entry&) = delete;\n\n \/\/\/ @brief The unified flat set.\n const flat_set_type data;\n\n \/\/\/ @brief Constructor.\n template <typename... Args>\n entry(Args&&... args)\n : data(std::forward<Args>(args)...)\n {\n }\n\n \/\/\/ @brief Comparison.\n bool\n operator==(const entry& other)\n const noexcept\n {\n return data == other.data;\n }\n };\n\n \/\/\/ @brief Hash an entry.\n struct hash\n {\n std::size_t\n operator()(const entry& e)\n const noexcept\n {\n std::size_t seed = 0;\n for (const auto& v : e.data)\n {\n internal::util::hash_combine(seed, v);\n }\n return seed;\n }\n };\n\n \/\/\/ @brief The type of the set of flat sets.\n typedef typename boost::intrusive::make_unordered_set<entry, boost::intrusive::hash<hash>>::type\n set_type;\n typedef typename set_type::bucket_type bucket_type;\n typedef typename set_type::bucket_traits bucket_traits;\n\n \/\/\/ @brief A pointer to the unified set of values.\n const flat_set_type* data_;\n\npublic:\n\n \/\/\/ @brief The type of an iterator on a flat set of values.\n typedef typename flat_set_type::const_iterator const_iterator;\n\n \/\/\/ @brief Default constructor.\n unique_flat_set()\n : data_(empty_set())\n {\n }\n\n \/\/\/ @brief Constructor with a range.\n template <typename InputIterator>\n unique_flat_set(InputIterator begin, InputIterator end)\n : data_(unify(begin, end))\n {\n }\n\n \/\/\/ @brief Constructor with a initializer_list.\n unique_flat_set(std::initializer_list<Value> values)\n : unique_flat_set(values.begin(), values.end())\n {\n }\n\n \/\/\/ @brief Constructor from a temporary flat_set_type.\n unique_flat_set(flat_set_type&& fs)\n : data_(unify(std::move(fs)))\n {\n }\n\n unique_flat_set(const unique_flat_set&) = default;\n unique_flat_set& operator=(const unique_flat_set&) = default;\n unique_flat_set(unique_flat_set&&) = default;\n unique_flat_set& operator=(unique_flat_set&&) = default;\n\n \/\/\/ @brief Insert a value.\n void\n insert(const Value& x)\n {\n flat_set_type s(*data_);\n const auto insertion = s.insert(x);\n if (insertion.second)\n {\n data_ = unify(std::move(s));\n }\n }\n\n \/\/\/ @brief Get the beginning of this set of values.\n const_iterator\n cbegin()\n const noexcept\n {\n return data_->cbegin();\n }\n\n \/\/\/ @brief Get the end of this set of values.\n const_iterator\n cend()\n const noexcept\n {\n return data_->cend();\n }\n\n \/\/\/ @brief Tell if this set of values is empty.\n bool\n empty()\n const noexcept\n {\n return data_->empty();\n }\n\n \/\/\/ @brief Get the number of contained values.\n std::size_t\n size()\n const noexcept\n {\n return data_->size();\n }\n\n \/\/\/ @brief Find a value.\n const_iterator\n find(const Value& x)\n const\n {\n return data_->find(x);\n }\n\n \/\/\/ @brief Erase a value.\n std::size_t\n erase(const Value& x)\n {\n flat_set_type fs(*data_);\n const std::size_t nb_erased = fs.erase(x);\n unify(std::move(fs));\n return nb_erased;\n }\n\n\/\/\/ @cond INTERNAL_DOC\n\n const flat_set_type* const\n data()\n const noexcept\n {\n return data_;\n }\n\n\/\/\/ @endcond\n\nprivate:\n\n \/\/\/ @brief Help cleaning the static set.\n struct set_disposer\n {\n bucket_type* buckets;\n set_type* set;\n\n set_disposer(std::size_t size)\n : buckets(new bucket_type[size])\n , set(new set_type(bucket_traits(buckets, size)))\n {\n }\n\n ~set_disposer()\n {\n set->clear_and_dispose([](entry* e){delete e;});\n delete set;\n delete[] buckets;\n }\n };\n\n \/\/\/ @brief Get the static set of flat sets.\n static\n set_type&\n set()\n {\n static set_disposer disposer(32000);\n return *disposer.set;\n }\n\n \/\/\/ @brief Get the static empty flat set.\n static\n const flat_set_type*\n empty_set()\n {\n static auto e = unify(flat_set_type());\n return e;\n }\n\n \/\/\/ @brief Unify a flat_set_type using a unique table.\n template <typename... Args>\n static\n const flat_set_type*\n unify(Args&&... args)\n {\n entry* ptr = new entry(std::forward<Args>(args)...);\n const auto insertion = set().insert(*ptr);\n if (not insertion.second)\n {\n delete ptr;\n }\n return &(insertion.first->data);\n }\n};\n\n\/*------------------------------------------------------------------------------------------------*\/\n\n\/\/\/ @brief Equality of unique_flat_set\n\/\/\/ @related unique_flat_set\ntemplate <typename Value>\ninline\nbool\noperator==(const unique_flat_set<Value>& lhs, const unique_flat_set<Value>& rhs)\nnoexcept\n{\n \/\/ Pointer comparison.\n return lhs.data() == rhs.data();\n}\n\n\/*------------------------------------------------------------------------------------------------*\/\n\n\/\/\/ @brief Comparison of unique_flat_set\n\/\/\/ @related unique_flat_set\ntemplate <typename Value>\ninline\nbool\noperator<(const unique_flat_set<Value>& lhs, const unique_flat_set<Value>& rhs)\nnoexcept\n{\n \/\/ Pointer comparison.\n return lhs.data() < rhs.data();\n}\n\n\/*------------------------------------------------------------------------------------------------*\/\n\n\/\/\/ @brief Textual output of a unique_flat_set\n\/\/\/ @related unique_flat_set\ntemplate <typename Value>\nstd::ostream&\noperator<<(std::ostream& os, const unique_flat_set<Value>& fs)\n{\n os << \"{\";\n if (not fs.empty())\n {\n std::copy(fs.cbegin(), std::prev(fs.cend()), std::ostream_iterator<Value>(os, \",\"));\n os << *std::prev(fs.cend());\n }\n return os << \"}\";\n}\n\n\/*------------------------------------------------------------------------------------------------*\/\n\n\/\/\/ @related unique_flat_set\ntemplate <typename Value>\ninline\nunique_flat_set<Value>\ndifference(const unique_flat_set<Value>& lhs, const unique_flat_set<Value>& rhs)\nnoexcept\n{\n typename unique_flat_set<Value>::flat_set_type res;\n std::set_difference( lhs.cbegin(), lhs.cend(), rhs.cbegin(), rhs.cend()\n , std::inserter(res, res.begin()));\n return unique_flat_set<Value>(std::move(res));\n}\n\n\/*------------------------------------------------------------------------------------------------*\/\n\n\/\/\/ @related unique_flat_set\ntemplate <typename Value>\ninline\nunique_flat_set<Value>\nintersection(const unique_flat_set<Value>& lhs, const unique_flat_set<Value>& rhs)\nnoexcept\n{\n typename unique_flat_set<Value>::flat_set_type res;\n std::set_intersection( lhs.cbegin(), lhs.cend(), rhs.cbegin(), rhs.cend()\n , std::inserter(res, res.begin()));\n return unique_flat_set<Value>(std::move(res));\n}\n\n\/*------------------------------------------------------------------------------------------------*\/\n\n\/\/\/ @related unique_flat_set\ntemplate <typename Value>\ninline\nunique_flat_set<Value>\nsum(const unique_flat_set<Value>& lhs, const unique_flat_set<Value>& rhs)\nnoexcept\n{\n typename unique_flat_set<Value>::flat_set_type res;\n std::set_union( lhs.cbegin(), lhs.cend(), rhs.cbegin(), rhs.cend()\n , std::inserter(res, res.begin()));\n return unique_flat_set<Value>(std::move(res));\n}\n\n\/*------------------------------------------------------------------------------------------------*\/\n\n}} \/\/ namespace sdd::values\n\nnamespace std {\n\n\/\/\/ @brief Hash specialization for sdd::values::flat_set\ntemplate <typename Value>\nstruct hash<sdd::values::unique_flat_set<Value>>\n{\n std::size_t\n operator()(const sdd::values::unique_flat_set<Value>& fs)\n const noexcept\n {\n return std::hash<decltype(fs.data())>()(fs.data());\n }\n};\n\n} \/\/ namespace std\n\n#endif \/\/ _SDD_VALUES_UNIQUE_FLAT_SET_HH_\n<|endoftext|>"} {"text":"<commit_before>#ifndef GENERIC_FORWARDER_HPP\n# define GENERIC_FORWARDER_HPP\n# pragma once\n\n#include <cassert>\n\n\/\/ ::std::size_t\n#include <cstddef>\n\n#include <functional>\n\n#include <type_traits>\n\n#include <utility>\n\nnamespace generic\n{\n\nnamespace detail\n{\n\nnamespace forwarder\n{\n\ntemplate <typename ...A>\nstruct argument_types\n{\n};\n\ntemplate <typename A>\nstruct argument_types<A>\n{\n using argument_type = A;\n};\n\ntemplate <typename A, typename B>\nstruct argument_types<A, B>\n{\n using first_argument_type = A;\n using second_argument_type = B;\n};\n\n}\n\n}\n\nconstexpr auto const default_forwarder_noexcept =\n#if __cpp_exceptions\nfalse;\n#else\ntrue;\n#endif \/\/ __cpp_exceptions\n\nconstexpr auto const default_forwarder_size = 4 * sizeof(void*);\n\ntemplate <typename F,\n bool NE = default_forwarder_noexcept,\n ::std::size_t N = default_forwarder_size>\nclass forwarder;\n\ntemplate <typename R, typename ...A, bool NE, ::std::size_t N>\nclass forwarder<R (A...), NE, N> : public detail::forwarder::argument_types<A...>\n{\n R (*stub_)(void const*, A&&...) noexcept(NE) {};\n\n typename ::std::aligned_storage_t<N> store_;\n\n template<typename T, typename ...U, ::std::size_t M>\n friend bool operator==(forwarder<T (U...), M> const&,\n ::std::nullptr_t) noexcept;\n template<typename T, typename ...U, ::std::size_t M>\n friend bool operator==(::std::nullptr_t,\n forwarder<T (U...), M> const&) noexcept;\n\n template<typename T, typename ...U, ::std::size_t M>\n friend bool operator!=(forwarder<T (U...), M> const&,\n ::std::nullptr_t) noexcept;\n template<typename T, typename ...U, ::std::size_t M>\n friend bool operator!=(::std::nullptr_t,\n forwarder<T (U...), M> const&) noexcept;\n\npublic:\n using result_type = R;\n\npublic:\n forwarder() = default;\n\n forwarder(forwarder const&) = default;\n\n forwarder(forwarder&&) = default;\n\n template<typename T>\n forwarder(T&& t) noexcept\n {\n assign(::std::forward<T>(t));\n }\n\n forwarder& operator=(forwarder const&) = default;\n\n forwarder& operator=(forwarder&&) = default;\n\n template <typename T>\n auto& operator=(T&& f) noexcept\n {\n assign(::std::forward<T>(f));\n\n return *this;\n }\n\n explicit operator bool() const noexcept { return stub_; }\n\n R operator()(A... args) const\n noexcept(noexcept(stub_(&store_, ::std::forward<A>(args)...)))\n {\n \/\/assert(stub_);\n return stub_(&store_, ::std::forward<A>(args)...);\n }\n\n void assign(::std::nullptr_t) noexcept\n {\n reset();\n }\n\n template <typename T>\n void assign(T&& f) noexcept\n {\n using functor_type = ::std::add_const_t<::std::remove_reference_t<T>>;\n\n static_assert(sizeof(functor_type) <= sizeof(store_),\n \"functor too large\");\n static_assert(::std::is_trivially_copyable<T>{},\n \"functor not trivially copyable\");\n\n ::new (static_cast<void*>(&store_)) functor_type(::std::forward<T>(f));\n\n stub_ = [](void const* const ptr, A&&... args) noexcept(\n noexcept(\n#if __cplusplus <= 201402L\n (\n *static_cast<functor_type*>(ptr))(::std::forward<A>(args)...)\n#else\n ::std::invoke(*static_cast<functor_type*>(ptr),\n ::std::forward<A>(args)...\n )\n#endif \/\/ __cplusplus\n )\n ) -> R\n {\n#if __cplusplus <= 201402L\n return (*static_cast<functor_type*>(ptr))(::std::forward<A>(args)...);\n#else\n return ::std::invoke(*static_cast<functor_type*>(ptr),\n ::std::forward<A>(args)...\n );\n#endif \/\/ __cplusplus\n };\n }\n\n void reset() noexcept { stub_ = nullptr; }\n\n void swap(forwarder& other) noexcept { ::std::swap(*this, other); }\n\n template <typename T>\n auto target() noexcept\n {\n return reinterpret_cast<T*>(&store_);\n }\n\n template <typename T> \n auto target() const noexcept\n {\n return reinterpret_cast<T const*>(&store_);\n }\n};\n\ntemplate<typename R, typename ...A, ::std::size_t N>\nbool operator==(forwarder<R (A...), N> const& f,\n ::std::nullptr_t const) noexcept\n{\n return f.stub_ == nullptr;\n}\n\ntemplate<typename R, typename ...A, ::std::size_t N>\nbool operator==(::std::nullptr_t const,\n forwarder<R (A...), N> const& f) noexcept\n{\n return f.stub_ == nullptr;\n}\n\ntemplate<typename R, typename ...A, ::std::size_t N>\nbool operator!=(forwarder<R (A...), N> const& f,\n ::std::nullptr_t const) noexcept\n{\n return !operator==(f, nullptr);\n}\n\ntemplate<typename R, typename ...A, ::std::size_t N>\nbool operator!=(::std::nullptr_t const,\n forwarder<R (A...), N> const& f) noexcept\n{\n return !operator==(f, nullptr);\n}\n\n}\n\n#endif \/\/ GENERIC_FORWARDER_HPP\n<commit_msg>some fixes<commit_after>#ifndef GENERIC_FORWARDER_HPP\n# define GENERIC_FORWARDER_HPP\n# pragma once\n\n#include <cassert>\n\n\/\/ ::std::size_t\n#include <cstddef>\n\n#include <functional>\n\n#include <type_traits>\n\n#include <utility>\n\nnamespace generic\n{\n\nnamespace detail\n{\n\nnamespace forwarder\n{\n\ntemplate <typename ...A>\nstruct argument_types\n{\n};\n\ntemplate <typename A>\nstruct argument_types<A>\n{\n using argument_type = A;\n};\n\ntemplate <typename A, typename B>\nstruct argument_types<A, B>\n{\n using first_argument_type = A;\n using second_argument_type = B;\n};\n\n}\n\n}\n\nconstexpr auto const default_forwarder_noexcept =\n#if __cpp_exceptions\nfalse;\n#else\ntrue;\n#endif \/\/ __cpp_exceptions\n\nconstexpr auto const default_forwarder_size = 4 * sizeof(void*);\n\ntemplate <typename F,\n bool NE = default_forwarder_noexcept,\n ::std::size_t N = default_forwarder_size>\nclass forwarder;\n\ntemplate <typename R, typename ...A, bool NE, ::std::size_t N>\nclass forwarder<R (A...), NE, N> : public detail::forwarder::argument_types<A...>\n{\n R (*stub_)(void const*, A&&...) noexcept(NE) {};\n\n typename ::std::aligned_storage_t<N> store_;\n\n template<typename T, typename ...U, ::std::size_t M>\n friend bool operator==(forwarder<T (U...), M> const&,\n ::std::nullptr_t) noexcept;\n template<typename T, typename ...U, ::std::size_t M>\n friend bool operator==(::std::nullptr_t,\n forwarder<T (U...), M> const&) noexcept;\n\n template<typename T, typename ...U, ::std::size_t M>\n friend bool operator!=(forwarder<T (U...), M> const&,\n ::std::nullptr_t) noexcept;\n template<typename T, typename ...U, ::std::size_t M>\n friend bool operator!=(::std::nullptr_t,\n forwarder<T (U...), M> const&) noexcept;\n\npublic:\n using result_type = R;\n\npublic:\n forwarder() = default;\n\n forwarder(forwarder const&) = default;\n\n forwarder(forwarder&&) = default;\n\n template<typename T>\n forwarder(T&& t) noexcept\n {\n assign(::std::forward<T>(t));\n }\n\n forwarder& operator=(forwarder const&) = default;\n\n forwarder& operator=(forwarder&&) = default;\n\n template <typename T>\n auto& operator=(T&& f) noexcept\n {\n assign(::std::forward<T>(f));\n\n return *this;\n }\n\n explicit operator bool() const noexcept { return stub_; }\n\n R operator()(A... args) const\n noexcept(noexcept(stub_(&store_, ::std::forward<A>(args)...)))\n {\n \/\/assert(stub_);\n return stub_(&store_, ::std::forward<A>(args)...);\n }\n\n void assign(::std::nullptr_t) noexcept\n {\n reset();\n }\n\n template <typename T>\n void assign(T&& f) noexcept\n {\n using functor_type = ::std::decay_t<T>;\n\n static_assert(sizeof(functor_type) <= sizeof(store_),\n \"functor too large\");\n static_assert(::std::is_trivially_copyable<functor_type>{},\n \"functor not trivially copyable\");\n\n ::new (static_cast<void*>(&store_)) functor_type(::std::forward<T>(f));\n\n stub_ = [](void const* const ptr, A&&... args) noexcept(\n noexcept(\n (\n#if __cplusplus <= 201402L\n *static_cast<functor_type const*>(ptr))(\n ::std::forward<A>(args)...)\n#else\n ::std::invoke(*static_cast<functor_type const*>(ptr),\n ::std::forward<A>(args)...)\n#endif \/\/ __cplusplus\n )\n ) -> R\n {\n#if __cplusplus <= 201402L\n return (*static_cast<functor_type const*>(ptr))(\n ::std::forward<A>(args)...);\n#else\n return ::std::invoke(*static_cast<functor_type const*>(ptr),\n ::std::forward<A>(args)...);\n#endif \/\/ __cplusplus\n };\n }\n\n void reset() noexcept { stub_ = nullptr; }\n\n void swap(forwarder& other) noexcept { ::std::swap(*this, other); }\n\n template <typename T>\n auto target() noexcept\n {\n return reinterpret_cast<T*>(&store_);\n }\n\n template <typename T> \n auto target() const noexcept\n {\n return reinterpret_cast<T const*>(&store_);\n }\n};\n\ntemplate<typename R, typename ...A, ::std::size_t N>\nbool operator==(forwarder<R (A...), N> const& f,\n ::std::nullptr_t const) noexcept\n{\n return f.stub_ == nullptr;\n}\n\ntemplate<typename R, typename ...A, ::std::size_t N>\nbool operator==(::std::nullptr_t const,\n forwarder<R (A...), N> const& f) noexcept\n{\n return f.stub_ == nullptr;\n}\n\ntemplate<typename R, typename ...A, ::std::size_t N>\nbool operator!=(forwarder<R (A...), N> const& f,\n ::std::nullptr_t const) noexcept\n{\n return !operator==(f, nullptr);\n}\n\ntemplate<typename R, typename ...A, ::std::size_t N>\nbool operator!=(::std::nullptr_t const,\n forwarder<R (A...), N> const& f) noexcept\n{\n return !operator==(f, nullptr);\n}\n\n}\n\n#endif \/\/ GENERIC_FORWARDER_HPP\n<|endoftext|>"} {"text":"<commit_before>\n\/*\n * Copyright 2011 Google Inc.\n *\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n *\/\n#include \"SkBenchmark.h\"\n#include \"SkBitmap.h\"\n#include \"SkCanvas.h\"\n#include \"SkColorPriv.h\"\n#include \"SkPaint.h\"\n#include \"SkShader.h\"\n#include \"SkString.h\"\n\nstatic const char* gConfigName[] = {\n \"ERROR\", \"a1\", \"a8\", \"index8\", \"565\", \"4444\", \"8888\"\n};\n\nstatic void drawIntoBitmap(const SkBitmap& bm) {\n const int w = bm.width();\n const int h = bm.height();\n\n SkCanvas canvas(bm);\n SkPaint p;\n p.setAntiAlias(true);\n p.setColor(SK_ColorRED);\n canvas.drawCircle(SkIntToScalar(w)\/2, SkIntToScalar(h)\/2,\n SkIntToScalar(SkMin32(w, h))*3\/8, p);\n\n SkRect r;\n r.set(0, 0, SkIntToScalar(w), SkIntToScalar(h));\n p.setStyle(SkPaint::kStroke_Style);\n p.setStrokeWidth(SkIntToScalar(4));\n p.setColor(SK_ColorBLUE);\n canvas.drawRect(r, p);\n}\n\nstatic int conv6ToByte(int x) {\n return x * 0xFF \/ 5;\n}\n\nstatic int convByteTo6(int x) {\n return x * 5 \/ 255;\n}\n\nstatic uint8_t compute666Index(SkPMColor c) {\n int r = SkGetPackedR32(c);\n int g = SkGetPackedG32(c);\n int b = SkGetPackedB32(c);\n\n return convByteTo6(r) * 36 + convByteTo6(g) * 6 + convByteTo6(b);\n}\n\nstatic void convertToIndex666(const SkBitmap& src, SkBitmap* dst) {\n SkColorTable* ctable = new SkColorTable(216);\n SkPMColor* colors = ctable->lockColors();\n \/\/ rrr ggg bbb\n for (int r = 0; r < 6; r++) {\n int rr = conv6ToByte(r);\n for (int g = 0; g < 6; g++) {\n int gg = conv6ToByte(g);\n for (int b = 0; b < 6; b++) {\n int bb = conv6ToByte(b);\n *colors++ = SkPreMultiplyARGB(0xFF, rr, gg, bb);\n }\n }\n }\n ctable->unlockColors(true);\n dst->setConfig(SkBitmap::kIndex8_Config, src.width(), src.height());\n dst->allocPixels(ctable);\n ctable->unref();\n\n SkAutoLockPixels alps(src);\n SkAutoLockPixels alpd(*dst);\n\n for (int y = 0; y < src.height(); y++) {\n const SkPMColor* srcP = src.getAddr32(0, y);\n uint8_t* dstP = dst->getAddr8(0, y);\n for (int x = src.width() - 1; x >= 0; --x) {\n *dstP++ = compute666Index(*srcP++);\n }\n }\n}\n\nclass RepeatTileBench : public SkBenchmark {\n SkPaint fPaint;\n SkString fName;\n enum { N = SkBENCHLOOP(20) };\npublic:\n RepeatTileBench(void* param, SkBitmap::Config c) : INHERITED(param) {\n const int w = 50;\n const int h = 50;\n SkBitmap bm;\n\n if (SkBitmap::kIndex8_Config == c) {\n bm.setConfig(SkBitmap::kARGB_8888_Config, w, h);\n } else {\n bm.setConfig(c, w, h);\n }\n bm.allocPixels();\n bm.eraseColor(0);\n\n drawIntoBitmap(bm);\n\n if (SkBitmap::kIndex8_Config == c) {\n SkBitmap tmp;\n convertToIndex666(bm, &tmp);\n bm = tmp;\n }\n\n SkShader* s = SkShader::CreateBitmapShader(bm,\n SkShader::kRepeat_TileMode,\n SkShader::kRepeat_TileMode);\n fPaint.setShader(s)->unref();\n fName.printf(\"repeatTile_%s\", gConfigName[bm.config()]);\n }\n\nprotected:\n virtual const char* onGetName() {\n return fName.c_str();\n }\n\n virtual void onDraw(SkCanvas* canvas) {\n SkPaint paint(fPaint);\n this->setupPaint(&paint);\n\n for (int i = 0; i < N; i++) {\n canvas->drawPaint(paint);\n }\n }\n\nprivate:\n typedef SkBenchmark INHERITED;\n};\n\nstatic SkBenchmark* Fact0(void* p) { return new RepeatTileBench(p, SkBitmap::kARGB_8888_Config); }\nstatic SkBenchmark* Fact1(void* p) { return new RepeatTileBench(p, SkBitmap::kRGB_565_Config); }\nstatic SkBenchmark* Fact2(void* p) { return new RepeatTileBench(p, SkBitmap::kARGB_4444_Config); }\nstatic SkBenchmark* Fact3(void* p) { return new RepeatTileBench(p, SkBitmap::kIndex8_Config); }\n\nstatic BenchRegistry gReg0(Fact0);\nstatic BenchRegistry gReg1(Fact1);\nstatic BenchRegistry gReg2(Fact2);\nstatic BenchRegistry gReg3(Fact3);\n<commit_msg>add opaque\/alpha variants<commit_after>\n\/*\n * Copyright 2011 Google Inc.\n *\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n *\/\n#include \"SkBenchmark.h\"\n#include \"SkBitmap.h\"\n#include \"SkCanvas.h\"\n#include \"SkColorPriv.h\"\n#include \"SkPaint.h\"\n#include \"SkShader.h\"\n#include \"SkString.h\"\n\nstatic const char* gConfigName[] = {\n \"ERROR\", \"a1\", \"a8\", \"index8\", \"565\", \"4444\", \"8888\"\n};\n\nstatic void drawIntoBitmap(const SkBitmap& bm) {\n const int w = bm.width();\n const int h = bm.height();\n\n SkCanvas canvas(bm);\n SkPaint p;\n p.setAntiAlias(true);\n p.setColor(SK_ColorRED);\n canvas.drawCircle(SkIntToScalar(w)\/2, SkIntToScalar(h)\/2,\n SkIntToScalar(SkMin32(w, h))*3\/8, p);\n\n SkRect r;\n r.set(0, 0, SkIntToScalar(w), SkIntToScalar(h));\n p.setStyle(SkPaint::kStroke_Style);\n p.setStrokeWidth(SkIntToScalar(4));\n p.setColor(SK_ColorBLUE);\n canvas.drawRect(r, p);\n}\n\nstatic int conv6ToByte(int x) {\n return x * 0xFF \/ 5;\n}\n\nstatic int convByteTo6(int x) {\n return x * 5 \/ 255;\n}\n\nstatic uint8_t compute666Index(SkPMColor c) {\n int r = SkGetPackedR32(c);\n int g = SkGetPackedG32(c);\n int b = SkGetPackedB32(c);\n\n return convByteTo6(r) * 36 + convByteTo6(g) * 6 + convByteTo6(b);\n}\n\nstatic void convertToIndex666(const SkBitmap& src, SkBitmap* dst) {\n SkColorTable* ctable = new SkColorTable(216);\n SkPMColor* colors = ctable->lockColors();\n \/\/ rrr ggg bbb\n for (int r = 0; r < 6; r++) {\n int rr = conv6ToByte(r);\n for (int g = 0; g < 6; g++) {\n int gg = conv6ToByte(g);\n for (int b = 0; b < 6; b++) {\n int bb = conv6ToByte(b);\n *colors++ = SkPreMultiplyARGB(0xFF, rr, gg, bb);\n }\n }\n }\n ctable->unlockColors(true);\n dst->setConfig(SkBitmap::kIndex8_Config, src.width(), src.height());\n dst->allocPixels(ctable);\n ctable->unref();\n\n SkAutoLockPixels alps(src);\n SkAutoLockPixels alpd(*dst);\n\n for (int y = 0; y < src.height(); y++) {\n const SkPMColor* srcP = src.getAddr32(0, y);\n uint8_t* dstP = dst->getAddr8(0, y);\n for (int x = src.width() - 1; x >= 0; --x) {\n *dstP++ = compute666Index(*srcP++);\n }\n }\n}\n\nclass RepeatTileBench : public SkBenchmark {\n SkPaint fPaint;\n SkString fName;\n enum { N = SkBENCHLOOP(20) };\npublic:\n RepeatTileBench(void* param, SkBitmap::Config c, bool isOpaque = false) : INHERITED(param) {\n const int w = 50;\n const int h = 50;\n SkBitmap bm;\n\n if (SkBitmap::kIndex8_Config == c) {\n bm.setConfig(SkBitmap::kARGB_8888_Config, w, h);\n } else {\n bm.setConfig(c, w, h);\n }\n bm.allocPixels();\n bm.eraseColor(isOpaque ? SK_ColorWHITE : 0);\n bm.setIsOpaque(isOpaque);\n\n drawIntoBitmap(bm);\n\n if (SkBitmap::kIndex8_Config == c) {\n SkBitmap tmp;\n convertToIndex666(bm, &tmp);\n bm = tmp;\n }\n\n SkShader* s = SkShader::CreateBitmapShader(bm,\n SkShader::kRepeat_TileMode,\n SkShader::kRepeat_TileMode);\n fPaint.setShader(s)->unref();\n fName.printf(\"repeatTile_%s_%c\", gConfigName[bm.config()], isOpaque ? 'X' : 'A');\n }\n\nprotected:\n virtual const char* onGetName() {\n return fName.c_str();\n }\n\n virtual void onDraw(SkCanvas* canvas) {\n SkPaint paint(fPaint);\n this->setupPaint(&paint);\n\n for (int i = 0; i < N; i++) {\n canvas->drawPaint(paint);\n }\n }\n\nprivate:\n typedef SkBenchmark INHERITED;\n};\n\nDEF_BENCH(return new RepeatTileBench(p, SkBitmap::kARGB_8888_Config, true))\nDEF_BENCH(return new RepeatTileBench(p, SkBitmap::kARGB_8888_Config, false))\nDEF_BENCH(return new RepeatTileBench(p, SkBitmap::kRGB_565_Config))\nDEF_BENCH(return new RepeatTileBench(p, SkBitmap::kARGB_4444_Config))\nDEF_BENCH(return new RepeatTileBench(p, SkBitmap::kIndex8_Config))\n\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ CPlayer.cpp\n\/\/ SwingGame\n\/\/\n\/\/ Created by Tim Brier on 11\/10\/2014.\n\/\/ Copyright (c) 2014 tbrier. All rights reserved.\n\/\/\n\n\/\/ =============================================================================\n\/\/ Include Files\n\/\/ -----------------------------------------------------------------------------\n#include \"SFMLIntegration\/SFMLIntegration.hpp\"\n#include \"CPlayer.hpp\"\n#include \"SystemUtilities.hpp\"\n#include \"CSwingGame.hpp\"\n#include \"CLevel.hpp\"\n#include \"CLine.hpp\"\n#include \"CollisionHandler.hpp\"\n#include \"CRigidSwing.hpp\"\n#include \"CFlexibleSwing.hpp\"\n#include \"CSpringSwing.hpp\"\n\n\/\/ =============================================================================\n\/\/ Static members\n\/\/ -----------------------------------------------------------------------------\nCVector2f CPlayer::smJumpVelocity = CVector2f(0.0f, -250.0f);\nCTime CPlayer::smJumpCooldown = CTime::Seconds(1.5f);\n\n\/\/ =============================================================================\n\/\/ SUVAT Helper Methods\n\/\/ -----------------------------------------------------------------------------\nCVector2f GetVectorMoved(CVector2f u, CTime t, CVector2f a)\n{\n \/\/ s = ut + 0.5at^2\n float ts = t.asSeconds();\n return (u * ts) + (0.5f * a * ts * ts);\n}\n\nCVector2f GetFinalVelocity(CVector2f u, CVector2f a, CTime t)\n{\n \/\/ v = u + at\n float ts = t.asSeconds();\n return u + (a * ts);\n}\n\n\/\/ =============================================================================\n\/\/ CPlayer constructor\/destrctor\n\/\/ -----------------------------------------------------------------------------\nCPlayer::CPlayer(CLevel *theParentLevel) : mParentLevel(theParentLevel)\n{\n \/\/ Create the shape\n mSmallestRadius = 10.0f;\n \n std::list<CVector2f> thePoints;\n thePoints.push_back(CVector2f(-mSmallestRadius, -mSmallestRadius));\n thePoints.push_back(CVector2f(mSmallestRadius, -mSmallestRadius));\n thePoints.push_back(CVector2f(mSmallestRadius, mSmallestRadius));\n thePoints.push_back(CVector2f(-mSmallestRadius, mSmallestRadius));\n \n SetShape(CConvexShape(thePoints));\n GetShape()->setFillColor(CColour(255, 0, 255));\n \n float mass = 1.0f; \/\/ Read from file?\n SetInverseMass(1.0f \/ mass);\n}\n\nCPlayer::~CPlayer()\n{\n \n}\n\n\/\/ =============================================================================\n\/\/ CPlayer::Update\n\/\/ -----------------------------------------------------------------------------\nvoid CPlayer::Update(CTime elapsedTime)\n{\n HandleInput();\n \n \/\/ Now simulate the physics until we've simulated the entire elapsedTime\n while (elapsedTime > CTime::Zero)\n {\n \/\/ Find the acceleration applied by any physics items\n CVector2f acceleration = HandlePhysics();\n \n \/\/ Now try to move based on our velocity\n CTime timeSimulated = MoveUntilCollision(elapsedTime, acceleration);\n elapsedTime -= timeSimulated;\n }\n}\n\n\/\/ =============================================================================\n\/\/ CPlayer::ShouldUpdateForState\n\/\/ -----------------------------------------------------------------------------\nbool CPlayer::ShouldUpdateForState(EGameState theState)\n{\n \/\/ Only update if we're not paused\n if ((theState & kGameStatePaused) != 0)\n {\n return false;\n }\n \n return CUpdateable::ShouldUpdateForState(theState);\n}\n\n\/\/ =============================================================================\n\/\/ CPlayer::Draw\n\/\/ -----------------------------------------------------------------------------\nvoid CPlayer::Draw(CWindow *theWindow)\n{\n \/\/ Colour the player by the colour of the swing we will fire\n GetShape()->setFillColor(mSwings[mSwingToFire]->GetColour());\n theWindow->DrawShape(*GetShape());\n}\n\n\/\/ =============================================================================\n\/\/ CPlayer::Init\n\/\/ -----------------------------------------------------------------------------\nvoid CPlayer::Init()\n{\n \/\/ Register any update\/renderables\n CSwingGame::RegisterUpdateable(this);\n CSwingGame::RegisterRenderable(this);\n \n mSwings[kSwingTypeRigid] = new CRigidSwing(this, mParentLevel);\n mSwings[kSwingTypeFlexible] = new CFlexibleSwing(this, mParentLevel);\n mSwings[kSwingTypeSpring] = new CSpringSwing(this, mParentLevel);\n}\n\n\/\/ =============================================================================\n\/\/ CPlayer::Cleanup\n\/\/ -----------------------------------------------------------------------------\nvoid CPlayer::Cleanup()\n{\n SAFE_DELETE(mSwings[kSwingTypeRigid]);\n SAFE_DELETE(mSwings[kSwingTypeFlexible]);\n SAFE_DELETE(mSwings[kSwingTypeSpring]);\n \n \/\/ Unregister update\/renderables\n CSwingGame::UnregisterUpdateable(this);\n CSwingGame::UnregisterRenderable(this);\n}\n\n\/\/ =============================================================================\n\/\/ CPlayer::StartLevel\n\/\/ -----------------------------------------------------------------------------\nvoid CPlayer::StartLevel(SStartPosition theStartPos)\n{\n GetShape()->setPosition(theStartPos.mPosition);\n SetVelocity(theStartPos.mVelocity);\n \n for (int i = 0; i < kSwingTypeMax; i++)\n {\n mSwings[i]->Detach();\n }\n \n mSwingToFire = theStartPos.mSwingType;\n mCurrentSwing = mSwings[mSwingToFire];\n \n mCurrentSwing->AttemptToAttach(theStartPos.mSwingTarget);\n \n \/\/ Start the jump clock at the cooldown time so we can jump straight away\n mJumpClock.Restart(smJumpCooldown);\n}\n\n\/\/ =============================================================================\n\/\/ CPlayer::HandleInput\n\/\/ -----------------------------------------------------------------------------\nvoid CPlayer::HandleInput()\n{\n#if SG_DEBUG \/\/ In debug move the player to the mouse pos if r shift is down\n if (CKeyboard::isKeyPressed(CKeyboard::RShift))\n {\n GetShape()->setPosition(SystemUtilities::GetMousePosition());\n HandleCollisions();\n \n \/\/ Reset velocity\n SetVelocity(CVector2f(0.0f, 0.0f));\n }\n#endif\n \n \/\/ Connect the swing on left mouse click\n CVector2f mousePos;\n if (SystemUtilities::WasButtonPressedThisCycle(CMouse::Left, &mousePos))\n {\n \/\/ Detach the current swing before we try to fire the next\n mCurrentSwing->Detach();\n \n \/\/ Update the current swing type and try to attach it\n mCurrentSwing = mSwings[mSwingToFire];\n mCurrentSwing->AttemptToAttach(mousePos);\n }\n \n \/\/ Disconnect on right click\n if (SystemUtilities::WasButtonPressedThisCycle(CMouse::Right, &mousePos))\n {\n \/\/ We specifically requested this detach so respond to it\n mCurrentSwing->Detach(true);\n }\n \n \/\/ Jump on space\n if (SystemUtilities::WasKeyPressedThisCycle(CKeyboard::Space))\n {\n \/\/ Only jump if we're attached to a swing, and detach it when we do\n if (mCurrentSwing->CanJumpFrom()\n && mJumpClock.GetElapsedTime() >= smJumpCooldown)\n {\n mCurrentSwing->Detach();\n SetVelocity(GetVelocity() + smJumpVelocity);\n mJumpClock.Restart();\n }\n }\n \n \/\/ Change swing type\n if (SystemUtilities::WasKeyPressedThisCycle(CKeyboard::Num1))\n {\n mSwingToFire = kSwingTypeRigid;\n }\n if (SystemUtilities::WasKeyPressedThisCycle(CKeyboard::Num2))\n {\n mSwingToFire = kSwingTypeFlexible;\n }\n if (SystemUtilities::WasKeyPressedThisCycle(CKeyboard::Num3))\n {\n mSwingToFire = kSwingTypeSpring;\n }\n}\n\n\/\/ =============================================================================\n\/\/ CPlayer::HandlePhysics\n\/\/ Return the resulting acceleration of the player\n\/\/ -----------------------------------------------------------------------------\nCVector2f CPlayer::HandlePhysics()\n{\n CVector2f acceleration = mParentLevel->GetGravityAcceleration();\n \n acceleration = mCurrentSwing->AttenuateGravity(acceleration);\n \n return acceleration;\n}\n\n\/\/ =============================================================================\n\/\/ CPlayer::HandleCollisions\n\/\/ Return true if we resolved a collision\n\/\/ -----------------------------------------------------------------------------\nbool CPlayer::HandleCollisions(bool shouldResolve \/* = false *\/)\n{\n bool didCollide = false;\n \n \/\/ Check for collisions against all level obstacles\n std::list<CPhysicsBody *> theObstacles = mParentLevel->GetObstacles();\n \n CVector2f correctionVector;\n FOR_EACH_IN_LIST(CPhysicsBody *, theObstacles)\n {\n if (CollisionHandler::AreColliding(*GetShape(),\n *((*it)->GetShape()),\n &correctionVector))\n {\n didCollide = true;\n \n if (shouldResolve)\n {\n \/\/ Resolve the collision\n CollisionHandler::Resolve(this, (*it), correctionVector);\n }\n }\n }\n \n return didCollide;\n}\n\n\/\/ =============================================================================\n\/\/ CPlayer::MoveUntilCollision\n\/\/ Move for the given amount of time with the given acceleration or until\n\/\/ we collide\n\/\/ Return the time we actually simulated movement for\n\/\/ -----------------------------------------------------------------------------\nCTime CPlayer::MoveUntilCollision(CTime elapsedTime, CVector2f acceleration)\n{\n \/\/ Find the total offset we've been requested to move\n CVector2f totalOffset;\n totalOffset = GetVectorMoved(GetVelocity(), elapsedTime, acceleration);\n float totalDistance = totalOffset.GetMagnitude();\n \n \/\/ If we don't need to move bail out\n if (totalDistance == 0)\n {\n return elapsedTime;\n }\n \n \/\/ Find how many timesteps we should use to make sure we don't move by\n \/\/ more than the shapes smallest \"radius\"\n int numTimesteps = ceil(totalDistance \/ mSmallestRadius);\n \n \/\/ Find how big this timesteps should be\n CTime timeStep = elapsedTime \/ (numTimesteps * 1.0f);\n \n \/\/ Now find how far we should move for each timestep\n CVector2f smallOffset = totalOffset \/ (numTimesteps * 1.0f);\n \n \/\/ And simulate these timesteps until we've done them all or we've collided\n bool haveCollided = false;\n CTime timeSimulatedSoFar = CTime::Zero;\n for (int i = 0; i < numTimesteps && !haveCollided; i++)\n {\n \/\/ Update velocity to what it will be at the end of this timestep\n SetVelocity(GetFinalVelocity(GetVelocity(), acceleration, timeStep));\n \n \/\/ Now move the shape and handle any collisions\n GetShape()->move(smallOffset);\n haveCollided = HandleCollisions();\n \n timeSimulatedSoFar += timeStep;\n }\n \n return timeSimulatedSoFar;\n}\n\n\/\/ =============================================================================\n\/\/ CPlayer::MoveFixedDistanceUntilCollision\n\/\/ -----------------------------------------------------------------------------\nvoid CPlayer::MoveFixedDistanceUntilCollision(CVector2f offset)\n{\n \/\/ Find out how far we want to move\n CVector2f totalOffset = offset;\n float totalDistance = totalOffset.GetMagnitude();\n \n \/\/ Break it down into a number of smaller offsets\n int numSteps = ceil(totalDistance \/ mSmallestRadius);\n CVector2f smallOffset = totalOffset \/ (numSteps * 1.0f);\n \n \/\/ Apply these until we collide\n bool haveCollided = false;\n for (int i = 0; i < numSteps && !haveCollided; i++)\n {\n \/\/ Move by the small offset\n GetShape()->move(smallOffset);\n haveCollided = HandleCollisions();\n }\n}\n\n\/\/ =============================================================================\n\/\/ CPlayer::IsColliding\n\/\/ -----------------------------------------------------------------------------\nbool CPlayer::IsColliding()\n{\n \/\/ Let HandleCollisions do this check\n return HandleCollisions(false);\n}\n\n\/\/ =============================================================================\n\/\/ CPlayer::PauseClocks()\n\/\/ -----------------------------------------------------------------------------\nvoid CPlayer::PauseClocks(bool paused)\n{\n if (paused)\n {\n mJumpClock.Pause();\n }\n else\n {\n mJumpClock.Resume();\n }\n}<commit_msg>Draw the jumo cooldown<commit_after>\/\/\n\/\/ CPlayer.cpp\n\/\/ SwingGame\n\/\/\n\/\/ Created by Tim Brier on 11\/10\/2014.\n\/\/ Copyright (c) 2014 tbrier. All rights reserved.\n\/\/\n\n\/\/ =============================================================================\n\/\/ Include Files\n\/\/ -----------------------------------------------------------------------------\n#include \"SFMLIntegration\/SFMLIntegration.hpp\"\n#include \"CPlayer.hpp\"\n#include \"SystemUtilities.hpp\"\n#include \"CSwingGame.hpp\"\n#include \"CLevel.hpp\"\n#include \"CLine.hpp\"\n#include \"CollisionHandler.hpp\"\n#include \"CRigidSwing.hpp\"\n#include \"CFlexibleSwing.hpp\"\n#include \"CSpringSwing.hpp\"\n\n\/\/ =============================================================================\n\/\/ Static members\n\/\/ -----------------------------------------------------------------------------\nCVector2f CPlayer::smJumpVelocity = CVector2f(0.0f, -250.0f);\nCTime CPlayer::smJumpCooldown = CTime::Seconds(1.5f);\n\n\/\/ =============================================================================\n\/\/ SUVAT Helper Methods\n\/\/ -----------------------------------------------------------------------------\nCVector2f GetVectorMoved(CVector2f u, CTime t, CVector2f a)\n{\n \/\/ s = ut + 0.5at^2\n float ts = t.asSeconds();\n return (u * ts) + (0.5f * a * ts * ts);\n}\n\nCVector2f GetFinalVelocity(CVector2f u, CVector2f a, CTime t)\n{\n \/\/ v = u + at\n float ts = t.asSeconds();\n return u + (a * ts);\n}\n\n\/\/ =============================================================================\n\/\/ CPlayer constructor\/destrctor\n\/\/ -----------------------------------------------------------------------------\nCPlayer::CPlayer(CLevel *theParentLevel) : mParentLevel(theParentLevel)\n{\n \/\/ Create the shape\n mSmallestRadius = 10.0f;\n \n std::list<CVector2f> thePoints;\n thePoints.push_back(CVector2f(-mSmallestRadius, -mSmallestRadius));\n thePoints.push_back(CVector2f(mSmallestRadius, -mSmallestRadius));\n thePoints.push_back(CVector2f(mSmallestRadius, mSmallestRadius));\n thePoints.push_back(CVector2f(-mSmallestRadius, mSmallestRadius));\n \n SetShape(CConvexShape(thePoints));\n GetShape()->setFillColor(CColour(255, 0, 255));\n \n float mass = 1.0f; \/\/ Read from file?\n SetInverseMass(1.0f \/ mass);\n}\n\nCPlayer::~CPlayer()\n{\n \n}\n\n\/\/ =============================================================================\n\/\/ CPlayer::Update\n\/\/ -----------------------------------------------------------------------------\nvoid CPlayer::Update(CTime elapsedTime)\n{\n HandleInput();\n \n \/\/ Now simulate the physics until we've simulated the entire elapsedTime\n while (elapsedTime > CTime::Zero)\n {\n \/\/ Find the acceleration applied by any physics items\n CVector2f acceleration = HandlePhysics();\n \n \/\/ Now try to move based on our velocity\n CTime timeSimulated = MoveUntilCollision(elapsedTime, acceleration);\n elapsedTime -= timeSimulated;\n }\n}\n\n\/\/ =============================================================================\n\/\/ CPlayer::ShouldUpdateForState\n\/\/ -----------------------------------------------------------------------------\nbool CPlayer::ShouldUpdateForState(EGameState theState)\n{\n \/\/ Only update if we're not paused\n if ((theState & kGameStatePaused) != 0)\n {\n return false;\n }\n \n return CUpdateable::ShouldUpdateForState(theState);\n}\n\n\/\/ =============================================================================\n\/\/ CPlayer::Draw\n\/\/ -----------------------------------------------------------------------------\nvoid CPlayer::Draw(CWindow *theWindow)\n{\n \/\/ Colour the player by the colour of the swing we will fire\n GetShape()->setFillColor(mSwings[mSwingToFire]->GetColour());\n theWindow->DrawShape(*GetShape());\n \n \/\/ Draw the cooldown timer for jumping\n CTime jumpClockTime = mJumpClock.GetElapsedTime();\n if (jumpClockTime < smJumpCooldown)\n {\n CTime timeLeft = smJumpCooldown - jumpClockTime;\n float percentageLeft = timeLeft \/ smJumpCooldown;\n float cooldownBarWidth = percentageLeft * (mSmallestRadius * 2.0f);\n float cooldownBarLeft = GetPosition().x - mSmallestRadius;\n float cooldownBarTop = GetPosition().y - 2.5f;\n std::list<CVector2f> points;\n points.push_back(CVector2f(0.0f, 0.0f));\n points.push_back(CVector2f(cooldownBarWidth, 0.0f));\n points.push_back(CVector2f(cooldownBarWidth, 5.0f));\n points.push_back(CVector2f(0.0f, 5.0f));\n CConvexShape cooldownBar(points);\n cooldownBar.setPosition(cooldownBarLeft, cooldownBarTop);\n cooldownBar.setFillColor(CColour::Red);\n theWindow->DrawShape(cooldownBar);\n }\n}\n\n\/\/ =============================================================================\n\/\/ CPlayer::Init\n\/\/ -----------------------------------------------------------------------------\nvoid CPlayer::Init()\n{\n \/\/ Register any update\/renderables\n CSwingGame::RegisterUpdateable(this);\n CSwingGame::RegisterRenderable(this);\n \n mSwings[kSwingTypeRigid] = new CRigidSwing(this, mParentLevel);\n mSwings[kSwingTypeFlexible] = new CFlexibleSwing(this, mParentLevel);\n mSwings[kSwingTypeSpring] = new CSpringSwing(this, mParentLevel);\n}\n\n\/\/ =============================================================================\n\/\/ CPlayer::Cleanup\n\/\/ -----------------------------------------------------------------------------\nvoid CPlayer::Cleanup()\n{\n SAFE_DELETE(mSwings[kSwingTypeRigid]);\n SAFE_DELETE(mSwings[kSwingTypeFlexible]);\n SAFE_DELETE(mSwings[kSwingTypeSpring]);\n \n \/\/ Unregister update\/renderables\n CSwingGame::UnregisterUpdateable(this);\n CSwingGame::UnregisterRenderable(this);\n}\n\n\/\/ =============================================================================\n\/\/ CPlayer::StartLevel\n\/\/ -----------------------------------------------------------------------------\nvoid CPlayer::StartLevel(SStartPosition theStartPos)\n{\n GetShape()->setPosition(theStartPos.mPosition);\n SetVelocity(theStartPos.mVelocity);\n \n for (int i = 0; i < kSwingTypeMax; i++)\n {\n mSwings[i]->Detach();\n }\n \n mSwingToFire = theStartPos.mSwingType;\n mCurrentSwing = mSwings[mSwingToFire];\n \n mCurrentSwing->AttemptToAttach(theStartPos.mSwingTarget);\n \n \/\/ Start the jump clock at the cooldown time so we can jump straight away\n mJumpClock.Restart(smJumpCooldown);\n}\n\n\/\/ =============================================================================\n\/\/ CPlayer::HandleInput\n\/\/ -----------------------------------------------------------------------------\nvoid CPlayer::HandleInput()\n{\n#if SG_DEBUG \/\/ In debug move the player to the mouse pos if r shift is down\n if (CKeyboard::isKeyPressed(CKeyboard::RShift))\n {\n GetShape()->setPosition(SystemUtilities::GetMousePosition());\n HandleCollisions();\n \n \/\/ Reset velocity\n SetVelocity(CVector2f(0.0f, 0.0f));\n }\n#endif\n \n \/\/ Connect the swing on left mouse click\n CVector2f mousePos;\n if (SystemUtilities::WasButtonPressedThisCycle(CMouse::Left, &mousePos))\n {\n \/\/ Detach the current swing before we try to fire the next\n mCurrentSwing->Detach();\n \n \/\/ Update the current swing type and try to attach it\n mCurrentSwing = mSwings[mSwingToFire];\n mCurrentSwing->AttemptToAttach(mousePos);\n }\n \n \/\/ Disconnect on right click\n if (SystemUtilities::WasButtonPressedThisCycle(CMouse::Right, &mousePos))\n {\n \/\/ We specifically requested this detach so respond to it\n mCurrentSwing->Detach(true);\n }\n \n \/\/ Jump on space\n if (SystemUtilities::WasKeyPressedThisCycle(CKeyboard::Space))\n {\n \/\/ Only jump if we're attached to a swing, and detach it when we do\n if (mCurrentSwing->CanJumpFrom()\n && mJumpClock.GetElapsedTime() >= smJumpCooldown)\n {\n mCurrentSwing->Detach();\n SetVelocity(GetVelocity() + smJumpVelocity);\n mJumpClock.Restart();\n }\n }\n \n \/\/ Change swing type\n if (SystemUtilities::WasKeyPressedThisCycle(CKeyboard::Num1))\n {\n mSwingToFire = kSwingTypeRigid;\n }\n if (SystemUtilities::WasKeyPressedThisCycle(CKeyboard::Num2))\n {\n mSwingToFire = kSwingTypeFlexible;\n }\n if (SystemUtilities::WasKeyPressedThisCycle(CKeyboard::Num3))\n {\n mSwingToFire = kSwingTypeSpring;\n }\n}\n\n\/\/ =============================================================================\n\/\/ CPlayer::HandlePhysics\n\/\/ Return the resulting acceleration of the player\n\/\/ -----------------------------------------------------------------------------\nCVector2f CPlayer::HandlePhysics()\n{\n CVector2f acceleration = mParentLevel->GetGravityAcceleration();\n \n acceleration = mCurrentSwing->AttenuateGravity(acceleration);\n \n return acceleration;\n}\n\n\/\/ =============================================================================\n\/\/ CPlayer::HandleCollisions\n\/\/ Return true if we resolved a collision\n\/\/ -----------------------------------------------------------------------------\nbool CPlayer::HandleCollisions(bool shouldResolve \/* = false *\/)\n{\n bool didCollide = false;\n \n \/\/ Check for collisions against all level obstacles\n std::list<CPhysicsBody *> theObstacles = mParentLevel->GetObstacles();\n \n CVector2f correctionVector;\n FOR_EACH_IN_LIST(CPhysicsBody *, theObstacles)\n {\n if (CollisionHandler::AreColliding(*GetShape(),\n *((*it)->GetShape()),\n &correctionVector))\n {\n didCollide = true;\n \n if (shouldResolve)\n {\n \/\/ Resolve the collision\n CollisionHandler::Resolve(this, (*it), correctionVector);\n }\n }\n }\n \n return didCollide;\n}\n\n\/\/ =============================================================================\n\/\/ CPlayer::MoveUntilCollision\n\/\/ Move for the given amount of time with the given acceleration or until\n\/\/ we collide\n\/\/ Return the time we actually simulated movement for\n\/\/ -----------------------------------------------------------------------------\nCTime CPlayer::MoveUntilCollision(CTime elapsedTime, CVector2f acceleration)\n{\n \/\/ Find the total offset we've been requested to move\n CVector2f totalOffset;\n totalOffset = GetVectorMoved(GetVelocity(), elapsedTime, acceleration);\n float totalDistance = totalOffset.GetMagnitude();\n \n \/\/ If we don't need to move bail out\n if (totalDistance == 0)\n {\n return elapsedTime;\n }\n \n \/\/ Find how many timesteps we should use to make sure we don't move by\n \/\/ more than the shapes smallest \"radius\"\n int numTimesteps = ceil(totalDistance \/ mSmallestRadius);\n \n \/\/ Find how big this timesteps should be\n CTime timeStep = elapsedTime \/ (numTimesteps * 1.0f);\n \n \/\/ Now find how far we should move for each timestep\n CVector2f smallOffset = totalOffset \/ (numTimesteps * 1.0f);\n \n \/\/ And simulate these timesteps until we've done them all or we've collided\n bool haveCollided = false;\n CTime timeSimulatedSoFar = CTime::Zero;\n for (int i = 0; i < numTimesteps && !haveCollided; i++)\n {\n \/\/ Update velocity to what it will be at the end of this timestep\n SetVelocity(GetFinalVelocity(GetVelocity(), acceleration, timeStep));\n \n \/\/ Now move the shape and handle any collisions\n GetShape()->move(smallOffset);\n haveCollided = HandleCollisions();\n \n timeSimulatedSoFar += timeStep;\n }\n \n return timeSimulatedSoFar;\n}\n\n\/\/ =============================================================================\n\/\/ CPlayer::MoveFixedDistanceUntilCollision\n\/\/ -----------------------------------------------------------------------------\nvoid CPlayer::MoveFixedDistanceUntilCollision(CVector2f offset)\n{\n \/\/ Find out how far we want to move\n CVector2f totalOffset = offset;\n float totalDistance = totalOffset.GetMagnitude();\n \n \/\/ Break it down into a number of smaller offsets\n int numSteps = ceil(totalDistance \/ mSmallestRadius);\n CVector2f smallOffset = totalOffset \/ (numSteps * 1.0f);\n \n \/\/ Apply these until we collide\n bool haveCollided = false;\n for (int i = 0; i < numSteps && !haveCollided; i++)\n {\n \/\/ Move by the small offset\n GetShape()->move(smallOffset);\n haveCollided = HandleCollisions();\n }\n}\n\n\/\/ =============================================================================\n\/\/ CPlayer::IsColliding\n\/\/ -----------------------------------------------------------------------------\nbool CPlayer::IsColliding()\n{\n \/\/ Let HandleCollisions do this check\n return HandleCollisions(false);\n}\n\n\/\/ =============================================================================\n\/\/ CPlayer::PauseClocks()\n\/\/ -----------------------------------------------------------------------------\nvoid CPlayer::PauseClocks(bool paused)\n{\n if (paused)\n {\n mJumpClock.Pause();\n }\n else\n {\n mJumpClock.Resume();\n }\n}<|endoftext|>"} {"text":"<commit_before>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\n\/\/\/ \\file generic.hpp\n\/\/\/ -----------------\n\/\/\/\n\/\/\/ (c) Copyright Domagoj Saric 2016.\n\/\/\/\n\/\/\/ Use, modification and distribution are subject to the\n\/\/\/ Boost Software License, Version 1.0. (See accompanying file\n\/\/\/ LICENSE_1_0.txt or copy at http:\/\/www.boost.org\/LICENSE_1_0.txt)\n\/\/\/\n\/\/\/ See http:\/\/www.boost.org for most recent version.\n\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/------------------------------------------------------------------------------\n#ifndef generic_hpp__99FE2034_248F_4C7D_8CD2_EB2BB8247377\n#define generic_hpp__99FE2034_248F_4C7D_8CD2_EB2BB8247377\n#pragma once\n\/\/------------------------------------------------------------------------------\n#include <boost\/sweater\/queues\/mpmc_moodycamel.hpp>\n\n#include <boost\/config_ex.hpp>\n#include <boost\/container\/small_vector.hpp>\n#include <boost\/container\/static_vector.hpp>\n#include <boost\/functionoid\/functionoid.hpp>\n#include <boost\/range\/algorithm\/count_if.hpp>\n#include <boost\/range\/iterator_range_core.hpp>\n#include <boost\/throw_exception.hpp>\n\n#include <atomic>\n#include <cstdint>\n#include <future>\n#include <iterator>\n#ifdef _MSC_VER\n#include <malloc.h>\n#else\n#include <alloca.h>\n#endif \/\/ _MSC_VER\n#include <memory>\n#include <mutex>\n#include <thread>\n\/\/------------------------------------------------------------------------------\nnamespace boost\n{\n\/\/------------------------------------------------------------------------------\nnamespace sweater\n{\n\/\/------------------------------------------------------------------------------\n\n#ifndef BOOST_SWEATER_MAX_HARDWARE_CONCURRENCY\n#\tdefine BOOST_SWEATER_MAX_HARDWARE_CONCURRENCY 0\n#endif \/\/ BOOST_SWEATER_MAX_HARDWARE_CONCURRENCY\n\nnamespace queues { template <typename Work> class mpmc_moodycamel; }\n\nBOOST_OVERRIDABLE_SYMBOL\nauto const hardware_concurrency( static_cast<std::uint8_t>( std::thread::hardware_concurrency() ) );\n\nclass impl\n{\nprivate:\n#ifdef __ANROID__\n \/\/ https:\/\/petewarden.com\/2015\/10\/11\/one-weird-trick-for-faster-android-multithreading\n static auto constexpr spin_count = 30 * 1000 * 1000;\n#else\n static auto constexpr spin_count = 1;\n#endif \/\/ __ANROID__\n\n struct worker_traits : functionoid::std_traits\n {\n static constexpr auto copyable = functionoid::support_level::na ;\n static constexpr auto moveable = functionoid::support_level::nofail ;\n static constexpr auto destructor = functionoid::support_level::trivial;\n static constexpr auto is_noexcept = true;\n static constexpr auto rtti = false;\n\n using empty_handler = functionoid::assert_on_empty;\n }; \/\/ struct worker_traits\n\n using worker_counter = std::atomic<std::uint16_t>;\n\n class batch_semaphore\n {\n public:\n batch_semaphore( std::uint16_t const initial_value ) : counter( initial_value ) {}\n\n void release() noexcept\n {\n std::unique_lock<std::mutex> lock( mutex );\n if ( counter.fetch_sub( 1, std::memory_order_acquire ) == 1 )\n event.notify_one();\n }\n\n BOOST_NOINLINE\n void wait() noexcept\n {\n for ( auto try_count( 0 ); try_count < spin_count; ++try_count )\n {\n bool const all_workers_done( counter.load( std::memory_order_relaxed ) == 0 );\n if ( BOOST_LIKELY( all_workers_done ) )\n return;\n }\n std::unique_lock<std::mutex> lock( mutex );\n while ( BOOST_UNLIKELY( counter.load( std::memory_order_relaxed ) != 0 ) )\n event.wait( lock );\n }\n\n private:\n worker_counter counter;\n mutable std::condition_variable event;\n std::mutex mutex;\n }; \/\/ struct batch_semaphore\n\n using work_t = functionoid::callable<void(), worker_traits>;\n\n using my_queue = queues::mpmc_moodycamel<work_t>;\n\npublic:\n\timpl()\n#if BOOST_SWEATER_MAX_HARDWARE_CONCURRENCY\n : pool_( BOOST_SWEATER_MAX_HARDWARE_CONCURRENCY - 1 )\n#endif\n\t{\n #if BOOST_SWEATER_MAX_HARDWARE_CONCURRENCY\n BOOST_ASSUME( hardware_concurrency <= BOOST_SWEATER_MAX_HARDWARE_CONCURRENCY );\n #else\n auto const number_of_worker_threads( hardware_concurrency - 1 );\n auto p_workers( std::make_unique<std::thread[]>( number_of_worker_threads ) );\n pool_ = make_iterator_range_n( p_workers.get(), number_of_worker_threads );\n #endif \/\/ !BOOST_SWEATER_MAX_HARDWARE_CONCURRENCY\n\t\tfor ( auto & worker : pool_ )\n\t\t{\n\t\t\tauto const worker_loop\n\t\t\t(\n\t\t\t\t[this]() noexcept\n\t\t\t\t{\n auto token( queue_.consumer_token() );\n\n work_t work;\n\n for ( ; ; )\n {\n for ( auto try_count( 0 ); try_count < spin_count; ++try_count )\n {\n if ( BOOST_LIKELY( queue_.dequeue( work, token ) ) )\n {\n work();\n if ( spin_count > 1 ) \/\/ restart the spin-wait\n try_count = 0;\n }\n }\n\n if ( BOOST_UNLIKELY( brexit_.load( std::memory_order_relaxed ) ) )\n\t\t\t\t\t\t\treturn;\n\n {\n std::unique_lock<std::mutex> lock( mutex_ );\n \/\/\/ \\note No need for a another loop here as a\n \/\/\/ spurious-wakeup would be handled by the check in\n \/\/\/ the loop above.\n \/\/\/ (08.11.2016.) (Domagoj Saric)\n if ( !BOOST_LIKELY( queue_.dequeue( work, token ) ) )\n {\n work.clear();\n work_event_.wait( lock );\n }\n }\n if ( BOOST_LIKELY( static_cast<bool>( work ) ) )\n work();\n }\n\t\t\t\t}\n\t\t\t); \/\/ worker_loop\n worker = std::thread( worker_loop );\n\t\t}\n #if !BOOST_SWEATER_MAX_HARDWARE_CONCURRENCY\n p_workers.release();\n #endif \/\/ !BOOST_SWEATER_MAX_HARDWARE_CONCURRENCY\n\t}\n\n\t~impl() noexcept\n\t{\n\t\tbrexit_.store( true, std::memory_order_relaxed );\n work_event_.notify_all();\n\t\tfor ( auto & worker : pool_ )\n\t\t\tworker.join();\n #if !BOOST_SWEATER_MAX_HARDWARE_CONCURRENCY\n delete[] pool_.begin();\n #endif \/\/ BOOST_SWEATER_MAX_HARDWARE_CONCURRENCY\n\t}\n\n\tauto number_of_workers() const\n {\n auto const result( static_cast<std::uint16_t>( pool_.size() + 1 ) );\n #if BOOST_SWEATER_MAX_HARDWARE_CONCURRENCY\n BOOST_ASSUME( result <= BOOST_SWEATER_MAX_HARDWARE_CONCURRENCY );\n #endif\n return result;\n }\n\n \/\/\/ For GCD dispatch_apply\/OMP-like parallel loops.\n \/\/\/ \\details Guarantees that <VAR>work<\/VAR> will not be called more than\n \/\/\/ <VAR>iterations<\/VAR> times (even if number_of_workers() > iterations).\n\ttemplate <typename F>\n\tbool spread_the_sweat( std::uint16_t const iterations, F && __restrict work ) noexcept\n\t{\n\t\tstatic_assert( noexcept( work( iterations, iterations ) ), \"F must be noexcept\" );\n\n if ( BOOST_UNLIKELY( iterations == 0 ) )\n return true;\n\n auto const number_of_workers ( this->number_of_workers() );\n\t\tauto const iterations_per_worker ( iterations \/ number_of_workers );\n auto const leave_one_for_the_calling_thread( iterations_per_worker == 0 ); \/\/ If iterations < workers prefer using the caller thread instead of waking up a worker thread...\n\t\tauto const threads_with_extra_iteration ( iterations % number_of_workers - leave_one_for_the_calling_thread );\n BOOST_ASSERT( !leave_one_for_the_calling_thread || iterations < number_of_workers );\n\n auto const number_of_work_parts( std::min<std::uint16_t>( number_of_workers, iterations ) );\n std::uint16_t const number_of_dispatched_work_parts( number_of_work_parts - 1 );\n\n batch_semaphore semaphore( number_of_dispatched_work_parts );\n\n# if BOOST_SWEATER_MAX_HARDWARE_CONCURRENCY\n BOOST_ASSUME( number_of_dispatched_work_parts < BOOST_SWEATER_MAX_HARDWARE_CONCURRENCY );\n# else\n BOOST_ASSUME( number_of_dispatched_work_parts < 512 );\n# endif\n \/\/\/ \\note MSVC does not support VLAs but has an alloca that returns\n \/\/\/ (16 byte) aligned memory. Clang's alloca is unaligned and it does\n \/\/\/ not support VLAs of non-POD types.\n \/\/\/ (21.01.2017.) (Domagoj Saric)\n# ifdef BOOST_MSVC\n auto const dispatched_work_parts( static_cast<work_t *>( alloca( ( number_of_dispatched_work_parts ) * sizeof( work_t ) ) ) );\n# else\n alignas( work_t ) char dispatched_work_parts_storage[ number_of_dispatched_work_parts * sizeof( work_t ) ];\n auto const dispatched_work_parts( reinterpret_cast<work_t *>( dispatched_work_parts_storage ) );\n# endif \/\/ _MSC_VER\n\n std::uint16_t iteration( 0 );\n if ( BOOST_LIKELY( iterations > 1 ) )\n {\n for ( std::uint8_t work_part( 0 ); work_part < number_of_dispatched_work_parts; ++work_part )\n {\n auto const start_iteration( iteration );\n auto const extra_iteration( work_part < threads_with_extra_iteration );\n auto const end_iteration ( start_iteration + iterations_per_worker + extra_iteration );\n new ( &dispatched_work_parts[ work_part ] ) work_t\n (\n [&work, &semaphore, start_iteration = iteration, end_iteration]() noexcept\n {\n work( start_iteration, end_iteration );\n semaphore.release();\n }\n );\n iteration = end_iteration;\n }\n\n auto const enqueue_succeeded( queue_.enqueue_bulk( std::make_move_iterator( dispatched_work_parts ), number_of_dispatched_work_parts ) );\n for ( std::uint8_t work_part( 0 ); work_part < number_of_dispatched_work_parts; ++work_part )\n dispatched_work_parts[ work_part ].~work_t();\n if ( !BOOST_LIKELY( enqueue_succeeded ) )\n return false;\n std::unique_lock<std::mutex> lock( mutex_ );\n work_event_.notify_all();\n }\n\n\t\tauto const caller_thread_start_iteration( iteration );\n\t\tBOOST_ASSERT( caller_thread_start_iteration < iterations );\n\t\twork( caller_thread_start_iteration, iterations );\n\n if ( BOOST_LIKELY( iterations > 1 ) )\n {\n semaphore.wait();\n }\n\n return true;\n\t}\n\n\ttemplate <typename F>\n\tbool fire_and_forget( F && work )\n\t{\n struct self_destructed_work\n {\n self_destructed_work( F && work ) noexcept( std::is_nothrow_move_constructible<F>::value ) { new ( storage ) F( std::move( work ) ); }\n self_destructed_work( F const & work ) noexcept( std::is_nothrow_copy_constructible<F>::value ) { new ( storage ) F( work ); }\n void operator()() noexcept\n {\n auto & work( reinterpret_cast<F &>( storage ) );\n work();\n work.~F();\n }\n alignas( work ) char storage[ sizeof( work ) ];\n };\n return queue_.enqueue( self_destructed_work( std::forward<F>( work ) ) );\n\t}\n\n template <typename F>\n auto dispatch( F && work )\n {\n \/\/ http:\/\/scottmeyers.blogspot.hr\/2013\/03\/stdfutures-from-stdasync-arent-special.html\n using result_t = typename std::result_of<F()>::type;\n std::promise<result_t> promise;\n std::future<result_t> future( promise.get_future() );\n if\n (\n fire_and_forget\n (\n [promise = std::move( promise ), work = std::forward<F>( work )]\n () mutable { promise.set_value( work() ); }\n )\n )\n return future;\n BOOST_THROW_EXCEPTION( std::bad_alloc() );\n }\n\nprivate:\n std::atomic<bool> brexit_ = ATOMIC_FLAG_INIT;\n\t std::mutex mutex_;\n mutable std::condition_variable work_event_;\n\n#if BOOST_SWEATER_MAX_HARDWARE_CONCURRENCY\n\tusing pool_threads_t = container::static_vector<std::thread, BOOST_SWEATER_MAX_HARDWARE_CONCURRENCY - 1>; \/\/ also sweat on the calling thread\n#else\n using pool_threads_t = iterator_range<std::thread *>;\n#endif\n\tpool_threads_t pool_;\n\n \/\/\/ \\todo Further queue refinements.\n \/\/\/ https:\/\/en.wikipedia.org\/wiki\/Work_stealing\n \/\/\/ http:\/\/www.drdobbs.com\/parallel\/writing-lock-free-code-a-corrected-queue\/210604448\n \/\/\/ https:\/\/github.com\/cameron314\/readerwriterqueue\n \/\/\/ http:\/\/moodycamel.com\/blog\/2013\/a-fast-lock-free-queue-for-c++\n \/\/\/ http:\/\/stackoverflow.com\/questions\/1164023\/is-there-a-production-ready-lock-free-queue-or-hash-implementation-in-c#14936831\n \/\/\/ https:\/\/github.com\/facebook\/folly\/blob\/master\/folly\/docs\/ProducerConsumerQueue.md\n \/\/\/ https:\/\/github.com\/facebook\/folly\/blob\/master\/folly\/MPMCQueue.h\n \/\/\/ http:\/\/landenlabs.com\/code\/ring\/ring.html\n \/\/\/ https:\/\/github.com\/Qarterd\/Honeycomb\/blob\/master\/src\/common\/Honey\/Thread\/Pool.cpp\n \/\/\/ (12.10.2016.) (Domagoj Saric)\n my_queue queue_;\n}; \/\/ class impl\n\n\/\/------------------------------------------------------------------------------\n} \/\/ namespace sweater\n\/\/------------------------------------------------------------------------------\n} \/\/ namespace boost\n\/\/------------------------------------------------------------------------------\n#endif \/\/ generic_hpp<commit_msg>Fixed generic fire_and_forget() to wake a worker thread. Minor optimizations.<commit_after>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\n\/\/\/ \\file generic.hpp\n\/\/\/ -----------------\n\/\/\/\n\/\/\/ (c) Copyright Domagoj Saric 2016.\n\/\/\/\n\/\/\/ Use, modification and distribution are subject to the\n\/\/\/ Boost Software License, Version 1.0. (See accompanying file\n\/\/\/ LICENSE_1_0.txt or copy at http:\/\/www.boost.org\/LICENSE_1_0.txt)\n\/\/\/\n\/\/\/ See http:\/\/www.boost.org for most recent version.\n\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/------------------------------------------------------------------------------\n#ifndef generic_hpp__99FE2034_248F_4C7D_8CD2_EB2BB8247377\n#define generic_hpp__99FE2034_248F_4C7D_8CD2_EB2BB8247377\n#pragma once\n\/\/------------------------------------------------------------------------------\n#include <boost\/sweater\/queues\/mpmc_moodycamel.hpp>\n\n#include <boost\/config_ex.hpp>\n#include <boost\/container\/small_vector.hpp>\n#include <boost\/container\/static_vector.hpp>\n#include <boost\/functionoid\/functionoid.hpp>\n#include <boost\/range\/algorithm\/count_if.hpp>\n#include <boost\/range\/iterator_range_core.hpp>\n\n#include <atomic>\n#include <cstdint>\n#include <exception>\n#include <future>\n#include <iterator>\n#ifdef _MSC_VER\n#include <malloc.h>\n#else\n#include <alloca.h>\n#endif \/\/ _MSC_VER\n#include <memory>\n#include <mutex>\n#include <thread>\n\/\/------------------------------------------------------------------------------\nnamespace boost\n{\n\/\/------------------------------------------------------------------------------\nnamespace sweater\n{\n\/\/------------------------------------------------------------------------------\n\n#ifndef BOOST_SWEATER_MAX_HARDWARE_CONCURRENCY\n#\tdefine BOOST_SWEATER_MAX_HARDWARE_CONCURRENCY 0\n#endif \/\/ BOOST_SWEATER_MAX_HARDWARE_CONCURRENCY\n\nnamespace queues { template <typename Work> class mpmc_moodycamel; }\n\nBOOST_OVERRIDABLE_SYMBOL\nauto const hardware_concurrency( static_cast<std::uint8_t>( std::thread::hardware_concurrency() ) );\n\nclass impl\n{\nprivate:\n#ifdef __ANROID__\n \/\/ https:\/\/petewarden.com\/2015\/10\/11\/one-weird-trick-for-faster-android-multithreading\n static auto constexpr spin_count = 30 * 1000 * 1000;\n#else\n static auto constexpr spin_count = 1;\n#endif \/\/ __ANROID__\n\n struct worker_traits : functionoid::std_traits\n {\n static constexpr auto copyable = functionoid::support_level::na ;\n static constexpr auto moveable = functionoid::support_level::nofail ;\n static constexpr auto destructor = functionoid::support_level::trivial;\n static constexpr auto is_noexcept = true;\n static constexpr auto rtti = false;\n\n using empty_handler = functionoid::assert_on_empty;\n }; \/\/ struct worker_traits\n\n using worker_counter = std::atomic<std::uint16_t>;\n\n class batch_semaphore\n {\n public:\n batch_semaphore( std::uint16_t const initial_value ) : counter( initial_value ) {}\n\n void release() noexcept\n {\n std::unique_lock<std::mutex> lock( mutex );\n if ( counter.fetch_sub( 1, std::memory_order_acquire ) == 1 )\n event.notify_one();\n }\n\n BOOST_NOINLINE\n void wait() noexcept\n {\n for ( auto try_count( 0 ); try_count < spin_count; ++try_count )\n {\n bool const all_workers_done( counter.load( std::memory_order_relaxed ) == 0 );\n if ( BOOST_LIKELY( all_workers_done ) )\n return;\n }\n std::unique_lock<std::mutex> lock( mutex );\n while ( BOOST_UNLIKELY( counter.load( std::memory_order_relaxed ) != 0 ) )\n event.wait( lock );\n }\n\n private:\n worker_counter counter;\n mutable std::condition_variable event;\n std::mutex mutex;\n }; \/\/ struct batch_semaphore\n\n using work_t = functionoid::callable<void(), worker_traits>;\n\n using my_queue = queues::mpmc_moodycamel<work_t>;\n\npublic:\n\timpl()\n#if BOOST_SWEATER_MAX_HARDWARE_CONCURRENCY\n : pool_( BOOST_SWEATER_MAX_HARDWARE_CONCURRENCY - 1 )\n#endif\n\t{\n #if BOOST_SWEATER_MAX_HARDWARE_CONCURRENCY\n BOOST_ASSUME( hardware_concurrency <= BOOST_SWEATER_MAX_HARDWARE_CONCURRENCY );\n #else\n auto const number_of_worker_threads( hardware_concurrency - 1 );\n auto p_workers( std::make_unique<std::thread[]>( number_of_worker_threads ) );\n pool_ = make_iterator_range_n( p_workers.get(), number_of_worker_threads );\n #endif \/\/ !BOOST_SWEATER_MAX_HARDWARE_CONCURRENCY\n\t\tfor ( auto & worker : pool_ )\n\t\t{\n\t\t\tauto const worker_loop\n\t\t\t(\n\t\t\t\t[this]() noexcept\n\t\t\t\t{\n auto token( queue_.consumer_token() );\n\n work_t work;\n\n for ( ; ; )\n {\n for ( auto try_count( 0 ); try_count < spin_count; ++try_count )\n {\n if ( BOOST_LIKELY( queue_.dequeue( work, token ) ) )\n {\n work();\n if ( spin_count > 1 ) \/\/ restart the spin-wait\n try_count = 0;\n }\n }\n\n if ( BOOST_UNLIKELY( brexit_.load( std::memory_order_relaxed ) ) )\n\t\t\t\t\t\t\treturn;\n\n {\n std::unique_lock<std::mutex> lock( mutex_ );\n \/\/\/ \\note No need for a another loop here as a\n \/\/\/ spurious-wakeup would be handled by the check in\n \/\/\/ the loop above.\n \/\/\/ (08.11.2016.) (Domagoj Saric)\n if ( !BOOST_LIKELY( queue_.dequeue( work, token ) ) )\n {\n work.clear();\n work_event_.wait( lock );\n }\n }\n if ( BOOST_LIKELY( static_cast<bool>( work ) ) )\n work();\n }\n\t\t\t\t}\n\t\t\t); \/\/ worker_loop\n worker = std::thread( worker_loop );\n\t\t}\n #if !BOOST_SWEATER_MAX_HARDWARE_CONCURRENCY\n p_workers.release();\n #endif \/\/ !BOOST_SWEATER_MAX_HARDWARE_CONCURRENCY\n\t}\n\n\t~impl() noexcept\n\t{\n\t\tbrexit_.store( true, std::memory_order_relaxed );\n work_event_.notify_all();\n\t\tfor ( auto & worker : pool_ )\n\t\t\tworker.join();\n #if !BOOST_SWEATER_MAX_HARDWARE_CONCURRENCY\n delete[] pool_.begin();\n #endif \/\/ BOOST_SWEATER_MAX_HARDWARE_CONCURRENCY\n\t}\n\n\tauto number_of_workers() const\n {\n auto const result( static_cast<std::uint16_t>( pool_.size() + 1 ) );\n #if BOOST_SWEATER_MAX_HARDWARE_CONCURRENCY\n BOOST_ASSUME( result <= BOOST_SWEATER_MAX_HARDWARE_CONCURRENCY );\n #endif\n return result;\n }\n\n \/\/\/ For GCD dispatch_apply\/OMP-like parallel loops.\n \/\/\/ \\details Guarantees that <VAR>work<\/VAR> will not be called more than\n \/\/\/ <VAR>iterations<\/VAR> times (even if number_of_workers() > iterations).\n\ttemplate <typename F>\n\tbool spread_the_sweat( std::uint16_t const iterations, F && __restrict work ) noexcept\n\t{\n\t\tstatic_assert( noexcept( work( iterations, iterations ) ), \"F must be noexcept\" );\n\n if ( BOOST_UNLIKELY( iterations == 0 ) )\n return true;\n\n auto const number_of_workers ( this->number_of_workers() );\n\t\tauto const iterations_per_worker ( iterations \/ number_of_workers );\n auto const leave_one_for_the_calling_thread( iterations_per_worker == 0 ); \/\/ If iterations < workers prefer using the caller thread instead of waking up a worker thread...\n\t\tauto const threads_with_extra_iteration ( iterations % number_of_workers - leave_one_for_the_calling_thread );\n BOOST_ASSERT( !leave_one_for_the_calling_thread || iterations < number_of_workers );\n\n auto const number_of_work_parts( std::min<std::uint16_t>( number_of_workers, iterations ) );\n std::uint16_t const number_of_dispatched_work_parts( number_of_work_parts - 1 );\n\n batch_semaphore semaphore( number_of_dispatched_work_parts );\n\n# if BOOST_SWEATER_MAX_HARDWARE_CONCURRENCY\n BOOST_ASSUME( number_of_dispatched_work_parts < BOOST_SWEATER_MAX_HARDWARE_CONCURRENCY );\n# else\n BOOST_ASSUME( number_of_dispatched_work_parts < 512 );\n# endif\n \/\/\/ \\note MSVC does not support VLAs but has an alloca that returns\n \/\/\/ (16 byte) aligned memory. Clang's alloca is unaligned and it does\n \/\/\/ not support VLAs of non-POD types.\n \/\/\/ (21.01.2017.) (Domagoj Saric)\n# ifdef BOOST_MSVC\n auto const dispatched_work_parts( static_cast<work_t *>( alloca( ( number_of_dispatched_work_parts ) * sizeof( work_t ) ) ) );\n# else\n alignas( work_t ) char dispatched_work_parts_storage[ number_of_dispatched_work_parts * sizeof( work_t ) ];\n auto const dispatched_work_parts( reinterpret_cast<work_t *>( dispatched_work_parts_storage ) );\n# endif \/\/ _MSC_VER\n\n std::uint16_t iteration( 0 );\n if ( BOOST_LIKELY( iterations > 1 ) )\n {\n for ( std::uint8_t work_part( 0 ); work_part < number_of_dispatched_work_parts; ++work_part )\n {\n auto const start_iteration( iteration );\n auto const extra_iteration( work_part < threads_with_extra_iteration );\n auto const end_iteration ( start_iteration + iterations_per_worker + extra_iteration );\n new ( &dispatched_work_parts[ work_part ] ) work_t\n (\n [&work, &semaphore, start_iteration = iteration, end_iteration]() noexcept\n {\n work( start_iteration, end_iteration );\n semaphore.release();\n }\n );\n iteration = end_iteration;\n }\n\n auto const enqueue_succeeded( queue_.enqueue_bulk( std::make_move_iterator( dispatched_work_parts ), number_of_dispatched_work_parts ) );\n for ( std::uint8_t work_part( 0 ); work_part < number_of_dispatched_work_parts; ++work_part )\n dispatched_work_parts[ work_part ].~work_t();\n \/\/\/ No need for a branch here as the worker thread has to handle\n \/\/\/ spurious wakeups anyway.\n std::unique_lock<std::mutex> lock( mutex_ );\n work_event_.notify_all();\n return BOOST_LIKELY( enqueue_succeeded );\n }\n\n\t\tauto const caller_thread_start_iteration( iteration );\n\t\tBOOST_ASSERT( caller_thread_start_iteration < iterations );\n\t\twork( caller_thread_start_iteration, iterations );\n\n if ( BOOST_LIKELY( iterations > 1 ) )\n {\n semaphore.wait();\n }\n\n return true;\n\t}\n\n\ttemplate <typename F>\n\tbool fire_and_forget( F && work )\n\t{\n struct self_destructed_work\n {\n self_destructed_work( F && work ) noexcept( std::is_nothrow_move_constructible<F>::value ) { new ( storage ) F( std::move( work ) ); }\n self_destructed_work( F const & work ) noexcept( std::is_nothrow_copy_constructible<F>::value ) { new ( storage ) F( work ); }\n void operator()() noexcept\n {\n auto & work( reinterpret_cast<F &>( storage ) );\n work();\n work.~F();\n }\n alignas( work ) char storage[ sizeof( work ) ];\n };\n auto const enqueue_succeeded( queue_.enqueue( self_destructed_work( std::forward<F>( work ) ) ) );\n std::unique_lock<std::mutex> lock( mutex_ );\n work_event_.notify_one();\n return BOOST_LIKELY( enqueue_succeeded );\n\t}\n\n template <typename F>\n auto dispatch( F && work )\n {\n \/\/ http:\/\/scottmeyers.blogspot.hr\/2013\/03\/stdfutures-from-stdasync-arent-special.html\n using result_t = typename std::result_of<F()>::type;\n std::promise<result_t> promise;\n std::future<result_t> future( promise.get_future() );\n auto const dispatch_succeeded\n (\n fire_and_forget\n (\n [promise = std::move( promise ), work = std::forward<F>( work )]\n () mutable { promise.set_value( work() ); }\n )\n );\n if ( BOOST_UNLIKELY( !dispatch_succeeded ) )\n future.set_exception( std::make_exception_ptr( std::bad_alloc() ) );\n return future;\n }\n\nprivate:\n std::atomic<bool> brexit_ = ATOMIC_FLAG_INIT;\n\t std::mutex mutex_;\n mutable std::condition_variable work_event_;\n\n#if BOOST_SWEATER_MAX_HARDWARE_CONCURRENCY\n\tusing pool_threads_t = container::static_vector<std::thread, BOOST_SWEATER_MAX_HARDWARE_CONCURRENCY - 1>; \/\/ also sweat on the calling thread\n#else\n using pool_threads_t = iterator_range<std::thread *>;\n#endif\n\tpool_threads_t pool_;\n\n \/\/\/ \\todo Further queue refinements.\n \/\/\/ https:\/\/en.wikipedia.org\/wiki\/Work_stealing\n \/\/\/ http:\/\/www.drdobbs.com\/parallel\/writing-lock-free-code-a-corrected-queue\/210604448\n \/\/\/ https:\/\/github.com\/cameron314\/readerwriterqueue\n \/\/\/ http:\/\/moodycamel.com\/blog\/2013\/a-fast-lock-free-queue-for-c++\n \/\/\/ http:\/\/stackoverflow.com\/questions\/1164023\/is-there-a-production-ready-lock-free-queue-or-hash-implementation-in-c#14936831\n \/\/\/ https:\/\/github.com\/facebook\/folly\/blob\/master\/folly\/docs\/ProducerConsumerQueue.md\n \/\/\/ https:\/\/github.com\/facebook\/folly\/blob\/master\/folly\/MPMCQueue.h\n \/\/\/ http:\/\/landenlabs.com\/code\/ring\/ring.html\n \/\/\/ https:\/\/github.com\/Qarterd\/Honeycomb\/blob\/master\/src\/common\/Honey\/Thread\/Pool.cpp\n \/\/\/ (12.10.2016.) (Domagoj Saric)\n my_queue queue_;\n}; \/\/ class impl\n\n\/\/------------------------------------------------------------------------------\n} \/\/ namespace sweater\n\/\/------------------------------------------------------------------------------\n} \/\/ namespace boost\n\/\/------------------------------------------------------------------------------\n#endif \/\/ generic_hpp<|endoftext|>"} {"text":"<commit_before>\/*\n * qiesmap.cpp\n *\n * Copyright (c) 2016 Tobias Wood.\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\n *\/\n\n#include <getopt.h>\n#include <iostream>\n#include <Eigen\/Dense>\n#include <Eigen\/Eigenvalues>\n\n#include \"QI\/Util.h\"\n#include \"Filters\/ApplyAlgorithmFilter.h\"\n\nusing namespace std;\nusing namespace Eigen;\n\nclass ESAlgo : public Algorithm<complex<double>> {\nprotected:\n size_t m_size = 0;\npublic:\n size_t numInputs() const override { return 1; }\n size_t numConsts() const override { return 1; }\n size_t numOutputs() const override { return 6; }\n const vector<string> & names() const {\n static vector<string> _names = {\"M\", \"T1\", \"T2\", \"th\", \"a\", \"b\"};\n return _names;\n }\n size_t dataSize() const override { return m_size; }\n void setSize(const size_t s) { m_size = s; }\n virtual TArray defaultConsts() override {\n \/\/ B1\n TArray def = TArray::Ones(1);\n return def;\n }\n \n ArrayXd solveEig(const MatrixXd &A, const MatrixXd &B) const {\n RealQZ<MatrixXd> qz(A, B);\n VectorXd v = ArrayXd::Zero(A.cols());\n const MatrixXd &mS = qz.matrixS();\n const MatrixXd &mT = qz.matrixT();\n const MatrixXd &mZT = qz.matrixZ().transpose();\n int sInd = 0;\n double sVal = numeric_limits<double>::infinity();\n for (int i = 0; i < 6; i++) {\n const double a = mS.coeffRef(i,i);\n const double b = mT.coeffRef(i,i);\n const double l = fabs(a \/ b);\n if (l < sVal) {\n sVal = l;\n sInd = i;\n }\n }\n \n v(sInd) = 1.0;\n const double a = qz.matrixS().coeffRef(sInd,sInd);\n const double b = qz.matrixT().coeffRef(sInd,sInd);\n for (int j = sInd-1; j >= 0; j--) {\n const int st = j+1;\n const int sz = sInd-j; \n v.coeffRef(j) = -v.segment(st,sz).transpose().cwiseProduct(b*mS.block(j,st,1,sz) - a*mT.block(j,st,1,sz)).sum() \/ (b*mS.coeffRef(j,j) - a*mT.coeffRef(j,j));\n }\n v = (mZT * v).normalized();\n return v;\n }\n \n MatrixXd buildS(const ArrayXd &x, const ArrayXd &y) const {\n Matrix<double, Dynamic, 6> D(x.rows(), 6);\n D.col(0) = x*x;\n D.col(1) = x*y;\n D.col(2) = y*y;\n D.col(3) = x;\n D.col(4) = y;\n D.col(5).setConstant(1);\n return D.transpose() * D;\n }\n \n MatrixXd fitzC() const {\n typedef Matrix<double, 6, 6> Matrix6d;\n Matrix6d C = Matrix6d::Zero();\n \/\/ Fitzgibbon et al\n C(0,2) = -2; C(1,1) = 1; C(2,0) = -2;\n return C;\n }\n \n MatrixXd hyperC(const ArrayXd &x, const ArrayXd &y) const {\n typedef Matrix<double, 6, 6> Matrix6d;\n Matrix6d C = Matrix6d::Zero();\n \/\/ Fitzgibbon et al\n \/\/C(0,2) = -2; C(1,1) = 1; C(2,0) = -2;\n \n \/\/ Hyper Ellipse\n const double N = x.cols();\n const double xc = x.sum() \/ N;\n const double yc = y.sum() \/ N;\n const double sx = x.square().sum() \/ N;\n const double sy = y.square().sum() \/ N;\n const double xy = (x * y).sum() \/ N; \n \n C << 6*sx, 6*xy, sx+sy, 6*xc, 2*yc, 1,\n 6*xy, 4*(sx+sy), 6*xy, 4*yc, 4*xc, 0,\n sx + sy, 6*xy, 6*sy, 2*xc, 6*yc, 1,\n 6*xc, 4*yc, 2*xc, 4, 0, 0,\n 2*yc, 4*xc, 6*yc, 0, 4, 0,\n 1, 0, 1, 0, 0, 0;\n \n return C;\n }\n \n void apply(const TInput &data, const TArray &inputs, TArray &outputs, TArray &resids, TIterations &its) const override\n {\n typedef Matrix<double, 6, 6> Matrix6d;\n typedef Matrix<double, 6, 1> Vector6d;\n const double B1 = inputs[0];\n const double scale = data.abs().maxCoeff();\n ArrayXd x = data.real() \/ scale;\n ArrayXd y = data.imag() \/ scale;\n \n MatrixXd S = buildS(x, y);\n Matrix6d C = hyperC(x, y);\n ArrayXd Z = solveEig(S, C);\n const double za = Z[0];\n const double zb = Z[1]\/2;\n const double zc = Z[2];\n const double zd = Z[3]\/2;\n const double zf = Z[4]\/2;\n const double zg = Z[5];\n const double dsc=(zb*zb-za*zc);\n const double xc = (zc*zd-zb*zf)\/dsc;\n const double yc = (za*zf-zb*zd)\/dsc;\n const double th = atan2(yc,xc);\n double A = sqrt((2*(za*(zf*zf)+zc*(zd*zd)+zg*(zb*zb)-2*zb*zd*zf-za*zc*zg))\/(dsc*(sqrt((za-zc)*(za-zc) + 4*zb*zb)-(za+zc))));\n double B = sqrt((2*(za*(zf*zf)+zc*(zd*zd)+zg*(zb*zb)-2*zb*zd*zf-za*zc*zg))\/(dsc*(-sqrt((za-zc)*(za-zc) + 4*zb*zb)-(za+zc))));\n if (A > B) {\n std::swap(A, B);\n }\n \/\/cout << \"Z \" << Z.transpose() << endl;\n \/\/cout << \"dsc \" << dsc << \" xc \" << xc << \" yc \" << yc << \" A \" << A << \" B \" << B << endl;\n const double c = sqrt(xc*xc+yc*yc);\n const double b = (-c*A + sqrt(c*c*A*A - (c*c + B*B)*(A*A - B*B)))\/(c*c + B*B);\n const double a = B \/ (b*B + c*sqrt(1-b*b));\n const double M = scale*c*(1-b*b)\/(1-a*b);\n const double TR = 0.0065;\n const double FA = B1 * (25*M_PI\/180.);\n const double T1 = -TR \/ log((a*(1+cos(FA)-a*b*cos(FA))-b)\/(a*(1+cos(FA)-a*b)-b*cos(FA)));\n const double T2 = -TR \/ log(a);\n \n outputs[0] = M;\n outputs[1] = T1;\n outputs[2] = T2;\n outputs[3] = th;\n outputs[4] = a;\n outputs[5] = b;\n }\n};\n\n\/\/******************************************************************************\n\/\/ Arguments \/ Usage\n\/\/******************************************************************************\nconst string usage {\n\"Usage is: qiesmap [options] input \\n\\\n\\n\\\nA utility for calculating T1,T2,PD and f0 maps from SSFP data.\\n\\\nInput must be a single complex image with at least 6 phase increments.\\n\\\n\\n\\\nOptions:\\n\\\n --help, -h : Print this message.\\n\\\n --verbose, -v : Print more information.\\n\\\n --out, -o path : Specify an output prefix.\\n\\\n --mask, -m file : Mask input with specified file.\\n\\\n --B1, -b file : B1 Map file (ratio)\\n\\\n --threads, -T N : Use N threads (default=hardware limit).\\n\"\n};\n\nbool verbose = false;\nstatic size_t num_threads = 4;\nstatic string outPrefix;\nconst struct option long_opts[] = {\n {\"help\", no_argument, 0, 'h'},\n {\"verbose\", no_argument, 0, 'v'},\n {\"out\", required_argument, 0, 'o'},\n {\"mask\", required_argument, 0, 'm'},\n {\"B1\", required_argument, 0, 'b'},\n {\"threads\", required_argument, 0, 'T'},\n {0, 0, 0, 0}\n};\nconst char *short_opts = \"hvo:m:b:T:\";\n\n\/\/******************************************************************************\n\/\/ Main\n\/\/******************************************************************************\nint main(int argc, char **argv) {\n Eigen::initParallel();\n QI::VolumeF::Pointer mask = ITK_NULLPTR;\n QI::VolumeF::Pointer B1 = ITK_NULLPTR;\n\n shared_ptr<ESAlgo> algo = make_shared<ESAlgo>();\n int indexptr = 0, c;\n while ((c = getopt_long(argc, argv, short_opts, long_opts, &indexptr)) != -1) {\n switch (c) {\n case 'v': verbose = true; break;\n case 'm':\n if (verbose) cout << \"Opening mask file \" << optarg << endl;\n mask = QI::ReadImage(optarg);\n break;\n case 'o':\n outPrefix = optarg;\n if (verbose) cout << \"Output prefix will be: \" << outPrefix << endl;\n break;\n case 'b':\n if (verbose) cout << \"Opening B1 file: \" << optarg << endl;\n B1 = QI::ReadImage(optarg);\n break;\n case 'T':\n num_threads = stoi(optarg);\n if (num_threads == 0)\n num_threads = std::thread::hardware_concurrency();\n break;\n case 'h':\n cout << QI::GetVersion() << endl << usage << endl;\n return EXIT_SUCCESS;\n case '?': \/\/ getopt will print an error message\n return EXIT_FAILURE;\n default:\n cout << \"Unhandled option \" << string(1, c) << endl;\n return EXIT_FAILURE;\n }\n }\n if ((argc - optind) != 1) {\n cout << \"Incorrect number of arguments.\" << endl << usage << endl;\n return EXIT_FAILURE;\n }\n\n string inputFilename = argv[optind++];\n if (verbose) cout << \"Opening file: \" << inputFilename << endl;\n auto data = QI::ReadVectorImage<complex<float>>(inputFilename);\n auto apply = itk::ApplyAlgorithmFilter<ESAlgo, complex<float>>::New();\n algo->setSize(data->GetNumberOfComponentsPerPixel());\n apply->SetAlgorithm(algo);\n apply->SetPoolsize(num_threads);\n apply->SetInput(0, data);\n if (mask)\n apply->SetMask(mask);\n if (B1)\n apply->SetConst(0, B1);\n if (verbose) {\n cout << \"Processing\" << endl;\n auto monitor = QI::GenericMonitor::New();\n apply->AddObserver(itk::ProgressEvent(), monitor);\n }\n apply->Update();\n if (verbose) {\n cout << \"Elapsed time was \" << apply->GetTotalTime() << \"s\" << endl;\n cout << \"Mean time per voxel was \" << apply->GetMeanTime() << \"s\" << endl;\n cout << \"Writing results files.\" << endl;\n }\n outPrefix = outPrefix + \"ES_\";\n for (int i = 0; i < algo->numOutputs(); i++) {\n QI::WriteImage(apply->GetOutput(i), outPrefix + algo->names().at(i) + QI::OutExt());\n }\n \n if (verbose) cout << \"Finished.\" << endl;\n return EXIT_SUCCESS;\n}\n<commit_msg>WIP: Added code to read in sequence parameters.<commit_after>\/*\n * qiesmap.cpp\n *\n * Copyright (c) 2016 Tobias Wood.\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\n *\/\n\n#include <getopt.h>\n#include <iostream>\n#include <Eigen\/Dense>\n#include <Eigen\/Eigenvalues>\n\n#include \"QI\/Util.h\"\n#include \"QI\/Sequences\/SteadyStateSequence.cpp\"\n#include \"Filters\/ApplyAlgorithmFilter.h\"\n\nusing namespace std;\nusing namespace Eigen;\n\nclass ESAlgo : public Algorithm<complex<double>> {\nprotected:\n size_t m_size = 0;\n shared_ptr<QI::SSFP_GS> m_sequence = nullptr;\npublic:\n size_t numInputs() const override { return 1; }\n size_t numConsts() const override { return 1; }\n size_t numOutputs() const override { return 6; }\n const vector<string> & names() const {\n static vector<string> _names = {\"M\", \"T1\", \"T2\", \"th\", \"a\", \"b\"};\n return _names;\n }\n size_t dataSize() const override { return m_size; }\n void setSize(const size_t s) { m_size = s; }\n virtual TArray defaultConsts() override {\n \/\/ B1\n TArray def = TArray::Ones(1);\n return def;\n }\n void SetSequence(const shared_ptr<QI::SSFP_GS> &s) { m_sequence = s;}\n \n ArrayXd solveEig(const MatrixXd &A, const MatrixXd &B) const {\n RealQZ<MatrixXd> qz(A, B);\n VectorXd v = ArrayXd::Zero(A.cols());\n const MatrixXd &mS = qz.matrixS();\n const MatrixXd &mT = qz.matrixT();\n const MatrixXd &mZT = qz.matrixZ().transpose();\n int sInd = 0;\n double sVal = numeric_limits<double>::infinity();\n for (int i = 0; i < 6; i++) {\n const double a = mS.coeffRef(i,i);\n const double b = mT.coeffRef(i,i);\n const double l = fabs(a \/ b);\n if (l < sVal) {\n sVal = l;\n sInd = i;\n }\n }\n \n v(sInd) = 1.0;\n const double a = qz.matrixS().coeffRef(sInd,sInd);\n const double b = qz.matrixT().coeffRef(sInd,sInd);\n for (int j = sInd-1; j >= 0; j--) {\n const int st = j+1;\n const int sz = sInd-j; \n v.coeffRef(j) = -v.segment(st,sz).transpose().cwiseProduct(b*mS.block(j,st,1,sz) - a*mT.block(j,st,1,sz)).sum() \/ (b*mS.coeffRef(j,j) - a*mT.coeffRef(j,j));\n }\n v = (mZT * v).normalized();\n return v;\n }\n \n MatrixXd buildS(const ArrayXd &x, const ArrayXd &y) const {\n Matrix<double, Dynamic, 6> D(x.rows(), 6);\n D.col(0) = x*x;\n D.col(1) = x*y;\n D.col(2) = y*y;\n D.col(3) = x;\n D.col(4) = y;\n D.col(5).setConstant(1);\n return D.transpose() * D;\n }\n \n MatrixXd fitzC() const {\n typedef Matrix<double, 6, 6> Matrix6d;\n Matrix6d C = Matrix6d::Zero();\n \/\/ Fitzgibbon et al\n C(0,2) = -2; C(1,1) = 1; C(2,0) = -2;\n return C;\n }\n \n MatrixXd hyperC(const ArrayXd &x, const ArrayXd &y) const {\n typedef Matrix<double, 6, 6> Matrix6d;\n Matrix6d C = Matrix6d::Zero();\n \/\/ Fitzgibbon et al\n \/\/C(0,2) = -2; C(1,1) = 1; C(2,0) = -2;\n \n \/\/ Hyper Ellipse\n const double N = x.cols();\n const double xc = x.sum() \/ N;\n const double yc = y.sum() \/ N;\n const double sx = x.square().sum() \/ N;\n const double sy = y.square().sum() \/ N;\n const double xy = (x * y).sum() \/ N; \n \n C << 6*sx, 6*xy, sx+sy, 6*xc, 2*yc, 1,\n 6*xy, 4*(sx+sy), 6*xy, 4*yc, 4*xc, 0,\n sx + sy, 6*xy, 6*sy, 2*xc, 6*yc, 1,\n 6*xc, 4*yc, 2*xc, 4, 0, 0,\n 2*yc, 4*xc, 6*yc, 0, 4, 0,\n 1, 0, 1, 0, 0, 0;\n \n return C;\n }\n \n void apply(const TInput &data, const TArray &inputs, TArray &outputs, TArray &resids, TIterations &its) const override\n {\n typedef Matrix<double, 6, 6> Matrix6d;\n typedef Matrix<double, 6, 1> Vector6d;\n const double B1 = inputs[0];\n const double scale = data.abs().maxCoeff();\n ArrayXd x = data.real() \/ scale;\n ArrayXd y = data.imag() \/ scale;\n \n MatrixXd S = buildS(x, y);\n Matrix6d C = hyperC(x, y);\n ArrayXd Z = solveEig(S, C);\n const double za = Z[0];\n const double zb = Z[1]\/2;\n const double zc = Z[2];\n const double zd = Z[3]\/2;\n const double zf = Z[4]\/2;\n const double zg = Z[5];\n const double dsc=(zb*zb-za*zc);\n const double xc = (zc*zd-zb*zf)\/dsc;\n const double yc = (za*zf-zb*zd)\/dsc;\n const double th = atan2(yc,xc);\n double A = sqrt((2*(za*(zf*zf)+zc*(zd*zd)+zg*(zb*zb)-2*zb*zd*zf-za*zc*zg))\/(dsc*(sqrt((za-zc)*(za-zc) + 4*zb*zb)-(za+zc))));\n double B = sqrt((2*(za*(zf*zf)+zc*(zd*zd)+zg*(zb*zb)-2*zb*zd*zf-za*zc*zg))\/(dsc*(-sqrt((za-zc)*(za-zc) + 4*zb*zb)-(za+zc))));\n if (A > B) {\n std::swap(A, B);\n }\n \/\/cout << \"Z \" << Z.transpose() << endl;\n \/\/cout << \"dsc \" << dsc << \" xc \" << xc << \" yc \" << yc << \" A \" << A << \" B \" << B << endl;\n const double c = sqrt(xc*xc+yc*yc);\n const double b = (-c*A + sqrt(c*c*A*A - (c*c + B*B)*(A*A - B*B)))\/(c*c + B*B);\n const double a = B \/ (b*B + c*sqrt(1-b*b));\n const double M = scale*c*(1-b*b)\/(1-a*b);\n const double TR = m_sequence->TR();\n const double ca = cos(B1 * m_sequence->flip()[0]);\n const double T1 = -TR \/ (log(a*(1.+ca-a*b*ca)-b) - log(a*(1.+ca-a*b)-b*ca));\n const double T2 = -TR \/ log(a);\n \n outputs[0] = M;\n outputs[1] = T1;\n outputs[2] = T2;\n outputs[3] = th;\n outputs[4] = a;\n outputs[5] = b;\n }\n};\n\n\/\/******************************************************************************\n\/\/ Arguments \/ Usage\n\/\/******************************************************************************\nconst string usage {\n\"Usage is: qiesmap [options] input \\n\\\n\\n\\\nA utility for calculating T1,T2,PD and f0 maps from SSFP data.\\n\\\nInput must be a single complex image with at least 6 phase increments.\\n\\\n\\n\\\nOptions:\\n\\\n --help, -h : Print this message.\\n\\\n --verbose, -v : Print more information.\\n\\\n --out, -o path : Specify an output prefix.\\n\\\n --mask, -m file : Mask input with specified file.\\n\\\n --B1, -b file : B1 Map file (ratio)\\n\\\n --threads, -T N : Use N threads (default=hardware limit).\\n\"\n};\n\nbool verbose = false;\nstatic size_t num_threads = 4;\nstatic string outPrefix;\nconst struct option long_opts[] = {\n {\"help\", no_argument, 0, 'h'},\n {\"verbose\", no_argument, 0, 'v'},\n {\"out\", required_argument, 0, 'o'},\n {\"mask\", required_argument, 0, 'm'},\n {\"B1\", required_argument, 0, 'b'},\n {\"threads\", required_argument, 0, 'T'},\n {0, 0, 0, 0}\n};\nconst char *short_opts = \"hvo:m:b:T:\";\n\n\/\/******************************************************************************\n\/\/ Main\n\/\/******************************************************************************\nint main(int argc, char **argv) {\n Eigen::initParallel();\n QI::VolumeF::Pointer mask = ITK_NULLPTR;\n QI::VolumeF::Pointer B1 = ITK_NULLPTR;\n\n shared_ptr<ESAlgo> algo = make_shared<ESAlgo>();\n int indexptr = 0, c;\n while ((c = getopt_long(argc, argv, short_opts, long_opts, &indexptr)) != -1) {\n switch (c) {\n case 'v': verbose = true; break;\n case 'm':\n if (verbose) cout << \"Opening mask file \" << optarg << endl;\n mask = QI::ReadImage(optarg);\n break;\n case 'o':\n outPrefix = optarg;\n if (verbose) cout << \"Output prefix will be: \" << outPrefix << endl;\n break;\n case 'b':\n if (verbose) cout << \"Opening B1 file: \" << optarg << endl;\n B1 = QI::ReadImage(optarg);\n break;\n case 'T':\n num_threads = stoi(optarg);\n if (num_threads == 0)\n num_threads = std::thread::hardware_concurrency();\n break;\n case 'h':\n cout << QI::GetVersion() << endl << usage << endl;\n return EXIT_SUCCESS;\n case '?': \/\/ getopt will print an error message\n return EXIT_FAILURE;\n default:\n cout << \"Unhandled option \" << string(1, c) << endl;\n return EXIT_FAILURE;\n }\n }\n if ((argc - optind) != 1) {\n cout << \"Incorrect number of arguments.\" << endl << usage << endl;\n return EXIT_FAILURE;\n }\n\n string inputFilename = argv[optind++];\n if (verbose) cout << \"Opening file: \" << inputFilename << endl;\n auto data = QI::ReadVectorImage<complex<float>>(inputFilename);\n shared_ptr<QI::SSFP_GS> seq = make_shared<QI::SSFP_GS>(cin, true);\n auto apply = itk::ApplyAlgorithmFilter<ESAlgo, complex<float>>::New();\n algo->setSize(data->GetNumberOfComponentsPerPixel());\n algo->SetSequence(seq);\n apply->SetAlgorithm(algo);\n apply->SetPoolsize(num_threads);\n apply->SetInput(0, data);\n \n if (mask)\n apply->SetMask(mask);\n if (B1)\n apply->SetConst(0, B1);\n if (verbose) {\n cout << \"Processing\" << endl;\n auto monitor = QI::GenericMonitor::New();\n apply->AddObserver(itk::ProgressEvent(), monitor);\n }\n apply->Update();\n if (verbose) {\n cout << \"Elapsed time was \" << apply->GetTotalTime() << \"s\" << endl;\n cout << \"Mean time per voxel was \" << apply->GetMeanTime() << \"s\" << endl;\n cout << \"Writing results files.\" << endl;\n }\n outPrefix = outPrefix + \"ES_\";\n for (int i = 0; i < algo->numOutputs(); i++) {\n QI::WriteImage(apply->GetOutput(i), outPrefix + algo->names().at(i) + QI::OutExt());\n }\n \n if (verbose) cout << \"Finished.\" << endl;\n return EXIT_SUCCESS;\n}\n<|endoftext|>"} {"text":"<commit_before>\/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- *\/\n\/* libmspub\n * Version: MPL 1.1 \/ GPLv2+ \/ LGPLv2+\n *\n * The contents of this file are subject to the Mozilla Public License Version\n * 1.1 (the \"License\"); you may not use this file except in compliance with\n * the License or as specified alternatively below. You may obtain a copy of\n * the License at http:\/\/www.mozilla.org\/MPL\/\n *\n * Software distributed under the License is distributed on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License\n * for the specific language governing rights and limitations under the\n * License.\n *\n * Major Contributor(s):\n * Copyright (C) 2012-2013 Brennan Vincent <brennanv@email.arizona.edu>\n * Copyright (C) 2011 Fridrich Strba <fridrich.strba@bluewin.ch>\n * Copyright (C) 2011 Eilidh McAdam <tibbylickle@gmail.com>\n *\n *\n * All Rights Reserved.\n *\n * For minor contributions see the git repository.\n *\n * Alternatively, the contents of this file may be used under the terms of\n * either the GNU General Public License Version 2 or later (the \"GPLv2+\"), or\n * the GNU Lesser General Public License Version 2 or later (the \"LGPLv2+\"),\n * in which case the provisions of the GPLv2+ or the LGPLv2+ are applicable\n * instead of those above.\n *\/\n\n#include <unicode\/ucnv.h>\n#include <unicode\/utypes.h>\n\n#include <string.h> \/\/ for memcpy\n#include <math.h>\n#include <zlib.h>\n#include <cstring>\n\n#include \"libmspub_utils.h\"\n\n#ifndef M_PI\n#define M_PI 3.14159265358979323846\n#endif\n\n#define ZLIB_CHUNK 16384\n\nusing std::strcmp;\nconst char *libmspub::windowsCharsetNameByOriginalCharset(const char *name)\n{\n if (strcmp(name, \"Shift_JIS\") == 0)\n {\n return \"windows-932\";\n }\n if (strcmp(name, \"GB18030\") == 0)\n {\n return \"windows-936\";\n }\n if (strcmp(name, \"Big5\") == 0)\n {\n return \"windows-950\";\n }\n if (strcmp(name, \"ISO-8859-1\") == 0)\n {\n return \"windows-1252\";\n }\n if (strcmp(name, \"ISO-8859-2\") == 0)\n {\n return \"windows-1250\";\n }\n if (strcmp(name, \"windows-1251\") == 0)\n {\n return \"windows-1251\";\n }\n if (strcmp(name, \"windows-1256\") == 0)\n {\n return \"windows-1256\";\n }\n return NULL;\n}\n\nconst char *libmspub::mimeByImgType(ImgType type)\n{\n switch (type)\n {\n case PNG:\n return \"image\/png\";\n case JPEG:\n return \"image\/jpeg\";\n case DIB:\n return \"image\/bmp\";\n case PICT:\n return \"image\/pict\";\n case WMF:\n return \"image\/wmf\";\n case EMF:\n return \"image\/emf\";\n case TIFF:\n return \"image\/tiff\";\n default:\n MSPUB_DEBUG_MSG((\"Unknown image type %d passed to mimeByImgType!\\n\", type));\n return 0;\n }\n}\n\nvoid libmspub::rotateCounter(double &x, double &y, double centerX, double centerY, short rotation)\n{\n double vecX = x - centerX;\n double vecY = centerY - y;\n double sinTheta = sin(rotation * M_PI \/ 180.);\n double cosTheta = cos(rotation * M_PI \/ 180.);\n double newVecX = cosTheta * vecX - sinTheta * vecY;\n double newVecY = sinTheta * vecX + cosTheta * vecY;\n x = centerX + newVecX;\n y = centerY - newVecY;\n}\n\ndouble libmspub::doubleModulo(double x, double y)\n{\n if (y <= 0) \/\/ y <= 0 doesn't make sense\n {\n return x;\n }\n while (x < 0)\n {\n x += y;\n }\n while (x >= y)\n {\n x -= y;\n }\n return x;\n}\n\ndouble libmspub::toFixedPoint(int fp)\n{\n unsigned short fractionalPart = ((unsigned short) fp) & 0xFFFF;\n short integralPart = fp >> 16;\n return integralPart + fractionalPart \/ 65536.;\n}\n\ndouble libmspub::readFixedPoint(WPXInputStream *input)\n{\n return toFixedPoint(readS32(input));\n}\n\nvoid libmspub::flipIfNecessary(double &x, double &y, double centerX, double centerY, bool flipVertical, bool flipHorizontal)\n{\n double vecX = x - centerX;\n double vecY = centerY - y;\n if (flipVertical)\n {\n y = centerY + vecY;\n }\n if (flipHorizontal)\n {\n x = centerX - vecX;\n }\n}\n\nunsigned libmspub::correctModulo(int x, unsigned n) \/\/ returns the canonical representation of x in Z\/nZ\n\/\/difference with C++ % operator is that this never returns negative values.\n{\n if (x < 0)\n {\n int result = x % (int)n;\n \/\/sign of result is implementation defined\n if (result < 0)\n {\n return n + result;\n }\n return result;\n }\n return x % n;\n}\n\nWPXBinaryData libmspub::inflateData(WPXBinaryData deflated)\n{\n WPXBinaryData inflated;\n unsigned char out[ZLIB_CHUNK];\n const unsigned char *data = deflated.getDataBuffer();\n z_stream strm;\n int ret;\n strm.zalloc = Z_NULL;\n strm.zfree = Z_NULL;\n strm.opaque = Z_NULL;\n strm.avail_in = 0;\n strm.next_in = Z_NULL;\n if (inflateInit2(&strm,-MAX_WBITS) != Z_OK)\n {\n return WPXBinaryData();\n }\n int have;\n unsigned left = deflated.size();\n do\n {\n strm.avail_in = ZLIB_CHUNK > left ? left : ZLIB_CHUNK;\n strm.next_in = (unsigned char *)data;\n do\n {\n strm.avail_out = ZLIB_CHUNK;\n strm.next_out = out;\n ret = inflate(&strm, Z_NO_FLUSH);\n if (ret == Z_STREAM_ERROR || ret == Z_NEED_DICT || ret == Z_DATA_ERROR || ret == Z_MEM_ERROR)\n {\n inflateEnd(&strm);\n return WPXBinaryData();\n }\n have = ZLIB_CHUNK - strm.avail_out;\n inflated.append(out, have);\n }\n while (strm.avail_out == 0);\n data += ZLIB_CHUNK > left ? left : ZLIB_CHUNK;\n left -= ZLIB_CHUNK > left ? left : ZLIB_CHUNK;\n }\n while (ret != Z_STREAM_END);\n inflateEnd(&strm);\n return inflated;\n}\n\nnamespace\n{\n\nstatic void _appendUCS4(WPXString &text, unsigned ucs4Character)\n{\n unsigned char first;\n int len;\n if (ucs4Character < 0x80)\n {\n first = 0;\n len = 1;\n }\n else if (ucs4Character < 0x800)\n {\n first = 0xc0;\n len = 2;\n }\n else if (ucs4Character < 0x10000)\n {\n first = 0xe0;\n len = 3;\n }\n else if (ucs4Character < 0x200000)\n {\n first = 0xf0;\n len = 4;\n }\n else if (ucs4Character < 0x4000000)\n {\n first = 0xf8;\n len = 5;\n }\n else\n {\n first = 0xfc;\n len = 6;\n }\n\n unsigned char outbuf[6] = { 0, 0, 0, 0, 0, 0 };\n int i;\n for (i = len - 1; i > 0; --i)\n {\n outbuf[i] = (ucs4Character & 0x3f) | 0x80;\n ucs4Character >>= 6;\n }\n outbuf[0] = (ucs4Character & 0xff) | first;\n\n for (i = 0; i < len; i++)\n text.append(outbuf[i]);\n}\n\n} \/\/ anonymous namespace\n\n#define MSPUB_NUM_ELEMENTS(array) sizeof(array)\/sizeof(array[0])\n\nuint8_t libmspub::readU8(WPXInputStream *input)\n{\n if (!input || input->atEOS())\n {\n MSPUB_DEBUG_MSG((\"Something bad happened here!Tell: %ld\\n\", input->tell()));\n throw EndOfStreamException();\n }\n unsigned long numBytesRead;\n uint8_t const *p = input->read(sizeof(uint8_t), numBytesRead);\n\n if (p && numBytesRead == sizeof(uint8_t))\n return *(uint8_t const *)(p);\n throw EndOfStreamException();\n}\n\nuint16_t libmspub::readU16(WPXInputStream *input)\n{\n uint16_t p0 = (uint16_t)readU8(input);\n uint16_t p1 = (uint16_t)readU8(input);\n return (uint16_t)(p0|(p1<<8));\n}\n\nuint32_t libmspub::readU32(WPXInputStream *input)\n{\n uint32_t p0 = (uint32_t)readU8(input);\n uint32_t p1 = (uint32_t)readU8(input);\n uint32_t p2 = (uint32_t)readU8(input);\n uint32_t p3 = (uint32_t)readU8(input);\n return (uint32_t)(p0|(p1<<8)|(p2<<16)|(p3<<24));\n}\n\nint8_t libmspub::readS8(WPXInputStream *input)\n{\n return (int8_t)readU8(input);\n}\n\nint16_t libmspub::readS16(WPXInputStream *input)\n{\n return (int16_t)readU16(input);\n}\n\nint32_t libmspub::readS32(WPXInputStream *input)\n{\n return (int32_t)readU32(input);\n}\n\nuint64_t libmspub::readU64(WPXInputStream *input)\n{\n uint64_t p0 = (uint64_t)readU8(input);\n uint64_t p1 = (uint64_t)readU8(input);\n uint64_t p2 = (uint64_t)readU8(input);\n uint64_t p3 = (uint64_t)readU8(input);\n uint64_t p4 = (uint64_t)readU8(input);\n uint64_t p5 = (uint64_t)readU8(input);\n uint64_t p6 = (uint64_t)readU8(input);\n uint64_t p7 = (uint64_t)readU8(input);\n return (uint64_t)(p0|(p1<<8)|(p2<<16)|(p3<<24)|(p4<<32)|(p5<<40)|(p6<<48)|(p7<<56));\n}\n\nvoid libmspub::readNBytes(WPXInputStream *input, unsigned long length, std::vector<unsigned char> &out)\n{\n unsigned long numBytesRead = 0;\n const unsigned char *tmpBuffer = input->read(length, numBytesRead);\n if (numBytesRead != length)\n {\n out.clear();\n return;\n }\n out = std::vector<unsigned char>(numBytesRead);\n memcpy(&out[0], tmpBuffer, numBytesRead);\n return;\n}\n\n#define SURROGATE_VALUE(h,l) (((h) - 0xd800) * 0x400 + (l) - 0xdc00 + 0x10000)\n\n\nvoid libmspub::appendCharacters(WPXString &text, const std::vector<unsigned char> characters,\n const char *encoding)\n{\n UErrorCode status = U_ZERO_ERROR;\n UConverter *conv = NULL;\n conv = ucnv_open(encoding, &status);\n if (U_SUCCESS(status))\n {\n \/\/ ICU documentation claims that character-by-character processing is faster \"for small amounts of data\" and \"'normal' charsets\"\n \/\/ (in any case, it is more convenient :) )\n const char *src = (const char *)&characters[0];\n const char *srcLimit = (const char *)src + characters.size();\n while (src < srcLimit)\n {\n uint32_t ucs4Character = (uint32_t)ucnv_getNextUChar(conv, &src, srcLimit, &status);\n if (U_SUCCESS(status))\n {\n _appendUCS4(text, ucs4Character);\n }\n }\n }\n if (conv)\n {\n ucnv_close(conv);\n }\n}\n\nbool libmspub::stillReading(WPXInputStream *input, unsigned long until)\n{\n if (input->atEOS())\n return false;\n if (input->tell() < 0)\n return false;\n if ((unsigned long)input->tell() >= until)\n return false;\n return true;\n}\n\n\/* vim:set shiftwidth=2 softtabstop=2 expandtab: *\/\n<commit_msg>return immediately if there's nothing to read<commit_after>\/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- *\/\n\/* libmspub\n * Version: MPL 1.1 \/ GPLv2+ \/ LGPLv2+\n *\n * The contents of this file are subject to the Mozilla Public License Version\n * 1.1 (the \"License\"); you may not use this file except in compliance with\n * the License or as specified alternatively below. You may obtain a copy of\n * the License at http:\/\/www.mozilla.org\/MPL\/\n *\n * Software distributed under the License is distributed on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License\n * for the specific language governing rights and limitations under the\n * License.\n *\n * Major Contributor(s):\n * Copyright (C) 2012-2013 Brennan Vincent <brennanv@email.arizona.edu>\n * Copyright (C) 2011 Fridrich Strba <fridrich.strba@bluewin.ch>\n * Copyright (C) 2011 Eilidh McAdam <tibbylickle@gmail.com>\n *\n *\n * All Rights Reserved.\n *\n * For minor contributions see the git repository.\n *\n * Alternatively, the contents of this file may be used under the terms of\n * either the GNU General Public License Version 2 or later (the \"GPLv2+\"), or\n * the GNU Lesser General Public License Version 2 or later (the \"LGPLv2+\"),\n * in which case the provisions of the GPLv2+ or the LGPLv2+ are applicable\n * instead of those above.\n *\/\n\n#include <unicode\/ucnv.h>\n#include <unicode\/utypes.h>\n\n#include <string.h> \/\/ for memcpy\n#include <math.h>\n#include <zlib.h>\n#include <cstring>\n\n#include \"libmspub_utils.h\"\n\n#ifndef M_PI\n#define M_PI 3.14159265358979323846\n#endif\n\n#define ZLIB_CHUNK 16384\n\nusing std::strcmp;\nconst char *libmspub::windowsCharsetNameByOriginalCharset(const char *name)\n{\n if (strcmp(name, \"Shift_JIS\") == 0)\n {\n return \"windows-932\";\n }\n if (strcmp(name, \"GB18030\") == 0)\n {\n return \"windows-936\";\n }\n if (strcmp(name, \"Big5\") == 0)\n {\n return \"windows-950\";\n }\n if (strcmp(name, \"ISO-8859-1\") == 0)\n {\n return \"windows-1252\";\n }\n if (strcmp(name, \"ISO-8859-2\") == 0)\n {\n return \"windows-1250\";\n }\n if (strcmp(name, \"windows-1251\") == 0)\n {\n return \"windows-1251\";\n }\n if (strcmp(name, \"windows-1256\") == 0)\n {\n return \"windows-1256\";\n }\n return NULL;\n}\n\nconst char *libmspub::mimeByImgType(ImgType type)\n{\n switch (type)\n {\n case PNG:\n return \"image\/png\";\n case JPEG:\n return \"image\/jpeg\";\n case DIB:\n return \"image\/bmp\";\n case PICT:\n return \"image\/pict\";\n case WMF:\n return \"image\/wmf\";\n case EMF:\n return \"image\/emf\";\n case TIFF:\n return \"image\/tiff\";\n default:\n MSPUB_DEBUG_MSG((\"Unknown image type %d passed to mimeByImgType!\\n\", type));\n return 0;\n }\n}\n\nvoid libmspub::rotateCounter(double &x, double &y, double centerX, double centerY, short rotation)\n{\n double vecX = x - centerX;\n double vecY = centerY - y;\n double sinTheta = sin(rotation * M_PI \/ 180.);\n double cosTheta = cos(rotation * M_PI \/ 180.);\n double newVecX = cosTheta * vecX - sinTheta * vecY;\n double newVecY = sinTheta * vecX + cosTheta * vecY;\n x = centerX + newVecX;\n y = centerY - newVecY;\n}\n\ndouble libmspub::doubleModulo(double x, double y)\n{\n if (y <= 0) \/\/ y <= 0 doesn't make sense\n {\n return x;\n }\n while (x < 0)\n {\n x += y;\n }\n while (x >= y)\n {\n x -= y;\n }\n return x;\n}\n\ndouble libmspub::toFixedPoint(int fp)\n{\n unsigned short fractionalPart = ((unsigned short) fp) & 0xFFFF;\n short integralPart = fp >> 16;\n return integralPart + fractionalPart \/ 65536.;\n}\n\ndouble libmspub::readFixedPoint(WPXInputStream *input)\n{\n return toFixedPoint(readS32(input));\n}\n\nvoid libmspub::flipIfNecessary(double &x, double &y, double centerX, double centerY, bool flipVertical, bool flipHorizontal)\n{\n double vecX = x - centerX;\n double vecY = centerY - y;\n if (flipVertical)\n {\n y = centerY + vecY;\n }\n if (flipHorizontal)\n {\n x = centerX - vecX;\n }\n}\n\nunsigned libmspub::correctModulo(int x, unsigned n) \/\/ returns the canonical representation of x in Z\/nZ\n\/\/difference with C++ % operator is that this never returns negative values.\n{\n if (x < 0)\n {\n int result = x % (int)n;\n \/\/sign of result is implementation defined\n if (result < 0)\n {\n return n + result;\n }\n return result;\n }\n return x % n;\n}\n\nWPXBinaryData libmspub::inflateData(WPXBinaryData deflated)\n{\n WPXBinaryData inflated;\n unsigned char out[ZLIB_CHUNK];\n const unsigned char *data = deflated.getDataBuffer();\n z_stream strm;\n int ret;\n strm.zalloc = Z_NULL;\n strm.zfree = Z_NULL;\n strm.opaque = Z_NULL;\n strm.avail_in = 0;\n strm.next_in = Z_NULL;\n if (inflateInit2(&strm,-MAX_WBITS) != Z_OK)\n {\n return WPXBinaryData();\n }\n int have;\n unsigned left = deflated.size();\n do\n {\n strm.avail_in = ZLIB_CHUNK > left ? left : ZLIB_CHUNK;\n strm.next_in = (unsigned char *)data;\n do\n {\n strm.avail_out = ZLIB_CHUNK;\n strm.next_out = out;\n ret = inflate(&strm, Z_NO_FLUSH);\n if (ret == Z_STREAM_ERROR || ret == Z_NEED_DICT || ret == Z_DATA_ERROR || ret == Z_MEM_ERROR)\n {\n inflateEnd(&strm);\n return WPXBinaryData();\n }\n have = ZLIB_CHUNK - strm.avail_out;\n inflated.append(out, have);\n }\n while (strm.avail_out == 0);\n data += ZLIB_CHUNK > left ? left : ZLIB_CHUNK;\n left -= ZLIB_CHUNK > left ? left : ZLIB_CHUNK;\n }\n while (ret != Z_STREAM_END);\n inflateEnd(&strm);\n return inflated;\n}\n\nnamespace\n{\n\nstatic void _appendUCS4(WPXString &text, unsigned ucs4Character)\n{\n unsigned char first;\n int len;\n if (ucs4Character < 0x80)\n {\n first = 0;\n len = 1;\n }\n else if (ucs4Character < 0x800)\n {\n first = 0xc0;\n len = 2;\n }\n else if (ucs4Character < 0x10000)\n {\n first = 0xe0;\n len = 3;\n }\n else if (ucs4Character < 0x200000)\n {\n first = 0xf0;\n len = 4;\n }\n else if (ucs4Character < 0x4000000)\n {\n first = 0xf8;\n len = 5;\n }\n else\n {\n first = 0xfc;\n len = 6;\n }\n\n unsigned char outbuf[6] = { 0, 0, 0, 0, 0, 0 };\n int i;\n for (i = len - 1; i > 0; --i)\n {\n outbuf[i] = (ucs4Character & 0x3f) | 0x80;\n ucs4Character >>= 6;\n }\n outbuf[0] = (ucs4Character & 0xff) | first;\n\n for (i = 0; i < len; i++)\n text.append(outbuf[i]);\n}\n\n} \/\/ anonymous namespace\n\n#define MSPUB_NUM_ELEMENTS(array) sizeof(array)\/sizeof(array[0])\n\nuint8_t libmspub::readU8(WPXInputStream *input)\n{\n if (!input || input->atEOS())\n {\n MSPUB_DEBUG_MSG((\"Something bad happened here!Tell: %ld\\n\", input->tell()));\n throw EndOfStreamException();\n }\n unsigned long numBytesRead;\n uint8_t const *p = input->read(sizeof(uint8_t), numBytesRead);\n\n if (p && numBytesRead == sizeof(uint8_t))\n return *(uint8_t const *)(p);\n throw EndOfStreamException();\n}\n\nuint16_t libmspub::readU16(WPXInputStream *input)\n{\n uint16_t p0 = (uint16_t)readU8(input);\n uint16_t p1 = (uint16_t)readU8(input);\n return (uint16_t)(p0|(p1<<8));\n}\n\nuint32_t libmspub::readU32(WPXInputStream *input)\n{\n uint32_t p0 = (uint32_t)readU8(input);\n uint32_t p1 = (uint32_t)readU8(input);\n uint32_t p2 = (uint32_t)readU8(input);\n uint32_t p3 = (uint32_t)readU8(input);\n return (uint32_t)(p0|(p1<<8)|(p2<<16)|(p3<<24));\n}\n\nint8_t libmspub::readS8(WPXInputStream *input)\n{\n return (int8_t)readU8(input);\n}\n\nint16_t libmspub::readS16(WPXInputStream *input)\n{\n return (int16_t)readU16(input);\n}\n\nint32_t libmspub::readS32(WPXInputStream *input)\n{\n return (int32_t)readU32(input);\n}\n\nuint64_t libmspub::readU64(WPXInputStream *input)\n{\n uint64_t p0 = (uint64_t)readU8(input);\n uint64_t p1 = (uint64_t)readU8(input);\n uint64_t p2 = (uint64_t)readU8(input);\n uint64_t p3 = (uint64_t)readU8(input);\n uint64_t p4 = (uint64_t)readU8(input);\n uint64_t p5 = (uint64_t)readU8(input);\n uint64_t p6 = (uint64_t)readU8(input);\n uint64_t p7 = (uint64_t)readU8(input);\n return (uint64_t)(p0|(p1<<8)|(p2<<16)|(p3<<24)|(p4<<32)|(p5<<40)|(p6<<48)|(p7<<56));\n}\n\nvoid libmspub::readNBytes(WPXInputStream *input, unsigned long length, std::vector<unsigned char> &out)\n{\n if (length == 0)\n {\n MSPUB_DEBUG_MSG((\"Attempt to read 0 bytes!\"));\n return;\n }\n\n unsigned long numBytesRead = 0;\n const unsigned char *tmpBuffer = input->read(length, numBytesRead);\n if (numBytesRead != length)\n {\n out.clear();\n return;\n }\n out = std::vector<unsigned char>(numBytesRead);\n memcpy(&out[0], tmpBuffer, numBytesRead);\n return;\n}\n\n#define SURROGATE_VALUE(h,l) (((h) - 0xd800) * 0x400 + (l) - 0xdc00 + 0x10000)\n\n\nvoid libmspub::appendCharacters(WPXString &text, const std::vector<unsigned char> characters,\n const char *encoding)\n{\n UErrorCode status = U_ZERO_ERROR;\n UConverter *conv = NULL;\n conv = ucnv_open(encoding, &status);\n if (U_SUCCESS(status))\n {\n \/\/ ICU documentation claims that character-by-character processing is faster \"for small amounts of data\" and \"'normal' charsets\"\n \/\/ (in any case, it is more convenient :) )\n const char *src = (const char *)&characters[0];\n const char *srcLimit = (const char *)src + characters.size();\n while (src < srcLimit)\n {\n uint32_t ucs4Character = (uint32_t)ucnv_getNextUChar(conv, &src, srcLimit, &status);\n if (U_SUCCESS(status))\n {\n _appendUCS4(text, ucs4Character);\n }\n }\n }\n if (conv)\n {\n ucnv_close(conv);\n }\n}\n\nbool libmspub::stillReading(WPXInputStream *input, unsigned long until)\n{\n if (input->atEOS())\n return false;\n if (input->tell() < 0)\n return false;\n if ((unsigned long)input->tell() >= until)\n return false;\n return true;\n}\n\n\/* vim:set shiftwidth=2 softtabstop=2 expandtab: *\/\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.\n#include \"frtconfigagent.h\"\n#include \"frtconfigrequestv3.h\"\n#include <vespa\/config\/common\/trace.h>\n\n#include <vespa\/log\/log.h>\nLOG_SETUP(\".config.frt.frtconfigagent\");\n\nnamespace config {\n\nFRTConfigAgent::FRTConfigAgent(const IConfigHolder::SP & holder, const TimingValues & timingValues)\n : _holder(holder),\n _timingValues(timingValues),\n _configState(),\n _latest(),\n _waitTime(0),\n _numConfigured(0),\n _failedRequests(0),\n _nextTimeout(_timingValues.initialTimeout)\n{\n}\n\nFRTConfigAgent::~FRTConfigAgent() {}\n\nvoid\nFRTConfigAgent::handleResponse(const ConfigRequest & request, ConfigResponse::UP response)\n{\n if (LOG_WOULD_LOG(spam)) {\n const ConfigKey & key(request.getKey());\n LOG(spam, \"current state for %s: generation %ld md5 %s\", key.toString().c_str(), _configState.generation, _configState.md5.c_str());\n }\n if (response->validateResponse() && !response->isError()) {\n handleOKResponse(request, std::move(response));\n } else {\n handleErrorResponse(request, std::move(response));\n }\n}\n\nvoid\nFRTConfigAgent::handleOKResponse(const ConfigRequest & request, ConfigResponse::UP response)\n{\n _failedRequests = 0;\n response->fill();\n if (LOG_WOULD_LOG(spam)) {\n LOG(spam, \"trace(%s)\", response->getTrace().toString().c_str());\n }\n\n ConfigState newState = response->getConfigState();\n if ( ! request.verifyState(newState)) {\n handleUpdatedGeneration(response->getKey(), newState, response->getValue());\n }\n setWaitTime(_timingValues.successDelay, 1);\n _nextTimeout = _timingValues.successTimeout;\n}\n\nvoid\nFRTConfigAgent::handleUpdatedGeneration(const ConfigKey & key, const ConfigState & newState, const ConfigValue & configValue)\n{\n if (LOG_WOULD_LOG(spam)) {\n LOG(spam, \"new generation %ld for key %s\", newState.generation, key.toString().c_str());\n }\n _latest = configValue;\n\n\n if (LOG_WOULD_LOG(spam)) {\n LOG(spam, \"updating holder for key %s,\", key.toString().c_str());\n }\n _holder->handle(ConfigUpdate::UP(new ConfigUpdate(_latest, true, newState.generation)));\n _numConfigured++;\n _configState = newState;\n}\n\nvoid\nFRTConfigAgent::handleErrorResponse(const ConfigRequest & request, ConfigResponse::UP response)\n{\n _failedRequests++;\n int multiplier = std::min(_failedRequests, _timingValues.maxDelayMultiplier);\n setWaitTime(_numConfigured > 0 ? _timingValues.configuredErrorDelay : _timingValues.unconfiguredDelay, multiplier);\n _nextTimeout = _timingValues.errorTimeout;\n const ConfigKey & key(request.getKey());\n LOG(info, \"Error response or no response from config server (key: %s) (errcode=%d, validresponse:%d), trying again in %ld milliseconds\", key.toString().c_str(), response->errorCode(), response->hasValidResponse() ? 1 : 0, _waitTime);\n}\n\nvoid\nFRTConfigAgent::setWaitTime(uint64_t delay, int multiplier)\n{\n uint64_t prevWait = _waitTime;\n _waitTime = _timingValues.fixedDelay + (multiplier * delay);\n LOG(spam, \"Adjusting waittime from %ld to %ld\", prevWait, _waitTime);\n}\n\nuint64_t FRTConfigAgent::getTimeout() const { return _nextTimeout; }\nuint64_t FRTConfigAgent::getWaitTime() const { return _waitTime; }\nconst ConfigState & FRTConfigAgent::getConfigState() const { return _configState; }\n\n}\n<commit_msg>Set _configState before calling out to holder.<commit_after>\/\/ Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.\n#include \"frtconfigagent.h\"\n#include \"frtconfigrequestv3.h\"\n#include <vespa\/config\/common\/trace.h>\n\n#include <vespa\/log\/log.h>\nLOG_SETUP(\".config.frt.frtconfigagent\");\n\nnamespace config {\n\nFRTConfigAgent::FRTConfigAgent(const IConfigHolder::SP & holder, const TimingValues & timingValues)\n : _holder(holder),\n _timingValues(timingValues),\n _configState(),\n _latest(),\n _waitTime(0),\n _numConfigured(0),\n _failedRequests(0),\n _nextTimeout(_timingValues.initialTimeout)\n{\n}\n\nFRTConfigAgent::~FRTConfigAgent() {}\n\nvoid\nFRTConfigAgent::handleResponse(const ConfigRequest & request, ConfigResponse::UP response)\n{\n if (LOG_WOULD_LOG(spam)) {\n const ConfigKey & key(request.getKey());\n LOG(spam, \"current state for %s: generation %ld md5 %s\", key.toString().c_str(), _configState.generation, _configState.md5.c_str());\n }\n if (response->validateResponse() && !response->isError()) {\n handleOKResponse(request, std::move(response));\n } else {\n handleErrorResponse(request, std::move(response));\n }\n}\n\nvoid\nFRTConfigAgent::handleOKResponse(const ConfigRequest & request, ConfigResponse::UP response)\n{\n _failedRequests = 0;\n response->fill();\n if (LOG_WOULD_LOG(spam)) {\n LOG(spam, \"trace(%s)\", response->getTrace().toString().c_str());\n }\n\n ConfigState newState = response->getConfigState();\n if ( ! request.verifyState(newState)) {\n handleUpdatedGeneration(response->getKey(), newState, response->getValue());\n }\n setWaitTime(_timingValues.successDelay, 1);\n _nextTimeout = _timingValues.successTimeout;\n}\n\nvoid\nFRTConfigAgent::handleUpdatedGeneration(const ConfigKey & key, const ConfigState & newState, const ConfigValue & configValue)\n{\n if (LOG_WOULD_LOG(spam)) {\n LOG(spam, \"new generation %ld for key %s\", newState.generation, key.toString().c_str());\n }\n _latest = configValue;\n _configState = newState;\n\n\n if (LOG_WOULD_LOG(spam)) {\n LOG(spam, \"updating holder for key %s,\", key.toString().c_str());\n }\n _holder->handle(ConfigUpdate::UP(new ConfigUpdate(_latest, true, newState.generation)));\n _numConfigured++;\n}\n\nvoid\nFRTConfigAgent::handleErrorResponse(const ConfigRequest & request, ConfigResponse::UP response)\n{\n _failedRequests++;\n int multiplier = std::min(_failedRequests, _timingValues.maxDelayMultiplier);\n setWaitTime(_numConfigured > 0 ? _timingValues.configuredErrorDelay : _timingValues.unconfiguredDelay, multiplier);\n _nextTimeout = _timingValues.errorTimeout;\n const ConfigKey & key(request.getKey());\n LOG(info, \"Error response or no response from config server (key: %s) (errcode=%d, validresponse:%d), trying again in %ld milliseconds\", key.toString().c_str(), response->errorCode(), response->hasValidResponse() ? 1 : 0, _waitTime);\n}\n\nvoid\nFRTConfigAgent::setWaitTime(uint64_t delay, int multiplier)\n{\n uint64_t prevWait = _waitTime;\n _waitTime = _timingValues.fixedDelay + (multiplier * delay);\n LOG(spam, \"Adjusting waittime from %ld to %ld\", prevWait, _waitTime);\n}\n\nuint64_t FRTConfigAgent::getTimeout() const { return _nextTimeout; }\nuint64_t FRTConfigAgent::getWaitTime() const { return _waitTime; }\nconst ConfigState & FRTConfigAgent::getConfigState() const { return _configState; }\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * qiesmap.cpp\n *\n * Copyright (c) 2016 Tobias Wood.\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\n *\/\n\n#include <getopt.h>\n#include <iostream>\n#include <Eigen\/Dense>\n#include <Eigen\/Eigenvalues>\n\n#include \"QI\/Util.h\"\n#include \"Filters\/ApplyAlgorithmFilter.h\"\n\nusing namespace std;\nusing namespace Eigen;\n\nclass ESAlgo : public Algorithm<complex<double>> {\nprotected:\n size_t m_size = 0;\npublic:\n size_t numInputs() const override { return 1; }\n size_t numConsts() const override { return 0; }\n size_t numOutputs() const override { return 6; }\n const vector<string> & names() const {\n static vector<string> _names = {\"M\", \"T1\", \"T2\", \"th\", \"a\", \"b\"};\n return _names;\n }\n size_t dataSize() const override { return m_size; }\n void setSize(const size_t s) { m_size = s; }\n virtual TArray defaultConsts() override {\n \/\/ B1\n TArray def = TArray::Ones(0);\n return def;\n }\n void apply(const TInput &data, const TArray &inputs, TArray &outputs, TArray &resids, TIterations &its) const override\n {\n typedef Matrix<double, 6, 6> Matrix6d;\n typedef Matrix<double, 6, 1> Vector6d;\n double scale = data.abs().maxCoeff();\n ArrayXd x = data.real() \/ scale;\n ArrayXd y = data.imag() \/ scale;\n \n Matrix<double, Dynamic, 6> D(data.rows(), 6);\n D.col(0) = x*x;\n D.col(1) = x*y;\n D.col(2) = y*y;\n D.col(3) = x;\n D.col(4) = y;\n D.col(5).setConstant(1);\n Matrix6d S = D.transpose() * D;\n Matrix6d C = Matrix6d::Zero();\n C(0,2) = -2; C(1,1) = 1; C(2,0) = -2;\n \n typedef GeneralizedEigenSolver<Matrix6d> ESolver;\n ESolver es(S, C);\n ArrayXd eVals = es.eigenvalues().real();\n ArrayXd Z;\n for (int i = 0; i < 6; i++) {\n if (isfinite(eVals(i)) && (eVals(i) < 0)) {\n Z = es.eigenvectors().col(i);\n break;\n }\n }\n \n const double za = Z[0];\n const double zb = Z[1]\/2;\n const double zc = Z[2];\n const double zd = Z[3]\/2;\n const double zf = Z[4]\/2;\n const double zg = Z[5];\n const double dsc=(zb*zb-za*zc);\n const double xc = (zc*zd-zb*zf)\/dsc;\n const double yc = (za*zf-zb*zd)\/dsc;\n const double th = atan2(yc,xc);\n double A = sqrt((2*(za*(zf*zf)+zc*(zd*zd)+zg*(zb*zb)-2*zb*zd*zf-za*zc*zg))\/(dsc*(sqrt((za-zc)*(za-zc) + 4*zb*zb)-(za+zc))));\n double B = sqrt((2*(za*(zf*zf)+zc*(zd*zd)+zg*(zb*zb)-2*zb*zd*zf-za*zc*zg))\/(dsc*(-sqrt((za-zc)*(za-zc) + 4*zb*zb)-(za+zc))));\n if (A > B) {\n std::swap(A, B);\n }\n cout << \"Z \" << Z.transpose() << endl;\n cout << \"dsc \" << dsc << \" xc \" << xc << \" yc \" << yc << \" A \" << A << \" B \" << B << endl;\n const double c = sqrt(xc*xc+yc*xc);\n const double b = (-2*c*A + sqrt(pow(2*c*A,2)-4*(c*c+B*B)*(A*A-B*B)))\/(2*(c*c+B*B));\n const double a = B \/ (b*B + c*sqrt(1-b*b));\n const double M = scale*c*(1-b*b)\/(1-a*b);\n const double TR = 0.0065;\n const double FA = (25*M_PI\/180.);\n const double T1 = -TR \/ log((a*(1+cos(FA)-a*b*cos(FA))-b)\/(a*(1+cos(FA)-a*b)-b*cos(FA)));\n const double T2 = -TR \/ log(a);\n \n outputs[0] = M;\n outputs[1] = T1;\n outputs[2] = T2;\n outputs[3] = th;\n outputs[4] = a;\n outputs[5] = b;\n }\n};\n\n\/\/******************************************************************************\n\/\/ Arguments \/ Usage\n\/\/******************************************************************************\nconst string usage {\n\"Usage is: qiesmap [options] input \\n\\\n\\n\\\nA utility for calculating T1,T2,PD and f0 maps from SSFP data.\\n\\\nInput must be a single complex image with at least 6 phase increments.\\n\\\n\\n\\\nOptions:\\n\\\n --help, -h : Print this message.\\n\\\n --verbose, -v : Print more information.\\n\\\n --out, -o path : Specify an output prefix.\\n\\\n --mask, -m file : Mask input with specified file.\\n\\\n --threads, -T N : Use N threads (default=hardware limit).\\n\"\n};\n\nbool verbose = false;\nstatic size_t num_threads = 4;\nstatic string outPrefix;\nconst struct option long_opts[] = {\n {\"help\", no_argument, 0, 'h'},\n {\"verbose\", no_argument, 0, 'v'},\n {\"out\", required_argument, 0, 'o'},\n {\"mask\", required_argument, 0, 'm'},\n {\"threads\", required_argument, 0, 'T'},\n {0, 0, 0, 0}\n};\nconst char *short_opts = \"hvo:m:T:\";\n\n\/\/******************************************************************************\n\/\/ Main\n\/\/******************************************************************************\nint main(int argc, char **argv) {\n Eigen::initParallel();\n QI::VolumeF::Pointer mask = ITK_NULLPTR;\n QI::VolumeF::Pointer B1 = ITK_NULLPTR;\n\n shared_ptr<ESAlgo> algo = make_shared<ESAlgo>();\n int indexptr = 0, c;\n while ((c = getopt_long(argc, argv, short_opts, long_opts, &indexptr)) != -1) {\n switch (c) {\n case 'v': verbose = true; break;\n case 'm':\n if (verbose) cout << \"Opening mask file \" << optarg << endl;\n mask = QI::ReadImage(optarg);\n break;\n case 'o':\n outPrefix = optarg;\n if (verbose) cout << \"Output prefix will be: \" << outPrefix << endl;\n break;\n case 'b':\n if (verbose) cout << \"Opening B1 file: \" << optarg << endl;\n B1 = QI::ReadImage(optarg);\n break;\n case 'T':\n num_threads = stoi(optarg);\n if (num_threads == 0)\n num_threads = std::thread::hardware_concurrency();\n break;\n case 'h':\n cout << QI::GetVersion() << endl << usage << endl;\n return EXIT_SUCCESS;\n case '?': \/\/ getopt will print an error message\n return EXIT_FAILURE;\n default:\n cout << \"Unhandled option \" << string(1, c) << endl;\n return EXIT_FAILURE;\n }\n }\n if ((argc - optind) != 1) {\n cout << \"Incorrect number of arguments.\" << endl << usage << endl;\n return EXIT_FAILURE;\n }\n\n string inputFilename = argv[optind++];\n if (verbose) cout << \"Opening file: \" << inputFilename << endl;\n auto data = QI::ReadVectorImage<complex<float>>(inputFilename);\n auto apply = itk::ApplyAlgorithmFilter<ESAlgo, complex<float>>::New();\n algo->setSize(data->GetNumberOfComponentsPerPixel());\n apply->SetAlgorithm(algo);\n apply->SetPoolsize(num_threads);\n apply->SetInput(0, data);\n if (mask)\n apply->SetMask(mask);\n \/*if (B1)\n apply->SetConst(0, B1);*\/\n if (verbose) {\n cout << \"Processing\" << endl;\n auto monitor = QI::GenericMonitor::New();\n apply->AddObserver(itk::ProgressEvent(), monitor);\n }\n apply->Update();\n if (verbose) {\n cout << \"Elapsed time was \" << apply->GetTotalTime() << \"s\" << endl;\n cout << \"Mean time per voxel was \" << apply->GetMeanTime() << \"s\" << endl;\n cout << \"Writing results files.\" << endl;\n }\n outPrefix = outPrefix + \"ES_\";\n for (int i = 0; i < algo->numOutputs(); i++) {\n QI::WriteImage(apply->GetOutput(i), outPrefix + algo->names().at(i) + QI::OutExt());\n }\n \n if (verbose) cout << \"Finished.\" << endl;\n return EXIT_SUCCESS;\n}\n<commit_msg>ENH: Added own code to find generalized eigenvectors.<commit_after>\/*\n * qiesmap.cpp\n *\n * Copyright (c) 2016 Tobias Wood.\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\n *\/\n\n#include <getopt.h>\n#include <iostream>\n#include <Eigen\/Dense>\n#include <Eigen\/Eigenvalues>\n\n#include \"QI\/Util.h\"\n#include \"Filters\/ApplyAlgorithmFilter.h\"\n\nusing namespace std;\nusing namespace Eigen;\n\nclass ESAlgo : public Algorithm<complex<double>> {\nprotected:\n size_t m_size = 0;\npublic:\n size_t numInputs() const override { return 1; }\n size_t numConsts() const override { return 1; }\n size_t numOutputs() const override { return 6; }\n const vector<string> & names() const {\n static vector<string> _names = {\"M\", \"T1\", \"T2\", \"th\", \"a\", \"b\"};\n return _names;\n }\n size_t dataSize() const override { return m_size; }\n void setSize(const size_t s) { m_size = s; }\n virtual TArray defaultConsts() override {\n \/\/ B1\n TArray def = TArray::Ones(1);\n return def;\n }\n \n ArrayXd solveEig(const MatrixXd &A, const MatrixXd &B) const {\n RealQZ<MatrixXd> qz(A, B);\n VectorXd v = ArrayXd::Zero(A.cols());\n const MatrixXd &mS = qz.matrixS();\n const MatrixXd &mT = qz.matrixT();\n const MatrixXd &mZT = qz.matrixZ().transpose();\n for (int i = 0; i < 6; i++) {\n const double a = mS.coeffRef(i,i);\n const double b = mT.coeffRef(i,i);\n const double l = a \/ b;\n if (isfinite(l) && (l < 0)) {\n v(i) = 1.0;\n const double a = qz.matrixS().coeffRef(i,i);\n const double b = qz.matrixT().coeffRef(i,i);\n for (Index j = i-1; j >= 0; j--) {\n const Index st = j+1;\n const Index sz = i-j; \n v.coeffRef(j) = -v.segment(st,sz).transpose().cwiseProduct(b*mS.block(j,st,1,sz) - a*mT.block(j,st,1,sz)).sum() \/ (b*mS.coeffRef(j,j) - a*mT.coeffRef(j,j));\n }\n v = (mZT * v).normalized();\n break;\n }\n }\n return v;\n }\n \n void apply(const TInput &data, const TArray &inputs, TArray &outputs, TArray &resids, TIterations &its) const override\n {\n typedef Matrix<double, 6, 6> Matrix6d;\n typedef Matrix<double, 6, 1> Vector6d;\n const double B1 = inputs[0];\n const double scale = data.abs().maxCoeff();\n ArrayXd x = data.real() \/ scale;\n ArrayXd y = data.imag() \/ scale;\n \n Matrix<double, Dynamic, 6> D(data.rows(), 6);\n D.col(0) = x*x;\n D.col(1) = x*y;\n D.col(2) = y*y;\n D.col(3) = x;\n D.col(4) = y;\n D.col(5).setConstant(1);\n Matrix6d S = D.transpose() * D;\n Matrix6d C = Matrix6d::Zero();\n C(0,2) = -2; C(1,1) = 1; C(2,0) = -2;\n ArrayXd Z = solveEig(S, C);\n const double za = Z[0];\n const double zb = Z[1]\/2;\n const double zc = Z[2];\n const double zd = Z[3]\/2;\n const double zf = Z[4]\/2;\n const double zg = Z[5];\n const double dsc=(zb*zb-za*zc);\n const double xc = (zc*zd-zb*zf)\/dsc;\n const double yc = (za*zf-zb*zd)\/dsc;\n const double th = atan2(yc,xc);\n double A = sqrt((2*(za*(zf*zf)+zc*(zd*zd)+zg*(zb*zb)-2*zb*zd*zf-za*zc*zg))\/(dsc*(sqrt((za-zc)*(za-zc) + 4*zb*zb)-(za+zc))));\n double B = sqrt((2*(za*(zf*zf)+zc*(zd*zd)+zg*(zb*zb)-2*zb*zd*zf-za*zc*zg))\/(dsc*(-sqrt((za-zc)*(za-zc) + 4*zb*zb)-(za+zc))));\n if (A > B) {\n std::swap(A, B);\n }\n \/\/cout << \"Z \" << Z.transpose() << endl;\n \/\/cout << \"dsc \" << dsc << \" xc \" << xc << \" yc \" << yc << \" A \" << A << \" B \" << B << endl;\n const double c = sqrt(xc*xc+yc*yc);\n const double b = (-c*A + sqrt(c*c*A*A - (c*c + B*B)*(A*A - B*B)))\/(c*c + B*B);\n const double a = B \/ (b*B + c*sqrt(1-b*b));\n const double M = scale*c*(1-b*b)\/(1-a*b);\n const double TR = 0.0065;\n const double FA = B1 * (25*M_PI\/180.);\n const double T1 = -TR \/ log((a*(1+cos(FA)-a*b*cos(FA))-b)\/(a*(1+cos(FA)-a*b)-b*cos(FA)));\n const double T2 = -TR \/ log(a);\n \n outputs[0] = M;\n outputs[1] = T1;\n outputs[2] = T2;\n outputs[3] = th;\n outputs[4] = a;\n outputs[5] = b;\n }\n};\n\n\/\/******************************************************************************\n\/\/ Arguments \/ Usage\n\/\/******************************************************************************\nconst string usage {\n\"Usage is: qiesmap [options] input \\n\\\n\\n\\\nA utility for calculating T1,T2,PD and f0 maps from SSFP data.\\n\\\nInput must be a single complex image with at least 6 phase increments.\\n\\\n\\n\\\nOptions:\\n\\\n --help, -h : Print this message.\\n\\\n --verbose, -v : Print more information.\\n\\\n --out, -o path : Specify an output prefix.\\n\\\n --mask, -m file : Mask input with specified file.\\n\\\n --B1, -b file : B1 Map file (ratio)\\n\\\n --threads, -T N : Use N threads (default=hardware limit).\\n\"\n};\n\nbool verbose = false;\nstatic size_t num_threads = 4;\nstatic string outPrefix;\nconst struct option long_opts[] = {\n {\"help\", no_argument, 0, 'h'},\n {\"verbose\", no_argument, 0, 'v'},\n {\"out\", required_argument, 0, 'o'},\n {\"mask\", required_argument, 0, 'm'},\n {\"B1\", required_argument, 0, 'b'},\n {\"threads\", required_argument, 0, 'T'},\n {0, 0, 0, 0}\n};\nconst char *short_opts = \"hvo:m:b:T:\";\n\n\/\/******************************************************************************\n\/\/ Main\n\/\/******************************************************************************\nint main(int argc, char **argv) {\n Eigen::initParallel();\n QI::VolumeF::Pointer mask = ITK_NULLPTR;\n QI::VolumeF::Pointer B1 = ITK_NULLPTR;\n\n shared_ptr<ESAlgo> algo = make_shared<ESAlgo>();\n int indexptr = 0, c;\n while ((c = getopt_long(argc, argv, short_opts, long_opts, &indexptr)) != -1) {\n switch (c) {\n case 'v': verbose = true; break;\n case 'm':\n if (verbose) cout << \"Opening mask file \" << optarg << endl;\n mask = QI::ReadImage(optarg);\n break;\n case 'o':\n outPrefix = optarg;\n if (verbose) cout << \"Output prefix will be: \" << outPrefix << endl;\n break;\n case 'b':\n if (verbose) cout << \"Opening B1 file: \" << optarg << endl;\n B1 = QI::ReadImage(optarg);\n break;\n case 'T':\n num_threads = stoi(optarg);\n if (num_threads == 0)\n num_threads = std::thread::hardware_concurrency();\n break;\n case 'h':\n cout << QI::GetVersion() << endl << usage << endl;\n return EXIT_SUCCESS;\n case '?': \/\/ getopt will print an error message\n return EXIT_FAILURE;\n default:\n cout << \"Unhandled option \" << string(1, c) << endl;\n return EXIT_FAILURE;\n }\n }\n if ((argc - optind) != 1) {\n cout << \"Incorrect number of arguments.\" << endl << usage << endl;\n return EXIT_FAILURE;\n }\n\n string inputFilename = argv[optind++];\n if (verbose) cout << \"Opening file: \" << inputFilename << endl;\n auto data = QI::ReadVectorImage<complex<float>>(inputFilename);\n auto apply = itk::ApplyAlgorithmFilter<ESAlgo, complex<float>>::New();\n algo->setSize(data->GetNumberOfComponentsPerPixel());\n apply->SetAlgorithm(algo);\n apply->SetPoolsize(num_threads);\n apply->SetInput(0, data);\n if (mask)\n apply->SetMask(mask);\n if (B1)\n apply->SetConst(0, B1);\n if (verbose) {\n cout << \"Processing\" << endl;\n auto monitor = QI::GenericMonitor::New();\n apply->AddObserver(itk::ProgressEvent(), monitor);\n }\n apply->Update();\n if (verbose) {\n cout << \"Elapsed time was \" << apply->GetTotalTime() << \"s\" << endl;\n cout << \"Mean time per voxel was \" << apply->GetMeanTime() << \"s\" << endl;\n cout << \"Writing results files.\" << endl;\n }\n outPrefix = outPrefix + \"ES_\";\n for (int i = 0; i < algo->numOutputs(); i++) {\n QI::WriteImage(apply->GetOutput(i), outPrefix + algo->names().at(i) + QI::OutExt());\n }\n \n if (verbose) cout << \"Finished.\" << endl;\n return EXIT_SUCCESS;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ vim:ts=2:sw=2:expandtab:autoindent:filetype=cpp:\n\/*\nCopyright (c) 2009 Aristid Breitkreuz, Ash Berlin, Ruediger Sonderfeld\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n*\/\n\n#ifndef FLUSSFPERD_CLASS_DESCRIPTION_HPP\n#define FLUSSFPERD_CLASS_DESCRIPTION_HPP\n\n#ifndef PREPROC_DEBUG\n#include \"class.hpp\"\n#endif\n#include <boost\/preprocessor.hpp>\n\n#define FLUSSPFERD_PP_GEN_TUPLE2SEQ_PROCESS2(x, y) \\\n ((x, y)) \\\n FLUSSPFERD_PP_GEN_TUPLE2SEQ_PROCESS\n\n#define FLUSSPFERD_PP_GEN_TUPLE2SEQ_PROCESS(x, y) \\\n ((x, y)) \\\n FLUSSPFERD_PP_GEN_TUPLE2SEQ_PROCESS2\n\n#define FLUSSPFERD_PP_GEN_TUPLE2SEQ_PROCESS_ELIM\n#define FLUSSPFERD_PP_GEN_TUPLE2SEQ_PROCESS2_ELIM\n\n#define FLUSSPFERD_PP_GEN_TUPLE2SEQ(x) \\\n BOOST_PP_CAT(BOOST_PP_EXPAND(FLUSSPFERD_PP_GEN_TUPLE2SEQ_PROCESS x), _ELIM)\n\n#define FLUSSPFERD_CD_PARAM_FOLD(s, state, elem) \\\n BOOST_PP_ARRAY_REPLACE( \\\n state, \\\n BOOST_PP_EXPAND( \\\n BOOST_PP_CAT(FLUSSPFERD_CD_PARAM__, \\\n BOOST_PP_TUPLE_ELEM(2, 0, elem))), \\\n BOOST_PP_TUPLE_ELEM(2, 1, elem)) \\\n \/* *\/\n\n#define FLUSSPFERD_CD_PARAM_INITIAL \\\n (5, ( \\\n ~cpp_name~, \/* name *\/ \\\n ~constructor_name~, \/* constructor name *\/ \\\n ~constructor_arity~, \/* constructor arity *\/ \\\n ~full_name~, \/* full name *\/ \\\n BOOST_PP_NIL \/* methods *\/ \\\n )) \\\n \/* *\/\n\n#define FLUSSPFERD_CD_PARAM__cpp_name 0\n#define FLUSSPFERD_CD_PARAM__constructor_name 1\n#define FLUSSPFERD_CD_PARAM__constructor_arity 2\n#define FLUSSPFERD_CD_PARAM__full_name 3\n#define FLUSSPFERD_CD_PARAM__methods 4\n\n#define FLUSSPFERD_CD_PARAM(tuple_seq) \\\n BOOST_PP_SEQ_FOLD_LEFT( \\\n FLUSSPFERD_CD_PARAM_FOLD, \\\n FLUSSPFERD_CD_PARAM_INITIAL, \\\n FLUSSPFERD_PP_GEN_TUPLE2SEQ(tuple_seq) \\\n ) \\\n \/* *\/\n\n#define FLUSSPFERD_CLASS_DESCRIPTION_A(array) \\\n BOOST_PP_EXPAND(FLUSSPFERD_CLASS_DESCRIPTION_P BOOST_PP_ARRAY_DATA(array)) \\\n \/* *\/\n\n#define FLUSSPFERD_CLASS_DESCRIPTION_P( \\\n p_cpp_name, \\\n p_constructor_name, \\\n p_constructor_arity, \\\n p_full_name, \\\n p_methods \\\n) \\\n class p_cpp_name { \\\n struct class_info : ::flusspferd::class_info_base { \\\n static char const *constructor_name() { \\\n return (p_constructor_name); \\\n } \\\n typedef ::boost::mpl::size_t< (p_constructor_arity) > constructor_arity; \\\n static char const *full_name() { \\\n return (p_full_name); \\\n } \\\n static ::flusspferd::object create_prototype() { \\\n ::flusspferd::object proto = ::flusspferd::create_object(); \\\n BOOST_PP_SEQ_FOR_EACH( \\\n FLUSSPFERD_CD_METHOD, \\\n p_cpp_name, \\\n p_methods) \\\n } \\\n }; \\\n \/* *\/\n\n#define FLUSSPFERD_CD_METHOD(r, p_cpp_name, element) \\\n ::flusspferd::create_native_method( \\\n proto, \\\n BOOST_PP_STRINGIZE(element), \\\n & p_cpp_name :: element); \\\n \/* *\/\n\n#define FLUSSPFERD_CLASS_DESCRIPTION(tuple_seq) \\\n FLUSSPFERD_CLASS_DESCRIPTION_A(FLUSSPFERD_CD_PARAM(tuple_seq)) \\\n \/* *\/\n\n#define FLUSSPFERD_CLASS_DESCRIPTION_END() \\\n }; \\\n \/* *\/\n\n#endif\n<commit_msg>class_macros: add augment_constructor<commit_after>\/\/ vim:ts=2:sw=2:expandtab:autoindent:filetype=cpp:\n\/*\nCopyright (c) 2009 Aristid Breitkreuz, Ash Berlin, Ruediger Sonderfeld\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n*\/\n\n#ifndef FLUSSFPERD_CLASS_DESCRIPTION_HPP\n#define FLUSSFPERD_CLASS_DESCRIPTION_HPP\n\n#ifndef PREPROC_DEBUG\n#include \"class.hpp\"\n#endif\n#include <boost\/preprocessor.hpp>\n\n#define FLUSSPFERD_PP_GEN_TUPLE2SEQ_PROCESS2(x, y) \\\n ((x, y)) \\\n FLUSSPFERD_PP_GEN_TUPLE2SEQ_PROCESS\n\n#define FLUSSPFERD_PP_GEN_TUPLE2SEQ_PROCESS(x, y) \\\n ((x, y)) \\\n FLUSSPFERD_PP_GEN_TUPLE2SEQ_PROCESS2\n\n#define FLUSSPFERD_PP_GEN_TUPLE2SEQ_PROCESS_ELIM\n#define FLUSSPFERD_PP_GEN_TUPLE2SEQ_PROCESS2_ELIM\n\n#define FLUSSPFERD_PP_GEN_TUPLE2SEQ(x) \\\n BOOST_PP_CAT(BOOST_PP_EXPAND(FLUSSPFERD_PP_GEN_TUPLE2SEQ_PROCESS x), _ELIM)\n\n#define FLUSSPFERD_CD_PARAM_FOLD(s, state, elem) \\\n BOOST_PP_ARRAY_REPLACE( \\\n state, \\\n BOOST_PP_EXPAND( \\\n BOOST_PP_CAT(FLUSSPFERD_CD_PARAM__, \\\n BOOST_PP_TUPLE_ELEM(2, 0, elem))), \\\n BOOST_PP_TUPLE_ELEM(2, 1, elem)) \\\n \/* *\/\n\n#define FLUSSPFERD_CD_PARAM_INITIAL \\\n (6, ( \\\n ~cpp_name~, \/* name *\/ \\\n ~constructor_name~, \/* constructor name *\/ \\\n ~constructor_arity~, \/* constructor arity *\/ \\\n ~full_name~, \/* full name *\/ \\\n BOOST_PP_NIL, \/* methods *\/ \\\n 0 \/* augment constructor *\/ \\\n )) \\\n \/* *\/\n\n#define FLUSSPFERD_CD_PARAM__cpp_name 0\n#define FLUSSPFERD_CD_PARAM__constructor_name 1\n#define FLUSSPFERD_CD_PARAM__constructor_arity 2\n#define FLUSSPFERD_CD_PARAM__full_name 3\n#define FLUSSPFERD_CD_PARAM__methods 4\n#define FLUSSPFERD_CD_PARAM__augment_constructor 5\n\n#define FLUSSPFERD_CD_PARAM(tuple_seq) \\\n BOOST_PP_SEQ_FOLD_LEFT( \\\n FLUSSPFERD_CD_PARAM_FOLD, \\\n FLUSSPFERD_CD_PARAM_INITIAL, \\\n FLUSSPFERD_PP_GEN_TUPLE2SEQ(tuple_seq) \\\n ) \\\n \/* *\/\n\n#define FLUSSPFERD_CLASS_DESCRIPTION_A(array) \\\n BOOST_PP_EXPAND(FLUSSPFERD_CLASS_DESCRIPTION_P BOOST_PP_ARRAY_DATA(array)) \\\n \/* *\/\n\n#define FLUSSPFERD_CLASS_DESCRIPTION_P( \\\n p_cpp_name, \\\n p_constructor_name, \\\n p_constructor_arity, \\\n p_full_name, \\\n p_methods, \\\n p_augment_constructor \\\n) \\\n class p_cpp_name { \\\n struct class_info : ::flusspferd::class_info_base { \\\n static char const *constructor_name() { \\\n return (p_constructor_name); \\\n } \\\n typedef ::boost::mpl::size_t< (p_constructor_arity) > constructor_arity; \\\n static char const *full_name() { \\\n return (p_full_name); \\\n } \\\n static ::flusspferd::object create_prototype() { \\\n ::flusspferd::object proto = ::flusspferd::create_object(); \\\n BOOST_PP_SEQ_FOR_EACH( \\\n FLUSSPFERD_CD_METHOD, \\\n p_cpp_name, \\\n p_methods) \\\n } \\\n BOOST_PP_EXPR_IF( \\\n p_augment_constructor, \\\n static void augment_constructor(::flusspferd::object &); \\\n ) \\\n }; \\\n \/* *\/\n\n#define FLUSSPFERD_CD_METHOD(r, p_cpp_name, element) \\\n ::flusspferd::create_native_method( \\\n proto, \\\n BOOST_PP_STRINGIZE(element), \\\n & p_cpp_name :: element); \\\n \/* *\/\n\n#define FLUSSPFERD_CLASS_DESCRIPTION(tuple_seq) \\\n FLUSSPFERD_CLASS_DESCRIPTION_A(FLUSSPFERD_CD_PARAM(tuple_seq)) \\\n \/* *\/\n\n#define FLUSSPFERD_CLASS_DESCRIPTION_END() \\\n }; \\\n \/* *\/\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2008 by Sun Microsystems, Inc.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: dbmetadata.cxx,v $\n * $Revision: 1.10.22.1 $\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * <http:\/\/www.openoffice.org\/license.html>\n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_connectivity.hxx\"\n\n#include \"connectivity\/dbmetadata.hxx\"\n#include \"connectivity\/dbexception.hxx\"\n#include \"connectivity\/DriversConfig.hxx\"\n#include \"resource\/common_res.hrc\"\n#include \"resource\/sharedresources.hxx\"\n\n\/** === begin UNO includes === **\/\n#include <com\/sun\/star\/lang\/IllegalArgumentException.hpp>\n#include <com\/sun\/star\/container\/XChild.hpp>\n#include <com\/sun\/star\/beans\/XPropertySet.hpp>\n#include <com\/sun\/star\/beans\/PropertyValue.hpp>\n#include <com\/sun\/star\/beans\/XPropertySetInfo.hpp>\n#include <com\/sun\/star\/sdb\/BooleanComparisonMode.hpp>\n#include <com\/sun\/star\/sdbc\/XDatabaseMetaData2.hpp>\n#include <com\/sun\/star\/sdbcx\/XUsersSupplier.hpp>\n#include <com\/sun\/star\/sdbcx\/XDataDefinitionSupplier.hpp>\n#include <com\/sun\/star\/sdbc\/XDriverAccess.hpp>\n\/** === end UNO includes === **\/\n\n#include <tools\/diagnose_ex.h>\n#include <comphelper\/namedvaluecollection.hxx>\n#include <comphelper\/componentcontext.hxx>\n#include <comphelper\/processfactory.hxx>\n\n#include <boost\/optional.hpp>\n\n\/\/........................................................................\nnamespace dbtools\n{\n\/\/........................................................................\n\n \/** === begin UNO using === **\/\n using ::com::sun::star::uno::Reference;\n using ::com::sun::star::sdbc::XConnection;\n using ::com::sun::star::sdbc::XConnection;\n using ::com::sun::star::sdbc::XDatabaseMetaData;\n using ::com::sun::star::sdbc::XDatabaseMetaData2;\n using ::com::sun::star::lang::IllegalArgumentException;\n using ::com::sun::star::uno::Exception;\n using ::com::sun::star::uno::Any;\n using ::com::sun::star::container::XChild;\n using ::com::sun::star::uno::UNO_QUERY_THROW;\n using ::com::sun::star::beans::XPropertySet;\n using ::com::sun::star::uno::Sequence;\n using ::com::sun::star::beans::PropertyValue;\n using ::com::sun::star::beans::XPropertySetInfo;\n using ::com::sun::star::uno::UNO_QUERY;\n using ::com::sun::star::sdbcx::XUsersSupplier;\n using ::com::sun::star::sdbcx::XDataDefinitionSupplier;\n using ::com::sun::star::sdbc::XDriverAccess;\n using ::com::sun::star::uno::UNO_SET_THROW;\n \/** === end UNO using === **\/\n namespace BooleanComparisonMode = ::com::sun::star::sdb::BooleanComparisonMode;\n\n \/\/====================================================================\n \/\/= DatabaseMetaData_Impl\n \/\/====================================================================\n struct DatabaseMetaData_Impl\n {\n Reference< XConnection > xConnection;\n Reference< XDatabaseMetaData > xConnectionMetaData;\n ::connectivity::DriversConfig aDriverConfig;\n\n ::boost::optional< ::rtl::OUString > sCachedIdentifierQuoteString;\n ::boost::optional< ::rtl::OUString > sCachedCatalogSeparator;\n\n DatabaseMetaData_Impl()\n :xConnection()\n ,xConnectionMetaData()\n ,aDriverConfig( ::comphelper::getProcessServiceFactory() )\n ,sCachedIdentifierQuoteString()\n ,sCachedCatalogSeparator()\n {\n }\n };\n\n \/\/--------------------------------------------------------------------\n namespace\n {\n \/\/................................................................\n static void lcl_construct( DatabaseMetaData_Impl& _metaDataImpl, const Reference< XConnection >& _connection )\n {\n _metaDataImpl.xConnection = _connection;\n if ( !_metaDataImpl.xConnection.is() )\n return;\n\n _metaDataImpl.xConnectionMetaData = _connection->getMetaData();\n if ( !_metaDataImpl.xConnectionMetaData.is() )\n throw IllegalArgumentException();\n }\n\n \/\/................................................................\n static void lcl_checkConnected( const DatabaseMetaData_Impl& _metaDataImpl )\n {\n if ( !_metaDataImpl.xConnection.is() || !_metaDataImpl.xConnectionMetaData.is() )\n {\n ::connectivity::SharedResources aResources;\n const ::rtl::OUString sError( aResources.getResourceString(STR_NO_CONNECTION_GIVEN));\n throwSQLException( sError, SQL_CONNECTION_DOES_NOT_EXIST, NULL );\n }\n }\n\n \/\/................................................................\n static bool lcl_getDriverSetting( const sal_Char* _asciiName, const DatabaseMetaData_Impl& _metaData, Any& _out_setting )\n {\n lcl_checkConnected( _metaData );\n const ::comphelper::NamedValueCollection& rDriverMetaData = _metaData.aDriverConfig.getMetaData( _metaData.xConnectionMetaData->getURL() );\n if ( !rDriverMetaData.has( _asciiName ) )\n return false;\n _out_setting = rDriverMetaData.get( _asciiName );\n return true;\n }\n\n \/\/................................................................\n static bool lcl_getConnectionSetting( const sal_Char* _asciiName, const DatabaseMetaData_Impl& _metaData, Any& _out_setting )\n {\n try\n {\n Reference< XChild > xConnectionAsChild( _metaData.xConnection, UNO_QUERY );\n if ( xConnectionAsChild.is() )\n {\n Reference< XPropertySet > xDataSource( xConnectionAsChild->getParent(), UNO_QUERY_THROW );\n Reference< XPropertySet > xDataSourceSettings(\n xDataSource->getPropertyValue( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( \"Settings\" ) ) ),\n UNO_QUERY_THROW );\n\n _out_setting = xDataSourceSettings->getPropertyValue( ::rtl::OUString::createFromAscii( _asciiName ) );\n }\n else\n {\n Reference< XDatabaseMetaData2 > xExtendedMetaData( _metaData.xConnectionMetaData, UNO_QUERY_THROW );\n ::comphelper::NamedValueCollection aSettings( xExtendedMetaData->getConnectionInfo() );\n _out_setting = aSettings.get( _asciiName );\n return _out_setting.hasValue();\n }\n return true;\n }\n catch( const Exception& )\n {\n DBG_UNHANDLED_EXCEPTION();\n }\n return false;\n }\n\n \/\/................................................................\n static const ::rtl::OUString& lcl_getConnectionStringSetting(\n const DatabaseMetaData_Impl& _metaData, ::boost::optional< ::rtl::OUString >& _cachedSetting,\n ::rtl::OUString (SAL_CALL XDatabaseMetaData::*_getter)() )\n {\n if ( !_cachedSetting )\n {\n lcl_checkConnected( _metaData );\n try\n {\n _cachedSetting.reset( (_metaData.xConnectionMetaData.get()->*_getter)() );\n }\n catch( const Exception& ) { DBG_UNHANDLED_EXCEPTION(); }\n }\n return *_cachedSetting;\n }\n }\n\n \/\/====================================================================\n \/\/= DatabaseMetaData\n \/\/====================================================================\n \/\/--------------------------------------------------------------------\n DatabaseMetaData::DatabaseMetaData()\n :m_pImpl( new DatabaseMetaData_Impl )\n {\n }\n\n \/\/--------------------------------------------------------------------\n DatabaseMetaData::DatabaseMetaData( const Reference< XConnection >& _connection )\n :m_pImpl( new DatabaseMetaData_Impl )\n {\n lcl_construct( *m_pImpl, _connection );\n }\n\n \/\/--------------------------------------------------------------------\n DatabaseMetaData::DatabaseMetaData( const DatabaseMetaData& _copyFrom )\n :m_pImpl( new DatabaseMetaData_Impl( *_copyFrom.m_pImpl ) )\n {\n }\n\n \/\/--------------------------------------------------------------------\n DatabaseMetaData& DatabaseMetaData::operator=( const DatabaseMetaData& _copyFrom )\n {\n if ( this == &_copyFrom )\n return *this;\n\n m_pImpl.reset( new DatabaseMetaData_Impl( *_copyFrom.m_pImpl ) );\n return *this;\n }\n\n \/\/--------------------------------------------------------------------\n DatabaseMetaData::~DatabaseMetaData()\n {\n }\n\n \/\/--------------------------------------------------------------------\n bool DatabaseMetaData::isConnected() const\n {\n return m_pImpl->xConnection.is();\n }\n\n \/\/--------------------------------------------------------------------\n bool DatabaseMetaData::supportsSubqueriesInFrom() const\n {\n lcl_checkConnected( *m_pImpl );\n\n bool supportsSubQueries = false;\n try\n {\n sal_Int32 maxTablesInselect = m_pImpl->xConnectionMetaData->getMaxTablesInSelect();\n supportsSubQueries = ( maxTablesInselect > 1 ) || ( maxTablesInselect == 0 );\n \/\/ TODO: is there a better way to determine this? The above is not really true. More precise,\n \/\/ it's a *very* generous heuristics ...\n }\n catch( const Exception& )\n {\n DBG_UNHANDLED_EXCEPTION();\n }\n return supportsSubQueries;\n }\n\n \/\/--------------------------------------------------------------------\n bool DatabaseMetaData::supportsPrimaryKeys() const\n {\n lcl_checkConnected( *m_pImpl );\n\n bool supportsPrimaryKeys = false;\n try\n {\n Any setting;\n if ( !( lcl_getConnectionSetting( \"PrimaryKeySupport\", *m_pImpl, setting ) )\n || !( setting >>= supportsPrimaryKeys )\n )\n supportsPrimaryKeys = m_pImpl->xConnectionMetaData->supportsCoreSQLGrammar();\n }\n catch( const Exception& )\n {\n DBG_UNHANDLED_EXCEPTION();\n }\n return supportsPrimaryKeys;\n }\n\n \/\/--------------------------------------------------------------------\n const ::rtl::OUString& DatabaseMetaData::getIdentifierQuoteString() const\n {\n return lcl_getConnectionStringSetting( *m_pImpl, m_pImpl->sCachedIdentifierQuoteString, &XDatabaseMetaData::getIdentifierQuoteString );\n }\n\n \/\/--------------------------------------------------------------------\n const ::rtl::OUString& DatabaseMetaData::getCatalogSeparator() const\n {\n return lcl_getConnectionStringSetting( *m_pImpl, m_pImpl->sCachedCatalogSeparator, &XDatabaseMetaData::getCatalogSeparator );\n }\n\n \/\/--------------------------------------------------------------------\n bool DatabaseMetaData::restrictIdentifiersToSQL92() const\n {\n lcl_checkConnected( *m_pImpl );\n\n bool restrict( false );\n Any setting;\n if ( lcl_getConnectionSetting( \"EnableSQL92Check\", *m_pImpl, setting ) )\n OSL_VERIFY( setting >>= restrict );\n return restrict;\n }\n\n \/\/--------------------------------------------------------------------\n bool DatabaseMetaData::generateASBeforeCorrelationName() const\n {\n bool doGenerate( true );\n Any setting;\n if ( lcl_getConnectionSetting( \"GenerateASBeforeCorrelationName\", *m_pImpl, setting ) )\n OSL_VERIFY( setting >>= doGenerate );\n return doGenerate;\n }\n \/\/--------------------------------------------------------------------\n bool DatabaseMetaData::shouldEscapeDateTime() const\n {\n bool doGenerate( true );\n Any setting;\n if ( lcl_getConnectionSetting( \"EscapeDateTime\", *m_pImpl, setting ) )\n OSL_VERIFY( setting >>= doGenerate );\n return doGenerate;\n }\n \/\/--------------------------------------------------------------------\n bool DatabaseMetaData::isAutoIncrementPrimaryKey() const\n {\n bool is( true );\n Any setting;\n if ( lcl_getDriverSetting( \"AutoIncrementIsPrimaryKey\", *m_pImpl, setting ) )\n OSL_VERIFY( setting >>= is );\n return is;\n }\n \/\/--------------------------------------------------------------------\n sal_Int32 DatabaseMetaData::getBooleanComparisonMode() const\n {\n sal_Int32 mode( BooleanComparisonMode::EQUAL_INTEGER );\n Any setting;\n if ( lcl_getConnectionSetting( \"BooleanComparisonMode\", *m_pImpl, setting ) )\n OSL_VERIFY( setting >>= mode );\n return mode;\n }\n \/\/--------------------------------------------------------------------\n bool DatabaseMetaData::supportsRelations() const\n {\n lcl_checkConnected( *m_pImpl );\n bool bSupport = false;\n try\n {\n bSupport = m_pImpl->xConnectionMetaData->supportsIntegrityEnhancementFacility();\n }\n catch( const Exception& )\n {\n DBG_UNHANDLED_EXCEPTION();\n }\n try\n {\n if ( !bSupport )\n {\n const ::rtl::OUString url = m_pImpl->xConnectionMetaData->getURL();\n char pMySQL[] = \"sdbc:mysql\";\n bSupport = url.matchAsciiL(pMySQL,(sizeof(pMySQL)\/sizeof(pMySQL[0]))-1);\n }\n }\n catch( const Exception& )\n {\n DBG_UNHANDLED_EXCEPTION();\n }\n return bSupport;\n }\n\n \/\/--------------------------------------------------------------------\n bool DatabaseMetaData::supportsColumnAliasInOrderBy() const\n {\n bool doGenerate( true );\n Any setting;\n if ( lcl_getConnectionSetting( \"ColumnAliasInOrderBy\", *m_pImpl, setting ) )\n OSL_VERIFY( setting >>= doGenerate );\n return doGenerate;\n }\n\n \/\/--------------------------------------------------------------------\n bool DatabaseMetaData::supportsUserAdministration( const ::comphelper::ComponentContext& _rContext ) const\n {\n lcl_checkConnected( *m_pImpl );\n\n bool isSupported( false );\n try\n {\n \/\/ find the XUsersSupplier interface\n \/\/ - either directly at the connection\n Reference< XUsersSupplier > xUsersSupp( m_pImpl->xConnection, UNO_QUERY );\n if ( !xUsersSupp.is() )\n {\n \/\/ - or at the driver manager\n Reference< XDriverAccess > xDriverManager(\n _rContext.createComponent( \"com.sun.star.sdbc.DriverManager\" ), UNO_QUERY_THROW );\n Reference< XDataDefinitionSupplier > xDriver( xDriverManager->getDriverByURL( m_pImpl->xConnectionMetaData->getURL() ), UNO_QUERY );\n if ( xDriver.is() )\n xUsersSupp.set( xDriver->getDataDefinitionByConnection( m_pImpl->xConnection ), UNO_QUERY );\n }\n\n isSupported = ( xUsersSupp.is() && xUsersSupp->getUsers().is() );\n }\n catch( const Exception& )\n {\n DBG_UNHANDLED_EXCEPTION();\n }\n return isSupported;\n }\n\n \/\/--------------------------------------------------------------------\n bool DatabaseMetaData::displayEmptyTableFolders() const\n {\n bool doDisplay( true );\n#ifdef IMPLEMENTED_LATER\n Any setting;\n if ( lcl_getConnectionSetting( \"DisplayEmptyTableFolders\", *m_pImpl, setting ) )\n OSL_VERIFY( setting >>= doDisplay );\n#else\n try\n {\n Reference< XDatabaseMetaData > xMeta( m_pImpl->xConnectionMetaData, UNO_SET_THROW );\n ::rtl::OUString sConnectionURL( xMeta->getURL() );\n doDisplay = sConnectionURL.compareToAscii( RTL_CONSTASCII_STRINGPARAM( \"sdbc:mysql:mysqlc\" ) ) == 0;\n }\n catch( const Exception& )\n {\n DBG_UNHANDLED_EXCEPTION();\n }\n#endif\n return doDisplay;\n }\n\n\/\/........................................................................\n} \/\/ namespace dbtools\n\/\/........................................................................\n\n<commit_msg>#i10000#<commit_after>\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2008 by Sun Microsystems, Inc.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: dbmetadata.cxx,v $\n * $Revision: 1.10.22.1 $\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * <http:\/\/www.openoffice.org\/license.html>\n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_connectivity.hxx\"\n\n#include \"connectivity\/dbmetadata.hxx\"\n#include \"connectivity\/dbexception.hxx\"\n#include \"connectivity\/DriversConfig.hxx\"\n#include \"resource\/common_res.hrc\"\n#include \"resource\/sharedresources.hxx\"\n\n\/** === begin UNO includes === **\/\n#include <com\/sun\/star\/lang\/IllegalArgumentException.hpp>\n#include <com\/sun\/star\/container\/XChild.hpp>\n#include <com\/sun\/star\/beans\/XPropertySet.hpp>\n#include <com\/sun\/star\/beans\/PropertyValue.hpp>\n#include <com\/sun\/star\/beans\/XPropertySetInfo.hpp>\n#include <com\/sun\/star\/sdb\/BooleanComparisonMode.hpp>\n#include <com\/sun\/star\/sdbc\/XDatabaseMetaData2.hpp>\n#include <com\/sun\/star\/sdbcx\/XUsersSupplier.hpp>\n#include <com\/sun\/star\/sdbcx\/XDataDefinitionSupplier.hpp>\n#include <com\/sun\/star\/sdbc\/XDriverAccess.hpp>\n\/** === end UNO includes === **\/\n\n#include <tools\/diagnose_ex.h>\n#include <comphelper\/namedvaluecollection.hxx>\n#include <comphelper\/componentcontext.hxx>\n#include <comphelper\/processfactory.hxx>\n\n#include <boost\/optional.hpp>\n\n\/\/........................................................................\nnamespace dbtools\n{\n\/\/........................................................................\n\n \/** === begin UNO using === **\/\n using ::com::sun::star::uno::Reference;\n using ::com::sun::star::sdbc::XConnection;\n using ::com::sun::star::sdbc::XConnection;\n using ::com::sun::star::sdbc::XDatabaseMetaData;\n using ::com::sun::star::sdbc::XDatabaseMetaData2;\n using ::com::sun::star::lang::IllegalArgumentException;\n using ::com::sun::star::uno::Exception;\n using ::com::sun::star::uno::Any;\n using ::com::sun::star::container::XChild;\n using ::com::sun::star::uno::UNO_QUERY_THROW;\n using ::com::sun::star::beans::XPropertySet;\n using ::com::sun::star::uno::Sequence;\n using ::com::sun::star::beans::PropertyValue;\n using ::com::sun::star::beans::XPropertySetInfo;\n using ::com::sun::star::uno::UNO_QUERY;\n using ::com::sun::star::sdbcx::XUsersSupplier;\n using ::com::sun::star::sdbcx::XDataDefinitionSupplier;\n using ::com::sun::star::sdbc::XDriverAccess;\n using ::com::sun::star::uno::UNO_SET_THROW;\n \/** === end UNO using === **\/\n namespace BooleanComparisonMode = ::com::sun::star::sdb::BooleanComparisonMode;\n\n \/\/====================================================================\n \/\/= DatabaseMetaData_Impl\n \/\/====================================================================\n struct DatabaseMetaData_Impl\n {\n Reference< XConnection > xConnection;\n Reference< XDatabaseMetaData > xConnectionMetaData;\n ::connectivity::DriversConfig aDriverConfig;\n\n ::boost::optional< ::rtl::OUString > sCachedIdentifierQuoteString;\n ::boost::optional< ::rtl::OUString > sCachedCatalogSeparator;\n\n DatabaseMetaData_Impl()\n :xConnection()\n ,xConnectionMetaData()\n ,aDriverConfig( ::comphelper::getProcessServiceFactory() )\n ,sCachedIdentifierQuoteString()\n ,sCachedCatalogSeparator()\n {\n }\n };\n\n \/\/--------------------------------------------------------------------\n namespace\n {\n \/\/................................................................\n static void lcl_construct( DatabaseMetaData_Impl& _metaDataImpl, const Reference< XConnection >& _connection )\n {\n _metaDataImpl.xConnection = _connection;\n if ( !_metaDataImpl.xConnection.is() )\n return;\n\n _metaDataImpl.xConnectionMetaData = _connection->getMetaData();\n if ( !_metaDataImpl.xConnectionMetaData.is() )\n throw IllegalArgumentException();\n }\n\n \/\/................................................................\n static void lcl_checkConnected( const DatabaseMetaData_Impl& _metaDataImpl )\n {\n if ( !_metaDataImpl.xConnection.is() || !_metaDataImpl.xConnectionMetaData.is() )\n {\n ::connectivity::SharedResources aResources;\n const ::rtl::OUString sError( aResources.getResourceString(STR_NO_CONNECTION_GIVEN));\n throwSQLException( sError, SQL_CONNECTION_DOES_NOT_EXIST, NULL );\n }\n }\n\n \/\/................................................................\n static bool lcl_getDriverSetting( const sal_Char* _asciiName, const DatabaseMetaData_Impl& _metaData, Any& _out_setting )\n {\n lcl_checkConnected( _metaData );\n const ::comphelper::NamedValueCollection& rDriverMetaData = _metaData.aDriverConfig.getMetaData( _metaData.xConnectionMetaData->getURL() );\n if ( !rDriverMetaData.has( _asciiName ) )\n return false;\n _out_setting = rDriverMetaData.get( _asciiName );\n return true;\n }\n\n \/\/................................................................\n static bool lcl_getConnectionSetting( const sal_Char* _asciiName, const DatabaseMetaData_Impl& _metaData, Any& _out_setting )\n {\n try\n {\n Reference< XChild > xConnectionAsChild( _metaData.xConnection, UNO_QUERY );\n if ( xConnectionAsChild.is() )\n {\n Reference< XPropertySet > xDataSource( xConnectionAsChild->getParent(), UNO_QUERY_THROW );\n Reference< XPropertySet > xDataSourceSettings(\n xDataSource->getPropertyValue( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( \"Settings\" ) ) ),\n UNO_QUERY_THROW );\n\n _out_setting = xDataSourceSettings->getPropertyValue( ::rtl::OUString::createFromAscii( _asciiName ) );\n }\n else\n {\n Reference< XDatabaseMetaData2 > xExtendedMetaData( _metaData.xConnectionMetaData, UNO_QUERY_THROW );\n ::comphelper::NamedValueCollection aSettings( xExtendedMetaData->getConnectionInfo() );\n _out_setting = aSettings.get( _asciiName );\n return _out_setting.hasValue();\n }\n return true;\n }\n catch( const Exception& )\n {\n DBG_UNHANDLED_EXCEPTION();\n }\n return false;\n }\n\n \/\/................................................................\n static const ::rtl::OUString& lcl_getConnectionStringSetting(\n const DatabaseMetaData_Impl& _metaData, ::boost::optional< ::rtl::OUString >& _cachedSetting,\n ::rtl::OUString (SAL_CALL XDatabaseMetaData::*_getter)() )\n {\n if ( !_cachedSetting )\n {\n lcl_checkConnected( _metaData );\n try\n {\n _cachedSetting.reset( (_metaData.xConnectionMetaData.get()->*_getter)() );\n }\n catch( const Exception& ) { DBG_UNHANDLED_EXCEPTION(); }\n }\n return *_cachedSetting;\n }\n }\n\n \/\/====================================================================\n \/\/= DatabaseMetaData\n \/\/====================================================================\n \/\/--------------------------------------------------------------------\n DatabaseMetaData::DatabaseMetaData()\n :m_pImpl( new DatabaseMetaData_Impl )\n {\n }\n\n \/\/--------------------------------------------------------------------\n DatabaseMetaData::DatabaseMetaData( const Reference< XConnection >& _connection )\n :m_pImpl( new DatabaseMetaData_Impl )\n {\n lcl_construct( *m_pImpl, _connection );\n }\n\n \/\/--------------------------------------------------------------------\n DatabaseMetaData::DatabaseMetaData( const DatabaseMetaData& _copyFrom )\n :m_pImpl( new DatabaseMetaData_Impl( *_copyFrom.m_pImpl ) )\n {\n }\n\n \/\/--------------------------------------------------------------------\n DatabaseMetaData& DatabaseMetaData::operator=( const DatabaseMetaData& _copyFrom )\n {\n if ( this == &_copyFrom )\n return *this;\n\n m_pImpl.reset( new DatabaseMetaData_Impl( *_copyFrom.m_pImpl ) );\n return *this;\n }\n\n \/\/--------------------------------------------------------------------\n DatabaseMetaData::~DatabaseMetaData()\n {\n }\n\n \/\/--------------------------------------------------------------------\n bool DatabaseMetaData::isConnected() const\n {\n return m_pImpl->xConnection.is();\n }\n\n \/\/--------------------------------------------------------------------\n bool DatabaseMetaData::supportsSubqueriesInFrom() const\n {\n lcl_checkConnected( *m_pImpl );\n\n bool supportsSubQueries = false;\n try\n {\n sal_Int32 maxTablesInselect = m_pImpl->xConnectionMetaData->getMaxTablesInSelect();\n supportsSubQueries = ( maxTablesInselect > 1 ) || ( maxTablesInselect == 0 );\n \/\/ TODO: is there a better way to determine this? The above is not really true. More precise,\n \/\/ it's a *very* generous heuristics ...\n }\n catch( const Exception& )\n {\n DBG_UNHANDLED_EXCEPTION();\n }\n return supportsSubQueries;\n }\n\n \/\/--------------------------------------------------------------------\n bool DatabaseMetaData::supportsPrimaryKeys() const\n {\n lcl_checkConnected( *m_pImpl );\n\n bool doesSupportPrimaryKeys = false;\n try\n {\n Any setting;\n if ( !( lcl_getConnectionSetting( \"PrimaryKeySupport\", *m_pImpl, setting ) )\n || !( setting >>= doesSupportPrimaryKeys )\n )\n doesSupportPrimaryKeys = m_pImpl->xConnectionMetaData->supportsCoreSQLGrammar();\n }\n catch( const Exception& )\n {\n DBG_UNHANDLED_EXCEPTION();\n }\n return doesSupportPrimaryKeys;\n }\n\n \/\/--------------------------------------------------------------------\n const ::rtl::OUString& DatabaseMetaData::getIdentifierQuoteString() const\n {\n return lcl_getConnectionStringSetting( *m_pImpl, m_pImpl->sCachedIdentifierQuoteString, &XDatabaseMetaData::getIdentifierQuoteString );\n }\n\n \/\/--------------------------------------------------------------------\n const ::rtl::OUString& DatabaseMetaData::getCatalogSeparator() const\n {\n return lcl_getConnectionStringSetting( *m_pImpl, m_pImpl->sCachedCatalogSeparator, &XDatabaseMetaData::getCatalogSeparator );\n }\n\n \/\/--------------------------------------------------------------------\n bool DatabaseMetaData::restrictIdentifiersToSQL92() const\n {\n lcl_checkConnected( *m_pImpl );\n\n bool restrict( false );\n Any setting;\n if ( lcl_getConnectionSetting( \"EnableSQL92Check\", *m_pImpl, setting ) )\n OSL_VERIFY( setting >>= restrict );\n return restrict;\n }\n\n \/\/--------------------------------------------------------------------\n bool DatabaseMetaData::generateASBeforeCorrelationName() const\n {\n bool doGenerate( true );\n Any setting;\n if ( lcl_getConnectionSetting( \"GenerateASBeforeCorrelationName\", *m_pImpl, setting ) )\n OSL_VERIFY( setting >>= doGenerate );\n return doGenerate;\n }\n \/\/--------------------------------------------------------------------\n bool DatabaseMetaData::shouldEscapeDateTime() const\n {\n bool doGenerate( true );\n Any setting;\n if ( lcl_getConnectionSetting( \"EscapeDateTime\", *m_pImpl, setting ) )\n OSL_VERIFY( setting >>= doGenerate );\n return doGenerate;\n }\n \/\/--------------------------------------------------------------------\n bool DatabaseMetaData::isAutoIncrementPrimaryKey() const\n {\n bool is( true );\n Any setting;\n if ( lcl_getDriverSetting( \"AutoIncrementIsPrimaryKey\", *m_pImpl, setting ) )\n OSL_VERIFY( setting >>= is );\n return is;\n }\n \/\/--------------------------------------------------------------------\n sal_Int32 DatabaseMetaData::getBooleanComparisonMode() const\n {\n sal_Int32 mode( BooleanComparisonMode::EQUAL_INTEGER );\n Any setting;\n if ( lcl_getConnectionSetting( \"BooleanComparisonMode\", *m_pImpl, setting ) )\n OSL_VERIFY( setting >>= mode );\n return mode;\n }\n \/\/--------------------------------------------------------------------\n bool DatabaseMetaData::supportsRelations() const\n {\n lcl_checkConnected( *m_pImpl );\n bool bSupport = false;\n try\n {\n bSupport = m_pImpl->xConnectionMetaData->supportsIntegrityEnhancementFacility();\n }\n catch( const Exception& )\n {\n DBG_UNHANDLED_EXCEPTION();\n }\n try\n {\n if ( !bSupport )\n {\n const ::rtl::OUString url = m_pImpl->xConnectionMetaData->getURL();\n char pMySQL[] = \"sdbc:mysql\";\n bSupport = url.matchAsciiL(pMySQL,(sizeof(pMySQL)\/sizeof(pMySQL[0]))-1);\n }\n }\n catch( const Exception& )\n {\n DBG_UNHANDLED_EXCEPTION();\n }\n return bSupport;\n }\n\n \/\/--------------------------------------------------------------------\n bool DatabaseMetaData::supportsColumnAliasInOrderBy() const\n {\n bool doGenerate( true );\n Any setting;\n if ( lcl_getConnectionSetting( \"ColumnAliasInOrderBy\", *m_pImpl, setting ) )\n OSL_VERIFY( setting >>= doGenerate );\n return doGenerate;\n }\n\n \/\/--------------------------------------------------------------------\n bool DatabaseMetaData::supportsUserAdministration( const ::comphelper::ComponentContext& _rContext ) const\n {\n lcl_checkConnected( *m_pImpl );\n\n bool isSupported( false );\n try\n {\n \/\/ find the XUsersSupplier interface\n \/\/ - either directly at the connection\n Reference< XUsersSupplier > xUsersSupp( m_pImpl->xConnection, UNO_QUERY );\n if ( !xUsersSupp.is() )\n {\n \/\/ - or at the driver manager\n Reference< XDriverAccess > xDriverManager(\n _rContext.createComponent( \"com.sun.star.sdbc.DriverManager\" ), UNO_QUERY_THROW );\n Reference< XDataDefinitionSupplier > xDriver( xDriverManager->getDriverByURL( m_pImpl->xConnectionMetaData->getURL() ), UNO_QUERY );\n if ( xDriver.is() )\n xUsersSupp.set( xDriver->getDataDefinitionByConnection( m_pImpl->xConnection ), UNO_QUERY );\n }\n\n isSupported = ( xUsersSupp.is() && xUsersSupp->getUsers().is() );\n }\n catch( const Exception& )\n {\n DBG_UNHANDLED_EXCEPTION();\n }\n return isSupported;\n }\n\n \/\/--------------------------------------------------------------------\n bool DatabaseMetaData::displayEmptyTableFolders() const\n {\n bool doDisplay( true );\n#ifdef IMPLEMENTED_LATER\n Any setting;\n if ( lcl_getConnectionSetting( \"DisplayEmptyTableFolders\", *m_pImpl, setting ) )\n OSL_VERIFY( setting >>= doDisplay );\n#else\n try\n {\n Reference< XDatabaseMetaData > xMeta( m_pImpl->xConnectionMetaData, UNO_SET_THROW );\n ::rtl::OUString sConnectionURL( xMeta->getURL() );\n doDisplay = sConnectionURL.compareToAscii( RTL_CONSTASCII_STRINGPARAM( \"sdbc:mysql:mysqlc\" ) ) == 0;\n }\n catch( const Exception& )\n {\n DBG_UNHANDLED_EXCEPTION();\n }\n#endif\n return doDisplay;\n }\n\n\/\/........................................................................\n} \/\/ namespace dbtools\n\/\/........................................................................\n\n<|endoftext|>"} {"text":"<commit_before>\n#include \"common_headers.h\"\n\n#include \"parser\/token.h\"\n#include \"parser\/token_stream.h\"\n#include \"bootstrapping.h\"\n#include \"branch.h\"\n#include \"builtin_functions.h\"\n#include \"errors.h\"\n#include \"function.h\"\n#include \"operations.h\"\n#include \"structs.h\"\n#include \"subroutine.h\"\n#include \"term.h\"\n#include \"type.h\"\n\nBranch* KERNEL = NULL;\nTerm* BUILTIN_INT_TYPE = NULL;\nTerm* BUILTIN_FLOAT_TYPE = NULL;\nTerm* BUILTIN_BOOL_TYPE = NULL;\nTerm* BUILTIN_STRING_TYPE = NULL;\nTerm* BUILTIN_TYPE_TYPE = NULL;\nTerm* BUILTIN_FUNCTION_TYPE = NULL;\nTerm* BUILTIN_CODEUNIT_TYPE = NULL;\nTerm* BUILTIN_SUBROUTINE_TYPE = NULL;\nTerm* BUILTIN_STRUCT_DEFINITION_TYPE = NULL;\nTerm* BUILTIN_BRANCH_TYPE = NULL;\nTerm* BUILTIN_ANY_TYPE = NULL;\nTerm* BUILTIN_VOID_TYPE = NULL;\nTerm* BUILTIN_REFERENCE_TYPE = NULL;\nTerm* BUILTIN_LIST_TYPE = NULL;\n\nvoid empty_execute_function(Term*) { }\nvoid empty_alloc_function(Term*) { }\n\nvoid const_generator(Term* caller)\n{\n Function *output = as_function(caller);\n Type* type = as_type(caller->inputs[0]);\n output->name = \"const-\" + type->name;\n output->outputType = caller->inputs[0];\n output->execute = empty_execute_function;\n}\n\nTerm* get_global(string name)\n{\n if (KERNEL->containsName(name))\n return KERNEL->getNamed(name);\n\n throw errors::KeyError(name);\n}\n\n\nvoid bootstrap_kernel()\n{\n KERNEL = new Branch();\n\n \/\/ Create const-generator function\n Term* constGenerator = new Term();\n Function_alloc(constGenerator);\n Function_setName(constGenerator, \"const-generator\");\n Function_setPureFunction(constGenerator, true);\n Function_setExecute(constGenerator, const_generator);\n KERNEL->bindName(constGenerator, \"const-generator\");\n\n \/\/ Create const-Type function\n Term* constTypeFunc = new Term();\n constTypeFunc->function = constGenerator;\n Function_alloc(constTypeFunc);\n Function_setName(constTypeFunc, \"const-Type\");\n Function_setPureFunction(constTypeFunc, true);\n\n \/\/ Create Type type\n Term* typeType = new Term;\n BUILTIN_TYPE_TYPE = typeType;\n typeType->function = constTypeFunc;\n typeType->type = typeType;\n Type_alloc(typeType);\n as_type(typeType)->name = \"Type\";\n as_type(typeType)->alloc = Type_alloc;\n KERNEL->bindName(typeType, \"Type\");\n\n \/\/ Implant the Type type\n set_input(constTypeFunc, 0, typeType);\n Function_setInputType(constGenerator, 0, typeType);\n Function_setOutputType(constTypeFunc, typeType);\n\n \/\/ Create const-Function function\n Term* constFuncFunc = new Term;\n constFuncFunc->function = constGenerator;\n Function_alloc(constFuncFunc);\n Function_setName (constFuncFunc, \"const-Function\");\n Function_setPureFunction(constFuncFunc, true);\n KERNEL->bindName(constFuncFunc, \"const-Function\");\n\n \/\/ Implant const-Function\n constGenerator->function = constFuncFunc;\n\n \/\/ Create Function type\n Term* functionType = new Term;\n BUILTIN_FUNCTION_TYPE = functionType;\n functionType->function = constTypeFunc;\n functionType->type = typeType;\n Type_alloc(functionType);\n as_type(functionType)->name = \"Function\";\n as_type(functionType)->alloc = Function_alloc;\n KERNEL->bindName(functionType, \"Function\");\n\n \/\/ Implant Function type\n set_input(constGenerator, 0, typeType);\n set_input(constFuncFunc, 0, functionType);\n constGenerator->type = functionType;\n constFuncFunc->type = functionType;\n constTypeFunc->type = functionType;\n Function_setOutputType(constGenerator, functionType);\n Function_setOutputType(constFuncFunc, functionType);\n\n \/\/ Don't let these terms get updated\n constGenerator->needsUpdate = false;\n constFuncFunc->needsUpdate = false;\n constTypeFunc->needsUpdate = false;\n functionType->needsUpdate = false;\n typeType->needsUpdate = false;\n}\n\nvoid int_alloc(Term* caller)\n{\n caller->value = new int;\n}\nvoid int_copy(Term* source, Term* dest)\n{\n as_int(dest) = as_int(source);\n}\n\nvoid float_alloc(Term* caller)\n{\n caller->value = new float;\n}\nvoid float_copy(Term* source, Term* dest)\n{\n as_float(dest) = as_float(source);\n}\n\nvoid string_alloc(Term* caller)\n{\n caller->value = new string;\n}\n\nvoid bool_alloc(Term* caller)\n{\n caller->value = new bool;\n}\n\nvoid int_tostring(Term* caller)\n{\n std::stringstream strm;\n strm << as_int(caller->inputs[0]);\n as_string(caller) = strm.str();\n}\nvoid float_tostring(Term* caller)\n{\n std::stringstream strm;\n strm << as_float(caller->inputs[0]);\n as_string(caller) = strm.str();\n}\nvoid string_tostring(Term* caller)\n{\n as_string(caller) = as_string(caller->inputs[0]);\n}\n\nvoid bool_tostring(Term* caller)\n{\n if (as_bool(caller))\n as_string(caller) = \"true\";\n else\n as_string(caller) = \"false\";\n}\n\nvoid create_builtin_types()\n{\n BUILTIN_STRING_TYPE = quick_create_type(KERNEL, \"string\", string_alloc, string_tostring);\n BUILTIN_INT_TYPE = quick_create_type(KERNEL, \"int\",\n int_alloc, int_tostring, int_copy);\n BUILTIN_FLOAT_TYPE = quick_create_type(KERNEL, \"float\",\n float_alloc, float_tostring, float_copy);\n BUILTIN_BOOL_TYPE = quick_create_type(KERNEL, \"bool\", bool_alloc, bool_tostring);\n BUILTIN_ANY_TYPE = quick_create_type(KERNEL, \"any\", empty_alloc_function, NULL);\n BUILTIN_VOID_TYPE = quick_create_type(KERNEL, \"void\", empty_alloc_function, NULL);\n BUILTIN_REFERENCE_TYPE = quick_create_type(KERNEL, \"Reference\", empty_alloc_function, NULL);\n}\n\nvoid initialize()\n{\n try {\n bootstrap_kernel();\n create_builtin_types();\n\n \/\/ Do initialize_term first\n initialize_term(KERNEL);\n\n initialize_branch(KERNEL);\n initialize_builtin_functions(KERNEL);\n initialize_structs(KERNEL);\n initialize_subroutine(KERNEL);\n\n } catch (errors::CircaError& e)\n {\n std::cout << \"An error occured while initializing.\" << std::endl;\n std::cout << e.message() << std::endl;\n exit(1);\n }\n}\n<commit_msg>Added string_copy<commit_after>\n#include \"common_headers.h\"\n\n#include \"parser\/token.h\"\n#include \"parser\/token_stream.h\"\n#include \"bootstrapping.h\"\n#include \"branch.h\"\n#include \"builtin_functions.h\"\n#include \"errors.h\"\n#include \"function.h\"\n#include \"operations.h\"\n#include \"structs.h\"\n#include \"subroutine.h\"\n#include \"term.h\"\n#include \"type.h\"\n\nBranch* KERNEL = NULL;\nTerm* BUILTIN_INT_TYPE = NULL;\nTerm* BUILTIN_FLOAT_TYPE = NULL;\nTerm* BUILTIN_BOOL_TYPE = NULL;\nTerm* BUILTIN_STRING_TYPE = NULL;\nTerm* BUILTIN_TYPE_TYPE = NULL;\nTerm* BUILTIN_FUNCTION_TYPE = NULL;\nTerm* BUILTIN_CODEUNIT_TYPE = NULL;\nTerm* BUILTIN_SUBROUTINE_TYPE = NULL;\nTerm* BUILTIN_STRUCT_DEFINITION_TYPE = NULL;\nTerm* BUILTIN_BRANCH_TYPE = NULL;\nTerm* BUILTIN_ANY_TYPE = NULL;\nTerm* BUILTIN_VOID_TYPE = NULL;\nTerm* BUILTIN_REFERENCE_TYPE = NULL;\nTerm* BUILTIN_LIST_TYPE = NULL;\n\nvoid empty_execute_function(Term*) { }\nvoid empty_alloc_function(Term*) { }\n\nvoid const_generator(Term* caller)\n{\n Function *output = as_function(caller);\n Type* type = as_type(caller->inputs[0]);\n output->name = \"const-\" + type->name;\n output->outputType = caller->inputs[0];\n output->execute = empty_execute_function;\n}\n\nTerm* get_global(string name)\n{\n if (KERNEL->containsName(name))\n return KERNEL->getNamed(name);\n\n throw errors::KeyError(name);\n}\n\n\nvoid bootstrap_kernel()\n{\n KERNEL = new Branch();\n\n \/\/ Create const-generator function\n Term* constGenerator = new Term();\n Function_alloc(constGenerator);\n Function_setName(constGenerator, \"const-generator\");\n Function_setPureFunction(constGenerator, true);\n Function_setExecute(constGenerator, const_generator);\n KERNEL->bindName(constGenerator, \"const-generator\");\n\n \/\/ Create const-Type function\n Term* constTypeFunc = new Term();\n constTypeFunc->function = constGenerator;\n Function_alloc(constTypeFunc);\n Function_setName(constTypeFunc, \"const-Type\");\n Function_setPureFunction(constTypeFunc, true);\n\n \/\/ Create Type type\n Term* typeType = new Term;\n BUILTIN_TYPE_TYPE = typeType;\n typeType->function = constTypeFunc;\n typeType->type = typeType;\n Type_alloc(typeType);\n as_type(typeType)->name = \"Type\";\n as_type(typeType)->alloc = Type_alloc;\n KERNEL->bindName(typeType, \"Type\");\n\n \/\/ Implant the Type type\n set_input(constTypeFunc, 0, typeType);\n Function_setInputType(constGenerator, 0, typeType);\n Function_setOutputType(constTypeFunc, typeType);\n\n \/\/ Create const-Function function\n Term* constFuncFunc = new Term;\n constFuncFunc->function = constGenerator;\n Function_alloc(constFuncFunc);\n Function_setName (constFuncFunc, \"const-Function\");\n Function_setPureFunction(constFuncFunc, true);\n KERNEL->bindName(constFuncFunc, \"const-Function\");\n\n \/\/ Implant const-Function\n constGenerator->function = constFuncFunc;\n\n \/\/ Create Function type\n Term* functionType = new Term;\n BUILTIN_FUNCTION_TYPE = functionType;\n functionType->function = constTypeFunc;\n functionType->type = typeType;\n Type_alloc(functionType);\n as_type(functionType)->name = \"Function\";\n as_type(functionType)->alloc = Function_alloc;\n KERNEL->bindName(functionType, \"Function\");\n\n \/\/ Implant Function type\n set_input(constGenerator, 0, typeType);\n set_input(constFuncFunc, 0, functionType);\n constGenerator->type = functionType;\n constFuncFunc->type = functionType;\n constTypeFunc->type = functionType;\n Function_setOutputType(constGenerator, functionType);\n Function_setOutputType(constFuncFunc, functionType);\n\n \/\/ Don't let these terms get updated\n constGenerator->needsUpdate = false;\n constFuncFunc->needsUpdate = false;\n constTypeFunc->needsUpdate = false;\n functionType->needsUpdate = false;\n typeType->needsUpdate = false;\n}\n\nvoid int_alloc(Term* caller)\n{\n caller->value = new int;\n}\nvoid int_copy(Term* source, Term* dest)\n{\n as_int(dest) = as_int(source);\n}\n\nvoid float_alloc(Term* caller)\n{\n caller->value = new float;\n}\nvoid float_copy(Term* source, Term* dest)\n{\n as_float(dest) = as_float(source);\n}\n\nvoid string_alloc(Term* caller)\n{\n caller->value = new string;\n}\n\nvoid bool_alloc(Term* caller)\n{\n caller->value = new bool;\n}\n\nvoid int_tostring(Term* caller)\n{\n std::stringstream strm;\n strm << as_int(caller->inputs[0]);\n as_string(caller) = strm.str();\n}\nvoid float_tostring(Term* caller)\n{\n std::stringstream strm;\n strm << as_float(caller->inputs[0]);\n as_string(caller) = strm.str();\n}\nvoid string_tostring(Term* caller)\n{\n as_string(caller) = as_string(caller->inputs[0]);\n}\nvoid string_copy(Term* source, Term* dest)\n{\n as_string(dest) = as_string(source);\n}\n\nvoid bool_tostring(Term* caller)\n{\n if (as_bool(caller))\n as_string(caller) = \"true\";\n else\n as_string(caller) = \"false\";\n}\n\nvoid create_builtin_types()\n{\n BUILTIN_STRING_TYPE = quick_create_type(KERNEL, \"string\",\n string_alloc, string_tostring, string_copy);\n BUILTIN_INT_TYPE = quick_create_type(KERNEL, \"int\",\n int_alloc, int_tostring, int_copy);\n BUILTIN_FLOAT_TYPE = quick_create_type(KERNEL, \"float\",\n float_alloc, float_tostring, float_copy);\n BUILTIN_BOOL_TYPE = quick_create_type(KERNEL, \"bool\", bool_alloc, bool_tostring);\n BUILTIN_ANY_TYPE = quick_create_type(KERNEL, \"any\", empty_alloc_function, NULL);\n BUILTIN_VOID_TYPE = quick_create_type(KERNEL, \"void\", empty_alloc_function, NULL);\n BUILTIN_REFERENCE_TYPE = quick_create_type(KERNEL, \"Reference\", empty_alloc_function, NULL);\n}\n\nvoid initialize()\n{\n try {\n bootstrap_kernel();\n create_builtin_types();\n\n \/\/ Do initialize_term first\n initialize_term(KERNEL);\n\n initialize_branch(KERNEL);\n initialize_builtin_functions(KERNEL);\n initialize_structs(KERNEL);\n initialize_subroutine(KERNEL);\n\n } catch (errors::CircaError& e)\n {\n std::cout << \"An error occured while initializing.\" << std::endl;\n std::cout << e.message() << std::endl;\n exit(1);\n }\n}\n<|endoftext|>"} {"text":"<commit_before>#pragma once\nnamespace mtao::geometry {\n template <typename PDerived, typename VDerived, typename BeginIt, typename EndIt>\n typename VDerived::Scalar winding_number(const Eigen::MatrixBase<VDerived>& V, const BeginIt& beginit, const EndIt& endit, const Eigen::MatrixBase<PDerived>& p) {\n using S = typename VDerived::Scalar;\n S value = 0;\n auto it = beginit;\n for(; it != endit; ++it) {\n auto it1 = it;\n it1++;\n if(it1 == endit) { it1 = beginit; }\n\n auto a = V.col(*it) - p;\n auto b = V.col(*it1) - p;\n S aa = std::atan2(a.y(),a.x());\n S ba = std::atan2(b.y(),b.x());\n S ang = ba - aa;\n if(ang > M_PI) {\n ang -= 2 * M_PI;\n } else if(ang <= -M_PI) {\n ang += 2*M_PI;\n }\n value += ang;\n\n }\n return value;\n }\n template <typename PDerived, typename VDerived, typename Container>\n typename VDerived::Scalar winding_number(const Eigen::MatrixBase<VDerived>& V, const Container& C, const Eigen::MatrixBase<PDerived>& p) {\n return winding_number(V,C.begin(),C.end(),p);\n }\n template <typename PDerived, typename VDerived>\n typename VDerived::Scalar winding_number(const Eigen::MatrixBase<VDerived>& V, const std::initializer_list<int>& C, const Eigen::MatrixBase<PDerived>& p) {\n return winding_number(V,C.begin(),C.end(),p);\n }\n template <typename PDerived, typename VDerived, typename BeginIt, typename EndIt>\n bool interior_winding_number(const Eigen::MatrixBase<VDerived>& V, const BeginIt& beginit, const EndIt& endit, const Eigen::MatrixBase<PDerived>& p) {\n return winding_number(V,beginit,endit,p) > 1;\n }\n template <typename PDerived, typename VDerived, typename Container>\n bool interior_winding_number(const Eigen::MatrixBase<VDerived>& V, const Container& C, const Eigen::MatrixBase<PDerived>& p) {\n return interior_winding_number(V,C.begin(),C.end(),p);\n }\n template <typename PDerived, typename VDerived>\n bool interior_winding_number(const Eigen::MatrixBase<VDerived>& V, const std::initializer_list<int>& C, const Eigen::MatrixBase<PDerived>& p) {\n return interior_winding_number(V,C.begin(),C.end(),p);\n }\n}\n<commit_msg>winding number checks for M_PI isntead of just hoping for >1<commit_after>#pragma once\nnamespace mtao::geometry {\n template <typename PDerived, typename VDerived, typename BeginIt, typename EndIt>\n typename VDerived::Scalar winding_number(const Eigen::MatrixBase<VDerived>& V, const BeginIt& beginit, const EndIt& endit, const Eigen::MatrixBase<PDerived>& p) {\n using S = typename VDerived::Scalar;\n S value = 0;\n auto it = beginit;\n for(; it != endit; ++it) {\n auto it1 = it;\n it1++;\n if(it1 == endit) { it1 = beginit; }\n\n auto a = V.col(*it) - p;\n auto b = V.col(*it1) - p;\n S aa = std::atan2(a.y(),a.x());\n S ba = std::atan2(b.y(),b.x());\n S ang = ba - aa;\n if(ang > M_PI) {\n ang -= 2 * M_PI;\n } else if(ang <= -M_PI) {\n ang += 2*M_PI;\n }\n value += ang;\n\n }\n return value;\n }\n template <typename PDerived, typename VDerived, typename Container>\n typename VDerived::Scalar winding_number(const Eigen::MatrixBase<VDerived>& V, const Container& C, const Eigen::MatrixBase<PDerived>& p) {\n return winding_number(V,C.begin(),C.end(),p);\n }\n template <typename PDerived, typename VDerived>\n typename VDerived::Scalar winding_number(const Eigen::MatrixBase<VDerived>& V, const std::initializer_list<int>& C, const Eigen::MatrixBase<PDerived>& p) {\n return winding_number(V,C.begin(),C.end(),p);\n }\n template <typename PDerived, typename VDerived, typename BeginIt, typename EndIt>\n bool interior_winding_number(const Eigen::MatrixBase<VDerived>& V, const BeginIt& beginit, const EndIt& endit, const Eigen::MatrixBase<PDerived>& p) {\n auto v = winding_number(V,beginit,endit,p);\n return std::abs(v - M_PI) < 1;\n }\n template <typename PDerived, typename VDerived, typename Container>\n bool interior_winding_number(const Eigen::MatrixBase<VDerived>& V, const Container& C, const Eigen::MatrixBase<PDerived>& p) {\n return interior_winding_number(V,C.begin(),C.end(),p);\n }\n template <typename PDerived, typename VDerived>\n bool interior_winding_number(const Eigen::MatrixBase<VDerived>& V, const std::initializer_list<int>& C, const Eigen::MatrixBase<PDerived>& p) {\n return interior_winding_number(V,C.begin(),C.end(),p);\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: Eservices.cxx,v $\n *\n * $Revision: 1.4 $\n *\n * last change: $Author: obo $ $Date: 2004-03-15 12:47:35 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef _CONNECTIVITY_FLAT_EDRIVER_HXX_\n#include \"flat\/EDriver.hxx\"\n#endif\n#ifndef _CPPUHELPER_FACTORY_HXX_\n#include <cppuhelper\/factory.hxx>\n#endif\n#ifndef _OSL_DIAGNOSE_H_\n#include <osl\/diagnose.h>\n#endif\n\nusing namespace connectivity::flat;\nusing ::rtl::OUString;\nusing ::com::sun::star::uno::Reference;\nusing ::com::sun::star::uno::Sequence;\nusing ::com::sun::star::registry::XRegistryKey;\nusing ::com::sun::star::lang::XSingleServiceFactory;\nusing ::com::sun::star::lang::XMultiServiceFactory;\n\ntypedef Reference< XSingleServiceFactory > (SAL_CALL *createFactoryFunc)\n (\n const Reference< XMultiServiceFactory > & rServiceManager,\n const OUString & rComponentName,\n ::cppu::ComponentInstantiation pCreateFunction,\n const Sequence< OUString > & rServiceNames,\n rtl_ModuleCount* _pT\n );\n\n\/\/***************************************************************************************\n\/\/\n\/\/ Die vorgeschriebene C-Api muss erfuellt werden!\n\/\/ Sie besteht aus drei Funktionen, die von dem Modul exportiert werden muessen.\n\/\/\n\n\/\/---------------------------------------------------------------------------------------\nvoid REGISTER_PROVIDER(\n const OUString& aServiceImplName,\n const Sequence< OUString>& Services,\n const Reference< ::com::sun::star::registry::XRegistryKey > & xKey)\n{\n OUString aMainKeyName;\n aMainKeyName = OUString::createFromAscii(\"\/\");\n aMainKeyName += aServiceImplName;\n aMainKeyName += OUString::createFromAscii(\"\/UNO\/SERVICES\");\n\n Reference< ::com::sun::star::registry::XRegistryKey > xNewKey( xKey->createKey(aMainKeyName) );\n OSL_ENSURE(xNewKey.is(), \"FILE::component_writeInfo : could not create a registry key !\");\n\n for (sal_Int32 i=0; i<Services.getLength(); ++i)\n xNewKey->createKey(Services[i]);\n}\n\n\n\/\/---------------------------------------------------------------------------------------\nstruct ProviderRequest\n{\n Reference< XSingleServiceFactory > xRet;\n Reference< XMultiServiceFactory > const xServiceManager;\n OUString const sImplementationName;\n\n ProviderRequest(\n void* pServiceManager,\n sal_Char const* pImplementationName\n )\n : xServiceManager(reinterpret_cast<XMultiServiceFactory*>(pServiceManager))\n , sImplementationName(OUString::createFromAscii(pImplementationName))\n {\n }\n\n inline\n sal_Bool CREATE_PROVIDER(\n const OUString& Implname,\n const Sequence< OUString > & Services,\n ::cppu::ComponentInstantiation Factory,\n createFactoryFunc creator\n )\n {\n if (!xRet.is() && (Implname == sImplementationName))\n try\n {\n xRet = creator( xServiceManager, sImplementationName,Factory, Services,0);\n }\n catch(...)\n {\n }\n return xRet.is();\n }\n\n void* getProvider() const { return xRet.get(); }\n};\n\n\/\/---------------------------------------------------------------------------------------\n\nextern \"C\" void SAL_CALL component_getImplementationEnvironment(\n const sal_Char **ppEnvTypeName,\n uno_Environment **ppEnv\n )\n{\n *ppEnvTypeName = CPPU_CURRENT_LANGUAGE_BINDING_NAME;\n}\n\n\/\/---------------------------------------------------------------------------------------\nextern \"C\" sal_Bool SAL_CALL component_writeInfo(\n void* pServiceManager,\n void* pRegistryKey\n )\n{\n if (pRegistryKey)\n try\n {\n Reference< ::com::sun::star::registry::XRegistryKey > xKey(reinterpret_cast< ::com::sun::star::registry::XRegistryKey*>(pRegistryKey));\n\n REGISTER_PROVIDER(\n ODriver::getImplementationName_Static(),\n ODriver::getSupportedServiceNames_Static(), xKey);\n\n return sal_True;\n }\n catch (::com::sun::star::registry::InvalidRegistryException& )\n {\n OSL_ENSURE(sal_False, \"FILE::component_writeInfo : could not create a registry key ! ## InvalidRegistryException !\");\n }\n\n return sal_False;\n}\n\n\/\/---------------------------------------------------------------------------------------\nextern \"C\" void* SAL_CALL component_getFactory(\n const sal_Char* pImplementationName,\n void* pServiceManager,\n void* pRegistryKey)\n{\n void* pRet = 0;\n if (pServiceManager)\n {\n ProviderRequest aReq(pServiceManager,pImplementationName);\n\n aReq.CREATE_PROVIDER(\n ODriver::getImplementationName_Static(),\n ODriver::getSupportedServiceNames_Static(),\n ODriver_CreateInstance, ::cppu::createSingleFactory)\n ;\n\n if(aReq.xRet.is())\n aReq.xRet->acquire();\n\n pRet = aReq.getProvider();\n }\n\n return pRet;\n};\n\n<commit_msg>INTEGRATION: CWS ooo19126 (1.4.160); FILE MERGED 2005\/09\/05 17:23:58 rt 1.4.160.1: #i54170# Change license header: remove SISSL<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: Eservices.cxx,v $\n *\n * $Revision: 1.5 $\n *\n * last change: $Author: rt $ $Date: 2005-09-08 06:02:07 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef _CONNECTIVITY_FLAT_EDRIVER_HXX_\n#include \"flat\/EDriver.hxx\"\n#endif\n#ifndef _CPPUHELPER_FACTORY_HXX_\n#include <cppuhelper\/factory.hxx>\n#endif\n#ifndef _OSL_DIAGNOSE_H_\n#include <osl\/diagnose.h>\n#endif\n\nusing namespace connectivity::flat;\nusing ::rtl::OUString;\nusing ::com::sun::star::uno::Reference;\nusing ::com::sun::star::uno::Sequence;\nusing ::com::sun::star::registry::XRegistryKey;\nusing ::com::sun::star::lang::XSingleServiceFactory;\nusing ::com::sun::star::lang::XMultiServiceFactory;\n\ntypedef Reference< XSingleServiceFactory > (SAL_CALL *createFactoryFunc)\n (\n const Reference< XMultiServiceFactory > & rServiceManager,\n const OUString & rComponentName,\n ::cppu::ComponentInstantiation pCreateFunction,\n const Sequence< OUString > & rServiceNames,\n rtl_ModuleCount* _pT\n );\n\n\/\/***************************************************************************************\n\/\/\n\/\/ Die vorgeschriebene C-Api muss erfuellt werden!\n\/\/ Sie besteht aus drei Funktionen, die von dem Modul exportiert werden muessen.\n\/\/\n\n\/\/---------------------------------------------------------------------------------------\nvoid REGISTER_PROVIDER(\n const OUString& aServiceImplName,\n const Sequence< OUString>& Services,\n const Reference< ::com::sun::star::registry::XRegistryKey > & xKey)\n{\n OUString aMainKeyName;\n aMainKeyName = OUString::createFromAscii(\"\/\");\n aMainKeyName += aServiceImplName;\n aMainKeyName += OUString::createFromAscii(\"\/UNO\/SERVICES\");\n\n Reference< ::com::sun::star::registry::XRegistryKey > xNewKey( xKey->createKey(aMainKeyName) );\n OSL_ENSURE(xNewKey.is(), \"FILE::component_writeInfo : could not create a registry key !\");\n\n for (sal_Int32 i=0; i<Services.getLength(); ++i)\n xNewKey->createKey(Services[i]);\n}\n\n\n\/\/---------------------------------------------------------------------------------------\nstruct ProviderRequest\n{\n Reference< XSingleServiceFactory > xRet;\n Reference< XMultiServiceFactory > const xServiceManager;\n OUString const sImplementationName;\n\n ProviderRequest(\n void* pServiceManager,\n sal_Char const* pImplementationName\n )\n : xServiceManager(reinterpret_cast<XMultiServiceFactory*>(pServiceManager))\n , sImplementationName(OUString::createFromAscii(pImplementationName))\n {\n }\n\n inline\n sal_Bool CREATE_PROVIDER(\n const OUString& Implname,\n const Sequence< OUString > & Services,\n ::cppu::ComponentInstantiation Factory,\n createFactoryFunc creator\n )\n {\n if (!xRet.is() && (Implname == sImplementationName))\n try\n {\n xRet = creator( xServiceManager, sImplementationName,Factory, Services,0);\n }\n catch(...)\n {\n }\n return xRet.is();\n }\n\n void* getProvider() const { return xRet.get(); }\n};\n\n\/\/---------------------------------------------------------------------------------------\n\nextern \"C\" void SAL_CALL component_getImplementationEnvironment(\n const sal_Char **ppEnvTypeName,\n uno_Environment **ppEnv\n )\n{\n *ppEnvTypeName = CPPU_CURRENT_LANGUAGE_BINDING_NAME;\n}\n\n\/\/---------------------------------------------------------------------------------------\nextern \"C\" sal_Bool SAL_CALL component_writeInfo(\n void* pServiceManager,\n void* pRegistryKey\n )\n{\n if (pRegistryKey)\n try\n {\n Reference< ::com::sun::star::registry::XRegistryKey > xKey(reinterpret_cast< ::com::sun::star::registry::XRegistryKey*>(pRegistryKey));\n\n REGISTER_PROVIDER(\n ODriver::getImplementationName_Static(),\n ODriver::getSupportedServiceNames_Static(), xKey);\n\n return sal_True;\n }\n catch (::com::sun::star::registry::InvalidRegistryException& )\n {\n OSL_ENSURE(sal_False, \"FILE::component_writeInfo : could not create a registry key ! ## InvalidRegistryException !\");\n }\n\n return sal_False;\n}\n\n\/\/---------------------------------------------------------------------------------------\nextern \"C\" void* SAL_CALL component_getFactory(\n const sal_Char* pImplementationName,\n void* pServiceManager,\n void* pRegistryKey)\n{\n void* pRet = 0;\n if (pServiceManager)\n {\n ProviderRequest aReq(pServiceManager,pImplementationName);\n\n aReq.CREATE_PROVIDER(\n ODriver::getImplementationName_Static(),\n ODriver::getSupportedServiceNames_Static(),\n ODriver_CreateInstance, ::cppu::createSingleFactory)\n ;\n\n if(aReq.xRet.is())\n aReq.xRet->acquire();\n\n pRet = aReq.getProvider();\n }\n\n return pRet;\n};\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2017-2018 Dr. Colin Hirsch and Daniel Frey\n\/\/ Please see LICENSE for license or visit https:\/\/github.com\/taocpp\/PEGTL\/\n\n#ifndef TAO_PEGTL_CONTRIB_PARSE_TREE_HPP\n#define TAO_PEGTL_CONTRIB_PARSE_TREE_HPP\n\n#include <cassert>\n#include <memory>\n#include <tuple>\n#include <type_traits>\n#include <typeinfo>\n#include <utility>\n#include <vector>\n\n#include \"..\/config.hpp\"\n#include \"..\/normal.hpp\"\n#include \"..\/nothing.hpp\"\n#include \"..\/parse.hpp\"\n\n#include \"..\/analysis\/counted.hpp\"\n#include \"..\/analysis\/generic.hpp\"\n#include \"..\/internal\/conditional.hpp\"\n#include \"..\/internal\/demangle.hpp\"\n#include \"..\/internal\/iterator.hpp\"\n\nnamespace tao\n{\n namespace TAO_PEGTL_NAMESPACE\n {\n namespace parse_tree\n {\n template< typename T >\n struct basic_node\n {\n using node_t = T;\n using children_t = std::vector< std::unique_ptr< node_t > >;\n children_t children;\n\n const std::type_info* id = nullptr;\n std::string source;\n\n TAO_PEGTL_NAMESPACE::internal::iterator m_begin;\n TAO_PEGTL_NAMESPACE::internal::iterator m_end;\n\n \/\/ each node will be default constructed\n basic_node() = default;\n\n \/\/ no copy\/move is necessary\n \/\/ (nodes are always owned\/handled by a std::unique_ptr)\n basic_node( const basic_node& ) = delete;\n basic_node( basic_node&& ) = delete;\n\n ~basic_node() = default;\n\n \/\/ no assignment either\n basic_node& operator=( const basic_node& ) = delete;\n basic_node& operator=( basic_node&& ) = delete;\n\n bool is_root() const noexcept\n {\n return id == nullptr;\n }\n\n template< typename U >\n bool is() const noexcept\n {\n return id == &typeid( U );\n }\n\n std::string name() const\n {\n assert( !is_root() );\n return TAO_PEGTL_NAMESPACE::internal::demangle( id->name() );\n }\n\n position begin() const\n {\n return position( m_begin, source );\n }\n\n position end() const\n {\n return position( m_end, source );\n }\n\n bool has_content() const noexcept\n {\n return m_end.data != nullptr;\n }\n\n std::string content() const\n {\n assert( has_content() );\n return std::string( m_begin.data, m_end.data );\n }\n\n template< typename... States >\n void remove_content( States&&... \/*unused*\/ ) noexcept\n {\n m_end.reset();\n }\n\n \/\/ all non-root nodes are initialized by calling this method\n template< typename Rule, typename Input, typename... States >\n void start( const Input& in, States&&... \/*unused*\/ )\n {\n id = &typeid( Rule );\n source = in.source();\n m_begin = in.iterator();\n }\n\n \/\/ if parsing of the rule succeeded, this method is called\n template< typename Rule, typename Input, typename... States >\n void success( const Input& in, States&&... \/*unused*\/ ) noexcept\n {\n m_end = in.iterator();\n }\n\n \/\/ if parsing of the rule failed, this method is called\n template< typename Rule, typename Input, typename... States >\n void failure( const Input& \/*unused*\/, States&&... \/*unused*\/ ) noexcept\n {\n }\n\n \/\/ if parsing succeeded and the (optional) transform call\n \/\/ did not discard the node, it is appended to its parent.\n \/\/ note that \"child\" is the node whose Rule just succeeded\n \/\/ and \"*this\" is the parent where the node should be appended.\n template< typename... States >\n void emplace_back( std::unique_ptr< node_t > child, States&&... \/*unused*\/ )\n {\n assert( child );\n children.emplace_back( std::move( child ) );\n }\n };\n\n struct node\n : basic_node< node >\n {\n };\n\n namespace internal\n {\n template< typename Node >\n struct state\n {\n std::vector< std::unique_ptr< Node > > stack;\n\n state()\n {\n emplace_back();\n }\n\n void emplace_back()\n {\n stack.emplace_back( std::unique_ptr< Node >( new Node ) ); \/\/ NOLINT: std::make_unique requires C++14\n }\n\n std::unique_ptr< Node >& back() noexcept\n {\n return stack.back();\n }\n\n void pop_back() noexcept\n {\n return stack.pop_back();\n }\n };\n\n template< typename Selector, typename... States >\n void transform( States&&... \/*unused*\/ ) noexcept\n {\n }\n\n template< typename Selector, typename Node, typename... States >\n auto transform( std::unique_ptr< Node >& n, States&&... st ) noexcept( noexcept( Selector::transform( n, st... ) ) )\n -> decltype( Selector::transform( n, st... ), void() )\n {\n Selector::transform( n, st... );\n }\n\n template< unsigned Level, typename Analyse, template< typename... > class Selector >\n struct is_leaf\n : std::false_type\n {\n };\n\n template< analysis::rule_type Type, template< typename... > class Selector >\n struct is_leaf< 0, analysis::generic< Type >, Selector >\n : std::true_type\n {\n };\n\n template< analysis::rule_type Type, unsigned Count, template< typename... > class Selector >\n struct is_leaf< 0, analysis::counted< Type, Count >, Selector >\n : std::true_type\n {\n };\n\n template< analysis::rule_type Type, typename... Rules, template< typename... > class Selector >\n struct is_leaf< 0, analysis::generic< Type, Rules... >, Selector >\n : std::false_type\n {\n };\n\n template< analysis::rule_type Type, unsigned Count, typename... Rules, template< typename... > class Selector >\n struct is_leaf< 0, analysis::counted< Type, Count, Rules... >, Selector >\n : std::false_type\n {\n };\n\n template< bool... >\n struct bool_sequence;\n\n template< bool... Bs >\n using is_all = std::is_same< bool_sequence< Bs..., true >, bool_sequence< true, Bs... > >;\n\n template< unsigned Level, typename Rule, template< typename... > class Selector >\n using is_unselected_leaf = std::integral_constant< bool, !Selector< Rule >::value && is_leaf< Level, typename Rule::analyze_t, Selector >::value >;\n\n template< unsigned Level, analysis::rule_type Type, typename... Rules, template< typename... > class Selector >\n struct is_leaf< Level, analysis::generic< Type, Rules... >, Selector >\n : is_all< is_unselected_leaf< Level - 1, Rules, Selector >::value... >\n {\n };\n\n template< unsigned Level, analysis::rule_type Type, unsigned Count, typename... Rules, template< typename... > class Selector >\n struct is_leaf< Level, analysis::counted< Type, Count, Rules... >, Selector >\n : is_all< is_unselected_leaf< Level - 1, Rules, Selector >::value... >\n {\n };\n\n template< typename Node, template< typename... > class Selector, template< typename... > class Control >\n struct make_control\n {\n template< typename Rule, bool, bool >\n struct control;\n\n template< typename Rule >\n using type = control< Rule, Selector< Rule >::value, is_leaf< 8, typename Rule::analyze_t, Selector >::value >;\n };\n\n template< typename Node, template< typename... > class Selector, template< typename... > class Control >\n template< typename Rule >\n struct make_control< Node, Selector, Control >::control< Rule, false, true >\n : Control< Rule >\n {\n };\n\n template< typename Node, template< typename... > class Selector, template< typename... > class Control >\n template< typename Rule >\n struct make_control< Node, Selector, Control >::control< Rule, false, false >\n : Control< Rule >\n {\n template< typename Input, typename... States >\n static void start( const Input& in, States&&... st )\n {\n Control< Rule >::start( in, st... );\n auto& state = std::get< sizeof...( st ) - 1 >( std::tie( st... ) );\n state.emplace_back();\n }\n\n template< typename Input, typename... States >\n static void success( const Input& in, States&&... st )\n {\n Control< Rule >::success( in, st... );\n auto& state = std::get< sizeof...( st ) - 1 >( std::tie( st... ) );\n auto n = std::move( state.back() );\n state.pop_back();\n for( auto& c : n->children ) {\n state.back()->children.emplace_back( std::move( c ) );\n }\n }\n\n template< typename Input, typename... States >\n static void failure( const Input& in, States&&... st ) noexcept( noexcept( Control< Rule >::failure( in, st... ) ) )\n {\n Control< Rule >::failure( in, st... );\n auto& state = std::get< sizeof...( st ) - 1 >( std::tie( st... ) );\n state.pop_back();\n }\n };\n\n template< typename Node, template< typename... > class Selector, template< typename... > class Control >\n template< typename Rule, bool B >\n struct make_control< Node, Selector, Control >::control< Rule, true, B >\n : Control< Rule >\n {\n template< typename Input, typename... States >\n static void start( const Input& in, States&&... st )\n {\n Control< Rule >::start( in, st... );\n auto& state = std::get< sizeof...( st ) - 1 >( std::tie( st... ) );\n state.emplace_back();\n state.back()->template start< Rule >( in, st... );\n }\n\n template< typename Input, typename... States >\n static void success( const Input& in, States&&... st )\n {\n Control< Rule >::success( in, st... );\n auto& state = std::get< sizeof...( st ) - 1 >( std::tie( st... ) );\n auto n = std::move( state.back() );\n state.pop_back();\n n->template success< Rule >( in, st... );\n transform< Selector< Rule > >( n, st... );\n if( n ) {\n state.back()->emplace_back( std::move( n ), st... );\n }\n }\n\n template< typename Input, typename... States >\n static void failure( const Input& in, States&&... st ) noexcept( noexcept( Control< Rule >::failure( in, st... ) ) && noexcept( std::declval< node& >().template failure< Rule >( in, st... ) ) )\n {\n Control< Rule >::failure( in, st... );\n auto& state = std::get< sizeof...( st ) - 1 >( std::tie( st... ) );\n state.back()->template failure< Rule >( in, st... );\n state.pop_back();\n }\n };\n\n template< typename >\n struct element\n {\n };\n\n template< typename >\n struct store_all : std::true_type\n {\n };\n\n } \/\/ namespace internal\n\n using store_content = std::true_type;\n\n \/\/ some nodes don't need to store their content\n struct remove_content : std::true_type\n {\n template< typename Node, typename... States >\n static void transform( std::unique_ptr< Node >& n, States&&... st ) noexcept( noexcept( n->Node::remove_content( st... ) ) )\n {\n n->remove_content( st... );\n }\n };\n\n \/\/ if a node has only one child, replace the node with its child, otherwise apply B\n template< typename Base >\n struct fold_one_or : Base\n {\n template< typename Node, typename... States >\n static void transform( std::unique_ptr< Node >& n, States&&... st ) noexcept( noexcept( n->children.size(), Base::transform( n, st... ) ) )\n {\n if( n->children.size() == 1 ) {\n n = std::move( n->children.front() );\n }\n else {\n Base::transform( n, st... );\n }\n }\n };\n\n \/\/ if a node has no children, discard the node, otherwise apply B\n template< typename Base >\n struct discard_empty_or : Base\n {\n template< typename Node, typename... States >\n static void transform( std::unique_ptr< Node >& n, States&&... st ) noexcept( noexcept( n->children.empty(), Base::transform( n, st... ) ) )\n {\n if( n->children.empty() ) {\n n.reset();\n }\n else {\n Base::transform( n, st... );\n }\n }\n };\n\n using fold_one = fold_one_or< remove_content >;\n using discard_empty = discard_empty_or< remove_content >;\n\n template< typename Rule, typename... Collections >\n struct selector : std::false_type\n {\n };\n\n \/\/ TODO: Implement in a non-recursive way\n \/\/ TODO: Check for multiple matches (currently: first match wins)\n template< typename Rule, typename Collection, typename... Collections >\n struct selector< Rule, Collection, Collections... >\n : TAO_PEGTL_NAMESPACE::internal::conditional< Collection::template contains< Rule >::value >::template type< typename Collection::type, selector< Rule, Collections... > >\n {\n };\n\n template< typename Base >\n struct apply\n {\n template< typename... Rules >\n struct to\n : internal::element< Rules >...\n {\n using type = Base;\n\n template< typename Rule >\n using contains = std::is_base_of< internal::element< Rule >, to >;\n };\n };\n\n using apply_store_content = apply< store_content >;\n using apply_remove_content = apply< remove_content >;\n using apply_fold_one = apply< fold_one >;\n using apply_discard_empty = apply< discard_empty >;\n\n template< typename Rule,\n typename Node,\n template< typename... > class Selector = internal::store_all,\n template< typename... > class Action = nothing,\n template< typename... > class Control = normal,\n typename Input,\n typename... States >\n std::unique_ptr< Node > parse( Input&& in, States&&... st )\n {\n internal::state< Node > state;\n if( !TAO_PEGTL_NAMESPACE::parse< Rule, Action, internal::make_control< Node, Selector, Control >::template type >( in, st..., state ) ) {\n return nullptr;\n }\n assert( state.stack.size() == 1 );\n return std::move( state.back() );\n }\n\n template< typename Rule,\n template< typename... > class Selector = internal::store_all,\n template< typename... > class Action = nothing,\n template< typename... > class Control = normal,\n typename Input,\n typename... States >\n std::unique_ptr< node > parse( Input&& in, States&&... st )\n {\n return parse< Rule, node, Selector, Action, Control >( in, st... );\n }\n\n } \/\/ namespace parse_tree\n\n } \/\/ namespace TAO_PEGTL_NAMESPACE\n\n} \/\/ namespace tao\n\n#endif\n<commit_msg>Provide a memory input for the content<commit_after>\/\/ Copyright (c) 2017-2018 Dr. Colin Hirsch and Daniel Frey\n\/\/ Please see LICENSE for license or visit https:\/\/github.com\/taocpp\/PEGTL\/\n\n#ifndef TAO_PEGTL_CONTRIB_PARSE_TREE_HPP\n#define TAO_PEGTL_CONTRIB_PARSE_TREE_HPP\n\n#include <cassert>\n#include <memory>\n#include <tuple>\n#include <type_traits>\n#include <typeinfo>\n#include <utility>\n#include <vector>\n\n#include \"..\/config.hpp\"\n#include \"..\/memory_input.hpp\"\n#include \"..\/normal.hpp\"\n#include \"..\/nothing.hpp\"\n#include \"..\/parse.hpp\"\n\n#include \"..\/analysis\/counted.hpp\"\n#include \"..\/analysis\/generic.hpp\"\n#include \"..\/internal\/conditional.hpp\"\n#include \"..\/internal\/demangle.hpp\"\n#include \"..\/internal\/iterator.hpp\"\n\nnamespace tao\n{\n namespace TAO_PEGTL_NAMESPACE\n {\n namespace parse_tree\n {\n template< typename T >\n struct basic_node\n {\n using node_t = T;\n using children_t = std::vector< std::unique_ptr< node_t > >;\n children_t children;\n\n const std::type_info* id = nullptr;\n std::string source;\n\n TAO_PEGTL_NAMESPACE::internal::iterator m_begin;\n TAO_PEGTL_NAMESPACE::internal::iterator m_end;\n\n \/\/ each node will be default constructed\n basic_node() = default;\n\n \/\/ no copy\/move is necessary\n \/\/ (nodes are always owned\/handled by a std::unique_ptr)\n basic_node( const basic_node& ) = delete;\n basic_node( basic_node&& ) = delete;\n\n ~basic_node() = default;\n\n \/\/ no assignment either\n basic_node& operator=( const basic_node& ) = delete;\n basic_node& operator=( basic_node&& ) = delete;\n\n bool is_root() const noexcept\n {\n return id == nullptr;\n }\n\n template< typename U >\n bool is() const noexcept\n {\n return id == &typeid( U );\n }\n\n std::string name() const\n {\n assert( !is_root() );\n return TAO_PEGTL_NAMESPACE::internal::demangle( id->name() );\n }\n\n position begin() const\n {\n return position( m_begin, source );\n }\n\n position end() const\n {\n return position( m_end, source );\n }\n\n bool has_content() const noexcept\n {\n return m_end.data != nullptr;\n }\n\n std::string content() const\n {\n assert( has_content() );\n return std::string( m_begin.data, m_end.data );\n }\n\n template< tracking_mode P = tracking_mode::IMMEDIATE, typename Eol = eol::lf_crlf >\n memory_input< P, Eol > as_memory_input() const\n {\n assert( has_content() );\n return memory_input< P, Eol >( m_begin.data, m_end.data - m_begin.data, source, m_begin.byte, m_begin.line, m_begin.byte_in_line );\n }\n\n template< typename... States >\n void remove_content( States&&... \/*unused*\/ ) noexcept\n {\n m_end.reset();\n }\n\n \/\/ all non-root nodes are initialized by calling this method\n template< typename Rule, typename Input, typename... States >\n void start( const Input& in, States&&... \/*unused*\/ )\n {\n id = &typeid( Rule );\n source = in.source();\n m_begin = in.iterator();\n }\n\n \/\/ if parsing of the rule succeeded, this method is called\n template< typename Rule, typename Input, typename... States >\n void success( const Input& in, States&&... \/*unused*\/ ) noexcept\n {\n m_end = in.iterator();\n }\n\n \/\/ if parsing of the rule failed, this method is called\n template< typename Rule, typename Input, typename... States >\n void failure( const Input& \/*unused*\/, States&&... \/*unused*\/ ) noexcept\n {\n }\n\n \/\/ if parsing succeeded and the (optional) transform call\n \/\/ did not discard the node, it is appended to its parent.\n \/\/ note that \"child\" is the node whose Rule just succeeded\n \/\/ and \"*this\" is the parent where the node should be appended.\n template< typename... States >\n void emplace_back( std::unique_ptr< node_t > child, States&&... \/*unused*\/ )\n {\n assert( child );\n children.emplace_back( std::move( child ) );\n }\n };\n\n struct node\n : basic_node< node >\n {\n };\n\n namespace internal\n {\n template< typename Node >\n struct state\n {\n std::vector< std::unique_ptr< Node > > stack;\n\n state()\n {\n emplace_back();\n }\n\n void emplace_back()\n {\n stack.emplace_back( std::unique_ptr< Node >( new Node ) ); \/\/ NOLINT: std::make_unique requires C++14\n }\n\n std::unique_ptr< Node >& back() noexcept\n {\n return stack.back();\n }\n\n void pop_back() noexcept\n {\n return stack.pop_back();\n }\n };\n\n template< typename Selector, typename... States >\n void transform( States&&... \/*unused*\/ ) noexcept\n {\n }\n\n template< typename Selector, typename Node, typename... States >\n auto transform( std::unique_ptr< Node >& n, States&&... st ) noexcept( noexcept( Selector::transform( n, st... ) ) )\n -> decltype( Selector::transform( n, st... ), void() )\n {\n Selector::transform( n, st... );\n }\n\n template< unsigned Level, typename Analyse, template< typename... > class Selector >\n struct is_leaf\n : std::false_type\n {\n };\n\n template< analysis::rule_type Type, template< typename... > class Selector >\n struct is_leaf< 0, analysis::generic< Type >, Selector >\n : std::true_type\n {\n };\n\n template< analysis::rule_type Type, unsigned Count, template< typename... > class Selector >\n struct is_leaf< 0, analysis::counted< Type, Count >, Selector >\n : std::true_type\n {\n };\n\n template< analysis::rule_type Type, typename... Rules, template< typename... > class Selector >\n struct is_leaf< 0, analysis::generic< Type, Rules... >, Selector >\n : std::false_type\n {\n };\n\n template< analysis::rule_type Type, unsigned Count, typename... Rules, template< typename... > class Selector >\n struct is_leaf< 0, analysis::counted< Type, Count, Rules... >, Selector >\n : std::false_type\n {\n };\n\n template< bool... >\n struct bool_sequence;\n\n template< bool... Bs >\n using is_all = std::is_same< bool_sequence< Bs..., true >, bool_sequence< true, Bs... > >;\n\n template< unsigned Level, typename Rule, template< typename... > class Selector >\n using is_unselected_leaf = std::integral_constant< bool, !Selector< Rule >::value && is_leaf< Level, typename Rule::analyze_t, Selector >::value >;\n\n template< unsigned Level, analysis::rule_type Type, typename... Rules, template< typename... > class Selector >\n struct is_leaf< Level, analysis::generic< Type, Rules... >, Selector >\n : is_all< is_unselected_leaf< Level - 1, Rules, Selector >::value... >\n {\n };\n\n template< unsigned Level, analysis::rule_type Type, unsigned Count, typename... Rules, template< typename... > class Selector >\n struct is_leaf< Level, analysis::counted< Type, Count, Rules... >, Selector >\n : is_all< is_unselected_leaf< Level - 1, Rules, Selector >::value... >\n {\n };\n\n template< typename Node, template< typename... > class Selector, template< typename... > class Control >\n struct make_control\n {\n template< typename Rule, bool, bool >\n struct control;\n\n template< typename Rule >\n using type = control< Rule, Selector< Rule >::value, is_leaf< 8, typename Rule::analyze_t, Selector >::value >;\n };\n\n template< typename Node, template< typename... > class Selector, template< typename... > class Control >\n template< typename Rule >\n struct make_control< Node, Selector, Control >::control< Rule, false, true >\n : Control< Rule >\n {\n };\n\n template< typename Node, template< typename... > class Selector, template< typename... > class Control >\n template< typename Rule >\n struct make_control< Node, Selector, Control >::control< Rule, false, false >\n : Control< Rule >\n {\n template< typename Input, typename... States >\n static void start( const Input& in, States&&... st )\n {\n Control< Rule >::start( in, st... );\n auto& state = std::get< sizeof...( st ) - 1 >( std::tie( st... ) );\n state.emplace_back();\n }\n\n template< typename Input, typename... States >\n static void success( const Input& in, States&&... st )\n {\n Control< Rule >::success( in, st... );\n auto& state = std::get< sizeof...( st ) - 1 >( std::tie( st... ) );\n auto n = std::move( state.back() );\n state.pop_back();\n for( auto& c : n->children ) {\n state.back()->children.emplace_back( std::move( c ) );\n }\n }\n\n template< typename Input, typename... States >\n static void failure( const Input& in, States&&... st ) noexcept( noexcept( Control< Rule >::failure( in, st... ) ) )\n {\n Control< Rule >::failure( in, st... );\n auto& state = std::get< sizeof...( st ) - 1 >( std::tie( st... ) );\n state.pop_back();\n }\n };\n\n template< typename Node, template< typename... > class Selector, template< typename... > class Control >\n template< typename Rule, bool B >\n struct make_control< Node, Selector, Control >::control< Rule, true, B >\n : Control< Rule >\n {\n template< typename Input, typename... States >\n static void start( const Input& in, States&&... st )\n {\n Control< Rule >::start( in, st... );\n auto& state = std::get< sizeof...( st ) - 1 >( std::tie( st... ) );\n state.emplace_back();\n state.back()->template start< Rule >( in, st... );\n }\n\n template< typename Input, typename... States >\n static void success( const Input& in, States&&... st )\n {\n Control< Rule >::success( in, st... );\n auto& state = std::get< sizeof...( st ) - 1 >( std::tie( st... ) );\n auto n = std::move( state.back() );\n state.pop_back();\n n->template success< Rule >( in, st... );\n transform< Selector< Rule > >( n, st... );\n if( n ) {\n state.back()->emplace_back( std::move( n ), st... );\n }\n }\n\n template< typename Input, typename... States >\n static void failure( const Input& in, States&&... st ) noexcept( noexcept( Control< Rule >::failure( in, st... ) ) && noexcept( std::declval< node& >().template failure< Rule >( in, st... ) ) )\n {\n Control< Rule >::failure( in, st... );\n auto& state = std::get< sizeof...( st ) - 1 >( std::tie( st... ) );\n state.back()->template failure< Rule >( in, st... );\n state.pop_back();\n }\n };\n\n template< typename >\n struct element\n {\n };\n\n template< typename >\n struct store_all : std::true_type\n {\n };\n\n } \/\/ namespace internal\n\n using store_content = std::true_type;\n\n \/\/ some nodes don't need to store their content\n struct remove_content : std::true_type\n {\n template< typename Node, typename... States >\n static void transform( std::unique_ptr< Node >& n, States&&... st ) noexcept( noexcept( n->Node::remove_content( st... ) ) )\n {\n n->remove_content( st... );\n }\n };\n\n \/\/ if a node has only one child, replace the node with its child, otherwise apply B\n template< typename Base >\n struct fold_one_or : Base\n {\n template< typename Node, typename... States >\n static void transform( std::unique_ptr< Node >& n, States&&... st ) noexcept( noexcept( n->children.size(), Base::transform( n, st... ) ) )\n {\n if( n->children.size() == 1 ) {\n n = std::move( n->children.front() );\n }\n else {\n Base::transform( n, st... );\n }\n }\n };\n\n \/\/ if a node has no children, discard the node, otherwise apply B\n template< typename Base >\n struct discard_empty_or : Base\n {\n template< typename Node, typename... States >\n static void transform( std::unique_ptr< Node >& n, States&&... st ) noexcept( noexcept( n->children.empty(), Base::transform( n, st... ) ) )\n {\n if( n->children.empty() ) {\n n.reset();\n }\n else {\n Base::transform( n, st... );\n }\n }\n };\n\n using fold_one = fold_one_or< remove_content >;\n using discard_empty = discard_empty_or< remove_content >;\n\n template< typename Rule, typename... Collections >\n struct selector : std::false_type\n {\n };\n\n \/\/ TODO: Implement in a non-recursive way\n \/\/ TODO: Check for multiple matches (currently: first match wins)\n template< typename Rule, typename Collection, typename... Collections >\n struct selector< Rule, Collection, Collections... >\n : TAO_PEGTL_NAMESPACE::internal::conditional< Collection::template contains< Rule >::value >::template type< typename Collection::type, selector< Rule, Collections... > >\n {\n };\n\n template< typename Base >\n struct apply\n {\n template< typename... Rules >\n struct to\n : internal::element< Rules >...\n {\n using type = Base;\n\n template< typename Rule >\n using contains = std::is_base_of< internal::element< Rule >, to >;\n };\n };\n\n using apply_store_content = apply< store_content >;\n using apply_remove_content = apply< remove_content >;\n using apply_fold_one = apply< fold_one >;\n using apply_discard_empty = apply< discard_empty >;\n\n template< typename Rule,\n typename Node,\n template< typename... > class Selector = internal::store_all,\n template< typename... > class Action = nothing,\n template< typename... > class Control = normal,\n typename Input,\n typename... States >\n std::unique_ptr< Node > parse( Input&& in, States&&... st )\n {\n internal::state< Node > state;\n if( !TAO_PEGTL_NAMESPACE::parse< Rule, Action, internal::make_control< Node, Selector, Control >::template type >( in, st..., state ) ) {\n return nullptr;\n }\n assert( state.stack.size() == 1 );\n return std::move( state.back() );\n }\n\n template< typename Rule,\n template< typename... > class Selector = internal::store_all,\n template< typename... > class Action = nothing,\n template< typename... > class Control = normal,\n typename Input,\n typename... States >\n std::unique_ptr< node > parse( Input&& in, States&&... st )\n {\n return parse< Rule, node, Selector, Action, Control >( in, st... );\n }\n\n } \/\/ namespace parse_tree\n\n } \/\/ namespace TAO_PEGTL_NAMESPACE\n\n} \/\/ namespace tao\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>#ifndef NON_EMPTY_SEQS_IMPLEMENTED\n#define NON_EMPTY_SEQS_IMPLEMENTED\n\n#include <yaml\/config.hpp>\n#include <yaml\/core.hpp>\n#include <yaml\/sequence\/sequence_def.hpp>\n#include <yaml\/sequence\/fold_right.hpp>\n\nBEGIN_YAML_NSP\n\nBEGIN_DETAIL_NSP\n\ntemplate<typename S> class non_empty_seqs_tmpl {\n\n template<typename> struct impl;\n\n template<> struct impl<empty_seq> {\n using type = empty_seq;\n };\n\n template<typename H, typename R> struct impl<seq<H, R>> {\n\n template<typename Y, typename R> struct f_tmpl {\n using type = cons::ret<Y, cons::ret<cons::ret<H, Y> , R>>;\n };\n\n using f = make_curried_t<f_tmpl>;\n\n using type = cons::ret<seq<H, empty_seq>,\n fold_right::ret<f, empty_seq, impl<force_t<R>>>>;\n\n };\n\npublic:\n\n using type = typename impl<force_t<S>>::type;\n\n};\n\nEND_DETAIL_NSP\n\n\/\/\/ brief Returns the list of all subsequences of the argument.\nusing non_empty_seqs = make_curried_t<DETAIL_NSP_REF non_empty_seqs_tmpl>;\n\nEND_YAML_NSP\n\n#endif NON_EMPTY_SEQS_IMPLEMENTED<commit_msg>fix non_empty_seqs brief comment<commit_after>#ifndef NON_EMPTY_SEQS_IMPLEMENTED\n#define NON_EMPTY_SEQS_IMPLEMENTED\n\n#include <yaml\/config.hpp>\n#include <yaml\/core.hpp>\n#include <yaml\/sequence\/sequence_def.hpp>\n#include <yaml\/sequence\/fold_right.hpp>\n\nBEGIN_YAML_NSP\n\nBEGIN_DETAIL_NSP\n\ntemplate<typename S> class non_empty_seqs_tmpl {\n\n template<typename> struct impl;\n\n template<> struct impl<empty_seq> {\n using type = empty_seq;\n };\n\n template<typename H, typename R> struct impl<seq<H, R>> {\n\n template<typename Y, typename R> struct f_tmpl {\n using type = cons::ret<Y, cons::ret<cons::ret<H, Y> , R>>;\n };\n\n using f = make_curried_t<f_tmpl>;\n\n using type = cons::ret<seq<H, empty_seq>,\n fold_right::ret<f, empty_seq, impl<force_t<R>>>>;\n\n };\n\npublic:\n\n using type = typename impl<force_t<S>>::type;\n\n};\n\nEND_DETAIL_NSP\n\n\/\/\/ brief Returns the list of all subsequences of the argument,\n\/\/\/ except for the empty list.\nusing non_empty_seqs = make_curried_t<DETAIL_NSP_REF non_empty_seqs_tmpl>;\n\nEND_YAML_NSP\n\n#endif NON_EMPTY_SEQS_IMPLEMENTED<|endoftext|>"} {"text":"<commit_before>#include <cppunit\/TestCase.h>\n#include <cppunit\/TestFixture.h>\n#include <cppunit\/ui\/text\/TextTestRunner.h>\n#include <cppunit\/extensions\/HelperMacros.h>\n#include <cppunit\/extensions\/TestFactoryRegistry.h>\n#include <cppunit\/TestResult.h>\n#include <cppunit\/TestResultCollector.h>\n#include <cppunit\/TestRunner.h>\n#include <cppunit\/BriefTestProgressListener.h>\n#include <cppunit\/CompilerOutputter.h>\n#include <cppunit\/XmlOutputter.h>\n#include <netinet\/in.h>\n\n#include \"Calculator.hpp\"\n\n#include <iostream>\n#include <string>\n#include <list>\n\nusing namespace CppUnit;\nusing namespace std;\n\n\/\/-----------------------------------------------------------------------------\n\nclass TestCalculator : public CppUnit::TestFixture\n{\n CPPUNIT_TEST_SUITE(TestCalculator);\n CPPUNIT_TEST(testSummation);\n CPPUNIT_TEST(testDifference);\n CPPUNIT_TEST(testMultiplication);\n CPPUNIT_TEST(testDivision);\n CPPUNIT_TEST_SUITE_END();\n\npublic:\n void setUp(void);\n void tearDown(void);\n\nprotected:\n void testSummation(void);\n void testDifference(void);\n void testMultiplication(void);\n void testDivision(void);\n\nprivate:\n\n Calculator *mTestObj;\n};\n\n\/\/-----------------------------------------------------------------------------\n\nvoid\nTestCalculator::testSummation(void)\n{\n CPPUNIT_ASSERT(9 == mTestObj->Summation(6,3));\n}\n\nvoid\nTestCalculator::testDifference(void)\n{\n CPPUNIT_ASSERT(3 == mTestObj->Difference(6,3));\n}\n\nvoid\nTestCalculator::testMultiplication(void)\n{\n CPPUNIT_ASSERT(18 == mTestObj->Multiplication(6,3));\n}\n\nvoid\nTestCalculator::testDivision(void)\n{\n CPPUNIT_ASSERT(2 == mTestObj->Division(6,3));\n}\n\nvoid\nTestCalculator::setUp(void)\n{\n mTestObj = new Calculator();\n}\n\nvoid TestCalculator::tearDown(void)\n{\n delete mTestObj;\n}\n\n\/\/-----------------------------------------------------------------------------\n\nCPPUNIT_TEST_SUITE_REGISTRATION( TestCalculator );\n\nint main(int argc, char* argv[])\n{\n \/\/ informs test-listener about testresults\n CPPUNIT_NS::TestResult testresult;\n\n \/\/ register listener for collecting the test-results\n CPPUNIT_NS::TestResultCollector collectedresults;\n testresult.addListener (&collectedresults);\n\n \/\/ register listener for per-test progress output\n CPPUNIT_NS::BriefTestProgressListener progress;\n testresult.addListener (&progress);\n\n \/\/ insert test-suite at test-runner by registry\n CPPUNIT_NS::TestRunner testrunner;\n testrunner.addTest (CPPUNIT_NS::TestFactoryRegistry::getRegistry().makeTest ());\n testrunner.run(testresult);\n\n \/\/ output results in compiler-format\n CPPUNIT_NS::CompilerOutputter compileroutputter(&collectedresults, std::cerr);\n compileroutputter.write ();\n\n \/\/ Output XML for Jenkins CPPunit plugin\n ofstream xmlFileOut(\"cppTestBasicMathResults.xml\");\n XmlOutputter xmlOut(&collectedresults, xmlFileOut);\n xmlOut.write();\n\n \/\/ return 0 if tests were successful\n return collectedresults.wasSuccessful() ? 0 : 1;\n}\n\n<commit_msg>Create TestCalculator.cpp<commit_after>#include <cppunit\/TestCase.h>\n#include <cppunit\/TestFixture.h>\n#include <cppunit\/ui\/text\/TextTestRunner.h>\n#include <cppunit\/extensions\/HelperMacros.h>\n#include <cppunit\/extensions\/TestFactoryRegistry.h>\n#include <cppunit\/TestResult.h>\n#include <cppunit\/TestResultCollector.h>\n#include <cppunit\/TestRunner.h>\n#include <cppunit\/BriefTestProgressListener.h>\n#include <cppunit\/CompilerOutputter.h>\n#include <cppunit\/XmlOutputter.h>\n#include <netinet\/in.h>\n\n\n#include <iostream>\n#include <string>\n#include <list>\n\n#include \"Calculator.hpp\"\n\nusing namespace CppUnit;\nusing namespace std;\n\n\/\/-----------------------------------------------------------------------------\n\nclass TestCalculator : public CppUnit::TestFixture\n{\n CPPUNIT_TEST_SUITE(TestCalculator);\n CPPUNIT_TEST(testSummation);\n CPPUNIT_TEST(testDifference);\n CPPUNIT_TEST(testMultiplication);\n CPPUNIT_TEST(testDivision);\n CPPUNIT_TEST_SUITE_END();\n\npublic:\n void setUp(void);\n void tearDown(void);\n\nprotected:\n void testSummation(void);\n void testDifference(void);\n void testMultiplication(void);\n void testDivision(void);\n\nprivate:\n\n Calculator *mTestObj;\n};\n\n\/\/-----------------------------------------------------------------------------\n\nvoid\nTestCalculator::testSummation(void)\n{\n CPPUNIT_ASSERT(9 == mTestObj->Summation(6,3));\n}\n\nvoid\nTestCalculator::testDifference(void)\n{\n CPPUNIT_ASSERT(3 == mTestObj->Difference(6,3));\n}\n\nvoid\nTestCalculator::testMultiplication(void)\n{\n CPPUNIT_ASSERT(18 == mTestObj->Multiplication(6,3));\n}\n\nvoid\nTestCalculator::testDivision(void)\n{\n CPPUNIT_ASSERT(2 == mTestObj->Division(6,3));\n}\n\nvoid\nTestCalculator::setUp(void)\n{\n mTestObj = new Calculator();\n}\n\nvoid TestCalculator::tearDown(void)\n{\n delete mTestObj;\n}\n\n\/\/-----------------------------------------------------------------------------\n\nCPPUNIT_TEST_SUITE_REGISTRATION( TestCalculator );\n\nint main(int argc, char* argv[])\n{\n \/\/ informs test-listener about testresults\n CPPUNIT_NS::TestResult testresult;\n\n \/\/ register listener for collecting the test-results\n CPPUNIT_NS::TestResultCollector collectedresults;\n testresult.addListener (&collectedresults);\n\n \/\/ register listener for per-test progress output\n CPPUNIT_NS::BriefTestProgressListener progress;\n testresult.addListener (&progress);\n\n \/\/ insert test-suite at test-runner by registry\n CPPUNIT_NS::TestRunner testrunner;\n testrunner.addTest (CPPUNIT_NS::TestFactoryRegistry::getRegistry().makeTest ());\n testrunner.run(testresult);\n\n \/\/ output results in compiler-format\n CPPUNIT_NS::CompilerOutputter compileroutputter(&collectedresults, std::cerr);\n compileroutputter.write ();\n\n \/\/ Output XML for Jenkins CPPunit plugin\n ofstream xmlFileOut(\"cppTestBasicMathResults.xml\");\n XmlOutputter xmlOut(&collectedresults, xmlFileOut);\n xmlOut.write();\n\n \/\/ return 0 if tests were successful\n return collectedresults.wasSuccessful() ? 0 : 1;\n}\n\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n\n#include <seqan\/base.h>\n#include <seqan\/align.h>\n#include <seqan\/file.h> \/\/ for printint strings\n\nint main()\n{\n seqan::Dna5String seqH = \"CGATT\";\n seqan::Dna5String seqV = \"CGAAATT\";\n\n seqan::Align<Dna5String> align;\n resize(rows(align), 2);\n assignSource(row(align, 0), seqH);\n assignSource(row(align, 0), seqV);\n\n seqan::Score<int, seqan::Simple> scoringScheme(2, -1, -2, -1);\n seqan::AlignConfig<> alignConfig;\n\n int result = globalAlignment(align, scoringScheme, alignConfig);\n\n std::cerr << \"The resulting alignment is\\n\"\n << align;\n\n return 0;\n}\n<commit_msg>[FIX] Fixing include in the align demos.<commit_after>#include <iostream>\n\n#include <seqan\/basic.h>\n#include <seqan\/align.h>\n#include <seqan\/file.h> \/\/ for printint strings\n\nint main()\n{\n seqan::Dna5String seqH = \"CGATT\";\n seqan::Dna5String seqV = \"CGAAATT\";\n\n seqan::Align<Dna5String> align;\n resize(rows(align), 2);\n assignSource(row(align, 0), seqH);\n assignSource(row(align, 0), seqV);\n\n seqan::Score<int, seqan::Simple> scoringScheme(2, -1, -2, -1);\n seqan::AlignConfig<> alignConfig;\n\n int result = globalAlignment(align, scoringScheme, alignConfig);\n\n std::cerr << \"The resulting alignment is\\n\"\n << align;\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>#pragma once\n\n#include <iostream>\n#include <vector>\n#include <cmath>\n#include <algorithm>\n#include <cassert>\n#include <limits>\n\n#include \"acmacs-base\/float.hh\"\n#include \"acmacs-base\/to-string.hh\"\n\n\/\/ ----------------------------------------------------------------------\n\nnamespace acmacs\n{\n class PointCoordinates\n {\n public:\n enum create_copy { create_copy };\n enum with_nan_coordinates_2D { with_nan_coordinates_2D };\n\n PointCoordinates(enum with_nan_coordinates_2D) : data_(2, std::numeric_limits<double>::quiet_NaN()), begin_{&*data_.begin()}, end_{&*data_.end()} {}\n PointCoordinates(size_t number_of_dimensions) : data_(number_of_dimensions, std::numeric_limits<double>::quiet_NaN()), begin_{&*data_.begin()}, end_{&*data_.end()} {}\n PointCoordinates(double x, double y) : data_{x, y}, begin_{&*data_.begin()}, end_{&*data_.end()} {}\n PointCoordinates(double x, double y, double z) : data_{x, y, z}, begin_{&*data_.begin()}, end_{&*data_.end()} {}\n PointCoordinates(enum create_copy, const PointCoordinates& source) : data_{source.begin_, source.end_}, begin_{&*data_.begin()}, end_{&*data_.end()} {}\n PointCoordinates(std::vector<double>::const_iterator first, std::vector<double>::const_iterator last) : begin_{&const_cast<double&>(*first)}, end_{&const_cast<double&>(*last)} {}\n explicit PointCoordinates(const std::vector<double>& source) : PointCoordinates(std::begin(source), std::end(source)) {}\n\n PointCoordinates(const PointCoordinates& rhs) : data_(rhs.data_), begin_{rhs.data_.empty() ? rhs.begin_ : &*data_.begin()}, end_{rhs.data_.empty() ? rhs.end_ : &*data_.end()} {}\n PointCoordinates(PointCoordinates&& rhs) : data_(std::move(rhs.data_)), begin_{rhs.data_.empty() ? rhs.begin_ : &*data_.begin()}, end_{rhs.data_.empty() ? rhs.end_ : &*data_.end()} {}\n\n PointCoordinates& operator=(const PointCoordinates& rhs)\n {\n assert(number_of_dimensions() == rhs.number_of_dimensions());\n if (rhs.data_.empty()) {\n data_.clear();\n begin_ = rhs.begin_;\n end_ = rhs.end_;\n }\n else {\n data_ = rhs.data_;\n begin_ = &*data_.begin();\n end_ = &*data_.end();\n }\n return *this;\n }\n\n bool operator==(const PointCoordinates& rhs) const { return std::equal(begin_, end_, rhs.begin_, rhs.end_); }\n bool operator!=(const PointCoordinates& rhs) const { return !operator==(rhs); }\n\n constexpr size_t number_of_dimensions() const { return static_cast<size_t>(end_ - begin_); }\n double operator[](size_t dim) const { \/* assert(dim < number_of_dimensions()); *\/ return *(begin_ + dim); }\n double& operator[](size_t dim) { \/* assert(dim < number_of_dimensions()); *\/ return *(begin_ + dim); }\n\n constexpr double x() const { return operator[](0); }\n constexpr double y() const { return operator[](1); }\n constexpr double z() const { return operator[](2); }\n\n void x(double val) { operator[](0) = val; }\n void y(double val) { operator[](1) = val; }\n void z(double val) { operator[](2) = val; }\n\n PointCoordinates operator-() const { PointCoordinates result(create_copy, *this); std::transform(begin_, end_, begin_, [](double val) { return -val; }); return result; }\n PointCoordinates operator+=(const PointCoordinates& rhs) { std::transform(begin_, end_, rhs.begin_, begin_, [](double v1, double v2) { return v1 + v2; }); return *this; }\n PointCoordinates operator+=(double val) { std::transform(begin_, end_, begin_, [val](double v1) { return v1 + val; }); return *this; }\n PointCoordinates operator-=(const PointCoordinates& rhs) { std::transform(begin_, end_, rhs.begin_, begin_, [](double v1, double v2) { return v1 - v2; }); return *this; }\n PointCoordinates operator*=(double val) { std::transform(begin_, end_, begin_, [val](double v1) { return v1 * val; }); return *this; }\n PointCoordinates operator\/=(double val) { std::transform(begin_, end_, begin_, [val](double v1) { return v1 \/ val; }); return *this; }\n\n constexpr const double* begin() const { return begin_; }\n constexpr const double* end() const { return end_; }\n constexpr double* begin() { return begin_; }\n constexpr double* end() { return end_; }\n\n bool not_nan() const\n {\n return std::all_of(begin(), end(), [](double value) -> bool { return !std::isnan(value); });\n }\n\n PointCoordinates mean_with(const PointCoordinates& another) const\n {\n PointCoordinates result(number_of_dimensions());\n std::transform(begin_, end_, another.begin_, result.begin_, [](double v1, double v2) { return (v1 + v2) \/ 2.0; });\n return result;\n }\n\n private:\n std::vector<double> data_;\n double* begin_;\n double* end_;\n\n }; \/\/ class PointCoordinates\n\n inline std::string to_string(const PointCoordinates& coord, size_t precision = 32)\n {\n auto result = '{' + acmacs::to_string(coord.x(), precision) + \", \" + acmacs::to_string(coord.y(), precision);\n if (coord.number_of_dimensions() == 3)\n result += \", \" + to_string(coord.z(), precision);\n return result + '}';\n }\n\n inline std::ostream& operator<<(std::ostream& out, const PointCoordinates& coord) { return out << to_string(coord); }\n\n inline double distance2(const PointCoordinates& p1, const PointCoordinates& p2)\n {\n std::vector<double> diff(p1.number_of_dimensions());\n std::transform(p1.begin(), p1.end(), p2.begin(), diff.begin(), [](double v1, double v2) { return v1 - v2; });\n return std::inner_product(diff.begin(), diff.end(), diff.begin(), 0.0);\n }\n\n inline double distance(const PointCoordinates& p1, const PointCoordinates& p2) { return std::sqrt(distance2(p1, p2)); }\n\n inline PointCoordinates operator+(const PointCoordinates& p1, const PointCoordinates& p2) { PointCoordinates result(PointCoordinates::create_copy, p1); result += p2; return result; }\n inline PointCoordinates operator+(const PointCoordinates& p1, double val) { PointCoordinates result(PointCoordinates::create_copy, p1); result += val; return result; }\n inline PointCoordinates operator-(const PointCoordinates& p1, const PointCoordinates& p2) { PointCoordinates result(PointCoordinates::create_copy, p1); result -= p2; return result; }\n inline PointCoordinates operator-(const PointCoordinates& p1, double val) { PointCoordinates result(PointCoordinates::create_copy, p1); result += -val; return result; }\n inline PointCoordinates operator*(const PointCoordinates& p1, double val) { PointCoordinates result(PointCoordinates::create_copy, p1); result *= val; return result; }\n inline PointCoordinates operator\/(const PointCoordinates& p1, double val) { PointCoordinates result(PointCoordinates::create_copy, p1); result \/= val; return result; }\n\n} \/\/ namespace acmacs\n\n\/\/ ----------------------------------------------------------------------\n\/\/\/ Local Variables:\n\/\/\/ eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))\n\/\/\/ End:\n<commit_msg>PointCoordinates development<commit_after>#pragma once\n\n#include <iostream>\n#include <vector>\n#include <cmath>\n#include <algorithm>\n#include <numeric>\n#include <cassert>\n#include <limits>\n\n#include \"acmacs-base\/float.hh\"\n#include \"acmacs-base\/to-string.hh\"\n\n\/\/ ----------------------------------------------------------------------\n\nnamespace acmacs\n{\n class PointCoordinates\n {\n public:\n enum create_copy { create_copy };\n enum with_nan_coordinates_2D { with_nan_coordinates_2D };\n\n PointCoordinates(enum with_nan_coordinates_2D) : data_(2, std::numeric_limits<double>::quiet_NaN()), begin_{&*data_.begin()}, end_{&*data_.end()} {}\n PointCoordinates(size_t number_of_dimensions) : data_(number_of_dimensions, std::numeric_limits<double>::quiet_NaN()), begin_{&*data_.begin()}, end_{&*data_.end()} {}\n PointCoordinates(double x, double y) : data_{x, y}, begin_{&*data_.begin()}, end_{&*data_.end()} {}\n PointCoordinates(double x, double y, double z) : data_{x, y, z}, begin_{&*data_.begin()}, end_{&*data_.end()} {}\n PointCoordinates(enum create_copy, const PointCoordinates& source) : data_{source.begin_, source.end_}, begin_{&*data_.begin()}, end_{&*data_.end()} {}\n PointCoordinates(std::vector<double>::const_iterator first, std::vector<double>::const_iterator last) : begin_{&const_cast<double&>(*first)}, end_{&const_cast<double&>(*last)} {}\n explicit PointCoordinates(const std::vector<double>& source) : PointCoordinates(std::begin(source), std::end(source)) {}\n\n PointCoordinates(const PointCoordinates& rhs) : data_(rhs.data_), begin_{rhs.data_.empty() ? rhs.begin_ : &*data_.begin()}, end_{rhs.data_.empty() ? rhs.end_ : &*data_.end()} {}\n PointCoordinates(PointCoordinates&& rhs) : data_(std::move(rhs.data_)), begin_{rhs.data_.empty() ? rhs.begin_ : &*data_.begin()}, end_{rhs.data_.empty() ? rhs.end_ : &*data_.end()} {}\n\n PointCoordinates& operator=(const PointCoordinates& rhs)\n {\n assert(number_of_dimensions() == rhs.number_of_dimensions());\n if (rhs.data_.empty()) {\n data_.clear();\n begin_ = rhs.begin_;\n end_ = rhs.end_;\n }\n else {\n data_ = rhs.data_;\n begin_ = &*data_.begin();\n end_ = &*data_.end();\n }\n return *this;\n }\n\n bool operator==(const PointCoordinates& rhs) const { return std::equal(begin_, end_, rhs.begin_, rhs.end_); }\n bool operator!=(const PointCoordinates& rhs) const { return !operator==(rhs); }\n\n constexpr size_t number_of_dimensions() const { return static_cast<size_t>(end_ - begin_); }\n double operator[](size_t dim) const { \/* assert(dim < number_of_dimensions()); *\/ return *(begin_ + dim); }\n double& operator[](size_t dim) { \/* assert(dim < number_of_dimensions()); *\/ return *(begin_ + dim); }\n\n constexpr double x() const { return operator[](0); }\n constexpr double y() const { return operator[](1); }\n constexpr double z() const { return operator[](2); }\n\n void x(double val) { operator[](0) = val; }\n void y(double val) { operator[](1) = val; }\n void z(double val) { operator[](2) = val; }\n\n PointCoordinates operator-() const { PointCoordinates result(create_copy, *this); std::transform(begin_, end_, begin_, [](double val) { return -val; }); return result; }\n PointCoordinates operator+=(const PointCoordinates& rhs) { std::transform(begin_, end_, rhs.begin_, begin_, [](double v1, double v2) { return v1 + v2; }); return *this; }\n PointCoordinates operator+=(double val) { std::transform(begin_, end_, begin_, [val](double v1) { return v1 + val; }); return *this; }\n PointCoordinates operator-=(const PointCoordinates& rhs) { std::transform(begin_, end_, rhs.begin_, begin_, [](double v1, double v2) { return v1 - v2; }); return *this; }\n PointCoordinates operator*=(double val) { std::transform(begin_, end_, begin_, [val](double v1) { return v1 * val; }); return *this; }\n PointCoordinates operator\/=(double val) { std::transform(begin_, end_, begin_, [val](double v1) { return v1 \/ val; }); return *this; }\n\n constexpr const double* begin() const { return begin_; }\n constexpr const double* end() const { return end_; }\n constexpr double* begin() { return begin_; }\n constexpr double* end() { return end_; }\n\n bool not_nan() const\n {\n return std::all_of(begin(), end(), [](double value) -> bool { return !std::isnan(value); });\n }\n\n PointCoordinates mean_with(const PointCoordinates& another) const\n {\n PointCoordinates result(number_of_dimensions());\n std::transform(begin_, end_, another.begin_, result.begin_, [](double v1, double v2) { return (v1 + v2) \/ 2.0; });\n return result;\n }\n\n private:\n std::vector<double> data_;\n double* begin_;\n double* end_;\n\n }; \/\/ class PointCoordinates\n\n inline std::string to_string(const PointCoordinates& coord, size_t precision = 32)\n {\n auto result = '{' + acmacs::to_string(coord.x(), precision) + \", \" + acmacs::to_string(coord.y(), precision);\n if (coord.number_of_dimensions() == 3)\n result += \", \" + to_string(coord.z(), precision);\n return result + '}';\n }\n\n inline std::ostream& operator<<(std::ostream& out, const PointCoordinates& coord) { return out << to_string(coord); }\n\n inline double distance2(const PointCoordinates& p1, const PointCoordinates& p2)\n {\n std::vector<double> diff(p1.number_of_dimensions());\n std::transform(p1.begin(), p1.end(), p2.begin(), diff.begin(), [](double v1, double v2) { return v1 - v2; });\n return std::inner_product(diff.begin(), diff.end(), diff.begin(), 0.0);\n }\n\n inline double distance(const PointCoordinates& p1, const PointCoordinates& p2) { return std::sqrt(distance2(p1, p2)); }\n\n inline PointCoordinates operator+(const PointCoordinates& p1, const PointCoordinates& p2) { PointCoordinates result(PointCoordinates::create_copy, p1); result += p2; return result; }\n inline PointCoordinates operator+(const PointCoordinates& p1, double val) { PointCoordinates result(PointCoordinates::create_copy, p1); result += val; return result; }\n inline PointCoordinates operator-(const PointCoordinates& p1, const PointCoordinates& p2) { PointCoordinates result(PointCoordinates::create_copy, p1); result -= p2; return result; }\n inline PointCoordinates operator-(const PointCoordinates& p1, double val) { PointCoordinates result(PointCoordinates::create_copy, p1); result += -val; return result; }\n inline PointCoordinates operator*(const PointCoordinates& p1, double val) { PointCoordinates result(PointCoordinates::create_copy, p1); result *= val; return result; }\n inline PointCoordinates operator\/(const PointCoordinates& p1, double val) { PointCoordinates result(PointCoordinates::create_copy, p1); result \/= val; return result; }\n\n} \/\/ namespace acmacs\n\n\/\/ ----------------------------------------------------------------------\n\/\/\/ Local Variables:\n\/\/\/ eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))\n\/\/\/ End:\n<|endoftext|>"} {"text":"<commit_before>\/*********************************************************************\n* ccea.h\n*\n* CCEATest is a set of unit tests for the CCEA library.\n*\n* Copyright (C) 2016 Eric Klinkhammer\n*\n* This program is free software: you can redistribute it and\/or modify\n* it under the terms of the GNU General Public License as published by\n* the Free Software Foundation, either version 3 of the License, or\n* (at your option) any later version.\n*\n* This program is distributed in the hope that it will be useful,\n* but WITHOUT ANY WARRANTY; without even the implied warranty of\n* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n* GNU General Public License for more details.\n*\n* You should have received a copy of the GNU General Public License\n* along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n*********************************************************************\/\n\n#include \"gtest\/gtest.h\"\n#include \"gmock\/gmock.h\"\n\n#include <iostream>\n#include <vector>\n\n#include \"ccea.h\"\n\nclass CCEATest : public::testing::Test {\n protected:\n\n CCEA ccea;\n\n \/\/ Used for unit tests. Will increment first element in scores by 1\n static void callback(std::vector<FANN::neural_net*>& nets, std::vector<double>& scores) {\n for (const auto net : nets) {\n scores.push_back(0);\n }\n }\n};\n\nTEST_F(CCEATest,testRunGeneration_popSizeConstant) {\n std::vector<std::vector<FANN::neural_net*> > initalPop = ccea.getPopulation();\n int popSizeInit = initalPop.size();\n int poolSizeInit = initalPop[0].size();\n\n ccea.runGeneration(callback);\n\n std::vector<std::vector<FANN::neural_net*> > afterPop = ccea.getPopulation();\n int popSizeAfter = afterPop.size();\n int poolSizeAfter = afterPop[0].size();\n\n EXPECT_EQ(popSizeInit, popSizeAfter);\n EXPECT_EQ(poolSizeInit, poolSizeAfter);\n}\n\nTEST_F(CCEATest,testRunGeneration_callsCallback) {\n\n}\n\nint main(int argc, char** argv) {\n ::testing::InitGoogleTest(&argc,argv);\n return RUN_ALL_TESTS();\n}\n<commit_msg>Creating model branch.<commit_after>\/*********************************************************************\n* ccea_test.h\n*\n* CCEATest is a set of unit tests for the CCEA library.\n*\n* Copyright (C) 2016 Eric Klinkhammer\n*\n* This program is free software: you can redistribute it and\/or modify\n* it under the terms of the GNU General Public License as published by\n* the Free Software Foundation, either version 3 of the License, or\n* (at your option) any later version.\n*\n* This program is distributed in the hope that it will be useful,\n* but WITHOUT ANY WARRANTY; without even the implied warranty of\n* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n* GNU General Public License for more details.\n*\n* You should have received a copy of the GNU General Public License\n* along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n*********************************************************************\/\n\n#include \"gtest\/gtest.h\"\n#include \"gmock\/gmock.h\"\n\n#include <iostream>\n#include <vector>\n\n#include \"ccea.h\"\n\nclass CCEATest : public::testing::Test {\n protected:\n\n CCEA ccea;\n\n \/\/ Used for unit tests. Will increment first element in scores by 1\n static void callback(std::vector<FANN::neural_net*>& nets, std::vector<double>& scores) {\n for (const auto net : nets) {\n scores.push_back(0);\n }\n }\n};\n\nTEST_F(CCEATest,testRunGeneration_popSizeConstant) {\n std::vector<std::vector<FANN::neural_net*> > initalPop = ccea.getPopulation();\n int popSizeInit = initalPop.size();\n int poolSizeInit = initalPop[0].size();\n\n ccea.runGeneration(callback);\n\n std::vector<std::vector<FANN::neural_net*> > afterPop = ccea.getPopulation();\n int popSizeAfter = afterPop.size();\n int poolSizeAfter = afterPop[0].size();\n\n EXPECT_EQ(popSizeInit, popSizeAfter);\n EXPECT_EQ(poolSizeInit, poolSizeAfter);\n}\n\nTEST_F(CCEATest,testRunGeneration_callsCallback) {\n\n}\n\nint main(int argc, char** argv) {\n ::testing::InitGoogleTest(&argc,argv);\n return RUN_ALL_TESTS();\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n\nCopyright (c) 2006, Arvid Norberg\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in\n the documentation and\/or other materials provided with the distribution.\n * Neither the name of the author nor the names of its\n contributors may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#include <boost\/date_time\/posix_time\/posix_time_types.hpp>\n#include <boost\/date_time\/posix_time\/ptime.hpp>\n#include <boost\/bind.hpp>\n\n#include <libtorrent\/io.hpp>\n#include <libtorrent\/invariant_check.hpp>\n#include <libtorrent\/kademlia\/rpc_manager.hpp>\n#include <libtorrent\/kademlia\/logging.hpp>\n#include <libtorrent\/kademlia\/routing_table.hpp>\n#include <libtorrent\/hasher.hpp>\n\n#include <fstream>\n\nusing boost::posix_time::ptime;\nusing boost::posix_time::time_duration;\nusing boost::posix_time::microsec_clock;\nusing boost::posix_time::seconds;\nusing boost::posix_time::milliseconds;\nusing boost::shared_ptr;\nusing boost::bind;\n\nnamespace libtorrent { namespace dht\n{\n\nnamespace io = libtorrent::detail;\n\n#ifdef TORRENT_DHT_VERBOSE_LOGGING\nTORRENT_DEFINE_LOG(rpc)\n#endif\n\nnode_id generate_id();\n\nrpc_manager::rpc_manager(fun const& f, node_id const& our_id\n\t, routing_table& table, send_fun const& sf)\n\t: m_next_transaction_id(rand() % max_transactions)\n\t, m_oldest_transaction_id(m_next_transaction_id)\n\t, m_incoming(f)\n\t, m_send(sf)\n\t, m_our_id(our_id)\n\t, m_table(table)\n\t, m_timer(boost::posix_time::microsec_clock::universal_time())\n\t, m_random_number(generate_id())\n\t, m_destructing(false)\n{\n\tstd::srand(time(0));\n}\n\nrpc_manager::~rpc_manager()\n{\n\tm_destructing = true;\n#ifdef TORRENT_DHT_VERBOSE_LOGGING\n\tTORRENT_LOG(rpc) << \"Destructing\";\n#endif\n\tstd::for_each(m_aborted_transactions.begin(), m_aborted_transactions.end()\n\t\t, bind(&observer::abort, _1));\n\t\n\tfor (transactions_t::iterator i = m_transactions.begin()\n\t\t, end(m_transactions.end()); i != end; ++i)\n\t{\n\t\tif (*i) (*i)->abort();\n\t}\n}\n\n#ifndef NDEBUG\nvoid rpc_manager::check_invariant() const\n{\n\tassert(m_oldest_transaction_id >= 0);\n\tassert(m_oldest_transaction_id < max_transactions);\n\tassert(m_next_transaction_id >= 0);\n\tassert(m_next_transaction_id < max_transactions);\n\tassert(!m_transactions[m_next_transaction_id]);\n\n\tfor (int i = (m_next_transaction_id + 1) % max_transactions;\n\t\ti != m_oldest_transaction_id; i = (i + 1) % max_transactions)\n\t{\n\t\tassert(!m_transactions[i]);\n\t}\n}\n#endif\n\nbool rpc_manager::incoming(msg const& m)\n{\n\tINVARIANT_CHECK;\n\n\tif (m_destructing) return false;\n\n\tif (m.reply)\n\t{\n\t\t\/\/ if we don't have the transaction id in our\n\t\t\/\/ request list, ignore the packet\n\n\t\tif (m.transaction_id.size() != 2)\n\t\t{\n#ifdef TORRENT_DHT_VERBOSE_LOGGING\n\t\t\tTORRENT_LOG(rpc) << \"Reply with invalid transaction id size: \" \n\t\t\t\t<< m.transaction_id.size() << \" from \" << m.addr;\n#endif\n\t\t\treturn false;\n\t\t}\n\t\n\t\tstd::string::const_iterator i = m.transaction_id.begin();\t\n\t\tint tid = io::read_uint16(i);\n\n\t\tif (tid >= (int)m_transactions.size()\n\t\t\t|| tid < 0)\n\t\t{\n#ifdef TORRENT_DHT_VERBOSE_LOGGING\n\t\t\tTORRENT_LOG(rpc) << \"Reply with unknown transaction id: \" \n\t\t\t\t<< tid << \" from \" << m.addr;\n#endif\n\t\t\treturn false;\n\t\t}\n\t\t\n\t\tboost::shared_ptr<observer> o = m_transactions[tid];\n\n\t\tif (!o)\n\t\t{\n#ifdef TORRENT_DHT_VERBOSE_LOGGING\n\t\t\tTORRENT_LOG(rpc) << \"Reply with unknown transaction id: \" \n\t\t\t\t<< tid << \" from \" << m.addr;\n#endif\n\t\t\treturn false;\n\t\t}\n\t\t\n\t\tif (m.addr != o->target_addr)\n\t\t{\n#ifdef TORRENT_DHT_VERBOSE_LOGGING\n\t\t\tTORRENT_LOG(rpc) << \"Reply with incorrect address and valid transaction id: \" \n\t\t\t\t<< tid << \" from \" << m.addr;\n#endif\n\t\t\treturn false;\n\t\t}\n\n#ifdef TORRENT_DHT_VERBOSE_LOGGING\n\t\tstd::ofstream reply_stats(\"libtorrent_logs\/round_trip_ms.log\", std::ios::app);\n\t\treply_stats << m.addr << \"\\t\" << (microsec_clock::universal_time()\n\t\t\t- o->sent).total_milliseconds() << std::endl;\n#endif\n\t\to->reply(m);\n\t\tm_transactions[tid].reset();\n\t\t\n\t\tif (m.piggy_backed_ping)\n\t\t{\n\t\t\t\/\/ there is a ping request piggy\n\t\t\t\/\/ backed in this reply\n\t\t\tmsg ph;\n\t\t\tph.message_id = messages::ping;\n\t\t\tph.transaction_id = m.ping_transaction_id;\n\t\t\tph.id = m_our_id;\n\t\t\tph.addr = m.addr;\n\n\t\t\tmsg empty;\n\t\t\t\n\t\t\treply(empty, ph);\n\t\t}\n\t\treturn m_table.node_seen(m.id, m.addr);\n\t}\n\telse\n\t{\n\t\t\/\/ this is an incoming request\n\t\tm_incoming(m);\n\t}\n\treturn false;\n}\n\ntime_duration rpc_manager::tick()\n{\n\tINVARIANT_CHECK;\n\n\tusing boost::posix_time::microsec_clock;\n\n\tconst int timeout_ms = 20 * 1000;\n\n\t\/\/\tlook for observers that has timed out\n\n\tif (m_next_transaction_id == m_oldest_transaction_id) return milliseconds(timeout_ms);\n\n\tstd::vector<shared_ptr<observer> > timeouts;\n\n\tfor (;m_next_transaction_id != m_oldest_transaction_id;\n\t\tm_oldest_transaction_id = (m_oldest_transaction_id + 1) % max_transactions)\n\t{\n\t\tassert(m_oldest_transaction_id >= 0);\n\t\tassert(m_oldest_transaction_id < max_transactions);\n\n\t\tboost::shared_ptr<observer> o = m_transactions[m_oldest_transaction_id];\n\t\tif (!o) continue;\n\n\t\ttime_duration diff = o->sent + milliseconds(timeout_ms)\n\t\t\t- microsec_clock::universal_time();\n\t\tif (diff > seconds(0))\n\t\t{\n\t\t\tif (diff < seconds(1)) return seconds(1);\n\t\t\treturn diff;\n\t\t}\n\t\t\n\t\ttry\n\t\t{\n\t\t\tm_transactions[m_oldest_transaction_id].reset();\n\t\t\ttimeouts.push_back(o);\n\t\t} catch (std::exception) {}\n\t}\n\t\n\tcheck_invariant();\n\n\tstd::for_each(timeouts.begin(), timeouts.end(), bind(&observer::timeout, _1));\n\ttimeouts.clear();\n\t\n\t\/\/ clear the aborted transactions, will likely\n\t\/\/ generate new requests. We need to swap, since the\n\t\/\/ destrutors may add more observers to the m_aborted_transactions\n\tstd::vector<shared_ptr<observer> >().swap(m_aborted_transactions);\n\treturn milliseconds(timeout_ms);\n}\n\nunsigned int rpc_manager::new_transaction_id(shared_ptr<observer> o)\n{\n\tINVARIANT_CHECK;\n\n\tunsigned int tid = m_next_transaction_id;\n\tm_next_transaction_id = (m_next_transaction_id + 1) % max_transactions;\n\tif (m_transactions[m_next_transaction_id])\n\t{\n\t\t\/\/ moving the observer into the set of aborted transactions\n\t\t\/\/ it will prevent it from spawning new requests right now,\n\t\t\/\/ since that would break the invariant\n\t\tm_aborted_transactions.push_back(m_transactions[m_next_transaction_id]);\n\t\tm_transactions[m_next_transaction_id].reset();\n\t\tassert(m_oldest_transaction_id == m_next_transaction_id);\n\t}\n\tassert(!m_transactions[tid]);\n\tm_transactions[tid] = o;\n\tif (m_oldest_transaction_id == m_next_transaction_id)\n\t{\n\t\tm_oldest_transaction_id = (m_oldest_transaction_id + 1) % max_transactions;\n#ifdef TORRENT_DHT_VERBOSE_LOGGING\n\t\tTORRENT_LOG(rpc) << \"WARNING: transaction limit reached! Too many concurrent\"\n\t\t\t\" messages! limit: \" << (int)max_transactions;\n#endif\n\t\tupdate_oldest_transaction_id();\n\t}\n\n\treturn tid;\n}\n\nvoid rpc_manager::update_oldest_transaction_id()\n{\n\tINVARIANT_CHECK;\n\n\tassert(m_oldest_transaction_id != m_next_transaction_id);\n\twhile (!m_transactions[m_oldest_transaction_id])\n\t{\n\t\tm_oldest_transaction_id = (m_oldest_transaction_id + 1)\n\t\t\t% max_transactions;\n\t\tif (m_oldest_transaction_id == m_next_transaction_id)\n\t\t\tbreak;\n\t}\n}\n\nvoid rpc_manager::invoke(int message_id, udp::endpoint target_addr\n\t, shared_ptr<observer> o)\n{\n\tINVARIANT_CHECK;\n\n\tif (m_destructing)\n\t{\n\t\to->abort();\n\t\treturn;\n\t}\n\n\tmsg m;\n\tm.message_id = message_id;\n\tm.reply = false;\n\tm.id = m_our_id;\n\tm.addr = target_addr;\n\tassert(!m_transactions[m_next_transaction_id]);\n\ttry\n\t{\n\t\tm.transaction_id.clear();\n\t\tstd::back_insert_iterator<std::string> out(m.transaction_id);\n\t\tio::write_uint16(m_next_transaction_id, out);\n\t\t\n\t\to->send(m);\n\n\t\to->sent = boost::posix_time::microsec_clock::universal_time();\n\t\to->target_addr = target_addr;\n\n\t#ifdef TORRENT_DHT_VERBOSE_LOGGING\n\t\tTORRENT_LOG(rpc) << \"Invoking \" << messages::ids[message_id] \n\t\t\t<< \" -> \" << target_addr;\n\t#endif\t\n\t\tm_send(m);\n\t\tnew_transaction_id(o);\n\t}\n\tcatch (std::exception&)\n\t{\n\t\tassert(false);\n\t}\n}\n\nvoid rpc_manager::reply(msg& m, msg const& reply_to)\n{\n\tINVARIANT_CHECK;\n\n\tif (m_destructing) return;\n\n\tif (m.message_id != messages::error)\n\t\tm.message_id = reply_to.message_id;\n\tm.addr = reply_to.addr;\n\tm.reply = true;\n\tm.piggy_backed_ping = false;\n\tm.id = m_our_id;\n\tm.transaction_id = reply_to.transaction_id;\n\t\n\tm_send(m);\n}\n\nnamespace\n{\n\tstruct dummy_observer : observer\n\t{\n\t\tvirtual void reply(msg const&) {}\n\t\tvirtual void timeout() {}\n\t\tvirtual void send(msg&) {}\n\t\tvoid abort() {}\n\t};\n}\n\nvoid rpc_manager::reply_with_ping(msg& m, msg const& reply_to)\n{\n\tINVARIANT_CHECK;\n\n\tif (m_destructing) return;\n\n\tif (m.message_id != messages::error)\n\t\tm.message_id = reply_to.message_id;\n\tm.addr = reply_to.addr;\n\tm.reply = true;\n\tm.piggy_backed_ping = true;\n\tm.id = m_our_id;\n\tm.transaction_id = reply_to.transaction_id;\n\n\ttry\n\t{\n\t\tm.ping_transaction_id.clear();\n\t\tstd::back_insert_iterator<std::string> out(m.ping_transaction_id);\n\t\tio::write_uint16(m_next_transaction_id, out);\n\n\t\tboost::shared_ptr<observer> o(new dummy_observer);\n\t\tassert(!m_transactions[m_next_transaction_id]);\n\t\to->sent = boost::posix_time::microsec_clock::universal_time();\n\t\to->target_addr = m.addr;\n\t\t\n\t\tm_send(m);\n\t\tnew_transaction_id(o);\n\t}\n\tcatch (std::exception& e)\n\t{\n\t\tassert(false);\n\t}\n}\n\n\n\n} } \/\/ namespace libtorrent::dht\n\n<commit_msg>removed invariant_check() left in by mistake<commit_after>\/*\n\nCopyright (c) 2006, Arvid Norberg\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in\n the documentation and\/or other materials provided with the distribution.\n * Neither the name of the author nor the names of its\n contributors may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#include <boost\/date_time\/posix_time\/posix_time_types.hpp>\n#include <boost\/date_time\/posix_time\/ptime.hpp>\n#include <boost\/bind.hpp>\n\n#include <libtorrent\/io.hpp>\n#include <libtorrent\/invariant_check.hpp>\n#include <libtorrent\/kademlia\/rpc_manager.hpp>\n#include <libtorrent\/kademlia\/logging.hpp>\n#include <libtorrent\/kademlia\/routing_table.hpp>\n#include <libtorrent\/hasher.hpp>\n\n#include <fstream>\n\nusing boost::posix_time::ptime;\nusing boost::posix_time::time_duration;\nusing boost::posix_time::microsec_clock;\nusing boost::posix_time::seconds;\nusing boost::posix_time::milliseconds;\nusing boost::shared_ptr;\nusing boost::bind;\n\nnamespace libtorrent { namespace dht\n{\n\nnamespace io = libtorrent::detail;\n\n#ifdef TORRENT_DHT_VERBOSE_LOGGING\nTORRENT_DEFINE_LOG(rpc)\n#endif\n\nnode_id generate_id();\n\nrpc_manager::rpc_manager(fun const& f, node_id const& our_id\n\t, routing_table& table, send_fun const& sf)\n\t: m_next_transaction_id(rand() % max_transactions)\n\t, m_oldest_transaction_id(m_next_transaction_id)\n\t, m_incoming(f)\n\t, m_send(sf)\n\t, m_our_id(our_id)\n\t, m_table(table)\n\t, m_timer(boost::posix_time::microsec_clock::universal_time())\n\t, m_random_number(generate_id())\n\t, m_destructing(false)\n{\n\tstd::srand(time(0));\n}\n\nrpc_manager::~rpc_manager()\n{\n\tm_destructing = true;\n#ifdef TORRENT_DHT_VERBOSE_LOGGING\n\tTORRENT_LOG(rpc) << \"Destructing\";\n#endif\n\tstd::for_each(m_aborted_transactions.begin(), m_aborted_transactions.end()\n\t\t, bind(&observer::abort, _1));\n\t\n\tfor (transactions_t::iterator i = m_transactions.begin()\n\t\t, end(m_transactions.end()); i != end; ++i)\n\t{\n\t\tif (*i) (*i)->abort();\n\t}\n}\n\n#ifndef NDEBUG\nvoid rpc_manager::check_invariant() const\n{\n\tassert(m_oldest_transaction_id >= 0);\n\tassert(m_oldest_transaction_id < max_transactions);\n\tassert(m_next_transaction_id >= 0);\n\tassert(m_next_transaction_id < max_transactions);\n\tassert(!m_transactions[m_next_transaction_id]);\n\n\tfor (int i = (m_next_transaction_id + 1) % max_transactions;\n\t\ti != m_oldest_transaction_id; i = (i + 1) % max_transactions)\n\t{\n\t\tassert(!m_transactions[i]);\n\t}\n}\n#endif\n\nbool rpc_manager::incoming(msg const& m)\n{\n\tINVARIANT_CHECK;\n\n\tif (m_destructing) return false;\n\n\tif (m.reply)\n\t{\n\t\t\/\/ if we don't have the transaction id in our\n\t\t\/\/ request list, ignore the packet\n\n\t\tif (m.transaction_id.size() != 2)\n\t\t{\n#ifdef TORRENT_DHT_VERBOSE_LOGGING\n\t\t\tTORRENT_LOG(rpc) << \"Reply with invalid transaction id size: \" \n\t\t\t\t<< m.transaction_id.size() << \" from \" << m.addr;\n#endif\n\t\t\treturn false;\n\t\t}\n\t\n\t\tstd::string::const_iterator i = m.transaction_id.begin();\t\n\t\tint tid = io::read_uint16(i);\n\n\t\tif (tid >= (int)m_transactions.size()\n\t\t\t|| tid < 0)\n\t\t{\n#ifdef TORRENT_DHT_VERBOSE_LOGGING\n\t\t\tTORRENT_LOG(rpc) << \"Reply with unknown transaction id: \" \n\t\t\t\t<< tid << \" from \" << m.addr;\n#endif\n\t\t\treturn false;\n\t\t}\n\t\t\n\t\tboost::shared_ptr<observer> o = m_transactions[tid];\n\n\t\tif (!o)\n\t\t{\n#ifdef TORRENT_DHT_VERBOSE_LOGGING\n\t\t\tTORRENT_LOG(rpc) << \"Reply with unknown transaction id: \" \n\t\t\t\t<< tid << \" from \" << m.addr;\n#endif\n\t\t\treturn false;\n\t\t}\n\t\t\n\t\tif (m.addr != o->target_addr)\n\t\t{\n#ifdef TORRENT_DHT_VERBOSE_LOGGING\n\t\t\tTORRENT_LOG(rpc) << \"Reply with incorrect address and valid transaction id: \" \n\t\t\t\t<< tid << \" from \" << m.addr;\n#endif\n\t\t\treturn false;\n\t\t}\n\n#ifdef TORRENT_DHT_VERBOSE_LOGGING\n\t\tstd::ofstream reply_stats(\"libtorrent_logs\/round_trip_ms.log\", std::ios::app);\n\t\treply_stats << m.addr << \"\\t\" << (microsec_clock::universal_time()\n\t\t\t- o->sent).total_milliseconds() << std::endl;\n#endif\n\t\to->reply(m);\n\t\tm_transactions[tid].reset();\n\t\t\n\t\tif (m.piggy_backed_ping)\n\t\t{\n\t\t\t\/\/ there is a ping request piggy\n\t\t\t\/\/ backed in this reply\n\t\t\tmsg ph;\n\t\t\tph.message_id = messages::ping;\n\t\t\tph.transaction_id = m.ping_transaction_id;\n\t\t\tph.id = m_our_id;\n\t\t\tph.addr = m.addr;\n\n\t\t\tmsg empty;\n\t\t\t\n\t\t\treply(empty, ph);\n\t\t}\n\t\treturn m_table.node_seen(m.id, m.addr);\n\t}\n\telse\n\t{\n\t\t\/\/ this is an incoming request\n\t\tm_incoming(m);\n\t}\n\treturn false;\n}\n\ntime_duration rpc_manager::tick()\n{\n\tINVARIANT_CHECK;\n\n\tusing boost::posix_time::microsec_clock;\n\n\tconst int timeout_ms = 20 * 1000;\n\n\t\/\/\tlook for observers that has timed out\n\n\tif (m_next_transaction_id == m_oldest_transaction_id) return milliseconds(timeout_ms);\n\n\tstd::vector<shared_ptr<observer> > timeouts;\n\n\tfor (;m_next_transaction_id != m_oldest_transaction_id;\n\t\tm_oldest_transaction_id = (m_oldest_transaction_id + 1) % max_transactions)\n\t{\n\t\tassert(m_oldest_transaction_id >= 0);\n\t\tassert(m_oldest_transaction_id < max_transactions);\n\n\t\tboost::shared_ptr<observer> o = m_transactions[m_oldest_transaction_id];\n\t\tif (!o) continue;\n\n\t\ttime_duration diff = o->sent + milliseconds(timeout_ms)\n\t\t\t- microsec_clock::universal_time();\n\t\tif (diff > seconds(0))\n\t\t{\n\t\t\tif (diff < seconds(1)) return seconds(1);\n\t\t\treturn diff;\n\t\t}\n\t\t\n\t\ttry\n\t\t{\n\t\t\tm_transactions[m_oldest_transaction_id].reset();\n\t\t\ttimeouts.push_back(o);\n\t\t} catch (std::exception) {}\n\t}\n\t\n\tstd::for_each(timeouts.begin(), timeouts.end(), bind(&observer::timeout, _1));\n\ttimeouts.clear();\n\t\n\t\/\/ clear the aborted transactions, will likely\n\t\/\/ generate new requests. We need to swap, since the\n\t\/\/ destrutors may add more observers to the m_aborted_transactions\n\tstd::vector<shared_ptr<observer> >().swap(m_aborted_transactions);\n\treturn milliseconds(timeout_ms);\n}\n\nunsigned int rpc_manager::new_transaction_id(shared_ptr<observer> o)\n{\n\tINVARIANT_CHECK;\n\n\tunsigned int tid = m_next_transaction_id;\n\tm_next_transaction_id = (m_next_transaction_id + 1) % max_transactions;\n\tif (m_transactions[m_next_transaction_id])\n\t{\n\t\t\/\/ moving the observer into the set of aborted transactions\n\t\t\/\/ it will prevent it from spawning new requests right now,\n\t\t\/\/ since that would break the invariant\n\t\tm_aborted_transactions.push_back(m_transactions[m_next_transaction_id]);\n\t\tm_transactions[m_next_transaction_id].reset();\n\t\tassert(m_oldest_transaction_id == m_next_transaction_id);\n\t}\n\tassert(!m_transactions[tid]);\n\tm_transactions[tid] = o;\n\tif (m_oldest_transaction_id == m_next_transaction_id)\n\t{\n\t\tm_oldest_transaction_id = (m_oldest_transaction_id + 1) % max_transactions;\n#ifdef TORRENT_DHT_VERBOSE_LOGGING\n\t\tTORRENT_LOG(rpc) << \"WARNING: transaction limit reached! Too many concurrent\"\n\t\t\t\" messages! limit: \" << (int)max_transactions;\n#endif\n\t\tupdate_oldest_transaction_id();\n\t}\n\n\treturn tid;\n}\n\nvoid rpc_manager::update_oldest_transaction_id()\n{\n\tINVARIANT_CHECK;\n\n\tassert(m_oldest_transaction_id != m_next_transaction_id);\n\twhile (!m_transactions[m_oldest_transaction_id])\n\t{\n\t\tm_oldest_transaction_id = (m_oldest_transaction_id + 1)\n\t\t\t% max_transactions;\n\t\tif (m_oldest_transaction_id == m_next_transaction_id)\n\t\t\tbreak;\n\t}\n}\n\nvoid rpc_manager::invoke(int message_id, udp::endpoint target_addr\n\t, shared_ptr<observer> o)\n{\n\tINVARIANT_CHECK;\n\n\tif (m_destructing)\n\t{\n\t\to->abort();\n\t\treturn;\n\t}\n\n\tmsg m;\n\tm.message_id = message_id;\n\tm.reply = false;\n\tm.id = m_our_id;\n\tm.addr = target_addr;\n\tassert(!m_transactions[m_next_transaction_id]);\n\ttry\n\t{\n\t\tm.transaction_id.clear();\n\t\tstd::back_insert_iterator<std::string> out(m.transaction_id);\n\t\tio::write_uint16(m_next_transaction_id, out);\n\t\t\n\t\to->send(m);\n\n\t\to->sent = boost::posix_time::microsec_clock::universal_time();\n\t\to->target_addr = target_addr;\n\n\t#ifdef TORRENT_DHT_VERBOSE_LOGGING\n\t\tTORRENT_LOG(rpc) << \"Invoking \" << messages::ids[message_id] \n\t\t\t<< \" -> \" << target_addr;\n\t#endif\t\n\t\tm_send(m);\n\t\tnew_transaction_id(o);\n\t}\n\tcatch (std::exception&)\n\t{\n\t\tassert(false);\n\t}\n}\n\nvoid rpc_manager::reply(msg& m, msg const& reply_to)\n{\n\tINVARIANT_CHECK;\n\n\tif (m_destructing) return;\n\n\tif (m.message_id != messages::error)\n\t\tm.message_id = reply_to.message_id;\n\tm.addr = reply_to.addr;\n\tm.reply = true;\n\tm.piggy_backed_ping = false;\n\tm.id = m_our_id;\n\tm.transaction_id = reply_to.transaction_id;\n\t\n\tm_send(m);\n}\n\nnamespace\n{\n\tstruct dummy_observer : observer\n\t{\n\t\tvirtual void reply(msg const&) {}\n\t\tvirtual void timeout() {}\n\t\tvirtual void send(msg&) {}\n\t\tvoid abort() {}\n\t};\n}\n\nvoid rpc_manager::reply_with_ping(msg& m, msg const& reply_to)\n{\n\tINVARIANT_CHECK;\n\n\tif (m_destructing) return;\n\n\tif (m.message_id != messages::error)\n\t\tm.message_id = reply_to.message_id;\n\tm.addr = reply_to.addr;\n\tm.reply = true;\n\tm.piggy_backed_ping = true;\n\tm.id = m_our_id;\n\tm.transaction_id = reply_to.transaction_id;\n\n\ttry\n\t{\n\t\tm.ping_transaction_id.clear();\n\t\tstd::back_insert_iterator<std::string> out(m.ping_transaction_id);\n\t\tio::write_uint16(m_next_transaction_id, out);\n\n\t\tboost::shared_ptr<observer> o(new dummy_observer);\n\t\tassert(!m_transactions[m_next_transaction_id]);\n\t\to->sent = boost::posix_time::microsec_clock::universal_time();\n\t\to->target_addr = m.addr;\n\t\t\n\t\tm_send(m);\n\t\tnew_transaction_id(o);\n\t}\n\tcatch (std::exception& e)\n\t{\n\t\tassert(false);\n\t}\n}\n\n\n\n} } \/\/ namespace libtorrent::dht\n\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: appdata.cxx,v $\n *\n * $Revision: 1.18 $\n *\n * last change: $Author: kz $ $Date: 2004-10-04 20:42:48 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n#ifndef _CACHESTR_HXX \/\/autogen\n#include <tools\/cachestr.hxx>\n#endif\n#ifndef _CONFIG_HXX\n#include <tools\/config.hxx>\n#endif\n#ifndef _INETSTRM_HXX \/\/autogen\n#include <svtools\/inetstrm.hxx>\n#endif\n#ifndef _SFXSTRITEM_HXX \/\/autogen\n#include <svtools\/stritem.hxx>\n#endif\n\n#define _SVSTDARR_STRINGS\n#include <svtools\/svstdarr.hxx>\n#include <vos\/mutex.hxx>\n\n#include <vcl\/menu.hxx>\n\n#ifndef _LOGINERR_HXX\n#include <svtools\/loginerr.hxx>\n#endif\n#ifndef _SV_MSGBOX_HXX\n#include <vcl\/msgbox.hxx>\n#endif\n#ifndef _DATETIMEITEM_HXX \/\/autogen\n#include <svtools\/dateitem.hxx>\n#endif\n#ifndef _SV_MENU_HXX\n#include <vcl\/menu.hxx>\n#endif\n#ifndef _SV_WRKWIN_HXX\n#include <vcl\/wrkwin.hxx>\n#endif\n#include \"comphelper\/processfactory.hxx\"\n\n#include \"viewfrm.hxx\"\n#include \"appdata.hxx\"\n#include \"dispatch.hxx\"\n#include \"event.hxx\"\n#include \"sfxtypes.hxx\"\n#include \"sfxdir.hxx\"\n#include \"doctempl.hxx\"\n\/\/#include \"dataurl.hxx\"\n#include \"arrdecl.hxx\"\n#include \"docfac.hxx\"\n#include \"docfile.hxx\"\n#include \"request.hxx\"\n#include \"referers.hxx\"\n#include \"app.hrc\"\n#include \"sfxresid.hxx\"\n#include \"objshimp.hxx\"\n#include \"appuno.hxx\"\n#include \"imestatuswindow.hxx\"\n\nSfxAppData_Impl::SfxAppData_Impl( SfxApplication* pApp ) :\n bServer( false ),\n pDdeService( 0 ),\n pDocTopics( 0 ),\n pTriggerTopic(0),\n pDdeService2(0),\n pFactArr(0),\n pSfxPluginObjectFactoryPtr( 0 ),\n pSfxPlugInObjectShellFactory( 0 ),\n pSfxFrameObjectFactoryPtr( 0 ),\n pTopFrames( new SfxFrameArr_Impl ),\n pInitLinkList(0),\n pMatcher( 0 ),\n pCancelMgr( 0 ),\n pLabelResMgr( 0 ),\n pAppDispatch(NULL),\n pTemplates( 0 ),\n pFilterIni( 0 ),\n pPool(0),\n pEventConfig(0),\n pDisabledSlotList( 0 ),\n pSecureURLs(0),\n pMiscConfig(0),\n pSaveOptions( 0 ),\n pUndoOptions( 0 ),\n pHelpOptions( 0 ),\n pThisDocument(0),\n pProgress(0),\n pDefFocusWin( 0 ),\n pTemplateCommon( 0 ),\n nDocModalMode(0),\n nAutoTabPageId(0),\n nExecutingSID( 0 ),\n bPlugged(sal_False),\n bDirectAliveCount(sal_False),\n bInQuit(sal_False),\n bInvalidateOnUnlock(sal_False),\n bBean( sal_False ),\n bMinimized( sal_False ),\n bInvisible( sal_False ),\n bInException( sal_False ),\n nAppEvent( 0 ),\n m_xImeStatusWindow(new sfx2::appl::ImeStatusWindow(\n *pApp, comphelper::getProcessServiceFactory()))\n{\n StartListening( *pApp );\n}\n\nSfxAppData_Impl::~SfxAppData_Impl()\n{\n\/\/#ifdef DBG_UTIL\n DeInitDDE();\n delete pTopFrames;\n delete pCancelMgr;\n delete pFilterIni;\n delete pSecureURLs;\n\/\/#endif\n}\n\nIMPL_STATIC_LINK( SfxAppData_Impl, CreateDocumentTemplates, void*, EMPTYARG)\n{\n pThis->GetDocumentTemplates();\n return 0;\n}\n\nvoid SfxAppData_Impl::UpdateApplicationSettings( sal_Bool bDontHide )\n{\n AllSettings aAllSet = Application::GetSettings();\n StyleSettings aStyleSet = aAllSet.GetStyleSettings();\n sal_uInt32 nStyleOptions = aStyleSet.GetOptions();\n if ( bDontHide )\n nStyleOptions &= ~STYLE_OPTION_HIDEDISABLED;\n else\n nStyleOptions |= STYLE_OPTION_HIDEDISABLED;\n aStyleSet.SetOptions( nStyleOptions );\n aAllSet.SetStyleSettings( aStyleSet );\n Application::SetSettings( aAllSet );\n}\n\nSfxDocumentTemplates* SfxAppData_Impl::GetDocumentTemplates()\n{\n if ( !pTemplates )\n pTemplates = new SfxDocumentTemplates;\n else\n pTemplates->ReInitFromComponent();\n return pTemplates;\n}\n\nvoid SfxAppData_Impl::Notify( SfxBroadcaster &rBC, const SfxHint &rHint )\n{\n SfxSimpleHint* pHint = PTR_CAST( SfxSimpleHint, &rHint );\n if( pHint && pHint->GetId() == SFX_HINT_CANCELLABLE )\n {\n\/*\n \/\/ vom Cancel-Manager\n for ( SfxViewFrame *pFrame = SfxViewFrame::GetFirst();\n pFrame;\n pFrame = SfxViewFrame::GetNext(*pFrame) )\n {\n SfxBindings &rBind = pFrame->GetBindings();\n rBind.Invalidate( SID_BROWSE_STOP );\n if ( !rBind.IsInRegistrations() )\n rBind.Update( SID_BROWSE_STOP );\n rBind.Invalidate( SID_BROWSE_STOP );\n }\n *\/\n }\n}\n\n<commit_msg>INTEGRATION: CWS valgrind57 (1.18.36); FILE MERGED 2004\/10\/18 13:21:51 dbo 1.18.36.1: #i35713# uninit members<commit_after>\/*************************************************************************\n *\n * $RCSfile: appdata.cxx,v $\n *\n * $Revision: 1.19 $\n *\n * last change: $Author: obo $ $Date: 2004-10-21 11:59:02 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n#ifndef _CACHESTR_HXX \/\/autogen\n#include <tools\/cachestr.hxx>\n#endif\n#ifndef _CONFIG_HXX\n#include <tools\/config.hxx>\n#endif\n#ifndef _INETSTRM_HXX \/\/autogen\n#include <svtools\/inetstrm.hxx>\n#endif\n#ifndef _SFXSTRITEM_HXX \/\/autogen\n#include <svtools\/stritem.hxx>\n#endif\n\n#define _SVSTDARR_STRINGS\n#include <svtools\/svstdarr.hxx>\n#include <vos\/mutex.hxx>\n\n#include <vcl\/menu.hxx>\n\n#ifndef _LOGINERR_HXX\n#include <svtools\/loginerr.hxx>\n#endif\n#ifndef _SV_MSGBOX_HXX\n#include <vcl\/msgbox.hxx>\n#endif\n#ifndef _DATETIMEITEM_HXX \/\/autogen\n#include <svtools\/dateitem.hxx>\n#endif\n#ifndef _SV_MENU_HXX\n#include <vcl\/menu.hxx>\n#endif\n#ifndef _SV_WRKWIN_HXX\n#include <vcl\/wrkwin.hxx>\n#endif\n#include \"comphelper\/processfactory.hxx\"\n\n#include \"viewfrm.hxx\"\n#include \"appdata.hxx\"\n#include \"dispatch.hxx\"\n#include \"event.hxx\"\n#include \"sfxtypes.hxx\"\n#include \"sfxdir.hxx\"\n#include \"doctempl.hxx\"\n\/\/#include \"dataurl.hxx\"\n#include \"arrdecl.hxx\"\n#include \"docfac.hxx\"\n#include \"docfile.hxx\"\n#include \"request.hxx\"\n#include \"referers.hxx\"\n#include \"app.hrc\"\n#include \"sfxresid.hxx\"\n#include \"objshimp.hxx\"\n#include \"appuno.hxx\"\n#include \"imestatuswindow.hxx\"\n\nSfxAppData_Impl::SfxAppData_Impl( SfxApplication* pApp ) :\n bServer( false ),\n pDdeService( 0 ),\n pDocTopics( 0 ),\n pTriggerTopic(0),\n pDdeService2(0),\n pFactArr(0),\n pSfxPluginObjectFactoryPtr( 0 ),\n pSfxPlugInObjectShellFactory( 0 ),\n pSfxFrameObjectFactoryPtr( 0 ),\n pTopFrames( new SfxFrameArr_Impl ),\n pInitLinkList(0),\n pMatcher( 0 ),\n pCancelMgr( 0 ),\n pLabelResMgr( 0 ),\n pAppDispatch(NULL),\n pTemplates( 0 ),\n pFilterIni( 0 ),\n pPool(0),\n pEventConfig(0),\n pDisabledSlotList( 0 ),\n pSecureURLs(0),\n pMiscConfig(0),\n pSaveOptions( 0 ),\n pUndoOptions( 0 ),\n pHelpOptions( 0 ),\n pThisDocument(0),\n pProgress(0),\n pDefFocusWin( 0 ),\n pTemplateCommon( 0 ),\n nDocModalMode(0),\n nAutoTabPageId(0),\n nExecutingSID( 0 ),\n nBasicCallLevel(0),\n nRescheduleLocks(0),\n nInReschedule(0),\n nAsynchronCalls(0),\n bPlugged(sal_False),\n bDirectAliveCount(sal_False),\n bInQuit(sal_False),\n bInvalidateOnUnlock(sal_False),\n bBean( sal_False ),\n bMinimized( sal_False ),\n bInvisible( sal_False ),\n bInException( sal_False ),\n nAppEvent( 0 ),\n m_xImeStatusWindow(new sfx2::appl::ImeStatusWindow(\n *pApp, comphelper::getProcessServiceFactory()))\n{\n StartListening( *pApp );\n}\n\nSfxAppData_Impl::~SfxAppData_Impl()\n{\n\/\/#ifdef DBG_UTIL\n DeInitDDE();\n delete pTopFrames;\n delete pCancelMgr;\n delete pFilterIni;\n delete pSecureURLs;\n\/\/#endif\n}\n\nIMPL_STATIC_LINK( SfxAppData_Impl, CreateDocumentTemplates, void*, EMPTYARG)\n{\n pThis->GetDocumentTemplates();\n return 0;\n}\n\nvoid SfxAppData_Impl::UpdateApplicationSettings( sal_Bool bDontHide )\n{\n AllSettings aAllSet = Application::GetSettings();\n StyleSettings aStyleSet = aAllSet.GetStyleSettings();\n sal_uInt32 nStyleOptions = aStyleSet.GetOptions();\n if ( bDontHide )\n nStyleOptions &= ~STYLE_OPTION_HIDEDISABLED;\n else\n nStyleOptions |= STYLE_OPTION_HIDEDISABLED;\n aStyleSet.SetOptions( nStyleOptions );\n aAllSet.SetStyleSettings( aStyleSet );\n Application::SetSettings( aAllSet );\n}\n\nSfxDocumentTemplates* SfxAppData_Impl::GetDocumentTemplates()\n{\n if ( !pTemplates )\n pTemplates = new SfxDocumentTemplates;\n else\n pTemplates->ReInitFromComponent();\n return pTemplates;\n}\n\nvoid SfxAppData_Impl::Notify( SfxBroadcaster &rBC, const SfxHint &rHint )\n{\n SfxSimpleHint* pHint = PTR_CAST( SfxSimpleHint, &rHint );\n if( pHint && pHint->GetId() == SFX_HINT_CANCELLABLE )\n {\n\/*\n \/\/ vom Cancel-Manager\n for ( SfxViewFrame *pFrame = SfxViewFrame::GetFirst();\n pFrame;\n pFrame = SfxViewFrame::GetNext(*pFrame) )\n {\n SfxBindings &rBind = pFrame->GetBindings();\n rBind.Invalidate( SID_BROWSE_STOP );\n if ( !rBind.IsInRegistrations() )\n rBind.Update( SID_BROWSE_STOP );\n rBind.Invalidate( SID_BROWSE_STOP );\n }\n *\/\n }\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n * WinFtpClient.cpp\n *\n * Created on: 01\/06\/2015\n *\/\n\n#include \"WinFtpClient.h\"\n#include <iostream>\n#include <fstream>\n#include <sstream>\n#include <cstdio>\n#include <vector>\n\nusing namespace std;\n\n\/**\n * Default constructor: replaces WinFtpClient + subsequent call to SetParameters\n *\/\nWinFtpClient::WinFtpClient(const string& strServerIpAddress,\n const string& strLogin, const string& strPassword)\n: BoTransfer ( )\n, m_strIpAddress(strServerIpAddress)\n, m_strLogin (strLogin)\n, m_strPassword (strPassword)\n, m_bIsConnected(false)\n, m_ulOffset (0 )\n{\n m_csCommand = INVALID_SOCKET;\n m_csData = INVALID_SOCKET;\n}\n\n\/**\n * Default destructor. Closes all open connections, if possible.\n *\/\nWinFtpClient::~WinFtpClient()\n{\n Disconnect();\n}\n\n\/*\n * Public functions\n *\/\nbool WinFtpClient::Connect()\n{\n printf(\"%s() ftp:\/\/%s@%s\\n\", __FUNCTION__, m_strLogin.c_str(), m_strIpAddress.c_str());\n\n \/* Test configuration *\/\n if( m_bIsConnected )\n {\n printf(\"%s() : Already connected\\n\", __FUNCTION__);\n return m_bIsConnected;\n }\n\n if( m_strIpAddress.empty() )\n {\n printf(\"%s() : ERROR - Bad configuration or not ready\\n\", __FUNCTION__);\n return false;\n }\n\n m_bIsConnected = true;\n\n \/\/ Startup WinSock\n WORD wVersionRequested;\n WSADATA wsaData;\n wVersionRequested = MAKEWORD(2, 2);\n if(WSAStartup(wVersionRequested, &wsaData) != 0)\n {\n printf(\"WSAStartup error\\n\");\n return false;\n }\n\n \/\/ Create the commnad socket\n m_csCommand = GetSocket(m_strIpAddress, FTP_COMMAND_PORT);\n\n if (m_csCommand == INVALID_SOCKET)\n {\n printf(\"%s() Socket error: %ld\\n\", __FUNCTION__, WSAGetLastError());\n if (m_csCommand == WSAEISCONN)\n {\n printf(\"Already connected\\n\");\n }\n m_bIsConnected = false;\n }\n else\n {\n \/\/ Read response\n char strConn[256] = {0};\n ReceiveAnswer(strConn, 256);\n strConn[255] = 0;\n if(!CheckExpectedResponse(strConn, \"220\"))\n {\n closesocket(m_csCommand);\n printf(\"%s() Closing command socket. Unexpected server response: %s\\n\", __FUNCTION__, strConn);\n m_bIsConnected = false;\n }\n else\n {\n \/\/ Force login if user and password are not empty\n if(!m_strLogin.empty() && !m_strPassword.empty()\n && !Login())\n {\n m_bIsConnected = false;\n closesocket(m_csCommand);\n printf(\"%s() Closing command socket. Login failed: %ld\\n\", __FUNCTION__, WSAGetLastError());\n }\n }\n }\n\n\n return m_bIsConnected;\n}\n\n\nvoid WinFtpClient::Disconnect()\n{\n printf(\"%s()\\n\", __FUNCTION__);\n\n if( shutdown(m_csCommand, SD_BOTH) == SOCKET_ERROR )\n {\n printf(\"m_csCommand shutdown failed: %d\\n\", WSAGetLastError());\n }\n\n if ( shutdown(m_csData, SD_BOTH) == SOCKET_ERROR )\n {\n printf(\"m_csData shutdown failed: %d\\n\", WSAGetLastError());\n }\n\n WSACleanup();\n\n \/\/ Set flag to false\n m_bIsConnected = false;\n}\n\nbool WinFtpClient::Login()\n{\n printf(\"Login\\n\");\n\n SendCommand(\"USER \" + m_strLogin + \"\\r\\n\");\n Sleep(250);\n char strUser[256] = {0};\n ReceiveAnswer(strUser, 256);\n strUser[255] = 0;\n \/\/ TODO poner reintentos\n if (!CheckExpectedResponse(strUser, \"331\")) {\n printf(\"USER failed! -- \\\"%s\\\"\\n\", strUser);\n return false;\n }\n\n SendCommand(\"PASS \" + m_strPassword + \"\\r\\n\");\n Sleep(250);\n char strPass[256] = {0};\n ReceiveAnswer(strPass, 256);\n strPass[255] = 0;\n\n int retry = 0;\n if (!CheckExpectedResponse(strPass, \"230\")) {\n printf(\"PASS failed! -- \\\"%s\\\"\\n\", strPass);\n return false;\n }\n\n printf(\"\\\"%s\\\"\\n\", strPass);\n\n return true;\n}\n\nbool WinFtpClient::IsConnected() const\n{\n return m_bIsConnected;\n}\n\nvoid WinFtpClient::SetParameters (const std::string& strIpAddress, const std::string& strLogin, const std::string& strPassword)\n{\n m_strIpAddress = strIpAddress;\n m_strLogin = strLogin;\n m_strPassword = strPassword;\n}\n\nbool WinFtpClient::FileExists (const std::string&)\n{\n return true;\n}\n\n\/\/ TODO\nbool WinFtpClient::MoveFile (const std::string& strSourcePath, const std::string& strTargetPath )\n{\n return true;\n}\n\nbool WinFtpClient::GetFile (const std::string& strSourcePath, const std::string& strTargetPath, bool )\n{\n return true;\n}\n\nbool WinFtpClient::RetrFile (const std::string& strSource, const std::string& strTarget, bool bRemoveSource)\n{\n return true;\n}\n\nlist<std::string> WinFtpClient::GetFileList (const std::string& strSourcePath)\n{\n std::list<std::string> l;\n return l;\n}\n\n\nbool WinFtpClient::SetDirectory(string const & destination)\n{\n const string& cwd = BuildCommand<string>(\"CWD\", destination);\n if(! SendCommand(cwd))\n {\n printf(\"Error while sending command sequence: %d\\n\", WSAGetLastError());\n return false;\n }\n\n char strBuffer[256];\n ReceiveAnswer(strBuffer, 256);\n return (CheckExpectedResponse(strBuffer, \"250\"));\n}\n\nbool WinFtpClient::SendFile(const string& strSourceFile, const string& strTargetPath, ulong_t ulOffset)\n{\n printf(\"%s() --> Begin\\n\", __FUNCTION__);\n\n string strDir = strTargetPath.substr(0, strTargetPath.find_last_of('\/'));\n string strTargetFilename = strTargetPath.substr(strTargetPath.find_last_of('\/') + 1,\n strTargetPath.size() - 1);\n\n \/*\n * Get text from strSourceFile starting at ulOffset.\n *\/\n string buffer = \"\";\n ifstream myfile (strSourceFile.c_str(), std::ifstream::in);\n\n if (myfile && myfile.is_open())\n {\n myfile.seekg (0, ios::end); \/\/ Move position to ulOffset\n int fsize = myfile.tellg();\n\n if(ulOffset < fsize)\n {\n myfile.seekg (ulOffset, ios::beg); \/\/ Move position to offset\n buffer.resize(fsize - ulOffset); \/\/ Allocate memory\n myfile.read(&buffer[0], buffer.size()); \/\/ Read the contents from offset to end\n myfile.close();\n }\n else\n {\n printf(\"%s() Offset value is greater than the file size itself (%lu > %lu)\\n\", __FUNCTION__, ulOffset, fsize);\n return false;\n }\n\n }\n else\n {\n printf(\"%s(): Error opening source file = %\\n\", __FUNCTION__, strSourceFile.c_str());\n return false;\n }\n\n \/* Set destination directory *\/\n if(!SetDirectory(strDir))\n {\n printf(\"%s(): Destination directory not found = %\\n\", __FUNCTION__, strSourceFile.c_str());\n return false;\n }\n\n \/* Start passive mode *\/\n char strBuffer[256];\n int port = PassiveMode();\n if(port == 0)\n {\n printf(\"%s() Couldn't determine connection port number for data interchange\\n\", __FUNCTION__);\n printf(\"%s\\n\", strBuffer);\n return false;\n }\n\n printf(\"%s() Using port %d\\n\", __FUNCTION__, port);\n\n \/* Resume upload if proceed *\/\n if(!ResumeUpload(strTargetFilename, ulOffset))\n {\n printf(\"Error while sending REST + STOR sequence: %d\\n\", WSAGetLastError());\n }\n\n printf(\"%s() Resuming uploading at %d\\n\", __FUNCTION__, ulOffset);\n\n m_csData = GetSocket(m_strIpAddress, port);\n if (m_csData == INVALID_SOCKET)\n {\n printf(\"%s() Error connecting: %d\\n\", __FUNCTION__, WSAGetLastError());\n return false;\n }\n\n printf(\"\\nSending...\\n\");\n \/\/ int result = send(m_csData, buffer.c_str(), buffer.size(), 0) != SOCKET_ERROR ;\n bool bResult = SendBuffer(m_csData, buffer, buffer.size()) == 0;\n closesocket(m_csData);\n printf(\"%s() closed socket: %d\\n\", __FUNCTION__, WSAGetLastError());\n\n\n \/\/ Check that the server updated correctly the target file\n ReceiveAnswer(strBuffer, 256);\n\n if(! (bResult &= CheckExpectedResponse(strBuffer, \"226\")) )\n {\n printf(\"Unexpected server response: %s\\n\", strBuffer);\n }\n\n return bResult;\n}\n\n\n\/*\n * Protected functions\n *\/\nbool WinFtpClient::ResumeUpload(const string& targetFile, int offset)\n{\n \/\/ Build rest command\n const string& rest = BuildCommand<int>(\"REST\", offset);\n if(!SendCommand(rest))\n {\n printf(\"REST command failed!\\n\");\n return false;\n }\n char strBuffer[256];\n ReceiveAnswer(strBuffer, 256);\n\n if(!CheckExpectedResponse(strBuffer, \"350\"))\n {\n printf(\"Unexpected server response: %s\\n\", strBuffer);\n return false;\n }\n\n \/\/ Stor command\n const string& stor = BuildCommand<string>(\"STOR\", targetFile);\n if(!SendCommand(stor))\n {\n printf(\"STOR command failed!\\n\");\n return false;\n }\n\n ReceiveAnswer(strBuffer, 256);\n\n return (CheckExpectedResponse(strBuffer, \"150\"));\n}\n\nint WinFtpClient::PassiveMode()\n{\n \/\/ Set type as binary\/image\n if(!SendCommand(\"TYPE I\\r\\n\"))\n {\n printf(\"TYPE command failed!\\n\");\n return 0;\n }\n char strBuffer[256];\n ReceiveAnswer(strBuffer, 256);\n\n if(!CheckExpectedResponse(strBuffer, \"200\"))\n {\n printf(\"Unexpected server response: %s\\n\", strBuffer);\n return 0;\n }\n\n \/\/ Proceed with passive mode\n if(!SendCommand(\"PASV\\r\\n\"))\n {\n printf(\"PASV command failed!\\n\");\n return 0;\n }\n\n \/\/ Get port for passive mode\n ReceiveAnswer(strBuffer, 256);\n if(!CheckExpectedResponse(strBuffer, \"227\"))\n {\n printf(\"Unexpected server response: %s\\n\", strBuffer);\n return 0;\n }\n\n printf(\"Passive answer: %s\\n\", strBuffer);\n\n return ParsePortPassive(strBuffer);\n}\n\nbool WinFtpClient::SendCommand(const string& strCommand)\n{\n int iResult;\n \/\/ Send an initial buffer\n iResult = send(m_csCommand, strCommand.c_str(), (int) strCommand.size(), 0);\n return iResult != SOCKET_ERROR;\n}\n\nbool WinFtpClient::ReceiveAnswer(char* const strBuffer, int iLength)\n{\n \/\/ Clean the array before use\n memset(&strBuffer[0], 0, iLength);\n\n int iResult = -1;\n \/\/ Send an initial buffer\n iResult = recv(m_csCommand, strBuffer, iLength, 0);\n\n if (iResult == SOCKET_ERROR) {\n printf(\"Answer failed: %d\\n\", WSAGetLastError());\n return false;\n }\n\n printf(\"Bytes received: %d\\n\", iResult);\n\n return true;\n}\n\nbool WinFtpClient::CheckExpectedResponse(const string& response, const string& expected)\n{\n std::istringstream f(response);\n std::string line;\n std::string before;\n while (std::getline(f, line) && !f.eof())\n {\n before = line;\n }\n return (before.find(expected.c_str(), 0) != std::string::npos);\n}\nint WinFtpClient::ParsePortPassive(const string& pasvAnswer)\n{\n std::istringstream f(pasvAnswer);\n std::string line;\n while (std::getline(f, line)\n && !(line.find(\"227\", 0) != std::string::npos));\n\n if(line.empty())\n {\n return 0;\n }\n vector<std::string> elems;\n std::stringstream ss(line.substr(0, line.find(\")\")));\n std::string item;\n int count = 0;\n while (std::getline(ss, item, ',')) {\n elems.push_back(item);\n }\n\n int p1, p2 = 0;\n p1 = atoi(elems.at(4).c_str());\n p2 = atoi(elems.at(5).c_str());\n\n int port = p1 * 256 + p2;\n\n return port;\n}\n\nSOCKET WinFtpClient::GetSocket(const string& strIpAddress, ushort_t usPort)\n{\n \/\/Fill out the information needed to initialize a socket…\n SOCKADDR_IN target; \/\/Socket address information\n\n target.sin_family = AF_INET; \/\/ address family Internet\n target.sin_port = htons (usPort); \/\/Port to connect on\n target.sin_addr.s_addr = inet_addr (strIpAddress.c_str()); \/\/Target IP\n\n SOCKET mySocket = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP); \/\/Create socket\n if (mySocket != INVALID_SOCKET)\n {\n \/\/Try connecting...\n connect(mySocket, (SOCKADDR *)&target, sizeof(target));\n }\n\n return mySocket;\n}\n\n\/*\n * Private functions\n *\/\ntemplate <typename T>\nstring WinFtpClient::BuildCommand(const string& strCommand, const T& strParams)\n{\n std::stringstream ss;\n ss << strCommand << \" \" << strParams << \"\\r\\n\";\n return (ss.str());\n}\n\nint WinFtpClient::SendBuffer(SOCKET socket, const string& strBuffer, int iStillToSend)\n{\n int iRC = 0;\n int iSendStatus = 0;\n timeval SendTimeout;\n\n fd_set fds;\n\n FD_ZERO(&fds);\n FD_SET(socket, &fds);\n\n \/\/ Set timeout\n SendTimeout.tv_sec = 0;\n SendTimeout.tv_usec = 250000; \/\/ 250 ms\n\n \/\/ As long as we need to send bytes...\n char *pBuffer = new char[strBuffer.size()];\n memcpy(pBuffer, strBuffer.c_str(), strBuffer.size());\n while(iStillToSend > 0)\n {\n iRC = select(0, NULL, &fds, NULL, &SendTimeout);\n\n \/\/ Timeout\n if(!iRC)\n return -1;\n\n \/\/ Error\n if(iRC < 0)\n return WSAGetLastError();\n\n \/\/ Send some bytes\n iSendStatus = send(socket, pBuffer, iStillToSend, 0);\n\n \/\/ Error\n if(iSendStatus < 0)\n return WSAGetLastError();\n else\n {\n \/\/ Update buffer and counter\n iStillToSend -= iSendStatus;\n pBuffer += iSendStatus;\n }\n }\n\n if(pBuffer) delete[] pBuffer;\n return 0;\n}\n\n\n\n\n<commit_msg>Update WinFtpClient.cpp<commit_after>\/*\n * WinFtpClient.cpp\n *\n *\/\n\n#include \"WinFtpClient.h\"\n#include <iostream>\n#include <fstream>\n#include <sstream>\n#include <cstdio>\n#include <vector>\n\nusing namespace std;\n\n\/**\n * Default constructor: replaces WinFtpClient + subsequent call to SetParameters\n *\/\nWinFtpClient::WinFtpClient(const string& strServerIpAddress,\n const string& strLogin, const string& strPassword)\n: m_strIpAddress(strServerIpAddress)\n, m_strLogin (strLogin)\n, m_strPassword (strPassword)\n, m_bIsConnected(false)\n, m_ulOffset (0 )\n{\n m_csCommand = INVALID_SOCKET;\n m_csData = INVALID_SOCKET;\n}\n\n\/**\n * Default destructor. Closes all open connections, if possible.\n *\/\nWinFtpClient::~WinFtpClient()\n{\n Disconnect();\n}\n\n\/*\n * Public functions\n *\/\nbool WinFtpClient::Connect()\n{\n printf(\"%s() ftp:\/\/%s@%s\\n\", __FUNCTION__, m_strLogin.c_str(), m_strIpAddress.c_str());\n\n \/* Test configuration *\/\n if( m_bIsConnected )\n {\n printf(\"%s() : Already connected\\n\", __FUNCTION__);\n return m_bIsConnected;\n }\n\n if( m_strIpAddress.empty() )\n {\n printf(\"%s() : ERROR - Bad configuration or not ready\\n\", __FUNCTION__);\n return false;\n }\n\n m_bIsConnected = true;\n\n \/\/ Startup WinSock\n WORD wVersionRequested;\n WSADATA wsaData;\n wVersionRequested = MAKEWORD(2, 2);\n if(WSAStartup(wVersionRequested, &wsaData) != 0)\n {\n printf(\"WSAStartup error\\n\");\n return false;\n }\n\n \/\/ Create the commnad socket\n m_csCommand = GetSocket(m_strIpAddress, FTP_COMMAND_PORT);\n\n if (m_csCommand == INVALID_SOCKET)\n {\n printf(\"%s() Socket error: %ld\\n\", __FUNCTION__, WSAGetLastError());\n if (m_csCommand == WSAEISCONN)\n {\n printf(\"Already connected\\n\");\n }\n m_bIsConnected = false;\n }\n else\n {\n \/\/ Read response\n char strConn[256] = {0};\n ReceiveAnswer(strConn, 256);\n strConn[255] = 0;\n if(!CheckExpectedResponse(strConn, \"220\"))\n {\n closesocket(m_csCommand);\n printf(\"%s() Closing command socket. Unexpected server response: %s\\n\", __FUNCTION__, strConn);\n m_bIsConnected = false;\n }\n else\n {\n \/\/ Force login if user and password are not empty\n if(!m_strLogin.empty() && !m_strPassword.empty()\n && !Login())\n {\n m_bIsConnected = false;\n closesocket(m_csCommand);\n printf(\"%s() Closing command socket. Login failed: %ld\\n\", __FUNCTION__, WSAGetLastError());\n }\n }\n }\n\n\n return m_bIsConnected;\n}\n\n\nvoid WinFtpClient::Disconnect()\n{\n printf(\"%s()\\n\", __FUNCTION__);\n\n if( shutdown(m_csCommand, SD_BOTH) == SOCKET_ERROR )\n {\n printf(\"m_csCommand shutdown failed: %d\\n\", WSAGetLastError());\n }\n\n if ( shutdown(m_csData, SD_BOTH) == SOCKET_ERROR )\n {\n printf(\"m_csData shutdown failed: %d\\n\", WSAGetLastError());\n }\n\n WSACleanup();\n\n \/\/ Set flag to false\n m_bIsConnected = false;\n}\n\nbool WinFtpClient::Login()\n{\n printf(\"Login\\n\");\n\n SendCommand(\"USER \" + m_strLogin + \"\\r\\n\");\n Sleep(250);\n char strUser[256] = {0};\n ReceiveAnswer(strUser, 256);\n strUser[255] = 0;\n \/\/ TODO poner reintentos\n if (!CheckExpectedResponse(strUser, \"331\")) {\n printf(\"USER failed! -- \\\"%s\\\"\\n\", strUser);\n return false;\n }\n\n SendCommand(\"PASS \" + m_strPassword + \"\\r\\n\");\n Sleep(250);\n char strPass[256] = {0};\n ReceiveAnswer(strPass, 256);\n strPass[255] = 0;\n\n int retry = 0;\n if (!CheckExpectedResponse(strPass, \"230\")) {\n printf(\"PASS failed! -- \\\"%s\\\"\\n\", strPass);\n return false;\n }\n\n printf(\"\\\"%s\\\"\\n\", strPass);\n\n return true;\n}\n\nbool WinFtpClient::IsConnected() const\n{\n return m_bIsConnected;\n}\n\nvoid WinFtpClient::SetParameters (const std::string& strIpAddress, const std::string& strLogin, const std::string& strPassword)\n{\n m_strIpAddress = strIpAddress;\n m_strLogin = strLogin;\n m_strPassword = strPassword;\n}\n\nbool WinFtpClient::FileExists (const std::string&)\n{\n return true;\n}\n\n\/\/ TODO\nbool WinFtpClient::MoveFile (const std::string& strSourcePath, const std::string& strTargetPath )\n{\n return true;\n}\n\nbool WinFtpClient::GetFile (const std::string& strSourcePath, const std::string& strTargetPath, bool )\n{\n return true;\n}\n\nbool WinFtpClient::RetrFile (const std::string& strSource, const std::string& strTarget, bool bRemoveSource)\n{\n return true;\n}\n\nlist<std::string> WinFtpClient::GetFileList (const std::string& strSourcePath)\n{\n std::list<std::string> l;\n return l;\n}\n\n\nbool WinFtpClient::SetDirectory(string const & destination)\n{\n const string& cwd = BuildCommand<string>(\"CWD\", destination);\n if(! SendCommand(cwd))\n {\n printf(\"Error while sending command sequence: %d\\n\", WSAGetLastError());\n return false;\n }\n\n char strBuffer[256];\n ReceiveAnswer(strBuffer, 256);\n return (CheckExpectedResponse(strBuffer, \"250\"));\n}\n\nbool WinFtpClient::SendFile(const string& strSourceFile, const string& strTargetPath, unsigned long ulOffset)\n{\n printf(\"%s() --> Begin\\n\", __FUNCTION__);\n\n string strDir = strTargetPath.substr(0, strTargetPath.find_last_of('\/'));\n string strTargetFilename = strTargetPath.substr(strTargetPath.find_last_of('\/') + 1,\n strTargetPath.size() - 1);\n\n \/*\n * Get text from strSourceFile starting at ulOffset.\n *\/\n string buffer = \"\";\n ifstream myfile (strSourceFile.c_str(), std::ifstream::in);\n\n if (myfile && myfile.is_open())\n {\n myfile.seekg (0, ios::end); \/\/ Move position to ulOffset\n int fsize = myfile.tellg();\n\n if(ulOffset < fsize)\n {\n myfile.seekg (ulOffset, ios::beg); \/\/ Move position to offset\n buffer.resize(fsize - ulOffset); \/\/ Allocate memory\n myfile.read(&buffer[0], buffer.size()); \/\/ Read the contents from offset to end\n myfile.close();\n }\n else\n {\n printf(\"%s() Offset value is greater than the file size itself (%lu > %lu)\\n\", __FUNCTION__, ulOffset, fsize);\n return false;\n }\n\n }\n else\n {\n printf(\"%s(): Error opening source file = %\\n\", __FUNCTION__, strSourceFile.c_str());\n return false;\n }\n\n \/* Set destination directory *\/\n if(!SetDirectory(strDir))\n {\n printf(\"%s(): Destination directory not found = %\\n\", __FUNCTION__, strSourceFile.c_str());\n return false;\n }\n\n \/* Start passive mode *\/\n char strBuffer[256];\n int port = PassiveMode();\n if(port == 0)\n {\n printf(\"%s() Couldn't determine connection port number for data interchange\\n\", __FUNCTION__);\n printf(\"%s\\n\", strBuffer);\n return false;\n }\n\n printf(\"%s() Using port %d\\n\", __FUNCTION__, port);\n\n \/* Resume upload if proceed *\/\n if(!ResumeUpload(strTargetFilename, ulOffset))\n {\n printf(\"Error while sending REST + STOR sequence: %d\\n\", WSAGetLastError());\n }\n\n printf(\"%s() Resuming uploading at %d\\n\", __FUNCTION__, ulOffset);\n\n m_csData = GetSocket(m_strIpAddress, port);\n if (m_csData == INVALID_SOCKET)\n {\n printf(\"%s() Error connecting: %d\\n\", __FUNCTION__, WSAGetLastError());\n return false;\n }\n\n printf(\"\\nSending...\\n\");\n \/\/ int result = send(m_csData, buffer.c_str(), buffer.size(), 0) != SOCKET_ERROR ;\n bool bResult = SendBuffer(m_csData, buffer, buffer.size()) == 0;\n closesocket(m_csData);\n printf(\"%s() closed socket: %d\\n\", __FUNCTION__, WSAGetLastError());\n\n\n \/\/ Check that the server updated correctly the target file\n ReceiveAnswer(strBuffer, 256);\n\n if(! (bResult &= CheckExpectedResponse(strBuffer, \"226\")) )\n {\n printf(\"Unexpected server response: %s\\n\", strBuffer);\n }\n\n return bResult;\n}\n\n\n\/*\n * Protected functions\n *\/\nbool WinFtpClient::ResumeUpload(const string& targetFile, int offset)\n{\n \/\/ Build rest command\n const string& rest = BuildCommand<int>(\"REST\", offset);\n if(!SendCommand(rest))\n {\n printf(\"REST command failed!\\n\");\n return false;\n }\n char strBuffer[256];\n ReceiveAnswer(strBuffer, 256);\n\n if(!CheckExpectedResponse(strBuffer, \"350\"))\n {\n printf(\"Unexpected server response: %s\\n\", strBuffer);\n return false;\n }\n\n \/\/ Stor command\n const string& stor = BuildCommand<string>(\"STOR\", targetFile);\n if(!SendCommand(stor))\n {\n printf(\"STOR command failed!\\n\");\n return false;\n }\n\n ReceiveAnswer(strBuffer, 256);\n\n return (CheckExpectedResponse(strBuffer, \"150\"));\n}\n\nint WinFtpClient::PassiveMode()\n{\n \/\/ Set type as binary\/image\n if(!SendCommand(\"TYPE I\\r\\n\"))\n {\n printf(\"TYPE command failed!\\n\");\n return 0;\n }\n char strBuffer[256];\n ReceiveAnswer(strBuffer, 256);\n\n if(!CheckExpectedResponse(strBuffer, \"200\"))\n {\n printf(\"Unexpected server response: %s\\n\", strBuffer);\n return 0;\n }\n\n \/\/ Proceed with passive mode\n if(!SendCommand(\"PASV\\r\\n\"))\n {\n printf(\"PASV command failed!\\n\");\n return 0;\n }\n\n \/\/ Get port for passive mode\n ReceiveAnswer(strBuffer, 256);\n if(!CheckExpectedResponse(strBuffer, \"227\"))\n {\n printf(\"Unexpected server response: %s\\n\", strBuffer);\n return 0;\n }\n\n printf(\"Passive answer: %s\\n\", strBuffer);\n\n return ParsePortPassive(strBuffer);\n}\n\nbool WinFtpClient::SendCommand(const string& strCommand)\n{\n int iResult;\n \/\/ Send an initial buffer\n iResult = send(m_csCommand, strCommand.c_str(), (int) strCommand.size(), 0);\n return iResult != SOCKET_ERROR;\n}\n\nbool WinFtpClient::ReceiveAnswer(char* const strBuffer, int iLength)\n{\n \/\/ Clean the array before use\n memset(&strBuffer[0], 0, iLength);\n\n int iResult = -1;\n \/\/ Send an initial buffer\n iResult = recv(m_csCommand, strBuffer, iLength, 0);\n\n if (iResult == SOCKET_ERROR) {\n printf(\"Answer failed: %d\\n\", WSAGetLastError());\n return false;\n }\n\n printf(\"Bytes received: %d\\n\", iResult);\n\n return true;\n}\n\nbool WinFtpClient::CheckExpectedResponse(const string& response, const string& expected)\n{\n std::istringstream f(response);\n std::string line;\n std::string before;\n while (std::getline(f, line) && !f.eof())\n {\n before = line;\n }\n return (before.find(expected.c_str(), 0) != std::string::npos);\n}\nint WinFtpClient::ParsePortPassive(const string& pasvAnswer)\n{\n std::istringstream f(pasvAnswer);\n std::string line;\n while (std::getline(f, line)\n && !(line.find(\"227\", 0) != std::string::npos));\n\n if(line.empty())\n {\n return 0;\n }\n vector<std::string> elems;\n std::stringstream ss(line.substr(0, line.find(\")\")));\n std::string item;\n int count = 0;\n while (std::getline(ss, item, ',')) {\n elems.push_back(item);\n }\n\n int p1, p2 = 0;\n p1 = atoi(elems.at(4).c_str());\n p2 = atoi(elems.at(5).c_str());\n\n int port = p1 * 256 + p2;\n\n return port;\n}\n\nSOCKET WinFtpClient::GetSocket(const string& strIpAddress, ushort_t usPort)\n{\n \/\/Fill out the information needed to initialize a socket…\n SOCKADDR_IN target; \/\/Socket address information\n\n target.sin_family = AF_INET; \/\/ address family Internet\n target.sin_port = htons (usPort); \/\/Port to connect on\n target.sin_addr.s_addr = inet_addr (strIpAddress.c_str()); \/\/Target IP\n\n SOCKET mySocket = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP); \/\/Create socket\n if (mySocket != INVALID_SOCKET)\n {\n \/\/Try connecting...\n connect(mySocket, (SOCKADDR *)&target, sizeof(target));\n }\n\n return mySocket;\n}\n\n\/*\n * Private functions\n *\/\ntemplate <typename T>\nstring WinFtpClient::BuildCommand(const string& strCommand, const T& strParams)\n{\n std::stringstream ss;\n ss << strCommand << \" \" << strParams << \"\\r\\n\";\n return (ss.str());\n}\n\nint WinFtpClient::SendBuffer(SOCKET socket, const string& strBuffer, int iStillToSend)\n{\n int iRC = 0;\n int iSendStatus = 0;\n timeval SendTimeout;\n\n fd_set fds;\n\n FD_ZERO(&fds);\n FD_SET(socket, &fds);\n\n \/\/ Set timeout\n SendTimeout.tv_sec = 0;\n SendTimeout.tv_usec = 250000; \/\/ 250 ms\n\n \/\/ As long as we need to send bytes...\n char *pBuffer = new char[strBuffer.size()];\n memcpy(pBuffer, strBuffer.c_str(), strBuffer.size());\n while(iStillToSend > 0)\n {\n iRC = select(0, NULL, &fds, NULL, &SendTimeout);\n\n \/\/ Timeout\n if(!iRC)\n return -1;\n\n \/\/ Error\n if(iRC < 0)\n return WSAGetLastError();\n\n \/\/ Send some bytes\n iSendStatus = send(socket, pBuffer, iStillToSend, 0);\n\n \/\/ Error\n if(iSendStatus < 0)\n return WSAGetLastError();\n else\n {\n \/\/ Update buffer and counter\n iStillToSend -= iSendStatus;\n pBuffer += iSendStatus;\n }\n }\n\n if(pBuffer) delete[] pBuffer;\n return 0;\n}\n\n\n\n\n<|endoftext|>"} {"text":"<commit_before>\/** @file\n @brief Implementation\n\n @date 2016\n\n @author\n Sensics, Inc.\n <http:\/\/sensics.com\/osvr>\n*\/\n\n\/\/ Copyright 2016 Sensics, Inc.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n\/\/ Internal Includes\n#include \"TrackedBodyTarget.h\"\n#include \"TrackedBody.h\"\n#include \"LED.h\"\n#include \"cvToEigen.h\"\n#include \"HDKLedIdentifier.h\"\n#include \"PoseEstimatorTypes.h\"\n#include \"PoseEstimator_RANSAC.h\"\n#include \"PoseEstimator_SCAATKalman.h\"\n#include \"BodyTargetInterface.h\"\n\n\/\/ Library\/third-party includes\n#include <boost\/assert.hpp>\n#include <util\/Stride.h>\n\n\/\/ Standard includes\n#include <iostream>\n\nnamespace osvr {\nnamespace vbtracker {\n enum class TargetTrackingState { RANSAC, Kalman };\n struct TrackedBodyTarget::Impl {\n Impl(ConfigParams const ¶ms, BodyTargetInterface const &bodyIface)\n : bodyInterface(bodyIface), kalmanEstimator(params) {}\n BodyTargetInterface bodyInterface;\n LedGroup leds;\n LedPtrList usableLeds;\n LedIdentifierPtr identifier;\n RANSACPoseEstimator ransacEstimator;\n SCAATKalmanPoseEstimator kalmanEstimator;\n\n TargetTrackingState trackingState = TargetTrackingState::RANSAC;\n bool hasPrev = false;\n osvr::util::time::TimeValue lastEstimate;\n };\n\n namespace detail {\n inline BeaconStateVec\n createBeaconStateVec(ConfigParams const ¶ms,\n TargetSetupData const &setupData,\n Eigen::Vector3d &beaconOffset) {\n {\n \/\/\/ Compute or retrieve the beacon offset.\n if (params.offsetToCentroid) {\n Eigen::Vector3d beaconSum = Eigen::Vector3d::Zero();\n auto bNum = size_t{0};\n for (auto &beacon : setupData.locations) {\n beaconSum += cvToVector(beacon).cast<double>();\n bNum++;\n }\n beaconOffset = beaconSum \/ bNum;\n#if 0\n if (params.debug) {\n std::cout << \"Beacon centroid: \" << m_centroid.transpose()\n << std::endl;\n }\n#endif\n } else {\n beaconOffset =\n Eigen::Vector3d::Map(params.manualBeaconOffset);\n }\n }\n \/\/\/ Create the vector we'll return, and then the beacon state\n \/\/\/ objects.\n using size_type = TargetSetupData::size_type;\n const auto n = setupData.numBeacons();\n BeaconStateVec beacons;\n beacons.reserve(n);\n Eigen::Vector3d location;\n for (size_type i = 0; i < n; ++i) {\n location = cvToVector(setupData.locations[i]).cast<double>() -\n beaconOffset;\n BeaconStatePtr beacon(new BeaconState(\n location, Eigen::Vector3d::Constant(\n setupData.initialAutocalibrationErrors[i])\n .asDiagonal()));\n beacons.emplace_back(std::move(beacon));\n }\n return beacons;\n }\n } \/\/ namespace detail\n\n TrackedBodyTarget::TrackedBodyTarget(TrackedBody &body,\n BodyTargetInterface const &bodyIface,\n Eigen::Isometry3d const &targetToBody,\n TargetSetupData const &setupData,\n TargetId id)\n : m_body(body), m_id(id), m_targetToBody(targetToBody),\n m_beaconMeasurementVariance(setupData.baseMeasurementVariances),\n m_beaconFixed(setupData.isFixed),\n m_beaconEmissionDirection(setupData.emissionDirections),\n m_impl(new Impl(getParams(), bodyIface)) {\n\n \/\/\/ Create the beacon state objects and initialize the beacon offset.\n m_beacons = detail::createBeaconStateVec(getParams(), setupData,\n m_beaconOffset);\n {\n \/\/\/ Create the LED identifier\n std::unique_ptr<OsvrHdkLedIdentifier> identifier(\n new OsvrHdkLedIdentifier(setupData.patterns));\n m_impl->identifier = std::move(identifier);\n }\n\n#if 0\n \/\/\/ Dump the beacon locations to console\n auto numBeacons = getNumBeacons();\n for (UnderlyingBeaconIdType i = 0; i < numBeacons; ++i) {\n auto id = ZeroBasedBeaconId(i);\n std::cout << \"Beacon \" << i + 1 << \": \"\n << getBeaconAutocalibPosition(id).transpose() << \"\\n\";\n }\n#endif\n }\n\n TrackedBodyTarget::~TrackedBodyTarget() {}\n\n BodyTargetId TrackedBodyTarget::getQualifiedId() const {\n return BodyTargetId(getBody().getId(), getId());\n }\n\n Eigen::Vector3d\n TrackedBodyTarget::getBeaconAutocalibPosition(ZeroBasedBeaconId i) const {\n BOOST_ASSERT(!i.empty());\n BOOST_ASSERT_MSG(i.value() < getNumBeacons(),\n \"Beacon ID must be less than number of beacons.\");\n BOOST_ASSERT_MSG(i.value() >= 0,\n \"Beacon ID must not be a sentinel value!\");\n return m_beacons.at(i.value())->stateVector() + m_beaconOffset;\n }\n\n Eigen::Vector3d\n TrackedBodyTarget::getBeaconAutocalibVariance(ZeroBasedBeaconId i) const {\n BOOST_ASSERT(!i.empty());\n BOOST_ASSERT_MSG(i.value() < getNumBeacons(),\n \"Beacon ID must be less than number of beacons.\");\n BOOST_ASSERT_MSG(i.value() >= 0,\n \"Beacon ID must not be a sentinel value!\");\n return m_beacons.at(i.value())->errorCovariance().diagonal();\n }\n\n std::size_t TrackedBodyTarget::processLedMeasurements(\n LedMeasurementVec const &undistortedLeds) {\n \/\/ std::list<LedMeasurement> measurements{begin(undistortedLeds),\n \/\/ end(undistortedLeds)};\n LedMeasurementVec measurements{undistortedLeds};\n\n \/\/\/ Clear the \"usableLeds\" that will be populated in a later step, if we\n \/\/\/ get that far.\n m_impl->usableLeds.clear();\n\n auto usedMeasurements = std::size_t{0};\n const auto blobMoveThreshold = getParams().blobMoveThreshold;\n const auto blobsKeepIdentity = getParams().blobsKeepIdentity;\n auto &myLeds = m_impl->leds;\n\n const auto numBeacons = getNumBeacons();\n\n \/\/\/ In theory this shouldn't happen, but there are checks\n \/\/\/ scattered all over the code. Now we can say that it doesn't\n \/\/\/ happen because we won't let any bad values escape this\n \/\/\/ routine.\n auto handleOutOfRangeIds = [numBeacons](Led &led) {\n if (led.identified() &&\n makeZeroBased(led.getID()).value() > numBeacons) {\n std::cerr << \"Got a beacon claiming to be \"\n << led.getOneBasedID().value()\n << \" when we only have \" << numBeacons << \" beacons\"\n << std::endl;\n \/\/\/ @todo a kinder way of doing this? Right now this blows away\n \/\/\/ the measurement history\n led.markMisidentified();\n return true;\n }\n return false;\n };\n\n auto led = begin(myLeds);\n while (led != end(myLeds)) {\n led->resetUsed();\n handleOutOfRangeIds(*led);\n auto threshold = blobMoveThreshold * led->getMeasurement().diameter;\n auto nearest = led->nearest(measurements, threshold);\n if (nearest == end(measurements)) {\n \/\/ We have no blob corresponding to this LED, so we need\n \/\/ to delete this LED.\n led = myLeds.erase(led);\n } else {\n \/\/ Update the values in this LED and then go on to the\n \/\/ next one. Remove this blob from the list of\n \/\/ potential matches.\n led->addMeasurement(*nearest, blobsKeepIdentity);\n if (!handleOutOfRangeIds(*led)) {\n \/\/\/ If that measurement didn't cause this beacon to go awry,\n \/\/\/ then we'll actually handle the measurement and increment\n \/\/\/ used measurements.\n measurements.erase(nearest);\n \/\/\/ @todo do we increment this only if the LED is\n \/\/\/ recognized?\n usedMeasurements++;\n }\n ++led;\n }\n }\n\n \/\/ If we have any blobs that have not been associated with an\n \/\/ LED, then we add a new LED for each of them.\n \/\/ std::cout << \"Had \" << Leds.size() << \" LEDs, \" <<\n \/\/ keyPoints.size() << \" new ones available\" << std::endl;\n for (auto &remainingLed : measurements) {\n myLeds.emplace_back(m_impl->identifier.get(), remainingLed);\n }\n return usedMeasurements;\n }\n\n bool TrackedBodyTarget::updatePoseEstimateFromLeds(\n CameraParameters const &camParams,\n osvr::util::time::TimeValue const &tv) {\n\n \/\/\/ Do the initial filtering of the LED group to just the identified\n \/\/\/ ones before we pass it to an estimator.\n auto &usable = usableLeds();\n auto &leds = m_impl->leds;\n for (auto &led : leds) {\n if (!led.identified()) {\n continue;\n }\n usable.push_back(&led);\n }\n auto msg = [&]() -> std::ostream & {\n return std::cout << \"[Tracker Target \" << getQualifiedId() << \"] \";\n };\n \/\/\/ Must pre\/post correct the state by our offset :-\/\n \/\/\/ @todo make this state correction less hacky.\n m_impl->bodyInterface.state.position() += getStateCorrection();\n\n \/\/\/ @todo put this in the class\n bool permitKalman = false;\n\n \/\/\/ OK, now must decide who we talk to for pose estimation.\n \/\/\/ @todo move state machine logic elsewhere\n switch (m_impl->trackingState) {\n case TargetTrackingState::RANSAC: {\n m_hasPoseEstimate = m_impl->ransacEstimator(\n camParams, usable, m_beacons, m_impl->bodyInterface.state);\n\n if (m_hasPoseEstimate && permitKalman) {\n msg() << \"Entering SCAAT Kalman mode...\" << std::endl;\n m_impl->trackingState = TargetTrackingState::Kalman;\n }\n break;\n }\n\n case TargetTrackingState::Kalman: {\n auto videoDt =\n osvrTimeValueDurationSeconds(&tv, &m_impl->lastEstimate);\n\n auto params = SCAATKalmanPoseEstimator::InOutParams{\n m_beacons,\n m_beaconMeasurementVariance,\n m_beaconFixed,\n m_beaconEmissionDirection,\n getBody().getState(),\n getBody().getProcessModel()};\n m_hasPoseEstimate =\n m_impl->kalmanEstimator(camParams, usable, videoDt, params);\n \/\/\/ @todo exit conditions for kalman mode here...\n break;\n }\n }\n#if 0\n if (m_hasPoseEstimate) {\n msg() << getBody().getState().position().transpose() << std::endl;\n }\n#endif\n\n \/\/\/ Update our local target-specific timestamp\n m_impl->lastEstimate = tv;\n\n \/\/\/ Corresponding post-correction.\n m_impl->bodyInterface.state.position() -= getStateCorrection();\n\n return m_hasPoseEstimate;\n }\n\n Eigen::Vector3d TrackedBodyTarget::getStateCorrection() const {\n return m_impl->bodyInterface.state.getQuaternion() * m_beaconOffset;\n }\n\n ConfigParams const &TrackedBodyTarget::getParams() const {\n return m_body.getParams();\n }\n\n LedGroup const &TrackedBodyTarget::leds() const { return m_impl->leds; }\n\n LedPtrList const &TrackedBodyTarget::usableLeds() const {\n return m_impl->usableLeds;\n }\n\n LedGroup &TrackedBodyTarget::leds() { return m_impl->leds; }\n\n LedPtrList &TrackedBodyTarget::usableLeds() { return m_impl->usableLeds; }\n\n} \/\/ namespace vbtracker\n} \/\/ namespace osvr\n<commit_msg>Add striding print.<commit_after>\/** @file\n @brief Implementation\n\n @date 2016\n\n @author\n Sensics, Inc.\n <http:\/\/sensics.com\/osvr>\n*\/\n\n\/\/ Copyright 2016 Sensics, Inc.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n\/\/ Internal Includes\n#include \"TrackedBodyTarget.h\"\n#include \"TrackedBody.h\"\n#include \"LED.h\"\n#include \"cvToEigen.h\"\n#include \"HDKLedIdentifier.h\"\n#include \"PoseEstimatorTypes.h\"\n#include \"PoseEstimator_RANSAC.h\"\n#include \"PoseEstimator_SCAATKalman.h\"\n#include \"BodyTargetInterface.h\"\n\n\/\/ Library\/third-party includes\n#include <boost\/assert.hpp>\n#include <util\/Stride.h>\n\n\/\/ Standard includes\n#include <iostream>\n\nnamespace osvr {\nnamespace vbtracker {\n enum class TargetTrackingState { RANSAC, Kalman };\n struct TrackedBodyTarget::Impl {\n Impl(ConfigParams const ¶ms, BodyTargetInterface const &bodyIface)\n : bodyInterface(bodyIface), kalmanEstimator(params) {}\n BodyTargetInterface bodyInterface;\n LedGroup leds;\n LedPtrList usableLeds;\n LedIdentifierPtr identifier;\n RANSACPoseEstimator ransacEstimator;\n SCAATKalmanPoseEstimator kalmanEstimator;\n\n TargetTrackingState trackingState = TargetTrackingState::RANSAC;\n bool hasPrev = false;\n osvr::util::time::TimeValue lastEstimate;\n };\n\n namespace detail {\n inline BeaconStateVec\n createBeaconStateVec(ConfigParams const ¶ms,\n TargetSetupData const &setupData,\n Eigen::Vector3d &beaconOffset) {\n {\n \/\/\/ Compute or retrieve the beacon offset.\n if (params.offsetToCentroid) {\n Eigen::Vector3d beaconSum = Eigen::Vector3d::Zero();\n auto bNum = size_t{0};\n for (auto &beacon : setupData.locations) {\n beaconSum += cvToVector(beacon).cast<double>();\n bNum++;\n }\n beaconOffset = beaconSum \/ bNum;\n#if 0\n if (params.debug) {\n std::cout << \"Beacon centroid: \" << m_centroid.transpose()\n << std::endl;\n }\n#endif\n } else {\n beaconOffset =\n Eigen::Vector3d::Map(params.manualBeaconOffset);\n }\n }\n \/\/\/ Create the vector we'll return, and then the beacon state\n \/\/\/ objects.\n using size_type = TargetSetupData::size_type;\n const auto n = setupData.numBeacons();\n BeaconStateVec beacons;\n beacons.reserve(n);\n Eigen::Vector3d location;\n for (size_type i = 0; i < n; ++i) {\n location = cvToVector(setupData.locations[i]).cast<double>() -\n beaconOffset;\n BeaconStatePtr beacon(new BeaconState(\n location, Eigen::Vector3d::Constant(\n setupData.initialAutocalibrationErrors[i])\n .asDiagonal()));\n beacons.emplace_back(std::move(beacon));\n }\n return beacons;\n }\n } \/\/ namespace detail\n\n TrackedBodyTarget::TrackedBodyTarget(TrackedBody &body,\n BodyTargetInterface const &bodyIface,\n Eigen::Isometry3d const &targetToBody,\n TargetSetupData const &setupData,\n TargetId id)\n : m_body(body), m_id(id), m_targetToBody(targetToBody),\n m_beaconMeasurementVariance(setupData.baseMeasurementVariances),\n m_beaconFixed(setupData.isFixed),\n m_beaconEmissionDirection(setupData.emissionDirections),\n m_impl(new Impl(getParams(), bodyIface)) {\n\n \/\/\/ Create the beacon state objects and initialize the beacon offset.\n m_beacons = detail::createBeaconStateVec(getParams(), setupData,\n m_beaconOffset);\n {\n \/\/\/ Create the LED identifier\n std::unique_ptr<OsvrHdkLedIdentifier> identifier(\n new OsvrHdkLedIdentifier(setupData.patterns));\n m_impl->identifier = std::move(identifier);\n }\n\n#if 0\n \/\/\/ Dump the beacon locations to console\n auto numBeacons = getNumBeacons();\n for (UnderlyingBeaconIdType i = 0; i < numBeacons; ++i) {\n auto id = ZeroBasedBeaconId(i);\n std::cout << \"Beacon \" << i + 1 << \": \"\n << getBeaconAutocalibPosition(id).transpose() << \"\\n\";\n }\n#endif\n }\n\n TrackedBodyTarget::~TrackedBodyTarget() {}\n\n BodyTargetId TrackedBodyTarget::getQualifiedId() const {\n return BodyTargetId(getBody().getId(), getId());\n }\n\n Eigen::Vector3d\n TrackedBodyTarget::getBeaconAutocalibPosition(ZeroBasedBeaconId i) const {\n BOOST_ASSERT(!i.empty());\n BOOST_ASSERT_MSG(i.value() < getNumBeacons(),\n \"Beacon ID must be less than number of beacons.\");\n BOOST_ASSERT_MSG(i.value() >= 0,\n \"Beacon ID must not be a sentinel value!\");\n return m_beacons.at(i.value())->stateVector() + m_beaconOffset;\n }\n\n Eigen::Vector3d\n TrackedBodyTarget::getBeaconAutocalibVariance(ZeroBasedBeaconId i) const {\n BOOST_ASSERT(!i.empty());\n BOOST_ASSERT_MSG(i.value() < getNumBeacons(),\n \"Beacon ID must be less than number of beacons.\");\n BOOST_ASSERT_MSG(i.value() >= 0,\n \"Beacon ID must not be a sentinel value!\");\n return m_beacons.at(i.value())->errorCovariance().diagonal();\n }\n\n std::size_t TrackedBodyTarget::processLedMeasurements(\n LedMeasurementVec const &undistortedLeds) {\n \/\/ std::list<LedMeasurement> measurements{begin(undistortedLeds),\n \/\/ end(undistortedLeds)};\n LedMeasurementVec measurements{undistortedLeds};\n\n \/\/\/ Clear the \"usableLeds\" that will be populated in a later step, if we\n \/\/\/ get that far.\n m_impl->usableLeds.clear();\n\n auto usedMeasurements = std::size_t{0};\n const auto blobMoveThreshold = getParams().blobMoveThreshold;\n const auto blobsKeepIdentity = getParams().blobsKeepIdentity;\n auto &myLeds = m_impl->leds;\n\n const auto numBeacons = getNumBeacons();\n\n \/\/\/ In theory this shouldn't happen, but there are checks\n \/\/\/ scattered all over the code. Now we can say that it doesn't\n \/\/\/ happen because we won't let any bad values escape this\n \/\/\/ routine.\n auto handleOutOfRangeIds = [numBeacons](Led &led) {\n if (led.identified() &&\n makeZeroBased(led.getID()).value() > numBeacons) {\n std::cerr << \"Got a beacon claiming to be \"\n << led.getOneBasedID().value()\n << \" when we only have \" << numBeacons << \" beacons\"\n << std::endl;\n \/\/\/ @todo a kinder way of doing this? Right now this blows away\n \/\/\/ the measurement history\n led.markMisidentified();\n return true;\n }\n return false;\n };\n\n auto led = begin(myLeds);\n while (led != end(myLeds)) {\n led->resetUsed();\n handleOutOfRangeIds(*led);\n auto threshold = blobMoveThreshold * led->getMeasurement().diameter;\n auto nearest = led->nearest(measurements, threshold);\n if (nearest == end(measurements)) {\n \/\/ We have no blob corresponding to this LED, so we need\n \/\/ to delete this LED.\n led = myLeds.erase(led);\n } else {\n \/\/ Update the values in this LED and then go on to the\n \/\/ next one. Remove this blob from the list of\n \/\/ potential matches.\n led->addMeasurement(*nearest, blobsKeepIdentity);\n if (!handleOutOfRangeIds(*led)) {\n \/\/\/ If that measurement didn't cause this beacon to go awry,\n \/\/\/ then we'll actually handle the measurement and increment\n \/\/\/ used measurements.\n measurements.erase(nearest);\n \/\/\/ @todo do we increment this only if the LED is\n \/\/\/ recognized?\n usedMeasurements++;\n }\n ++led;\n }\n }\n\n \/\/ If we have any blobs that have not been associated with an\n \/\/ LED, then we add a new LED for each of them.\n \/\/ std::cout << \"Had \" << Leds.size() << \" LEDs, \" <<\n \/\/ keyPoints.size() << \" new ones available\" << std::endl;\n for (auto &remainingLed : measurements) {\n myLeds.emplace_back(m_impl->identifier.get(), remainingLed);\n }\n return usedMeasurements;\n }\n\n bool TrackedBodyTarget::updatePoseEstimateFromLeds(\n CameraParameters const &camParams,\n osvr::util::time::TimeValue const &tv) {\n\n \/\/\/ Do the initial filtering of the LED group to just the identified\n \/\/\/ ones before we pass it to an estimator.\n auto &usable = usableLeds();\n auto &leds = m_impl->leds;\n for (auto &led : leds) {\n if (!led.identified()) {\n continue;\n }\n usable.push_back(&led);\n }\n auto msg = [&]() -> std::ostream & {\n return std::cout << \"[Tracker Target \" << getQualifiedId() << \"] \";\n };\n \/\/\/ Must pre\/post correct the state by our offset :-\/\n \/\/\/ @todo make this state correction less hacky.\n m_impl->bodyInterface.state.position() += getStateCorrection();\n\n \/\/\/ @todo put this in the class\n bool permitKalman = false;\n\n \/\/\/ OK, now must decide who we talk to for pose estimation.\n \/\/\/ @todo move state machine logic elsewhere\n switch (m_impl->trackingState) {\n case TargetTrackingState::RANSAC: {\n m_hasPoseEstimate = m_impl->ransacEstimator(\n camParams, usable, m_beacons, m_impl->bodyInterface.state);\n\n if (m_hasPoseEstimate && permitKalman) {\n msg() << \"Entering SCAAT Kalman mode...\" << std::endl;\n m_impl->trackingState = TargetTrackingState::Kalman;\n }\n break;\n }\n\n case TargetTrackingState::Kalman: {\n auto videoDt =\n osvrTimeValueDurationSeconds(&tv, &m_impl->lastEstimate);\n\n auto params = SCAATKalmanPoseEstimator::InOutParams{\n m_beacons,\n m_beaconMeasurementVariance,\n m_beaconFixed,\n m_beaconEmissionDirection,\n getBody().getState(),\n getBody().getProcessModel()};\n m_hasPoseEstimate =\n m_impl->kalmanEstimator(camParams, usable, videoDt, params);\n \/\/\/ @todo exit conditions for kalman mode here...\n break;\n }\n }\n if (m_hasPoseEstimate) {\n static ::util::Stride s(13);\n if (++s) {\n msg() << getBody().getState().position().transpose()\n << std::endl;\n }\n }\n\n \/\/\/ Update our local target-specific timestamp\n m_impl->lastEstimate = tv;\n\n \/\/\/ Corresponding post-correction.\n m_impl->bodyInterface.state.position() -= getStateCorrection();\n\n return m_hasPoseEstimate;\n }\n\n Eigen::Vector3d TrackedBodyTarget::getStateCorrection() const {\n return m_impl->bodyInterface.state.getQuaternion() * m_beaconOffset;\n }\n\n ConfigParams const &TrackedBodyTarget::getParams() const {\n return m_body.getParams();\n }\n\n LedGroup const &TrackedBodyTarget::leds() const { return m_impl->leds; }\n\n LedPtrList const &TrackedBodyTarget::usableLeds() const {\n return m_impl->usableLeds;\n }\n\n LedGroup &TrackedBodyTarget::leds() { return m_impl->leds; }\n\n LedPtrList &TrackedBodyTarget::usableLeds() { return m_impl->usableLeds; }\n\n} \/\/ namespace vbtracker\n} \/\/ namespace osvr\n<|endoftext|>"} {"text":"<commit_before>#include \"Timer.h\"\n#include \"Navio\/PWM.h\"\n#include \"Navio\/RCInput.h\"\n#include \"Navio\/RGBled.h\"\n#include \"Navio\/Util.h\"\n#include <algorithm>\n#include <limits.h>\n#include <stdlib.h>\n#include <time.h>\n\n\nstatic const int inpThrottle = 0, minThrottle = 1120, maxThrottle = 1880;\nstatic const int inpRoll = 1, rightRoll = 1110, leftRoll = 1890;\nstatic const int inpPitch = 2, upPitch = 1110, downPitch = 1890;\nstatic const int inpYaw = 3, rightYaw = 1110, leftYaw = 1890;\n\nstatic const int inpCenter = 1500;\nstatic const int inpCenterR = 5;\n\nstatic const int outTiltCamera = 0;\nstatic const int outLeftMotor = 1;\nstatic const int outRightMotor = 2;\nstatic const int outPanCamera = 3;\n\nstatic const float outMin = 1.;\nstatic const float outNeutral = 1.5;\nstatic const float outMax = 2.;\n\n\nstatic const int refreshRate = 30;\n\n\nstatic void InitPWMChannel(PWM& pwm, int ch) {\n pwm.init(ch);\n pwm.enable(ch);\n pwm.set_period(ch, 50);\n}\n\nint main(int \/*argc*\/, char** \/*argv*\/) {\n if (! check_apm()) {\n system(\"sudo modprobe bcm2835-v4l2\");\n\n PWM pwm;\n RCInput rc;\n Timer timer;\n\n InitPWMChannel(pwm, outLeftMotor);\n InitPWMChannel(pwm, outRightMotor);\n rc.init();\n\n timer.Start();\n for (;;) {\n\n int steer = rc.read(inpRoll);\n float rightSteerScale = std::min(std::max(-1., 2. * (steer - rightRoll) \/ (inpCenter - inpCenterR - rightRoll) - 1.), 1.);\n float leftSteerScale = std::min(std::max(-1., 2. * (steer - leftRoll) \/ (inpCenter + inpCenterR - leftRoll ) - 1.), 1.);\n float throttleScale = float(rc.read(inpThrottle) - minThrottle) \/ (maxThrottle - minThrottle);\n\n pwm.set_duty_cycle(outLeftMotor, leftSteerScale * throttleScale * (outMax - outNeutral) + outNeutral);\n pwm.set_duty_cycle(outRightMotor, rightSteerScale * throttleScale * (outMax - outNeutral) + outNeutral);\n\n struct timespec sleep = {0, 1000 * timer.NextSleep(refreshRate, INT_MAX)};\n if (sleep.tv_nsec > 0) {\n nanosleep(&sleep, NULL);\n }\n }\n }\n return 0;\n}\n<commit_msg>center the camera<commit_after>#include \"Timer.h\"\n#include \"Navio\/PWM.h\"\n#include \"Navio\/RCInput.h\"\n#include \"Navio\/RGBled.h\"\n#include \"Navio\/Util.h\"\n#include <algorithm>\n#include <limits.h>\n#include <stdlib.h>\n#include <time.h>\n\n\nstatic const int inpThrottle = 0, minThrottle = 1120, maxThrottle = 1880;\nstatic const int inpRoll = 1, rightRoll = 1110, leftRoll = 1890;\nstatic const int inpPitch = 2, upPitch = 1110, downPitch = 1890;\nstatic const int inpYaw = 3, rightYaw = 1110, leftYaw = 1890;\n\nstatic const int inpCenter = 1500;\nstatic const int inpCenterR = 5;\n\nstatic const int outTiltCamera = 0;\nstatic const int outLeftMotor = 1;\nstatic const int outRightMotor = 2;\nstatic const int outPanCamera = 3;\n\nstatic const float outMin = 1.;\nstatic const float outNeutral = 1.5;\nstatic const float outMax = 2.;\n\n\nstatic const int refreshRate = 30;\n\n\nstatic void InitPWMChannel(PWM& pwm, int ch) {\n pwm.init(ch);\n pwm.enable(ch);\n pwm.set_period(ch, 50);\n}\n\nint main(int \/*argc*\/, char** \/*argv*\/) {\n if (! check_apm()) {\n system(\"sudo modprobe bcm2835-v4l2\");\n\n PWM pwm;\n RCInput rc;\n Timer timer;\n\n InitPWMChannel(pwm, outLeftMotor);\n InitPWMChannel(pwm, outRightMotor);\n InitPWMChannel(pwm, outTiltCamera);\n InitPWMChannel(pwm, outPanCamera);\n rc.init();\n\n pwm.set_duty_cycle(outPanCamera, outNeutral);\n pwm.set_duty_cycle(outTiltCamera, outNeutral);\n\n timer.Start();\n for (;;) {\n\n int steer = rc.read(inpRoll);\n float rightSteerScale = std::min(std::max(-1., 2. * (steer - rightRoll) \/ (inpCenter - inpCenterR - rightRoll) - 1.), 1.);\n float leftSteerScale = std::min(std::max(-1., 2. * (steer - leftRoll) \/ (inpCenter + inpCenterR - leftRoll ) - 1.), 1.);\n float throttleScale = float(rc.read(inpThrottle) - minThrottle) \/ (maxThrottle - minThrottle);\n\n pwm.set_duty_cycle(outLeftMotor, leftSteerScale * throttleScale * (outMax - outNeutral) + outNeutral);\n pwm.set_duty_cycle(outRightMotor, rightSteerScale * throttleScale * (outMax - outNeutral) + outNeutral);\n\n struct timespec sleep = {0, 1000 * timer.NextSleep(refreshRate, INT_MAX)};\n if (sleep.tv_nsec > 0) {\n nanosleep(&sleep, NULL);\n }\n }\n }\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>#ifndef MJOLNIR_CORE_G_BAOAB_LANGEVIN_INTEGRATOR_HPP\n#define MJOLNIR_CORE_G_BAOAB_LANGEVIN_INTEGRATOR_HPP\n#include <mjolnir\/core\/SimulatorTraits.hpp>\n#include <mjolnir\/core\/RandomNumberGenerator.hpp>\n#include <mjolnir\/core\/System.hpp>\n#include <mjolnir\/core\/ForceField.hpp>\n#include <mjolnir\/core\/SystemMotionRemover.hpp>\n#include <mjolnir\/core\/Unit.hpp>\n#include <mjolnir\/util\/logger.hpp>\n\nnamespace mjolnir\n{\n\n\/\/ g-BAOAB Langevin integrator developed by the following papers\n\/\/ Leimkuhler B., Matthews C., Proc. R. Soc. A Math. Phys. Eng. Sci. (2016)\ntemplate<typename traitsT>\nclass GBAOABLangevinIntegrator\n{\n public:\n using traits_type = traitsT;\n using real_type = typename traits_type::real_type;\n using coordinate_type = typename traits_type::coordinate_type;\n using indices_type = std::array<std::size_t, 2>;\n using constraints_type = std::vector<std::pair<indices_type, real_type>>;\n using system_type = System<traitsT>;\n using forcefield_type = ForceField<traitsT>;\n using rng_type = RandomNumberGenerator<traits_type>;\n using remover_type = SystemMotionRemover<traits_type>;\n\n public:\n\n GBAOABLangevinIntegrator(const real_type dt, std::vector<real_type>&& gamma,\n constraints_type&& constraint, remover_type&& remover,\n std::size_t correction_iter_num, std::size_t max_iter_correction,\n real_type correction_tolerance)\n : dt_(dt), halfdt_(dt \/ 2), gammas_(std::move(gamma)),\n exp_gamma_dt_(gammas_.size()), noise_coeff_ (gammas_.size()),\n constraints_(constraint),\n square_v0s_(constraint.size()),\n r_reduced_mass_(constraint.size()),\n remover_(std::move(remover)),\n correction_iter_num_(correction_iter_num),\n correction_max_iter_(max_iter_correction),\n correction_tolerance_dt_(correction_tolerance\/ dt),\n correction_tolerance_dt_itr_(correction_tolerance\/ dt * correction_iter_num),\n dt_in_correction_(dt * 0.5 \/ correction_iter_num_),\n r_dt_in_correction_(1 \/ dt_in_correction_),\n old_position_(gammas_.size()),\n old_pos_rattle_(gammas_.size())\n {}\n ~GBAOABLangevinIntegrator() = default;\n\n void initialize(system_type& sys, forcefield_type& ff, rng_type& rng);\n\n real_type step(const real_type time, system_type& sys, forcefield_type& ff,\n rng_type& rng);\n\n void update(const system_type& sys)\n {\n if(!sys.has_attribute(\"temperature\"))\n {\n throw std::out_of_range(\"mjolnir::g-BAOABLangevinIntegrator: \"\n \"Langevin Integrator requires reference temperature, but \"\n \"`temperature` is not found in `system.attribute`.\");\n }\n this->temperature_ = sys.attribute(\"temperature\");\n this->reset_parameter(sys);\n return;\n }\n\n real_type delta_t() const noexcept {return dt_;}\n std::vector<real_type> const& parameters() const noexcept {return gammas_;}\n\n private:\n\n void reset_parameter(const system_type& sys) noexcept\n {\n const auto kBT = physics::constants<real_type>::kB() * this->temperature_;\n for(std::size_t i=0; i<sys.size(); ++i)\n {\n const auto gamma = this->gammas_.at(i);\n const auto gamma_dt = -1 * gamma * this->dt_;\n this->exp_gamma_dt_.at(i) = std::exp(gamma_dt);\n this->noise_coeff_ .at(i) = std::sqrt(\n kBT * (1 - std::exp(2 * gamma_dt)) * sys.rmass(i));\n }\n return;\n };\n\n coordinate_type gen_R(rng_type& rng) noexcept\n {\n const auto x = rng.gaussian();\n const auto y = rng.gaussian();\n const auto z = rng.gaussian();\n return math::make_coordinate<coordinate_type>(x, y, z);\n }\n\n void correct_coordinate(system_type& sys, const real_type tolerance)\n {\n MJOLNIR_GET_DEFAULT_LOGGER();\n\n std::size_t rattle_step = 0;\n while(rattle_step<correction_max_iter_)\n {\n bool corrected = false;\n for(std::size_t i=0; i<this->constraints_.size(); ++i)\n {\n const auto& constraint = constraints_[i];\n const auto& indices = constraint.first;\n auto& p1 = sys.position(indices[0]);\n auto& p2 = sys.position(indices[1]);\n auto& v1 = sys.velocity(indices[0]);\n auto& v2 = sys.velocity(indices[1]);\n auto& op1 = this->old_pos_rattle_[indices[0]];\n auto& op2 = this->old_pos_rattle_[indices[1]];\n auto& rm1 = sys.rmass(indices[0]);\n auto& rm2 = sys.rmass(indices[1]);\n\n const auto dp = p2 - p1;\n const real_type dp2 = math::length_sq(dp);\n const real_type missmatch = square_v0s_[i] - dp2;\n\n if(abs(missmatch) > tolerance)\n {\n corrected = true;\n const auto old_dp = op2 - op1;\n const real_type dot_old_new_dp = math::dot_product(old_dp, dp);\n const real_type lambda =\n 0.5 * missmatch * r_reduced_mass_[i] * dot_old_new_dp;\n const coordinate_type correction_force = lambda * old_dp;\n const coordinate_type correction_vec1 = correction_force * rm1;\n const coordinate_type correction_vec2 = correction_force * rm2;\n p1 -= correction_vec1;\n p2 += correction_vec2;\n v1 -= correction_vec1 * r_dt_in_correction_;\n v2 += correction_vec2 * r_dt_in_correction_;\n op1 = p1;\n op2 = p2;\n }\n }\n\n if(!corrected) break;\n\n ++rattle_step;\n }\n\n if(rattle_step >= correction_max_iter_)\n {\n MJOLNIR_LOG_WARN(\"rattle iteration number exceeds rattle max iteration\");\n }\n\n return;\n }\n\n void correct_velocity(system_type& sys, const real_type tolerance)\n {\n MJOLNIR_GET_DEFAULT_LOGGER();\n\n std::size_t rattle_step = 0;\n while(rattle_step<correction_max_iter_)\n {\n bool corrected = false;\n for(std::size_t i=0; i<this->constraints_.size(); ++i)\n {\n const auto& constraint = constraints_[i];\n const auto& indices = constraint.first;\n auto& p1 = sys.position(indices[0]);\n auto& p2 = sys.position(indices[1]);\n auto& v1 = sys.velocity(indices[0]);\n auto& v2 = sys.velocity(indices[1]);\n auto& rm1 = sys.rmass(indices[0]);\n auto& rm2 = sys.rmass(indices[1]);\n\n const auto pos_diff = p2 - p1;\n const auto vel_diff = v2 - v1;\n const real_type dot_pdvd = math::dot_product(pos_diff, vel_diff);\n const real_type lambda = dot_pdvd * r_reduced_mass_[i] * square_v0s_[i];\n\n if(std::abs(lambda) > tolerance)\n {\n const auto correction_vec = lambda * pos_diff;\n v1 += correction_vec * rm1;\n v2 -= correction_vec * rm2;\n corrected = true;\n }\n }\n\n if(!corrected) break;\n\n ++rattle_step;\n }\n\n if(rattle_step >= correction_max_iter_)\n {\n MJOLNIR_LOG_WARN(\"rattle iteration number exceeds rattle max iteration.\");\n }\n return;\n }\n\n private:\n real_type dt_;\n real_type halfdt_;\n std::vector<real_type> gammas_;\n std::vector<real_type> exp_gamma_dt_;\n std::vector<real_type> noise_coeff_;\n constraints_type constraints_; \/\/ pair of index pair and v0.\n std::vector<real_type> square_v0s_;\n std::vector<real_type> r_reduced_mass_;\n remover_type remover_;\n\n real_type temperature_;\n std::size_t correction_iter_num_;\n std::size_t correction_max_iter_;\n real_type correction_tolerance_dt_;\n real_type correction_tolerance_dt_itr_;\n real_type dt_in_correction_;\n real_type r_dt_in_correction_;\n\n std::vector<coordinate_type> old_position_;\n std::vector<coordinate_type> old_pos_rattle_;\n\n};\n\ntemplate<typename traitsT>\nvoid GBAOABLangevinIntegrator<traitsT>::initialize(\n system_type& system, forcefield_type& ff, rng_type&)\n{\n MJOLNIR_GET_DEFAULT_LOGGER();\n MJOLNIR_LOG_FUNCTION();\n \n \/\/ calculate parameters for each particles\n this->update(system);\n\n \/\/ calculate force\n for(std::size_t i=0; i<system.size(); ++i)\n {\n system.force(i) = math::make_coordinate<coordinate_type>(0, 0, 0);\n }\n ff.calc_force(system);\n\n \/\/ buffering old position\n for(std::size_t i=0; i<system.size(); ++i)\n {\n old_position_[i] = system.position(i);\n }\n\n for(std::size_t i=0; i<constraints_.size(); ++i)\n {\n \/\/ calculate square v0\n square_v0s_[i] = std::pow(constraints_[i].second, 2);\n\n \/\/ calculate inverse reduced mass\n const auto& constraint = constraints_[i];\n std::size_t first_idx = constraint.first[0];\n std::size_t second_idx = constraint.first[1];\n r_reduced_mass_[i] = system.rmass(first_idx) + system.rmass(second_idx);\n }\n\n return;\n}\n\ntemplate<typename traitsT>\ntypename GBAOABLangevinIntegrator<traitsT>::real_type\nGBAOABLangevinIntegrator<traitsT>::step(\n const real_type time, system_type& sys, forcefield_type& ff, rng_type& rng)\n{\n \/\/ B step\n for(std::size_t i=0; i<sys.size(); ++i)\n {\n sys.velocity(i) += this->halfdt_ * sys.rmass(i) * sys.force(i);\n }\n \/\/ velocity correction step\n correct_velocity(sys, correction_tolerance_dt_);\n \/\/ A step\n for(std::size_t correction_step=0; correction_step<correction_iter_num_; ++correction_step)\n {\n for(std::size_t i=0; i<sys.size(); ++i)\n {\n this->old_pos_rattle_[i] = sys.position(i);\n sys.position(i) += this->dt_in_correction_ * sys.velocity(i);\n }\n \/\/ coordinate correction step\n \/\/ TODO\n \/\/ velocity correction step\n correct_velocity(sys, correction_tolerance_dt_itr_);\n }\n \/\/ O step\n for(std::size_t i=0; i<sys.size(); ++i)\n {\n sys.velocity(i) *= this->exp_gamma_dt_[i]; \/\/ *= exp(- gamma dt)\n sys.velocity(i) += this->noise_coeff_[i] * this->gen_R(rng);\n }\n \/\/ velocity correction step\n \/\/ TODO\n \/\/ A step\n for(std::size_t correction_step=0; correction_step<correction_iter_num_; ++correction_step)\n {\n for(std::size_t i=0; i<sys.size(); ++i)\n {\n this->old_pos_rattle_[i] = sys.position(i);\n sys.position(i) += this->dt_in_correction_ * sys.velocity(i);\n }\n \/\/ coordinate correction step\n \/\/ TODO\n \/\/ velocity correction step\n correct_velocity(sys, correction_tolerance_dt_itr_);\n }\n \/\/ update neighbor list; reduce margin, reconstruct the list if needed;\n real_type largest_disp2(0.0);\n for(std::size_t i=0; i<sys.size(); ++i)\n {\n coordinate_type displacement = sys.position(i) - this->old_position_[i];\n largest_disp2 = std::max(largest_disp2, math::length_sq(displacement));\n sys.position(i) = sys.adjust_position(sys.position(i));\n\n \/\/ reset force\n sys.force(i) = math::make_coordinate<coordinate_type>(0, 0, 0);\n }\n\n ff.reduce_margin(2 * std::sqrt(largest_disp2), sys);\n\n \/\/ B step\n ff.calc_force(sys);\n for(std::size_t i=0; i<sys.size(); ++i)\n {\n sys.velocity(i) += this->halfdt_ * sys.rmass(i) * sys.force(i);\n }\n \/\/ velocity correction step\n correct_velocity(sys, correction_tolerance_dt_);\n\n remover_.remove(sys);\n\n for(std::size_t i=0; i<sys.size(); ++i)\n {\n this->old_position_[i] = sys.position(i);\n }\n\n return time + dt_;\n}\n\n} \/\/ mjolnir\n#endif \/* MJOLNIR_CORE_G_BAOAB_LANGEVIN_INTEGRATOR_HPP *\/\n<commit_msg>feat: implement coordinate correction function<commit_after>#ifndef MJOLNIR_CORE_G_BAOAB_LANGEVIN_INTEGRATOR_HPP\n#define MJOLNIR_CORE_G_BAOAB_LANGEVIN_INTEGRATOR_HPP\n#include <mjolnir\/core\/SimulatorTraits.hpp>\n#include <mjolnir\/core\/RandomNumberGenerator.hpp>\n#include <mjolnir\/core\/System.hpp>\n#include <mjolnir\/core\/ForceField.hpp>\n#include <mjolnir\/core\/SystemMotionRemover.hpp>\n#include <mjolnir\/core\/Unit.hpp>\n#include <mjolnir\/util\/logger.hpp>\n\nnamespace mjolnir\n{\n\n\/\/ g-BAOAB Langevin integrator developed by the following papers\n\/\/ Leimkuhler B., Matthews C., Proc. R. Soc. A Math. Phys. Eng. Sci. (2016)\ntemplate<typename traitsT>\nclass GBAOABLangevinIntegrator\n{\n public:\n using traits_type = traitsT;\n using real_type = typename traits_type::real_type;\n using coordinate_type = typename traits_type::coordinate_type;\n using indices_type = std::array<std::size_t, 2>;\n using constraints_type = std::vector<std::pair<indices_type, real_type>>;\n using system_type = System<traitsT>;\n using forcefield_type = ForceField<traitsT>;\n using rng_type = RandomNumberGenerator<traits_type>;\n using remover_type = SystemMotionRemover<traits_type>;\n\n public:\n\n GBAOABLangevinIntegrator(const real_type dt, std::vector<real_type>&& gamma,\n constraints_type&& constraint, remover_type&& remover,\n std::size_t correction_iter_num, std::size_t max_iter_correction,\n real_type correction_tolerance)\n : dt_(dt), halfdt_(dt \/ 2), gammas_(std::move(gamma)),\n exp_gamma_dt_(gammas_.size()), noise_coeff_ (gammas_.size()),\n constraints_(constraint),\n square_v0s_(constraint.size()),\n r_reduced_mass_(constraint.size()),\n remover_(std::move(remover)),\n correction_iter_num_(correction_iter_num),\n correction_max_iter_(max_iter_correction),\n correction_tolerance_dt_(correction_tolerance\/ dt),\n correction_tolerance_dt_itr_(correction_tolerance\/ dt * correction_iter_num),\n dt_in_correction_(dt * 0.5 \/ correction_iter_num_),\n r_dt_in_correction_(1 \/ dt_in_correction_),\n old_position_(gammas_.size()),\n old_pos_rattle_(gammas_.size())\n {}\n ~GBAOABLangevinIntegrator() = default;\n\n void initialize(system_type& sys, forcefield_type& ff, rng_type& rng);\n\n real_type step(const real_type time, system_type& sys, forcefield_type& ff,\n rng_type& rng);\n\n void update(const system_type& sys)\n {\n if(!sys.has_attribute(\"temperature\"))\n {\n throw std::out_of_range(\"mjolnir::g-BAOABLangevinIntegrator: \"\n \"Langevin Integrator requires reference temperature, but \"\n \"`temperature` is not found in `system.attribute`.\");\n }\n this->temperature_ = sys.attribute(\"temperature\");\n this->reset_parameter(sys);\n return;\n }\n\n real_type delta_t() const noexcept {return dt_;}\n std::vector<real_type> const& parameters() const noexcept {return gammas_;}\n\n private:\n\n void reset_parameter(const system_type& sys) noexcept\n {\n const auto kBT = physics::constants<real_type>::kB() * this->temperature_;\n for(std::size_t i=0; i<sys.size(); ++i)\n {\n const auto gamma = this->gammas_.at(i);\n const auto gamma_dt = -1 * gamma * this->dt_;\n this->exp_gamma_dt_.at(i) = std::exp(gamma_dt);\n this->noise_coeff_ .at(i) = std::sqrt(\n kBT * (1 - std::exp(2 * gamma_dt)) * sys.rmass(i));\n }\n return;\n };\n\n coordinate_type gen_R(rng_type& rng) noexcept\n {\n const auto x = rng.gaussian();\n const auto y = rng.gaussian();\n const auto z = rng.gaussian();\n return math::make_coordinate<coordinate_type>(x, y, z);\n }\n\n void correct_coordinate(system_type& sys, const real_type tolerance)\n {\n MJOLNIR_GET_DEFAULT_LOGGER();\n\n std::size_t rattle_step = 0;\n while(rattle_step<correction_max_iter_)\n {\n bool corrected = false;\n for(std::size_t i=0; i<this->constraints_.size(); ++i)\n {\n const auto& constraint = constraints_[i];\n const auto& indices = constraint.first;\n auto& p1 = sys.position(indices[0]);\n auto& p2 = sys.position(indices[1]);\n auto& v1 = sys.velocity(indices[0]);\n auto& v2 = sys.velocity(indices[1]);\n auto& op1 = this->old_pos_rattle_[indices[0]];\n auto& op2 = this->old_pos_rattle_[indices[1]];\n auto& rm1 = sys.rmass(indices[0]);\n auto& rm2 = sys.rmass(indices[1]);\n\n const auto dp = p2 - p1;\n const real_type dp2 = math::length_sq(dp);\n const real_type missmatch = square_v0s_[i] - dp2;\n\n if(abs(missmatch) > tolerance)\n {\n corrected = true;\n const auto old_dp = op2 - op1;\n const real_type dot_old_new_dp = math::dot_product(old_dp, dp);\n const real_type lambda =\n 0.5 * missmatch * r_reduced_mass_[i] * dot_old_new_dp;\n const coordinate_type correction_force = lambda * old_dp;\n const coordinate_type correction_vec1 = correction_force * rm1;\n const coordinate_type correction_vec2 = correction_force * rm2;\n p1 -= correction_vec1;\n p2 += correction_vec2;\n v1 -= correction_vec1 * r_dt_in_correction_;\n v2 += correction_vec2 * r_dt_in_correction_;\n op1 = p1;\n op2 = p2;\n }\n }\n\n if(!corrected) break;\n\n ++rattle_step;\n }\n\n if(rattle_step >= correction_max_iter_)\n {\n MJOLNIR_LOG_WARN(\"rattle iteration number exceeds rattle max iteration\");\n }\n\n return;\n }\n\n void correct_velocity(system_type& sys, const real_type tolerance)\n {\n MJOLNIR_GET_DEFAULT_LOGGER();\n\n std::size_t rattle_step = 0;\n while(rattle_step<correction_max_iter_)\n {\n bool corrected = false;\n for(std::size_t i=0; i<this->constraints_.size(); ++i)\n {\n const auto& constraint = constraints_[i];\n const auto& indices = constraint.first;\n auto& p1 = sys.position(indices[0]);\n auto& p2 = sys.position(indices[1]);\n auto& v1 = sys.velocity(indices[0]);\n auto& v2 = sys.velocity(indices[1]);\n auto& rm1 = sys.rmass(indices[0]);\n auto& rm2 = sys.rmass(indices[1]);\n\n const auto pos_diff = p2 - p1;\n const auto vel_diff = v2 - v1;\n const real_type dot_pdvd = math::dot_product(pos_diff, vel_diff);\n const real_type lambda = dot_pdvd * r_reduced_mass_[i] * square_v0s_[i];\n\n if(std::abs(lambda) > tolerance)\n {\n const auto correction_vec = lambda * pos_diff;\n v1 += correction_vec * rm1;\n v2 -= correction_vec * rm2;\n corrected = true;\n }\n }\n\n if(!corrected) break;\n\n ++rattle_step;\n }\n\n if(rattle_step >= correction_max_iter_)\n {\n MJOLNIR_LOG_WARN(\"rattle iteration number exceeds rattle max iteration.\");\n }\n return;\n }\n\n private:\n real_type dt_;\n real_type halfdt_;\n std::vector<real_type> gammas_;\n std::vector<real_type> exp_gamma_dt_;\n std::vector<real_type> noise_coeff_;\n constraints_type constraints_; \/\/ pair of index pair and v0.\n std::vector<real_type> square_v0s_;\n std::vector<real_type> r_reduced_mass_;\n remover_type remover_;\n\n real_type temperature_;\n std::size_t correction_iter_num_;\n std::size_t correction_max_iter_;\n real_type correction_tolerance_dt_;\n real_type correction_tolerance_dt_itr_;\n real_type dt_in_correction_;\n real_type r_dt_in_correction_;\n\n std::vector<coordinate_type> old_position_;\n std::vector<coordinate_type> old_pos_rattle_;\n\n};\n\ntemplate<typename traitsT>\nvoid GBAOABLangevinIntegrator<traitsT>::initialize(\n system_type& system, forcefield_type& ff, rng_type&)\n{\n MJOLNIR_GET_DEFAULT_LOGGER();\n MJOLNIR_LOG_FUNCTION();\n \n \/\/ calculate parameters for each particles\n this->update(system);\n\n \/\/ calculate force\n for(std::size_t i=0; i<system.size(); ++i)\n {\n system.force(i) = math::make_coordinate<coordinate_type>(0, 0, 0);\n }\n ff.calc_force(system);\n\n \/\/ buffering old position\n for(std::size_t i=0; i<system.size(); ++i)\n {\n old_position_[i] = system.position(i);\n }\n\n for(std::size_t i=0; i<constraints_.size(); ++i)\n {\n \/\/ calculate square v0\n square_v0s_[i] = std::pow(constraints_[i].second, 2);\n\n \/\/ calculate inverse reduced mass\n const auto& constraint = constraints_[i];\n std::size_t first_idx = constraint.first[0];\n std::size_t second_idx = constraint.first[1];\n r_reduced_mass_[i] = system.rmass(first_idx) + system.rmass(second_idx);\n }\n\n return;\n}\n\ntemplate<typename traitsT>\ntypename GBAOABLangevinIntegrator<traitsT>::real_type\nGBAOABLangevinIntegrator<traitsT>::step(\n const real_type time, system_type& sys, forcefield_type& ff, rng_type& rng)\n{\n \/\/ B step\n for(std::size_t i=0; i<sys.size(); ++i)\n {\n sys.velocity(i) += this->halfdt_ * sys.rmass(i) * sys.force(i);\n }\n correct_velocity(sys, correction_tolerance_dt_);\n\n \/\/ A step\n for(std::size_t correction_step=0; correction_step<correction_iter_num_; ++correction_step)\n {\n for(std::size_t i=0; i<sys.size(); ++i)\n {\n this->old_pos_rattle_[i] = sys.position(i);\n sys.position(i) += this->dt_in_correction_ * sys.velocity(i);\n }\n correct_coordinate(sys, correction_tolerance_dt_itr_);\n correct_velocity(sys, correction_tolerance_dt_itr_);\n }\n\n \/\/ O step\n for(std::size_t i=0; i<sys.size(); ++i)\n {\n sys.velocity(i) *= this->exp_gamma_dt_[i]; \/\/ *= exp(- gamma dt)\n sys.velocity(i) += this->noise_coeff_[i] * this->gen_R(rng);\n }\n correct_velocity(sys, correction_tolerance_dt_);\n\n \/\/ A step\n for(std::size_t correction_step=0; correction_step<correction_iter_num_; ++correction_step)\n {\n for(std::size_t i=0; i<sys.size(); ++i)\n {\n this->old_pos_rattle_[i] = sys.position(i);\n sys.position(i) += this->dt_in_correction_ * sys.velocity(i);\n }\n correct_coordinate(sys, correction_tolerance_dt_itr_);\n correct_velocity(sys, correction_tolerance_dt_itr_);\n }\n \/\/ update neighbor list; reduce margin, reconstruct the list if needed;\n real_type largest_disp2(0.0);\n for(std::size_t i=0; i<sys.size(); ++i)\n {\n coordinate_type displacement = sys.position(i) - this->old_position_[i];\n largest_disp2 = std::max(largest_disp2, math::length_sq(displacement));\n sys.position(i) = sys.adjust_position(sys.position(i));\n\n \/\/ reset force\n sys.force(i) = math::make_coordinate<coordinate_type>(0, 0, 0);\n }\n\n ff.reduce_margin(2 * std::sqrt(largest_disp2), sys);\n\n \/\/ B step\n ff.calc_force(sys);\n for(std::size_t i=0; i<sys.size(); ++i)\n {\n sys.velocity(i) += this->halfdt_ * sys.rmass(i) * sys.force(i);\n }\n correct_velocity(sys, correction_tolerance_dt_);\n\n remover_.remove(sys);\n\n for(std::size_t i=0; i<sys.size(); ++i)\n {\n this->old_position_[i] = sys.position(i);\n }\n\n return time + dt_;\n}\n\n} \/\/ mjolnir\n#endif \/* MJOLNIR_CORE_G_BAOAB_LANGEVIN_INTEGRATOR_HPP *\/\n<|endoftext|>"} {"text":"<commit_before>\/**\n * Copyright (c) 2015 - The CM Authors <legal@clickmatcher.com>\n * All Rights Reserved.\n *\n * This file is CONFIDENTIAL -- Distribution or duplication of this material or\n * the information contained herein is strictly forbidden unless prior written\n * permission is obtained.\n *\/\n#define BOOST_NO_CXX11_NUMERIC_LIMITS 1\n#include <stdlib.h>\n#include <unistd.h>\n#include <signal.h>\n#include \"fnord-base\/io\/filerepository.h\"\n#include \"fnord-base\/io\/fileutil.h\"\n#include \"fnord-base\/application.h\"\n#include \"fnord-base\/logging.h\"\n#include \"fnord-base\/random.h\"\n#include \"fnord-base\/thread\/eventloop.h\"\n#include \"fnord-base\/thread\/threadpool.h\"\n#include \"fnord-base\/wallclock.h\"\n#include \"fnord-rpc\/ServerGroup.h\"\n#include \"fnord-rpc\/RPC.h\"\n#include \"fnord-rpc\/RPCClient.h\"\n#include \"fnord-base\/cli\/flagparser.h\"\n#include \"fnord-json\/json.h\"\n#include \"fnord-json\/jsonrpc.h\"\n#include \"fnord-http\/httprouter.h\"\n#include \"fnord-http\/httpserver.h\"\n#include \"fnord-feeds\/FeedService.h\"\n#include \"fnord-feeds\/RemoteFeedFactory.h\"\n#include \"fnord-feeds\/RemoteFeedReader.h\"\n#include \"fnord-base\/stats\/statsdagent.h\"\n#include \"fnord-fts\/fts.h\"\n#include \"fnord-fts\/fts_common.h\"\n#include \"fnord-mdb\/MDB.h\"\n#include \"CustomerNamespace.h\"\n#include \"FeatureSchema.h\"\n#include \"FeatureIndexWriter.h\"\n#include \"IndexRequest.h\"\n#include \"IndexBuild.h\"\n\nusing namespace cm;\nusing namespace fnord;\n\nstd::atomic<bool> cm_indexbuild_shutdown;\n\nvoid quit(int n) {\n cm_indexbuild_shutdown = true;\n}\n\nint main(int argc, const char** argv) {\n Application::init();\n Application::logToStderr();\n\n \/* shutdown hook *\/\n cm_indexbuild_shutdown = false;\n struct sigaction sa;\n memset(&sa, 0, sizeof(struct sigaction));\n sa.sa_handler = quit;\n sigaction(SIGTERM, &sa, NULL);\n sigaction(SIGQUIT, &sa, NULL);\n sigaction(SIGINT, &sa, NULL);\n\n cli::FlagParser flags;\n\n flags.defineFlag(\n \"index\",\n cli::FlagParser::T_STRING,\n true,\n NULL,\n NULL,\n \"index dir\",\n \"<path>\");\n\n flags.defineFlag(\n \"statsd_addr\",\n fnord::cli::FlagParser::T_STRING,\n false,\n NULL,\n \"127.0.0.1:8192\",\n \"Statsd addr\",\n \"<addr>\");\n\n flags.defineFlag(\n \"batch_size\",\n fnord::cli::FlagParser::T_INTEGER,\n false,\n NULL,\n \"2048\",\n \"batch_size\",\n \"<num>\");\n\n flags.defineFlag(\n \"buffer_size\",\n fnord::cli::FlagParser::T_INTEGER,\n false,\n NULL,\n \"8192\",\n \"buffer_size\",\n \"<num>\");\n\n flags.defineFlag(\n \"db_commit_size\",\n fnord::cli::FlagParser::T_INTEGER,\n false,\n NULL,\n \"1024\",\n \"db_commit_size\",\n \"<num>\");\n\n flags.defineFlag(\n \"db_commit_interval\",\n fnord::cli::FlagParser::T_INTEGER,\n false,\n NULL,\n \"5\",\n \"db_commit_interval\",\n \"<num>\");\n\n flags.defineFlag(\n \"dbsize\",\n fnord::cli::FlagParser::T_INTEGER,\n false,\n NULL,\n \"128\",\n \"max sessiondb size\",\n \"<MB>\");\n\n flags.defineFlag(\n \"loglevel\",\n fnord::cli::FlagParser::T_STRING,\n false,\n NULL,\n \"INFO\",\n \"loglevel\",\n \"<level>\");\n\n flags.parseArgv(argc, argv);\n\n Logger::get()->setMinimumLogLevel(\n strToLogLevel(flags.getString(\"loglevel\")));\n\n \/* set up feature schema *\/\n FeatureSchema feature_schema;\n feature_schema.registerFeature(\"shop_id\", 1, 1);\n feature_schema.registerFeature(\"category1\", 2, 1);\n feature_schema.registerFeature(\"category2\", 3, 1);\n feature_schema.registerFeature(\"category3\", 4, 1);\n feature_schema.registerFeature(\"title~de\", 5, 2);\n\n \/* start event loop *\/\n fnord::thread::EventLoop ev;\n\n auto evloop_thread = std::thread([&ev] {\n ev.run();\n });\n\n \/* set up rpc client *\/\n HTTPRPCClient rpc_client(&ev);\n\n \/* start stats reporting *\/\n fnord::stats::StatsdAgent statsd_agent(\n fnord::net::InetAddr::resolve(flags.getString(\"statsd_addr\")),\n 10 * fnord::kMicrosPerSecond);\n\n statsd_agent.start();\n\n \/* set up indexbuild *\/\n size_t batch_size = flags.getInt(\"batch_size\");\n size_t buffer_size = flags.getInt(\"buffer_size\");\n size_t db_commit_size = flags.getInt(\"db_commit_size\");\n size_t db_commit_interval = flags.getInt(\"db_commit_interval\");\n\n fnord::logInfo(\n \"cm.indexbuild\",\n \"Starting cm-indexbuild with:\\n index=$0\\n batch_size=$1\\n\" \\\n \" buffer_size=$2\\n db_commit_size=$3\\n db_commit_interval=$4\\n\"\n \" max_dbsize=$5MB\",\n flags.getString(\"index\"),\n batch_size,\n buffer_size,\n db_commit_size,\n db_commit_interval,\n flags.getInt(\"dbsize\"));\n\n \/* stats *\/\n fnord::stats::Counter<uint64_t> stat_documents_indexed_total_;\n fnord::stats::Counter<uint64_t> stat_documents_indexed_success_;\n fnord::stats::Counter<uint64_t> stat_documents_indexed_error_;\n\n exportStat(\n \"\/cm-indexbuild\/global\/documents_indexed_total\",\n &stat_documents_indexed_total_,\n fnord::stats::ExportMode::EXPORT_DELTA);\n\n exportStat(\n \"\/cm-indexbuild\/global\/documents_indexed_success\",\n &stat_documents_indexed_success_,\n fnord::stats::ExportMode::EXPORT_DELTA);\n\n exportStat(\n \"\/cm-indexbuild\/global\/documents_indexed_error\",\n &stat_documents_indexed_error_,\n fnord::stats::ExportMode::EXPORT_DELTA);\n\n \/* open featuredb db *\/\n auto featuredb_path = FileUtil::joinPaths(flags.getString(\"index\"), \"db\");\n FileUtil::mkdir_p(featuredb_path);\n auto featuredb = mdb::MDB::open(featuredb_path);\n featuredb->setMaxSize(1000000 * flags.getInt(\"dbsize\"));\n cm::FeatureIndexWriter feature_index_writer(&feature_schema);\n\n \/* open full index *\/\n auto fullindex_path = FileUtil::joinPaths(flags.getString(\"index\"), \"docs\");\n FileUtil::mkdir_p(fullindex_path);\n cm::FullIndex full_index(fullindex_path);\n\n \/* open lucene index *\/\n \/*\n auto index_path = FileUtil::joinPaths(\n cmdata_path,\n StringUtil::format(\"index\/$0\/fts\", cmcustomer));\n FileUtil::mkdir_p(index_path);\n\n auto index_writer =\n fts::newLucene<fts::IndexWriter>(\n fts::FSDirectory::open(StringUtil::convertUTF8To16(index_path)),\n fts::newLucene<fts::StandardAnalyzer>(\n fts::LuceneVersion::LUCENE_CURRENT),\n true,\n fts::IndexWriter::MaxFieldLengthLIMITED);\n *\/\n\n cm::IndexBuild index_build(&feature_index_writer, &full_index);\n\n \/* set up input feed reader *\/\n feeds::RemoteFeedReader feed_reader(&rpc_client);\n feed_reader.setMaxSpread(3600 * 24 * 30 * kMicrosPerSecond);\n\n HashMap<String, URI> input_feeds;\n auto cmcustomer = \"dawanda\";\n input_feeds.emplace(\n StringUtil::format(\n \"$0.index_requests.feedserver01.nue01.production.fnrd.net\",\n cmcustomer),\n URI(\"http:\/\/s01.nue01.production.fnrd.net:7001\/rpc\"));\n input_feeds.emplace(\n StringUtil::format(\n \"$0.index_requests.feedserver02.nue01.production.fnrd.net\",\n cmcustomer),\n URI(\"http:\/\/s02.nue01.production.fnrd.net:7001\/rpc\"));\n\n \/* resume from last offset *\/\n auto txn = featuredb->startTransaction(true);\n try {\n for (const auto& input_feed : input_feeds) {\n uint64_t offset = 0;\n\n auto last_offset = txn->get(\n StringUtil::format(\"__indexfeed_offset~$0\", input_feed.first));\n\n if (!last_offset.isEmpty()) {\n offset = std::stoul(last_offset.get().toString());\n }\n\n fnord::logInfo(\n \"cm.indexbuild\",\n \"Adding source feed:\\n feed=$0\\n url=$1\\n offset: $2\",\n input_feed.first,\n input_feed.second.toString(),\n offset);\n\n feed_reader.addSourceFeed(\n input_feed.second,\n input_feed.first,\n offset,\n batch_size,\n buffer_size);\n }\n\n txn->abort();\n } catch (...) {\n txn->abort();\n throw;\n }\n\n fnord::logInfo(\"cm.indexbuild\", \"Resuming IndexBuild...\");\n \/\/ index document\n\/*\n auto doc = fts::newLucene<fts::Document>();\n doc->add(\n fts::newLucene<fts::Field>(\n L\"keywords\",\n L\"my fnordy document\",\n fts::Field::STORE_NO,\n fts::Field::INDEX_ANALYZED));\n\n index_writer->addDocument(doc);\n*\/\n\n\n \/\/index_writer->commit();\n \/\/index_writer->close();\n\n \/\/ simple search\n \/*\n auto index_reader = fts::IndexReader::open(\n fts::FSDirectory::open(StringUtil::convertUTF8To16(index_path)),\n true);\n\n auto searcher = fts::newLucene<fts::IndexSearcher>(index_reader);\n\n auto analyzer = fts::newLucene<fts::StandardAnalyzer>(\n fts::LuceneVersion::LUCENE_CURRENT);\n\n auto query_parser = fts::newLucene<fts::QueryParser>(\n fts::LuceneVersion::LUCENE_CURRENT,\n L\"keywords\",\n analyzer);\n\n auto collector = fts::TopScoreDocCollector::create(\n 500,\n false);\n\n auto query = query_parser->parse(L\"fnordy\");\n\n searcher->search(query, collector);\n fnord::iputs(\"found $0 documents\", collector->getTotalHits());\n *\/\n\n DateTime last_iter;\n uint64_t rate_limit_micros = db_commit_interval * kMicrosPerSecond;\n\n for (;;) {\n last_iter = WallClock::now();\n feed_reader.fillBuffers();\n int i = 0;\n for (; i < db_commit_size; ++i) {\n auto entry = feed_reader.fetchNextEntry();\n\n if (entry.isEmpty()) {\n break;\n }\n\n try {\n stat_documents_indexed_total_.incr(1);\n fnord::logTrace(\"cm.indexbuild\", \"Indexing: $0\", entry.get().data);\n auto index_req = json::fromJSON<cm::IndexRequest>(entry.get().data);\n index_build.updateDocument(index_req);\n stat_documents_indexed_success_.incr(1);\n } catch (const std::exception& e) {\n stat_documents_indexed_error_.incr(1);\n fnord::logError(\n \"cm.indexbuild\",\n e,\n \"error while indexing document: $0\",\n entry.get().data);\n }\n }\n\n auto stream_offsets = feed_reader.streamOffsets();\n String stream_offsets_str;\n\n index_build.commit();\n\n auto txn = featuredb->startTransaction();\n\n for (const auto& soff : stream_offsets) {\n txn->update(\n StringUtil::format(\"__indexfeed_offset~$0\", soff.first),\n StringUtil::toString(soff.second));\n\n stream_offsets_str +=\n StringUtil::format(\"\\n offset[$0]=$1\", soff.first, soff.second);\n }\n\n fnord::logInfo(\n \"cm.indexbuild\",\n \"IndexBuild comitting...$0\",\n stream_offsets_str);\n\n txn->commit();\n\n if (cm_indexbuild_shutdown.load() == true) {\n break;\n }\n\n auto etime = WallClock::now().unixMicros() - last_iter.unixMicros();\n if (i < 1 && etime < rate_limit_micros) {\n usleep(rate_limit_micros - etime);\n }\n }\n\n ev.shutdown();\n \/\/evloop_thread.join();\n\n fnord::logInfo(\"cm.indexbuild\", \"IndexBuild exiting...\");\n exit(0); \/\/ FIXPAUL\n\n return 0;\n}\n\n<commit_msg>move all the feed subscription code into a separate method in cm-indexbuild<commit_after>\/**\n * Copyright (c) 2015 - The CM Authors <legal@clickmatcher.com>\n * All Rights Reserved.\n *\n * This file is CONFIDENTIAL -- Distribution or duplication of this material or\n * the information contained herein is strictly forbidden unless prior written\n * permission is obtained.\n *\/\n#define BOOST_NO_CXX11_NUMERIC_LIMITS 1\n#include <stdlib.h>\n#include <unistd.h>\n#include <signal.h>\n#include \"fnord-base\/io\/filerepository.h\"\n#include \"fnord-base\/io\/fileutil.h\"\n#include \"fnord-base\/application.h\"\n#include \"fnord-base\/logging.h\"\n#include \"fnord-base\/random.h\"\n#include \"fnord-base\/thread\/eventloop.h\"\n#include \"fnord-base\/thread\/threadpool.h\"\n#include \"fnord-base\/wallclock.h\"\n#include \"fnord-rpc\/ServerGroup.h\"\n#include \"fnord-rpc\/RPC.h\"\n#include \"fnord-rpc\/RPCClient.h\"\n#include \"fnord-base\/cli\/flagparser.h\"\n#include \"fnord-json\/json.h\"\n#include \"fnord-json\/jsonrpc.h\"\n#include \"fnord-http\/httprouter.h\"\n#include \"fnord-http\/httpserver.h\"\n#include \"fnord-feeds\/FeedService.h\"\n#include \"fnord-feeds\/RemoteFeedFactory.h\"\n#include \"fnord-feeds\/RemoteFeedReader.h\"\n#include \"fnord-base\/stats\/statsdagent.h\"\n#include \"fnord-fts\/fts.h\"\n#include \"fnord-fts\/fts_common.h\"\n#include \"fnord-mdb\/MDB.h\"\n#include \"CustomerNamespace.h\"\n#include \"FeatureSchema.h\"\n#include \"FeatureIndexWriter.h\"\n#include \"IndexRequest.h\"\n#include \"IndexBuild.h\"\n\nusing namespace cm;\nusing namespace fnord;\n\nstd::atomic<bool> cm_indexbuild_shutdown;\n\n\/* stats *\/\nfnord::stats::Counter<uint64_t> stat_documents_indexed_total_;\nfnord::stats::Counter<uint64_t> stat_documents_indexed_success_;\nfnord::stats::Counter<uint64_t> stat_documents_indexed_error_;\n\nvoid quit(int n) {\n cm_indexbuild_shutdown = true;\n}\n\nvoid buildIndexFromFeed(\n IndexBuild* index_build,\n RefPtr<mdb::MDB> featuredb,\n const cli::FlagParser& flags) {\n size_t batch_size = flags.getInt(\"batch_size\");\n size_t buffer_size = flags.getInt(\"buffer_size\");\n size_t db_commit_size = flags.getInt(\"db_commit_size\");\n size_t db_commit_interval = flags.getInt(\"db_commit_interval\");\n\n \/* start event loop *\/\n fnord::thread::EventLoop ev;\n\n auto evloop_thread = std::thread([&ev] {\n ev.run();\n });\n\n \/* set up rpc client *\/\n HTTPRPCClient rpc_client(&ev);\n\n feeds::RemoteFeedReader feed_reader(&rpc_client);\n feed_reader.setMaxSpread(3600 * 24 * 30 * kMicrosPerSecond);\n\n HashMap<String, URI> input_feeds;\n auto cmcustomer = \"dawanda\";\n input_feeds.emplace(\n StringUtil::format(\n \"$0.index_requests.feedserver01.nue01.production.fnrd.net\",\n cmcustomer),\n URI(\"http:\/\/s01.nue01.production.fnrd.net:7001\/rpc\"));\n input_feeds.emplace(\n StringUtil::format(\n \"$0.index_requests.feedserver02.nue01.production.fnrd.net\",\n cmcustomer),\n URI(\"http:\/\/s02.nue01.production.fnrd.net:7001\/rpc\"));\n\n \/* resume from last offset *\/\n auto txn = featuredb->startTransaction(true);\n try {\n for (const auto& input_feed : input_feeds) {\n uint64_t offset = 0;\n\n auto last_offset = txn->get(\n StringUtil::format(\"__indexfeed_offset~$0\", input_feed.first));\n\n if (!last_offset.isEmpty()) {\n offset = std::stoul(last_offset.get().toString());\n }\n\n fnord::logInfo(\n \"cm.indexbuild\",\n \"Adding source feed:\\n feed=$0\\n url=$1\\n offset: $2\",\n input_feed.first,\n input_feed.second.toString(),\n offset);\n\n feed_reader.addSourceFeed(\n input_feed.second,\n input_feed.first,\n offset,\n batch_size,\n buffer_size);\n }\n\n txn->abort();\n } catch (...) {\n txn->abort();\n throw;\n }\n\n fnord::logInfo(\"cm.indexbuild\", \"Resuming IndexBuild...\");\n\n DateTime last_iter;\n uint64_t rate_limit_micros = db_commit_interval * kMicrosPerSecond;\n\n for (;;) {\n last_iter = WallClock::now();\n feed_reader.fillBuffers();\n int i = 0;\n for (; i < db_commit_size; ++i) {\n auto entry = feed_reader.fetchNextEntry();\n\n if (entry.isEmpty()) {\n break;\n }\n\n try {\n stat_documents_indexed_total_.incr(1);\n fnord::logTrace(\"cm.indexbuild\", \"Indexing: $0\", entry.get().data);\n auto index_req = json::fromJSON<cm::IndexRequest>(entry.get().data);\n index_build->updateDocument(index_req);\n stat_documents_indexed_success_.incr(1);\n } catch (const std::exception& e) {\n stat_documents_indexed_error_.incr(1);\n fnord::logError(\n \"cm.indexbuild\",\n e,\n \"error while indexing document: $0\",\n entry.get().data);\n }\n }\n\n auto stream_offsets = feed_reader.streamOffsets();\n String stream_offsets_str;\n\n index_build->commit();\n\n auto txn = featuredb->startTransaction();\n\n for (const auto& soff : stream_offsets) {\n txn->update(\n StringUtil::format(\"__indexfeed_offset~$0\", soff.first),\n StringUtil::toString(soff.second));\n\n stream_offsets_str +=\n StringUtil::format(\"\\n offset[$0]=$1\", soff.first, soff.second);\n }\n\n fnord::logInfo(\n \"cm.indexbuild\",\n \"IndexBuild comitting...$0\",\n stream_offsets_str);\n\n txn->commit();\n\n if (cm_indexbuild_shutdown.load() == true) {\n break;\n }\n\n auto etime = WallClock::now().unixMicros() - last_iter.unixMicros();\n if (i < 1 && etime < rate_limit_micros) {\n usleep(rate_limit_micros - etime);\n }\n }\n\n ev.shutdown();\n evloop_thread.join();\n}\n\nint main(int argc, const char** argv) {\n Application::init();\n Application::logToStderr();\n\n \/* shutdown hook *\/\n cm_indexbuild_shutdown = false;\n struct sigaction sa;\n memset(&sa, 0, sizeof(struct sigaction));\n sa.sa_handler = quit;\n sigaction(SIGTERM, &sa, NULL);\n sigaction(SIGQUIT, &sa, NULL);\n sigaction(SIGINT, &sa, NULL);\n\n cli::FlagParser flags;\n\n flags.defineFlag(\n \"index\",\n cli::FlagParser::T_STRING,\n true,\n NULL,\n NULL,\n \"index dir\",\n \"<path>\");\n\n flags.defineFlag(\n \"statsd_addr\",\n fnord::cli::FlagParser::T_STRING,\n false,\n NULL,\n \"127.0.0.1:8192\",\n \"Statsd addr\",\n \"<addr>\");\n\n flags.defineFlag(\n \"batch_size\",\n fnord::cli::FlagParser::T_INTEGER,\n false,\n NULL,\n \"2048\",\n \"batch_size\",\n \"<num>\");\n\n flags.defineFlag(\n \"buffer_size\",\n fnord::cli::FlagParser::T_INTEGER,\n false,\n NULL,\n \"8192\",\n \"buffer_size\",\n \"<num>\");\n\n flags.defineFlag(\n \"db_commit_size\",\n fnord::cli::FlagParser::T_INTEGER,\n false,\n NULL,\n \"1024\",\n \"db_commit_size\",\n \"<num>\");\n\n flags.defineFlag(\n \"db_commit_interval\",\n fnord::cli::FlagParser::T_INTEGER,\n false,\n NULL,\n \"5\",\n \"db_commit_interval\",\n \"<num>\");\n\n flags.defineFlag(\n \"dbsize\",\n fnord::cli::FlagParser::T_INTEGER,\n false,\n NULL,\n \"128\",\n \"max sessiondb size\",\n \"<MB>\");\n\n flags.defineFlag(\n \"loglevel\",\n fnord::cli::FlagParser::T_STRING,\n false,\n NULL,\n \"INFO\",\n \"loglevel\",\n \"<level>\");\n\n flags.parseArgv(argc, argv);\n\n Logger::get()->setMinimumLogLevel(\n strToLogLevel(flags.getString(\"loglevel\")));\n\n \/* set up feature schema *\/\n FeatureSchema feature_schema;\n feature_schema.registerFeature(\"shop_id\", 1, 1);\n feature_schema.registerFeature(\"category1\", 2, 1);\n feature_schema.registerFeature(\"category2\", 3, 1);\n feature_schema.registerFeature(\"category3\", 4, 1);\n feature_schema.registerFeature(\"title~de\", 5, 2);\n\n \/* start stats reporting *\/\n fnord::stats::StatsdAgent statsd_agent(\n fnord::net::InetAddr::resolve(flags.getString(\"statsd_addr\")),\n 10 * fnord::kMicrosPerSecond);\n\n statsd_agent.start();\n\n \/* set up indexbuild *\/\n size_t batch_size = flags.getInt(\"batch_size\");\n size_t buffer_size = flags.getInt(\"buffer_size\");\n size_t db_commit_size = flags.getInt(\"db_commit_size\");\n size_t db_commit_interval = flags.getInt(\"db_commit_interval\");\n\n fnord::logInfo(\n \"cm.indexbuild\",\n \"Starting cm-indexbuild with:\\n index=$0\\n batch_size=$1\\n\" \\\n \" buffer_size=$2\\n db_commit_size=$3\\n db_commit_interval=$4\\n\"\n \" max_dbsize=$5MB\",\n flags.getString(\"index\"),\n batch_size,\n buffer_size,\n db_commit_size,\n db_commit_interval,\n flags.getInt(\"dbsize\"));\n\n exportStat(\n \"\/cm-indexbuild\/global\/documents_indexed_total\",\n &stat_documents_indexed_total_,\n fnord::stats::ExportMode::EXPORT_DELTA);\n\n exportStat(\n \"\/cm-indexbuild\/global\/documents_indexed_success\",\n &stat_documents_indexed_success_,\n fnord::stats::ExportMode::EXPORT_DELTA);\n\n exportStat(\n \"\/cm-indexbuild\/global\/documents_indexed_error\",\n &stat_documents_indexed_error_,\n fnord::stats::ExportMode::EXPORT_DELTA);\n\n \/* open featuredb db *\/\n auto featuredb_path = FileUtil::joinPaths(flags.getString(\"index\"), \"db\");\n FileUtil::mkdir_p(featuredb_path);\n auto featuredb = mdb::MDB::open(featuredb_path);\n featuredb->setMaxSize(1000000 * flags.getInt(\"dbsize\"));\n cm::FeatureIndexWriter feature_index_writer(&feature_schema);\n\n \/* open full index *\/\n auto fullindex_path = FileUtil::joinPaths(flags.getString(\"index\"), \"docs\");\n FileUtil::mkdir_p(fullindex_path);\n cm::FullIndex full_index(fullindex_path);\n\n cm::IndexBuild index_build(&feature_index_writer, &full_index);\n\n buildIndexFromFeed(&index_build, featuredb, flags);\n\n fnord::logInfo(\"cm.indexbuild\", \"IndexBuild exiting...\");\n return 0;\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\/* open lucene index *\/\n \/*\n auto index_path = FileUtil::joinPaths(\n cmdata_path,\n StringUtil::format(\"index\/$0\/fts\", cmcustomer));\n FileUtil::mkdir_p(index_path);\n\n auto index_writer =\n fts::newLucene<fts::IndexWriter>(\n fts::FSDirectory::open(StringUtil::convertUTF8To16(index_path)),\n fts::newLucene<fts::StandardAnalyzer>(\n fts::LuceneVersion::LUCENE_CURRENT),\n true,\n fts::IndexWriter::MaxFieldLengthLIMITED);\n *\/\n \/\/ index document\n\/*\n auto doc = fts::newLucene<fts::Document>();\n doc->add(\n fts::newLucene<fts::Field>(\n L\"keywords\",\n L\"my fnordy document\",\n fts::Field::STORE_NO,\n fts::Field::INDEX_ANALYZED));\n\n index_writer->addDocument(doc);\n*\/\n\n\n \/\/index_writer->commit();\n \/\/index_writer->close();\n\n \/\/ simple search\n \/*\n auto index_reader = fts::IndexReader::open(\n fts::FSDirectory::open(StringUtil::convertUTF8To16(index_path)),\n true);\n\n auto searcher = fts::newLucene<fts::IndexSearcher>(index_reader);\n\n auto analyzer = fts::newLucene<fts::StandardAnalyzer>(\n fts::LuceneVersion::LUCENE_CURRENT);\n\n auto query_parser = fts::newLucene<fts::QueryParser>(\n fts::LuceneVersion::LUCENE_CURRENT,\n L\"keywords\",\n analyzer);\n\n auto collector = fts::TopScoreDocCollector::create(\n 500,\n false);\n\n auto query = query_parser->parse(L\"fnordy\");\n\n searcher->search(query, collector);\n fnord::iputs(\"found $0 documents\", collector->getTotalHits());\n *\/\n\n\n<|endoftext|>"} {"text":"<commit_before>#include \"xchainer\/array_repr.h\"\n\n#include <gtest\/gtest.h>\n\n#include <algorithm>\n#include <cmath>\n#include <limits>\n#include <vector>\n\n#include \"xchainer\/device.h\"\n\nnamespace xchainer {\nnamespace {\n\ntemplate <typename T>\nvoid CheckArrayReprWithCurrentDevice(const std::vector<T>& data_vec, Shape shape, const std::string& expected,\n std::vector<GraphId> graph_ids) {\n \/\/ Copy to a contiguous memory block because std::vector<bool> is not packed as a sequence of bool's.\n std::shared_ptr<T> data_ptr = std::make_unique<T[]>(data_vec.size());\n std::copy(data_vec.begin(), data_vec.end(), data_ptr.get());\n Array array = Array::FromBuffer(shape, TypeToDtype<T>, static_cast<std::shared_ptr<void>>(data_ptr));\n std::for_each(graph_ids.begin(), graph_ids.end(), [&array](const GraphId& graph_id) { array.RequireGrad(graph_id); });\n\n \/\/ std::string version\n EXPECT_EQ(ArrayRepr(array), expected);\n\n \/\/ std::ostream version\n std::ostringstream os;\n os << array;\n EXPECT_EQ(os.str(), expected);\n}\n\ntemplate <typename T>\nvoid CheckArrayRepr(const std::vector<T>& data_vec, Shape shape, const std::string& expected,\n const std::vector<GraphId>& graph_ids = std::vector<GraphId>()) {\n {\n DeviceScope ctx{\"cpu\"};\n CheckArrayReprWithCurrentDevice(data_vec, shape, expected, graph_ids);\n }\n\n {\n#ifdef XCHAINER_ENABLE_CUDA\n DeviceScope ctx{\"cuda\"};\n CheckArrayReprWithCurrentDevice(data_vec, shape, expected, graph_ids);\n#endif \/\/ XCHAINER_ENABLE_CUDA\n }\n}\n\nTEST(ArrayReprTest, ArrayRepr) {\n \/\/ bool\n CheckArrayRepr<bool>({false}, Shape({1}), \"array([False], dtype=bool)\");\n CheckArrayRepr<bool>({true}, Shape({1}), \"array([ True], dtype=bool)\");\n CheckArrayRepr<bool>({false, true, true, true, false, true}, Shape({2, 3}),\n \"array([[False, True, True],\\n\"\n \" [ True, False, True]], dtype=bool)\");\n CheckArrayRepr<bool>({true}, Shape({1, 1, 1, 1}), \"array([[[[ True]]]], dtype=bool)\");\n\n \/\/ int8\n CheckArrayRepr<int8_t>({0}, Shape({1}), \"array([0], dtype=int8)\");\n CheckArrayRepr<int8_t>({-2}, Shape({1}), \"array([-2], dtype=int8)\");\n CheckArrayRepr<int8_t>({0, 1, 2, 3, 4, 5}, Shape({2, 3}),\n \"array([[0, 1, 2],\\n\"\n \" [3, 4, 5]], dtype=int8)\");\n CheckArrayRepr<int8_t>({0, 1, 2, -3, 4, 5}, Shape({2, 3}),\n \"array([[ 0, 1, 2],\\n\"\n \" [-3, 4, 5]], dtype=int8)\");\n CheckArrayRepr<int8_t>({3}, Shape({1, 1, 1, 1}), \"array([[[[3]]]], dtype=int8)\");\n\n \/\/ int16\n CheckArrayRepr<int16_t>({0}, Shape({1}), \"array([0], dtype=int16)\");\n CheckArrayRepr<int16_t>({-2}, Shape({1}), \"array([-2], dtype=int16)\");\n CheckArrayRepr<int16_t>({0, 1, 2, 3, 4, 5}, Shape({2, 3}),\n \"array([[0, 1, 2],\\n\"\n \" [3, 4, 5]], dtype=int16)\");\n CheckArrayRepr<int16_t>({0, 1, 2, -3, 4, 5}, Shape({2, 3}),\n \"array([[ 0, 1, 2],\\n\"\n \" [-3, 4, 5]], dtype=int16)\");\n CheckArrayRepr<int16_t>({3}, Shape({1, 1, 1, 1}), \"array([[[[3]]]], dtype=int16)\");\n\n \/\/ int32\n CheckArrayRepr<int32_t>({0}, Shape({1}), \"array([0], dtype=int32)\");\n CheckArrayRepr<int32_t>({-2}, Shape({1}), \"array([-2], dtype=int32)\");\n CheckArrayRepr<int32_t>({0, 1, 2, 3, 4, 5}, Shape({2, 3}),\n \"array([[0, 1, 2],\\n\"\n \" [3, 4, 5]], dtype=int32)\");\n CheckArrayRepr<int32_t>({0, 1, 2, -3, 4, 5}, Shape({2, 3}),\n \"array([[ 0, 1, 2],\\n\"\n \" [-3, 4, 5]], dtype=int32)\");\n CheckArrayRepr<int32_t>({3}, Shape({1, 1, 1, 1}), \"array([[[[3]]]], dtype=int32)\");\n\n \/\/ int64\n CheckArrayRepr<int64_t>({0}, Shape({1}), \"array([0], dtype=int64)\");\n CheckArrayRepr<int64_t>({-2}, Shape({1}), \"array([-2], dtype=int64)\");\n CheckArrayRepr<int64_t>({0, 1, 2, 3, 4, 5}, Shape({2, 3}),\n \"array([[0, 1, 2],\\n\"\n \" [3, 4, 5]], dtype=int64)\");\n CheckArrayRepr<int64_t>({0, 1, 2, -3, 4, 5}, Shape({2, 3}),\n \"array([[ 0, 1, 2],\\n\"\n \" [-3, 4, 5]], dtype=int64)\");\n CheckArrayRepr<int64_t>({3}, Shape({1, 1, 1, 1}), \"array([[[[3]]]], dtype=int64)\");\n\n \/\/ uint8\n CheckArrayRepr<uint8_t>({0}, Shape({1}), \"array([0], dtype=uint8)\");\n CheckArrayRepr<uint8_t>({2}, Shape({1}), \"array([2], dtype=uint8)\");\n CheckArrayRepr<uint8_t>({0, 1, 2, 3, 4, 5}, Shape({2, 3}),\n \"array([[0, 1, 2],\\n\"\n \" [3, 4, 5]], dtype=uint8)\");\n CheckArrayRepr<uint8_t>({3}, Shape({1, 1, 1, 1}), \"array([[[[3]]]], dtype=uint8)\");\n\n \/\/ float32\n CheckArrayRepr<float>({0}, Shape({1}), \"array([0.], dtype=float32)\");\n CheckArrayRepr<float>({3.25}, Shape({1}), \"array([3.25], dtype=float32)\");\n CheckArrayRepr<float>({-3.25}, Shape({1}), \"array([-3.25], dtype=float32)\");\n CheckArrayRepr<float>({std::numeric_limits<float>::infinity()}, Shape({1}), \"array([ inf], dtype=float32)\");\n CheckArrayRepr<float>({-std::numeric_limits<float>::infinity()}, Shape({1}), \"array([ -inf], dtype=float32)\");\n CheckArrayRepr<float>({std::nanf(\"\")}, Shape({1}), \"array([ nan], dtype=float32)\");\n CheckArrayRepr<float>({0, 1, 2, 3, 4, 5}, Shape({2, 3}),\n \"array([[0., 1., 2.],\\n\"\n \" [3., 4., 5.]], dtype=float32)\");\n CheckArrayRepr<float>({0, 1, 2, 3.25, 4, 5}, Shape({2, 3}),\n \"array([[0. , 1. , 2. ],\\n\"\n \" [3.25, 4. , 5. ]], dtype=float32)\");\n CheckArrayRepr<float>({0, 1, 2, -3.25, 4, 5}, Shape({2, 3}),\n \"array([[ 0. , 1. , 2. ],\\n\"\n \" [-3.25, 4. , 5. ]], dtype=float32)\");\n CheckArrayRepr<float>({3.25}, Shape({1, 1, 1, 1}), \"array([[[[3.25]]]], dtype=float32)\");\n\n \/\/ float64\n CheckArrayRepr<double>({0}, Shape({1}), \"array([0.], dtype=float64)\");\n CheckArrayRepr<double>({3.25}, Shape({1}), \"array([3.25], dtype=float64)\");\n CheckArrayRepr<double>({-3.25}, Shape({1}), \"array([-3.25], dtype=float64)\");\n CheckArrayRepr<double>({std::numeric_limits<double>::infinity()}, Shape({1}), \"array([ inf], dtype=float64)\");\n CheckArrayRepr<double>({-std::numeric_limits<double>::infinity()}, Shape({1}), \"array([ -inf], dtype=float64)\");\n CheckArrayRepr<double>({std::nan(\"\")}, Shape({1}), \"array([ nan], dtype=float64)\");\n CheckArrayRepr<double>({0, 1, 2, 3, 4, 5}, Shape({2, 3}),\n \"array([[0., 1., 2.],\\n\"\n \" [3., 4., 5.]], dtype=float64)\");\n CheckArrayRepr<double>({0, 1, 2, 3.25, 4, 5}, Shape({2, 3}),\n \"array([[0. , 1. , 2. ],\\n\"\n \" [3.25, 4. , 5. ]], dtype=float64)\");\n CheckArrayRepr<double>({0, 1, 2, -3.25, 4, 5}, Shape({2, 3}),\n \"array([[ 0. , 1. , 2. ],\\n\"\n \" [-3.25, 4. , 5. ]], dtype=float64)\");\n CheckArrayRepr<double>({3.25}, Shape({1, 1, 1, 1}), \"array([[[[3.25]]]], dtype=float64)\");\n}\n\nTEST(ArrayReprTest, ArrayReprWithGraphIds) {\n \/\/ No graph\n CheckArrayRepr<int32_t>({3}, Shape({1}), \"array([3], dtype=int32)\");\n\n \/\/ Single graph\n CheckArrayRepr<int32_t>({-2}, Shape({1}), \"array([-2], dtype=int32, graph_ids=[graph_1])\", {\"graph_1\"});\n\n \/\/ Two graphs\n CheckArrayRepr<int32_t>({1}, Shape({1}), \"array([1], dtype=int32, graph_ids=[graph_1, graph_2])\", {\"graph_1, graph_2\"});\n\n \/\/ Multiple graphs\n CheckArrayRepr<int32_t>({-9}, Shape({1}), \"array([-9], dtype=int32, graph_ids=[graph_1, graph_2, graph_3, graph_4, graph_5])\",\n {\"graph_1, graph_2\", \"graph_3\", \"graph_4\", \"graph_5\"});\n}\n\n} \/\/ namespace\n} \/\/ namespace xchainer\n<commit_msg>Put expectation first<commit_after>#include \"xchainer\/array_repr.h\"\n\n#include <gtest\/gtest.h>\n\n#include <algorithm>\n#include <cmath>\n#include <limits>\n#include <vector>\n\n#include \"xchainer\/device.h\"\n\nnamespace xchainer {\nnamespace {\n\ntemplate <typename T>\nvoid CheckArrayReprWithCurrentDevice(const std::string& expected, const std::vector<T>& data_vec, Shape shape,\n std::vector<GraphId> graph_ids) {\n \/\/ Copy to a contiguous memory block because std::vector<bool> is not packed as a sequence of bool's.\n std::shared_ptr<T> data_ptr = std::make_unique<T[]>(data_vec.size());\n std::copy(data_vec.begin(), data_vec.end(), data_ptr.get());\n Array array = Array::FromBuffer(shape, TypeToDtype<T>, static_cast<std::shared_ptr<void>>(data_ptr));\n std::for_each(graph_ids.begin(), graph_ids.end(), [&array](const GraphId& graph_id) { array.RequireGrad(graph_id); });\n\n \/\/ std::string version\n EXPECT_EQ(ArrayRepr(array), expected);\n\n \/\/ std::ostream version\n std::ostringstream os;\n os << array;\n EXPECT_EQ(os.str(), expected);\n}\n\ntemplate <typename T>\nvoid CheckArrayRepr(const std::string& expected, const std::vector<T>& data_vec, Shape shape,\n const std::vector<GraphId>& graph_ids = std::vector<GraphId>()) {\n {\n DeviceScope ctx{\"cpu\"};\n CheckArrayReprWithCurrentDevice(expected, data_vec, shape, graph_ids);\n }\n\n {\n#ifdef XCHAINER_ENABLE_CUDA\n DeviceScope ctx{\"cuda\"};\n CheckArrayReprWithCurrentDevice(expected, data_vec, shape, graph_ids);\n#endif \/\/ XCHAINER_ENABLE_CUDA\n }\n}\n\nTEST(ArrayReprTest, ArrayRepr) {\n \/\/ bool\n CheckArrayRepr<bool>(\"array([False], dtype=bool)\", {false}, Shape({1}));\n CheckArrayRepr<bool>(\"array([ True], dtype=bool)\", {true}, Shape({1}));\n CheckArrayRepr<bool>(\n \"array([[False, True, True],\\n\"\n \" [ True, False, True]], dtype=bool)\",\n {false, true, true, true, false, true}, Shape({2, 3}));\n CheckArrayRepr<bool>(\"array([[[[ True]]]], dtype=bool)\", {true}, Shape({1, 1, 1, 1}));\n\n \/\/ int8\n CheckArrayRepr<int8_t>(\"array([0], dtype=int8)\", {0}, Shape({1}));\n CheckArrayRepr<int8_t>(\"array([-2], dtype=int8)\", {-2}, Shape({1}));\n CheckArrayRepr<int8_t>(\n \"array([[0, 1, 2],\\n\"\n \" [3, 4, 5]], dtype=int8)\",\n {0, 1, 2, 3, 4, 5}, Shape({2, 3}));\n\n CheckArrayRepr<int8_t>(\n \"array([[ 0, 1, 2],\\n\"\n \" [-3, 4, 5]], dtype=int8)\",\n {0, 1, 2, -3, 4, 5}, Shape({2, 3}));\n\n CheckArrayRepr<int8_t>(\"array([[[[3]]]], dtype=int8)\", {3}, Shape({1, 1, 1, 1}));\n\n \/\/ int16\n CheckArrayRepr<int16_t>(\"array([0], dtype=int16)\", {0}, Shape({1}));\n CheckArrayRepr<int16_t>(\"array([-2], dtype=int16)\", {-2}, Shape({1}));\n CheckArrayRepr<int16_t>(\n \"array([[0, 1, 2],\\n\"\n \" [3, 4, 5]], dtype=int16)\",\n {0, 1, 2, 3, 4, 5}, Shape({2, 3}));\n\n CheckArrayRepr<int16_t>(\n \"array([[ 0, 1, 2],\\n\"\n \" [-3, 4, 5]], dtype=int16)\",\n {0, 1, 2, -3, 4, 5}, Shape({2, 3}));\n CheckArrayRepr<int16_t>(\"array([[[[3]]]], dtype=int16)\", {3}, Shape({1, 1, 1, 1}));\n\n \/\/ int32\n CheckArrayRepr<int32_t>(\"array([0], dtype=int32)\", {0}, Shape({1}));\n CheckArrayRepr<int32_t>(\"array([-2], dtype=int32)\", {-2}, Shape({1}));\n CheckArrayRepr<int32_t>(\n \"array([[0, 1, 2],\\n\"\n \" [3, 4, 5]], dtype=int32)\",\n {0, 1, 2, 3, 4, 5}, Shape({2, 3}));\n\n CheckArrayRepr<int32_t>(\n \"array([[ 0, 1, 2],\\n\"\n \" [-3, 4, 5]], dtype=int32)\",\n {0, 1, 2, -3, 4, 5}, Shape({2, 3}));\n CheckArrayRepr<int32_t>(\"array([[[[3]]]], dtype=int32)\", {3}, Shape({1, 1, 1, 1}));\n\n \/\/ int64\n CheckArrayRepr<int64_t>(\"array([0], dtype=int64)\", {0}, Shape({1}));\n CheckArrayRepr<int64_t>(\"array([-2], dtype=int64)\", {-2}, Shape({1}));\n CheckArrayRepr<int64_t>(\n \"array([[0, 1, 2],\\n\"\n \" [3, 4, 5]], dtype=int64)\",\n {0, 1, 2, 3, 4, 5}, Shape({2, 3}));\n CheckArrayRepr<int64_t>(\n \"array([[ 0, 1, 2],\\n\"\n \" [-3, 4, 5]], dtype=int64)\",\n {0, 1, 2, -3, 4, 5}, Shape({2, 3}));\n CheckArrayRepr<int64_t>(\"array([[[[3]]]], dtype=int64)\", {3}, Shape({1, 1, 1, 1}));\n\n \/\/ uint8\n CheckArrayRepr<uint8_t>(\"array([0], dtype=uint8)\", {0}, Shape({1}));\n CheckArrayRepr<uint8_t>(\"array([2], dtype=uint8)\", {2}, Shape({1}));\n CheckArrayRepr<uint8_t>(\n \"array([[0, 1, 2],\\n\"\n \" [3, 4, 5]], dtype=uint8)\",\n {0, 1, 2, 3, 4, 5}, Shape({2, 3}));\n CheckArrayRepr<uint8_t>(\"array([[[[3]]]], dtype=uint8)\", {3}, Shape({1, 1, 1, 1}));\n\n \/\/ float32\n CheckArrayRepr<float>(\"array([0.], dtype=float32)\", {0}, Shape({1}));\n CheckArrayRepr<float>(\"array([3.25], dtype=float32)\", {3.25}, Shape({1}));\n CheckArrayRepr<float>(\"array([-3.25], dtype=float32)\", {-3.25}, Shape({1}));\n CheckArrayRepr<float>(\"array([ inf], dtype=float32)\", {std::numeric_limits<float>::infinity()}, Shape({1}));\n CheckArrayRepr<float>(\"array([ -inf], dtype=float32)\", {-std::numeric_limits<float>::infinity()}, Shape({1}));\n CheckArrayRepr<float>(\"array([ nan], dtype=float32)\", {std::nanf(\"\")}, Shape({1}));\n CheckArrayRepr<float>(\n \"array([[0., 1., 2.],\\n\"\n \" [3., 4., 5.]], dtype=float32)\",\n {0, 1, 2, 3, 4, 5}, Shape({2, 3}));\n CheckArrayRepr<float>(\n \"array([[0. , 1. , 2. ],\\n\"\n \" [3.25, 4. , 5. ]], dtype=float32)\",\n {0, 1, 2, 3.25, 4, 5}, Shape({2, 3}));\n CheckArrayRepr<float>(\n \"array([[ 0. , 1. , 2. ],\\n\"\n \" [-3.25, 4. , 5. ]], dtype=float32)\",\n {0, 1, 2, -3.25, 4, 5}, Shape({2, 3}));\n CheckArrayRepr<float>(\"array([[[[3.25]]]], dtype=float32)\", {3.25}, Shape({1, 1, 1, 1}));\n\n \/\/ float64\n CheckArrayRepr<double>(\"array([0.], dtype=float64)\", {0}, Shape({1}));\n CheckArrayRepr<double>(\"array([3.25], dtype=float64)\", {3.25}, Shape({1}));\n CheckArrayRepr<double>(\"array([-3.25], dtype=float64)\", {-3.25}, Shape({1}));\n CheckArrayRepr<double>(\"array([ inf], dtype=float64)\", {std::numeric_limits<double>::infinity()}, Shape({1}));\n CheckArrayRepr<double>(\"array([ -inf], dtype=float64)\", {-std::numeric_limits<double>::infinity()}, Shape({1}));\n CheckArrayRepr<double>(\"array([ nan], dtype=float64)\", {std::nan(\"\")}, Shape({1}));\n CheckArrayRepr<double>(\n \"array([[0., 1., 2.],\\n\"\n \" [3., 4., 5.]], dtype=float64)\",\n {0, 1, 2, 3, 4, 5}, Shape({2, 3}));\n CheckArrayRepr<double>(\n \"array([[0. , 1. , 2. ],\\n\"\n \" [3.25, 4. , 5. ]], dtype=float64)\",\n {0, 1, 2, 3.25, 4, 5}, Shape({2, 3}));\n CheckArrayRepr<double>(\n \"array([[ 0. , 1. , 2. ],\\n\"\n \" [-3.25, 4. , 5. ]], dtype=float64)\",\n {0, 1, 2, -3.25, 4, 5}, Shape({2, 3}));\n CheckArrayRepr<double>(\"array([[[[3.25]]]], dtype=float64)\", {3.25}, Shape({1, 1, 1, 1}));\n}\n\nTEST(ArrayReprTest, ArrayReprWithGraphIds) {\n \/\/ No graph\n CheckArrayRepr<int32_t>(\"array([3], dtype=int32)\", {3}, Shape({1}));\n\n \/\/ Single graph\n CheckArrayRepr<int32_t>(\"array([-2], dtype=int32, graph_ids=[graph_1])\", {-2}, Shape({1}), {\"graph_1\"});\n\n \/\/ Two graphs\n CheckArrayRepr<int32_t>(\"array([1], dtype=int32, graph_ids=[graph_1, graph_2])\", {1}, Shape({1}), {\"graph_1, graph_2\"});\n\n \/\/ Multiple graphs\n CheckArrayRepr<int32_t>(\"array([-9], dtype=int32, graph_ids=[graph_1, graph_2, graph_3, graph_4, graph_5])\", {-9}, Shape({1}),\n {\"graph_1, graph_2\", \"graph_3\", \"graph_4\", \"graph_5\"});\n}\n\n} \/\/ namespace\n} \/\/ namespace xchainer\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright 2017 Google Inc.\n *\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n *\/\n\n#include \"modules\/svg\/include\/SkSVGPattern.h\"\n\n#include \"include\/core\/SkPictureRecorder.h\"\n#include \"include\/core\/SkShader.h\"\n#include \"modules\/svg\/include\/SkSVGRenderContext.h\"\n#include \"modules\/svg\/include\/SkSVGValue.h\"\n\nSkSVGPattern::SkSVGPattern() : INHERITED(SkSVGTag::kPattern) {}\n\nbool SkSVGPattern::parseAndSetAttribute(const char* name, const char* value) {\n return INHERITED::parseAndSetAttribute(name, value) ||\n this->setX(SkSVGAttributeParser::parse<SkSVGLength>(\"x\", name, value)) ||\n this->setY(SkSVGAttributeParser::parse<SkSVGLength>(\"y\", name, value)) ||\n this->setWidth(SkSVGAttributeParser::parse<SkSVGLength>(\"width\", name, value)) ||\n this->setHeight(SkSVGAttributeParser::parse<SkSVGLength>(\"height\", name, value)) ||\n this->setPatternTransform(SkSVGAttributeParser::parse<SkSVGTransformType>(\n \"patternTransform\", name, value)) ||\n this->setHref(SkSVGAttributeParser::parse<SkSVGIRI>(\"xlink:href\", name, value));\n}\n\nconst SkSVGPattern* SkSVGPattern::hrefTarget(const SkSVGRenderContext& ctx) const {\n if (fHref.iri().isEmpty()) {\n return nullptr;\n }\n\n const auto href = ctx.findNodeById(fHref);\n if (!href || href->tag() != SkSVGTag::kPattern) {\n return nullptr;\n }\n\n return static_cast<const SkSVGPattern*>(href.get());\n}\n\ntemplate <typename T>\nbool inherit_if_needed(const SkTLazy<T>& src, SkTLazy<T>& dst) {\n if (!dst.isValid()) {\n dst = src;\n return true;\n }\n\n return false;\n}\n\n\/* https:\/\/www.w3.org\/TR\/SVG11\/pservers.html#PatternElementHrefAttribute\n *\n * Any attributes which are defined on the referenced element which are not defined on this element\n * are inherited by this element. If this element has no children, and the referenced element does\n * (possibly due to its own ‘xlink:href’ attribute), then this element inherits the children from\n * the referenced element. Inheritance can be indirect to an arbitrary level; thus, if the\n * referenced element inherits attributes or children due to its own ‘xlink:href’ attribute, then\n * the current element can inherit those attributes or children.\n *\/\nconst SkSVGPattern* SkSVGPattern::resolveHref(const SkSVGRenderContext& ctx,\n PatternAttributes* attrs) const {\n const SkSVGPattern *currentNode = this,\n *contentNode = this;\n do {\n \/\/ Bitwise OR to avoid short-circuiting.\n const bool didInherit =\n inherit_if_needed(currentNode->fX , attrs->fX) |\n inherit_if_needed(currentNode->fY , attrs->fY) |\n inherit_if_needed(currentNode->fWidth , attrs->fWidth) |\n inherit_if_needed(currentNode->fHeight , attrs->fHeight) |\n inherit_if_needed(currentNode->fPatternTransform, attrs->fPatternTransform);\n\n if (!contentNode->hasChildren()) {\n contentNode = currentNode;\n }\n\n if (contentNode->hasChildren() && !didInherit) {\n \/\/ All attributes have been resolved, and a valid content node has been found.\n \/\/ We can terminate the href chain early.\n break;\n }\n\n \/\/ TODO: reference loop mitigation.\n currentNode = currentNode->hrefTarget(ctx);\n } while (currentNode);\n\n return contentNode;\n}\n\nbool SkSVGPattern::onAsPaint(const SkSVGRenderContext& ctx, SkPaint* paint) const {\n PatternAttributes attrs;\n const auto* contentNode = this->resolveHref(ctx, &attrs);\n\n const auto tile = ctx.lengthContext().resolveRect(\n attrs.fX.isValid() ? *attrs.fX : SkSVGLength(0),\n attrs.fY.isValid() ? *attrs.fY : SkSVGLength(0),\n attrs.fWidth.isValid() ? *attrs.fWidth : SkSVGLength(0),\n attrs.fHeight.isValid() ? *attrs.fHeight : SkSVGLength(0));\n\n if (tile.isEmpty()) {\n return false;\n }\n\n const SkMatrix* patternTransform = attrs.fPatternTransform.isValid()\n ? attrs.fPatternTransform.get()\n : nullptr;\n\n SkPictureRecorder recorder;\n SkSVGRenderContext recordingContext(ctx, recorder.beginRecording(tile));\n\n \/\/ Cannot call into INHERITED:: because SkSVGHiddenContainer skips rendering.\n contentNode->SkSVGContainer::onRender(recordingContext);\n\n paint->setShader(recorder.finishRecordingAsPicture()->makeShader(\n SkTileMode::kRepeat,\n SkTileMode::kRepeat,\n SkFilterMode::kLinear,\n patternTransform,\n &tile));\n return true;\n}\n<commit_msg>Fix Clang warning -Wbitwise-instead-of-logical.<commit_after>\/*\n * Copyright 2017 Google Inc.\n *\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n *\/\n\n#include \"modules\/svg\/include\/SkSVGPattern.h\"\n\n#include \"include\/core\/SkPictureRecorder.h\"\n#include \"include\/core\/SkShader.h\"\n#include \"modules\/svg\/include\/SkSVGRenderContext.h\"\n#include \"modules\/svg\/include\/SkSVGValue.h\"\n\nSkSVGPattern::SkSVGPattern() : INHERITED(SkSVGTag::kPattern) {}\n\nbool SkSVGPattern::parseAndSetAttribute(const char* name, const char* value) {\n return INHERITED::parseAndSetAttribute(name, value) ||\n this->setX(SkSVGAttributeParser::parse<SkSVGLength>(\"x\", name, value)) ||\n this->setY(SkSVGAttributeParser::parse<SkSVGLength>(\"y\", name, value)) ||\n this->setWidth(SkSVGAttributeParser::parse<SkSVGLength>(\"width\", name, value)) ||\n this->setHeight(SkSVGAttributeParser::parse<SkSVGLength>(\"height\", name, value)) ||\n this->setPatternTransform(SkSVGAttributeParser::parse<SkSVGTransformType>(\n \"patternTransform\", name, value)) ||\n this->setHref(SkSVGAttributeParser::parse<SkSVGIRI>(\"xlink:href\", name, value));\n}\n\nconst SkSVGPattern* SkSVGPattern::hrefTarget(const SkSVGRenderContext& ctx) const {\n if (fHref.iri().isEmpty()) {\n return nullptr;\n }\n\n const auto href = ctx.findNodeById(fHref);\n if (!href || href->tag() != SkSVGTag::kPattern) {\n return nullptr;\n }\n\n return static_cast<const SkSVGPattern*>(href.get());\n}\n\ntemplate <typename T>\nint inherit_if_needed(const SkTLazy<T>& src, SkTLazy<T>& dst) {\n if (!dst.isValid()) {\n dst = src;\n return 1;\n }\n\n return 0;\n}\n\n\/* https:\/\/www.w3.org\/TR\/SVG11\/pservers.html#PatternElementHrefAttribute\n *\n * Any attributes which are defined on the referenced element which are not defined on this element\n * are inherited by this element. If this element has no children, and the referenced element does\n * (possibly due to its own ‘xlink:href’ attribute), then this element inherits the children from\n * the referenced element. Inheritance can be indirect to an arbitrary level; thus, if the\n * referenced element inherits attributes or children due to its own ‘xlink:href’ attribute, then\n * the current element can inherit those attributes or children.\n *\/\nconst SkSVGPattern* SkSVGPattern::resolveHref(const SkSVGRenderContext& ctx,\n PatternAttributes* attrs) const {\n const SkSVGPattern *currentNode = this,\n *contentNode = this;\n do {\n \/\/ Bitwise OR to avoid short-circuiting.\n const bool didInherit =\n inherit_if_needed(currentNode->fX , attrs->fX) |\n inherit_if_needed(currentNode->fY , attrs->fY) |\n inherit_if_needed(currentNode->fWidth , attrs->fWidth) |\n inherit_if_needed(currentNode->fHeight , attrs->fHeight) |\n inherit_if_needed(currentNode->fPatternTransform, attrs->fPatternTransform);\n\n if (!contentNode->hasChildren()) {\n contentNode = currentNode;\n }\n\n if (contentNode->hasChildren() && !didInherit) {\n \/\/ All attributes have been resolved, and a valid content node has been found.\n \/\/ We can terminate the href chain early.\n break;\n }\n\n \/\/ TODO: reference loop mitigation.\n currentNode = currentNode->hrefTarget(ctx);\n } while (currentNode);\n\n return contentNode;\n}\n\nbool SkSVGPattern::onAsPaint(const SkSVGRenderContext& ctx, SkPaint* paint) const {\n PatternAttributes attrs;\n const auto* contentNode = this->resolveHref(ctx, &attrs);\n\n const auto tile = ctx.lengthContext().resolveRect(\n attrs.fX.isValid() ? *attrs.fX : SkSVGLength(0),\n attrs.fY.isValid() ? *attrs.fY : SkSVGLength(0),\n attrs.fWidth.isValid() ? *attrs.fWidth : SkSVGLength(0),\n attrs.fHeight.isValid() ? *attrs.fHeight : SkSVGLength(0));\n\n if (tile.isEmpty()) {\n return false;\n }\n\n const SkMatrix* patternTransform = attrs.fPatternTransform.isValid()\n ? attrs.fPatternTransform.get()\n : nullptr;\n\n SkPictureRecorder recorder;\n SkSVGRenderContext recordingContext(ctx, recorder.beginRecording(tile));\n\n \/\/ Cannot call into INHERITED:: because SkSVGHiddenContainer skips rendering.\n contentNode->SkSVGContainer::onRender(recordingContext);\n\n paint->setShader(recorder.finishRecordingAsPicture()->makeShader(\n SkTileMode::kRepeat,\n SkTileMode::kRepeat,\n SkFilterMode::kLinear,\n patternTransform,\n &tile));\n return true;\n}\n<|endoftext|>"} {"text":"<commit_before>#pragma once\n\n#include \"pile.hpp\"\n\nnamespace morda{\n\n\/**\n * @brief Overlay container for displaying widgets on top of anything.\n * Overlay container is used for displaying topmost widgets like context menus, hint popups etc.\n * Essentially, the overlay is a simple pile container which keeps track of open overlay widgets.\n * From GUI scripts it can be instantiated as \"overlay\".\n *\/\nclass overlay :\n\t\tvirtual public widget,\n\t\tpublic pile\n{\npublic:\n\toverlay(std::shared_ptr<morda::context> c, const puu::forest& desc);\n\t\n\toverlay(const overlay&) = delete;\n\toverlay& operator=(const overlay&) = delete;\n\t\n\t\/**\n\t * @brief Showing context menu.\n\t * This function adds the context menu widget to the overlay as the topmost widget.\n\t * The given context menu widget is wrapped into special overhead container to make it properly positioned\n\t * on the screen and to handle mouse clicks outside of the context menu widget\n\t * (i.e. close the context menu in case of mouse click outside).\n\t * @param menu - context menu widget.\n\t * @param pos - position of top left corner of the context menu within the overlay container.\n\t * @return the final widget added to the overlay pile. This widget can be used to later close the particular context menu\n\t * by just removing the widget from its parent.\n\t *\/\n\tstd::shared_ptr<widget> show_context_menu(std::shared_ptr<widget> menu, vector2 pos);\n\t\n\t\/**\n\t * @brief Close all context menus.\n\t *\/\n\tvoid close_all_context_menus();\nprivate:\n\n};\n\n}\n<commit_msg>stuff<commit_after>#pragma once\n\n#include \"pile.hpp\"\n\nnamespace morda{\n\n\/**\n * @brief Overlay container for displaying widgets on top of anything.\n * Overlay container is used for displaying topmost widgets like context menus, hint popups etc.\n * Essentially, the overlay is a simple pile container which keeps track of open overlay widgets.\n * From GUI scripts it can be instantiated as \"overlay\".\n *\/\nclass overlay : public pile\n{\npublic:\n\toverlay(std::shared_ptr<morda::context> c, const puu::forest& desc);\n\t\n\toverlay(const overlay&) = delete;\n\toverlay& operator=(const overlay&) = delete;\n\t\n\t\/**\n\t * @brief Showing context menu.\n\t * This function adds the context menu widget to the overlay as the topmost widget.\n\t * The given context menu widget is wrapped into special overhead container to make it properly positioned\n\t * on the screen and to handle mouse clicks outside of the context menu widget\n\t * (i.e. close the context menu in case of mouse click outside).\n\t * @param menu - context menu widget.\n\t * @param pos - position of top left corner of the context menu within the overlay container.\n\t * @return the final widget added to the overlay pile. This widget can be used to later close the particular context menu\n\t * by just removing the widget from its parent.\n\t *\/\n\tstd::shared_ptr<widget> show_context_menu(std::shared_ptr<widget> menu, vector2 pos);\n\t\n\t\/**\n\t * @brief Close all context menus.\n\t *\/\n\tvoid close_all_context_menus();\nprivate:\n\n};\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Copyright (c) 2007-2016 musikcube team\n\/\/\n\/\/ All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright notice,\n\/\/ this list of conditions and the following disclaimer.\n\/\/\n\/\/ * Redistributions in binary form must reproduce the above copyright\n\/\/ notice, this list of conditions and the following disclaimer in the\n\/\/ documentation and\/or other materials provided with the distribution.\n\/\/\n\/\/ * Neither the name of the author nor the names of other contributors may\n\/\/ be used to endorse or promote products derived from this software\n\/\/ without specific prior written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n\/\/ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\/\/ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\/\/ ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\n\/\/ LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n\/\/ CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n\/\/ SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n\/\/ INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n\/\/ CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n\/\/ ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n\/\/ POSSIBILITY OF SUCH DAMAGE.\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"stdafx.h\"\n#include \"TrackListView.h\"\n\n#include <cursespp\/Colors.h>\n#include <cursespp\/SingleLineEntry.h>\n#include <cursespp\/IMessage.h>\n#include <cursespp\/Text.h>\n\n#include <core\/library\/LocalLibraryConstants.h>\n\n#include <app\/util\/Hotkeys.h>\n#include <app\/util\/Duration.h>\n#include <app\/window\/EntryWithHeader.h>\n\n#include <boost\/format.hpp>\n\n#define WINDOW_MESSAGE_QUERY_COMPLETED 1002\n\nusing namespace musik::core;\nusing namespace musik::core::audio;\nusing namespace musik::core::library;\nusing namespace musik::box;\nusing namespace cursespp;\n\nusing namespace boost::chrono;\n\n\/* if the user hasn't changed the selected index in 30 seconds\nwe assume he's not paying attention, and will automatically scroll\nthe view to the next track if it's invisible. *\/\nstatic const milliseconds AUTO_SCROLL_COOLDOWN = milliseconds(30000LL);\n\nstatic inline milliseconds now() {\n return duration_cast<milliseconds>(system_clock::now().time_since_epoch());\n}\n\nstatic IScrollAdapter::EntryPtr MISSING_ENTRY = IScrollAdapter::EntryPtr();\n\nTrackListView::TrackListView(\n PlaybackService& playback,\n LibraryPtr library,\n RowFormatter formatter)\n: ListWindow(nullptr)\n, playback(playback) {\n this->library = library;\n this->library->QueryCompleted.connect(this, &TrackListView::OnQueryCompleted);\n this->playback.TrackChanged.connect(this, &TrackListView::OnTrackChanged);\n this->adapter = new Adapter(*this);\n this->lastQueryHash = 0;\n this->lastChanged = now();\n this->formatter = formatter;\n\n if (!MISSING_ENTRY) {\n auto e = std::shared_ptr<SingleLineEntry>(new SingleLineEntry(\"track missing\"));\n e->SetAttrs(COLOR_PAIR(CURSESPP_TEXT_ERROR));\n MISSING_ENTRY = e;\n }\n}\n\nTrackListView::~TrackListView() {\n delete this->adapter;\n this->adapter = nullptr;\n}\n\nvoid TrackListView::Requery(std::shared_ptr<TrackListQueryBase> query) {\n this->query = query;\n this->library->Enqueue(this->query);\n}\n\nvoid TrackListView::OnQueryCompleted(IQueryPtr query) {\n if (query == this->query) {\n this->PostMessage(WINDOW_MESSAGE_QUERY_COMPLETED);\n }\n}\n\nvoid TrackListView::OnSelectionChanged(size_t newIndex, size_t oldIndex) {\n ListWindow::OnSelectionChanged(newIndex, oldIndex);\n this->lastChanged = now();\n}\n\nstd::shared_ptr<TrackList> TrackListView::GetTrackList() {\n return this->metadata;\n}\n\nvoid TrackListView::Clear() {\n this->query.reset();\n this->metadata.reset(new TrackList(this->library));\n this->headers.reset(new std::set<size_t>());\n this->OnAdapterChanged();\n}\n\nvoid TrackListView::ScrollToPlaying() {\n if (this->playing) {\n DBID id = this->playing->Id();\n for (size_t i = 0; i < this->metadata->Count(); i++) {\n if (this->metadata->GetId(i) == id) {\n this->SetSelectedIndex(i);\n\n auto pos = this->GetScrollPosition();\n size_t first = pos.firstVisibleEntryIndex;\n size_t last = first + pos.visibleEntryCount;\n if (i < first || i > last) {\n \/* only scroll if the playing track is not visible. *\/\n this->ScrollTo(i);\n }\n break;\n }\n }\n }\n}\n\nvoid TrackListView::ProcessMessage(IMessage &message) {\n if (message.Type() == WINDOW_MESSAGE_QUERY_COMPLETED) {\n if (this->query && this->query->GetStatus() == IQuery::Finished) {\n this->metadata = this->query->GetResult();\n this->headers = this->query->GetHeaders();\n\n \/* if the query was functionally the same as the last query, don't\n mess with the selected index *\/\n if (this->lastQueryHash != query->GetQueryHash()) {\n this->SetSelectedIndex(0);\n this->ScrollToTop();\n }\n\n this->lastQueryHash = this->query->GetQueryHash();\n this->query.reset();\n\n this->OnAdapterChanged(); \/* internal handling *\/\n this->Requeried(); \/* for external handlers *\/\n }\n }\n}\n\nbool TrackListView::KeyPress(const std::string& key) {\n if (Hotkeys::Is(Hotkeys::NavigateJumpToPlaying, key)) {\n this->ScrollToPlaying();\n return true;\n }\n\n return ListWindow::KeyPress(key);\n}\n\nvoid TrackListView::OnTrackChanged(size_t index, musik::core::TrackPtr track) {\n this->playing = track;\n this->OnAdapterChanged();\n\n if (now() - lastChanged >= AUTO_SCROLL_COOLDOWN) {\n this->ScrollToPlaying();\n }\n}\n\nIScrollAdapter& TrackListView::GetScrollAdapter() {\n return *this->adapter;\n}\n\nTrackListView::Adapter::Adapter(TrackListView &parent)\n: parent(parent) {\n}\n\nsize_t TrackListView::Adapter::GetEntryCount() {\n return parent.metadata ? parent.metadata->Count() : 0;\n}\n\n#define TRACK_COL_WIDTH 3\n#define ARTIST_COL_WIDTH 17\n#define DURATION_COL_WIDTH 5 \/* 00:00 *\/\n\nstatic std::string formatWithoutAlbum(TrackPtr track, size_t width) {\n std::string trackNum = text::Align(\n track->GetValue(constants::Track::TRACK_NUM),\n text::AlignRight,\n TRACK_COL_WIDTH);\n\n std::string duration = text::Align(\n musik::box::duration::Duration(track->GetValue(constants::Track::DURATION)),\n text::AlignRight,\n DURATION_COL_WIDTH);\n\n std::string artist = text::Align(\n track->GetValue(constants::Track::ARTIST),\n text::AlignLeft,\n ARTIST_COL_WIDTH);\n\n int titleWidth =\n width -\n TRACK_COL_WIDTH -\n DURATION_COL_WIDTH -\n ARTIST_COL_WIDTH -\n (3 * 3); \/* 3 = spacing *\/\n\n titleWidth = std::max(0, titleWidth);\n\n std::string title = text::Align(\n track->GetValue(constants::Track::TITLE),\n text::AlignLeft,\n titleWidth);\n\n return boost::str(\n boost::format(\"%s %s %s %s\")\n % trackNum % title % duration % artist);\n}\n\nIScrollAdapter::EntryPtr TrackListView::Adapter::GetEntry(size_t index) {\n bool selected = index == parent.GetSelectedIndex();\n int64 attrs = selected ? COLOR_PAIR(CURSESPP_HIGHLIGHTED_LIST_ITEM) : -1LL;\n\n TrackPtr track = parent.metadata->Get(index);\n\n if (!track) {\n return MISSING_ENTRY;\n }\n\n TrackPtr playing = parent.playing;\n if (playing &&\n playing->Id() == track->Id() &&\n playing->LibraryId() == track->LibraryId())\n {\n if (selected) {\n attrs = COLOR_PAIR(CURSESPP_HIGHLIGHTED_SELECTED_LIST_ITEM);\n }\n else {\n attrs = COLOR_PAIR(CURSESPP_SELECTED_LIST_ITEM);\n }\n }\n\n std::string text = parent.formatter\n ? parent.formatter(track, this->GetWidth())\n : formatWithoutAlbum(track, this->GetWidth());\n\n if (this->parent.headers->find(index) != this->parent.headers->end()) {\n std::string album = track->GetValue(constants::Track::ALBUM);\n std::shared_ptr<EntryWithHeader> entry(new EntryWithHeader(album, text));\n entry->SetAttrs(COLOR_PAIR(CURSESPP_LIST_ITEM_HEADER), attrs);\n return entry;\n }\n else {\n std::shared_ptr<SingleLineEntry> entry(new SingleLineEntry(text));\n entry->SetAttrs(attrs);\n return entry;\n }\n}\n<commit_msg>Fixed a silly null pointer dereference in TrackListView related to auto-scrolling behavior.<commit_after>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Copyright (c) 2007-2016 musikcube team\n\/\/\n\/\/ All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright notice,\n\/\/ this list of conditions and the following disclaimer.\n\/\/\n\/\/ * Redistributions in binary form must reproduce the above copyright\n\/\/ notice, this list of conditions and the following disclaimer in the\n\/\/ documentation and\/or other materials provided with the distribution.\n\/\/\n\/\/ * Neither the name of the author nor the names of other contributors may\n\/\/ be used to endorse or promote products derived from this software\n\/\/ without specific prior written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n\/\/ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\/\/ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\/\/ ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\n\/\/ LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n\/\/ CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n\/\/ SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n\/\/ INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n\/\/ CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n\/\/ ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n\/\/ POSSIBILITY OF SUCH DAMAGE.\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"stdafx.h\"\n#include \"TrackListView.h\"\n\n#include <cursespp\/Colors.h>\n#include <cursespp\/SingleLineEntry.h>\n#include <cursespp\/IMessage.h>\n#include <cursespp\/Text.h>\n\n#include <core\/library\/LocalLibraryConstants.h>\n\n#include <app\/util\/Hotkeys.h>\n#include <app\/util\/Duration.h>\n#include <app\/window\/EntryWithHeader.h>\n\n#include <boost\/format.hpp>\n\n#define WINDOW_MESSAGE_QUERY_COMPLETED 1002\n\nusing namespace musik::core;\nusing namespace musik::core::audio;\nusing namespace musik::core::library;\nusing namespace musik::box;\nusing namespace cursespp;\n\nusing namespace boost::chrono;\n\n\/* if the user hasn't changed the selected index in 30 seconds\nwe assume he's not paying attention, and will automatically scroll\nthe view to the next track if it's invisible. *\/\nstatic const milliseconds AUTO_SCROLL_COOLDOWN = milliseconds(30000LL);\n\nstatic inline milliseconds now() {\n return duration_cast<milliseconds>(system_clock::now().time_since_epoch());\n}\n\nstatic IScrollAdapter::EntryPtr MISSING_ENTRY = IScrollAdapter::EntryPtr();\n\nTrackListView::TrackListView(\n PlaybackService& playback,\n LibraryPtr library,\n RowFormatter formatter)\n: ListWindow(nullptr)\n, playback(playback) {\n this->library = library;\n this->library->QueryCompleted.connect(this, &TrackListView::OnQueryCompleted);\n this->playback.TrackChanged.connect(this, &TrackListView::OnTrackChanged);\n this->adapter = new Adapter(*this);\n this->lastQueryHash = 0;\n this->lastChanged = now();\n this->formatter = formatter;\n\n if (!MISSING_ENTRY) {\n auto e = std::shared_ptr<SingleLineEntry>(new SingleLineEntry(\"track missing\"));\n e->SetAttrs(COLOR_PAIR(CURSESPP_TEXT_ERROR));\n MISSING_ENTRY = e;\n }\n}\n\nTrackListView::~TrackListView() {\n delete this->adapter;\n this->adapter = nullptr;\n}\n\nvoid TrackListView::Requery(std::shared_ptr<TrackListQueryBase> query) {\n this->query = query;\n this->library->Enqueue(this->query);\n}\n\nvoid TrackListView::OnQueryCompleted(IQueryPtr query) {\n if (query == this->query) {\n this->PostMessage(WINDOW_MESSAGE_QUERY_COMPLETED);\n }\n}\n\nvoid TrackListView::OnSelectionChanged(size_t newIndex, size_t oldIndex) {\n ListWindow::OnSelectionChanged(newIndex, oldIndex);\n this->lastChanged = now();\n}\n\nstd::shared_ptr<TrackList> TrackListView::GetTrackList() {\n return this->metadata;\n}\n\nvoid TrackListView::Clear() {\n this->query.reset();\n this->metadata.reset(new TrackList(this->library));\n this->headers.reset(new std::set<size_t>());\n this->OnAdapterChanged();\n}\n\nvoid TrackListView::ScrollToPlaying() {\n if (this->playing && this->metadata) {\n DBID id = this->playing->Id();\n for (size_t i = 0; i < this->metadata->Count(); i++) {\n if (this->metadata->GetId(i) == id) {\n this->SetSelectedIndex(i);\n\n auto pos = this->GetScrollPosition();\n size_t first = pos.firstVisibleEntryIndex;\n size_t last = first + pos.visibleEntryCount;\n if (i < first || i > last) {\n \/* only scroll if the playing track is not visible. *\/\n this->ScrollTo(i);\n }\n break;\n }\n }\n }\n}\n\nvoid TrackListView::ProcessMessage(IMessage &message) {\n if (message.Type() == WINDOW_MESSAGE_QUERY_COMPLETED) {\n if (this->query && this->query->GetStatus() == IQuery::Finished) {\n this->metadata = this->query->GetResult();\n this->headers = this->query->GetHeaders();\n\n \/* if the query was functionally the same as the last query, don't\n mess with the selected index *\/\n if (this->lastQueryHash != query->GetQueryHash()) {\n this->SetSelectedIndex(0);\n this->ScrollToTop();\n }\n\n this->lastQueryHash = this->query->GetQueryHash();\n this->query.reset();\n\n this->OnAdapterChanged(); \/* internal handling *\/\n this->Requeried(); \/* for external handlers *\/\n }\n }\n}\n\nbool TrackListView::KeyPress(const std::string& key) {\n if (Hotkeys::Is(Hotkeys::NavigateJumpToPlaying, key)) {\n this->ScrollToPlaying();\n return true;\n }\n\n return ListWindow::KeyPress(key);\n}\n\nvoid TrackListView::OnTrackChanged(size_t index, musik::core::TrackPtr track) {\n this->playing = track;\n this->OnAdapterChanged();\n\n if (now() - lastChanged >= AUTO_SCROLL_COOLDOWN) {\n this->ScrollToPlaying();\n }\n}\n\nIScrollAdapter& TrackListView::GetScrollAdapter() {\n return *this->adapter;\n}\n\nTrackListView::Adapter::Adapter(TrackListView &parent)\n: parent(parent) {\n}\n\nsize_t TrackListView::Adapter::GetEntryCount() {\n return parent.metadata ? parent.metadata->Count() : 0;\n}\n\n#define TRACK_COL_WIDTH 3\n#define ARTIST_COL_WIDTH 17\n#define DURATION_COL_WIDTH 5 \/* 00:00 *\/\n\nstatic std::string formatWithoutAlbum(TrackPtr track, size_t width) {\n std::string trackNum = text::Align(\n track->GetValue(constants::Track::TRACK_NUM),\n text::AlignRight,\n TRACK_COL_WIDTH);\n\n std::string duration = text::Align(\n musik::box::duration::Duration(track->GetValue(constants::Track::DURATION)),\n text::AlignRight,\n DURATION_COL_WIDTH);\n\n std::string artist = text::Align(\n track->GetValue(constants::Track::ARTIST),\n text::AlignLeft,\n ARTIST_COL_WIDTH);\n\n int titleWidth =\n width -\n TRACK_COL_WIDTH -\n DURATION_COL_WIDTH -\n ARTIST_COL_WIDTH -\n (3 * 3); \/* 3 = spacing *\/\n\n titleWidth = std::max(0, titleWidth);\n\n std::string title = text::Align(\n track->GetValue(constants::Track::TITLE),\n text::AlignLeft,\n titleWidth);\n\n return boost::str(\n boost::format(\"%s %s %s %s\")\n % trackNum % title % duration % artist);\n}\n\nIScrollAdapter::EntryPtr TrackListView::Adapter::GetEntry(size_t index) {\n bool selected = index == parent.GetSelectedIndex();\n int64 attrs = selected ? COLOR_PAIR(CURSESPP_HIGHLIGHTED_LIST_ITEM) : -1LL;\n\n TrackPtr track = parent.metadata->Get(index);\n\n if (!track) {\n return MISSING_ENTRY;\n }\n\n TrackPtr playing = parent.playing;\n if (playing &&\n playing->Id() == track->Id() &&\n playing->LibraryId() == track->LibraryId())\n {\n if (selected) {\n attrs = COLOR_PAIR(CURSESPP_HIGHLIGHTED_SELECTED_LIST_ITEM);\n }\n else {\n attrs = COLOR_PAIR(CURSESPP_SELECTED_LIST_ITEM);\n }\n }\n\n std::string text = parent.formatter\n ? parent.formatter(track, this->GetWidth())\n : formatWithoutAlbum(track, this->GetWidth());\n\n if (this->parent.headers->find(index) != this->parent.headers->end()) {\n std::string album = track->GetValue(constants::Track::ALBUM);\n std::shared_ptr<EntryWithHeader> entry(new EntryWithHeader(album, text));\n entry->SetAttrs(COLOR_PAIR(CURSESPP_LIST_ITEM_HEADER), attrs);\n return entry;\n }\n else {\n std::shared_ptr<SingleLineEntry> entry(new SingleLineEntry(text));\n entry->SetAttrs(attrs);\n return entry;\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/**\n * 2.4.4 constexpr 和 常量表达式\n * @Author Bob\n * @Eamil 0haizhu0@gmail.com\n * @Date 2017\/7\/12\n *\/\nint main() {\n \/**\n * 常量表达式:是指值不会改变并且在编译过程中就能得到计算结果的表达式。\n * 显然,字面值属于常量表达式。\n * 一个对象是不是常量表达式由它的数据类型和初始值共同决定。\n *\/\n const int max_files = 20; \/\/ 是常量表达式\n const int limit = max_files; \/\/ 是常量表达式\n int staff_size = 27; \/\/ 不是常量表达式:虽然初始值是个字面值常量,但他的数据类型只是普通int而不是const int,所以不属于常量表达式。\n \/\/ const int sz = get_size(); \/\/ sz不是常量表达式:尽管sz本身是一个常量,但是它的具体指要到运行时才能获取到,所以不属于常量表达式。\n\n \/**\n * C++ 11 标准中,允许将常量声明为constexpr类型以便编辑器来验证变量的值是否是一个常量表达式。\n * 声明为constexpr的变量一定是一个常量,而且必须用常量表达式初始化。\n *\/\n constexpr int mf = 20; \/\/ 20 是常量表达式\n constexpr int limit2 = mf + 1; \/\/ mf+1 是常量表达式\n \/\/ constexpr int sz2 = size(); \/\/ 只有当size是一个constexpr函数时才是一条正确的声明语句\n\n \/**\n * 字面值类型:常量表达式的值需要在编译时就得到计算,因此对声明constexpr时用到的类型必须有所限制。\n * 因为这些类型一般比较简单,值也显而易见、容易得到,就把它们成为\"字面值类型\"(literal type)。\n * 目前接触过的数据类型中,算数类型、引用、指针都属于字面值类型。\n * 自定义Sales_item、IO库、string 类型则不属于字面值类型,也就不能被定义为constexpr。\n *\/\n\n \/**\n * 指针和constexpr:在constexpr声明中如果定义了一个指针,限定符constexpr仅对指针有效,与指针所指的对象无关。\n * 如下所示:constexpr把它所定义的对象置为了顶层const。\n *\/\n const int *p = nullptr; \/\/ p是一个指向整数常量的指针\n constexpr int *q = nullptr; \/\/ q是一个指向整数的常量指针\n\n \/**\n * 与其他常量指针类似,constexpr既可以指向常量也可以指向非常量。\n *\/\n\n return 0;\n}\n<commit_msg>2.4.4 constexpr 和 常量表达式<commit_after>\/**\n * 2.4.4 constexpr 和 常量表达式\n * @Author Bob\n * @Eamil 0haizhu0@gmail.com\n * @Date 2017\/7\/12\n *\/\nint main() {\n \/**\n * 常量表达式:是指值不会改变并且在编译过程中就能得到计算结果的表达式。\n * 显然,字面值属于常量表达式。\n * 一个对象是不是常量表达式由它的数据类型和初始值共同决定。\n *\/\n const int max_files = 20; \/\/ 是常量表达式\n const int limit = max_files; \/\/ 是常量表达式\n int staff_size = 27; \/\/ 不是常量表达式:虽然初始值是个字面值常量,但他的数据类型只是普通int而不是const int,所以不属于常量表达式。\n \/\/ const int sz = get_size(); \/\/ sz不是常量表达式:尽管sz本身是一个常量,但是它的具体指要到运行时才能获取到,所以不属于常量表达式。\n\n \/**\n * C++ 11 标准中,允许将常量声明为constexpr类型以便编辑器来验证变量的值是否是一个常量表达式。\n * 声明为constexpr的变量一定是一个常量,而且必须用常量表达式初始化。\n *\/\n constexpr int mf = 20; \/\/ 20 是常量表达式\n constexpr int limit2 = mf + 1; \/\/ mf+1 是常量表达式\n \/\/ constexpr int sz2 = size(); \/\/ 只有当size是一个constexpr函数时才是一条正确的声明语句\n\n \/**\n * 字面值类型:常量表达式的值需要在编译时就得到计算,因此对声明constexpr时用到的类型必须有所限制。\n * 因为这些类型一般比较简单,值也显而易见、容易得到,就把它们成为\"字面值类型\"(literal type)。\n * 目前接触过的数据类型中,算数类型、引用、指针都属于字面值类型。\n * 自定义Sales_item、IO库、string 类型则不属于字面值类型,也就不能被定义为constexpr。\n *\/\n\n \/**\n * 指针和constexpr:在constexpr声明中如果定义了一个指针,限定符constexpr仅对指针有效,与指针所指的对象无关。\n * 如下所示:constexpr把它所定义的对象置为了顶层const。\n *\/\n const int *p = nullptr; \/\/ p是一个指向整数常量的指针,可以修改p指向的对象,但不能修改对象的值\n constexpr int *q = nullptr; \/\/ q是一个指向整数的常量指针,不能修改p指向的对象,但能修改对象的值\n\n \/**\n * 与其他常量指针类似,constexpr既可以指向常量也可以指向非常量。\n *\n * 总的来说,使用const的地方就可以用constexpr,但要注意最后一个范例的区别\n *\/\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2011 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/ui\/views\/tab_contents\/native_tab_contents_container_aura.h\"\n\n#include \"chrome\/browser\/ui\/view_ids.h\"\n#include \"chrome\/browser\/ui\/views\/tab_contents\/tab_contents_container.h\"\n#include \"chrome\/browser\/ui\/views\/tab_contents\/tab_contents_view_views.h\"\n#include \"content\/browser\/tab_contents\/interstitial_page.h\"\n#include \"content\/browser\/tab_contents\/tab_contents.h\"\n#include \"ui\/aura\/window.h\"\n#include \"ui\/base\/accessibility\/accessible_view_state.h\"\n#include \"ui\/views\/focus\/focus_manager.h\"\n#include \"ui\/views\/focus\/widget_focus_manager.h\"\n#include \"ui\/views\/views_delegate.h\"\n\nusing content::WebContents;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ NativeTabContentsContainerAura, public:\n\nNativeTabContentsContainerAura::NativeTabContentsContainerAura(\n TabContentsContainer* container)\n : container_(container) {\n set_id(VIEW_ID_TAB_CONTAINER_FOCUS_VIEW);\n}\n\nNativeTabContentsContainerAura::~NativeTabContentsContainerAura() {\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ NativeTabContentsContainerAura, NativeTabContentsContainer overrides:\n\nvoid NativeTabContentsContainerAura::AttachContents(WebContents* contents) {\n \/\/ We need to register the tab contents window with the BrowserContainer so\n \/\/ that the BrowserContainer is the focused view when the focus is on the\n \/\/ TabContents window (for the TabContents case).\n set_focus_view(this);\n\n Attach(contents->GetNativeView());\n}\n\nvoid NativeTabContentsContainerAura::DetachContents(WebContents* contents) {\n \/\/ Detach the TabContents. Do this before we unparent the\n \/\/ TabContentsViewViews so that the window hierarchy is intact for any\n \/\/ cleanup during Detach().\n Detach();\n}\n\nvoid NativeTabContentsContainerAura::SetFastResize(bool fast_resize) {\n set_fast_resize(fast_resize);\n}\n\nbool NativeTabContentsContainerAura::GetFastResize() const {\n return fast_resize();\n}\n\nbool NativeTabContentsContainerAura::FastResizeAtLastLayout() const {\n return fast_resize_at_last_layout();\n}\n\nvoid NativeTabContentsContainerAura::RenderViewHostChanged(\n RenderViewHost* old_host,\n RenderViewHost* new_host) {\n \/\/ If we are focused, we need to pass the focus to the new RenderViewHost.\n if (GetFocusManager()->GetFocusedView() == this)\n OnFocus();\n}\n\nviews::View* NativeTabContentsContainerAura::GetView() {\n return this;\n}\n\nvoid NativeTabContentsContainerAura::WebContentsFocused(WebContents* contents) {\n views::FocusManager* focus_manager = GetFocusManager();\n if (!focus_manager) {\n NOTREACHED();\n return;\n }\n focus_manager->SetFocusedView(this);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ NativeTabContentsContainerAura, views::View overrides:\n\nbool NativeTabContentsContainerAura::SkipDefaultKeyEventProcessing(\n const views::KeyEvent& e) {\n \/\/ Don't look-up accelerators or tab-traversal if we are showing a non-crashed\n \/\/ TabContents.\n \/\/ We'll first give the page a chance to process the key events. If it does\n \/\/ not process them, they'll be returned to us and we'll treat them as\n \/\/ accelerators then.\n return container_->web_contents() &&\n !container_->web_contents()->IsCrashed();\n}\n\nbool NativeTabContentsContainerAura::IsFocusable() const {\n \/\/ We need to be focusable when our contents is not a view hierarchy, as\n \/\/ clicking on the contents needs to focus us.\n return container_->tab_contents() != NULL;\n}\n\nvoid NativeTabContentsContainerAura::OnFocus() {\n if (container_->web_contents())\n container_->web_contents()->Focus();\n}\n\nvoid NativeTabContentsContainerAura::RequestFocus() {\n \/\/ This is a hack to circumvent the fact that a the OnFocus() method is not\n \/\/ invoked when RequestFocus() is called on an already focused view.\n \/\/ The TabContentsContainer is the view focused when the TabContents has\n \/\/ focus. When switching between from one tab that has focus to another tab\n \/\/ that should also have focus, RequestFocus() is invoked one the\n \/\/ TabContentsContainer. In order to make sure OnFocus() is invoked we need\n \/\/ to clear the focus before hands.\n if (GetFocusManager()) {\n \/\/ Disable notifications. Clear focus will assign the focus to the main\n \/\/ browser window. Because this change of focus was not user requested,\n \/\/ don't send it to listeners.\n views::AutoNativeNotificationDisabler local_notification_disabler;\n GetFocusManager()->ClearFocus();\n }\n View::RequestFocus();\n}\n\nvoid NativeTabContentsContainerAura::AboutToRequestFocusFromTabTraversal(\n bool reverse) {\n container_->web_contents()->FocusThroughTabTraversal(reverse);\n}\n\nvoid NativeTabContentsContainerAura::GetAccessibleState(\n ui::AccessibleViewState* state) {\n state->role = ui::AccessibilityTypes::ROLE_GROUPING;\n}\n\ngfx::NativeViewAccessible\n NativeTabContentsContainerAura::GetNativeViewAccessible() {\n \/\/ TODO(beng):\n NOTIMPLEMENTED();\n return View::GetNativeViewAccessible();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ NativeTabContentsContainer, public:\n\n\/\/ static\nNativeTabContentsContainer* NativeTabContentsContainer::CreateNativeContainer(\n TabContentsContainer* container) {\n return new NativeTabContentsContainerAura(container);\n}\n<commit_msg>Fix aura<commit_after>\/\/ Copyright (c) 2011 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/ui\/views\/tab_contents\/native_tab_contents_container_aura.h\"\n\n#include \"chrome\/browser\/ui\/view_ids.h\"\n#include \"chrome\/browser\/ui\/views\/tab_contents\/tab_contents_container.h\"\n#include \"chrome\/browser\/ui\/views\/tab_contents\/tab_contents_view_views.h\"\n#include \"content\/browser\/tab_contents\/interstitial_page.h\"\n#include \"content\/browser\/tab_contents\/tab_contents.h\"\n#include \"ui\/aura\/window.h\"\n#include \"ui\/base\/accessibility\/accessible_view_state.h\"\n#include \"ui\/views\/focus\/focus_manager.h\"\n#include \"ui\/views\/focus\/widget_focus_manager.h\"\n#include \"ui\/views\/views_delegate.h\"\n\nusing content::WebContents;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ NativeTabContentsContainerAura, public:\n\nNativeTabContentsContainerAura::NativeTabContentsContainerAura(\n TabContentsContainer* container)\n : container_(container) {\n set_id(VIEW_ID_TAB_CONTAINER_FOCUS_VIEW);\n}\n\nNativeTabContentsContainerAura::~NativeTabContentsContainerAura() {\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ NativeTabContentsContainerAura, NativeTabContentsContainer overrides:\n\nvoid NativeTabContentsContainerAura::AttachContents(WebContents* contents) {\n \/\/ We need to register the tab contents window with the BrowserContainer so\n \/\/ that the BrowserContainer is the focused view when the focus is on the\n \/\/ TabContents window (for the TabContents case).\n set_focus_view(this);\n\n Attach(contents->GetNativeView());\n}\n\nvoid NativeTabContentsContainerAura::DetachContents(WebContents* contents) {\n \/\/ Detach the TabContents. Do this before we unparent the\n \/\/ TabContentsViewViews so that the window hierarchy is intact for any\n \/\/ cleanup during Detach().\n Detach();\n}\n\nvoid NativeTabContentsContainerAura::SetFastResize(bool fast_resize) {\n set_fast_resize(fast_resize);\n}\n\nbool NativeTabContentsContainerAura::GetFastResize() const {\n return fast_resize();\n}\n\nbool NativeTabContentsContainerAura::FastResizeAtLastLayout() const {\n return fast_resize_at_last_layout();\n}\n\nvoid NativeTabContentsContainerAura::RenderViewHostChanged(\n RenderViewHost* old_host,\n RenderViewHost* new_host) {\n \/\/ If we are focused, we need to pass the focus to the new RenderViewHost.\n if (GetFocusManager()->GetFocusedView() == this)\n OnFocus();\n}\n\nviews::View* NativeTabContentsContainerAura::GetView() {\n return this;\n}\n\nvoid NativeTabContentsContainerAura::WebContentsFocused(WebContents* contents) {\n views::FocusManager* focus_manager = GetFocusManager();\n if (!focus_manager) {\n NOTREACHED();\n return;\n }\n focus_manager->SetFocusedView(this);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ NativeTabContentsContainerAura, views::View overrides:\n\nbool NativeTabContentsContainerAura::SkipDefaultKeyEventProcessing(\n const views::KeyEvent& e) {\n \/\/ Don't look-up accelerators or tab-traversal if we are showing a non-crashed\n \/\/ TabContents.\n \/\/ We'll first give the page a chance to process the key events. If it does\n \/\/ not process them, they'll be returned to us and we'll treat them as\n \/\/ accelerators then.\n return container_->web_contents() &&\n !container_->web_contents()->IsCrashed();\n}\n\nbool NativeTabContentsContainerAura::IsFocusable() const {\n \/\/ We need to be focusable when our contents is not a view hierarchy, as\n \/\/ clicking on the contents needs to focus us.\n return container_->web_contents() != NULL;\n}\n\nvoid NativeTabContentsContainerAura::OnFocus() {\n if (container_->web_contents())\n container_->web_contents()->Focus();\n}\n\nvoid NativeTabContentsContainerAura::RequestFocus() {\n \/\/ This is a hack to circumvent the fact that a the OnFocus() method is not\n \/\/ invoked when RequestFocus() is called on an already focused view.\n \/\/ The TabContentsContainer is the view focused when the TabContents has\n \/\/ focus. When switching between from one tab that has focus to another tab\n \/\/ that should also have focus, RequestFocus() is invoked one the\n \/\/ TabContentsContainer. In order to make sure OnFocus() is invoked we need\n \/\/ to clear the focus before hands.\n if (GetFocusManager()) {\n \/\/ Disable notifications. Clear focus will assign the focus to the main\n \/\/ browser window. Because this change of focus was not user requested,\n \/\/ don't send it to listeners.\n views::AutoNativeNotificationDisabler local_notification_disabler;\n GetFocusManager()->ClearFocus();\n }\n View::RequestFocus();\n}\n\nvoid NativeTabContentsContainerAura::AboutToRequestFocusFromTabTraversal(\n bool reverse) {\n container_->web_contents()->FocusThroughTabTraversal(reverse);\n}\n\nvoid NativeTabContentsContainerAura::GetAccessibleState(\n ui::AccessibleViewState* state) {\n state->role = ui::AccessibilityTypes::ROLE_GROUPING;\n}\n\ngfx::NativeViewAccessible\n NativeTabContentsContainerAura::GetNativeViewAccessible() {\n \/\/ TODO(beng):\n NOTIMPLEMENTED();\n return View::GetNativeViewAccessible();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ NativeTabContentsContainer, public:\n\n\/\/ static\nNativeTabContentsContainer* NativeTabContentsContainer::CreateNativeContainer(\n TabContentsContainer* container) {\n return new NativeTabContentsContainerAura(container);\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2015 Open Source Robotics Foundation, Inc.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \"rclcpp\/executors\/multi_threaded_executor.hpp\"\n\n#include <chrono>\n#include <functional>\n#include <vector>\n\n#include \"rclcpp\/utilities.hpp\"\n#include \"rclcpp\/scope_exit.hpp\"\n\nusing rclcpp::executors::multi_threaded_executor::MultiThreadedExecutor;\n\nMultiThreadedExecutor::MultiThreadedExecutor(rclcpp::memory_strategy::MemoryStrategy::SharedPtr ms)\n: executor::Executor(ms)\n{\n number_of_threads_ = std::thread::hardware_concurrency();\n if (number_of_threads_ == 0) {\n number_of_threads_ = 1;\n }\n}\n\nMultiThreadedExecutor::~MultiThreadedExecutor() {}\n\nvoid\nMultiThreadedExecutor::spin()\n{\n if (spinning.exchange(true)) {\n throw std::runtime_error(\"spin() called while already spinning\");\n }\n RCLCPP_SCOPE_EXIT(this->spinning.store(false); );\n std::vector<std::thread> threads;\n {\n std::lock_guard<std::mutex> wait_lock(wait_mutex_);\n size_t thread_id = 1;\n for (size_t i = number_of_threads_; i > 0; --i) {\n std::this_thread::sleep_for(std::chrono::milliseconds(100));\n auto func = std::bind(&MultiThreadedExecutor::run, this, thread_id++);\n threads.emplace_back(func);\n }\n }\n for (auto & thread : threads) {\n thread.join();\n }\n}\n\nsize_t\nMultiThreadedExecutor::get_number_of_threads()\n{\n return number_of_threads_;\n}\n\nvoid\nMultiThreadedExecutor::run(size_t this_thread_number)\n{\n thread_number_by_thread_id_[std::this_thread::get_id()] = this_thread_number;\n while (rclcpp::utilities::ok() && spinning.load()) {\n executor::AnyExecutable::SharedPtr any_exec;\n {\n std::lock_guard<std::mutex> wait_lock(wait_mutex_);\n if (!rclcpp::utilities::ok() || !spinning.load()) {\n return;\n }\n any_exec = get_next_executable();\n }\n execute_any_executable(any_exec);\n }\n}\n<commit_msg>Get rid of idle thread in MultiThreadedExecutor<commit_after>\/\/ Copyright 2015 Open Source Robotics Foundation, Inc.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \"rclcpp\/executors\/multi_threaded_executor.hpp\"\n\n#include <chrono>\n#include <functional>\n#include <vector>\n\n#include \"rclcpp\/utilities.hpp\"\n#include \"rclcpp\/scope_exit.hpp\"\n\nusing rclcpp::executors::multi_threaded_executor::MultiThreadedExecutor;\n\nMultiThreadedExecutor::MultiThreadedExecutor(rclcpp::memory_strategy::MemoryStrategy::SharedPtr ms)\n: executor::Executor(ms)\n{\n number_of_threads_ = std::thread::hardware_concurrency();\n if (number_of_threads_ == 0) {\n number_of_threads_ = 1;\n }\n}\n\nMultiThreadedExecutor::~MultiThreadedExecutor() {}\n\nvoid\nMultiThreadedExecutor::spin()\n{\n if (spinning.exchange(true)) {\n throw std::runtime_error(\"spin() called while already spinning\");\n }\n RCLCPP_SCOPE_EXIT(this->spinning.store(false); );\n std::vector<std::thread> threads;\n size_t thread_id = 0;\n {\n std::lock_guard<std::mutex> wait_lock(wait_mutex_);\n for (; thread_id < number_of_threads_ - 1; ++thread_id) {\n std::this_thread::sleep_for(std::chrono::milliseconds(100));\n auto func = std::bind(&MultiThreadedExecutor::run, this, thread_id);\n threads.emplace_back(func);\n }\n }\n\n run(thread_id);\n for (auto & thread : threads) {\n thread.join();\n }\n}\n\nsize_t\nMultiThreadedExecutor::get_number_of_threads()\n{\n return number_of_threads_;\n}\n\nvoid\nMultiThreadedExecutor::run(size_t this_thread_number)\n{\n thread_number_by_thread_id_[std::this_thread::get_id()] = this_thread_number;\n while (rclcpp::utilities::ok() && spinning.load()) {\n executor::AnyExecutable::SharedPtr any_exec;\n {\n std::lock_guard<std::mutex> wait_lock(wait_mutex_);\n if (!rclcpp::utilities::ok() || !spinning.load()) {\n return;\n }\n any_exec = get_next_executable();\n }\n execute_any_executable(any_exec);\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2015 Open Source Robotics Foundation, Inc.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \"rclcpp\/executors\/multi_threaded_executor.hpp\"\n\n#include <chrono>\n#include <functional>\n#include <vector>\n\n#include \"rclcpp\/utilities.hpp\"\n#include \"rclcpp\/scope_exit.hpp\"\n\nusing rclcpp::executors::multi_threaded_executor::MultiThreadedExecutor;\n\nMultiThreadedExecutor::MultiThreadedExecutor(rclcpp::memory_strategy::MemoryStrategy::SharedPtr ms)\n: executor::Executor(ms)\n{\n number_of_threads_ = std::thread::hardware_concurrency();\n if (number_of_threads_ == 0) {\n number_of_threads_ = 1;\n }\n}\n\nMultiThreadedExecutor::~MultiThreadedExecutor() {}\n\nvoid\nMultiThreadedExecutor::spin()\n{\n if (spinning.exchange(true)) {\n throw std::runtime_error(\"spin() called while already spinning\");\n }\n RCLCPP_SCOPE_EXIT(this->spinning.store(false); );\n std::vector<std::thread> threads;\n size_t thread_id = 0;\n {\n std::lock_guard<std::mutex> wait_lock(wait_mutex_);\n for (; thread_id < number_of_threads_ - 1; ++thread_id) {\n std::this_thread::sleep_for(std::chrono::milliseconds(100));\n auto func = std::bind(&MultiThreadedExecutor::run, this, thread_id);\n threads.emplace_back(func);\n }\n }\n\n run(thread_id);\n for (auto & thread : threads) {\n thread.join();\n }\n}\n\nsize_t\nMultiThreadedExecutor::get_number_of_threads()\n{\n return number_of_threads_;\n}\n\nvoid\nMultiThreadedExecutor::run(size_t this_thread_number)\n{\n thread_number_by_thread_id_[std::this_thread::get_id()] = this_thread_number;\n while (rclcpp::utilities::ok() && spinning.load()) {\n executor::AnyExecutable::SharedPtr any_exec;\n {\n std::lock_guard<std::mutex> wait_lock(wait_mutex_);\n if (!rclcpp::utilities::ok() || !spinning.load()) {\n return;\n }\n any_exec = get_next_executable();\n }\n execute_any_executable(any_exec);\n }\n}\n<commit_msg>remove excess sleep identified in #169<commit_after>\/\/ Copyright 2015 Open Source Robotics Foundation, Inc.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \"rclcpp\/executors\/multi_threaded_executor.hpp\"\n\n#include <chrono>\n#include <functional>\n#include <vector>\n\n#include \"rclcpp\/utilities.hpp\"\n#include \"rclcpp\/scope_exit.hpp\"\n\nusing rclcpp::executors::multi_threaded_executor::MultiThreadedExecutor;\n\nMultiThreadedExecutor::MultiThreadedExecutor(rclcpp::memory_strategy::MemoryStrategy::SharedPtr ms)\n: executor::Executor(ms)\n{\n number_of_threads_ = std::thread::hardware_concurrency();\n if (number_of_threads_ == 0) {\n number_of_threads_ = 1;\n }\n}\n\nMultiThreadedExecutor::~MultiThreadedExecutor() {}\n\nvoid\nMultiThreadedExecutor::spin()\n{\n if (spinning.exchange(true)) {\n throw std::runtime_error(\"spin() called while already spinning\");\n }\n RCLCPP_SCOPE_EXIT(this->spinning.store(false); );\n std::vector<std::thread> threads;\n size_t thread_id = 0;\n {\n std::lock_guard<std::mutex> wait_lock(wait_mutex_);\n for (; thread_id < number_of_threads_ - 1; ++thread_id) {\n auto func = std::bind(&MultiThreadedExecutor::run, this, thread_id);\n threads.emplace_back(func);\n }\n }\n\n run(thread_id);\n for (auto & thread : threads) {\n thread.join();\n }\n}\n\nsize_t\nMultiThreadedExecutor::get_number_of_threads()\n{\n return number_of_threads_;\n}\n\nvoid\nMultiThreadedExecutor::run(size_t this_thread_number)\n{\n thread_number_by_thread_id_[std::this_thread::get_id()] = this_thread_number;\n while (rclcpp::utilities::ok() && spinning.load()) {\n executor::AnyExecutable::SharedPtr any_exec;\n {\n std::lock_guard<std::mutex> wait_lock(wait_mutex_);\n if (!rclcpp::utilities::ok() || !spinning.load()) {\n return;\n }\n any_exec = get_next_executable();\n }\n execute_any_executable(any_exec);\n }\n}\n<|endoftext|>"} {"text":"<commit_before>#include <ncurses.h>\n#include <stdint.h>\n\n#include \"display\/Screen.h\"\n\nint main()\n{\n\tScreen screen;\n\n\t\/\/printw(\"Starting curses mode with multiple windows...\");\n\t\/\/refresh();\n\n\t\/\/getch();\n\n\tuint32_t screen_y = screen.getHeight();\n\tuint32_t screen_x = screen.getWidth();\n\n\tscreen_y = 40;\n\tscreen_x = 40;\n\n\tWINDOW* top = newwin(1, screen_x, 0, 0);\n\tWINDOW* left = newwin(screen_y-1, 10, 1, 0);\n\tWINDOW* right = newwin(screen_y-1, screen_x-10, 1, 10);\n\n\tmvwprintw(top, 0, 0, \"Top\");\n\tmvwprintw(left, 0, 0, \"Left\");\n\tmvwprintw(right, 0, 0, \"Right\");\n\n\twrefresh(top);\n\twrefresh(left);\n\twrefresh(right);\n\n\tgetch();\n}\n<commit_msg>InterfaceTest panels have borders, labels.<commit_after>#include <ncurses.h>\n#include <stdint.h>\n\n#include \"display\/Screen.h\"\n\nint main()\n{\n\tScreen screen;\n\n\tuint32_t screen_y = screen.getHeight();\n\tuint32_t screen_x = screen.getWidth();\n\n\tWINDOW* top = newwin(3, screen_x, 0, 0);\n\tWINDOW* left = newwin(screen_y-2, 20, 2, 0);\n\tWINDOW* right = newwin(screen_y-2, screen_x-19, 2, 19);\n\n\twborder(top, '|', '|', '-', '-', '+', '+', '+', '+');\n\twborder(left, '|', '|', '-', '-', '+', '+', '+', '+');\n\twborder(right, '|', '|', '-', '-', '+', '+', '+', '+');\n\n\tmvwprintw(top, 0, 1, \"Message Panel\");\n\tmvwprintw(left, 0, 1, \"Stat Panel\");\n\tmvwprintw(right, 0, 1, \"Main Panel\");\n\n\twrefresh(top);\n\twrefresh(left);\n\twrefresh(right);\n\n\tgetch();\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright 2007-2017 Content Management AG\n * All rights reserved.\n *\n * author: Max Kellermann <mk@cm4all.com>\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * - Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n *\n * - Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the\n * distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,\n * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED\n * OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#ifndef BENG_PROXY_LB_MONITOR_CONTROLLER_HXX\n#define BENG_PROXY_LB_MONITOR_CONTROLLER_HXX\n\n#include \"Monitor.hxx\"\n#include \"io\/Logger.hxx\"\n#include \"event\/TimerEvent.hxx\"\n#include \"net\/AllocatedSocketAddress.hxx\"\n#include \"net\/FailureRef.hxx\"\n#include \"util\/Cancellable.hxx\"\n\nclass EventLoop;\nclass FailureManager;\nclass SocketAddress;\nstruct LbMonitorConfig;\nstruct LbMonitorClass;\nclass LbMonitorController;\n\nclass LbMonitorController final : public LbMonitorHandler {\n EventLoop &event_loop;\n FailureRef failure;\n\n const LbMonitorConfig &config;\n const AllocatedSocketAddress address;\n const LbMonitorClass &class_;\n\n const Logger logger;\n\n const struct timeval interval;\n TimerEvent interval_event;\n\n const struct timeval timeout;\n TimerEvent timeout_event;\n\n CancellablePointer cancel_ptr;\n\n bool state = true;\n bool fade = false;\n\npublic:\n LbMonitorController(EventLoop &_event_loop,\n FailureManager &_failure_manager,\n const char *node_name,\n const LbMonitorConfig &_config,\n SocketAddress _address,\n const LbMonitorClass &_class);\n\n ~LbMonitorController();\n\n LbMonitorController(const LbMonitorController &) = delete;\n LbMonitorController &operator=(const LbMonitorController &) = delete;\n\n const SocketAddress GetAddress() const {\n return address;\n }\n\nprivate:\n void IntervalCallback();\n void TimeoutCallback();\n\n \/* virtual methods from class LbMonitorHandler *\/\n virtual void Success() override;\n virtual void Fade() override;\n virtual void Timeout() override;\n virtual void Error(std::exception_ptr e) override;\n};\n\n#endif\n<commit_msg>lb\/MonitorStock: add reference counter<commit_after>\/*\n * Copyright 2007-2017 Content Management AG\n * All rights reserved.\n *\n * author: Max Kellermann <mk@cm4all.com>\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * - Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n *\n * - Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the\n * distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,\n * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED\n * OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#ifndef BENG_PROXY_LB_MONITOR_CONTROLLER_HXX\n#define BENG_PROXY_LB_MONITOR_CONTROLLER_HXX\n\n#include \"Monitor.hxx\"\n#include \"io\/Logger.hxx\"\n#include \"event\/TimerEvent.hxx\"\n#include \"net\/AllocatedSocketAddress.hxx\"\n#include \"net\/FailureRef.hxx\"\n#include \"util\/Cancellable.hxx\"\n\nclass EventLoop;\nclass FailureManager;\nclass SocketAddress;\nstruct LbMonitorConfig;\nstruct LbMonitorClass;\nclass LbMonitorController;\n\nclass LbMonitorController final : public LbMonitorHandler {\n EventLoop &event_loop;\n FailureRef failure;\n\n const LbMonitorConfig &config;\n const AllocatedSocketAddress address;\n const LbMonitorClass &class_;\n\n const Logger logger;\n\n const struct timeval interval;\n TimerEvent interval_event;\n\n const struct timeval timeout;\n TimerEvent timeout_event;\n\n CancellablePointer cancel_ptr;\n\n bool state = true;\n bool fade = false;\n\n unsigned ref = 0;\n\npublic:\n LbMonitorController(EventLoop &_event_loop,\n FailureManager &_failure_manager,\n const char *node_name,\n const LbMonitorConfig &_config,\n SocketAddress _address,\n const LbMonitorClass &_class);\n\n ~LbMonitorController();\n\n LbMonitorController(const LbMonitorController &) = delete;\n LbMonitorController &operator=(const LbMonitorController &) = delete;\n\n void Ref() noexcept {\n ++ref;\n }\n\n \/**\n * @return true if the reference counter has dropped to 0 (and the\n * object can be deleted)\n *\/\n bool Unref() noexcept {\n return --ref == 0;\n }\n\n const SocketAddress GetAddress() const {\n return address;\n }\n\nprivate:\n void IntervalCallback();\n void TimeoutCallback();\n\n \/* virtual methods from class LbMonitorHandler *\/\n virtual void Success() override;\n virtual void Fade() override;\n virtual void Timeout() override;\n virtual void Error(std::exception_ptr e) override;\n};\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/\/snippet-sourcedescription:[update_table.cpp demonstrates how to update information about an Amazon DynamoDB table.]\r\n\/\/snippet-keyword:[AWS SDK for C++]\r\n\/\/snippet-keyword:[Code Sample]\r\n\/\/snippet-service:[Amazon DynamoDB]\r\n\/\/snippet-sourcetype:[full-example]\r\n\/\/snippet-sourcedate:[11\/30\/2021]\r\n\/\/snippet-sourceauthor:[scmacdon - aws]\r\n\r\n\r\n\/*\r\n Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\r\n SPDX-License-Identifier: Apache-2.0\r\n*\/\r\n\r\n\/\/snippet-start:[dynamodb.cpp.update_table.inc]\r\n#include <aws\/core\/Aws.h>\r\n#include <aws\/core\/utils\/Outcome.h> \r\n#include <aws\/dynamodb\/DynamoDBClient.h>\r\n#include <aws\/dynamodb\/model\/ProvisionedThroughput.h>\r\n#include <aws\/dynamodb\/model\/UpdateTableRequest.h>\r\n#include <iostream>\r\n\/\/snippet-end:[dynamodb.cpp.update_table.inc]\r\n\r\n\r\n\/**\r\n Update a DynamoDB table.\r\n\r\n Takes the name of the table to update, the read capacity and the write\r\n capacity to use.\r\n\r\n To run this C++ code example, ensure that you have setup your development environment, including your credentials.\r\n For information, see this documentation topic:\r\n https:\/\/docs.aws.amazon.com\/sdk-for-cpp\/v1\/developer-guide\/getting-started.html\r\n*\/\r\nint main(int argc, char** argv)\r\n{\r\n const std::string USAGE = \\\r\n \"Usage:\\n\"\r\n \" update_table <table> <read> <write>\\n\\n\"\r\n \"Where:\\n\"\r\n \" table - the table to put the item in.\\n\"\r\n \" read - the new read capacity of the table.\\n\"\r\n \" write - the new write capacity of the table.\\n\\n\"\r\n \"Example:\\n\"\r\n \" update_table HelloTable 16 10\\n\";\r\n\r\n if (argc < 3)\r\n {\r\n std::cout << USAGE;\r\n return 1;\r\n }\r\n\r\n Aws::SDKOptions options;\r\n Aws::InitAPI(options);\r\n {\r\n const Aws::String table(argv[1]);\r\n const long long rc = Aws::Utils::StringUtils::ConvertToInt64(argv[2]);\r\n const long long wc = Aws::Utils::StringUtils::ConvertToInt64(argv[3]);\r\n\r\n \/\/ snippet-start:[dynamodb.cpp.update_table.code]\r\n Aws::Client::ClientConfiguration clientConfig;\r\n Aws::DynamoDB::DynamoDBClient dynamoClient(clientConfig);\r\n\r\n std::cout << \"Updating \" << table << \" with new provisioned throughput values\" << std::endl;\r\n std::cout << \"Read capacity : \" << rc << std::endl;\r\n std::cout << \"Write capacity: \" << wc << std::endl;\r\n\r\n Aws::DynamoDB::Model::UpdateTableRequest utr;\r\n Aws::DynamoDB::Model::ProvisionedThroughput pt;\r\n pt.WithReadCapacityUnits(rc).WithWriteCapacityUnits(wc);\r\n utr.WithProvisionedThroughput(pt).WithTableName(table);\r\n\r\n const Aws::DynamoDB::Model::UpdateTableOutcome& result = dynamoClient.UpdateTable(utr);\r\n if (!result.IsSuccess())\r\n {\r\n std::cout << result.GetError().GetMessage() << std::endl;\r\n return 1;\r\n }\r\n std::cout << \"Done!\" << std::endl;\r\n \/\/ snippet-end:[dynamodb.cpp.update_table.code]\r\n }\r\n Aws::ShutdownAPI(options);\r\n return 0;\r\n}<commit_msg>Delete update_table.cpp<commit_after><|endoftext|>"} {"text":"<commit_before>\/**\n * @file x_tre_split.hpp\n * @author Andrew Wells\n *\n * Defintion of the XTreeSplit class, a class that splits the nodes of an X tree, starting\n * at a leaf node and moving upwards if necessary.\n *\/\n#ifndef __MLPACK_CORE_TREE_RECTANGLE_TREE_X_TREE_SPLIT_HPP\n#define __MLPACK_CORE_TREE_RECTANGLE_TREE_X_TREE_SPLIT_HPP\n\n#include <mlpack\/core.hpp>\n\nnamespace mlpack {\nnamespace tree \/** Trees and tree-building procedures. *\/ {\n\n\/**\n * A Rectangle Tree has new points inserted at the bottom. When these\n * nodes overflow, we split them, moving up the tree and splitting nodes\n * as necessary.\n *\/\ntemplate<typename DescentType,\n\t typename StatisticType,\n\t typename MatType>\nclass XTreeSplit\n{\npublic:\n\n\/** \n * The X-tree paper says that a maximum allowable overlap of 20% works well.\n *\/\nconst static double MAX_OVERLAP = 0.2;\n \n\/**\n * Split a leaf node using the algorithm described in \"The R*-tree: An Efficient and Robust Access method\n * for Points and Rectangles.\" If necessary, this split will propagate\n * upwards through the tree.\n *\/\nstatic void SplitLeafNode(RectangleTree<XTreeSplit<DescentType, StatisticType, MatType>, DescentType, StatisticType, MatType>* tree, std::vector<bool>& relevels);\n\n\/**\n * Split a non-leaf node using the \"default\" algorithm. If this is a root node, the \n * tree increases in depth.\n *\/\nstatic bool SplitNonLeafNode(RectangleTree<XTreeSplit<DescentType, StatisticType, MatType>, DescentType, StatisticType, MatType>* tree, std::vector<bool>& relevels);\n\nprivate:\n\/**\n * Class to allow for faster sorting.\n *\/\nclass sortStruct {\npublic:\n double d;\n int n;\n};\n\n\/**\n * Comparator for sorting with sortStruct.\n *\/\nstatic bool structComp(const sortStruct& s1, const sortStruct& s2) {\n return s1.d < s2.d;\n}\n\n\/**\n * Insert a node into another node.\n *\/\nstatic void InsertNodeIntoTree(\n RectangleTree<XTreeSplit<DescentType, StatisticType, MatType>, DescentType, StatisticType, MatType>* destTree,\n RectangleTree<XTreeSplit<DescentType, StatisticType, MatType>, DescentType, StatisticType, MatType>* srcNode);\n\n};\n\n}; \/\/ namespace tree\n}; \/\/ namespace mlpack\n\n\/\/ Include implementation\n#include \"x_tree_split_impl.hpp\"\n\n#endif<commit_msg>Add comment pointing out that there is a bug.<commit_after>\/**\n * @file x_tre_split.hpp\n * @author Andrew Wells\n *\n * Defintion of the XTreeSplit class, a class that splits the nodes of an X\n * tree, starting at a leaf node and moving upwards if necessary.\n *\n * This is known to have a bug: see #368.\n *\/\n#ifndef __MLPACK_CORE_TREE_RECTANGLE_TREE_X_TREE_SPLIT_HPP\n#define __MLPACK_CORE_TREE_RECTANGLE_TREE_X_TREE_SPLIT_HPP\n\n#include <mlpack\/core.hpp>\n\nnamespace mlpack {\nnamespace tree \/** Trees and tree-building procedures. *\/ {\n\n\/**\n * A Rectangle Tree has new points inserted at the bottom. When these\n * nodes overflow, we split them, moving up the tree and splitting nodes\n * as necessary.\n *\/\ntemplate<typename DescentType,\n\t typename StatisticType,\n\t typename MatType>\nclass XTreeSplit\n{\npublic:\n\n\/**\n * The X-tree paper says that a maximum allowable overlap of 20% works well.\n *\/\nconst static double MAX_OVERLAP = 0.2;\n\n\/**\n * Split a leaf node using the algorithm described in \"The R*-tree: An Efficient and Robust Access method\n * for Points and Rectangles.\" If necessary, this split will propagate\n * upwards through the tree.\n *\/\nstatic void SplitLeafNode(RectangleTree<XTreeSplit<DescentType, StatisticType, MatType>, DescentType, StatisticType, MatType>* tree, std::vector<bool>& relevels);\n\n\/**\n * Split a non-leaf node using the \"default\" algorithm. If this is a root node, the\n * tree increases in depth.\n *\/\nstatic bool SplitNonLeafNode(RectangleTree<XTreeSplit<DescentType, StatisticType, MatType>, DescentType, StatisticType, MatType>* tree, std::vector<bool>& relevels);\n\nprivate:\n\/**\n * Class to allow for faster sorting.\n *\/\nclass sortStruct {\npublic:\n double d;\n int n;\n};\n\n\/**\n * Comparator for sorting with sortStruct.\n *\/\nstatic bool structComp(const sortStruct& s1, const sortStruct& s2) {\n return s1.d < s2.d;\n}\n\n\/**\n * Insert a node into another node.\n *\/\nstatic void InsertNodeIntoTree(\n RectangleTree<XTreeSplit<DescentType, StatisticType, MatType>, DescentType, StatisticType, MatType>* destTree,\n RectangleTree<XTreeSplit<DescentType, StatisticType, MatType>, DescentType, StatisticType, MatType>* srcNode);\n\n};\n\n}; \/\/ namespace tree\n}; \/\/ namespace mlpack\n\n\/\/ Include implementation\n#include \"x_tree_split_impl.hpp\"\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n#include <map>\n#include <vector>\n#include <sstream>\n#include <string>\n#include \"version.h\"\n#include \"ast.h\"\n#include \"generator.h\"\n\nusing std::stringstream;\nusing std::endl;\n\nnamespace ecc\n{\n generator::generator()\n {\n\n }\n\n generator::~generator()\n {\n\n }\n\n void defgen::translate(const ast::elist_t& items, \n\t const std::string& fHeader, \n\t\t\t const std::string& fCode,\n\t\t\t std::ostream& ostr_c, \n\t\t\t std::ostream& ostr_h)\n {\n\tostr_h << tl_header();\n\tostr_c << tl_header();\n\n\t\/** c file needs to include <string>, and our header *\/\n\tostr_c << \"#include <string>\" << endl;\n\n\tstd::string headerLeaf;\n\tint pos = fHeader.rfind('\/');\n\tif ( pos == std::string::npos )\n\t{\n\t \/\/ File is already a leaf\n\t headerLeaf = fHeader;\n\t}\n\telse\n\t{\n\t \/\/ File is not leaf, use everything after the last '\/'\n\t headerLeaf = fHeader.substr(pos+1, fHeader.length()-pos);\n\t}\n\t\n\tostr_c << \"#include \\\"\" << headerLeaf << \"\\\"\" << std::endl;\n\n\tstd::string guard = headerLeaf + \"_\";\n\tfor ( auto i = guard.begin(); i!=guard.end(); i++ )\n\t{\n\t if ( (*i) == '.') \n\t\t(*i) = '_';\n\t else\n\t\t(*i) = toupper(*i);\n\t}\n\n\tostr_h << \"#ifndef \" << guard << std::endl;\n\tostr_h << \"#define \" << guard << std::endl;\n\n\tfor ( auto pEnum : items )\n\t{\n\t ostr_h << tl_typedef(*pEnum);\n\t}\n\n\tostr_c << tl_strings(items);\n\n\tfor (auto pEnum : items )\n\t{\n\t ostr_c << tl_functions(*pEnum);\n\t}\n\n\tostr_h << std::endl << \"#endif \/\/ \" << guard << std::endl;\n\n }\n\n const std::string defgen::tl_header(void) const\n {\n\tstringstream ss;\n\tss <<\"\/** Generated by \" << ecc::version << \"*\/\" << endl;\n\treturn ss.str();\n }\n \n const std::string defgen::tl_typedef(const ast::enumdef& ed) const\n {\n\tstringstream ss;\n\tss << endl << \"\/** typedef \" << ed.get_name() << \" *\/\" << endl;\n\tss << \"typedef enum {\";\n\n\tstd::string sep = \"\";\n\n\tfor ( auto vp : ed.getvalues() )\n\t{\n\t ss << sep << endl << \" \" << vp.first;\n\t if (vp.second!=AST_DEFAULT_ENUM_VALUE)\n\t\tss << \"=\" << vp.second;\n\t sep = \",\";\n\t}\n\n\tss << endl << \"} \" << ed.get_name() << \";\" << endl;\n\n\treturn ss.str();\n }\n\n const std::string defgen::tl_strings(const ast::elist_t& items) const\n {\n\tstringstream ss;\n\n\tss << endl << \"namespace {\" << endl;\n\tss << \" static const std::string notfound=\\\"\\\";\" << endl;\n\t\n\tfor ( auto pItem : items )\n\t{\n\t for ( auto vp : pItem->getvalues() )\n\t {\n\t\tss << \" static const std::string \" << pItem->get_name() << \"_\"\n\t\t << vp.first << \" = \" << \"\\\"\" << vp.first << \"\\\";\" << endl;\n\t }\n\t}\n\n\tss << \"}\" << endl;\n\n\treturn ss.str();\n }\n\n const std::string defgen::tl_functions(const ast::enumdef& ed) const\n {\n\tstringstream ss;\n\n\tss << endl << \"const std::string& getstr_\" << ed.get_name() << \"(\"\n\t << ed.get_name() << \" v) {\" << endl;\n\t\n\tss << \" switch (v) {\" << endl;\n\t\n\tfor ( auto vp : ed.getvalues() )\n\t{\n\t ss << \" case \" << vp.first << \":\" << endl;\n\t ss << \" return \" << ed.get_name() << \"_\" << vp.first << \";\" << endl; \n\t}\n\n\tss << \" default: \" << endl;\n\tss << \" return notfound;\" << endl;\n\n\tss << \" }\" << endl;\n\n\tss << \"}\" << endl;\n\n\treturn ss.str();\n }\n}\n<commit_msg>Added prefix to guard header string<commit_after>#include <iostream>\n#include <map>\n#include <vector>\n#include <sstream>\n#include <string>\n#include \"version.h\"\n#include \"ast.h\"\n#include \"generator.h\"\n\nusing std::stringstream;\nusing std::endl;\n\nnamespace ecc\n{\n generator::generator()\n {\n\n }\n\n generator::~generator()\n {\n\n }\n\n void defgen::translate(const ast::elist_t& items, \n\t const std::string& fHeader, \n\t\t\t const std::string& fCode,\n\t\t\t std::ostream& ostr_c, \n\t\t\t std::ostream& ostr_h)\n {\n\tostr_h << tl_header();\n\tostr_c << tl_header();\n\n\t\/** c file needs to include <string>, and our header *\/\n\tostr_c << \"#include <string>\" << endl;\n\n\tstd::string headerLeaf;\n\tint pos = fHeader.rfind('\/');\n\tif ( pos == std::string::npos )\n\t{\n\t \/\/ File is already a leaf\n\t headerLeaf = fHeader;\n\t}\n\telse\n\t{\n\t \/\/ File is not leaf, use everything after the last '\/'\n\t headerLeaf = fHeader.substr(pos+1, fHeader.length()-pos);\n\t}\n\t\n\tostr_c << \"#include \\\"\" << headerLeaf << \"\\\"\" << std::endl;\n\n\tstd::string guard = \"_HG_\" + headerLeaf + \"_\";\n\tfor ( auto i = guard.begin(); i!=guard.end(); i++ )\n\t{\n\t if ( (*i) == '.') \n\t\t(*i) = '_';\n\t else\n\t\t(*i) = toupper(*i);\n\t}\n\n\tostr_h << \"#ifndef \" << guard << std::endl;\n\tostr_h << \"#define \" << guard << std::endl;\n\n\tfor ( auto pEnum : items )\n\t{\n\t ostr_h << tl_typedef(*pEnum);\n\t}\n\n\tostr_c << tl_strings(items);\n\n\tfor (auto pEnum : items )\n\t{\n\t ostr_c << tl_functions(*pEnum);\n\t}\n\n\tostr_h << std::endl << \"#endif \/\/ \" << guard << std::endl;\n\n }\n\n const std::string defgen::tl_header(void) const\n {\n\tstringstream ss;\n\tss <<\"\/** Generated by \" << ecc::version << \"*\/\" << endl;\n\treturn ss.str();\n }\n \n const std::string defgen::tl_typedef(const ast::enumdef& ed) const\n {\n\tstringstream ss;\n\tss << endl << \"\/** typedef \" << ed.get_name() << \" *\/\" << endl;\n\tss << \"typedef enum {\";\n\n\tstd::string sep = \"\";\n\n\tfor ( auto vp : ed.getvalues() )\n\t{\n\t ss << sep << endl << \" \" << vp.first;\n\t if (vp.second!=AST_DEFAULT_ENUM_VALUE)\n\t\tss << \"=\" << vp.second;\n\t sep = \",\";\n\t}\n\n\tss << endl << \"} \" << ed.get_name() << \";\" << endl;\n\n\treturn ss.str();\n }\n\n const std::string defgen::tl_strings(const ast::elist_t& items) const\n {\n\tstringstream ss;\n\n\tss << endl << \"namespace {\" << endl;\n\tss << \" static const std::string notfound=\\\"\\\";\" << endl;\n\t\n\tfor ( auto pItem : items )\n\t{\n\t for ( auto vp : pItem->getvalues() )\n\t {\n\t\tss << \" static const std::string \" << pItem->get_name() << \"_\"\n\t\t << vp.first << \" = \" << \"\\\"\" << vp.first << \"\\\";\" << endl;\n\t }\n\t}\n\n\tss << \"}\" << endl;\n\n\treturn ss.str();\n }\n\n const std::string defgen::tl_functions(const ast::enumdef& ed) const\n {\n\tstringstream ss;\n\n\tss << endl << \"const std::string& getstr_\" << ed.get_name() << \"(\"\n\t << ed.get_name() << \" v) {\" << endl;\n\t\n\tss << \" switch (v) {\" << endl;\n\t\n\tfor ( auto vp : ed.getvalues() )\n\t{\n\t ss << \" case \" << vp.first << \":\" << endl;\n\t ss << \" return \" << ed.get_name() << \"_\" << vp.first << \";\" << endl; \n\t}\n\n\tss << \" default: \" << endl;\n\tss << \" return notfound;\" << endl;\n\n\tss << \" }\" << endl;\n\n\tss << \"}\" << endl;\n\n\treturn ss.str();\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ LFSR.hpp\n\/\/ Clock Signal\n\/\/\n\/\/ Created by Thomas Harte on 19\/01\/2020.\n\/\/ Copyright © 2020 Thomas Harte. All rights reserved.\n\/\/\n\n#ifndef LFSR_h\n#define LFSR_h\n\n#include <cstdint>\n#include <cstdlib>\n\n#include \"Sizes.hpp\"\n\nnamespace Numeric {\n\ntemplate <typename IntType> struct LSFRPolynomial {};\n\n\/\/ The following were taken 'at random' from https:\/\/users.ece.cmu.edu\/~koopman\/lfsr\/index.html\ntemplate <> struct LSFRPolynomial<uint64_t> {\n\tstatic constexpr uint64_t value = 0x80000000000019E2;\n};\n\ntemplate <> struct LSFRPolynomial<uint32_t> {\n\tstatic constexpr uint32_t value = 0x80000C34;\n};\n\ntemplate <> struct LSFRPolynomial<uint16_t> {\n\tstatic constexpr uint16_t value = 0x853E;\n};\n\ntemplate <> struct LSFRPolynomial<uint8_t> {\n\tstatic constexpr uint8_t value = 0xAF;\n};\n\n\/*!\n\tProvides a linear-feedback shift register with a random initial state; if no polynomial is supplied\n\tthen one will be picked that is guaranteed to give the maximal number of LFSR states that can fit\n\tin the specified int type.\n*\/\ntemplate <typename IntType = uint64_t, IntType polynomial = LSFRPolynomial<IntType>::value> class LFSR {\n\tpublic:\n\t\t\/*!\n\t\t\tConstructs an LFSR with a random initial value.\n\t\t*\/\n\t\tconstexpr LFSR() noexcept {\n\t\t\t\/\/ Randomise the value, ensuring it doesn't end up being 0;\n\t\t\t\/\/ don't set any top bits, in case this is a signed type.\n\t\t\twhile(!value_) {\n\t\t\t\tuint8_t *value_byte = reinterpret_cast<uint8_t *>(&value_);\n\t\t\t\tfor(size_t c = 0; c < sizeof(IntType); ++c) {\n\t\t\t\t\t*value_byte = uint8_t(uint64_t(rand()) * 127 \/ RAND_MAX);\n\t\t\t\t\t++value_byte;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t\/*!\n\t\t\tConstructs an LFSR with the specified initial value.\n\n\t\t\tAn initial value of 0 is invalid.\n\t\t*\/\n\t\tLFSR(IntType initial_value) : value_(initial_value) {}\n\n\t\t\/*!\n\t\t\tAdvances the LSFR, returning either an @c IntType of value @c 1 or @c 0,\n\t\t\tdetermining the bit that was just shifted out.\n\t\t*\/\n\t\tIntType next() {\n\t\t\tconst auto result = value_ & 1;\n\t\t\tvalue_ = (value_ >> 1) ^ (result * polynomial);\n\t\t\treturn result;\n\t\t}\n\n\tprivate:\n\t\tIntType value_ = 0;\n};\n\ntemplate <uint64_t polynomial> class LFSRv: public LFSR<typename MinIntTypeValue<polynomial>::type, polynomial> {};\n\n}\n\n#endif \/* LFSR_h *\/\n<commit_msg>Corrects for IntType != int.<commit_after>\/\/\n\/\/ LFSR.hpp\n\/\/ Clock Signal\n\/\/\n\/\/ Created by Thomas Harte on 19\/01\/2020.\n\/\/ Copyright © 2020 Thomas Harte. All rights reserved.\n\/\/\n\n#ifndef LFSR_h\n#define LFSR_h\n\n#include <cstdint>\n#include <cstdlib>\n\n#include \"Sizes.hpp\"\n\nnamespace Numeric {\n\ntemplate <typename IntType> struct LSFRPolynomial {};\n\n\/\/ The following were taken 'at random' from https:\/\/users.ece.cmu.edu\/~koopman\/lfsr\/index.html\ntemplate <> struct LSFRPolynomial<uint64_t> {\n\tstatic constexpr uint64_t value = 0x80000000000019E2;\n};\n\ntemplate <> struct LSFRPolynomial<uint32_t> {\n\tstatic constexpr uint32_t value = 0x80000C34;\n};\n\ntemplate <> struct LSFRPolynomial<uint16_t> {\n\tstatic constexpr uint16_t value = 0x853E;\n};\n\ntemplate <> struct LSFRPolynomial<uint8_t> {\n\tstatic constexpr uint8_t value = 0xAF;\n};\n\n\/*!\n\tProvides a linear-feedback shift register with a random initial state; if no polynomial is supplied\n\tthen one will be picked that is guaranteed to give the maximal number of LFSR states that can fit\n\tin the specified int type.\n*\/\ntemplate <typename IntType = uint64_t, IntType polynomial = LSFRPolynomial<IntType>::value> class LFSR {\n\tpublic:\n\t\t\/*!\n\t\t\tConstructs an LFSR with a random initial value.\n\t\t*\/\n\t\tconstexpr LFSR() noexcept {\n\t\t\t\/\/ Randomise the value, ensuring it doesn't end up being 0;\n\t\t\t\/\/ don't set any top bits, in case this is a signed type.\n\t\t\twhile(!value_) {\n\t\t\t\tuint8_t *value_byte = reinterpret_cast<uint8_t *>(&value_);\n\t\t\t\tfor(size_t c = 0; c < sizeof(IntType); ++c) {\n\t\t\t\t\t*value_byte = uint8_t(uint64_t(rand()) * 127 \/ RAND_MAX);\n\t\t\t\t\t++value_byte;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t\/*!\n\t\t\tConstructs an LFSR with the specified initial value.\n\n\t\t\tAn initial value of 0 is invalid.\n\t\t*\/\n\t\tLFSR(IntType initial_value) : value_(initial_value) {}\n\n\t\t\/*!\n\t\t\tAdvances the LSFR, returning either an @c IntType of value @c 1 or @c 0,\n\t\t\tdetermining the bit that was just shifted out.\n\t\t*\/\n\t\tIntType next() {\n\t\t\tconst auto result = IntType(value_ & 1);\n\t\t\tvalue_ = IntType((value_ >> 1) ^ (result * polynomial));\n\t\t\treturn result;\n\t\t}\n\n\tprivate:\n\t\tIntType value_ = 0;\n};\n\ntemplate <uint64_t polynomial> class LFSRv: public LFSR<typename MinIntTypeValue<polynomial>::type, polynomial> {};\n\n}\n\n#endif \/* LFSR_h *\/\n<|endoftext|>"} {"text":"<commit_before>\/*\n * SRT - Secure, Reliable, Transport\n * Copyright (c) 2019 Haivision Systems Inc.\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\n * Written by:\n * Haivision Systems Inc.\n *\/\n\n#include <gtest\/gtest.h>\n#include <future>\n#include <thread>\n\n#include \"srt.h\"\n\nusing namespace std;\n\n\nclass TestSocketOptions\n : public ::testing::Test\n{\nprotected:\n TestSocketOptions()\n {\n \/\/ initialization code here\n }\n\n ~TestSocketOptions()\n {\n \/\/ cleanup any pending stuff, but no exceptions allowed\n }\n\nprotected:\n \/\/ SetUp() is run immediately before a test starts.\n void SetUp()\n {\n ASSERT_GE(srt_startup(), 0);\n const int yes = 1;\n\n m_caller_sock = srt_create_socket();\n ASSERT_NE(m_caller_sock, SRT_INVALID_SOCK);\n ASSERT_EQ(srt_setsockopt(m_caller_sock, 0, SRTO_RCVSYN, &yes, sizeof yes), SRT_SUCCESS); \/\/ for async connect\n ASSERT_EQ(srt_setsockopt(m_caller_sock, 0, SRTO_SNDSYN, &yes, sizeof yes), SRT_SUCCESS); \/\/ for async connect\n\n m_listen_sock = srt_create_socket();\n ASSERT_NE(m_listen_sock, SRT_INVALID_SOCK);\n ASSERT_EQ(srt_setsockopt(m_listen_sock, 0, SRTO_RCVSYN, &yes, sizeof yes), SRT_SUCCESS); \/\/ for async connect\n ASSERT_EQ(srt_setsockopt(m_listen_sock, 0, SRTO_SNDSYN, &yes, sizeof yes), SRT_SUCCESS); \/\/ for async connect\n }\n\n void TearDown()\n {\n \/\/ Code here will be called just after the test completes.\n \/\/ OK to throw exceptions from here if needed.\n ASSERT_NE(srt_close(m_caller_sock), SRT_ERROR);\n ASSERT_NE(srt_close(m_listen_sock), SRT_ERROR);\n srt_cleanup();\n }\n\nprotected:\n \/\/ put in any custom data members that you need\n\n SRTSOCKET m_caller_sock = SRT_INVALID_SOCK;\n SRTSOCKET m_listen_sock = SRT_INVALID_SOCK;\n\n int m_pollid = 0;\n};\n\n\n\/\/\/ A regression test for issue #735, fixed by PR #843.\n\/\/\/ Checks propagation of listener's socket option SRTO_LOSSMAXTTL\n\/\/\/ on SRT sockets being accepted.\nTEST_F(TestSocketOptions, LossMaxTTL)\n{\n const int loss_max_ttl = 5;\n ASSERT_EQ(srt_setsockopt(m_listen_sock, 0, SRTO_LOSSMAXTTL, &loss_max_ttl, sizeof loss_max_ttl), SRT_SUCCESS);\n\n \/\/ Specify address\n sockaddr_in sa;\n memset(&sa, 0, sizeof sa);\n sa.sin_family = AF_INET;\n sa.sin_port = htons(5200);\n ASSERT_EQ(inet_pton(AF_INET, \"127.0.0.1\", &sa.sin_addr), 1);\n sockaddr* psa = (sockaddr*)&sa;\n ASSERT_NE(srt_bind(m_listen_sock, psa, sizeof sa), SRT_ERROR);\n\n srt_listen(m_listen_sock, 1);\n\n auto accept_async = [](SRTSOCKET listen_sock) {\n sockaddr_in client_address;\n int length = sizeof(sockaddr_in);\n const SRTSOCKET accepted_socket = srt_accept(listen_sock, (sockaddr*)&client_address, &length);\n return accepted_socket;\n };\n auto accept_res = async(launch::async, accept_async, m_listen_sock);\n\n const int connect_res = srt_connect(m_caller_sock, psa, sizeof sa);\n EXPECT_EQ(connect_res, SRT_SUCCESS);\n\n const SRTSOCKET accepted_sock = accept_res.get();\n ASSERT_NE(accepted_sock, SRT_INVALID_SOCK);\n\n int opt_val = 0;\n int opt_len = 0;\n ASSERT_EQ(srt_getsockopt(accepted_sock, 0, SRTO_LOSSMAXTTL, &opt_val, &opt_len), SRT_SUCCESS);\n EXPECT_EQ(opt_val, loss_max_ttl) << \"Wrong SRTO_LOSSMAXTTL value on the accepted socket\";\n EXPECT_EQ(opt_len, sizeof opt_len) << \"Wrong SRTO_LOSSMAXTTL value length on the accepted socket\";\n\n SRT_TRACEBSTATS stats;\n EXPECT_EQ(srt_bstats(accepted_sock, &stats, 0), SRT_SUCCESS);\n EXPECT_EQ(stats.pktReorderTolerance, loss_max_ttl);\n\n ASSERT_EQ(srt_getsockopt(m_listen_sock, 0, SRTO_LOSSMAXTTL, &opt_val, &opt_len), SRT_SUCCESS);\n EXPECT_EQ(opt_val, loss_max_ttl) << \"Wrong SRTO_LOSSMAXTTL value on the listener socket\";\n EXPECT_EQ(opt_len, sizeof opt_len) << \"Wrong SRTO_LOSSMAXTTL value length on the listener socket\";\n\n ASSERT_NE(srt_close(accepted_sock), SRT_ERROR);\n}\n\n\n<commit_msg>[tests] Added tests for SRTO_MININPUTBW<commit_after>\/*\n * SRT - Secure, Reliable, Transport\n * Copyright (c) 2019 Haivision Systems Inc.\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\n * Written by:\n * Haivision Systems Inc.\n *\/\n\n#include <gtest\/gtest.h>\n#include <future>\n#include <thread>\n\n#include \"srt.h\"\n\nusing namespace std;\n\n\nclass TestSocketOptions\n : public ::testing::Test\n{\nprotected:\n TestSocketOptions()\n {\n \/\/ initialization code here\n }\n\n ~TestSocketOptions()\n {\n \/\/ cleanup any pending stuff, but no exceptions allowed\n }\n\npublic:\n void StartListener()\n {\n \/\/ Specify address of the listener\n sockaddr* psa = (sockaddr*)&m_sa;\n ASSERT_NE(srt_bind(m_listen_sock, psa, sizeof m_sa), SRT_ERROR);\n\n srt_listen(m_listen_sock, 1);\n }\n\n SRTSOCKET EstablishConnection()\n {\n auto accept_async = [](SRTSOCKET listen_sock) {\n sockaddr_in client_address;\n int length = sizeof(sockaddr_in);\n const SRTSOCKET accepted_socket = srt_accept(listen_sock, (sockaddr*)&client_address, &length);\n return accepted_socket;\n };\n auto accept_res = async(launch::async, accept_async, m_listen_sock);\n\n sockaddr* psa = (sockaddr*)&m_sa;\n const int connect_res = srt_connect(m_caller_sock, psa, sizeof m_sa);\n EXPECT_EQ(connect_res, SRT_SUCCESS);\n\n const SRTSOCKET accepted_sock = accept_res.get();\n EXPECT_NE(accepted_sock, SRT_INVALID_SOCK);\n\n return accepted_sock;\n }\n\nprotected:\n \/\/ SetUp() is run immediately before a test starts.\n void SetUp()\n {\n ASSERT_GE(srt_startup(), 0);\n const int yes = 1;\n\n memset(&m_sa, 0, sizeof m_sa);\n m_sa.sin_family = AF_INET;\n m_sa.sin_port = htons(5200);\n ASSERT_EQ(inet_pton(AF_INET, \"127.0.0.1\", &m_sa.sin_addr), 1);\n\n m_caller_sock = srt_create_socket();\n ASSERT_NE(m_caller_sock, SRT_INVALID_SOCK);\n ASSERT_EQ(srt_setsockopt(m_caller_sock, 0, SRTO_RCVSYN, &yes, sizeof yes), SRT_SUCCESS); \/\/ for async connect\n ASSERT_EQ(srt_setsockopt(m_caller_sock, 0, SRTO_SNDSYN, &yes, sizeof yes), SRT_SUCCESS); \/\/ for async connect\n\n m_listen_sock = srt_create_socket();\n ASSERT_NE(m_listen_sock, SRT_INVALID_SOCK);\n ASSERT_EQ(srt_setsockopt(m_listen_sock, 0, SRTO_RCVSYN, &yes, sizeof yes), SRT_SUCCESS); \/\/ for async connect\n ASSERT_EQ(srt_setsockopt(m_listen_sock, 0, SRTO_SNDSYN, &yes, sizeof yes), SRT_SUCCESS); \/\/ for async connect\n }\n\n void TearDown()\n {\n \/\/ Code here will be called just after the test completes.\n \/\/ OK to throw exceptions from here if needed.\n ASSERT_NE(srt_close(m_caller_sock), SRT_ERROR);\n ASSERT_NE(srt_close(m_listen_sock), SRT_ERROR);\n srt_cleanup();\n }\n\nprotected:\n \/\/ put in any custom data members that you need\n\n sockaddr_in m_sa;\n SRTSOCKET m_caller_sock = SRT_INVALID_SOCK;\n SRTSOCKET m_listen_sock = SRT_INVALID_SOCK;\n\n int m_pollid = 0;\n};\n\n\n\/\/\/ A regression test for issue #735, fixed by PR #843.\n\/\/\/ Checks propagation of listener's socket option SRTO_LOSSMAXTTL\n\/\/\/ on SRT sockets being accepted.\nTEST_F(TestSocketOptions, LossMaxTTL)\n{\n const int loss_max_ttl = 5;\n ASSERT_EQ(srt_setsockopt(m_listen_sock, 0, SRTO_LOSSMAXTTL, &loss_max_ttl, sizeof loss_max_ttl), SRT_SUCCESS);\n\n StartListener();\n const SRTSOCKET accepted_sock = EstablishConnection();\n\n int opt_val = 0;\n int opt_len = 0;\n ASSERT_EQ(srt_getsockopt(accepted_sock, 0, SRTO_LOSSMAXTTL, &opt_val, &opt_len), SRT_SUCCESS);\n EXPECT_EQ(opt_val, loss_max_ttl) << \"Wrong SRTO_LOSSMAXTTL value on the accepted socket\";\n EXPECT_EQ(opt_len, sizeof opt_len) << \"Wrong SRTO_LOSSMAXTTL value length on the accepted socket\";\n\n SRT_TRACEBSTATS stats;\n EXPECT_EQ(srt_bstats(accepted_sock, &stats, 0), SRT_SUCCESS);\n EXPECT_EQ(stats.pktReorderTolerance, loss_max_ttl);\n\n ASSERT_EQ(srt_getsockopt(m_listen_sock, 0, SRTO_LOSSMAXTTL, &opt_val, &opt_len), SRT_SUCCESS);\n EXPECT_EQ(opt_val, loss_max_ttl) << \"Wrong SRTO_LOSSMAXTTL value on the listener socket\";\n EXPECT_EQ(opt_len, sizeof opt_len) << \"Wrong SRTO_LOSSMAXTTL value length on the listener socket\";\n\n ASSERT_NE(srt_close(accepted_sock), SRT_ERROR);\n}\n\n\n\/\/ Try to set\/get SRTO_MININPUTBW with wrong optlen\nTEST_F(TestSocketOptions, MinInputBWWrongLen)\n{\n int64_t mininputbw = 0;\n int optlen = (int)(sizeof mininputbw) - 1;\n EXPECT_EQ(srt_getsockopt(m_listen_sock, 0, SRTO_MININPUTBW, &mininputbw, &optlen), SRT_ERROR);\n EXPECT_EQ(srt_getlasterror(NULL), SRT_EINVPARAM);\n optlen += 2;\n EXPECT_EQ(srt_getsockopt(m_listen_sock, 0, SRTO_MININPUTBW, &mininputbw, &optlen), SRT_SUCCESS) << \"Bigger storage is allowed\";\n EXPECT_EQ(optlen, (int)(sizeof mininputbw));\n\n EXPECT_EQ(srt_setsockopt(m_listen_sock, 0, SRTO_MININPUTBW, &mininputbw, sizeof mininputbw - 1), SRT_ERROR);\n EXPECT_EQ(srt_getlasterror(NULL), SRT_EINVPARAM);\n EXPECT_EQ(srt_setsockopt(m_listen_sock, 0, SRTO_MININPUTBW, &mininputbw, sizeof mininputbw + 1), SRT_ERROR);\n EXPECT_EQ(srt_getlasterror(NULL), SRT_EINVPARAM);\n}\n\n\/\/ Check the default SRTO_MININPUTBW is SRT_PACING_MAXBW_DEFAULT\nTEST_F(TestSocketOptions, MinInputBWDefault)\n{\n const int mininputbw_expected = 0;\n int64_t mininputbw = 1;\n int optlen = (int)(sizeof mininputbw);\n EXPECT_EQ(srt_getsockopt(m_listen_sock, 0, SRTO_MININPUTBW, &mininputbw, &optlen), SRT_SUCCESS);\n EXPECT_EQ(optlen, (int)(sizeof mininputbw));\n EXPECT_EQ(mininputbw, mininputbw_expected);\n\n StartListener();\n const SRTSOCKET accepted_sock = EstablishConnection();\n\n \/\/ Check both listener and accepted socket have default values\n for (SRTSOCKET sock : { m_listen_sock, accepted_sock })\n {\n optlen = (int)(sizeof mininputbw);\n EXPECT_EQ(srt_getsockopt(sock, 0, SRTO_MININPUTBW, &mininputbw, &optlen), SRT_SUCCESS);\n EXPECT_EQ(optlen, (int)(sizeof mininputbw));\n EXPECT_EQ(mininputbw, mininputbw_expected);\n }\n\n ASSERT_NE(srt_close(accepted_sock), SRT_ERROR);\n}\n\n\/\/ Check setting and getting SRT_MININPUTBW\nTEST_F(TestSocketOptions, MinInputBWSet)\n{\n const int64_t mininputbw_dflt = 0;\n const int64_t mininputbw = 50000000;\n int optlen = (int)(sizeof mininputbw);\n\n int64_t bw = -100;\n EXPECT_EQ(srt_setsockopt(m_listen_sock, 0, SRTO_MININPUTBW, &bw, sizeof bw), SRT_ERROR) << \"Has to be a non-negative number\";\n EXPECT_EQ(srt_getsockopt(m_listen_sock, 0, SRTO_MININPUTBW, &bw, &optlen), SRT_SUCCESS);\n EXPECT_EQ(bw, mininputbw_dflt);\n\n bw = mininputbw;\n EXPECT_EQ(srt_setsockopt(m_listen_sock, 0, SRTO_MININPUTBW, &bw, sizeof bw), SRT_SUCCESS);\n EXPECT_EQ(srt_getsockopt(m_listen_sock, 0, SRTO_MININPUTBW, &bw, &optlen), SRT_SUCCESS);\n EXPECT_EQ(bw, mininputbw);\n\n StartListener();\n const SRTSOCKET accepted_sock = EstablishConnection();\n\n \/\/ Check accepted socket inherits values\n for (SRTSOCKET sock : { m_listen_sock, accepted_sock })\n {\n optlen = (int)(sizeof bw);\n EXPECT_EQ(srt_getsockopt(sock, 0, SRTO_MININPUTBW, &bw, &optlen), SRT_SUCCESS);\n EXPECT_EQ(optlen, (int)(sizeof bw));\n EXPECT_EQ(bw, mininputbw);\n }\n\n ASSERT_NE(srt_close(accepted_sock), SRT_ERROR);\n}\n\n\/\/ Check setting and getting SRTO_MININPUTBW in runtime\nTEST_F(TestSocketOptions, MinInputBWRuntime)\n{\n const int64_t mininputbw = 50000000;\n\n \/\/ Establish a connection\n StartListener();\n const SRTSOCKET accepted_sock = EstablishConnection();\n\n \/\/ Test a connected socket\n int64_t bw = mininputbw;\n int optlen = (int)(sizeof bw);\n EXPECT_EQ(srt_setsockopt(accepted_sock, 0, SRTO_MININPUTBW, &bw, sizeof bw), SRT_SUCCESS);\n EXPECT_EQ(srt_getsockopt(accepted_sock, 0, SRTO_MININPUTBW, &bw, &optlen), SRT_SUCCESS);\n EXPECT_EQ(bw, mininputbw);\n\n bw = 0;\n EXPECT_EQ(srt_setsockopt(accepted_sock, 0, SRTO_INPUTBW, &bw, sizeof bw), SRT_SUCCESS);\n EXPECT_EQ(srt_getsockopt(accepted_sock, 0, SRTO_INPUTBW, &bw, &optlen), SRT_SUCCESS);\n EXPECT_EQ(bw, 0);\n\n EXPECT_EQ(srt_setsockopt(accepted_sock, 0, SRTO_MAXBW, &bw, sizeof bw), SRT_SUCCESS);\n EXPECT_EQ(srt_getsockopt(accepted_sock, 0, SRTO_MAXBW, &bw, &optlen), SRT_SUCCESS);\n EXPECT_EQ(bw, 0);\n\n EXPECT_EQ(srt_getsockopt(accepted_sock, 0, SRTO_MININPUTBW, &bw, &optlen), SRT_SUCCESS);\n EXPECT_EQ(bw, mininputbw);\n\n const int64_t new_mininputbw = 20000000;\n bw = new_mininputbw;\n EXPECT_EQ(srt_setsockopt(accepted_sock, 0, SRTO_MININPUTBW, &bw, sizeof bw), SRT_SUCCESS);\n EXPECT_EQ(srt_getsockopt(accepted_sock, 0, SRTO_MININPUTBW, &bw, &optlen), SRT_SUCCESS);\n EXPECT_EQ(bw, new_mininputbw);\n\n ASSERT_NE(srt_close(accepted_sock), SRT_ERROR);\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/******************************************************************************\n* Copyright (c) 2011, Michael P. Gerlek (mpg@flaxen.com)\n*\n* All rights reserved.\n*\n* Redistribution and use in source and binary forms, with or without\n* modification, are permitted provided that the following\n* conditions are met:\n*\n* * Redistributions of source code must retain the above copyright\n* notice, this list of conditions and the following disclaimer.\n* * Redistributions in binary form must reproduce the above copyright\n* notice, this list of conditions and the following disclaimer in\n* the documentation and\/or other materials provided\n* with the distribution.\n* * Neither the name of Hobu, Inc. or Flaxen Geo Consulting nor the\n* names of its contributors may be used to endorse or promote\n* products derived from this software without specific prior\n* written permission.\n*\n* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n* \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS\n* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED\n* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT\n* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY\n* OF SUCH DAMAGE.\n****************************************************************************\/\n\n#include <boost\/test\/unit_test.hpp>\n#include <boost\/cstdint.hpp>\n\n#include <libpc\/drivers\/faux\/Reader.hpp>\n\nusing namespace libpc;\n\nBOOST_AUTO_TEST_SUITE(FauxReaderTest)\n\nBOOST_AUTO_TEST_CASE(test_constant)\n{\n Bounds<double> bounds(1.0, 2.0, 3.0, 101.0, 102.0, 103.0);\n libpc::drivers::faux::Reader reader(bounds, 1000, libpc::drivers::faux::Reader::Constant);\n BOOST_CHECK(reader.getName() == \"Faux Reader\");\n\n const Schema& schema = reader.getHeader().getSchema();\n SchemaLayout layout(schema);\n\n PointData data(layout, 750);\n \n boost::uint32_t numRead = reader.read(data);\n\n BOOST_CHECK(numRead == 750);\n\n int offsetX = schema.getDimensionIndex(Dimension::Field_X);\n int offsetY = schema.getDimensionIndex(Dimension::Field_Y);\n int offsetZ = schema.getDimensionIndex(Dimension::Field_Z);\n int offsetT = schema.getDimensionIndex(Dimension::Field_Time);\n\n for (boost::uint32_t i=0; i<numRead; i++)\n {\n float x = data.getField<float>(i, offsetX);\n float y = data.getField<float>(i, offsetY);\n float z = data.getField<float>(i, offsetZ);\n boost::uint64_t t = data.getField<boost::uint64_t>(i, offsetT);\n\n BOOST_CHECK(x == 1.0);\n BOOST_CHECK(y == 2.0);\n BOOST_CHECK(z == 3.0);\n BOOST_CHECK(t == i);\n }\n\n return;\n}\n\n\nBOOST_AUTO_TEST_CASE(test_random)\n{\n Bounds<double> bounds(1.0, 2.0, 3.0, 101.0, 102.0, 103.0);\n libpc::drivers::faux::Reader reader(bounds, 1000, libpc::drivers::faux::Reader::Random);\n\n const Schema& schema = reader.getHeader().getSchema();\n SchemaLayout layout(schema);\n\n PointData data(layout, 750);\n \n boost::uint32_t numRead = reader.read(data);\n\n BOOST_CHECK(numRead == 750);\n\n int offsetX = schema.getDimensionIndex(Dimension::Field_X);\n int offsetY = schema.getDimensionIndex(Dimension::Field_Y);\n int offsetZ = schema.getDimensionIndex(Dimension::Field_Z);\n int offsetT = schema.getDimensionIndex(Dimension::Field_Time);\n\n for (boost::uint32_t i=0; i<numRead; i++)\n {\n float x = data.getField<float>(i, offsetX);\n float y = data.getField<float>(i, offsetY);\n float z = data.getField<float>(i, offsetZ);\n boost::uint64_t t = data.getField<boost::uint64_t>(i, offsetT);\n\n BOOST_CHECK(x >= 1.0 && x <= 101.0);\n BOOST_CHECK(y >= 2.0 && y <= 102.0);\n BOOST_CHECK(z >= 3.0 && z <= 103.0);\n BOOST_CHECK(t == i);\n }\n\n return;\n}\n\n\nBOOST_AUTO_TEST_CASE(test_custom_fields)\n{\n Bounds<double> bounds(1.0, 2.0, 3.0, 101.0, 102.0, 103.0);\n\n Dimension dimY(Dimension::Field_Y, Dimension::Uint8);\n Dimension dimX(Dimension::Field_X, Dimension::Uint8);\n std::vector<Dimension> dims;\n dims.push_back(dimY);\n dims.push_back(dimX);\n\n libpc::drivers::faux::Reader reader(bounds, 1000, libpc::drivers::faux::Reader::Random, dims);\n\n const Schema& schema = reader.getHeader().getSchema();\n BOOST_CHECK(schema.getDimensions().size() == 2);\n BOOST_CHECK(schema.getDimension(0).getField() == Dimension::Field_Y);\n BOOST_CHECK(schema.getDimension(1).getField() == Dimension::Field_X);\n\n return;\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n<commit_msg>more epsilon compares<commit_after>\/******************************************************************************\n* Copyright (c) 2011, Michael P. Gerlek (mpg@flaxen.com)\n*\n* All rights reserved.\n*\n* Redistribution and use in source and binary forms, with or without\n* modification, are permitted provided that the following\n* conditions are met:\n*\n* * Redistributions of source code must retain the above copyright\n* notice, this list of conditions and the following disclaimer.\n* * Redistributions in binary form must reproduce the above copyright\n* notice, this list of conditions and the following disclaimer in\n* the documentation and\/or other materials provided\n* with the distribution.\n* * Neither the name of Hobu, Inc. or Flaxen Geo Consulting nor the\n* names of its contributors may be used to endorse or promote\n* products derived from this software without specific prior\n* written permission.\n*\n* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n* \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS\n* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED\n* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT\n* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY\n* OF SUCH DAMAGE.\n****************************************************************************\/\n\n#include <boost\/test\/unit_test.hpp>\n#include <boost\/cstdint.hpp>\n\n#include <libpc\/drivers\/faux\/Reader.hpp>\n\nusing namespace libpc;\n\nBOOST_AUTO_TEST_SUITE(FauxReaderTest)\n\nBOOST_AUTO_TEST_CASE(test_constant)\n{\n Bounds<double> bounds(1.0, 2.0, 3.0, 101.0, 102.0, 103.0);\n libpc::drivers::faux::Reader reader(bounds, 1000, libpc::drivers::faux::Reader::Constant);\n BOOST_CHECK(reader.getName() == \"Faux Reader\");\n\n const Schema& schema = reader.getHeader().getSchema();\n SchemaLayout layout(schema);\n\n PointData data(layout, 750);\n \n boost::uint32_t numRead = reader.read(data);\n\n BOOST_CHECK(numRead == 750);\n\n int offsetX = schema.getDimensionIndex(Dimension::Field_X);\n int offsetY = schema.getDimensionIndex(Dimension::Field_Y);\n int offsetZ = schema.getDimensionIndex(Dimension::Field_Z);\n int offsetT = schema.getDimensionIndex(Dimension::Field_Time);\n\n for (boost::uint32_t i=0; i<numRead; i++)\n {\n float x = data.getField<float>(i, offsetX);\n float y = data.getField<float>(i, offsetY);\n float z = data.getField<float>(i, offsetZ);\n boost::uint64_t t = data.getField<boost::uint64_t>(i, offsetT);\n\n BOOST_CHECK( Utils::compare_approx( (double)x, 1.0, (std::numeric_limits<double>::min)()) == true);\n BOOST_CHECK(Utils::compare_approx( (double)y, 2.0, (std::numeric_limits<double>::min)()) == true);\n BOOST_CHECK(Utils::compare_approx( (double)z, 3.0, (std::numeric_limits<double>::min)()) == true);\n BOOST_CHECK(Utils::compare_approx( (double)t, (double) i, (std::numeric_limits<double>::min)()) == true);\n }\n\n return;\n}\n\n\nBOOST_AUTO_TEST_CASE(test_random)\n{\n Bounds<double> bounds(1.0, 2.0, 3.0, 101.0, 102.0, 103.0);\n libpc::drivers::faux::Reader reader(bounds, 1000, libpc::drivers::faux::Reader::Random);\n\n const Schema& schema = reader.getHeader().getSchema();\n SchemaLayout layout(schema);\n\n PointData data(layout, 750);\n \n boost::uint32_t numRead = reader.read(data);\n\n BOOST_CHECK(numRead == 750);\n\n int offsetX = schema.getDimensionIndex(Dimension::Field_X);\n int offsetY = schema.getDimensionIndex(Dimension::Field_Y);\n int offsetZ = schema.getDimensionIndex(Dimension::Field_Z);\n int offsetT = schema.getDimensionIndex(Dimension::Field_Time);\n\n for (boost::uint32_t i=0; i<numRead; i++)\n {\n float x = data.getField<float>(i, offsetX);\n float y = data.getField<float>(i, offsetY);\n float z = data.getField<float>(i, offsetZ);\n boost::uint64_t t = data.getField<boost::uint64_t>(i, offsetT);\n\n BOOST_CHECK(x >= 1.0 && x <= 101.0);\n BOOST_CHECK(y >= 2.0 && y <= 102.0);\n BOOST_CHECK(z >= 3.0 && z <= 103.0);\n BOOST_CHECK(t == i);\n }\n\n return;\n}\n\n\nBOOST_AUTO_TEST_CASE(test_custom_fields)\n{\n Bounds<double> bounds(1.0, 2.0, 3.0, 101.0, 102.0, 103.0);\n\n Dimension dimY(Dimension::Field_Y, Dimension::Uint8);\n Dimension dimX(Dimension::Field_X, Dimension::Uint8);\n std::vector<Dimension> dims;\n dims.push_back(dimY);\n dims.push_back(dimX);\n\n libpc::drivers::faux::Reader reader(bounds, 1000, libpc::drivers::faux::Reader::Random, dims);\n\n const Schema& schema = reader.getHeader().getSchema();\n BOOST_CHECK(schema.getDimensions().size() == 2);\n BOOST_CHECK(schema.getDimension(0).getField() == Dimension::Field_Y);\n BOOST_CHECK(schema.getDimension(1).getField() == Dimension::Field_X);\n\n return;\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n<|endoftext|>"} {"text":"<commit_before>#pragma once\n#include <mutex>\n\/\/#include <shared_mutex>\n#include <boost\/parameter.hpp>\n#include <boost\/mpl\/arg.hpp>\n#include <boost\/parameter\/name.hpp>\n#include <boost\/parameter\/binding.hpp>\nnamespace fox {\n using boost::mpl::_;\n BOOST_PARAMETER_TEMPLATE_KEYWORD(RecursiveType)\n BOOST_PARAMETER_TEMPLATE_KEYWORD(TimedType)\n BOOST_PARAMETER_TEMPLATE_KEYWORD(SharedType)\n\n class SharedWay\n {\n };\n class NotShared :public SharedWay {\n\n };\n class Shared :public SharedWay {\n\n };\n class TimedWay\n {\n };\n class NotTimed :public TimedWay {\n\n };\n class Timed :public TimedWay {\n\n };\n class RecursiveWay\n {\n };\n class NotRecursive :public RecursiveWay {\n\n };\n class Recursive :public RecursiveWay {\n\n };\n template<class T, class U, class V>\n class Mutex;\n template<>\n class Mutex<NotRecursive, NotTimed, NotShared> : public std::mutex {\n };\n\n template<>\n class Mutex<Recursive, NotTimed, NotShared> : public std::recursive_mutex {\n };\n\n template<>\n class Mutex<NotRecursive, Timed, NotShared> : public std::timed_mutex {\n };\n template<>\n class Mutex<Recursive, Timed, NotShared> : public std::recursive_timed_mutex {\n };\n \/\/template<>\n \/\/class Mutex<NotRecursive, NotTimed, Shared> : public std::shared_mutex {\n \/\/};\n \/\/template<>\n \/\/class Mutex<NotRecursive, Timed, Shared> : public std::shared_timed_mutex {\n \/\/};\n namespace parameter = boost::parameter;\n typedef parameter::parameters<\n parameter::optional<parameter::deduced<tag::RecursiveType>, boost::is_base_and_derived<RecursiveWay, _>>\n , parameter::optional<parameter::deduced<tag::TimedType>, boost::is_base_and_derived<TimedWay, _>>\n , parameter::optional<parameter::deduced<tag::SharedType>, boost::is_base_and_derived<SharedWay, _>>\n > class_signature;\n template <\n class A0 = parameter::void_\n , class A1 = parameter::void_\n , class A2 = parameter::void_\n >\n struct MyMutexImpl\n {\n typedef typename\n class_signature::bind<A0, A1, A2>::type\n args;\n\n \/\/ Extract first logical parameter.\n typedef typename parameter::value_type<\n args, tag::RecursiveType, NotRecursive >::type RecursiveType;\n\n typedef typename parameter::value_type<\n args, tag::TimedType, NotTimed >::type TimedType;\n\n typedef typename parameter::value_type<\n args, tag::SharedType, NotShared >::type SharedType;\n typedef Mutex<RecursiveType, TimedType, SharedType> MutexType;\n };\n\n template <\n class A0 = parameter::void_\n , class A1 = parameter::void_\n , class A2 = parameter::void_\n >\n using GeneralMutex = typename MyMutexImpl<A0, A1, A2>::MutexType;\n}\n<commit_msg>shared mutex<commit_after>#pragma once\n#include <mutex>\n#include <shared_mutex>\n#include <boost\/parameter.hpp>\n#include <boost\/mpl\/arg.hpp>\n#include <boost\/parameter\/name.hpp>\n#include <boost\/parameter\/binding.hpp>\nnamespace fox {\n using boost::mpl::_;\n BOOST_PARAMETER_TEMPLATE_KEYWORD(RecursiveType)\n BOOST_PARAMETER_TEMPLATE_KEYWORD(TimedType)\n BOOST_PARAMETER_TEMPLATE_KEYWORD(SharedType)\n\n class SharedWay\n {\n };\n class NotShared :public SharedWay {\n\n };\n class Shared :public SharedWay {\n\n };\n class TimedWay\n {\n };\n class NotTimed :public TimedWay {\n\n };\n class Timed :public TimedWay {\n\n };\n class RecursiveWay\n {\n };\n class NotRecursive :public RecursiveWay {\n\n };\n class Recursive :public RecursiveWay {\n\n };\n template<class T, class U, class V>\n class Mutex;\n template<>\n class Mutex<NotRecursive, NotTimed, NotShared> : public std::mutex {\n };\n\n template<>\n class Mutex<Recursive, NotTimed, NotShared> : public std::recursive_mutex {\n };\n\n template<>\n class Mutex<NotRecursive, Timed, NotShared> : public std::timed_mutex {\n };\n template<>\n class Mutex<Recursive, Timed, NotShared> : public std::recursive_timed_mutex {\n };\n template<>\n class Mutex<NotRecursive, NotTimed, Shared> : public std::shared_mutex {\n };\n template<>\n class Mutex<NotRecursive, Timed, Shared> : public std::shared_timed_mutex {\n };\n namespace parameter = boost::parameter;\n typedef parameter::parameters<\n parameter::optional<parameter::deduced<tag::RecursiveType>, boost::is_base_and_derived<RecursiveWay, _>>\n , parameter::optional<parameter::deduced<tag::TimedType>, boost::is_base_and_derived<TimedWay, _>>\n , parameter::optional<parameter::deduced<tag::SharedType>, boost::is_base_and_derived<SharedWay, _>>\n > class_signature;\n template <\n class A0 = parameter::void_\n , class A1 = parameter::void_\n , class A2 = parameter::void_\n >\n struct MyMutexImpl\n {\n typedef typename\n class_signature::bind<A0, A1, A2>::type\n args;\n\n typedef typename parameter::value_type<\n args, tag::RecursiveType, NotRecursive >::type RecursiveType;\n\n typedef typename parameter::value_type<\n args, tag::TimedType, NotTimed >::type TimedType;\n\n typedef typename parameter::value_type<\n args, tag::SharedType, NotShared >::type SharedType;\n typedef Mutex<RecursiveType, TimedType, SharedType> MutexType;\n };\n\n template <\n class A0 = parameter::void_\n , class A1 = parameter::void_\n , class A2 = parameter::void_\n >\n using GeneralMutex = typename MyMutexImpl<A0, A1, A2>::MutexType;\n}\n<|endoftext|>"} {"text":"<commit_before>\/******************************************************************************\n * This file is part of dirtsand. *\n * *\n * dirtsand is free software: you can redistribute it and\/or modify *\n * it under the terms of the GNU Affero General Public License as *\n * published by the Free Software Foundation, either version 3 of the *\n * License, or (at your option) any later version. *\n * *\n * dirtsand is distributed in the hope that it will be useful, *\n * but WITHOUT ANY WARRANTY; without even the implied warranty of *\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *\n * GNU Affero General Public License for more details. *\n * *\n * You should have received a copy of the GNU Affero General Public License *\n * along with dirtsand. If not, see <http:\/\/www.gnu.org\/licenses\/>. *\n ******************************************************************************\/\n\n#include \"SockIO.h\"\n#include \"errors.h\"\n\n#include <sys\/types.h>\n#include <sys\/socket.h>\n#include <sys\/ioctl.h>\n#include <netinet\/in.h>\n#include <netinet\/tcp.h>\n#include <arpa\/inet.h>\n#include <netdb.h>\n#include <unistd.h>\n#include <cstdio>\n#include <cstring>\n#include <mutex>\n\nstatic const int SOCK_YES = 1;\n\nstruct SocketHandle_Private\n{\n int m_sockfd;\n union {\n sockaddr m_addr;\n sockaddr_in m_in4addr;\n sockaddr_in6 m_in6addr;\n sockaddr_storage m_addrMax;\n };\n socklen_t m_addrLen;\n std::mutex m_sendLock;\n\n SocketHandle_Private() : m_addrLen(sizeof(m_addrMax)) { }\n};\n\nstatic void* get_in_addr(SocketHandle_Private* sock)\n{\n if (sock->m_addr.sa_family == AF_INET)\n return &sock->m_in4addr.sin_addr;\n return &sock->m_in6addr.sin6_addr;\n}\n\nstatic uint16_t get_in_port(SocketHandle_Private* sock)\n{\n if (sock->m_addr.sa_family == AF_INET)\n return ntohs(sock->m_in4addr.sin_port);\n return ntohs(sock->m_in6addr.sin6_port);\n}\n\nDS::SocketHandle DS::BindSocket(const char* address, const char* port)\n{\n int result;\n int sockfd;\n\n addrinfo info;\n memset(&info, 0, sizeof(info));\n info.ai_family = AF_UNSPEC;\n info.ai_socktype = SOCK_STREAM;\n info.ai_flags = AI_PASSIVE;\n\n addrinfo* addrList;\n result = getaddrinfo(address, port, &info, &addrList);\n DS_PASSERT(result == 0);\n\n addrinfo* addr_iter;\n for (addr_iter = addrList; addr_iter != 0; addr_iter = addr_iter->ai_next) {\n sockfd = socket(addr_iter->ai_family, addr_iter->ai_socktype,\n addr_iter->ai_protocol);\n if (sockfd == -1)\n continue;\n\n \/\/ Avoid annoying \"Address already in use\" messages when restarting\n \/\/ the server.\n setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &SOCK_YES, sizeof(SOCK_YES));\n if (bind(sockfd, addr_iter->ai_addr, addr_iter->ai_addrlen) == 0)\n break;\n fprintf(stderr, \"[Bind] %s\\n\", strerror(errno));\n\n \/\/ Couldn't bind, try the next one\n close(sockfd);\n }\n freeaddrinfo(addrList);\n\n \/\/ Die if we didn't get a successful socket\n DS_PASSERT(addr_iter);\n\n SocketHandle_Private* sockinfo = new SocketHandle_Private();\n sockinfo->m_sockfd = sockfd;\n result = getsockname(sockfd, &sockinfo->m_addr, &sockinfo->m_addrLen);\n if (result != 0) {\n delete sockinfo;\n DS_PASSERT(0);\n }\n return reinterpret_cast<SocketHandle>(sockinfo);\n}\n\nvoid DS::ListenSock(const DS::SocketHandle sock, int backlog)\n{\n DS_DASSERT(sock);\n int result = listen(reinterpret_cast<SocketHandle_Private*>(sock)->m_sockfd, backlog);\n DS_PASSERT(result == 0);\n}\n\nDS::SocketHandle DS::AcceptSock(const DS::SocketHandle sock)\n{\n DS_DASSERT(sock);\n SocketHandle_Private* sockp = reinterpret_cast<SocketHandle_Private*>(sock);\n\n SocketHandle_Private* client = new SocketHandle_Private();\n client->m_sockfd = accept(sockp->m_sockfd, &client->m_addr, &client->m_addrLen);\n if (client->m_sockfd < 0) {\n delete client;\n if (errno == EINVAL) {\n throw DS::SockHup();\n } else if (errno == ECONNABORTED) {\n return 0;\n } else {\n fprintf(stderr, \"Socket closed: %s\\n\", strerror(errno));\n DS_DASSERT(0);\n }\n }\n timeval tv;\n \/\/ Client pings us every 30 seconds. A timeout of 45 gives us some wiggle room\n \/\/ so networks can suck without kicking a client off.\n tv.tv_sec = 45;\n tv.tv_usec = 0;\n setsockopt(client->m_sockfd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv));\n \/\/ Allow 50ms on blocking sends to account for net suckiness\n tv.tv_sec = 0;\n tv.tv_usec = (50 * 1000);\n setsockopt(client->m_sockfd, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv));\n \/\/ eap-tastic protocols require Nagle's algo be disabled\n setsockopt(client->m_sockfd, IPPROTO_TCP, TCP_NODELAY, &SOCK_YES, sizeof(SOCK_YES));\n return reinterpret_cast<SocketHandle>(client);\n}\n\nvoid DS::CloseSock(DS::SocketHandle sock)\n{\n DS_DASSERT(sock);\n shutdown(reinterpret_cast<SocketHandle_Private*>(sock)->m_sockfd, SHUT_RDWR);\n close(reinterpret_cast<SocketHandle_Private*>(sock)->m_sockfd);\n}\n\nvoid DS::FreeSock(DS::SocketHandle sock)\n{\n CloseSock(sock);\n delete reinterpret_cast<SocketHandle_Private*>(sock);\n}\n\nDS::String DS::SockIpAddress(const DS::SocketHandle sock)\n{\n char addrbuf[256];\n SocketHandle_Private* sockp = reinterpret_cast<SocketHandle_Private*>(sock);\n inet_ntop(sockp->m_addr.sa_family, get_in_addr(sockp), addrbuf, 256);\n return String::Format(\"%s\/%u\", addrbuf, get_in_port(sockp));\n}\n\nuint32_t DS::GetAddress4(const char* lookup)\n{\n addrinfo info;\n memset(&info, 0, sizeof(info));\n info.ai_family = AF_INET;\n info.ai_socktype = SOCK_STREAM;\n info.ai_flags = 0;\n\n addrinfo* addrList;\n int result = getaddrinfo(lookup, 0, &info, &addrList);\n DS_PASSERT(result == 0);\n DS_PASSERT(addrList != 0);\n uint32_t addr = reinterpret_cast<sockaddr_in*>(addrList->ai_addr)->sin_addr.s_addr;\n freeaddrinfo(addrList);\n\n return ntohl(addr);\n}\n\nvoid DS::SendBuffer(const DS::SocketHandle sock, const void* buffer, size_t size, SendFlag mode)\n{\n int32_t flags = (mode & DS::e_SendNonBlocking) ? MSG_DONTWAIT : 0;\n bool retry = !(mode & DS::e_SendNoRetry);\n std::lock_guard<std::mutex> guard(reinterpret_cast<SocketHandle_Private*>(sock)->m_sendLock);\n do {\n ssize_t bytes = send(reinterpret_cast<SocketHandle_Private*>(sock)->m_sockfd,\n buffer, size, flags);\n if (bytes < 0) {\n if (errno == EPIPE || errno == ECONNRESET) {\n throw DS::SockHup();\n } else if (errno == EAGAIN || errno == EWOULDBLOCK) {\n if (retry)\n continue;\n else {\n CloseSock(sock);\n throw DS::SockHup();\n }\n }\n } else if (bytes == 0)\n throw DS::SockHup();\n DS_PASSERT(bytes > 0);\n\n size -= bytes;\n buffer = reinterpret_cast<const void*>(reinterpret_cast<const uint8_t*>(buffer) + bytes);\n } while ((size > 0) && retry);\n\n if (size > 0) {\n CloseSock(sock);\n throw DS::SockHup();\n }\n}\n\nvoid DS::RecvBuffer(const DS::SocketHandle sock, void* buffer, size_t size)\n{\n while (size > 0) {\n ssize_t bytes = recv(reinterpret_cast<SocketHandle_Private*>(sock)->m_sockfd,\n buffer, size, 0);\n if (bytes < 0 && (errno == ECONNRESET || errno == EAGAIN || errno == EWOULDBLOCK))\n throw DS::SockHup();\n if (bytes < 0 && errno == EINTR)\n continue;\n else if (bytes == 0)\n throw DS::SockHup();\n DS_PASSERT(bytes > 0);\n\n size -= bytes;\n buffer = reinterpret_cast<void*>(reinterpret_cast<uint8_t*>(buffer) + bytes);\n }\n}\n\nsize_t DS::PeekSize(const SocketHandle sock)\n{\n uint8_t buffer[256];\n ssize_t bytes = recv(reinterpret_cast<SocketHandle_Private*>(sock)->m_sockfd,\n buffer, 256, MSG_PEEK | MSG_TRUNC);\n\n if (bytes < 0 && (errno == ECONNRESET || errno == EAGAIN || errno == EWOULDBLOCK))\n throw DS::SockHup();\n else if (bytes == 0)\n throw DS::SockHup();\n DS_PASSERT(bytes > 0);\n\n return static_cast<size_t>(bytes);\n}\n<commit_msg>more EPIPE handling == less assertions<commit_after>\/******************************************************************************\n * This file is part of dirtsand. *\n * *\n * dirtsand is free software: you can redistribute it and\/or modify *\n * it under the terms of the GNU Affero General Public License as *\n * published by the Free Software Foundation, either version 3 of the *\n * License, or (at your option) any later version. *\n * *\n * dirtsand is distributed in the hope that it will be useful, *\n * but WITHOUT ANY WARRANTY; without even the implied warranty of *\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *\n * GNU Affero General Public License for more details. *\n * *\n * You should have received a copy of the GNU Affero General Public License *\n * along with dirtsand. If not, see <http:\/\/www.gnu.org\/licenses\/>. *\n ******************************************************************************\/\n\n#include \"SockIO.h\"\n#include \"errors.h\"\n\n#include <sys\/types.h>\n#include <sys\/socket.h>\n#include <sys\/ioctl.h>\n#include <netinet\/in.h>\n#include <netinet\/tcp.h>\n#include <arpa\/inet.h>\n#include <netdb.h>\n#include <unistd.h>\n#include <cstdio>\n#include <cstring>\n#include <mutex>\n\nstatic const int SOCK_YES = 1;\n\nstruct SocketHandle_Private\n{\n int m_sockfd;\n union {\n sockaddr m_addr;\n sockaddr_in m_in4addr;\n sockaddr_in6 m_in6addr;\n sockaddr_storage m_addrMax;\n };\n socklen_t m_addrLen;\n std::mutex m_sendLock;\n\n SocketHandle_Private() : m_addrLen(sizeof(m_addrMax)) { }\n};\n\nstatic void* get_in_addr(SocketHandle_Private* sock)\n{\n if (sock->m_addr.sa_family == AF_INET)\n return &sock->m_in4addr.sin_addr;\n return &sock->m_in6addr.sin6_addr;\n}\n\nstatic uint16_t get_in_port(SocketHandle_Private* sock)\n{\n if (sock->m_addr.sa_family == AF_INET)\n return ntohs(sock->m_in4addr.sin_port);\n return ntohs(sock->m_in6addr.sin6_port);\n}\n\nDS::SocketHandle DS::BindSocket(const char* address, const char* port)\n{\n int result;\n int sockfd;\n\n addrinfo info;\n memset(&info, 0, sizeof(info));\n info.ai_family = AF_UNSPEC;\n info.ai_socktype = SOCK_STREAM;\n info.ai_flags = AI_PASSIVE;\n\n addrinfo* addrList;\n result = getaddrinfo(address, port, &info, &addrList);\n DS_PASSERT(result == 0);\n\n addrinfo* addr_iter;\n for (addr_iter = addrList; addr_iter != 0; addr_iter = addr_iter->ai_next) {\n sockfd = socket(addr_iter->ai_family, addr_iter->ai_socktype,\n addr_iter->ai_protocol);\n if (sockfd == -1)\n continue;\n\n \/\/ Avoid annoying \"Address already in use\" messages when restarting\n \/\/ the server.\n setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &SOCK_YES, sizeof(SOCK_YES));\n if (bind(sockfd, addr_iter->ai_addr, addr_iter->ai_addrlen) == 0)\n break;\n fprintf(stderr, \"[Bind] %s\\n\", strerror(errno));\n\n \/\/ Couldn't bind, try the next one\n close(sockfd);\n }\n freeaddrinfo(addrList);\n\n \/\/ Die if we didn't get a successful socket\n DS_PASSERT(addr_iter);\n\n SocketHandle_Private* sockinfo = new SocketHandle_Private();\n sockinfo->m_sockfd = sockfd;\n result = getsockname(sockfd, &sockinfo->m_addr, &sockinfo->m_addrLen);\n if (result != 0) {\n delete sockinfo;\n DS_PASSERT(0);\n }\n return reinterpret_cast<SocketHandle>(sockinfo);\n}\n\nvoid DS::ListenSock(const DS::SocketHandle sock, int backlog)\n{\n DS_DASSERT(sock);\n int result = listen(reinterpret_cast<SocketHandle_Private*>(sock)->m_sockfd, backlog);\n DS_PASSERT(result == 0);\n}\n\nDS::SocketHandle DS::AcceptSock(const DS::SocketHandle sock)\n{\n DS_DASSERT(sock);\n SocketHandle_Private* sockp = reinterpret_cast<SocketHandle_Private*>(sock);\n\n SocketHandle_Private* client = new SocketHandle_Private();\n client->m_sockfd = accept(sockp->m_sockfd, &client->m_addr, &client->m_addrLen);\n if (client->m_sockfd < 0) {\n delete client;\n if (errno == EINVAL) {\n throw DS::SockHup();\n } else if (errno == ECONNABORTED) {\n return 0;\n } else {\n fprintf(stderr, \"Socket closed: %s\\n\", strerror(errno));\n DS_DASSERT(0);\n }\n }\n timeval tv;\n \/\/ Client pings us every 30 seconds. A timeout of 45 gives us some wiggle room\n \/\/ so networks can suck without kicking a client off.\n tv.tv_sec = 45;\n tv.tv_usec = 0;\n setsockopt(client->m_sockfd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv));\n \/\/ Allow 50ms on blocking sends to account for net suckiness\n tv.tv_sec = 0;\n tv.tv_usec = (50 * 1000);\n setsockopt(client->m_sockfd, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv));\n \/\/ eap-tastic protocols require Nagle's algo be disabled\n setsockopt(client->m_sockfd, IPPROTO_TCP, TCP_NODELAY, &SOCK_YES, sizeof(SOCK_YES));\n return reinterpret_cast<SocketHandle>(client);\n}\n\nvoid DS::CloseSock(DS::SocketHandle sock)\n{\n DS_DASSERT(sock);\n shutdown(reinterpret_cast<SocketHandle_Private*>(sock)->m_sockfd, SHUT_RDWR);\n close(reinterpret_cast<SocketHandle_Private*>(sock)->m_sockfd);\n}\n\nvoid DS::FreeSock(DS::SocketHandle sock)\n{\n CloseSock(sock);\n delete reinterpret_cast<SocketHandle_Private*>(sock);\n}\n\nDS::String DS::SockIpAddress(const DS::SocketHandle sock)\n{\n char addrbuf[256];\n SocketHandle_Private* sockp = reinterpret_cast<SocketHandle_Private*>(sock);\n inet_ntop(sockp->m_addr.sa_family, get_in_addr(sockp), addrbuf, 256);\n return String::Format(\"%s\/%u\", addrbuf, get_in_port(sockp));\n}\n\nuint32_t DS::GetAddress4(const char* lookup)\n{\n addrinfo info;\n memset(&info, 0, sizeof(info));\n info.ai_family = AF_INET;\n info.ai_socktype = SOCK_STREAM;\n info.ai_flags = 0;\n\n addrinfo* addrList;\n int result = getaddrinfo(lookup, 0, &info, &addrList);\n DS_PASSERT(result == 0);\n DS_PASSERT(addrList != 0);\n uint32_t addr = reinterpret_cast<sockaddr_in*>(addrList->ai_addr)->sin_addr.s_addr;\n freeaddrinfo(addrList);\n\n return ntohl(addr);\n}\n\nvoid DS::SendBuffer(const DS::SocketHandle sock, const void* buffer, size_t size, SendFlag mode)\n{\n int32_t flags = (mode & DS::e_SendNonBlocking) ? MSG_DONTWAIT : 0;\n bool retry = !(mode & DS::e_SendNoRetry);\n std::lock_guard<std::mutex> guard(reinterpret_cast<SocketHandle_Private*>(sock)->m_sendLock);\n do {\n ssize_t bytes = send(reinterpret_cast<SocketHandle_Private*>(sock)->m_sockfd,\n buffer, size, flags);\n if (bytes < 0) {\n if (errno == EPIPE || errno == ECONNRESET) {\n throw DS::SockHup();\n } else if (errno == EAGAIN || errno == EWOULDBLOCK) {\n if (retry)\n continue;\n else {\n CloseSock(sock);\n throw DS::SockHup();\n }\n }\n } else if (bytes == 0)\n throw DS::SockHup();\n DS_PASSERT(bytes > 0);\n\n size -= bytes;\n buffer = reinterpret_cast<const void*>(reinterpret_cast<const uint8_t*>(buffer) + bytes);\n } while ((size > 0) && retry);\n\n if (size > 0) {\n CloseSock(sock);\n throw DS::SockHup();\n }\n}\n\nvoid DS::RecvBuffer(const DS::SocketHandle sock, void* buffer, size_t size)\n{\n while (size > 0) {\n ssize_t bytes = recv(reinterpret_cast<SocketHandle_Private*>(sock)->m_sockfd,\n buffer, size, 0);\n if (bytes < 0 && (errno == ECONNRESET || errno == EAGAIN || errno == EWOULDBLOCK || errno == EPIPE))\n throw DS::SockHup();\n if (bytes < 0 && errno == EINTR)\n continue;\n else if (bytes == 0)\n throw DS::SockHup();\n DS_PASSERT(bytes > 0);\n\n size -= bytes;\n buffer = reinterpret_cast<void*>(reinterpret_cast<uint8_t*>(buffer) + bytes);\n }\n}\n\nsize_t DS::PeekSize(const SocketHandle sock)\n{\n uint8_t buffer[256];\n ssize_t bytes = recv(reinterpret_cast<SocketHandle_Private*>(sock)->m_sockfd,\n buffer, 256, MSG_PEEK | MSG_TRUNC);\n\n if (bytes < 0 && (errno == ECONNRESET || errno == EAGAIN || errno == EWOULDBLOCK))\n throw DS::SockHup();\n else if (bytes == 0)\n throw DS::SockHup();\n DS_PASSERT(bytes > 0);\n\n return static_cast<size_t>(bytes);\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"alfe\/main.h\"\n\nclass Symbol\n{\npublic:\n Symbol() : _cookie(_nextCookie) { ++_nextCookie; }\n bool operator==(Symbol other) { return _cookie == other._cookie; }\n bool operator!=(Symbol other) { return _cookie != other._cookie; }\n UInt32 hash(int t) { return Hash(typeid(Symbol)).mixin(_cookie); }\nprivate:\n static int _nextCookie;\n int _cookie;\n};\n\nint Symbol::_nextCookie = 0;\n\nSymbol zero;\nSymbol unknown;\n\nclass Register\n{\npublic:\n Register(String name, int binaryEncoding, int width)\n : _name(name), _binaryEncoding(binaryEncoding), _width(width) { }\n Word value() { return _value; }\n bool isConstant() { return _symbol == zero; }\n virtual void assign(T value, Symbol symbol)\n {\n _value = value;\n _symbol = symbol;\n for (auto& i : _partOf)\n i->partAssigned(value, symbol, this);\n }\n bool hasValue(Word v) { return isConstant() && value() == v; }\n void clear() { assign(0, unknown); }\n void makePartOf(Register* larger)\n {\n _partOf.append(larger);\n }\n virtual void partAssigned(Word value, Symbol symbol, Register* part) { }\nprotected:\n String _name;\n int _width;\n int _binaryEncoding;\n Word _value;\n Symbol _symbol;\n AppendableArray<Register*> _partOf;\n};\n\nclass CompoundRegister : public Register\n{\npublic:\n CompoundRegister(String name, int binaryEncoding, Register* lowPart,\n Register* highPart)\n : Register(name, binaryEncoding, lowPart->_width + highPart->_width),\n _lowPart(lowPart), _highPart(highPart)\n {\n lowPart->makePartOf(this);\n highPart->makePartOf(this);\n }\n void assign(Word value, Symbol symbol)\n {\n Register::assign(value, symbol);\n int shift = 8 * lowPart->_width;\n \/\/ Assign direcly instead of going through assign to avoid sprious\n \/\/ partAssigned() calls.\n _lowPart->_value = value & ((1 << shift) - 1);\n _lowPart->_symbol = symbol;\n _highPart->_value = value >> shift;\n _highPart->_symbol = (symbol == zero ? zero : unknown);\n }\n void partAssigned(Word value, Symbol symbol, Register* part)\n {\n int shift = 8 * lowPart->_width;\n if (part == _lowPart) {\n _value = (_highPart->_value << shift) | value;\n if (symbol != _symbol) {\n if (_highPart->_symbol == zero && symbol == zero)\n _symbol = zero;\n else\n _symbol = unknown;\n }\n }\n else {\n _value = _lowPart->_value | (value << shift);\n if (_lowPart->_symbol == zero && symbol == zero)\n _symbol = zero;\n else\n _symbol = unknown;\n }\n }\nprivate:\n Register<T2>* _lowPart;\n Register<T2>* _highPart;\n int _binaryEncoding;\n};\n\nRegisterFile registerFile;\nRegister al(\"al\", 0, 1);\nRegister cl(\"cl\", 1, 1);\nRegister dl(\"dl\", 2, 1);\nRegister bl(\"bl\", 3, 1);\nRegister ah(\"ah\", 4, 1);\nRegister ch(\"ch\", 5, 1);\nRegister dh(\"dh\", 6, 1);\nRegister bh(\"bh\", 7, 1);\nCompoundRegister ax(\"ax\", 0, &al, &ah);\nCompoundRegister cx(\"cx\", 1, &cl, &dh);\nCompoundRegister dx(\"dx\", 2, &dl, &dh);\nCompoundRegister bx(\"bx\", 3, &bl, &bh);\nRegister sp(\"sp\", 4, 2);\nRegister bp(\"bp\", 5, 2);\nRegister si(\"si\", 6, 2);\nRegister di(\"di\", 7, 2);\nRegister es(\"es\", 0, 2);\nRegister cs(\"cs\", 1, 2);\nRegister ss(\"ss\", 2, 2);\nRegister ds(\"ds\", 3, 2);\nRegister ip(\"ip\", 0, 2);\nRegister flags(\"flags\", 0, 2);\n\nclass Instruction : public LinkedListMember<Instruction>\n{\n};\n\nclass MovInstruction : public Instruction\n{\npublic:\n MovInstruction(Operand destination, Operand source)\n : _destination(destination), _source(source)\n { }\nprivate:\n Operand _destination;\n Operand _source;\n\n};\n\nclass LabelInstruction : public Instruction\n{\n};\n\nclass InstructionChain\n{\npublic:\n void add(Instruction* instruction) { _instructions.add(instruction); }\nprivate:\n OwningLinkedList<Instruction> _instructions;\n};\n\nclass Operand\n{\n};\n\nvoid emit_mov(InstructionChain chain, Operand destination, Operand source)\n{\n chain.add(MovInstruction(destination, source));\n}\n\nvoid out(Operand port, Operand value)\n{\n if (port >= 0x100)\n mov(dx, port);\n if (value.size() == 1) {\n mov(al, value);\n if (dx.value() == port\n }\n else\n mov(ax, value);\n\n\n}\n\nclass SetInstruction\n{\npublic:\n SetInstruction(Register* destination, Word value, Symbol symbol = zero)\n : _destination(destination), _value(value), _symbol(symbol) { }\n Instruction* expand()\n {\n if (dynamic_cast<CPURegister*>(destination) != 0)\n return this;\n\n if (symbol == zero) {\n if (destination->symbol() == zero) {\n auto pr = dynamic_cast<IndexedPortRegister*>(destination);\n if (pr != 0) {\n insertBefore(new SetInstruction(pr->indexRegister(),\n pr->indexValue());\n }\n insertBefore(new PortWriteByteInstruction(pr->registerPort(),\n value);\n\n\n }\n else {\n\n }\n }\n else {\n\n }\n\n }\nprivate:\n Register* _destination;\n Word _value;\n Symbol _symbol;\n};\n\nstatic const Word port_CGA_status = 0x3da;\nstatic const Byte mask_CGA_notDisplayEnable = 1;\nstatic const Byte mask_CGA_verticalSync = 8;\n\nclass CGAWaitForDisplayEnableInstruction : public Instruction\n{\npublic:\n Instruction* expand()\n {\n insertBefore(new SetInstruction(&dx, port_CGA_status));\n LabelInstruction wait = new LabelInstruction();\n insertBefore(wait);\n insertBefore(new INInstruction(&al, &dx));\n insertBefore(new TESTInstruction(&al, mask_CGA_notDisplayEnable));\n insertBefore(new JNZInstruction(wait));\n Instruction* r = previous();\n remove();\n return r;\n }\n};\n\nclass CGAWaitForDisplayDisableInstruction : public Instruction\n{\npublic:\n Instruction* expand()\n {\n insertBefore(new SetInstruction(&dx, port_CGA_status));\n LabelInstruction wait = new LabelInstruction();\n insertBefore(wait);\n insertBefore(new INInstruction(&al, &dx));\n insertBefore(new TESTInstruction(&al, mask_CGA_notDisplayEnable));\n insertBefore(new JZInstruction(wait));\n Instruction* r = previous();\n remove();\n return r;\n }\n};\n\nclass CGAWaitForVerticalSyncInstruction : public Instruction\n{\npublic:\n Instruction* expand()\n {\n insertBefore(new SetInstruction(&dx, port_CGA_status));\n LabelInstruction wait = new LabelInstruction();\n insertBefore(wait);\n insertBefore(new INInstruction(&al, &dx));\n insertBefore(new TESTInstruction(&al, mask_CGA_verticalSync));\n insertBefore(new JZInstruction(wait));\n Instruction* r = previous();\n remove();\n return r;\n }\n};\n\nclass CGAWaitForNoVerticalSyncInstruction : public Instruction\n{\npublic:\n Instruction* expand()\n {\n insertBefore(new SetInstruction(&dx, port_CGA_status));\n LabelInstruction wait = new LabelInstruction();\n insertBefore(wait);\n insertBefore(new INInstruction(&al, &dx));\n insertBefore(new TESTInstruction(&al, mask_CGA_verticalSync));\n insertBefore(new JNZInstruction(wait));\n Instruction* r = previous();\n remove();\n return r;\n }\n};\n\n\nclass Program : public ProgramBase\n{\npublic:\n void run()\n {\n\n }\n};\n<commit_msg>More assembler work<commit_after>#include \"alfe\/main.h\"\n\nclass Symbol\n{\npublic:\n Symbol() : _cookie(_nextCookie) { ++_nextCookie; }\n bool operator==(Symbol other) { return _cookie == other._cookie; }\n bool operator!=(Symbol other) { return _cookie != other._cookie; }\n UInt32 hash(int t) { return Hash(typeid(Symbol)).mixin(_cookie); }\nprivate:\n static int _nextCookie;\n int _cookie;\n};\n\nint Symbol::_nextCookie = 0;\n\nSymbol zero;\nSymbol unknown;\n\nclass Register\n{\npublic:\n Register(String name, int binaryEncoding, int width)\n : _name(name), _binaryEncoding(binaryEncoding), _width(width) { }\n Word value() { return _value; }\n bool isConstant() { return _symbol == zero; }\n virtual void assign(T value, Symbol symbol)\n {\n _value = value;\n _symbol = symbol;\n for (auto& i : _partOf)\n i->partAssigned(value, symbol, this);\n }\n bool hasValue(Word v) { return isConstant() && value() == v; }\n void clear() { assign(0, unknown); }\n void makePartOf(Register* larger)\n {\n _partOf.append(larger);\n }\n virtual void partAssigned(Word value, Symbol symbol, Register* part) { }\nprotected:\n String _name;\n int _width;\n int _binaryEncoding;\n Word _value;\n Symbol _symbol;\n AppendableArray<Register*> _partOf;\n};\n\nclass CompoundRegister : public Register\n{\npublic:\n CompoundRegister(String name, int binaryEncoding, Register* lowPart,\n Register* highPart)\n : Register(name, binaryEncoding, lowPart->_width + highPart->_width),\n _lowPart(lowPart), _highPart(highPart)\n {\n lowPart->makePartOf(this);\n highPart->makePartOf(this);\n }\n void assign(Word value, Symbol symbol)\n {\n Register::assign(value, symbol);\n int shift = 8 * lowPart->_width;\n \/\/ Assign direcly instead of going through assign to avoid sprious\n \/\/ partAssigned() calls.\n _lowPart->_value = value & ((1 << shift) - 1);\n _lowPart->_symbol = symbol;\n _highPart->_value = value >> shift;\n _highPart->_symbol = (symbol == zero ? zero : unknown);\n }\n void partAssigned(Word value, Symbol symbol, Register* part)\n {\n int shift = 8 * lowPart->_width;\n if (part == _lowPart) {\n _value = (_highPart->_value << shift) | value;\n if (symbol != _symbol) {\n if (_highPart->_symbol == zero && symbol == zero)\n _symbol = zero;\n else\n _symbol = unknown;\n }\n }\n else {\n _value = _lowPart->_value | (value << shift);\n if (_lowPart->_symbol == zero && symbol == zero)\n _symbol = zero;\n else\n _symbol = unknown;\n }\n }\nprivate:\n Register<T2>* _lowPart;\n Register<T2>* _highPart;\n int _binaryEncoding;\n};\n\nRegisterFile registerFile;\nRegister al(\"al\", 0, 1);\nRegister cl(\"cl\", 1, 1);\nRegister dl(\"dl\", 2, 1);\nRegister bl(\"bl\", 3, 1);\nRegister ah(\"ah\", 4, 1);\nRegister ch(\"ch\", 5, 1);\nRegister dh(\"dh\", 6, 1);\nRegister bh(\"bh\", 7, 1);\nCompoundRegister ax(\"ax\", 0, &al, &ah);\nCompoundRegister cx(\"cx\", 1, &cl, &dh);\nCompoundRegister dx(\"dx\", 2, &dl, &dh);\nCompoundRegister bx(\"bx\", 3, &bl, &bh);\nRegister sp(\"sp\", 4, 2);\nRegister bp(\"bp\", 5, 2);\nRegister si(\"si\", 6, 2);\nRegister di(\"di\", 7, 2);\nRegister es(\"es\", 0, 2);\nRegister cs(\"cs\", 1, 2);\nRegister ss(\"ss\", 2, 2);\nRegister ds(\"ds\", 3, 2);\nRegister ip(\"ip\", 0, 2);\nRegister flags(\"flags\", 0, 2);\n\nclass Instruction : public LinkedListMember<Instruction>\n{\n};\n\nclass MovInstruction : public Instruction\n{\npublic:\n MovInstruction(Operand destination, Operand source)\n : _destination(destination), _source(source)\n { }\nprivate:\n Operand _destination;\n Operand _source;\n\n};\n\nclass LabelInstruction : public Instruction\n{\n};\n\nclass InstructionChain\n{\npublic:\n void add(Instruction* instruction) { _instructions.add(instruction); }\nprivate:\n OwningLinkedList<Instruction> _instructions;\n};\n\nclass Operand\n{\n};\n\nvoid emit_mov(InstructionChain chain, Operand destination, Operand source)\n{\n chain.add(MovInstruction(destination, source));\n}\n\nvoid out(Operand port, Operand value)\n{\n if (port >= 0x100)\n mov(dx, port);\n if (value.size() == 1) {\n mov(al, value);\n if (dx.value() == port\n }\n else\n mov(ax, value);\n\n\n}\n\nclass SetInstruction\n{\npublic:\n SetInstruction(Register* destination, Word value, Symbol symbol = zero)\n : _destination(destination), _value(value), _symbol(symbol) { }\n Instruction* expand()\n {\n if (dynamic_cast<CPURegister*>(_destination) != 0)\n return this;\n\n if (_symbol == zero) {\n if (_destination->symbol() == zero) {\n auto pr = dynamic_cast<PortRegister*>(_destionation);\n if (pr != 0) {\n auto ipr = dynamic_cast<IndexedPortRegister*>(pr);\n if (ipr != 0) {\n insertBefore(new SetInstruction(ipr->indexRegister(),\n ipr->indexValue());\n }\n insertBefore(new PortWriteByteInstruction(\n pr->registerPort(), value);\n insertBefore(new SetNote(_destination, _value, _symbol));\n Instruction* r = previous();\n remove();\n return r;\n }\n else {\n if (!_destination->hasValue(_value)) {\n\n }\n }\n }\n else {\n\n }\n }\n else {\n\n }\n\n }\nprivate:\n Register* _destination;\n Word _value;\n Symbol _symbol;\n};\n\nstatic const Word port_CGA_status = 0x3da;\nstatic const Byte mask_CGA_notDisplayEnable = 1;\nstatic const Byte mask_CGA_verticalSync = 8;\n\nclass CGAWaitForDisplayEnableInstruction : public Instruction\n{\npublic:\n Instruction* expand()\n {\n insertBefore(new SetInstruction(&dx, port_CGA_status));\n LabelInstruction wait = new LabelInstruction();\n insertBefore(wait);\n insertBefore(new INInstruction(&al, &dx));\n insertBefore(new TESTInstruction(&al, mask_CGA_notDisplayEnable));\n insertBefore(new JNZInstruction(wait));\n Instruction* r = previous();\n remove();\n return r;\n }\n};\n\nclass CGAWaitForDisplayDisableInstruction : public Instruction\n{\npublic:\n Instruction* expand()\n {\n insertBefore(new SetInstruction(&dx, port_CGA_status));\n LabelInstruction wait = new LabelInstruction();\n insertBefore(wait);\n insertBefore(new INInstruction(&al, &dx));\n insertBefore(new TESTInstruction(&al, mask_CGA_notDisplayEnable));\n insertBefore(new JZInstruction(wait));\n Instruction* r = previous();\n remove();\n return r;\n }\n};\n\nclass CGAWaitForVerticalSyncInstruction : public Instruction\n{\npublic:\n Instruction* expand()\n {\n insertBefore(new SetInstruction(&dx, port_CGA_status));\n LabelInstruction wait = new LabelInstruction();\n insertBefore(wait);\n insertBefore(new INInstruction(&al, &dx));\n insertBefore(new TESTInstruction(&al, mask_CGA_verticalSync));\n insertBefore(new JZInstruction(wait));\n Instruction* r = previous();\n remove();\n return r;\n }\n};\n\nclass CGAWaitForNoVerticalSyncInstruction : public Instruction\n{\npublic:\n Instruction* expand()\n {\n insertBefore(new SetInstruction(&dx, port_CGA_status));\n LabelInstruction wait = new LabelInstruction();\n insertBefore(wait);\n insertBefore(new INInstruction(&al, &dx));\n insertBefore(new TESTInstruction(&al, mask_CGA_verticalSync));\n insertBefore(new JNZInstruction(wait));\n Instruction* r = previous();\n remove();\n return r;\n }\n};\n\n\nclass Program : public ProgramBase\n{\npublic:\n void run()\n {\n\n }\n};\n<|endoftext|>"} {"text":"<commit_before>\/*-------------------------------\nPASA LA CALCULADORA\nAutores: \nJaime Sevilla Molina\nVictor Gonzalez\nFecha\n2014\/11\nVersion: 1.0\n---------------------------------*\/\n\n\/\/BIBLIOTECAS\n#include <iostream>\n#include <cstdlib>\n#include <string>\n#include <ctime>\n#include <cmath>\n#include <fstream>\n#include <iomanip>\n\nusing namespace std;\n\n\/\/TIPOS PROPIOS\ntypedef enum tJugador\n{\n\tNadie,\n\tJugador,\n\tAutomata\n};\n\n\/\/FUNCIONES\n\/\/FUNCIONES DE JUEGO\n\nvoid saludar ();\n\n\/\/Dependiendo de quien gane, la despedida sera distinta\nvoid despedirse (tJugador ganador);\n\n\/\/Muestra un menu que permite al jugador jugar, salir, o ver las reglas del juego\nint menu();\n\n\/\/Muestra las instrucciones del juego, siempre que su archivo no contenga errores\nbool acerca();\n\n\/\/Conduce el desarrollo del juego y devuelve el ganador. \n\/\/Si se abandona, devuelve Nadie.\ntJugador pasaCalculadora();\n\n\/\/Decide aleatoriamente quien empieza.\ntJugador quienEmpieza();\n\/\/Devuelve true si nuevo esta en la misma fila que ultimo\nbool mismaFila(int ultimo, int nuevo);\n\n\n\/\/Devuelve true si nuevo esta en la misma columna que ultimo\nbool mismaColumna(int ultimo, int nuevo);\n\n\/\/Devuelve true si nuevo cumple las reglas del juego con respecto a ultimo\n\/\/Si ultimo == 0, este es el primer digito de la partida, y devuelve true\nbool digitoValido(int ultimo, int nuevo);\n\n\n\/\/FUNCIONES DE IA NIVEL 1\n\/\/Devuelve un digito del 1 al 9\nint digitoAleatorio();\n\n\/\/Devuelve un digito que cumpla las reglas del juego con respecto a ultimo.\nint digitoAutomata(int ultimo);\n\n\/\/FUNCIONES DE JUGADOR\n\/\/Pide un digito al jugador. Solo devolvera un valor valido (entre 0 y 9).\n\/\/Para un valor no valido, mostrara un error.\nint digitoPersona();\n\n\/\/Pide un digito al jugador mostrando el teclado. Solo devolvera un valor \n\/\/que cumpla las reglas del juego o 0. Para un valor no valido, mostrara un error.\nint digitoPersona(int ultimo);\n\n\/\/Determina si el numero de la calculadora se muestra o no, en funcion de si es valido\nchar mNumero(int ultimo, int n);\n\n\/\/Muestra los botones de la calculadora (solo los que se pueden pulsar en cada turno)\nvoid mostrarCalculadora(int ultimo);\n\n\n\/* Las funciones a continuacion se implementaran en un futuro\n\/\/FUNCIONES DE INFORME\n\/\/Actualiza el archivo informePC.txt con los tres argumentos. En caso de no encontrar\n\/\/el archivo, lo crea y devuelve false; en otro caso devuelve true.\nbool actInforme(int jugadas, int ganadas, int abandonos);\n\n\n\/\/FUNCIONES DE DIFICULTAD AVANZADA\nint botDificil(int ultimo);\n\n-----------------------------------------------------------------------------------*\/\n\n\nint main(){\n\ttJugador ganador;\n\tint opcion;\n\t\n\tsaludar();\n\t\n\t\/\/Bucle Menu\n\tdo{\n\t\topcion = menu();\n\t\tif(opcion == 1){\t\n\t\t\tganador = pasaCalculadora();\n\t\t\tdespedirse(ganador);\n\t\t}\n\t\telse if(opcion == 2) acerca();\n\t\n\t}while(opcion != 0);\n\t\n\tcout << \"Hasta la proxima (pulsa enter)\";\n\tcin;\n\n\treturn 0;\n}\n\t\n\/\/Saluda al jugador y le pregunta su nombre\nvoid saludar(){\n\tstring nombre;\n\tcout << \"Bienvenido a Pasa la calculadora!\" << endl;\n\tcout << \"Como te llamas? \";\n\tcin >> nombre;\n\tcout << \"Hola \" << nombre << endl << endl;\n}\n\n\/\/Se despide del jugador, la despedida varia segun gane el jugador, el automata o ninguno de ellos (el jugador abandone)\nvoid despedirse(tJugador ganador){\n\tstring nombre;\n\tif (ganador == Nadie){\n\t\tcout << \"¿Abandonas? Ohhh...\" << endl;\n\t}\n\telse if (ganador == Jugador){\n\t\tcout << \"Enhorabuena, has ganado\" << endl;\n\t}\n\telse \/*if (ganador == Automata)*\/{\n\t\tcout << \"Lo siento, he ganado\" << endl;\n\t}\n}\n\n\/\/Proporciona al jugador la posibilidad de jugar, ver las instrucciones del juego o salir.\nint menu(){\n\tint seleccionar;\n\tcout << \"1 - Jugar\" << endl;\n\tcout << \"2 - Acerca de\" << endl;\n\tcout << \"0 - Salir\" << endl;\n\t\n\tdo{\n\t\tcin.sync(); \/\/Por si quedan datos basura en el buffer\n\t\tcin >> seleccionar;\n\n\t\tif (seleccionar < 0 || seleccionar > 2)\n\t\t{\n\t\t\tcout << \"Error! Introduce un digito entre 0 y 2\" << endl;\n\t\t\tseleccionar = -1;\n\t\t}\n\t\telse if(cin.fail())\n\t\t{\n\t\t\tcout << \"Error! Introduce un digito\" << endl;\n\t\t\tcin.clear();\n\t\t}\n\t}while (seleccionar == -1);\n\n\treturn seleccionar;\n}\n\n\/\/Muestra el archivo \"acerca.txt\" siempre que este no contenga errores\nbool acerca(){\n\n\tbool ok;\n\tifstream acerca;\n\tchar c;\n\n\tacerca.open(\"acerca.txt\");\n\t\n\tif(acerca.is_open())\n\t{\n\t\tacerca.get(c); \/\/Lee el primer caracter\n\n\t\twhile(!acerca.fail()) \/\/Mientras la lectura no falle\n\t\t{\n\t\t\tcout << c;\n\t\t\tacerca.get(c); \/\/Lee el siguiente caracter\n\t\t}\n\n\t\tok = true;\n\t\tacerca.close();\n\n\t}\n\telse\n\t{\n\t\tok = false;\n\t\tcout << \"Error, el archivo 'acerca.txt' no existe\" << endl;\n\t}\n\n\treturn ok;\n}\n\n\/\/Conduce el desarrollo del juego y devuelve el ganador. \n\/\/Si se abandona, devuelve Nadie.\ntJugador pasaCalculadora(){\n\t\/\/Variables\n\ttJugador turno;\n\tint total = 0, ultimoDigito = 0;\n\tconst int META=31;\n\t\t\/\/Inicializar partida\n\tsrand(time(NULL));\/\/Semilla\n\tturno = quienEmpieza();\n\n\t\/\/Bucle de juego\n\tdo\n\t{\n\t\t\/\/Turno jugador\n\t\tif (turno == Jugador)\n\t\t{\n\t\t\tultimoDigito = digitoPersona(ultimoDigito);\n\t\t\tturno = Automata;\n\t\t}\n\t\t\/\/Turno bot\n\t\telse \/*if (turno == Automata)*\/\n\t\t{\n\t\t\tultimoDigito = digitoAutomata(ultimoDigito);\n\t\t\tturno = Jugador;\n\t\t}\n\t\ttotal += ultimoDigito;\n\t\tcout << \"Total = \" << total << endl;\n\t}\n\twhile ((total < META) && (ultimoDigito != 0));\n\t\n\tif (ultimoDigito == 0) turno = Nadie; \n\t\/\/Si el jugador abandona, no gana nadie\n\n\treturn turno;\n}\n\n\/\/Decide aleatoriamente quien empieza la partida, si el automata o el jugador\ntJugador quienEmpieza(){\n\tif (rand() % 2)\n\t{\n\t\tcout << \"Tu empiezas\" << endl;\n\t\treturn Jugador;\n\t}\n\telse\n\t{\n\t\tcout << \"Empiezo yo\" << endl;\n\t\treturn Automata;\n\t}\n}\n\n\/\/Define que numeros se encuentran en la misma fila que el ultimo pulsado\nbool mismaFila(int ultimo, int nuevo)\n{\n\tdouble filaUltimo, filaNuevo;\n\tfilaUltimo = (ultimo\/3);\n\tfilaNuevo = (nuevo\/3);\n\treturn ceil(filaUltimo) == ceil(filaNuevo);\n}\n\n\/\/Define que numeros se encuentran en la misma columna que el ultimo\nbool mismaColumna(int ultimo, int nuevo)\n{\n\tint columnaUltimo, columnaNuevo;\n\tcolumnaUltimo = (ultimo % 3);\n\tcolumnaNuevo = (nuevo % 3);\n\treturn columnaUltimo == columnaNuevo;\n}\n\n\/\/Determina que digitos se pueden pulsar en funcion de las reglas del juego\nbool digitoValido(int ultimo, int nuevo) \/\/hay un bug\n{\n\tif (ultimo == 0) return true;\/\/Si es el primer turno, todos los numeros valen\n\n\treturn ((mismaFila(ultimo, nuevo))||(mismaColumna(ultimo, nuevo)))&&(ultimo!=nuevo);\n}\n\n\/\/Genera un digito aleatorio\nint digitoAleatorio()\n{\n\treturn (rand() % 9) + 1;\n}\n\n\/\/Devuelve un digito que cumpla las reglas del juego con respecto a ultimo.\nint digitoAutomata(int ultimo)\n{\n\tint digito;\n\n\tdo\n\t{\n\tdigito = digitoAleatorio();\n\t}\n\twhile (!digitoValido(ultimo, digito));\n\n\tcout << \"Elijo el numero \" << digito << endl;\n\n\treturn digito;\n}\n\n\/\/Pide un digito al jugador. Solo devolvera un valor valido (entre 0 y 9).\n\/\/Para un valor no valido, mostrara un error.\nint digitoPersona()\n{\n\tint digito = -1;\n\n\tdo\n\t{\n\t\tcin.sync(); \/\/Por si quedan datos basura en el buffer\n\t\tcin >> digito;\n\n\t\tif (digito < 0 || digito > 9) \n\t\t{\n\t\tcout << \"Error! Introduce un digito entre 0 y 9\" << endl;\n\t\tdigito = -1;\n\t\t}\n\n\t\telse if (cin.fail())\n\t\t{\n\t\t\tcout << \"Error! Introduce un digito\" << endl;\n\t\t\tcin.clear();\n\t\t}\n\t}\n\twhile (digito == -1);\n\n\treturn digito;\n}\n\n\/\/Pide un digito al jugador mostrando el teclado. Solo devolvera un valor \n\/\/que cumpla las reglas del juego o 0. Para un valor no valido, mostrara un error.\nint digitoPersona(int ultimo)\n{\n\tint digito; \/\/-1 es mi error flag\n\t\n\tmostrarCalculadora(ultimo);\n\n\tdo\n\t{\n\t\tdigito = digitoPersona();\n\t\tif (!digitoValido(ultimo, digito))\n\t\t{\n\t\t\tcout << \"Error! El digito debe estar en la misma fila y columna que el ultimo\" << endl;\n\t\t\tdigito = -1;\n\t\t}\n\t}\n\twhile (digito == -1);\n\n\tcout << \"Has elegido el \" << digito << endl;\n\n\treturn digito;\n}\n\n\/\/Determina si el numero de la calculadora se muestra o no, en funcion de si es valido\nchar mNumero(int ultimo, int n)\n{\n\tif(digitoValido(ultimo, n)) return char (n+int('0'));\n\telse return ' ';\n}\n\n\/\/Muestra los botones de la calculadora (solo los que se pueden pulsar en cada turno)\nvoid mostrarCalculadora(int ultimo)\n{\n\tfor (int i = 7; i<10; i++)\n\t{\n\t\tcout << setw(3) << mNumero(ultimo, i);\n\t}\n\tcout << endl;\n\tfor (int i = 4; i<7; i++)\n\t{\n\t\tcout << setw(3) << mNumero(ultimo, i);\n\t}\n\tcout << endl;\n\tfor (int i = 1; i<4; i++)\n\t{\n\t\tcout << setw(3) << mNumero(ultimo, i);\n\t}\n\tcout << endl;\n}\n<commit_msg>Matando duendes<commit_after>\/*-------------------------------\nPASA LA CALCULADORA\nAutores: \nJaime Sevilla Molina\nVictor Gonzalez\nFecha\n2014\/11\nVersion: 2.0\n---------------------------------*\/\n\n\/\/BIBLIOTECAS\n#include <iostream>\n#include <cstdlib>\n#include <string>\n#include <ctime>\n#include <cmath>\n#include <fstream>\n#include <iomanip>\n\nusing namespace std;\n\n\/\/TIPOS PROPIOS\ntypedef enum tJugador\n{\n\tNadie,\n\tJugador,\n\tAutomata\n};\n\n\/\/FUNCIONES\n\/\/FUNCIONES DE JUEGO\n\nvoid saludar ();\n\n\/\/Dependiendo de quien gane, la despedida sera distinta\nvoid despedirse (tJugador ganador);\n\n\/\/Muestra un menu que permite al jugador jugar, salir, o ver las reglas del juego\nint menu();\n\n\/\/Muestra las instrucciones del juego, siempre que su archivo no contenga errores\nbool acerca();\n\n\/\/Conduce el desarrollo del juego y devuelve el ganador. \n\/\/Si se abandona, devuelve Nadie.\ntJugador pasaCalculadora();\n\n\/\/Decide aleatoriamente quien empieza.\ntJugador quienEmpieza();\n\/\/Devuelve true si nuevo esta en la misma fila que ultimo\nbool mismaFila(int ultimo, int nuevo);\n\n\n\/\/Devuelve true si nuevo esta en la misma columna que ultimo\nbool mismaColumna(int ultimo, int nuevo);\n\n\/\/Devuelve true si nuevo cumple las reglas del juego con respecto a ultimo\n\/\/Si ultimo == 0, este es el primer digito de la partida, y devuelve true\nbool digitoValido(int ultimo, int nuevo);\n\n\n\/\/FUNCIONES DE IA NIVEL 1\n\/\/Devuelve un digito del 1 al 9\nint digitoAleatorio();\n\n\/\/Devuelve un digito que cumpla las reglas del juego con respecto a ultimo.\nint digitoAutomata(int ultimo);\n\n\/\/FUNCIONES DE JUGADOR\n\/\/Pide un digito al jugador. Solo devolvera un valor valido (entre 0 y 9).\n\/\/Para un valor no valido, mostrara un error.\nint digitoPersona();\n\n\/\/Pide un digito al jugador mostrando el teclado. Solo devolvera un valor \n\/\/que cumpla las reglas del juego o 0. Para un valor no valido, mostrara un error.\nint digitoPersona(int ultimo);\n\n\/\/Determina si el numero de la calculadora se muestra o no, en funcion de si es valido\nchar mNumero(int ultimo, int n);\n\n\/\/Muestra los botones de la calculadora (solo los que se pueden pulsar en cada turno)\nvoid mostrarCalculadora(int ultimo);\n\n\n\/* Las funciones a continuacion se implementaran en un futuro\n\/\/FUNCIONES DE INFORME\n\/\/Actualiza el archivo informePC.txt con los tres argumentos. En caso de no encontrar\n\/\/el archivo, lo crea y devuelve false; en otro caso devuelve true.\nbool actInforme(int jugadas, int ganadas, int abandonos);\n\n\n\/\/FUNCIONES DE DIFICULTAD AVANZADA\nint botDificil(int ultimo);\n\n-----------------------------------------------------------------------------------*\/\n\n\nint main(){\n\ttJugador ganador;\n\tint opcion;\n\t\n\tsaludar();\n\t\n\t\/\/Bucle Menu\n\tdo{\n\t\topcion = menu();\n\t\tif(opcion == 1){\t\n\t\t\tganador = pasaCalculadora();\n\t\t\tdespedirse(ganador);\n\t\t}\n\t\telse if(opcion == 2) acerca();\n\t\n\t}while(opcion != 0);\n\t\n\tcout << \"Hasta la proxima (pulsa enter)\";\n\tcin;\n\n\treturn 0;\n}\n\t\n\/\/Saluda al jugador y le pregunta su nombre\nvoid saludar(){\n\tstring nombre;\n\tcout << \"Bienvenido a Pasa la calculadora!\" << endl;\n\tcout << \"Como te llamas? \";\n\tcin >> nombre;\n\tcout << \"Hola \" << nombre << endl << endl;\n}\n\n\/\/Se despide del jugador, la despedida varia segun gane el jugador, el automata o ninguno de ellos (el jugador abandone)\nvoid despedirse(tJugador ganador){\n\tstring nombre;\n\tif (ganador == Nadie){\n\t\tcout << \"Abandonas? Ohhh...\" << endl;\n\t}\n\telse if (ganador == Jugador){\n\t\tcout << \"Enhorabuena, has ganado\" << endl;\n\t}\n\telse \/*if (ganador == Automata)*\/{\n\t\tcout << \"Lo siento, he ganado\" << endl;\n\t}\n}\n\n\/\/Proporciona al jugador la posibilidad de jugar, ver las instrucciones del juego o salir.\nint menu(){\n\tint seleccionar = -1; \/\/Error flag\n\tcout << \"1 - Jugar\" << endl;\n\tcout << \"2 - Acerca de\" << endl;\n\tcout << \"0 - Salir\" << endl;\n\t\n\tdo{\n\t\tcin.sync(); \/\/Por si quedan datos basura en el buffer\n\t\tcin >> seleccionar;\n\n\t\tif(cin.fail())\n\t\t{\n\t\t\tcout << \"Error! Introduce un digito\" << endl;\n\t\t\tcin.clear();\n\t\t}\n\n\t\telse if (seleccionar < 0 || seleccionar > 2)\n\t\t{\n\t\t\tcout << \"Error! Introduce un digito entre 0 y 2\" << endl;\n\t\t\tseleccionar = -1;\n\t\t}\n\t\t\n\t}while (seleccionar == -1);\n\n\treturn seleccionar;\n}\n\n\/\/Muestra el archivo \"acerca.txt\" siempre que este no contenga errores\nbool acerca(){\n\n\tbool ok;\n\tifstream acerca;\n\tchar c;\n\n\tacerca.open(\"acerca.txt\");\n\t\n\tif(acerca.is_open())\n\t{\n\t\tacerca.get(c); \/\/Lee el primer caracter\n\n\t\twhile(!acerca.fail()) \/\/Mientras la lectura no falle\n\t\t{\n\t\t\tcout << c;\n\t\t\tacerca.get(c); \/\/Lee el siguiente caracter\n\t\t}\n\n\t\tok = true;\n\t\tacerca.close();\n\n\t}\n\telse\n\t{\n\t\tok = false;\n\t\tcout << \"Error, el archivo 'acerca.txt' no existe\" << endl;\n\t}\n\n\treturn ok;\n}\n\n\/\/Conduce el desarrollo del juego y devuelve el ganador. \n\/\/Si se abandona, devuelve Nadie.\ntJugador pasaCalculadora(){\n\t\/\/Variables\n\ttJugador turno;\n\tint total = 0, ultimoDigito = 0;\n\tconst int META=31;\n\t\t\/\/Inicializar partida\n\tsrand(time(NULL));\/\/Semilla\n\tturno = quienEmpieza();\n\n\t\/\/Bucle de juego\n\tdo\n\t{\n\t\t\/\/Turno jugador\n\t\tif (turno == Jugador)\n\t\t{\n\t\t\tultimoDigito = digitoPersona(ultimoDigito);\n\t\t\tturno = Automata;\n\t\t}\n\t\t\/\/Turno bot\n\t\telse \/*if (turno == Automata)*\/\n\t\t{\n\t\t\tultimoDigito = digitoAutomata(ultimoDigito);\n\t\t\tturno = Jugador;\n\t\t}\n\t\ttotal += ultimoDigito;\n\t\tcout << \"Total = \" << total << endl;\n\t}\n\twhile ((total < META) && (ultimoDigito != 0));\n\t\n\tif (ultimoDigito == 0) turno = Nadie; \n\t\/\/Si el jugador abandona, no gana nadie\n\n\treturn turno;\n}\n\n\/\/Decide aleatoriamente quien empieza la partida, si el automata o el jugador\ntJugador quienEmpieza(){\n\tif (rand() % 2)\n\t{\n\t\tcout << \"Tu empiezas\" << endl;\n\t\treturn Jugador;\n\t}\n\telse\n\t{\n\t\tcout << \"Empiezo yo\" << endl;\n\t\treturn Automata;\n\t}\n}\n\n\/\/Define que numeros se encuentran en la misma fila que el ultimo pulsado\nbool mismaFila(int ultimo, int nuevo)\n{\n\tdouble filaUltimo, filaNuevo;\n\tfilaUltimo = (ultimo\/3);\n\tfilaNuevo = (nuevo\/3);\n\treturn ceil(filaUltimo) == ceil(filaNuevo);\n}\n\n\/\/Define que numeros se encuentran en la misma columna que el ultimo\nbool mismaColumna(int ultimo, int nuevo)\n{\n\tint columnaUltimo, columnaNuevo;\n\tcolumnaUltimo = (ultimo % 3);\n\tcolumnaNuevo = (nuevo % 3);\n\treturn columnaUltimo == columnaNuevo;\n}\n\n\/\/Determina que digitos se pueden pulsar en funcion de las reglas del juego\nbool digitoValido(int ultimo, int nuevo) \/\/hay un bug\n{\n\tif (ultimo == 0) return true;\/\/Si es el primer turno, todos los numeros valen\n\n\treturn ((mismaFila(ultimo, nuevo))||(mismaColumna(ultimo, nuevo)))&&(ultimo!=nuevo);\n}\n\n\/\/Genera un digito aleatorio\nint digitoAleatorio()\n{\n\treturn (rand() % 9) + 1;\n}\n\n\/\/Devuelve un digito que cumpla las reglas del juego con respecto a ultimo.\nint digitoAutomata(int ultimo)\n{\n\tint digito;\n\n\tdo\n\t{\n\tdigito = digitoAleatorio();\n\t}\n\twhile (!digitoValido(ultimo, digito));\n\n\tcout << \"Elijo el numero \" << digito << endl;\n\n\treturn digito;\n}\n\n\/\/Pide un digito al jugador. Solo devolvera un valor valido (entre 0 y 9).\n\/\/Para un valor no valido, mostrara un error.\nint digitoPersona()\n{\n\tint digito = -1;\n\n\tdo\n\t{\n\t\tcin.sync(); \/\/Por si quedan datos basura en el buffer\n\t\tcin >> digito;\n\n\t\tif (cin.fail())\n\t\t{\n\t\t\tcout << \"Error! Introduce un digito\" << endl;\n\t\t\tcin.clear();\n\t\t}\n\n\t\telse if (digito < 0 || digito > 9) \n\t\t{\n\t\tcout << \"Error! Introduce un digito entre 0 y 9\" << endl;\n\t\tdigito = -1;\n\t\t}\n\t\t\n\t}\n\twhile (digito == -1);\n\n\treturn digito;\n}\n\n\/\/Pide un digito al jugador mostrando el teclado. Solo devolvera un valor \n\/\/que cumpla las reglas del juego o 0. Para un valor no valido, mostrara un error.\nint digitoPersona(int ultimo)\n{\n\tint digito = -1; \/\/-1 es mi error flag\n\t\n\tmostrarCalculadora(ultimo);\n\n\tdo\n\t{\n\t\tdigito = digitoPersona();\n\t\tif (!digitoValido(ultimo, digito))\n\t\t{\n\t\t\tcout << \"Error! El digito debe estar en la misma fila y columna que el ultimo\" << endl;\n\t\t\tdigito = -1;\n\t\t}\n\t}\n\twhile (digito == -1);\n\n\tcout << \"Has elegido el \" << digito << endl;\n\n\treturn digito;\n}\n\n\/\/Determina si el numero de la calculadora se muestra o no, en funcion de si es valido\nchar mNumero(int ultimo, int n)\n{\n\tif(digitoValido(ultimo, n)) return char (n+int('0'));\n\telse return ' ';\n}\n\n\/\/Muestra los botones de la calculadora (solo los que se pueden pulsar en cada turno)\nvoid mostrarCalculadora(int ultimo)\n{\n\tfor (int i = 7; i<10; i++)\n\t{\n\t\tcout << setw(3) << mNumero(ultimo, i);\n\t}\n\tcout << endl;\n\tfor (int i = 4; i<7; i++)\n\t{\n\t\tcout << setw(3) << mNumero(ultimo, i);\n\t}\n\tcout << endl;\n\tfor (int i = 1; i<4; i++)\n\t{\n\t\tcout << setw(3) << mNumero(ultimo, i);\n\t}\n\tcout << endl;\n}\n<|endoftext|>"} {"text":"<commit_before>\/************************************************************************\/\/**\n * @file PeerIOSerialControl.cpp\n * @brief Arduino Peer IO-Control through Serial Port Communications.\n * @authors \n * tgit23 1\/2017 Original\n ******************************************************************************\/\n#include \"PeerIOSerialControl.h\"\n#define ID_MASK 0x0F \/\/ Bytes[0] [0000 1111] ArduinoID ( 0-15 )\n#define REPLY_BIT 4 \/\/ Bytes[0] [0001 0000] Reply-1, Send-0\n#define RW_BIT 5 \/\/ Bytes[0] [0010 0000] Read-1, Write-0\n#define DA_BIT 6 \/\/ Bytes[0] [0100 0000] Digital-1, Analog-0\n#define DPIN_MASK 0x3F \/\/ Bytes[1] [0011 1111] Digital Pins ( 0 - 63 )\n#define APIN_MASK 0x7F \/\/ Bytes[1] [0111 1111] Analog Pins ( 0 - 127 )\n#define HL_BIT 6 \/\/ Bytes[1] [0100 0000] High-1, Low-0\n#define END_BIT 7 \/\/ Bytes[?} [1000 0000] Any set 8th bit flags END-OF-PACKET\n\n\/\/-----------------------------------------------------------------------------------------------------\n\/\/ Initializer\n\/\/-----------------------------------------------------------------------------------------------------\nPeerIOSerialControl::PeerIOSerialControl(int ThisArduinoID, Stream &CommunicationPort, Stream &DebugPort) {\n ArduinoID = ThisArduinoID;\n COMPort = &CommunicationPort;\n DBPort = &DebugPort;\n}\n\n\nvoid PeerIOSerialControl::digitalWriteB(uint8_t Pin, uint8_t Value) {\n int packetID = SendPacket(DIGITAL,WRITE,Pin,Value);\n unsigned long Start = millis();\n do {\n if ( Available() ) break;\n } while ( (millis() - Start) < BlockingTimeoutMS );\n}\nint PeerIOSerialControl::digitalReadB(uint8_t Pin) {\n int packetID = SendPacket(DIGITAL,READ,Pin);\n unsigned long Start = millis();\n do {\n if ( Available() ) return GetReply(packetID);\n } while ( (millis() - Start) < BlockingTimeoutMS );\n return -1;\n}\nint PeerIOSerialControl::analogReadB(uint8_t Pin) {\n int packetID = SendPacket(ANALOG,READ,Pin);\n unsigned long Start = millis();\n do {\n if ( Available() ) return GetReply(packetID);\n } while ( (millis() - Start) < BlockingTimeoutMS );\n return -1;\n}\nvoid PeerIOSerialControl::analogWriteB(uint8_t Pin, int Value) {\n int packetID = SendPacket(ANALOG,WRITE,Pin,Value);\n unsigned long Start = millis();\n do {\n if ( Available() ) break;\n } while ( (millis() - Start) < BlockingTimeoutMS );\n}\n\n\nint PeerIOSerialControl::digitalWriteNB(uint8_t Pin, uint8_t Value) {\n return SendPacket(DIGITAL,WRITE,Pin,Value);\n}\nint PeerIOSerialControl::digitalReadNB(uint8_t Pin) {\n return SendPacket(DIGITAL,READ,Pin);\n}\nint PeerIOSerialControl::analogReadNB(uint8_t Pin) {\n return SendPacket(ANALOG,READ,Pin);\n}\nint PeerIOSerialControl::analogWriteNB(uint8_t Pin, int Value) {\n return SendPacket(ANALOG,WRITE,Pin,Value);\n}\n\nvoid PeerIOSerialControl::TargetArduinoID(int ID) {\n iTargetArduinoID = ID;\n}\nint PeerIOSerialControl::TargetArduinoID() {\n return iTargetArduinoID;\n}\n\nvoid PeerIOSerialControl::Timeout(int milliseconds) {\n BlockingTimeoutMS = milliseconds;\n}\nint PeerIOSerialControl::Timeout() {\n return BlockingTimeoutMS;\n}\nvoid PeerIOSerialControl::VirtualPin(int Pin, int Value) {\n if ( Pin > 63 && Pin < 128 ) iVirtualPin[Pin-64] = Value;\n}\nint PeerIOSerialControl::VirtualPin(int Pin) {\n if ( Pin > 63 && Pin < 128 ) return iVirtualPin[Pin-64];\n}\n \n\/\/-----------------------------------------------------------------------------------------------------\n\/\/ SendPacket()\n\/\/-----------------------------------------------------------------------------------------------------\nint PeerIOSerialControl::SendPacket(bool DA, bool RW, byte Pin, int Value = -1) {\n DBL((\"+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\"));\n DBL((\"SendPacket()\"));\n byte SBytes[4] = { 0,0,0,0 };\n if ( DA ) bitSet(SBytes[0],DA_BIT);\n if ( RW ) bitSet(SBytes[0],RW_BIT);\n SBytes[0] = SBytes[0] | (iTargetArduinoID & ID_MASK);\n \n if ( DA == DIGITAL ) {\n SBytes[1] = (Pin & DPIN_MASK); \/\/ 6-bit Pin for Digital\n if ( RW != READ ) bitWrite(SBytes[1],HL_BIT,(Value>0)); \/\/ Digital Write - Set H\/L Bit\n bitSet(SBytes[1],END_BIT); \/\/ Digital only uses 2-Bytes \n \n } else {\n SBytes[1] = (Pin & APIN_MASK); \/\/ 7-bit Pin for Analog\n if ( Value > -1 ) {\n Value = ValueTo7bits(Value); \/\/ Conversion marks the END_BIT\n SBytes[2] = lowByte(Value);\n SBytes[3] = highByte(Value);\n } else {\n bitSet(SBytes[1],END_BIT); \/\/ Set END_BIT if not sending Value\n }\n } \n \n DB((\"SendBytes( \"));\n COMPort->write(SBytes[0]);\n COMPort->write(SBytes[1]);\n if ( SBytes[2] != 0 ) COMPort->write(SBytes[2]);\n if ( SBytes[3] != 0 ) COMPort->write(SBytes[3]);\n DB((SBytes[0],HEX));DBC;DB((SBytes[1],HEX));DBC;DB((SBytes[2],HEX));DBC;DB((SBytes[3],HEX));DBL((\" )\"));\n \n return ( SBytes[1] << 8 ) | SBytes[0]; \/\/ Return Bytes 0, 1 for tracking\n}\n\n\/\/-----------------------------------------------------------------------------------------------------\n\/\/ GetReply()\n\/\/-----------------------------------------------------------------------------------------------------\nint PeerIOSerialControl::GetReply(int packetID = -1) {\n DB((\"GetReply(\"));DB((packetID,HEX));DBL((\")\"));\n int UseRBI = RBI - 1;\n if ( UseRBI < 1 ) UseRBI = 0;\n \n \/\/ Find the Reply for this Command\n if ( packetID != -1 ) {\n byte Byte0 = lowByte(packetID);\n byte Byte1 = highByte(packetID);\n int i = UseRBI; UseRBI = -1;\n do {\n DB((\"\\tRBytes[\"));DB((i));DB((\"][0] = \"));DBL((RBytes[i][0],HEX));\n DB((\"\\tRBytes[\"));DB((i));DB((\"][1] = \"));DBL((RBytes[i][1],HEX));\n if ( (Byte0 & 0xEF) == (RBytes[i][0] & 0xEF) && \n (Byte1 & 0x3F) == (RBytes[i][1] & 0x3F) ) { \n UseRBI = i; \n break;\n }\n i--; if ( i < 0 ) i = 9;\n } while ( i != RBI );\n }\n\n if ( UseRBI < 0 ) return -1;\n if ( bitRead(RBytes[UseRBI][0],RW_BIT) == WRITE ) { \n return 0; \/\/ Okay Status for a WRITE COMMAND\n } else {\n if ( bitRead(RBytes[UseRBI][0],DA_BIT) == DIGITAL ) { \/\/ Value of the Reply\n return bitRead(RBytes[UseRBI][1],HL_BIT);\n } else {\n return ValueTo8bits(RBytes[UseRBI][2],RBytes[UseRBI][3]);\n }\n }\n}\n\n\/\/-----------------------------------------------------------------------------------------------------\n\/\/ ValueTo8bits() ValueTo7bits()\n\/\/ - Encodes \/ Decodes numeric values into (2)7-bit bytes for the 14-bit 'AV' (Analog Value) Bytes\n\/\/ - This function automatically attaches the END_BIT at the appropriate location.\n\/\/-----------------------------------------------------------------------------------------------------\nint PeerIOSerialControl::ValueTo8bits(byte lByte, byte hByte) {\n bitClear(hByte,7); \/\/ Clear any End-Of-Packet flag\n bitWrite(lByte,7,bitRead(hByte,0)); \/\/ Transfer hByte<0> onto lByte<7>\n return (hByte<<7) | lByte; \/\/ Left shift 7 overwrites lByte<7>\n}\nint PeerIOSerialControl::ValueTo7bits(int From8BitValue) {\n byte lByte = lowByte(From8BitValue);\n byte hByte = highByte(From8BitValue);\n if ( From8BitValue > 0x3FFF ) return -1; \/\/ Value is too big for a 14-bit Value\n hByte = hByte << 1; \/\/ Make Room on hByte for bit-7 of lByte\n bitWrite(hByte,0,bitRead(lByte,7)); \/\/ Transfer lByte<7> onto hByte<0>\n if ( From8BitValue > 0x7F ) { \n bitSet(hByte,7); \/\/ Value > 7-bits so Set 'END_BIT' @ hByte\n bitClear(lByte,7);\n } else {\n bitSet(lByte,7); \/\/ Value <= 7-bits so Set 'END_BIT' @ lByte\n bitClear(hByte,7);\n }\n return (hByte<<8) | lByte; \n}\n\n\/\/-----------------------------------------------------------------------------------------------------\n\/\/ DecodePacket()\n\/\/-----------------------------------------------------------------------------------------------------\nvoid PeerIOSerialControl::DecodePacket(long lPacket = -1) {\n byte Byte0; byte Byte1; byte Byte2; byte Byte3;\n if ( lPacket = -1 ) { \n Byte0=Bytes[0];Byte1=Bytes[1];Byte2=Bytes[2];Byte3=Bytes[3];\n } else {\n Byte0 = ( lPacket >> 24 ) & 0xFF;\n Byte1 = ( lPacket >> 16 ) & 0xFF;\n Byte2 = ( lPacket >> 8 ) & 0xFF;\n Byte3 = lPacket & 0xFF; \n }\n DB((\"D\/A Flag = \"));if ( bitRead(Byte0,DA_BIT) ) { DBL((\"DIGITAL\")); } else { DBL((\"ANALOG\")); }\n DB((\"R\/W Flag = \"));if ( bitRead(Byte0,RW_BIT) ) { DBL((\"READ\")); } else { DBL((\"WRITE\")); }\n DB((\"S\/R Flag = \"));if ( bitRead(Byte0,REPLY_BIT) ) { DBL((\"REPLY\")); } else { DBL((\"SEND\")); }\n DB((\"Arduino ID = \"));DBL(( (Byte0 & ID_MASK) ));\n if ( bitRead(Byte0,DA_BIT) ) { \n DB((\"H\/L Flag = \"));\n if ( bitRead(Byte0,HL_BIT) ) { DBL((\"HIGH\")); } else { DBL((\"LOW\")); }\n DB((\"PIN = \"));DBL(( (Byte1 & DPIN_MASK) ));\n } else {\n DB((\"Value = \"));DBL(( ValueTo8bits(Byte2, Byte3) ));\n DB((\"PIN = \"));DBL(( (Byte1 & APIN_MASK) ));\n }\n}\n \n\/\/-----------------------------------------------------------------------------------------------------\n\/\/ ProcessPacket()\n\/\/-----------------------------------------------------------------------------------------------------\nvoid PeerIOSerialControl::ProcessPacket() {\n DB((\"ProcessPacket( \"));\n DB((Bytes[0],HEX));DBC;DB((Bytes[1],HEX));DBC;DB((Bytes[2],HEX));DBC;DB((Bytes[3],HEX));\n DB((\" ) - \"));\n \n \/\/ REPLY PACKET RECEIVED\n if ( bitRead(Bytes[0],REPLY_BIT) ) {\n DBL((\"Packet Type REPLY\"));\n for ( int i=0;i<4;i++ ) RBytes[RBI][i] = Bytes[i]; \/\/ Put Replies in RBytes Buffer\n#if defined(DEBUG)\n #if DEBUG>0\n DecodePacket();\n #endif\n#endif\n\n\n \/\/ COMMAND PACKET RECEIVED\n } else if ( (Bytes[0] & ID_MASK) == ArduinoID ) {\n \n DBL((\"Packet Type SEND\"));\n \/\/ DIGITAL\n if ( bitRead(Bytes[0],DA_BIT) == DIGITAL ) {\n int pin = Bytes[1] & DPIN_MASK;\n if ( bitRead(Bytes[0],RW_BIT) == READ ) {\n DB((\"digitalRead(\"));DB((pin));DBL((\")\"));\n bitWrite(Bytes[1],HL_BIT,digitalRead(pin));\n } else {\n DB((\"digitalWrite(\"));DB((pin));DB((\",\"));DB((bitRead(Bytes[1],HL_BIT)));DBL((\")\"));\n digitalWrite(pin,bitRead(Bytes[1],HL_BIT));\n }\n bitSet(Bytes[1],END_BIT);\n\n \/\/ ANALOG\n } else {\n int pin = Bytes[1] & APIN_MASK;\n int val = 0;\n if ( bitRead(Bytes[0],RW_BIT) == READ ) {\n DB((\"analogRead(\"));DB((pin));DBL((\")\"));\n if ( pin > 63 && pin < 128 ) { \n val = ValueTo7bits(iVirtualPin[pin-64]); \n } else { \n val = ValueTo7bits(analogRead(pin)); \n }\n Bytes[2] = lowByte(val);\n Bytes[3] = highByte(val);\n } else { \n DB((\"analogWrite(\"));DB((pin));DB((\",\"));DB((ValueTo8bits(Bytes[2],Bytes[3])));DBL((\")\"));\n if ( pin > 63 && pin < 128 ) { \n iVirtualPin[pin-64] = ValueTo8bits(Bytes[2],Bytes[3]); \n } else { \n analogWrite(pin,ValueTo8bits(Bytes[2],Bytes[3]));\n }\n }\n }\n \n \/\/ Send out the Reply Packet\n bitSet(Bytes[0],REPLY_BIT); \/\/ Set the Reply Bit\n DB((\"SendBytes( \"));\n COMPort->write(Bytes[0]);\n COMPort->write(Bytes[1]);\n if ( Bytes[2] != 0 ) COMPort->write(Bytes[2]);\n if ( Bytes[3] != 0 ) COMPort->write(Bytes[3]);\n DB((Bytes[0],HEX));DBC;DB((Bytes[1],HEX));DBC;DB((Bytes[2],HEX));DBC;DB((Bytes[3],HEX));DBL((\" )\"));\n } \n\n}\n\n\/\/-----------------------------------------------------------------------------------------------------\n\/\/ Available()\n\/\/-----------------------------------------------------------------------------------------------------\nbool PeerIOSerialControl::Available() {\n \/\/ Receive Bytes\n while(COMPort->available() > 0) {\n Bytes[idx] = COMPort->read();\n if ( Bytes[idx] != -1 ) {\n \/\/DBL((Bytes[idx],HEX));\n if ( bitRead(Bytes[idx],END_BIT) ) {\n DBL((\"-----------------------------------------------------------\"));\n DB((\"Packet Received @ Size: \"));DBL((idx+1));\n bitClear(Bytes[idx],END_BIT); \/\/ Clear the END_BIT\n for(int i=(idx+1);i<4;i++) Bytes[i]=0; \/\/ Clear unused bytes\n idx = 0;\n ProcessPacket();\n return true;\n } else {\n idx++;\n }\n }\n }\n}\n\n<commit_msg>Fixed new compiler warnings<commit_after>\/************************************************************************\/\/**\n * @file PeerIOSerialControl.cpp\n * @brief Arduino Peer IO-Control through Serial Port Communications.\n * @authors \n * tgit23 1\/2017 Original\n ******************************************************************************\/\n#include \"PeerIOSerialControl.h\"\n#define ID_MASK 0x0F \/\/ Bytes[0] [0000 1111] ArduinoID ( 0-15 )\n#define REPLY_BIT 4 \/\/ Bytes[0] [0001 0000] Reply-1, Send-0\n#define RW_BIT 5 \/\/ Bytes[0] [0010 0000] Read-1, Write-0\n#define DA_BIT 6 \/\/ Bytes[0] [0100 0000] Digital-1, Analog-0\n#define DPIN_MASK 0x3F \/\/ Bytes[1] [0011 1111] Digital Pins ( 0 - 63 )\n#define APIN_MASK 0x7F \/\/ Bytes[1] [0111 1111] Analog Pins ( 0 - 127 )\n#define HL_BIT 6 \/\/ Bytes[1] [0100 0000] High-1, Low-0\n#define END_BIT 7 \/\/ Bytes[?} [1000 0000] Any set 8th bit flags END-OF-PACKET\n\n\/\/-----------------------------------------------------------------------------------------------------\n\/\/ Initializer\n\/\/-----------------------------------------------------------------------------------------------------\nPeerIOSerialControl::PeerIOSerialControl(int ThisArduinoID, Stream &CommunicationPort, Stream &DebugPort) {\n ArduinoID = ThisArduinoID;\n COMPort = &CommunicationPort;\n DBPort = &DebugPort;\n}\n\n\nvoid PeerIOSerialControl::digitalWriteB(uint8_t Pin, uint8_t Value) {\n int packetID = SendPacket(DIGITAL,WRITE,Pin,Value);\n unsigned long Start = millis();\n do {\n if ( Available() ) break;\n } while ( (millis() - Start) < BlockingTimeoutMS );\n}\nint PeerIOSerialControl::digitalReadB(uint8_t Pin) {\n int packetID = SendPacket(DIGITAL,READ,Pin);\n unsigned long Start = millis();\n do {\n if ( Available() ) return GetReply(packetID);\n } while ( (millis() - Start) < BlockingTimeoutMS );\n return -1;\n}\nint PeerIOSerialControl::analogReadB(uint8_t Pin) {\n int packetID = SendPacket(ANALOG,READ,Pin);\n unsigned long Start = millis();\n do {\n if ( Available() ) return GetReply(packetID);\n } while ( (millis() - Start) < BlockingTimeoutMS );\n return -1;\n}\nvoid PeerIOSerialControl::analogWriteB(uint8_t Pin, int Value) {\n int packetID = SendPacket(ANALOG,WRITE,Pin,Value);\n unsigned long Start = millis();\n do {\n if ( Available() ) break;\n } while ( (millis() - Start) < BlockingTimeoutMS );\n}\n\n\nint PeerIOSerialControl::digitalWriteNB(uint8_t Pin, uint8_t Value) {\n return SendPacket(DIGITAL,WRITE,Pin,Value);\n}\nint PeerIOSerialControl::digitalReadNB(uint8_t Pin) {\n return SendPacket(DIGITAL,READ,Pin);\n}\nint PeerIOSerialControl::analogReadNB(uint8_t Pin) {\n return SendPacket(ANALOG,READ,Pin);\n}\nint PeerIOSerialControl::analogWriteNB(uint8_t Pin, int Value) {\n return SendPacket(ANALOG,WRITE,Pin,Value);\n}\n\nvoid PeerIOSerialControl::TargetArduinoID(int ID) {\n iTargetArduinoID = ID;\n}\nint PeerIOSerialControl::TargetArduinoID() {\n return iTargetArduinoID;\n}\n\nvoid PeerIOSerialControl::Timeout(int milliseconds) {\n BlockingTimeoutMS = milliseconds;\n}\nint PeerIOSerialControl::Timeout() {\n return BlockingTimeoutMS;\n}\nvoid PeerIOSerialControl::VirtualPin(int Pin, int Value) {\n if ( Pin > 63 && Pin < 128 ) iVirtualPin[Pin-64] = Value;\n}\nint PeerIOSerialControl::VirtualPin(int Pin) {\n if ( Pin > 63 && Pin < 128 ) return iVirtualPin[Pin-64];\n}\n \n\/\/-----------------------------------------------------------------------------------------------------\n\/\/ SendPacket()\n\/\/-----------------------------------------------------------------------------------------------------\nint PeerIOSerialControl::SendPacket(bool DA, bool RW, byte Pin, int Value) {\n DBL((\"+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\"));\n DBL((\"SendPacket()\"));\n byte SBytes[4] = { 0,0,0,0 };\n if ( DA ) bitSet(SBytes[0],DA_BIT);\n if ( RW ) bitSet(SBytes[0],RW_BIT);\n SBytes[0] = SBytes[0] | (iTargetArduinoID & ID_MASK);\n \n if ( DA == DIGITAL ) {\n SBytes[1] = (Pin & DPIN_MASK); \/\/ 6-bit Pin for Digital\n if ( RW != READ ) bitWrite(SBytes[1],HL_BIT,(Value>0)); \/\/ Digital Write - Set H\/L Bit\n bitSet(SBytes[1],END_BIT); \/\/ Digital only uses 2-Bytes \n \n } else {\n SBytes[1] = (Pin & APIN_MASK); \/\/ 7-bit Pin for Analog\n if ( Value > -1 ) {\n Value = ValueTo7bits(Value); \/\/ Conversion marks the END_BIT\n SBytes[2] = lowByte(Value);\n SBytes[3] = highByte(Value);\n } else {\n bitSet(SBytes[1],END_BIT); \/\/ Set END_BIT if not sending Value\n }\n } \n \n DB((\"SendBytes( \"));\n COMPort->write(SBytes[0]);\n COMPort->write(SBytes[1]);\n if ( SBytes[2] != 0 ) COMPort->write(SBytes[2]);\n if ( SBytes[3] != 0 ) COMPort->write(SBytes[3]);\n DB((SBytes[0],HEX));DBC;DB((SBytes[1],HEX));DBC;DB((SBytes[2],HEX));DBC;DB((SBytes[3],HEX));DBL((\" )\"));\n \n return ( SBytes[1] << 8 ) | SBytes[0]; \/\/ Return Bytes 0, 1 for tracking\n}\n\n\/\/-----------------------------------------------------------------------------------------------------\n\/\/ GetReply()\n\/\/-----------------------------------------------------------------------------------------------------\nint PeerIOSerialControl::GetReply(int packetID) {\n DB((\"GetReply(\"));DB((packetID,HEX));DBL((\")\"));\n int UseRBI = RBI - 1;\n if ( UseRBI < 1 ) UseRBI = 0;\n \n \/\/ Find the Reply for this Command\n if ( packetID != -1 ) {\n byte Byte0 = lowByte(packetID);\n byte Byte1 = highByte(packetID);\n int i = UseRBI; UseRBI = -1;\n do {\n DB((\"\\tRBytes[\"));DB((i));DB((\"][0] = \"));DBL((RBytes[i][0],HEX));\n DB((\"\\tRBytes[\"));DB((i));DB((\"][1] = \"));DBL((RBytes[i][1],HEX));\n if ( (Byte0 & 0xEF) == (RBytes[i][0] & 0xEF) && \n (Byte1 & 0x3F) == (RBytes[i][1] & 0x3F) ) { \n UseRBI = i; \n break;\n }\n i--; if ( i < 0 ) i = 9;\n } while ( i != RBI );\n }\n\n if ( UseRBI < 0 ) return -1;\n if ( bitRead(RBytes[UseRBI][0],RW_BIT) == WRITE ) { \n return 0; \/\/ Okay Status for a WRITE COMMAND\n } else {\n if ( bitRead(RBytes[UseRBI][0],DA_BIT) == DIGITAL ) { \/\/ Value of the Reply\n return bitRead(RBytes[UseRBI][1],HL_BIT);\n } else {\n return ValueTo8bits(RBytes[UseRBI][2],RBytes[UseRBI][3]);\n }\n }\n}\n\n\/\/-----------------------------------------------------------------------------------------------------\n\/\/ ValueTo8bits() ValueTo7bits()\n\/\/ - Encodes \/ Decodes numeric values into (2)7-bit bytes for the 14-bit 'AV' (Analog Value) Bytes\n\/\/ - This function automatically attaches the END_BIT at the appropriate location.\n\/\/-----------------------------------------------------------------------------------------------------\nint PeerIOSerialControl::ValueTo8bits(byte lByte, byte hByte) {\n bitClear(hByte,7); \/\/ Clear any End-Of-Packet flag\n bitWrite(lByte,7,bitRead(hByte,0)); \/\/ Transfer hByte<0> onto lByte<7>\n return (hByte<<7) | lByte; \/\/ Left shift 7 overwrites lByte<7>\n}\nint PeerIOSerialControl::ValueTo7bits(int From8BitValue) {\n byte lByte = lowByte(From8BitValue);\n byte hByte = highByte(From8BitValue);\n if ( From8BitValue > 0x3FFF ) return -1; \/\/ Value is too big for a 14-bit Value\n hByte = hByte << 1; \/\/ Make Room on hByte for bit-7 of lByte\n bitWrite(hByte,0,bitRead(lByte,7)); \/\/ Transfer lByte<7> onto hByte<0>\n if ( From8BitValue > 0x7F ) { \n bitSet(hByte,7); \/\/ Value > 7-bits so Set 'END_BIT' @ hByte\n bitClear(lByte,7);\n } else {\n bitSet(lByte,7); \/\/ Value <= 7-bits so Set 'END_BIT' @ lByte\n bitClear(hByte,7);\n }\n return (hByte<<8) | lByte; \n}\n\n\/\/-----------------------------------------------------------------------------------------------------\n\/\/ DecodePacket()\n\/\/-----------------------------------------------------------------------------------------------------\nvoid PeerIOSerialControl::DecodePacket(long lPacket) {\n byte Byte0; byte Byte1; byte Byte2; byte Byte3;\n if ( lPacket = -1 ) { \n Byte0=Bytes[0];Byte1=Bytes[1];Byte2=Bytes[2];Byte3=Bytes[3];\n } else {\n Byte0 = ( lPacket >> 24 ) & 0xFF;\n Byte1 = ( lPacket >> 16 ) & 0xFF;\n Byte2 = ( lPacket >> 8 ) & 0xFF;\n Byte3 = lPacket & 0xFF; \n }\n DB((\"D\/A Flag = \"));if ( bitRead(Byte0,DA_BIT) ) { DBL((\"DIGITAL\")); } else { DBL((\"ANALOG\")); }\n DB((\"R\/W Flag = \"));if ( bitRead(Byte0,RW_BIT) ) { DBL((\"READ\")); } else { DBL((\"WRITE\")); }\n DB((\"S\/R Flag = \"));if ( bitRead(Byte0,REPLY_BIT) ) { DBL((\"REPLY\")); } else { DBL((\"SEND\")); }\n DB((\"Arduino ID = \"));DBL(( (Byte0 & ID_MASK) ));\n if ( bitRead(Byte0,DA_BIT) ) { \n DB((\"H\/L Flag = \"));\n if ( bitRead(Byte0,HL_BIT) ) { DBL((\"HIGH\")); } else { DBL((\"LOW\")); }\n DB((\"PIN = \"));DBL(( (Byte1 & DPIN_MASK) ));\n } else {\n DB((\"Value = \"));DBL(( ValueTo8bits(Byte2, Byte3) ));\n DB((\"PIN = \"));DBL(( (Byte1 & APIN_MASK) ));\n }\n}\n \n\/\/-----------------------------------------------------------------------------------------------------\n\/\/ ProcessPacket()\n\/\/-----------------------------------------------------------------------------------------------------\nvoid PeerIOSerialControl::ProcessPacket() {\n DB((\"ProcessPacket( \"));\n DB((Bytes[0],HEX));DBC;DB((Bytes[1],HEX));DBC;DB((Bytes[2],HEX));DBC;DB((Bytes[3],HEX));\n DB((\" ) - \"));\n \n \/\/ REPLY PACKET RECEIVED\n if ( bitRead(Bytes[0],REPLY_BIT) ) {\n DBL((\"Packet Type REPLY\"));\n for ( int i=0;i<4;i++ ) RBytes[RBI][i] = Bytes[i]; \/\/ Put Replies in RBytes Buffer\n#if defined(DEBUG)\n #if DEBUG>0\n DecodePacket();\n #endif\n#endif\n\n\n \/\/ COMMAND PACKET RECEIVED\n } else if ( (Bytes[0] & ID_MASK) == ArduinoID ) {\n \n DBL((\"Packet Type SEND\"));\n \/\/ DIGITAL\n if ( bitRead(Bytes[0],DA_BIT) == DIGITAL ) {\n int pin = Bytes[1] & DPIN_MASK;\n if ( bitRead(Bytes[0],RW_BIT) == READ ) {\n DB((\"digitalRead(\"));DB((pin));DBL((\")\"));\n bitWrite(Bytes[1],HL_BIT,digitalRead(pin));\n } else {\n DB((\"digitalWrite(\"));DB((pin));DB((\",\"));DB((bitRead(Bytes[1],HL_BIT)));DBL((\")\"));\n digitalWrite(pin,bitRead(Bytes[1],HL_BIT));\n }\n bitSet(Bytes[1],END_BIT);\n\n \/\/ ANALOG\n } else {\n int pin = Bytes[1] & APIN_MASK;\n int val = 0;\n if ( bitRead(Bytes[0],RW_BIT) == READ ) {\n DB((\"analogRead(\"));DB((pin));DBL((\")\"));\n if ( pin > 63 && pin < 128 ) { \n val = ValueTo7bits(iVirtualPin[pin-64]); \n } else { \n val = ValueTo7bits(analogRead(pin)); \n }\n Bytes[2] = lowByte(val);\n Bytes[3] = highByte(val);\n } else { \n DB((\"analogWrite(\"));DB((pin));DB((\",\"));DB((ValueTo8bits(Bytes[2],Bytes[3])));DBL((\")\"));\n if ( pin > 63 && pin < 128 ) { \n iVirtualPin[pin-64] = ValueTo8bits(Bytes[2],Bytes[3]); \n } else { \n analogWrite(pin,ValueTo8bits(Bytes[2],Bytes[3]));\n }\n }\n }\n \n \/\/ Send out the Reply Packet\n bitSet(Bytes[0],REPLY_BIT); \/\/ Set the Reply Bit\n DB((\"SendBytes( \"));\n COMPort->write(Bytes[0]);\n COMPort->write(Bytes[1]);\n if ( Bytes[2] != 0 ) COMPort->write(Bytes[2]);\n if ( Bytes[3] != 0 ) COMPort->write(Bytes[3]);\n DB((Bytes[0],HEX));DBC;DB((Bytes[1],HEX));DBC;DB((Bytes[2],HEX));DBC;DB((Bytes[3],HEX));DBL((\" )\"));\n } \n\n}\n\n\/\/-----------------------------------------------------------------------------------------------------\n\/\/ Available()\n\/\/-----------------------------------------------------------------------------------------------------\nbool PeerIOSerialControl::Available() {\n \/\/ Receive Bytes\n while(COMPort->available() > 0) {\n Bytes[idx] = COMPort->read();\n if ( Bytes[idx] != -1 ) {\n \/\/DBL((Bytes[idx],HEX));\n if ( bitRead(Bytes[idx],END_BIT) ) {\n DBL((\"-----------------------------------------------------------\"));\n DB((\"Packet Received @ Size: \"));DBL((idx+1));\n bitClear(Bytes[idx],END_BIT); \/\/ Clear the END_BIT\n for(int i=(idx+1);i<4;i++) Bytes[i]=0; \/\/ Clear unused bytes\n idx = 0;\n ProcessPacket();\n return true;\n } else {\n idx++;\n }\n }\n }\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/* IBM_PROLOG_BEGIN_TAG *\/\n\/* This is an automatically generated prolog. *\/\n\/* *\/\n\/* $Source: src\/import\/chips\/p9\/procedures\/hwp\/memory\/lib\/phy\/dp16.H $ *\/\n\/* *\/\n\/* OpenPOWER HostBoot Project *\/\n\/* *\/\n\/* Contributors Listed Below - COPYRIGHT 2015,2019 *\/\n\/* [+] International Business Machines Corp. *\/\n\/* *\/\n\/* *\/\n\/* Licensed under the Apache License, Version 2.0 (the \"License\"); *\/\n\/* you may not use this file except in compliance with the License. *\/\n\/* You may obtain a copy of the License at *\/\n\/* *\/\n\/* http:\/\/www.apache.org\/licenses\/LICENSE-2.0 *\/\n\/* *\/\n\/* Unless required by applicable law or agreed to in writing, software *\/\n\/* distributed under the License is distributed on an \"AS IS\" BASIS, *\/\n\/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or *\/\n\/* implied. See the License for the specific language governing *\/\n\/* permissions and limitations under the License. *\/\n\/* *\/\n\/* IBM_PROLOG_END_TAG *\/\n\n\/\/\/\n\/\/\/ @file dp16.H\n\/\/\/ @brief Subroutines to control the DP16 logic blocks\n\/\/\/\n\/\/ *HWP HWP Owner: Brian Silver <bsilver@us.ibm.com>\n\/\/ *HWP HWP Backup: Andre Marin <aamarin@us.ibm.com>\n\/\/ *HWP Team: Memory\n\/\/ *HWP Level: 2\n\/\/ *HWP Consumed by: FSP:HB\n\n#ifndef _MSS_DP16_H_\n#define _MSS_DP16_H_\n\n#include <fapi2.H>\n#include <vector>\n\nnamespace mss\n{\nnamespace dp16\n{\n\n\/\/\/\n\/\/\/ @brief Configure the DP16 sysclk\n\/\/\/ @tparam T the fapi2 target type\n\/\/\/ @param[in] i_target a target\n\/\/\/ @return FAPI2_RC_SUCCESs iff ok\n\/\/\/\ntemplate< fapi2::TargetType T >\nfapi2::ReturnCode setup_sysclk( const fapi2::Target<T>& i_target );\n\n\/\/\/\n\/\/\/ @brief Configure the DP16 sysclk\n\/\/\/ @param[in] i_target a MCBIST target\n\/\/\/ @return FAPI2_RC_SUCCESs iff ok\n\/\/\/\ntemplate<>\nfapi2::ReturnCode setup_sysclk( const fapi2::Target<fapi2::TARGET_TYPE_MCBIST>& i_target );\n\n\/\/\/\n\/\/\/ @brief Reset the training delay configureation\n\/\/\/ @tparam T the type of the port\n\/\/\/ @param[in] i_target the port target\n\/\/\/ @param[in] l_rank_pairs vector of rank pairs\n\/\/\/ @return FAPI2_RC_SUCCES iff ok\n\/\/\/\ntemplate< fapi2::TargetType T>\nfapi2::ReturnCode reset_delay_values( const fapi2::Target<T>& i_target,\n const std::vector< uint64_t >& l_rank_pairs );\n\n\/\/\/\n\/\/\/ @brief Reset the training delay configureation\n\/\/\/ @param[in] i_target the port target\n\/\/\/ @param[in] l_rank_pairs vector of rank pairs\n\/\/\/ @return FAPI2_RC_SUCCES iff ok\n\/\/\/\ntemplate<>\nfapi2::ReturnCode reset_delay_values( const fapi2::Target<fapi2::TARGET_TYPE_MCA>& i_target,\n const std::vector< uint64_t >& l_rank_pairs );\n\n\/\/\/\n\/\/\/ @brief Write the read clock enable registers\n\/\/\/ @tparam T the type of the port\n\/\/\/ @param[in] i_target a port target\n\/\/\/ @param[in] l_rank_pairs vector of rank pairs\n\/\/\/ @return FAPI2_RC_SUCCES iff ok\n\/\/\/\ntemplate< fapi2::TargetType T>\nfapi2::ReturnCode read_clock_enable( const fapi2::Target<T>& i_target,\n const std::vector< uint64_t >& l_rank_pairs );\n\n\/\/\/\n\/\/\/ @brief Write the clock enable registers\n\/\/\/ @param[in] i_target a port target\n\/\/\/ @param[in] l_rank_pairs vector of rank pairs\n\/\/\/ @return FAPI2_RC_SUCCES iff ok\n\/\/\/\ntemplate<>\nfapi2::ReturnCode read_clock_enable( const fapi2::Target<fapi2::TARGET_TYPE_MCA>& i_target,\n const std::vector< uint64_t >& l_rank_pairs );\n\n\/\/\/\n\/\/\/ @brief Write the clock enable registers\n\/\/\/ @tparam T the type of the port\n\/\/\/ @param[in] i_target a port target\n\/\/\/ @param[in] l_rank_pairs vector of rank pairs\n\/\/\/ @return FAPI2_RC_SUCCES iff ok\n\/\/\/\ntemplate< fapi2::TargetType T>\nfapi2::ReturnCode write_clock_enable( const fapi2::Target<T>& i_target,\n const std::vector< uint64_t >& l_rank_pairs );\n\n\/\/\/\n\/\/\/ @brief Write the clock enable registers\n\/\/\/ @param[in] i_target a port target\n\/\/\/ @param[in] l_rank_pairs vector of rank pairs\n\/\/\/ @return FAPI2_RC_SUCCES iff ok\n\/\/\/\ntemplate<>\nfapi2::ReturnCode write_clock_enable( const fapi2::Target<fapi2::TARGET_TYPE_MCA>& i_target,\n const std::vector< uint64_t >& l_rank_pairs );\n\n\/\/\/\n\/\/\/ @brief Write the data bit enable registers\n\/\/\/ @tparam T the type of the port\n\/\/\/ @param[in] i_target a port target\n\/\/\/ @return FAPI2_RC_SUCCESs iff ok\n\/\/\/\ntemplate< fapi2::TargetType T>\nfapi2::ReturnCode write_data_bit_enable( const fapi2::Target<T>& i_target );\n\n\/\/\/\n\/\/\/ @brief Write the data bit enable registers\n\/\/\/ @param[in] i_target a port target\n\/\/\/ @return FAPI2_RC_SUCCESs iff ok\n\/\/\/\ntemplate<>\nfapi2::ReturnCode write_data_bit_enable( const fapi2::Target<fapi2::TARGET_TYPE_MCA>& i_target );\n\n\/\/\/\n\/\/\/ @brief Setup the bad-bits masks for a port\n\/\/\/ @tparam T the fapi2::TargetType\n\/\/\/ @param[in] i_target the target (MCA or MBA?)\n\/\/\/ @return FAPI2_RC_SUCCESS if and only if ok\n\/\/\/\ntemplate< fapi2::TargetType T>\ninline fapi2::ReturnCode set_bad_bits(const fapi2::Target<T>& i_target);\n\n\/\/\/\n\/\/\/ @brief Setup the bad-bits masks for a port\n\/\/\/ @tparam T the fapi2::TargetType\n\/\/\/ @param[in] i_target the target (MCA or MBA?)\n\/\/\/ @return FAPI2_RC_SUCCESS if and only if ok\n\/\/\/\ntemplate<>\ninline fapi2::ReturnCode set_bad_bits(const fapi2::Target<fapi2::TARGET_TYPE_MCA>& i_target)\n{\n \/\/ Note: We need to do this ... BRS\n return fapi2::FAPI2_RC_SUCCESS;\n}\n\n}\n}\n\n#endif\n<commit_msg>Add phy control error checking, clean up dp16, apb<commit_after>\/* IBM_PROLOG_BEGIN_TAG *\/\n\/* This is an automatically generated prolog. *\/\n\/* *\/\n\/* $Source: src\/import\/chips\/p9\/procedures\/hwp\/memory\/lib\/phy\/dp16.H $ *\/\n\/* *\/\n\/* OpenPOWER HostBoot Project *\/\n\/* *\/\n\/* Contributors Listed Below - COPYRIGHT 2015,2019 *\/\n\/* [+] International Business Machines Corp. *\/\n\/* *\/\n\/* *\/\n\/* Licensed under the Apache License, Version 2.0 (the \"License\"); *\/\n\/* you may not use this file except in compliance with the License. *\/\n\/* You may obtain a copy of the License at *\/\n\/* *\/\n\/* http:\/\/www.apache.org\/licenses\/LICENSE-2.0 *\/\n\/* *\/\n\/* Unless required by applicable law or agreed to in writing, software *\/\n\/* distributed under the License is distributed on an \"AS IS\" BASIS, *\/\n\/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or *\/\n\/* implied. See the License for the specific language governing *\/\n\/* permissions and limitations under the License. *\/\n\/* *\/\n\/* IBM_PROLOG_END_TAG *\/\n\n\/\/\/\n\/\/\/ @file dp16.H\n\/\/\/ @brief Subroutines to control the DP16 logic blocks\n\/\/\/\n\/\/ *HWP HWP Owner: Brian Silver <bsilver@us.ibm.com>\n\/\/ *HWP HWP Backup: Andre Marin <aamarin@us.ibm.com>\n\/\/ *HWP Team: Memory\n\/\/ *HWP Level: 2\n\/\/ *HWP Consumed by: FSP:HB\n\n#ifndef _MSS_DP16_H_\n#define _MSS_DP16_H_\n\n#include <vector>\n#include <fapi2.H>\n#include <p9_mc_scom_addresses.H>\n#include <p9_mc_scom_addresses_fld.H>\n\n\nnamespace mss\n{\n\n\/\/ I have a dream that the PHY code can be shared among controllers. So, I drive the\n\/\/ engine from a set of traits. This might be folly. Allow me to dream. BRS\n\n\/\/\/\n\/\/\/ @class dp16Traits\n\/\/\/ @brief a collection of traits associated with the PHY DP16 block\n\/\/\/ @tparam T fapi2::TargetType representing the PHY\n\/\/\/\ntemplate< fapi2::TargetType T >\nclass dp16Traits;\n\n\/\/\/\n\/\/\/ @class dp16Traits\n\/\/\/ @brief a collection of traits associated with the Centaur PHY\n\/\/\/\ntemplate<>\nclass dp16Traits<fapi2::TARGET_TYPE_MBA>\n{\n};\n\n\/\/\/\n\/\/\/ @class dp16Traits\n\/\/\/ @brief a collection of traits associated with the Nimbus PHY DP16 block\n\/\/\/\ntemplate<>\nclass dp16Traits<fapi2::TARGET_TYPE_MCA>\n{\n};\n\n\/\/\/\n\/\/\/ @class mss::dp16\n\/\/\/ @brief PHY DP16 Block class\n\/\/\/ @tparam T fapi2 Target Type\n\/\/\/ @tparam TT traits type defaults to dp16Traits<T>\n\/\/\/\ntemplate< fapi2::TargetType T, typename TT = dp16Traits<T> >\nclass dp16\n{\n public:\n\n \/\/\/\n \/\/\/ @brief Configure the DP16 sysclk\n \/\/\/ @tparam K the fapi2 target type\n \/\/\/ @param[in] i_target a target\n \/\/\/ @return FAPI2_RC_SUCCESs iff ok\n \/\/\/\n template< fapi2::TargetType K >\n fapi2::ReturnCode setup_sysclk( const fapi2::Target<K>& i_target );\n\n \/\/\/\n \/\/\/ @brief Reset the training delay configureation\n \/\/\/ @tparam T the type of the port\n \/\/\/ @param[in] i_target the port target\n \/\/\/ @param[in] l_rank_pairs vector of rank pairs\n \/\/\/ @return FAPI2_RC_SUCCES iff ok\n \/\/\/\n fapi2::ReturnCode reset_delay_values( const fapi2::Target<T>& i_target,\n const std::vector< uint64_t >& l_rank_pairs );\n\n \/\/\/\n \/\/\/ @brief Write the read clock enable registers\n \/\/\/ @tparam T the type of the port\n \/\/\/ @param[in] i_target a port target\n \/\/\/ @param[in] l_rank_pairs vector of rank pairs\n \/\/\/ @return FAPI2_RC_SUCCES iff ok\n \/\/\/\n fapi2::ReturnCode read_clock_enable( const fapi2::Target<T>& i_target,\n const std::vector< uint64_t >& l_rank_pairs );\n\n \/\/\/\n \/\/\/ @brief Write the clock enable registers\n \/\/\/ @tparam T the type of the port\n \/\/\/ @param[in] i_target a port target\n \/\/\/ @param[in] l_rank_pairs vector of rank pairs\n \/\/\/ @return FAPI2_RC_SUCCES iff ok\n \/\/\/\n fapi2::ReturnCode write_clock_enable( const fapi2::Target<T>& i_target,\n const std::vector< uint64_t >& l_rank_pairs );\n\n \/\/\/\n \/\/\/ @brief Write the data bit enable registers\n \/\/\/ @tparam T the type of the port\n \/\/\/ @param[in] i_target a port target\n \/\/\/ @return FAPI2_RC_SUCCESs iff ok\n \/\/\/\n fapi2::ReturnCode write_data_bit_enable( const fapi2::Target<T>& i_target );\n\n\n \/\/\/\n \/\/\/ @brief Setup the bad-bits masks for a port\n \/\/\/ @tparam T the fapi2::TargetType\n \/\/\/ @param[in] i_target the target (MCA or MBA?)\n \/\/\/ @return FAPI2_RC_SUCCESS if and only if ok\n \/\/\/\n inline fapi2::ReturnCode set_bad_bits(const fapi2::Target<T>& i_target);\n\n};\n\n\/\/\/\n\/\/\/ @brief Configure the DP16 sysclk\n\/\/\/ @param[in] i_target a MCBIST target\n\/\/\/ @return FAPI2_RC_SUCCESs iff ok\n\/\/\/\ntemplate<>\ntemplate<>\nfapi2::ReturnCode dp16<fapi2::TARGET_TYPE_MCA>::setup_sysclk(\n const fapi2::Target<fapi2::TARGET_TYPE_MCBIST>& i_target );\n\n\/\/\/\n\/\/\/ @brief Reset the training delay configureation\n\/\/\/ @param[in] i_target the port target\n\/\/\/ @param[in] l_rank_pairs vector of rank pairs\n\/\/\/ @return FAPI2_RC_SUCCES iff ok\n\/\/\/\ntemplate<>\nfapi2::ReturnCode dp16<fapi2::TARGET_TYPE_MCA>::reset_delay_values(\n const fapi2::Target<fapi2::TARGET_TYPE_MCA>& i_target,\n const std::vector< uint64_t >& l_rank_pairs );\n\n\/\/\/\n\/\/\/ @brief Write the clock enable registers\n\/\/\/ @param[in] i_target a port target\n\/\/\/ @param[in] l_rank_pairs vector of rank pairs\n\/\/\/ @return FAPI2_RC_SUCCES iff ok\n\/\/\/\ntemplate<>\nfapi2::ReturnCode dp16<fapi2::TARGET_TYPE_MCA>::read_clock_enable(\n const fapi2::Target<fapi2::TARGET_TYPE_MCA>& i_target,\n const std::vector< uint64_t >& l_rank_pairs );\n\n\/\/\/\n\/\/\/ @brief Write the clock enable registers\n\/\/\/ @param[in] i_target a port target\n\/\/\/ @param[in] l_rank_pairs vector of rank pairs\n\/\/\/ @return FAPI2_RC_SUCCES iff ok\n\/\/\/\ntemplate<>\nfapi2::ReturnCode dp16<fapi2::TARGET_TYPE_MCA>::write_clock_enable(\n const fapi2::Target<fapi2::TARGET_TYPE_MCA>& i_target,\n const std::vector< uint64_t >& l_rank_pairs );\n\n\/\/\/\n\/\/\/ @brief Write the data bit enable registers\n\/\/\/ @param[in] i_target a port target\n\/\/\/ @return FAPI2_RC_SUCCESs iff ok\n\/\/\/\ntemplate<>\nfapi2::ReturnCode dp16<fapi2::TARGET_TYPE_MCA>::write_data_bit_enable(\n const fapi2::Target<fapi2::TARGET_TYPE_MCA>& i_target );\n\n\/\/\/\n\/\/\/ @brief Setup the bad-bits masks for a port\n\/\/\/ @tparam T the fapi2::TargetType\n\/\/\/ @param[in] i_target the target (MCA or MBA?)\n\/\/\/ @return FAPI2_RC_SUCCESS if and only if ok\n\/\/\/\ntemplate<>\ninline fapi2::ReturnCode dp16<fapi2::TARGET_TYPE_MCA>::set_bad_bits(\n const fapi2::Target<fapi2::TARGET_TYPE_MCA>& i_target)\n{\n \/\/ Note: We need to do this ... BRS\n return fapi2::FAPI2_RC_SUCCESS;\n}\n\n\n}\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ This file is part of the Marble Desktop Globe.\n\/\/\n\/\/ This program is free software licensed under the GNU LGPL. You can\n\/\/ find a copy of this license in LICENSE.txt in the top directory of\n\/\/ the source code.\n\/\/\n\/\/ Copyright 2006-2007 Torsten Rahn <tackat@kde.org>\"\n\/\/ Copyright 2007 Inge Wallin <ingwa@kde.org>\"\n\/\/\n\n#include \"PlacemarkManager.h\"\n\n#include <QtCore\/QBuffer>\n#include <QtCore\/QByteArray>\n#include <QtCore\/QDataStream>\n#include <QtCore\/QDateTime>\n#include <QtCore\/QDebug>\n#include <QtCore\/QDir>\n#include <QtCore\/QFileInfo>\n#include <QtXml\/QXmlInputSource>\n#include <QtXml\/QXmlSimpleReader>\n\n#include \"KmlFileViewItem.h\"\n#include \"FileViewModel.h\"\n#include \"MarbleDirs.h\"\n#include \"MarblePlacemarkModel.h\"\n#include \"MarbleGeometryModel.h\"\n#include \"PlacemarkContainer.h\"\n#include \"PlacemarkLoader.h\"\n\n#include \"GeoDataDocument.h\"\n#include \"GeoDataParser.h\"\n#include \"GeoDataPlacemark.h\"\n\n\nusing namespace Marble;\n\nnamespace Marble {\nclass PlacemarkManagerPrivate\n{\n public:\n PlacemarkManagerPrivate( QObject* parent )\n : m_model( 0 )\n , m_geomodel( new MarbleGeometryModel() )\n , m_fileViewModel( new FileViewModel(parent ) )\n , m_finalized( true )\n , m_target( QString() )\n {\n };\n\n MarblePlacemarkModel* m_model;\n MarbleGeometryModel* m_geomodel;\n QList<PlacemarkLoader*> m_loaderList;\n FileViewModel* m_fileViewModel;\n QStringList m_pathList;\n\n bool m_finalized;\n QString m_target;\n};\n}\n\nPlacemarkManager::PlacemarkManager( QObject *parent )\n : QObject( parent )\n , d( new PlacemarkManagerPrivate( parent ) )\n{\n \n}\n\n\nPlacemarkManager::~PlacemarkManager()\n{\n foreach( PlacemarkLoader *loader, d->m_loaderList ) {\n if ( loader ) {\n loader->wait();\n }\n }\n\n delete d->m_model;\n delete d->m_fileViewModel;\n delete d;\n \/* do not delete the d->m_geomodel here\n * it is not this models property\n *\/\n}\n\nMarblePlacemarkModel* PlacemarkManager::model() const\n{\n return d->m_model;\n}\n\nFileViewModel* PlacemarkManager::fileViewModel() const\n{\n return d->m_fileViewModel;\n}\n\nMarbleGeometryModel* PlacemarkManager::geomodel() const\n{\n return d->m_geomodel;\n}\n\nvoid PlacemarkManager::setGeoModel( MarbleGeometryModel * model )\n{\n d->m_geomodel = model;\n}\n\nvoid PlacemarkManager::setPlacemarkModel( MarblePlacemarkModel *model )\n{\n d->m_model = model;\n}\n\nvoid PlacemarkManager::clearPlacemarks()\n{\n d->m_model->clearPlacemarks();\n}\n\nQStringList PlacemarkManager::containers() const\n{\n return fileViewModel()->containers() + d->m_pathList;\n}\n\nQString PlacemarkManager::toRegularName( QString name )\n{\n return name.remove(\".kml\").remove(\".cache\");\n}\n\nvoid PlacemarkManager::addPlacemarkFile( const QString& filepath, bool finalized )\n{\n if( ! containers().contains( toRegularName( filepath ) ) ) {\n qDebug() << \"adding container:\" << toRegularName( filepath ) << finalized;\n PlacemarkLoader* loader = new PlacemarkLoader( this, filepath, finalized );\n connect ( loader, SIGNAL( placemarksLoaded( PlacemarkLoader*, PlacemarkContainer * ) ), \n this, SLOT( loadPlacemarkContainer( PlacemarkLoader*, PlacemarkContainer * ) ) );\n connect ( loader, SIGNAL( placemarkLoaderFailed( PlacemarkLoader* ) ), \n this, SLOT( cleanupLoader( PlacemarkLoader* ) ) );\n connect ( loader, SIGNAL( newGeoDataDocumentAdded( GeoDataDocument* ) ), \n this, SLOT( addGeoDataDocument( GeoDataDocument* ) ) );\n d->m_loaderList.append( loader );\n d->m_pathList.append( toRegularName( filepath ) );\n loader->start();\n }\n}\n\nvoid PlacemarkManager::addGeoDataDocument( GeoDataDocument* document )\n{\n AbstractFileViewItem* item = new KmlFileViewItem( *this, *document );\n\n d->m_fileViewModel->append( item );\n\n \/\/ now get the document that will be preserved throughout the life time\n GeoDataDocument* doc = dynamic_cast<KmlFileViewItem*>(item)->document();\n \/\/ remove the hashes in front of the styles.\n QVector<GeoDataFeature>::Iterator end = doc->end();\n QVector<GeoDataFeature>::Iterator itr = doc->begin();\n for ( ; itr != end; ++itr ) {\n \/\/ use *itr (or itr.value()) here\n QString styleUrl = itr->styleUrl().remove('#');\n itr->setStyle( &doc->style( styleUrl ) );\n }\n\n \/\/ do not set this file if it only contains points\n if( doc->isVisible() )\n d->m_geomodel->setGeoDataRoot( doc );\n emit geoDataDocumentAdded( *doc );\n}\n\nvoid PlacemarkManager::addPlacemarkData( const QString& data, const QString& key )\n{\n loadKmlFromData( data, key, false );\n}\n\nvoid PlacemarkManager::removePlacemarkKey( const QString& key )\n{\n QString nkey = key;\n qDebug() << \"trying to remove file:\" << key;\n for( int i = 0; i < d->m_fileViewModel->rowCount(); ++i )\n {\n if( toRegularName( nkey ) == toRegularName( d->m_fileViewModel->data(d->m_fileViewModel->index(i, 0)).toString() ) ) {\n d->m_fileViewModel->remove(d->m_fileViewModel->index(i, 0));\n break;\n }\n };\n}\n\nvoid PlacemarkManager::cleanupLoader( PlacemarkLoader* loader )\n{\n d->m_loaderList.removeAll( loader );\n if ( loader->isFinished() ) {\n d->m_pathList.removeAll( loader->path() );\n delete loader;\n }\n}\n\nvoid PlacemarkManager::loadPlacemarkContainer( PlacemarkLoader* loader, PlacemarkContainer * container )\n{\n qDebug() << \"Containername:\" << container->name() << \"to be finalized:\" << (d->m_loaderList.size() == 1) << d->m_loaderList.size();\n d->m_loaderList.removeAll( loader );\n if ( container )\n { \n d->m_model->addPlacemarks( *container, false, d->m_finalized && d->m_loaderList.isEmpty() );\n }\n\n if( d->m_loaderList.isEmpty() ) {\n emit finalize();\n }\n\n if ( loader->isFinished() ) {\n d->m_pathList.removeAll( loader->path() );\n delete loader;\n }\n}\n\nvoid PlacemarkManager::loadKml( const QString& filename, bool clearPrevious )\n{\n Q_UNUSED( clearPrevious )\n\n addPlacemarkFile( filename, true );\n}\n\nvoid PlacemarkManager::loadKmlFromData( const QString& data, const QString& key, bool finalize )\n{\n Q_UNUSED( finalize )\n\n Q_ASSERT( d->m_model != 0 && \"You have called loadKmlFromData before creating a model!\" );\n\n PlacemarkContainer container;\n\n d->m_finalized = true;\n qDebug() << \"adding container:\" << key;\n PlacemarkLoader* loader = new PlacemarkLoader( this, data, key );\n connect ( loader, SIGNAL( placemarksLoaded( PlacemarkLoader*, PlacemarkContainer * ) ), \n this, SLOT( loadPlacemarkContainer( PlacemarkLoader*, PlacemarkContainer * ) ) );\n connect ( loader, SIGNAL( placemarkLoaderFailed( PlacemarkLoader* ) ), \n this, SLOT( cleanupLoader( PlacemarkLoader* ) ) );\n connect ( loader, SIGNAL( newGeoDataDocumentAdded( GeoDataDocument* ) ), \n this, SLOT( addGeoDataDocument( GeoDataDocument* ) ) );\n d->m_loaderList.append( loader );\n loader->start();\n}\n\n#include \"PlacemarkManager.moc\"\n<commit_msg>Marble PlacemarkManager didn't delete it's default MarbleGeometryModel, because it doesn't take ownership of it. Now the MarbleGeometryModel is initialized with 0 to prevent this memory leak. Thanks to mjansen.<commit_after>\/\/\n\/\/ This file is part of the Marble Desktop Globe.\n\/\/\n\/\/ This program is free software licensed under the GNU LGPL. You can\n\/\/ find a copy of this license in LICENSE.txt in the top directory of\n\/\/ the source code.\n\/\/\n\/\/ Copyright 2006-2007 Torsten Rahn <tackat@kde.org>\"\n\/\/ Copyright 2007 Inge Wallin <ingwa@kde.org>\"\n\/\/\n\n#include \"PlacemarkManager.h\"\n\n#include <QtCore\/QBuffer>\n#include <QtCore\/QByteArray>\n#include <QtCore\/QDataStream>\n#include <QtCore\/QDateTime>\n#include <QtCore\/QDebug>\n#include <QtCore\/QDir>\n#include <QtCore\/QFileInfo>\n#include <QtXml\/QXmlInputSource>\n#include <QtXml\/QXmlSimpleReader>\n\n#include \"KmlFileViewItem.h\"\n#include \"FileViewModel.h\"\n#include \"MarbleDirs.h\"\n#include \"MarblePlacemarkModel.h\"\n#include \"MarbleGeometryModel.h\"\n#include \"PlacemarkContainer.h\"\n#include \"PlacemarkLoader.h\"\n\n#include \"GeoDataDocument.h\"\n#include \"GeoDataParser.h\"\n#include \"GeoDataPlacemark.h\"\n\n\nusing namespace Marble;\n\nnamespace Marble {\nclass PlacemarkManagerPrivate\n{\n public:\n PlacemarkManagerPrivate( QObject* parent )\n : m_model( 0 )\n , m_geomodel( 0 )\n , m_fileViewModel( new FileViewModel(parent ) )\n , m_finalized( true )\n , m_target( QString() )\n {\n };\n\n MarblePlacemarkModel* m_model;\n MarbleGeometryModel* m_geomodel;\n QList<PlacemarkLoader*> m_loaderList;\n FileViewModel* m_fileViewModel;\n QStringList m_pathList;\n\n bool m_finalized;\n QString m_target;\n};\n}\n\nPlacemarkManager::PlacemarkManager( QObject *parent )\n : QObject( parent )\n , d( new PlacemarkManagerPrivate( parent ) )\n{\n \n}\n\n\nPlacemarkManager::~PlacemarkManager()\n{\n foreach( PlacemarkLoader *loader, d->m_loaderList ) {\n if ( loader ) {\n loader->wait();\n }\n }\n\n delete d->m_model;\n delete d->m_fileViewModel;\n delete d;\n \/* do not delete the d->m_geomodel here\n * it is not this models property\n *\/\n}\n\nMarblePlacemarkModel* PlacemarkManager::model() const\n{\n return d->m_model;\n}\n\nFileViewModel* PlacemarkManager::fileViewModel() const\n{\n return d->m_fileViewModel;\n}\n\nMarbleGeometryModel* PlacemarkManager::geomodel() const\n{\n return d->m_geomodel;\n}\n\nvoid PlacemarkManager::setGeoModel( MarbleGeometryModel * model )\n{\n d->m_geomodel = model;\n}\n\nvoid PlacemarkManager::setPlacemarkModel( MarblePlacemarkModel *model )\n{\n d->m_model = model;\n}\n\nvoid PlacemarkManager::clearPlacemarks()\n{\n d->m_model->clearPlacemarks();\n}\n\nQStringList PlacemarkManager::containers() const\n{\n return fileViewModel()->containers() + d->m_pathList;\n}\n\nQString PlacemarkManager::toRegularName( QString name )\n{\n return name.remove(\".kml\").remove(\".cache\");\n}\n\nvoid PlacemarkManager::addPlacemarkFile( const QString& filepath, bool finalized )\n{\n if( ! containers().contains( toRegularName( filepath ) ) ) {\n qDebug() << \"adding container:\" << toRegularName( filepath ) << finalized;\n PlacemarkLoader* loader = new PlacemarkLoader( this, filepath, finalized );\n connect ( loader, SIGNAL( placemarksLoaded( PlacemarkLoader*, PlacemarkContainer * ) ), \n this, SLOT( loadPlacemarkContainer( PlacemarkLoader*, PlacemarkContainer * ) ) );\n connect ( loader, SIGNAL( placemarkLoaderFailed( PlacemarkLoader* ) ), \n this, SLOT( cleanupLoader( PlacemarkLoader* ) ) );\n connect ( loader, SIGNAL( newGeoDataDocumentAdded( GeoDataDocument* ) ), \n this, SLOT( addGeoDataDocument( GeoDataDocument* ) ) );\n d->m_loaderList.append( loader );\n d->m_pathList.append( toRegularName( filepath ) );\n loader->start();\n }\n}\n\nvoid PlacemarkManager::addGeoDataDocument( GeoDataDocument* document )\n{\n AbstractFileViewItem* item = new KmlFileViewItem( *this, *document );\n\n d->m_fileViewModel->append( item );\n\n \/\/ now get the document that will be preserved throughout the life time\n GeoDataDocument* doc = dynamic_cast<KmlFileViewItem*>(item)->document();\n \/\/ remove the hashes in front of the styles.\n QVector<GeoDataFeature>::Iterator end = doc->end();\n QVector<GeoDataFeature>::Iterator itr = doc->begin();\n for ( ; itr != end; ++itr ) {\n \/\/ use *itr (or itr.value()) here\n QString styleUrl = itr->styleUrl().remove('#');\n itr->setStyle( &doc->style( styleUrl ) );\n }\n\n \/\/ do not set this file if it only contains points\n if( doc->isVisible() && d->m_geomodel )\n d->m_geomodel->setGeoDataRoot( doc );\n emit geoDataDocumentAdded( *doc );\n}\n\nvoid PlacemarkManager::addPlacemarkData( const QString& data, const QString& key )\n{\n loadKmlFromData( data, key, false );\n}\n\nvoid PlacemarkManager::removePlacemarkKey( const QString& key )\n{\n QString nkey = key;\n qDebug() << \"trying to remove file:\" << key;\n for( int i = 0; i < d->m_fileViewModel->rowCount(); ++i )\n {\n if( toRegularName( nkey ) == toRegularName( d->m_fileViewModel->data(d->m_fileViewModel->index(i, 0)).toString() ) ) {\n d->m_fileViewModel->remove(d->m_fileViewModel->index(i, 0));\n break;\n }\n };\n}\n\nvoid PlacemarkManager::cleanupLoader( PlacemarkLoader* loader )\n{\n d->m_loaderList.removeAll( loader );\n if ( loader->isFinished() ) {\n d->m_pathList.removeAll( loader->path() );\n delete loader;\n }\n}\n\nvoid PlacemarkManager::loadPlacemarkContainer( PlacemarkLoader* loader, PlacemarkContainer * container )\n{\n qDebug() << \"Containername:\" << container->name() << \"to be finalized:\" << (d->m_loaderList.size() == 1) << d->m_loaderList.size();\n d->m_loaderList.removeAll( loader );\n if ( container )\n { \n d->m_model->addPlacemarks( *container, false, d->m_finalized && d->m_loaderList.isEmpty() );\n }\n\n if( d->m_loaderList.isEmpty() ) {\n emit finalize();\n }\n\n if ( loader->isFinished() ) {\n d->m_pathList.removeAll( loader->path() );\n delete loader;\n }\n}\n\nvoid PlacemarkManager::loadKml( const QString& filename, bool clearPrevious )\n{\n Q_UNUSED( clearPrevious )\n\n addPlacemarkFile( filename, true );\n}\n\nvoid PlacemarkManager::loadKmlFromData( const QString& data, const QString& key, bool finalize )\n{\n Q_UNUSED( finalize )\n\n Q_ASSERT( d->m_model != 0 && \"You have called loadKmlFromData before creating a model!\" );\n\n PlacemarkContainer container;\n\n d->m_finalized = true;\n qDebug() << \"adding container:\" << key;\n PlacemarkLoader* loader = new PlacemarkLoader( this, data, key );\n connect ( loader, SIGNAL( placemarksLoaded( PlacemarkLoader*, PlacemarkContainer * ) ), \n this, SLOT( loadPlacemarkContainer( PlacemarkLoader*, PlacemarkContainer * ) ) );\n connect ( loader, SIGNAL( placemarkLoaderFailed( PlacemarkLoader* ) ), \n this, SLOT( cleanupLoader( PlacemarkLoader* ) ) );\n connect ( loader, SIGNAL( newGeoDataDocumentAdded( GeoDataDocument* ) ), \n this, SLOT( addGeoDataDocument( GeoDataDocument* ) ) );\n d->m_loaderList.append( loader );\n loader->start();\n}\n\n#include \"PlacemarkManager.moc\"\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Debug.cpp\n * OpenLieroX\n *\n * Created by Albert Zeyer on 01.01.09.\n * code under LGPL\n *\n *\/\n\n#include \"Debug.h\"\n#include \"StringUtils.h\"\n\n\n#ifdef WIN32\n\nvoid RaiseDebugger() {\n#ifdef DEBUG\n\t\/\/ TODO: what does that do if not run in a debugger?\n\t\/\/ If it just does nothing then, remove the surrounding #ifdef DEBUG\n\t\/\/ I read about a Win32's IsDebuggerPresent() function, perhaps you should use that one here.\n\t__asm { int 3 };\n#endif\n}\n\n#else\n\n#if defined(__APPLE__)\n\n#include <cassert>\n#include <stdbool.h>\n#include <sys\/types.h>\n#include <unistd.h>\n#include <sys\/sysctl.h>\n\n\/\/ Based on Apple's recommended method as described in\n\/\/ http:\/\/developer.apple.com\/qa\/qa2004\/qa1361.html\nstatic bool AmIBeingDebugged()\n \/\/ Returns true if the current process is being debugged (either\n \/\/ running under the debugger or has a debugger attached post facto).\n{\n\t\/\/ Initialize mib, which tells sysctl what info we want. In this case,\n\t\/\/ we're looking for information about a specific process ID.\n\tint mib[] =\n\t{\n\t\tCTL_KERN,\n\t\tKERN_PROC,\n\t\tKERN_PROC_PID,\n\t\tgetpid()\n\t};\n\t\n\t\/\/ Caution: struct kinfo_proc is marked __APPLE_API_UNSTABLE. The source and\n\t\/\/ binary interfaces may change.\n\tstruct kinfo_proc info;\n\tsize_t info_size = sizeof ( info );\n\t\n\tint sysctl_result = sysctl ( mib, arraysize ( mib ), &info, &info_size, NULL, 0 );\n\tDCHECK ( sysctl_result == 0 );\n\tif ( sysctl_result != 0 )\n\t\treturn false;\n\t\n\t\/\/ This process is being debugged if the P_TRACED flag is set.\n\treturn ( info.kp_proc.p_flag & P_TRACED ) != 0;\n}\n\n#else\n\n#include <sys\/types.h>\n#include <sys\/stat.h>\n#include <fcntl.h>\n#include <cstring>\n\nstatic bool AmIBeingDebugged() {\n\t\/\/ We can look in \/proc\/self\/status for TracerPid. We are likely used in crash\n\t\/\/ handling, so we are careful not to use the heap or have side effects.\n\tint status_fd = open(\"\/proc\/self\/status\", O_RDONLY);\n\tif (status_fd == -1)\n\t\treturn false;\n\n\t\/\/ We assume our line will be in the first 1024 characters and that we can\n\t\/\/ read this much all at once. In practice this will generally be true.\n\t\/\/ This simplifies and speeds up things considerably.\n\tchar buf[1024];\n\n\tssize_t num_read = read(status_fd, buf, sizeof(buf));\n\tfix_markend(buf);\n\tclose(status_fd);\n\tif (num_read <= 0) return false;\n\n\tconst char* searchStr = \"TracerPid:\\t\";\n\tconst char* f = strstr(buf, searchStr);\n\tif(f == NULL) return false;\n\t\n\t\/\/ Our pid is 0 without a debugger, assume this for any pid starting with 0.\n\tf += strlen(searchStr);\n\treturn f < &buf[num_read] && *f != '0';\n}\n\n#endif \/\/ OSX\/LINUX\n\n#include <signal.h>\n\nvoid RaiseDebugger() {\n\tif(AmIBeingDebugged()) {\n\t\traise(SIGABRT);\n\t}\n}\n\n#endif\n\n\n#ifdef WIN32\nvoid OlxWriteCoreDump(const char* file_postfix) {}\n\n#else\n\n#ifdef GCOREDUMPER\n#include <google\/coredumper.h>\n#endif\n#include <unistd.h>\n#include <sys\/types.h>\n#include <sys\/wait.h>\n#include <cstring>\n#include <cstdio>\n\n#ifndef GCOREDUMPER\nstatic void GdbWriteCoreDump(const char* fname) {\n\t\/\/ WARNING: this is terribly slow like this\n\tchar gdbparam[1000];\n\tsprintf(gdbparam,\n\t\t\t\"attach %i \\n\"\n\t\t\t\"gcore %s \\n\"\n\t\t\t\"detach \\n\"\n\t\t\t\"quit \\n\",\n\t\t\tgetpid(), fname);\n\tFILE* p = popen(\"gdb -q\", \"w\");\n\tif(p) {\n\t\tfprintf(p, \"%s\", gdbparam);\n\t\tfflush(p);\n\t\tint status = 0; wait(&status);\n\t\tpclose(p);\n\t}\n}\n#endif\n\nvoid OlxWriteCoreDump(const char* file_postfix) {\n\tchar corefile[PATH_MAX + 100];\n\tif(getcwd(corefile, PATH_MAX) == NULL) strcpy(corefile, \"\");\n\tstrcat(corefile, \"\/core.OpenLieroX\");\n\tif(file_postfix) { strcat(corefile, \".\"); strcat(corefile, file_postfix); }\n\tprintf(\"writing coredump to %s\\n\", corefile);\n\t\n\tprintf(\"dumping core ... \"); fflush(0);\n#ifdef GCOREDUMPER\n\tWriteCoreDump(corefile);\n#else\n\tGdbWriteCoreDump(corefile);\n#endif\n\tprintf(\"ready\\n\");\n}\n\n#endif\n\n#if (defined(__GLIBCXX__) || defined(__GLIBC__) || !defined(WIN32)) && !defined(__MINGW32_VERSION)\n\n#include <execinfo.h>\n#include <stdio.h>\n#include <stdlib.h>\n\nvoid DumpCallstackPrintf(void* callpnt) {\n\tvoid *callstack[128];\n\tint framesC = backtrace(callstack, sizeof(callstack));\n\tprintf(\"backtrace() returned %d addresses\\n\", framesC);\n\tif(callpnt != NULL && framesC > 3) callstack[3] = callpnt; \/\/ expected to be called from signal handler\n\tchar** strs = backtrace_symbols(callstack, framesC);\n\tfor(int i = 0; i < framesC; ++i) {\n\t\tif(strs[i])\n\t\t\tprintf(\"%s\\n\", strs[i]);\n\t\telse\n\t\t\tbreak;\n\t}\n\tfree(strs);\n}\n\nvoid DumpCallstack(void (*PrintOutFct) (const std::string&)) {\n\tvoid *callstack[128];\n\tint framesC = backtrace(callstack, sizeof(callstack));\n\t(*PrintOutFct) (\"DumpCallstack: \" + itoa(framesC) + \" addresses:\");\n\tchar** strs = backtrace_symbols(callstack, framesC);\n\tfor(int i = 0; i < framesC; ++i) {\n\t\tif(strs[i])\n\t\t\t(*PrintOutFct) (std::string(\" \") + strs[i] + \"\\n\");\n\t\telse\n\t\t\tbreak;\n\t}\n\tfree(strs);\n}\n\n#else\n\n#include \"StackWalker.h\" \/\/ Call Luke Stackwalker for help\n\ntypedef void (*PrintOutFct) (const std::string&);\n\n\/\/ Override the default stackwalker with our own print functions\nclass PrintStackWalker : public StackWalker {\nprivate:\n\tPrintOutFct m_print;\n\npublic:\n\tPrintStackWalker(PrintOutFct fct = NULL) : StackWalker(RetrieveVerbose) { m_print = fct; }\n\tvoid OnLoadModule(LPCSTR img, LPCSTR mod, DWORD64 baseAddr, DWORD size, DWORD result, LPCSTR symType, LPCSTR pdbName, ULONGLONG fileVersion)\n\t{\n\n\t}\n\n\tvoid OnOutput(LPCSTR szText) \n\t{\n\t\tif (m_print == NULL)\n\t\t\tprintf(szText);\n\t\telse\n\t\t\tm_print(std::string(szText));\n\t\tStackWalker::OnOutput(szText);\n\t}\n};\n\nvoid DumpCallstackPrintf(void* callpnt) \n{\n\tPrintStackWalker sw;\n\tsw.ShowCallstack();\n\t\n}\nvoid DumpCallstack(void (*LineOutFct) (const std::string&)) \n{ \n\tPrintStackWalker sw(LineOutFct);\n\tsw.ShowCallstack();\n}\n\n#endif\n\nLogger notes(0,2,1000, \"n: \");\nLogger hints(0,1,100, \"H: \");\nLogger warnings(0,0,10, \"W: \");\nLogger errors(-1,-1,1, \"E: \");\n\n#include <iostream>\n#include <sstream>\n#include \"ThreadPool.h\"\n#include \"Options.h\"\n#include \"console.h\"\n#include \"StringUtils.h\"\n\nstatic SDL_mutex* globalCoutMutex = NULL;\n\nLogger::Logger(int o, int ingame, int callst, const std::string& p)\n: minCoutVerb(o), minIngameConVerb(ingame), minCallstackVerb(callst), prefix(p), lastWasNewline(true), mutex(NULL) {\n\tmutex = SDL_CreateMutex();\n\tif(!globalCoutMutex)\n\t\tglobalCoutMutex = SDL_CreateMutex();\n}\n\nLogger::~Logger() {\n\tSDL_DestroyMutex(mutex); mutex = NULL;\n\tif(globalCoutMutex) {\n\t\tSDL_DestroyMutex(globalCoutMutex);\n\t\tglobalCoutMutex = NULL;\n\t}\n}\n\nvoid Logger::lock() {\n\tSDL_mutexP(mutex);\n}\n\nvoid Logger::unlock() {\n\tSDL_mutexV(mutex);\n}\n\nstatic void CoutPrint(const std::string& str) {\n\t\/\/ TODO: We have used std::cout here before but it doesn't seem to work after a while for some reason.\n\t\/\/ TODO: c_str() is slow and not really needed here.\n\tprintf(\"%s\", str.c_str());\n}\n\ntemplate<int col> void ConPrint(const std::string& str) {\n\t\/\/ TODO: Con_AddText adds a line but we only want to add str\n\tstd::string buf = str;\n\tif(buf.size() > 0 && buf[buf.size()-1] == '\\n') buf.erase(buf.size()-1);\n\tCon_AddText(col, buf, false);\n}\n\n\/\/ true if last was newline\nstatic bool logger_output(Logger& log, const std::string& buf) {\n\tbool ret = true;\n\tif(!tLXOptions || tLXOptions->iVerbosity >= log.minCoutVerb) {\n\t\tSDL_mutexP(globalCoutMutex);\n\t\tret = PrettyPrint(log.prefix, buf, CoutPrint, log.lastWasNewline);\n\t\t\/\/std::cout.flush();\n\t\tSDL_mutexV(globalCoutMutex);\n\t}\n\tif(tLXOptions && tLXOptions->iVerbosity >= log.minCallstackVerb) {\n\t\tDumpCallstackPrintf();\n\t}\n\tif(tLXOptions && Con_IsInited() && tLXOptions->iVerbosity >= log.minIngameConVerb) {\n\t\t\/\/ the check is a bit hacky (see Con_AddText) but I really dont want to overcomplicate this\n\t\tif(!strStartsWith(buf, \"Ingame console: \")) {\n\t\t\t\/\/ we are not safing explicitly a color in the Logger, thus we try to assume a good color from the verbosity level\n\t\t\tif(log.minIngameConVerb < 0)\n\t\t\t\tret = PrettyPrint(log.prefix, buf, ConPrint<CNC_ERROR>, log.lastWasNewline);\n\t\t\telse if(log.minIngameConVerb == 0)\n\t\t\t\tret = PrettyPrint(log.prefix, buf, ConPrint<CNC_WARNING>, log.lastWasNewline);\n\t\t\telse if(log.minIngameConVerb == 1)\n\t\t\t\tret = PrettyPrint(log.prefix, buf, ConPrint<CNC_NOTIFY>, log.lastWasNewline);\n\t\t\telse if(log.minIngameConVerb < 5)\n\t\t\t\tret = PrettyPrint(log.prefix, buf, ConPrint<CNC_NORMAL>, log.lastWasNewline);\n\t\t\telse \/\/ >=5\n\t\t\t\tret = PrettyPrint(log.prefix, buf, ConPrint<CNC_DEV>, log.lastWasNewline);\n\t\t}\n\t\tif(tLXOptions->iVerbosity >= log.minCallstackVerb) {\n\t\t\tDumpCallstack(ConPrint<CNC_DEV>);\n\t\t}\n\t}\n\treturn ret;\n}\n\nLogger& Logger::flush() {\n\tlock();\n\tlastWasNewline = logger_output(*this, buffer);\n\tbuffer = \"\";\n\tunlock();\n\treturn *this;\n}\n<commit_msg>small fix<commit_after>\/*\n * Debug.cpp\n * OpenLieroX\n *\n * Created by Albert Zeyer on 01.01.09.\n * code under LGPL\n *\n *\/\n\n#include \"Debug.h\"\n#include \"StringUtils.h\"\n\n\n#ifdef WIN32\n\nvoid RaiseDebugger() {\n#ifdef DEBUG\n\t\/\/ TODO: what does that do if not run in a debugger?\n\t\/\/ If it just does nothing then, remove the surrounding #ifdef DEBUG\n\t\/\/ I read about a Win32's IsDebuggerPresent() function, perhaps you should use that one here.\n\t__asm { int 3 };\n#endif\n}\n\n#else\n\n#if defined(__APPLE__)\n\n#include <cassert>\n#include <stdbool.h>\n#include <sys\/types.h>\n#include <unistd.h>\n#include <sys\/sysctl.h>\n\n\/\/ Based on Apple's recommended method as described in\n\/\/ http:\/\/developer.apple.com\/qa\/qa2004\/qa1361.html\nstatic bool AmIBeingDebugged()\n \/\/ Returns true if the current process is being debugged (either\n \/\/ running under the debugger or has a debugger attached post facto).\n{\n\t\/\/ Initialize mib, which tells sysctl what info we want. In this case,\n\t\/\/ we're looking for information about a specific process ID.\n\tint mib[] =\n\t{\n\t\tCTL_KERN,\n\t\tKERN_PROC,\n\t\tKERN_PROC_PID,\n\t\tgetpid()\n\t};\n\t\n\t\/\/ Caution: struct kinfo_proc is marked __APPLE_API_UNSTABLE. The source and\n\t\/\/ binary interfaces may change.\n\tstruct kinfo_proc info;\n\tsize_t info_size = sizeof ( info );\n\t\n\tint sysctl_result = sysctl ( mib, sizeof(mib) \/ sizeof(*mib), &info, &info_size, NULL, 0 );\n\tif ( sysctl_result != 0 )\n\t\treturn false;\n\t\n\t\/\/ This process is being debugged if the P_TRACED flag is set.\n\treturn ( info.kp_proc.p_flag & P_TRACED ) != 0;\n}\n\n#else\n\n#include <sys\/types.h>\n#include <sys\/stat.h>\n#include <fcntl.h>\n#include <cstring>\n\nstatic bool AmIBeingDebugged() {\n\t\/\/ We can look in \/proc\/self\/status for TracerPid. We are likely used in crash\n\t\/\/ handling, so we are careful not to use the heap or have side effects.\n\tint status_fd = open(\"\/proc\/self\/status\", O_RDONLY);\n\tif (status_fd == -1)\n\t\treturn false;\n\n\t\/\/ We assume our line will be in the first 1024 characters and that we can\n\t\/\/ read this much all at once. In practice this will generally be true.\n\t\/\/ This simplifies and speeds up things considerably.\n\tchar buf[1024];\n\n\tssize_t num_read = read(status_fd, buf, sizeof(buf));\n\tfix_markend(buf);\n\tclose(status_fd);\n\tif (num_read <= 0) return false;\n\n\tconst char* searchStr = \"TracerPid:\\t\";\n\tconst char* f = strstr(buf, searchStr);\n\tif(f == NULL) return false;\n\t\n\t\/\/ Our pid is 0 without a debugger, assume this for any pid starting with 0.\n\tf += strlen(searchStr);\n\treturn f < &buf[num_read] && *f != '0';\n}\n\n#endif \/\/ OSX\/LINUX\n\n#include <signal.h>\n\nvoid RaiseDebugger() {\n\tif(AmIBeingDebugged()) {\n\t\tprintf(\"I am being debugged, raising debugger ...\\n\");\n\t\traise(SIGABRT);\n\t} else\n\t\tprintf(\"I am not being debugged, ignoring debugger raise.\\n\");\n}\n\n#endif\n\n\n#ifdef WIN32\nvoid OlxWriteCoreDump(const char* file_postfix) {}\n\n#else\n\n#ifdef GCOREDUMPER\n#include <google\/coredumper.h>\n#endif\n#include <unistd.h>\n#include <sys\/types.h>\n#include <sys\/wait.h>\n#include <cstring>\n#include <cstdio>\n\n#ifndef GCOREDUMPER\nstatic void GdbWriteCoreDump(const char* fname) {\n\t\/\/ WARNING: this is terribly slow like this\n\tchar gdbparam[1000];\n\tsprintf(gdbparam,\n\t\t\t\"attach %i \\n\"\n\t\t\t\"gcore %s \\n\"\n\t\t\t\"detach \\n\"\n\t\t\t\"quit \\n\",\n\t\t\tgetpid(), fname);\n\tFILE* p = popen(\"gdb -q\", \"w\");\n\tif(p) {\n\t\tfprintf(p, \"%s\", gdbparam);\n\t\tfflush(p);\n\t\tint status = 0; wait(&status);\n\t\tpclose(p);\n\t}\n}\n#endif\n\nvoid OlxWriteCoreDump(const char* file_postfix) {\n\tchar corefile[PATH_MAX + 100];\n\tif(getcwd(corefile, PATH_MAX) == NULL) strcpy(corefile, \"\");\n\tstrcat(corefile, \"\/core.OpenLieroX\");\n\tif(file_postfix) { strcat(corefile, \".\"); strcat(corefile, file_postfix); }\n\tprintf(\"writing coredump to %s\\n\", corefile);\n\t\n\tprintf(\"dumping core ... \"); fflush(0);\n#ifdef GCOREDUMPER\n\tWriteCoreDump(corefile);\n#else\n\tGdbWriteCoreDump(corefile);\n#endif\n\tprintf(\"ready\\n\");\n}\n\n#endif\n\n#if (defined(__GLIBCXX__) || defined(__GLIBC__) || !defined(WIN32)) && !defined(__MINGW32_VERSION)\n\n#include <execinfo.h>\n#include <stdio.h>\n#include <stdlib.h>\n\nvoid DumpCallstackPrintf(void* callpnt) {\n\tvoid *callstack[128];\n\tint framesC = backtrace(callstack, sizeof(callstack));\n\tprintf(\"backtrace() returned %d addresses\\n\", framesC);\n\tif(callpnt != NULL && framesC > 3) callstack[3] = callpnt; \/\/ expected to be called from signal handler\n\tchar** strs = backtrace_symbols(callstack, framesC);\n\tfor(int i = 0; i < framesC; ++i) {\n\t\tif(strs[i])\n\t\t\tprintf(\"%s\\n\", strs[i]);\n\t\telse\n\t\t\tbreak;\n\t}\n\tfree(strs);\n}\n\nvoid DumpCallstack(void (*PrintOutFct) (const std::string&)) {\n\tvoid *callstack[128];\n\tint framesC = backtrace(callstack, sizeof(callstack));\n\t(*PrintOutFct) (\"DumpCallstack: \" + itoa(framesC) + \" addresses:\");\n\tchar** strs = backtrace_symbols(callstack, framesC);\n\tfor(int i = 0; i < framesC; ++i) {\n\t\tif(strs[i])\n\t\t\t(*PrintOutFct) (std::string(\" \") + strs[i] + \"\\n\");\n\t\telse\n\t\t\tbreak;\n\t}\n\tfree(strs);\n}\n\n#else\n\n#include \"StackWalker.h\" \/\/ Call Luke Stackwalker for help\n\ntypedef void (*PrintOutFct) (const std::string&);\n\n\/\/ Override the default stackwalker with our own print functions\nclass PrintStackWalker : public StackWalker {\nprivate:\n\tPrintOutFct m_print;\n\npublic:\n\tPrintStackWalker(PrintOutFct fct = NULL) : StackWalker(RetrieveVerbose) { m_print = fct; }\n\tvoid OnLoadModule(LPCSTR img, LPCSTR mod, DWORD64 baseAddr, DWORD size, DWORD result, LPCSTR symType, LPCSTR pdbName, ULONGLONG fileVersion)\n\t{\n\n\t}\n\n\tvoid OnOutput(LPCSTR szText) \n\t{\n\t\tif (m_print == NULL)\n\t\t\tprintf(szText);\n\t\telse\n\t\t\tm_print(std::string(szText));\n\t\tStackWalker::OnOutput(szText);\n\t}\n};\n\nvoid DumpCallstackPrintf(void* callpnt) \n{\n\tPrintStackWalker sw;\n\tsw.ShowCallstack();\n\t\n}\nvoid DumpCallstack(void (*LineOutFct) (const std::string&)) \n{ \n\tPrintStackWalker sw(LineOutFct);\n\tsw.ShowCallstack();\n}\n\n#endif\n\nLogger notes(0,2,1000, \"n: \");\nLogger hints(0,1,100, \"H: \");\nLogger warnings(0,0,10, \"W: \");\nLogger errors(-1,-1,1, \"E: \");\n\n#include <iostream>\n#include <sstream>\n#include \"ThreadPool.h\"\n#include \"Options.h\"\n#include \"console.h\"\n#include \"StringUtils.h\"\n\nstatic SDL_mutex* globalCoutMutex = NULL;\n\nLogger::Logger(int o, int ingame, int callst, const std::string& p)\n: minCoutVerb(o), minIngameConVerb(ingame), minCallstackVerb(callst), prefix(p), lastWasNewline(true), mutex(NULL) {\n\tmutex = SDL_CreateMutex();\n\tif(!globalCoutMutex)\n\t\tglobalCoutMutex = SDL_CreateMutex();\n}\n\nLogger::~Logger() {\n\tSDL_DestroyMutex(mutex); mutex = NULL;\n\tif(globalCoutMutex) {\n\t\tSDL_DestroyMutex(globalCoutMutex);\n\t\tglobalCoutMutex = NULL;\n\t}\n}\n\nvoid Logger::lock() {\n\tSDL_mutexP(mutex);\n}\n\nvoid Logger::unlock() {\n\tSDL_mutexV(mutex);\n}\n\nstatic void CoutPrint(const std::string& str) {\n\t\/\/ TODO: We have used std::cout here before but it doesn't seem to work after a while for some reason.\n\t\/\/ TODO: c_str() is slow and not really needed here.\n\tprintf(\"%s\", str.c_str());\n}\n\ntemplate<int col> void ConPrint(const std::string& str) {\n\t\/\/ TODO: Con_AddText adds a line but we only want to add str\n\tstd::string buf = str;\n\tif(buf.size() > 0 && buf[buf.size()-1] == '\\n') buf.erase(buf.size()-1);\n\tCon_AddText(col, buf, false);\n}\n\n\/\/ true if last was newline\nstatic bool logger_output(Logger& log, const std::string& buf) {\n\tbool ret = true;\n\tif(!tLXOptions || tLXOptions->iVerbosity >= log.minCoutVerb) {\n\t\tSDL_mutexP(globalCoutMutex);\n\t\tret = PrettyPrint(log.prefix, buf, CoutPrint, log.lastWasNewline);\n\t\t\/\/std::cout.flush();\n\t\tSDL_mutexV(globalCoutMutex);\n\t}\n\tif(tLXOptions && tLXOptions->iVerbosity >= log.minCallstackVerb) {\n\t\tDumpCallstackPrintf();\n\t}\n\tif(tLXOptions && Con_IsInited() && tLXOptions->iVerbosity >= log.minIngameConVerb) {\n\t\t\/\/ the check is a bit hacky (see Con_AddText) but I really dont want to overcomplicate this\n\t\tif(!strStartsWith(buf, \"Ingame console: \")) {\n\t\t\t\/\/ we are not safing explicitly a color in the Logger, thus we try to assume a good color from the verbosity level\n\t\t\tif(log.minIngameConVerb < 0)\n\t\t\t\tret = PrettyPrint(log.prefix, buf, ConPrint<CNC_ERROR>, log.lastWasNewline);\n\t\t\telse if(log.minIngameConVerb == 0)\n\t\t\t\tret = PrettyPrint(log.prefix, buf, ConPrint<CNC_WARNING>, log.lastWasNewline);\n\t\t\telse if(log.minIngameConVerb == 1)\n\t\t\t\tret = PrettyPrint(log.prefix, buf, ConPrint<CNC_NOTIFY>, log.lastWasNewline);\n\t\t\telse if(log.minIngameConVerb < 5)\n\t\t\t\tret = PrettyPrint(log.prefix, buf, ConPrint<CNC_NORMAL>, log.lastWasNewline);\n\t\t\telse \/\/ >=5\n\t\t\t\tret = PrettyPrint(log.prefix, buf, ConPrint<CNC_DEV>, log.lastWasNewline);\n\t\t}\n\t\tif(tLXOptions->iVerbosity >= log.minCallstackVerb) {\n\t\t\tDumpCallstack(ConPrint<CNC_DEV>);\n\t\t}\n\t}\n\treturn ret;\n}\n\nLogger& Logger::flush() {\n\tlock();\n\tlastWasNewline = logger_output(*this, buffer);\n\tbuffer = \"\";\n\tunlock();\n\treturn *this;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Debug.cpp\n * OpenLieroX\n *\n * Created by Albert Zeyer on 01.01.09.\n * code under LGPL\n *\n *\/\n\n#include \"Debug.h\"\n\n#ifdef WIN32\nvoid OlxWriteCoreDump(const char* file_postfix) {}\n\n#else\n\n#ifdef GCOREDUMPER\n#include <google\/coredumper.h>\n#endif\n#include <unistd.h>\n#include <sys\/types.h>\n#include <cstring>\n#include <cstdio>\n\n#ifndef GCOREDUMPER\nstatic void GdbWriteCoreDump(const char* fname) {\n\t\/\/ WARNING: this is terribly slow like this\n\tchar gdbparam[1000];\n\tsprintf(gdbparam,\n\t\t\t\"attach %i \\n\"\n\t\t\t\"gcore %s \\n\"\n\t\t\t\"detach \\n\",\n\t\t\tgetpid(), fname);\n\tFILE* p = popen(\"gdb\", \"w\");\n\tif(p) {\n\t\tfprintf(p, \"%s\", gdbparam);\n\t\tfflush(p);\n\t\tpclose(p);\n\t}\n}\n#endif\n\nvoid OlxWriteCoreDump(const char* file_postfix) {\n\tchar corefile[PATH_MAX + 100];\n\tif(getcwd(corefile, PATH_MAX) == NULL) strcpy(corefile, \"\");\n\tstrcat(corefile, \"\/core.OpenLieroX\");\n\tif(file_postfix) { strcat(corefile, \".\"); strcat(corefile, file_postfix); }\n\tprintf(\"writing coredump to %s\\n\", corefile);\n\t\n\tprintf(\"dumping core ... \"); fflush(0);\n#ifdef GCOREDUMPER\n\tWriteCoreDump(corefile);\n#else\n\tGdbWriteCoreDump(corefile);\n#endif\n\tprintf(\"ready\\n\");\n}\n\n#endif\n\n#if (defined(__GLIBCXX__) || defined(__GLIBC__) || !defined(WIN32)) && !defined(__MINGW32_VERSION)\n\n#include <execinfo.h>\n#include <stdio.h>\n#include <stdlib.h>\n\nvoid DumpCallstackPrintf(void* callpnt) {\n\tvoid *callstack[128];\n\tint framesC = backtrace(callstack, sizeof(callstack));\n\tprintf(\"backtrace() returned %d addresses\\n\", framesC);\n\tif(callpnt != NULL && framesC > 3) callstack[3] = callpnt; \/\/ expected to be called from signal handler\n\tchar** strs = backtrace_symbols(callstack, framesC);\n\tfor(int i = 0; i < framesC; ++i) {\n\t\tif(strs[i])\n\t\t\tprintf(\"%s\\n\", strs[i]);\n\t\telse\n\t\t\tbreak;\n\t}\n\tfree(strs);\n}\n\nvoid DumpCallstack(void (*PrintOutFct) (const std::string&)) {\n\tvoid *callstack[128];\n\tint framesC = backtrace(callstack, sizeof(callstack));\n\t(*PrintOutFct) (\"DumpCallstack: \" + itoa(framesC) + \" addresses:\");\n\tchar** strs = backtrace_symbols(callstack, framesC);\n\tfor(int i = 0; i < framesC; ++i) {\n\t\tif(strs[i])\n\t\t\t(*PrintOutFct) (std::string(\" \") + strs[i] + \"\\n\");\n\t\telse\n\t\t\tbreak;\n\t}\n\tfree(strs);\n}\n\n#else\n\n#include \"StackWalker.h\" \/\/ Call Luke Stackwalker for help\n\ntypedef void (*PrintOutFct) (const std::string&);\n\n\/\/ Override the default stackwalker with our own print functions\nclass PrintStackWalker : public StackWalker {\nprivate:\n\tPrintOutFct m_print;\n\npublic:\n\tPrintStackWalker(PrintOutFct fct = NULL) : StackWalker(RetrieveVerbose) { m_print = fct; }\n\tvoid OnLoadModule(LPCSTR img, LPCSTR mod, DWORD64 baseAddr, DWORD size, DWORD result, LPCSTR symType, LPCSTR pdbName, ULONGLONG fileVersion)\n\t{\n\n\t}\n\n\tvoid OnOutput(LPCSTR szText) \n\t{\n\t\tif (m_print == NULL)\n\t\t\tprintf(szText);\n\t\telse\n\t\t\tm_print(std::string(szText));\n\t\tStackWalker::OnOutput(szText);\n\t}\n};\n\nvoid DumpCallstackPrintf(void* callpnt) \n{\n\tPrintStackWalker sw;\n\tsw.ShowCallstack();\n\t\n}\nvoid DumpCallstack(void (*LineOutFct) (const std::string&)) \n{ \n\tPrintStackWalker sw(LineOutFct);\n\tsw.ShowCallstack();\n}\n\n#endif\n\nLogger notes(0,2,1000, \"n: \");\nLogger hints(0,1,100, \"H: \");\nLogger warnings(0,0,10, \"W: \");\nLogger errors(-1,-1,1, \"E: \");\n\n#include <iostream>\n#include <sstream>\n#include \"ThreadPool.h\"\n#include \"Options.h\"\n#include \"console.h\"\n#include \"StringUtils.h\"\n\nstatic SDL_mutex* globalCoutMutex = NULL;\n\nLogger::Logger(int o, int ingame, int callst, const std::string& p)\n: minCoutVerb(o), minIngameConVerb(ingame), minCallstackVerb(callst), prefix(p), lastWasNewline(true), mutex(NULL) {\n\tmutex = SDL_CreateMutex();\n\tif(!globalCoutMutex)\n\t\tglobalCoutMutex = SDL_CreateMutex();\n}\n\nLogger::~Logger() {\n\tSDL_DestroyMutex(mutex); mutex = NULL;\n\tif(globalCoutMutex) {\n\t\tSDL_DestroyMutex(globalCoutMutex);\n\t\tglobalCoutMutex = NULL;\n\t}\n}\n\nvoid Logger::lock() {\n\tSDL_mutexP(mutex);\n}\n\nvoid Logger::unlock() {\n\tSDL_mutexV(mutex);\n}\n\nstatic void CoutPrint(const std::string& str) {\n\t\/\/ TODO: We have used std::cout here before but it doesn't seem to work after a while for some reason.\n\t\/\/ TODO: c_str() is slow and not really needed here.\n\tprintf(\"%s\", str.c_str());\n}\n\ntemplate<int col> void ConPrint(const std::string& str) {\n\t\/\/ TODO: Con_AddText adds a line but we only want to add str\n\tstd::string buf = str;\n\tif(buf.size() > 0 && buf[buf.size()-1] == '\\n') buf.erase(buf.size()-1);\n\tCon_AddText(col, buf, false);\n}\n\n\/\/ true if last was newline\nstatic bool logger_output(Logger& log, const std::string& buf) {\n\tbool ret = true;\n\tif(!tLXOptions || tLXOptions->iVerbosity >= log.minCoutVerb) {\n\t\tSDL_mutexP(globalCoutMutex);\n\t\tret = PrettyPrint(log.prefix, buf, CoutPrint, log.lastWasNewline);\n\t\t\/\/std::cout.flush();\n\t\tSDL_mutexV(globalCoutMutex);\n\t}\n\tif(tLXOptions && tLXOptions->iVerbosity >= log.minCallstackVerb) {\n\t\tDumpCallstackPrintf();\n\t}\n\tif(tLXOptions && Con_IsInited() && tLXOptions->iVerbosity >= log.minIngameConVerb) {\n\t\t\/\/ the check is a bit hacky (see Con_AddText) but I really dont want to overcomplicate this\n\t\tif(!strStartsWith(buf, \"Ingame console: \")) {\n\t\t\t\/\/ we are not safing explicitly a color in the Logger, thus we try to assume a good color from the verbosity level\n\t\t\tif(log.minIngameConVerb < 0)\n\t\t\t\tret = PrettyPrint(log.prefix, buf, ConPrint<CNC_ERROR>, log.lastWasNewline);\n\t\t\telse if(log.minIngameConVerb == 0)\n\t\t\t\tret = PrettyPrint(log.prefix, buf, ConPrint<CNC_WARNING>, log.lastWasNewline);\n\t\t\telse if(log.minIngameConVerb == 1)\n\t\t\t\tret = PrettyPrint(log.prefix, buf, ConPrint<CNC_NOTIFY>, log.lastWasNewline);\n\t\t\telse if(log.minIngameConVerb < 5)\n\t\t\t\tret = PrettyPrint(log.prefix, buf, ConPrint<CNC_NORMAL>, log.lastWasNewline);\n\t\t\telse \/\/ >=5\n\t\t\t\tret = PrettyPrint(log.prefix, buf, ConPrint<CNC_DEV>, log.lastWasNewline);\n\t\t}\n\t\tif(tLXOptions->iVerbosity >= log.minCallstackVerb) {\n\t\t\tDumpCallstack(ConPrint<CNC_DEV>);\n\t\t}\n\t}\n\treturn ret;\n}\n\nLogger& Logger::flush() {\n\tlock();\n\tlastWasNewline = logger_output(*this, buffer);\n\tbuffer = \"\";\n\tunlock();\n\treturn *this;\n}\n<commit_msg>wait until gdb is ready with coredumping<commit_after>\/*\n * Debug.cpp\n * OpenLieroX\n *\n * Created by Albert Zeyer on 01.01.09.\n * code under LGPL\n *\n *\/\n\n#include \"Debug.h\"\n\n#ifdef WIN32\nvoid OlxWriteCoreDump(const char* file_postfix) {}\n\n#else\n\n#ifdef GCOREDUMPER\n#include <google\/coredumper.h>\n#endif\n#include <unistd.h>\n#include <sys\/types.h>\n#include <sys\/wait.h>\n#include <cstring>\n#include <cstdio>\n\n#ifndef GCOREDUMPER\nstatic void GdbWriteCoreDump(const char* fname) {\n\t\/\/ WARNING: this is terribly slow like this\n\tchar gdbparam[1000];\n\tsprintf(gdbparam,\n\t\t\t\"attach %i \\n\"\n\t\t\t\"gcore %s \\n\"\n\t\t\t\"detach \\n\"\n\t\t\t\"quit \\n\",\n\t\t\tgetpid(), fname);\n\tFILE* p = popen(\"gdb -q\", \"w\");\n\tif(p) {\n\t\tfprintf(p, \"%s\", gdbparam);\n\t\tfflush(p);\n\t\tint status = 0; wait(&status);\n\t\tpclose(p);\n\t}\n}\n#endif\n\nvoid OlxWriteCoreDump(const char* file_postfix) {\n\tchar corefile[PATH_MAX + 100];\n\tif(getcwd(corefile, PATH_MAX) == NULL) strcpy(corefile, \"\");\n\tstrcat(corefile, \"\/core.OpenLieroX\");\n\tif(file_postfix) { strcat(corefile, \".\"); strcat(corefile, file_postfix); }\n\tprintf(\"writing coredump to %s\\n\", corefile);\n\t\n\tprintf(\"dumping core ... \"); fflush(0);\n#ifdef GCOREDUMPER\n\tWriteCoreDump(corefile);\n#else\n\tGdbWriteCoreDump(corefile);\n#endif\n\tprintf(\"ready\\n\");\n}\n\n#endif\n\n#if (defined(__GLIBCXX__) || defined(__GLIBC__) || !defined(WIN32)) && !defined(__MINGW32_VERSION)\n\n#include <execinfo.h>\n#include <stdio.h>\n#include <stdlib.h>\n\nvoid DumpCallstackPrintf(void* callpnt) {\n\tvoid *callstack[128];\n\tint framesC = backtrace(callstack, sizeof(callstack));\n\tprintf(\"backtrace() returned %d addresses\\n\", framesC);\n\tif(callpnt != NULL && framesC > 3) callstack[3] = callpnt; \/\/ expected to be called from signal handler\n\tchar** strs = backtrace_symbols(callstack, framesC);\n\tfor(int i = 0; i < framesC; ++i) {\n\t\tif(strs[i])\n\t\t\tprintf(\"%s\\n\", strs[i]);\n\t\telse\n\t\t\tbreak;\n\t}\n\tfree(strs);\n}\n\nvoid DumpCallstack(void (*PrintOutFct) (const std::string&)) {\n\tvoid *callstack[128];\n\tint framesC = backtrace(callstack, sizeof(callstack));\n\t(*PrintOutFct) (\"DumpCallstack: \" + itoa(framesC) + \" addresses:\");\n\tchar** strs = backtrace_symbols(callstack, framesC);\n\tfor(int i = 0; i < framesC; ++i) {\n\t\tif(strs[i])\n\t\t\t(*PrintOutFct) (std::string(\" \") + strs[i] + \"\\n\");\n\t\telse\n\t\t\tbreak;\n\t}\n\tfree(strs);\n}\n\n#else\n\n#include \"StackWalker.h\" \/\/ Call Luke Stackwalker for help\n\ntypedef void (*PrintOutFct) (const std::string&);\n\n\/\/ Override the default stackwalker with our own print functions\nclass PrintStackWalker : public StackWalker {\nprivate:\n\tPrintOutFct m_print;\n\npublic:\n\tPrintStackWalker(PrintOutFct fct = NULL) : StackWalker(RetrieveVerbose) { m_print = fct; }\n\tvoid OnLoadModule(LPCSTR img, LPCSTR mod, DWORD64 baseAddr, DWORD size, DWORD result, LPCSTR symType, LPCSTR pdbName, ULONGLONG fileVersion)\n\t{\n\n\t}\n\n\tvoid OnOutput(LPCSTR szText) \n\t{\n\t\tif (m_print == NULL)\n\t\t\tprintf(szText);\n\t\telse\n\t\t\tm_print(std::string(szText));\n\t\tStackWalker::OnOutput(szText);\n\t}\n};\n\nvoid DumpCallstackPrintf(void* callpnt) \n{\n\tPrintStackWalker sw;\n\tsw.ShowCallstack();\n\t\n}\nvoid DumpCallstack(void (*LineOutFct) (const std::string&)) \n{ \n\tPrintStackWalker sw(LineOutFct);\n\tsw.ShowCallstack();\n}\n\n#endif\n\nLogger notes(0,2,1000, \"n: \");\nLogger hints(0,1,100, \"H: \");\nLogger warnings(0,0,10, \"W: \");\nLogger errors(-1,-1,1, \"E: \");\n\n#include <iostream>\n#include <sstream>\n#include \"ThreadPool.h\"\n#include \"Options.h\"\n#include \"console.h\"\n#include \"StringUtils.h\"\n\nstatic SDL_mutex* globalCoutMutex = NULL;\n\nLogger::Logger(int o, int ingame, int callst, const std::string& p)\n: minCoutVerb(o), minIngameConVerb(ingame), minCallstackVerb(callst), prefix(p), lastWasNewline(true), mutex(NULL) {\n\tmutex = SDL_CreateMutex();\n\tif(!globalCoutMutex)\n\t\tglobalCoutMutex = SDL_CreateMutex();\n}\n\nLogger::~Logger() {\n\tSDL_DestroyMutex(mutex); mutex = NULL;\n\tif(globalCoutMutex) {\n\t\tSDL_DestroyMutex(globalCoutMutex);\n\t\tglobalCoutMutex = NULL;\n\t}\n}\n\nvoid Logger::lock() {\n\tSDL_mutexP(mutex);\n}\n\nvoid Logger::unlock() {\n\tSDL_mutexV(mutex);\n}\n\nstatic void CoutPrint(const std::string& str) {\n\t\/\/ TODO: We have used std::cout here before but it doesn't seem to work after a while for some reason.\n\t\/\/ TODO: c_str() is slow and not really needed here.\n\tprintf(\"%s\", str.c_str());\n}\n\ntemplate<int col> void ConPrint(const std::string& str) {\n\t\/\/ TODO: Con_AddText adds a line but we only want to add str\n\tstd::string buf = str;\n\tif(buf.size() > 0 && buf[buf.size()-1] == '\\n') buf.erase(buf.size()-1);\n\tCon_AddText(col, buf, false);\n}\n\n\/\/ true if last was newline\nstatic bool logger_output(Logger& log, const std::string& buf) {\n\tbool ret = true;\n\tif(!tLXOptions || tLXOptions->iVerbosity >= log.minCoutVerb) {\n\t\tSDL_mutexP(globalCoutMutex);\n\t\tret = PrettyPrint(log.prefix, buf, CoutPrint, log.lastWasNewline);\n\t\t\/\/std::cout.flush();\n\t\tSDL_mutexV(globalCoutMutex);\n\t}\n\tif(tLXOptions && tLXOptions->iVerbosity >= log.minCallstackVerb) {\n\t\tDumpCallstackPrintf();\n\t}\n\tif(tLXOptions && Con_IsInited() && tLXOptions->iVerbosity >= log.minIngameConVerb) {\n\t\t\/\/ the check is a bit hacky (see Con_AddText) but I really dont want to overcomplicate this\n\t\tif(!strStartsWith(buf, \"Ingame console: \")) {\n\t\t\t\/\/ we are not safing explicitly a color in the Logger, thus we try to assume a good color from the verbosity level\n\t\t\tif(log.minIngameConVerb < 0)\n\t\t\t\tret = PrettyPrint(log.prefix, buf, ConPrint<CNC_ERROR>, log.lastWasNewline);\n\t\t\telse if(log.minIngameConVerb == 0)\n\t\t\t\tret = PrettyPrint(log.prefix, buf, ConPrint<CNC_WARNING>, log.lastWasNewline);\n\t\t\telse if(log.minIngameConVerb == 1)\n\t\t\t\tret = PrettyPrint(log.prefix, buf, ConPrint<CNC_NOTIFY>, log.lastWasNewline);\n\t\t\telse if(log.minIngameConVerb < 5)\n\t\t\t\tret = PrettyPrint(log.prefix, buf, ConPrint<CNC_NORMAL>, log.lastWasNewline);\n\t\t\telse \/\/ >=5\n\t\t\t\tret = PrettyPrint(log.prefix, buf, ConPrint<CNC_DEV>, log.lastWasNewline);\n\t\t}\n\t\tif(tLXOptions->iVerbosity >= log.minCallstackVerb) {\n\t\t\tDumpCallstack(ConPrint<CNC_DEV>);\n\t\t}\n\t}\n\treturn ret;\n}\n\nLogger& Logger::flush() {\n\tlock();\n\tlastWasNewline = logger_output(*this, buffer);\n\tbuffer = \"\";\n\tunlock();\n\treturn *this;\n}\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n\n#include <SFML\/Graphics.hpp>\n#include \"game.h\"\n\n\n\nGame::Game():\n playing(true),\n screen(),\n map(nullptr)\n \/\/map_camera(nullptr),\n \/\/unitRepository(nullptr)\n{\n sf::ContextSettings settings;\n settings.antialiasingLevel = 8;\n screen.create(sf::VideoMode(800, 600), \"Dune 2 - The Maker\", sf::Style::Close, settings);\n screen.setFramerateLimit(IDEAL_FPS);\n screen.setMouseCursorVisible(false);\n\n if (!init()){\n std::cerr << \"Failed to initialized game.\";\n playing = false;\n }\n}\n\nint Game::execute() {\n\n sf::Clock clock;\n\n while(playing) {\n sf::Event event;\n actionMap.clearEvents();\n sf::Time dt = clock.restart();\n while(screen.pollEvent(event)) {\n actionMap.pushEvent(event);\n }\n\n updateState(dt);\n render();\n }\n\n return 0;\n}\n\nbool Game::init() {\n if (!terrain.loadFromFile(\"graphics\/terrain.png\")) {\n std::cout << \"Failed to read graphics\/terrain.png data\" << std::endl;\n return false;\n }\n\n sf::Image temp;\n if (!temp.loadFromFile(\"graphics\/shroud_edges.bmp\")) {\n std::cout << \"Failed to read graphics\/shroud_edges.bmp data\" << std::endl;\n return false;\n }\n\n temp.createMaskFromColor(sf::Color(255, 0, 255));\n shroud_edges.loadFromImage(temp);\n\n map.reset(new Map(terrain, shroud_edges));\n map->load(\"maps\/4PL_Mountains.ini\");\n\n camera.reset({0,0,800,600});\n screen.setView(camera);\n\n \/\/init a trike\n sf::Image trikeImage;\n trikeImage.loadFromFile(\"graphics\/Unit_Trike.bmp\");\n trikeImage.createMaskFromColor(sf::Color(0,0,0));\n sf::Texture* trikeTexture = new sf::Texture; \/\/yes we are leaking! Player should own this\n trikeTexture->loadFromImage(trikeImage);\n\n sf::Image trikeShadowImage;\n trikeShadowImage.loadFromFile(\"graphics\/Unit_Trike_s.bmp\");\n trikeShadowImage.createMaskFromColor(sf::Color(255,0,255));\n sf::Texture* trikeShadowTexture = new sf::Texture;\n trikeShadowTexture->loadFromImage(trikeShadowImage);\n\n sf::Image selectedImage;\n selectedImage.loadFromFile(\"graphics\/selected.bmp\");\n selectedImage.createMaskFromColor(sf::Color(255, 0, 255));\n sf::Texture* selectedTexture = new sf::Texture; \/\/more leaks!\n selectedTexture->loadFromImage(selectedImage);\n units.emplace_back(new Unit(*trikeTexture, *trikeShadowTexture, *selectedTexture, 256, 256, 0));\n\n \/\/remove shroud here\n map->removeShroud(static_cast<sf::Vector2i>(units[0]->getPosition()), 10);\n\n \/\/\/\/init two players\n \/\/int idCount = 0;\n \/\/players.emplace_back(House::Sardaukar, idCount++);\n \/\/players.emplace_back(House::Harkonnen, idCount++);\n\n \/\/units.emplace_back(unitRepository->create(UNIT_FRIGATE, House::Sardaukar, 3, 3, 10, SUBCELL_CENTER, players[0]));\n \/\/units.emplace_back(unitRepository->create(UNIT_TRIKE, House::Sardaukar, 8, 8, 3, SUBCELL_CENTER, players[0]));\n\n \/\/\/\/ soldiers\n \/\/units.emplace_back(unitRepository->create(UNIT_SOLDIER, House::Sardaukar, 14, 14, 3, SUBCELL_CENTER, players[0]));\n \/\/units.emplace_back(unitRepository->create(UNIT_SOLDIER, House::Sardaukar, 14, 14, 3, SUBCELL_UPLEFT, players[0]));\n \/\/units.emplace_back(unitRepository->create(UNIT_SOLDIER, House::Sardaukar, 14, 14, 3, SUBCELL_UPRIGHT, players[0]));\n \/\/units.emplace_back(unitRepository->create(UNIT_SOLDIER, House::Sardaukar, 14, 14, 3, SUBCELL_DOWNLEFT, players[0]));\n \/\/units.emplace_back(unitRepository->create(UNIT_SOLDIER, House::Sardaukar, 14, 14, 3, SUBCELL_DOWNRIGHT, players[0]));\n\n \/\/units.emplace_back(unitRepository->create(UNIT_SOLDIER, House::Harkonnen, 18, 8, 3, SUBCELL_CENTER, players[1]));\n \/\/units.emplace_back(unitRepository->create(UNIT_SOLDIER, House::Harkonnen, 18, 8, 3, SUBCELL_UPLEFT, players[1]));\n \/\/units.emplace_back(unitRepository->create(UNIT_SOLDIER, House::Harkonnen, 18, 8, 3, SUBCELL_UPRIGHT, players[1]));\n \/\/units.emplace_back(unitRepository->create(UNIT_SOLDIER, House::Harkonnen, 18, 8, 3, SUBCELL_DOWNLEFT, players[1]));\n \/\/units.emplace_back(unitRepository->create(UNIT_SOLDIER, House::Harkonnen, 18, 8, 3, SUBCELL_DOWNRIGHT, players[1]));\n\n \/\/thor Actions here\n\n actionMap[\"boxStart\"] = thor::Action(sf::Mouse::Left, thor::Action::PressOnce);\n actionMap[\"orderMove\"] = thor::Action(sf::Mouse::Left, thor::Action::PressOnce);\n actionMap[\"boxDrag\"] = thor::Action(sf::Mouse::Left, thor::Action::Hold);\n actionMap[\"boxRelease\"] = thor::Action(sf::Mouse::Left, thor::Action::ReleaseOnce);\n actionMap[\"deselectAll\"] = thor::Action(sf::Mouse::Right, thor::Action::PressOnce);\n actionMap[\"close\"] = thor::Action(sf::Event::Closed) || thor::Action(sf::Keyboard::Q, thor::Action::PressOnce);\n actionMap[\"cameraLeft\"] = thor::Action(sf::Keyboard::Left, thor::Action::Hold);\n actionMap[\"cameraRight\"] = thor::Action(sf::Keyboard::Right, thor::Action::Hold);\n actionMap[\"cameraUp\"] = thor::Action(sf::Keyboard::Up, thor::Action::Hold);\n actionMap[\"cameraDown\"] = thor::Action(sf::Keyboard::Down, thor::Action::Hold);\n\n typedef thor::ActionContext<std::string> actionContext;\n\n system.connect(\"close\", [this](actionContext){playing = false;});\n\n system.connect(\"boxRelease\", [this](actionContext){\n for (auto& unit : units){\n if (box.intersects(unit->getBounds())){\n unit->select();\n system.connect(\"orderMove\", [this, &unit](actionContext context){\n unit->order_move(screen.mapPixelToCoords(sf::Vector2i(context.event->mouseButton.x, context.event->mouseButton.y)));\n });\n mouse.setType(Mouse::Type::Move); \/\/at least one unit selected...\n }\n }\n box.clear();\n });\n\n system.connect(\"boxStart\", [this](actionContext context){\n sf::Vector2f toSet = screen.mapPixelToCoords(sf::Vector2i(context.event->mouseButton.x, context.event->mouseButton.y));\n box.setTopLeft(toSet);\n });\n\n system.connect(\"deselectAll\", [this](actionContext){\n\/\/ system.clearConnections(\"orderMove\"); \/\/ -> This is bugged in Thor\n mouse.setType(Mouse::Type::Default);\n for (auto& unit : units)\n unit->unselect();\n });\n\n system.connect(\"boxDrag\", [this](actionContext){\n box.setBottomRight(screen.mapPixelToCoords(sf::Mouse::getPosition(screen)));\n });\n\n const float cameraSpeed = 15.f;\n\n moveVector = sf::Vector2f();\n\n system.connect(\"cameraLeft\", [this, cameraSpeed](actionContext) {moveVector.x -= cameraSpeed;});\n system.connect(\"cameraRight\", [this, cameraSpeed](actionContext){moveVector.x = cameraSpeed; });\n system.connect(\"cameraUp\", [this, cameraSpeed](actionContext) {moveVector.y -= cameraSpeed;});\n system.connect(\"cameraDown\", [this, cameraSpeed](actionContext) {moveVector.y = cameraSpeed; });\n\n return true;\n}\n\nvoid Game::render() {\n screen.clear();\n\n screen.setView(camera);\n\n screen.draw(*map);\n\n for (const auto& unit : units)\n screen.draw(*unit);\n\n map->drawShrouded(screen, sf::RenderStates::Default);\n\n screen.draw(box);\n\n screen.draw(fpsCounter);\n\n screen.setView(camera);\n screen.draw(mouse);\n\n screen.display();\n}\n\nvoid Game::updateState(sf::Time dt) {\n actionMap.invokeCallbacks(system, &screen); \n\n mouse.setPosition(screen.mapPixelToCoords(sf::Mouse::getPosition(screen)));\n\n sf::Vector2f topLeft = camera.getCenter() - (camera.getSize() \/ 2.f);\n sf::Vector2f downRight = camera.getCenter() + (camera.getSize() \/ 2.f);\n\n if (moveVector.x < 0 && topLeft.x <= 0) moveVector.x = 0;\n if (moveVector.y < 0 && topLeft.y <= 0) moveVector.y = 0;\n if (moveVector.x > 0 && downRight.x >= (map->getMaxWidth() + 3) * Cell::TILE_SIZE) moveVector.x = 0;\n if (moveVector.y > 0 && downRight.y >= (map->getMaxHeight() + 3) * Cell::TILE_SIZE) moveVector.y = 0;\n camera.move(moveVector);\n moveVector = sf::Vector2f();\n\n for (auto& unit: units){\n unit->updateState();\n }\n\n fpsCounter.update(dt);\n map->prepare(screen.mapPixelToCoords(sf::Vector2i(0,0)));\n}\n<commit_msg>map camera boundaries are now respected for every camera speed<commit_after>#include <iostream>\n\n#include <SFML\/Graphics.hpp>\n#include \"game.h\"\n\n\n\nGame::Game():\n playing(true),\n screen(),\n map(nullptr)\n \/\/map_camera(nullptr),\n \/\/unitRepository(nullptr)\n{\n sf::ContextSettings settings;\n settings.antialiasingLevel = 8;\n screen.create(sf::VideoMode(800, 600), \"Dune 2 - The Maker\", sf::Style::Close, settings);\n screen.setFramerateLimit(IDEAL_FPS);\n screen.setMouseCursorVisible(false);\n\n if (!init()){\n std::cerr << \"Failed to initialized game.\";\n playing = false;\n }\n}\n\nint Game::execute() {\n\n sf::Clock clock;\n\n while(playing) {\n sf::Event event;\n actionMap.clearEvents();\n sf::Time dt = clock.restart();\n while(screen.pollEvent(event)) {\n actionMap.pushEvent(event);\n }\n\n updateState(dt);\n render();\n }\n\n return 0;\n}\n\nbool Game::init() {\n if (!terrain.loadFromFile(\"graphics\/terrain.png\")) {\n std::cout << \"Failed to read graphics\/terrain.png data\" << std::endl;\n return false;\n }\n\n sf::Image temp;\n if (!temp.loadFromFile(\"graphics\/shroud_edges.bmp\")) {\n std::cout << \"Failed to read graphics\/shroud_edges.bmp data\" << std::endl;\n return false;\n }\n\n temp.createMaskFromColor(sf::Color(255, 0, 255));\n shroud_edges.loadFromImage(temp);\n\n map.reset(new Map(terrain, shroud_edges));\n map->load(\"maps\/4PL_Mountains.ini\");\n\n camera.reset({0,0,800,600});\n screen.setView(camera);\n\n \/\/init a trike\n sf::Image trikeImage;\n trikeImage.loadFromFile(\"graphics\/Unit_Trike.bmp\");\n trikeImage.createMaskFromColor(sf::Color(0,0,0));\n sf::Texture* trikeTexture = new sf::Texture; \/\/yes we are leaking! Player should own this\n trikeTexture->loadFromImage(trikeImage);\n\n sf::Image trikeShadowImage;\n trikeShadowImage.loadFromFile(\"graphics\/Unit_Trike_s.bmp\");\n trikeShadowImage.createMaskFromColor(sf::Color(255,0,255));\n sf::Texture* trikeShadowTexture = new sf::Texture;\n trikeShadowTexture->loadFromImage(trikeShadowImage);\n\n sf::Image selectedImage;\n selectedImage.loadFromFile(\"graphics\/selected.bmp\");\n selectedImage.createMaskFromColor(sf::Color(255, 0, 255));\n sf::Texture* selectedTexture = new sf::Texture; \/\/more leaks!\n selectedTexture->loadFromImage(selectedImage);\n units.emplace_back(new Unit(*trikeTexture, *trikeShadowTexture, *selectedTexture, 256, 256, 0));\n\n \/\/remove shroud here\n map->removeShroud(static_cast<sf::Vector2i>(units[0]->getPosition()), 10);\n\n \/\/\/\/init two players\n \/\/int idCount = 0;\n \/\/players.emplace_back(House::Sardaukar, idCount++);\n \/\/players.emplace_back(House::Harkonnen, idCount++);\n\n \/\/units.emplace_back(unitRepository->create(UNIT_FRIGATE, House::Sardaukar, 3, 3, 10, SUBCELL_CENTER, players[0]));\n \/\/units.emplace_back(unitRepository->create(UNIT_TRIKE, House::Sardaukar, 8, 8, 3, SUBCELL_CENTER, players[0]));\n\n \/\/\/\/ soldiers\n \/\/units.emplace_back(unitRepository->create(UNIT_SOLDIER, House::Sardaukar, 14, 14, 3, SUBCELL_CENTER, players[0]));\n \/\/units.emplace_back(unitRepository->create(UNIT_SOLDIER, House::Sardaukar, 14, 14, 3, SUBCELL_UPLEFT, players[0]));\n \/\/units.emplace_back(unitRepository->create(UNIT_SOLDIER, House::Sardaukar, 14, 14, 3, SUBCELL_UPRIGHT, players[0]));\n \/\/units.emplace_back(unitRepository->create(UNIT_SOLDIER, House::Sardaukar, 14, 14, 3, SUBCELL_DOWNLEFT, players[0]));\n \/\/units.emplace_back(unitRepository->create(UNIT_SOLDIER, House::Sardaukar, 14, 14, 3, SUBCELL_DOWNRIGHT, players[0]));\n\n \/\/units.emplace_back(unitRepository->create(UNIT_SOLDIER, House::Harkonnen, 18, 8, 3, SUBCELL_CENTER, players[1]));\n \/\/units.emplace_back(unitRepository->create(UNIT_SOLDIER, House::Harkonnen, 18, 8, 3, SUBCELL_UPLEFT, players[1]));\n \/\/units.emplace_back(unitRepository->create(UNIT_SOLDIER, House::Harkonnen, 18, 8, 3, SUBCELL_UPRIGHT, players[1]));\n \/\/units.emplace_back(unitRepository->create(UNIT_SOLDIER, House::Harkonnen, 18, 8, 3, SUBCELL_DOWNLEFT, players[1]));\n \/\/units.emplace_back(unitRepository->create(UNIT_SOLDIER, House::Harkonnen, 18, 8, 3, SUBCELL_DOWNRIGHT, players[1]));\n\n \/\/thor Actions here\n\n actionMap[\"boxStart\"] = thor::Action(sf::Mouse::Left, thor::Action::PressOnce);\n actionMap[\"orderMove\"] = thor::Action(sf::Mouse::Left, thor::Action::PressOnce);\n actionMap[\"boxDrag\"] = thor::Action(sf::Mouse::Left, thor::Action::Hold);\n actionMap[\"boxRelease\"] = thor::Action(sf::Mouse::Left, thor::Action::ReleaseOnce);\n actionMap[\"deselectAll\"] = thor::Action(sf::Mouse::Right, thor::Action::PressOnce);\n actionMap[\"close\"] = thor::Action(sf::Event::Closed) || thor::Action(sf::Keyboard::Q, thor::Action::PressOnce);\n actionMap[\"cameraLeft\"] = thor::Action(sf::Keyboard::Left, thor::Action::Hold);\n actionMap[\"cameraRight\"] = thor::Action(sf::Keyboard::Right, thor::Action::Hold);\n actionMap[\"cameraUp\"] = thor::Action(sf::Keyboard::Up, thor::Action::Hold);\n actionMap[\"cameraDown\"] = thor::Action(sf::Keyboard::Down, thor::Action::Hold);\n\n typedef thor::ActionContext<std::string> actionContext;\n\n system.connect(\"close\", [this](actionContext){playing = false;});\n\n system.connect(\"boxRelease\", [this](actionContext){\n for (auto& unit : units){\n if (box.intersects(unit->getBounds())){\n unit->select();\n system.connect(\"orderMove\", [this, &unit](actionContext context){\n unit->order_move(screen.mapPixelToCoords(sf::Vector2i(context.event->mouseButton.x, context.event->mouseButton.y)));\n });\n mouse.setType(Mouse::Type::Move); \/\/at least one unit selected...\n }\n }\n box.clear();\n });\n\n system.connect(\"boxStart\", [this](actionContext context){\n sf::Vector2f toSet = screen.mapPixelToCoords(sf::Vector2i(context.event->mouseButton.x, context.event->mouseButton.y));\n box.setTopLeft(toSet);\n });\n\n system.connect(\"deselectAll\", [this](actionContext){\n\/\/ system.clearConnections(\"orderMove\"); \/\/ -> This is bugged in Thor\n mouse.setType(Mouse::Type::Default);\n for (auto& unit : units)\n unit->unselect();\n });\n\n system.connect(\"boxDrag\", [this](actionContext){\n box.setBottomRight(screen.mapPixelToCoords(sf::Mouse::getPosition(screen)));\n });\n\n const float cameraSpeed = 15.f;\n\n moveVector = sf::Vector2f();\n\n system.connect(\"cameraLeft\", [this, cameraSpeed](actionContext) {moveVector.x -= cameraSpeed;});\n system.connect(\"cameraRight\", [this, cameraSpeed](actionContext){moveVector.x = cameraSpeed; });\n system.connect(\"cameraUp\", [this, cameraSpeed](actionContext) {moveVector.y -= cameraSpeed;});\n system.connect(\"cameraDown\", [this, cameraSpeed](actionContext) {moveVector.y = cameraSpeed; });\n\n return true;\n}\n\nvoid Game::render() {\n screen.clear();\n\n screen.setView(camera);\n\n screen.draw(*map);\n\n for (const auto& unit : units)\n screen.draw(*unit);\n\n map->drawShrouded(screen, sf::RenderStates::Default);\n\n screen.draw(box);\n\n screen.draw(fpsCounter);\n\n screen.setView(camera);\n\n screen.draw(mouse);\n\n screen.display();\n}\n\nvoid Game::updateState(sf::Time dt) {\n actionMap.invokeCallbacks(system, &screen); \n\n mouse.setPosition(screen.mapPixelToCoords(sf::Mouse::getPosition(screen)));\n\n camera.move(moveVector);\n sf::Vector2f half_of_camera = camera.getSize() \/ 2.f;\n sf::Vector2f topLeft = camera.getCenter() - (half_of_camera);\n sf::Vector2f downRight = camera.getCenter() + (half_of_camera);\n\n if (topLeft.x <= Cell::TILE_SIZE) camera.setCenter(half_of_camera.x + Cell::TILE_SIZE, camera.getCenter().y);\n if (topLeft.y <= Cell::TILE_SIZE) camera.setCenter(camera.getCenter().x, half_of_camera.y + Cell::TILE_SIZE);\n\n int max_width = (map->getMaxWidth() + 1) * Cell::TILE_SIZE;\n int max_height = (map->getMaxHeight() + 1) * Cell::TILE_SIZE;\n\n if (downRight.x >= max_width) camera.setCenter(max_width - half_of_camera.x, camera.getCenter().y);\n if (downRight.y >= max_height) camera.setCenter(camera.getCenter().x, max_height - half_of_camera.y);\n\n moveVector = sf::Vector2f();\n\n for (auto& unit: units){\n unit->updateState();\n }\n\n fpsCounter.update(dt);\n map->prepare(screen.mapPixelToCoords(sf::Vector2i(0,0)));\n}\n<|endoftext|>"} {"text":"<commit_before>#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <unistd.h>\n#include <sqlite3.h>\n#include <getopt.h>\n#include <string>\n#include <vector>\n#include <map>\n#include <set>\n#include <zlib.h>\n#include <math.h>\n#include <fcntl.h>\n#include <sys\/stat.h>\n#include <sys\/mman.h>\n#include <protozero\/pbf_reader.hpp>\n#include \"mvt.hpp\"\n#include \"projection.hpp\"\n#include \"geometry.hpp\"\n#include \"write_json.hpp\"\n\nint minzoom = 0;\nint maxzoom = 32;\nbool force = false;\n\nvoid do_stats(mvt_tile &tile, size_t size, bool compressed, int z, unsigned x, unsigned y) {\n\tprintf(\"{ \\\"zoom\\\": %d, \\\"x\\\": %u, \\\"y\\\": %u, \\\"bytes\\\": %zu, \\\"compressed\\\": %s\", z, x, y, size, compressed ? \"true\" : \"false\");\n\n\tprintf(\", \\\"layers\\\": { \");\n\tfor (size_t i = 0; i < tile.layers.size(); i++) {\n\t\tif (i != 0) {\n\t\t\tprintf(\", \");\n\t\t}\n\t\tfprintq(stdout, tile.layers[i].name.c_str());\n\n\t\tint points = 0, lines = 0, polygons = 0;\n\t\tfor (size_t j = 0; j < tile.layers[i].features.size(); j++) {\n\t\t\tif (tile.layers[i].features[j].type == mvt_point) {\n\t\t\t\tpoints++;\n\t\t\t} else if (tile.layers[i].features[j].type == mvt_linestring) {\n\t\t\t\tlines++;\n\t\t\t} else if (tile.layers[i].features[j].type == mvt_polygon) {\n\t\t\t\tpolygons++;\n\t\t\t}\n\t\t}\n\n\t\tprintf(\": { \\\"points\\\": %d, \\\"lines\\\": %d, \\\"polygons\\\": %d, \\\"extent\\\": %lld }\", points, lines, polygons, tile.layers[i].extent);\n\t}\n\n\tprintf(\" } }\\n\");\n}\n\nvoid handle(std::string message, int z, unsigned x, unsigned y, int describe, std::set<std::string> const &to_decode, bool pipeline, bool stats) {\n\tmvt_tile tile;\n\tbool was_compressed;\n\n\ttry {\n\t\tif (!tile.decode(message, was_compressed)) {\n\t\t\tfprintf(stderr, \"Couldn't parse tile %d\/%u\/%u\\n\", z, x, y);\n\t\t\texit(EXIT_FAILURE);\n\t\t}\n\t} catch (protozero::unknown_pbf_wire_type_exception e) {\n\t\tfprintf(stderr, \"PBF decoding error in tile %d\/%u\/%u\\n\", z, x, y);\n\t\texit(EXIT_FAILURE);\n\t}\n\n\tif (stats) {\n\t\tdo_stats(tile, message.size(), was_compressed, z, x, y);\n\t\treturn;\n\t}\n\n\tif (!pipeline) {\n\t\tprintf(\"{ \\\"type\\\": \\\"FeatureCollection\\\"\");\n\n\t\tif (describe) {\n\t\t\tprintf(\", \\\"properties\\\": { \\\"zoom\\\": %d, \\\"x\\\": %d, \\\"y\\\": %d\", z, x, y);\n\t\t\tif (!was_compressed) {\n\t\t\t\tprintf(\", \\\"compressed\\\": false\");\n\t\t\t}\n\t\t\tprintf(\" }\");\n\n\t\t\tif (projection != projections) {\n\t\t\t\tprintf(\", \\\"crs\\\": { \\\"type\\\": \\\"name\\\", \\\"properties\\\": { \\\"name\\\": \");\n\t\t\t\tfprintq(stdout, projection->alias);\n\t\t\t\tprintf(\" } }\");\n\t\t\t}\n\t\t}\n\n\t\tprintf(\", \\\"features\\\": [\\n\");\n\t}\n\n\tbool first_layer = true;\n\tfor (size_t l = 0; l < tile.layers.size(); l++) {\n\t\tmvt_layer &layer = tile.layers[l];\n\n\t\tif (layer.extent <= 0) {\n\t\t\tfprintf(stderr, \"Impossible layer extent %lld in mbtiles\\n\", layer.extent);\n\t\t\texit(EXIT_FAILURE);\n\t\t}\n\n\t\tif (to_decode.size() != 0 && !to_decode.count(layer.name)) {\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (!pipeline) {\n\t\t\tif (describe) {\n\t\t\t\tif (!first_layer) {\n\t\t\t\t\tprintf(\",\\n\");\n\t\t\t\t}\n\n\t\t\t\tprintf(\"{ \\\"type\\\": \\\"FeatureCollection\\\"\");\n\t\t\t\tprintf(\", \\\"properties\\\": { \\\"layer\\\": \");\n\t\t\t\tfprintq(stdout, layer.name.c_str());\n\t\t\t\tprintf(\", \\\"version\\\": %d, \\\"extent\\\": %lld\", layer.version, layer.extent);\n\t\t\t\tprintf(\" }\");\n\t\t\t\tprintf(\", \\\"features\\\": [\\n\");\n\n\t\t\t\tfirst_layer = false;\n\t\t\t}\n\t\t}\n\n\t\t\/\/ X and Y are unsigned, so no need to check <0\n\t\tif (x > (1 << z) || y > (1 << z)) {\n\t\t\tfprintf(stderr, \"Impossible tile %d\/%u\/%u\\n\", z, x, y);\n\t\t\texit(EXIT_FAILURE);\n\t\t}\n\n\t\tlayer_to_geojson(stdout, layer, z, x, y, !pipeline, pipeline, pipeline, 0, 0, 0, !force);\n\n\t\tif (!pipeline) {\n\t\t\tif (describe) {\n\t\t\t\tprintf(\"] }\\n\");\n\t\t\t}\n\t\t}\n\t}\n\n\tif (!pipeline) {\n\t\tprintf(\"] }\\n\");\n\t}\n}\n\nvoid decode(char *fname, int z, unsigned x, unsigned y, std::set<std::string> const &to_decode, bool pipeline, bool stats) {\n\tsqlite3 *db;\n\tint oz = z;\n\tunsigned ox = x, oy = y;\n\n\tint fd = open(fname, O_RDONLY | O_CLOEXEC);\n\tif (fd >= 0) {\n\t\tstruct stat st;\n\t\tif (fstat(fd, &st) == 0) {\n\t\t\tif (st.st_size < 50 * 1024 * 1024) {\n\t\t\t\tchar *map = (char *) mmap(NULL, st.st_size, PROT_READ, MAP_PRIVATE, fd, 0);\n\t\t\t\tif (map != NULL && map != MAP_FAILED) {\n\t\t\t\t\tif (strcmp(map, \"SQLite format 3\") != 0) {\n\t\t\t\t\t\tif (z >= 0) {\n\t\t\t\t\t\t\tstd::string s = std::string(map, st.st_size);\n\t\t\t\t\t\t\thandle(s, z, x, y, 1, to_decode, pipeline, stats);\n\t\t\t\t\t\t\tmunmap(map, st.st_size);\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tfprintf(stderr, \"Must specify zoom\/x\/y to decode a single pbf file\\n\");\n\t\t\t\t\t\t\texit(EXIT_FAILURE);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tmunmap(map, st.st_size);\n\t\t\t}\n\t\t} else {\n\t\t\tperror(\"fstat\");\n\t\t}\n\t\tif (close(fd) != 0) {\n\t\t\tperror(\"close\");\n\t\t\texit(EXIT_FAILURE);\n\t\t}\n\t} else {\n\t\tperror(fname);\n\t}\n\n\tif (sqlite3_open(fname, &db) != SQLITE_OK) {\n\t\tfprintf(stderr, \"%s: %s\\n\", fname, sqlite3_errmsg(db));\n\t\texit(EXIT_FAILURE);\n\t}\n\n\tif (z < 0) {\n\t\tint within = 0;\n\n\t\tif (!pipeline && !stats) {\n\t\t\tprintf(\"{ \\\"type\\\": \\\"FeatureCollection\\\", \\\"properties\\\": {\\n\");\n\n\t\t\tconst char *sql2 = \"SELECT name, value from metadata order by name;\";\n\t\t\tsqlite3_stmt *stmt2;\n\t\t\tif (sqlite3_prepare_v2(db, sql2, -1, &stmt2, NULL) != SQLITE_OK) {\n\t\t\t\tfprintf(stderr, \"%s: select failed: %s\\n\", fname, sqlite3_errmsg(db));\n\t\t\t\texit(EXIT_FAILURE);\n\t\t\t}\n\n\t\t\twhile (sqlite3_step(stmt2) == SQLITE_ROW) {\n\t\t\t\tif (within) {\n\t\t\t\t\tprintf(\",\\n\");\n\t\t\t\t}\n\t\t\t\twithin = 1;\n\n\t\t\t\tconst unsigned char *name = sqlite3_column_text(stmt2, 0);\n\t\t\t\tconst unsigned char *value = sqlite3_column_text(stmt2, 1);\n\n\t\t\t\tif (name == NULL || value == NULL) {\n\t\t\t\t\tfprintf(stderr, \"Corrupt mbtiles file: null metadata\\n\");\n\t\t\t\t\texit(EXIT_FAILURE);\n\t\t\t\t}\n\n\t\t\t\tfprintq(stdout, (char *) name);\n\t\t\t\tprintf(\": \");\n\t\t\t\tfprintq(stdout, (char *) value);\n\t\t\t}\n\n\t\t\tsqlite3_finalize(stmt2);\n\t\t}\n\n\t\tif (stats) {\n\t\t\tprintf(\"[\\n\");\n\t\t}\n\n\t\tconst char *sql = \"SELECT tile_data, zoom_level, tile_column, tile_row from tiles where zoom_level between ? and ? order by zoom_level, tile_column, tile_row;\";\n\t\tsqlite3_stmt *stmt;\n\t\tif (sqlite3_prepare_v2(db, sql, -1, &stmt, NULL) != SQLITE_OK) {\n\t\t\tfprintf(stderr, \"%s: select failed: %s\\n\", fname, sqlite3_errmsg(db));\n\t\t\texit(EXIT_FAILURE);\n\t\t}\n\n\t\tsqlite3_bind_int(stmt, 1, minzoom);\n\t\tsqlite3_bind_int(stmt, 2, maxzoom);\n\n\t\tif (!pipeline && !stats) {\n\t\t\tprintf(\"\\n}, \\\"features\\\": [\\n\");\n\t\t}\n\n\t\twithin = 0;\n\t\twhile (sqlite3_step(stmt) == SQLITE_ROW) {\n\t\t\tif (!pipeline && !stats) {\n\t\t\t\tif (within) {\n\t\t\t\t\tprintf(\",\\n\");\n\t\t\t\t}\n\t\t\t\twithin = 1;\n\t\t\t}\n\t\t\tif (stats) {\n\t\t\t\tif (within) {\n\t\t\t\t\tprintf(\",\\n\");\n\t\t\t\t}\n\t\t\t\twithin = 1;\n\t\t\t}\n\n\t\t\tint len = sqlite3_column_bytes(stmt, 0);\n\t\t\tint tz = sqlite3_column_int(stmt, 1);\n\t\t\tint tx = sqlite3_column_int(stmt, 2);\n\t\t\tint ty = sqlite3_column_int(stmt, 3);\n\n\t\t\tif (tz < 0 || tz >= 32) {\n\t\t\t\tfprintf(stderr, \"Impossible zoom level %d in mbtiles\\n\", tz);\n\t\t\t\texit(EXIT_FAILURE);\n\t\t\t}\n\n\t\t\tty = (1LL << tz) - 1 - ty;\n\t\t\tconst char *s = (const char *) sqlite3_column_blob(stmt, 0);\n\n\t\t\thandle(std::string(s, len), tz, tx, ty, 1, to_decode, pipeline, stats);\n\t\t}\n\n\t\tif (!pipeline && !stats) {\n\t\t\tprintf(\"] }\\n\");\n\t\t}\n\t\tif (stats) {\n\t\t\tprintf(\"]\\n\");\n\t\t}\n\n\t\tsqlite3_finalize(stmt);\n\t} else {\n\t\tint handled = 0;\n\t\twhile (z >= 0 && !handled) {\n\t\t\tconst char *sql = \"SELECT tile_data from tiles where zoom_level = ? and tile_column = ? and tile_row = ?;\";\n\t\t\tsqlite3_stmt *stmt;\n\t\t\tif (sqlite3_prepare_v2(db, sql, -1, &stmt, NULL) != SQLITE_OK) {\n\t\t\t\tfprintf(stderr, \"%s: select failed: %s\\n\", fname, sqlite3_errmsg(db));\n\t\t\t\texit(EXIT_FAILURE);\n\t\t\t}\n\n\t\t\tsqlite3_bind_int(stmt, 1, z);\n\t\t\tsqlite3_bind_int(stmt, 2, x);\n\t\t\tsqlite3_bind_int(stmt, 3, (1LL << z) - 1 - y);\n\n\t\t\twhile (sqlite3_step(stmt) == SQLITE_ROW) {\n\t\t\t\tint len = sqlite3_column_bytes(stmt, 0);\n\t\t\t\tconst char *s = (const char *) sqlite3_column_blob(stmt, 0);\n\n\t\t\t\tif (z != oz) {\n\t\t\t\t\tfprintf(stderr, \"%s: Warning: using tile %d\/%u\/%u instead of %d\/%u\/%u\\n\", fname, z, x, y, oz, ox, oy);\n\t\t\t\t}\n\n\t\t\t\thandle(std::string(s, len), z, x, y, 0, to_decode, pipeline, stats);\n\t\t\t\thandled = 1;\n\t\t\t}\n\n\t\t\tsqlite3_finalize(stmt);\n\n\t\t\tz--;\n\t\t\tx \/= 2;\n\t\t\ty \/= 2;\n\t\t}\n\t}\n\n\tif (sqlite3_close(db) != SQLITE_OK) {\n\t\tfprintf(stderr, \"%s: could not close database: %s\\n\", fname, sqlite3_errmsg(db));\n\t\texit(EXIT_FAILURE);\n\t}\n}\n\nvoid usage(char **argv) {\n\tfprintf(stderr, \"Usage: %s [-s projection] [-Z minzoom] [-z maxzoom] [-l layer ...] file.mbtiles [zoom x y]\\n\", argv[0]);\n\texit(EXIT_FAILURE);\n}\n\nint main(int argc, char **argv) {\n\textern int optind;\n\textern char *optarg;\n\tint i;\n\tstd::set<std::string> to_decode;\n\tbool pipeline = false;\n\tbool stats = false;\n\n\tstruct option long_options[] = {\n\t\t{\"projection\", required_argument, 0, 's'},\n\t\t{\"maximum-zoom\", required_argument, 0, 'z'},\n\t\t{\"minimum-zoom\", required_argument, 0, 'Z'},\n\t\t{\"layer\", required_argument, 0, 'l'},\n\t\t{\"tag-layer-and-zoom\", no_argument, 0, 'c'},\n\t\t{\"stats\", no_argument, 0, 'S'},\n\t\t{\"force\", no_argument, 0, 'f'},\n\t\t{0, 0, 0, 0},\n\t};\n\n\tstd::string getopt_str;\n\tfor (size_t lo = 0; long_options[lo].name != NULL; lo++) {\n\t\tif (long_options[lo].val > ' ') {\n\t\t\tgetopt_str.push_back(long_options[lo].val);\n\n\t\t\tif (long_options[lo].has_arg == required_argument) {\n\t\t\t\tgetopt_str.push_back(':');\n\t\t\t}\n\t\t}\n\t}\n\n\twhile ((i = getopt_long(argc, argv, getopt_str.c_str(), long_options, NULL)) != -1) {\n\t\tswitch (i) {\n\t\tcase 0:\n\t\t\tbreak;\n\n\t\tcase 's':\n\t\t\tset_projection_or_exit(optarg);\n\t\t\tbreak;\n\n\t\tcase 'z':\n\t\t\tmaxzoom = atoi(optarg);\n\t\t\tbreak;\n\n\t\tcase 'Z':\n\t\t\tminzoom = atoi(optarg);\n\t\t\tbreak;\n\n\t\tcase 'l':\n\t\t\tto_decode.insert(optarg);\n\t\t\tbreak;\n\n\t\tcase 'c':\n\t\t\tpipeline = true;\n\t\t\tbreak;\n\n\t\tcase 'S':\n\t\t\tstats = true;\n\t\t\tbreak;\n\n\t\tcase 'f':\n\t\t\tforce = true;\n\t\t\tbreak;\n\n\t\tdefault:\n\t\t\tusage(argv);\n\t\t}\n\t}\n\n\tif (argc == optind + 4) {\n\t\tdecode(argv[optind], atoi(argv[optind + 1]), atoi(argv[optind + 2]), atoi(argv[optind + 3]), to_decode, pipeline, stats);\n\t} else if (argc == optind + 1) {\n\t\tdecode(argv[optind], -1, -1, -1, to_decode, pipeline, stats);\n\t} else {\n\t\tusage(argv);\n\t}\n\n\treturn 0;\n}\n<commit_msg>Fix signed comparison warning from g++<commit_after>#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <unistd.h>\n#include <sqlite3.h>\n#include <getopt.h>\n#include <string>\n#include <vector>\n#include <map>\n#include <set>\n#include <zlib.h>\n#include <math.h>\n#include <fcntl.h>\n#include <sys\/stat.h>\n#include <sys\/mman.h>\n#include <protozero\/pbf_reader.hpp>\n#include \"mvt.hpp\"\n#include \"projection.hpp\"\n#include \"geometry.hpp\"\n#include \"write_json.hpp\"\n\nint minzoom = 0;\nint maxzoom = 32;\nbool force = false;\n\nvoid do_stats(mvt_tile &tile, size_t size, bool compressed, int z, unsigned x, unsigned y) {\n\tprintf(\"{ \\\"zoom\\\": %d, \\\"x\\\": %u, \\\"y\\\": %u, \\\"bytes\\\": %zu, \\\"compressed\\\": %s\", z, x, y, size, compressed ? \"true\" : \"false\");\n\n\tprintf(\", \\\"layers\\\": { \");\n\tfor (size_t i = 0; i < tile.layers.size(); i++) {\n\t\tif (i != 0) {\n\t\t\tprintf(\", \");\n\t\t}\n\t\tfprintq(stdout, tile.layers[i].name.c_str());\n\n\t\tint points = 0, lines = 0, polygons = 0;\n\t\tfor (size_t j = 0; j < tile.layers[i].features.size(); j++) {\n\t\t\tif (tile.layers[i].features[j].type == mvt_point) {\n\t\t\t\tpoints++;\n\t\t\t} else if (tile.layers[i].features[j].type == mvt_linestring) {\n\t\t\t\tlines++;\n\t\t\t} else if (tile.layers[i].features[j].type == mvt_polygon) {\n\t\t\t\tpolygons++;\n\t\t\t}\n\t\t}\n\n\t\tprintf(\": { \\\"points\\\": %d, \\\"lines\\\": %d, \\\"polygons\\\": %d, \\\"extent\\\": %lld }\", points, lines, polygons, tile.layers[i].extent);\n\t}\n\n\tprintf(\" } }\\n\");\n}\n\nvoid handle(std::string message, int z, unsigned x, unsigned y, int describe, std::set<std::string> const &to_decode, bool pipeline, bool stats) {\n\tmvt_tile tile;\n\tbool was_compressed;\n\n\ttry {\n\t\tif (!tile.decode(message, was_compressed)) {\n\t\t\tfprintf(stderr, \"Couldn't parse tile %d\/%u\/%u\\n\", z, x, y);\n\t\t\texit(EXIT_FAILURE);\n\t\t}\n\t} catch (protozero::unknown_pbf_wire_type_exception e) {\n\t\tfprintf(stderr, \"PBF decoding error in tile %d\/%u\/%u\\n\", z, x, y);\n\t\texit(EXIT_FAILURE);\n\t}\n\n\tif (stats) {\n\t\tdo_stats(tile, message.size(), was_compressed, z, x, y);\n\t\treturn;\n\t}\n\n\tif (!pipeline) {\n\t\tprintf(\"{ \\\"type\\\": \\\"FeatureCollection\\\"\");\n\n\t\tif (describe) {\n\t\t\tprintf(\", \\\"properties\\\": { \\\"zoom\\\": %d, \\\"x\\\": %d, \\\"y\\\": %d\", z, x, y);\n\t\t\tif (!was_compressed) {\n\t\t\t\tprintf(\", \\\"compressed\\\": false\");\n\t\t\t}\n\t\t\tprintf(\" }\");\n\n\t\t\tif (projection != projections) {\n\t\t\t\tprintf(\", \\\"crs\\\": { \\\"type\\\": \\\"name\\\", \\\"properties\\\": { \\\"name\\\": \");\n\t\t\t\tfprintq(stdout, projection->alias);\n\t\t\t\tprintf(\" } }\");\n\t\t\t}\n\t\t}\n\n\t\tprintf(\", \\\"features\\\": [\\n\");\n\t}\n\n\tbool first_layer = true;\n\tfor (size_t l = 0; l < tile.layers.size(); l++) {\n\t\tmvt_layer &layer = tile.layers[l];\n\n\t\tif (layer.extent <= 0) {\n\t\t\tfprintf(stderr, \"Impossible layer extent %lld in mbtiles\\n\", layer.extent);\n\t\t\texit(EXIT_FAILURE);\n\t\t}\n\n\t\tif (to_decode.size() != 0 && !to_decode.count(layer.name)) {\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (!pipeline) {\n\t\t\tif (describe) {\n\t\t\t\tif (!first_layer) {\n\t\t\t\t\tprintf(\",\\n\");\n\t\t\t\t}\n\n\t\t\t\tprintf(\"{ \\\"type\\\": \\\"FeatureCollection\\\"\");\n\t\t\t\tprintf(\", \\\"properties\\\": { \\\"layer\\\": \");\n\t\t\t\tfprintq(stdout, layer.name.c_str());\n\t\t\t\tprintf(\", \\\"version\\\": %d, \\\"extent\\\": %lld\", layer.version, layer.extent);\n\t\t\t\tprintf(\" }\");\n\t\t\t\tprintf(\", \\\"features\\\": [\\n\");\n\n\t\t\t\tfirst_layer = false;\n\t\t\t}\n\t\t}\n\n\t\t\/\/ X and Y are unsigned, so no need to check <0\n\t\tif (x > (1ULL << z) || y > (1ULL << z)) {\n\t\t\tfprintf(stderr, \"Impossible tile %d\/%u\/%u\\n\", z, x, y);\n\t\t\texit(EXIT_FAILURE);\n\t\t}\n\n\t\tlayer_to_geojson(stdout, layer, z, x, y, !pipeline, pipeline, pipeline, 0, 0, 0, !force);\n\n\t\tif (!pipeline) {\n\t\t\tif (describe) {\n\t\t\t\tprintf(\"] }\\n\");\n\t\t\t}\n\t\t}\n\t}\n\n\tif (!pipeline) {\n\t\tprintf(\"] }\\n\");\n\t}\n}\n\nvoid decode(char *fname, int z, unsigned x, unsigned y, std::set<std::string> const &to_decode, bool pipeline, bool stats) {\n\tsqlite3 *db;\n\tint oz = z;\n\tunsigned ox = x, oy = y;\n\n\tint fd = open(fname, O_RDONLY | O_CLOEXEC);\n\tif (fd >= 0) {\n\t\tstruct stat st;\n\t\tif (fstat(fd, &st) == 0) {\n\t\t\tif (st.st_size < 50 * 1024 * 1024) {\n\t\t\t\tchar *map = (char *) mmap(NULL, st.st_size, PROT_READ, MAP_PRIVATE, fd, 0);\n\t\t\t\tif (map != NULL && map != MAP_FAILED) {\n\t\t\t\t\tif (strcmp(map, \"SQLite format 3\") != 0) {\n\t\t\t\t\t\tif (z >= 0) {\n\t\t\t\t\t\t\tstd::string s = std::string(map, st.st_size);\n\t\t\t\t\t\t\thandle(s, z, x, y, 1, to_decode, pipeline, stats);\n\t\t\t\t\t\t\tmunmap(map, st.st_size);\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tfprintf(stderr, \"Must specify zoom\/x\/y to decode a single pbf file\\n\");\n\t\t\t\t\t\t\texit(EXIT_FAILURE);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tmunmap(map, st.st_size);\n\t\t\t}\n\t\t} else {\n\t\t\tperror(\"fstat\");\n\t\t}\n\t\tif (close(fd) != 0) {\n\t\t\tperror(\"close\");\n\t\t\texit(EXIT_FAILURE);\n\t\t}\n\t} else {\n\t\tperror(fname);\n\t}\n\n\tif (sqlite3_open(fname, &db) != SQLITE_OK) {\n\t\tfprintf(stderr, \"%s: %s\\n\", fname, sqlite3_errmsg(db));\n\t\texit(EXIT_FAILURE);\n\t}\n\n\tif (z < 0) {\n\t\tint within = 0;\n\n\t\tif (!pipeline && !stats) {\n\t\t\tprintf(\"{ \\\"type\\\": \\\"FeatureCollection\\\", \\\"properties\\\": {\\n\");\n\n\t\t\tconst char *sql2 = \"SELECT name, value from metadata order by name;\";\n\t\t\tsqlite3_stmt *stmt2;\n\t\t\tif (sqlite3_prepare_v2(db, sql2, -1, &stmt2, NULL) != SQLITE_OK) {\n\t\t\t\tfprintf(stderr, \"%s: select failed: %s\\n\", fname, sqlite3_errmsg(db));\n\t\t\t\texit(EXIT_FAILURE);\n\t\t\t}\n\n\t\t\twhile (sqlite3_step(stmt2) == SQLITE_ROW) {\n\t\t\t\tif (within) {\n\t\t\t\t\tprintf(\",\\n\");\n\t\t\t\t}\n\t\t\t\twithin = 1;\n\n\t\t\t\tconst unsigned char *name = sqlite3_column_text(stmt2, 0);\n\t\t\t\tconst unsigned char *value = sqlite3_column_text(stmt2, 1);\n\n\t\t\t\tif (name == NULL || value == NULL) {\n\t\t\t\t\tfprintf(stderr, \"Corrupt mbtiles file: null metadata\\n\");\n\t\t\t\t\texit(EXIT_FAILURE);\n\t\t\t\t}\n\n\t\t\t\tfprintq(stdout, (char *) name);\n\t\t\t\tprintf(\": \");\n\t\t\t\tfprintq(stdout, (char *) value);\n\t\t\t}\n\n\t\t\tsqlite3_finalize(stmt2);\n\t\t}\n\n\t\tif (stats) {\n\t\t\tprintf(\"[\\n\");\n\t\t}\n\n\t\tconst char *sql = \"SELECT tile_data, zoom_level, tile_column, tile_row from tiles where zoom_level between ? and ? order by zoom_level, tile_column, tile_row;\";\n\t\tsqlite3_stmt *stmt;\n\t\tif (sqlite3_prepare_v2(db, sql, -1, &stmt, NULL) != SQLITE_OK) {\n\t\t\tfprintf(stderr, \"%s: select failed: %s\\n\", fname, sqlite3_errmsg(db));\n\t\t\texit(EXIT_FAILURE);\n\t\t}\n\n\t\tsqlite3_bind_int(stmt, 1, minzoom);\n\t\tsqlite3_bind_int(stmt, 2, maxzoom);\n\n\t\tif (!pipeline && !stats) {\n\t\t\tprintf(\"\\n}, \\\"features\\\": [\\n\");\n\t\t}\n\n\t\twithin = 0;\n\t\twhile (sqlite3_step(stmt) == SQLITE_ROW) {\n\t\t\tif (!pipeline && !stats) {\n\t\t\t\tif (within) {\n\t\t\t\t\tprintf(\",\\n\");\n\t\t\t\t}\n\t\t\t\twithin = 1;\n\t\t\t}\n\t\t\tif (stats) {\n\t\t\t\tif (within) {\n\t\t\t\t\tprintf(\",\\n\");\n\t\t\t\t}\n\t\t\t\twithin = 1;\n\t\t\t}\n\n\t\t\tint len = sqlite3_column_bytes(stmt, 0);\n\t\t\tint tz = sqlite3_column_int(stmt, 1);\n\t\t\tint tx = sqlite3_column_int(stmt, 2);\n\t\t\tint ty = sqlite3_column_int(stmt, 3);\n\n\t\t\tif (tz < 0 || tz >= 32) {\n\t\t\t\tfprintf(stderr, \"Impossible zoom level %d in mbtiles\\n\", tz);\n\t\t\t\texit(EXIT_FAILURE);\n\t\t\t}\n\n\t\t\tty = (1LL << tz) - 1 - ty;\n\t\t\tconst char *s = (const char *) sqlite3_column_blob(stmt, 0);\n\n\t\t\thandle(std::string(s, len), tz, tx, ty, 1, to_decode, pipeline, stats);\n\t\t}\n\n\t\tif (!pipeline && !stats) {\n\t\t\tprintf(\"] }\\n\");\n\t\t}\n\t\tif (stats) {\n\t\t\tprintf(\"]\\n\");\n\t\t}\n\n\t\tsqlite3_finalize(stmt);\n\t} else {\n\t\tint handled = 0;\n\t\twhile (z >= 0 && !handled) {\n\t\t\tconst char *sql = \"SELECT tile_data from tiles where zoom_level = ? and tile_column = ? and tile_row = ?;\";\n\t\t\tsqlite3_stmt *stmt;\n\t\t\tif (sqlite3_prepare_v2(db, sql, -1, &stmt, NULL) != SQLITE_OK) {\n\t\t\t\tfprintf(stderr, \"%s: select failed: %s\\n\", fname, sqlite3_errmsg(db));\n\t\t\t\texit(EXIT_FAILURE);\n\t\t\t}\n\n\t\t\tsqlite3_bind_int(stmt, 1, z);\n\t\t\tsqlite3_bind_int(stmt, 2, x);\n\t\t\tsqlite3_bind_int(stmt, 3, (1LL << z) - 1 - y);\n\n\t\t\twhile (sqlite3_step(stmt) == SQLITE_ROW) {\n\t\t\t\tint len = sqlite3_column_bytes(stmt, 0);\n\t\t\t\tconst char *s = (const char *) sqlite3_column_blob(stmt, 0);\n\n\t\t\t\tif (z != oz) {\n\t\t\t\t\tfprintf(stderr, \"%s: Warning: using tile %d\/%u\/%u instead of %d\/%u\/%u\\n\", fname, z, x, y, oz, ox, oy);\n\t\t\t\t}\n\n\t\t\t\thandle(std::string(s, len), z, x, y, 0, to_decode, pipeline, stats);\n\t\t\t\thandled = 1;\n\t\t\t}\n\n\t\t\tsqlite3_finalize(stmt);\n\n\t\t\tz--;\n\t\t\tx \/= 2;\n\t\t\ty \/= 2;\n\t\t}\n\t}\n\n\tif (sqlite3_close(db) != SQLITE_OK) {\n\t\tfprintf(stderr, \"%s: could not close database: %s\\n\", fname, sqlite3_errmsg(db));\n\t\texit(EXIT_FAILURE);\n\t}\n}\n\nvoid usage(char **argv) {\n\tfprintf(stderr, \"Usage: %s [-s projection] [-Z minzoom] [-z maxzoom] [-l layer ...] file.mbtiles [zoom x y]\\n\", argv[0]);\n\texit(EXIT_FAILURE);\n}\n\nint main(int argc, char **argv) {\n\textern int optind;\n\textern char *optarg;\n\tint i;\n\tstd::set<std::string> to_decode;\n\tbool pipeline = false;\n\tbool stats = false;\n\n\tstruct option long_options[] = {\n\t\t{\"projection\", required_argument, 0, 's'},\n\t\t{\"maximum-zoom\", required_argument, 0, 'z'},\n\t\t{\"minimum-zoom\", required_argument, 0, 'Z'},\n\t\t{\"layer\", required_argument, 0, 'l'},\n\t\t{\"tag-layer-and-zoom\", no_argument, 0, 'c'},\n\t\t{\"stats\", no_argument, 0, 'S'},\n\t\t{\"force\", no_argument, 0, 'f'},\n\t\t{0, 0, 0, 0},\n\t};\n\n\tstd::string getopt_str;\n\tfor (size_t lo = 0; long_options[lo].name != NULL; lo++) {\n\t\tif (long_options[lo].val > ' ') {\n\t\t\tgetopt_str.push_back(long_options[lo].val);\n\n\t\t\tif (long_options[lo].has_arg == required_argument) {\n\t\t\t\tgetopt_str.push_back(':');\n\t\t\t}\n\t\t}\n\t}\n\n\twhile ((i = getopt_long(argc, argv, getopt_str.c_str(), long_options, NULL)) != -1) {\n\t\tswitch (i) {\n\t\tcase 0:\n\t\t\tbreak;\n\n\t\tcase 's':\n\t\t\tset_projection_or_exit(optarg);\n\t\t\tbreak;\n\n\t\tcase 'z':\n\t\t\tmaxzoom = atoi(optarg);\n\t\t\tbreak;\n\n\t\tcase 'Z':\n\t\t\tminzoom = atoi(optarg);\n\t\t\tbreak;\n\n\t\tcase 'l':\n\t\t\tto_decode.insert(optarg);\n\t\t\tbreak;\n\n\t\tcase 'c':\n\t\t\tpipeline = true;\n\t\t\tbreak;\n\n\t\tcase 'S':\n\t\t\tstats = true;\n\t\t\tbreak;\n\n\t\tcase 'f':\n\t\t\tforce = true;\n\t\t\tbreak;\n\n\t\tdefault:\n\t\t\tusage(argv);\n\t\t}\n\t}\n\n\tif (argc == optind + 4) {\n\t\tdecode(argv[optind], atoi(argv[optind + 1]), atoi(argv[optind + 2]), atoi(argv[optind + 3]), to_decode, pipeline, stats);\n\t} else if (argc == optind + 1) {\n\t\tdecode(argv[optind], -1, -1, -1, to_decode, pipeline, stats);\n\t} else {\n\t\tusage(argv);\n\t}\n\n\treturn 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n Copyright (c) 2006 Volker Krause <vkrause@kde.org>\n\n This library is free software; you can redistribute it and\/or modify it\n under the terms of the GNU Library General Public License as published by\n the Free Software Foundation; either version 2 of the License, or (at your\n option) any later version.\n\n This library is distributed in the hope that it will be useful, but WITHOUT\n ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public\n License for more details.\n\n You should have received a copy of the GNU Library General Public License\n along with this library; see the file COPYING.LIB. If not, write to the\n Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA\n 02110-1301, USA.\n*\/\n\n#include \"modify.h\"\n\n#include <akonadiconnection.h>\n#include <storage\/datastore.h>\n#include <storage\/entity.h>\n#include <storage\/transaction.h>\n#include \"libs\/imapparser_p.h\"\n#include \"imapstreamparser.h\"\n#include <handlerhelper.h>\n#include <response.h>\n#include <storage\/itemretriever.h>\n#include <storage\/selectquerybuilder.h>\n#include <storage\/collectionqueryhelper.h>\n#include <libs\/protocol_p.h>\n#include <search\/searchmanager.h>\n#include <akdebug.h>\n\nusing namespace Akonadi;\n\nModify::Modify( Scope::SelectionScope scope )\n : m_scope( scope )\n{\n}\n\nbool Modify::parseStream()\n{\n m_scope.parseScope( m_streamParser );\n SelectQueryBuilder<Collection> qb;\n CollectionQueryHelper::scopeToQuery( m_scope, connection(), qb );\n if ( !qb.exec() ) {\n throw HandlerException( \"Unable to execute collection query\" );\n }\n const Collection::List collections = qb.result();\n if ( collections.isEmpty() ) {\n throw HandlerException( \"No such collection\" );\n }\n if ( collections.size() > 1 ) { \/\/ TODO\n throw HandlerException( \"Mass-modifying collections is not yet implemented\" );\n }\n Collection collection = collections.first();\n\n \/\/TODO: do it cleanly with the streaming parser, which doesn't have look-ahead at this moment\n QByteArray line = m_streamParser->readUntilCommandEnd();\n m_streamParser->insertData( \"\\n\" );\n\n int p = 0;\n if ( ( p = line.indexOf( AKONADI_PARAM_PARENT ) ) > 0 ) {\n QByteArray tmp;\n ImapParser::parseString( line, tmp, p + 6 );\n const Collection newParent = HandlerHelper::collectionFromIdOrName( tmp );\n if ( newParent.isValid() && collection.parentId() != newParent.id()\n && collection.resourceId() != newParent.resourceId() ) {\n ItemRetriever retriever( connection() );\n retriever.setCollection( collection, true );\n retriever.setRetrieveFullPayload( true );\n if ( !retriever.exec() ) {\n throw HandlerException( retriever.lastError() );\n }\n }\n }\n\n DataStore *db = connection()->storageBackend();\n Transaction transaction( db );\n QList<QByteArray> changes;\n\n int pos = 0;\n while ( pos < line.length() ) {\n QByteArray type;\n pos = ImapParser::parseString( line, type, pos );\n if ( type == AKONADI_PARAM_MIMETYPE ) {\n QList<QByteArray> mimeTypes;\n pos = ImapParser::parseParenthesizedList( line, mimeTypes, pos );\n QStringList mts;\n Q_FOREACH ( const QByteArray &ba, mimeTypes ) {\n mts << QString::fromLatin1( ba );\n }\n MimeType::List currentMts = collection.mimeTypes();\n bool equal = true;\n Q_FOREACH ( const MimeType ¤tMt, currentMts ) {\n if ( mts.contains( currentMt.name() ) ) {\n mts.removeAll( currentMt.name() );\n continue;\n }\n equal = false;\n if ( !collection.removeMimeType( currentMt ) ) {\n throw HandlerException( \"Unable to remove collection mimetype\" );\n }\n }\n if ( !db->appendMimeTypeForCollection( collection.id(), mts ) ) {\n return failureResponse( \"Unable to add collection mimetypes\" );\n }\n if ( !equal || !mts.isEmpty() ) {\n changes.append( AKONADI_PARAM_MIMETYPE );\n }\n } else if ( type == AKONADI_PARAM_CACHEPOLICY ) {\n bool changed = false;\n pos = HandlerHelper::parseCachePolicy( line, collection, pos, &changed );\n if ( changed ) {\n changes.append( AKONADI_PARAM_CACHEPOLICY );\n }\n } else if ( type == AKONADI_PARAM_NAME ) {\n QString newName;\n pos = ImapParser::parseString( line, newName, pos );\n if ( collection.name() == newName ) {\n continue;\n }\n if ( !CollectionQueryHelper::hasAllowedName( collection, newName, collection.parentId() ) ) {\n throw HandlerException( \"Collection with the same name exists already\" );\n }\n collection.setName( newName );\n changes.append( AKONADI_PARAM_NAME );\n } else if ( type == AKONADI_PARAM_PARENT ) {\n qint64 newParent;\n bool ok = false;\n pos = ImapParser::parseNumber( line, newParent, &ok, pos );\n if ( !ok ) {\n return failureResponse( \"Invalid syntax\" );\n }\n if ( collection.parentId() == newParent ) {\n continue;\n }\n if ( !db->moveCollection( collection, Collection::retrieveById( newParent ) ) ) {\n return failureResponse( \"Unable to reparent collection\" );\n }\n changes.append( AKONADI_PARAM_PARENT );\n } else if ( type == AKONADI_PARAM_VIRTUAL ) {\n QString newValue;\n pos = ImapParser::parseString( line, newValue, pos );\n if ( newValue.toInt() != collection.isVirtual() ) {\n return failureResponse( \"Can't modify VIRTUAL collection flag\" );\n }\n } else if ( type == AKONADI_PARAM_REMOTEID ) {\n QString rid;\n pos = ImapParser::parseString( line, rid, pos );\n if ( rid == collection.remoteId() ) {\n continue;\n }\n if ( !connection()->isOwnerResource( collection ) ) {\n throw HandlerException( \"Only resources can modify remote identifiers\" );\n }\n collection.setRemoteId( rid );\n changes.append( AKONADI_PARAM_REMOTEID );\n } else if ( type == AKONADI_PARAM_REMOTEREVISION ) {\n QString remoteRevision;\n pos = ImapParser::parseString( line, remoteRevision, pos );\n if ( remoteRevision == collection.remoteRevision() ) {\n continue;\n }\n collection.setRemoteRevision( remoteRevision );\n changes.append( AKONADI_PARAM_REMOTEREVISION );\n } else if ( type == AKONADI_PARAM_PERSISTENTSEARCH ) {\n QByteArray tmp;\n QList<QByteArray> queryArgs;\n pos = ImapParser::parseString( line, tmp, pos );\n ImapParser::parseParenthesizedList( tmp, queryArgs );\n QString queryString, queryCollections, queryAttributes;\n QStringList attrs;\n for ( int i = 0; i < queryArgs.size() - 1; ++i ) {\n const QByteArray key = queryArgs.at( i );\n if ( key == AKONADI_PARAM_PERSISTENTSEARCH_QUERYSTRING ) {\n queryString = QString::fromUtf8( queryArgs.at( i + 1 ) );\n ++i;\n } else if ( key == AKONADI_PARAM_PERSISTENTSEARCH_QUERYCOLLECTIONS ) {\n QList<QByteArray> cols;\n ImapParser::parseParenthesizedList( queryArgs.at( i + 1), cols );\n queryCollections = QString::fromLatin1( ImapParser::join( cols, \" \" ) );\n ++i;\n } else if ( key == AKONADI_PARAM_PERSISTENTSEARCH_QUERYLANG ) {\n attrs << QString::fromLatin1( key ) << QString::fromUtf8( queryArgs.at( i + 1 ) );\n ++i;\n } else if ( key == AKONADI_PARAM_REMOTE ) {\n attrs << QString::fromLatin1( key );\n } else if ( key == AKONADI_PARAM_RECURSIVE ) {\n attrs << QString::fromLatin1( key );\n }\n }\n\n queryAttributes = attrs.join( QLatin1String( \" \" ) );\n\n if ( collection.queryAttributes() != queryAttributes\n || collection.queryString() != queryString\n || changes.contains( AKONADI_PARAM_MIMETYPE ) ) {\n collection.setQueryString( queryString );\n collection.setQueryAttributes( queryAttributes );\n\n SearchManager::instance()->updateSearch( collection, db->notificationCollector() );\n\n changes.append( AKONADI_PARAM_PERSISTENTSEARCH );\n }\n } else if ( type.isEmpty() ) {\n break; \/\/ input end\n } else {\n \/\/ custom attribute\n if ( type.startsWith( '-' ) ) {\n type = type.mid( 1 );\n if ( db->removeCollectionAttribute( collection, type ) ) {\n changes.append( type );\n }\n } else {\n QByteArray value;\n pos = ImapParser::parseString( line, value, pos );\n\n SelectQueryBuilder<CollectionAttribute> qb;\n qb.addValueCondition( CollectionAttribute::collectionIdColumn(), Query::Equals, collection.id() );\n qb.addValueCondition( CollectionAttribute::typeColumn(), Query::Equals, type );\n if ( !qb.exec() ) {\n throw HandlerException( \"Unable to retrieve collection attribute\" );\n }\n\n const CollectionAttribute::List attrs = qb.result();\n if ( attrs.isEmpty() ) {\n CollectionAttribute attr;\n attr.setCollectionId( collection.id() );\n attr.setType( type );\n attr.setValue( value );\n if ( !attr.insert() ) {\n throw HandlerException( \"Unable to add collection attribute\" );\n }\n changes.append( type );\n } else if ( attrs.size() == 1 ) {\n CollectionAttribute attr = attrs.first();\n if ( attr.value() == value ) {\n continue;\n }\n attr.setValue( value );\n if ( !attr.update() ) {\n throw HandlerException( \"Unable to update collection attribute\" );\n }\n changes.append( type );\n } else {\n throw HandlerException( \"WTF: more than one attribute with the same name\" );\n }\n }\n }\n }\n\n if ( !changes.isEmpty() ) {\n if ( collection.hasPendingChanges() && !collection.update() ) {\n return failureResponse( \"Unable to update collection\" );\n }\n db->notificationCollector()->collectionChanged( collection, changes );\n if ( !transaction.commit() ) {\n return failureResponse( \"Unable to commit transaction\" );\n }\n }\n\n Response response;\n response.setTag( tag() );\n response.setString( \"MODIFY done\" );\n Q_EMIT responseAvailable( response );\n return true;\n}\n<commit_msg>Fix parsing of persistent search attributes in MODIFY command<commit_after>\/*\n Copyright (c) 2006 Volker Krause <vkrause@kde.org>\n\n This library is free software; you can redistribute it and\/or modify it\n under the terms of the GNU Library General Public License as published by\n the Free Software Foundation; either version 2 of the License, or (at your\n option) any later version.\n\n This library is distributed in the hope that it will be useful, but WITHOUT\n ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public\n License for more details.\n\n You should have received a copy of the GNU Library General Public License\n along with this library; see the file COPYING.LIB. If not, write to the\n Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA\n 02110-1301, USA.\n*\/\n\n#include \"modify.h\"\n\n#include <akonadiconnection.h>\n#include <storage\/datastore.h>\n#include <storage\/entity.h>\n#include <storage\/transaction.h>\n#include \"libs\/imapparser_p.h\"\n#include \"imapstreamparser.h\"\n#include <handlerhelper.h>\n#include <response.h>\n#include <storage\/itemretriever.h>\n#include <storage\/selectquerybuilder.h>\n#include <storage\/collectionqueryhelper.h>\n#include <libs\/protocol_p.h>\n#include <search\/searchmanager.h>\n#include <akdebug.h>\n\nusing namespace Akonadi;\n\nModify::Modify( Scope::SelectionScope scope )\n : m_scope( scope )\n{\n}\n\nbool Modify::parseStream()\n{\n m_scope.parseScope( m_streamParser );\n SelectQueryBuilder<Collection> qb;\n CollectionQueryHelper::scopeToQuery( m_scope, connection(), qb );\n if ( !qb.exec() ) {\n throw HandlerException( \"Unable to execute collection query\" );\n }\n const Collection::List collections = qb.result();\n if ( collections.isEmpty() ) {\n throw HandlerException( \"No such collection\" );\n }\n if ( collections.size() > 1 ) { \/\/ TODO\n throw HandlerException( \"Mass-modifying collections is not yet implemented\" );\n }\n Collection collection = collections.first();\n\n \/\/TODO: do it cleanly with the streaming parser, which doesn't have look-ahead at this moment\n QByteArray line = m_streamParser->readUntilCommandEnd();\n m_streamParser->insertData( \"\\n\" );\n\n int p = 0;\n if ( ( p = line.indexOf( AKONADI_PARAM_PARENT ) ) > 0 ) {\n QByteArray tmp;\n ImapParser::parseString( line, tmp, p + 6 );\n const Collection newParent = HandlerHelper::collectionFromIdOrName( tmp );\n if ( newParent.isValid() && collection.parentId() != newParent.id()\n && collection.resourceId() != newParent.resourceId() ) {\n ItemRetriever retriever( connection() );\n retriever.setCollection( collection, true );\n retriever.setRetrieveFullPayload( true );\n if ( !retriever.exec() ) {\n throw HandlerException( retriever.lastError() );\n }\n }\n }\n\n DataStore *db = connection()->storageBackend();\n Transaction transaction( db );\n QList<QByteArray> changes;\n\n int pos = 0;\n while ( pos < line.length() ) {\n QByteArray type;\n pos = ImapParser::parseString( line, type, pos );\n if ( type == AKONADI_PARAM_MIMETYPE ) {\n QList<QByteArray> mimeTypes;\n pos = ImapParser::parseParenthesizedList( line, mimeTypes, pos );\n QStringList mts;\n Q_FOREACH ( const QByteArray &ba, mimeTypes ) {\n mts << QString::fromLatin1( ba );\n }\n MimeType::List currentMts = collection.mimeTypes();\n bool equal = true;\n Q_FOREACH ( const MimeType ¤tMt, currentMts ) {\n if ( mts.contains( currentMt.name() ) ) {\n mts.removeAll( currentMt.name() );\n continue;\n }\n equal = false;\n if ( !collection.removeMimeType( currentMt ) ) {\n throw HandlerException( \"Unable to remove collection mimetype\" );\n }\n }\n if ( !db->appendMimeTypeForCollection( collection.id(), mts ) ) {\n return failureResponse( \"Unable to add collection mimetypes\" );\n }\n if ( !equal || !mts.isEmpty() ) {\n changes.append( AKONADI_PARAM_MIMETYPE );\n }\n } else if ( type == AKONADI_PARAM_CACHEPOLICY ) {\n bool changed = false;\n pos = HandlerHelper::parseCachePolicy( line, collection, pos, &changed );\n if ( changed ) {\n changes.append( AKONADI_PARAM_CACHEPOLICY );\n }\n } else if ( type == AKONADI_PARAM_NAME ) {\n QString newName;\n pos = ImapParser::parseString( line, newName, pos );\n if ( collection.name() == newName ) {\n continue;\n }\n if ( !CollectionQueryHelper::hasAllowedName( collection, newName, collection.parentId() ) ) {\n throw HandlerException( \"Collection with the same name exists already\" );\n }\n collection.setName( newName );\n changes.append( AKONADI_PARAM_NAME );\n } else if ( type == AKONADI_PARAM_PARENT ) {\n qint64 newParent;\n bool ok = false;\n pos = ImapParser::parseNumber( line, newParent, &ok, pos );\n if ( !ok ) {\n return failureResponse( \"Invalid syntax\" );\n }\n if ( collection.parentId() == newParent ) {\n continue;\n }\n if ( !db->moveCollection( collection, Collection::retrieveById( newParent ) ) ) {\n return failureResponse( \"Unable to reparent collection\" );\n }\n changes.append( AKONADI_PARAM_PARENT );\n } else if ( type == AKONADI_PARAM_VIRTUAL ) {\n QString newValue;\n pos = ImapParser::parseString( line, newValue, pos );\n if ( newValue.toInt() != collection.isVirtual() ) {\n return failureResponse( \"Can't modify VIRTUAL collection flag\" );\n }\n } else if ( type == AKONADI_PARAM_REMOTEID ) {\n QString rid;\n pos = ImapParser::parseString( line, rid, pos );\n if ( rid == collection.remoteId() ) {\n continue;\n }\n if ( !connection()->isOwnerResource( collection ) ) {\n throw HandlerException( \"Only resources can modify remote identifiers\" );\n }\n collection.setRemoteId( rid );\n changes.append( AKONADI_PARAM_REMOTEID );\n } else if ( type == AKONADI_PARAM_REMOTEREVISION ) {\n QString remoteRevision;\n pos = ImapParser::parseString( line, remoteRevision, pos );\n if ( remoteRevision == collection.remoteRevision() ) {\n continue;\n }\n collection.setRemoteRevision( remoteRevision );\n changes.append( AKONADI_PARAM_REMOTEREVISION );\n } else if ( type == AKONADI_PARAM_PERSISTENTSEARCH ) {\n QByteArray tmp;\n QList<QByteArray> queryArgs;\n pos = ImapParser::parseString( line, tmp, pos );\n ImapParser::parseParenthesizedList( tmp, queryArgs );\n QString queryString, queryCollections, queryAttributes;\n QStringList attrs;\n for ( int i = 0; i < queryArgs.size(); ++i ) {\n const QByteArray key = queryArgs.at( i );\n qDebug() << key;\n if ( key == AKONADI_PARAM_PERSISTENTSEARCH_QUERYSTRING ) {\n queryString = QString::fromUtf8( queryArgs.at( i + 1 ) );\n ++i;\n } else if ( key == AKONADI_PARAM_PERSISTENTSEARCH_QUERYCOLLECTIONS ) {\n QList<QByteArray> cols;\n ImapParser::parseParenthesizedList( queryArgs.at( i + 1), cols );\n queryCollections = QString::fromLatin1( ImapParser::join( cols, \" \" ) );\n ++i;\n } else if ( key == AKONADI_PARAM_PERSISTENTSEARCH_QUERYLANG ) {\n \/\/ Ignore query lang\n ++i;\n } else if ( key == AKONADI_PARAM_REMOTE ) {\n attrs << QString::fromLatin1( key );\n } else if ( key == AKONADI_PARAM_RECURSIVE ) {\n attrs << QString::fromLatin1( key );\n }\n }\n\n queryAttributes = attrs.join( QLatin1String( \" \" ) );\n\n if ( collection.queryAttributes() != queryAttributes\n || collection.queryCollections() != queryCollections\n || collection.queryString() != queryString\n || changes.contains( AKONADI_PARAM_MIMETYPE ) ) {\n collection.setQueryString( queryString );\n collection.setQueryCollections( queryCollections );\n collection.setQueryAttributes( queryAttributes );\n\n SearchManager::instance()->updateSearch( collection, db->notificationCollector() );\n\n changes.append( AKONADI_PARAM_PERSISTENTSEARCH );\n }\n } else if ( type.isEmpty() ) {\n break; \/\/ input end\n } else {\n \/\/ custom attribute\n if ( type.startsWith( '-' ) ) {\n type = type.mid( 1 );\n if ( db->removeCollectionAttribute( collection, type ) ) {\n changes.append( type );\n }\n } else {\n QByteArray value;\n pos = ImapParser::parseString( line, value, pos );\n\n SelectQueryBuilder<CollectionAttribute> qb;\n qb.addValueCondition( CollectionAttribute::collectionIdColumn(), Query::Equals, collection.id() );\n qb.addValueCondition( CollectionAttribute::typeColumn(), Query::Equals, type );\n if ( !qb.exec() ) {\n throw HandlerException( \"Unable to retrieve collection attribute\" );\n }\n\n const CollectionAttribute::List attrs = qb.result();\n if ( attrs.isEmpty() ) {\n CollectionAttribute attr;\n attr.setCollectionId( collection.id() );\n attr.setType( type );\n attr.setValue( value );\n if ( !attr.insert() ) {\n throw HandlerException( \"Unable to add collection attribute\" );\n }\n changes.append( type );\n } else if ( attrs.size() == 1 ) {\n CollectionAttribute attr = attrs.first();\n if ( attr.value() == value ) {\n continue;\n }\n attr.setValue( value );\n if ( !attr.update() ) {\n throw HandlerException( \"Unable to update collection attribute\" );\n }\n changes.append( type );\n } else {\n throw HandlerException( \"WTF: more than one attribute with the same name\" );\n }\n }\n }\n }\n\n if ( !changes.isEmpty() ) {\n if ( collection.hasPendingChanges() && !collection.update() ) {\n return failureResponse( \"Unable to update collection\" );\n }\n db->notificationCollector()->collectionChanged( collection, changes );\n if ( !transaction.commit() ) {\n return failureResponse( \"Unable to commit transaction\" );\n }\n }\n\n Response response;\n response.setTag( tag() );\n response.setString( \"MODIFY done\" );\n Q_EMIT responseAvailable( response );\n return true;\n}\n<|endoftext|>"} {"text":"<commit_before>\/* json_endpoint.cc\n Jeremy Barnes, 22 February 2011\n Copyright (c) 2011 Datacratic. All rights reserved.\n\n*\/\n\n#include \"soa\/service\/\/json_endpoint.h\"\n#include \"jml\/arch\/exception.h\"\n#include \"soa\/jsoncpp\/json.h\"\n\n\nusing namespace ML;\nusing namespace std;\n\n\nnamespace Datacratic {\n\n\n\/*****************************************************************************\/\n\/* JSON CONNECTION HANDLER *\/\n\/*****************************************************************************\/\n\nJsonConnectionHandler::\nJsonConnectionHandler()\n{\n}\n\nvoid\nJsonConnectionHandler::\nhandleHttpHeader(const HttpHeader & header)\n{\n if (!header.contentType.empty()\n && header.contentType.find(\"json\") == string::npos\n && header.contentType.find(\"text\") == string::npos)\n throw Exception(\"invalid content type '%s' for JSON\",\n header.contentType.c_str());\n if (header.verb != \"POST\")\n throw Exception(\"invalid verb\");\n}\n\nvoid\nJsonConnectionHandler::\nhandleHttpPayload(const HttpHeader & header,\n const std::string & payload)\n{\n Json::Value request;\n\n const char * start = payload.c_str();\n const char * end = start + payload.length();\n \n while (end > start && end[-1] == '\\n') --end;\n \n try {\n Json::Reader reader;\n if (!reader.parse(start, end, request, false)) {\n \/\/cerr << \"JSON parsing error\" << endl;\n doError(\"parsing JSON payload: \"\n + reader.getFormattedErrorMessages());\n \/\/ return;\n }\n } catch (const std::exception & exc) {\n doError(\"parsing JSON request: \" + string(exc.what()));\n return;\n }\n\n addActivity(\"finishedJsonParsing\");\n\n handleJson(header, request, string(start, end));\n}\n\nvoid\nJsonConnectionHandler::\nhandleHttpChunk(const HttpHeader & header,\n const std::string & chunkHeader,\n const std::string & chunk)\n{\n Json::Value request;\n\n const char * start = chunk.c_str();\n const char * end = start + chunk.length();\n \n while (end > start && end[-1] == '\\n') --end;\n \n try {\n Json::Reader reader;\n if (!reader.parse(start, end, request, false)) {\n \/\/cerr << \"JSON parsing error\" << endl;\n doError(\"parsing JSON chunk: \"\n + reader.getFormattedErrorMessages());\n return;\n }\n } catch (const std::exception & exc) {\n doError(\"parsing JSON request: \" + string(exc.what()));\n return;\n }\n\n addActivity(\"finishedJsonParsing\");\n\n handleJson(header, request, string(start, end));\n}\n\n} \/\/ namespace Datacratic\n\n<commit_msg>rollback<commit_after>\/* json_endpoint.cc\n Jeremy Barnes, 22 February 2011\n Copyright (c) 2011 Datacratic. All rights reserved.\n\n*\/\n\n#include \"soa\/service\/\/json_endpoint.h\"\n#include \"jml\/arch\/exception.h\"\n#include \"soa\/jsoncpp\/json.h\"\n\n\nusing namespace ML;\nusing namespace std;\n\n\nnamespace Datacratic {\n\n\n\/*****************************************************************************\/\n\/* JSON CONNECTION HANDLER *\/\n\/*****************************************************************************\/\n\nJsonConnectionHandler::\nJsonConnectionHandler()\n{\n}\n\nvoid\nJsonConnectionHandler::\nhandleHttpHeader(const HttpHeader & header)\n{\n if (!header.contentType.empty()\n && header.contentType.find(\"json\") == string::npos\n && header.contentType.find(\"text\") == string::npos)\n throw Exception(\"invalid content type '%s' for JSON\",\n header.contentType.c_str());\n if (header.verb != \"POST\")\n throw Exception(\"invalid verb\");\n}\n\nvoid\nJsonConnectionHandler::\nhandleHttpPayload(const HttpHeader & header,\n const std::string & payload)\n{\n Json::Value request;\n\n const char * start = payload.c_str();\n const char * end = start + payload.length();\n \n while (end > start && end[-1] == '\\n') --end;\n \n try {\n Json::Reader reader;\n if (!reader.parse(start, end, request, false)) {\n \/\/cerr << \"JSON parsing error\" << endl;\n doError(\"parsing JSON payload: \"\n + reader.getFormattedErrorMessages());\n return;\n }\n } catch (const std::exception & exc) {\n doError(\"parsing JSON request: \" + string(exc.what()));\n return;\n }\n\n addActivity(\"finishedJsonParsing\");\n\n handleJson(header, request, string(start, end));\n}\n\nvoid\nJsonConnectionHandler::\nhandleHttpChunk(const HttpHeader & header,\n const std::string & chunkHeader,\n const std::string & chunk)\n{\n Json::Value request;\n\n const char * start = chunk.c_str();\n const char * end = start + chunk.length();\n \n while (end > start && end[-1] == '\\n') --end;\n \n try {\n Json::Reader reader;\n if (!reader.parse(start, end, request, false)) {\n \/\/cerr << \"JSON parsing error\" << endl;\n doError(\"parsing JSON chunk: \"\n + reader.getFormattedErrorMessages());\n return;\n }\n } catch (const std::exception & exc) {\n doError(\"parsing JSON request: \" + string(exc.what()));\n return;\n }\n\n addActivity(\"finishedJsonParsing\");\n\n handleJson(header, request, string(start, end));\n}\n\n} \/\/ namespace Datacratic\n\n<|endoftext|>"} {"text":"<commit_before>\/****************************************************************************\n**\n** Copyright (C) 2014 Digia Plc and\/or its subsidiary(-ies).\n** Contact: http:\/\/www.qt-project.org\/legal\n**\n** This file is part of Qt Creator.\n**\n** Commercial License Usage\n** Licensees holding valid commercial Qt licenses may use this file in\n** accordance with the commercial license agreement provided with the\n** Software or, alternatively, in accordance with the terms contained in\n** a written agreement between you and Digia. For licensing terms and\n** conditions see http:\/\/qt.digia.com\/licensing. For further information\n** use the contact form at http:\/\/qt.digia.com\/contact-us.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Digia gives you certain additional\n** rights. These rights are described in the Digia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n****************************************************************************\/\n\n#include \"genericproject.h\"\n\n#include \"genericbuildconfiguration.h\"\n#include \"genericmakestep.h\"\n#include \"genericprojectconstants.h\"\n\n#include <coreplugin\/documentmanager.h>\n#include <coreplugin\/icontext.h>\n#include <coreplugin\/icore.h>\n#include <coreplugin\/mimedatabase.h>\n#include <cpptools\/cpptoolsconstants.h>\n#include <cpptools\/cppmodelmanagerinterface.h>\n#include <extensionsystem\/pluginmanager.h>\n#include <projectexplorer\/abi.h>\n#include <projectexplorer\/buildsteplist.h>\n#include <projectexplorer\/headerpath.h>\n#include <projectexplorer\/kitinformation.h>\n#include <projectexplorer\/kitmanager.h>\n#include <projectexplorer\/projectexplorerconstants.h>\n#include <qtsupport\/customexecutablerunconfiguration.h>\n#include <utils\/fileutils.h>\n#include <utils\/qtcassert.h>\n\n#include <QDir>\n#include <QProcessEnvironment>\n\nusing namespace Core;\nusing namespace ProjectExplorer;\n\nnamespace GenericProjectManager {\nnamespace Internal {\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ GenericProject\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nGenericProject::GenericProject(Manager *manager, const QString &fileName)\n : m_manager(manager),\n m_fileName(fileName)\n{\n setId(Constants::GENERICPROJECT_ID);\n setProjectContext(Context(GenericProjectManager::Constants::PROJECTCONTEXT));\n setProjectLanguages(Context(ProjectExplorer::Constants::LANG_CXX));\n\n QFileInfo fileInfo(m_fileName);\n QDir dir = fileInfo.dir();\n\n m_projectName = fileInfo.completeBaseName();\n m_filesFileName = QFileInfo(dir, m_projectName + QLatin1String(\".files\")).absoluteFilePath();\n m_includesFileName = QFileInfo(dir, m_projectName + QLatin1String(\".includes\")).absoluteFilePath();\n m_configFileName = QFileInfo(dir, m_projectName + QLatin1String(\".config\")).absoluteFilePath();\n\n m_creatorIDocument = new GenericProjectFile(this, m_fileName, GenericProject::Everything);\n m_filesIDocument = new GenericProjectFile(this, m_filesFileName, GenericProject::Files);\n m_includesIDocument = new GenericProjectFile(this, m_includesFileName, GenericProject::Configuration);\n m_configIDocument = new GenericProjectFile(this, m_configFileName, GenericProject::Configuration);\n\n DocumentManager::addDocument(m_creatorIDocument);\n DocumentManager::addDocument(m_filesIDocument);\n DocumentManager::addDocument(m_includesIDocument);\n DocumentManager::addDocument(m_configIDocument);\n\n m_rootNode = new GenericProjectNode(this, m_creatorIDocument);\n\n m_manager->registerProject(this);\n}\n\nGenericProject::~GenericProject()\n{\n m_codeModelFuture.cancel();\n m_manager->unregisterProject(this);\n\n delete m_rootNode;\n}\n\nQString GenericProject::filesFileName() const\n{\n return m_filesFileName;\n}\n\nQString GenericProject::includesFileName() const\n{\n return m_includesFileName;\n}\n\nQString GenericProject::configFileName() const\n{\n return m_configFileName;\n}\n\nstatic QStringList readLines(const QString &absoluteFileName)\n{\n QStringList lines;\n\n QFile file(absoluteFileName);\n if (file.open(QFile::ReadOnly)) {\n QTextStream stream(&file);\n\n forever {\n QString line = stream.readLine();\n if (line.isNull())\n break;\n\n lines.append(line);\n }\n }\n\n return lines;\n}\n\nbool GenericProject::saveRawFileList(const QStringList &rawFileList)\n{\n \/\/ Make sure we can open the file for writing\n Utils::FileSaver saver(filesFileName(), QIODevice::Text);\n if (!saver.hasError()) {\n QTextStream stream(saver.file());\n foreach (const QString &filePath, rawFileList)\n stream << filePath << QLatin1Char('\\n');\n saver.setResult(&stream);\n }\n if (!saver.finalize(ICore::mainWindow()))\n return false;\n refresh(GenericProject::Files);\n return true;\n}\n\nbool GenericProject::addFiles(const QStringList &filePaths)\n{\n QStringList newList = m_rawFileList;\n\n QDir baseDir(QFileInfo(m_fileName).dir());\n foreach (const QString &filePath, filePaths)\n newList.append(baseDir.relativeFilePath(filePath));\n\n return saveRawFileList(newList);\n}\n\nbool GenericProject::removeFiles(const QStringList &filePaths)\n{\n QStringList newList = m_rawFileList;\n\n foreach (const QString &filePath, filePaths) {\n QHash<QString, QString>::iterator i = m_rawListEntries.find(filePath);\n if (i != m_rawListEntries.end())\n newList.removeOne(i.value());\n }\n\n return saveRawFileList(newList);\n}\n\nbool GenericProject::setFiles(const QStringList &filePaths)\n{\n QStringList newList;\n QDir baseDir(QFileInfo(m_fileName).dir());\n foreach (const QString &filePath, filePaths)\n newList.append(baseDir.relativeFilePath(filePath));\n\n return saveRawFileList(newList);\n}\n\nbool GenericProject::renameFile(const QString &filePath, const QString &newFilePath)\n{\n QStringList newList = m_rawFileList;\n\n QHash<QString, QString>::iterator i = m_rawListEntries.find(filePath);\n if (i != m_rawListEntries.end()) {\n int index = newList.indexOf(i.value());\n if (index != -1) {\n QDir baseDir(QFileInfo(m_fileName).dir());\n newList.replace(index, baseDir.relativeFilePath(newFilePath));\n }\n }\n\n return saveRawFileList(newList);\n}\n\nvoid GenericProject::parseProject(RefreshOptions options)\n{\n if (options & Files) {\n m_rawListEntries.clear();\n m_rawFileList = readLines(filesFileName());\n m_files = processEntries(m_rawFileList, &m_rawListEntries);\n }\n\n if (options & Configuration) {\n m_projectIncludePaths = processEntries(readLines(includesFileName()));\n\n \/\/ TODO: Possibly load some configuration from the project file\n \/\/QSettings projectInfo(m_fileName, QSettings::IniFormat);\n }\n\n if (options & Files)\n emit fileListChanged();\n}\n\nvoid GenericProject::refresh(RefreshOptions options)\n{\n QSet<QString> oldFileList;\n if (!(options & Configuration))\n oldFileList = m_files.toSet();\n\n parseProject(options);\n\n if (options & Files)\n m_rootNode->refresh(oldFileList);\n\n CppTools::CppModelManagerInterface *modelManager =\n CppTools::CppModelManagerInterface::instance();\n\n if (modelManager) {\n CppTools::CppModelManagerInterface::ProjectInfo pinfo = modelManager->projectInfo(this);\n pinfo.clearProjectParts();\n CppTools::ProjectPart::Ptr part(new CppTools::ProjectPart);\n part->project = this;\n part->displayName = displayName();\n part->projectFile = projectFilePath().toString();\n\n foreach (const QString &inc, projectIncludePaths())\n part->headerPaths += CppTools::ProjectPart::HeaderPath(\n inc, CppTools::ProjectPart::HeaderPath::IncludePath);\n\n Kit *k = activeTarget() ? activeTarget()->kit() : KitManager::defaultKit();\n if (ToolChain *tc = ToolChainKitInformation::toolChain(k)) {\n QStringList cflags;\n QStringList cxxflags;\n cxxflags << QLatin1String(\"-std=c++11\");\n\n part->evaluateToolchain(tc, cxxflags, cflags,\n SysRootKitInformation::sysRoot(k));\n }\n\n part->projectConfigFile = configFileName();\n\n \/\/ ### add _defines.\n\n \/\/ Add any C\/C++ files to be parsed\n CppTools::ProjectFileAdder adder(part->files);\n foreach (const QString &file, files())\n adder.maybeAdd(file);\n\n m_codeModelFuture.cancel();\n\n pinfo.appendProjectPart(part);\n setProjectLanguage(ProjectExplorer::Constants::LANG_CXX, !part->files.isEmpty());\n\n m_codeModelFuture = modelManager->updateProjectInfo(pinfo);\n }\n}\n\n\/**\n * Expands environment variables in the given \\a string when they are written\n * like $$(VARIABLE).\n *\/\nstatic void expandEnvironmentVariables(const QProcessEnvironment &env, QString &string)\n{\n static QRegExp candidate(QLatin1String(\"\\\\$\\\\$\\\\((.+)\\\\)\"));\n\n int index = candidate.indexIn(string);\n while (index != -1) {\n const QString value = env.value(candidate.cap(1));\n\n string.replace(index, candidate.matchedLength(), value);\n index += value.length();\n\n index = candidate.indexIn(string, index);\n }\n}\n\n\/**\n * Expands environment variables and converts the path from relative to the\n * project to an absolute path.\n *\n * The \\a map variable is an optional argument that will map the returned\n * absolute paths back to their original \\a entries.\n *\/\nQStringList GenericProject::processEntries(const QStringList &paths,\n QHash<QString, QString> *map) const\n{\n const QProcessEnvironment env = QProcessEnvironment::systemEnvironment();\n const QDir projectDir(QFileInfo(m_fileName).dir());\n\n QFileInfo fileInfo;\n QStringList absolutePaths;\n foreach (const QString &path, paths) {\n QString trimmedPath = path.trimmed();\n if (trimmedPath.isEmpty())\n continue;\n\n expandEnvironmentVariables(env, trimmedPath);\n\n trimmedPath = Utils::FileName::fromUserInput(trimmedPath).toString();\n\n fileInfo.setFile(projectDir, trimmedPath);\n if (fileInfo.exists()) {\n const QString absPath = fileInfo.absoluteFilePath();\n absolutePaths.append(absPath);\n if (map)\n map->insert(absPath, trimmedPath);\n }\n }\n absolutePaths.removeDuplicates();\n return absolutePaths;\n}\n\nQStringList GenericProject::projectIncludePaths() const\n{\n return m_projectIncludePaths;\n}\n\nQStringList GenericProject::files() const\n{\n return m_files;\n}\n\nQString GenericProject::displayName() const\n{\n return m_projectName;\n}\n\nIDocument *GenericProject::document() const\n{\n return m_creatorIDocument;\n}\n\nIProjectManager *GenericProject::projectManager() const\n{\n return m_manager;\n}\n\nGenericProjectNode *GenericProject::rootProjectNode() const\n{\n return m_rootNode;\n}\n\nQStringList GenericProject::files(FilesMode fileMode) const\n{\n Q_UNUSED(fileMode)\n return m_files;\n}\n\nQStringList GenericProject::buildTargets() const\n{\n QStringList targets;\n targets.append(QLatin1String(\"all\"));\n targets.append(QLatin1String(\"clean\"));\n return targets;\n}\n\nbool GenericProject::fromMap(const QVariantMap &map)\n{\n if (!Project::fromMap(map))\n return false;\n\n Kit *defaultKit = KitManager::defaultKit();\n if (!activeTarget() && defaultKit)\n addTarget(createTarget(defaultKit));\n\n \/\/ Sanity check: We need both a buildconfiguration and a runconfiguration!\n QList<Target *> targetList = targets();\n foreach (Target *t, targetList) {\n if (!t->activeBuildConfiguration()) {\n removeTarget(t);\n continue;\n }\n if (!t->activeRunConfiguration())\n t->addRunConfiguration(new QtSupport::CustomExecutableRunConfiguration(t));\n }\n\n refresh(Everything);\n return true;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ GenericProjectFile\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nGenericProjectFile::GenericProjectFile(GenericProject *parent, QString fileName, GenericProject::RefreshOptions options)\n : IDocument(parent),\n m_project(parent),\n m_options(options)\n{\n setId(\"Generic.ProjectFile\");\n setMimeType(QLatin1String(Constants::GENERICMIMETYPE));\n setFilePath(fileName);\n}\n\nbool GenericProjectFile::save(QString *, const QString &, bool)\n{\n return false;\n}\n\nQString GenericProjectFile::defaultPath() const\n{\n return QString();\n}\n\nQString GenericProjectFile::suggestedFileName() const\n{\n return QString();\n}\n\nbool GenericProjectFile::isModified() const\n{\n return false;\n}\n\nbool GenericProjectFile::isSaveAsAllowed() const\n{\n return false;\n}\n\nIDocument::ReloadBehavior GenericProjectFile::reloadBehavior(ChangeTrigger state, ChangeType type) const\n{\n Q_UNUSED(state)\n Q_UNUSED(type)\n return BehaviorSilent;\n}\n\nbool GenericProjectFile::reload(QString *errorString, ReloadFlag flag, ChangeType type)\n{\n Q_UNUSED(errorString)\n Q_UNUSED(flag)\n if (type == TypePermissions)\n return true;\n m_project->refresh(m_options);\n return true;\n}\n\n} \/\/ namespace Internal\n} \/\/ namespace GenericProjectManager\n<commit_msg>GenericProject: Fix logic for refresh(Everything)<commit_after>\/****************************************************************************\n**\n** Copyright (C) 2014 Digia Plc and\/or its subsidiary(-ies).\n** Contact: http:\/\/www.qt-project.org\/legal\n**\n** This file is part of Qt Creator.\n**\n** Commercial License Usage\n** Licensees holding valid commercial Qt licenses may use this file in\n** accordance with the commercial license agreement provided with the\n** Software or, alternatively, in accordance with the terms contained in\n** a written agreement between you and Digia. For licensing terms and\n** conditions see http:\/\/qt.digia.com\/licensing. For further information\n** use the contact form at http:\/\/qt.digia.com\/contact-us.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Digia gives you certain additional\n** rights. These rights are described in the Digia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n****************************************************************************\/\n\n#include \"genericproject.h\"\n\n#include \"genericbuildconfiguration.h\"\n#include \"genericmakestep.h\"\n#include \"genericprojectconstants.h\"\n\n#include <coreplugin\/documentmanager.h>\n#include <coreplugin\/icontext.h>\n#include <coreplugin\/icore.h>\n#include <coreplugin\/mimedatabase.h>\n#include <cpptools\/cpptoolsconstants.h>\n#include <cpptools\/cppmodelmanagerinterface.h>\n#include <extensionsystem\/pluginmanager.h>\n#include <projectexplorer\/abi.h>\n#include <projectexplorer\/buildsteplist.h>\n#include <projectexplorer\/headerpath.h>\n#include <projectexplorer\/kitinformation.h>\n#include <projectexplorer\/kitmanager.h>\n#include <projectexplorer\/projectexplorerconstants.h>\n#include <qtsupport\/customexecutablerunconfiguration.h>\n#include <utils\/fileutils.h>\n#include <utils\/qtcassert.h>\n\n#include <QDir>\n#include <QProcessEnvironment>\n\nusing namespace Core;\nusing namespace ProjectExplorer;\n\nnamespace GenericProjectManager {\nnamespace Internal {\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ GenericProject\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nGenericProject::GenericProject(Manager *manager, const QString &fileName)\n : m_manager(manager),\n m_fileName(fileName)\n{\n setId(Constants::GENERICPROJECT_ID);\n setProjectContext(Context(GenericProjectManager::Constants::PROJECTCONTEXT));\n setProjectLanguages(Context(ProjectExplorer::Constants::LANG_CXX));\n\n QFileInfo fileInfo(m_fileName);\n QDir dir = fileInfo.dir();\n\n m_projectName = fileInfo.completeBaseName();\n m_filesFileName = QFileInfo(dir, m_projectName + QLatin1String(\".files\")).absoluteFilePath();\n m_includesFileName = QFileInfo(dir, m_projectName + QLatin1String(\".includes\")).absoluteFilePath();\n m_configFileName = QFileInfo(dir, m_projectName + QLatin1String(\".config\")).absoluteFilePath();\n\n m_creatorIDocument = new GenericProjectFile(this, m_fileName, GenericProject::Everything);\n m_filesIDocument = new GenericProjectFile(this, m_filesFileName, GenericProject::Files);\n m_includesIDocument = new GenericProjectFile(this, m_includesFileName, GenericProject::Configuration);\n m_configIDocument = new GenericProjectFile(this, m_configFileName, GenericProject::Configuration);\n\n DocumentManager::addDocument(m_creatorIDocument);\n DocumentManager::addDocument(m_filesIDocument);\n DocumentManager::addDocument(m_includesIDocument);\n DocumentManager::addDocument(m_configIDocument);\n\n m_rootNode = new GenericProjectNode(this, m_creatorIDocument);\n\n m_manager->registerProject(this);\n}\n\nGenericProject::~GenericProject()\n{\n m_codeModelFuture.cancel();\n m_manager->unregisterProject(this);\n\n delete m_rootNode;\n}\n\nQString GenericProject::filesFileName() const\n{\n return m_filesFileName;\n}\n\nQString GenericProject::includesFileName() const\n{\n return m_includesFileName;\n}\n\nQString GenericProject::configFileName() const\n{\n return m_configFileName;\n}\n\nstatic QStringList readLines(const QString &absoluteFileName)\n{\n QStringList lines;\n\n QFile file(absoluteFileName);\n if (file.open(QFile::ReadOnly)) {\n QTextStream stream(&file);\n\n forever {\n QString line = stream.readLine();\n if (line.isNull())\n break;\n\n lines.append(line);\n }\n }\n\n return lines;\n}\n\nbool GenericProject::saveRawFileList(const QStringList &rawFileList)\n{\n \/\/ Make sure we can open the file for writing\n Utils::FileSaver saver(filesFileName(), QIODevice::Text);\n if (!saver.hasError()) {\n QTextStream stream(saver.file());\n foreach (const QString &filePath, rawFileList)\n stream << filePath << QLatin1Char('\\n');\n saver.setResult(&stream);\n }\n if (!saver.finalize(ICore::mainWindow()))\n return false;\n refresh(GenericProject::Files);\n return true;\n}\n\nbool GenericProject::addFiles(const QStringList &filePaths)\n{\n QStringList newList = m_rawFileList;\n\n QDir baseDir(QFileInfo(m_fileName).dir());\n foreach (const QString &filePath, filePaths)\n newList.append(baseDir.relativeFilePath(filePath));\n\n return saveRawFileList(newList);\n}\n\nbool GenericProject::removeFiles(const QStringList &filePaths)\n{\n QStringList newList = m_rawFileList;\n\n foreach (const QString &filePath, filePaths) {\n QHash<QString, QString>::iterator i = m_rawListEntries.find(filePath);\n if (i != m_rawListEntries.end())\n newList.removeOne(i.value());\n }\n\n return saveRawFileList(newList);\n}\n\nbool GenericProject::setFiles(const QStringList &filePaths)\n{\n QStringList newList;\n QDir baseDir(QFileInfo(m_fileName).dir());\n foreach (const QString &filePath, filePaths)\n newList.append(baseDir.relativeFilePath(filePath));\n\n return saveRawFileList(newList);\n}\n\nbool GenericProject::renameFile(const QString &filePath, const QString &newFilePath)\n{\n QStringList newList = m_rawFileList;\n\n QHash<QString, QString>::iterator i = m_rawListEntries.find(filePath);\n if (i != m_rawListEntries.end()) {\n int index = newList.indexOf(i.value());\n if (index != -1) {\n QDir baseDir(QFileInfo(m_fileName).dir());\n newList.replace(index, baseDir.relativeFilePath(newFilePath));\n }\n }\n\n return saveRawFileList(newList);\n}\n\nvoid GenericProject::parseProject(RefreshOptions options)\n{\n if (options & Files) {\n m_rawListEntries.clear();\n m_rawFileList = readLines(filesFileName());\n m_files = processEntries(m_rawFileList, &m_rawListEntries);\n }\n\n if (options & Configuration) {\n m_projectIncludePaths = processEntries(readLines(includesFileName()));\n\n \/\/ TODO: Possibly load some configuration from the project file\n \/\/QSettings projectInfo(m_fileName, QSettings::IniFormat);\n }\n\n if (options & Files)\n emit fileListChanged();\n}\n\nvoid GenericProject::refresh(RefreshOptions options)\n{\n QSet<QString> oldFileList;\n if (options & Files)\n oldFileList = m_files.toSet();\n\n parseProject(options);\n\n if (options & Files)\n m_rootNode->refresh(oldFileList);\n\n CppTools::CppModelManagerInterface *modelManager =\n CppTools::CppModelManagerInterface::instance();\n\n if (modelManager) {\n CppTools::CppModelManagerInterface::ProjectInfo pinfo = modelManager->projectInfo(this);\n pinfo.clearProjectParts();\n CppTools::ProjectPart::Ptr part(new CppTools::ProjectPart);\n part->project = this;\n part->displayName = displayName();\n part->projectFile = projectFilePath().toString();\n\n foreach (const QString &inc, projectIncludePaths())\n part->headerPaths += CppTools::ProjectPart::HeaderPath(\n inc, CppTools::ProjectPart::HeaderPath::IncludePath);\n\n Kit *k = activeTarget() ? activeTarget()->kit() : KitManager::defaultKit();\n if (ToolChain *tc = ToolChainKitInformation::toolChain(k)) {\n QStringList cflags;\n QStringList cxxflags;\n cxxflags << QLatin1String(\"-std=c++11\");\n\n part->evaluateToolchain(tc, cxxflags, cflags,\n SysRootKitInformation::sysRoot(k));\n }\n\n part->projectConfigFile = configFileName();\n\n \/\/ ### add _defines.\n\n \/\/ Add any C\/C++ files to be parsed\n CppTools::ProjectFileAdder adder(part->files);\n foreach (const QString &file, files())\n adder.maybeAdd(file);\n\n m_codeModelFuture.cancel();\n\n pinfo.appendProjectPart(part);\n setProjectLanguage(ProjectExplorer::Constants::LANG_CXX, !part->files.isEmpty());\n\n m_codeModelFuture = modelManager->updateProjectInfo(pinfo);\n }\n}\n\n\/**\n * Expands environment variables in the given \\a string when they are written\n * like $$(VARIABLE).\n *\/\nstatic void expandEnvironmentVariables(const QProcessEnvironment &env, QString &string)\n{\n static QRegExp candidate(QLatin1String(\"\\\\$\\\\$\\\\((.+)\\\\)\"));\n\n int index = candidate.indexIn(string);\n while (index != -1) {\n const QString value = env.value(candidate.cap(1));\n\n string.replace(index, candidate.matchedLength(), value);\n index += value.length();\n\n index = candidate.indexIn(string, index);\n }\n}\n\n\/**\n * Expands environment variables and converts the path from relative to the\n * project to an absolute path.\n *\n * The \\a map variable is an optional argument that will map the returned\n * absolute paths back to their original \\a entries.\n *\/\nQStringList GenericProject::processEntries(const QStringList &paths,\n QHash<QString, QString> *map) const\n{\n const QProcessEnvironment env = QProcessEnvironment::systemEnvironment();\n const QDir projectDir(QFileInfo(m_fileName).dir());\n\n QFileInfo fileInfo;\n QStringList absolutePaths;\n foreach (const QString &path, paths) {\n QString trimmedPath = path.trimmed();\n if (trimmedPath.isEmpty())\n continue;\n\n expandEnvironmentVariables(env, trimmedPath);\n\n trimmedPath = Utils::FileName::fromUserInput(trimmedPath).toString();\n\n fileInfo.setFile(projectDir, trimmedPath);\n if (fileInfo.exists()) {\n const QString absPath = fileInfo.absoluteFilePath();\n absolutePaths.append(absPath);\n if (map)\n map->insert(absPath, trimmedPath);\n }\n }\n absolutePaths.removeDuplicates();\n return absolutePaths;\n}\n\nQStringList GenericProject::projectIncludePaths() const\n{\n return m_projectIncludePaths;\n}\n\nQStringList GenericProject::files() const\n{\n return m_files;\n}\n\nQString GenericProject::displayName() const\n{\n return m_projectName;\n}\n\nIDocument *GenericProject::document() const\n{\n return m_creatorIDocument;\n}\n\nIProjectManager *GenericProject::projectManager() const\n{\n return m_manager;\n}\n\nGenericProjectNode *GenericProject::rootProjectNode() const\n{\n return m_rootNode;\n}\n\nQStringList GenericProject::files(FilesMode fileMode) const\n{\n Q_UNUSED(fileMode)\n return m_files;\n}\n\nQStringList GenericProject::buildTargets() const\n{\n QStringList targets;\n targets.append(QLatin1String(\"all\"));\n targets.append(QLatin1String(\"clean\"));\n return targets;\n}\n\nbool GenericProject::fromMap(const QVariantMap &map)\n{\n if (!Project::fromMap(map))\n return false;\n\n Kit *defaultKit = KitManager::defaultKit();\n if (!activeTarget() && defaultKit)\n addTarget(createTarget(defaultKit));\n\n \/\/ Sanity check: We need both a buildconfiguration and a runconfiguration!\n QList<Target *> targetList = targets();\n foreach (Target *t, targetList) {\n if (!t->activeBuildConfiguration()) {\n removeTarget(t);\n continue;\n }\n if (!t->activeRunConfiguration())\n t->addRunConfiguration(new QtSupport::CustomExecutableRunConfiguration(t));\n }\n\n refresh(Everything);\n return true;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ GenericProjectFile\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nGenericProjectFile::GenericProjectFile(GenericProject *parent, QString fileName, GenericProject::RefreshOptions options)\n : IDocument(parent),\n m_project(parent),\n m_options(options)\n{\n setId(\"Generic.ProjectFile\");\n setMimeType(QLatin1String(Constants::GENERICMIMETYPE));\n setFilePath(fileName);\n}\n\nbool GenericProjectFile::save(QString *, const QString &, bool)\n{\n return false;\n}\n\nQString GenericProjectFile::defaultPath() const\n{\n return QString();\n}\n\nQString GenericProjectFile::suggestedFileName() const\n{\n return QString();\n}\n\nbool GenericProjectFile::isModified() const\n{\n return false;\n}\n\nbool GenericProjectFile::isSaveAsAllowed() const\n{\n return false;\n}\n\nIDocument::ReloadBehavior GenericProjectFile::reloadBehavior(ChangeTrigger state, ChangeType type) const\n{\n Q_UNUSED(state)\n Q_UNUSED(type)\n return BehaviorSilent;\n}\n\nbool GenericProjectFile::reload(QString *errorString, ReloadFlag flag, ChangeType type)\n{\n Q_UNUSED(errorString)\n Q_UNUSED(flag)\n if (type == TypePermissions)\n return true;\n m_project->refresh(m_options);\n return true;\n}\n\n} \/\/ namespace Internal\n} \/\/ namespace GenericProjectManager\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: stgavl.cxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: rt $ $Date: 2005-09-08 07:39:58 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\n#include \"stgavl.hxx\"\n#pragma hdrstop\n\nStgAvlNode::StgAvlNode()\n{\n pLeft = pRight = NULL;\n nBalance = nId = 0;\n}\n\nStgAvlNode::~StgAvlNode()\n{\n delete pLeft;\n delete pRight;\n}\n\nStgAvlNode* StgAvlNode::Find( StgAvlNode* pFind )\n{\n StgAvlNode* p = this;\n while( p )\n {\n short nRes = p->Compare( pFind );\n if( !nRes )\n return p;\n else p = ( nRes < 0 ) ? p->pLeft : p->pRight;\n }\n return NULL;\n}\n\n\/\/ find point to add node to AVL tree and returns\n\/\/ +\/0\/- for >\/=\/< previous\n\nshort StgAvlNode::Locate\n ( StgAvlNode* pFind,\n StgAvlNode** pPivot, StgAvlNode **pParent, StgAvlNode** pPrev )\n{\n short nRes = 0;\n StgAvlNode* pCur = this;\n *pParent = *pPrev = NULL;\n *pPivot = this;\n\n \/\/ search tree for insertion point\n\n while( pCur != NULL )\n {\n \/\/ check for pPivot\n if( pCur->nBalance != 0 )\n *pPivot = pCur, *pParent = *pPrev;\n \/\/ save pPrev location and see what direction to go\n *pPrev = pCur;\n nRes = pCur->Compare( pFind );\n if( nRes == 0 )\n break;\n else pCur = ( nRes < 0 ) ? pCur->pLeft : pCur->pRight;\n }\n return( nRes );\n}\n\n\/\/ adjust balance factors in AVL tree from pivot down.\n\/\/ Returns delta balance.\n\nshort StgAvlNode::Adjust( StgAvlNode** pHeavy, StgAvlNode* pNew )\n{\n StgAvlNode* pCur = this;\n short nDelta;\n \/\/ no traversing\n if( pCur == pNew )\n return nBalance;\n short nRes = Compare( pNew );\n if( nRes > 0 )\n {\n *pHeavy = pCur = pRight;\n nDelta = -1;\n }\n else\n {\n *pHeavy = pCur = pLeft;\n nDelta = 1;\n }\n nBalance = 0;\n while( pCur != pNew )\n {\n nRes = pCur->Compare( pNew );\n if( nRes > 0 )\n {\n \/\/ height of right increases by 1\n pCur->nBalance = -1;\n pCur = pCur->pRight;\n }\n else\n {\n \/\/ height of left increases by 1\n pCur->nBalance = 1;\n pCur = pCur->pLeft;\n }\n }\n nBalance += nDelta;\n return nDelta;\n}\n\n\/\/ perform LL rotation and return new root\n\nStgAvlNode* StgAvlNode::RotLL()\n{\n StgAvlNode *pHeavy = pLeft;\n pLeft = pHeavy->pRight;\n pHeavy->pRight = this;\n pHeavy->nBalance = nBalance = 0;\n return pHeavy;\n}\n\n\/\/ perform LR rotation and return new root\n\nStgAvlNode* StgAvlNode::RotLR()\n{\n\n StgAvlNode* pHeavy = pLeft;\n StgAvlNode* pNewRoot = pHeavy->pRight;\n\n pHeavy->pRight = pNewRoot->pLeft;\n pLeft = pNewRoot->pRight;\n pNewRoot->pLeft = pHeavy;\n pNewRoot->pRight = this;\n\n switch( pNewRoot->nBalance )\n {\n case 1: \/\/ LR( b )\n nBalance = -1;\n pHeavy->nBalance = 0;\n break;\n case -1: \/\/ LR( c )\n pHeavy->nBalance = 1;\n nBalance = 0;\n break;\n case 0: \/\/ LR( a )\n nBalance = 0;\n pHeavy->nBalance = 0;\n break;\n }\n pNewRoot->nBalance = 0;\n return pNewRoot;\n}\n\n\/\/ perform RR rotation and return new root\n\nStgAvlNode* StgAvlNode::RotRR()\n{\n StgAvlNode* pHeavy = pRight;\n pRight = pHeavy->pLeft;\n pHeavy->pLeft = this;\n nBalance = pHeavy->nBalance = 0;\n return pHeavy;\n}\n\n\/\/ perform the RL rotation and return the new root\n\nStgAvlNode* StgAvlNode::RotRL()\n{\n StgAvlNode* pHeavy = pRight;\n StgAvlNode* pNewRoot = pHeavy->pLeft;\n pHeavy->pLeft = pNewRoot->pRight;\n pRight = pNewRoot->pLeft;\n pNewRoot->pRight = pHeavy;\n pNewRoot->pLeft = this;\n switch( pNewRoot->nBalance )\n {\n case -1: \/\/ RL( b )\n nBalance = 1;\n pHeavy->nBalance = 0;\n break;\n case 1: \/\/ RL( c )\n pHeavy->nBalance = -1;\n nBalance = 0;\n break;\n case 0: \/\/ RL( a )\n nBalance = 0;\n pHeavy->nBalance = 0;\n break;\n }\n pNewRoot->nBalance = 0;\n return pNewRoot;\n}\n\n\/\/ Remove a tree element. Return the removed element or NULL.\n\nStgAvlNode* StgAvlNode::Rem( StgAvlNode** p, StgAvlNode* pDel, BOOL bPtrs )\n{\n if( *p )\n {\n StgAvlNode* pCur = *p;\n short nRes = bPtrs ? ( pCur == pDel ) : pCur->Compare( pDel );\n if( !nRes )\n {\n \/\/ Element found: remove\n if( !pCur->pRight )\n {\n *p = pCur->pLeft; pCur->pLeft = NULL;\n }\n else if( !pCur->pLeft )\n {\n *p = pCur->pRight; pCur->pRight = NULL;\n }\n else\n {\n \/\/ The damn element has two leaves. Get the\n \/\/ rightmost element of the left subtree (which\n \/\/ is lexically before this element) and replace\n \/\/ this element with the element found.\n StgAvlNode* last = pCur;\n StgAvlNode* l;\n for( l = pCur->pLeft;\n l->pRight; last = l, l = l->pRight ) {}\n \/\/ remove the element from chain\n if( l == last->pRight )\n last->pRight = l->pLeft;\n else\n last->pLeft = l->pLeft;\n \/\/ perform the replacement\n l->pLeft = pCur->pLeft;\n l->pRight = pCur->pRight;\n *p = l;\n \/\/ delete the element\n pCur->pLeft = pCur->pRight = NULL;\n }\n return pCur;\n }\n else\n {\n if( nRes < 0 )\n return Rem( &pCur->pLeft, pDel, bPtrs );\n else\n return Rem( &pCur->pRight, pDel, bPtrs );\n }\n }\n return NULL;\n}\n\n\/\/ Enumerate the tree for later iteration\n\nvoid StgAvlNode::Enum( short& n )\n{\n if( this )\n {\n if( pLeft )\n pLeft->Enum( n );\n nId = n++;\n if( pRight )\n pRight->Enum( n );\n }\n}\n\n\/\/ Add node to AVL tree.\n\/\/ Return FALSE if the element already exists.\n\nBOOL StgAvlNode::Insert( StgAvlNode** pRoot, StgAvlNode* pIns )\n{\n StgAvlNode* pPivot, *pHeavy, *pNewRoot, *pParent, *pPrev;\n \/\/ special case - empty tree\n if( *pRoot == NULL )\n {\n *pRoot = pIns;\n return TRUE;\n }\n \/\/ find insertion point and return if already present\n short nRes = (*pRoot)->Locate( pIns, &pPivot, &pParent, &pPrev );\n if( !nRes )\n return FALSE;\n \/\/ add new node\n if( nRes < 0 )\n pPrev->pLeft = pIns;\n else\n pPrev->pRight = pIns;\n \/\/ rebalance tree\n short nDelta = pPivot->Adjust( &pHeavy, pIns );\n if( pPivot->nBalance >= 2 || pPivot->nBalance <= -2 )\n {\n pHeavy = ( nDelta < 0 ) ? pPivot->pRight : pPivot->pLeft;\n \/\/ left imbalance\n if( nDelta > 0 )\n if( pHeavy->nBalance == 1 )\n pNewRoot = pPivot->RotLL();\n else\n pNewRoot = pPivot->RotLR();\n \/\/ right imbalance\n else if( pHeavy->nBalance == -1 )\n pNewRoot = pPivot->RotRR();\n else\n pNewRoot = pPivot->RotRL();\n \/\/ relink balanced subtree\n if( pParent == NULL )\n *pRoot = pNewRoot;\n else if( pPivot == pParent->pLeft )\n pParent->pLeft = pNewRoot;\n else if( pPivot == pParent->pRight )\n pParent->pRight = pNewRoot;\n }\n return TRUE;\n}\n\n\/\/ Remove node from tree. Returns TRUE is found and removed.\n\/\/ Actually delete if bDel\n\nBOOL StgAvlNode::Remove( StgAvlNode** pRoot, StgAvlNode* pDel, BOOL bDel )\n{\n \/\/ special case - empty tree\n if( *pRoot == NULL )\n return FALSE;\n \/\/ delete the element\n pDel = Rem( pRoot, pDel, FALSE );\n if( pDel )\n {\n if( bDel )\n delete pDel;\n \/\/ Rebalance the tree the hard way\n \/\/ OS 22.09.95: Auf MD's Wunsch auskommentiert wg. Absturz\n\/* StgAvlNode* pNew = NULL;\n while( *pRoot )\n {\n StgAvlNode* p = Rem( pRoot, *pRoot, FALSE );\n Insert( &pNew, p );\n }\n *pRoot = pNew;*\/\n return TRUE;\n }\n else\n return FALSE;\n}\n\n\/\/ Move node to a different tree. Returns TRUE is found and moved. This routine\n\/\/ may be called when the key has changed.\n\nBOOL StgAvlNode::Move\n ( StgAvlNode** pRoot1, StgAvlNode** pRoot2, StgAvlNode* pMove )\n{\n \/\/ special case - empty tree\n if( *pRoot1 == NULL )\n return FALSE;\n pMove = Rem( pRoot1, pMove, FALSE );\n if( pMove )\n return Insert( pRoot2, pMove );\n else\n return FALSE;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ class AvlIterator \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/ The iterator walks through a tree one entry by one.\n\nStgAvlIterator::StgAvlIterator( StgAvlNode* p )\n{\n pRoot = p;\n nCount = 0;\n if( p )\n p->Enum( nCount );\n}\n\nStgAvlNode* StgAvlIterator::Find( short n )\n{\n StgAvlNode* p = pRoot;\n while( p )\n {\n if( n == p->nId )\n break;\n else p = ( n < p->nId ) ? p->pLeft : p->pRight;\n }\n return p;\n}\n\nStgAvlNode* StgAvlIterator::First()\n{\n nCur = -1;\n return Next();\n}\n\nStgAvlNode* StgAvlIterator::Last()\n{\n nCur = nCount;\n return Prev();\n}\n\nStgAvlNode* StgAvlIterator::Next()\n{\n return Find( ++nCur );\n}\n\nStgAvlNode* StgAvlIterator::Prev()\n{\n return Find( --nCur );\n}\n\n<commit_msg>INTEGRATION: CWS warnings01 (1.3.10); FILE MERGED 2006\/04\/06 14:23:14 cd 1.3.10.3: #55991# Make warning free for MSVC compiler 2005\/10\/28 16:15:28 pl 1.3.10.2: #i55991# removed warnings for solaris platform 2005\/10\/21 16:25:09 pl 1.3.10.1: #i55991# removed warnings for linux platform<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: stgavl.cxx,v $\n *\n * $Revision: 1.4 $\n *\n * last change: $Author: hr $ $Date: 2006-06-20 05:53:53 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\n#include \"stgavl.hxx\"\n\nStgAvlNode::StgAvlNode()\n{\n pLeft = pRight = NULL;\n nBalance = nId = 0;\n}\n\nStgAvlNode::~StgAvlNode()\n{\n delete pLeft;\n delete pRight;\n}\n\nStgAvlNode* StgAvlNode::Find( StgAvlNode* pFind )\n{\n StgAvlNode* p = this;\n while( p )\n {\n short nRes = p->Compare( pFind );\n if( !nRes )\n return p;\n else p = ( nRes < 0 ) ? p->pLeft : p->pRight;\n }\n return NULL;\n}\n\n\/\/ find point to add node to AVL tree and returns\n\/\/ +\/0\/- for >\/=\/< previous\n\nshort StgAvlNode::Locate\n ( StgAvlNode* pFind,\n StgAvlNode** pPivot, StgAvlNode **pParent, StgAvlNode** pPrev )\n{\n short nRes = 0;\n StgAvlNode* pCur = this;\n *pParent = *pPrev = NULL;\n *pPivot = this;\n\n \/\/ search tree for insertion point\n\n while( pCur != NULL )\n {\n \/\/ check for pPivot\n if( pCur->nBalance != 0 )\n *pPivot = pCur, *pParent = *pPrev;\n \/\/ save pPrev location and see what direction to go\n *pPrev = pCur;\n nRes = pCur->Compare( pFind );\n if( nRes == 0 )\n break;\n else pCur = ( nRes < 0 ) ? pCur->pLeft : pCur->pRight;\n }\n return( nRes );\n}\n\n\/\/ adjust balance factors in AVL tree from pivot down.\n\/\/ Returns delta balance.\n\nshort StgAvlNode::Adjust( StgAvlNode** pHeavy, StgAvlNode* pNew )\n{\n StgAvlNode* pCur = this;\n short nDelta;\n \/\/ no traversing\n if( pCur == pNew )\n return nBalance;\n short nRes = Compare( pNew );\n if( nRes > 0 )\n {\n *pHeavy = pCur = pRight;\n nDelta = -1;\n }\n else\n {\n *pHeavy = pCur = pLeft;\n nDelta = 1;\n }\n nBalance = 0;\n while( pCur != pNew )\n {\n nRes = pCur->Compare( pNew );\n if( nRes > 0 )\n {\n \/\/ height of right increases by 1\n pCur->nBalance = -1;\n pCur = pCur->pRight;\n }\n else\n {\n \/\/ height of left increases by 1\n pCur->nBalance = 1;\n pCur = pCur->pLeft;\n }\n }\n nBalance = nBalance + nDelta;\n return nDelta;\n}\n\n\/\/ perform LL rotation and return new root\n\nStgAvlNode* StgAvlNode::RotLL()\n{\n StgAvlNode *pHeavy = pLeft;\n pLeft = pHeavy->pRight;\n pHeavy->pRight = this;\n pHeavy->nBalance = nBalance = 0;\n return pHeavy;\n}\n\n\/\/ perform LR rotation and return new root\n\nStgAvlNode* StgAvlNode::RotLR()\n{\n\n StgAvlNode* pHeavy = pLeft;\n StgAvlNode* pNewRoot = pHeavy->pRight;\n\n pHeavy->pRight = pNewRoot->pLeft;\n pLeft = pNewRoot->pRight;\n pNewRoot->pLeft = pHeavy;\n pNewRoot->pRight = this;\n\n switch( pNewRoot->nBalance )\n {\n case 1: \/\/ LR( b )\n nBalance = -1;\n pHeavy->nBalance = 0;\n break;\n case -1: \/\/ LR( c )\n pHeavy->nBalance = 1;\n nBalance = 0;\n break;\n case 0: \/\/ LR( a )\n nBalance = 0;\n pHeavy->nBalance = 0;\n break;\n }\n pNewRoot->nBalance = 0;\n return pNewRoot;\n}\n\n\/\/ perform RR rotation and return new root\n\nStgAvlNode* StgAvlNode::RotRR()\n{\n StgAvlNode* pHeavy = pRight;\n pRight = pHeavy->pLeft;\n pHeavy->pLeft = this;\n nBalance = pHeavy->nBalance = 0;\n return pHeavy;\n}\n\n\/\/ perform the RL rotation and return the new root\n\nStgAvlNode* StgAvlNode::RotRL()\n{\n StgAvlNode* pHeavy = pRight;\n StgAvlNode* pNewRoot = pHeavy->pLeft;\n pHeavy->pLeft = pNewRoot->pRight;\n pRight = pNewRoot->pLeft;\n pNewRoot->pRight = pHeavy;\n pNewRoot->pLeft = this;\n switch( pNewRoot->nBalance )\n {\n case -1: \/\/ RL( b )\n nBalance = 1;\n pHeavy->nBalance = 0;\n break;\n case 1: \/\/ RL( c )\n pHeavy->nBalance = -1;\n nBalance = 0;\n break;\n case 0: \/\/ RL( a )\n nBalance = 0;\n pHeavy->nBalance = 0;\n break;\n }\n pNewRoot->nBalance = 0;\n return pNewRoot;\n}\n\n\/\/ Remove a tree element. Return the removed element or NULL.\n\nStgAvlNode* StgAvlNode::Rem( StgAvlNode** p, StgAvlNode* pDel, BOOL bPtrs )\n{\n if( *p )\n {\n StgAvlNode* pCur = *p;\n short nRes = bPtrs ? short( pCur == pDel ) : short(pCur->Compare( pDel ));\n if( !nRes )\n {\n \/\/ Element found: remove\n if( !pCur->pRight )\n {\n *p = pCur->pLeft; pCur->pLeft = NULL;\n }\n else if( !pCur->pLeft )\n {\n *p = pCur->pRight; pCur->pRight = NULL;\n }\n else\n {\n \/\/ The damn element has two leaves. Get the\n \/\/ rightmost element of the left subtree (which\n \/\/ is lexically before this element) and replace\n \/\/ this element with the element found.\n StgAvlNode* last = pCur;\n StgAvlNode* l;\n for( l = pCur->pLeft;\n l->pRight; last = l, l = l->pRight ) {}\n \/\/ remove the element from chain\n if( l == last->pRight )\n last->pRight = l->pLeft;\n else\n last->pLeft = l->pLeft;\n \/\/ perform the replacement\n l->pLeft = pCur->pLeft;\n l->pRight = pCur->pRight;\n *p = l;\n \/\/ delete the element\n pCur->pLeft = pCur->pRight = NULL;\n }\n return pCur;\n }\n else\n {\n if( nRes < 0 )\n return Rem( &pCur->pLeft, pDel, bPtrs );\n else\n return Rem( &pCur->pRight, pDel, bPtrs );\n }\n }\n return NULL;\n}\n\n\/\/ Enumerate the tree for later iteration\n\nvoid StgAvlNode::StgEnum( short& n )\n{\n if( this )\n {\n if( pLeft )\n pLeft->StgEnum( n );\n nId = n++;\n if( pRight )\n pRight->StgEnum( n );\n }\n}\n\n\/\/ Add node to AVL tree.\n\/\/ Return FALSE if the element already exists.\n\nBOOL StgAvlNode::Insert( StgAvlNode** pRoot, StgAvlNode* pIns )\n{\n StgAvlNode* pPivot, *pHeavy, *pNewRoot, *pParent, *pPrev;\n \/\/ special case - empty tree\n if( *pRoot == NULL )\n {\n *pRoot = pIns;\n return TRUE;\n }\n \/\/ find insertion point and return if already present\n short nRes = (*pRoot)->Locate( pIns, &pPivot, &pParent, &pPrev );\n if( !nRes )\n return FALSE;\n \/\/ add new node\n if( nRes < 0 )\n pPrev->pLeft = pIns;\n else\n pPrev->pRight = pIns;\n \/\/ rebalance tree\n short nDelta = pPivot->Adjust( &pHeavy, pIns );\n if( pPivot->nBalance >= 2 || pPivot->nBalance <= -2 )\n {\n pHeavy = ( nDelta < 0 ) ? pPivot->pRight : pPivot->pLeft;\n \/\/ left imbalance\n if( nDelta > 0 )\n if( pHeavy->nBalance == 1 )\n pNewRoot = pPivot->RotLL();\n else\n pNewRoot = pPivot->RotLR();\n \/\/ right imbalance\n else if( pHeavy->nBalance == -1 )\n pNewRoot = pPivot->RotRR();\n else\n pNewRoot = pPivot->RotRL();\n \/\/ relink balanced subtree\n if( pParent == NULL )\n *pRoot = pNewRoot;\n else if( pPivot == pParent->pLeft )\n pParent->pLeft = pNewRoot;\n else if( pPivot == pParent->pRight )\n pParent->pRight = pNewRoot;\n }\n return TRUE;\n}\n\n\/\/ Remove node from tree. Returns TRUE is found and removed.\n\/\/ Actually delete if bDel\n\nBOOL StgAvlNode::Remove( StgAvlNode** pRoot, StgAvlNode* pDel, BOOL bDel )\n{\n \/\/ special case - empty tree\n if( *pRoot == NULL )\n return FALSE;\n \/\/ delete the element\n pDel = Rem( pRoot, pDel, FALSE );\n if( pDel )\n {\n if( bDel )\n delete pDel;\n \/\/ Rebalance the tree the hard way\n \/\/ OS 22.09.95: Auf MD's Wunsch auskommentiert wg. Absturz\n\/* StgAvlNode* pNew = NULL;\n while( *pRoot )\n {\n StgAvlNode* p = Rem( pRoot, *pRoot, FALSE );\n Insert( &pNew, p );\n }\n *pRoot = pNew;*\/\n return TRUE;\n }\n else\n return FALSE;\n}\n\n\/\/ Move node to a different tree. Returns TRUE is found and moved. This routine\n\/\/ may be called when the key has changed.\n\nBOOL StgAvlNode::Move\n ( StgAvlNode** pRoot1, StgAvlNode** pRoot2, StgAvlNode* pMove )\n{\n \/\/ special case - empty tree\n if( *pRoot1 == NULL )\n return FALSE;\n pMove = Rem( pRoot1, pMove, FALSE );\n if( pMove )\n return Insert( pRoot2, pMove );\n else\n return FALSE;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ class AvlIterator \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/ The iterator walks through a tree one entry by one.\n\nStgAvlIterator::StgAvlIterator( StgAvlNode* p )\n{\n pRoot = p;\n nCount = 0;\n if( p )\n p->StgEnum( nCount );\n}\n\nStgAvlNode* StgAvlIterator::Find( short n )\n{\n StgAvlNode* p = pRoot;\n while( p )\n {\n if( n == p->nId )\n break;\n else p = ( n < p->nId ) ? p->pLeft : p->pRight;\n }\n return p;\n}\n\nStgAvlNode* StgAvlIterator::First()\n{\n nCur = -1;\n return Next();\n}\n\nStgAvlNode* StgAvlIterator::Last()\n{\n nCur = nCount;\n return Prev();\n}\n\nStgAvlNode* StgAvlIterator::Next()\n{\n return Find( ++nCur );\n}\n\nStgAvlNode* StgAvlIterator::Prev()\n{\n return Find( --nCur );\n}\n\n<|endoftext|>"} {"text":"<commit_before><commit_msg>WebBrowser: clang format<commit_after><|endoftext|>"} {"text":"<commit_before>\/*********************************************************************\n * Software License Agreement (BSD License)\n *\n * Copyright (c) 2019, PickNik LLC\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following\n * disclaimer in the documentation and\/or other materials provided\n * with the distribution.\n * * Neither the name of PickNik LLC nor the names of its\n * contributors may be used to endorse or promote products derived\n * from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *********************************************************************\/\n\n\/* Author: Henning Kayser *\/\n\n#include <stdexcept>\n\n#include <moveit\/moveit_cpp\/planning_component.h>\n#include <moveit\/kinematic_constraints\/utils.h>\n#include <moveit\/planning_pipeline\/planning_pipeline.h>\n#include <moveit\/planning_scene_monitor\/planning_scene_monitor.h>\n#include <moveit\/robot_state\/conversions.h>\n\nnamespace moveit_cpp\n{\nconstexpr char LOGNAME[] = \"planning_component\";\n\nPlanningComponent::PlanningComponent(const std::string& group_name, const MoveItCppPtr& moveit_cpp)\n : nh_(moveit_cpp->getNodeHandle()), moveit_cpp_(moveit_cpp), group_name_(group_name)\n{\n joint_model_group_ = moveit_cpp_->getRobotModel()->getJointModelGroup(group_name);\n if (!joint_model_group_)\n {\n std::string error = \"Could not find joint model group '\" + group_name + \"'.\";\n ROS_FATAL_STREAM_NAMED(LOGNAME, error);\n throw std::runtime_error(error);\n }\n planning_pipeline_names_ = moveit_cpp_->getPlanningPipelineNames(group_name);\n plan_request_parameters_.load(nh_);\n ROS_DEBUG_STREAM_NAMED(\n LOGNAME, \"Plan request parameters loaded with --\"\n << \" planning_pipeline: \" << plan_request_parameters_.planning_pipeline << \",\"\n << \" planner_id: \" << plan_request_parameters_.planner_id << \",\"\n << \" planning_time: \" << plan_request_parameters_.planning_time << \",\"\n << \" planning_attempts: \" << plan_request_parameters_.planning_attempts << \",\"\n << \" max_velocity_scaling_factor: \" << plan_request_parameters_.max_velocity_scaling_factor << \",\"\n << \" max_acceleration_scaling_factor: \" << plan_request_parameters_.max_acceleration_scaling_factor);\n}\n\nPlanningComponent::PlanningComponent(const std::string& group_name, const ros::NodeHandle& nh)\n : PlanningComponent(group_name, std::make_shared<MoveItCpp>(nh))\n{\n}\n\nPlanningComponent::~PlanningComponent()\n{\n ROS_INFO_NAMED(LOGNAME, \"Deleting PlanningComponent '%s'\", group_name_.c_str());\n clearContents();\n}\n\nconst std::vector<std::string> PlanningComponent::getNamedTargetStates()\n{\n if (joint_model_group_)\n {\n return joint_model_group_->getDefaultStateNames();\n }\n else\n {\n ROS_WARN_NAMED(LOGNAME, \"Unable to find joint group with name '%s'.\", group_name_.c_str());\n }\n\n std::vector<std::string> empty;\n return empty;\n}\n\nconst std::string& PlanningComponent::getPlanningGroupName() const\n{\n return group_name_;\n}\n\nbool PlanningComponent::setPathConstraints(const moveit_msgs::Constraints& path_constraints)\n{\n current_path_constraints_ = path_constraints;\n return true;\n}\n\nPlanningComponent::PlanSolution PlanningComponent::plan(const PlanRequestParameters& parameters)\n{\n last_plan_solution_ = std::make_shared<PlanSolution>();\n if (!joint_model_group_)\n {\n ROS_ERROR_NAMED(LOGNAME, \"Failed to retrieve joint model group for name '%s'.\", group_name_.c_str());\n last_plan_solution_->error_code = moveit::core::MoveItErrorCode::INVALID_GROUP_NAME;\n return *last_plan_solution_;\n }\n\n \/\/ Clone current planning scene\n planning_scene_monitor::PlanningSceneMonitorPtr planning_scene_monitor =\n moveit_cpp_->getPlanningSceneMonitorNonConst();\n planning_scene_monitor->updateFrameTransforms();\n planning_scene_monitor->lockSceneRead(); \/\/ LOCK planning scene\n planning_scene::PlanningScenePtr planning_scene =\n planning_scene::PlanningScene::clone(planning_scene_monitor->getPlanningScene());\n planning_scene_monitor->unlockSceneRead(); \/\/ UNLOCK planning scene\n planning_scene_monitor.reset(); \/\/ release this pointer\n\n \/\/ Init MotionPlanRequest\n ::planning_interface::MotionPlanRequest req;\n req.group_name = group_name_;\n req.planner_id = parameters.planner_id;\n req.num_planning_attempts = std::max(1, parameters.planning_attempts);\n req.allowed_planning_time = parameters.planning_time;\n req.max_velocity_scaling_factor = parameters.max_velocity_scaling_factor;\n req.max_acceleration_scaling_factor = parameters.max_acceleration_scaling_factor;\n if (workspace_parameters_set_)\n req.workspace_parameters = workspace_parameters_;\n\n \/\/ Set start state\n moveit::core::RobotStatePtr start_state = considered_start_state_;\n if (!start_state)\n start_state = moveit_cpp_->getCurrentState();\n start_state->update();\n moveit::core::robotStateToRobotStateMsg(*start_state, req.start_state);\n planning_scene->setCurrentState(*start_state);\n\n \/\/ Set goal constraints\n if (current_goal_constraints_.empty())\n {\n ROS_ERROR_NAMED(LOGNAME, \"No goal constraints set for planning request\");\n last_plan_solution_->error_code = moveit::core::MoveItErrorCode::INVALID_GOAL_CONSTRAINTS;\n return *last_plan_solution_;\n }\n req.goal_constraints = current_goal_constraints_;\n\n \/\/ Set path constraints\n req.path_constraints = current_path_constraints_;\n\n \/\/ Run planning attempt\n ::planning_interface::MotionPlanResponse res;\n if (planning_pipeline_names_.find(parameters.planning_pipeline) == planning_pipeline_names_.end())\n {\n ROS_ERROR_NAMED(LOGNAME, \"No planning pipeline available for name '%s'\", parameters.planning_pipeline.c_str());\n last_plan_solution_->error_code = moveit::core::MoveItErrorCode::FAILURE;\n return *last_plan_solution_;\n }\n const planning_pipeline::PlanningPipelinePtr pipeline =\n moveit_cpp_->getPlanningPipelines().at(parameters.planning_pipeline);\n pipeline->generatePlan(planning_scene, req, res);\n last_plan_solution_->error_code = res.error_code_.val;\n if (res.error_code_.val != res.error_code_.SUCCESS)\n {\n ROS_ERROR(\"Could not compute plan successfully\");\n return *last_plan_solution_;\n }\n last_plan_solution_->start_state = req.start_state;\n last_plan_solution_->trajectory = res.trajectory_;\n \/\/ TODO(henningkayser): Visualize trajectory\n \/\/ std::vector<const moveit::core::LinkModel*> eef_links;\n \/\/ if (joint_model_group->getEndEffectorTips(eef_links))\n \/\/{\n \/\/ for (const auto& eef_link : eef_links)\n \/\/ {\n \/\/ ROS_INFO_STREAM(\"Publishing trajectory for end effector \" << eef_link->getName());\n \/\/ visual_tools_->publishTrajectoryLine(last_solution_trajectory_, eef_link);\n \/\/ visual_tools_->publishTrajectoryPath(last_solution_trajectory_, false);\n \/\/ visual_tools_->publishRobotState(last_solution_trajectory_->getLastWayPoint(), rviz_visual_tools::TRANSLUCENT);\n \/\/ }\n \/\/}\n return *last_plan_solution_;\n}\n\nPlanningComponent::PlanSolution PlanningComponent::plan()\n{\n return plan(plan_request_parameters_);\n}\n\nbool PlanningComponent::setStartState(const moveit::core::RobotState& start_state)\n{\n considered_start_state_ = std::make_shared<moveit::core::RobotState>(start_state);\n return true;\n}\n\nmoveit::core::RobotStatePtr PlanningComponent::getStartState()\n{\n if (considered_start_state_)\n return considered_start_state_;\n else\n {\n moveit::core::RobotStatePtr s;\n moveit_cpp_->getCurrentState(s, 1.0);\n return s;\n }\n}\n\nbool PlanningComponent::setStartState(const std::string& start_state_name)\n{\n const auto& named_targets = getNamedTargetStates();\n if (std::find(named_targets.begin(), named_targets.end(), start_state_name) == named_targets.end())\n {\n ROS_ERROR_NAMED(LOGNAME, \"No predefined joint state found for target name '%s'\", start_state_name.c_str());\n return false;\n }\n moveit::core::RobotState start_state(moveit_cpp_->getRobotModel());\n start_state.setToDefaultValues(joint_model_group_, start_state_name);\n return setStartState(start_state);\n}\n\nvoid PlanningComponent::setStartStateToCurrentState()\n{\n considered_start_state_.reset();\n}\n\nstd::map<std::string, double> PlanningComponent::getNamedTargetStateValues(const std::string& name)\n{\n \/\/ TODO(henningkayser): verify result\n std::map<std::string, double> positions;\n joint_model_group_->getVariableDefaultPositions(name, positions);\n return positions;\n}\n\nvoid PlanningComponent::setWorkspace(double minx, double miny, double minz, double maxx, double maxy, double maxz)\n{\n workspace_parameters_.header.frame_id = moveit_cpp_->getRobotModel()->getModelFrame();\n workspace_parameters_.header.stamp = ros::Time::now();\n workspace_parameters_.min_corner.x = minx;\n workspace_parameters_.min_corner.y = miny;\n workspace_parameters_.min_corner.z = minz;\n workspace_parameters_.max_corner.x = maxx;\n workspace_parameters_.max_corner.y = maxy;\n workspace_parameters_.max_corner.z = maxz;\n workspace_parameters_set_ = true;\n}\n\nvoid PlanningComponent::unsetWorkspace()\n{\n workspace_parameters_set_ = false;\n}\n\nbool PlanningComponent::setGoal(const std::vector<moveit_msgs::Constraints>& goal_constraints)\n{\n current_goal_constraints_ = goal_constraints;\n return true;\n}\n\nbool PlanningComponent::setGoal(const moveit::core::RobotState& goal_state)\n{\n current_goal_constraints_ = { kinematic_constraints::constructGoalConstraints(goal_state, joint_model_group_) };\n return true;\n}\n\nbool PlanningComponent::setGoal(const geometry_msgs::PoseStamped& goal_pose, const std::string& link_name)\n{\n current_goal_constraints_ = { kinematic_constraints::constructGoalConstraints(link_name, goal_pose) };\n return true;\n}\n\nbool PlanningComponent::setGoal(const std::string& goal_state_name)\n{\n const auto& named_targets = getNamedTargetStates();\n if (std::find(named_targets.begin(), named_targets.end(), goal_state_name) == named_targets.end())\n {\n ROS_ERROR_NAMED(LOGNAME, \"No predefined joint state found for target name '%s'\", goal_state_name.c_str());\n return false;\n }\n moveit::core::RobotState goal_state(moveit_cpp_->getRobotModel());\n goal_state.setToDefaultValues(joint_model_group_, goal_state_name);\n return setGoal(goal_state);\n}\n\nbool PlanningComponent::execute(bool blocking)\n{\n if (!last_plan_solution_)\n {\n ROS_ERROR_NAMED(LOGNAME, \"There is no successfull plan to execute\");\n return false;\n }\n\n \/\/ TODO(henningkayser): parameterize timestamps if required\n \/\/ trajectory_processing::TimeOptimalTrajectoryGeneration totg;\n \/\/ if (!totg.computeTimeStamps(*last_solution_trajectory_, max_velocity_scaling_factor_,\n \/\/ max_acceleration_scaling_factor_))\n \/\/{\n \/\/ ROS_ERROR(\"Failed to parameterize trajectory\");\n \/\/ return false;\n \/\/}\n return moveit_cpp_->execute(group_name_, last_plan_solution_->trajectory, blocking);\n}\n\nconst PlanningComponent::PlanSolutionPtr PlanningComponent::getLastPlanSolution()\n{\n return last_plan_solution_;\n}\n\nvoid PlanningComponent::clearContents()\n{\n considered_start_state_.reset();\n last_plan_solution_.reset();\n current_goal_constraints_.clear();\n moveit_cpp_.reset();\n planning_pipeline_names_.clear();\n}\n} \/\/ namespace moveit_cpp\n<commit_msg>Fix typo (#3255)<commit_after>\/*********************************************************************\n * Software License Agreement (BSD License)\n *\n * Copyright (c) 2019, PickNik LLC\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following\n * disclaimer in the documentation and\/or other materials provided\n * with the distribution.\n * * Neither the name of PickNik LLC nor the names of its\n * contributors may be used to endorse or promote products derived\n * from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *********************************************************************\/\n\n\/* Author: Henning Kayser *\/\n\n#include <stdexcept>\n\n#include <moveit\/moveit_cpp\/planning_component.h>\n#include <moveit\/kinematic_constraints\/utils.h>\n#include <moveit\/planning_pipeline\/planning_pipeline.h>\n#include <moveit\/planning_scene_monitor\/planning_scene_monitor.h>\n#include <moveit\/robot_state\/conversions.h>\n\nnamespace moveit_cpp\n{\nconstexpr char LOGNAME[] = \"planning_component\";\n\nPlanningComponent::PlanningComponent(const std::string& group_name, const MoveItCppPtr& moveit_cpp)\n : nh_(moveit_cpp->getNodeHandle()), moveit_cpp_(moveit_cpp), group_name_(group_name)\n{\n joint_model_group_ = moveit_cpp_->getRobotModel()->getJointModelGroup(group_name);\n if (!joint_model_group_)\n {\n std::string error = \"Could not find joint model group '\" + group_name + \"'.\";\n ROS_FATAL_STREAM_NAMED(LOGNAME, error);\n throw std::runtime_error(error);\n }\n planning_pipeline_names_ = moveit_cpp_->getPlanningPipelineNames(group_name);\n plan_request_parameters_.load(nh_);\n ROS_DEBUG_STREAM_NAMED(\n LOGNAME, \"Plan request parameters loaded with --\"\n << \" planning_pipeline: \" << plan_request_parameters_.planning_pipeline << \",\"\n << \" planner_id: \" << plan_request_parameters_.planner_id << \",\"\n << \" planning_time: \" << plan_request_parameters_.planning_time << \",\"\n << \" planning_attempts: \" << plan_request_parameters_.planning_attempts << \",\"\n << \" max_velocity_scaling_factor: \" << plan_request_parameters_.max_velocity_scaling_factor << \",\"\n << \" max_acceleration_scaling_factor: \" << plan_request_parameters_.max_acceleration_scaling_factor);\n}\n\nPlanningComponent::PlanningComponent(const std::string& group_name, const ros::NodeHandle& nh)\n : PlanningComponent(group_name, std::make_shared<MoveItCpp>(nh))\n{\n}\n\nPlanningComponent::~PlanningComponent()\n{\n ROS_INFO_NAMED(LOGNAME, \"Deleting PlanningComponent '%s'\", group_name_.c_str());\n clearContents();\n}\n\nconst std::vector<std::string> PlanningComponent::getNamedTargetStates()\n{\n if (joint_model_group_)\n {\n return joint_model_group_->getDefaultStateNames();\n }\n else\n {\n ROS_WARN_NAMED(LOGNAME, \"Unable to find joint group with name '%s'.\", group_name_.c_str());\n }\n\n std::vector<std::string> empty;\n return empty;\n}\n\nconst std::string& PlanningComponent::getPlanningGroupName() const\n{\n return group_name_;\n}\n\nbool PlanningComponent::setPathConstraints(const moveit_msgs::Constraints& path_constraints)\n{\n current_path_constraints_ = path_constraints;\n return true;\n}\n\nPlanningComponent::PlanSolution PlanningComponent::plan(const PlanRequestParameters& parameters)\n{\n last_plan_solution_ = std::make_shared<PlanSolution>();\n if (!joint_model_group_)\n {\n ROS_ERROR_NAMED(LOGNAME, \"Failed to retrieve joint model group for name '%s'.\", group_name_.c_str());\n last_plan_solution_->error_code = moveit::core::MoveItErrorCode::INVALID_GROUP_NAME;\n return *last_plan_solution_;\n }\n\n \/\/ Clone current planning scene\n planning_scene_monitor::PlanningSceneMonitorPtr planning_scene_monitor =\n moveit_cpp_->getPlanningSceneMonitorNonConst();\n planning_scene_monitor->updateFrameTransforms();\n planning_scene_monitor->lockSceneRead(); \/\/ LOCK planning scene\n planning_scene::PlanningScenePtr planning_scene =\n planning_scene::PlanningScene::clone(planning_scene_monitor->getPlanningScene());\n planning_scene_monitor->unlockSceneRead(); \/\/ UNLOCK planning scene\n planning_scene_monitor.reset(); \/\/ release this pointer\n\n \/\/ Init MotionPlanRequest\n ::planning_interface::MotionPlanRequest req;\n req.group_name = group_name_;\n req.planner_id = parameters.planner_id;\n req.num_planning_attempts = std::max(1, parameters.planning_attempts);\n req.allowed_planning_time = parameters.planning_time;\n req.max_velocity_scaling_factor = parameters.max_velocity_scaling_factor;\n req.max_acceleration_scaling_factor = parameters.max_acceleration_scaling_factor;\n if (workspace_parameters_set_)\n req.workspace_parameters = workspace_parameters_;\n\n \/\/ Set start state\n moveit::core::RobotStatePtr start_state = considered_start_state_;\n if (!start_state)\n start_state = moveit_cpp_->getCurrentState();\n start_state->update();\n moveit::core::robotStateToRobotStateMsg(*start_state, req.start_state);\n planning_scene->setCurrentState(*start_state);\n\n \/\/ Set goal constraints\n if (current_goal_constraints_.empty())\n {\n ROS_ERROR_NAMED(LOGNAME, \"No goal constraints set for planning request\");\n last_plan_solution_->error_code = moveit::core::MoveItErrorCode::INVALID_GOAL_CONSTRAINTS;\n return *last_plan_solution_;\n }\n req.goal_constraints = current_goal_constraints_;\n\n \/\/ Set path constraints\n req.path_constraints = current_path_constraints_;\n\n \/\/ Run planning attempt\n ::planning_interface::MotionPlanResponse res;\n if (planning_pipeline_names_.find(parameters.planning_pipeline) == planning_pipeline_names_.end())\n {\n ROS_ERROR_NAMED(LOGNAME, \"No planning pipeline available for name '%s'\", parameters.planning_pipeline.c_str());\n last_plan_solution_->error_code = moveit::core::MoveItErrorCode::FAILURE;\n return *last_plan_solution_;\n }\n const planning_pipeline::PlanningPipelinePtr pipeline =\n moveit_cpp_->getPlanningPipelines().at(parameters.planning_pipeline);\n pipeline->generatePlan(planning_scene, req, res);\n last_plan_solution_->error_code = res.error_code_.val;\n if (res.error_code_.val != res.error_code_.SUCCESS)\n {\n ROS_ERROR(\"Could not compute plan successfully\");\n return *last_plan_solution_;\n }\n last_plan_solution_->start_state = req.start_state;\n last_plan_solution_->trajectory = res.trajectory_;\n \/\/ TODO(henningkayser): Visualize trajectory\n \/\/ std::vector<const moveit::core::LinkModel*> eef_links;\n \/\/ if (joint_model_group->getEndEffectorTips(eef_links))\n \/\/{\n \/\/ for (const auto& eef_link : eef_links)\n \/\/ {\n \/\/ ROS_INFO_STREAM(\"Publishing trajectory for end effector \" << eef_link->getName());\n \/\/ visual_tools_->publishTrajectoryLine(last_solution_trajectory_, eef_link);\n \/\/ visual_tools_->publishTrajectoryPath(last_solution_trajectory_, false);\n \/\/ visual_tools_->publishRobotState(last_solution_trajectory_->getLastWayPoint(), rviz_visual_tools::TRANSLUCENT);\n \/\/ }\n \/\/}\n return *last_plan_solution_;\n}\n\nPlanningComponent::PlanSolution PlanningComponent::plan()\n{\n return plan(plan_request_parameters_);\n}\n\nbool PlanningComponent::setStartState(const moveit::core::RobotState& start_state)\n{\n considered_start_state_ = std::make_shared<moveit::core::RobotState>(start_state);\n return true;\n}\n\nmoveit::core::RobotStatePtr PlanningComponent::getStartState()\n{\n if (considered_start_state_)\n return considered_start_state_;\n else\n {\n moveit::core::RobotStatePtr s;\n moveit_cpp_->getCurrentState(s, 1.0);\n return s;\n }\n}\n\nbool PlanningComponent::setStartState(const std::string& start_state_name)\n{\n const auto& named_targets = getNamedTargetStates();\n if (std::find(named_targets.begin(), named_targets.end(), start_state_name) == named_targets.end())\n {\n ROS_ERROR_NAMED(LOGNAME, \"No predefined joint state found for target name '%s'\", start_state_name.c_str());\n return false;\n }\n moveit::core::RobotState start_state(moveit_cpp_->getRobotModel());\n start_state.setToDefaultValues(joint_model_group_, start_state_name);\n return setStartState(start_state);\n}\n\nvoid PlanningComponent::setStartStateToCurrentState()\n{\n considered_start_state_.reset();\n}\n\nstd::map<std::string, double> PlanningComponent::getNamedTargetStateValues(const std::string& name)\n{\n \/\/ TODO(henningkayser): verify result\n std::map<std::string, double> positions;\n joint_model_group_->getVariableDefaultPositions(name, positions);\n return positions;\n}\n\nvoid PlanningComponent::setWorkspace(double minx, double miny, double minz, double maxx, double maxy, double maxz)\n{\n workspace_parameters_.header.frame_id = moveit_cpp_->getRobotModel()->getModelFrame();\n workspace_parameters_.header.stamp = ros::Time::now();\n workspace_parameters_.min_corner.x = minx;\n workspace_parameters_.min_corner.y = miny;\n workspace_parameters_.min_corner.z = minz;\n workspace_parameters_.max_corner.x = maxx;\n workspace_parameters_.max_corner.y = maxy;\n workspace_parameters_.max_corner.z = maxz;\n workspace_parameters_set_ = true;\n}\n\nvoid PlanningComponent::unsetWorkspace()\n{\n workspace_parameters_set_ = false;\n}\n\nbool PlanningComponent::setGoal(const std::vector<moveit_msgs::Constraints>& goal_constraints)\n{\n current_goal_constraints_ = goal_constraints;\n return true;\n}\n\nbool PlanningComponent::setGoal(const moveit::core::RobotState& goal_state)\n{\n current_goal_constraints_ = { kinematic_constraints::constructGoalConstraints(goal_state, joint_model_group_) };\n return true;\n}\n\nbool PlanningComponent::setGoal(const geometry_msgs::PoseStamped& goal_pose, const std::string& link_name)\n{\n current_goal_constraints_ = { kinematic_constraints::constructGoalConstraints(link_name, goal_pose) };\n return true;\n}\n\nbool PlanningComponent::setGoal(const std::string& goal_state_name)\n{\n const auto& named_targets = getNamedTargetStates();\n if (std::find(named_targets.begin(), named_targets.end(), goal_state_name) == named_targets.end())\n {\n ROS_ERROR_NAMED(LOGNAME, \"No predefined joint state found for target name '%s'\", goal_state_name.c_str());\n return false;\n }\n moveit::core::RobotState goal_state(moveit_cpp_->getRobotModel());\n goal_state.setToDefaultValues(joint_model_group_, goal_state_name);\n return setGoal(goal_state);\n}\n\nbool PlanningComponent::execute(bool blocking)\n{\n if (!last_plan_solution_)\n {\n ROS_ERROR_NAMED(LOGNAME, \"There is no successful plan to execute\");\n return false;\n }\n\n \/\/ TODO(henningkayser): parameterize timestamps if required\n \/\/ trajectory_processing::TimeOptimalTrajectoryGeneration totg;\n \/\/ if (!totg.computeTimeStamps(*last_solution_trajectory_, max_velocity_scaling_factor_,\n \/\/ max_acceleration_scaling_factor_))\n \/\/{\n \/\/ ROS_ERROR(\"Failed to parameterize trajectory\");\n \/\/ return false;\n \/\/}\n return moveit_cpp_->execute(group_name_, last_plan_solution_->trajectory, blocking);\n}\n\nconst PlanningComponent::PlanSolutionPtr PlanningComponent::getLastPlanSolution()\n{\n return last_plan_solution_;\n}\n\nvoid PlanningComponent::clearContents()\n{\n considered_start_state_.reset();\n last_plan_solution_.reset();\n current_goal_constraints_.clear();\n moveit_cpp_.reset();\n planning_pipeline_names_.clear();\n}\n} \/\/ namespace moveit_cpp\n<|endoftext|>"} {"text":"<commit_before>\/*\n * ChibaNishizekiTriangleCounter.cpp\n *\n * Created on: 22.05.2014\n * Author: Gerd Lindner\n *\/\n\n#include \"ChibaNishizekiTriangleCounter.h\"\n#include \"..\/auxiliary\/Log.h\"\n#include \"..\/auxiliary\/Timer.h\"\n\nnamespace NetworKit {\n\nstd::vector<int> ChibaNishizekiTriangleCounter::getAttribute(const Graph& graph, const std::vector<int>& attribute) {\n\tstd::vector<std::vector<std::pair<node, edgeid> > > edges(graph.upperNodeIdBound());\n\n\t\/\/ copy edges with edge ids\n\tgraph.parallelForNodes([&](node u) {\n\t\tedges[u].reserve(graph.degree(u));\n\t\tgraph.forEdgesOf(u, [&](node _u, node v, edgeid eid) {\n\t\t\tedges[u].emplace_back(v, eid);\n\t\t});\n\t});\n\n\t\/\/Node attribute: marker\n\tstd::vector<edgeid> nodeMarker(graph.upperNodeIdBound(), none);\n\n\t\/\/Edge attribute: triangle count\n\tstd::vector<int> triangleCount(graph.upperEdgeIdBound(), 0);\n\n\t\/\/ bucket sort\n\tcount n = graph.numberOfNodes();\n\tstd::vector<node> sortedNodes(n);\n\t{\n\t\tstd::vector<index> nodePos(n + 1, 0);\n\n\t\tgraph.forNodes([&](node u) {\n\t\t\t++nodePos[n - graph.degree(u)];\n\t\t});\n\n\t\t\/\/ exclusive prefix sum\n\t\tindex tmp = nodePos[0];\n\t\tindex sum = tmp;\n\t\tnodePos[0] = 0;\n\n\t\tfor (index i = 1; i < nodePos.size(); ++i) {\n\t\t\ttmp = nodePos[i];\n\t\t\tnodePos[i] = sum;\n\t\t\tsum += tmp;\n\t\t}\n\n\t\tgraph.forNodes([&](node u) {\n\t\t\tsortedNodes[nodePos[n - graph.degree(u)]++] = u;\n\t\t});\n\t}\n\n\tfor (node u : sortedNodes) {\n\t\t\/\/Mark all neighbors\n\t\tfor (auto uv : edges[u]) {\n\t\t\tnodeMarker[uv.first] = uv.second;\n\t\t}\n\n\t\t\/\/For all neighbors: check for already marked neighbors.\n\t\tfor (auto uv : edges[u]) {\n\t\t\tbool edgeDeleted = false;\n\t\t\tfor (auto vw = edges[uv.first].begin(); vw != edges[uv.first].end(); ++vw) {\n\t\t\t\tif (edgeDeleted) {\n\t\t\t\t\t(*(vw-1)) = *vw;\n\t\t\t\t}\n\t\t\t\tif (nodeMarker[vw->first] != none) {\n\n\t\t\t\t\tedgeid eid_uw = nodeMarker[vw->first];\n\n\t\t\t\t\t++triangleCount[uv.second];\n\t\t\t\t\t++triangleCount[eid_uw];\n\t\t\t\t\t++triangleCount[vw->second];\n\t\t\t\t} else if (vw->first == u) {\n\t\t\t\t\tedgeDeleted = true;\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\tassert(edgeDeleted);\n\t\t\t\n\t\t\tedges[uv.first].pop_back();\n\n\t\t\tnodeMarker[uv.first] = none;\n\t\t}\n\t}\n\n\treturn triangleCount;\n}\n\n} \/* namespace NetworKit *\/\n<commit_msg>More efficient edge deletion in ChibaNishizekiTriangleCounter<commit_after>\/*\n * ChibaNishizekiTriangleCounter.cpp\n *\n * Created on: 22.05.2014\n * Author: Gerd Lindner\n *\/\n\n#include \"ChibaNishizekiTriangleCounter.h\"\n#include \"..\/auxiliary\/Log.h\"\n#include \"..\/auxiliary\/Timer.h\"\n\nnamespace NetworKit {\n\nstd::vector<int> ChibaNishizekiTriangleCounter::getAttribute(const Graph& graph, const std::vector<int>& attribute) {\n\tstd::vector<std::vector<std::pair<node, edgeid> > > edges(graph.upperNodeIdBound());\n\n\t\/\/ copy edges with edge ids\n\tgraph.parallelForNodes([&](node u) {\n\t\tedges[u].reserve(graph.degree(u));\n\t\tgraph.forEdgesOf(u, [&](node _u, node v, edgeid eid) {\n\t\t\tedges[u].emplace_back(v, eid);\n\t\t});\n\t});\n\n\t\/\/Node attribute: marker\n\tstd::vector<edgeid> nodeMarker(graph.upperNodeIdBound(), none);\n\n\t\/\/Edge attribute: triangle count\n\tstd::vector<int> triangleCount(graph.upperEdgeIdBound(), 0);\n\n\t\/\/ bucket sort\n\tcount n = graph.numberOfNodes();\n\tstd::vector<node> sortedNodes(n);\n\t{\n\t\tstd::vector<index> nodePos(n + 1, 0);\n\n\t\tgraph.forNodes([&](node u) {\n\t\t\t++nodePos[n - graph.degree(u)];\n\t\t});\n\n\t\t\/\/ exclusive prefix sum\n\t\tindex tmp = nodePos[0];\n\t\tindex sum = tmp;\n\t\tnodePos[0] = 0;\n\n\t\tfor (index i = 1; i < nodePos.size(); ++i) {\n\t\t\ttmp = nodePos[i];\n\t\t\tnodePos[i] = sum;\n\t\t\tsum += tmp;\n\t\t}\n\n\t\tgraph.forNodes([&](node u) {\n\t\t\tsortedNodes[nodePos[n - graph.degree(u)]++] = u;\n\t\t});\n\t}\n\n\tfor (node u : sortedNodes) {\n\t\t\/\/Mark all neighbors\n\t\tfor (auto uv : edges[u]) {\n\t\t\tnodeMarker[uv.first] = uv.second;\n\t\t}\n\n\t\t\/\/For all neighbors: check for already marked neighbors.\n\t\tfor (auto uv : edges[u]) {\n\t\t\tfor (auto vw = edges[uv.first].begin(); vw != edges[uv.first].end(); ++vw) {\n\t\t\t\t\/\/ delete the edge to u as we do not need to consider it again.\n\t\t\t\t\/\/ the opposite edge doesn't need to be deleted as we will never again consider\n\t\t\t\t\/\/ outgoing edges of u as u cannot be reached anymore after the uv loop.\n\t\t\t\tif (vw->first == u) {\n\t\t\t\t\t\/\/ move last element to current position in order to avoid changing too much\n\t\t\t\t\t*vw = edges[uv.first].back();\n\t\t\t\t\tedges[uv.first].pop_back();\n\t\t\t\t\tif (vw == edges[uv.first].end()) \/\/ break if we were at the last element already\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\tif (nodeMarker[vw->first] != none) { \/\/ triangle found - count it!\n\t\t\t\t\tedgeid eid_uw = nodeMarker[vw->first];\n\n\t\t\t\t\t++triangleCount[uv.second];\n\t\t\t\t\t++triangleCount[eid_uw];\n\t\t\t\t\t++triangleCount[vw->second];\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tnodeMarker[uv.first] = none; \/\/ all triangles with u and v have been counted already\n\t\t}\n\t}\n\n\treturn triangleCount;\n}\n\n} \/* namespace NetworKit *\/\n<|endoftext|>"} {"text":"<commit_before>\/*******************************************************************************\n\nLicensed to the OpenCOR team under one or more contributor license agreements.\nSee the NOTICE.txt file distributed with this work for additional information\nregarding copyright ownership. The OpenCOR team licenses this file to you under\nthe Apache License, Version 2.0 (the \"License\"); you may not use this file\nexcept in compliance with the License. You may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software distributed\nunder the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR\nCONDITIONS OF ANY KIND, either express or implied. See the License for the\nspecific language governing permissions and limitations under the License.\n\n*******************************************************************************\/\n\n\/\/==============================================================================\n\/\/ File manager\n\/\/==============================================================================\n\n#include \"cliutils.h\"\n#include \"filemanager.h\"\n\n\/\/==============================================================================\n\n#include <QApplication>\n#include <QDir>\n#include <QFile>\n#include <QFileInfo>\n#include <QIODevice>\n#include <QTemporaryFile>\n#include <QTextStream>\n#include <QTimer>\n\n\/\/==============================================================================\n\nnamespace OpenCOR {\nnamespace Core {\n\n\/\/==============================================================================\n\nFileManager::FileManager() :\n mActive(true),\n mFiles(QList<File *>()),\n mFilesReadable(QMap<QString, bool>()),\n mFilesWritable(QMap<QString, bool>())\n{\n \/\/ Create our timer\n\n mTimer = new QTimer(this);\n\n \/\/ A connection to handle the timing out of our timer\n\n connect(mTimer, SIGNAL(timeout()),\n this, SLOT(checkFiles()));\n}\n\n\/\/==============================================================================\n\nFileManager::~FileManager()\n{\n \/\/ Delete some internal objects\n\n delete mTimer;\n\n \/\/ Remove all the managed files\n\n foreach (File *file, mFiles)\n delete file;\n}\n\n\/\/==============================================================================\n\nFileManager * FileManager::instance()\n{\n \/\/ Return the 'global' instance of our file manager class\n\n static FileManager instance;\n\n return static_cast<FileManager *>(Core::globalInstance(\"OpenCOR::Core::FileManager::instance()\",\n &instance));\n}\n\n\/\/==============================================================================\n\nFileManager::Status FileManager::manage(const QString &pFileName,\n const File::Type &pType,\n const QString &pUrl)\n{\n \/\/ Manage the given file, should it not be already managed\n\n QString nativeFileName = nativeCanonicalFileName(pFileName);\n\n if (QFile::exists(nativeFileName)) {\n if (isManaged(nativeFileName)) {\n \/\/ The file is already managed, so...\n\n return AlreadyManaged;\n } else {\n \/\/ The file isn't already managed, so add it to our list of managed\n \/\/ files, let people know about it being now managed\n\n mFiles << new File(nativeFileName, pType, pUrl);\n\n if (!mTimer->isActive())\n mTimer->start(1000);\n\n emit fileManaged(nativeFileName);\n\n return Added;\n }\n } else {\n \/\/ The file doesn't exist, so...\n\n return DoesNotExist;\n }\n}\n\n\/\/==============================================================================\n\nFileManager::Status FileManager::unmanage(const QString &pFileName)\n{\n \/\/ Unmanage the given file, should it be managed\n\n QString nativeFileName = nativeCanonicalFileName(pFileName);\n\n if (QFile::exists(nativeFileName)) {\n File *file = isManaged(nativeFileName);\n\n if (file) {\n \/\/ The file is managed, so we can remove it\n\n mFiles.removeAt(mFiles.indexOf(file));\n\n delete file;\n\n if (mFiles.isEmpty())\n mTimer->stop();\n\n emit fileUnmanaged(nativeFileName);\n\n return Removed;\n } else {\n \/\/ The file isn't managed, so...\n\n return NotManaged;\n }\n } else {\n \/\/ The file doesn't exist, so...\n\n return NotManaged;\n }\n}\n\n\/\/==============================================================================\n\nFile * FileManager::isManaged(const QString &pFileName) const\n{\n \/\/ Return whether the given file is managed\n\n QString nativeFileName = nativeCanonicalFileName(pFileName);\n\n foreach (File *file, mFiles)\n if (!file->fileName().compare(nativeFileName))\n \/\/ The file has been found meaning it is managed\n\n return file;\n\n \/\/ The file couldn't be found meaning it's not managed\n\n return 0;\n}\n\n\/\/==============================================================================\n\nbool FileManager::isActive() const\n{\n \/\/ Return whether we are active\n\n return mActive;\n}\n\n\/\/==============================================================================\n\nvoid FileManager::setActive(const bool &pActive)\n{\n \/\/ Set whether we are active\n\n mActive = pActive;\n}\n\n\/\/==============================================================================\n\nvoid FileManager::reset(const QString &pFileName)\n{\n \/\/ Reset the given file, should it be managed\n\n QString nativeFileName = nativeCanonicalFileName(pFileName);\n File *file = isManaged(nativeFileName);\n\n if (file)\n file->reset();\n}\n\n\/\/==============================================================================\n\nint FileManager::newIndex(const QString &pFileName) const\n{\n \/\/ Return the given file's new index, if it is being managed\n\n File *file = isManaged(nativeCanonicalFileName(pFileName));\n\n if (file)\n return file->newIndex();\n else\n return 0;\n}\n\n\/\/==============================================================================\n\nQString FileManager::url(const QString &pFileName) const\n{\n \/\/ Return the given file's URL, if it is being managed\n\n File *file = isManaged(nativeCanonicalFileName(pFileName));\n\n if (file)\n return file->url();\n else\n return QString();\n}\n\n\/\/==============================================================================\n\nbool FileManager::isNew(const QString &pFileName) const\n{\n \/\/ Return whether the given file, if it is being managed, is new\n\n File *file = isManaged(nativeCanonicalFileName(pFileName));\n\n if (file)\n return file->isNew();\n else\n return false;\n}\n\n\/\/==============================================================================\n\nbool FileManager::isRemote(const QString &pFileName) const\n{\n \/\/ Return whether the given file, if it is being managed, is a remote one\n\n File *file = isManaged(nativeCanonicalFileName(pFileName));\n\n if (file)\n return file->isRemote();\n else\n return false;\n}\n\n\/\/==============================================================================\n\nbool FileManager::isModified(const QString &pFileName) const\n{\n \/\/ Return whether the given file, if it is being managed, has been modified\n\n File *file = isManaged(nativeCanonicalFileName(pFileName));\n\n if (file)\n return file->isModified();\n else\n return false;\n}\n\n\/\/==============================================================================\n\nbool FileManager::isNewOrModified(const QString &pFileName) const\n{\n \/\/ Return whether the given file is new or modified\n\n return isNew(pFileName) || isModified(pFileName);\n}\n\n\/\/==============================================================================\n\nvoid FileManager::setModified(const QString &pFileName, const bool &pModified)\n{\n \/\/ Set the modified state of the given file, should it be managed\n\n QString nativeFileName = nativeCanonicalFileName(pFileName);\n File *file = isManaged(nativeFileName);\n\n if (file && file->setModified(pModified))\n emit fileModified(nativeFileName, pModified);\n}\n\n\/\/==============================================================================\n\nbool FileManager::isReadable(const QString &pFileName) const\n{\n \/\/ Return whether the given file, if it is being managed, is readable\n\n File *file = isManaged(nativeCanonicalFileName(pFileName));\n\n if (file)\n return file->isReadable();\n else\n return false;\n}\n\n\/\/==============================================================================\n\nbool FileManager::isWritable(const QString &pFileName) const\n{\n \/\/ Return whether the given file, if it is being managed, is writable\n\n File *file = isManaged(nativeCanonicalFileName(pFileName));\n\n if (file)\n return file->isWritable();\n else\n return false;\n}\n\n\/\/==============================================================================\n\nbool FileManager::isReadableAndWritable(const QString &pFileName) const\n{\n \/\/ Return whether the given file, if it is being managed, is readable and\n \/\/ writable\n\n return isReadable(pFileName) && isWritable(pFileName);\n}\n\n\/\/==============================================================================\n\nbool FileManager::isLocked(const QString &pFileName) const\n{\n \/\/ Return whether the given file, if it is being managed, is locked\n\n File *file = isManaged(nativeCanonicalFileName(pFileName));\n\n if (file)\n return file->isLocked();\n else\n return false;\n}\n\n\/\/==============================================================================\n\nFileManager::Status FileManager::setLocked(const QString &pFileName,\n const bool &pLocked)\n{\n \/\/ Set the locked status of the given file, should it be managed\n\n QString nativeFileName = nativeCanonicalFileName(pFileName);\n File *file = isManaged(nativeFileName);\n\n if (file) {\n File::Status status = file->setLocked(pLocked);\n\n if (status == File::LockedSet)\n emit filePermissionsChanged(nativeFileName);\n\n if (status == File::LockedNotNeeded)\n return LockedNotNeeded;\n else if (status == File::LockedSet)\n return LockedSet;\n else\n return LockedNotSet;\n } else {\n return NotManaged;\n }\n}\n\n\/\/==============================================================================\n\nvoid FileManager::reload(const QString &pFileName)\n{\n \/\/ Make sure that the given file is managed\n\n QString nativeFileName = nativeCanonicalFileName(pFileName);\n\n if (isManaged(nativeFileName))\n \/\/ The file is managed, so let people know that it should be reloaded\n\n emit fileReloaded(nativeFileName);\n}\n\n\/\/==============================================================================\n\nFileManager::Status FileManager::create(const QString &pUrl,\n const QString &pContents)\n{\n \/\/ Create a new file\n\n QTemporaryFile createdFile(QDir::tempPath()+QDir::separator()+QFileInfo(qApp->applicationFilePath()).baseName()+\"_XXXXXX.tmp\");\n\n if (createdFile.open()) {\n createdFile.setAutoRemove(false);\n \/\/ Note: by default, a temporary file is to autoremove itself, but we\n \/\/ clearly don't want that here...\n\n QTextStream createdFileOut(&createdFile);\n\n createdFileOut << pContents;\n\n createdFile.close();\n\n \/\/ Let people know that we have created a file\n\n emit fileCreated(createdFile.fileName(), pUrl);\n\n return Created;\n } else {\n return NotCreated;\n }\n}\n\n\/\/==============================================================================\n\nFileManager::Status FileManager::rename(const QString &pOldFileName,\n const QString &pNewFileName)\n{\n \/\/ Make sure that the given 'old' file is managed\n\n QString oldNativeFileName = nativeCanonicalFileName(pOldFileName);\n File *file = isManaged(oldNativeFileName);\n\n if (file) {\n \/\/ The 'old' file is managed, so rename it and let people know about it\n\n QString newNativeFileName = nativeCanonicalFileName(pNewFileName);\n\n if (file->setFileName(newNativeFileName)) {\n emit fileRenamed(oldNativeFileName, newNativeFileName);\n\n return Renamed;\n } else {\n return RenamingNotNeeded;\n }\n } else {\n return NotManaged;\n }\n}\n\n\/\/==============================================================================\n\nFileManager::Status FileManager::duplicate(const QString &pFileName)\n{\n \/\/ Make sure that the given file is managed\n\n QString nativeFileName = nativeCanonicalFileName(pFileName);\n File *file = isManaged(nativeFileName);\n\n if (file) {\n \/\/ The file is managed, so retrieve its contents\n\n QString fileContents;\n\n if (Core::readTextFromFile(pFileName, fileContents)) {\n \/\/ Now, we can create a new file, which contents will be that of our\n \/\/ given file\n\n QTemporaryFile duplicatedFile(QDir::tempPath()+QDir::separator()+QFileInfo(qApp->applicationFilePath()).baseName()+\"_XXXXXX.\"+QFileInfo(pFileName).completeSuffix());\n\n if (duplicatedFile.open()) {\n duplicatedFile.setAutoRemove(false);\n \/\/ Note: by default, a temporary file is to autoremove itself,\n \/\/ but we clearly don't want that here...\n\n QTextStream duplicatedFileOut(&duplicatedFile);\n\n duplicatedFileOut << fileContents;\n\n duplicatedFile.close();\n\n \/\/ Let people know that we have duplicated a file\n\n emit fileDuplicated(duplicatedFile.fileName());\n\n return Duplicated;\n } else {\n return NotDuplicated;\n }\n } else {\n return NotDuplicated;\n }\n } else {\n return NotManaged;\n }\n}\n\n\/\/==============================================================================\n\nint FileManager::count() const\n{\n \/\/ Return the number of files currently being managed\n\n return mFiles.count();\n}\n\n\/\/==============================================================================\n\nvoid FileManager::checkFiles()\n{\n \/\/ We only want to check our files if we are active and if there is no\n \/\/ currently active dialog box\n\n if (!mActive || QApplication::activeModalWidget())\n return;\n\n \/\/ Check our various files, as well as their locked status, but only if they\n \/\/ are not being ignored\n\n foreach (File *file, mFiles) {\n switch (file->check()) {\n case File::Changed:\n \/\/ The file has changed, so let people know about it\n\n emit fileChanged(file->fileName());\n\n break;\n case File::Deleted:\n \/\/ The file has been deleted, so let people know about it\n\n emit fileDeleted(file->fileName());\n\n break;\n default:\n \/\/ The file is unchanged, so do nothing...\n\n ;\n }\n\n bool fileReadable = isReadable(file->fileName());\n bool fileWritable = isWritable(file->fileName());\n\n if ( (fileReadable != mFilesReadable.value(file->fileName(), false))\n || (fileWritable != mFilesWritable.value(file->fileName(), false))\n || !( mFilesReadable.contains(file->fileName())\n && mFilesWritable.contains(file->fileName()))) {\n emit filePermissionsChanged(file->fileName());\n\n mFilesReadable.insert(file->fileName(), fileReadable);\n mFilesWritable.insert(file->fileName(), fileWritable);\n }\n }\n}\n\n\/\/==============================================================================\n\n} \/\/ namespace Core\n} \/\/ namespace OpenCOR\n\n\/\/==============================================================================\n\/\/ End of file\n\/\/==============================================================================\n<commit_msg>Some minor cleaning up [ci skip].<commit_after>\/*******************************************************************************\n\nLicensed to the OpenCOR team under one or more contributor license agreements.\nSee the NOTICE.txt file distributed with this work for additional information\nregarding copyright ownership. The OpenCOR team licenses this file to you under\nthe Apache License, Version 2.0 (the \"License\"); you may not use this file\nexcept in compliance with the License. You may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software distributed\nunder the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR\nCONDITIONS OF ANY KIND, either express or implied. See the License for the\nspecific language governing permissions and limitations under the License.\n\n*******************************************************************************\/\n\n\/\/==============================================================================\n\/\/ File manager\n\/\/==============================================================================\n\n#include \"cliutils.h\"\n#include \"filemanager.h\"\n\n\/\/==============================================================================\n\n#include <QApplication>\n#include <QDir>\n#include <QFile>\n#include <QFileInfo>\n#include <QIODevice>\n#include <QTemporaryFile>\n#include <QTextStream>\n#include <QTimer>\n\n\/\/==============================================================================\n\nnamespace OpenCOR {\nnamespace Core {\n\n\/\/==============================================================================\n\nFileManager::FileManager() :\n mActive(true),\n mFiles(QList<File *>()),\n mFilesReadable(QMap<QString, bool>()),\n mFilesWritable(QMap<QString, bool>())\n{\n \/\/ Create our timer\n\n mTimer = new QTimer(this);\n\n \/\/ A connection to handle the timing out of our timer\n\n connect(mTimer, SIGNAL(timeout()),\n this, SLOT(checkFiles()));\n}\n\n\/\/==============================================================================\n\nFileManager::~FileManager()\n{\n \/\/ Delete some internal objects\n\n delete mTimer;\n\n \/\/ Remove all the managed files\n\n foreach (File *file, mFiles)\n delete file;\n}\n\n\/\/==============================================================================\n\nFileManager * FileManager::instance()\n{\n \/\/ Return the 'global' instance of our file manager class\n\n static FileManager instance;\n\n return static_cast<FileManager *>(Core::globalInstance(\"OpenCOR::Core::FileManager::instance()\",\n &instance));\n}\n\n\/\/==============================================================================\n\nFileManager::Status FileManager::manage(const QString &pFileName,\n const File::Type &pType,\n const QString &pUrl)\n{\n \/\/ Manage the given file, should it not be already managed\n\n QString nativeFileName = nativeCanonicalFileName(pFileName);\n\n if (QFile::exists(nativeFileName)) {\n if (isManaged(nativeFileName)) {\n \/\/ The file is already managed, so...\n\n return AlreadyManaged;\n } else {\n \/\/ The file isn't already managed, so add it to our list of managed\n \/\/ files, let people know about it being now managed\n\n mFiles << new File(nativeFileName, pType, pUrl);\n\n if (!mTimer->isActive())\n mTimer->start(1000);\n\n emit fileManaged(nativeFileName);\n\n return Added;\n }\n } else {\n \/\/ The file doesn't exist, so...\n\n return DoesNotExist;\n }\n}\n\n\/\/==============================================================================\n\nFileManager::Status FileManager::unmanage(const QString &pFileName)\n{\n \/\/ Unmanage the given file, should it be managed\n\n QString nativeFileName = nativeCanonicalFileName(pFileName);\n\n if (QFile::exists(nativeFileName)) {\n File *file = isManaged(nativeFileName);\n\n if (file) {\n \/\/ The file is managed, so we can remove it\n\n mFiles.removeAt(mFiles.indexOf(file));\n\n delete file;\n\n if (mFiles.isEmpty())\n mTimer->stop();\n\n emit fileUnmanaged(nativeFileName);\n\n return Removed;\n } else {\n \/\/ The file isn't managed, so...\n\n return NotManaged;\n }\n } else {\n \/\/ The file doesn't exist, so...\n\n return NotManaged;\n }\n}\n\n\/\/==============================================================================\n\nFile * FileManager::isManaged(const QString &pFileName) const\n{\n \/\/ Return whether the given file is managed\n\n QString nativeFileName = nativeCanonicalFileName(pFileName);\n\n foreach (File *file, mFiles)\n if (!file->fileName().compare(nativeFileName))\n \/\/ The file has been found meaning it is managed\n\n return file;\n\n \/\/ The file couldn't be found meaning it's not managed\n\n return 0;\n}\n\n\/\/==============================================================================\n\nbool FileManager::isActive() const\n{\n \/\/ Return whether we are active\n\n return mActive;\n}\n\n\/\/==============================================================================\n\nvoid FileManager::setActive(const bool &pActive)\n{\n \/\/ Set whether we are active\n\n mActive = pActive;\n}\n\n\/\/==============================================================================\n\nvoid FileManager::reset(const QString &pFileName)\n{\n \/\/ Reset the given file, should it be managed\n\n QString nativeFileName = nativeCanonicalFileName(pFileName);\n File *file = isManaged(nativeFileName);\n\n if (file)\n file->reset();\n}\n\n\/\/==============================================================================\n\nint FileManager::newIndex(const QString &pFileName) const\n{\n \/\/ Return the given file's new index, if it is being managed\n\n File *file = isManaged(nativeCanonicalFileName(pFileName));\n\n if (file)\n return file->newIndex();\n else\n return 0;\n}\n\n\/\/==============================================================================\n\nQString FileManager::url(const QString &pFileName) const\n{\n \/\/ Return the given file's URL, if it is being managed\n\n File *file = isManaged(nativeCanonicalFileName(pFileName));\n\n if (file)\n return file->url();\n else\n return QString();\n}\n\n\/\/==============================================================================\n\nbool FileManager::isNew(const QString &pFileName) const\n{\n \/\/ Return whether the given file, if it is being managed, is new\n\n File *file = isManaged(nativeCanonicalFileName(pFileName));\n\n if (file)\n return file->isNew();\n else\n return false;\n}\n\n\/\/==============================================================================\n\nbool FileManager::isRemote(const QString &pFileName) const\n{\n \/\/ Return whether the given file, if it is being managed, is a remote one\n\n File *file = isManaged(nativeCanonicalFileName(pFileName));\n\n if (file)\n return file->isRemote();\n else\n return false;\n}\n\n\/\/==============================================================================\n\nbool FileManager::isModified(const QString &pFileName) const\n{\n \/\/ Return whether the given file, if it is being managed, has been modified\n\n File *file = isManaged(nativeCanonicalFileName(pFileName));\n\n if (file)\n return file->isModified();\n else\n return false;\n}\n\n\/\/==============================================================================\n\nbool FileManager::isNewOrModified(const QString &pFileName) const\n{\n \/\/ Return whether the given file is new or modified\n\n return isNew(pFileName) || isModified(pFileName);\n}\n\n\/\/==============================================================================\n\nvoid FileManager::setModified(const QString &pFileName, const bool &pModified)\n{\n \/\/ Set the modified state of the given file, should it be managed\n\n QString nativeFileName = nativeCanonicalFileName(pFileName);\n File *file = isManaged(nativeFileName);\n\n if (file && file->setModified(pModified))\n emit fileModified(nativeFileName, pModified);\n}\n\n\/\/==============================================================================\n\nbool FileManager::isReadable(const QString &pFileName) const\n{\n \/\/ Return whether the given file, if it is being managed, is readable\n\n File *file = isManaged(nativeCanonicalFileName(pFileName));\n\n if (file)\n return file->isReadable();\n else\n return false;\n}\n\n\/\/==============================================================================\n\nbool FileManager::isWritable(const QString &pFileName) const\n{\n \/\/ Return whether the given file, if it is being managed, is writable\n\n File *file = isManaged(nativeCanonicalFileName(pFileName));\n\n if (file)\n return file->isWritable();\n else\n return false;\n}\n\n\/\/==============================================================================\n\nbool FileManager::isReadableAndWritable(const QString &pFileName) const\n{\n \/\/ Return whether the given file, if it is being managed, is readable and\n \/\/ writable\n\n return isReadable(pFileName) && isWritable(pFileName);\n}\n\n\/\/==============================================================================\n\nbool FileManager::isLocked(const QString &pFileName) const\n{\n \/\/ Return whether the given file, if it is being managed, is locked\n\n File *file = isManaged(nativeCanonicalFileName(pFileName));\n\n if (file)\n return file->isLocked();\n else\n return false;\n}\n\n\/\/==============================================================================\n\nFileManager::Status FileManager::setLocked(const QString &pFileName,\n const bool &pLocked)\n{\n \/\/ Set the locked status of the given file, should it be managed\n\n QString nativeFileName = nativeCanonicalFileName(pFileName);\n File *file = isManaged(nativeFileName);\n\n if (file) {\n File::Status status = file->setLocked(pLocked);\n\n if (status == File::LockedSet)\n emit filePermissionsChanged(nativeFileName);\n\n if (status == File::LockedNotNeeded)\n return LockedNotNeeded;\n else if (status == File::LockedSet)\n return LockedSet;\n else\n return LockedNotSet;\n } else {\n return NotManaged;\n }\n}\n\n\/\/==============================================================================\n\nvoid FileManager::reload(const QString &pFileName)\n{\n \/\/ Make sure that the given file is managed\n\n QString nativeFileName = nativeCanonicalFileName(pFileName);\n\n if (isManaged(nativeFileName))\n \/\/ The file is managed, so let people know that it should be reloaded\n\n emit fileReloaded(nativeFileName);\n}\n\n\/\/==============================================================================\n\nFileManager::Status FileManager::create(const QString &pUrl,\n const QString &pContents)\n{\n \/\/ Create a new file\n\n QTemporaryFile createdFile(QDir::tempPath()+QDir::separator()+QFileInfo(qApp->applicationFilePath()).baseName()+\"_XXXXXX.tmp\");\n\n if (createdFile.open()) {\n createdFile.setAutoRemove(false);\n \/\/ Note: by default, a temporary file is to autoremove itself, but we\n \/\/ clearly don't want that here...\n\n QTextStream createdFileOut(&createdFile);\n\n createdFileOut << pContents;\n\n createdFile.close();\n\n \/\/ Let people know that we have created a file\n\n emit fileCreated(createdFile.fileName(), pUrl);\n\n return Created;\n } else {\n return NotCreated;\n }\n}\n\n\/\/==============================================================================\n\nFileManager::Status FileManager::rename(const QString &pOldFileName,\n const QString &pNewFileName)\n{\n \/\/ Make sure that the given 'old' file is managed\n\n QString oldNativeFileName = nativeCanonicalFileName(pOldFileName);\n File *file = isManaged(oldNativeFileName);\n\n if (file) {\n \/\/ The 'old' file is managed, so rename it and let people know about it\n\n QString newNativeFileName = nativeCanonicalFileName(pNewFileName);\n\n if (file->setFileName(newNativeFileName)) {\n emit fileRenamed(oldNativeFileName, newNativeFileName);\n\n return Renamed;\n } else {\n return RenamingNotNeeded;\n }\n } else {\n return NotManaged;\n }\n}\n\n\/\/==============================================================================\n\nFileManager::Status FileManager::duplicate(const QString &pFileName)\n{\n \/\/ Make sure that the given file is managed\n\n QString nativeFileName = nativeCanonicalFileName(pFileName);\n File *file = isManaged(nativeFileName);\n\n if (file) {\n \/\/ The file is managed, so retrieve its contents\n\n QString fileContents;\n\n if (Core::readTextFromFile(pFileName, fileContents)) {\n \/\/ Now, we can create a new file, which contents will be that of our\n \/\/ given file\n\n QTemporaryFile duplicatedFile(QDir::tempPath()+QDir::separator()+QFileInfo(qApp->applicationFilePath()).baseName()+\"_XXXXXX.\"+QFileInfo(pFileName).completeSuffix());\n\n if (duplicatedFile.open()) {\n duplicatedFile.setAutoRemove(false);\n \/\/ Note: by default, a temporary file is to autoremove itself,\n \/\/ but we clearly don't want that here...\n\n QTextStream duplicatedFileOut(&duplicatedFile);\n\n duplicatedFileOut << fileContents;\n\n duplicatedFile.close();\n\n \/\/ Let people know that we have duplicated a file\n\n emit fileDuplicated(duplicatedFile.fileName());\n\n return Duplicated;\n } else {\n return NotDuplicated;\n }\n } else {\n return NotDuplicated;\n }\n } else {\n return NotManaged;\n }\n}\n\n\/\/==============================================================================\n\nint FileManager::count() const\n{\n \/\/ Return the number of files currently being managed\n\n return mFiles.count();\n}\n\n\/\/==============================================================================\n\nvoid FileManager::checkFiles()\n{\n \/\/ We only want to check our files if we are active and if there is no\n \/\/ currently active dialog box\n\n if (!mActive || QApplication::activeModalWidget())\n return;\n\n \/\/ Check our various files, as well as their locked status, but only if they\n \/\/ are not being ignored\n\n foreach (File *file, mFiles) {\n switch (file->check()) {\n case File::Changed:\n \/\/ The file has changed, so let people know about it\n\n emit fileChanged(file->fileName());\n\n break;\n case File::Deleted:\n \/\/ The file has been deleted, so let people know about it\n\n emit fileDeleted(file->fileName());\n\n break;\n default:\n \/\/ The file is unchanged, so do nothing...\n\n ;\n }\n\n bool fileReadable = isReadable(file->fileName());\n bool fileWritable = isWritable(file->fileName());\n\n if ( (fileReadable != mFilesReadable.value(file->fileName(), false))\n || (fileWritable != mFilesWritable.value(file->fileName(), false))\n || !( mFilesReadable.contains(file->fileName())\n && mFilesWritable.contains(file->fileName()))) {\n emit filePermissionsChanged(file->fileName());\n\n mFilesReadable.insert(file->fileName(), fileReadable);\n mFilesWritable.insert(file->fileName(), fileWritable);\n }\n }\n}\n\n\/\/==============================================================================\n\n} \/\/ namespace Core\n} \/\/ namespace OpenCOR\n\n\/\/==============================================================================\n\/\/ End of file\n\/\/==============================================================================\n<|endoftext|>"} {"text":"<commit_before>\n#pragma once\n\n#include \"geometry\/identity.hpp\"\n\n#include \"base\/mappable.hpp\"\n#include \"geometry\/grassmann.hpp\"\n#include \"geometry\/sign.hpp\"\n\nnamespace principia {\nnamespace geometry {\nnamespace internal_identity {\n\ntemplate<typename FromFrame, typename ToFrame>\nIdentity<FromFrame, ToFrame>::Identity() {}\n\ntemplate<typename FromFrame, typename ToFrame>\nSign Identity<FromFrame, ToFrame>::Determinant() const {\n return Sign::Positive();\n}\n\ntemplate<typename FromFrame, typename ToFrame>\nIdentity<ToFrame, FromFrame> Identity<FromFrame, ToFrame>::Inverse() const {\n return Identity<ToFrame, FromFrame>();\n}\n\ntemplate<typename FromFrame, typename ToFrame>\ntemplate<typename Scalar>\nVector<Scalar, ToFrame> Identity<FromFrame, ToFrame>::operator()(\n Vector<Scalar, FromFrame> const& vector) const {\n return Vector<Scalar, ToFrame>(vector.coordinates());\n}\n\ntemplate<typename FromFrame, typename ToFrame>\ntemplate<typename Scalar>\nBivector<Scalar, ToFrame> Identity<FromFrame, ToFrame>::operator()(\n Bivector<Scalar, FromFrame> const& bivector) const {\n return Bivector<Scalar, ToFrame>(bivector.coordinates());\n}\n\ntemplate<typename FromFrame, typename ToFrame>\ntemplate<typename Scalar>\nTrivector<Scalar, ToFrame> Identity<FromFrame, ToFrame>::operator()(\n Trivector<Scalar, FromFrame> const& trivector) const {\n return Trivector<Scalar, ToFrame>(trivector.coordinates());\n}\n\ntemplate<typename FromFrame, typename ToFrame>\ntemplate<typename Scalar>\nSymmetricBilinearForm<Scalar, ToFrame> Identity<FromFrame, ToFrame>::operator()(\n SymmetricBilinearForm<Scalar, FromFrame> const& form) const {\n return SymmetricBilinearForm<Scalar, ToFrame>(form.coordinates());\n}\n\ntemplate<typename FromFrame, typename ToFrame>\ntemplate<typename T>\ntypename base::Mappable<Identity<FromFrame, ToFrame>, T>::type\nIdentity<FromFrame, ToFrame>::operator()(T const& t) const {\n return base::Mappable<Identity, T>::Do(*this, t);\n}\n\ntemplate<typename FromFrame, typename ToFrame>\nOrthogonalMap<FromFrame, ToFrame> Identity<FromFrame, ToFrame>::Forget() const {\n return OrthogonalMap<FromFrame, ToFrame>(\n Determinant(),\n Rotation<FromFrame, ToFrame>::Identity());\n}\n\ntemplate<typename FromFrame, typename ToFrame>\nvoid Identity<FromFrame, ToFrame>::WriteToMessage(\n not_null<serialization::LinearMap*> const message) const {\n LinearMap<FromFrame, ToFrame>::WriteToMessage(message);\n WriteToMessage(message->MutableExtension(serialization::Identity::extension));\n}\n\ntemplate<typename FromFrame, typename ToFrame>\nIdentity<FromFrame, ToFrame> Identity<FromFrame, ToFrame>::ReadFromMessage(\n serialization::LinearMap const& message) {\n LinearMap<FromFrame, ToFrame>::ReadFromMessage(message);\n CHECK(message.HasExtension(serialization::Identity::extension));\n return ReadFromMessage(\n message.GetExtension(serialization::Identity::extension));\n}\n\ntemplate<typename FromFrame, typename ToFrame>\nvoid Identity<FromFrame, ToFrame>::WriteToMessage(\n not_null<serialization::Identity*> const message) const {}\n\ntemplate<typename FromFrame, typename ToFrame>\nIdentity<FromFrame, ToFrame> Identity<FromFrame, ToFrame>::ReadFromMessage(\n serialization::Identity const& message) {\n return Identity();\n}\n\ntemplate<typename FromFrame, typename ThroughFrame, typename ToFrame>\nIdentity<FromFrame, ToFrame> operator*(\n Identity<ThroughFrame, ToFrame> const& left,\n Identity<FromFrame, ThroughFrame> const& right) {\n return Identity<FromFrame, ToFrame>();\n}\n\ntemplate<typename FromFrame, typename ToFrame>\nstd::ostream& operator<<(std::ostream& out,\n Identity<FromFrame, ToFrame> const& identity) {\n return out << \"𝟙\";\n}\n\n} \/\/ namespace internal_identity\n} \/\/ namespace geometry\n} \/\/ namespace principia\n<commit_msg>After egg's review.<commit_after>\n#pragma once\n\n#include \"geometry\/identity.hpp\"\n\n#include \"base\/mappable.hpp\"\n#include \"geometry\/grassmann.hpp\"\n#include \"geometry\/sign.hpp\"\n\nnamespace principia {\nnamespace geometry {\nnamespace internal_identity {\n\ntemplate<typename FromFrame, typename ToFrame>\nIdentity<FromFrame, ToFrame>::Identity() {}\n\ntemplate<typename FromFrame, typename ToFrame>\nSign Identity<FromFrame, ToFrame>::Determinant() const {\n return Sign::Positive();\n}\n\ntemplate<typename FromFrame, typename ToFrame>\nIdentity<ToFrame, FromFrame> Identity<FromFrame, ToFrame>::Inverse() const {\n return Identity<ToFrame, FromFrame>();\n}\n\ntemplate<typename FromFrame, typename ToFrame>\ntemplate<typename Scalar>\nVector<Scalar, ToFrame> Identity<FromFrame, ToFrame>::operator()(\n Vector<Scalar, FromFrame> const& vector) const {\n return Vector<Scalar, ToFrame>(vector.coordinates());\n}\n\ntemplate<typename FromFrame, typename ToFrame>\ntemplate<typename Scalar>\nBivector<Scalar, ToFrame> Identity<FromFrame, ToFrame>::operator()(\n Bivector<Scalar, FromFrame> const& bivector) const {\n return Bivector<Scalar, ToFrame>(bivector.coordinates());\n}\n\ntemplate<typename FromFrame, typename ToFrame>\ntemplate<typename Scalar>\nTrivector<Scalar, ToFrame> Identity<FromFrame, ToFrame>::operator()(\n Trivector<Scalar, FromFrame> const& trivector) const {\n return Trivector<Scalar, ToFrame>(trivector.coordinates());\n}\n\ntemplate<typename FromFrame, typename ToFrame>\ntemplate<typename Scalar>\nSymmetricBilinearForm<Scalar, ToFrame> Identity<FromFrame, ToFrame>::operator()(\n SymmetricBilinearForm<Scalar, FromFrame> const& form) const {\n return SymmetricBilinearForm<Scalar, ToFrame>(form.coordinates());\n}\n\ntemplate<typename FromFrame, typename ToFrame>\ntemplate<typename T>\ntypename base::Mappable<Identity<FromFrame, ToFrame>, T>::type\nIdentity<FromFrame, ToFrame>::operator()(T const& t) const {\n return base::Mappable<Identity, T>::Do(*this, t);\n}\n\ntemplate<typename FromFrame, typename ToFrame>\nOrthogonalMap<FromFrame, ToFrame> Identity<FromFrame, ToFrame>::Forget() const {\n return OrthogonalMap<FromFrame, ToFrame>(\n Determinant(),\n Rotation<FromFrame, ToFrame>::Identity());\n}\n\ntemplate<typename FromFrame, typename ToFrame>\nvoid Identity<FromFrame, ToFrame>::WriteToMessage(\n not_null<serialization::LinearMap*> const message) const {\n LinearMap<FromFrame, ToFrame>::WriteToMessage(message);\n WriteToMessage(message->MutableExtension(serialization::Identity::extension));\n}\n\ntemplate<typename FromFrame, typename ToFrame>\nIdentity<FromFrame, ToFrame> Identity<FromFrame, ToFrame>::ReadFromMessage(\n serialization::LinearMap const& message) {\n LinearMap<FromFrame, ToFrame>::ReadFromMessage(message);\n CHECK(message.HasExtension(serialization::Identity::extension));\n return ReadFromMessage(\n message.GetExtension(serialization::Identity::extension));\n}\n\ntemplate<typename FromFrame, typename ToFrame>\nvoid Identity<FromFrame, ToFrame>::WriteToMessage(\n not_null<serialization::Identity*> const message) const {}\n\ntemplate<typename FromFrame, typename ToFrame>\nIdentity<FromFrame, ToFrame> Identity<FromFrame, ToFrame>::ReadFromMessage(\n serialization::Identity const& message) {\n return Identity();\n}\n\ntemplate<typename FromFrame, typename ThroughFrame, typename ToFrame>\nIdentity<FromFrame, ToFrame> operator*(\n Identity<ThroughFrame, ToFrame> const& left,\n Identity<FromFrame, ThroughFrame> const& right) {\n return Identity<FromFrame, ToFrame>();\n}\n\ntemplate<typename FromFrame, typename ToFrame>\nstd::ostream& operator<<(std::ostream& out,\n Identity<FromFrame, ToFrame> const& identity) {\n return out << u8\"𝟙\";\n}\n\n} \/\/ namespace internal_identity\n} \/\/ namespace geometry\n} \/\/ namespace principia\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2008, Google Inc.\n\/\/ All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are\n\/\/ met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright\n\/\/ notice, this list of conditions and the following disclaimer.\n\/\/ * Redistributions in binary form must reproduce the above\n\/\/ copyright notice, this list of conditions and the following disclaimer\n\/\/ in the documentation and\/or other materials provided with the\n\/\/ distribution.\n\/\/ * Neither the name of Google Inc. nor the names of its\n\/\/ contributors may be used to endorse or promote products derived from\n\/\/ this software without specific prior written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\/\/ \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n\/\/ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n\/\/ A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n\/\/ OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n\/\/ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n\/\/ LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n\/\/ DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n\/\/ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n\/\/ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n\/\/ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n#include \"chrome\/common\/rand_util.h\"\n\n#include <stdlib.h>\n#include <time.h>\n\n#include \"base\/logging.h\"\n#include \"base\/thread_local_storage.h\"\n#include \"base\/win_util.h\"\n\nnamespace rand_util {\n\n\/\/ Using TLS since srand() needs to be called once in each thread.\nint g_tls_index = ThreadLocalStorage::Alloc();\n\nint RandInt(int min, int max) {\n if (ThreadLocalStorage::Get(g_tls_index) == 0) {\n ThreadLocalStorage::Set(g_tls_index, reinterpret_cast<void*>(1));\n srand(static_cast<unsigned int>(time(0)));\n }\n\n \/\/ From the rand man page, use this instead of just rand() % max, so that the\n \/\/ higher bits are used.\n return min + static_cast<int>(static_cast<double>(max - min + 1) *\n (::rand() \/ (RAND_MAX + 1.0)));\n}\n\nint RandIntSecure(int min, int max) {\n if (win_util::GetWinVersion() < win_util::WINVERSION_XP) {\n \/\/ rand_s needs XP and later.\n return RandInt(min, max);\n }\n\n unsigned int number;\n errno_t rv = rand_s(&number);\n DCHECK(rv == 0) << \"rand_s failed with error \" << rv;\n\n \/\/ From the rand man page, use this instead of just rand() % max, so that the\n \/\/ higher bits are used.\n return min + static_cast<int>(static_cast<double>(max - min + 1.0) *\n (number \/ (UINT_MAX + 1.0)));\n}\n\n} \/\/ namespace rand_util\n<commit_msg>Using a better seed. Using time() causes the random sequence to start with the same number when run several times consecutively.<commit_after>\/\/ Copyright 2008, Google Inc.\n\/\/ All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are\n\/\/ met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright\n\/\/ notice, this list of conditions and the following disclaimer.\n\/\/ * Redistributions in binary form must reproduce the above\n\/\/ copyright notice, this list of conditions and the following disclaimer\n\/\/ in the documentation and\/or other materials provided with the\n\/\/ distribution.\n\/\/ * Neither the name of Google Inc. nor the names of its\n\/\/ contributors may be used to endorse or promote products derived from\n\/\/ this software without specific prior written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\/\/ \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n\/\/ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n\/\/ A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n\/\/ OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n\/\/ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n\/\/ LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n\/\/ DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n\/\/ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n\/\/ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n\/\/ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n#include \"chrome\/common\/rand_util.h\"\n\n#include <stdlib.h>\n#include <time.h>\n\n#include \"base\/logging.h\"\n#include \"base\/thread_local_storage.h\"\n#include \"base\/time.h\"\n#include \"base\/win_util.h\"\n\nnamespace rand_util {\n\n\/\/ Using TLS since srand() needs to be called once in each thread.\nint g_tls_index = ThreadLocalStorage::Alloc();\n\nint RandInt(int min, int max) {\n if (ThreadLocalStorage::Get(g_tls_index) == 0) {\n ThreadLocalStorage::Set(g_tls_index, reinterpret_cast<void*>(1));\n TimeDelta now = TimeTicks::UnreliableHighResNow() - TimeTicks();\n unsigned int seed = static_cast<unsigned int>(now.InMicroseconds());\n srand(seed);\n }\n\n \/\/ From the rand man page, use this instead of just rand() % max, so that the\n \/\/ higher bits are used.\n return min + static_cast<int>(static_cast<double>(max - min + 1) *\n (::rand() \/ (RAND_MAX + 1.0)));\n}\n\nint RandIntSecure(int min, int max) {\n if (win_util::GetWinVersion() < win_util::WINVERSION_XP) {\n \/\/ rand_s needs XP and later.\n return RandInt(min, max);\n }\n\n unsigned int number;\n errno_t rv = rand_s(&number);\n DCHECK(rv == 0) << \"rand_s failed with error \" << rv;\n\n \/\/ From the rand man page, use this instead of just rand() % max, so that the\n \/\/ higher bits are used.\n return min + static_cast<int>(static_cast<double>(max - min + 1.0) *\n (number \/ (UINT_MAX + 1.0)));\n}\n\n} \/\/ namespace rand_util\n<|endoftext|>"} {"text":"<commit_before>\/\/=====================================================================\/\/\n\/*! @file\n\t@brief メイン @n\n\t\t\tCopyright 2017 Kunihito Hiramatsu\n\t@author 平松邦仁 (hira@rvf-rc45.net)\n*\/\n\/\/=====================================================================\/\/\n#include \"main.hpp\"\n#include \"ignitor.hpp\"\n\ntypedef app::ignitor start_app;\n\nstatic const char* window_key_ = { \"application\/window\" };\nstatic const char* app_title_ = { \"ignitor app\" };\nstatic const vtx::spos start_pos_(10, 40);\nstatic const vtx::spos start_size_(1400, 840);\nstatic const vtx::spos limit_size_(1400, 840);\n\nint main(int argc, char** argv)\n{\n\tgl::core& core = gl::core::get_instance();\n\n\tif(!core.initialize(argc, argv)) {\n\t\tstd::cerr << \"Core initialize error\" << std::endl;\n\t\treturn -1;\n\t}\n\n\tstd::string pref = core.get_exec_path();\n\tpref += \".pre\";\n\n\tutils::director<app::core> director;\n\n\tdirector.at().preference_.load(pref);\n\n\tvtx::srect rect(start_pos_, start_size_);\n\tif(!director.at().preference_.load_rect(window_key_, rect)) {\n\/\/\t\tstd::cerr << \"Load preference error: '\" << window_key_ << \"'\" << std::endl; \n\t}\n\n\tif(!core.setup(rect, app_title_, false)) {\n\t\tstd::cerr << \"Core setup error\" << std::endl;\n\t\treturn -1;\n\t}\n\tcore.set_limit_size(limit_size_);\n\n\/\/\tdirector.at().sound_.initialize(16);\n\n\tdirector.at().widget_director_.initialize();\n\n\tdirector.install_scene<start_app>();\n\n\twhile(!core.get_exit_signal()) {\n\t\tcore.service();\n\n\t\tglClearColor(0, 0, 0, 255);\n\t\tglClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );\n\t\tgl::glColor(img::rgbaf(1.0f));\n\n\t\tglTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);\n\t\tglEnable(GL_TEXTURE_2D);\n\t\tglEnable(GL_BLEND);\n\t\tglDisable(GL_DEPTH_TEST);\n\t\tglBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);\n\n\t\tdirector.render();\n\n\t\tcore.flip_frame();\n\n\/\/\t\tdirector.at().sound_.service();\n\t}\n\t\/\/ プログラム終了の廃棄\n\tdirector.erase_scene();\n\tdirector.render();\n\n\t{\n\t\tconst vtx::srect& rect = core.get_rect();\n\t\tdirector.at().preference_.save_rect(window_key_, rect);\n\t}\n\n\tdirector.at().preference_.save(pref);\n\n\tcore.destroy();\n}\n<commit_msg>update: start windows size<commit_after>\/\/=====================================================================\/\/\n\/*! @file\n\t@brief メイン @n\n\t\t\tCopyright 2017 Kunihito Hiramatsu\n\t@author 平松邦仁 (hira@rvf-rc45.net)\n*\/\n\/\/=====================================================================\/\/\n#include \"main.hpp\"\n#include \"ignitor.hpp\"\n\ntypedef app::ignitor start_app;\n\nstatic const char* window_key_ = { \"application\/window\" };\nstatic const char* app_title_ = { \"ignitor app\" };\nstatic const vtx::spos start_pos_(10, 40);\nstatic const vtx::spos start_size_(1550, 840);\nstatic const vtx::spos limit_size_(1550, 840);\n\nint main(int argc, char** argv)\n{\n\tgl::core& core = gl::core::get_instance();\n\n\tif(!core.initialize(argc, argv)) {\n\t\tstd::cerr << \"Core initialize error\" << std::endl;\n\t\treturn -1;\n\t}\n\n\tstd::string pref = core.get_exec_path();\n\tpref += \".pre\";\n\n\tutils::director<app::core> director;\n\n\tdirector.at().preference_.load(pref);\n\n\tvtx::srect rect(start_pos_, start_size_);\n\tif(!director.at().preference_.load_rect(window_key_, rect)) {\n\/\/\t\tstd::cerr << \"Load preference error: '\" << window_key_ << \"'\" << std::endl; \n\t}\n\n\tif(!core.setup(rect, app_title_, false)) {\n\t\tstd::cerr << \"Core setup error\" << std::endl;\n\t\treturn -1;\n\t}\n\tcore.set_limit_size(limit_size_);\n\n\/\/\tdirector.at().sound_.initialize(16);\n\n\tdirector.at().widget_director_.initialize();\n\n\tdirector.install_scene<start_app>();\n\n\twhile(!core.get_exit_signal()) {\n\t\tcore.service();\n\n\t\tglClearColor(0, 0, 0, 255);\n\t\tglClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );\n\t\tgl::glColor(img::rgbaf(1.0f));\n\n\t\tglTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);\n\t\tglEnable(GL_TEXTURE_2D);\n\t\tglEnable(GL_BLEND);\n\t\tglDisable(GL_DEPTH_TEST);\n\t\tglBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);\n\n\t\tdirector.render();\n\n\t\tcore.flip_frame();\n\n\/\/\t\tdirector.at().sound_.service();\n\t}\n\t\/\/ プログラム終了の廃棄\n\tdirector.erase_scene();\n\tdirector.render();\n\n\t{\n\t\tconst vtx::srect& rect = core.get_rect();\n\t\tdirector.at().preference_.save_rect(window_key_, rect);\n\t}\n\n\tdirector.at().preference_.save(pref);\n\n\tcore.destroy();\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"imagefetcher.h\"\nusing namespace AhoViewer::Booru;\n\nint ImageFetcher::socket_cb(CURL*, curl_socket_t s, int action, void *userp, void *sockp)\n{\n ImageFetcher *self = static_cast<ImageFetcher*>(userp);\n SockInfo *fdp = static_cast<SockInfo*>(sockp);\n\n if (action == CURL_POLL_REMOVE && fdp)\n {\n delete fdp;\n }\n else\n {\n if (!fdp)\n {\n fdp = new SockInfo();\n fdp->chan = Glib::IOChannel::create_from_fd(s);\n curl_multi_assign(self->m_MultiHandle, s, fdp);\n }\n\n Glib::IOCondition kind;\n if (action & CURL_POLL_IN) kind |= Glib::IO_IN;\n if (action & CURL_POLL_OUT) kind |= Glib::IO_OUT;\n\n Glib::RefPtr<Glib::IOSource> source = fdp->chan->create_watch(kind);\n fdp->sockfd = s;\n\n if (fdp->conn)\n fdp->conn.disconnect();\n\n fdp->conn = source->connect(sigc::bind<0>(sigc::mem_fun(self, &ImageFetcher::event_cb), s));\n source->attach(self->m_MainContext);\n }\n\n return 0;\n}\n\nint ImageFetcher::timer_cb(CURLM*, long timeout_ms, void *userp)\n{\n ImageFetcher *self = static_cast<ImageFetcher*>(userp);\n\n self->m_TimeoutConn = self->m_MainContext->signal_timeout().connect(\n sigc::mem_fun(self, &ImageFetcher::timeout_cb), timeout_ms);\n\n return 0;\n}\n\nImageFetcher::ImageFetcher()\n : m_MainContext(Glib::MainContext::create()),\n m_MainLoop(Glib::MainLoop::create(m_MainContext)),\n m_MultiHandle(curl_multi_init()),\n m_RunningHandles(0)\n{\n m_Thread = std::thread([ this ]() { m_MainLoop->run(); });\n\n curl_multi_setopt(m_MultiHandle, CURLMOPT_SOCKETFUNCTION, &ImageFetcher::socket_cb);\n curl_multi_setopt(m_MultiHandle, CURLMOPT_SOCKETDATA, this);\n curl_multi_setopt(m_MultiHandle, CURLMOPT_TIMERFUNCTION, &ImageFetcher::timer_cb);\n curl_multi_setopt(m_MultiHandle, CURLMOPT_TIMERDATA, this);\n}\n\nImageFetcher::~ImageFetcher()\n{\n m_MainLoop->quit();\n m_Thread.join();\n\n for (Curler *c : m_Curlers)\n remove_handle(c);\n\n curl_multi_cleanup(m_MultiHandle);\n}\n\nvoid ImageFetcher::add_handle(Curler *curler)\n{\n std::lock_guard<std::mutex> lock(m_Mutex);\n\n curl_easy_setopt(curler->m_EasyHandle, CURLOPT_PRIVATE, curler);\n\n curler->m_Cancel->reset();\n curler->clear();\n\n m_Curlers.push_back(curler);\n curl_multi_add_handle(m_MultiHandle, curler->m_EasyHandle);\n\n curler->m_Active = true;\n curler->m_StartTime = std::chrono::steady_clock::now();\n}\n\nvoid ImageFetcher::remove_handle(Curler *curler)\n{\n if (!curler)\n return;\n\n if (curler->m_EasyHandle)\n curl_multi_remove_handle(m_MultiHandle, curler->m_EasyHandle);\n\n m_Curlers.erase(std::remove(m_Curlers.begin(), m_Curlers.end(), curler), m_Curlers.end());\n\n curler->m_Active = false;\n}\n\nbool ImageFetcher::event_cb(curl_socket_t sockfd, Glib::IOCondition cond)\n{\n int action = (cond & Glib::IO_IN ? CURL_CSELECT_IN : 0) |\n (cond & Glib::IO_OUT ? CURL_CSELECT_OUT : 0);\n\n curl_multi_socket_action(m_MultiHandle, sockfd, action, &m_RunningHandles);\n read_info();\n\n if (m_RunningHandles == 0)\n {\n m_TimeoutConn.disconnect();\n return false;\n }\n\n return true;\n}\n\nbool ImageFetcher::timeout_cb()\n{\n curl_multi_socket_action(m_MultiHandle, CURL_SOCKET_TIMEOUT, 0, &m_RunningHandles);\n read_info();\n\n return false;\n}\n\nvoid ImageFetcher::read_info()\n{\n int msgs;\n CURLMsg *msg = nullptr;\n\n while ((msg = curl_multi_info_read(m_MultiHandle, &msgs)))\n {\n if (msg->msg == CURLMSG_DONE)\n {\n Curler *curler = nullptr;\n curl_easy_getinfo(msg->easy_handle, CURLINFO_PRIVATE, &curler);\n\n if (curler)\n {\n remove_handle(curler);\n\n if (!curler->is_cancelled())\n curler->m_SignalFinished();\n }\n }\n }\n}\n<commit_msg>Revert \"booru\/imagefetcher: Remove unneeded mutex locks\"<commit_after>#include \"imagefetcher.h\"\nusing namespace AhoViewer::Booru;\n\nint ImageFetcher::socket_cb(CURL*, curl_socket_t s, int action, void *userp, void *sockp)\n{\n ImageFetcher *self = static_cast<ImageFetcher*>(userp);\n SockInfo *fdp = static_cast<SockInfo*>(sockp);\n\n if (action == CURL_POLL_REMOVE && fdp)\n {\n delete fdp;\n }\n else\n {\n if (!fdp)\n {\n fdp = new SockInfo();\n fdp->chan = Glib::IOChannel::create_from_fd(s);\n curl_multi_assign(self->m_MultiHandle, s, fdp);\n }\n\n Glib::IOCondition kind;\n if (action & CURL_POLL_IN) kind |= Glib::IO_IN;\n if (action & CURL_POLL_OUT) kind |= Glib::IO_OUT;\n\n Glib::RefPtr<Glib::IOSource> source = fdp->chan->create_watch(kind);\n fdp->sockfd = s;\n\n if (fdp->conn)\n fdp->conn.disconnect();\n\n fdp->conn = source->connect(sigc::bind<0>(sigc::mem_fun(self, &ImageFetcher::event_cb), s));\n source->attach(self->m_MainContext);\n }\n\n return 0;\n}\n\nint ImageFetcher::timer_cb(CURLM*, long timeout_ms, void *userp)\n{\n ImageFetcher *self = static_cast<ImageFetcher*>(userp);\n\n self->m_TimeoutConn = self->m_MainContext->signal_timeout().connect(\n sigc::mem_fun(self, &ImageFetcher::timeout_cb), timeout_ms);\n\n return 0;\n}\n\nImageFetcher::ImageFetcher()\n : m_MainContext(Glib::MainContext::create()),\n m_MainLoop(Glib::MainLoop::create(m_MainContext)),\n m_MultiHandle(curl_multi_init()),\n m_RunningHandles(0)\n{\n m_Thread = std::thread([ this ]() { m_MainLoop->run(); });\n\n curl_multi_setopt(m_MultiHandle, CURLMOPT_SOCKETFUNCTION, &ImageFetcher::socket_cb);\n curl_multi_setopt(m_MultiHandle, CURLMOPT_SOCKETDATA, this);\n curl_multi_setopt(m_MultiHandle, CURLMOPT_TIMERFUNCTION, &ImageFetcher::timer_cb);\n curl_multi_setopt(m_MultiHandle, CURLMOPT_TIMERDATA, this);\n}\n\nImageFetcher::~ImageFetcher()\n{\n std::lock_guard<std::mutex> lock(m_Mutex);\n\n m_MainLoop->quit();\n m_Thread.join();\n\n for (Curler *c : m_Curlers)\n remove_handle(c);\n\n curl_multi_cleanup(m_MultiHandle);\n}\n\nvoid ImageFetcher::add_handle(Curler *curler)\n{\n std::lock_guard<std::mutex> lock(m_Mutex);\n\n curl_easy_setopt(curler->m_EasyHandle, CURLOPT_PRIVATE, curler);\n\n curler->m_Cancel->reset();\n curler->clear();\n\n m_Curlers.push_back(curler);\n curl_multi_add_handle(m_MultiHandle, curler->m_EasyHandle);\n\n curler->m_Active = true;\n curler->m_StartTime = std::chrono::steady_clock::now();\n}\n\nvoid ImageFetcher::remove_handle(Curler *curler)\n{\n if (!curler)\n return;\n\n if (curler->m_EasyHandle)\n curl_multi_remove_handle(m_MultiHandle, curler->m_EasyHandle);\n\n m_Curlers.erase(std::remove(m_Curlers.begin(), m_Curlers.end(), curler), m_Curlers.end());\n\n curler->m_Active = false;\n}\n\nbool ImageFetcher::event_cb(curl_socket_t sockfd, Glib::IOCondition cond)\n{\n int action = (cond & Glib::IO_IN ? CURL_CSELECT_IN : 0) |\n (cond & Glib::IO_OUT ? CURL_CSELECT_OUT : 0);\n\n {\n std::lock_guard<std::mutex> lock(m_Mutex);\n curl_multi_socket_action(m_MultiHandle, sockfd, action, &m_RunningHandles);\n }\n read_info();\n\n if (m_RunningHandles == 0)\n {\n m_TimeoutConn.disconnect();\n return false;\n }\n\n return true;\n}\n\nbool ImageFetcher::timeout_cb()\n{\n curl_multi_socket_action(m_MultiHandle, CURL_SOCKET_TIMEOUT, 0, &m_RunningHandles);\n read_info();\n\n return false;\n}\n\nvoid ImageFetcher::read_info()\n{\n int msgs;\n CURLMsg *msg = nullptr;\n std::lock_guard<std::mutex> lock(m_Mutex);\n\n while ((msg = curl_multi_info_read(m_MultiHandle, &msgs)))\n {\n if (msg->msg == CURLMSG_DONE)\n {\n Curler *curler = nullptr;\n curl_easy_getinfo(msg->easy_handle, CURLINFO_PRIVATE, &curler);\n\n if (curler)\n {\n remove_handle(curler);\n\n if (!curler->is_cancelled())\n curler->m_SignalFinished();\n }\n }\n }\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"processor\/external_symbol_supplier.h\"\n\n#include <sys\/wait.h>\n#include <iostream>\n#include <fstream>\n#include <sstream>\n\n#include \"google_breakpad\/processor\/code_module.h\"\n#include \"processor\/logging.h\"\n\nusing std::stringstream;\n\nnamespace google_breakpad {\n\nExternalSymbolSupplier::ExternalSymbolSupplier(const string& fetch_command)\n : symbol_fetch_command_(fetch_command) {\n}\n\nSymbolSupplier::SymbolResult ExternalSymbolSupplier::GetSymbolFile(const CodeModule *module,\n const SystemInfo *system_info,\n string *symbol_file) {\n BPLOG_ERROR << \"GetSymbolFile() is not implemented\";\n return INTERRUPT;\n}\n\nSymbolSupplier::SymbolResult ExternalSymbolSupplier::GetSymbolFile(const CodeModule *module,\n const SystemInfo *system_info,\n string *symbol_file,\n string *symbol_data) {\n BPLOG_ERROR << \"GetSymbolFile() is not implemented\";\n return INTERRUPT;\n}\n\nSymbolSupplier::SymbolResult ExternalSymbolSupplier::GetCStringSymbolData(const CodeModule *module,\n const SystemInfo *system_info,\n string *symbol_file,\n char **symbol_data) {\n \/\/ search for already-loaded debug info\n map<string,string>::const_iterator it = symbol_cache_.find(module->code_file());\n if (it != symbol_cache_.end()) {\n const std::string& content = it->second;\n if (content.empty()) {\n \/\/ debug info has been requested before but was not found previously\n return NOT_FOUND;\n } else {\n *symbol_data = const_cast<char*>(content.data());\n return FOUND;\n }\n }\n\n \/\/ run external command to fetch debug info\n stringstream symbol_content;\n stringstream fetch_command;\n fetch_command << symbol_fetch_command_ << \" \" << module->debug_file() << \" \" << module->debug_identifier();\n FILE *child_proc = popen(fetch_command.str().data(), \"r\");\n if (!child_proc) {\n BPLOG_ERROR << \"Failed to start symbol fetcher \" << fetch_command.str();\n return INTERRUPT;\n }\n\n const int BUF_SIZE = 4096;\n char buffer[BUF_SIZE];\n while (!feof(child_proc)) {\n size_t nread = fread(buffer, 1, BUF_SIZE, child_proc);\n symbol_content.write(buffer, nread);\n }\n int status = pclose(child_proc);\n if (!WIFEXITED(status)) {\n BPLOG_INFO << fetch_command.str() << \" failed\";\n return INTERRUPT;\n }\n\n int exitCode = WEXITSTATUS(status);\n if (exitCode == 127) {\n \/\/ command not found\n BPLOG_INFO << \"Failed to run symbol fetch command: \" << fetch_command.str();\n return INTERRUPT;\n }\n\n if (exitCode != 0) {\n \/\/ no matching debug info found,\n \/\/ cache the omission to avoid repeated lookups for the same module\n symbol_cache_[module->code_file()] = std::string();\n BPLOG_INFO << \"No symbols found with \" << fetch_command.str() << \" (status: \" << exitCode << \")\";\n return NOT_FOUND;\n }\n\n \/\/ cache and return debug info\n symbol_cache_[module->code_file()] = symbol_content.str();\n return GetCStringSymbolData(module, system_info, symbol_file, symbol_data);\n}\n\nvoid ExternalSymbolSupplier::FreeSymbolData(const CodeModule *module) {\n map<string,string>::iterator it = symbol_cache_.find(module->code_file());\n if (it != symbol_cache_.end()) {\n symbol_cache_.erase(it);\n }\n}\n\n}\n\n<commit_msg>Fix passing of module names to external symbol fetchers on Windows<commit_after>#include \"processor\/external_symbol_supplier.h\"\n\n#include <sys\/wait.h>\n#include <iostream>\n#include <fstream>\n#include <sstream>\n\n#include \"google_breakpad\/processor\/code_module.h\"\n#include \"processor\/logging.h\"\n\nusing std::stringstream;\n\nnamespace google_breakpad {\n\nExternalSymbolSupplier::ExternalSymbolSupplier(const string& fetch_command)\n : symbol_fetch_command_(fetch_command) {\n}\n\nSymbolSupplier::SymbolResult ExternalSymbolSupplier::GetSymbolFile(const CodeModule *module,\n const SystemInfo *system_info,\n string *symbol_file) {\n BPLOG_ERROR << \"GetSymbolFile() is not implemented\";\n return INTERRUPT;\n}\n\nSymbolSupplier::SymbolResult ExternalSymbolSupplier::GetSymbolFile(const CodeModule *module,\n const SystemInfo *system_info,\n string *symbol_file,\n string *symbol_data) {\n BPLOG_ERROR << \"GetSymbolFile() is not implemented\";\n return INTERRUPT;\n}\n\nstd::string ShellEscape(const std::string& arg)\n{\n std::string result = \"'\";\n for (int i=0; i < arg.size(); i++) {\n if (arg[i] == '\\'') {\n result += '\\\\';\n }\n result += arg[i];\n }\n result += \"'\";\n return result;\n}\n\n\/\/ Returns the part of 'path' following the final trailing slash.\n\/\/\n\/\/ To support both Windows and Unix minidump paths, both '\\' and '\/'\n\/\/ are considered path component separators.\nstd::string FileBasename(const std::string& path)\n{\n int basename_start_pos = path.size();\n while (basename_start_pos > 0) {\n if (path[basename_start_pos-1] == '\/' ||\n path[basename_start_pos-1] == '\\\\') {\n break;\n }\n --basename_start_pos;\n }\n return path.substr(basename_start_pos);\n}\n\nSymbolSupplier::SymbolResult ExternalSymbolSupplier::GetCStringSymbolData(const CodeModule *module,\n const SystemInfo *system_info,\n string *symbol_file,\n char **symbol_data) {\n \/\/ search for already-loaded debug info\n map<string,string>::const_iterator it = symbol_cache_.find(module->code_file());\n if (it != symbol_cache_.end()) {\n const std::string& content = it->second;\n if (content.empty()) {\n \/\/ debug info has been requested before but was not found previously\n return NOT_FOUND;\n } else {\n *symbol_data = const_cast<char*>(content.data());\n return FOUND;\n }\n }\n\n \/\/ run external command to fetch debug info\n std::string debug_file_basename = FileBasename(module->debug_file());\n stringstream symbol_content;\n stringstream fetch_command;\n fetch_command << symbol_fetch_command_ << \" \" << ShellEscape(debug_file_basename) << \" \" << ShellEscape(module->debug_identifier());\n FILE *child_proc = popen(fetch_command.str().data(), \"r\");\n if (!child_proc) {\n BPLOG_ERROR << \"Failed to start symbol fetcher \" << fetch_command.str();\n return INTERRUPT;\n }\n\n const int BUF_SIZE = 4096;\n char buffer[BUF_SIZE];\n while (!feof(child_proc)) {\n size_t nread = fread(buffer, 1, BUF_SIZE, child_proc);\n symbol_content.write(buffer, nread);\n }\n int status = pclose(child_proc);\n if (!WIFEXITED(status)) {\n BPLOG_INFO << fetch_command.str() << \" failed\";\n return INTERRUPT;\n }\n\n int exitCode = WEXITSTATUS(status);\n if (exitCode == 127) {\n \/\/ command not found\n BPLOG_INFO << \"Failed to run symbol fetch command: \" << fetch_command.str();\n return INTERRUPT;\n }\n\n if (exitCode != 0) {\n \/\/ no matching debug info found,\n \/\/ cache the omission to avoid repeated lookups for the same module\n symbol_cache_[module->code_file()] = std::string();\n BPLOG_INFO << \"No symbols found with \" << fetch_command.str() << \" (status: \" << exitCode << \")\";\n return NOT_FOUND;\n }\n\n \/\/ cache and return debug info\n symbol_cache_[module->code_file()] = symbol_content.str();\n return GetCStringSymbolData(module, system_info, symbol_file, symbol_data);\n}\n\nvoid ExternalSymbolSupplier::FreeSymbolData(const CodeModule *module) {\n map<string,string>::iterator it = symbol_cache_.find(module->code_file());\n if (it != symbol_cache_.end()) {\n symbol_cache_.erase(it);\n }\n}\n\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n Copyright 2011 Google Inc.\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n *\/\n\n#include \"GrGLInterface.h\"\n\n#include <Windows.h>\n#include <GL\/GL.h>\n\n\/*\n * Windows makes the GL funcs all be __stdcall instead of __cdecl :(\n * This implementation will only work if GR_GL_FUNCTION_TYPE is __stdcall.\n * Otherwise, a springboard would be needed that hides the calling convention.\n *\/\n\n#define GR_GL_GET_PROC(F) gDefaultInterface.f ## F = (GrGLInterface::GrGL ## F ## Proc) wglGetProcAddress(\"gl\" #F);\n#define GR_GL_GET_PROC_SUFFIX(F, S) gDefaultInterface.f ## F = (GrGLInterface::GrGL ## F ## Proc) wglGetProcAddress(\"gl\" #F #S);\n\nvoid GrGLSetDefaultGLInterface() {\n static GrGLInterface gDefaultInterface;\n static bool gDefaultInterfaceInit;\n if (!gDefaultInterfaceInit) {\n \n \/\/ wglGetProcAddress requires a context.\n if (NULL != wglGetCurrentContext()) {\n int major, minor;\n const char* versionString = (const char*) glGetString(GL_VERSION);\n const char* extString = (const char*) glGetString(GL_EXTENSIONS);\n gl_version_from_string(&major, &minor, versionString);\n\n if (major == 1 && minor < 5) {\n \/\/ We must have array and element_array buffer objects.\n return;\n }\n\n \/\/ Functions that are part of GL 1.1 will return NULL in \n \/\/ wglGetProcAddress\n gDefaultInterface.fBlendFunc = glBlendFunc;\n gDefaultInterface.fClear = glClear;\n gDefaultInterface.fClearColor = glClearColor;\n gDefaultInterface.fClearStencil = glClearStencil;\n gDefaultInterface.fColor4ub = glColor4ub;\n gDefaultInterface.fColorMask = glColorMask;\n gDefaultInterface.fColorPointer = glColorPointer;\n gDefaultInterface.fCullFace = glCullFace;\n gDefaultInterface.fDeleteTextures = glDeleteTextures;\n gDefaultInterface.fDepthMask = glDepthMask;\n gDefaultInterface.fDisable = glDisable;\n gDefaultInterface.fDisableClientState = glDisableClientState;\n gDefaultInterface.fDrawArrays = glDrawArrays;\n gDefaultInterface.fDrawElements = glDrawElements;\n gDefaultInterface.fEnable = glEnable;\n gDefaultInterface.fEnableClientState = glEnableClientState;\n gDefaultInterface.fFrontFace = glFrontFace;\n gDefaultInterface.fGenTextures = glGenTextures;\n gDefaultInterface.fGetError = glGetError;\n gDefaultInterface.fGetIntegerv = glGetIntegerv;\n gDefaultInterface.fGetString = glGetString;\n gDefaultInterface.fLineWidth = glLineWidth;\n gDefaultInterface.fLoadMatrixf = glLoadMatrixf;\n gDefaultInterface.fMatrixMode = glMatrixMode;\n gDefaultInterface.fPixelStorei = glPixelStorei;\n gDefaultInterface.fPointSize = glPointSize;\n gDefaultInterface.fReadPixels = glReadPixels;\n gDefaultInterface.fScissor = glScissor;\n gDefaultInterface.fShadeModel = glShadeModel;\n gDefaultInterface.fStencilFunc = glStencilFunc;\n gDefaultInterface.fStencilMask = glStencilMask;\n gDefaultInterface.fStencilOp = glStencilOp;\n gDefaultInterface.fTexImage2D = glTexImage2D;\n gDefaultInterface.fTexParameteri = glTexParameteri;\n gDefaultInterface.fTexCoordPointer = glTexCoordPointer;\n gDefaultInterface.fTexEnvi = glTexEnvi;\n gDefaultInterface.fTexSubImage2D = glTexSubImage2D;\n gDefaultInterface.fViewport = glViewport;\n gDefaultInterface.fVertexPointer = glVertexPointer;\n\n GR_GL_GET_PROC(ActiveTexture);\n GR_GL_GET_PROC(AttachShader);\n GR_GL_GET_PROC(BindAttribLocation);\n GR_GL_GET_PROC(BindBuffer);\n GR_GL_GET_PROC(BindTexture);\n GR_GL_GET_PROC(BlendColor);\n GR_GL_GET_PROC(BufferData);\n GR_GL_GET_PROC(BufferSubData);\n GR_GL_GET_PROC(ClientActiveTexture);\n GR_GL_GET_PROC(CompileShader);\n GR_GL_GET_PROC(CompressedTexImage2D);\n GR_GL_GET_PROC(CreateProgram);\n GR_GL_GET_PROC(CreateShader);\n GR_GL_GET_PROC(DeleteBuffers);\n GR_GL_GET_PROC(DeleteProgram);\n GR_GL_GET_PROC(DeleteShader);\n GR_GL_GET_PROC(DisableVertexAttribArray);\n GR_GL_GET_PROC(EnableVertexAttribArray);\n GR_GL_GET_PROC(GenBuffers);\n GR_GL_GET_PROC(GetBufferParameteriv);\n GR_GL_GET_PROC(GetProgramInfoLog);\n GR_GL_GET_PROC(GetProgramiv);\n GR_GL_GET_PROC(GetShaderInfoLog);\n GR_GL_GET_PROC(GetShaderiv);\n GR_GL_GET_PROC(GetUniformLocation);\n GR_GL_GET_PROC(LinkProgram);\n GR_GL_GET_PROC(ShaderSource);\n GR_GL_GET_PROC(StencilFuncSeparate);\n GR_GL_GET_PROC(StencilMaskSeparate);\n GR_GL_GET_PROC(StencilOpSeparate);\n GR_GL_GET_PROC(Uniform1fv);\n GR_GL_GET_PROC(Uniform1i);\n GR_GL_GET_PROC(Uniform4fv);\n GR_GL_GET_PROC(UniformMatrix3fv);\n GR_GL_GET_PROC(UseProgram);\n GR_GL_GET_PROC(VertexAttrib4fv);\n GR_GL_GET_PROC(VertexAttribPointer);\n\n \/\/ First look for GL3.0 FBO or GL_ARB_framebuffer_object (same since\n \/\/ GL_ARB_framebuffer_object doesn't use ARB suffix.)\n if (major >= 3 || has_gl_extension(\"GL_ARB_framebuffer_object\")) {\n GR_GL_GET_PROC(GenFramebuffers);\n GR_GL_GET_PROC(BindFramebuffer);\n GR_GL_GET_PROC(FramebufferTexture2D);\n GR_GL_GET_PROC(CheckFramebufferStatus);\n GR_GL_GET_PROC(DeleteFramebuffers);\n GR_GL_GET_PROC(RenderbufferStorage);\n GR_GL_GET_PROC(GenRenderbuffers);\n GR_GL_GET_PROC(DeleteRenderbuffers);\n GR_GL_GET_PROC(FramebufferRenderbuffer);\n GR_GL_GET_PROC(BindRenderbuffer);\n GR_GL_GET_PROC(RenderbufferStorageMultisample);\n GR_GL_GET_PROC(BlitFramebuffer);\n } else if (has_gl_extension_from_string(\"GL_EXT_framebuffer_object\",\n extString)) {\n GR_GL_GET_PROC_SUFFIX(GenFramebuffers, EXT);\n GR_GL_GET_PROC_SUFFIX(BindFramebuffer, EXT);\n GR_GL_GET_PROC_SUFFIX(FramebufferTexture2D, EXT);\n GR_GL_GET_PROC_SUFFIX(CheckFramebufferStatus, EXT);\n GR_GL_GET_PROC_SUFFIX(DeleteFramebuffers, EXT);\n GR_GL_GET_PROC_SUFFIX(RenderbufferStorage, EXT);\n GR_GL_GET_PROC_SUFFIX(GenRenderbuffers, EXT);\n GR_GL_GET_PROC_SUFFIX(DeleteRenderbuffers, EXT);\n GR_GL_GET_PROC_SUFFIX(FramebufferRenderbuffer, EXT);\n GR_GL_GET_PROC_SUFFIX(BindRenderbuffer, EXT);\n if (has_gl_extension_from_string(\"GL_EXT_framebuffer_multisample\",\n extString)) {\n GR_GL_GET_PROC_SUFFIX(RenderbufferStorageMultisample, EXT);\n }\n if (has_gl_extension_from_string(\"GL_EXT_framebuffer_blit\",\n extString)) {\n GR_GL_GET_PROC_SUFFIX(BlitFramebuffer, EXT);\n }\n } else {\n \/\/ we must have FBOs\n return;\n }\n GR_GL_GET_PROC(MapBuffer);\n GR_GL_GET_PROC(UnmapBuffer);\n\n gDefaultInterface.fBindingsExported = kDesktop_GrGLBinding;\n\n gDefaultInterfaceInit = true;\n }\n }\n if (gDefaultInterfaceInit) {\n GrGLSetGLInterface(&gDefaultInterface);\n }\n}\n<commit_msg>Use has_gl_extension_from_string in GrGLDefaultInterface_win.cpp (before the GL iface is installed).<commit_after>\/*\n Copyright 2011 Google Inc.\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n *\/\n\n#include \"GrGLInterface.h\"\n\n#include <Windows.h>\n#include <GL\/GL.h>\n\n\/*\n * Windows makes the GL funcs all be __stdcall instead of __cdecl :(\n * This implementation will only work if GR_GL_FUNCTION_TYPE is __stdcall.\n * Otherwise, a springboard would be needed that hides the calling convention.\n *\/\n\n#define GR_GL_GET_PROC(F) gDefaultInterface.f ## F = (GrGLInterface::GrGL ## F ## Proc) wglGetProcAddress(\"gl\" #F);\n#define GR_GL_GET_PROC_SUFFIX(F, S) gDefaultInterface.f ## F = (GrGLInterface::GrGL ## F ## Proc) wglGetProcAddress(\"gl\" #F #S);\n\nvoid GrGLSetDefaultGLInterface() {\n static GrGLInterface gDefaultInterface;\n static bool gDefaultInterfaceInit;\n if (!gDefaultInterfaceInit) {\n \n \/\/ wglGetProcAddress requires a context.\n if (NULL != wglGetCurrentContext()) {\n int major, minor;\n const char* versionString = (const char*) glGetString(GL_VERSION);\n const char* extString = (const char*) glGetString(GL_EXTENSIONS);\n gl_version_from_string(&major, &minor, versionString);\n\n if (major == 1 && minor < 5) {\n \/\/ We must have array and element_array buffer objects.\n return;\n }\n\n \/\/ Functions that are part of GL 1.1 will return NULL in \n \/\/ wglGetProcAddress\n gDefaultInterface.fBlendFunc = glBlendFunc;\n gDefaultInterface.fClear = glClear;\n gDefaultInterface.fClearColor = glClearColor;\n gDefaultInterface.fClearStencil = glClearStencil;\n gDefaultInterface.fColor4ub = glColor4ub;\n gDefaultInterface.fColorMask = glColorMask;\n gDefaultInterface.fColorPointer = glColorPointer;\n gDefaultInterface.fCullFace = glCullFace;\n gDefaultInterface.fDeleteTextures = glDeleteTextures;\n gDefaultInterface.fDepthMask = glDepthMask;\n gDefaultInterface.fDisable = glDisable;\n gDefaultInterface.fDisableClientState = glDisableClientState;\n gDefaultInterface.fDrawArrays = glDrawArrays;\n gDefaultInterface.fDrawElements = glDrawElements;\n gDefaultInterface.fEnable = glEnable;\n gDefaultInterface.fEnableClientState = glEnableClientState;\n gDefaultInterface.fFrontFace = glFrontFace;\n gDefaultInterface.fGenTextures = glGenTextures;\n gDefaultInterface.fGetError = glGetError;\n gDefaultInterface.fGetIntegerv = glGetIntegerv;\n gDefaultInterface.fGetString = glGetString;\n gDefaultInterface.fLineWidth = glLineWidth;\n gDefaultInterface.fLoadMatrixf = glLoadMatrixf;\n gDefaultInterface.fMatrixMode = glMatrixMode;\n gDefaultInterface.fPixelStorei = glPixelStorei;\n gDefaultInterface.fPointSize = glPointSize;\n gDefaultInterface.fReadPixels = glReadPixels;\n gDefaultInterface.fScissor = glScissor;\n gDefaultInterface.fShadeModel = glShadeModel;\n gDefaultInterface.fStencilFunc = glStencilFunc;\n gDefaultInterface.fStencilMask = glStencilMask;\n gDefaultInterface.fStencilOp = glStencilOp;\n gDefaultInterface.fTexImage2D = glTexImage2D;\n gDefaultInterface.fTexParameteri = glTexParameteri;\n gDefaultInterface.fTexCoordPointer = glTexCoordPointer;\n gDefaultInterface.fTexEnvi = glTexEnvi;\n gDefaultInterface.fTexSubImage2D = glTexSubImage2D;\n gDefaultInterface.fViewport = glViewport;\n gDefaultInterface.fVertexPointer = glVertexPointer;\n\n GR_GL_GET_PROC(ActiveTexture);\n GR_GL_GET_PROC(AttachShader);\n GR_GL_GET_PROC(BindAttribLocation);\n GR_GL_GET_PROC(BindBuffer);\n GR_GL_GET_PROC(BindTexture);\n GR_GL_GET_PROC(BlendColor);\n GR_GL_GET_PROC(BufferData);\n GR_GL_GET_PROC(BufferSubData);\n GR_GL_GET_PROC(ClientActiveTexture);\n GR_GL_GET_PROC(CompileShader);\n GR_GL_GET_PROC(CompressedTexImage2D);\n GR_GL_GET_PROC(CreateProgram);\n GR_GL_GET_PROC(CreateShader);\n GR_GL_GET_PROC(DeleteBuffers);\n GR_GL_GET_PROC(DeleteProgram);\n GR_GL_GET_PROC(DeleteShader);\n GR_GL_GET_PROC(DisableVertexAttribArray);\n GR_GL_GET_PROC(EnableVertexAttribArray);\n GR_GL_GET_PROC(GenBuffers);\n GR_GL_GET_PROC(GetBufferParameteriv);\n GR_GL_GET_PROC(GetProgramInfoLog);\n GR_GL_GET_PROC(GetProgramiv);\n GR_GL_GET_PROC(GetShaderInfoLog);\n GR_GL_GET_PROC(GetShaderiv);\n GR_GL_GET_PROC(GetUniformLocation);\n GR_GL_GET_PROC(LinkProgram);\n GR_GL_GET_PROC(ShaderSource);\n GR_GL_GET_PROC(StencilFuncSeparate);\n GR_GL_GET_PROC(StencilMaskSeparate);\n GR_GL_GET_PROC(StencilOpSeparate);\n GR_GL_GET_PROC(Uniform1fv);\n GR_GL_GET_PROC(Uniform1i);\n GR_GL_GET_PROC(Uniform4fv);\n GR_GL_GET_PROC(UniformMatrix3fv);\n GR_GL_GET_PROC(UseProgram);\n GR_GL_GET_PROC(VertexAttrib4fv);\n GR_GL_GET_PROC(VertexAttribPointer);\n\n \/\/ First look for GL3.0 FBO or GL_ARB_framebuffer_object (same since\n \/\/ GL_ARB_framebuffer_object doesn't use ARB suffix.)\n if (major >= 3 || has_gl_extension_from_string(\"GL_ARB_framebuffer_object\", extString)) {\n GR_GL_GET_PROC(GenFramebuffers);\n GR_GL_GET_PROC(BindFramebuffer);\n GR_GL_GET_PROC(FramebufferTexture2D);\n GR_GL_GET_PROC(CheckFramebufferStatus);\n GR_GL_GET_PROC(DeleteFramebuffers);\n GR_GL_GET_PROC(RenderbufferStorage);\n GR_GL_GET_PROC(GenRenderbuffers);\n GR_GL_GET_PROC(DeleteRenderbuffers);\n GR_GL_GET_PROC(FramebufferRenderbuffer);\n GR_GL_GET_PROC(BindRenderbuffer);\n GR_GL_GET_PROC(RenderbufferStorageMultisample);\n GR_GL_GET_PROC(BlitFramebuffer);\n } else if (has_gl_extension_from_string(\"GL_EXT_framebuffer_object\", extString)) {\n GR_GL_GET_PROC_SUFFIX(GenFramebuffers, EXT);\n GR_GL_GET_PROC_SUFFIX(BindFramebuffer, EXT);\n GR_GL_GET_PROC_SUFFIX(FramebufferTexture2D, EXT);\n GR_GL_GET_PROC_SUFFIX(CheckFramebufferStatus, EXT);\n GR_GL_GET_PROC_SUFFIX(DeleteFramebuffers, EXT);\n GR_GL_GET_PROC_SUFFIX(RenderbufferStorage, EXT);\n GR_GL_GET_PROC_SUFFIX(GenRenderbuffers, EXT);\n GR_GL_GET_PROC_SUFFIX(DeleteRenderbuffers, EXT);\n GR_GL_GET_PROC_SUFFIX(FramebufferRenderbuffer, EXT);\n GR_GL_GET_PROC_SUFFIX(BindRenderbuffer, EXT);\n if (has_gl_extension_from_string(\"GL_EXT_framebuffer_multisample\", extString)) {\n GR_GL_GET_PROC_SUFFIX(RenderbufferStorageMultisample, EXT);\n }\n if (has_gl_extension_from_string(\"GL_EXT_framebuffer_blit\", extString)) {\n GR_GL_GET_PROC_SUFFIX(BlitFramebuffer, EXT);\n }\n } else {\n \/\/ we must have FBOs\n return;\n }\n GR_GL_GET_PROC(MapBuffer);\n GR_GL_GET_PROC(UnmapBuffer);\n\n gDefaultInterface.fBindingsExported = kDesktop_GrGLBinding;\n\n gDefaultInterfaceInit = true;\n }\n }\n if (gDefaultInterfaceInit) {\n GrGLSetGLInterface(&gDefaultInterface);\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ **************************************************************************\n\/\/ * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *\n\/\/ * *\n\/\/ * Author: The ALICE Off-line Project. *\n\/\/ * Contributors are mentioned in the code where appropriate. *\n\/\/ * *\n\/\/ * Permission to use, copy, modify and distribute this software and its *\n\/\/ * documentation strictly for non-commercial purposes is hereby granted *\n\/\/ * without fee, provided that the above copyright notice appears in all *\n\/\/ * copies and that both the copyright notice and this permission notice *\n\/\/ * appear in the supporting documentation. The authors make no claims *\n\/\/ * about the suitability of this software for any purpose. It is *\n\/\/ * provided \"as is\" without express or implied warranty. *\n\/\/ **************************************************************************\n\n#include \"AliRICHCluster.h\" \/\/class header\n#include <TMinuit.h> \/\/Solve()\n#include <AliStack.h> \/\/FindCfm(), Solve() \n#include <TParticle.h> \/\/FindCfm()\n#include <TClonesArray.h> \/\/Solve() Test()\n\nClassImp(AliRICHCluster)\n\/\/__________________________________________________________________________________________________\nvoid AliRICHCluster::CoG()\n{\n\/\/ Calculates naive cluster position as a center of gravity of its digits.\n\/\/ Arguments: none \n\/\/ Returns: shape of the cluster i.e. the box which fully contains the cluster \n if(fDigs==0) return; \/\/no digits in this cluster\n fX=fY=0; \/\/set cluster position to (0,0) to start to collect contributions\n for(Int_t iDig=0;iDig<fDigs->GetEntriesFast();iDig++){\/\/digits loop\n AliRICHDigit *pDig=(AliRICHDigit*)fDigs->At(iDig); \/\/get pointer to next digit\n TVector pad=pDig->Pad(); Double_t q=pDig->Qdc(); \/\/get pad adn QDC of this digit \n TVector2 x2=AliRICHParam::Pad2Loc(pad); \/\/calculate center of the pad in LORS\n fX += x2.X()*q;fY +=x2.Y()*q; \/\/sum up digit centers weighted by QDC\n }\/\/digits loop\n fX\/=fQdc;fY\/=fQdc; \/\/final center of gravity\n\n TVector2 center = AliRICHParam::Pad2Loc(AliRICHParam::Loc2Pad(TVector2(fX,fY)));\/\/center of the pad containing calculated cluster position\n fX += AliRICHParam::CogCorr(fX-center.X()); \/\/correct cluster position for sinoid\n\n fStatus=kCoG;\n}\/\/CoG()\n\/\/__________________________________________________________________________________________________\nvoid AliRICHCluster::FitFunc(Int_t &iNpars, Double_t *, Double_t &chi2, Double_t *par, Int_t )\n{\n\/\/ Cluster fit function \n\/\/ par[0]=x par[1]=y par[2]=q for the first Mathieson shape\n\/\/ par[3]=x par[4]=y par[5]=q for the second Mathieson shape and so on up to iNpars\/3 Mathieson shapes\n\/\/ We need to calculate QpadExp - QpadMathieson summup over all pads of the cluster\n\/\/ Here QpadExp is a actual charge of the pad, QpadMathieson is calculated charge of the pad induced by all Mathiesons\n\/\/ Arguments: iNpars - number of parameters which is number of local maxima of cluster * 3\n\/\/ chi2 - function result to be minimised \n\/\/ par - parameters array of size iNpars \n\/\/ Returns: none \n AliRICHCluster *pClu=(AliRICHCluster*)gMinuit->GetObjectFit();\n Int_t iNmathiesons = iNpars\/3;\n \n TVector2 curMathiesonPos;\n chi2 = 0;\n for(Int_t i=0;i<pClu->Size();i++){ \/\/loop on all pads of the cluster\n TVector pad = pClu->Dig(i)->Pad();\n Double_t dQpadExp = pClu->Dig(i)->Qdc();\n Double_t dQpadMathieson = 0;\n for(Int_t j=0;j<iNmathiesons;j++){ \/\/Mathiesons loop as all of them may contribute to this pad\n curMathiesonPos.Set(par[3*j],par[3*j+1]); \/\/get position of current Mathieson\n dQpadMathieson += par[3*j+2]*AliRICHParam::FracQdc(curMathiesonPos,pad); \/\/sums up contributions to the current pad from all Mathiesons\n }\n chi2 += TMath::Power((dQpadMathieson-dQpadExp),2); \/\/\n } \/\/loop on all pads of the cluster \n}\/\/FitFunction()\n\/\/__________________________________________________________________________________________________\nvoid AliRICHCluster::Print(Option_t* opt)const\n{\n\/\/Print current cluster \n const char *status=0;\n switch(fStatus){\n case kFormed: status=\"formed\" ;break;\n case kUnfolded: status=\"unfolded\" ;break;\n case kCoG: status=\"coged\" ;break;\n case kEmpty: status=\"empty\" ;break;\n }\n Printf(\"%s cs=%2i, Size=%2i (x=%7.3f cm,y=%7.3f cm,Q=%4i qdc), %s\",\n opt,fCham,Size(),fX,fY,fQdc,status);\n for(Int_t i=0;i<Size();i++) Dig(i)->Print(); \n}\/\/Print()\n\/\/__________________________________________________________________________________________________\nInt_t AliRICHCluster::Solve(TClonesArray *pCluLst,Bool_t isTryUnfold)\n{\n\/\/This methode is invoked when the cluster is formed to solve it. Solve the cluster means to try to unfold the cluster\n\/\/into the local maxima number of clusters. This methode is invoked by AliRICHRconstructor::Dig2Clu() on cluster by cluster basis. \n\/\/At this point, cluster contains a list of digits, cluster charge and size is precalculated in AddDigit(), position is preset to (-1,-1) in ctor,\n\/\/status is preset to kFormed in AddDigit(), chamber-sector info is preseted to actual values in AddDigit()\n\/\/Method first finds number of local maxima and if it's more then one tries to unfold this cluster into local maxima number of clusters\n\/\/Arguments: pCluLst - cluster list pointer where to add new cluster(s)\n\/\/ isTryUnfold - flag to switch on\/off unfolding \n\/\/ Returns: number of local maxima of original cluster\n\n\/\/Phase 0. Initialise TMinuit \n const Int_t kMaxLocMax=6; \/\/max allowed number of loc max for fitting\n TMinuit *pMinuit = new TMinuit(3*kMaxLocMax); \/\/init MINUIT with this number of parameters (3 params per mathieson)\n pMinuit->SetObjectFit((TObject*)this); pMinuit->SetFCN(AliRICHCluster::FitFunc); \/\/set fit function\n Double_t aArg=-1,parStart,parStep,parLow,parHigh; Int_t iErrFlg; \/\/tmp vars for TMinuit\n pMinuit->mnexcm(\"SET PRI\",&aArg,1,iErrFlg); \/\/suspend all printout from TMinuit \n pMinuit->mnexcm(\"SET NOW\",&aArg,0,iErrFlg); \/\/suspend all warning printout from TMinuit\n\/\/Phase 1. Find number of local maxima. Strategy is to check if the current pad has QDC more then all neigbours \n Int_t iLocMaxCnt=0;\n for(Int_t iDig1=0;iDig1<Size();iDig1++) { \/\/first digits loop\n AliRICHDigit *pDig1 = Dig(iDig1); \/\/take next digit\n Int_t iHowManyMoreCnt = 0; \/\/counts how many neighbouring pads has QDC more then current one\n for(Int_t iDig2=0;iDig2<Size();iDig2++) { \/\/loop on all digits again\n AliRICHDigit *pDig2 = Dig(iDig2); \/\/take second digit to compare with the first one\n if(iDig1==iDig2) continue; \/\/the same digit, no need to compare \n Int_t dist = TMath::Sign(Int_t(pDig1->PadX()-pDig2->PadX()),1)+TMath::Sign(Int_t(pDig1->PadY()-pDig2->PadY()),1);\/\/distance between pads\n if(dist==1) \/\/means dig2 is a neighbour of dig1\n if(pDig2->Qdc()>=pDig1->Qdc()) iHowManyMoreCnt++; \/\/count number of pads with Q more then Q of current pad\n }\/\/second digits loop\n if(iHowManyMoreCnt==0&&iLocMaxCnt<=kMaxLocMax){ \/\/this pad has Q more then any neighbour so it's local maximum\n TVector2 x2=AliRICHParam::Pad2Loc(pDig1->Pad()); \/\/take pad center position and use it as parameter for current Mathienson shape\n pMinuit->mnparm(3*iLocMaxCnt ,Form(\"x%i\",iLocMaxCnt),parStart=x2.X() ,parStep=0.01,parLow=0,parHigh=0,iErrFlg);\n pMinuit->mnparm(3*iLocMaxCnt+1,Form(\"y%i\",iLocMaxCnt),parStart=x2.Y() ,parStep=0.01,parLow=0,parHigh=0,iErrFlg);\n pMinuit->mnparm(3*iLocMaxCnt+2,Form(\"q%i\",iLocMaxCnt),parStart=pDig1->Qdc(),parStep=0.01,parLow=0,parHigh=0,iErrFlg);\n iLocMaxCnt++;\n }\/\/if this pad is local maximum\n }\/\/first digits loop\n\/\/Phase 2. Fit loc max number of Mathiesons or add this current cluster to the list\n Int_t iCluCnt=pCluLst->GetEntriesFast(); \/\/get current number of clusters already stored in the list by previous operations\n if(isTryUnfold==kTRUE && iLocMaxCnt<=kMaxLocMax){ \/\/resonable number of local maxima to fit and user requested it\n pMinuit->mnexcm(\"MIGRAD\" ,&aArg,0,iErrFlg); \/\/start fitting\n Double_t fitX,fitY,fitQ,d1,d2,d3; TString sName; \/\/vars to get results from TMinuit\n for(Int_t i=0;i<iLocMaxCnt;i++){\/\/local maxima loop\n pMinuit->mnpout(3*i ,sName, fitX, d1 , d2, d3, iErrFlg);\n pMinuit->mnpout(3*i+1 ,sName, fitY, d1 , d2, d3, iErrFlg);\n pMinuit->mnpout(3*i+2 ,sName, fitQ, d1 , d2, d3, iErrFlg);\n new ((*pCluLst)[iCluCnt++]) AliRICHCluster(C(),fitX,fitY,(Int_t)fitQ);\t \/\/add new unfolded clusters\n }\/\/local maxima loop\n }else{\/\/do not unfold since number of loc max is unresonably high or user's baned unfolding \n CoG();\n new ((*pCluLst)[iCluCnt++]) AliRICHCluster(*this); \/\/add this raw cluster \n }\n delete pMinuit;\n return iLocMaxCnt;\n}\/\/Solve()\n\/\/__________________________________________________________________________________________________\nvoid AliRICHCluster::Test(Double_t x,Double_t y,Double_t e,Bool_t isTryUnfold)\n{\n\/\/This is to test all cluster functionality\n\/\/Uses AddDigit() to add a predifined pad structure and then calls Solve \n TVector2 hitX2(x,y);\n Int_t iQtot=AliRICHParam::TotQdc(hitX2,e);\n if(iQtot==0){\n Printf(\"Provided hit position out of sensitive area\");\n return;\n }\n TVector area=AliRICHParam::Loc2Area(hitX2);\n TVector pad(2);\n AliRICHCluster clu;\n for(pad[1]=area[1];pad[1]<=area[3];pad[1]++){\/\/affected pads loop first y\n for(pad[0]=area[0];pad[0]<=area[2];pad[0]++){\/\/then x \n Double_t dQpad=iQtot*AliRICHParam::FracQdc(hitX2,pad);\/\/charge fraction from Mathieson centered at x to pad\n clu.DigAdd(new AliRICHDigit(pad,dQpad));\n }\/\/affected pads loop \n }\n clu.CoG(); clu.Print(\"Initial cluster:\");\n TClonesArray *pCluLst=new TClonesArray(\"AliRICHCluster\",1);\n clu.Solve(pCluLst,isTryUnfold); \n Printf(\"Initial hit : (%.2f,%.2f) Qtot=%i E=%.2f eV\",x,y,iQtot,e*1e9);\n ((AliRICHCluster *)pCluLst->At(0))->Print(\"Solved cluster:\");\n \n delete pCluLst; clu.Reset();\n}\/\/Test()\n\/\/__________________________________________________________________________________________________\nvoid AliRICHCluster::Test()\n{\n\/\/Test cluster builder by a number of predefined digit patterns\n\/\/Arguments: none\n\/\/ Returns: none\n AliRICHCluster clu; Int_t ch,padx,pady,qdc; TClonesArray *pCluLst=new TClonesArray(\"AliRICHCluster\",10);\n Printf(\"2 digits vertical cluster\");\n clu.DigAdd(new AliRICHDigit(AliRICHDigit::P2A(ch=1,padx=3,pady=3),qdc=101));\n clu.DigAdd(new AliRICHDigit(AliRICHDigit::P2A(ch=1,padx=3,pady=4),qdc=202)); \n \n clu.Print(\"Formed cluster:\");\n clu.Solve(pCluLst,kTRUE); \n pCluLst->Print();\n delete pCluLst;\n}\n<commit_msg>Fix to avoid problems in the fit of clusters (K.Shileev)<commit_after>\/\/ **************************************************************************\n\/\/ * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *\n\/\/ * *\n\/\/ * Author: The ALICE Off-line Project. *\n\/\/ * Contributors are mentioned in the code where appropriate. *\n\/\/ * *\n\/\/ * Permission to use, copy, modify and distribute this software and its *\n\/\/ * documentation strictly for non-commercial purposes is hereby granted *\n\/\/ * without fee, provided that the above copyright notice appears in all *\n\/\/ * copies and that both the copyright notice and this permission notice *\n\/\/ * appear in the supporting documentation. The authors make no claims *\n\/\/ * about the suitability of this software for any purpose. It is *\n\/\/ * provided \"as is\" without express or implied warranty. *\n\/\/ **************************************************************************\n\n#include \"AliRICHCluster.h\" \/\/class header\n#include <TMinuit.h> \/\/Solve()\n#include <AliStack.h> \/\/FindCfm(), Solve() \n#include <TParticle.h> \/\/FindCfm()\n#include <TClonesArray.h> \/\/Solve() Test()\n\nClassImp(AliRICHCluster)\n\/\/__________________________________________________________________________________________________\nvoid AliRICHCluster::CoG()\n{\n\/\/ Calculates naive cluster position as a center of gravity of its digits.\n\/\/ Arguments: none \n\/\/ Returns: shape of the cluster i.e. the box which fully contains the cluster \n if(fDigs==0) return; \/\/no digits in this cluster\n fX=fY=0; \/\/set cluster position to (0,0) to start to collect contributions\n for(Int_t iDig=0;iDig<fDigs->GetEntriesFast();iDig++){\/\/digits loop\n AliRICHDigit *pDig=(AliRICHDigit*)fDigs->At(iDig); \/\/get pointer to next digit\n TVector pad=pDig->Pad(); Double_t q=pDig->Qdc(); \/\/get pad adn QDC of this digit \n TVector2 x2=AliRICHParam::Pad2Loc(pad); \/\/calculate center of the pad in LORS\n fX += x2.X()*q;fY +=x2.Y()*q; \/\/sum up digit centers weighted by QDC\n }\/\/digits loop\n fX\/=fQdc;fY\/=fQdc; \/\/final center of gravity\n\n TVector2 center = AliRICHParam::Pad2Loc(AliRICHParam::Loc2Pad(TVector2(fX,fY)));\/\/center of the pad containing calculated cluster position\n fX += AliRICHParam::CogCorr(fX-center.X()); \/\/correct cluster position for sinoid\n\n fStatus=kCoG;\n}\/\/CoG()\n\/\/__________________________________________________________________________________________________\nvoid AliRICHCluster::FitFunc(Int_t &iNpars, Double_t *, Double_t &chi2, Double_t *par, Int_t )\n{\n\/\/ Cluster fit function \n\/\/ par[0]=x par[1]=y par[2]=q for the first Mathieson shape\n\/\/ par[3]=x par[4]=y par[5]=q for the second Mathieson shape and so on up to iNpars\/3 Mathieson shapes\n\/\/ We need to calculate QpadExp - QpadMathieson summup over all pads of the cluster\n\/\/ Here QpadExp is a actual charge of the pad, QpadMathieson is calculated charge of the pad induced by all Mathiesons\n\/\/ Arguments: iNpars - number of parameters which is number of local maxima of cluster * 3\n\/\/ chi2 - function result to be minimised \n\/\/ par - parameters array of size iNpars \n\/\/ Returns: none \n AliRICHCluster *pClu=(AliRICHCluster*)gMinuit->GetObjectFit();\n Int_t iNmathiesons = iNpars\/3;\n \n TVector2 curMathiesonPos;\n chi2 = 0;\n for(Int_t i=0;i<pClu->Size();i++){ \/\/loop on all pads of the cluster\n TVector pad = pClu->Dig(i)->Pad();\n Double_t dQpadExp = pClu->Dig(i)->Qdc();\n Double_t dQpadMathieson = 0;\n for(Int_t j=0;j<iNmathiesons;j++){ \/\/Mathiesons loop as all of them may contribute to this pad\n curMathiesonPos.Set(par[3*j],par[3*j+1]); \/\/get position of current Mathieson\n dQpadMathieson += par[3*j+2]*AliRICHParam::FracQdc(curMathiesonPos,pad); \/\/sums up contributions to the current pad from all Mathiesons\n }\n chi2 += TMath::Power((dQpadMathieson-dQpadExp),2); \/\/\n } \/\/loop on all pads of the cluster \n}\/\/FitFunction()\n\/\/__________________________________________________________________________________________________\nvoid AliRICHCluster::Print(Option_t* opt)const\n{\n\/\/Print current cluster \n const char *status=0;\n switch(fStatus){\n case kFormed: status=\"formed\" ;break;\n case kUnfolded: status=\"unfolded\" ;break;\n case kCoG: status=\"coged\" ;break;\n case kEmpty: status=\"empty\" ;break;\n }\n Printf(\"%s cs=%2i, Size=%2i (x=%7.3f cm,y=%7.3f cm,Q=%4i qdc), %s\",\n opt,fCham,Size(),fX,fY,fQdc,status);\n for(Int_t i=0;i<Size();i++) Dig(i)->Print(); \n}\/\/Print()\n\/\/__________________________________________________________________________________________________\nInt_t AliRICHCluster::Solve(TClonesArray *pCluLst,Bool_t isTryUnfold)\n{\n\/\/This methode is invoked when the cluster is formed to solve it. Solve the cluster means to try to unfold the cluster\n\/\/into the local maxima number of clusters. This methode is invoked by AliRICHRconstructor::Dig2Clu() on cluster by cluster basis. \n\/\/At this point, cluster contains a list of digits, cluster charge and size is precalculated in AddDigit(), position is preset to (-1,-1) in ctor,\n\/\/status is preset to kFormed in AddDigit(), chamber-sector info is preseted to actual values in AddDigit()\n\/\/Method first finds number of local maxima and if it's more then one tries to unfold this cluster into local maxima number of clusters\n\/\/Arguments: pCluLst - cluster list pointer where to add new cluster(s)\n\/\/ isTryUnfold - flag to switch on\/off unfolding \n\/\/ Returns: number of local maxima of original cluster\n\n\/\/Phase 0. Initialise TMinuit \n const Int_t kMaxLocMax=6; \/\/max allowed number of loc max for fitting\n TMinuit *pMinuit = new TMinuit(3*kMaxLocMax); \/\/init MINUIT with this number of parameters (3 params per mathieson)\n pMinuit->SetObjectFit((TObject*)this); pMinuit->SetFCN(AliRICHCluster::FitFunc); \/\/set fit function\n Double_t aArg=-1,parStart,parStep,parLow,parHigh; Int_t iErrFlg; \/\/tmp vars for TMinuit\n pMinuit->mnexcm(\"SET PRI\",&aArg,1,iErrFlg); \/\/suspend all printout from TMinuit \n pMinuit->mnexcm(\"SET NOW\",&aArg,0,iErrFlg); \/\/suspend all warning printout from TMinuit\n\/\/Phase 1. Find number of local maxima. Strategy is to check if the current pad has QDC more then all neigbours \n Int_t iLocMaxCnt=0;\n for(Int_t iDig1=0;iDig1<Size();iDig1++) { \/\/first digits loop\n AliRICHDigit *pDig1 = Dig(iDig1); \/\/take next digit\n Int_t iHowManyMoreCnt = 0; \/\/counts how many neighbouring pads has QDC more then current one\n for(Int_t iDig2=0;iDig2<Size();iDig2++) { \/\/loop on all digits again\n if(iDig1==iDig2) continue; \/\/the same digit, no need to compare \n AliRICHDigit *pDig2 = Dig(iDig2); \/\/take second digit to compare with the first one\n Int_t dist = TMath::Sign(Int_t(pDig1->PadX()-pDig2->PadX()),1)+TMath::Sign(Int_t(pDig1->PadY()-pDig2->PadY()),1);\/\/distance between pads\n if(dist==1) \/\/means dig2 is a neighbour of dig1\n if(pDig2->Qdc()>=pDig1->Qdc()) iHowManyMoreCnt++; \/\/count number of pads with Q more then Q of current pad\n }\/\/second digits loop\n if(iHowManyMoreCnt==0&&iLocMaxCnt<kMaxLocMax){ \/\/this pad has Q more then any neighbour so it's local maximum\n TVector2 x2=AliRICHParam::Pad2Loc(pDig1->Pad()); \/\/take pad center position and use it as parameter for current Mathienson shape\n pMinuit->mnparm(3*iLocMaxCnt ,Form(\"x%i\",iLocMaxCnt),parStart=x2.X() ,parStep=0.01,parLow=0,parHigh=0,iErrFlg);\n pMinuit->mnparm(3*iLocMaxCnt+1,Form(\"y%i\",iLocMaxCnt),parStart=x2.Y() ,parStep=0.01,parLow=0,parHigh=0,iErrFlg);\n pMinuit->mnparm(3*iLocMaxCnt+2,Form(\"q%i\",iLocMaxCnt),parStart=pDig1->Qdc(),parStep=0.01,parLow=0,parHigh=0,iErrFlg);\n iLocMaxCnt++;\n }\/\/if this pad is local maximum\n }\/\/first digits loop\n\/\/Phase 2. Fit loc max number of Mathiesons or add this current cluster to the list\n Int_t iCluCnt=pCluLst->GetEntriesFast(); \/\/get current number of clusters already stored in the list by previous operations\n if(isTryUnfold==kTRUE && iLocMaxCnt<kMaxLocMax){ \/\/resonable number of local maxima to fit and user requested it\n pMinuit->mnexcm(\"MIGRAD\" ,&aArg,0,iErrFlg); \/\/start fitting\n Double_t fitX,fitY,fitQ,d1,d2,d3; TString sName; \/\/vars to get results from TMinuit\n for(Int_t i=0;i<iLocMaxCnt;i++){\/\/local maxima loop\n pMinuit->mnpout(3*i ,sName, fitX, d1 , d2, d3, iErrFlg);\n pMinuit->mnpout(3*i+1 ,sName, fitY, d1 , d2, d3, iErrFlg);\n pMinuit->mnpout(3*i+2 ,sName, fitQ, d1 , d2, d3, iErrFlg);\n new ((*pCluLst)[iCluCnt++]) AliRICHCluster(C(),fitX,fitY,(Int_t)fitQ);\t \/\/add new unfolded clusters\n }\/\/local maxima loop\n }else{\/\/do not unfold since number of loc max is unresonably high or user's baned unfolding \n CoG();\n new ((*pCluLst)[iCluCnt++]) AliRICHCluster(*this); \/\/add this raw cluster \n }\n delete pMinuit;\n return iLocMaxCnt;\n}\/\/Solve()\n\/\/__________________________________________________________________________________________________\nvoid AliRICHCluster::Test(Double_t x,Double_t y,Double_t e,Bool_t isTryUnfold)\n{\n\/\/This is to test all cluster functionality\n\/\/Uses AddDigit() to add a predifined pad structure and then calls Solve \n TVector2 hitX2(x,y);\n Int_t iQtot=AliRICHParam::TotQdc(hitX2,e);\n if(iQtot==0){\n Printf(\"Provided hit position out of sensitive area\");\n return;\n }\n TVector area=AliRICHParam::Loc2Area(hitX2);\n TVector pad(2);\n AliRICHCluster clu;\n for(pad[1]=area[1];pad[1]<=area[3];pad[1]++){\/\/affected pads loop first y\n for(pad[0]=area[0];pad[0]<=area[2];pad[0]++){\/\/then x \n Double_t dQpad=iQtot*AliRICHParam::FracQdc(hitX2,pad);\/\/charge fraction from Mathieson centered at x to pad\n clu.DigAdd(new AliRICHDigit(pad,dQpad));\n }\/\/affected pads loop \n }\n clu.CoG(); clu.Print(\"Initial cluster:\");\n TClonesArray *pCluLst=new TClonesArray(\"AliRICHCluster\",1);\n clu.Solve(pCluLst,isTryUnfold); \n Printf(\"Initial hit : (%.2f,%.2f) Qtot=%i E=%.2f eV\",x,y,iQtot,e*1e9);\n ((AliRICHCluster *)pCluLst->At(0))->Print(\"Solved cluster:\");\n \n delete pCluLst; clu.Reset();\n}\/\/Test()\n\/\/__________________________________________________________________________________________________\nvoid AliRICHCluster::Test()\n{\n\/\/Test cluster builder by a number of predefined digit patterns\n\/\/Arguments: none\n\/\/ Returns: none\n AliRICHCluster clu; Int_t ch,padx,pady,qdc; TClonesArray *pCluLst=new TClonesArray(\"AliRICHCluster\",10);\n Printf(\"2 digits vertical cluster\");\n clu.DigAdd(new AliRICHDigit(AliRICHDigit::P2A(ch=1,padx=3,pady=3),qdc=101));\n clu.DigAdd(new AliRICHDigit(AliRICHDigit::P2A(ch=1,padx=3,pady=4),qdc=202)); \n \n clu.Print(\"Formed cluster:\");\n clu.Solve(pCluLst,kTRUE); \n pCluLst->Print();\n delete pCluLst;\n}\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n#include <stdexcept>\n#include <string>\n#include <vector>\n#include <fstream>\n\n#include <spine\/HTTP.h>\n\n#include <boost\/program_options.hpp>\n#include <boost\/filesystem.hpp>\n#include <boost\/asio.hpp>\n#include <boost\/foreach.hpp>\n#include <boost\/array.hpp>\n#include <boost\/bind.hpp>\n#include <boost\/date_time\/posix_time\/posix_time.hpp>\n#include <boost\/algorithm\/string.hpp>\n\n#include <macgyver\/ThreadPool.h>\n\ntypedef Fmi::ThreadPool::ThreadPool<> pool;\n\nusing namespace std;\n\nnamespace fs = boost::filesystem;\n\nnamespace ip = boost::asio::ip;\n\nnamespace bp = boost::posix_time;\n\nnamespace po = boost::program_options;\n\npair<string, string> parseStatus(const boost::iterator_range<char*>& message)\n{\n std::vector<boost::iterator_range<std::string::const_iterator> > headerTokens;\n vector<string> statusLineTokens(3);\n\n auto header_boundary = boost::algorithm::find_first(message, \"\\r\\n\\r\\n\");\n\n auto header_range = boost::make_iterator_range(message.begin(), header_boundary.begin());\n boost::algorithm::split(\n headerTokens, header_range, boost::is_any_of(\"\\r\\n\"), boost::token_compress_on);\n\n if (headerTokens.empty())\n {\n return pair<string, string>();\n }\n\n auto startIt = headerTokens.begin();\n boost::algorithm::split(statusLineTokens, *startIt, boost::is_space(), boost::token_compress_on);\n\n string messageBody = string(header_boundary.end(), message.end());\n\n boost::algorithm::replace_all(messageBody, \"\\n\", \" \");\n boost::algorithm::replace_all(messageBody, \"\\r\", \" \");\n\n string code;\n try\n {\n code = statusLineTokens.at(1);\n }\n catch (...)\n {\n return pair<string, string>();\n }\n\n return make_pair(code, messageBody);\n}\n\nstruct Request\n{\n Request(string host, unsigned short port, string URI) : hostName(host), port(port), URI(URI) {}\n friend ostream& operator<<(ostream& stream, const Request& theReq)\n {\n stream << theReq.hostName << \":\" << theReq.port << theReq.URI;\n return stream;\n }\n\n string hostName;\n\n unsigned short port;\n\n string URI;\n};\n\nstruct Result\n{\n Result(bp::ptime resTime, string URI, bp::time_duration duration, string status, string response)\n : resTime(resTime), URI(URI), duration(duration), status(status), response(response)\n {\n }\n\n friend ostream& operator<<(ostream& stream, const Result& theRes)\n {\n stream << theRes.resTime << \"###\" << theRes.URI << \"###\"\n << bp::to_simple_string(theRes.duration) << \"###\" << theRes.status << \"###\"\n << theRes.response;\n return stream;\n }\n\n bp::ptime resTime;\n\n string URI;\n\n bp::time_duration duration;\n\n string status;\n\n string response;\n};\n\nclass Tester\n{\n public:\n Tester(const string& requestFile,\n unsigned int threads,\n const string& hostname,\n unsigned short port)\n : itsHostName(hostname),\n itsPort(port),\n itsRequestFilePath(requestFile),\n itsThreadPool(new pool(threads)),\n itsSignals(itsIO),\n itsCurrentResultInd(0),\n itsPrintResults(false)\n {\n if (!fs::exists(itsRequestFilePath))\n {\n throw runtime_error(\"Request file not found\");\n }\n\n readReqFile();\n\n itsResults.reserve(itsRequests.size());\n\n \/\/ Fill the pool prior to starting\n BOOST_FOREACH (const auto& req, itsRequests)\n {\n itsThreadPool->schedule(boost::bind(&Tester::performRequest, this, req));\n }\n\n itsSignals.add(SIGQUIT);\n\n itsSignals.async_wait(boost::bind(&Tester::handleSignal, this, _1, _2));\n\n itsTimer.reset(new boost::asio::deadline_timer(itsIO));\n\n itsThread.reset(\n new boost::thread(boost::bind(&boost::asio::io_service::run, boost::ref(itsIO))));\n }\n\n ~Tester()\n {\n if (itsThreadPool != NULL)\n {\n delete itsThreadPool;\n itsThreadPool = NULL;\n }\n }\n\n void run()\n {\n itsTimer->expires_from_now(bp::seconds(5));\n\n itsTimer->async_wait(boost::bind(&Tester::printProgress, this, _1));\n\n itsThreadPool->start();\n\n itsThreadPool->join();\n }\n\n void printResults()\n {\n boost::lock_guard<boost::mutex> lock(itsResultMutex);\n BOOST_FOREACH (const auto& res, itsResults)\n {\n cout << res << endl;\n }\n }\n\n bool getPrintResults() { return itsPrintResults; }\n void dumpRequests()\n {\n BOOST_FOREACH (const auto& req, itsRequests)\n {\n cout << req << endl;\n }\n }\n\n void probeRemote()\n {\n ip::tcp::resolver resolver(itsIO);\n\n ip::tcp::resolver::query query(itsHostName, to_string((long long unsigned int)itsPort));\n auto end_iterator = resolver.resolve(query);\n\n ip::tcp::socket socket(itsIO);\n boost::asio::connect(socket, end_iterator);\n\n string reqString = \"GET \/ HTTP\/1.0\\r\\n\\r\\n\";\n\n \/\/ Send request\n boost::asio::write(socket, boost::asio::buffer(reqString));\n\n \/\/ Read at least something\n boost::array<char, 512> retArray;\n std::size_t size = 0;\n string tmp;\n string response;\n size =\n boost::asio::read(socket, boost::asio::buffer(retArray), boost::asio::transfer_at_least(8));\n\n \/\/ If no exceptions are thrown, the remote is succesfully contacted\n }\n\n private:\n const string itsHostName;\n\n unsigned int itsPort;\n\n fs::path itsRequestFilePath;\n\n pool* itsThreadPool;\n\n boost::asio::io_service itsIO;\n\n boost::asio::signal_set itsSignals;\n\n long itsCurrentResultInd;\n\n boost::scoped_ptr<boost::thread> itsThread;\n\n boost::scoped_ptr<boost::asio::deadline_timer> itsTimer;\n\n vector<Request> itsRequests;\n\n vector<Result> itsResults;\n\n boost::mutex itsResultMutex;\n\n bool itsPrintResults;\n\n void readReqFile()\n {\n ifstream inFile(itsRequestFilePath.string());\n\n string line;\n\n if (inFile.is_open())\n {\n while (getline(inFile, line))\n {\n boost::algorithm::replace_all(line, \" \", \"+\"); \/\/(At least spaces must be encoded\n itsRequests.emplace_back(itsHostName, itsPort, line);\n }\n\n \/\/ Shuffle the requests\n random_shuffle(itsRequests.begin(), itsRequests.end());\n }\n\n inFile.close();\n }\n\n void handleSignal(const boost::system::error_code& err, int signal_number)\n {\n itsIO.stop();\n itsThreadPool->shutdown();\n if (signal_number == 3) \/\/ SigQuit should print results\n {\n itsPrintResults = true;\n }\n }\n\n void printProgress(const boost::system::error_code& err)\n {\n if (err != boost::asio::error::operation_aborted)\n {\n std::vector<Result> theseResults;\n {\n boost::lock_guard<boost::mutex> lock(itsResultMutex);\n theseResults.assign(itsResults.begin() + itsCurrentResultInd, itsResults.end());\n itsCurrentResultInd = itsResults.size();\n }\n\n if (!theseResults.empty())\n {\n std::size_t reqs = theseResults.size();\n\n long average_duration = 0;\n\n BOOST_FOREACH (const auto& res, theseResults)\n {\n average_duration += res.duration.total_milliseconds();\n }\n\n average_duration \/= reqs;\n\n std::cerr << bp::second_clock::local_time() << \" Completed \" << reqs\n << \" requests with average response time of \" << average_duration << \" ms.\"\n << std::endl;\n }\n else\n {\n std::cerr << bp::second_clock::local_time() << \" No completed requests in this time slice\"\n << std::endl;\n }\n\n itsTimer->expires_from_now(bp::seconds(5));\n itsTimer->async_wait(boost::bind(&Tester::printProgress, this, _1));\n }\n }\n\n void performRequest(Request theReq)\n {\n ip::tcp::resolver resolver(itsIO);\n ip::tcp::resolver::query query(theReq.hostName, to_string((long long unsigned int)theReq.port));\n auto end_iterator = resolver.resolve(query);\n\n ip::tcp::socket socket(itsIO);\n boost::asio::connect(socket, end_iterator);\n\n string reqString = \"GET \" + theReq.URI + \" HTTP\/1.0\\r\\n\\r\\n\";\n\n \/\/ Send request\n auto before = bp::microsec_clock::universal_time();\n boost::system::error_code err;\n boost::asio::write(socket, boost::asio::buffer(reqString), err);\n\n \/\/ Read at least something\n boost::array<char, 512> retArray;\n std::size_t size = 0;\n string errorCode;\n string response;\n if (!err)\n {\n size = boost::asio::read(\n socket, boost::asio::buffer(retArray), boost::asio::transfer_at_least(8), err);\n auto parsedResult =\n parseStatus(boost::make_iterator_range(retArray.begin(), retArray.begin() + size));\n errorCode = parsedResult.first;\n response = parsedResult.second;\n }\n else\n {\n \/\/ Don't include erroneus connects\n return;\n }\n\n auto after = bp::microsec_clock::universal_time();\n \/\/ This request is done\n\n boost::lock_guard<boost::mutex> lock(itsResultMutex);\n itsResults.emplace_back(before, theReq.URI, after - before, errorCode, response);\n }\n};\n\nvoid testRequest(Request theReq)\n{\n boost::asio::io_service itsIO;\n ip::tcp::resolver resolver(itsIO);\n ip::tcp::resolver::query query(theReq.hostName, to_string((long long unsigned int)theReq.port));\n auto end_iterator = resolver.resolve(query);\n\n ip::tcp::socket socket(itsIO);\n boost::asio::connect(socket, end_iterator);\n\n string reqString = \"GET \" + theReq.URI + \" HTTP\/1.0\\r\\n\\r\\n\";\n\n boost::asio::write(socket, boost::asio::buffer(reqString));\n\n boost::array<char, 512> retArray;\n\n \/\/ Read until retArray is full\n auto size =\n boost::asio::read(socket, boost::asio::buffer(retArray), boost::asio::transfer_at_least(8));\n \/\/ This request is done\n\n std::cout << string(retArray.begin(), retArray.begin() + size) << std::endl;\n}\n\nint main(int argc, const char* argv[])\n{\n unsigned int threads;\n string host;\n unsigned short port;\n string suite_file;\n\n po::options_description desc(\"Allowed Options\");\n\n desc.add_options()(\"help,h\", \"Print this help\")(\n \"host,H\", po::value<string>(&host)->default_value(\"brainstormgw.fmi.fi\"), \"Host\")(\n \"port,p\", po::value<unsigned short>(&port)->default_value(80), \"Port\")(\n \"suite,s\", po::value<string>(&suite_file), \"File from which to read the suite\")(\n \"threads,t\", po::value<unsigned int>(&threads)->default_value(5), \"Number of worker threads\");\n\n po::variables_map vmap;\n\n po::store(po::command_line_parser(argc, argv).options(desc).run(), vmap);\n\n po::notify(vmap);\n\n if (vmap.count(\"help\"))\n {\n std::cout << \"Usage: \"\n << \"tester [options]\" << std::endl;\n std::cout << desc << std::endl;\n return 1;\n }\n\n if (vmap.count(\"suite\") == 0)\n {\n std::cout << \"Please provide the test suite file\" << std::endl;\n std::cout << \"Usage: \"\n << \"tester [options]\" << std::endl;\n std::cout << desc << std::endl;\n\n return 1;\n }\n\n Tester theTester(vmap[\"suite\"].as<string>(),\n vmap[\"threads\"].as<unsigned int>(),\n vmap[\"host\"].as<string>(),\n vmap[\"port\"].as<unsigned short>());\n\n std::cerr << \"Probing the remote...\" << std::endl;\n\n theTester.probeRemote();\n\n std::cerr << \"Succesfully probed, running test...\" << std::endl;\n\n theTester.run();\n\n if (theTester.getPrintResults())\n {\n theTester.printResults();\n }\n}\n<commit_msg>Replaced boost::scoped_ptr with std::unique_ptr<commit_after>#include <iostream>\n#include <stdexcept>\n#include <string>\n#include <vector>\n#include <fstream>\n\n#include <spine\/HTTP.h>\n\n#include <boost\/program_options.hpp>\n#include <boost\/filesystem.hpp>\n#include <boost\/asio.hpp>\n#include <boost\/foreach.hpp>\n#include <boost\/array.hpp>\n#include <boost\/bind.hpp>\n#include <boost\/date_time\/posix_time\/posix_time.hpp>\n#include <boost\/algorithm\/string.hpp>\n\n#include <macgyver\/ThreadPool.h>\n\ntypedef Fmi::ThreadPool::ThreadPool<> pool;\n\nusing namespace std;\n\nnamespace fs = boost::filesystem;\n\nnamespace ip = boost::asio::ip;\n\nnamespace bp = boost::posix_time;\n\nnamespace po = boost::program_options;\n\npair<string, string> parseStatus(const boost::iterator_range<char*>& message)\n{\n std::vector<boost::iterator_range<std::string::const_iterator> > headerTokens;\n vector<string> statusLineTokens(3);\n\n auto header_boundary = boost::algorithm::find_first(message, \"\\r\\n\\r\\n\");\n\n auto header_range = boost::make_iterator_range(message.begin(), header_boundary.begin());\n boost::algorithm::split(\n headerTokens, header_range, boost::is_any_of(\"\\r\\n\"), boost::token_compress_on);\n\n if (headerTokens.empty())\n {\n return pair<string, string>();\n }\n\n auto startIt = headerTokens.begin();\n boost::algorithm::split(statusLineTokens, *startIt, boost::is_space(), boost::token_compress_on);\n\n string messageBody = string(header_boundary.end(), message.end());\n\n boost::algorithm::replace_all(messageBody, \"\\n\", \" \");\n boost::algorithm::replace_all(messageBody, \"\\r\", \" \");\n\n string code;\n try\n {\n code = statusLineTokens.at(1);\n }\n catch (...)\n {\n return pair<string, string>();\n }\n\n return make_pair(code, messageBody);\n}\n\nstruct Request\n{\n Request(string host, unsigned short port, string URI) : hostName(host), port(port), URI(URI) {}\n friend ostream& operator<<(ostream& stream, const Request& theReq)\n {\n stream << theReq.hostName << \":\" << theReq.port << theReq.URI;\n return stream;\n }\n\n string hostName;\n\n unsigned short port;\n\n string URI;\n};\n\nstruct Result\n{\n Result(bp::ptime resTime, string URI, bp::time_duration duration, string status, string response)\n : resTime(resTime), URI(URI), duration(duration), status(status), response(response)\n {\n }\n\n friend ostream& operator<<(ostream& stream, const Result& theRes)\n {\n stream << theRes.resTime << \"###\" << theRes.URI << \"###\"\n << bp::to_simple_string(theRes.duration) << \"###\" << theRes.status << \"###\"\n << theRes.response;\n return stream;\n }\n\n bp::ptime resTime;\n\n string URI;\n\n bp::time_duration duration;\n\n string status;\n\n string response;\n};\n\nclass Tester\n{\n public:\n Tester(const string& requestFile,\n unsigned int threads,\n const string& hostname,\n unsigned short port)\n : itsHostName(hostname),\n itsPort(port),\n itsRequestFilePath(requestFile),\n itsThreadPool(new pool(threads)),\n itsSignals(itsIO),\n itsCurrentResultInd(0),\n itsPrintResults(false)\n {\n if (!fs::exists(itsRequestFilePath))\n {\n throw runtime_error(\"Request file not found\");\n }\n\n readReqFile();\n\n itsResults.reserve(itsRequests.size());\n\n \/\/ Fill the pool prior to starting\n BOOST_FOREACH (const auto& req, itsRequests)\n {\n itsThreadPool->schedule(boost::bind(&Tester::performRequest, this, req));\n }\n\n itsSignals.add(SIGQUIT);\n\n itsSignals.async_wait(boost::bind(&Tester::handleSignal, this, _1, _2));\n\n itsTimer.reset(new boost::asio::deadline_timer(itsIO));\n\n itsThread.reset(\n new boost::thread(boost::bind(&boost::asio::io_service::run, boost::ref(itsIO))));\n }\n\n ~Tester()\n {\n if (itsThreadPool != NULL)\n {\n delete itsThreadPool;\n itsThreadPool = NULL;\n }\n }\n\n void run()\n {\n itsTimer->expires_from_now(bp::seconds(5));\n\n itsTimer->async_wait(boost::bind(&Tester::printProgress, this, _1));\n\n itsThreadPool->start();\n\n itsThreadPool->join();\n }\n\n void printResults()\n {\n boost::lock_guard<boost::mutex> lock(itsResultMutex);\n BOOST_FOREACH (const auto& res, itsResults)\n {\n cout << res << endl;\n }\n }\n\n bool getPrintResults() { return itsPrintResults; }\n void dumpRequests()\n {\n BOOST_FOREACH (const auto& req, itsRequests)\n {\n cout << req << endl;\n }\n }\n\n void probeRemote()\n {\n ip::tcp::resolver resolver(itsIO);\n\n ip::tcp::resolver::query query(itsHostName, to_string((long long unsigned int)itsPort));\n auto end_iterator = resolver.resolve(query);\n\n ip::tcp::socket socket(itsIO);\n boost::asio::connect(socket, end_iterator);\n\n string reqString = \"GET \/ HTTP\/1.0\\r\\n\\r\\n\";\n\n \/\/ Send request\n boost::asio::write(socket, boost::asio::buffer(reqString));\n\n \/\/ Read at least something\n boost::array<char, 512> retArray;\n std::size_t size = 0;\n string tmp;\n string response;\n size =\n boost::asio::read(socket, boost::asio::buffer(retArray), boost::asio::transfer_at_least(8));\n\n \/\/ If no exceptions are thrown, the remote is succesfully contacted\n }\n\n private:\n const string itsHostName;\n\n unsigned int itsPort;\n\n fs::path itsRequestFilePath;\n\n pool* itsThreadPool;\n\n boost::asio::io_service itsIO;\n\n boost::asio::signal_set itsSignals;\n\n long itsCurrentResultInd;\n\n std::unique_ptr<boost::thread> itsThread;\n\n std::unique_ptr<boost::asio::deadline_timer> itsTimer;\n\n vector<Request> itsRequests;\n\n vector<Result> itsResults;\n\n boost::mutex itsResultMutex;\n\n bool itsPrintResults;\n\n void readReqFile()\n {\n ifstream inFile(itsRequestFilePath.string());\n\n string line;\n\n if (inFile.is_open())\n {\n while (getline(inFile, line))\n {\n boost::algorithm::replace_all(line, \" \", \"+\"); \/\/(At least spaces must be encoded\n itsRequests.emplace_back(itsHostName, itsPort, line);\n }\n\n \/\/ Shuffle the requests\n random_shuffle(itsRequests.begin(), itsRequests.end());\n }\n\n inFile.close();\n }\n\n void handleSignal(const boost::system::error_code& err, int signal_number)\n {\n itsIO.stop();\n itsThreadPool->shutdown();\n if (signal_number == 3) \/\/ SigQuit should print results\n {\n itsPrintResults = true;\n }\n }\n\n void printProgress(const boost::system::error_code& err)\n {\n if (err != boost::asio::error::operation_aborted)\n {\n std::vector<Result> theseResults;\n {\n boost::lock_guard<boost::mutex> lock(itsResultMutex);\n theseResults.assign(itsResults.begin() + itsCurrentResultInd, itsResults.end());\n itsCurrentResultInd = itsResults.size();\n }\n\n if (!theseResults.empty())\n {\n std::size_t reqs = theseResults.size();\n\n long average_duration = 0;\n\n BOOST_FOREACH (const auto& res, theseResults)\n {\n average_duration += res.duration.total_milliseconds();\n }\n\n average_duration \/= reqs;\n\n std::cerr << bp::second_clock::local_time() << \" Completed \" << reqs\n << \" requests with average response time of \" << average_duration << \" ms.\"\n << std::endl;\n }\n else\n {\n std::cerr << bp::second_clock::local_time() << \" No completed requests in this time slice\"\n << std::endl;\n }\n\n itsTimer->expires_from_now(bp::seconds(5));\n itsTimer->async_wait(boost::bind(&Tester::printProgress, this, _1));\n }\n }\n\n void performRequest(Request theReq)\n {\n ip::tcp::resolver resolver(itsIO);\n ip::tcp::resolver::query query(theReq.hostName, to_string((long long unsigned int)theReq.port));\n auto end_iterator = resolver.resolve(query);\n\n ip::tcp::socket socket(itsIO);\n boost::asio::connect(socket, end_iterator);\n\n string reqString = \"GET \" + theReq.URI + \" HTTP\/1.0\\r\\n\\r\\n\";\n\n \/\/ Send request\n auto before = bp::microsec_clock::universal_time();\n boost::system::error_code err;\n boost::asio::write(socket, boost::asio::buffer(reqString), err);\n\n \/\/ Read at least something\n boost::array<char, 512> retArray;\n std::size_t size = 0;\n string errorCode;\n string response;\n if (!err)\n {\n size = boost::asio::read(\n socket, boost::asio::buffer(retArray), boost::asio::transfer_at_least(8), err);\n auto parsedResult =\n parseStatus(boost::make_iterator_range(retArray.begin(), retArray.begin() + size));\n errorCode = parsedResult.first;\n response = parsedResult.second;\n }\n else\n {\n \/\/ Don't include erroneus connects\n return;\n }\n\n auto after = bp::microsec_clock::universal_time();\n \/\/ This request is done\n\n boost::lock_guard<boost::mutex> lock(itsResultMutex);\n itsResults.emplace_back(before, theReq.URI, after - before, errorCode, response);\n }\n};\n\nvoid testRequest(Request theReq)\n{\n boost::asio::io_service itsIO;\n ip::tcp::resolver resolver(itsIO);\n ip::tcp::resolver::query query(theReq.hostName, to_string((long long unsigned int)theReq.port));\n auto end_iterator = resolver.resolve(query);\n\n ip::tcp::socket socket(itsIO);\n boost::asio::connect(socket, end_iterator);\n\n string reqString = \"GET \" + theReq.URI + \" HTTP\/1.0\\r\\n\\r\\n\";\n\n boost::asio::write(socket, boost::asio::buffer(reqString));\n\n boost::array<char, 512> retArray;\n\n \/\/ Read until retArray is full\n auto size =\n boost::asio::read(socket, boost::asio::buffer(retArray), boost::asio::transfer_at_least(8));\n \/\/ This request is done\n\n std::cout << string(retArray.begin(), retArray.begin() + size) << std::endl;\n}\n\nint main(int argc, const char* argv[])\n{\n unsigned int threads;\n string host;\n unsigned short port;\n string suite_file;\n\n po::options_description desc(\"Allowed Options\");\n\n desc.add_options()(\"help,h\", \"Print this help\")(\n \"host,H\", po::value<string>(&host)->default_value(\"brainstormgw.fmi.fi\"), \"Host\")(\n \"port,p\", po::value<unsigned short>(&port)->default_value(80), \"Port\")(\n \"suite,s\", po::value<string>(&suite_file), \"File from which to read the suite\")(\n \"threads,t\", po::value<unsigned int>(&threads)->default_value(5), \"Number of worker threads\");\n\n po::variables_map vmap;\n\n po::store(po::command_line_parser(argc, argv).options(desc).run(), vmap);\n\n po::notify(vmap);\n\n if (vmap.count(\"help\"))\n {\n std::cout << \"Usage: \"\n << \"tester [options]\" << std::endl;\n std::cout << desc << std::endl;\n return 1;\n }\n\n if (vmap.count(\"suite\") == 0)\n {\n std::cout << \"Please provide the test suite file\" << std::endl;\n std::cout << \"Usage: \"\n << \"tester [options]\" << std::endl;\n std::cout << desc << std::endl;\n\n return 1;\n }\n\n Tester theTester(vmap[\"suite\"].as<string>(),\n vmap[\"threads\"].as<unsigned int>(),\n vmap[\"host\"].as<string>(),\n vmap[\"port\"].as<unsigned short>());\n\n std::cerr << \"Probing the remote...\" << std::endl;\n\n theTester.probeRemote();\n\n std::cerr << \"Succesfully probed, running test...\" << std::endl;\n\n theTester.run();\n\n if (theTester.getPrintResults())\n {\n theTester.printResults();\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: CenterViewFocusModule.cxx,v $\n *\n * $Revision: 1.2 $\n *\n * last change: $Author: rt $ $Date: 2007-04-03 15:50:35 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#include \"precompiled_sd.hxx\"\n\n#include \"CenterViewFocusModule.hxx\"\n\n#include \"framework\/ConfigurationController.hxx\"\n#include \"framework\/FrameworkHelper.hxx\"\n#include \"framework\/ViewShellWrapper.hxx\"\n\n#include \"DrawController.hxx\"\n#include \"ViewShellBase.hxx\"\n#include \"ViewShellManager.hxx\"\n#include \"strings.hrc\"\n#include \"sdresid.hxx\"\n\n#ifndef _COM_SUN_STAR_DRAWING_FRAMEWORK_XCONTROLLERMANAGER_HPP_\n#include <com\/sun\/star\/drawing\/framework\/XControllerManager.hpp>\n#endif\n#ifndef _COM_SUN_STAR_DRAWING_FRAMEWORK_XCONFIGURATIONCONTROLLER_HPP_\n#include <com\/sun\/star\/drawing\/framework\/XConfigurationController.hpp>\n#endif\n\n#include <toolkit\/awt\/vclxdevice.hxx>\n#include <sfx2\/viewfrm.hxx>\n\nusing namespace ::com::sun::star;\nusing namespace ::com::sun::star::uno;\nusing namespace ::com::sun::star::drawing::framework;\n\nusing ::rtl::OUString;\nusing ::sd::framework::FrameworkHelper;\n\n\nnamespace sd { namespace framework {\n\n\/\/===== CenterViewFocusModule ====================================================\n\nCenterViewFocusModule::CenterViewFocusModule (Reference<frame::XController>& rxController)\n : CenterViewFocusModuleInterfaceBase(MutexOwner::maMutex),\n mbValid(false),\n mxViewController(),\n mxConfigurationController(),\n mpBase(NULL),\n mbNewViewCreated(false)\n{\n Reference<XControllerManager> xControllerManager (rxController, UNO_QUERY);\n if (xControllerManager.is())\n {\n mxViewController = xControllerManager->getViewController();\n mxConfigurationController = xControllerManager->getConfigurationController();\n\n \/\/ Tunnel through the controller to obtain a ViewShellBase.\n Reference<lang::XUnoTunnel> xTunnel (rxController, UNO_QUERY);\n if (xTunnel.is())\n {\n ::sd::DrawController* pController = reinterpret_cast<sd::DrawController*>(\n xTunnel->getSomething(sd::DrawController::getUnoTunnelId()));\n if (pController != NULL)\n mpBase = pController->GetViewShellBase();\n }\n\n \/\/ Check, if all required objects do exist.\n if (mxViewController.is()\n && mxConfigurationController.is()\n && mpBase!=NULL)\n {\n mbValid = true;\n }\n }\n\n if (mbValid)\n {\n mxConfigurationController->addConfigurationChangeListener(\n this,\n FrameworkHelper::msConfigurationUpdateEndEvent,\n Any());\n mxConfigurationController->addConfigurationChangeListener(\n this,\n FrameworkHelper::msResourceActivationEvent,\n Any());\n }\n}\n\n\n\n\nCenterViewFocusModule::~CenterViewFocusModule (void)\n{\n}\n\n\n\n\nvoid SAL_CALL CenterViewFocusModule::disposing (void)\n{\n if (mxConfigurationController.is())\n mxConfigurationController->removeConfigurationChangeListener(this);\n\n mbValid = false;\n mxViewController = NULL;\n mxConfigurationController = NULL;\n mpBase = NULL;\n}\n\n\n\n\nvoid SAL_CALL CenterViewFocusModule::notifyConfigurationChange (\n const ConfigurationChangeEvent& rEvent)\n throw (RuntimeException)\n{\n if (mbValid)\n {\n if (rEvent.Type.equals(FrameworkHelper::msConfigurationUpdateEndEvent))\n {\n ConfigurationUpdateEnd();\n }\n else if (rEvent.Type.equals(FrameworkHelper::msResourceActivationEvent))\n {\n if (rEvent.ResourceId->getResourceURL().match(FrameworkHelper::msViewURLPrefix))\n mbNewViewCreated = true;\n }\n }\n}\n\n\n\n\nvoid CenterViewFocusModule::ConfigurationUpdateEnd (void)\n{\n if (mbNewViewCreated)\n {\n mbNewViewCreated = false;\n \/\/ Make the center pane the active one. Tunnel through the\n \/\/ controller to obtain a ViewShell pointer.\n Reference<XView> xView (mxViewController->getFirstViewForAnchor(\n FrameworkHelper::CreateResourceId(FrameworkHelper::msCenterPaneURL)));\n Reference<lang::XUnoTunnel> xTunnel (xView, UNO_QUERY);\n if (xTunnel.is() && mpBase!=NULL)\n {\n ViewShellWrapper* pViewShellWrapper = reinterpret_cast<ViewShellWrapper*>(\n xTunnel->getSomething(ViewShellWrapper::getUnoTunnelId()));\n if (pViewShellWrapper != NULL)\n {\n ::boost::shared_ptr<ViewShell> pViewShell = pViewShellWrapper->GetViewShell();\n if (pViewShell.get() != NULL)\n mpBase->GetViewShellManager().MoveToTop(*pViewShell);\n }\n }\n }\n}\n\n\n\n\nvoid SAL_CALL CenterViewFocusModule::disposing (\n const lang::EventObject& rEvent)\n throw (RuntimeException)\n{\n if (mxConfigurationController.is())\n if (rEvent.Source == mxConfigurationController)\n {\n mbValid = false;\n mxConfigurationController = NULL;\n mxViewController = NULL;\n mpBase = NULL;\n }\n}\n\n\n\n} } \/\/ end of namespace sd::framework\n<commit_msg>INTEGRATION: CWS presenterview (1.2.22); FILE MERGED 2007\/07\/10 14:24:33 af 1.2.22.2: #i18486# Converted several members of ViewShellBase to shared_ptrs. 2007\/06\/19 08:01:42 af 1.2.22.1: #i18486# Adaption to recent framework API changes.<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: CenterViewFocusModule.cxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: kz $ $Date: 2008-04-03 13:37:17 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#include \"precompiled_sd.hxx\"\n\n#include \"CenterViewFocusModule.hxx\"\n\n#include \"framework\/ConfigurationController.hxx\"\n#include \"framework\/FrameworkHelper.hxx\"\n#include \"framework\/ViewShellWrapper.hxx\"\n\n#include \"DrawController.hxx\"\n#include \"ViewShellBase.hxx\"\n#include \"ViewShellManager.hxx\"\n#include \"strings.hrc\"\n#include \"sdresid.hxx\"\n\n#ifndef _COM_SUN_STAR_DRAWING_FRAMEWORK_XCONTROLLERMANAGER_HPP_\n#include <com\/sun\/star\/drawing\/framework\/XControllerManager.hpp>\n#endif\n#ifndef _COM_SUN_STAR_DRAWING_FRAMEWORK_XCONFIGURATIONCONTROLLER_HPP_\n#include <com\/sun\/star\/drawing\/framework\/XConfigurationController.hpp>\n#endif\n\n#include <toolkit\/awt\/vclxdevice.hxx>\n#include <sfx2\/viewfrm.hxx>\n\nusing namespace ::com::sun::star;\nusing namespace ::com::sun::star::uno;\nusing namespace ::com::sun::star::drawing::framework;\n\nusing ::rtl::OUString;\nusing ::sd::framework::FrameworkHelper;\n\n\nnamespace sd { namespace framework {\n\n\/\/===== CenterViewFocusModule ====================================================\n\nCenterViewFocusModule::CenterViewFocusModule (Reference<frame::XController>& rxController)\n : CenterViewFocusModuleInterfaceBase(MutexOwner::maMutex),\n mbValid(false),\n mxConfigurationController(),\n mpBase(NULL),\n mbNewViewCreated(false)\n{\n Reference<XControllerManager> xControllerManager (rxController, UNO_QUERY);\n if (xControllerManager.is())\n {\n mxConfigurationController = xControllerManager->getConfigurationController();\n\n \/\/ Tunnel through the controller to obtain a ViewShellBase.\n Reference<lang::XUnoTunnel> xTunnel (rxController, UNO_QUERY);\n if (xTunnel.is())\n {\n ::sd::DrawController* pController = reinterpret_cast<sd::DrawController*>(\n xTunnel->getSomething(sd::DrawController::getUnoTunnelId()));\n if (pController != NULL)\n mpBase = pController->GetViewShellBase();\n }\n\n \/\/ Check, if all required objects do exist.\n if (mxConfigurationController.is() && mpBase!=NULL)\n {\n mbValid = true;\n }\n }\n\n if (mbValid)\n {\n mxConfigurationController->addConfigurationChangeListener(\n this,\n FrameworkHelper::msConfigurationUpdateEndEvent,\n Any());\n mxConfigurationController->addConfigurationChangeListener(\n this,\n FrameworkHelper::msResourceActivationEvent,\n Any());\n }\n}\n\n\n\n\nCenterViewFocusModule::~CenterViewFocusModule (void)\n{\n}\n\n\n\n\nvoid SAL_CALL CenterViewFocusModule::disposing (void)\n{\n if (mxConfigurationController.is())\n mxConfigurationController->removeConfigurationChangeListener(this);\n\n mbValid = false;\n mxConfigurationController = NULL;\n mpBase = NULL;\n}\n\n\n\n\nvoid SAL_CALL CenterViewFocusModule::notifyConfigurationChange (\n const ConfigurationChangeEvent& rEvent)\n throw (RuntimeException)\n{\n if (mbValid)\n {\n if (rEvent.Type.equals(FrameworkHelper::msConfigurationUpdateEndEvent))\n {\n HandleNewView(rEvent.Configuration);\n }\n else if (rEvent.Type.equals(FrameworkHelper::msResourceActivationEvent))\n {\n if (rEvent.ResourceId->getResourceURL().match(FrameworkHelper::msViewURLPrefix))\n mbNewViewCreated = true;\n }\n }\n}\n\n\n\n\nvoid CenterViewFocusModule::HandleNewView (\n const Reference<XConfiguration>& rxConfiguration)\n{\n if (mbNewViewCreated)\n {\n mbNewViewCreated = false;\n \/\/ Make the center pane the active one. Tunnel through the\n \/\/ controller to obtain a ViewShell pointer.\n\n Sequence<Reference<XResourceId> > xViewIds (rxConfiguration->getResources(\n FrameworkHelper::CreateResourceId(FrameworkHelper::msCenterPaneURL),\n FrameworkHelper::msViewURLPrefix,\n AnchorBindingMode_DIRECT));\n Reference<XView> xView;\n if (xViewIds.getLength() > 0)\n xView = Reference<XView>(\n mxConfigurationController->getResource(xViewIds[0]),UNO_QUERY);\n Reference<lang::XUnoTunnel> xTunnel (xView, UNO_QUERY);\n if (xTunnel.is() && mpBase!=NULL)\n {\n ViewShellWrapper* pViewShellWrapper = reinterpret_cast<ViewShellWrapper*>(\n xTunnel->getSomething(ViewShellWrapper::getUnoTunnelId()));\n if (pViewShellWrapper != NULL)\n {\n ::boost::shared_ptr<ViewShell> pViewShell = pViewShellWrapper->GetViewShell();\n if (pViewShell.get() != NULL)\n mpBase->GetViewShellManager()->MoveToTop(*pViewShell);\n }\n }\n }\n}\n\n\n\n\nvoid SAL_CALL CenterViewFocusModule::disposing (\n const lang::EventObject& rEvent)\n throw (RuntimeException)\n{\n if (mxConfigurationController.is())\n if (rEvent.Source == mxConfigurationController)\n {\n mbValid = false;\n mxConfigurationController = NULL;\n mpBase = NULL;\n }\n}\n\n\n\n} } \/\/ end of namespace sd::framework\n<|endoftext|>"} {"text":"<commit_before>\/******************************************************************************\n* SOFA, Simulation Open-Framework Architecture, development version *\n* (c) 2006-2017 INRIA, USTL, UJF, CNRS, MGH *\n* *\n* This program is free software; you can redistribute it and\/or modify it *\n* under the terms of the GNU Lesser General Public License as published by *\n* the Free Software Foundation; either version 2.1 of the License, or (at *\n* your option) any later version. *\n* *\n* This program is distributed in the hope that it will be useful, but WITHOUT *\n* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or *\n* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License *\n* for more details. *\n* *\n* You should have received a copy of the GNU Lesser General Public License *\n* along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>. *\n*******************************************************************************\n* Authors: The SOFA Team and external contributors (see Authors.txt) *\n* *\n* Contact information: contact@sofa-framework.org *\n******************************************************************************\/\n#include \"PythonMacros.h\"\n#include \"PythonEnvironment.h\"\n#include \"SceneLoaderPY.h\"\n\n\n#include <sofa\/simulation\/Simulation.h>\n#include <SofaSimulationCommon\/xml\/NodeElement.h>\n#include <SofaSimulationCommon\/FindByTypeVisitor.h>\n\n#include <sstream>\n\n#include \"PythonMainScriptController.h\"\n#include \"PythonEnvironment.h\"\n#include \"PythonFactory.h\"\n\nusing namespace sofa::core::objectmodel;\n\nnamespace sofa\n{\n\nnamespace simulation\n{\n\nstd::string SceneLoaderPY::OurHeader;\n\nvoid SceneLoaderPY::setHeader(const std::string& header)\n{\n OurHeader = header;\n}\n\nbool SceneLoaderPY::canLoadFileExtension(const char *extension)\n{\n std::string ext = extension;\n std::transform(ext.begin(), ext.end(), ext.begin(), ::tolower);\n return (ext==\"py\" || ext==\"pyscn\");\n}\n\nbool SceneLoaderPY::canWriteFileExtension(const char *extension)\n{\n return canLoadFileExtension(extension);\n}\n\n\/\/\/ get the file type description\nstd::string SceneLoaderPY::getFileTypeDesc()\n{\n return \"Python Scenes\";\n}\n\n\/\/\/ get the list of file extensions\nvoid SceneLoaderPY::getExtensionList(ExtensionList* list)\n{\n list->clear();\n list->push_back(\"pyscn\");\n list->push_back(\"py\");\n}\n\nsofa::simulation::Node::SPtr SceneLoaderPY::load(const char *filename)\n{\n return loadSceneWithArguments(filename);\n}\n\nsofa::simulation::Node::SPtr SceneLoaderPY::loadSceneWithArguments(const char *filename, const std::vector<std::string>& arguments)\n{\n if(!OurHeader.empty() && 0 != PyRun_SimpleString(OurHeader.c_str()))\n {\n SP_MESSAGE_ERROR( \"header script run error.\" )\n return NULL;\n }\n\n PythonEnvironment::runString(\"createScene=None\");\n PythonEnvironment::runString(\"createSceneAndController=None\");\n\n PythonEnvironment::runString(std::string(\"__file__=\\\"\") + filename + \"\\\"\");\n\n \/\/ We go the the current file's directory so that all relative path are correct\n helper::system::SetDirectory chdir ( filename );\n\n notifyLoadingScene();\n if(!PythonEnvironment::runFile(helper::system::SetDirectory::GetFileName(filename).c_str(), arguments))\n {\n \/\/ LOAD ERROR\n SP_MESSAGE_ERROR( \"scene script load error.\" )\n return NULL;\n }\n\n PyObject* pDict = PyModule_GetDict(PyImport_AddModule(\"__main__\"));\n\n \/\/ pFunc is also a borrowed reference\n PyObject *pFunc = PyDict_GetItemString(pDict, \"createScene\");\n if (PyCallable_Check(pFunc))\n {\n Node::SPtr rootNode = Node::create(\"root\");\n SP_CALL_MODULEFUNC(pFunc, \"(O)\", sofa::PythonFactory::toPython(rootNode.get()))\n\n return rootNode;\n }\n else\n {\n PyObject *pFunc = PyDict_GetItemString(pDict, \"createSceneAndController\");\n if (PyCallable_Check(pFunc))\n {\n Node::SPtr rootNode = Node::create(\"root\");\n SP_CALL_MODULEFUNC(pFunc, \"(O)\", sofa::PythonFactory::toPython(rootNode.get()))\n\n rootNode->addObject( core::objectmodel::New<component::controller::PythonMainScriptController>( filename ) );\n\n return rootNode;\n }\n }\n\n SP_MESSAGE_ERROR( \"cannot create Scene, no \\\"createScene(rootNode)\\\" nor \\\"createSceneAndController(rootNode)\\\" module method found.\" )\n return NULL;\n}\n\n\nbool SceneLoaderPY::loadTestWithArguments(const char *filename, const std::vector<std::string>& arguments)\n{\n if(!OurHeader.empty() && 0 != PyRun_SimpleString(OurHeader.c_str()))\n {\n SP_MESSAGE_ERROR( \"header script run error.\" )\n return false;\n }\n\n PythonEnvironment::runString(\"createScene=None\");\n PythonEnvironment::runString(\"createSceneAndController=None\");\n\n PythonEnvironment::runString(std::string(\"__file__=\\\"\") + filename + \"\\\"\");\n\n \/\/ it runs the unecessary SofaPython script but it is not a big deal\n if(!PythonEnvironment::runFile(filename,arguments))\n {\n \/\/ LOAD ERROR\n SP_MESSAGE_ERROR( \"script load error.\" )\n return false;\n }\n\n PyObject* pDict = PyModule_GetDict(PyImport_AddModule(\"__main__\"));\n\n \/\/ pFunc is also a borrowed reference\n PyObject *pFunc = PyDict_GetItemString(pDict, \"run\");\n if (PyCallable_Check(pFunc))\n {\n PyObject *res = PyObject_CallObject(pFunc,0);\n printPythonExceptions();\n\n if( !res )\n {\n SP_MESSAGE_ERROR( \"Python test 'run' function does not return any value\" )\n return false;\n }\n else if( !PyBool_Check(res) )\n {\n SP_MESSAGE_ERROR( \"Python test 'run' function does not return a boolean\" )\n Py_DECREF(res);\n return false;\n }\n\n bool result = ( res == Py_True );\n Py_DECREF(res);\n\n return result;\n }\n else\n {\n SP_MESSAGE_ERROR( \"Python test has no 'run'' function\" )\n return false;\n }\n}\n\n\n\nvoid SceneLoaderPY::write(Node* node, const char *filename)\n{\n exportPython( node, filename );\n}\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\n\nstatic const std::string s_tab = \" \";\n\n\ninline void printBaseHeader( std::ostream& out, Node* node )\n{\n out << \"import Sofa\\n\\n\\n\";\n out << \"def createScene(root):\\n\";\n\n out << s_tab << \"root.dt = \" << node->getDt() << std::endl;\n const Context::Vec3& g = node->getGravity();\n out << s_tab << \"root.gravity = [\" << g[0] << \",\" << g[1] << \",\" << g[2] << \"]\" << std::endl;\n}\n\n\nvoid exportPython( Node* node, const char* fileName )\n{\n if ( !node ) return;\n\n if ( fileName!=NULL )\n {\n std::ofstream out( fileName );\n\n printBaseHeader( out, node );\n\n PythonExporterVisitor print( out );\n node->execute( print );\n }\n else\n {\n printBaseHeader( std::cout, node );\n\n PythonExporterVisitor print( std::cout );\n node->execute( print );\n }\n}\n\n\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\n\n\ntemplate<class T>\nvoid PythonExporterVisitor::processObject( T obj, const std::string& nodeVariable )\n{\n std::string classname = obj->getClassName();\n std::string templatename = obj->getTemplateName();\n\n m_out << s_tab << nodeVariable << \".createObject( '\" << classname <<\"', template='\" << templatename << \"'\";\n\n obj->writeDatas( m_out, \", \" );\n\n m_out << \")\" << std::endl;\n}\n\n\nVisitor::Result PythonExporterVisitor::processNodeTopDown(Node* node)\n{\n m_out << \"\\n\\n\";\n\n m_variableIndex++;\n\n sofa::helper::vector< core::objectmodel::BaseNode* > parents = node->getParents();\n\n\n std::string nodeName = node->getName();\n std::stringstream nodeVariable;\n\n\n if( !parents.empty() ) \/\/ not root\n {\n nodeVariable << nodeName << \"_Node\" << m_variableIndex;\n m_mapNodeVariable[node] = nodeVariable.str();\n\n const std::string& parentVariable = m_mapNodeVariable[parents[0]];\n\n m_out << s_tab << nodeVariable.str() << \" = \"<<parentVariable<<\".createChild( '\"<<nodeName <<\"' )\" << std::endl;\n }\n else\n {\n nodeVariable << \"root\";\n m_mapNodeVariable[node] = nodeVariable.str();\n }\n\n\n for (Node::ObjectIterator it = node->object.begin(); it != node->object.end(); ++it)\n {\n sofa::core::objectmodel::BaseObject* obj = it->get();\n this->processObject( obj, nodeVariable.str() );\n }\n\n return RESULT_CONTINUE;\n}\n\nvoid PythonExporterVisitor::processNodeBottomUp(Node* node)\n{\n sofa::helper::vector< core::objectmodel::BaseNode* > parents = node->getParents();\n\n const std::string& nodeVariable = m_mapNodeVariable[node];\n\n\n \/\/ add all its parents to a multinode\n for( size_t i = 1 ; i<parents.size() ; ++ i)\n {\n const std::string& parentVariable = m_mapNodeVariable[parents[i]];\n\n m_out << s_tab << parentVariable << \".addChild(\" << nodeVariable << \")\\n\";\n }\n}\n\n\n} \/\/ namespace simulation\n\n} \/\/ namespace sofa\n\n<commit_msg>[SofaPython] gil sofapyloader too<commit_after>\/******************************************************************************\n* SOFA, Simulation Open-Framework Architecture, development version *\n* (c) 2006-2017 INRIA, USTL, UJF, CNRS, MGH *\n* *\n* This program is free software; you can redistribute it and\/or modify it *\n* under the terms of the GNU Lesser General Public License as published by *\n* the Free Software Foundation; either version 2.1 of the License, or (at *\n* your option) any later version. *\n* *\n* This program is distributed in the hope that it will be useful, but WITHOUT *\n* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or *\n* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License *\n* for more details. *\n* *\n* You should have received a copy of the GNU Lesser General Public License *\n* along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>. *\n*******************************************************************************\n* Authors: The SOFA Team and external contributors (see Authors.txt) *\n* *\n* Contact information: contact@sofa-framework.org *\n******************************************************************************\/\n#include \"PythonMacros.h\"\n#include \"PythonEnvironment.h\"\n#include \"SceneLoaderPY.h\"\n\n\n#include <sofa\/simulation\/Simulation.h>\n#include <SofaSimulationCommon\/xml\/NodeElement.h>\n#include <SofaSimulationCommon\/FindByTypeVisitor.h>\n\n#include <sstream>\n\n#include \"PythonMainScriptController.h\"\n#include \"PythonEnvironment.h\"\n#include \"PythonFactory.h\"\n\nusing namespace sofa::core::objectmodel;\n\nnamespace sofa\n{\n\nnamespace simulation\n{\n\nstd::string SceneLoaderPY::OurHeader;\n\nvoid SceneLoaderPY::setHeader(const std::string& header)\n{\n OurHeader = header;\n}\n\nbool SceneLoaderPY::canLoadFileExtension(const char *extension)\n{\n std::string ext = extension;\n std::transform(ext.begin(), ext.end(), ext.begin(), ::tolower);\n return (ext==\"py\" || ext==\"pyscn\");\n}\n\nbool SceneLoaderPY::canWriteFileExtension(const char *extension)\n{\n return canLoadFileExtension(extension);\n}\n\n\/\/\/ get the file type description\nstd::string SceneLoaderPY::getFileTypeDesc()\n{\n return \"Python Scenes\";\n}\n\n\/\/\/ get the list of file extensions\nvoid SceneLoaderPY::getExtensionList(ExtensionList* list)\n{\n list->clear();\n list->push_back(\"pyscn\");\n list->push_back(\"py\");\n}\n\nsofa::simulation::Node::SPtr SceneLoaderPY::load(const char *filename)\n{\n return loadSceneWithArguments(filename);\n}\n\nsofa::simulation::Node::SPtr SceneLoaderPY::loadSceneWithArguments(const char *filename, const std::vector<std::string>& arguments)\n{\n PythonEnvironment::gil lock(__func__); \n if(!OurHeader.empty() && 0 != PyRun_SimpleString(OurHeader.c_str()))\n {\n SP_MESSAGE_ERROR( \"header script run error.\" )\n return NULL;\n }\n\n PythonEnvironment::runString(\"createScene=None\");\n PythonEnvironment::runString(\"createSceneAndController=None\");\n\n PythonEnvironment::runString(std::string(\"__file__=\\\"\") + filename + \"\\\"\");\n\n \/\/ We go the the current file's directory so that all relative path are correct\n helper::system::SetDirectory chdir ( filename );\n\n notifyLoadingScene();\n if(!PythonEnvironment::runFile(helper::system::SetDirectory::GetFileName(filename).c_str(), arguments))\n {\n \/\/ LOAD ERROR\n SP_MESSAGE_ERROR( \"scene script load error.\" )\n return NULL;\n }\n\n PyObject* pDict = PyModule_GetDict(PyImport_AddModule(\"__main__\"));\n\n \/\/ pFunc is also a borrowed reference\n PyObject *pFunc = PyDict_GetItemString(pDict, \"createScene\");\n if (PyCallable_Check(pFunc))\n {\n Node::SPtr rootNode = Node::create(\"root\");\n SP_CALL_MODULEFUNC(pFunc, \"(O)\", sofa::PythonFactory::toPython(rootNode.get()))\n\n return rootNode;\n }\n else\n {\n PyObject *pFunc = PyDict_GetItemString(pDict, \"createSceneAndController\");\n if (PyCallable_Check(pFunc))\n {\n Node::SPtr rootNode = Node::create(\"root\");\n SP_CALL_MODULEFUNC(pFunc, \"(O)\", sofa::PythonFactory::toPython(rootNode.get()))\n\n rootNode->addObject( core::objectmodel::New<component::controller::PythonMainScriptController>( filename ) );\n\n return rootNode;\n }\n }\n\n SP_MESSAGE_ERROR( \"cannot create Scene, no \\\"createScene(rootNode)\\\" nor \\\"createSceneAndController(rootNode)\\\" module method found.\" )\n return NULL;\n}\n\n\nbool SceneLoaderPY::loadTestWithArguments(const char *filename, const std::vector<std::string>& arguments)\n{\n PythonEnvironment::gil lock(__func__); \n if(!OurHeader.empty() && 0 != PyRun_SimpleString(OurHeader.c_str()))\n {\n SP_MESSAGE_ERROR( \"header script run error.\" )\n return false;\n }\n\n PythonEnvironment::runString(\"createScene=None\");\n PythonEnvironment::runString(\"createSceneAndController=None\");\n\n PythonEnvironment::runString(std::string(\"__file__=\\\"\") + filename + \"\\\"\");\n\n \/\/ it runs the unecessary SofaPython script but it is not a big deal\n if(!PythonEnvironment::runFile(filename,arguments))\n {\n \/\/ LOAD ERROR\n SP_MESSAGE_ERROR( \"script load error.\" )\n return false;\n }\n\n PyObject* pDict = PyModule_GetDict(PyImport_AddModule(\"__main__\"));\n\n \/\/ pFunc is also a borrowed reference\n PyObject *pFunc = PyDict_GetItemString(pDict, \"run\");\n if (PyCallable_Check(pFunc))\n {\n PyObject *res = PyObject_CallObject(pFunc,0);\n printPythonExceptions();\n\n if( !res )\n {\n SP_MESSAGE_ERROR( \"Python test 'run' function does not return any value\" )\n return false;\n }\n else if( !PyBool_Check(res) )\n {\n SP_MESSAGE_ERROR( \"Python test 'run' function does not return a boolean\" )\n Py_DECREF(res);\n return false;\n }\n\n bool result = ( res == Py_True );\n Py_DECREF(res);\n\n return result;\n }\n else\n {\n SP_MESSAGE_ERROR( \"Python test has no 'run'' function\" )\n return false;\n }\n}\n\n\n\nvoid SceneLoaderPY::write(Node* node, const char *filename)\n{\n exportPython( node, filename );\n}\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\n\nstatic const std::string s_tab = \" \";\n\n\ninline void printBaseHeader( std::ostream& out, Node* node )\n{\n out << \"import Sofa\\n\\n\\n\";\n out << \"def createScene(root):\\n\";\n\n out << s_tab << \"root.dt = \" << node->getDt() << std::endl;\n const Context::Vec3& g = node->getGravity();\n out << s_tab << \"root.gravity = [\" << g[0] << \",\" << g[1] << \",\" << g[2] << \"]\" << std::endl;\n}\n\n\nvoid exportPython( Node* node, const char* fileName )\n{\n if ( !node ) return;\n\n if ( fileName!=NULL )\n {\n std::ofstream out( fileName );\n\n printBaseHeader( out, node );\n\n PythonExporterVisitor print( out );\n node->execute( print );\n }\n else\n {\n printBaseHeader( std::cout, node );\n\n PythonExporterVisitor print( std::cout );\n node->execute( print );\n }\n}\n\n\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\n\n\ntemplate<class T>\nvoid PythonExporterVisitor::processObject( T obj, const std::string& nodeVariable )\n{\n std::string classname = obj->getClassName();\n std::string templatename = obj->getTemplateName();\n\n m_out << s_tab << nodeVariable << \".createObject( '\" << classname <<\"', template='\" << templatename << \"'\";\n\n obj->writeDatas( m_out, \", \" );\n\n m_out << \")\" << std::endl;\n}\n\n\nVisitor::Result PythonExporterVisitor::processNodeTopDown(Node* node)\n{\n m_out << \"\\n\\n\";\n\n m_variableIndex++;\n\n sofa::helper::vector< core::objectmodel::BaseNode* > parents = node->getParents();\n\n\n std::string nodeName = node->getName();\n std::stringstream nodeVariable;\n\n\n if( !parents.empty() ) \/\/ not root\n {\n nodeVariable << nodeName << \"_Node\" << m_variableIndex;\n m_mapNodeVariable[node] = nodeVariable.str();\n\n const std::string& parentVariable = m_mapNodeVariable[parents[0]];\n\n m_out << s_tab << nodeVariable.str() << \" = \"<<parentVariable<<\".createChild( '\"<<nodeName <<\"' )\" << std::endl;\n }\n else\n {\n nodeVariable << \"root\";\n m_mapNodeVariable[node] = nodeVariable.str();\n }\n\n\n for (Node::ObjectIterator it = node->object.begin(); it != node->object.end(); ++it)\n {\n sofa::core::objectmodel::BaseObject* obj = it->get();\n this->processObject( obj, nodeVariable.str() );\n }\n\n return RESULT_CONTINUE;\n}\n\nvoid PythonExporterVisitor::processNodeBottomUp(Node* node)\n{\n sofa::helper::vector< core::objectmodel::BaseNode* > parents = node->getParents();\n\n const std::string& nodeVariable = m_mapNodeVariable[node];\n\n\n \/\/ add all its parents to a multinode\n for( size_t i = 1 ; i<parents.size() ; ++ i)\n {\n const std::string& parentVariable = m_mapNodeVariable[parents[i]];\n\n m_out << s_tab << parentVariable << \".addChild(\" << nodeVariable << \")\\n\";\n }\n}\n\n\n} \/\/ namespace simulation\n\n} \/\/ namespace sofa\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ Time: O(n)\n\/\/ Space: O(n)\n\nclass Solution {\npublic:\n vector<int> findMinHeightTrees(int n, vector<pair<int, int>>& edges) {\n if (n == 1) {\n return {0};\n }\n\n unordered_map<int, unordered_set<int>> neighbors;\n for (const auto& e : edges) {\n int u, v;\n tie(u, v) = e;\n neighbors[u].emplace(v);\n neighbors[v].emplace(u);\n }\n\n vector<int> pre_level, cur_level;\n unordered_set<int> unvisited;\n for (int i = 0; i < n; ++i) {\n if (neighbors[i].size() == 1) { \/\/ A leaf.\n pre_level.emplace_back(i);\n }\n unvisited.emplace(i);\n }\n\n \/\/ A graph can have 2 MHTs at most.\n \/\/ BFS from the leaves until the number \n \/\/ of the unvisited nodes is less than 3.\n while (unvisited.size() > 2) {\n cur_level.clear();\n for (const auto& u : pre_level) {\n unvisited.erase(u);\n for (const auto& v : neighbors[u]) {\n if (unvisited.count(v)) { \n neighbors[v].erase(u);\n if (neighbors[v].size() == 1) {\n cur_level.emplace_back(v);\n }\n }\n }\n }\n swap(pre_level, cur_level);\n }\n vector<int> res(unvisited.begin(), unvisited.end());\n return res;\n }\n};\n<commit_msg>Update minimum-height-trees.cpp<commit_after>\/\/ Time: O(n)\n\/\/ Space: O(n)\n\nclass Solution {\npublic:\n vector<int> findMinHeightTrees(int n, vector<pair<int, int>>& edges) {\n if (n == 1) {\n return {0};\n }\n\n unordered_map<int, unordered_set<int>> neighbors;\n for (const auto& e : edges) {\n int u, v;\n tie(u, v) = e;\n neighbors[u].emplace(v);\n neighbors[v].emplace(u);\n }\n\n vector<int> pre_level, cur_level;\n unordered_set<int> unvisited;\n for (int i = 0; i < n; ++i) {\n if (neighbors[i].size() == 1) { \/\/ A leaf.\n pre_level.emplace_back(i);\n }\n unvisited.emplace(i);\n }\n\n \/\/ A graph can have 2 MHTs at most.\n \/\/ BFS from the leaves until the number \n \/\/ of the unvisited nodes is less than 3.\n while (unvisited.size() > 2) {\n cur_level.clear();\n for (const auto& u : pre_level) {\n unvisited.erase(u);\n for (const auto& v : neighbors[u]) {\n if (unvisited.count(v)) { \n neighbors[v].erase(u);\n if (neighbors[v].size() == 1) {\n cur_level.emplace_back(v);\n }\n }\n }\n }\n swap(pre_level, cur_level);\n }\n\n vector<int> res(unvisited.begin(), unvisited.end());\n return res;\n }\n};\n<|endoftext|>"} {"text":"<commit_before>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @file drawBox.cpp\n\/\/\/ @author Chris L Baker (clb) <chris@chimail.net>\n\/\/\/ @date 2014.05.20\n\/\/\/ @brief Simple example for using the draw lib\n\/\/\/\n\/\/\/ @attention Copyright (C) 2014\n\/\/\/ @attention All rights reserved\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/\/ The main draw object\n#include <DDDisplayInterface\/DisplayInterface.h>\n\n\/\/\/ The things to include for drawing\n#include <DDDisplayObjects\/Grids.h> \/\/ for ground()\n#include <DDDisplayObjects\/Triads.h> \/\/ for the world origin\n#include <DDDisplayObjects\/Colors.h> \/\/ gets various colors\n#include <DDDisplayObjects\/Capsules.h> \/\/ to draw the actual box\n#include <DDDisplayObjects\/HeadsUpDisplay.h> \/\/ flashing awesome\n\n\/\/\/ std stuff\n#include <thread>\n\nint main()\n{\n \/\/ draws a \"standard\" grid on the ground (z=0 plane)\n d3::di().add( \"Ground\", d3::ground() );\n\n \/\/ draws an rgb triad at the origin\n d3::di().add( \"Origin\", d3::origin() );\n\n \/\/ create a simple HUD\n static const float width(0.13), height(0.07);\n static const d3::HeadsUpDisplay::Position position(d3::HeadsUpDisplay::Position::CENTER);\n static const std::string initText(\"AWESOME\");\n d3::HeadsUpDisplay hud(width, height, position, initText);\n hud.setBackgroundColor(d3::black());\n\n \/\/ add the hud to the display\n d3::di().add( \"HUD\", d3::get(hud) );\n\n \/\/ create a little thread to \"flash\" the hud\n std::thread thrd\n ([&]()\n {\n while ( d3::di().running() )\n {\n \/\/ we are messing directly with things in the render thread -\n \/\/ make sure we lock the display interface\n if ( d3::di().try_lock() )\n {\n hud.show(not hud.isShown());\n d3::di().unlock();\n }\n\n \/\/ flash at about 2Hz\n usleep(500000);\n }\n });\n\n \/\/ create the box as a set of capsules\n static const double radius(0.1);\n d3::CapsuleVec_t capsules;\n\n \/\/ The bottom square\n capsules.push_back({{-1.0, -1.0, -1.0}, { 1.0, -1.0, -1.0}, radius, d3::nextColor()});\n capsules.push_back({{ 1.0, -1.0, -1.0}, { 1.0, 1.0, -1.0}, radius, d3::nextColor()});\n capsules.push_back({{ 1.0, 1.0, -1.0}, {-1.0, 1.0, -1.0}, radius, d3::nextColor()});\n capsules.push_back({{-1.0, 1.0, -1.0}, {-1.0, -1.0, -1.0}, radius, d3::nextColor()});\n\n \/\/ The top square\n capsules.push_back({{-1.0, -1.0, 1.0}, { 1.0, -1.0, 1.0}, radius, d3::nextColor()});\n capsules.push_back({{ 1.0, -1.0, 1.0}, { 1.0, 1.0, 1.0}, radius, d3::nextColor()});\n capsules.push_back({{ 1.0, 1.0, 1.0}, {-1.0, 1.0, 1.0}, radius, d3::nextColor()});\n capsules.push_back({{-1.0, 1.0, 1.0}, {-1.0, -1.0, 1.0}, radius, d3::nextColor()});\n\n \/\/ Joins the top to the bottom\n capsules.push_back({{-1.0, -1.0, -1.0}, {-1.0, -1.0, 1.0}, radius, d3::nextColor()});\n capsules.push_back({{ 1.0, -1.0, -1.0}, { 1.0, -1.0, 1.0}, radius, d3::nextColor()});\n capsules.push_back({{ 1.0, 1.0, -1.0}, { 1.0, 1.0, 1.0}, radius, d3::nextColor()});\n capsules.push_back({{-1.0, 1.0, -1.0}, {-1.0, 1.0, 1.0}, radius, d3::nextColor()});\n\n \/\/ add the capsules to the display\n d3::di().add( \"box\", d3::get(capsules) );\n\n \/\/ wait for the drawing to close\n d3::di().blockForClose();\n\n return EXIT_SUCCESS;\n};\n<commit_msg>Why doesn't my compiler know about usleep? Changed to std::this_thread::sleep_for and seems to work...<commit_after>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @file drawBox.cpp\n\/\/\/ @author Chris L Baker (clb) <chris@chimail.net>\n\/\/\/ @date 2014.05.20\n\/\/\/ @brief Simple example for using the draw lib\n\/\/\/\n\/\/\/ @attention Copyright (C) 2014\n\/\/\/ @attention All rights reserved\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/\/ The main draw object\n#include <DDDisplayInterface\/DisplayInterface.h>\n\n\/\/\/ The things to include for drawing\n#include <DDDisplayObjects\/Grids.h> \/\/ for ground()\n#include <DDDisplayObjects\/Triads.h> \/\/ for the world origin\n#include <DDDisplayObjects\/Colors.h> \/\/ gets various colors\n#include <DDDisplayObjects\/Capsules.h> \/\/ to draw the actual box\n#include <DDDisplayObjects\/HeadsUpDisplay.h> \/\/ flashing awesome\n\n\/\/\/ std stuff\n#include <chrono>\n#include <thread>\n\nint main()\n{\n \/\/ draws a \"standard\" grid on the ground (z=0 plane)\n d3::di().add( \"Ground\", d3::ground() );\n\n \/\/ draws an rgb triad at the origin\n d3::di().add( \"Origin\", d3::origin() );\n\n \/\/ create a simple HUD\n static const float width(0.13), height(0.07);\n static const d3::HeadsUpDisplay::Position position(d3::HeadsUpDisplay::Position::CENTER);\n static const std::string initText(\"AWESOME\");\n d3::HeadsUpDisplay hud(width, height, position, initText);\n hud.setBackgroundColor(d3::black());\n\n \/\/ add the hud to the display\n d3::di().add( \"HUD\", d3::get(hud) );\n\n \/\/ create a little thread to \"flash\" the hud\n std::thread thrd\n ([&]()\n {\n while ( d3::di().running() )\n {\n \/\/ we are messing directly with things in the render thread -\n \/\/ make sure we lock the display interface\n if ( d3::di().try_lock() )\n {\n hud.show(not hud.isShown());\n d3::di().unlock();\n }\n\n \/\/ flash at about 2Hz\n std::this_thread::sleep_for(std::chrono::milliseconds(500));\n }\n });\n\n \/\/ create the box as a set of capsules\n static const double radius(0.1);\n d3::CapsuleVec_t capsules;\n\n \/\/ The bottom square\n capsules.push_back({{-1.0, -1.0, -1.0}, { 1.0, -1.0, -1.0}, radius, d3::nextColor()});\n capsules.push_back({{ 1.0, -1.0, -1.0}, { 1.0, 1.0, -1.0}, radius, d3::nextColor()});\n capsules.push_back({{ 1.0, 1.0, -1.0}, {-1.0, 1.0, -1.0}, radius, d3::nextColor()});\n capsules.push_back({{-1.0, 1.0, -1.0}, {-1.0, -1.0, -1.0}, radius, d3::nextColor()});\n\n \/\/ The top square\n capsules.push_back({{-1.0, -1.0, 1.0}, { 1.0, -1.0, 1.0}, radius, d3::nextColor()});\n capsules.push_back({{ 1.0, -1.0, 1.0}, { 1.0, 1.0, 1.0}, radius, d3::nextColor()});\n capsules.push_back({{ 1.0, 1.0, 1.0}, {-1.0, 1.0, 1.0}, radius, d3::nextColor()});\n capsules.push_back({{-1.0, 1.0, 1.0}, {-1.0, -1.0, 1.0}, radius, d3::nextColor()});\n\n \/\/ Joins the top to the bottom\n capsules.push_back({{-1.0, -1.0, -1.0}, {-1.0, -1.0, 1.0}, radius, d3::nextColor()});\n capsules.push_back({{ 1.0, -1.0, -1.0}, { 1.0, -1.0, 1.0}, radius, d3::nextColor()});\n capsules.push_back({{ 1.0, 1.0, -1.0}, { 1.0, 1.0, 1.0}, radius, d3::nextColor()});\n capsules.push_back({{-1.0, 1.0, -1.0}, {-1.0, 1.0, 1.0}, radius, d3::nextColor()});\n\n \/\/ add the capsules to the display\n d3::di().add( \"box\", d3::get(capsules) );\n\n \/\/ wait for the drawing to close\n d3::di().blockForClose();\n\n return EXIT_SUCCESS;\n};\n<|endoftext|>"} {"text":"<commit_before>\/\/ Time: O(p), p is number of positions\n\/\/ Space: O(p)\n\n\/\/ Using unordered_map.\nclass Solution {\npublic:\n vector<int> numIslands2(int m, int n, vector<pair<int, int>>& positions) {\n vector<int> numbers;\n int number = 0;\n const vector<pair<int, int>> directions{{0, -1}, {0, 1},\n {-1, 0}, {1, 0}};\n unordered_map<int, int> set;\n for (const auto& position : positions) {\n const auto& node = make_pair(position.first, position.second);\n set[node_id(node, n)] = node_id(node, n);\n ++number;\n\n for (const auto& d : directions) {\n const auto& neighbor = make_pair(position.first + d.first,\n position.second + d.second);\n if (neighbor.first >= 0 && neighbor.first < m &&\n neighbor.second >= 0 && neighbor.second < n &&\n set.find(node_id(neighbor, n)) != set.end()) {\n if (find_set(node_id(node, n), &set) != \n find_set(node_id(neighbor, n), &set)) {\n \/\/ Merge different islands.\n union_set(&set, node_id(node, n), node_id(neighbor, n));\n --number;\n }\n }\n }\n numbers.emplace_back(number);\n }\n\n return numbers;\n }\n\n int node_id(const pair<int, int>& node, const int n) {\n return node.first * n + node.second;\n }\n\n int find_set(int x, unordered_map<int, int> *set) {\n if ((*set)[x] != x) {\n (*set)[x] = find_set((*set)[x], set); \/\/ path compression.\n }\n return (*set)[x];\n }\n\n void union_set(unordered_map<int, int> *set, const int x, const int y) {\n int x_root = find_set(x, set), y_root = find_set(y, set);\n (*set)[min(x_root, y_root)] = max(x_root, y_root);\n }\n};\n\n\n\/\/ Time: O(p), p is number of positions\n\/\/ Space: O(m * n)\n\/\/ Using vector.\nclass Solution2 {\npublic:\n \/**\n * @param n an integer\n * @param m an integer\n * @param operators an array of point\n * @return an integer array\n *\/\n vector<int> numIslands2(int m, int n, vector<pair<int, int>>& positions) {\n vector<int> numbers;\n int number = 0;\n const vector<pair<int, int>> directions{{0, -1}, {0, 1},\n {-1, 0}, {1, 0}};\n vector<int> set(m * n, -1);\n for (const auto& position : positions) {\n const auto& node = make_pair(position.first, position.second);\n set[node_id(node, n)] = node_id(node, n);\n ++number;\n\n for (const auto& d : directions) {\n const auto& neighbor = make_pair(position.first + d.first,\n position.second + d.second);\n if (neighbor.first >= 0 && neighbor.first < m &&\n neighbor.second >= 0 && neighbor.second < n &&\n set[node_id(neighbor, n)] != -1) {\n if (find_set(node_id(node, n), &set) != \n find_set(node_id(neighbor, n), &set)) {\n \/\/ Merge different islands.\n union_set(&set, node_id(node, n), node_id(neighbor, n));\n --number;\n }\n }\n }\n numbers.emplace_back(number);\n }\n\n return numbers;\n }\n\n int node_id(const pair<int, int>& node, const int m) {\n return node.first * m + node.second;\n }\n\n int find_set(int x, vector<int> *set) {\n int parent = x;\n while ((*set)[parent] != parent) {\n parent = (*set)[parent];\n }\n while ((*set)[x] != x) {\n int tmp = (*set)[x];\n (*set)[x] = parent;\n x = tmp;\n }\n return parent;\n }\n\n void union_set(vector<int> *set, const int x, const int y) {\n int x_root = find_set(x, set), y_root = find_set(y, set);\n (*set)[min(x_root, y_root)] = max(x_root, y_root);\n }\n};\n<commit_msg>Update number-of-islands-ii.cpp<commit_after>\/\/ Time: O(k * log(m * n)), k is the length of the positions\n\/\/ Space: O(k)\n\n\/\/ Using unordered_map.\nclass Solution {\npublic:\n vector<int> numIslands2(int m, int n, vector<pair<int, int>>& positions) {\n vector<int> numbers;\n int number = 0;\n const vector<pair<int, int>> directions{{0, -1}, {0, 1},\n {-1, 0}, {1, 0}};\n unordered_map<int, int> set;\n for (const auto& position : positions) {\n const auto& node = make_pair(position.first, position.second);\n set[node_id(node, n)] = node_id(node, n);\n ++number;\n\n for (const auto& d : directions) {\n const auto& neighbor = make_pair(position.first + d.first,\n position.second + d.second);\n if (neighbor.first >= 0 && neighbor.first < m &&\n neighbor.second >= 0 && neighbor.second < n &&\n set.find(node_id(neighbor, n)) != set.end()) {\n if (find_set(node_id(node, n), &set) != \n find_set(node_id(neighbor, n), &set)) {\n \/\/ Merge different islands.\n union_set(&set, node_id(node, n), node_id(neighbor, n));\n --number;\n }\n }\n }\n numbers.emplace_back(number);\n }\n\n return numbers;\n }\n\n int node_id(const pair<int, int>& node, const int n) {\n return node.first * n + node.second;\n }\n\n int find_set(int x, unordered_map<int, int> *set) {\n if ((*set)[x] != x) {\n (*set)[x] = find_set((*set)[x], set); \/\/ path compression.\n }\n return (*set)[x];\n }\n\n void union_set(unordered_map<int, int> *set, const int x, const int y) {\n int x_root = find_set(x, set), y_root = find_set(y, set);\n (*set)[min(x_root, y_root)] = max(x_root, y_root);\n }\n};\n\n\n\/\/ Time: O(k * log(m * n)), k is the length of the positions\n\/\/ Space: O(m * n)\n\/\/ Using vector.\nclass Solution2 {\npublic:\n \/**\n * @param n an integer\n * @param m an integer\n * @param operators an array of point\n * @return an integer array\n *\/\n vector<int> numIslands2(int m, int n, vector<pair<int, int>>& positions) {\n vector<int> numbers;\n int number = 0;\n const vector<pair<int, int>> directions{{0, -1}, {0, 1},\n {-1, 0}, {1, 0}};\n vector<int> set(m * n, -1);\n for (const auto& position : positions) {\n const auto& node = make_pair(position.first, position.second);\n set[node_id(node, n)] = node_id(node, n);\n ++number;\n\n for (const auto& d : directions) {\n const auto& neighbor = make_pair(position.first + d.first,\n position.second + d.second);\n if (neighbor.first >= 0 && neighbor.first < m &&\n neighbor.second >= 0 && neighbor.second < n &&\n set[node_id(neighbor, n)] != -1) {\n if (find_set(node_id(node, n), &set) != \n find_set(node_id(neighbor, n), &set)) {\n \/\/ Merge different islands.\n union_set(&set, node_id(node, n), node_id(neighbor, n));\n --number;\n }\n }\n }\n numbers.emplace_back(number);\n }\n\n return numbers;\n }\n\n int node_id(const pair<int, int>& node, const int m) {\n return node.first * m + node.second;\n }\n\n int find_set(int x, vector<int> *set) {\n int parent = x;\n while ((*set)[parent] != parent) {\n parent = (*set)[parent];\n }\n while ((*set)[x] != x) {\n int tmp = (*set)[x];\n (*set)[x] = parent;\n x = tmp;\n }\n return parent;\n }\n\n void union_set(vector<int> *set, const int x, const int y) {\n int x_root = find_set(x, set), y_root = find_set(y, set);\n (*set)[min(x_root, y_root)] = max(x_root, y_root);\n }\n};\n<|endoftext|>"} {"text":"<commit_before>\/\/ Jubatus: Online machine learning framework for distributed environment\n\/\/ Copyright (C) 2013 Preferred Infrastructure and Nippon Telegraph and Telephone Corporation.\n\/\/\n\/\/ This library is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU Lesser General Public\n\/\/ License version 2.1 as published by the Free Software Foundation.\n\/\/\n\/\/ This library is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ Lesser General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License along with this library; if not, write to the Free Software\n\/\/ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n#include <vector>\n#include <utility>\n#include <map>\n#include <string>\n\n#include <gtest\/gtest.h>\n\n#include \"jubatus\/util\/lang\/cast.h\"\n\n#include \"..\/fv_converter\/datum.hpp\"\n#include \"..\/fv_converter\/converter_config.hpp\"\n#include \"..\/recommender\/recommender.hpp\"\n#include \"..\/recommender\/recommender_type.hpp\"\n#include \"..\/classifier\/classifier_test_util.hpp\"\n#include \"..\/framework\/stream_writer.hpp\"\n#include \"recommender.hpp\"\n\n#include \"test_util.hpp\"\n\nusing std::string;\nusing std::map;\nusing std::vector;\nusing std::pair;\nusing std::make_pair;\nusing std::stringstream;\n\nusing jubatus::util::lang::lexical_cast;\nusing jubatus::core::fv_converter::datum;\n\nnamespace jubatus {\nnamespace core {\nnamespace driver {\n\nclass recommender_test : public ::testing::Test {\n protected:\n void SetUp() {\n recommender_.reset(new driver::recommender(\n jubatus::util::lang::shared_ptr<core::recommender::recommender_base>(\n new core::recommender::inverted_index),\n make_fv_converter()));\n }\n\n void TearDown() {\n recommender_.reset();\n }\n\n jubatus::util::lang::shared_ptr<core::driver::recommender> recommender_;\n};\n\n\nTEST_F(recommender_test, small) {\n datum d;\n d.num_values_.push_back(make_pair(\"f1\", 1.0));\n recommender_->update_row(\"key\", d);\n recommender_->clear_row(\"key\");\n recommender_->update_row(\"key\", d);\n\n recommender_->complete_row_from_datum(d);\n recommender_->complete_row_from_id(\"key\");\n}\n\n} \/\/ namespace driver\n} \/\/ namespace core\n} \/\/ namespace jubatus\n<commit_msg>add nearest_neighbor_recommender test<commit_after>\/\/ Jubatus: Online machine learning framework for distributed environment\n\/\/ Copyright (C) 2013 Preferred Infrastructure and Nippon Telegraph and Telephone Corporation.\n\/\/\n\/\/ This library is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU Lesser General Public\n\/\/ License version 2.1 as published by the Free Software Foundation.\n\/\/\n\/\/ This library is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ Lesser General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License along with this library; if not, write to the Free Software\n\/\/ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n#include <vector>\n#include <utility>\n#include <map>\n#include <string>\n\n#include <gtest\/gtest.h>\n\n#include \"jubatus\/util\/lang\/cast.h\"\n#include \"jubatus\/util\/lang\/shared_ptr.h\"\n#include \"..\/common\/jsonconfig.hpp\"\n\n#include \"..\/fv_converter\/datum.hpp\"\n#include \"..\/fv_converter\/converter_config.hpp\"\n#include \"..\/recommender\/recommender.hpp\"\n#include \"..\/recommender\/recommender_type.hpp\"\n#include \"..\/recommender\/recommender_factory.hpp\"\n#include \"..\/classifier\/classifier_test_util.hpp\"\n#include \"..\/framework\/stream_writer.hpp\"\n#include \"recommender.hpp\"\n\n#include \"test_util.hpp\"\n\nusing std::string;\nusing std::map;\nusing std::vector;\nusing std::pair;\nusing std::make_pair;\nusing std::stringstream;\nusing jubatus::util::lang::shared_ptr;\nusing jubatus::util::text::json::json;\nusing jubatus::util::text::json::json_object;\nusing jubatus::util::text::json::json_integer;\nusing jubatus::util::text::json::json_string;\nusing jubatus::util::text::json::json_float;\nusing jubatus::util::lang::lexical_cast;\nusing jubatus::core::fv_converter::datum;\nusing jubatus::core::recommender::recommender_base;\nnamespace jubatus {\nnamespace core {\nnamespace driver {\n\nclass recommender_test : public ::testing::Test {\n protected:\n void SetUp() {\n recommender_.reset(new driver::recommender(\n jubatus::util::lang::shared_ptr<core::recommender::recommender_base>(\n new core::recommender::inverted_index),\n make_fv_converter()));\n }\n\n void TearDown() {\n recommender_.reset();\n }\n\n jubatus::util::lang::shared_ptr<core::driver::recommender> recommender_;\n};\n\n\nTEST_F(recommender_test, small) {\n datum d;\n d.num_values_.push_back(make_pair(\"f1\", 1.0));\n recommender_->update_row(\"key\", d);\n recommender_->clear_row(\"key\");\n recommender_->update_row(\"key\", d);\n\n recommender_->complete_row_from_datum(d);\n recommender_->complete_row_from_id(\"key\");\n}\n\nclass nn_recommender_test\n : public ::testing::TestWithParam<\n shared_ptr<core::recommender::recommender_base> > {\n protected:\n void SetUp() {\n recommender_.reset(new driver::recommender(\n jubatus::util::lang::shared_ptr<core::recommender::recommender_base>(\n new core::recommender::inverted_index),\n make_tf_idf_fv_converter()));\n }\n\n void TearDown() {\n recommender_.reset();\n }\n\n jubatus::util::lang::shared_ptr<core::driver::recommender> recommender_;\n};\n\nvector<shared_ptr<recommender_base> >\ncreate_recommender_bases() {\n const std::string id(\"my_id\");\n vector<shared_ptr<recommender_base> > recommenders;\n\n vector<pair<string, int> > pattern;\n for (size_t i = 8; i < 3000; i = i << 1) { \/\/ up to 2048\n pattern.push_back(make_pair(\"lsh\", i));\n pattern.push_back(make_pair(\"euclid_lsh\", i));\n pattern.push_back(make_pair(\"minhash\", i));\n }\n for (size_t i = 0; i < pattern.size(); ++i) {\n shared_ptr<core::table::column_table> table(new core::table::column_table);\n\n json jsconf(new json_object);\n json method_param(new json_object);\n method_param[\"hash_num\"] = new json_integer(pattern[i].second);\n jsconf[\"parameter\"] = method_param;\n jsconf[\"method\"] = new json_string(pattern[i].first);\n common::jsonconfig::config conf(jsconf);\n recommenders.push_back(\n core::recommender::recommender_factory::create_recommender(\n \"nearest_neighbor_recommender\",\n conf,\n id));\n }\n return recommenders;\n}\n\nfv_converter::datum create_datum_str(const string& key, const string& value) {\n fv_converter::datum d;\n d.string_values_.push_back(make_pair(key, value));\n return d;\n}\n\nTEST_P(nn_recommender_test, update) {\n datum d = create_datum_str(\"a\", \"f g h\");\n for (int i = 0; i < 10; ++i) {\n recommender_->update_row(\"id1\", create_datum_str(\"a\", \"a b c\"));\n recommender_->update_row(\"id2\", create_datum_str(\"a\", \"d e f\"));\n recommender_->update_row(\"id3\", create_datum_str(\"a\", \"e f g\"));\n recommender_->update_row(\"id4\", create_datum_str(\"a\", \"f g h\"));\n recommender_->update_row(\"id5\", create_datum_str(\"a\", \"h i j\"));\n recommender_->update_row(\"id6\", create_datum_str(\"a\", \"i j a\"));\n recommender_->update_row(\"id7\", create_datum_str(\"a\", \"j a b\"));\n }\n\n vector<pair<string, float> > ret = recommender_->similar_row_from_datum(d, 10);\n ASSERT_EQ(\"id4\", ret[0].first);\n}\n\nINSTANTIATE_TEST_CASE_P(nn_recommender_test_instance,\n nn_recommender_test,\n testing::ValuesIn(create_recommender_bases()));\n} \/\/ namespace driver\n} \/\/ namespace core\n} \/\/ namespace jubatus\n<|endoftext|>"} {"text":"<commit_before>#ifndef STAN__MATH__MATRIX_SPARSE_EXTRACTORS_HPP\n#define STAN__MATH__MATRIX_SPARSE_EXTRACTORS_HPP\n\n#include <Eigen\/Sparse>\n#include <vector>\n#include <numeric>\n\nnamespace stan {\n\n namespace math {\n \/\/ FIXME: The implementations are the same, only the interpretation\n \/\/ differs in CSC vs. CSR. In the time I had I couldn't get one\n \/\/ implementation that swallowed both matrix types.\n\n \/** @defgroup sparse_csc CSC Sparse Extractors.\n * This group of functions extracts the components of a\n * Compressed Sparse Column (CSC) sparse matrix. The components\n * are:\n * - w: the non-zero values in the sparse matrix.\n * - v: one-based row index for each value in w, as a result this\n * is the same length as w.\n * - u: one-based index of where each column starts in w, length\n * is equal to the number of columns plus one. Last entry is\n * one-past-the-end in w (one-based...)\n * - z: number of non-zero entries in each column of w, length is\n * equal to the number of columns.\n * @{\n *\/\n\n template <typename T> \n const Eigen::Matrix<T, Eigen::Dynamic,1> extract_w(Eigen::SparseMatrix<T> A) {\n Eigen::Matrix<T,Eigen::Dynamic,1> w(A.nonZeros());\n w.setZero();\n for (int j = 0; j < A.nonZeros(); ++j)\n w[j] = *(A.valuePtr()+j);\n return w;\n }\n \n template <typename T> \n const std::vector<int> extract_v(Eigen::SparseMatrix<T> A) {\n std::vector<int> v(A.nonZeros());\n for (int j = 0; j < A.nonZeros(); ++j)\n v[j] = *(A.innerIndexPtr()+j) + 1; \/\/ make 1-indexed\n return v;\n }\n \n template <typename T> \n const std::vector<int> extract_u(Eigen::SparseMatrix<T> A) {\n std::vector<int> u(A.outerSize()+1);\n for (int j = 0; j <= A.outerSize(); ++j)\n u[j] = *(A.outerIndexPtr()+j) + 1; \/\/ make 1-indexed\n return u;\n }\n \n template <typename T> \n const std::vector<int> extract_z(Eigen::SparseMatrix<T> A) {\n std::vector<int> u(A.outerSize()+1);\n std::vector<int> z(A.outerSize()+1);\n u = extract_u(A);\n std::adjacent_difference(u.begin(), u.end(), z.begin());\n z.erase(z.begin());\n return z;\n }\n \/** @} *\/ \/\/ end of sparse_csc group. \n \n }\n}\n\n#endif\n<commit_msg>linted sparse_extractors_csc, no meaningful changes.<commit_after>#ifndef STAN__MATH__MATRIX_SPARSE_EXTRACTORS_HPP\n#define STAN__MATH__MATRIX_SPARSE_EXTRACTORS_HPP\n\n#include <Eigen\/Sparse>\n#include <vector>\n#include <numeric>\n\nnamespace stan {\n\n namespace math {\n \/\/ FIXME: The implementations are the same, only the interpretation\n \/\/ differs in CSC vs. CSR. In the time I had I couldn't get one\n \/\/ implementation that swallowed both matrix types.\n\n \/** @defgroup sparse_csc CSC Sparse Extractors.\n * This group of functions extracts the components of a\n * Compressed Sparse Column (CSC) sparse matrix. The components\n * are:\n * - w: the non-zero values in the sparse matrix.\n * - v: one-based row index for each value in w, as a result this\n * is the same length as w.\n * - u: one-based index of where each column starts in w, length\n * is equal to the number of columns plus one. Last entry is\n * one-past-the-end in w (one-based...)\n * - z: number of non-zero entries in each column of w, length is\n * equal to the number of columns.\n * @{\n *\/\n\n template <typename T>\n const Eigen::Matrix<T, Eigen::Dynamic, 1>\n extract_w(Eigen::SparseMatrix<T> A) {\n Eigen::Matrix<T, Eigen::Dynamic, 1> w(A.nonZeros());\n w.setZero();\n for (int j = 0; j < A.nonZeros(); ++j)\n w[j] = *(A.valuePtr()+j);\n return w;\n }\n\n template <typename T>\n const std::vector<int> extract_v(Eigen::SparseMatrix<T> A) {\n std::vector<int> v(A.nonZeros());\n for (int j = 0; j < A.nonZeros(); ++j)\n v[j] = *(A.innerIndexPtr()+j) + 1; \/\/ make 1-indexed\n return v;\n }\n\n template <typename T>\n const std::vector<int> extract_u(Eigen::SparseMatrix<T> A) {\n std::vector<int> u(A.outerSize()+1);\n for (int j = 0; j <= A.outerSize(); ++j)\n u[j] = *(A.outerIndexPtr()+j) + 1; \/\/ make 1-indexed\n return u;\n }\n\n template <typename T>\n const std::vector<int> extract_z(Eigen::SparseMatrix<T> A) {\n std::vector<int> u(A.outerSize()+1);\n std::vector<int> z(A.outerSize()+1);\n u = extract_u(A);\n std::adjacent_difference(u.begin(), u.end(), z.begin());\n z.erase(z.begin());\n return z;\n }\n \/** @} *\/ \/\/ end of sparse_csc group.\n\n }\n}\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/\/ Time: O(N^2)\n\/\/ Space: O(N)\n\nclass Solution {\npublic:\n \/**\n * @param A an integer array\n * @return a long integer\n *\/\n long long permutationIndexII(vector<int>& A) {\n long long index = 1;\n \/\/ Position 1 is paired with factor 0 and so is skipped.\n int position = 2;\n long long factor = 1;\n map<int, int> number_to_count;\n ++number_to_count[A.back()];\n for (int i = static_cast<int>(A.size()) - 2; i >= 0; --i) {\n ++number_to_count[A[i]];\n for (const auto& kvp : number_to_count) {\n if (kvp.first >= A[i]) {\n break;\n } \n index += factor * kvp.second \/ number_to_count[A[i]];\n }\n factor = factor * position \/ number_to_count[A[i]];\n ++position;\n }\n return index;\n }\n};\n\n\/\/ Time: O(N^2)\n\/\/ Space: O(N)\nclass Solution2 {\npublic:\n \/**\n * @param A an integer array\n * @return a long integer\n *\/\n long long permutationIndexII(vector<int>& A) {\n long long index = 1;\n \/\/ Position 1 is paired with factor 0 and so is skipped.\n int position = 2;\n long long factor = 1;\n unordered_map<int, int> number_to_count;\n ++number_to_count[A.back()];\n for (int i = static_cast<int>(A.size()) - 2; i >= 0; --i) {\n unordered_map<int, int> successor_to_count;\n ++number_to_count[A[i]];\n for (int j = i + 1; j < A.size(); ++j) {\n if (A[i] > A[j]) {\n ++successor_to_count[A[j]];\n }\n }\n for (const auto& kvp : successor_to_count) {\n index += factor * kvp.second \/ number_to_count[A[i]];\n }\n factor = factor * position \/ number_to_count[A[i]];\n ++position;\n }\n return index;\n }\n};\n\n\/\/ Time: O(N^3)\n\/\/ Space: O(N)\nclass Solution3 {\npublic:\n \/**\n * @param A an integer array\n * @return a long integer\n *\/\n long long permutationIndexII(vector<int>& A) {\n long long index = 1;\n unordered_map<int, int> number_to_count;\n ++number_to_count[A.back()];\n for (int i = static_cast<int>(A.size()) - 2; i >= 0; --i) {\n unordered_map<int, int> successor_to_count;\n ++number_to_count[A[i]];\n for (int j = i + 1; j < A.size(); ++j) {\n if (A[i] > A[j]) {\n ++successor_to_count[A[j]];\n }\n }\n for (const auto& kvp : successor_to_count) {\n --number_to_count[kvp.first];\n index += combination(number_to_count);\n ++number_to_count[kvp.first];\n }\n }\n return index;\n }\n\n long long combination(const unordered_map<int, int>& number_to_count) {\n int n = 0;\n for (const auto& kvp : number_to_count) {\n n += kvp.second;\n }\n long long count = 1;\n for (const auto& kvp : number_to_count) {\n \/\/ C(n, k) = (n) \/ 1 * (n - 1) \/ 2 ... * (n - k + 1) \/ k\n for (int i = 1; i <= kvp.second; ++i, --n) {\n count = count * n \/ i;\n }\n }\n\n return count;\n }\n};\n<commit_msg>Update permutation-index-ii.cpp<commit_after>\/\/ Time: O(n^2)\n\/\/ Space: O(n)\n\nclass Solution {\npublic:\n \/**\n * @param A an integer array\n * @return a long integer\n *\/\n long long permutationIndexII(vector<int>& A) {\n long long index = 1;\n \/\/ Position 1 is paired with factor 0 and so is skipped.\n int position = 2;\n long long factor = 1;\n map<int, int> number_to_count;\n ++number_to_count[A.back()];\n for (int i = static_cast<int>(A.size()) - 2; i >= 0; --i) {\n ++number_to_count[A[i]];\n for (const auto& kvp : number_to_count) {\n if (kvp.first >= A[i]) {\n break;\n } \n index += factor * kvp.second \/ number_to_count[A[i]];\n }\n factor = factor * position \/ number_to_count[A[i]];\n ++position;\n }\n return index;\n }\n};\n\n\/\/ Time: O(n^2)\n\/\/ Space: O(n)\nclass Solution2 {\npublic:\n \/**\n * @param A an integer array\n * @return a long integer\n *\/\n long long permutationIndexII(vector<int>& A) {\n long long index = 1;\n \/\/ Position 1 is paired with factor 0 and so is skipped.\n int position = 2;\n long long factor = 1;\n unordered_map<int, int> number_to_count;\n ++number_to_count[A.back()];\n for (int i = static_cast<int>(A.size()) - 2; i >= 0; --i) {\n unordered_map<int, int> successor_to_count;\n ++number_to_count[A[i]];\n for (int j = i + 1; j < A.size(); ++j) {\n if (A[i] > A[j]) {\n ++successor_to_count[A[j]];\n }\n }\n for (const auto& kvp : successor_to_count) {\n index += factor * kvp.second \/ number_to_count[A[i]];\n }\n factor = factor * position \/ number_to_count[A[i]];\n ++position;\n }\n return index;\n }\n};\n\n\/\/ Time: O(n^3)\n\/\/ Space: O(n)\nclass Solution3 {\npublic:\n \/**\n * @param A an integer array\n * @return a long integer\n *\/\n long long permutationIndexII(vector<int>& A) {\n long long index = 1;\n unordered_map<int, int> number_to_count;\n ++number_to_count[A.back()];\n for (int i = static_cast<int>(A.size()) - 2; i >= 0; --i) {\n unordered_map<int, int> successor_to_count;\n ++number_to_count[A[i]];\n for (int j = i + 1; j < A.size(); ++j) {\n if (A[i] > A[j]) {\n ++successor_to_count[A[j]];\n }\n }\n for (const auto& kvp : successor_to_count) {\n --number_to_count[kvp.first];\n index += combination(number_to_count);\n ++number_to_count[kvp.first];\n }\n }\n return index;\n }\n\n long long combination(const unordered_map<int, int>& number_to_count) {\n int n = 0;\n for (const auto& kvp : number_to_count) {\n n += kvp.second;\n }\n long long count = 1;\n for (const auto& kvp : number_to_count) {\n \/\/ C(n, k) = (n) \/ 1 * (n - 1) \/ 2 ... * (n - k + 1) \/ k\n for (int i = 1; i <= kvp.second; ++i, --n) {\n count = count * n \/ i;\n }\n }\n\n return count;\n }\n};\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (C) 2003 Unai Garro <ugarro@users.sourceforge.net>\n *\/\n\n#include \"pref.h\"\n#include \"krecipes.h\"\n#include \"krecipesview.h\"\n#include \"dialogs\/recipeinputdialog.h\"\n#include \"dialogs\/selectrecipedialog.h\"\n#include \"dialogs\/ingredientsdialog.h\"\n#include \"dialogs\/propertiesdialog.h\"\n#include \"dialogs\/shoppinglistdialog.h\"\n#include \"dialogs\/categorieseditordialog.h\"\n#include \"dialogs\/authorsdialog.h\"\n#include \"dialogs\/unitsdialog.h\"\n\n#include \"gui\/pagesetupdialog.h\"\n\n#include \"importers\/kreimporter.h\"\n#include \"importers\/mmfimporter.h\"\n#include \"importers\/mx2importer.h\"\n#include \"importers\/mxpimporter.h\"\n#include \"importers\/nycgenericimporter.h\"\n#include \"importers\/recipemlimporter.h\"\n\n#include \"recipe.h\"\n#include \"DBBackend\/recipedb.h\"\n\n#include <qdragobject.h>\n#include <kprinter.h>\n#include <qpainter.h>\n#include <qpaintdevicemetrics.h>\n#include <qmessagebox.h>\n\n#include <kprogress.h>\n#include <kmessagebox.h>\n#include <kglobal.h>\n#include <klocale.h>\n#include <kiconloader.h>\n#include <kmenubar.h>\n#include <kstatusbar.h>\n#include <kkeydialog.h>\n#include <kaccel.h>\n#include <kio\/netaccess.h>\n#include <kfiledialog.h>\n#include <kconfig.h>\n\n#include <kedittoolbar.h>\n#include <kstdaccel.h>\n#include <kaction.h>\n#include <kstdaction.h>\n\/\/Settings headers\n#include <kdeversion.h>\n#if defined(KDE_MAKE_VERSION)\n # if KDE_VERSION > KDE_MAKE_VERSION(3,1,4)\n #include <kautoconfigdialog.h>\n # endif\n#endif\n\n#include \"serverprefs.h\"\n#include \"unitsprefs.h\"\n#include \"importprefs.h\"\n\nKrecipes::Krecipes()\n : KMainWindow( 0, \"Krecipes\" ),\n m_view(new KrecipesView(this)),\n m_printer(0)\n{\n\n\n \/\/ accept dnd\n setAcceptDrops(true);\n\n \/\/ tell the KMainWindow that this is indeed the main widget\n setCentralWidget(m_view);\n\n \/\/ then, setup our actions\n setupActions();\n\n \/\/ and a status bar\n statusBar()->show();\n\n \/\/ apply the saved mainwindow settings, if any, and ask the mainwindow\n \/\/ to automatically save settings if changed: window size, toolbar\n \/\/ position, icon size, etc.\n setAutoSaveSettings();\n\n\n\n \/\/ Resize if the window is too small so the buttons are shown\n QSize wsize=size();\n if (wsize.width()<640)\n \t{\n\twsize.setWidth(640);\n\tresize(wsize);\n\t}\n\n \/\/ allow the view to change the statusbar and caption\n connect(m_view, SIGNAL(signalChangeStatusbar(const QString&)),\n this, SLOT(changeStatusbar(const QString&)));\n connect(m_view, SIGNAL(signalChangeCaption(const QString&)),\n this, SLOT(changeCaption(const QString&)));\n\n \/\/ Enable\/Disable the Save Button (Initialize disabled, and connect signal)\n\n connect(this->m_view, SIGNAL(enableSaveOption(bool)), this, SLOT(enableSaveOption(bool)));\n enableSaveOption(false); \/\/ Disables saving initially\n\n \/\/ Enable\/Disable the SaveAs Button (Initialize disabled, and connect signal)\n\n connect(this->m_view->selectPanel, SIGNAL(recipeSelected(bool)), saveAsAction, SLOT(setEnabled(bool)));\n\n parsing_file_dlg = new KDialog(this,\"parsing_file_dlg\",true,Qt::WX11BypassWM);\n QLabel *parsing_file_dlg_label = new QLabel(i18n(\"Gathering recipe data from file.\\nPlease wait...\"),parsing_file_dlg);\n parsing_file_dlg_label->setFrameStyle( QFrame::Box | QFrame::Raised );\n (new QVBoxLayout(parsing_file_dlg))->addWidget( parsing_file_dlg_label );\n parsing_file_dlg->adjustSize();\n \/\/parsing_file_dlg->setFixedSize(parsing_file_dlg->size());\n}\n\nKrecipes::~Krecipes()\n{\n}\n\n\nvoid Krecipes::setupActions()\n{\n KStdAction::openNew(this, SLOT(fileNew()), actionCollection());\n KStdAction::open(this, SLOT(fileOpen()), actionCollection());\n saveAction=KStdAction::save(this, SLOT(fileSave()), actionCollection());\n saveAsAction=KStdAction::saveAs(this, SLOT(fileSaveAs()), actionCollection());\n saveAsAction->setEnabled(false);\n KStdAction::print(this, SLOT(filePrint()), actionCollection());\n KStdAction::quit(kapp, SLOT(quit()), actionCollection());\n\n m_toolbarAction = KStdAction::showToolbar(this, SLOT(optionsShowToolbar()), actionCollection());\n m_statusbarAction = KStdAction::showStatusbar(this, SLOT(optionsShowStatusbar()), actionCollection());\n\n KStdAction::keyBindings(this, SLOT(optionsConfigureKeys()), actionCollection());\n KStdAction::configureToolbars(this, SLOT(optionsConfigureToolbars()), actionCollection());\n KStdAction::preferences(this, SLOT(optionsPreferences()), actionCollection());\n\n (void)new KAction(i18n(\"Import...\"), CTRL+Key_I,\n this, SLOT(import()),\n actionCollection(), \"import_action\");\n\n (void)new KAction(i18n(\"Page Setup...\"), 0,\n this, SLOT(pageSetupSlot()),\n actionCollection(), \"page_setup_action\");\n\n createGUI();\n}\n\nvoid Krecipes::saveProperties(KConfig *)\n{\n \/\/ the 'config' object points to the session managed\n \/\/ config file. anything you write here will be available\n \/\/ later when this app is restored\n\n \/\/if (!m_view->currentURL().isNull())\n \/\/ config->writeEntry(\"lastURL\", m_view->currentURL());\n}\n\nvoid Krecipes::readProperties(KConfig *)\n{\n \/\/ the 'config' object points to the session managed\n \/\/ config file. this function is automatically called whenever\n \/\/ the app is being restored. read in here whatever you wrote\n \/\/ in 'saveProperties'\n\n \/\/QString url = config->readEntry(\"lastURL\");\n\n \/\/if (!url.isNull())\n \/\/ m_view->openURL(KURL(url));\n}\n\nvoid Krecipes::dragEnterEvent(QDragEnterEvent *event)\n{\n \/\/ accept uri drops only\n event->accept(QUriDrag::canDecode(event));\n}\n\n\nvoid Krecipes::fileNew()\n{\n\n \/\/ Create a new element (Element depends on active panel. New recipe by default)\n m_view->createNewElement();\n}\n\nvoid Krecipes::fileOpen()\n{\n \/\/ this slot is called whenever the File->Open menu is selected,\n \/\/ the Open shortcut is pressed (usually CTRL+O) or the Open toolbar\n \/\/ button is clicked\n\/*\n \/\/ this brings up the generic open dialog\n KURL url = KURLRequesterDlg::getURL(QString::null, this, i18n(\"Open Location\") );\n*\/\n \/\/ standard filedialog\n \/*KURL url = KFileDialog::getOpenURL(QString::null, QString::null, this, i18n(\"Open Location\"));\n if (!url.isEmpty())\n m_view->openURL(url);*\/\n}\n\nvoid Krecipes::fileSave()\n{\n \/\/ this slot is called whenever the File->Save menu is selected,\n \/\/ the Save shortcut is pressed (usually CTRL+S) or the Save toolbar\n \/\/ button is clicked\nm_view->save();\n}\n\nvoid Krecipes::fileSaveAs()\n{\n \/\/ this slot is called whenever the File->Save As menu is selected,\n\tm_view->exportRecipe();\n}\n\nvoid Krecipes::filePrint()\n{\n\tm_view->print();\n}\n\nvoid Krecipes::import()\n{\n\tKFileDialog file_dialog( QString::null,\n\t \"*.kre *.kreml|Krecipes (*.kre, *.kreml)\\n\"\n\t \"*.mx2|MasterCook (*.mx2)\\n\"\n\t \"*.mxp *.txt|MasterCook Export (*.mxp, *.txt)\\n\"\n\t \"*.mmf *.txt|Meal-Master Format (*.mmf, *.txt)\\n\"\n\t \"*.txt|\\\"Now You're Cooking\\\" Generic Export (*.txt)\\n\"\n\t \"*.xml *.recipeml|RecipeML (*.xml, *.recipeml)\",\n\t this,\n\t \"file_dialog\",\n\t true\n\t);\n\tfile_dialog.setMode( KFile::Files );\n\n\tif ( file_dialog.exec() == KFileDialog::Accepted )\n\t{\n\t\tQStringList warnings_list;\n\n\t\tQString selected_filter = file_dialog.currentFilter();\n\t\tQStringList files = file_dialog.selectedFiles();\n\n\t\tfor ( QStringList::const_iterator it = files.begin(); it != files.end(); ++it )\n\t\t{\n\t\t\tparsing_file_dlg->show();\n\n\t\t\tBaseImporter *importer;\n\t\t\tif ( selected_filter == \"*.mxp *.txt\" )\n\t\t\t\timporter = new MXPImporter( *it );\n\t\t\telse if ( selected_filter == \"*.mmf *.txt\" )\n\t\t\t\timporter = new MMFImporter( *it );\n\t\t\telse if ( selected_filter == \"*.txt\" )\n\t\t\t\timporter = new NYCGenericImporter( *it );\n\t\t\telse if ( selected_filter == \"*.mx2\" )\n\t\t\t\timporter = new MX2Importer( *it );\n\t\t\telse if ( selected_filter == \"*.kre *.kreml\" )\n\t\t\t\timporter = new KreImporter( *it );\n\t\t\telse if ( selected_filter == \"*.xml *.recipeml\" )\n\t\t\t\timporter = new RecipeMLImporter( *it );\n\t\t\telse\n\t\t\t{\n\t\t\t\tKMessageBox::sorry( this,\n\t\t\t\t QString(i18n(\"Filter \\\"%1\\\" not recognized.\\n\"\n\t\t\t\t \"Please select one of the provided filters.\")).arg(selected_filter),\n\t\t\t\t i18n(\"Unrecognized Filter\")\n\t\t\t\t);\n\t\t\t\tparsing_file_dlg->hide();\n\t\t\t\timport(); \/\/let's try again :)\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tparsing_file_dlg->hide();\n\n\t\t\tQString error = importer->getErrorMsg();\n\t\t\tif ( !error.isNull() )\n\t\t\t\tKMessageBox::error( this, QString(i18n(\"Error importing file %1\\n%2\")).arg(*it).arg(error) );\n\t\t\telse\n\t\t\t\tm_view->import( *importer );\n\n\t\t\tif ( importer->getWarningMsgs().count() > 0 )\n\t\t\t{\n\t\t\t\twarnings_list += QString(i18n(\"The file \\\"%1\\\" generated the following warnings:\")).arg(*it);\n\t\t\t\twarnings_list += importer->getWarningMsgs();\n\t\t\t}\n\n\t\t\tdelete importer;\n\t\t}\n\n\t\tif ( warnings_list.count() > 0 )\n\t\t{\n\t\t\twarnings_list.prepend(i18n(\"NOTE: We recommend that all recipes generating warnings be checked to ensure that they were properly imported, and no loss of recipe data has occured.\"));\n\n\t\t\tKTextEdit *warningEdit = new KTextEdit( this );\n\t\t\twarningEdit->setText( warnings_list.join(\"\\n\\n\") );\n\t\t\twarningEdit->setReadOnly(true);\n\n\t\t\tKDialogBase showWarningsDlg( KDialogBase::Swallow, i18n(\"Import warnings\"), KDialogBase::Ok, KDialogBase::Default, this );\n\t\t\tshowWarningsDlg.setMainWidget( warningEdit ); \/\/KDialogBase will delete warningEdit for us\n\t\t\tshowWarningsDlg.resize( QSize(550,250) );\n\t\t\tshowWarningsDlg.exec();\n\t\t}\n\n\t\t\/\/TODO: to just reload the active panel would be preferable\n\t\tm_view->selectPanel->reload();\n\t\tm_view->ingredientsPanel->reload();\n\t\tm_view->propertiesPanel->reload();\n\t\tm_view->unitsPanel->reload();\n\t\tm_view->shoppingListPanel->reload();\n\t\tm_view->categoriesPanel->reload();\n\t\tm_view->authorsPanel->reload();\n\t}\n}\n\nvoid Krecipes::pageSetupSlot()\n{\n\tRecipe recipe;\n\tm_view->selectPanel->getCurrentRecipe(&recipe);\n\n\tPageSetupDialog *page_setup = new PageSetupDialog(this,recipe);\n\tpage_setup->exec();\n\n\tdelete page_setup;\n}\n\n\/\/return true to close app\nbool Krecipes::queryClose()\n{\n\tif ( !m_view->inputPanel->everythingSaved() )\n\t{\n\t\tswitch( KMessageBox::questionYesNoCancel( this,\n\t\t i18n(\"A recipe contains unsaved changes.\\n\"\n\t\t \"Do you want to save the changes before exiting?\"),\n\t\t i18n(\"Unsaved Changes\") ) )\n\t\t{\n\t\tcase KMessageBox::Yes: m_view->save();\n\t\tcase KMessageBox::No: return true;\n\t\tcase KMessageBox::Cancel: return false;\n\t\tdefault: return true;\n\t\t}\n\t}\n\telse\n\t\treturn true;\n}\n\nvoid Krecipes::optionsShowToolbar()\n{\n \/\/ this is all very cut and paste code for showing\/hiding the\n \/\/ toolbar\n if (m_toolbarAction->isChecked())\n toolBar()->show();\n else\n toolBar()->hide();\n}\n\nvoid Krecipes::optionsShowStatusbar()\n{\n \/\/ this is all very cut and paste code for showing\/hiding the\n \/\/ statusbar\n if (m_statusbarAction->isChecked())\n statusBar()->show();\n else\n statusBar()->hide();\n}\n\nvoid Krecipes::optionsConfigureKeys()\n{\n#if defined(KDE_MAKE_VERSION)\n# if KDE_VERSION > KDE_MAKE_VERSION(3,1,4)\n \/\/ for KDE 3.2: KKeyDialog::configureKeys is deprecated\n KKeyDialog::configure(actionCollection(), this, true);\n #else\n KKeyDialog::configureKeys(actionCollection(), \"krecipesui.rc\");\n#endif\n #else\n KKeyDialog::configureKeys(actionCollection(), \"krecipesui.rc\");\n#endif\n}\n\nvoid Krecipes::optionsConfigureToolbars()\n{\n \/\/ use the standard toolbar editor\n#if defined(KDE_MAKE_VERSION)\n# if KDE_VERSION >= KDE_MAKE_VERSION(3,1,0)\n saveMainWindowSettings(KGlobal::config(), autoSaveGroup());\n# else\n saveMainWindowSettings(KGlobal::config());\n# endif\n#else\n saveMainWindowSettings(KGlobal::config());\n#endif\n KEditToolbar dlg(actionCollection());\n connect(&dlg, SIGNAL(newToolbarConfig()), this, SLOT(newToolbarConfig()));\n dlg.exec();\n}\n\nvoid Krecipes::newToolbarConfig()\n{\n \/\/ this slot is called when user clicks \"Ok\" or \"Apply\" in the toolbar editor.\n \/\/ recreate our GUI, and re-apply the settings (e.g. \"text under icons\", etc.)\n createGUI();\n\n#if defined(KDE_MAKE_VERSION)\n# if KDE_VERSION >= KDE_MAKE_VERSION(3,1,0)\n applyMainWindowSettings(KGlobal::config(), autoSaveGroup());\n# else\n applyMainWindowSettings(KGlobal::config());\n# endif\n#else\n applyMainWindowSettings(KGlobal::config());\n#endif\n}\n\nvoid Krecipes::optionsPreferences()\n{\n#if defined(KDE_MAKE_VERSION)\n# if KDE_VERSION > KDE_MAKE_VERSION(3,1,4)\n if(KAutoConfigDialog::showDialog(\"settings\"))\n\t\treturn;\n\n KAutoConfigDialog *dialog = new KAutoConfigDialog(this, \"settings\");\n dialog->addPage(new serverprefs(0, \"serverprefs\"), i18n(\"Server Settings\"), \"Server\", \"identity\", i18n(\"Database Server Options\"));\n dialog->addPage(new unitsprefs(0, \"NumberFormat\"), i18n(\"Units\"), \"Units\", \"frac\", i18n(\"Customize Units\"));\n dialog->addPage(new importprefs(0, \"Import\"), i18n(\"Units\"), \"Import\", \"redo\", i18n(\"Recipe Import Options\"));\n \/\/connect(dialog, SIGNAL(settingsChanged()), this, SLOT(loadSettings()));\n dialog->show();\n# else\n \/\/ popup some sort of preference dialog, here\n KrecipesPreferences dlg(this);\n if (dlg.exec())\n {}\n# endif\n#else\n \/\/ popup some sort of preference dialog, here\n KrecipesPreferences dlg(this);\n if (dlg.exec())\n {}\n#endif\n}\n\nvoid Krecipes::changeStatusbar(const QString& text)\n{\n \/\/ display the text on the statusbar\n statusBar()->message(text);\n}\n\nvoid Krecipes::changeCaption(const QString& text)\n{\n \/\/ display the text on the caption\n setCaption(text);\n}\nvoid Krecipes::enableSaveOption(bool en)\n{\nsaveAction->setEnabled(en);\n}\n\n#include \"krecipes.moc\"\n<commit_msg>use a better method to filter versions. 3.1.5 will not have KAutoConfigDialog stuff in....<commit_after>\/*\n * Copyright (C) 2003 Unai Garro <ugarro@users.sourceforge.net>\n *\/\n\n#include \"pref.h\"\n#include \"krecipes.h\"\n#include \"krecipesview.h\"\n#include \"dialogs\/recipeinputdialog.h\"\n#include \"dialogs\/selectrecipedialog.h\"\n#include \"dialogs\/ingredientsdialog.h\"\n#include \"dialogs\/propertiesdialog.h\"\n#include \"dialogs\/shoppinglistdialog.h\"\n#include \"dialogs\/categorieseditordialog.h\"\n#include \"dialogs\/authorsdialog.h\"\n#include \"dialogs\/unitsdialog.h\"\n\n#include \"gui\/pagesetupdialog.h\"\n\n#include \"importers\/kreimporter.h\"\n#include \"importers\/mmfimporter.h\"\n#include \"importers\/mx2importer.h\"\n#include \"importers\/mxpimporter.h\"\n#include \"importers\/nycgenericimporter.h\"\n#include \"importers\/recipemlimporter.h\"\n\n#include \"recipe.h\"\n#include \"DBBackend\/recipedb.h\"\n\n#include <qdragobject.h>\n#include <kprinter.h>\n#include <qpainter.h>\n#include <qpaintdevicemetrics.h>\n#include <qmessagebox.h>\n\n#include <kprogress.h>\n#include <kmessagebox.h>\n#include <kglobal.h>\n#include <klocale.h>\n#include <kiconloader.h>\n#include <kmenubar.h>\n#include <kstatusbar.h>\n#include <kkeydialog.h>\n#include <kaccel.h>\n#include <kio\/netaccess.h>\n#include <kfiledialog.h>\n#include <kconfig.h>\n\n#include <kedittoolbar.h>\n#include <kstdaccel.h>\n#include <kaction.h>\n#include <kstdaction.h>\n\/\/Settings headers\n#include <kdeversion.h>\n#if defined(KDE_MAKE_VERSION)\n # if KDE_VERSION > KDE_MAKE_VERSION(3,1,4)\n #include <kautoconfigdialog.h>\n # endif\n#endif\n\n#include \"serverprefs.h\"\n#include \"unitsprefs.h\"\n#include \"importprefs.h\"\n\nKrecipes::Krecipes()\n : KMainWindow( 0, \"Krecipes\" ),\n m_view(new KrecipesView(this)),\n m_printer(0)\n{\n\n\n \/\/ accept dnd\n setAcceptDrops(true);\n\n \/\/ tell the KMainWindow that this is indeed the main widget\n setCentralWidget(m_view);\n\n \/\/ then, setup our actions\n setupActions();\n\n \/\/ and a status bar\n statusBar()->show();\n\n \/\/ apply the saved mainwindow settings, if any, and ask the mainwindow\n \/\/ to automatically save settings if changed: window size, toolbar\n \/\/ position, icon size, etc.\n setAutoSaveSettings();\n\n\n\n \/\/ Resize if the window is too small so the buttons are shown\n QSize wsize=size();\n if (wsize.width()<640)\n \t{\n\twsize.setWidth(640);\n\tresize(wsize);\n\t}\n\n \/\/ allow the view to change the statusbar and caption\n connect(m_view, SIGNAL(signalChangeStatusbar(const QString&)),\n this, SLOT(changeStatusbar(const QString&)));\n connect(m_view, SIGNAL(signalChangeCaption(const QString&)),\n this, SLOT(changeCaption(const QString&)));\n\n \/\/ Enable\/Disable the Save Button (Initialize disabled, and connect signal)\n\n connect(this->m_view, SIGNAL(enableSaveOption(bool)), this, SLOT(enableSaveOption(bool)));\n enableSaveOption(false); \/\/ Disables saving initially\n\n \/\/ Enable\/Disable the SaveAs Button (Initialize disabled, and connect signal)\n\n connect(this->m_view->selectPanel, SIGNAL(recipeSelected(bool)), saveAsAction, SLOT(setEnabled(bool)));\n\n parsing_file_dlg = new KDialog(this,\"parsing_file_dlg\",true,Qt::WX11BypassWM);\n QLabel *parsing_file_dlg_label = new QLabel(i18n(\"Gathering recipe data from file.\\nPlease wait...\"),parsing_file_dlg);\n parsing_file_dlg_label->setFrameStyle( QFrame::Box | QFrame::Raised );\n (new QVBoxLayout(parsing_file_dlg))->addWidget( parsing_file_dlg_label );\n parsing_file_dlg->adjustSize();\n \/\/parsing_file_dlg->setFixedSize(parsing_file_dlg->size());\n}\n\nKrecipes::~Krecipes()\n{\n}\n\n\nvoid Krecipes::setupActions()\n{\n KStdAction::openNew(this, SLOT(fileNew()), actionCollection());\n KStdAction::open(this, SLOT(fileOpen()), actionCollection());\n saveAction=KStdAction::save(this, SLOT(fileSave()), actionCollection());\n saveAsAction=KStdAction::saveAs(this, SLOT(fileSaveAs()), actionCollection());\n saveAsAction->setEnabled(false);\n KStdAction::print(this, SLOT(filePrint()), actionCollection());\n KStdAction::quit(kapp, SLOT(quit()), actionCollection());\n\n m_toolbarAction = KStdAction::showToolbar(this, SLOT(optionsShowToolbar()), actionCollection());\n m_statusbarAction = KStdAction::showStatusbar(this, SLOT(optionsShowStatusbar()), actionCollection());\n\n KStdAction::keyBindings(this, SLOT(optionsConfigureKeys()), actionCollection());\n KStdAction::configureToolbars(this, SLOT(optionsConfigureToolbars()), actionCollection());\n KStdAction::preferences(this, SLOT(optionsPreferences()), actionCollection());\n\n (void)new KAction(i18n(\"Import...\"), CTRL+Key_I,\n this, SLOT(import()),\n actionCollection(), \"import_action\");\n\n (void)new KAction(i18n(\"Page Setup...\"), 0,\n this, SLOT(pageSetupSlot()),\n actionCollection(), \"page_setup_action\");\n\n createGUI();\n}\n\nvoid Krecipes::saveProperties(KConfig *)\n{\n \/\/ the 'config' object points to the session managed\n \/\/ config file. anything you write here will be available\n \/\/ later when this app is restored\n\n \/\/if (!m_view->currentURL().isNull())\n \/\/ config->writeEntry(\"lastURL\", m_view->currentURL());\n}\n\nvoid Krecipes::readProperties(KConfig *)\n{\n \/\/ the 'config' object points to the session managed\n \/\/ config file. this function is automatically called whenever\n \/\/ the app is being restored. read in here whatever you wrote\n \/\/ in 'saveProperties'\n\n \/\/QString url = config->readEntry(\"lastURL\");\n\n \/\/if (!url.isNull())\n \/\/ m_view->openURL(KURL(url));\n}\n\nvoid Krecipes::dragEnterEvent(QDragEnterEvent *event)\n{\n \/\/ accept uri drops only\n event->accept(QUriDrag::canDecode(event));\n}\n\n\nvoid Krecipes::fileNew()\n{\n\n \/\/ Create a new element (Element depends on active panel. New recipe by default)\n m_view->createNewElement();\n}\n\nvoid Krecipes::fileOpen()\n{\n \/\/ this slot is called whenever the File->Open menu is selected,\n \/\/ the Open shortcut is pressed (usually CTRL+O) or the Open toolbar\n \/\/ button is clicked\n\/*\n \/\/ this brings up the generic open dialog\n KURL url = KURLRequesterDlg::getURL(QString::null, this, i18n(\"Open Location\") );\n*\/\n \/\/ standard filedialog\n \/*KURL url = KFileDialog::getOpenURL(QString::null, QString::null, this, i18n(\"Open Location\"));\n if (!url.isEmpty())\n m_view->openURL(url);*\/\n}\n\nvoid Krecipes::fileSave()\n{\n \/\/ this slot is called whenever the File->Save menu is selected,\n \/\/ the Save shortcut is pressed (usually CTRL+S) or the Save toolbar\n \/\/ button is clicked\nm_view->save();\n}\n\nvoid Krecipes::fileSaveAs()\n{\n \/\/ this slot is called whenever the File->Save As menu is selected,\n\tm_view->exportRecipe();\n}\n\nvoid Krecipes::filePrint()\n{\n\tm_view->print();\n}\n\nvoid Krecipes::import()\n{\n\tKFileDialog file_dialog( QString::null,\n\t \"*.kre *.kreml|Krecipes (*.kre, *.kreml)\\n\"\n\t \"*.mx2|MasterCook (*.mx2)\\n\"\n\t \"*.mxp *.txt|MasterCook Export (*.mxp, *.txt)\\n\"\n\t \"*.mmf *.txt|Meal-Master Format (*.mmf, *.txt)\\n\"\n\t \"*.txt|\\\"Now You're Cooking\\\" Generic Export (*.txt)\\n\"\n\t \"*.xml *.recipeml|RecipeML (*.xml, *.recipeml)\",\n\t this,\n\t \"file_dialog\",\n\t true\n\t);\n\tfile_dialog.setMode( KFile::Files );\n\n\tif ( file_dialog.exec() == KFileDialog::Accepted )\n\t{\n\t\tQStringList warnings_list;\n\n\t\tQString selected_filter = file_dialog.currentFilter();\n\t\tQStringList files = file_dialog.selectedFiles();\n\n\t\tfor ( QStringList::const_iterator it = files.begin(); it != files.end(); ++it )\n\t\t{\n\t\t\tparsing_file_dlg->show();\n\n\t\t\tBaseImporter *importer;\n\t\t\tif ( selected_filter == \"*.mxp *.txt\" )\n\t\t\t\timporter = new MXPImporter( *it );\n\t\t\telse if ( selected_filter == \"*.mmf *.txt\" )\n\t\t\t\timporter = new MMFImporter( *it );\n\t\t\telse if ( selected_filter == \"*.txt\" )\n\t\t\t\timporter = new NYCGenericImporter( *it );\n\t\t\telse if ( selected_filter == \"*.mx2\" )\n\t\t\t\timporter = new MX2Importer( *it );\n\t\t\telse if ( selected_filter == \"*.kre *.kreml\" )\n\t\t\t\timporter = new KreImporter( *it );\n\t\t\telse if ( selected_filter == \"*.xml *.recipeml\" )\n\t\t\t\timporter = new RecipeMLImporter( *it );\n\t\t\telse\n\t\t\t{\n\t\t\t\tKMessageBox::sorry( this,\n\t\t\t\t QString(i18n(\"Filter \\\"%1\\\" not recognized.\\n\"\n\t\t\t\t \"Please select one of the provided filters.\")).arg(selected_filter),\n\t\t\t\t i18n(\"Unrecognized Filter\")\n\t\t\t\t);\n\t\t\t\tparsing_file_dlg->hide();\n\t\t\t\timport(); \/\/let's try again :)\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tparsing_file_dlg->hide();\n\n\t\t\tQString error = importer->getErrorMsg();\n\t\t\tif ( !error.isNull() )\n\t\t\t\tKMessageBox::error( this, QString(i18n(\"Error importing file %1\\n%2\")).arg(*it).arg(error) );\n\t\t\telse\n\t\t\t\tm_view->import( *importer );\n\n\t\t\tif ( importer->getWarningMsgs().count() > 0 )\n\t\t\t{\n\t\t\t\twarnings_list += QString(i18n(\"The file \\\"%1\\\" generated the following warnings:\")).arg(*it);\n\t\t\t\twarnings_list += importer->getWarningMsgs();\n\t\t\t}\n\n\t\t\tdelete importer;\n\t\t}\n\n\t\tif ( warnings_list.count() > 0 )\n\t\t{\n\t\t\twarnings_list.prepend(i18n(\"NOTE: We recommend that all recipes generating warnings be checked to ensure that they were properly imported, and no loss of recipe data has occured.\"));\n\n\t\t\tKTextEdit *warningEdit = new KTextEdit( this );\n\t\t\twarningEdit->setText( warnings_list.join(\"\\n\\n\") );\n\t\t\twarningEdit->setReadOnly(true);\n\n\t\t\tKDialogBase showWarningsDlg( KDialogBase::Swallow, i18n(\"Import warnings\"), KDialogBase::Ok, KDialogBase::Default, this );\n\t\t\tshowWarningsDlg.setMainWidget( warningEdit ); \/\/KDialogBase will delete warningEdit for us\n\t\t\tshowWarningsDlg.resize( QSize(550,250) );\n\t\t\tshowWarningsDlg.exec();\n\t\t}\n\n\t\t\/\/TODO: to just reload the active panel would be preferable\n\t\tm_view->selectPanel->reload();\n\t\tm_view->ingredientsPanel->reload();\n\t\tm_view->propertiesPanel->reload();\n\t\tm_view->unitsPanel->reload();\n\t\tm_view->shoppingListPanel->reload();\n\t\tm_view->categoriesPanel->reload();\n\t\tm_view->authorsPanel->reload();\n\t}\n}\n\nvoid Krecipes::pageSetupSlot()\n{\n\tRecipe recipe;\n\tm_view->selectPanel->getCurrentRecipe(&recipe);\n\n\tPageSetupDialog *page_setup = new PageSetupDialog(this,recipe);\n\tpage_setup->exec();\n\n\tdelete page_setup;\n}\n\n\/\/return true to close app\nbool Krecipes::queryClose()\n{\n\tif ( !m_view->inputPanel->everythingSaved() )\n\t{\n\t\tswitch( KMessageBox::questionYesNoCancel( this,\n\t\t i18n(\"A recipe contains unsaved changes.\\n\"\n\t\t \"Do you want to save the changes before exiting?\"),\n\t\t i18n(\"Unsaved Changes\") ) )\n\t\t{\n\t\tcase KMessageBox::Yes: m_view->save();\n\t\tcase KMessageBox::No: return true;\n\t\tcase KMessageBox::Cancel: return false;\n\t\tdefault: return true;\n\t\t}\n\t}\n\telse\n\t\treturn true;\n}\n\nvoid Krecipes::optionsShowToolbar()\n{\n \/\/ this is all very cut and paste code for showing\/hiding the\n \/\/ toolbar\n if (m_toolbarAction->isChecked())\n toolBar()->show();\n else\n toolBar()->hide();\n}\n\nvoid Krecipes::optionsShowStatusbar()\n{\n \/\/ this is all very cut and paste code for showing\/hiding the\n \/\/ statusbar\n if (m_statusbarAction->isChecked())\n statusBar()->show();\n else\n statusBar()->hide();\n}\n\nvoid Krecipes::optionsConfigureKeys()\n{\n#if defined(KDE_MAKE_VERSION)\n# if KDE_VERSION > KDE_MAKE_VERSION(3,1,4)\n \/\/ for KDE 3.2: KKeyDialog::configureKeys is deprecated\n KKeyDialog::configure(actionCollection(), this, true);\n #else\n KKeyDialog::configureKeys(actionCollection(), \"krecipesui.rc\");\n#endif\n #else\n KKeyDialog::configureKeys(actionCollection(), \"krecipesui.rc\");\n#endif\n}\n\nvoid Krecipes::optionsConfigureToolbars()\n{\n \/\/ use the standard toolbar editor\n#if defined(KDE_MAKE_VERSION)\n# if KDE_VERSION >= KDE_MAKE_VERSION(3,1,0)\n saveMainWindowSettings(KGlobal::config(), autoSaveGroup());\n# else\n saveMainWindowSettings(KGlobal::config());\n# endif\n#else\n saveMainWindowSettings(KGlobal::config());\n#endif\n KEditToolbar dlg(actionCollection());\n connect(&dlg, SIGNAL(newToolbarConfig()), this, SLOT(newToolbarConfig()));\n dlg.exec();\n}\n\nvoid Krecipes::newToolbarConfig()\n{\n \/\/ this slot is called when user clicks \"Ok\" or \"Apply\" in the toolbar editor.\n \/\/ recreate our GUI, and re-apply the settings (e.g. \"text under icons\", etc.)\n createGUI();\n\n#if defined(KDE_MAKE_VERSION)\n# if KDE_VERSION >= KDE_MAKE_VERSION(3,1,0)\n applyMainWindowSettings(KGlobal::config(), autoSaveGroup());\n# else\n applyMainWindowSettings(KGlobal::config());\n# endif\n#else\n applyMainWindowSettings(KGlobal::config());\n#endif\n}\n\nvoid Krecipes::optionsPreferences()\n{\n\n#if KDE_IS_VERSION(3,1,92 )\n\n if(KAutoConfigDialog::showDialog(\"settings\"))\n\t\treturn;\n\n KAutoConfigDialog *dialog = new KAutoConfigDialog(this, \"settings\");\n dialog->addPage(new serverprefs(0, \"serverprefs\"), i18n(\"Server Settings\"), \"Server\", \"identity\", i18n(\"Database Server Options\"));\n dialog->addPage(new unitsprefs(0, \"NumberFormat\"), i18n(\"Units\"), \"Units\", \"frac\", i18n(\"Customize Units\"));\n dialog->addPage(new importprefs(0, \"Import\"), i18n(\"Units\"), \"Import\", \"redo\", i18n(\"Recipe Import Options\"));\n \/\/connect(dialog, SIGNAL(settingsChanged()), this, SLOT(loadSettings()));\n dialog->show();\n# else\n \/\/ popup some sort of preference dialog, here\n KrecipesPreferences dlg(this);\n if (dlg.exec())\n {}\n# endif\n\n}\n\nvoid Krecipes::changeStatusbar(const QString& text)\n{\n \/\/ display the text on the statusbar\n statusBar()->message(text);\n}\n\nvoid Krecipes::changeCaption(const QString& text)\n{\n \/\/ display the text on the caption\n setCaption(text);\n}\nvoid Krecipes::enableSaveOption(bool en)\n{\nsaveAction->setEnabled(en);\n}\n\n#include \"krecipes.moc\"\n<|endoftext|>"} {"text":"<commit_before>#include <string>\n\n#include \"Option.h\"\n\n#include \"Interpreter.h\"\n\n#include \"FatalErrorCode.h\"\n#include \"ErrorHandler.h\"\n\nnamespace lyrics\n{\n\tusing std::u16string;\n\n\tconst u16string Tokenizer::BREAK = u\"break\";\n\tconst u16string Tokenizer::CASE = u\"case\";\n\tconst u16string Tokenizer::CLASS = u\"class\";\n\tconst u16string Tokenizer::DEF = u\"def\";\n\tconst u16string Tokenizer::DO = u\"do\";\n\tconst u16string Tokenizer::END = u\"end\";\n\tconst u16string Tokenizer::ELSE = u\"else\";\n\tconst u16string Tokenizer::ELSEIF = u\"elseif\";\n\tconst u16string Tokenizer::FALSE = u\"false\";\n\tconst u16string Tokenizer::FOR = u\"for\";\n\tconst u16string Tokenizer::FOREACH = u\"foreach\";\n\tconst u16string Tokenizer::IF = u\"if\";\n\tconst u16string Tokenizer::IMPORT = u\"import\";\n\tconst u16string Tokenizer::IN = u\"in\";\n\tconst u16string Tokenizer::INCLUDE = u\"include\";\n\tconst u16string Tokenizer::NEXT = u\"next\";\n\tconst u16string Tokenizer::NULL_TOKEN = u\"null\";\n\tconst u16string Tokenizer::OUT = u\"out\";\n\tconst u16string Tokenizer::PACKAGE = u\"package\";\n\tconst u16string Tokenizer::PRIVATE = u\"private\";\n\tconst u16string Tokenizer::PROTECTED = u\"protected\";\n\tconst u16string Tokenizer::PUBLIC = u\"public\";\n\tconst u16string Tokenizer::RETURN = u\"return\";\n\tconst u16string Tokenizer::THEN = u\"then\";\n\tconst u16string Tokenizer::THIS = u\"this\";\n\tconst u16string Tokenizer::TRUE = u\"true\";\n\tconst u16string Tokenizer::WHEN = u\"when\";\n\tconst u16string Tokenizer::WHILE = u\"while\";\n\n\tforward_list<Token>::const_iterator Interpreter::mToken;\n\tunordered_map<u16string, Literal> Interpreter::mSymbolTable;\n\n\tconstexpr char ErrorHandler::WARNING[];\n\tconstexpr char ErrorHandler::ERROR[];\n\tconstexpr char ErrorHandler::FATAL_ERROR[];\n}\n\nint main( int argc, char *argv[] )\n{\n\tconst lyrics::Option option = lyrics::Option( argc, argv );\n\n\tif ( option.GetSourceFileName().empty() )\n\t{\n\t\tlyrics::Logger::ErrorHandler( lyrics::FatalErrorCode::NO_INPUT_FILES );\n\t\treturn 0;\n\t}\n\n\tif ( !lyrics::Interpreter::Interpret( option.GetSourceFileName() ) )\n\t{\n\t\t\/\/ TODO:\n\t\treturn 0;\n\t}\n\n\treturn 0;\n}\n<commit_msg>Use ErrorHandler<commit_after>#include <string>\n\n#include \"Option.h\"\n\n#include \"Interpreter.h\"\n\n#include \"FatalErrorCode.h\"\n#include \"ErrorHandler.h\"\n\nnamespace lyrics\n{\n\tusing std::u16string;\n\n\tconst u16string Tokenizer::BREAK = u\"break\";\n\tconst u16string Tokenizer::CASE = u\"case\";\n\tconst u16string Tokenizer::CLASS = u\"class\";\n\tconst u16string Tokenizer::DEF = u\"def\";\n\tconst u16string Tokenizer::DO = u\"do\";\n\tconst u16string Tokenizer::END = u\"end\";\n\tconst u16string Tokenizer::ELSE = u\"else\";\n\tconst u16string Tokenizer::ELSEIF = u\"elseif\";\n\tconst u16string Tokenizer::FALSE = u\"false\";\n\tconst u16string Tokenizer::FOR = u\"for\";\n\tconst u16string Tokenizer::FOREACH = u\"foreach\";\n\tconst u16string Tokenizer::IF = u\"if\";\n\tconst u16string Tokenizer::IMPORT = u\"import\";\n\tconst u16string Tokenizer::IN = u\"in\";\n\tconst u16string Tokenizer::INCLUDE = u\"include\";\n\tconst u16string Tokenizer::NEXT = u\"next\";\n\tconst u16string Tokenizer::NULL_TOKEN = u\"null\";\n\tconst u16string Tokenizer::OUT = u\"out\";\n\tconst u16string Tokenizer::PACKAGE = u\"package\";\n\tconst u16string Tokenizer::PRIVATE = u\"private\";\n\tconst u16string Tokenizer::PROTECTED = u\"protected\";\n\tconst u16string Tokenizer::PUBLIC = u\"public\";\n\tconst u16string Tokenizer::RETURN = u\"return\";\n\tconst u16string Tokenizer::THEN = u\"then\";\n\tconst u16string Tokenizer::THIS = u\"this\";\n\tconst u16string Tokenizer::TRUE = u\"true\";\n\tconst u16string Tokenizer::WHEN = u\"when\";\n\tconst u16string Tokenizer::WHILE = u\"while\";\n\n\tforward_list<Token>::const_iterator Interpreter::mToken;\n\tunordered_map<u16string, Literal> Interpreter::mSymbolTable;\n\n\tconstexpr char ErrorHandler::WARNING[];\n\tconstexpr char ErrorHandler::ERROR[];\n\tconstexpr char ErrorHandler::FATAL_ERROR[];\n}\n\nint main( int argc, char *argv[] )\n{\n\tconst lyrics::Option option = lyrics::Option( argc, argv );\n\n\tif ( option.GetSourceFileName().empty() )\n\t{\n\t\tlyrics::ErrorHandler::FatalError( lyrics::FatalErrorCode::NO_INPUT_FILES );\n\t\treturn 0;\n\t}\n\n\tif ( !lyrics::Interpreter::Interpret( option.GetSourceFileName() ) )\n\t{\n\t\t\/\/ TODO:\n\t\treturn 0;\n\t}\n\n\treturn 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/===-- DWARFASTParserSwift.cpp ---------------------------------*- C++ -*-===\/\/\n\/\/\n\/\/ This source file is part of the Swift.org open source project\n\/\/\n\/\/ Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors\n\/\/ Licensed under Apache License v2.0 with Runtime Library Exception\n\/\/\n\/\/ See https:\/\/swift.org\/LICENSE.txt for license information\n\/\/ See https:\/\/swift.org\/CONTRIBUTORS.txt for the list of Swift project authors\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"DWARFASTParserSwift.h\"\n\n#include \"DWARFASTParserClang.h\"\n#include \"DWARFCompileUnit.h\"\n#include \"DWARFDIE.h\"\n#include \"DWARFDebugInfo.h\"\n#include \"DWARFDefines.h\"\n#include \"SymbolFileDWARF.h\"\n\n#include \"swift\/AST\/ASTContext.h\"\n#include \"swift\/Demangling\/Demangle.h\"\n\n#include \"lldb\/Core\/Module.h\"\n#include \"lldb\/Symbol\/ClangASTContext.h\"\n#include \"lldb\/Symbol\/CompileUnit.h\"\n#include \"lldb\/Symbol\/Function.h\"\n#include \"lldb\/Symbol\/ObjectFile.h\"\n#include \"lldb\/Symbol\/SwiftASTContext.h\"\n#include \"lldb\/Symbol\/SymbolVendor.h\"\n#include \"lldb\/Symbol\/Type.h\"\n#include \"lldb\/Symbol\/TypeMap.h\"\n#include \"lldb\/Target\/SwiftLanguageRuntime.h\"\n#include \"lldb\/Utility\/Log.h\"\n#include \"lldb\/Utility\/Status.h\"\n\nusing namespace lldb;\nusing namespace lldb_private;\n\nDWARFASTParserSwift::DWARFASTParserSwift(SwiftASTContext &ast) : m_ast(ast) {}\n\nDWARFASTParserSwift::~DWARFASTParserSwift() {}\n\nstatic llvm::StringRef GetTypedefName(const DWARFDIE &die) {\n if (die.Tag() != DW_TAG_typedef)\n return {};\n DWARFDIE type_die = die.GetAttributeValueAsReferenceDIE(DW_AT_type);\n if (!type_die.IsValid())\n return {};\n return llvm::StringRef::withNullAsEmpty(type_die.GetName());\n}\n\nlldb::TypeSP DWARFASTParserSwift::ParseTypeFromDWARF(const SymbolContext &sc,\n const DWARFDIE &die,\n Log *log,\n bool *type_is_new_ptr) {\n lldb::TypeSP type_sp;\n CompilerType compiler_type;\n Status error;\n\n Declaration decl;\n ConstString mangled_name;\n ConstString name;\n bool is_clang_type = false;\n llvm::Optional<uint64_t> dwarf_byte_size;\n\n DWARFAttributes attributes;\n const size_t num_attributes = die.GetAttributes(attributes);\n DWARFFormValue type_attr;\n\n if (num_attributes > 0) {\n uint32_t i;\n for (i = 0; i < num_attributes; ++i) {\n const dw_attr_t attr = attributes.AttributeAtIndex(i);\n DWARFFormValue form_value;\n if (attributes.ExtractFormValueAtIndex(i, form_value)) {\n switch (attr) {\n case DW_AT_decl_file:\n decl.SetFile(sc.comp_unit->GetSupportFiles().GetFileSpecAtIndex(\n form_value.Unsigned()));\n break;\n case DW_AT_decl_line:\n decl.SetLine(form_value.Unsigned());\n break;\n case DW_AT_decl_column:\n decl.SetColumn(form_value.Unsigned());\n break;\n case DW_AT_name:\n name.SetCString(form_value.AsCString());\n break;\n case DW_AT_linkage_name:\n case DW_AT_MIPS_linkage_name:\n mangled_name.SetCString(form_value.AsCString());\n break;\n case DW_AT_byte_size:\n dwarf_byte_size = form_value.Unsigned();\n break;\n default:\n break;\n }\n }\n }\n }\n\n if (!mangled_name && name) {\n if (name.GetStringRef().equals(\"$swift.fixedbuffer\")) {\n DWARFDIE type_die =\n die.GetFirstChild().GetAttributeValueAsReferenceDIE(DW_AT_type);\n if (auto wrapped_type =\n ParseTypeFromDWARF(sc, type_die, log, type_is_new_ptr)) {\n \/\/ Create a unique pointer for the type + fixed buffer flag.\n type_sp.reset(new Type(*wrapped_type));\n type_sp->SetSwiftFixedValueBuffer(true);\n return type_sp;\n }\n }\n if (SwiftLanguageRuntime::IsSwiftMangledName(name.GetCString()))\n mangled_name = name;\n else {\n const char *type_name_cstr = name.GetCString();\n \/\/ TODO: remove this once all mangled names are always included for all\n \/\/ types in DWARF\n swift::ModuleDecl *swift_module = m_ast.GetModule(decl.GetFile(), error);\n if (swift_module)\n compiler_type = m_ast.FindType(type_name_cstr, swift_module);\n }\n }\n\n if (mangled_name) {\n type_sp = m_ast.GetCachedType(mangled_name);\n if (type_sp)\n return type_sp;\n\n \/\/ Try to import the type from one of the loaded Swift modules.\n compiler_type =\n m_ast.GetTypeFromMangledTypename(mangled_name.GetCString(), error);\n }\n\n if (!compiler_type &&\n swift::Demangle::isObjCSymbol(mangled_name.GetStringRef())) {\n \/\/ When we failed to look up the type because no .swiftmodule is\n \/\/ present or it couldn't be read, fall back to presenting objects\n \/\/ that look like they might be come from Objective-C (or C) as\n \/\/ Clang types. LLDB's Objective-C part is very robust against\n \/\/ malformed object pointers, so this isn't very risky.\n if (auto *clang_ctx = llvm::dyn_cast_or_null<ClangASTContext>(\n sc.module_sp->GetTypeSystemForLanguage(eLanguageTypeObjC))) {\n DWARFASTParserClang *clang_ast_parser =\n static_cast<DWARFASTParserClang *>(clang_ctx->GetDWARFParser());\n TypeMap clang_types;\n GetClangType(die, mangled_name.GetStringRef(), clang_types);\n\n \/\/ Import the Clang type into the Clang context.\n if (clang_types.GetSize())\n if (TypeSP clang_type_sp = clang_types.GetTypeAtIndex(0))\n if (clang_type_sp) {\n is_clang_type = true;\n compiler_type = clang_ast_parser->GetClangASTImporter().CopyType(\n *clang_ctx, clang_type_sp->GetForwardCompilerType());\n \/\/ Swift doesn't know pointers. Convert top-level\n \/\/ Objective-C object types to object pointers for Clang.\n auto clang_type = clang::QualType::getFromOpaquePtr(\n compiler_type.GetOpaqueQualType());\n if (clang_type->isObjCObjectOrInterfaceType())\n compiler_type = compiler_type.GetPointerType();\n }\n\n \/\/ Fall back to (id), which is not necessarily correct.\n if (!compiler_type) {\n is_clang_type = true;\n compiler_type = clang_ctx->GetBasicType(eBasicTypeObjCClass);\n }\n }\n }\n\n ConstString preferred_name;\n if (!compiler_type && name) {\n \/\/ Handle Archetypes, which are typedefs to RawPointerType.\n if (GetTypedefName(die).startswith(\"$sBp\")) {\n swift::ASTContext *swift_ast_ctx = m_ast.GetASTContext();\n if (!swift_ast_ctx) {\n if (log)\n log->Printf(\"Empty Swift AST context while looking up %s.\",\n name.AsCString());\n return {};\n }\n preferred_name = name;\n compiler_type = {swift_ast_ctx->TheRawPointerType};\n }\n }\n\n switch (die.Tag()) {\n case DW_TAG_inlined_subroutine:\n case DW_TAG_subprogram:\n case DW_TAG_subroutine_type:\n if (!compiler_type || !compiler_type.IsFunctionType()) {\n \/\/ Make sure we at least have some function type. The mangling for\n \/\/ the \"top_level_code\" is returning the empty tuple type \"()\",\n \/\/ which is not a function type.\n compiler_type = m_ast.GetVoidFunctionType();\n }\n break;\n default:\n break;\n }\n\n if (compiler_type) {\n type_sp = TypeSP(new Type(\n die.GetID(), die.GetDWARF(),\n preferred_name ? preferred_name : compiler_type.GetTypeName(),\n is_clang_type ? dwarf_byte_size\n : compiler_type.GetByteSize(nullptr),\n NULL, LLDB_INVALID_UID, Type::eEncodingIsUID, &decl, compiler_type,\n is_clang_type ? Type::eResolveStateForward : Type::eResolveStateFull));\n \/\/ FIXME: This ought to work lazily, too.\n if (is_clang_type)\n type_sp->GetFullCompilerType();\n }\n\n \/\/ Cache this type.\n if (type_sp && mangled_name &&\n SwiftLanguageRuntime::IsSwiftMangledName(mangled_name.GetCString()))\n m_ast.SetCachedType(mangled_name, type_sp);\n\n return type_sp;\n}\n\nvoid DWARFASTParserSwift::GetClangType(const DWARFDIE &die,\n llvm::StringRef mangled_name,\n TypeMap &clang_types) const {\n std::vector<CompilerContext> decl_context;\n die.GetDeclContext(decl_context);\n if (!decl_context.size())\n return;\n\n \/\/ Typedefs don't have a DW_AT_linkage_name, so their DW_AT_name is the\n \/\/ mangled. Get the unmangled name.\n auto fixup_typedef = [&mangled_name, &decl_context]() {\n using namespace swift::Demangle;\n Context Ctx;\n NodePointer node = Ctx.demangleSymbolAsNode(mangled_name);\n if (!node || node->getNumChildren() != 1 ||\n node->getKind() != Node::Kind::Global)\n return;\n node = node->getFirstChild();\n if (node->getNumChildren() != 1 ||\n node->getKind() != Node::Kind::TypeMangling)\n return;\n node = node->getFirstChild();\n if (node->getNumChildren() != 1 || node->getKind() != Node::Kind::Type)\n return;\n node = node->getFirstChild();\n if (node->getKind() != Node::Kind::TypeAlias)\n return;\n for (NodePointer child : *node)\n if (child->getKind() == Node::Kind::Identifier && child->hasText()) {\n decl_context.back().type = CompilerContextKind::Typedef;\n decl_context.back().name = ConstString(child->getText());\n return;\n }\n };\n fixup_typedef();\n\n auto *sym_file = die.GetCU()->GetSymbolFileDWARF();\n sym_file->UpdateExternalModuleListIfNeeded();\n\n CompilerContextKind kinds[] = {decl_context.back().type,\n CompilerContextKind::Union,\n CompilerContextKind::Enumeration};\n\n \/\/ The Swift projection of all Clang type is a struct; search every kind.\n for (CompilerContextKind kind : kinds) {\n decl_context.back().type = kind;\n \/\/ Search any modules referenced by DWARF.\n for (const auto &name_module : sym_file->getExternalTypeModules()) {\n if (!name_module.second)\n continue;\n SymbolVendor *sym_vendor = name_module.second->GetSymbolVendor();\n if (sym_vendor->FindTypes(decl_context, true, clang_types))\n return;\n }\n \/\/ Next search the .dSYM the DIE came from, if applicable.\n if (SymbolFileDWARF *sym_file = die.GetCU()->GetSymbolFileDWARF())\n if (sym_file->FindTypes(decl_context, true, clang_types))\n return;\n }\n}\n\nFunction *DWARFASTParserSwift::ParseFunctionFromDWARF(\n lldb_private::CompileUnit &comp_unit, const DWARFDIE &die) {\n DWARFRangeList func_ranges;\n const char *name = NULL;\n const char *mangled = NULL;\n int decl_file = 0;\n int decl_line = 0;\n int decl_column = 0;\n int call_file = 0;\n int call_line = 0;\n int call_column = 0;\n DWARFExpression frame_base(die.GetCU());\n\n if (die.Tag() != DW_TAG_subprogram)\n return NULL;\n\n if (die.GetDIENamesAndRanges(name, mangled, func_ranges, decl_file, decl_line,\n decl_column, call_file, call_line, call_column,\n &frame_base)) {\n \/\/ Union of all ranges in the function DIE (if the function is\n \/\/ discontiguous)\n SymbolFileDWARF *dwarf = die.GetDWARF();\n AddressRange func_range;\n lldb::addr_t lowest_func_addr = func_ranges.GetMinRangeBase(0);\n lldb::addr_t highest_func_addr = func_ranges.GetMaxRangeEnd(0);\n if (lowest_func_addr != LLDB_INVALID_ADDRESS &&\n lowest_func_addr <= highest_func_addr) {\n ModuleSP module_sp(dwarf->GetObjectFile()->GetModule());\n func_range.GetBaseAddress().ResolveAddressUsingFileSections(\n lowest_func_addr, module_sp->GetSectionList());\n if (func_range.GetBaseAddress().IsValid())\n func_range.SetByteSize(highest_func_addr - lowest_func_addr);\n }\n\n if (func_range.GetBaseAddress().IsValid()) {\n Mangled func_name;\n if (mangled)\n func_name.SetValue(ConstString(mangled), true);\n else\n func_name.SetValue(ConstString(name), false);\n\n \/\/ See if this function can throw. We can't get that from the\n \/\/ mangled name (even though the information is often there)\n \/\/ because Swift reserves the right to omit it from the name\n \/\/ if it doesn't need it. So instead we look for the\n \/\/ DW_TAG_thrown_type:\n\n bool can_throw = false;\n\n DWARFDebugInfoEntry *child(die.GetFirstChild().GetDIE());\n while (child) {\n if (child->Tag() == DW_TAG_thrown_type) {\n can_throw = true;\n break;\n }\n child = child->GetSibling();\n }\n\n FunctionSP func_sp;\n std::unique_ptr<Declaration> decl_ap;\n if (decl_file != 0 || decl_line != 0 || decl_column != 0)\n decl_ap.reset(new Declaration(\n comp_unit.GetSupportFiles().GetFileSpecAtIndex(decl_file),\n decl_line, decl_column));\n\n if (dwarf->FixupAddress(func_range.GetBaseAddress())) {\n const user_id_t func_user_id = die.GetID();\n func_sp.reset(new Function(&comp_unit, func_user_id, func_user_id,\n func_name, nullptr, func_range,\n can_throw)); \/\/ first address range\n\n if (func_sp.get() != NULL) {\n if (frame_base.IsValid())\n func_sp->GetFrameBaseExpression() = frame_base;\n comp_unit.AddFunction(func_sp);\n return func_sp.get();\n }\n }\n }\n }\n return NULL;\n}\n\nlldb_private::CompilerDeclContext\nDWARFASTParserSwift::GetDeclContextForUIDFromDWARF(const DWARFDIE &die) {\n return CompilerDeclContext();\n}\n\nlldb_private::CompilerDeclContext\nDWARFASTParserSwift::GetDeclContextContainingUIDFromDWARF(const DWARFDIE &die) {\n return CompilerDeclContext();\n}\n<commit_msg>[DWARF] Fix Swift build after r361849<commit_after>\/\/===-- DWARFASTParserSwift.cpp ---------------------------------*- C++ -*-===\/\/\n\/\/\n\/\/ This source file is part of the Swift.org open source project\n\/\/\n\/\/ Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors\n\/\/ Licensed under Apache License v2.0 with Runtime Library Exception\n\/\/\n\/\/ See https:\/\/swift.org\/LICENSE.txt for license information\n\/\/ See https:\/\/swift.org\/CONTRIBUTORS.txt for the list of Swift project authors\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"DWARFASTParserSwift.h\"\n\n#include \"DWARFASTParserClang.h\"\n#include \"DWARFCompileUnit.h\"\n#include \"DWARFDIE.h\"\n#include \"DWARFDebugInfo.h\"\n#include \"DWARFDefines.h\"\n#include \"SymbolFileDWARF.h\"\n\n#include \"swift\/AST\/ASTContext.h\"\n#include \"swift\/Demangling\/Demangle.h\"\n\n#include \"lldb\/Core\/Module.h\"\n#include \"lldb\/Symbol\/ClangASTContext.h\"\n#include \"lldb\/Symbol\/CompileUnit.h\"\n#include \"lldb\/Symbol\/Function.h\"\n#include \"lldb\/Symbol\/ObjectFile.h\"\n#include \"lldb\/Symbol\/SwiftASTContext.h\"\n#include \"lldb\/Symbol\/SymbolVendor.h\"\n#include \"lldb\/Symbol\/Type.h\"\n#include \"lldb\/Symbol\/TypeMap.h\"\n#include \"lldb\/Target\/SwiftLanguageRuntime.h\"\n#include \"lldb\/Utility\/Log.h\"\n#include \"lldb\/Utility\/Status.h\"\n\nusing namespace lldb;\nusing namespace lldb_private;\n\nDWARFASTParserSwift::DWARFASTParserSwift(SwiftASTContext &ast) : m_ast(ast) {}\n\nDWARFASTParserSwift::~DWARFASTParserSwift() {}\n\nstatic llvm::StringRef GetTypedefName(const DWARFDIE &die) {\n if (die.Tag() != DW_TAG_typedef)\n return {};\n DWARFDIE type_die = die.GetAttributeValueAsReferenceDIE(DW_AT_type);\n if (!type_die.IsValid())\n return {};\n return llvm::StringRef::withNullAsEmpty(type_die.GetName());\n}\n\nlldb::TypeSP DWARFASTParserSwift::ParseTypeFromDWARF(const SymbolContext &sc,\n const DWARFDIE &die,\n Log *log,\n bool *type_is_new_ptr) {\n lldb::TypeSP type_sp;\n CompilerType compiler_type;\n Status error;\n\n Declaration decl;\n ConstString mangled_name;\n ConstString name;\n bool is_clang_type = false;\n llvm::Optional<uint64_t> dwarf_byte_size;\n\n DWARFAttributes attributes;\n const size_t num_attributes = die.GetAttributes(attributes);\n DWARFFormValue type_attr;\n\n if (num_attributes > 0) {\n uint32_t i;\n for (i = 0; i < num_attributes; ++i) {\n const dw_attr_t attr = attributes.AttributeAtIndex(i);\n DWARFFormValue form_value;\n if (attributes.ExtractFormValueAtIndex(i, form_value)) {\n switch (attr) {\n case DW_AT_decl_file:\n decl.SetFile(sc.comp_unit->GetSupportFiles().GetFileSpecAtIndex(\n form_value.Unsigned()));\n break;\n case DW_AT_decl_line:\n decl.SetLine(form_value.Unsigned());\n break;\n case DW_AT_decl_column:\n decl.SetColumn(form_value.Unsigned());\n break;\n case DW_AT_name:\n name.SetCString(form_value.AsCString());\n break;\n case DW_AT_linkage_name:\n case DW_AT_MIPS_linkage_name:\n mangled_name.SetCString(form_value.AsCString());\n break;\n case DW_AT_byte_size:\n dwarf_byte_size = form_value.Unsigned();\n break;\n default:\n break;\n }\n }\n }\n }\n\n if (!mangled_name && name) {\n if (name.GetStringRef().equals(\"$swift.fixedbuffer\")) {\n DWARFDIE type_die =\n die.GetFirstChild().GetAttributeValueAsReferenceDIE(DW_AT_type);\n if (auto wrapped_type =\n ParseTypeFromDWARF(sc, type_die, log, type_is_new_ptr)) {\n \/\/ Create a unique pointer for the type + fixed buffer flag.\n type_sp.reset(new Type(*wrapped_type));\n type_sp->SetSwiftFixedValueBuffer(true);\n return type_sp;\n }\n }\n if (SwiftLanguageRuntime::IsSwiftMangledName(name.GetCString()))\n mangled_name = name;\n else {\n const char *type_name_cstr = name.GetCString();\n \/\/ TODO: remove this once all mangled names are always included for all\n \/\/ types in DWARF\n swift::ModuleDecl *swift_module = m_ast.GetModule(decl.GetFile(), error);\n if (swift_module)\n compiler_type = m_ast.FindType(type_name_cstr, swift_module);\n }\n }\n\n if (mangled_name) {\n type_sp = m_ast.GetCachedType(mangled_name);\n if (type_sp)\n return type_sp;\n\n \/\/ Try to import the type from one of the loaded Swift modules.\n compiler_type =\n m_ast.GetTypeFromMangledTypename(mangled_name.GetCString(), error);\n }\n\n if (!compiler_type &&\n swift::Demangle::isObjCSymbol(mangled_name.GetStringRef())) {\n \/\/ When we failed to look up the type because no .swiftmodule is\n \/\/ present or it couldn't be read, fall back to presenting objects\n \/\/ that look like they might be come from Objective-C (or C) as\n \/\/ Clang types. LLDB's Objective-C part is very robust against\n \/\/ malformed object pointers, so this isn't very risky.\n if (auto *clang_ctx = llvm::dyn_cast_or_null<ClangASTContext>(\n sc.module_sp->GetTypeSystemForLanguage(eLanguageTypeObjC))) {\n DWARFASTParserClang *clang_ast_parser =\n static_cast<DWARFASTParserClang *>(clang_ctx->GetDWARFParser());\n TypeMap clang_types;\n GetClangType(die, mangled_name.GetStringRef(), clang_types);\n\n \/\/ Import the Clang type into the Clang context.\n if (clang_types.GetSize())\n if (TypeSP clang_type_sp = clang_types.GetTypeAtIndex(0))\n if (clang_type_sp) {\n is_clang_type = true;\n compiler_type = clang_ast_parser->GetClangASTImporter().CopyType(\n *clang_ctx, clang_type_sp->GetForwardCompilerType());\n \/\/ Swift doesn't know pointers. Convert top-level\n \/\/ Objective-C object types to object pointers for Clang.\n auto clang_type = clang::QualType::getFromOpaquePtr(\n compiler_type.GetOpaqueQualType());\n if (clang_type->isObjCObjectOrInterfaceType())\n compiler_type = compiler_type.GetPointerType();\n }\n\n \/\/ Fall back to (id), which is not necessarily correct.\n if (!compiler_type) {\n is_clang_type = true;\n compiler_type = clang_ctx->GetBasicType(eBasicTypeObjCClass);\n }\n }\n }\n\n ConstString preferred_name;\n if (!compiler_type && name) {\n \/\/ Handle Archetypes, which are typedefs to RawPointerType.\n if (GetTypedefName(die).startswith(\"$sBp\")) {\n swift::ASTContext *swift_ast_ctx = m_ast.GetASTContext();\n if (!swift_ast_ctx) {\n if (log)\n log->Printf(\"Empty Swift AST context while looking up %s.\",\n name.AsCString());\n return {};\n }\n preferred_name = name;\n compiler_type = {swift_ast_ctx->TheRawPointerType};\n }\n }\n\n switch (die.Tag()) {\n case DW_TAG_inlined_subroutine:\n case DW_TAG_subprogram:\n case DW_TAG_subroutine_type:\n if (!compiler_type || !compiler_type.IsFunctionType()) {\n \/\/ Make sure we at least have some function type. The mangling for\n \/\/ the \"top_level_code\" is returning the empty tuple type \"()\",\n \/\/ which is not a function type.\n compiler_type = m_ast.GetVoidFunctionType();\n }\n break;\n default:\n break;\n }\n\n if (compiler_type) {\n type_sp = TypeSP(new Type(\n die.GetID(), die.GetDWARF(),\n preferred_name ? preferred_name : compiler_type.GetTypeName(),\n is_clang_type ? dwarf_byte_size\n : compiler_type.GetByteSize(nullptr),\n NULL, LLDB_INVALID_UID, Type::eEncodingIsUID, &decl, compiler_type,\n is_clang_type ? Type::eResolveStateForward : Type::eResolveStateFull));\n \/\/ FIXME: This ought to work lazily, too.\n if (is_clang_type)\n type_sp->GetFullCompilerType();\n }\n\n \/\/ Cache this type.\n if (type_sp && mangled_name &&\n SwiftLanguageRuntime::IsSwiftMangledName(mangled_name.GetCString()))\n m_ast.SetCachedType(mangled_name, type_sp);\n\n return type_sp;\n}\n\nvoid DWARFASTParserSwift::GetClangType(const DWARFDIE &die,\n llvm::StringRef mangled_name,\n TypeMap &clang_types) const {\n std::vector<CompilerContext> decl_context;\n die.GetDeclContext(decl_context);\n if (!decl_context.size())\n return;\n\n \/\/ Typedefs don't have a DW_AT_linkage_name, so their DW_AT_name is the\n \/\/ mangled. Get the unmangled name.\n auto fixup_typedef = [&mangled_name, &decl_context]() {\n using namespace swift::Demangle;\n Context Ctx;\n NodePointer node = Ctx.demangleSymbolAsNode(mangled_name);\n if (!node || node->getNumChildren() != 1 ||\n node->getKind() != Node::Kind::Global)\n return;\n node = node->getFirstChild();\n if (node->getNumChildren() != 1 ||\n node->getKind() != Node::Kind::TypeMangling)\n return;\n node = node->getFirstChild();\n if (node->getNumChildren() != 1 || node->getKind() != Node::Kind::Type)\n return;\n node = node->getFirstChild();\n if (node->getKind() != Node::Kind::TypeAlias)\n return;\n for (NodePointer child : *node)\n if (child->getKind() == Node::Kind::Identifier && child->hasText()) {\n decl_context.back().type = CompilerContextKind::Typedef;\n decl_context.back().name = ConstString(child->getText());\n return;\n }\n };\n fixup_typedef();\n\n auto *sym_file = die.GetCU()->GetSymbolFileDWARF();\n sym_file->UpdateExternalModuleListIfNeeded();\n\n CompilerContextKind kinds[] = {decl_context.back().type,\n CompilerContextKind::Union,\n CompilerContextKind::Enumeration};\n\n \/\/ The Swift projection of all Clang type is a struct; search every kind.\n for (CompilerContextKind kind : kinds) {\n decl_context.back().type = kind;\n \/\/ Search any modules referenced by DWARF.\n for (const auto &name_module : sym_file->getExternalTypeModules()) {\n if (!name_module.second)\n continue;\n SymbolVendor *sym_vendor = name_module.second->GetSymbolVendor();\n if (sym_vendor->FindTypes(decl_context, true, clang_types))\n return;\n }\n \/\/ Next search the .dSYM the DIE came from, if applicable.\n if (SymbolFileDWARF *sym_file = die.GetCU()->GetSymbolFileDWARF())\n if (sym_file->FindTypes(decl_context, true, clang_types))\n return;\n }\n}\n\nFunction *DWARFASTParserSwift::ParseFunctionFromDWARF(\n lldb_private::CompileUnit &comp_unit, const DWARFDIE &die) {\n DWARFRangeList func_ranges;\n const char *name = NULL;\n const char *mangled = NULL;\n int decl_file = 0;\n int decl_line = 0;\n int decl_column = 0;\n int call_file = 0;\n int call_line = 0;\n int call_column = 0;\n DWARFExpression frame_base;\n\n if (die.Tag() != DW_TAG_subprogram)\n return NULL;\n\n if (die.GetDIENamesAndRanges(name, mangled, func_ranges, decl_file, decl_line,\n decl_column, call_file, call_line, call_column,\n &frame_base)) {\n \/\/ Union of all ranges in the function DIE (if the function is\n \/\/ discontiguous)\n SymbolFileDWARF *dwarf = die.GetDWARF();\n AddressRange func_range;\n lldb::addr_t lowest_func_addr = func_ranges.GetMinRangeBase(0);\n lldb::addr_t highest_func_addr = func_ranges.GetMaxRangeEnd(0);\n if (lowest_func_addr != LLDB_INVALID_ADDRESS &&\n lowest_func_addr <= highest_func_addr) {\n ModuleSP module_sp(dwarf->GetObjectFile()->GetModule());\n func_range.GetBaseAddress().ResolveAddressUsingFileSections(\n lowest_func_addr, module_sp->GetSectionList());\n if (func_range.GetBaseAddress().IsValid())\n func_range.SetByteSize(highest_func_addr - lowest_func_addr);\n }\n\n if (func_range.GetBaseAddress().IsValid()) {\n Mangled func_name;\n if (mangled)\n func_name.SetValue(ConstString(mangled), true);\n else\n func_name.SetValue(ConstString(name), false);\n\n \/\/ See if this function can throw. We can't get that from the\n \/\/ mangled name (even though the information is often there)\n \/\/ because Swift reserves the right to omit it from the name\n \/\/ if it doesn't need it. So instead we look for the\n \/\/ DW_TAG_thrown_type:\n\n bool can_throw = false;\n\n DWARFDebugInfoEntry *child(die.GetFirstChild().GetDIE());\n while (child) {\n if (child->Tag() == DW_TAG_thrown_type) {\n can_throw = true;\n break;\n }\n child = child->GetSibling();\n }\n\n FunctionSP func_sp;\n std::unique_ptr<Declaration> decl_ap;\n if (decl_file != 0 || decl_line != 0 || decl_column != 0)\n decl_ap.reset(new Declaration(\n comp_unit.GetSupportFiles().GetFileSpecAtIndex(decl_file),\n decl_line, decl_column));\n\n if (dwarf->FixupAddress(func_range.GetBaseAddress())) {\n const user_id_t func_user_id = die.GetID();\n func_sp.reset(new Function(&comp_unit, func_user_id, func_user_id,\n func_name, nullptr, func_range,\n can_throw)); \/\/ first address range\n\n if (func_sp.get() != NULL) {\n if (frame_base.IsValid())\n func_sp->GetFrameBaseExpression() = frame_base;\n comp_unit.AddFunction(func_sp);\n return func_sp.get();\n }\n }\n }\n }\n return NULL;\n}\n\nlldb_private::CompilerDeclContext\nDWARFASTParserSwift::GetDeclContextForUIDFromDWARF(const DWARFDIE &die) {\n return CompilerDeclContext();\n}\n\nlldb_private::CompilerDeclContext\nDWARFASTParserSwift::GetDeclContextContainingUIDFromDWARF(const DWARFDIE &die) {\n return CompilerDeclContext();\n}\n<|endoftext|>"} {"text":"<commit_before>\n#pragma once\n\n\n#include <sstream>\n\n#include <cppassist\/string\/manipulation.h>\n#include <cppassist\/memory\/make_unique.inl>\n\n\nnamespace cppexpose\n{\n\n\ntemplate <typename T, typename BASE>\nclass DirectValue;\n\ntemplate <typename T, typename BASE>\nclass StoredValue;\n\n\ntemplate <typename T, typename ET, size_t Size, typename BASE>\nTypedArray<T, ET, Size, BASE>::TypedArray()\n{\n}\n\n\ntemplate <typename T, typename ET, size_t Size, typename BASE>\nTypedArray<T, ET, Size, BASE>::TypedArray(const TypedArray & rhs)\n: Typed<T, BASE>(rhs)\n{\n \/\/ don't copy m_subValues which will be lazy-initialized when used\n}\n\n\ntemplate <typename T, typename ET, size_t Size, typename BASE>\nTypedArray<T, ET, Size, BASE>::TypedArray(TypedArray && rhs)\n: Typed<T, BASE>(std::move(rhs))\n, m_subValues(std::move(rhs.m_subValues))\n{\n}\n\ntemplate <typename T, typename ET, size_t Size, typename BASE>\nTypedArray<T, ET, Size, BASE>::~TypedArray()\n{\n}\n\n\ntemplate <typename T, typename ET, size_t Size, typename BASE>\nTypedArray<T, ET, Size, BASE> & TypedArray<T, ET, Size, BASE>::operator=(const TypedArray & rhs)\n{\n Typed<T, BASE>::operator=(std::move(rhs));\n\n \/\/ don't copy m_subValues which will be lazy-initialized when used\n\n return *this;\n}\n\n\ntemplate <typename T, typename ET, size_t Size, typename BASE>\nTypedArray<T, ET, Size, BASE> & TypedArray<T, ET, Size, BASE>::operator=(TypedArray && rhs)\n{\n Typed<T, BASE>::operator=(std::move(rhs));\n\n m_subValues = std::move(rhs.m_subValues);\n\n return *this;\n}\n\ntemplate <typename T, typename ET, size_t Size, typename BASE>\nsize_t TypedArray<T, ET, Size, BASE>::numElements() const\n{\n return Size;\n}\n\ntemplate <typename T, typename ET, size_t Size, typename BASE>\nstd::string TypedArray<T, ET, Size, BASE>::typeName() const\n{\n \/\/ [TODO] This is not nice and potentially expensive.\n \/\/ Find a better way to get type names.\n DirectValue<ET> dummy;\n\n std::stringstream s;\n s << \"array<\" << dummy.typeName() << \", \" << Size << \">\";\n return s.str();\n}\n\ntemplate <typename T, typename ET, size_t Size, typename BASE>\nbool TypedArray<T, ET, Size, BASE>::isComposite() const\n{\n return true;\n}\n\ntemplate <typename T, typename ET, size_t Size, typename BASE>\nsize_t TypedArray<T, ET, Size, BASE>::numSubValues() const\n{\n return Size;\n}\n\ntemplate <typename T, typename ET, size_t Size, typename BASE>\nAbstractTyped * TypedArray<T, ET, Size, BASE>::subValue(size_t index)\n{\n \/\/ Create typed accessor for sub-values on first call to this function\n if (m_subValues.empty())\n {\n for (size_t i=0; i<Size; i++)\n {\n m_subValues.push_back(cppassist::make_unique<StoredValue<ET>>(\n [this, i] () -> ET {\n return this->getElement(i);\n },\n [this, i] (const ET & value) {\n this->setElement(i, value);\n }\n ));\n }\n }\n\n \/\/ Return sub-value accessor\n return (index < Size) ? m_subValues[index].get() : nullptr;\n}\n\ntemplate <typename T, typename ET, size_t Size, typename BASE>\nbool TypedArray<T, ET, Size, BASE>::isArray() const\n{\n return true;\n}\n\ntemplate <typename T, typename ET, size_t Size, typename BASE>\nstd::string TypedArray<T, ET, Size, BASE>::toString() const\n{\n std::string str = \"(\";\n\n for (size_t i=0; i<Size; i++) {\n if (i > 0) str += \", \";\n str += const_cast<TypedArray<T, ET, Size, BASE> *>(this)->subValue(i)->toString();\n }\n\n str += \")\";\n\n return str;\n}\n\ntemplate <typename T, typename ET, size_t Size, typename BASE>\nbool TypedArray<T, ET, Size, BASE>::fromString(const std::string & value)\n{\n std::vector<std::string> elementStrings = cppassist::string::parseArray(value, Size);\n if (elementStrings.size() != Size) {\n return false;\n }\n\n for (size_t i=0; i<Size; i++)\n {\n if (!this->subValue(i)->fromString(elementStrings[i])) {\n return false;\n }\n }\n\n return true;\n}\n\n\n} \/\/ namespace cppexpose\n<commit_msg>Fix std::move in copy assignment<commit_after>\n#pragma once\n\n\n#include <sstream>\n\n#include <cppassist\/string\/manipulation.h>\n#include <cppassist\/memory\/make_unique.inl>\n\n\nnamespace cppexpose\n{\n\n\ntemplate <typename T, typename BASE>\nclass DirectValue;\n\ntemplate <typename T, typename BASE>\nclass StoredValue;\n\n\ntemplate <typename T, typename ET, size_t Size, typename BASE>\nTypedArray<T, ET, Size, BASE>::TypedArray()\n{\n}\n\n\ntemplate <typename T, typename ET, size_t Size, typename BASE>\nTypedArray<T, ET, Size, BASE>::TypedArray(const TypedArray & rhs)\n: Typed<T, BASE>(rhs)\n{\n \/\/ don't copy m_subValues which will be lazy-initialized when used\n}\n\n\ntemplate <typename T, typename ET, size_t Size, typename BASE>\nTypedArray<T, ET, Size, BASE>::TypedArray(TypedArray && rhs)\n: Typed<T, BASE>(std::move(rhs))\n, m_subValues(std::move(rhs.m_subValues))\n{\n}\n\ntemplate <typename T, typename ET, size_t Size, typename BASE>\nTypedArray<T, ET, Size, BASE>::~TypedArray()\n{\n}\n\n\ntemplate <typename T, typename ET, size_t Size, typename BASE>\nTypedArray<T, ET, Size, BASE> & TypedArray<T, ET, Size, BASE>::operator=(const TypedArray & rhs)\n{\n Typed<T, BASE>::operator=(rhs);\n\n \/\/ don't copy m_subValues which will be lazy-initialized when used\n\n return *this;\n}\n\n\ntemplate <typename T, typename ET, size_t Size, typename BASE>\nTypedArray<T, ET, Size, BASE> & TypedArray<T, ET, Size, BASE>::operator=(TypedArray && rhs)\n{\n Typed<T, BASE>::operator=(std::move(rhs));\n\n m_subValues = std::move(rhs.m_subValues);\n\n return *this;\n}\n\ntemplate <typename T, typename ET, size_t Size, typename BASE>\nsize_t TypedArray<T, ET, Size, BASE>::numElements() const\n{\n return Size;\n}\n\ntemplate <typename T, typename ET, size_t Size, typename BASE>\nstd::string TypedArray<T, ET, Size, BASE>::typeName() const\n{\n \/\/ [TODO] This is not nice and potentially expensive.\n \/\/ Find a better way to get type names.\n DirectValue<ET> dummy;\n\n std::stringstream s;\n s << \"array<\" << dummy.typeName() << \", \" << Size << \">\";\n return s.str();\n}\n\ntemplate <typename T, typename ET, size_t Size, typename BASE>\nbool TypedArray<T, ET, Size, BASE>::isComposite() const\n{\n return true;\n}\n\ntemplate <typename T, typename ET, size_t Size, typename BASE>\nsize_t TypedArray<T, ET, Size, BASE>::numSubValues() const\n{\n return Size;\n}\n\ntemplate <typename T, typename ET, size_t Size, typename BASE>\nAbstractTyped * TypedArray<T, ET, Size, BASE>::subValue(size_t index)\n{\n \/\/ Create typed accessor for sub-values on first call to this function\n if (m_subValues.empty())\n {\n for (size_t i=0; i<Size; i++)\n {\n m_subValues.push_back(cppassist::make_unique<StoredValue<ET>>(\n [this, i] () -> ET {\n return this->getElement(i);\n },\n [this, i] (const ET & value) {\n this->setElement(i, value);\n }\n ));\n }\n }\n\n \/\/ Return sub-value accessor\n return (index < Size) ? m_subValues[index].get() : nullptr;\n}\n\ntemplate <typename T, typename ET, size_t Size, typename BASE>\nbool TypedArray<T, ET, Size, BASE>::isArray() const\n{\n return true;\n}\n\ntemplate <typename T, typename ET, size_t Size, typename BASE>\nstd::string TypedArray<T, ET, Size, BASE>::toString() const\n{\n std::string str = \"(\";\n\n for (size_t i=0; i<Size; i++) {\n if (i > 0) str += \", \";\n str += const_cast<TypedArray<T, ET, Size, BASE> *>(this)->subValue(i)->toString();\n }\n\n str += \")\";\n\n return str;\n}\n\ntemplate <typename T, typename ET, size_t Size, typename BASE>\nbool TypedArray<T, ET, Size, BASE>::fromString(const std::string & value)\n{\n std::vector<std::string> elementStrings = cppassist::string::parseArray(value, Size);\n if (elementStrings.size() != Size) {\n return false;\n }\n\n for (size_t i=0; i<Size; i++)\n {\n if (!this->subValue(i)->fromString(elementStrings[i])) {\n return false;\n }\n }\n\n return true;\n}\n\n\n} \/\/ namespace cppexpose\n<|endoftext|>"} {"text":"<commit_before>\/* bzflag\n * Copyright (c) 1993 - 2003 Tim Riker\n *\n * This package is free software; you can redistribute it and\/or\n * modify it under the terms of the license found in the file\n * named COPYING that should have accompanied this file.\n *\n * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR\n * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED\n * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.\n *\/\n\n#include \"WorldWeapons.h\"\n#include \"ShotUpdate.h\"\n#include \"Protocol.h\"\n#include \"Address.h\"\n\nchar *getDirectMessageBuffer();\nvoid broadcastMessage(uint16_t code, int len, const void *msg);\n\n\nWorldWeapons::WorldWeapons()\n: worldShotId(0)\n{\n}\n\nWorldWeapons::~WorldWeapons()\n{\n for (std::vector<Weapon*>::iterator it = weapons.begin(); it != weapons.end(); ++it) {\n Weapon *w = *it;\n delete w;\n }\n weapons.clear();\n}\n\nvoid WorldWeapons::fire()\n{\n for (std::vector<Weapon*>::iterator it = weapons.begin(); it != weapons.end(); ++it) {\n Weapon *w = *it;\n if (w->nextTime <= TimeKeeper::getCurrent()) {\n\n void *buf, *bufStart = getDirectMessageBuffer();\n\n FiringInfo firingInfo;\n firingInfo.flagType = (FlagType*)w->type;\n firingInfo.lifetime = BZDB->eval(StateDatabase::BZDB_RELOADTIME);\n firingInfo.shot.player = ServerPlayer;\n memmove(firingInfo.shot.pos, w->origin, 3 * sizeof(float));\n float shotSpeed = BZDB->eval(StateDatabase::BZDB_SHOTSPEED);\n firingInfo.shot.vel[0] = shotSpeed*cos(w->direction);\n firingInfo.shot.vel[1] = shotSpeed*sin(w->direction);\n firingInfo.shot.vel[2] = 0.0f;\n firingInfo.shot.id = worldShotId++;\n if (worldShotId > 30) \/\/ Maximum of 30 world shots\n worldShotId = 0;\n firingInfo.shot.dt = 0;\n buf = firingInfo.pack(bufStart);\n\n\n broadcastMessage(MsgShotBegin, (char *)buf - (char *)bufStart, bufStart);\n\n\n \/\/Set up timer for next shot\n w->nextTime += w->delay[w->nextDelay];\n w->nextDelay++;\n if (w->nextDelay == (int)w->delay.size())\n w->nextDelay = 0;\n }\n }\n}\n\nvoid WorldWeapons::add(const FlagType *type, const float *origin, float direction, float initdelay, const std::vector<float> &delay, TimeKeeper &sync)\n{\n Weapon *w = new Weapon();\n w->type = type;\n memmove(&w->origin, origin, 3*sizeof(float));\n w->direction = direction;\n w->nextTime = sync;\n w->nextTime += initdelay;\n w->nextDelay = 0;\n w->delay = delay;\n\n weapons.push_back(w);\n}\n\n\/\/ Local variables: ***\n\/\/ mode:C++ ***\n\/\/ tab-width: 8 ***\n\/\/ c-basic-offset: 2 ***\n\/\/ indent-tabs-mode: t ***\n\/\/ End: ***\n\/\/ ex: shiftwidth=2 tabstop=8\n<commit_msg>header comment foo<commit_after>\/* bzflag\n * Copyright (c) 1993 - 2003 Tim Riker\n *\n * This package is free software; you can redistribute it and\/or\n * modify it under the terms of the license found in the file\n * named COPYING that should have accompanied this file.\n *\n * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR\n * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED\n * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.\n *\/\n\n\/\/ class-interface header\n#include \"WorldWeapons.h\"\n\n\/\/ common-interface headers\n#include \"ShotUpdate.h\"\n#include \"Protocol.h\"\n#include \"Address.h\"\n\nchar *getDirectMessageBuffer();\nvoid broadcastMessage(uint16_t code, int len, const void *msg);\n\n\nWorldWeapons::WorldWeapons()\n: worldShotId(0)\n{\n}\n\nWorldWeapons::~WorldWeapons()\n{\n for (std::vector<Weapon*>::iterator it = weapons.begin(); it != weapons.end(); ++it) {\n Weapon *w = *it;\n delete w;\n }\n weapons.clear();\n}\n\nvoid WorldWeapons::fire()\n{\n for (std::vector<Weapon*>::iterator it = weapons.begin(); it != weapons.end(); ++it) {\n Weapon *w = *it;\n if (w->nextTime <= TimeKeeper::getCurrent()) {\n\n void *buf, *bufStart = getDirectMessageBuffer();\n\n FiringInfo firingInfo;\n firingInfo.flagType = (FlagType*)w->type;\n firingInfo.lifetime = BZDB->eval(StateDatabase::BZDB_RELOADTIME);\n firingInfo.shot.player = ServerPlayer;\n memmove(firingInfo.shot.pos, w->origin, 3 * sizeof(float));\n float shotSpeed = BZDB->eval(StateDatabase::BZDB_SHOTSPEED);\n firingInfo.shot.vel[0] = shotSpeed*cos(w->direction);\n firingInfo.shot.vel[1] = shotSpeed*sin(w->direction);\n firingInfo.shot.vel[2] = 0.0f;\n firingInfo.shot.id = worldShotId++;\n if (worldShotId > 30) \/\/ Maximum of 30 world shots\n worldShotId = 0;\n firingInfo.shot.dt = 0;\n buf = firingInfo.pack(bufStart);\n\n\n broadcastMessage(MsgShotBegin, (char *)buf - (char *)bufStart, bufStart);\n\n\n \/\/Set up timer for next shot\n w->nextTime += w->delay[w->nextDelay];\n w->nextDelay++;\n if (w->nextDelay == (int)w->delay.size())\n w->nextDelay = 0;\n }\n }\n}\n\nvoid WorldWeapons::add(const FlagType *type, const float *origin, float direction, float initdelay, const std::vector<float> &delay, TimeKeeper &sync)\n{\n Weapon *w = new Weapon();\n w->type = type;\n memmove(&w->origin, origin, 3*sizeof(float));\n w->direction = direction;\n w->nextTime = sync;\n w->nextTime += initdelay;\n w->nextDelay = 0;\n w->delay = delay;\n\n weapons.push_back(w);\n}\n\n\/\/ Local variables: ***\n\/\/ mode:C++ ***\n\/\/ tab-width: 8 ***\n\/\/ c-basic-offset: 2 ***\n\/\/ indent-tabs-mode: t ***\n\/\/ End: ***\n\/\/ ex: shiftwidth=2 tabstop=8\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (C) 2008-2013 The Communi Project\n *\n * This example is free, and not covered by the LGPL license. There is no\n * restriction applied to their modification, redistribution, using and so on.\n * You can study them, modify them, use them in your own program - either\n * completely or partially.\n *\/\n\n#include \"bufferview.h\"\n#include \"textdocument.h\"\n#include \"textbrowser.h\"\n#include \"textinput.h\"\n#include \"listview.h\"\n#include \"titlebar.h\"\n#include <IrcBufferModel>\n#include <QApplication>\n#include <QVBoxLayout>\n#include <IrcChannel>\n#include <IrcBuffer>\n\nBufferView::BufferView(QWidget* parent) : QWidget(parent)\n{\n d.titleBar = new TitleBar(this);\n d.listView = new ListView(this);\n d.textInput = new TextInput(this);\n d.textBrowser = new TextBrowser(this);\n d.textBrowser->setBuddy(d.textInput);\n\n d.splitter = new QSplitter(this);\n d.splitter->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Expanding);\n\n QVBoxLayout* layout = new QVBoxLayout(this);\n layout->setSpacing(0);\n layout->setMargin(0);\n layout->addWidget(d.titleBar);\n layout->addWidget(d.splitter);\n layout->addWidget(d.textInput);\n layout->setStretchFactor(d.splitter, 1);\n\n d.splitter->addWidget(d.textBrowser);\n d.splitter->addWidget(d.listView);\n d.splitter->setStretchFactor(0, 1);\n\n connect(d.listView, SIGNAL(queried(QString)), this, SLOT(query(QString)));\n connect(d.textBrowser, SIGNAL(queried(QString)), this, SLOT(query(QString)));\n}\n\nBufferView::~BufferView()\n{\n emit destroyed(this);\n}\n\nIrcBuffer* BufferView::buffer() const\n{\n return d.buffer;\n}\n\nListView* BufferView::listView() const\n{\n return d.listView;\n}\n\nTextInput* BufferView::textInput() const\n{\n return d.textInput;\n}\n\nTitleBar* BufferView::titleBar() const\n{\n return d.titleBar;\n}\n\nTextBrowser* BufferView::textBrowser() const\n{\n return d.textBrowser;\n}\n\nvoid BufferView::setBuffer(IrcBuffer* buffer)\n{\n if (d.buffer != buffer) {\n d.buffer = buffer;\n\n IrcChannel* channel = qobject_cast<IrcChannel*>(buffer);\n d.listView->setChannel(channel);\n d.listView->setVisible(channel);\n\n d.titleBar->setBuffer(buffer);\n d.textInput->setBuffer(buffer);\n if (buffer) {\n QWidget* focus = qApp->focusWidget();\n if (!focus || !focus->inherits(\"QLineEdit\") || (focus->inherits(\"TextInput\") && !isAncestorOf(focus)))\n d.textInput->setFocus();\n\n TextDocument* doc = 0;\n QList<TextDocument*> documents = d.buffer->findChildren<TextDocument*>();\n \/\/ there might be multiple clones, but at least one instance\n \/\/ must always remain there to avoid losing history...\n Q_ASSERT(!documents.isEmpty());\n foreach (TextDocument* d, documents) {\n if (!d->isVisible())\n doc = d;\n }\n if (!doc) {\n doc = documents.first()->clone();\n emit cloned(doc);\n }\n d.textBrowser->setDocument(doc);\n }\n\n emit bufferChanged(buffer);\n }\n}\n\nvoid BufferView::closeBuffer()\n{\n if (d.buffer)\n emit bufferClosed(d.buffer);\n}\n\nvoid BufferView::query(const QString& user)\n{\n IrcBufferModel* model = d.buffer ? d.buffer->model() : 0;\n if (model)\n setBuffer(model->add(user));\n}\n<commit_msg>BufferView: fix uninitialized variable<commit_after>\/*\n * Copyright (C) 2008-2013 The Communi Project\n *\n * This example is free, and not covered by the LGPL license. There is no\n * restriction applied to their modification, redistribution, using and so on.\n * You can study them, modify them, use them in your own program - either\n * completely or partially.\n *\/\n\n#include \"bufferview.h\"\n#include \"textdocument.h\"\n#include \"textbrowser.h\"\n#include \"textinput.h\"\n#include \"listview.h\"\n#include \"titlebar.h\"\n#include <IrcBufferModel>\n#include <QApplication>\n#include <QVBoxLayout>\n#include <IrcChannel>\n#include <IrcBuffer>\n\nBufferView::BufferView(QWidget* parent) : QWidget(parent)\n{\n d.buffer = 0;\n\n d.titleBar = new TitleBar(this);\n d.listView = new ListView(this);\n d.textInput = new TextInput(this);\n d.textBrowser = new TextBrowser(this);\n d.textBrowser->setBuddy(d.textInput);\n\n d.splitter = new QSplitter(this);\n d.splitter->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Expanding);\n\n QVBoxLayout* layout = new QVBoxLayout(this);\n layout->setSpacing(0);\n layout->setMargin(0);\n layout->addWidget(d.titleBar);\n layout->addWidget(d.splitter);\n layout->addWidget(d.textInput);\n layout->setStretchFactor(d.splitter, 1);\n\n d.splitter->addWidget(d.textBrowser);\n d.splitter->addWidget(d.listView);\n d.splitter->setStretchFactor(0, 1);\n\n connect(d.listView, SIGNAL(queried(QString)), this, SLOT(query(QString)));\n connect(d.textBrowser, SIGNAL(queried(QString)), this, SLOT(query(QString)));\n}\n\nBufferView::~BufferView()\n{\n emit destroyed(this);\n}\n\nIrcBuffer* BufferView::buffer() const\n{\n return d.buffer;\n}\n\nListView* BufferView::listView() const\n{\n return d.listView;\n}\n\nTextInput* BufferView::textInput() const\n{\n return d.textInput;\n}\n\nTitleBar* BufferView::titleBar() const\n{\n return d.titleBar;\n}\n\nTextBrowser* BufferView::textBrowser() const\n{\n return d.textBrowser;\n}\n\nvoid BufferView::setBuffer(IrcBuffer* buffer)\n{\n if (d.buffer != buffer) {\n d.buffer = buffer;\n\n IrcChannel* channel = qobject_cast<IrcChannel*>(buffer);\n d.listView->setChannel(channel);\n d.listView->setVisible(channel);\n\n d.titleBar->setBuffer(buffer);\n d.textInput->setBuffer(buffer);\n if (buffer) {\n QWidget* focus = qApp->focusWidget();\n if (!focus || !focus->inherits(\"QLineEdit\") || (focus->inherits(\"TextInput\") && !isAncestorOf(focus)))\n d.textInput->setFocus();\n\n TextDocument* doc = 0;\n QList<TextDocument*> documents = d.buffer->findChildren<TextDocument*>();\n \/\/ there might be multiple clones, but at least one instance\n \/\/ must always remain there to avoid losing history...\n Q_ASSERT(!documents.isEmpty());\n foreach (TextDocument* d, documents) {\n if (!d->isVisible())\n doc = d;\n }\n if (!doc) {\n doc = documents.first()->clone();\n emit cloned(doc);\n }\n d.textBrowser->setDocument(doc);\n }\n\n emit bufferChanged(buffer);\n }\n}\n\nvoid BufferView::closeBuffer()\n{\n if (d.buffer)\n emit bufferClosed(d.buffer);\n}\n\nvoid BufferView::query(const QString& user)\n{\n IrcBufferModel* model = d.buffer ? d.buffer->model() : 0;\n if (model)\n setBuffer(model->add(user));\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Author: Brendan Le Foll <brendan.le.foll@intel.com>\n * Contributions: Jon Trulson <jtrulson@ics.com>\n * Contributions: Thomas Ingleby <thomas.c.ingleby@intel.com>\n * Copyright (c) 2014 - 2015 Intel Corporation.\n *\n * Permission is hereby granted, free of charge, to any person obtaining\n * a copy of this software and associated documentation files (the\n * \"Software\"), to deal in the Software without restriction, including\n * without limitation the rights to use, copy, modify, merge, publish,\n * distribute, sublicense, and\/or sell copies of the Software, and to\n * permit persons to whom the Software is furnished to do so, subject to\n * the following conditions:\n *\n * The above copyright notice and this permission notice shall be\n * included in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n *\/\n\n#pragma once\n\n#include \"uart.h\"\n#include \"types.hpp\"\n#include <stdlib.h>\n#include <stdexcept>\n#include <cstring>\n\nnamespace mraa\n{\n\n\/**\n * @brief API to UART (enabling only)\n *\n * This file defines the UART interface for libmraa\n *\n * @snippet Uart-example.cpp Interesting\n *\/\nclass Uart\n{\n public:\n \/**\n * Uart Constructor, takes a pin number which will map directly to the\n * linux uart number, this 'enables' the uart, nothing more\n *\n * @param uart the index of the uart set to use\n *\/\n Uart(int uart)\n {\n m_uart = mraa_uart_init(uart);\n\n if (m_uart == NULL) {\n throw std::invalid_argument(\"Error initialising UART\");\n }\n }\n\n \/**\n * Uart Constructor, takes a string to the path of the serial\n * interface that is needed.\n *\n * @param uart the index of the uart set to use\n *\/\n Uart(std::string path)\n {\n m_uart = mraa_uart_init_raw(path.c_str());\n\n if (m_uart == NULL) {\n throw std::invalid_argument(\"Error initialising UART\");\n }\n }\n\n \/**\n * Uart Constructor, takes a pointer to the UART context and initialises\n * the UART class\n *\n * @param void * to a UART context\n *\/\n Uart(void* uart_context)\n {\n m_uart = (mraa_uart_context) uart_context;\n\n if (m_uart == NULL) {\n throw std::invalid_argument(\"Invalid UART context\");\n }\n }\n \/**\n * Uart destructor\n *\/\n ~Uart()\n {\n mraa_uart_stop(m_uart);\n }\n\n \/**\n * Get string with tty device path within Linux\n * For example. Could point to \"\/dev\/ttyS0\"\n *\n * @return char pointer of device path\n *\/\n std::string\n getDevicePath()\n {\n std::string ret_val(mraa_uart_get_dev_path(m_uart));\n return ret_val;\n }\n\n \/**\n * Read bytes from the device into char* buffer\n *\n * @param data buffer pointer\n * @param length maximum size of buffer\n * @return numbers of bytes read\n *\/\n int\n read(char* data, int length)\n {\n return mraa_uart_read(m_uart, data, (size_t) length);\n }\n\n \/**\n * Write bytes in String object to a device\n *\n * @param data buffer pointer\n * @param length maximum size of buffer\n * @return the number of bytes written, or -1 if an error occurred\n *\/\n int\n write(const char* data, int length)\n {\n return mraa_uart_write(m_uart, data, (size_t) length);\n }\n\n \/**\n * Read bytes from the device into a String object\n *\n * @param length to read\n * @throws std::bad_alloc If there is no space left for read.\n * @return string of data\n *\/\n std::string\n readStr(int length)\n {\n char* data = (char*) malloc(sizeof(char) * length);\n if (data == NULL) {\n throw std::bad_alloc();\n }\n\n int v = mraa_uart_read(m_uart, data, (size_t) length);\n std::string ret(data, v);\n free(data);\n return ret;\n }\n\n \/**\n * Write bytes in String object to a device\n *\n * @param string to write\n * @return the number of bytes written, or -1 if an error occurred\n *\/\n int\n writeStr(std::string data)\n {\n \/\/ this is data.length() not +1 because we want to avoid the '\\0' char\n return mraa_uart_write(m_uart, data.c_str(), (data.length()));\n }\n\n \/**\n * Check to see if data is available on the device for reading\n *\n * @param millis number of milliseconds to wait, or 0 to return immediately\n * @return true if there is data available to read, false otherwise\n *\/\n bool\n dataAvailable(unsigned int millis = 0)\n {\n if (mraa_uart_data_available(m_uart, millis))\n return true;\n else\n return false;\n }\n\n \/**\n * Flush the outbound data.\n * Blocks until complete.\n *\n * @return Result of operation\n *\/\n Result\n flush()\n {\n return (Result) mraa_uart_flush(m_uart);\n }\n\n \/**\n * Set the baudrate.\n * Takes an int and will attempt to decide what baudrate is\n * to be used on the UART hardware.\n *\n * @param baud unsigned int of baudrate i.e. 9600\n * @return Result of operation\n *\/\n Result\n setBaudRate(unsigned int baud)\n {\n return (Result) mraa_uart_set_baudrate(m_uart, baud);\n }\n\n \/**\n * Set the transfer mode\n * For example setting the mode to 8N1 would be\n * \"dev.setMode(8,UART_PARITY_NONE , 1)\"\n *\n * @param bytesize data bits\n * @param parity Parity bit setting\n * @param stopbits stop bits\n * @return Result of operation\n *\/\n Result\n setMode(int bytesize, UartParity parity, int stopbits)\n {\n return (Result) mraa_uart_set_mode(m_uart, bytesize, (mraa_uart_parity_t) parity, stopbits);\n }\n\n \/**\n * Set the flowcontrol\n *\n * @param xonxoff XON\/XOFF Software flow control.\n * @param rtscts RTS\/CTS out of band hardware flow control\n * @return Result of operation\n *\/\n Result\n setFlowcontrol(bool xonxoff, bool rtscts)\n {\n return (Result) mraa_uart_set_flowcontrol(m_uart, xonxoff, rtscts);\n }\n\n \/**\n * Set the timeout for read and write operations\n * <= 0 will disable that timeout\n *\n * @param read read timeout\n * @param write write timeout\n * @param interchar inbetween char timeout\n * @return Result of operation\n *\/\n Result\n setTimeout(int read, int write, int interchar)\n {\n return (Result) mraa_uart_set_timeout(m_uart, read, write, interchar);\n }\n\n \/**\n * Set the blocking state for write operations\n *\n * @param dev The UART context\n * @param nonblock new nonblocking state\n * @return Result of operation\n *\/\n Result\n SetNonBlocking(bool nonblock)\n {\n return (Result) mraa_uart_set_non_blocking(m_uart, nonblock);\n }\n\n private:\n mraa_uart_context m_uart;\n};\n}\n<commit_msg>uart.hpp: fix typo in write() description<commit_after>\/*\n * Author: Brendan Le Foll <brendan.le.foll@intel.com>\n * Contributions: Jon Trulson <jtrulson@ics.com>\n * Contributions: Thomas Ingleby <thomas.c.ingleby@intel.com>\n * Copyright (c) 2014 - 2015 Intel Corporation.\n *\n * Permission is hereby granted, free of charge, to any person obtaining\n * a copy of this software and associated documentation files (the\n * \"Software\"), to deal in the Software without restriction, including\n * without limitation the rights to use, copy, modify, merge, publish,\n * distribute, sublicense, and\/or sell copies of the Software, and to\n * permit persons to whom the Software is furnished to do so, subject to\n * the following conditions:\n *\n * The above copyright notice and this permission notice shall be\n * included in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n *\/\n\n#pragma once\n\n#include \"uart.h\"\n#include \"types.hpp\"\n#include <stdlib.h>\n#include <stdexcept>\n#include <cstring>\n\nnamespace mraa\n{\n\n\/**\n * @brief API to UART (enabling only)\n *\n * This file defines the UART interface for libmraa\n *\n * @snippet Uart-example.cpp Interesting\n *\/\nclass Uart\n{\n public:\n \/**\n * Uart Constructor, takes a pin number which will map directly to the\n * linux uart number, this 'enables' the uart, nothing more\n *\n * @param uart the index of the uart set to use\n *\/\n Uart(int uart)\n {\n m_uart = mraa_uart_init(uart);\n\n if (m_uart == NULL) {\n throw std::invalid_argument(\"Error initialising UART\");\n }\n }\n\n \/**\n * Uart Constructor, takes a string to the path of the serial\n * interface that is needed.\n *\n * @param uart the index of the uart set to use\n *\/\n Uart(std::string path)\n {\n m_uart = mraa_uart_init_raw(path.c_str());\n\n if (m_uart == NULL) {\n throw std::invalid_argument(\"Error initialising UART\");\n }\n }\n\n \/**\n * Uart Constructor, takes a pointer to the UART context and initialises\n * the UART class\n *\n * @param void * to a UART context\n *\/\n Uart(void* uart_context)\n {\n m_uart = (mraa_uart_context) uart_context;\n\n if (m_uart == NULL) {\n throw std::invalid_argument(\"Invalid UART context\");\n }\n }\n \/**\n * Uart destructor\n *\/\n ~Uart()\n {\n mraa_uart_stop(m_uart);\n }\n\n \/**\n * Get string with tty device path within Linux\n * For example. Could point to \"\/dev\/ttyS0\"\n *\n * @return char pointer of device path\n *\/\n std::string\n getDevicePath()\n {\n std::string ret_val(mraa_uart_get_dev_path(m_uart));\n return ret_val;\n }\n\n \/**\n * Read bytes from the device into char* buffer\n *\n * @param data buffer pointer\n * @param length maximum size of buffer\n * @return numbers of bytes read\n *\/\n int\n read(char* data, int length)\n {\n return mraa_uart_read(m_uart, data, (size_t) length);\n }\n\n \/**\n * Write bytes in char* buffer to a device\n *\n * @param data buffer pointer\n * @param length maximum size of buffer\n * @return the number of bytes written, or -1 if an error occurred\n *\/\n int\n write(const char* data, int length)\n {\n return mraa_uart_write(m_uart, data, (size_t) length);\n }\n\n \/**\n * Read bytes from the device into a String object\n *\n * @param length to read\n * @throws std::bad_alloc If there is no space left for read.\n * @return string of data\n *\/\n std::string\n readStr(int length)\n {\n char* data = (char*) malloc(sizeof(char) * length);\n if (data == NULL) {\n throw std::bad_alloc();\n }\n\n int v = mraa_uart_read(m_uart, data, (size_t) length);\n std::string ret(data, v);\n free(data);\n return ret;\n }\n\n \/**\n * Write bytes in String object to a device\n *\n * @param string to write\n * @return the number of bytes written, or -1 if an error occurred\n *\/\n int\n writeStr(std::string data)\n {\n \/\/ this is data.length() not +1 because we want to avoid the '\\0' char\n return mraa_uart_write(m_uart, data.c_str(), (data.length()));\n }\n\n \/**\n * Check to see if data is available on the device for reading\n *\n * @param millis number of milliseconds to wait, or 0 to return immediately\n * @return true if there is data available to read, false otherwise\n *\/\n bool\n dataAvailable(unsigned int millis = 0)\n {\n if (mraa_uart_data_available(m_uart, millis))\n return true;\n else\n return false;\n }\n\n \/**\n * Flush the outbound data.\n * Blocks until complete.\n *\n * @return Result of operation\n *\/\n Result\n flush()\n {\n return (Result) mraa_uart_flush(m_uart);\n }\n\n \/**\n * Set the baudrate.\n * Takes an int and will attempt to decide what baudrate is\n * to be used on the UART hardware.\n *\n * @param baud unsigned int of baudrate i.e. 9600\n * @return Result of operation\n *\/\n Result\n setBaudRate(unsigned int baud)\n {\n return (Result) mraa_uart_set_baudrate(m_uart, baud);\n }\n\n \/**\n * Set the transfer mode\n * For example setting the mode to 8N1 would be\n * \"dev.setMode(8,UART_PARITY_NONE , 1)\"\n *\n * @param bytesize data bits\n * @param parity Parity bit setting\n * @param stopbits stop bits\n * @return Result of operation\n *\/\n Result\n setMode(int bytesize, UartParity parity, int stopbits)\n {\n return (Result) mraa_uart_set_mode(m_uart, bytesize, (mraa_uart_parity_t) parity, stopbits);\n }\n\n \/**\n * Set the flowcontrol\n *\n * @param xonxoff XON\/XOFF Software flow control.\n * @param rtscts RTS\/CTS out of band hardware flow control\n * @return Result of operation\n *\/\n Result\n setFlowcontrol(bool xonxoff, bool rtscts)\n {\n return (Result) mraa_uart_set_flowcontrol(m_uart, xonxoff, rtscts);\n }\n\n \/**\n * Set the timeout for read and write operations\n * <= 0 will disable that timeout\n *\n * @param read read timeout\n * @param write write timeout\n * @param interchar inbetween char timeout\n * @return Result of operation\n *\/\n Result\n setTimeout(int read, int write, int interchar)\n {\n return (Result) mraa_uart_set_timeout(m_uart, read, write, interchar);\n }\n\n \/**\n * Set the blocking state for write operations\n *\n * @param dev The UART context\n * @param nonblock new nonblocking state\n * @return Result of operation\n *\/\n Result\n SetNonBlocking(bool nonblock)\n {\n return (Result) mraa_uart_set_non_blocking(m_uart, nonblock);\n }\n\n private:\n mraa_uart_context m_uart;\n};\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"clguetzli.h\"\n#include \"ocl.h\"\n\nocl_args_d_t& getOcl(void)\n{\n\tstatic bool bInit = false;\n\tstatic ocl_args_d_t ocl;\n\n\tif (bInit == true) return ocl;\n\n\tbInit = true;\n\tSetupOpenCL(&ocl, CL_DEVICE_TYPE_GPU);\n\n\tcl_int err = SetupOpenCL(&ocl, CL_DEVICE_TYPE_GPU);\n\tif (CL_SUCCESS != err)\n\t{\n\t\tLogError(\"Error: clBuildProgram() for source program returned %s.\\n\", TranslateOpenCLError(err));\n\t}\n\n\tchar* source = nullptr;\n\tsize_t src_size = 0;\n\tReadSourceFromFile(\"clguetzli\\\\clguetzli.cl\", &source, &src_size);\n\n\tocl.program = clCreateProgramWithSource(ocl.context, 1, (const char**)&source, &src_size, &err);\n\n\tdelete[] source;\n\n\terr = clBuildProgram(ocl.program, 1, &ocl.device, \"\", NULL, NULL);\n\tif (CL_SUCCESS != err)\n\t{\n\t\tLogError(\"Error: clBuildProgram() for source program returned %s.\\n\", TranslateOpenCLError(err));\n\t}\n\tocl.kernel[KERNEL_MINSQUAREVAL] = clCreateKernel(ocl.program, \"MinSquareVal\", &err);\n\tif (CL_SUCCESS != err)\n\t{\n\t\tLogError(\"Error: clCreateKernel(MinSquareVal) for source program returned %s.\\n\", TranslateOpenCLError(err));\n\t}\n\tocl.kernel[KERNEL_CONVOLUTION] = clCreateKernel(ocl.program, \"Convolution\", &err);\n\tif (CL_SUCCESS != err)\n\t{\n\t\tLogError(\"Error: clCreateKernel(Convolution) for source program returned %s.\\n\", TranslateOpenCLError(err));\n\t}\n\n\treturn ocl;\n}\n\nvoid clMinSquareVal(size_t square_size, size_t offset,\n\tsize_t xsize, size_t ysize,\n\tfloat *values)\n{\n\tcl_int err = CL_SUCCESS;\n\tocl_args_d_t &ocl = getOcl();\n\n\tocl.allocA(sizeof(cl_float) * xsize * ysize);\n\tocl.allocC(sizeof(cl_float) * xsize * ysize);\n\n\tmemcpy(ocl.inputA, values, sizeof(cl_float) * xsize * ysize);\n\n\tcl_int cloffset = offset;\n\tcl_int clsquare_size = square_size;\n\n\tcl_kernel kernel = ocl.kernel[KERNEL_MINSQUAREVAL];\n\tclSetKernelArg(kernel, 0, sizeof(cl_mem), (void*)&ocl.srcA);\n\tclSetKernelArg(kernel, 1, sizeof(cl_mem), (void*)&ocl.dstMem);\n\tclSetKernelArg(kernel, 2, sizeof(cl_int), (void*)&clsquare_size);\n\tclSetKernelArg(kernel, 3, sizeof(cl_int), (void*)&cloffset);\n\n\tsize_t globalWorkSize[2] = { xsize, ysize };\n\terr = clEnqueueNDRangeKernel(ocl.commandQueue, kernel, 2, NULL, globalWorkSize, NULL, 0, NULL, NULL);\n\tif (CL_SUCCESS != err)\n\t{\n\t\tLogError(\"Error: clBuildProgram() for source program returned %s.\\n\", TranslateOpenCLError(err));\n\t}\n\terr = clFinish(ocl.commandQueue);\n\tif (CL_SUCCESS != err)\n\t{\n\t\tLogError(\"Error: clBuildProgram() for source program returned %s.\\n\", TranslateOpenCLError(err));\n\t}\n\n\tcl_float *resultPtr = (cl_float *)clEnqueueMapBuffer(ocl.commandQueue, ocl.dstMem, true, CL_MAP_READ, 0, sizeof(cl_float) * xsize * ysize, 0, NULL, NULL, &err);\n\tif (CL_SUCCESS != err)\n\t{\n\t\tLogError(\"Error: clEnqueueMapBuffer returned %s\\n\", TranslateOpenCLError(err));\n\t}\n\terr = clFinish(ocl.commandQueue);\n\tif (CL_SUCCESS != err)\n\t{\n\t\tLogError(\"Error: clFinish returned %s\\n\", TranslateOpenCLError(err));\n\t}\n\n\tmemcpy(values, resultPtr, sizeof(cl_float) * xsize * ysize);\n}\n\nvoid clConvolution(size_t xsize, size_t ysize,\n\tsize_t xstep,\n\tsize_t len, size_t offset,\n\tconst float* multipliers,\n\tconst float* inp,\n\tfloat border_ratio,\n\tfloat* result)\n{\n\tcl_int err = CL_SUCCESS;\n\tocl_args_d_t &ocl = getOcl();\n\n\tsize_t oxsize = xsize \/ xstep;\n\n\tocl.allocA(sizeof(cl_float) * len);\n\tocl.allocB(sizeof(cl_float) * xsize * ysize);\n\tocl.allocC(sizeof(cl_float) * oxsize * ysize);\n\n\tmemcpy(ocl.inputA, multipliers, sizeof(cl_float) * len);\n\tmemcpy(ocl.inputB, inp, sizeof(cl_float) * xsize * ysize);\n\n\tcl_int clxsize = xsize;\n\tcl_int clxstep = xstep;\n\tcl_int cllen = len;\n\tcl_int cloffset = offset;\n\tcl_float clborder_ratio = border_ratio;\n\n\tcl_kernel kernel = ocl.kernel[KERNEL_CONVOLUTION];\n\tclSetKernelArg(kernel, 0, sizeof(cl_mem), (void*)&ocl.srcA);\n\tclSetKernelArg(kernel, 1, sizeof(cl_mem), (void*)&ocl.srcB);\n\tclSetKernelArg(kernel, 2, sizeof(cl_mem), (void*)&ocl.dstMem);\n\tclSetKernelArg(kernel, 3, sizeof(cl_int), (void*)&clxsize);\n\tclSetKernelArg(kernel, 4, sizeof(cl_int), (void*)&clxstep);\n\tclSetKernelArg(kernel, 5, sizeof(cl_int), (void*)&cllen);\n\tclSetKernelArg(kernel, 6, sizeof(cl_int), (void*)&cloffset);\n\tclSetKernelArg(kernel, 7, sizeof(cl_float), (void*)&clborder_ratio);\n\n\tsize_t globalWorkSize[2] = { xsize \/ xstep, ysize };\n\terr = clEnqueueNDRangeKernel(ocl.commandQueue, kernel, 2, NULL, globalWorkSize, NULL, 0, NULL, NULL);\n\tif (CL_SUCCESS != err)\n\t{\n\t\tLogError(\"Error: clBuildProgram() for source program returned %s.\\n\", TranslateOpenCLError(err));\n\t}\n\terr = clFinish(ocl.commandQueue);\n\tif (CL_SUCCESS != err)\n\t{\n\t\tLogError(\"Error: clBuildProgram() for source program returned %s.\\n\", TranslateOpenCLError(err));\n\t}\n\n\tcl_float *resultPtr = (cl_float *)clEnqueueMapBuffer(ocl.commandQueue, ocl.dstMem, true, CL_MAP_READ, 0, sizeof(cl_float) * oxsize * ysize, 0, NULL, NULL, &err);\n\tif (CL_SUCCESS != err)\n\t{\n\t\tLogError(\"Error: clEnqueueMapBuffer returned %s\\n\", TranslateOpenCLError(err));\n\t}\n\terr = clFinish(ocl.commandQueue);\n\tif (CL_SUCCESS != err)\n\t{\n\t\tLogError(\"Error: clFinish returned %s\\n\", TranslateOpenCLError(err));\n\t}\n\n\tmemcpy(result, resultPtr, sizeof(cl_float) * oxsize * ysize);\n}<commit_msg>fix setupopencl<commit_after>#include \"clguetzli.h\"\n#include \"ocl.h\"\n\nocl_args_d_t& getOcl(void)\n{\n\tstatic bool bInit = false;\n\tstatic ocl_args_d_t ocl;\n\n\tif (bInit == true) return ocl;\n\n\tbInit = true;\n\tcl_int err = SetupOpenCL(&ocl, CL_DEVICE_TYPE_GPU);\n\tif (CL_SUCCESS != err)\n\t{\n\t\tLogError(\"Error: clBuildProgram() for source program returned %s.\\n\", TranslateOpenCLError(err));\n\t}\n\n\tchar* source = nullptr;\n\tsize_t src_size = 0;\n\tReadSourceFromFile(\"clguetzli\\\\clguetzli.cl\", &source, &src_size);\n\n\tocl.program = clCreateProgramWithSource(ocl.context, 1, (const char**)&source, &src_size, &err);\n\n\tdelete[] source;\n\n\terr = clBuildProgram(ocl.program, 1, &ocl.device, \"\", NULL, NULL);\n\tif (CL_SUCCESS != err)\n\t{\n\t\tLogError(\"Error: clBuildProgram() for source program returned %s.\\n\", TranslateOpenCLError(err));\n\t}\n\tocl.kernel[KERNEL_MINSQUAREVAL] = clCreateKernel(ocl.program, \"MinSquareVal\", &err);\n\tif (CL_SUCCESS != err)\n\t{\n\t\tLogError(\"Error: clCreateKernel(MinSquareVal) for source program returned %s.\\n\", TranslateOpenCLError(err));\n\t}\n\tocl.kernel[KERNEL_CONVOLUTION] = clCreateKernel(ocl.program, \"Convolution\", &err);\n\tif (CL_SUCCESS != err)\n\t{\n\t\tLogError(\"Error: clCreateKernel(Convolution) for source program returned %s.\\n\", TranslateOpenCLError(err));\n\t}\n\n\treturn ocl;\n}\n\nvoid clMinSquareVal(size_t square_size, size_t offset,\n\tsize_t xsize, size_t ysize,\n\tfloat *values)\n{\n\tcl_int err = CL_SUCCESS;\n\tocl_args_d_t &ocl = getOcl();\n\n\tocl.allocA(sizeof(cl_float) * xsize * ysize);\n\tocl.allocC(sizeof(cl_float) * xsize * ysize);\n\n\tmemcpy(ocl.inputA, values, sizeof(cl_float) * xsize * ysize);\n\n\tcl_int cloffset = offset;\n\tcl_int clsquare_size = square_size;\n\n\tcl_kernel kernel = ocl.kernel[KERNEL_MINSQUAREVAL];\n\tclSetKernelArg(kernel, 0, sizeof(cl_mem), (void*)&ocl.srcA);\n\tclSetKernelArg(kernel, 1, sizeof(cl_mem), (void*)&ocl.dstMem);\n\tclSetKernelArg(kernel, 2, sizeof(cl_int), (void*)&clsquare_size);\n\tclSetKernelArg(kernel, 3, sizeof(cl_int), (void*)&cloffset);\n\n\tsize_t globalWorkSize[2] = { xsize, ysize };\n\terr = clEnqueueNDRangeKernel(ocl.commandQueue, kernel, 2, NULL, globalWorkSize, NULL, 0, NULL, NULL);\n\tif (CL_SUCCESS != err)\n\t{\n\t\tLogError(\"Error: clBuildProgram() for source program returned %s.\\n\", TranslateOpenCLError(err));\n\t}\n\terr = clFinish(ocl.commandQueue);\n\tif (CL_SUCCESS != err)\n\t{\n\t\tLogError(\"Error: clBuildProgram() for source program returned %s.\\n\", TranslateOpenCLError(err));\n\t}\n\n\tcl_float *resultPtr = (cl_float *)clEnqueueMapBuffer(ocl.commandQueue, ocl.dstMem, true, CL_MAP_READ, 0, sizeof(cl_float) * xsize * ysize, 0, NULL, NULL, &err);\n\tif (CL_SUCCESS != err)\n\t{\n\t\tLogError(\"Error: clEnqueueMapBuffer returned %s\\n\", TranslateOpenCLError(err));\n\t}\n\terr = clFinish(ocl.commandQueue);\n\tif (CL_SUCCESS != err)\n\t{\n\t\tLogError(\"Error: clFinish returned %s\\n\", TranslateOpenCLError(err));\n\t}\n\n\tmemcpy(values, resultPtr, sizeof(cl_float) * xsize * ysize);\n}\n\nvoid clConvolution(size_t xsize, size_t ysize,\n\tsize_t xstep,\n\tsize_t len, size_t offset,\n\tconst float* multipliers,\n\tconst float* inp,\n\tfloat border_ratio,\n\tfloat* result)\n{\n\tcl_int err = CL_SUCCESS;\n\tocl_args_d_t &ocl = getOcl();\n\n\tsize_t oxsize = xsize \/ xstep;\n\n\tocl.allocA(sizeof(cl_float) * len);\n\tocl.allocB(sizeof(cl_float) * xsize * ysize);\n\tocl.allocC(sizeof(cl_float) * oxsize * ysize);\n\n\tmemcpy(ocl.inputA, multipliers, sizeof(cl_float) * len);\n\tmemcpy(ocl.inputB, inp, sizeof(cl_float) * xsize * ysize);\n\n\tcl_int clxsize = xsize;\n\tcl_int clxstep = xstep;\n\tcl_int cllen = len;\n\tcl_int cloffset = offset;\n\tcl_float clborder_ratio = border_ratio;\n\n\tcl_kernel kernel = ocl.kernel[KERNEL_CONVOLUTION];\n\tclSetKernelArg(kernel, 0, sizeof(cl_mem), (void*)&ocl.srcA);\n\tclSetKernelArg(kernel, 1, sizeof(cl_mem), (void*)&ocl.srcB);\n\tclSetKernelArg(kernel, 2, sizeof(cl_mem), (void*)&ocl.dstMem);\n\tclSetKernelArg(kernel, 3, sizeof(cl_int), (void*)&clxsize);\n\tclSetKernelArg(kernel, 4, sizeof(cl_int), (void*)&clxstep);\n\tclSetKernelArg(kernel, 5, sizeof(cl_int), (void*)&cllen);\n\tclSetKernelArg(kernel, 6, sizeof(cl_int), (void*)&cloffset);\n\tclSetKernelArg(kernel, 7, sizeof(cl_float), (void*)&clborder_ratio);\n\n\tsize_t globalWorkSize[2] = { xsize \/ xstep, ysize };\n\terr = clEnqueueNDRangeKernel(ocl.commandQueue, kernel, 2, NULL, globalWorkSize, NULL, 0, NULL, NULL);\n\tif (CL_SUCCESS != err)\n\t{\n\t\tLogError(\"Error: clBuildProgram() for source program returned %s.\\n\", TranslateOpenCLError(err));\n\t}\n\terr = clFinish(ocl.commandQueue);\n\tif (CL_SUCCESS != err)\n\t{\n\t\tLogError(\"Error: clBuildProgram() for source program returned %s.\\n\", TranslateOpenCLError(err));\n\t}\n\n\tcl_float *resultPtr = (cl_float *)clEnqueueMapBuffer(ocl.commandQueue, ocl.dstMem, true, CL_MAP_READ, 0, sizeof(cl_float) * oxsize * ysize, 0, NULL, NULL, &err);\n\tif (CL_SUCCESS != err)\n\t{\n\t\tLogError(\"Error: clEnqueueMapBuffer returned %s\\n\", TranslateOpenCLError(err));\n\t}\n\terr = clFinish(ocl.commandQueue);\n\tif (CL_SUCCESS != err)\n\t{\n\t\tLogError(\"Error: clFinish returned %s\\n\", TranslateOpenCLError(err));\n\t}\n\n\tmemcpy(result, resultPtr, sizeof(cl_float) * oxsize * ysize);\n}<|endoftext|>"} {"text":"<commit_before>\/*\n * Author: Brendan Le Foll <brendan.le.foll@intel.com>\n * Contributions: Jon Trulson <jtrulson@ics.com>\n * Contributions: Thomas Ingleby <thomas.c.ingleby@intel.com>\n * Copyright (c) 2014 - 2015 Intel Corporation.\n *\n * Permission is hereby granted, free of charge, to any person obtaining\n * a copy of this software and associated documentation files (the\n * \"Software\"), to deal in the Software without restriction, including\n * without limitation the rights to use, copy, modify, merge, publish,\n * distribute, sublicense, and\/or sell copies of the Software, and to\n * permit persons to whom the Software is furnished to do so, subject to\n * the following conditions:\n *\n * The above copyright notice and this permission notice shall be\n * included in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n *\/\n\n#pragma once\n\n#include \"uart.h\"\n#include <stdexcept>\n#include <cstring>\n\nnamespace mraa\n{\n\n\/**\n * @brief API to UART (enabling only)\n *\n * This file defines the UART interface for libmraa\n *\n * @snippet Uart-example.cpp Interesting\n *\/\nclass Uart\n{\n public:\n \/**\n * Uart Constructor, takes a pin number which will map directly to the\n * linux uart number, this 'enables' the uart, nothing more\n *\n * @param uart the index of the uart set to use\n *\/\n Uart(int uart)\n {\n m_uart = mraa_uart_init(uart);\n\n if (m_uart == NULL) {\n throw std::invalid_argument(\"Error initialising UART\");\n }\n }\n\n \/**\n * Uart Constructor, takes a string to the path of the serial\n * interface that is needed.\n *\n * @param uart the index of the uart set to use\n *\/\n Uart(std::string path)\n {\n m_uart = mraa_uart_init_raw(path.c_str());\n\n if (m_uart == NULL) {\n throw std::invalid_argument(\"Error initialising UART\");\n }\n }\n\n \/**\n * Uart destructor\n *\/\n ~Uart()\n {\n mraa_uart_stop(m_uart);\n }\n\n \/**\n * Get string with tty device path within Linux\n * For example. Could point to \"\/dev\/ttyS0\"\n *\n * @return char pointer of device path\n *\/\n std::string\n getDevicePath()\n {\n std::string ret_val(mraa_uart_get_dev_path(m_uart));\n return ret_val;\n }\n\n \/**\n * Read bytes from the device into char* buffer\n *\n * @param data buffer pointer\n * @param length maximum size of buffer\n * @return numbers of bytes read\n *\/\n int\n read(char* data, int length)\n {\n return mraa_uart_read(m_uart, data, (size_t) length);\n }\n\n \/**\n * Write bytes in String object to a device\n *\n * @param data buffer pointer\n * @param length maximum size of buffer\n * @return the number of bytes written, or -1 if an error occurred\n *\/\n int\n write(const char* data, int length)\n {\n return mraa_uart_write(m_uart, data, (size_t) length);\n }\n\n \/**\n * Read bytes from the device into a String object\n *\n * @param length to read\n * @return string of data\n *\/\n std::string\n readStr(int length)\n {\n char* data = (char*) malloc(sizeof(char) * length);\n int v = mraa_uart_read(m_uart, data, (size_t) length);\n std::string ret(data, v);\n free(data);\n return ret;\n }\n\n \/**\n * Write bytes in String object to a device\n *\n * @param string to write\n * @return the number of bytes written, or -1 if an error occurred\n *\/\n int\n writeStr(std::string data)\n {\n \/\/ this is data.length() not +1 because we want to avoid the '\\0' char\n return mraa_uart_write(m_uart, data.c_str(), (data.length()));\n }\n\n \/**\n * Check to see if data is available on the device for reading\n *\n * @param millis number of milliseconds to wait, or 0 to return immediately\n * @return true if there is data available to read, false otherwise\n *\/\n bool\n dataAvailable(unsigned int millis = 0)\n {\n if (mraa_uart_data_available(m_uart, millis))\n return true;\n else\n return false;\n }\n\n \/**\n * Flush the outbound data.\n * Blocks until complete.\n *\n * @return Result of operation\n *\/\n Result\n flush()\n {\n return (Result) mraa_uart_flush(m_uart);\n }\n\n \/**\n * Set the baudrate.\n * Takes an int and will attempt to decide what baudrate is\n * to be used on the UART hardware.\n *\n * @param baud unsigned int of baudrate i.e. 9600\n * @return Result of operation\n *\/\n Result\n setBaudRate(unsigned int baud)\n {\n return (Result) mraa_uart_set_baudrate(m_uart, baud);\n }\n\n \/**\n * Set the transfer mode\n * For example setting the mode to 8N1 would be\n * \"dev.setMode(8,UART_PARITY_NONE , 1)\"\n *\n * @param bytesize data bits\n * @param parity Parity bit setting\n * @param stopbits stop bits\n * @return Result of operation\n *\/\n Result\n setMode(int bytesize, UartParity parity, int stopbits)\n {\n return (Result) mraa_uart_set_mode(m_uart, bytesize, (mraa_uart_parity_t) parity, stopbits);\n }\n\n \/**\n * Set the flowcontrol\n *\n * @param xonxoff XON\/XOFF Software flow control.\n * @param rtscts RTS\/CTS out of band hardware flow control\n * @return Result of operation\n *\/\n Result\n setFlowcontrol(bool xonxoff, bool rtscts)\n {\n return (Result) mraa_uart_set_flowcontrol(m_uart, xonxoff, rtscts);\n }\n\n \/**\n * Set the timeout for read and write operations\n * <= 0 will disable that timeout\n *\n * @param read read timeout\n * @param write write timeout\n * @param interchar inbetween char timeout\n * @return Result of operation\n *\/\n Result\n setTimeout(int read, int write, int interchar)\n {\n return (Result) mraa_uart_set_timeout(m_uart, read, write, interchar);\n }\n\n private:\n mraa_uart_context m_uart;\n};\n}\n<commit_msg>uart.hpp: Added missing include for types.hpp<commit_after>\/*\n * Author: Brendan Le Foll <brendan.le.foll@intel.com>\n * Contributions: Jon Trulson <jtrulson@ics.com>\n * Contributions: Thomas Ingleby <thomas.c.ingleby@intel.com>\n * Copyright (c) 2014 - 2015 Intel Corporation.\n *\n * Permission is hereby granted, free of charge, to any person obtaining\n * a copy of this software and associated documentation files (the\n * \"Software\"), to deal in the Software without restriction, including\n * without limitation the rights to use, copy, modify, merge, publish,\n * distribute, sublicense, and\/or sell copies of the Software, and to\n * permit persons to whom the Software is furnished to do so, subject to\n * the following conditions:\n *\n * The above copyright notice and this permission notice shall be\n * included in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n *\/\n\n#pragma once\n\n#include \"uart.h\"\n#include \"types.hpp\"\n#include <stdexcept>\n#include <cstring>\n\nnamespace mraa\n{\n\n\/**\n * @brief API to UART (enabling only)\n *\n * This file defines the UART interface for libmraa\n *\n * @snippet Uart-example.cpp Interesting\n *\/\nclass Uart\n{\n public:\n \/**\n * Uart Constructor, takes a pin number which will map directly to the\n * linux uart number, this 'enables' the uart, nothing more\n *\n * @param uart the index of the uart set to use\n *\/\n Uart(int uart)\n {\n m_uart = mraa_uart_init(uart);\n\n if (m_uart == NULL) {\n throw std::invalid_argument(\"Error initialising UART\");\n }\n }\n\n \/**\n * Uart Constructor, takes a string to the path of the serial\n * interface that is needed.\n *\n * @param uart the index of the uart set to use\n *\/\n Uart(std::string path)\n {\n m_uart = mraa_uart_init_raw(path.c_str());\n\n if (m_uart == NULL) {\n throw std::invalid_argument(\"Error initialising UART\");\n }\n }\n\n \/**\n * Uart destructor\n *\/\n ~Uart()\n {\n mraa_uart_stop(m_uart);\n }\n\n \/**\n * Get string with tty device path within Linux\n * For example. Could point to \"\/dev\/ttyS0\"\n *\n * @return char pointer of device path\n *\/\n std::string\n getDevicePath()\n {\n std::string ret_val(mraa_uart_get_dev_path(m_uart));\n return ret_val;\n }\n\n \/**\n * Read bytes from the device into char* buffer\n *\n * @param data buffer pointer\n * @param length maximum size of buffer\n * @return numbers of bytes read\n *\/\n int\n read(char* data, int length)\n {\n return mraa_uart_read(m_uart, data, (size_t) length);\n }\n\n \/**\n * Write bytes in String object to a device\n *\n * @param data buffer pointer\n * @param length maximum size of buffer\n * @return the number of bytes written, or -1 if an error occurred\n *\/\n int\n write(const char* data, int length)\n {\n return mraa_uart_write(m_uart, data, (size_t) length);\n }\n\n \/**\n * Read bytes from the device into a String object\n *\n * @param length to read\n * @return string of data\n *\/\n std::string\n readStr(int length)\n {\n char* data = (char*) malloc(sizeof(char) * length);\n int v = mraa_uart_read(m_uart, data, (size_t) length);\n std::string ret(data, v);\n free(data);\n return ret;\n }\n\n \/**\n * Write bytes in String object to a device\n *\n * @param string to write\n * @return the number of bytes written, or -1 if an error occurred\n *\/\n int\n writeStr(std::string data)\n {\n \/\/ this is data.length() not +1 because we want to avoid the '\\0' char\n return mraa_uart_write(m_uart, data.c_str(), (data.length()));\n }\n\n \/**\n * Check to see if data is available on the device for reading\n *\n * @param millis number of milliseconds to wait, or 0 to return immediately\n * @return true if there is data available to read, false otherwise\n *\/\n bool\n dataAvailable(unsigned int millis = 0)\n {\n if (mraa_uart_data_available(m_uart, millis))\n return true;\n else\n return false;\n }\n\n \/**\n * Flush the outbound data.\n * Blocks until complete.\n *\n * @return Result of operation\n *\/\n Result\n flush()\n {\n return (Result) mraa_uart_flush(m_uart);\n }\n\n \/**\n * Set the baudrate.\n * Takes an int and will attempt to decide what baudrate is\n * to be used on the UART hardware.\n *\n * @param baud unsigned int of baudrate i.e. 9600\n * @return Result of operation\n *\/\n Result\n setBaudRate(unsigned int baud)\n {\n return (Result) mraa_uart_set_baudrate(m_uart, baud);\n }\n\n \/**\n * Set the transfer mode\n * For example setting the mode to 8N1 would be\n * \"dev.setMode(8,UART_PARITY_NONE , 1)\"\n *\n * @param bytesize data bits\n * @param parity Parity bit setting\n * @param stopbits stop bits\n * @return Result of operation\n *\/\n Result\n setMode(int bytesize, UartParity parity, int stopbits)\n {\n return (Result) mraa_uart_set_mode(m_uart, bytesize, (mraa_uart_parity_t) parity, stopbits);\n }\n\n \/**\n * Set the flowcontrol\n *\n * @param xonxoff XON\/XOFF Software flow control.\n * @param rtscts RTS\/CTS out of band hardware flow control\n * @return Result of operation\n *\/\n Result\n setFlowcontrol(bool xonxoff, bool rtscts)\n {\n return (Result) mraa_uart_set_flowcontrol(m_uart, xonxoff, rtscts);\n }\n\n \/**\n * Set the timeout for read and write operations\n * <= 0 will disable that timeout\n *\n * @param read read timeout\n * @param write write timeout\n * @param interchar inbetween char timeout\n * @return Result of operation\n *\/\n Result\n setTimeout(int read, int write, int interchar)\n {\n return (Result) mraa_uart_set_timeout(m_uart, read, write, interchar);\n }\n\n private:\n mraa_uart_context m_uart;\n};\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/---------------------------------------------------------------------------\n\/\/\/ \\file es\/storage.hpp\n\/\/\/ \\brief The entity\/component data store\n\/\/\n\/\/ Copyright 2013, nocte@hippie.nu Released under the MIT License.\n\/\/---------------------------------------------------------------------------\n#include \"storage.hpp\"\n\nnamespace es {\n\nstorage::storage()\n : next_id_(0)\n{\n component_offsets_.push_back(0);\n}\n\nstorage::~storage()\n{\n for (auto i (entities_.begin()); i != entities_.end(); ++i)\n call_destructors(i);\n}\n\nstorage::component_id\nstorage::find_component (const std::string& name) const\n{\n auto found (std::find(components_.begin(), components_.end(), name));\n if (found == components_.end())\n throw std::logic_error(\"component does not exist\");\n\n return std::distance(components_.begin(), found);\n}\n\nentity\nstorage::new_entity()\n{\n auto result (entities_.emplace(next_id_, elem()).first);\n if (on_new_entity)\n on_new_entity(result);\n\n ++next_id_;\n return next_id_ - 1;\n}\n\nstorage::iterator\nstorage::make (uint32_t id)\n{\n if (next_id_ <= id)\n next_id_ = id + 1;\n\n auto result (entities_.emplace(id, elem()));\n if (result.second && on_new_entity)\n on_new_entity(result.first);\n\n return result.first;\n}\n\nstd::pair<entity, entity>\nstorage::new_entities (size_t count)\n{\n auto range_begin (next_id_);\n for (; count > 0; --count)\n entities_[next_id_++];\n\n return std::make_pair(range_begin, next_id_);\n}\n\nentity\nstorage::clone_entity (iterator f)\n{ \n auto cloned (entities_.emplace(next_id_, f->second).first);\n elem& e (cloned->second);\n\n \/\/ Quick check if we need to make deep copies\n if ((e.components & flat_mask_).any())\n {\n size_t off (0);\n for (int c_id (0); c_id < 64 && off < e.data.size(); ++c_id)\n {\n if (e.components[c_id])\n {\n if (!components_[c_id].is_flat())\n {\n auto ptr (reinterpret_cast<placeholder*>(&*e.data.begin() + off));\n ptr->clone()->move_to(e.data.begin() + off);\n }\n off += components_[c_id].size();\n }\n }\n }\n if (on_new_entity)\n on_new_entity(cloned);\n\n ++next_id_;\n return next_id_ - 1;\n}\n\nstorage::iterator\nstorage::find (entity en)\n{\n auto found (entities_.find(en));\n if (found == entities_.end())\n throw std::logic_error(\"unknown entity\");\n\n return found;\n}\n\nstorage::const_iterator\nstorage::find (entity en) const\n{\n auto found (entities_.find(en));\n if (found == entities_.end())\n throw std::logic_error(\"unknown entity\");\n\n return found;\n}\n\nsize_t\nstorage::size() const\n{\n return entities_.size();\n}\n\nbool\nstorage::delete_entity (entity en)\n{\n auto found (find(en));\n if (found != entities_.end())\n {\n delete_entity(found);\n return true;\n }\n return false;\n}\n\nvoid\nstorage::delete_entity (iterator f)\n{\n if (on_deleted_entity)\n on_deleted_entity(f);\n\n call_destructors(f);\n entities_.erase(f);\n}\n\nvoid\nstorage::remove_component_from_entity (iterator en, component_id c)\n{\n auto& e (en->second);\n if (!e.components[c])\n return;\n\n size_t off (offset(e, c));\n auto& comp_info (components_[c]);\n if (!comp_info.is_flat())\n {\n auto ptr (reinterpret_cast<placeholder*>(&*e.data.begin() + off));\n if (ptr)\n ptr->~placeholder();\n }\n auto o (e.data.begin() + off);\n e.data.erase(o, o + comp_info.size());\n e.components.reset(c);\n e.dirty = true;\n}\n\nbool\nstorage::entity_has_component (iterator en, component_id c) const\n{\n return c < components_.size() && en->second.components.test(c);\n}\n\nsize_t\nstorage::offset (const elem& e, component_id c) const\n{\n assert(c < components_.size());\n assert((c & cache_mask) < component_offsets_.size());\n\n size_t result (component_offsets_[((1 << c) - 1) & e.components.to_ulong() & cache_mask]);\n\n for (component_id search (cache_size); search < c; ++search)\n {\n if (e.components[search])\n result += components_[search].size();\n }\n\n return result;\n}\n\nbool\nstorage::check_dirty (iterator en)\n{\n return en->second.dirty;\n}\n\nbool\nstorage::check_dirty_and_clear (iterator en)\n{\n bool result (check_dirty(en));\n en->second.dirty = false;\n return result;\n}\n\nvoid\nstorage::serialize (const_iterator en, std::vector<char>& buffer) const\n{\n auto& e (en->second);\n buffer.reserve(8 + e.data.size());\n buffer.resize(8);\n\n *(reinterpret_cast<uint64_t*>(&buffer[0])) = e.components.to_ullong();\n\n auto first (e.data.begin());\n auto last (first);\n\n for (size_t i (0); i < components_.size(); ++i)\n {\n if (!e.components[i])\n continue;\n\n auto& c (components_[i]);\n if (c.is_flat())\n {\n \/\/ As long as we have a flat memory layout, just move the\n \/\/ end of the range.\n std::advance(last, c.size());\n }\n else\n {\n \/\/ If not, write the current range to the buffer.\n buffer.insert(buffer.end(), first, last);\n \/\/ Then serialize the object using the function the caller\n \/\/ provided.\n auto ptr (reinterpret_cast<const component::placeholder*>(&*last));\n ptr->serialize(buffer);\n \/\/ Reset the range.\n std::advance(last, c.size());\n first = last;\n }\n\n if (last >= e.data.end())\n break;\n }\n \/\/ Write the last bit after we're done.\n assert(last == e.data.end());\n buffer.insert(buffer.end(), first, e.data.end());\n}\n\nvoid\nstorage::deserialize (iterator en, const std::vector<char>& buffer)\n{\n auto first (buffer.begin());\n auto& e (en->second);\n\n call_destructors(en);\n e.data.clear();\n e.components = *(reinterpret_cast<const uint64_t*>(&*first));\n\n std::advance(first, 8);\n auto last (first);\n\n for (size_t i (0); i < components_.size(); ++i)\n {\n if (!e.components[i])\n continue;\n\n auto& c (components_[i]);\n if (c.is_flat())\n {\n \/\/ As long as we have a flat memory layout, just move the\n \/\/ end of the range.\n std::advance(last, c.size());\n }\n else\n {\n \/\/ If not, write the current range to the entity data.\n e.data.insert(e.data.end(), first, last);\n \/\/ Create a new object for the component and deserialize the\n \/\/ data using the function the caller provided.\n auto ptr (c.clone());\n last = ptr->deserialize(last, buffer.end());\n first = last;\n \/\/ Move the object to the buffer.\n auto offset (e.data.size());\n e.data.resize(offset + c.size());\n ptr->move_to(e.data.begin() + offset);\n }\n\n if (last >= buffer.end())\n break;\n }\n \/\/ Write the last bit after we're done.\n assert(last == buffer.end());\n e.data.insert(e.data.end(), first, buffer.end());\n}\n\nvoid\nstorage::call_destructors(iterator i) const\n{\n elem& e (i->second);\n\n \/\/ Quick check if we'll have to call any destructors.\n if ((e.components & flat_mask_).any())\n {\n size_t off (0);\n for (int search (0); search < 64 && off < e.data.size(); ++search)\n {\n if (e.components[search])\n {\n if (!components_[search].is_flat())\n {\n auto ptr (reinterpret_cast<placeholder*>(&*e.data.begin() + off));\n ptr->~placeholder();\n }\n off += components_[search].size();\n }\n }\n }\n}\n\n} \/\/ namespace es\n<commit_msg>Fixes for Launchpad.net<commit_after>\/\/---------------------------------------------------------------------------\n\/\/\/ \\file es\/storage.hpp\n\/\/\/ \\brief The entity\/component data store\n\/\/\n\/\/ Copyright 2013, nocte@hippie.nu Released under the MIT License.\n\/\/---------------------------------------------------------------------------\n#include \"storage.hpp\"\n\nnamespace es {\n\nstorage::storage()\n : next_id_(0)\n{\n component_offsets_.push_back(0);\n}\n\nstorage::~storage()\n{\n for (auto i (entities_.begin()); i != entities_.end(); ++i)\n call_destructors(i);\n}\n\nstorage::component_id\nstorage::find_component (const std::string& name) const\n{\n auto found (std::find(components_.begin(), components_.end(), name));\n if (found == components_.end())\n throw std::logic_error(\"component does not exist\");\n\n return std::distance(components_.begin(), found);\n}\n\nentity\nstorage::new_entity()\n{\n auto result (entities_.insert(std::make_pair(next_id_, elem())).first);\n if (on_new_entity)\n on_new_entity(result);\n\n ++next_id_;\n return next_id_ - 1;\n}\n\nstorage::iterator\nstorage::make (uint32_t id)\n{\n if (next_id_ <= id)\n next_id_ = id + 1;\n\n auto result (entities_.insert(std::make_pair(next_id_, elem())));\n if (result.second && on_new_entity)\n on_new_entity(result.first);\n\n return result.first;\n}\n\nstd::pair<entity, entity>\nstorage::new_entities (size_t count)\n{\n auto range_begin (next_id_);\n for (; count > 0; --count)\n entities_[next_id_++];\n\n return std::make_pair(range_begin, next_id_);\n}\n\nentity\nstorage::clone_entity (iterator f)\n{ \n auto cloned (entities_.insert(std::make_pair(next_id_, f->second)).first);\n elem& e (cloned->second);\n\n \/\/ Quick check if we need to make deep copies\n if ((e.components & flat_mask_).any())\n {\n size_t off (0);\n for (int c_id (0); c_id < 64 && off < e.data.size(); ++c_id)\n {\n if (e.components[c_id])\n {\n if (!components_[c_id].is_flat())\n {\n auto ptr (reinterpret_cast<placeholder*>(&*e.data.begin() + off));\n ptr->clone()->move_to(e.data.begin() + off);\n }\n off += components_[c_id].size();\n }\n }\n }\n if (on_new_entity)\n on_new_entity(cloned);\n\n ++next_id_;\n return next_id_ - 1;\n}\n\nstorage::iterator\nstorage::find (entity en)\n{\n auto found (entities_.find(en));\n if (found == entities_.end())\n throw std::logic_error(\"unknown entity\");\n\n return found;\n}\n\nstorage::const_iterator\nstorage::find (entity en) const\n{\n auto found (entities_.find(en));\n if (found == entities_.end())\n throw std::logic_error(\"unknown entity\");\n\n return found;\n}\n\nsize_t\nstorage::size() const\n{\n return entities_.size();\n}\n\nbool\nstorage::delete_entity (entity en)\n{\n auto found (find(en));\n if (found != entities_.end())\n {\n delete_entity(found);\n return true;\n }\n return false;\n}\n\nvoid\nstorage::delete_entity (iterator f)\n{\n if (on_deleted_entity)\n on_deleted_entity(f);\n\n call_destructors(f);\n entities_.erase(f);\n}\n\nvoid\nstorage::remove_component_from_entity (iterator en, component_id c)\n{\n auto& e (en->second);\n if (!e.components[c])\n return;\n\n size_t off (offset(e, c));\n auto& comp_info (components_[c]);\n if (!comp_info.is_flat())\n {\n auto ptr (reinterpret_cast<placeholder*>(&*e.data.begin() + off));\n if (ptr)\n ptr->~placeholder();\n }\n auto o (e.data.begin() + off);\n e.data.erase(o, o + comp_info.size());\n e.components.reset(c);\n e.dirty = true;\n}\n\nbool\nstorage::entity_has_component (iterator en, component_id c) const\n{\n return c < components_.size() && en->second.components.test(c);\n}\n\nsize_t\nstorage::offset (const elem& e, component_id c) const\n{\n assert(c < components_.size());\n assert((c & cache_mask) < component_offsets_.size());\n\n size_t result (component_offsets_[((1 << c) - 1) & e.components.to_ulong() & cache_mask]);\n\n for (component_id search (cache_size); search < c; ++search)\n {\n if (e.components[search])\n result += components_[search].size();\n }\n\n return result;\n}\n\nbool\nstorage::check_dirty (iterator en)\n{\n return en->second.dirty;\n}\n\nbool\nstorage::check_dirty_and_clear (iterator en)\n{\n bool result (check_dirty(en));\n en->second.dirty = false;\n return result;\n}\n\nvoid\nstorage::serialize (const_iterator en, std::vector<char>& buffer) const\n{\n auto& e (en->second);\n buffer.reserve(8 + e.data.size());\n buffer.resize(8);\n\n *(reinterpret_cast<uint64_t*>(&buffer[0])) = e.components.to_ullong();\n\n auto first (e.data.begin());\n auto last (first);\n\n for (size_t i (0); i < components_.size(); ++i)\n {\n if (!e.components[i])\n continue;\n\n auto& c (components_[i]);\n if (c.is_flat())\n {\n \/\/ As long as we have a flat memory layout, just move the\n \/\/ end of the range.\n std::advance(last, c.size());\n }\n else\n {\n \/\/ If not, write the current range to the buffer.\n buffer.insert(buffer.end(), first, last);\n \/\/ Then serialize the object using the function the caller\n \/\/ provided.\n auto ptr (reinterpret_cast<const component::placeholder*>(&*last));\n ptr->serialize(buffer);\n \/\/ Reset the range.\n std::advance(last, c.size());\n first = last;\n }\n\n if (last >= e.data.end())\n break;\n }\n \/\/ Write the last bit after we're done.\n assert(last == e.data.end());\n buffer.insert(buffer.end(), first, e.data.end());\n}\n\nvoid\nstorage::deserialize (iterator en, const std::vector<char>& buffer)\n{\n auto first (buffer.begin());\n auto& e (en->second);\n\n call_destructors(en);\n e.data.clear();\n e.components = *(reinterpret_cast<const uint64_t*>(&*first));\n\n std::advance(first, 8);\n auto last (first);\n\n for (size_t i (0); i < components_.size(); ++i)\n {\n if (!e.components[i])\n continue;\n\n auto& c (components_[i]);\n if (c.is_flat())\n {\n \/\/ As long as we have a flat memory layout, just move the\n \/\/ end of the range.\n std::advance(last, c.size());\n }\n else\n {\n \/\/ If not, write the current range to the entity data.\n e.data.insert(e.data.end(), first, last);\n \/\/ Create a new object for the component and deserialize the\n \/\/ data using the function the caller provided.\n auto ptr (c.clone());\n last = ptr->deserialize(last, buffer.end());\n first = last;\n \/\/ Move the object to the buffer.\n auto offset (e.data.size());\n e.data.resize(offset + c.size());\n ptr->move_to(e.data.begin() + offset);\n }\n\n if (last >= buffer.end())\n break;\n }\n \/\/ Write the last bit after we're done.\n assert(last == buffer.end());\n e.data.insert(e.data.end(), first, buffer.end());\n}\n\nvoid\nstorage::call_destructors(iterator i) const\n{\n elem& e (i->second);\n\n \/\/ Quick check if we'll have to call any destructors.\n if ((e.components & flat_mask_).any())\n {\n size_t off (0);\n for (int search (0); search < 64 && off < e.data.size(); ++search)\n {\n if (e.components[search])\n {\n if (!components_[search].is_flat())\n {\n auto ptr (reinterpret_cast<placeholder*>(&*e.data.begin() + off));\n ptr->~placeholder();\n }\n off += components_[search].size();\n }\n }\n }\n}\n\n} \/\/ namespace es\n<|endoftext|>"} {"text":"<commit_before>#include \"clay.hpp\"\n\nvector<OverloadPtr> typeOverloads;\n\nvoid addTypeOverload(OverloadPtr x)\n{\n typeOverloads.insert(typeOverloads.begin(), x);\n}\n\nvoid initTypeOverloads(TypePtr t)\n{\n assert(!t->overloadsInitialized);\n\n for (unsigned i = 0; i < typeOverloads.size(); ++i) {\n OverloadPtr x = typeOverloads[i];\n EnvPtr env = new Env(x->env);\n const vector<IdentifierPtr> &pvars = x->code->patternVars;\n for (unsigned i = 0; i < pvars.size(); ++i) {\n PatternCellPtr cell = new PatternCell(pvars[i], NULL);\n addLocal(env, pvars[i], cell.ptr());\n }\n PatternPtr pattern = evaluatePattern(x->target, env);\n if (unify(pattern, t.ptr()))\n t->overloads.insert(t->overloads.begin(), x);\n }\n\n t->overloadsInitialized = true;\n}\n\nvoid initBuiltinIsStaticFlags(TypePtr t) {\n switch (t->typeKind) {\n\n case ARRAY_TYPE : {\n ArrayType *x = (ArrayType *)t.ptr();\n FlagsMapEntry &flags = lookupFlagsMapEntry(t.ptr(), x->size);\n assert(!flags.initialized);\n flags.initialized = true;\n flags.isStaticFlags.assign(x->size, false);\n break;\n }\n\n case TUPLE_TYPE : {\n TupleType *x = (TupleType *)t.ptr();\n FlagsMapEntry &flags =\n lookupFlagsMapEntry(t.ptr(), x->elementTypes.size());\n assert(!flags.initialized);\n flags.initialized = true;\n flags.isStaticFlags.assign(x->elementTypes.size(), false);\n break;\n }\n\n case RECORD_TYPE : {\n RecordType *x = (RecordType *)t.ptr();\n const vector<TypePtr> &fieldTypes = recordFieldTypes(x);\n FlagsMapEntry &flags = lookupFlagsMapEntry(t.ptr(), fieldTypes.size());\n assert(!flags.initialized);\n flags.initialized = true;\n flags.isStaticFlags.assign(fieldTypes.size(), false);\n break;\n }\n\n }\n}\n\nvoid verifyBuiltinConstructor(TypePtr t,\n const vector<bool> &isStaticFlags,\n const vector<ObjectPtr> &argsKey,\n const vector<LocationPtr> &argLocations)\n{\n switch (t->typeKind) {\n\n case ARRAY_TYPE : {\n ArrayType *x = (ArrayType *)t.ptr();\n if (x->size != (int)isStaticFlags.size())\n error(\"incorrect no. of arguments\");\n for (unsigned i = 0; i < isStaticFlags.size(); ++i) {\n assert(isStaticFlags[i]);\n assert(argsKey[i]->objKind == TYPE);\n TypePtr y = (Type *)argsKey[i].ptr();\n if (y != x->elementType) {\n LocationContext loc(argLocations[i]);\n error(\"type mismatch\");\n }\n }\n break;\n }\n\n case TUPLE_TYPE : {\n TupleType *x = (TupleType *)t.ptr();\n if (x->elementTypes.size() != isStaticFlags.size())\n error(\"incorrect no. of arguments\");\n for (unsigned i = 0; i < isStaticFlags.size(); ++i) {\n assert(isStaticFlags[i]);\n assert(argsKey[i]->objKind == TYPE);\n TypePtr y = (Type *)argsKey[i].ptr();\n if (y != x->elementTypes[i]) {\n LocationContext loc(argLocations[i]);\n error(\"type mismatch\");\n }\n }\n break;\n }\n\n case RECORD_TYPE : {\n RecordType *x = (RecordType *)t.ptr();\n const vector<TypePtr> &fieldTypes = recordFieldTypes(x);\n if (fieldTypes.size() != isStaticFlags.size())\n error(\"incorrect no. of arguments\");\n for (unsigned i = 0; i < isStaticFlags.size(); ++i) {\n assert(!isStaticFlags[i]);\n assert(argsKey[i]->objKind == TYPE);\n TypePtr y = (Type *)argsKey[i].ptr();\n if (y != fieldTypes[i]) {\n LocationContext loc(argLocations[i]);\n error(\"type mismatch\");\n }\n }\n break;\n }\n\n default :\n error(\"no matching constructor found\");\n\n }\n}\n<commit_msg>fixed silly bug in 'initTypeOverloads'.<commit_after>#include \"clay.hpp\"\n\nvector<OverloadPtr> typeOverloads;\n\nvoid addTypeOverload(OverloadPtr x)\n{\n typeOverloads.insert(typeOverloads.begin(), x);\n}\n\nvoid initTypeOverloads(TypePtr t)\n{\n assert(!t->overloadsInitialized);\n\n for (unsigned i = 0; i < typeOverloads.size(); ++i) {\n OverloadPtr x = typeOverloads[i];\n EnvPtr env = new Env(x->env);\n const vector<IdentifierPtr> &pvars = x->code->patternVars;\n for (unsigned i = 0; i < pvars.size(); ++i) {\n PatternCellPtr cell = new PatternCell(pvars[i], NULL);\n addLocal(env, pvars[i], cell.ptr());\n }\n PatternPtr pattern = evaluatePattern(x->target, env);\n if (unify(pattern, t.ptr()))\n t->overloads.push_back(x);\n }\n\n t->overloadsInitialized = true;\n}\n\nvoid initBuiltinIsStaticFlags(TypePtr t) {\n switch (t->typeKind) {\n\n case ARRAY_TYPE : {\n ArrayType *x = (ArrayType *)t.ptr();\n FlagsMapEntry &flags = lookupFlagsMapEntry(t.ptr(), x->size);\n assert(!flags.initialized);\n flags.initialized = true;\n flags.isStaticFlags.assign(x->size, false);\n break;\n }\n\n case TUPLE_TYPE : {\n TupleType *x = (TupleType *)t.ptr();\n FlagsMapEntry &flags =\n lookupFlagsMapEntry(t.ptr(), x->elementTypes.size());\n assert(!flags.initialized);\n flags.initialized = true;\n flags.isStaticFlags.assign(x->elementTypes.size(), false);\n break;\n }\n\n case RECORD_TYPE : {\n RecordType *x = (RecordType *)t.ptr();\n const vector<TypePtr> &fieldTypes = recordFieldTypes(x);\n FlagsMapEntry &flags = lookupFlagsMapEntry(t.ptr(), fieldTypes.size());\n assert(!flags.initialized);\n flags.initialized = true;\n flags.isStaticFlags.assign(fieldTypes.size(), false);\n break;\n }\n\n }\n}\n\nvoid verifyBuiltinConstructor(TypePtr t,\n const vector<bool> &isStaticFlags,\n const vector<ObjectPtr> &argsKey,\n const vector<LocationPtr> &argLocations)\n{\n switch (t->typeKind) {\n\n case ARRAY_TYPE : {\n ArrayType *x = (ArrayType *)t.ptr();\n if (x->size != (int)isStaticFlags.size())\n error(\"incorrect no. of arguments\");\n for (unsigned i = 0; i < isStaticFlags.size(); ++i) {\n assert(isStaticFlags[i]);\n assert(argsKey[i]->objKind == TYPE);\n TypePtr y = (Type *)argsKey[i].ptr();\n if (y != x->elementType) {\n LocationContext loc(argLocations[i]);\n error(\"type mismatch\");\n }\n }\n break;\n }\n\n case TUPLE_TYPE : {\n TupleType *x = (TupleType *)t.ptr();\n if (x->elementTypes.size() != isStaticFlags.size())\n error(\"incorrect no. of arguments\");\n for (unsigned i = 0; i < isStaticFlags.size(); ++i) {\n assert(isStaticFlags[i]);\n assert(argsKey[i]->objKind == TYPE);\n TypePtr y = (Type *)argsKey[i].ptr();\n if (y != x->elementTypes[i]) {\n LocationContext loc(argLocations[i]);\n error(\"type mismatch\");\n }\n }\n break;\n }\n\n case RECORD_TYPE : {\n RecordType *x = (RecordType *)t.ptr();\n const vector<TypePtr> &fieldTypes = recordFieldTypes(x);\n if (fieldTypes.size() != isStaticFlags.size())\n error(\"incorrect no. of arguments\");\n for (unsigned i = 0; i < isStaticFlags.size(); ++i) {\n assert(!isStaticFlags[i]);\n assert(argsKey[i]->objKind == TYPE);\n TypePtr y = (Type *)argsKey[i].ptr();\n if (y != fieldTypes[i]) {\n LocationContext loc(argLocations[i]);\n error(\"type mismatch\");\n }\n }\n break;\n }\n\n default :\n error(\"no matching constructor found\");\n\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 2013-2014 Nicholas Corgan (n.corgan@gmail.com)\n *\n * Distributed under the MIT License (MIT) (See accompanying file LICENSE.txt\n * or copy at http:\/\/opensource.org\/licenses\/MIT)\n *\/\n\n#include <cstdio>\n\n#include <boost\/assign.hpp>\n#include <boost\/format.hpp>\n\n#include <pkmn\/enums.hpp>\n#include <pkmn\/paths.hpp>\n#include <pkmn\/database\/queries.hpp>\n#include <pkmn\/types\/prng.hpp>\n\n#include \"SQLiteCpp\/src\/SQLiteC++.h\"\n\n#include \"team_pokemon_modernimpl.hpp\"\n\nusing namespace std;\n\nnamespace pkmn\n{\n team_pokemon_modernimpl::team_pokemon_modernimpl(base_pokemon::sptr base, unsigned int game, unsigned int level,\n unsigned int move1, unsigned int move2,\n unsigned int move3, unsigned int move4): team_pokemon_impl(base,game,level,\n move1,move2,move3,move4)\n {\n \/\/Random individual values\n _ivHP = _rand_gen.lcrng_next(_generation) % 32;\n _ivATK = _rand_gen.lcrng_next(_generation) % 32;\n _ivDEF = _rand_gen.lcrng_next(_generation) % 32;\n _ivSPD = _rand_gen.lcrng_next(_generation) % 32;\n _ivSATK = _rand_gen.lcrng_next(_generation) % 32;\n _ivSDEF = _rand_gen.lcrng_next(_generation) % 32;\n\n \/*\n * Random effort values within following rules:\n * - Sum <= 510\n * - EV <= 255\n *\/\n _evHP = 256;\n _evATK = 256;\n _evDEF = 256;\n _evSPD = 256;\n _evSATK = 256;\n _evSDEF = 256;\n while((_evHP+_evATK+_evDEF+_evSPD+_evSATK+_evSDEF)>510 || _evHP>255 || _evATK>255 || _evDEF>255 || _evSPD>255 || _evSATK>255 || _evSDEF>255)\n {\n _evHP = _rand_gen.lcrng_next(_generation) % 256;\n _evATK = _rand_gen.lcrng_next(_generation) % 256;\n _evDEF = _rand_gen.lcrng_next(_generation) % 256;\n _evSPD = _rand_gen.lcrng_next(_generation) % 256;\n _evSATK = _rand_gen.lcrng_next(_generation) % 256;\n _evSDEF = _rand_gen.lcrng_next(_generation) % 256;\n }\n\n _gender = _determine_gender();\n _ability = _determine_ability();\n _ability = _determine_ability();\n\n _set_stats();\n }\n\n std::string team_pokemon_modernimpl::get_gender() const {return _gender;}\n\n std::string team_pokemon_modernimpl::get_nature() const {return _nature;}\n\n std::string team_pokemon_modernimpl::get_ability() const {return _ability;}\n\n bool team_pokemon_modernimpl::is_shiny() const\n {\n int p1, p2, E, F;\n p1 = (_personality & 0xFFFF0000) >> 16;\n p2 = _personality & 0xFFFF;\n E = _tid.public_id ^ _tid.secret_id;\n F = p1 ^ p2;\n return (E ^ F) < 8;\n }\n\n pkmn::dict<std::string, unsigned int> team_pokemon_modernimpl::get_stats() const\n {\n pkmn::dict<std::string, unsigned int> stats;\n stats[\"HP\"] = _HP;\n stats[\"Attack\"] = _ATK;\n stats[\"Defense\"] = _DEF;\n stats[\"Special Attack\"] = _SATK;\n stats[\"Special Defense\"] = _SDEF;\n stats[\"Speed\"] = _SPD;\n\n return stats;\n }\n\n pkmn::dict<std::string, unsigned int> team_pokemon_modernimpl::get_EVs() const\n {\n pkmn::dict<std::string, unsigned int> EVs;\n EVs[\"HP\"] = _evHP;\n EVs[\"Attack\"] = _evATK;\n EVs[\"Defense\"] = _evDEF;\n EVs[\"Special Attack\"] = _evSATK;\n EVs[\"Special Defense\"] = _evSDEF;\n EVs[\"Speed\"] = _evSPD;\n \n return EVs;\n }\n\n pkmn::dict<std::string, unsigned int> team_pokemon_modernimpl::get_IVs() const\n {\n pkmn::dict<std::string, unsigned int> IVs;\n IVs[\"HP\"] = _ivHP;\n IVs[\"Attack\"] = _ivATK;\n IVs[\"Defense\"] = _ivDEF;\n IVs[\"Special Attack\"] = _ivSATK;\n IVs[\"Special Defense\"] = _ivSDEF;\n IVs[\"Speed\"] = _ivSPD;\n\n return IVs;\n }\n\n void team_pokemon_modernimpl::set_personality(unsigned int personality)\n {\n _personality = personality;\n _ability = _determine_ability();\n _gender = _determine_gender();\n _ability = _determine_ability();\n }\n\n void team_pokemon_modernimpl::set_gender(std::string gender)\n {\n if(gender == \"Male\" or gender == \"Female\") _gender = gender;\n }\n\n void team_pokemon_modernimpl::set_nature(std::string nature)\n {\n \/\/Search for given nature in database\n std::string query_string = str(boost::format(\"SELECT nature_id FROM nature_names WHERE name='%s'\")\n % nature.c_str());\n SQLite::Statement nature_names_query(_db, query_string.c_str());\n if(nature_names_query.executeStep())\n {\n _nature = nature;\n _set_stats();\n return;\n }\n\n \/\/If not in nature_names, check in abilities\n query_string = str(boost::format(\"Select id FROM natures WHERE identifier='%s'\")\n % nature);\n SQLite::Statement natures_query(_db, query_string.c_str());\n if(natures_query.executeStep())\n {\n nature[0] = tolower(nature[0]);\n _nature = nature;\n _set_stats();\n }\n }\n \n void team_pokemon_modernimpl::set_ability(std::string ability)\n {\n \/\/Search for given ability in database\n std::string query_string = str(boost::format(\"SELECT ability_id FROM ability_names WHERE name='%s'\")\n % ability.c_str());\n SQLite::Statement ability_names_query(_db, query_string.c_str());\n if(ability_names_query.executeStep())\n {\n _ability = ability;\n return;\n }\n\n \/\/If not in ability_names, check in abilities\n query_string = str(boost::format(\"Select id FROM abilities WHERE identifier='%s'\")\n % ability);\n SQLite::Statement abilities_query(_db, query_string.c_str());\n if(abilities_query.executeStep())\n {\n ability[0] = tolower(ability[0]);\n _ability = ability;\n }\n }\n\n void team_pokemon_modernimpl::set_using_hidden_ability(bool val)\n {\n _has_hidden_ability = val;\n _ability = _determine_ability();\n }\n\n void team_pokemon_modernimpl::set_EV(std::string EV, unsigned int val)\n {\n if(val > 255)\n {\n cerr << \"Gen 3-5 EV's must be 0-255.\" << endl;\n exit(EXIT_FAILURE);\n }\n\n if(EV == \"HP\")\n {\n _evHP = val;\n _HP = _get_hp();\n }\n else if(EV == \"Attack\")\n {\n _evATK = val;\n _ATK = _get_stat(\"Attack\", _evATK, _ivATK);\n }\n else if(EV == \"Defense\")\n {\n _evDEF = val;\n _DEF = _get_stat(\"Defense\", _evDEF, _ivDEF);\n }\n else if(EV == \"Speed\")\n {\n _evSPD = val;\n _SPD = _get_stat(\"Speed\", _evSPD, _ivSPD);\n }\n else if(EV == \"Special Attack\")\n {\n _evSATK = val;\n _SATK = _get_stat(\"Special Attack\", _evSATK, _ivSATK);\n }\n else if(EV == \"Special Defense\")\n {\n _evSDEF = val;\n _SDEF = _get_stat(\"Special Defense\", _evSDEF, _ivSDEF);\n }\n }\n \n void team_pokemon_modernimpl::set_IV(std::string IV, unsigned int val)\n {\n if(val > 31)\n {\n cerr << \"Gen 3-5 IV's must be 0-31.\" << endl;\n exit(EXIT_FAILURE);\n }\n\n if(IV == \"HP\")\n { \n _ivHP = val;\n _HP = _get_hp();\n } \n else if(IV == \"Attack\")\n { \n _ivATK = val;\n _ATK = _get_stat(\"Attack\", _evATK, _ivATK);\n } \n else if(IV == \"Defense\")\n { \n _ivDEF = val;\n _DEF = _get_stat(\"Defense\", _evDEF, _ivDEF);\n } \n else if(IV == \"Speed\")\n { \n _ivSPD = val;\n _SPD = _get_stat(\"Speed\", _evSPD, _ivSPD);\n } \n else if(IV == \"Special Attack\")\n { \n _ivSATK = val;\n _SATK = _get_stat(\"Special Attack\", _evSATK, _ivSATK);\n } \n else if(IV == \"Special Defense\")\n { \n _ivSDEF = val;\n _SDEF = _get_stat(\"Special Defense\", _evSDEF, _ivSDEF);\n } \n }\n\n void team_pokemon_modernimpl::set_form(unsigned int form)\n {\n _base_pkmn->set_form(form);\n _set_stats();\n _ability = _determine_ability();\n }\n\n void team_pokemon_modernimpl::set_form(std::string form)\n {\n _base_pkmn->set_form(form);\n _set_stats();\n _ability = _determine_ability();\n }\n\n unsigned int team_pokemon_modernimpl::_get_hp() const\n {\n pkmn::dict<std::string, unsigned int> stats = _base_pkmn->get_base_stats();\n\n unsigned int hp_val = int(floor(((double(_ivHP) + (2.0*double(stats[\"HP\"])) + (0.25*double(_evHP)) + 100.0)\n * double(_level))\/100.0 + 10.0));\n return hp_val;\n }\n\n unsigned int team_pokemon_modernimpl::_get_stat(std::string stat, unsigned int EV, unsigned int IV) const\n {\n \/\/TODO: better solution\n pkmn::dict<std::string, unsigned int> stat_enums = boost::assign::map_list_of\n (\"HP\", Stats::HP)\n (\"Attack\", Stats::ATTACK)\n (\"Defense\", Stats::DEFENSE)\n (\"Special Attack\", Stats::SPECIAL_ATTACK)\n (\"Special Defense\", Stats::SPECIAL_DEFENSE)\n (\"Speed\", Stats::SPEED)\n ;\n\n pkmn::dict<std::string, unsigned int> stats = _base_pkmn->get_base_stats();\n double ability_mod = database::get_nature_stat_effect(_nature, stat_enums[stat]);\n\n unsigned int stat_val = int(ceil(((((double(IV) + 2.0*double(stats[stat]) + 0.25*double(EV))\n * double(_level))\/100.0) + 5.0) * ability_mod));\n return stat_val;\n }\n\n void team_pokemon_modernimpl::_set_stats()\n {\n if(_base_pkmn->get_species_id() == Species::SHEDINJA) _HP = 1;\n else _HP = _get_hp();\n _ATK = _get_stat(\"Attack\", _evATK, _ivATK);\n _DEF = _get_stat(\"Defense\", _evDEF, _ivDEF);\n _SPD = _get_stat(\"Speed\", _evSPD, _ivSPD);\n _SATK = _get_stat(\"Special Attack\", _evSATK, _ivSATK);\n _SDEF = _get_stat(\"Special Defense\", _evSDEF, _ivSDEF);\n }\n\n std::string team_pokemon_modernimpl::_determine_ability() const\n {\n string_pair_t abilities = _base_pkmn->get_abilities();\n std::string hidden_ability = _base_pkmn->get_hidden_ability();\n\n if(_base_pkmn->get_species_id() == Species::NONE or _base_pkmn->get_species_id() == Species::INVALID) return \"None\";\n else if(_has_hidden_ability and _generation >= 5) return hidden_ability;\n else return ((_personality % 2) == 0) ? abilities.first : abilities.second;\n }\n \n std::string team_pokemon_modernimpl::_determine_gender() const\n {\n if(_base_pkmn->get_chance_male() + _base_pkmn->get_chance_female() == 0\n or _base_pkmn->get_species_id() == Species::NONE\n or _base_pkmn->get_species_id() == Species::INVALID) return \"Genderless\";\n else if(_base_pkmn->get_chance_male() == 1.0) return \"Male\";\n else if(_base_pkmn->get_chance_female() == 1.0) return \"Female\";\n else\n {\n if((_personality % 256) > int(floor(255*(1-_base_pkmn->get_chance_male())))) return \"Male\";\n else return \"Female\";\n }\n\n \/\/Should never get here, this stops Clang from complaining\n return \"Male\";\n }\n} \/* namespace pkmn *\/\n<commit_msg>team_pokemon: fixed _determine_nature<commit_after>\/*\n * Copyright (c) 2013-2014 Nicholas Corgan (n.corgan@gmail.com)\n *\n * Distributed under the MIT License (MIT) (See accompanying file LICENSE.txt\n * or copy at http:\/\/opensource.org\/licenses\/MIT)\n *\/\n\n#include <cstdio>\n\n#include <boost\/assign.hpp>\n#include <boost\/format.hpp>\n\n#include <pkmn\/enums.hpp>\n#include <pkmn\/paths.hpp>\n#include <pkmn\/database\/queries.hpp>\n#include <pkmn\/types\/prng.hpp>\n\n#include \"SQLiteCpp\/src\/SQLiteC++.h\"\n\n#include \"team_pokemon_modernimpl.hpp\"\n\nusing namespace std;\n\nnamespace pkmn\n{\n team_pokemon_modernimpl::team_pokemon_modernimpl(base_pokemon::sptr base, unsigned int game, unsigned int level,\n unsigned int move1, unsigned int move2,\n unsigned int move3, unsigned int move4): team_pokemon_impl(base,game,level,\n move1,move2,move3,move4)\n {\n \/\/Random individual values\n _ivHP = _rand_gen.lcrng_next(_generation) % 32;\n _ivATK = _rand_gen.lcrng_next(_generation) % 32;\n _ivDEF = _rand_gen.lcrng_next(_generation) % 32;\n _ivSPD = _rand_gen.lcrng_next(_generation) % 32;\n _ivSATK = _rand_gen.lcrng_next(_generation) % 32;\n _ivSDEF = _rand_gen.lcrng_next(_generation) % 32;\n\n \/*\n * Random effort values within following rules:\n * - Sum <= 510\n * - EV <= 255\n *\/\n _evHP = 256;\n _evATK = 256;\n _evDEF = 256;\n _evSPD = 256;\n _evSATK = 256;\n _evSDEF = 256;\n while((_evHP+_evATK+_evDEF+_evSPD+_evSATK+_evSDEF)>510 || _evHP>255 || _evATK>255 || _evDEF>255 || _evSPD>255 || _evSATK>255 || _evSDEF>255)\n {\n _evHP = _rand_gen.lcrng_next(_generation) % 256;\n _evATK = _rand_gen.lcrng_next(_generation) % 256;\n _evDEF = _rand_gen.lcrng_next(_generation) % 256;\n _evSPD = _rand_gen.lcrng_next(_generation) % 256;\n _evSATK = _rand_gen.lcrng_next(_generation) % 256;\n _evSDEF = _rand_gen.lcrng_next(_generation) % 256;\n }\n\n _gender = _determine_gender();\n _nature = _determine_nature();\n _ability = _determine_ability();\n\n _set_stats();\n }\n\n std::string team_pokemon_modernimpl::get_gender() const {return _gender;}\n\n std::string team_pokemon_modernimpl::get_nature() const {return _nature;}\n\n std::string team_pokemon_modernimpl::get_ability() const {return _ability;}\n\n bool team_pokemon_modernimpl::is_shiny() const\n {\n int p1, p2, E, F;\n p1 = (_personality & 0xFFFF0000) >> 16;\n p2 = _personality & 0xFFFF;\n E = _tid.public_id ^ _tid.secret_id;\n F = p1 ^ p2;\n return (E ^ F) < 8;\n }\n\n pkmn::dict<std::string, unsigned int> team_pokemon_modernimpl::get_stats() const\n {\n pkmn::dict<std::string, unsigned int> stats;\n stats[\"HP\"] = _HP;\n stats[\"Attack\"] = _ATK;\n stats[\"Defense\"] = _DEF;\n stats[\"Special Attack\"] = _SATK;\n stats[\"Special Defense\"] = _SDEF;\n stats[\"Speed\"] = _SPD;\n\n return stats;\n }\n\n pkmn::dict<std::string, unsigned int> team_pokemon_modernimpl::get_EVs() const\n {\n pkmn::dict<std::string, unsigned int> EVs;\n EVs[\"HP\"] = _evHP;\n EVs[\"Attack\"] = _evATK;\n EVs[\"Defense\"] = _evDEF;\n EVs[\"Special Attack\"] = _evSATK;\n EVs[\"Special Defense\"] = _evSDEF;\n EVs[\"Speed\"] = _evSPD;\n \n return EVs;\n }\n\n pkmn::dict<std::string, unsigned int> team_pokemon_modernimpl::get_IVs() const\n {\n pkmn::dict<std::string, unsigned int> IVs;\n IVs[\"HP\"] = _ivHP;\n IVs[\"Attack\"] = _ivATK;\n IVs[\"Defense\"] = _ivDEF;\n IVs[\"Special Attack\"] = _ivSATK;\n IVs[\"Special Defense\"] = _ivSDEF;\n IVs[\"Speed\"] = _ivSPD;\n\n return IVs;\n }\n\n void team_pokemon_modernimpl::set_personality(unsigned int personality)\n {\n _personality = personality;\n _ability = _determine_ability();\n _gender = _determine_gender();\n _nature = _determine_nature();\n }\n\n void team_pokemon_modernimpl::set_gender(std::string gender)\n {\n if(gender == \"Male\" or gender == \"Female\") _gender = gender;\n }\n\n void team_pokemon_modernimpl::set_nature(std::string nature)\n {\n \/\/Search for given nature in database\n std::string query_string = str(boost::format(\"SELECT nature_id FROM nature_names WHERE name='%s'\")\n % nature.c_str());\n SQLite::Statement nature_names_query(_db, query_string.c_str());\n if(nature_names_query.executeStep())\n {\n _nature = nature;\n _set_stats();\n return;\n }\n\n \/\/If not in nature_names, check in abilities\n query_string = str(boost::format(\"Select id FROM natures WHERE identifier='%s'\")\n % nature);\n SQLite::Statement natures_query(_db, query_string.c_str());\n if(natures_query.executeStep())\n {\n nature[0] = tolower(nature[0]);\n _nature = nature;\n _set_stats();\n }\n }\n \n void team_pokemon_modernimpl::set_ability(std::string ability)\n {\n \/\/Search for given ability in database\n std::string query_string = str(boost::format(\"SELECT ability_id FROM ability_names WHERE name='%s'\")\n % ability.c_str());\n SQLite::Statement ability_names_query(_db, query_string.c_str());\n if(ability_names_query.executeStep())\n {\n _ability = ability;\n return;\n }\n\n \/\/If not in ability_names, check in abilities\n query_string = str(boost::format(\"Select id FROM abilities WHERE identifier='%s'\")\n % ability);\n SQLite::Statement abilities_query(_db, query_string.c_str());\n if(abilities_query.executeStep())\n {\n ability[0] = tolower(ability[0]);\n _ability = ability;\n }\n }\n\n void team_pokemon_modernimpl::set_using_hidden_ability(bool val)\n {\n _has_hidden_ability = val;\n _ability = _determine_ability();\n }\n\n void team_pokemon_modernimpl::set_EV(std::string EV, unsigned int val)\n {\n if(val > 255)\n {\n cerr << \"Gen 3-5 EV's must be 0-255.\" << endl;\n exit(EXIT_FAILURE);\n }\n\n if(EV == \"HP\")\n {\n _evHP = val;\n _HP = _get_hp();\n }\n else if(EV == \"Attack\")\n {\n _evATK = val;\n _ATK = _get_stat(\"Attack\", _evATK, _ivATK);\n }\n else if(EV == \"Defense\")\n {\n _evDEF = val;\n _DEF = _get_stat(\"Defense\", _evDEF, _ivDEF);\n }\n else if(EV == \"Speed\")\n {\n _evSPD = val;\n _SPD = _get_stat(\"Speed\", _evSPD, _ivSPD);\n }\n else if(EV == \"Special Attack\")\n {\n _evSATK = val;\n _SATK = _get_stat(\"Special Attack\", _evSATK, _ivSATK);\n }\n else if(EV == \"Special Defense\")\n {\n _evSDEF = val;\n _SDEF = _get_stat(\"Special Defense\", _evSDEF, _ivSDEF);\n }\n }\n \n void team_pokemon_modernimpl::set_IV(std::string IV, unsigned int val)\n {\n if(val > 31)\n {\n cerr << \"Gen 3-5 IV's must be 0-31.\" << endl;\n exit(EXIT_FAILURE);\n }\n\n if(IV == \"HP\")\n { \n _ivHP = val;\n _HP = _get_hp();\n } \n else if(IV == \"Attack\")\n { \n _ivATK = val;\n _ATK = _get_stat(\"Attack\", _evATK, _ivATK);\n } \n else if(IV == \"Defense\")\n { \n _ivDEF = val;\n _DEF = _get_stat(\"Defense\", _evDEF, _ivDEF);\n } \n else if(IV == \"Speed\")\n { \n _ivSPD = val;\n _SPD = _get_stat(\"Speed\", _evSPD, _ivSPD);\n } \n else if(IV == \"Special Attack\")\n { \n _ivSATK = val;\n _SATK = _get_stat(\"Special Attack\", _evSATK, _ivSATK);\n } \n else if(IV == \"Special Defense\")\n { \n _ivSDEF = val;\n _SDEF = _get_stat(\"Special Defense\", _evSDEF, _ivSDEF);\n } \n }\n\n void team_pokemon_modernimpl::set_form(unsigned int form)\n {\n _base_pkmn->set_form(form);\n _set_stats();\n _ability = _determine_ability();\n }\n\n void team_pokemon_modernimpl::set_form(std::string form)\n {\n _base_pkmn->set_form(form);\n _set_stats();\n _ability = _determine_ability();\n }\n\n unsigned int team_pokemon_modernimpl::_get_hp() const\n {\n pkmn::dict<std::string, unsigned int> stats = _base_pkmn->get_base_stats();\n\n unsigned int hp_val = int(floor(((double(_ivHP) + (2.0*double(stats[\"HP\"])) + (0.25*double(_evHP)) + 100.0)\n * double(_level))\/100.0 + 10.0));\n return hp_val;\n }\n\n unsigned int team_pokemon_modernimpl::_get_stat(std::string stat, unsigned int EV, unsigned int IV) const\n {\n \/\/TODO: better solution\n pkmn::dict<std::string, unsigned int> stat_enums = boost::assign::map_list_of\n (\"HP\", Stats::HP)\n (\"Attack\", Stats::ATTACK)\n (\"Defense\", Stats::DEFENSE)\n (\"Special Attack\", Stats::SPECIAL_ATTACK)\n (\"Special Defense\", Stats::SPECIAL_DEFENSE)\n (\"Speed\", Stats::SPEED)\n ;\n\n pkmn::dict<std::string, unsigned int> stats = _base_pkmn->get_base_stats();\n double ability_mod = database::get_nature_stat_effect(_nature, stat_enums[stat]);\n\n unsigned int stat_val = int(ceil(((((double(IV) + 2.0*double(stats[stat]) + 0.25*double(EV))\n * double(_level))\/100.0) + 5.0) * ability_mod));\n return stat_val;\n }\n\n void team_pokemon_modernimpl::_set_stats()\n {\n if(_base_pkmn->get_species_id() == Species::SHEDINJA) _HP = 1;\n else _HP = _get_hp();\n _ATK = _get_stat(\"Attack\", _evATK, _ivATK);\n _DEF = _get_stat(\"Defense\", _evDEF, _ivDEF);\n _SPD = _get_stat(\"Speed\", _evSPD, _ivSPD);\n _SATK = _get_stat(\"Special Attack\", _evSATK, _ivSATK);\n _SDEF = _get_stat(\"Special Defense\", _evSDEF, _ivSDEF);\n }\n\n std::string team_pokemon_modernimpl::_determine_ability() const\n {\n string_pair_t abilities = _base_pkmn->get_abilities();\n std::string hidden_ability = _base_pkmn->get_hidden_ability();\n\n if(_base_pkmn->get_species_id() == Species::NONE or _base_pkmn->get_species_id() == Species::INVALID) return \"None\";\n else if(_has_hidden_ability and _generation >= 5) return hidden_ability;\n else return ((_personality % 2) == 0) ? abilities.first : abilities.second;\n }\n \n std::string team_pokemon_modernimpl::_determine_gender() const\n {\n if(_base_pkmn->get_chance_male() + _base_pkmn->get_chance_female() == 0\n or _base_pkmn->get_species_id() == Species::NONE\n or _base_pkmn->get_species_id() == Species::INVALID) return \"Genderless\";\n else if(_base_pkmn->get_chance_male() == 1.0) return \"Male\";\n else if(_base_pkmn->get_chance_female() == 1.0) return \"Female\";\n else\n {\n if((_personality % 256) > int(floor(255*(1-_base_pkmn->get_chance_male())))) return \"Male\";\n else return \"Female\";\n }\n\n \/\/Should never get here, this stops Clang from complaining\n return \"Male\";\n }\n\n std::string team_pokemon_modernimpl::_determine_nature() const\n {\n return database::get_nature_name(_personality % 24);\n }\n} \/* namespace pkmn *\/\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************************\n * Copyright (C) 2012 by Alejandro Fiestas Olivares <afiestas@kde.org> *\n * *\n * This program is free software; you can redistribute it and\/or *\n * modify it under the terms of the GNU General Public License *\n * as published by the Free Software Foundation; either version 2 *\n * of the License, or (at your option) any later version. *\n * *\n * This program is distributed in the hope that it will be useful, *\n * but WITHOUT ANY WARRANTY; without even the implied warranty of *\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *\n * GNU General Public License for more details. *\n * *\n * You should have received a copy of the GNU General Public License *\n * along with this program; if not, write to the Free Software *\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA *\n *************************************************************************************\/\n\n#include \"console.h\"\n\n#include <QX11Info>\n#include <QtCore\/QDebug>\n#include <QtCore\/QDateTime>\n#include <QtCore\/QDir>\n#include <QtCore\/QTextStream>\n\n#include <qjson\/parser.h>\n#include <qjson\/serializer.h>\n\n#include <kscreen\/config.h>\n#include <kscreen\/output.h>\n#include <kscreen\/mode.h>\n#include <kscreen\/configmonitor.h>\n#include <kscreen\/edid.h>\n\n#include <KStandardDirs>\n\nusing namespace KScreen;\n\nConsole::Console(QObject* parent): QObject(parent)\n{\n qDebug() << \"START\";\n QDateTime date = QDateTime::currentDateTime();\n m_config = Config::current();\n qDebug() << \"Config::current() took\" << date.msecsTo(QDateTime::currentDateTime()) << \"milliseconds\";\n}\n\nConsole::~Console()\n{\n\n}\n\nvoid Console::printConfig()\n{\n qDebug() << \"KScreen version: \" << KSCREEN_VERSION;\n\n if (!m_config) {\n qDebug() << \"Config is invalid, probably backend couldn't load\";\n return;\n }\n if (!m_config->screen()) {\n qDebug() << \"No screen in the configuration, broken backend\";\n return;\n }\n\n qDebug() << \"Screen:\";\n qDebug() << \"\\tmaxSize:\" << m_config->screen()->maxSize();\n qDebug() << \"\\tminSize:\" << m_config->screen()->minSize();\n qDebug() << \"\\tcurrentSize:\" << m_config->screen()->currentSize();\n\n OutputList outputs = m_config->outputs();\n Q_FOREACH(Output *output, outputs) {\n qDebug() << \"\\n-----------------------------------------------------\\n\";\n qDebug() << \"Id: \" << output->id();\n qDebug() << \"Name: \" << output->name();\n qDebug() << \"Type: \" << typetoString(output->type());\n qDebug() << \"Connected: \" << output->isConnected();\n if (!output->isConnected()) {\n continue;\n }\n qDebug() << \"Enabled: \" << output->isEnabled();\n qDebug() << \"Primary: \" << output->isPrimary();\n qDebug() << \"Rotation: \" << output->rotation();\n qDebug() << \"Pos: \" << output->pos();\n if (output->currentMode()) {\n qDebug() << \"Size: \" << output->currentMode()->size();\n }\n qDebug() << \"Clones: \" << output->clones().isEmpty();\n qDebug() << \"Mode: \" << output->currentModeId();\n qDebug() << \"Preferred Mode: \" << output->preferredModeId();\n qDebug() << \"Preferred modes: \" << output->preferredModes();\n qDebug() << \"Modes: \";\n\n ModeList modes = output->modes();\n Q_FOREACH(Mode* mode, modes) {\n qDebug() << \"\\t\" << mode->id() << \" \" << mode->name() << \" \" << mode->size() << \" \" << mode->refreshRate();\n }\n\n Edid* edid = output->edid();\n qDebug() << \"EDID Info: \";\n if (edid && edid->isValid()) {\n qDebug() << \"\\tDevice ID: \" << edid->deviceId();\n qDebug() << \"\\tName: \" << edid->name();\n qDebug() << \"\\tVendor: \" << edid->vendor();\n qDebug() << \"\\tSerial: \" << edid->serial();\n qDebug() << \"\\tEISA ID: \" << edid->eisaId();\n qDebug() << \"\\tHash: \" << edid->hash();\n qDebug() << \"\\tWidth: \" << edid->width();\n qDebug() << \"\\tHeight: \" << edid->height();\n qDebug() << \"\\tGamma: \" << edid->gamma();\n qDebug() << \"\\tRed: \" << edid->red();\n qDebug() << \"\\tGreen: \" << edid->green();\n qDebug() << \"\\tBlue: \" << edid->blue();\n qDebug() << \"\\tWhite: \" << edid->white();\n } else {\n qDebug() << \"\\tUnavailable\";\n }\n }\n}\n\nQString Console::typetoString(const Output::Type& type) const\n{\n switch (type) {\n case Output::Unknown:\n return QLatin1String(\"Unknown\");\n case Output::Panel:\n return QLatin1String(\"Panel (Laptop)\");\n case Output::VGA:\n return QLatin1String(\"VGA\");\n case Output::DVII:\n return QLatin1String(\"DVI-I\");\n case Output::DVIA:\n return QLatin1String(\"DVI-A\");\n case Output::DVID:\n return QLatin1String(\"DVI-D\");\n case Output::HDMI:\n return QLatin1String(\"HDMI\");\n case Output::TV:\n return QLatin1String(\"TV\");\n case Output::TVComposite:\n return QLatin1String(\"TV-Composite\");\n case Output::TVSVideo:\n return QLatin1String(\"TV-SVideo\");\n case Output::TVComponent:\n return QLatin1String(\"TV-Component\");\n case Output::TVSCART:\n return QLatin1String(\"TV-SCART\");\n case Output::TVC4:\n return QLatin1String(\"TV-C4\");\n case Output::DisplayPort:\n return QLatin1String(\"DisplayPort\");\n default:\n return QLatin1String(\"Invalid Type\");\n\n };\n}\n\nvoid Console::printSerializations()\n{\n QString path = KStandardDirs::locateLocal(\"data\", \"kscreen\/\");\n qDebug() << \"Configs in: \" << path;\n\n QDir dir(path);\n QStringList files = dir.entryList(QDir::Files);\n qDebug() << \"Number of files: \" << files.count() << endl;\n\n bool ok;\n QJson::Parser parser;\n QJson::Serializer serializer;\n serializer.setIndentMode(QJson::IndentFull);\n Q_FOREACH(const QString fileName, files) {\n ok = true;\n qDebug() << fileName;\n QFile file(path + \"\/\" + fileName);\n file.open(QFile::ReadOnly);\n QVariant data = parser.parse(file.readAll(), &ok);\n if (!ok) {\n qDebug() << \" \" << \"can't parse file\";\n qDebug() << \" \" << parser.errorString();\n continue;\n }\n\n qDebug() << serializer.serialize(data) << endl;\n }\n}\n\nvoid Console::monitor()\n{\n ConfigMonitor::instance()->addConfig(m_config);\n}\n\nvoid Console::monitorAndPrint()\n{\n monitor();\n connect(ConfigMonitor::instance(), SIGNAL(configurationChanged()), SLOT(printConfig()));\n}\n\n#include <console.moc>\n<commit_msg>Output of \"Clones\" bit more good looking<commit_after>\/*************************************************************************************\n * Copyright (C) 2012 by Alejandro Fiestas Olivares <afiestas@kde.org> *\n * *\n * This program is free software; you can redistribute it and\/or *\n * modify it under the terms of the GNU General Public License *\n * as published by the Free Software Foundation; either version 2 *\n * of the License, or (at your option) any later version. *\n * *\n * This program is distributed in the hope that it will be useful, *\n * but WITHOUT ANY WARRANTY; without even the implied warranty of *\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *\n * GNU General Public License for more details. *\n * *\n * You should have received a copy of the GNU General Public License *\n * along with this program; if not, write to the Free Software *\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA *\n *************************************************************************************\/\n\n#include \"console.h\"\n\n#include <QX11Info>\n#include <QtCore\/QDebug>\n#include <QtCore\/QDateTime>\n#include <QtCore\/QDir>\n#include <QtCore\/QTextStream>\n\n#include <qjson\/parser.h>\n#include <qjson\/serializer.h>\n\n#include <kscreen\/config.h>\n#include <kscreen\/output.h>\n#include <kscreen\/mode.h>\n#include <kscreen\/configmonitor.h>\n#include <kscreen\/edid.h>\n\n#include <KStandardDirs>\n\nusing namespace KScreen;\n\nConsole::Console(QObject* parent): QObject(parent)\n{\n qDebug() << \"START\";\n QDateTime date = QDateTime::currentDateTime();\n m_config = Config::current();\n qDebug() << \"Config::current() took\" << date.msecsTo(QDateTime::currentDateTime()) << \"milliseconds\";\n}\n\nConsole::~Console()\n{\n\n}\n\nvoid Console::printConfig()\n{\n qDebug() << \"KScreen version: \" << KSCREEN_VERSION;\n\n if (!m_config) {\n qDebug() << \"Config is invalid, probably backend couldn't load\";\n return;\n }\n if (!m_config->screen()) {\n qDebug() << \"No screen in the configuration, broken backend\";\n return;\n }\n\n qDebug() << \"Screen:\";\n qDebug() << \"\\tmaxSize:\" << m_config->screen()->maxSize();\n qDebug() << \"\\tminSize:\" << m_config->screen()->minSize();\n qDebug() << \"\\tcurrentSize:\" << m_config->screen()->currentSize();\n\n OutputList outputs = m_config->outputs();\n Q_FOREACH(Output *output, outputs) {\n qDebug() << \"\\n-----------------------------------------------------\\n\";\n qDebug() << \"Id: \" << output->id();\n qDebug() << \"Name: \" << output->name();\n qDebug() << \"Type: \" << typetoString(output->type());\n qDebug() << \"Connected: \" << output->isConnected();\n if (!output->isConnected()) {\n continue;\n }\n qDebug() << \"Enabled: \" << output->isEnabled();\n qDebug() << \"Primary: \" << output->isPrimary();\n qDebug() << \"Rotation: \" << output->rotation();\n qDebug() << \"Pos: \" << output->pos();\n if (output->currentMode()) {\n qDebug() << \"Size: \" << output->currentMode()->size();\n }\n if (output->clones().isEmpty()) {\n qDebug() << \"Clones: \" << \"None\";\n } else {\n qDebug() << \"Clones: \" << output->clones().count();\n }\n qDebug() << \"Mode: \" << output->currentModeId();\n qDebug() << \"Preferred Mode: \" << output->preferredModeId();\n qDebug() << \"Preferred modes: \" << output->preferredModes();\n qDebug() << \"Modes: \";\n\n ModeList modes = output->modes();\n Q_FOREACH(Mode* mode, modes) {\n qDebug() << \"\\t\" << mode->id() << \" \" << mode->name() << \" \" << mode->size() << \" \" << mode->refreshRate();\n }\n\n Edid* edid = output->edid();\n qDebug() << \"EDID Info: \";\n if (edid && edid->isValid()) {\n qDebug() << \"\\tDevice ID: \" << edid->deviceId();\n qDebug() << \"\\tName: \" << edid->name();\n qDebug() << \"\\tVendor: \" << edid->vendor();\n qDebug() << \"\\tSerial: \" << edid->serial();\n qDebug() << \"\\tEISA ID: \" << edid->eisaId();\n qDebug() << \"\\tHash: \" << edid->hash();\n qDebug() << \"\\tWidth: \" << edid->width();\n qDebug() << \"\\tHeight: \" << edid->height();\n qDebug() << \"\\tGamma: \" << edid->gamma();\n qDebug() << \"\\tRed: \" << edid->red();\n qDebug() << \"\\tGreen: \" << edid->green();\n qDebug() << \"\\tBlue: \" << edid->blue();\n qDebug() << \"\\tWhite: \" << edid->white();\n } else {\n qDebug() << \"\\tUnavailable\";\n }\n }\n}\n\nQString Console::typetoString(const Output::Type& type) const\n{\n switch (type) {\n case Output::Unknown:\n return QLatin1String(\"Unknown\");\n case Output::Panel:\n return QLatin1String(\"Panel (Laptop)\");\n case Output::VGA:\n return QLatin1String(\"VGA\");\n case Output::DVII:\n return QLatin1String(\"DVI-I\");\n case Output::DVIA:\n return QLatin1String(\"DVI-A\");\n case Output::DVID:\n return QLatin1String(\"DVI-D\");\n case Output::HDMI:\n return QLatin1String(\"HDMI\");\n case Output::TV:\n return QLatin1String(\"TV\");\n case Output::TVComposite:\n return QLatin1String(\"TV-Composite\");\n case Output::TVSVideo:\n return QLatin1String(\"TV-SVideo\");\n case Output::TVComponent:\n return QLatin1String(\"TV-Component\");\n case Output::TVSCART:\n return QLatin1String(\"TV-SCART\");\n case Output::TVC4:\n return QLatin1String(\"TV-C4\");\n case Output::DisplayPort:\n return QLatin1String(\"DisplayPort\");\n default:\n return QLatin1String(\"Invalid Type\");\n\n };\n}\n\nvoid Console::printSerializations()\n{\n QString path = KStandardDirs::locateLocal(\"data\", \"kscreen\/\");\n qDebug() << \"Configs in: \" << path;\n\n QDir dir(path);\n QStringList files = dir.entryList(QDir::Files);\n qDebug() << \"Number of files: \" << files.count() << endl;\n\n bool ok;\n QJson::Parser parser;\n QJson::Serializer serializer;\n serializer.setIndentMode(QJson::IndentFull);\n Q_FOREACH(const QString fileName, files) {\n ok = true;\n qDebug() << fileName;\n QFile file(path + \"\/\" + fileName);\n file.open(QFile::ReadOnly);\n QVariant data = parser.parse(file.readAll(), &ok);\n if (!ok) {\n qDebug() << \" \" << \"can't parse file\";\n qDebug() << \" \" << parser.errorString();\n continue;\n }\n\n qDebug() << serializer.serialize(data) << endl;\n }\n}\n\nvoid Console::monitor()\n{\n ConfigMonitor::instance()->addConfig(m_config);\n}\n\nvoid Console::monitorAndPrint()\n{\n monitor();\n connect(ConfigMonitor::instance(), SIGNAL(configurationChanged()), SLOT(printConfig()));\n}\n\n#include <console.moc>\n<|endoftext|>"} {"text":"<commit_before>\/*\n The MIT License\n\n Copyright (c) 2009 Institut of Mechanics and Fluid Dynamics,\n TU Bergakademie Freiberg.\n\n\n Permission is hereby granted, free of charge, to any person obtaining a\n copy of this software and associated documentation files (the \"Software\"),\n to deal in the Software without restriction, including without limitation\n the rights to use, copy, modify, merge, publish, distribute, sublicense,\n and\/or sell copies of the Software, and to permit persons to whom the\n Software is furnished to do so, subject to the following conditions:\n\n The above copyright notice and this permission notice shall be included\n in all copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n DEALINGS IN THE SOFTWARE.\n*\/\n\n\/**\n \\file REKConverter.cpp\n \\author Andre Liebscher\n Institut of Mechanics and Fluid Dynamics\n TU Bergakademie Freiberg\n \\date March 2009\n*\/\n\n#include <fstream>\n#include <sstream>\n#include <cstring>\n#include \"boost\/cstdint.hpp\"\n#include \"REKConverter.h\"\n#include \"Controller\/Controller.h\"\n#include \"Basics\/EndianConvert.h\"\n\nusing namespace std;\n\nREKConverter::REKConverter()\n{\n m_vConverterDesc = \"Fraunhofer EZRT Volume\";\n m_vSupportedExt.push_back(\"REK\");\n}\n\nbool\nREKConverter::ConvertToRAW(const std::string& strSourceFilename,\n const std::string&,\n bool, UINT64& iHeaderSkip,\n UINT64& iComponentSize,\n UINT64& iComponentCount,\n bool& bConvertEndianess, bool& bSigned,\n bool& bIsFloat, UINT64VECTOR3& vVolumeSize,\n FLOATVECTOR3& vVolumeAspect,\n std::string& strTitle,\n UVFTables::ElementSemanticTable& eType,\n std::string& strIntermediateFile,\n bool& bDeleteIntermediateFile)\n{\n MESSAGE(\"Attempting to convert REK dataset %s\", strSourceFilename.c_str());\n\n \/\/ Find out machine endianess\n bConvertEndianess = EndianConvert::IsBigEndian();\n\n \/\/ Read header an check for \"magic\" values of the REK file\n ifstream fileData(strSourceFilename.c_str(), ifstream::in | ifstream::binary);\n char buffer[2048];\n\n if(fileData.is_open()) {\n fileData.read( buffer, sizeof(buffer) );\n if(Parse<boost::uint16_t, 2>( &buffer[10], bConvertEndianess ) != 2 &&\n Parse<boost::uint16_t, 2>( &buffer[12], bConvertEndianess ) != 4) {\n WARNING(\"The file %s is not a REK file\", strSourceFilename.c_str());\n fileData.close();\n return false;\n }\n } else {\n WARNING(\"Could not open REK file %s\", strSourceFilename.c_str());\n return false;\n }\n fileData.close();\n\n \/\/ Standard values which are always true (I guess)\n strTitle = \"Fraunhofer EZRT\";\n eType = UVFTables::ES_UNDEFINED;\n vVolumeAspect = FLOATVECTOR3(1,1,1);\n bSigned = false;\n bIsFloat = false;\n iComponentCount = 1;\n strIntermediateFile = strSourceFilename;\n bDeleteIntermediateFile = false;\n\n \/\/ Read file format from header\n vVolumeSize[0] = Parse<boost::uint16_t, 2>(&buffer[0], bConvertEndianess);\n vVolumeSize[1] = Parse<boost::uint16_t, 2>(&buffer[2], bConvertEndianess);\n vVolumeSize[2] = Parse<boost::uint16_t, 2>(&buffer[6], bConvertEndianess);\n iComponentSize = Parse<boost::uint16_t, 2>(&buffer[4], bConvertEndianess);\n iHeaderSkip = Parse<boost::uint16_t, 2>(&buffer[8], bConvertEndianess);\n\n return true;\n}\n\n\/\/ unimplemented!\nbool\nREKConverter::ConvertToNative(const std::string&,\n const std::string&,\n UINT64, UINT64,\n UINT64, bool,\n bool,\n UINT64VECTOR3,\n FLOATVECTOR3,\n bool,\n bool)\n{\n return false;\n}\n<commit_msg>Rename displayed dataset name.<commit_after>\/*\n The MIT License\n\n Copyright (c) 2009 Institut of Mechanics and Fluid Dynamics,\n TU Bergakademie Freiberg.\n\n\n Permission is hereby granted, free of charge, to any person obtaining a\n copy of this software and associated documentation files (the \"Software\"),\n to deal in the Software without restriction, including without limitation\n the rights to use, copy, modify, merge, publish, distribute, sublicense,\n and\/or sell copies of the Software, and to permit persons to whom the\n Software is furnished to do so, subject to the following conditions:\n\n The above copyright notice and this permission notice shall be included\n in all copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n DEALINGS IN THE SOFTWARE.\n*\/\n\n\/**\n \\file REKConverter.cpp\n \\author Andre Liebscher\n Institut of Mechanics and Fluid Dynamics\n TU Bergakademie Freiberg\n \\date March 2009\n*\/\n\n#include <fstream>\n#include <sstream>\n#include <cstring>\n#include \"boost\/cstdint.hpp\"\n#include \"REKConverter.h\"\n#include \"Controller\/Controller.h\"\n#include \"Basics\/EndianConvert.h\"\n\nusing namespace std;\n\nREKConverter::REKConverter()\n{\n m_vConverterDesc = \"Fraunhofer Raw Volume\";\n m_vSupportedExt.push_back(\"REK\");\n}\n\nbool\nREKConverter::ConvertToRAW(const std::string& strSourceFilename,\n const std::string&,\n bool, UINT64& iHeaderSkip,\n UINT64& iComponentSize,\n UINT64& iComponentCount,\n bool& bConvertEndianess, bool& bSigned,\n bool& bIsFloat, UINT64VECTOR3& vVolumeSize,\n FLOATVECTOR3& vVolumeAspect,\n std::string& strTitle,\n UVFTables::ElementSemanticTable& eType,\n std::string& strIntermediateFile,\n bool& bDeleteIntermediateFile)\n{\n MESSAGE(\"Attempting to convert REK dataset %s\", strSourceFilename.c_str());\n\n \/\/ Find out machine endianess\n bConvertEndianess = EndianConvert::IsBigEndian();\n\n \/\/ Read header an check for \"magic\" values of the REK file\n ifstream fileData(strSourceFilename.c_str(), ifstream::in | ifstream::binary);\n char buffer[2048];\n\n if(fileData.is_open()) {\n fileData.read( buffer, sizeof(buffer) );\n if(Parse<boost::uint16_t, 2>( &buffer[10], bConvertEndianess ) != 2 &&\n Parse<boost::uint16_t, 2>( &buffer[12], bConvertEndianess ) != 4) {\n WARNING(\"The file %s is not a REK file\", strSourceFilename.c_str());\n fileData.close();\n return false;\n }\n } else {\n WARNING(\"Could not open REK file %s\", strSourceFilename.c_str());\n return false;\n }\n fileData.close();\n\n \/\/ Standard values which are always true (I guess)\n strTitle = \"Fraunhofer EZRT\";\n eType = UVFTables::ES_UNDEFINED;\n vVolumeAspect = FLOATVECTOR3(1,1,1);\n bSigned = false;\n bIsFloat = false;\n iComponentCount = 1;\n strIntermediateFile = strSourceFilename;\n bDeleteIntermediateFile = false;\n\n \/\/ Read file format from header\n vVolumeSize[0] = Parse<boost::uint16_t, 2>(&buffer[0], bConvertEndianess);\n vVolumeSize[1] = Parse<boost::uint16_t, 2>(&buffer[2], bConvertEndianess);\n vVolumeSize[2] = Parse<boost::uint16_t, 2>(&buffer[6], bConvertEndianess);\n iComponentSize = Parse<boost::uint16_t, 2>(&buffer[4], bConvertEndianess);\n iHeaderSkip = Parse<boost::uint16_t, 2>(&buffer[8], bConvertEndianess);\n\n return true;\n}\n\n\/\/ unimplemented!\nbool\nREKConverter::ConvertToNative(const std::string&,\n const std::string&,\n UINT64, UINT64,\n UINT64, bool,\n bool,\n UINT64VECTOR3,\n FLOATVECTOR3,\n bool,\n bool)\n{\n return false;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*!\n \\file console.cpp\n \\brief Console management implementation\n \\author Ivan Shynkarenka\n \\date 29.07.2015\n \\copyright MIT License\n*\/\n\n#include \"benchmark\/console.h\"\n\n#include <cstdio>\n\n#if defined(_WIN32) || defined(_WIN64)\n#include <windows.h>\n#endif\n\nnamespace CppBenchmark {\n\nstd::ostream& operator<<(std::ostream& stream, Color color)\n{\n Console::SetColor(color);\n return stream;\n}\n\nstd::ostream& operator<<(std::ostream& stream, std::pair<Color, Color> colors)\n{\n Console::SetColor(colors.first, colors.second);\n return stream;\n}\n\nvoid Console::SetColor(Color color, Color background)\n{\n#if defined(_WIN32) || defined(_WIN64)\n HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);\n SetConsoleTextAttribute(hConsole, (((WORD)color) & 0x0F) + ((((WORD)background) & 0x0F) << 4));\n#elif defined(unix) || defined(__unix) || defined(__unix__)\n const char* colors[] =\n {\n \"\\033[22;30m\", \/\/ Black color\n \"\\033[22;34m\", \/\/ Blue color\n \"\\033[22;32m\", \/\/ Green color\n \"\\033[22;36m\", \/\/ Cyan color\n \"\\033[22;31m\", \/\/ Red color\n \"\\033[22;35m\", \/\/ Magenta color\n \"\\033[22;33m\", \/\/ Brown color\n \"\\033[22;37m\", \/\/ Grey color\n \"\\033[01;30m\", \/\/ Dark grey color\n \"\\033[01;34m\", \/\/ Light blue color\n \"\\033[01;32m\", \/\/ Light green color\n \"\\033[01;36m\", \/\/ Light cyan color\n \"\\033[01;31m\", \/\/ Light red color\n \"\\033[01;35m\", \/\/ Light magenta color\n \"\\033[01;33m\", \/\/ Yellow color\n \"\\033[01;37m\" \/\/ White color\n };\n const char* backgrounds[] =\n {\n \"\\033[22;40m\", \/\/ Black color\n \"\\033[22;44m\", \/\/ Blue color\n \"\\033[22;42m\", \/\/ Green color\n \"\\033[22;46m\", \/\/ Cyan color\n \"\\033[22;41m\", \/\/ Red color\n \"\\033[22;45m\", \/\/ Magenta color\n \"\\033[22;43m\", \/\/ Brown color\n \"\\033[22;47m\", \/\/ Grey color\n \"\\033[01;40m\", \/\/ Dark grey color\n \"\\033[01;44m\", \/\/ Light blue color\n \"\\033[01;42m\", \/\/ Light green color\n \"\\033[01;46m\", \/\/ Light cyan color\n \"\\033[01;41m\", \/\/ Light red color\n \"\\033[01;45m\", \/\/ Light magenta color\n \"\\033[01;43m\", \/\/ Yellow color\n \"\\033[01;47m\" \/\/ White color\n };\n std::fwrite(colors[color - Color::BLACK], 1, 8, stdout);\n std::fwrite(backgrounds[background - Color::BLACK], 1, 8, stdout);\n#endif\n}\n\n} \/\/ namespace CppBenchmark\n<commit_msg>Bugfixing<commit_after>\/*!\n \\file console.cpp\n \\brief Console management implementation\n \\author Ivan Shynkarenka\n \\date 29.07.2015\n \\copyright MIT License\n*\/\n\n#include \"benchmark\/console.h\"\n\n#include <cstdio>\n\n#if defined(_WIN32) || defined(_WIN64)\n#include <windows.h>\n#endif\n\nnamespace CppBenchmark {\n\nstd::ostream& operator<<(std::ostream& stream, Color color)\n{\n Console::SetColor(color);\n return stream;\n}\n\nstd::ostream& operator<<(std::ostream& stream, std::pair<Color, Color> colors)\n{\n Console::SetColor(colors.first, colors.second);\n return stream;\n}\n\nvoid Console::SetColor(Color color, Color background)\n{\n#if defined(_WIN32) || defined(_WIN64)\n HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);\n SetConsoleTextAttribute(hConsole, (((WORD)color) & 0x0F) + ((((WORD)background) & 0x0F) << 4));\n#elif defined(unix) || defined(__unix) || defined(__unix__)\n const char* colors[] =\n {\n \"\\033[22;30m\", \/\/ Black color\n \"\\033[22;34m\", \/\/ Blue color\n \"\\033[22;32m\", \/\/ Green color\n \"\\033[22;36m\", \/\/ Cyan color\n \"\\033[22;31m\", \/\/ Red color\n \"\\033[22;35m\", \/\/ Magenta color\n \"\\033[22;33m\", \/\/ Brown color\n \"\\033[22;37m\", \/\/ Grey color\n \"\\033[01;30m\", \/\/ Dark grey color\n \"\\033[01;34m\", \/\/ Light blue color\n \"\\033[01;32m\", \/\/ Light green color\n \"\\033[01;36m\", \/\/ Light cyan color\n \"\\033[01;31m\", \/\/ Light red color\n \"\\033[01;35m\", \/\/ Light magenta color\n \"\\033[01;33m\", \/\/ Yellow color\n \"\\033[01;37m\" \/\/ White color\n };\n const char* backgrounds[] =\n {\n \"\\033[22;40m\", \/\/ Black color\n \"\\033[22;44m\", \/\/ Blue color\n \"\\033[22;42m\", \/\/ Green color\n \"\\033[22;46m\", \/\/ Cyan color\n \"\\033[22;41m\", \/\/ Red color\n \"\\033[22;45m\", \/\/ Magenta color\n \"\\033[22;43m\", \/\/ Brown color\n \"\\033[22;47m\", \/\/ Grey color\n \"\\033[01;40m\", \/\/ Dark grey color\n \"\\033[01;44m\", \/\/ Light blue color\n \"\\033[01;42m\", \/\/ Light green color\n \"\\033[01;46m\", \/\/ Light cyan color\n \"\\033[01;41m\", \/\/ Light red color\n \"\\033[01;45m\", \/\/ Light magenta color\n \"\\033[01;43m\", \/\/ Yellow color\n \"\\033[01;47m\" \/\/ White color\n };\n std::fwrite(colors[(int)color - (int)Color::BLACK], 1, 8, stdout);\n std::fwrite(backgrounds[(int)background - (int)Color::BLACK], 1, 8, stdout);\n#endif\n}\n\n} \/\/ namespace CppBenchmark\n<|endoftext|>"} {"text":"<commit_before>\/* IBM_PROLOG_BEGIN_TAG *\/\n\/* This is an automatically generated prolog. *\/\n\/* *\/\n\/* $Source: src\/usr\/hwpf\/hwp\/sbe_centaur_init\/sbe_centaur_init.C $ *\/\n\/* *\/\n\/* IBM CONFIDENTIAL *\/\n\/* *\/\n\/* COPYRIGHT International Business Machines Corp. 2012,2014 *\/\n\/* *\/\n\/* p1 *\/\n\/* *\/\n\/* Object Code Only (OCO) source materials *\/\n\/* Licensed Internal Code Source Materials *\/\n\/* IBM HostBoot Licensed Internal Code *\/\n\/* *\/\n\/* The source code for this program is not published or otherwise *\/\n\/* divested of its trade secrets, irrespective of what has been *\/\n\/* deposited with the U.S. Copyright Office. *\/\n\/* *\/\n\/* Origin: 30 *\/\n\/* *\/\n\/* IBM_PROLOG_END_TAG *\/\n\/**\n * @file sbe_centaur_init.C\n *\n * Support file for IStep:\n * sbe_centaur_init\n *\n *\n *\n * HWP_IGNORE_VERSION_CHECK\n *\n *\/\n\n\n\/******************************************************************************\/\n\/\/ Includes\n\/******************************************************************************\/\n#include <stdint.h>\n\n#include <trace\/interface.H>\n#include <initservice\/taskargs.H>\n#include <errl\/errlentry.H>\n#include <initservice\/isteps_trace.H>\n#include <targeting\/common\/commontargeting.H>\n#include <targeting\/common\/utilFilter.H>\n#include <fapi.H>\n#include <fapiPoreVeArg.H>\n#include <fapiTarget.H>\n#include <fapi.H>\n#include <fapiPlatHwpInvoker.H>\n#include <vfs\/vfs.H>\n#include \"sbe_centaur_init.H\"\n#include <hwpisteperror.H>\n#include <errl\/errludtarget.H>\n#include <sbe\/sbeif.H>\n#include \"cen_xip_customize.H\"\n\nextern fapi::ReturnCode fapiPoreVe(const fapi::Target i_target,\n std::list<uint64_t> & io_sharedObjectArgs);\n\nconst uint64_t REPAIR_LOADER_RETRY_CTR_MASK = 0x000007FC00000000ull;\n\n\/\/ Constants\n\/\/ Memory Relocation Register for Centaur SBE image\nconst uint64_t CENTAUR_SBE_PNOR_MRR = 0;\n\n\/\/ Max SBE image buffer size\nconst uint32_t MAX_SBE_IMG_SIZE = 48 * 1024; \n\nnamespace SBE_CENTAUR_INIT\n{\n\nusing namespace ISTEP;\nusing namespace ISTEP_ERROR;\nusing namespace ERRORLOG;\nusing namespace TARGETING;\nusing namespace fapi;\nusing namespace vsbe;\n\n\n\/\/\n\/\/ Wrapper function to call step 10\n\/\/\nvoid* call_sbe_centaur_init( void *io_pArgs )\n{\n\n TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace,\n \"call_sbe_centaur_init entry\");\n\n \/\/ Get target list to pass in procedure\n TARGETING::TargetHandleList l_membufTargetList;\n getAllChips(l_membufTargetList, TYPE_MEMBUF);\n\n size_t l_sbePnorSize = 0;\n void* l_sbePnorAddr = NULL;\n errlHndl_t l_errl = NULL;\n\n IStepError l_StepError;\n\n \/\/ Loop thru all Centaurs in list\n for (TargetHandleList::const_iterator\n l_membuf_iter = l_membufTargetList.begin();\n l_membuf_iter != l_membufTargetList.end();\n ++l_membuf_iter)\n {\n \/\/find SBE image in PNOR\n TARGETING::Target* l_membuf_target = *l_membuf_iter;\n\n uint8_t cur_ec = (*l_membuf_iter)->getAttr<TARGETING::ATTR_EC>();\n\n\n TRACDCOMP( ISTEPS_TRACE::g_trac_isteps_trace, INFO_MRK,\n \"call_sbe_centaur_init() - Find SBE image in PNOR\");\n\n l_errl = SBE::findSBEInPnor(l_membuf_target,\n l_sbePnorAddr,\n l_sbePnorSize,\n NULL);\n if (l_errl)\n {\n TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace, ERR_MRK,\n \"call_sbe_centaur_init() - Error getting image from PNOR. ec=0x%.2X\",\n cur_ec );\n\n TRACFBIN(ISTEPS_TRACE::g_trac_isteps_trace,\n \"call_sbe_centaur_init - l_sbePnorAddr\",l_sbePnorAddr,400);\n\n \/\/ capture the target data in the elog\n ErrlUserDetailsTarget(l_membuf_target).addToLog( l_errl );\n\n \/\/ Create IStep error log and cross reference error that occurred\n l_StepError.addErrorDetails( l_errl );\n\n \/\/ Commit Error\n errlCommit( l_errl, HWPF_COMP_ID );\n continue;\n }\n\n char l_header[10];\n memcpy (l_header, l_sbePnorAddr, 9);\n l_header[9] = '\\0';\n\n TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace,\n \"call_sbe_centaur_init - Loading \"\n \"centaur sbe from pnor, Addr 0x%llX, Size %d, Header %s\",\n l_sbePnorAddr, l_sbePnorSize, l_header);\n\n \/\/ Create a FAPI Target\n const fapi::Target l_fapiTarget( fapi::TARGET_TYPE_MEMBUF_CHIP,\n (const_cast<TARGETING::Target*>(l_membuf_target)));\n\n \/\/ Expand buffer for new image size\n const uint32_t l_customizedMaxSize = MAX_SBE_IMG_SIZE;\n const uint32_t l_buf1Size = MAX_SBE_IMG_SIZE;\n const uint32_t l_buf2Size = MAX_SBE_IMG_SIZE;\n\n uint32_t l_customizedSize = l_customizedMaxSize;\n char * l_pCustomizedImage = (char *)malloc(l_customizedMaxSize);\n void * l_pBuf1 = malloc(l_buf1Size);\n void * l_pBuf2 = malloc(l_buf2Size);\n\n \/\/ Setup args\n std::list<uint64_t> myArgs;\n\n \/\/ Set FapiPoreVeOtherArg: run unlimited instructions\n FapiPoreVeOtherArg *l_otherArg =\n new FapiPoreVeOtherArg(vsbe::RUN_UNLIMITED, vsbe::PORE_SBE);\n \/\/ Entry point\n l_otherArg->iv_entryPoint = const_cast<char*>(\"pnor::_sbe_pnor_start\");\n l_otherArg->iv_mrr = CENTAUR_SBE_PNOR_MRR;\n myArgs.push_back(reinterpret_cast<uint64_t>(l_otherArg));\n\n \/\/ Set FapiPoreVeMemArg for pnor option, base address = 0\n uint32_t base_addr = 0;\n char* l_dataPnor = const_cast<char*>(l_pCustomizedImage);\n FapiPoreVeMemArg* l_memArg = new FapiPoreVeMemArg(ARG_PNOR,\n base_addr, l_customizedSize,\n static_cast<void*>(l_dataPnor));\n myArgs.push_back(reinterpret_cast<uint64_t>(l_memArg));\n\n \/\/ Create state argument to dump out state for debugging purpose\n FapiPoreVeStateArg *l_stateArg = new FapiPoreVeStateArg(NULL);\n l_stateArg->iv_installState = false;\n l_stateArg->iv_extractState = true;\n myArgs.push_back(reinterpret_cast<uint64_t>(l_stateArg));\n\n \/\/ Put out info on target\n TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace,\n \"Running call_sbe_centaur_init on Centaur \"\n \" target HUID %.8X\", TARGETING::get_huid(l_membuf_target));\n\n \/\/ XIP customize is going to look for a PLL ring with a \"stub\"\n \/\/ mem freq -- so set to a default, then clear it (so as not\n \/\/ to mess up MSS HWP later\n l_membuf_target->setAttr<TARGETING::ATTR_MSS_FREQ>(1600);\n\n\n FAPI_INVOKE_HWP( l_errl, cen_xip_customize,\n l_fapiTarget, l_sbePnorAddr,\n l_pCustomizedImage, l_customizedSize,\n l_pBuf1, l_buf1Size,\n l_pBuf2, l_buf2Size );\n\n l_membuf_target->setAttr<TARGETING::ATTR_MSS_FREQ>(0);\n\n if (l_errl)\n {\n TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace,\n \"ERROR 0x%.8X call_sbe_centaur_init - Error returned from\"\n \" cen_xip_customize, l_rc 0x%llX\", l_errl->reasonCode());\n }\n else\n {\n \/\/ Run the engine\n TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace,\n \"call_sbe_centaur_init - Start VSBE engine...\");\n\n FAPI_INVOKE_HWP(l_errl, fapiPoreVe, l_fapiTarget, myArgs);\n\n if (l_errl)\n {\n TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace,\n \"ERROR 0x%.8X call_sbe_centaur_init - Error returned from\"\n \" VSBE engine on this Centaur, l_rc 0x%llX\",\n l_errl->reasonCode());\n l_errl->collectTrace(FAPI_IMP_TRACE_NAME, 1024);\n l_errl->collectTrace(\"ISTEPS_TRACE\", 512);\n }\n \n \/\/ Remove 0x0104000A reading, per Joe, the IPL procedures are no\n \/\/ longer writing information related to the repair loader into\n \/\/ this register\n\n }\n\n \/\/ Freeing memory\n delete l_otherArg;\n delete l_memArg;\n delete l_stateArg;\n free( l_pCustomizedImage );\n free( l_pBuf1 );\n free( l_pBuf2 );\n\n if (l_errl )\n {\n \/\/ capture the target data in the elog\n ErrlUserDetailsTarget(l_membuf_target).addToLog( l_errl );\n\n \/\/ Create IStep error log and cross reference error that occurred\n l_StepError.addErrorDetails( l_errl );\n\n \/\/ Commit Error\n errlCommit( l_errl, HWPF_COMP_ID );\n }\n else\n {\n TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace,\n \"call_sbe_centaur_init - VSBE engine runs successfully \"\n \"on this Centaur\");\n }\n\n } \/\/ end for\n\n TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace,\n \"call_sbe_centaur_init exit\" );\n\n return l_StepError.getErrorHandle();\n}\n\n}; \/\/ end namespace\n\n<commit_msg>Invalid trace on error path in sbe_centaur_init.C<commit_after>\/* IBM_PROLOG_BEGIN_TAG *\/\n\/* This is an automatically generated prolog. *\/\n\/* *\/\n\/* $Source: src\/usr\/hwpf\/hwp\/sbe_centaur_init\/sbe_centaur_init.C $ *\/\n\/* *\/\n\/* IBM CONFIDENTIAL *\/\n\/* *\/\n\/* COPYRIGHT International Business Machines Corp. 2012,2014 *\/\n\/* *\/\n\/* p1 *\/\n\/* *\/\n\/* Object Code Only (OCO) source materials *\/\n\/* Licensed Internal Code Source Materials *\/\n\/* IBM HostBoot Licensed Internal Code *\/\n\/* *\/\n\/* The source code for this program is not published or otherwise *\/\n\/* divested of its trade secrets, irrespective of what has been *\/\n\/* deposited with the U.S. Copyright Office. *\/\n\/* *\/\n\/* Origin: 30 *\/\n\/* *\/\n\/* IBM_PROLOG_END_TAG *\/\n\/**\n * @file sbe_centaur_init.C\n *\n * Support file for IStep:\n * sbe_centaur_init\n *\n *\n *\n * HWP_IGNORE_VERSION_CHECK\n *\n *\/\n\n\n\/******************************************************************************\/\n\/\/ Includes\n\/******************************************************************************\/\n#include <stdint.h>\n\n#include <trace\/interface.H>\n#include <initservice\/taskargs.H>\n#include <errl\/errlentry.H>\n#include <initservice\/isteps_trace.H>\n#include <targeting\/common\/commontargeting.H>\n#include <targeting\/common\/utilFilter.H>\n#include <fapi.H>\n#include <fapiPoreVeArg.H>\n#include <fapiTarget.H>\n#include <fapi.H>\n#include <fapiPlatHwpInvoker.H>\n#include <vfs\/vfs.H>\n#include \"sbe_centaur_init.H\"\n#include <hwpisteperror.H>\n#include <errl\/errludtarget.H>\n#include <sbe\/sbeif.H>\n#include \"cen_xip_customize.H\"\n\nextern fapi::ReturnCode fapiPoreVe(const fapi::Target i_target,\n std::list<uint64_t> & io_sharedObjectArgs);\n\nconst uint64_t REPAIR_LOADER_RETRY_CTR_MASK = 0x000007FC00000000ull;\n\n\/\/ Constants\n\/\/ Memory Relocation Register for Centaur SBE image\nconst uint64_t CENTAUR_SBE_PNOR_MRR = 0;\n\n\/\/ Max SBE image buffer size\nconst uint32_t MAX_SBE_IMG_SIZE = 48 * 1024; \n\nnamespace SBE_CENTAUR_INIT\n{\n\nusing namespace ISTEP;\nusing namespace ISTEP_ERROR;\nusing namespace ERRORLOG;\nusing namespace TARGETING;\nusing namespace fapi;\nusing namespace vsbe;\n\n\n\/\/\n\/\/ Wrapper function to call step 10\n\/\/\nvoid* call_sbe_centaur_init( void *io_pArgs )\n{\n\n TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace,\n \"call_sbe_centaur_init entry\");\n\n \/\/ Get target list to pass in procedure\n TARGETING::TargetHandleList l_membufTargetList;\n getAllChips(l_membufTargetList, TYPE_MEMBUF);\n\n size_t l_sbePnorSize = 0;\n void* l_sbePnorAddr = NULL;\n errlHndl_t l_errl = NULL;\n\n IStepError l_StepError;\n\n \/\/ Loop thru all Centaurs in list\n for (TargetHandleList::const_iterator\n l_membuf_iter = l_membufTargetList.begin();\n l_membuf_iter != l_membufTargetList.end();\n ++l_membuf_iter)\n {\n \/\/find SBE image in PNOR\n TARGETING::Target* l_membuf_target = *l_membuf_iter;\n\n uint8_t cur_ec = (*l_membuf_iter)->getAttr<TARGETING::ATTR_EC>();\n\n\n TRACDCOMP( ISTEPS_TRACE::g_trac_isteps_trace, INFO_MRK,\n \"call_sbe_centaur_init() - Find SBE image in PNOR\");\n\n l_errl = SBE::findSBEInPnor(l_membuf_target,\n l_sbePnorAddr,\n l_sbePnorSize,\n NULL);\n if (l_errl)\n {\n TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace, ERR_MRK,\n \"call_sbe_centaur_init() - Error getting image from PNOR. \"\n \"Target 0x%.8X, EC=0x%.2X\",\n TARGETING::get_huid(l_membuf_target), cur_ec );\n\n \/\/ capture the target data in the elog\n ErrlUserDetailsTarget(l_membuf_target).addToLog( l_errl );\n\n \/\/ Create IStep error log and cross reference error that occurred\n l_StepError.addErrorDetails( l_errl );\n\n \/\/ Commit Error\n errlCommit( l_errl, HWPF_COMP_ID );\n continue;\n }\n\n char l_header[10];\n memcpy (l_header, l_sbePnorAddr, 9);\n l_header[9] = '\\0';\n\n TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace,\n \"call_sbe_centaur_init - Loading \"\n \"centaur sbe from pnor, Addr 0x%llX, Size %d, Header %s\",\n l_sbePnorAddr, l_sbePnorSize, l_header);\n\n \/\/ Create a FAPI Target\n const fapi::Target l_fapiTarget( fapi::TARGET_TYPE_MEMBUF_CHIP,\n (const_cast<TARGETING::Target*>(l_membuf_target)));\n\n \/\/ Expand buffer for new image size\n const uint32_t l_customizedMaxSize = MAX_SBE_IMG_SIZE;\n const uint32_t l_buf1Size = MAX_SBE_IMG_SIZE;\n const uint32_t l_buf2Size = MAX_SBE_IMG_SIZE;\n\n uint32_t l_customizedSize = l_customizedMaxSize;\n char * l_pCustomizedImage = (char *)malloc(l_customizedMaxSize);\n void * l_pBuf1 = malloc(l_buf1Size);\n void * l_pBuf2 = malloc(l_buf2Size);\n\n \/\/ Setup args\n std::list<uint64_t> myArgs;\n\n \/\/ Set FapiPoreVeOtherArg: run unlimited instructions\n FapiPoreVeOtherArg *l_otherArg =\n new FapiPoreVeOtherArg(vsbe::RUN_UNLIMITED, vsbe::PORE_SBE);\n \/\/ Entry point\n l_otherArg->iv_entryPoint = const_cast<char*>(\"pnor::_sbe_pnor_start\");\n l_otherArg->iv_mrr = CENTAUR_SBE_PNOR_MRR;\n myArgs.push_back(reinterpret_cast<uint64_t>(l_otherArg));\n\n \/\/ Set FapiPoreVeMemArg for pnor option, base address = 0\n uint32_t base_addr = 0;\n char* l_dataPnor = const_cast<char*>(l_pCustomizedImage);\n FapiPoreVeMemArg* l_memArg = new FapiPoreVeMemArg(ARG_PNOR,\n base_addr, l_customizedSize,\n static_cast<void*>(l_dataPnor));\n myArgs.push_back(reinterpret_cast<uint64_t>(l_memArg));\n\n \/\/ Create state argument to dump out state for debugging purpose\n FapiPoreVeStateArg *l_stateArg = new FapiPoreVeStateArg(NULL);\n l_stateArg->iv_installState = false;\n l_stateArg->iv_extractState = true;\n myArgs.push_back(reinterpret_cast<uint64_t>(l_stateArg));\n\n \/\/ Put out info on target\n TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace,\n \"Running call_sbe_centaur_init on Centaur \"\n \" target HUID %.8X\", TARGETING::get_huid(l_membuf_target));\n\n \/\/ XIP customize is going to look for a PLL ring with a \"stub\"\n \/\/ mem freq -- so set to a default, then clear it (so as not\n \/\/ to mess up MSS HWP later\n l_membuf_target->setAttr<TARGETING::ATTR_MSS_FREQ>(1600);\n\n\n FAPI_INVOKE_HWP( l_errl, cen_xip_customize,\n l_fapiTarget, l_sbePnorAddr,\n l_pCustomizedImage, l_customizedSize,\n l_pBuf1, l_buf1Size,\n l_pBuf2, l_buf2Size );\n\n l_membuf_target->setAttr<TARGETING::ATTR_MSS_FREQ>(0);\n\n if (l_errl)\n {\n TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace,\n \"ERROR 0x%.8X call_sbe_centaur_init - Error returned from\"\n \" cen_xip_customize, l_rc 0x%llX\", l_errl->reasonCode());\n }\n else\n {\n \/\/ Run the engine\n TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace,\n \"call_sbe_centaur_init - Start VSBE engine...\");\n\n FAPI_INVOKE_HWP(l_errl, fapiPoreVe, l_fapiTarget, myArgs);\n\n if (l_errl)\n {\n TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace,\n \"ERROR 0x%.8X call_sbe_centaur_init - Error returned from\"\n \" VSBE engine on this Centaur, l_rc 0x%llX\",\n l_errl->reasonCode());\n l_errl->collectTrace(FAPI_IMP_TRACE_NAME, 1024);\n l_errl->collectTrace(\"ISTEPS_TRACE\", 512);\n }\n \n \/\/ Remove 0x0104000A reading, per Joe, the IPL procedures are no\n \/\/ longer writing information related to the repair loader into\n \/\/ this register\n\n }\n\n \/\/ Freeing memory\n delete l_otherArg;\n delete l_memArg;\n delete l_stateArg;\n free( l_pCustomizedImage );\n free( l_pBuf1 );\n free( l_pBuf2 );\n\n if (l_errl )\n {\n \/\/ capture the target data in the elog\n ErrlUserDetailsTarget(l_membuf_target).addToLog( l_errl );\n\n \/\/ Create IStep error log and cross reference error that occurred\n l_StepError.addErrorDetails( l_errl );\n\n \/\/ Commit Error\n errlCommit( l_errl, HWPF_COMP_ID );\n }\n else\n {\n TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace,\n \"call_sbe_centaur_init - VSBE engine runs successfully \"\n \"on this Centaur\");\n }\n\n } \/\/ end for\n\n TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace,\n \"call_sbe_centaur_init exit\" );\n\n return l_StepError.getErrorHandle();\n}\n\n}; \/\/ end namespace\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n\n nsjail\n -----------------------------------------\n\n Copyright 2014 Google Inc. All Rights Reserved.\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n\n*\/\n\n#include \"nsjail.h\"\n\n#include <fcntl.h>\n#include <poll.h>\n#include <signal.h>\n#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <sys\/ioctl.h>\n#include <sys\/time.h>\n#include <termios.h>\n#include <unistd.h>\n\n#include <algorithm>\n#include <cerrno>\n#include <memory>\n#include <vector>\n\n#include \"cmdline.h\"\n#include \"logs.h\"\n#include \"macros.h\"\n#include \"net.h\"\n#include \"sandbox.h\"\n#include \"subproc.h\"\n#include \"util.h\"\n\nnamespace nsjail {\n\nstatic __thread int sigFatal = 0;\nstatic __thread bool showProc = false;\n\nstatic void sigHandler(int sig) {\n\tif (sig == SIGALRM || sig == SIGCHLD || sig == SIGPIPE) {\n\t\treturn;\n\t}\n\tif (sig == SIGUSR1 || sig == SIGQUIT) {\n\t\tshowProc = true;\n\t\treturn;\n\t}\n\tsigFatal = sig;\n}\n\nstatic bool setSigHandler(int sig) {\n\tLOG_D(\"Setting sighandler for signal %s (%d)\", util::sigName(sig).c_str(), sig);\n\n\tsigset_t smask;\n\tsigemptyset(&smask);\n\n\tstruct sigaction sa;\n\tsa.sa_handler = sigHandler;\n\tsa.sa_mask = smask;\n\tsa.sa_flags = 0;\n\tsa.sa_restorer = NULL;\n\n\tif (sig == SIGTTIN || sig == SIGTTOU) {\n\t\tsa.sa_handler = SIG_IGN;\n\t}\n\tif (sigaction(sig, &sa, NULL) == -1) {\n\t\tPLOG_E(\"sigaction(%d)\", sig);\n\t\treturn false;\n\t}\n\treturn true;\n}\n\nstatic bool setSigHandlers(void) {\n\tfor (const auto& i : nssigs) {\n\t\tif (!setSigHandler(i)) {\n\t\t\treturn false;\n\t\t}\n\t}\n\treturn true;\n}\n\nstatic bool setTimer(nsjconf_t* nsjconf) {\n\tif (nsjconf->mode == MODE_STANDALONE_EXECVE) {\n\t\treturn true;\n\t}\n\n\tstruct itimerval it = {\n\t .it_interval =\n\t\t{\n\t\t .tv_sec = 1,\n\t\t .tv_usec = 0,\n\t\t},\n\t .it_value =\n\t\t{\n\t\t .tv_sec = 1,\n\t\t .tv_usec = 0,\n\t\t},\n\t};\n\tif (setitimer(ITIMER_REAL, &it, NULL) == -1) {\n\t\tPLOG_E(\"setitimer(ITIMER_REAL)\");\n\t\treturn false;\n\t}\n\treturn true;\n}\n\nstatic bool pipeTraffic(nsjconf_t* nsjconf, int listenfd) {\n\tstd::vector<struct pollfd> fds;\n\tfds.reserve(nsjconf->pipes.size() * 3 + 1);\n\tfor (const auto& p : nsjconf->pipes) {\n\t\tfds.push_back({\n\t\t .fd = p.sock_fd,\n\t\t .events = POLLIN | POLLOUT,\n\t\t .revents = 0,\n\t\t});\n\t\tfds.push_back({\n\t\t .fd = p.pipe_in,\n\t\t .events = POLLOUT,\n\t\t .revents = 0,\n\t\t});\n\t\tfds.push_back({\n\t\t .fd = p.pipe_out,\n\t\t .events = POLLIN,\n\t\t .revents = 0,\n\t\t});\n\t}\n\tfds.push_back({\n\t .fd = listenfd,\n\t .events = POLLIN,\n\t .revents = 0,\n\t});\n\tLOG_D(\"Waiting for fd activity\");\n\twhile (poll(fds.data(), fds.size(), -1) > 0) {\n\t\tif (sigFatal > 0 || showProc) {\n\t\t\treturn false;\n\t\t}\n\t\tif (fds.back().revents != 0) {\n\t\t\tLOG_D(\"New connection ready\");\n\t\t\treturn true;\n\t\t}\n\t\tbool cleanup = false;\n\t\tfor (size_t i = 0; i < fds.size() - 1; ++i) {\n\t\t\tif (fds[i].revents & POLLIN) {\n\t\t\t\tfds[i].events &= ~POLLIN;\n\t\t\t}\n\t\t\tif (fds[i].revents & POLLOUT) {\n\t\t\t\tfds[i].events &= ~POLLOUT;\n\t\t\t}\n\t\t}\n\t\tfor (size_t i = 0; i < fds.size() - 3; i += 3) {\n\t\t\tconst size_t pipe_no = i \/ 3;\n\t\t\tint in, out;\n\t\t\tconst char* direction;\n\t\t\tbool closed = false;\n\t\t\tstd::tuple<int, int, const char*> direction_map[] = {\n\t\t\t {i, i + 1, \"in\"}, {i + 2, i, \"out\"}};\n\t\t\tfor (const auto& entry : direction_map) {\n\t\t\t\tstd::tie(in, out, direction) = entry;\n\t\t\t\tbool in_ready = (fds[in].events & POLLIN) == 0 ||\n\t\t\t\t\t\t(fds[in].revents & POLLIN) == POLLIN;\n\t\t\t\tbool out_ready = (fds[out].events & POLLOUT) == 0 ||\n\t\t\t\t\t\t (fds[out].revents & POLLOUT) == POLLOUT;\n\t\t\t\tif (in_ready && out_ready) {\n\t\t\t\t\tLOG_D(\"#%zu piping data %s\", pipe_no, direction);\n\t\t\t\t\tssize_t rv = splice(fds[in].fd, nullptr, fds[out].fd,\n\t\t\t\t\t nullptr, 4096, SPLICE_F_NONBLOCK);\n\t\t\t\t\tif (rv == -1 && errno != EAGAIN) {\n\t\t\t\t\t\tPLOG_E(\"splice fd pair #%zu {%d, %d}\\n\", pipe_no,\n\t\t\t\t\t\t fds[in].fd, fds[out].fd);\n\t\t\t\t\t}\n\t\t\t\t\tif (rv == 0) {\n\t\t\t\t\t\tclosed = true;\n\t\t\t\t\t}\n\t\t\t\t\tfds[in].events |= POLLIN;\n\t\t\t\t\tfds[out].events |= POLLOUT;\n\t\t\t\t}\n\t\t\t\tif ((fds[in].revents & (POLLERR | POLLHUP)) != 0 ||\n\t\t\t\t (fds[out].revents & (POLLERR | POLLHUP)) != 0) {\n\t\t\t\t\tclosed = true;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (closed) {\n\t\t\t\tLOG_D(\"#%zu connection closed\", pipe_no);\n\t\t\t\tcleanup = true;\n\t\t\t\tclose(nsjconf->pipes[pipe_no].sock_fd);\n\t\t\t\tclose(nsjconf->pipes[pipe_no].pipe_in);\n\t\t\t\tclose(nsjconf->pipes[pipe_no].pipe_out);\n\t\t\t\tnsjconf->pipes[pipe_no] = {};\n\t\t\t}\n\t\t}\n\t\tif (cleanup) {\n\t\t\tbreak;\n\t\t}\n\t}\n\tnsjconf->pipes.erase(std::remove(nsjconf->pipes.begin(), nsjconf->pipes.end(), pipemap_t{}),\n\t nsjconf->pipes.end());\n\treturn false;\n}\n\nstatic int listenMode(nsjconf_t* nsjconf) {\n\tint listenfd = net::getRecvSocket(nsjconf->bindhost.c_str(), nsjconf->port);\n\tif (listenfd == -1) {\n\t\treturn EXIT_FAILURE;\n\t}\n\tfor (;;) {\n\t\tif (sigFatal > 0) {\n\t\t\tsubproc::killAndReapAll(nsjconf);\n\t\t\tlogs::logStop(sigFatal);\n\t\t\tclose(listenfd);\n\t\t\treturn EXIT_SUCCESS;\n\t\t}\n\t\tif (showProc) {\n\t\t\tshowProc = false;\n\t\t\tsubproc::displayProc(nsjconf);\n\t\t}\n\t\tif (pipeTraffic(nsjconf, listenfd)) {\n\t\t\tint connfd = net::acceptConn(listenfd);\n\t\t\tif (connfd >= 0) {\n\t\t\t\tint in[2];\n\t\t\t\tint out[2];\n\t\t\t\tif (pipe(in) != 0 || pipe(out) != 0) {\n\t\t\t\t\tPLOG_E(\"pipe\");\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tnsjconf->pipes.push_back({\n\t\t\t\t .sock_fd = connfd,\n\t\t\t\t .pipe_in = in[1],\n\t\t\t\t .pipe_out = out[0],\n\t\t\t\t});\n\t\t\t\tsubproc::runChild(nsjconf, connfd, in[0], out[1], out[1]);\n\t\t\t\tclose(in[0]);\n\t\t\t\tclose(out[1]);\n\t\t\t}\n\t\t}\n\t\tsubproc::reapProc(nsjconf);\n\t}\n}\n\nstatic int standaloneMode(nsjconf_t* nsjconf) {\n\tfor (;;) {\n\t\tif (!subproc::runChild(\n\t\t\tnsjconf, \/* netfd= *\/ -1, STDIN_FILENO, STDOUT_FILENO, STDERR_FILENO)) {\n\t\t\tLOG_E(\"Couldn't launch the child process\");\n\t\t\treturn 0xff;\n\t\t}\n\t\tfor (;;) {\n\t\t\tint child_status = subproc::reapProc(nsjconf);\n\t\t\tif (subproc::countProc(nsjconf) == 0) {\n\t\t\t\tif (nsjconf->mode == MODE_STANDALONE_ONCE) {\n\t\t\t\t\treturn child_status;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tif (showProc) {\n\t\t\t\tshowProc = false;\n\t\t\t\tsubproc::displayProc(nsjconf);\n\t\t\t}\n\t\t\tif (sigFatal > 0) {\n\t\t\t\tsubproc::killAndReapAll(nsjconf);\n\t\t\t\tlogs::logStop(sigFatal);\n\t\t\t\treturn (128 + sigFatal);\n\t\t\t}\n\t\t\tpause();\n\t\t}\n\t}\n\t\/\/ not reached\n}\n\nstd::unique_ptr<struct termios> getTC(int fd) {\n\tstd::unique_ptr<struct termios> trm(new struct termios);\n\n\tif (ioctl(fd, TCGETS, trm.get()) == -1) {\n\t\tPLOG_D(\"ioctl(fd=%d, TCGETS) failed\", fd);\n\t\treturn nullptr;\n\t}\n\tLOG_D(\"Saved the current state of the TTY\");\n\treturn trm;\n}\n\nvoid setTC(int fd, const struct termios* trm) {\n\tif (!trm) {\n\t\treturn;\n\t}\n\tif (ioctl(fd, TCSETS, trm) == -1) {\n\t\tPLOG_W(\"ioctl(fd=%d, TCSETS) failed\", fd);\n\t\treturn;\n\t}\n\tif (tcflush(fd, TCIFLUSH) == -1) {\n\t\tPLOG_W(\"tcflush(fd=%d, TCIFLUSH) failed\", fd);\n\t\treturn;\n\t}\n}\n\n} \/\/ namespace nsjail\n\nint main(int argc, char* argv[]) {\n\tstd::unique_ptr<nsjconf_t> nsjconf = cmdline::parseArgs(argc, argv);\n\tstd::unique_ptr<struct termios> trm = nsjail::getTC(STDIN_FILENO);\n\n\tif (!nsjconf) {\n\t\tLOG_F(\"Couldn't parse cmdline options\");\n\t}\n\tif (nsjconf->daemonize && (daemon(0, 0) == -1)) {\n\t\tPLOG_F(\"daemon\");\n\t}\n\tcmdline::logParams(nsjconf.get());\n\tif (!nsjail::setSigHandlers()) {\n\t\tLOG_F(\"nsjail::setSigHandlers() failed\");\n\t}\n\tif (!nsjail::setTimer(nsjconf.get())) {\n\t\tLOG_F(\"nsjail::setTimer() failed\");\n\t}\n\tif (!sandbox::preparePolicy(nsjconf.get())) {\n\t\tLOG_F(\"Couldn't prepare sandboxing policy\");\n\t}\n\n\tint ret = 0;\n\tif (nsjconf->mode == MODE_LISTEN_TCP) {\n\t\tret = nsjail::listenMode(nsjconf.get());\n\t} else {\n\t\tret = nsjail::standaloneMode(nsjconf.get());\n\t}\n\n\tsandbox::closePolicy(nsjconf.get());\n\t\/* Try to restore the underlying console's params in case some program has changed it *\/\n\tif (!nsjconf->daemonize) {\n\t\tnsjail::setTC(STDIN_FILENO, trm.get());\n\t}\n\n\tLOG_D(\"Returning with %d\", ret);\n\treturn ret;\n}\n<commit_msg>nsjail: don't change cwd during daemon()<commit_after>\/*\n\n nsjail\n -----------------------------------------\n\n Copyright 2014 Google Inc. All Rights Reserved.\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n\n*\/\n\n#include \"nsjail.h\"\n\n#include <fcntl.h>\n#include <poll.h>\n#include <signal.h>\n#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <sys\/ioctl.h>\n#include <sys\/time.h>\n#include <termios.h>\n#include <unistd.h>\n\n#include <algorithm>\n#include <cerrno>\n#include <memory>\n#include <vector>\n\n#include \"cmdline.h\"\n#include \"logs.h\"\n#include \"macros.h\"\n#include \"net.h\"\n#include \"sandbox.h\"\n#include \"subproc.h\"\n#include \"util.h\"\n\nnamespace nsjail {\n\nstatic __thread int sigFatal = 0;\nstatic __thread bool showProc = false;\n\nstatic void sigHandler(int sig) {\n\tif (sig == SIGALRM || sig == SIGCHLD || sig == SIGPIPE) {\n\t\treturn;\n\t}\n\tif (sig == SIGUSR1 || sig == SIGQUIT) {\n\t\tshowProc = true;\n\t\treturn;\n\t}\n\tsigFatal = sig;\n}\n\nstatic bool setSigHandler(int sig) {\n\tLOG_D(\"Setting sighandler for signal %s (%d)\", util::sigName(sig).c_str(), sig);\n\n\tsigset_t smask;\n\tsigemptyset(&smask);\n\n\tstruct sigaction sa;\n\tsa.sa_handler = sigHandler;\n\tsa.sa_mask = smask;\n\tsa.sa_flags = 0;\n\tsa.sa_restorer = NULL;\n\n\tif (sig == SIGTTIN || sig == SIGTTOU) {\n\t\tsa.sa_handler = SIG_IGN;\n\t}\n\tif (sigaction(sig, &sa, NULL) == -1) {\n\t\tPLOG_E(\"sigaction(%d)\", sig);\n\t\treturn false;\n\t}\n\treturn true;\n}\n\nstatic bool setSigHandlers(void) {\n\tfor (const auto& i : nssigs) {\n\t\tif (!setSigHandler(i)) {\n\t\t\treturn false;\n\t\t}\n\t}\n\treturn true;\n}\n\nstatic bool setTimer(nsjconf_t* nsjconf) {\n\tif (nsjconf->mode == MODE_STANDALONE_EXECVE) {\n\t\treturn true;\n\t}\n\n\tstruct itimerval it = {\n\t .it_interval =\n\t\t{\n\t\t .tv_sec = 1,\n\t\t .tv_usec = 0,\n\t\t},\n\t .it_value =\n\t\t{\n\t\t .tv_sec = 1,\n\t\t .tv_usec = 0,\n\t\t},\n\t};\n\tif (setitimer(ITIMER_REAL, &it, NULL) == -1) {\n\t\tPLOG_E(\"setitimer(ITIMER_REAL)\");\n\t\treturn false;\n\t}\n\treturn true;\n}\n\nstatic bool pipeTraffic(nsjconf_t* nsjconf, int listenfd) {\n\tstd::vector<struct pollfd> fds;\n\tfds.reserve(nsjconf->pipes.size() * 3 + 1);\n\tfor (const auto& p : nsjconf->pipes) {\n\t\tfds.push_back({\n\t\t .fd = p.sock_fd,\n\t\t .events = POLLIN | POLLOUT,\n\t\t .revents = 0,\n\t\t});\n\t\tfds.push_back({\n\t\t .fd = p.pipe_in,\n\t\t .events = POLLOUT,\n\t\t .revents = 0,\n\t\t});\n\t\tfds.push_back({\n\t\t .fd = p.pipe_out,\n\t\t .events = POLLIN,\n\t\t .revents = 0,\n\t\t});\n\t}\n\tfds.push_back({\n\t .fd = listenfd,\n\t .events = POLLIN,\n\t .revents = 0,\n\t});\n\tLOG_D(\"Waiting for fd activity\");\n\twhile (poll(fds.data(), fds.size(), -1) > 0) {\n\t\tif (sigFatal > 0 || showProc) {\n\t\t\treturn false;\n\t\t}\n\t\tif (fds.back().revents != 0) {\n\t\t\tLOG_D(\"New connection ready\");\n\t\t\treturn true;\n\t\t}\n\t\tbool cleanup = false;\n\t\tfor (size_t i = 0; i < fds.size() - 1; ++i) {\n\t\t\tif (fds[i].revents & POLLIN) {\n\t\t\t\tfds[i].events &= ~POLLIN;\n\t\t\t}\n\t\t\tif (fds[i].revents & POLLOUT) {\n\t\t\t\tfds[i].events &= ~POLLOUT;\n\t\t\t}\n\t\t}\n\t\tfor (size_t i = 0; i < fds.size() - 3; i += 3) {\n\t\t\tconst size_t pipe_no = i \/ 3;\n\t\t\tint in, out;\n\t\t\tconst char* direction;\n\t\t\tbool closed = false;\n\t\t\tstd::tuple<int, int, const char*> direction_map[] = {\n\t\t\t {i, i + 1, \"in\"}, {i + 2, i, \"out\"}};\n\t\t\tfor (const auto& entry : direction_map) {\n\t\t\t\tstd::tie(in, out, direction) = entry;\n\t\t\t\tbool in_ready = (fds[in].events & POLLIN) == 0 ||\n\t\t\t\t\t\t(fds[in].revents & POLLIN) == POLLIN;\n\t\t\t\tbool out_ready = (fds[out].events & POLLOUT) == 0 ||\n\t\t\t\t\t\t (fds[out].revents & POLLOUT) == POLLOUT;\n\t\t\t\tif (in_ready && out_ready) {\n\t\t\t\t\tLOG_D(\"#%zu piping data %s\", pipe_no, direction);\n\t\t\t\t\tssize_t rv = splice(fds[in].fd, nullptr, fds[out].fd,\n\t\t\t\t\t nullptr, 4096, SPLICE_F_NONBLOCK);\n\t\t\t\t\tif (rv == -1 && errno != EAGAIN) {\n\t\t\t\t\t\tPLOG_E(\"splice fd pair #%zu {%d, %d}\\n\", pipe_no,\n\t\t\t\t\t\t fds[in].fd, fds[out].fd);\n\t\t\t\t\t}\n\t\t\t\t\tif (rv == 0) {\n\t\t\t\t\t\tclosed = true;\n\t\t\t\t\t}\n\t\t\t\t\tfds[in].events |= POLLIN;\n\t\t\t\t\tfds[out].events |= POLLOUT;\n\t\t\t\t}\n\t\t\t\tif ((fds[in].revents & (POLLERR | POLLHUP)) != 0 ||\n\t\t\t\t (fds[out].revents & (POLLERR | POLLHUP)) != 0) {\n\t\t\t\t\tclosed = true;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (closed) {\n\t\t\t\tLOG_D(\"#%zu connection closed\", pipe_no);\n\t\t\t\tcleanup = true;\n\t\t\t\tclose(nsjconf->pipes[pipe_no].sock_fd);\n\t\t\t\tclose(nsjconf->pipes[pipe_no].pipe_in);\n\t\t\t\tclose(nsjconf->pipes[pipe_no].pipe_out);\n\t\t\t\tnsjconf->pipes[pipe_no] = {};\n\t\t\t}\n\t\t}\n\t\tif (cleanup) {\n\t\t\tbreak;\n\t\t}\n\t}\n\tnsjconf->pipes.erase(std::remove(nsjconf->pipes.begin(), nsjconf->pipes.end(), pipemap_t{}),\n\t nsjconf->pipes.end());\n\treturn false;\n}\n\nstatic int listenMode(nsjconf_t* nsjconf) {\n\tint listenfd = net::getRecvSocket(nsjconf->bindhost.c_str(), nsjconf->port);\n\tif (listenfd == -1) {\n\t\treturn EXIT_FAILURE;\n\t}\n\tfor (;;) {\n\t\tif (sigFatal > 0) {\n\t\t\tsubproc::killAndReapAll(nsjconf);\n\t\t\tlogs::logStop(sigFatal);\n\t\t\tclose(listenfd);\n\t\t\treturn EXIT_SUCCESS;\n\t\t}\n\t\tif (showProc) {\n\t\t\tshowProc = false;\n\t\t\tsubproc::displayProc(nsjconf);\n\t\t}\n\t\tif (pipeTraffic(nsjconf, listenfd)) {\n\t\t\tint connfd = net::acceptConn(listenfd);\n\t\t\tif (connfd >= 0) {\n\t\t\t\tint in[2];\n\t\t\t\tint out[2];\n\t\t\t\tif (pipe(in) != 0 || pipe(out) != 0) {\n\t\t\t\t\tPLOG_E(\"pipe\");\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tnsjconf->pipes.push_back({\n\t\t\t\t .sock_fd = connfd,\n\t\t\t\t .pipe_in = in[1],\n\t\t\t\t .pipe_out = out[0],\n\t\t\t\t});\n\t\t\t\tsubproc::runChild(nsjconf, connfd, in[0], out[1], out[1]);\n\t\t\t\tclose(in[0]);\n\t\t\t\tclose(out[1]);\n\t\t\t}\n\t\t}\n\t\tsubproc::reapProc(nsjconf);\n\t}\n}\n\nstatic int standaloneMode(nsjconf_t* nsjconf) {\n\tfor (;;) {\n\t\tif (!subproc::runChild(\n\t\t\tnsjconf, \/* netfd= *\/ -1, STDIN_FILENO, STDOUT_FILENO, STDERR_FILENO)) {\n\t\t\tLOG_E(\"Couldn't launch the child process\");\n\t\t\treturn 0xff;\n\t\t}\n\t\tfor (;;) {\n\t\t\tint child_status = subproc::reapProc(nsjconf);\n\t\t\tif (subproc::countProc(nsjconf) == 0) {\n\t\t\t\tif (nsjconf->mode == MODE_STANDALONE_ONCE) {\n\t\t\t\t\treturn child_status;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tif (showProc) {\n\t\t\t\tshowProc = false;\n\t\t\t\tsubproc::displayProc(nsjconf);\n\t\t\t}\n\t\t\tif (sigFatal > 0) {\n\t\t\t\tsubproc::killAndReapAll(nsjconf);\n\t\t\t\tlogs::logStop(sigFatal);\n\t\t\t\treturn (128 + sigFatal);\n\t\t\t}\n\t\t\tpause();\n\t\t}\n\t}\n\t\/\/ not reached\n}\n\nstd::unique_ptr<struct termios> getTC(int fd) {\n\tstd::unique_ptr<struct termios> trm(new struct termios);\n\n\tif (ioctl(fd, TCGETS, trm.get()) == -1) {\n\t\tPLOG_D(\"ioctl(fd=%d, TCGETS) failed\", fd);\n\t\treturn nullptr;\n\t}\n\tLOG_D(\"Saved the current state of the TTY\");\n\treturn trm;\n}\n\nvoid setTC(int fd, const struct termios* trm) {\n\tif (!trm) {\n\t\treturn;\n\t}\n\tif (ioctl(fd, TCSETS, trm) == -1) {\n\t\tPLOG_W(\"ioctl(fd=%d, TCSETS) failed\", fd);\n\t\treturn;\n\t}\n\tif (tcflush(fd, TCIFLUSH) == -1) {\n\t\tPLOG_W(\"tcflush(fd=%d, TCIFLUSH) failed\", fd);\n\t\treturn;\n\t}\n}\n\n} \/\/ namespace nsjail\n\nint main(int argc, char* argv[]) {\n\tstd::unique_ptr<nsjconf_t> nsjconf = cmdline::parseArgs(argc, argv);\n\tstd::unique_ptr<struct termios> trm = nsjail::getTC(STDIN_FILENO);\n\n\tif (!nsjconf) {\n\t\tLOG_F(\"Couldn't parse cmdline options\");\n\t}\n\tif (nsjconf->daemonize && (daemon(\/* nochdir= *\/ 1, \/* noclose= *\/ 0) == -1)) {\n\t\tPLOG_F(\"daemon\");\n\t}\n\tcmdline::logParams(nsjconf.get());\n\tif (!nsjail::setSigHandlers()) {\n\t\tLOG_F(\"nsjail::setSigHandlers() failed\");\n\t}\n\tif (!nsjail::setTimer(nsjconf.get())) {\n\t\tLOG_F(\"nsjail::setTimer() failed\");\n\t}\n\tif (!sandbox::preparePolicy(nsjconf.get())) {\n\t\tLOG_F(\"Couldn't prepare sandboxing policy\");\n\t}\n\n\tint ret = 0;\n\tif (nsjconf->mode == MODE_LISTEN_TCP) {\n\t\tret = nsjail::listenMode(nsjconf.get());\n\t} else {\n\t\tret = nsjail::standaloneMode(nsjconf.get());\n\t}\n\n\tsandbox::closePolicy(nsjconf.get());\n\t\/* Try to restore the underlying console's params in case some program has changed it *\/\n\tif (!nsjconf->daemonize) {\n\t\tnsjail::setTC(STDIN_FILENO, trm.get());\n\t}\n\n\tLOG_D(\"Returning with %d\", ret);\n\treturn ret;\n}\n<|endoftext|>"} {"text":"<commit_before>#include <kms++util\/resourcemanager.h>\n#include <algorithm>\n#include <kms++util\/strhelpers.h>\n\nusing namespace kms;\nusing namespace std;\n\ntemplate<class C, class T>\nauto contains(const C& v, const T& x)\n-> decltype(end(v), true)\n{\n\treturn end(v) != std::find(begin(v), end(v), x);\n}\n\nResourceManager::ResourceManager(Card& card)\n\t: m_card(card)\n{\n}\n\nvoid ResourceManager::reset()\n{\n\tm_reserved_connectors.clear();\n\tm_reserved_crtcs.clear();\n\tm_reserved_planes.clear();\n}\n\nstatic Connector* find_connector(Card& card, const vector<Connector*> reserved)\n{\n\tfor (Connector* conn : card.get_connectors()) {\n\t\tif (!conn->connected())\n\t\t\tcontinue;\n\n\t\tif (contains(reserved, conn))\n\t\t\tcontinue;\n\n\t\treturn conn;\n\t}\n\n\treturn nullptr;\n}\n\nstatic Connector* resolve_connector(Card& card, const string& name, const vector<Connector*> reserved)\n{\n\tauto connectors = card.get_connectors();\n\n\tif (name[0] == '@') {\n\t\tchar* endptr;\n\t\tunsigned id = strtoul(name.c_str() + 1, &endptr, 10);\n\t\tif (*endptr == 0) {\n\t\t\tConnector* c = card.get_connector(id);\n\n\t\t\tif (!c || contains(reserved, c))\n\t\t\t\treturn nullptr;\n\n\t\t\treturn c;\n\t\t}\n\t} else {\n\t\tchar* endptr;\n\t\tunsigned idx = strtoul(name.c_str(), &endptr, 10);\n\t\tif (*endptr == 0) {\n\t\t\tif (idx >= connectors.size())\n\t\t\t\treturn nullptr;\n\n\t\t\tConnector* c = connectors[idx];\n\n\t\t\tif (contains(reserved, c))\n\t\t\t\treturn nullptr;\n\n\t\t\treturn c;\n\t\t}\n\t}\n\n\tfor (Connector* conn : connectors) {\n\t\tif (to_lower(conn->fullname()).find(to_lower(name)) == string::npos)\n\t\t\tcontinue;\n\n\t\tif (contains(reserved, conn))\n\t\t\tcontinue;\n\n\t\treturn conn;\n\t}\n\n\treturn nullptr;\n}\n\nConnector* ResourceManager::reserve_connector(const string& name)\n{\n\tConnector* conn;\n\n\tif (name.empty())\n\t\tconn = find_connector(m_card, m_reserved_connectors);\n\telse\n\t\tconn = resolve_connector(m_card, name, m_reserved_connectors);\n\n\tif (!conn)\n\t\treturn nullptr;\n\n\tm_reserved_connectors.push_back(conn);\n\treturn conn;\n}\n\nConnector* ResourceManager::reserve_connector(Connector* conn)\n{\n\tif (!conn)\n\t\treturn nullptr;\n\n\tif (contains(m_reserved_connectors, conn))\n\t\treturn nullptr;\n\n\tm_reserved_connectors.push_back(conn);\n\treturn conn;\n}\n\nCrtc* ResourceManager::reserve_crtc(Connector* conn)\n{\n\tif (!conn)\n\t\treturn nullptr;\n\n\tif (Crtc* crtc = conn->get_current_crtc()) {\n\t\tm_reserved_crtcs.push_back(crtc);\n\t\treturn crtc;\n\t}\n\n\tfor (Crtc* crtc : conn->get_possible_crtcs()) {\n\t\tif (contains(m_reserved_crtcs, crtc))\n\t\t\tcontinue;\n\n\t\tm_reserved_crtcs.push_back(crtc);\n\t\treturn crtc;\n\t}\n\n\treturn nullptr;\n}\n\nPlane* ResourceManager::reserve_plane(Crtc* crtc, PlaneType type, PixelFormat format)\n{\n\tif (!crtc)\n\t\treturn nullptr;\n\n\tfor (Plane* plane : crtc->get_possible_planes()) {\n\t\tif (plane->plane_type() == type)\n\t\t\tcontinue;\n\n\t\tif (format != PixelFormat::Undefined && !plane->supports_format(format))\n\t\t\tcontinue;\n\n\t\tif (contains(m_reserved_planes, plane))\n\t\t\tcontinue;\n\n\t\tm_reserved_planes.push_back(plane);\n\t\treturn plane;\n\t}\n\n\treturn nullptr;\n}\n\nPlane* ResourceManager::reserve_generic_plane(Crtc* crtc, PixelFormat format)\n{\n\tif (!crtc)\n\t\treturn nullptr;\n\n\tfor (Plane* plane : crtc->get_possible_planes()) {\n\t\tif (plane->plane_type() == PlaneType::Cursor)\n\t\t\tcontinue;\n\n\t\tif (format != PixelFormat::Undefined && !plane->supports_format(format))\n\t\t\tcontinue;\n\n\t\tif (contains(m_reserved_planes, plane))\n\t\t\tcontinue;\n\n\t\tm_reserved_planes.push_back(plane);\n\t\treturn plane;\n\t}\n\n\treturn nullptr;\n}\n\nPlane* ResourceManager::reserve_primary_plane(Crtc* crtc, PixelFormat format)\n{\n\treturn reserve_plane(crtc, PlaneType::Primary, format);\n}\n\nPlane* ResourceManager::reserve_overlay_plane(Crtc* crtc, PixelFormat format)\n{\n\treturn reserve_plane(crtc, PlaneType::Overlay, format);\n}\n<commit_msg>resmgr: fix reserve_plane()<commit_after>#include <kms++util\/resourcemanager.h>\n#include <algorithm>\n#include <kms++util\/strhelpers.h>\n\nusing namespace kms;\nusing namespace std;\n\ntemplate<class C, class T>\nauto contains(const C& v, const T& x)\n-> decltype(end(v), true)\n{\n\treturn end(v) != std::find(begin(v), end(v), x);\n}\n\nResourceManager::ResourceManager(Card& card)\n\t: m_card(card)\n{\n}\n\nvoid ResourceManager::reset()\n{\n\tm_reserved_connectors.clear();\n\tm_reserved_crtcs.clear();\n\tm_reserved_planes.clear();\n}\n\nstatic Connector* find_connector(Card& card, const vector<Connector*> reserved)\n{\n\tfor (Connector* conn : card.get_connectors()) {\n\t\tif (!conn->connected())\n\t\t\tcontinue;\n\n\t\tif (contains(reserved, conn))\n\t\t\tcontinue;\n\n\t\treturn conn;\n\t}\n\n\treturn nullptr;\n}\n\nstatic Connector* resolve_connector(Card& card, const string& name, const vector<Connector*> reserved)\n{\n\tauto connectors = card.get_connectors();\n\n\tif (name[0] == '@') {\n\t\tchar* endptr;\n\t\tunsigned id = strtoul(name.c_str() + 1, &endptr, 10);\n\t\tif (*endptr == 0) {\n\t\t\tConnector* c = card.get_connector(id);\n\n\t\t\tif (!c || contains(reserved, c))\n\t\t\t\treturn nullptr;\n\n\t\t\treturn c;\n\t\t}\n\t} else {\n\t\tchar* endptr;\n\t\tunsigned idx = strtoul(name.c_str(), &endptr, 10);\n\t\tif (*endptr == 0) {\n\t\t\tif (idx >= connectors.size())\n\t\t\t\treturn nullptr;\n\n\t\t\tConnector* c = connectors[idx];\n\n\t\t\tif (contains(reserved, c))\n\t\t\t\treturn nullptr;\n\n\t\t\treturn c;\n\t\t}\n\t}\n\n\tfor (Connector* conn : connectors) {\n\t\tif (to_lower(conn->fullname()).find(to_lower(name)) == string::npos)\n\t\t\tcontinue;\n\n\t\tif (contains(reserved, conn))\n\t\t\tcontinue;\n\n\t\treturn conn;\n\t}\n\n\treturn nullptr;\n}\n\nConnector* ResourceManager::reserve_connector(const string& name)\n{\n\tConnector* conn;\n\n\tif (name.empty())\n\t\tconn = find_connector(m_card, m_reserved_connectors);\n\telse\n\t\tconn = resolve_connector(m_card, name, m_reserved_connectors);\n\n\tif (!conn)\n\t\treturn nullptr;\n\n\tm_reserved_connectors.push_back(conn);\n\treturn conn;\n}\n\nConnector* ResourceManager::reserve_connector(Connector* conn)\n{\n\tif (!conn)\n\t\treturn nullptr;\n\n\tif (contains(m_reserved_connectors, conn))\n\t\treturn nullptr;\n\n\tm_reserved_connectors.push_back(conn);\n\treturn conn;\n}\n\nCrtc* ResourceManager::reserve_crtc(Connector* conn)\n{\n\tif (!conn)\n\t\treturn nullptr;\n\n\tif (Crtc* crtc = conn->get_current_crtc()) {\n\t\tm_reserved_crtcs.push_back(crtc);\n\t\treturn crtc;\n\t}\n\n\tfor (Crtc* crtc : conn->get_possible_crtcs()) {\n\t\tif (contains(m_reserved_crtcs, crtc))\n\t\t\tcontinue;\n\n\t\tm_reserved_crtcs.push_back(crtc);\n\t\treturn crtc;\n\t}\n\n\treturn nullptr;\n}\n\nPlane* ResourceManager::reserve_plane(Crtc* crtc, PlaneType type, PixelFormat format)\n{\n\tif (!crtc)\n\t\treturn nullptr;\n\n\tfor (Plane* plane : crtc->get_possible_planes()) {\n\t\tif (plane->plane_type() != type)\n\t\t\tcontinue;\n\n\t\tif (format != PixelFormat::Undefined && !plane->supports_format(format))\n\t\t\tcontinue;\n\n\t\tif (contains(m_reserved_planes, plane))\n\t\t\tcontinue;\n\n\t\tm_reserved_planes.push_back(plane);\n\t\treturn plane;\n\t}\n\n\treturn nullptr;\n}\n\nPlane* ResourceManager::reserve_generic_plane(Crtc* crtc, PixelFormat format)\n{\n\tif (!crtc)\n\t\treturn nullptr;\n\n\tfor (Plane* plane : crtc->get_possible_planes()) {\n\t\tif (plane->plane_type() == PlaneType::Cursor)\n\t\t\tcontinue;\n\n\t\tif (format != PixelFormat::Undefined && !plane->supports_format(format))\n\t\t\tcontinue;\n\n\t\tif (contains(m_reserved_planes, plane))\n\t\t\tcontinue;\n\n\t\tm_reserved_planes.push_back(plane);\n\t\treturn plane;\n\t}\n\n\treturn nullptr;\n}\n\nPlane* ResourceManager::reserve_primary_plane(Crtc* crtc, PixelFormat format)\n{\n\treturn reserve_plane(crtc, PlaneType::Primary, format);\n}\n\nPlane* ResourceManager::reserve_overlay_plane(Crtc* crtc, PixelFormat format)\n{\n\treturn reserve_plane(crtc, PlaneType::Overlay, format);\n}\n<|endoftext|>"} {"text":"<commit_before>\/* lexer.cpp\n * this file provides lexical analysis for Tetra it implements the yylex\n * function used by the parser. Tetra does not use flex principally because\n * doing whitespace-based blocking is difficult due to the limitations of flex\n * (not being able to capture and respond to EOF) *\/\n\n#include <cstdlib>\n#include <cstring>\n#include <iostream>\n#include <string>\n\n#include \"frontend.h\"\n#include \"parser.genh\"\n\nusing namespace std;\n\n\/* whether or not we have seen whitespace so far this line *\/\nint start_of_line = 1;\n\n\/* the number of spaces used for one indentation level *\/\nint spaces_per_indent = 0;\n\n\/* the current number of indent levels *\/\nint indent_level = 0;\n\n\/* the number of DEDENTs to return before anything else *\/\nint dedents_left = 0;\n\n\/* line number we are at - used for error messages *\/\nint yylineno = 1;\n\n\/* reset the lexer state *\/\nvoid reset_lexer() {\n start_of_line = 1;\n spaces_per_indent = 0;\n indent_level = 0;\n dedents_left = 0;\n yylineno = 1;\n}\n\n\/* the symbol used to comunicate with bison *\/\nextern YYSTYPE yylval;\n\n\/* the istream to use for doing all input *\/\nistream* in;\n\n\/* look up a string and return its token code *\/\nint lookupId(const string& id) {\n yylval.lineno = yylineno;\n if (id == \"if\") {\n return TOK_IF;\n }\n if (id == \"elif\") {\n return TOK_ELIF;\n }\n if (id == \"else\") {\n return TOK_ELSE;\n }\n if (id == \"for\") {\n return TOK_FOR;\n }\n if (id == \"in\") {\n return TOK_IN;\n }\n if (id == \"parallel\") {\n return TOK_PARALLEL;\n }\n if (id == \"while\") {\n return TOK_WHILE;\n }\n if (id == \"continue\") {\n return TOK_CONTINUE;\n }\n if (id == \"break\") {\n return TOK_BREAK;\n }\n if (id == \"def\") {\n return TOK_DEF;\n }\n if (id == \"or\") {\n return TOK_OR;\n }\n if (id == \"and\") {\n return TOK_AND;\n }\n if (id == \"not\") {\n return TOK_NOT;\n }\n if (id == \"pass\") {\n return TOK_PASS;\n }\n if (id == \"return\") {\n return TOK_RETURN;\n }\n if (id == \"background\") {\n return TOK_BACKGROUND;\n }\n if (id == \"lock\") {\n return TOK_LOCK;\n }\n if (id == \"int\") {\n return TOK_INT;\n }\n if (id == \"real\") {\n return TOK_REAL;\n }\n if (id == \"bool\") {\n return TOK_BOOL;\n }\n if (id == \"constant\") {\n return TOK_CONST;\n }\n if (id == \"global\") {\n return TOK_GLOBAL;\n }\n if (id == \"string\") {\n return TOK_STRING;\n }\n if (id == \"init\") {\n return TOK_INIT;\n }\n if (id == \"none\") {\n return TOK_NONE;\n }\n if (id == \"lambda\") {\n return TOK_LAMBDA;\n }\n if (id == \"wait\") {\n return TOK_WAIT;\n }\n if (id == \"self\") {\n return TOK_SELF;\n }\n if (id == \"class\") {\n return TOK_CLASS;\n }\n if (id == \"open\") {\n return TOK_OPEN;\n }\n if (id == \"import\") {\n return TOK_IMPORT;\n }\n if (id == \"mutex\") {\n return TOK_MUTEX;\n }\n if (id == \"task\") {\n return TOK_TASK;\n }\n if (id == \"declare\") {\n return TOK_DECLARE;\n }\n if (id == \"true\") {\n yylval.boolval = true;\n return TOK_BOOLVAL;\n } else if (id == \"false\") {\n yylval.boolval = false;\n return TOK_BOOLVAL;\n }\n\n \/* save the identifier *\/\n strcpy(yylval.stringval, id.c_str());\n return TOK_IDENTIFIER;\n}\n\n\/* lex an identifier (or reserved word) given a start *\/\nint lexIdent(int start) {\n string id;\n id.push_back((char)start);\n\n while (isalnum(in->peek()) || in->peek() == '_') {\n id.push_back(in->get());\n }\n\n return lookupId(id);\n}\n\n\/* lex a number\n * TODO handle more bases, scientific notation etc. *\/\nint lexNumber(int start) {\n string number;\n number.push_back((char)start);\n\n \/* have we seen a decimal point yet? *\/\n bool seendot = (start == '.');\n\n \/* scan forward *\/\n while (true) {\n char next = in->peek();\n\n if (isdigit(next)) {\n number.push_back(next);\n in->get();\n continue;\n }\n\n if (next == '.' && seendot) {\n break;\n }\n\n if (next == '.') {\n \/* hesitantly read the . *\/\n next = in->get();\n\n \/* check if next is dot too *\/\n if (in->peek() == '.') {\n \/* put the . back and bail *\/\n in->putback(next);\n break;\n } else {\n number.push_back(next);\n seendot = true;\n continue;\n }\n }\n\n \/* it is not a number or dot, just break! *\/\n break;\n }\n\n \/* if there's no decimal its an int *\/\n if (number.find('.') == string::npos) {\n yylval.intval = atoi(number.c_str());\n return TOK_INTVAL;\n } else {\n yylval.realval = atof(number.c_str());\n return TOK_REALVAL;\n }\n}\n\n\/* lex a string constant *\/\nint lexString() {\n string str;\n while (true) {\n char next = in->get();\n if (next == '\\\\') {\n \/* get the thing after this *\/\n next = in->get();\n switch (next) {\n case 'n':\n str.push_back('\\n');\n break;\n case 't':\n str.push_back('\\t');\n break;\n case '\"':\n str.push_back('\"');\n case '\\\\':\n str.push_back('\\\\');\n break;\n default:\n str.push_back(next);\n }\n } else if (next == '\"') {\n break;\n } else {\n str.push_back(next);\n }\n }\n\n \/* save the string *\/\n strcpy(yylval.stringval, str.c_str());\n return TOK_STRINGVAL;\n}\n\n\/* the lexer function - Tetra would have used flex, but it is not possible\n * (without\n * horrible hacks) to detect EOF and add DEDENT tokens - which makes it tough to\n * do\n * whitespace based blocking a la Python *\/\nint yylex() {\n \/* if there are dedents left to return, do it *\/\n if (dedents_left > 0) {\n dedents_left--;\n indent_level--;\n return TOK_DEDENT;\n }\n\n \/* read in the next character in the stream *\/\n int next = in->get();\n\n \/* check for EOF *\/\n if (in->eof()) {\n if (indent_level != 0) {\n dedents_left = indent_level;\n return yylex();\n } else {\n return 0;\n }\n }\n\n \/* we do NOT allow tabs *\/\n if (next == '\\t') {\n throw Error(\"Tab characters are not allowed in Tetra!\", yylineno);\n }\n\n \/* if it's a new line, set to beginning of line and return next *\/\n if (next == '\\n') {\n start_of_line = 1;\n yylineno++;\n return TOK_NEWLINE;\n }\n\n \/* if it's whitespace, NOT at the start of a line, ignore it *\/\n if (!start_of_line && next == ' ') {\n \/* recurse to skip it *\/\n return yylex();\n }\n\n \/* if it's whitespace and IS at the start of the line *\/\n if (start_of_line && next == ' ') {\n \/* count the spaces *\/\n int spaces = 1;\n while (in->peek() == ' ') {\n in->get();\n spaces++;\n }\n start_of_line = 0;\n\n \/* if this is the first one, treat it as the level *\/\n if (spaces_per_indent == 0) {\n spaces_per_indent = spaces;\n }\n\n \/* level is spaces \/ spaces_per_indent *\/\n int level = spaces \/ spaces_per_indent;\n if ((spaces % spaces_per_indent) != 0) {\n throw Error(\"Indentation level inconsistent.\", yylineno);\n }\n\n \/* if the level is greater than the current one (by one) indent *\/\n if (level == (indent_level + 1)) {\n indent_level++;\n return TOK_INDENT;\n }\n\n \/* If the level is EVEN greater than that, error *\/\n if (level > indent_level) {\n cerr << \"Level = \" << level << endl;\n cerr << \"Indent level = \" << indent_level << endl;\n throw Error(\"Too much indentation.\", yylineno);\n }\n\n \/* if the level is less than the current one *\/\n if (level < indent_level) {\n \/* set dedents_left to the difference *\/\n dedents_left = indent_level - level;\n\n \/* recurse *\/\n return yylex();\n }\n\n \/* if it's the same, just move on *\/\n if (level == indent_level) {\n return yylex();\n }\n\n \/* else it's the start of line, but NOT whitespace *\/\n } else if (start_of_line) {\n start_of_line = 0;\n \/* if there is indentation, set the dedents to return to that - 1, and\n * return 1 *\/\n if (indent_level > 0) {\n \/* put the thing we read back! *\/\n in->putback(next);\n dedents_left = indent_level - 1;\n indent_level--;\n return TOK_DEDENT;\n }\n }\n\n \/* it's not start of line any more *\/\n start_of_line = 0;\n\n \/* if it's a letter or underscore, we have an identifier (or reserved word) *\/\n if (isalpha(next)) {\n return lexIdent(next);\n }\n\n \/* if it's three decimal points, it's an elipsis *\/\n if (next == '.' && in->peek() == '.') {\n in->get();\n\n if (in->get() != '.') {\n throw Error(\"Lexical error: '..' not correct\", yylineno);\n }\n\n return TOK_ELLIPSIS;\n }\n\n \/* if it's a number or decimal point, we have a number of some kind *\/\n if (isdigit(next) || (next == '.' && isdigit(in->peek()))) {\n return lexNumber(next);\n }\n\n \/* check for the dot operator *\/\n if (next == '.') {\n return TOK_DOT; \n }\n\n \/* handle comments *\/\n if (next == '#') {\n \/* eat it all *\/\n while (in->peek() != '\\n') {\n in->get();\n }\n \/* get the new line *\/\n in->get();\n start_of_line = 1;\n yylineno++;\n\n \/* skip it *\/\n return yylex();\n }\n\n \/* handle string constants *\/\n if (next == '\"') {\n return lexString();\n }\n\n \/* character operators and punctuation *\/\n yylval.lineno = yylineno;\n switch (next) {\n \/* single character ones *\/\n case '~':\n return TOK_BITNOT;\n case '(':\n return TOK_LEFTPARENS;\n case ')':\n return TOK_RIGHTPARENS;\n case ',':\n return TOK_COMMA;\n case ';':\n return TOK_SEMICOLON;\n case ':':\n return TOK_COLON;\n case '[':\n return TOK_LEFTBRACKET;\n case ']':\n return TOK_RIGHTBRACKET;\n case '{':\n return TOK_LEFTBRACE;\n case '}':\n return TOK_RIGHTBRACE;\n\n \/* ones that have some single and double ones *\/\n case '=':\n if (in->peek() == '=') {\n in->get();\n return TOK_EQ;\n } else {\n return TOK_ASSIGN;\n }\n case '+':\n if (in->peek() == '=') {\n in->get();\n return TOK_PLUSEQ;\n } else {\n return TOK_PLUS;\n }\n case '-':\n if (in->peek() == '=') {\n in->get();\n return TOK_MINUSEQ;\n } else if (in->peek() == '>') {\n in->get();\n return TOK_RIGHTARROW;\n } else {\n return TOK_MINUS;\n }\n case '*':\n if (in->peek() == '=') {\n in->get();\n return TOK_TIMESEQ;\n } else if (in->peek() == '*') {\n in->get();\n if (in->peek() == '=') {\n in->get();\n return TOK_EXPEQ;\n } else {\n return TOK_EXP;\n }\n } else {\n return TOK_TIMES;\n }\n case '\/':\n if (in->peek() == '=') {\n in->get();\n return TOK_DIVIDEEQ;\n } else {\n return TOK_DIVIDE;\n }\n case '%':\n if (in->peek() == '=') {\n in->get();\n return TOK_MODULUSEQ;\n } else {\n return TOK_MODULUS;\n }\n case '^':\n if (in->peek() == '=') {\n in->get();\n return TOK_XOREQ;\n } else {\n return TOK_BITXOR;\n }\n case '|':\n if (in->peek() == '=') {\n in->get();\n return TOK_OREQ;\n } else {\n return TOK_BITOR;\n }\n case '&':\n if (in->peek() == '=') {\n in->get();\n return TOK_ANDEQ;\n } else {\n return TOK_BITAND;\n }\n case '!':\n if (in->peek() != '=') {\n throw Error(\"Error, invalid lexeme '!'\", yylineno);\n } else {\n in->get();\n return TOK_NEQ;\n }\n case '<':\n if (in->peek() == '=') {\n in->get();\n return TOK_LTE;\n } else if (in->peek() == '<') {\n in->get();\n if (in->peek() == '=') {\n in->get();\n return TOK_LSHIFTEQ;\n } else {\n return TOK_LSHIFT;\n }\n } else {\n return TOK_LT;\n }\n case '>':\n if (in->peek() == '=') {\n in->get();\n return TOK_GTE;\n } else if (in->peek() == '>') {\n in->get();\n if (in->peek() == '=') {\n in->get();\n return TOK_RSHIFTEQ;\n } else {\n return TOK_RSHIFT;\n }\n } else {\n return TOK_GT;\n }\n }\n\n \/* if we get down here, there must be a lexer error :( *\/\n throw Error(string(next, 1) + \" is not a valid lexeme.\", yylineno);\n return 0;\n}\n\n\n\n\n<commit_msg>Add abiiltiy to escape a newline.<commit_after>\/* lexer.cpp\n * this file provides lexical analysis for Tetra it implements the yylex\n * function used by the parser. Tetra does not use flex principally because\n * doing whitespace-based blocking is difficult due to the limitations of flex\n * (not being able to capture and respond to EOF) *\/\n\n#include <cstdlib>\n#include <cstring>\n#include <iostream>\n#include <string>\n\n#include \"frontend.h\"\n#include \"parser.genh\"\n\nusing namespace std;\n\n\/* whether or not we have seen whitespace so far this line *\/\nint start_of_line = 1;\n\n\/* the number of spaces used for one indentation level *\/\nint spaces_per_indent = 0;\n\n\/* the current number of indent levels *\/\nint indent_level = 0;\n\n\/* the number of DEDENTs to return before anything else *\/\nint dedents_left = 0;\n\n\/* line number we are at - used for error messages *\/\nint yylineno = 1;\n\n\/* reset the lexer state *\/\nvoid reset_lexer() {\n start_of_line = 1;\n spaces_per_indent = 0;\n indent_level = 0;\n dedents_left = 0;\n yylineno = 1;\n}\n\n\/* the symbol used to comunicate with bison *\/\nextern YYSTYPE yylval;\n\n\/* the istream to use for doing all input *\/\nistream* in;\n\n\/* look up a string and return its token code *\/\nint lookupId(const string& id) {\n yylval.lineno = yylineno;\n if (id == \"if\") {\n return TOK_IF;\n }\n if (id == \"elif\") {\n return TOK_ELIF;\n }\n if (id == \"else\") {\n return TOK_ELSE;\n }\n if (id == \"for\") {\n return TOK_FOR;\n }\n if (id == \"in\") {\n return TOK_IN;\n }\n if (id == \"parallel\") {\n return TOK_PARALLEL;\n }\n if (id == \"while\") {\n return TOK_WHILE;\n }\n if (id == \"continue\") {\n return TOK_CONTINUE;\n }\n if (id == \"break\") {\n return TOK_BREAK;\n }\n if (id == \"def\") {\n return TOK_DEF;\n }\n if (id == \"or\") {\n return TOK_OR;\n }\n if (id == \"and\") {\n return TOK_AND;\n }\n if (id == \"not\") {\n return TOK_NOT;\n }\n if (id == \"pass\") {\n return TOK_PASS;\n }\n if (id == \"return\") {\n return TOK_RETURN;\n }\n if (id == \"background\") {\n return TOK_BACKGROUND;\n }\n if (id == \"lock\") {\n return TOK_LOCK;\n }\n if (id == \"int\") {\n return TOK_INT;\n }\n if (id == \"real\") {\n return TOK_REAL;\n }\n if (id == \"bool\") {\n return TOK_BOOL;\n }\n if (id == \"constant\") {\n return TOK_CONST;\n }\n if (id == \"global\") {\n return TOK_GLOBAL;\n }\n if (id == \"string\") {\n return TOK_STRING;\n }\n if (id == \"init\") {\n return TOK_INIT;\n }\n if (id == \"none\") {\n return TOK_NONE;\n }\n if (id == \"lambda\") {\n return TOK_LAMBDA;\n }\n if (id == \"wait\") {\n return TOK_WAIT;\n }\n if (id == \"self\") {\n return TOK_SELF;\n }\n if (id == \"class\") {\n return TOK_CLASS;\n }\n if (id == \"open\") {\n return TOK_OPEN;\n }\n if (id == \"import\") {\n return TOK_IMPORT;\n }\n if (id == \"mutex\") {\n return TOK_MUTEX;\n }\n if (id == \"task\") {\n return TOK_TASK;\n }\n if (id == \"declare\") {\n return TOK_DECLARE;\n }\n if (id == \"true\") {\n yylval.boolval = true;\n return TOK_BOOLVAL;\n } else if (id == \"false\") {\n yylval.boolval = false;\n return TOK_BOOLVAL;\n }\n\n \/* save the identifier *\/\n strcpy(yylval.stringval, id.c_str());\n return TOK_IDENTIFIER;\n}\n\n\/* lex an identifier (or reserved word) given a start *\/\nint lexIdent(int start) {\n string id;\n id.push_back((char)start);\n\n while (isalnum(in->peek()) || in->peek() == '_') {\n id.push_back(in->get());\n }\n\n return lookupId(id);\n}\n\n\/* lex a number\n * TODO handle more bases, scientific notation etc. *\/\nint lexNumber(int start) {\n string number;\n number.push_back((char)start);\n\n \/* have we seen a decimal point yet? *\/\n bool seendot = (start == '.');\n\n \/* scan forward *\/\n while (true) {\n char next = in->peek();\n\n if (isdigit(next)) {\n number.push_back(next);\n in->get();\n continue;\n }\n\n if (next == '.' && seendot) {\n break;\n }\n\n if (next == '.') {\n \/* hesitantly read the . *\/\n next = in->get();\n\n \/* check if next is dot too *\/\n if (in->peek() == '.') {\n \/* put the . back and bail *\/\n in->putback(next);\n break;\n } else {\n number.push_back(next);\n seendot = true;\n continue;\n }\n }\n\n \/* it is not a number or dot, just break! *\/\n break;\n }\n\n \/* if there's no decimal its an int *\/\n if (number.find('.') == string::npos) {\n yylval.intval = atoi(number.c_str());\n return TOK_INTVAL;\n } else {\n yylval.realval = atof(number.c_str());\n return TOK_REALVAL;\n }\n}\n\n\/* lex a string constant *\/\nint lexString() {\n string str;\n while (true) {\n char next = in->get();\n if (next == '\\\\') {\n \/* get the thing after this *\/\n next = in->get();\n switch (next) {\n case 'n':\n str.push_back('\\n');\n break;\n case 't':\n str.push_back('\\t');\n break;\n case '\"':\n str.push_back('\"');\n case '\\\\':\n str.push_back('\\\\');\n break;\n default:\n str.push_back(next);\n }\n } else if (next == '\"') {\n break;\n } else {\n str.push_back(next);\n }\n }\n\n \/* save the string *\/\n strcpy(yylval.stringval, str.c_str());\n return TOK_STRINGVAL;\n}\n\n\/* the lexer function - Tetra would have used flex, but it is not possible\n * (without\n * horrible hacks) to detect EOF and add DEDENT tokens - which makes it tough to\n * do\n * whitespace based blocking a la Python *\/\nint yylex() {\n \/* if there are dedents left to return, do it *\/\n if (dedents_left > 0) {\n dedents_left--;\n indent_level--;\n return TOK_DEDENT;\n }\n\n \/* read in the next character in the stream *\/\n int next = in->get();\n\n \/* check for EOF *\/\n if (in->eof()) {\n if (indent_level != 0) {\n dedents_left = indent_level;\n return yylex();\n } else {\n return 0;\n }\n }\n\n \/* we do NOT allow tabs *\/\n if (next == '\\t') {\n throw Error(\"Tab characters are not allowed in Tetra!\", yylineno);\n }\n\n \/* if it's a new line, set to beginning of line and return next *\/\n if (next == '\\n') {\n start_of_line = 1;\n yylineno++;\n return TOK_NEWLINE;\n }\n\n \/* if it's whitespace, NOT at the start of a line, ignore it *\/\n if (!start_of_line && next == ' ') {\n \/* recurse to skip it *\/\n return yylex();\n }\n\n \/* if it's whitespace and IS at the start of the line *\/\n if (start_of_line && next == ' ') {\n \/* count the spaces *\/\n int spaces = 1;\n while (in->peek() == ' ') {\n in->get();\n spaces++;\n }\n start_of_line = 0;\n\n \/* if this is the first one, treat it as the level *\/\n if (spaces_per_indent == 0) {\n spaces_per_indent = spaces;\n }\n\n \/* level is spaces \/ spaces_per_indent *\/\n int level = spaces \/ spaces_per_indent;\n if ((spaces % spaces_per_indent) != 0) {\n throw Error(\"Indentation level inconsistent.\", yylineno);\n }\n\n \/* if the level is greater than the current one (by one) indent *\/\n if (level == (indent_level + 1)) {\n indent_level++;\n return TOK_INDENT;\n }\n\n \/* If the level is EVEN greater than that, error *\/\n if (level > indent_level) {\n cerr << \"Level = \" << level << endl;\n cerr << \"Indent level = \" << indent_level << endl;\n throw Error(\"Too much indentation.\", yylineno);\n }\n\n \/* if the level is less than the current one *\/\n if (level < indent_level) {\n \/* set dedents_left to the difference *\/\n dedents_left = indent_level - level;\n\n \/* recurse *\/\n return yylex();\n }\n\n \/* if it's the same, just move on *\/\n if (level == indent_level) {\n return yylex();\n }\n\n \/* else it's the start of line, but NOT whitespace *\/\n } else if (start_of_line) {\n start_of_line = 0;\n \/* if there is indentation, set the dedents to return to that - 1, and\n * return 1 *\/\n if (indent_level > 0) {\n \/* put the thing we read back! *\/\n in->putback(next);\n dedents_left = indent_level - 1;\n indent_level--;\n return TOK_DEDENT;\n }\n }\n\n \/* it's not start of line any more *\/\n start_of_line = 0;\n\n \/* if it's a letter or underscore, we have an identifier (or reserved word) *\/\n if (isalpha(next)) {\n return lexIdent(next);\n }\n\n \/* if it's three decimal points, it's an elipsis *\/\n if (next == '.' && in->peek() == '.') {\n in->get();\n\n if (in->get() != '.') {\n throw Error(\"Lexical error: '..' not correct\", yylineno);\n }\n\n return TOK_ELLIPSIS;\n }\n\n \/* if it's a number or decimal point, we have a number of some kind *\/\n if (isdigit(next) || (next == '.' && isdigit(in->peek()))) {\n return lexNumber(next);\n }\n\n \/* check for the dot operator *\/\n if (next == '.') {\n return TOK_DOT; \n }\n\n \/* handle comments *\/\n if (next == '#') {\n \/* eat it all *\/\n while (in->peek() != '\\n') {\n in->get();\n }\n \/* get the new line *\/\n in->get();\n start_of_line = 1;\n yylineno++;\n\n \/* skip it *\/\n return yylex();\n }\n\n \/* handle string constants *\/\n if (next == '\"') {\n return lexString();\n }\n\n \/* character operators and punctuation *\/\n yylval.lineno = yylineno;\n switch (next) {\n \/* single character ones *\/\n case '~':\n return TOK_BITNOT;\n case '(':\n return TOK_LEFTPARENS;\n case ')':\n return TOK_RIGHTPARENS;\n case ',':\n return TOK_COMMA;\n case ';':\n return TOK_SEMICOLON;\n case ':':\n return TOK_COLON;\n case '[':\n return TOK_LEFTBRACKET;\n case ']':\n return TOK_RIGHTBRACKET;\n case '{':\n return TOK_LEFTBRACE;\n case '}':\n return TOK_RIGHTBRACE;\n\n \/* ones that have some single and double ones *\/\n case '=':\n if (in->peek() == '=') {\n in->get();\n return TOK_EQ;\n } else {\n return TOK_ASSIGN;\n }\n case '+':\n if (in->peek() == '=') {\n in->get();\n return TOK_PLUSEQ;\n } else {\n return TOK_PLUS;\n }\n case '-':\n if (in->peek() == '=') {\n in->get();\n return TOK_MINUSEQ;\n } else if (in->peek() == '>') {\n in->get();\n return TOK_RIGHTARROW;\n } else {\n return TOK_MINUS;\n }\n case '*':\n if (in->peek() == '=') {\n in->get();\n return TOK_TIMESEQ;\n } else if (in->peek() == '*') {\n in->get();\n if (in->peek() == '=') {\n in->get();\n return TOK_EXPEQ;\n } else {\n return TOK_EXP;\n }\n } else {\n return TOK_TIMES;\n }\n case '\/':\n if (in->peek() == '=') {\n in->get();\n return TOK_DIVIDEEQ;\n } else {\n return TOK_DIVIDE;\n }\n case '%':\n if (in->peek() == '=') {\n in->get();\n return TOK_MODULUSEQ;\n } else {\n return TOK_MODULUS;\n }\n case '^':\n if (in->peek() == '=') {\n in->get();\n return TOK_XOREQ;\n } else {\n return TOK_BITXOR;\n }\n case '|':\n if (in->peek() == '=') {\n in->get();\n return TOK_OREQ;\n } else {\n return TOK_BITOR;\n }\n case '&':\n if (in->peek() == '=') {\n in->get();\n return TOK_ANDEQ;\n } else {\n return TOK_BITAND;\n }\n case '!':\n if (in->peek() != '=') {\n throw Error(\"Error, invalid lexeme '!'\", yylineno);\n } else {\n in->get();\n return TOK_NEQ;\n }\n case '<':\n if (in->peek() == '=') {\n in->get();\n return TOK_LTE;\n } else if (in->peek() == '<') {\n in->get();\n if (in->peek() == '=') {\n in->get();\n return TOK_LSHIFTEQ;\n } else {\n return TOK_LSHIFT;\n }\n } else {\n return TOK_LT;\n }\n case '>':\n if (in->peek() == '=') {\n in->get();\n return TOK_GTE;\n } else if (in->peek() == '>') {\n in->get();\n if (in->peek() == '=') {\n in->get();\n return TOK_RSHIFTEQ;\n } else {\n return TOK_RSHIFT;\n }\n } else {\n return TOK_GT;\n }\n case '\\\\':\n if (in->peek() == '\\n'){\n in->get();\n while(in->peek() == ' '){\n in->get();\n }\n \n \/* recurse to skip it *\/\n return yylex();\n }\n }\n\n \/* if we get down here, there must be a lexer error :( *\/\n throw Error(string(next, 1) + \" is not a valid lexeme.\", yylineno);\n return 0;\n}\n\n\n\n\n<|endoftext|>"} {"text":"<commit_before>\n\/*!\n\t\\file\n\n\t\\author Igor Mironchik (igor.mironchik at gmail dot com).\n\n\tCopyright (c) 2017 Igor Mironchik\n\n\tPermission is hereby granted, free of charge, to any person\n\tobtaining a copy of this software and associated documentation\n\tfiles (the \"Software\"), to deal in the Software without\n\trestriction, including without limitation the rights to use,\n\tcopy, modify, merge, publish, distribute, sublicense, and\/or sell\n\tcopies of the Software, and to permit persons to whom the\n\tSoftware is furnished to do so, subject to the following\n\tconditions:\n\n\tThe above copyright notice and this permission notice shall be\n\tincluded in all copies or substantial portions of the Software.\n\n\tTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n\tEXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES\n\tOF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n\tNONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n\tHOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,\n\tWHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n\tFROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\n\tOTHER DEALINGS IN THE SOFTWARE.\n*\/\n\n\/\/ UnitTest include.\n#include <UnitTest\/unit_test.hpp>\n\n\/\/ cfgfile include.\n#include <cfgfile\/all.hpp>\n\n\nTEST( QtParser, test_undefined_first_mandatory_tag )\n{\n\tQDomDocument doc;\n\n\tcfgfile::tag_no_value_t< cfgfile::qstring_trait_t > tag( \"cfg\", true );\n\n\tcfgfile::parser_t< cfgfile::qstring_trait_t > parser( tag, doc );\n\n\ttry {\n\t\tparser.parse( \"test_undefined_first_mandatory_tag\" );\n\n\t\tCHECK_CONDITION( false )\n\t}\n\tcatch( const cfgfile::exception_t< cfgfile::qstring_trait_t > & x )\n\t{\n\t\tCHECK_CONDITION( x.desc() == \"Unexpected end of file. \"\n\t\t\t\"Undefined mandatory tag \\\"cfg\\\". In file \"\n\t\t\t\"\\\"test_undefined_first_mandatory_tag\\\" on line -1.\" )\n\t}\n}\n\nTEST( QtParser, test_unexpected_tag )\n{\n\tQDomDocument doc;\n\tQString error;\n\tint line = 0;\n\tint column = 0;\n\n\tdoc.setContent( QLatin1String( \"<wrong><\/wrong>\" ),\n\t\ttrue, &error, &line, &column );\n\n\tcfgfile::tag_no_value_t< cfgfile::qstring_trait_t > tag( \"cfg\", true );\n\n\tcfgfile::parser_t< cfgfile::qstring_trait_t > parser( tag, doc );\n\n\ttry {\n\t\tparser.parse( \"test_unexpected_tag\" );\n\n\t\tCHECK_CONDITION( false )\n\t}\n\tcatch( const cfgfile::exception_t< cfgfile::qstring_trait_t > & x )\n\t{\n\t\tCHECK_CONDITION( x.desc() == \"Unexpected tag name. \"\n\t\t\t\"We expected \\\"cfg\\\", but we've got \\\"wrong\\\". In file \"\n\t\t\t\"\\\"test_unexpected_tag\\\" on line 1.\" )\n\t}\n}\n\nTEST( QtParser, test_unexpected_child_tag )\n{\n\tQDomDocument doc;\n\tQString error;\n\tint line = 0;\n\tint column = 0;\n\n\tdoc.setContent( QLatin1String( \"<cfg><wrong><\/wrong><\/cfg>\" ),\n\t\ttrue, &error, &line, &column );\n\n\tcfgfile::tag_no_value_t< cfgfile::qstring_trait_t > tag( \"cfg\", true );\n\n\tcfgfile::parser_t< cfgfile::qstring_trait_t > parser( tag, doc );\n\n\ttry {\n\t\tparser.parse( \"test_unexpected_child_tag\" );\n\n\t\tCHECK_CONDITION( false )\n\t}\n\tcatch( const cfgfile::exception_t< cfgfile::qstring_trait_t > & x )\n\t{\n\t\tCHECK_CONDITION( x.desc() == \"Unexpected tag name. \"\n\t\t\t\"We expected one child tag of tag \\\"cfg\\\", but we've got \\\"wrong\\\". \"\n\t\t\t\"In file \\\"test_unexpected_child_tag\\\" on line 1.\" )\n\t}\n}\n\nTEST( QtParser, test_cant_set_xml )\n{\n\tQTextStream s( \"<a>abc\" );\n\n\tcfgfile::tag_no_value_t< cfgfile::qstring_trait_t > tag( \"cfg\", true );\n\n\ttry {\n\t\tcfgfile::read_cfgfile( tag, s, \"test_cant_set_xml\" );\n\n\t\tCHECK_CONDITION( false )\n\t}\n\tcatch( const cfgfile::exception_t< cfgfile::qstring_trait_t > & x )\n\t{\n\t\tCHECK_CONDITION( x.desc() == \"Unable to parse XML \"\n\t\t\t\"from file: \\\"test_cant_set_xml\\\". \\\"unexpected end of file\\\" \"\n\t\t\t\"On line 1, column 7.\" )\n\t}\n}\n\nint main()\n{\n\tRUN_ALL_TESTS()\n\n\treturn 0;\n}\n<commit_msg>Testing.<commit_after>\n\/*!\n\t\\file\n\n\t\\author Igor Mironchik (igor.mironchik at gmail dot com).\n\n\tCopyright (c) 2017 Igor Mironchik\n\n\tPermission is hereby granted, free of charge, to any person\n\tobtaining a copy of this software and associated documentation\n\tfiles (the \"Software\"), to deal in the Software without\n\trestriction, including without limitation the rights to use,\n\tcopy, modify, merge, publish, distribute, sublicense, and\/or sell\n\tcopies of the Software, and to permit persons to whom the\n\tSoftware is furnished to do so, subject to the following\n\tconditions:\n\n\tThe above copyright notice and this permission notice shall be\n\tincluded in all copies or substantial portions of the Software.\n\n\tTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n\tEXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES\n\tOF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n\tNONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n\tHOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,\n\tWHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n\tFROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\n\tOTHER DEALINGS IN THE SOFTWARE.\n*\/\n\n\/\/ UnitTest include.\n#include <UnitTest\/unit_test.hpp>\n\n\/\/ cfgfile include.\n#include <cfgfile\/all.hpp>\n\n\nTEST( QtParser, test_undefined_first_mandatory_tag )\n{\n\tQDomDocument doc;\n\n\tcfgfile::tag_no_value_t< cfgfile::qstring_trait_t > tag( \"cfg\", true );\n\n\tcfgfile::parser_t< cfgfile::qstring_trait_t > parser( tag, doc );\n\n\ttry {\n\t\tparser.parse( \"test_undefined_first_mandatory_tag\" );\n\n\t\tCHECK_CONDITION( false )\n\t}\n\tcatch( const cfgfile::exception_t< cfgfile::qstring_trait_t > & x )\n\t{\n\t\tCHECK_CONDITION( x.desc() == \"Unexpected end of file. \"\n\t\t\t\"Undefined mandatory tag \\\"cfg\\\". In file \"\n\t\t\t\"\\\"test_undefined_first_mandatory_tag\\\" on line -1.\" )\n\t}\n}\n\nTEST( QtParser, test_unexpected_tag )\n{\n\tQDomDocument doc;\n\tQString error;\n\tint line = 0;\n\tint column = 0;\n\n\tdoc.setContent( QLatin1String( \"<wrong><\/wrong>\" ),\n\t\ttrue, &error, &line, &column );\n\n\tcfgfile::tag_no_value_t< cfgfile::qstring_trait_t > tag( \"cfg\", true );\n\n\tcfgfile::parser_t< cfgfile::qstring_trait_t > parser( tag, doc );\n\n\ttry {\n\t\tparser.parse( \"test_unexpected_tag\" );\n\n\t\tCHECK_CONDITION( false )\n\t}\n\tcatch( const cfgfile::exception_t< cfgfile::qstring_trait_t > & x )\n\t{\n\t\tCHECK_CONDITION( x.desc() == \"Unexpected tag name. \"\n\t\t\t\"We expected \\\"cfg\\\", but we've got \\\"wrong\\\". In file \"\n\t\t\t\"\\\"test_unexpected_tag\\\" on line 1.\" )\n\t}\n}\n\nTEST( QtParser, test_unexpected_child_tag )\n{\n\tQDomDocument doc;\n\tQString error;\n\tint line = 0;\n\tint column = 0;\n\n\tdoc.setContent( QLatin1String( \"<cfg><wrong><\/wrong><\/cfg>\" ),\n\t\ttrue, &error, &line, &column );\n\n\tcfgfile::tag_no_value_t< cfgfile::qstring_trait_t > tag( \"cfg\", true );\n\n\tcfgfile::parser_t< cfgfile::qstring_trait_t > parser( tag, doc );\n\n\ttry {\n\t\tparser.parse( \"test_unexpected_child_tag\" );\n\n\t\tCHECK_CONDITION( false )\n\t}\n\tcatch( const cfgfile::exception_t< cfgfile::qstring_trait_t > & x )\n\t{\n\t\tCHECK_CONDITION( x.desc() == \"Unexpected tag name. \"\n\t\t\t\"We expected one child tag of tag \\\"cfg\\\", but we've got \\\"wrong\\\". \"\n\t\t\t\"In file \\\"test_unexpected_child_tag\\\" on line 1.\" )\n\t}\n}\n\nTEST( QtParser, test_cant_set_xml )\n{\n\tQTextStream s( \"<a>abc\" );\n\n\tcfgfile::tag_no_value_t< cfgfile::qstring_trait_t > tag( \"cfg\", true );\n\n\ttry {\n\t\tcfgfile::read_cfgfile( tag, s, \"test_cant_set_xml\" );\n\n\t\tCHECK_CONDITION( false )\n\t}\n\tcatch( const cfgfile::exception_t< cfgfile::qstring_trait_t > & x )\n\t{\n\t\tCHECK_CONDITION( x.desc() == \"Unable to parse XML \"\n\t\t\t\"from file: \\\"test_cant_set_xml\\\". \\\"unexpected end of file\\\" \"\n\t\t\t\"On line 1, column 7.\" )\n\t}\n}\n\nTEST( QtParser, test_unexpected_xml )\n{\n\tcfgfile::tag_no_value_t< cfgfile::qstring_trait_t > tag( \"cfg\", true );\n\n\tQDomDocument doc;\n\n\tQDomElement cfg = doc.createElement( \"cfg\" );\n\n\tdoc.appendChild( cfg );\n\n\tQDomComment c = doc.createComment( \"data\" );\n\n\tcfg.appendChild( c );\n\n\tcfgfile::parser_t< cfgfile::qstring_trait_t > parser( tag, doc );\n\n\ttry {\n\t\tparser.parse( \"test_unexpected_xml\" );\n\n\t\tCHECK_CONDITION( false )\n\t}\n\tcatch( const cfgfile::exception_t< cfgfile::qstring_trait_t > & x )\n\t{\n\t\tCHECK_CONDITION( x.desc() == \"Unexpected tag name. \"\n\t\t\t\"We expected one child tag of tag \\\"cfg\\\", but we've got \\\"#comment\\\". \"\n\t\t\t\"In file \\\"test_unexpected_xml\\\" on line -1.\" )\n\t}\n}\n\nint main()\n{\n\tRUN_ALL_TESTS()\n\n\treturn 0;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"CAppNodeImpl.h\"\n#include \"Utility\/Utils.h\"\n\nCAppNodeImpl::CAppNodeImpl( int argc, ACE_TCHAR *argv[], std::string appNameIn, int domainIDIn ):\n\tCAppNode( argc, argv, appNameIn )\n\t, m_applicationTerminate( false)\n\t, _domainID( domainIDIn )\n\t, _argCount( argc )\n{\n\tfor( size_t i = 0; i < _argCount; ++i)\n\t{\n\t\t_pargVect[i] = argv[i];\n\t}\n}\n\nCAppNodeImpl::~CAppNodeImpl()\n{\n\n}\n\nvoid CAppNodeImpl::Initialize()\n{\n\ttry\n\t{\n\t\t\/\/ Setup signal handler for ctrl-c\n\t\t_psignalHandler->SetupSignalHandlers();\n\n\t\t\/\/ Init all DDS related components\n\t\tInitParticipant();\n\n\t\tInitPublisherAndSubscriber();\n\n\t\tInitTopicinfo();\n\n\t\tInitDataWriter();\n\n\t\tInitDataReader();\n\n\t}catch( CORBA::SystemException &excpt )\n\t{\n\t\tLOG( ERROR ) << \"Failed: CORBA Exception.\";\n\n\t\tCleanUp();\n\t}\n\n}\n\nstd::string CAppNodeImpl::GetName()\n{\n\treturn _appName;\n}\n\nvoid CAppNodeImpl::Run()\n{\n\t\/\/ Example Messaage to write\n\tExampleApp::Event message;\n\n\t\/\/ For example writes\n\tint count = 0;\n\n\twhile( !_psignalHandler->GotExitSignal() )\n\t{\n\t\t\/\/ Write out example message to ourselves\n\t\tmessage.kicker = \"test\";\n\t\tmessage.timestamp = nodeutils::GetUnixTimestampMs();\n\n\t\t\/\/if( count % 5 != 0 )\n\t\t\/\/{\n\t\t\tDDS::ReturnCode_t ret = _eventWriter->write( message, DDS::HANDLE_NIL );\n\n\t\t\tif( ret != DDS::RETCODE_OK )\n\t\t\t{\n\t\t\t\tLOG( ERROR ) << \"Error write returned: \" << ret;\n\t\t\t}\n\t\t\/\/s}\n\n\t\tcount++;\n\n\t\t\/\/Wait for acknowledgement\n\/\/\t\tDDS::Duration_t timeout = { 30, 0 };\n\/\/\t\t_eventWriter->wait_for_acknowledgments( timeout );\n\n\t\t\/\/ Handle received messages\n\t\tHandleWaitCondition();\n\t}\n\n\tCleanUp();\n}\n\nvoid CAppNodeImpl::CleanUp()\n{\n\tLOG( INFO ) << \"Cleaning up application...\";\n\ttry\n\t{\n\t\t\/\/ Clean-up!\n\t\t_participant->delete_contained_entities();\n\n\t\t_domainParticipantFactory->delete_participant( _participant );\n\n\t\tTheServiceParticipant->shutdown();\n\n\t}catch( CORBA::SystemException &excpt )\n\t{\n\t\tLOG( ERROR ) << \"Failed: CORBA Exception participants and factory not properly deleted.\";\n\t}\n}\n\nvoid CAppNodeImpl::HandleWaitCondition()\n{\n\t\/\/ Block until Subscriber is available\n\tDDS::StatusCondition_var condition = _writer->get_statuscondition();\n\tcondition->set_enabled_statuses( DDS::PUBLICATION_MATCHED_STATUS );\n\n\tDDS::WaitSet_var waitSet = new DDS::WaitSet;\n\twaitSet->attach_condition( condition );\n\n\tDDS::ConditionSeq conditions;\n\tDDS::SubscriptionMatchedStatus matches = { 0, 0, 0, 0, 0 };\n\tDDS::Duration_t timeout = { 30, 0 };\n\n\t\/\/do {\n\t if ( waitSet->wait(conditions, timeout ) != DDS::RETCODE_OK )\n\t {\n\t\tLOG( ERROR ) << \"wait condition failed.\";\n\t }\n\n\t if ( _reader->get_subscription_matched_status( matches ) != DDS::RETCODE_OK )\n\t {\n\t\tLOG( ERROR ) << \"Publication matched status failed.\";\n\t }\n\n\t\/\/} while ( matches.current_count > 0 );\n\n\twaitSet->detach_condition( condition );\n}\n\nvoid CAppNodeImpl::InitParticipant()\n{\n\t\/\/ Init the participant factory and participant\n\t_domainParticipantFactory = TheParticipantFactoryWithArgs( _argCount, _pargVect );\n\n\t_participant = _domainParticipantFactory->create_participant( _domainID, PARTICIPANT_QOS_DEFAULT,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tDDS::DomainParticipantListener::_nil(),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tOpenDDS::DCPS::DEFAULT_STATUS_MASK );\n\n\t\/\/ Exit is nil\n\tif( !_participant )\n\t{\n\t\tLOG( ERROR ) << \"Create Participant Failed.\";\n\t}\n}\n\nvoid CAppNodeImpl::InitPublisherAndSubscriber()\n{\n\t\/\/ Publisher\n\t_publisher = _participant->create_publisher( PUBLISHER_QOS_DEFAULT,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tDDS::PublisherListener::_nil(),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tOpenDDS::DCPS::DEFAULT_STATUS_MASK );\n\n\t\/\/ Exit if nil\n\tif( !_publisher )\n\t{\n\t\tLOG( ERROR ) << \"Create publisher failed.\";\n\t}\n\n\t\/\/ Subscriber\n\t_subscriber = _participant->create_subscriber( SUBSCRIBER_QOS_DEFAULT,\n\t\t\t\t\t\t\t\t\t\t\t\t\tDDS::SubscriberListener::_nil(),\n\t\t\t\t\t\t\t\t\t\t\t\t\tOpenDDS::DCPS::DEFAULT_STATUS_MASK );\n\tif( !_subscriber )\n\t{\n\t\tLOG( ERROR ) << \"Create subscriber failed.\";\n\t}\n}\n\nvoid CAppNodeImpl::InitTopicinfo()\n{\n\t\/\/ Type registration\n\t_exampleTypeSupport = new ExampleApp::EventTypeSupportImpl();\n\n\t\/\/ Exit if retcode ! ok\n\tif( DDS::RETCODE_OK != _exampleTypeSupport->register_type( _participant, \"\" ) )\n\t{\n\t\tLOG( ERROR ) << \"register type failed.\";\n\t}\n\n\t\/\/ Create a topic\n\t_topicTypeName = _exampleTypeSupport->get_type_name();\n\n\t_topic = _participant->create_topic( \"Test Topic\", _topicTypeName.in(),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tTOPIC_QOS_DEFAULT,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tDDS::TopicListener::_nil(),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tOpenDDS::DCPS::DEFAULT_STATUS_MASK );\n\n\tif( !_topic )\n\t{\n\t\tLOG( ERROR ) << \"Create topic failed\";\n\t}\n}\n\nvoid CAppNodeImpl::InitDataWriter()\n{\n\t\/\/ Create the data writer\n\t_writer = _publisher->create_datawriter( _topic, DATAWRITER_QOS_DEFAULT,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tDDS::DataWriterListener::_nil(),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tOpenDDS::DCPS::DEFAULT_STATUS_MASK );\n\n\tif( !_writer )\n\t{\n\t\tLOG( ERROR ) << \"Create datawriter failed\";\n\t}\n\n\t_eventWriter = ExampleApp::EventDataWriter::_narrow( _writer );\n\n\tif( !_eventWriter )\n\t{\n\t\tLOG( ERROR ) << \"_narrow failed\";\n\t}\n\n}\n\nvoid CAppNodeImpl::InitDataReader()\n{\n\t\/\/ Data Reader\n\t_listener = new CDataReaderListenerImpl;\n\n\t_reader = _subscriber->create_datareader( _topic, DATAREADER_QOS_DEFAULT,\n\t\t\t\t\t\t\t\t\t\t\t\t_listener,\n\t\t\t\t\t\t\t\t\t\t\t\tOpenDDS::DCPS::DEFAULT_STATUS_MASK );\n\n\tif( !_reader )\n\t{\n\t\tLOG( ERROR ) << \" Create data reader failed\";\n\t}\n\n\t_readerI = ExampleApp::EventDataReader::_narrow( _reader );\n\n\tif( !_readerI )\n\t{\n\n\t\tLOG( ERROR ) << \" _narrow failed\";\n\t}\n}\n<commit_msg>example write throttling<commit_after>#include \"CAppNodeImpl.h\"\n#include \"Utility\/Utils.h\"\n\nCAppNodeImpl::CAppNodeImpl( int argc, ACE_TCHAR *argv[], std::string appNameIn, int domainIDIn ):\n\tCAppNode( argc, argv, appNameIn )\n\t, m_applicationTerminate( false)\n\t, _domainID( domainIDIn )\n\t, _argCount( argc )\n{\n\tfor( size_t i = 0; i < _argCount; ++i)\n\t{\n\t\t_pargVect[i] = argv[i];\n\t}\n}\n\nCAppNodeImpl::~CAppNodeImpl()\n{\n\n}\n\nvoid CAppNodeImpl::Initialize()\n{\n\ttry\n\t{\n\t\t\/\/ Setup signal handler for ctrl-c\n\t\t_psignalHandler->SetupSignalHandlers();\n\n\t\t\/\/ Init all DDS related components\n\t\tInitParticipant();\n\n\t\tInitPublisherAndSubscriber();\n\n\t\tInitTopicinfo();\n\n\t\tInitDataWriter();\n\n\t\tInitDataReader();\n\n\t}catch( CORBA::SystemException &excpt )\n\t{\n\t\tLOG( ERROR ) << \"Failed: CORBA Exception.\";\n\n\t\tCleanUp();\n\t}\n\n}\n\nstd::string CAppNodeImpl::GetName()\n{\n\treturn _appName;\n}\n\nvoid CAppNodeImpl::Run()\n{\n\t\/\/ Example Messaage to write\n\tExampleApp::Event message;\n\n\twhile( !_psignalHandler->GotExitSignal() )\n\t{\n\t\t\/\/ Write out example message to ourselves\n\t\tmessage.kicker = \"test\";\n\t\tmessage.timestamp = nodeutils::GetUnixTimestampMs();\n\n\t\t\tDDS::ReturnCode_t ret = _eventWriter->write( message, DDS::HANDLE_NIL );\n\n\t\t\tif( ret != DDS::RETCODE_OK )\n\t\t\t{\n\t\t\t\tLOG( ERROR ) << \"Error write returned: \" << ret;\n\t\t\t}\n\n\t\t\/\/ Handle received messages\n\t\tHandleWaitCondition();\n\n\t\t\/\/ Pause - example write throttling\n\t\tsleep( 3 );\n\t}\n\n\tCleanUp();\n}\n\nvoid CAppNodeImpl::CleanUp()\n{\n\tLOG( INFO ) << \"Cleaning up application...\";\n\ttry\n\t{\n\t\t\/\/ Clean-up!\n\t\t_participant->delete_contained_entities();\n\n\t\t_domainParticipantFactory->delete_participant( _participant );\n\n\t\tTheServiceParticipant->shutdown();\n\n\t}catch( CORBA::SystemException &excpt )\n\t{\n\t\tLOG( ERROR ) << \"Failed: CORBA Exception participants and factory not properly deleted.\";\n\t}\n}\n\nvoid CAppNodeImpl::HandleWaitCondition()\n{\n\t\/\/ Block until Subscriber is available\n\tDDS::StatusCondition_var condition = _writer->get_statuscondition();\n\tcondition->set_enabled_statuses( DDS::PUBLICATION_MATCHED_STATUS );\n\n\tDDS::WaitSet_var waitSet = new DDS::WaitSet;\n\twaitSet->attach_condition( condition );\n\n\tDDS::ConditionSeq conditions;\n\tDDS::SubscriptionMatchedStatus matches = { 0, 0, 0, 0, 0 };\n\tDDS::Duration_t timeout = { 30, 0 };\n\n\t\/\/do {\n\t if ( waitSet->wait(conditions, timeout ) != DDS::RETCODE_OK )\n\t {\n\t\tLOG( ERROR ) << \"wait condition failed.\";\n\t }\n\n\t if ( _reader->get_subscription_matched_status( matches ) != DDS::RETCODE_OK )\n\t {\n\t\tLOG( ERROR ) << \"Publication matched status failed.\";\n\t }\n\n\t\/\/} while ( matches.current_count > 0 );\n\n\twaitSet->detach_condition( condition );\n}\n\nvoid CAppNodeImpl::InitParticipant()\n{\n\t\/\/ Init the participant factory and participant\n\t_domainParticipantFactory = TheParticipantFactoryWithArgs( _argCount, _pargVect );\n\n\t_participant = _domainParticipantFactory->create_participant( _domainID, PARTICIPANT_QOS_DEFAULT,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tDDS::DomainParticipantListener::_nil(),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tOpenDDS::DCPS::DEFAULT_STATUS_MASK );\n\n\t\/\/ Exit is nil\n\tif( !_participant )\n\t{\n\t\tLOG( ERROR ) << \"Create Participant Failed.\";\n\t}\n}\n\nvoid CAppNodeImpl::InitPublisherAndSubscriber()\n{\n\t\/\/ Publisher\n\t_publisher = _participant->create_publisher( PUBLISHER_QOS_DEFAULT,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tDDS::PublisherListener::_nil(),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tOpenDDS::DCPS::DEFAULT_STATUS_MASK );\n\n\t\/\/ Exit if nil\n\tif( !_publisher )\n\t{\n\t\tLOG( ERROR ) << \"Create publisher failed.\";\n\t}\n\n\t\/\/ Subscriber\n\t_subscriber = _participant->create_subscriber( SUBSCRIBER_QOS_DEFAULT,\n\t\t\t\t\t\t\t\t\t\t\t\t\tDDS::SubscriberListener::_nil(),\n\t\t\t\t\t\t\t\t\t\t\t\t\tOpenDDS::DCPS::DEFAULT_STATUS_MASK );\n\tif( !_subscriber )\n\t{\n\t\tLOG( ERROR ) << \"Create subscriber failed.\";\n\t}\n}\n\nvoid CAppNodeImpl::InitTopicinfo()\n{\n\t\/\/ Type registration\n\t_exampleTypeSupport = new ExampleApp::EventTypeSupportImpl();\n\n\t\/\/ Exit if retcode ! ok\n\tif( DDS::RETCODE_OK != _exampleTypeSupport->register_type( _participant, \"\" ) )\n\t{\n\t\tLOG( ERROR ) << \"register type failed.\";\n\t}\n\n\t\/\/ Create a topic\n\t_topicTypeName = _exampleTypeSupport->get_type_name();\n\n\t_topic = _participant->create_topic( \"Test Topic\", _topicTypeName.in(),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tTOPIC_QOS_DEFAULT,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tDDS::TopicListener::_nil(),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tOpenDDS::DCPS::DEFAULT_STATUS_MASK );\n\n\tif( !_topic )\n\t{\n\t\tLOG( ERROR ) << \"Create topic failed\";\n\t}\n}\n\nvoid CAppNodeImpl::InitDataWriter()\n{\n\t\/\/ Create the data writer\n\t_writer = _publisher->create_datawriter( _topic, DATAWRITER_QOS_DEFAULT,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tDDS::DataWriterListener::_nil(),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tOpenDDS::DCPS::DEFAULT_STATUS_MASK );\n\n\tif( !_writer )\n\t{\n\t\tLOG( ERROR ) << \"Create datawriter failed\";\n\t}\n\n\t_eventWriter = ExampleApp::EventDataWriter::_narrow( _writer );\n\n\tif( !_eventWriter )\n\t{\n\t\tLOG( ERROR ) << \"_narrow failed\";\n\t}\n\n}\n\nvoid CAppNodeImpl::InitDataReader()\n{\n\t\/\/ Data Reader\n\t_listener = new CDataReaderListenerImpl;\n\n\t_reader = _subscriber->create_datareader( _topic, DATAREADER_QOS_DEFAULT,\n\t\t\t\t\t\t\t\t\t\t\t\t_listener,\n\t\t\t\t\t\t\t\t\t\t\t\tOpenDDS::DCPS::DEFAULT_STATUS_MASK );\n\n\tif( !_reader )\n\t{\n\t\tLOG( ERROR ) << \" Create data reader failed\";\n\t}\n\n\t_readerI = ExampleApp::EventDataReader::_narrow( _reader );\n\n\tif( !_readerI )\n\t{\n\n\t\tLOG( ERROR ) << \" _narrow failed\";\n\t}\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"SysConfig.h\"\n#if(HAS_PCA9539)\n\n#include <CI2C.h>\n#include \"CPCA9539.h\"\n#include \"CTimer.h\"\n#include \"NDataManager.h\"\n\nnamespace\n{\n CTimer pca9539_sample_timer;\n bool toggle = true;\n\n}\n\nCPCA9539::CPCA9539( CI2C *i2cInterfaceIn )\n : m_pca( i2cInterfaceIn )\n{\n\n}\n\nvoid CPCA9539::Initialize()\n{\n Serial.println( \"CPCA9539.Status:INIT;\" );\n\n pca9539_sample_timer.Reset();\n m_pca.Initialize();\n m_pca.PinMode( OUTPUT );\n\n Serial.println( \"CPCA9539.Status:POST_INIT;\");\n}\n\nvoid CPCA9539::Update( CCommand &commandIn )\n{\n if( pca9539_sample_timer.HasElapsed( 1000 ) )\n {\n Serial.println( \"PCA9539.Status:LOOP;\" );\n if( toggle )\n {\n auto ret = m_pca.DigitalWrite( 0 , HIGH )\n Serial.println( ret );\n }\n else\n {\n auto ret = m_pca.DigitalWrite( 0 , LOW )\n Serial.println( ret );\n }\n \n }\n}\n\n#endif<commit_msg>semicolons<commit_after>#include \"SysConfig.h\"\n#if(HAS_PCA9539)\n\n#include <CI2C.h>\n#include \"CPCA9539.h\"\n#include \"CTimer.h\"\n#include \"NDataManager.h\"\n\nnamespace\n{\n CTimer pca9539_sample_timer;\n bool toggle = true;\n\n}\n\nCPCA9539::CPCA9539( CI2C *i2cInterfaceIn )\n : m_pca( i2cInterfaceIn )\n{\n\n}\n\nvoid CPCA9539::Initialize()\n{\n Serial.println( \"CPCA9539.Status:INIT;\" );\n\n pca9539_sample_timer.Reset();\n m_pca.Initialize();\n m_pca.PinMode( OUTPUT );\n\n Serial.println( \"CPCA9539.Status:POST_INIT;\");\n}\n\nvoid CPCA9539::Update( CCommand &commandIn )\n{\n if( pca9539_sample_timer.HasElapsed( 1000 ) )\n {\n Serial.println( \"PCA9539.Status:LOOP;\" );\n if( toggle )\n {\n auto ret = m_pca.DigitalWrite( 0 , HIGH );\n Serial.println( ret );\n }\n else\n {\n auto ret = m_pca.DigitalWrite( 0 , LOW );\n Serial.println( ret );\n }\n \n }\n}\n\n#endif<|endoftext|>"} {"text":"<commit_before>\/* dataproxy.cc\t\t\tKPilot\n**\n** Copyright (C) 2007 by Bertjan Broeksema <b.broeksema@kdemail.net>\n** Copyright (C) 2007 by Jason \"vanRijn\" Kasper <vr@movingparts.net>\n*\/\n\n\/*\n** This program is free software; you can redistribute it and\/or modify\n** it under the terms of the GNU Lesser General Public License as published by\n** the Free Software Foundation; either version 2.1 of the License, or\n** (at your option) any later version.\n**\n** This program is distributed in the hope that it will be useful,\n** but WITHOUT ANY WARRANTY; without even the implied warranty of\n** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n** GNU Lesser General Public License for more details.\n**\n** You should have received a copy of the GNU Lesser General Public License\n** along with this program in a file called COPYING; if not, write to\n** the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,\n** MA 02110-1301, USA.\n*\/\n\n\/*\n** Bug reports and questions can be sent to kde-pim@kde.org\n*\/\n\n#include \"dataproxy.h\"\n#include \"record.h\"\n\n#include \"options.h\"\n\nDataProxy::DataProxy() : fIterator( fRecords )\n{\n\tFUNCTIONSETUP;\n}\n\nDataProxy::~DataProxy()\n{\n\tFUNCTIONSETUP;\n\t\n\tqDeleteAll( fRecords );\n}\n\nQString DataProxy::create( Record *record )\n{\n\tFUNCTIONSETUP;\n\t\n\t\/\/ Temporary id.\n\tQString uniqueId = generateUniqueId();\n\t\n\t\/\/ Make sure that the new record has the right id and add the record.\n\trecord->setId( uniqueId );\n\t\n\tDEBUGKPILOT << \"Record created with id: [\" << uniqueId << \"]\";\n\t\n\tfRecords.insert( uniqueId, record );\n\t\n\t\/\/ Update rollback\/volatility information.\n\tfCreated.insert( uniqueId, false );\n\tfCounter.created();\n\t\n\treturn uniqueId;\n}\n\nvoid DataProxy::remove( const QString &id )\n{\n\tFUNCTIONSETUP;\n\t\n\tRecord *rec = fRecords.value( id );\n\tif( rec == 0L )\n\t{\n\t\t\/\/ No record\n\t\treturn;\n\t}\n\t\n\tDEBUGKPILOT << \"Removing record id: [\" << id << \"]\";\n\t\/\/ Remove record.\n\tfRecords.remove( id );\n\t\n\t\/\/ Update rollback\/volatility information.\n\tfDeletedRecords.insert( rec->id(), rec );\n\tfDeleted.insert( rec->id(), false );\n\tfCounter.deleted();\n}\n\nvoid DataProxy::update( const QString &id, Record *newRecord )\n{\n\tFUNCTIONSETUP;\n\t\n\tRecord *oldRecord = fRecords.value( id );\n\tif( oldRecord == 0L )\n\t{\n\t\t\/\/ No record, should not happen.\n\t\tDEBUGKPILOT << \"There is no record with id: [\" << id\n\t\t\t<< \"]. Record not updated and not added.\";\n\t\treturn;\n\t}\n\tDEBUGKPILOT << \"Updating record id: [\" << id << \"]\";\n\t\/\/ Make sure that the new record has the right id and update the old record.\n\tnewRecord->setId( id );\n\tfRecords.insert( id, newRecord );\n\t\n\t\/\/ Update rollback\/volatility information.\n\tfOldRecords.insert( id, oldRecord );\n\tfCounter.updated();\n}\n\nQList<QString> DataProxy::ids() const\n{\n\treturn fRecords.keys();\n}\n\nconst CUDCounter* DataProxy::counter() const\n{\n\tFUNCTIONSETUP;\n\t\n\treturn &fCounter;\n}\n\nvoid DataProxy::setEndcount()\n{\n\tFUNCTIONSETUP;\n\t\n\tfCounter.setEndCount( fRecords.size() );\n}\n\nvoid DataProxy::setIterateMode( const Mode m )\n{\n\tFUNCTIONSETUP;\n\t\n\tfMode = m;\n}\n\nunsigned int DataProxy::recordCount() const\n{\n\treturn fRecords.size();\n}\n\nRecord* DataProxy::find( const QString &id ) const\n{\n\tFUNCTIONSETUP;\n\treturn fRecords.value( id );\n}\n\nvoid DataProxy::resetIterator()\n{\n\tfIterator = QMapIterator<QString, Record*>( fRecords );\n}\n\nbool DataProxy::hasNext() const\n{\n\tFUNCTIONSETUP;\n\t\n\tif( fMode == All )\n\t{\n\t\treturn fIterator.hasNext();\n\t}\n\telse\n\t{\n\t\tQMapIterator<QString, Record*> tmpIt = fIterator;\n\t\twhile( tmpIt.hasNext() )\n\t\t{\n\t\t\tRecord *rec = tmpIt.next().value();\n\t\t\tif( rec->isModified() )\n\t\t\t{\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t}\n\t\n\treturn false;\n}\n\nRecord* DataProxy::next()\n{\n\tFUNCTIONSETUP;\n\t\n\tif( fMode == All )\n\t{\n\t\t\treturn fIterator.next().value();\n\t}\n\telse\n\t{\n\t\twhile( fIterator.hasNext() )\n\t\t{\n\t\t\tRecord *rec = fIterator.next().value();\n\t\t\tif( rec->isModified() )\n\t\t\t{\n\t\t\t\treturn rec;\n\t\t\t}\n\t\t}\n\t}\n\t\n\treturn 0L;\n}\n\nbool DataProxy::commit()\n{\n\tFUNCTIONSETUP;\n\t\n\t\/\/ Commit created records.\n\tQStringListIterator it( fCreated.keys() );\n\t\n\tDEBUGKPILOT << \"Committing: [\" << fCreated.size() << \"] records.\";\n\t\n\t\/\/ Reset the map\n\tfCreated.clear();\n\t\n\twhile( it.hasNext() )\n\t{\n\t\tQString id = it.next();\n\t\t\n\t\tDEBUGKPILOT << \"Committing id: [\" << id << \"]\";\n\t\t\n\t\tRecord *rec = find( id );\n\t\tif( rec )\n\t\t{\n\t\t\tcommitCreate( rec );\n\t\t\t\n\t\t\t\/\/ Put the record with the new id in.\n\t\t\tif( rec->id() != id )\n\t\t\t{\n\t\t\t\tfCreated.remove( id );\n\t\t\t\tfCreated.insert( rec->id(), true );\n\t\t\t\t\n\t\t\t\tfRecords.remove( id );\n\t\t\t\tfRecords.insert( rec->id(), rec );\n\t\t\t\n\t\t\t\tfChangedIds.insert( id, rec->id() );\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tfCreated.insert( rec->id(), true );\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tDEBUGKPILOT << \"Record with id: [\" << id << \"] not found!\";\n\t\t}\n\t}\n\t\n\t\/\/ Commit updated records.\n\tDEBUGKPILOT << \"Updating: [\" << fOldRecords.size() << \"] records.\";\n\t\n\tQListIterator<Record*> i( fOldRecords.values() );\n\twhile( i.hasNext() )\n\t{\n\t\t\/\/ i.next() contains the old values.\n\t\tRecord *oldRec = i.next();\n\t\tQString id = oldRec->id();\n\t\t\n\t\t\/\/ Look up the new values\n\t\tRecord *rec = find( id );\n\t\t\n\t\tif( rec && !fCreated.value( id ) )\n\t\t{\n\t\t\tcommitUpdate( rec );\n\t\t\tQString newId = rec->id();\n\t\t\t\n\t\t\tif( newId != id )\n\t\t\t{\n\t\t\t\toldRec->setId( newId );\n\t\t\t\t\n\t\t\t\tfChangedIds.insert( id, newId );\n\t\t\t}\n\t\t\tfUpdated.insert( rec->id(), true );\n\t\t}\n\t}\n\t\n\t\/\/ Commit deleted records\n\tDEBUGKPILOT << \"Updating: [\" << fDeletedRecords.size() << \"] records.\";\n\t\n\ti = QListIterator<Record*>( fDeletedRecords.values() );\n\twhile( i.hasNext() )\n\t{\n\t\tRecord *oldRec = i.next();\n\t\t\n\t\tif( !fDeleted.value( oldRec->id() ) )\n\t\t{\n\t\t\tDEBUGKPILOT << \"Deleting record: [\" << oldRec->id() << \"].\";\n\t\t\tcommitDelete( oldRec );\n\t\t\tfDeleted.insert( oldRec->id(), true );\n\t\t}\n\t}\n\t\n\t\/\/ Give implementing classes the change to do things if necessary.\n\treturn _commit();\n}\n\nbool DataProxy::rollback()\n{\n\tFUNCTIONSETUP;\n\t\n\t\/\/ Delete committed new records.\n\tQStringListIterator it( fCreated.keys() );\n\t\n\twhile( it.hasNext() )\n\t{\n\t\tQString id = it.next();\n\t\t\n\t\t\/\/ Only undo creates that are committed.\n\t\tRecord *rec = find( id );\n\t\tif( rec && fCreated.value( id ) )\n\t\t{\n\t\t\tDEBUGKPILOT << \"Deleting created record: [\" << rec->id() << \"].\";\n\t\t\t\n\t\t\tcommitDelete( rec );\n\t\t\tfCreated.insert( rec->id(), false );\n\t\t}\n\t}\n\t\n\t\/\/ Reset the map\n\tfCreated.clear();\n\t\n\t\/\/ Undo changes to updated records.\n\tQListIterator<Record*> i( fOldRecords.values() );\n\twhile( i.hasNext() )\n\t{\n\t\tRecord *oldRec = i.next();\n\t\tif( fUpdated.value( oldRec->id() ) )\n\t\t{\n\t\t\tDEBUGKPILOT << \"Restoring changed record: [\" << oldRec->id() << \"].\";\n\t\t\t\n\t\t\tQString oldId = oldRec->id();\n\t\t\tcommitUpdate( oldRec );\n\t\t\t\n\t\t\t\/\/ Id might have changed\n\t\t\tif( oldRec->id() != oldId )\n\t\t\t{\n\t\t\t\tfUpdated.remove( oldId );\n\t\t\t\t\n\t\t\t\tfChangedIds.insert( oldId, oldRec->id() );\n\t\t\t}\n\t\t\t\n\t\t\tfUpdated.insert( oldRec->id(), false );\n\t\t}\n\t}\n\t\n\t\/\/ Restore deleted records.\n\ti = QListIterator<Record*>( fDeletedRecords.values() );\n\twhile( i.hasNext() )\n\t{\n\t\tRecord *oldRec = i.next();\n\t\t\n\t\tif( fDeleted.value( oldRec->id() ) )\n\t\t{\n\t\t\tDEBUGKPILOT << \"Restoring deleted record: [\" << oldRec->id() << \"].\";\n\t\t\n\t\t\tQString oldId = oldRec->id();\n\t\t\tcommitCreate( oldRec );\n\t\t\t\n\t\t\t\/\/ Id might have changed\n\t\t\tif( oldRec->id() != oldId )\n\t\t\t{\n\t\t\t\tfDeleted.remove( oldId );\n\t\t\t\t\n\t\t\t\tfChangedIds.insert( oldId, oldRec->id() );\n\t\t\t}\n\t\t\t\n\t\t\tfDeleted.insert( oldRec->id(), false );\n\t\t}\n\t}\n\t\n\t\/\/ Give implementing classes the change to rollback things if necessary.\n\treturn _rollback();\n}\n\nQMap<QString,QString> DataProxy::changedIds()\n{\n\treturn fChangedIds;\n}\n<commit_msg>SVN_SILENT: Debug info update.<commit_after>\/* dataproxy.cc\t\t\tKPilot\n**\n** Copyright (C) 2007 by Bertjan Broeksema <b.broeksema@kdemail.net>\n** Copyright (C) 2007 by Jason \"vanRijn\" Kasper <vr@movingparts.net>\n*\/\n\n\/*\n** This program is free software; you can redistribute it and\/or modify\n** it under the terms of the GNU Lesser General Public License as published by\n** the Free Software Foundation; either version 2.1 of the License, or\n** (at your option) any later version.\n**\n** This program is distributed in the hope that it will be useful,\n** but WITHOUT ANY WARRANTY; without even the implied warranty of\n** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n** GNU Lesser General Public License for more details.\n**\n** You should have received a copy of the GNU Lesser General Public License\n** along with this program in a file called COPYING; if not, write to\n** the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,\n** MA 02110-1301, USA.\n*\/\n\n\/*\n** Bug reports and questions can be sent to kde-pim@kde.org\n*\/\n\n#include \"dataproxy.h\"\n#include \"record.h\"\n\n#include \"options.h\"\n\nDataProxy::DataProxy() : fIterator( fRecords )\n{\n\tFUNCTIONSETUP;\n}\n\nDataProxy::~DataProxy()\n{\n\tFUNCTIONSETUP;\n\t\n\tqDeleteAll( fRecords );\n}\n\nQString DataProxy::create( Record *record )\n{\n\tFUNCTIONSETUP;\n\t\n\t\/\/ Temporary id.\n\tQString uniqueId = generateUniqueId();\n\t\n\t\/\/ Make sure that the new record has the right id and add the record.\n\trecord->setId( uniqueId );\n\t\n\tDEBUGKPILOT << \"Record created with id: [\" << uniqueId << \"]\";\n\t\n\tfRecords.insert( uniqueId, record );\n\t\n\t\/\/ Update rollback\/volatility information.\n\tfCreated.insert( uniqueId, false );\n\tfCounter.created();\n\t\n\treturn uniqueId;\n}\n\nvoid DataProxy::remove( const QString &id )\n{\n\tFUNCTIONSETUP;\n\t\n\tRecord *rec = fRecords.value( id );\n\tif( rec == 0L )\n\t{\n\t\t\/\/ No record\n\t\treturn;\n\t}\n\t\n\tDEBUGKPILOT << \"Removing record id: [\" << id << \"]\";\n\t\/\/ Remove record.\n\tfRecords.remove( id );\n\t\n\t\/\/ Update rollback\/volatility information.\n\tfDeletedRecords.insert( rec->id(), rec );\n\tfDeleted.insert( rec->id(), false );\n\tfCounter.deleted();\n}\n\nvoid DataProxy::update( const QString &id, Record *newRecord )\n{\n\tFUNCTIONSETUP;\n\t\n\tRecord *oldRecord = fRecords.value( id );\n\tif( oldRecord == 0L )\n\t{\n\t\t\/\/ No record, should not happen.\n\t\tDEBUGKPILOT << \"There is no record with id: [\" << id\n\t\t\t<< \"]. Record not updated and not added.\";\n\t\treturn;\n\t}\n\tDEBUGKPILOT << \"Updating record id: [\" << id << \"]\";\n\t\/\/ Make sure that the new record has the right id and update the old record.\n\tnewRecord->setId( id );\n\tfRecords.insert( id, newRecord );\n\t\n\t\/\/ Update rollback\/volatility information.\n\tfOldRecords.insert( id, oldRecord );\n\tfCounter.updated();\n}\n\nQList<QString> DataProxy::ids() const\n{\n\treturn fRecords.keys();\n}\n\nconst CUDCounter* DataProxy::counter() const\n{\n\tFUNCTIONSETUP;\n\t\n\treturn &fCounter;\n}\n\nvoid DataProxy::setEndcount()\n{\n\tFUNCTIONSETUP;\n\t\n\tfCounter.setEndCount( fRecords.size() );\n}\n\nvoid DataProxy::setIterateMode( const Mode m )\n{\n\tFUNCTIONSETUP;\n\t\n\tfMode = m;\n}\n\nunsigned int DataProxy::recordCount() const\n{\n\treturn fRecords.size();\n}\n\nRecord* DataProxy::find( const QString &id ) const\n{\n\tFUNCTIONSETUP;\n\treturn fRecords.value( id );\n}\n\nvoid DataProxy::resetIterator()\n{\n\tfIterator = QMapIterator<QString, Record*>( fRecords );\n}\n\nbool DataProxy::hasNext() const\n{\n\tFUNCTIONSETUP;\n\t\n\tif( fMode == All )\n\t{\n\t\treturn fIterator.hasNext();\n\t}\n\telse\n\t{\n\t\tQMapIterator<QString, Record*> tmpIt = fIterator;\n\t\twhile( tmpIt.hasNext() )\n\t\t{\n\t\t\tRecord *rec = tmpIt.next().value();\n\t\t\tif( rec->isModified() )\n\t\t\t{\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t}\n\t\n\treturn false;\n}\n\nRecord* DataProxy::next()\n{\n\tFUNCTIONSETUP;\n\t\n\tif( fMode == All )\n\t{\n\t\t\treturn fIterator.next().value();\n\t}\n\telse\n\t{\n\t\twhile( fIterator.hasNext() )\n\t\t{\n\t\t\tRecord *rec = fIterator.next().value();\n\t\t\tif( rec->isModified() )\n\t\t\t{\n\t\t\t\treturn rec;\n\t\t\t}\n\t\t}\n\t}\n\t\n\treturn 0L;\n}\n\nbool DataProxy::commit()\n{\n\tFUNCTIONSETUP;\n\t\n\t\/\/ Commit created records.\n\tQStringListIterator it( fCreated.keys() );\n\t\n\tDEBUGKPILOT << \"Committing: [\" << fCreated.size() << \"] records.\";\n\t\n\t\/\/ Reset the map\n\tfCreated.clear();\n\t\n\twhile( it.hasNext() )\n\t{\n\t\tQString id = it.next();\n\t\t\n\t\tDEBUGKPILOT << \"Committing id: [\" << id << \"]\";\n\t\t\n\t\tRecord *rec = find( id );\n\t\tif( rec )\n\t\t{\n\t\t\tcommitCreate( rec );\n\t\t\t\n\t\t\t\/\/ Put the record with the new id in.\n\t\t\tif( rec->id() != id )\n\t\t\t{\n\t\t\t\tfCreated.remove( id );\n\t\t\t\tfCreated.insert( rec->id(), true );\n\t\t\t\t\n\t\t\t\tfRecords.remove( id );\n\t\t\t\tfRecords.insert( rec->id(), rec );\n\t\t\t\n\t\t\t\tfChangedIds.insert( id, rec->id() );\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tfCreated.insert( rec->id(), true );\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tDEBUGKPILOT << \"Record with id: [\" << id << \"] not found!\";\n\t\t}\n\t}\n\t\n\t\/\/ Commit updated records.\n\tDEBUGKPILOT << \"Updating: [\" << fOldRecords.size() << \"] records.\";\n\t\n\tQListIterator<Record*> i( fOldRecords.values() );\n\twhile( i.hasNext() )\n\t{\n\t\t\/\/ i.next() contains the old values.\n\t\tRecord *oldRec = i.next();\n\t\tQString id = oldRec->id();\n\t\t\n\t\t\/\/ Look up the new values\n\t\tRecord *rec = find( id );\n\t\t\n\t\tif( rec && !fCreated.value( id ) )\n\t\t{\n\t\t\tcommitUpdate( rec );\n\t\t\tQString newId = rec->id();\n\t\t\t\n\t\t\tif( newId != id )\n\t\t\t{\n\t\t\t\toldRec->setId( newId );\n\t\t\t\t\n\t\t\t\tfChangedIds.insert( id, newId );\n\t\t\t}\n\t\t\tfUpdated.insert( rec->id(), true );\n\t\t}\n\t}\n\t\n\t\/\/ Commit deleted records\n\tDEBUGKPILOT << \"Deleting: [\" << fDeletedRecords.size() << \"] records.\";\n\t\n\ti = QListIterator<Record*>( fDeletedRecords.values() );\n\twhile( i.hasNext() )\n\t{\n\t\tRecord *oldRec = i.next();\n\t\t\n\t\tif( !fDeleted.value( oldRec->id() ) )\n\t\t{\n\t\t\tDEBUGKPILOT << \"Deleting record: [\" << oldRec->id() << \"].\";\n\t\t\tcommitDelete( oldRec );\n\t\t\tfDeleted.insert( oldRec->id(), true );\n\t\t}\n\t}\n\t\n\t\/\/ Give implementing classes the change to do things if necessary.\n\treturn _commit();\n}\n\nbool DataProxy::rollback()\n{\n\tFUNCTIONSETUP;\n\t\n\t\/\/ Delete committed new records.\n\tQStringListIterator it( fCreated.keys() );\n\t\n\twhile( it.hasNext() )\n\t{\n\t\tQString id = it.next();\n\t\t\n\t\t\/\/ Only undo creates that are committed.\n\t\tRecord *rec = find( id );\n\t\tif( rec && fCreated.value( id ) )\n\t\t{\n\t\t\tDEBUGKPILOT << \"Deleting created record: [\" << rec->id() << \"].\";\n\t\t\t\n\t\t\tcommitDelete( rec );\n\t\t\tfCreated.insert( rec->id(), false );\n\t\t}\n\t}\n\t\n\t\/\/ Reset the map\n\tfCreated.clear();\n\t\n\t\/\/ Undo changes to updated records.\n\tQListIterator<Record*> i( fOldRecords.values() );\n\twhile( i.hasNext() )\n\t{\n\t\tRecord *oldRec = i.next();\n\t\tif( fUpdated.value( oldRec->id() ) )\n\t\t{\n\t\t\tDEBUGKPILOT << \"Restoring changed record: [\" << oldRec->id() << \"].\";\n\t\t\t\n\t\t\tQString oldId = oldRec->id();\n\t\t\tcommitUpdate( oldRec );\n\t\t\t\n\t\t\t\/\/ Id might have changed\n\t\t\tif( oldRec->id() != oldId )\n\t\t\t{\n\t\t\t\tfUpdated.remove( oldId );\n\t\t\t\t\n\t\t\t\tfChangedIds.insert( oldId, oldRec->id() );\n\t\t\t}\n\t\t\t\n\t\t\tfUpdated.insert( oldRec->id(), false );\n\t\t}\n\t}\n\t\n\t\/\/ Restore deleted records.\n\ti = QListIterator<Record*>( fDeletedRecords.values() );\n\twhile( i.hasNext() )\n\t{\n\t\tRecord *oldRec = i.next();\n\t\t\n\t\tif( fDeleted.value( oldRec->id() ) )\n\t\t{\n\t\t\tDEBUGKPILOT << \"Restoring deleted record: [\" << oldRec->id() << \"].\";\n\t\t\n\t\t\tQString oldId = oldRec->id();\n\t\t\tcommitCreate( oldRec );\n\t\t\t\n\t\t\t\/\/ Id might have changed\n\t\t\tif( oldRec->id() != oldId )\n\t\t\t{\n\t\t\t\tfDeleted.remove( oldId );\n\t\t\t\t\n\t\t\t\tfChangedIds.insert( oldId, oldRec->id() );\n\t\t\t}\n\t\t\t\n\t\t\tfDeleted.insert( oldRec->id(), false );\n\t\t}\n\t}\n\t\n\t\/\/ Give implementing classes the change to rollback things if necessary.\n\treturn _rollback();\n}\n\nQMap<QString,QString> DataProxy::changedIds()\n{\n\treturn fChangedIds;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright by Contributors\n#include \"..\/..\/src\/tree\/param.h\"\n\n#include \"..\/helpers.h\"\n\nTEST(Param, VectorIOStream) {\n std::vector<int> vals = {3, 2, 1};\n std::stringstream ss;\n std::vector<int> vals_in;\n \n ss << vals;\n EXPECT_EQ(ss.str(), \"(3,2,1)\");\n\n ss >> vals_in;\n EXPECT_EQ(vals_in, vals);\n\n vals.clear(); ss.flush(); ss.clear(); ss.str(\"\");\n vals = {1};\n ss << vals;\n EXPECT_EQ(ss.str(), \"(1,)\");\n}\n\nTEST(Param, VectorStreamRead) {\n std::vector<int> vals = {3, 2, 1};\n std::stringstream ss;\n std::vector<int> vals_in;\n\n vals_in.clear(); ss.flush(); ss.clear(); ss.str(\"\");\n ss << \"(3, 2, 1)\";\n ss >> vals_in;\n EXPECT_EQ(vals_in, vals);\n\n vals_in.clear(); ss.flush(); ss.clear(); ss.str(\"\");\n ss << \"(3L,2L,1L)\";\n ss >> vals_in;\n EXPECT_EQ(vals_in, vals);\n\n vals_in.clear(); ss.flush(); ss.clear(); ss.str(\"\");\n ss << \" (3,2,1,)\";\n ss >> vals_in;\n EXPECT_EQ(vals_in, vals);\n\n vals_in.clear(); ss.flush(); ss.clear(); ss.str(\"\");\n ss << \" ( 3, 2,1 )\";\n ss >> vals_in;\n EXPECT_EQ(vals_in, vals);\n\n vals_in.clear(); ss.flush(); ss.clear(); ss.str(\"\");\n ss << \" ( 3, 2,1 ) \";\n ss >> vals_in;\n EXPECT_EQ(vals_in, vals);\n\n vals_in.clear(); ss.flush(); ss.clear(); ss.str(\"\");\n ss << \" 321 \";\n ss >> vals_in;\n EXPECT_EQ(vals_in[0], 321);\n\n vals_in.clear(); ss.flush(); ss.clear(); ss.str(\"\");\n ss << \"(3.0,2,1)\";\n ss >> vals_in;\n EXPECT_NE(vals_in, vals);\n\n vals_in.clear(); ss.flush(); ss.clear(); ss.str(\"\");\n ss << \"1a\";\n ss >> vals_in;\n EXPECT_NE(vals_in, vals);\n\n vals_in.clear(); ss.flush(); ss.clear(); ss.str(\"\");\n ss << \"abcde\";\n ss >> vals_in;\n EXPECT_NE(vals_in, vals);\n\n vals_in.clear(); ss.flush(); ss.clear(); ss.str(\"\");\n ss << \"(3,2,1\";\n ss >> vals_in;\n EXPECT_NE(vals_in, vals);\n}\n<commit_msg>tests\/cpp: Add tests for SplitEntry<commit_after>\/\/ Copyright by Contributors\n#include \"..\/..\/src\/tree\/param.h\"\n\n#include \"..\/helpers.h\"\n\nTEST(Param, VectorIOStream) {\n std::vector<int> vals = {3, 2, 1};\n std::stringstream ss;\n std::vector<int> vals_in;\n \n ss << vals;\n EXPECT_EQ(ss.str(), \"(3,2,1)\");\n\n ss >> vals_in;\n EXPECT_EQ(vals_in, vals);\n\n vals.clear(); ss.flush(); ss.clear(); ss.str(\"\");\n vals = {1};\n ss << vals;\n EXPECT_EQ(ss.str(), \"(1,)\");\n}\n\nTEST(Param, VectorStreamRead) {\n std::vector<int> vals = {3, 2, 1};\n std::stringstream ss;\n std::vector<int> vals_in;\n\n vals_in.clear(); ss.flush(); ss.clear(); ss.str(\"\");\n ss << \"(3, 2, 1)\";\n ss >> vals_in;\n EXPECT_EQ(vals_in, vals);\n\n vals_in.clear(); ss.flush(); ss.clear(); ss.str(\"\");\n ss << \"(3L,2L,1L)\";\n ss >> vals_in;\n EXPECT_EQ(vals_in, vals);\n\n vals_in.clear(); ss.flush(); ss.clear(); ss.str(\"\");\n ss << \" (3,2,1,)\";\n ss >> vals_in;\n EXPECT_EQ(vals_in, vals);\n\n vals_in.clear(); ss.flush(); ss.clear(); ss.str(\"\");\n ss << \" ( 3, 2,1 )\";\n ss >> vals_in;\n EXPECT_EQ(vals_in, vals);\n\n vals_in.clear(); ss.flush(); ss.clear(); ss.str(\"\");\n ss << \" ( 3, 2,1 ) \";\n ss >> vals_in;\n EXPECT_EQ(vals_in, vals);\n\n vals_in.clear(); ss.flush(); ss.clear(); ss.str(\"\");\n ss << \" 321 \";\n ss >> vals_in;\n EXPECT_EQ(vals_in[0], 321);\n\n vals_in.clear(); ss.flush(); ss.clear(); ss.str(\"\");\n ss << \"(3.0,2,1)\";\n ss >> vals_in;\n EXPECT_NE(vals_in, vals);\n\n vals_in.clear(); ss.flush(); ss.clear(); ss.str(\"\");\n ss << \"1a\";\n ss >> vals_in;\n EXPECT_NE(vals_in, vals);\n\n vals_in.clear(); ss.flush(); ss.clear(); ss.str(\"\");\n ss << \"abcde\";\n ss >> vals_in;\n EXPECT_NE(vals_in, vals);\n\n vals_in.clear(); ss.flush(); ss.clear(); ss.str(\"\");\n ss << \"(3,2,1\";\n ss >> vals_in;\n EXPECT_NE(vals_in, vals);\n}\n\nTEST(Param, SplitEntry) {\n xgboost::tree::SplitEntry se1;\n EXPECT_FALSE(se1.NeedReplace(-1, 100));\n\n xgboost::tree::SplitEntry se2;\n EXPECT_FALSE(se1.Update(se2));\n EXPECT_FALSE(se2.Update(-1, 100, 0, true));\n ASSERT_TRUE(se2.Update(1, 100, 0, true));\n ASSERT_TRUE(se1.Update(se2));\n\n xgboost::tree::SplitEntry se3;\n se3.Update(2, 101, 0, false);\n xgboost::tree::SplitEntry::Reduce(se2, se3);\n EXPECT_EQ(se2.split_index(), 101);\n EXPECT_FALSE(se2.default_left());\n\n EXPECT_TRUE(se1.NeedReplace(3, 1));\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * tidyup_planning_scene_updater.cpp\n *\n * Created on: 10 Aug 2012\n * Author: andreas\n *\/\n\n#include \"planner_modules_pr2\/tidyup_planning_scene_updater.h\"\n#include <tidyup_utils\/planning_scene_interface.h>\n#include <tidyup_utils\/arm_state.h>\n#include <tidyup_utils\/stringutil.h>\n#include <hardcoded_facts\/geometryPoses.h>\n#include <ros\/ros.h>\n\nusing std::vector;\nusing std::map;\nusing std::set;\nusing std::string;\n\nTidyupPlanningSceneUpdater* TidyupPlanningSceneUpdater::instance = NULL;\n\nTidyupPlanningSceneUpdater::TidyupPlanningSceneUpdater() : logName(\"[psu]\")\n{\n string doorLocationFileName;\n ros::param::get(\"\/continual_planning_executive\/door_location_file\", doorLocationFileName);\n loadDoorPoses(doorLocationFileName);\n\n defaultAttachPose.position.x = 0.032;\n defaultAttachPose.position.y = 0.015;\n defaultAttachPose.position.z = 0.0;\n defaultAttachPose.orientation.x = 0.707;\n defaultAttachPose.orientation.y = -0.106;\n defaultAttachPose.orientation.z = -0.690;\n defaultAttachPose.orientation.w = 0.105;\n\n ROS_INFO(\"%s initialized.\\n\", logName.c_str());\n}\n\nTidyupPlanningSceneUpdater::~TidyupPlanningSceneUpdater()\n{\n}\n\nbool TidyupPlanningSceneUpdater::readState(\n const string& robotLocation,\n predicateCallbackType predicateCallback,\n numericalFluentCallbackType numericalFluentCallback,\n geometry_msgs::Pose& robotPose,\n map<string, geometry_msgs::Pose>& movableObjects,\n map<string, string>& graspedObjects,\n map<string, string>& objectsOnStatic,\n set<string>& openDoors)\n{\n if (instance == NULL) instance = new TidyupPlanningSceneUpdater();\n return instance->readState_(robotLocation, predicateCallback, numericalFluentCallback, robotPose, movableObjects, graspedObjects, objectsOnStatic, openDoors);\n}\n\nbool TidyupPlanningSceneUpdater::readState_(\n const string& robotLocation,\n predicateCallbackType predicateCallback,\n numericalFluentCallbackType numericalFluentCallback,\n geometry_msgs::Pose& robotPose,\n map<string, geometry_msgs::Pose>& movableObjects,\n map<string, string>& graspedObjects,\n map<string, string>& objectsOnStatic,\n set<string>& openDoors)\n{\n \/\/ get poses of all movable objects\n PlanningSceneInterface* psi = PlanningSceneInterface::instance();\n \/\/ psi->resetPlanningScene();\n geometry_msgs::Pose pose;\n const vector <arm_navigation_msgs::CollisionObject>& collisionObjects = psi->getCollisionObjects();\n for (vector <arm_navigation_msgs::CollisionObject>::const_iterator it = collisionObjects.begin();\n it != collisionObjects.end(); it++)\n {\n const string& objectName = it->id;\n if (StringUtil::startsWith(objectName, \"table\"))\n continue;\n if (StringUtil::startsWith(objectName, \"door\"))\n continue;\n if (! fillPoseFromState(pose, objectName, numericalFluentCallback))\n {\n psi->removeObject(objectName);\n }\n else\n {\n movableObjects.insert(make_pair(objectName, pose));\n }\n }\n const vector <arm_navigation_msgs::AttachedCollisionObject>& attachedObjects = psi->getAttachedCollisionObjects();\n for (vector <arm_navigation_msgs::AttachedCollisionObject>::const_iterator it = attachedObjects.begin(); it != attachedObjects.end(); it++)\n {\n const string& objectName = it->object.id;\n if (! fillPoseFromState(pose, objectName, numericalFluentCallback))\n {\n psi->removeObject(objectName);\n }\n else\n {\n movableObjects.insert(make_pair(objectName, pose));\n }\n }\n\n \/\/ find grasped objects and objects on tables\n PredicateList* predicates = NULL;\n if (!predicateCallback(predicates))\n {\n ROS_ERROR(\"%s predicateCallback failed.\", logName.c_str());\n return false;\n }\n ROS_ASSERT(predicates != NULL);\n for (PredicateList::iterator it = predicates->begin(); it != predicates->end(); it++)\n {\n Predicate p = *it;\n if (!p.value)\n continue;\n if (p.name == \"on\")\n {\n ROS_ASSERT(p.parameters.size() == 2);\n \/\/ (on movable static)\n objectsOnStatic.insert(make_pair(p.parameters.front().value, p.parameters.back().value));\n }\n else if (p.name == \"grasped\")\n {\n ROS_ASSERT(p.parameters.size() == 2);\n \/\/ (grasped object arm)\n graspedObjects.insert(make_pair(p.parameters.front().value, p.parameters.back().value));\n }\n else if (p.name == \"door-open\")\n {\n ROS_ASSERT(p.parameters.size() == 1);\n \/\/ (door-open door)\n openDoors.insert(p.parameters.front().value);\n }\n }\n\n \/\/ Robot pose\n if (! fillPoseFromState(robotPose, robotLocation, numericalFluentCallback))\n {\n ROS_ERROR(\"%s get robot location failed.\", logName.c_str());\n }\n return true;\n}\n\nbool TidyupPlanningSceneUpdater::update(const geometry_msgs::Pose& robotPose,\n const map<string, geometry_msgs::Pose>& movableObjects,\n const map<string, string>& graspedObjects,\n const set<string>& openDoors)\n{\n if (instance == NULL) instance = new TidyupPlanningSceneUpdater();\n return instance->update_(robotPose, movableObjects, graspedObjects, openDoors);\n}\n\nbool TidyupPlanningSceneUpdater::update_(const geometry_msgs::Pose& robotPose,\n const map<string, geometry_msgs::Pose>& movableObjects,\n const map<string, string>& graspedObjects,\n const set<string>& openDoors)\n{\n PlanningSceneInterface* psi = PlanningSceneInterface::instance();\n\/\/ psi->resetPlanningScene();\n\n \/\/ set robot state in planning scene\n ROS_INFO(\"%s update robot state in planning scene\", logName.c_str());\n arm_navigation_msgs::RobotState state = psi->getRobotState();\n state.multi_dof_joint_state.poses[0] = robotPose;\n ArmState::get(\"\/arm_configurations\/side_tuck\/position\/\", \"right_arm\").replaceJointPositions(state.joint_state);\n ArmState::get(\"\/arm_configurations\/side_tuck\/position\/\", \"left_arm\").replaceJointPositions(state.joint_state);\n\n \/\/ update pose of graspable object in the planning scene\n for(map<string, geometry_msgs::Pose>::const_iterator movabelObjectIt = movableObjects.begin(); movabelObjectIt != movableObjects.end(); movabelObjectIt++)\n {\n string object_name = movabelObjectIt->first;\n ROS_INFO(\"%s updating object %s\", logName.c_str(), object_name.c_str());\n \/\/ if this object is attached somewhere we need to detach it\n if (psi->getAttachedCollisionObject(object_name) != NULL)\n {\n psi->detachObjectAndAdd(object_name);\n }\n \/\/ object is not attached, update pose\n if (psi->getCollisionObject(object_name) != NULL)\n {\n psi->updateObject(object_name, movabelObjectIt->second);\n }\n else\n {\n ROS_ERROR(\"%s object %s does not exist in planning scene.\", logName.c_str(), object_name.c_str());\n return false;\n }\n }\n\n \/\/ attach putdown object to the correct arm\n\/\/ const arm_navigation_msgs::CollisionObject* object = psi->getCollisionObject(request.putdown_object);\n for (map<string, string>::const_iterator graspedIt = graspedObjects.begin(); graspedIt != graspedObjects.end(); graspedIt++)\n {\n const string& objectName = graspedIt->first;\n const string& arm = graspedIt->second;\n ROS_INFO(\"%s attaching object %s to arm %s\", logName.c_str(), objectName.c_str(), arm.c_str());\n ArmState::get(\"\/arm_configurations\/side_carry\/position\/\", arm).replaceJointPositions(state.joint_state);\n psi->attachObjectToGripper(objectName, arm);\n psi->updateObject(objectName, defaultAttachPose);\n }\n psi->setRobotState(state);\n\n \/\/ update doors\n for (map<string, Door>::const_iterator doorIt = doors.begin(); doorIt != doors.end(); doorIt++)\n {\n if (openDoors.find(doorIt->first) != openDoors.end())\n {\n \/\/ door is open\n psi->updateObject(doorIt->first, doorIt->second.openPose);\n }\n else\n {\n \/\/ door is closed\n psi->updateObject(doorIt->first, doorIt->second.closedPose);\n }\n }\n\n \/\/ send changes\n return psi->sendDiff();\n}\n\nbool TidyupPlanningSceneUpdater::fillPoseFromState(geometry_msgs::Pose& pose,\n const string& poseName,\n numericalFluentCallbackType numericalFluentCallback)\n{\n \/\/ create the numerical fluent request\n ParameterList startParams;\n startParams.push_back(Parameter(\"\", \"\", poseName));\n NumericalFluentList nfRequest;\n nfRequest.reserve(7);\n nfRequest.push_back(NumericalFluent(\"x\", startParams));\n nfRequest.push_back(NumericalFluent(\"y\", startParams));\n nfRequest.push_back(NumericalFluent(\"z\", startParams));\n nfRequest.push_back(NumericalFluent(\"qx\", startParams));\n nfRequest.push_back(NumericalFluent(\"qy\", startParams));\n nfRequest.push_back(NumericalFluent(\"qz\", startParams));\n nfRequest.push_back(NumericalFluent(\"qw\", startParams));\n\n \/\/ get the fluents\n NumericalFluentList* nfRequestP = &nfRequest;\n if (!numericalFluentCallback(nfRequestP))\n {\n ROS_ERROR(\"fillPoseFromState failed for object: %s\", poseName.c_str());\n return false;\n }\n\n \/\/ fill pose stamped\n pose.position.x = nfRequest[0].value;\n pose.position.y = nfRequest[1].value;\n pose.position.z = nfRequest[2].value;\n pose.orientation.x = nfRequest[3].value;\n pose.orientation.y = nfRequest[4].value;\n pose.orientation.z = nfRequest[5].value;\n pose.orientation.w = nfRequest[6].value;\n return true;\n}\n\nvoid TidyupPlanningSceneUpdater::loadDoorPoses(const string& doorLocationFileName)\n{\n GeometryPoses locations = GeometryPoses();\n ROS_ASSERT_MSG(locations.load(doorLocationFileName), \"Could not load locations from \\\"%s\\\".\", doorLocationFileName.c_str());\n const std::map<std::string, geometry_msgs::PoseStamped>& poses = locations.getPoses();\n for(std::map<std::string, geometry_msgs::PoseStamped>::const_iterator posesIterator = poses.begin(); posesIterator != poses.end(); posesIterator++)\n {\n string name = posesIterator->first;\n if (StringUtil::startsWith(name, \"door\"))\n {\n string doorName;\n bool open = false;\n if(StringUtil::endsWith(name, \"_closed\"))\n {\n doorName = name.substr(0, name.length()-7);\n }\n else if(StringUtil::endsWith(name, \"_open\"))\n {\n doorName = name.substr(0, name.length()-5);\n open = true;\n }\n else\n {\n ROS_ERROR(\"navstack planning scene: misformated door location entry %s in file %s\", name.c_str(), doorLocationFileName.c_str());\n continue;\n }\n map<string, Door>::iterator doorIterator = doors.find(doorName);\n if (doorIterator == doors.end())\n {\n doors.insert(make_pair(doorName, Door(doorName)));\n doorIterator = doors.find(doorName);\n }\n Door& door = doorIterator->second;\n if (open)\n {\n door.openPose = posesIterator->second.pose;\n }\n else\n {\n door.closedPose = posesIterator->second.pose;\n }\n }\n }\n}\n\n<commit_msg>reset planning scene before update<commit_after>\/*\n * tidyup_planning_scene_updater.cpp\n *\n * Created on: 10 Aug 2012\n * Author: andreas\n *\/\n\n#include \"planner_modules_pr2\/tidyup_planning_scene_updater.h\"\n#include <tidyup_utils\/planning_scene_interface.h>\n#include <tidyup_utils\/arm_state.h>\n#include <tidyup_utils\/stringutil.h>\n#include <hardcoded_facts\/geometryPoses.h>\n#include <ros\/ros.h>\n\nusing std::vector;\nusing std::map;\nusing std::set;\nusing std::string;\n\nTidyupPlanningSceneUpdater* TidyupPlanningSceneUpdater::instance = NULL;\n\nTidyupPlanningSceneUpdater::TidyupPlanningSceneUpdater() : logName(\"[psu]\")\n{\n string doorLocationFileName;\n ros::param::get(\"\/continual_planning_executive\/door_location_file\", doorLocationFileName);\n loadDoorPoses(doorLocationFileName);\n\n defaultAttachPose.position.x = 0.032;\n defaultAttachPose.position.y = 0.015;\n defaultAttachPose.position.z = 0.0;\n defaultAttachPose.orientation.x = 0.707;\n defaultAttachPose.orientation.y = -0.106;\n defaultAttachPose.orientation.z = -0.690;\n defaultAttachPose.orientation.w = 0.105;\n\n ROS_INFO(\"%s initialized.\\n\", logName.c_str());\n}\n\nTidyupPlanningSceneUpdater::~TidyupPlanningSceneUpdater()\n{\n}\n\nbool TidyupPlanningSceneUpdater::readState(\n const string& robotLocation,\n predicateCallbackType predicateCallback,\n numericalFluentCallbackType numericalFluentCallback,\n geometry_msgs::Pose& robotPose,\n map<string, geometry_msgs::Pose>& movableObjects,\n map<string, string>& graspedObjects,\n map<string, string>& objectsOnStatic,\n set<string>& openDoors)\n{\n if (instance == NULL) instance = new TidyupPlanningSceneUpdater();\n return instance->readState_(robotLocation, predicateCallback, numericalFluentCallback, robotPose, movableObjects, graspedObjects, objectsOnStatic, openDoors);\n}\n\nbool TidyupPlanningSceneUpdater::readState_(\n const string& robotLocation,\n predicateCallbackType predicateCallback,\n numericalFluentCallbackType numericalFluentCallback,\n geometry_msgs::Pose& robotPose,\n map<string, geometry_msgs::Pose>& movableObjects,\n map<string, string>& graspedObjects,\n map<string, string>& objectsOnStatic,\n set<string>& openDoors)\n{\n \/\/ get poses of all movable objects\n PlanningSceneInterface* psi = PlanningSceneInterface::instance();\n psi->resetPlanningScene();\n geometry_msgs::Pose pose;\n const vector <arm_navigation_msgs::CollisionObject>& collisionObjects = psi->getCollisionObjects();\n for (vector <arm_navigation_msgs::CollisionObject>::const_iterator it = collisionObjects.begin();\n it != collisionObjects.end(); it++)\n {\n const string& objectName = it->id;\n if (StringUtil::startsWith(objectName, \"table\"))\n continue;\n if (StringUtil::startsWith(objectName, \"door\"))\n continue;\n if (! fillPoseFromState(pose, objectName, numericalFluentCallback))\n {\n psi->removeObject(objectName);\n }\n else\n {\n movableObjects.insert(make_pair(objectName, pose));\n }\n }\n const vector <arm_navigation_msgs::AttachedCollisionObject>& attachedObjects = psi->getAttachedCollisionObjects();\n for (vector <arm_navigation_msgs::AttachedCollisionObject>::const_iterator it = attachedObjects.begin(); it != attachedObjects.end(); it++)\n {\n const string& objectName = it->object.id;\n if (! fillPoseFromState(pose, objectName, numericalFluentCallback))\n {\n psi->removeObject(objectName);\n }\n else\n {\n movableObjects.insert(make_pair(objectName, pose));\n }\n }\n\n \/\/ find grasped objects and objects on tables\n PredicateList* predicates = NULL;\n if (!predicateCallback(predicates))\n {\n ROS_ERROR(\"%s predicateCallback failed.\", logName.c_str());\n return false;\n }\n ROS_ASSERT(predicates != NULL);\n for (PredicateList::iterator it = predicates->begin(); it != predicates->end(); it++)\n {\n Predicate p = *it;\n if (!p.value)\n continue;\n if (p.name == \"on\")\n {\n ROS_ASSERT(p.parameters.size() == 2);\n \/\/ (on movable static)\n objectsOnStatic.insert(make_pair(p.parameters.front().value, p.parameters.back().value));\n }\n else if (p.name == \"grasped\")\n {\n ROS_ASSERT(p.parameters.size() == 2);\n \/\/ (grasped object arm)\n graspedObjects.insert(make_pair(p.parameters.front().value, p.parameters.back().value));\n }\n else if (p.name == \"door-open\")\n {\n ROS_ASSERT(p.parameters.size() == 1);\n \/\/ (door-open door)\n openDoors.insert(p.parameters.front().value);\n }\n }\n\n \/\/ Robot pose\n if (! fillPoseFromState(robotPose, robotLocation, numericalFluentCallback))\n {\n ROS_ERROR(\"%s get robot location failed.\", logName.c_str());\n }\n return true;\n}\n\nbool TidyupPlanningSceneUpdater::update(const geometry_msgs::Pose& robotPose,\n const map<string, geometry_msgs::Pose>& movableObjects,\n const map<string, string>& graspedObjects,\n const set<string>& openDoors)\n{\n if (instance == NULL) instance = new TidyupPlanningSceneUpdater();\n return instance->update_(robotPose, movableObjects, graspedObjects, openDoors);\n}\n\nbool TidyupPlanningSceneUpdater::update_(const geometry_msgs::Pose& robotPose,\n const map<string, geometry_msgs::Pose>& movableObjects,\n const map<string, string>& graspedObjects,\n const set<string>& openDoors)\n{\n PlanningSceneInterface* psi = PlanningSceneInterface::instance();\n\/\/ psi->resetPlanningScene();\n\n \/\/ set robot state in planning scene\n ROS_INFO(\"%s update robot state in planning scene\", logName.c_str());\n arm_navigation_msgs::RobotState state = psi->getRobotState();\n state.multi_dof_joint_state.poses[0] = robotPose;\n ArmState::get(\"\/arm_configurations\/side_tuck\/position\/\", \"right_arm\").replaceJointPositions(state.joint_state);\n ArmState::get(\"\/arm_configurations\/side_tuck\/position\/\", \"left_arm\").replaceJointPositions(state.joint_state);\n\n \/\/ update pose of graspable object in the planning scene\n for(map<string, geometry_msgs::Pose>::const_iterator movabelObjectIt = movableObjects.begin(); movabelObjectIt != movableObjects.end(); movabelObjectIt++)\n {\n string object_name = movabelObjectIt->first;\n ROS_INFO(\"%s updating object %s\", logName.c_str(), object_name.c_str());\n \/\/ if this object is attached somewhere we need to detach it\n if (psi->getAttachedCollisionObject(object_name) != NULL)\n {\n psi->detachObjectAndAdd(object_name);\n }\n \/\/ object is not attached, update pose\n if (psi->getCollisionObject(object_name) != NULL)\n {\n psi->updateObject(object_name, movabelObjectIt->second);\n }\n else\n {\n ROS_ERROR(\"%s object %s does not exist in planning scene.\", logName.c_str(), object_name.c_str());\n return false;\n }\n }\n\n \/\/ attach putdown object to the correct arm\n\/\/ const arm_navigation_msgs::CollisionObject* object = psi->getCollisionObject(request.putdown_object);\n for (map<string, string>::const_iterator graspedIt = graspedObjects.begin(); graspedIt != graspedObjects.end(); graspedIt++)\n {\n const string& objectName = graspedIt->first;\n const string& arm = graspedIt->second;\n ROS_INFO(\"%s attaching object %s to arm %s\", logName.c_str(), objectName.c_str(), arm.c_str());\n ArmState::get(\"\/arm_configurations\/side_carry\/position\/\", arm).replaceJointPositions(state.joint_state);\n psi->attachObjectToGripper(objectName, arm);\n psi->updateObject(objectName, defaultAttachPose);\n }\n psi->setRobotState(state);\n\n \/\/ update doors\n for (map<string, Door>::const_iterator doorIt = doors.begin(); doorIt != doors.end(); doorIt++)\n {\n if (openDoors.find(doorIt->first) != openDoors.end())\n {\n \/\/ door is open\n psi->updateObject(doorIt->first, doorIt->second.openPose);\n }\n else\n {\n \/\/ door is closed\n psi->updateObject(doorIt->first, doorIt->second.closedPose);\n }\n }\n\n \/\/ send changes\n return psi->sendDiff();\n}\n\nbool TidyupPlanningSceneUpdater::fillPoseFromState(geometry_msgs::Pose& pose,\n const string& poseName,\n numericalFluentCallbackType numericalFluentCallback)\n{\n \/\/ create the numerical fluent request\n ParameterList startParams;\n startParams.push_back(Parameter(\"\", \"\", poseName));\n NumericalFluentList nfRequest;\n nfRequest.reserve(7);\n nfRequest.push_back(NumericalFluent(\"x\", startParams));\n nfRequest.push_back(NumericalFluent(\"y\", startParams));\n nfRequest.push_back(NumericalFluent(\"z\", startParams));\n nfRequest.push_back(NumericalFluent(\"qx\", startParams));\n nfRequest.push_back(NumericalFluent(\"qy\", startParams));\n nfRequest.push_back(NumericalFluent(\"qz\", startParams));\n nfRequest.push_back(NumericalFluent(\"qw\", startParams));\n\n \/\/ get the fluents\n NumericalFluentList* nfRequestP = &nfRequest;\n if (!numericalFluentCallback(nfRequestP))\n {\n ROS_ERROR(\"fillPoseFromState failed for object: %s\", poseName.c_str());\n return false;\n }\n\n \/\/ fill pose stamped\n pose.position.x = nfRequest[0].value;\n pose.position.y = nfRequest[1].value;\n pose.position.z = nfRequest[2].value;\n pose.orientation.x = nfRequest[3].value;\n pose.orientation.y = nfRequest[4].value;\n pose.orientation.z = nfRequest[5].value;\n pose.orientation.w = nfRequest[6].value;\n return true;\n}\n\nvoid TidyupPlanningSceneUpdater::loadDoorPoses(const string& doorLocationFileName)\n{\n GeometryPoses locations = GeometryPoses();\n ROS_ASSERT_MSG(locations.load(doorLocationFileName), \"Could not load locations from \\\"%s\\\".\", doorLocationFileName.c_str());\n const std::map<std::string, geometry_msgs::PoseStamped>& poses = locations.getPoses();\n for(std::map<std::string, geometry_msgs::PoseStamped>::const_iterator posesIterator = poses.begin(); posesIterator != poses.end(); posesIterator++)\n {\n string name = posesIterator->first;\n if (StringUtil::startsWith(name, \"door\"))\n {\n string doorName;\n bool open = false;\n if(StringUtil::endsWith(name, \"_closed\"))\n {\n doorName = name.substr(0, name.length()-7);\n }\n else if(StringUtil::endsWith(name, \"_open\"))\n {\n doorName = name.substr(0, name.length()-5);\n open = true;\n }\n else\n {\n ROS_ERROR(\"navstack planning scene: misformated door location entry %s in file %s\", name.c_str(), doorLocationFileName.c_str());\n continue;\n }\n map<string, Door>::iterator doorIterator = doors.find(doorName);\n if (doorIterator == doors.end())\n {\n doors.insert(make_pair(doorName, Door(doorName)));\n doorIterator = doors.find(doorName);\n }\n Door& door = doorIterator->second;\n if (open)\n {\n door.openPose = posesIterator->second.pose;\n }\n else\n {\n door.closedPose = posesIterator->second.pose;\n }\n }\n }\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/* Lantern - A path tracer\n*\n* Lantern is the legal property of Adrian Astley\n* Copyright Adrian Astley 2015 - 2016\n*\/\n\n#include \"renderer\/renderer.h\"\n\n#include \"renderer\/surface_interaction.h\"\n\n#include \"scene\/scene.h\"\n#include \"scene\/ray.h\"\n\n#include \"bsdfs\/bsdf.h\"\n\n#include \"math\/uniform_sampler.h\"\n#include \"math\/vector_math.h\"\n#include \"math\/sampling.h\"\n\n#include <tbb\/parallel_for.h>\n\n#include <algorithm>\n\n\nnamespace Lantern {\n\nvoid Renderer::RenderFrame() {\n\tuint width = m_scene->Camera.FrameBuffer.Width;\n\tuint height = m_scene->Camera.FrameBuffer.Height;\n\n\tconst int numTilesX = (width + kTileSize - 1) \/ kTileSize;\n\tconst int numTilesY = (height + kTileSize - 1) \/ kTileSize;\n\n\ttbb::parallel_for(size_t(0), size_t(numTilesX * numTilesY), [=](size_t i) {\n\t\tRenderTile(i, width, height, numTilesX, numTilesY);\n\t});\n\n\t++m_frameNumber;\n}\n\n\/\/ MurmurHash3\ninline uint HashMix(uint hash, uint k) {\n\tconst uint c1 = 0xcc9e2d51;\n\tconst uint c2 = 0x1b873593;\n\tconst uint r1 = 15;\n\tconst uint r2 = 13;\n\tconst uint m = 5;\n\tconst uint n = 0xe6546b64;\n\n\tk *= c1;\n\tk = (k << r1) | (k >> (32 - r1));\n\tk *= c2;\n\n\thash ^= k;\n\thash = ((hash << r2) | (hash >> (32 - r2))) * m + n;\n\n\treturn hash;\n}\n\n\/\/ MurmurHash3\ninline uint HashFinalize(uint hash) {\n\thash ^= hash >> 16;\n\thash *= 0x85ebca6b;\n\thash ^= hash >> 13;\n\thash *= 0xc2b2ae35;\n\thash ^= hash >> 16;\n\n\treturn hash;\n}\n\nvoid Renderer::RenderTile(uint index, uint width, uint height, uint numTilesX, uint numTilesY) {\n\tuint tileY = index \/ numTilesX;\n\tuint tileX = index - tileY * numTilesX;\n\n\tuint x0 = tileX * kTileSize;\n\tuint x1 = std::min(x0 + kTileSize, width);\n\tuint y0 = tileY * kTileSize;\n\tuint y1 = std::min(y0 + kTileSize, height);\n\n\tuint hash = 0u;\n\thash = HashMix(hash, index);\n\thash = HashMix(hash, m_frameNumber);\n\thash = HashFinalize(hash);\n\t\n\tUniformSampler sampler(hash, m_frameNumber);\n\n\tfor (uint y = y0; y < y1; ++y) {\n\t\tfor (uint x = x0; x < x1; ++x) {\n\t\t\tRenderPixel(x, y, &sampler);\n\t\t}\n\t}\n}\n\nvoid Renderer::RenderPixel(uint x, uint y, UniformSampler *sampler) {\n\tRay ray = m_scene->Camera.CalculateRayFromPixel(x, y, sampler);\n\n\tfloat3 color(0.0f);\n\tfloat3 throughput(1.0f);\n\n\t\/\/ Bounce the ray around the scene\n\tfor (uint bounces = 0; bounces < 10; ++bounces) {\n\t\tm_scene->Intersect(ray);\n\n\t\t\/\/ The ray missed. Return the background color\n\t\tif (ray.GeomID == INVALID_GEOMETRY_ID) {\n\t\t\tcolor += throughput * m_scene->BackgroundColor;\n\t\t\tbreak;\n\t\t}\n\n\t\t\/\/ We hit an object\n\t\t\t\n\t\t\/\/ Fetch the bsdf\n\t\tBSDF *bsdf = m_scene->GetBSDF(ray.GeomID);\n\t\t\/\/ The object might be emissive. If so, it will have a corresponding light\n\t\t\/\/ Otherwise, GetLight will return nullptr\n\t\tLight *light = m_scene->GetLight(ray.GeomID);\n\n\t\t\/\/ If this is the first bounce or if we just had a specular bounce,\n\t\t\/\/ we need to add the emmisive light\n\t\tif (bounces == 0 && light != nullptr) {\n\t\t\tcolor += throughput * light->Le();\n\t\t}\n\n\t\tSurfaceInteraction interaction;\n\t\tinteraction.Position = ray.Origin + ray.Direction * ray.TFar;\n\t\tinteraction.Normal = normalize(ray.GeomNormal);\n\t\tinteraction.OutputDirection = normalize(-ray.Direction);\n\t\t\n\n\t\t\/\/ Calculate the direct lighting\n\t\tcolor += throughput * SampleOneLight(sampler, interaction, bsdf, light);\n\n\t\t\/\/ Get the new ray direction\n\t\t\/\/ Choose the direction based on the bsdf\n\t\tbsdf->Sample(interaction, sampler);\n\t\tfloat pdf = bsdf->Pdf(interaction);\n\n\t\t\/\/ Accumulate the diffuse\/specular weight\n\t\tthroughput = throughput * bsdf->Eval(interaction) \/ pdf;\n\n\t\t\/\/ Russian Roulette\n\t\tif (bounces > 3) {\n\t\t\tfloat p = std::max(throughput.x, std::max(throughput.y, throughput.z));\n\t\t\tif (sampler->NextFloat() > p) {\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tthroughput *= 1 \/ p;\n\t\t}\n\n\t\t\/\/ Shoot a new ray\n\n\t\t\/\/ Set the origin at the intersection point\n\t\tray.Origin = interaction.Position;\n\n\t\t\/\/ Reset the other ray properties\n\t\tray.Direction = interaction.InputDirection;\n\t\tray.TNear = 0.001f;\n\t\tray.TFar = infinity;\n\t\tray.GeomID = INVALID_GEOMETRY_ID;\n\t\tray.PrimID = INVALID_PRIMATIVE_ID;\n\t\tray.InstID = INVALID_INSTANCE_ID;\n\t\tray.Mask = 0xFFFFFFFF;\n\t\tray.Time = 0.0f;\n\t}\n\n\tm_scene->Camera.FrameBuffer.SplatPixel(x, y, color);\n}\n\nfloat3 Renderer::SampleOneLight(UniformSampler *sampler, SurfaceInteraction interaction, BSDF *bsdf, Light *hitLight) const {\n\tstd::size_t numLights = m_scene->NumLights();\n\t\n\t\/\/ Return black if there are no lights\n\t\/\/ And don't let a light contribute light to itself\n\t\/\/ Aka, if we hit a light\n\t\/\/ This is the special case where there is only 1 light\n\tif (numLights == 0 || numLights == 1 && hitLight != nullptr) {\n\t\treturn float3(0.0f);\n\t}\n\n\t\/\/ Don't let a light contribute light to itself\n\t\/\/ Choose another one\n\tLight *light;\n\tdo {\n\t\tlight = m_scene->RandomOneLight(sampler);\n\t} while (light == hitLight);\n\n\treturn numLights * EstimateDirect(light, sampler, interaction, bsdf);\n}\n\nfloat3 Renderer::EstimateDirect(Light *light, UniformSampler *sampler, SurfaceInteraction &interaction, BSDF *bsdf) const {\n\tfloat3 directLighting = float3(0.0f);\n\tfloat3 f;\n\tfloat lightPdf, scatteringPdf;\n\n\n\t\/\/ Sample lighting with multiple importance sampling\n\n\tfloat3 Li = light->SampleLi(sampler, m_scene, interaction, &lightPdf);\n\n\t\/\/ Make sure the pdf isn't zero and the radiance isn't black\n\tif (lightPdf != 0.0f && !all(Li)) {\n\t\t\/\/ Calculate the brdf value\n\t\tf = bsdf->Eval(interaction);\n\t\tscatteringPdf = bsdf->Pdf(interaction);\n\n\t\tif (scatteringPdf != 0.0f && !all(f)) {\n\t\t\tfloat weight = PowerHeuristic(1, lightPdf, 1, scatteringPdf);\n\t\t\tdirectLighting += f * Li * weight \/ lightPdf;\n\t\t}\n\t}\n\n\n\t\/\/ Sample brdf with multiple importance sampling\n\n\tbsdf->Sample(interaction, sampler);\n\tf = bsdf->Eval(interaction);\n\tscatteringPdf = bsdf->Pdf(interaction);\n\tif (scatteringPdf != 0.0f && !all(f)) {\n\t\tlightPdf = light->PdfLi(m_scene, interaction);\n\t\tif (lightPdf == 0.0f) {\n\t\t\t\/\/ We didn't hit anything, so ignore the brdf sample\n\t\t\treturn directLighting;\n\t\t}\n\n\t\tfloat weight = PowerHeuristic(1, scatteringPdf, 1, lightPdf);\n\t\tLi = light->Le();\n\t\tdirectLighting += f * Li * weight \/ scatteringPdf;\n\t}\n\n\treturn directLighting;\n}\n\n\n} \/\/ End of namespace Lantern\n<commit_msg>RenderTile and RenderPixel are const<commit_after>\/* Lantern - A path tracer\n*\n* Lantern is the legal property of Adrian Astley\n* Copyright Adrian Astley 2015 - 2016\n*\/\n\n#include \"renderer\/renderer.h\"\n\n#include \"renderer\/surface_interaction.h\"\n\n#include \"scene\/scene.h\"\n#include \"scene\/ray.h\"\n\n#include \"bsdfs\/bsdf.h\"\n\n#include \"math\/uniform_sampler.h\"\n#include \"math\/vector_math.h\"\n#include \"math\/sampling.h\"\n\n#include <tbb\/parallel_for.h>\n\n#include <algorithm>\n\n\nnamespace Lantern {\n\nvoid Renderer::RenderFrame() {\n\tuint width = m_scene->Camera.FrameBuffer.Width;\n\tuint height = m_scene->Camera.FrameBuffer.Height;\n\n\tconst int numTilesX = (width + kTileSize - 1) \/ kTileSize;\n\tconst int numTilesY = (height + kTileSize - 1) \/ kTileSize;\n\n\ttbb::parallel_for(size_t(0), size_t(numTilesX * numTilesY), [=](size_t i) {\n\t\tRenderTile(i, width, height, numTilesX, numTilesY);\n\t});\n\n\t++m_frameNumber;\n}\n\n\/\/ MurmurHash3\ninline uint HashMix(uint hash, uint k) {\n\tconst uint c1 = 0xcc9e2d51;\n\tconst uint c2 = 0x1b873593;\n\tconst uint r1 = 15;\n\tconst uint r2 = 13;\n\tconst uint m = 5;\n\tconst uint n = 0xe6546b64;\n\n\tk *= c1;\n\tk = (k << r1) | (k >> (32 - r1));\n\tk *= c2;\n\n\thash ^= k;\n\thash = ((hash << r2) | (hash >> (32 - r2))) * m + n;\n\n\treturn hash;\n}\n\n\/\/ MurmurHash3\ninline uint HashFinalize(uint hash) {\n\thash ^= hash >> 16;\n\thash *= 0x85ebca6b;\n\thash ^= hash >> 13;\n\thash *= 0xc2b2ae35;\n\thash ^= hash >> 16;\n\n\treturn hash;\n}\n\nvoid Renderer::RenderTile(uint index, uint width, uint height, uint numTilesX, uint numTilesY) const {\n\tuint tileY = index \/ numTilesX;\n\tuint tileX = index - tileY * numTilesX;\n\n\tuint x0 = tileX * kTileSize;\n\tuint x1 = std::min(x0 + kTileSize, width);\n\tuint y0 = tileY * kTileSize;\n\tuint y1 = std::min(y0 + kTileSize, height);\n\n\tuint hash = 0u;\n\thash = HashMix(hash, index);\n\thash = HashMix(hash, m_frameNumber);\n\thash = HashFinalize(hash);\n\t\n\tUniformSampler sampler(hash, m_frameNumber);\n\n\tfor (uint y = y0; y < y1; ++y) {\n\t\tfor (uint x = x0; x < x1; ++x) {\n\t\t\tRenderPixel(x, y, &sampler);\n\t\t}\n\t}\n}\n\nvoid Renderer::RenderPixel(uint x, uint y, UniformSampler *sampler) const {\n\tRay ray = m_scene->Camera.CalculateRayFromPixel(x, y, sampler);\n\n\tfloat3 color(0.0f);\n\tfloat3 throughput(1.0f);\n\n\t\/\/ Bounce the ray around the scene\n\tfor (uint bounces = 0; bounces < 10; ++bounces) {\n\t\tm_scene->Intersect(ray);\n\n\t\t\/\/ The ray missed. Return the background color\n\t\tif (ray.GeomID == INVALID_GEOMETRY_ID) {\n\t\t\tcolor += throughput * m_scene->BackgroundColor;\n\t\t\tbreak;\n\t\t}\n\n\t\t\/\/ We hit an object\n\t\t\t\n\t\t\/\/ Fetch the bsdf\n\t\tBSDF *bsdf = m_scene->GetBSDF(ray.GeomID);\n\t\t\/\/ The object might be emissive. If so, it will have a corresponding light\n\t\t\/\/ Otherwise, GetLight will return nullptr\n\t\tLight *light = m_scene->GetLight(ray.GeomID);\n\n\t\t\/\/ If this is the first bounce or if we just had a specular bounce,\n\t\t\/\/ we need to add the emmisive light\n\t\tif (bounces == 0 && light != nullptr) {\n\t\t\tcolor += throughput * light->Le();\n\t\t}\n\n\t\tSurfaceInteraction interaction;\n\t\tinteraction.Position = ray.Origin + ray.Direction * ray.TFar;\n\t\tinteraction.Normal = normalize(ray.GeomNormal);\n\t\tinteraction.OutputDirection = normalize(-ray.Direction);\n\t\t\n\n\t\t\/\/ Calculate the direct lighting\n\t\tcolor += throughput * SampleOneLight(sampler, interaction, bsdf, light);\n\n\t\t\/\/ Get the new ray direction\n\t\t\/\/ Choose the direction based on the bsdf\n\t\tbsdf->Sample(interaction, sampler);\n\t\tfloat pdf = bsdf->Pdf(interaction);\n\n\t\t\/\/ Accumulate the diffuse\/specular weight\n\t\tthroughput = throughput * bsdf->Eval(interaction) \/ pdf;\n\n\t\t\/\/ Russian Roulette\n\t\tif (bounces > 3) {\n\t\t\tfloat p = std::max(throughput.x, std::max(throughput.y, throughput.z));\n\t\t\tif (sampler->NextFloat() > p) {\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tthroughput *= 1 \/ p;\n\t\t}\n\n\t\t\/\/ Shoot a new ray\n\n\t\t\/\/ Set the origin at the intersection point\n\t\tray.Origin = interaction.Position;\n\n\t\t\/\/ Reset the other ray properties\n\t\tray.Direction = interaction.InputDirection;\n\t\tray.TNear = 0.001f;\n\t\tray.TFar = infinity;\n\t\tray.GeomID = INVALID_GEOMETRY_ID;\n\t\tray.PrimID = INVALID_PRIMATIVE_ID;\n\t\tray.InstID = INVALID_INSTANCE_ID;\n\t\tray.Mask = 0xFFFFFFFF;\n\t\tray.Time = 0.0f;\n\t}\n\n\tm_scene->Camera.FrameBuffer.SplatPixel(x, y, color);\n}\n\nfloat3 Renderer::SampleOneLight(UniformSampler *sampler, SurfaceInteraction interaction, BSDF *bsdf, Light *hitLight) const {\n\tstd::size_t numLights = m_scene->NumLights();\n\t\n\t\/\/ Return black if there are no lights\n\t\/\/ And don't let a light contribute light to itself\n\t\/\/ Aka, if we hit a light\n\t\/\/ This is the special case where there is only 1 light\n\tif (numLights == 0 || numLights == 1 && hitLight != nullptr) {\n\t\treturn float3(0.0f);\n\t}\n\n\t\/\/ Don't let a light contribute light to itself\n\t\/\/ Choose another one\n\tLight *light;\n\tdo {\n\t\tlight = m_scene->RandomOneLight(sampler);\n\t} while (light == hitLight);\n\n\treturn numLights * EstimateDirect(light, sampler, interaction, bsdf);\n}\n\nfloat3 Renderer::EstimateDirect(Light *light, UniformSampler *sampler, SurfaceInteraction &interaction, BSDF *bsdf) const {\n\tfloat3 directLighting = float3(0.0f);\n\tfloat3 f;\n\tfloat lightPdf, scatteringPdf;\n\n\n\t\/\/ Sample lighting with multiple importance sampling\n\n\tfloat3 Li = light->SampleLi(sampler, m_scene, interaction, &lightPdf);\n\n\t\/\/ Make sure the pdf isn't zero and the radiance isn't black\n\tif (lightPdf != 0.0f && !all(Li)) {\n\t\t\/\/ Calculate the brdf value\n\t\tf = bsdf->Eval(interaction);\n\t\tscatteringPdf = bsdf->Pdf(interaction);\n\n\t\tif (scatteringPdf != 0.0f && !all(f)) {\n\t\t\tfloat weight = PowerHeuristic(1, lightPdf, 1, scatteringPdf);\n\t\t\tdirectLighting += f * Li * weight \/ lightPdf;\n\t\t}\n\t}\n\n\n\t\/\/ Sample brdf with multiple importance sampling\n\n\tbsdf->Sample(interaction, sampler);\n\tf = bsdf->Eval(interaction);\n\tscatteringPdf = bsdf->Pdf(interaction);\n\tif (scatteringPdf != 0.0f && !all(f)) {\n\t\tlightPdf = light->PdfLi(m_scene, interaction);\n\t\tif (lightPdf == 0.0f) {\n\t\t\t\/\/ We didn't hit anything, so ignore the brdf sample\n\t\t\treturn directLighting;\n\t\t}\n\n\t\tfloat weight = PowerHeuristic(1, scatteringPdf, 1, lightPdf);\n\t\tLi = light->Le();\n\t\tdirectLighting += f * Li * weight \/ scatteringPdf;\n\t}\n\n\treturn directLighting;\n}\n\n\n} \/\/ End of namespace Lantern\n<|endoftext|>"} {"text":"<commit_before>#include <rviz_helper\/kr_marker.hpp>\n#include <rviz_helper\/viz_manager.hpp>\n\nnamespace kr {\nnamespace viz {\n\n\/\/ \/\/ \/\/ \/\/ \/\/ \/\/ \/\/ KR Marker \/\/ \/\/ \/\/ \/\/ \/\/ \/\/ \/\/ \/\/ \/\/ \/\/ \/\/ \/\/ \/\/ \/\/ \/\/\n\nint Marker::getUniqueId() {\n static int id = 0;\n return id++;\n}\n\nMarker::Marker() {\n \/\/ set default values\n mark_.color.a = 1.0;\n mark_.color.r = kr::viz::colors::FUCHSIA.r_;\n mark_.color.g = kr::viz::colors::FUCHSIA.g_;\n mark_.color.b = kr::viz::colors::FUCHSIA.b_;\n\n mark_.pose.orientation.w = 1;\n mark_.ns = \"viz\";\n mark_.header.frame_id = \"world\";\n mark_.id = getUniqueId();\n mark_.action = visualization_msgs::Marker::ADD;\n\n mark_.scale.x = 1.0;\n mark_.scale.y = 1.0;\n mark_.scale.z = 1.0;\n\n mark_.type = visualization_msgs::Marker::SPHERE;\n mark_.header.stamp = ros::Time::now();\n}\n\n\/\/ Implementations\nMarker &Marker::color(const std_msgs::ColorRGBA &col) {\n mark_.color = col;\n return *this;\n}\nMarker &Marker::color(const rviz::Color &col) {\n mark_.color.r = col.r_;\n mark_.color.b = col.b_;\n mark_.color.g = col.g_;\n return *this;\n}\nMarker &Marker::scale(const geometry_msgs::Vector3 &sca) {\n mark_.scale = sca;\n return *this;\n}\nMarker &Marker::scale(double x, double y, double z) {\n mark_.scale.x = x;\n mark_.scale.y = y;\n mark_.scale.z = z;\n return *this;\n}\nMarker &Marker::position(const geometry_msgs::Point pose) {\n mark_.pose.position = pose;\n return *this;\n}\nMarker &Marker::scale(double s) { return scale(s, s, s); }\nMarker &Marker::alpha(double a) {\n mark_.color.a = a;\n return *this;\n}\n\nMarkerArray MarkerArray::operator+(const MarkerArray &array) {\n for (auto &mark : array.array_) array_.push_back(mark);\n return *this;\n}\nMarkerArray MarkerArray::operator+(const Marker &mark) {\n array_.push_back(mark);\n return *this;\n}\nMarkerArray MarkerArray::operator+=(const MarkerArray &array) {\n for (auto &mark : array.array_) array_.push_back(mark);\n return *this;\n}\nMarkerArray MarkerArray::operator+=(const Marker &marker) {\n array_.push_back(marker);\n return *this;\n}\n\/\/ \/\/ \/\/ \/\/ \/\/ \/\/ \/\/ Viz Manager \/\/ \/\/ \/\/ \/\/ \/\/ \/\/ \/\/ \/\/ \/\/ \/\/ \/\/ \/\/ \/\/ \/\/ \/\/\n\nVizManager::VizManager() : nh_(\"\"), nh_priv_(\"~\") {}\nVizManager &VizManager::instance() {\n static VizManager man;\n return man;\n}\nMarkerPubHandle::MarkerPubHandle(const std::string &topic)\n : manager_(VizManager::instance()), pub_(manager_.getPublisher(topic)) {}\nros::Publisher &VizManager::getPublisher(const std::string &topic) {\n auto element = publishers_.find(topic);\n if (element == publishers_.end()) {\n publishers_[topic] = nh_priv_.advertise<visualization_msgs::MarkerArray>(\n topic.c_str(), 10, this);\n return publishers_[topic];\n } else {\n return element->second;\n }\n}\nMarker::operator visualization_msgs::MarkerArray() {\n MarkerArray array;\n array.push_back(*this);\n return array;\n}\nMarkerArray::operator visualization_msgs::MarkerArray() {\n visualization_msgs::MarkerArray array;\n for (auto &mark : array_) array.markers.push_back(mark);\n return array;\n}\nvoid MarkerArray::push_back(const Marker &mark) { array_.push_back(mark); }\nMarkerArray::MarkerArray() {}\nMarker &Marker::mesh(const std::string &resource) {\n mark_.mesh_resource = resource;\n mark_.type = visualization_msgs::Marker::MESH_RESOURCE;\n return *this;\n}\nMarker &Marker::type(int32_t tp) {\n mark_.type = tp;\n return *this;\n}\nMarker &Marker::point_push_back(const geometry_msgs::Point &pt) {\n mark_.points.push_back(pt);\n return *this;\n}\nMarker &Marker::action(u_int8_t a) {\n mark_.action = a;\n return *this;\n}\n\nMarkerArray::MarkerArray(double lx, double ly, double lz, double ux, double uy,\n double uz, rviz::Color col) {\n kr::viz::Marker mark_lines;\n kr::viz::Marker mark_points;\n\n geometry_msgs::Point p000;\n geometry_msgs::Point p001;\n geometry_msgs::Point p010;\n geometry_msgs::Point p011;\n geometry_msgs::Point p100;\n geometry_msgs::Point p101;\n geometry_msgs::Point p110;\n geometry_msgs::Point p111;\n\n p000.x = lx;\n p000.y = ly;\n p000.z = lz;\n p001.x = lx;\n p001.y = ly;\n p001.z = uz;\n p010.x = lx;\n p010.y = uy;\n p010.z = lz;\n p011.x = lx;\n p011.y = uy;\n p011.z = uz;\n p100.x = ux;\n p100.y = ly;\n p100.z = lz;\n p101.x = ux;\n p101.y = ly;\n p101.z = uz;\n p110.x = ux;\n p110.y = uy;\n p110.z = lz;\n p111.x = ux;\n p111.y = uy;\n p111.z = uz;\n\n \/\/ edges\n mark_lines.type(visualization_msgs::Marker::LINE_LIST).color(col);\n mark_lines.point_push_back(p000);\n mark_lines.point_push_back(p001);\n mark_lines.point_push_back(p000);\n mark_lines.point_push_back(p010);\n mark_lines.point_push_back(p000);\n mark_lines.point_push_back(p100);\n\n mark_lines.point_push_back(p001);\n mark_lines.point_push_back(p101);\n mark_lines.point_push_back(p001);\n mark_lines.point_push_back(p011);\n\n mark_lines.point_push_back(p010);\n mark_lines.point_push_back(p110);\n mark_lines.point_push_back(p010);\n mark_lines.point_push_back(p011);\n\n mark_lines.point_push_back(p100);\n mark_lines.point_push_back(p110);\n mark_lines.point_push_back(p100);\n mark_lines.point_push_back(p101);\n\n mark_lines.point_push_back(p011);\n mark_lines.point_push_back(p111);\n mark_lines.point_push_back(p101);\n mark_lines.point_push_back(p111);\n mark_lines.point_push_back(p110);\n mark_lines.point_push_back(p111);\n\n \/\/ corners\n mark_points.type(visualization_msgs::Marker::SPHERE_LIST).color(col);\n mark_points.point_push_back(p000);\n mark_points.point_push_back(p001);\n mark_points.point_push_back(p010);\n mark_points.point_push_back(p011);\n mark_points.point_push_back(p100);\n mark_points.point_push_back(p101);\n mark_points.point_push_back(p110);\n mark_points.point_push_back(p111);\n\n mark_lines.scale(0.1);\n mark_points.scale(0.1);\n\n array_.push_back(mark_lines);\n array_.push_back(mark_points);\n}\n\n\/\/ batch opperations\nvoid MarkerArray::push_back(const MarkerArray &ma) {\n for(uint i = 0 ; i < ma.size(); i++)\n array_.push_back(ma.at(i));\n}\n\nMarkerArray &MarkerArray::color(const rviz::Color &col) {\n for (auto &mark : array_) mark.color(col);\n return *this;\n}\nMarkerArray &MarkerArray::color(const std_msgs::ColorRGBA &col) {\n for (auto &mark : array_) mark.color(col);\n return *this;\n}\nMarkerArray &MarkerArray::scale(const geometry_msgs::Vector3 &sca) {\n for (auto &mark : array_) mark.scale(sca);\n return *this;\n}\nMarkerArray &MarkerArray::scale(double x, double y, double z) {\n for (auto &mark : array_) mark.scale(x, y, z);\n return *this;\n}\nMarkerArray &MarkerArray::scale(double s) {\n for (auto &mark : array_) mark.scale(s);\n return *this;\n}\nMarkerArray &MarkerArray::mesh(const std::string &resource) {\n for (auto &mark : array_) mark.mesh(resource);\n return *this;\n}\nMarkerArray &MarkerArray::type(int32_t tp) {\n for (auto &mark : array_) mark.type(tp);\n return *this;\n}\nMarkerArray &MarkerArray::point_push_back(const geometry_msgs::Point &pt) {\n for (auto &mark : array_) mark.point_push_back(pt);\n return *this;\n}\nMarkerArray &MarkerArray::position(const geometry_msgs::Point pose) {\n for (auto &mark : array_) mark.position(pose);\n return *this;\n}\nMarkerArray &MarkerArray::alpha(double a) {\n for (auto &mark : array_) mark.alpha(a);\n return *this;\n}\nMarkerArray &MarkerArray::action(u_int8_t a) {\n for (auto &mark : array_) mark.action(a);\n return *this;\n}\n\nconst Marker & MarkerArray::at(int pos) const {\n return array_.at(pos);\n}\nMarker & MarkerArray::at(int pos){\n return array_.at(pos);\n}\n\n} \/\/ namespace viz\n} \/\/ namespace kr\n<commit_msg>added missing implementation<commit_after>#include <rviz_helper\/kr_marker.hpp>\n#include <rviz_helper\/viz_manager.hpp>\n\nnamespace kr {\nnamespace viz {\n\n\/\/ \/\/ \/\/ \/\/ \/\/ \/\/ \/\/ KR Marker \/\/ \/\/ \/\/ \/\/ \/\/ \/\/ \/\/ \/\/ \/\/ \/\/ \/\/ \/\/ \/\/ \/\/ \/\/\n\nint Marker::getUniqueId() {\n static int id = 0;\n return id++;\n}\n\nMarker::Marker() {\n \/\/ set default values\n mark_.color.a = 1.0;\n mark_.color.r = kr::viz::colors::FUCHSIA.r_;\n mark_.color.g = kr::viz::colors::FUCHSIA.g_;\n mark_.color.b = kr::viz::colors::FUCHSIA.b_;\n\n mark_.pose.orientation.w = 1;\n mark_.ns = \"viz\";\n mark_.header.frame_id = \"world\";\n mark_.id = getUniqueId();\n mark_.action = visualization_msgs::Marker::ADD;\n\n mark_.scale.x = 1.0;\n mark_.scale.y = 1.0;\n mark_.scale.z = 1.0;\n\n mark_.type = visualization_msgs::Marker::SPHERE;\n mark_.header.stamp = ros::Time::now();\n}\n\n\/\/ Implementations\nMarker &Marker::color(const std_msgs::ColorRGBA &col) {\n mark_.color = col;\n return *this;\n}\nMarker &Marker::color(const rviz::Color &col) {\n mark_.color.r = col.r_;\n mark_.color.b = col.b_;\n mark_.color.g = col.g_;\n return *this;\n}\nMarker &Marker::scale(const geometry_msgs::Vector3 &sca) {\n mark_.scale = sca;\n return *this;\n}\nMarker &Marker::scale(double x, double y, double z) {\n mark_.scale.x = x;\n mark_.scale.y = y;\n mark_.scale.z = z;\n return *this;\n}\nMarker &Marker::position(const geometry_msgs::Point pose) {\n mark_.pose.position = pose;\n return *this;\n}\nMarker &Marker::scale(double s) { return scale(s, s, s); }\nMarker &Marker::alpha(double a) {\n mark_.color.a = a;\n return *this;\n}\n\nMarkerArray MarkerArray::operator+(const MarkerArray &array) {\n for (auto &mark : array.array_) array_.push_back(mark);\n return *this;\n}\nMarkerArray MarkerArray::operator+(const Marker &mark) {\n array_.push_back(mark);\n return *this;\n}\nMarkerArray MarkerArray::operator+=(const MarkerArray &array) {\n for (auto &mark : array.array_) array_.push_back(mark);\n return *this;\n}\nMarkerArray MarkerArray::operator+=(const Marker &marker) {\n array_.push_back(marker);\n return *this;\n}\n\/\/ \/\/ \/\/ \/\/ \/\/ \/\/ \/\/ Viz Manager \/\/ \/\/ \/\/ \/\/ \/\/ \/\/ \/\/ \/\/ \/\/ \/\/ \/\/ \/\/ \/\/ \/\/ \/\/\n\nVizManager::VizManager() : nh_(\"\"), nh_priv_(\"~\") {}\nVizManager &VizManager::instance() {\n static VizManager man;\n return man;\n}\nMarkerPubHandle::MarkerPubHandle(const std::string &topic)\n : manager_(VizManager::instance()), pub_(manager_.getPublisher(topic)) {}\nros::Publisher &VizManager::getPublisher(const std::string &topic) {\n auto element = publishers_.find(topic);\n if (element == publishers_.end()) {\n publishers_[topic] = nh_priv_.advertise<visualization_msgs::MarkerArray>(\n topic.c_str(), 10, this);\n return publishers_[topic];\n } else {\n return element->second;\n }\n}\nMarker::operator visualization_msgs::MarkerArray() {\n MarkerArray array;\n array.push_back(*this);\n return array;\n}\nMarkerArray::operator visualization_msgs::MarkerArray() {\n visualization_msgs::MarkerArray array;\n for (auto &mark : array_) array.markers.push_back(mark);\n return array;\n}\nvoid MarkerArray::push_back(const Marker &mark) { array_.push_back(mark); }\nMarkerArray::MarkerArray() {}\nMarker &Marker::mesh(const std::string &resource) {\n mark_.mesh_resource = resource;\n mark_.type = visualization_msgs::Marker::MESH_RESOURCE;\n return *this;\n}\nMarker &Marker::type(int32_t tp) {\n mark_.type = tp;\n return *this;\n}\nMarker &Marker::point_push_back(const geometry_msgs::Point &pt) {\n mark_.points.push_back(pt);\n return *this;\n}\nMarker &Marker::action(u_int8_t a) {\n mark_.action = a;\n return *this;\n}\n\nMarkerArray::MarkerArray(double lx, double ly, double lz, double ux, double uy,\n double uz, rviz::Color col) {\n kr::viz::Marker mark_lines;\n kr::viz::Marker mark_points;\n\n geometry_msgs::Point p000;\n geometry_msgs::Point p001;\n geometry_msgs::Point p010;\n geometry_msgs::Point p011;\n geometry_msgs::Point p100;\n geometry_msgs::Point p101;\n geometry_msgs::Point p110;\n geometry_msgs::Point p111;\n\n p000.x = lx;\n p000.y = ly;\n p000.z = lz;\n p001.x = lx;\n p001.y = ly;\n p001.z = uz;\n p010.x = lx;\n p010.y = uy;\n p010.z = lz;\n p011.x = lx;\n p011.y = uy;\n p011.z = uz;\n p100.x = ux;\n p100.y = ly;\n p100.z = lz;\n p101.x = ux;\n p101.y = ly;\n p101.z = uz;\n p110.x = ux;\n p110.y = uy;\n p110.z = lz;\n p111.x = ux;\n p111.y = uy;\n p111.z = uz;\n\n \/\/ edges\n mark_lines.type(visualization_msgs::Marker::LINE_LIST).color(col);\n mark_lines.point_push_back(p000);\n mark_lines.point_push_back(p001);\n mark_lines.point_push_back(p000);\n mark_lines.point_push_back(p010);\n mark_lines.point_push_back(p000);\n mark_lines.point_push_back(p100);\n\n mark_lines.point_push_back(p001);\n mark_lines.point_push_back(p101);\n mark_lines.point_push_back(p001);\n mark_lines.point_push_back(p011);\n\n mark_lines.point_push_back(p010);\n mark_lines.point_push_back(p110);\n mark_lines.point_push_back(p010);\n mark_lines.point_push_back(p011);\n\n mark_lines.point_push_back(p100);\n mark_lines.point_push_back(p110);\n mark_lines.point_push_back(p100);\n mark_lines.point_push_back(p101);\n\n mark_lines.point_push_back(p011);\n mark_lines.point_push_back(p111);\n mark_lines.point_push_back(p101);\n mark_lines.point_push_back(p111);\n mark_lines.point_push_back(p110);\n mark_lines.point_push_back(p111);\n\n \/\/ corners\n mark_points.type(visualization_msgs::Marker::SPHERE_LIST).color(col);\n mark_points.point_push_back(p000);\n mark_points.point_push_back(p001);\n mark_points.point_push_back(p010);\n mark_points.point_push_back(p011);\n mark_points.point_push_back(p100);\n mark_points.point_push_back(p101);\n mark_points.point_push_back(p110);\n mark_points.point_push_back(p111);\n\n mark_lines.scale(0.1);\n mark_points.scale(0.1);\n\n array_.push_back(mark_lines);\n array_.push_back(mark_points);\n}\nMarkerArray::MarkerArray(const visualization_msgs::MarkerArray &array) {\n for(auto &mark:array.markers)\n array_.push_back(mark);\n}\n\n\/\/ batch opperations\nvoid MarkerArray::push_back(const MarkerArray &ma) {\n for(uint i = 0 ; i < ma.size(); i++)\n array_.push_back(ma.at(i));\n}\n\nMarkerArray &MarkerArray::color(const rviz::Color &col) {\n for (auto &mark : array_) mark.color(col);\n return *this;\n}\nMarkerArray &MarkerArray::color(const std_msgs::ColorRGBA &col) {\n for (auto &mark : array_) mark.color(col);\n return *this;\n}\nMarkerArray &MarkerArray::scale(const geometry_msgs::Vector3 &sca) {\n for (auto &mark : array_) mark.scale(sca);\n return *this;\n}\nMarkerArray &MarkerArray::scale(double x, double y, double z) {\n for (auto &mark : array_) mark.scale(x, y, z);\n return *this;\n}\nMarkerArray &MarkerArray::scale(double s) {\n for (auto &mark : array_) mark.scale(s);\n return *this;\n}\nMarkerArray &MarkerArray::mesh(const std::string &resource) {\n for (auto &mark : array_) mark.mesh(resource);\n return *this;\n}\nMarkerArray &MarkerArray::type(int32_t tp) {\n for (auto &mark : array_) mark.type(tp);\n return *this;\n}\nMarkerArray &MarkerArray::point_push_back(const geometry_msgs::Point &pt) {\n for (auto &mark : array_) mark.point_push_back(pt);\n return *this;\n}\nMarkerArray &MarkerArray::position(const geometry_msgs::Point pose) {\n for (auto &mark : array_) mark.position(pose);\n return *this;\n}\nMarkerArray &MarkerArray::alpha(double a) {\n for (auto &mark : array_) mark.alpha(a);\n return *this;\n}\nMarkerArray &MarkerArray::action(u_int8_t a) {\n for (auto &mark : array_) mark.action(a);\n return *this;\n}\n\nconst Marker & MarkerArray::at(int pos) const {\n return array_.at(pos);\n}\nMarker & MarkerArray::at(int pos){\n return array_.at(pos);\n}\n\n} \/\/ namespace viz\n} \/\/ namespace kr\n<|endoftext|>"} {"text":"<commit_before>#include \"file.h\"\n#include \"string.h\"\n#include <algorithm>\n#include <cstdio>\n#include <cstring>\n#include <fstream>\n#include <memory>\n#include <stdexcept>\n#include <string>\n\n#if defined(WIN32) || defined(_WIN32) || defined(__WIN32) && !defined(__CYGWIN__)\n#define PLATFORM_WINDOWS\n#endif\n\n#ifdef PLATFORM_WINDOWS\n#include <direct.h>\n#include <shlwapi.h>\n#include <windows.h>\n#else\n#include <fcntl.h>\n#include <stdlib.h>\n#include <sys\/stat.h>\n#include <unistd.h>\n#endif\n\n#ifdef PLATFORM_WINDOWS\n\/\/ This is the only module that requires windows character conversion\n\nstd::string to_string(const wchar_t* str = L\"\")\n{\n if (!str) {\n str = L\"\";\n }\n auto length = WideCharToMultiByte(CP_UTF8, 0, str, -1, nullptr, 0, nullptr, nullptr);\n std::unique_ptr<char[]> buffer(new char[length + 1]);\n WideCharToMultiByte(CP_UTF8, 0, str, -1, buffer.get(), length, nullptr, nullptr);\n\n return std::string(buffer.get());\n}\n\n\/\/ use unique_ptr to prevent memory leak with exceptions.\ninline std::unique_ptr<wchar_t[]> to_wchar(const std::string str)\n{\n auto length = MultiByteToWideChar(CP_UTF8, 0, str.c_str(), -1, nullptr, 0);\n std::unique_ptr<wchar_t[]> buffer(new wchar_t[length + 1]);\n MultiByteToWideChar(CP_UTF8, 0, str.c_str(), -1, buffer.get(), length);\n\n return std::move(buffer);\n}\n#endif\n\nusing namespace UnTech;\n\nstd::string File::readUtf8TextFile(const std::string& filename)\n{\n std::ifstream in(filename, std::ios::in | std::ios::binary);\n if (in) {\n uint8_t bom[3];\n in.read((char*)bom, sizeof(bom));\n\n in.seekg(0, std::ios::end);\n size_t size = in.tellg();\n\n \/\/ check for BOM\n if (size > 3 && bom[0] == 0xEF && bom[1] == 0xBB && bom[2] == 0xBF) {\n in.seekg(3, std::ios::beg);\n size -= 3;\n }\n else {\n in.seekg(0, std::ios::beg);\n }\n\n std::string ret;\n ret.reserve(size + 1);\n\n ret.assign((std::istreambuf_iterator<char>(in)), (std::istreambuf_iterator<char>()));\n\n in.close();\n\n if (!String::checkUtf8WellFormed(ret)) {\n throw std::runtime_error(\"File is not UTF-8 Well Formed\");\n }\n\n return (ret);\n }\n throw std::runtime_error(\"Cannot open file\");\n}\n\nstd::pair<std::string, std::string> File::splitFilename(const std::string& filename)\n{\n if (filename.empty()) {\n return { std::string(), std::string() };\n }\n\n#ifdef PLATFORM_WINDOWS\n \/\/ search both types of slash in windows.\n auto i = filename.find_last_of(\"\\\\\/\");\n#else\n auto i = filename.find_last_of('\/');\n#endif\n\n if (i == std::string::npos) {\n return { std::string(), filename };\n }\n else {\n return { filename.substr(0, i + 1), filename.substr(i + 1) };\n }\n}\n\nstd::string File::cwd()\n{\n#ifdef PLATFORM_WINDOWS\n wchar_t wpath[PATH_MAX] = L\"\";\n\n if (!_wgetcwd(wpath, PATH_MAX)) {\n throw std::runtime_error(\"Error getting working directory\");\n }\n\n return to_string(wpath);\n\n#else\n char* dir = get_current_dir_name();\n\n if (dir) {\n std::string ret(dir);\n free(dir);\n return ret;\n }\n else {\n throw std::runtime_error(\"Error with path\");\n }\n#endif\n}\n\nstd::string File::cleanPath(const std::string& path)\n{\n if (path.empty()) {\n return path;\n }\n\n#ifdef PLATFORM_WINDOWS\n const char SEP = '\\\\';\n\n std::string newPath = path;\n std::replace(newPath.begin(), newPath.end(), '\/', '\\\\');\n\n const char* source = newPath.c_str();\n\n#else\n const char SEP = '\/';\n\n const char* source = path.c_str();\n#endif\n\n char ret[path.length() + 1];\n\n char* pos = ret;\n char* dirs[path.length() \/ 2];\n size_t nDirs = 0;\n\n while (*source != 0) {\n \/\/ Start of a directory\/file\n\n if (source[0] == '.' && source[1] == SEP) {\n \/\/ ignore all . directories\n source += 2;\n }\n\n else if (source[0] == '.' && source[1] == '.' && source[2] == SEP) {\n if (nDirs > 1) {\n \/\/ shift pos to previous directory\n\n pos = dirs[nDirs - 2];\n nDirs--;\n source += 3;\n }\n else {\n pos[0] = source[0];\n pos[1] = source[1];\n pos[2] = source[2];\n pos += 3;\n source += 3;\n }\n }\n\n else {\n \/\/ loop until end of directory separator\n\n while (*source != 0 && *source != SEP) {\n *(pos++) = *(source++);\n }\n\n \/\/ include terminator ('\/' or '\\0').\n *(pos++) = *(source++);\n\n if (*(source - 1) == 0) {\n break;\n }\n else if (*(source - 1) == SEP) {\n \/\/ remember previous dir position\n dirs[nDirs] = pos;\n nDirs++;\n }\n }\n\n#ifndef PLATFORM_WINDOWS\n \/\/ ignore duplicate separators\n while (*source == SEP) {\n source++;\n }\n#endif\n }\n\n return std::string(ret);\n}\n\nstd::string File::joinPath(const std::string& dir, const std::string& path)\n{\n#ifdef PLATFORM_WINDOWS\n auto wdir = to_wchar(dir);\n auto wpath = to_wchar(path);\n wchar_t wjoined[PATH_MAX] = L\"\";\n\n PathCombineW(wjoined, wdir.get(), wpath.get());\n\n return to_string(wjoined);\n\n#else\n if (path.front() == '\/') {\n return path;\n }\n\n std::string join;\n join.reserve(dir.length() + path.length() + 1);\n\n if (!dir.empty() && dir.back() != '\/') {\n join = dir + '\/' + path;\n }\n else {\n join = dir + path;\n }\n\n return cleanPath(join);\n#endif\n}\n\nstd::string File::fullPath(const std::string& path)\n{\n#ifdef PLATFORM_WINDOWS\n wchar_t wfullpath[PATH_MAX] = L\"\";\n auto wpath = to_wchar(path);\n\n if (!_wfullpath(wfullpath, wpath.get(), PATH_MAX)) {\n throw std::runtime_error(\"Error expanding path\");\n }\n\n return to_string(wfullpath);\n\n#else\n if (path.front() == '\/') {\n return path;\n }\n\n return joinPath(cwd(), path);\n#endif\n}\n\nstd::string File::relativePath(const std::string& sourceDir, const std::string& destPath)\n{\n if (sourceDir.empty()) {\n return File::fullPath(destPath);\n }\n\n#ifdef PLATFORM_WINDOWS\n wchar_t wrelpath[PATH_MAX] = L\"\";\n auto wsource = to_wchar(sourceDir);\n auto wdest = to_wchar(destPath);\n\n if (!PathRelativePathToW(wrelpath, wsource.get(), FILE_ATTRIBUTE_DIRECTORY, wdest.get(), FILE_ATTRIBUTE_NORMAL)) {\n throw std::runtime_error(\"Error expanding path\");\n }\n\n return to_string(wrelpath);\n\n#else\n std::string source = File::fullPath(sourceDir);\n std::string dest = File::fullPath(destPath);\n\n if (source.empty() || dest.empty()\n || source.front() != '\/' || dest.front() != '\/') {\n\n return dest;\n }\n\n std::string ret;\n\n \/\/ Get common root directories\n size_t lastCommonSep = 0;\n {\n size_t i = 0;\n while (i < source.size() && i < dest.size() && source[i] == dest[i]) {\n if (source[i] == '\/') {\n lastCommonSep = i;\n }\n i++;\n }\n\n if (i == source.size() && dest.size() > source.size() && dest[i] == '\/') {\n lastCommonSep = i;\n }\n }\n\n if (source.size() > lastCommonSep) {\n size_t p = lastCommonSep + 1;\n\n while ((p = source.find('\/', p)) != std::string::npos) {\n ret += \"..\/\";\n p += 1;\n }\n }\n\n ret += dest.substr(lastCommonSep + 1);\n\n return ret;\n#endif\n}\n\n#ifdef PLATFORM_WINDOWS\nvoid File::atomicWrite(const std::string& filename, const void* data, size_t size)\n{\n const size_t BLOCK_SIZE = 4096;\n\n \/\/ atomically creating a tempfile name is hard\n \/\/ just simplify it by using a ~ temp file instead.\n auto tmpFilename = to_wchar(filename + \"~\");\n\n \/\/ open file normally.\n \/\/ error out if file exists.\n HANDLE hFile = CreateFileW(tmpFilename.get(), GENERIC_WRITE, 0, nullptr,\n CREATE_NEW, FILE_ATTRIBUTE_NORMAL, nullptr);\n\n if (hFile == INVALID_HANDLE_VALUE) {\n if (GetLastError() == ERROR_FILE_EXISTS) {\n throw std::runtime_error(\"Temporary file already exists: \" + filename + \"~\");\n }\n else {\n throw std::runtime_error(\"Cannot open temporary file \" + filename + \"~\");\n }\n }\n\n const uint8_t* ptr = static_cast<const uint8_t*>(data);\n size_t todo = size;\n\n while (todo > 0) {\n DWORD toWrite = std::min(BLOCK_SIZE, todo);\n DWORD written = 0;\n\n auto ret = WriteFile(hFile, ptr, toWrite, &written, NULL);\n\n if (ret == FALSE || written != toWrite) {\n CloseHandle(hFile);\n throw std::runtime_error(\"Error writing file\");\n }\n\n ptr += toWrite;\n todo -= toWrite;\n }\n\n CloseHandle(hFile);\n\n auto wFilename = to_wchar(filename);\n bool s = MoveFileExW(tmpFilename.get(), wFilename.get(),\n MOVEFILE_REPLACE_EXISTING | MOVEFILE_COPY_ALLOWED);\n if (!s) {\n throw std::runtime_error(\"MoveFileEx failed\");\n }\n}\n#else\nvoid File::atomicWrite(const std::string& filename, const void* data, size_t size)\n{\n const size_t BLOCK_SIZE = 4096;\n\n int fd;\n char tmpFilename[filename.size() + 12];\n strncpy(tmpFilename, filename.c_str(), filename.size() + 1);\n strncpy(tmpFilename + filename.size(), \"-tmpXXXXXX\", 12);\n\n struct stat statbuf;\n if (stat(filename.c_str(), &statbuf) == 0) {\n if (S_ISLNK(statbuf.st_mode)) {\n throw std::runtime_error(\"Cannot write to a symbolic link\");\n }\n\n \/\/ check if we can write to file\n bool canWrite = ((getuid() == statbuf.st_uid) && (statbuf.st_mode & S_IWUSR))\n || ((getgid() == statbuf.st_gid) && (statbuf.st_mode & S_IWGRP))\n || (statbuf.st_mode & S_IWOTH);\n if (!canWrite) {\n throw std::runtime_error(\"User can not write to \" + filename);\n }\n\n fd = mkostemp(tmpFilename, O_WRONLY);\n if (fd < 0) {\n throw std::system_error(errno, std::system_category());\n }\n\n \/\/ mkostemp sets file permission to 0600\n \/\/ Set the permissions to match filename\n chmod(tmpFilename, statbuf.st_mode);\n chown(tmpFilename, statbuf.st_uid, statbuf.st_gid);\n }\n else {\n fd = mkostemp(tmpFilename, O_WRONLY);\n if (fd < 0) {\n throw std::system_error(errno, std::system_category());\n }\n\n \/\/ mkostemp sets file permission to 0600\n \/\/ Set the permissions what user would expect\n mode_t mask = umask(0);\n umask(mask);\n chmod(tmpFilename, 0666 & ~mask);\n }\n\n const uint8_t* ptr = static_cast<const uint8_t*>(data);\n size_t todo = size;\n ssize_t done;\n\n while (todo > 0) {\n done = ::write(fd, ptr, std::min(BLOCK_SIZE, todo));\n if (done < 0) {\n auto err = errno;\n close(fd);\n throw std::system_error(err, std::system_category());\n }\n\n ptr += done;\n todo -= done;\n }\n\n int r;\n r = close(fd);\n if (r != 0) {\n throw std::system_error(errno, std::system_category());\n }\n\n r = rename(tmpFilename, filename.c_str());\n if (r != 0) {\n throw std::system_error(errno, std::system_category());\n }\n}\n#endif\n<commit_msg>fix: make File::relativePath consistent between windows\/unix<commit_after>#include \"file.h\"\n#include \"string.h\"\n#include <algorithm>\n#include <cstdio>\n#include <cstring>\n#include <fstream>\n#include <memory>\n#include <stdexcept>\n#include <string>\n\n#if defined(WIN32) || defined(_WIN32) || defined(__WIN32) && !defined(__CYGWIN__)\n#define PLATFORM_WINDOWS\n#endif\n\n#ifdef PLATFORM_WINDOWS\n#include <direct.h>\n#include <shlwapi.h>\n#include <windows.h>\n#else\n#include <fcntl.h>\n#include <stdlib.h>\n#include <sys\/stat.h>\n#include <unistd.h>\n#endif\n\n#ifdef PLATFORM_WINDOWS\n\/\/ This is the only module that requires windows character conversion\n\nstd::string to_string(const wchar_t* str = L\"\")\n{\n if (!str) {\n str = L\"\";\n }\n auto length = WideCharToMultiByte(CP_UTF8, 0, str, -1, nullptr, 0, nullptr, nullptr);\n std::unique_ptr<char[]> buffer(new char[length + 1]);\n WideCharToMultiByte(CP_UTF8, 0, str, -1, buffer.get(), length, nullptr, nullptr);\n\n return std::string(buffer.get());\n}\n\n\/\/ use unique_ptr to prevent memory leak with exceptions.\ninline std::unique_ptr<wchar_t[]> to_wchar(const std::string str)\n{\n auto length = MultiByteToWideChar(CP_UTF8, 0, str.c_str(), -1, nullptr, 0);\n std::unique_ptr<wchar_t[]> buffer(new wchar_t[length + 1]);\n MultiByteToWideChar(CP_UTF8, 0, str.c_str(), -1, buffer.get(), length);\n\n return std::move(buffer);\n}\n#endif\n\nusing namespace UnTech;\n\nstd::string File::readUtf8TextFile(const std::string& filename)\n{\n std::ifstream in(filename, std::ios::in | std::ios::binary);\n if (in) {\n uint8_t bom[3];\n in.read((char*)bom, sizeof(bom));\n\n in.seekg(0, std::ios::end);\n size_t size = in.tellg();\n\n \/\/ check for BOM\n if (size > 3 && bom[0] == 0xEF && bom[1] == 0xBB && bom[2] == 0xBF) {\n in.seekg(3, std::ios::beg);\n size -= 3;\n }\n else {\n in.seekg(0, std::ios::beg);\n }\n\n std::string ret;\n ret.reserve(size + 1);\n\n ret.assign((std::istreambuf_iterator<char>(in)), (std::istreambuf_iterator<char>()));\n\n in.close();\n\n if (!String::checkUtf8WellFormed(ret)) {\n throw std::runtime_error(\"File is not UTF-8 Well Formed\");\n }\n\n return (ret);\n }\n throw std::runtime_error(\"Cannot open file\");\n}\n\nstd::pair<std::string, std::string> File::splitFilename(const std::string& filename)\n{\n if (filename.empty()) {\n return { std::string(), std::string() };\n }\n\n#ifdef PLATFORM_WINDOWS\n \/\/ search both types of slash in windows.\n auto i = filename.find_last_of(\"\\\\\/\");\n#else\n auto i = filename.find_last_of('\/');\n#endif\n\n if (i == std::string::npos) {\n return { std::string(), filename };\n }\n else {\n return { filename.substr(0, i + 1), filename.substr(i + 1) };\n }\n}\n\nstd::string File::cwd()\n{\n#ifdef PLATFORM_WINDOWS\n wchar_t wpath[PATH_MAX] = L\"\";\n\n if (!_wgetcwd(wpath, PATH_MAX)) {\n throw std::runtime_error(\"Error getting working directory\");\n }\n\n return to_string(wpath);\n\n#else\n char* dir = get_current_dir_name();\n\n if (dir) {\n std::string ret(dir);\n free(dir);\n return ret;\n }\n else {\n throw std::runtime_error(\"Error with path\");\n }\n#endif\n}\n\nstd::string File::cleanPath(const std::string& path)\n{\n if (path.empty()) {\n return path;\n }\n\n#ifdef PLATFORM_WINDOWS\n const char SEP = '\\\\';\n\n std::string newPath = path;\n std::replace(newPath.begin(), newPath.end(), '\/', '\\\\');\n\n const char* source = newPath.c_str();\n\n#else\n const char SEP = '\/';\n\n const char* source = path.c_str();\n#endif\n\n char ret[path.length() + 1];\n\n char* pos = ret;\n char* dirs[path.length() \/ 2];\n size_t nDirs = 0;\n\n while (*source != 0) {\n \/\/ Start of a directory\/file\n\n if (source[0] == '.' && source[1] == SEP) {\n \/\/ ignore all . directories\n source += 2;\n }\n\n else if (source[0] == '.' && source[1] == '.' && source[2] == SEP) {\n if (nDirs > 1) {\n \/\/ shift pos to previous directory\n\n pos = dirs[nDirs - 2];\n nDirs--;\n source += 3;\n }\n else {\n pos[0] = source[0];\n pos[1] = source[1];\n pos[2] = source[2];\n pos += 3;\n source += 3;\n }\n }\n\n else {\n \/\/ loop until end of directory separator\n\n while (*source != 0 && *source != SEP) {\n *(pos++) = *(source++);\n }\n\n \/\/ include terminator ('\/' or '\\0').\n *(pos++) = *(source++);\n\n if (*(source - 1) == 0) {\n break;\n }\n else if (*(source - 1) == SEP) {\n \/\/ remember previous dir position\n dirs[nDirs] = pos;\n nDirs++;\n }\n }\n\n#ifndef PLATFORM_WINDOWS\n \/\/ ignore duplicate separators\n while (*source == SEP) {\n source++;\n }\n#endif\n }\n\n return std::string(ret);\n}\n\nstd::string File::joinPath(const std::string& dir, const std::string& path)\n{\n#ifdef PLATFORM_WINDOWS\n auto wdir = to_wchar(dir);\n auto wpath = to_wchar(path);\n wchar_t wjoined[PATH_MAX] = L\"\";\n\n PathCombineW(wjoined, wdir.get(), wpath.get());\n\n return to_string(wjoined);\n\n#else\n if (path.front() == '\/') {\n return path;\n }\n\n std::string join;\n join.reserve(dir.length() + path.length() + 1);\n\n if (!dir.empty() && dir.back() != '\/') {\n join = dir + '\/' + path;\n }\n else {\n join = dir + path;\n }\n\n return cleanPath(join);\n#endif\n}\n\nstd::string File::fullPath(const std::string& path)\n{\n#ifdef PLATFORM_WINDOWS\n wchar_t wfullpath[PATH_MAX] = L\"\";\n auto wpath = to_wchar(path);\n\n if (!_wfullpath(wfullpath, wpath.get(), PATH_MAX)) {\n throw std::runtime_error(\"Error expanding path\");\n }\n\n return to_string(wfullpath);\n\n#else\n if (path.front() == '\/') {\n return path;\n }\n\n return joinPath(cwd(), path);\n#endif\n}\n\nstd::string File::relativePath(const std::string& sourceDir, const std::string& destPath)\n{\n if (sourceDir.empty()) {\n return File::fullPath(destPath);\n }\n\n#ifdef PLATFORM_WINDOWS\n wchar_t wrelpath[PATH_MAX] = L\"\";\n auto wsource = to_wchar(sourceDir);\n auto wdest = to_wchar(destPath);\n\n if (!PathRelativePathToW(wrelpath, wsource.get(), FILE_ATTRIBUTE_DIRECTORY, wdest.get(), FILE_ATTRIBUTE_NORMAL)) {\n return File::fullPath(destPath);\n }\n\n if (wrelpath[0] != L'\\\\') {\n return to_string(wrelpath);\n }\n else {\n return to_string(wrelpath + 1);\n }\n\n#else\n\n std::string source = File::fullPath(sourceDir);\n std::string dest = File::fullPath(destPath);\n\n if (source.empty() || dest.empty()\n || source.front() != '\/' || dest.front() != '\/') {\n\n return dest;\n }\n\n std::string ret;\n\n \/\/ Get common root directories\n size_t lastCommonSep = 0;\n {\n size_t i = 0;\n while (i < source.size() && i < dest.size() && source[i] == dest[i]) {\n if (source[i] == '\/') {\n lastCommonSep = i;\n }\n i++;\n }\n\n if (i == source.size() && dest.size() > source.size() && dest[i] == '\/') {\n lastCommonSep = i;\n }\n }\n\n if (source.size() > lastCommonSep) {\n size_t p = lastCommonSep + 1;\n\n while ((p = source.find('\/', p)) != std::string::npos) {\n ret += \"..\/\";\n p += 1;\n }\n }\n\n ret += dest.substr(lastCommonSep + 1);\n\n return ret;\n#endif\n}\n\n#ifdef PLATFORM_WINDOWS\nvoid File::atomicWrite(const std::string& filename, const void* data, size_t size)\n{\n const size_t BLOCK_SIZE = 4096;\n\n \/\/ atomically creating a tempfile name is hard\n \/\/ just simplify it by using a ~ temp file instead.\n auto tmpFilename = to_wchar(filename + \"~\");\n\n \/\/ open file normally.\n \/\/ error out if file exists.\n HANDLE hFile = CreateFileW(tmpFilename.get(), GENERIC_WRITE, 0, nullptr,\n CREATE_NEW, FILE_ATTRIBUTE_NORMAL, nullptr);\n\n if (hFile == INVALID_HANDLE_VALUE) {\n if (GetLastError() == ERROR_FILE_EXISTS) {\n throw std::runtime_error(\"Temporary file already exists: \" + filename + \"~\");\n }\n else {\n throw std::runtime_error(\"Cannot open temporary file \" + filename + \"~\");\n }\n }\n\n const uint8_t* ptr = static_cast<const uint8_t*>(data);\n size_t todo = size;\n\n while (todo > 0) {\n DWORD toWrite = std::min(BLOCK_SIZE, todo);\n DWORD written = 0;\n\n auto ret = WriteFile(hFile, ptr, toWrite, &written, NULL);\n\n if (ret == FALSE || written != toWrite) {\n CloseHandle(hFile);\n throw std::runtime_error(\"Error writing file\");\n }\n\n ptr += toWrite;\n todo -= toWrite;\n }\n\n CloseHandle(hFile);\n\n auto wFilename = to_wchar(filename);\n bool s = MoveFileExW(tmpFilename.get(), wFilename.get(),\n MOVEFILE_REPLACE_EXISTING | MOVEFILE_COPY_ALLOWED);\n if (!s) {\n throw std::runtime_error(\"MoveFileEx failed\");\n }\n}\n#else\nvoid File::atomicWrite(const std::string& filename, const void* data, size_t size)\n{\n const size_t BLOCK_SIZE = 4096;\n\n int fd;\n char tmpFilename[filename.size() + 12];\n strncpy(tmpFilename, filename.c_str(), filename.size() + 1);\n strncpy(tmpFilename + filename.size(), \"-tmpXXXXXX\", 12);\n\n struct stat statbuf;\n if (stat(filename.c_str(), &statbuf) == 0) {\n if (S_ISLNK(statbuf.st_mode)) {\n throw std::runtime_error(\"Cannot write to a symbolic link\");\n }\n\n \/\/ check if we can write to file\n bool canWrite = ((getuid() == statbuf.st_uid) && (statbuf.st_mode & S_IWUSR))\n || ((getgid() == statbuf.st_gid) && (statbuf.st_mode & S_IWGRP))\n || (statbuf.st_mode & S_IWOTH);\n if (!canWrite) {\n throw std::runtime_error(\"User can not write to \" + filename);\n }\n\n fd = mkostemp(tmpFilename, O_WRONLY);\n if (fd < 0) {\n throw std::system_error(errno, std::system_category());\n }\n\n \/\/ mkostemp sets file permission to 0600\n \/\/ Set the permissions to match filename\n chmod(tmpFilename, statbuf.st_mode);\n chown(tmpFilename, statbuf.st_uid, statbuf.st_gid);\n }\n else {\n fd = mkostemp(tmpFilename, O_WRONLY);\n if (fd < 0) {\n throw std::system_error(errno, std::system_category());\n }\n\n \/\/ mkostemp sets file permission to 0600\n \/\/ Set the permissions what user would expect\n mode_t mask = umask(0);\n umask(mask);\n chmod(tmpFilename, 0666 & ~mask);\n }\n\n const uint8_t* ptr = static_cast<const uint8_t*>(data);\n size_t todo = size;\n ssize_t done;\n\n while (todo > 0) {\n done = ::write(fd, ptr, std::min(BLOCK_SIZE, todo));\n if (done < 0) {\n auto err = errno;\n close(fd);\n throw std::system_error(err, std::system_category());\n }\n\n ptr += done;\n todo -= done;\n }\n\n int r;\n r = close(fd);\n if (r != 0) {\n throw std::system_error(errno, std::system_category());\n }\n\n r = rename(tmpFilename, filename.c_str());\n if (r != 0) {\n throw std::system_error(errno, std::system_category());\n }\n}\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ JustInTime.hpp\n\/\/ Clock Signal\n\/\/\n\/\/ Created by Thomas Harte on 28\/07\/2019.\n\/\/ Copyright © 2019 Thomas Harte. All rights reserved.\n\/\/\n\n#ifndef JustInTime_h\n#define JustInTime_h\n\n#include \"..\/Concurrency\/AsyncTaskQueue.hpp\"\n#include \"ClockingHintSource.hpp\"\n#include \"ForceInline.hpp\"\n\n\/*!\n\tA JustInTimeActor holds (i) an embedded object with a run_for method; and (ii) an amount\n\tof time since run_for was last called.\n\n\tTime can be added using the += operator. The -> operator can be used to access the\n\tembedded object. All time accumulated will be pushed to object before the pointer is returned.\n\n\tMachines that accumulate HalfCycle time but supply to a Cycle-counted device may supply a\n\tseparate @c TargetTimeScale at template declaration.\n\n\tIf the held object implements get_next_sequence_point() then it'll be used to flush implicitly\n\tas and when sequence points are hit. Callers can use will_flush() to predict these.\n\n\tIf the held object is a subclass of ClockingHint::Source, this template will register as an\n\tobserver and potentially stop clocking or stop delaying clocking until just-in-time references\n\tas directed.\n*\/\ntemplate <class T, int multiplier = 1, int divider = 1, class LocalTimeScale = HalfCycles, class TargetTimeScale = LocalTimeScale> class JustInTimeActor:\n\tpublic ClockingHint::Observer {\n\tprivate:\n\t\tclass SequencePointAwareDeleter {\n\t\t\tpublic:\n\t\t\t\texplicit SequencePointAwareDeleter(JustInTimeActor<T, multiplier, divider, LocalTimeScale, TargetTimeScale> *actor) : actor_(actor) {}\n\n\t\t\t\tvoid operator ()(const T *const) const {\n\t\t\t\t\tif constexpr (has_sequence_points<T>::value) {\n\t\t\t\t\t\tactor_->update_sequence_point();\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\tprivate:\n\t\t\t\tJustInTimeActor<T, multiplier, divider, LocalTimeScale, TargetTimeScale> *const actor_;\n\t\t};\n\n\tpublic:\n\t\t\/\/\/ Constructs a new JustInTimeActor using the same construction arguments as the included object.\n\t\ttemplate<typename... Args> JustInTimeActor(Args&&... args) : object_(std::forward<Args>(args)...) {\n\t\t\tif constexpr (std::is_base_of<ClockingHint::Source, T>::value) {\n\t\t\t\tobject_.set_clocking_hint_observer(this);\n\t\t\t}\n\t\t}\n\n\t\t\/\/\/ Adds time to the actor.\n\t\tforceinline void operator += (LocalTimeScale rhs) {\n\t\t\tif constexpr (std::is_base_of<ClockingHint::Source, T>::value) {\n\t\t\t\tif(clocking_preference_ == ClockingHint::Preference::None) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif constexpr (multiplier != 1) {\n\t\t\t\ttime_since_update_ += rhs * multiplier;\n\t\t\t} else {\n\t\t\t\ttime_since_update_ += rhs;\n\t\t\t}\n\t\t\tis_flushed_ = false;\n\n\t\t\tif constexpr (std::is_base_of<ClockingHint::Source, T>::value) {\n\t\t\t\tif (clocking_preference_ == ClockingHint::Preference::RealTime) {\n\t\t\t\t\tflush();\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif constexpr (has_sequence_points<T>::value) {\n\t\t\t\ttime_until_event_ -= rhs;\n\t\t\t\tif(time_until_event_ <= LocalTimeScale(0)) {\n\t\t\t\t\tflush();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t\/\/\/ Flushes all accumulated time and returns a pointer to the included object.\n\t\t\/\/\/\n\t\t\/\/\/ If this object provides sequence points, checks for changes to the next\n\t\t\/\/\/ sequence point upon deletion of the pointer.\n\t\tforceinline auto operator->() {\n\t\t\tflush();\n\t\t\treturn std::unique_ptr<T, SequencePointAwareDeleter>(&object_, SequencePointAwareDeleter(this));\n\t\t}\n\n\t\t\/\/\/ Acts exactly as per the standard ->, but preserves constness.\n\t\t\/\/\/\n\t\t\/\/\/ Despite being const, this will flush the object and, if relevant, update the next sequence point.\n\t\tforceinline auto operator -> () const {\n\t\t\tauto non_const_this = const_cast<JustInTimeActor<T, multiplier, divider, LocalTimeScale, TargetTimeScale> *>(this);\n\t\t\tnon_const_this->flush();\n\t\t\treturn std::unique_ptr<const T, SequencePointAwareDeleter>(&object_, SequencePointAwareDeleter(non_const_this));\n\t\t}\n\n\t\t\/\/\/ @returns a pointer to the included object, without flushing time.\n\t\tforceinline T *last_valid() {\n\t\t\treturn &object_;\n\t\t}\n\n\t\t\/\/\/ @returns the amount of time since the object was last flushed, in the target time scale.\n\t\tforceinline TargetTimeScale time_since_flush() const {\n\t\t\t\/\/ TODO: does this handle conversions properly where TargetTimeScale != LocalTimeScale?\n\t\t\tif constexpr (divider == 1) {\n\t\t\t\treturn time_since_update_;\n\t\t\t}\n\t\t\treturn TargetTimeScale(time_since_update_.as_integral() \/ divider);\n\t\t}\n\n\t\t\/\/\/ Flushes all accumulated time.\n\t\t\/\/\/\n\t\t\/\/\/ This does not affect this actor's record of when the next sequence point will occur.\n\t\tforceinline void flush() {\n\t\t\tif(!is_flushed_) {\n\t\t\t\tdid_flush_ = is_flushed_ = true;\n\t\t\t\tif constexpr (divider == 1) {\n\t\t\t\t\tconst auto duration = time_since_update_.template flush<TargetTimeScale>();\n\t\t\t\t\tobject_.run_for(duration);\n\t\t\t\t} else {\n\t\t\t\t\tconst auto duration = time_since_update_.template divide<TargetTimeScale>(LocalTimeScale(divider));\n\t\t\t\t\tif(duration > TargetTimeScale(0))\n\t\t\t\t\t\tobject_.run_for(duration);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t\/\/\/ Indicates whether a flush has occurred since the last call to did_flush().\n\t\tforceinline bool did_flush() {\n\t\t\tconst bool did_flush = did_flush_;\n\t\t\tdid_flush_ = false;\n\t\t\treturn did_flush;\n\t\t}\n\n\t\t\/\/\/ @returns the number of cycles until the next sequence-point-based flush, if the embedded object\n\t\t\/\/\/ supports sequence points; @c LocalTimeScale() otherwise.\n\t\tLocalTimeScale cycles_until_implicit_flush() const {\n\t\t\treturn time_until_event_;\n\t\t}\n\n\t\t\/\/\/ Indicates whether a sequence-point-caused flush will occur if the specified period is added.\n\t\tforceinline bool will_flush(LocalTimeScale rhs) const {\n\t\t\tif constexpr (!has_sequence_points<T>::value) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\treturn rhs >= time_until_event_;\n\t\t}\n\n\t\t\/\/\/ Updates this template's record of the next sequence point.\n\t\tvoid update_sequence_point() {\n\t\t\tif constexpr (has_sequence_points<T>::value) {\n\t\t\t\ttime_until_event_ = object_.get_next_sequence_point();\n\t\t\t\tassert(time_until_event_ > LocalTimeScale(0));\n\t\t\t}\n\t\t}\n\n\tprivate:\n\t\tT object_;\n\t\tLocalTimeScale time_since_update_, time_until_event_;\n\t\tbool is_flushed_ = true;\n\t\tbool did_flush_ = false;\n\n\t\ttemplate <typename S, typename = void> struct has_sequence_points : std::false_type {};\n\t\ttemplate <typename S> struct has_sequence_points<S, decltype(void(std::declval<S &>().get_next_sequence_point()))> : std::true_type {};\n\n\t\tClockingHint::Preference clocking_preference_ = ClockingHint::Preference::JustInTime;\n\t\tvoid set_component_prefers_clocking(ClockingHint::Source *, ClockingHint::Preference clocking) {\n\t\t\tclocking_preference_ = clocking;\n\t\t}\n};\n\n\/*!\n\tA RealTimeActor presents the same interface as a JustInTimeActor but doesn't defer work.\n\tTime added will be performed immediately.\n\n\tIts primary purpose is to allow consumers to remain flexible in their scheduling.\n*\/\ntemplate <class T, int multiplier = 1, int divider = 1, class LocalTimeScale = HalfCycles, class TargetTimeScale = LocalTimeScale> class RealTimeActor {\n\tpublic:\n\t\ttemplate<typename... Args> RealTimeActor(Args&&... args) : object_(std::forward<Args>(args)...) {}\n\n\t\tforceinline void operator += (const LocalTimeScale &rhs) {\n\t\t\tif constexpr (multiplier == 1 && divider == 1) {\n\t\t\t\tobject_.run_for(TargetTimeScale(rhs));\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif constexpr (multiplier == 1) {\n\t\t\t\taccumulated_time_ += rhs;\n\t\t\t} else {\n\t\t\t\taccumulated_time_ += rhs * multiplier;\n\t\t\t}\n\n\t\t\tif constexpr (divider == 1) {\n\t\t\t\tconst auto duration = accumulated_time_.template flush<TargetTimeScale>();\n\t\t\t\tobject_.run_for(duration);\n\t\t\t} else {\n\t\t\t\tconst auto duration = accumulated_time_.template divide<TargetTimeScale>(LocalTimeScale(divider));\n\t\t\t\tif(duration > TargetTimeScale(0))\n\t\t\t\t\tobject_.run_for(duration);\n\t\t\t}\n\t\t}\n\n\t\tforceinline T *operator->()\t\t\t\t{\treturn &object_;\t}\n\t\tforceinline const T *operator->() const\t{\treturn &object_;\t}\n\t\tforceinline T *last_valid() \t\t\t{\treturn &object_;\t}\n\t\tforceinline void flush()\t\t\t\t{}\n\n\tprivate:\n\t\tT object_;\n\t\tLocalTimeScale accumulated_time_;\n};\n\n\/*!\n\tA AsyncJustInTimeActor acts like a JustInTimeActor but additionally contains an AsyncTaskQueue.\n\tAny time the amount of accumulated time crosses a threshold provided at construction time,\n\tthe object will be updated on the AsyncTaskQueue.\n*\/\ntemplate <class T, class LocalTimeScale = HalfCycles, class TargetTimeScale = LocalTimeScale> class AsyncJustInTimeActor {\n\tpublic:\n\t\t\/\/\/ Constructs a new AsyncJustInTimeActor using the same construction arguments as the included object.\n\t\ttemplate<typename... Args> AsyncJustInTimeActor(TargetTimeScale threshold, Args&&... args) :\n\t\t\tobject_(std::forward<Args>(args)...),\n\t\t \tthreshold_(threshold) {}\n\n\t\t\/\/\/ Adds time to the actor.\n\t\tinline void operator += (const LocalTimeScale &rhs) {\n\t\t\ttime_since_update_ += rhs;\n\t\t\tif(time_since_update_ >= threshold_) {\n\t\t\t\ttime_since_update_ -= threshold_;\n\t\t\t\ttask_queue_.enqueue([this] () {\n\t\t\t\t\tobject_.run_for(threshold_);\n\t\t\t\t});\n\t\t\t}\n\t\t\tis_flushed_ = false;\n\t\t}\n\n\t\t\/\/\/ Flushes all accumulated time and returns a pointer to the included object.\n\t\tinline T *operator->() {\n\t\t\tflush();\n\t\t\treturn &object_;\n\t\t}\n\n\t\t\/\/\/ Returns a pointer to the included object without flushing time.\n\t\tinline T *last_valid() {\n\t\t\treturn &object_;\n\t\t}\n\n\t\t\/\/\/ Flushes all accumulated time.\n\t\tinline void flush() {\n\t\t\tif(!is_flushed_) {\n\t\t\t\ttask_queue_.flush();\n\t\t\t\tobject_.run_for(time_since_update_.template flush<TargetTimeScale>());\n\t\t\t\tis_flushed_ = true;\n\t\t\t}\n\t\t}\n\n\tprivate:\n\t\tT object_;\n\t\tLocalTimeScale time_since_update_;\n\t\tTargetTimeScale threshold_;\n\t\tbool is_flushed_ = true;\n\t\tConcurrency::AsyncTaskQueue task_queue_;\n};\n\n#endif \/* JustInTime_h *\/\n<commit_msg>Eliminates unused RealTimeActor, provides more feedback from +=, gets specific as to `nodiscard`s.<commit_after>\/\/\n\/\/ JustInTime.hpp\n\/\/ Clock Signal\n\/\/\n\/\/ Created by Thomas Harte on 28\/07\/2019.\n\/\/ Copyright © 2019 Thomas Harte. All rights reserved.\n\/\/\n\n#ifndef JustInTime_h\n#define JustInTime_h\n\n#include \"..\/Concurrency\/AsyncTaskQueue.hpp\"\n#include \"ClockingHintSource.hpp\"\n#include \"ForceInline.hpp\"\n\n\/*!\n\tA JustInTimeActor holds (i) an embedded object with a run_for method; and (ii) an amount\n\tof time since run_for was last called.\n\n\tTime can be added using the += operator. The -> operator can be used to access the\n\tembedded object. All time accumulated will be pushed to object before the pointer is returned.\n\n\tMachines that accumulate HalfCycle time but supply to a Cycle-counted device may supply a\n\tseparate @c TargetTimeScale at template declaration.\n\n\tIf the held object implements get_next_sequence_point() then it'll be used to flush implicitly\n\tas and when sequence points are hit. Callers can use will_flush() to predict these.\n\n\tIf the held object is a subclass of ClockingHint::Source, this template will register as an\n\tobserver and potentially stop clocking or stop delaying clocking until just-in-time references\n\tas directed.\n*\/\ntemplate <class T, int multiplier = 1, int divider = 1, class LocalTimeScale = HalfCycles, class TargetTimeScale = LocalTimeScale> class JustInTimeActor:\n\tpublic ClockingHint::Observer {\n\tprivate:\n\t\tclass SequencePointAwareDeleter {\n\t\t\tpublic:\n\t\t\t\texplicit SequencePointAwareDeleter(JustInTimeActor<T, multiplier, divider, LocalTimeScale, TargetTimeScale> *actor) : actor_(actor) {}\n\n\t\t\t\tvoid operator ()(const T *const) const {\n\t\t\t\t\tif constexpr (has_sequence_points<T>::value) {\n\t\t\t\t\t\tactor_->update_sequence_point();\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\tprivate:\n\t\t\t\tJustInTimeActor<T, multiplier, divider, LocalTimeScale, TargetTimeScale> *const actor_;\n\t\t};\n\n\tpublic:\n\t\t\/\/\/ Constructs a new JustInTimeActor using the same construction arguments as the included object.\n\t\ttemplate<typename... Args> JustInTimeActor(Args&&... args) : object_(std::forward<Args>(args)...) {\n\t\t\tif constexpr (std::is_base_of<ClockingHint::Source, T>::value) {\n\t\t\t\tobject_.set_clocking_hint_observer(this);\n\t\t\t}\n\t\t}\n\n\t\t\/\/\/ Adds time to the actor.\n\t\t\/\/\/\n\t\t\/\/\/ @returns @c true if adding time caused a flush; @c false otherwise.\n\t\tforceinline bool operator += (LocalTimeScale rhs) {\n\t\t\tif constexpr (std::is_base_of<ClockingHint::Source, T>::value) {\n\t\t\t\tif(clocking_preference_ == ClockingHint::Preference::None) {\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif constexpr (multiplier != 1) {\n\t\t\t\ttime_since_update_ += rhs * multiplier;\n\t\t\t} else {\n\t\t\t\ttime_since_update_ += rhs;\n\t\t\t}\n\t\t\tis_flushed_ = false;\n\n\t\t\tif constexpr (std::is_base_of<ClockingHint::Source, T>::value) {\n\t\t\t\tif (clocking_preference_ == ClockingHint::Preference::RealTime) {\n\t\t\t\t\tflush();\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif constexpr (has_sequence_points<T>::value) {\n\t\t\t\ttime_until_event_ -= rhs;\n\t\t\t\tif(time_until_event_ <= LocalTimeScale(0)) {\n\t\t\t\t\tflush();\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn false;\n\t\t}\n\n\t\t\/\/\/ Flushes all accumulated time and returns a pointer to the included object.\n\t\t\/\/\/\n\t\t\/\/\/ If this object provides sequence points, checks for changes to the next\n\t\t\/\/\/ sequence point upon deletion of the pointer.\n\t\t[[nodiscard]] forceinline auto operator->() {\n\t\t\tflush();\n\t\t\treturn std::unique_ptr<T, SequencePointAwareDeleter>(&object_, SequencePointAwareDeleter(this));\n\t\t}\n\n\t\t\/\/\/ Acts exactly as per the standard ->, but preserves constness.\n\t\t\/\/\/\n\t\t\/\/\/ Despite being const, this will flush the object and, if relevant, update the next sequence point.\n\t\t[[nodiscard]] forceinline auto operator -> () const {\n\t\t\tauto non_const_this = const_cast<JustInTimeActor<T, multiplier, divider, LocalTimeScale, TargetTimeScale> *>(this);\n\t\t\tnon_const_this->flush();\n\t\t\treturn std::unique_ptr<const T, SequencePointAwareDeleter>(&object_, SequencePointAwareDeleter(non_const_this));\n\t\t}\n\n\t\t\/\/\/ @returns a pointer to the included object, without flushing time.\n\t\t[[nodiscard]] forceinline T *last_valid() {\n\t\t\treturn &object_;\n\t\t}\n\n\t\t\/\/\/ @returns the amount of time since the object was last flushed, in the target time scale.\n\t\t[[nodiscard]] forceinline TargetTimeScale time_since_flush() const {\n\t\t\t\/\/ TODO: does this handle conversions properly where TargetTimeScale != LocalTimeScale?\n\t\t\tif constexpr (divider == 1) {\n\t\t\t\treturn time_since_update_;\n\t\t\t}\n\t\t\treturn TargetTimeScale(time_since_update_.as_integral() \/ divider);\n\t\t}\n\n\t\t\/\/\/ Flushes all accumulated time.\n\t\t\/\/\/\n\t\t\/\/\/ This does not affect this actor's record of when the next sequence point will occur.\n\t\tforceinline void flush() {\n\t\t\tif(!is_flushed_) {\n\t\t\t\tdid_flush_ = is_flushed_ = true;\n\t\t\t\tif constexpr (divider == 1) {\n\t\t\t\t\tconst auto duration = time_since_update_.template flush<TargetTimeScale>();\n\t\t\t\t\tobject_.run_for(duration);\n\t\t\t\t} else {\n\t\t\t\t\tconst auto duration = time_since_update_.template divide<TargetTimeScale>(LocalTimeScale(divider));\n\t\t\t\t\tif(duration > TargetTimeScale(0))\n\t\t\t\t\t\tobject_.run_for(duration);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t\/\/\/ Indicates whether a flush has occurred since the last call to did_flush().\n\t\t[[nodiscard]] forceinline bool did_flush() {\n\t\t\tconst bool did_flush = did_flush_;\n\t\t\tdid_flush_ = false;\n\t\t\treturn did_flush;\n\t\t}\n\n\t\t\/\/\/ @returns the number of cycles until the next sequence-point-based flush, if the embedded object\n\t\t\/\/\/ supports sequence points; @c LocalTimeScale() otherwise.\n\t\t[[nodiscard]] LocalTimeScale cycles_until_implicit_flush() const {\n\t\t\treturn time_until_event_;\n\t\t}\n\n\t\t\/\/\/ Indicates whether a sequence-point-caused flush will occur if the specified period is added.\n\t\t[[nodiscard]] forceinline bool will_flush(LocalTimeScale rhs) const {\n\t\t\tif constexpr (!has_sequence_points<T>::value) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\treturn rhs >= time_until_event_;\n\t\t}\n\n\t\t\/\/\/ Updates this template's record of the next sequence point.\n\t\tvoid update_sequence_point() {\n\t\t\tif constexpr (has_sequence_points<T>::value) {\n\t\t\t\ttime_until_event_ = object_.get_next_sequence_point();\n\t\t\t\tassert(time_until_event_ > LocalTimeScale(0));\n\t\t\t}\n\t\t}\n\n\tprivate:\n\t\tT object_;\n\t\tLocalTimeScale time_since_update_, time_until_event_;\n\t\tbool is_flushed_ = true;\n\t\tbool did_flush_ = false;\n\n\t\ttemplate <typename S, typename = void> struct has_sequence_points : std::false_type {};\n\t\ttemplate <typename S> struct has_sequence_points<S, decltype(void(std::declval<S &>().get_next_sequence_point()))> : std::true_type {};\n\n\t\tClockingHint::Preference clocking_preference_ = ClockingHint::Preference::JustInTime;\n\t\tvoid set_component_prefers_clocking(ClockingHint::Source *, ClockingHint::Preference clocking) {\n\t\t\tclocking_preference_ = clocking;\n\t\t}\n};\n\n\/*!\n\tA AsyncJustInTimeActor acts like a JustInTimeActor but additionally contains an AsyncTaskQueue.\n\tAny time the amount of accumulated time crosses a threshold provided at construction time,\n\tthe object will be updated on the AsyncTaskQueue.\n*\/\ntemplate <class T, class LocalTimeScale = HalfCycles, class TargetTimeScale = LocalTimeScale> class AsyncJustInTimeActor {\n\tpublic:\n\t\t\/\/\/ Constructs a new AsyncJustInTimeActor using the same construction arguments as the included object.\n\t\ttemplate<typename... Args> AsyncJustInTimeActor(TargetTimeScale threshold, Args&&... args) :\n\t\t\tobject_(std::forward<Args>(args)...),\n\t\t \tthreshold_(threshold) {}\n\n\t\t\/\/\/ Adds time to the actor.\n\t\tinline void operator += (const LocalTimeScale &rhs) {\n\t\t\ttime_since_update_ += rhs;\n\t\t\tif(time_since_update_ >= threshold_) {\n\t\t\t\ttime_since_update_ -= threshold_;\n\t\t\t\ttask_queue_.enqueue([this] () {\n\t\t\t\t\tobject_.run_for(threshold_);\n\t\t\t\t});\n\t\t\t}\n\t\t\tis_flushed_ = false;\n\t\t}\n\n\t\t\/\/\/ Flushes all accumulated time and returns a pointer to the included object.\n\t\tinline T *operator->() {\n\t\t\tflush();\n\t\t\treturn &object_;\n\t\t}\n\n\t\t\/\/\/ Returns a pointer to the included object without flushing time.\n\t\tinline T *last_valid() {\n\t\t\treturn &object_;\n\t\t}\n\n\t\t\/\/\/ Flushes all accumulated time.\n\t\tinline void flush() {\n\t\t\tif(!is_flushed_) {\n\t\t\t\ttask_queue_.flush();\n\t\t\t\tobject_.run_for(time_since_update_.template flush<TargetTimeScale>());\n\t\t\t\tis_flushed_ = true;\n\t\t\t}\n\t\t}\n\n\tprivate:\n\t\tT object_;\n\t\tLocalTimeScale time_since_update_;\n\t\tTargetTimeScale threshold_;\n\t\tbool is_flushed_ = true;\n\t\tConcurrency::AsyncTaskQueue task_queue_;\n};\n\n#endif \/* JustInTime_h *\/\n<|endoftext|>"} {"text":"<commit_before>\/*\n * qmqtt_network.cpp - qmqtt network\n *\n * Copyright (c) 2013 Ery Lee <ery.lee at gmail dot com>\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * * Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution.\n * * Neither the name of mqttc nor the names of its contributors may be used\n * to endorse or promote products derived from this software without\n * specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n *\/\n#include <QDataStream>\n#include \"qmqtt_network_p.h\"\n#include \"qmqtt_socket_p.h\"\n#include \"qmqtt_ssl_socket_p.h\"\n#include \"qmqtt_timer_p.h\"\n#include \"qmqtt_websocket_p.h\"\n\nconst QString DEFAULT_HOST_NAME = QStringLiteral(\"localhost\");\nconst QHostAddress DEFAULT_HOST = QHostAddress::LocalHost;\nconst quint16 DEFAULT_PORT = 1883;\nconst quint16 DEFAULT_SSL_PORT = 8883;\nconst bool DEFAULT_AUTORECONNECT = false;\nconst int DEFAULT_AUTORECONNECT_INTERVAL_MS = 5000;\n\nQMQTT::Network::Network(QObject* parent)\n : NetworkInterface(parent)\n , _port(DEFAULT_PORT)\n , _host(DEFAULT_HOST)\n , _autoReconnect(DEFAULT_AUTORECONNECT)\n , _autoReconnectInterval(DEFAULT_AUTORECONNECT_INTERVAL_MS)\n , _socket(new QMQTT::Socket)\n , _autoReconnectTimer(new QMQTT::Timer)\n , _readState(Header)\n{\n initialize();\n}\n\n#ifndef QT_NO_SSL\nQMQTT::Network::Network(const QSslConfiguration &config, bool ignoreSelfSigned, QObject *parent)\n : NetworkInterface(parent)\n , _port(DEFAULT_SSL_PORT)\n , _hostName(DEFAULT_HOST_NAME)\n , _autoReconnect(DEFAULT_AUTORECONNECT)\n , _autoReconnectInterval(DEFAULT_AUTORECONNECT_INTERVAL_MS)\n , _socket(new QMQTT::SslSocket(config, ignoreSelfSigned))\n , _autoReconnectTimer(new QMQTT::Timer)\n , _readState(Header)\n{\n initialize();\n}\n#endif \/\/ QT_NO_SSL\n\n#ifdef QT_WEBSOCKETS_LIB\nQMQTT::Network::Network(const QString& origin, QWebSocketProtocol::Version version,\n bool ignoreSelfSigned, QObject* parent)\n : NetworkInterface(parent)\n , _port(DEFAULT_SSL_PORT)\n , _hostName(DEFAULT_HOST_NAME)\n , _autoReconnect(DEFAULT_AUTORECONNECT)\n , _autoReconnectInterval(DEFAULT_AUTORECONNECT_INTERVAL_MS)\n , _socket(new QMQTT::WebSocket(origin, version, ignoreSelfSigned))\n , _autoReconnectTimer(new QMQTT::Timer)\n , _readState(Header)\n{\n initialize();\n}\n#endif \/\/ QT_WEBSOCKETS_LIB\n\nQMQTT::Network::Network(SocketInterface* socketInterface, TimerInterface* timerInterface,\n QObject* parent)\n : NetworkInterface(parent)\n , _port(DEFAULT_PORT)\n , _host(DEFAULT_HOST)\n , _autoReconnect(DEFAULT_AUTORECONNECT)\n , _autoReconnectInterval(DEFAULT_AUTORECONNECT_INTERVAL_MS)\n , _socket(socketInterface)\n , _autoReconnectTimer(timerInterface)\n , _readState(Header)\n{\n initialize();\n}\n\nvoid QMQTT::Network::initialize()\n{\n _socket->setParent(this);\n _autoReconnectTimer->setParent(this);\n _autoReconnectTimer->setSingleShot(true);\n _autoReconnectTimer->setInterval(_autoReconnectInterval);\n\n QObject::connect(_socket, &SocketInterface::connected, this, &Network::connected);\n QObject::connect(_socket, &SocketInterface::disconnected, this, &Network::onDisconnected);\n QObject::connect(_socket->ioDevice(), &QIODevice::readyRead, this, &Network::onSocketReadReady);\n QObject::connect(\n _autoReconnectTimer, &TimerInterface::timeout,\n this, static_cast<void (Network::*)()>(&Network::connectToHost)); \n QObject::connect(_socket,\n static_cast<void (SocketInterface::*)(QAbstractSocket::SocketError)>(&SocketInterface::error),\n this, &Network::onSocketError);\n}\n\nQMQTT::Network::~Network()\n{\n}\n\nbool QMQTT::Network::isConnectedToHost() const\n{\n return _socket->state() == QAbstractSocket::ConnectedState;\n}\n\nvoid QMQTT::Network::connectToHost(const QHostAddress& host, const quint16 port)\n{\n \/\/ Reset the hostname, because if it is not empty connectToHost() will use it instead of _host.\n _hostName.clear();\n _host = host;\n _port = port;\n connectToHost();\n}\n\nvoid QMQTT::Network::connectToHost(const QString& hostName, const quint16 port)\n{\n _hostName = hostName;\n _port = port;\n connectToHost();\n}\n\nvoid QMQTT::Network::connectToHost()\n{\n _readState = Header;\n if (_hostName.isEmpty())\n {\n _socket->connectToHost(_host, _port);\n }\n else\n {\n _socket->connectToHost(_hostName, _port);\n }\n}\n\nvoid QMQTT::Network::onSocketError(QAbstractSocket::SocketError socketError)\n{\n emit error(socketError);\n if(_autoReconnect)\n {\n _autoReconnectTimer->start();\n }\n}\n\nvoid QMQTT::Network::sendFrame(Frame& frame)\n{\n if(_socket->state() == QAbstractSocket::ConnectedState)\n {\n QDataStream out(_socket->ioDevice());\n frame.write(out);\n }\n}\n\nvoid QMQTT::Network::disconnectFromHost()\n{\n _socket->disconnectFromHost();\n}\n\nQAbstractSocket::SocketState QMQTT::Network::state() const\n{\n return _socket->state();\n}\n\nbool QMQTT::Network::autoReconnect() const\n{\n return _autoReconnect;\n}\n\nvoid QMQTT::Network::setAutoReconnect(const bool autoReconnect)\n{\n _autoReconnect = autoReconnect;\n}\n\nint QMQTT::Network::autoReconnectInterval() const\n{\n return _autoReconnectInterval;\n}\n\nvoid QMQTT::Network::setAutoReconnectInterval(const int autoReconnectInterval)\n{\n _autoReconnectInterval = autoReconnectInterval;\n _autoReconnectTimer->setInterval(_autoReconnectInterval);\n}\n\nvoid QMQTT::Network::onSocketReadReady()\n{\n QIODevice *ioDevice = _socket->ioDevice();\n \/\/ Only read the available (cached) bytes, so the read will never block.\n QByteArray data = ioDevice->read(ioDevice->bytesAvailable());\n foreach(char byte, data) {\n switch (_readState) {\n case Header:\n _header = static_cast<quint8>(byte);\n _readState = Length;\n _length = 0;\n _shift = 0;\n _data.resize(0); \/\/ keep allocated buffer\n break;\n case Length:\n _length |= (byte & 0x7F) << _shift;\n _shift += 7;\n if ((byte & 0x80) != 0)\n break;\n if (_length == 0) {\n _readState = Header;\n Frame frame(_header, _data);\n emit received(frame);\n break;\n }\n _readState = PayLoad;\n _data.reserve(_length);\n break;\n case PayLoad:\n _data.append(byte);\n --_length;\n if (_length > 0)\n break;\n _readState = Header;\n Frame frame(_header, _data);\n emit received(frame);\n break;\n }\n }\n}\n\nvoid QMQTT::Network::onDisconnected()\n{\n emit disconnected();\n if(_autoReconnect)\n {\n _autoReconnectTimer->start();\n }\n}\n<commit_msg>Remove default hostname and IP address from Network class<commit_after>\/*\n * qmqtt_network.cpp - qmqtt network\n *\n * Copyright (c) 2013 Ery Lee <ery.lee at gmail dot com>\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * * Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution.\n * * Neither the name of mqttc nor the names of its contributors may be used\n * to endorse or promote products derived from this software without\n * specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n *\/\n#include <QDataStream>\n#include \"qmqtt_network_p.h\"\n#include \"qmqtt_socket_p.h\"\n#include \"qmqtt_ssl_socket_p.h\"\n#include \"qmqtt_timer_p.h\"\n#include \"qmqtt_websocket_p.h\"\n\nconst quint16 DEFAULT_PORT = 1883;\nconst quint16 DEFAULT_SSL_PORT = 8883;\nconst bool DEFAULT_AUTORECONNECT = false;\nconst int DEFAULT_AUTORECONNECT_INTERVAL_MS = 5000;\n\nQMQTT::Network::Network(QObject* parent)\n : NetworkInterface(parent)\n , _port(DEFAULT_PORT)\n , _autoReconnect(DEFAULT_AUTORECONNECT)\n , _autoReconnectInterval(DEFAULT_AUTORECONNECT_INTERVAL_MS)\n , _socket(new QMQTT::Socket)\n , _autoReconnectTimer(new QMQTT::Timer)\n , _readState(Header)\n{\n initialize();\n}\n\n#ifndef QT_NO_SSL\nQMQTT::Network::Network(const QSslConfiguration &config, bool ignoreSelfSigned, QObject *parent)\n : NetworkInterface(parent)\n , _port(DEFAULT_SSL_PORT)\n , _autoReconnect(DEFAULT_AUTORECONNECT)\n , _autoReconnectInterval(DEFAULT_AUTORECONNECT_INTERVAL_MS)\n , _socket(new QMQTT::SslSocket(config, ignoreSelfSigned))\n , _autoReconnectTimer(new QMQTT::Timer)\n , _readState(Header)\n{\n initialize();\n}\n#endif \/\/ QT_NO_SSL\n\n#ifdef QT_WEBSOCKETS_LIB\nQMQTT::Network::Network(const QString& origin, QWebSocketProtocol::Version version,\n bool ignoreSelfSigned, QObject* parent)\n : NetworkInterface(parent)\n , _port(DEFAULT_SSL_PORT)\n , _autoReconnect(DEFAULT_AUTORECONNECT)\n , _autoReconnectInterval(DEFAULT_AUTORECONNECT_INTERVAL_MS)\n , _socket(new QMQTT::WebSocket(origin, version, ignoreSelfSigned))\n , _autoReconnectTimer(new QMQTT::Timer)\n , _readState(Header)\n{\n initialize();\n}\n#endif \/\/ QT_WEBSOCKETS_LIB\n\nQMQTT::Network::Network(SocketInterface* socketInterface, TimerInterface* timerInterface,\n QObject* parent)\n : NetworkInterface(parent)\n , _port(DEFAULT_PORT)\n , _autoReconnect(DEFAULT_AUTORECONNECT)\n , _autoReconnectInterval(DEFAULT_AUTORECONNECT_INTERVAL_MS)\n , _socket(socketInterface)\n , _autoReconnectTimer(timerInterface)\n , _readState(Header)\n{\n initialize();\n}\n\nvoid QMQTT::Network::initialize()\n{\n _socket->setParent(this);\n _autoReconnectTimer->setParent(this);\n _autoReconnectTimer->setSingleShot(true);\n _autoReconnectTimer->setInterval(_autoReconnectInterval);\n\n QObject::connect(_socket, &SocketInterface::connected, this, &Network::connected);\n QObject::connect(_socket, &SocketInterface::disconnected, this, &Network::onDisconnected);\n QObject::connect(_socket->ioDevice(), &QIODevice::readyRead, this, &Network::onSocketReadReady);\n QObject::connect(\n _autoReconnectTimer, &TimerInterface::timeout,\n this, static_cast<void (Network::*)()>(&Network::connectToHost)); \n QObject::connect(_socket,\n static_cast<void (SocketInterface::*)(QAbstractSocket::SocketError)>(&SocketInterface::error),\n this, &Network::onSocketError);\n}\n\nQMQTT::Network::~Network()\n{\n}\n\nbool QMQTT::Network::isConnectedToHost() const\n{\n return _socket->state() == QAbstractSocket::ConnectedState;\n}\n\nvoid QMQTT::Network::connectToHost(const QHostAddress& host, const quint16 port)\n{\n \/\/ Reset the hostname, because if it is not empty connectToHost() will use it instead of _host.\n _hostName.clear();\n _host = host;\n _port = port;\n connectToHost();\n}\n\nvoid QMQTT::Network::connectToHost(const QString& hostName, const quint16 port)\n{\n _hostName = hostName;\n _port = port;\n connectToHost();\n}\n\nvoid QMQTT::Network::connectToHost()\n{\n _readState = Header;\n if (_hostName.isEmpty())\n {\n _socket->connectToHost(_host, _port);\n }\n else\n {\n _socket->connectToHost(_hostName, _port);\n }\n}\n\nvoid QMQTT::Network::onSocketError(QAbstractSocket::SocketError socketError)\n{\n emit error(socketError);\n if(_autoReconnect)\n {\n _autoReconnectTimer->start();\n }\n}\n\nvoid QMQTT::Network::sendFrame(Frame& frame)\n{\n if(_socket->state() == QAbstractSocket::ConnectedState)\n {\n QDataStream out(_socket->ioDevice());\n frame.write(out);\n }\n}\n\nvoid QMQTT::Network::disconnectFromHost()\n{\n _socket->disconnectFromHost();\n}\n\nQAbstractSocket::SocketState QMQTT::Network::state() const\n{\n return _socket->state();\n}\n\nbool QMQTT::Network::autoReconnect() const\n{\n return _autoReconnect;\n}\n\nvoid QMQTT::Network::setAutoReconnect(const bool autoReconnect)\n{\n _autoReconnect = autoReconnect;\n}\n\nint QMQTT::Network::autoReconnectInterval() const\n{\n return _autoReconnectInterval;\n}\n\nvoid QMQTT::Network::setAutoReconnectInterval(const int autoReconnectInterval)\n{\n _autoReconnectInterval = autoReconnectInterval;\n _autoReconnectTimer->setInterval(_autoReconnectInterval);\n}\n\nvoid QMQTT::Network::onSocketReadReady()\n{\n QIODevice *ioDevice = _socket->ioDevice();\n \/\/ Only read the available (cached) bytes, so the read will never block.\n QByteArray data = ioDevice->read(ioDevice->bytesAvailable());\n foreach(char byte, data) {\n switch (_readState) {\n case Header:\n _header = static_cast<quint8>(byte);\n _readState = Length;\n _length = 0;\n _shift = 0;\n _data.resize(0); \/\/ keep allocated buffer\n break;\n case Length:\n _length |= (byte & 0x7F) << _shift;\n _shift += 7;\n if ((byte & 0x80) != 0)\n break;\n if (_length == 0) {\n _readState = Header;\n Frame frame(_header, _data);\n emit received(frame);\n break;\n }\n _readState = PayLoad;\n _data.reserve(_length);\n break;\n case PayLoad:\n _data.append(byte);\n --_length;\n if (_length > 0)\n break;\n _readState = Header;\n Frame frame(_header, _data);\n emit received(frame);\n break;\n }\n }\n}\n\nvoid QMQTT::Network::onDisconnected()\n{\n emit disconnected();\n if(_autoReconnect)\n {\n _autoReconnectTimer->start();\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/**************************************************************************\n**\n** This file is part of Qt Creator\n**\n** Copyright (c) 2012 Nokia Corporation and\/or its subsidiary(-ies).\n**\n** Contact: http:\/\/www.qt-project.org\/\n**\n**\n** GNU Lesser General Public License Usage\n**\n** This file may be used under the terms of the GNU Lesser General Public\n** License version 2.1 as published by the Free Software Foundation and\n** appearing in the file LICENSE.LGPL included in the packaging of this file.\n** Please review the following information to ensure the GNU Lesser General\n** Public License version 2.1 requirements will be met:\n** http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Nokia gives you certain additional\n** rights. These rights are described in the Nokia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n** Other Usage\n**\n** Alternatively, this file may be used in accordance with the terms and\n** conditions contained in a signed written agreement between you and Nokia.\n**\n**\n**************************************************************************\/\n\n#include \"qt4projectconfigwidget.h\"\n\n#include \"makestep.h\"\n#include \"qmakestep.h\"\n#include \"qt4project.h\"\n#include \"qt4projectmanagerconstants.h\"\n#include \"qt4projectmanager.h\"\n#include \"qt4buildconfiguration.h\"\n#include \"ui_qt4projectconfigwidget.h\"\n\n#include <coreplugin\/icore.h>\n#include <coreplugin\/idocument.h>\n\n#include <projectexplorer\/target.h>\n#include <projectexplorer\/toolchain.h>\n#include <projectexplorer\/task.h>\n#include <projectexplorer\/projectexplorerconstants.h>\n#include <projectexplorer\/buildconfiguration.h>\n#include <qtsupport\/qtversionfactory.h>\n#include <qtsupport\/baseqtversion.h>\n#include <qtsupport\/qtkitinformation.h>\n#include <qtsupport\/qtsupportconstants.h>\n#include <qtsupport\/qtversionmanager.h>\n#include <utils\/qtcassert.h>\n#include <utils\/qtcprocess.h>\n#include <extensionsystem\/pluginmanager.h>\n\n#include <QFileDialog>\n#include <QPushButton>\n#include <utils\/detailswidget.h>\n\nnamespace {\nbool debug = false;\n}\n\nusing namespace Qt4ProjectManager;\nusing namespace Qt4ProjectManager::Internal;\nusing namespace ProjectExplorer;\n\nQt4ProjectConfigWidget::Qt4ProjectConfigWidget(ProjectExplorer::Target *target)\n : BuildConfigWidget(),\n m_buildConfiguration(0),\n m_ignoreChange(false)\n{\n QVBoxLayout *vbox = new QVBoxLayout(this);\n vbox->setMargin(0);\n m_detailsContainer = new Utils::DetailsWidget(this);\n m_detailsContainer->setState(Utils::DetailsWidget::NoSummary);\n vbox->addWidget(m_detailsContainer);\n QWidget *details = new QWidget(m_detailsContainer);\n m_detailsContainer->setWidget(details);\n m_ui = new Ui::Qt4ProjectConfigWidget();\n m_ui->setupUi(details);\n\n m_browseButton = m_ui->shadowBuildDirEdit->buttonAtIndex(0);\n\n m_ui->shadowBuildDirEdit->setPromptDialogTitle(tr(\"Shadow Build Directory\"));\n m_ui->shadowBuildDirEdit->setExpectedKind(Utils::PathChooser::ExistingDirectory);\n\n connect(m_ui->shadowBuildCheckBox, SIGNAL(clicked(bool)),\n this, SLOT(shadowBuildClicked(bool)));\n\n connect(m_ui->shadowBuildDirEdit, SIGNAL(beforeBrowsing()),\n this, SLOT(onBeforeBeforeShadowBuildDirBrowsed()));\n\n connect(m_ui->shadowBuildDirEdit, SIGNAL(changed(QString)),\n this, SLOT(shadowBuildEdited()));\n\n Qt4Project *project = static_cast<Qt4Project *>(target->project());\n connect(project, SIGNAL(environmentChanged()), this, SLOT(environmentChanged()));\n connect(project, SIGNAL(buildDirectoryInitialized()), this, SLOT(updateProblemLabel()));\n}\n\nQt4ProjectConfigWidget::~Qt4ProjectConfigWidget()\n{\n delete m_ui;\n}\n\nvoid Qt4ProjectConfigWidget::updateDetails()\n{\n m_detailsContainer->setSummaryText(\n tr(\"building in <b>%1<\/b>\")\n .arg(QDir::toNativeSeparators(m_buildConfiguration->buildDirectory())));\n}\n\nvoid Qt4ProjectConfigWidget::environmentChanged()\n{\n m_ui->shadowBuildDirEdit->setEnvironment(m_buildConfiguration->environment());\n}\n\nQString Qt4ProjectConfigWidget::displayName() const\n{\n return tr(\"General\");\n}\n\nvoid Qt4ProjectConfigWidget::init(ProjectExplorer::BuildConfiguration *bc)\n{\n QTC_ASSERT(bc, return);\n\n if (debug)\n qDebug() << \"Qt4ProjectConfigWidget::init() for\" << bc->displayName();\n\n if (m_buildConfiguration) {\n disconnect(m_buildConfiguration, SIGNAL(buildDirectoryChanged()),\n this, SLOT(buildDirectoryChanged()));\n disconnect(m_buildConfiguration, SIGNAL(qmakeBuildConfigurationChanged()),\n this, SLOT(updateProblemLabel()));\n }\n m_buildConfiguration = static_cast<Qt4BuildConfiguration *>(bc);\n m_ui->shadowBuildDirEdit->setEnvironment(m_buildConfiguration->environment());\n\n connect(m_buildConfiguration, SIGNAL(buildDirectoryChanged()),\n this, SLOT(buildDirectoryChanged()));\n connect(m_buildConfiguration, SIGNAL(qmakeBuildConfigurationChanged()),\n this, SLOT(updateProblemLabel()));\n\n m_ui->shadowBuildDirEdit->setBaseDirectory(m_buildConfiguration->target()->project()->projectDirectory());\n\n buildDirectoryChanged();\n}\n\nvoid Qt4ProjectConfigWidget::buildDirectoryChanged()\n{\n if (m_ignoreChange)\n return;\n m_ui->shadowBuildDirEdit->setPath(m_buildConfiguration->shadowBuildDirectory());\n bool shadowBuild = m_buildConfiguration->shadowBuild();\n m_ui->shadowBuildCheckBox->setChecked(shadowBuild);\n m_ui->shadowBuildDirEdit->setEnabled(shadowBuild);\n m_browseButton->setEnabled(shadowBuild);\n\n updateDetails();\n updateProblemLabel();\n}\n\nvoid Qt4ProjectConfigWidget::onBeforeBeforeShadowBuildDirBrowsed()\n{\n QString initialDirectory = m_buildConfiguration->target()->project()->projectDirectory();\n if (!initialDirectory.isEmpty())\n m_ui->shadowBuildDirEdit->setInitialBrowsePathBackup(initialDirectory);\n}\n\nvoid Qt4ProjectConfigWidget::shadowBuildClicked(bool checked)\n{\n m_ui->shadowBuildDirEdit->setEnabled(checked);\n m_browseButton->setEnabled(checked);\n bool b = m_ui->shadowBuildCheckBox->isChecked();\n\n m_ignoreChange = true;\n m_buildConfiguration->setShadowBuildAndDirectory(b, m_ui->shadowBuildDirEdit->rawPath());\n m_ignoreChange = false;\n\n updateDetails();\n updateProblemLabel();\n}\n\nvoid Qt4ProjectConfigWidget::shadowBuildEdited()\n{\n if (m_buildConfiguration->shadowBuildDirectory() == m_ui->shadowBuildDirEdit->rawPath())\n return;\n m_ignoreChange = true;\n m_buildConfiguration->setShadowBuildAndDirectory(m_buildConfiguration->shadowBuild(), m_ui->shadowBuildDirEdit->rawPath());\n m_ignoreChange = false;\n\n \/\/ if the directory already exists\n \/\/ check if we have a build in there and\n \/\/ offer to import it\n updateProblemLabel();\n updateDetails();\n}\n\nvoid Qt4ProjectConfigWidget::updateProblemLabel()\n{\n bool targetMismatch = false;\n bool incompatibleBuild = false;\n bool allGood = false;\n\n ProjectExplorer::Kit *k = m_buildConfiguration->target()->kit();\n const QString proFileName = m_buildConfiguration->target()->project()->document()->fileName();\n\n QtSupport::BaseQtVersion *version = QtSupport::QtKitInformation::qtVersion(k);\n if (!version) {\n m_ui->problemLabel->setVisible(true);\n m_ui->warningLabel->setVisible(true);\n m_ui->problemLabel->setText(tr(\"This target cannot build this project since it does not define a \"\n \"Qt version.\"));\n return;\n }\n\n \/\/ we only show if we actually have a qmake and makestep\n if (m_buildConfiguration->qmakeStep() && m_buildConfiguration->makeStep()) {\n QString makefile = m_buildConfiguration->buildDirectory() + QLatin1Char('\/');\n if (m_buildConfiguration->makefile().isEmpty())\n makefile.append(QLatin1String(\"Makefile\"));\n else\n makefile.append(m_buildConfiguration->makefile());\n\n switch (m_buildConfiguration->compareToImportFrom(makefile)) {\n case Qt4BuildConfiguration::MakefileMatches:\n allGood = true;\n break;\n case Qt4BuildConfiguration::MakefileMissing:\n allGood = true;\n break;\n case Qt4BuildConfiguration::MakefileIncompatible:\n incompatibleBuild = true;\n break;\n case Qt4BuildConfiguration::MakefileForWrongProject:\n targetMismatch = true;\n break;\n }\n }\n\n QString shadowBuildWarning;\n if (!version->supportsShadowBuilds() && m_buildConfiguration->shadowBuild()) {\n shadowBuildWarning =tr(\"The Qt version %1 does not support shadow builds, building might fail.\")\n .arg(version->displayName())\n + QLatin1String(\"<br>\");\n }\n\n if (allGood) {\n QString buildDirectory = m_buildConfiguration->target()->project()->projectDirectory();;\n if (m_buildConfiguration->shadowBuild())\n buildDirectory = m_buildConfiguration->buildDirectory();\n QList<ProjectExplorer::Task> issues;\n issues = version->reportIssues(proFileName, buildDirectory);\n qSort(issues);\n\n if (issues.isEmpty() && shadowBuildWarning.isEmpty()) {\n m_ui->problemLabel->setVisible(false);\n m_ui->warningLabel->setVisible(false);\n } else {\n m_ui->problemLabel->setVisible(true);\n m_ui->warningLabel->setVisible(true);\n QString text = QLatin1String(\"<nobr>\") + shadowBuildWarning;\n foreach (const ProjectExplorer::Task &task, issues) {\n QString type;\n switch (task.type) {\n case ProjectExplorer::Task::Error:\n type = tr(\"Error:\");\n type += QLatin1Char(' ');\n break;\n case ProjectExplorer::Task::Warning:\n type = tr(\"Warning:\");\n type += QLatin1Char(' ');\n break;\n case ProjectExplorer::Task::Unknown:\n default:\n break;\n }\n if (!text.endsWith(QLatin1String(\"br>\")))\n text.append(QLatin1String(\"<br>\"));\n text.append(type + task.description);\n }\n m_ui->problemLabel->setText(text);\n }\n } else if (targetMismatch) {\n m_ui->problemLabel->setVisible(true);\n m_ui->warningLabel->setVisible(true);\n m_ui->problemLabel->setText(shadowBuildWarning + tr(\"A build for a different project exists in %1, which will be overwritten.\",\n \"%1 build directory\")\n .arg(m_ui->shadowBuildDirEdit->path()));\n } else if (incompatibleBuild) {\n m_ui->warningLabel->setVisible(true);\n m_ui->problemLabel->setVisible(true);\n m_ui->problemLabel->setText(shadowBuildWarning +tr(\"An incompatible build exists in %1, which will be overwritten.\",\n \"%1 build directory\")\n .arg(m_ui->shadowBuildDirEdit->path()));\n } else if (!shadowBuildWarning.isEmpty()) {\n m_ui->warningLabel->setVisible(true);\n m_ui->problemLabel->setVisible(true);\n m_ui->problemLabel->setText(shadowBuildWarning);\n }\n}\n<commit_msg>Qt4Project: Fix updating of problem label on kit changes<commit_after>\/**************************************************************************\n**\n** This file is part of Qt Creator\n**\n** Copyright (c) 2012 Nokia Corporation and\/or its subsidiary(-ies).\n**\n** Contact: http:\/\/www.qt-project.org\/\n**\n**\n** GNU Lesser General Public License Usage\n**\n** This file may be used under the terms of the GNU Lesser General Public\n** License version 2.1 as published by the Free Software Foundation and\n** appearing in the file LICENSE.LGPL included in the packaging of this file.\n** Please review the following information to ensure the GNU Lesser General\n** Public License version 2.1 requirements will be met:\n** http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Nokia gives you certain additional\n** rights. These rights are described in the Nokia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n** Other Usage\n**\n** Alternatively, this file may be used in accordance with the terms and\n** conditions contained in a signed written agreement between you and Nokia.\n**\n**\n**************************************************************************\/\n\n#include \"qt4projectconfigwidget.h\"\n\n#include \"makestep.h\"\n#include \"qmakestep.h\"\n#include \"qt4project.h\"\n#include \"qt4projectmanagerconstants.h\"\n#include \"qt4projectmanager.h\"\n#include \"qt4buildconfiguration.h\"\n#include \"ui_qt4projectconfigwidget.h\"\n\n#include <coreplugin\/icore.h>\n#include <coreplugin\/idocument.h>\n\n#include <projectexplorer\/target.h>\n#include <projectexplorer\/toolchain.h>\n#include <projectexplorer\/task.h>\n#include <projectexplorer\/projectexplorerconstants.h>\n#include <projectexplorer\/buildconfiguration.h>\n#include <qtsupport\/qtversionfactory.h>\n#include <qtsupport\/baseqtversion.h>\n#include <qtsupport\/qtkitinformation.h>\n#include <qtsupport\/qtsupportconstants.h>\n#include <qtsupport\/qtversionmanager.h>\n#include <utils\/qtcassert.h>\n#include <utils\/qtcprocess.h>\n#include <extensionsystem\/pluginmanager.h>\n\n#include <QFileDialog>\n#include <QPushButton>\n#include <utils\/detailswidget.h>\n\nnamespace {\nbool debug = false;\n}\n\nusing namespace Qt4ProjectManager;\nusing namespace Qt4ProjectManager::Internal;\nusing namespace ProjectExplorer;\n\nQt4ProjectConfigWidget::Qt4ProjectConfigWidget(ProjectExplorer::Target *target)\n : BuildConfigWidget(),\n m_buildConfiguration(0),\n m_ignoreChange(false)\n{\n QVBoxLayout *vbox = new QVBoxLayout(this);\n vbox->setMargin(0);\n m_detailsContainer = new Utils::DetailsWidget(this);\n m_detailsContainer->setState(Utils::DetailsWidget::NoSummary);\n vbox->addWidget(m_detailsContainer);\n QWidget *details = new QWidget(m_detailsContainer);\n m_detailsContainer->setWidget(details);\n m_ui = new Ui::Qt4ProjectConfigWidget();\n m_ui->setupUi(details);\n\n m_browseButton = m_ui->shadowBuildDirEdit->buttonAtIndex(0);\n\n m_ui->shadowBuildDirEdit->setPromptDialogTitle(tr(\"Shadow Build Directory\"));\n m_ui->shadowBuildDirEdit->setExpectedKind(Utils::PathChooser::ExistingDirectory);\n\n connect(m_ui->shadowBuildCheckBox, SIGNAL(clicked(bool)),\n this, SLOT(shadowBuildClicked(bool)));\n\n connect(m_ui->shadowBuildDirEdit, SIGNAL(beforeBrowsing()),\n this, SLOT(onBeforeBeforeShadowBuildDirBrowsed()));\n\n connect(m_ui->shadowBuildDirEdit, SIGNAL(changed(QString)),\n this, SLOT(shadowBuildEdited()));\n\n Qt4Project *project = static_cast<Qt4Project *>(target->project());\n connect(project, SIGNAL(environmentChanged()), this, SLOT(environmentChanged()));\n connect(project, SIGNAL(buildDirectoryInitialized()), this, SLOT(updateProblemLabel()));\n\n connect(target, SIGNAL(kitChanged()), this, SLOT(updateProblemLabel()));\n}\n\nQt4ProjectConfigWidget::~Qt4ProjectConfigWidget()\n{\n delete m_ui;\n}\n\nvoid Qt4ProjectConfigWidget::updateDetails()\n{\n m_detailsContainer->setSummaryText(\n tr(\"building in <b>%1<\/b>\")\n .arg(QDir::toNativeSeparators(m_buildConfiguration->buildDirectory())));\n}\n\nvoid Qt4ProjectConfigWidget::environmentChanged()\n{\n m_ui->shadowBuildDirEdit->setEnvironment(m_buildConfiguration->environment());\n}\n\nQString Qt4ProjectConfigWidget::displayName() const\n{\n return tr(\"General\");\n}\n\nvoid Qt4ProjectConfigWidget::init(ProjectExplorer::BuildConfiguration *bc)\n{\n QTC_ASSERT(bc, return);\n\n if (debug)\n qDebug() << \"Qt4ProjectConfigWidget::init() for\" << bc->displayName();\n\n if (m_buildConfiguration) {\n disconnect(m_buildConfiguration, SIGNAL(buildDirectoryChanged()),\n this, SLOT(buildDirectoryChanged()));\n disconnect(m_buildConfiguration, SIGNAL(qmakeBuildConfigurationChanged()),\n this, SLOT(updateProblemLabel()));\n }\n m_buildConfiguration = static_cast<Qt4BuildConfiguration *>(bc);\n m_ui->shadowBuildDirEdit->setEnvironment(m_buildConfiguration->environment());\n\n connect(m_buildConfiguration, SIGNAL(buildDirectoryChanged()),\n this, SLOT(buildDirectoryChanged()));\n connect(m_buildConfiguration, SIGNAL(qmakeBuildConfigurationChanged()),\n this, SLOT(updateProblemLabel()));\n\n m_ui->shadowBuildDirEdit->setBaseDirectory(m_buildConfiguration->target()->project()->projectDirectory());\n\n buildDirectoryChanged();\n}\n\nvoid Qt4ProjectConfigWidget::buildDirectoryChanged()\n{\n if (m_ignoreChange)\n return;\n m_ui->shadowBuildDirEdit->setPath(m_buildConfiguration->shadowBuildDirectory());\n bool shadowBuild = m_buildConfiguration->shadowBuild();\n m_ui->shadowBuildCheckBox->setChecked(shadowBuild);\n m_ui->shadowBuildDirEdit->setEnabled(shadowBuild);\n m_browseButton->setEnabled(shadowBuild);\n\n updateDetails();\n updateProblemLabel();\n}\n\nvoid Qt4ProjectConfigWidget::onBeforeBeforeShadowBuildDirBrowsed()\n{\n QString initialDirectory = m_buildConfiguration->target()->project()->projectDirectory();\n if (!initialDirectory.isEmpty())\n m_ui->shadowBuildDirEdit->setInitialBrowsePathBackup(initialDirectory);\n}\n\nvoid Qt4ProjectConfigWidget::shadowBuildClicked(bool checked)\n{\n m_ui->shadowBuildDirEdit->setEnabled(checked);\n m_browseButton->setEnabled(checked);\n bool b = m_ui->shadowBuildCheckBox->isChecked();\n\n m_ignoreChange = true;\n m_buildConfiguration->setShadowBuildAndDirectory(b, m_ui->shadowBuildDirEdit->rawPath());\n m_ignoreChange = false;\n\n updateDetails();\n updateProblemLabel();\n}\n\nvoid Qt4ProjectConfigWidget::shadowBuildEdited()\n{\n if (m_buildConfiguration->shadowBuildDirectory() == m_ui->shadowBuildDirEdit->rawPath())\n return;\n m_ignoreChange = true;\n m_buildConfiguration->setShadowBuildAndDirectory(m_buildConfiguration->shadowBuild(), m_ui->shadowBuildDirEdit->rawPath());\n m_ignoreChange = false;\n\n \/\/ if the directory already exists\n \/\/ check if we have a build in there and\n \/\/ offer to import it\n updateProblemLabel();\n updateDetails();\n}\n\nvoid Qt4ProjectConfigWidget::updateProblemLabel()\n{\n bool targetMismatch = false;\n bool incompatibleBuild = false;\n bool allGood = false;\n\n ProjectExplorer::Kit *k = m_buildConfiguration->target()->kit();\n const QString proFileName = m_buildConfiguration->target()->project()->document()->fileName();\n\n QtSupport::BaseQtVersion *version = QtSupport::QtKitInformation::qtVersion(k);\n if (!version) {\n m_ui->problemLabel->setVisible(true);\n m_ui->warningLabel->setVisible(true);\n m_ui->problemLabel->setText(tr(\"This target cannot build this project since it does not define a \"\n \"Qt version.\"));\n return;\n }\n\n \/\/ we only show if we actually have a qmake and makestep\n if (m_buildConfiguration->qmakeStep() && m_buildConfiguration->makeStep()) {\n QString makefile = m_buildConfiguration->buildDirectory() + QLatin1Char('\/');\n if (m_buildConfiguration->makefile().isEmpty())\n makefile.append(QLatin1String(\"Makefile\"));\n else\n makefile.append(m_buildConfiguration->makefile());\n\n switch (m_buildConfiguration->compareToImportFrom(makefile)) {\n case Qt4BuildConfiguration::MakefileMatches:\n allGood = true;\n break;\n case Qt4BuildConfiguration::MakefileMissing:\n allGood = true;\n break;\n case Qt4BuildConfiguration::MakefileIncompatible:\n incompatibleBuild = true;\n break;\n case Qt4BuildConfiguration::MakefileForWrongProject:\n targetMismatch = true;\n break;\n }\n }\n\n QString shadowBuildWarning;\n if (!version->supportsShadowBuilds() && m_buildConfiguration->shadowBuild()) {\n shadowBuildWarning =tr(\"The Qt version %1 does not support shadow builds, building might fail.\")\n .arg(version->displayName())\n + QLatin1String(\"<br>\");\n }\n\n if (allGood) {\n QString buildDirectory = m_buildConfiguration->target()->project()->projectDirectory();;\n if (m_buildConfiguration->shadowBuild())\n buildDirectory = m_buildConfiguration->buildDirectory();\n QList<ProjectExplorer::Task> issues;\n issues = version->reportIssues(proFileName, buildDirectory);\n qSort(issues);\n\n if (issues.isEmpty() && shadowBuildWarning.isEmpty()) {\n m_ui->problemLabel->setVisible(false);\n m_ui->warningLabel->setVisible(false);\n } else {\n m_ui->problemLabel->setVisible(true);\n m_ui->warningLabel->setVisible(true);\n QString text = QLatin1String(\"<nobr>\") + shadowBuildWarning;\n foreach (const ProjectExplorer::Task &task, issues) {\n QString type;\n switch (task.type) {\n case ProjectExplorer::Task::Error:\n type = tr(\"Error:\");\n type += QLatin1Char(' ');\n break;\n case ProjectExplorer::Task::Warning:\n type = tr(\"Warning:\");\n type += QLatin1Char(' ');\n break;\n case ProjectExplorer::Task::Unknown:\n default:\n break;\n }\n if (!text.endsWith(QLatin1String(\"br>\")))\n text.append(QLatin1String(\"<br>\"));\n text.append(type + task.description);\n }\n m_ui->problemLabel->setText(text);\n }\n } else if (targetMismatch) {\n m_ui->problemLabel->setVisible(true);\n m_ui->warningLabel->setVisible(true);\n m_ui->problemLabel->setText(shadowBuildWarning + tr(\"A build for a different project exists in %1, which will be overwritten.\",\n \"%1 build directory\")\n .arg(m_ui->shadowBuildDirEdit->path()));\n } else if (incompatibleBuild) {\n m_ui->warningLabel->setVisible(true);\n m_ui->problemLabel->setVisible(true);\n m_ui->problemLabel->setText(shadowBuildWarning +tr(\"An incompatible build exists in %1, which will be overwritten.\",\n \"%1 build directory\")\n .arg(m_ui->shadowBuildDirEdit->path()));\n } else if (!shadowBuildWarning.isEmpty()) {\n m_ui->warningLabel->setVisible(true);\n m_ui->problemLabel->setVisible(true);\n m_ui->problemLabel->setText(shadowBuildWarning);\n }\n}\n<|endoftext|>"} {"text":"<commit_before>#include <tuple>\n#include <array>\n\n#include \"acmacs-base\/color-modifier.hh\"\n#include \"acmacs-base\/color-hsv.hh\"\n\n\/\/ ----------------------------------------------------------------------\n\nusing en = std::tuple<Color, std::string_view, Color>;\nusing namespace std::string_view_literals;\n\nstatic const std::array test_data{\n en{GREEN, \":s-0.5\", 0x7fff7f},\n en{GREEN, \":s-0.9\", 0xE5FFE5},\n en{TRANSPARENT, \":s-0.5\", TRANSPARENT},\n en{GREEN, \":s0.5\", GREEN},\n en{GREEN, \":s+0.5\", GREEN},\n\n en{BLUE, \":b-0.5\", 0x00007F},\n en{BLUE, \":b-0.9\", 0x000019},\n en{TRANSPARENT, \":b-0.5\", TRANSPARENT},\n en{BLUE, \":b0.5\", BLUE},\n en{BLUE, \":b+0.5\", BLUE},\n\n en{0xAB3838, \":s-0.5\", 0xAB7171},\n en{0xAB3838, \":s-0.9\", 0xAB9F9F},\n en{0xAB3838, \":s+0.5\", 0xAB1B1B},\n en{0xAB3838, \":s0.9\", 0xAB0505},\n en{0x80AB3838, \":s0.9\", 0x80AB0505},\n\n en{0xAB3838, \":b-0.5\", 0x551B1B},\n en{0xAB3838, \":b-0.9\", 0x110505},\n en{0xAB3838, \":b+0.5\", 0xD44545},\n en{0x77AB3838, \":b+0.5\", 0x77D44545},\n en{0xAB3838, \":b0.9\", 0xF65050},\n\n en{0xAB3838, \":t-0.1\", 0xAB3838},\n en{0xAB3838, \":t0.1\", 0x19AB3838},\n\n en{TRANSPARENT, \":s+0.5\", TRANSPARENT},\n en{TRANSPARENT, \":b+0.5\", 0xFF7F7F7F},\n en{TRANSPARENT, \":t+0.5\", TRANSPARENT},\n en{TRANSPARENT, \":t-0.5\", 0x7F000000},\n en{0xFF808080, \":t-0.5\", 0x7F808080},\n\n en{BLACK, \":s-0.5\", BLACK},\n en{BLACK, \":b-0.5\", BLACK},\n en{BLACK, \":t+0.5\", 0x7F000000},\n\n en{BLUE, \":p+0.5\", 0x7F7FFF},\n en{BLACK, \":p+0.5\", 0x7F7F7F},\n en{0x7F7F7F, \":p+0.5\", 0xBFBFBF},\n};\n\nint main()\n{\n int errors{0};\n for (const auto& [source, modifier, expected] : test_data) {\n Color color{source};\n if (acmacs::color::modify(color, modifier) != expected) {\n ++errors;\n AD_ERROR(\"color modifier failed: \\\"{}\\\"({}) + \\\"{}\\\" -> \\\"{}\\\"({}) expected: \\\"{}\\\"({})\", source, acmacs::color::HSV{source}, modifier, color, acmacs::color::HSV{color}, expected,\n acmacs::color::HSV{expected});\n }\n }\n return errors;\n}\n\n\/\/ ----------------------------------------------------------------------\n\/\/\/ Local Variables:\n\/\/\/ eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))\n\/\/\/ End:\n<commit_msg>debugging color modifier<commit_after>#include <tuple>\n#include <array>\n\n#include \"acmacs-base\/color-modifier.hh\"\n#include \"acmacs-base\/color-hsv.hh\"\n\n\/\/ ----------------------------------------------------------------------\n\nusing en = std::tuple<Color, std::string_view, Color>;\nusing namespace std::string_view_literals;\n\nstatic const std::array test_data{\n en{GREEN, \":s-0.5\", 0x7fff7f},\n en{GREEN, \":s-0.9\", 0xE5FFE5},\n en{TRANSPARENT, \":s-0.5\", TRANSPARENT},\n en{GREEN, \":s0.5\", GREEN},\n en{GREEN, \":s+0.5\", GREEN},\n en{0x6495ED, \":s=0.5\", 0x78aaf1},\n\n en{BLUE, \":b-0.5\", 0x00007F},\n en{BLUE, \":b-0.9\", 0x000019},\n en{TRANSPARENT, \":b-0.5\", TRANSPARENT},\n en{BLUE, \":b0.5\", BLUE},\n en{BLUE, \":b+0.5\", BLUE},\n\n en{0xAB3838, \":s-0.5\", 0xAB7171},\n en{0xAB3838, \":s-0.9\", 0xAB9F9F},\n en{0xAB3838, \":s+0.5\", 0xAB1B1B},\n en{0xAB3838, \":s0.9\", 0xAB0505},\n en{0x80AB3838, \":s0.9\", 0x80AB0505},\n\n en{0xAB3838, \":b-0.5\", 0x551B1B},\n en{0xAB3838, \":b-0.9\", 0x110505},\n en{0xAB3838, \":b+0.5\", 0xD44545},\n en{0x77AB3838, \":b+0.5\", 0x77D44545},\n en{0xAB3838, \":b0.9\", 0xF65050},\n\n en{0xAB3838, \":t-0.1\", 0xAB3838},\n en{0xAB3838, \":t0.1\", 0x19AB3838},\n\n en{TRANSPARENT, \":s+0.5\", TRANSPARENT},\n en{TRANSPARENT, \":b+0.5\", 0xFF7F7F7F},\n en{TRANSPARENT, \":t+0.5\", TRANSPARENT},\n en{TRANSPARENT, \":t-0.5\", 0x7F000000},\n en{0xFF808080, \":t-0.5\", 0x7F808080},\n\n en{BLACK, \":s-0.5\", BLACK},\n en{BLACK, \":b-0.5\", BLACK},\n en{BLACK, \":t+0.5\", 0x7F000000},\n\n en{BLUE, \":p+0.5\", 0x7F7FFF},\n en{BLACK, \":p+0.5\", 0x7F7F7F},\n en{0x7F7F7F, \":p+0.5\", 0xBFBFBF},\n};\n\nint main()\n{\n int errors{0};\n for (const auto& [source, modifier, expected] : test_data) {\n Color color{source};\n if (acmacs::color::modify(color, modifier) != expected) {\n ++errors;\n AD_ERROR(\"color modifier failed: \\\"{}\\\"({}) + \\\"{}\\\" -> \\\"{}\\\"({}) expected: \\\"{}\\\"({})\", source, acmacs::color::HSV{source}, modifier, color, acmacs::color::HSV{color}, expected,\n acmacs::color::HSV{expected});\n }\n }\n return errors;\n}\n\n\/\/ ----------------------------------------------------------------------\n\/\/\/ Local Variables:\n\/\/\/ eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))\n\/\/\/ End:\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n#include <string>\n#include <vector>\n#include <tuple>\n\n#include \"acmacs-base\/argv.hh\"\n#include \"acmacs-base\/filesystem.hh\"\n#include \"acmacs-base\/named-type.hh\"\n#include \"acmacs-base\/string.hh\"\n#include \"acmacs-chart-2\/factory-import.hh\"\n#include \"acmacs-chart-2\/chart.hh\"\n\n\/\/ ----------------------------------------------------------------------\n\n\/\/ using namespace acmacs::argv;\n\n\/\/ struct Options : public argv\n\/\/ {\n\/\/ Options(int a_argc, const char* const a_argv[], on_error on_err = on_error::exit) : argv() { parse(a_argc, a_argv, on_err); }\n\n\/\/ argument<str> period{*this, arg_name{\"monthly|yearly|weekly\"}, mandatory};\n\/\/ argument<Date> start{*this, arg_name{\"start-date\"}, mandatory};\n\/\/ argument<Date> end{*this, arg_name{\"end-date\"}, mandatory};\n\/\/ argument<str> output{*this, arg_name{\"output.json\"}, dflt{\"\"}};\n\/\/ };\n\n\/\/ ----------------------------------------------------------------------\n\ninline bool is_acmacs_file(const fs::path& path)\n{\n if (path.extension() == \".ace\")\n return true;\n if (path.extension() == \".bz2\") {\n if (path.stem().extension() == \".acd1\")\n return true;\n }\n return false;\n}\n\n\/\/ ----------------------------------------------------------------------\n\nclass SerumIds\n{\n public:\n using Name = acmacs::chart::Name;\n using Passage = acmacs::chart::Passage;\n using Reassortant = acmacs::chart::Reassortant;\n using Annotations = acmacs::chart::Annotations;\n using SerumId = acmacs::chart::SerumId;\n using SerumIdRoot = acmacs::named_t<std::string, struct SerumIdRootTag>;\n using SerumEntry = std::tuple<Name, Reassortant, Annotations, SerumId, Passage>;\n using TableEntry = std::tuple<acmacs::chart::VirusType, acmacs::chart::Lab, acmacs::chart::Assay, acmacs::chart::RbcSpecies, acmacs::chart::TableDate>;\n using Entry = std::tuple<SerumIdRoot, SerumId, Name, Reassortant, Annotations, acmacs::chart::VirusType, acmacs::chart::Lab, acmacs::chart::Assay, acmacs::chart::RbcSpecies, acmacs::chart::TableDate, Passage>;\n using Entries = std::vector<Entry>;\n using EntryPtr = typename Entries::const_iterator;\n using PerSerumIdEntry = std::tuple<EntryPtr, EntryPtr>;\n using PerSerumIdRootEntry = std::tuple<EntryPtr, EntryPtr, std::vector<PerSerumIdEntry>>;\n using PerSerumIdRootEntries = std::vector<PerSerumIdRootEntry>;\n \n SerumIds() = default;\n\n size_t size() const { return data_.size(); }\n void sort() { std::sort(data_.begin(), data_.end()); \/* data_.erase(std::unique(data_.begin(), data_.end()), data_.end()); *\/ }\n\n void add(const SerumEntry& serum, const TableEntry& table)\n {\n data_.emplace_back(serum_id_root(serum, table), std::get<SerumId>(serum),\n std::get<Name>(serum), std::get<Reassortant>(serum), std::get<Annotations>(serum),\n std::get<acmacs::chart::VirusType>(table), std::get<acmacs::chart::Lab>(table), std::get<acmacs::chart::Assay>(table), std::get<acmacs::chart::RbcSpecies>(table), std::get<acmacs::chart::TableDate>(table),\n std::get<Passage>(serum));\n }\n\n void scan()\n {\n for (EntryPtr entry_ptr = data_.begin(); entry_ptr != data_.end(); ++entry_ptr) {\n if (per_root_.empty() || std::get<SerumIdRoot>(*entry_ptr) != std::get<SerumIdRoot>(*std::get<0>(per_root_.back()))) {\n per_root_.emplace_back(entry_ptr, entry_ptr + 1, std::vector<PerSerumIdEntry>{{entry_ptr, entry_ptr + 1}});\n }\n else {\n std::get<1>(per_root_.back()) = entry_ptr + 1;\n const auto last = std::get<0>(std::get<2>(per_root_.back()).back());\n const auto name = make_name(entry_ptr), name_last = make_name(last);\n if (std::get<SerumId>(*entry_ptr) != std::get<SerumId>(*last) || name != name_last) {\n std::get<2>(per_root_.back()).emplace_back(entry_ptr, entry_ptr + 1);\n }\n else {\n std::get<1>(std::get<2>(per_root_.back()).back()) = entry_ptr + 1;\n }\n }\n }\n std::cout << \"per_root_ \" << per_root_.size() << '\\n';\n }\n\n void print(bool print_good) const\n {\n const bool show_assay = std::get<acmacs::chart::VirusType>(*std::get<0>(per_root_.front())) == \"A(H3N2)\";\n const bool show_rbc = show_assay;\n for (const auto& per_root_entry : per_root_) {\n const auto name = make_name(std::get<0>(per_root_entry)), name_last = make_name(std::get<1>(per_root_entry) - 1);\n if (const bool good = std::get<2>(per_root_entry).size() == 1; !good || print_good) {\n std::cout << std::get<SerumIdRoot>(*std::get<0>(per_root_entry)) << ' ' << (std::get<1>(per_root_entry) - std::get<0>(per_root_entry)) << '\\n';\n for (const auto& per_serum_id_entry : std::get<2>(per_root_entry)) {\n const auto tabs = tables(std::get<0>(per_serum_id_entry), std::get<1>(per_serum_id_entry), show_assay, show_rbc);\n std::cout << \" \" << std::get<SerumId>(*std::get<0>(per_serum_id_entry)) << ' ' << tabs.size()\n << \" [\" << make_name(std::get<0>(per_serum_id_entry)) << ']';\n for (const auto& table : tabs)\n std::cout << ' ' << table;\n std::cout << '\\n';\n }\n if (!good) {\n const auto& sids = std::get<2>(per_root_entry);\n if (std::get<SerumId>(*std::get<0>(sids.front())) != std::get<SerumId>(*std::get<0>(sids.back()))) {\n const auto sid = std::max_element(sids.begin(), sids.end(), [](const auto& e1, const auto& e2) -> bool { return (std::get<1>(e1) - std::get<0>(e1)) < (std::get<1>(e2) - std::get<0>(e2)); });\n for (auto ep = sids.begin(); ep != sids.end(); ++ep) {\n if (ep != sid) {\n const bool same_size = (std::get<1>(*ep) - std::get<0>(*ep)) == (std::get<1>(*sid) - std::get<0>(*sid));\n std::cout << \" \" << (same_size ? \"?? \" : \"\") << \"--fix \" << std::get<SerumId>(*std::get<0>(*ep)) << '^' << std::get<SerumId>(*std::get<0>(*sid)) << '\\n';\n }\n }\n }\n }\n }\n }\n }\n\n private:\n Entries data_;\n PerSerumIdRootEntries per_root_;\n\n SerumIdRoot serum_id_root(const SerumEntry& serum, const TableEntry& table) const\n {\n const auto& serum_id = std::get<SerumId>(serum);\n if (std::get<acmacs::chart::Lab>(table) == \"MELB\") {\n if (serum_id.size() > 6 && (serum_id[0] == 'F' || serum_id[0] == 'R') && serum_id[5] == '-' && serum_id.back() == 'D')\n return SerumIdRoot(serum_id.substr(0, 5));\n else\n return SerumIdRoot(serum_id);\n }\n else\n return SerumIdRoot(serum_id);\n }\n\n static inline std::string make_name(EntryPtr ptr)\n {\n return string::join({std::get<Name>(*ptr), std::get<Reassortant>(*ptr), string::join(\" \", std::get<Annotations>(*ptr))});\n }\n\n static inline std::vector<std::string> tables(EntryPtr first, EntryPtr last, bool assay, bool rbc)\n {\n std::vector<std::string> tables(static_cast<size_t>(last - first));\n std::transform(first, last, tables.begin(), [assay, rbc](const auto& entry) {\n std::vector<std::string> fields;\n if (assay)\n fields.push_back(std::get<acmacs::chart::Assay>(entry));\n if (rbc)\n fields.push_back(std::get<acmacs::chart::RbcSpecies>(entry));\n fields.push_back(std::get<acmacs::chart::TableDate>(entry));\n return string::join(\":\", fields);\n });\n std::reverse(tables.begin(), tables.end());\n return tables;\n }\n\n};\n\n\/\/ ----------------------------------------------------------------------\n\nint main(int \/*argc*\/, const char* \/*argv*\/[])\n{\n int exit_code = 0;\n try {\n \/\/ Options opt(argc, argv);\n SerumIds serum_ids;\n size_t charts_processed = 0;\n for (auto& entry : fs::directory_iterator(\".\")) {\n if (entry.is_regular_file() && is_acmacs_file(entry.path())) {\n \/\/ std::cout << entry.path() << '\\n';\n auto chart = acmacs::chart::import_from_file(entry.path());\n std::tuple table(chart->info()->virus_type(), chart->info()->lab(), chart->info()->assay(), chart->info()->rbc_species(), chart->info()->date());\n auto sera = chart->sera();\n for (auto serum : *sera)\n serum_ids.add({serum->name(), serum->reassortant(), serum->annotations(), serum->serum_id(), serum->passage()}, table);\n \/\/ name_id.emplace_back(serum->designation_without_serum_id(), serum->serum_id(), date);\n ++charts_processed;\n }\n }\n std::cout << charts_processed << \" charts processed\\n\";\n std::cout << serum_ids.size() << \" entries\\n\";\n serum_ids.sort();\n serum_ids.scan();\n \/\/ std::cout << serum_ids.size() << \" entries\\n\";\n serum_ids.print(false);\n \n \/\/ std::vector<std::pair<std::string, std::vector<std::string>>> name_ids;\n \/\/ for (const auto& entry : name_id) {\n \/\/ if (name_ids.empty() || name_ids.back().first != entry.first)\n \/\/ name_ids.emplace_back(entry.first, std::vector<std::string>{entry.second});\n \/\/ else\n \/\/ name_ids.back().second.push_back(entry.second);\n \/\/ }\n \/\/ std::cout << name_ids.size() << \" serum names found\\n\";\n\n \/\/ for (const auto& entry : name_ids) {\n \/\/ std::cout << entry.first << '\\n';\n \/\/ for (const auto& serum_id : entry.second) {\n \/\/ std::cout << \" \" << serum_id;\n \/\/ if (serum_id[0] == 'F' || serum_id[0] == 'R') {\n \/\/ if (serum_id.back() != 'D')\n \/\/ std::cout << \" Warning: FIX!\";\n \/\/ }\n \/\/ else\n \/\/ std::cout << \" Warning: not MELB\";\n \/\/ std::cout << '\\n';\n \/\/ }\n \/\/ }\n }\n catch (std::exception& err) {\n std::cerr << \"ERROR: \" << err.what() << '\\n';\n exit_code = 2;\n }\n return exit_code;\n}\n\n\/\/ ----------------------------------------------------------------------\n\/\/\/ Local Variables:\n\/\/\/ eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))\n\/\/\/ End:\n<commit_msg>scan serum ids of MELB tables<commit_after>#include <iostream>\n#include <string>\n#include <vector>\n#include <tuple>\n\n#include \"acmacs-base\/argv.hh\"\n#include \"acmacs-base\/filesystem.hh\"\n#include \"acmacs-base\/named-type.hh\"\n#include \"acmacs-base\/string.hh\"\n#include \"acmacs-chart-2\/factory-import.hh\"\n#include \"acmacs-chart-2\/chart.hh\"\n\n\/\/ ----------------------------------------------------------------------\n\nclass SerumIds\n{\n public:\n using Name = acmacs::chart::Name;\n using Passage = acmacs::chart::Passage;\n using Reassortant = acmacs::chart::Reassortant;\n using Annotations = acmacs::chart::Annotations;\n using SerumId = acmacs::chart::SerumId;\n using SerumIdRoot = acmacs::named_t<std::string, struct SerumIdRootTag>;\n using SerumEntry = std::tuple<Name, Reassortant, Annotations, SerumId, Passage>;\n using TableEntry = std::tuple<acmacs::chart::VirusType, acmacs::chart::Lab, acmacs::chart::Assay, acmacs::chart::RbcSpecies, acmacs::chart::TableDate>;\n using Entry = std::tuple<SerumIdRoot, SerumId, Name, Reassortant, Annotations, acmacs::chart::VirusType, acmacs::chart::Lab, acmacs::chart::Assay, acmacs::chart::RbcSpecies, acmacs::chart::TableDate, Passage>;\n using Entries = std::vector<Entry>;\n using EntryPtr = typename Entries::const_iterator;\n using PerSerumIdEntry = std::tuple<EntryPtr, EntryPtr>;\n using PerSerumIdRootEntry = std::tuple<EntryPtr, EntryPtr, std::vector<PerSerumIdEntry>>;\n using PerSerumIdRootEntries = std::vector<PerSerumIdRootEntry>;\n \n SerumIds() = default;\n\n size_t size() const { return data_.size(); }\n void sort() { std::sort(data_.begin(), data_.end()); \/* data_.erase(std::unique(data_.begin(), data_.end()), data_.end()); *\/ }\n\n void add(const SerumEntry& serum, const TableEntry& table)\n {\n data_.emplace_back(serum_id_root(serum, table), std::get<SerumId>(serum),\n std::get<Name>(serum), std::get<Reassortant>(serum), std::get<Annotations>(serum),\n std::get<acmacs::chart::VirusType>(table), std::get<acmacs::chart::Lab>(table), std::get<acmacs::chart::Assay>(table), std::get<acmacs::chart::RbcSpecies>(table), std::get<acmacs::chart::TableDate>(table),\n std::get<Passage>(serum));\n }\n\n void scan()\n {\n for (EntryPtr entry_ptr = data_.begin(); entry_ptr != data_.end(); ++entry_ptr) {\n if (per_root_.empty() || std::get<SerumIdRoot>(*entry_ptr) != std::get<SerumIdRoot>(*std::get<0>(per_root_.back()))) {\n per_root_.emplace_back(entry_ptr, entry_ptr + 1, std::vector<PerSerumIdEntry>{{entry_ptr, entry_ptr + 1}});\n }\n else {\n std::get<1>(per_root_.back()) = entry_ptr + 1;\n const auto last = std::get<0>(std::get<2>(per_root_.back()).back());\n const auto name = make_name(entry_ptr), name_last = make_name(last);\n if (std::get<SerumId>(*entry_ptr) != std::get<SerumId>(*last) || name != name_last) {\n std::get<2>(per_root_.back()).emplace_back(entry_ptr, entry_ptr + 1);\n }\n else {\n std::get<1>(std::get<2>(per_root_.back()).back()) = entry_ptr + 1;\n }\n }\n }\n std::cout << \"per_root_ \" << per_root_.size() << '\\n';\n }\n\n void print(bool print_good) const\n {\n const bool show_assay = std::get<acmacs::chart::VirusType>(*std::get<0>(per_root_.front())) == \"A(H3N2)\";\n const bool show_rbc = show_assay;\n for (const auto& per_root_entry : per_root_) {\n const auto name = make_name(std::get<0>(per_root_entry)), name_last = make_name(std::get<1>(per_root_entry) - 1);\n if (const bool good = std::get<2>(per_root_entry).size() == 1; !good || print_good) {\n std::cout << std::get<SerumIdRoot>(*std::get<0>(per_root_entry)) << ' ' << (std::get<1>(per_root_entry) - std::get<0>(per_root_entry)) << '\\n';\n for (const auto& per_serum_id_entry : std::get<2>(per_root_entry)) {\n const auto tabs = tables(std::get<0>(per_serum_id_entry), std::get<1>(per_serum_id_entry), show_assay, show_rbc);\n std::cout << \" \" << std::get<SerumId>(*std::get<0>(per_serum_id_entry)) << ' ' << tabs.size()\n << \" [\" << make_name(std::get<0>(per_serum_id_entry)) << ']';\n for (const auto& table : tabs)\n std::cout << ' ' << table;\n std::cout << '\\n';\n }\n if (!good) {\n const auto& sids = std::get<2>(per_root_entry);\n if (std::get<SerumId>(*std::get<0>(sids.front())) != std::get<SerumId>(*std::get<0>(sids.back()))) {\n const auto sid = std::max_element(sids.begin(), sids.end(), [](const auto& e1, const auto& e2) -> bool { return (std::get<1>(e1) - std::get<0>(e1)) < (std::get<1>(e2) - std::get<0>(e2)); });\n for (auto ep = sids.begin(); ep != sids.end(); ++ep) {\n if (ep != sid) {\n const bool same_size = (std::get<1>(*ep) - std::get<0>(*ep)) == (std::get<1>(*sid) - std::get<0>(*sid));\n std::cout << \" \" << (same_size ? \"?? \" : \"\") << \"--fix \" << std::get<SerumId>(*std::get<0>(*ep)) << '^' << std::get<SerumId>(*std::get<0>(*sid)) << '\\n';\n }\n }\n }\n }\n }\n }\n }\n\n private:\n Entries data_;\n PerSerumIdRootEntries per_root_;\n\n SerumIdRoot serum_id_root(const SerumEntry& serum, const TableEntry& table) const\n {\n const auto& serum_id = std::get<SerumId>(serum);\n if (std::get<acmacs::chart::Lab>(table) == \"MELB\") {\n if (serum_id.size() > 6 && (serum_id[0] == 'F' || serum_id[0] == 'R') && serum_id[5] == '-' && serum_id.back() == 'D')\n return SerumIdRoot(serum_id.substr(0, 5));\n else\n return SerumIdRoot(serum_id);\n }\n else\n return SerumIdRoot(serum_id);\n }\n\n static inline std::string make_name(EntryPtr ptr)\n {\n return string::join({std::get<Name>(*ptr), std::get<Reassortant>(*ptr), string::join(\" \", std::get<Annotations>(*ptr))});\n }\n\n static inline std::vector<std::string> tables(EntryPtr first, EntryPtr last, bool assay, bool rbc)\n {\n std::vector<std::string> tables(static_cast<size_t>(last - first));\n std::transform(first, last, tables.begin(), [assay, rbc](const auto& entry) {\n std::vector<std::string> fields;\n if (assay)\n fields.push_back(std::get<acmacs::chart::Assay>(entry));\n if (rbc)\n fields.push_back(std::get<acmacs::chart::RbcSpecies>(entry));\n fields.push_back(std::get<acmacs::chart::TableDate>(entry));\n return string::join(\":\", fields);\n });\n std::reverse(tables.begin(), tables.end());\n return tables;\n }\n\n};\n\n\/\/ ----------------------------------------------------------------------\n\ninline bool is_acmacs_file(const fs::path& path)\n{\n if (path.extension() == \".ace\")\n return true;\n if (path.extension() == \".bz2\") {\n if (path.stem().extension() == \".acd1\")\n return true;\n }\n return false;\n}\n\n\/\/ ----------------------------------------------------------------------\n\nusing namespace acmacs::argv;\n\nstruct Options : public argv\n{\n Options(int a_argc, const char* const a_argv[], on_error on_err = on_error::exit) : argv() { parse(a_argc, a_argv, on_err); }\n\n option<str> fix{*this, \"fix\", dflt{\"\"}};\n \/\/ argument<str> period{*this, arg_name{\"monthly|yearly|weekly\"}, mandatory};\n \/\/ argument<Date> start{*this, arg_name{\"start-date\"}, mandatory};\n \/\/ argument<Date> end{*this, arg_name{\"end-date\"}, mandatory};\n \/\/ argument<str> output{*this, arg_name{\"output.json\"}, dflt{\"\"}};\n};\n\n\/\/ ----------------------------------------------------------------------\n\nint main(int argc, const char* argv[])\n{\n int exit_code = 0;\n try {\n Options opt(argc, argv);\n SerumIds serum_ids;\n size_t charts_processed = 0;\n for (auto& entry : fs::directory_iterator(\".\")) {\n if (entry.is_regular_file() && is_acmacs_file(entry.path())) {\n \/\/ std::cout << entry.path() << '\\n';\n auto chart = acmacs::chart::import_from_file(entry.path());\n if (!opt.fix.has_value()) { \/\/ scan\n std::tuple table(chart->info()->virus_type(), chart->info()->lab(), chart->info()->assay(), chart->info()->rbc_species(), chart->info()->date());\n auto sera = chart->sera();\n for (auto serum : *sera)\n serum_ids.add({serum->name(), serum->reassortant(), serum->annotations(), serum->serum_id(), serum->passage()}, table);\n }\n else { \/\/ fix\n std::cerr << \"FIX\\n\";\n }\n ++charts_processed;\n }\n }\n std::cout << charts_processed << \" charts processed\\n\";\n std::cout << serum_ids.size() << \" entries\\n\";\n serum_ids.sort();\n serum_ids.scan();\n \/\/ std::cout << serum_ids.size() << \" entries\\n\";\n serum_ids.print(false);\n }\n catch (std::exception& err) {\n std::cerr << \"ERROR: \" << err.what() << '\\n';\n exit_code = 2;\n }\n return exit_code;\n}\n\n\/\/ ----------------------------------------------------------------------\n\/\/\/ Local Variables:\n\/\/\/ eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))\n\/\/\/ End:\n<|endoftext|>"} {"text":"<commit_before>#include \"login.h\"\n#include \"mainwindow.h\"\n\nextern QMdiArea *emarea;\n\nLoginDialog::LoginDialog(QWidget *parent) :\n\tQDialog(parent)\n{\n setUpGUI();\n setWindowTitle( tr(\"User Login\") );\n setModal( true );\n subwindow = emarea->addSubWindow(this, windowType());\n}\n\nvoid LoginDialog::setUpGUI(){\n \/\/ set up the layout\n QGridLayout* formGridLayout = new QGridLayout( this );\n\n \/\/ initialize the username combo box so that it is editable\n comboUsername = new QComboBox( this );\n comboUsername->setEditable( true );\n \/\/ initialize the password field so that it does not echo\n \/\/ characters\n editPassword = new QLineEdit( this );\n editPassword->setEchoMode( QLineEdit::Password );\n\n \/\/ initialize the labels\n labelUsername = new QLabel( this );\n labelPassword = new QLabel( this );\n labelUsername->setText( tr( \"Username\" ) );\n labelUsername->setBuddy( comboUsername );\n labelPassword->setText( tr( \"Password\" ) );\n labelPassword->setBuddy( editPassword );\n\n\n\n \/\/ initialize buttons\n buttons = new QDialogButtonBox( this );\n buttons->addButton( QDialogButtonBox::Ok );\n buttons->addButton( QDialogButtonBox::Cancel );\n buttons->button( QDialogButtonBox::Ok )->setText( tr(\"Login\") );\n buttons->button( QDialogButtonBox::Cancel )->setText( tr(\"Abort\") );\n\n \/\/ connects slots\n connect( buttons->button( QDialogButtonBox::Cancel ),\n SIGNAL(clicked()),\n this,\n SLOT(close())\n );\n\n connect( buttons->button( QDialogButtonBox::Ok ),\n SIGNAL(clicked()),\n this,\n SLOT(slotAcceptLogin()) );\n\n \/\/ place components into the dialog\n formGridLayout->addWidget( labelUsername, 0, 0 );\n formGridLayout->addWidget( comboUsername, 0, 1 );\n formGridLayout->addWidget( labelPassword, 1, 0 );\n formGridLayout->addWidget( editPassword, 1, 1 );\n formGridLayout->addWidget( buttons, 2, 0, 1, 2 );\n\n setLayout( formGridLayout );\n}\n\n\nvoid LoginDialog::setUsername(QString &username){\n bool found = false;\n for( int i = 0; i < comboUsername->count() && ! found ; i++ )\n if( comboUsername->itemText( i ) == username ){\n comboUsername->setCurrentIndex( i );\n found = true;\n }\n\n if( ! found ){\n int index = comboUsername->count();\n qDebug() << \"Select username \" << index;\n comboUsername->addItem( username );\n\n comboUsername->setCurrentIndex( index );\n }\n\n \/\/ place the focus on the password field\n editPassword->setFocus();\n}\n\n\nvoid LoginDialog::setPassword(QString &password){\n editPassword->setText( password );\n}\n\nvoid LoginDialog::slotAcceptLogin(){\n QString username = comboUsername->currentText();\n QString password = editPassword->text();\n int index = comboUsername->currentIndex();\n\n emit acceptLogin( username, \/\/ current username\n password, \/\/ current password\n index \/\/ index in the username list\n );\n\n \/\/ close this dialog\n close();\n}\n\n\nvoid LoginDialog::setUsernamesList(const QStringList &usernames){\n comboUsername->addItems( usernames );\n}\n<commit_msg>login: get uname and passwd<commit_after>#include \"login.h\"\n#include \"mainwindow.h\"\n\nextern QMdiArea *emarea;\n\nLoginDialog::LoginDialog(QWidget *parent) :\n\tQDialog(parent)\n{\n setUpGUI();\n setWindowTitle( tr(\"User Login\") );\n setModal( true );\n subwindow = emarea->addSubWindow(this, windowType());\n}\n\nvoid LoginDialog::setUpGUI(){\n \/\/ set up the layout\n QGridLayout* formGridLayout = new QGridLayout( this );\n\n \/\/ initialize the username combo box so that it is editable\n comboUsername = new QComboBox( this );\n comboUsername->setEditable( true );\n \/\/ initialize the password field so that it does not echo\n \/\/ characters\n editPassword = new QLineEdit( this );\n editPassword->setEchoMode( QLineEdit::Password );\n\n \/\/ initialize the labels\n labelUsername = new QLabel( this );\n labelPassword = new QLabel( this );\n labelUsername->setText( tr( \"Username\" ) );\n labelUsername->setBuddy( comboUsername );\n labelPassword->setText( tr( \"Password\" ) );\n labelPassword->setBuddy( editPassword );\n\n\n\n \/\/ initialize buttons\n buttons = new QDialogButtonBox( this );\n buttons->addButton( QDialogButtonBox::Ok );\n buttons->addButton( QDialogButtonBox::Cancel );\n buttons->button( QDialogButtonBox::Ok )->setText( tr(\"Login\") );\n buttons->button( QDialogButtonBox::Cancel )->setText( tr(\"Abort\") );\n\n \/\/ connects slots\n connect( buttons->button( QDialogButtonBox::Cancel ),\n SIGNAL(clicked()),\n this,\n SLOT(close())\n );\n\n connect( buttons->button( QDialogButtonBox::Ok ),\n SIGNAL(clicked()),\n this,\n SLOT(slotAcceptLogin()) );\n\n \/\/ place components into the dialog\n formGridLayout->addWidget( labelUsername, 0, 0 );\n formGridLayout->addWidget( comboUsername, 0, 1 );\n formGridLayout->addWidget( labelPassword, 1, 0 );\n formGridLayout->addWidget( editPassword, 1, 1 );\n formGridLayout->addWidget( buttons, 2, 0, 1, 2 );\n\n setLayout( formGridLayout );\n}\n\n\nvoid LoginDialog::setUsername(QString &username){\n bool found = false;\n for( int i = 0; i < comboUsername->count() && ! found ; i++ )\n if( comboUsername->itemText( i ) == username ){\n comboUsername->setCurrentIndex( i );\n found = true;\n }\n\n if( ! found ){\n int index = comboUsername->count();\n qDebug() << \"Select username \" << index;\n comboUsername->addItem( username );\n\n comboUsername->setCurrentIndex( index );\n }\n\n \/\/ place the focus on the password field\n editPassword->setFocus();\n}\n\n\nvoid LoginDialog::setPassword(QString &password){\n editPassword->setText( password );\n}\n\nvoid LoginDialog::slotAcceptLogin(){\n QString username = comboUsername->currentText();\n QString password = editPassword->text();\n int index = comboUsername->currentIndex();\n\n char *uname = username.toAscii().data();\n char *pwd = password.toAscii().data();\n\n emit acceptLogin( username, \/\/ current username\n password, \/\/ current password\n index \/\/ index in the username list\n );\n\n \/\/ close this dialog\n close();\n}\n\nvoid LoginDialog::setUsernamesList(const QStringList &usernames){\n comboUsername->addItems( usernames );\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"entitySystem.h\"\n#include \"systems\/movementsystem.h\"\n#include \"systems\/updatesystem.h\"\n#include \"systems\/chatsystem.h\"\n#include \"systems\/inventorysystem.h\"\n#include \"systems\/partysystem.h\"\n#include \"database.h\"\n\nusing namespace RoseCommon;\n\nEntitySystem::EntitySystem() : systemManager_(*this) {\n systemManager_.add<Systems::MovementSystem>();\n systemManager_.add<Systems::UpdateSystem>();\n systemManager_.add<Systems::ChatSystem>();\n systemManager_.add<Systems::InventorySystem>();\n systemManager_.add<Systems::PartySystem>();\n}\n\nEntityManager &EntitySystem::getEntityManager() {\n return entityManager_;\n}\n\nvoid EntitySystem::registerEntity(Entity entity) {\n if (!entity)\n return;\n auto basic = entity.component<BasicInfo>();\n if (!basic || basic->name_ == \"\" || !basic->id_)\n return;\n nameToEntity_[basic->name_] = entity;\n idToEntity_[basic->id_] = entity;\n}\n\nEntity EntitySystem::getEntity(const std::string &name) {\n return nameToEntity_[name];\n}\n\nEntity EntitySystem::getEntity(uint32_t charId) {\n return idToEntity_[charId];\n}\n\nvoid EntitySystem::update(double dt) {\n systemManager_.update(dt);\n for (auto it : toDestroy_) {\n if (it)\n it.destroy();\n }\n toDestroy_.clear();\n}\n\nvoid EntitySystem::destroy(Entity entity) {\n if (!entity)\n return;\n if (entity.component<SocketConnector>())\n entity.remove<SocketConnector>();\n toDestroy_.push_back(entity);\n}\n\nEntity EntitySystem::create() {\n Entity entity = entityManager_.create();\n return entity;\n}\n\nbool EntitySystem::isNearby(Entity a, Entity b) {\n return true; \/\/ FIXME : actually implement the sight calculation instead of the distance\n if (!a || !b)\n return false;\n auto posa = a.component<Position>();\n auto posb = b.component<Position>();\n if (!posa || !posb)\n return false; \/\/ FIXME : is it a bug if there is no position?\n if (posa->map_ != posb->map_)\n return false;\n double dist = (posa->x_ - posb->x_) * (posa->x_ - posb->x_) + (posa->y_ - posb->y_) * (posa->y_ - posb->y_);\n if (dist > NEARBY_DIST)\n return false;\n return true;\n}\n\nbool EntitySystem::dispatch(Entity entity, const RoseCommon::CRosePacket &packet) {\n if (!entity)\n return false;\n return systemManager_.dispatch(entity, packet);\n}\n\nEntity EntitySystem::loadCharacter(uint32_t charId, bool platinium, uint32_t id) {\n auto &database = Core::databasePool.getDatabase();\n auto res = database.QStore(fmt::format(\"CALL get_character({});\", charId));\n auto entity = create();\n if (!res || res->size() != 1) {\n entity.destroy();\n return Entity();\n }\n auto pos = entity.assign<Position>();\n res->getFloat(\"x\", pos->x_);\n res->getFloat(\"y\", pos->y_);\n res->getInt(\"map\", pos->map_);\n res->getInt(\"revive_map\", pos->spawn_);\n\n auto basic = entity.assign<BasicInfo>();\n res->getString(\"name\", basic->name_);\n res->getInt(\"exp\", basic->xp_);\n res->getInt(\"level\", basic->level_);\n basic->id_ = id;\n basic->tag_ = id;\n\n auto stats = entity.assign<Stats>();\n res->getInt(\"max_hp\", stats->maxHp_);\n res->getInt(\"max_mp\", stats->maxMp_);\n res->getInt(\"str\", stats->str_);\n res->getInt(\"dex\", stats->dex_);\n res->getInt(\"int_\", stats->int_);\n res->getInt(\"con\", stats->con_);\n res->getInt(\"charm\", stats->charm_);\n res->getInt(\"sense\", stats->sense_);\n\n auto advanced = entity.assign<AdvancedInfo>();\n res->getInt(\"zuly\", advanced->zuly_);\n res->getInt(\"current_hp\", advanced->hp_);\n res->getInt(\"current_mp\", advanced->mp_);\n\n auto graphics = entity.assign<CharacterGraphics>();\n res->getInt(\"face\", graphics->face_);\n res->getInt(\"hair\", graphics->hair_);\n res->getInt(\"race\", graphics->race_);\n\n auto info = entity.assign<CharacterInfo>();\n res->getInt(\"job\", info->job_);\n res->getInt(\"stone\", info->stone_);\n res->getInt(\"stat_points\", info->statPoints_);\n res->getInt(\"skill_points\", info->skillPoints_);\n res->getInt(\"penalty_exp\", info->penaltyXp_);\n res->getInt(\"delete_date\", info->deleteDate_);\n info->platinium_ = platinium;\n res->getInt(\"factionid\", info->factionId_);\n res->getInt(\"faction_rank\", info->factionRank_);\n res->getInt(\"fame\", info->fame_);\n res->getInt(\"faction_fame1\", info->factionFame_[0]);\n res->getInt(\"faction_fame2\", info->factionFame_[1]);\n res->getInt(\"faction_points1\", info->factionPoints_[0]);\n res->getInt(\"faction_points2\", info->factionPoints_[1]);\n res->getInt(\"faction_points3\", info->factionPoints_[2]);\n res->getInt(\"clanid\", info->guildId_);\n res->getInt(\"clan_contribution\", info->guildContribution_);\n res->getInt(\"clan_rank\", info->guildRank_);\n res->getInt(\"pk_flag\", info->pkFlag_);\n res->getInt(\"stamina\", info->stamina_);\n\n \/\/ TODO : write the pat initialization code\n auto skills = entity.assign<Skills>();\n auto sks = database.QStore(fmt::format(\"SELECT id, level from skill where char_id = {};\", charId));\n if (sks) {\n size_t i = 0;\n for (auto &sk : *sks) {\n if (i >= 120)\n break;\n sk->getInt(\"id\", skills->skills_[i].id_);\n sk->getInt(\"level\", skills->skills_[i].level_);\n ++i;\n }\n }\n\n \/\/ TODO : write the hotbar table and loading code\n entity.assign<Hotbar>();\n\n entity.assign<StatusEffects>();\n entity.assign<RidingItems>();\n entity.assign<BulletItems>();\n\n \/\/ TODO : write the inventory code\n auto inventory = entity.assign<Inventory>();\n res = database.QStore(fmt::format(\"CALL get_inventory({});\", charId));\n if (!res) {\n entity.destroy();\n return Entity();\n }\n for (auto &it : *res) {\n size_t slot;\n it->getInt(\"slot\", slot);\n if (slot >= Inventory::maxItems)\n continue; \/\/ TODO : add a warning about that slot\n inventory->items_[slot].loadFromDatabase(*it);\n }\n Systems::UpdateSystem::calculateSpeed(entity);\n\n registerEntity(entity);\n return entity;\n}\n\nvoid EntitySystem::saveCharacter(uint32_t charId, Entity entity) {\n if (!entity)\n return;\n (void)charId;\n}\n<commit_msg>Updated code as per reviewed<commit_after>#include \"entitySystem.h\"\n#include \"systems\/movementsystem.h\"\n#include \"systems\/updatesystem.h\"\n#include \"systems\/chatsystem.h\"\n#include \"systems\/inventorysystem.h\"\n#include \"systems\/partysystem.h\"\n#include \"database.h\"\n\nusing namespace RoseCommon;\n\nEntitySystem::EntitySystem() : systemManager_(*this) {\n systemManager_.add<Systems::MovementSystem>();\n systemManager_.add<Systems::UpdateSystem>();\n systemManager_.add<Systems::ChatSystem>();\n systemManager_.add<Systems::InventorySystem>();\n systemManager_.add<Systems::PartySystem>();\n}\n\nEntityManager &EntitySystem::getEntityManager() {\n return entityManager_;\n}\n\nvoid EntitySystem::registerEntity(Entity entity) {\n if (!entity)\n return;\n auto basic = entity.component<BasicInfo>();\n if (!basic || basic->name_ == \"\" || !basic->id_)\n return;\n nameToEntity_[basic->name_] = entity;\n idToEntity_[basic->id_] = entity;\n}\n\nEntity EntitySystem::getEntity(const std::string &name) {\n return nameToEntity_[name];\n}\n\nEntity EntitySystem::getEntity(uint32_t charId) {\n return idToEntity_[charId];\n}\n\nvoid EntitySystem::update(double dt) {\n systemManager_.update(dt);\n for (auto it : toDestroy_) {\n if (it)\n it.destroy();\n }\n toDestroy_.clear();\n}\n\nvoid EntitySystem::destroy(Entity entity) {\n if (!entity)\n return;\n if (entity.component<SocketConnector>())\n entity.remove<SocketConnector>();\n toDestroy_.push_back(entity);\n}\n\nEntity EntitySystem::create() {\n return entityManager_.create();\n}\n\nbool EntitySystem::isNearby(Entity a, Entity b) {\n return true; \/\/ FIXME : actually implement the sight calculation instead of the distance\n if (!a || !b)\n return false;\n auto posa = a.component<Position>();\n auto posb = b.component<Position>();\n if (!posa || !posb)\n return false; \/\/ FIXME : is it a bug if there is no position?\n if (posa->map_ != posb->map_)\n return false;\n double dist = (posa->x_ - posb->x_) * (posa->x_ - posb->x_) + (posa->y_ - posb->y_) * (posa->y_ - posb->y_);\n if (dist > NEARBY_DIST)\n return false;\n return true;\n}\n\nbool EntitySystem::dispatch(Entity entity, const RoseCommon::CRosePacket &packet) {\n if (!entity)\n return false;\n return systemManager_.dispatch(entity, packet);\n}\n\nEntity EntitySystem::loadCharacter(uint32_t charId, bool platinium, uint32_t id) {\n auto &database = Core::databasePool.getDatabase();\n auto res = database.QStore(fmt::format(\"CALL get_character({});\", charId));\n auto entity = create();\n if (!res || res->size() != 1) {\n entity.destroy();\n return Entity();\n }\n auto pos = entity.assign<Position>();\n res->getFloat(\"x\", pos->x_);\n res->getFloat(\"y\", pos->y_);\n res->getInt(\"map\", pos->map_);\n res->getInt(\"revive_map\", pos->spawn_);\n\n auto basic = entity.assign<BasicInfo>();\n res->getString(\"name\", basic->name_);\n res->getInt(\"exp\", basic->xp_);\n res->getInt(\"level\", basic->level_);\n basic->id_ = id;\n basic->tag_ = id;\n\n auto stats = entity.assign<Stats>();\n res->getInt(\"max_hp\", stats->maxHp_);\n res->getInt(\"max_mp\", stats->maxMp_);\n res->getInt(\"str\", stats->str_);\n res->getInt(\"dex\", stats->dex_);\n res->getInt(\"int_\", stats->int_);\n res->getInt(\"con\", stats->con_);\n res->getInt(\"charm\", stats->charm_);\n res->getInt(\"sense\", stats->sense_);\n\n auto advanced = entity.assign<AdvancedInfo>();\n res->getInt(\"zuly\", advanced->zuly_);\n res->getInt(\"current_hp\", advanced->hp_);\n res->getInt(\"current_mp\", advanced->mp_);\n\n auto graphics = entity.assign<CharacterGraphics>();\n res->getInt(\"face\", graphics->face_);\n res->getInt(\"hair\", graphics->hair_);\n res->getInt(\"race\", graphics->race_);\n\n auto info = entity.assign<CharacterInfo>();\n res->getInt(\"job\", info->job_);\n res->getInt(\"stone\", info->stone_);\n res->getInt(\"stat_points\", info->statPoints_);\n res->getInt(\"skill_points\", info->skillPoints_);\n res->getInt(\"penalty_exp\", info->penaltyXp_);\n res->getInt(\"delete_date\", info->deleteDate_);\n info->platinium_ = platinium;\n res->getInt(\"factionid\", info->factionId_);\n res->getInt(\"faction_rank\", info->factionRank_);\n res->getInt(\"fame\", info->fame_);\n res->getInt(\"faction_fame1\", info->factionFame_[0]);\n res->getInt(\"faction_fame2\", info->factionFame_[1]);\n res->getInt(\"faction_points1\", info->factionPoints_[0]);\n res->getInt(\"faction_points2\", info->factionPoints_[1]);\n res->getInt(\"faction_points3\", info->factionPoints_[2]);\n res->getInt(\"clanid\", info->guildId_);\n res->getInt(\"clan_contribution\", info->guildContribution_);\n res->getInt(\"clan_rank\", info->guildRank_);\n res->getInt(\"pk_flag\", info->pkFlag_);\n res->getInt(\"stamina\", info->stamina_);\n\n \/\/ TODO : write the pat initialization code\n auto skills = entity.assign<Skills>();\n auto sks = database.QStore(fmt::format(\"SELECT id, level from skill where char_id = {};\", charId));\n if (sks) {\n size_t i = 0;\n for (auto &sk : *sks) {\n if (i >= 120)\n break;\n sk->getInt(\"id\", skills->skills_[i].id_);\n sk->getInt(\"level\", skills->skills_[i].level_);\n ++i;\n }\n }\n\n \/\/ TODO : write the hotbar table and loading code\n entity.assign<Hotbar>();\n\n entity.assign<StatusEffects>();\n entity.assign<RidingItems>();\n entity.assign<BulletItems>();\n\n \/\/ TODO : write the inventory code\n auto inventory = entity.assign<Inventory>();\n res = database.QStore(fmt::format(\"CALL get_inventory({});\", charId));\n if (!res) {\n entity.destroy();\n return Entity();\n }\n for (auto &it : *res) {\n size_t slot;\n it->getInt(\"slot\", slot);\n if (slot >= Inventory::maxItems)\n continue; \/\/ TODO : add a warning about that slot\n inventory->items_[slot].loadFromDatabase(*it);\n }\n Systems::UpdateSystem::calculateSpeed(entity);\n\n registerEntity(entity);\n return entity;\n}\n\nvoid EntitySystem::saveCharacter(uint32_t charId, Entity entity) {\n if (!entity)\n return;\n (void)charId;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 2012-2014 ARM Limited\n * All rights reserved\n *\n * The license below extends only to copyright in the software and shall\n * not be construed as granting a license to any other intellectual\n * property including but not limited to intellectual property relating\n * to a hardware implementation of the functionality of the software\n * licensed hereunder. You may use the software subject to the license\n * terms below provided that you ensure that this notice is replicated\n * unmodified and in its entirety in all distributions of the software,\n * modified or unmodified, in source code or in binary form.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met: redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer;\n * redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution;\n * neither the name of the copyright holders nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n * Authors: Andrew Bardsley\n *\/\n\n#include \"arch\/utility.hh\"\n#include \"cpu\/minor\/cpu.hh\"\n#include \"cpu\/minor\/dyn_inst.hh\"\n#include \"cpu\/minor\/fetch1.hh\"\n#include \"cpu\/minor\/pipeline.hh\"\n#include \"debug\/Drain.hh\"\n#include \"debug\/MinorCPU.hh\"\n#include \"debug\/Quiesce.hh\"\n\nMinorCPU::MinorCPU(MinorCPUParams *params) :\n BaseCPU(params)\n{\n \/* This is only written for one thread at the moment *\/\n Minor::MinorThread *thread;\n\n if (FullSystem) {\n thread = new Minor::MinorThread(this, 0, params->system, params->itb,\n params->dtb, params->isa[0]);\n } else {\n \/* thread_id 0 *\/\n thread = new Minor::MinorThread(this, 0, params->system,\n params->workload[0], params->itb, params->dtb, params->isa[0]);\n }\n\n threads.push_back(thread);\n\n thread->setStatus(ThreadContext::Halted);\n\n ThreadContext *tc = thread->getTC();\n\n if (params->checker) {\n fatal(\"The Minor model doesn't support checking (yet)\\n\");\n }\n\n threadContexts.push_back(tc);\n\n Minor::MinorDynInst::init();\n\n pipeline = new Minor::Pipeline(*this, *params);\n activityRecorder = pipeline->getActivityRecorder();\n}\n\nMinorCPU::~MinorCPU()\n{\n delete pipeline;\n\n for (ThreadID thread_id = 0; thread_id < threads.size(); thread_id++) {\n delete threads[thread_id];\n }\n}\n\nvoid\nMinorCPU::init()\n{\n BaseCPU::init();\n\n if (!params()->switched_out &&\n system->getMemoryMode() != Enums::timing)\n {\n fatal(\"The Minor CPU requires the memory system to be in \"\n \"'timing' mode.\\n\");\n }\n\n \/* Initialise the ThreadContext's memory proxies *\/\n for (ThreadID thread_id = 0; thread_id < threads.size(); thread_id++) {\n ThreadContext *tc = getContext(thread_id);\n\n tc->initMemProxies(tc);\n }\n\n \/* Initialise CPUs (== threads in the ISA) *\/\n if (FullSystem && !params()->switched_out) {\n for (ThreadID thread_id = 0; thread_id < threads.size(); thread_id++)\n {\n ThreadContext *tc = getContext(thread_id);\n\n \/* Initialize CPU, including PC *\/\n TheISA::initCPU(tc, cpuId());\n }\n }\n}\n\n\/** Stats interface from SimObject (by way of BaseCPU) *\/\nvoid\nMinorCPU::regStats()\n{\n BaseCPU::regStats();\n stats.regStats(name(), *this);\n pipeline->regStats();\n}\n\nvoid\nMinorCPU::serializeThread(CheckpointOut &cp, ThreadID thread_id) const\n{\n threads[thread_id]->serialize(cp);\n}\n\nvoid\nMinorCPU::unserializeThread(CheckpointIn &cp, ThreadID thread_id)\n{\n if (thread_id != 0)\n fatal(\"Trying to load more than one thread into a MinorCPU\\n\");\n\n threads[thread_id]->unserialize(cp);\n}\n\nvoid\nMinorCPU::serialize(CheckpointOut &cp) const\n{\n pipeline->serialize(cp);\n BaseCPU::serialize(cp);\n}\n\nvoid\nMinorCPU::unserialize(CheckpointIn &cp)\n{\n pipeline->unserialize(cp);\n BaseCPU::unserialize(cp);\n}\n\nAddr\nMinorCPU::dbg_vtophys(Addr addr)\n{\n \/* Note that this gives you the translation for thread 0 *\/\n panic(\"No implementation for vtophy\\n\");\n\n return 0;\n}\n\nvoid\nMinorCPU::wakeup()\n{\n DPRINTF(Drain, \"MinorCPU wakeup\\n\");\n\n for (auto i = threads.begin(); i != threads.end(); i ++) {\n if ((*i)->status() == ThreadContext::Suspended)\n (*i)->activate();\n }\n\n DPRINTF(Drain,\"Suspended Processor awoke\\n\");\n}\n\nvoid\nMinorCPU::startup()\n{\n DPRINTF(MinorCPU, \"MinorCPU startup\\n\");\n\n BaseCPU::startup();\n\n for (auto i = threads.begin(); i != threads.end(); i ++)\n (*i)->startup();\n\n \/* CPU state setup, activate initial context *\/\n activateContext(0);\n}\n\nDrainState\nMinorCPU::drain()\n{\n DPRINTF(Drain, \"MinorCPU drain\\n\");\n\n \/* Need to suspend all threads and wait for Execute to idle.\n * Tell Fetch1 not to fetch *\/\n if (pipeline->drain()) {\n DPRINTF(Drain, \"MinorCPU drained\\n\");\n return DrainState::Drained;\n } else {\n DPRINTF(Drain, \"MinorCPU not finished draining\\n\");\n return DrainState::Draining;\n }\n}\n\nvoid\nMinorCPU::signalDrainDone()\n{\n DPRINTF(Drain, \"MinorCPU drain done\\n\");\n signalDrainDone();\n}\n\nvoid\nMinorCPU::drainResume()\n{\n assert(drainState() == DrainState::Drained);\n\n if (switchedOut()) {\n DPRINTF(Drain, \"drainResume while switched out. Ignoring\\n\");\n return;\n }\n\n DPRINTF(Drain, \"MinorCPU drainResume\\n\");\n\n if (!system->isTimingMode()) {\n fatal(\"The Minor CPU requires the memory system to be in \"\n \"'timing' mode.\\n\");\n }\n\n wakeup();\n pipeline->drainResume();\n}\n\nvoid\nMinorCPU::memWriteback()\n{\n DPRINTF(Drain, \"MinorCPU memWriteback\\n\");\n}\n\nvoid\nMinorCPU::switchOut()\n{\n DPRINTF(MinorCPU, \"MinorCPU switchOut\\n\");\n\n assert(!switchedOut());\n BaseCPU::switchOut();\n\n \/* Check that the CPU is drained? *\/\n activityRecorder->reset();\n}\n\nvoid\nMinorCPU::takeOverFrom(BaseCPU *old_cpu)\n{\n DPRINTF(MinorCPU, \"MinorCPU takeOverFrom\\n\");\n\n BaseCPU::takeOverFrom(old_cpu);\n\n \/* Don't think I need to do anything here *\/\n}\n\nvoid\nMinorCPU::activateContext(ThreadID thread_id)\n{\n DPRINTF(MinorCPU, \"ActivateContext thread: %d\", thread_id);\n\n \/* Do some cycle accounting. lastStopped is reset to stop the\n * wakeup call on the pipeline from adding the quiesce period\n * to BaseCPU::numCycles *\/\n stats.quiesceCycles += pipeline->cyclesSinceLastStopped();\n pipeline->resetLastStopped();\n\n \/* Wake up the thread, wakeup the pipeline tick *\/\n threads[thread_id]->activate();\n wakeupOnEvent(Minor::Pipeline::CPUStageId);\n pipeline->wakeupFetch();\n}\n\nvoid\nMinorCPU::suspendContext(ThreadID thread_id)\n{\n DPRINTF(MinorCPU, \"SuspendContext %d\\n\", thread_id);\n\n threads[thread_id]->suspend();\n}\n\nvoid\nMinorCPU::wakeupOnEvent(unsigned int stage_id)\n{\n DPRINTF(Quiesce, \"Event wakeup from stage %d\\n\", stage_id);\n\n \/* Mark that some activity has taken place and start the pipeline *\/\n activityRecorder->activateStage(stage_id);\n pipeline->start();\n}\n\nMinorCPU *\nMinorCPUParams::create()\n{\n numThreads = 1;\n if (!FullSystem && workload.size() != 1)\n panic(\"only one workload allowed\");\n return new MinorCPU(this);\n}\n\nMasterPort &MinorCPU::getInstPort()\n{\n return pipeline->getInstPort();\n}\n\nMasterPort &MinorCPU::getDataPort()\n{\n return pipeline->getDataPort();\n}\n\nCounter\nMinorCPU::totalInsts() const\n{\n Counter ret = 0;\n\n for (auto i = threads.begin(); i != threads.end(); i ++)\n ret += (*i)->numInst;\n\n return ret;\n}\n\nCounter\nMinorCPU::totalOps() const\n{\n Counter ret = 0;\n\n for (auto i = threads.begin(); i != threads.end(); i ++)\n ret += (*i)->numOp;\n\n return ret;\n}\n<commit_msg>cpu: Fix drain issues in the Minor CPU<commit_after>\/*\n * Copyright (c) 2012-2014 ARM Limited\n * All rights reserved\n *\n * The license below extends only to copyright in the software and shall\n * not be construed as granting a license to any other intellectual\n * property including but not limited to intellectual property relating\n * to a hardware implementation of the functionality of the software\n * licensed hereunder. You may use the software subject to the license\n * terms below provided that you ensure that this notice is replicated\n * unmodified and in its entirety in all distributions of the software,\n * modified or unmodified, in source code or in binary form.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met: redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer;\n * redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution;\n * neither the name of the copyright holders nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n * Authors: Andrew Bardsley\n *\/\n\n#include \"arch\/utility.hh\"\n#include \"cpu\/minor\/cpu.hh\"\n#include \"cpu\/minor\/dyn_inst.hh\"\n#include \"cpu\/minor\/fetch1.hh\"\n#include \"cpu\/minor\/pipeline.hh\"\n#include \"debug\/Drain.hh\"\n#include \"debug\/MinorCPU.hh\"\n#include \"debug\/Quiesce.hh\"\n\nMinorCPU::MinorCPU(MinorCPUParams *params) :\n BaseCPU(params)\n{\n \/* This is only written for one thread at the moment *\/\n Minor::MinorThread *thread;\n\n if (FullSystem) {\n thread = new Minor::MinorThread(this, 0, params->system, params->itb,\n params->dtb, params->isa[0]);\n } else {\n \/* thread_id 0 *\/\n thread = new Minor::MinorThread(this, 0, params->system,\n params->workload[0], params->itb, params->dtb, params->isa[0]);\n }\n\n threads.push_back(thread);\n\n thread->setStatus(ThreadContext::Halted);\n\n ThreadContext *tc = thread->getTC();\n\n if (params->checker) {\n fatal(\"The Minor model doesn't support checking (yet)\\n\");\n }\n\n threadContexts.push_back(tc);\n\n Minor::MinorDynInst::init();\n\n pipeline = new Minor::Pipeline(*this, *params);\n activityRecorder = pipeline->getActivityRecorder();\n}\n\nMinorCPU::~MinorCPU()\n{\n delete pipeline;\n\n for (ThreadID thread_id = 0; thread_id < threads.size(); thread_id++) {\n delete threads[thread_id];\n }\n}\n\nvoid\nMinorCPU::init()\n{\n BaseCPU::init();\n\n if (!params()->switched_out &&\n system->getMemoryMode() != Enums::timing)\n {\n fatal(\"The Minor CPU requires the memory system to be in \"\n \"'timing' mode.\\n\");\n }\n\n \/* Initialise the ThreadContext's memory proxies *\/\n for (ThreadID thread_id = 0; thread_id < threads.size(); thread_id++) {\n ThreadContext *tc = getContext(thread_id);\n\n tc->initMemProxies(tc);\n }\n\n \/* Initialise CPUs (== threads in the ISA) *\/\n if (FullSystem && !params()->switched_out) {\n for (ThreadID thread_id = 0; thread_id < threads.size(); thread_id++)\n {\n ThreadContext *tc = getContext(thread_id);\n\n \/* Initialize CPU, including PC *\/\n TheISA::initCPU(tc, cpuId());\n }\n }\n}\n\n\/** Stats interface from SimObject (by way of BaseCPU) *\/\nvoid\nMinorCPU::regStats()\n{\n BaseCPU::regStats();\n stats.regStats(name(), *this);\n pipeline->regStats();\n}\n\nvoid\nMinorCPU::serializeThread(CheckpointOut &cp, ThreadID thread_id) const\n{\n threads[thread_id]->serialize(cp);\n}\n\nvoid\nMinorCPU::unserializeThread(CheckpointIn &cp, ThreadID thread_id)\n{\n if (thread_id != 0)\n fatal(\"Trying to load more than one thread into a MinorCPU\\n\");\n\n threads[thread_id]->unserialize(cp);\n}\n\nvoid\nMinorCPU::serialize(CheckpointOut &cp) const\n{\n pipeline->serialize(cp);\n BaseCPU::serialize(cp);\n}\n\nvoid\nMinorCPU::unserialize(CheckpointIn &cp)\n{\n pipeline->unserialize(cp);\n BaseCPU::unserialize(cp);\n}\n\nAddr\nMinorCPU::dbg_vtophys(Addr addr)\n{\n \/* Note that this gives you the translation for thread 0 *\/\n panic(\"No implementation for vtophy\\n\");\n\n return 0;\n}\n\nvoid\nMinorCPU::wakeup()\n{\n DPRINTF(Drain, \"MinorCPU wakeup\\n\");\n\n for (auto i = threads.begin(); i != threads.end(); i ++) {\n if ((*i)->status() == ThreadContext::Suspended)\n (*i)->activate();\n }\n\n DPRINTF(Drain,\"Suspended Processor awoke\\n\");\n}\n\nvoid\nMinorCPU::startup()\n{\n DPRINTF(MinorCPU, \"MinorCPU startup\\n\");\n\n BaseCPU::startup();\n\n for (auto i = threads.begin(); i != threads.end(); i ++)\n (*i)->startup();\n\n \/* CPU state setup, activate initial context *\/\n activateContext(0);\n}\n\nDrainState\nMinorCPU::drain()\n{\n DPRINTF(Drain, \"MinorCPU drain\\n\");\n\n \/* Need to suspend all threads and wait for Execute to idle.\n * Tell Fetch1 not to fetch *\/\n if (pipeline->drain()) {\n DPRINTF(Drain, \"MinorCPU drained\\n\");\n return DrainState::Drained;\n } else {\n DPRINTF(Drain, \"MinorCPU not finished draining\\n\");\n return DrainState::Draining;\n }\n}\n\nvoid\nMinorCPU::signalDrainDone()\n{\n DPRINTF(Drain, \"MinorCPU drain done\\n\");\n Drainable::signalDrainDone();\n}\n\nvoid\nMinorCPU::drainResume()\n{\n if (switchedOut()) {\n DPRINTF(Drain, \"drainResume while switched out. Ignoring\\n\");\n return;\n }\n\n DPRINTF(Drain, \"MinorCPU drainResume\\n\");\n\n if (!system->isTimingMode()) {\n fatal(\"The Minor CPU requires the memory system to be in \"\n \"'timing' mode.\\n\");\n }\n\n wakeup();\n pipeline->drainResume();\n}\n\nvoid\nMinorCPU::memWriteback()\n{\n DPRINTF(Drain, \"MinorCPU memWriteback\\n\");\n}\n\nvoid\nMinorCPU::switchOut()\n{\n DPRINTF(MinorCPU, \"MinorCPU switchOut\\n\");\n\n assert(!switchedOut());\n BaseCPU::switchOut();\n\n \/* Check that the CPU is drained? *\/\n activityRecorder->reset();\n}\n\nvoid\nMinorCPU::takeOverFrom(BaseCPU *old_cpu)\n{\n DPRINTF(MinorCPU, \"MinorCPU takeOverFrom\\n\");\n\n BaseCPU::takeOverFrom(old_cpu);\n\n \/* Don't think I need to do anything here *\/\n}\n\nvoid\nMinorCPU::activateContext(ThreadID thread_id)\n{\n DPRINTF(MinorCPU, \"ActivateContext thread: %d\", thread_id);\n\n \/* Do some cycle accounting. lastStopped is reset to stop the\n * wakeup call on the pipeline from adding the quiesce period\n * to BaseCPU::numCycles *\/\n stats.quiesceCycles += pipeline->cyclesSinceLastStopped();\n pipeline->resetLastStopped();\n\n \/* Wake up the thread, wakeup the pipeline tick *\/\n threads[thread_id]->activate();\n wakeupOnEvent(Minor::Pipeline::CPUStageId);\n pipeline->wakeupFetch();\n}\n\nvoid\nMinorCPU::suspendContext(ThreadID thread_id)\n{\n DPRINTF(MinorCPU, \"SuspendContext %d\\n\", thread_id);\n\n threads[thread_id]->suspend();\n}\n\nvoid\nMinorCPU::wakeupOnEvent(unsigned int stage_id)\n{\n DPRINTF(Quiesce, \"Event wakeup from stage %d\\n\", stage_id);\n\n \/* Mark that some activity has taken place and start the pipeline *\/\n activityRecorder->activateStage(stage_id);\n pipeline->start();\n}\n\nMinorCPU *\nMinorCPUParams::create()\n{\n numThreads = 1;\n if (!FullSystem && workload.size() != 1)\n panic(\"only one workload allowed\");\n return new MinorCPU(this);\n}\n\nMasterPort &MinorCPU::getInstPort()\n{\n return pipeline->getInstPort();\n}\n\nMasterPort &MinorCPU::getDataPort()\n{\n return pipeline->getDataPort();\n}\n\nCounter\nMinorCPU::totalInsts() const\n{\n Counter ret = 0;\n\n for (auto i = threads.begin(); i != threads.end(); i ++)\n ret += (*i)->numInst;\n\n return ret;\n}\n\nCounter\nMinorCPU::totalOps() const\n{\n Counter ret = 0;\n\n for (auto i = threads.begin(); i != threads.end(); i ++)\n ret += (*i)->numOp;\n\n return ret;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n kopetexsl.cpp - Kopete XSL Routines\n\n Copyright (c) 2003 by Jason Keirstead <jason@keirstead.org>\n\n *************************************************************************\n * *\n * This program is free software; you can redistribute it and\/or modify *\n * it under the terms of the GNU General Public License as published by *\n * the Free Software Foundation; either version 2 of the License, or *\n * (at your option) any later version. *\n * *\n *************************************************************************\n*\/\n\n#include <libxslt\/xsltInternals.h>\n#include <libxslt\/transform.h>\n#include <libxslt\/xsltutils.h>\n#include <libxml\/xmlIO.h>\n#include <libxml\/parser.h>\n\n#include <qtimer.h>\n#include <kdebug.h>\n#include <kopetexsl.h>\n#include <qregexp.h>\n\n\/\/#define XSL_DEBUG 1\n\nextern int xmlLoadExtDtdDefaultValue;\n\nconst QString KopeteXSL::xsltTransform( const QString &xmlString, const QString &xslString )\n{\n\tKopeteXSLThread mThread( xmlString, xslString );\n\tmThread.start();\n\tmThread.wait();\n\treturn mThread.result();\n}\n\nvoid KopeteXSL::xsltTransformAsync( const QString &xmlString, const QString &xslString,\n\t\t\tQObject *target, const char* slotCompleted )\n{\n\tKopeteXSLThread *mThread = new KopeteXSLThread( xmlString, xslString );\n\tQObject::connect( mThread, SIGNAL(complete( const QString & )), target, slotCompleted );\n\tmThread->start();\n}\n\nQDomDocument KopeteXSL::xsltTransform( const QDomDocument &xmlDocument, const QDomDocument &xslDocument )\n{\n\tKopeteXSLThread mThread( xmlDocument.toString(), xslDocument.toString() );\n\tmThread.start();\n\tmThread.wait();\n\treturn mThread.resultDocument();\n}\n\nvoid KopeteXSL::xsltTransformAsync( const QDomDocument &xmlDocument, const QDomDocument &xslDocument,\n\t\t\tQObject *target, const char* slotCompleted )\n{\n\tKopeteXSLThread *mThread = new KopeteXSLThread( xmlDocument.toString(), xslDocument.toString() );\n\tQObject::connect( mThread, SIGNAL(documentComplete( const QString & )), target, slotCompleted );\n\tmThread->start();\n}\n\nKopeteXSLThread::KopeteXSLThread( const QString &xmlString, const QString &xslString )\n{\n\tm_xml = xmlString;\n\tm_xsl = xslString;\n}\n\nvoid KopeteXSLThread::run()\n{\n\txsltStylesheetPtr style_sheet = NULL;\n\txmlDocPtr xmlDoc, xslDoc, resultDoc;\n\n\t\/\/Init Stuff\n\txmlInitMemory();\n\txmlLoadExtDtdDefaultValue = 0;\n\txmlSubstituteEntitiesDefault(1);\n\n\t#ifdef XSL_DEBUG\n\t\tkdDebug() << m_xml << endl;\n\t\tkdDebug() << m_xsl << endl;\n\t#endif\n\n\t\/\/ Convert QString into a C string\n\tQCString xmlCString = m_xml.latin1();\n\tQCString xslCString = m_xsl.latin1();\n\n\t\/\/ Read XML docs in from memory\n\txmlDoc = xmlParseMemory( xmlCString, xmlCString.length() );\n\txslDoc = xmlParseMemory( xslCString, xslCString.length() );\n\n\tif( xslDoc != NULL && xmlDoc != NULL )\n\t{\n\t\tstyle_sheet = xsltParseStylesheetDoc( xslDoc );\n\t\tresultDoc = xsltApplyStylesheet(style_sheet, xmlDoc, NULL);\n\t\tif( resultDoc != NULL )\n\t\t{\n\t\t\t\/\/Save the result into the QString\n\t\t\txmlOutputBufferPtr outp = xmlOutputBufferCreateIO( writeToQString, (xmlOutputCloseCallback)closeQString, &m_resultString, 0);\n\t\t\toutp->written = 0;\n\t\t\txsltSaveResultTo ( outp, resultDoc, style_sheet );\n\t\t\txmlOutputBufferFlush(outp);\n\t\t\txmlFreeDoc(resultDoc);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tkdDebug() << \"Transformed document is null!!!\" << endl;\n\t\t}\n\t\txmlFreeDoc(xmlDoc);\n\t\txsltFreeStylesheet(style_sheet);\n\t}\n\telse\n\t{\n\t\tkdDebug() << \"XML\/XSL Document could not be parsed!!!\" << endl;\n\t}\n\n\t\/\/Cleanup\n\txsltCleanupGlobals();\n\txmlCleanupParser();\n\txmlMemoryDump();\n\n\t\/\/Remove escaping\n\t\/\/KopeteXSL::unescape( m_resultString );\n\n\t\/\/Save the resuling DOM document\n\tm_result.setContent( m_resultString );\n\n\t\/\/Signal completion\n\temit( complete( m_resultString ) );\n\temit( documentComplete( m_result ) );\n\n\t\/\/Delete ourselves\n\tQTimer::singleShot( 500, this, SLOT( deleteLater() ) );\n}\n\nvoid KopeteXSL::unescape( QString &xml )\n{\n\txml.replace( QRegExp( QString::fromLatin1( \"\\\"\\\"\" ) ), QString::fromLatin1( \"\\\"\" ) );\n\txml.replace( QRegExp( QString::fromLatin1( \">\" ) ), QString::fromLatin1( \">\" ) );\n\txml.replace( QRegExp( QString::fromLatin1( \"<\" ) ), QString::fromLatin1( \"<\" ) );\n\txml.replace( QRegExp( QString::fromLatin1( \""\" ) ), QString::fromLatin1( \"\\\"\" ) );\n\txml.replace( QRegExp( QString::fromLatin1( \"&\" ) ), QString::fromLatin1( \"&\" ) );\n}\n\nint KopeteXSLThread::writeToQString( void * context, const char * buffer, int len )\n{\n\tQString *t = (QString*)context;\n\t*t += QString::fromUtf8(buffer, len);\n\treturn len;\n}\n\nint KopeteXSLThread::closeQString( void * context )\n{\n\tQString *t = (QString*)context;\n\t*t += QString::fromLatin1(\"\\n\");\n\treturn 0;\n}\n\n#include \"kopetexsl.moc\"\n\n<commit_msg>Encoding is UTF8, not latin1<commit_after>\/*\n kopetexsl.cpp - Kopete XSL Routines\n\n Copyright (c) 2003 by Jason Keirstead <jason@keirstead.org>\n\n *************************************************************************\n * *\n * This program is free software; you can redistribute it and\/or modify *\n * it under the terms of the GNU General Public License as published by *\n * the Free Software Foundation; either version 2 of the License, or *\n * (at your option) any later version. *\n * *\n *************************************************************************\n*\/\n\n#include <libxslt\/xsltInternals.h>\n#include <libxslt\/transform.h>\n#include <libxslt\/xsltutils.h>\n#include <libxml\/xmlIO.h>\n#include <libxml\/parser.h>\n\n#include <qtimer.h>\n#include <kdebug.h>\n#include <kopetexsl.h>\n#include <qregexp.h>\n\n\/\/#define XSL_DEBUG 1\n\nextern int xmlLoadExtDtdDefaultValue;\n\nconst QString KopeteXSL::xsltTransform( const QString &xmlString, const QString &xslString )\n{\n\tKopeteXSLThread mThread( xmlString, xslString );\n\tmThread.start();\n\tmThread.wait();\n\treturn mThread.result();\n}\n\nvoid KopeteXSL::xsltTransformAsync( const QString &xmlString, const QString &xslString,\n\t\t\tQObject *target, const char* slotCompleted )\n{\n\tKopeteXSLThread *mThread = new KopeteXSLThread( xmlString, xslString );\n\tQObject::connect( mThread, SIGNAL(complete( const QString & )), target, slotCompleted );\n\tmThread->start();\n}\n\nQDomDocument KopeteXSL::xsltTransform( const QDomDocument &xmlDocument, const QDomDocument &xslDocument )\n{\n\tKopeteXSLThread mThread( xmlDocument.toString(), xslDocument.toString() );\n\tmThread.start();\n\tmThread.wait();\n\treturn mThread.resultDocument();\n}\n\nvoid KopeteXSL::xsltTransformAsync( const QDomDocument &xmlDocument, const QDomDocument &xslDocument,\n\t\t\tQObject *target, const char* slotCompleted )\n{\n\tKopeteXSLThread *mThread = new KopeteXSLThread( xmlDocument.toString(), xslDocument.toString() );\n\tQObject::connect( mThread, SIGNAL(documentComplete( const QString & )), target, slotCompleted );\n\tmThread->start();\n}\n\nKopeteXSLThread::KopeteXSLThread( const QString &xmlString, const QString &xslString )\n{\n\tm_xml = xmlString;\n\tm_xsl = xslString;\n}\n\nvoid KopeteXSLThread::run()\n{\n\txsltStylesheetPtr style_sheet = NULL;\n\txmlDocPtr xmlDoc, xslDoc, resultDoc;\n\n\t\/\/Init Stuff\n\txmlInitMemory();\n\txmlLoadExtDtdDefaultValue = 0;\n\txmlSubstituteEntitiesDefault(1);\n\n\t#ifdef XSL_DEBUG\n\t\tkdDebug() << m_xml << endl;\n\t\tkdDebug() << m_xsl << endl;\n\t#endif\n\n\t\/\/ Convert QString into a C string\n\tQCString xmlCString = m_xml.utf8();\n\tQCString xslCString = m_xsl.utf8();\n\n\t\/\/ Read XML docs in from memory\n\txmlDoc = xmlParseMemory( xmlCString, xmlCString.length() );\n\txslDoc = xmlParseMemory( xslCString, xslCString.length() );\n\n\tif( xslDoc != NULL && xmlDoc != NULL )\n\t{\n\t\tstyle_sheet = xsltParseStylesheetDoc( xslDoc );\n\t\tresultDoc = xsltApplyStylesheet(style_sheet, xmlDoc, NULL);\n\t\tif( resultDoc != NULL )\n\t\t{\n\t\t\t\/\/Save the result into the QString\n\t\t\txmlOutputBufferPtr outp = xmlOutputBufferCreateIO( writeToQString, (xmlOutputCloseCallback)closeQString, &m_resultString, 0);\n\t\t\toutp->written = 0;\n\t\t\txsltSaveResultTo ( outp, resultDoc, style_sheet );\n\t\t\txmlOutputBufferFlush(outp);\n\t\t\txmlFreeDoc(resultDoc);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tkdDebug() << \"Transformed document is null!!!\" << endl;\n\t\t}\n\t\txmlFreeDoc(xmlDoc);\n\t\txsltFreeStylesheet(style_sheet);\n\t}\n\telse\n\t{\n\t\tkdDebug() << \"XML\/XSL Document could not be parsed!!!\" << endl;\n\t}\n\n\t\/\/Cleanup\n\txsltCleanupGlobals();\n\txmlCleanupParser();\n\txmlMemoryDump();\n\n\t\/\/Remove escaping\n\t\/\/KopeteXSL::unescape( m_resultString );\n\n\t\/\/Save the resuling DOM document\n\tm_result.setContent( m_resultString );\n\n\t\/\/Signal completion\n\temit( complete( m_resultString ) );\n\temit( documentComplete( m_result ) );\n\n\t\/\/Delete ourselves\n\tQTimer::singleShot( 500, this, SLOT( deleteLater() ) );\n}\n\nvoid KopeteXSL::unescape( QString &xml )\n{\n\txml.replace( QRegExp( QString::fromLatin1( \"\\\"\\\"\" ) ), QString::fromLatin1( \"\\\"\" ) );\n\txml.replace( QRegExp( QString::fromLatin1( \">\" ) ), QString::fromLatin1( \">\" ) );\n\txml.replace( QRegExp( QString::fromLatin1( \"<\" ) ), QString::fromLatin1( \"<\" ) );\n\txml.replace( QRegExp( QString::fromLatin1( \""\" ) ), QString::fromLatin1( \"\\\"\" ) );\n\txml.replace( QRegExp( QString::fromLatin1( \"&\" ) ), QString::fromLatin1( \"&\" ) );\n}\n\nint KopeteXSLThread::writeToQString( void * context, const char * buffer, int len )\n{\n\tQString *t = (QString*)context;\n\t*t += QString::fromUtf8(buffer, len);\n\treturn len;\n}\n\nint KopeteXSLThread::closeQString( void * context )\n{\n\tQString *t = (QString*)context;\n\t*t += QString::fromLatin1(\"\\n\");\n\treturn 0;\n}\n\n#include \"kopetexsl.moc\"\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (C) 2011, Paul Tagliamonte <tag@pault.ag>\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n *\/\n\n#include <ansiescape.hh>\n#include <ansicsi.hh>\n#include <iostream>\n\n#include \"ANSITerminal.hh\"\n#include \"Terminal.hh\"\n\nANSITerminal::ANSITerminal() {\n\tthis->_init_ANSITerminal();\n\tthis->_init_Terminal( 80, 25 );\n}\nANSITerminal::ANSITerminal( int width, int height ) {\n\tthis->_init_ANSITerminal();\n\tthis->_init_Terminal( width, height );\n}\nANSITerminal::~ANSITerminal() {}\n\nvoid ANSITerminal::_init_ANSITerminal() {\n\tansi_escape_parser_reset();\n}\n\nvoid ANSITerminal::_handle_escape( ansi_sequence * last ) {\n\tchar mode = last->mode;\n\tstd::vector<int> * seqs = last->values;\n\t\n\tint move_steps = 1;\n\t\n\tswitch ( mode ) {\n\t\tcase CSI_CUP:\n\t\tcase CSI_CUD:\n\t\tcase CSI_CUF:\n\t\tcase CSI_CUB:\n\t\t\t\/* Moves the cursor n (default 1) cells in the given direction. If\n\t\t\t * the cursor is already at the edge of the screen, this has no\n\t\t\t * effect. *\/\n\t\t\tswitch ( seqs->at(0) ) {\n\t\t\t\tcase -1:\n\t\t\t\t\tmove_steps = 1;\n\t\t\t\tdefault:\n\t\t\t\t\tmove_steps = seqs->at(0);\n\t\t\t\t\tfor ( int i = 0; i < move_steps; ++i ) {\n\t\t\t\t\t\tswitch ( mode ) {\n\t\t\t\t\t\t\tcase CSI_CUP:\n\t\t\t\t\t\t\t\tthis->cY--;\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\tcase CSI_CUD:\n\t\t\t\t\t\t\t\tthis->cY++;\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\tcase CSI_CUF:\n\t\t\t\t\t\t\t\tthis->cX++;\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\tcase CSI_CUB:\n\t\t\t\t\t\t\t\tthis->cX--;\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tthis->cX = ( this->cX < this->width )\n\t\t\t\t\t\t? this->cX : this->width;\n\t\t\t\t\tthis->cY = ( this->cY < this->height )\n\t\t\t\t\t\t? this->cY : this->height;\n\t\t\t\t\t\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t\tbreak;\n\t\t\t\n\t\tcase CSI_EL:\n\t\t\t\/* Erases part of the line. If n is zero (or missing), clear from\n\t\t\t * cursor to the end of the line. If n is one, clear from cursor to\n\t\t\t * beginning of the line. If n is two, clear entire line. Cursor\n\t\t\t * position does not change. *\/\n\t\t\tswitch ( seqs->at(0) ) {\n\t\t\t\tcase -1:\n\t\t\t\tcase 0:\n\t\t\t\t\tthis->erase_to_from( this->cX, this->cY,\n\t\t\t\t\t\tthis->width, this->cY );\n\t\t\t\t\tbreak;\n\t\t\t\tcase 1:\n\t\t\t\t\tthis->erase_to_from( 0, this->cY, this->cX, this->cY );\n\t\t\t\t\tbreak;\n\t\t\t\tcase 2:\n\t\t\t\t\tthis->erase_to_from( 0, this->cY,\n\t\t\t\t\t\tthis->width, this->cY );\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t\tbreak;\n\t\tcase CSI_ED:\n\t\t\t\/* Clears part of the screen. If n is zero (or missing),\n\t\t\t * clear from cursor to end of screen. If n is one,\n\t\t\t * clear from cursor to beginning of the screen. If n is two, clear\n\t\t\t * entire screen (and moves cursor to upper left on MS-DOS\n\t\t\t * ANSI.SYS).*\/\n\t\t\tswitch ( seqs->at(0) ) {\n\t\t\t\tcase -1: \/* Missing *\/\n\t\t\t\tcase 0:\n\t\t\t\t\tthis->erase_to_from( this->cX, this->cY,\n\t\t\t\t\t\tthis->width, this->height );\n\t\t\t\t\tbreak;\n\t\t\t\tcase 1:\n\t\t\t\t\tthis->erase_to_from( 0, 0, this->cX, this->cY );\n\t\t\t\t\tbreak;\n\t\t\t\tcase 2:\n\t\t\t\t\tthis->erase_to_from( 0, 0, this->width, this->height );\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t\tbreak;\n\t\tdefault:\n\t\t\t\/* Unknown sequence *\/\n\t\t\tbreak;\n\t}\n\t\n}\n\nvoid ANSITerminal::insert( unsigned char c ) {\n\tANSI_ESCAPE_PARSE_T res = ansi_escape_parser_feed( c );\n\tansi_sequence * last = NULL;\n\t\n\tswitch ( res ) {\n\t\tcase ANSI_ESCAPE_PARSE_OK:\n\t\t\tlast = ansi_escape_get_last_sequence();\n\t\t\tthis->_handle_escape( last );\n\t\t\tbreak;\n\t\tcase ANSI_ESCAPE_PARSE_BAD:\n\t\t\tansi_escape_parser_reset();\n\t\t\t\/* If we don't reset, the following bytes are \"INCOMPLETE\" *\/\n\t\t\tTerminal::insert(c);\n\t\t\tbreak;\n\t\tcase ANSI_ESCAPE_PARSE_INCOMPLETE:\n\t\t\tbreak;\n\t}\n}\n<commit_msg>Adding in some more stuff<commit_after>\/*\n * Copyright (C) 2011, Paul Tagliamonte <tag@pault.ag>\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n *\/\n\n#include <ansiescape.hh>\n#include <ansicsi.hh>\n#include <iostream>\n\n#include \"ANSITerminal.hh\"\n#include \"Terminal.hh\"\n\nANSITerminal::ANSITerminal() {\n\tthis->_init_ANSITerminal();\n\tthis->_init_Terminal( 80, 25 );\n}\nANSITerminal::ANSITerminal( int width, int height ) {\n\tthis->_init_ANSITerminal();\n\tthis->_init_Terminal( width, height );\n}\nANSITerminal::~ANSITerminal() {}\n\nvoid ANSITerminal::_init_ANSITerminal() {\n\tansi_escape_parser_reset();\n}\n\nvoid ANSITerminal::_handle_escape( ansi_sequence * last ) {\n\tchar mode = last->mode;\n\tstd::vector<int> * seqs = last->values;\n\t\n\tint move_steps = 1;\n\tint nRow = -1;\n\tint nCol = -1;\n\t\n\tswitch ( mode ) {\n\t\tcase CSI_CUU:\n\t\tcase CSI_CUD:\n\t\tcase CSI_CUF:\n\t\tcase CSI_CUB:\n\t\t\t\/* Moves the cursor n (default 1) cells in the given direction. If\n\t\t\t * the cursor is already at the edge of the screen, this has no\n\t\t\t * effect. *\/\n\t\t\tswitch ( seqs->at(0) ) {\n\t\t\t\tcase -1:\n\t\t\t\t\tmove_steps = 1;\n\t\t\t\tdefault:\n\t\t\t\t\tmove_steps = seqs->at(0);\n\t\t\t\t\tfor ( int i = 0; i < move_steps; ++i ) {\n\t\t\t\t\t\tswitch ( mode ) {\n\t\t\t\t\t\t\tcase CSI_CUP:\n\t\t\t\t\t\t\t\tthis->cY--;\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\tcase CSI_CUD:\n\t\t\t\t\t\t\t\tthis->cY++;\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\tcase CSI_CUF:\n\t\t\t\t\t\t\t\tthis->cX++;\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\tcase CSI_CUB:\n\t\t\t\t\t\t\t\tthis->cX--;\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tthis->cX = ( this->cX < this->width )\n\t\t\t\t\t\t? this->cX : this->width;\n\t\t\t\t\tthis->cY = ( this->cY < this->height )\n\t\t\t\t\t\t? this->cY : this->height;\n\t\t\t\t\t\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t\tbreak;\n\t\tcase CSI_CHA:\n\t\t\t\/* Moves the cursor to column n. *\/\n\t\t\tthis->cX = ( seqs->at(0) != -1 ) ? seqs->at(0) : 0;\n\t\t\tbreak;\n\t\tcase CSI_CUP:\n\t\t\t\/* Moves the cursor to row n, column m. The values are 1-based, and\n\t\t\t * default to 1 (top left corner) if omitted. A sequence such as CSI\n\t\t\t * ;5H is a synonym for CSI 1;5H as well as CSI 17;H is the same as\n\t\t\t * CSI 17H and CSI 17;1H *\/\n\t\t\tnRow = seqs->at(0);\n\t\t\t\n\t\t\tif ( nRow < 0 )\n\t\t\t\tnRow = 1;\n\t\t\t\n\t\t\tif ( seqs->size() >= 2 )\n\t\t\t\tnCol = seqs->at(1);\n\t\t\telse\n\t\t\t\tnCol = 1;\n\t\t\t\n\t\t\tthis->cX = (nCol - 1);\n\t\t\tthis->cY = (nRow - 1);\n\t\t\t\n\t\t\tbreak;\n\t\tcase CSI_EL:\n\t\t\t\/* Erases part of the line. If n is zero (or missing), clear from\n\t\t\t * cursor to the end of the line. If n is one, clear from cursor to\n\t\t\t * beginning of the line. If n is two, clear entire line. Cursor\n\t\t\t * position does not change. *\/\n\t\t\tswitch ( seqs->at(0) ) {\n\t\t\t\tcase -1:\n\t\t\t\tcase 0:\n\t\t\t\t\tthis->erase_to_from( this->cX, this->cY,\n\t\t\t\t\t\tthis->width, this->cY );\n\t\t\t\t\tbreak;\n\t\t\t\tcase 1:\n\t\t\t\t\tthis->erase_to_from( 0, this->cY, this->cX, this->cY );\n\t\t\t\t\tbreak;\n\t\t\t\tcase 2:\n\t\t\t\t\tthis->erase_to_from( 0, this->cY,\n\t\t\t\t\t\tthis->width, this->cY );\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t\tbreak;\n\t\tcase CSI_ED:\n\t\t\t\/* Clears part of the screen. If n is zero (or missing),\n\t\t\t * clear from cursor to end of screen. If n is one,\n\t\t\t * clear from cursor to beginning of the screen. If n is two, clear\n\t\t\t * entire screen (and moves cursor to upper left on MS-DOS\n\t\t\t * ANSI.SYS).*\/\n\t\t\tswitch ( seqs->at(0) ) {\n\t\t\t\tcase -1: \/* Missing *\/\n\t\t\t\tcase 0:\n\t\t\t\t\tthis->erase_to_from( this->cX, this->cY,\n\t\t\t\t\t\tthis->width, this->height );\n\t\t\t\t\tbreak;\n\t\t\t\tcase 1:\n\t\t\t\t\tthis->erase_to_from( 0, 0, this->cX, this->cY );\n\t\t\t\t\tbreak;\n\t\t\t\tcase 2:\n\t\t\t\t\tthis->erase_to_from( 0, 0, this->width, this->height );\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t\tbreak;\n\t\tdefault:\n\t\t\t\/* Unknown sequence *\/\n\t\t\t\/\/ std::cerr << \"UK-SEQ: \" << mode << std::endl;\n\t\t\tbreak;\n\t}\n\t\n}\n\nvoid ANSITerminal::insert( unsigned char c ) {\n\tANSI_ESCAPE_PARSE_T res = ansi_escape_parser_feed( c );\n\tansi_sequence * last = NULL;\n\t\n\tswitch ( res ) {\n\t\tcase ANSI_ESCAPE_PARSE_OK:\n\t\t\tlast = ansi_escape_get_last_sequence();\n\t\t\tthis->_handle_escape( last );\n\t\t\tbreak;\n\t\tcase ANSI_ESCAPE_PARSE_BAD:\n\t\t\tansi_escape_parser_reset();\n\t\t\t\/* If we don't reset, the following bytes are \"INCOMPLETE\" *\/\n\t\t\tTerminal::insert(c);\n\t\t\tbreak;\n\t\tcase ANSI_ESCAPE_PARSE_INCOMPLETE:\n\t\t\tbreak;\n\t}\n}\n<|endoftext|>"} {"text":"<commit_before>\n#include \"swganh\/simulation\/movement_manager.h\"\n\n#include <glog\/logging.h>\n\n#include \"anh\/event_dispatcher.h\"\n\n#include \"swganh\/object\/object.h\"\n#include \"swganh\/object\/creature\/creature.h\"\n#include \"swganh\/object\/object_controller.h\"\n\n#include \"swganh\/messages\/controllers\/data_transform.h\"\n#include \"swganh\/messages\/controllers\/data_transform_with_parent.h\"\n#include \"swganh\/messages\/update_containment_message.h\"\n#include \"swganh\/messages\/update_transform_message.h\"\n#include \"swganh\/messages\/update_transform_with_parent_message.h\"\n\nusing namespace anh::event_dispatcher;\nusing namespace std;\nusing namespace swganh::messages;\nusing namespace swganh::messages::controllers;\nusing namespace swganh::object;\nusing namespace swganh::object::creature;\nusing namespace swganh::simulation;\n\nMovementManager::MovementManager(anh::EventDispatcher* event_dispatcher)\n{\n RegisterEvents(event_dispatcher);\n}\n\nvoid MovementManager::HandleDataTransform(\n const shared_ptr<ObjectController>& controller, \n const ObjControllerMessage& message)\n{\n DataTransform transform;\n transform.Deserialize(message.data);\n \n auto object = controller->GetObject();\n \n if (!ValidateCounter_(object->GetObjectId(), transform.counter))\n {\n return;\n }\n\n counter_map_[object->GetObjectId()] = transform.counter;\n \n object->SetPosition(transform.position);\n object->SetOrientation(transform.orientation);\n \n SendUpdateDataTransformMessage(object);\n}\n\nvoid MovementManager::HandleDataTransformWithParent(\n const std::shared_ptr<ObjectController>& controller, \n const ObjControllerMessage& message)\n{\n throw std::runtime_error(\"Cell movement currently disabled\");\n\n DataTransformWithParent transform;\n transform.Deserialize(message.data);\n \n auto object = controller->GetObject();\n \n if (!ValidateCounter_(object->GetObjectId(), transform.counter))\n {\n return;\n }\n\n counter_map_[object->GetObjectId()] = transform.counter;\n \n object->SetPosition(transform.position);\n object->SetOrientation(transform.orientation);\n \n SendUpdateDataTransformWithParentMessage(object);\n}\n\nvoid MovementManager::SendDataTransformMessage(const shared_ptr<Object>& object, uint32_t unknown)\n{\n auto creature = static_pointer_cast<Creature>(object);\n\n DataTransform transform;\n transform.counter = ++counter_map_[object->GetObjectId()];\n transform.orientation = object->GetOrientation();\n transform.position = object->GetPosition();\n transform.speed = creature->GetWalkingSpeed();\n \n ObjControllerMessage message(unknown, move(transform));\n\n object->NotifyObservers(message);\n}\n\nvoid MovementManager::SendUpdateDataTransformMessage(const shared_ptr<Object>& object)\n{\n UpdateTransformMessage transform_update;\n transform_update.object_id = object->GetObjectId();\n transform_update.heading = object->GetHeading();\n transform_update.position = object->GetPosition();\n transform_update.update_counter = ++counter_map_[object->GetObjectId()];\n \n object->NotifyObservers(transform_update);\n}\n\nvoid MovementManager::SendDataTransformWithParentMessage(const shared_ptr<Object>& object, uint32_t unknown)\n{ \n auto creature = static_pointer_cast<Creature>(object);\n\n DataTransformWithParent transform;\n transform.cell_id = object->GetContainer()->GetObjectId();\n transform.counter = ++counter_map_[object->GetObjectId()];\n transform.orientation = object->GetOrientation();\n transform.position = object->GetPosition();\n transform.speed = creature->GetWalkingSpeed();\n \n ObjControllerMessage message(unknown, move(transform));\n\n object->NotifyObservers(message);\n}\n\nvoid MovementManager::SendUpdateDataTransformWithParentMessage(const shared_ptr<Object>& object)\n{ \n UpdateTransformWithParentMessage transform_update;\n transform_update.object_id = object->GetObjectId();\n transform_update.cell_id = object->GetContainer()->GetObjectId();\n transform_update.heading = object->GetHeading();\n transform_update.position = object->GetPosition();\n transform_update.update_counter = ++counter_map_[object->GetObjectId()];\n \n object->NotifyObservers(transform_update);\n}\n\nvoid MovementManager::RegisterEvents(anh::EventDispatcher* event_dispatcher)\n{\n event_dispatcher->Subscribe(\n \"ObjectReadyEvent\",\n [this] (shared_ptr<anh::EventInterface> incoming_event)\n {\n const auto& object = static_pointer_cast<anh::ValueEvent<shared_ptr<Object>>>(incoming_event)->Get();\n \n if (counter_map_.find(object->GetObjectId()) == counter_map_.end())\n {\n counter_map_[object->GetObjectId()] = 0;\n }\n\n if (object->GetContainer())\n {\n SendDataTransformWithParentMessage(object);\n }\n else\n {\n SendDataTransformMessage(object);\n }\n });\n}\n\nbool MovementManager::ValidateCounter_(uint64_t object_id, uint32_t counter)\n{ \n return counter > counter_map_[object_id];\n}\n\n<commit_msg>fix bad merge, not pulling in apathy's fix for 'warping on logging'<commit_after>\n#include \"swganh\/simulation\/movement_manager.h\"\n\n#include <glog\/logging.h>\n\n#include \"anh\/event_dispatcher.h\"\n\n#include \"swganh\/object\/object.h\"\n#include \"swganh\/object\/creature\/creature.h\"\n#include \"swganh\/object\/object_controller.h\"\n\n#include \"swganh\/messages\/controllers\/data_transform.h\"\n#include \"swganh\/messages\/controllers\/data_transform_with_parent.h\"\n#include \"swganh\/messages\/update_containment_message.h\"\n#include \"swganh\/messages\/update_transform_message.h\"\n#include \"swganh\/messages\/update_transform_with_parent_message.h\"\n\nusing namespace anh::event_dispatcher;\nusing namespace std;\nusing namespace swganh::messages;\nusing namespace swganh::messages::controllers;\nusing namespace swganh::object;\nusing namespace swganh::object::creature;\nusing namespace swganh::simulation;\n\nMovementManager::MovementManager(anh::EventDispatcher* event_dispatcher)\n{\n RegisterEvents(event_dispatcher);\n}\n\nvoid MovementManager::HandleDataTransform(\n const shared_ptr<ObjectController>& controller, \n const ObjControllerMessage& message)\n{\n DataTransform transform;\n transform.Deserialize(message.data);\n \n auto object = controller->GetObject();\n \n if (!ValidateCounter_(object->GetObjectId(), transform.counter))\n {\n return;\n }\n\n counter_map_[object->GetObjectId()] = transform.counter;\n \n object->SetPosition(transform.position);\n object->SetOrientation(transform.orientation);\n \n SendUpdateDataTransformMessage(object);\n}\n\nvoid MovementManager::HandleDataTransformWithParent(\n const std::shared_ptr<ObjectController>& controller, \n const ObjControllerMessage& message)\n{\n throw std::runtime_error(\"Cell movement currently disabled\");\n\n DataTransformWithParent transform;\n transform.Deserialize(message.data);\n \n auto object = controller->GetObject();\n \n if (!ValidateCounter_(object->GetObjectId(), transform.counter))\n {\n return;\n }\n\n counter_map_[object->GetObjectId()] = transform.counter;\n \n object->SetPosition(transform.position);\n object->SetOrientation(transform.orientation);\n \n SendUpdateDataTransformWithParentMessage(object);\n}\n\nvoid MovementManager::SendDataTransformMessage(const shared_ptr<Object>& object, uint32_t unknown)\n{\n auto creature = static_pointer_cast<Creature>(object);\n\n DataTransform transform;\n transform.counter = ++counter_map_[object->GetObjectId()];\n transform.orientation = object->GetOrientation();\n transform.position = object->GetPosition();\n transform.speed = creature->GetWalkingSpeed();\n \n ObjControllerMessage message(unknown, move(transform));\n\n object->GetController()->Notify(message);\n}\n\nvoid MovementManager::SendUpdateDataTransformMessage(const shared_ptr<Object>& object)\n{\n UpdateTransformMessage transform_update;\n transform_update.object_id = object->GetObjectId();\n transform_update.heading = object->GetHeading();\n transform_update.position = object->GetPosition();\n transform_update.update_counter = ++counter_map_[object->GetObjectId()];\n \n object->NotifyObservers(transform_update);\n}\n\nvoid MovementManager::SendDataTransformWithParentMessage(const shared_ptr<Object>& object, uint32_t unknown)\n{ \n auto creature = static_pointer_cast<Creature>(object);\n\n DataTransformWithParent transform;\n transform.cell_id = object->GetContainer()->GetObjectId();\n transform.counter = ++counter_map_[object->GetObjectId()];\n transform.orientation = object->GetOrientation();\n transform.position = object->GetPosition();\n transform.speed = creature->GetWalkingSpeed();\n \n ObjControllerMessage message(unknown, move(transform));\n\n object->GetController()->Notify(message);\n}\n\nvoid MovementManager::SendUpdateDataTransformWithParentMessage(const shared_ptr<Object>& object)\n{ \n UpdateTransformWithParentMessage transform_update;\n transform_update.object_id = object->GetObjectId();\n transform_update.cell_id = object->GetContainer()->GetObjectId();\n transform_update.heading = object->GetHeading();\n transform_update.position = object->GetPosition();\n transform_update.update_counter = ++counter_map_[object->GetObjectId()];\n \n object->NotifyObservers(transform_update);\n}\n\nvoid MovementManager::RegisterEvents(anh::EventDispatcher* event_dispatcher)\n{\n event_dispatcher->Subscribe(\n \"ObjectReadyEvent\",\n [this] (shared_ptr<anh::EventInterface> incoming_event)\n {\n const auto& object = static_pointer_cast<anh::ValueEvent<shared_ptr<Object>>>(incoming_event)->Get();\n \n if (counter_map_.find(object->GetObjectId()) == counter_map_.end())\n {\n counter_map_[object->GetObjectId()] = 0;\n }\n\n if (object->GetContainer())\n {\n SendDataTransformWithParentMessage(object);\n }\n else\n {\n SendDataTransformMessage(object);\n }\n });\n}\n\nbool MovementManager::ValidateCounter_(uint64_t object_id, uint32_t counter)\n{ \n return counter > counter_map_[object_id];\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c)2008-2011, Preferred Infrastructure Inc.\n\/\/ \n\/\/ All rights reserved.\n\/\/ \n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are met:\n\/\/ \n\/\/ * Redistributions of source code must retain the above copyright\n\/\/ notice, this list of conditions and the following disclaimer.\n\/\/ \n\/\/ * Redistributions in binary form must reproduce the above\n\/\/ copyright notice, this list of conditions and the following\n\/\/ disclaimer in the documentation and\/or other materials provided\n\/\/ with the distribution.\n\/\/ \n\/\/ * Neither the name of Preferred Infrastructure nor the names of other\n\/\/ contributors may be used to endorse or promote products derived\n\/\/ from this software without specific prior written permission.\n\/\/ \n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\/\/ \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n\/\/ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n\/\/ A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n\/\/ OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n\/\/ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n\/\/ LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n\/\/ DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n\/\/ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n\/\/ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n\/\/ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n#include <gtest\/gtest.h>\n\n#include \"mprpc.h\"\n\n#include <vector>\n#include <map>\n\n#include \"..\/lang\/bind.h\"\n#include \"..\/concurrent\/thread.h\"\n\nusing namespace std;\nusing namespace pfi::lang;\nusing namespace pfi::concurrent;\n\nMPRPC_PROC(test_str, string(string));\nstatic string test_str(const string& v){ return v; }\nMPRPC_PROC(test_pair, pair<int,string>(pair<int,string>));\nstatic pair<int,string> test_pair(const pair<int,string>& v){ return v; }\nMPRPC_PROC(test_vec, vector<int>(vector<int>));\nstatic vector<int> test_vec(const vector<int>& v){ return v; }\nMPRPC_PROC(test_map, map<int,int>(map<int,int>));\nstatic map<int, int> test_map(const map<int, int>& v){ return v; }\nMPRPC_PROC(test_set, set<int>(set<int> v));\nstatic set<int> test_set(const set<int>& v){ return v; }\n\nMPRPC_GEN(1, testrpc, test_str, test_pair, test_vec, test_map, test_set);\n\nnamespace {\nconst string kLocalhost = \"localhost\";\nconst int kServThreads = 10;\nconst int kTestRPCPort = 31241;\nconst int kTestStructRPCPort = 31242;\nconst double kServerTimeout = 3.0;\nconst double kClientTimeout = 3.0;\n}\n\nstatic void server_thread(testrpc_server *ser)\n{\n ser->set_test_str(&test_str);\n ser->set_test_pair(&test_pair);\n ser->set_test_vec(&test_vec);\n ser->set_test_map(&test_map);\n ser->set_test_set(&test_set);\n ser->serv(kTestRPCPort, kServThreads);\n}\n\nTEST(mprpc, mprpc_test)\n{\n testrpc_server ser(kServerTimeout);\n thread t(pfi::lang::bind(&server_thread, &ser));\n t.start();\n\n sleep(1);\n\n int times = 100;\n EXPECT_NO_THROW({ testrpc_client cln1(kLocalhost, kTestRPCPort, kClientTimeout); });\n {\n testrpc_client cln(kLocalhost, kTestRPCPort, kClientTimeout);\n for (int t=0;t<times;t++) {\n {\n string v;\n for (int i=0;i<10;i++)\n v+='0'+(rand()%10);\n string r;\n EXPECT_NO_THROW({ r = cln.call_test_str(v); });\n EXPECT_EQ(r.size(), 10U);\n for (int i=0;i<10;i++)\n EXPECT_EQ(r[i], v[i]);\n }\n {\n string vs;\n for (int i=0;i<10;i++)\n vs+='0'+(rand()%10);\n pair<int, string> v = make_pair(rand(), vs);\n pair<int, string> r;\n EXPECT_NO_THROW({ r = cln.call_test_pair(v); });\n EXPECT_EQ(r.first, v.first);\n EXPECT_EQ(r.second, v.second);\n }\n {\n vector<int> v;\n for (int i=0;i<10;i++)\n v.push_back(rand());\n vector<int> r;\n EXPECT_NO_THROW({ r = cln.call_test_vec(v); });\n EXPECT_EQ(r.size(), 10U);\n for (int i=0;i<10;i++)\n EXPECT_EQ(r[i], v[i]);\n }\n {\n map<int, int> v;\n for (int i=0;i<10;i++)\n v[i]=rand();\n map<int, int> r;\n EXPECT_NO_THROW({ r = cln.call_test_map(v); });\n EXPECT_EQ(r.size(), 10U);\n for (int i=0;i<10;i++){\n EXPECT_EQ(r[i], v[i]);\n }\n }\n {\n set<int> v;\n for (int i=0;i<10;i++)\n v.insert(i*100);\n set<int> r;\n EXPECT_NO_THROW({ r = cln.call_test_set(v); });\n EXPECT_EQ(r.size(), 10U);\n int cnt = 0;\n for (set<int>::iterator it=v.begin();it!=v.end();++it){\n EXPECT_EQ(*it, cnt++ * 100);\n }\n }\n }\n }\n\n ser.stop();\n t.join();\n}\n\n\/\/ test for struct and empty vector\nstruct tstruct {\n int i;\n vector<unsigned char> v;\n\n MSGPACK_DEFINE(i, v);\n};\n\nMPRPC_PROC(test_struct, tstruct(tstruct));\nMPRPC_GEN(1, test_struct_rpc, test_struct);\nstatic tstruct f_test_struct(tstruct t) { return t; }\nstatic void struct_server_thread(test_struct_rpc_server *ser)\n{\n ser->set_test_struct(&f_test_struct);\n ser->serv(kTestStructRPCPort, kServThreads);\n}\n\nTEST(mprpc, test_struct)\n{\n test_struct_rpc_server ser(kServerTimeout);\n thread t(pfi::lang::bind(&struct_server_thread, &ser));\n t.start();\n\n sleep(1);\n\n {\n tstruct t1;\n t1.i = 9;\n EXPECT_NO_THROW({ test_struct_rpc_client cln1(kLocalhost, kTestStructRPCPort, kClientTimeout); });\n test_struct_rpc_client cln(kLocalhost, kTestStructRPCPort, kClientTimeout);\n\n tstruct t2;\n EXPECT_NO_THROW({ t2 = cln.call_test_struct(t1); });\n EXPECT_EQ(t1.i, t2.i);\n }\n\n ser.stop();\n t.join();\n}\n<commit_msg>Added timeout testing to mprpc_test<commit_after>\/\/ Copyright (c)2008-2011, Preferred Infrastructure Inc.\n\/\/ \n\/\/ All rights reserved.\n\/\/ \n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are met:\n\/\/ \n\/\/ * Redistributions of source code must retain the above copyright\n\/\/ notice, this list of conditions and the following disclaimer.\n\/\/ \n\/\/ * Redistributions in binary form must reproduce the above\n\/\/ copyright notice, this list of conditions and the following\n\/\/ disclaimer in the documentation and\/or other materials provided\n\/\/ with the distribution.\n\/\/ \n\/\/ * Neither the name of Preferred Infrastructure nor the names of other\n\/\/ contributors may be used to endorse or promote products derived\n\/\/ from this software without specific prior written permission.\n\/\/ \n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\/\/ \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n\/\/ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n\/\/ A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n\/\/ OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n\/\/ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n\/\/ LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n\/\/ DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n\/\/ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n\/\/ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n\/\/ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n#include <gtest\/gtest.h>\n\n#include \"mprpc.h\"\n\n#include <vector>\n#include <map>\n\n#include \"..\/lang\/bind.h\"\n#include \"..\/concurrent\/thread.h\"\n#include \"..\/system\/time_util.h\"\n\nusing namespace std;\nusing namespace pfi::lang;\nusing namespace pfi::concurrent;\nusing namespace pfi::system::time;\n\nMPRPC_PROC(test_str, string(string));\nstatic string test_str(const string& v){ return v; }\nMPRPC_PROC(test_pair, pair<int,string>(pair<int,string>));\nstatic pair<int,string> test_pair(const pair<int,string>& v){ return v; }\nMPRPC_PROC(test_vec, vector<int>(vector<int>));\nstatic vector<int> test_vec(const vector<int>& v){ return v; }\nMPRPC_PROC(test_map, map<int,int>(map<int,int>));\nstatic map<int, int> test_map(const map<int, int>& v){ return v; }\nMPRPC_PROC(test_set, set<int>(set<int> v));\nstatic set<int> test_set(const set<int>& v){ return v; }\n\nMPRPC_GEN(1, testrpc, test_str, test_pair, test_vec, test_map, test_set);\n\nnamespace {\nconst string kLocalhost = \"localhost\";\nconst int kServThreads = 10;\nconst int kTestRPCPort = 31241;\nconst int kTestStructRPCPort = 31242;\nconst double kServerTimeout = 3.0;\nconst double kClientTimeout = 3.0;\nconst double kTestTimeout = 0.5;\n}\n\nstatic void server_thread(testrpc_server *ser)\n{\n ser->set_test_str(&test_str);\n ser->set_test_pair(&test_pair);\n ser->set_test_vec(&test_vec);\n ser->set_test_map(&test_map);\n ser->set_test_set(&test_set);\n ser->serv(kTestRPCPort, kServThreads);\n}\n\nTEST(mprpc, mprpc_test)\n{\n testrpc_server ser(kServerTimeout);\n thread t(pfi::lang::bind(&server_thread, &ser));\n t.start();\n\n sleep(1);\n\n int times = 100;\n EXPECT_NO_THROW({ testrpc_client cln1(kLocalhost, kTestRPCPort, kClientTimeout); });\n {\n testrpc_client cln(kLocalhost, kTestRPCPort, kClientTimeout);\n for (int t=0;t<times;t++) {\n {\n string v;\n for (int i=0;i<10;i++)\n v+='0'+(rand()%10);\n string r;\n EXPECT_NO_THROW({ r = cln.call_test_str(v); });\n EXPECT_EQ(r.size(), 10U);\n for (int i=0;i<10;i++)\n EXPECT_EQ(r[i], v[i]);\n }\n {\n string vs;\n for (int i=0;i<10;i++)\n vs+='0'+(rand()%10);\n pair<int, string> v = make_pair(rand(), vs);\n pair<int, string> r;\n EXPECT_NO_THROW({ r = cln.call_test_pair(v); });\n EXPECT_EQ(r.first, v.first);\n EXPECT_EQ(r.second, v.second);\n }\n {\n vector<int> v;\n for (int i=0;i<10;i++)\n v.push_back(rand());\n vector<int> r;\n EXPECT_NO_THROW({ r = cln.call_test_vec(v); });\n EXPECT_EQ(r.size(), 10U);\n for (int i=0;i<10;i++)\n EXPECT_EQ(r[i], v[i]);\n }\n {\n map<int, int> v;\n for (int i=0;i<10;i++)\n v[i]=rand();\n map<int, int> r;\n EXPECT_NO_THROW({ r = cln.call_test_map(v); });\n EXPECT_EQ(r.size(), 10U);\n for (int i=0;i<10;i++){\n EXPECT_EQ(r[i], v[i]);\n }\n }\n {\n set<int> v;\n for (int i=0;i<10;i++)\n v.insert(i*100);\n set<int> r;\n EXPECT_NO_THROW({ r = cln.call_test_set(v); });\n EXPECT_EQ(r.size(), 10U);\n int cnt = 0;\n for (set<int>::iterator it=v.begin();it!=v.end();++it){\n EXPECT_EQ(*it, cnt++ * 100);\n }\n }\n }\n }\n\n ser.stop();\n t.join();\n}\n\nTEST(mprpc, mprpc_server_timeout_test)\n{\n testrpc_server ser(kTestTimeout);\n thread t(pfi::lang::bind(&server_thread, &ser));\n t.start();\n\n sleep(1);\n\n \/\/ connect server but server disconnect by timeout\n pfi::network::mprpc::socket sock;\n ASSERT_TRUE(sock.connect(kLocalhost, kTestRPCPort));\n\n clock_time start_time = get_clock_time();\n int res;\n EXPECT_EQ(0, ::read(sock.get(), &res, sizeof(res)));\n EXPECT_GT((get_clock_time() - start_time), kTestTimeout);\n\n ser.stop();\n t.join();\n}\n\nnamespace {\nvoid timeout_server_thread(pfi::network::mprpc::socket *server_socket)\n{\n sleep(1);\n\n ::accept(server_socket->get(), NULL, NULL);\n sleep(1 + kTestTimeout);\n\n \/\/ wait for socket shutdown listened socket\n ::accept(server_socket->get(), NULL, NULL);\n}\n} \/\/ namespace\n\nTEST(mprpc, mprpc_client_timeout_test)\n{\n pfi::network::mprpc::socket server_socket;\n server_socket.listen(kTestRPCPort);\n thread t(pfi::lang::bind(&timeout_server_thread, &server_socket));\n t.start();\n\n sleep(1);\n\n EXPECT_NO_THROW({ testrpc_client cln1(kLocalhost, kTestRPCPort, kTestTimeout); });\n\n { \/\/ connect server but client disconnect by timeout\n testrpc_client cln(kLocalhost, kTestRPCPort, kTestTimeout);\n string v, r;\n EXPECT_THROW({ r = cln.call_test_str(v); }, pfi::network::mprpc::rpc_timeout_error);\n }\n\n server_socket.close();\n t.join();\n}\n\n\/\/ test for struct and empty vector\nstruct tstruct {\n int i;\n vector<unsigned char> v;\n\n MSGPACK_DEFINE(i, v);\n};\n\nMPRPC_PROC(test_struct, tstruct(tstruct));\nMPRPC_GEN(1, test_struct_rpc, test_struct);\nstatic tstruct f_test_struct(tstruct t) { return t; }\nstatic void struct_server_thread(test_struct_rpc_server *ser)\n{\n ser->set_test_struct(&f_test_struct);\n ser->serv(kTestStructRPCPort, kServThreads);\n}\n\nTEST(mprpc, test_struct)\n{\n test_struct_rpc_server ser(kServerTimeout);\n thread t(pfi::lang::bind(&struct_server_thread, &ser));\n t.start();\n\n sleep(1);\n\n {\n tstruct t1;\n t1.i = 9;\n EXPECT_NO_THROW({ test_struct_rpc_client cln1(kLocalhost, kTestStructRPCPort, kClientTimeout); });\n test_struct_rpc_client cln(kLocalhost, kTestStructRPCPort, kClientTimeout);\n\n tstruct t2;\n EXPECT_NO_THROW({ t2 = cln.call_test_struct(t1); });\n EXPECT_EQ(t1.i, t2.i);\n }\n\n ser.stop();\n t.join();\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"..\/SDP_Solver_Parameters.hxx\"\n\n#include <boost\/program_options.hpp>\n#include <boost\/filesystem\/fstream.hpp>\n\nnamespace po = boost::program_options;\n\nSDP_Solver_Parameters::SDP_Solver_Parameters(int argc, char *argv[])\n{\n int int_verbosity;\n std::string write_solution_string;\n using namespace std::string_literals;\n\n po::options_description required_options(\"Required options\");\n required_options.add_options()(\n \"sdpDir,s\", po::value<boost::filesystem::path>(&sdp_directory)->required(),\n \"Directory containing preprocessed SDP data files.\");\n required_options.add_options()(\n \"procsPerNode\", po::value<size_t>(&procs_per_node)->required(),\n \"The number of processes that can run on a node. When running on \"\n \"more \"\n \"than one node, the load balancer needs to know how many processes \"\n \"are assigned to each node. On a laptop or desktop, this would be \"\n \"the number of physical cores on your machine, not including \"\n \"hyperthreaded cores. For current laptops (2018), this is probably \"\n \"2 or 4.\\n\\n\"\n \"If you are using the Slurm workload manager, this should be set to \"\n \"'$SLURM_NTASKS_PER_NODE'.\");\n\n po::options_description basic_options(\"Basic options\");\n basic_options.add_options()(\"help,h\", \"Show this helpful message.\");\n basic_options.add_options()(\"version\",\n \"Show version and configuration info.\");\n basic_options.add_options()(\n \"paramFile,p\", po::value<boost::filesystem::path>(¶m_file),\n \"Any parameter can optionally be set via this file in key=value \"\n \"format. Command line arguments override values in the parameter \"\n \"file.\");\n basic_options.add_options()(\n \"outDir,o\", po::value<boost::filesystem::path>(&out_directory),\n \"The optimal solution is saved to this directory in Mathematica \"\n \"format. Defaults to sdpDir with '_out' appended.\");\n basic_options.add_options()(\n \"checkpointDir,c\", po::value<boost::filesystem::path>(&checkpoint_out),\n \"Checkpoints are saved to this directory every checkpointInterval. \"\n \"Defaults to sdpDir with '.ck' extension.\");\n basic_options.add_options()(\n \"initialCheckpointDir,i\",\n po::value<boost::filesystem::path>(&checkpoint_in),\n \"The initial checkpoint directory to load. Defaults to \"\n \"checkpointDir.\");\n basic_options.add_options()(\n \"checkpointInterval\",\n po::value<int64_t>(&checkpoint_interval)->default_value(3600),\n \"Save checkpoints to checkpointDir every checkpointInterval \"\n \"seconds.\");\n basic_options.add_options()(\n \"noFinalCheckpoint\",\n po::bool_switch(&no_final_checkpoint)->default_value(false),\n \"Don't save a final checkpoint after terminating (useful when \"\n \"debugging).\");\n basic_options.add_options()(\n \"writeSolution\",\n po::value<std::string>(&write_solution_string)->default_value(\"x,y\"s),\n \"A comma separated list of vectors and matrices to write into the output \"\n \"directory. The default only writes the vectors 'x' and 'y'. If you add \"\n \"the 'X' and 'Y' matrices, then the output directory can be used as a \"\n \"final text \"\n \"checkpoint. Runs started from text checkpoints will very close to, but \"\n \"not bitwise identical to, the original run. To only output the result \"\n \"(because, for example, you only want to know if SDPB found a primal \"\n \"feasible point), set this to an empty string.\");\n basic_options.add_options()(\n \"procGranularity\", po::value<size_t>(&proc_granularity)->default_value(1),\n \"procGranularity must evenly divide procsPerNode.\\n\\n\"\n \"The minimum number of cores in a group, used during load balancing. \"\n \"Setting it to anything larger than 1 will make the solution take \"\n \"longer. \"\n \"This option is generally useful only when trying to fit a large problem \"\n \"in a small machine.\");\n basic_options.add_options()(\"verbosity\",\n po::value<int>(&int_verbosity)->default_value(1),\n \"Verbosity. 0 -> no output, 1 -> regular \"\n \"output, 2 -> debug output\");\n\n \/\/ We set default parameters using El::BigFloat(\"1e-10\",10)\n \/\/ rather than a straight double precision 1e-10 so that results\n \/\/ are more reproducible at high precision. Using double\n \/\/ precision defaults results in differences of about 1e-15 in\n \/\/ primalObjective after one step.\n po::options_description solver_options(\"Solver parameters\");\n solver_options.add_options()(\n \"precision\", po::value<size_t>(&precision)->default_value(400),\n \"The precision, in the number of bits, for numbers in the \"\n \"computation. \"\n \" This should be less than or equal to the precision used when \"\n \"preprocessing the XML input files with 'pvm2sdp'. GMP will round \"\n \"this up to a multiple of 32 or 64, depending on the system.\");\n solver_options.add_options()(\n \"findPrimalFeasible\",\n po::bool_switch(&find_primal_feasible)->default_value(false),\n \"Terminate once a primal feasible solution is found.\");\n solver_options.add_options()(\n \"findDualFeasible\",\n po::bool_switch(&find_dual_feasible)->default_value(false),\n \"Terminate once a dual feasible solution is found.\");\n solver_options.add_options()(\n \"detectPrimalFeasibleJump\",\n po::bool_switch(&detect_primal_feasible_jump)->default_value(false),\n \"Terminate if a primal-step of 1 is taken. This often indicates that \"\n \"a \"\n \"primal feasible solution would be found if the precision were high \"\n \"enough. Try increasing either primalErrorThreshold or precision \"\n \"and run from the latest checkpoint.\");\n solver_options.add_options()(\n \"detectDualFeasibleJump\",\n po::bool_switch(&detect_dual_feasible_jump)->default_value(false),\n \"Terminate if a dual-step of 1 is taken. This often indicates that a \"\n \"dual feasible solution would be found if the precision were high \"\n \"enough. Try increasing either dualErrorThreshold or precision \"\n \"and run from the latest checkpoint.\");\n solver_options.add_options()(\n \"maxIterations\", po::value<int64_t>(&max_iterations)->default_value(500),\n \"Maximum number of iterations to run the solver.\");\n solver_options.add_options()(\n \"maxRuntime\", po::value<int64_t>(&max_runtime)->default_value(86400),\n \"Maximum amount of time to run the solver in seconds.\");\n solver_options.add_options()(\n \"dualityGapThreshold\",\n po::value<El::BigFloat>(&duality_gap_threshold)\n ->default_value(El::BigFloat(\"1e-30\", 10)),\n \"Threshold for duality gap (roughly the difference in primal and dual \"\n \"objective) at which the solution is considered \"\n \"optimal. Corresponds to SDPA's epsilonStar.\");\n solver_options.add_options()(\n \"primalErrorThreshold\",\n po::value<El::BigFloat>(&primal_error_threshold)\n ->default_value(El::BigFloat(\"1e-30\", 10)),\n \"Threshold for feasibility of the primal problem. Corresponds to \"\n \"SDPA's epsilonBar.\");\n solver_options.add_options()(\n \"dualErrorThreshold\",\n po::value<El::BigFloat>(&dual_error_threshold)\n ->default_value(El::BigFloat(\"1e-30\", 10)),\n \"Threshold for feasibility of the dual problem. Corresponds to SDPA's \"\n \"epsilonBar.\");\n solver_options.add_options()(\n \"initialMatrixScalePrimal\",\n po::value<El::BigFloat>(&initial_matrix_scale_primal)\n ->default_value(El::BigFloat(\"1e20\", 10)),\n \"The primal matrix X begins at initialMatrixScalePrimal times the \"\n \"identity matrix. Corresponds to SDPA's lambdaStar.\");\n solver_options.add_options()(\n \"initialMatrixScaleDual\",\n po::value<El::BigFloat>(&initial_matrix_scale_dual)\n ->default_value(El::BigFloat(\"1e20\", 10)),\n \"The dual matrix Y begins at initialMatrixScaleDual times the \"\n \"identity matrix. Corresponds to SDPA's lambdaStar.\");\n solver_options.add_options()(\n \"feasibleCenteringParameter\",\n po::value<El::BigFloat>(&feasible_centering_parameter)\n ->default_value(El::BigFloat(\"0.1\", 10)),\n \"Shrink the complementarity X Y by this factor when the primal and \"\n \"dual \"\n \"problems are feasible. Corresponds to SDPA's betaStar.\");\n solver_options.add_options()(\n \"infeasibleCenteringParameter\",\n po::value<El::BigFloat>(&infeasible_centering_parameter)\n ->default_value(El::BigFloat(\"0.3\", 10)),\n \"Shrink the complementarity X Y by this factor when either the primal \"\n \"or dual problems are infeasible. Corresponds to SDPA's betaBar.\");\n solver_options.add_options()(\n \"stepLengthReduction\",\n po::value<El::BigFloat>(&step_length_reduction)\n ->default_value(El::BigFloat(\"0.7\", 10)),\n \"Shrink each newton step by this factor (smaller means slower, more \"\n \"stable convergence). Corresponds to SDPA's gammaStar.\");\n solver_options.add_options()(\n \"maxComplementarity\",\n po::value<El::BigFloat>(&max_complementarity)\n ->default_value(El::BigFloat(\"1e100\", 10)),\n \"Terminate if the complementarity mu = Tr(X Y)\/dim(X) \"\n \"exceeds this value.\");\n\n po::options_description cmd_line_options;\n cmd_line_options.add(required_options).add(basic_options).add(solver_options);\n\n po::variables_map variables_map;\n try\n {\n po::store(po::parse_command_line(argc, argv, cmd_line_options),\n variables_map);\n\n if(variables_map.count(\"help\") != 0)\n {\n if(El::mpi::Rank() == 0)\n {\n std::cout << cmd_line_options << '\\n';\n }\n }\n else if(variables_map.count(\"version\") != 0)\n {\n if(El::mpi::Rank() == 0)\n {\n std::cout << \"SDPB \" << SDPB_VERSION_STRING << \"\\n\";\n }\n El::PrintVersion();\n El::PrintConfig();\n El::PrintCCompilerInfo();\n El::PrintCxxCompilerInfo();\n }\n else\n {\n if(variables_map.count(\"paramFile\") != 0)\n {\n param_file\n = variables_map[\"paramFile\"].as<boost::filesystem::path>();\n std::ifstream ifs(param_file.string().c_str());\n if(!ifs.good())\n {\n throw std::runtime_error(\"Could not open '\"\n + param_file.string() + \"'\");\n }\n\n po::store(po::parse_config_file(ifs, cmd_line_options),\n variables_map);\n }\n\n po::notify(variables_map);\n\n if(!boost::filesystem::exists(sdp_directory))\n {\n throw std::runtime_error(\"sdp directory '\"\n + sdp_directory.string()\n + \"' does not exist\");\n }\n if(!boost::filesystem::is_directory(sdp_directory))\n {\n throw std::runtime_error(\"sdp directory '\"\n + sdp_directory.string()\n + \"' is not a directory\");\n }\n\n if(variables_map.count(\"outDir\") == 0)\n {\n out_directory = sdp_directory;\n if(out_directory.filename() == \".\")\n {\n out_directory = out_directory.parent_path();\n }\n out_directory += \"_out\";\n }\n\n if(variables_map.count(\"checkpointDir\") == 0)\n {\n checkpoint_out = sdp_directory;\n if(checkpoint_out.filename() == \".\")\n {\n checkpoint_out = checkpoint_out.parent_path();\n }\n checkpoint_out += \".ck\";\n }\n\n if(variables_map.count(\"initialCheckpointDir\") == 0)\n {\n checkpoint_in = checkpoint_out;\n }\n else\n {\n require_initial_checkpoint = true;\n }\n\n write_solution=Write_Solution(write_solution_string);\n \n if(El::mpi::Rank() == 0)\n {\n boost::filesystem::create_directories(out_directory);\n boost::filesystem::ofstream ofs(out_directory \/ \"out.txt\");\n if(!ofs.good())\n {\n throw std::runtime_error(\"Cannot write to outDir: \"\n + out_directory.string());\n }\n }\n\n if(int_verbosity != 0 && int_verbosity != 1 && int_verbosity != 2)\n {\n throw std::runtime_error(\n \"Invalid number for Verbosity. Only 0, 1 or 2 are allowed\\n\");\n }\n else\n {\n verbosity = static_cast<Verbosity>(int_verbosity);\n }\n }\n }\n catch(po::error &e)\n {\n El::ReportException(e);\n El::mpi::Abort(El::mpi::COMM_WORLD, 1);\n }\n}\n<commit_msg>Change default maxRuntime to effectively infinity<commit_after>#include \"..\/SDP_Solver_Parameters.hxx\"\n\n#include <boost\/program_options.hpp>\n#include <boost\/filesystem\/fstream.hpp>\n\nnamespace po = boost::program_options;\n\nSDP_Solver_Parameters::SDP_Solver_Parameters(int argc, char *argv[])\n{\n int int_verbosity;\n std::string write_solution_string;\n using namespace std::string_literals;\n\n po::options_description required_options(\"Required options\");\n required_options.add_options()(\n \"sdpDir,s\", po::value<boost::filesystem::path>(&sdp_directory)->required(),\n \"Directory containing preprocessed SDP data files.\");\n required_options.add_options()(\n \"procsPerNode\", po::value<size_t>(&procs_per_node)->required(),\n \"The number of processes that can run on a node. When running on \"\n \"more \"\n \"than one node, the load balancer needs to know how many processes \"\n \"are assigned to each node. On a laptop or desktop, this would be \"\n \"the number of physical cores on your machine, not including \"\n \"hyperthreaded cores. For current laptops (2018), this is probably \"\n \"2 or 4.\\n\\n\"\n \"If you are using the Slurm workload manager, this should be set to \"\n \"'$SLURM_NTASKS_PER_NODE'.\");\n\n po::options_description basic_options(\"Basic options\");\n basic_options.add_options()(\"help,h\", \"Show this helpful message.\");\n basic_options.add_options()(\"version\",\n \"Show version and configuration info.\");\n basic_options.add_options()(\n \"paramFile,p\", po::value<boost::filesystem::path>(¶m_file),\n \"Any parameter can optionally be set via this file in key=value \"\n \"format. Command line arguments override values in the parameter \"\n \"file.\");\n basic_options.add_options()(\n \"outDir,o\", po::value<boost::filesystem::path>(&out_directory),\n \"The optimal solution is saved to this directory in Mathematica \"\n \"format. Defaults to sdpDir with '_out' appended.\");\n basic_options.add_options()(\n \"checkpointDir,c\", po::value<boost::filesystem::path>(&checkpoint_out),\n \"Checkpoints are saved to this directory every checkpointInterval. \"\n \"Defaults to sdpDir with '.ck' extension.\");\n basic_options.add_options()(\n \"initialCheckpointDir,i\",\n po::value<boost::filesystem::path>(&checkpoint_in),\n \"The initial checkpoint directory to load. Defaults to \"\n \"checkpointDir.\");\n basic_options.add_options()(\n \"checkpointInterval\",\n po::value<int64_t>(&checkpoint_interval)->default_value(3600),\n \"Save checkpoints to checkpointDir every checkpointInterval \"\n \"seconds.\");\n basic_options.add_options()(\n \"noFinalCheckpoint\",\n po::bool_switch(&no_final_checkpoint)->default_value(false),\n \"Don't save a final checkpoint after terminating (useful when \"\n \"debugging).\");\n basic_options.add_options()(\n \"writeSolution\",\n po::value<std::string>(&write_solution_string)->default_value(\"x,y\"s),\n \"A comma separated list of vectors and matrices to write into the output \"\n \"directory. The default only writes the vectors 'x' and 'y'. If you add \"\n \"the 'X' and 'Y' matrices, then the output directory can be used as a \"\n \"final text \"\n \"checkpoint. Runs started from text checkpoints will very close to, but \"\n \"not bitwise identical to, the original run. To only output the result \"\n \"(because, for example, you only want to know if SDPB found a primal \"\n \"feasible point), set this to an empty string.\");\n basic_options.add_options()(\n \"procGranularity\", po::value<size_t>(&proc_granularity)->default_value(1),\n \"procGranularity must evenly divide procsPerNode.\\n\\n\"\n \"The minimum number of cores in a group, used during load balancing. \"\n \"Setting it to anything larger than 1 will make the solution take \"\n \"longer. \"\n \"This option is generally useful only when trying to fit a large problem \"\n \"in a small machine.\");\n basic_options.add_options()(\"verbosity\",\n po::value<int>(&int_verbosity)->default_value(1),\n \"Verbosity. 0 -> no output, 1 -> regular \"\n \"output, 2 -> debug output\");\n\n \/\/ We set default parameters using El::BigFloat(\"1e-10\",10)\n \/\/ rather than a straight double precision 1e-10 so that results\n \/\/ are more reproducible at high precision. Using double\n \/\/ precision defaults results in differences of about 1e-15 in\n \/\/ primalObjective after one step.\n po::options_description solver_options(\"Solver parameters\");\n solver_options.add_options()(\n \"precision\", po::value<size_t>(&precision)->default_value(400),\n \"The precision, in the number of bits, for numbers in the \"\n \"computation. \"\n \" This should be less than or equal to the precision used when \"\n \"preprocessing the XML input files with 'pvm2sdp'. GMP will round \"\n \"this up to a multiple of 32 or 64, depending on the system.\");\n solver_options.add_options()(\n \"findPrimalFeasible\",\n po::bool_switch(&find_primal_feasible)->default_value(false),\n \"Terminate once a primal feasible solution is found.\");\n solver_options.add_options()(\n \"findDualFeasible\",\n po::bool_switch(&find_dual_feasible)->default_value(false),\n \"Terminate once a dual feasible solution is found.\");\n solver_options.add_options()(\n \"detectPrimalFeasibleJump\",\n po::bool_switch(&detect_primal_feasible_jump)->default_value(false),\n \"Terminate if a primal-step of 1 is taken. This often indicates that \"\n \"a \"\n \"primal feasible solution would be found if the precision were high \"\n \"enough. Try increasing either primalErrorThreshold or precision \"\n \"and run from the latest checkpoint.\");\n solver_options.add_options()(\n \"detectDualFeasibleJump\",\n po::bool_switch(&detect_dual_feasible_jump)->default_value(false),\n \"Terminate if a dual-step of 1 is taken. This often indicates that a \"\n \"dual feasible solution would be found if the precision were high \"\n \"enough. Try increasing either dualErrorThreshold or precision \"\n \"and run from the latest checkpoint.\");\n solver_options.add_options()(\n \"maxIterations\", po::value<int64_t>(&max_iterations)->default_value(500),\n \"Maximum number of iterations to run the solver.\");\n solver_options.add_options()(\n \"maxRuntime\",\n po::value<int64_t>(&max_runtime)\n ->default_value(std::numeric_limits<int64_t>::max()),\n \"Maximum amount of time to run the solver in seconds.\");\n solver_options.add_options()(\n \"dualityGapThreshold\",\n po::value<El::BigFloat>(&duality_gap_threshold)\n ->default_value(El::BigFloat(\"1e-30\", 10)),\n \"Threshold for duality gap (roughly the difference in primal and dual \"\n \"objective) at which the solution is considered \"\n \"optimal. Corresponds to SDPA's epsilonStar.\");\n solver_options.add_options()(\n \"primalErrorThreshold\",\n po::value<El::BigFloat>(&primal_error_threshold)\n ->default_value(El::BigFloat(\"1e-30\", 10)),\n \"Threshold for feasibility of the primal problem. Corresponds to \"\n \"SDPA's epsilonBar.\");\n solver_options.add_options()(\n \"dualErrorThreshold\",\n po::value<El::BigFloat>(&dual_error_threshold)\n ->default_value(El::BigFloat(\"1e-30\", 10)),\n \"Threshold for feasibility of the dual problem. Corresponds to SDPA's \"\n \"epsilonBar.\");\n solver_options.add_options()(\n \"initialMatrixScalePrimal\",\n po::value<El::BigFloat>(&initial_matrix_scale_primal)\n ->default_value(El::BigFloat(\"1e20\", 10)),\n \"The primal matrix X begins at initialMatrixScalePrimal times the \"\n \"identity matrix. Corresponds to SDPA's lambdaStar.\");\n solver_options.add_options()(\n \"initialMatrixScaleDual\",\n po::value<El::BigFloat>(&initial_matrix_scale_dual)\n ->default_value(El::BigFloat(\"1e20\", 10)),\n \"The dual matrix Y begins at initialMatrixScaleDual times the \"\n \"identity matrix. Corresponds to SDPA's lambdaStar.\");\n solver_options.add_options()(\n \"feasibleCenteringParameter\",\n po::value<El::BigFloat>(&feasible_centering_parameter)\n ->default_value(El::BigFloat(\"0.1\", 10)),\n \"Shrink the complementarity X Y by this factor when the primal and \"\n \"dual \"\n \"problems are feasible. Corresponds to SDPA's betaStar.\");\n solver_options.add_options()(\n \"infeasibleCenteringParameter\",\n po::value<El::BigFloat>(&infeasible_centering_parameter)\n ->default_value(El::BigFloat(\"0.3\", 10)),\n \"Shrink the complementarity X Y by this factor when either the primal \"\n \"or dual problems are infeasible. Corresponds to SDPA's betaBar.\");\n solver_options.add_options()(\n \"stepLengthReduction\",\n po::value<El::BigFloat>(&step_length_reduction)\n ->default_value(El::BigFloat(\"0.7\", 10)),\n \"Shrink each newton step by this factor (smaller means slower, more \"\n \"stable convergence). Corresponds to SDPA's gammaStar.\");\n solver_options.add_options()(\n \"maxComplementarity\",\n po::value<El::BigFloat>(&max_complementarity)\n ->default_value(El::BigFloat(\"1e100\", 10)),\n \"Terminate if the complementarity mu = Tr(X Y)\/dim(X) \"\n \"exceeds this value.\");\n\n po::options_description cmd_line_options;\n cmd_line_options.add(required_options).add(basic_options).add(solver_options);\n\n po::variables_map variables_map;\n try\n {\n po::store(po::parse_command_line(argc, argv, cmd_line_options),\n variables_map);\n\n if(variables_map.count(\"help\") != 0)\n {\n if(El::mpi::Rank() == 0)\n {\n std::cout << cmd_line_options << '\\n';\n }\n }\n else if(variables_map.count(\"version\") != 0)\n {\n if(El::mpi::Rank() == 0)\n {\n std::cout << \"SDPB \" << SDPB_VERSION_STRING << \"\\n\";\n }\n El::PrintVersion();\n El::PrintConfig();\n El::PrintCCompilerInfo();\n El::PrintCxxCompilerInfo();\n }\n else\n {\n if(variables_map.count(\"paramFile\") != 0)\n {\n param_file\n = variables_map[\"paramFile\"].as<boost::filesystem::path>();\n std::ifstream ifs(param_file.string().c_str());\n if(!ifs.good())\n {\n throw std::runtime_error(\"Could not open '\"\n + param_file.string() + \"'\");\n }\n\n po::store(po::parse_config_file(ifs, cmd_line_options),\n variables_map);\n }\n\n po::notify(variables_map);\n\n if(!boost::filesystem::exists(sdp_directory))\n {\n throw std::runtime_error(\"sdp directory '\"\n + sdp_directory.string()\n + \"' does not exist\");\n }\n if(!boost::filesystem::is_directory(sdp_directory))\n {\n throw std::runtime_error(\"sdp directory '\"\n + sdp_directory.string()\n + \"' is not a directory\");\n }\n\n if(variables_map.count(\"outDir\") == 0)\n {\n out_directory = sdp_directory;\n if(out_directory.filename() == \".\")\n {\n out_directory = out_directory.parent_path();\n }\n out_directory += \"_out\";\n }\n\n if(variables_map.count(\"checkpointDir\") == 0)\n {\n checkpoint_out = sdp_directory;\n if(checkpoint_out.filename() == \".\")\n {\n checkpoint_out = checkpoint_out.parent_path();\n }\n checkpoint_out += \".ck\";\n }\n\n if(variables_map.count(\"initialCheckpointDir\") == 0)\n {\n checkpoint_in = checkpoint_out;\n }\n else\n {\n require_initial_checkpoint = true;\n }\n\n write_solution = Write_Solution(write_solution_string);\n\n if(El::mpi::Rank() == 0)\n {\n boost::filesystem::create_directories(out_directory);\n boost::filesystem::ofstream ofs(out_directory \/ \"out.txt\");\n if(!ofs.good())\n {\n throw std::runtime_error(\"Cannot write to outDir: \"\n + out_directory.string());\n }\n }\n\n if(int_verbosity != 0 && int_verbosity != 1 && int_verbosity != 2)\n {\n throw std::runtime_error(\n \"Invalid number for Verbosity. Only 0, 1 or 2 are allowed\\n\");\n }\n else\n {\n verbosity = static_cast<Verbosity>(int_verbosity);\n }\n }\n }\n catch(po::error &e)\n {\n El::ReportException(e);\n El::mpi::Abort(El::mpi::COMM_WORLD, 1);\n }\n}\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n#include <string>\n#include <cstring>\n#include <cmath>\n#include <ctime>\n#include <fstream>\n#include <sstream>\n#include <exception>\n#include <cstring>\n#include <boost\/tokenizer.hpp>\n#include <boost\/circular_buffer.hpp>\n#include <boost\/filesystem.hpp>\n#include <map>\n#include <set>\n#include <unordered_map>\n#include <cstdarg>\n#include \"options.hpp\"\n#include \"basic_utils\/stream_reader.hpp\"\n\ntypedef int64_t Index;\n\n#include \"basic_utils\/utils.hpp\"\n#include \"vocabulary.hpp\"\n#include \"json.hpp\"\n\nusing json = nlohmann::json;\ntypedef std::map<Index,Index> Accumulator;\nstd::vector<Accumulator> counters;\njson metadata;\n\nVocabulary vocab;\n\n#include \"basic_utils\/file_io.hpp\"\n\nstruct window_params\n{\n uint64_t size_window;\n bool symmetric;\n};\n\nstd::string get_str_time()\n{\n std::time_t result = std::time(nullptr);\n auto res = std::asctime(std::localtime(&result));\n return std::string(res);\n}\n\n\nint main(int argc, char * argv[])\n{\n auto time_start = std::time(nullptr);\n Options options = ProcessOptions(argc,argv);\n auto str_path_in = options.path_in.string();\n auto path_out=options.path_out;\n if (boost::filesystem::create_directory(path_out))\n {\n std::cerr << \"creating target directory\\n\";\n }\n metadata[\"timestamp\"] = get_str_time();\n metadata[\"path_source\"] = str_path_in;\n\n std::cerr<<\"assigning ids\\n\";\n vocab.read_from_dir(str_path_in);\n\n metadata[\"size_corpus\"] = vocab.cnt_words_processed;\n metadata[\"cnt_words_untrimmed\"] = vocab.cnt_words;\n \n vocab.reduce(options.min_frequency);\n metadata[\"min_frequency\"] = options.min_frequency;\n metadata[\"cnt_words\"] = vocab.cnt_words;\n\n std::cerr<<\"creating list of frequencies\\n\";\n\n vocab.freq_per_id.resize(vocab.cnt_words);\n vocab.lst_id2word.resize(vocab.cnt_words);\n std::fill (vocab.freq_per_id.begin(),vocab.freq_per_id.end(),0); \n std::cerr<<\"populating frequencies\\n\";\n vocab.populate_frequency();\n vocab.reassign_ids(vocab.freq_per_id);\n vocab.populate_frequency();\n vocab.populate_ids();\n auto time_end = std::time(nullptr); \n metadata[\"execution_time\"] = time_end - time_start;\n std::cerr<<\"dumping ids and frequencies\\n\";\n\n vocab.dump_ids((path_out \/ boost::filesystem::path(\"ids\")).string());\n vocab.dump_frequency((path_out \/ boost::filesystem::path(\"frequencies\")).string());\n write_vector_to_file((path_out \/ boost::filesystem::path(\"freq_per_id\")).string(),vocab.freq_per_id);\n write_value_to_file((path_out \/ boost::filesystem::path(\"metadata.json\")).string(), metadata.dump(4));\n\n return 0;\n}<commit_msg>style<commit_after>#include <iostream>\n#include <string>\n#include <cstring>\n#include <cmath>\n#include <ctime>\n#include <fstream>\n#include <sstream>\n#include <exception>\n#include <cstring>\n#include <boost\/tokenizer.hpp>\n#include <boost\/circular_buffer.hpp>\n#include <boost\/filesystem.hpp>\n#include <map>\n#include <set>\n#include <unordered_map>\n#include <cstdarg>\n#include \"options.hpp\"\n#include \"basic_utils\/stream_reader.hpp\"\n\ntypedef int64_t Index;\n\n#include \"basic_utils\/utils.hpp\"\n#include \"vocabulary.hpp\"\n#include \"json.hpp\"\n\nusing json = nlohmann::json;\ntypedef std::map<Index, Index> Accumulator;\nstd::vector<Accumulator> counters;\njson metadata;\n\nVocabulary vocab;\n\n#include \"basic_utils\/file_io.hpp\"\n\nstruct window_params\n{\n uint64_t size_window;\n bool symmetric;\n};\n\nstd::string get_str_time()\n{\n std::time_t result = std::time(nullptr);\n auto res = std::asctime(std::localtime(&result));\n return std::string(res);\n}\n\n\nint main(int argc, char * argv[])\n{\n auto time_start = std::time(nullptr);\n Options options = ProcessOptions(argc, argv);\n auto str_path_in = options.path_in.string();\n auto path_out = options.path_out;\n if (boost::filesystem::create_directory(path_out))\n {\n std::cerr << \"creating target directory\\n\";\n }\n metadata[\"timestamp\"] = get_str_time();\n metadata[\"path_source\"] = str_path_in;\n\n std::cerr << \"assigning ids\\n\";\n vocab.read_from_dir(str_path_in);\n\n metadata[\"size_corpus\"] = vocab.cnt_words_processed;\n metadata[\"cnt_words_untrimmed\"] = vocab.cnt_words;\n\n vocab.reduce(options.min_frequency);\n metadata[\"min_frequency\"] = options.min_frequency;\n metadata[\"cnt_words\"] = vocab.cnt_words;\n\n std::cerr << \"creating list of frequencies\\n\";\n\n vocab.freq_per_id.resize(vocab.cnt_words);\n vocab.lst_id2word.resize(vocab.cnt_words);\n std::fill (vocab.freq_per_id.begin(), vocab.freq_per_id.end(), 0);\n std::cerr << \"populating frequencies\\n\";\n vocab.populate_frequency();\n vocab.reassign_ids(vocab.freq_per_id);\n vocab.populate_frequency();\n vocab.populate_ids();\n auto time_end = std::time(nullptr);\n metadata[\"execution_time\"] = time_end - time_start;\n std::cerr << \"dumping ids and frequencies\\n\";\n\n vocab.dump_ids((path_out \/ boost::filesystem::path(\"ids\")).string());\n vocab.dump_frequency((path_out \/ boost::filesystem::path(\"frequencies\")).string());\n write_vector_to_file((path_out \/ boost::filesystem::path(\"freq_per_id\")).string(), vocab.freq_per_id);\n write_value_to_file((path_out \/ boost::filesystem::path(\"metadata.json\")).string(), metadata.dump(4));\n\n return 0;\n}<|endoftext|>"} {"text":"<commit_before>\/**\n * \\class DirectionlessOdometer\n * A class to represent the common - directionless - Odometers (speed encoders)\n * that can be used to primarily measure the travelled distance of the car\n * as well as its speed.\n *\/\n#pragma once\n\n#include <stdint.h>\n\n#include \"..\/..\/..\/runtime\/Runtime.hpp\"\n#include \"..\/Odometer.hpp\"\n\n#ifdef SMARTCAR_BUILD_FOR_ARDUINO\n#include \"..\/..\/..\/runtime\/arduino_runtime\/ArduinoRuntime.hpp\"\nextern ArduinoRuntime arduinoRuntime;\n#endif\n\nclass DirectionlessOdometer : public Odometer\n{\npublic:\n#ifdef SMARTCAR_BUILD_FOR_ARDUINO\n \/**\n * Constructs an odometer that can measure distance, speed but not direction\n * @param pulsesPerMeter The amount of odometer pulses that constitute a meter\n *\n * **Example:**\n * \\code\n * unsigned short ODOMETER_PIN = 32;\n * unsigned long PULSES_PER_METER = 110;\n *\n * DirectionlessOdometer odometer(ODOMETER_PIN,\n * []() { odometer.update(); },\n * PULSES_PER_METER);\n * \\endcode\n *\/\n DirectionlessOdometer(uint8_t pin,\n InterruptCallback callback,\n unsigned long pulsesPerMeter,\n Runtime& runtime = arduinoRuntime);\n#else\n DirectionlessOdometer(uint8_t pin,\n InterruptCallback callback,\n unsigned long pulsesPerMeter,\n Runtime& runtime);\n#endif\n\n virtual ~DirectionlessOdometer() = default;\n\n \/* Check `Odometer` interface for documentation *\/\n long getDistance() override;\n\n \/* Check `Odometer` interface for documentation *\/\n float getSpeed() override;\n\n \/* Check `Odometer` interface for documentation *\/\n bool isAttached() const override;\n\n \/* Check `Odometer` interface for documentation *\/\n bool providesDirection() const override;\n\n \/**\n * Resets the total travelled distance and speed to `0`\n *\/\n virtual void reset();\n\n \/**\n * Conducts the distance and speed measurements.\n * Updates the current dt with the time difference between the last two pulses\n * and increases the pulse counter.\n * **Do not** call it directly in your sketch!\n * Instead, pass it in a lambda to the constructor.\n *\/\n virtual void update();\n\n volatile unsigned long mPulsesCounter{ 0 };\n\nprotected:\n const float mPulsesPerMeterRatio;\n\nprivate:\n const unsigned long mMillimetersPerPulse;\n Runtime& mRuntime;\n const bool kSensorAttached;\n \/\/ volatile unsigned long mPulsesCounter{ 0 };\n volatile unsigned long mPreviousPulse{ 0 };\n volatile unsigned long mDt{ 0 };\n};\n\n\/**\n * \\example findPulsesPerMeter.ino\n * An example on how to determine how many pulses are emitted from your Odometer\n * for every meter travelled. The output should be supplied to the constructor.\n *\n * \\example singleOdometer.ino\n * An example on how to get the travelled distance from a single DirectionlessOdometer.\n *\n * \\example twoOdometers.ino\n * An example on how to get the travelled distance from two DirectionlessOdometer.\n *\/\n<commit_msg>Revert pulses counter to being a private variable<commit_after>\/**\n * \\class DirectionlessOdometer\n * A class to represent the common - directionless - Odometers (speed encoders)\n * that can be used to primarily measure the travelled distance of the car\n * as well as its speed.\n *\/\n#pragma once\n\n#include <stdint.h>\n\n#include \"..\/..\/..\/runtime\/Runtime.hpp\"\n#include \"..\/Odometer.hpp\"\n\n#ifdef SMARTCAR_BUILD_FOR_ARDUINO\n#include \"..\/..\/..\/runtime\/arduino_runtime\/ArduinoRuntime.hpp\"\nextern ArduinoRuntime arduinoRuntime;\n#endif\n\nclass DirectionlessOdometer : public Odometer\n{\npublic:\n#ifdef SMARTCAR_BUILD_FOR_ARDUINO\n \/**\n * Constructs an odometer that can measure distance, speed but not direction\n * @param pulsesPerMeter The amount of odometer pulses that constitute a meter\n *\n * **Example:**\n * \\code\n * unsigned short ODOMETER_PIN = 32;\n * unsigned long PULSES_PER_METER = 110;\n *\n * DirectionlessOdometer odometer(ODOMETER_PIN,\n * []() { odometer.update(); },\n * PULSES_PER_METER);\n * \\endcode\n *\/\n DirectionlessOdometer(uint8_t pin,\n InterruptCallback callback,\n unsigned long pulsesPerMeter,\n Runtime& runtime = arduinoRuntime);\n#else\n DirectionlessOdometer(uint8_t pin,\n InterruptCallback callback,\n unsigned long pulsesPerMeter,\n Runtime& runtime);\n#endif\n\n virtual ~DirectionlessOdometer() = default;\n\n \/* Check `Odometer` interface for documentation *\/\n long getDistance() override;\n\n \/* Check `Odometer` interface for documentation *\/\n float getSpeed() override;\n\n \/* Check `Odometer` interface for documentation *\/\n bool isAttached() const override;\n\n \/* Check `Odometer` interface for documentation *\/\n bool providesDirection() const override;\n\n \/**\n * Resets the total travelled distance and speed to `0`\n *\/\n virtual void reset();\n\n \/**\n * Conducts the distance and speed measurements.\n * Updates the current dt with the time difference between the last two pulses\n * and increases the pulse counter.\n * **Do not** call it directly in your sketch!\n * Instead, pass it in a lambda to the constructor.\n *\/\n virtual void update();\n\nprotected:\n const float mPulsesPerMeterRatio;\n\nprivate:\n const unsigned long mMillimetersPerPulse;\n Runtime& mRuntime;\n const bool kSensorAttached;\n volatile unsigned long mPulsesCounter{ 0 };\n volatile unsigned long mPreviousPulse{ 0 };\n volatile unsigned long mDt{ 0 };\n};\n\n\/**\n * \\example findPulsesPerMeter.ino\n * An example on how to determine how many pulses are emitted from your Odometer\n * for every meter travelled. The output should be supplied to the constructor.\n *\n * \\example singleOdometer.ino\n * An example on how to get the travelled distance from a single DirectionlessOdometer.\n *\n * \\example twoOdometers.ino\n * An example on how to get the travelled distance from two DirectionlessOdometer.\n *\/\n<|endoftext|>"} {"text":"<commit_before>\/\/===-- LLVMTargetMachine.cpp - Implement the LLVMTargetMachine class -----===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file was developed by Chris Lattner and is distributed under\n\/\/ the University of Illinois Open Source License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This file implements the LLVMTargetMachine class.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/Target\/TargetMachine.h\"\n#include \"llvm\/PassManager.h\"\n#include \"llvm\/Pass.h\"\n#include \"llvm\/Assembly\/PrintModulePass.h\"\n#include \"llvm\/Analysis\/LoopPass.h\"\n#include \"llvm\/CodeGen\/Passes.h\"\n#include \"llvm\/Target\/TargetOptions.h\"\n#include \"llvm\/Transforms\/Scalar.h\"\n#include \"llvm\/Support\/CommandLine.h\"\nusing namespace llvm;\n\nstatic cl::opt<bool> PrintLSR(\"print-lsr-output\", cl::Hidden,\n cl::desc(\"Print LLVM IR produced by the loop-reduce pass\"));\nstatic cl::opt<bool> PrintISelInput(\"print-isel-input\", cl::Hidden,\n cl::desc(\"Print LLVM IR input to isel pass\"));\n\nFileModel::Model\nLLVMTargetMachine::addPassesToEmitFile(FunctionPassManager &PM,\n std::ostream &Out,\n CodeGenFileType FileType,\n bool Fast) {\n \/\/ Standard LLVM-Level Passes.\n \n \/\/ Run loop strength reduction before anything else.\n if (!Fast) {\n PM.add(createLoopStrengthReducePass(getTargetLowering()));\n if (PrintLSR)\n PM.add(new PrintFunctionPass(\"\\n\\n*** Code after LSR *** \\n\", &cerr));\n }\n \n \/\/ FIXME: Implement efficient support for garbage collection intrinsics.\n PM.add(createLowerGCPass());\n \n \/\/ FIXME: Implement the invoke\/unwind instructions!\n if (!ExceptionHandling)\n PM.add(createLowerInvokePass(getTargetLowering()));\n \n \/\/ Make sure that no unreachable blocks are instruction selected.\n PM.add(createUnreachableBlockEliminationPass());\n\n if (!Fast)\n PM.add(createCodeGenPreparePass(getTargetLowering()));\n\n if (PrintISelInput)\n PM.add(new PrintFunctionPass(\"\\n\\n*** Final LLVM Code input to ISel *** \\n\",\n &cerr));\n \n \/\/ Ask the target for an isel.\n if (addInstSelector(PM, Fast))\n return FileModel::Error;\n\n \/\/ Print the instruction selected machine code...\n if (PrintMachineCode)\n PM.add(createMachineFunctionPrinterPass(cerr));\n \n \/\/ Perform register allocation to convert to a concrete x86 representation\n PM.add(createRegisterAllocator());\n \n if (PrintMachineCode)\n PM.add(createMachineFunctionPrinterPass(cerr));\n\n \/\/ Run post-ra passes.\n if (addPostRegAlloc(PM, Fast) && PrintMachineCode)\n PM.add(createMachineFunctionPrinterPass(cerr));\n\n \/\/ Insert prolog\/epilog code. Eliminate abstract frame index references...\n PM.add(createPrologEpilogCodeInserter());\n \n \/\/ Branch folding must be run after regalloc and prolog\/epilog insertion.\n if (!Fast)\n PM.add(createBranchFoldingPass(getEnableTailMergeDefault()));\n \n \/\/ Fold redundant debug labels.\n PM.add(createDebugLabelFoldingPass());\n \n if (PrintMachineCode) \/\/ Print the register-allocated code\n PM.add(createMachineFunctionPrinterPass(cerr));\n\n if (addPreEmitPass(PM, Fast) && PrintMachineCode)\n PM.add(createMachineFunctionPrinterPass(cerr));\n\n switch (FileType) {\n default:\n break;\n case TargetMachine::AssemblyFile:\n if (addAssemblyEmitter(PM, Fast, Out))\n return FileModel::Error;\n return FileModel::AsmFile;\n case TargetMachine::ObjectFile:\n if (getMachOWriterInfo())\n return FileModel::MachOFile;\n else if (getELFWriterInfo())\n return FileModel::ElfFile;\n }\n\n return FileModel::Error;\n}\n \n\/\/\/ addPassesToEmitFileFinish - If the passes to emit the specified file had to\n\/\/\/ be split up (e.g., to add an object writer pass), this method can be used to\n\/\/\/ finish up adding passes to emit the file, if necessary.\nbool LLVMTargetMachine::addPassesToEmitFileFinish(FunctionPassManager &PM,\n MachineCodeEmitter *MCE,\n bool Fast) {\n if (MCE)\n addSimpleCodeEmitter(PM, Fast, *MCE);\n\n \/\/ Delete machine code for this function\n PM.add(createMachineCodeDeleter());\n\n return false; \/\/ success!\n}\n\n\/\/\/ addPassesToEmitMachineCode - Add passes to the specified pass manager to\n\/\/\/ get machine code emitted. This uses a MachineCodeEmitter object to handle\n\/\/\/ actually outputting the machine code and resolving things like the address\n\/\/\/ of functions. This method should returns true if machine code emission is\n\/\/\/ not supported.\n\/\/\/\nbool LLVMTargetMachine::addPassesToEmitMachineCode(FunctionPassManager &PM,\n MachineCodeEmitter &MCE,\n bool Fast) {\n \/\/ Standard LLVM-Level Passes.\n \n \/\/ Run loop strength reduction before anything else.\n if (!Fast) {\n PM.add(createLoopStrengthReducePass(getTargetLowering()));\n if (PrintLSR)\n PM.add(new PrintFunctionPass(\"\\n\\n*** Code after LSR *** \\n\", &cerr));\n }\n \n \/\/ FIXME: Implement efficient support for garbage collection intrinsics.\n PM.add(createLowerGCPass());\n \n \/\/ FIXME: Implement the invoke\/unwind instructions!\n PM.add(createLowerInvokePass(getTargetLowering()));\n \n \/\/ Make sure that no unreachable blocks are instruction selected.\n PM.add(createUnreachableBlockEliminationPass());\n\n if (!Fast)\n PM.add(createCodeGenPreparePass(getTargetLowering()));\n\n if (PrintISelInput)\n PM.add(new PrintFunctionPass(\"\\n\\n*** Final LLVM Code input to ISel *** \\n\",\n &cerr));\n\n \/\/ Ask the target for an isel.\n if (addInstSelector(PM, Fast))\n return true;\n\n \/\/ Print the instruction selected machine code...\n if (PrintMachineCode)\n PM.add(createMachineFunctionPrinterPass(cerr));\n \n \/\/ Perform register allocation to convert to a concrete x86 representation\n PM.add(createRegisterAllocator());\n \n if (PrintMachineCode)\n PM.add(createMachineFunctionPrinterPass(cerr));\n\n \/\/ Run post-ra passes.\n if (addPostRegAlloc(PM, Fast) && PrintMachineCode)\n PM.add(createMachineFunctionPrinterPass(cerr));\n\n \/\/ Insert prolog\/epilog code. Eliminate abstract frame index references...\n PM.add(createPrologEpilogCodeInserter());\n \n if (PrintMachineCode) \/\/ Print the register-allocated code\n PM.add(createMachineFunctionPrinterPass(cerr));\n \n \/\/ Branch folding must be run after regalloc and prolog\/epilog insertion.\n if (!Fast)\n PM.add(createBranchFoldingPass(getEnableTailMergeDefault()));\n \n if (addPreEmitPass(PM, Fast) && PrintMachineCode)\n PM.add(createMachineFunctionPrinterPass(cerr));\n\n addCodeEmitter(PM, Fast, MCE);\n \n \/\/ Delete machine code for this function\n PM.add(createMachineCodeDeleter());\n \n return false; \/\/ success!\n}\n<commit_msg>Exception handling has been implemented.<commit_after>\/\/===-- LLVMTargetMachine.cpp - Implement the LLVMTargetMachine class -----===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file was developed by Chris Lattner and is distributed under\n\/\/ the University of Illinois Open Source License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This file implements the LLVMTargetMachine class.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/Target\/TargetMachine.h\"\n#include \"llvm\/PassManager.h\"\n#include \"llvm\/Pass.h\"\n#include \"llvm\/Assembly\/PrintModulePass.h\"\n#include \"llvm\/Analysis\/LoopPass.h\"\n#include \"llvm\/CodeGen\/Passes.h\"\n#include \"llvm\/Target\/TargetOptions.h\"\n#include \"llvm\/Transforms\/Scalar.h\"\n#include \"llvm\/Support\/CommandLine.h\"\nusing namespace llvm;\n\nstatic cl::opt<bool> PrintLSR(\"print-lsr-output\", cl::Hidden,\n cl::desc(\"Print LLVM IR produced by the loop-reduce pass\"));\nstatic cl::opt<bool> PrintISelInput(\"print-isel-input\", cl::Hidden,\n cl::desc(\"Print LLVM IR input to isel pass\"));\n\nFileModel::Model\nLLVMTargetMachine::addPassesToEmitFile(FunctionPassManager &PM,\n std::ostream &Out,\n CodeGenFileType FileType,\n bool Fast) {\n \/\/ Standard LLVM-Level Passes.\n \n \/\/ Run loop strength reduction before anything else.\n if (!Fast) {\n PM.add(createLoopStrengthReducePass(getTargetLowering()));\n if (PrintLSR)\n PM.add(new PrintFunctionPass(\"\\n\\n*** Code after LSR *** \\n\", &cerr));\n }\n \n \/\/ FIXME: Implement efficient support for garbage collection intrinsics.\n PM.add(createLowerGCPass());\n\n if (!ExceptionHandling)\n PM.add(createLowerInvokePass(getTargetLowering()));\n\n \/\/ Make sure that no unreachable blocks are instruction selected.\n PM.add(createUnreachableBlockEliminationPass());\n\n if (!Fast)\n PM.add(createCodeGenPreparePass(getTargetLowering()));\n\n if (PrintISelInput)\n PM.add(new PrintFunctionPass(\"\\n\\n*** Final LLVM Code input to ISel *** \\n\",\n &cerr));\n \n \/\/ Ask the target for an isel.\n if (addInstSelector(PM, Fast))\n return FileModel::Error;\n\n \/\/ Print the instruction selected machine code...\n if (PrintMachineCode)\n PM.add(createMachineFunctionPrinterPass(cerr));\n \n \/\/ Perform register allocation to convert to a concrete x86 representation\n PM.add(createRegisterAllocator());\n \n if (PrintMachineCode)\n PM.add(createMachineFunctionPrinterPass(cerr));\n\n \/\/ Run post-ra passes.\n if (addPostRegAlloc(PM, Fast) && PrintMachineCode)\n PM.add(createMachineFunctionPrinterPass(cerr));\n\n \/\/ Insert prolog\/epilog code. Eliminate abstract frame index references...\n PM.add(createPrologEpilogCodeInserter());\n \n \/\/ Branch folding must be run after regalloc and prolog\/epilog insertion.\n if (!Fast)\n PM.add(createBranchFoldingPass(getEnableTailMergeDefault()));\n \n \/\/ Fold redundant debug labels.\n PM.add(createDebugLabelFoldingPass());\n \n if (PrintMachineCode) \/\/ Print the register-allocated code\n PM.add(createMachineFunctionPrinterPass(cerr));\n\n if (addPreEmitPass(PM, Fast) && PrintMachineCode)\n PM.add(createMachineFunctionPrinterPass(cerr));\n\n switch (FileType) {\n default:\n break;\n case TargetMachine::AssemblyFile:\n if (addAssemblyEmitter(PM, Fast, Out))\n return FileModel::Error;\n return FileModel::AsmFile;\n case TargetMachine::ObjectFile:\n if (getMachOWriterInfo())\n return FileModel::MachOFile;\n else if (getELFWriterInfo())\n return FileModel::ElfFile;\n }\n\n return FileModel::Error;\n}\n \n\/\/\/ addPassesToEmitFileFinish - If the passes to emit the specified file had to\n\/\/\/ be split up (e.g., to add an object writer pass), this method can be used to\n\/\/\/ finish up adding passes to emit the file, if necessary.\nbool LLVMTargetMachine::addPassesToEmitFileFinish(FunctionPassManager &PM,\n MachineCodeEmitter *MCE,\n bool Fast) {\n if (MCE)\n addSimpleCodeEmitter(PM, Fast, *MCE);\n\n \/\/ Delete machine code for this function\n PM.add(createMachineCodeDeleter());\n\n return false; \/\/ success!\n}\n\n\/\/\/ addPassesToEmitMachineCode - Add passes to the specified pass manager to\n\/\/\/ get machine code emitted. This uses a MachineCodeEmitter object to handle\n\/\/\/ actually outputting the machine code and resolving things like the address\n\/\/\/ of functions. This method should returns true if machine code emission is\n\/\/\/ not supported.\n\/\/\/\nbool LLVMTargetMachine::addPassesToEmitMachineCode(FunctionPassManager &PM,\n MachineCodeEmitter &MCE,\n bool Fast) {\n \/\/ Standard LLVM-Level Passes.\n \n \/\/ Run loop strength reduction before anything else.\n if (!Fast) {\n PM.add(createLoopStrengthReducePass(getTargetLowering()));\n if (PrintLSR)\n PM.add(new PrintFunctionPass(\"\\n\\n*** Code after LSR *** \\n\", &cerr));\n }\n \n \/\/ FIXME: Implement efficient support for garbage collection intrinsics.\n PM.add(createLowerGCPass());\n \n \/\/ FIXME: Implement the invoke\/unwind instructions!\n PM.add(createLowerInvokePass(getTargetLowering()));\n \n \/\/ Make sure that no unreachable blocks are instruction selected.\n PM.add(createUnreachableBlockEliminationPass());\n\n if (!Fast)\n PM.add(createCodeGenPreparePass(getTargetLowering()));\n\n if (PrintISelInput)\n PM.add(new PrintFunctionPass(\"\\n\\n*** Final LLVM Code input to ISel *** \\n\",\n &cerr));\n\n \/\/ Ask the target for an isel.\n if (addInstSelector(PM, Fast))\n return true;\n\n \/\/ Print the instruction selected machine code...\n if (PrintMachineCode)\n PM.add(createMachineFunctionPrinterPass(cerr));\n \n \/\/ Perform register allocation to convert to a concrete x86 representation\n PM.add(createRegisterAllocator());\n \n if (PrintMachineCode)\n PM.add(createMachineFunctionPrinterPass(cerr));\n\n \/\/ Run post-ra passes.\n if (addPostRegAlloc(PM, Fast) && PrintMachineCode)\n PM.add(createMachineFunctionPrinterPass(cerr));\n\n \/\/ Insert prolog\/epilog code. Eliminate abstract frame index references...\n PM.add(createPrologEpilogCodeInserter());\n \n if (PrintMachineCode) \/\/ Print the register-allocated code\n PM.add(createMachineFunctionPrinterPass(cerr));\n \n \/\/ Branch folding must be run after regalloc and prolog\/epilog insertion.\n if (!Fast)\n PM.add(createBranchFoldingPass(getEnableTailMergeDefault()));\n \n if (addPreEmitPass(PM, Fast) && PrintMachineCode)\n PM.add(createMachineFunctionPrinterPass(cerr));\n\n addCodeEmitter(PM, Fast, MCE);\n \n \/\/ Delete machine code for this function\n PM.add(createMachineCodeDeleter());\n \n return false; \/\/ success!\n}\n<|endoftext|>"} {"text":"<commit_before>\/* bzflag\n* Copyright (c) 1993 - 2005 Tim Riker\n*\n* This package is free software; you can redistribute it and\/or\n* modify it under the terms of the license found in the file\n* named COPYING that should have accompanied this file.\n*\n* THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR\n* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED\n* WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.\n*\/\n\n#ifdef _MSC_VER\n#pragma warning( 4: 4786)\n#define _WINSOCK2API_\n#endif\n\n\/\/ bzflag common header\n#include \"common.h\"\n\n\/\/ class interface header\n#include \"URLManager.h\"\n\n\/\/ system headers\n#include <winsock2.h>\n#ifdef HAVE_CURL\n#include <curl\/curl.h>\n#endif\n#include <iostream>\n\n\/\/ common implementation headers\n#include \"bzfio.h\"\n#include \"StateDatabase.h\"\n\n\ntemplate <>\nURLManager* Singleton<URLManager>::_instance = (URLManager*)0;\n\n#ifdef HAVE_CURL\nstatic size_t writeFunction(void *ptr, size_t size, size_t nmemb, void *stream);\n#endif \/\/ HAVE_CURL\n\nbool URLManager::getURL(const std::string URL, std::string &data)\n{\n clearInternal();\n\n if (!beginGet(URL))\n return false;\n\n char* newData = (char*)malloc(theLen + 1);\n memcpy(newData, theData, theLen);\n newData[theLen] = 0;\n\n data = newData;\n free(newData);\n\n return true;\n}\n\nbool URLManager::getURL(const std::string URL, void **data, unsigned int& size)\n{\n clearInternal();\n\n if (!beginGet(URL))\n return false;\n\n *data = malloc(theLen);\n memcpy(*data, theData, theLen);\n size = theLen;\n return true;\n}\n\nvoid URLManager::freeURLData(void *data)\n{\n free(data);\n}\n\nURLManager::URLManager()\n{\n easyHandle = NULL;\n theData = NULL;\n theLen = 0;\n\n#ifdef HAVE_CURL\n CURLcode curlResult;\n\n#if LIBCURL_VERSION_NUM >= 0x070a00\n if ((curlResult = curl_global_init(CURL_GLOBAL_NOTHING)))\n DEBUG1(\"Unexpected error from libcurl; Error: %d\\n\", curlResult);\n#endif\n\n easyHandle = curl_easy_init();\n if (!easyHandle) {\n DEBUG1(\"Something wrong with CURL\\n\");\n return;\n }\n\n CURLcode result = curl_easy_setopt((CURL*)easyHandle, CURLOPT_WRITEFUNCTION, writeFunction);\n if (result)\n DEBUG1(\"Something wrong with CURL; Error: %d\\n\", result);\n\n result = curl_easy_setopt((CURL*)easyHandle, CURLOPT_FILE, this);\n if (result)\n DEBUG1(\"Something wrong with CURL; Error: %d\\n\", result);\n#endif\n}\n\nURLManager::~URLManager()\n{\n clearInternal();\n\n#ifdef HAVE_CURL\n if (easyHandle)\n curl_easy_cleanup((CURL*)easyHandle);\n\n#if LIBCURL_VERSION_NUM >= 0x070a00\n curl_global_cleanup();\n#endif\n\n#endif\n}\n\nvoid URLManager::collectData(char* ptr, int len)\n{\n unsigned char\t*newData = (unsigned char*)malloc(theLen + len);\n if (theData)\n memcpy(newData, theData, theLen);\n\n memcpy(&(newData[theLen]), ptr, len);\n theLen += len;\n\n free(theData);\n theData = newData;\n}\n\nvoid URLManager::clearInternal()\n{\n if (theData)\n free (theData);\n\n theData = NULL;\n theLen = 0;\n}\n\n#ifdef HAVE_CURL\nbool URLManager::beginGet(const std::string URL)\n#else\nbool URLManager::beginGet(const std::string)\n#endif\n{\n#ifdef HAVE_CURL\n CURLcode result = CURLE_OK;\n if (!easyHandle) {\n return false;\n }\n\n float timeout = 15;\n if (BZDB.isSet(\"httpTimeout\"))\n timeout = BZDB.eval(\"httpTimeout\");\n\n#if LIBCURL_VERSION_NUM >= 0x070a00\n result = curl_easy_setopt((CURL*)easyHandle, CURLOPT_NOSIGNAL, true);\n if (result) {\n DEBUG1(\"Something wrong with CURL; Error: %d\\n\", result);\n }\n#endif\n\n result = curl_easy_setopt((CURL*)easyHandle, CURLOPT_TIMEOUT, timeout);\n if (result) {\n DEBUG1(\"Something wrong with CURL; Error: %d\\n\", result);\n }\n\n result = curl_easy_setopt((CURL*)easyHandle, CURLOPT_URL, URL.c_str());\n if (result) {\n DEBUG1(\"Something wrong with CURL; Error: %d\\n\", result);\n }\n\n \/\/ FIXME: This could block for a _long_ time.\n result = curl_easy_perform((CURL*)easyHandle);\n if (result == (CURLcode)CURLOPT_ERRORBUFFER) {\n DEBUG1(\"Error: server reported: %d\\n\", result);\n return false;\n } else if (result) {\n DEBUG1(\"Something wrong with CURL; Error: %d\\n\", result);\n return false;\n }\n\n result = curl_easy_setopt((CURL*)easyHandle, CURLOPT_URL, NULL);\n if (result) {\n DEBUG1(\"Something wrong with CURL; Error: %d\\n\", result);\n return false;\n }\n\n if (!theData)\n return false;\n\n return true;\n#else\n return false;\n#endif \/\/ HAVE_CURL\n}\n\n#ifdef HAVE_CURL\nstatic size_t writeFunction(void *ptr, size_t size, size_t nmemb, void *stream)\n{\n int len = size * nmemb;\n ((URLManager*)stream)->collectData((char*)ptr, len);\n return len;\n}\n#endif \/\/ HAVE_CURL\n\n\/\/ Local Variables: ***\n\/\/ mode:C++ ***\n\/\/ tab-width: 8 ***\n\/\/ c-basic-offset: 2 ***\n\/\/ indent-tabs-mode: t ***\n\/\/ End: ***\n\/\/ ex: shiftwidth=2 tabstop=8\n<commit_msg>yeah, and only include winsock on windows<commit_after>\/* bzflag\n* Copyright (c) 1993 - 2005 Tim Riker\n*\n* This package is free software; you can redistribute it and\/or\n* modify it under the terms of the license found in the file\n* named COPYING that should have accompanied this file.\n*\n* THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR\n* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED\n* WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.\n*\/\n\n#ifdef _MSC_VER\n#pragma warning( 4: 4786)\n#define _WINSOCK2API_\n#endif\n\n\/\/ bzflag common header\n#include \"common.h\"\n\n\/\/ class interface header\n#include \"URLManager.h\"\n\n\/\/ system headers\n#ifdef _WIN32\n#include <winsock2.h>\n#endif\n#ifdef HAVE_CURL\n#include <curl\/curl.h>\n#endif\n#include <iostream>\n\n\/\/ common implementation headers\n#include \"bzfio.h\"\n#include \"StateDatabase.h\"\n\n\ntemplate <>\nURLManager* Singleton<URLManager>::_instance = (URLManager*)0;\n\n#ifdef HAVE_CURL\nstatic size_t writeFunction(void *ptr, size_t size, size_t nmemb, void *stream);\n#endif \/\/ HAVE_CURL\n\nbool URLManager::getURL(const std::string URL, std::string &data)\n{\n clearInternal();\n\n if (!beginGet(URL))\n return false;\n\n char* newData = (char*)malloc(theLen + 1);\n memcpy(newData, theData, theLen);\n newData[theLen] = 0;\n\n data = newData;\n free(newData);\n\n return true;\n}\n\nbool URLManager::getURL(const std::string URL, void **data, unsigned int& size)\n{\n clearInternal();\n\n if (!beginGet(URL))\n return false;\n\n *data = malloc(theLen);\n memcpy(*data, theData, theLen);\n size = theLen;\n return true;\n}\n\nvoid URLManager::freeURLData(void *data)\n{\n free(data);\n}\n\nURLManager::URLManager()\n{\n easyHandle = NULL;\n theData = NULL;\n theLen = 0;\n\n#ifdef HAVE_CURL\n CURLcode curlResult;\n\n#if LIBCURL_VERSION_NUM >= 0x070a00\n if ((curlResult = curl_global_init(CURL_GLOBAL_NOTHING)))\n DEBUG1(\"Unexpected error from libcurl; Error: %d\\n\", curlResult);\n#endif\n\n easyHandle = curl_easy_init();\n if (!easyHandle) {\n DEBUG1(\"Something wrong with CURL\\n\");\n return;\n }\n\n CURLcode result = curl_easy_setopt((CURL*)easyHandle, CURLOPT_WRITEFUNCTION, writeFunction);\n if (result)\n DEBUG1(\"Something wrong with CURL; Error: %d\\n\", result);\n\n result = curl_easy_setopt((CURL*)easyHandle, CURLOPT_FILE, this);\n if (result)\n DEBUG1(\"Something wrong with CURL; Error: %d\\n\", result);\n#endif\n}\n\nURLManager::~URLManager()\n{\n clearInternal();\n\n#ifdef HAVE_CURL\n if (easyHandle)\n curl_easy_cleanup((CURL*)easyHandle);\n\n#if LIBCURL_VERSION_NUM >= 0x070a00\n curl_global_cleanup();\n#endif\n\n#endif\n}\n\nvoid URLManager::collectData(char* ptr, int len)\n{\n unsigned char\t*newData = (unsigned char*)malloc(theLen + len);\n if (theData)\n memcpy(newData, theData, theLen);\n\n memcpy(&(newData[theLen]), ptr, len);\n theLen += len;\n\n free(theData);\n theData = newData;\n}\n\nvoid URLManager::clearInternal()\n{\n if (theData)\n free (theData);\n\n theData = NULL;\n theLen = 0;\n}\n\n#ifdef HAVE_CURL\nbool URLManager::beginGet(const std::string URL)\n#else\nbool URLManager::beginGet(const std::string)\n#endif\n{\n#ifdef HAVE_CURL\n CURLcode result = CURLE_OK;\n if (!easyHandle) {\n return false;\n }\n\n float timeout = 15;\n if (BZDB.isSet(\"httpTimeout\"))\n timeout = BZDB.eval(\"httpTimeout\");\n\n#if LIBCURL_VERSION_NUM >= 0x070a00\n result = curl_easy_setopt((CURL*)easyHandle, CURLOPT_NOSIGNAL, true);\n if (result) {\n DEBUG1(\"Something wrong with CURL; Error: %d\\n\", result);\n }\n#endif\n\n result = curl_easy_setopt((CURL*)easyHandle, CURLOPT_TIMEOUT, timeout);\n if (result) {\n DEBUG1(\"Something wrong with CURL; Error: %d\\n\", result);\n }\n\n result = curl_easy_setopt((CURL*)easyHandle, CURLOPT_URL, URL.c_str());\n if (result) {\n DEBUG1(\"Something wrong with CURL; Error: %d\\n\", result);\n }\n\n \/\/ FIXME: This could block for a _long_ time.\n result = curl_easy_perform((CURL*)easyHandle);\n if (result == (CURLcode)CURLOPT_ERRORBUFFER) {\n DEBUG1(\"Error: server reported: %d\\n\", result);\n return false;\n } else if (result) {\n DEBUG1(\"Something wrong with CURL; Error: %d\\n\", result);\n return false;\n }\n\n result = curl_easy_setopt((CURL*)easyHandle, CURLOPT_URL, NULL);\n if (result) {\n DEBUG1(\"Something wrong with CURL; Error: %d\\n\", result);\n return false;\n }\n\n if (!theData)\n return false;\n\n return true;\n#else\n return false;\n#endif \/\/ HAVE_CURL\n}\n\n#ifdef HAVE_CURL\nstatic size_t writeFunction(void *ptr, size_t size, size_t nmemb, void *stream)\n{\n int len = size * nmemb;\n ((URLManager*)stream)->collectData((char*)ptr, len);\n return len;\n}\n#endif \/\/ HAVE_CURL\n\n\/\/ Local Variables: ***\n\/\/ mode:C++ ***\n\/\/ tab-width: 8 ***\n\/\/ c-basic-offset: 2 ***\n\/\/ indent-tabs-mode: t ***\n\/\/ End: ***\n\/\/ ex: shiftwidth=2 tabstop=8\n<|endoftext|>"} {"text":"<commit_before>#include <deal.II\/fe\/fe_values.h>\n\n#include <boost\/algorithm\/string.hpp>\n#include <deal.II\/dofs\/dof_tools.h>\n#include <deal.II\/grid\/cell_id.h>\n\n#include <deal.II\/lac\/petsc_solver.h>\n#include <deal.II\/lac\/solver_bicgstab.h>\n\n#include <algorithm>\n\n#include \"transport_base.h\"\n#include \"..\/aqdata\/aq_base.h\"\n#include \"..\/aqdata\/aq_lsgc.h\"\n\nusing namespace dealii;\n\ntemplate <int dim>\nBartDriver<dim>::BartDriver (ParameterHandler &prm)\n:\nmpi_communicator (MPI_COMM_WORLD),\ntriangulation (mpi_communicator,\n typename Triangulation<dim>::MeshSmoothing\n (Triangulation<dim>::smoothing_on_refinement |\n Triangulation<dim>::smoothing_on_coarsening)),\ndof_handler (triangulation),\nprm(prm),\ntransport_model_name(prm.get(\"transport model\")),\naq_name(prm.get(\"angular quadrature name\")),\ndiscretization(prm.get(\"spatial discretization\")),\nn_group(prm.get_integer(\"number of groups\")),\nn_azi(prm.get_integer(\"angular quadrature order\")),\nis_eigen_problem(prm.get_bool(\"do eigenvalue calculations\")),\ndo_nda(prm.get_bool(\"do NDA\")),\ndo_print_sn_quad(prm.get_bool(\"do print angular quadrature info\")),\nhave_reflective_bc(prm.get_bool(\"have reflective BC\")),\np_order(prm.get_integer(\"finite element polynomial degree\")),\nglobal_refinements(prm.get_integer(\"uniform refinements\")),\nnamebase(prm.get(\"output file name base\")),\nho_linear_solver_name(prm.get(\"HO linear solver name\")),\nho_preconditioner_name(prm.get(\"HO preconditioner name\")),\npcout(std::cout,\n (Utilities::MPI::this_mpi_process(mpi_communicator)\n == 0))\n{\n aqd_ptr = build_aq_model (prm)\n aqd_ptr->make_aq (prm);\n n_total_ho_vars = aqd_ptr->get_n_total_ho_vars ();\n n_azi = aqd_ptr->get_sn_order ();\n n_dir = aqd_ptr->get_n_dir ();\n msh_ptr = std_cxx11::shared_ptr<MeshGenerator<dim> >\n (new MeshGenerator<dim>(prm));\n this->process_input ();\n}\n\ntemplate <int dim>\nBartDriver<dim>::~BartDriver ()\n{\n dof_handler.clear();\n}\n\ntemplate <int dim>\nvoid BartDriver<dim>::report_system ()\n{\n pcout << \"SN quadrature order: \" << n_azi << std::endl\n << \"Number of angles: \" << n_dir << std::endl\n << \"Number of groups: \" << n_group << std::endl;\n\n radio (\"Transport model\", transport_model_name);\n radio (\"Spatial discretization\", discretization);\n radio (\"HO linear solver\", ho_linear_solver_name);\n if (ho_linear_solver_name!=\"direct\")\n radio (\"HO preconditioner\", ho_preconditioner_name);\n radio (\"do NDA?\", do_nda);\n \n radio (\"Number of cells\", triangulation.n_global_active_cells());\n radio (\"High-order total DoF counts\", n_total_ho_vars*dof_handler.n_dofs());\n\n if (is_eigen_problem)\n radio (\"Problem type: k-eigenvalue problem\");\n if (do_nda)\n radio (\"NDA total DoF counts\", n_group*dof_handler.n_dofs());\n radio (\"print sn quad?\", do_print_sn_quad);\n if (do_print_sn_quad &&\n Utilities::MPI::this_mpi_process(mpi_communicator)==0)\n aqd_ptr->print_angular_quad ();\n radio (\"is eigenvalue problem?\", is_eigen_problem);\n}\n\ntemplate <int dim>\nvoid BartDriver<dim>::setup_system ()\n{\n radio (\"setup system\");\n initialize_dealii_objects ();\n initialize_system_matrices_vectors ();\n}\n\ntemplate <int dim>\nvoid BartDriver<dim>::initialize_system_matrices_vectors ()\n{\n DynamicSparsityPattern dsp (relevant_dofs);\n\n if (discretization==\"dfem\")\n {\n \/*\n Table<2,DoFTools::Coupling> cell_coupling (1,1);\n Table<2,DoFTools::Coupling> face_coupling (1,1);\n\n cell_coupling[0][0] = DoFTools::nonzero;\n face_coupling[0][0] = DoFTools::nonzero;\n\n DoFTools::make_flux_sparsity_pattern (dof_handler,\n dsp,\n cell_coupling,\n face_coupling);\n *\/\n\n DoFTools::make_flux_sparsity_pattern (dof_handler,\n dsp,\n constraints,\n false);\n }\n else\n DoFTools::make_sparsity_pattern (dof_handler,\n dsp,\n constraints,\n false);\n\n \/\/ be careful with the following\n SparsityTools::distribute_sparsity_pattern (dsp,\n dof_handler.n_locally_owned_dofs_per_processor (),\n mpi_communicator,\n relevant_dofs);\n\n for (unsigned int g=0; g<n_group; ++g)\n {\n if (do_nda)\n {\n vec_lo_sys.push_back (new LA::MPI::SparseMatrix);\n vec_lo_rhs.push_back (new LA::MPI::Vector);\n vec_lo_sflx.push_back (new LA::MPI::Vector);\n vec_lo_sflx_old.push_back (new LA::MPI::Vector);\n vec_lo_fixed_rhs.push_back (new LA::MPI::Vector);\n }\n\n vec_ho_sflx.push_back (new LA::MPI::Vector);\n vec_ho_sflx_prev_gen.push_back (new LA::MPI::Vector);\n vec_ho_sflx_old.push_back (new LA::MPI::Vector);\n\n for (unsigned int i_dir=0; i_dir<n_dir; ++i_dir)\n {\n vec_ho_sys.push_back (new LA::MPI::SparseMatrix);\n vec_aflx.push_back (new LA::MPI::Vector);\n vec_ho_rhs.push_back (new LA::MPI::Vector);\n vec_ho_fixed_rhs.push_back (new LA::MPI::Vector);\n }\n }\n\n for (unsigned int g=0; g<n_group; ++g)\n {\n if (do_nda)\n {\n vec_lo_sys[g]->reinit (local_dofs,\n local_dofs,\n dsp,\n mpi_communicator);\n vec_lo_rhs[g]->reinit (local_dofs,\n mpi_communicator);\n vec_lo_fixed_rhs[g]->reinit (local_dofs,\n mpi_communicator);\n vec_lo_sflx[g]->reinit (local_dofs,\n mpi_communicator);\n vec_lo_sflx_old[g]->reinit (local_dofs,\n mpi_communicator);\n }\n\n vec_ho_sflx[g]->reinit (local_dofs,\n mpi_communicator);\n vec_ho_sflx_old[g]->reinit (local_dofs,\n mpi_communicator);\n\n for (unsigned int i_dir=0; i_dir<n_dir; ++i_dir)\n {\n vec_ho_sys[get_component_index(i_dir, g)]->reinit(local_dofs,\n local_dofs,\n dsp,\n mpi_communicator);\n vec_aflx[get_component_index(i_dir, g)]->reinit(local_dofs,\n mpi_communicator);\n vec_ho_rhs[get_component_index(i_dir, g)]->reinit (local_dofs,\n mpi_communicator);\n vec_ho_fixed_rhs[get_component_index(i_dir, g)]->reinit (local_dofs,\n mpi_communicator);\n }\n }\n}\n\ntemplate <int dim>\nvoid BartDriver<dim>::initialize_dealii_objects ()\n{\n if (discretization==\"dfem\")\n fe = (new FE_DGQ<dim> (p_order));\n else\n fe = (new FE_Q<dim> (p_order));\n\n dof_handler.distribute_dofs (*fe);\n\n local_dofs = dof_handler.locally_owned_dofs ();\n DoFTools::extract_locally_relevant_dofs (dof_handler,\n relevant_dofs);\n\n constraints.clear ();\n constraints.reinit (relevant_dofs);\n DoFTools::make_hanging_node_constraints (dof_handler,\n constraints);\n constraints.close ();\n}\n\ntemplate <int dim>\nvoid BartDriver<dim>::output_results () const\n{\n std::string sec_name = \"Graphical output\";\n DataOut<dim> data_out;\n data_out.attach_dof_handler (dof_handler);\n\n for (unsigned int g=0; g<n_group; ++g)\n {\n std::ostringstream os;\n os << \"ho_phi_g_\" << g;\n data_out.add_data_vector (sflx_proc[g], os.str ());\n }\n\n Vector<float> subdomain (triangulation.n_active_cells ());\n for (unsigned int i=0; i<subdomain.size(); ++i)\n subdomain(i) = triangulation.locally_owned_subdomain ();\n data_out.add_data_vector (subdomain, \"subdomain\");\n\n data_out.build_patches ();\n\n const std::string filename =\n (namebase + \"-\" + discretization + \"-\" + Utilities::int_to_string\n (triangulation.locally_owned_subdomain (), 4));\n std::ofstream output ((filename + \".vtu\").c_str ());\n data_out.write_vtu (output);\n\n if (Utilities::MPI::this_mpi_process(mpi_communicator) == 0)\n {\n std::vector<std::string> filenames;\n for (unsigned int i=0;\n i<Utilities::MPI::n_mpi_processes(mpi_communicator);\n ++i)\n filenames.push_back (namebase + \"-\" + discretization + \"-\" +\n Utilities::int_to_string (i, 4) + \".vtu\");\n std::ostringstream os;\n os << namebase << \"-\" << discretization << \"-\" << global_refinements << \".pvtu\";\n std::ofstream master_output ((os.str()).c_str ());\n data_out.write_pvtu_record (master_output, filenames);\n }\n}\n\ntemplate <int dim>\nvoid BartDriver<dim>::run ()\n{\n radio (\"making grid\");\n msh_ptr->make_grid (triangulation);\n msh_ptr->get_relevant_cell_iterators (dof_handler,\n local_cells,\n ref_bd_cells,\n is_cell_at_bd,\n is_cell_at_ref_bd);\n setup_system ();\n report_system ();\n assemble_ho_system ();\n do_iterations ();\n output_results();\n}\n\n\/\/ wrapper functions used to retrieve info from various Hash tables\ntemplate <int dim>\nunsigned int BartDriver<dim>::get_component_index\n(unsigned int incident_angle_index, unsigned int g)\n{\n \/\/ retrieve component indecis given direction and group\n \/\/ must be used after initializing the index map\n return component_index[std::make_pair (incident_angle_index, g)];\n}\n\ntemplate <int dim>\nunsigned int BartDriver<dim>::get_component_direction (unsigned int comp_ind)\n{\n return inverse_component_index[comp_ind].first;\n}\n\ntemplate <int dim>\nunsigned int BartDriver<dim>::get_component_group (unsigned int comp_ind)\n{\n return inverse_component_index[comp_ind].second;\n}\n\ntemplate <int dim>\nunsigned int BartDriver<dim>::get_reflective_direction_index\n(unsigned int boundary_id, unsigned int incident_angle_index)\n{\n AssertThrow (is_reflective_bc[boundary_id],\n ExcMessage (\"must be reflective boundary to retrieve the reflective boundary\"));\n return reflective_direction_index[std::make_pair (boundary_id,\n incident_angle_index)];\n}\n\n\/\/functions used to cout information for diagonose or just simply cout\ntemplate <int dim>\nvoid BartDriver<dim>::radio (std::string str)\n{\n pcout << str << std::endl;\n}\n\ntemplate <int dim>\nvoid BartDriver<dim>::radio (std::string str1, std::string str2)\n{\n pcout << str1 << \": \" << str2 << std::endl;\n}\n\ntemplate <int dim>\nvoid BartDriver<dim>::radio (std::string str,\n double num)\n{\n pcout << str << \": \" << num << std::endl;\n}\n\ntemplate <int dim>\nvoid BartDriver<dim>::radio (std::string str1, unsigned int num1,\n std::string str2, unsigned int num2,\n std::string str3, unsigned int num3)\n{\n pcout << str1 << \": \" << num1 << \", \";\n pcout << str2 << \": \" << num2 << \", \";\n pcout << str3 << \": \" << num3 << std::endl;;\n}\n\ntemplate <int dim>\nvoid BartDriver<dim>::radio (std::string str,\n unsigned int num)\n{\n pcout << str << \": \" << num << std::endl;\n}\n\ntemplate <int dim>\nvoid BartDriver<dim>::radio (std::string str, bool boolean)\n{\n pcout << str << \": \" << (boolean?\"true\":\"false\") << std::endl;\n}\n\ntemplate <int dim>\nvoid BartDriver<dim>::radio ()\n{\n pcout << \"-------------------------------------\" << std::endl << std::endl;\n}\n\n\/\/ explicit instantiation to avoid linking error\ntemplate class BartDriver<2>;\ntemplate class BartDriver<3>;\n<commit_msg>BartDriver cleaning #10<commit_after>#include <deal.II\/fe\/fe_values.h>\n\n#include <boost\/algorithm\/string.hpp>\n#include <deal.II\/dofs\/dof_tools.h>\n#include <deal.II\/grid\/cell_id.h>\n\n#include <deal.II\/lac\/petsc_solver.h>\n#include <deal.II\/lac\/solver_bicgstab.h>\n\n#include <algorithm>\n\n#include \"transport_base.h\"\n#include \"..\/aqdata\/aq_base.h\"\n#include \"..\/aqdata\/aq_lsgc.h\"\n\nusing namespace dealii;\n\ntemplate <int dim>\nBartDriver<dim>::BartDriver (ParameterHandler &prm)\n:\ntriangulation (MPI_COMM_WORLD,\n typename Triangulation<dim>::MeshSmoothing\n (Triangulation<dim>::smoothing_on_refinement |\n Triangulation<dim>::smoothing_on_coarsening)),\ndof_handler (triangulation),\nprm(prm),\ntransport_model_name(prm.get(\"transport model\")),\naq_name(prm.get(\"angular quadrature name\")),\ndiscretization(prm.get(\"spatial discretization\")),\nn_group(prm.get_integer(\"number of groups\")),\nn_azi(prm.get_integer(\"angular quadrature order\")),\nis_eigen_problem(prm.get_bool(\"do eigenvalue calculations\")),\ndo_nda(prm.get_bool(\"do NDA\")),\ndo_print_sn_quad(prm.get_bool(\"do print angular quadrature info\")),\nhave_reflective_bc(prm.get_bool(\"have reflective BC\")),\np_order(prm.get_integer(\"finite element polynomial degree\")),\nglobal_refinements(prm.get_integer(\"uniform refinements\")),\nnamebase(prm.get(\"output file name base\")),\nho_linear_solver_name(prm.get(\"HO linear solver name\")),\nho_preconditioner_name(prm.get(\"HO preconditioner name\")),\npcout(std::cout,\n Utilities::MPI::this_mpi_process(MPI_COMM_WORLD)==0)\n{\n aqd_ptr = build_aq_model (prm)\n aqd_ptr->make_aq (prm);\n n_total_ho_vars = aqd_ptr->get_n_total_ho_vars ();\n n_azi = aqd_ptr->get_sn_order ();\n n_dir = aqd_ptr->get_n_dir ();\n msh_ptr = std_cxx11::shared_ptr<MeshGenerator<dim> >\n (new MeshGenerator<dim>(prm));\n this->process_input ();\n}\n\ntemplate <int dim>\nBartDriver<dim>::~BartDriver ()\n{\n dof_handler.clear();\n}\n\ntemplate <int dim>\nvoid BartDriver<dim>::report_system ()\n{\n pcout << \"SN quadrature order: \" << n_azi << std::endl\n << \"Number of angles: \" << n_dir << std::endl\n << \"Number of groups: \" << n_group << std::endl;\n\n radio (\"Transport model\", transport_model_name);\n radio (\"Spatial discretization\", discretization);\n radio (\"HO linear solver\", ho_linear_solver_name);\n if (ho_linear_solver_name!=\"direct\")\n radio (\"HO preconditioner\", ho_preconditioner_name);\n radio (\"do NDA?\", do_nda);\n \n radio (\"Number of cells\", triangulation.n_global_active_cells());\n radio (\"High-order total DoF counts\", n_total_ho_vars*dof_handler.n_dofs());\n\n if (is_eigen_problem)\n radio (\"Problem type: k-eigenvalue problem\");\n if (do_nda)\n radio (\"NDA total DoF counts\", n_group*dof_handler.n_dofs());\n radio (\"print sn quad?\", do_print_sn_quad);\n radio (\"is eigenvalue problem?\", is_eigen_problem);\n}\n\ntemplate <int dim>\nvoid BartDriver<dim>::setup_system ()\n{\n radio (\"setup system\");\n initialize_dealii_objects ();\n initialize_system_matrices_vectors ();\n}\n\ntemplate <int dim>\nvoid BartDriver<dim>::initialize_system_matrices_vectors ()\n{\n DynamicSparsityPattern dsp (relevant_dofs);\n\n if (discretization==\"dfem\")\n {\n \/*\n Table<2,DoFTools::Coupling> cell_coupling (1,1);\n Table<2,DoFTools::Coupling> face_coupling (1,1);\n\n cell_coupling[0][0] = DoFTools::nonzero;\n face_coupling[0][0] = DoFTools::nonzero;\n\n DoFTools::make_flux_sparsity_pattern (dof_handler,\n dsp,\n cell_coupling,\n face_coupling);\n *\/\n\n DoFTools::make_flux_sparsity_pattern (dof_handler,\n dsp,\n constraints,\n false);\n }\n else\n DoFTools::make_sparsity_pattern (dof_handler,\n dsp,\n constraints,\n false);\n\n \/\/ be careful with the following\n SparsityTools::distribute_sparsity_pattern (dsp,\n dof_handler.n_locally_owned_dofs_per_processor (),\n MPI_COMM_WORLD,\n relevant_dofs);\n\n for (unsigned int g=0; g<n_group; ++g)\n {\n if (do_nda)\n {\n vec_lo_sys.push_back (new LA::MPI::SparseMatrix);\n vec_lo_rhs.push_back (new LA::MPI::Vector);\n vec_lo_sflx.push_back (new LA::MPI::Vector);\n vec_lo_sflx_old.push_back (new LA::MPI::Vector);\n vec_lo_fixed_rhs.push_back (new LA::MPI::Vector);\n }\n\n vec_ho_sflx.push_back (new LA::MPI::Vector);\n vec_ho_sflx_prev_gen.push_back (new LA::MPI::Vector);\n vec_ho_sflx_old.push_back (new LA::MPI::Vector);\n\n for (unsigned int i_dir=0; i_dir<n_dir; ++i_dir)\n {\n vec_ho_sys.push_back (new LA::MPI::SparseMatrix);\n vec_aflx.push_back (new LA::MPI::Vector);\n vec_ho_rhs.push_back (new LA::MPI::Vector);\n vec_ho_fixed_rhs.push_back (new LA::MPI::Vector);\n }\n }\n\n for (unsigned int g=0; g<n_group; ++g)\n {\n if (do_nda)\n {\n vec_lo_sys[g]->reinit (local_dofs,\n local_dofs,\n dsp,\n MPI_COMM_WORLD);\n vec_lo_rhs[g]->reinit (local_dofs, MPI_COMM_WORLD);\n vec_lo_fixed_rhs[g]->reinit (local_dofs, MPI_COMM_WORLD);\n vec_lo_sflx[g]->reinit (local_dofs, MPI_COMM_WORLD);\n vec_lo_sflx_old[g]->reinit (local_dofs, MPI_COMM_WORLD);\n }\n\n vec_ho_sflx[g]->reinit (local_dofs, MPI_COMM_WORLD);\n vec_ho_sflx_old[g]->reinit (local_dofs, MPI_COMM_WORLD);\n }\n \n for (unsigned int k=0; k<n_total_ho_vars; ++k)\n {\n vec_ho_sys[k]->reinit(local_dofs,\n local_dofs,\n dsp,\n MPI_COMM_WORLD);\n vec_aflx[k]->reinit(local_dofs, MPI_COMM_WORLD);\n vec_ho_rhs[k]->reinit (local_dofs, MPI_COMM_WORLD);\n vec_ho_fixed_rhs[k]->reinit (local_dofs, MPI_COMM_WORLD);\n }\n}\n\ntemplate <int dim>\nvoid BartDriver<dim>::initialize_dealii_objects ()\n{\n if (discretization==\"dfem\")\n fe = (new FE_DGQ<dim> (p_order));\n else\n fe = (new FE_Q<dim> (p_order));\n\n dof_handler.distribute_dofs (*fe);\n\n local_dofs = dof_handler.locally_owned_dofs ();\n DoFTools::extract_locally_relevant_dofs (dof_handler,\n relevant_dofs);\n\n constraints.clear ();\n constraints.reinit (relevant_dofs);\n DoFTools::make_hanging_node_constraints (dof_handler,\n constraints);\n constraints.close ();\n}\n\ntemplate <int dim>\nvoid BartDriver<dim>::output_results () const\n{\n std::string sec_name = \"Graphical output\";\n DataOut<dim> data_out;\n data_out.attach_dof_handler (dof_handler);\n\n for (unsigned int g=0; g<n_group; ++g)\n {\n std::ostringstream os;\n os << \"ho_phi_g_\" << g;\n data_out.add_data_vector (sflx_proc[g], os.str ());\n }\n\n Vector<float> subdomain (triangulation.n_active_cells ());\n for (unsigned int i=0; i<subdomain.size(); ++i)\n subdomain(i) = triangulation.locally_owned_subdomain ();\n data_out.add_data_vector (subdomain, \"subdomain\");\n\n data_out.build_patches ();\n\n const std::string filename =\n (namebase + \"-\" + discretization + \"-\" + Utilities::int_to_string\n (triangulation.locally_owned_subdomain (), 4));\n std::ofstream output ((filename + \".vtu\").c_str ());\n data_out.write_vtu (output);\n\n if (Utilities::MPI::this_mpi_process(MPI_COMM_WORLD) == 0)\n {\n std::vector<std::string> filenames;\n for (unsigned int i=0;\n i<Utilities::MPI::n_mpi_processes(MPI_COMM_WORLD);\n ++i)\n filenames.push_back (namebase + \"-\" + discretization + \"-\" +\n Utilities::int_to_string (i, 4) + \".vtu\");\n std::ostringstream os;\n os << namebase << \"-\" << discretization << \"-\" << global_refinements << \".pvtu\";\n std::ofstream master_output ((os.str()).c_str ());\n data_out.write_pvtu_record (master_output, filenames);\n }\n}\n\ntemplate <int dim>\nvoid BartDriver<dim>::run ()\n{\n radio (\"making grid\");\n msh_ptr->make_grid (triangulation);\n msh_ptr->get_relevant_cell_iterators (dof_handler,\n local_cells,\n ref_bd_cells,\n is_cell_at_bd,\n is_cell_at_ref_bd);\n setup_system ();\n report_system ();\n assemble_ho_system ();\n do_iterations ();\n output_results();\n}\n\n\/\/ explicit instantiation to avoid linking error\ntemplate class BartDriver<2>;\ntemplate class BartDriver<3>;\n<|endoftext|>"} {"text":"<commit_before>\/\/===-- LoopUnroll.cpp - Loop unroller pass -------------------------------===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This pass implements a simple loop unroller. It works best when loops have\n\/\/ been canonicalized by the -indvars pass, allowing it to determine the trip\n\/\/ counts of loops easily.\n\/\/===----------------------------------------------------------------------===\/\/\n\n#define DEBUG_TYPE \"loop-unroll\"\n#include \"llvm\/IntrinsicInst.h\"\n#include \"llvm\/Transforms\/Scalar.h\"\n#include \"llvm\/Analysis\/LoopPass.h\"\n#include \"llvm\/Analysis\/InlineCost.h\"\n#include \"llvm\/Analysis\/ScalarEvolution.h\"\n#include \"llvm\/Support\/CommandLine.h\"\n#include \"llvm\/Support\/Debug.h\"\n#include \"llvm\/Support\/raw_ostream.h\"\n#include \"llvm\/Transforms\/Utils\/UnrollLoop.h\"\n#include <climits>\n\nusing namespace llvm;\n\nstatic cl::opt<unsigned>\nUnrollThreshold(\"unroll-threshold\", cl::init(200), cl::Hidden,\n cl::desc(\"The cut-off point for automatic loop unrolling\"));\n\nstatic cl::opt<unsigned>\nUnrollCount(\"unroll-count\", cl::init(0), cl::Hidden,\n cl::desc(\"Use this unroll count for all loops, for testing purposes\"));\n\nstatic cl::opt<bool>\nUnrollAllowPartial(\"unroll-allow-partial\", cl::init(false), cl::Hidden,\n cl::desc(\"Allows loops to be partially unrolled until \"\n \"-unroll-threshold loop size is reached.\"));\n\nnamespace {\n class LoopUnroll : public LoopPass {\n public:\n static char ID; \/\/ Pass ID, replacement for typeid\n LoopUnroll() : LoopPass(ID) {}\n\n \/\/\/ A magic value for use with the Threshold parameter to indicate\n \/\/\/ that the loop unroll should be performed regardless of how much\n \/\/\/ code expansion would result.\n static const unsigned NoThreshold = UINT_MAX;\n\n bool runOnLoop(Loop *L, LPPassManager &LPM);\n\n \/\/\/ This transformation requires natural loop information & requires that\n \/\/\/ loop preheaders be inserted into the CFG...\n \/\/\/\n virtual void getAnalysisUsage(AnalysisUsage &AU) const {\n AU.addRequired<LoopInfo>();\n AU.addPreserved<LoopInfo>();\n AU.addRequiredID(LoopSimplifyID);\n AU.addPreservedID(LoopSimplifyID);\n AU.addRequiredID(LCSSAID);\n AU.addPreservedID(LCSSAID);\n AU.addPreserved<ScalarEvolution>();\n \/\/ FIXME: Loop unroll requires LCSSA. And LCSSA requires dom info.\n \/\/ If loop unroll does not preserve dom info then LCSSA pass on next\n \/\/ loop will receive invalid dom info.\n \/\/ For now, recreate dom info, if loop is unrolled.\n AU.addPreserved<DominatorTree>();\n }\n };\n}\n\nchar LoopUnroll::ID = 0;\nINITIALIZE_PASS(LoopUnroll, \"loop-unroll\", \"Unroll loops\", false, false);\n\nPass *llvm::createLoopUnrollPass() { return new LoopUnroll(); }\n\n\/\/\/ ApproximateLoopSize - Approximate the size of the loop.\nstatic unsigned ApproximateLoopSize(const Loop *L, unsigned &NumCalls) {\n CodeMetrics Metrics;\n for (Loop::block_iterator I = L->block_begin(), E = L->block_end();\n I != E; ++I)\n Metrics.analyzeBasicBlock(*I);\n NumCalls = Metrics.NumCalls;\n return Metrics.NumInsts;\n}\n\nbool LoopUnroll::runOnLoop(Loop *L, LPPassManager &LPM) {\n LoopInfo *LI = &getAnalysis<LoopInfo>();\n\n BasicBlock *Header = L->getHeader();\n DEBUG(dbgs() << \"Loop Unroll: F[\" << Header->getParent()->getName()\n << \"] Loop %\" << Header->getName() << \"\\n\");\n (void)Header;\n\n \/\/ Find trip count\n unsigned TripCount = L->getSmallConstantTripCount();\n unsigned Count = UnrollCount;\n\n \/\/ Automatically select an unroll count.\n if (Count == 0) {\n \/\/ Conservative heuristic: if we know the trip count, see if we can\n \/\/ completely unroll (subject to the threshold, checked below); otherwise\n \/\/ try to find greatest modulo of the trip count which is still under\n \/\/ threshold value.\n if (TripCount == 0)\n return false;\n Count = TripCount;\n }\n\n \/\/ Enforce the threshold.\n if (UnrollThreshold != NoThreshold) {\n unsigned NumCalls;\n unsigned LoopSize = ApproximateLoopSize(L, NumCalls);\n DEBUG(dbgs() << \" Loop Size = \" << LoopSize << \"\\n\");\n if (NumCalls != 0) {\n DEBUG(dbgs() << \" Not unrolling loop with function calls.\\n\");\n return false;\n }\n uint64_t Size = (uint64_t)LoopSize*Count;\n if (TripCount != 1 && Size > UnrollThreshold) {\n DEBUG(dbgs() << \" Too large to fully unroll with count: \" << Count\n << \" because size: \" << Size << \">\" << UnrollThreshold << \"\\n\");\n if (!UnrollAllowPartial) {\n DEBUG(dbgs() << \" will not try to unroll partially because \"\n << \"-unroll-allow-partial not given\\n\");\n return false;\n }\n \/\/ Reduce unroll count to be modulo of TripCount for partial unrolling\n Count = UnrollThreshold \/ LoopSize;\n while (Count != 0 && TripCount%Count != 0) {\n Count--;\n }\n if (Count < 2) {\n DEBUG(dbgs() << \" could not unroll partially\\n\");\n return false;\n }\n DEBUG(dbgs() << \" partially unrolling with count: \" << Count << \"\\n\");\n }\n }\n\n \/\/ Unroll the loop.\n Function *F = L->getHeader()->getParent();\n if (!UnrollLoop(L, Count, LI, &LPM))\n return false;\n\n \/\/ FIXME: Reconstruct dom info, because it is not preserved properly.\n if (DominatorTree *DT = getAnalysisIfAvailable<DominatorTree>())\n DT->runOnFunction(*F);\n return true;\n}\n<commit_msg>Add a separate unrolling threshold when the current function is being optimized for size. The threshold value of 50 is arbitrary, and I chose it simply by analogy to the inlining thresholds, where the baseline unrolling threshold is slightly smaller than the baseline inlining threshold. This could undoubtedly use some tuning.<commit_after>\/\/===-- LoopUnroll.cpp - Loop unroller pass -------------------------------===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This pass implements a simple loop unroller. It works best when loops have\n\/\/ been canonicalized by the -indvars pass, allowing it to determine the trip\n\/\/ counts of loops easily.\n\/\/===----------------------------------------------------------------------===\/\/\n\n#define DEBUG_TYPE \"loop-unroll\"\n#include \"llvm\/IntrinsicInst.h\"\n#include \"llvm\/Transforms\/Scalar.h\"\n#include \"llvm\/Analysis\/LoopPass.h\"\n#include \"llvm\/Analysis\/InlineCost.h\"\n#include \"llvm\/Analysis\/ScalarEvolution.h\"\n#include \"llvm\/Support\/CommandLine.h\"\n#include \"llvm\/Support\/Debug.h\"\n#include \"llvm\/Support\/raw_ostream.h\"\n#include \"llvm\/Transforms\/Utils\/UnrollLoop.h\"\n#include <climits>\n\nusing namespace llvm;\n\nstatic cl::opt<unsigned>\nUnrollThreshold(\"unroll-threshold\", cl::init(200), cl::Hidden,\n cl::desc(\"The cut-off point for automatic loop unrolling\"));\n\nstatic cl::opt<unsigned>\nUnrollCount(\"unroll-count\", cl::init(0), cl::Hidden,\n cl::desc(\"Use this unroll count for all loops, for testing purposes\"));\n\nstatic cl::opt<bool>\nUnrollAllowPartial(\"unroll-allow-partial\", cl::init(false), cl::Hidden,\n cl::desc(\"Allows loops to be partially unrolled until \"\n \"-unroll-threshold loop size is reached.\"));\n\nnamespace {\n class LoopUnroll : public LoopPass {\n public:\n static char ID; \/\/ Pass ID, replacement for typeid\n LoopUnroll() : LoopPass(ID) {}\n\n \/\/\/ A magic value for use with the Threshold parameter to indicate\n \/\/\/ that the loop unroll should be performed regardless of how much\n \/\/\/ code expansion would result.\n static const unsigned NoThreshold = UINT_MAX;\n \n \/\/ Threshold to use when optsize is specified (and there is no\n \/\/ explicit -unroll-threshold).\n static const unsigned OptSizeUnrollThreshold = 50;\n \n unsigned CurrentThreshold;\n\n bool runOnLoop(Loop *L, LPPassManager &LPM);\n\n \/\/\/ This transformation requires natural loop information & requires that\n \/\/\/ loop preheaders be inserted into the CFG...\n \/\/\/\n virtual void getAnalysisUsage(AnalysisUsage &AU) const {\n AU.addRequired<LoopInfo>();\n AU.addPreserved<LoopInfo>();\n AU.addRequiredID(LoopSimplifyID);\n AU.addPreservedID(LoopSimplifyID);\n AU.addRequiredID(LCSSAID);\n AU.addPreservedID(LCSSAID);\n AU.addPreserved<ScalarEvolution>();\n \/\/ FIXME: Loop unroll requires LCSSA. And LCSSA requires dom info.\n \/\/ If loop unroll does not preserve dom info then LCSSA pass on next\n \/\/ loop will receive invalid dom info.\n \/\/ For now, recreate dom info, if loop is unrolled.\n AU.addPreserved<DominatorTree>();\n }\n };\n}\n\nchar LoopUnroll::ID = 0;\nINITIALIZE_PASS(LoopUnroll, \"loop-unroll\", \"Unroll loops\", false, false);\n\nPass *llvm::createLoopUnrollPass() { return new LoopUnroll(); }\n\n\/\/\/ ApproximateLoopSize - Approximate the size of the loop.\nstatic unsigned ApproximateLoopSize(const Loop *L, unsigned &NumCalls) {\n CodeMetrics Metrics;\n for (Loop::block_iterator I = L->block_begin(), E = L->block_end();\n I != E; ++I)\n Metrics.analyzeBasicBlock(*I);\n NumCalls = Metrics.NumCalls;\n return Metrics.NumInsts;\n}\n\nbool LoopUnroll::runOnLoop(Loop *L, LPPassManager &LPM) {\n \n LoopInfo *LI = &getAnalysis<LoopInfo>();\n\n BasicBlock *Header = L->getHeader();\n DEBUG(dbgs() << \"Loop Unroll: F[\" << Header->getParent()->getName()\n << \"] Loop %\" << Header->getName() << \"\\n\");\n (void)Header;\n \n \/\/ Determine the current unrolling threshold. While this is normally set\n \/\/ from UnrollThreshold, it is overridden to a smaller value if the current\n \/\/ function is marked as optimize-for-size, and the unroll threshold was\n \/\/ not user specified.\n CurrentThreshold = UnrollThreshold;\n if (Header->getParent()->hasFnAttr(Attribute::OptimizeForSize) &&\n UnrollThreshold.getNumOccurrences() == 0)\n CurrentThreshold = OptSizeUnrollThreshold;\n\n \/\/ Find trip count\n unsigned TripCount = L->getSmallConstantTripCount();\n unsigned Count = UnrollCount;\n\n \/\/ Automatically select an unroll count.\n if (Count == 0) {\n \/\/ Conservative heuristic: if we know the trip count, see if we can\n \/\/ completely unroll (subject to the threshold, checked below); otherwise\n \/\/ try to find greatest modulo of the trip count which is still under\n \/\/ threshold value.\n if (TripCount == 0)\n return false;\n Count = TripCount;\n }\n\n \/\/ Enforce the threshold.\n if (CurrentThreshold != NoThreshold) {\n unsigned NumCalls;\n unsigned LoopSize = ApproximateLoopSize(L, NumCalls);\n DEBUG(dbgs() << \" Loop Size = \" << LoopSize << \"\\n\");\n if (NumCalls != 0) {\n DEBUG(dbgs() << \" Not unrolling loop with function calls.\\n\");\n return false;\n }\n uint64_t Size = (uint64_t)LoopSize*Count;\n if (TripCount != 1 && Size > CurrentThreshold) {\n DEBUG(dbgs() << \" Too large to fully unroll with count: \" << Count\n << \" because size: \" << Size << \">\" << CurrentThreshold << \"\\n\");\n if (!UnrollAllowPartial) {\n DEBUG(dbgs() << \" will not try to unroll partially because \"\n << \"-unroll-allow-partial not given\\n\");\n return false;\n }\n \/\/ Reduce unroll count to be modulo of TripCount for partial unrolling\n Count = CurrentThreshold \/ LoopSize;\n while (Count != 0 && TripCount%Count != 0) {\n Count--;\n }\n if (Count < 2) {\n DEBUG(dbgs() << \" could not unroll partially\\n\");\n return false;\n }\n DEBUG(dbgs() << \" partially unrolling with count: \" << Count << \"\\n\");\n }\n }\n\n \/\/ Unroll the loop.\n Function *F = L->getHeader()->getParent();\n if (!UnrollLoop(L, Count, LI, &LPM))\n return false;\n\n \/\/ FIXME: Reconstruct dom info, because it is not preserved properly.\n if (DominatorTree *DT = getAnalysisIfAvailable<DominatorTree>())\n DT->runOnFunction(*F);\n return true;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*!\n * \\file painter_enums.hpp\n * \\brief file painter_enums.hpp\n *\n * Copyright 2016 by Intel.\n *\n * Contact: kevin.rogovin@intel.com\n *\n * This Source Code Form is subject to the\n * terms of the Mozilla Public License, v. 2.0.\n * If a copy of the MPL was not distributed with\n * this file, You can obtain one at\n * http:\/\/mozilla.org\/MPL\/2.0\/.\n *\n * \\author Kevin Rogovin <kevin.rogovin@intel.com>\n *\n *\/\n\n\n#pragma once\n\nnamespace fastuidraw\n{\n\/*!\\addtogroup Painter\n * @{\n *\/\n\n \/*!\n * \\brief Class to encapsulate enumerations used in Painter\n * interface, part of the main library libFastUIDraw.\n *\/\n class PainterEnums\n {\n public:\n \/*!\n * \\brief\n * Enumeration to indicate in what direction the\n * y-coordinate increases\n *\/\n enum screen_orientation\n {\n y_increases_downwards, \/*!< y-coordinate increases downwards *\/\n y_increases_upwards \/*!< y-coordinate increases upwards *\/\n };\n\n \/*!\n * \\brief\n * Enumeration to specify orientation of a rotation\n *\/\n enum rotation_orientation_t\n {\n clockwise, \/*!< indicates clockwise *\/\n counter_clockwise \/*!< indicates counter-clockwise *\/\n };\n\n \/*!\n * \\brief\n * Enumeration to indicate if glyph layout is horizontal\n * or vertical\n *\/\n enum glyph_layout_type\n {\n \/*!\n * Glyphs are layed out horizontally, thus will use\n * \\ref GlyphMetrics::horizontal_layout_offset()\n * to offset the glyphs.\n *\/\n glyph_layout_horizontal,\n\n \/*!\n * Glyphs are layed out vertically, thus will use\n * \\ref GlyphMetrics::vertical_layout_offset()\n * to offset the glyphs.\n *\/\n glyph_layout_vertical\n };\n\n \/*!\n * \\brief\n * Enumeration specifying if and how to draw caps when stroking.\n *\/\n enum cap_style\n {\n flat_caps, \/*!< indicates to have flat (i.e. no) caps when stroking *\/\n rounded_caps, \/*!< indicates to have rounded caps when stroking *\/\n square_caps, \/*!< indicates to have square caps when stroking *\/\n\n number_cap_styles \/*!< number of cap styles *\/\n };\n\n \/*!\n * \\brief\n * Enumeration specifying if and how to draw joins when stroking\n *\/\n enum join_style\n {\n \/*!\n * indicates to stroke without joins\n *\/\n no_joins,\n\n \/*!\n * indicates to stroke with rounded joins\n *\/\n rounded_joins,\n\n \/*!\n * indicates to stroke with bevel joins\n *\/\n bevel_joins,\n\n \/*!\n * indicates to stroke with miter joins where if miter distance\n * is exceeded then the miter join is clipped to the miter\n * distance.\n *\/\n miter_clip_joins,\n\n \/*!\n * indicates to stroke with miter joins where if miter distance\n * is exceeded then the miter join is drawn as a bevel join.\n *\/\n miter_bevel_joins,\n\n \/*!\n * indicates to stroke with miter joins where if miter distance\n * is exceeded then the miter-tip is truncated to the miter\n * distance.\n *\/\n miter_joins,\n\n number_join_styles, \/*!< number of join styles *\/\n };\n\n \/*!\n * \\brief\n * Enumerations specifying common fill rules.\n *\/\n enum fill_rule_t\n {\n odd_even_fill_rule, \/*!< indicates to use odd-even fill rule *\/\n complement_odd_even_fill_rule, \/*!< indicates to give the complement of the odd-even fill rule *\/\n nonzero_fill_rule, \/*!< indicates to use the non-zero fill rule *\/\n complement_nonzero_fill_rule, \/*!< indicates to give the complement of the non-zero fill rule *\/\n\n fill_rule_data_count \/*!< count of enums *\/\n };\n\n \/*!\n * Enumeration to describe high quality shader\n * anti-aliasing support in \\ref PainterFillShader\n * and \\ref PainterStrokeShader.\n *\/\n enum hq_anti_alias_support_t\n {\n \/*!\n * Indicates that high quality anti-aliasing is NOT\n * supported.\n *\/\n hq_anti_alias_no_support,\n\n \/*!\n * Indicates that high quality anti-aliasing is\n * supported with significant performance impact.\n *\/\n hq_anti_alias_slow,\n\n \/*!\n * Indicates that high quality anti-aliasing is\n * supported with no or minimal performance impact.\n *\/\n hq_anti_alias_fast,\n };\n\n \/*!\n * Enumeration to specify the anti-aliasing quality\n * to apply when performing path fills or strokes.\n *\/\n enum shader_anti_alias_t\n {\n \/*!\n * Do not apply any shader based anti-aliasing\n * to the fill.\n *\/\n shader_anti_alias_none,\n\n \/*!\n * Applies simpler anti-aliasing shading to path\n * fill or stroke. This will potentially give under\n * coverage to fragments (typically where the path\n * crosses itself or when the path is filled or\n * stroke highly minified).\n *\/\n shader_anti_alias_simple,\n\n \/*!\n * Applies higher quality anti-aliasing shading\n * that avoids the issues that come from \\ref\n * shader_anti_alias_simple. This option will give\n * the highest quality anti-aliasing at the\n * potential cost of performance. The shader works\n * in two passes: the first pass renders to the\n * IMMEDIATE coverage buffer and the 2nd pass reads\n * from it and uses that as the coverage value.\n *\/\n shader_anti_alias_high_quality,\n\n \/*!\n * Applies higher quality anti-aliasing shading\n * that avoids the issues that come from \\ref\n * shader_anti_alias_simple. This option will give\n * the highest quality anti-aliasing at the\n * potential cost of performance. The shader works\n * in two passes: the first pass renders to the\n * IMMEDIATE coverage buffer and the 2nd pass reads\n * from it and uses that as the coverage value.\n *\/\n shader_anti_alias_deferred_coverage,\n\n \/* make the modes that indicate for Painter to choose\n * to come after the modes that precisely specify a\n * choice.\n *\/\n\n \/*!\n * Represents to use \\ref shader_anti_alias_high_quality\n * if using it does not have a large performance impact\n * and otherwise to use \\ref shader_anti_alias_simple.\n *\/\n shader_anti_alias_auto,\n\n \/*!\n * Represents to use the fastest anti-alias mode\n * (which is not shader_anti_alias_none).\n *\/\n shader_anti_alias_fastest,\n\n \/*!\n * Number of shader-anti-alias enums present.\n *\/\n number_shader_anti_alias_enums,\n };\n\n \/*!\n * Enumeration to specify how to stroke\n *\/\n enum stroking_method_t\n {\n \/*!\n * Use linear stroking taken directly from the\n * Path. Thus the passed \\ref StrokedPath only\n * consists of line segments.\n *\/\n stroking_method_linear,\n\n \/*!\n * Use arc-stroking, i.e. the passed \\ref\n * StrokedPath has both arc-segments and\n * line segments. This results in fewer\n * vertices with the fragment shader\n * computing per-pixel coverage.\n *\/\n stroking_method_arc,\n\n \/* make the modes that indicate to choose to come\n * after the modes that precisely specify a value.\n *\/\n\n \/*!\n * Choose for optimal performance.\n *\/\n stroking_method_auto,\n };\n\n \/*!\n * \\brief\n * Enumeration specifying composite modes\n *\/\n enum composite_mode_t\n {\n composite_porter_duff_clear, \/*!< Clear mode of Porter-Duff *\/\n composite_porter_duff_src, \/*!< Source mode of Porter-Duff *\/\n composite_porter_duff_dst, \/*!< Destination mode of Porter-Duff *\/\n composite_porter_duff_src_over, \/*!< Source over mode of Porter-Duff *\/\n composite_porter_duff_dst_over, \/*!< Destination over mode of Porter-Duff *\/\n composite_porter_duff_src_in, \/*!< Source In mode of Porter-Duff *\/\n composite_porter_duff_dst_in, \/*!< Destination In mode of Porter-Duff *\/\n composite_porter_duff_src_out, \/*!< Source Out mode of Porter-Duff *\/\n composite_porter_duff_dst_out, \/*!< Destination Out mode of Porter-Duff *\/\n composite_porter_duff_src_atop, \/*!< Source Atop mode of Porter-Duff *\/\n composite_porter_duff_dst_atop, \/*!< Destination Atop mode of Porter-Duff *\/\n composite_porter_duff_xor, \/*!< Xor mode of Porter-Duff *\/\n composite_porter_duff_plus, \/*!< Plus operator mode of Porter-Duff *\/\n composite_porter_duff_modulate, \/*! < Modulate operator mode of Porter-Duff *\/\n };\n\n \/*!\n * \\brief\n * Enumeration specifying W3C blending modes\n *\/\n enum blend_w3c_mode_t\n {\n blend_w3c_normal, \/*!< W3C multiply mode: Src, i.e. no blending operation *\/\n blend_w3c_multiply, \/*!< W3C multiply mode: Dest * Src *\/\n blend_w3c_screen, \/*!< W3C screen mode: 1 - (1 - Dest) * (1 - Src) *\/\n\n \/*!\n * W3C overlay mode: for each channel,\n * (Dst <= 0.5) ?\n * 2.0 * Dest * Src :\n * 1 - 2 * (1 - Dst) * (1 - Src)\n *\/\n blend_w3c_overlay,\n blend_w3c_darken, \/*!< W3C darken mode: min(Src, Dest) *\/\n blend_w3c_lighten, \/*!< W3C lighten mode: max(Src, Dest) *\/\n\n \/*!\n * W3C color-dodge mode: for each channel\n * (Dest == 0) ? 0 : (Src == 1) ? 1 : min(1, Dst \/ (1 - Src) )\n * i.e. if Dest is 0, write 0. If Src is 1, write 1. Otherwise\n * write Dst \/ (1 - Src)\n *\/\n blend_w3c_color_dodge,\n\n \/*!\n * W3C color-burn mode: for each channel\n * (Dest == 1) ? 1 : (Src == 0) ? 0 : 1 - min(1, (1 - Dst) \/ Src)\n * i.e. if Dest is 1, write 1. If Src is 0, write 0. Otherwise\n * write (1 - Dst ) \/ Src\n *\/\n blend_w3c_color_burn,\n\n \/*!\n * W3C hardlight mode: for each channel,\n * (Src <= 0.5) ?\n * 2.0 * Dest * Src :\n * 1 - 2 * (1 - Dst) * (1 - Src)\n *\/\n blend_w3c_hardlight,\n\n \/*!\n * W3C soft light mode: for each channel:\n * (Src <= 0.5) ?\n * Dst - (1 - 2 * Src) * Dst * (1 - Dst) :\n * Dst + (2 * Src - 1) * (Z - Dst)\n * where\n * Z = (Dst <= 0.25) ?\n * ((16 * Dst - 12) * Dst + 4) * Dst :\n * sqrt(Dst)\n *\/\n blend_w3c_softlight,\n\n blend_w3c_difference, \/*!< W3C difference mode: for each channel, abs(Dest - Src) *\/\n blend_w3c_exclusion, \/*!< W3C exclusion mode: for each channel, Dest + Src - 2 * Dest * Src *\/\n\n \/*!\n * w3c hue mode, see w3c for formula\n *\/\n blend_w3c_hue,\n\n \/*!\n * w3c saturation mode, see w3c for formula\n *\/\n blend_w3c_saturation,\n\n \/*!\n * w3c color mode, see w3c for formula\n *\/\n blend_w3c_color,\n\n \/*!\n * w3c luminosity mode, see w3c for formula\n *\/\n blend_w3c_luminosity,\n };\n\n \/*!\n * \\brief\n * Enumeration to query the statistics of how\n * much data has been packed\n *\/\n enum query_stats_t\n {\n \/*!\n * Offset to how many attributes processed\n *\/\n num_attributes,\n\n \/*!\n * Offset to how many indices processed\n *\/\n num_indices,\n\n \/*!\n * Offset to how many generic_data values placed\n * onto store buffer(s).\n *\/\n num_generic_datas,\n\n \/*!\n * Offset to how many PainterDraw objects sent\n *\/\n num_draws,\n\n \/*!\n * Offset to how many painter headers packed.\n *\/\n num_headers,\n\n \/*!\n * Number of distinct render targets needed.\n *\/\n num_render_targets,\n\n \/*!\n * Number of times PainterBackend::end() was called\n *\/\n num_ends,\n\n \/*!\n * Number of times begin_layer()\/end_layer() was called\n *\/\n num_layers,\n };\n\n \/*!\n * Given a fill rule, return the fill rule for the complement.\n *\/\n static\n enum fill_rule_t\n complement_fill_rule(enum fill_rule_t f);\n };\n\/*! @} *\/\n}\n<commit_msg>fastuidraw\/painter\/painter_enums: make enumeration value specifying the number of stroking modes<commit_after>\/*!\n * \\file painter_enums.hpp\n * \\brief file painter_enums.hpp\n *\n * Copyright 2016 by Intel.\n *\n * Contact: kevin.rogovin@intel.com\n *\n * This Source Code Form is subject to the\n * terms of the Mozilla Public License, v. 2.0.\n * If a copy of the MPL was not distributed with\n * this file, You can obtain one at\n * http:\/\/mozilla.org\/MPL\/2.0\/.\n *\n * \\author Kevin Rogovin <kevin.rogovin@intel.com>\n *\n *\/\n\n\n#pragma once\n\nnamespace fastuidraw\n{\n\/*!\\addtogroup Painter\n * @{\n *\/\n\n \/*!\n * \\brief Class to encapsulate enumerations used in Painter\n * interface, part of the main library libFastUIDraw.\n *\/\n class PainterEnums\n {\n public:\n \/*!\n * \\brief\n * Enumeration to indicate in what direction the\n * y-coordinate increases\n *\/\n enum screen_orientation\n {\n y_increases_downwards, \/*!< y-coordinate increases downwards *\/\n y_increases_upwards \/*!< y-coordinate increases upwards *\/\n };\n\n \/*!\n * \\brief\n * Enumeration to specify orientation of a rotation\n *\/\n enum rotation_orientation_t\n {\n clockwise, \/*!< indicates clockwise *\/\n counter_clockwise \/*!< indicates counter-clockwise *\/\n };\n\n \/*!\n * \\brief\n * Enumeration to indicate if glyph layout is horizontal\n * or vertical\n *\/\n enum glyph_layout_type\n {\n \/*!\n * Glyphs are layed out horizontally, thus will use\n * \\ref GlyphMetrics::horizontal_layout_offset()\n * to offset the glyphs.\n *\/\n glyph_layout_horizontal,\n\n \/*!\n * Glyphs are layed out vertically, thus will use\n * \\ref GlyphMetrics::vertical_layout_offset()\n * to offset the glyphs.\n *\/\n glyph_layout_vertical\n };\n\n \/*!\n * \\brief\n * Enumeration specifying if and how to draw caps when stroking.\n *\/\n enum cap_style\n {\n flat_caps, \/*!< indicates to have flat (i.e. no) caps when stroking *\/\n rounded_caps, \/*!< indicates to have rounded caps when stroking *\/\n square_caps, \/*!< indicates to have square caps when stroking *\/\n\n number_cap_styles \/*!< number of cap styles *\/\n };\n\n \/*!\n * \\brief\n * Enumeration specifying if and how to draw joins when stroking\n *\/\n enum join_style\n {\n \/*!\n * indicates to stroke without joins\n *\/\n no_joins,\n\n \/*!\n * indicates to stroke with rounded joins\n *\/\n rounded_joins,\n\n \/*!\n * indicates to stroke with bevel joins\n *\/\n bevel_joins,\n\n \/*!\n * indicates to stroke with miter joins where if miter distance\n * is exceeded then the miter join is clipped to the miter\n * distance.\n *\/\n miter_clip_joins,\n\n \/*!\n * indicates to stroke with miter joins where if miter distance\n * is exceeded then the miter join is drawn as a bevel join.\n *\/\n miter_bevel_joins,\n\n \/*!\n * indicates to stroke with miter joins where if miter distance\n * is exceeded then the miter-tip is truncated to the miter\n * distance.\n *\/\n miter_joins,\n\n number_join_styles, \/*!< number of join styles *\/\n };\n\n \/*!\n * \\brief\n * Enumerations specifying common fill rules.\n *\/\n enum fill_rule_t\n {\n odd_even_fill_rule, \/*!< indicates to use odd-even fill rule *\/\n complement_odd_even_fill_rule, \/*!< indicates to give the complement of the odd-even fill rule *\/\n nonzero_fill_rule, \/*!< indicates to use the non-zero fill rule *\/\n complement_nonzero_fill_rule, \/*!< indicates to give the complement of the non-zero fill rule *\/\n\n fill_rule_data_count \/*!< count of enums *\/\n };\n\n \/*!\n * Enumeration to describe high quality shader\n * anti-aliasing support in \\ref PainterFillShader\n * and \\ref PainterStrokeShader.\n *\/\n enum hq_anti_alias_support_t\n {\n \/*!\n * Indicates that high quality anti-aliasing is NOT\n * supported.\n *\/\n hq_anti_alias_no_support,\n\n \/*!\n * Indicates that high quality anti-aliasing is\n * supported with significant performance impact.\n *\/\n hq_anti_alias_slow,\n\n \/*!\n * Indicates that high quality anti-aliasing is\n * supported with no or minimal performance impact.\n *\/\n hq_anti_alias_fast,\n };\n\n \/*!\n * Enumeration to specify the anti-aliasing quality\n * to apply when performing path fills or strokes.\n *\/\n enum shader_anti_alias_t\n {\n \/*!\n * Do not apply any shader based anti-aliasing\n * to the fill.\n *\/\n shader_anti_alias_none,\n\n \/*!\n * Applies simpler anti-aliasing shading to path\n * fill or stroke. This will potentially give under\n * coverage to fragments (typically where the path\n * crosses itself or when the path is filled or\n * stroke highly minified).\n *\/\n shader_anti_alias_simple,\n\n \/*!\n * Applies higher quality anti-aliasing shading\n * that avoids the issues that come from \\ref\n * shader_anti_alias_simple. This option will give\n * the highest quality anti-aliasing at the\n * potential cost of performance. The shader works\n * in two passes: the first pass renders to the\n * IMMEDIATE coverage buffer and the 2nd pass reads\n * from it and uses that as the coverage value.\n *\/\n shader_anti_alias_high_quality,\n\n \/*!\n * Applies higher quality anti-aliasing shading\n * that avoids the issues that come from \\ref\n * shader_anti_alias_simple. This option will give\n * the highest quality anti-aliasing at the\n * potential cost of performance. The shader works\n * in two passes: the first pass renders to the\n * IMMEDIATE coverage buffer and the 2nd pass reads\n * from it and uses that as the coverage value.\n *\/\n shader_anti_alias_deferred_coverage,\n\n \/* make the modes that indicate for Painter to choose\n * to come after the modes that precisely specify a\n * choice.\n *\/\n\n \/*!\n * Represents to use \\ref shader_anti_alias_high_quality\n * if using it does not have a large performance impact\n * and otherwise to use \\ref shader_anti_alias_simple.\n *\/\n shader_anti_alias_auto,\n\n \/*!\n * Represents to use the fastest anti-alias mode\n * (which is not shader_anti_alias_none).\n *\/\n shader_anti_alias_fastest,\n\n \/*!\n * Number of shader-anti-alias enums present.\n *\/\n number_shader_anti_alias_enums,\n };\n\n \/*!\n * Enumeration to specify how to stroke\n *\/\n enum stroking_method_t\n {\n \/*!\n * Use linear stroking taken directly from the\n * Path. Thus the passed \\ref StrokedPath only\n * consists of line segments.\n *\/\n stroking_method_linear,\n\n \/*!\n * Use arc-stroking, i.e. the passed \\ref\n * StrokedPath has both arc-segments and\n * line segments. This results in fewer\n * vertices with the fragment shader\n * computing per-pixel coverage.\n *\/\n stroking_method_arc,\n\n \/* make the modes that indicate to choose to come\n * after the modes that precisely specify a value.\n *\/\n\n \/*!\n * Choose for optimal performance.\n *\/\n stroking_method_auto,\n\n \/*!\n * Number of stroking enums present.\n *\/\n number_stroking_methods,\n };\n\n \/*!\n * \\brief\n * Enumeration specifying composite modes\n *\/\n enum composite_mode_t\n {\n composite_porter_duff_clear, \/*!< Clear mode of Porter-Duff *\/\n composite_porter_duff_src, \/*!< Source mode of Porter-Duff *\/\n composite_porter_duff_dst, \/*!< Destination mode of Porter-Duff *\/\n composite_porter_duff_src_over, \/*!< Source over mode of Porter-Duff *\/\n composite_porter_duff_dst_over, \/*!< Destination over mode of Porter-Duff *\/\n composite_porter_duff_src_in, \/*!< Source In mode of Porter-Duff *\/\n composite_porter_duff_dst_in, \/*!< Destination In mode of Porter-Duff *\/\n composite_porter_duff_src_out, \/*!< Source Out mode of Porter-Duff *\/\n composite_porter_duff_dst_out, \/*!< Destination Out mode of Porter-Duff *\/\n composite_porter_duff_src_atop, \/*!< Source Atop mode of Porter-Duff *\/\n composite_porter_duff_dst_atop, \/*!< Destination Atop mode of Porter-Duff *\/\n composite_porter_duff_xor, \/*!< Xor mode of Porter-Duff *\/\n composite_porter_duff_plus, \/*!< Plus operator mode of Porter-Duff *\/\n composite_porter_duff_modulate, \/*! < Modulate operator mode of Porter-Duff *\/\n };\n\n \/*!\n * \\brief\n * Enumeration specifying W3C blending modes\n *\/\n enum blend_w3c_mode_t\n {\n blend_w3c_normal, \/*!< W3C multiply mode: Src, i.e. no blending operation *\/\n blend_w3c_multiply, \/*!< W3C multiply mode: Dest * Src *\/\n blend_w3c_screen, \/*!< W3C screen mode: 1 - (1 - Dest) * (1 - Src) *\/\n\n \/*!\n * W3C overlay mode: for each channel,\n * (Dst <= 0.5) ?\n * 2.0 * Dest * Src :\n * 1 - 2 * (1 - Dst) * (1 - Src)\n *\/\n blend_w3c_overlay,\n blend_w3c_darken, \/*!< W3C darken mode: min(Src, Dest) *\/\n blend_w3c_lighten, \/*!< W3C lighten mode: max(Src, Dest) *\/\n\n \/*!\n * W3C color-dodge mode: for each channel\n * (Dest == 0) ? 0 : (Src == 1) ? 1 : min(1, Dst \/ (1 - Src) )\n * i.e. if Dest is 0, write 0. If Src is 1, write 1. Otherwise\n * write Dst \/ (1 - Src)\n *\/\n blend_w3c_color_dodge,\n\n \/*!\n * W3C color-burn mode: for each channel\n * (Dest == 1) ? 1 : (Src == 0) ? 0 : 1 - min(1, (1 - Dst) \/ Src)\n * i.e. if Dest is 1, write 1. If Src is 0, write 0. Otherwise\n * write (1 - Dst ) \/ Src\n *\/\n blend_w3c_color_burn,\n\n \/*!\n * W3C hardlight mode: for each channel,\n * (Src <= 0.5) ?\n * 2.0 * Dest * Src :\n * 1 - 2 * (1 - Dst) * (1 - Src)\n *\/\n blend_w3c_hardlight,\n\n \/*!\n * W3C soft light mode: for each channel:\n * (Src <= 0.5) ?\n * Dst - (1 - 2 * Src) * Dst * (1 - Dst) :\n * Dst + (2 * Src - 1) * (Z - Dst)\n * where\n * Z = (Dst <= 0.25) ?\n * ((16 * Dst - 12) * Dst + 4) * Dst :\n * sqrt(Dst)\n *\/\n blend_w3c_softlight,\n\n blend_w3c_difference, \/*!< W3C difference mode: for each channel, abs(Dest - Src) *\/\n blend_w3c_exclusion, \/*!< W3C exclusion mode: for each channel, Dest + Src - 2 * Dest * Src *\/\n\n \/*!\n * w3c hue mode, see w3c for formula\n *\/\n blend_w3c_hue,\n\n \/*!\n * w3c saturation mode, see w3c for formula\n *\/\n blend_w3c_saturation,\n\n \/*!\n * w3c color mode, see w3c for formula\n *\/\n blend_w3c_color,\n\n \/*!\n * w3c luminosity mode, see w3c for formula\n *\/\n blend_w3c_luminosity,\n };\n\n \/*!\n * \\brief\n * Enumeration to query the statistics of how\n * much data has been packed\n *\/\n enum query_stats_t\n {\n \/*!\n * Offset to how many attributes processed\n *\/\n num_attributes,\n\n \/*!\n * Offset to how many indices processed\n *\/\n num_indices,\n\n \/*!\n * Offset to how many generic_data values placed\n * onto store buffer(s).\n *\/\n num_generic_datas,\n\n \/*!\n * Offset to how many PainterDraw objects sent\n *\/\n num_draws,\n\n \/*!\n * Offset to how many painter headers packed.\n *\/\n num_headers,\n\n \/*!\n * Number of distinct render targets needed.\n *\/\n num_render_targets,\n\n \/*!\n * Number of times PainterBackend::end() was called\n *\/\n num_ends,\n\n \/*!\n * Number of times begin_layer()\/end_layer() was called\n *\/\n num_layers,\n };\n\n \/*!\n * Given a fill rule, return the fill rule for the complement.\n *\/\n static\n enum fill_rule_t\n complement_fill_rule(enum fill_rule_t f);\n };\n\/*! @} *\/\n}\n<|endoftext|>"} {"text":"<commit_before>#ifndef ALEPH_GEOMETRY_WITNESS_COMPLEX_HH__\n#define ALEPH_GEOMETRY_WITNESS_COMPLEX_HH__\n\n#include <algorithm>\n#include <limits>\n#include <iterator>\n#include <vector>\n\n#include <aleph\/geometry\/distances\/Traits.hh>\n\n#include <aleph\/topology\/Simplex.hh>\n#include <aleph\/topology\/SimplicialComplex.hh>\n\nnamespace aleph\n{\n\nnamespace geometry\n{\n\ntemplate <class Distance, class Container, class InputIterator> auto buildWitnessComplex(\n const Container& container,\n InputIterator begin, InputIterator end,\n unsigned nu = 2,\n typename Distance::ResultType R = typename Distance::ResultType() ) -> topology::SimplicialComplex< topology::Simplex<typename Distance::ResultType, unsigned> >\n{\n using IndexType = typename std::iterator_traits<InputIterator>::value_type;\n using DataType = typename Distance::ResultType;\n using Traits = aleph::distances::Traits<Distance>;\n using VertexType = unsigned; \/\/ TODO: make configurable\n using Simplex = topology::Simplex<DataType, VertexType>;\n using SimplicialComplex = topology::SimplicialComplex<Simplex>;\n\n \/\/ These are only the *indices* of the landmarks, with respect to the\n \/\/ underlying point cloud.\n std::vector<IndexType> landmarkIndices( begin, end );\n\n auto n = landmarkIndices.size();\n auto N = container.size();\n auto d = container.dimension();\n\n \/\/ Much of the behaviour below will be undefined if we permit such\n \/\/ situations to occur.\n if( n == 0 || N == 0 )\n return {};\n\n \/\/ Distance matrix between a set of $n$ landmarks (rows) and $N$ data\n \/\/ points.\n std::vector< std::vector<DataType> > D;\n D.reserve( n );\n\n Distance dist;\n Traits traits;\n\n for( std::size_t i = 0; i < n; i++ )\n {\n std::vector<DataType> distances;\n distances.reserve( N );\n\n auto&& landmark = container[ landmarkIndices.at(i) ];\n\n for( std::size_t j = 0; j < N; j++ )\n {\n auto&& point = container[j];\n\n distances.emplace_back( traits.from( dist( landmark.begin(), point.begin(), d ) ) );\n }\n\n D.push_back( distances );\n }\n\n \/\/ Records the appearance times of each potential edge in the witness\n \/\/ complex.\n \/\/\n \/\/ TODO: this should become a symmetric matrix\n std::vector< std::vector<DataType> > M( n, std::vector<DataType>( n ) );\n\n for( std::size_t i = 0; i < n; i++ )\n {\n for( std::size_t j = i+1; j < n; j++ )\n {\n auto min = std::numeric_limits<DataType>::max();\n\n for( std::size_t k = 0; k < N; k++ )\n min = std::min( min, std::max( D[i][k], D[j][k] ) );\n\n M[i][j] = min;\n M[j][i] = min;\n }\n }\n\n \/\/ Get smallest entries of the distance matrix. This is required for\n \/\/ deciding whether a specific edge is valid or not, with respect to\n \/\/ the given parameters.\n\n std::vector<DataType> smallest( N );\n\n if( nu != 0 )\n {\n for( std::size_t col = 0; col < N; col++ )\n {\n \/\/ FIXME: getting the column like this is extremely wasteful;\n \/\/ would it not be nicer to store the values differently?\n std::vector<DataType> column( n );\n for( std::size_t i = 0; i < n; i++ )\n column[i] = D[i][col];\n\n std::nth_element( column.begin(), column.begin() + nu - 1, column.end() );\n smallest[col] = column.at( nu - 1 );\n }\n }\n\n auto max = *std::max_element( smallest.begin(), smallest.end() );\n\n std::vector<Simplex> simplices;\n\n for( std::size_t i = 0; i < n; i++ )\n {\n simplices.push_back( Simplex( static_cast<VertexType>(i) ) );\n\n for( std::size_t j = i+1; j < n; j++ )\n {\n \/\/ Skip pairs that cannot possibly give rise to an edge because of\n \/\/ their distance to each other.\n if( M[i][j] > R + max )\n continue;\n\n for( std::size_t col = 0; col < N; col++ )\n {\n if( M[i][j] <= R + smallest.at(col) )\n {\n auto u = static_cast<VertexType>(i);\n auto v = static_cast<VertexType>(j);\n\n simplices.push_back( Simplex( {u,v}, M[i][j] ) );\n break;\n }\n }\n }\n }\n\n return SimplicialComplex( simplices.begin(), simplices.end() );\n}\n\n} \/\/ namespace geometry\n\n} \/\/ namespace aleph\n\n#endif\n<commit_msg>Using symmetric matrix class for witness complex calculation<commit_after>#ifndef ALEPH_GEOMETRY_WITNESS_COMPLEX_HH__\n#define ALEPH_GEOMETRY_WITNESS_COMPLEX_HH__\n\n#include <algorithm>\n#include <limits>\n#include <iterator>\n#include <vector>\n\n#include <aleph\/geometry\/distances\/Traits.hh>\n\n#include <aleph\/math\/SymmetricMatrix.hh>\n\n#include <aleph\/topology\/Simplex.hh>\n#include <aleph\/topology\/SimplicialComplex.hh>\n\nnamespace aleph\n{\n\nnamespace geometry\n{\n\ntemplate <class Distance, class Container, class InputIterator> auto buildWitnessComplex(\n const Container& container,\n InputIterator begin, InputIterator end,\n unsigned nu = 2,\n typename Distance::ResultType R = typename Distance::ResultType() ) -> topology::SimplicialComplex< topology::Simplex<typename Distance::ResultType, unsigned> >\n{\n using IndexType = typename std::iterator_traits<InputIterator>::value_type;\n using DataType = typename Distance::ResultType;\n using Traits = aleph::distances::Traits<Distance>;\n using VertexType = unsigned; \/\/ TODO: make configurable\n using Simplex = topology::Simplex<DataType, VertexType>;\n using SimplicialComplex = topology::SimplicialComplex<Simplex>;\n\n \/\/ These are only the *indices* of the landmarks, with respect to the\n \/\/ underlying point cloud.\n std::vector<IndexType> landmarkIndices( begin, end );\n\n auto n = landmarkIndices.size();\n auto N = container.size();\n auto d = container.dimension();\n\n \/\/ Much of the behaviour below will be undefined if we permit such\n \/\/ situations to occur.\n if( n == 0 || N == 0 )\n return {};\n\n \/\/ Distance matrix between a set of $n$ landmarks (rows) and $N$ data\n \/\/ points.\n std::vector< std::vector<DataType> > D;\n D.reserve( n );\n\n Distance dist;\n Traits traits;\n\n for( std::size_t i = 0; i < n; i++ )\n {\n std::vector<DataType> distances;\n distances.reserve( N );\n\n auto&& landmark = container[ landmarkIndices.at(i) ];\n\n for( std::size_t j = 0; j < N; j++ )\n {\n auto&& point = container[j];\n\n distances.emplace_back( traits.from( dist( landmark.begin(), point.begin(), d ) ) );\n }\n\n D.push_back( distances );\n }\n\n \/\/ Records the appearance times of each potential edge in the witness\n \/\/ complex.\n\n aleph::math::SymmetricMatrix<DataType> M( n );\n\n for( std::size_t i = 0; i < n; i++ )\n {\n for( std::size_t j = i+1; j < n; j++ )\n {\n auto min = std::numeric_limits<DataType>::max();\n\n for( std::size_t k = 0; k < N; k++ )\n min = std::min( min, std::max( D[i][k], D[j][k] ) );\n\n M(i,j) = min;\n }\n }\n\n \/\/ Get smallest entries of the distance matrix. This is required for\n \/\/ deciding whether a specific edge is valid or not, with respect to\n \/\/ the given parameters.\n\n std::vector<DataType> smallest( N );\n\n if( nu != 0 )\n {\n for( std::size_t col = 0; col < N; col++ )\n {\n \/\/ FIXME: getting the column like this is extremely wasteful;\n \/\/ would it not be nicer to store the values differently?\n std::vector<DataType> column( n );\n for( std::size_t i = 0; i < n; i++ )\n column[i] = D[i][col];\n\n std::nth_element( column.begin(), column.begin() + nu - 1, column.end() );\n smallest[col] = column.at( nu - 1 );\n }\n }\n\n auto max = *std::max_element( smallest.begin(), smallest.end() );\n\n std::vector<Simplex> simplices;\n\n for( std::size_t i = 0; i < n; i++ )\n {\n simplices.push_back( Simplex( static_cast<VertexType>(i) ) );\n\n for( std::size_t j = i+1; j < n; j++ )\n {\n \/\/ Skip pairs that cannot possibly give rise to an edge because of\n \/\/ their distance to each other.\n if( M(i,j) > R + max )\n continue;\n\n for( std::size_t col = 0; col < N; col++ )\n {\n if( M(i,j) <= R + smallest.at(col) )\n {\n auto u = static_cast<VertexType>(i);\n auto v = static_cast<VertexType>(j);\n\n simplices.push_back( Simplex( {u,v}, M(i,j) ) );\n break;\n }\n }\n }\n }\n\n return SimplicialComplex( simplices.begin(), simplices.end() );\n}\n\n} \/\/ namespace geometry\n\n} \/\/ namespace aleph\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>#pragma once\n\/*\n* Covariant Script OS Support\n*\n* Licensed under the Covariant Innovation General Public License,\n* Version 1.0 (the \"License\");\n* you may not use this file except in compliance with the License.\n* You may obtain a copy of the License at\n*\n* https:\/\/covariant.cn\/licenses\/LICENSE-1.0\n*\n* Unless required by applicable law or agreed to in writing, software\n* distributed under the License is distributed on an \"AS IS\" BASIS,\n* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n* See the License for the specific language governing permissions and\n* limitations under the License.\n*\n* Copyright (C) 2019 Michael Lee(李登淳)\n* Email: mikecovlee@163.com\n* Github: https:\/\/github.com\/mikecovlee\n*\/\n#if defined(_WIN32) || defined(WIN32)\n\n#include \".\/win32_impl.hpp\"\n\n#else\n\n#include \".\/unix_impl.hpp\"\n\n#endif\n<commit_msg>Update system.hpp<commit_after>#pragma once\n\/*\n* Covariant Script OS Support\n*\n* Licensed under the Covariant Innovation General Public License,\n* Version 1.0 (the \"License\");\n* you may not use this file except in compliance with the License.\n* You may obtain a copy of the License at\n*\n* https:\/\/covariant.cn\/licenses\/LICENSE-1.0\n*\n* Unless required by applicable law or agreed to in writing, software\n* distributed under the License is distributed on an \"AS IS\" BASIS,\n* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n* See the License for the specific language governing permissions and\n* limitations under the License.\n*\n* Copyright (C) 2019 Michael Lee(李登淳)\n* Email: mikecovlee@163.com\n* Github: https:\/\/github.com\/mikecovlee\n*\/\n#if defined(_WIN32) || defined(WIN32)\n\n#include \".\/win32_impl.hpp\"\n\n#else\n\n#include \".\/unix_impl.hpp\"\n\n#endif\n\n#include <sys\/stat.h>\n\nnamespace cs_impl {\n namespace filesystem {\n bool is_directory(const std::string &path) {\n struct stat s{};\n if (stat(path.c_str(), &s) == 0) {\n return S_ISDIR(s.st_mode);\n }\n return false;\n }\n }\n}<|endoftext|>"} {"text":"<commit_before>\/\/ vim:ts=2:sw=2:expandtab:autoindent:filetype=cpp:\n\/*\nCopyright (c) 2009 Aristid Breitkreuz, Ash Berlin, Ruediger Sonderfeld\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n*\/\n\n#ifndef FLUSSFPERD_CLASS_DESCRIPTION_HPP\n#define FLUSSFPERD_CLASS_DESCRIPTION_HPP\n\n#ifndef PREPROC_DEBUG\n#include \"class.hpp\"\n#endif\n#include <boost\/preprocessor.hpp>\n\n#define FLUSSPFERD_PP_GEN_TUPLE2SEQ_PROCESS2(x, y) \\\n ((x, y)) \\\n FLUSSPFERD_PP_GEN_TUPLE2SEQ_PROCESS\n\n#define FLUSSPFERD_PP_GEN_TUPLE2SEQ_PROCESS(x, y) \\\n ((x, y)) \\\n FLUSSPFERD_PP_GEN_TUPLE2SEQ_PROCESS2\n\n#define FLUSSPFERD_PP_GEN_TUPLE2SEQ_PROCESS_ELIM\n#define FLUSSPFERD_PP_GEN_TUPLE2SEQ_PROCESS2_ELIM\n\n#define FLUSSPFERD_PP_GEN_TUPLE2SEQ(x) \\\n BOOST_PP_CAT(BOOST_PP_EXPAND(FLUSSPFERD_PP_GEN_TUPLE2SEQ_PROCESS x), _ELIM)\n\n#define FLUSSPFERD_CD_PARAM_FOLD(s, state, elem) \\\n BOOST_PP_ARRAY_REPLACE( \\\n state, \\\n BOOST_PP_EXPAND( \\\n BOOST_PP_CAT(FLUSSPFERD_CD_PARAM__, \\\n BOOST_PP_TUPLE_ELEM(2, 0, elem))), \\\n BOOST_PP_TUPLE_ELEM(2, 1, elem)) \\\n \/* *\/\n\n#define FLUSSPFERD_CD_PARAM_INITIAL \\\n (6, ( \\\n ~cpp_name~, \/* name *\/ \\\n ~constructor_name~, \/* constructor name *\/ \\\n ~constructor_arity~, \/* constructor arity *\/ \\\n ~full_name~, \/* full name *\/ \\\n BOOST_PP_NIL, \/* methods *\/ \\\n 0 \/* augment constructor *\/ \\\n )) \\\n \/* *\/\n\n#define FLUSSPFERD_CD_PARAM__cpp_name 0\n#define FLUSSPFERD_CD_PARAM__constructor_name 1\n#define FLUSSPFERD_CD_PARAM__constructor_arity 2\n#define FLUSSPFERD_CD_PARAM__full_name 3\n#define FLUSSPFERD_CD_PARAM__methods 4\n#define FLUSSPFERD_CD_PARAM__augment_constructor 5\n\n#define FLUSSPFERD_CD_PARAM(tuple_seq) \\\n BOOST_PP_SEQ_FOLD_LEFT( \\\n FLUSSPFERD_CD_PARAM_FOLD, \\\n FLUSSPFERD_CD_PARAM_INITIAL, \\\n FLUSSPFERD_PP_GEN_TUPLE2SEQ(tuple_seq) \\\n ) \\\n \/* *\/\n\n#define FLUSSPFERD_CLASS_DESCRIPTION_A(array) \\\n BOOST_PP_EXPAND(FLUSSPFERD_CLASS_DESCRIPTION_P BOOST_PP_ARRAY_DATA(array)) \\\n \/* *\/\n\n#define FLUSSPFERD_CLASS_DESCRIPTION_P( \\\n p_cpp_name, \\\n p_constructor_name, \\\n p_constructor_arity, \\\n p_full_name, \\\n p_methods, \\\n p_augment_constructor \\\n) \\\n class p_cpp_name { \\\n struct class_info : ::flusspferd::class_info_base { \\\n static char const *constructor_name() { \\\n return (p_constructor_name); \\\n } \\\n typedef ::boost::mpl::size_t< (p_constructor_arity) > constructor_arity; \\\n static char const *full_name() { \\\n return (p_full_name); \\\n } \\\n static ::flusspferd::object create_prototype() { \\\n ::flusspferd::object proto = ::flusspferd::create_object(); \\\n BOOST_PP_SEQ_FOR_EACH( \\\n FLUSSPFERD_CD_METHOD, \\\n p_cpp_name, \\\n p_methods) \\\n } \\\n BOOST_PP_EXPR_IF( \\\n p_augment_constructor, \\\n static void augment_constructor(::flusspferd::object &); \\\n ) \\\n }; \\\n \/* *\/\n\n#define FLUSSPFERD_CD_METHOD(r, p_cpp_name, element) \\\n ::flusspferd::create_native_method( \\\n proto, \\\n BOOST_PP_STRINGIZE(element), \\\n & p_cpp_name :: element); \\\n \/* *\/\n\n#define FLUSSPFERD_CLASS_DESCRIPTION(tuple_seq) \\\n FLUSSPFERD_CLASS_DESCRIPTION_A(FLUSSPFERD_CD_PARAM(tuple_seq)) \\\n \/* *\/\n\n#define FLUSSPFERD_CLASS_DESCRIPTION_END() \\\n }; \\\n \/* *\/\n\n#endif\n<commit_msg>class_macros: add base class and public\/private classifiers<commit_after>\/\/ vim:ts=2:sw=2:expandtab:autoindent:filetype=cpp:\n\/*\nCopyright (c) 2009 Aristid Breitkreuz, Ash Berlin, Ruediger Sonderfeld\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n*\/\n\n#ifndef FLUSSFPERD_CLASS_DESCRIPTION_HPP\n#define FLUSSFPERD_CLASS_DESCRIPTION_HPP\n\n#ifndef PREPROC_DEBUG\n#include \"class.hpp\"\n#include \"native_object_base.hpp\"\n#endif\n#include <boost\/preprocessor.hpp>\n\n#define FLUSSPFERD_PP_GEN_TUPLE2SEQ_PROCESS2(x, y) \\\n ((x, y)) \\\n FLUSSPFERD_PP_GEN_TUPLE2SEQ_PROCESS\n\n#define FLUSSPFERD_PP_GEN_TUPLE2SEQ_PROCESS(x, y) \\\n ((x, y)) \\\n FLUSSPFERD_PP_GEN_TUPLE2SEQ_PROCESS2\n\n#define FLUSSPFERD_PP_GEN_TUPLE2SEQ_PROCESS_ELIM\n#define FLUSSPFERD_PP_GEN_TUPLE2SEQ_PROCESS2_ELIM\n\n#define FLUSSPFERD_PP_GEN_TUPLE2SEQ(x) \\\n BOOST_PP_CAT(BOOST_PP_EXPAND(FLUSSPFERD_PP_GEN_TUPLE2SEQ_PROCESS x), _ELIM)\n\n#define FLUSSPFERD_CD_PARAM_FOLD(s, state, elem) \\\n BOOST_PP_ARRAY_REPLACE( \\\n state, \\\n BOOST_PP_EXPAND( \\\n BOOST_PP_CAT(FLUSSPFERD_CD_PARAM__, \\\n BOOST_PP_TUPLE_ELEM(2, 0, elem))), \\\n BOOST_PP_TUPLE_ELEM(2, 1, elem)) \\\n \/* *\/\n\n#define FLUSSPFERD_CD_PARAM_INITIAL \\\n (6, ( \\\n ~cpp_name~, \/* name *\/ \\\n ~constructor_name~, \/* constructor name *\/ \\\n ~constructor_arity~, \/* constructor arity *\/ \\\n ~full_name~, \/* full name *\/ \\\n BOOST_PP_NIL, \/* methods *\/ \\\n 0 \/* augment constructor *\/ \\\n )) \\\n \/* *\/\n\n#define FLUSSPFERD_CD_PARAM__cpp_name 0\n#define FLUSSPFERD_CD_PARAM__constructor_name 1\n#define FLUSSPFERD_CD_PARAM__constructor_arity 2\n#define FLUSSPFERD_CD_PARAM__full_name 3\n#define FLUSSPFERD_CD_PARAM__methods 4\n#define FLUSSPFERD_CD_PARAM__augment_constructor 5\n\n#define FLUSSPFERD_CD_PARAM(tuple_seq) \\\n BOOST_PP_SEQ_FOLD_LEFT( \\\n FLUSSPFERD_CD_PARAM_FOLD, \\\n FLUSSPFERD_CD_PARAM_INITIAL, \\\n FLUSSPFERD_PP_GEN_TUPLE2SEQ(tuple_seq) \\\n ) \\\n \/* *\/\n\n#define FLUSSPFERD_CLASS_DESCRIPTION_A(array) \\\n BOOST_PP_EXPAND(FLUSSPFERD_CLASS_DESCRIPTION_P BOOST_PP_ARRAY_DATA(array)) \\\n \/* *\/\n\n#define FLUSSPFERD_CLASS_DESCRIPTION_P( \\\n p_cpp_name, \\\n p_constructor_name, \\\n p_constructor_arity, \\\n p_full_name, \\\n p_methods, \\\n p_augment_constructor \\\n) \\\n class p_cpp_name : public ::flusspferd::native_object_base { \\\n public: \\\n struct class_info : ::flusspferd::class_info_base { \\\n static char const *constructor_name() { \\\n return (p_constructor_name); \\\n } \\\n typedef ::boost::mpl::size_t< (p_constructor_arity) > constructor_arity; \\\n static char const *full_name() { \\\n return (p_full_name); \\\n } \\\n static ::flusspferd::object create_prototype() { \\\n ::flusspferd::object proto = ::flusspferd::create_object(); \\\n BOOST_PP_SEQ_FOR_EACH( \\\n FLUSSPFERD_CD_METHOD, \\\n p_cpp_name, \\\n p_methods) \\\n } \\\n BOOST_PP_EXPR_IF( \\\n p_augment_constructor, \\\n static void augment_constructor(::flusspferd::object &); \\\n ) \\\n }; \\\n private: \\\n \/* *\/\n\n#define FLUSSPFERD_CD_METHOD(r, p_cpp_name, element) \\\n ::flusspferd::create_native_method( \\\n proto, \\\n BOOST_PP_STRINGIZE(element), \\\n & p_cpp_name :: element); \\\n \/* *\/\n\n#define FLUSSPFERD_CLASS_DESCRIPTION(tuple_seq) \\\n FLUSSPFERD_CLASS_DESCRIPTION_A(FLUSSPFERD_CD_PARAM(tuple_seq)) \\\n \/* *\/\n\n#define FLUSSPFERD_CLASS_DESCRIPTION_END() \\\n }; \\\n \/* *\/\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/\/ kate: indent-mode cstyle; indent-width 4; tab-width 4; space-indent false;\n\/\/ vim:ai ts=4 et\n\n#include <iostream>\n\n#include <boost\/foreach.hpp>\n\n#include \"BallModel.hpp\"\n\nusing namespace std;\n\nModeling::BallModel::BallModel(mode_t mode, RobotModel::RobotMap *robotMap) :\n\tA(6,6), B(6,6), P(6,6), Q(6,6), R(2,2), H(2,6),\n\tZ(2), U(6), X0(6), _mode(mode), _robotMap(robotMap)\n{\n\tlastObservedTime = 0;\n\tlastUpdatedTime = 0;\n\n\tif (_mode == MODELTESTS) {\n\t\tcout << \"Running ball model tests...\" << endl;\n\t\tinitKalman();\n\t\tinitRBPF();\n\t\tkalmanTestPosError = 0; kalmanTestVelError = 0;\n\t\trbpfTestPosError = 0; rbpfTestVelError = 0;\n\t} else if (_mode == KALMAN) {\n\t\tinitKalman();\n\t} else if (_mode == RBPF) {\n\t\tinitRBPF();\n\t} else if (_mode == ABG) {\n\t\tinitABG();\n\t} else {\n\t\tcout << \"ERROR: Invalid initialization type, defaulting to RPBF!\" << endl;\n\t\t_mode = RBPF;\n\t\tinitRBPF();\n\t}\n}\n\nvoid Modeling::BallModel::initABG() {\n\talpha = 1;\n\tbeta = .4;\n\tgamma = .1;\n}\n\nvoid Modeling::BallModel::initKalman() {\n\tA.zero();\n\tB.zero();\n\tQ.zero();\n\tR.zero();\n\tH.zero();\n\tP.zero();\n\tX0.zero();\n\n\t\/\/Process covariance between position and velocity (E[x,x_dot])\n\t\/\/ \tQ(1,0) = Q(4,3) = 0.01;\n\n\t\/\/Process covariance between velocity and acceleration (E[x)dot,x_ddot])\n\t\/\/ \tQ(2,1) = Q(5,4) = 0.001;\n\n\t\/\/Process covariance between position and acceleration (E[x,x_ddot])\n\t\/\/ \tQ(2,0) = Q(5,3) = 0.0001;\n\n\t\/\/Process covariance (E[x,x], E[x_dot,x_dot], etc)\n\tQ(0,0) = Q(3,3) = 10;\n\n\tQ(1,1) = Q(4,4) = 10;\n\n\tQ(2,2) = Q(5,5) = 10;\n\n\t\/\/Measurement Covariance for position in the x and the y\n\tR(0,0) = R(1,1) = 0.84;\n\n\t\/\/Measurement Model. We can only measure position\n\tH(0,0) = H(1,3) = 1;\n\n\t\/\/State Model\n\tA(0,0) = A(1,1) = A(2,2) = A(3,3) = A(4,4) = A(5,5) = 1;\n\n\tposKalman = new DifferenceKalmanFilter(&A, &B, &X0, &P, &Q, &R, &H);\n}\n\nvoid Modeling::BallModel::initRBPF() {\n\t\/\/ Construct initial state X (n x 1)\n\tVector X(6); X.clear();\n\t\/\/ Construct initial state covariance P (n x n)\n\tMatrix P(6,6); P.clear(); P(0,0)=P(1,1)= P(2,2)=P(3,3)=P(4,4)=P(5,5)=0.01;\n\t\/\/ Create Rbpf\n\tint numParticles = 20; \/\/ Number of particles in filter\n\traoBlackwellizedParticleFilter = new Rbpf(X,P,numParticles);\n\t\/\/ create model graph\n\traoBlackwellizedParticleFilter->addModel(new RbpfModelRolling(_robotMap));\n\traoBlackwellizedParticleFilter->addModel(new RbpfModelKicked(_robotMap));\n\traoBlackwellizedParticleFilter->setTransProb(0,0,0.9);\n\traoBlackwellizedParticleFilter->setTransProb(0,1,0.1);\n\traoBlackwellizedParticleFilter->setTransProb(1,0,0.9);\n\traoBlackwellizedParticleFilter->setTransProb(1,1,0.1);\n}\n\nGeometry2d::Point Modeling::BallModel::predictPosAtTime(float dtime)\n{\n\treturn pos + vel * dtime + accel * 0.5f * dtime * dtime;\n}\n\nvoid Modeling::BallModel::observation(uint64_t time, const Geometry2d::Point &pos, observation_mode obs_type)\n{\n\tobservation_type obs = {time, pos, obs_type};\n\t_observations.push_back(obs);\n\n\t\/\/ set lastObservedTime to the last observation's time\n\tif (time > lastObservedTime)\n\t\tlastObservedTime = time;\n}\n\nvoid Modeling::BallModel::kalmanUpdate(float dtime) {\n\t\/\/Update model\n\tA(0,1) = dtime;\n\tA(0,2) = 0.5*dtime*dtime;\n\n\tA(1,2) = dtime;\n\n\tA(3,4) = dtime;\n\tA(3,5) = 0.5*dtime*dtime;\n\n\tA(4,5) = dtime;\n\n\t\/\/Position\n\tZ(0) = observedPos.x;\n\tZ(1) = observedPos.y;\n\n\tposKalman->predict(&U);\n\tposKalman->correct(&Z);\n\n\tpos.x = (float)posKalman->state()->elt(0);\n\tvel.x = (float)posKalman->state()->elt(1);\n\taccel.x = (float)posKalman->state()->elt(2);\n\tpos.y = (float)posKalman->state()->elt(3);\n\tvel.y = (float)posKalman->state()->elt(4);\n\taccel.y = (float)posKalman->state()->elt(5);\n}\n\nvoid Modeling::BallModel::rbpfUpdate(float dtime) {\n\traoBlackwellizedParticleFilter->update(observedPos.x,observedPos.y,dtime);\n\tRbpfState* bestState = raoBlackwellizedParticleFilter->getBestFilterState();\n\tpos.x = bestState->X(0);\n\tpos.y = bestState->X(1);\n\tvel.x = bestState->X(2);\n\tvel.y = bestState->X(3);\n\taccel.x = bestState->X(4);\n\taccel.y = bestState->X(5);\n}\n\nvoid Modeling::BallModel::rbpfUpdateMultipleObs(std::vector<observation_type> &obs){\n\tint numObs = obs.size();\n\tdouble x[numObs];\n\tdouble y[numObs];\n\tdouble dt[numObs];\n\tfor(int i=obs.size()-1; i>=0; i--){\n\t\tx[i] = obs[i].pos.x;\n\t\ty[i] = obs[i].pos.y;\n\t\tdt[i] = (float)(obs[i].time - lastUpdatedTime) \/ 1e6;\n\t}\n\traoBlackwellizedParticleFilter->updateMultipleObs(x,y,dt,numObs);\n\tRbpfState* bestState = raoBlackwellizedParticleFilter->getBestFilterState();\n\tpos.x = bestState->X(0);\n\tpos.y = bestState->X(1);\n\tvel.x = bestState->X(2);\n\tvel.y = bestState->X(3);\n\taccel.x = bestState->X(4);\n\taccel.y = bestState->X(5);\n}\n\nvoid Modeling::BallModel::abgUpdate(float dtime) {\n\tGeometry2d::Point predictPos = abgPos + vel * dtime + accel * 0.5f * dtime * dtime;\n\tGeometry2d::Point predictVel = vel + accel * dtime;\n\n\tGeometry2d::Point posError = observedPos - predictPos;\n\tabgPos = predictPos + posError * alpha;\n\tvel = predictVel + posError * beta \/ dtime;\n\taccel += posError * gamma \/ (dtime * dtime);\n}\n\nbool Modeling::BallModel::valid(uint64_t time) {\n\t\/\/return !_observations.empty() || ((time - lastUpdatedTime) > MaxCoastTime);\n\t\/\/ even with no observations, we can be valid.\n\treturn ((time - lastUpdatedTime) > MaxCoastTime);\n}\n\nvoid Modeling::BallModel::update(uint64_t time)\n{\n\tconst bool verbose = false;\n\n\tif(_observations.empty()) {\n\t\t\/\/ coast the ball using simple integrator\n\t\tfloat dtime = (float)(time - lastUpdatedTime) \/ 1e6;\n\t\tpos = predictPosAtTime(dtime);\n\t\tvel += accel * 0.5f * dtime * dtime;\n\t\treturn;\n\t}\n\n\t\/\/ loop through the observations and determine if we got vision observations\n\tbool gotCameraObservation = false;\n\tBOOST_FOREACH(const observation_type& obs, _observations) {\n\t\tif(obs.obs_type == BallModel::VISION){\n\t\t\tgotCameraObservation = true;\n\t\t\tbreak;\n\t\t}\n\t}\n\n\t\/\/ If there are camera observations, remove robot sensor observations.\n\tvector<observation_type> goodObs;\n\tif(gotCameraObservation){\n\t\tBOOST_FOREACH(const observation_type& obs, _observations) {\n\t\t\tif (obs.obs_type == BallModel::VISION) {\n\t\t\t\tgoodObs.push_back(obs);\n\t\t\t}\n\t\t}\n\t} else {\n\t\tgoodObs = _observations;\n\t}\n\t_observations = goodObs;\n\tif (verbose) cout << \" ballModel has \" << _observations.size() << \" observations, updating...\" << endl;\n\n\t\/\/ TODO: handle non-RBPF filters properly\n\tif (_mode != RBPF){\n\t\tcout << \"update() not implemented in ballmodel.cpp\" << endl;\n\t} else if (_mode == RBPF) {\n\t\trbpfUpdateMultipleObs(_observations);\n\t}\n\n\t\/\/ remove previous observations after processing them\n\t_observations.clear();\n\n\t\/\/ remember last update\n\tlastUpdatedTime = time;\n\n\t\/*\n\tfloat dtime = (float)(bestObservedTime - lastObservedTime) \/ 1e6;\n\n\tif (missedFrames > 5 || bestError < (0.2 * 0.2))\n\t{\n\t\tlastObservedTime = bestObservedTime;\n\n\t\t\/\/ assuming we moved, then update the filter\n\t\tif (dtime)\n\t\t{\n\t\t\tif (_mode == MODELTESTS){\n\t\t\t\tGeometry2d::Point posKalmanDiff, posRbpfDiff;\n\t\t\t\tGeometry2d::Point velKalmanDiff, velRbpfDiff;\n\t\t\t\tGeometry2d::Point observedVel = (observedPos - prevObservedPos)*(1\/dtime);\n\t\t\t\tfloat errorPosKalman, errorPosRbpf;\n\t\t\t\tfloat errorVelKalman, errorVelRbpf;\n\n\t\t\t\tkalmanUpdate(dtime);\n\t\t\t\tposKalmanDiff = observedPos - pos;\n\t\t\t\tvelKalmanDiff = observedVel - vel;\n\t\t\t\trbpfUpdate(dtime);\n\t\t\t\tposRbpfDiff = observedPos - pos;\n\t\t\t\tvelRbpfDiff = observedVel - vel;\n\n\t\t\t\terrorPosKalman = posKalmanDiff.mag();\n\t\t\t\terrorPosRbpf = posRbpfDiff.mag();\n\t\t\t\terrorVelKalman = velKalmanDiff.mag();\n\t\t\t\terrorVelRbpf = velRbpfDiff.mag();\n\n\t\t\t\tkalmanTestPosError += errorPosKalman;\n\t\t\t\trbpfTestPosError += errorPosRbpf;\n\t\t\t\tkalmanTestVelError += errorVelKalman;\n\t\t\t\trbpfTestVelError += errorVelRbpf;\n\t\t\t\t\/\/cout << \"Total error (Kal, Rbpf): (\" << kalmanTesPostError << \",\" << rbpfTestPosError << \"), this obs error (Kal, Rbpf): (\" << errorKalman << \",\" << errorRbpf << \")\" << endl;\n\t\t\t\tcout << \"Total pos error (Kal, Rbpf): (\" << kalmanTestPosError << \",\" << rbpfTestPosError << \"), total vel error (Kal, Rbpf): (\" << kalmanTestVelError << \",\" << rbpfTestVelError << \")\" << endl;\n\t\t\t} else if (_mode == KALMAN) {\n\t\t\t\tkalmanUpdate(dtime);\n\t\t\t} else if (_mode == ABG) {\n\t\t\t\tabgUpdate(dtime);\n\t\t\t} else if (_mode == RBPF) {\n\t\t\t\trbpfUpdate(dtime);\n\t\t\t}\n\t\t\tprevObservedPos = observedPos;\n\t\t}\n\t} else {\n\t\t\/\/ Ball moved too far to possibly be a valid track, so just extrapolate from the last known state\n\t\tif (dtime)\n\t\t{\n\t\t\tif(_mode == MODELTESTS){\n\t\t\t\tcout << \"Ball Model Tests: missed too many frames, extrapolating.\" << endl;\n\t\t\t}\n\t\t\tpos += vel * dtime + accel * 0.5f * dtime * dtime;\n\t\t}\n\n\t\t++missedFrames;\n\t}\n\tbestError = -1;\n\t*\/\n}\n<commit_msg>Fixed coasting error<commit_after>\/\/ kate: indent-mode cstyle; indent-width 4; tab-width 4; space-indent false;\n\/\/ vim:ai ts=4 et\n\n#include <iostream>\n\n#include <boost\/foreach.hpp>\n\n#include \"BallModel.hpp\"\n\nusing namespace std;\n\nModeling::BallModel::BallModel(mode_t mode, RobotModel::RobotMap *robotMap) :\n\tA(6,6), B(6,6), P(6,6), Q(6,6), R(2,2), H(2,6),\n\tZ(2), U(6), X0(6), _mode(mode), _robotMap(robotMap)\n{\n\tlastObservedTime = 0;\n\tlastUpdatedTime = 0;\n\n\tif (_mode == MODELTESTS) {\n\t\tcout << \"Running ball model tests...\" << endl;\n\t\tinitKalman();\n\t\tinitRBPF();\n\t\tkalmanTestPosError = 0; kalmanTestVelError = 0;\n\t\trbpfTestPosError = 0; rbpfTestVelError = 0;\n\t} else if (_mode == KALMAN) {\n\t\tinitKalman();\n\t} else if (_mode == RBPF) {\n\t\tinitRBPF();\n\t} else if (_mode == ABG) {\n\t\tinitABG();\n\t} else {\n\t\tcout << \"ERROR: Invalid initialization type, defaulting to RPBF!\" << endl;\n\t\t_mode = RBPF;\n\t\tinitRBPF();\n\t}\n}\n\nvoid Modeling::BallModel::initABG() {\n\talpha = 1;\n\tbeta = .4;\n\tgamma = .1;\n}\n\nvoid Modeling::BallModel::initKalman() {\n\tA.zero();\n\tB.zero();\n\tQ.zero();\n\tR.zero();\n\tH.zero();\n\tP.zero();\n\tX0.zero();\n\n\t\/\/Process covariance between position and velocity (E[x,x_dot])\n\t\/\/ \tQ(1,0) = Q(4,3) = 0.01;\n\n\t\/\/Process covariance between velocity and acceleration (E[x)dot,x_ddot])\n\t\/\/ \tQ(2,1) = Q(5,4) = 0.001;\n\n\t\/\/Process covariance between position and acceleration (E[x,x_ddot])\n\t\/\/ \tQ(2,0) = Q(5,3) = 0.0001;\n\n\t\/\/Process covariance (E[x,x], E[x_dot,x_dot], etc)\n\tQ(0,0) = Q(3,3) = 10;\n\n\tQ(1,1) = Q(4,4) = 10;\n\n\tQ(2,2) = Q(5,5) = 10;\n\n\t\/\/Measurement Covariance for position in the x and the y\n\tR(0,0) = R(1,1) = 0.84;\n\n\t\/\/Measurement Model. We can only measure position\n\tH(0,0) = H(1,3) = 1;\n\n\t\/\/State Model\n\tA(0,0) = A(1,1) = A(2,2) = A(3,3) = A(4,4) = A(5,5) = 1;\n\n\tposKalman = new DifferenceKalmanFilter(&A, &B, &X0, &P, &Q, &R, &H);\n}\n\nvoid Modeling::BallModel::initRBPF() {\n\t\/\/ Construct initial state X (n x 1)\n\tVector X(6); X.clear();\n\t\/\/ Construct initial state covariance P (n x n)\n\tMatrix P(6,6); P.clear(); P(0,0)=P(1,1)= P(2,2)=P(3,3)=P(4,4)=P(5,5)=0.01;\n\t\/\/ Create Rbpf\n\tint numParticles = 20; \/\/ Number of particles in filter\n\traoBlackwellizedParticleFilter = new Rbpf(X,P,numParticles);\n\t\/\/ create model graph\n\traoBlackwellizedParticleFilter->addModel(new RbpfModelRolling(_robotMap));\n\traoBlackwellizedParticleFilter->addModel(new RbpfModelKicked(_robotMap));\n\traoBlackwellizedParticleFilter->setTransProb(0,0,0.9);\n\traoBlackwellizedParticleFilter->setTransProb(0,1,0.1);\n\traoBlackwellizedParticleFilter->setTransProb(1,0,0.9);\n\traoBlackwellizedParticleFilter->setTransProb(1,1,0.1);\n}\n\nGeometry2d::Point Modeling::BallModel::predictPosAtTime(float dtime)\n{\n\treturn pos + vel * dtime + accel * 0.5f * dtime * dtime;\n}\n\nvoid Modeling::BallModel::observation(uint64_t time, const Geometry2d::Point &pos, observation_mode obs_type)\n{\n\tobservation_type obs = {time, pos, obs_type};\n\t_observations.push_back(obs);\n\n\t\/\/ set lastObservedTime to the last observation's time\n\tif (time > lastObservedTime)\n\t\tlastObservedTime = time;\n}\n\nvoid Modeling::BallModel::kalmanUpdate(float dtime) {\n\t\/\/Update model\n\tA(0,1) = dtime;\n\tA(0,2) = 0.5*dtime*dtime;\n\n\tA(1,2) = dtime;\n\n\tA(3,4) = dtime;\n\tA(3,5) = 0.5*dtime*dtime;\n\n\tA(4,5) = dtime;\n\n\t\/\/Position\n\tZ(0) = observedPos.x;\n\tZ(1) = observedPos.y;\n\n\tposKalman->predict(&U);\n\tposKalman->correct(&Z);\n\n\tpos.x = (float)posKalman->state()->elt(0);\n\tvel.x = (float)posKalman->state()->elt(1);\n\taccel.x = (float)posKalman->state()->elt(2);\n\tpos.y = (float)posKalman->state()->elt(3);\n\tvel.y = (float)posKalman->state()->elt(4);\n\taccel.y = (float)posKalman->state()->elt(5);\n}\n\nvoid Modeling::BallModel::rbpfUpdate(float dtime) {\n\traoBlackwellizedParticleFilter->update(observedPos.x,observedPos.y,dtime);\n\tRbpfState* bestState = raoBlackwellizedParticleFilter->getBestFilterState();\n\tpos.x = bestState->X(0);\n\tpos.y = bestState->X(1);\n\tvel.x = bestState->X(2);\n\tvel.y = bestState->X(3);\n\taccel.x = bestState->X(4);\n\taccel.y = bestState->X(5);\n}\n\nvoid Modeling::BallModel::rbpfUpdateMultipleObs(std::vector<observation_type> &obs){\n\tint numObs = obs.size();\n\tdouble x[numObs];\n\tdouble y[numObs];\n\tdouble dt[numObs];\n\tfor(int i=obs.size()-1; i>=0; i--){\n\t\tx[i] = obs[i].pos.x;\n\t\ty[i] = obs[i].pos.y;\n\t\tdt[i] = (float)(obs[i].time - lastUpdatedTime) \/ 1e6;\n\t}\n\traoBlackwellizedParticleFilter->updateMultipleObs(x,y,dt,numObs);\n\tRbpfState* bestState = raoBlackwellizedParticleFilter->getBestFilterState();\n\tpos.x = bestState->X(0);\n\tpos.y = bestState->X(1);\n\tvel.x = bestState->X(2);\n\tvel.y = bestState->X(3);\n\taccel.x = bestState->X(4);\n\taccel.y = bestState->X(5);\n}\n\nvoid Modeling::BallModel::abgUpdate(float dtime) {\n\tGeometry2d::Point predictPos = abgPos + vel * dtime + accel * 0.5f * dtime * dtime;\n\tGeometry2d::Point predictVel = vel + accel * dtime;\n\n\tGeometry2d::Point posError = observedPos - predictPos;\n\tabgPos = predictPos + posError * alpha;\n\tvel = predictVel + posError * beta \/ dtime;\n\taccel += posError * gamma \/ (dtime * dtime);\n}\n\nbool Modeling::BallModel::valid(uint64_t time) {\n\treturn !_observations.empty() || ((time - lastUpdatedTime) < MaxCoastTime);\n}\n\nvoid Modeling::BallModel::update(uint64_t time)\n{\n\tconst bool verbose = false;\n\n\tif(_observations.empty()) {\n\t\t\/\/ coast the ball using simple integrator\n\t\tfloat dtime = (float)(time - lastUpdatedTime) \/ 1e6;\n\t\tpos = predictPosAtTime(dtime);\n\t\tvel += accel * 0.5f * dtime * dtime;\n\t\treturn;\n\t}\n\n\t\/\/ loop through the observations and determine if we got vision observations\n\tbool gotCameraObservation = false;\n\tBOOST_FOREACH(const observation_type& obs, _observations) {\n\t\tif(obs.obs_type == BallModel::VISION){\n\t\t\tgotCameraObservation = true;\n\t\t\tbreak;\n\t\t}\n\t}\n\n\t\/\/ If there are camera observations, remove robot sensor observations.\n\tvector<observation_type> goodObs;\n\tif(gotCameraObservation){\n\t\tBOOST_FOREACH(const observation_type& obs, _observations) {\n\t\t\tif (obs.obs_type == BallModel::VISION) {\n\t\t\t\tgoodObs.push_back(obs);\n\t\t\t}\n\t\t}\n\t} else {\n\t\tgoodObs = _observations;\n\t}\n\t_observations = goodObs;\n\tif (verbose) cout << \" ballModel has \" << _observations.size() << \" observations, updating...\" << endl;\n\n\t\/\/ TODO: handle non-RBPF filters properly\n\tif (_mode != RBPF){\n\t\tcout << \"update() not implemented in ballmodel.cpp\" << endl;\n\t} else if (_mode == RBPF) {\n\t\trbpfUpdateMultipleObs(_observations);\n\t}\n\n\t\/\/ remove previous observations after processing them\n\t_observations.clear();\n\n\t\/\/ remember last update\n\tlastUpdatedTime = time;\n\n\t\/*\n\tfloat dtime = (float)(bestObservedTime - lastObservedTime) \/ 1e6;\n\n\tif (missedFrames > 5 || bestError < (0.2 * 0.2))\n\t{\n\t\tlastObservedTime = bestObservedTime;\n\n\t\t\/\/ assuming we moved, then update the filter\n\t\tif (dtime)\n\t\t{\n\t\t\tif (_mode == MODELTESTS){\n\t\t\t\tGeometry2d::Point posKalmanDiff, posRbpfDiff;\n\t\t\t\tGeometry2d::Point velKalmanDiff, velRbpfDiff;\n\t\t\t\tGeometry2d::Point observedVel = (observedPos - prevObservedPos)*(1\/dtime);\n\t\t\t\tfloat errorPosKalman, errorPosRbpf;\n\t\t\t\tfloat errorVelKalman, errorVelRbpf;\n\n\t\t\t\tkalmanUpdate(dtime);\n\t\t\t\tposKalmanDiff = observedPos - pos;\n\t\t\t\tvelKalmanDiff = observedVel - vel;\n\t\t\t\trbpfUpdate(dtime);\n\t\t\t\tposRbpfDiff = observedPos - pos;\n\t\t\t\tvelRbpfDiff = observedVel - vel;\n\n\t\t\t\terrorPosKalman = posKalmanDiff.mag();\n\t\t\t\terrorPosRbpf = posRbpfDiff.mag();\n\t\t\t\terrorVelKalman = velKalmanDiff.mag();\n\t\t\t\terrorVelRbpf = velRbpfDiff.mag();\n\n\t\t\t\tkalmanTestPosError += errorPosKalman;\n\t\t\t\trbpfTestPosError += errorPosRbpf;\n\t\t\t\tkalmanTestVelError += errorVelKalman;\n\t\t\t\trbpfTestVelError += errorVelRbpf;\n\t\t\t\t\/\/cout << \"Total error (Kal, Rbpf): (\" << kalmanTesPostError << \",\" << rbpfTestPosError << \"), this obs error (Kal, Rbpf): (\" << errorKalman << \",\" << errorRbpf << \")\" << endl;\n\t\t\t\tcout << \"Total pos error (Kal, Rbpf): (\" << kalmanTestPosError << \",\" << rbpfTestPosError << \"), total vel error (Kal, Rbpf): (\" << kalmanTestVelError << \",\" << rbpfTestVelError << \")\" << endl;\n\t\t\t} else if (_mode == KALMAN) {\n\t\t\t\tkalmanUpdate(dtime);\n\t\t\t} else if (_mode == ABG) {\n\t\t\t\tabgUpdate(dtime);\n\t\t\t} else if (_mode == RBPF) {\n\t\t\t\trbpfUpdate(dtime);\n\t\t\t}\n\t\t\tprevObservedPos = observedPos;\n\t\t}\n\t} else {\n\t\t\/\/ Ball moved too far to possibly be a valid track, so just extrapolate from the last known state\n\t\tif (dtime)\n\t\t{\n\t\t\tif(_mode == MODELTESTS){\n\t\t\t\tcout << \"Ball Model Tests: missed too many frames, extrapolating.\" << endl;\n\t\t\t}\n\t\t\tpos += vel * dtime + accel * 0.5f * dtime * dtime;\n\t\t}\n\n\t\t++missedFrames;\n\t}\n\tbestError = -1;\n\t*\/\n}\n<|endoftext|>"} {"text":"<commit_before>#pragma once\n\n\n#include <QtWidgets\/QWidget>\n\n#include \"PortType.hpp\"\n#include \"NodeData.hpp\"\n#include \"Serializable.hpp\"\n#include \"NodeGeometry.hpp\"\n#include \"NodeStyle.hpp\"\n#include \"NodePainterDelegate.hpp\"\n#include \"Export.hpp\"\n#include \"memory.hpp\"\n\nnamespace QtNodes\n{\n\nenum class NodeValidationState\n{\n Valid,\n Warning,\n Error\n};\n\nclass Connection;\n\nclass StyleCollection;\n\nclass NODE_EDITOR_PUBLIC NodeDataModel\n : public QObject\n , public Serializable\n{\n Q_OBJECT\n\npublic:\n\n NodeDataModel();\n\n virtual\n ~NodeDataModel() = default;\n\n \/\/\/ Caption is used in GUI\n virtual QString\n caption() const = 0;\n\n \/\/\/ It is possible to hide caption in GUI\n virtual bool\n captionVisible() const { return true; }\n\n \/\/\/ Port caption is used in GUI to label individual ports\n virtual QString\n portCaption(PortType, PortIndex) const { return QString(); }\n\n \/\/\/ It is possible to hide port caption in GUI\n virtual bool\n portCaptionVisible(PortType, PortIndex) const { return false; }\n\n \/\/\/ Name makes this model unique\n virtual QString\n name() const = 0;\n\npublic:\n\n QJsonObject\n save() const override;\n\npublic:\n\n virtual\n unsigned int nPorts(PortType portType) const = 0;\n\n virtual\n NodeDataType dataType(PortType portType, PortIndex portIndex) const = 0;\n\npublic:\n\n enum class ConnectionPolicy\n {\n One,\n Many,\n };\n\n virtual\n ConnectionPolicy\n portOutConnectionPolicy(PortIndex) const\n {\n return ConnectionPolicy::Many;\n }\n\n virtual\n ConnectionPolicy\n portInConnectionPolicy(PortIndex) const\n {\n return ConnectionPolicy::One;\n }\n\n NodeStyle const&\n nodeStyle() const;\n\n void\n setNodeStyle(NodeStyle const& style);\n\npublic:\n\n \/\/\/ Triggers the algorithm\n virtual\n void\n setInData(std::shared_ptr<NodeData> nodeData,\n PortIndex port) = 0;\n\n \/\/ Use this if portInConnectionPolicy returns ConnectionPolicy::Many\n virtual\n void\n setInData(std::shared_ptr<NodeData> nodeData,\n PortIndex port,\n const QUuid& connectionId)\n {\n Q_UNUSED(connectionId);\n setInData(nodeData, port);\n }\n\n virtual\n std::shared_ptr<NodeData>\n outData(PortIndex port) = 0;\n\n \/**\n * It is recommented to preform a lazy initialization for the\n * embedded widget and create it inside this function, not in the\n * constructor of the current model.\n *\n * Our Model Registry is able to shortly instantiate models in order\n * to call the non-static `Model::name()`. If the embedded widget is\n * allocated in the constructor but not actually embedded into some\n * QGraphicsProxyWidget, we'll gonna have a dangling pointer.\n *\/\n virtual\n QWidget *\n embeddedWidget() = 0;\n\n virtual\n bool\n resizable() const { return false; }\n\n virtual\n NodeValidationState\n validationState() const { return NodeValidationState::Valid; }\n\n virtual\n QString\n validationMessage() const { return QString(\"\"); }\n\n virtual\n NodePainterDelegate* painterDelegate() const { return nullptr; }\n\npublic Q_SLOTS:\n\n virtual void\n inputConnectionCreated(Connection const&)\n {\n }\n\n virtual void\n inputConnectionDeleted(Connection const&)\n {\n }\n\n virtual void\n outputConnectionCreated(Connection const&)\n {\n }\n\n virtual void\n outputConnectionDeleted(Connection const&)\n {\n }\n\nQ_SIGNALS:\n\n \/\/\/ Triggers the updates in the nodes downstream.\n void\n dataUpdated(PortIndex index);\n\n \/\/\/ Triggers the propagation of the empty data downstream.\n void\n dataInvalidated(PortIndex index);\n\n void\n computingStarted();\n\n void\n computingFinished();\n\n void embeddedWidgetSizeUpdated();\n\nprivate:\n\n NodeStyle _nodeStyle;\n};\n}\n<commit_msg>Add forward declaration in NodeDataModel.hpp (#323)<commit_after>#pragma once\n\n\n#include <QtWidgets\/QWidget>\n\n#include \"PortType.hpp\"\n#include \"NodeData.hpp\"\n#include \"Serializable.hpp\"\n#include \"NodeGeometry.hpp\"\n#include \"NodeStyle.hpp\"\n#include \"NodePainterDelegate.hpp\"\n#include \"Export.hpp\"\n#include \"memory.hpp\"\n\nnamespace QtNodes\n{\n\nclass NodePainterDelegate;\n\nenum class NodeValidationState\n{\n Valid,\n Warning,\n Error\n};\n\nclass Connection;\n\nclass StyleCollection;\n\nclass NODE_EDITOR_PUBLIC NodeDataModel\n : public QObject\n , public Serializable\n{\n Q_OBJECT\n\npublic:\n\n NodeDataModel();\n\n virtual\n ~NodeDataModel() = default;\n\n \/\/\/ Caption is used in GUI\n virtual QString\n caption() const = 0;\n\n \/\/\/ It is possible to hide caption in GUI\n virtual bool\n captionVisible() const { return true; }\n\n \/\/\/ Port caption is used in GUI to label individual ports\n virtual QString\n portCaption(PortType, PortIndex) const { return QString(); }\n\n \/\/\/ It is possible to hide port caption in GUI\n virtual bool\n portCaptionVisible(PortType, PortIndex) const { return false; }\n\n \/\/\/ Name makes this model unique\n virtual QString\n name() const = 0;\n\npublic:\n\n QJsonObject\n save() const override;\n\npublic:\n\n virtual\n unsigned int nPorts(PortType portType) const = 0;\n\n virtual\n NodeDataType dataType(PortType portType, PortIndex portIndex) const = 0;\n\npublic:\n\n enum class ConnectionPolicy\n {\n One,\n Many,\n };\n\n virtual\n ConnectionPolicy\n portOutConnectionPolicy(PortIndex) const\n {\n return ConnectionPolicy::Many;\n }\n\n virtual\n ConnectionPolicy\n portInConnectionPolicy(PortIndex) const\n {\n return ConnectionPolicy::One;\n }\n\n NodeStyle const&\n nodeStyle() const;\n\n void\n setNodeStyle(NodeStyle const& style);\n\npublic:\n\n \/\/\/ Triggers the algorithm\n virtual\n void\n setInData(std::shared_ptr<NodeData> nodeData,\n PortIndex port) = 0;\n\n \/\/ Use this if portInConnectionPolicy returns ConnectionPolicy::Many\n virtual\n void\n setInData(std::shared_ptr<NodeData> nodeData,\n PortIndex port,\n const QUuid& connectionId)\n {\n Q_UNUSED(connectionId);\n setInData(nodeData, port);\n }\n\n virtual\n std::shared_ptr<NodeData>\n outData(PortIndex port) = 0;\n\n \/**\n * It is recommented to preform a lazy initialization for the\n * embedded widget and create it inside this function, not in the\n * constructor of the current model.\n *\n * Our Model Registry is able to shortly instantiate models in order\n * to call the non-static `Model::name()`. If the embedded widget is\n * allocated in the constructor but not actually embedded into some\n * QGraphicsProxyWidget, we'll gonna have a dangling pointer.\n *\/\n virtual\n QWidget *\n embeddedWidget() = 0;\n\n virtual\n bool\n resizable() const { return false; }\n\n virtual\n NodeValidationState\n validationState() const { return NodeValidationState::Valid; }\n\n virtual\n QString\n validationMessage() const { return QString(\"\"); }\n\n virtual\n NodePainterDelegate* painterDelegate() const { return nullptr; }\n\npublic Q_SLOTS:\n\n virtual void\n inputConnectionCreated(Connection const&)\n {\n }\n\n virtual void\n inputConnectionDeleted(Connection const&)\n {\n }\n\n virtual void\n outputConnectionCreated(Connection const&)\n {\n }\n\n virtual void\n outputConnectionDeleted(Connection const&)\n {\n }\n\nQ_SIGNALS:\n\n \/\/\/ Triggers the updates in the nodes downstream.\n void\n dataUpdated(PortIndex index);\n\n \/\/\/ Triggers the propagation of the empty data downstream.\n void\n dataInvalidated(PortIndex index);\n\n void\n computingStarted();\n\n void\n computingFinished();\n\n void embeddedWidgetSizeUpdated();\n\nprivate:\n\n NodeStyle _nodeStyle;\n};\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\nCopyright (C) 2007 <SWGEmu>\n\nThis File is part of Core3.\n\nThis program is free software; you can redistribute\nit and\/or modify it under the terms of the GNU Lesser\nGeneral Public License as published by the Free Software\nFoundation; either version 2 of the License,\nor (at your option) any later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\nSee the GNU Lesser General Public License for\nmore details.\n\nYou should have received a copy of the GNU Lesser General\nPublic License along with this program; if not, write to\nthe Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n\nLinking Engine3 statically or dynamically with other modules\nis making a combined work based on Engine3.\nThus, the terms and conditions of the GNU Lesser General Public License\ncover the whole combination.\n\nIn addition, as a special exception, the copyright holders of Engine3\ngive you permission to combine Engine3 program with free software\nprograms or libraries that are released under the GNU LGPL and with\ncode included in the standard release of Core3 under the GNU LGPL\nlicense (or modified versions of such code, with unchanged license).\nYou may copy and distribute such a system following the terms of the\nGNU LGPL for Engine3 and the licenses of the other code concerned,\nprovided that you include the source code of that other code when\nand as the GNU LGPL requires distribution of source code.\n\nNote that people who make modified versions of Engine3 are not obligated\nto grant this special exception for their modified versions;\nit is their choice whether to do so. The GNU Lesser General Public License\ngives permission to release a modified version without this exception;\nthis exception also makes it possible to release a modified version\nwhich carries forward this exception.\n*\/\n\n#include \"DeliverMissionScreenHandler.h\"\n#include \"server\/zone\/objects\/mission\/DeliverMissionObjective.h\"\n#include \"server\/zone\/managers\/mission\/spawnmaps\/NpcSpawnPoint.h\"\n\nconst String DeliverMissionScreenHandler::STARTSCREENHANDLERID = \"convoscreenstart\";\n\nMissionObject* DeliverMissionScreenHandler::getRelevantMissionObject(CreatureObject* player, CreatureObject* npc) {\n\tif (player == NULL || npc == NULL) {\n\t\treturn NULL;\n\t}\n\n\tSceneObject* datapad = player->getSlottedObject(\"datapad\");\n\n\tif (datapad == NULL) {\n\t\treturn NULL;\n\t}\n\n\tint datapadSize = datapad->getContainerObjectsSize();\n\n\tfor (int i = 0; i < datapadSize; ++i) {\n\t\tif (datapad->getContainerObject(i)->isMissionObject()) {\n\t\t\tMissionObject* mission = cast<MissionObject*>(datapad->getContainerObject(i));\n\n\t\t\tif (mission != NULL && mission->getTypeCRC() == MissionObject::DELIVER) {\n\t\t\t\tDeliverMissionObjective* objective = cast<DeliverMissionObjective*>(mission->getMissionObjective());\n\t\t\t\tif (objective != NULL) {\n\t\t\t\t\t\/\/Check if it is target or destination NPC\n\t\t\t\t\tif (isTargetNpc(objective, npc->getPosition()) ||\n\t\t\t\t\t\t\tisDestinationNpc(objective, npc->getPosition())) {\n\t\t\t\t\t\treturn mission;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/No relevant mission found.\n\treturn NULL;\n}\n\nbool DeliverMissionScreenHandler::isTargetNpc(DeliverMissionObjective* objective, const Vector3& npcPosition) {\n\treturn isSameSpawnPoint(objective->getTargetSpawnPoint()->getPosition()->getX(), objective->getTargetSpawnPoint()->getPosition()->getY(), npcPosition);\n}\n\nbool DeliverMissionScreenHandler::isDestinationNpc(DeliverMissionObjective* objective, const Vector3& npcPosition) {\n\treturn isSameSpawnPoint(objective->getDestinationSpawnPoint()->getPosition()->getX(), objective->getDestinationSpawnPoint()->getPosition()->getY(), npcPosition);\n}\n\nbool DeliverMissionScreenHandler::isSameSpawnPoint(const float& positionX, const float& positionY, const Vector3& comparisonPosition) {\n\tif (positionX == comparisonPosition.getX() &&\n\t\t\tpositionY == comparisonPosition.getY()) {\n\t\t\/\/Spawn point is the same.\n\t\treturn true;\n\t}\n\treturn false;\n}\n\nConversationScreen* DeliverMissionScreenHandler::handleScreen(CreatureObject* conversingPlayer, CreatureObject* conversingNPC, int selectedOption, ConversationScreen* conversationScreen) {\n\t\/\/Get relevant mission object if it exists.\n\tMissionObject* mission = getRelevantMissionObject(conversingPlayer, conversingNPC);\n\n\tif (mission == NULL) {\n\t\t\/\/NPC is not related to any mission for this player.\n\t\tint randomAnswer = System::random(4);\n\t\tconversationScreen->setDialogText(\"@mission\/mission_generic:deliver_incorrect_player_\" + String::valueOf(randomAnswer));\n\t} else {\n\t\t\/\/NPC is related to a mission for this player.\n\t\tDeliverMissionObjective* objective = cast<DeliverMissionObjective*>(mission->getMissionObjective());\n\t\tif (objective != NULL) {\n\t\t\t\/\/Run mission logic.\n\n\t\t\tString text;\n\t\t\tif (isTargetNpc(objective, conversingNPC->getPosition())) {\n\t\t\t\t\/\/Target NPC.\n\t\t\t\tif (objective->getObjectiveStatus() == DeliverMissionObjective::INITSTATUS) {\n\t\t\t\t\tobjective->updateMissionStatus(conversingPlayer);\n\t\t\t\t\tswitch (mission->getFaction()) {\n\t\t\t\t\tcase MissionObject::FACTIONIMPERIAL:\n\t\t\t\t\t\tconversationScreen->setDialogText(\"@mission\/mission_deliver_imperial_easy:m\" + String::valueOf(mission->getMissionNumber()) + \"p\");\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase MissionObject::FACTIONREBEL:\n\t\t\t\t\t\tconversationScreen->setDialogText(\"@mission\/mission_deliver_rebel_easy:m\" + String::valueOf(mission->getMissionNumber()) + \"p\");\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tdefault:\n\t\t\t\t\t\tconversationScreen->setDialogText(\"@mission\/mission_deliver_neutral_easy:m\" + String::valueOf(mission->getMissionNumber()) + \"p\");\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\ttext = \"@mission\/mission_generic:deliver_already_picked_up\";\n\t\t\t\t\tconversationScreen->setDialogText(text);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t\/\/Destination NPC.\n\t\t\t\tif (objective->getObjectiveStatus() == DeliverMissionObjective::PICKEDUPSTATUS) {\n\t\t\t\t\tobjective->updateMissionStatus(conversingPlayer);\n\t\t\t\t\tswitch (mission->getFaction()) {\n\t\t\t\t\tcase MissionObject::FACTIONIMPERIAL:\n\t\t\t\t\t\tconversationScreen->setDialogText(\"@mission\/mission_deliver_imperial_easy:m\" + String::valueOf(mission->getMissionNumber()) + \"r\");\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase MissionObject::FACTIONREBEL:\n\t\t\t\t\t\tconversationScreen->setDialogText(\"@mission\/mission_deliver_rebel_easy:m\" + String::valueOf(mission->getMissionNumber()) + \"r\");\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tdefault:\n\t\t\t\t\t\tconversationScreen->setDialogText(\"@mission\/mission_deliver_neutral_easy:m\" + String::valueOf(mission->getMissionNumber()) + \"r\");\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t} else if (objective->getObjectiveStatus() == DeliverMissionObjective::INITSTATUS) {\n\t\t\t\t\ttext = \"@mission\/mission_generic:give_item\";\n\t\t\t\t\tconversationScreen->setDialogText(text);\n\t\t\t\t} else {\n\t\t\t\t\ttext = \"@mission\/mission_generic:deliver_already_dropped_off\";\n\t\t\t\t\tconversationScreen->setDialogText(text);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn conversationScreen;\n}\n<commit_msg>[fixed] Delivery missions: end NPC will tell you to give him\/her an item if you deleted\/removed the item you should give him\/her from your inventory.<commit_after>\/*\nCopyright (C) 2007 <SWGEmu>\n\nThis File is part of Core3.\n\nThis program is free software; you can redistribute\nit and\/or modify it under the terms of the GNU Lesser\nGeneral Public License as published by the Free Software\nFoundation; either version 2 of the License,\nor (at your option) any later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\nSee the GNU Lesser General Public License for\nmore details.\n\nYou should have received a copy of the GNU Lesser General\nPublic License along with this program; if not, write to\nthe Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n\nLinking Engine3 statically or dynamically with other modules\nis making a combined work based on Engine3.\nThus, the terms and conditions of the GNU Lesser General Public License\ncover the whole combination.\n\nIn addition, as a special exception, the copyright holders of Engine3\ngive you permission to combine Engine3 program with free software\nprograms or libraries that are released under the GNU LGPL and with\ncode included in the standard release of Core3 under the GNU LGPL\nlicense (or modified versions of such code, with unchanged license).\nYou may copy and distribute such a system following the terms of the\nGNU LGPL for Engine3 and the licenses of the other code concerned,\nprovided that you include the source code of that other code when\nand as the GNU LGPL requires distribution of source code.\n\nNote that people who make modified versions of Engine3 are not obligated\nto grant this special exception for their modified versions;\nit is their choice whether to do so. The GNU Lesser General Public License\ngives permission to release a modified version without this exception;\nthis exception also makes it possible to release a modified version\nwhich carries forward this exception.\n*\/\n\n#include \"DeliverMissionScreenHandler.h\"\n#include \"server\/zone\/objects\/mission\/DeliverMissionObjective.h\"\n#include \"server\/zone\/managers\/mission\/spawnmaps\/NpcSpawnPoint.h\"\n\nconst String DeliverMissionScreenHandler::STARTSCREENHANDLERID = \"convoscreenstart\";\n\nMissionObject* DeliverMissionScreenHandler::getRelevantMissionObject(CreatureObject* player, CreatureObject* npc) {\n\tif (player == NULL || npc == NULL) {\n\t\treturn NULL;\n\t}\n\n\tSceneObject* datapad = player->getSlottedObject(\"datapad\");\n\n\tif (datapad == NULL) {\n\t\treturn NULL;\n\t}\n\n\tint datapadSize = datapad->getContainerObjectsSize();\n\n\tfor (int i = 0; i < datapadSize; ++i) {\n\t\tif (datapad->getContainerObject(i)->isMissionObject()) {\n\t\t\tMissionObject* mission = cast<MissionObject*>(datapad->getContainerObject(i));\n\n\t\t\tif (mission != NULL && mission->getTypeCRC() == MissionObject::DELIVER) {\n\t\t\t\tDeliverMissionObjective* objective = cast<DeliverMissionObjective*>(mission->getMissionObjective());\n\t\t\t\tif (objective != NULL) {\n\t\t\t\t\t\/\/Check if it is target or destination NPC\n\t\t\t\t\tif (isTargetNpc(objective, npc->getPosition()) ||\n\t\t\t\t\t\t\tisDestinationNpc(objective, npc->getPosition())) {\n\t\t\t\t\t\treturn mission;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/No relevant mission found.\n\treturn NULL;\n}\n\nbool DeliverMissionScreenHandler::isTargetNpc(DeliverMissionObjective* objective, const Vector3& npcPosition) {\n\treturn isSameSpawnPoint(objective->getTargetSpawnPoint()->getPosition()->getX(), objective->getTargetSpawnPoint()->getPosition()->getY(), npcPosition);\n}\n\nbool DeliverMissionScreenHandler::isDestinationNpc(DeliverMissionObjective* objective, const Vector3& npcPosition) {\n\treturn isSameSpawnPoint(objective->getDestinationSpawnPoint()->getPosition()->getX(), objective->getDestinationSpawnPoint()->getPosition()->getY(), npcPosition);\n}\n\nbool DeliverMissionScreenHandler::isSameSpawnPoint(const float& positionX, const float& positionY, const Vector3& comparisonPosition) {\n\tif (positionX == comparisonPosition.getX() &&\n\t\t\tpositionY == comparisonPosition.getY()) {\n\t\t\/\/Spawn point is the same.\n\t\treturn true;\n\t}\n\treturn false;\n}\n\nConversationScreen* DeliverMissionScreenHandler::handleScreen(CreatureObject* conversingPlayer, CreatureObject* conversingNPC, int selectedOption, ConversationScreen* conversationScreen) {\n\t\/\/Get relevant mission object if it exists.\n\tMissionObject* mission = getRelevantMissionObject(conversingPlayer, conversingNPC);\n\n\tif (mission == NULL) {\n\t\t\/\/NPC is not related to any mission for this player.\n\t\tint randomAnswer = System::random(4);\n\t\tconversationScreen->setDialogText(\"@mission\/mission_generic:deliver_incorrect_player_\" + String::valueOf(randomAnswer));\n\t} else {\n\t\t\/\/NPC is related to a mission for this player.\n\t\tDeliverMissionObjective* objective = cast<DeliverMissionObjective*>(mission->getMissionObjective());\n\t\tif (objective != NULL) {\n\t\t\t\/\/Run mission logic.\n\n\t\t\tString text;\n\t\t\tif (isTargetNpc(objective, conversingNPC->getPosition())) {\n\t\t\t\t\/\/Target NPC.\n\t\t\t\tif (objective->getObjectiveStatus() == DeliverMissionObjective::INITSTATUS) {\n\t\t\t\t\tobjective->updateMissionStatus(conversingPlayer);\n\t\t\t\t\tswitch (mission->getFaction()) {\n\t\t\t\t\tcase MissionObject::FACTIONIMPERIAL:\n\t\t\t\t\t\tconversationScreen->setDialogText(\"@mission\/mission_deliver_imperial_easy:m\" + String::valueOf(mission->getMissionNumber()) + \"p\");\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase MissionObject::FACTIONREBEL:\n\t\t\t\t\t\tconversationScreen->setDialogText(\"@mission\/mission_deliver_rebel_easy:m\" + String::valueOf(mission->getMissionNumber()) + \"p\");\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tdefault:\n\t\t\t\t\t\tconversationScreen->setDialogText(\"@mission\/mission_deliver_neutral_easy:m\" + String::valueOf(mission->getMissionNumber()) + \"p\");\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\ttext = \"@mission\/mission_generic:deliver_already_picked_up\";\n\t\t\t\t\tconversationScreen->setDialogText(text);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t\/\/Destination NPC.\n\t\t\t\tif (objective->getObjectiveStatus() == DeliverMissionObjective::PICKEDUPSTATUS) {\n\t\t\t\t\tobjective->updateMissionStatus(conversingPlayer);\n\t\t\t\t\tif (objective->getObjectiveStatus() == DeliverMissionObjective::DELIVEREDSTATUS) {\n\t\t\t\t\t\tswitch (mission->getFaction()) {\n\t\t\t\t\t\tcase MissionObject::FACTIONIMPERIAL:\n\t\t\t\t\t\t\tconversationScreen->setDialogText(\"@mission\/mission_deliver_imperial_easy:m\" + String::valueOf(mission->getMissionNumber()) + \"r\");\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase MissionObject::FACTIONREBEL:\n\t\t\t\t\t\t\tconversationScreen->setDialogText(\"@mission\/mission_deliver_rebel_easy:m\" + String::valueOf(mission->getMissionNumber()) + \"r\");\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\tconversationScreen->setDialogText(\"@mission\/mission_deliver_neutral_easy:m\" + String::valueOf(mission->getMissionNumber()) + \"r\");\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\ttext = \"@mission\/mission_generic:give_item\";\n\t\t\t\t\t\tconversationScreen->setDialogText(text);\n\t\t\t\t\t}\n\t\t\t\t} else if (objective->getObjectiveStatus() == DeliverMissionObjective::INITSTATUS) {\n\t\t\t\t\ttext = \"@mission\/mission_generic:give_item\";\n\t\t\t\t\tconversationScreen->setDialogText(text);\n\t\t\t\t} else {\n\t\t\t\t\ttext = \"@mission\/mission_generic:deliver_already_dropped_off\";\n\t\t\t\t\tconversationScreen->setDialogText(text);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn conversationScreen;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/------------------------------------------------------------------------------\n\/\/ CLING - the C++ LLVM-based InterpreterG :)\n\/\/ author: Vassil Vassilev <vvasilev@cern.ch>\n\/\/\n\/\/ This file is dual-licensed: you can choose to license it under the University\n\/\/ of Illinois Open Source License or the GNU Lesser General Public License. See\n\/\/ LICENSE.TXT for details.\n\/\/------------------------------------------------------------------------------\n\n#include \"BackendPasses.h\"\n\n#include \"IncrementalJIT.h\"\n\n#include \"llvm\/Analysis\/InlineCost.h\"\n#include \"llvm\/Analysis\/TargetLibraryInfo.h\"\n#include \"llvm\/Analysis\/TargetTransformInfo.h\"\n#include \"llvm\/IR\/LegacyPassManager.h\"\n#include \"llvm\/IR\/Module.h\"\n#include \"llvm\/IR\/Verifier.h\"\n#include \"llvm\/Target\/TargetMachine.h\"\n#include \"llvm\/Transforms\/IPO.h\"\n#include \"llvm\/Transforms\/IPO\/AlwaysInliner.h\"\n#include \"llvm\/Transforms\/IPO\/Inliner.h\"\n#include \"llvm\/Transforms\/IPO\/PassManagerBuilder.h\"\n#include \"llvm\/Transforms\/Scalar.h\"\n#include \"llvm\/Transforms\/Utils.h\"\n\n\/\/#include \"clang\/Basic\/LangOptions.h\"\n\/\/#include \"clang\/Basic\/TargetOptions.h\"\n#include \"clang\/Basic\/CharInfo.h\"\n#include \"clang\/Basic\/CodeGenOptions.h\"\n\nusing namespace cling;\nusing namespace clang;\nusing namespace llvm;\nusing namespace llvm::legacy;\n\nnamespace {\n class KeepLocalGVPass: public ModulePass {\n static char ID;\n\n bool runOnGlobal(GlobalValue& GV) {\n if (GV.isDeclaration())\n return false; \/\/ no change.\n\n \/\/ GV is a definition.\n\n llvm::GlobalValue::LinkageTypes LT = GV.getLinkage();\n if (!GV.isDiscardableIfUnused(LT))\n return false;\n\n if (LT == llvm::GlobalValue::InternalLinkage\n || LT == llvm::GlobalValue::PrivateLinkage) {\n GV.setLinkage(llvm::GlobalValue::ExternalLinkage);\n return true; \/\/ a change!\n }\n return false;\n }\n\n public:\n KeepLocalGVPass() : ModulePass(ID) {}\n\n bool runOnModule(Module &M) override {\n bool ret = false;\n for (auto &&F: M)\n ret |= runOnGlobal(F);\n for (auto &&G: M.globals())\n ret |= runOnGlobal(G);\n return ret;\n }\n };\n}\n\nchar KeepLocalGVPass::ID = 0;\n\nnamespace {\n\n \/\/ Add a suffix to the CUDA module ctor\/dtor to generate a unique name.\n \/\/ This is necessary for lazy compilation. Without suffix, cling cannot\n \/\/ distinguish ctor\/dtor of subsequent modules.\n class UniqueCUDAStructorName : public ModulePass {\n static char ID;\n\n bool runOnFunction(Function& F, const StringRef ModuleName){\n if(F.hasName() && (F.getName() == \"__cuda_module_ctor\"\n || F.getName() == \"__cuda_module_dtor\") ){\n llvm::SmallString<128> NewFunctionName;\n NewFunctionName.append(F.getName());\n NewFunctionName.append(\"_\");\n NewFunctionName.append(ModuleName);\n\n for (size_t i = 0; i < NewFunctionName.size(); ++i) {\n \/\/ Replace everything that is not [a-zA-Z0-9._] with a _. This set\n \/\/ happens to be the set of C preprocessing numbers.\n if (!isPreprocessingNumberBody(NewFunctionName[i]))\n NewFunctionName[i] = '_';\n }\n\n F.setName(NewFunctionName);\n\n return true;\n }\n\n return false;\n }\n\n public:\n UniqueCUDAStructorName() : ModulePass(ID) {}\n\n bool runOnModule(Module &M) override {\n bool ret = false;\n const StringRef ModuleName = M.getName();\n for (auto &&F: M)\n ret |= runOnFunction(F, ModuleName);\n return ret;\n }\n };\n}\n\nchar UniqueCUDAStructorName::ID = 0;\n\n\nnamespace {\n\n \/\/ Replace definitions of weak symbols for which symbols already exist by\n \/\/ declarations. This reduces the amount of emitted symbols.\n class ReuseExistingWeakSymbols : public ModulePass {\n static char ID;\n cling::IncrementalJIT& m_JIT;\n\n bool runOnGlobal(GlobalValue& GV) {\n if (GV.isDeclaration())\n return false; \/\/ no change.\n\n \/\/ GV is a definition.\n\n llvm::GlobalValue::LinkageTypes LT = GV.getLinkage();\n if (!GV.isDiscardableIfUnused(LT) || !GV.isWeakForLinker(LT))\n return false;\n\n \/\/ Find the symbol in JIT or shared libraries.\n if (m_JIT.getSymbolAddress(GV.getName(), \/*AlsoInProcess*\/ true)) {\n if (auto *Var = dyn_cast<GlobalVariable>(&GV)) {\n Var->setInitializer(nullptr); \/\/ make this a declaration\n } else if (auto *Func = dyn_cast<Function>(&GV)) {\n Func->deleteBody(); \/\/ make this a declaration\n } else {\n llvm_unreachable(\"What is this?\");\n }\n return true; \/\/ a change!\n }\n return false;\n }\n\n public:\n ReuseExistingWeakSymbols(cling::IncrementalJIT& JIT) :\n ModulePass(ID), m_JIT(JIT) {}\n\n bool runOnModule(Module &M) override {\n bool ret = false;\n for (auto &&F: M)\n ret |= runOnGlobal(F);\n for (auto &&G: M.globals())\n ret |= runOnGlobal(G);\n return ret;\n }\n };\n}\n\nchar ReuseExistingWeakSymbols::ID = 0;\n\n\nBackendPasses::BackendPasses(const clang::CodeGenOptions &CGOpts,\n const clang::TargetOptions & \/*TOpts*\/,\n const clang::LangOptions & \/*LOpts*\/,\n llvm::TargetMachine& TM,\n cling::IncrementalJIT& JIT):\n m_TM(TM),\n m_CGOpts(CGOpts),\n \/\/m_TOpts(TOpts),\n \/\/m_LOpts(LOpts)\n m_JIT(JIT)\n{}\n\n\nBackendPasses::~BackendPasses() {\n \/\/delete m_PMBuilder->Inliner;\n}\n\nvoid BackendPasses::CreatePasses(llvm::Module& M, int OptLevel)\n{\n \/\/ From BackEndUtil's clang::EmitAssemblyHelper::CreatePasses().\n\n#if 0\n CodeGenOptions::InliningMethod Inlining = m_CGOpts.getInlining();\n CodeGenOptions& CGOpts_ = const_cast<CodeGenOptions&>(m_CGOpts);\n \/\/ DON'T: we will not find our symbols...\n \/\/CGOpts_.CXXCtorDtorAliases = 1;\n\n \/\/ Default clang -O2 on Linux 64bit also has the following, but see\n \/\/ CIFactory.cpp.\n CGOpts_.DisableFPElim = 0;\n CGOpts_.DiscardValueNames = 1;\n CGOpts_.OmitLeafFramePointer = 1;\n CGOpts_.OptimizationLevel = 2;\n CGOpts_.RelaxAll = 0;\n CGOpts_.UnrollLoops = 1;\n CGOpts_.VectorizeLoop = 1;\n CGOpts_.VectorizeSLP = 1;\n#endif\n\n#if 0 \/\/ def __GNUC__\n \/\/ Better inlining is pending https:\/\/bugs.llvm.org\/\/show_bug.cgi?id=19668\n \/\/ and its consequence https:\/\/sft.its.cern.ch\/jira\/browse\/ROOT-7111\n \/\/ shown e.g. by roottest\/cling\/stl\/map\/badstringMap\n if (Inlining > CodeGenOptions::NormalInlining)\n Inlining = CodeGenOptions::NormalInlining;\n#endif\n\n \/\/ Handle disabling of LLVM optimization, where we want to preserve the\n \/\/ internal module before any optimization.\n if (m_CGOpts.DisableLLVMPasses) {\n OptLevel = 0;\n \/\/ Always keep at least ForceInline - NoInlining is deadly for libc++.\n \/\/ Inlining = CGOpts.NoInlining;\n }\n\n llvm::PassManagerBuilder PMBuilder;\n PMBuilder.OptLevel = OptLevel;\n PMBuilder.SizeLevel = m_CGOpts.OptimizeSize;\n PMBuilder.SLPVectorize = OptLevel > 1 ? 1 : 0; \/\/ m_CGOpts.VectorizeSLP\n PMBuilder.LoopVectorize = OptLevel > 1 ? 1 : 0; \/\/ m_CGOpts.VectorizeLoop\n\n PMBuilder.DisableTailCalls = m_CGOpts.DisableTailCalls;\n PMBuilder.DisableUnrollLoops = !m_CGOpts.UnrollLoops;\n PMBuilder.MergeFunctions = m_CGOpts.MergeFunctions;\n PMBuilder.RerollLoops = m_CGOpts.RerollLoops;\n\n PMBuilder.LibraryInfo = new TargetLibraryInfoImpl(m_TM.getTargetTriple());\n\n \/\/ At O0 and O1 we only run the always inliner which is more efficient. At\n \/\/ higher optimization levels we run the normal inliner.\n \/\/ See also call to `CGOpts.setInlining()` in CIFactory!\n if (PMBuilder.OptLevel <= 1) {\n bool InsertLifetimeIntrinsics = PMBuilder.OptLevel != 0;\n PMBuilder.Inliner = createAlwaysInlinerLegacyPass(InsertLifetimeIntrinsics);\n } else {\n PMBuilder.Inliner = createFunctionInliningPass(OptLevel,\n PMBuilder.SizeLevel,\n (!m_CGOpts.SampleProfileFile.empty() && m_CGOpts.PrepareForThinLTO));\n }\n\n \/\/ Set up the per-module pass manager.\n m_MPM[OptLevel].reset(new legacy::PassManager());\n\n m_MPM[OptLevel]->add(new KeepLocalGVPass());\n m_MPM[OptLevel]->add(new ReuseExistingWeakSymbols(m_JIT));\n\n \/\/ The function __cuda_module_ctor and __cuda_module_dtor will just generated,\n \/\/ if a CUDA fatbinary file exist. Without file path there is no need for the\n \/\/ function pass.\n if(!m_CGOpts.CudaGpuBinaryFileName.empty())\n m_MPM[OptLevel]->add(new UniqueCUDAStructorName());\n m_MPM[OptLevel]->add(createTargetTransformInfoWrapperPass(\n m_TM.getTargetIRAnalysis()));\n\n m_TM.adjustPassManager(PMBuilder);\n\n PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible,\n [&](const PassManagerBuilder &,\n legacy::PassManagerBase &PM) {\n PM.add(createAddDiscriminatorsPass());\n });\n\n \/\/if (!CGOpts.RewriteMapFiles.empty())\n \/\/ addSymbolRewriterPass(CGOpts, m_MPM);\n\n PMBuilder.populateModulePassManager(*m_MPM[OptLevel]);\n\n m_FPM[OptLevel].reset(new legacy::FunctionPassManager(&M));\n m_FPM[OptLevel]->add(createTargetTransformInfoWrapperPass(\n m_TM.getTargetIRAnalysis()));\n if (m_CGOpts.VerifyModule)\n m_FPM[OptLevel]->add(createVerifierPass());\n PMBuilder.populateFunctionPassManager(*m_FPM[OptLevel]);\n}\n\nvoid BackendPasses::runOnModule(Module& M, int OptLevel) {\n\n if (OptLevel < 0)\n OptLevel = 0;\n if (OptLevel > 3)\n OptLevel = 3;\n\n if (!m_MPM[OptLevel])\n CreatePasses(M, OptLevel);\n\n static constexpr std::array<llvm::CodeGenOpt::Level, 4> CGOptLevel {{\n llvm::CodeGenOpt::None,\n llvm::CodeGenOpt::Less,\n llvm::CodeGenOpt::Default,\n llvm::CodeGenOpt::Aggressive\n }};\n \/\/ TM's OptLevel is used to build orc::SimpleCompiler passes for every Module.\n m_TM.setOptLevel(CGOptLevel[OptLevel]);\n\n \/\/ Run the per-function passes on the module.\n m_FPM[OptLevel]->doInitialization();\n for (auto&& I: M.functions())\n if (!I.isDeclaration())\n m_FPM[OptLevel]->run(I);\n m_FPM[OptLevel]->doFinalization();\n\n m_MPM[OptLevel]->run(M);\n}\n<commit_msg>Windows: always emit definitions of JITed \"weak\" variables<commit_after>\/\/------------------------------------------------------------------------------\n\/\/ CLING - the C++ LLVM-based InterpreterG :)\n\/\/ author: Vassil Vassilev <vvasilev@cern.ch>\n\/\/\n\/\/ This file is dual-licensed: you can choose to license it under the University\n\/\/ of Illinois Open Source License or the GNU Lesser General Public License. See\n\/\/ LICENSE.TXT for details.\n\/\/------------------------------------------------------------------------------\n\n#include \"BackendPasses.h\"\n\n#include \"IncrementalJIT.h\"\n\n#include \"llvm\/Analysis\/InlineCost.h\"\n#include \"llvm\/Analysis\/TargetLibraryInfo.h\"\n#include \"llvm\/Analysis\/TargetTransformInfo.h\"\n#include \"llvm\/IR\/LegacyPassManager.h\"\n#include \"llvm\/IR\/Module.h\"\n#include \"llvm\/IR\/Verifier.h\"\n#include \"llvm\/Target\/TargetMachine.h\"\n#include \"llvm\/Transforms\/IPO.h\"\n#include \"llvm\/Transforms\/IPO\/AlwaysInliner.h\"\n#include \"llvm\/Transforms\/IPO\/Inliner.h\"\n#include \"llvm\/Transforms\/IPO\/PassManagerBuilder.h\"\n#include \"llvm\/Transforms\/Scalar.h\"\n#include \"llvm\/Transforms\/Utils.h\"\n\n\/\/#include \"clang\/Basic\/LangOptions.h\"\n\/\/#include \"clang\/Basic\/TargetOptions.h\"\n#include \"clang\/Basic\/CharInfo.h\"\n#include \"clang\/Basic\/CodeGenOptions.h\"\n\nusing namespace cling;\nusing namespace clang;\nusing namespace llvm;\nusing namespace llvm::legacy;\n\nnamespace {\n class KeepLocalGVPass: public ModulePass {\n static char ID;\n\n bool runOnGlobal(GlobalValue& GV) {\n if (GV.isDeclaration())\n return false; \/\/ no change.\n\n \/\/ GV is a definition.\n\n llvm::GlobalValue::LinkageTypes LT = GV.getLinkage();\n if (!GV.isDiscardableIfUnused(LT))\n return false;\n\n if (LT == llvm::GlobalValue::InternalLinkage\n || LT == llvm::GlobalValue::PrivateLinkage) {\n GV.setLinkage(llvm::GlobalValue::ExternalLinkage);\n return true; \/\/ a change!\n }\n return false;\n }\n\n public:\n KeepLocalGVPass() : ModulePass(ID) {}\n\n bool runOnModule(Module &M) override {\n bool ret = false;\n for (auto &&F: M)\n ret |= runOnGlobal(F);\n for (auto &&G: M.globals())\n ret |= runOnGlobal(G);\n return ret;\n }\n };\n}\n\nchar KeepLocalGVPass::ID = 0;\n\nnamespace {\n\n \/\/ Add a suffix to the CUDA module ctor\/dtor to generate a unique name.\n \/\/ This is necessary for lazy compilation. Without suffix, cling cannot\n \/\/ distinguish ctor\/dtor of subsequent modules.\n class UniqueCUDAStructorName : public ModulePass {\n static char ID;\n\n bool runOnFunction(Function& F, const StringRef ModuleName){\n if(F.hasName() && (F.getName() == \"__cuda_module_ctor\"\n || F.getName() == \"__cuda_module_dtor\") ){\n llvm::SmallString<128> NewFunctionName;\n NewFunctionName.append(F.getName());\n NewFunctionName.append(\"_\");\n NewFunctionName.append(ModuleName);\n\n for (size_t i = 0; i < NewFunctionName.size(); ++i) {\n \/\/ Replace everything that is not [a-zA-Z0-9._] with a _. This set\n \/\/ happens to be the set of C preprocessing numbers.\n if (!isPreprocessingNumberBody(NewFunctionName[i]))\n NewFunctionName[i] = '_';\n }\n\n F.setName(NewFunctionName);\n\n return true;\n }\n\n return false;\n }\n\n public:\n UniqueCUDAStructorName() : ModulePass(ID) {}\n\n bool runOnModule(Module &M) override {\n bool ret = false;\n const StringRef ModuleName = M.getName();\n for (auto &&F: M)\n ret |= runOnFunction(F, ModuleName);\n return ret;\n }\n };\n}\n\nchar UniqueCUDAStructorName::ID = 0;\n\n\nnamespace {\n\n \/\/ Replace definitions of weak symbols for which symbols already exist by\n \/\/ declarations. This reduces the amount of emitted symbols.\n class ReuseExistingWeakSymbols : public ModulePass {\n static char ID;\n cling::IncrementalJIT& m_JIT;\n\n bool runOnGlobal(GlobalValue& GV) {\n if (GV.isDeclaration())\n return false; \/\/ no change.\n\n \/\/ GV is a definition.\n\n llvm::GlobalValue::LinkageTypes LT = GV.getLinkage();\n if (!GV.isDiscardableIfUnused(LT) || !GV.isWeakForLinker(LT))\n return false;\n\n \/\/ Find the symbol in JIT or shared libraries.\n if (m_JIT.getSymbolAddress(GV.getName(), \/*AlsoInProcess*\/ true)) {\n#if !defined(_WIN32)\n \/\/ Heuristically, Windows cannot handle cross-library variables; they\n \/\/ must be library-local.\n if (auto *Var = dyn_cast<GlobalVariable>(&GV)) {\n Var->setInitializer(nullptr); \/\/ make this a declaration\n } else\n#endif\n if (auto *Func = dyn_cast<Function>(&GV)) {\n Func->deleteBody(); \/\/ make this a declaration\n } else {\n llvm_unreachable(\"What is this?\");\n }\n return true; \/\/ a change!\n }\n return false;\n }\n\n public:\n ReuseExistingWeakSymbols(cling::IncrementalJIT& JIT) :\n ModulePass(ID), m_JIT(JIT) {}\n\n bool runOnModule(Module &M) override {\n bool ret = false;\n for (auto &&F: M)\n ret |= runOnGlobal(F);\n for (auto &&G: M.globals())\n ret |= runOnGlobal(G);\n return ret;\n }\n };\n}\n\nchar ReuseExistingWeakSymbols::ID = 0;\n\n\nBackendPasses::BackendPasses(const clang::CodeGenOptions &CGOpts,\n const clang::TargetOptions & \/*TOpts*\/,\n const clang::LangOptions & \/*LOpts*\/,\n llvm::TargetMachine& TM,\n cling::IncrementalJIT& JIT):\n m_TM(TM),\n m_CGOpts(CGOpts),\n \/\/m_TOpts(TOpts),\n \/\/m_LOpts(LOpts)\n m_JIT(JIT)\n{}\n\n\nBackendPasses::~BackendPasses() {\n \/\/delete m_PMBuilder->Inliner;\n}\n\nvoid BackendPasses::CreatePasses(llvm::Module& M, int OptLevel)\n{\n \/\/ From BackEndUtil's clang::EmitAssemblyHelper::CreatePasses().\n\n#if 0\n CodeGenOptions::InliningMethod Inlining = m_CGOpts.getInlining();\n CodeGenOptions& CGOpts_ = const_cast<CodeGenOptions&>(m_CGOpts);\n \/\/ DON'T: we will not find our symbols...\n \/\/CGOpts_.CXXCtorDtorAliases = 1;\n\n \/\/ Default clang -O2 on Linux 64bit also has the following, but see\n \/\/ CIFactory.cpp.\n CGOpts_.DisableFPElim = 0;\n CGOpts_.DiscardValueNames = 1;\n CGOpts_.OmitLeafFramePointer = 1;\n CGOpts_.OptimizationLevel = 2;\n CGOpts_.RelaxAll = 0;\n CGOpts_.UnrollLoops = 1;\n CGOpts_.VectorizeLoop = 1;\n CGOpts_.VectorizeSLP = 1;\n#endif\n\n#if 0 \/\/ def __GNUC__\n \/\/ Better inlining is pending https:\/\/bugs.llvm.org\/\/show_bug.cgi?id=19668\n \/\/ and its consequence https:\/\/sft.its.cern.ch\/jira\/browse\/ROOT-7111\n \/\/ shown e.g. by roottest\/cling\/stl\/map\/badstringMap\n if (Inlining > CodeGenOptions::NormalInlining)\n Inlining = CodeGenOptions::NormalInlining;\n#endif\n\n \/\/ Handle disabling of LLVM optimization, where we want to preserve the\n \/\/ internal module before any optimization.\n if (m_CGOpts.DisableLLVMPasses) {\n OptLevel = 0;\n \/\/ Always keep at least ForceInline - NoInlining is deadly for libc++.\n \/\/ Inlining = CGOpts.NoInlining;\n }\n\n llvm::PassManagerBuilder PMBuilder;\n PMBuilder.OptLevel = OptLevel;\n PMBuilder.SizeLevel = m_CGOpts.OptimizeSize;\n PMBuilder.SLPVectorize = OptLevel > 1 ? 1 : 0; \/\/ m_CGOpts.VectorizeSLP\n PMBuilder.LoopVectorize = OptLevel > 1 ? 1 : 0; \/\/ m_CGOpts.VectorizeLoop\n\n PMBuilder.DisableTailCalls = m_CGOpts.DisableTailCalls;\n PMBuilder.DisableUnrollLoops = !m_CGOpts.UnrollLoops;\n PMBuilder.MergeFunctions = m_CGOpts.MergeFunctions;\n PMBuilder.RerollLoops = m_CGOpts.RerollLoops;\n\n PMBuilder.LibraryInfo = new TargetLibraryInfoImpl(m_TM.getTargetTriple());\n\n \/\/ At O0 and O1 we only run the always inliner which is more efficient. At\n \/\/ higher optimization levels we run the normal inliner.\n \/\/ See also call to `CGOpts.setInlining()` in CIFactory!\n if (PMBuilder.OptLevel <= 1) {\n bool InsertLifetimeIntrinsics = PMBuilder.OptLevel != 0;\n PMBuilder.Inliner = createAlwaysInlinerLegacyPass(InsertLifetimeIntrinsics);\n } else {\n PMBuilder.Inliner = createFunctionInliningPass(OptLevel,\n PMBuilder.SizeLevel,\n (!m_CGOpts.SampleProfileFile.empty() && m_CGOpts.PrepareForThinLTO));\n }\n\n \/\/ Set up the per-module pass manager.\n m_MPM[OptLevel].reset(new legacy::PassManager());\n\n m_MPM[OptLevel]->add(new KeepLocalGVPass());\n m_MPM[OptLevel]->add(new ReuseExistingWeakSymbols(m_JIT));\n\n \/\/ The function __cuda_module_ctor and __cuda_module_dtor will just generated,\n \/\/ if a CUDA fatbinary file exist. Without file path there is no need for the\n \/\/ function pass.\n if(!m_CGOpts.CudaGpuBinaryFileName.empty())\n m_MPM[OptLevel]->add(new UniqueCUDAStructorName());\n m_MPM[OptLevel]->add(createTargetTransformInfoWrapperPass(\n m_TM.getTargetIRAnalysis()));\n\n m_TM.adjustPassManager(PMBuilder);\n\n PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible,\n [&](const PassManagerBuilder &,\n legacy::PassManagerBase &PM) {\n PM.add(createAddDiscriminatorsPass());\n });\n\n \/\/if (!CGOpts.RewriteMapFiles.empty())\n \/\/ addSymbolRewriterPass(CGOpts, m_MPM);\n\n PMBuilder.populateModulePassManager(*m_MPM[OptLevel]);\n\n m_FPM[OptLevel].reset(new legacy::FunctionPassManager(&M));\n m_FPM[OptLevel]->add(createTargetTransformInfoWrapperPass(\n m_TM.getTargetIRAnalysis()));\n if (m_CGOpts.VerifyModule)\n m_FPM[OptLevel]->add(createVerifierPass());\n PMBuilder.populateFunctionPassManager(*m_FPM[OptLevel]);\n}\n\nvoid BackendPasses::runOnModule(Module& M, int OptLevel) {\n\n if (OptLevel < 0)\n OptLevel = 0;\n if (OptLevel > 3)\n OptLevel = 3;\n\n if (!m_MPM[OptLevel])\n CreatePasses(M, OptLevel);\n\n static constexpr std::array<llvm::CodeGenOpt::Level, 4> CGOptLevel {{\n llvm::CodeGenOpt::None,\n llvm::CodeGenOpt::Less,\n llvm::CodeGenOpt::Default,\n llvm::CodeGenOpt::Aggressive\n }};\n \/\/ TM's OptLevel is used to build orc::SimpleCompiler passes for every Module.\n m_TM.setOptLevel(CGOptLevel[OptLevel]);\n\n \/\/ Run the per-function passes on the module.\n m_FPM[OptLevel]->doInitialization();\n for (auto&& I: M.functions())\n if (!I.isDeclaration())\n m_FPM[OptLevel]->run(I);\n m_FPM[OptLevel]->doFinalization();\n\n m_MPM[OptLevel]->run(M);\n}\n<|endoftext|>"} {"text":"<commit_before>\/******************************************************************************\n Copyright 2013 Allied Telesis Labs Ltd. All rights reserved.\n \nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n 1. Redistributions of source code must retain the above copyright notice,\n this list of conditions and the following disclaimer.\n\n 2. Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in the\n documentation and\/or other materials provided with the distribution.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\nANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\nWARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR\nANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\nLOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON\nANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\nSOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*******************************************************************************\/\n\n#include <buildsys.h>\n\nstatic char *git_hash(const char *gdir)\n{\n\tchdir(gdir);\n\tFILE *f = popen(\"git rev-parse HEAD\", \"r\");\n\tchar *Commit = (char *) calloc(41, sizeof(char));\n\tfread(Commit, sizeof(char), 40, f);\n\tchdir(WORLD->getWorkingDir()->c_str());\n\tpclose(f);\n\treturn Commit;\n}\n\nstatic char *git_diff_hash(const char *gdir)\n{\n\tchdir(gdir);\n\tFILE *f = popen(\"git diff HEAD | sha1sum\", \"r\");\n\tchar *Commit = (char *) calloc(41, sizeof(char));\n\tfread(Commit, sizeof(char), 40, f);\n\tchdir(WORLD->getWorkingDir()->c_str());\n\tpclose(f);\n\treturn Commit;\n}\n\nbool Extraction::add(ExtractionUnit * eu)\n{\n\tExtractionUnit **t = this->EUs;\n\tthis->EU_count++;\n\tthis->EUs =\n\t (ExtractionUnit **) realloc(t, sizeof(ExtractionUnit *) * this->EU_count);\n\tif(this->EUs == NULL) {\n\t\tthis->EUs = t;\n\t\tthis->EU_count--;\n\t\treturn false;\n\t}\n\tthis->EUs[this->EU_count - 1] = eu;\n\treturn true;\n}\n\nTarExtractionUnit::TarExtractionUnit(const char *fname)\n{\n\tthis->uri = std::string(fname);\n\tchar *Hash = hash_file(fname);\n\tthis->hash = std::string(Hash);\n\tfree(Hash);\n}\n\nbool TarExtractionUnit::extract(Package * P, BuildDir * bd)\n{\n\tstd::unique_ptr < PackageCmd > pc(new PackageCmd(bd->getPath(), \"tar\"));\n\n\tint res = mkdir(\"dl\", 0700);\n\tif((res < 0) && (errno != EEXIST)) {\n\t\tthrow CustomException(\"Error: Creating download directory\");\n\t}\n\tpc->addArg(\"xf\");\n\tpc->addArgFmt(\"%s\/%s\", WORLD->getWorkingDir()->c_str(), this->uri.c_str());\n\n\tif(!pc->Run(P))\n\t\tthrow CustomException(\"Failed to extract file\");\n\n\treturn true;\n}\n\nZipExtractionUnit::ZipExtractionUnit(const char *fname)\n{\n\tthis->uri = std::string(fname);\n\tchar *Hash = hash_file(fname);\n\tthis->hash = std::string(Hash);\n\tfree(Hash);\n}\n\nbool ZipExtractionUnit::extract(Package * P, BuildDir * bd)\n{\n\tstd::unique_ptr < PackageCmd > pc(new PackageCmd(bd->getPath(), \"unzip\"));\n\n\tint res = mkdir(\"dl\", 0700);\n\tif((res < 0) && (errno != EEXIST)) {\n\t\tthrow CustomException(\"Error: Creating download directory\");\n\t}\n\n\tpc->addArg(\"-o\");\n\tpc->addArgFmt(\"%s\/%s\", WORLD->getWorkingDir()->c_str(), this->uri.c_str());\n\n\tif(!pc->Run(P))\n\t\tthrow CustomException(\"Failed to extract file\");\n\n\treturn true;\n}\n\n\nPatchExtractionUnit::PatchExtractionUnit(int level, char *pp, char *uri)\n{\n\tthis->uri = std::string(uri);\n\tchar *Hash = hash_file(uri);\n\tthis->hash = std::string(Hash);\n\tfree(Hash);\n\tthis->level = level;\n\tthis->patch_path = strdup(pp);\n}\n\nbool PatchExtractionUnit::extract(Package * P, BuildDir * bd)\n{\n\tstd::unique_ptr < PackageCmd > pc_dry(new PackageCmd(this->patch_path, \"patch\"));\n\tstd::unique_ptr < PackageCmd > pc(new PackageCmd(this->patch_path, \"patch\"));\n\n\tpc_dry->addArgFmt(\"-p%i\", this->level);\n\tpc->addArgFmt(\"-p%i\", this->level);\n\n\tpc_dry->addArg(\"-stN\");\n\tpc->addArg(\"-stN\");\n\n\tpc_dry->addArg(\"-i\");\n\tpc->addArg(\"-i\");\n\n\tconst char *pwd = WORLD->getWorkingDir()->c_str();\n\tpc_dry->addArgFmt(\"%s\/%s\", pwd, this->uri.c_str());\n\tpc->addArgFmt(\"%s\/%s\", pwd, this->uri.c_str());\n\n\tpc_dry->addArg(\"--dry-run\");\n\n\tif(!pc_dry->Run(P)) {\n\t\tlog(P->getName().c_str(), \"Patch file: %s\", this->uri.c_str());\n\t\tthrow CustomException(\"Will fail to patch\");\n\t}\n\n\tif(!pc->Run(P))\n\t\tthrow CustomException(\"Truely failed to patch\");\n\n\treturn true;\n}\n\nFileCopyExtractionUnit::FileCopyExtractionUnit(const char *fname)\n{\n\tthis->uri = std::string(fname);\n\tchar *Hash = hash_file(fname);\n\tthis->hash = std::string(Hash);\n\tfree(Hash);\n}\n\nbool FileCopyExtractionUnit::extract(Package * P, BuildDir * bd)\n{\n\tstd::unique_ptr < PackageCmd > pc(new PackageCmd(bd->getPath(), \"cp\"));\n\tpc->addArg(\"-pRuf\");\n\n\tpc->addArgFmt(\"%s\/%s\", WORLD->getWorkingDir()->c_str(), this->uri.c_str());\n\n\tpc->addArg(\".\");\n\n\tif(!pc->Run(P)) {\n\t\tthrow CustomException(\"Failed to copy file\");\n\t}\n\n\treturn true;\n}\n\nGitDirExtractionUnit::GitDirExtractionUnit(const char *git_dir, const char *to_dir)\n{\n\tthis->uri = std::string(git_dir);\n\tchar *Hash = git_hash(git_dir);\n\tthis->hash = std::string(Hash);\n\tfree(Hash);\n\tthis->toDir = std::string(to_dir);\n}\n\nbool GitDirExtractionUnit::isDirty()\n{\n\tchdir(this->localPath().c_str());\n\tint res = system(\"git diff --quiet HEAD\");\n\tchdir(WORLD->getWorkingDir()->c_str());\n\treturn (res != 0);\n}\n\nstd::string GitDirExtractionUnit::dirtyHash()\n{\n\tchar *phash = git_diff_hash(this->localPath().c_str());\n\tstd::string ret(phash);\n\tfree(phash);\n\treturn ret;\n}\n\nbool LinkGitDirExtractionUnit::extract(Package * P, BuildDir * bd)\n{\n\tstd::unique_ptr < PackageCmd > pc(new PackageCmd(bd->getPath(), \"ln\"));\n\n\tpc->addArg(\"-sfT\");\n\n\tif(this->uri[0] == '.') {\n\t\tpc->addArgFmt(\"%s\/%s\", WORLD->getWorkingDir()->c_str(), this->uri.c_str());\n\t} else {\n\t\tpc->addArg(this->uri.c_str());\n\t}\n\tpc->addArg(this->toDir);\n\n\tif(!pc->Run(P)) {\n\t\tthrow CustomException(\"Operation failed\");\n\t}\n\n\treturn true;\n}\n\nbool CopyGitDirExtractionUnit::extract(Package * P, BuildDir * bd)\n{\n\tstd::unique_ptr < PackageCmd > pc(new PackageCmd(bd->getPath(), \"cp\"));\n\tpc->addArg(\"-dpRuf\");\n\n\tif(this->uri[0] == '.') {\n\t\tpc->addArgFmt(\"%s\/%s\", WORLD->getWorkingDir()->c_str(), this->uri.c_str());\n\t} else {\n\t\tpc->addArg(this->uri);\n\t}\n\tpc->addArg(this->toDir);\n\n\tif(!pc->Run(P)) {\n\t\tthrow CustomException(\"Operation failed\");\n\t}\n\n\treturn true;\n}\n\nbool GitExtractionUnit::fetch(Package * P)\n{\n\tchar *location = strdup(this->uri.c_str());\n\tchar *repo_name = strrchr(location, '\/');\n\tif(repo_name != NULL) {\n\t\trepo_name = strdup(repo_name + 1);\n\t\tchar *dotgit = strstr(repo_name, \".git\");\n\t\tif(dotgit) {\n\t\t\tdotgit[0] = '\\0';\n\t\t}\n\t\tif(strlen(repo_name) == 0) {\n\t\t\tfree(repo_name);\n\t\t\trepo_name = strrchr(strrchr(location, '\/'), '\/');\n\t\t\trepo_name = strdup(repo_name);\n\t\t}\n\t}\n\n\tchar *source_dir = NULL;\n\tconst char *cwd = WORLD->getWorkingDir()->c_str();\n\tasprintf(&source_dir, \"%s\/source\/%s\", cwd, repo_name);\n\n\tthis->local = std::string(source_dir);\n\n\tbool exists = false;\n\t{\n\t\tstruct stat s;\n\t\tint err = stat(source_dir, &s);\n\t\tif(err == 0 && S_ISDIR(s.st_mode)) {\n\t\t\texists = true;\n\t\t}\n\t}\n\n\tstd::unique_ptr < PackageCmd > pc(new PackageCmd(exists ? source_dir : cwd, \"git\"));\n\n\tif(exists) {\n\t\tpc->addArg(\"fetch\");\n\t\tpc->addArg(\"origin\");\n\t\tpc->addArg(\"--tags\");\n\t\tif(!pc->Run(P)) {\n\t\t\tthrow CustomException(\"Failed: git fetch origin --tags\");\n\t\t}\n\t} else {\n\t\tpc->addArg(\"clone\");\n\t\tpc->addArg(\"-n\");\n\t\tpc->addArg(location);\n\t\tpc->addArg(source_dir);\n\t\tif(!pc->Run(P))\n\t\t\tthrow CustomException(\"Failed to git clone\");\n\t}\n\n\tpc.reset(new PackageCmd(source_dir, \"git\"));\n\t\/\/ switch to refspec\n\tpc->addArg(\"checkout\");\n\tpc->addArg(\"-q\");\n\tpc->addArg(\"--detach\");\n\tpc->addArg(this->refspec.c_str());\n\tif(!pc->Run(P))\n\t\tthrow CustomException(\"Failed to checkout\");\n\n\tfree(repo_name);\n\tfree(location);\n\tfree(source_dir);\n\n\treturn true;\n}\n\nbool GitExtractionUnit::extract(Package * P, BuildDir * bd)\n{\n\t\/\/ copy to work dir\n\tstd::unique_ptr < PackageCmd > pc(new PackageCmd(bd->getPath(), \"cp\"));\n\tpc->addArg(\"-dpRuf\");\n\tpc->addArg(this->localPath());\n\tpc->addArg(\".\");\n\tif(!pc->Run(P))\n\t\tthrow CustomException(\"Failed to checkout\");\n\n\treturn true;\n}\n\nbool BuildDescription::add(BuildUnit * bu)\n{\n\tBuildUnit **t = this->BUs;\n\tthis->BU_count++;\n\tthis->BUs = (BuildUnit **) realloc(t, sizeof(BuildUnit *) * this->BU_count);\n\tif(this->BUs == NULL) {\n\t\tthis->BUs = t;\n\t\tthis->BU_count--;\n\t\treturn false;\n\t}\n\tthis->BUs[this->BU_count - 1] = bu;\n\treturn true;\n}\n\nPackageFileUnit::PackageFileUnit(const char *fname)\n{\n\tthis->uri = std::string(fname);\n\tchar *Hash = hash_file(fname);\n\tthis->hash = std::string(Hash);\n\tfree(Hash);\n}\n\nExtractionInfoFileUnit::ExtractionInfoFileUnit(const char *fname)\n{\n\tthis->uri = std::string(fname);\n\tchar *Hash = hash_file(fname);\n\tthis->hash = std::string(Hash);\n\tfree(Hash);\n}\n\nBuildInfoFileUnit::BuildInfoFileUnit(const char *fname)\n{\n\tthis->uri = std::string(fname);\n\tchar *Hash = hash_file(fname);\n\tthis->hash = std::string(Hash);\n\tfree(Hash);\n}\n\nOutputInfoFileUnit::OutputInfoFileUnit(const char *fname)\n{\n\tthis->uri = std::string(fname);\n\tchar *Hash = hash_file(fname);\n\tthis->hash = std::string(Hash);\n\tfree(Hash);\n}\n\nbool FeatureValueUnit::print(std::ostream & out)\n{\n\tif(!WORLD->isIgnoredFeature(this->feature)) {\n\t\tout << this->type() << \" \" << this->\n\t\t feature << \" \" << this->value << std::endl;\n\t}\n\treturn true;\n}\n<commit_msg>re-hash fetch(git) repos during extraction<commit_after>\/******************************************************************************\n Copyright 2013 Allied Telesis Labs Ltd. All rights reserved.\n \nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n 1. Redistributions of source code must retain the above copyright notice,\n this list of conditions and the following disclaimer.\n\n 2. Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in the\n documentation and\/or other materials provided with the distribution.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\nANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\nWARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR\nANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\nLOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON\nANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\nSOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*******************************************************************************\/\n\n#include <buildsys.h>\n\nstatic char *git_hash(const char *gdir)\n{\n\tchdir(gdir);\n\tFILE *f = popen(\"git rev-parse HEAD\", \"r\");\n\tchar *Commit = (char *) calloc(41, sizeof(char));\n\tfread(Commit, sizeof(char), 40, f);\n\tchdir(WORLD->getWorkingDir()->c_str());\n\tpclose(f);\n\treturn Commit;\n}\n\nstatic char *git_diff_hash(const char *gdir)\n{\n\tchdir(gdir);\n\tFILE *f = popen(\"git diff HEAD | sha1sum\", \"r\");\n\tchar *Commit = (char *) calloc(41, sizeof(char));\n\tfread(Commit, sizeof(char), 40, f);\n\tchdir(WORLD->getWorkingDir()->c_str());\n\tpclose(f);\n\treturn Commit;\n}\n\nbool Extraction::add(ExtractionUnit * eu)\n{\n\tExtractionUnit **t = this->EUs;\n\tthis->EU_count++;\n\tthis->EUs =\n\t (ExtractionUnit **) realloc(t, sizeof(ExtractionUnit *) * this->EU_count);\n\tif(this->EUs == NULL) {\n\t\tthis->EUs = t;\n\t\tthis->EU_count--;\n\t\treturn false;\n\t}\n\tthis->EUs[this->EU_count - 1] = eu;\n\treturn true;\n}\n\nTarExtractionUnit::TarExtractionUnit(const char *fname)\n{\n\tthis->uri = std::string(fname);\n\tchar *Hash = hash_file(fname);\n\tthis->hash = std::string(Hash);\n\tfree(Hash);\n}\n\nbool TarExtractionUnit::extract(Package * P, BuildDir * bd)\n{\n\tstd::unique_ptr < PackageCmd > pc(new PackageCmd(bd->getPath(), \"tar\"));\n\n\tint res = mkdir(\"dl\", 0700);\n\tif((res < 0) && (errno != EEXIST)) {\n\t\tthrow CustomException(\"Error: Creating download directory\");\n\t}\n\tpc->addArg(\"xf\");\n\tpc->addArgFmt(\"%s\/%s\", WORLD->getWorkingDir()->c_str(), this->uri.c_str());\n\n\tif(!pc->Run(P))\n\t\tthrow CustomException(\"Failed to extract file\");\n\n\treturn true;\n}\n\nZipExtractionUnit::ZipExtractionUnit(const char *fname)\n{\n\tthis->uri = std::string(fname);\n\tchar *Hash = hash_file(fname);\n\tthis->hash = std::string(Hash);\n\tfree(Hash);\n}\n\nbool ZipExtractionUnit::extract(Package * P, BuildDir * bd)\n{\n\tstd::unique_ptr < PackageCmd > pc(new PackageCmd(bd->getPath(), \"unzip\"));\n\n\tint res = mkdir(\"dl\", 0700);\n\tif((res < 0) && (errno != EEXIST)) {\n\t\tthrow CustomException(\"Error: Creating download directory\");\n\t}\n\n\tpc->addArg(\"-o\");\n\tpc->addArgFmt(\"%s\/%s\", WORLD->getWorkingDir()->c_str(), this->uri.c_str());\n\n\tif(!pc->Run(P))\n\t\tthrow CustomException(\"Failed to extract file\");\n\n\treturn true;\n}\n\n\nPatchExtractionUnit::PatchExtractionUnit(int level, char *pp, char *uri)\n{\n\tthis->uri = std::string(uri);\n\tchar *Hash = hash_file(uri);\n\tthis->hash = std::string(Hash);\n\tfree(Hash);\n\tthis->level = level;\n\tthis->patch_path = strdup(pp);\n}\n\nbool PatchExtractionUnit::extract(Package * P, BuildDir * bd)\n{\n\tstd::unique_ptr < PackageCmd > pc_dry(new PackageCmd(this->patch_path, \"patch\"));\n\tstd::unique_ptr < PackageCmd > pc(new PackageCmd(this->patch_path, \"patch\"));\n\n\tpc_dry->addArgFmt(\"-p%i\", this->level);\n\tpc->addArgFmt(\"-p%i\", this->level);\n\n\tpc_dry->addArg(\"-stN\");\n\tpc->addArg(\"-stN\");\n\n\tpc_dry->addArg(\"-i\");\n\tpc->addArg(\"-i\");\n\n\tconst char *pwd = WORLD->getWorkingDir()->c_str();\n\tpc_dry->addArgFmt(\"%s\/%s\", pwd, this->uri.c_str());\n\tpc->addArgFmt(\"%s\/%s\", pwd, this->uri.c_str());\n\n\tpc_dry->addArg(\"--dry-run\");\n\n\tif(!pc_dry->Run(P)) {\n\t\tlog(P->getName().c_str(), \"Patch file: %s\", this->uri.c_str());\n\t\tthrow CustomException(\"Will fail to patch\");\n\t}\n\n\tif(!pc->Run(P))\n\t\tthrow CustomException(\"Truely failed to patch\");\n\n\treturn true;\n}\n\nFileCopyExtractionUnit::FileCopyExtractionUnit(const char *fname)\n{\n\tthis->uri = std::string(fname);\n\tchar *Hash = hash_file(fname);\n\tthis->hash = std::string(Hash);\n\tfree(Hash);\n}\n\nbool FileCopyExtractionUnit::extract(Package * P, BuildDir * bd)\n{\n\tstd::unique_ptr < PackageCmd > pc(new PackageCmd(bd->getPath(), \"cp\"));\n\tpc->addArg(\"-pRuf\");\n\n\tpc->addArgFmt(\"%s\/%s\", WORLD->getWorkingDir()->c_str(), this->uri.c_str());\n\n\tpc->addArg(\".\");\n\n\tif(!pc->Run(P)) {\n\t\tthrow CustomException(\"Failed to copy file\");\n\t}\n\n\treturn true;\n}\n\nGitDirExtractionUnit::GitDirExtractionUnit(const char *git_dir, const char *to_dir)\n{\n\tthis->uri = std::string(git_dir);\n\tchar *Hash = git_hash(git_dir);\n\tthis->hash = std::string(Hash);\n\tfree(Hash);\n\tthis->toDir = std::string(to_dir);\n}\n\nbool GitDirExtractionUnit::isDirty()\n{\n\tchdir(this->localPath().c_str());\n\tint res = system(\"git diff --quiet HEAD\");\n\tchdir(WORLD->getWorkingDir()->c_str());\n\treturn (res != 0);\n}\n\nstd::string GitDirExtractionUnit::dirtyHash()\n{\n\tchar *phash = git_diff_hash(this->localPath().c_str());\n\tstd::string ret(phash);\n\tfree(phash);\n\treturn ret;\n}\n\nbool LinkGitDirExtractionUnit::extract(Package * P, BuildDir * bd)\n{\n\tstd::unique_ptr < PackageCmd > pc(new PackageCmd(bd->getPath(), \"ln\"));\n\n\tpc->addArg(\"-sfT\");\n\n\tif(this->uri[0] == '.') {\n\t\tpc->addArgFmt(\"%s\/%s\", WORLD->getWorkingDir()->c_str(), this->uri.c_str());\n\t} else {\n\t\tpc->addArg(this->uri.c_str());\n\t}\n\tpc->addArg(this->toDir);\n\n\tif(!pc->Run(P)) {\n\t\tthrow CustomException(\"Operation failed\");\n\t}\n\n\treturn true;\n}\n\nbool CopyGitDirExtractionUnit::extract(Package * P, BuildDir * bd)\n{\n\tstd::unique_ptr < PackageCmd > pc(new PackageCmd(bd->getPath(), \"cp\"));\n\tpc->addArg(\"-dpRuf\");\n\n\tif(this->uri[0] == '.') {\n\t\tpc->addArgFmt(\"%s\/%s\", WORLD->getWorkingDir()->c_str(), this->uri.c_str());\n\t} else {\n\t\tpc->addArg(this->uri);\n\t}\n\tpc->addArg(this->toDir);\n\n\tif(!pc->Run(P)) {\n\t\tthrow CustomException(\"Operation failed\");\n\t}\n\n\treturn true;\n}\n\nbool GitExtractionUnit::fetch(Package * P)\n{\n\tchar *location = strdup(this->uri.c_str());\n\tchar *repo_name = strrchr(location, '\/');\n\tif(repo_name != NULL) {\n\t\trepo_name = strdup(repo_name + 1);\n\t\tchar *dotgit = strstr(repo_name, \".git\");\n\t\tif(dotgit) {\n\t\t\tdotgit[0] = '\\0';\n\t\t}\n\t\tif(strlen(repo_name) == 0) {\n\t\t\tfree(repo_name);\n\t\t\trepo_name = strrchr(strrchr(location, '\/'), '\/');\n\t\t\trepo_name = strdup(repo_name);\n\t\t}\n\t}\n\n\tchar *source_dir = NULL;\n\tconst char *cwd = WORLD->getWorkingDir()->c_str();\n\tasprintf(&source_dir, \"%s\/source\/%s\", cwd, repo_name);\n\n\tthis->local = std::string(source_dir);\n\n\tbool exists = false;\n\t{\n\t\tstruct stat s;\n\t\tint err = stat(source_dir, &s);\n\t\tif(err == 0 && S_ISDIR(s.st_mode)) {\n\t\t\texists = true;\n\t\t}\n\t}\n\n\tstd::unique_ptr < PackageCmd > pc(new PackageCmd(exists ? source_dir : cwd, \"git\"));\n\n\tif(exists) {\n\t\tpc->addArg(\"fetch\");\n\t\tpc->addArg(\"origin\");\n\t\tpc->addArg(\"--tags\");\n\t\tif(!pc->Run(P)) {\n\t\t\tthrow CustomException(\"Failed: git fetch origin --tags\");\n\t\t}\n\t} else {\n\t\tpc->addArg(\"clone\");\n\t\tpc->addArg(\"-n\");\n\t\tpc->addArg(location);\n\t\tpc->addArg(source_dir);\n\t\tif(!pc->Run(P))\n\t\t\tthrow CustomException(\"Failed to git clone\");\n\t}\n\n\tpc.reset(new PackageCmd(source_dir, \"git\"));\n\t\/\/ switch to refspec\n\tpc->addArg(\"checkout\");\n\tpc->addArg(\"-q\");\n\tpc->addArg(\"--detach\");\n\tpc->addArg(this->refspec.c_str());\n\tif(!pc->Run(P))\n\t\tthrow CustomException(\"Failed to checkout\");\n\n\tfree(repo_name);\n\tfree(location);\n\n\tchar *Hash = git_hash(source_dir);\n\tthis->hash = std::string(Hash);\n\tfree(Hash);\n\n\tfree(source_dir);\n\n\treturn true;\n}\n\nbool GitExtractionUnit::extract(Package * P, BuildDir * bd)\n{\n\t\/\/ copy to work dir\n\tstd::unique_ptr < PackageCmd > pc(new PackageCmd(bd->getPath(), \"cp\"));\n\tpc->addArg(\"-dpRuf\");\n\tpc->addArg(this->localPath());\n\tpc->addArg(\".\");\n\tif(!pc->Run(P))\n\t\tthrow CustomException(\"Failed to checkout\");\n\n\treturn true;\n}\n\nbool BuildDescription::add(BuildUnit * bu)\n{\n\tBuildUnit **t = this->BUs;\n\tthis->BU_count++;\n\tthis->BUs = (BuildUnit **) realloc(t, sizeof(BuildUnit *) * this->BU_count);\n\tif(this->BUs == NULL) {\n\t\tthis->BUs = t;\n\t\tthis->BU_count--;\n\t\treturn false;\n\t}\n\tthis->BUs[this->BU_count - 1] = bu;\n\treturn true;\n}\n\nPackageFileUnit::PackageFileUnit(const char *fname)\n{\n\tthis->uri = std::string(fname);\n\tchar *Hash = hash_file(fname);\n\tthis->hash = std::string(Hash);\n\tfree(Hash);\n}\n\nExtractionInfoFileUnit::ExtractionInfoFileUnit(const char *fname)\n{\n\tthis->uri = std::string(fname);\n\tchar *Hash = hash_file(fname);\n\tthis->hash = std::string(Hash);\n\tfree(Hash);\n}\n\nBuildInfoFileUnit::BuildInfoFileUnit(const char *fname)\n{\n\tthis->uri = std::string(fname);\n\tchar *Hash = hash_file(fname);\n\tthis->hash = std::string(Hash);\n\tfree(Hash);\n}\n\nOutputInfoFileUnit::OutputInfoFileUnit(const char *fname)\n{\n\tthis->uri = std::string(fname);\n\tchar *Hash = hash_file(fname);\n\tthis->hash = std::string(Hash);\n\tfree(Hash);\n}\n\nbool FeatureValueUnit::print(std::ostream & out)\n{\n\tif(!WORLD->isIgnoredFeature(this->feature)) {\n\t\tout << this->type() << \" \" << this->\n\t\t feature << \" \" << this->value << std::endl;\n\t}\n\treturn true;\n}\n<|endoftext|>"} {"text":"<commit_before>#include <graphics\/pipeline\/renderpass.h>\r\n#include <core\/video\/context.h>\r\n#include <core\/log\/log.h>\r\n\r\nnamespace fd {\r\nnamespace graphics {\r\nnamespace pipeline {\r\n\r\nusing namespace core;\r\nusing namespace video;\r\nusing namespace utils;\r\nusing namespace texture;\r\nusing namespace log;\r\nusing namespace math;\r\nusing namespace event;\r\n\r\nstatic bool CheckFramebuffers(const List<Framebuffer*>& framebuffers) {\r\n\r\n\tuint32 w = framebuffers[0]->GetWidth();\r\n\tuint32 h = framebuffers[0]->GetHeight();\r\n\r\n\tfor (uint_t i = 1; i < framebuffers.GetSize(); i++) {\r\n\t\tif (framebuffers[i]->GetWidth() != w) {\r\n\t\t\treturn false;\r\n\t\t} else if (framebuffers[i]->GetHeight() != h) {\r\n\t\t\treturn false;\r\n\t\t}\r\n\t}\r\n\r\n\treturn true;\r\n}\r\n\r\nRenderPass::RenderPass() : EventListener(EventWindow), renderPass(nullptr) {\r\n\r\n\tVkAttachmentDescription colorAttachment;\r\n\r\n\tcolorAttachment.flags = 0;\r\n\tcolorAttachment.format = Context::GetSwapchainFormat();\r\n\tcolorAttachment.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;\r\n\tcolorAttachment.finalLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR;\r\n\tcolorAttachment.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;\r\n\tcolorAttachment.storeOp = VK_ATTACHMENT_STORE_OP_STORE;\r\n\tcolorAttachment.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;\r\n\tcolorAttachment.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;\r\n\tcolorAttachment.samples = VK_SAMPLE_COUNT_1_BIT;\r\n\r\n\tVkAttachmentReference ref;\r\n\r\n\tref.attachment = 0;\r\n\tref.layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;\r\n\r\n\tVkSubpassDescription subDesc;\r\n\r\n\tsubDesc.flags = 0;\r\n\tsubDesc.colorAttachmentCount = 1;\r\n\tsubDesc.pColorAttachments = &ref;\r\n\tsubDesc.inputAttachmentCount = 0;\r\n\tsubDesc.pInputAttachments = nullptr;\r\n\tsubDesc.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS;\r\n\tsubDesc.pResolveAttachments = nullptr;\r\n\tsubDesc.preserveAttachmentCount = 0;\r\n\tsubDesc.pPreserveAttachments = nullptr;\r\n\tsubDesc.pDepthStencilAttachment = nullptr;\r\n\r\n\tVkSubpassDependency dependency;\r\n\r\n\tdependency.dependencyFlags = 0;\r\n\tdependency.srcSubpass = VK_SUBPASS_EXTERNAL;\r\n\tdependency.dstSubpass = 0;\r\n\tdependency.srcAccessMask = 0;\r\n\tdependency.dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;\r\n\tdependency.srcStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;\r\n\tdependency.dstStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;\r\n\r\n\tVkRenderPassCreateInfo renderInfo;\r\n\r\n\trenderInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO;\r\n\trenderInfo.pNext = nullptr;\r\n\trenderInfo.flags = 0;\r\n\trenderInfo.dependencyCount = 1;\r\n\trenderInfo.pDependencies = &dependency;\r\n\trenderInfo.attachmentCount = 1;\r\n\trenderInfo.pAttachments = &colorAttachment;\r\n\trenderInfo.subpassCount = 1;\r\n\trenderInfo.pSubpasses = &subDesc;\r\n\r\n\tVK(vkCreateRenderPass(Context::GetDevice(), &renderInfo, nullptr, &renderPass));\r\n\r\n\tconst List<VkImageView>& swapchainViews = Context::GetSwapchainImageViews();\r\n\r\n\tfor (uint_t i = 0; i < swapchainViews.GetSize(); i++) {\r\n\t\tVkFramebufferCreateInfo info;\r\n\r\n\t\tinfo.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO;\r\n\t\tinfo.pNext = nullptr;\r\n\t\tinfo.flags = 0;\r\n\t\tinfo.width = width = Context::GetSwapchainExtent().width;\r\n\t\tinfo.height = height = Context::GetSwapchainExtent().height;\r\n\t\tinfo.layers = 1;\r\n\t\tinfo.renderPass = renderPass;\r\n\t\tinfo.attachmentCount = 1;\r\n\t\tinfo.pAttachments = &swapchainViews[i];\r\n\r\n\t\tVkFramebuffer tmp = nullptr;\r\n\r\n\t\tVK(vkCreateFramebuffer(Context::GetDevice(), &info, nullptr, &tmp));\r\n\r\n\t\tframebufferObjects.Push_back(tmp);\r\n\t}\r\n\r\n}\r\n\r\nRenderPass::RenderPass(const RenderPassInfo* info) : EventListener(EventWindow, false), renderPass(nullptr), info(new RenderPassInfo), framebuffers(info->framebuffers) {\r\n\tmemcpy(this->info, info, sizeof(RenderPassInfo));\r\n\r\n\tVkAttachmentDescription* attachments = new VkAttachmentDescription[framebuffers.GetSize() + 1];\r\n\r\n\tuint32 swapchainIndex = framebuffers.GetSize();\r\n\r\n\tVkAttachmentDescription& swapchainAttachment = attachments[swapchainIndex];\r\n\r\n\tswapchainAttachment.flags = 0;\r\n\tswapchainAttachment.format = Context::GetSwapchainFormat();\r\n\tswapchainAttachment.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;\r\n\tswapchainAttachment.finalLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR;\r\n\tswapchainAttachment.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;\r\n\tswapchainAttachment.storeOp = VK_ATTACHMENT_STORE_OP_STORE;\r\n\tswapchainAttachment.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;\r\n\tswapchainAttachment.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;\r\n\tswapchainAttachment.samples = VK_SAMPLE_COUNT_1_BIT;\r\n\r\n\tfor (uint_t i = 0; i < info->framebuffers.GetSize(); i++) {\r\n\t\tVkAttachmentDescription& desc = attachments[i];\r\n\r\n\t\tdesc.flags = 0;\r\n\t\tdesc.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;\r\n\t\tdesc.finalLayout = VK_IMAGE_LAYOUT_UNDEFINED;\r\n\t\tdesc.format = info->framebuffers[i]->GetFormat();\r\n\t\tdesc.samples = VK_SAMPLE_COUNT_1_BIT;\r\n\t\tdesc.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;\r\n\t\tdesc.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;\r\n\t\tdesc.storeOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;\r\n\t\tdesc.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;\r\n\t}\r\n\r\n\tList<VkAttachmentReference> attachmentReferences;\r\n\tList<VkSubpassDescription> subpassDescriptions;\r\n\r\n\tattachmentReferences.Reserve(info->subpasses.GetSize() * FD_MAX_ATTACHMENTS + 1);\r\n\r\n\tusesSwapchainImage = false;\r\n\r\n\tif (info->depthAttachment != FD_NO_ATTACHMENT) {\r\n\t\tVkAttachmentReference ref;\r\n\r\n\t\tref.attachment = info->depthAttachment;\r\n\t\tref.layout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;\r\n\r\n\t\tattachmentReferences.Push_back(ref);\r\n\t}\r\n\r\n\tfor (uint_t i = 0; i < info->subpasses.GetSize(); i++) {\r\n\t\tRenderSubPassInfo subInfo = info->subpasses[i];\r\n\t\t\r\n\t\tVkSubpassDescription subpass;\r\n\r\n\t\tsubpass.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS;\r\n\t\tsubpass.flags = 0;\r\n\t\tsubpass.colorAttachmentCount = ~0;\r\n\t\tsubpass.inputAttachmentCount = ~0;\r\n\t\tsubpass.preserveAttachmentCount = 0;\r\n\t\tsubpass.pInputAttachments = nullptr;\r\n\t\tsubpass.pDepthStencilAttachment = nullptr;\r\n\t\tsubpass.pPreserveAttachments = nullptr;\r\n\t\tsubpass.pResolveAttachments = nullptr;\r\n\r\n\t\tVkAttachmentReference ref;\r\n\r\n\t\tref.layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;\r\n\r\n\t\tfor (uint32 j = 0; j < FD_MAX_ATTACHMENTS; j++) {\r\n\t\t\tref.attachment = subInfo.colorAttachments[j];\r\n\r\n\t\t\tif (ref.attachment == FD_NO_ATTACHMENT) {\r\n\t\t\t\tsubpass.colorAttachmentCount = j;\r\n\t\t\t\tbreak;\r\n\t\t\t} else if (ref.attachment == FD_SWAPCHAIN_ATTACHMENT_INDEX) {\r\n\t\t\t\tref.attachment = swapchainIndex;\r\n\t\t\t\tusesSwapchainImage = true;\r\n\t\t\t}\r\n\r\n\t\t\tif (ref.attachment == info->depthAttachment) {\r\n\t\t\t\tLog::Fatal(\"[RenderPass] Color attachment can't use the same framebuffer as depth\/stencil attachment\");\r\n\t\t\t\treturn;\r\n\t\t\t}\r\n\r\n\t\t\tattachmentReferences.Push_back(ref);\r\n\t\t}\r\n\r\n\t\tif (subpass.colorAttachmentCount == ~0) {\r\n\t\t\tsubpass.colorAttachmentCount = FD_MAX_ATTACHMENTS;\r\n\t\t} else if (subpass.colorAttachmentCount == 0) {\r\n\t\t\tLog::Fatal(\"[RenderPass] No color attachment specified!\");\r\n\t\t\treturn;\r\n\t\t}\r\n\r\n\t\tsubpass.pColorAttachments = &attachmentReferences[attachmentReferences.GetSize() - subpass.colorAttachmentCount];\r\n\r\n\t\tref.layout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;\r\n\r\n\t\tfor (uint32 j = 0; j < FD_MAX_ATTACHMENTS; j++) {\r\n\t\t\tref.attachment = subInfo.inputAttachments[j];\r\n\r\n\t\t\tif (ref.attachment == FD_NO_ATTACHMENT) {\r\n\t\t\t\tsubpass.inputAttachmentCount = j;\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\r\n\t\t\tattachmentReferences.Push_back(ref);\r\n\t\t}\r\n\r\n\t\tif (subpass.inputAttachmentCount == ~0) {\r\n\t\t\tsubpass.inputAttachmentCount = FD_MAX_ATTACHMENTS;\r\n\t\t}\r\n\r\n\t\tif (subpass.inputAttachmentCount != 0) subpass.pInputAttachments = &attachmentReferences[attachmentReferences.GetSize() - subpass.inputAttachmentCount];\r\n\r\n\t\tif (info->depthAttachment != FD_NO_ATTACHMENT) {\r\n\t\t\tsubpass.pDepthStencilAttachment = &attachmentReferences[0];\r\n\t\t}\r\n\t\t\r\n\t\tsubpassDescriptions.Push_back(subpass);\r\n\t}\r\n\r\n\tclearValues.Resize(framebuffers.GetSize());\r\n\r\n\tfor (uint_t i = 0; framebuffers.GetSize(); i++) {\r\n\t\tif (i == info->depthAttachment) {\r\n\t\t\tclearValues[i].depthStencil.depth = info->depthClearValue;\r\n\t\t} else {\r\n\t\t\tmemcpy(&clearValues[i].color, &info->clearColor, sizeof(vec4));\r\n\t\t}\r\n\t}\r\n\r\n\tif (usesSwapchainImage) {\r\n\t\tclearValues.Resize(clearValues.GetSize() + 1);\r\n\t\tmemcpy(&clearValues[swapchainIndex].color, &info->clearColor, sizeof(vec4));\r\n\t}\r\n\r\n\tList<VkSubpassDependency> dependencies;\r\n\r\n\tVkSubpassDependency dep;\r\n\r\n\tdep.srcSubpass = VK_SUBPASS_EXTERNAL;\r\n\tdep.dstSubpass = 1;\r\n\tdep.srcStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;\r\n\tdep.srcAccessMask = 0;\r\n\tdep.dstStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;\r\n\tdep.dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;\r\n\tdep.dependencyFlags = 0;\r\n\t\r\n\tdependencies.Push_back(dep);\r\n\r\n\tfor (uint32 i = 1; i < subpassDescriptions.GetSize(); i++) {\r\n\t\tdep.srcSubpass = i - 1;\r\n\t\tdep.dstSubpass = i;\r\n\r\n\t\tdependencies.Push_back(dep);\r\n\t}\r\n\r\n\tVkRenderPassCreateInfo rinfo;\r\n\r\n\trinfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO;\r\n\trinfo.pNext = nullptr;\r\n\trinfo.flags = 0;\r\n\trinfo.attachmentCount = info->framebuffers.GetSize() + usesSwapchainImage ? 1 : 0;\r\n\trinfo.pAttachments = attachments;\r\n\trinfo.subpassCount = subpassDescriptions.GetSize();\r\n\trinfo.pSubpasses = &subpassDescriptions[0];\r\n\trinfo.dependencyCount = dependencies.GetSize();\r\n\trinfo.pDependencies = &dependencies[0];\r\n\r\n\tVK(vkCreateRenderPass(Context::GetDevice(), &rinfo, nullptr, &renderPass));\r\n\r\n\tVkImageView* imageViews = new VkImageView[framebuffers.GetSize() + 1];\r\n\r\n\tfor (uint_t i = 0; i < framebuffers.GetSize(); i++) {\r\n\t\timageViews[i] = framebuffers[i]->GetImageView();\r\n\t}\r\n\r\n\tfinfo.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO;\r\n\tfinfo.flags = 0;\r\n\tfinfo.layers = 1;\r\n\tfinfo.renderPass = renderPass;\r\n\tfinfo.pAttachments = imageViews;\r\n\t\r\n\tif (usesSwapchainImage) {\r\n\t\tfinfo.width = width = Context::GetSwapchainExtent().width;\r\n\t\tfinfo.height = height = Context::GetSwapchainExtent().height;\r\n\t\tfinfo.attachmentCount = framebuffers.GetSize() + 1;\r\n\r\n\t\tList<VkImageView> swapViews = Context::GetSwapchainImageViews();\r\n\r\n\t\tfor (uint_t i = 0; i < swapViews.GetSize(); i++) {\r\n\t\t\timageViews[swapchainIndex] = swapViews[i];\r\n\r\n\t\t\tVkFramebuffer framebuffer;\r\n\r\n\t\t\tVK(vkCreateFramebuffer(Context::GetDevice(), &finfo, nullptr, &framebuffer));\r\n\r\n\t\t\tframebufferObjects.Push_back(framebuffer);\r\n\t\t}\r\n\r\n\t\tRegister();\r\n\r\n\t} else {\r\n\t\tCheckFramebuffers(framebuffers);\r\n\t\tfinfo.width = width = framebuffers[0]->GetWidth();\r\n\t\tfinfo.height = height = framebuffers[0]->GetHeight();\r\n\t\tfinfo.attachmentCount = framebuffers.GetSize();\r\n\r\n\t\tVkFramebuffer framebuffer;\r\n\r\n\t\tVK(vkCreateFramebuffer(Context::GetDevice(), &finfo, nullptr, &framebuffer));\r\n\r\n\t\tframebufferObjects.Push_back(framebuffer);\r\n\t}\r\n\r\n}\r\n\r\nRenderPass::~RenderPass() {\r\n\tfor (uint_t i = 0; i < framebufferObjects.GetSize(); i++) {\r\n\t\tvkDestroyFramebuffer(Context::GetDevice(), framebufferObjects[i], nullptr);\r\n\t}\r\n\r\n\tvkDestroyRenderPass(Context::GetDevice(), renderPass, nullptr);\r\n\r\n\tdelete info;\r\n}\r\n\r\nvoid RenderPass::InitializeRenderPass(VkRenderPassBeginInfo* const info) const {\r\n\tinfo->clearValueCount = clearValues.GetSize();\r\n\tinfo->pClearValues = clearValues.GetData();\r\n}\r\n\r\nbool RenderPass::OnWindowEventResize(const vec2i& size) {\r\n\tif (info == nullptr) {\r\n\t\tfor (uint_t i = 0; i < framebufferObjects.GetSize(); i++) {\r\n\t\t\tvkDestroyFramebuffer(Context::GetDevice(), framebufferObjects[i], nullptr);\r\n\t\t}\r\n\r\n\t\tframebufferObjects.Clear();\r\n\r\n\t\tconst List<VkImageView>& swapchainViews = Context::GetSwapchainImageViews();\r\n\r\n\t\tfor (uint_t i = 0; i < swapchainViews.GetSize(); i++) {\r\n\t\t\tVkFramebufferCreateInfo info;\r\n\r\n\t\t\tinfo.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO;\r\n\t\t\tinfo.pNext = nullptr;\r\n\t\t\tinfo.flags = 0;\r\n\t\t\tinfo.width = width = size.x;\r\n\t\t\tinfo.height = height = size.y;\r\n\t\t\tinfo.layers = 1;\r\n\t\t\tinfo.renderPass = renderPass;\r\n\t\t\tinfo.attachmentCount = 1;\r\n\t\t\tinfo.pAttachments = &swapchainViews[i];\r\n\r\n\t\t\tVkFramebuffer tmp = nullptr;\r\n\r\n\t\t\tVK(vkCreateFramebuffer(Context::GetDevice(), &info, nullptr, &tmp));\r\n\r\n\t\t\tframebufferObjects.Push_back(tmp);\r\n\t\t}\r\n\t} else {\r\n\t\tfor (uint_t i = 0; i < framebufferObjects.GetSize(); i++) {\r\n\t\t\tvkDestroyFramebuffer(Context::GetDevice(), framebufferObjects[i], nullptr);\r\n\t\t}\r\n\r\n\t\tframebufferObjects.Clear();\r\n\r\n\t\tfinfo.width = width = size.x;\r\n\t\tfinfo.height = height = size.y;\r\n\r\n\t\tList<VkImageView> swapViews = Context::GetSwapchainImageViews();\r\n\r\n\t\tuint64 swapchainIndex = framebuffers.GetSize();\r\n\r\n\t\tVkImageView* imageViews = (VkImageView*)finfo.pAttachments;\r\n\r\n\t\tfor (uint_t i = 0; i < swapViews.GetSize(); i++) {\r\n\t\t\timageViews[swapchainIndex] = swapViews[i];\r\n\r\n\t\t\tVkFramebuffer framebuffer;\r\n\r\n\t\t\tVK(vkCreateFramebuffer(Context::GetDevice(), &finfo, nullptr, &framebuffer));\r\n\r\n\t\t\tframebufferObjects.Push_back(framebuffer);\r\n\t\t}\r\n\t}\r\n\r\n\treturn true;\r\n}\r\n\r\n}\r\n}\r\n}<commit_msg>Render pass now resizes framebuffers<commit_after>#include <graphics\/pipeline\/renderpass.h>\r\n#include <core\/video\/context.h>\r\n#include <core\/log\/log.h>\r\n\r\nnamespace fd {\r\nnamespace graphics {\r\nnamespace pipeline {\r\n\r\nusing namespace core;\r\nusing namespace video;\r\nusing namespace utils;\r\nusing namespace texture;\r\nusing namespace log;\r\nusing namespace math;\r\nusing namespace event;\r\n\r\nstatic bool CheckFramebuffers(const List<Framebuffer*>& framebuffers) {\r\n\r\n\tuint32 w = framebuffers[0]->GetWidth();\r\n\tuint32 h = framebuffers[0]->GetHeight();\r\n\r\n\tfor (uint_t i = 1; i < framebuffers.GetSize(); i++) {\r\n\t\tif (framebuffers[i]->GetWidth() != w) {\r\n\t\t\treturn false;\r\n\t\t} else if (framebuffers[i]->GetHeight() != h) {\r\n\t\t\treturn false;\r\n\t\t}\r\n\t}\r\n\r\n\treturn true;\r\n}\r\n\r\nRenderPass::RenderPass() : EventListener(EventWindow), renderPass(nullptr) {\r\n\r\n\tVkAttachmentDescription colorAttachment;\r\n\r\n\tcolorAttachment.flags = 0;\r\n\tcolorAttachment.format = Context::GetSwapchainFormat();\r\n\tcolorAttachment.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;\r\n\tcolorAttachment.finalLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR;\r\n\tcolorAttachment.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;\r\n\tcolorAttachment.storeOp = VK_ATTACHMENT_STORE_OP_STORE;\r\n\tcolorAttachment.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;\r\n\tcolorAttachment.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;\r\n\tcolorAttachment.samples = VK_SAMPLE_COUNT_1_BIT;\r\n\r\n\tVkAttachmentReference ref;\r\n\r\n\tref.attachment = 0;\r\n\tref.layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;\r\n\r\n\tVkSubpassDescription subDesc;\r\n\r\n\tsubDesc.flags = 0;\r\n\tsubDesc.colorAttachmentCount = 1;\r\n\tsubDesc.pColorAttachments = &ref;\r\n\tsubDesc.inputAttachmentCount = 0;\r\n\tsubDesc.pInputAttachments = nullptr;\r\n\tsubDesc.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS;\r\n\tsubDesc.pResolveAttachments = nullptr;\r\n\tsubDesc.preserveAttachmentCount = 0;\r\n\tsubDesc.pPreserveAttachments = nullptr;\r\n\tsubDesc.pDepthStencilAttachment = nullptr;\r\n\r\n\tVkSubpassDependency dependency;\r\n\r\n\tdependency.dependencyFlags = 0;\r\n\tdependency.srcSubpass = VK_SUBPASS_EXTERNAL;\r\n\tdependency.dstSubpass = 0;\r\n\tdependency.srcAccessMask = 0;\r\n\tdependency.dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;\r\n\tdependency.srcStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;\r\n\tdependency.dstStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;\r\n\r\n\tVkRenderPassCreateInfo renderInfo;\r\n\r\n\trenderInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO;\r\n\trenderInfo.pNext = nullptr;\r\n\trenderInfo.flags = 0;\r\n\trenderInfo.dependencyCount = 1;\r\n\trenderInfo.pDependencies = &dependency;\r\n\trenderInfo.attachmentCount = 1;\r\n\trenderInfo.pAttachments = &colorAttachment;\r\n\trenderInfo.subpassCount = 1;\r\n\trenderInfo.pSubpasses = &subDesc;\r\n\r\n\tVK(vkCreateRenderPass(Context::GetDevice(), &renderInfo, nullptr, &renderPass));\r\n\r\n\tconst List<VkImageView>& swapchainViews = Context::GetSwapchainImageViews();\r\n\r\n\tfor (uint_t i = 0; i < swapchainViews.GetSize(); i++) {\r\n\t\tVkFramebufferCreateInfo info;\r\n\r\n\t\tinfo.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO;\r\n\t\tinfo.pNext = nullptr;\r\n\t\tinfo.flags = 0;\r\n\t\tinfo.width = width = Context::GetSwapchainExtent().width;\r\n\t\tinfo.height = height = Context::GetSwapchainExtent().height;\r\n\t\tinfo.layers = 1;\r\n\t\tinfo.renderPass = renderPass;\r\n\t\tinfo.attachmentCount = 1;\r\n\t\tinfo.pAttachments = &swapchainViews[i];\r\n\r\n\t\tVkFramebuffer tmp = nullptr;\r\n\r\n\t\tVK(vkCreateFramebuffer(Context::GetDevice(), &info, nullptr, &tmp));\r\n\r\n\t\tframebufferObjects.Push_back(tmp);\r\n\t}\r\n\r\n}\r\n\r\nRenderPass::RenderPass(const RenderPassInfo* info) : EventListener(EventWindow, false), renderPass(nullptr), info(new RenderPassInfo), framebuffers(info->framebuffers) {\r\n\tmemcpy(this->info, info, sizeof(RenderPassInfo));\r\n\r\n\tVkAttachmentDescription* attachments = new VkAttachmentDescription[framebuffers.GetSize() + 1];\r\n\r\n\tuint32 swapchainIndex = framebuffers.GetSize();\r\n\r\n\tVkAttachmentDescription& swapchainAttachment = attachments[swapchainIndex];\r\n\r\n\tswapchainAttachment.flags = 0;\r\n\tswapchainAttachment.format = Context::GetSwapchainFormat();\r\n\tswapchainAttachment.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;\r\n\tswapchainAttachment.finalLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR;\r\n\tswapchainAttachment.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;\r\n\tswapchainAttachment.storeOp = VK_ATTACHMENT_STORE_OP_STORE;\r\n\tswapchainAttachment.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;\r\n\tswapchainAttachment.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;\r\n\tswapchainAttachment.samples = VK_SAMPLE_COUNT_1_BIT;\r\n\r\n\tfor (uint_t i = 0; i < info->framebuffers.GetSize(); i++) {\r\n\t\tVkAttachmentDescription& desc = attachments[i];\r\n\r\n\t\tdesc.flags = 0;\r\n\t\tdesc.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;\r\n\t\tdesc.finalLayout = VK_IMAGE_LAYOUT_UNDEFINED;\r\n\t\tdesc.format = info->framebuffers[i]->GetFormat();\r\n\t\tdesc.samples = VK_SAMPLE_COUNT_1_BIT;\r\n\t\tdesc.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;\r\n\t\tdesc.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;\r\n\t\tdesc.storeOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;\r\n\t\tdesc.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;\r\n\t}\r\n\r\n\tList<VkAttachmentReference> attachmentReferences;\r\n\tList<VkSubpassDescription> subpassDescriptions;\r\n\r\n\tattachmentReferences.Reserve(info->subpasses.GetSize() * FD_MAX_ATTACHMENTS + 1);\r\n\r\n\tusesSwapchainImage = false;\r\n\r\n\tif (info->depthAttachment != FD_NO_ATTACHMENT) {\r\n\t\tVkAttachmentReference ref;\r\n\r\n\t\tref.attachment = info->depthAttachment;\r\n\t\tref.layout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;\r\n\r\n\t\tattachmentReferences.Push_back(ref);\r\n\t}\r\n\r\n\tfor (uint_t i = 0; i < info->subpasses.GetSize(); i++) {\r\n\t\tRenderSubPassInfo subInfo = info->subpasses[i];\r\n\t\t\r\n\t\tVkSubpassDescription subpass;\r\n\r\n\t\tsubpass.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS;\r\n\t\tsubpass.flags = 0;\r\n\t\tsubpass.colorAttachmentCount = ~0;\r\n\t\tsubpass.inputAttachmentCount = ~0;\r\n\t\tsubpass.preserveAttachmentCount = 0;\r\n\t\tsubpass.pInputAttachments = nullptr;\r\n\t\tsubpass.pDepthStencilAttachment = nullptr;\r\n\t\tsubpass.pPreserveAttachments = nullptr;\r\n\t\tsubpass.pResolveAttachments = nullptr;\r\n\r\n\t\tVkAttachmentReference ref;\r\n\r\n\t\tref.layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;\r\n\r\n\t\tfor (uint32 j = 0; j < FD_MAX_ATTACHMENTS; j++) {\r\n\t\t\tref.attachment = subInfo.colorAttachments[j];\r\n\r\n\t\t\tif (ref.attachment == FD_NO_ATTACHMENT) {\r\n\t\t\t\tsubpass.colorAttachmentCount = j;\r\n\t\t\t\tbreak;\r\n\t\t\t} else if (ref.attachment == FD_SWAPCHAIN_ATTACHMENT_INDEX) {\r\n\t\t\t\tref.attachment = swapchainIndex;\r\n\t\t\t\tusesSwapchainImage = true;\r\n\t\t\t}\r\n\r\n\t\t\tif (ref.attachment == info->depthAttachment) {\r\n\t\t\t\tLog::Fatal(\"[RenderPass] Color attachment can't use the same framebuffer as depth\/stencil attachment\");\r\n\t\t\t\treturn;\r\n\t\t\t}\r\n\r\n\t\t\tattachmentReferences.Push_back(ref);\r\n\t\t}\r\n\r\n\t\tif (subpass.colorAttachmentCount == ~0) {\r\n\t\t\tsubpass.colorAttachmentCount = FD_MAX_ATTACHMENTS;\r\n\t\t} else if (subpass.colorAttachmentCount == 0) {\r\n\t\t\tLog::Fatal(\"[RenderPass] No color attachment specified!\");\r\n\t\t\treturn;\r\n\t\t}\r\n\r\n\t\tsubpass.pColorAttachments = &attachmentReferences[attachmentReferences.GetSize() - subpass.colorAttachmentCount];\r\n\r\n\t\tref.layout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;\r\n\r\n\t\tfor (uint32 j = 0; j < FD_MAX_ATTACHMENTS; j++) {\r\n\t\t\tref.attachment = subInfo.inputAttachments[j];\r\n\r\n\t\t\tif (ref.attachment == FD_NO_ATTACHMENT) {\r\n\t\t\t\tsubpass.inputAttachmentCount = j;\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\r\n\t\t\tattachmentReferences.Push_back(ref);\r\n\t\t}\r\n\r\n\t\tif (subpass.inputAttachmentCount == ~0) {\r\n\t\t\tsubpass.inputAttachmentCount = FD_MAX_ATTACHMENTS;\r\n\t\t}\r\n\r\n\t\tif (subpass.inputAttachmentCount != 0) subpass.pInputAttachments = &attachmentReferences[attachmentReferences.GetSize() - subpass.inputAttachmentCount];\r\n\r\n\t\tif (info->depthAttachment != FD_NO_ATTACHMENT) {\r\n\t\t\tsubpass.pDepthStencilAttachment = &attachmentReferences[0];\r\n\t\t}\r\n\t\t\r\n\t\tsubpassDescriptions.Push_back(subpass);\r\n\t}\r\n\r\n\tclearValues.Resize(framebuffers.GetSize());\r\n\r\n\tfor (uint_t i = 0; framebuffers.GetSize(); i++) {\r\n\t\tif (i == info->depthAttachment) {\r\n\t\t\tclearValues[i].depthStencil.depth = info->depthClearValue;\r\n\t\t} else {\r\n\t\t\tmemcpy(&clearValues[i].color, &info->clearColor, sizeof(vec4));\r\n\t\t}\r\n\t}\r\n\r\n\tif (usesSwapchainImage) {\r\n\t\tclearValues.Resize(clearValues.GetSize() + 1);\r\n\t\tmemcpy(&clearValues[swapchainIndex].color, &info->clearColor, sizeof(vec4));\r\n\t}\r\n\r\n\tList<VkSubpassDependency> dependencies;\r\n\r\n\tVkSubpassDependency dep;\r\n\r\n\tdep.srcSubpass = VK_SUBPASS_EXTERNAL;\r\n\tdep.dstSubpass = 1;\r\n\tdep.srcStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;\r\n\tdep.srcAccessMask = 0;\r\n\tdep.dstStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;\r\n\tdep.dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;\r\n\tdep.dependencyFlags = 0;\r\n\t\r\n\tdependencies.Push_back(dep);\r\n\r\n\tfor (uint32 i = 1; i < subpassDescriptions.GetSize(); i++) {\r\n\t\tdep.srcSubpass = i - 1;\r\n\t\tdep.dstSubpass = i;\r\n\r\n\t\tdependencies.Push_back(dep);\r\n\t}\r\n\r\n\tVkRenderPassCreateInfo rinfo;\r\n\r\n\trinfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO;\r\n\trinfo.pNext = nullptr;\r\n\trinfo.flags = 0;\r\n\trinfo.attachmentCount = info->framebuffers.GetSize() + usesSwapchainImage ? 1 : 0;\r\n\trinfo.pAttachments = attachments;\r\n\trinfo.subpassCount = subpassDescriptions.GetSize();\r\n\trinfo.pSubpasses = &subpassDescriptions[0];\r\n\trinfo.dependencyCount = dependencies.GetSize();\r\n\trinfo.pDependencies = &dependencies[0];\r\n\r\n\tVK(vkCreateRenderPass(Context::GetDevice(), &rinfo, nullptr, &renderPass));\r\n\r\n\tVkImageView* imageViews = new VkImageView[framebuffers.GetSize() + 1];\r\n\r\n\tfor (uint_t i = 0; i < framebuffers.GetSize(); i++) {\r\n\t\timageViews[i] = framebuffers[i]->GetImageView();\r\n\t}\r\n\r\n\tfinfo.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO;\r\n\tfinfo.flags = 0;\r\n\tfinfo.layers = 1;\r\n\tfinfo.renderPass = renderPass;\r\n\tfinfo.pAttachments = imageViews;\r\n\t\r\n\tif (usesSwapchainImage) {\r\n\t\tfinfo.width = width = Context::GetSwapchainExtent().width;\r\n\t\tfinfo.height = height = Context::GetSwapchainExtent().height;\r\n\t\tfinfo.attachmentCount = framebuffers.GetSize() + 1;\r\n\r\n\t\tList<VkImageView> swapViews = Context::GetSwapchainImageViews();\r\n\r\n\t\tfor (uint_t i = 0; i < swapViews.GetSize(); i++) {\r\n\t\t\timageViews[swapchainIndex] = swapViews[i];\r\n\r\n\t\t\tVkFramebuffer framebuffer;\r\n\r\n\t\t\tVK(vkCreateFramebuffer(Context::GetDevice(), &finfo, nullptr, &framebuffer));\r\n\r\n\t\t\tframebufferObjects.Push_back(framebuffer);\r\n\t\t}\r\n\r\n\t\tRegister();\r\n\r\n\t} else {\r\n\t\tCheckFramebuffers(framebuffers);\r\n\t\tfinfo.width = width = framebuffers[0]->GetWidth();\r\n\t\tfinfo.height = height = framebuffers[0]->GetHeight();\r\n\t\tfinfo.attachmentCount = framebuffers.GetSize();\r\n\r\n\t\tVkFramebuffer framebuffer;\r\n\r\n\t\tVK(vkCreateFramebuffer(Context::GetDevice(), &finfo, nullptr, &framebuffer));\r\n\r\n\t\tframebufferObjects.Push_back(framebuffer);\r\n\t}\r\n\r\n}\r\n\r\nRenderPass::~RenderPass() {\r\n\tfor (uint_t i = 0; i < framebufferObjects.GetSize(); i++) {\r\n\t\tvkDestroyFramebuffer(Context::GetDevice(), framebufferObjects[i], nullptr);\r\n\t}\r\n\r\n\tvkDestroyRenderPass(Context::GetDevice(), renderPass, nullptr);\r\n\r\n\tdelete info;\r\n}\r\n\r\nvoid RenderPass::InitializeRenderPass(VkRenderPassBeginInfo* const info) const {\r\n\tinfo->clearValueCount = clearValues.GetSize();\r\n\tinfo->pClearValues = clearValues.GetData();\r\n}\r\n\r\nbool RenderPass::OnWindowEventResize(const vec2i& size) {\r\n\tif (info == nullptr) {\r\n\t\tfor (uint_t i = 0; i < framebufferObjects.GetSize(); i++) {\r\n\t\t\tvkDestroyFramebuffer(Context::GetDevice(), framebufferObjects[i], nullptr);\r\n\t\t}\r\n\r\n\t\tframebufferObjects.Clear();\r\n\r\n\t\tconst List<VkImageView>& swapchainViews = Context::GetSwapchainImageViews();\r\n\r\n\t\tfor (uint_t i = 0; i < swapchainViews.GetSize(); i++) {\r\n\t\t\tVkFramebufferCreateInfo info;\r\n\r\n\t\t\tinfo.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO;\r\n\t\t\tinfo.pNext = nullptr;\r\n\t\t\tinfo.flags = 0;\r\n\t\t\tinfo.width = width = size.x;\r\n\t\t\tinfo.height = height = size.y;\r\n\t\t\tinfo.layers = 1;\r\n\t\t\tinfo.renderPass = renderPass;\r\n\t\t\tinfo.attachmentCount = 1;\r\n\t\t\tinfo.pAttachments = &swapchainViews[i];\r\n\r\n\t\t\tVkFramebuffer tmp = nullptr;\r\n\r\n\t\t\tVK(vkCreateFramebuffer(Context::GetDevice(), &info, nullptr, &tmp));\r\n\r\n\t\t\tframebufferObjects.Push_back(tmp);\r\n\t\t}\r\n\t} else {\r\n\t\tfor (uint_t i = 0; i < framebufferObjects.GetSize(); i++) {\r\n\t\t\tvkDestroyFramebuffer(Context::GetDevice(), framebufferObjects[i], nullptr);\r\n\t\t}\r\n\r\n\t\tframebufferObjects.Clear();\r\n\r\n\t\tfinfo.width = width = size.x;\r\n\t\tfinfo.height = height = size.y;\r\n\r\n\t\tList<VkImageView> swapViews = Context::GetSwapchainImageViews();\r\n\r\n\t\tuint64 swapchainIndex = framebuffers.GetSize();\r\n\r\n\t\tVkImageView* imageViews = (VkImageView*)finfo.pAttachments;\r\n\r\n\t\tfor (uint_t i = 0; i < framebuffers.GetSize(); i++) {\r\n\t\t\tframebuffers[i]->Resize(size.x, size.y);\r\n\t\t\timageViews[i] = framebuffers[i]->GetImageView();\r\n\t\t}\r\n\r\n\t\tfor (uint_t i = 0; i < swapViews.GetSize(); i++) {\r\n\t\t\timageViews[swapchainIndex] = swapViews[i];\r\n\r\n\t\t\tVkFramebuffer framebuffer;\r\n\r\n\t\t\tVK(vkCreateFramebuffer(Context::GetDevice(), &finfo, nullptr, &framebuffer));\r\n\r\n\t\t\tframebufferObjects.Push_back(framebuffer);\r\n\t\t}\r\n\t}\r\n\r\n\treturn true;\r\n}\r\n\r\n}\r\n}\r\n}<|endoftext|>"} {"text":"<commit_before>AliGenerator* CreateGenerator();\n\nvoid fastGenDPMjet(Int_t nev = 1, char* filename = \"galice.root\")\n{\n\/\/ Runloader\n\n gSystem->Load(\"libdpmjet.so\");\n gSystem->Load(\"libTDPMjet.so\");\n \n AliRunLoader* rl = AliRunLoader::Open(\"galice.root\",\"FASTRUN\",\"recreate\");\n \n rl->SetCompressionLevel(2);\n rl->SetNumberOfEventsPerFile(nev);\n rl->LoadKinematics(\"RECREATE\");\n rl->MakeTree(\"E\");\n gAlice->SetRunLoader(rl);\n\n\/\/ Create stack\n rl->MakeStack();\n AliStack* stack = rl->Stack();\n \n\/\/ Header\n AliHeader* header = rl->GetHeader();\n\/\/\n\/\/ Create and Initialize Generator\n AliGenerator *gener = CreateGenerator();\n gener->Init();\n gener->SetStack(stack);\n \n\/\/\n\/\/ Event Loop\n\/\/\n Int_t iev;\n \n for (iev = 0; iev < nev; iev++) {\n\n\tprintf(\"\\n \\n Event number %d \\n \\n\", iev);\n\t\n\/\/ Initialize event\n\theader->Reset(0,iev);\n\trl->SetEventNumber(iev);\n\tstack->Reset();\n\trl->MakeTree(\"K\");\n\/\/\tstack->ConnectTree();\n \n\/\/ Generate event\n\tgener->Generate();\n\/\/ Analysis\n\tInt_t npart = stack->GetNprimary();\n\tprintf(\"Analyse %d Particles\\n\", npart);\n\tfor (Int_t part=0; part<npart; part++) {\n\t TParticle *MPart = stack->Particle(part);\n\t Int_t pdg = MPart->GetPdgCode();\n\t Int_t pis = MPart->GetStatusCode();\n\/\/\t printf(\"Particle %5d %5d\\n\", part, pdg, pis);\n\t}\n\t\n\/\/ Finish event\n\theader->SetNprimary(stack->GetNprimary());\n\theader->SetNtrack(stack->GetNtrack()); \n\/\/ I\/O\n\/\/\t\n\tstack->FinishEvent();\n\theader->SetStack(stack);\n\trl->TreeE()->Fill();\n\trl->WriteKinematics(\"OVERWRITE\");\n\n } \/\/ event loop\n\/\/\n\/\/ Termination\n\/\/ Generator\n gener->FinishRun();\n\/\/ Write file\n rl->WriteHeader(\"OVERWRITE\");\n gener->Write();\n rl->Write();\n \n}\n\n\nAliGenerator* CreateGenerator()\n{ \n \/\/ kDpmMb\n \/\/ kDpmMbNonDiffr\n \/\/ kDpmDiffr\n \/\/ kDpmSingleDiffr\n \/\/ kDpmDoubleDiffr\n gener = new AliGenDPMjet(1);\n gener->SetProcess(kDpmMb);\n gener->SetEnergyCMS(14000.);\n return gener;\n}\n\n\n\n\n\n\n\n\n\n\n\n\n<commit_msg>Explicite loading of pythia library (> 6.2 to match with UA5 data)<commit_after>AliGenerator* CreateGenerator();\n\nvoid fastGenDPMjet(Int_t nev = 1, char* filename = \"galice.root\")\n{\n\/\/ Runloader\n gSystem->Load(\"liblhapdf\"); \n gSystem->Load(\"libpythia6\"); \n gSystem->Load(\"libdpmjet.so\");\n gSystem->Load(\"libTDPMjet.so\");\n \n AliRunLoader* rl = AliRunLoader::Open(\"galice.root\",\"FASTRUN\",\"recreate\");\n AliPythiaRndm::SetPythiaRandom(new TRandom());\n\n rl->SetCompressionLevel(2);\n rl->SetNumberOfEventsPerFile(nev);\n rl->LoadKinematics(\"RECREATE\");\n rl->MakeTree(\"E\");\n gAlice->SetRunLoader(rl);\n\n\/\/ Create stack\n rl->MakeStack();\n AliStack* stack = rl->Stack();\n \n\/\/ Header\n AliHeader* header = rl->GetHeader();\n\/\/\n\/\/ Create and Initialize Generator\n AliGenerator *gener = CreateGenerator();\n gener->Init();\n gener->SetStack(stack);\n \n\/\/\n\/\/ Event Loop\n\/\/\n Int_t iev;\n \n for (iev = 0; iev < nev; iev++) {\n\n\tprintf(\"\\n \\n Event number %d \\n \\n\", iev);\n\t\n\/\/ Initialize event\n\theader->Reset(0,iev);\n\trl->SetEventNumber(iev);\n\tstack->Reset();\n\trl->MakeTree(\"K\");\n\/\/\tstack->ConnectTree();\n \n\/\/ Generate event\n\tgener->Generate();\n\/\/ Analysis\n\tInt_t npart = stack->GetNprimary();\n\tprintf(\"Analyse %d Particles\\n\", npart);\n\tfor (Int_t part=0; part<npart; part++) {\n\t TParticle *MPart = stack->Particle(part);\n\t Int_t pdg = MPart->GetPdgCode();\n\t Int_t pis = MPart->GetStatusCode();\n\/\/\t printf(\"Particle %5d %5d\\n\", part, pdg, pis);\n\t}\n\t\n\/\/ Finish event\n\theader->SetNprimary(stack->GetNprimary());\n\theader->SetNtrack(stack->GetNtrack()); \n\/\/ I\/O\n\/\/\t\n\tstack->FinishEvent();\n\theader->SetStack(stack);\n\trl->TreeE()->Fill();\n\trl->WriteKinematics(\"OVERWRITE\");\n\n } \/\/ event loop\n\/\/\n\/\/ Termination\n\/\/ Generator\n gener->FinishRun();\n\/\/ Write file\n rl->WriteHeader(\"OVERWRITE\");\n gener->Write();\n rl->Write();\n \n}\n\n\nAliGenerator* CreateGenerator()\n{ \n \/\/ kDpmMb\n \/\/ kDpmMbNonDiffr\n \/\/ kDpmDiffr\n \/\/ kDpmSingleDiffr\n \/\/ kDpmDoubleDiffr\n gener = new AliGenDPMjet(1);\n gener->SetProcess(kDpmMb);\n gener->SetProjectile(\"P\", 1, 1);\n gener->SetTarget(\"P\", 1, 1);\n gener->SetEnergyCMS(14000.);\n return gener;\n}\n\n\n\n\n\n\n\n\n\n\n\n\n<|endoftext|>"} {"text":"<commit_before>const int sN = 10000000;\nint lp[sN];\nvector<int> pr;\n\nfor (int i = 2; i < sN; i++) {\n\tif (!lp[i]) {\n\t\tlp[i] = i;\n\t\tpr.pb(i);\n\t}\n\tfor (int j = 0; j < pr.size() && pr[j] <= lp[i] && 1ll * i * pr[j] < sN; j++)\n\t\tlp[i * pr[j]] = pr[j];\n}<commit_msg>Fact sieve init<commit_after>const int sN = 10000000;\nint lp[sN];\nvector<int> pr;\n\nbool initSieve() {\n\tfor (int i = 2; i < sN; i++) {\n\t\tif (!lp[i]) {\n\t\t\tlp[i] = i;\n\t\t\tpr.pb(i);\n\t\t}\n\t\tfor (int j = 0; j < pr.size() && pr[j] <= lp[i] && 1ll * i * pr[j] < sN; j++)\n\t\t\tlp[i * pr[j]] = pr[j];\n\t}\n}\nbool sieve = initSieve();<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ Copyright 2014 DreamWorks Animation LLC.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"Apache License\")\n\/\/ with the following modification; you may not use this file except in\n\/\/ compliance with the Apache License and the following modification to it:\n\/\/ Section 6. Trademarks. is deleted and replaced with:\n\/\/\n\/\/ 6. Trademarks. This License does not grant permission to use the trade\n\/\/ names, trademarks, service marks, or product names of the Licensor\n\/\/ and its affiliates, except as required to comply with Section 4(c) of\n\/\/ the License and to reproduce the content of the NOTICE file.\n\/\/\n\/\/ You may obtain a copy of the Apache License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the Apache License with the above modification is\n\/\/ distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n\/\/ KIND, either express or implied. See the Apache License for the specific\n\/\/ language governing permissions and limitations under the Apache License.\n\/\/\n#include \"..\/sdc\/type.h\"\n#include \"..\/sdc\/options.h\"\n#include \"..\/sdc\/crease.h\"\n#include \"..\/vtr\/level.h\"\n#include \"..\/far\/topologyRefiner.h\"\n#include \"..\/far\/topologyRefinerFactory.h\"\n\nnamespace OpenSubdiv {\nnamespace OPENSUBDIV_VERSION {\n\nnamespace Far {\n\n\/\/\n\/\/ Methods for the Factory base class -- general enough to warrant including in\n\/\/ the base class rather than the subclass template (and so replicated for each\n\/\/ usage)\n\/\/\n\/\/\nvoid\nTopologyRefinerFactoryBase::validateComponentTopologySizing(TopologyRefiner& refiner) {\n\n Vtr::Level& baseLevel = refiner.getBaseLevel();\n\n int vCount = baseLevel.getNumVertices();\n int eCount = baseLevel.getNumEdges();\n int fCount = baseLevel.getNumFaces();\n\n assert((vCount > 0) && (fCount > 0));\n\n \/\/\n \/\/ This still needs a little work -- currently we are assuming all counts and offsets\n \/\/ have been assigned, but eventually only the counts will be assigined (in arbitrary\n \/\/ order) and we will need to accumulate the offsets to get the total sizes. That\n \/\/ will require new methods on Vtr::Level -- we do not want direct member access here.\n \/\/\n int fVertCount = 0;\n for (int i = 0; i < fCount; ++i) {\n fVertCount += baseLevel.getNumFaceVertices(i);\n }\n baseLevel.resizeFaceVertices(fVertCount);\n assert(baseLevel.getNumFaceVerticesTotal() > 0);\n\n if (eCount > 0) {\n baseLevel.resizeFaceEdges(baseLevel.getNumFaceVerticesTotal());\n baseLevel.resizeEdgeVertices();\n baseLevel.resizeEdgeFaces( baseLevel.getNumEdgeFaces(eCount-1) + baseLevel.getOffsetOfEdgeFaces(eCount-1));\n baseLevel.resizeVertexFaces(baseLevel.getNumVertexFaces(vCount-1) + baseLevel.getOffsetOfVertexFaces(vCount-1));\n baseLevel.resizeVertexEdges(baseLevel.getNumVertexEdges(vCount-1) + baseLevel.getOffsetOfVertexEdges(vCount-1));\n\n assert(baseLevel.getNumFaceEdgesTotal() > 0);\n assert(baseLevel.getNumEdgeVerticesTotal() > 0);\n assert(baseLevel.getNumEdgeFacesTotal() > 0);\n assert(baseLevel.getNumVertexFacesTotal() > 0);\n assert(baseLevel.getNumVertexEdgesTotal() > 0);\n }\n}\n\nvoid\nTopologyRefinerFactoryBase::validateVertexComponentTopologyAssignment(TopologyRefiner& refiner) {\n\n Vtr::Level& baseLevel = refiner.getBaseLevel();\n\n \/\/\n \/\/ In future we may want the ability to complete aspects of the topology that are incovenient\n \/\/ for clients to specify, e.g. the local indices associated with some relations, orienting\n \/\/ the vertex relations, etc. For the near term we'll be assuming only face-vertices have\n \/\/ been specified and the absence of edges will trigger the construction of everything else:\n \/\/\n bool completeMissingTopology = (baseLevel.getNumEdges() == 0);\n if (completeMissingTopology) {\n \/\/ Need to invoke some Vtr::Level method to \"fill in\" the missing topology...\n baseLevel.completeTopologyFromFaceVertices();\n }\n\n bool applyValidation = false;\n if (applyValidation) {\n if (!baseLevel.validateTopology()) {\n printf(\"Invalid topology detected in TopologyRefinerFactory (%s)\\n\",\n completeMissingTopology ? \"partially specified and completed\" : \"fully specified\");\n \/\/baseLevel.print();\n assert(false);\n }\n }\n}\n\nvoid\nTopologyRefinerFactoryBase::validateFaceVaryingComponentTopologyAssignment(TopologyRefiner& refiner) {\n\n for (int channel=0; channel<refiner.GetNumFVarChannels(); ++channel) {\n refiner.completeFVarChannelTopology(channel);\n }\n}\n\n\/\/\n\/\/ This method combines the initialization of component tags with the sharpening of edges and\n\/\/ vertices according to the given boundary interpolation rule in the Options. Since both\n\/\/ involve traversing the edge and vertex lists and noting the presence of boundaries -- best\n\/\/ to do both at once...\n\/\/\nvoid\nTopologyRefinerFactoryBase::applyComponentTagsAndBoundarySharpness(TopologyRefiner& refiner) {\n\n Vtr::Level& baseLevel = refiner.getBaseLevel();\n\n assert((int)baseLevel._edgeTags.size() == baseLevel.getNumEdges());\n assert((int)baseLevel._vertTags.size() == baseLevel.getNumVertices());\n assert((int)baseLevel._faceTags.size() == baseLevel.getNumFaces());\n\n Sdc::Options options = refiner.GetSchemeOptions();\n Sdc::Crease creasing(options);\n\n bool sharpenCornerVerts = (options.GetVVarBoundaryInterpolation() == Sdc::Options::VVAR_BOUNDARY_EDGE_AND_CORNER);\n bool sharpenNonManFeatures = (options.GetNonManifoldInterpolation() == Sdc::Options::NON_MANIFOLD_SHARP);\n\n \/\/\n \/\/ Process the Edge tags first, as Vertex tags (notably the Rule) are dependent on\n \/\/ properties of their incident edges.\n \/\/\n for (Vtr::Index eIndex = 0; eIndex < baseLevel.getNumEdges(); ++eIndex) {\n Vtr::Level::ETag& eTag = baseLevel._edgeTags[eIndex];\n float& eSharpness = baseLevel._edgeSharpness[eIndex];\n\n eTag._boundary = (baseLevel._edgeFaceCountsAndOffsets[eIndex*2 + 0] < 2);\n if (eTag._boundary || (eTag._nonManifold && sharpenNonManFeatures)) {\n eSharpness = Sdc::Crease::SHARPNESS_INFINITE;\n }\n eTag._infSharp = Sdc::Crease::IsInfinite(eSharpness);\n eTag._semiSharp = Sdc::Crease::IsSharp(eSharpness) && !eTag._infSharp;\n }\n\n \/\/\n \/\/ Process the Vertex tags now -- for some tags (semi-sharp and its rule) we need\n \/\/ to inspect all incident edges:\n \/\/\n for (Vtr::Index vIndex = 0; vIndex < baseLevel.getNumVertices(); ++vIndex) {\n Vtr::Level::VTag& vTag = baseLevel._vertTags[vIndex];\n float& vSharpness = baseLevel._vertSharpness[vIndex];\n\n Vtr::IndexArray const vEdges = baseLevel.getVertexEdges(vIndex);\n Vtr::IndexArray const vFaces = baseLevel.getVertexFaces(vIndex);\n\n \/\/\n \/\/ Take inventory of properties of incident edges that affect this vertex:\n \/\/\n int infSharpEdgeCount = 0;\n int semiSharpEdgeCount = 0;\n int nonManifoldEdgeCount = 0;\n for (int i = 0; i < vEdges.size(); ++i) {\n Vtr::Level::ETag const& eTag = baseLevel._edgeTags[vEdges[i]];\n\n infSharpEdgeCount += eTag._infSharp;\n semiSharpEdgeCount += eTag._semiSharp;\n nonManifoldEdgeCount += eTag._nonManifold;\n }\n int sharpEdgeCount = infSharpEdgeCount + semiSharpEdgeCount;\n\n \/\/\n \/\/ Sharpen the vertex before using it in conjunction with incident edge\n \/\/ properties to determine the semi-sharp tag and rule:\n \/\/\n bool isCorner = (vFaces.size() == 1) && (vEdges.size() == 2);\n if (isCorner && sharpenCornerVerts) {\n vSharpness = Sdc::Crease::SHARPNESS_INFINITE;\n } else if (vTag._nonManifold && sharpenNonManFeatures) {\n \/\/ Don't sharpen the vertex if a non-manifold crease:\n if (nonManifoldEdgeCount != 2) {\n vSharpness = Sdc::Crease::SHARPNESS_INFINITE;\n }\n }\n\n vTag._infSharp = Sdc::Crease::IsInfinite(vSharpness);\n\n vTag._semiSharp = Sdc::Crease::IsSemiSharp(vSharpness) || (semiSharpEdgeCount > 0);\n\n vTag._rule = (Vtr::Level::VTag::VTagSize)creasing.DetermineVertexVertexRule(vSharpness, sharpEdgeCount);\n\n \/\/\n \/\/ Assign topological tags -- note that the \"xordinary\" (or conversely a \"regular\")\n \/\/ tag is still being considered, but regardless, it depends on the Sdc::Scheme...\n \/\/\n assert(refiner.GetSchemeType() == Sdc::TYPE_CATMARK);\n\n vTag._boundary = (vFaces.size() < vEdges.size());\n if (isCorner) {\n vTag._xordinary = !sharpenCornerVerts;\n } else if (vTag._boundary) {\n vTag._xordinary = (vFaces.size() != 2);\n } else {\n vTag._xordinary = (vFaces.size() != 4);\n }\n }\n\n \/\/\n \/\/ Anything more to be done with Face tags? (eventually when processing edits perhaps)\n \/\/\n \/\/ for (Vtr::Index fIndex = 0; fIndex < baseLevel.getNumFaces(); ++fIndex) {\n \/\/ }\n}\n\n\/\/\n\/\/ Specialization for raw topology data\n\/\/\ntemplate <>\nvoid\nTopologyRefinerFactory<TopologyRefinerFactoryBase::TopologyDescriptor>::resizeComponentTopology(\n TopologyRefiner & refiner, TopologyDescriptor const & desc) {\n\n refiner.setNumBaseVertices(desc.numVertices);\n refiner.setNumBaseFaces(desc.numFaces);\n\n for (int face=0; face<desc.numFaces; ++face) {\n\n refiner.setNumBaseFaceVertices(face, desc.vertsPerFace[face]);\n }\n}\n\ntemplate <>\nvoid\nTopologyRefinerFactory<TopologyRefinerFactoryBase::TopologyDescriptor>::assignComponentTopology(\n TopologyRefiner & refiner, TopologyDescriptor const & desc) {\n\n for (int face=0, idx=0; face<desc.numFaces; ++face) {\n\n IndexArray dstFaceVerts = refiner.setBaseFaceVertices(face);\n\n for (int vert=0; vert<dstFaceVerts.size(); ++vert) {\n\n dstFaceVerts[vert] = desc.vertIndices[idx++];\n }\n }\n}\n\ntemplate <>\nvoid\nTopologyRefinerFactory<TopologyRefinerFactoryBase::TopologyDescriptor>::assignFaceVaryingTopology(\n TopologyRefiner & refiner, TopologyDescriptor const & desc) {\n\n if (desc.numFVarChannels>0) {\n\n for (int channel=0; channel<desc.numFVarChannels; ++channel) {\n\n int channelSize = desc.fvarChannels[channel].numValues;\n int const* channelIndices = desc.fvarChannels[channel].valueIndices;\n\n#if defined(DEBUG) or defined(_DEBUG)\n int channelIndex = refiner.createFVarChannel(channelSize);\n assert(channelIndex == channel);\n#else\n refiner.createFVarChannel(channelSize);\n#endif\n for (int face=0, idx=0; face<desc.numFaces; ++face) {\n\n IndexArray dstFaceValues = refiner.getBaseFVarFaceValues(face, channel);\n\n for (int vert=0; vert<dstFaceValues.size(); ++vert) {\n\n dstFaceValues[vert] = channelIndices[idx++];\n }\n }\n }\n }\n}\n\ntemplate <>\nvoid\nTopologyRefinerFactory<TopologyRefinerFactoryBase::TopologyDescriptor>::assignComponentTags(\n TopologyRefiner & refiner, TopologyDescriptor const & desc) {\n\n\n if ((desc.numCreases>0) and desc.creaseVertexIndexPairs and desc.creaseWeights) {\n\n int const * vertIndexPairs = desc.creaseVertexIndexPairs;\n for (int edge=0; edge<desc.numCreases; ++edge, vertIndexPairs+=2) {\n\n Index idx = refiner.FindEdge(0, vertIndexPairs[0], vertIndexPairs[1]);\n\n if (idx!=Vtr::INDEX_INVALID) {\n refiner.baseEdgeSharpness(idx) = desc.creaseWeights[edge];\n } else {\n \/\/ XXXX report error !\n }\n }\n }\n\n if ((desc.numCorners>0) and desc.cornerVertexIndices and desc.cornerWeights) {\n\n for (int vert=0; vert<desc.numCorners; ++vert) {\n\n int idx = desc.cornerVertexIndices[vert];\n\n if (idx < refiner.GetNumVertices(0)) {\n refiner.baseVertexSharpness(idx) = desc.cornerWeights[vert];\n } else {\n \/\/ XXXX report error !\n }\n }\n }\n\n}\n\nTopologyRefinerFactoryBase::TopologyDescriptor::TopologyDescriptor() :\n numVertices(0), numFaces(0), vertsPerFace(0), vertIndices(0),\n numCreases(0), creaseVertexIndexPairs(0), creaseWeights(0),\n numCorners(0), cornerVertexIndices(0), cornerWeights(0),\n numFVarChannels(0), fvarChannels(0) {\n}\n\n} \/\/ end namespace Far\n\n} \/\/ end namespace OPENSUBDIV_VERSION\n} \/\/ end namespace OpenSubdiv\n<commit_msg>Added initialization of Vtr::Level::VTag._incomplete in refiner factory.<commit_after>\/\/\n\/\/ Copyright 2014 DreamWorks Animation LLC.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"Apache License\")\n\/\/ with the following modification; you may not use this file except in\n\/\/ compliance with the Apache License and the following modification to it:\n\/\/ Section 6. Trademarks. is deleted and replaced with:\n\/\/\n\/\/ 6. Trademarks. This License does not grant permission to use the trade\n\/\/ names, trademarks, service marks, or product names of the Licensor\n\/\/ and its affiliates, except as required to comply with Section 4(c) of\n\/\/ the License and to reproduce the content of the NOTICE file.\n\/\/\n\/\/ You may obtain a copy of the Apache License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the Apache License with the above modification is\n\/\/ distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n\/\/ KIND, either express or implied. See the Apache License for the specific\n\/\/ language governing permissions and limitations under the Apache License.\n\/\/\n#include \"..\/sdc\/type.h\"\n#include \"..\/sdc\/options.h\"\n#include \"..\/sdc\/crease.h\"\n#include \"..\/vtr\/level.h\"\n#include \"..\/far\/topologyRefiner.h\"\n#include \"..\/far\/topologyRefinerFactory.h\"\n\nnamespace OpenSubdiv {\nnamespace OPENSUBDIV_VERSION {\n\nnamespace Far {\n\n\/\/\n\/\/ Methods for the Factory base class -- general enough to warrant including in\n\/\/ the base class rather than the subclass template (and so replicated for each\n\/\/ usage)\n\/\/\n\/\/\nvoid\nTopologyRefinerFactoryBase::validateComponentTopologySizing(TopologyRefiner& refiner) {\n\n Vtr::Level& baseLevel = refiner.getBaseLevel();\n\n int vCount = baseLevel.getNumVertices();\n int eCount = baseLevel.getNumEdges();\n int fCount = baseLevel.getNumFaces();\n\n assert((vCount > 0) && (fCount > 0));\n\n \/\/\n \/\/ This still needs a little work -- currently we are assuming all counts and offsets\n \/\/ have been assigned, but eventually only the counts will be assigined (in arbitrary\n \/\/ order) and we will need to accumulate the offsets to get the total sizes. That\n \/\/ will require new methods on Vtr::Level -- we do not want direct member access here.\n \/\/\n int fVertCount = 0;\n for (int i = 0; i < fCount; ++i) {\n fVertCount += baseLevel.getNumFaceVertices(i);\n }\n baseLevel.resizeFaceVertices(fVertCount);\n assert(baseLevel.getNumFaceVerticesTotal() > 0);\n\n if (eCount > 0) {\n baseLevel.resizeFaceEdges(baseLevel.getNumFaceVerticesTotal());\n baseLevel.resizeEdgeVertices();\n baseLevel.resizeEdgeFaces( baseLevel.getNumEdgeFaces(eCount-1) + baseLevel.getOffsetOfEdgeFaces(eCount-1));\n baseLevel.resizeVertexFaces(baseLevel.getNumVertexFaces(vCount-1) + baseLevel.getOffsetOfVertexFaces(vCount-1));\n baseLevel.resizeVertexEdges(baseLevel.getNumVertexEdges(vCount-1) + baseLevel.getOffsetOfVertexEdges(vCount-1));\n\n assert(baseLevel.getNumFaceEdgesTotal() > 0);\n assert(baseLevel.getNumEdgeVerticesTotal() > 0);\n assert(baseLevel.getNumEdgeFacesTotal() > 0);\n assert(baseLevel.getNumVertexFacesTotal() > 0);\n assert(baseLevel.getNumVertexEdgesTotal() > 0);\n }\n}\n\nvoid\nTopologyRefinerFactoryBase::validateVertexComponentTopologyAssignment(TopologyRefiner& refiner) {\n\n Vtr::Level& baseLevel = refiner.getBaseLevel();\n\n \/\/\n \/\/ In future we may want the ability to complete aspects of the topology that are incovenient\n \/\/ for clients to specify, e.g. the local indices associated with some relations, orienting\n \/\/ the vertex relations, etc. For the near term we'll be assuming only face-vertices have\n \/\/ been specified and the absence of edges will trigger the construction of everything else:\n \/\/\n bool completeMissingTopology = (baseLevel.getNumEdges() == 0);\n if (completeMissingTopology) {\n \/\/ Need to invoke some Vtr::Level method to \"fill in\" the missing topology...\n baseLevel.completeTopologyFromFaceVertices();\n }\n\n bool applyValidation = false;\n if (applyValidation) {\n if (!baseLevel.validateTopology()) {\n printf(\"Invalid topology detected in TopologyRefinerFactory (%s)\\n\",\n completeMissingTopology ? \"partially specified and completed\" : \"fully specified\");\n \/\/baseLevel.print();\n assert(false);\n }\n }\n}\n\nvoid\nTopologyRefinerFactoryBase::validateFaceVaryingComponentTopologyAssignment(TopologyRefiner& refiner) {\n\n for (int channel=0; channel<refiner.GetNumFVarChannels(); ++channel) {\n refiner.completeFVarChannelTopology(channel);\n }\n}\n\n\/\/\n\/\/ This method combines the initialization of component tags with the sharpening of edges and\n\/\/ vertices according to the given boundary interpolation rule in the Options. Since both\n\/\/ involve traversing the edge and vertex lists and noting the presence of boundaries -- best\n\/\/ to do both at once...\n\/\/\nvoid\nTopologyRefinerFactoryBase::applyComponentTagsAndBoundarySharpness(TopologyRefiner& refiner) {\n\n Vtr::Level& baseLevel = refiner.getBaseLevel();\n\n assert((int)baseLevel._edgeTags.size() == baseLevel.getNumEdges());\n assert((int)baseLevel._vertTags.size() == baseLevel.getNumVertices());\n assert((int)baseLevel._faceTags.size() == baseLevel.getNumFaces());\n\n Sdc::Options options = refiner.GetSchemeOptions();\n Sdc::Crease creasing(options);\n\n bool sharpenCornerVerts = (options.GetVVarBoundaryInterpolation() == Sdc::Options::VVAR_BOUNDARY_EDGE_AND_CORNER);\n bool sharpenNonManFeatures = (options.GetNonManifoldInterpolation() == Sdc::Options::NON_MANIFOLD_SHARP);\n\n \/\/\n \/\/ Process the Edge tags first, as Vertex tags (notably the Rule) are dependent on\n \/\/ properties of their incident edges.\n \/\/\n for (Vtr::Index eIndex = 0; eIndex < baseLevel.getNumEdges(); ++eIndex) {\n Vtr::Level::ETag& eTag = baseLevel._edgeTags[eIndex];\n float& eSharpness = baseLevel._edgeSharpness[eIndex];\n\n eTag._boundary = (baseLevel._edgeFaceCountsAndOffsets[eIndex*2 + 0] < 2);\n if (eTag._boundary || (eTag._nonManifold && sharpenNonManFeatures)) {\n eSharpness = Sdc::Crease::SHARPNESS_INFINITE;\n }\n eTag._infSharp = Sdc::Crease::IsInfinite(eSharpness);\n eTag._semiSharp = Sdc::Crease::IsSharp(eSharpness) && !eTag._infSharp;\n }\n\n \/\/\n \/\/ Process the Vertex tags now -- for some tags (semi-sharp and its rule) we need\n \/\/ to inspect all incident edges:\n \/\/\n for (Vtr::Index vIndex = 0; vIndex < baseLevel.getNumVertices(); ++vIndex) {\n Vtr::Level::VTag& vTag = baseLevel._vertTags[vIndex];\n float& vSharpness = baseLevel._vertSharpness[vIndex];\n\n Vtr::IndexArray const vEdges = baseLevel.getVertexEdges(vIndex);\n Vtr::IndexArray const vFaces = baseLevel.getVertexFaces(vIndex);\n\n \/\/\n \/\/ Take inventory of properties of incident edges that affect this vertex:\n \/\/\n int infSharpEdgeCount = 0;\n int semiSharpEdgeCount = 0;\n int nonManifoldEdgeCount = 0;\n for (int i = 0; i < vEdges.size(); ++i) {\n Vtr::Level::ETag const& eTag = baseLevel._edgeTags[vEdges[i]];\n\n infSharpEdgeCount += eTag._infSharp;\n semiSharpEdgeCount += eTag._semiSharp;\n nonManifoldEdgeCount += eTag._nonManifold;\n }\n int sharpEdgeCount = infSharpEdgeCount + semiSharpEdgeCount;\n\n \/\/\n \/\/ Sharpen the vertex before using it in conjunction with incident edge\n \/\/ properties to determine the semi-sharp tag and rule:\n \/\/\n bool isCorner = (vFaces.size() == 1) && (vEdges.size() == 2);\n if (isCorner && sharpenCornerVerts) {\n vSharpness = Sdc::Crease::SHARPNESS_INFINITE;\n } else if (vTag._nonManifold && sharpenNonManFeatures) {\n \/\/ Don't sharpen the vertex if a non-manifold crease:\n if (nonManifoldEdgeCount != 2) {\n vSharpness = Sdc::Crease::SHARPNESS_INFINITE;\n }\n }\n\n vTag._infSharp = Sdc::Crease::IsInfinite(vSharpness);\n\n vTag._semiSharp = Sdc::Crease::IsSemiSharp(vSharpness) || (semiSharpEdgeCount > 0);\n\n vTag._rule = (Vtr::Level::VTag::VTagSize)creasing.DetermineVertexVertexRule(vSharpness, sharpEdgeCount);\n\n \/\/\n \/\/ Assign topological tags -- note that the \"xordinary\" (or conversely a \"regular\")\n \/\/ tag is still being considered, but regardless, it depends on the Sdc::Scheme...\n \/\/\n assert(refiner.GetSchemeType() == Sdc::TYPE_CATMARK);\n\n vTag._boundary = (vFaces.size() < vEdges.size());\n if (isCorner) {\n vTag._xordinary = !sharpenCornerVerts;\n } else if (vTag._boundary) {\n vTag._xordinary = (vFaces.size() != 2);\n } else {\n vTag._xordinary = (vFaces.size() != 4);\n }\n vTag._incomplete = 0;\n }\n\n \/\/\n \/\/ Anything more to be done with Face tags? (eventually when processing edits perhaps)\n \/\/\n \/\/ for (Vtr::Index fIndex = 0; fIndex < baseLevel.getNumFaces(); ++fIndex) {\n \/\/ }\n}\n\n\/\/\n\/\/ Specialization for raw topology data\n\/\/\ntemplate <>\nvoid\nTopologyRefinerFactory<TopologyRefinerFactoryBase::TopologyDescriptor>::resizeComponentTopology(\n TopologyRefiner & refiner, TopologyDescriptor const & desc) {\n\n refiner.setNumBaseVertices(desc.numVertices);\n refiner.setNumBaseFaces(desc.numFaces);\n\n for (int face=0; face<desc.numFaces; ++face) {\n\n refiner.setNumBaseFaceVertices(face, desc.vertsPerFace[face]);\n }\n}\n\ntemplate <>\nvoid\nTopologyRefinerFactory<TopologyRefinerFactoryBase::TopologyDescriptor>::assignComponentTopology(\n TopologyRefiner & refiner, TopologyDescriptor const & desc) {\n\n for (int face=0, idx=0; face<desc.numFaces; ++face) {\n\n IndexArray dstFaceVerts = refiner.setBaseFaceVertices(face);\n\n for (int vert=0; vert<dstFaceVerts.size(); ++vert) {\n\n dstFaceVerts[vert] = desc.vertIndices[idx++];\n }\n }\n}\n\ntemplate <>\nvoid\nTopologyRefinerFactory<TopologyRefinerFactoryBase::TopologyDescriptor>::assignFaceVaryingTopology(\n TopologyRefiner & refiner, TopologyDescriptor const & desc) {\n\n if (desc.numFVarChannels>0) {\n\n for (int channel=0; channel<desc.numFVarChannels; ++channel) {\n\n int channelSize = desc.fvarChannels[channel].numValues;\n int const* channelIndices = desc.fvarChannels[channel].valueIndices;\n\n#if defined(DEBUG) or defined(_DEBUG)\n int channelIndex = refiner.createFVarChannel(channelSize);\n assert(channelIndex == channel);\n#else\n refiner.createFVarChannel(channelSize);\n#endif\n for (int face=0, idx=0; face<desc.numFaces; ++face) {\n\n IndexArray dstFaceValues = refiner.getBaseFVarFaceValues(face, channel);\n\n for (int vert=0; vert<dstFaceValues.size(); ++vert) {\n\n dstFaceValues[vert] = channelIndices[idx++];\n }\n }\n }\n }\n}\n\ntemplate <>\nvoid\nTopologyRefinerFactory<TopologyRefinerFactoryBase::TopologyDescriptor>::assignComponentTags(\n TopologyRefiner & refiner, TopologyDescriptor const & desc) {\n\n\n if ((desc.numCreases>0) and desc.creaseVertexIndexPairs and desc.creaseWeights) {\n\n int const * vertIndexPairs = desc.creaseVertexIndexPairs;\n for (int edge=0; edge<desc.numCreases; ++edge, vertIndexPairs+=2) {\n\n Index idx = refiner.FindEdge(0, vertIndexPairs[0], vertIndexPairs[1]);\n\n if (idx!=Vtr::INDEX_INVALID) {\n refiner.baseEdgeSharpness(idx) = desc.creaseWeights[edge];\n } else {\n \/\/ XXXX report error !\n }\n }\n }\n\n if ((desc.numCorners>0) and desc.cornerVertexIndices and desc.cornerWeights) {\n\n for (int vert=0; vert<desc.numCorners; ++vert) {\n\n int idx = desc.cornerVertexIndices[vert];\n\n if (idx < refiner.GetNumVertices(0)) {\n refiner.baseVertexSharpness(idx) = desc.cornerWeights[vert];\n } else {\n \/\/ XXXX report error !\n }\n }\n }\n\n}\n\nTopologyRefinerFactoryBase::TopologyDescriptor::TopologyDescriptor() :\n numVertices(0), numFaces(0), vertsPerFace(0), vertIndices(0),\n numCreases(0), creaseVertexIndexPairs(0), creaseWeights(0),\n numCorners(0), cornerVertexIndices(0), cornerWeights(0),\n numFVarChannels(0), fvarChannels(0) {\n}\n\n} \/\/ end namespace Far\n\n} \/\/ end namespace OPENSUBDIV_VERSION\n} \/\/ end namespace OpenSubdiv\n<|endoftext|>"} {"text":"<commit_before>#include \"listener.h\"\n#include \"log.h\"\n#include \"buffers.h\"\n\nbool conditionalEnqueue(QUEUE_TYPE(uint8_t)* queue, uint8_t* message,\n int messageSize) {\n if(queue_available(queue) < messageSize + 2) {\n return false;\n }\n\n for(int i = 0; i < messageSize; i++) {\n QUEUE_PUSH(uint8_t, queue, (uint8_t)message[i]);\n }\n QUEUE_PUSH(uint8_t, queue, (uint8_t)'\\r');\n QUEUE_PUSH(uint8_t, queue, (uint8_t)'\\n');\n return true;\n}\n\nvoid sendMessage(Listener* listener, uint8_t* message, int messageSize) {\n if(!conditionalEnqueue(&listener->usb->sendQueue, message, messageSize)) {\n debug(\"USB send queue full, dropping CAN message: %s\\r\\n\", message);\n }\n\n if(!conditionalEnqueue(&listener->serial->sendQueue, message, messageSize)) {\n debug(\"UART send queue full, dropping CAN message: %s\\r\\n\", message);\n }\n}\n\nvoid processListenerQueues(Listener* listener) {\n \/\/ Must always process USB, because this function usually runs the MCU's USB\n \/\/ task that handles SETUP and enumeration.\n processInputQueue(listener->usb);\n processInputQueue(listener->serial);\n}\n<commit_msg>Only enqueue for USB if it's actually connected.<commit_after>#include \"listener.h\"\n#include \"log.h\"\n#include \"buffers.h\"\n\nbool conditionalEnqueue(QUEUE_TYPE(uint8_t)* queue, uint8_t* message,\n int messageSize) {\n if(queue_available(queue) < messageSize + 2) {\n return false;\n }\n\n for(int i = 0; i < messageSize; i++) {\n QUEUE_PUSH(uint8_t, queue, (uint8_t)message[i]);\n }\n QUEUE_PUSH(uint8_t, queue, (uint8_t)'\\r');\n QUEUE_PUSH(uint8_t, queue, (uint8_t)'\\n');\n return true;\n}\n\nvoid sendMessage(Listener* listener, uint8_t* message, int messageSize) {\n if(listener->usb->configured && !conditionalEnqueue(\n &listener->usb->sendQueue, message, messageSize)) {\n debug(\"USB send queue full, dropping CAN message: %s\\r\\n\", message);\n }\n\n if(!conditionalEnqueue(&listener->serial->sendQueue, message, messageSize)) {\n debug(\"UART send queue full, dropping CAN message: %s\\r\\n\", message);\n }\n}\n\nvoid processListenerQueues(Listener* listener) {\n \/\/ Must always process USB, because this function usually runs the MCU's USB\n \/\/ task that handles SETUP and enumeration.\n processInputQueue(listener->usb);\n processInputQueue(listener->serial);\n}\n<|endoftext|>"} {"text":"<commit_before>\/** @file\n\n A brief file description\n\n @section license License\n\n Licensed to the Apache Software Foundation (ASF) under one\n or more contributor license agreements. See the NOTICE file\n distributed with this work for additional information\n regarding copyright ownership. The ASF licenses this file\n to you under the Apache License, Version 2.0 (the\n \"License\"); you may not use this file except in compliance\n with the License. You may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n *\/\n\n#include \"P_EventSystem.h\" \/* MAGIC_EDITING_TAG *\/\n#include <sched.h>\n#if TS_USE_HWLOC\n#if HAVE_ALLOCA_H\n#include <alloca.h>\n#endif\n#include <hwloc.h>\n#endif\n#include \"ts\/ink_defs.h\"\n#include \"ts\/hugepages.h\"\n\nEventType\nEventProcessor::spawn_event_threads(int n_threads, const char *et_name, size_t stacksize)\n{\n char thr_name[MAX_THREAD_NAME_LENGTH];\n EventType new_thread_group_id;\n int i;\n\n ink_release_assert(n_threads > 0);\n ink_release_assert((n_ethreads + n_threads) <= MAX_EVENT_THREADS);\n ink_release_assert(n_thread_groups < MAX_EVENT_TYPES);\n\n new_thread_group_id = (EventType)n_thread_groups;\n\n for (i = 0; i < n_threads; i++) {\n EThread *t = new EThread(REGULAR, n_ethreads + i);\n all_ethreads[n_ethreads + i] = t;\n eventthread[new_thread_group_id][i] = t;\n t->set_event_type(new_thread_group_id);\n }\n\n n_threads_for_type[new_thread_group_id] = n_threads;\n for (i = 0; i < n_threads; i++) {\n snprintf(thr_name, MAX_THREAD_NAME_LENGTH, \"[%s %d]\", et_name, i);\n eventthread[new_thread_group_id][i]->start(thr_name, stacksize);\n }\n\n n_thread_groups++;\n n_ethreads += n_threads;\n Debug(\"iocore_thread\", \"Created thread group '%s' id %d with %d threads\", et_name, new_thread_group_id, n_threads);\n\n return new_thread_group_id;\n}\n\nclass EventProcessor eventProcessor;\n\nint\nEventProcessor::start(int n_event_threads, size_t stacksize)\n{\n char thr_name[MAX_THREAD_NAME_LENGTH];\n int i;\n\n \/\/ do some sanity checking.\n static int started = 0;\n ink_release_assert(!started);\n ink_release_assert(n_event_threads > 0 && n_event_threads <= MAX_EVENT_THREADS);\n started = 1;\n\n n_ethreads = n_event_threads;\n n_thread_groups = 1;\n\n \/\/ Make sure that our thread stack size is at least the minimum size\n stacksize = MAX(stacksize, INK_THREAD_STACK_MIN);\n\n \/\/ Make sure it is a multiple of our page size\n if (ats_hugepage_enabled()) {\n stacksize = INK_ALIGN(stacksize, ats_hugepage_size());\n } else {\n stacksize = INK_ALIGN(stacksize, ats_pagesize());\n }\n\n for (i = 0; i < n_event_threads; i++) {\n EThread *t = new EThread(REGULAR, i);\n if (i == 0) {\n ink_thread_setspecific(Thread::thread_data_key, t);\n Thread::get_hrtime_updated();\n }\n all_ethreads[i] = t;\n\n eventthread[ET_CALL][i] = t;\n t->set_event_type((EventType)ET_CALL);\n }\n n_threads_for_type[ET_CALL] = n_event_threads;\n\n#if TS_USE_HWLOC\n int affinity = 1;\n REC_ReadConfigInteger(affinity, \"proxy.config.exec_thread.affinity\");\n hwloc_obj_t obj;\n hwloc_obj_type_t obj_type;\n int obj_count = 0;\n char *obj_name;\n\n switch (affinity) {\n case 4: \/\/ assign threads to logical processing units\n\/\/ Older versions of libhwloc (eg. Ubuntu 10.04) don't have HWLOC_OBJ_PU.\n#if HAVE_HWLOC_OBJ_PU\n obj_type = HWLOC_OBJ_PU;\n obj_name = (char *)\"Logical Processor\";\n break;\n#endif\n case 3: \/\/ assign threads to real cores\n obj_type = HWLOC_OBJ_CORE;\n obj_name = (char *)\"Core\";\n break;\n case 1: \/\/ assign threads to NUMA nodes (often 1:1 with sockets)\n obj_type = HWLOC_OBJ_NODE;\n obj_name = (char *)\"NUMA Node\";\n if (hwloc_get_nbobjs_by_type(ink_get_topology(), obj_type) > 0) {\n break;\n }\n case 2: \/\/ assign threads to sockets\n obj_type = HWLOC_OBJ_SOCKET;\n obj_name = (char *)\"Socket\";\n break;\n default: \/\/ assign threads to the machine as a whole (a level below SYSTEM)\n obj_type = HWLOC_OBJ_MACHINE;\n obj_name = (char *)\"Machine\";\n }\n\n obj_count = hwloc_get_nbobjs_by_type(ink_get_topology(), obj_type);\n Debug(\"iocore_thread\", \"Affinity: %d %ss: %d PU: %d\", affinity, obj_name, obj_count, ink_number_of_processors());\n\n#endif\n for (i = 0; i < n_ethreads; i++) {\n ink_thread tid;\n if (i > 0) {\n snprintf(thr_name, MAX_THREAD_NAME_LENGTH, \"[ET_NET %d]\", i);\n tid = all_ethreads[i]->start(thr_name, stacksize);\n } else {\n tid = ink_thread_self();\n }\n#if TS_USE_HWLOC\n if (obj_count > 0) {\n obj = hwloc_get_obj_by_type(ink_get_topology(), obj_type, i % obj_count);\n#if HWLOC_API_VERSION >= 0x00010100\n int cpu_mask_len = hwloc_bitmap_snprintf(NULL, 0, obj->cpuset) + 1;\n char *cpu_mask = (char *)alloca(cpu_mask_len);\n hwloc_bitmap_snprintf(cpu_mask, cpu_mask_len, obj->cpuset);\n Debug(\"iocore_thread\", \"EThread: %d %s: %d CPU Mask: %s\", i, obj_name, obj->logical_index, cpu_mask);\n#else\n Debug(\"iocore_thread\", \"EThread: %d %s: %d\", i, obj_name, obj->logical_index);\n#endif \/\/ HWLOC_API_VERSION\n hwloc_set_thread_cpubind(ink_get_topology(), tid, obj->cpuset, HWLOC_CPUBIND_STRICT);\n } else {\n Warning(\"hwloc returned an unexpected value -- CPU affinity disabled\");\n }\n#else\n (void)tid;\n#endif \/\/ TS_USE_HWLOC\n }\n\n Debug(\"iocore_thread\", \"Created event thread group id %d with %d threads\", ET_CALL, n_event_threads);\n return 0;\n}\n\nvoid\nEventProcessor::shutdown()\n{\n}\n\nEvent *\nEventProcessor::spawn_thread(Continuation *cont, const char *thr_name, size_t stacksize)\n{\n ink_release_assert(n_dthreads < MAX_EVENT_THREADS);\n Event *e = eventAllocator.alloc();\n\n e->init(cont, 0, 0);\n all_dthreads[n_dthreads] = new EThread(DEDICATED, e);\n e->ethread = all_dthreads[n_dthreads];\n e->mutex = e->continuation->mutex = all_dthreads[n_dthreads]->mutex;\n n_dthreads++;\n e->ethread->start(thr_name, stacksize);\n\n return e;\n}\n<commit_msg>TS-4806: Allocate thread stacks on corresponding NUMA nodes.<commit_after>\/** @file\n\n A brief file description\n\n @section license License\n\n Licensed to the Apache Software Foundation (ASF) under one\n or more contributor license agreements. See the NOTICE file\n distributed with this work for additional information\n regarding copyright ownership. The ASF licenses this file\n to you under the Apache License, Version 2.0 (the\n \"License\"); you may not use this file except in compliance\n with the License. You may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n *\/\n\n#include \"P_EventSystem.h\" \/* MAGIC_EDITING_TAG *\/\n#include <sched.h>\n#if TS_USE_HWLOC\n#if HAVE_ALLOCA_H\n#include <alloca.h>\n#endif\n#include <hwloc.h>\n#endif\n#include \"ts\/ink_defs.h\"\n#include \"ts\/hugepages.h\"\n\nEventType\nEventProcessor::spawn_event_threads(int n_threads, const char *et_name, size_t stacksize)\n{\n char thr_name[MAX_THREAD_NAME_LENGTH];\n EventType new_thread_group_id;\n int i;\n\n ink_release_assert(n_threads > 0);\n ink_release_assert((n_ethreads + n_threads) <= MAX_EVENT_THREADS);\n ink_release_assert(n_thread_groups < MAX_EVENT_TYPES);\n\n new_thread_group_id = (EventType)n_thread_groups;\n\n for (i = 0; i < n_threads; i++) {\n EThread *t = new EThread(REGULAR, n_ethreads + i);\n all_ethreads[n_ethreads + i] = t;\n eventthread[new_thread_group_id][i] = t;\n t->set_event_type(new_thread_group_id);\n }\n\n n_threads_for_type[new_thread_group_id] = n_threads;\n for (i = 0; i < n_threads; i++) {\n snprintf(thr_name, MAX_THREAD_NAME_LENGTH, \"[%s %d]\", et_name, i);\n eventthread[new_thread_group_id][i]->start(thr_name, stacksize);\n }\n\n n_thread_groups++;\n n_ethreads += n_threads;\n Debug(\"iocore_thread\", \"Created thread group '%s' id %d with %d threads\", et_name, new_thread_group_id, n_threads);\n\n return new_thread_group_id;\n}\n\nclass EventProcessor eventProcessor;\n\nint\nEventProcessor::start(int n_event_threads, size_t stacksize)\n{\n char thr_name[MAX_THREAD_NAME_LENGTH];\n int i;\n void *stack = NULL;\n\n \/\/ do some sanity checking.\n static int started = 0;\n ink_release_assert(!started);\n ink_release_assert(n_event_threads > 0 && n_event_threads <= MAX_EVENT_THREADS);\n started = 1;\n\n n_ethreads = n_event_threads;\n n_thread_groups = 1;\n\n \/\/ Make sure that our thread stack size is at least the minimum size\n stacksize = MAX(stacksize, INK_THREAD_STACK_MIN);\n\n \/\/ Make sure it is a multiple of our page size\n if (ats_hugepage_enabled()) {\n stacksize = INK_ALIGN(stacksize, ats_hugepage_size());\n } else {\n stacksize = INK_ALIGN(stacksize, ats_pagesize());\n }\n\n for (i = 0; i < n_event_threads; i++) {\n EThread *t = new EThread(REGULAR, i);\n if (i == 0) {\n ink_thread_setspecific(Thread::thread_data_key, t);\n Thread::get_hrtime_updated();\n }\n all_ethreads[i] = t;\n\n eventthread[ET_CALL][i] = t;\n t->set_event_type((EventType)ET_CALL);\n }\n n_threads_for_type[ET_CALL] = n_event_threads;\n\n#if TS_USE_HWLOC\n int affinity = 1;\n REC_ReadConfigInteger(affinity, \"proxy.config.exec_thread.affinity\");\n hwloc_obj_t obj;\n hwloc_obj_type_t obj_type;\n int obj_count = 0;\n char *obj_name;\n\n switch (affinity) {\n case 4: \/\/ assign threads to logical processing units\n\/\/ Older versions of libhwloc (eg. Ubuntu 10.04) don't have HWLOC_OBJ_PU.\n#if HAVE_HWLOC_OBJ_PU\n obj_type = HWLOC_OBJ_PU;\n obj_name = (char *)\"Logical Processor\";\n break;\n#endif\n case 3: \/\/ assign threads to real cores\n obj_type = HWLOC_OBJ_CORE;\n obj_name = (char *)\"Core\";\n break;\n case 1: \/\/ assign threads to NUMA nodes (often 1:1 with sockets)\n obj_type = HWLOC_OBJ_NODE;\n obj_name = (char *)\"NUMA Node\";\n if (hwloc_get_nbobjs_by_type(ink_get_topology(), obj_type) > 0) {\n break;\n }\n case 2: \/\/ assign threads to sockets\n obj_type = HWLOC_OBJ_SOCKET;\n obj_name = (char *)\"Socket\";\n break;\n default: \/\/ assign threads to the machine as a whole (a level below SYSTEM)\n obj_type = HWLOC_OBJ_MACHINE;\n obj_name = (char *)\"Machine\";\n }\n\n obj_count = hwloc_get_nbobjs_by_type(ink_get_topology(), obj_type);\n Debug(\"iocore_thread\", \"Affinity: %d %ss: %d PU: %d\", affinity, obj_name, obj_count, ink_number_of_processors());\n\n#endif\n for (i = 0; i < n_ethreads; i++) {\n ink_thread tid;\n\n#if TS_USE_HWLOC\n if (obj_count > 0) {\n obj = hwloc_get_obj_by_type(ink_get_topology(), obj_type, i % obj_count);\n#if HWLOC_API_VERSION >= 0x00010100\n int cpu_mask_len = hwloc_bitmap_snprintf(NULL, 0, obj->cpuset) + 1;\n char *cpu_mask = (char *)alloca(cpu_mask_len);\n hwloc_bitmap_snprintf(cpu_mask, cpu_mask_len, obj->cpuset);\n Debug(\"iocore_thread\", \"EThread: %d %s: %d CPU Mask: %s\", i, obj_name, obj->logical_index, cpu_mask);\n#else\n Debug(\"iocore_thread\", \"EThread: %d %s: %d\", i, obj_name, obj->logical_index);\n#endif \/\/ HWLOC_API_VERSION\n }\n#endif \/\/ TS_USE_HWLOC\n\n if (i > 0) {\n snprintf(thr_name, MAX_THREAD_NAME_LENGTH, \"[ET_NET %d]\", i);\n#if TS_USE_HWLOC\n if (obj_count > 0) {\n hwloc_nodeset_t nodeset = hwloc_bitmap_alloc();\n\n hwloc_cpuset_to_nodeset(ink_get_topology(), obj->cpuset, nodeset);\n\n if (hwloc_get_nbobjs_inside_cpuset_by_type(ink_get_topology(), obj->cpuset, HWLOC_OBJ_NODE) == 1) {\n stack = hwloc_alloc_membind_nodeset(ink_get_topology(), stacksize, nodeset, HWLOC_MEMBIND_BIND, 0);\n } else if (hwloc_get_nbobjs_inside_cpuset_by_type(ink_get_topology(), obj->cpuset, HWLOC_OBJ_NODE) > 1) {\n stack = hwloc_alloc_membind_nodeset(ink_get_topology(), stacksize, nodeset, HWLOC_MEMBIND_INTERLEAVE, 0);\n } else {\n stack = NULL;\n }\n\n hwloc_bitmap_free(nodeset);\n }\n#endif \/\/ TS_USE_HWLOC\n tid = all_ethreads[i]->start(thr_name, stacksize, NULL, stack);\n } else {\n \/\/ We should stop using this thread like this and create a new one and have the master thread just join all these and block\n \/\/ indefinitely.\n tid = ink_thread_self();\n }\n\n#if TS_USE_HWLOC\n if (obj_count > 0) {\n hwloc_set_thread_cpubind(ink_get_topology(), tid, obj->cpuset, HWLOC_CPUBIND_STRICT);\n } else {\n Warning(\"hwloc returned an unexpected value -- CPU affinity disabled\");\n }\n#else\n (void)tid;\n#endif \/\/ TS_USE_HWLOC\n }\n\n Debug(\"iocore_thread\", \"Created event thread group id %d with %d threads\", ET_CALL, n_event_threads);\n return 0;\n}\n\nvoid\nEventProcessor::shutdown()\n{\n}\n\nEvent *\nEventProcessor::spawn_thread(Continuation *cont, const char *thr_name, size_t stacksize)\n{\n ink_release_assert(n_dthreads < MAX_EVENT_THREADS);\n Event *e = eventAllocator.alloc();\n\n e->init(cont, 0, 0);\n all_dthreads[n_dthreads] = new EThread(DEDICATED, e);\n e->ethread = all_dthreads[n_dthreads];\n e->mutex = e->continuation->mutex = all_dthreads[n_dthreads]->mutex;\n n_dthreads++;\n e->ethread->start(thr_name, stacksize);\n\n return e;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ SkipGramCpp.cpp\n\/\/ dopamine\n\/\/\n\/\/ Created by 佐原 瑠能 on 2017\/05\/31.\n\/\/ Copyright © 2017年 Runo. All rights reserved.\n\/\/\n\n#include <cstring>\n#include <cmath>\n#include <random>\n\nextern \"C\" {\n\t\n#include \"FloatBufferCpp.hpp\"\n#include \"SkipGramCpp.hpp\"\n\n#define EXPTABLE_SIZE\t\t1000\n#define EXPTABLE_INPUTMAX\t6.0f\n\nfloat* _SkipGram_ExpTable = NULL;\n\t\nvoid _SkipGram_GlobalInit() {\n\t\n\t\/\/ exp\/(exp+1)の計算テーブル\n\tif (_SkipGram_ExpTable == nullptr) {\n\t\t_SkipGram_ExpTable = (float*)malloc(EXPTABLE_SIZE * sizeof(float));\n\t\tfor (int tableIndex = 0; tableIndex < EXPTABLE_SIZE; tableIndex++) {\n\t\t\tfloat input = (((float)tableIndex) \/ ((float)EXPTABLE_SIZE)) * (EXPTABLE_INPUTMAX * 2.0f) - EXPTABLE_INPUTMAX;\n\t\t\tfloat val = expf(input);\n\t\t\t_SkipGram_ExpTable[tableIndex] = val \/ (val + 1.0f);\n\t\t}\n\t}\n\t\n}\n\nvoid _SkipGram_TrainInit(int* itemSequenceBuffer, int itemSequenceBufferLength, int* itemSequenceOffsetArray, int* itemSequencesCount, float* itemNegLotteryInfoArray, int* itemsCount) {\n\n\tint maxItemSequencesCount = *itemSequencesCount;\n\tint maxItemsCount = *itemsCount;\n\t\n\tif (maxItemSequencesCount == 0 || maxItemsCount == 0) {\n\t\t*itemSequencesCount = 0;\n\t\t*itemsCount = 0;\n\t\treturn;\n\t}\n\t\n\tint maxItemIndex = 0;\n\tmemset(itemNegLotteryInfoArray, 0, maxItemsCount * sizeof (float));\n\titemSequenceOffsetArray[0] = 0;\n\tint curItemSequenceIndex = 1;\n\n\t\/\/ バッファーを列挙する\n\tint* itemSequenceHead = itemSequenceBuffer;\n\tint* itemSequenceBufferEnd = itemSequenceBuffer + itemSequenceBufferLength;\n\tfor (; itemSequenceHead < itemSequenceBufferEnd; itemSequenceHead++) {\n\n\t\tint itemIndex = *itemSequenceHead;\n\t\t\n\t\t\/\/ シーケンスの終了チェック\n\t\tif (itemIndex < 0) {\n\t\t\t\n\t\t\t\/\/ 最後のシーケンス\n\t\t\tif (itemSequenceHead + 1 == itemSequenceBufferEnd\n\t\t\t\t|| maxItemSequencesCount == curItemSequenceIndex) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\t\n\t\t\titemSequenceOffsetArray[curItemSequenceIndex] = (int)(itemSequenceHead - itemSequenceBuffer) + 1;\n\t\t\tcurItemSequenceIndex++;\n\t\t}\n\t\t\n\t\t\/\/ アイテムIDの上限チェック\n\t\tif (itemIndex >= maxItemsCount) {\n\t\t\tbreak;\n\t\t}\n\t\t\n\t\t\/\/ 最大値更新\n\t\tif (itemIndex > maxItemIndex) {\n\t\t\tmaxItemIndex = itemIndex;\n\t\t}\n\t\t\n\t\t\/\/ アイテムをカウント\n\t\titemNegLotteryInfoArray[itemIndex] += 1.0f;\n\t}\n\n\t\/\/ 結果を設定\n\t*itemSequencesCount = curItemSequenceIndex;\n\tint actualItemsCount = maxItemIndex + 1;\n\t*itemsCount = actualItemsCount;\n\n\t\/\/ 抽選データを準備\n\tfloat sum = 0.0f;\n\tfloat* itemNegLotteryInfoEnd = itemNegLotteryInfoArray + actualItemsCount;\n\tfor (float* head = itemNegLotteryInfoArray; head < itemNegLotteryInfoEnd; head++) {\n\t\t*head = powf(*head, 0.75f);\n\t\tsum += *head;\n\t}\n\tfloat sumInv = 1.0f \/ sum;\n\tfloat acc = 0.0f;\n\tfor (float* head = itemNegLotteryInfoArray; head < itemNegLotteryInfoEnd; head++) {\n\t\tacc += *head * sumInv;\n\t\t*head = acc;\n\t}\n}\n\ninline int _SkipGram_RandomNegativeItemIndex(float* itemNegLotteryInfoArray, int itemsCount, float randVal) {\n\n\tint minIndex = 0;\n\tint maxIndex = itemsCount - 1;\n\twhile (minIndex < maxIndex) {\n\t\tint testIndex = (minIndex + maxIndex) \/ 2;\n\t\tfloat testVal = itemNegLotteryInfoArray[testIndex];\n\t\tif (randVal < testVal) {\n\t\t\tmaxIndex = testIndex - 1;\n\t\t} else {\n\t\t\tminIndex = testIndex + 1;\n\t\t}\n\t}\n\treturn maxIndex;\n}\n\t\ninline float _SkipGram_ExpTableOutput(float input) {\n\n\tint tableIndex = (input + EXPTABLE_INPUTMAX) * (((float)EXPTABLE_SIZE) \/ EXPTABLE_INPUTMAX \/ 2.0f);\n\tif (tableIndex < 0)\n\t\treturn 0.0f;\n\tif (tableIndex >= EXPTABLE_SIZE)\n\t\treturn 1.0f;\n\t\n\treturn _SkipGram_ExpTable[tableIndex];\n}\n\nvoid _SkipGram_TrainIterate(int* itemSequenceBuffer, int* itemSequenceOffsetArray, int itemSequencesCount, float* itemNegLotteryInfoArray, int itemsCount, int itemVectorSize, float* weightBuffer, float* negWeightBuffer, float* tempItemVector, int windowSize, int negativeSamplingCount, float learningRate, int iterationsCount) {\n\t\n\tstd::random_device dev;\n\tstd::mt19937 gen(dev());\n\tstd::uniform_real_distribution<float> dist(0.0f, itemNegLotteryInfoArray[itemsCount - 1]);\n\n\twhile (iterationsCount--) { \/\/ For each iteration.\n\t\tfor (int itemSequenceIndex = 0; itemSequenceIndex < itemSequencesCount; itemSequenceIndex++) { \/\/ For each sequence.\n\t\t\t\n\t\t\tint* itemSequenceStart = itemSequenceBuffer + itemSequenceOffsetArray[itemSequenceIndex];\n\t\t\tfor (int* headItem = itemSequenceStart; ; headItem++) { \/\/ For each item.\n\t\t\t\tint itemIndex = *headItem;\n\t\t\t\tif (itemIndex < 0) {\n\t\t\t\t\tbreak; \/\/ End of sequence.\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tint* headRelated = headItem - windowSize;\n\t\t\t\tint* headRelatedEnd = headItem + windowSize;\n\t\t\t\tif (headRelated < itemSequenceStart) {\n\t\t\t\t\theadRelated = itemSequenceStart;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tfor (; headRelated <= headRelatedEnd; headRelated++) { \/\/ For each related item.\n\t\t\t\t\tint relatedItemIndex = *headRelated;\n\t\t\t\t\tif (relatedItemIndex == itemIndex) {\n\t\t\t\t\t\tcontinue; \/\/ Skip center item.\n\t\t\t\t\t}\n\t\t\t\t\tif (relatedItemIndex < 0) {\n\t\t\t\t\t\tbreak; \/\/ End of sequence.\n\t\t\t\t\t}\n\n\t\t\t\t\tmemset(tempItemVector, 0, itemVectorSize * sizeof (float));\n\t\t\t\t\t\n\t\t\t\t\tfloat* relatedVector = weightBuffer + (itemVectorSize * relatedItemIndex);\n\t\t\t\t\t\n\t\t\t\t\t\/\/ Positive sampling, then negative sampling.\n\t\t\t\t\tfloat label;\n\t\t\t\t\tint targetItemIndex;\n\t\t\t\t\tfor (int negativeSamplingIndex = -1; negativeSamplingIndex < negativeSamplingCount; negativeSamplingIndex++) { \/\/ For each (positive\/negative) sampling.\n\t\t\t\t\t\t\n\t\t\t\t\t\tif (negativeSamplingIndex == -1) {\n\t\t\t\t\t\t\ttargetItemIndex = itemIndex;\n\t\t\t\t\t\t\tlabel = 1.0f;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\ttargetItemIndex = _SkipGram_RandomNegativeItemIndex(itemNegLotteryInfoArray, itemsCount, dist(gen));\n\t\t\t\t\t\t\tif (targetItemIndex == itemIndex) {\n\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tlabel = 0.0f;\n\t\t\t\t\t\t}\n\t\t\t\t\t\t\n\t\t\t\t\t\tfloat* targetVector = negWeightBuffer + (itemVectorSize * targetItemIndex);\n\n\t\t\t\t\t\tfloat dotProduct = _FloatBuffer_DotProduct(relatedVector, targetVector, itemVectorSize);\n\n#if 0 \/\/ 計算版\n\t\t\t\t\t\tfloat expDotProduct = expf(dotProduct);\n\t\t\t\t\t\tfloat delta = (label - (expDotProduct \/ (expDotProduct + 1.0f))) * learningRate;\n#else \/\/ テーブル版\n\t\t\t\t\t\tfloat delta = (label - _SkipGram_ExpTableOutput(dotProduct)) * learningRate;\n#endif\n\n#if 0 \/\/ BLAS版\n\t\t\t\t\t\t_FloatBuffer_AddScaled(tempItemVector, targetVector, delta, itemVectorSize, itemVectorSize);\n\t\t\t\t\t\t_FloatBuffer_AddScaled(targetVector, relatedVector, delta, itemVectorSize, itemVectorSize);\n#endif\n#if 1 \/\/ ポインタ版\n\t\t\t\t\t\tfloat* headTempItemVector = tempItemVector;\n\t\t\t\t\t\tfloat* headRelatedVector = relatedVector;\n\t\t\t\t\t\tfor (float* targetVectorEnd = targetVector + itemVectorSize; targetVector < targetVectorEnd; targetVector++) {\n\t\t\t\t\t\t\t*headTempItemVector += delta * *targetVector;\n\t\t\t\t\t\t\t*targetVector += delta * *headRelatedVector;\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\theadTempItemVector++;\n\t\t\t\t\t\t\theadRelatedVector++;\n\t\t\t\t\t\t}\n#endif\n\t\t\t\t\t\t\n\t\t\t\t\t} \/\/ For each (positive\/negative) sampling.\n\t\t\t\t\t\n\t\t\t\t\tFloatBuffer_Add(relatedVector, tempItemVector, itemVectorSize, itemVectorSize);\n\t\t\t\t\t\n\t\t\t\t} \/\/ For each related item.\n\n\t\t\t} \/\/ For each item.\n\n\t\t} \/\/ For each sequence.\n\t\t\n\t} \/\/ For each iteration.\n\n}\n\n}\n<commit_msg>インデックスクリップ<commit_after>\/\/\n\/\/ SkipGramCpp.cpp\n\/\/ dopamine\n\/\/\n\/\/ Created by 佐原 瑠能 on 2017\/05\/31.\n\/\/ Copyright © 2017年 Runo. All rights reserved.\n\/\/\n\n#include <cstring>\n#include <cmath>\n#include <random>\n\nextern \"C\" {\n\t\n#include \"FloatBufferCpp.hpp\"\n#include \"SkipGramCpp.hpp\"\n\n#define EXPTABLE_SIZE\t\t1000\n#define EXPTABLE_INPUTMAX\t6.0f\n\nfloat* _SkipGram_ExpTable = NULL;\n\t\nvoid _SkipGram_GlobalInit() {\n\t\n\t\/\/ exp\/(exp+1)の計算テーブル\n\tif (_SkipGram_ExpTable == nullptr) {\n\t\t_SkipGram_ExpTable = (float*)malloc(EXPTABLE_SIZE * sizeof(float));\n\t\tfor (int tableIndex = 0; tableIndex < EXPTABLE_SIZE; tableIndex++) {\n\t\t\tfloat input = (((float)tableIndex) \/ ((float)EXPTABLE_SIZE)) * (EXPTABLE_INPUTMAX * 2.0f) - EXPTABLE_INPUTMAX;\n\t\t\tfloat val = expf(input);\n\t\t\t_SkipGram_ExpTable[tableIndex] = val \/ (val + 1.0f);\n\t\t}\n\t}\n\t\n}\n\nvoid _SkipGram_TrainInit(int* itemSequenceBuffer, int itemSequenceBufferLength, int* itemSequenceOffsetArray, int* itemSequencesCount, float* itemNegLotteryInfoArray, int* itemsCount) {\n\n\tint maxItemSequencesCount = *itemSequencesCount;\n\tint maxItemsCount = *itemsCount;\n\t\n\tif (maxItemSequencesCount == 0 || maxItemsCount == 0) {\n\t\t*itemSequencesCount = 0;\n\t\t*itemsCount = 0;\n\t\treturn;\n\t}\n\t\n\tint maxItemIndex = 0;\n\tmemset(itemNegLotteryInfoArray, 0, maxItemsCount * sizeof (float));\n\titemSequenceOffsetArray[0] = 0;\n\tint curItemSequenceIndex = 1;\n\n\t\/\/ バッファーを列挙する\n\tint* itemSequenceHead = itemSequenceBuffer;\n\tint* itemSequenceBufferEnd = itemSequenceBuffer + itemSequenceBufferLength;\n\tfor (; itemSequenceHead < itemSequenceBufferEnd; itemSequenceHead++) {\n\n\t\tint itemIndex = *itemSequenceHead;\n\t\t\n\t\t\/\/ シーケンスの終了チェック\n\t\tif (itemIndex < 0) {\n\t\t\t\n\t\t\t\/\/ 最後のシーケンス\n\t\t\tif (itemSequenceHead + 1 == itemSequenceBufferEnd\n\t\t\t\t|| maxItemSequencesCount == curItemSequenceIndex) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\t\n\t\t\titemSequenceOffsetArray[curItemSequenceIndex] = (int)(itemSequenceHead - itemSequenceBuffer) + 1;\n\t\t\tcurItemSequenceIndex++;\n\t\t}\n\t\t\n\t\t\/\/ アイテムIDの上限チェック\n\t\tif (itemIndex >= maxItemsCount) {\n\t\t\tbreak;\n\t\t}\n\t\t\n\t\t\/\/ 最大値更新\n\t\tif (itemIndex > maxItemIndex) {\n\t\t\tmaxItemIndex = itemIndex;\n\t\t}\n\t\t\n\t\t\/\/ アイテムをカウント\n\t\titemNegLotteryInfoArray[itemIndex] += 1.0f;\n\t}\n\n\t\/\/ 結果を設定\n\t*itemSequencesCount = curItemSequenceIndex;\n\tint actualItemsCount = maxItemIndex + 1;\n\t*itemsCount = actualItemsCount;\n\n\t\/\/ 抽選データを準備\n\tfloat sum = 0.0f;\n\tfloat* itemNegLotteryInfoEnd = itemNegLotteryInfoArray + actualItemsCount;\n\tfor (float* head = itemNegLotteryInfoArray; head < itemNegLotteryInfoEnd; head++) {\n\t\t*head = powf(*head, 0.75f);\n\t\tsum += *head;\n\t}\n\tfloat sumInv = 1.0f \/ sum;\n\tfloat acc = 0.0f;\n\tfor (float* head = itemNegLotteryInfoArray; head < itemNegLotteryInfoEnd; head++) {\n\t\tacc += *head * sumInv;\n\t\t*head = acc;\n\t}\n}\n\ninline int _SkipGram_RandomNegativeItemIndex(float* itemNegLotteryInfoArray, int itemsCount, float randVal) {\n\n\tint minIndex = 0;\n\tint maxIndex = itemsCount - 1;\n\twhile (minIndex < maxIndex) {\n\t\tint testIndex = (minIndex + maxIndex) \/ 2;\n\t\tfloat testVal = itemNegLotteryInfoArray[testIndex];\n\t\tif (randVal < testVal) {\n\t\t\tmaxIndex = testIndex - 1;\n\t\t} else {\n\t\t\tminIndex = testIndex + 1;\n\t\t}\n\t}\n\t\n\tif (maxIndex < 0)\n\t\treturn 0;\n\tif (maxIndex >= itemsCount)\n\t\treturn itemsCount - 1;\n\treturn maxIndex;\n}\n\t\ninline float _SkipGram_ExpTableOutput(float input) {\n\n\tint tableIndex = (input + EXPTABLE_INPUTMAX) * (((float)EXPTABLE_SIZE) \/ EXPTABLE_INPUTMAX \/ 2.0f);\n\tif (tableIndex < 0)\n\t\treturn 0.0f;\n\tif (tableIndex >= EXPTABLE_SIZE)\n\t\treturn 1.0f;\n\t\n\treturn _SkipGram_ExpTable[tableIndex];\n}\n\nvoid _SkipGram_TrainIterate(int* itemSequenceBuffer, int* itemSequenceOffsetArray, int itemSequencesCount, float* itemNegLotteryInfoArray, int itemsCount, int itemVectorSize, float* weightBuffer, float* negWeightBuffer, float* tempItemVector, int windowSize, int negativeSamplingCount, float learningRate, int iterationsCount) {\n\t\n\tstd::random_device dev;\n\tstd::mt19937 gen(dev());\n\tstd::uniform_real_distribution<float> dist(0.0f, itemNegLotteryInfoArray[itemsCount - 1]);\n\n\twhile (iterationsCount--) { \/\/ For each iteration.\n\t\tfor (int itemSequenceIndex = 0; itemSequenceIndex < itemSequencesCount; itemSequenceIndex++) { \/\/ For each sequence.\n\t\t\t\n\t\t\tint* itemSequenceStart = itemSequenceBuffer + itemSequenceOffsetArray[itemSequenceIndex];\n\t\t\tfor (int* headItem = itemSequenceStart; ; headItem++) { \/\/ For each item.\n\t\t\t\tint itemIndex = *headItem;\n\t\t\t\tif (itemIndex < 0) {\n\t\t\t\t\tbreak; \/\/ End of sequence.\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tint* headRelated = headItem - windowSize;\n\t\t\t\tint* headRelatedEnd = headItem + windowSize;\n\t\t\t\tif (headRelated < itemSequenceStart) {\n\t\t\t\t\theadRelated = itemSequenceStart;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tfor (; headRelated <= headRelatedEnd; headRelated++) { \/\/ For each related item.\n\t\t\t\t\tint relatedItemIndex = *headRelated;\n\t\t\t\t\tif (relatedItemIndex == itemIndex) {\n\t\t\t\t\t\tcontinue; \/\/ Skip center item.\n\t\t\t\t\t}\n\t\t\t\t\tif (relatedItemIndex < 0) {\n\t\t\t\t\t\tbreak; \/\/ End of sequence.\n\t\t\t\t\t}\n\n\t\t\t\t\tmemset(tempItemVector, 0, itemVectorSize * sizeof (float));\n\t\t\t\t\t\n\t\t\t\t\tfloat* relatedVector = weightBuffer + (itemVectorSize * relatedItemIndex);\n\t\t\t\t\t\n\t\t\t\t\t\/\/ Positive sampling, then negative sampling.\n\t\t\t\t\tfloat label;\n\t\t\t\t\tint targetItemIndex;\n\t\t\t\t\tfor (int negativeSamplingIndex = -1; negativeSamplingIndex < negativeSamplingCount; negativeSamplingIndex++) { \/\/ For each (positive\/negative) sampling.\n\t\t\t\t\t\t\n\t\t\t\t\t\tif (negativeSamplingIndex == -1) {\n\t\t\t\t\t\t\ttargetItemIndex = itemIndex;\n\t\t\t\t\t\t\tlabel = 1.0f;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\ttargetItemIndex = _SkipGram_RandomNegativeItemIndex(itemNegLotteryInfoArray, itemsCount, dist(gen));\n\t\t\t\t\t\t\tif (targetItemIndex == itemIndex) {\n\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tlabel = 0.0f;\n\t\t\t\t\t\t}\n\t\t\t\t\t\t\n\t\t\t\t\t\tfloat* targetVector = negWeightBuffer + (itemVectorSize * targetItemIndex);\n\n\t\t\t\t\t\tfloat dotProduct = _FloatBuffer_DotProduct(relatedVector, targetVector, itemVectorSize);\n\n#if 0 \/\/ 計算版\n\t\t\t\t\t\tfloat expDotProduct = expf(dotProduct);\n\t\t\t\t\t\tfloat delta = (label - (expDotProduct \/ (expDotProduct + 1.0f))) * learningRate;\n#else \/\/ テーブル版\n\t\t\t\t\t\tfloat delta = (label - _SkipGram_ExpTableOutput(dotProduct)) * learningRate;\n#endif\n\n#if 0 \/\/ BLAS版\n\t\t\t\t\t\t_FloatBuffer_AddScaled(tempItemVector, targetVector, delta, itemVectorSize, itemVectorSize);\n\t\t\t\t\t\t_FloatBuffer_AddScaled(targetVector, relatedVector, delta, itemVectorSize, itemVectorSize);\n#endif\n#if 1 \/\/ ポインタ版\n\t\t\t\t\t\tfloat* headTempItemVector = tempItemVector;\n\t\t\t\t\t\tfloat* headRelatedVector = relatedVector;\n\t\t\t\t\t\tfor (float* targetVectorEnd = targetVector + itemVectorSize; targetVector < targetVectorEnd; targetVector++) {\n\t\t\t\t\t\t\t*headTempItemVector += delta * *targetVector;\n\t\t\t\t\t\t\t*targetVector += delta * *headRelatedVector;\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\theadTempItemVector++;\n\t\t\t\t\t\t\theadRelatedVector++;\n\t\t\t\t\t\t}\n#endif\n\t\t\t\t\t\t\n\t\t\t\t\t} \/\/ For each (positive\/negative) sampling.\n\t\t\t\t\t\n\t\t\t\t\tFloatBuffer_Add(relatedVector, tempItemVector, itemVectorSize, itemVectorSize);\n\t\t\t\t\t\n\t\t\t\t} \/\/ For each related item.\n\n\t\t\t} \/\/ For each item.\n\n\t\t} \/\/ For each sequence.\n\t\t\n\t} \/\/ For each iteration.\n\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/\/ @file\n\/\/\/ @author uentity\n\/\/\/ @date 28.06.2018\n\/\/\/ @brief BS tree links serialization code\n\/\/\/ @copyright\n\/\/\/ This Source Code Form is subject to the terms of the Mozilla Public License,\n\/\/\/ v. 2.0. If a copy of the MPL was not distributed with this file,\n\/\/\/ You can obtain one at https:\/\/mozilla.org\/MPL\/2.0\/\n\n#include <bs\/serialize\/serialize.h>\n#include <bs\/serialize\/tree.h>\n#include <bs\/serialize\/boost_uuid.h>\n\n#include \"tree_impl.h\"\n#include \"..\/tree\/link_actor.h\"\n#include \"..\/tree\/hard_link.h\"\n#include \"..\/tree\/fusion_link_actor.h\"\n#include \"..\/tree\/map_engine.h\"\n\n#include <cereal\/types\/chrono.hpp>\n\nusing namespace cereal;\nusing namespace blue_sky;\nusing blue_sky::detail::shared;\n\n\/*-----------------------------------------------------------------------------\n * inode\n *-----------------------------------------------------------------------------*\/\nBSS_FCN_BEGIN(save, tree::inode)\n\tar(\n\t\tmake_nvp(\"flags\", t.flags),\n\t\tmake_nvp(\"u\", t.u),\n\t\tmake_nvp(\"g\", t.g),\n\t\tmake_nvp(\"o\", t.o),\n\t\tmake_nvp(\"mod_time\", t.mod_time),\n\t\tmake_nvp(\"owner\", t.owner),\n\t\tmake_nvp(\"group\", t.group)\n\t);\nBSS_FCN_END\n\nBSS_FCN_BEGIN(load, tree::inode)\n\ttree::inode::Flags flags;\n\tar(make_nvp(\"flags\", flags));\n\tt.flags = flags;\n\tstd::uint8_t r;\n\tar(make_nvp(\"u\", r));\n\tt.u = r;\n\tar(make_nvp(\"g\", r));\n\tt.g = r;\n\tar(make_nvp(\"o\", r));\n\tt.o = r;\n\tar(\n\t\tmake_nvp(\"mod_time\", t.mod_time),\n\t\tmake_nvp(\"owner\", t.owner),\n\t\tmake_nvp(\"group\", t.group)\n\t);\nBSS_FCN_END\n\nBSS_FCN_EXPORT(save, tree::inode)\nBSS_FCN_EXPORT(load, tree::inode)\n\n\/*-----------------------------------------------------------------------------\n * link_impl\n *-----------------------------------------------------------------------------*\/\nBSS_FCN_BEGIN(serialize, tree::link_impl)\n\t\/\/ [NOTE] intentionally do net serialize owner, it will be set up when parent node is loaded\n\tar(\n\t\tmake_nvp(\"id\", t.id_),\n\t\tmake_nvp(\"name\", t.name_),\n\t\tmake_nvp(\"flags\", t.flags_)\n\t);\nBSS_FCN_END\n\nCEREAL_REGISTER_POLYMORPHIC_RELATION(tree::engine::impl, tree::link_impl)\nCEREAL_REGISTER_TYPE_WITH_NAME(tree::link_impl, \"link\")\nBSS_FCN_EXPORT(serialize, tree::link_impl)\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ ilink_impl\n\/\/\nBSS_FCN_INL_BEGIN(serialize, tree::ilink_impl)\n\t\/\/ serialize inode\n\tar(make_nvp(\"inode\", t.inode_));\n\n\tserialize<tree::link_impl>::go(ar, t, version);\nBSS_FCN_INL_END(serialize, tree::ilink_impl)\n\nCEREAL_REGISTER_POLYMORPHIC_RELATION(tree::link_impl, tree::ilink_impl)\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ hard_link_impl\n\/\/\nBSS_FCN_INL_BEGIN(serialize, tree::hard_link_impl)\n\tif constexpr(Archive::is_saving::value) {\n\t\tar( make_nvp(\"data\", t.data_) );\n\t}\n\telse {\n\t\t\/\/ load data with deferred 2nd trial\n\t\tar(defer_failed(\n\t\t\tt.data_,\n\t\t\t[&t](auto obj) { t.set_data(std::move(obj)); },\n\t\t\tPtrInitTrigger::SuccessAndRetry\n\t\t));\n\t}\n\n\tserialize<tree::ilink_impl>::go(ar, t, version);\n\t\/\/ar( make_nvp(\"linkbase\", base_class<tree::ilink_impl>(&t)) );\nBSS_FCN_INL_END(serialize, tree::hard_link_impl)\n\nCEREAL_REGISTER_POLYMORPHIC_RELATION(tree::ilink_impl, tree::hard_link_impl)\nCEREAL_REGISTER_TYPE_WITH_NAME(tree::hard_link_impl, \"hard_link\")\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ weak_link_impl\n\/\/\nBSS_FCN_INL_BEGIN(serialize, tree::weak_link_impl)\n\tif constexpr(Archive::is_saving::value) {\n\t\tar( make_nvp(\"data\", t.data_.lock()) );\n\t}\n\telse {\n\t\tauto unused = sp_obj{};\n\t\tar(defer_failed(\n\t\t\tunused,\n\t\t\t[&t](auto obj) { t.set_data(std::move(obj)); },\n\t\t\tPtrInitTrigger::SuccessAndRetry\n\t\t));\n\t}\n\n\tserialize<tree::ilink_impl>::go(ar, t, version);\n\t\/\/ar( make_nvp(\"linkbase\", base_class<tree::ilink_impl>(&t)) );\nBSS_FCN_INL_END(serialize, tree::weak_link_impl)\n\nCEREAL_REGISTER_POLYMORPHIC_RELATION(tree::ilink_impl, tree::weak_link_impl)\nCEREAL_REGISTER_TYPE_WITH_NAME(tree::weak_link_impl, \"weak_link\")\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ sym_link_impl\n\/\/\nBSS_FCN_INL_BEGIN(serialize, tree::sym_link_impl)\n\tar(make_nvp(\"path\", t.path_));\n\n\tserialize<tree::link_impl>::go(ar, t, version);\nBSS_FCN_INL_END(serialize, tree::sym_link_impl)\n\nCEREAL_REGISTER_POLYMORPHIC_RELATION(tree::link_impl, tree::sym_link_impl)\nCEREAL_REGISTER_TYPE_WITH_NAME(tree::sym_link_impl, \"sym_link\")\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ fusion_link_impl\n\/\/\nBSS_FCN_INL_BEGIN(serialize, tree::fusion_link_impl)\n\tif constexpr(Archive::is_saving::value) {\n\t\tar( make_nvp(\"bridge\", t.bridge_) );\n\t}\n\telse {\n\t\t\/\/ load bridge with deferred trial\n\t\tar(defer_failed(\n\t\t\tt.bridge_,\n\t\t\t[&t](auto B) { t.bridge_ = std::move(B); },\n\t\t\tPtrInitTrigger::SuccessAndRetry\n\t\t));\n\t}\n\n\tserialize<tree::ilink_impl>::go(ar, t, version);\n\t\/\/ar( make_nvp(\"linkbase\", base_class<tree::ilink_impl>(&t)) );\nBSS_FCN_INL_END(serialize, tree::fusion_link_impl)\n\nCEREAL_REGISTER_POLYMORPHIC_RELATION(tree::ilink_impl, tree::fusion_link_impl)\nCEREAL_REGISTER_TYPE_WITH_NAME(tree::fusion_link_impl, \"fusion_link\")\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ map_link - not serialized\n\/\/\nCEREAL_REGISTER_POLYMORPHIC_RELATION(tree::link_impl, tree::map_link_impl)\nCEREAL_REGISTER_TYPE_WITH_NAME(tree::map_link_impl, \"map_link\")\n\n\/*-----------------------------------------------------------------------------\n * link\n *-----------------------------------------------------------------------------*\/\nBSS_FCN_BEGIN(serialize, tree::link)\n\t\/\/ map links are not serialized at all\n\tif(t.type_id() == tree::map_link::type_id_()) return;\n\n\t\/\/ [NOTE] intentionally do net serialize owner, it will be set up when parent node is loaded\n\tif constexpr(Archive::is_saving::value) {\n\t\t\/\/ for nil links save empty impl pointer\n\t\tauto Limpl = t ? t.pimpl_ : tree::sp_limpl{};\n\t\tar(make_nvp(\"link\", Limpl));\n\t}\n\telse {\n\t\tar(make_nvp(\"link\", t.pimpl_));\n\t\tif(!t.pimpl_) t = tree::link{};\n\t\t\/\/ ID is ready, we can start internal actor\n\t\tt.start_engine();\n\t\t\/\/ if pointee is a node, correct it's handle\n\t\tt.pimpl()->propagate_handle();\n\t}\nBSS_FCN_END\n\nBSS_FCN_EXPORT(serialize, tree::link)\n\nBSS_REGISTER_DYNAMIC_INIT(link)\n<commit_msg>serial: disable serialization of inodes<commit_after>\/\/\/ @file\n\/\/\/ @author uentity\n\/\/\/ @date 28.06.2018\n\/\/\/ @brief BS tree links serialization code\n\/\/\/ @copyright\n\/\/\/ This Source Code Form is subject to the terms of the Mozilla Public License,\n\/\/\/ v. 2.0. If a copy of the MPL was not distributed with this file,\n\/\/\/ You can obtain one at https:\/\/mozilla.org\/MPL\/2.0\/\n\n#include <bs\/serialize\/serialize.h>\n#include <bs\/serialize\/tree.h>\n#include <bs\/serialize\/boost_uuid.h>\n\n#include \"tree_impl.h\"\n#include \"..\/tree\/link_actor.h\"\n#include \"..\/tree\/hard_link.h\"\n#include \"..\/tree\/fusion_link_actor.h\"\n#include \"..\/tree\/map_engine.h\"\n\n#include <cereal\/types\/chrono.hpp>\n\nusing namespace cereal;\nusing namespace blue_sky;\nusing blue_sky::detail::shared;\n\n\/*-----------------------------------------------------------------------------\n * inode\n *-----------------------------------------------------------------------------*\/\nBSS_FCN_BEGIN(save, tree::inode)\n\tar(\n\t\tmake_nvp(\"flags\", t.flags),\n\t\tmake_nvp(\"u\", t.u),\n\t\tmake_nvp(\"g\", t.g),\n\t\tmake_nvp(\"o\", t.o),\n\t\tmake_nvp(\"mod_time\", t.mod_time),\n\t\tmake_nvp(\"owner\", t.owner),\n\t\tmake_nvp(\"group\", t.group)\n\t);\nBSS_FCN_END\n\nBSS_FCN_BEGIN(load, tree::inode)\n\ttree::inode::Flags flags;\n\tar(make_nvp(\"flags\", flags));\n\tt.flags = flags;\n\tstd::uint8_t r;\n\tar(make_nvp(\"u\", r));\n\tt.u = r;\n\tar(make_nvp(\"g\", r));\n\tt.g = r;\n\tar(make_nvp(\"o\", r));\n\tt.o = r;\n\tar(\n\t\tmake_nvp(\"mod_time\", t.mod_time),\n\t\tmake_nvp(\"owner\", t.owner),\n\t\tmake_nvp(\"group\", t.group)\n\t);\nBSS_FCN_END\n\nBSS_FCN_EXPORT(save, tree::inode)\nBSS_FCN_EXPORT(load, tree::inode)\n\n\/*-----------------------------------------------------------------------------\n * link_impl\n *-----------------------------------------------------------------------------*\/\nBSS_FCN_BEGIN(serialize, tree::link_impl)\n\t\/\/ [NOTE] intentionally do net serialize owner, it will be set up when parent node is loaded\n\tar(\n\t\tmake_nvp(\"id\", t.id_),\n\t\tmake_nvp(\"name\", t.name_),\n\t\tmake_nvp(\"flags\", t.flags_)\n\t);\nBSS_FCN_END\n\nCEREAL_REGISTER_POLYMORPHIC_RELATION(tree::engine::impl, tree::link_impl)\nCEREAL_REGISTER_TYPE_WITH_NAME(tree::link_impl, \"link\")\nBSS_FCN_EXPORT(serialize, tree::link_impl)\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ ilink_impl\n\/\/\nBSS_FCN_INL_BEGIN(serialize, tree::ilink_impl)\n\t\/\/ serialize inode\n\t\/\/ [NOTE] disabled - inodes aren't actually used now\n\t\/\/ [TODO] reenable later when conception will be more thought out\n\t\/\/ar(make_nvp(\"inode\", t.inode_));\n\n\tserialize<tree::link_impl>::go(ar, t, version);\nBSS_FCN_INL_END(serialize, tree::ilink_impl)\n\nCEREAL_REGISTER_POLYMORPHIC_RELATION(tree::link_impl, tree::ilink_impl)\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ hard_link_impl\n\/\/\nBSS_FCN_INL_BEGIN(serialize, tree::hard_link_impl)\n\tif constexpr(Archive::is_saving::value) {\n\t\tar( make_nvp(\"data\", t.data_) );\n\t}\n\telse {\n\t\t\/\/ load data with deferred 2nd trial\n\t\tar(defer_failed(\n\t\t\tt.data_,\n\t\t\t[&t](auto obj) { t.set_data(std::move(obj)); },\n\t\t\tPtrInitTrigger::SuccessAndRetry\n\t\t));\n\t}\n\n\tserialize<tree::ilink_impl>::go(ar, t, version);\n\t\/\/ar( make_nvp(\"linkbase\", base_class<tree::ilink_impl>(&t)) );\nBSS_FCN_INL_END(serialize, tree::hard_link_impl)\n\nCEREAL_REGISTER_POLYMORPHIC_RELATION(tree::ilink_impl, tree::hard_link_impl)\nCEREAL_REGISTER_TYPE_WITH_NAME(tree::hard_link_impl, \"hard_link\")\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ weak_link_impl\n\/\/\nBSS_FCN_INL_BEGIN(serialize, tree::weak_link_impl)\n\tif constexpr(Archive::is_saving::value) {\n\t\tar( make_nvp(\"data\", t.data_.lock()) );\n\t}\n\telse {\n\t\tauto unused = sp_obj{};\n\t\tar(defer_failed(\n\t\t\tunused,\n\t\t\t[&t](auto obj) { t.set_data(std::move(obj)); },\n\t\t\tPtrInitTrigger::SuccessAndRetry\n\t\t));\n\t}\n\n\tserialize<tree::ilink_impl>::go(ar, t, version);\n\t\/\/ar( make_nvp(\"linkbase\", base_class<tree::ilink_impl>(&t)) );\nBSS_FCN_INL_END(serialize, tree::weak_link_impl)\n\nCEREAL_REGISTER_POLYMORPHIC_RELATION(tree::ilink_impl, tree::weak_link_impl)\nCEREAL_REGISTER_TYPE_WITH_NAME(tree::weak_link_impl, \"weak_link\")\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ sym_link_impl\n\/\/\nBSS_FCN_INL_BEGIN(serialize, tree::sym_link_impl)\n\tar(make_nvp(\"path\", t.path_));\n\n\tserialize<tree::link_impl>::go(ar, t, version);\nBSS_FCN_INL_END(serialize, tree::sym_link_impl)\n\nCEREAL_REGISTER_POLYMORPHIC_RELATION(tree::link_impl, tree::sym_link_impl)\nCEREAL_REGISTER_TYPE_WITH_NAME(tree::sym_link_impl, \"sym_link\")\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ fusion_link_impl\n\/\/\nBSS_FCN_INL_BEGIN(serialize, tree::fusion_link_impl)\n\tif constexpr(Archive::is_saving::value) {\n\t\tar( make_nvp(\"bridge\", t.bridge_) );\n\t}\n\telse {\n\t\t\/\/ load bridge with deferred trial\n\t\tar(defer_failed(\n\t\t\tt.bridge_,\n\t\t\t[&t](auto B) { t.bridge_ = std::move(B); },\n\t\t\tPtrInitTrigger::SuccessAndRetry\n\t\t));\n\t}\n\n\tserialize<tree::ilink_impl>::go(ar, t, version);\n\t\/\/ar( make_nvp(\"linkbase\", base_class<tree::ilink_impl>(&t)) );\nBSS_FCN_INL_END(serialize, tree::fusion_link_impl)\n\nCEREAL_REGISTER_POLYMORPHIC_RELATION(tree::ilink_impl, tree::fusion_link_impl)\nCEREAL_REGISTER_TYPE_WITH_NAME(tree::fusion_link_impl, \"fusion_link\")\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ map_link - not serialized\n\/\/\nCEREAL_REGISTER_POLYMORPHIC_RELATION(tree::link_impl, tree::map_link_impl)\nCEREAL_REGISTER_TYPE_WITH_NAME(tree::map_link_impl, \"map_link\")\n\n\/*-----------------------------------------------------------------------------\n * link\n *-----------------------------------------------------------------------------*\/\nBSS_FCN_BEGIN(serialize, tree::link)\n\t\/\/ map links are not serialized at all\n\tif(t.type_id() == tree::map_link::type_id_()) return;\n\n\t\/\/ [NOTE] intentionally do net serialize owner, it will be set up when parent node is loaded\n\tif constexpr(Archive::is_saving::value) {\n\t\t\/\/ for nil links save empty impl pointer\n\t\tauto Limpl = t ? t.pimpl_ : tree::sp_limpl{};\n\t\tar(make_nvp(\"link\", Limpl));\n\t}\n\telse {\n\t\tar(make_nvp(\"link\", t.pimpl_));\n\t\tif(!t.pimpl_) t = tree::link{};\n\t\t\/\/ ID is ready, we can start internal actor\n\t\tt.start_engine();\n\t\t\/\/ if pointee is a node, correct it's handle\n\t\tt.pimpl()->propagate_handle();\n\t}\nBSS_FCN_END\n\nBSS_FCN_EXPORT(serialize, tree::link)\n\nBSS_REGISTER_DYNAMIC_INIT(link)\n<|endoftext|>"} {"text":"<commit_before>\/\/\/ @file\n\/\/\/ @author uentity\n\/\/\/ @date 28.06.2018\n\/\/\/ @brief BS tree links serialization code\n\/\/\/ @copyright\n\/\/\/ This Source Code Form is subject to the terms of the Mozilla Public License,\n\/\/\/ v. 2.0. If a copy of the MPL was not distributed with this file,\n\/\/\/ You can obtain one at https:\/\/mozilla.org\/MPL\/2.0\/\n\n#include <bs\/serialize\/serialize.h>\n#include <bs\/serialize\/tree.h>\n#include <bs\/serialize\/boost_uuid.h>\n\n#include \"tree_impl.h\"\n#include \"..\/tree\/link_actor.h\"\n#include \"..\/tree\/hard_link.h\"\n#include \"..\/tree\/fusion_link_actor.h\"\n#include \"..\/tree\/map_engine.h\"\n\n#include <cereal\/types\/chrono.hpp>\n#include <cereal\/types\/unordered_map.hpp>\n\nusing namespace cereal;\nusing namespace blue_sky;\n\n\/*-----------------------------------------------------------------------------\n * inode\n *-----------------------------------------------------------------------------*\/\nBSS_FCN_BEGIN(save, tree::inode)\n\tar(\n\t\tmake_nvp(\"flags\", t.flags),\n\t\tmake_nvp(\"u\", t.u),\n\t\tmake_nvp(\"g\", t.g),\n\t\tmake_nvp(\"o\", t.o),\n\t\tmake_nvp(\"mod_time\", t.mod_time),\n\t\tmake_nvp(\"owner\", t.owner),\n\t\tmake_nvp(\"group\", t.group)\n\t);\nBSS_FCN_END\n\nBSS_FCN_BEGIN(load, tree::inode)\n\ttree::inode::Flags flags;\n\tar(make_nvp(\"flags\", flags));\n\tt.flags = flags;\n\tstd::uint8_t r;\n\tar(make_nvp(\"u\", r));\n\tt.u = r;\n\tar(make_nvp(\"g\", r));\n\tt.g = r;\n\tar(make_nvp(\"o\", r));\n\tt.o = r;\n\tar(\n\t\tmake_nvp(\"mod_time\", t.mod_time),\n\t\tmake_nvp(\"owner\", t.owner),\n\t\tmake_nvp(\"group\", t.group)\n\t);\nBSS_FCN_END\n\nBSS_FCN_EXPORT(save, tree::inode)\nBSS_FCN_EXPORT(load, tree::inode)\n\n\/*-----------------------------------------------------------------------------\n * link_impl\n *-----------------------------------------------------------------------------*\/\nBSS_FCN_BEGIN(serialize, tree::link_impl)\n\t\/\/ [NOTE] intentionally do net serialize owner, it will be set up when parent node is loaded\n\tar(\n\t\tmake_nvp(\"id\", t.id_),\n\t\tmake_nvp(\"name\", t.name_),\n\t\tmake_nvp(\"flags\", t.flags_)\n\t);\nBSS_FCN_END\n\nCEREAL_REGISTER_POLYMORPHIC_RELATION(tree::engine::impl, tree::link_impl)\nCEREAL_REGISTER_TYPE_WITH_NAME(tree::link_impl, \"link\")\nBSS_FCN_EXPORT(serialize, tree::link_impl)\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ ilink_impl\n\/\/\nBSS_FCN_INL_BEGIN(serialize, tree::ilink_impl)\n\t\/\/ serialize inode\n\t\/\/ [NOTE] disabled - inodes aren't actually used now\n\t\/\/ [TODO] reenable later when conception will be more thought out\n\t\/\/ar(make_nvp(\"inode\", t.inode_));\n\n\tserialize<tree::link_impl>::go(ar, t, version);\nBSS_FCN_INL_END(serialize, tree::ilink_impl)\n\nCEREAL_REGISTER_POLYMORPHIC_RELATION(tree::link_impl, tree::ilink_impl)\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ hard_link_impl\n\/\/\nBSS_FCN_INL_BEGIN(serialize, tree::hard_link_impl)\n\tif constexpr(Archive::is_saving::value) {\n\t\tar( make_nvp(\"data\", t.data_) );\n\t}\n\telse {\n\t\t\/\/ load data with deferred 2nd trial\n\t\tar(defer_failed(\n\t\t\tt.data_,\n\t\t\t[&t](auto obj) { t.set_data(std::move(obj)); },\n\t\t\tPtrInitTrigger::SuccessAndRetry\n\t\t));\n\t}\n\n\tserialize<tree::ilink_impl>::go(ar, t, version);\n\t\/\/ar( make_nvp(\"linkbase\", base_class<tree::ilink_impl>(&t)) );\nBSS_FCN_INL_END(serialize, tree::hard_link_impl)\n\nCEREAL_REGISTER_POLYMORPHIC_RELATION(tree::ilink_impl, tree::hard_link_impl)\nCEREAL_REGISTER_TYPE_WITH_NAME(tree::hard_link_impl, \"hard_link\")\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ weak_link_impl\n\/\/\nBSS_FCN_INL_BEGIN(serialize, tree::weak_link_impl)\n\tif constexpr(Archive::is_saving::value) {\n\t\tar( make_nvp(\"data\", t.data_.lock()) );\n\t}\n\telse {\n\t\tauto unused = sp_obj{};\n\t\tar(defer_failed(\n\t\t\tunused,\n\t\t\t[&t](auto obj) { t.set_data(std::move(obj)); },\n\t\t\tPtrInitTrigger::SuccessAndRetry\n\t\t));\n\t}\n\n\tserialize<tree::ilink_impl>::go(ar, t, version);\nBSS_FCN_INL_END(serialize, tree::weak_link_impl)\n\nCEREAL_REGISTER_POLYMORPHIC_RELATION(tree::ilink_impl, tree::weak_link_impl)\nCEREAL_REGISTER_TYPE_WITH_NAME(tree::weak_link_impl, \"weak_link\")\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ sym_link_impl\n\/\/\nBSS_FCN_INL_BEGIN(serialize, tree::sym_link_impl)\n\tar(make_nvp(\"path\", t.path_));\n\n\tserialize<tree::link_impl>::go(ar, t, version);\nBSS_FCN_INL_END(serialize, tree::sym_link_impl)\n\nCEREAL_REGISTER_POLYMORPHIC_RELATION(tree::link_impl, tree::sym_link_impl)\nCEREAL_REGISTER_TYPE_WITH_NAME(tree::sym_link_impl, \"sym_link\")\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ fusion_link_impl\n\/\/\nBSS_FCN_INL_BEGIN(serialize, tree::fusion_link_impl)\n\tusing namespace blue_sky::tree;\n\tif constexpr(Archive::is_saving::value) {\n\t\tar( make_nvp(\"bridge\", t.bridge_) );\n\t\t\/\/ save status values\n\t\tar(\n\t\t\tmake_nvp(\"data_status\", t.req_status(Req::Data)),\n\t\t\tmake_nvp(\"dnode_status\", t.req_status(Req::DataNode))\n\t\t);\n\t\t\/\/ save cached object\n\t\tar( make_nvp(\"data\", t.data_) );\n\t}\n\telse {\n\t\t\/\/ load bridge with deferred trial\n\t\tar(defer_failed(\n\t\t\tt.bridge_,\n\t\t\t[&t](auto B) { t.bridge_ = std::move(B); },\n\t\t\tPtrInitTrigger::SuccessAndRetry\n\t\t));\n\t\t\/\/ restore status\n\t\ttree::ReqStatus s;\n\t\tar(make_nvp(\"data_status\", s));\n\t\tt.rs_reset(Req::Data, ReqReset::Always, s);\n\t\tar(make_nvp(\"dnode_status\", s));\n\t\tt.rs_reset(Req::DataNode, ReqReset::Always, s);\n\n\t\t\/\/ load data with deferred 2nd trial\n\t\tar(defer_failed(\n\t\t\tt.data_,\n\t\t\t[&](auto obj) { t.data_ = std::move(obj); },\n\t\t\tPtrInitTrigger::SuccessAndRetry\n\t\t));\n\t}\n\n\tserialize<tree::ilink_impl>::go(ar, t, version);\nBSS_FCN_INL_END(serialize, tree::fusion_link_impl)\n\nCEREAL_REGISTER_POLYMORPHIC_RELATION(tree::ilink_impl, tree::fusion_link_impl)\nCEREAL_REGISTER_TYPE_WITH_NAME(tree::fusion_link_impl, \"fusion_link\")\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ map_link\n\/\/\nBSS_FCN_INL_BEGIN(serialize, tree::map_link_impl_base)\n\tif constexpr(Archive::is_saving::value) {\n\t\t\/\/ dump contained node only if map_link owns it\n\t\tif(t.out_.handle().id() == t.id_)\n\t\t\tar(make_nvp( \"out\", t.out_ ));\n\t\telse\n\t\t\tar(make_nvp( \"out\", tree::node::nil() ));\n\t}\n\telse {\n\t\t\/\/ load out node\n\t\ttree::node out_node;\n\t\tar(make_nvp( \"out\", out_node ));\n\t\tif(t.out_ = out_node)\n\t\t\tt.link_impl::propagate_handle(t.out_);\n\t}\n\n\tserialize<tree::link_impl>::go(ar, t, version);\nBSS_FCN_INL_END(serialize, tree::map_link_impl_base)\n\n\nBSS_FCN_INL_BEGIN(serialize, tree::map_link_impl)\n\tar(make_nvp( \"io_map\", t.io_map_ ));\n\tserialize<tree::map_link_impl_base>::go(ar, t, version);\nBSS_FCN_INL_END(serialize, tree::map_link_impl)\n\n\nBSS_FCN_INL_BEGIN(serialize, tree::map_node_impl)\n\tserialize<tree::map_link_impl_base>::go(ar, t, version);\nBSS_FCN_INL_END(serialize, tree::map_node_impl)\n\nCEREAL_REGISTER_POLYMORPHIC_RELATION(tree::link_impl, tree::map_link_impl_base)\nCEREAL_REGISTER_POLYMORPHIC_RELATION(tree::map_link_impl_base, tree::map_link_impl)\nCEREAL_REGISTER_POLYMORPHIC_RELATION(tree::map_link_impl_base, tree::map_node_impl)\nCEREAL_REGISTER_TYPE_WITH_NAME(tree::map_link_impl, \"map_link\")\nCEREAL_REGISTER_TYPE_WITH_NAME(tree::map_node_impl, \"map_node\")\n\n\/*-----------------------------------------------------------------------------\n * link\n *-----------------------------------------------------------------------------*\/\nBSS_FCN_BEGIN(serialize, tree::link)\n\t\/\/ [NOTE] intentionally do net serialize owner, it will be set up when parent node is loaded\n\tif constexpr(Archive::is_saving::value) {\n\t\t\/\/ for nil link save empty impl pointer\n\t\tar(make_nvp( \"link\", t ? t.pimpl_ : tree::sp_limpl{} ));\n\t}\n\telse {\n\t\tar(make_nvp(\"link\", t.pimpl_));\n\t\tif(t.pimpl_) {\n\t\t\t\/\/ ID is ready, we can start internal actor\n\t\t\tt.start_engine();\n\t\t\t\/\/ if pointee is a node, correct it's handle\n\t\t\tt.pimpl()->propagate_handle();\n\t\t}\n\t\telse\n\t\t\tt = tree::link{};\n\t}\nBSS_FCN_END\n\nBSS_FCN_EXPORT(serialize, tree::link)\n\nBSS_REGISTER_DYNAMIC_INIT(link)\n<commit_msg>serial\/tree: refactor status values serialization<commit_after>\/\/\/ @file\n\/\/\/ @author uentity\n\/\/\/ @date 28.06.2018\n\/\/\/ @brief BS tree links serialization code\n\/\/\/ @copyright\n\/\/\/ This Source Code Form is subject to the terms of the Mozilla Public License,\n\/\/\/ v. 2.0. If a copy of the MPL was not distributed with this file,\n\/\/\/ You can obtain one at https:\/\/mozilla.org\/MPL\/2.0\/\n\n#include <bs\/serialize\/serialize.h>\n#include <bs\/serialize\/tree.h>\n#include <bs\/serialize\/boost_uuid.h>\n\n#include \"bs\/serialize\/carray.h\"\n#include \"tree_impl.h\"\n#include \"..\/tree\/link_actor.h\"\n#include \"..\/tree\/hard_link.h\"\n#include \"..\/tree\/fusion_link_actor.h\"\n#include \"..\/tree\/map_engine.h\"\n\n#include <cereal\/types\/chrono.hpp>\n#include <cereal\/types\/unordered_map.hpp>\n\nusing namespace cereal;\nusing namespace blue_sky;\n\n\/*-----------------------------------------------------------------------------\n * inode\n *-----------------------------------------------------------------------------*\/\nBSS_FCN_BEGIN(save, tree::inode)\n\tar(\n\t\tmake_nvp(\"flags\", t.flags),\n\t\tmake_nvp(\"u\", t.u),\n\t\tmake_nvp(\"g\", t.g),\n\t\tmake_nvp(\"o\", t.o),\n\t\tmake_nvp(\"mod_time\", t.mod_time),\n\t\tmake_nvp(\"owner\", t.owner),\n\t\tmake_nvp(\"group\", t.group)\n\t);\nBSS_FCN_END\n\nBSS_FCN_BEGIN(load, tree::inode)\n\ttree::inode::Flags flags;\n\tar(make_nvp(\"flags\", flags));\n\tt.flags = flags;\n\tstd::uint8_t r;\n\tar(make_nvp(\"u\", r));\n\tt.u = r;\n\tar(make_nvp(\"g\", r));\n\tt.g = r;\n\tar(make_nvp(\"o\", r));\n\tt.o = r;\n\tar(\n\t\tmake_nvp(\"mod_time\", t.mod_time),\n\t\tmake_nvp(\"owner\", t.owner),\n\t\tmake_nvp(\"group\", t.group)\n\t);\nBSS_FCN_END\n\nBSS_FCN_EXPORT(save, tree::inode)\nBSS_FCN_EXPORT(load, tree::inode)\n\n\/*-----------------------------------------------------------------------------\n * link_impl\n *-----------------------------------------------------------------------------*\/\nBSS_FCN_BEGIN(serialize, tree::link_impl)\n\t\/\/ [NOTE] intentionally do net serialize owner, it will be set up when parent node is loaded\n\tar(\n\t\tmake_nvp(\"id\", t.id_),\n\t\tmake_nvp(\"name\", t.name_),\n\t\tmake_nvp(\"flags\", t.flags_)\n\t);\nBSS_FCN_END\n\nCEREAL_REGISTER_POLYMORPHIC_RELATION(tree::engine::impl, tree::link_impl)\nCEREAL_REGISTER_TYPE_WITH_NAME(tree::link_impl, \"link\")\nBSS_FCN_EXPORT(serialize, tree::link_impl)\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ ilink_impl\n\/\/\nBSS_FCN_INL_BEGIN(serialize, tree::ilink_impl)\n\t\/\/ serialize inode\n\t\/\/ [NOTE] disabled - inodes aren't actually used now\n\t\/\/ [TODO] reenable later when conception will be more thought out\n\t\/\/ar(make_nvp(\"inode\", t.inode_));\n\n\tserialize<tree::link_impl>::go(ar, t, version);\nBSS_FCN_INL_END(serialize, tree::ilink_impl)\n\nCEREAL_REGISTER_POLYMORPHIC_RELATION(tree::link_impl, tree::ilink_impl)\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ hard_link_impl\n\/\/\nBSS_FCN_INL_BEGIN(serialize, tree::hard_link_impl)\n\tif constexpr(Archive::is_saving::value) {\n\t\tar( make_nvp(\"data\", t.data_) );\n\t}\n\telse {\n\t\t\/\/ load data with deferred 2nd trial\n\t\tar(defer_failed(\n\t\t\tt.data_,\n\t\t\t[&t](auto obj) { t.set_data(std::move(obj)); },\n\t\t\tPtrInitTrigger::SuccessAndRetry\n\t\t));\n\t}\n\n\tserialize<tree::ilink_impl>::go(ar, t, version);\n\t\/\/ar( make_nvp(\"linkbase\", base_class<tree::ilink_impl>(&t)) );\nBSS_FCN_INL_END(serialize, tree::hard_link_impl)\n\nCEREAL_REGISTER_POLYMORPHIC_RELATION(tree::ilink_impl, tree::hard_link_impl)\nCEREAL_REGISTER_TYPE_WITH_NAME(tree::hard_link_impl, \"hard_link\")\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ weak_link_impl\n\/\/\nBSS_FCN_INL_BEGIN(serialize, tree::weak_link_impl)\n\tif constexpr(Archive::is_saving::value) {\n\t\tar( make_nvp(\"data\", t.data_.lock()) );\n\t}\n\telse {\n\t\tauto unused = sp_obj{};\n\t\tar(defer_failed(\n\t\t\tunused,\n\t\t\t[&t](auto obj) { t.set_data(std::move(obj)); },\n\t\t\tPtrInitTrigger::SuccessAndRetry\n\t\t));\n\t}\n\n\tserialize<tree::ilink_impl>::go(ar, t, version);\nBSS_FCN_INL_END(serialize, tree::weak_link_impl)\n\nCEREAL_REGISTER_POLYMORPHIC_RELATION(tree::ilink_impl, tree::weak_link_impl)\nCEREAL_REGISTER_TYPE_WITH_NAME(tree::weak_link_impl, \"weak_link\")\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ sym_link_impl\n\/\/\nBSS_FCN_INL_BEGIN(serialize, tree::sym_link_impl)\n\tar(make_nvp(\"path\", t.path_));\n\n\tserialize<tree::link_impl>::go(ar, t, version);\nBSS_FCN_INL_END(serialize, tree::sym_link_impl)\n\nCEREAL_REGISTER_POLYMORPHIC_RELATION(tree::link_impl, tree::sym_link_impl)\nCEREAL_REGISTER_TYPE_WITH_NAME(tree::sym_link_impl, \"sym_link\")\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ fusion_link_impl\n\/\/\nNAMESPACE_BEGIN()\n\ntemplate<typename Archive>\nauto serialize_status(Archive& ar, tree::link_impl& t) {\n\tusing namespace blue_sky::tree;\n\tusing array_t = std::array<tree::ReqStatus, 2>;\n\n\tauto stat = [&]() -> array_t {\n\t\tif constexpr(Archive::is_saving::value)\n\t\t\treturn {t.req_status(Req::Data), t.req_status(Req::DataNode)};\n\t\telse return {};\n\t}();\n\tserialize_carray(ar, stat, \"status\");\n\n\tif constexpr(Archive::is_loading::value) {\n\t\tt.rs_reset(Req::Data, ReqReset::Always, stat[0]);\n\t\tt.rs_reset(Req::DataNode, ReqReset::Always, stat[1]);\n\t}\n}\n\nNAMESPACE_END()\n\nBSS_FCN_INL_BEGIN(serialize, tree::fusion_link_impl)\n\tusing namespace blue_sky::tree;\n\n\tif constexpr(Archive::is_saving::value) {\n\t\tar( make_nvp(\"bridge\", t.bridge_) );\n\t\t\/\/ save cached object\n\t\tar( make_nvp(\"data\", t.data_) );\n\t}\n\telse {\n\t\t\/\/ load bridge with deferred trial\n\t\tar(defer_failed(\n\t\t\tt.bridge_,\n\t\t\t[&t](auto B) { t.bridge_ = std::move(B); },\n\t\t\tPtrInitTrigger::SuccessAndRetry\n\t\t));\n\t\t\/\/ load data with deferred 2nd trial\n\t\tar(defer_failed(\n\t\t\tt.data_,\n\t\t\t[&](auto obj) { t.data_ = std::move(obj); },\n\t\t\tPtrInitTrigger::SuccessAndRetry\n\t\t));\n\t}\n\n\tserialize_status(ar, t);\n\tserialize<tree::ilink_impl>::go(ar, t, version);\nBSS_FCN_INL_END(serialize, tree::fusion_link_impl)\n\nCEREAL_REGISTER_POLYMORPHIC_RELATION(tree::ilink_impl, tree::fusion_link_impl)\nCEREAL_REGISTER_TYPE_WITH_NAME(tree::fusion_link_impl, \"fusion_link\")\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ map_link\n\/\/\nBSS_FCN_INL_BEGIN(serialize, tree::map_link_impl_base)\n\tif constexpr(Archive::is_saving::value) {\n\t\t\/\/ dump contained node only if map_link owns it\n\t\tif(t.out_.handle().id() == t.id_)\n\t\t\tar(make_nvp( \"out\", t.out_ ));\n\t\telse\n\t\t\tar(make_nvp( \"out\", tree::node::nil() ));\n\t}\n\telse {\n\t\t\/\/ load out node\n\t\ttree::node out_node;\n\t\tar(make_nvp( \"out\", out_node ));\n\t\tif(t.out_ = out_node)\n\t\t\tt.link_impl::propagate_handle(t.out_);\n\t}\n\n\tserialize_status(ar, t);\n\tserialize<tree::link_impl>::go(ar, t, version);\nBSS_FCN_INL_END(serialize, tree::map_link_impl_base)\n\n\nBSS_FCN_INL_BEGIN(serialize, tree::map_link_impl)\n\tar(make_nvp( \"io_map\", t.io_map_ ));\n\tserialize<tree::map_link_impl_base>::go(ar, t, version);\nBSS_FCN_INL_END(serialize, tree::map_link_impl)\n\n\nBSS_FCN_INL_BEGIN(serialize, tree::map_node_impl)\n\tserialize<tree::map_link_impl_base>::go(ar, t, version);\nBSS_FCN_INL_END(serialize, tree::map_node_impl)\n\nCEREAL_REGISTER_POLYMORPHIC_RELATION(tree::link_impl, tree::map_link_impl_base)\nCEREAL_REGISTER_POLYMORPHIC_RELATION(tree::map_link_impl_base, tree::map_link_impl)\nCEREAL_REGISTER_POLYMORPHIC_RELATION(tree::map_link_impl_base, tree::map_node_impl)\nCEREAL_REGISTER_TYPE_WITH_NAME(tree::map_link_impl, \"map_link\")\nCEREAL_REGISTER_TYPE_WITH_NAME(tree::map_node_impl, \"map_node\")\n\n\/*-----------------------------------------------------------------------------\n * link\n *-----------------------------------------------------------------------------*\/\nBSS_FCN_BEGIN(serialize, tree::link)\n\t\/\/ [NOTE] intentionally do net serialize owner, it will be set up when parent node is loaded\n\tif constexpr(Archive::is_saving::value) {\n\t\t\/\/ for nil link save empty impl pointer\n\t\tar(make_nvp( \"link\", t ? t.pimpl_ : tree::sp_limpl{} ));\n\t}\n\telse {\n\t\tar(make_nvp(\"link\", t.pimpl_));\n\t\tif(t.pimpl_) {\n\t\t\t\/\/ ID is ready, we can start internal actor\n\t\t\tt.start_engine();\n\t\t\t\/\/ if pointee is a node, correct it's handle\n\t\t\tt.pimpl()->propagate_handle();\n\t\t}\n\t\telse\n\t\t\tt = tree::link{};\n\t}\nBSS_FCN_END\n\nBSS_FCN_EXPORT(serialize, tree::link)\n\nBSS_REGISTER_DYNAMIC_INIT(link)\n<|endoftext|>"} {"text":"<commit_before>\/\/===--- IterativeTypeChecker.cpp - Iterative Type Checker ----------------===\/\/\n\/\/\n\/\/ This source file is part of the Swift.org open source project\n\/\/\n\/\/ Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors\n\/\/ Licensed under Apache License v2.0 with Runtime Library Exception\n\/\/\n\/\/ See http:\/\/swift.org\/LICENSE.txt for license information\n\/\/ See http:\/\/swift.org\/CONTRIBUTORS.txt for the list of Swift project authors\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This file implements the IterativeTypeChecker class, which\n\/\/ performs iterative type checking by tracking the set of\n\/\/ outstanding type-checking requests and servicing them as needed.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"TypeChecker.h\"\n#include \"swift\/Sema\/IterativeTypeChecker.h\"\n#include \"swift\/AST\/Decl.h\"\n#include \"swift\/AST\/DiagnosticsSema.h\"\n#include \"swift\/Basic\/Defer.h\"\nusing namespace swift;\n\nASTContext &IterativeTypeChecker::getASTContext() const {\n return TC.Context;\n}\n\nDiagnosticEngine &IterativeTypeChecker::getDiags() const {\n return getASTContext().Diags;\n}\n\nvoid IterativeTypeChecker::process(\n TypeCheckRequest request,\n UnsatisfiedDependency unsatisfiedDependency) {\n switch (request.getKind()) {\n#define TYPE_CHECK_REQUEST(Request,PayloadName) \\\n case TypeCheckRequest::Request: \\\n return process##Request(request.get##PayloadName##Payload(), \\\n unsatisfiedDependency);\n\n#include \"swift\/Sema\/TypeCheckRequestKinds.def\"\n }\n}\n\n\/\/\/ Determine whether the given request has already been satisfied.\nbool IterativeTypeChecker::isSatisfied(TypeCheckRequest request) {\n switch (request.getKind()) {\n#define TYPE_CHECK_REQUEST(Request,PayloadName) \\\n case TypeCheckRequest::Request: \\\n return is##Request##Satisfied(request.get##PayloadName##Payload());\n\n#include \"swift\/Sema\/TypeCheckRequestKinds.def\"\n }\n}\n\nbool IterativeTypeChecker::breakCycle(TypeCheckRequest request) {\n switch (request.getKind()) {\n#define TYPE_CHECK_REQUEST(Request,PayloadName) \\\n case TypeCheckRequest::Request: \\\n return breakCycleFor##Request(request.get##PayloadName##Payload());\n\n#include \"swift\/Sema\/TypeCheckRequestKinds.def\"\n } \n}\n\nvoid IterativeTypeChecker::satisfy(TypeCheckRequest request) {\n auto startingSize = ActiveRequests.size();\n \n auto addToActiveRequests = [&](TypeCheckRequest request) {\n \/\/ Check for circular dependencies in our requests.\n auto existingRequest = std::find(ActiveRequests.rbegin(),\n ActiveRequests.rend(),\n request);\n if (existingRequest != ActiveRequests.rend()) {\n auto first = existingRequest.base();\n --first;\n diagnoseCircularReference(llvm::makeArrayRef(&*first,\n &*ActiveRequests.end()));\n return;\n }\n \/\/ Add this request to the stack of active requests.\n ActiveRequests.push_back(request);\n };\n \n addToActiveRequests(request);\n SWIFT_DEFER { ActiveRequests.pop_back(); };\n\n while (ActiveRequests.size() != startingSize) {\n request = ActiveRequests.back();\n \/\/ If the request has already been satisfied, we're done.\n if (isSatisfied(request)) {\n ActiveRequests.pop_back();\n continue;\n }\n \n \/\/ Process this requirement, enumerating dependencies if anything else needs\n \/\/ to be handled first.\n process(request, [&](TypeCheckRequest dependency) -> bool {\n if (isSatisfied(dependency)) return false;\n \/\/ Record the unsatisfied dependency.\n addToActiveRequests(dependency);\n return true;\n });\n }\n}\n\nstatic bool isSelfRedefinedTypeAliasDecl(const TypeCheckRequest &Request) {\n if (Request.getKind() == TypeCheckRequest::Kind::ResolveTypeDecl) {\n if (auto TAD = dyn_cast<TypeAliasDecl>(Request.getAnchor())) {\n SourceRange SR = TAD->getUnderlyingTypeLoc().getSourceRange();\n SourceManager &SM = TAD->getASTContext().SourceMgr;\n CharSourceRange CR = CharSourceRange(SM, SR.Start,\n Lexer::getLocForEndOfToken(SM,\n SR.End));\n return CR.str() == TAD->getNameStr();\n }\n }\n return false;\n}\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ Diagnostics\n\/\/===----------------------------------------------------------------------===\/\/\nvoid IterativeTypeChecker::diagnoseCircularReference(\n ArrayRef<TypeCheckRequest> requests) {\n bool isFirst = true;\n for (const auto &request : requests) {\n if (isSelfRedefinedTypeAliasDecl(request)) {\n diagnose(request.getLoc(), diag::redundant_type_alias_define).\n fixItRemove(request.getAnchor()->getSourceRange());\n } else {\n diagnose(request.getLoc(),\n isFirst ? diag::circular_reference :\n diag::circular_reference_through);\n }\n\n isFirst = false;\n }\n\n \/\/ Now try to break the cycle.\n#ifndef NDEBUG\n bool brokeCycle = false;\n#endif\n for (const auto &request : reverse(requests)) {\n if (breakCycle(request)) {\n#ifndef NDEBUG\n brokeCycle = true;\n#endif\n break;\n }\n }\n\n assert(brokeCycle && \"Will the cycle be unbroken?\");\n}\n<commit_msg>Revert IterativeTypeChecker changes<commit_after>\/\/===--- IterativeTypeChecker.cpp - Iterative Type Checker ----------------===\/\/\n\/\/\n\/\/ This source file is part of the Swift.org open source project\n\/\/\n\/\/ Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors\n\/\/ Licensed under Apache License v2.0 with Runtime Library Exception\n\/\/\n\/\/ See http:\/\/swift.org\/LICENSE.txt for license information\n\/\/ See http:\/\/swift.org\/CONTRIBUTORS.txt for the list of Swift project authors\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This file implements the IterativeTypeChecker class, which\n\/\/ performs iterative type checking by tracking the set of\n\/\/ outstanding type-checking requests and servicing them as needed.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"TypeChecker.h\"\n#include \"swift\/Sema\/IterativeTypeChecker.h\"\n#include \"swift\/AST\/Decl.h\"\n#include \"swift\/AST\/DiagnosticsSema.h\"\n#include \"swift\/Basic\/Defer.h\"\nusing namespace swift;\n\nASTContext &IterativeTypeChecker::getASTContext() const {\n return TC.Context;\n}\n\nDiagnosticEngine &IterativeTypeChecker::getDiags() const {\n return getASTContext().Diags;\n}\n\nvoid IterativeTypeChecker::process(\n TypeCheckRequest request,\n UnsatisfiedDependency unsatisfiedDependency) {\n switch (request.getKind()) {\n#define TYPE_CHECK_REQUEST(Request,PayloadName) \\\n case TypeCheckRequest::Request: \\\n return process##Request(request.get##PayloadName##Payload(), \\\n unsatisfiedDependency);\n\n#include \"swift\/Sema\/TypeCheckRequestKinds.def\"\n }\n}\n\n\/\/\/ Determine whether the given request has already been satisfied.\nbool IterativeTypeChecker::isSatisfied(TypeCheckRequest request) {\n switch (request.getKind()) {\n#define TYPE_CHECK_REQUEST(Request,PayloadName) \\\n case TypeCheckRequest::Request: \\\n return is##Request##Satisfied(request.get##PayloadName##Payload());\n\n#include \"swift\/Sema\/TypeCheckRequestKinds.def\"\n }\n}\n\nbool IterativeTypeChecker::breakCycle(TypeCheckRequest request) {\n switch (request.getKind()) {\n#define TYPE_CHECK_REQUEST(Request,PayloadName) \\\n case TypeCheckRequest::Request: \\\n return breakCycleFor##Request(request.get##PayloadName##Payload());\n\n#include \"swift\/Sema\/TypeCheckRequestKinds.def\"\n } \n}\n\nvoid IterativeTypeChecker::satisfy(TypeCheckRequest request) {\n \/\/ If the request has already been satisfied, we're done.\n if (isSatisfied(request)) return;\n\n \/\/ Check for circular dependencies in our requests.\n \/\/ FIXME: This stack operation is painfully inefficient.\n auto existingRequest = std::find(ActiveRequests.rbegin(),\n ActiveRequests.rend(),\n request);\n if (existingRequest != ActiveRequests.rend()) {\n auto first = existingRequest.base();\n --first;\n diagnoseCircularReference(llvm::makeArrayRef(&*first,\n &*ActiveRequests.end()));\n return;\n }\n\n \/\/ Add this request to the stack of active requests.\n ActiveRequests.push_back(request);\n SWIFT_DEFER { ActiveRequests.pop_back(); };\n\n while (true) {\n \/\/ Process this requirement, enumerating dependencies if anything else needs\n \/\/ to be handled first.\n SmallVector<TypeCheckRequest, 4> unsatisfied;\n process(request, [&](TypeCheckRequest dependency) -> bool {\n if (isSatisfied(dependency)) return false;\n\n \/\/ Record the unsatisfied dependency.\n unsatisfied.push_back(dependency);\n return true;\n });\n\n \/\/ If there were no unsatisfied dependencies, we're done.\n if (unsatisfied.empty()) {\n assert(isSatisfied(request));\n break;\n }\n\n \/\/ Recurse to satisfy any unsatisfied dependencies.\n \/\/ FIXME: Don't recurse in the iterative type checker, silly!\n for (auto dependency : unsatisfied) {\n satisfy(dependency);\n }\n }\n}\n\nstatic bool isSelfRedefinedTypeAliasDecl(const TypeCheckRequest &Request) {\n if (Request.getKind() == TypeCheckRequest::Kind::ResolveTypeDecl) {\n if (auto TAD = dyn_cast<TypeAliasDecl>(Request.getAnchor())) {\n SourceRange SR = TAD->getUnderlyingTypeLoc().getSourceRange();\n SourceManager &SM = TAD->getASTContext().SourceMgr;\n CharSourceRange CR = CharSourceRange(SM, SR.Start,\n Lexer::getLocForEndOfToken(SM,\n SR.End));\n return CR.str() == TAD->getNameStr();\n }\n }\n return false;\n}\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ Diagnostics\n\/\/===----------------------------------------------------------------------===\/\/\nvoid IterativeTypeChecker::diagnoseCircularReference(\n ArrayRef<TypeCheckRequest> requests) {\n bool isFirst = true;\n for (const auto &request : requests) {\n if (isSelfRedefinedTypeAliasDecl(request)) {\n diagnose(request.getLoc(), diag::redundant_type_alias_define).\n fixItRemove(request.getAnchor()->getSourceRange());\n } else {\n diagnose(request.getLoc(),\n isFirst ? diag::circular_reference :\n diag::circular_reference_through);\n }\n\n isFirst = false;\n }\n\n \/\/ Now try to break the cycle.\n#ifndef NDEBUG\n bool brokeCycle = false;\n#endif\n for (const auto &request : reverse(requests)) {\n if (breakCycle(request)) {\n#ifndef NDEBUG\n brokeCycle = true;\n#endif\n break;\n }\n }\n\n assert(brokeCycle && \"Will the cycle be unbroken?\");\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n\tThis file is part of cpp-ethereum.\n\n\tcpp-ethereum is free software: you can redistribute it and\/or modify\n\tit under the terms of the GNU General Public License as published by\n\tthe Free Software Foundation, either version 3 of the License, or\n\t(at your option) any later version.\n\n\tcpp-ethereum is distributed in the hope that it will be useful,\n\tbut WITHOUT ANY WARRANTY; without even the implied warranty of\n\tMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n\tGNU General Public License for more details.\n\n\tYou should have received a copy of the GNU General Public License\n\talong with cpp-ethereum. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n\/**\n * @author Marek Kotewicz <marek@ethdev.com>\n * @date 2014\n * Unit tests for the solidity compiler JSON Interface output.\n *\/\n\n#include \"..\/TestHelper.h\"\n#include <libsolidity\/CompilerStack.h>\n#include <json\/json.h>\n#include <libdevcore\/Exceptions.h>\n\nnamespace dev\n{\nnamespace solidity\n{\nnamespace test\n{\n\nclass JSONInterfaceChecker\n{\npublic:\n\tJSONInterfaceChecker(): m_compilerStack(false) {}\n\n\tvoid checkInterface(std::string const& _code, std::string const& _expectedInterfaceString)\n\t{\n\t\tETH_TEST_REQUIRE_NO_THROW(m_compilerStack.parse(_code), \"Parsing contract failed\");\n\t\tstd::string generatedInterfaceString = m_compilerStack.getMetadata(\"\", DocumentationType::ABIInterface);\n\t\tJson::Value generatedInterface;\n\t\tm_reader.parse(generatedInterfaceString, generatedInterface);\n\t\tJson::Value expectedInterface;\n\t\tm_reader.parse(_expectedInterfaceString, expectedInterface);\n\t\tBOOST_CHECK_MESSAGE(expectedInterface == generatedInterface,\n\t\t\t\t\t\t\t\"Expected:\\n\" << expectedInterface.toStyledString() <<\n\t\t\t\t\t\t\t\"\\n but got:\\n\" << generatedInterface.toStyledString());\n\t}\n\nprivate:\n\tCompilerStack m_compilerStack;\n\tJson::Reader m_reader;\n};\n\nBOOST_FIXTURE_TEST_SUITE(SolidityABIJSON, JSONInterfaceChecker)\n\nBOOST_AUTO_TEST_CASE(basic_test)\n{\n\tchar const* sourceCode = \"contract test {\\n\"\n\t\" function f(uint a) returns(uint d) { return a * 7; }\\n\"\n\t\"}\\n\";\n\n\tchar const* interface = R\"([\n\t{\n\t\t\"name\": \"f\",\n\t\t\"constant\": false,\n\t\t\"type\": \"function\",\n\t\t\"inputs\": [\n\t\t{\n\t\t\t\"name\": \"a\",\n\t\t\t\"type\": \"uint256\"\n\t\t}\n\t\t],\n\t\t\"outputs\": [\n\t\t{\n\t\t\t\"name\": \"d\",\n\t\t\t\"type\": \"uint256\"\n\t\t}\n\t\t]\n\t}\n\t])\";\n\n\tcheckInterface(sourceCode, interface);\n}\n\nBOOST_AUTO_TEST_CASE(empty_contract)\n{\n\tchar const* sourceCode = \"contract test {\\n\"\n\t\"}\\n\";\n\tchar const* interface = \"[]\";\n\n\tcheckInterface(sourceCode, interface);\n}\n\nBOOST_AUTO_TEST_CASE(multiple_methods)\n{\n\tchar const* sourceCode = \"contract test {\\n\"\n\t\" function f(uint a) returns(uint d) { return a * 7; }\\n\"\n\t\" function g(uint b) returns(uint e) { return b * 8; }\\n\"\n\t\"}\\n\";\n\n\tchar const* interface = R\"([\n\t{\n\t\t\"name\": \"f\",\n\t\t\"constant\": false,\n\t\t\"type\": \"function\",\n\t\t\"inputs\": [\n\t\t{\n\t\t\t\"name\": \"a\",\n\t\t\t\"type\": \"uint256\"\n\t\t}\n\t\t],\n\t\t\"outputs\": [\n\t\t{\n\t\t\t\"name\": \"d\",\n\t\t\t\"type\": \"uint256\"\n\t\t}\n\t\t]\n\t},\n\t{\n\t\t\"name\": \"g\",\n\t\t\"constant\": false,\n\t\t\"type\": \"function\",\n\t\t\"inputs\": [\n\t\t{\n\t\t\t\"name\": \"b\",\n\t\t\t\"type\": \"uint256\"\n\t\t}\n\t\t],\n\t\t\"outputs\": [\n\t\t{\n\t\t\t\"name\": \"e\",\n\t\t\t\"type\": \"uint256\"\n\t\t}\n\t\t]\n\t}\n\t])\";\n\n\tcheckInterface(sourceCode, interface);\n}\n\nBOOST_AUTO_TEST_CASE(multiple_params)\n{\n\tchar const* sourceCode = \"contract test {\\n\"\n\t\" function f(uint a, uint b) returns(uint d) { return a + b; }\\n\"\n\t\"}\\n\";\n\n\tchar const* interface = R\"([\n\t{\n\t\t\"name\": \"f\",\n\t\t\"constant\": false,\n\t\t\"type\": \"function\",\n\t\t\"inputs\": [\n\t\t{\n\t\t\t\"name\": \"a\",\n\t\t\t\"type\": \"uint256\"\n\t\t},\n\t\t{\n\t\t\t\"name\": \"b\",\n\t\t\t\"type\": \"uint256\"\n\t\t}\n\t\t],\n\t\t\"outputs\": [\n\t\t{\n\t\t\t\"name\": \"d\",\n\t\t\t\"type\": \"uint256\"\n\t\t}\n\t\t]\n\t}\n\t])\";\n\n\tcheckInterface(sourceCode, interface);\n}\n\nBOOST_AUTO_TEST_CASE(multiple_methods_order)\n{\n\t\/\/ methods are expected to be in alpabetical order\n\tchar const* sourceCode = \"contract test {\\n\"\n\t\" function f(uint a) returns(uint d) { return a * 7; }\\n\"\n\t\" function c(uint b) returns(uint e) { return b * 8; }\\n\"\n\t\"}\\n\";\n\n\tchar const* interface = R\"([\n\t{\n\t\t\"name\": \"c\",\n\t\t\"constant\": false,\n\t\t\"type\": \"function\",\n\t\t\"inputs\": [\n\t\t{\n\t\t\t\"name\": \"b\",\n\t\t\t\"type\": \"uint256\"\n\t\t}\n\t\t],\n\t\t\"outputs\": [\n\t\t{\n\t\t\t\"name\": \"e\",\n\t\t\t\"type\": \"uint256\"\n\t\t}\n\t\t]\n\t},\n\t{\n\t\t\"name\": \"f\",\n\t\t\"constant\": false,\n\t\t\"type\": \"function\",\n\t\t\"inputs\": [\n\t\t{\n\t\t\t\"name\": \"a\",\n\t\t\t\"type\": \"uint256\"\n\t\t}\n\t\t],\n\t\t\"outputs\": [\n\t\t{\n\t\t\t\"name\": \"d\",\n\t\t\t\"type\": \"uint256\"\n\t\t}\n\t\t]\n\t}\n\t])\";\n\n\tcheckInterface(sourceCode, interface);\n}\n\nBOOST_AUTO_TEST_CASE(const_function)\n{\n\tchar const* sourceCode = \"contract test {\\n\"\n\t\" function foo(uint a, uint b) returns(uint d) { return a + b; }\\n\"\n\t\" function boo(uint32 a) constant returns(uint b) { return a * 4; }\\n\"\n\t\"}\\n\";\n\n\tchar const* interface = R\"([\n\t{\n\t\t\"name\": \"foo\",\n\t\t\"constant\": false,\n\t\t\"type\": \"function\",\n\t\t\"inputs\": [\n\t\t{\n\t\t\t\"name\": \"a\",\n\t\t\t\"type\": \"uint256\"\n\t\t},\n\t\t{\n\t\t\t\"name\": \"b\",\n\t\t\t\"type\": \"uint256\"\n\t\t}\n\t\t],\n\t\t\"outputs\": [\n\t\t{\n\t\t\t\"name\": \"d\",\n\t\t\t\"type\": \"uint256\"\n\t\t}\n\t\t]\n\t},\n\t{\n\t\t\"name\": \"boo\",\n\t\t\"constant\": true,\n\t\t\"type\": \"function\",\n\t\t\"inputs\": [{\n\t\t\t\"name\": \"a\",\n\t\t\t\"type\": \"uint32\"\n\t\t}],\n\t\t\"outputs\": [\n\t\t{\n\t\t\t\"name\": \"b\",\n\t\t\t\"type\": \"uint256\"\n\t\t}\n\t\t]\n\t}\n\t])\";\n\n\tcheckInterface(sourceCode, interface);\n}\n\nBOOST_AUTO_TEST_CASE(exclude_fallback_function)\n{\n\tchar const* sourceCode = \"contract test { function() {} }\";\n\n\tchar const* interface = \"[]\";\n\n\tcheckInterface(sourceCode, interface);\n}\n\nBOOST_AUTO_TEST_CASE(events)\n{\n\tchar const* sourceCode = \"contract test {\\n\"\n\t\" function f(uint a) returns(uint d) { return a * 7; }\\n\"\n\t\" event e1(uint b, address indexed c); \\n\"\n\t\" event e2(); \\n\"\n\t\"}\\n\";\n\tchar const* interface = R\"([\n\t{\n\t\t\"name\": \"f\",\n\t\t\"constant\": false,\n\t\t\"type\": \"function\",\n\t\t\"inputs\": [\n\t\t{\n\t\t\t\"name\": \"a\",\n\t\t\t\"type\": \"uint256\"\n\t\t}\n\t\t],\n\t\t\"outputs\": [\n\t\t{\n\t\t\t\"name\": \"d\",\n\t\t\t\"type\": \"uint256\"\n\t\t}\n\t\t]\n\t},\n\t{\n\t\t\"name\": \"e1\",\n\t\t\"type\": \"event\",\n\t\t\"anonymous\": false,\n\t\t\"inputs\": [\n\t\t{\n\t\t\t\"indexed\": false,\n\t\t\t\"name\": \"b\",\n\t\t\t\"type\": \"uint256\"\n\t\t},\n\t\t{\n\t\t\t\"indexed\": true,\n\t\t\t\"name\": \"c\",\n\t\t\t\"type\": \"address\"\n\t\t}\n\t\t]\n\t},\n\t{\n\t\t\"name\": \"e2\",\n\t\t\"type\": \"event\",\n\t\t\"anonymous\": false,\n\t\t\"inputs\": []\n\t}\n\n\t])\";\n\n\tcheckInterface(sourceCode, interface);\n}\n\nBOOST_AUTO_TEST_CASE(events_anonymous)\n{\n\tchar const* sourceCode = \"contract test {\\n\"\n\t\" event e() anonymous; \\n\"\n\t\"}\\n\";\n\tchar const* interface = R\"([\n\t{\n\t\t\"name\": \"e\",\n\t\t\"type\": \"event\",\n\t\t\"anonymous\": true,\n\t\t\"inputs\": []\n\t}\n\n\t])\";\n\n\tcheckInterface(sourceCode, interface);\n}\n\nBOOST_AUTO_TEST_CASE(inherited)\n{\n\tchar const* sourceCode =\n\t\"\tcontract Base { \\n\"\n\t\"\t\tfunction baseFunction(uint p) returns (uint i) { return p; } \\n\"\n\t\"\t\tevent baseEvent(bytes32 indexed evtArgBase); \\n\"\n\t\"\t} \\n\"\n\t\"\tcontract Derived is Base { \\n\"\n\t\"\t\tfunction derivedFunction(bytes32 p) returns (bytes32 i) { return p; } \\n\"\n\t\"\t\tevent derivedEvent(uint indexed evtArgDerived); \\n\"\n\t\"\t}\";\n\n\tchar const* interface = R\"([\n\t{\n\t\t\"name\": \"baseFunction\",\n\t\t\"constant\": false,\n\t\t\"type\": \"function\",\n\t\t\"inputs\":\n\t\t[{\n\t\t\t\"name\": \"p\",\n\t\t\t\"type\": \"uint256\"\n\t\t}],\n\t\t\"outputs\":\n\t\t[{\n\t\t\t\"name\": \"i\",\n\t\t\t\"type\": \"uint256\"\n\t\t}]\n\t},\n\t{\n\t\t\"name\": \"derivedFunction\",\n\t\t\"constant\": false,\n\t\t\"type\": \"function\",\n\t\t\"inputs\":\n\t\t[{\n\t\t\t\"name\": \"p\",\n\t\t\t\"type\": \"bytes32\"\n\t\t}],\n\t\t\"outputs\":\n\t\t[{\n\t\t\t\"name\": \"i\",\n\t\t\t\"type\": \"bytes32\"\n\t\t}]\n\t},\n\t{\n\t\t\"name\": \"derivedEvent\",\n\t\t\"type\": \"event\",\n\t\t\"anonymous\": false,\n\t\t\"inputs\":\n\t\t[{\n\t\t\t\"indexed\": true,\n\t\t\t\"name\": \"evtArgDerived\",\n\t\t\t\"type\": \"uint256\"\n\t\t}]\n\t},\n\t{\n\t\t\"name\": \"baseEvent\",\n\t\t\"type\": \"event\",\n\t\t\"anonymous\": false,\n\t\t\"inputs\":\n\t\t[{\n\t\t\t\"indexed\": true,\n\t\t\t\"name\": \"evtArgBase\",\n\t\t\t\"type\": \"bytes32\"\n\t\t}]\n\t}])\";\n\n\n\tcheckInterface(sourceCode, interface);\n}\nBOOST_AUTO_TEST_CASE(empty_name_input_parameter_with_named_one)\n{\n\tchar const* sourceCode = R\"(\n\tcontract test {\n\t\tfunction f(uint, uint k) returns(uint ret_k, uint ret_g){\n\t\t\tuint g = 8;\n\t\t\tret_k = k;\n\t\t\tret_g = g;\n\t\t}\n\t})\";\n\n\tchar const* interface = R\"([\n\t{\n\t\t\"name\": \"f\",\n\t\t\"constant\": false,\n\t\t\"type\": \"function\",\n\t\t\"inputs\": [\n\t\t{\n\t\t\t\"name\": \"\",\n\t\t\t\"type\": \"uint256\"\n\t\t},\n\t\t{\n\t\t\t\"name\": \"k\",\n\t\t\t\"type\": \"uint256\"\n\t\t}\n\t\t],\n\t\t\"outputs\": [\n\t\t{\n\t\t\t\"name\": \"ret_k\",\n\t\t\t\"type\": \"uint256\"\n\t\t},\n\t\t{\n\t\t\t\"name\": \"ret_g\",\n\t\t\t\"type\": \"uint256\"\n\t\t}\n\t\t]\n\t}\n\t])\";\n\n\tcheckInterface(sourceCode, interface);\n}\n\nBOOST_AUTO_TEST_CASE(empty_name_return_parameter)\n{\n\tchar const* sourceCode = R\"(\n\t\tcontract test {\n\t\tfunction f(uint k) returns(uint){\n\t\t\treturn k;\n\t\t}\n\t})\";\n\n\tchar const* interface = R\"([\n\t{\n\t\t\"name\": \"f\",\n\t\t\"constant\": false,\n\t\t\"type\": \"function\",\n\t\t\"inputs\": [\n\t\t{\n\t\t\t\"name\": \"k\",\n\t\t\t\"type\": \"uint256\"\n\t\t}\n\t\t],\n\t\t\"outputs\": [\n\t\t{\n\t\t\t\"name\": \"\",\n\t\t\t\"type\": \"uint256\"\n\t\t}\n\t\t]\n\t}\n\t])\";\n\tcheckInterface(sourceCode, interface);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n\n}\n}\n}\n<commit_msg>test for resalts<commit_after>\/*\n\tThis file is part of cpp-ethereum.\n\n\tcpp-ethereum is free software: you can redistribute it and\/or modify\n\tit under the terms of the GNU General Public License as published by\n\tthe Free Software Foundation, either version 3 of the License, or\n\t(at your option) any later version.\n\n\tcpp-ethereum is distributed in the hope that it will be useful,\n\tbut WITHOUT ANY WARRANTY; without even the implied warranty of\n\tMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n\tGNU General Public License for more details.\n\n\tYou should have received a copy of the GNU General Public License\n\talong with cpp-ethereum. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n\/**\n * @author Marek Kotewicz <marek@ethdev.com>\n * @date 2014\n * Unit tests for the solidity compiler JSON Interface output.\n *\/\n\n#include \"..\/TestHelper.h\"\n#include <libsolidity\/CompilerStack.h>\n#include <json\/json.h>\n#include <libdevcore\/Exceptions.h>\n\nnamespace dev\n{\nnamespace solidity\n{\nnamespace test\n{\n\nclass JSONInterfaceChecker\n{\npublic:\n\tJSONInterfaceChecker(): m_compilerStack(false) {}\n\n\tvoid checkInterface(std::string const& _code, std::string const& _expectedInterfaceString)\n\t{\n\t\tETH_TEST_REQUIRE_NO_THROW(m_compilerStack.parse(_code), \"Parsing contract failed\");\n\t\tstd::string generatedInterfaceString = m_compilerStack.getMetadata(\"\", DocumentationType::ABIInterface);\n\t\tJson::Value generatedInterface;\n\t\tm_reader.parse(generatedInterfaceString, generatedInterface);\n\t\tJson::Value expectedInterface;\n\t\tm_reader.parse(_expectedInterfaceString, expectedInterface);\n\t\tBOOST_CHECK_MESSAGE(expectedInterface == generatedInterface,\n\t\t\t\t\t\t\t\"Expected:\\n\" << expectedInterface.toStyledString() <<\n\t\t\t\t\t\t\t\"\\n but got:\\n\" << generatedInterface.toStyledString());\n\t}\n\nprivate:\n\tCompilerStack m_compilerStack;\n\tJson::Reader m_reader;\n};\n\nBOOST_FIXTURE_TEST_SUITE(SolidityABIJSON, JSONInterfaceChecker)\n\nBOOST_AUTO_TEST_CASE(basic_test)\n{\n\tchar const* sourceCode = \"contract test {\\n\"\n\t\" function f(uint a) returns(uint d) { return a * 7; }\\n\"\n\t\"}\\n\";\n\n\tchar const* interface = R\"([\n\t{\n\t\t\"name\": \"f\",\n\t\t\"constant\": false,\n\t\t\"type\": \"function\",\n\t\t\"inputs\": [\n\t\t{\n\t\t\t\"name\": \"a\",\n\t\t\t\"type\": \"uint256\"\n\t\t}\n\t\t],\n\t\t\"outputs\": [\n\t\t{\n\t\t\t\"name\": \"d\",\n\t\t\t\"type\": \"uint256\"\n\t\t}\n\t\t]\n\t}\n\t])\";\n\n\tcheckInterface(sourceCode, interface);\n}\n\nBOOST_AUTO_TEST_CASE(empty_contract)\n{\n\tchar const* sourceCode = \"contract test {\\n\"\n\t\"}\\n\";\n\tchar const* interface = \"[]\";\n\n\tcheckInterface(sourceCode, interface);\n}\n\nBOOST_AUTO_TEST_CASE(multiple_methods)\n{\n\tchar const* sourceCode = \"contract test {\\n\"\n\t\" function f(uint a) returns(uint d) { return a * 7; }\\n\"\n\t\" function g(uint b) returns(uint e) { return b * 8; }\\n\"\n\t\"}\\n\";\n\n\tchar const* interface = R\"([\n\t{\n\t\t\"name\": \"f\",\n\t\t\"constant\": false,\n\t\t\"type\": \"function\",\n\t\t\"inputs\": [\n\t\t{\n\t\t\t\"name\": \"a\",\n\t\t\t\"type\": \"uint256\"\n\t\t}\n\t\t],\n\t\t\"outputs\": [\n\t\t{\n\t\t\t\"name\": \"d\",\n\t\t\t\"type\": \"uint256\"\n\t\t}\n\t\t]\n\t},\n\t{\n\t\t\"name\": \"g\",\n\t\t\"constant\": false,\n\t\t\"type\": \"function\",\n\t\t\"inputs\": [\n\t\t{\n\t\t\t\"name\": \"b\",\n\t\t\t\"type\": \"uint256\"\n\t\t}\n\t\t],\n\t\t\"outputs\": [\n\t\t{\n\t\t\t\"name\": \"e\",\n\t\t\t\"type\": \"uint256\"\n\t\t}\n\t\t]\n\t}\n\t])\";\n\n\tcheckInterface(sourceCode, interface);\n}\n\nBOOST_AUTO_TEST_CASE(multiple_params)\n{\n\tchar const* sourceCode = \"contract test {\\n\"\n\t\" function f(uint a, uint b) returns(uint d) { return a + b; }\\n\"\n\t\"}\\n\";\n\n\tchar const* interface = R\"([\n\t{\n\t\t\"name\": \"f\",\n\t\t\"constant\": false,\n\t\t\"type\": \"function\",\n\t\t\"inputs\": [\n\t\t{\n\t\t\t\"name\": \"a\",\n\t\t\t\"type\": \"uint256\"\n\t\t},\n\t\t{\n\t\t\t\"name\": \"b\",\n\t\t\t\"type\": \"uint256\"\n\t\t}\n\t\t],\n\t\t\"outputs\": [\n\t\t{\n\t\t\t\"name\": \"d\",\n\t\t\t\"type\": \"uint256\"\n\t\t}\n\t\t]\n\t}\n\t])\";\n\n\tcheckInterface(sourceCode, interface);\n}\n\nBOOST_AUTO_TEST_CASE(multiple_methods_order)\n{\n\t\/\/ methods are expected to be in alpabetical order\n\tchar const* sourceCode = \"contract test {\\n\"\n\t\" function f(uint a) returns(uint d) { return a * 7; }\\n\"\n\t\" function c(uint b) returns(uint e) { return b * 8; }\\n\"\n\t\"}\\n\";\n\n\tchar const* interface = R\"([\n\t{\n\t\t\"name\": \"c\",\n\t\t\"constant\": false,\n\t\t\"type\": \"function\",\n\t\t\"inputs\": [\n\t\t{\n\t\t\t\"name\": \"b\",\n\t\t\t\"type\": \"uint256\"\n\t\t}\n\t\t],\n\t\t\"outputs\": [\n\t\t{\n\t\t\t\"name\": \"e\",\n\t\t\t\"type\": \"uint256\"\n\t\t}\n\t\t]\n\t},\n\t{\n\t\t\"name\": \"f\",\n\t\t\"constant\": false,\n\t\t\"type\": \"function\",\n\t\t\"inputs\": [\n\t\t{\n\t\t\t\"name\": \"a\",\n\t\t\t\"type\": \"uint256\"\n\t\t}\n\t\t],\n\t\t\"outputs\": [\n\t\t{\n\t\t\t\"name\": \"d\",\n\t\t\t\"type\": \"uint256\"\n\t\t}\n\t\t]\n\t}\n\t])\";\n\n\tcheckInterface(sourceCode, interface);\n}\n\nBOOST_AUTO_TEST_CASE(const_function)\n{\n\tchar const* sourceCode = \"contract test {\\n\"\n\t\" function foo(uint a, uint b) returns(uint d) { return a + b; }\\n\"\n\t\" function boo(uint32 a) constant returns(uint b) { return a * 4; }\\n\"\n\t\"}\\n\";\n\n\tchar const* interface = R\"([\n\t{\n\t\t\"name\": \"foo\",\n\t\t\"constant\": false,\n\t\t\"type\": \"function\",\n\t\t\"inputs\": [\n\t\t{\n\t\t\t\"name\": \"a\",\n\t\t\t\"type\": \"uint256\"\n\t\t},\n\t\t{\n\t\t\t\"name\": \"b\",\n\t\t\t\"type\": \"uint256\"\n\t\t}\n\t\t],\n\t\t\"outputs\": [\n\t\t{\n\t\t\t\"name\": \"d\",\n\t\t\t\"type\": \"uint256\"\n\t\t}\n\t\t]\n\t},\n\t{\n\t\t\"name\": \"boo\",\n\t\t\"constant\": true,\n\t\t\"type\": \"function\",\n\t\t\"inputs\": [{\n\t\t\t\"name\": \"a\",\n\t\t\t\"type\": \"uint32\"\n\t\t}],\n\t\t\"outputs\": [\n\t\t{\n\t\t\t\"name\": \"b\",\n\t\t\t\"type\": \"uint256\"\n\t\t}\n\t\t]\n\t}\n\t])\";\n\n\tcheckInterface(sourceCode, interface);\n}\n\nBOOST_AUTO_TEST_CASE(exclude_fallback_function)\n{\n\tchar const* sourceCode = \"contract test { function() {} }\";\n\n\tchar const* interface = \"[]\";\n\n\tcheckInterface(sourceCode, interface);\n}\n\nBOOST_AUTO_TEST_CASE(events)\n{\n\tchar const* sourceCode = \"contract test {\\n\"\n\t\" function f(uint a) returns(uint d) { return a * 7; }\\n\"\n\t\" event e1(uint b, address indexed c); \\n\"\n\t\" event e2(); \\n\"\n\t\"}\\n\";\n\tchar const* interface = R\"([\n\t{\n\t\t\"name\": \"f\",\n\t\t\"constant\": false,\n\t\t\"type\": \"function\",\n\t\t\"inputs\": [\n\t\t{\n\t\t\t\"name\": \"a\",\n\t\t\t\"type\": \"uint256\"\n\t\t}\n\t\t],\n\t\t\"outputs\": [\n\t\t{\n\t\t\t\"name\": \"d\",\n\t\t\t\"type\": \"uint256\"\n\t\t}\n\t\t]\n\t},\n\t{\n\t\t\"name\": \"e1\",\n\t\t\"type\": \"event\",\n\t\t\"anonymous\": false,\n\t\t\"inputs\": [\n\t\t{\n\t\t\t\"indexed\": false,\n\t\t\t\"name\": \"b\",\n\t\t\t\"type\": \"uint256\"\n\t\t},\n\t\t{\n\t\t\t\"indexed\": true,\n\t\t\t\"name\": \"c\",\n\t\t\t\"type\": \"address\"\n\t\t}\n\t\t]\n\t},\n\t{\n\t\t\"name\": \"e2\",\n\t\t\"type\": \"event\",\n\t\t\"anonymous\": false,\n\t\t\"inputs\": []\n\t}\n\n\t])\";\n\n\tcheckInterface(sourceCode, interface);\n}\n\nBOOST_AUTO_TEST_CASE(events_anonymous)\n{\n\tchar const* sourceCode = \"contract test {\\n\"\n\t\" event e() anonymous; \\n\"\n\t\"}\\n\";\n\tchar const* interface = R\"([\n\t{\n\t\t\"name\": \"e\",\n\t\t\"type\": \"event\",\n\t\t\"anonymous\": true,\n\t\t\"inputs\": []\n\t}\n\n\t])\";\n\n\tcheckInterface(sourceCode, interface);\n}\n\nBOOST_AUTO_TEST_CASE(inherited)\n{\n\tchar const* sourceCode =\n\t\"\tcontract Base { \\n\"\n\t\"\t\tfunction baseFunction(uint p) returns (uint i) { return p; } \\n\"\n\t\"\t\tevent baseEvent(bytes32 indexed evtArgBase); \\n\"\n\t\"\t} \\n\"\n\t\"\tcontract Derived is Base { \\n\"\n\t\"\t\tfunction derivedFunction(bytes32 p) returns (bytes32 i) { return p; } \\n\"\n\t\"\t\tevent derivedEvent(uint indexed evtArgDerived); \\n\"\n\t\"\t}\";\n\n\tchar const* interface = R\"([\n\t{\n\t\t\"name\": \"baseFunction\",\n\t\t\"constant\": false,\n\t\t\"type\": \"function\",\n\t\t\"inputs\":\n\t\t[{\n\t\t\t\"name\": \"p\",\n\t\t\t\"type\": \"uint256\"\n\t\t}],\n\t\t\"outputs\":\n\t\t[{\n\t\t\t\"name\": \"i\",\n\t\t\t\"type\": \"uint256\"\n\t\t}]\n\t},\n\t{\n\t\t\"name\": \"derivedFunction\",\n\t\t\"constant\": false,\n\t\t\"type\": \"function\",\n\t\t\"inputs\":\n\t\t[{\n\t\t\t\"name\": \"p\",\n\t\t\t\"type\": \"bytes32\"\n\t\t}],\n\t\t\"outputs\":\n\t\t[{\n\t\t\t\"name\": \"i\",\n\t\t\t\"type\": \"bytes32\"\n\t\t}]\n\t},\n\t{\n\t\t\"name\": \"derivedEvent\",\n\t\t\"type\": \"event\",\n\t\t\"anonymous\": false,\n\t\t\"inputs\":\n\t\t[{\n\t\t\t\"indexed\": true,\n\t\t\t\"name\": \"evtArgDerived\",\n\t\t\t\"type\": \"uint256\"\n\t\t}]\n\t},\n\t{\n\t\t\"name\": \"baseEvent\",\n\t\t\"type\": \"event\",\n\t\t\"anonymous\": false,\n\t\t\"inputs\":\n\t\t[{\n\t\t\t\"indexed\": true,\n\t\t\t\"name\": \"evtArgBase\",\n\t\t\t\"type\": \"bytes32\"\n\t\t}]\n\t}])\";\n\n\n\tcheckInterface(sourceCode, interface);\n}\nBOOST_AUTO_TEST_CASE(empty_name_input_parameter_with_named_one)\n{\n\tchar const* sourceCode = R\"(\n\tcontract test {\n\t\tfunction f(uint, uint k) returns(uint ret_k, uint ret_g){\n\t\t\tuint g = 8;\n\t\t\tret_k = k;\n\t\t\tret_g = g;\n\t\t}\n\t})\";\n\n\tchar const* interface = R\"([\n\t{\n\t\t\"name\": \"f\",\n\t\t\"constant\": false,\n\t\t\"type\": \"function\",\n\t\t\"inputs\": [\n\t\t{\n\t\t\t\"name\": \"\",\n\t\t\t\"type\": \"uint256\"\n\t\t},\n\t\t{\n\t\t\t\"name\": \"k\",\n\t\t\t\"type\": \"uint256\"\n\t\t}\n\t\t],\n\t\t\"outputs\": [\n\t\t{\n\t\t\t\"name\": \"ret_k\",\n\t\t\t\"type\": \"uint256\"\n\t\t},\n\t\t{\n\t\t\t\"name\": \"ret_g\",\n\t\t\t\"type\": \"uint256\"\n\t\t}\n\t\t]\n\t}\n\t])\";\n\n\tcheckInterface(sourceCode, interface);\n}\n\nBOOST_AUTO_TEST_CASE(empty_name_return_parameter)\n{\n\tchar const* sourceCode = R\"(\n\t\tcontract test {\n\t\tfunction f(uint k) returns(uint){\n\t\t\treturn k;\n\t\t}\n\t})\";\n\n\tchar const* interface = R\"([\n\t{\n\t\t\"name\": \"f\",\n\t\t\"constant\": false,\n\t\t\"type\": \"function\",\n\t\t\"inputs\": [\n\t\t{\n\t\t\t\"name\": \"k\",\n\t\t\t\"type\": \"uint256\"\n\t\t}\n\t\t],\n\t\t\"outputs\": [\n\t\t{\n\t\t\t\"name\": \"\",\n\t\t\t\"type\": \"uint256\"\n\t\t}\n\t\t]\n\t}\n\t])\";\n\tcheckInterface(sourceCode, interface);\n}\n\nBOOST_AUTO_TEST_CASE(constructor_abi)\n{\n\tchar const* sourceCode = R\"(\n\t\tcontract test {\n\t\tfunction test() {\n\t\t}\n\t})\";\n\n\tchar const* interface = R\"(\"\n\t[\n\t\t{\n\t\t \"constant\" : false,\n\t\t \"inputs\" : [],\n\t\t \"name\" : \"test\",\n\t\t \"outputs\" : [],\n\t\t \"type\" : \"constructor\"\n\t\t}\n\t])\";\n\tcheckInterface(sourceCode, interface);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n\n}\n}\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n* specguiorder.cpp\n* StatusSpec project\n*\n* Copyright (c) 2014 thesupremecommander\n* BSD 2-Clause License\n* http:\/\/opensource.org\/licenses\/BSD-2-Clause\n*\n*\/\n\n#include \"specguiorder.h\"\n\nSpecGUIOrder::SpecGUIOrder() {\n\tenabled = new ConVar(\"statusspec_specguiorder_enabled\", \"0\", FCVAR_NONE, \"enable ordering of spec GUI\");\n\treverse_blu = new ConVar(\"statusspec_specguiorder_reverse_blu\", \"0\", FCVAR_NONE, \"reverse order for BLU players\");\n\treverse_red = new ConVar(\"statusspec_specguiorder_reverse_red\", \"0\", FCVAR_NONE, \"reverse order for RED players\");\n\n\tspecguiSettings = new KeyValues(\"Resource\/UI\/SpectatorTournament.res\");\n\tspecguiSettings->LoadFromFile(Interfaces::pFileSystem, \"resource\/ui\/spectatortournament.res\", \"mod\");\n}\n\nbool SpecGUIOrder::IsEnabled() {\n\treturn enabled->GetBool();\n}\n\nvoid SpecGUIOrder::InterceptMessage(vgui::VPANEL vguiPanel, KeyValues *params, vgui::VPANEL ifromPanel) {\n\tstd::string originPanelName = g_pVGuiPanel->GetName(ifromPanel);\n\n\tif (originPanelName.substr(0, 11).compare(\"playerpanel\") == 0 && strcmp(params->GetName(), \"DialogVariables\") == 0) {\n\t\tconst char *playerName = params->GetString(\"playername\", NULL);\n\n\t\tif (playerName) {\n\t\t\tfor (int i = 0; i <= MAX_PLAYERS; i++) {\n\t\t\t\tPlayer player = i;\n\n\t\t\t\tif (!player) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tif (strcmp(playerName, player.GetName()) == 0) {\n\t\t\t\t\tplayerPanels[originPanelName] = player;\n\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\nbool SpecGUIOrder::SetPosOverride(vgui::VPANEL vguiPanel, int &x, int &y) {\n\tstd::string panelName = g_pVGuiPanel->GetName(vguiPanel);\n\n\tif (panelName.substr(0, 11).compare(\"playerpanel\") == 0) {\n\t\tPlayer player = playerPanels[panelName];\n\n\t\tif (!player) {\n\t\t\treturn false;\n\t\t}\n\n\t\tTFTeam team = player.GetTeam();\n\n\t\tif (team == TFTeam_Red) {\n\t\t\tint position;\n\t\t\t\n\t\t\tif (!reverse_red->GetBool()) {\n\t\t\t\tposition = std::distance(redPlayers.begin(), std::find(redPlayers.begin(), redPlayers.end(), player));\n\t\t\t}\n\t\t\telse {\n\t\t\t\tposition = std::distance(redPlayers.rbegin(), std::find(redPlayers.rbegin(), redPlayers.rend(), player));\n\t\t\t}\n\n\t\t\tint baseX = specguiSettings->FindKey(\"specgui\")->GetInt(\"team2_player_base_offset_x\");\n\t\t\tint baseY = specguiSettings->FindKey(\"specgui\")->GetInt(\"team2_player_base_y\");\n\t\t\tint deltaX = specguiSettings->FindKey(\"specgui\")->GetInt(\"team2_player_delta_x\");\n\t\t\tint deltaY = specguiSettings->FindKey(\"specgui\")->GetInt(\"team2_player_delta_y\");\n\n\t\t\tx = g_pVGuiSchemeManager->GetProportionalScaledValue(baseX + (position * deltaX));\n\t\t\ty = g_pVGuiSchemeManager->GetProportionalScaledValue(baseY + (position * deltaY));\n\n\t\t\treturn true;\n\t\t}\n\t\telse if (team == TFTeam_Blue) {\n\t\t\tint position;\n\n\t\t\tif (!reverse_red->GetBool()) {\n\t\t\t\tposition = std::distance(bluPlayers.begin(), std::find(bluPlayers.begin(), bluPlayers.end(), player));\n\t\t\t}\n\t\t\telse {\n\t\t\t\tposition = std::distance(bluPlayers.rbegin(), std::find(bluPlayers.rbegin(), bluPlayers.rend(), player));\n\t\t\t}\n\n\t\t\tint baseX = specguiSettings->FindKey(\"specgui\")->GetInt(\"team1_player_base_offset_x\");\n\t\t\tint baseY = specguiSettings->FindKey(\"specgui\")->GetInt(\"team1_player_base_y\");\n\t\t\tint deltaX = specguiSettings->FindKey(\"specgui\")->GetInt(\"team1_player_delta_x\");\n\t\t\tint deltaY = specguiSettings->FindKey(\"specgui\")->GetInt(\"team1_player_delta_y\");\n\n\t\t\tx = g_pVGuiSchemeManager->GetProportionalScaledValue(baseX + (position * deltaX));\n\t\t\ty = g_pVGuiSchemeManager->GetProportionalScaledValue(baseY + (position * deltaY));\n\n\t\t\treturn true;\n\t\t}\n\t}\n\n\treturn false;\n}\n\nvoid SpecGUIOrder::PreEntityUpdate() {\n\tbluPlayers.clear();\n\tredPlayers.clear();\n}\n\nvoid SpecGUIOrder::ProcessEntity(IClientEntity *entity) {\n\tPlayer player = entity;\n\n\tif (!player) {\n\t\treturn;\n\t}\n\n\tTFTeam team = player.GetTeam();\n\n\tif (team == TFTeam_Red) {\n\t\tredPlayers.push_back(player);\n\t}\n\telse if (team == TFTeam_Blue) {\n\t\tbluPlayers.push_back(player);\n\t}\n}\n\nvoid SpecGUIOrder::PostEntityUpdate() {\n\tbluPlayers.sort();\n\tredPlayers.sort();\n}<commit_msg>Fix wrong variable for BLU players.<commit_after>\/*\n* specguiorder.cpp\n* StatusSpec project\n*\n* Copyright (c) 2014 thesupremecommander\n* BSD 2-Clause License\n* http:\/\/opensource.org\/licenses\/BSD-2-Clause\n*\n*\/\n\n#include \"specguiorder.h\"\n\nSpecGUIOrder::SpecGUIOrder() {\n\tenabled = new ConVar(\"statusspec_specguiorder_enabled\", \"0\", FCVAR_NONE, \"enable ordering of spec GUI\");\n\treverse_blu = new ConVar(\"statusspec_specguiorder_reverse_blu\", \"0\", FCVAR_NONE, \"reverse order for BLU players\");\n\treverse_red = new ConVar(\"statusspec_specguiorder_reverse_red\", \"0\", FCVAR_NONE, \"reverse order for RED players\");\n\n\tspecguiSettings = new KeyValues(\"Resource\/UI\/SpectatorTournament.res\");\n\tspecguiSettings->LoadFromFile(Interfaces::pFileSystem, \"resource\/ui\/spectatortournament.res\", \"mod\");\n}\n\nbool SpecGUIOrder::IsEnabled() {\n\treturn enabled->GetBool();\n}\n\nvoid SpecGUIOrder::InterceptMessage(vgui::VPANEL vguiPanel, KeyValues *params, vgui::VPANEL ifromPanel) {\n\tstd::string originPanelName = g_pVGuiPanel->GetName(ifromPanel);\n\n\tif (originPanelName.substr(0, 11).compare(\"playerpanel\") == 0 && strcmp(params->GetName(), \"DialogVariables\") == 0) {\n\t\tconst char *playerName = params->GetString(\"playername\", NULL);\n\n\t\tif (playerName) {\n\t\t\tfor (int i = 0; i <= MAX_PLAYERS; i++) {\n\t\t\t\tPlayer player = i;\n\n\t\t\t\tif (!player) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tif (strcmp(playerName, player.GetName()) == 0) {\n\t\t\t\t\tplayerPanels[originPanelName] = player;\n\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\nbool SpecGUIOrder::SetPosOverride(vgui::VPANEL vguiPanel, int &x, int &y) {\n\tstd::string panelName = g_pVGuiPanel->GetName(vguiPanel);\n\n\tif (panelName.substr(0, 11).compare(\"playerpanel\") == 0) {\n\t\tPlayer player = playerPanels[panelName];\n\n\t\tif (!player) {\n\t\t\treturn false;\n\t\t}\n\n\t\tTFTeam team = player.GetTeam();\n\n\t\tif (team == TFTeam_Red) {\n\t\t\tint position;\n\t\t\t\n\t\t\tif (!reverse_red->GetBool()) {\n\t\t\t\tposition = std::distance(redPlayers.begin(), std::find(redPlayers.begin(), redPlayers.end(), player));\n\t\t\t}\n\t\t\telse {\n\t\t\t\tposition = std::distance(redPlayers.rbegin(), std::find(redPlayers.rbegin(), redPlayers.rend(), player));\n\t\t\t}\n\n\t\t\tint baseX = specguiSettings->FindKey(\"specgui\")->GetInt(\"team2_player_base_offset_x\");\n\t\t\tint baseY = specguiSettings->FindKey(\"specgui\")->GetInt(\"team2_player_base_y\");\n\t\t\tint deltaX = specguiSettings->FindKey(\"specgui\")->GetInt(\"team2_player_delta_x\");\n\t\t\tint deltaY = specguiSettings->FindKey(\"specgui\")->GetInt(\"team2_player_delta_y\");\n\n\t\t\tx = g_pVGuiSchemeManager->GetProportionalScaledValue(baseX + (position * deltaX));\n\t\t\ty = g_pVGuiSchemeManager->GetProportionalScaledValue(baseY + (position * deltaY));\n\n\t\t\treturn true;\n\t\t}\n\t\telse if (team == TFTeam_Blue) {\n\t\t\tint position;\n\n\t\t\tif (!reverse_blu->GetBool()) {\n\t\t\t\tposition = std::distance(bluPlayers.begin(), std::find(bluPlayers.begin(), bluPlayers.end(), player));\n\t\t\t}\n\t\t\telse {\n\t\t\t\tposition = std::distance(bluPlayers.rbegin(), std::find(bluPlayers.rbegin(), bluPlayers.rend(), player));\n\t\t\t}\n\n\t\t\tint baseX = specguiSettings->FindKey(\"specgui\")->GetInt(\"team1_player_base_offset_x\");\n\t\t\tint baseY = specguiSettings->FindKey(\"specgui\")->GetInt(\"team1_player_base_y\");\n\t\t\tint deltaX = specguiSettings->FindKey(\"specgui\")->GetInt(\"team1_player_delta_x\");\n\t\t\tint deltaY = specguiSettings->FindKey(\"specgui\")->GetInt(\"team1_player_delta_y\");\n\n\t\t\tx = g_pVGuiSchemeManager->GetProportionalScaledValue(baseX + (position * deltaX));\n\t\t\ty = g_pVGuiSchemeManager->GetProportionalScaledValue(baseY + (position * deltaY));\n\n\t\t\treturn true;\n\t\t}\n\t}\n\n\treturn false;\n}\n\nvoid SpecGUIOrder::PreEntityUpdate() {\n\tbluPlayers.clear();\n\tredPlayers.clear();\n}\n\nvoid SpecGUIOrder::ProcessEntity(IClientEntity *entity) {\n\tPlayer player = entity;\n\n\tif (!player) {\n\t\treturn;\n\t}\n\n\tTFTeam team = player.GetTeam();\n\n\tif (team == TFTeam_Red) {\n\t\tredPlayers.push_back(player);\n\t}\n\telse if (team == TFTeam_Blue) {\n\t\tbluPlayers.push_back(player);\n\t}\n}\n\nvoid SpecGUIOrder::PostEntityUpdate() {\n\tbluPlayers.sort();\n\tredPlayers.sort();\n}<|endoftext|>"} {"text":"<commit_before>#include \"testshelpers.h\"\r\n#include <QThread>\r\n#include <QCoreApplication>\r\n\r\nvoid sleepWait(int seconds, const std::function<bool ()> &condition) {\r\n int times = 0;\r\n while (times < seconds) {\r\n if (!condition()) {\r\n QCoreApplication::processEvents(QEventLoop::AllEvents);\r\n QThread::sleep(1);\r\n }\r\n\r\n times++;\r\n }\r\n}\r\n<commit_msg>Fix for sleepwait helper<commit_after>#include \"testshelpers.h\"\r\n#include <QThread>\r\n#include <QCoreApplication>\r\n#include <QDebug>\r\n\r\nvoid sleepWait(int seconds, const std::function<bool ()> &condition) {\r\n int times = 0;\r\n bool becameTrue = false;\r\n\r\n while (times < seconds) {\r\n if (!condition()) {\r\n QCoreApplication::processEvents(QEventLoop::AllEvents);\r\n QThread::sleep(1);\r\n times++;\r\n } else {\r\n qDebug() << \"Condition became true in\" << times << \"try out of\" << seconds;\r\n becameTrue = true;\r\n break;\r\n }\r\n }\r\n\r\n if (!becameTrue) {\r\n qDebug() << \"Condition never was true\";\r\n }\r\n}\r\n<|endoftext|>"} {"text":"<commit_before>#include \"ResultDialog.h\"\n#include \"ui_ResultDialog.h\"\n#include \"StAssert.h\"\n#include \"LanguageHelper.h\"\n\n#include <QDesktopWidget>\n#include <QMouseEvent>\n#include <QMenu>\n\nResultDialog::ResultDialog (const LanguageHelper &dictionary, QWidget *parent) :\n QDialog (parent),\n ui (new Ui::ResultDialog),\n dictionary_ (dictionary), isShowAtCapturePos_ (true),\n contextMenu_ (NULL), recognizeSubMenu_ (NULL), clipboardAction_ (NULL) {\n ui->setupUi (this);\n setWindowFlags (Qt::FramelessWindowHint | Qt::NoDropShadowWindowHint |\n Qt::WindowStaysOnTopHint | Qt::X11BypassWindowManagerHint);\n\n installEventFilter (this);\n createContextMenu ();\n applySettings ();\n}\n\nResultDialog::~ResultDialog () {\n delete contextMenu_;\n delete ui;\n}\n\nconst ProcessingItem &ResultDialog::item () const {\n return item_;\n}\n\nvoid ResultDialog::applySettings () {\n dictionary_.updateMenu (recognizeSubMenu_, dictionary_.availableOcrLanguagesUi ());\n}\n\nvoid ResultDialog::createContextMenu () {\n contextMenu_ = new QMenu ();\n recognizeSubMenu_ = contextMenu_->addMenu (tr (\"Распознать другой язык\"));\n clipboardAction_ = contextMenu_->addAction (tr (\"Скопировать в буфер\"));\n}\n\nbool ResultDialog::eventFilter (QObject *object, QEvent *event) {\n Q_UNUSED (object);\n if (event->type () == QEvent::MouseButtonPress) {\n Qt::MouseButton button = static_cast<QMouseEvent *>(event)->button ();\n if (button == Qt::RightButton) {\n QAction *action = contextMenu_->exec (QCursor::pos ());\n QWidget *subMenu = action->parentWidget ();\n if (recognizeSubMenu_->isAncestorOf (subMenu)) {\n ProcessingItem item = item_;\n item.translated = item.recognized = QString ();\n item.ocrLanguage = dictionary_.ocrUiToCode (action->text ());\n emit requestRecognize (item);\n }\n else if (action == clipboardAction_) {\n emit requestClipboard ();\n }\n }\n hide ();\n }\n else if (event->type () == QEvent::WindowDeactivate) {\n hide ();\n }\n return QDialog::eventFilter (object, event);\n}\n\nvoid ResultDialog::showResult (ProcessingItem item) {\n ST_ASSERT (item.isValid ());\n item_ = item;\n ui->sourceLabel->setPixmap (item.source);\n ui->recognizeLabel->setText (item.recognized);\n ui->translateLabel->setText (item.translated);\n bool gotTranslation = !item.translated.isEmpty ();\n ui->translateLabel->setVisible (gotTranslation);\n ui->translateLine->setVisible (gotTranslation);\n\n show ();\n adjustSize ();\n\n QDesktopWidget *desktop = QApplication::desktop ();\n Q_CHECK_PTR (desktop);\n if (isShowAtCapturePos_) {\n QPoint correction = QPoint (ui->frame->lineWidth (), ui->frame->lineWidth ());\n move (item.screenPos - correction);\n QRect screenRect = desktop->screenGeometry (this);\n int minY = screenRect.bottom () - height ();\n if (y () > minY) {\n move (x (), minY);\n }\n }\n else {\n\n QRect screenRect = desktop->availableGeometry (this);\n ST_ASSERT (screenRect.isValid ());\n QPoint newPos (screenRect.width () - width (), screenRect.height () - height ());\n move (newPos);\n }\n activateWindow ();\n}\n<commit_msg>More correct submenu detection.<commit_after>#include \"ResultDialog.h\"\n#include \"ui_ResultDialog.h\"\n#include \"StAssert.h\"\n#include \"LanguageHelper.h\"\n\n#include <QDesktopWidget>\n#include <QMouseEvent>\n#include <QMenu>\n\nResultDialog::ResultDialog (const LanguageHelper &dictionary, QWidget *parent) :\n QDialog (parent),\n ui (new Ui::ResultDialog),\n dictionary_ (dictionary), isShowAtCapturePos_ (true),\n contextMenu_ (NULL), recognizeSubMenu_ (NULL), clipboardAction_ (NULL) {\n ui->setupUi (this);\n setWindowFlags (Qt::FramelessWindowHint | Qt::NoDropShadowWindowHint |\n Qt::WindowStaysOnTopHint | Qt::X11BypassWindowManagerHint);\n\n installEventFilter (this);\n createContextMenu ();\n applySettings ();\n}\n\nResultDialog::~ResultDialog () {\n delete contextMenu_;\n delete ui;\n}\n\nconst ProcessingItem &ResultDialog::item () const {\n return item_;\n}\n\nvoid ResultDialog::applySettings () {\n dictionary_.updateMenu (recognizeSubMenu_, dictionary_.availableOcrLanguagesUi ());\n}\n\nvoid ResultDialog::createContextMenu () {\n contextMenu_ = new QMenu ();\n recognizeSubMenu_ = contextMenu_->addMenu (tr (\"Распознать другой язык\"));\n clipboardAction_ = contextMenu_->addAction (tr (\"Скопировать в буфер\"));\n}\n\nbool ResultDialog::eventFilter (QObject *object, QEvent *event) {\n Q_UNUSED (object);\n if (event->type () == QEvent::MouseButtonPress) {\n Qt::MouseButton button = static_cast<QMouseEvent *>(event)->button ();\n if (button == Qt::RightButton) {\n QAction *action = contextMenu_->exec (QCursor::pos ());\n if (recognizeSubMenu_->findChildren<QAction *> ().contains (action)) {\n ProcessingItem item = item_;\n item.translated = item.recognized = QString ();\n item.ocrLanguage = dictionary_.ocrUiToCode (action->text ());\n emit requestRecognize (item);\n }\n else if (action == clipboardAction_) {\n emit requestClipboard ();\n }\n }\n hide ();\n }\n else if (event->type () == QEvent::WindowDeactivate) {\n hide ();\n }\n return QDialog::eventFilter (object, event);\n}\n\nvoid ResultDialog::showResult (ProcessingItem item) {\n ST_ASSERT (item.isValid ());\n item_ = item;\n ui->sourceLabel->setPixmap (item.source);\n ui->recognizeLabel->setText (item.recognized);\n ui->translateLabel->setText (item.translated);\n bool gotTranslation = !item.translated.isEmpty ();\n ui->translateLabel->setVisible (gotTranslation);\n ui->translateLine->setVisible (gotTranslation);\n\n show ();\n adjustSize ();\n\n QDesktopWidget *desktop = QApplication::desktop ();\n Q_CHECK_PTR (desktop);\n if (isShowAtCapturePos_) {\n QPoint correction = QPoint (ui->frame->lineWidth (), ui->frame->lineWidth ());\n move (item.screenPos - correction);\n QRect screenRect = desktop->screenGeometry (this);\n int minY = screenRect.bottom () - height ();\n if (y () > minY) {\n move (x (), minY);\n }\n }\n else {\n\n QRect screenRect = desktop->availableGeometry (this);\n ST_ASSERT (screenRect.isValid ());\n QPoint newPos (screenRect.width () - width (), screenRect.height () - height ());\n move (newPos);\n }\n activateWindow ();\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"mainwindow.h\"\n#include \"ui_mainwindow.h\"\n#include <QMessageBox>\n#include <iostream>\n#include <QCloseEvent>\n#include <QColorDialog>\n#include <chrono>\n#include <thread>\n#include \"icononbuttonhandler.h\"\n#include \"inputwindow.h\"\n#include \"Video\/shapes\/shape.h\"\n\nusing namespace std;\nusing namespace cv;\n\n\/**\n * @brief MainWindow::MainWindow\n * Constructor\n * @param parent a QWidget variable\n *\/\nMainWindow::MainWindow(QWidget *parent) :\n QMainWindow(parent),\n ui(new Ui::MainWindow){\n ui->setupUi(this);\n video_slider = findChild<QSlider*>(\"videoSlider\");\n iconOnButtonHandler = new IconOnButtonHandler();\n iconOnButtonHandler->set_pictures_to_buttons(ui);\n\n fileHandler = new FileHandler();\n set_shortcuts();\n\n \/\/ Add this object as a listener to videoFrame.\n ui->videoFrame->installEventFilter(this);\n\n mvideo_player = new video_player();\n QObject::connect(mvideo_player, SIGNAL(processedImage(QImage)),\n this, SLOT(update_video(QImage)));\n QObject::connect(mvideo_player, SIGNAL(currentFrame(int)),\n this, SLOT(set_video_slider_pos(int)));\n\n \/\/Used for rescaling the source image for video playback\n mvideo_player->set_frame_height(ui->videoFrame->height());\n mvideo_player->set_frame_width(ui->videoFrame->width());\n}\n\n\/**\n * @brief MainWindow::~MainWindow\n * Destructor\n *\/\n\nMainWindow::~MainWindow() {\n\n delete iconOnButtonHandler;\n delete fileHandler;\n delete mvideo_player;\n delete ui;\n}\n\n\/**\n * @brief MainWindow::set_shortcuts\n * Function to set shortcuts on actions\n *\/\nvoid MainWindow::set_shortcuts(){\n ui->actionExit->setShortcut(tr(\"Ctrl+e\"));\n}\n\n\/**\n * @brief MainWindow::set_status_bar\n * @param status text to show in the statusbar\n * @param timer time to show it in the bar in ms, 750ms is standard\n *\/\nvoid MainWindow::set_status_bar(string status, int timer = 750){\n ui->statusBar->showMessage(QString::fromStdString(status), timer);\n}\n\n\/**\n * @brief MainWindow::on_fastBackwardButton_clicked\n * The button supposed to play the video slower\n *\n *\/\nvoid MainWindow::on_fastBackwardButton_clicked(){\n\n}\n\n\n\/**\n * @brief MainWindow::on_playPauseButton_clicked\n * The button supposed to play and pause the video\n *\/\nvoid MainWindow::on_playPauseButton_clicked() {\n if (mvideo_player->is_paused() || mvideo_player->is_stopped()) {\n set_status_bar(\"Playing\");\n iconOnButtonHandler->set_icon(\"pause\", ui->playPauseButton);\/\/changes the icon on the play button to a pause-icon\n mvideo_player->start();\n } else {\n set_status_bar(\"Paused\");\n iconOnButtonHandler->set_icon(\"play\", ui->playPauseButton);\n mvideo_player->play_pause();\n mvideo_player->wait();\n }\n}\n\n\n\/**\n * @brief MainWindow::on_fastForwardButton_clicked\n * The button supposed to play the video faster\n *\/\nvoid MainWindow::on_fastForwardButton_clicked(){\n\n}\n\n\/**\n * @brief MainWindow::on_stopButton_clicked\n * The button supposed to stop the video\n *\/\nvoid MainWindow::on_stopButton_clicked() {\n set_status_bar(\"Stopped\");\n if (!mvideo_player->is_paused()) {\n iconOnButtonHandler->set_icon(\"play\", ui->playPauseButton);\n }\n\n mvideo_player->stop_video();\n}\n\n\/**\n * @brief MainWindow::on_nextFrameButton_clicked\n * The button supposed to play the next frame of the video\n *\/\nvoid MainWindow::on_nextFrameButton_clicked() {\n if (mvideo_player->is_paused()) {\n set_status_bar(\"Went forward a frame\");\n mvideo_player->next_frame();\n } else {\n set_status_bar(\"Needs to be paused\");\n }\n}\n\n\/**\n * @brief MainWindow::on_previousFrameButton_clicked\n * The button supposed to play the previous frame of the video\n *\/\nvoid MainWindow::on_previousFrameButton_clicked() {\n if (mvideo_player->is_paused()) {\n set_status_bar(\"Went back a frame\");\n mvideo_player->previous_frame();\n } else {\n set_status_bar(\"Needs to be paused\");\n }\n}\n\n\/**\n * @brief MainWindow::update_video\n * Sets the videoFrame pixmap to the current frame from video\n * @param frame\n *\/\nvoid MainWindow::update_video(QImage frame) {\n ui->videoFrame->setPixmap(QPixmap::fromImage(frame));\n}\n\n\/**\n * @brief MainWindow::set_video_slider_pos\n * Sets the position of slider in video to position pos\n * @param pos\n *\/\nvoid MainWindow::set_video_slider_pos(int pos) {\n if (pos <= video_slider->maximum()) {\n video_slider->setSliderPosition(pos);\n }\n}\n\n\/**\n * @brief MainWindow::resizeEvent\n * Used for rescaling the source image for video playback\n * @param event\n *\/\nvoid MainWindow::resizeEvent(QResizeEvent* event) {\n QMainWindow::resizeEvent(event);\n mvideo_player->set_frame_height(ui->videoFrame->height());\n mvideo_player->set_frame_width(ui->videoFrame->width());\n}\n\n\/**\n * @brief MainWindow::on_videoSlider_valueChanged\n * Update the slider to where the mouse is\n * @param newPos current position of the slider\n *\/\nvoid MainWindow::on_videoSlider_valueChanged(int newPos){\n \/\/ Make slider to follow the mouse directly and not by pageStep steps\n Qt::MouseButtons btns = QApplication::mouseButtons();\n QPoint localMousePos = ui->videoSlider->mapFromGlobal(QCursor::pos());\n bool clickOnSlider = (btns & Qt::LeftButton) &&\n (localMousePos.x() >= 0 && localMousePos.y() >= 0 &&\n localMousePos.x() < ui->videoSlider->size().width() &&\n localMousePos.y() < ui->videoSlider->size().height());\n if (clickOnSlider)\n {\n \/\/ Attention! The following works only for Horizontal, Left-to-right sliders\n float posRatio = localMousePos.x() \/ (float )ui->videoSlider->size().width();\n int sliderRange = ui->videoSlider->maximum() - ui->videoSlider->minimum();\n int sliderPosUnderMouse = ui->videoSlider->minimum() + sliderRange * posRatio;\n if (sliderPosUnderMouse != newPos)\n {\n ui->videoSlider->setValue(sliderPosUnderMouse);\n return;\n }\n }\n}\n\/**\n * @brief MainWindow::closeEvent\n * asks if you are sure you want to quit.\n * @param event closing\n *\/\nvoid MainWindow::closeEvent (QCloseEvent *event){\n set_status_bar(\"Closing\");\n QMessageBox::StandardButton resBtn = QMessageBox::question( this, \"Exit\",\n tr(\"Are you sure you want to quit?\\n\"),\n QMessageBox::No | QMessageBox::Yes,\n QMessageBox::No);\n\n if (resBtn != QMessageBox::Yes) {\n event->ignore();\n } else {\n event->accept();\n }\n}\n\/**\n * @brief MainWindow::on_actionExit_triggered\n * sends a closeEvent when you press exit\n *\/\nvoid MainWindow::on_actionExit_triggered(){\n this->close();\n}\n\n\/**\n * @brief MainWindow::on_bookmarkButton_clicked\n * the button supposed to add a bookmark\n *\/\nvoid MainWindow::on_bookmarkButton_clicked(){\n \/\/ The code here is only temporary and should be moved\/removed\n \/\/ once a proper video selector is added\n\n mvideo_player->load_video(\"seq_01.mp4\");\n iconOnButtonHandler->set_icon(\"pause\", ui->playPauseButton);\n video_slider->setMaximum(mvideo_player->get_num_frames());\n mvideo_player->set_playback_frame(700);\n}\n\n\/**\n * @brief MainWindow::on_actionAddProject_triggered\n *\/\nvoid MainWindow::on_actionAddProject_triggered() {\n ACTION action = ADD_PROJECT;\n inputWindow = new inputwindow(this, action, \"Project name:\");\n inputWindow->show();\n set_status_bar(\"Adding project, need name\");\n}\n\n\/**\n * @brief MainWindow::inputSwitchCase\n * @param input the input from the user\n * @param action the action that was triggered earlier\n *\/\nvoid MainWindow::inputSwitchCase(ACTION action, QString qInput) {\n std::string input = qInput.toStdString();\n switch(action){\n case ADD_PROJECT: {\n fileHandler->create_project(input);\n QTreeWidgetItem *projectInTree = new QTreeWidgetItem();\n projectInTree->setText(0, qInput);\n ui->ProjectTree->addTopLevelItem(projectInTree);\n set_status_bar(\"Project \" + input + \"created.\");\n break;\n }\n case CANCEL: {\n set_status_bar(\"Cancel\");\n break;\n }\n default:\n break;\n\n }\n delete inputWindow;\n}\n\/**\n * @brief MainWindow::on_ProjectTree_itemClicked\n * @param item the item in the projectTree that was clicked\n * @param column the column in the tree\n *\/\nvoid MainWindow::on_ProjectTree_itemClicked(QTreeWidgetItem *item, int column) {\n}\n\n \/** @brief MainWindow::on_actionShow_hide_overview_triggered\n * Toggles the showing\/hiding of the overlay.\n * Invoked by menu item.\n *\/\nvoid MainWindow::on_actionShow_hide_overview_triggered() {\n mvideo_player->toggle_overlay();\n if (mvideo_player->is_showing_overlay()) {\n set_status_bar(\"Overlay: On.\");\n } else {\n set_status_bar(\"Overlay: Off.\");\n }\n}\n\n\/**\n * @brief MainWindow::on_actionColour_triggered\n * Selects a colour for the overlay drawing tool.\n *\/\nvoid MainWindow::on_actionColour_triggered() {\n QColor col = QColorDialog::getColor();\n mvideo_player->set_overlay_colour(col);\n set_status_bar(\"Color choosen.\");\n}\n\n\/**\n * @brief MainWindow::on_actionRectangle_triggered\n * Selects the rectangle shape for the overlay drawing tool.\n *\/\nvoid MainWindow::on_actionRectangle_triggered() {\n mvideo_player->set_overlay_tool(RECTANGLE);\n set_status_bar(\"Tool: rectangle.\");\n}\n\n\/**\n * @brief MainWindow::on_actionCircle_triggered\n * Selects the circle shape for the overlay drawing tool.\n *\/\nvoid MainWindow::on_actionCircle_triggered() {\n mvideo_player->set_overlay_tool(CIRCLE);\n set_status_bar(\"Tool: circle.\");\n}\n\n\/**\n * @brief MainWindow::on_actionLine_triggered\n * Selects the line shape for the overlay drawing tool.\n *\/\nvoid MainWindow::on_actionLine_triggered() {\n mvideo_player->set_overlay_tool(LINE);\n set_status_bar(\"Tool: line.\");\n}\n\n\/**\n * @brief MainWindow::on_actionArrow_triggered\n * Selects the arrow shape for the overlay drawing tool.\n *\/\nvoid MainWindow::on_actionArrow_triggered() {\n mvideo_player->set_overlay_tool(ARROW);\n set_status_bar(\"Tool: arrow.\");\n}\n\nvoid MainWindow::on_actionPen_triggered() {\n mvideo_player->set_overlay_tool(PEN);\n set_status_bar(\"Tool: pen.\");\n}\n\n\/**\n * @brief MainWindow::on_actionUndo_triggered\n * Undo the drawings on the overlay.\n *\/\nvoid MainWindow::on_actionUndo_triggered() {\n mvideo_player->undo_overlay();\n set_status_bar(\"Undo drawing.\");\n}\n\n\/**\n * @brief MainWindow::on_actionClear_triggered\n * Clear the drawings on the overlay.\n *\/\nvoid MainWindow::on_actionClear_triggered() {\n mvideo_player->clear_overlay();\n set_status_bar(\"Cleared drawings.\");\n}\n\n\/**\n * @brief MainWindow::eventFilter\n * Listener function for all eventFilters MainWindow has installed.\n * @param obj the object invoking the event\n * @param event the invooked event\n * @return\n *\/\nbool MainWindow::eventFilter(QObject *obj, QEvent *event) {\n \/\/ Check who invoked the event.\n if (qobject_cast<QLabel*>(obj)==ui->videoFrame) {\n \/\/ Cast to a mouse event to get the mouse position.\n QMouseEvent *mouseEvent = static_cast<QMouseEvent*>(event);\n QPoint pos = mouseEvent->pos();\n \/\/ Check what kind of event.\n if (event->type() == QEvent::MouseButtonPress) {\n mvideo_player->video_mouse_pressed(pos);\n } else if (event->type() == QEvent::MouseButtonRelease) {\n mvideo_player->video_mouse_released(pos);\n } else if (event->type() == QEvent::MouseMove) {\n mvideo_player->video_mouse_moved(pos);\n }\n }\n}\n<commit_msg>added comment for actionPen in mainwindow<commit_after>#include \"mainwindow.h\"\n#include \"ui_mainwindow.h\"\n#include <QMessageBox>\n#include <iostream>\n#include <QCloseEvent>\n#include <QColorDialog>\n#include <chrono>\n#include <thread>\n#include \"icononbuttonhandler.h\"\n#include \"inputwindow.h\"\n#include \"Video\/shapes\/shape.h\"\n\nusing namespace std;\nusing namespace cv;\n\n\/**\n * @brief MainWindow::MainWindow\n * Constructor\n * @param parent a QWidget variable\n *\/\nMainWindow::MainWindow(QWidget *parent) :\n QMainWindow(parent),\n ui(new Ui::MainWindow){\n ui->setupUi(this);\n video_slider = findChild<QSlider*>(\"videoSlider\");\n iconOnButtonHandler = new IconOnButtonHandler();\n iconOnButtonHandler->set_pictures_to_buttons(ui);\n\n fileHandler = new FileHandler();\n set_shortcuts();\n\n \/\/ Add this object as a listener to videoFrame.\n ui->videoFrame->installEventFilter(this);\n\n mvideo_player = new video_player();\n QObject::connect(mvideo_player, SIGNAL(processedImage(QImage)),\n this, SLOT(update_video(QImage)));\n QObject::connect(mvideo_player, SIGNAL(currentFrame(int)),\n this, SLOT(set_video_slider_pos(int)));\n\n \/\/Used for rescaling the source image for video playback\n mvideo_player->set_frame_height(ui->videoFrame->height());\n mvideo_player->set_frame_width(ui->videoFrame->width());\n}\n\n\/**\n * @brief MainWindow::~MainWindow\n * Destructor\n *\/\n\nMainWindow::~MainWindow() {\n\n delete iconOnButtonHandler;\n delete fileHandler;\n delete mvideo_player;\n delete ui;\n}\n\n\/**\n * @brief MainWindow::set_shortcuts\n * Function to set shortcuts on actions\n *\/\nvoid MainWindow::set_shortcuts(){\n ui->actionExit->setShortcut(tr(\"Ctrl+e\"));\n}\n\n\/**\n * @brief MainWindow::set_status_bar\n * @param status text to show in the statusbar\n * @param timer time to show it in the bar in ms, 750ms is standard\n *\/\nvoid MainWindow::set_status_bar(string status, int timer = 750){\n ui->statusBar->showMessage(QString::fromStdString(status), timer);\n}\n\n\/**\n * @brief MainWindow::on_fastBackwardButton_clicked\n * The button supposed to play the video slower\n *\n *\/\nvoid MainWindow::on_fastBackwardButton_clicked(){\n\n}\n\n\n\/**\n * @brief MainWindow::on_playPauseButton_clicked\n * The button supposed to play and pause the video\n *\/\nvoid MainWindow::on_playPauseButton_clicked() {\n if (mvideo_player->is_paused() || mvideo_player->is_stopped()) {\n set_status_bar(\"Playing\");\n iconOnButtonHandler->set_icon(\"pause\", ui->playPauseButton);\/\/changes the icon on the play button to a pause-icon\n mvideo_player->start();\n } else {\n set_status_bar(\"Paused\");\n iconOnButtonHandler->set_icon(\"play\", ui->playPauseButton);\n mvideo_player->play_pause();\n mvideo_player->wait();\n }\n}\n\n\n\/**\n * @brief MainWindow::on_fastForwardButton_clicked\n * The button supposed to play the video faster\n *\/\nvoid MainWindow::on_fastForwardButton_clicked(){\n\n}\n\n\/**\n * @brief MainWindow::on_stopButton_clicked\n * The button supposed to stop the video\n *\/\nvoid MainWindow::on_stopButton_clicked() {\n set_status_bar(\"Stopped\");\n if (!mvideo_player->is_paused()) {\n iconOnButtonHandler->set_icon(\"play\", ui->playPauseButton);\n }\n\n mvideo_player->stop_video();\n}\n\n\/**\n * @brief MainWindow::on_nextFrameButton_clicked\n * The button supposed to play the next frame of the video\n *\/\nvoid MainWindow::on_nextFrameButton_clicked() {\n if (mvideo_player->is_paused()) {\n set_status_bar(\"Went forward a frame\");\n mvideo_player->next_frame();\n } else {\n set_status_bar(\"Needs to be paused\");\n }\n}\n\n\/**\n * @brief MainWindow::on_previousFrameButton_clicked\n * The button supposed to play the previous frame of the video\n *\/\nvoid MainWindow::on_previousFrameButton_clicked() {\n if (mvideo_player->is_paused()) {\n set_status_bar(\"Went back a frame\");\n mvideo_player->previous_frame();\n } else {\n set_status_bar(\"Needs to be paused\");\n }\n}\n\n\/**\n * @brief MainWindow::update_video\n * Sets the videoFrame pixmap to the current frame from video\n * @param frame\n *\/\nvoid MainWindow::update_video(QImage frame) {\n ui->videoFrame->setPixmap(QPixmap::fromImage(frame));\n}\n\n\/**\n * @brief MainWindow::set_video_slider_pos\n * Sets the position of slider in video to position pos\n * @param pos\n *\/\nvoid MainWindow::set_video_slider_pos(int pos) {\n if (pos <= video_slider->maximum()) {\n video_slider->setSliderPosition(pos);\n }\n}\n\n\/**\n * @brief MainWindow::resizeEvent\n * Used for rescaling the source image for video playback\n * @param event\n *\/\nvoid MainWindow::resizeEvent(QResizeEvent* event) {\n QMainWindow::resizeEvent(event);\n mvideo_player->set_frame_height(ui->videoFrame->height());\n mvideo_player->set_frame_width(ui->videoFrame->width());\n}\n\n\/**\n * @brief MainWindow::on_videoSlider_valueChanged\n * Update the slider to where the mouse is\n * @param newPos current position of the slider\n *\/\nvoid MainWindow::on_videoSlider_valueChanged(int newPos){\n \/\/ Make slider to follow the mouse directly and not by pageStep steps\n Qt::MouseButtons btns = QApplication::mouseButtons();\n QPoint localMousePos = ui->videoSlider->mapFromGlobal(QCursor::pos());\n bool clickOnSlider = (btns & Qt::LeftButton) &&\n (localMousePos.x() >= 0 && localMousePos.y() >= 0 &&\n localMousePos.x() < ui->videoSlider->size().width() &&\n localMousePos.y() < ui->videoSlider->size().height());\n if (clickOnSlider)\n {\n \/\/ Attention! The following works only for Horizontal, Left-to-right sliders\n float posRatio = localMousePos.x() \/ (float )ui->videoSlider->size().width();\n int sliderRange = ui->videoSlider->maximum() - ui->videoSlider->minimum();\n int sliderPosUnderMouse = ui->videoSlider->minimum() + sliderRange * posRatio;\n if (sliderPosUnderMouse != newPos)\n {\n ui->videoSlider->setValue(sliderPosUnderMouse);\n return;\n }\n }\n}\n\/**\n * @brief MainWindow::closeEvent\n * asks if you are sure you want to quit.\n * @param event closing\n *\/\nvoid MainWindow::closeEvent (QCloseEvent *event){\n set_status_bar(\"Closing\");\n QMessageBox::StandardButton resBtn = QMessageBox::question( this, \"Exit\",\n tr(\"Are you sure you want to quit?\\n\"),\n QMessageBox::No | QMessageBox::Yes,\n QMessageBox::No);\n\n if (resBtn != QMessageBox::Yes) {\n event->ignore();\n } else {\n event->accept();\n }\n}\n\/**\n * @brief MainWindow::on_actionExit_triggered\n * sends a closeEvent when you press exit\n *\/\nvoid MainWindow::on_actionExit_triggered(){\n this->close();\n}\n\n\/**\n * @brief MainWindow::on_bookmarkButton_clicked\n * the button supposed to add a bookmark\n *\/\nvoid MainWindow::on_bookmarkButton_clicked(){\n \/\/ The code here is only temporary and should be moved\/removed\n \/\/ once a proper video selector is added\n\n mvideo_player->load_video(\"seq_01.mp4\");\n iconOnButtonHandler->set_icon(\"pause\", ui->playPauseButton);\n video_slider->setMaximum(mvideo_player->get_num_frames());\n mvideo_player->set_playback_frame(700);\n}\n\n\/**\n * @brief MainWindow::on_actionAddProject_triggered\n *\/\nvoid MainWindow::on_actionAddProject_triggered() {\n ACTION action = ADD_PROJECT;\n inputWindow = new inputwindow(this, action, \"Project name:\");\n inputWindow->show();\n set_status_bar(\"Adding project, need name\");\n}\n\n\/**\n * @brief MainWindow::inputSwitchCase\n * @param input the input from the user\n * @param action the action that was triggered earlier\n *\/\nvoid MainWindow::inputSwitchCase(ACTION action, QString qInput) {\n std::string input = qInput.toStdString();\n switch(action){\n case ADD_PROJECT: {\n fileHandler->create_project(input);\n QTreeWidgetItem *projectInTree = new QTreeWidgetItem();\n projectInTree->setText(0, qInput);\n ui->ProjectTree->addTopLevelItem(projectInTree);\n set_status_bar(\"Project \" + input + \"created.\");\n break;\n }\n case CANCEL: {\n set_status_bar(\"Cancel\");\n break;\n }\n default:\n break;\n\n }\n delete inputWindow;\n}\n\/**\n * @brief MainWindow::on_ProjectTree_itemClicked\n * @param item the item in the projectTree that was clicked\n * @param column the column in the tree\n *\/\nvoid MainWindow::on_ProjectTree_itemClicked(QTreeWidgetItem *item, int column) {\n}\n\n \/** @brief MainWindow::on_actionShow_hide_overview_triggered\n * Toggles the showing\/hiding of the overlay.\n * Invoked by menu item.\n *\/\nvoid MainWindow::on_actionShow_hide_overview_triggered() {\n mvideo_player->toggle_overlay();\n if (mvideo_player->is_showing_overlay()) {\n set_status_bar(\"Overlay: On.\");\n } else {\n set_status_bar(\"Overlay: Off.\");\n }\n}\n\n\/**\n * @brief MainWindow::on_actionColour_triggered\n * Selects a colour for the overlay drawing tool.\n *\/\nvoid MainWindow::on_actionColour_triggered() {\n QColor col = QColorDialog::getColor();\n mvideo_player->set_overlay_colour(col);\n set_status_bar(\"Color choosen.\");\n}\n\n\/**\n * @brief MainWindow::on_actionRectangle_triggered\n * Selects the rectangle shape for the overlay drawing tool.\n *\/\nvoid MainWindow::on_actionRectangle_triggered() {\n mvideo_player->set_overlay_tool(RECTANGLE);\n set_status_bar(\"Tool: rectangle.\");\n}\n\n\/**\n * @brief MainWindow::on_actionCircle_triggered\n * Selects the circle shape for the overlay drawing tool.\n *\/\nvoid MainWindow::on_actionCircle_triggered() {\n mvideo_player->set_overlay_tool(CIRCLE);\n set_status_bar(\"Tool: circle.\");\n}\n\n\/**\n * @brief MainWindow::on_actionLine_triggered\n * Selects the line shape for the overlay drawing tool.\n *\/\nvoid MainWindow::on_actionLine_triggered() {\n mvideo_player->set_overlay_tool(LINE);\n set_status_bar(\"Tool: line.\");\n}\n\n\/**\n * @brief MainWindow::on_actionArrow_triggered\n * Selects the arrow shape for the overlay drawing tool.\n *\/\nvoid MainWindow::on_actionArrow_triggered() {\n mvideo_player->set_overlay_tool(ARROW);\n set_status_bar(\"Tool: arrow.\");\n}\n\n\/**\n * @brief MainWindow::on_actionPen_triggered\n * Selects the pen for the overlay drawing tool.\n *\/\nvoid MainWindow::on_actionPen_triggered() {\n mvideo_player->set_overlay_tool(PEN);\n set_status_bar(\"Tool: pen.\");\n}\n\n\/**\n * @brief MainWindow::on_actionUndo_triggered\n * Undo the drawings on the overlay.\n *\/\nvoid MainWindow::on_actionUndo_triggered() {\n mvideo_player->undo_overlay();\n set_status_bar(\"Undo drawing.\");\n}\n\n\/**\n * @brief MainWindow::on_actionClear_triggered\n * Clear the drawings on the overlay.\n *\/\nvoid MainWindow::on_actionClear_triggered() {\n mvideo_player->clear_overlay();\n set_status_bar(\"Cleared drawings.\");\n}\n\n\/**\n * @brief MainWindow::eventFilter\n * Listener function for all eventFilters MainWindow has installed.\n * @param obj the object invoking the event\n * @param event the invooked event\n * @return\n *\/\nbool MainWindow::eventFilter(QObject *obj, QEvent *event) {\n \/\/ Check who invoked the event.\n if (qobject_cast<QLabel*>(obj)==ui->videoFrame) {\n \/\/ Cast to a mouse event to get the mouse position.\n QMouseEvent *mouseEvent = static_cast<QMouseEvent*>(event);\n QPoint pos = mouseEvent->pos();\n \/\/ Check what kind of event.\n if (event->type() == QEvent::MouseButtonPress) {\n mvideo_player->video_mouse_pressed(pos);\n } else if (event->type() == QEvent::MouseButtonRelease) {\n mvideo_player->video_mouse_released(pos);\n } else if (event->type() == QEvent::MouseMove) {\n mvideo_player->video_mouse_moved(pos);\n }\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n This file is part of KOrganizer.\n Copyright (c) 2000,2001 Cornelius Schumacher <schumacher@kde.org>\n\n This program is free software; you can redistribute it and\/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation; either version 2 of the License, or\n (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with this program; if not, write to the Free Software\n Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.\n\n As a special exception, permission is given to link this program\n with any edition of Qt, and distribute the resulting executable,\n without including the source code for Qt in the source distribution.\n*\/\n\n\/\/ ArchiveDialog -- archive\/delete past events.\n\n#include <qlabel.h>\n#include <qlayout.h>\n#include <qdatetime.h>\n#include <qcheckbox.h>\n#include <qwhatsthis.h>\n\n#include <kdebug.h>\n#include <klocale.h>\n#include <kurlrequester.h>\n#include <kmessagebox.h>\n#include <kfiledialog.h>\n#include <kurl.h>\n#include <klineedit.h>\n#include <kactivelabel.h>\n\n#include <libkdepim\/kdateedit.h>\n\n#include \"koprefs.h\"\n\n#include \"archivedialog.h\"\n#include \"eventarchiver.h\"\n#include <knuminput.h>\n#include <qbuttongroup.h>\n#include <qradiobutton.h>\n#include \"archivedialog.moc\"\n\nArchiveDialog::ArchiveDialog(Calendar *cal,QWidget *parent, const char *name)\n : KDialogBase (Plain,i18n(\"Archive\/Delete Past Events\"),\n User1|Cancel,User1,parent,name,false,true,\n i18n(\"&Archive\"))\n{\n mCalendar = cal;\n\n QFrame *topFrame = plainPage();\n QVBoxLayout *topLayout = new QVBoxLayout(topFrame);\n topLayout->setSpacing(spacingHint());\n\n KActiveLabel *descLabel = new KActiveLabel(\n i18n(\"Archiving saves old events into the given file and \"\n \"then deletes them in the current calendar. If the archive file \"\n \"already exists they will be added. \"\n \"(<a href=\\\"whatsthis:In order to add an archive \"\n \"to your calendar, use the "Merge Calendar" function. \"\n \"You can view an archive by opening it in KOrganizer like any \"\n \"other calendar. It is not saved in a special format, but as \"\n \"vCalendar.\\\">How to restore<\/a>)\"),\n topFrame);\n topLayout->addWidget(descLabel);\n\n QButtonGroup* radioBG = new QButtonGroup( this );\n radioBG->hide(); \/\/ just for the exclusive behavior\n connect( radioBG, SIGNAL( clicked( int ) ), SLOT( slotActionChanged() ) );\n\n QHBoxLayout *dateLayout = new QHBoxLayout(0);\n mArchiveOnceRB = new QRadioButton(i18n(\"Archive now events older than:\"),topFrame);\n dateLayout->addWidget(mArchiveOnceRB);\n radioBG->insert(mArchiveOnceRB);\n mDateEdit = new KDateEdit(topFrame);\n QWhatsThis::add(mDateEdit,\n i18n(\"The date before which events should be archived. All older events will \"\n \"be saved and deleted, the newer (and events exactly on that date) will be kept.\"));\n dateLayout->addWidget(mDateEdit);\n topLayout->addLayout(dateLayout);\n\n \/\/ Checkbox, numinput and combo for auto-archiving\n \/\/ (similar to kmail's mExpireFolderCheckBox\/mReadExpiryTimeNumInput in kmfolderdia.cpp)\n QHBox* autoArchiveHBox = new QHBox(topFrame);\n topLayout->addWidget(autoArchiveHBox);\n mAutoArchiveRB = new QRadioButton(i18n(\"Automaticall&y archive events older than:\"), autoArchiveHBox);\n radioBG->insert(mAutoArchiveRB);\n QWhatsThis::add(mAutoArchiveRB,\n i18n(\"If this feature is enabled, KOrganizer will regularly check if events have to be archived; \"\n \"this means you will not need to use this dialog box again, except to change the settings.\"));\n\n mExpiryTimeNumInput = new KIntNumInput(autoArchiveHBox);\n mExpiryTimeNumInput->setRange(1, 500, 1, false);\n mExpiryTimeNumInput->setEnabled(false);\n mExpiryTimeNumInput->setValue(7);\n QWhatsThis::add(mExpiryTimeNumInput,\n i18n(\"The age of the events to archive. All older events \"\n \"will be saved and deleted, the newer will be kept.\"));\n\n mExpiryUnitsComboBox = new QComboBox(autoArchiveHBox);\n \/\/ Those items must match the \"Expiry Unit\" enum in the kcfg file!\n mExpiryUnitsComboBox->insertItem(i18n(\"Day(s)\"));\n mExpiryUnitsComboBox->insertItem(i18n(\"Week(s)\"));\n mExpiryUnitsComboBox->insertItem(i18n(\"Month(s)\"));\n mExpiryUnitsComboBox->setEnabled(false);\n\n QHBoxLayout *fileLayout = new QHBoxLayout(0);\n fileLayout->setSpacing(spacingHint());\n QLabel *l = new QLabel(i18n(\"Archive &file:\"),topFrame);\n fileLayout->addWidget(l);\n mArchiveFile = new KURLRequester(KOPrefs::instance()->mArchiveFile,topFrame);\n mArchiveFile->setMode(KFile::File);\n mArchiveFile->setFilter(i18n(\"*.vcs|vCalendar Files\"));\n QWhatsThis::add(mArchiveFile,\n i18n(\"The path of the archive. The events will be added to the \"\n \"archive file, so any events that are already in the file \"\n \"will not be modified or deleted. You can later load or merge the \"\n \"file like any other calendar. It is not saved in a special \"\n \"format, it uses the vCalendar format. \"));\n l->setBuddy(mArchiveFile->lineEdit());\n fileLayout->addWidget(mArchiveFile);\n topLayout->addLayout(fileLayout);\n\n mDeleteCb = new QCheckBox(i18n(\"&Delete only, do not save\"),\n topFrame);\n QWhatsThis::add(mDeleteCb,\n i18n(\"Select this option to delete old events without saving them. \"\n \"It is not possible to recover the events later.\"));\n topLayout->addWidget(mDeleteCb);\n connect(mDeleteCb, SIGNAL(toggled(bool)), mArchiveFile, SLOT(setDisabled(bool)));\n connect(mDeleteCb, SIGNAL(toggled(bool)), this, SLOT(slotEnableUser1()));\n connect(mArchiveFile->lineEdit(),SIGNAL(textChanged ( const QString & )),\n this,SLOT(slotEnableUser1()));\n\n \/\/ Load settings from KOPrefs\n mExpiryTimeNumInput->setValue( KOPrefs::instance()->mExpiryTime );\n mExpiryUnitsComboBox->setCurrentItem( KOPrefs::instance()->mExpiryUnit );\n mDeleteCb->setChecked( KOPrefs::instance()->mArchiveAction == KOPrefs::actionDelete );\n\n slotEnableUser1();\n\n \/\/ The focus should go to a useful field by default, not to the top richtext-label\n if ( KOPrefs::instance()->mAutoArchive ) {\n mAutoArchiveRB->setChecked( true );\n mAutoArchiveRB->setFocus();\n } else {\n mArchiveOnceRB->setChecked( true );\n mArchiveOnceRB->setFocus();\n }\n slotActionChanged();\n}\n\nArchiveDialog::~ArchiveDialog()\n{\n}\n\nvoid ArchiveDialog::slotEnableUser1()\n{\n bool state = ( mDeleteCb->isChecked() ||\n !mArchiveFile->lineEdit()->text().isEmpty() );\n enableButton(KDialogBase::User1,state);\n}\n\nvoid ArchiveDialog::slotActionChanged()\n{\n mDateEdit->setEnabled( mArchiveOnceRB->isChecked() );\n mExpiryTimeNumInput->setEnabled( mAutoArchiveRB->isChecked() );\n mExpiryUnitsComboBox->setEnabled( mAutoArchiveRB->isChecked() );\n}\n\n\/\/ Archive old events\nvoid ArchiveDialog::slotUser1()\n{\n EventArchiver archiver;\n connect( &archiver, SIGNAL( eventsDeleted() ), this, SLOT( slotEventsDeleted() ) );\n\n KOPrefs::instance()->mAutoArchive = mAutoArchiveRB->isChecked();\n KOPrefs::instance()->mExpiryTime = mExpiryTimeNumInput->value();\n KOPrefs::instance()->mExpiryUnit = mExpiryUnitsComboBox->currentItem();\n\n if (mDeleteCb->isChecked()) {\n KOPrefs::instance()->mArchiveAction = KOPrefs::actionDelete;\n } else {\n KOPrefs::instance()->mArchiveAction = KOPrefs::actionArchive;\n\n \/\/ Get destination URL\n KURL destUrl( mArchiveFile->url() );\n if ( !destUrl.isValid() ) {\n KMessageBox::sorry(this,i18n(\"The archive file name is not valid.\\n\"));\n return;\n }\n \/\/ Force filename to be ending with vCalendar extension\n QString filename = destUrl.fileName();\n if (!filename.endsWith(\".vcs\") && !filename.endsWith(\".ics\")) {\n filename.append(\".ics\");\n destUrl.setFileName(filename);\n }\n\n KOPrefs::instance()->mArchiveFile = destUrl.url();\n }\n if ( KOPrefs::instance()->mAutoArchive ) {\n archiver.runAuto( mCalendar, this, true \/*with gui*\/ );\n emit autoArchivingSettingsModified();\n accept();\n }\n else\n archiver.runOnce( mCalendar, mDateEdit->date(), this );\n}\n\nvoid ArchiveDialog::slotEventsDeleted()\n{\n emit eventsDeleted();\n if ( !KOPrefs::instance()->mAutoArchive )\n accept();\n}\n<commit_msg>Archive expects an .ics file. Reusing existing i18n string here<commit_after>\/*\n This file is part of KOrganizer.\n Copyright (c) 2000,2001 Cornelius Schumacher <schumacher@kde.org>\n\n This program is free software; you can redistribute it and\/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation; either version 2 of the License, or\n (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with this program; if not, write to the Free Software\n Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.\n\n As a special exception, permission is given to link this program\n with any edition of Qt, and distribute the resulting executable,\n without including the source code for Qt in the source distribution.\n*\/\n\n\/\/ ArchiveDialog -- archive\/delete past events.\n\n#include <qlabel.h>\n#include <qlayout.h>\n#include <qdatetime.h>\n#include <qcheckbox.h>\n#include <qwhatsthis.h>\n\n#include <kdebug.h>\n#include <klocale.h>\n#include <kurlrequester.h>\n#include <kmessagebox.h>\n#include <kfiledialog.h>\n#include <kurl.h>\n#include <klineedit.h>\n#include <kactivelabel.h>\n\n#include <libkdepim\/kdateedit.h>\n\n#include \"koprefs.h\"\n\n#include \"archivedialog.h\"\n#include \"eventarchiver.h\"\n#include <knuminput.h>\n#include <qbuttongroup.h>\n#include <qradiobutton.h>\n#include \"archivedialog.moc\"\n\nArchiveDialog::ArchiveDialog(Calendar *cal,QWidget *parent, const char *name)\n : KDialogBase (Plain,i18n(\"Archive\/Delete Past Events\"),\n User1|Cancel,User1,parent,name,false,true,\n i18n(\"&Archive\"))\n{\n mCalendar = cal;\n\n QFrame *topFrame = plainPage();\n QVBoxLayout *topLayout = new QVBoxLayout(topFrame);\n topLayout->setSpacing(spacingHint());\n\n KActiveLabel *descLabel = new KActiveLabel(\n i18n(\"Archiving saves old events into the given file and \"\n \"then deletes them in the current calendar. If the archive file \"\n \"already exists they will be added. \"\n \"(<a href=\\\"whatsthis:In order to add an archive \"\n \"to your calendar, use the "Merge Calendar" function. \"\n \"You can view an archive by opening it in KOrganizer like any \"\n \"other calendar. It is not saved in a special format, but as \"\n \"vCalendar.\\\">How to restore<\/a>)\"),\n topFrame);\n topLayout->addWidget(descLabel);\n\n QButtonGroup* radioBG = new QButtonGroup( this );\n radioBG->hide(); \/\/ just for the exclusive behavior\n connect( radioBG, SIGNAL( clicked( int ) ), SLOT( slotActionChanged() ) );\n\n QHBoxLayout *dateLayout = new QHBoxLayout(0);\n mArchiveOnceRB = new QRadioButton(i18n(\"Archive now events older than:\"),topFrame);\n dateLayout->addWidget(mArchiveOnceRB);\n radioBG->insert(mArchiveOnceRB);\n mDateEdit = new KDateEdit(topFrame);\n QWhatsThis::add(mDateEdit,\n i18n(\"The date before which events should be archived. All older events will \"\n \"be saved and deleted, the newer (and events exactly on that date) will be kept.\"));\n dateLayout->addWidget(mDateEdit);\n topLayout->addLayout(dateLayout);\n\n \/\/ Checkbox, numinput and combo for auto-archiving\n \/\/ (similar to kmail's mExpireFolderCheckBox\/mReadExpiryTimeNumInput in kmfolderdia.cpp)\n QHBox* autoArchiveHBox = new QHBox(topFrame);\n topLayout->addWidget(autoArchiveHBox);\n mAutoArchiveRB = new QRadioButton(i18n(\"Automaticall&y archive events older than:\"), autoArchiveHBox);\n radioBG->insert(mAutoArchiveRB);\n QWhatsThis::add(mAutoArchiveRB,\n i18n(\"If this feature is enabled, KOrganizer will regularly check if events have to be archived; \"\n \"this means you will not need to use this dialog box again, except to change the settings.\"));\n\n mExpiryTimeNumInput = new KIntNumInput(autoArchiveHBox);\n mExpiryTimeNumInput->setRange(1, 500, 1, false);\n mExpiryTimeNumInput->setEnabled(false);\n mExpiryTimeNumInput->setValue(7);\n QWhatsThis::add(mExpiryTimeNumInput,\n i18n(\"The age of the events to archive. All older events \"\n \"will be saved and deleted, the newer will be kept.\"));\n\n mExpiryUnitsComboBox = new QComboBox(autoArchiveHBox);\n \/\/ Those items must match the \"Expiry Unit\" enum in the kcfg file!\n mExpiryUnitsComboBox->insertItem(i18n(\"Day(s)\"));\n mExpiryUnitsComboBox->insertItem(i18n(\"Week(s)\"));\n mExpiryUnitsComboBox->insertItem(i18n(\"Month(s)\"));\n mExpiryUnitsComboBox->setEnabled(false);\n\n QHBoxLayout *fileLayout = new QHBoxLayout(0);\n fileLayout->setSpacing(spacingHint());\n QLabel *l = new QLabel(i18n(\"Archive &file:\"),topFrame);\n fileLayout->addWidget(l);\n mArchiveFile = new KURLRequester(KOPrefs::instance()->mArchiveFile,topFrame);\n mArchiveFile->setMode(KFile::File);\n mArchiveFile->setFilter(i18n(\"*.ics|ICalendars\"));\n QWhatsThis::add(mArchiveFile,\n i18n(\"The path of the archive. The events will be added to the \"\n \"archive file, so any events that are already in the file \"\n \"will not be modified or deleted. You can later load or merge the \"\n \"file like any other calendar. It is not saved in a special \"\n \"format, it uses the vCalendar format. \"));\n l->setBuddy(mArchiveFile->lineEdit());\n fileLayout->addWidget(mArchiveFile);\n topLayout->addLayout(fileLayout);\n\n mDeleteCb = new QCheckBox(i18n(\"&Delete only, do not save\"),\n topFrame);\n QWhatsThis::add(mDeleteCb,\n i18n(\"Select this option to delete old events without saving them. \"\n \"It is not possible to recover the events later.\"));\n topLayout->addWidget(mDeleteCb);\n connect(mDeleteCb, SIGNAL(toggled(bool)), mArchiveFile, SLOT(setDisabled(bool)));\n connect(mDeleteCb, SIGNAL(toggled(bool)), this, SLOT(slotEnableUser1()));\n connect(mArchiveFile->lineEdit(),SIGNAL(textChanged ( const QString & )),\n this,SLOT(slotEnableUser1()));\n\n \/\/ Load settings from KOPrefs\n mExpiryTimeNumInput->setValue( KOPrefs::instance()->mExpiryTime );\n mExpiryUnitsComboBox->setCurrentItem( KOPrefs::instance()->mExpiryUnit );\n mDeleteCb->setChecked( KOPrefs::instance()->mArchiveAction == KOPrefs::actionDelete );\n\n slotEnableUser1();\n\n \/\/ The focus should go to a useful field by default, not to the top richtext-label\n if ( KOPrefs::instance()->mAutoArchive ) {\n mAutoArchiveRB->setChecked( true );\n mAutoArchiveRB->setFocus();\n } else {\n mArchiveOnceRB->setChecked( true );\n mArchiveOnceRB->setFocus();\n }\n slotActionChanged();\n}\n\nArchiveDialog::~ArchiveDialog()\n{\n}\n\nvoid ArchiveDialog::slotEnableUser1()\n{\n bool state = ( mDeleteCb->isChecked() ||\n !mArchiveFile->lineEdit()->text().isEmpty() );\n enableButton(KDialogBase::User1,state);\n}\n\nvoid ArchiveDialog::slotActionChanged()\n{\n mDateEdit->setEnabled( mArchiveOnceRB->isChecked() );\n mExpiryTimeNumInput->setEnabled( mAutoArchiveRB->isChecked() );\n mExpiryUnitsComboBox->setEnabled( mAutoArchiveRB->isChecked() );\n}\n\n\/\/ Archive old events\nvoid ArchiveDialog::slotUser1()\n{\n EventArchiver archiver;\n connect( &archiver, SIGNAL( eventsDeleted() ), this, SLOT( slotEventsDeleted() ) );\n\n KOPrefs::instance()->mAutoArchive = mAutoArchiveRB->isChecked();\n KOPrefs::instance()->mExpiryTime = mExpiryTimeNumInput->value();\n KOPrefs::instance()->mExpiryUnit = mExpiryUnitsComboBox->currentItem();\n\n if (mDeleteCb->isChecked()) {\n KOPrefs::instance()->mArchiveAction = KOPrefs::actionDelete;\n } else {\n KOPrefs::instance()->mArchiveAction = KOPrefs::actionArchive;\n\n \/\/ Get destination URL\n KURL destUrl( mArchiveFile->url() );\n if ( !destUrl.isValid() ) {\n KMessageBox::sorry(this,i18n(\"The archive file name is not valid.\\n\"));\n return;\n }\n \/\/ Force filename to be ending with vCalendar extension\n QString filename = destUrl.fileName();\n if (!filename.endsWith(\".vcs\") && !filename.endsWith(\".ics\")) {\n filename.append(\".ics\");\n destUrl.setFileName(filename);\n }\n\n KOPrefs::instance()->mArchiveFile = destUrl.url();\n }\n if ( KOPrefs::instance()->mAutoArchive ) {\n archiver.runAuto( mCalendar, this, true \/*with gui*\/ );\n emit autoArchivingSettingsModified();\n accept();\n }\n else\n archiver.runOnce( mCalendar, mDateEdit->date(), this );\n}\n\nvoid ArchiveDialog::slotEventsDeleted()\n{\n emit eventsDeleted();\n if ( !KOPrefs::instance()->mAutoArchive )\n accept();\n}\n<|endoftext|>"} {"text":"<commit_before>#pragma once\n\/\/=====================================================================\/\/\n\/*!\t@file\n\t@brief\tR8C グループ・A\/D 制御 @n\n\t\t\tCopyright 2015 Kunihito Hiramatsu\n\t@author\t平松邦仁 (hira@rvf-rc45.net)\n*\/\n\/\/=====================================================================\/\/\n#include \"common\/vect.h\"\n#include \"adc.hpp\"\n#include \"intr.hpp\"\n#include \"system.hpp\"\n\nnamespace device {\n\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\t\/*!\n\t\t@brief A\/D 制御クラス\n\t\t@param[in]\tTASK\tA\/D 変換終了時起動タスク\n\t*\/\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\ttemplate <class TASK>\n\tclass adc_io {\n\n\t\tstatic TASK\ttask_;\n\t\tstatic volatile uint8_t intr_count_;\n\n\tpublic:\n\t\tenum class cnv_type : uint8_t {\n\t\t\tCH0,\t\t\/\/< チャネル0のみ\n\t\t\tCH1,\t\t\/\/< チャネル1のみ\n\t\t\tCH0_CH1\t\t\/\/< 0,1チャネル\n\t\t};\n\n\t\tenum class ch_grp : uint8_t {\n\t\t\tAN0_AN1,\t\/\/< AN0, AN1\n\t\t\tAN2_AN3,\t\/\/< AN2, AN3\n\t\t\tAN4_AN7\t\t\/\/< AN4, AN7\n\t\t};\n\n\t\tstatic INTERRUPT_FUNC void itask() __attribute__ ((section (\".text\"))) {\n\t\t\t++intr_count_;\n\t\t\ttask_();\n\t\t\t\/\/ IR 関係フラグは必ず mov 命令で・・\n\t\t\tvolatile uint8_t r = ADICSR();\n\t\t\tADICSR = 0x00;\n\t\t}\n\n\tprivate:\n\t\tuint8_t\tlevel_;\n\t\tuint8_t\tcount_;\n\n\t\t\/\/ ※同期が必要なら、実装する\n\t\tvoid sleep_() const {\n\t\t\tasm(\"nop\");\n\t\t}\n\n\tpublic:\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\t\/*!\n\t\t\t@brief コンストラクター\n\t\t*\/\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\t__attribute__ ((section (\".text\"))) \n\t\tadc_io() : level_(0), count_(0) { }\n\n\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\t\/*!\n\t\t\t@brief 変換開始\n\t\t\t@param[in]\tct\t\t変換タイプ\n\t\t\t@param[in]\tgrp\t\tグループ\n\t\t\t@param[in]\tcycle\t繰り返し変換の場合「true」\n\t\t\t@param[in]\tlevel\t割り込みレベル(0の場合割り込みを使用しない)\n\t\t*\/\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\tvoid start(cnv_type ct, ch_grp cg, bool cycle, uint8_t level = 0)\n\t\t{\n\t\t\tlevel_ = level;\n\n\t\t\tMSTCR.MSTAD = 0;\n\n\t\t\tADCON0.ADST = 0;\n\n\t\t\tuint8_t md = 0;\n\t\t\tif(ct == cnv_type::CH0_CH1) md = 2;\n\t\t\tif(cycle) ++md; \n\t\t\tADMOD = ADMOD.CKS.b(3) | ADMOD.MD.b(md);\n\n\t\t\tuint8_t chn = 0;\n\t\t\tif(ct == cnv_type::CH1) chn = 1; \n\t\t\tADINSEL = ADINSEL.CH0.b(chn) | ADINSEL.ADGSEL.b(static_cast<uint8_t>(cg));\n\n\t\t\tILVL7.B01 = level_;\n\t\t}\n\n\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\t\/*!\n\t\t\t@brief 変換開始\n\t\t\t@param[in]\tf\t変換停止の場合「false」\n\t\t*\/\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\tvoid scan(bool f = 1) {\n\t\t\tcount_ = intr_count_;\n\t\t\tif(f && level_ > 0) {\n\t\t\t\tADICSR.ADIE = 1;\n\t\t\t}\n\t\t\tADCON0.ADST = f;\n\t\t}\n\n\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\t\/*!\n\t\t\t@brief 変換終了検査\n\t\t\t@return 変換終了なら「true」\n\t\t*\/\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\tbool get_state() const {\n\t\t\tif(level_ == 0) {\n\t\t\t\tbool f = ADICSR.ADF();\n\t\t\t\tif(f) ADICSR.ADF = 0;\n\t\t\t\treturn f;\n\t\t\t} else {\n\t\t\t\treturn count_ != intr_count_;\n\t\t\t}\n\t\t}\n\n\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\t\/*!\n\t\t\t@brief 変換終了を同期\n\t\t*\/\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\tvoid sync() const {\n\t\t\twhile(!get_state()) sleep_();\n\t\t}\n\n\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\t\/*!\n\t\t\t@brief 変換結果の取得\n\t\t\t@param[in]\tchanel\tチャネル(0、1)\n\t\t\t@return 変換結果\n\t\t*\/\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\tuint16_t get_value(bool chanel) const {\n\t\t\tif(chanel) {\n\t\t\t\treturn AD1();\n\t\t\t} else {\n\t\t\t\treturn AD0();\n\t\t\t}\n\t\t}\n\t};\n\n\t\/\/ スタティック実態定義\n\ttemplate<class TASK>\n\tTASK adc_io<TASK>::task_;\n\n\ttemplate<class TASK>\n\tvolatile uint8_t adc_io<TASK>::intr_count_ = 0;\n}\n<commit_msg>update comment<commit_after>#pragma once\n\/\/=====================================================================\/\/\n\/*!\t@file\n\t@brief\tR8C グループ・A\/D 制御 @n\n\t\t\tCopyright 2015 Kunihito Hiramatsu\n\t@author\t平松邦仁 (hira@rvf-rc45.net)\n*\/\n\/\/=====================================================================\/\/\n#include \"common\/vect.h\"\n#include \"adc.hpp\"\n#include \"intr.hpp\"\n#include \"system.hpp\"\n\nnamespace device {\n\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\t\/*!\n\t\t@brief A\/D 制御クラス\n\t\t@param[in]\tTASK\tA\/D 変換終了時起動タスク\n\t*\/\n\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\ttemplate <class TASK>\n\tclass adc_io {\n\n\t\tstatic TASK\ttask_;\n\t\tstatic volatile uint8_t intr_count_;\n\n\tpublic:\n\t\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\t\t\/*!\n\t\t\t@brief チャネル・タイプ\n\t\t*\/\n\t\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\t\tenum class cnv_type : uint8_t {\n\t\t\tCH0,\t\t\/\/< チャネル0のみ\n\t\t\tCH1,\t\t\/\/< チャネル1のみ\n\t\t\tCH0_CH1\t\t\/\/< 0,1チャネル\n\t\t};\n\n\n\t\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\t\t\/*!\n\t\t\t@brief チャネル・グループ\n\t\t*\/\n\t\t\/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\t\tenum class ch_grp : uint8_t {\n\t\t\tAN0_AN1,\t\/\/< AN0, AN1\n\t\t\tAN2_AN3,\t\/\/< AN2, AN3\n\t\t\tAN4_AN7\t\t\/\/< AN4, AN7\n\t\t};\n\n\n\t\tstatic INTERRUPT_FUNC void itask() __attribute__ ((section (\".text\"))) {\n\t\t\t++intr_count_;\n\t\t\ttask_();\n\t\t\t\/\/ IR 関係フラグは必ず mov 命令で・・\n\t\t\tvolatile uint8_t r = ADICSR();\n\t\t\tADICSR = 0x00;\n\t\t}\n\n\tprivate:\n\t\tuint8_t\tlevel_;\n\t\tuint8_t\tcount_;\n\n\t\t\/\/ ※同期が必要なら、実装する\n\t\tvoid sleep_() const {\n\t\t\tasm(\"nop\");\n\t\t}\n\n\tpublic:\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\t\/*!\n\t\t\t@brief コンストラクター\n\t\t*\/\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\t__attribute__ ((section (\".text\"))) \n\t\tadc_io() : level_(0), count_(0) { }\n\n\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\t\/*!\n\t\t\t@brief 変換開始\n\t\t\t@param[in]\tct\t\t変換タイプ\n\t\t\t@param[in]\tgrp\t\tグループ\n\t\t\t@param[in]\tcycle\t繰り返し変換の場合「true」\n\t\t\t@param[in]\tlevel\t割り込みレベル(0の場合割り込みを使用しない)\n\t\t*\/\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\tvoid start(cnv_type ct, ch_grp cg, bool cycle, uint8_t level = 0)\n\t\t{\n\t\t\tlevel_ = level;\n\n\t\t\tMSTCR.MSTAD = 0;\n\n\t\t\tADCON0.ADST = 0;\n\n\t\t\tuint8_t md = 0;\n\t\t\tif(ct == cnv_type::CH0_CH1) md = 2;\n\t\t\tif(cycle) ++md; \n\t\t\tADMOD = ADMOD.CKS.b(3) | ADMOD.MD.b(md);\n\n\t\t\tuint8_t chn = 0;\n\t\t\tif(ct == cnv_type::CH1) chn = 1; \n\t\t\tADINSEL = ADINSEL.CH0.b(chn) | ADINSEL.ADGSEL.b(static_cast<uint8_t>(cg));\n\n\t\t\tILVL7.B01 = level_;\n\t\t}\n\n\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\t\/*!\n\t\t\t@brief 変換開始\n\t\t\t@param[in]\tf\t変換停止の場合「false」\n\t\t*\/\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\tvoid scan(bool f = 1) {\n\t\t\tcount_ = intr_count_;\n\t\t\tif(f && level_ > 0) {\n\t\t\t\tADICSR.ADIE = 1;\n\t\t\t}\n\t\t\tADCON0.ADST = f;\n\t\t}\n\n\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\t\/*!\n\t\t\t@brief 変換終了検査\n\t\t\t@return 変換終了なら「true」\n\t\t*\/\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\tbool get_state() const {\n\t\t\tif(level_ == 0) {\n\t\t\t\tbool f = ADICSR.ADF();\n\t\t\t\tif(f) ADICSR.ADF = 0;\n\t\t\t\treturn f;\n\t\t\t} else {\n\t\t\t\treturn count_ != intr_count_;\n\t\t\t}\n\t\t}\n\n\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\t\/*!\n\t\t\t@brief 変換終了を同期\n\t\t*\/\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\tvoid sync() const {\n\t\t\twhile(!get_state()) sleep_();\n\t\t}\n\n\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\t\/*!\n\t\t\t@brief 変換結果の取得\n\t\t\t@param[in]\tchanel\tチャネル(0、1)\n\t\t\t@return 変換結果\n\t\t*\/\n\t\t\/\/-----------------------------------------------------------------\/\/\n\t\tuint16_t get_value(bool chanel) const {\n\t\t\tif(chanel) {\n\t\t\t\treturn AD1();\n\t\t\t} else {\n\t\t\t\treturn AD0();\n\t\t\t}\n\t\t}\n\t};\n\n\t\/\/ スタティック実態定義\n\ttemplate<class TASK>\n\tTASK adc_io<TASK>::task_;\n\n\ttemplate<class TASK>\n\tvolatile uint8_t adc_io<TASK>::intr_count_ = 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/******************************************************************************\n * _ _____ __________ *\n * | | \/ \/ _ | \/ __\/_ __\/ Visibility *\n * | |\/ \/ __ |_\\ \\ \/ \/ Across *\n * |___\/_\/ |_\/___\/ \/_\/ Space and Time *\n * *\n * This file is part of VAST. It is subject to the license terms in the *\n * LICENSE file found in the top-level directory of this distribution and at *\n * http:\/\/vast.io\/license. No part of VAST, including this file, may be *\n * copied, modified, propagated, or distributed except according to the terms *\n * contained in the LICENSE file. *\n ******************************************************************************\/\n\n#include <caf\/all.hpp>\n\n#include \"vast\/concept\/printable\/std\/chrono.hpp\"\n#include \"vast\/concept\/printable\/to_string.hpp\"\n#include \"vast\/concept\/printable\/vast\/event.hpp\"\n#include \"vast\/concept\/printable\/vast\/expression.hpp\"\n#include \"vast\/concept\/printable\/vast\/uuid.hpp\"\n#include \"vast\/const_table_slice_handle.hpp\"\n#include \"vast\/detail\/assert.hpp\"\n#include \"vast\/event.hpp\"\n#include \"vast\/expression_visitors.hpp\"\n#include \"vast\/logger.hpp\"\n#include \"vast\/table_slice.hpp\"\n#include \"vast\/to_events.hpp\"\n\n#include \"vast\/system\/archive.hpp\"\n#include \"vast\/system\/atoms.hpp\"\n#include \"vast\/system\/exporter.hpp\"\n\n#include \"vast\/detail\/assert.hpp\"\n\nusing namespace std::chrono;\nusing namespace std::string_literals;\nusing namespace caf;\n\nnamespace vast {\nnamespace system {\n\nnamespace {\n\nvoid ship_results(stateful_actor<exporter_state>* self) {\n VAST_TRACE(\"\");\n if (self->state.results.empty() || self->state.stats.requested == 0) {\n return;\n }\n VAST_INFO(self, \"relays\", self->state.results.size(), \"events\");\n message msg;\n if (self->state.results.size() <= self->state.stats.requested) {\n self->state.stats.requested -= self->state.results.size();\n self->state.stats.shipped += self->state.results.size();\n msg = make_message(std::move(self->state.results));\n self->state.results = {};\n } else {\n std::vector<event> remainder;\n remainder.reserve(self->state.results.size() - self->state.stats.requested);\n auto begin = self->state.results.begin() + self->state.stats.requested;\n auto end = self->state.results.end();\n std::move(begin, end, std::back_inserter(remainder));\n self->state.results.resize(self->state.stats.requested);\n msg = make_message(std::move(self->state.results));\n self->state.results = std::move(remainder);\n self->state.stats.shipped += self->state.stats.requested;\n self->state.stats.requested = 0;\n }\n self->send(self->state.sink, msg);\n}\n\nvoid report_statistics(stateful_actor<exporter_state>* self) {\n timespan runtime = steady_clock::now() - self->state.start;\n self->state.stats.runtime = runtime;\n VAST_INFO(self, \"completed in\", runtime);\n self->send(self->state.sink, self->state.id, self->state.stats);\n if (self->state.accountant) {\n auto hits = rank(self->state.hits);\n auto processed = self->state.stats.processed;\n auto shipped = self->state.stats.shipped;\n auto results = shipped + self->state.results.size();\n auto selectivity = double(results) \/ hits;\n self->send(self->state.accountant, \"exporter.hits\", hits);\n self->send(self->state.accountant, \"exporter.processed\", processed);\n self->send(self->state.accountant, \"exporter.results\", results);\n self->send(self->state.accountant, \"exporter.shipped\", shipped);\n self->send(self->state.accountant, \"exporter.selectivity\", selectivity);\n self->send(self->state.accountant, \"exporter.runtime\", runtime);\n }\n}\n\nvoid shutdown(stateful_actor<exporter_state>* self, caf::error err) {\n VAST_DEBUG(self, \"initiates shutdown with error\", self->system().render(err));\n self->send_exit(self, std::move(err));\n}\n\nvoid shutdown(stateful_actor<exporter_state>* self) {\n if (rank(self->state.unprocessed) > 0 || !self->state.results.empty()\n || has_continuous_option(self->state.options))\n return;\n VAST_DEBUG(self, \"initiates shutdown\");\n self->send_exit(self, exit_reason::normal);\n}\n\nvoid request_more_hits(stateful_actor<exporter_state>* self) {\n if (!has_historical_option(self->state.options))\n return;\n auto waiting_for_hits =\n self->state.stats.received == self->state.stats.scheduled;\n auto need_more_results = self->state.stats.requested > 0;\n auto have_no_inflight_requests = any<1>(self->state.unprocessed);\n \/\/ If we're (1) no longer waiting for index hits, (2) still need more\n \/\/ results, and (3) have no inflight requests to the archive, we ask\n \/\/ the index for more hits.\n if (!waiting_for_hits && need_more_results && have_no_inflight_requests) {\n auto remaining = self->state.stats.expected - self->state.stats.received;\n VAST_ASSERT(remaining > 0);\n \/\/ TODO: Figure out right number of partitions to ask for. For now, we\n \/\/ bound the number by an arbitrary constant.\n auto n = std::min(remaining, size_t{2});\n VAST_DEBUG(self, \"asks index to process\", n, \"more partitions\");\n self->send(self->state.index, self->state.id, n);\n }\n}\n\n} \/\/ namespace <anonymous>\n\nbehavior exporter(stateful_actor<exporter_state>* self, expression expr,\n query_options options) {\n auto eu = self->system().dummy_execution_unit();\n self->state.sink = actor_pool::make(eu, actor_pool::broadcast());\n if (auto a = self->system().registry().get(accountant_atom::value))\n self->state.accountant = actor_cast<accountant_type>(a);\n self->state.options = options;\n if (has_continuous_option(options))\n VAST_DEBUG(self, \"has continuous query option\");\n self->set_exit_handler(\n [=](const exit_msg& msg) {\n VAST_DEBUG(self, \"received exit from\", msg.source, \"with reason:\", msg.reason);\n self->send(self->state.sink, sys_atom::value, delete_atom::value);\n self->send_exit(self->state.sink, msg.reason);\n self->quit(msg.reason);\n if (msg.reason != exit_reason::kill)\n report_statistics(self);\n }\n );\n self->set_down_handler(\n [=](const down_msg& msg) {\n VAST_DEBUG(self, \"received DOWN from\", msg.source);\n if (has_continuous_option(self->state.options)\n && (msg.source == self->state.archive\n || msg.source == self->state.index))\n report_statistics(self);\n }\n );\n auto handle_batch = [=](std::vector<event>& candidates) {\n VAST_DEBUG(self, \"got batch of\", candidates.size(), \"events\");\n \/\/ Events can arrive in any order: sort them by ID first. Otherwise, we\n \/\/ can't compute the bitmap mask as easily.\n std::sort(candidates.begin(), candidates.end(),\n [](auto& x, auto& y) { return x.id() < y.id(); });\n bitmap mask;\n auto sender = self->current_sender();\n for (auto& candidate : candidates) {\n auto& checker = self->state.checkers[candidate.type()];\n \/\/ Construct a candidate checker if we don't have one for this type.\n if (caf::holds_alternative<caf::none_t>(checker)) {\n auto x = tailor(expr, candidate.type());\n if (!x) {\n VAST_ERROR(self, \"failed to tailor expression:\",\n self->system().render(x.error()));\n ship_results(self);\n self->send_exit(self, exit_reason::normal);\n return;\n }\n checker = std::move(*x);\n VAST_DEBUG(self, \"tailored AST to\", candidate.type() << ':', checker);\n }\n \/\/ Append ID to our bitmap mask.\n if (sender == self->state.archive) {\n mask.append_bits(false, candidate.id() - mask.size());\n mask.append_bit(true);\n }\n \/\/ Perform candidate check and keep event as result on success.\n if (caf::visit(event_evaluator{candidate}, checker))\n self->state.results.push_back(std::move(candidate));\n else\n VAST_DEBUG(self, \"ignores false positive:\", candidate);\n }\n self->state.stats.processed += candidates.size();\n if (sender == self->state.archive)\n self->state.unprocessed -= mask;\n ship_results(self);\n request_more_hits(self);\n if (self->state.stats.received == self->state.stats.expected)\n shutdown(self);\n };\n return {\n [=](ids& hits) {\n timespan runtime = steady_clock::now() - self->state.start;\n self->state.stats.runtime = runtime;\n auto count = rank(hits);\n if (self->state.accountant) {\n if (self->state.hits.empty())\n self->send(self->state.accountant, \"exporter.hits.first\", runtime);\n self->send(self->state.accountant, \"exporter.hits.arrived\", runtime);\n self->send(self->state.accountant, \"exporter.hits.count\", count);\n }\n VAST_DEBUG(self, \"got\", count, \"index hits\",\n (count == 0 ? \"\" : (\"in [\"s + to_string(select(hits, 1)) + ','\n + to_string(select(hits, -1) + 1) + ')')));\n if (count > 0) {\n self->state.hits |= hits;\n self->state.unprocessed |= hits;\n VAST_DEBUG(self, \"forwards hits to archive\");\n \/\/ FIXME: restrict according to configured limit.\n self->send(self->state.archive, std::move(hits));\n }\n \/\/ Figure out if we're done.\n ++self->state.stats.received;\n self->send(self->state.sink, self->state.id, self->state.stats);\n if (self->state.stats.received < self->state.stats.expected) {\n VAST_DEBUG(self, \"received\", self->state.stats.received << '\/'\n << self->state.stats.expected, \"ID sets\");\n request_more_hits(self);\n } else {\n VAST_DEBUG(self, \"received all\", self->state.stats.expected,\n \"ID set(s) in\", runtime);\n if (self->state.accountant)\n self->send(self->state.accountant, \"exporter.hits.runtime\", runtime);\n shutdown(self);\n }\n },\n [=](std::vector<event>& candidates) {\n handle_batch(candidates);\n },\n [=](extract_atom) {\n if (self->state.stats.requested == max_events) {\n VAST_WARNING(self, \"ignores extract request, already getting all\");\n return;\n }\n self->state.stats.requested = max_events;\n ship_results(self);\n request_more_hits(self);\n },\n [=](extract_atom, uint64_t requested) {\n if (self->state.stats.requested == max_events) {\n VAST_WARNING(self, \"ignores extract request, already getting all\");\n return;\n }\n auto n = std::min(max_events - requested, requested);\n self->state.stats.requested += n;\n VAST_DEBUG(self, \"got request to extract\", n, \"new events in addition to\",\n self->state.stats.requested, \"pending results\");\n ship_results(self);\n request_more_hits(self);\n },\n [=](const archive_type& archive) {\n VAST_DEBUG(self, \"registers archive\", archive);\n self->state.archive = archive;\n if (has_continuous_option(self->state.options))\n self->monitor(archive);\n },\n [=](index_atom, const actor& index) {\n VAST_DEBUG(self, \"registers index\", index);\n self->state.index = index;\n if (has_continuous_option(self->state.options))\n self->monitor(index);\n },\n [=](sink_atom, const actor& sink) {\n VAST_DEBUG(self, \"registers sink\", sink);\n self->send(self->state.sink, sys_atom::value, put_atom::value, sink);\n self->monitor(self->state.sink);\n },\n [=](importer_atom, const std::vector<actor>& importers) {\n \/\/ Register for events at running IMPORTERs.\n if (has_continuous_option(self->state.options))\n for (auto& x : importers)\n self->send(x, exporter_atom::value, self);\n },\n [=](run_atom) {\n VAST_INFO(self, \"executes query\", expr);\n self->state.start = steady_clock::now();\n if (!has_historical_option(self->state.options))\n return;\n self->request(self->state.index, infinite, expr).then(\n [=](const uuid& lookup, size_t partitions, size_t scheduled) {\n VAST_DEBUG(self, \"got lookup handle\", lookup << \", scheduled\",\n scheduled << '\/' << partitions, \"partitions\");\n self->state.id = lookup;\n if (partitions > 0) {\n self->state.stats.expected = partitions;\n self->state.stats.scheduled = scheduled;\n } else {\n shutdown(self);\n }\n },\n [=](const error& e) {\n VAST_IGNORE_UNUSED(e);\n VAST_DEBUG(self, \"failed to lookup query at index:\",\n self->system().render(e));\n shutdown(self, e);\n }\n );\n },\n [=](caf::stream<const_table_slice_handle> in) {\n return self->make_sink(\n in,\n [](caf::unit_t&) {\n \/\/ nop\n },\n [=](caf::unit_t&, const const_table_slice_handle& slice) {\n \/\/ TODO: portjto new table slice API\n auto candidates = to_events(*slice);\n handle_batch(candidates);\n },\n [=](caf::unit_t&, const error& err) {\n VAST_IGNORE_UNUSED(err);\n VAST_ERROR(self, \"got error during streaming: \", err);\n }\n );\n },\n };\n}\n\n} \/\/ namespace system\n} \/\/ namespace vast\n<commit_msg>Remove overly noisy debug statement<commit_after>\/******************************************************************************\n * _ _____ __________ *\n * | | \/ \/ _ | \/ __\/_ __\/ Visibility *\n * | |\/ \/ __ |_\\ \\ \/ \/ Across *\n * |___\/_\/ |_\/___\/ \/_\/ Space and Time *\n * *\n * This file is part of VAST. It is subject to the license terms in the *\n * LICENSE file found in the top-level directory of this distribution and at *\n * http:\/\/vast.io\/license. No part of VAST, including this file, may be *\n * copied, modified, propagated, or distributed except according to the terms *\n * contained in the LICENSE file. *\n ******************************************************************************\/\n\n#include <caf\/all.hpp>\n\n#include \"vast\/concept\/printable\/std\/chrono.hpp\"\n#include \"vast\/concept\/printable\/to_string.hpp\"\n#include \"vast\/concept\/printable\/vast\/event.hpp\"\n#include \"vast\/concept\/printable\/vast\/expression.hpp\"\n#include \"vast\/concept\/printable\/vast\/uuid.hpp\"\n#include \"vast\/const_table_slice_handle.hpp\"\n#include \"vast\/detail\/assert.hpp\"\n#include \"vast\/event.hpp\"\n#include \"vast\/expression_visitors.hpp\"\n#include \"vast\/logger.hpp\"\n#include \"vast\/table_slice.hpp\"\n#include \"vast\/to_events.hpp\"\n\n#include \"vast\/system\/archive.hpp\"\n#include \"vast\/system\/atoms.hpp\"\n#include \"vast\/system\/exporter.hpp\"\n\n#include \"vast\/detail\/assert.hpp\"\n\nusing namespace std::chrono;\nusing namespace std::string_literals;\nusing namespace caf;\n\nnamespace vast {\nnamespace system {\n\nnamespace {\n\nvoid ship_results(stateful_actor<exporter_state>* self) {\n VAST_TRACE(\"\");\n if (self->state.results.empty() || self->state.stats.requested == 0) {\n return;\n }\n VAST_INFO(self, \"relays\", self->state.results.size(), \"events\");\n message msg;\n if (self->state.results.size() <= self->state.stats.requested) {\n self->state.stats.requested -= self->state.results.size();\n self->state.stats.shipped += self->state.results.size();\n msg = make_message(std::move(self->state.results));\n self->state.results = {};\n } else {\n std::vector<event> remainder;\n remainder.reserve(self->state.results.size() - self->state.stats.requested);\n auto begin = self->state.results.begin() + self->state.stats.requested;\n auto end = self->state.results.end();\n std::move(begin, end, std::back_inserter(remainder));\n self->state.results.resize(self->state.stats.requested);\n msg = make_message(std::move(self->state.results));\n self->state.results = std::move(remainder);\n self->state.stats.shipped += self->state.stats.requested;\n self->state.stats.requested = 0;\n }\n self->send(self->state.sink, msg);\n}\n\nvoid report_statistics(stateful_actor<exporter_state>* self) {\n timespan runtime = steady_clock::now() - self->state.start;\n self->state.stats.runtime = runtime;\n VAST_INFO(self, \"completed in\", runtime);\n self->send(self->state.sink, self->state.id, self->state.stats);\n if (self->state.accountant) {\n auto hits = rank(self->state.hits);\n auto processed = self->state.stats.processed;\n auto shipped = self->state.stats.shipped;\n auto results = shipped + self->state.results.size();\n auto selectivity = double(results) \/ hits;\n self->send(self->state.accountant, \"exporter.hits\", hits);\n self->send(self->state.accountant, \"exporter.processed\", processed);\n self->send(self->state.accountant, \"exporter.results\", results);\n self->send(self->state.accountant, \"exporter.shipped\", shipped);\n self->send(self->state.accountant, \"exporter.selectivity\", selectivity);\n self->send(self->state.accountant, \"exporter.runtime\", runtime);\n }\n}\n\nvoid shutdown(stateful_actor<exporter_state>* self, caf::error err) {\n VAST_DEBUG(self, \"initiates shutdown with error\", self->system().render(err));\n self->send_exit(self, std::move(err));\n}\n\nvoid shutdown(stateful_actor<exporter_state>* self) {\n if (rank(self->state.unprocessed) > 0 || !self->state.results.empty()\n || has_continuous_option(self->state.options))\n return;\n VAST_DEBUG(self, \"initiates shutdown\");\n self->send_exit(self, exit_reason::normal);\n}\n\nvoid request_more_hits(stateful_actor<exporter_state>* self) {\n if (!has_historical_option(self->state.options))\n return;\n auto waiting_for_hits =\n self->state.stats.received == self->state.stats.scheduled;\n auto need_more_results = self->state.stats.requested > 0;\n auto have_no_inflight_requests = any<1>(self->state.unprocessed);\n \/\/ If we're (1) no longer waiting for index hits, (2) still need more\n \/\/ results, and (3) have no inflight requests to the archive, we ask\n \/\/ the index for more hits.\n if (!waiting_for_hits && need_more_results && have_no_inflight_requests) {\n auto remaining = self->state.stats.expected - self->state.stats.received;\n VAST_ASSERT(remaining > 0);\n \/\/ TODO: Figure out right number of partitions to ask for. For now, we\n \/\/ bound the number by an arbitrary constant.\n auto n = std::min(remaining, size_t{2});\n VAST_DEBUG(self, \"asks index to process\", n, \"more partitions\");\n self->send(self->state.index, self->state.id, n);\n }\n}\n\n} \/\/ namespace <anonymous>\n\nbehavior exporter(stateful_actor<exporter_state>* self, expression expr,\n query_options options) {\n auto eu = self->system().dummy_execution_unit();\n self->state.sink = actor_pool::make(eu, actor_pool::broadcast());\n if (auto a = self->system().registry().get(accountant_atom::value))\n self->state.accountant = actor_cast<accountant_type>(a);\n self->state.options = options;\n if (has_continuous_option(options))\n VAST_DEBUG(self, \"has continuous query option\");\n self->set_exit_handler(\n [=](const exit_msg& msg) {\n VAST_DEBUG(self, \"received exit from\", msg.source, \"with reason:\", msg.reason);\n self->send(self->state.sink, sys_atom::value, delete_atom::value);\n self->send_exit(self->state.sink, msg.reason);\n self->quit(msg.reason);\n if (msg.reason != exit_reason::kill)\n report_statistics(self);\n }\n );\n self->set_down_handler(\n [=](const down_msg& msg) {\n VAST_DEBUG(self, \"received DOWN from\", msg.source);\n if (has_continuous_option(self->state.options)\n && (msg.source == self->state.archive\n || msg.source == self->state.index))\n report_statistics(self);\n }\n );\n auto handle_batch = [=](std::vector<event>& candidates) {\n VAST_DEBUG(self, \"got batch of\", candidates.size(), \"events\");\n \/\/ Events can arrive in any order: sort them by ID first. Otherwise, we\n \/\/ can't compute the bitmap mask as easily.\n std::sort(candidates.begin(), candidates.end(),\n [](auto& x, auto& y) { return x.id() < y.id(); });\n bitmap mask;\n auto sender = self->current_sender();\n for (auto& candidate : candidates) {\n auto& checker = self->state.checkers[candidate.type()];\n \/\/ Construct a candidate checker if we don't have one for this type.\n if (caf::holds_alternative<caf::none_t>(checker)) {\n auto x = tailor(expr, candidate.type());\n if (!x) {\n VAST_ERROR(self, \"failed to tailor expression:\",\n self->system().render(x.error()));\n ship_results(self);\n self->send_exit(self, exit_reason::normal);\n return;\n }\n checker = std::move(*x);\n VAST_DEBUG(self, \"tailored AST to\", candidate.type() << ':', checker);\n }\n \/\/ Append ID to our bitmap mask.\n if (sender == self->state.archive) {\n mask.append_bits(false, candidate.id() - mask.size());\n mask.append_bit(true);\n }\n \/\/ Perform candidate check and keep event as result on success.\n if (caf::visit(event_evaluator{candidate}, checker))\n self->state.results.push_back(std::move(candidate));\n else\n VAST_DEBUG(self, \"ignores false positive:\", candidate);\n }\n self->state.stats.processed += candidates.size();\n if (sender == self->state.archive)\n self->state.unprocessed -= mask;\n ship_results(self);\n request_more_hits(self);\n if (self->state.stats.received == self->state.stats.expected)\n shutdown(self);\n };\n return {\n [=](ids& hits) {\n timespan runtime = steady_clock::now() - self->state.start;\n self->state.stats.runtime = runtime;\n auto count = rank(hits);\n if (self->state.accountant) {\n if (self->state.hits.empty())\n self->send(self->state.accountant, \"exporter.hits.first\", runtime);\n self->send(self->state.accountant, \"exporter.hits.arrived\", runtime);\n self->send(self->state.accountant, \"exporter.hits.count\", count);\n }\n VAST_DEBUG(self, \"got\", count, \"index hits\",\n (count == 0 ? \"\" : (\"in [\"s + to_string(select(hits, 1)) + ','\n + to_string(select(hits, -1) + 1) + ')')));\n if (count > 0) {\n self->state.hits |= hits;\n self->state.unprocessed |= hits;\n VAST_DEBUG(self, \"forwards hits to archive\");\n \/\/ FIXME: restrict according to configured limit.\n self->send(self->state.archive, std::move(hits));\n }\n \/\/ Figure out if we're done.\n ++self->state.stats.received;\n self->send(self->state.sink, self->state.id, self->state.stats);\n if (self->state.stats.received < self->state.stats.expected) {\n VAST_DEBUG(self, \"received\", self->state.stats.received << '\/'\n << self->state.stats.expected, \"ID sets\");\n request_more_hits(self);\n } else {\n VAST_DEBUG(self, \"received all\", self->state.stats.expected,\n \"ID set(s) in\", runtime);\n if (self->state.accountant)\n self->send(self->state.accountant, \"exporter.hits.runtime\", runtime);\n shutdown(self);\n }\n },\n [=](std::vector<event>& candidates) {\n handle_batch(candidates);\n },\n [=](extract_atom) {\n if (self->state.stats.requested == max_events) {\n VAST_WARNING(self, \"ignores extract request, already getting all\");\n return;\n }\n self->state.stats.requested = max_events;\n ship_results(self);\n request_more_hits(self);\n },\n [=](extract_atom, uint64_t requested) {\n if (self->state.stats.requested == max_events) {\n VAST_WARNING(self, \"ignores extract request, already getting all\");\n return;\n }\n auto n = std::min(max_events - requested, requested);\n self->state.stats.requested += n;\n VAST_DEBUG(self, \"got request to extract\", n, \"new events in addition to\",\n self->state.stats.requested, \"pending results\");\n ship_results(self);\n request_more_hits(self);\n },\n [=](const archive_type& archive) {\n VAST_DEBUG(self, \"registers archive\", archive);\n self->state.archive = archive;\n if (has_continuous_option(self->state.options))\n self->monitor(archive);\n },\n [=](index_atom, const actor& index) {\n VAST_DEBUG(self, \"registers index\", index);\n self->state.index = index;\n if (has_continuous_option(self->state.options))\n self->monitor(index);\n },\n [=](sink_atom, const actor& sink) {\n VAST_DEBUG(self, \"registers sink\", sink);\n self->send(self->state.sink, sys_atom::value, put_atom::value, sink);\n self->monitor(self->state.sink);\n },\n [=](importer_atom, const std::vector<actor>& importers) {\n \/\/ Register for events at running IMPORTERs.\n if (has_continuous_option(self->state.options))\n for (auto& x : importers)\n self->send(x, exporter_atom::value, self);\n },\n [=](run_atom) {\n VAST_INFO(self, \"executes query\", expr);\n self->state.start = steady_clock::now();\n if (!has_historical_option(self->state.options))\n return;\n self->request(self->state.index, infinite, expr).then(\n [=](const uuid& lookup, size_t partitions, size_t scheduled) {\n VAST_DEBUG(self, \"got lookup handle\", lookup << \", scheduled\",\n scheduled << '\/' << partitions, \"partitions\");\n self->state.id = lookup;\n if (partitions > 0) {\n self->state.stats.expected = partitions;\n self->state.stats.scheduled = scheduled;\n } else {\n shutdown(self);\n }\n },\n [=](const error& e) {\n shutdown(self, e);\n }\n );\n },\n [=](caf::stream<const_table_slice_handle> in) {\n return self->make_sink(\n in,\n [](caf::unit_t&) {\n \/\/ nop\n },\n [=](caf::unit_t&, const const_table_slice_handle& slice) {\n \/\/ TODO: portjto new table slice API\n auto candidates = to_events(*slice);\n handle_batch(candidates);\n },\n [=](caf::unit_t&, const error& err) {\n VAST_IGNORE_UNUSED(err);\n VAST_ERROR(self, \"got error during streaming: \", err);\n }\n );\n },\n };\n}\n\n} \/\/ namespace system\n} \/\/ namespace vast\n<|endoftext|>"} {"text":"<commit_before>#include \"stdafx.h\"\n#include \"buffer.h\"\n#include \"pipeline.h\"\n#include \"dimensions.h\"\n#include \"vulkanapp.h\"\n#include \"input_state.h\"\n\nstatic PFN_vkCreateDebugReportCallbackEXT pfnCreateDebugReportCallbackEXT = nullptr;\nstatic PFN_vkDestroyDebugReportCallbackEXT pfnDestroyDebugReportCallbackEXT = nullptr;\n\nstatic VKAPI_ATTR VkBool32 VKAPI_CALL debug_report_callback(\n VkDebugReportFlagsEXT flags,\n VkDebugReportObjectTypeEXT objectType,\n uint64_t object,\n size_t location,\n int32_t messageCode,\n const char* pLayerPrefix,\n const char* pMessage,\n void* pUserData)\n{\n fprintf(stderr, \"%s: %s\\n\", pLayerPrefix, pMessage);\n return false;\n}\n\nstatic VkDebugReportCallbackEXT create_debug_report_callback(VkInstance vulkan)\n{\n pfnCreateDebugReportCallbackEXT = reinterpret_cast<PFN_vkCreateDebugReportCallbackEXT>(\n vkGetInstanceProcAddr(vulkan, \"vkCreateDebugReportCallbackEXT\")\n );\n pfnDestroyDebugReportCallbackEXT = reinterpret_cast<PFN_vkDestroyDebugReportCallbackEXT>(\n vkGetInstanceProcAddr(vulkan, \"vkDestroyDebugReportCallbackEXT\")\n );\n\n#if _DEBUG\n VkDebugReportCallbackCreateInfoEXT info = {};\n info.sType = VK_STRUCTURE_TYPE_DEBUG_REPORT_CREATE_INFO_EXT;\n info.flags =\n VK_DEBUG_REPORT_ERROR_BIT_EXT |\n VK_DEBUG_REPORT_WARNING_BIT_EXT |\n VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT;\n info.pfnCallback = &debug_report_callback;\n\n VkDebugReportCallbackEXT callback;\n auto error = pfnCreateDebugReportCallbackEXT(vulkan, &info, nullptr, &callback);\n assert(!error);\n return callback;\n#else\n return nullptr;\n#endif\n}\n\nstatic void error_callback(int error, const char* description)\n{\n throw std::runtime_error(description);\n}\n\nvk::Instance create_instance()\n{\n#if _DEBUG\n const auto layerCount = 1;\n const char* layerNames[layerCount] = {\"VK_LAYER_LUNARG_standard_validation\"};\n#else\n const auto layerCount = 0;\n const char** layerNames = nullptr;\n#endif\n\n const auto extensionCount = 3;\n const char* extensionNames[extensionCount] = {\n VK_EXT_DEBUG_REPORT_EXTENSION_NAME,\n VK_KHR_SURFACE_EXTENSION_NAME,\n VK_KHR_WIN32_SURFACE_EXTENSION_NAME,\n };\n\n return vk::createInstance(\n vk::InstanceCreateInfo()\n .setEnabledLayerCount(layerCount)\n .setPpEnabledLayerNames(layerNames)\n .setEnabledExtensionCount(extensionCount)\n .setPpEnabledExtensionNames(extensionNames)\n );\n}\n\nstatic vk::PhysicalDevice get_physical_device(vk::Instance vulkan)\n{\n auto devices = vulkan.enumeratePhysicalDevices();\n assert(devices.size() == 1);\n\n auto props = devices[0].getProperties();\n std::printf(\"Using physical device: %s\\n\", props.deviceName);\n return devices[0];\n}\n\nstatic vk::Device create_device(vk::PhysicalDevice physical_device)\n{\n auto props = physical_device.getQueueFamilyProperties();\n assert((props[0].queueFlags & vk::QueueFlagBits::eGraphics) == vk::QueueFlagBits::eGraphics);\n\n float priorities[] = {0.f};\n auto queueInfo = vk::DeviceQueueCreateInfo()\n .setQueueCount(1)\n .setPQueuePriorities(priorities);\n\n#if _DEBUG\n const auto layerCount = 1;\n const char* layerNames[layerCount] = {\"VK_LAYER_LUNARG_standard_validation\"};\n#else\n const auto layerCount = 0;\n const char** layerNames = nullptr;\n#endif\n\n const auto extensionCount = 1;\n const char* extensionNames[extensionCount] = {VK_KHR_SWAPCHAIN_EXTENSION_NAME};\n\n auto features = vk::PhysicalDeviceFeatures()\n .setMultiDrawIndirect(true)\n .setDrawIndirectFirstInstance(true)\n .setShaderClipDistance(true)\n .setShaderCullDistance(true);\n\n return physical_device.createDevice(\n vk::DeviceCreateInfo()\n .setQueueCreateInfoCount(1)\n .setPQueueCreateInfos(&queueInfo)\n .setEnabledLayerCount(layerCount)\n .setPpEnabledLayerNames(layerNames)\n .setEnabledExtensionCount(1)\n .setPpEnabledExtensionNames(extensionNames)\n .setPEnabledFeatures(&features)\n );\n}\n\nstatic void initialize_imgui()\n{\n auto& io = ImGui::GetIO();\n io.DisplaySize = ImVec2(float(WIDTH), float(HEIGHT));\n io.KeyMap[ImGuiKey_Tab] = GLFW_KEY_TAB;\n io.KeyMap[ImGuiKey_LeftArrow] = GLFW_KEY_LEFT;\n io.KeyMap[ImGuiKey_RightArrow] = GLFW_KEY_RIGHT;\n io.KeyMap[ImGuiKey_UpArrow] = GLFW_KEY_UP;\n io.KeyMap[ImGuiKey_DownArrow] = GLFW_KEY_DOWN;\n io.KeyMap[ImGuiKey_PageUp] = GLFW_KEY_PAGE_UP;\n io.KeyMap[ImGuiKey_PageDown] = GLFW_KEY_PAGE_DOWN;\n io.KeyMap[ImGuiKey_Home] = GLFW_KEY_HOME;\n io.KeyMap[ImGuiKey_End] = GLFW_KEY_END;\n io.KeyMap[ImGuiKey_Delete] = GLFW_KEY_DELETE;\n io.KeyMap[ImGuiKey_Backspace] = GLFW_KEY_BACKSPACE;\n io.KeyMap[ImGuiKey_Enter] = GLFW_KEY_ENTER;\n io.KeyMap[ImGuiKey_Escape] = GLFW_KEY_ESCAPE;\n io.KeyMap[ImGuiKey_A] = GLFW_KEY_A;\n io.KeyMap[ImGuiKey_C] = GLFW_KEY_C;\n io.KeyMap[ImGuiKey_V] = GLFW_KEY_V;\n io.KeyMap[ImGuiKey_X] = GLFW_KEY_X;\n io.KeyMap[ImGuiKey_Y] = GLFW_KEY_Y;\n io.KeyMap[ImGuiKey_Z] = GLFW_KEY_Z;\n \/\/ TODO clipboard, ime\n}\n\nint main(int argc, char** argv)\n{\n auto instance = create_instance();\n auto callback = create_debug_report_callback(instance);\n auto physical_device = get_physical_device(instance);\n auto device = create_device(physical_device);\n auto mdl = read_model(\n physical_device,\n device,\n \"C:\\\\Users\\\\Christiaan\\\\OneDrive\\\\Documenten\\\\Master\\\\Advanced computer graphics\\\\Facial Point Rendering\\\\Test models\\\\Armadillo.ply\"\n );\n\n initialize_imgui();\n\n auto success = glfwInit();\n assert(success);\n\n glfwSetErrorCallback(error_callback);\n\n glfwWindowHint(GLFW_CLIENT_API, GLFW_NO_API);\n glfwWindowHint(GLFW_RESIZABLE, GLFW_FALSE);\n auto window = glfwCreateWindow(WIDTH, HEIGHT, \"Vulkan renderer\", nullptr, nullptr);\n assert(window);\n\n VkSurfaceKHR surface;\n auto result = glfwCreateWindowSurface(instance, window, nullptr, &surface);\n assert(result == VK_SUCCESS);\n\n input_state input(window);\n auto app = vulkanapp(physical_device, device, surface, mdl);\n while (!glfwWindowShouldClose(window))\n {\n input.update();\n app.update(device, input);\n }\n app.destroy(device);\n\n instance.destroySurfaceKHR(surface);\n\n glfwTerminate();\n\n device.destroy();\n#if _DEBUG\n pfnDestroyDebugReportCallbackEXT(instance, callback, nullptr);\n#endif\n instance.destroy();\n\n ImGui::Shutdown();\n\n return EXIT_SUCCESS;\n}\n<commit_msg>Allow picking a file<commit_after>#include \"stdafx.h\"\n#include \"buffer.h\"\n#include \"pipeline.h\"\n#include \"dimensions.h\"\n#include \"vulkanapp.h\"\n#include \"input_state.h\"\n\nstatic PFN_vkCreateDebugReportCallbackEXT pfnCreateDebugReportCallbackEXT = nullptr;\nstatic PFN_vkDestroyDebugReportCallbackEXT pfnDestroyDebugReportCallbackEXT = nullptr;\n\nstatic VKAPI_ATTR VkBool32 VKAPI_CALL debug_report_callback(\n VkDebugReportFlagsEXT flags,\n VkDebugReportObjectTypeEXT objectType,\n uint64_t object,\n size_t location,\n int32_t messageCode,\n const char* pLayerPrefix,\n const char* pMessage,\n void* pUserData)\n{\n fprintf(stderr, \"%s: %s\\n\", pLayerPrefix, pMessage);\n return false;\n}\n\nstatic VkDebugReportCallbackEXT create_debug_report_callback(VkInstance vulkan)\n{\n pfnCreateDebugReportCallbackEXT = reinterpret_cast<PFN_vkCreateDebugReportCallbackEXT>(\n vkGetInstanceProcAddr(vulkan, \"vkCreateDebugReportCallbackEXT\")\n );\n pfnDestroyDebugReportCallbackEXT = reinterpret_cast<PFN_vkDestroyDebugReportCallbackEXT>(\n vkGetInstanceProcAddr(vulkan, \"vkDestroyDebugReportCallbackEXT\")\n );\n\n#if _DEBUG\n VkDebugReportCallbackCreateInfoEXT info = {};\n info.sType = VK_STRUCTURE_TYPE_DEBUG_REPORT_CREATE_INFO_EXT;\n info.flags =\n VK_DEBUG_REPORT_ERROR_BIT_EXT |\n VK_DEBUG_REPORT_WARNING_BIT_EXT |\n VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT;\n info.pfnCallback = &debug_report_callback;\n\n VkDebugReportCallbackEXT callback;\n auto error = pfnCreateDebugReportCallbackEXT(vulkan, &info, nullptr, &callback);\n assert(!error);\n return callback;\n#else\n return nullptr;\n#endif\n}\n\nstatic void error_callback(int error, const char* description)\n{\n throw std::runtime_error(description);\n}\n\nvk::Instance create_instance()\n{\n#if _DEBUG\n const auto layerCount = 1;\n const char* layerNames[layerCount] = {\"VK_LAYER_LUNARG_standard_validation\"};\n#else\n const auto layerCount = 0;\n const char** layerNames = nullptr;\n#endif\n\n const auto extensionCount = 3;\n const char* extensionNames[extensionCount] = {\n VK_EXT_DEBUG_REPORT_EXTENSION_NAME,\n VK_KHR_SURFACE_EXTENSION_NAME,\n VK_KHR_WIN32_SURFACE_EXTENSION_NAME,\n };\n\n return vk::createInstance(\n vk::InstanceCreateInfo()\n .setEnabledLayerCount(layerCount)\n .setPpEnabledLayerNames(layerNames)\n .setEnabledExtensionCount(extensionCount)\n .setPpEnabledExtensionNames(extensionNames)\n );\n}\n\nstatic vk::PhysicalDevice get_physical_device(vk::Instance vulkan)\n{\n auto devices = vulkan.enumeratePhysicalDevices();\n assert(devices.size() == 1);\n\n auto props = devices[0].getProperties();\n std::printf(\"Using physical device: %s\\n\", props.deviceName);\n return devices[0];\n}\n\nstatic vk::Device create_device(vk::PhysicalDevice physical_device)\n{\n auto props = physical_device.getQueueFamilyProperties();\n assert((props[0].queueFlags & vk::QueueFlagBits::eGraphics) == vk::QueueFlagBits::eGraphics);\n\n float priorities[] = {0.f};\n auto queueInfo = vk::DeviceQueueCreateInfo()\n .setQueueCount(1)\n .setPQueuePriorities(priorities);\n\n#if _DEBUG\n const auto layerCount = 1;\n const char* layerNames[layerCount] = {\"VK_LAYER_LUNARG_standard_validation\"};\n#else\n const auto layerCount = 0;\n const char** layerNames = nullptr;\n#endif\n\n const auto extensionCount = 1;\n const char* extensionNames[extensionCount] = {VK_KHR_SWAPCHAIN_EXTENSION_NAME};\n\n auto features = vk::PhysicalDeviceFeatures()\n .setMultiDrawIndirect(true)\n .setDrawIndirectFirstInstance(true)\n .setShaderClipDistance(true)\n .setShaderCullDistance(true);\n\n return physical_device.createDevice(\n vk::DeviceCreateInfo()\n .setQueueCreateInfoCount(1)\n .setPQueueCreateInfos(&queueInfo)\n .setEnabledLayerCount(layerCount)\n .setPpEnabledLayerNames(layerNames)\n .setEnabledExtensionCount(1)\n .setPpEnabledExtensionNames(extensionNames)\n .setPEnabledFeatures(&features)\n );\n}\n\nstatic void initialize_imgui()\n{\n auto& io = ImGui::GetIO();\n io.DisplaySize = ImVec2(float(WIDTH), float(HEIGHT));\n io.KeyMap[ImGuiKey_Tab] = GLFW_KEY_TAB;\n io.KeyMap[ImGuiKey_LeftArrow] = GLFW_KEY_LEFT;\n io.KeyMap[ImGuiKey_RightArrow] = GLFW_KEY_RIGHT;\n io.KeyMap[ImGuiKey_UpArrow] = GLFW_KEY_UP;\n io.KeyMap[ImGuiKey_DownArrow] = GLFW_KEY_DOWN;\n io.KeyMap[ImGuiKey_PageUp] = GLFW_KEY_PAGE_UP;\n io.KeyMap[ImGuiKey_PageDown] = GLFW_KEY_PAGE_DOWN;\n io.KeyMap[ImGuiKey_Home] = GLFW_KEY_HOME;\n io.KeyMap[ImGuiKey_End] = GLFW_KEY_END;\n io.KeyMap[ImGuiKey_Delete] = GLFW_KEY_DELETE;\n io.KeyMap[ImGuiKey_Backspace] = GLFW_KEY_BACKSPACE;\n io.KeyMap[ImGuiKey_Enter] = GLFW_KEY_ENTER;\n io.KeyMap[ImGuiKey_Escape] = GLFW_KEY_ESCAPE;\n io.KeyMap[ImGuiKey_A] = GLFW_KEY_A;\n io.KeyMap[ImGuiKey_C] = GLFW_KEY_C;\n io.KeyMap[ImGuiKey_V] = GLFW_KEY_V;\n io.KeyMap[ImGuiKey_X] = GLFW_KEY_X;\n io.KeyMap[ImGuiKey_Y] = GLFW_KEY_Y;\n io.KeyMap[ImGuiKey_Z] = GLFW_KEY_Z;\n \/\/ TODO clipboard, ime\n}\n\nint main(int argc, char** argv)\n{\n auto pattern = \"*.ply\";\n auto model_path = tinyfd_openFileDialog(\"Open 3D model\", nullptr, 1, &pattern, nullptr, 0);\n if (!model_path)\n {\n return EXIT_FAILURE;\n }\n\n auto instance = create_instance();\n auto callback = create_debug_report_callback(instance);\n auto physical_device = get_physical_device(instance);\n auto device = create_device(physical_device);\n auto mdl = read_model(physical_device, device, model_path);\n\n initialize_imgui();\n\n auto success = glfwInit();\n assert(success);\n\n glfwSetErrorCallback(error_callback);\n\n glfwWindowHint(GLFW_CLIENT_API, GLFW_NO_API);\n glfwWindowHint(GLFW_RESIZABLE, GLFW_FALSE);\n auto window = glfwCreateWindow(WIDTH, HEIGHT, \"Vulkan renderer\", nullptr, nullptr);\n assert(window);\n\n VkSurfaceKHR surface;\n auto result = glfwCreateWindowSurface(instance, window, nullptr, &surface);\n assert(result == VK_SUCCESS);\n\n input_state input(window);\n auto app = vulkanapp(physical_device, device, surface, mdl);\n while (!glfwWindowShouldClose(window))\n {\n input.update();\n app.update(device, input);\n }\n app.destroy(device);\n\n instance.destroySurfaceKHR(surface);\n\n glfwTerminate();\n\n device.destroy();\n#if _DEBUG\n pfnDestroyDebugReportCallbackEXT(instance, callback, nullptr);\n#endif\n instance.destroy();\n\n ImGui::Shutdown();\n\n return EXIT_SUCCESS;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ kmfilterrulesedit.cpp\n\/\/ Author: Marc Mutz <Marc@Mutz.com>\n\/\/ This code is under GPL\n\n#include \"kmsearchpatternedit.h\"\n\/\/#include \"kmfilter.h\"\n\/\/#include \"kmfilterdlg.h\"\n\n#include <klocale.h>\n#include <kdebug.h>\n#include <kbuttonbox.h>\n\n#include <qstring.h>\n#include <qlayout.h>\n#include <qradiobutton.h>\n#include <qpushbutton.h>\n#include <qlineedit.h>\n#include <qcombobox.h>\n#include <qbuttongroup.h>\n\n#include <assert.h>\n\nstatic QStringList sFilterFieldList, sFilterFuncList;\n\n\/\/=============================================================================\n\/\/\n\/\/ class KMSearchRuleWidget\n\/\/\n\/\/=============================================================================\n\nKMSearchRuleWidget::KMSearchRuleWidget(QWidget *parent, KMSearchRule *aRule, const char *name)\n : QHBox(parent,name)\n{\n kdDebug() << \"KMSearchRuleWidget::KMSearchRuleWidget\" << endl;\n initLists(); \/\/ sFilter{Func,Field}List are local to KMSearchRuleWidget\n initWidget();\n \n if ( aRule )\n setRule(aRule);\n else\n reset();\n}\n\nvoid KMSearchRuleWidget::initWidget()\n{\n kdDebug() << \"KMSearchRuleWidget::initWidget\" << endl;\n \/\/ QHBoxLayout *l = new QHBoxLayout(this,0,4); \/\/ with margin 0 and spacing 4\n \n setSpacing(4);\n\n mRuleField = new QComboBox( true, this, \"mRuleField\" );\n mRuleFunc = new QComboBox( false, this, \"mRuleFunc\" );\n mRuleValue = new QLineEdit( this, \"mRuleValue\" );\n \n mRuleFunc->insertStringList(sFilterFuncList);\n mRuleFunc->adjustSize();\n\n mRuleField->insertStringList(sFilterFieldList);\n mRuleField->adjustSize();\n \n connect( mRuleField, SIGNAL(textChanged(const QString &)),\n\t this, SIGNAL(fieldChanged(const QString &)) );\n connect( mRuleValue, SIGNAL(textChanged(const QString &)),\n\t this, SIGNAL(contentsChanged(const QString &)) );\n}\n\nvoid KMSearchRuleWidget::setRule(KMSearchRule *aRule)\n{\n assert ( aRule );\n\n \/\/--------------set the field\n int i = indexOfRuleField( aRule->field() );\n \n kdDebug() << aRule->function() << endl;\n\n if ( i<0 ) { \/\/ not found -> user defined field\n mRuleField->changeItem( aRule->field(), 0 );\n i=0;\n } else \/\/ found in the list of predefined fields\n mRuleField->changeItem( \" \", 0 );\n \n mRuleField->setCurrentItem( i );\n\n kdDebug() << aRule->function() << endl;\n\n \/\/--------------set function and contents\n mRuleFunc->setCurrentItem( (int)aRule->function() );\n mRuleValue->setText( aRule->contents() );\n}\n\nKMSearchRule* KMSearchRuleWidget::rule() const\n{\n KMSearchRule *r = new KMSearchRule;\n\n r->init( ruleFieldToEnglish( mRuleField->currentText() ),\n\t (KMSearchRule::Function)mRuleFunc->currentItem(),\n\t mRuleValue->text() );\n\n return r;\n}\n\nvoid KMSearchRuleWidget::reset()\n{\n mRuleField->changeItem( \" \", 0 );\n mRuleField->setCurrentItem( 0 );\n\n mRuleFunc->setCurrentItem( 0 );\n\n mRuleValue->clear();\n}\n\nQString KMSearchRuleWidget::ruleFieldToEnglish(const QString & i18nVal) const\n{\n if (i18nVal == i18n(\"<To or Cc>\")) return QString(\"<To or Cc>\");\n if (i18nVal == i18n(\"<body>\")) return QString(\"<body>\");\n if (i18nVal == i18n(\"<message>\")) return QString(\"<message>\");\n if (i18nVal == i18n(\"<any header>\")) return QString(\"<any header>\");\n return i18nVal;\n}\n\nint KMSearchRuleWidget::indexOfRuleField(const QString aName) const\n{\n int i;\n\n if ( aName.isEmpty() ) return -1;\n\n for (i=sFilterFieldList.count()-1; i>=0; i--) {\n if (*(sFilterFieldList.at(i))==i18n(aName)) break;\n }\n return i;\n}\n\nvoid KMSearchRuleWidget::initLists() const\n{\n \/\/---------- initialize list of filter operators\n if ( sFilterFuncList.isEmpty() )\n {\n \/\/ also see KMSearchRule::matches() and KMSearchRule::Function\n \/\/ you change the following strings!\n sFilterFuncList.append(i18n(\"equals\"));\n sFilterFuncList.append(i18n(\"doesn't equal\"));\n sFilterFuncList.append(i18n(\"contains\"));\n sFilterFuncList.append(i18n(\"doesn't contain\"));\n sFilterFuncList.append(i18n(\"matches regular expr.\"));\n sFilterFuncList.append(i18n(\"doesn't match reg. expr.\"));\n }\n\n \/\/---------- initialize list of filter operators\n if ( sFilterFieldList.isEmpty() )\n {\n sFilterFieldList.append(\" \");\n \/\/ also see KMSearchRule::matches() and ruleFieldToEnglish() if\n \/\/ you change the following i18n-ized strings!\n sFilterFieldList.append(i18n(\"<message>\"));\n sFilterFieldList.append(i18n(\"<body>\"));\n sFilterFieldList.append(i18n(\"<any header>\"));\n sFilterFieldList.append(i18n(\"<To or Cc>\"));\n \/\/ these others only represent meassage headers and you can add to\n \/\/ them as you like\n sFilterFieldList.append(\"Subject\");\n sFilterFieldList.append(\"From\");\n sFilterFieldList.append(\"To\");\n sFilterFieldList.append(\"Cc\");\n sFilterFieldList.append(\"Reply-To\");\n sFilterFieldList.append(\"Organization\");\n sFilterFieldList.append(\"Resent-From\");\n sFilterFieldList.append(\"X-Loop\");\n }\n}\n\n\/\/=============================================================================\n\/\/\n\/\/ class KMFilterActionWidgetLister (the filter action editor)\n\/\/\n\/\/=============================================================================\n\nKMSearchRuleWidgetLister::KMSearchRuleWidgetLister( QWidget *parent, const char* name )\n : KWidgetLister( 1, FILTER_MAX_RULES, parent, name )\n{\n mRuleList = 0;\n}\n\nKMSearchRuleWidgetLister::~KMSearchRuleWidgetLister()\n{\n}\n\nvoid KMSearchRuleWidgetLister::setRuleList( QList<KMSearchRule> *aList )\n{\n assert ( aList );\n\n if ( mRuleList )\n regenerateRuleListFromWidgets();\n\n mRuleList = aList;\n\n if ( mWidgetList.first() ) \/\/ move this below next 'if'?\n mWidgetList.first()->blockSignals(TRUE);\n\n if ( aList->count() == 0 ) {\n slotClear();\n mWidgetList.first()->blockSignals(FALSE);\n return;\n }\n\n int superfluousItems = (int)mRuleList->count() - mMaxWidgets ;\n if ( superfluousItems > 0 ) {\n kdDebug() << \"KMSearchRuleWidgetLister: Clipping rule list to \"\n\t << mMaxWidgets << \" items!\" << endl;\n\n for ( ; superfluousItems ; superfluousItems-- )\n mRuleList->removeLast();\n }\n\n \/\/ set the right number of widgets\n setNumberOfShownWidgetsTo( QMAX((int)mRuleList->count(),mMinWidgets) );\n\n \/\/ load the actions into the widgets\n QListIterator<KMSearchRule> rIt( *mRuleList );\n QListIterator<QWidget> wIt( mWidgetList );\n for ( rIt.toFirst(), wIt.toFirst() ;\n\trIt.current() && wIt.current() ; ++rIt, ++wIt ) {\n ((KMSearchRuleWidget*)(*wIt))->setRule( (*rIt) );\n }\n\n assert( mWidgetList.first() );\n mWidgetList.first()->blockSignals(FALSE);\n}\n\nvoid KMSearchRuleWidgetLister::reset()\n{\n if ( mRuleList )\n regenerateRuleListFromWidgets();\n\n mRuleList = 0;\n slotClear();\n}\n\nQWidget* KMSearchRuleWidgetLister::createWidget( QWidget *parent )\n{\n return new KMSearchRuleWidget(parent);\n}\n\nvoid KMSearchRuleWidgetLister::clearWidget( QWidget *aWidget )\n{\n if ( aWidget )\n ((KMSearchRuleWidget*)aWidget)->reset();\n}\n\nvoid KMSearchRuleWidgetLister::regenerateRuleListFromWidgets()\n{\n if ( !mRuleList ) return;\n\n mRuleList->clear();\n\n QListIterator<QWidget> it( mWidgetList );\n for ( it.toFirst() ; it.current() ; ++it ) {\n KMSearchRule *r = ((KMSearchRuleWidget*)(*it))->rule();\n if ( r )\n mRuleList->append( r );\n }\n}\n\n\n\n\n\/\/=============================================================================\n\/\/\n\/\/ class KMSearchPatternEdit\n\/\/\n\/\/=============================================================================\n\nKMSearchPatternEdit::KMSearchPatternEdit(QWidget *parent, const char *name )\n : QGroupBox( 1\/*columns*\/, Horizontal, parent, name )\n{\n setTitle( i18n(\"Search Criteria\") );\n initLayout();\n}\n\nKMSearchPatternEdit::KMSearchPatternEdit(const QString & title, QWidget *parent, const char *name )\n : QGroupBox( 1\/*column*\/, Horizontal, title, parent, name )\n{\n initLayout();\n}\n\nKMSearchPatternEdit::~KMSearchPatternEdit()\n{\n}\n\nvoid KMSearchPatternEdit::initLayout()\n{\n \/\/------------the radio buttons\t\n mAllRBtn = new QRadioButton( i18n(\"Match all of the following\"), this, \"mAllRBtn\" );\n mAnyRBtn = new QRadioButton( i18n(\"Match any of the following\"), this, \"mAnyRBtn\" );\n \n mAllRBtn->setChecked(TRUE);\n mAnyRBtn->setChecked(FALSE);\n\n QButtonGroup *bg = new QButtonGroup( this );\n bg->hide();\n bg->insert( mAllRBtn, (int)KMSearchPattern::OpAnd );\n bg->insert( mAnyRBtn, (int)KMSearchPattern::OpOr );\n\n \/\/------------the list of KMSearchRuleWidget's\n mRuleLister = new KMSearchRuleWidgetLister( this );\n mRuleLister->slotClear();\n\n \/\/------------connect a few signals\n connect( bg, SIGNAL(clicked(int)),\n\t this, SLOT(slotRadioClicked(int)) );\n\n KMSearchRuleWidget *srw = (KMSearchRuleWidget*)mRuleLister->mWidgetList.first();\n if ( srw ) {\n connect( srw, SIGNAL(fieldChanged(const QString &)),\n\t this, SLOT(slotAutoNameHack()) );\n connect( srw, SIGNAL(contentsChanged(const QString &)),\n\t this, SLOT(slotAutoNameHack()) );\n } else\n kdDebug() << \"KMSearchPatternEdit: no first KMSearchRuleWidget, though slotClear() has been called!\" << endl;\n}\n\nvoid KMSearchPatternEdit::setSearchPattern( KMSearchPattern *aPattern )\n{\n assert( aPattern );\n\n blockSignals(TRUE);\n\n mRuleLister->setRuleList( aPattern );\n \n mPattern = aPattern;\n\n if ( mPattern->op() == KMSearchPattern::OpOr )\n mAnyRBtn->setChecked(TRUE);\n else\n mAllRBtn->setChecked(TRUE);\n\n setEnabled( TRUE );\n\n blockSignals(FALSE);\n}\n\nvoid KMSearchPatternEdit::reset()\n{\n mRuleLister->reset();\n mAllRBtn->setChecked( TRUE );\n setEnabled( FALSE );\n}\n\nvoid KMSearchPatternEdit::slotRadioClicked(int aIdx)\n{\n if ( mPattern ) \n mPattern->setOp( (KMSearchPattern::Operator)aIdx );\n}\n\nvoid KMSearchPatternEdit::slotAutoNameHack()\n{\n mRuleLister->regenerateRuleListFromWidgets();\n emit maybeNameChanged();\n}\n#include \"kmsearchpatternedit.moc\"\n<commit_msg>Increase the minimum number of search rules again to 2 and fix a missing variable initialization.<commit_after>\/\/ kmfilterrulesedit.cpp\n\/\/ Author: Marc Mutz <Marc@Mutz.com>\n\/\/ This code is under GPL\n\n#include \"kmsearchpatternedit.h\"\n\/\/#include \"kmfilter.h\"\n\/\/#include \"kmfilterdlg.h\"\n\n#include <klocale.h>\n#include <kdebug.h>\n#include <kbuttonbox.h>\n\n#include <qstring.h>\n#include <qlayout.h>\n#include <qradiobutton.h>\n#include <qpushbutton.h>\n#include <qlineedit.h>\n#include <qcombobox.h>\n#include <qbuttongroup.h>\n\n#include <assert.h>\n\nstatic QStringList sFilterFieldList, sFilterFuncList;\n\n\/\/=============================================================================\n\/\/\n\/\/ class KMSearchRuleWidget\n\/\/\n\/\/=============================================================================\n\nKMSearchRuleWidget::KMSearchRuleWidget(QWidget *parent, KMSearchRule *aRule, const char *name)\n : QHBox(parent,name)\n{\n kdDebug() << \"KMSearchRuleWidget::KMSearchRuleWidget\" << endl;\n initLists(); \/\/ sFilter{Func,Field}List are local to KMSearchRuleWidget\n initWidget();\n \n if ( aRule )\n setRule(aRule);\n else\n reset();\n}\n\nvoid KMSearchRuleWidget::initWidget()\n{\n kdDebug() << \"KMSearchRuleWidget::initWidget\" << endl;\n \/\/ QHBoxLayout *l = new QHBoxLayout(this,0,4); \/\/ with margin 0 and spacing 4\n \n setSpacing(4);\n\n mRuleField = new QComboBox( true, this, \"mRuleField\" );\n mRuleFunc = new QComboBox( false, this, \"mRuleFunc\" );\n mRuleValue = new QLineEdit( this, \"mRuleValue\" );\n \n mRuleFunc->insertStringList(sFilterFuncList);\n mRuleFunc->adjustSize();\n\n mRuleField->insertStringList(sFilterFieldList);\n mRuleField->adjustSize();\n \n connect( mRuleField, SIGNAL(textChanged(const QString &)),\n\t this, SIGNAL(fieldChanged(const QString &)) );\n connect( mRuleValue, SIGNAL(textChanged(const QString &)),\n\t this, SIGNAL(contentsChanged(const QString &)) );\n}\n\nvoid KMSearchRuleWidget::setRule(KMSearchRule *aRule)\n{\n assert ( aRule );\n\n \/\/--------------set the field\n int i = indexOfRuleField( aRule->field() );\n \n kdDebug() << aRule->function() << endl;\n\n if ( i<0 ) { \/\/ not found -> user defined field\n mRuleField->changeItem( aRule->field(), 0 );\n i=0;\n } else \/\/ found in the list of predefined fields\n mRuleField->changeItem( \" \", 0 );\n \n mRuleField->setCurrentItem( i );\n\n kdDebug() << aRule->function() << endl;\n\n \/\/--------------set function and contents\n mRuleFunc->setCurrentItem( (int)aRule->function() );\n mRuleValue->setText( aRule->contents() );\n}\n\nKMSearchRule* KMSearchRuleWidget::rule() const\n{\n KMSearchRule *r = new KMSearchRule;\n\n r->init( ruleFieldToEnglish( mRuleField->currentText() ),\n\t (KMSearchRule::Function)mRuleFunc->currentItem(),\n\t mRuleValue->text() );\n\n return r;\n}\n\nvoid KMSearchRuleWidget::reset()\n{\n mRuleField->changeItem( \" \", 0 );\n mRuleField->setCurrentItem( 0 );\n\n mRuleFunc->setCurrentItem( 0 );\n\n mRuleValue->clear();\n}\n\nQString KMSearchRuleWidget::ruleFieldToEnglish(const QString & i18nVal) const\n{\n if (i18nVal == i18n(\"<To or Cc>\")) return QString(\"<To or Cc>\");\n if (i18nVal == i18n(\"<body>\")) return QString(\"<body>\");\n if (i18nVal == i18n(\"<message>\")) return QString(\"<message>\");\n if (i18nVal == i18n(\"<any header>\")) return QString(\"<any header>\");\n return i18nVal;\n}\n\nint KMSearchRuleWidget::indexOfRuleField(const QString aName) const\n{\n int i;\n\n if ( aName.isEmpty() ) return -1;\n\n for (i=sFilterFieldList.count()-1; i>=0; i--) {\n if (*(sFilterFieldList.at(i))==i18n(aName)) break;\n }\n return i;\n}\n\nvoid KMSearchRuleWidget::initLists() const\n{\n \/\/---------- initialize list of filter operators\n if ( sFilterFuncList.isEmpty() )\n {\n \/\/ also see KMSearchRule::matches() and KMSearchRule::Function\n \/\/ you change the following strings!\n sFilterFuncList.append(i18n(\"equals\"));\n sFilterFuncList.append(i18n(\"doesn't equal\"));\n sFilterFuncList.append(i18n(\"contains\"));\n sFilterFuncList.append(i18n(\"doesn't contain\"));\n sFilterFuncList.append(i18n(\"matches regular expr.\"));\n sFilterFuncList.append(i18n(\"doesn't match reg. expr.\"));\n }\n\n \/\/---------- initialize list of filter operators\n if ( sFilterFieldList.isEmpty() )\n {\n sFilterFieldList.append(\" \");\n \/\/ also see KMSearchRule::matches() and ruleFieldToEnglish() if\n \/\/ you change the following i18n-ized strings!\n sFilterFieldList.append(i18n(\"<message>\"));\n sFilterFieldList.append(i18n(\"<body>\"));\n sFilterFieldList.append(i18n(\"<any header>\"));\n sFilterFieldList.append(i18n(\"<To or Cc>\"));\n \/\/ these others only represent meassage headers and you can add to\n \/\/ them as you like\n sFilterFieldList.append(\"Subject\");\n sFilterFieldList.append(\"From\");\n sFilterFieldList.append(\"To\");\n sFilterFieldList.append(\"Cc\");\n sFilterFieldList.append(\"Reply-To\");\n sFilterFieldList.append(\"Organization\");\n sFilterFieldList.append(\"Resent-From\");\n sFilterFieldList.append(\"X-Loop\");\n }\n}\n\n\/\/=============================================================================\n\/\/\n\/\/ class KMFilterActionWidgetLister (the filter action editor)\n\/\/\n\/\/=============================================================================\n\nKMSearchRuleWidgetLister::KMSearchRuleWidgetLister( QWidget *parent, const char* name )\n : KWidgetLister( 2, FILTER_MAX_RULES, parent, name )\n{\n mRuleList = 0;\n}\n\nKMSearchRuleWidgetLister::~KMSearchRuleWidgetLister()\n{\n}\n\nvoid KMSearchRuleWidgetLister::setRuleList( QList<KMSearchRule> *aList )\n{\n assert ( aList );\n\n if ( mRuleList )\n regenerateRuleListFromWidgets();\n\n mRuleList = aList;\n\n if ( mWidgetList.first() ) \/\/ move this below next 'if'?\n mWidgetList.first()->blockSignals(TRUE);\n\n if ( aList->count() == 0 ) {\n slotClear();\n mWidgetList.first()->blockSignals(FALSE);\n return;\n }\n\n int superfluousItems = (int)mRuleList->count() - mMaxWidgets ;\n if ( superfluousItems > 0 ) {\n kdDebug() << \"KMSearchRuleWidgetLister: Clipping rule list to \"\n\t << mMaxWidgets << \" items!\" << endl;\n\n for ( ; superfluousItems ; superfluousItems-- )\n mRuleList->removeLast();\n }\n\n \/\/ set the right number of widgets\n setNumberOfShownWidgetsTo( QMAX((int)mRuleList->count(),mMinWidgets) );\n\n \/\/ load the actions into the widgets\n QListIterator<KMSearchRule> rIt( *mRuleList );\n QListIterator<QWidget> wIt( mWidgetList );\n for ( rIt.toFirst(), wIt.toFirst() ;\n\trIt.current() && wIt.current() ; ++rIt, ++wIt ) {\n ((KMSearchRuleWidget*)(*wIt))->setRule( (*rIt) );\n }\n for ( ; wIt.current() ; ++wIt )\n ((KMSearchRuleWidget*)(*wIt))->reset();\n\n assert( mWidgetList.first() );\n mWidgetList.first()->blockSignals(FALSE);\n}\n\nvoid KMSearchRuleWidgetLister::reset()\n{\n if ( mRuleList )\n regenerateRuleListFromWidgets();\n\n mRuleList = 0;\n slotClear();\n}\n\nQWidget* KMSearchRuleWidgetLister::createWidget( QWidget *parent )\n{\n return new KMSearchRuleWidget(parent);\n}\n\nvoid KMSearchRuleWidgetLister::clearWidget( QWidget *aWidget )\n{\n if ( aWidget )\n ((KMSearchRuleWidget*)aWidget)->reset();\n}\n\nvoid KMSearchRuleWidgetLister::regenerateRuleListFromWidgets()\n{\n if ( !mRuleList ) return;\n\n mRuleList->clear();\n\n QListIterator<QWidget> it( mWidgetList );\n for ( it.toFirst() ; it.current() ; ++it ) {\n KMSearchRule *r = ((KMSearchRuleWidget*)(*it))->rule();\n if ( r )\n mRuleList->append( r );\n }\n}\n\n\n\n\n\/\/=============================================================================\n\/\/\n\/\/ class KMSearchPatternEdit\n\/\/\n\/\/=============================================================================\n\nKMSearchPatternEdit::KMSearchPatternEdit(QWidget *parent, const char *name )\n : QGroupBox( 1\/*columns*\/, Horizontal, parent, name )\n{\n setTitle( i18n(\"Search Criteria\") );\n initLayout();\n}\n\nKMSearchPatternEdit::KMSearchPatternEdit(const QString & title, QWidget *parent, const char *name )\n : QGroupBox( 1\/*column*\/, Horizontal, title, parent, name )\n{\n initLayout();\n}\n\nKMSearchPatternEdit::~KMSearchPatternEdit()\n{\n}\n\nvoid KMSearchPatternEdit::initLayout()\n{\n \/\/------------the radio buttons\t\n mAllRBtn = new QRadioButton( i18n(\"Match all of the following\"), this, \"mAllRBtn\" );\n mAnyRBtn = new QRadioButton( i18n(\"Match any of the following\"), this, \"mAnyRBtn\" );\n \n mAllRBtn->setChecked(TRUE);\n mAnyRBtn->setChecked(FALSE);\n\n QButtonGroup *bg = new QButtonGroup( this );\n bg->hide();\n bg->insert( mAllRBtn, (int)KMSearchPattern::OpAnd );\n bg->insert( mAnyRBtn, (int)KMSearchPattern::OpOr );\n\n \/\/------------the list of KMSearchRuleWidget's\n mRuleLister = new KMSearchRuleWidgetLister( this );\n mRuleLister->slotClear();\n\n \/\/------------connect a few signals\n connect( bg, SIGNAL(clicked(int)),\n\t this, SLOT(slotRadioClicked(int)) );\n\n KMSearchRuleWidget *srw = (KMSearchRuleWidget*)mRuleLister->mWidgetList.first();\n if ( srw ) {\n connect( srw, SIGNAL(fieldChanged(const QString &)),\n\t this, SLOT(slotAutoNameHack()) );\n connect( srw, SIGNAL(contentsChanged(const QString &)),\n\t this, SLOT(slotAutoNameHack()) );\n } else\n kdDebug() << \"KMSearchPatternEdit: no first KMSearchRuleWidget, though slotClear() has been called!\" << endl;\n}\n\nvoid KMSearchPatternEdit::setSearchPattern( KMSearchPattern *aPattern )\n{\n assert( aPattern );\n\n blockSignals(TRUE);\n\n mRuleLister->setRuleList( aPattern );\n \n mPattern = aPattern;\n\n if ( mPattern->op() == KMSearchPattern::OpOr )\n mAnyRBtn->setChecked(TRUE);\n else\n mAllRBtn->setChecked(TRUE);\n\n setEnabled( TRUE );\n\n blockSignals(FALSE);\n}\n\nvoid KMSearchPatternEdit::reset()\n{\n mRuleLister->reset();\n mAllRBtn->setChecked( TRUE );\n setEnabled( FALSE );\n}\n\nvoid KMSearchPatternEdit::slotRadioClicked(int aIdx)\n{\n if ( mPattern ) \n mPattern->setOp( (KMSearchPattern::Operator)aIdx );\n}\n\nvoid KMSearchPatternEdit::slotAutoNameHack()\n{\n mRuleLister->regenerateRuleListFromWidgets();\n emit maybeNameChanged();\n}\n#include \"kmsearchpatternedit.moc\"\n<|endoftext|>"} {"text":"<commit_before>\/******************************************************************************\n * _ _____ __________ *\n * | | \/ \/ _ | \/ __\/_ __\/ Visibility *\n * | |\/ \/ __ |_\\ \\ \/ \/ Across *\n * |___\/_\/ |_\/___\/ \/_\/ Space and Time *\n * *\n * This file is part of VAST. It is subject to the license terms in the *\n * LICENSE file found in the top-level directory of this distribution and at *\n * http:\/\/vast.io\/license. No part of VAST, including this file, may be *\n * copied, modified, propagated, or distributed except according to the terms *\n * contained in the LICENSE file. *\n ******************************************************************************\/\n\n#include <caf\/all.hpp>\n\n#include \"vast\/event.hpp\"\n#include \"vast\/logger.hpp\"\n#include \"vast\/concept\/printable\/std\/chrono.hpp\"\n#include \"vast\/concept\/printable\/vast\/event.hpp\"\n#include \"vast\/concept\/printable\/vast\/expression.hpp\"\n#include \"vast\/concept\/printable\/vast\/uuid.hpp\"\n#include \"vast\/detail\/assert.hpp\"\n#include \"vast\/expression_visitors.hpp\"\n\n#include \"vast\/system\/archive.hpp\"\n#include \"vast\/system\/atoms.hpp\"\n#include \"vast\/system\/exporter.hpp\"\n\nusing namespace std::chrono;\nusing namespace std::string_literals;\nusing namespace caf;\n\nnamespace vast {\nnamespace system {\n\nnamespace {\n\nvoid ship_results(stateful_actor<exporter_state>* self) {\n if (self->state.results.empty() || self->state.stats.requested == 0)\n return;\n VAST_DEBUG(self, \"relays\", self->state.results.size(), \"events\");\n message msg;\n if (self->state.results.size() <= self->state.stats.requested) {\n self->state.stats.requested -= self->state.results.size();\n self->state.stats.shipped += self->state.results.size();\n msg = make_message(std::move(self->state.results));\n } else {\n std::vector<event> remainder;\n remainder.reserve(self->state.results.size() - self->state.stats.requested);\n auto begin = self->state.results.begin() + self->state.stats.requested;\n auto end = self->state.results.end();\n std::move(begin, end, std::back_inserter(remainder));\n self->state.results.resize(self->state.stats.requested);\n msg = make_message(std::move(self->state.results));\n self->state.results = std::move(remainder);\n self->state.stats.shipped += self->state.stats.requested;\n self->state.stats.requested = 0;\n }\n self->send(self->state.sink, msg);\n}\n\nvoid report_statistics(stateful_actor<exporter_state>* self) {\n timespan runtime = steady_clock::now() - self->state.start;\n self->state.stats.runtime = runtime;\n VAST_DEBUG(self, \"completed in\", runtime);\n self->send(self->state.sink, self->state.id, self->state.stats);\n if (self->state.accountant) {\n auto hits = rank(self->state.hits);\n auto processed = self->state.stats.processed;\n auto shipped = self->state.stats.shipped;\n auto results = shipped + self->state.results.size();\n auto selectivity = double(results) \/ hits;\n self->send(self->state.accountant, \"exporter.hits\", hits);\n self->send(self->state.accountant, \"exporter.processed\", processed);\n self->send(self->state.accountant, \"exporter.results\", results);\n self->send(self->state.accountant, \"exporter.shipped\", shipped);\n self->send(self->state.accountant, \"exporter.selectivity\", selectivity);\n self->send(self->state.accountant, \"exporter.runtime\", runtime);\n }\n}\n\nvoid shutdown(stateful_actor<exporter_state>* self) {\n if (rank(self->state.unprocessed) > 0 || !self->state.results.empty()\n || has_continuous_option(self->state.options))\n return;\n report_statistics(self);\n self->send_exit(self, exit_reason::normal);\n}\n\nvoid request_more_hits(stateful_actor<exporter_state>* self) {\n if (!has_historical_option(self->state.options))\n return;\n auto waiting_for_hits =\n self->state.stats.received == self->state.stats.scheduled;\n auto need_more_results = self->state.stats.requested > 0;\n auto have_no_inflight_requests = any<1>(self->state.unprocessed);\n \/\/ If we're (1) no longer waiting for index hits, (2) still need more\n \/\/ results, and (3) have no inflight requests to the archive, we ask\n \/\/ the index for more hits.\n if (waiting_for_hits && need_more_results && have_no_inflight_requests) {\n auto remaining = self->state.stats.expected - self->state.stats.received;\n \/\/ TODO: Figure out right amount of partitions to ask for.\n auto n = std::min(remaining, size_t{2});\n VAST_DEBUG(self, \"asks index to process\", n, \"more partitions\");\n self->send(self->state.index, self->state.id, n);\n }\n}\n\n} \/\/ namespace <anonymous>\n\nbehavior exporter(stateful_actor<exporter_state>* self, expression expr,\n query_options options) {\n auto eu = self->system().dummy_execution_unit();\n self->state.sink = actor_pool::make(eu, actor_pool::broadcast());\n if (auto a = self->system().registry().get(accountant_atom::value))\n self->state.accountant = actor_cast<accountant_type>(a);\n self->state.options = options;\n if (has_continuous_option(options))\n VAST_DEBUG(self, \"has continuous query option\");\n self->set_exit_handler(\n [=](const exit_msg& msg) {\n self->send(self->state.sink, sys_atom::value, delete_atom::value);\n self->send_exit(self->state.sink, msg.reason);\n self->quit(msg.reason);\n if (msg.reason != exit_reason::kill)\n report_statistics(self);\n }\n );\n self->set_down_handler(\n [=](const down_msg& msg) {\n VAST_DEBUG(self, \"received DOWN from\", msg.source);\n if (has_continuous_option(self->state.options)\n && (msg.source == self->state.archive\n || msg.source == self->state.index))\n report_statistics(self);\n }\n );\n return {\n [=](ids& hits) {\n timespan runtime = steady_clock::now() - self->state.start;\n self->state.stats.runtime = runtime;\n auto count = rank(hits);\n if (self->state.accountant) {\n if (self->state.hits.empty())\n self->send(self->state.accountant, \"exporter.hits.first\", runtime);\n self->send(self->state.accountant, \"exporter.hits.arrived\", runtime);\n self->send(self->state.accountant, \"exporter.hits.count\", count);\n }\n VAST_DEBUG(self, \"got\", count, \"index hits\",\n (count == 0 ? \"\" : (\"in [\"s + to_string(select(hits, 1)) + ','\n + to_string(select(hits, -1) + 1) + ')')));\n if (count > 0) {\n self->state.hits |= hits;\n self->state.unprocessed |= hits;\n VAST_DEBUG(self, \"forwards hits to archive\");\n \/\/ FIXME: restrict according to configured limit.\n self->send(self->state.archive, std::move(hits));\n }\n \/\/ Figure out if we're done.\n ++self->state.stats.received;\n self->send(self->state.sink, self->state.id, self->state.stats);\n if (self->state.stats.received < self->state.stats.expected) {\n VAST_DEBUG(self, \"received\", self->state.stats.received << '\/'\n << self->state.stats.expected, \"ID sets\");\n request_more_hits(self);\n } else {\n VAST_DEBUG(self, \"received all\", self->state.stats.expected,\n \"ID set(s) in\", runtime);\n if (self->state.accountant)\n self->send(self->state.accountant, \"exporter.hits.runtime\", runtime);\n shutdown(self);\n }\n },\n [=](std::vector<event>& candidates) {\n VAST_DEBUG(self, \"got batch of\", candidates.size(), \"events\");\n bitmap mask;\n auto sender = self->current_sender();\n for (auto& candidate : candidates) {\n auto& checker = self->state.checkers[candidate.type()];\n \/\/ Construct a candidate checker if we don't have one for this type.\n if (is<none>(checker)) {\n auto x = tailor(expr, candidate.type());\n if (!x) {\n VAST_ERROR(self, \"failed to tailor expression:\",\n self->system().render(x.error()));\n ship_results(self);\n self->send_exit(self, exit_reason::normal);\n return;\n }\n checker = std::move(*x);\n VAST_DEBUG(self, \"tailored AST to\", candidate.type() << ':', checker);\n }\n \/\/ Perform candidate check and keep event as result on success.\n if (visit(event_evaluator{candidate}, checker))\n self->state.results.push_back(std::move(candidate));\n else\n VAST_DEBUG(self, \"ignores false positive:\", candidate);\n if (sender == self->state.archive) {\n mask.append_bits(false, candidate.id() - mask.size());\n mask.append_bit(true);\n }\n }\n self->state.stats.processed += candidates.size();\n if (sender == self->state.archive)\n self->state.unprocessed -= mask;\n ship_results(self);\n request_more_hits(self);\n if (self->state.stats.received == self->state.stats.expected)\n shutdown(self);\n },\n [=](extract_atom) {\n if (self->state.stats.requested == max_events) {\n VAST_WARNING(self, \"ignores extract request, already getting all\");\n return;\n }\n self->state.stats.requested = max_events;\n ship_results(self);\n request_more_hits(self);\n },\n [=](extract_atom, uint64_t requested) {\n if (self->state.stats.requested == max_events) {\n VAST_WARNING(self, \"ignores extract request, already getting all\");\n return;\n }\n auto n = std::min(max_events - requested, requested);\n self->state.stats.requested += n;\n VAST_DEBUG(self, \"got request to extract\", n, \"new events in addition to\",\n self->state.stats.requested, \"pending results\");\n ship_results(self);\n request_more_hits(self);\n },\n [=](const archive_type& archive) {\n VAST_DEBUG(self, \"registers archive\", archive);\n self->state.archive = archive;\n if (has_continuous_option(self->state.options))\n self->monitor(archive);\n },\n [=](index_atom, const actor& index) {\n VAST_DEBUG(self, \"registers index\", index);\n self->state.index = index;\n if (has_continuous_option(self->state.options))\n self->monitor(index);\n },\n [=](sink_atom, const actor& sink) {\n VAST_DEBUG(self, \"registers index\", sink);\n self->send(self->state.sink, sys_atom::value, put_atom::value, sink);\n self->monitor(self->state.sink);\n },\n [=](importer_atom, const std::vector<actor>& importers) {\n \/\/ Register for events at running IMPORTERs.\n if (has_continuous_option(self->state.options))\n for (auto& x : importers)\n self->send(x, exporter_atom::value, self);\n },\n [=](run_atom) {\n VAST_INFO(self, \"executes query\", expr);\n self->state.start = steady_clock::now();\n if (!has_historical_option(self->state.options))\n return;\n self->request(self->state.index, infinite, expr).then(\n [=](const uuid& lookup, size_t partitions, size_t scheduled) {\n VAST_DEBUG(self, \"got lookup handle\", lookup << \", scheduled\",\n scheduled << '\/' << partitions, \"partitions\");\n self->state.id = lookup;\n if (partitions > 0) {\n self->state.stats.expected = partitions;\n self->state.stats.scheduled = scheduled;\n } else {\n shutdown(self);\n }\n },\n [=](const error& e) {\n VAST_IGNORE_UNUSED(e);\n VAST_DEBUG(self, \"failed to lookup query at index:\",\n self->system().render(e));\n }\n );\n },\n };\n}\n\n} \/\/ namespace system\n} \/\/ namespace vast\n<commit_msg>Avoid duplicate reporting of statistics<commit_after>\/******************************************************************************\n * _ _____ __________ *\n * | | \/ \/ _ | \/ __\/_ __\/ Visibility *\n * | |\/ \/ __ |_\\ \\ \/ \/ Across *\n * |___\/_\/ |_\/___\/ \/_\/ Space and Time *\n * *\n * This file is part of VAST. It is subject to the license terms in the *\n * LICENSE file found in the top-level directory of this distribution and at *\n * http:\/\/vast.io\/license. No part of VAST, including this file, may be *\n * copied, modified, propagated, or distributed except according to the terms *\n * contained in the LICENSE file. *\n ******************************************************************************\/\n\n#include <caf\/all.hpp>\n\n#include \"vast\/event.hpp\"\n#include \"vast\/logger.hpp\"\n#include \"vast\/concept\/printable\/std\/chrono.hpp\"\n#include \"vast\/concept\/printable\/vast\/event.hpp\"\n#include \"vast\/concept\/printable\/vast\/expression.hpp\"\n#include \"vast\/concept\/printable\/vast\/uuid.hpp\"\n#include \"vast\/detail\/assert.hpp\"\n#include \"vast\/expression_visitors.hpp\"\n\n#include \"vast\/system\/archive.hpp\"\n#include \"vast\/system\/atoms.hpp\"\n#include \"vast\/system\/exporter.hpp\"\n\nusing namespace std::chrono;\nusing namespace std::string_literals;\nusing namespace caf;\n\nnamespace vast {\nnamespace system {\n\nnamespace {\n\nvoid ship_results(stateful_actor<exporter_state>* self) {\n if (self->state.results.empty() || self->state.stats.requested == 0)\n return;\n VAST_DEBUG(self, \"relays\", self->state.results.size(), \"events\");\n message msg;\n if (self->state.results.size() <= self->state.stats.requested) {\n self->state.stats.requested -= self->state.results.size();\n self->state.stats.shipped += self->state.results.size();\n msg = make_message(std::move(self->state.results));\n } else {\n std::vector<event> remainder;\n remainder.reserve(self->state.results.size() - self->state.stats.requested);\n auto begin = self->state.results.begin() + self->state.stats.requested;\n auto end = self->state.results.end();\n std::move(begin, end, std::back_inserter(remainder));\n self->state.results.resize(self->state.stats.requested);\n msg = make_message(std::move(self->state.results));\n self->state.results = std::move(remainder);\n self->state.stats.shipped += self->state.stats.requested;\n self->state.stats.requested = 0;\n }\n self->send(self->state.sink, msg);\n}\n\nvoid report_statistics(stateful_actor<exporter_state>* self) {\n timespan runtime = steady_clock::now() - self->state.start;\n self->state.stats.runtime = runtime;\n VAST_DEBUG(self, \"completed in\", runtime);\n self->send(self->state.sink, self->state.id, self->state.stats);\n if (self->state.accountant) {\n auto hits = rank(self->state.hits);\n auto processed = self->state.stats.processed;\n auto shipped = self->state.stats.shipped;\n auto results = shipped + self->state.results.size();\n auto selectivity = double(results) \/ hits;\n self->send(self->state.accountant, \"exporter.hits\", hits);\n self->send(self->state.accountant, \"exporter.processed\", processed);\n self->send(self->state.accountant, \"exporter.results\", results);\n self->send(self->state.accountant, \"exporter.shipped\", shipped);\n self->send(self->state.accountant, \"exporter.selectivity\", selectivity);\n self->send(self->state.accountant, \"exporter.runtime\", runtime);\n }\n}\n\nvoid shutdown(stateful_actor<exporter_state>* self) {\n if (rank(self->state.unprocessed) > 0 || !self->state.results.empty()\n || has_continuous_option(self->state.options))\n return;\n self->send_exit(self, exit_reason::normal);\n}\n\nvoid request_more_hits(stateful_actor<exporter_state>* self) {\n if (!has_historical_option(self->state.options))\n return;\n auto waiting_for_hits =\n self->state.stats.received == self->state.stats.scheduled;\n auto need_more_results = self->state.stats.requested > 0;\n auto have_no_inflight_requests = any<1>(self->state.unprocessed);\n \/\/ If we're (1) no longer waiting for index hits, (2) still need more\n \/\/ results, and (3) have no inflight requests to the archive, we ask\n \/\/ the index for more hits.\n if (waiting_for_hits && need_more_results && have_no_inflight_requests) {\n auto remaining = self->state.stats.expected - self->state.stats.received;\n \/\/ TODO: Figure out right amount of partitions to ask for.\n auto n = std::min(remaining, size_t{2});\n VAST_DEBUG(self, \"asks index to process\", n, \"more partitions\");\n self->send(self->state.index, self->state.id, n);\n }\n}\n\n} \/\/ namespace <anonymous>\n\nbehavior exporter(stateful_actor<exporter_state>* self, expression expr,\n query_options options) {\n auto eu = self->system().dummy_execution_unit();\n self->state.sink = actor_pool::make(eu, actor_pool::broadcast());\n if (auto a = self->system().registry().get(accountant_atom::value))\n self->state.accountant = actor_cast<accountant_type>(a);\n self->state.options = options;\n if (has_continuous_option(options))\n VAST_DEBUG(self, \"has continuous query option\");\n self->set_exit_handler(\n [=](const exit_msg& msg) {\n self->send(self->state.sink, sys_atom::value, delete_atom::value);\n self->send_exit(self->state.sink, msg.reason);\n self->quit(msg.reason);\n if (msg.reason != exit_reason::kill)\n report_statistics(self);\n }\n );\n self->set_down_handler(\n [=](const down_msg& msg) {\n VAST_DEBUG(self, \"received DOWN from\", msg.source);\n if (has_continuous_option(self->state.options)\n && (msg.source == self->state.archive\n || msg.source == self->state.index))\n report_statistics(self);\n }\n );\n return {\n [=](ids& hits) {\n timespan runtime = steady_clock::now() - self->state.start;\n self->state.stats.runtime = runtime;\n auto count = rank(hits);\n if (self->state.accountant) {\n if (self->state.hits.empty())\n self->send(self->state.accountant, \"exporter.hits.first\", runtime);\n self->send(self->state.accountant, \"exporter.hits.arrived\", runtime);\n self->send(self->state.accountant, \"exporter.hits.count\", count);\n }\n VAST_DEBUG(self, \"got\", count, \"index hits\",\n (count == 0 ? \"\" : (\"in [\"s + to_string(select(hits, 1)) + ','\n + to_string(select(hits, -1) + 1) + ')')));\n if (count > 0) {\n self->state.hits |= hits;\n self->state.unprocessed |= hits;\n VAST_DEBUG(self, \"forwards hits to archive\");\n \/\/ FIXME: restrict according to configured limit.\n self->send(self->state.archive, std::move(hits));\n }\n \/\/ Figure out if we're done.\n ++self->state.stats.received;\n self->send(self->state.sink, self->state.id, self->state.stats);\n if (self->state.stats.received < self->state.stats.expected) {\n VAST_DEBUG(self, \"received\", self->state.stats.received << '\/'\n << self->state.stats.expected, \"ID sets\");\n request_more_hits(self);\n } else {\n VAST_DEBUG(self, \"received all\", self->state.stats.expected,\n \"ID set(s) in\", runtime);\n if (self->state.accountant)\n self->send(self->state.accountant, \"exporter.hits.runtime\", runtime);\n shutdown(self);\n }\n },\n [=](std::vector<event>& candidates) {\n VAST_DEBUG(self, \"got batch of\", candidates.size(), \"events\");\n bitmap mask;\n auto sender = self->current_sender();\n for (auto& candidate : candidates) {\n auto& checker = self->state.checkers[candidate.type()];\n \/\/ Construct a candidate checker if we don't have one for this type.\n if (is<none>(checker)) {\n auto x = tailor(expr, candidate.type());\n if (!x) {\n VAST_ERROR(self, \"failed to tailor expression:\",\n self->system().render(x.error()));\n ship_results(self);\n self->send_exit(self, exit_reason::normal);\n return;\n }\n checker = std::move(*x);\n VAST_DEBUG(self, \"tailored AST to\", candidate.type() << ':', checker);\n }\n \/\/ Perform candidate check and keep event as result on success.\n if (visit(event_evaluator{candidate}, checker))\n self->state.results.push_back(std::move(candidate));\n else\n VAST_DEBUG(self, \"ignores false positive:\", candidate);\n if (sender == self->state.archive) {\n mask.append_bits(false, candidate.id() - mask.size());\n mask.append_bit(true);\n }\n }\n self->state.stats.processed += candidates.size();\n if (sender == self->state.archive)\n self->state.unprocessed -= mask;\n ship_results(self);\n request_more_hits(self);\n if (self->state.stats.received == self->state.stats.expected)\n shutdown(self);\n },\n [=](extract_atom) {\n if (self->state.stats.requested == max_events) {\n VAST_WARNING(self, \"ignores extract request, already getting all\");\n return;\n }\n self->state.stats.requested = max_events;\n ship_results(self);\n request_more_hits(self);\n },\n [=](extract_atom, uint64_t requested) {\n if (self->state.stats.requested == max_events) {\n VAST_WARNING(self, \"ignores extract request, already getting all\");\n return;\n }\n auto n = std::min(max_events - requested, requested);\n self->state.stats.requested += n;\n VAST_DEBUG(self, \"got request to extract\", n, \"new events in addition to\",\n self->state.stats.requested, \"pending results\");\n ship_results(self);\n request_more_hits(self);\n },\n [=](const archive_type& archive) {\n VAST_DEBUG(self, \"registers archive\", archive);\n self->state.archive = archive;\n if (has_continuous_option(self->state.options))\n self->monitor(archive);\n },\n [=](index_atom, const actor& index) {\n VAST_DEBUG(self, \"registers index\", index);\n self->state.index = index;\n if (has_continuous_option(self->state.options))\n self->monitor(index);\n },\n [=](sink_atom, const actor& sink) {\n VAST_DEBUG(self, \"registers index\", sink);\n self->send(self->state.sink, sys_atom::value, put_atom::value, sink);\n self->monitor(self->state.sink);\n },\n [=](importer_atom, const std::vector<actor>& importers) {\n \/\/ Register for events at running IMPORTERs.\n if (has_continuous_option(self->state.options))\n for (auto& x : importers)\n self->send(x, exporter_atom::value, self);\n },\n [=](run_atom) {\n VAST_INFO(self, \"executes query\", expr);\n self->state.start = steady_clock::now();\n if (!has_historical_option(self->state.options))\n return;\n self->request(self->state.index, infinite, expr).then(\n [=](const uuid& lookup, size_t partitions, size_t scheduled) {\n VAST_DEBUG(self, \"got lookup handle\", lookup << \", scheduled\",\n scheduled << '\/' << partitions, \"partitions\");\n self->state.id = lookup;\n if (partitions > 0) {\n self->state.stats.expected = partitions;\n self->state.stats.scheduled = scheduled;\n } else {\n shutdown(self);\n }\n },\n [=](const error& e) {\n VAST_IGNORE_UNUSED(e);\n VAST_DEBUG(self, \"failed to lookup query at index:\",\n self->system().render(e));\n }\n );\n },\n };\n}\n\n} \/\/ namespace system\n} \/\/ namespace vast\n<|endoftext|>"} {"text":"<commit_before>#include \"lua_class.h\"\n#include \"..\/table\/table.h\"\n#include \"..\/util\/string_enum.h\"\n\nnamespace saki\n{\n\n\n\nbool isValidSuitStr(const std::string &s)\n{\n return s.size() == 1 && T34::isValidSuit(s[0]);\n}\n\nstd::string toLower(const char *s)\n{\n std::string res(s);\n std::for_each(res.begin(), res.end(), [](char &c) {\n c = static_cast<char>(std::tolower(c));\n });\n return res;\n}\n\nstd::pair<Mount::Exit, bool> parseMountExit(const std::string &s)\n{\n std::pair<Mount::Exit, bool> res;\n\n res.second = true;\n if (s == \"pii\")\n res.first = Mount::Exit::PII;\n else if (s == \"rinshan\")\n res.first = Mount::Exit::RINSHAN;\n else if (s == \"dorahyou\")\n res.first = Mount::Exit::DORAHYOU;\n else if (s == \"urahyou\")\n res.first = Mount::Exit::URAHYOU;\n else\n res.second = false;\n\n return res;\n}\n\ntemplate<typename Class, typename Ret, typename... Args>\nclass AsTable\n{\npublic:\n using Method = Ret (Class::*)(Args...) const;\n using Table = sol::as_table_t<sol::meta::unqualified_t<Ret>>;\n\n explicit AsTable(Method method)\n : mMethod(method)\n {\n }\n\n Table operator()(Class &thiz, Args... args)\n {\n return sol::as_table((thiz.*mMethod)(args...));\n }\n\nprivate:\n Method mMethod;\n};\n\nvoid setupLuaClasses(const sol::environment &env, LuaUserErrorHandler &error)\n{\n setupLuaTile(env, error);\n setupLuaWho(env);\n setupLuaMeld(env, error);\n setupLuaExist(env, error);\n setupLuaMount(env, error);\n setupLuaTileCount(env, error);\n setupLuaHand(env);\n setupLuaGame(env);\n}\n\nvoid setupLuaTile(sol::environment env, LuaUserErrorHandler &error)\n{\n env.new_usertype<T34>(\n \"T34\",\n sol::meta_function::construct, sol::factories(\n [&error](int ti) {\n if (ti < 0 || ti >= 34) {\n error.handleUserError(\"invalid T34 id\");\n return T34();\n }\n\n return T34(ti);\n },\n [&error](const std::string s) {\n static const std::array<std::string, 34> dict {\n \"1m\", \"2m\", \"3m\", \"4m\", \"5m\", \"6m\", \"7m\", \"8m\", \"9m\",\n \"1p\", \"2p\", \"3p\", \"4p\", \"5p\", \"6p\", \"7p\", \"8p\", \"9p\",\n \"1s\", \"2s\", \"3s\", \"4s\", \"5s\", \"6s\", \"7s\", \"8s\", \"9s\",\n \"1f\", \"2f\", \"3f\", \"4f\", \"1y\", \"2y\", \"3y\"\n };\n\n auto it = std::find(dict.begin(), dict.end(), s);\n if (it == dict.end()) {\n error.handleUserError(\"invalid T34 string\");\n return T34();\n }\n\n return T34(static_cast<int>(it - dict.begin()));\n }\n ),\n \"id34\", &T34::id34,\n \"suit\", [](T34 t) { return T34::charOf(t.suit()); },\n \"val\", &T34::val,\n \"str34\", &T34::str34,\n \"isz\", &T34::isZ,\n \"isnum\", &T34::isNum,\n \"isnum19\", &T34::isNum19,\n \"isyao\", &T34::isYao,\n \"isyakuhai\", &T34::isYakuhai,\n \"dora\", &T34::dora,\n \"indicator\", &T34::indicator,\n sol::meta_function::to_string, &T34::str34,\n sol::meta_function::equal_to, &T34::operator==,\n sol::meta_function::less_than, &T34::operator<,\n sol::meta_function::modulus, &T34::operator%,\n \"all\", sol::var(std::vector<T34>(tiles34::ALL34.begin(), tiles34::ALL34.end()))\n );\n\n env.new_usertype<T37>(\n \"T37\",\n sol::meta_function::construct, sol::factories(\n [&error](int ti) {\n if (ti < 0 || ti >= 34) {\n error.handleUserError(\"invalid T34 id\");\n return T37();\n }\n\n return T37(ti);\n },\n [&error](const std::string s) {\n if (!T37::isValidStr(s.c_str())) {\n error.handleUserError(\"invalid T37 suit\");\n return T37();\n }\n return T37(s.c_str());\n }\n ),\n \"isaka5\", &T37::isAka5,\n \"lookssame\", &T37::looksSame,\n \"str37\", &T37::str37,\n sol::meta_function::to_string, &T37::str37,\n sol::base_classes, sol::bases<T34>()\n );\n}\n\nvoid setupLuaWho(sol::environment env)\n{\n env.new_usertype<Who>(\n \"Who\",\n \"right\", &Who::right,\n \"cross\", &Who::cross,\n \"left\", &Who::left,\n \"bydice\", &Who::byDice,\n \"byturn\", &Who::byTurn,\n \"looksat\", &Who::looksAt,\n \"turnfrom\", &Who::turnFrom,\n \"index\", [](Who w) { return w.index() + 1; },\n sol::meta_function::to_string, [](Who w) { return w.index() + 1; },\n sol::meta_function::equal_to, &Who::operator==\n );\n}\n\nvoid setupLuaMeld(sol::environment env, LuaUserErrorHandler &error)\n{\n env.new_usertype<M37>(\n \"M37\",\n \"type\", [](const M37 &m) {\n return toLower(util::stringOf(m.type()));\n },\n \"has\", &M37::has,\n sol::meta_function::index, [&error](const M37 &m, int index) {\n int zeroIndex = index - 1;\n int size = static_cast<int>(m.tiles().size());\n if (zeroIndex < 0 || zeroIndex > size) {\n error.handleUserError(\"invalid meld index\");\n return T37();\n }\n\n return m[index];\n }\n );\n}\n\nvoid setupLuaExist(sol::environment env, LuaUserErrorHandler &error)\n{\n (void) error;\n env.new_usertype<Exist>(\n \"Exist\",\n \"incmk\", sol::overload(\n [](Exist &exist, T34 t, int delta) {\n exist.incMk(t, delta);\n },\n [](Exist &exist, const T37 &t, int delta) {\n exist.incMk(t, delta);\n }\n )\n );\n}\n\nvoid setupLuaMount(sol::environment env, LuaUserErrorHandler &error)\n{\n env.new_usertype<Mount>(\n \"Mount\",\n \"remainpii\", &Mount::remainPii,\n \"remainrinshan\", &Mount::remainRinshan,\n \"remaina\", sol::overload(\n [](Mount &mount, T34 t) {\n mount.remainA(t);\n },\n [](Mount &mount, const T37 &t) {\n mount.remainA(t);\n }\n ),\n \"getdrids\", AsTable(&Mount::getDrids),\n \"geturids\", AsTable(&Mount::getUrids),\n \"lighta\", sol::overload(\n [](Mount &mount, T34 t, int mk, bool rin) {\n mount.lightA(t, mk, rin);\n },\n [](Mount &mount, const T37 &t, int mk, bool rin) {\n mount.lightA(t, mk, rin);\n },\n [](Mount &mount, T34 t, int mk) {\n mount.lightA(t, mk);\n },\n [](Mount &mount, const T37 &t, int mk) {\n mount.lightA(t, mk);\n }\n ),\n \"lightb\", sol::overload(\n [](Mount &mount, T34 t, int mk, bool rin) {\n mount.lightB(t, mk, rin);\n },\n [](Mount &mount, const T37 &t, int mk, bool rin) {\n mount.lightB(t, mk, rin);\n },\n [](Mount &mount, T34 t, int mk) {\n mount.lightB(t, mk);\n },\n [](Mount &mount, const T37 &t, int mk) {\n mount.lightB(t, mk);\n }\n ),\n \"incmk\", sol::overload(\n [&error](Mount &mount, std::string exit, size_t pos, T34 t, int delta, bool bSpace) {\n auto [e, ok] = parseMountExit(exit);\n if (!ok) {\n error.handleUserError(\"invalid mount exit\");\n return;\n }\n mount.incMk(e, pos, t, delta, bSpace);\n },\n [&error](Mount &mount, std::string exit, size_t pos, const T37 &t, int delta, bool bSpace) {\n auto [e, ok] = parseMountExit(exit);\n if (!ok) {\n error.handleUserError(\"invalid mount exit\");\n return;\n }\n mount.incMk(e, pos, t, delta, bSpace);\n }\n ),\n \"loadb\", &Mount::loadB\n );\n}\n\nvoid setupLuaTileCount(sol::environment env, LuaUserErrorHandler &error)\n{\n env.new_usertype<TileCount>(\n \"Tilecount\",\n \"ct\", sol::overload(\n [](const TileCount &tc, T34 t) {\n return tc.ct(t);\n },\n [](const TileCount &tc, const T37 &t) {\n return tc.ct(t);\n },\n [&error](const TileCount &tc, std::string suit) {\n if (!isValidSuitStr(suit)) {\n error.handleUserError(\"invalid suit\");\n return 0;\n }\n\n return tc.ct(T34::suitOf(suit[0]));\n }\n )\n );\n}\n\nvoid setupLuaHand(sol::environment env)\n{\n env.new_usertype<Hand>(\n \"Hand\",\n \"closed\", &Hand::closed,\n \"ct\", &Hand::ct,\n \"ctaka5\", &Hand::ctAka5,\n \"ready\", &Hand::ready,\n \"step\", &Hand::step,\n \"step4\", &Hand::step4,\n \"step7\", &Hand::step7,\n \"step7gb\", &Hand::step7Gb,\n \"step13\", &Hand::step13,\n \"effa\", AsTable(&Hand::effA),\n \"effa4\", AsTable(&Hand::effA4),\n \"ismenzen\", &Hand::isMenzen,\n \"barks\", AsTable(&Hand::barks),\n \"canchii\", &Hand::canChii,\n \"canchiiasleft\", &Hand::canChiiAsLeft,\n \"canchiiasmiddle\", &Hand::canChiiAsMiddle,\n \"canchiiasright\", &Hand::canChiiAsRight,\n \"canpon\", &Hand::canPon,\n \"candaiminkan\", &Hand::canDaiminkan,\n sol::meta_function::modulus, sol::overload(\n [](const util::Stactor<T37, 5> &ids, const Hand &hand) {\n return ids % hand;\n },\n [](T34 indic, const Hand &hand) {\n return indic % hand;\n }\n )\n );\n}\n\nvoid setupLuaGame(sol::environment env)\n{\n env.new_usertype<Table>(\n \"Game\",\n \"gethand\", &Table::getHand,\n \"getround\", &Table::getRound,\n \"getextraround\", &Table::getExtraRound,\n \"getdealer\", &Table::getDealer,\n \"getselfwind\", &Table::getSelfWind,\n \"getroundwind\", &Table::getRoundWind,\n \"getriver\", AsTable(&Table::getRiver),\n \"riichiestablished\", &Table::riichiEstablished\n );\n}\n\nsol::table toLuaTable(sol::environment env, const TableEvent &event)\n{\n using TE = TableEvent;\n\n sol::table args = env.create();\n\n switch (event.type()) {\n case TE::Type::TABLE_STARTED:\n args[\"seed\"] = event.as<TE::TableStarted>().seed;\n break;\n case TE::Type::FIRST_DEALER_CHOSEN:\n args[\"who\"] = event.as<TE::FirstDealerChosen>().who;\n break;\n case TE::Type::ROUND_STARTED: {\n const auto &a = event.as<TE::RoundStarted>();\n args[\"round\"] = a.round;\n args[\"extraround\"] = a.extraRound;\n args[\"dealer\"] = a.dealer;\n args[\"alllast\"] = a.allLast;\n args[\"deposit\"] = a.deposit;\n args[\"seed\"] = a.seed;\n break;\n }\n case TE::Type::DICED: {\n const auto &a = event.as<TE::Diced>();\n args[\"die1\"] = a.die1;\n args[\"die2\"] = a.die2;\n break;\n }\n case TE::Type::DRAWN:\n args[\"who\"] = event.as<TE::Drawn>().who;\n break;\n case TE::Type::DISCARDED:\n args[\"spin\"] = event.as<TE::Discarded>().spin;\n break;\n case TE::Type::RIICHI_CALLED:\n args[\"who\"] = event.as<TE::RiichiCalled>().who;\n break;\n case TE::Type::RIICHI_ESTABLISHED:\n args[\"who\"] = event.as<TE::RiichiEstablished>().who;\n break;\n case TE::Type::BARKED: {\n const auto &a = event.as<TE::Barked>();\n args[\"who\"] = a.who;\n args[\"bark\"] = a.bark;\n args[\"spin\"] = a.spin;\n break;\n }\n case TE::Type::ROUND_ENDED: {\n const auto &a = event.as<TE::RoundEnded>();\n args[\"result\"] = util::stringOf(a.result);\n args[\"openers\"] = a.openers;\n args[\"gunner\"] = a.gunner;\n args[\"forms\"] = a.forms;\n break;\n }\n case TE::Type::TABLE_ENDED: {\n const auto &a = event.as<TE::TableEnded>();\n args[\"ranks\"] = a.ranks;\n args[\"scores\"] = a.scores;\n break;\n }\n case TE::Type::POPPED_UP:\n args[\"who\"] = event.as<TE::PoppedUp>().who;\n break;\n default:\n break;\n }\n\n return env.create_with(\n \"type\", util::stringOf(event.type()),\n \"args\", args\n );\n}\n\n\n\n} \/\/ namespace saki\n<commit_msg>add table-based \"drids % hand\" to lua api<commit_after>#include \"lua_class.h\"\n#include \"..\/table\/table.h\"\n#include \"..\/util\/string_enum.h\"\n\nnamespace saki\n{\n\n\n\nbool isValidSuitStr(const std::string &s)\n{\n return s.size() == 1 && T34::isValidSuit(s[0]);\n}\n\nstd::string toLower(const char *s)\n{\n std::string res(s);\n std::for_each(res.begin(), res.end(), [](char &c) {\n c = static_cast<char>(std::tolower(c));\n });\n return res;\n}\n\nstd::pair<Mount::Exit, bool> parseMountExit(const std::string &s)\n{\n std::pair<Mount::Exit, bool> res;\n\n res.second = true;\n if (s == \"pii\")\n res.first = Mount::Exit::PII;\n else if (s == \"rinshan\")\n res.first = Mount::Exit::RINSHAN;\n else if (s == \"dorahyou\")\n res.first = Mount::Exit::DORAHYOU;\n else if (s == \"urahyou\")\n res.first = Mount::Exit::URAHYOU;\n else\n res.second = false;\n\n return res;\n}\n\ntemplate<typename Class, typename Ret, typename... Args>\nclass AsTable\n{\npublic:\n using Method = Ret (Class::*)(Args...) const;\n using Table = sol::as_table_t<sol::meta::unqualified_t<Ret>>;\n\n explicit AsTable(Method method)\n : mMethod(method)\n {\n }\n\n Table operator()(Class &thiz, Args... args)\n {\n return sol::as_table((thiz.*mMethod)(args...));\n }\n\nprivate:\n Method mMethod;\n};\n\nvoid setupLuaClasses(const sol::environment &env, LuaUserErrorHandler &error)\n{\n setupLuaTile(env, error);\n setupLuaWho(env);\n setupLuaMeld(env, error);\n setupLuaExist(env, error);\n setupLuaMount(env, error);\n setupLuaTileCount(env, error);\n setupLuaHand(env);\n setupLuaGame(env);\n}\n\nvoid setupLuaTile(sol::environment env, LuaUserErrorHandler &error)\n{\n env.new_usertype<T34>(\n \"T34\",\n sol::meta_function::construct, sol::factories(\n [&error](int ti) {\n if (ti < 0 || ti >= 34) {\n error.handleUserError(\"invalid T34 id\");\n return T34();\n }\n\n return T34(ti);\n },\n [&error](const std::string s) {\n static const std::array<std::string, 34> dict {\n \"1m\", \"2m\", \"3m\", \"4m\", \"5m\", \"6m\", \"7m\", \"8m\", \"9m\",\n \"1p\", \"2p\", \"3p\", \"4p\", \"5p\", \"6p\", \"7p\", \"8p\", \"9p\",\n \"1s\", \"2s\", \"3s\", \"4s\", \"5s\", \"6s\", \"7s\", \"8s\", \"9s\",\n \"1f\", \"2f\", \"3f\", \"4f\", \"1y\", \"2y\", \"3y\"\n };\n\n auto it = std::find(dict.begin(), dict.end(), s);\n if (it == dict.end()) {\n error.handleUserError(\"invalid T34 string\");\n return T34();\n }\n\n return T34(static_cast<int>(it - dict.begin()));\n }\n ),\n \"id34\", &T34::id34,\n \"suit\", [](T34 t) { return T34::charOf(t.suit()); },\n \"val\", &T34::val,\n \"str34\", &T34::str34,\n \"isz\", &T34::isZ,\n \"isnum\", &T34::isNum,\n \"isnum19\", &T34::isNum19,\n \"isyao\", &T34::isYao,\n \"isyakuhai\", &T34::isYakuhai,\n \"dora\", &T34::dora,\n \"indicator\", &T34::indicator,\n sol::meta_function::to_string, &T34::str34,\n sol::meta_function::equal_to, &T34::operator==,\n sol::meta_function::less_than, &T34::operator<,\n sol::meta_function::modulus, &T34::operator%,\n \"all\", sol::var(std::vector<T34>(tiles34::ALL34.begin(), tiles34::ALL34.end()))\n );\n\n env.new_usertype<T37>(\n \"T37\",\n sol::meta_function::construct, sol::factories(\n [&error](int ti) {\n if (ti < 0 || ti >= 34) {\n error.handleUserError(\"invalid T34 id\");\n return T37();\n }\n\n return T37(ti);\n },\n [&error](const std::string s) {\n if (!T37::isValidStr(s.c_str())) {\n error.handleUserError(\"invalid T37 suit\");\n return T37();\n }\n return T37(s.c_str());\n }\n ),\n \"isaka5\", &T37::isAka5,\n \"lookssame\", &T37::looksSame,\n \"str37\", &T37::str37,\n sol::meta_function::to_string, &T37::str37,\n sol::base_classes, sol::bases<T34>()\n );\n}\n\nvoid setupLuaWho(sol::environment env)\n{\n env.new_usertype<Who>(\n \"Who\",\n \"right\", &Who::right,\n \"cross\", &Who::cross,\n \"left\", &Who::left,\n \"bydice\", &Who::byDice,\n \"byturn\", &Who::byTurn,\n \"looksat\", &Who::looksAt,\n \"turnfrom\", &Who::turnFrom,\n \"index\", [](Who w) { return w.index() + 1; },\n sol::meta_function::to_string, [](Who w) { return w.index() + 1; },\n sol::meta_function::equal_to, &Who::operator==\n );\n}\n\nvoid setupLuaMeld(sol::environment env, LuaUserErrorHandler &error)\n{\n env.new_usertype<M37>(\n \"M37\",\n \"type\", [](const M37 &m) {\n return toLower(util::stringOf(m.type()));\n },\n \"has\", &M37::has,\n sol::meta_function::index, [&error](const M37 &m, int index) {\n int zeroIndex = index - 1;\n int size = static_cast<int>(m.tiles().size());\n if (zeroIndex < 0 || zeroIndex > size) {\n error.handleUserError(\"invalid meld index\");\n return T37();\n }\n\n return m[index];\n }\n );\n}\n\nvoid setupLuaExist(sol::environment env, LuaUserErrorHandler &error)\n{\n (void) error;\n env.new_usertype<Exist>(\n \"Exist\",\n \"incmk\", sol::overload(\n [](Exist &exist, T34 t, int delta) {\n exist.incMk(t, delta);\n },\n [](Exist &exist, const T37 &t, int delta) {\n exist.incMk(t, delta);\n }\n )\n );\n}\n\nvoid setupLuaMount(sol::environment env, LuaUserErrorHandler &error)\n{\n env.new_usertype<Mount>(\n \"Mount\",\n \"remainpii\", &Mount::remainPii,\n \"remainrinshan\", &Mount::remainRinshan,\n \"remaina\", sol::overload(\n [](Mount &mount, T34 t) {\n mount.remainA(t);\n },\n [](Mount &mount, const T37 &t) {\n mount.remainA(t);\n }\n ),\n \"getdrids\", AsTable(&Mount::getDrids),\n \"geturids\", AsTable(&Mount::getUrids),\n \"lighta\", sol::overload(\n [](Mount &mount, T34 t, int mk, bool rin) {\n mount.lightA(t, mk, rin);\n },\n [](Mount &mount, const T37 &t, int mk, bool rin) {\n mount.lightA(t, mk, rin);\n },\n [](Mount &mount, T34 t, int mk) {\n mount.lightA(t, mk);\n },\n [](Mount &mount, const T37 &t, int mk) {\n mount.lightA(t, mk);\n }\n ),\n \"lightb\", sol::overload(\n [](Mount &mount, T34 t, int mk, bool rin) {\n mount.lightB(t, mk, rin);\n },\n [](Mount &mount, const T37 &t, int mk, bool rin) {\n mount.lightB(t, mk, rin);\n },\n [](Mount &mount, T34 t, int mk) {\n mount.lightB(t, mk);\n },\n [](Mount &mount, const T37 &t, int mk) {\n mount.lightB(t, mk);\n }\n ),\n \"incmk\", sol::overload(\n [&error](Mount &mount, std::string exit, size_t pos, T34 t, int delta, bool bSpace) {\n auto [e, ok] = parseMountExit(exit);\n if (!ok) {\n error.handleUserError(\"invalid mount exit\");\n return;\n }\n mount.incMk(e, pos, t, delta, bSpace);\n },\n [&error](Mount &mount, std::string exit, size_t pos, const T37 &t, int delta, bool bSpace) {\n auto [e, ok] = parseMountExit(exit);\n if (!ok) {\n error.handleUserError(\"invalid mount exit\");\n return;\n }\n mount.incMk(e, pos, t, delta, bSpace);\n }\n ),\n \"loadb\", &Mount::loadB\n );\n}\n\nvoid setupLuaTileCount(sol::environment env, LuaUserErrorHandler &error)\n{\n env.new_usertype<TileCount>(\n \"Tilecount\",\n \"ct\", sol::overload(\n [](const TileCount &tc, T34 t) {\n return tc.ct(t);\n },\n [](const TileCount &tc, const T37 &t) {\n return tc.ct(t);\n },\n [&error](const TileCount &tc, std::string suit) {\n if (!isValidSuitStr(suit)) {\n error.handleUserError(\"invalid suit\");\n return 0;\n }\n\n return tc.ct(T34::suitOf(suit[0]));\n }\n )\n );\n}\n\nvoid setupLuaHand(sol::environment env)\n{\n env.new_usertype<Hand>(\n \"Hand\",\n \"closed\", &Hand::closed,\n \"ct\", &Hand::ct,\n \"ctaka5\", &Hand::ctAka5,\n \"ready\", &Hand::ready,\n \"step\", &Hand::step,\n \"step4\", &Hand::step4,\n \"step7\", &Hand::step7,\n \"step7gb\", &Hand::step7Gb,\n \"step13\", &Hand::step13,\n \"effa\", AsTable(&Hand::effA),\n \"effa4\", AsTable(&Hand::effA4),\n \"ismenzen\", &Hand::isMenzen,\n \"barks\", AsTable(&Hand::barks),\n \"canchii\", &Hand::canChii,\n \"canchiiasleft\", &Hand::canChiiAsLeft,\n \"canchiiasmiddle\", &Hand::canChiiAsMiddle,\n \"canchiiasright\", &Hand::canChiiAsRight,\n \"canpon\", &Hand::canPon,\n \"candaiminkan\", &Hand::canDaiminkan,\n sol::meta_function::modulus, sol::overload(\n [](sol::table ids, const Hand &hand) {\n int ct = 0;\n for (auto [key, ref] : ids) {\n (void) ref; \/\/ conv-to-opt doesn't work somehow\n\n std::optional<T34> id;\n id = ids[key];\n if (id == std::nullopt) {\n std::optional<T37> id37 = ids[key];\n id = id37;\n }\n\n if (id != std::nullopt)\n ct += *id % hand;\n }\n\n return ct;\n },\n [](T34 indic, const Hand &hand) {\n return indic % hand;\n }\n )\n );\n}\n\nvoid setupLuaGame(sol::environment env)\n{\n env.new_usertype<Table>(\n \"Game\",\n \"gethand\", &Table::getHand,\n \"getround\", &Table::getRound,\n \"getextraround\", &Table::getExtraRound,\n \"getdealer\", &Table::getDealer,\n \"getselfwind\", &Table::getSelfWind,\n \"getroundwind\", &Table::getRoundWind,\n \"getriver\", AsTable(&Table::getRiver),\n \"riichiestablished\", &Table::riichiEstablished\n );\n}\n\nsol::table toLuaTable(sol::environment env, const TableEvent &event)\n{\n using TE = TableEvent;\n\n sol::table args = env.create();\n\n switch (event.type()) {\n case TE::Type::TABLE_STARTED:\n args[\"seed\"] = event.as<TE::TableStarted>().seed;\n break;\n case TE::Type::FIRST_DEALER_CHOSEN:\n args[\"who\"] = event.as<TE::FirstDealerChosen>().who;\n break;\n case TE::Type::ROUND_STARTED: {\n const auto &a = event.as<TE::RoundStarted>();\n args[\"round\"] = a.round;\n args[\"extraround\"] = a.extraRound;\n args[\"dealer\"] = a.dealer;\n args[\"alllast\"] = a.allLast;\n args[\"deposit\"] = a.deposit;\n args[\"seed\"] = a.seed;\n break;\n }\n case TE::Type::DICED: {\n const auto &a = event.as<TE::Diced>();\n args[\"die1\"] = a.die1;\n args[\"die2\"] = a.die2;\n break;\n }\n case TE::Type::DRAWN:\n args[\"who\"] = event.as<TE::Drawn>().who;\n break;\n case TE::Type::DISCARDED:\n args[\"spin\"] = event.as<TE::Discarded>().spin;\n break;\n case TE::Type::RIICHI_CALLED:\n args[\"who\"] = event.as<TE::RiichiCalled>().who;\n break;\n case TE::Type::RIICHI_ESTABLISHED:\n args[\"who\"] = event.as<TE::RiichiEstablished>().who;\n break;\n case TE::Type::BARKED: {\n const auto &a = event.as<TE::Barked>();\n args[\"who\"] = a.who;\n args[\"bark\"] = a.bark;\n args[\"spin\"] = a.spin;\n break;\n }\n case TE::Type::ROUND_ENDED: {\n const auto &a = event.as<TE::RoundEnded>();\n args[\"result\"] = util::stringOf(a.result);\n args[\"openers\"] = a.openers;\n args[\"gunner\"] = a.gunner;\n args[\"forms\"] = a.forms;\n break;\n }\n case TE::Type::TABLE_ENDED: {\n const auto &a = event.as<TE::TableEnded>();\n args[\"ranks\"] = a.ranks;\n args[\"scores\"] = a.scores;\n break;\n }\n case TE::Type::POPPED_UP:\n args[\"who\"] = event.as<TE::PoppedUp>().who;\n break;\n default:\n break;\n }\n\n return env.create_with(\n \"type\", util::stringOf(event.type()),\n \"args\", args\n );\n}\n\n\n\n} \/\/ namespace saki\n<|endoftext|>"} {"text":"<commit_before>\/\/===- X86MacroFusion.cpp - X86 Macro Fusion ------------------------------===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/\/ \\file This file contains the X86 implementation of the DAG scheduling\n\/\/\/ mutation to pair instructions back to back.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"X86MacroFusion.h\"\n#include \"X86Subtarget.h\"\n#include \"llvm\/CodeGen\/MacroFusion.h\"\n#include \"llvm\/CodeGen\/TargetInstrInfo.h\"\n\nusing namespace llvm;\n\n\/\/\/ Check if the instr pair, FirstMI and SecondMI, should be fused\n\/\/\/ together. Given SecondMI, when FirstMI is unspecified, then check if\n\/\/\/ SecondMI may be part of a fused pair at all.\nstatic bool shouldScheduleAdjacent(const TargetInstrInfo &TII,\n const TargetSubtargetInfo &TSI,\n const MachineInstr *FirstMI,\n const MachineInstr &SecondMI) {\n const X86Subtarget &ST = static_cast<const X86Subtarget&>(TSI);\n \/\/ Check if this processor supports macro-fusion.\n if (!ST.hasMacroFusion())\n return false;\n\n enum {\n FuseTest,\n FuseCmp,\n FuseInc\n } FuseKind;\n\n unsigned FirstOpcode = FirstMI\n ? FirstMI->getOpcode()\n : static_cast<unsigned>(X86::INSTRUCTION_LIST_END);\n unsigned SecondOpcode = SecondMI.getOpcode();\n\n switch (SecondOpcode) {\n default:\n return false;\n case X86::JE_1:\n case X86::JNE_1:\n case X86::JL_1:\n case X86::JLE_1:\n case X86::JG_1:\n case X86::JGE_1:\n FuseKind = FuseInc;\n break;\n case X86::JB_1:\n case X86::JBE_1:\n case X86::JA_1:\n case X86::JAE_1:\n FuseKind = FuseCmp;\n break;\n case X86::JS_1:\n case X86::JNS_1:\n case X86::JP_1:\n case X86::JNP_1:\n case X86::JO_1:\n case X86::JNO_1:\n FuseKind = FuseTest;\n break;\n }\n\n switch (FirstOpcode) {\n default:\n return false;\n case X86::TEST8rr:\n case X86::TEST16rr:\n case X86::TEST32rr:\n case X86::TEST64rr:\n case X86::TEST8ri:\n case X86::TEST16ri:\n case X86::TEST32ri:\n case X86::TEST32i32:\n case X86::TEST64i32:\n case X86::TEST64ri32:\n case X86::TEST8mr:\n case X86::TEST16mr:\n case X86::TEST32mr:\n case X86::TEST64mr:\n case X86::AND16i16:\n case X86::AND16ri:\n case X86::AND16ri8:\n case X86::AND16rm:\n case X86::AND16rr:\n case X86::AND32i32:\n case X86::AND32ri:\n case X86::AND32ri8:\n case X86::AND32rm:\n case X86::AND32rr:\n case X86::AND64i32:\n case X86::AND64ri32:\n case X86::AND64ri8:\n case X86::AND64rm:\n case X86::AND64rr:\n case X86::AND8i8:\n case X86::AND8ri:\n case X86::AND8rm:\n case X86::AND8rr:\n return true;\n case X86::CMP16i16:\n case X86::CMP16ri:\n case X86::CMP16ri8:\n case X86::CMP16rm:\n case X86::CMP16rr:\n case X86::CMP16mr:\n case X86::CMP32i32:\n case X86::CMP32ri:\n case X86::CMP32ri8:\n case X86::CMP32rm:\n case X86::CMP32rr:\n case X86::CMP32mr:\n case X86::CMP64i32:\n case X86::CMP64ri32:\n case X86::CMP64ri8:\n case X86::CMP64rm:\n case X86::CMP64rr:\n case X86::CMP64mr:\n case X86::CMP8i8:\n case X86::CMP8ri:\n case X86::CMP8rm:\n case X86::CMP8rr:\n case X86::CMP8mr:\n case X86::ADD16i16:\n case X86::ADD16ri:\n case X86::ADD16ri8:\n case X86::ADD16ri8_DB:\n case X86::ADD16ri_DB:\n case X86::ADD16rm:\n case X86::ADD16rr:\n case X86::ADD16rr_DB:\n case X86::ADD32i32:\n case X86::ADD32ri:\n case X86::ADD32ri8:\n case X86::ADD32ri8_DB:\n case X86::ADD32ri_DB:\n case X86::ADD32rm:\n case X86::ADD32rr:\n case X86::ADD32rr_DB:\n case X86::ADD64i32:\n case X86::ADD64ri32:\n case X86::ADD64ri32_DB:\n case X86::ADD64ri8:\n case X86::ADD64ri8_DB:\n case X86::ADD64rm:\n case X86::ADD64rr:\n case X86::ADD64rr_DB:\n case X86::ADD8i8:\n case X86::ADD8ri:\n case X86::ADD8rm:\n case X86::ADD8rr:\n case X86::SUB16i16:\n case X86::SUB16ri:\n case X86::SUB16ri8:\n case X86::SUB16rm:\n case X86::SUB16rr:\n case X86::SUB32i32:\n case X86::SUB32ri:\n case X86::SUB32ri8:\n case X86::SUB32rm:\n case X86::SUB32rr:\n case X86::SUB64i32:\n case X86::SUB64ri32:\n case X86::SUB64ri8:\n case X86::SUB64rm:\n case X86::SUB64rr:\n case X86::SUB8i8:\n case X86::SUB8ri:\n case X86::SUB8rm:\n case X86::SUB8rr:\n return FuseKind == FuseCmp || FuseKind == FuseInc;\n case X86::INC16r:\n case X86::INC32r:\n case X86::INC64r:\n case X86::INC8r:\n case X86::DEC16r:\n case X86::DEC32r:\n case X86::DEC64r:\n case X86::DEC8r:\n return FuseKind == FuseInc;\n case X86::INSTRUCTION_LIST_END:\n return true;\n }\n}\n\nnamespace llvm {\n\nstd::unique_ptr<ScheduleDAGMutation>\ncreateX86MacroFusionDAGMutation () {\n return createBranchMacroFusionDAGMutation(shouldScheduleAdjacent);\n}\n\n} \/\/ end namespace llvm\n<commit_msg>[X86] Remove the AL\/AX\/EAX\/RAX short immediate forms from the macro fusion shouldScheduleAdjacent. NFC<commit_after>\/\/===- X86MacroFusion.cpp - X86 Macro Fusion ------------------------------===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/\/ \\file This file contains the X86 implementation of the DAG scheduling\n\/\/\/ mutation to pair instructions back to back.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"X86MacroFusion.h\"\n#include \"X86Subtarget.h\"\n#include \"llvm\/CodeGen\/MacroFusion.h\"\n#include \"llvm\/CodeGen\/TargetInstrInfo.h\"\n\nusing namespace llvm;\n\n\/\/\/ Check if the instr pair, FirstMI and SecondMI, should be fused\n\/\/\/ together. Given SecondMI, when FirstMI is unspecified, then check if\n\/\/\/ SecondMI may be part of a fused pair at all.\nstatic bool shouldScheduleAdjacent(const TargetInstrInfo &TII,\n const TargetSubtargetInfo &TSI,\n const MachineInstr *FirstMI,\n const MachineInstr &SecondMI) {\n const X86Subtarget &ST = static_cast<const X86Subtarget&>(TSI);\n \/\/ Check if this processor supports macro-fusion.\n if (!ST.hasMacroFusion())\n return false;\n\n enum {\n FuseTest,\n FuseCmp,\n FuseInc\n } FuseKind;\n\n unsigned FirstOpcode = FirstMI\n ? FirstMI->getOpcode()\n : static_cast<unsigned>(X86::INSTRUCTION_LIST_END);\n unsigned SecondOpcode = SecondMI.getOpcode();\n\n switch (SecondOpcode) {\n default:\n return false;\n case X86::JE_1:\n case X86::JNE_1:\n case X86::JL_1:\n case X86::JLE_1:\n case X86::JG_1:\n case X86::JGE_1:\n FuseKind = FuseInc;\n break;\n case X86::JB_1:\n case X86::JBE_1:\n case X86::JA_1:\n case X86::JAE_1:\n FuseKind = FuseCmp;\n break;\n case X86::JS_1:\n case X86::JNS_1:\n case X86::JP_1:\n case X86::JNP_1:\n case X86::JO_1:\n case X86::JNO_1:\n FuseKind = FuseTest;\n break;\n }\n\n switch (FirstOpcode) {\n default:\n return false;\n case X86::TEST8rr:\n case X86::TEST16rr:\n case X86::TEST32rr:\n case X86::TEST64rr:\n case X86::TEST8ri:\n case X86::TEST16ri:\n case X86::TEST32ri:\n case X86::TEST64ri32:\n case X86::TEST8mr:\n case X86::TEST16mr:\n case X86::TEST32mr:\n case X86::TEST64mr:\n case X86::AND16ri:\n case X86::AND16ri8:\n case X86::AND16rm:\n case X86::AND16rr:\n case X86::AND32ri:\n case X86::AND32ri8:\n case X86::AND32rm:\n case X86::AND32rr:\n case X86::AND64ri32:\n case X86::AND64ri8:\n case X86::AND64rm:\n case X86::AND64rr:\n case X86::AND8ri:\n case X86::AND8rm:\n case X86::AND8rr:\n return true;\n case X86::CMP16ri:\n case X86::CMP16ri8:\n case X86::CMP16rm:\n case X86::CMP16rr:\n case X86::CMP16mr:\n case X86::CMP32ri:\n case X86::CMP32ri8:\n case X86::CMP32rm:\n case X86::CMP32rr:\n case X86::CMP32mr:\n case X86::CMP64ri32:\n case X86::CMP64ri8:\n case X86::CMP64rm:\n case X86::CMP64rr:\n case X86::CMP64mr:\n case X86::CMP8ri:\n case X86::CMP8rm:\n case X86::CMP8rr:\n case X86::CMP8mr:\n case X86::ADD16ri:\n case X86::ADD16ri8:\n case X86::ADD16ri8_DB:\n case X86::ADD16ri_DB:\n case X86::ADD16rm:\n case X86::ADD16rr:\n case X86::ADD16rr_DB:\n case X86::ADD32ri:\n case X86::ADD32ri8:\n case X86::ADD32ri8_DB:\n case X86::ADD32ri_DB:\n case X86::ADD32rm:\n case X86::ADD32rr:\n case X86::ADD32rr_DB:\n case X86::ADD64ri32:\n case X86::ADD64ri32_DB:\n case X86::ADD64ri8:\n case X86::ADD64ri8_DB:\n case X86::ADD64rm:\n case X86::ADD64rr:\n case X86::ADD64rr_DB:\n case X86::ADD8ri:\n case X86::ADD8rm:\n case X86::ADD8rr:\n case X86::SUB16ri:\n case X86::SUB16ri8:\n case X86::SUB16rm:\n case X86::SUB16rr:\n case X86::SUB32ri:\n case X86::SUB32ri8:\n case X86::SUB32rm:\n case X86::SUB32rr:\n case X86::SUB64ri32:\n case X86::SUB64ri8:\n case X86::SUB64rm:\n case X86::SUB64rr:\n case X86::SUB8ri:\n case X86::SUB8rm:\n case X86::SUB8rr:\n return FuseKind == FuseCmp || FuseKind == FuseInc;\n case X86::INC16r:\n case X86::INC32r:\n case X86::INC64r:\n case X86::INC8r:\n case X86::DEC16r:\n case X86::DEC32r:\n case X86::DEC64r:\n case X86::DEC8r:\n return FuseKind == FuseInc;\n case X86::INSTRUCTION_LIST_END:\n return true;\n }\n}\n\nnamespace llvm {\n\nstd::unique_ptr<ScheduleDAGMutation>\ncreateX86MacroFusionDAGMutation () {\n return createBranchMacroFusionDAGMutation(shouldScheduleAdjacent);\n}\n\n} \/\/ end namespace llvm\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ R2000DataReader.cpp\n\/\/ R2000DataReader\n\/\/\n\/\/ Created by inx on 20\/12\/15.\n\/\/\n\/\/\n\n#include \"ofxR2000DataReader.h\"\n\n#include <zlib.h>\n\nstatic int sps[] = {25200, 16800, 12600, 10080, 8400, 7200, 6300, 5600, 5040, 4200, 3600, 2400, 1800, 1440, 1200, 900, 800, 720, 600, 480, 450, 400, 360, 240, 180, 144, 120, 90, 72};\nstatic int sps_size = sizeof(sps) \/ sizeof(int);\n\n\n\/*\n *\/\nstatic void zipuncompress_uint32( const std::vector< unsigned char > & src, std::vector< std::uint32_t > & ret )\n{\n\tif ( src.size() < 4 ) {\n\t\tret.clear();\n\t\treturn;\n\t}\n\t\n\t\/\/\/ load header (size of compressed buffer)\n\tuLongf originalSize = 0;\n\t{\n\t\toriginalSize += ( src[0] << 24 );\n\t\toriginalSize += ( src[1] << 16 );\n\t\toriginalSize += ( src[2] << 8 );\n\t\toriginalSize += ( src[3] << 0 );\n\t}\n\t\n\tret.resize( originalSize, 0 );\n\tunsigned long ret_size = originalSize * sizeof(std::uint32_t);\n\t{\n\t\t\/\/ try to uncompress with sizeof( uLongf )\n\t\tint error = uncompress( (unsigned char*)ret.data(), &ret_size, src.data() + sizeof( uLongf ), src.size() );\n\t\t\n\t\tif ( error == Z_OK )\n\t\t{\n\t\t\tret.resize( ret_size \/ sizeof(std::uint32_t), 0 );\n\t\t}\n\t\telse\n\t\t{\n\t\t\t\/\/ failed... try with other uLongSize...\n\t\t\tint error = Z_OK;\n\t\t\t\n\t\t\tif (sizeof(uLongf) == 4) {\n\t\t\t\t\/\/ try with uLongF size 8\n\t\t\t\tuint8_t sizeOfULongf = 8;\n\t\t\t\terror = uncompress( (unsigned char*)ret.data(), &ret_size, src.data() + sizeOfULongf, src.size() );\n\t\t\t\t\n\t\t\t} else if (sizeof(uLongf) == 8) {\n\t\t\t\t\/\/ try with uLongF size 4\n\t\t\t\tuint8_t sizeOfULongf = 4;\n\t\t\t\terror = uncompress( (unsigned char*)ret.data(), &ret_size, src.data() + sizeOfULongf, src.size() );\n\t\t\t}\n\t\t\t\n\t\t\tif ( error == Z_OK )\n\t\t\t{\n\t\t\t\tret.resize( ret_size \/ sizeof(std::uint32_t), 0 );\n\t\t\t} else {\n\t\t\t\tofLogError( \"zipuncompress_uint32()\" ) << \"zlib uncompress() error: \" << error;\n\t\t\t\tret.clear();\n\t\t\t}\n\t\t}\n\t}\n}\n\n\n\/*\n *\/\nR2000DataReader::R2000DataReader() :\n\tdataStart(0)\n\t,count(0)\n\t,samplesPerScan(0)\n\t,scanFrequency(0)\n\t,updateTime(0)\n\t,lastUpdate(0)\n{}\n\nR2000DataReader::R2000DataReader(string& filepath) : R2000DataReader() {\n\t\n\tbool ret = load(filepath);\n}\n\n\nR2000DataReader::R2000DataReader(ofFile& file) : R2000DataReader() {\n\tload(file);\n}\n\nR2000DataReader::~R2000DataReader() {\n\tinfile.close();\n}\n\n\nbool R2000DataReader::load(const char* filepath) {\n\tstring p(filepath);\n\treturn load(p);\n}\n\nbool R2000DataReader::load(string& filepath) {\n\n\tbool ret = infile.open(filepath);\n\t\n\tif (ret){\n\t\tinitRead();\n\t}\n\t\n\treturn ret;\n}\n\nvoid R2000DataReader::load(ofFile& file) {\n\tinfile = file;\n\tinitRead();\n}\n\n\nvoid R2000DataReader::initRead() {\n\t\n\tif (!infile.isFile()) {\n\t\treturn;\n\t}\n\t\n\tuint8_t readSize;\n\t\n\tinfile.read((char*)&readSize, sizeof(uint8_t));\n\tinfile.read((char*)&samplesPerScan, readSize);\n\t\n\tinfile.read((char*)&readSize, sizeof(uint8_t));\n\tinfile.read((char*)&scanFrequency, readSize);\n\t\n\t\/\/----------------------------------------\n\t\/\/ check values\n\tbool correctValue = false;\n\tfor (int j=0; j<sps_size; j++) {\n\t\tif (samplesPerScan == sps[j]) {\n\t\t\tcorrectValue = true;\n\t\t\tbreak;\n\t\t}\n\t}\n\t\n\tif (scanFrequency < 10 || scanFrequency > 50) {\n\t\tcorrectValue = false;\n\t}\n\t\n\t\n\tif (!correctValue) {\n\t\tofLogError() << \"not a correct value\";\n\t\tOF_EXIT_APP(-1);\n\t}\n\n\tlastScanData.distance_data.resize(samplesPerScan);\n\tlastScanData.amplitude_data.resize(samplesPerScan);\n\t\n\t\/\/----------------------------------------\n\tupdateTime = 1000.0 \/ (double)scanFrequency;\n\tdataStart = infile.tellg();\n\tlastUpdate = ofGetElapsedTimeMillis() - updateTime;\n}\n\n\nbool R2000DataReader::update() {\n\t\n\tbool newScan = false;\n\t\n\tif ((double)(ofGetElapsedTimeMillis() - lastUpdate) >= updateTime) {\n\t\t\n\t\tlastUpdate = ofGetElapsedTimeMillis();\n\t\t\n\t\tbool doCompress = false;\n\t\t\n\t\tuint8_t readSize;\n\t\tstd::uint32_t vectorSize;\n\t\t\n\t\t\/\/----------------------------------------------------\n\t\t\/\/ get count\n\t\tinfile.read((char*)&readSize, sizeof(uint8_t));\n\t\t\/\/ check for eof, assume that data is alligned\n\t\tif (infile.eof()) {\n\t\t\tinfile.clear();\n\t\t\tinfile.seekg(dataStart);\n\t\t\t\n\t\t\t\/\/ read byte again\n\t\t\tinfile.read((char*)&readSize, sizeof(uint8_t));\n\t\t}\n\t\tinfile.read((char*)&count, readSize);\n\t\t\n\t\t\n\t\t\/\/----------------------------------------------------\n\t\t\/\/ distance data\n\t\t\n\t\t\/\/ compression-flag\n\t\tinfile.read((char*)&doCompress, 1);\n\t\t\n\t\tinfile.read((char*)&readSize, sizeof(uint8_t));\n\t\tinfile.read((char*)&vectorSize, readSize);\n\t\tif (doCompress) {\n\t\t\tstd::vector<unsigned char> data;\n\t\t\tdata.resize(vectorSize);\n\t\t\tinfile.read((char*)data.data(), vectorSize);\n\t\t\t\n\t\t\tofLogNotice() << \"uncompress distance data: \" << vectorSize;\n\t\t\t\n\t\t\tzipuncompress_uint32(data, lastScanData.distance_data);\n\t\t\t\n\t\t\t\/\/ correct\n\t\t\tvectorSize = lastScanData.distance_data.size();\n\t\t} else {\n\t\t\tif (lastScanData.distance_data.size() != vectorSize) {\n\t\t\t\tofLogNotice() << \"resize distance vector\";\n\t\t\t\tlastScanData.distance_data.resize(vectorSize);\n\t\t\t}\n\t\t\tinfile.read((char*)lastScanData.distance_data.data(), (vectorSize * sizeof(std::uint32_t)));\n\t\t}\n\t\t\n\t\t\n\t\t\/\/----------------------------------------------------\n\t\t\/\/ amplitude data\n\t\t\n\t\t\/\/ compression-flag\n\t\tinfile.read((char*)&doCompress, 1);\n\t\t\n\t\tinfile.read((char*)&readSize, sizeof(uint8_t));\n\t\tinfile.read((char*)&vectorSize, readSize);\n\t\tif (doCompress) {\n\t\t\tstd::vector<unsigned char> data;\n\t\t\tdata.resize(vectorSize);\n\t\t\tinfile.read((char*)data.data(), vectorSize);\n\t\t\t\n\t\t\tofLogNotice() << \"uncompress amplitude data: \" << vectorSize;\n\t\t\t\n\t\t\tzipuncompress_uint32(data, lastScanData.amplitude_data);\n\t\t\t\/\/ correct\n\t\t\tvectorSize = lastScanData.amplitude_data.size();\n\t\t} else {\n\t\t\tif (lastScanData.amplitude_data.size() != vectorSize) {\n\t\t\t\tofLogNotice() << \"resize amplitude vector\";\n\t\t\t\tlastScanData.amplitude_data.resize(vectorSize);\n\t\t\t}\n\t\t\tinfile.read((char*)lastScanData.amplitude_data.data(), (vectorSize * sizeof(std::uint32_t)));\n\t\t}\n\t\t\n\t\t\n\t\t\/\/----------------------------------------------------\n\t\t\/\/ header data\n\t\t\n\t\t\/\/ compression-flag\n\t\tinfile.read((char*)&doCompress, 1);\n\t\t\n\t\tinfile.read((char*)&readSize, sizeof(uint8_t));\n\t\tinfile.read((char*)&vectorSize, readSize);\n\t\tif (doCompress || !doCompress) {\n\t\t\tif (lastScanData.headers.size() != vectorSize) {\n\t\t\t\tlastScanData.headers.resize(vectorSize);\n\t\t\t}\n\t\t\tinfile.read((char*)lastScanData.headers.data(), (vectorSize * sizeof(PacketHeader)));\n\t\t}\n\t\t\/\/\t\tofLogNotice() << \"HEADERS: \" << vectorSize;\n\t\t\n\t\tnewScan = true;\n\t}\n\t\n\treturn newScan;\n}<commit_msg>remove logs<commit_after>\/\/\n\/\/ R2000DataReader.cpp\n\/\/ R2000DataReader\n\/\/\n\/\/ Created by inx on 20\/12\/15.\n\/\/\n\/\/\n\n#include \"ofxR2000DataReader.h\"\n\n#include <zlib.h>\n\nstatic int sps[] = {25200, 16800, 12600, 10080, 8400, 7200, 6300, 5600, 5040, 4200, 3600, 2400, 1800, 1440, 1200, 900, 800, 720, 600, 480, 450, 400, 360, 240, 180, 144, 120, 90, 72};\nstatic int sps_size = sizeof(sps) \/ sizeof(int);\n\n\n\/*\n *\/\nstatic void zipuncompress_uint32( const std::vector< unsigned char > & src, std::vector< std::uint32_t > & ret )\n{\n\tif ( src.size() < 4 ) {\n\t\tret.clear();\n\t\treturn;\n\t}\n\t\n\t\/\/\/ load header (size of compressed buffer)\n\tuLongf originalSize = 0;\n\t{\n\t\toriginalSize += ( src[0] << 24 );\n\t\toriginalSize += ( src[1] << 16 );\n\t\toriginalSize += ( src[2] << 8 );\n\t\toriginalSize += ( src[3] << 0 );\n\t}\n\t\n\tret.resize( originalSize, 0 );\n\tunsigned long ret_size = originalSize * sizeof(std::uint32_t);\n\t{\n\t\t\/\/ try to uncompress with sizeof( uLongf )\n\t\tint error = uncompress( (unsigned char*)ret.data(), &ret_size, src.data() + sizeof( uLongf ), src.size() );\n\t\t\n\t\tif ( error == Z_OK )\n\t\t{\n\t\t\tret.resize( ret_size \/ sizeof(std::uint32_t), 0 );\n\t\t}\n\t\telse\n\t\t{\n\t\t\t\/\/ failed... try with other uLongSize...\n\t\t\tint error = Z_OK;\n\t\t\t\n\t\t\tif (sizeof(uLongf) == 4) {\n\t\t\t\t\/\/ try with uLongF size 8\n\t\t\t\tuint8_t sizeOfULongf = 8;\n\t\t\t\terror = uncompress( (unsigned char*)ret.data(), &ret_size, src.data() + sizeOfULongf, src.size() );\n\t\t\t\t\n\t\t\t} else if (sizeof(uLongf) == 8) {\n\t\t\t\t\/\/ try with uLongF size 4\n\t\t\t\tuint8_t sizeOfULongf = 4;\n\t\t\t\terror = uncompress( (unsigned char*)ret.data(), &ret_size, src.data() + sizeOfULongf, src.size() );\n\t\t\t}\n\t\t\t\n\t\t\tif ( error == Z_OK )\n\t\t\t{\n\t\t\t\tret.resize( ret_size \/ sizeof(std::uint32_t), 0 );\n\t\t\t} else {\n\t\t\t\tofLogError( \"zipuncompress_uint32()\" ) << \"zlib uncompress() error: \" << error;\n\t\t\t\tret.clear();\n\t\t\t}\n\t\t}\n\t}\n}\n\n\n\/*\n *\/\nR2000DataReader::R2000DataReader() :\n\tdataStart(0)\n\t,count(0)\n\t,samplesPerScan(0)\n\t,scanFrequency(0)\n\t,updateTime(0)\n\t,lastUpdate(0)\n{}\n\nR2000DataReader::R2000DataReader(string& filepath) : R2000DataReader() {\n\t\n\tbool ret = load(filepath);\n}\n\n\nR2000DataReader::R2000DataReader(ofFile& file) : R2000DataReader() {\n\tload(file);\n}\n\nR2000DataReader::~R2000DataReader() {\n\tinfile.close();\n}\n\n\nbool R2000DataReader::load(const char* filepath) {\n\tstring p(filepath);\n\treturn load(p);\n}\n\nbool R2000DataReader::load(string& filepath) {\n\n\tbool ret = infile.open(filepath);\n\t\n\tif (ret){\n\t\tinitRead();\n\t}\n\t\n\treturn ret;\n}\n\nvoid R2000DataReader::load(ofFile& file) {\n\tinfile = file;\n\tinitRead();\n}\n\n\nvoid R2000DataReader::initRead() {\n\t\n\tif (!infile.isFile()) {\n\t\treturn;\n\t}\n\t\n\tuint8_t readSize;\n\t\n\tinfile.read((char*)&readSize, sizeof(uint8_t));\n\tinfile.read((char*)&samplesPerScan, readSize);\n\t\n\tinfile.read((char*)&readSize, sizeof(uint8_t));\n\tinfile.read((char*)&scanFrequency, readSize);\n\t\n\t\/\/----------------------------------------\n\t\/\/ check values\n\tbool correctValue = false;\n\tfor (int j=0; j<sps_size; j++) {\n\t\tif (samplesPerScan == sps[j]) {\n\t\t\tcorrectValue = true;\n\t\t\tbreak;\n\t\t}\n\t}\n\t\n\tif (scanFrequency < 10 || scanFrequency > 50) {\n\t\tcorrectValue = false;\n\t}\n\t\n\t\n\tif (!correctValue) {\n\t\tofLogError() << \"not a correct value\";\n\t\tOF_EXIT_APP(-1);\n\t}\n\n\tlastScanData.distance_data.resize(samplesPerScan);\n\tlastScanData.amplitude_data.resize(samplesPerScan);\n\t\n\t\/\/----------------------------------------\n\tupdateTime = 1000.0 \/ (double)scanFrequency;\n\tdataStart = infile.tellg();\n\tlastUpdate = ofGetElapsedTimeMillis() - updateTime;\n}\n\n\nbool R2000DataReader::update() {\n\t\n\tbool newScan = false;\n\t\n\tif ((double)(ofGetElapsedTimeMillis() - lastUpdate) >= updateTime) {\n\t\t\n\t\tlastUpdate = ofGetElapsedTimeMillis();\n\t\t\n\t\tbool doCompress = false;\n\t\t\n\t\tuint8_t readSize;\n\t\tstd::uint32_t vectorSize;\n\t\t\n\t\t\/\/----------------------------------------------------\n\t\t\/\/ get count\n\t\tinfile.read((char*)&readSize, sizeof(uint8_t));\n\t\t\/\/ check for eof, assume that data is alligned\n\t\tif (infile.eof()) {\n\t\t\tinfile.clear();\n\t\t\tinfile.seekg(dataStart);\n\t\t\t\n\t\t\t\/\/ read byte again\n\t\t\tinfile.read((char*)&readSize, sizeof(uint8_t));\n\t\t}\n\t\tinfile.read((char*)&count, readSize);\n\t\t\n\t\t\n\t\t\/\/----------------------------------------------------\n\t\t\/\/ distance data\n\t\t\n\t\t\/\/ compression-flag\n\t\tinfile.read((char*)&doCompress, 1);\n\t\t\n\t\tinfile.read((char*)&readSize, sizeof(uint8_t));\n\t\tinfile.read((char*)&vectorSize, readSize);\n\t\tif (doCompress) {\n\t\t\tstd::vector<unsigned char> data;\n\t\t\tdata.resize(vectorSize);\n\t\t\tinfile.read((char*)data.data(), vectorSize);\n\t\t\t\n\t\t\tzipuncompress_uint32(data, lastScanData.distance_data);\n\t\t\t\n\t\t\t\/\/ correct\n\t\t\tvectorSize = lastScanData.distance_data.size();\n\t\t} else {\n\t\t\tif (lastScanData.distance_data.size() != vectorSize) {\n\t\t\t\tofLogNotice() << \"resize distance vector\";\n\t\t\t\tlastScanData.distance_data.resize(vectorSize);\n\t\t\t}\n\t\t\tinfile.read((char*)lastScanData.distance_data.data(), (vectorSize * sizeof(std::uint32_t)));\n\t\t}\n\t\t\n\t\t\n\t\t\/\/----------------------------------------------------\n\t\t\/\/ amplitude data\n\t\t\n\t\t\/\/ compression-flag\n\t\tinfile.read((char*)&doCompress, 1);\n\t\t\n\t\tinfile.read((char*)&readSize, sizeof(uint8_t));\n\t\tinfile.read((char*)&vectorSize, readSize);\n\t\tif (doCompress) {\n\t\t\tstd::vector<unsigned char> data;\n\t\t\tdata.resize(vectorSize);\n\t\t\tinfile.read((char*)data.data(), vectorSize);\n\t\t\t\n\t\t\tzipuncompress_uint32(data, lastScanData.amplitude_data);\n\t\t\t\/\/ correct\n\t\t\tvectorSize = lastScanData.amplitude_data.size();\n\t\t} else {\n\t\t\tif (lastScanData.amplitude_data.size() != vectorSize) {\n\t\t\t\tofLogNotice() << \"resize amplitude vector\";\n\t\t\t\tlastScanData.amplitude_data.resize(vectorSize);\n\t\t\t}\n\t\t\tinfile.read((char*)lastScanData.amplitude_data.data(), (vectorSize * sizeof(std::uint32_t)));\n\t\t}\n\t\t\n\t\t\n\t\t\/\/----------------------------------------------------\n\t\t\/\/ header data\n\t\t\n\t\t\/\/ compression-flag\n\t\tinfile.read((char*)&doCompress, 1);\n\t\t\n\t\tinfile.read((char*)&readSize, sizeof(uint8_t));\n\t\tinfile.read((char*)&vectorSize, readSize);\n\t\tif (doCompress || !doCompress) {\n\t\t\tif (lastScanData.headers.size() != vectorSize) {\n\t\t\t\tlastScanData.headers.resize(vectorSize);\n\t\t\t}\n\t\t\tinfile.read((char*)lastScanData.headers.data(), (vectorSize * sizeof(PacketHeader)));\n\t\t}\n\t\t\/\/\t\tofLogNotice() << \"HEADERS: \" << vectorSize;\n\t\t\n\t\tnewScan = true;\n\t}\n\t\n\treturn newScan;\n}<|endoftext|>"} {"text":"<commit_before>#include \"memory.hpp\"\n#include <new>\n#include <atomic>\n\nnamespace warpcoil\n{\n namespace\n {\n std::atomic<std::uint64_t> allocation_counter;\n }\n\n std::uint64_t number_of_allocations()\n {\n return allocation_counter.load();\n }\n}\n\nvoid *operator new(std::size_t count)\n{\n ++warpcoil::allocation_counter;\n return std::malloc(count);\n}\n\nvoid *operator new[](std::size_t count)\n{\n ++warpcoil::allocation_counter;\n return std::malloc(count);\n}\n\nvoid operator delete(void *ptr)\n{\n std::free(ptr);\n}\n\nvoid operator delete[](void *ptr)\n{\n std::free(ptr);\n}\n<commit_msg>#include for GCC<commit_after>#include \"memory.hpp\"\n#include <new>\n#include <atomic>\n#include <cstdlib>\n\nnamespace warpcoil\n{\n namespace\n {\n std::atomic<std::uint64_t> allocation_counter;\n }\n\n std::uint64_t number_of_allocations()\n {\n return allocation_counter.load();\n }\n}\n\nvoid *operator new(std::size_t count)\n{\n ++warpcoil::allocation_counter;\n return std::malloc(count);\n}\n\nvoid *operator new[](std::size_t count)\n{\n ++warpcoil::allocation_counter;\n return std::malloc(count);\n}\n\nvoid operator delete(void *ptr)\n{\n std::free(ptr);\n}\n\nvoid operator delete[](void *ptr)\n{\n std::free(ptr);\n}\n<|endoftext|>"} {"text":"<commit_before>\n#include \"..\/msdfgen.h\"\n\n#include <vector>\n#include \"edge-selectors.h\"\n#include \"contour-combiners.h\"\n\nnamespace msdfgen {\n\ntemplate <typename DistanceType>\nclass DistancePixelConversion;\n\ntemplate <>\nclass DistancePixelConversion<double> {\npublic:\n typedef float PixelType;\n inline static PixelType convert(double distance, double range) {\n return PixelType(distance\/range+.5);\n }\n};\n\ntemplate <>\nclass DistancePixelConversion<MultiDistance> {\npublic:\n typedef FloatRGB PixelType;\n inline static PixelType convert(const MultiDistance &distance, double range) {\n PixelType pixel;\n pixel.r = float(distance.r\/range+.5);\n pixel.g = float(distance.g\/range+.5);\n pixel.b = float(distance.b\/range+.5);\n return pixel;\n }\n};\n\ntemplate <class ContourCombiner>\nvoid generateDistanceField(Bitmap<typename DistancePixelConversion<typename ContourCombiner::DistanceType>::PixelType> &output, const Shape &shape, double range, const Vector2 &scale, const Vector2 &translate) {\n int w = output.width(), h = output.height();\n\n#ifdef MSDFGEN_USE_OPENMP\n #pragma omp parallel\n#endif\n {\n ContourCombiner contourCombiner(shape);\n Point2 p;\n#ifdef MSDFGEN_USE_OPENMP\n #pragma omp for\n#endif\n for (int y = 0; y < h; ++y) {\n int row = shape.inverseYAxis ? h-y-1 : y;\n p.y = (y+.5)\/scale.y-translate.y;\n for (int x = 0; x < w; ++x) {\n p.x = (x+.5)\/scale.x-translate.x;\n\n contourCombiner.reset(p);\n\n for (std::vector<Contour>::const_iterator contour = shape.contours.begin(); contour != shape.contours.end(); ++contour) {\n if (!contour->edges.empty()) {\n ContourCombiner::EdgeSelectorType edgeSelector(p);\n\n const EdgeSegment *prevEdge = contour->edges.size() >= 2 ? *(contour->edges.end()-2) : *contour->edges.begin();\n const EdgeSegment *curEdge = contour->edges.back();\n for (std::vector<EdgeHolder>::const_iterator edge = contour->edges.begin(); edge != contour->edges.end(); ++edge) {\n const EdgeSegment *nextEdge = *edge;\n edgeSelector.addEdge(prevEdge, curEdge, nextEdge);\n prevEdge = curEdge;\n curEdge = nextEdge;\n }\n\n contourCombiner.setContourEdge(int(contour-shape.contours.begin()), edgeSelector);\n }\n }\n\n ContourCombiner::DistanceType distance = contourCombiner.distance();\n output(x, row) = DistancePixelConversion<ContourCombiner::DistanceType>::convert(distance, range);\n }\n }\n }\n}\n\nvoid generateSDF(Bitmap<float> &output, const Shape &shape, double range, const Vector2 &scale, const Vector2 &translate, bool overlapSupport) {\n if (overlapSupport)\n generateDistanceField<OverlappingContourCombiner<TrueDistanceSelector> >(output, shape, range, scale, translate);\n else\n generateDistanceField<SimpleContourCombiner<TrueDistanceSelector> >(output, shape, range, scale, translate);\n}\n\nvoid generatePseudoSDF(Bitmap<float> &output, const Shape &shape, double range, const Vector2 &scale, const Vector2 &translate, bool overlapSupport) {\n if (overlapSupport)\n generateDistanceField<OverlappingContourCombiner<PseudoDistanceSelector> >(output, shape, range, scale, translate);\n else\n generateDistanceField<SimpleContourCombiner<PseudoDistanceSelector> >(output, shape, range, scale, translate);\n}\n\nvoid generateMSDF(Bitmap<FloatRGB> &output, const Shape &shape, double range, const Vector2 &scale, const Vector2 &translate, double edgeThreshold, bool overlapSupport) {\n if (overlapSupport)\n generateDistanceField<OverlappingContourCombiner<MultiDistanceSelector> >(output, shape, range, scale, translate);\n else\n generateDistanceField<SimpleContourCombiner<MultiDistanceSelector> >(output, shape, range, scale, translate);\n if (edgeThreshold > 0)\n msdfErrorCorrection(output, edgeThreshold\/(scale*range));\n}\n\ninline static bool detectClash(const FloatRGB &a, const FloatRGB &b, double threshold) {\n \/\/ Sort channels so that pairs (a0, b0), (a1, b1), (a2, b2) go from biggest to smallest absolute difference\n float a0 = a.r, a1 = a.g, a2 = a.b;\n float b0 = b.r, b1 = b.g, b2 = b.b;\n float tmp;\n if (fabsf(b0-a0) < fabsf(b1-a1)) {\n tmp = a0, a0 = a1, a1 = tmp;\n tmp = b0, b0 = b1, b1 = tmp;\n }\n if (fabsf(b1-a1) < fabsf(b2-a2)) {\n tmp = a1, a1 = a2, a2 = tmp;\n tmp = b1, b1 = b2, b2 = tmp;\n if (fabsf(b0-a0) < fabsf(b1-a1)) {\n tmp = a0, a0 = a1, a1 = tmp;\n tmp = b0, b0 = b1, b1 = tmp;\n }\n }\n return (fabsf(b1-a1) >= threshold) &&\n !(b0 == b1 && b0 == b2) && \/\/ Ignore if other pixel has been equalized\n fabsf(a2-.5f) >= fabsf(b2-.5f); \/\/ Out of the pair, only flag the pixel farther from a shape edge\n}\n\nvoid msdfErrorCorrection(Bitmap<FloatRGB> &output, const Vector2 &threshold) {\n std::vector<std::pair<int, int> > clashes;\n int w = output.width(), h = output.height();\n for (int y = 0; y < h; ++y)\n for (int x = 0; x < w; ++x) {\n if (\n (x > 0 && detectClash(output(x, y), output(x-1, y), threshold.x)) ||\n (x < w-1 && detectClash(output(x, y), output(x+1, y), threshold.x)) ||\n (y > 0 && detectClash(output(x, y), output(x, y-1), threshold.y)) ||\n (y < h-1 && detectClash(output(x, y), output(x, y+1), threshold.y))\n )\n clashes.push_back(std::make_pair(x, y));\n }\n for (std::vector<std::pair<int, int> >::const_iterator clash = clashes.begin(); clash != clashes.end(); ++clash) {\n FloatRGB &pixel = output(clash->first, clash->second);\n float med = median(pixel.r, pixel.g, pixel.b);\n pixel.r = med, pixel.g = med, pixel.b = med;\n }\n#ifndef MSDFGEN_NO_DIAGONAL_CLASH_DETECTION\n clashes.clear();\n for (int y = 0; y < h; ++y)\n for (int x = 0; x < w; ++x) {\n if (\n (x > 0 && y > 0 && detectClash(output(x, y), output(x-1, y-1), threshold.x+threshold.y)) ||\n (x < w-1 && y > 0 && detectClash(output(x, y), output(x+1, y-1), threshold.x+threshold.y)) ||\n (x > 0 && y < h-1 && detectClash(output(x, y), output(x-1, y+1), threshold.x+threshold.y)) ||\n (x < w-1 && y < h-1 && detectClash(output(x, y), output(x+1, y+1), threshold.x+threshold.y))\n )\n clashes.push_back(std::make_pair(x, y));\n }\n for (std::vector<std::pair<int, int> >::const_iterator clash = clashes.begin(); clash != clashes.end(); ++clash) {\n FloatRGB &pixel = output(clash->first, clash->second);\n float med = median(pixel.r, pixel.g, pixel.b);\n pixel.r = med, pixel.g = med, pixel.b = med;\n }\n#endif\n}\n\n\/\/ Legacy version\n\nvoid generateSDF_legacy(Bitmap<float> &output, const Shape &shape, double range, const Vector2 &scale, const Vector2 &translate) {\n int w = output.width(), h = output.height();\n#ifdef MSDFGEN_USE_OPENMP\n #pragma omp parallel for\n#endif\n for (int y = 0; y < h; ++y) {\n int row = shape.inverseYAxis ? h-y-1 : y;\n for (int x = 0; x < w; ++x) {\n double dummy;\n Point2 p = Vector2(x+.5, y+.5)\/scale-translate;\n SignedDistance minDistance;\n for (std::vector<Contour>::const_iterator contour = shape.contours.begin(); contour != shape.contours.end(); ++contour)\n for (std::vector<EdgeHolder>::const_iterator edge = contour->edges.begin(); edge != contour->edges.end(); ++edge) {\n SignedDistance distance = (*edge)->signedDistance(p, dummy);\n if (distance < minDistance)\n minDistance = distance;\n }\n output(x, row) = float(minDistance.distance\/range+.5);\n }\n }\n}\n\nvoid generatePseudoSDF_legacy(Bitmap<float> &output, const Shape &shape, double range, const Vector2 &scale, const Vector2 &translate) {\n int w = output.width(), h = output.height();\n#ifdef MSDFGEN_USE_OPENMP\n #pragma omp parallel for\n#endif\n for (int y = 0; y < h; ++y) {\n int row = shape.inverseYAxis ? h-y-1 : y;\n for (int x = 0; x < w; ++x) {\n Point2 p = Vector2(x+.5, y+.5)\/scale-translate;\n SignedDistance minDistance;\n const EdgeHolder *nearEdge = NULL;\n double nearParam = 0;\n for (std::vector<Contour>::const_iterator contour = shape.contours.begin(); contour != shape.contours.end(); ++contour)\n for (std::vector<EdgeHolder>::const_iterator edge = contour->edges.begin(); edge != contour->edges.end(); ++edge) {\n double param;\n SignedDistance distance = (*edge)->signedDistance(p, param);\n if (distance < minDistance) {\n minDistance = distance;\n nearEdge = &*edge;\n nearParam = param;\n }\n }\n if (nearEdge)\n (*nearEdge)->distanceToPseudoDistance(minDistance, p, nearParam);\n output(x, row) = float(minDistance.distance\/range+.5);\n }\n }\n}\n\nvoid generateMSDF_legacy(Bitmap<FloatRGB> &output, const Shape &shape, double range, const Vector2 &scale, const Vector2 &translate, double edgeThreshold) {\n int w = output.width(), h = output.height();\n#ifdef MSDFGEN_USE_OPENMP\n #pragma omp parallel for\n#endif\n for (int y = 0; y < h; ++y) {\n int row = shape.inverseYAxis ? h-y-1 : y;\n for (int x = 0; x < w; ++x) {\n Point2 p = Vector2(x+.5, y+.5)\/scale-translate;\n\n struct {\n SignedDistance minDistance;\n const EdgeHolder *nearEdge;\n double nearParam;\n } r, g, b;\n r.nearEdge = g.nearEdge = b.nearEdge = NULL;\n r.nearParam = g.nearParam = b.nearParam = 0;\n\n for (std::vector<Contour>::const_iterator contour = shape.contours.begin(); contour != shape.contours.end(); ++contour)\n for (std::vector<EdgeHolder>::const_iterator edge = contour->edges.begin(); edge != contour->edges.end(); ++edge) {\n double param;\n SignedDistance distance = (*edge)->signedDistance(p, param);\n if ((*edge)->color&RED && distance < r.minDistance) {\n r.minDistance = distance;\n r.nearEdge = &*edge;\n r.nearParam = param;\n }\n if ((*edge)->color&GREEN && distance < g.minDistance) {\n g.minDistance = distance;\n g.nearEdge = &*edge;\n g.nearParam = param;\n }\n if ((*edge)->color&BLUE && distance < b.minDistance) {\n b.minDistance = distance;\n b.nearEdge = &*edge;\n b.nearParam = param;\n }\n }\n\n if (r.nearEdge)\n (*r.nearEdge)->distanceToPseudoDistance(r.minDistance, p, r.nearParam);\n if (g.nearEdge)\n (*g.nearEdge)->distanceToPseudoDistance(g.minDistance, p, g.nearParam);\n if (b.nearEdge)\n (*b.nearEdge)->distanceToPseudoDistance(b.minDistance, p, b.nearParam);\n output(x, row).r = float(r.minDistance.distance\/range+.5);\n output(x, row).g = float(g.minDistance.distance\/range+.5);\n output(x, row).b = float(b.minDistance.distance\/range+.5);\n }\n }\n\n if (edgeThreshold > 0)\n msdfErrorCorrection(output, edgeThreshold\/(scale*range));\n}\n\n}\n<commit_msg>Add missing typenames for dependent types<commit_after>\n#include \"..\/msdfgen.h\"\n\n#include <vector>\n#include \"edge-selectors.h\"\n#include \"contour-combiners.h\"\n\nnamespace msdfgen {\n\ntemplate <typename DistanceType>\nclass DistancePixelConversion;\n\ntemplate <>\nclass DistancePixelConversion<double> {\npublic:\n typedef float PixelType;\n inline static PixelType convert(double distance, double range) {\n return PixelType(distance\/range+.5);\n }\n};\n\ntemplate <>\nclass DistancePixelConversion<MultiDistance> {\npublic:\n typedef FloatRGB PixelType;\n inline static PixelType convert(const MultiDistance &distance, double range) {\n PixelType pixel;\n pixel.r = float(distance.r\/range+.5);\n pixel.g = float(distance.g\/range+.5);\n pixel.b = float(distance.b\/range+.5);\n return pixel;\n }\n};\n\ntemplate <class ContourCombiner>\nvoid generateDistanceField(Bitmap<typename DistancePixelConversion<typename ContourCombiner::DistanceType>::PixelType> &output, const Shape &shape, double range, const Vector2 &scale, const Vector2 &translate) {\n int w = output.width(), h = output.height();\n\n#ifdef MSDFGEN_USE_OPENMP\n #pragma omp parallel\n#endif\n {\n ContourCombiner contourCombiner(shape);\n Point2 p;\n#ifdef MSDFGEN_USE_OPENMP\n #pragma omp for\n#endif\n for (int y = 0; y < h; ++y) {\n int row = shape.inverseYAxis ? h-y-1 : y;\n p.y = (y+.5)\/scale.y-translate.y;\n for (int x = 0; x < w; ++x) {\n p.x = (x+.5)\/scale.x-translate.x;\n\n contourCombiner.reset(p);\n\n for (std::vector<Contour>::const_iterator contour = shape.contours.begin(); contour != shape.contours.end(); ++contour) {\n if (!contour->edges.empty()) {\n typename ContourCombiner::EdgeSelectorType edgeSelector(p);\n\n const EdgeSegment *prevEdge = contour->edges.size() >= 2 ? *(contour->edges.end()-2) : *contour->edges.begin();\n const EdgeSegment *curEdge = contour->edges.back();\n for (std::vector<EdgeHolder>::const_iterator edge = contour->edges.begin(); edge != contour->edges.end(); ++edge) {\n const EdgeSegment *nextEdge = *edge;\n edgeSelector.addEdge(prevEdge, curEdge, nextEdge);\n prevEdge = curEdge;\n curEdge = nextEdge;\n }\n\n contourCombiner.setContourEdge(int(contour-shape.contours.begin()), edgeSelector);\n }\n }\n\n typename ContourCombiner::DistanceType distance = contourCombiner.distance();\n output(x, row) = DistancePixelConversion<typename ContourCombiner::DistanceType>::convert(distance, range);\n }\n }\n }\n}\n\nvoid generateSDF(Bitmap<float> &output, const Shape &shape, double range, const Vector2 &scale, const Vector2 &translate, bool overlapSupport) {\n if (overlapSupport)\n generateDistanceField<OverlappingContourCombiner<TrueDistanceSelector> >(output, shape, range, scale, translate);\n else\n generateDistanceField<SimpleContourCombiner<TrueDistanceSelector> >(output, shape, range, scale, translate);\n}\n\nvoid generatePseudoSDF(Bitmap<float> &output, const Shape &shape, double range, const Vector2 &scale, const Vector2 &translate, bool overlapSupport) {\n if (overlapSupport)\n generateDistanceField<OverlappingContourCombiner<PseudoDistanceSelector> >(output, shape, range, scale, translate);\n else\n generateDistanceField<SimpleContourCombiner<PseudoDistanceSelector> >(output, shape, range, scale, translate);\n}\n\nvoid generateMSDF(Bitmap<FloatRGB> &output, const Shape &shape, double range, const Vector2 &scale, const Vector2 &translate, double edgeThreshold, bool overlapSupport) {\n if (overlapSupport)\n generateDistanceField<OverlappingContourCombiner<MultiDistanceSelector> >(output, shape, range, scale, translate);\n else\n generateDistanceField<SimpleContourCombiner<MultiDistanceSelector> >(output, shape, range, scale, translate);\n if (edgeThreshold > 0)\n msdfErrorCorrection(output, edgeThreshold\/(scale*range));\n}\n\ninline static bool detectClash(const FloatRGB &a, const FloatRGB &b, double threshold) {\n \/\/ Sort channels so that pairs (a0, b0), (a1, b1), (a2, b2) go from biggest to smallest absolute difference\n float a0 = a.r, a1 = a.g, a2 = a.b;\n float b0 = b.r, b1 = b.g, b2 = b.b;\n float tmp;\n if (fabsf(b0-a0) < fabsf(b1-a1)) {\n tmp = a0, a0 = a1, a1 = tmp;\n tmp = b0, b0 = b1, b1 = tmp;\n }\n if (fabsf(b1-a1) < fabsf(b2-a2)) {\n tmp = a1, a1 = a2, a2 = tmp;\n tmp = b1, b1 = b2, b2 = tmp;\n if (fabsf(b0-a0) < fabsf(b1-a1)) {\n tmp = a0, a0 = a1, a1 = tmp;\n tmp = b0, b0 = b1, b1 = tmp;\n }\n }\n return (fabsf(b1-a1) >= threshold) &&\n !(b0 == b1 && b0 == b2) && \/\/ Ignore if other pixel has been equalized\n fabsf(a2-.5f) >= fabsf(b2-.5f); \/\/ Out of the pair, only flag the pixel farther from a shape edge\n}\n\nvoid msdfErrorCorrection(Bitmap<FloatRGB> &output, const Vector2 &threshold) {\n std::vector<std::pair<int, int> > clashes;\n int w = output.width(), h = output.height();\n for (int y = 0; y < h; ++y)\n for (int x = 0; x < w; ++x) {\n if (\n (x > 0 && detectClash(output(x, y), output(x-1, y), threshold.x)) ||\n (x < w-1 && detectClash(output(x, y), output(x+1, y), threshold.x)) ||\n (y > 0 && detectClash(output(x, y), output(x, y-1), threshold.y)) ||\n (y < h-1 && detectClash(output(x, y), output(x, y+1), threshold.y))\n )\n clashes.push_back(std::make_pair(x, y));\n }\n for (std::vector<std::pair<int, int> >::const_iterator clash = clashes.begin(); clash != clashes.end(); ++clash) {\n FloatRGB &pixel = output(clash->first, clash->second);\n float med = median(pixel.r, pixel.g, pixel.b);\n pixel.r = med, pixel.g = med, pixel.b = med;\n }\n#ifndef MSDFGEN_NO_DIAGONAL_CLASH_DETECTION\n clashes.clear();\n for (int y = 0; y < h; ++y)\n for (int x = 0; x < w; ++x) {\n if (\n (x > 0 && y > 0 && detectClash(output(x, y), output(x-1, y-1), threshold.x+threshold.y)) ||\n (x < w-1 && y > 0 && detectClash(output(x, y), output(x+1, y-1), threshold.x+threshold.y)) ||\n (x > 0 && y < h-1 && detectClash(output(x, y), output(x-1, y+1), threshold.x+threshold.y)) ||\n (x < w-1 && y < h-1 && detectClash(output(x, y), output(x+1, y+1), threshold.x+threshold.y))\n )\n clashes.push_back(std::make_pair(x, y));\n }\n for (std::vector<std::pair<int, int> >::const_iterator clash = clashes.begin(); clash != clashes.end(); ++clash) {\n FloatRGB &pixel = output(clash->first, clash->second);\n float med = median(pixel.r, pixel.g, pixel.b);\n pixel.r = med, pixel.g = med, pixel.b = med;\n }\n#endif\n}\n\n\/\/ Legacy version\n\nvoid generateSDF_legacy(Bitmap<float> &output, const Shape &shape, double range, const Vector2 &scale, const Vector2 &translate) {\n int w = output.width(), h = output.height();\n#ifdef MSDFGEN_USE_OPENMP\n #pragma omp parallel for\n#endif\n for (int y = 0; y < h; ++y) {\n int row = shape.inverseYAxis ? h-y-1 : y;\n for (int x = 0; x < w; ++x) {\n double dummy;\n Point2 p = Vector2(x+.5, y+.5)\/scale-translate;\n SignedDistance minDistance;\n for (std::vector<Contour>::const_iterator contour = shape.contours.begin(); contour != shape.contours.end(); ++contour)\n for (std::vector<EdgeHolder>::const_iterator edge = contour->edges.begin(); edge != contour->edges.end(); ++edge) {\n SignedDistance distance = (*edge)->signedDistance(p, dummy);\n if (distance < minDistance)\n minDistance = distance;\n }\n output(x, row) = float(minDistance.distance\/range+.5);\n }\n }\n}\n\nvoid generatePseudoSDF_legacy(Bitmap<float> &output, const Shape &shape, double range, const Vector2 &scale, const Vector2 &translate) {\n int w = output.width(), h = output.height();\n#ifdef MSDFGEN_USE_OPENMP\n #pragma omp parallel for\n#endif\n for (int y = 0; y < h; ++y) {\n int row = shape.inverseYAxis ? h-y-1 : y;\n for (int x = 0; x < w; ++x) {\n Point2 p = Vector2(x+.5, y+.5)\/scale-translate;\n SignedDistance minDistance;\n const EdgeHolder *nearEdge = NULL;\n double nearParam = 0;\n for (std::vector<Contour>::const_iterator contour = shape.contours.begin(); contour != shape.contours.end(); ++contour)\n for (std::vector<EdgeHolder>::const_iterator edge = contour->edges.begin(); edge != contour->edges.end(); ++edge) {\n double param;\n SignedDistance distance = (*edge)->signedDistance(p, param);\n if (distance < minDistance) {\n minDistance = distance;\n nearEdge = &*edge;\n nearParam = param;\n }\n }\n if (nearEdge)\n (*nearEdge)->distanceToPseudoDistance(minDistance, p, nearParam);\n output(x, row) = float(minDistance.distance\/range+.5);\n }\n }\n}\n\nvoid generateMSDF_legacy(Bitmap<FloatRGB> &output, const Shape &shape, double range, const Vector2 &scale, const Vector2 &translate, double edgeThreshold) {\n int w = output.width(), h = output.height();\n#ifdef MSDFGEN_USE_OPENMP\n #pragma omp parallel for\n#endif\n for (int y = 0; y < h; ++y) {\n int row = shape.inverseYAxis ? h-y-1 : y;\n for (int x = 0; x < w; ++x) {\n Point2 p = Vector2(x+.5, y+.5)\/scale-translate;\n\n struct {\n SignedDistance minDistance;\n const EdgeHolder *nearEdge;\n double nearParam;\n } r, g, b;\n r.nearEdge = g.nearEdge = b.nearEdge = NULL;\n r.nearParam = g.nearParam = b.nearParam = 0;\n\n for (std::vector<Contour>::const_iterator contour = shape.contours.begin(); contour != shape.contours.end(); ++contour)\n for (std::vector<EdgeHolder>::const_iterator edge = contour->edges.begin(); edge != contour->edges.end(); ++edge) {\n double param;\n SignedDistance distance = (*edge)->signedDistance(p, param);\n if ((*edge)->color&RED && distance < r.minDistance) {\n r.minDistance = distance;\n r.nearEdge = &*edge;\n r.nearParam = param;\n }\n if ((*edge)->color&GREEN && distance < g.minDistance) {\n g.minDistance = distance;\n g.nearEdge = &*edge;\n g.nearParam = param;\n }\n if ((*edge)->color&BLUE && distance < b.minDistance) {\n b.minDistance = distance;\n b.nearEdge = &*edge;\n b.nearParam = param;\n }\n }\n\n if (r.nearEdge)\n (*r.nearEdge)->distanceToPseudoDistance(r.minDistance, p, r.nearParam);\n if (g.nearEdge)\n (*g.nearEdge)->distanceToPseudoDistance(g.minDistance, p, g.nearParam);\n if (b.nearEdge)\n (*b.nearEdge)->distanceToPseudoDistance(b.minDistance, p, b.nearParam);\n output(x, row).r = float(r.minDistance.distance\/range+.5);\n output(x, row).g = float(g.minDistance.distance\/range+.5);\n output(x, row).b = float(b.minDistance.distance\/range+.5);\n }\n }\n\n if (edgeThreshold > 0)\n msdfErrorCorrection(output, edgeThreshold\/(scale*range));\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before>#include <fcntl.h>\n#include <getopt.h>\n#include <string.h>\n#include <sys\/types.h>\n#include <unistd.h>\n#include <wait.h>\n\n#include <iostream>\n#include <string>\n#include <vector>\n\n#include \"..\/utils\/utils.h\"\n#include \"Tester.h\"\n#include \"..\/tests\/BaseTestCase.h\"\n\n#define TEST_SO_PATH \"tests\/\"\n#define PERMUTER_SO_PATH \"permuter\/\"\n\/\/ TODO(ashmrtn): Find a good delay time to use for tests.\n#define TEST_DIRTY_EXPIRE_TIME \"500\"\n#define WRITE_DELAY 30\n#define MOUNT_DELAY WRITE_DELAY\n\n#define OPTS_STRING \"d:l:m:np:r:st:v\"\n\nusing std::cerr;\nusing std::cout;\nusing std::endl;\nusing std::string;\nusing fs_testing::Tester;\n\nstatic const option long_options[] = {\n {\"no-snap\", no_argument, NULL, 's'},\n {\"dry-run\", no_argument, NULL, 'n'},\n {\"verbose\", no_argument, NULL, 'v'},\n {\"fs-type\", required_argument, NULL, 't'},\n {\"test-dev\", required_argument, NULL, 'd'},\n {\"log-file\", required_argument, NULL, 'l'},\n {\"reload-log-file\", required_argument, NULL, 'r'},\n {\"mount-opts\", required_argument, NULL, 'm'},\n {\"permuter\", required_argument, NULL, 'p'},\n {0, 0, 0, 0},\n};\n\nint main(int argc, char** argv) {\n string dirty_expire_time_centisecs(TEST_DIRTY_EXPIRE_TIME);\n unsigned long int test_sleep_delay = WRITE_DELAY;\n string fs_type(\"ext4\");\n string test_dev(\"\/dev\/ram0\");\n string mount_opts(\"\");\n string log_file_save(\"\");\n string log_file_load(\"\");\n string permuter(PERMUTER_SO_PATH \"RandomPermuter.so\");\n bool dry_run = false;\n bool no_lvm = false;\n bool no_snap = false;\n bool verbose = false;\n\n int option_idx = 0;\n\n \/\/ Parse command line arguments.\n for (int c = getopt_long(argc, argv, OPTS_STRING, long_options, &option_idx);\n c != -1;\n c = getopt_long(argc, argv, OPTS_STRING, long_options, &option_idx)) {\n switch (c) {\n case 'd':\n test_dev = string(optarg);\n break;\n case 'l':\n log_file_save = string(optarg);\n break;\n case 'm':\n mount_opts = string(optarg);\n break;\n case 'n':\n dry_run = 1;\n break;\n case 'p':\n permuter = string(optarg);\n break;\n case 'r':\n log_file_load = string(optarg);\n break;\n case 's':\n no_snap = 1;\n dry_run = 1;\n break;\n case 't':\n fs_type = string(optarg);\n break;\n case 'v':\n verbose = true;\n break;\n case '?':\n default:\n return -1;\n }\n }\n\n const unsigned int test_case_idx = optind;\n\n if (test_case_idx == argc) {\n cerr << \"Please give a .so test case to load\" << endl;\n return -1;\n }\n\n Tester test_harness(verbose);\n test_harness.set_fs_type(fs_type);\n test_harness.set_device(test_dev);\n\n \/\/ Load the class being tested.\n cout << \"Loading test case\" << endl;\n if (test_harness.test_load_class(argv[test_case_idx]) != SUCCESS) {\n test_harness.cleanup_harness();\n return -1;\n }\n\n \/\/ Load the permuter to use for the test.\n \/\/ TODO(ashmrtn): Consider making a line in the test file which specifies the\n \/\/ permuter to use?\n cout << \"Loading permuter\" << endl;\n if (test_harness.permuter_load_class(permuter.c_str()) != SUCCESS) {\n test_harness.cleanup_harness();\n return -1;\n }\n\n \/\/ Update dirty_expire_time.\n cout << \"Updating dirty_expire_time_centisecs\" << endl;\n const char* old_expire_time =\n test_harness.update_dirty_expire_time(dirty_expire_time_centisecs.c_str());\n if (old_expire_time == NULL) {\n cerr << \"Error updating dirty_expire_time_centisecs\" << endl;\n test_harness.cleanup_harness();\n return -1;\n }\n\n \/\/ Partition drive.\n \/\/ TODO(ashmrtn): Consider making a flag for this?\n cout << \"Wiping test device\" << endl;\n if (test_harness.wipe_partitions() != SUCCESS) {\n cerr << \"Error wiping paritions on test device\" << endl;\n test_harness.cleanup_harness();\n return -1;\n }\n\n \/\/ Run the normal test setup stuff if we don't have a log file.\n if (log_file_load.empty()) {\n\n \/\/ Create a new partition table on test device.\n cout << \"Partitioning test drive\" << endl;\n if (test_harness.partition_drive() != SUCCESS) {\n test_harness.cleanup_harness();\n return -1;\n }\n\n \/\/ Format test drive to desired type.\n cout << \"Formatting test drive\" << endl;\n if (test_harness.format_drive() != SUCCESS) {\n cerr << \"Error formatting test drive\" << endl;\n test_harness.cleanup_harness();\n return -1;\n }\n\n \/\/ Mount test file system for pre-test setup.\n cout << \"Mounting test file system for pre-test setup\\n\";\n if (test_harness.mount_device_raw(mount_opts.c_str()) != SUCCESS) {\n cerr << \"Error mounting test device\" << endl;\n test_harness.cleanup_harness();\n return -1;\n }\n\n \/\/ Run pre-test setup stuff.\n cout << \"Running pre-test setup\\n\";\n {\n const pid_t child = fork();\n if (child < 0) {\n cerr << \"Error creating child process to run pre-test setup\\n\";\n test_harness.cleanup_harness();\n } else if (child != 0) {\n \/\/ Parent process should wait for child to terminate before proceeding.\n pid_t status;\n wait(&status);\n if (status != 0) {\n cerr << \"Error in pre-test setup\\n\";\n test_harness.cleanup_harness();\n }\n } else {\n return test_harness.test_setup();\n }\n }\n\n \/\/ Unmount the test file system after pre-test setup.\n cout << \"Unmounting test file system after pre-test setup\\n\";\n if (test_harness.umount_device() != SUCCESS) {\n test_harness.cleanup_harness();\n return -1;\n }\n\n \/\/ Create snapshot of disk for testing.\n if (!no_snap) {\n cout << \"Making new snapshot\\n\";\n if (test_harness.clone_device() != SUCCESS) {\n test_harness.cleanup_harness();\n return -1;\n }\n\n \/\/ If we're logging this test run then also save the snapshot.\n if (!log_file_save.empty()) {\n cout << \"Saving snapshot to log file\" << endl;\n if (test_harness.log_snapshot_save(log_file_save + \"_snap\")\n != SUCCESS) {\n test_harness.cleanup_harness();\n return -1;\n }\n }\n }\n } else {\n \/\/ Load the snapshot in the log file and then write it to disk.\n cout << \"Loading saved snapshot\" << endl;\n if (test_harness.log_snapshot_load(log_file_load + \"_snap\") != SUCCESS) {\n test_harness.cleanup_harness();\n return -1;\n }\n cout << \"Restoring disk snapshot\" << endl;\n if (test_harness.clone_device_restore(true) != SUCCESS) {\n test_harness.cleanup_harness();\n return -1;\n }\n }\n\n \/\/ TODO(ashmrtn): Consider making a flag for this?\n cout << \"Clearing caches\" << endl;\n if (test_harness.clear_caches() != SUCCESS) {\n cerr << \"Error clearing caches\" << endl;\n test_harness.cleanup_harness();\n return -1;\n }\n\n\n \/\/ No log file given so run the test profile.\n if (log_file_load.empty()) {\n\n \/\/ Insert the disk block wrapper into the kernel.\n cout << \"Inserting wrapper module into kernel\\n\";\n if (test_harness.insert_wrapper() != SUCCESS) {\n cerr << \"Error inserting kernel wrapper module\\n\";\n test_harness.cleanup_harness();\n return -1;\n }\n\n \/\/ Mount the file system under the wrapper module for profiling.\n cout << \"Mounting wrapper file system\\n\";\n if (test_harness.mount_wrapper_device(mount_opts.c_str()) != SUCCESS) {\n cerr << \"Error mounting wrapper file system\\n\";\n test_harness.cleanup_harness();\n return -1;\n }\n\n cout << \"Sleeping after mount\" << endl;\n unsigned int to_sleep = MOUNT_DELAY;\n do {\n to_sleep = sleep(to_sleep);\n } while (to_sleep > 0);\n\n \/\/ Get access to wrapper module ioctl functions via FD.\n cout << \"Getting wrapper device ioctl fd\\n\";\n if (test_harness.get_wrapper_ioctl() != SUCCESS) {\n cerr << \"Error opening device file\\n\";\n test_harness.cleanup_harness();\n return -1;\n }\n\n \/\/ Clear wrapper module logs prior to test profiling.\n cout << \"Clearing wrapper device logs\\n\";\n test_harness.clear_wrapper_log();\n cout << \"Enabling wrapper device logging\\n\";\n test_harness.begin_wrapper_logging();\n\n \/\/ Fork off a new process and run test profiling. Forking makes it easier to\n \/\/ handle making sure everything is taken care of in profiling and ensures\n \/\/ that even if all file handles aren't closed in the test process the parent\n \/\/ won't hang due to a busy mount point.\n cout << \"Running test profile\\n\";\n {\n const pid_t child = fork();\n if (child < 0) {\n cerr << \"Error spinning off test process\\n\";\n test_harness.cleanup_harness();\n return -1;\n } else if (child != 0) {\n pid_t status;\n wait(&status);\n if (status != 0) {\n cerr << \"Error in test process\\n\";\n test_harness.cleanup_harness();\n return -1;\n }\n sleep(WRITE_DELAY);\n } else {\n \/\/ Forked process' stuff.\n return test_harness.test_run();\n }\n }\n\n cout << \"Unmounting wrapper file system after test profiling\\n\";\n if (test_harness.umount_device() != SUCCESS) {\n cerr << \"Error unmounting wrapper file system\\n\";\n test_harness.cleanup_harness();\n return -1;\n }\n\n cout << \"Disabling wrapper device logging\" << std::endl;\n test_harness.end_wrapper_logging();\n cout << \"Getting wrapper data\\n\";\n if (test_harness.get_wrapper_log() != SUCCESS) {\n test_harness.cleanup_harness();\n return -1;\n }\n\n cout << \"Close wrapper ioctl fd\\n\";\n test_harness.put_wrapper_ioctl();\n cout << \"Removing wrapper module from kernel\\n\";\n if (test_harness.remove_wrapper() != SUCCESS) {\n cerr << \"Error cleaning up: remove wrapper module\\n\";\n test_harness.cleanup_harness();\n return -1;\n }\n\n \/\/ Write log data out to file if we're given a file.\n if (!log_file_save.empty()) {\n cout << \"Saving logged profile data to disk\" << endl;\n if (test_harness.log_profile_save(log_file_save + \"_profile\") != SUCCESS) {\n cerr << \"Error saving logged test file\" << endl;\n \/\/ TODO(ashmrtn): Remove this in later versions?\n test_harness.cleanup_harness();\n return -1;\n }\n }\n } else {\n \/\/ Logged test data given, load it into the test harness.\n cout << \"Loading logged profile data from disk\" << endl;\n if (test_harness.log_profile_load(log_file_load + \"_profile\") != SUCCESS) {\n cerr << \"Error loading logged test file\" << endl;\n test_harness.cleanup_harness();\n return -1;\n }\n }\n\n \/***************************************************\/\n \/*\n#define TEST_CASE_FSCK \"fsck -T -t \"\n\n \/\/ Create a new partition table on test device.\n cout << \"Partitioning test drive\" << endl;\n if (test_harness.partition_drive() != SUCCESS) {\n test_harness.cleanup_harness();\n return -1;\n }\n\n cout << \"Restoring device clone\" << std::endl;\n if (test_harness.clone_device_restore() != SUCCESS) {\n test_harness.cleanup_harness();\n cerr << \"Error restoring device clone\" << std::endl;\n return -1;\n }\n\n cout << \"Restoring log data\" << std::endl;\n if (test_harness.test_restore_log() != SUCCESS) {\n test_harness.cleanup_harness();\n cerr << \"Error restoring log data\" << std::endl;\n return -1;\n }\n\n std::cout << \"Result of current test is \" << test_harness.test_check_current()\n << std::endl;\n *\/\n\n \/***************************************************\/\n\n if (!dry_run) {\n cout << \"Writing profiled data to block device and checking with fsck\\n\";\n test_harness.test_check_random_permutations(1);\n\n cout << \"Ran \" << test_harness.test_test_stats[TESTS_TESTS_RUN] << \" tests\"\n << endl\n << '\\t' << test_harness.test_test_stats[TESTS_TEST_FSCK_FAIL]\n << \" tests fsck failed\" << endl\n << '\\t' << test_harness.test_test_stats[TESTS_TEST_BAD_DATA]\n << \" tests bad data\" << endl\n << '\\t' << test_harness.test_test_stats[TESTS_TEST_FSCK_FIX]\n << \" tests fsck fix\" << endl\n << '\\t' << test_harness.test_test_stats[TESTS_TEST_PASS]\n << \" tests passed\" << endl\n << '\\t' << test_harness.test_test_stats[TESTS_TEST_ERR]\n << \" tests errored\" << endl;\n }\n\n \/\/ Finish cleaning everything up.\n test_harness.cleanup_harness();\n return 0;\n}\n<commit_msg>Switch back to mostly ramdisks.<commit_after>#include <fcntl.h>\n#include <getopt.h>\n#include <string.h>\n#include <sys\/types.h>\n#include <unistd.h>\n#include <wait.h>\n\n#include <iostream>\n#include <string>\n#include <vector>\n\n#include \"..\/utils\/utils.h\"\n#include \"Tester.h\"\n#include \"..\/tests\/BaseTestCase.h\"\n\n#define TEST_SO_PATH \"tests\/\"\n#define PERMUTER_SO_PATH \"permuter\/\"\n\/\/ TODO(ashmrtn): Find a good delay time to use for tests.\n#define TEST_DIRTY_EXPIRE_TIME \"500\"\n#define WRITE_DELAY 30\n#define MOUNT_DELAY 3\n\n#define OPTS_STRING \"d:il:m:np:r:st:v\"\n\nusing std::cerr;\nusing std::cout;\nusing std::endl;\nusing std::string;\nusing fs_testing::Tester;\n\nstatic const option long_options[] = {\n {\"no-snap\", no_argument, NULL, 's'},\n {\"in-memory\", no_argument, NULL, 'i'},\n {\"dry-run\", no_argument, NULL, 'n'},\n {\"verbose\", no_argument, NULL, 'v'},\n {\"fs-type\", required_argument, NULL, 't'},\n {\"test-dev\", required_argument, NULL, 'd'},\n {\"log-file\", required_argument, NULL, 'l'},\n {\"reload-log-file\", required_argument, NULL, 'r'},\n {\"mount-opts\", required_argument, NULL, 'm'},\n {\"permuter\", required_argument, NULL, 'p'},\n {0, 0, 0, 0},\n};\n\nint main(int argc, char** argv) {\n string dirty_expire_time_centisecs(TEST_DIRTY_EXPIRE_TIME);\n unsigned long int test_sleep_delay = WRITE_DELAY;\n string fs_type(\"ext4\");\n string test_dev(\"\/dev\/ram0\");\n string mount_opts(\"\");\n string log_file_save(\"\");\n string log_file_load(\"\");\n string permuter(PERMUTER_SO_PATH \"RandomPermuter.so\");\n bool dry_run = false;\n bool no_lvm = false;\n bool no_snap = false;\n bool verbose = false;\n \/\/ TODO(ashmrtn): Find a better way to track whether we are using a ramdisk or\n \/\/ not. ramdisks don't need paritioned and will fail if we try to run fdisk\n \/\/ (the partitioning steps) on them so we need to detect them and change our\n \/\/ method for them.\n bool in_memory = true; \/\/ Assume ramdisk.\n\n int option_idx = 0;\n\n \/\/ Parse command line arguments.\n for (int c = getopt_long(argc, argv, OPTS_STRING, long_options, &option_idx);\n c != -1;\n c = getopt_long(argc, argv, OPTS_STRING, long_options, &option_idx)) {\n switch (c) {\n case 'd':\n test_dev = string(optarg);\n in_memory = false;\n break;\n case 'i':\n in_memory = true;\n break;\n case 'l':\n log_file_save = string(optarg);\n break;\n case 'm':\n mount_opts = string(optarg);\n break;\n case 'n':\n dry_run = 1;\n break;\n case 'p':\n permuter = string(optarg);\n break;\n case 'r':\n log_file_load = string(optarg);\n break;\n case 's':\n no_snap = 1;\n dry_run = 1;\n break;\n case 't':\n fs_type = string(optarg);\n break;\n case 'v':\n verbose = true;\n break;\n case '?':\n default:\n return -1;\n }\n }\n\n const unsigned int test_case_idx = optind;\n\n if (test_case_idx == argc) {\n cerr << \"Please give a .so test case to load\" << endl;\n return -1;\n }\n\n Tester test_harness(verbose);\n test_harness.set_fs_type(fs_type);\n test_harness.set_device(test_dev);\n\n \/\/ Load the class being tested.\n cout << \"Loading test case\" << endl;\n if (test_harness.test_load_class(argv[test_case_idx]) != SUCCESS) {\n test_harness.cleanup_harness();\n return -1;\n }\n\n \/\/ Load the permuter to use for the test.\n \/\/ TODO(ashmrtn): Consider making a line in the test file which specifies the\n \/\/ permuter to use?\n cout << \"Loading permuter\" << endl;\n if (test_harness.permuter_load_class(permuter.c_str()) != SUCCESS) {\n test_harness.cleanup_harness();\n return -1;\n }\n\n \/\/ Update dirty_expire_time.\n cout << \"Updating dirty_expire_time_centisecs\" << endl;\n const char* old_expire_time =\n test_harness.update_dirty_expire_time(dirty_expire_time_centisecs.c_str());\n if (old_expire_time == NULL) {\n cerr << \"Error updating dirty_expire_time_centisecs\" << endl;\n test_harness.cleanup_harness();\n return -1;\n }\n\n if (!in_memory) {\n \/\/ Partition drive.\n \/\/ TODO(ashmrtn): Consider making a flag for this?\n cout << \"Wiping test device\" << endl;\n if (test_harness.wipe_partitions() != SUCCESS) {\n cerr << \"Error wiping paritions on test device\" << endl;\n test_harness.cleanup_harness();\n return -1;\n }\n }\n\n \/\/ Run the normal test setup stuff if we don't have a log file.\n if (log_file_load.empty()) {\n\n if (!in_memory) {\n \/\/ Create a new partition table on test device.\n cout << \"Partitioning test drive\" << endl;\n if (test_harness.partition_drive() != SUCCESS) {\n test_harness.cleanup_harness();\n return -1;\n }\n }\n\n \/\/ Format test drive to desired type.\n cout << \"Formatting test drive\" << endl;\n if (test_harness.format_drive() != SUCCESS) {\n cerr << \"Error formatting test drive\" << endl;\n test_harness.cleanup_harness();\n return -1;\n }\n\n \/\/ Mount test file system for pre-test setup.\n cout << \"Mounting test file system for pre-test setup\\n\";\n if (test_harness.mount_device_raw(mount_opts.c_str()) != SUCCESS) {\n cerr << \"Error mounting test device\" << endl;\n test_harness.cleanup_harness();\n return -1;\n }\n\n \/\/ Run pre-test setup stuff.\n cout << \"Running pre-test setup\\n\";\n {\n const pid_t child = fork();\n if (child < 0) {\n cerr << \"Error creating child process to run pre-test setup\\n\";\n test_harness.cleanup_harness();\n } else if (child != 0) {\n \/\/ Parent process should wait for child to terminate before proceeding.\n pid_t status;\n wait(&status);\n if (status != 0) {\n cerr << \"Error in pre-test setup\\n\";\n test_harness.cleanup_harness();\n }\n } else {\n return test_harness.test_setup();\n }\n }\n\n \/\/ Unmount the test file system after pre-test setup.\n cout << \"Unmounting test file system after pre-test setup\\n\";\n if (test_harness.umount_device() != SUCCESS) {\n test_harness.cleanup_harness();\n return -1;\n }\n\n \/\/ Create snapshot of disk for testing.\n if (!no_snap) {\n cout << \"Making new snapshot\\n\";\n if (test_harness.clone_device() != SUCCESS) {\n test_harness.cleanup_harness();\n return -1;\n }\n\n \/\/ If we're logging this test run then also save the snapshot.\n if (!log_file_save.empty()) {\n cout << \"Saving snapshot to log file\" << endl;\n if (test_harness.log_snapshot_save(log_file_save + \"_snap\")\n != SUCCESS) {\n test_harness.cleanup_harness();\n return -1;\n }\n }\n }\n } else {\n \/\/ Load the snapshot in the log file and then write it to disk.\n cout << \"Loading saved snapshot\" << endl;\n if (test_harness.log_snapshot_load(log_file_load + \"_snap\") != SUCCESS) {\n test_harness.cleanup_harness();\n return -1;\n }\n }\n\n \/\/ TODO(ashmrtn): Consider making a flag for this?\n cout << \"Clearing caches\" << endl;\n if (test_harness.clear_caches() != SUCCESS) {\n cerr << \"Error clearing caches\" << endl;\n test_harness.cleanup_harness();\n return -1;\n }\n\n\n \/\/ No log file given so run the test profile.\n if (log_file_load.empty()) {\n\n \/\/ Insert the disk block wrapper into the kernel.\n cout << \"Inserting wrapper module into kernel\\n\";\n if (test_harness.insert_wrapper() != SUCCESS) {\n cerr << \"Error inserting kernel wrapper module\\n\";\n test_harness.cleanup_harness();\n return -1;\n }\n\n \/\/ Mount the file system under the wrapper module for profiling.\n cout << \"Mounting wrapper file system\\n\";\n if (test_harness.mount_wrapper_device(mount_opts.c_str()) != SUCCESS) {\n cerr << \"Error mounting wrapper file system\\n\";\n test_harness.cleanup_harness();\n return -1;\n }\n\n cout << \"Sleeping after mount\" << endl;\n unsigned int to_sleep = MOUNT_DELAY;\n do {\n to_sleep = sleep(to_sleep);\n } while (to_sleep > 0);\n\n \/\/ Get access to wrapper module ioctl functions via FD.\n cout << \"Getting wrapper device ioctl fd\\n\";\n if (test_harness.get_wrapper_ioctl() != SUCCESS) {\n cerr << \"Error opening device file\\n\";\n test_harness.cleanup_harness();\n return -1;\n }\n\n \/\/ Clear wrapper module logs prior to test profiling.\n cout << \"Clearing wrapper device logs\\n\";\n test_harness.clear_wrapper_log();\n cout << \"Enabling wrapper device logging\\n\";\n test_harness.begin_wrapper_logging();\n\n \/\/ Fork off a new process and run test profiling. Forking makes it easier to\n \/\/ handle making sure everything is taken care of in profiling and ensures\n \/\/ that even if all file handles aren't closed in the test process the parent\n \/\/ won't hang due to a busy mount point.\n cout << \"Running test profile\\n\";\n {\n const pid_t child = fork();\n if (child < 0) {\n cerr << \"Error spinning off test process\\n\";\n test_harness.cleanup_harness();\n return -1;\n } else if (child != 0) {\n pid_t status;\n wait(&status);\n if (status != 0) {\n cerr << \"Error in test process\\n\";\n test_harness.cleanup_harness();\n return -1;\n }\n sleep(WRITE_DELAY);\n\n \/\/ Wait a small amount of time for writes to propogate to the block\n \/\/ layer and then stop logging writes.\n cout << \"Disabling wrapper device logging\" << std::endl;\n test_harness.end_wrapper_logging();\n cout << \"Getting wrapper data\\n\";\n if (test_harness.get_wrapper_log() != SUCCESS) {\n test_harness.cleanup_harness();\n return -1;\n }\n } else {\n \/\/ Forked process' stuff.\n return test_harness.test_run();\n }\n }\n\n cout << \"Unmounting wrapper file system after test profiling\\n\";\n if (test_harness.umount_device() != SUCCESS) {\n cerr << \"Error unmounting wrapper file system\\n\";\n test_harness.cleanup_harness();\n return -1;\n }\n\n cout << \"Close wrapper ioctl fd\\n\";\n test_harness.put_wrapper_ioctl();\n cout << \"Removing wrapper module from kernel\\n\";\n if (test_harness.remove_wrapper() != SUCCESS) {\n cerr << \"Error cleaning up: remove wrapper module\\n\";\n test_harness.cleanup_harness();\n return -1;\n }\n\n \/\/ Write log data out to file if we're given a file.\n if (!log_file_save.empty()) {\n cout << \"Saving logged profile data to disk\" << endl;\n if (test_harness.log_profile_save(log_file_save + \"_profile\") != SUCCESS) {\n cerr << \"Error saving logged test file\" << endl;\n \/\/ TODO(ashmrtn): Remove this in later versions?\n test_harness.cleanup_harness();\n return -1;\n }\n }\n } else {\n \/\/ Logged test data given, load it into the test harness.\n cout << \"Loading logged profile data from disk\" << endl;\n if (test_harness.log_profile_load(log_file_load + \"_profile\") != SUCCESS) {\n cerr << \"Error loading logged test file\" << endl;\n test_harness.cleanup_harness();\n return -1;\n }\n }\n\n \/***************************************************\/\n \/*\n#define TEST_CASE_FSCK \"fsck -T -t \"\n\n \/\/ Create a new partition table on test device.\n cout << \"Partitioning test drive\" << endl;\n if (test_harness.partition_drive() != SUCCESS) {\n test_harness.cleanup_harness();\n return -1;\n }\n\n cout << \"Restoring device clone\" << std::endl;\n if (test_harness.clone_device_restore() != SUCCESS) {\n test_harness.cleanup_harness();\n cerr << \"Error restoring device clone\" << std::endl;\n return -1;\n }\n\n cout << \"Restoring log data\" << std::endl;\n if (test_harness.test_restore_log() != SUCCESS) {\n test_harness.cleanup_harness();\n cerr << \"Error restoring log data\" << std::endl;\n return -1;\n }\n\n std::cout << \"Result of current test is \" << test_harness.test_check_current()\n << std::endl;\n *\/\n\n \/***************************************************\/\n\n if (!dry_run) {\n cout << \"Writing profiled data to block device and checking with fsck\\n\";\n test_harness.test_check_random_permutations(1);\n\n cout << \"Ran \" << test_harness.test_test_stats[TESTS_TESTS_RUN] << \" tests\"\n << endl\n << '\\t' << test_harness.test_test_stats[TESTS_TEST_FSCK_FAIL]\n << \" tests fsck failed\" << endl\n << '\\t' << test_harness.test_test_stats[TESTS_TEST_BAD_DATA]\n << \" tests bad data\" << endl\n << '\\t' << test_harness.test_test_stats[TESTS_TEST_FSCK_FIX]\n << \" tests fsck fix\" << endl\n << '\\t' << test_harness.test_test_stats[TESTS_TEST_PASS]\n << \" tests passed\" << endl\n << '\\t' << test_harness.test_test_stats[TESTS_TEST_ERR]\n << \" tests errored\" << endl;\n }\n\n \/\/ Finish cleaning everything up.\n test_harness.cleanup_harness();\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>#include <gmi_null.h>\n#include <gmi_mesh.h>\n#include <apfMDS.h>\n#include <apfMesh2.h>\n#include <apf.h>\n#include <PCU.h>\n#include <parma.h>\n#include <stdlib.h>\n\nint main(int argc, char** argv) {\n MPI_Init(&argc,&argv);\n PCU_Comm_Init();\n if ( argc != 4 ) {\n if ( !PCU_Comm_Self() )\n printf(\"Usage: %s <model> <mesh> <out prefix>\\n\", argv[0]);\n MPI_Finalize();\n exit(EXIT_FAILURE);\n }\n PCU_Debug_Open();\n gmi_register_null();\n gmi_register_mesh();\n apf::Mesh2* m = apf::loadMdsMesh(argv[1],argv[2]);\n apf::MeshTag* order = Parma_BfsReorder(m);\n apf::reorderMdsMesh(m, order);\n apf::writeVtkFiles(\"parma_ordered\", m);\n m->writeNative(argv[3]);\n m->destroyNative();\n apf::destroyMesh(m);\n PCU_Comm_Free();\n MPI_Finalize();\n}\n<commit_msg>remove debug outputs<commit_after>#include <gmi_null.h>\n#include <gmi_mesh.h>\n#include <apfMDS.h>\n#include <apfMesh2.h>\n#include <apf.h>\n#include <PCU.h>\n#include <parma.h>\n#include <stdlib.h>\n\nint main(int argc, char** argv) {\n MPI_Init(&argc,&argv);\n PCU_Comm_Init();\n if ( argc != 4 ) {\n if ( !PCU_Comm_Self() )\n printf(\"Usage: %s <model> <mesh> <out prefix>\\n\", argv[0]);\n MPI_Finalize();\n exit(EXIT_FAILURE);\n }\n gmi_register_null();\n gmi_register_mesh();\n apf::Mesh2* m = apf::loadMdsMesh(argv[1],argv[2]);\n apf::MeshTag* order = Parma_BfsReorder(m);\n apf::reorderMdsMesh(m, order);\n m->writeNative(argv[3]);\n m->destroyNative();\n apf::destroyMesh(m);\n PCU_Comm_Free();\n MPI_Finalize();\n}\n<|endoftext|>"} {"text":"<commit_before>\/* -*- mode: C++; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8 -*- *\/\n\n\/* tests\/test-trace.C\n *\n * Written by David Saunders \n *\n * --------------------------------------------------------\n * See COPYING for license information\n *\/\n\n#include \"linbox-config.h\"\n\n#include <iostream>\n#include <fstream>\n#include <vector>\n#include <functional>\n\n#include \"test-common.h\"\n\n#include \"linbox\/util\/commentator.h\"\n#include \"linbox\/field\/ntl-pid-zz_p.h\"\n#include \"linbox\/field\/local2_32.h\"\n#include \"linbox\/blackbox\/dense.h\"\n#include \"linbox\/algorithms\/local-smith.h\"\n#include \"linbox\/algorithms\/2local-smith.h\"\n#include \"linbox\/vector\/stream.h\"\n#include <linbox\/matrix\/matrix-domain.h>\n#include <linbox\/util\/timer.h>\n\nusing namespace LinBox;\n\n\/* Test 1: Invariant factors of random diagonal matrix\n *\n * Construct a random diagonal matrix and check that its computed smith form\n * is the sort on the P powers.\n *\n * R - PID over which to perform computations\n * stream - Stream that comprises source of diagonal vectors\n *\n * Return true on success and false on failure\n *\/\n\ntemplate <class LocalPID>\nclass foobar {\n\tpublic:\n\ttypedef typename LocalPID::Element first_argument_type;\n\ttypedef LocalPID second_argument_type;\n\ttypedef void result_type;\n\tvoid operator()(typename LocalPID::Element& d, const LocalPID& R) const\n\t{ \n\t\ttypename LocalPID::Element x = d;\n\t\tR.gcd(d, x, x);\n\t}\n};\ntemplate<>\nclass foobar<LinBox::Local2_32> {\npublic:\n\ttypedef LinBox::Local2_32 LocalPID;\n\t\n\ttypedef LocalPID::Element first_argument_type;\n\ttypedef LocalPID second_argument_type;\n\ttypedef void result_type;\n\tvoid operator()(LocalPID::Element& d, const LocalPID& R) const\n\t{\n\n\n\t\tif(d != 0) {\n\n\t\t\tint r = 1;\n\n\t\t\twhile ( !(d & 1) ) {\n\t\t\t\td >>= 1;\n\t\t\t\tr <<= 1;\n\t\t\t}\n\n\t\t\td = r;\n\t\t}\n\t\t\n\t \n\t}\n};\n\t\t\t\t\ntemplate <class LocalPID>\nclass pplt\n{ public:\n\tpplt(LocalPID R) : _R(R){}\n\tbool operator() (typename LocalPID::Element a, typename LocalPID::Element b)\n\t{ \n\t if ( b == 0 ) return true;\n \t else if ( a == 0 ) return false;\n\t else return a <= b;\n \t}\t\t\n \/\/protected:\n LocalPID _R;\n};\n\ntemplate<>\nclass pplt<LinBox::NTL_PID_zz_p> {\npublic:\n\ttypedef LinBox::NTL_PID_zz_p LocalPID;\n\t\n\tpplt(LocalPID R) : _R(R){}\n\tbool operator() (LocalPID::Element a, LocalPID::Element b)\n\t{ \n\t if ( b == 0 ) return true;\n \t else if ( a == 0 ) return false;\n\t else return NTL::rep(a) <= NTL::rep(b);\n \t}\t\t\n \/\/protected:\n LocalPID _R;\n};\n\ntemplate <class LocalPID>\nstatic bool testDiagonalLocalSmith (const LocalPID &R, VectorStream<vector<typename LocalPID::Element> > &stream) \n{\n\ttypedef vector <typename LocalPID::Element> Vector;\n\ttypedef typename LocalPID::Element Elt;\n\ttypedef DenseMatrix<LocalPID> Blackbox;\n\n\tcommentator.start (\"Testing diagonal local smith\", \"testDiagonalLocalSmith\", stream.m ());\n\n\tVectorDomain<LocalPID> VD (R);\n\n\tbool ret = true;\n\tsize_t i;\n\tsize_t n = stream.n();\n\n\tVector d;\n\n\tVectorWrapper::ensureDim (d, stream.dim ());\n\n\twhile (stream) {\n\t\tcommentator.startIteration (stream.j ());\n\n\t\tstream.next (d);\n\n\t\tostream &report = commentator.report (Commentator::LEVEL_IMPORTANT, INTERNAL_DESCRIPTION);\n\t\t\/\/ostream &report = std::cout; \n\t\treport << \"Input vector: \";\n\t\tVD.write (report, d);\n\t\treport << endl;\n\n\t\tBlackbox Lm (R, n, n), D (R, n, n), U (R, n, n), A (R, n, n);\n\t\tfor( i = 0; i < n; ++i ) {D[i][i] = d[i];Lm[i][i]=U[i][i]=1;}\n\t\t\n\t\tsize_t j;\n\t\t\n\t\tfor (i = 0; i < n; ++ i) \n\t\t for ( j = 0; j < i; ++ j) {\n\t\t\t \n\t\t\t D[i][j] = D[j][i] = 0;\n\t\t\t \n\t\t\t Lm[i][j] = rand() % 10;\n\t\t\t Lm[j][i] = 0;\n\t\t\t \n\t\t\t U[j][i] = rand() % 10;\n\t\t\t U[i][j] = 0;\n\t\t }\n\n\t\tMatrixDomain<LocalPID> MR(R);\n\t\t\n\t\tTimer timer;\n\t\t\n\t\treport << \"D\\n\";\n\t\tD.write(report);\n\n\t\treport << \"L\\n\";\n\t\tLm.write(report);\n\n\t\treport << \"U\\n\";\n\t\tU.write(report);\n\n\t\ttimer.start();\n\t\tMR.mul(A,Lm,D);\n\n\t\treport << \"L D\\n\";\n\t\tA.write(report);\n\n\t\tMR.mulin(A,U);\n\t\ttimer.stop();\n\t\treport << \"Two matrix multiplication: \" << timer << \"\\n\";\n\t\t\n\t\treport << \"A \\n\";\n\t\tA.write(report);\n\t\t\/\/for( i = 0; i < n; ++i ) D[i][i] = rand() % 10 + 1;\n\n\t\tlist< typename LocalPID::Element > L;\n\t\tLocalSmith< LocalPID > SmithForm;\n\t\ttimer.start();\n\t\tSmithForm( L, A, R );\n\t\ttimer.stop();\n\t\treport << \"Time \" << timer <<\"\\n\";\n\t\t\t\n\t\treport.flush();\n\t\treport << \"Computed invariants: \";\n\t\t\n\t\treport << \"[\";\n\t\ttypedef typename list<Elt>::iterator listptr;\n\t\tfor (listptr p = L.begin(); p != L.end(); ++p)\n\t\t report << *p << \", \";\n\t\treport << \"\\b\\b]\" << endl;\n\n\t\tpplt<LocalPID> lt(R);\n\t\treport << \"normalize done\" << endl;\n\t\treport.flush();\n\n\t\tfor_each(d.begin(), d.end(), bind2nd(foobar<LocalPID>(), R));\n\t\ttimer.start();\n\t\tstable_sort(d.begin(), d.end(), lt);\n\t\ttimer.stop();\n\t\treport << \"Sorting \" << timer <<\"\\n\";\n\n\t\treport << \"sort done\" << endl;\n\t\treport.flush();\n\n\t\treport << \"True invariants: \";\n\t\tVD.write (report, d);\n\t\treport << endl;\n\t\treport << flush;\n\n\t\tif ( L.size() != D.rowdim() ) {ret = false; break;}\n\t\ttypedef typename Vector::iterator vectptr;\n\t\tlistptr p; vectptr q;\n\t\tfor (p = L.begin(), q = d.begin(); \n\t\t q != d.end(); \n\t\t ++p, ++q)\n\t\t if ( !R.areEqual (*p, *q ) )\n\t\t {\n\t\t\tcommentator.report (Commentator::LEVEL_IMPORTANT, INTERNAL_ERROR)\n\t\t\t\t<< \"ERROR: Computed invariants incorrect\" << endl;\n\t\t\t ret = false;\n\t\t }\n\t\tcommentator.stop(\"done\");\n\t\tcommentator.progress();\n\t}\n\n\tcommentator.stop (MSG_STATUS (ret), (const char *) 0, \"testDiagonalTrace\");\n\n\treturn ret;\n}\n\nint main (int argc, char **argv)\n{\n\tbool pass = true;\n\n\tstatic size_t n = 20;\n\tstatic integer q = 101;\n\tstatic int iterations = 1;\n\n\tstatic Argument args[] = {\n\t\t{ 'n', \"-n N\", \"Set dimension of test matrices to NxN (default 256)\", TYPE_INT, &n },\n\t\t{ 'q', \"-q Q\", \"Operate over the \\\"field\\\" GF(Q) [1] (default 101)\", TYPE_INTEGER, &q },\n\t\t{ 'i', \"-i I\", \"Perform each test for I iterations (default 10)\", TYPE_INT, &iterations },\n\t};\n\n\ttypedef NTL_PID_zz_p Ring;\n\ttypedef vector<Ring::Element> Vector;\n\n\tparseArguments (argc, argv, args);\n\tRing R (536870912);\n\n\tcout << endl << \"Black box local smith test suite\" << endl;\n\n\tcommentator.getMessageClass (INTERNAL_DESCRIPTION).setMaxDepth (5);\n\n\tRandomDenseStream<Ring, Vector> stream (R, n, iterations);\n\n\tif (!testDiagonalLocalSmith<Ring> (R, stream)) pass = false;\n\n\t\/\/ power of 2 test\n\tLocal2_32 R2;\n\tRandomDenseStream<Local2_32, vector<Local2_32::Element> > \n\t\tstream2 (R2, n, iterations);\n\tif (!testDiagonalLocalSmith<Local2_32> (R2, stream2)) pass = false;\n\n\treturn pass ? 0 : -1;\n}\n\n<commit_msg>min change in comments<commit_after>\/* -*- mode: C++; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8 -*- *\/\n\n\/* tests\/test-trace.C\n *\n * Written by David Saunders \n *\n * --------------------------------------------------------\n * See COPYING for license information\n *\/\n\n#include \"linbox-config.h\"\n\n#include <iostream>\n#include <fstream>\n#include <vector>\n#include <functional>\n\n#include \"test-common.h\"\n\n#include \"linbox\/util\/commentator.h\"\n#include \"linbox\/field\/ntl-pid-zz_p.h\"\n#include \"linbox\/field\/local2_32.h\"\n#include \"linbox\/blackbox\/dense.h\"\n#include \"linbox\/algorithms\/local-smith.h\"\n#include \"linbox\/algorithms\/2local-smith.h\"\n#include \"linbox\/vector\/stream.h\"\n#include <linbox\/matrix\/matrix-domain.h>\n#include <linbox\/util\/timer.h>\n\nusing namespace LinBox;\n\n\/** @memo Test 1: Invariant factors of random dense matrices.\n *\n * Construct a random matrix which is equivalent to a random diagonal matrix,\n * and check its Smith form.\n *\n * R - PIR over which to perform computations\n * stream - Stream that comprises source of diagonal vectors\n *\n * Return true on success and false on failure\n *\/\n\ntemplate <class LocalPID>\nclass foobar {\n\tpublic:\n\ttypedef typename LocalPID::Element first_argument_type;\n\ttypedef LocalPID second_argument_type;\n\ttypedef void result_type;\n\tvoid operator()(typename LocalPID::Element& d, const LocalPID& R) const\n\t{ \n\t\ttypename LocalPID::Element x = d;\n\t\tR.gcd(d, x, x);\n\t}\n};\ntemplate<>\nclass foobar<LinBox::Local2_32> {\npublic:\n\ttypedef LinBox::Local2_32 LocalPID;\n\t\n\ttypedef LocalPID::Element first_argument_type;\n\ttypedef LocalPID second_argument_type;\n\ttypedef void result_type;\n\tvoid operator()(LocalPID::Element& d, const LocalPID& R) const\n\t{\n\n\n\t\tif(d != 0) {\n\n\t\t\tint r = 1;\n\n\t\t\twhile ( !(d & 1) ) {\n\t\t\t\td >>= 1;\n\t\t\t\tr <<= 1;\n\t\t\t}\n\n\t\t\td = r;\n\t\t}\n\t\t\n\t \n\t}\n};\n\t\t\t\t\ntemplate <class LocalPID>\nclass pplt\n{ public:\n\tpplt(LocalPID R) : _R(R){}\n\tbool operator() (typename LocalPID::Element a, typename LocalPID::Element b)\n\t{ \n\t if ( b == 0 ) return true;\n \t else if ( a == 0 ) return false;\n\t else return a <= b;\n \t}\t\t\n \/\/protected:\n LocalPID _R;\n};\n\ntemplate<>\nclass pplt<LinBox::NTL_PID_zz_p> {\npublic:\n\ttypedef LinBox::NTL_PID_zz_p LocalPID;\n\t\n\tpplt(LocalPID R) : _R(R){}\n\tbool operator() (LocalPID::Element a, LocalPID::Element b)\n\t{ \n\t if ( b == 0 ) return true;\n \t else if ( a == 0 ) return false;\n\t else return NTL::rep(a) <= NTL::rep(b);\n \t}\t\t\n \/\/protected:\n LocalPID _R;\n};\n\ntemplate <class LocalPID>\nstatic bool testLocalSmith (const LocalPID &R, VectorStream<vector<typename LocalPID::Element> > &stream) \n{\n\ttypedef vector <typename LocalPID::Element> Vector;\n\ttypedef typename LocalPID::Element Elt;\n\ttypedef DenseMatrix<LocalPID> Blackbox;\n\n\tcommentator.start (\"Testing local smith on random dense matrices\", \"testLocalSmith\", stream.m ());\n\n\tVectorDomain<LocalPID> VD (R);\n\n\tbool ret = true;\n\tsize_t i;\n\tsize_t n = stream.n();\n\n\tVector d;\n\n\tVectorWrapper::ensureDim (d, stream.dim ());\n\n\twhile (stream) {\n\t\tcommentator.startIteration (stream.j ());\n\n\t\tstream.next (d);\n\n\t\tostream &report = commentator.report (Commentator::LEVEL_IMPORTANT, INTERNAL_DESCRIPTION);\n\t\t\/\/ostream &report = std::cout; \n\t\treport << \"Input vector: \";\n\t\tVD.write (report, d);\n\t\treport << endl;\n\n\t\tBlackbox Lm (R, n, n), D (R, n, n), U (R, n, n), A (R, n, n);\n\t\tfor( i = 0; i < n; ++i ) {D[i][i] = d[i];Lm[i][i]=U[i][i]=1;}\n\t\t\n\t\tsize_t j;\n\t\t\n\t\tfor (i = 0; i < n; ++ i) \n\t\t for ( j = 0; j < i; ++ j) {\n\t\t\t \n\t\t\t D[i][j] = D[j][i] = 0;\n\t\t\t \n\t\t\t Lm[i][j] = rand() % 10;\n\t\t\t Lm[j][i] = 0;\n\t\t\t \n\t\t\t U[j][i] = rand() % 10;\n\t\t\t U[i][j] = 0;\n\t\t }\n\n\t\tMatrixDomain<LocalPID> MR(R);\n\t\t\n\t\tTimer timer;\n\t\t\n\t\treport << \"D\\n\";\n\t\tD.write(report);\n\n\t\treport << \"L\\n\";\n\t\tLm.write(report);\n\n\t\treport << \"U\\n\";\n\t\tU.write(report);\n\n\t\ttimer.start();\n\t\tMR.mul(A,Lm,D);\n\n\t\treport << \"L D\\n\";\n\t\tA.write(report);\n\n\t\tMR.mulin(A,U);\n\t\ttimer.stop();\n\t\treport << \"Two matrix multiplication: \" << timer << \"\\n\";\n\t\t\n\t\treport << \"A \\n\";\n\t\tA.write(report);\n\t\t\/\/for( i = 0; i < n; ++i ) D[i][i] = rand() % 10 + 1;\n\n\t\tlist< typename LocalPID::Element > L;\n\t\tLocalSmith< LocalPID > SmithForm;\n\t\ttimer.start();\n\t\tSmithForm( L, A, R );\n\t\ttimer.stop();\n\t\treport << \"Time \" << timer <<\"\\n\";\n\t\t\t\n\t\treport.flush();\n\t\treport << \"Computed invariants: \";\n\t\t\n\t\treport << \"[\";\n\t\ttypedef typename list<Elt>::iterator listptr;\n\t\tfor (listptr p = L.begin(); p != L.end(); ++p)\n\t\t report << *p << \", \";\n\t\treport << \"\\b\\b]\" << endl;\n\n\t\tpplt<LocalPID> lt(R);\n\t\treport << \"normalize done\" << endl;\n\t\treport.flush();\n\n\t\tfor_each(d.begin(), d.end(), bind2nd(foobar<LocalPID>(), R));\n\t\ttimer.start();\n\t\tstable_sort(d.begin(), d.end(), lt);\n\t\ttimer.stop();\n\t\treport << \"Sorting \" << timer <<\"\\n\";\n\n\t\treport << \"sort done\" << endl;\n\t\treport.flush();\n\n\t\treport << \"True invariants: \";\n\t\tVD.write (report, d);\n\t\treport << endl;\n\t\treport << flush;\n\n\t\tif ( L.size() != D.rowdim() ) {ret = false; break;}\n\t\ttypedef typename Vector::iterator vectptr;\n\t\tlistptr p; vectptr q;\n\t\tfor (p = L.begin(), q = d.begin(); \n\t\t q != d.end(); \n\t\t ++p, ++q)\n\t\t if ( !R.areEqual (*p, *q ) )\n\t\t {\n\t\t\tcommentator.report (Commentator::LEVEL_IMPORTANT, INTERNAL_ERROR)\n\t\t\t\t<< \"ERROR: Computed invariants incorrect\" << endl;\n\t\t\t ret = false;\n\t\t }\n\t\tcommentator.stop(\"done\");\n\t\tcommentator.progress();\n\t}\n\n\tcommentator.stop (MSG_STATUS (ret), (const char *) 0, \"testDiagonalTrace\");\n\n\treturn ret;\n}\n\nint main (int argc, char **argv)\n{\n\tbool pass = true;\n\n\tstatic size_t n = 20;\n\tstatic integer q = 101;\n\tstatic int iterations = 1;\n\n\tstatic Argument args[] = {\n\t\t{ 'n', \"-n N\", \"Set dimension of test matrices to NxN (default 256)\", TYPE_INT, &n },\n\t\t{ 'q', \"-q Q\", \"Operate over the \\\"field\\\" GF(Q) [1] (default 101)\", TYPE_INTEGER, &q },\n\t\t{ 'i', \"-i I\", \"Perform each test for I iterations (default 10)\", TYPE_INT, &iterations },\n\t};\n\n\ttypedef NTL_PID_zz_p Ring;\n\ttypedef vector<Ring::Element> Vector;\n\n\tparseArguments (argc, argv, args);\n\tRing R (536870912);\n\n\tcout << endl << \"Random dense matrix local smith test suite\" << endl;\n\n\tcommentator.getMessageClass (INTERNAL_DESCRIPTION).setMaxDepth (5);\n\n\tRandomDenseStream<Ring, Vector> stream (R, n, iterations);\n\n\tif (!testLocalSmith<Ring> (R, stream)) pass = false;\n\n\t\/\/ power of 2 test\n\tLocal2_32 R2;\n\tRandomDenseStream<Local2_32, vector<Local2_32::Element> > \n\t\tstream2 (R2, n, iterations);\n\tif (!testLocalSmith<Local2_32> (R2, stream2)) pass = false;\n\n\treturn pass ? 0 : -1;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ ==================================================================\n\/\/ ROCS - Toolkit for Robots Comprehending Space\n\/\/ Copyright (C) 2011 Andrzej Pronobis, Kristoffer Sjöo\n\/\/\n\/\/ This file is part of ROCS.\n\/\/\n\/\/ ROCS is free software: you can redistribute it and\/or modify it\n\/\/ under the terms of the GNU Lesser General Public License as\n\/\/ published by the Free Software Foundation, either version 3\n\/\/ of the License, or (at your option) any later version.\n\/\/\n\/\/ ROCS is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n\/\/ GNU Lesser General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU General Public License\n\/\/ along with ROCS. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n\/\/ ==================================================================\n\n\/*!\n *\n *\n * \\author Andrzej Pronobis, Kristoffer Sjöo\n * \\file AxiomFactorClassGenerator.cc\n *\/\n\n#include \"rocs\/concept\/AxiomFactorClassGenerator.h\"\n\n#include \"rocs\/ml\/FactorClassSet.h\"\n#include <opencv2\/core\/core.hpp>\n\nnamespace rocs {\nnamespace concept {\n\nusing namespace ml;\n\n\nvoid AxiomFactorClassGenerator::generate(size_t inCount, size_t intCount, size_t onCount)\n{\n {\n int sizes[] = {2, 2};\n cv::Mat supportAntisymmetricalPotentials(2, sizes, CV_64F);\n supportAntisymmetricalPotentials.setTo(1);\n int indices[] = {1,1};\n supportAntisymmetricalPotentials.at(indices) = 0;\n\n _supportAntisymmetricalFactorClass = &_fcs->addFactorClass(*_ontRelationVariableClass,\n\t*_ontRelationVariableClass, supportAntisymmetricalPotentials);\n }\n\n {\n int sizes[] = {2, 2};\n cv::Mat containmentAntisymmetricalPotentials(2, sizes, CV_64F);\n containmentAntisymmetricalPotentials.setTo(1);\n int indices[] = {1,1};\n containmentAntisymmetricalPotentials.at(indices) = 0;\n\n _containmentAntisymmetricalFactorClass = &_fcs->addFactorClass(*_ontRelationVariableClass,\n\t*_ontRelationVariableClass, containmentAntisymmetricalPotentials);\n }\n\n {\n int sizes[] = {2, 2};\n cv::Mat supportImpliesTransitiveSupportPotentials(2, sizes, CV_64F);\n supportImpliesTransitiveSupportPotentials.setTo(1);\n int indices[] = {1,0};\n supportImpliesTransitiveSupportPotentials.at(indices) = 0;\n\n _supportImpliesTransitiveSupportFactorClass = &_fcs->addFactorClass(*_onRelationVariableClass,\n\t*_ontRelationVariableClass, supportImpliesTransitiveSupportFactorClass);\n }\n\n {\n int sizes[] = {2, 2, 2};\n cv::Mat supportTransitivePotentials(3, sizes, CV_64F);\n supportTransitivePotentials.setTo(1);\n int indices[] = {1,1,0};\/\/Forbid true, true, false case\n supportTransitivePotentials.at(indices) = 0;\n\n std::vector<ml::FactorClass *>classes;\n classes.push_back(_ontRelationVariableClass);\n classes.push_back(_ontRelationVariableClass);\n classes.push_back(_ontRelationVariableClass);\n\n _supportTransitiveFactorClass = &_fcs->addFactorClass(classes, supportTransitivePotentials);\n }\n\n {\n int sizes[] = {2, 2, 2};\n cv::Mat containmentTransitivePotentials(3, sizes, CV_64F);\n containmentTransitivePotentials.setTo(1);\n int indices[] = {1,1,0};\/\/Forbid true, true, false case\n containmentTransitivePotentials.at(indices) = 0;\n\n std::vector<ml::FactorClass *>classes;\n classes.push_back(_inRelationVariableClass);\n classes.push_back(_inRelationVariableClass);\n classes.push_back(_inRelationVariableClass);\n\n _containmentTransitiveFactorClass = &_fcs->addFactorClass(classes, containmentTransitivePotentials);\n }\n\n {\n int sizes[] = {2, 2, 2};\n cv::Mat generousContainmentPotentials(3, sizes, CV_64F);\n generousContainmentPotentials.setTo(1);\n int indices[] = {1,1,0};\/\/Forbid true, true, false case\n generousContainmentPotentials.at(indices) = 0;\n\n std::vector<ml::FactorClass *>classes;\n classes.push_back(_ontRelationVariableClass);\n classes.push_back(_inRelationVariableClass);\n classes.push_back(_inRelationVariableClass);\n\n _generousContainmentFactorClass = &_fcs->addFactorClass(classes, generousContainmentPotentials);\n }\n}\n\n\n}\n}\n<commit_msg>Again<commit_after>\/\/ ==================================================================\n\/\/ ROCS - Toolkit for Robots Comprehending Space\n\/\/ Copyright (C) 2011 Andrzej Pronobis, Kristoffer Sjöo\n\/\/\n\/\/ This file is part of ROCS.\n\/\/\n\/\/ ROCS is free software: you can redistribute it and\/or modify it\n\/\/ under the terms of the GNU Lesser General Public License as\n\/\/ published by the Free Software Foundation, either version 3\n\/\/ of the License, or (at your option) any later version.\n\/\/\n\/\/ ROCS is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n\/\/ GNU Lesser General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU General Public License\n\/\/ along with ROCS. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n\/\/ ==================================================================\n\n\/*!\n *\n *\n * \\author Andrzej Pronobis, Kristoffer Sjöo\n * \\file AxiomFactorClassGenerator.cc\n *\/\n\n#include \"rocs\/concept\/AxiomFactorClassGenerator.h\"\n\n#include \"rocs\/ml\/FactorClassSet.h\"\n#include <opencv2\/core\/core.hpp>\n#include <stddef.h>\n\nnamespace rocs {\nnamespace concept {\n\nusing namespace ml;\n\n\nvoid recurseSupportRequirement(cv::Mat &potentials, int *indices, int depth, int maxDepth)\n{\n if (depth > maxDepth) {\n potentials.at<double>(indices) = 0;\n }\n else {\n \/\/Case: ~ONt(z,y)\n indices[depth*3] = 0; \t\/\/~ONt(zn,y)\n indices[depth*3+1] = 0; \t\/\/~ON(x,zn)\n indices[depth*3+2] = 0; \t\/\/~IN(x,zn)\n recurseSupportRequirement(potentials, indices, depth+3, maxDepth);\n indices[depth*3+1] = 1; \t\/\/ON(x,zn)\n recurseSupportRequirement(potentials, indices, depth+3, maxDepth);\n indices[depth*3+1] = 0; \t\/\/~ON(x,zn)\n indices[depth*3+2] = 1; \t\/\/IN(x,zn)\n recurseSupportRequirement(potentials, indices, depth+3, maxDepth);\n indices[depth*3+1] = 1; \t\/\/ON(x,zn)\n recurseSupportRequirement(potentials, indices, depth+3, maxDepth);\n\n \/\/ ONt(z,y) and ~ON(x,z) and ~IN(x,z)) (case when ~ONt(z,y) already covered above)\n indices[depth*3] = 1;\n indices[depth*3+1] = 0;\n indices[depth*3+2] = 0;\n recurseSupportRequirement(potentials, indices, depth+3, maxDepth);\n }\n}\n\nvoid AxiomFactorClassGenerator::generate(size_t inCount, size_t ontCount, size_t onCount)\n{\n {\n int sizes[] = {2, 2};\n cv::Mat supportAntisymmetricalPotentials(2, sizes, CV_64F);\n supportAntisymmetricalPotentials.setTo(1);\n int indices[] = {1,1};\n supportAntisymmetricalPotentials.at<double>(indices) = 0;\n\n _supportAntisymmetricalFactorClass = &_fcs->addFactorClass(*_ontRelationVariableClass,\n\t*_ontRelationVariableClass, supportAntisymmetricalPotentials);\n }\n\n {\n int sizes[] = {2, 2};\n cv::Mat containmentAntisymmetricalPotentials(2, sizes, CV_64F);\n containmentAntisymmetricalPotentials.setTo(1);\n int indices[] = {1,1};\n containmentAntisymmetricalPotentials.at<double>(indices) = 0;\n\n _containmentAntisymmetricalFactorClass = &_fcs->addFactorClass(*_ontRelationVariableClass,\n\t*_ontRelationVariableClass, containmentAntisymmetricalPotentials);\n }\n\n {\n int sizes[] = {2, 2};\n cv::Mat supportImpliesTransitiveSupportPotentials(2, sizes, CV_64F);\n supportImpliesTransitiveSupportPotentials.setTo(1);\n int indices[] = {1,0};\n supportImpliesTransitiveSupportPotentials.at<double>(indices) = 0;\n\n _supportImpliesTransitiveSupportFactorClass = &_fcs->addFactorClass(*_onRelationVariableClass,\n\t*_ontRelationVariableClass, supportImpliesTransitiveSupportPotentials);\n }\n\n {\n int sizes[] = {2, 2, 2};\n cv::Mat supportTransitivePotentials(3, sizes, CV_64F);\n supportTransitivePotentials.setTo(1);\n int indices[] = {1,1,0};\/\/Forbid true, true, false case\n supportTransitivePotentials.at<double>(indices) = 0;\n\n std::vector<ml::VariableClass>classes;\n classes.push_back(*_ontRelationVariableClass);\n classes.push_back(*_ontRelationVariableClass);\n classes.push_back(*_ontRelationVariableClass);\n\n _supportTransitiveFactorClass = &_fcs->addFactorClass(classes, supportTransitivePotentials);\n }\n\n {\n int sizes[] = {2, 2, 2};\n cv::Mat containmentTransitivePotentials(3, sizes, CV_64F);\n containmentTransitivePotentials.setTo(1);\n int indices[] = {1,1,0};\/\/Forbid true, true, false case\n containmentTransitivePotentials.at<double>(indices) = 0;\n\n std::vector<ml::VariableClass>classes;\n classes.push_back(*_inRelationVariableClass);\n classes.push_back(*_inRelationVariableClass);\n classes.push_back(*_inRelationVariableClass);\n\n _containmentTransitiveFactorClass = &_fcs->addFactorClass(classes, containmentTransitivePotentials);\n }\n\n {\n int sizes[] = {2, 2, 2};\n cv::Mat generousContainmentPotentials(3, sizes, CV_64F);\n generousContainmentPotentials.setTo(1);\n int indices[] = {1,1,0};\/\/Forbid true, true, false case\n generousContainmentPotentials.at<double>(indices) = 0;\n\n std::vector<ml::VariableClass>classes;\n classes.push_back(*_ontRelationVariableClass);\n classes.push_back(*_inRelationVariableClass);\n classes.push_back(*_inRelationVariableClass);\n\n _generousContainmentFactorClass = &_fcs->addFactorClass(classes, generousContainmentPotentials);\n }\n\n {\n int sizes[] = {2, 2, 2};\n cv::Mat containmentSupportsPotentials(3, sizes, CV_64F);\n containmentSupportsPotentials.setTo(1);\n int indices[] = {1,1,0};\/\/Forbid true, true, false case\n containmentSupportsPotentials.at<double>(indices) = 0;\n\n std::vector<ml::VariableClass>classes;\n classes.push_back(*_inRelationVariableClass);\n classes.push_back(*_ontRelationVariableClass);\n classes.push_back(*_ontRelationVariableClass);\n\n _containmentSupportsFactorClass = &_fcs->addFactorClass(classes, containmentSupportsPotentials);\n }\n\n {\n int dimensions = inCount + ontCount + onCount;\n int *sizes = new int[dimensions];\n for (int i = 0; i < dimensions; i++) {\n sizes[i] = 2;\n }\n cv::Mat directSupportRequiredPotentials(dimensions, sizes, CV_64F);\n directSupportRequiredPotentials.setTo(1);\n\n \/\/For all (x,y)\n \/\/ If ONt(x,y) and ~ON(x,y)\n \/\/ For all z1\n \/\/ if (~ONt(z,y) or (~ON(x,z) and ~IN(x,z)))\n \/\/ For all z2...\n \/\/ ...\n \/\/ set false\n\n std::vector<ml::VariableClass>classes;\n \/\/classes filled out as follows:\n \/\/ONt(x,y) (LHS),\n \/\/ON(x,y) (RHS),\n \/\/IN(x,y),\n \/\/ONt(z1,y)\t\t\n \/\/ON(x,z1) \t\t\n \/\/IN(x,z1) \t\t\n \/\/ONt(z2,y) ...\/\/excluding ONt(x,y)\n \/\/ON(x,z2) \/\/excluding ON(x,y)\n \/\/IN(x,z2) \/\/excluding IN(x,y)\n for(int i = 0; i < dimensions; i+=3) {\n classes.push_back(*_ontRelationVariableClass);\n classes.push_back(*_onRelationVariableClass);\n classes.push_back(*_inRelationVariableClass);\n }\n\n int *indices = new int[dimensions];\n indices[0] = 1;\/\/ONt(x,y)\n indices[1] = 0;\/\/~ON(x,y)\n indices[2] = 0;\/\/~IN(x,y)\n recurseSupportRequirement(directSupportRequiredPotentials, indices, 3, dimensions);\n indices[2] = 1;\/\/IN(x,y)\n recurseSupportRequirement(directSupportRequiredPotentials, indices, 3, dimensions);\n\n _directSupportRequiredFactorClass = &_fcs->addFactorClass(classes, directSupportRequiredPotentials);\n }\n\n {\n int dimensions = inCount + ontCount;\n int *sizes = new int[dimensions];\n for (int i = 0; i < dimensions; i++) {\n sizes[i] = 2;\n }\n cv::Mat supportRequiredPotentials(dimensions, sizes, CV_64F);\n supportRequiredPotentials.setTo(1);\n\n \/\/classes filled out as follows:\n \/\/ONt(x,y1),\n \/\/IN(x,y1),\n \/\/ONt(x,y2) ... \/\/excluding ONt(x,x)\n \/\/IN(x,y2) ... \/\/excluding IN(x,x)\n\n std::vector<ml::VariableClass>classes;\n int *indices = new int[dimensions];\n for(int i = 0; i < dimensions; i+=2) {\n classes.push_back(*_ontRelationVariableClass);\n classes.push_back(*_inRelationVariableClass);\n indices[i] = 0;\t\t\/\/~ONt(x,y)\n indices[i+1] = 0;\t\t\/\/~IN(x,y)\n }\n\n supportRequiredPotentials.at<double>(indices) = 0;\n _supportRequiredFactorClass = &_fcs->addFactorClass(classes, supportRequiredPotentials);\n }\n\n {\n \/\/Assume relations given are ON(x,y) and ON(x,z) where y!=z\n int sizes[] = {2, 2};\n cv::Mat uniqueSupportPotentials(2, sizes, CV_64F);\n uniqueSupportPotentials.setTo(1);\n int indices[] = {1,0};\/\/Forbid true, true, false case\n uniqueSupportPotentials.at<double>(indices) = 0;\n\n _uniqueSupportFactorClass = &_fcs->addFactorClass(*_onRelationVariableClass,\n\t*_ontRelationVariableClass, uniqueSupportPotentials);\n }\n\n {\n \/\/Assume relations given are ONt(x,y), ONt(x,z), ONt(y,z), ONt(z,y)\n int sizes[] = {2, 2, 2, 2};\n cv::Mat uniqueTransitiveSupportPotentials(4, sizes, CV_64F);\n uniqueTransitiveSupportPotentials.setTo(1);\n int indices[] = {1,1,0,0};\/\/Forbid true, true, false, false case\n uniqueTransitiveSupportPotentials.at<double>(indices) = 0;\n\n std::vector<ml::VariableClass>classes;\n classes.push_back(*_ontRelationVariableClass);\n classes.push_back(*_ontRelationVariableClass);\n classes.push_back(*_ontRelationVariableClass);\n classes.push_back(*_ontRelationVariableClass);\n\n _uniqueTransitiveSupportFactorClass = &_fcs->addFactorClass(classes, uniqueTransitiveSupportPotentials);\n }\n\n {\n \/\/Assume relations given are IN(x,y), IN(x,z), IN(y,z), IN(z,y)\n int sizes[] = {2, 2, 2, 2};\n cv::Mat uniqueInnessPotentials(4, sizes, CV_64F);\n uniqueInnessPotentials.setTo(1);\n int indices[] = {1,1,0,0};\/\/Forbid true, true, false, false case\n uniqueInnessPotentials.at<double>(indices) = 0;\n\n std::vector<ml::VariableClass>classes;\n classes.push_back(*_inRelationVariableClass);\n classes.push_back(*_inRelationVariableClass);\n classes.push_back(*_inRelationVariableClass);\n classes.push_back(*_inRelationVariableClass);\n\n _uniqueInnessFactorClass = &_fcs->addFactorClass(classes, uniqueInnessPotentials);\n }\n}\n\n\n};\n};\n<|endoftext|>"} {"text":"<commit_before>\/* DummyModule.cpp - stalkware(1) dummy module implementation\n * stalkware - blah bleh - (C) 2013, Timo Buhrmester\n * See README for contact-, COPYING for license information. *\/\n\n#if HAVE_CONFIG_H\n# include <config.h>\n#endif\n\n#include <cstdlib>\n#include <cstdio>\n#include <ctime>\n\n#include \"DummyModule.h\"\n\n#define DEF_MINROLL 4\n\nDummyModule::DummyModule()\n: Module(),\n name_(\"N\/A\"),\n minroll_(DEF_MINROLL),\n pstr_(\"DummyPlatform\")\n{\n}\n\nDummyModule::~DummyModule()\n{\n}\n\nbool\nDummyModule::init(string const& name, map<string, cfgent> const& cfg)\n{\n\tsrand(time(NULL));\n\tname_ = name;\n\tif (cfg.count(\"minroll\"))\n\t\tminroll_ = (int)cfg.at(\"minroll\").val.lng_;\n}\n\nstring const&\nDummyModule::name() const\n{\n\treturn name_;\n}\n\nvoid\nDummyModule::check(vector<vector<string> > const& stalkees,\n\t\tvector<pair<string, string> > & result) const\n{\n\tfor(vector<vector<string> >::const_iterator sit = stalkees.begin();\n\t\t\tsit != stalkees.end(); sit++) {\n\t\tstring extname = (*sit)[0];\n\t\tfor(vector<string>::const_iterator nit = sit->begin() + 1;\n\t\t\t\tnit != sit->end(); nit++) {\n\n\t\t\tstring intname = *nit;\n\t\t\tif (find_user(intname)) {\n\t\t\t\tresult.push_back(pair<string, string>(\n\t\t\t\t\t\textname, intname));\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n}\n\nbool\nDummyModule::find_user(string const& intname) const\n{\n\treturn (rand()>>3) % 6 >= minroll_-1;\n}\n<commit_msg>forgot return in init<commit_after>\/* DummyModule.cpp - stalkware(1) dummy module implementation\n * stalkware - blah bleh - (C) 2013, Timo Buhrmester\n * See README for contact-, COPYING for license information. *\/\n\n#if HAVE_CONFIG_H\n# include <config.h>\n#endif\n\n#include <cstdlib>\n#include <cstdio>\n#include <ctime>\n\n#include \"DummyModule.h\"\n\n#define DEF_MINROLL 4\n\nDummyModule::DummyModule()\n: Module(),\n name_(\"N\/A\"),\n minroll_(DEF_MINROLL),\n pstr_(\"DummyPlatform\")\n{\n}\n\nDummyModule::~DummyModule()\n{\n}\n\nbool\nDummyModule::init(string const& name, map<string, cfgent> const& cfg)\n{\n\tsrand(time(NULL));\n\tname_ = name;\n\tif (cfg.count(\"minroll\"))\n\t\tminroll_ = (int)cfg.at(\"minroll\").val.lng_;\n\treturn true;\n}\n\nstring const&\nDummyModule::name() const\n{\n\treturn name_;\n}\n\nvoid\nDummyModule::check(vector<vector<string> > const& stalkees,\n\t\tvector<pair<string, string> > & result) const\n{\n\tfor(vector<vector<string> >::const_iterator sit = stalkees.begin();\n\t\t\tsit != stalkees.end(); sit++) {\n\t\tstring extname = (*sit)[0];\n\t\tfor(vector<string>::const_iterator nit = sit->begin() + 1;\n\t\t\t\tnit != sit->end(); nit++) {\n\n\t\t\tstring intname = *nit;\n\t\t\tif (find_user(intname)) {\n\t\t\t\tresult.push_back(pair<string, string>(\n\t\t\t\t\t\textname, intname));\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n}\n\nbool\nDummyModule::find_user(string const& intname) const\n{\n\treturn (rand()>>3) % 6 >= minroll_-1;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2015 Charles D. Aylward\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/\n\/\/ A (possibly updated) copy of of this software is available at\n\/\/ https:\/\/github.com\/cdaylward\/nosecone\n\n#include <algorithm>\n#include <chrono>\n#include <fstream>\n#include <iostream>\n\n#include \"3rdparty\/cdaylward\/pathname.h\"\n#include \"3rdparty\/nlohmann\/json.h\"\n\n#include \"appc\/schema\/image.h\"\n#include \"appc\/os\/mkdir.h\"\n\n#include \"nosecone\/help.h\"\n#include \"nosecone\/config.h\"\n#include \"nosecone\/command\/run.h\"\n#include \"nosecone\/executor\/fetch.h\"\n#include \"nosecone\/executor\/uuid.h\"\n#include \"nosecone\/executor\/container.h\"\n#include \"nosecone\/executor\/container\/linux.h\"\n\n#include \"appc\/discovery\/types.h\"\n\n\nnamespace nosecone {\nnamespace command {\n\n\nusing Json = nlohmann::json;\nusing namespace nosecone::executor;\n\n\nstatic Json to_json(const Container& container) {\n Json json{};\n \/\/ TODO Move to container start time, not to_json time.\n using clock = std::chrono::system_clock;\n json[\"created\"] = std::chrono::duration_cast<std::chrono::seconds>(\n clock::now().time_since_epoch()).count();\n json[\"id\"] = container.id();\n json[\"pid\"] = container.pid();\n json[\"has_pty\"] = container.has_pty();\n return json;\n}\n\n\nstatic void dump_container_stdout(const Container& container) {\n const int pty_master_fd = container.pty_fd();\n char pty_buffer[4096];\n for (int rc = 0;\n rc != -1;\n rc = read(pty_master_fd, pty_buffer, sizeof(pty_buffer) - 1)) {\n if (rc > 0) {\n pty_buffer[rc] = '\\0';\n std::cout << pty_buffer;\n }\n }\n}\n\n\nint perform_run(const Arguments& args) {\n if (args.ordered_args.size() < 1) {\n std::cerr << \"Missing argument: <app name>\" << std::endl << std::endl;\n print_help(command::run);\n return EXIT_FAILURE;\n }\n\n const appc::discovery::Name name{args.ordered_args[0]};\n\n appc::discovery::Labels labels = config.default_labels;\n\n if (args.ordered_args.size() > 1) {\n for (auto iter = args.ordered_args.begin() + 1; iter != args.ordered_args.end(); iter++) {\n auto& label_set = *iter;\n auto delim = label_set.find(\":\");\n if (delim == std::string::npos ||\n delim == label_set.length() - 1) {\n std::cerr << \"Additional argument that isn't a label: \" << label_set << std::endl;\n return EXIT_FAILURE;\n }\n auto name = label_set.substr(0, delim);\n auto value = label_set.substr(delim + 1);\n labels[name] = value;\n }\n }\n\n const bool wait_for_container = args.has_flag(\"wait\") ? true : false;\n const bool dump_stdout = args.has_flag(\"stdout\") ? true : false;\n\n if (geteuid() != 0) {\n std::cerr << \"Containers can only be started by root.\" << std::endl;\n return EXIT_FAILURE;\n }\n\n const auto made_nosecone_root = appc::os::mkdir(config.containers_path, 0755, true);\n if (!made_nosecone_root) {\n std::cerr << \"Could not create dir for containers: \" << made_nosecone_root.message << std::endl;\n return EXIT_FAILURE;\n }\n\n auto images_try = fetch_and_validate(name, labels, true);\n if (!images_try) {\n std::cerr << images_try.failure_reason() << std::endl;\n return EXIT_FAILURE;\n }\n\n auto images = from_result(images_try);\n\n if (!images[0].manifest.app) {\n std::cerr << \"Image has no app, nothing to run.\" << std::endl;\n return EXIT_FAILURE;\n }\n\n const auto uuid_try = new_uuid();\n if (!uuid_try) {\n std::cerr << \"Could not generate uuid: \" << uuid_try.failure_reason() << std::endl;\n return EXIT_FAILURE;\n }\n\n const auto uuid = from_result(uuid_try);\n\n std::cerr << \"Container ID: \" << uuid << std::endl;\n\n const std::string container_root = pathname::join(config.containers_path, uuid);\n auto container = container::linux::Container(uuid, container_root, images);\n\n container.create_rootfs();\n \/\/ always?\n container.create_pty();\n auto started = container.start();\n if (!started) {\n std::cerr << \"Could not start container: \" << started.message << std::endl;\n return EXIT_FAILURE;\n }\n\n \/\/ REM we are potentially cloned (forked) here, so check that we are the parent of the\n \/\/ container before doing parent things.\n if (parent_of(container)) {\n std::cerr << \"Container started, PID: \" << container.pid() << std::endl;\n \/\/ TODO move this to container.start...probably.\n auto info_json = to_json(container);\n const auto container_info_file = pathname::join(container_root, \"info\");\n std::ofstream info(container_info_file);\n if (info) {\n info << info_json.dump(4) << std::endl;\n info.close();\n }\n if (dump_stdout) {\n std::cerr << \"--- 8< ---\" << std::endl;\n dump_container_stdout(container);\n } else if (wait_for_container) {\n auto waited = await(container);\n }\n }\n\n return EXIT_SUCCESS;\n}\n\n\n} \/\/ namespace command\n} \/\/ namespace nosecone\n<commit_msg>run: Fix for loss of precision in term reader<commit_after>\/\/ Copyright 2015 Charles D. Aylward\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/\n\/\/ A (possibly updated) copy of of this software is available at\n\/\/ https:\/\/github.com\/cdaylward\/nosecone\n\n#include <algorithm>\n#include <chrono>\n#include <fstream>\n#include <iostream>\n\n#include \"3rdparty\/cdaylward\/pathname.h\"\n#include \"3rdparty\/nlohmann\/json.h\"\n\n#include \"appc\/schema\/image.h\"\n#include \"appc\/os\/mkdir.h\"\n\n#include \"nosecone\/help.h\"\n#include \"nosecone\/config.h\"\n#include \"nosecone\/command\/run.h\"\n#include \"nosecone\/executor\/fetch.h\"\n#include \"nosecone\/executor\/uuid.h\"\n#include \"nosecone\/executor\/container.h\"\n#include \"nosecone\/executor\/container\/linux.h\"\n\n#include \"appc\/discovery\/types.h\"\n\n\nnamespace nosecone {\nnamespace command {\n\n\nusing Json = nlohmann::json;\nusing namespace nosecone::executor;\n\n\nstatic Json to_json(const Container& container) {\n Json json{};\n \/\/ TODO Move to container start time, not to_json time.\n using clock = std::chrono::system_clock;\n json[\"created\"] = std::chrono::duration_cast<std::chrono::seconds>(\n clock::now().time_since_epoch()).count();\n json[\"id\"] = container.id();\n json[\"pid\"] = container.pid();\n json[\"has_pty\"] = container.has_pty();\n return json;\n}\n\n\nstatic void dump_container_stdout(const Container& container) {\n const int pty_master_fd = container.pty_fd();\n char pty_buffer[4096];\n for (ssize_t rc = 0;\n rc != -1;\n rc = read(pty_master_fd, pty_buffer, sizeof(pty_buffer) - 1)) {\n if (rc > 0) {\n pty_buffer[rc] = '\\0';\n std::cout << pty_buffer;\n }\n }\n}\n\n\nint perform_run(const Arguments& args) {\n if (args.ordered_args.size() < 1) {\n std::cerr << \"Missing argument: <app name>\" << std::endl << std::endl;\n print_help(command::run);\n return EXIT_FAILURE;\n }\n\n const appc::discovery::Name name{args.ordered_args[0]};\n\n appc::discovery::Labels labels = config.default_labels;\n\n if (args.ordered_args.size() > 1) {\n for (auto iter = args.ordered_args.begin() + 1; iter != args.ordered_args.end(); iter++) {\n auto& label_set = *iter;\n auto delim = label_set.find(\":\");\n if (delim == std::string::npos ||\n delim == label_set.length() - 1) {\n std::cerr << \"Additional argument that isn't a label: \" << label_set << std::endl;\n return EXIT_FAILURE;\n }\n auto name = label_set.substr(0, delim);\n auto value = label_set.substr(delim + 1);\n labels[name] = value;\n }\n }\n\n const bool wait_for_container = args.has_flag(\"wait\") ? true : false;\n const bool dump_stdout = args.has_flag(\"stdout\") ? true : false;\n\n if (geteuid() != 0) {\n std::cerr << \"Containers can only be started by root.\" << std::endl;\n return EXIT_FAILURE;\n }\n\n const auto made_nosecone_root = appc::os::mkdir(config.containers_path, 0755, true);\n if (!made_nosecone_root) {\n std::cerr << \"Could not create dir for containers: \" << made_nosecone_root.message << std::endl;\n return EXIT_FAILURE;\n }\n\n auto images_try = fetch_and_validate(name, labels, true);\n if (!images_try) {\n std::cerr << images_try.failure_reason() << std::endl;\n return EXIT_FAILURE;\n }\n\n auto images = from_result(images_try);\n\n if (!images[0].manifest.app) {\n std::cerr << \"Image has no app, nothing to run.\" << std::endl;\n return EXIT_FAILURE;\n }\n\n const auto uuid_try = new_uuid();\n if (!uuid_try) {\n std::cerr << \"Could not generate uuid: \" << uuid_try.failure_reason() << std::endl;\n return EXIT_FAILURE;\n }\n\n const auto uuid = from_result(uuid_try);\n\n std::cerr << \"Container ID: \" << uuid << std::endl;\n\n const std::string container_root = pathname::join(config.containers_path, uuid);\n auto container = container::linux::Container(uuid, container_root, images);\n\n container.create_rootfs();\n \/\/ always?\n container.create_pty();\n auto started = container.start();\n if (!started) {\n std::cerr << \"Could not start container: \" << started.message << std::endl;\n return EXIT_FAILURE;\n }\n\n \/\/ REM we are potentially cloned (forked) here, so check that we are the parent of the\n \/\/ container before doing parent things.\n if (parent_of(container)) {\n std::cerr << \"Container started, PID: \" << container.pid() << std::endl;\n \/\/ TODO move this to container.start...probably.\n auto info_json = to_json(container);\n const auto container_info_file = pathname::join(container_root, \"info\");\n std::ofstream info(container_info_file);\n if (info) {\n info << info_json.dump(4) << std::endl;\n info.close();\n }\n if (dump_stdout) {\n std::cerr << \"--- 8< ---\" << std::endl;\n dump_container_stdout(container);\n } else if (wait_for_container) {\n auto waited = await(container);\n }\n }\n\n return EXIT_SUCCESS;\n}\n\n\n} \/\/ namespace command\n} \/\/ namespace nosecone\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright NVIDIA Corporation 2007 -- Ignacio Castano <icastano@nvidia.com>\r\n\/\/ \r\n\/\/ Permission is hereby granted, free of charge, to any person\r\n\/\/ obtaining a copy of this software and associated documentation\r\n\/\/ files (the \"Software\"), to deal in the Software without\r\n\/\/ restriction, including without limitation the rights to use,\r\n\/\/ copy, modify, merge, publish, distribute, sublicense, and\/or sell\r\n\/\/ copies of the Software, and to permit persons to whom the\r\n\/\/ Software is furnished to do so, subject to the following\r\n\/\/ conditions:\r\n\/\/ \r\n\/\/ The above copyright notice and this permission notice shall be\r\n\/\/ included in all copies or substantial portions of the Software.\r\n\/\/ \r\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\r\n\/\/ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES\r\n\/\/ OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\r\n\/\/ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\r\n\/\/ HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,\r\n\/\/ WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\r\n\/\/ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\r\n\/\/ OTHER DEALINGS IN THE SOFTWARE.\r\n\r\n#include <nvtt\/nvtt.h>\r\n#include <nvimage\/Image.h>\r\n#include <nvimage\/ImageIO.h>\r\n#include <nvimage\/BlockDXT.h>\r\n#include <nvimage\/ColorBlock.h>\r\n#include <nvcore\/Ptr.h>\r\n#include <nvcore\/Debug.h>\r\n#include <nvcore\/StrLib.h>\r\n#include <nvcore\/StdStream.h>\r\n#include <nvcore\/TextWriter.h>\r\n#include <nvcore\/FileSystem.h>\r\n\r\n#include <stdlib.h> \/\/ free\r\n#include <string.h> \/\/ memcpy\r\n#include <time.h> \/\/ clock\r\n\r\n\r\nusing namespace nv;\r\n\r\n\/\/ Kodak image set\r\nstatic const char * s_kodakImageSet[] = {\r\n\t\"kodim01.png\",\r\n\t\"kodim02.png\",\r\n\t\"kodim03.png\",\r\n\t\"kodim04.png\",\r\n\t\"kodim05.png\",\r\n\t\"kodim06.png\",\r\n\t\"kodim07.png\",\r\n\t\"kodim08.png\",\r\n\t\"kodim09.png\",\r\n\t\"kodim10.png\",\r\n\t\"kodim11.png\",\r\n\t\"kodim12.png\",\r\n\t\"kodim13.png\",\r\n\t\"kodim14.png\",\r\n\t\"kodim15.png\",\r\n\t\"kodim16.png\",\r\n\t\"kodim17.png\",\r\n\t\"kodim18.png\",\r\n\t\"kodim19.png\",\r\n\t\"kodim20.png\",\r\n\t\"kodim21.png\",\r\n\t\"kodim22.png\",\r\n\t\"kodim23.png\",\r\n\t\"kodim24.png\",\r\n};\r\n\r\n\/\/ Waterloo image set\r\nstatic const char * s_waterlooImageSet[] = {\r\n\t\"clegg.png\",\r\n\t\"frymire.png\",\r\n\t\"lena.png\",\r\n\t\"monarch.png\",\r\n\t\"peppers.png\",\r\n\t\"sail.png\",\r\n\t\"serrano.png\",\r\n\t\"tulips.png\",\r\n};\r\n\r\n\/\/ Epic image set\r\nstatic const char * s_epicImageSet[] = {\r\n\t\"Bradley1.png\",\r\n\t\"Gradient.png\",\r\n\t\"MoreRocks.png\",\r\n\t\"Wall.png\",\r\n\t\"Rainbow.png\",\r\n\t\"Text.png\",\r\n};\r\n\r\nstruct ImageSet\r\n{\r\n\tconst char ** fileNames;\r\n\tint fileCount;\r\n};\r\n\r\nstatic ImageSet s_imageSets[] = {\r\n\t{s_kodakImageSet, sizeof(s_kodakImageSet)\/sizeof(s_kodakImageSet[0])},\r\n\t{s_waterlooImageSet, sizeof(s_waterlooImageSet)\/sizeof(s_waterlooImageSet[0])},\r\n\t{s_epicImageSet, sizeof(s_epicImageSet)\/sizeof(s_epicImageSet[0])},\r\n};\r\nconst int s_imageSetCount = sizeof(s_imageSets)\/sizeof(s_imageSets[0]);\r\n\r\n\r\nstruct MyOutputHandler : public nvtt::OutputHandler\r\n{\r\n\tMyOutputHandler() : m_data(NULL), m_ptr(NULL) {}\r\n\t~MyOutputHandler()\r\n\t{\r\n\t\tfree(m_data);\r\n\t}\r\n\r\n\tvirtual void beginImage(int size, int width, int height, int depth, int face, int miplevel)\r\n\t{\r\n\t\tm_size = size;\r\n\t\tm_width = width;\r\n\t\tm_height = height;\r\n\t\tfree(m_data);\r\n\t\tm_data = (unsigned char *)malloc(size);\r\n\t\tm_ptr = m_data;\r\n\t}\r\n\t\r\n\tvirtual bool writeData(const void * data, int size)\r\n\t{\r\n\t\tmemcpy(m_ptr, data, size);\r\n\t\tm_ptr += size;\r\n\t\treturn true;\r\n\t}\r\n\r\n\tImage * decompress(nvtt::Format format)\r\n\t{\r\n\t\tint bw = (m_width + 3) \/ 4;\r\n\t\tint bh = (m_height + 3) \/ 4;\r\n\r\n\t\tAutoPtr<Image> img( new Image() );\r\n\t\timg->allocate(m_width, m_height);\r\n\r\n\t\tif (format == nvtt::Format_BC1)\r\n\t\t{\r\n\t\t\tBlockDXT1 * block = (BlockDXT1 *)m_data;\r\n\r\n\t\t\tfor (int y = 0; y < bh; y++)\r\n\t\t\t{\r\n\t\t\t\tfor (int x = 0; x < bw; x++)\r\n\t\t\t\t{\r\n\t\t\t\t\tColorBlock colors;\r\n\t\t\t\t\tblock->decodeBlock(&colors);\r\n\r\n\t\t\t\t\tfor (int yy = 0; yy < 4; yy++)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tfor (int xx = 0; xx < 4; xx++)\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\tColor32 c = colors.color(xx, yy);\r\n\r\n\t\t\t\t\t\t\tif (x * 4 + xx < m_width && y * 4 + yy < m_height)\r\n\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\timg->pixel(x * 4 + xx, y * 4 + yy) = c;\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\tblock++;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\treturn img.release();\r\n\t}\r\n\r\n\tint m_size;\r\n\tint m_width;\r\n\tint m_height;\r\n\tunsigned char * m_data;\r\n\tunsigned char * m_ptr;\r\n};\r\n\r\n\r\nfloat rmsError(const Image * a, const Image * b)\r\n{\r\n\tnvCheck(a != NULL);\r\n\tnvCheck(b != NULL);\r\n\tnvCheck(a->width() == b->width());\r\n\tnvCheck(a->height() == b->height());\r\n\r\n\tint mse = 0;\r\n\r\n\tconst uint count = a->width() * a->height();\r\n\r\n\tfor (uint i = 0; i < count; i++)\r\n\t{\r\n\t\tColor32 c0 = a->pixel(i);\r\n\t\tColor32 c1 = b->pixel(i);\r\n\r\n\t\tint r = c0.r - c1.r;\r\n\t\tint g = c0.g - c1.g;\r\n\t\tint b = c0.b - c1.b;\r\n\t\t\/\/int a = c0.a - c1.a;\r\n\r\n\t\tmse += r * r;\r\n\t\tmse += g * g;\r\n\t\tmse += b * b;\r\n\t}\r\n\r\n\treturn sqrtf(float(mse) \/ count);\r\n}\r\n\r\n\r\nint main(int argc, char *argv[])\r\n{\r\n\tconst uint version = nvtt::version();\r\n\tconst uint major = version \/ 100;\r\n\tconst uint minor = version % 100;\r\n\t\r\n\tprintf(\"NVIDIA Texture Tools %u.%u - Copyright NVIDIA Corporation 2007 - 2008\\n\\n\", major, minor);\r\n\t\r\n\tint set = 0;\r\n\tbool fast = false;\r\n\tbool nocuda = false;\r\n\tbool showHelp = false;\r\n\tconst char * basePath = \"\";\r\n\tconst char * outPath = \"output\";\r\n\tconst char * regressPath = NULL;\r\n\t\r\n\t\/\/ Parse arguments.\r\n\tfor (int i = 1; i < argc; i++)\r\n\t{\r\n\t\tif (strcmp(\"-set\", argv[i]) == 0)\r\n\t\t{\r\n\t\t\tif (i+1 < argc && argv[i+1][0] != '-') {\r\n\t\t\t\tset = atoi(argv[i+1]);\r\n\t\t\t\ti++;\r\n\t\t\t}\r\n\t\t}\r\n\t\telse if (strcmp(\"-fast\", argv[i]) == 0)\r\n\t\t{\r\n\t\t\tfast = true;\r\n\t\t}\r\n\t\telse if (strcmp(\"-nocuda\", argv[i]) == 0)\r\n\t\t{\r\n\t\t\tnocuda = true;\r\n\t\t}\r\n\t\telse if (strcmp(\"-help\", argv[i]) == 0)\r\n\t\t{\r\n\t\t\tshowHelp = true;\r\n\t\t}\r\n\t\telse if (strcmp(\"-path\", argv[i]) == 0)\r\n\t\t{\r\n\t\t\tif (i+1 < argc && argv[i+1][0] != '-') {\r\n\t\t\t\tbasePath = argv[i+1];\r\n\t\t\t\ti++;\r\n\t\t\t}\r\n\t\t}\r\n\t\telse if (strcmp(\"-out\", argv[i]) == 0)\r\n\t\t{\r\n\t\t\tif (i+1 < argc && argv[i+1][0] != '-') {\r\n\t\t\t\toutPath = argv[i+1];\r\n\t\t\t\ti++;\r\n\t\t\t}\r\n\t\t}\r\n\t\telse if (strcmp(\"-regress\", argv[i]) == 0)\r\n\t\t{\r\n\t\t\tif (i+1 < argc && argv[i+1][0] != '-') {\r\n\t\t\t\tregressPath = argv[i+1];\r\n\t\t\t\ti++;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\tif (showHelp)\r\n\t{\r\n\t\tprintf(\"usage: nvtestsuite [options]\\n\\n\");\r\n\t\t\r\n\t\tprintf(\"Input options:\\n\");\r\n\t\tprintf(\" -path <path>\\tInput image path.\\n\");\r\n\t\tprintf(\" -set [0:2]\\tImage set.\\n\");\r\n\t\tprintf(\" -regress <path>\\tRegression directory.\\n\");\r\n\r\n\t\tprintf(\"Compression options:\\n\");\r\n\t\tprintf(\" -fast \\tFast compression.\\n\");\r\n\t\tprintf(\" -nocuda \\tDo not use cuda compressor.\\n\");\r\n\t\t\r\n\t\tprintf(\"Output options:\\n\");\r\n\t\tprintf(\" -out <path> \\tOutput directory.\\n\");\r\n\r\n\t\treturn 1;\r\n\t}\r\n\t\r\n\tnvtt::InputOptions inputOptions;\r\n\tinputOptions.setMipmapGeneration(false);\r\n\r\n\tnvtt::CompressionOptions compressionOptions;\r\n\tcompressionOptions.setFormat(nvtt::Format_BC1);\r\n\tif (fast)\r\n\t{\r\n\t\tcompressionOptions.setQuality(nvtt::Quality_Fastest);\r\n\t}\r\n\telse\r\n\t{\r\n\t\tcompressionOptions.setQuality(nvtt::Quality_Production);\r\n\t}\r\n\r\n\tnvtt::OutputOptions outputOptions;\r\n\toutputOptions.setOutputHeader(false);\r\n\r\n\tMyOutputHandler outputHandler;\r\n\toutputOptions.setOutputHandler(&outputHandler);\r\n\r\n\tnvtt::Context context;\r\n\tcontext.enableCudaAcceleration(!nocuda);\r\n\r\n\tFileSystem::changeDirectory(basePath);\r\n\tFileSystem::createDirectory(outPath);\r\n\r\n\tPath csvFileName;\r\n\tcsvFileName.format(\"%s\/result.csv\", outPath);\r\n\tStdOutputStream csvStream(csvFileName);\r\n\tTextWriter csvWriter(&csvStream);\r\n\r\n\tfloat totalTime = 0;\r\n\tfloat totalRMSE = 0;\r\n\tint failedTests = 0;\r\n\tfloat totalDiff = 0;\r\n\r\n\tconst char ** fileNames = s_imageSets[set].fileNames;\r\n\tint fileCount = s_imageSets[set].fileCount;\r\n\r\n\tfor (int i = 0; i < fileCount; i++)\r\n\t{\r\n\t\tAutoPtr<Image> img( new Image() );\r\n\t\t\r\n\t\tif (!img->load(fileNames[i]))\r\n\t\t{\r\n\t\t\tprintf(\"Input image '%s' not found.\\n\", fileNames[i]);\r\n\t\t\treturn EXIT_FAILURE;\r\n\t\t}\r\n\r\n\t\tinputOptions.setTextureLayout(nvtt::TextureType_2D, img->width(), img->height());\r\n\t\tinputOptions.setMipmapData(img->pixels(), img->width(), img->height());\r\n\r\n\t\tprintf(\"Compressing: \\t'%s'\\n\", fileNames[i]);\r\n\r\n\t\tclock_t start = clock();\r\n\r\n\t\tcontext.process(inputOptions, compressionOptions, outputOptions);\r\n\r\n\t\tclock_t end = clock();\r\n\t\tprintf(\" Time: \\t%.3f sec\\n\", float(end-start) \/ CLOCKS_PER_SEC);\r\n\t\ttotalTime += float(end-start);\r\n\r\n\t\tAutoPtr<Image> img_out( outputHandler.decompress(nvtt::Format_BC1) );\r\n\r\n\t\tPath outputFileName;\r\n\t\toutputFileName.format(\"%s\/%s\", outPath, fileNames[i]);\r\n\t\toutputFileName.stripExtension();\r\n\t\toutputFileName.append(\".png\");\r\n\t\tif (!ImageIO::save(outputFileName, img_out.ptr()))\r\n\t\t{\r\n\t\t\tprintf(\"Error saving file '%s'.\\n\", outputFileName.str());\r\n\t\t}\r\n\r\n\t\tfloat rmse = rmsError(img.ptr(), img_out.ptr());\r\n\t\ttotalRMSE += rmse;\r\n\r\n\t\tprintf(\" RMSE: \\t%.4f\\n\", rmse);\r\n\r\n\t\t\/\/ Output csv file\r\n\t\tcsvWriter << \"\\\"\" << fileNames[i] << \"\\\",\" << rmse << \"\\n\";\r\n\r\n\t\tif (regressPath != NULL)\r\n\t\t{\r\n\t\t\tPath regressFileName;\r\n\t\t\tregressFileName.format(\"%s\/%s\", regressPath, fileNames[i]);\r\n\t\t\tregressFileName.stripExtension();\r\n\t\t\tregressFileName.append(\".png\");\r\n\r\n\t\t\tAutoPtr<Image> img_reg( new Image() );\r\n\t\t\tif (!img_reg->load(regressFileName.str()))\r\n\t\t\t{\r\n\t\t\t\tprintf(\"Regression image '%s' not found.\\n\", regressFileName.str());\r\n\t\t\t\treturn EXIT_FAILURE;\r\n\t\t\t}\r\n\r\n\t\t\tfloat rmse_reg = rmsError(img.ptr(), img_reg.ptr());\r\n\r\n\t\t\tfloat diff = rmse_reg - rmse;\r\n\t\t\ttotalDiff += diff;\r\n\r\n\t\t\tconst char * text = \"PASSED\";\r\n\t\t\tif (equal(diff, 0)) text = \"PASSED\";\r\n\t\t\telse if (diff < 0) {\r\n\t\t\t\ttext = \"FAILED\";\r\n\t\t\t\tfailedTests++;\r\n\t\t\t}\r\n\r\n\t\t\tprintf(\" Diff: \\t%.4f (%s)\\n\", diff, text);\r\n\t\t}\r\n\r\n\t\tfflush(stdout);\r\n\t}\r\n\r\n\ttotalRMSE \/= fileCount;\r\n\ttotalDiff \/= fileCount;\r\n\r\n\tprintf(\"Total Results:\\n\");\r\n\tprintf(\" Total Time: \\t%.3f sec\\n\", totalTime \/ CLOCKS_PER_SEC);\r\n\tprintf(\" Average RMSE:\\t%.4f\\n\", totalRMSE);\r\n\r\n\tif (regressPath != NULL)\r\n\t{\r\n\t\tprintf(\"Regression Results:\\n\");\r\n\t\tprintf(\" Diff: %.4f\\n\", totalDiff);\r\n\t\tprintf(\" %d\/%d tests failed.\\n\", failedTests, fileCount);\r\n\t}\r\n\r\n\treturn EXIT_SUCCESS;\r\n}\r\n\r\n<commit_msg>Add farbrausch images to testsuite.<commit_after>\/\/ Copyright NVIDIA Corporation 2007 -- Ignacio Castano <icastano@nvidia.com>\r\n\/\/ \r\n\/\/ Permission is hereby granted, free of charge, to any person\r\n\/\/ obtaining a copy of this software and associated documentation\r\n\/\/ files (the \"Software\"), to deal in the Software without\r\n\/\/ restriction, including without limitation the rights to use,\r\n\/\/ copy, modify, merge, publish, distribute, sublicense, and\/or sell\r\n\/\/ copies of the Software, and to permit persons to whom the\r\n\/\/ Software is furnished to do so, subject to the following\r\n\/\/ conditions:\r\n\/\/ \r\n\/\/ The above copyright notice and this permission notice shall be\r\n\/\/ included in all copies or substantial portions of the Software.\r\n\/\/ \r\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\r\n\/\/ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES\r\n\/\/ OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\r\n\/\/ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\r\n\/\/ HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,\r\n\/\/ WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\r\n\/\/ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\r\n\/\/ OTHER DEALINGS IN THE SOFTWARE.\r\n\r\n#include <nvtt\/nvtt.h>\r\n#include <nvimage\/Image.h>\r\n#include <nvimage\/ImageIO.h>\r\n#include <nvimage\/BlockDXT.h>\r\n#include <nvimage\/ColorBlock.h>\r\n#include <nvcore\/Ptr.h>\r\n#include <nvcore\/Debug.h>\r\n#include <nvcore\/StrLib.h>\r\n#include <nvcore\/StdStream.h>\r\n#include <nvcore\/TextWriter.h>\r\n#include <nvcore\/FileSystem.h>\r\n\r\n#include <stdlib.h> \/\/ free\r\n#include <string.h> \/\/ memcpy\r\n#include <time.h> \/\/ clock\r\n\r\n\r\nusing namespace nv;\r\n\r\n\/\/ Kodak image set\r\nstatic const char * s_kodakImageSet[] = {\r\n\t\"kodim01.png\",\r\n\t\"kodim02.png\",\r\n\t\"kodim03.png\",\r\n\t\"kodim04.png\",\r\n\t\"kodim05.png\",\r\n\t\"kodim06.png\",\r\n\t\"kodim07.png\",\r\n\t\"kodim08.png\",\r\n\t\"kodim09.png\",\r\n\t\"kodim10.png\",\r\n\t\"kodim11.png\",\r\n\t\"kodim12.png\",\r\n\t\"kodim13.png\",\r\n\t\"kodim14.png\",\r\n\t\"kodim15.png\",\r\n\t\"kodim16.png\",\r\n\t\"kodim17.png\",\r\n\t\"kodim18.png\",\r\n\t\"kodim19.png\",\r\n\t\"kodim20.png\",\r\n\t\"kodim21.png\",\r\n\t\"kodim22.png\",\r\n\t\"kodim23.png\",\r\n\t\"kodim24.png\",\r\n};\r\n\r\n\/\/ Waterloo image set\r\nstatic const char * s_waterlooImageSet[] = {\r\n\t\"clegg.png\",\r\n\t\"frymire.png\",\r\n\t\"lena.png\",\r\n\t\"monarch.png\",\r\n\t\"peppers.png\",\r\n\t\"sail.png\",\r\n\t\"serrano.png\",\r\n\t\"tulips.png\",\r\n};\r\n\r\n\/\/ Epic image set\r\nstatic const char * s_epicImageSet[] = {\r\n\t\"Bradley1.png\",\r\n\t\"Gradient.png\",\r\n\t\"MoreRocks.png\",\r\n\t\"Wall.png\",\r\n\t\"Rainbow.png\",\r\n\t\"Text.png\",\r\n};\r\n\r\n\/\/ Farbrausch\r\nstatic const char * s_farbrauschImageSet[] = {\r\n\t\"t.2d.pn02.bmp\",\r\n\t\"t.aircondition.01.bmp\",\r\n\t\"t.bricks.02.bmp\",\r\n\t\"t.bricks.05.bmp\",\r\n\t\"t.concrete.cracked.01.bmp\",\r\n\t\"t.envi.colored02.bmp\",\r\n\t\"t.envi.colored03.bmp\",\r\n\t\"t.font.01.bmp\",\r\n\t\"t.sewers.01.bmp\",\r\n\t\"t.train.03.bmp\",\r\n\t\"t.yello.01.bmp\",\r\n};\r\n\r\nstruct ImageSet\r\n{\r\n\tconst char ** fileNames;\r\n\tint fileCount;\r\n};\r\n\r\nstatic ImageSet s_imageSets[] = {\r\n\t{s_kodakImageSet, sizeof(s_kodakImageSet)\/sizeof(s_kodakImageSet[0])},\r\n\t{s_waterlooImageSet, sizeof(s_waterlooImageSet)\/sizeof(s_waterlooImageSet[0])},\r\n\t{s_epicImageSet, sizeof(s_epicImageSet)\/sizeof(s_epicImageSet[0])},\r\n\t{s_farbrauschImageSet, sizeof(s_farbrauschImageSet)\/sizeof(s_farbrauschImageSet[0])},\r\n};\r\nconst int s_imageSetCount = sizeof(s_imageSets)\/sizeof(s_imageSets[0]);\r\n\r\n\r\nstruct MyOutputHandler : public nvtt::OutputHandler\r\n{\r\n\tMyOutputHandler() : m_data(NULL), m_ptr(NULL) {}\r\n\t~MyOutputHandler()\r\n\t{\r\n\t\tfree(m_data);\r\n\t}\r\n\r\n\tvirtual void beginImage(int size, int width, int height, int depth, int face, int miplevel)\r\n\t{\r\n\t\tm_size = size;\r\n\t\tm_width = width;\r\n\t\tm_height = height;\r\n\t\tfree(m_data);\r\n\t\tm_data = (unsigned char *)malloc(size);\r\n\t\tm_ptr = m_data;\r\n\t}\r\n\t\r\n\tvirtual bool writeData(const void * data, int size)\r\n\t{\r\n\t\tmemcpy(m_ptr, data, size);\r\n\t\tm_ptr += size;\r\n\t\treturn true;\r\n\t}\r\n\r\n\tImage * decompress(nvtt::Format format)\r\n\t{\r\n\t\tint bw = (m_width + 3) \/ 4;\r\n\t\tint bh = (m_height + 3) \/ 4;\r\n\r\n\t\tAutoPtr<Image> img( new Image() );\r\n\t\timg->allocate(m_width, m_height);\r\n\r\n\t\tif (format == nvtt::Format_BC1)\r\n\t\t{\r\n\t\t\tBlockDXT1 * block = (BlockDXT1 *)m_data;\r\n\r\n\t\t\tfor (int y = 0; y < bh; y++)\r\n\t\t\t{\r\n\t\t\t\tfor (int x = 0; x < bw; x++)\r\n\t\t\t\t{\r\n\t\t\t\t\tColorBlock colors;\r\n\t\t\t\t\tblock->decodeBlock(&colors);\r\n\r\n\t\t\t\t\tfor (int yy = 0; yy < 4; yy++)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tfor (int xx = 0; xx < 4; xx++)\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\tColor32 c = colors.color(xx, yy);\r\n\r\n\t\t\t\t\t\t\tif (x * 4 + xx < m_width && y * 4 + yy < m_height)\r\n\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\timg->pixel(x * 4 + xx, y * 4 + yy) = c;\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\tblock++;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\treturn img.release();\r\n\t}\r\n\r\n\tint m_size;\r\n\tint m_width;\r\n\tint m_height;\r\n\tunsigned char * m_data;\r\n\tunsigned char * m_ptr;\r\n};\r\n\r\n\r\nfloat rmsError(const Image * a, const Image * b)\r\n{\r\n\tnvCheck(a != NULL);\r\n\tnvCheck(b != NULL);\r\n\tnvCheck(a->width() == b->width());\r\n\tnvCheck(a->height() == b->height());\r\n\r\n\tint mse = 0;\r\n\r\n\tconst uint count = a->width() * a->height();\r\n\r\n\tfor (uint i = 0; i < count; i++)\r\n\t{\r\n\t\tColor32 c0 = a->pixel(i);\r\n\t\tColor32 c1 = b->pixel(i);\r\n\r\n\t\tint r = c0.r - c1.r;\r\n\t\tint g = c0.g - c1.g;\r\n\t\tint b = c0.b - c1.b;\r\n\t\t\/\/int a = c0.a - c1.a;\r\n\r\n\t\tmse += r * r;\r\n\t\tmse += g * g;\r\n\t\tmse += b * b;\r\n\t}\r\n\r\n\treturn sqrtf(float(mse) \/ count);\r\n}\r\n\r\n\r\nint main(int argc, char *argv[])\r\n{\r\n\tconst uint version = nvtt::version();\r\n\tconst uint major = version \/ 100;\r\n\tconst uint minor = version % 100;\r\n\t\r\n\tprintf(\"NVIDIA Texture Tools %u.%u - Copyright NVIDIA Corporation 2007 - 2008\\n\\n\", major, minor);\r\n\t\r\n\tint set = 0;\r\n\tbool fast = false;\r\n\tbool nocuda = false;\r\n\tbool showHelp = false;\r\n\tconst char * basePath = \"\";\r\n\tconst char * outPath = \"output\";\r\n\tconst char * regressPath = NULL;\r\n\t\r\n\t\/\/ Parse arguments.\r\n\tfor (int i = 1; i < argc; i++)\r\n\t{\r\n\t\tif (strcmp(\"-set\", argv[i]) == 0)\r\n\t\t{\r\n\t\t\tif (i+1 < argc && argv[i+1][0] != '-') {\r\n\t\t\t\tset = atoi(argv[i+1]);\r\n\t\t\t\ti++;\r\n\t\t\t}\r\n\t\t}\r\n\t\telse if (strcmp(\"-fast\", argv[i]) == 0)\r\n\t\t{\r\n\t\t\tfast = true;\r\n\t\t}\r\n\t\telse if (strcmp(\"-nocuda\", argv[i]) == 0)\r\n\t\t{\r\n\t\t\tnocuda = true;\r\n\t\t}\r\n\t\telse if (strcmp(\"-help\", argv[i]) == 0)\r\n\t\t{\r\n\t\t\tshowHelp = true;\r\n\t\t}\r\n\t\telse if (strcmp(\"-path\", argv[i]) == 0)\r\n\t\t{\r\n\t\t\tif (i+1 < argc && argv[i+1][0] != '-') {\r\n\t\t\t\tbasePath = argv[i+1];\r\n\t\t\t\ti++;\r\n\t\t\t}\r\n\t\t}\r\n\t\telse if (strcmp(\"-out\", argv[i]) == 0)\r\n\t\t{\r\n\t\t\tif (i+1 < argc && argv[i+1][0] != '-') {\r\n\t\t\t\toutPath = argv[i+1];\r\n\t\t\t\ti++;\r\n\t\t\t}\r\n\t\t}\r\n\t\telse if (strcmp(\"-regress\", argv[i]) == 0)\r\n\t\t{\r\n\t\t\tif (i+1 < argc && argv[i+1][0] != '-') {\r\n\t\t\t\tregressPath = argv[i+1];\r\n\t\t\t\ti++;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\tif (showHelp)\r\n\t{\r\n\t\tprintf(\"usage: nvtestsuite [options]\\n\\n\");\r\n\t\t\r\n\t\tprintf(\"Input options:\\n\");\r\n\t\tprintf(\" -path <path>\\tInput image path.\\n\");\r\n\t\tprintf(\" -set [0:2]\\tImage set.\\n\");\r\n\t\tprintf(\" -regress <path>\\tRegression directory.\\n\");\r\n\r\n\t\tprintf(\"Compression options:\\n\");\r\n\t\tprintf(\" -fast \\tFast compression.\\n\");\r\n\t\tprintf(\" -nocuda \\tDo not use cuda compressor.\\n\");\r\n\t\t\r\n\t\tprintf(\"Output options:\\n\");\r\n\t\tprintf(\" -out <path> \\tOutput directory.\\n\");\r\n\r\n\t\treturn 1;\r\n\t}\r\n\t\r\n\tnvtt::InputOptions inputOptions;\r\n\tinputOptions.setMipmapGeneration(false);\r\n\r\n\tnvtt::CompressionOptions compressionOptions;\r\n\tcompressionOptions.setFormat(nvtt::Format_BC1);\r\n\tif (fast)\r\n\t{\r\n\t\tcompressionOptions.setQuality(nvtt::Quality_Fastest);\r\n\t}\r\n\telse\r\n\t{\r\n\t\tcompressionOptions.setQuality(nvtt::Quality_Production);\r\n\t}\r\n\r\n\tnvtt::OutputOptions outputOptions;\r\n\toutputOptions.setOutputHeader(false);\r\n\r\n\tMyOutputHandler outputHandler;\r\n\toutputOptions.setOutputHandler(&outputHandler);\r\n\r\n\tnvtt::Context context;\r\n\tcontext.enableCudaAcceleration(!nocuda);\r\n\r\n\tFileSystem::changeDirectory(basePath);\r\n\tFileSystem::createDirectory(outPath);\r\n\r\n\tPath csvFileName;\r\n\tcsvFileName.format(\"%s\/result.csv\", outPath);\r\n\tStdOutputStream csvStream(csvFileName);\r\n\tTextWriter csvWriter(&csvStream);\r\n\r\n\tfloat totalTime = 0;\r\n\tfloat totalRMSE = 0;\r\n\tint failedTests = 0;\r\n\tfloat totalDiff = 0;\r\n\r\n\tconst char ** fileNames = s_imageSets[set].fileNames;\r\n\tint fileCount = s_imageSets[set].fileCount;\r\n\r\n\tfor (int i = 0; i < fileCount; i++)\r\n\t{\r\n\t\tAutoPtr<Image> img( new Image() );\r\n\t\t\r\n\t\tif (!img->load(fileNames[i]))\r\n\t\t{\r\n\t\t\tprintf(\"Input image '%s' not found.\\n\", fileNames[i]);\r\n\t\t\treturn EXIT_FAILURE;\r\n\t\t}\r\n\r\n\t\tinputOptions.setTextureLayout(nvtt::TextureType_2D, img->width(), img->height());\r\n\t\tinputOptions.setMipmapData(img->pixels(), img->width(), img->height());\r\n\r\n\t\tprintf(\"Compressing: \\t'%s'\\n\", fileNames[i]);\r\n\r\n\t\tclock_t start = clock();\r\n\r\n\t\tcontext.process(inputOptions, compressionOptions, outputOptions);\r\n\r\n\t\tclock_t end = clock();\r\n\t\tprintf(\" Time: \\t%.3f sec\\n\", float(end-start) \/ CLOCKS_PER_SEC);\r\n\t\ttotalTime += float(end-start);\r\n\r\n\t\tAutoPtr<Image> img_out( outputHandler.decompress(nvtt::Format_BC1) );\r\n\r\n\t\tPath outputFileName;\r\n\t\toutputFileName.format(\"%s\/%s\", outPath, fileNames[i]);\r\n\t\toutputFileName.stripExtension();\r\n\t\toutputFileName.append(\".png\");\r\n\t\tif (!ImageIO::save(outputFileName, img_out.ptr()))\r\n\t\t{\r\n\t\t\tprintf(\"Error saving file '%s'.\\n\", outputFileName.str());\r\n\t\t}\r\n\r\n\t\tfloat rmse = rmsError(img.ptr(), img_out.ptr());\r\n\t\ttotalRMSE += rmse;\r\n\r\n\t\tprintf(\" RMSE: \\t%.4f\\n\", rmse);\r\n\r\n\t\t\/\/ Output csv file\r\n\t\tcsvWriter << \"\\\"\" << fileNames[i] << \"\\\",\" << rmse << \"\\n\";\r\n\r\n\t\tif (regressPath != NULL)\r\n\t\t{\r\n\t\t\tPath regressFileName;\r\n\t\t\tregressFileName.format(\"%s\/%s\", regressPath, fileNames[i]);\r\n\t\t\tregressFileName.stripExtension();\r\n\t\t\tregressFileName.append(\".png\");\r\n\r\n\t\t\tAutoPtr<Image> img_reg( new Image() );\r\n\t\t\tif (!img_reg->load(regressFileName.str()))\r\n\t\t\t{\r\n\t\t\t\tprintf(\"Regression image '%s' not found.\\n\", regressFileName.str());\r\n\t\t\t\treturn EXIT_FAILURE;\r\n\t\t\t}\r\n\r\n\t\t\tfloat rmse_reg = rmsError(img.ptr(), img_reg.ptr());\r\n\r\n\t\t\tfloat diff = rmse_reg - rmse;\r\n\t\t\ttotalDiff += diff;\r\n\r\n\t\t\tconst char * text = \"PASSED\";\r\n\t\t\tif (equal(diff, 0)) text = \"PASSED\";\r\n\t\t\telse if (diff < 0) {\r\n\t\t\t\ttext = \"FAILED\";\r\n\t\t\t\tfailedTests++;\r\n\t\t\t}\r\n\r\n\t\t\tprintf(\" Diff: \\t%.4f (%s)\\n\", diff, text);\r\n\t\t}\r\n\r\n\t\tfflush(stdout);\r\n\t}\r\n\r\n\ttotalRMSE \/= fileCount;\r\n\ttotalDiff \/= fileCount;\r\n\r\n\tprintf(\"Total Results:\\n\");\r\n\tprintf(\" Total Time: \\t%.3f sec\\n\", totalTime \/ CLOCKS_PER_SEC);\r\n\tprintf(\" Average RMSE:\\t%.4f\\n\", totalRMSE);\r\n\r\n\tif (regressPath != NULL)\r\n\t{\r\n\t\tprintf(\"Regression Results:\\n\");\r\n\t\tprintf(\" Diff: %.4f\\n\", totalDiff);\r\n\t\tprintf(\" %d\/%d tests failed.\\n\", failedTests, fileCount);\r\n\t}\r\n\r\n\treturn EXIT_SUCCESS;\r\n}\r\n\r\n<|endoftext|>"} {"text":"<commit_before>\/**\n * Copyright 2015 Google Inc. All Rights Reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"identifier_evaluator.h\"\n#include \"i_dbg_stack_frame.h\"\n#include \"i_eval_coordinator.h\"\n#include \"dbg_object.h\"\n#include \"dbg_class_property.h\"\n\nnamespace google_cloud_debugger {\n\nIdentifierEvaluator::IdentifierEvaluator(std::string identifier_name)\n : identifier_name_(identifier_name) {\n}\n\nHRESULT IdentifierEvaluator::Compile(\n IDbgStackFrame *stack_frame,\n ICorDebugILFrame *debug_frame,\n std::ostream *err_stream) {\n \/\/ Only needs to check null for stack frame because we don't\n \/\/ invoke the other arguments.\n if (!stack_frame) {\n return E_INVALIDARG;\n }\n\n \/\/ Case 1: this is a local variable.\n HRESULT hr = stack_frame->GetLocalVariable(identifier_name_,\n &identifier_object_, err_stream);\n if (FAILED(hr)) {\n return hr;\n }\n\n \/\/ S_FALSE means there is no match.\n if (SUCCEEDED(hr) && hr != S_FALSE) {\n return identifier_object_->GetTypeSignature(&result_type_);\n }\n\n \/\/ Case 2: static and non-static fields and auto-implemented properties.\n hr = stack_frame->GetFieldAndAutoPropFromFrame(identifier_name_,\n &identifier_object_, debug_frame, err_stream);\n if (FAILED(hr)) {\n return hr;\n }\n\n \/\/ S_FALSE means there is no match.\n if (SUCCEEDED(hr) && hr != S_FALSE) {\n return identifier_object_->GetTypeSignature(&result_type_);\n }\n\n \/\/ Case 3: static and non-static properties with getter.\n hr = stack_frame->GetPropertyFromFrame(identifier_name_,\n &class_property_, err_stream);\n if (hr == S_FALSE) {\n hr = E_FAIL;\n }\n\n if (FAILED(hr)) {\n return hr;\n }\n\n hr = class_property_->GetTypeSignature(&result_type_);\n if (FAILED(hr)) {\n return hr;\n }\n\n \/\/ Generic type parameters for the class that the method is in.\n return stack_frame->GetClassGenericTypeParameters(debug_frame,\n &generic_class_types_);\n}\n\nHRESULT IdentifierEvaluator::Evaluate(\n std::shared_ptr<DbgObject> *dbg_object,\n IEvalCoordinator *eval_coordinator,\n IDbgObjectFactory *obj_factory,\n std::ostream * err_stream) const {\n if (class_property_ == nullptr) {\n *dbg_object = identifier_object_;\n return S_OK;\n }\n\n CComPtr<ICorDebugValue> invoking_object;\n\n HRESULT hr;\n \/\/ If this is a non-static property, we have to get the invoking object.\n if (!class_property_->IsStatic()) {\n CComPtr<ICorDebugILFrame> debug_frame;\n hr = eval_coordinator->GetActiveDebugFrame(&debug_frame);\n if (FAILED(hr)) {\n *err_stream << \"Failed to get the active debug frame.\";\n return hr;\n }\n\n \/\/ Returns this object.\n hr = debug_frame->GetArgument(0, &invoking_object);\n if (FAILED(hr)) {\n *err_stream << \"Failed to get the invoking object.\";\n return hr;\n }\n }\n\n hr = class_property_->Evaluate(invoking_object, eval_coordinator,\n const_cast<std::vector<CComPtr<ICorDebugType>> *>(&generic_class_types_));\n if (FAILED(hr)) {\n *err_stream << \"Failed to evaluate property.\";\n return hr;\n }\n\n *dbg_object = class_property_->GetMemberValue();\n return S_OK;\n}\n\n} \/\/ namespace google_cloud_debugger\n<commit_msg>Add clarifying comments in identifier evaluator<commit_after>\/**\n * Copyright 2015 Google Inc. All Rights Reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"identifier_evaluator.h\"\n#include \"i_dbg_stack_frame.h\"\n#include \"i_eval_coordinator.h\"\n#include \"dbg_object.h\"\n#include \"dbg_class_property.h\"\n\nnamespace google_cloud_debugger {\n\nIdentifierEvaluator::IdentifierEvaluator(std::string identifier_name)\n : identifier_name_(identifier_name) {\n}\n\nHRESULT IdentifierEvaluator::Compile(\n IDbgStackFrame *stack_frame,\n ICorDebugILFrame *debug_frame,\n std::ostream *err_stream) {\n \/\/ Only needs to check null for stack frame because we don't\n \/\/ invoke the other arguments.\n if (!stack_frame) {\n return E_INVALIDARG;\n }\n\n \/\/ Case 1: this is a local variable.\n HRESULT hr = stack_frame->GetLocalVariable(identifier_name_,\n &identifier_object_, err_stream);\n if (FAILED(hr)) {\n return hr;\n }\n\n \/\/ S_FALSE means there is no match.\n if (SUCCEEDED(hr) && hr != S_FALSE) {\n return identifier_object_->GetTypeSignature(&result_type_);\n }\n\n \/\/ Case 2: static and non-static fields and auto-implemented properties.\n hr = stack_frame->GetFieldAndAutoPropFromFrame(identifier_name_,\n &identifier_object_, debug_frame, err_stream);\n if (FAILED(hr)) {\n return hr;\n }\n\n \/\/ S_FALSE means there is no match.\n if (SUCCEEDED(hr) && hr != S_FALSE) {\n return identifier_object_->GetTypeSignature(&result_type_);\n }\n\n \/\/ Case 3: static and non-static properties with getter.\n hr = stack_frame->GetPropertyFromFrame(identifier_name_,\n &class_property_, err_stream);\n if (hr == S_FALSE) {\n hr = E_FAIL;\n }\n\n if (FAILED(hr)) {\n return hr;\n }\n\n hr = class_property_->GetTypeSignature(&result_type_);\n if (FAILED(hr)) {\n return hr;\n }\n\n \/\/ Generic type parameters for the class that the method is in.\n return stack_frame->GetClassGenericTypeParameters(debug_frame,\n &generic_class_types_);\n}\n\nHRESULT IdentifierEvaluator::Evaluate(\n std::shared_ptr<DbgObject> *dbg_object,\n IEvalCoordinator *eval_coordinator,\n IDbgObjectFactory *obj_factory,\n std::ostream * err_stream) const {\n if (class_property_ == nullptr) {\n *dbg_object = identifier_object_;\n return S_OK;\n }\n\n CComPtr<ICorDebugValue> invoking_object;\n\n HRESULT hr;\n \/\/ If this is a non-static property, we have to get the invoking object.\n if (!class_property_->IsStatic()) {\n CComPtr<ICorDebugILFrame> debug_frame;\n hr = eval_coordinator->GetActiveDebugFrame(&debug_frame);\n if (FAILED(hr)) {\n *err_stream << \"Failed to get the active debug frame.\";\n return hr;\n }\n\n \/\/ Returns 'this' object.\n hr = debug_frame->GetArgument(0, &invoking_object);\n if (FAILED(hr)) {\n *err_stream << \"Failed to get the invoking object.\";\n return hr;\n }\n }\n\n hr = class_property_->Evaluate(invoking_object, eval_coordinator,\n const_cast<std::vector<CComPtr<ICorDebugType>> *>(&generic_class_types_));\n if (FAILED(hr)) {\n *err_stream << \"Failed to evaluate property.\";\n return hr;\n }\n\n *dbg_object = class_property_->GetMemberValue();\n return S_OK;\n}\n\n} \/\/ namespace google_cloud_debugger\n<|endoftext|>"} {"text":"<commit_before>#include \"stock\/Stock.hxx\"\n#include \"stock\/Class.hxx\"\n#include \"stock\/GetHandler.hxx\"\n#include \"stock\/Item.hxx\"\n#include \"event\/Base.hxx\"\n#include \"async.hxx\"\n#include \"pool.hxx\"\n\n#include <glib.h>\n\n#include <assert.h>\n\nstatic unsigned num_create, num_fail, num_borrow, num_release, num_destroy;\nstatic bool next_fail;\nstatic bool got_item;\nstatic StockItem *last_item;\n\nstruct MyStockItem final : PoolStockItem {\n void *info;\n\n explicit MyStockItem(struct pool &_pool, CreateStockItem c)\n :PoolStockItem(_pool, c) {}\n\n ~MyStockItem() override {\n ++num_destroy;\n }\n\n \/* virtual methods from class StockItem *\/\n bool Borrow(gcc_unused void *ctx) override {\n ++num_borrow;\n return true;\n }\n\n bool Release(gcc_unused void *ctx) override {\n ++num_release;\n return true;\n }\n};\n\nstatic inline GQuark\ntest_quark(void)\n{\n return g_quark_from_static_string(\"test\");\n}\n\n\/*\n * stock class\n *\n *\/\n\nstatic void\nmy_stock_create(void *ctx gcc_unused,\n struct pool &parent_pool, CreateStockItem c,\n gcc_unused const char *uri, void *info,\n gcc_unused struct pool &caller_pool,\n gcc_unused struct async_operation_ref &async_ref)\n{\n auto &pool = *pool_new_linear(&parent_pool, \"my_stock\", 512);\n auto *item = NewFromPool<MyStockItem>(pool, pool, c);\n\n item->info = info;\n\n if (next_fail) {\n ++num_fail;\n\n GError *error = g_error_new_literal(test_quark(), 0, \"next_fail\");\n item->InvokeCreateError(error);\n } else {\n ++num_create;\n item->InvokeCreateSuccess();\n }\n}\n\nstatic constexpr StockClass my_stock_class = {\n .create = my_stock_create,\n};\n\nclass MyStockGetHandler final : public StockGetHandler {\npublic:\n \/* virtual methods from class StockGetHandler *\/\n void OnStockItemReady(StockItem &item) override {\n assert(!got_item);\n\n got_item = true;\n last_item = &item;\n }\n\n void OnStockItemError(GError *error) override {\n g_printerr(\"%s\\n\", error->message);\n g_error_free(error);\n\n got_item = true;\n last_item = nullptr;\n }\n};\n\nint main(gcc_unused int argc, gcc_unused char **argv)\n{\n struct pool *pool;\n Stock *stock;\n struct async_operation_ref async_ref;\n StockItem *item, *second, *third;\n\n EventBase event_base;\n pool = pool_new_libc(nullptr, \"root\");\n\n stock = new Stock(*pool, my_stock_class, nullptr, nullptr, 3, 8);\n\n MyStockGetHandler handler;\n\n \/* create first item *\/\n\n stock->Get(*pool, nullptr, handler, async_ref);\n assert(got_item);\n assert(last_item != nullptr);\n assert(num_create == 1 && num_fail == 0);\n assert(num_borrow == 0 && num_release == 0 && num_destroy == 0);\n item = last_item;\n\n \/* release first item *\/\n\n stock->Put(*item, false);\n event_loop(EVLOOP_NONBLOCK);\n assert(num_create == 1 && num_fail == 0);\n assert(num_borrow == 0 && num_release == 1 && num_destroy == 0);\n\n \/* reuse first item *\/\n\n got_item = false;\n last_item = nullptr;\n stock->Get(*pool, nullptr, handler, async_ref);\n assert(got_item);\n assert(last_item == item);\n assert(num_create == 1 && num_fail == 0);\n assert(num_borrow == 1 && num_release == 1 && num_destroy == 0);\n\n \/* create second item *\/\n\n got_item = false;\n last_item = nullptr;\n stock->Get(*pool, nullptr, handler, async_ref);\n assert(got_item);\n assert(last_item != nullptr);\n assert(last_item != item);\n assert(num_create == 2 && num_fail == 0);\n assert(num_borrow == 1 && num_release == 1 && num_destroy == 0);\n second = last_item;\n\n \/* fail to create third item *\/\n\n next_fail = true;\n got_item = false;\n last_item = nullptr;\n stock->Get(*pool, nullptr, handler, async_ref);\n assert(got_item);\n assert(last_item == nullptr);\n assert(num_create == 2 && num_fail == 1);\n assert(num_borrow == 1 && num_release == 1 && num_destroy == 1);\n\n \/* create third item *\/\n\n next_fail = false;\n got_item = false;\n last_item = nullptr;\n stock->Get(*pool, nullptr, handler, async_ref);\n assert(got_item);\n assert(last_item != nullptr);\n assert(num_create == 3 && num_fail == 1);\n assert(num_borrow == 1 && num_release == 1 && num_destroy == 1);\n third = last_item;\n\n \/* fourth item waiting *\/\n\n got_item = false;\n last_item = nullptr;\n stock->Get(*pool, nullptr, handler, async_ref);\n assert(!got_item);\n assert(num_create == 3 && num_fail == 1);\n assert(num_borrow == 1 && num_release == 1 && num_destroy == 1);\n\n \/* fifth item waiting *\/\n\n stock->Get(*pool, nullptr, handler, async_ref);\n assert(!got_item);\n assert(num_create == 3 && num_fail == 1);\n assert(num_borrow == 1 && num_release == 1 && num_destroy == 1);\n\n \/* return third item *\/\n\n stock->Put(*third, false);\n event_loop(EVLOOP_NONBLOCK);\n assert(num_create == 3 && num_fail == 1);\n assert(num_borrow == 2 && num_release == 2 && num_destroy == 1);\n assert(got_item);\n assert(last_item == third);\n\n \/* destroy second item *\/\n\n got_item = false;\n last_item = nullptr;\n stock->Put(*second, true);\n event_loop(EVLOOP_NONBLOCK);\n assert(num_create == 4 && num_fail == 1);\n assert(num_borrow == 2 && num_release == 2 && num_destroy == 2);\n assert(got_item);\n assert(last_item != nullptr);\n second = last_item;\n\n \/* destroy first item *\/\n\n stock->Put(*item, true);\n assert(num_create == 4 && num_fail == 1);\n assert(num_borrow == 2 && num_release == 2 && num_destroy == 3);\n\n \/* destroy second item *\/\n\n stock->Put(*second, true);\n assert(num_create == 4 && num_fail == 1);\n assert(num_borrow == 2 && num_release == 2 && num_destroy == 4);\n\n \/* destroy third item *\/\n\n stock->Put(*third, true);\n assert(num_create == 4 && num_fail == 1);\n assert(num_borrow == 2 && num_release == 2 && num_destroy == 5);\n\n \/* cleanup *\/\n\n delete stock;\n\n pool_unref(pool);\n pool_commit();\n pool_recycler_clear();\n}\n<commit_msg>test\/t_stock: use HeapStockItem<commit_after>#include \"stock\/Stock.hxx\"\n#include \"stock\/Class.hxx\"\n#include \"stock\/GetHandler.hxx\"\n#include \"stock\/Item.hxx\"\n#include \"event\/Base.hxx\"\n#include \"async.hxx\"\n#include \"pool.hxx\"\n\n#include <glib.h>\n\n#include <assert.h>\n\nstatic unsigned num_create, num_fail, num_borrow, num_release, num_destroy;\nstatic bool next_fail;\nstatic bool got_item;\nstatic StockItem *last_item;\n\nstruct MyStockItem final : HeapStockItem {\n void *info;\n\n explicit MyStockItem(CreateStockItem c)\n :HeapStockItem(c) {}\n\n ~MyStockItem() override {\n ++num_destroy;\n }\n\n \/* virtual methods from class StockItem *\/\n bool Borrow(gcc_unused void *ctx) override {\n ++num_borrow;\n return true;\n }\n\n bool Release(gcc_unused void *ctx) override {\n ++num_release;\n return true;\n }\n};\n\nstatic inline GQuark\ntest_quark(void)\n{\n return g_quark_from_static_string(\"test\");\n}\n\n\/*\n * stock class\n *\n *\/\n\nstatic void\nmy_stock_create(gcc_unused void *ctx,\n gcc_unused struct pool &parent_pool, CreateStockItem c,\n gcc_unused const char *uri, void *info,\n gcc_unused struct pool &caller_pool,\n gcc_unused struct async_operation_ref &async_ref)\n{\n auto *item = new MyStockItem(c);\n\n item->info = info;\n\n if (next_fail) {\n ++num_fail;\n\n GError *error = g_error_new_literal(test_quark(), 0, \"next_fail\");\n item->InvokeCreateError(error);\n } else {\n ++num_create;\n item->InvokeCreateSuccess();\n }\n}\n\nstatic constexpr StockClass my_stock_class = {\n .create = my_stock_create,\n};\n\nclass MyStockGetHandler final : public StockGetHandler {\npublic:\n \/* virtual methods from class StockGetHandler *\/\n void OnStockItemReady(StockItem &item) override {\n assert(!got_item);\n\n got_item = true;\n last_item = &item;\n }\n\n void OnStockItemError(GError *error) override {\n g_printerr(\"%s\\n\", error->message);\n g_error_free(error);\n\n got_item = true;\n last_item = nullptr;\n }\n};\n\nint main(gcc_unused int argc, gcc_unused char **argv)\n{\n struct pool *pool;\n Stock *stock;\n struct async_operation_ref async_ref;\n StockItem *item, *second, *third;\n\n EventBase event_base;\n pool = pool_new_libc(nullptr, \"root\");\n\n stock = new Stock(*pool, my_stock_class, nullptr, nullptr, 3, 8);\n\n MyStockGetHandler handler;\n\n \/* create first item *\/\n\n stock->Get(*pool, nullptr, handler, async_ref);\n assert(got_item);\n assert(last_item != nullptr);\n assert(num_create == 1 && num_fail == 0);\n assert(num_borrow == 0 && num_release == 0 && num_destroy == 0);\n item = last_item;\n\n \/* release first item *\/\n\n stock->Put(*item, false);\n event_loop(EVLOOP_NONBLOCK);\n assert(num_create == 1 && num_fail == 0);\n assert(num_borrow == 0 && num_release == 1 && num_destroy == 0);\n\n \/* reuse first item *\/\n\n got_item = false;\n last_item = nullptr;\n stock->Get(*pool, nullptr, handler, async_ref);\n assert(got_item);\n assert(last_item == item);\n assert(num_create == 1 && num_fail == 0);\n assert(num_borrow == 1 && num_release == 1 && num_destroy == 0);\n\n \/* create second item *\/\n\n got_item = false;\n last_item = nullptr;\n stock->Get(*pool, nullptr, handler, async_ref);\n assert(got_item);\n assert(last_item != nullptr);\n assert(last_item != item);\n assert(num_create == 2 && num_fail == 0);\n assert(num_borrow == 1 && num_release == 1 && num_destroy == 0);\n second = last_item;\n\n \/* fail to create third item *\/\n\n next_fail = true;\n got_item = false;\n last_item = nullptr;\n stock->Get(*pool, nullptr, handler, async_ref);\n assert(got_item);\n assert(last_item == nullptr);\n assert(num_create == 2 && num_fail == 1);\n assert(num_borrow == 1 && num_release == 1 && num_destroy == 1);\n\n \/* create third item *\/\n\n next_fail = false;\n got_item = false;\n last_item = nullptr;\n stock->Get(*pool, nullptr, handler, async_ref);\n assert(got_item);\n assert(last_item != nullptr);\n assert(num_create == 3 && num_fail == 1);\n assert(num_borrow == 1 && num_release == 1 && num_destroy == 1);\n third = last_item;\n\n \/* fourth item waiting *\/\n\n got_item = false;\n last_item = nullptr;\n stock->Get(*pool, nullptr, handler, async_ref);\n assert(!got_item);\n assert(num_create == 3 && num_fail == 1);\n assert(num_borrow == 1 && num_release == 1 && num_destroy == 1);\n\n \/* fifth item waiting *\/\n\n stock->Get(*pool, nullptr, handler, async_ref);\n assert(!got_item);\n assert(num_create == 3 && num_fail == 1);\n assert(num_borrow == 1 && num_release == 1 && num_destroy == 1);\n\n \/* return third item *\/\n\n stock->Put(*third, false);\n event_loop(EVLOOP_NONBLOCK);\n assert(num_create == 3 && num_fail == 1);\n assert(num_borrow == 2 && num_release == 2 && num_destroy == 1);\n assert(got_item);\n assert(last_item == third);\n\n \/* destroy second item *\/\n\n got_item = false;\n last_item = nullptr;\n stock->Put(*second, true);\n event_loop(EVLOOP_NONBLOCK);\n assert(num_create == 4 && num_fail == 1);\n assert(num_borrow == 2 && num_release == 2 && num_destroy == 2);\n assert(got_item);\n assert(last_item != nullptr);\n second = last_item;\n\n \/* destroy first item *\/\n\n stock->Put(*item, true);\n assert(num_create == 4 && num_fail == 1);\n assert(num_borrow == 2 && num_release == 2 && num_destroy == 3);\n\n \/* destroy second item *\/\n\n stock->Put(*second, true);\n assert(num_create == 4 && num_fail == 1);\n assert(num_borrow == 2 && num_release == 2 && num_destroy == 4);\n\n \/* destroy third item *\/\n\n stock->Put(*third, true);\n assert(num_create == 4 && num_fail == 1);\n assert(num_borrow == 2 && num_release == 2 && num_destroy == 5);\n\n \/* cleanup *\/\n\n delete stock;\n\n pool_unref(pool);\n pool_commit();\n pool_recycler_clear();\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ async_queue.cpp (Oclgrind)\n\/\/ Copyright (c) 2013-2014, James Price and Simon McIntosh-Smith,\n\/\/ University of Bristol. All rights reserved.\n\/\/\n\/\/ This program is provided under a three-clause BSD license. For full\n\/\/ license terms please see the LICENSE file distributed with this\n\/\/ source code.\n\n#include \"async_queue.h\"\n\n#include <cassert>\n#include <iostream>\n#include <list>\n#include <map>\n\n#include <spirsim\/Kernel.h>\n#include <spirsim\/Queue.h>\n\nusing namespace oclgrind;\nusing namespace std;\n\n\/\/ Maps to keep track of retained objects\nstatic map< Queue::Command*, list<cl_mem> > memObjectMap;\nstatic map< Queue::Command*, cl_kernel > kernelMap;\nstatic map< Queue::Command*, cl_event > eventMap;\nstatic map< Queue::Command*, list<cl_event> > waitListMap;\n\nvoid asyncEnqueue(cl_command_queue queue,\n cl_command_type type,\n Queue::Command *cmd,\n cl_uint numEvents,\n const cl_event *waitList,\n cl_event *eventOut)\n{\n \/\/ Add event wait list to command\n for (int i = 0; i < numEvents; i++)\n {\n cmd->waitList.push_back(waitList[i]->event);\n waitListMap[cmd].push_back(waitList[i]);\n clRetainEvent(waitList[i]);\n }\n\n \/\/ Enqueue command\n Event *event = queue->queue->enqueue(cmd);\n\n \/\/ Create event objects\n cl_event _event = new _cl_event;\n _event->dispatch = m_dispatchTable;\n _event->context = queue->context;\n _event->queue = queue;\n _event->type = type;\n _event->event = event;\n _event->refCount = 1;\n\n \/\/ Add event to map\n eventMap[cmd] = _event;\n\n \/\/ Pass event as output and retain (if required)\n if (eventOut)\n {\n clRetainEvent(_event);\n *eventOut = _event;\n }\n}\n\nvoid asyncQueueRetain(Queue::Command *cmd, cl_mem mem)\n{\n \/\/ Retain object and add to map\n clRetainMemObject(mem);\n memObjectMap[cmd].push_back(mem);\n}\n\nvoid asyncQueueRetain(Queue::Command *cmd, cl_kernel kernel)\n{\n assert(kernelMap.find(cmd) == kernelMap.end());\n\n \/\/ Retain kernel and add to map\n clRetainKernel(kernel);\n kernelMap[cmd] = kernel;\n\n \/\/ Retain memory objects arguments\n map<cl_uint,cl_mem>::const_iterator itr;\n for (itr = kernel->memArgs.begin(); itr != kernel->memArgs.end(); itr++)\n {\n asyncQueueRetain(cmd, itr->second);\n }\n}\n\nvoid asyncQueueRelease(Queue::Command *cmd)\n{\n \/\/ Release memory objects\n if (memObjectMap.find(cmd) != memObjectMap.end())\n {\n list<cl_mem> memObjects = memObjectMap[cmd];\n while (!memObjects.empty())\n {\n clReleaseMemObject(memObjects.front());\n memObjects.pop_front();\n }\n memObjectMap.erase(cmd);\n }\n\n \/\/ Release kernel\n if (cmd->type == Queue::KERNEL)\n {\n assert(kernelMap.find(cmd) != kernelMap.end());\n clReleaseKernel(kernelMap[cmd]);\n kernelMap.erase(cmd);\n delete ((Queue::KernelCommand*)cmd)->kernel;\n }\n\n \/\/ Remove event from map\n cl_event event = eventMap[cmd];\n eventMap.erase(cmd);\n\n \/\/ Perform callbacks\n list< pair<void (CL_CALLBACK *)(cl_event, cl_int, void *),\n void*> >::iterator callItr;\n for (callItr = event->callbacks.begin();\n callItr != event->callbacks.end();\n callItr++)\n {\n callItr->first(event, event->event->state, callItr->second);\n }\n\n \/\/ Release events\n list<cl_event>::iterator waitItr;\n for (waitItr = waitListMap[cmd].begin();\n waitItr != waitListMap[cmd].end();\n waitItr++)\n {\n clReleaseEvent(*waitItr);\n }\n waitListMap.erase(cmd);\n clReleaseEvent(event);\n}\n<commit_msg>More includes with user-include syntax.<commit_after>\/\/ async_queue.cpp (Oclgrind)\n\/\/ Copyright (c) 2013-2014, James Price and Simon McIntosh-Smith,\n\/\/ University of Bristol. All rights reserved.\n\/\/\n\/\/ This program is provided under a three-clause BSD license. For full\n\/\/ license terms please see the LICENSE file distributed with this\n\/\/ source code.\n\n#include \"async_queue.h\"\n\n#include <cassert>\n#include <iostream>\n#include <list>\n#include <map>\n\n#include \"spirsim\/Kernel.h\"\n#include \"spirsim\/Queue.h\"\n\nusing namespace oclgrind;\nusing namespace std;\n\n\/\/ Maps to keep track of retained objects\nstatic map< Queue::Command*, list<cl_mem> > memObjectMap;\nstatic map< Queue::Command*, cl_kernel > kernelMap;\nstatic map< Queue::Command*, cl_event > eventMap;\nstatic map< Queue::Command*, list<cl_event> > waitListMap;\n\nvoid asyncEnqueue(cl_command_queue queue,\n cl_command_type type,\n Queue::Command *cmd,\n cl_uint numEvents,\n const cl_event *waitList,\n cl_event *eventOut)\n{\n \/\/ Add event wait list to command\n for (int i = 0; i < numEvents; i++)\n {\n cmd->waitList.push_back(waitList[i]->event);\n waitListMap[cmd].push_back(waitList[i]);\n clRetainEvent(waitList[i]);\n }\n\n \/\/ Enqueue command\n Event *event = queue->queue->enqueue(cmd);\n\n \/\/ Create event objects\n cl_event _event = new _cl_event;\n _event->dispatch = m_dispatchTable;\n _event->context = queue->context;\n _event->queue = queue;\n _event->type = type;\n _event->event = event;\n _event->refCount = 1;\n\n \/\/ Add event to map\n eventMap[cmd] = _event;\n\n \/\/ Pass event as output and retain (if required)\n if (eventOut)\n {\n clRetainEvent(_event);\n *eventOut = _event;\n }\n}\n\nvoid asyncQueueRetain(Queue::Command *cmd, cl_mem mem)\n{\n \/\/ Retain object and add to map\n clRetainMemObject(mem);\n memObjectMap[cmd].push_back(mem);\n}\n\nvoid asyncQueueRetain(Queue::Command *cmd, cl_kernel kernel)\n{\n assert(kernelMap.find(cmd) == kernelMap.end());\n\n \/\/ Retain kernel and add to map\n clRetainKernel(kernel);\n kernelMap[cmd] = kernel;\n\n \/\/ Retain memory objects arguments\n map<cl_uint,cl_mem>::const_iterator itr;\n for (itr = kernel->memArgs.begin(); itr != kernel->memArgs.end(); itr++)\n {\n asyncQueueRetain(cmd, itr->second);\n }\n}\n\nvoid asyncQueueRelease(Queue::Command *cmd)\n{\n \/\/ Release memory objects\n if (memObjectMap.find(cmd) != memObjectMap.end())\n {\n list<cl_mem> memObjects = memObjectMap[cmd];\n while (!memObjects.empty())\n {\n clReleaseMemObject(memObjects.front());\n memObjects.pop_front();\n }\n memObjectMap.erase(cmd);\n }\n\n \/\/ Release kernel\n if (cmd->type == Queue::KERNEL)\n {\n assert(kernelMap.find(cmd) != kernelMap.end());\n clReleaseKernel(kernelMap[cmd]);\n kernelMap.erase(cmd);\n delete ((Queue::KernelCommand*)cmd)->kernel;\n }\n\n \/\/ Remove event from map\n cl_event event = eventMap[cmd];\n eventMap.erase(cmd);\n\n \/\/ Perform callbacks\n list< pair<void (CL_CALLBACK *)(cl_event, cl_int, void *),\n void*> >::iterator callItr;\n for (callItr = event->callbacks.begin();\n callItr != event->callbacks.end();\n callItr++)\n {\n callItr->first(event, event->event->state, callItr->second);\n }\n\n \/\/ Release events\n list<cl_event>::iterator waitItr;\n for (waitItr = waitListMap[cmd].begin();\n waitItr != waitListMap[cmd].end();\n waitItr++)\n {\n clReleaseEvent(*waitItr);\n }\n waitListMap.erase(cmd);\n clReleaseEvent(event);\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"catch.hpp\"\n#include <map>\n#include <iostream>\n#include <functional>\n\n#include <boost\/asio.hpp>\n\n\/\/ #include <net\/asio\/statsd.h>\n\nnamespace net {\nnamespace protocol {\n\nnamespace statsd {\n\n\/** Represents a single item stored on the server *\/\nclass stored_item {\npublic:\n\tbool operator<(int64_t v) const { return value_ < v; }\n\tbool operator>(int64_t v) const { return value_ > v; }\n\tbool operator==(int64_t v) const { return value_ == v; }\n\n\tstored_item &operator=(int64_t v) { value_ = v; return *this; }\n\tstored_item &operator++() { ++value_; }\n\tstored_item &operator++(int) { operator++(); return *this; }\n\tstored_item &operator--() { --value_; }\n\tstored_item &operator--(int) { operator--(); return *this; }\n\nprivate:\n\tstd::string key_;\n\tint64_t value_;\n};\n\nclass gauge : public stored_item { };\nclass counter : public stored_item { };\nclass timer : public stored_item { };\nclass meter : public stored_item { };\n\n#if 0\nclass x {\npublic:\n\n\tproto << key_ << \":\" << value_ << \"|\" << type_;\n\t\/\/ key_ is a vector of strings\n\t\/\/ value is int64_t\n\tstd::string key_;\n\tint64_t value_;\n\tchar type_;\n};\n#endif\n\n\/** The server interface *\/\nclass server {\npublic:\n\tserver() = default;\n\n\t\/** Returns true if we have any information about the given key *\/\n\tbool has(const std::string &k) const { return items_.count(k) > 0; }\n\tconst stored_item &key(const std::string &k) const { return items_.at(k); }\n\nprivate:\n\tstd::map<std::string, stored_item> items_;\n};\n\n\/** An item that can be updated *\/\nclass item {\npublic:\n\titem(const std::string &k):key_(k) { }\n\n\titem &operator=(int64_t v) { value_ = v; return *this; }\n\titem &operator++() { ++value_; }\n\titem &operator++(int) { operator++(); return *this; }\n\titem &operator--() { --value_; }\n\titem &operator--(int) { operator--(); return *this; }\n\nprivate:\n\tstd::string key_;\n\tint64_t value_;\n};\n\nclass client {\npublic:\n\tclient(server &s):srv_(s) { }\n\titem key(const std::string &s) { }\n\nprivate:\n\tserver &srv_;\n};\n\n};\n\n};\n};\n\nclass statsd_server : public std::enable_shared_from_this<statsd_server> {\npublic:\n\tstatsd_server(\n\t\tboost::asio::io_service &service\n\t):endpoint_{ boost::asio::ip::udp::v4(), 0 },\n\t socket_{ service, endpoint_ },\n\t max_length_{1024}\n\t{\n\t}\n\n\tuint16_t port() const { return endpoint_.port(); }\n\n\tvoid on_packet(const std::string &in) {\n\t\tstd::cout << \"Incoming packet: \" << in << std::endl;\n\t}\n\n\t\/**\n\t * statsd server - continuously accepts incoming message packets\n\t *\/\n\tvoid\n\taccept_next()\n\t{\n\t\tauto self = shared_from_this();\n\t\t\/** Incoming data storage *\/\n\t\tauto storage = std::make_shared<std::vector<char>>(max_length_);\n\t\tsocket_.async_receive_from(\n\t\t\tboost::asio::buffer(&((*storage)[0]), storage->size()),\n\t\t\tendpoint_,\n\t\t\t\/* We want to transfer std::unique_ptr ownership to our lambda, but\n\t\t\t * might not have C++14 semantics available\n\t\t\t *\/\n\t\t\t[self, storage](\n\t\t\t\tconst boost::system::error_code &ec,\n\t\t\t\tsize_t bytes\n\t\t\t) {\n\t\t\t\tif(ec) {\n\t\t\t\t\tstd::cerr << \"Had an error while waiting for next packet: \" << ec.message() << std::endl;\n\t\t\t\t} else if(bytes > 0) {\n\t\t\t\t\tself->on_packet(std::string { storage->cbegin(), storage->cend() });\n\t\t\t\t}\n\t\t\t\tself->accept_next();\n\t\t\t}\n\t\t);\n\t}\n\nprivate:\n\tboost::asio::ip::udp::endpoint endpoint_;\n\tboost::asio::ip::udp::socket socket_;\n\tsize_t max_length_;\n};\n\n\/**\n * statsd client - just sends out a packet for each stat\n *\/\nclass statsd_client : public std::enable_shared_from_this<statsd_client> {\npublic:\n\tstatsd_client(\n\t\tboost::asio::io_service &service\n\t):socket_(service, boost::asio::ip::udp::endpoint(boost::asio::ip::udp::v4(), 0)),\n\t max_length_{4096}\n\t{\n\t}\n\n\tvoid send_packet(const std::string &in)\n\t{\n\t\tauto self = shared_from_this();\n\t\tauto storage = std::make_shared<std::vector<char>>(in.cbegin(), in.cend());\n\t\tauto length = storage->size();\n\t\tsocket_.async_send_to(\n\t\t\tboost::asio::buffer(&((*storage)[0]), storage->size()),\n\t\t\tendpoint_,\n\t\t\t[self, length, storage](\n\t\t\t\tconst boost::system::error_code &ec,\n\t\t\t\tsize_t bytes\n\t\t\t) {\n\t\t\t\tif(ec) {\n\t\t\t\t\tstd::cerr << \"Error sending: \" << ec.message() << std::endl;\n\t\t\t\t} else if(bytes == length) {\n\t\t\t\t\tstd::cout << \"Sent all expected data\\n\";\n\t\t\t\t} else {\n\t\t\t\t\tstd::cerr << \"Sent fewer bytes than we expected\\n\";\n\t\t\t\t}\n\t\t\t}\n\t\t);\n\t}\nprivate:\n\tboost::asio::ip::udp::socket socket_;\n\tboost::asio::ip::udp::endpoint endpoint_;\n\tsize_t max_length_;\n};\n\n#if 0\nSCENARIO(\"statsd server\") {\n\tusing namespace net::protocol;\n\tGIVEN(\"a statsd server instance\") {\n\t\tauto srv = statsd::server();\n\t\tauto cli = statsd::client(srv);\n\t\tWHEN(\"we inc a key\") {\n\t\t\tcli.key(\"some.key\")++;\n\t\t\tTHEN(\"the value is correct\") {\n\t\t\t\tCHECK(srv.has(\"some.key\"));\n\t\t\t\tCHECK(srv.key(\"some.key\") == 1);\n\t\t\t}\n\t\t}\n\t\tWHEN(\"we dec that key\") {\n\t\t\tcli.key(\"some.key\")--;\n\t\t\tTHEN(\"the value is correct\") {\n\t\t\t\tCHECK(srv.has(\"some.key\"));\n\t\t\t\tCHECK(srv.key(\"some.key\") == 0);\n\t\t\t}\n\t\t}\n\t}\n}\n#endif\n\nSCENARIO(\"UDP handling\", \"[statsd][udp]\") {\n\tboost::asio::io_service iosrv;\n\tGIVEN(\"a statsd server instance\") {\n\t\tauto srv = statsd_server(iosrv);\n\t\tCHECK(srv.port() > 0);\n\t\tstd::cout << srv.port() << \"\\n\";\n\t\tiosrv.run();\n\t}\n}\n<commit_msg>Disable this test pending UDP abstraction refactoring<commit_after>#include \"catch.hpp\"\n#include <map>\n#include <iostream>\n#include <functional>\n\n#include <boost\/asio.hpp>\n\n\/\/ #include <net\/asio\/statsd.h>\n\nnamespace net {\nnamespace protocol {\n\nnamespace statsd {\n\n\/** Represents a single item stored on the server *\/\nclass stored_item {\npublic:\n\tbool operator<(int64_t v) const { return value_ < v; }\n\tbool operator>(int64_t v) const { return value_ > v; }\n\tbool operator==(int64_t v) const { return value_ == v; }\n\n\tstored_item &operator=(int64_t v) { value_ = v; return *this; }\n\tstored_item &operator++() { ++value_; }\n\tstored_item &operator++(int) { operator++(); return *this; }\n\tstored_item &operator--() { --value_; }\n\tstored_item &operator--(int) { operator--(); return *this; }\n\nprivate:\n\tstd::string key_;\n\tint64_t value_;\n};\n\nclass gauge : public stored_item { };\nclass counter : public stored_item { };\nclass timer : public stored_item { };\nclass meter : public stored_item { };\n\n#if 0\nclass x {\npublic:\n\n\tproto << key_ << \":\" << value_ << \"|\" << type_;\n\t\/\/ key_ is a vector of strings\n\t\/\/ value is int64_t\n\tstd::string key_;\n\tint64_t value_;\n\tchar type_;\n};\n#endif\n\n\/** The server interface *\/\nclass server {\npublic:\n\tserver() = default;\n\n\t\/** Returns true if we have any information about the given key *\/\n\tbool has(const std::string &k) const { return items_.count(k) > 0; }\n\tconst stored_item &key(const std::string &k) const { return items_.at(k); }\n\nprivate:\n\tstd::map<std::string, stored_item> items_;\n};\n\n\/** An item that can be updated *\/\nclass item {\npublic:\n\titem(const std::string &k):key_(k) { }\n\n\titem &operator=(int64_t v) { value_ = v; return *this; }\n\titem &operator++() { ++value_; }\n\titem &operator++(int) { operator++(); return *this; }\n\titem &operator--() { --value_; }\n\titem &operator--(int) { operator--(); return *this; }\n\nprivate:\n\tstd::string key_;\n\tint64_t value_;\n};\n\nclass client {\npublic:\n\tclient(server &s):srv_(s) { }\n\titem key(const std::string &s) { }\n\nprivate:\n\tserver &srv_;\n};\n\n};\n\n};\n};\n\nclass statsd_server : public std::enable_shared_from_this<statsd_server> {\npublic:\n\tstatsd_server(\n\t\tboost::asio::io_service &service\n\t):endpoint_{ boost::asio::ip::udp::v4(), 0 },\n\t socket_{ service, endpoint_ },\n\t max_length_{1024}\n\t{\n\t}\n\n\tuint16_t port() const { return endpoint_.port(); }\n\n\tvoid on_packet(const std::string &in) {\n\t\tstd::cout << \"Incoming packet: \" << in << std::endl;\n\t}\n\n\t\/**\n\t * statsd server - continuously accepts incoming message packets\n\t *\/\n\tvoid\n\taccept_next()\n\t{\n\t\tauto self = shared_from_this();\n\t\t\/** Incoming data storage *\/\n\t\tauto storage = std::make_shared<std::vector<char>>(max_length_);\n\t\tsocket_.async_receive_from(\n\t\t\tboost::asio::buffer(&((*storage)[0]), storage->size()),\n\t\t\tendpoint_,\n\t\t\t\/* We want to transfer std::unique_ptr ownership to our lambda, but\n\t\t\t * might not have C++14 semantics available\n\t\t\t *\/\n\t\t\t[self, storage](\n\t\t\t\tconst boost::system::error_code &ec,\n\t\t\t\tsize_t bytes\n\t\t\t) {\n\t\t\t\tif(ec) {\n\t\t\t\t\tstd::cerr << \"Had an error while waiting for next packet: \" << ec.message() << std::endl;\n\t\t\t\t} else if(bytes > 0) {\n\t\t\t\t\tself->on_packet(std::string { storage->cbegin(), storage->cend() });\n\t\t\t\t}\n\t\t\t\tself->accept_next();\n\t\t\t}\n\t\t);\n\t}\n\nprivate:\n\tboost::asio::ip::udp::endpoint endpoint_;\n\tboost::asio::ip::udp::socket socket_;\n\tsize_t max_length_;\n};\n\n\/**\n * statsd client - just sends out a packet for each stat\n *\/\nclass statsd_client : public std::enable_shared_from_this<statsd_client> {\npublic:\n\tstatsd_client(\n\t\tboost::asio::io_service &service\n\t):socket_(service, boost::asio::ip::udp::endpoint(boost::asio::ip::udp::v4(), 0)),\n\t max_length_{4096}\n\t{\n\t}\n\n\tvoid send_packet(const std::string &in)\n\t{\n\t\tauto self = shared_from_this();\n\t\tauto storage = std::make_shared<std::vector<char>>(in.cbegin(), in.cend());\n\t\tauto length = storage->size();\n\t\tsocket_.async_send_to(\n\t\t\tboost::asio::buffer(&((*storage)[0]), storage->size()),\n\t\t\tendpoint_,\n\t\t\t[self, length, storage](\n\t\t\t\tconst boost::system::error_code &ec,\n\t\t\t\tsize_t bytes\n\t\t\t) {\n\t\t\t\tif(ec) {\n\t\t\t\t\tstd::cerr << \"Error sending: \" << ec.message() << std::endl;\n\t\t\t\t} else if(bytes == length) {\n\t\t\t\t\tstd::cout << \"Sent all expected data\\n\";\n\t\t\t\t} else {\n\t\t\t\t\tstd::cerr << \"Sent fewer bytes than we expected\\n\";\n\t\t\t\t}\n\t\t\t}\n\t\t);\n\t}\nprivate:\n\tboost::asio::ip::udp::socket socket_;\n\tboost::asio::ip::udp::endpoint endpoint_;\n\tsize_t max_length_;\n};\n\n#if 0\nSCENARIO(\"statsd server\") {\n\tusing namespace net::protocol;\n\tGIVEN(\"a statsd server instance\") {\n\t\tauto srv = statsd::server();\n\t\tauto cli = statsd::client(srv);\n\t\tWHEN(\"we inc a key\") {\n\t\t\tcli.key(\"some.key\")++;\n\t\t\tTHEN(\"the value is correct\") {\n\t\t\t\tCHECK(srv.has(\"some.key\"));\n\t\t\t\tCHECK(srv.key(\"some.key\") == 1);\n\t\t\t}\n\t\t}\n\t\tWHEN(\"we dec that key\") {\n\t\t\tcli.key(\"some.key\")--;\n\t\t\tTHEN(\"the value is correct\") {\n\t\t\t\tCHECK(srv.has(\"some.key\"));\n\t\t\t\tCHECK(srv.key(\"some.key\") == 0);\n\t\t\t}\n\t\t}\n\t}\n}\n\nSCENARIO(\"UDP handling\", \"[statsd][udp]\") {\n\tboost::asio::io_service iosrv;\n\tGIVEN(\"a statsd server instance\") {\n\t\tauto srv = statsd_server(iosrv);\n\t\tCHECK(srv.port() > 0);\n\t\tstd::cout << srv.port() << \"\\n\";\n\t\tiosrv.run();\n\t}\n}\n#endif\n<|endoftext|>"} {"text":"<commit_before>#include \"..\/includes\/FileWatcher.h\"\n#include \"..\/includes\/FileWatcherInterface.h\"\n\n#if defined(_WIN32)\n#include \"..\/includes\/FileWatcher32.h\"\n#define USE_WINDOWS_INIT\n#elif defined(__APPLE_CC__) || defined(BSD)\n#include \"..\/includes\/FileWatcherOSX.h\"\n#define FILE_WATCHER_INTERFACE FileWatcherOSX\n#elif defined(__linux__)\n#include \"..\/includes\/FileWatcherLinux.h\"\n#define FILE_WATCHER_INTERFACE FileWatcherLinux\n#endif\n\nnamespace NSFW {\n\n FileWatcher::FileWatcher(std::string path)\n : mPath(path), mWatchFiles(false) {}\n\n FileWatcher::~FileWatcher() {\n #ifndef USE_WINDOWS_INIT\n delete fwInterface;\n #endif\n }\n\n \/\/ Public methods\n bool FileWatcher::running() {\n return mWatchFiles;\n }\n\n bool FileWatcher::start() {\n if (!mWatchFiles) {\n mWatchFiles = true;\n\n \/\/ normalization\n if (mPath[mPath.length() - 1] == '\/' || mPath[mPath.length() - 1] == '\\\\') {\n mPath = mPath.substr(0, mPath.length() - 2);\n }\n\n #if defined(USE_WINDOWS_INIT)\n createFileWatcher(mPath, mEventsQueue, mWatchFiles);\n #else\n fwInterface = new FILE_WATCHER_INTERFACE(mPath, mEventsQueue, mWatchFiles);\n fwInterface->start();\n #endif\n return true;\n } else {\n return false;\n }\n }\n\n bool FileWatcher::stop() {\n if (!mWatchFiles) {\n return false;\n } else {\n mWatchFiles = false;\n #ifndef USE_WINDOWS_INIT\n fwInterface->stop();\n delete fwInterface;\n #endif\n return true;\n }\n }\n\n \/\/ Internal methods\n std::queue<Event> *FileWatcher::pollEvents() {\n if (mEventsQueue.empty) {\n return NULL;\n }\n std::queue<Event> *out = new std::queue<Event>();\n std::swap(mEventsQueue, *out);\n return out;\n }\n\n}\n<commit_msg>Fixed syntax error<commit_after>#include \"..\/includes\/FileWatcher.h\"\n#include \"..\/includes\/FileWatcherInterface.h\"\n\n#if defined(_WIN32)\n#include \"..\/includes\/FileWatcher32.h\"\n#define USE_WINDOWS_INIT\n#elif defined(__APPLE_CC__) || defined(BSD)\n#include \"..\/includes\/FileWatcherOSX.h\"\n#define FILE_WATCHER_INTERFACE FileWatcherOSX\n#elif defined(__linux__)\n#include \"..\/includes\/FileWatcherLinux.h\"\n#define FILE_WATCHER_INTERFACE FileWatcherLinux\n#endif\n\nnamespace NSFW {\n\n FileWatcher::FileWatcher(std::string path)\n : mPath(path), mWatchFiles(false) {}\n\n FileWatcher::~FileWatcher() {\n #ifndef USE_WINDOWS_INIT\n delete fwInterface;\n #endif\n }\n\n \/\/ Public methods\n bool FileWatcher::running() {\n return mWatchFiles;\n }\n\n bool FileWatcher::start() {\n if (!mWatchFiles) {\n mWatchFiles = true;\n\n \/\/ normalization\n if (mPath[mPath.length() - 1] == '\/' || mPath[mPath.length() - 1] == '\\\\') {\n mPath = mPath.substr(0, mPath.length() - 2);\n }\n\n #if defined(USE_WINDOWS_INIT)\n createFileWatcher(mPath, mEventsQueue, mWatchFiles);\n #else\n fwInterface = new FILE_WATCHER_INTERFACE(mPath, mEventsQueue, mWatchFiles);\n fwInterface->start();\n #endif\n return true;\n } else {\n return false;\n }\n }\n\n bool FileWatcher::stop() {\n if (!mWatchFiles) {\n return false;\n } else {\n mWatchFiles = false;\n #ifndef USE_WINDOWS_INIT\n fwInterface->stop();\n delete fwInterface;\n #endif\n return true;\n }\n }\n\n \/\/ Internal methods\n std::queue<Event> *FileWatcher::pollEvents() {\n if (mEventsQueue.empty()) {\n return NULL;\n }\n std::queue<Event> *out = new std::queue<Event>();\n std::swap(mEventsQueue, *out);\n return out;\n }\n\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"sto3g.hpp\"\n\/\/\n\/\/\n\/\/\nvoid lcao_wavefunction::sto3g::build_repulsion_matrix()\n{\n\/\/\n v_matrix.create_array(number_of_atoms, number_of_atoms);\n v_matrix.array::set_config(*config);\n v_matrix.set_name(\"One electron Coulomb repulsion matrix\");\n\/\/\n double ii_integral = 0.0;\n double ij_integral = 0.0;\n double jj_integral = 0.0; \n double i_distance = 0.0; \n double j_distance = 0.0;\n double ij_distance = 0.0;\n double i_atomic_num = 0.0;\n double a = 0.0;\n double b = 0.0;\n double c = 0.0;\n double d = 0.0;\n double e = 0.0;\n double f = 0.0; \n unsigned int i_atom = 0;\n unsigned int i_type = 0;\n #pragma omp parallel for private(i_atom, i_type, i_atomic_num, ij_distance, i_distance, a, b, c, d, e, f) reduction(+:ii_integral, ij_integral, jj_integral) ordered schedule(dynamic)\n for(i_atom = 1; i_atom <= number_of_atoms; i_atom++)\n {\n i_type = (type -> get(i_atom));\n i_atomic_num = ((double) i_type);\n unsigned int j_atom = 0;\n unsigned int j_type = 0;\n #pragma omp parallel for private(j_atom, j_type, ij_distance, j_distance, a, b, c, d, e, f) reduction(+:ii_integral, ij_integral, jj_integral) ordered schedule(dynamic)\n for(j_atom = 1; j_atom <= number_of_atoms; j_atom++)\n {\n j_type = (type -> get(j_atom));\n if(i_atom == j_atom)\n {\n unsigned int m_primitive = 0;\n #pragma omp parallel for private(m_primitive, a, b, c, d, e, f) reduction(+:ii_integral, ij_integral, jj_integral) ordered schedule(dynamic)\n for(m_primitive = 1; m_primitive <= (i_type == 1? 3:6); m_primitive++)\n {\n unsigned int n_primitive = 0;\n #pragma omp parallel for private(n_primitive, a, b, c, d, e, f) reduction(+:ii_integral, ij_integral, jj_integral) ordered schedule(dynamic)\n for(n_primitive = 1; n_primitive <= (i_type == 1? 3:6); n_primitive++)\n {\n #pragma omp parallel sections num_threads(4)\n {\n #pragma omp section\n {\n a = coeff(i_type, m_primitive)*coeff(i_type, n_primitive);\n }\n #pragma omp section\n {\n b = -2.0*M_PI\/(exp(i_type, m_primitive) + exp(i_type, n_primitive));\n }\n #pragma omp section\n {\n c = gf_product_const(exp(i_type, m_primitive), exp(i_type, n_primitive), 0.0);\n }\n #pragma omp section\n {\n d = error_function(0.0);\n }\n }\n\/\/\n #pragma omp atomic\n ii_integral += a*b*c*d*i_atomic_num;\n\/\/\n a = b = c = d = 0.0;\n } \/\/ for(n_primitive)\n } \/\/ for(m_primitive)\n v_matrix.set(i_atom, j_atom, v_matrix.get(i_atom, j_atom) + ii_integral);\n ii_integral = 0.0;\n }\n else \/\/ if(i_atom != j_atom)\n {\n ij_distance = interatomic_distance(i_atom, j_atom);\n for(unsigned int m_primitive = 1; m_primitive <= (i_type == 1? 3:6); m_primitive++)\n {\n for(unsigned int n_primitive = 1; n_primitive <= (i_type == 1? 3:6); n_primitive++)\n {\n gf_midpoint(i_distance,\n j_distance,\n exp(i_type, m_primitive),\n exp(j_type, n_primitive),\n ij_distance);\n a = gsl_pow_2(i_distance)*(exp(i_type, m_primitive) + exp(j_type, n_primitive));\n b = gsl_pow_2(ij_distance)*(exp(j_type, m_primitive) + exp(j_type, n_primitive));\n #pragma omp parallel sections num_threads(4)\n {\n #pragma omp section\n {\n c = coeff(i_type, m_primitive)*coeff(j_type, n_primitive);\n }\n #pragma omp section\n {\n d = -2.0*M_PI\/(exp(i_type, m_primitive) + exp(j_type, n_primitive));\n }\n #pragma omp section\n {\n e = gf_product_const(exp(i_type, m_primitive), exp(j_type, n_primitive), ij_distance);\n }\n #pragma omp section\n {\n f = error_function(a);\n }\n }\n\/\/\n #pragma omp atomic\n ij_integral += c*d*e*f*i_atomic_num;\n\/\/\n c = d = e = f = 0.0;\n #pragma omp parallel sections num_threads(4)\n {\n #pragma omp section\n {\n c = coeff(j_type, m_primitive)*coeff(j_type, n_primitive);\n }\n #pragma omp section\n {\n d = -2.0*M_PI\/(exp(j_type, m_primitive) + exp(j_type, n_primitive));\n }\n #pragma omp section\n {\n e = gf_product_const(exp(j_type, m_primitive), exp(j_type, n_primitive), 0.0);\n }\n #pragma omp section\n {\n f = error_function(b);\n }\n }\n\/\/\n #pragma omp atomic\n jj_integral += c*d*e*f*i_atomic_num;\n\/\/\n a = b = c = d = e = f = 0.0;\n } \/\/ for(n_primitive)\n } \/\/ for(m_primitive)\n v_matrix.set(i_atom, j_atom, v_matrix.get(i_atom, j_atom) + ij_integral);\n v_matrix.set(j_atom, i_atom, v_matrix.get(i_atom, j_atom));\n v_matrix.set(j_atom, j_atom, v_matrix.get(j_atom, j_atom) + jj_integral);\n ij_integral = jj_integral = i_distance = j_distance = ij_distance = 0.0;\n }\n } \/\/ for(j_atom)\n } \/\/ for(i_atom)\n}\n<commit_msg>Delete sto3g__build_repulsion_matrix.cpp<commit_after><|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ OperatorType.cpp\n\/\/ lemonscript\n\/\/\n\/\/ Created by Donald Pinckney on 2\/28\/16.\n\/\/ Copyright © 2016 Donald Pinckney. All rights reserved.\n\/\/\n\n#include \"OperatorType.h\"\n\n#include <string.h>\n#include <functional>\n#include <math.h>\n\n#include \"AvailableCppCommandDeclaration.h\"\n\nusing namespace lemonscript_expressions;\nusing namespace lemonscript;\nusing namespace std;\n\nstd::ostream & lemonscript_expressions::operator<<(std::ostream &o, OperatorType opType) {\n o << opType.operatorText;\n return o;\n}\n\n\/*\n \nconst Operator<ExpressionDesc> DataType_unaryNegO(\"!.*\", 1, true, operatorResolve(genericOperatorTypes({BOOLEAN}, {unaryNegO<bool>}, 1)));\nconst Operator<ExpressionDesc> DataType_unaryMathNegO(\"-.*\", 1, true, operatorResolve(genericOperatorTypes({INT,FLOAT}, {unaryMathNegO<int>, unaryMathNegO<float>}, 1)));\n\nconst Operator<ExpressionDesc> DataType_expO(\".*\\\\^.*\", 2, true, operatorResolve(genericOperatorTypes({INT,FLOAT}, {binaryExpO<int>, binaryExpO<float>}, 2)));\n\nconst Operator<ExpressionDesc> DataType_modO(\".*%.*\", 2, true, operatorResolve(genericOperatorTypes({INT}, {binaryModO<int>}, 2)));\nconst Operator<ExpressionDesc> DataType_divO(\"\/\", 2, true, operatorResolve(genericOperatorTypes({INT,FLOAT}, {binaryDivO<int>, binaryDivO<float>}, 2)));\nconst Operator<ExpressionDesc> DataType_andO(\".*&&.*\", 2, true, operatorResolve(genericOperatorTypes({BOOLEAN}, {binaryAndO<bool>}, 2)));\nconst Operator<ExpressionDesc> DataType_multO(\".*\\\\*.*\", 2, true, operatorResolve(genericOperatorTypes({INT,FLOAT}, {binaryMultO<int>, binaryMultO<float>}, 2)));\n\nconst Operator<ExpressionDesc> DataType_subO(\".*-.*\", 2, true, operatorResolve(genericOperatorTypes({INT,FLOAT}, {binarySubO<int>, binarySubO<float>}, 2)));\nconst Operator<ExpressionDesc> DataType_orO(\".*\\\\|\\\\|.*\", 2, true, operatorResolve(genericOperatorTypes({BOOLEAN}, {binaryOrO<bool>}, 2)));\nconst Operator<ExpressionDesc> DataType_addO(\".*\\\\+.*\", 2, true, operatorResolve(genericOperatorTypes({INT,FLOAT}, {binaryAddO<int>, binaryAddO<float>}, 2)));\n\nconst Operator<ExpressionDesc> DataType_impliesO(\".*=>.*\", 2, true, operatorResolve(genericOperatorTypes({BOOLEAN}, {binaryImpliesO<bool>}, 2)));\n\nconst Operator<ExpressionDesc> DataType_equalsO(\".*==.*\", 2, true, operatorResolve(genericOperatorTypesOtherReturn({INT,FLOAT,BOOLEAN}, {binaryEqualsO<int>, binaryEqualsFLOAT_O<float>, binaryEqualsO<bool>}, BOOLEAN, 2)));\n\n\n*\/\n\n\/\/ Unary operators\n\/\/ Precedence N\/A\ntemplate <typename T>\nT negation(T x) {\n return -x;\n}\n\ntemplate <typename T>\nT boolNegation(T x) {\n return !x;\n}\n\n\n\/\/ Binary operators\n\n\/\/ Exponentiation: 160\ntemplate <typename T>\nT exp(T x, T y) {\n return (T)powf((float)x, (float)y);\n}\n\n\/\/ Multiplicative: 150\ntemplate <typename T>\nT mult(T x, T y) {\n return x * y;\n}\n\ntemplate <typename T>\nT div(T x, T y) {\n return x \/ y;\n}\n\ntemplate <typename T>\nT mod(T x, T y) {\n return x % y;\n}\n\n\n\/\/ Additive: 140\ntemplate <typename T>\nT add(T x, T y) {\n return x + y;\n}\n\ntemplate <typename T>\nT subtract(T x, T y) {\n return x - y;\n}\n\n\n\/\/ Cast: 132\ntemplate <typename T, typename U>\nU as(T x) {\n return (U)x;\n}\n\n\n\n\n\/\/ Implication: 131\ntemplate <typename T>\nT implies(T x, T y) {\n return !x || y;\n}\n\n\/\/ Comparative: 130\ntemplate <typename T>\nbool equal(T x, T y) {\n return x == y;\n}\n\ntemplate <typename T>\nbool notEqual(T x, T y) {\n return x != y;\n}\n\ntemplate <typename T>\nbool leq(T x, T y) {\n return x <= y;\n}\n\ntemplate <typename T>\nbool geq(T x, T y) {\n return x >= y;\n}\n\ntemplate <typename T>\nbool lessThan(T x, T y) {\n return x < y;\n}\n\ntemplate <typename T>\nbool greaterThan(T x, T y) {\n return x > y;\n}\n\n\n\/\/ Conjuctive: 120\ntemplate <typename T>\nT _and(T x, T y) {\n return x && y;\n}\n\n\/\/ Disjunctive: 110\ntemplate <typename T>\nT _or (T x, T y) {\n return x || y;\n}\n\n\n\n\ntemplate <typename T>\nTypeSpecification generateTypeSpecificationUnaryGenericUniform(DataType t, function<T (T)> f) {\n\n TypeSpecification spec;\n spec.inputTypes = {t};\n spec.returnType = t;\n spec.func = [f] (std::vector<int> xs) {\n \n T retVal = f(*(T *)&xs[0]);\n \n int retInt;\n bzero(&retInt, sizeof(int));\n \n memcpy(&retInt, &retVal, sizeof(T));\n \n return retInt;\n };\n \n return spec;\n}\n\ntemplate <typename T>\nTypeSpecification generateTypeSpecificationBinaryGenericUniform(DataType t, function<T (T,T)> f) {\n \n TypeSpecification spec;\n spec.inputTypes = {t, t};\n spec.returnType = t;\n spec.func = [f] (std::vector<int> xs) {\n \n T retVal = f(*(T *)&xs[0], *(T *)&xs[1]);\n \n int retInt;\n bzero(&retInt, sizeof(int));\n \n memcpy(&retInt, &retVal, sizeof(T));\n \n return retInt;\n };\n \n return spec;\n}\n\ntemplate <typename T, typename U>\nTypeSpecification generateTypeSpecificationBinaryGenericUniformSpecificReturn(DataType t, DataType u, function<U (T,T)> f) {\n \n TypeSpecification spec;\n spec.inputTypes = {t, t};\n spec.returnType = u;\n spec.func = [f] (std::vector<int> xs) {\n \n U retVal = f(*(T *)&xs[0], *(T *)&xs[1]);\n \n int retInt;\n bzero(&retInt, sizeof(int));\n \n memcpy(&retInt, &retVal, sizeof(U));\n \n return retInt;\n };\n \n return spec;\n}\n\nmap<string, OperatorType> OperatorType::operatorTypeMemoization;\n\nOperatorType OperatorType::lookupOperatorType(std::string opString) {\n \n OperatorType &opType = operatorTypeMemoization[opString];\n \n if(opType.operatorText.length() > 0) {\n return opType;\n }\n \n opType.isIdentityOperator = false;\n opType.operatorText = opString;\n \n int precedence;\n vector<TypeSpecification> typeSpecs;\n \n if(opString == \"!\") {\n TypeSpecification unaryNegationBool = generateTypeSpecificationUnaryGenericUniform<bool>(DataType::BOOLEAN, boolNegation<bool>);\n precedence = 999;\n typeSpecs = {unaryNegationBool};\n } else if(opString == \"^\") {\n TypeSpecification binaryInt = generateTypeSpecificationBinaryGenericUniform<int>(DataType::INT, exp<int>);\n TypeSpecification binaryFloat = generateTypeSpecificationBinaryGenericUniform<float>(DataType::FLOAT, exp<float>);\n \n typeSpecs = {binaryInt, binaryFloat};\n precedence = 160;\n } else if(opString == \"*\") {\n TypeSpecification binaryInt = generateTypeSpecificationBinaryGenericUniform<int>(DataType::INT, mult<int>);\n TypeSpecification binaryFloat = generateTypeSpecificationBinaryGenericUniform<float>(DataType::FLOAT, mult<float>);\n \n typeSpecs = {binaryInt, binaryFloat};\n precedence = 150;\n } else if(opString == \"\/\") {\n TypeSpecification binaryInt = generateTypeSpecificationBinaryGenericUniform<int>(DataType::INT, div<int>);\n TypeSpecification binaryFloat = generateTypeSpecificationBinaryGenericUniform<float>(DataType::FLOAT, div<float>);\n \n typeSpecs = {binaryInt, binaryFloat};\n precedence = 150;\n } else if(opString == \"%\") {\n TypeSpecification binaryInt = generateTypeSpecificationBinaryGenericUniform<int>(DataType::INT, mod<int>);\n \n typeSpecs = {binaryInt};\n precedence = 150;\n } else if(opString == \"+\") {\n TypeSpecification binaryInt = generateTypeSpecificationBinaryGenericUniform<int>(DataType::INT, add<int>);\n TypeSpecification binaryFloat = generateTypeSpecificationBinaryGenericUniform<float>(DataType::FLOAT, add<float>);\n \n typeSpecs = {binaryInt, binaryFloat};\n precedence = 140;\n } else if(opString == \"-\") {\n TypeSpecification unaryMinusInt = generateTypeSpecificationUnaryGenericUniform<int>(DataType::INT, negation<int>);\n TypeSpecification unaryMinusFloat = generateTypeSpecificationUnaryGenericUniform<float>(DataType::FLOAT, negation<float>);\n\n TypeSpecification binaryMinusInt = generateTypeSpecificationBinaryGenericUniform<int>(DataType::INT, subtract<int>);\n TypeSpecification binaryMinusFloat = generateTypeSpecificationBinaryGenericUniform<float>(DataType::FLOAT, subtract<float>);\n\n typeSpecs = {unaryMinusInt, unaryMinusFloat, binaryMinusInt, binaryMinusFloat};\n precedence = 140;\n } else if(opString == \"=>\") {\n TypeSpecification binaryBool = generateTypeSpecificationBinaryGenericUniform<bool>(DataType::BOOLEAN, implies<bool>);\n \n typeSpecs = {binaryBool};\n precedence = 131;\n } else if(opString == \"==\") {\n TypeSpecification binaryBool = generateTypeSpecificationBinaryGenericUniformSpecificReturn<bool, bool>(DataType::BOOLEAN, DataType::BOOLEAN, equal<bool>);\n TypeSpecification binaryInt = generateTypeSpecificationBinaryGenericUniformSpecificReturn<int, bool>(DataType::INT, DataType::BOOLEAN, equal<int>);\n TypeSpecification binaryFloat = generateTypeSpecificationBinaryGenericUniformSpecificReturn<float, bool>(DataType::FLOAT, DataType::BOOLEAN, equal<float>);\n\n typeSpecs = {binaryBool, binaryInt, binaryFloat};\n precedence = 130;\n } else if(opString == \"!=\") {\n TypeSpecification binaryBool = generateTypeSpecificationBinaryGenericUniformSpecificReturn<bool, bool>(DataType::BOOLEAN, DataType::BOOLEAN, notEqual<bool>);\n TypeSpecification binaryInt = generateTypeSpecificationBinaryGenericUniformSpecificReturn<int, bool>(DataType::INT, DataType::BOOLEAN, notEqual<int>);\n TypeSpecification binaryFloat = generateTypeSpecificationBinaryGenericUniformSpecificReturn<float, bool>(DataType::FLOAT, DataType::BOOLEAN, notEqual<float>);\n \n typeSpecs = {binaryBool, binaryInt, binaryFloat};\n precedence = 130;\n } else if(opString == \"<=\") {\n TypeSpecification binaryBool = generateTypeSpecificationBinaryGenericUniformSpecificReturn<bool, bool>(DataType::BOOLEAN, DataType::BOOLEAN, leq<bool>);\n TypeSpecification binaryInt = generateTypeSpecificationBinaryGenericUniformSpecificReturn<int, bool>(DataType::INT, DataType::BOOLEAN, leq<int>);\n TypeSpecification binaryFloat = generateTypeSpecificationBinaryGenericUniformSpecificReturn<float, bool>(DataType::FLOAT, DataType::BOOLEAN, leq<float>);\n \n typeSpecs = {binaryBool, binaryInt, binaryFloat};\n precedence = 130;\n } else if(opString == \">=\") {\n TypeSpecification binaryBool = generateTypeSpecificationBinaryGenericUniformSpecificReturn<bool, bool>(DataType::BOOLEAN, DataType::BOOLEAN, geq<bool>);\n TypeSpecification binaryInt = generateTypeSpecificationBinaryGenericUniformSpecificReturn<int, bool>(DataType::INT, DataType::BOOLEAN, geq<int>);\n TypeSpecification binaryFloat = generateTypeSpecificationBinaryGenericUniformSpecificReturn<float, bool>(DataType::FLOAT, DataType::BOOLEAN, geq<float>);\n \n typeSpecs = {binaryBool, binaryInt, binaryFloat};\n precedence = 130;\n } else if(opString == \"<\") {\n TypeSpecification binaryBool = generateTypeSpecificationBinaryGenericUniformSpecificReturn<bool, bool>(DataType::BOOLEAN, DataType::BOOLEAN, lessThan<bool>);\n TypeSpecification binaryInt = generateTypeSpecificationBinaryGenericUniformSpecificReturn<int, bool>(DataType::INT, DataType::BOOLEAN, lessThan<int>);\n TypeSpecification binaryFloat = generateTypeSpecificationBinaryGenericUniformSpecificReturn<float, bool>(DataType::FLOAT, DataType::BOOLEAN, lessThan<float>);\n \n typeSpecs = {binaryBool, binaryInt, binaryFloat};\n precedence = 130;\n } else if(opString == \">\") {\n TypeSpecification binaryBool = generateTypeSpecificationBinaryGenericUniformSpecificReturn<bool, bool>(DataType::BOOLEAN, DataType::BOOLEAN, greaterThan<bool>);\n TypeSpecification binaryInt = generateTypeSpecificationBinaryGenericUniformSpecificReturn<int, bool>(DataType::INT, DataType::BOOLEAN, greaterThan<int>);\n TypeSpecification binaryFloat = generateTypeSpecificationBinaryGenericUniformSpecificReturn<float, bool>(DataType::FLOAT, DataType::BOOLEAN, greaterThan<float>);\n \n typeSpecs = {binaryBool, binaryInt, binaryFloat};\n precedence = 130;\n } else if(opString == \"&&\") {\n TypeSpecification binaryBool = generateTypeSpecificationBinaryGenericUniform<bool>(DataType::BOOLEAN, _and<bool>);\n \n typeSpecs = {binaryBool};\n precedence = 120;\n } else if(opString == \"||\") {\n TypeSpecification binaryBool = generateTypeSpecificationBinaryGenericUniform<bool>(DataType::BOOLEAN, _or<bool>);\n \n typeSpecs = {binaryBool};\n precedence = 110;\n } else {\n throw \"Unknown operator: \" + opString;\n }\n \n opType.specifications = typeSpecs;\n opType.precedence = precedence;\n \n return opType;\n}\n\n\n\n\nOperatorType OperatorType::identity() {\n std::vector<TypeSpecification> specs;\n std::vector<lemonscript::DataType> types = {lemonscript::DataType::BOOLEAN, lemonscript::DataType::INT, lemonscript::DataType::FLOAT};\n for(auto it = types.begin(); it != types.end(); ++it) {\n lemonscript::DataType t = *it;\n TypeSpecification spec;\n spec.inputTypes = {t};\n spec.returnType = t;\n spec.func = [] (std::vector<int> xs) { return xs[0]; };\n specs.push_back(spec);\n }\n OperatorType opType;\n opType.isIdentityOperator = true;\n opType.specifications = specs;\n opType.operatorText = \"i\";\n opType.precedence = 999;\n \n return opType;\n}<commit_msg>Fix build on (recent versions of ) GCC (#24)<commit_after>\/\/\n\/\/ OperatorType.cpp\n\/\/ lemonscript\n\/\/\n\/\/ Created by Donald Pinckney on 2\/28\/16.\n\/\/ Copyright © 2016 Donald Pinckney. All rights reserved.\n\/\/\n\n#include \"OperatorType.h\"\n\n#include <string.h>\n#include <functional>\n#include <cmath>\n\n#include \"AvailableCppCommandDeclaration.h\"\n\nusing namespace lemonscript_expressions;\nusing namespace lemonscript;\n\nusing std::function;\nusing std::vector;\nusing std::map;\nusing std::string;\n\nstd::ostream & lemonscript_expressions::operator<<(std::ostream &o, OperatorType opType) {\n o << opType.operatorText;\n return o;\n}\n\n\/*\n \nconst Operator<ExpressionDesc> DataType_unaryNegO(\"!.*\", 1, true, operatorResolve(genericOperatorTypes({BOOLEAN}, {unaryNegO<bool>}, 1)));\nconst Operator<ExpressionDesc> DataType_unaryMathNegO(\"-.*\", 1, true, operatorResolve(genericOperatorTypes({INT,FLOAT}, {unaryMathNegO<int>, unaryMathNegO<float>}, 1)));\n\nconst Operator<ExpressionDesc> DataType_expO(\".*\\\\^.*\", 2, true, operatorResolve(genericOperatorTypes({INT,FLOAT}, {binaryExpO<int>, binaryExpO<float>}, 2)));\n\nconst Operator<ExpressionDesc> DataType_modO(\".*%.*\", 2, true, operatorResolve(genericOperatorTypes({INT}, {binaryModO<int>}, 2)));\nconst Operator<ExpressionDesc> DataType_divO(\"\/\", 2, true, operatorResolve(genericOperatorTypes({INT,FLOAT}, {binaryDivO<int>, binaryDivO<float>}, 2)));\nconst Operator<ExpressionDesc> DataType_andO(\".*&&.*\", 2, true, operatorResolve(genericOperatorTypes({BOOLEAN}, {binaryAndO<bool>}, 2)));\nconst Operator<ExpressionDesc> DataType_multO(\".*\\\\*.*\", 2, true, operatorResolve(genericOperatorTypes({INT,FLOAT}, {binaryMultO<int>, binaryMultO<float>}, 2)));\n\nconst Operator<ExpressionDesc> DataType_subO(\".*-.*\", 2, true, operatorResolve(genericOperatorTypes({INT,FLOAT}, {binarySubO<int>, binarySubO<float>}, 2)));\nconst Operator<ExpressionDesc> DataType_orO(\".*\\\\|\\\\|.*\", 2, true, operatorResolve(genericOperatorTypes({BOOLEAN}, {binaryOrO<bool>}, 2)));\nconst Operator<ExpressionDesc> DataType_addO(\".*\\\\+.*\", 2, true, operatorResolve(genericOperatorTypes({INT,FLOAT}, {binaryAddO<int>, binaryAddO<float>}, 2)));\n\nconst Operator<ExpressionDesc> DataType_impliesO(\".*=>.*\", 2, true, operatorResolve(genericOperatorTypes({BOOLEAN}, {binaryImpliesO<bool>}, 2)));\n\nconst Operator<ExpressionDesc> DataType_equalsO(\".*==.*\", 2, true, operatorResolve(genericOperatorTypesOtherReturn({INT,FLOAT,BOOLEAN}, {binaryEqualsO<int>, binaryEqualsFLOAT_O<float>, binaryEqualsO<bool>}, BOOLEAN, 2)));\n\n\n*\/\n\n\/\/ Unary operators\n\/\/ Precedence N\/A\ntemplate <typename T>\nT negation(T x) {\n return -x;\n}\n\ntemplate <typename T>\nT boolNegation(T x) {\n return !x;\n}\n\n\n\/\/ Binary operators\n\n\/\/ Exponentiation: 160\ntemplate <typename T>\nT exp(T x, T y) {\n return (T)powf((float)x, (float)y);\n}\n\n\/\/ Multiplicative: 150\ntemplate <typename T>\nT mult(T x, T y) {\n return x * y;\n}\n\ntemplate <typename T>\nT div(T x, T y) {\n return x \/ y;\n}\n\ntemplate <typename T>\nT mod(T x, T y) {\n return x % y;\n}\n\n\n\/\/ Additive: 140\ntemplate <typename T>\nT add(T x, T y) {\n return x + y;\n}\n\ntemplate <typename T>\nT subtract(T x, T y) {\n return x - y;\n}\n\n\n\/\/ Cast: 132\ntemplate <typename T, typename U>\nU as(T x) {\n return (U)x;\n}\n\n\n\n\n\/\/ Implication: 131\ntemplate <typename T>\nT implies(T x, T y) {\n return !x || y;\n}\n\n\/\/ Comparative: 130\ntemplate <typename T>\nbool equal(T x, T y) {\n return x == y;\n}\n\ntemplate <typename T>\nbool notEqual(T x, T y) {\n return x != y;\n}\n\ntemplate <typename T>\nbool leq(T x, T y) {\n return x <= y;\n}\n\ntemplate <typename T>\nbool geq(T x, T y) {\n return x >= y;\n}\n\ntemplate <typename T>\nbool lessThan(T x, T y) {\n return x < y;\n}\n\ntemplate <typename T>\nbool greaterThan(T x, T y) {\n return x > y;\n}\n\n\n\/\/ Conjuctive: 120\ntemplate <typename T>\nT _and(T x, T y) {\n return x && y;\n}\n\n\/\/ Disjunctive: 110\ntemplate <typename T>\nT _or (T x, T y) {\n return x || y;\n}\n\n\n\n\ntemplate <typename T>\nTypeSpecification generateTypeSpecificationUnaryGenericUniform(DataType t, function<T (T)> f) {\n\n TypeSpecification spec;\n spec.inputTypes = {t};\n spec.returnType = t;\n spec.func = [f] (std::vector<int> xs) {\n \n T retVal = f(*(T *)&xs[0]);\n \n int retInt;\n bzero(&retInt, sizeof(int));\n \n memcpy(&retInt, &retVal, sizeof(T));\n \n return retInt;\n };\n \n return spec;\n}\n\ntemplate <typename T>\nTypeSpecification generateTypeSpecificationBinaryGenericUniform(DataType t, function<T (T,T)> f) {\n \n TypeSpecification spec;\n spec.inputTypes = {t, t};\n spec.returnType = t;\n spec.func = [f] (std::vector<int> xs) {\n \n T retVal = f(*(T *)&xs[0], *(T *)&xs[1]);\n \n int retInt;\n bzero(&retInt, sizeof(int));\n \n memcpy(&retInt, &retVal, sizeof(T));\n \n return retInt;\n };\n \n return spec;\n}\n\ntemplate <typename T, typename U>\nTypeSpecification generateTypeSpecificationBinaryGenericUniformSpecificReturn(DataType t, DataType u, function<U (T,T)> f) {\n \n TypeSpecification spec;\n spec.inputTypes = {t, t};\n spec.returnType = u;\n spec.func = [f] (std::vector<int> xs) {\n \n U retVal = f(*(T *)&xs[0], *(T *)&xs[1]);\n \n int retInt;\n bzero(&retInt, sizeof(int));\n \n memcpy(&retInt, &retVal, sizeof(U));\n \n return retInt;\n };\n \n return spec;\n}\n\nmap<string, OperatorType> OperatorType::operatorTypeMemoization;\n\nOperatorType OperatorType::lookupOperatorType(std::string opString) {\n \n OperatorType &opType = operatorTypeMemoization[opString];\n \n if(opType.operatorText.length() > 0) {\n return opType;\n }\n \n opType.isIdentityOperator = false;\n opType.operatorText = opString;\n \n int precedence;\n vector<TypeSpecification> typeSpecs;\n \n if(opString == \"!\") {\n TypeSpecification unaryNegationBool = generateTypeSpecificationUnaryGenericUniform<bool>(DataType::BOOLEAN, boolNegation<bool>);\n precedence = 999;\n typeSpecs = {unaryNegationBool};\n } else if(opString == \"^\") {\n TypeSpecification binaryInt = generateTypeSpecificationBinaryGenericUniform<int>(DataType::INT, exp<int>);\n TypeSpecification binaryFloat = generateTypeSpecificationBinaryGenericUniform<float>(DataType::FLOAT, exp<float>);\n \n typeSpecs = {binaryInt, binaryFloat};\n precedence = 160;\n } else if(opString == \"*\") {\n TypeSpecification binaryInt = generateTypeSpecificationBinaryGenericUniform<int>(DataType::INT, mult<int>);\n TypeSpecification binaryFloat = generateTypeSpecificationBinaryGenericUniform<float>(DataType::FLOAT, mult<float>);\n \n typeSpecs = {binaryInt, binaryFloat};\n precedence = 150;\n } else if(opString == \"\/\") {\n TypeSpecification binaryInt = generateTypeSpecificationBinaryGenericUniform<int>(DataType::INT, div<int>);\n TypeSpecification binaryFloat = generateTypeSpecificationBinaryGenericUniform<float>(DataType::FLOAT, div<float>);\n \n typeSpecs = {binaryInt, binaryFloat};\n precedence = 150;\n } else if(opString == \"%\") {\n TypeSpecification binaryInt = generateTypeSpecificationBinaryGenericUniform<int>(DataType::INT, mod<int>);\n \n typeSpecs = {binaryInt};\n precedence = 150;\n } else if(opString == \"+\") {\n TypeSpecification binaryInt = generateTypeSpecificationBinaryGenericUniform<int>(DataType::INT, add<int>);\n TypeSpecification binaryFloat = generateTypeSpecificationBinaryGenericUniform<float>(DataType::FLOAT, add<float>);\n \n typeSpecs = {binaryInt, binaryFloat};\n precedence = 140;\n } else if(opString == \"-\") {\n TypeSpecification unaryMinusInt = generateTypeSpecificationUnaryGenericUniform<int>(DataType::INT, negation<int>);\n TypeSpecification unaryMinusFloat = generateTypeSpecificationUnaryGenericUniform<float>(DataType::FLOAT, negation<float>);\n\n TypeSpecification binaryMinusInt = generateTypeSpecificationBinaryGenericUniform<int>(DataType::INT, subtract<int>);\n TypeSpecification binaryMinusFloat = generateTypeSpecificationBinaryGenericUniform<float>(DataType::FLOAT, subtract<float>);\n\n typeSpecs = {unaryMinusInt, unaryMinusFloat, binaryMinusInt, binaryMinusFloat};\n precedence = 140;\n } else if(opString == \"=>\") {\n TypeSpecification binaryBool = generateTypeSpecificationBinaryGenericUniform<bool>(DataType::BOOLEAN, implies<bool>);\n \n typeSpecs = {binaryBool};\n precedence = 131;\n } else if(opString == \"==\") {\n TypeSpecification binaryBool = generateTypeSpecificationBinaryGenericUniformSpecificReturn<bool, bool>(DataType::BOOLEAN, DataType::BOOLEAN, equal<bool>);\n TypeSpecification binaryInt = generateTypeSpecificationBinaryGenericUniformSpecificReturn<int, bool>(DataType::INT, DataType::BOOLEAN, equal<int>);\n TypeSpecification binaryFloat = generateTypeSpecificationBinaryGenericUniformSpecificReturn<float, bool>(DataType::FLOAT, DataType::BOOLEAN, equal<float>);\n\n typeSpecs = {binaryBool, binaryInt, binaryFloat};\n precedence = 130;\n } else if(opString == \"!=\") {\n TypeSpecification binaryBool = generateTypeSpecificationBinaryGenericUniformSpecificReturn<bool, bool>(DataType::BOOLEAN, DataType::BOOLEAN, notEqual<bool>);\n TypeSpecification binaryInt = generateTypeSpecificationBinaryGenericUniformSpecificReturn<int, bool>(DataType::INT, DataType::BOOLEAN, notEqual<int>);\n TypeSpecification binaryFloat = generateTypeSpecificationBinaryGenericUniformSpecificReturn<float, bool>(DataType::FLOAT, DataType::BOOLEAN, notEqual<float>);\n \n typeSpecs = {binaryBool, binaryInt, binaryFloat};\n precedence = 130;\n } else if(opString == \"<=\") {\n TypeSpecification binaryBool = generateTypeSpecificationBinaryGenericUniformSpecificReturn<bool, bool>(DataType::BOOLEAN, DataType::BOOLEAN, leq<bool>);\n TypeSpecification binaryInt = generateTypeSpecificationBinaryGenericUniformSpecificReturn<int, bool>(DataType::INT, DataType::BOOLEAN, leq<int>);\n TypeSpecification binaryFloat = generateTypeSpecificationBinaryGenericUniformSpecificReturn<float, bool>(DataType::FLOAT, DataType::BOOLEAN, leq<float>);\n \n typeSpecs = {binaryBool, binaryInt, binaryFloat};\n precedence = 130;\n } else if(opString == \">=\") {\n TypeSpecification binaryBool = generateTypeSpecificationBinaryGenericUniformSpecificReturn<bool, bool>(DataType::BOOLEAN, DataType::BOOLEAN, geq<bool>);\n TypeSpecification binaryInt = generateTypeSpecificationBinaryGenericUniformSpecificReturn<int, bool>(DataType::INT, DataType::BOOLEAN, geq<int>);\n TypeSpecification binaryFloat = generateTypeSpecificationBinaryGenericUniformSpecificReturn<float, bool>(DataType::FLOAT, DataType::BOOLEAN, geq<float>);\n \n typeSpecs = {binaryBool, binaryInt, binaryFloat};\n precedence = 130;\n } else if(opString == \"<\") {\n TypeSpecification binaryBool = generateTypeSpecificationBinaryGenericUniformSpecificReturn<bool, bool>(DataType::BOOLEAN, DataType::BOOLEAN, lessThan<bool>);\n TypeSpecification binaryInt = generateTypeSpecificationBinaryGenericUniformSpecificReturn<int, bool>(DataType::INT, DataType::BOOLEAN, lessThan<int>);\n TypeSpecification binaryFloat = generateTypeSpecificationBinaryGenericUniformSpecificReturn<float, bool>(DataType::FLOAT, DataType::BOOLEAN, lessThan<float>);\n \n typeSpecs = {binaryBool, binaryInt, binaryFloat};\n precedence = 130;\n } else if(opString == \">\") {\n TypeSpecification binaryBool = generateTypeSpecificationBinaryGenericUniformSpecificReturn<bool, bool>(DataType::BOOLEAN, DataType::BOOLEAN, greaterThan<bool>);\n TypeSpecification binaryInt = generateTypeSpecificationBinaryGenericUniformSpecificReturn<int, bool>(DataType::INT, DataType::BOOLEAN, greaterThan<int>);\n TypeSpecification binaryFloat = generateTypeSpecificationBinaryGenericUniformSpecificReturn<float, bool>(DataType::FLOAT, DataType::BOOLEAN, greaterThan<float>);\n \n typeSpecs = {binaryBool, binaryInt, binaryFloat};\n precedence = 130;\n } else if(opString == \"&&\") {\n TypeSpecification binaryBool = generateTypeSpecificationBinaryGenericUniform<bool>(DataType::BOOLEAN, _and<bool>);\n \n typeSpecs = {binaryBool};\n precedence = 120;\n } else if(opString == \"||\") {\n TypeSpecification binaryBool = generateTypeSpecificationBinaryGenericUniform<bool>(DataType::BOOLEAN, _or<bool>);\n \n typeSpecs = {binaryBool};\n precedence = 110;\n } else {\n throw \"Unknown operator: \" + opString;\n }\n \n opType.specifications = typeSpecs;\n opType.precedence = precedence;\n \n return opType;\n}\n\n\n\n\nOperatorType OperatorType::identity() {\n std::vector<TypeSpecification> specs;\n std::vector<lemonscript::DataType> types = {lemonscript::DataType::BOOLEAN, lemonscript::DataType::INT, lemonscript::DataType::FLOAT};\n for(auto it = types.begin(); it != types.end(); ++it) {\n lemonscript::DataType t = *it;\n TypeSpecification spec;\n spec.inputTypes = {t};\n spec.returnType = t;\n spec.func = [] (std::vector<int> xs) { return xs[0]; };\n specs.push_back(spec);\n }\n OperatorType opType;\n opType.isIdentityOperator = true;\n opType.specifications = specs;\n opType.operatorText = \"i\";\n opType.precedence = 999;\n \n return opType;\n}\n<|endoftext|>"} {"text":"<commit_before>\/* IBM_PROLOG_BEGIN_TAG *\/\n\/* This is an automatically generated prolog. *\/\n\/* *\/\n\/* $Source: src\/import\/chips\/p9\/procedures\/hwp\/memory\/lib\/mss_utils.H $ *\/\n\/* *\/\n\/* OpenPOWER HostBoot Project *\/\n\/* *\/\n\/* Contributors Listed Below - COPYRIGHT 2015,2019 *\/\n\/* [+] International Business Machines Corp. *\/\n\/* *\/\n\/* *\/\n\/* Licensed under the Apache License, Version 2.0 (the \"License\"); *\/\n\/* you may not use this file except in compliance with the License. *\/\n\/* You may obtain a copy of the License at *\/\n\/* *\/\n\/* http:\/\/www.apache.org\/licenses\/LICENSE-2.0 *\/\n\/* *\/\n\/* Unless required by applicable law or agreed to in writing, software *\/\n\/* distributed under the License is distributed on an \"AS IS\" BASIS, *\/\n\/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or *\/\n\/* implied. See the License for the specific language governing *\/\n\/* permissions and limitations under the License. *\/\n\/* *\/\n\/* IBM_PROLOG_END_TAG *\/\n\n\/\/\/\n\/\/\/ @file mss_utils.H\n\/\/\/ @brief Main include file for the Memory Subsystem\n\/\/\/\n\/\/ *HWP HWP Owner: Craig Hamilton <cchamilt@us.ibm.com>\n\/\/ *HWP HWP Backup: Brian Silver <bsilver@us.ibm.com>\n\/\/ *HWP Team: Memory\n\/\/ *HWP Level: 2\n\/\/ *HWP Consumed by: HB:FSP\n\n#ifndef _MSS_P9_ATTR_UTILS_H_\n#define _MSS_P9_ATTR_UTILS_H_\n\n#include \"utils\/index.H\"\n#include \"utils\/c_str.H\"\n\n#endif \/\/ _MSS_P9_ATTR_UTILS_H_\n<commit_msg>Change include paths in memory\/lib, tests<commit_after>\/* IBM_PROLOG_BEGIN_TAG *\/\n\/* This is an automatically generated prolog. *\/\n\/* *\/\n\/* $Source: src\/import\/chips\/p9\/procedures\/hwp\/memory\/lib\/mss_utils.H $ *\/\n\/* *\/\n\/* OpenPOWER HostBoot Project *\/\n\/* *\/\n\/* Contributors Listed Below - COPYRIGHT 2015,2019 *\/\n\/* [+] International Business Machines Corp. *\/\n\/* *\/\n\/* *\/\n\/* Licensed under the Apache License, Version 2.0 (the \"License\"); *\/\n\/* you may not use this file except in compliance with the License. *\/\n\/* You may obtain a copy of the License at *\/\n\/* *\/\n\/* http:\/\/www.apache.org\/licenses\/LICENSE-2.0 *\/\n\/* *\/\n\/* Unless required by applicable law or agreed to in writing, software *\/\n\/* distributed under the License is distributed on an \"AS IS\" BASIS, *\/\n\/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or *\/\n\/* implied. See the License for the specific language governing *\/\n\/* permissions and limitations under the License. *\/\n\/* *\/\n\/* IBM_PROLOG_END_TAG *\/\n\n\/\/\/\n\/\/\/ @file mss_utils.H\n\/\/\/ @brief Main include file for the Memory Subsystem\n\/\/\/\n\/\/ *HWP HWP Owner: Craig Hamilton <cchamilt@us.ibm.com>\n\/\/ *HWP HWP Backup: Brian Silver <bsilver@us.ibm.com>\n\/\/ *HWP Team: Memory\n\/\/ *HWP Level: 2\n\/\/ *HWP Consumed by: HB:FSP\n\n#ifndef _MSS_P9_ATTR_UTILS_H_\n#define _MSS_P9_ATTR_UTILS_H_\n\n\/\/TK: what is this for? BRS\n\n#include <lib\/utils\/index.H>\n#include <lib\/utils\/c_str.H>\n\n#endif \/\/ _MSS_P9_ATTR_UTILS_H_\n<|endoftext|>"} {"text":"<commit_before>\/\/===-- Reproducer.cpp ------------------------------------------*- C++ -*-===\/\/\n\/\/\n\/\/ Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.\n\/\/ See https:\/\/llvm.org\/LICENSE.txt for license information.\n\/\/ SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"lldb\/Utility\/Reproducer.h\"\n#include \"lldb\/Utility\/LLDBAssert.h\"\n\n#include \"llvm\/Support\/FileSystem.h\"\n#include \"llvm\/Support\/Threading.h\"\n#include \"llvm\/Support\/raw_ostream.h\"\n\nusing namespace lldb_private;\nusing namespace lldb_private::repro;\nusing namespace llvm;\nusing namespace llvm::yaml;\n\nReproducer &Reproducer::Instance() { return *InstanceImpl(); }\n\nllvm::Error Reproducer::Initialize(ReproducerMode mode,\n llvm::Optional<FileSpec> root) {\n lldbassert(!InstanceImpl() && \"Already initialized.\");\n InstanceImpl().emplace();\n\n switch (mode) {\n case ReproducerMode::Capture: {\n if (!root) {\n SmallString<128> repro_dir;\n auto ec = sys::fs::createUniqueDirectory(\"reproducer\", repro_dir);\n if (ec)\n return make_error<StringError>(\n \"unable to create unique reproducer directory\", ec);\n root.emplace(repro_dir);\n } else {\n auto ec = sys::fs::create_directory(root->GetPath());\n if (ec)\n return make_error<StringError>(\"unable to create reproducer directory\",\n ec);\n }\n return Instance().SetCapture(root);\n } break;\n case ReproducerMode::Replay:\n return Instance().SetReplay(root);\n case ReproducerMode::Off:\n break;\n };\n\n return Error::success();\n}\n\nbool Reproducer::Initialized() { return InstanceImpl().operator bool(); }\n\nvoid Reproducer::Terminate() {\n lldbassert(InstanceImpl() && \"Already terminated.\");\n InstanceImpl().reset();\n}\n\nOptional<Reproducer> &Reproducer::InstanceImpl() {\n static Optional<Reproducer> g_reproducer;\n return g_reproducer;\n}\n\nconst Generator *Reproducer::GetGenerator() const {\n std::lock_guard<std::mutex> guard(m_mutex);\n if (m_generator)\n return &(*m_generator);\n return nullptr;\n}\n\nconst Loader *Reproducer::GetLoader() const {\n std::lock_guard<std::mutex> guard(m_mutex);\n if (m_loader)\n return &(*m_loader);\n return nullptr;\n}\n\nGenerator *Reproducer::GetGenerator() {\n std::lock_guard<std::mutex> guard(m_mutex);\n if (m_generator)\n return &(*m_generator);\n return nullptr;\n}\n\nLoader *Reproducer::GetLoader() {\n std::lock_guard<std::mutex> guard(m_mutex);\n if (m_loader)\n return &(*m_loader);\n return nullptr;\n}\n\nllvm::Error Reproducer::SetCapture(llvm::Optional<FileSpec> root) {\n std::lock_guard<std::mutex> guard(m_mutex);\n\n if (root && m_loader)\n return make_error<StringError>(\n \"cannot generate a reproducer when replay one\",\n inconvertibleErrorCode());\n\n if (!root) {\n m_generator.reset();\n return Error::success();\n }\n\n m_generator.emplace(*root);\n return Error::success();\n}\n\nllvm::Error Reproducer::SetReplay(llvm::Optional<FileSpec> root) {\n std::lock_guard<std::mutex> guard(m_mutex);\n\n if (root && m_generator)\n return make_error<StringError>(\n \"cannot replay a reproducer when generating one\",\n inconvertibleErrorCode());\n\n if (!root) {\n m_loader.reset();\n return Error::success();\n }\n\n m_loader.emplace(*root);\n if (auto e = m_loader->LoadIndex())\n return e;\n\n return Error::success();\n}\n\nFileSpec Reproducer::GetReproducerPath() const {\n if (auto g = GetGenerator())\n return g->GetRoot();\n if (auto l = GetLoader())\n return l->GetRoot();\n return {};\n}\n\nGenerator::Generator(const FileSpec &root) : m_root(root), m_done(false) {}\n\nGenerator::~Generator() {}\n\nProviderBase *Generator::Register(std::unique_ptr<ProviderBase> provider) {\n std::lock_guard<std::mutex> lock(m_providers_mutex);\n std::pair<const void *, std::unique_ptr<ProviderBase>> key_value(\n provider->DynamicClassID(), std::move(provider));\n auto e = m_providers.insert(std::move(key_value));\n return e.first->getSecond().get();\n}\n\nvoid Generator::Keep() {\n assert(!m_done);\n m_done = true;\n\n for (auto &provider : m_providers)\n provider.second->Keep();\n\n AddProvidersToIndex();\n}\n\nvoid Generator::Discard() {\n assert(!m_done);\n m_done = true;\n\n for (auto &provider : m_providers)\n provider.second->Discard();\n\n llvm::sys::fs::remove_directories(m_root.GetPath());\n}\n\nconst FileSpec &Generator::GetRoot() const { return m_root; }\n\nvoid Generator::AddProvidersToIndex() {\n FileSpec index = m_root;\n index.AppendPathComponent(\"index.yaml\");\n\n std::error_code EC;\n auto strm = llvm::make_unique<raw_fd_ostream>(index.GetPath(), EC,\n sys::fs::OpenFlags::F_None);\n yaml::Output yout(*strm);\n\n std::vector<std::string> files;\n files.reserve(m_providers.size());\n for (auto &provider : m_providers) {\n files.emplace_back(provider.second->GetFile());\n }\n\n yout << files;\n}\n\nLoader::Loader(const FileSpec &root) : m_root(root), m_loaded(false) {}\n\nllvm::Error Loader::LoadIndex() {\n if (m_loaded)\n return llvm::Error::success();\n\n FileSpec index = m_root.CopyByAppendingPathComponent(\"index.yaml\");\n\n auto error_or_file = MemoryBuffer::getFile(index.GetPath());\n if (auto err = error_or_file.getError())\n return make_error<StringError>(\"unable to load reproducer index\", err);\n\n yaml::Input yin((*error_or_file)->getBuffer());\n yin >> m_files;\n if (auto err = yin.error())\n return make_error<StringError>(\"unable to read reproducer index\", err);\n\n \/\/ Sort files to speed up search.\n llvm::sort(m_files);\n\n \/\/ Remember that we've loaded the index.\n m_loaded = true;\n\n return llvm::Error::success();\n}\n\nbool Loader::HasFile(StringRef file) {\n assert(m_loaded);\n auto it = std::lower_bound(m_files.begin(), m_files.end(), file.str());\n return (it != m_files.end()) && (*it == file);\n}\n\nllvm::Expected<std::unique_ptr<DataRecorder>>\nDataRecorder::Create(FileSpec filename) {\n std::error_code ec;\n auto recorder = llvm::make_unique<DataRecorder>(std::move(filename), ec);\n if (ec)\n return llvm::errorCodeToError(ec);\n return recorder;\n}\n\nDataRecorder *CommandProvider::GetNewDataRecorder() {\n std::size_t i = m_data_recorders.size() + 1;\n std::string filename = (llvm::Twine(info::name) + llvm::Twine(\"-\") +\n llvm::Twine(i) + llvm::Twine(\".txt\"))\n .str();\n auto recorder_or_error =\n DataRecorder::Create(GetRoot().CopyByAppendingPathComponent(filename));\n if (!recorder_or_error) {\n llvm::consumeError(recorder_or_error.takeError());\n return nullptr;\n }\n\n m_data_recorders.push_back(std::move(*recorder_or_error));\n return m_data_recorders.back().get();\n}\n\nvoid CommandProvider::Keep() {\n std::vector<std::string> files;\n for (auto &recorder : m_data_recorders)\n files.push_back(recorder->GetFilename().GetPath());\n\n FileSpec file = GetRoot().CopyByAppendingPathComponent(info::file);\n std::error_code ec;\n llvm::raw_fd_ostream os(file.GetPath(), ec, llvm::sys::fs::F_Text);\n if (ec)\n return;\n yaml::Output yout(os);\n yout << files;\n\n m_data_recorders.clear();\n}\n\nvoid CommandProvider::Discard() { m_data_recorders.clear(); }\n\nvoid ProviderBase::anchor() {}\nchar ProviderBase::ID = 0;\nchar FileProvider::ID = 0;\nchar CommandProvider::ID = 0;\nconst char *FileInfo::name = \"files\";\nconst char *FileInfo::file = \"files.yaml\";\nconst char *CommandInfo::name = \"command-interpreter\";\nconst char *CommandInfo::file = \"command-interpreter.yaml\";\n<commit_msg>Fix gcc build for r355249<commit_after>\/\/===-- Reproducer.cpp ------------------------------------------*- C++ -*-===\/\/\n\/\/\n\/\/ Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.\n\/\/ See https:\/\/llvm.org\/LICENSE.txt for license information.\n\/\/ SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"lldb\/Utility\/Reproducer.h\"\n#include \"lldb\/Utility\/LLDBAssert.h\"\n\n#include \"llvm\/Support\/FileSystem.h\"\n#include \"llvm\/Support\/Threading.h\"\n#include \"llvm\/Support\/raw_ostream.h\"\n\nusing namespace lldb_private;\nusing namespace lldb_private::repro;\nusing namespace llvm;\nusing namespace llvm::yaml;\n\nReproducer &Reproducer::Instance() { return *InstanceImpl(); }\n\nllvm::Error Reproducer::Initialize(ReproducerMode mode,\n llvm::Optional<FileSpec> root) {\n lldbassert(!InstanceImpl() && \"Already initialized.\");\n InstanceImpl().emplace();\n\n switch (mode) {\n case ReproducerMode::Capture: {\n if (!root) {\n SmallString<128> repro_dir;\n auto ec = sys::fs::createUniqueDirectory(\"reproducer\", repro_dir);\n if (ec)\n return make_error<StringError>(\n \"unable to create unique reproducer directory\", ec);\n root.emplace(repro_dir);\n } else {\n auto ec = sys::fs::create_directory(root->GetPath());\n if (ec)\n return make_error<StringError>(\"unable to create reproducer directory\",\n ec);\n }\n return Instance().SetCapture(root);\n } break;\n case ReproducerMode::Replay:\n return Instance().SetReplay(root);\n case ReproducerMode::Off:\n break;\n };\n\n return Error::success();\n}\n\nbool Reproducer::Initialized() { return InstanceImpl().operator bool(); }\n\nvoid Reproducer::Terminate() {\n lldbassert(InstanceImpl() && \"Already terminated.\");\n InstanceImpl().reset();\n}\n\nOptional<Reproducer> &Reproducer::InstanceImpl() {\n static Optional<Reproducer> g_reproducer;\n return g_reproducer;\n}\n\nconst Generator *Reproducer::GetGenerator() const {\n std::lock_guard<std::mutex> guard(m_mutex);\n if (m_generator)\n return &(*m_generator);\n return nullptr;\n}\n\nconst Loader *Reproducer::GetLoader() const {\n std::lock_guard<std::mutex> guard(m_mutex);\n if (m_loader)\n return &(*m_loader);\n return nullptr;\n}\n\nGenerator *Reproducer::GetGenerator() {\n std::lock_guard<std::mutex> guard(m_mutex);\n if (m_generator)\n return &(*m_generator);\n return nullptr;\n}\n\nLoader *Reproducer::GetLoader() {\n std::lock_guard<std::mutex> guard(m_mutex);\n if (m_loader)\n return &(*m_loader);\n return nullptr;\n}\n\nllvm::Error Reproducer::SetCapture(llvm::Optional<FileSpec> root) {\n std::lock_guard<std::mutex> guard(m_mutex);\n\n if (root && m_loader)\n return make_error<StringError>(\n \"cannot generate a reproducer when replay one\",\n inconvertibleErrorCode());\n\n if (!root) {\n m_generator.reset();\n return Error::success();\n }\n\n m_generator.emplace(*root);\n return Error::success();\n}\n\nllvm::Error Reproducer::SetReplay(llvm::Optional<FileSpec> root) {\n std::lock_guard<std::mutex> guard(m_mutex);\n\n if (root && m_generator)\n return make_error<StringError>(\n \"cannot replay a reproducer when generating one\",\n inconvertibleErrorCode());\n\n if (!root) {\n m_loader.reset();\n return Error::success();\n }\n\n m_loader.emplace(*root);\n if (auto e = m_loader->LoadIndex())\n return e;\n\n return Error::success();\n}\n\nFileSpec Reproducer::GetReproducerPath() const {\n if (auto g = GetGenerator())\n return g->GetRoot();\n if (auto l = GetLoader())\n return l->GetRoot();\n return {};\n}\n\nGenerator::Generator(const FileSpec &root) : m_root(root), m_done(false) {}\n\nGenerator::~Generator() {}\n\nProviderBase *Generator::Register(std::unique_ptr<ProviderBase> provider) {\n std::lock_guard<std::mutex> lock(m_providers_mutex);\n std::pair<const void *, std::unique_ptr<ProviderBase>> key_value(\n provider->DynamicClassID(), std::move(provider));\n auto e = m_providers.insert(std::move(key_value));\n return e.first->getSecond().get();\n}\n\nvoid Generator::Keep() {\n assert(!m_done);\n m_done = true;\n\n for (auto &provider : m_providers)\n provider.second->Keep();\n\n AddProvidersToIndex();\n}\n\nvoid Generator::Discard() {\n assert(!m_done);\n m_done = true;\n\n for (auto &provider : m_providers)\n provider.second->Discard();\n\n llvm::sys::fs::remove_directories(m_root.GetPath());\n}\n\nconst FileSpec &Generator::GetRoot() const { return m_root; }\n\nvoid Generator::AddProvidersToIndex() {\n FileSpec index = m_root;\n index.AppendPathComponent(\"index.yaml\");\n\n std::error_code EC;\n auto strm = llvm::make_unique<raw_fd_ostream>(index.GetPath(), EC,\n sys::fs::OpenFlags::F_None);\n yaml::Output yout(*strm);\n\n std::vector<std::string> files;\n files.reserve(m_providers.size());\n for (auto &provider : m_providers) {\n files.emplace_back(provider.second->GetFile());\n }\n\n yout << files;\n}\n\nLoader::Loader(const FileSpec &root) : m_root(root), m_loaded(false) {}\n\nllvm::Error Loader::LoadIndex() {\n if (m_loaded)\n return llvm::Error::success();\n\n FileSpec index = m_root.CopyByAppendingPathComponent(\"index.yaml\");\n\n auto error_or_file = MemoryBuffer::getFile(index.GetPath());\n if (auto err = error_or_file.getError())\n return make_error<StringError>(\"unable to load reproducer index\", err);\n\n yaml::Input yin((*error_or_file)->getBuffer());\n yin >> m_files;\n if (auto err = yin.error())\n return make_error<StringError>(\"unable to read reproducer index\", err);\n\n \/\/ Sort files to speed up search.\n llvm::sort(m_files);\n\n \/\/ Remember that we've loaded the index.\n m_loaded = true;\n\n return llvm::Error::success();\n}\n\nbool Loader::HasFile(StringRef file) {\n assert(m_loaded);\n auto it = std::lower_bound(m_files.begin(), m_files.end(), file.str());\n return (it != m_files.end()) && (*it == file);\n}\n\nllvm::Expected<std::unique_ptr<DataRecorder>>\nDataRecorder::Create(FileSpec filename) {\n std::error_code ec;\n auto recorder = llvm::make_unique<DataRecorder>(std::move(filename), ec);\n if (ec)\n return llvm::errorCodeToError(ec);\n return std::move(recorder);\n}\n\nDataRecorder *CommandProvider::GetNewDataRecorder() {\n std::size_t i = m_data_recorders.size() + 1;\n std::string filename = (llvm::Twine(info::name) + llvm::Twine(\"-\") +\n llvm::Twine(i) + llvm::Twine(\".txt\"))\n .str();\n auto recorder_or_error =\n DataRecorder::Create(GetRoot().CopyByAppendingPathComponent(filename));\n if (!recorder_or_error) {\n llvm::consumeError(recorder_or_error.takeError());\n return nullptr;\n }\n\n m_data_recorders.push_back(std::move(*recorder_or_error));\n return m_data_recorders.back().get();\n}\n\nvoid CommandProvider::Keep() {\n std::vector<std::string> files;\n for (auto &recorder : m_data_recorders)\n files.push_back(recorder->GetFilename().GetPath());\n\n FileSpec file = GetRoot().CopyByAppendingPathComponent(info::file);\n std::error_code ec;\n llvm::raw_fd_ostream os(file.GetPath(), ec, llvm::sys::fs::F_Text);\n if (ec)\n return;\n yaml::Output yout(os);\n yout << files;\n\n m_data_recorders.clear();\n}\n\nvoid CommandProvider::Discard() { m_data_recorders.clear(); }\n\nvoid ProviderBase::anchor() {}\nchar ProviderBase::ID = 0;\nchar FileProvider::ID = 0;\nchar CommandProvider::ID = 0;\nconst char *FileInfo::name = \"files\";\nconst char *FileInfo::file = \"files.yaml\";\nconst char *CommandInfo::name = \"command-interpreter\";\nconst char *CommandInfo::file = \"command-interpreter.yaml\";\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n#include <time.h>\n#include <array>\n#include <SDL_mixer.h>\n#include \"GameManager.h\"\n#include \"Log.h\"\n#include \"Menu.h\"\n#include \"Timer.h\"\n#include \"levelLoader.h\"\n\nGameManager::GameManager(Window* window):\n window(window)\n{\n currentState = STATE_MENU;\n _quit = false;\n}\n\nvoid GameManager::runGame()\n{\n Mix_OpenAudio(MIX_DEFAULT_FREQUENCY, MIX_DEFAULT_FORMAT, 2, 4096);\n Mix_Music *music = NULL;\n std::string resPath = \"res\";\n std::string filePath = \"\";\n filePath = resPath + PATH_SEP + \"backgroundmusic.wav\";\n\n music = Mix_LoadMUS(filePath.c_str());\n \n if(!music)\n \/\/ TODO: Adapt this to \n printf(\"Mix_LoadMUS(\\\"backgroundmusic.wav\\\"): %s\\n\", Mix_GetError());\n\n Mix_PlayMusic(music, -1);\n\n Entity* paddle = new Entity(window, \"paddle.bmp\", 305, 490);\n paddle->setMoveRate(5);\n entities.push_back(paddle);\n\n ball = new Ball(window, \"ball.bmp\", window->getWidth() \/ 2, window->getHeight() \/ 2, paddle);\n ball->setOnPaddle(true);\n\n ball2 = new Ball(window, \"ball2.bmp\", window->getWidth() \/ 2, window->getHeight() \/ 2, paddle);\n ball2->setOnPaddle(true);\n\tlevelLoader* loader = new levelLoader(window, entities);\n\n \/\/used for random powerup spwaning\n srand(time(NULL));\n randNum = rand() % 4;\n mod = new Mods(window, \"PowerUP.bmp\", 305, 0 );\/\/makes a new power down object\n\n upNum = rand() % 2;\n\tdownNum = rand() % 2;\n\n Timer fpsTimer;\n Timer capTimer;\n\n uint32_t frameCount = 0;\n fpsTimer.start();\n\n Menu mainMenu(this);\n mainMenu.addEntry(\"Play\");\n mainMenu.addEntry(\"Settings\");\n mainMenu.addEntry(\"Exit\");\n\n Menu settingsMenu(this);\n settingsMenu.addEntry(\"Back\");\n\n while (!_quit)\n {\n window->clear();\n\n capTimer.start();\n\n switch (currentState)\n {\n case STATE_MENU:\n {\n SDL_Texture* bgTexture = window->loadTexture(\"bg.bmp\");\n window->renderTexture(bgTexture, 0, 0);\n mainMenu.tick();\n break;\n }\n case STATE_SETTINGS:\n break;\n case STATE_PLAYING:\n gameTick();\n break;\n default:\n Log::warn(\"Recieved unhandled gamestate: \" + std::to_string(currentState));\n break;\n }\n\n \/\/ divide the amount of frames displayed by the runtime in seconds to get the average fps\n float avgFps = frameCount \/ (fpsTimer.getTicks() \/ 1000.f);\n if (avgFps > 2000000)\n avgFps = 0;\n\n window->renderText(std::to_string((int)avgFps), window->getWidth()-30, 0, { 0, 0, 0 }, 25, FONT_RENDER_BLENDED, { 0, 0, 0 });\n\n window->render();\n\n frameCount++;\n\n \/\/ if our fps it too high, wait here until we're back to ~60fps\n if (capTimer.getTicks() < (1000 \/ window->getMaxFps()))\n {\n int waitTime = (1000 \/ window->getMaxFps()) - capTimer.getTicks();\n \/\/Log::info(\"Waiting \" + std::to_string(waitTime) + \" MS\");\n SDL_Delay(waitTime);\n }\n }\n}\n\nvoid GameManager::gameTick()\n{\n SDL_PollEvent(&event);\n\n \/\/ paddle is always added to the entities vector first, so this is fine\n Entity* paddle = entities[0];\n\n switch (event.type)\n {\n \/\/ if user clicks the red X\n case SDL_QUIT:\n _quit = true;\n break;\n\n case SDL_KEYDOWN:\n switch (event.key.keysym.sym)\n {\n case SDLK_LEFT:\n paddle->startMoving(MOVE_LEFT);\n break;\n case SDLK_RIGHT:\n paddle->startMoving(MOVE_RIGHT);\n break;\n case SDLK_SPACE:\n if (ball->isOnPaddle())\n ball->detach();\n break;\n }\n break;\n\n case SDL_KEYUP:\n switch (event.key.keysym.sym)\n {\n case SDLK_LEFT:\n paddle->stopMoving(MOVE_LEFT);\n break;\n case SDLK_RIGHT:\n paddle->stopMoving(MOVE_RIGHT);\n break;\n }\n break;\n }\n\n for (Entity* e : entities)\n {\n \/\/ don't think this is that cpu intensive but I guess it could be\n if (ball->collidedWith(e))\n {\n ball->handleCollision(e);\n\n }\n\n if(ball2->collidedWith(e))\n ball2->handleCollision(e);\n\n e->update();\n }\n\n\/************** Code segment used for powerup implementation ***************\/\nif(randNum == 0) \/\/anthony is gay\n{\n mod->update();\n if(mod->collidedWith(paddle))\n {\n mod->fastPaddle();\n paddle->setMoveRate(7);\n mod->remove();\n }\n}\n\nif(randNum == 1)\n{\n mod->update();\n if(mod->collidedWith(paddle))\n {\n mod->largePaddle();\n mod->remove();\n }\n}\n\nif(randNum == 2)\n{\n mod->update();\n if(mod->collidedWith(paddle))\n {\n mod->slowerPaddle();\n paddle->setMoveRate(3);\n mod->remove();\n }\n }\n if(randNum == 3)\n {\n mod->update();\n if(mod->collidedWith(paddle))\n {\n mod->smallPaddle();\n mod->remove();\n }\n }\n\/***************************************************************************\/\n\n ball->update();\n}\n<commit_msg>Fixed LevelLoader<commit_after>#include <iostream>\n#include <time.h>\n#include <array>\n#include <SDL_mixer.h>\n#include \"GameManager.h\"\n#include \"Log.h\"\n#include \"Menu.h\"\n#include \"Timer.h\"\n#include \"levelLoader.h\"\n\nGameManager::GameManager(Window* window):\n window(window)\n{\n currentState = STATE_MENU;\n _quit = false;\n}\n\nvoid GameManager::runGame()\n{\n Mix_OpenAudio(MIX_DEFAULT_FREQUENCY, MIX_DEFAULT_FORMAT, 2, 4096);\n Mix_Music *music = NULL;\n std::string resPath = \"res\";\n std::string filePath = \"\";\n filePath = resPath + PATH_SEP + \"backgroundmusic.wav\";\n\n music = Mix_LoadMUS(filePath.c_str());\n \n if(!music)\n \/\/ TODO: Adapt this to \n printf(\"Mix_LoadMUS(\\\"backgroundmusic.wav\\\"): %s\\n\", Mix_GetError());\n\n Mix_PlayMusic(music, -1);\n\n Entity* paddle = new Entity(window, \"paddle.bmp\", 305, 490);\n paddle->setMoveRate(5);\n entities.push_back(paddle);\n\n ball = new Ball(window, \"ball.bmp\", window->getWidth() \/ 2, window->getHeight() \/ 2, paddle);\n ball->setOnPaddle(true);\n\n ball2 = new Ball(window, \"ball2.bmp\", window->getWidth() \/ 2, window->getHeight() \/ 2, paddle);\n ball2->setOnPaddle(true);\n\tLevelLoader* loader = new LevelLoader(window, entities);\n\n \/\/used for random powerup spwaning\n srand(time(NULL));\n randNum = rand() % 4;\n mod = new Mods(window, \"PowerUP.bmp\", 305, 0 );\/\/makes a new power down object\n\n upNum = rand() % 2;\n\tdownNum = rand() % 2;\n\n Timer fpsTimer;\n Timer capTimer;\n\n uint32_t frameCount = 0;\n fpsTimer.start();\n\n Menu mainMenu(this);\n mainMenu.addEntry(\"Play\");\n mainMenu.addEntry(\"Settings\");\n mainMenu.addEntry(\"Exit\");\n\n Menu settingsMenu(this);\n settingsMenu.addEntry(\"Back\");\n\n while (!_quit)\n {\n window->clear();\n\n capTimer.start();\n\n switch (currentState)\n {\n case STATE_MENU:\n {\n SDL_Texture* bgTexture = window->loadTexture(\"bg.bmp\");\n window->renderTexture(bgTexture, 0, 0);\n mainMenu.tick();\n break;\n }\n case STATE_SETTINGS:\n break;\n case STATE_PLAYING:\n gameTick();\n break;\n default:\n Log::warn(\"Recieved unhandled gamestate: \" + std::to_string(currentState));\n break;\n }\n\n \/\/ divide the amount of frames displayed by the runtime in seconds to get the average fps\n float avgFps = frameCount \/ (fpsTimer.getTicks() \/ 1000.f);\n if (avgFps > 2000000)\n avgFps = 0;\n\n window->renderText(std::to_string((int)avgFps), window->getWidth()-30, 0, { 0, 0, 0 }, 25, FONT_RENDER_BLENDED, { 0, 0, 0 });\n\n window->render();\n\n frameCount++;\n\n \/\/ if our fps it too high, wait here until we're back to ~60fps\n if (capTimer.getTicks() < (1000 \/ window->getMaxFps()))\n {\n int waitTime = (1000 \/ window->getMaxFps()) - capTimer.getTicks();\n \/\/Log::info(\"Waiting \" + std::to_string(waitTime) + \" MS\");\n SDL_Delay(waitTime);\n }\n }\n}\n\nvoid GameManager::gameTick()\n{\n SDL_PollEvent(&event);\n\n \/\/ paddle is always added to the entities vector first, so this is fine\n Entity* paddle = entities[0];\n\n switch (event.type)\n {\n \/\/ if user clicks the red X\n case SDL_QUIT:\n _quit = true;\n break;\n\n case SDL_KEYDOWN:\n switch (event.key.keysym.sym)\n {\n case SDLK_LEFT:\n paddle->startMoving(MOVE_LEFT);\n break;\n case SDLK_RIGHT:\n paddle->startMoving(MOVE_RIGHT);\n break;\n case SDLK_SPACE:\n if (ball->isOnPaddle())\n ball->detach();\n break;\n }\n break;\n\n case SDL_KEYUP:\n switch (event.key.keysym.sym)\n {\n case SDLK_LEFT:\n paddle->stopMoving(MOVE_LEFT);\n break;\n case SDLK_RIGHT:\n paddle->stopMoving(MOVE_RIGHT);\n break;\n }\n break;\n }\n\n for (Entity* e : entities)\n {\n \/\/ don't think this is that cpu intensive but I guess it could be\n if (ball->collidedWith(e))\n {\n ball->handleCollision(e);\n\n }\n\n if(ball2->collidedWith(e))\n ball2->handleCollision(e);\n\n e->update();\n }\n\n\/************** Code segment used for powerup implementation ***************\/\nif(randNum == 0) \/\/anthony is gay\n{\n mod->update();\n if(mod->collidedWith(paddle))\n {\n mod->fastPaddle();\n paddle->setMoveRate(7);\n mod->remove();\n }\n}\n\nif(randNum == 1)\n{\n mod->update();\n if(mod->collidedWith(paddle))\n {\n mod->largePaddle();\n mod->remove();\n }\n}\n\nif(randNum == 2)\n{\n mod->update();\n if(mod->collidedWith(paddle))\n {\n mod->slowerPaddle();\n paddle->setMoveRate(3);\n mod->remove();\n }\n }\n if(randNum == 3)\n {\n mod->update();\n if(mod->collidedWith(paddle))\n {\n mod->smallPaddle();\n mod->remove();\n }\n }\n\/***************************************************************************\/\n\n ball->update();\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n RawSpeed - RAW file decoder.\n\n Copyright (C) 2009-2010 Klaus Post\n Copyright (C) 2014-2015 Pedro Côrte-Real\n Copyright (C) 2017 Roman Lebedev\n\n This library is free software; you can redistribute it and\/or\n modify it under the terms of the GNU Lesser General Public\n License as published by the Free Software Foundation; either\n version 2 of the License, or (at your option) any later version.\n\n This library is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n Lesser General Public License for more details.\n\n You should have received a copy of the GNU Lesser General Public\n License along with this library; if not, write to the Free Software\n Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n*\/\n\n#include \"decompressors\/SamsungV2Decompressor.h\"\n#include \"common\/Common.h\" \/\/ for uint32, ushort16, int32\n#include \"common\/Point.h\" \/\/ for iPoint2D\n#include \"common\/RawImage.h\" \/\/ for RawImage, RawImageData\n#include \"decoders\/RawDecoderException.h\" \/\/ for ThrowRDE\n#include \"io\/BitPumpMSB32.h\" \/\/ for BitPumpMSB32\n#include \"io\/ByteStream.h\" \/\/ for ByteStream\n#include <algorithm> \/\/ for max\n#include <cassert> \/\/ for assert\n\nnamespace rawspeed {\n\n\/\/ Seriously Samsung just use lossless jpeg already, it compresses better too :)\n\n\/\/ Thanks to Michael Reichmann (Luminous Landscape) for putting Pedro Côrte-Real\n\/\/ in contact and Loring von Palleske (Samsung) for pointing to the open-source\n\/\/ code of Samsung's DNG converter at http:\/\/opensource.samsung.com\/\n\nenum struct SamsungV2Decompressor::OptFlags : uint32 {\n NONE = 0U, \/\/ no flags\n SKIP = 1U << 0U, \/\/ Skip checking if we need differences from previous line\n MV = 1U << 1U, \/\/ Simplify motion vector definition\n QP = 1U << 2U, \/\/ Don't scale the diff values\n\n \/\/ all possible flags\n ALL = SKIP | MV | QP,\n};\n\nconstexpr SamsungV2Decompressor::OptFlags\noperator|(SamsungV2Decompressor::OptFlags lhs,\n SamsungV2Decompressor::OptFlags rhs) {\n return static_cast<SamsungV2Decompressor::OptFlags>(\n static_cast<std::underlying_type<SamsungV2Decompressor::OptFlags>::type>(\n lhs) |\n static_cast<std::underlying_type<SamsungV2Decompressor::OptFlags>::type>(\n rhs));\n}\n\nconstexpr bool operator&(SamsungV2Decompressor::OptFlags lhs,\n SamsungV2Decompressor::OptFlags rhs) {\n const auto intersect = static_cast<SamsungV2Decompressor::OptFlags>(\n static_cast<std::underlying_type<SamsungV2Decompressor::OptFlags>::type>(\n lhs) &\n static_cast<std::underlying_type<SamsungV2Decompressor::OptFlags>::type>(\n rhs));\n return intersect != SamsungV2Decompressor::OptFlags::NONE;\n}\n\nSamsungV2Decompressor::SamsungV2Decompressor(const RawImage& image,\n const ByteStream& bs, int bit)\n : AbstractSamsungDecompressor(image), bits(bit) {\n BitPumpMSB32 startpump(bs);\n\n \/\/ Process the initial metadata bits, we only really use initVal, width and\n \/\/ height (the last two match the TIFF values anyway)\n startpump.getBits(16); \/\/ NLCVersion\n startpump.getBits(4); \/\/ ImgFormat\n bitDepth = startpump.getBits(4) + 1;\n startpump.getBits(4); \/\/ NumBlkInRCUnit\n startpump.getBits(4); \/\/ CompressionRatio\n width = startpump.getBits(16);\n height = startpump.getBits(16);\n startpump.getBits(16); \/\/ TileWidth\n startpump.getBits(4); \/\/ reserved\n\n \/\/ The format includes an optimization code that sets 3 flags to change the\n \/\/ decoding parameters\n const uint32 optflags = startpump.getBits(4);\n if (optflags > static_cast<uint32>(OptFlags::ALL))\n ThrowRDE(\"Invalid opt flags %x\", optflags);\n _flags = static_cast<OptFlags>(optflags);\n\n startpump.getBits(8); \/\/ OverlapWidth\n startpump.getBits(8); \/\/ reserved\n startpump.getBits(8); \/\/ Inc\n startpump.getBits(2); \/\/ reserved\n initVal = startpump.getBits(14);\n\n if (width == 0 || height == 0 || width % 16 != 0 || width > 6496 ||\n height > 4336)\n ThrowRDE(\"Unexpected image dimensions found: (%u; %u)\", width, height);\n\n if (width != static_cast<uint32>(mRaw->dim.x) ||\n height != static_cast<uint32>(mRaw->dim.y))\n ThrowRDE(\"EXIF image dimensions do not match dimensions from raw header\");\n\n data = startpump.getStream(startpump.getRemainSize());\n}\n\nvoid SamsungV2Decompressor::decompress() {\n switch (_flags) {\n case OptFlags::NONE:\n for (uint32 row = 0; row < height; row++)\n decompressRow<OptFlags::NONE>(row);\n break;\n case OptFlags::ALL:\n for (uint32 row = 0; row < height; row++)\n decompressRow<OptFlags::ALL>(row);\n break;\n\n case OptFlags::SKIP:\n for (uint32 row = 0; row < height; row++)\n decompressRow<OptFlags::SKIP>(row);\n break;\n case OptFlags::MV:\n for (uint32 row = 0; row < height; row++)\n decompressRow<OptFlags::MV>(row);\n break;\n case OptFlags::QP:\n for (uint32 row = 0; row < height; row++)\n decompressRow<OptFlags::QP>(row);\n break;\n\n#pragma GCC diagnostic push\n#pragma GCC diagnostic ignored \"-Wswitch\"\n case OptFlags::SKIP | OptFlags::MV:\n for (uint32 row = 0; row < height; row++)\n decompressRow<OptFlags::SKIP | OptFlags::MV>(row);\n break;\n case OptFlags::SKIP | OptFlags::QP:\n for (uint32 row = 0; row < height; row++)\n decompressRow<OptFlags::SKIP | OptFlags::QP>(row);\n break;\n\n case OptFlags::MV | OptFlags::QP:\n for (uint32 row = 0; row < height; row++)\n decompressRow<OptFlags::MV | OptFlags::QP>(row);\n break;\n#pragma GCC diagnostic pop\n\n default:\n __builtin_unreachable();\n }\n}\n\ntemplate <SamsungV2Decompressor::OptFlags optflags>\nvoid SamsungV2Decompressor::decompressRow(uint32 row) {\n \/\/ The format is relatively straightforward. Each line gets encoded as a set\n \/\/ of differences from pixels from another line. Pixels are grouped in blocks\n \/\/ of 16 (8 green, 8 red or blue). Each block is encoded in three sections.\n \/\/ First 1 or 4 bits to specify which reference pixels to use, then a section\n \/\/ that specifies for each pixel the number of bits in the difference, then\n \/\/ the actual difference bits\n\n \/\/ Align pump to 16byte boundary\n const auto line_offset = data.getPosition();\n if ((line_offset & 0xf) != 0)\n data.skipBytes(16 - (line_offset & 0xf));\n\n BitPumpMSB32 pump(data);\n\n auto* img = reinterpret_cast<ushort16*>(mRaw->getData(0, row));\n ushort16* img_up = reinterpret_cast<ushort16*>(\n mRaw->getData(0, std::max(0, static_cast<int>(row) - 1)));\n ushort16* img_up2 = reinterpret_cast<ushort16*>(\n mRaw->getData(0, std::max(0, static_cast<int>(row) - 2)));\n\n \/\/ Initialize the motion and diff modes at the start of the line\n uint32 motion = 7;\n \/\/ By default we are not scaling values at all\n int32 scale = 0;\n\n uint32 diffBitsMode[3][2] = {{0}};\n for (auto& i : diffBitsMode)\n i[0] = i[1] = (row == 0 || row == 1) ? 7 : 4;\n\n assert(width >= 16);\n for (uint32 col = 0; col < width; col += 16) {\n if (!(optflags & OptFlags::QP) && !(col & 63)) {\n int32 scalevals[] = {0, -2, 2};\n uint32 i = pump.getBits(2);\n scale = i < 3 ? scale + scalevals[i] : pump.getBits(12);\n }\n\n \/\/ First we figure out which reference pixels mode we're in\n if (optflags & OptFlags::MV)\n motion = pump.getBits(1) ? 3 : 7;\n else if (!pump.getBits(1))\n motion = pump.getBits(3);\n\n if ((row == 0 || row == 1) && (motion != 7))\n ThrowRDE(\"At start of image and motion isn't 7. File corrupted?\");\n\n if (motion == 7) {\n \/\/ The base case, just set all pixels to the previous ones on the same\n \/\/ line If we're at the left edge we just start at the initial value\n for (uint32 i = 0; i < 16; i++)\n img[i] = (col == 0) ? initVal : *(img + i - 2);\n } else {\n \/\/ The complex case, we now need to actually lookup one or two lines\n \/\/ above\n if (row < 2)\n ThrowRDE(\n \"Got a previous line lookup on first two lines. File corrupted?\");\n\n int32 motionOffset[7] = {-4, -2, -2, 0, 0, 2, 4};\n int32 motionDoAverage[7] = {0, 0, 1, 0, 1, 0, 0};\n\n int32 slideOffset = motionOffset[motion];\n int32 doAverage = motionDoAverage[motion];\n\n for (uint32 i = 0; i < 16; i++) {\n ushort16* refpixel;\n\n if ((row + i) & 0x1) \/\/ Red or blue pixels use same color two lines up\n refpixel = img_up2 + i + slideOffset;\n else \/\/ Green pixel N uses Green pixel N from row above (top left or\n \/\/ top right)\n refpixel = img_up + i + slideOffset + (((i % 2) != 0) ? -1 : 1);\n\n \/\/ In some cases we use as reference interpolation of this pixel and\n \/\/ the next\n if (doAverage)\n img[i] = (*refpixel + *(refpixel + 2) + 1) >> 1;\n else\n img[i] = *refpixel;\n }\n }\n\n \/\/ Figure out how many difference bits we have to read for each pixel\n uint32 diffBits[4] = {0};\n if (optflags & OptFlags::SKIP || !pump.getBits(1)) {\n uint32 flags[4];\n for (unsigned int& flag : flags)\n flag = pump.getBits(2);\n\n for (uint32 i = 0; i < 4; i++) {\n \/\/ The color is 0-Green 1-Blue 2-Red\n uint32 colornum = (row % 2 != 0) ? i >> 1 : ((i >> 1) + 2) % 3;\n\n assert(flags[i] <= 3);\n switch (flags[i]) {\n case 0:\n diffBits[i] = diffBitsMode[colornum][0];\n break;\n case 1:\n diffBits[i] = diffBitsMode[colornum][0] + 1;\n break;\n case 2:\n diffBits[i] = diffBitsMode[colornum][0] - 1;\n break;\n case 3:\n diffBits[i] = pump.getBits(4);\n break;\n default:\n __builtin_unreachable();\n }\n\n diffBitsMode[colornum][0] = diffBitsMode[colornum][1];\n diffBitsMode[colornum][1] = diffBits[i];\n\n if (diffBits[i] > bitDepth + 1)\n ThrowRDE(\"Too many difference bits. File corrupted?\");\n }\n }\n\n \/\/ Actually read the differences and write them to the pixels\n for (uint32 i = 0; i < 16; i++) {\n uint32 len = diffBits[i >> 2];\n int32 diff = pump.getBits(len);\n\n \/\/ If the first bit is 1 we need to turn this into a negative number\n if (len != 0 && diff >> (len - 1))\n diff -= (1 << len);\n\n ushort16* value = nullptr;\n \/\/ Apply the diff to pixels 0 2 4 6 8 10 12 14 1 3 5 7 9 11 13 15\n if (row % 2)\n value = &img[((i & 0x7) << 1) + 1 - (i >> 3)];\n else\n value = &img[((i & 0x7) << 1) + (i >> 3)];\n\n diff = diff * (scale * 2 + 1) + scale;\n *value = clampBits(static_cast<int>(*value) + diff, bits);\n }\n\n img += 16;\n img_up += 16;\n img_up2 += 16;\n }\n\n data.skipBytes(pump.getBufferPosition());\n}\n\n} \/\/ namespace rawspeed\n<commit_msg>SamsungV2Decompressor: OptFlags operator&: damn gcc4.9<commit_after>\/*\n RawSpeed - RAW file decoder.\n\n Copyright (C) 2009-2010 Klaus Post\n Copyright (C) 2014-2015 Pedro Côrte-Real\n Copyright (C) 2017 Roman Lebedev\n\n This library is free software; you can redistribute it and\/or\n modify it under the terms of the GNU Lesser General Public\n License as published by the Free Software Foundation; either\n version 2 of the License, or (at your option) any later version.\n\n This library is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n Lesser General Public License for more details.\n\n You should have received a copy of the GNU Lesser General Public\n License along with this library; if not, write to the Free Software\n Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n*\/\n\n#include \"decompressors\/SamsungV2Decompressor.h\"\n#include \"common\/Common.h\" \/\/ for uint32, ushort16, int32\n#include \"common\/Point.h\" \/\/ for iPoint2D\n#include \"common\/RawImage.h\" \/\/ for RawImage, RawImageData\n#include \"decoders\/RawDecoderException.h\" \/\/ for ThrowRDE\n#include \"io\/BitPumpMSB32.h\" \/\/ for BitPumpMSB32\n#include \"io\/ByteStream.h\" \/\/ for ByteStream\n#include <algorithm> \/\/ for max\n#include <cassert> \/\/ for assert\n\nnamespace rawspeed {\n\n\/\/ Seriously Samsung just use lossless jpeg already, it compresses better too :)\n\n\/\/ Thanks to Michael Reichmann (Luminous Landscape) for putting Pedro Côrte-Real\n\/\/ in contact and Loring von Palleske (Samsung) for pointing to the open-source\n\/\/ code of Samsung's DNG converter at http:\/\/opensource.samsung.com\/\n\nenum struct SamsungV2Decompressor::OptFlags : uint32 {\n NONE = 0U, \/\/ no flags\n SKIP = 1U << 0U, \/\/ Skip checking if we need differences from previous line\n MV = 1U << 1U, \/\/ Simplify motion vector definition\n QP = 1U << 2U, \/\/ Don't scale the diff values\n\n \/\/ all possible flags\n ALL = SKIP | MV | QP,\n};\n\nconstexpr SamsungV2Decompressor::OptFlags\noperator|(SamsungV2Decompressor::OptFlags lhs,\n SamsungV2Decompressor::OptFlags rhs) {\n return static_cast<SamsungV2Decompressor::OptFlags>(\n static_cast<std::underlying_type<SamsungV2Decompressor::OptFlags>::type>(\n lhs) |\n static_cast<std::underlying_type<SamsungV2Decompressor::OptFlags>::type>(\n rhs));\n}\n\nconstexpr bool operator&(SamsungV2Decompressor::OptFlags lhs,\n SamsungV2Decompressor::OptFlags rhs) {\n return SamsungV2Decompressor::OptFlags::NONE !=\n static_cast<SamsungV2Decompressor::OptFlags>(\n static_cast<\n std::underlying_type<SamsungV2Decompressor::OptFlags>::type>(\n lhs) &\n static_cast<\n std::underlying_type<SamsungV2Decompressor::OptFlags>::type>(\n rhs));\n}\n\nSamsungV2Decompressor::SamsungV2Decompressor(const RawImage& image,\n const ByteStream& bs, int bit)\n : AbstractSamsungDecompressor(image), bits(bit) {\n BitPumpMSB32 startpump(bs);\n\n \/\/ Process the initial metadata bits, we only really use initVal, width and\n \/\/ height (the last two match the TIFF values anyway)\n startpump.getBits(16); \/\/ NLCVersion\n startpump.getBits(4); \/\/ ImgFormat\n bitDepth = startpump.getBits(4) + 1;\n startpump.getBits(4); \/\/ NumBlkInRCUnit\n startpump.getBits(4); \/\/ CompressionRatio\n width = startpump.getBits(16);\n height = startpump.getBits(16);\n startpump.getBits(16); \/\/ TileWidth\n startpump.getBits(4); \/\/ reserved\n\n \/\/ The format includes an optimization code that sets 3 flags to change the\n \/\/ decoding parameters\n const uint32 optflags = startpump.getBits(4);\n if (optflags > static_cast<uint32>(OptFlags::ALL))\n ThrowRDE(\"Invalid opt flags %x\", optflags);\n _flags = static_cast<OptFlags>(optflags);\n\n startpump.getBits(8); \/\/ OverlapWidth\n startpump.getBits(8); \/\/ reserved\n startpump.getBits(8); \/\/ Inc\n startpump.getBits(2); \/\/ reserved\n initVal = startpump.getBits(14);\n\n if (width == 0 || height == 0 || width % 16 != 0 || width > 6496 ||\n height > 4336)\n ThrowRDE(\"Unexpected image dimensions found: (%u; %u)\", width, height);\n\n if (width != static_cast<uint32>(mRaw->dim.x) ||\n height != static_cast<uint32>(mRaw->dim.y))\n ThrowRDE(\"EXIF image dimensions do not match dimensions from raw header\");\n\n data = startpump.getStream(startpump.getRemainSize());\n}\n\nvoid SamsungV2Decompressor::decompress() {\n switch (_flags) {\n case OptFlags::NONE:\n for (uint32 row = 0; row < height; row++)\n decompressRow<OptFlags::NONE>(row);\n break;\n case OptFlags::ALL:\n for (uint32 row = 0; row < height; row++)\n decompressRow<OptFlags::ALL>(row);\n break;\n\n case OptFlags::SKIP:\n for (uint32 row = 0; row < height; row++)\n decompressRow<OptFlags::SKIP>(row);\n break;\n case OptFlags::MV:\n for (uint32 row = 0; row < height; row++)\n decompressRow<OptFlags::MV>(row);\n break;\n case OptFlags::QP:\n for (uint32 row = 0; row < height; row++)\n decompressRow<OptFlags::QP>(row);\n break;\n\n#pragma GCC diagnostic push\n#pragma GCC diagnostic ignored \"-Wswitch\"\n case OptFlags::SKIP | OptFlags::MV:\n for (uint32 row = 0; row < height; row++)\n decompressRow<OptFlags::SKIP | OptFlags::MV>(row);\n break;\n case OptFlags::SKIP | OptFlags::QP:\n for (uint32 row = 0; row < height; row++)\n decompressRow<OptFlags::SKIP | OptFlags::QP>(row);\n break;\n\n case OptFlags::MV | OptFlags::QP:\n for (uint32 row = 0; row < height; row++)\n decompressRow<OptFlags::MV | OptFlags::QP>(row);\n break;\n#pragma GCC diagnostic pop\n\n default:\n __builtin_unreachable();\n }\n}\n\ntemplate <SamsungV2Decompressor::OptFlags optflags>\nvoid SamsungV2Decompressor::decompressRow(uint32 row) {\n \/\/ The format is relatively straightforward. Each line gets encoded as a set\n \/\/ of differences from pixels from another line. Pixels are grouped in blocks\n \/\/ of 16 (8 green, 8 red or blue). Each block is encoded in three sections.\n \/\/ First 1 or 4 bits to specify which reference pixels to use, then a section\n \/\/ that specifies for each pixel the number of bits in the difference, then\n \/\/ the actual difference bits\n\n \/\/ Align pump to 16byte boundary\n const auto line_offset = data.getPosition();\n if ((line_offset & 0xf) != 0)\n data.skipBytes(16 - (line_offset & 0xf));\n\n BitPumpMSB32 pump(data);\n\n auto* img = reinterpret_cast<ushort16*>(mRaw->getData(0, row));\n ushort16* img_up = reinterpret_cast<ushort16*>(\n mRaw->getData(0, std::max(0, static_cast<int>(row) - 1)));\n ushort16* img_up2 = reinterpret_cast<ushort16*>(\n mRaw->getData(0, std::max(0, static_cast<int>(row) - 2)));\n\n \/\/ Initialize the motion and diff modes at the start of the line\n uint32 motion = 7;\n \/\/ By default we are not scaling values at all\n int32 scale = 0;\n\n uint32 diffBitsMode[3][2] = {{0}};\n for (auto& i : diffBitsMode)\n i[0] = i[1] = (row == 0 || row == 1) ? 7 : 4;\n\n assert(width >= 16);\n for (uint32 col = 0; col < width; col += 16) {\n if (!(optflags & OptFlags::QP) && !(col & 63)) {\n int32 scalevals[] = {0, -2, 2};\n uint32 i = pump.getBits(2);\n scale = i < 3 ? scale + scalevals[i] : pump.getBits(12);\n }\n\n \/\/ First we figure out which reference pixels mode we're in\n if (optflags & OptFlags::MV)\n motion = pump.getBits(1) ? 3 : 7;\n else if (!pump.getBits(1))\n motion = pump.getBits(3);\n\n if ((row == 0 || row == 1) && (motion != 7))\n ThrowRDE(\"At start of image and motion isn't 7. File corrupted?\");\n\n if (motion == 7) {\n \/\/ The base case, just set all pixels to the previous ones on the same\n \/\/ line If we're at the left edge we just start at the initial value\n for (uint32 i = 0; i < 16; i++)\n img[i] = (col == 0) ? initVal : *(img + i - 2);\n } else {\n \/\/ The complex case, we now need to actually lookup one or two lines\n \/\/ above\n if (row < 2)\n ThrowRDE(\n \"Got a previous line lookup on first two lines. File corrupted?\");\n\n int32 motionOffset[7] = {-4, -2, -2, 0, 0, 2, 4};\n int32 motionDoAverage[7] = {0, 0, 1, 0, 1, 0, 0};\n\n int32 slideOffset = motionOffset[motion];\n int32 doAverage = motionDoAverage[motion];\n\n for (uint32 i = 0; i < 16; i++) {\n ushort16* refpixel;\n\n if ((row + i) & 0x1) \/\/ Red or blue pixels use same color two lines up\n refpixel = img_up2 + i + slideOffset;\n else \/\/ Green pixel N uses Green pixel N from row above (top left or\n \/\/ top right)\n refpixel = img_up + i + slideOffset + (((i % 2) != 0) ? -1 : 1);\n\n \/\/ In some cases we use as reference interpolation of this pixel and\n \/\/ the next\n if (doAverage)\n img[i] = (*refpixel + *(refpixel + 2) + 1) >> 1;\n else\n img[i] = *refpixel;\n }\n }\n\n \/\/ Figure out how many difference bits we have to read for each pixel\n uint32 diffBits[4] = {0};\n if (optflags & OptFlags::SKIP || !pump.getBits(1)) {\n uint32 flags[4];\n for (unsigned int& flag : flags)\n flag = pump.getBits(2);\n\n for (uint32 i = 0; i < 4; i++) {\n \/\/ The color is 0-Green 1-Blue 2-Red\n uint32 colornum = (row % 2 != 0) ? i >> 1 : ((i >> 1) + 2) % 3;\n\n assert(flags[i] <= 3);\n switch (flags[i]) {\n case 0:\n diffBits[i] = diffBitsMode[colornum][0];\n break;\n case 1:\n diffBits[i] = diffBitsMode[colornum][0] + 1;\n break;\n case 2:\n diffBits[i] = diffBitsMode[colornum][0] - 1;\n break;\n case 3:\n diffBits[i] = pump.getBits(4);\n break;\n default:\n __builtin_unreachable();\n }\n\n diffBitsMode[colornum][0] = diffBitsMode[colornum][1];\n diffBitsMode[colornum][1] = diffBits[i];\n\n if (diffBits[i] > bitDepth + 1)\n ThrowRDE(\"Too many difference bits. File corrupted?\");\n }\n }\n\n \/\/ Actually read the differences and write them to the pixels\n for (uint32 i = 0; i < 16; i++) {\n uint32 len = diffBits[i >> 2];\n int32 diff = pump.getBits(len);\n\n \/\/ If the first bit is 1 we need to turn this into a negative number\n if (len != 0 && diff >> (len - 1))\n diff -= (1 << len);\n\n ushort16* value = nullptr;\n \/\/ Apply the diff to pixels 0 2 4 6 8 10 12 14 1 3 5 7 9 11 13 15\n if (row % 2)\n value = &img[((i & 0x7) << 1) + 1 - (i >> 3)];\n else\n value = &img[((i & 0x7) << 1) + (i >> 3)];\n\n diff = diff * (scale * 2 + 1) + scale;\n *value = clampBits(static_cast<int>(*value) + diff, bits);\n }\n\n img += 16;\n img_up += 16;\n img_up2 += 16;\n }\n\n data.skipBytes(pump.getBufferPosition());\n}\n\n} \/\/ namespace rawspeed\n<|endoftext|>"} {"text":"<commit_before>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Copyright 2006 - 2015, Göteborg Bit Factory.\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included\n\/\/ in all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n\/\/ OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n\/\/ THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n\/\/ SOFTWARE.\n\/\/\n\/\/ http:\/\/www.opensource.org\/licenses\/mit-license.php\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include <cmake.h>\n#include <iostream>\n#include <utf8.h>\n#include <test.h>\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nint main (int argc, char** argv)\n{\n UnitTest t (17);\n\n std::string ascii_text = \"This is a test\";\n std::string utf8_text = \"más sábado miércoles\";\n std::string utf8_wide_text = \"改变各种颜色\";\n\n std::string ascii_text_color = \"This \u001b[1mis\u001b[0m a test\";\n std::string utf8_text_color = \"más \u001b[1msábado\u001b[0m miércoles\";\n std::string utf8_wide_text_color = \"改\u001b[1m变各种\u001b[0m颜色\";\n\n \/\/ unsigned int utf8_codepoint (const std::string&);\n t.is ((int) utf8_codepoint (\"\\\\u0020\"), 32, \"\\\\u0020 --> ' '\");\n t.is ((int) utf8_codepoint (\"U+0020\"), 32, \"U+0020 --> ' '\");\n\n \/\/ TODO unsigned int utf8_next_char (const std::string&, std::string::size_type&);\n \/\/ TODO std::string utf8_character (unsigned int);\n \/\/ TODO int utf8_sequence (unsigned int);\n\n \/\/ unsigned int utf8_length (const std::string&);\n t.is ((int) utf8_length (ascii_text), 14, \"ASCII utf8_length\");\n t.is ((int) utf8_length (utf8_text), 20, \"UTF8 utf8_length\");\n t.is ((int) utf8_length (utf8_wide_text), 6, \"UTF8 wide utf8_length\");\n\n \/\/ unsigned int utf8_width (const std::string&);\n t.is ((int) utf8_width (ascii_text), 14, \"ASCII utf8_width\");\n t.is ((int) utf8_width (utf8_text), 20, \"UTF8 utf8_width\");\n t.is ((int) utf8_width (utf8_wide_text), 12, \"UTF8 wide utf8_width\");\n\n \/\/ unsigned int utf8_text_length (const std::string&);\n t.is ((int) utf8_text_length (ascii_text_color), 14, \"ASCII utf8_text_length\");\n t.is ((int) utf8_text_length (utf8_text_color), 20, \"UTF8 utf8_text_length\");\n t.is ((int) utf8_text_length (utf8_wide_text_color), 6, \"UTF8 wide utf8_text_length\");\n\n \/\/ unsigned int utf8_text_width (const std::string&);\n t.is ((int) utf8_text_width (ascii_text_color), 14, \"ASCII utf8_text_width\");\n t.is ((int) utf8_text_width (utf8_text_color), 20, \"UTF8 utf8_text_width\");\n t.is ((int) utf8_text_width (utf8_wide_text_color), 12, \"UTF8 wide utf8_text_width\");\n\n \/\/ const std::string utf8_substr (const std::string&, unsigned int, unsigned int length = 0);\n t.is (utf8_substr (ascii_text, 0, 2), \"Th\", \"ASCII utf8_substr\");\n t.is (utf8_substr (utf8_text, 0, 2), \"má\", \"UTF8 utf8_substr\");\n t.is (utf8_substr (utf8_wide_text, 0, 2), \"改变\", \"UTF8 wide utf8_substr\");\n\n return 0;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n<commit_msg>Tests: Migrated improvements over from Taskwarrior<commit_after>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Copyright 2006 - 2015, Göteborg Bit Factory.\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included\n\/\/ in all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n\/\/ OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n\/\/ THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n\/\/ SOFTWARE.\n\/\/\n\/\/ http:\/\/www.opensource.org\/licenses\/mit-license.php\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include <cmake.h>\n#include <utf8.h>\n#include <test.h>\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nint main (int argc, char** argv)\n{\n UnitTest t (33);\n\n std::string ascii_text = \"This is a test\";\n std::string utf8_text = \"más sábado miércoles\";\n std::string utf8_wide_text = \"改变各种颜色\";\n\n std::string ascii_text_color = \"This \u001b[1mis\u001b[0m a test\";\n std::string utf8_text_color = \"más \u001b[1msábado\u001b[0m miércoles\";\n std::string utf8_wide_text_color = \"改\u001b[1m变各种\u001b[0m颜色\";\n\n \/\/ unsigned int utf8_codepoint (const std::string&);\n t.is ((int) utf8_codepoint (\"\\\\u0020\"), 32, \"\\\\u0020 --> ' '\");\n t.is ((int) utf8_codepoint (\"U+0020\"), 32, \"U+0020 --> ' '\");\n\n \/\/ TODO unsigned int utf8_next_char (const std::string&, std::string::size_type&);\n \/\/ TODO std::string utf8_character (unsigned int);\n \/\/ TODO int utf8_sequence (unsigned int);\n\n \/\/ unsigned int utf8_length (const std::string&);\n t.is ((int) utf8_length (ascii_text), 14, \"ASCII utf8_length\");\n t.is ((int) utf8_length (utf8_text), 20, \"UTF8 utf8_length\");\n t.is ((int) utf8_length (utf8_wide_text), 6, \"UTF8 wide utf8_length\");\n\n \/\/ unsigned int utf8_width (const std::string&);\n t.is ((int) utf8_width (ascii_text), 14, \"ASCII utf8_width\");\n t.is ((int) utf8_width (utf8_text), 20, \"UTF8 utf8_width\");\n t.is ((int) utf8_width (utf8_wide_text), 12, \"UTF8 wide utf8_width\");\n\n \/\/ unsigned int utf8_text_length (const std::string&);\n t.is ((int) utf8_text_length (ascii_text_color), 14, \"ASCII utf8_text_length\");\n t.is ((int) utf8_text_length (utf8_text_color), 20, \"UTF8 utf8_text_length\");\n t.is ((int) utf8_text_length (utf8_wide_text_color), 6, \"UTF8 wide utf8_text_length\");\n\n \/\/ unsigned int utf8_text_width (const std::string&);\n t.is ((int) utf8_text_width (ascii_text_color), 14, \"ASCII utf8_text_width\");\n t.is ((int) utf8_text_width (utf8_text_color), 20, \"UTF8 utf8_text_width\");\n t.is ((int) utf8_text_width (utf8_wide_text_color), 12, \"UTF8 wide utf8_text_width\");\n\n \/\/ const std::string utf8_substr (const std::string&, unsigned int, unsigned int length = 0);\n t.is (utf8_substr (ascii_text, 0, 2), \"Th\", \"ASCII utf8_substr\");\n t.is (utf8_substr (utf8_text, 0, 2), \"má\", \"UTF8 utf8_substr\");\n t.is (utf8_substr (utf8_wide_text, 0, 2), \"改变\", \"UTF8 wide utf8_substr\");\n\n \/\/ int mk_wcwidth (wchar_t);\n t.is (mk_wcwidth ('a'), 1, \"mk_wcwidth U+0061 --> 1\");\n t.is (mk_wcwidth (0x5149), 2, \"mk_wcwidth U+5149 --> 2\");\n t.is (mk_wcwidth (0x9a8c), 2, \"mk_wcwidth U+9a8c --> 2\");\n t.is (mk_wcwidth (0x4e70), 2, \"mk_wcwidth U+4e70 --> 2\");\n t.is (mk_wcwidth (0x94b1), 2, \"mk_wcwidth U+94b1 --> 2\");\n t.is (mk_wcwidth (0x5305), 2, \"mk_wcwidth U+5305 --> 2\");\n t.is (mk_wcwidth (0x91cd), 2, \"mk_wcwidth U+91cd --> 2\");\n t.is (mk_wcwidth (0x65b0), 2, \"mk_wcwidth U+65b0 --> 2\");\n t.is (mk_wcwidth (0x8bbe), 2, \"mk_wcwidth U+8bbe --> 2\");\n t.is (mk_wcwidth (0x8ba1), 2, \"mk_wcwidth U+8ba1 --> 2\");\n t.is (mk_wcwidth (0x5411), 2, \"mk_wcwidth U+5411 --> 2\");\n t.is (mk_wcwidth (0x4e0a), 2, \"mk_wcwidth U+4e0a --> 2\");\n t.is (mk_wcwidth (0x4e0b), 2, \"mk_wcwidth U+4e0b --> 2\");\n t.is (mk_wcwidth (0x7bad), 2, \"mk_wcwidth U+7bad --> 2\");\n t.is (mk_wcwidth (0x5934), 2, \"mk_wcwidth U+5934 --> 2\");\n t.is (mk_wcwidth (0xff0c), 2, \"mk_wcwidth U+ff0c --> 2\"); \/\/ comma\n\n return 0;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n<|endoftext|>"} {"text":"<commit_before>\/*\n For more information, please see: http:\/\/software.sci.utah.edu\n\n The MIT License\n\n Copyright (c) 2012 Scientific Computing and Imaging Institute,\n University of Utah.\n\n License for the specific language governing rights and limitations under\n Permission is hereby granted, free of charge, to any person obtaining a\n copy of this software and associated documentation files (the \"Software\"),\n to deal in the Software without restriction, including without limitation\n the rights to use, copy, modify, merge, publish, distribute, sublicense,\n and\/or sell copies of the Software, and to permit persons to whom the\n Software is furnished to do so, subject to the following conditions:\n\n The above copyright notice and this permission notice shall be included\n in all copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n DEALINGS IN THE SOFTWARE.\n*\/\n\n#include <iostream>\n#include <boost\/thread.hpp>\n#include <Dataflow\/Engine\/Controller\/NetworkEditorController.h>\n\n#include <Dataflow\/Network\/Connection.h>\n#include <Dataflow\/Network\/Network.h>\n#include <Dataflow\/Network\/ModuleDescription.h>\n#include <Dataflow\/Network\/Module.h>\n#include <Dataflow\/Serialization\/Network\/NetworkXMLSerializer.h>\n#include <Dataflow\/Serialization\/Network\/NetworkDescriptionSerialization.h>\n#ifdef BUILD_WITH_PYTHON\n#include <Dataflow\/Engine\/Python\/NetworkEditorPythonAPI.h>\n#include <Dataflow\/Engine\/Controller\/PythonImpl.h>\n#endif\n\n\n#include <log4cpp\/Category.hh>\n#include <log4cpp\/Appender.hh>\n#include <log4cpp\/OstreamAppender.hh>\n#include <log4cpp\/FileAppender.hh>\n#include <log4cpp\/Layout.hh>\n#include <log4cpp\/BasicLayout.hh>\n#include <log4cpp\/PatternLayout.hh>\n#include <log4cpp\/Priority.hh>\n\nusing namespace SCIRun;\nusing namespace SCIRun::Dataflow::Engine;\nusing namespace SCIRun::Dataflow::Networks;\n\nNetworkEditorController::NetworkEditorController(ModuleFactoryHandle mf, ModuleStateFactoryHandle sf, ExecutionStrategyFactoryHandle executorFactory, ModulePositionEditor* mpg) : \n theNetwork_(new Network(mf, sf)),\n moduleFactory_(mf), \n stateFactory_(sf), \n executorFactory_(executorFactory),\n modulePositionEditor_(mpg)\n{\n \/\/TODO should this class own the network or just keep a reference?\n\n#ifdef BUILD_WITH_PYTHON\n NetworkEditorPythonAPI::setImpl(boost::make_shared<PythonImpl>(*this));\n#endif\n\n log4cpp::Appender *appender1 = new log4cpp::OstreamAppender(\"console\", &std::cout);\n auto layout1 = new log4cpp::PatternLayout();\n layout1->setConversionPattern(\"%d{%Y-%m-%d %H:%M:%S.%l} [%p] %m%n\");\n appender1->setLayout(layout1);\n\n log4cpp::Appender *appender2 = new log4cpp::FileAppender(\"default\", \"scirun5.log\");\n auto layout2 = new log4cpp::PatternLayout();\n layout2->setConversionPattern(\"%d{%Y-%m-%d %H:%M:%S.%l} [%p] %m%n\");\n appender2->setLayout(layout2);\n\n log4cpp::Category& root = log4cpp::Category::getRoot();\n \/\/root.setPriority(log4cpp::Priority::WARN);\n root.addAppender(appender1);\n root.addAppender(appender2);\n}\n\nNetworkEditorController::NetworkEditorController(SCIRun::Dataflow::Networks::NetworkHandle network, ExecutionStrategyFactoryHandle executorFactory, ModulePositionEditor* mpg)\n : theNetwork_(network), executorFactory_(executorFactory), modulePositionEditor_(mpg)\n{\n}\n\nModuleHandle NetworkEditorController::addModule(const std::string& moduleName)\n{\n auto realModule = addModuleImpl(moduleName);\n \/*emit*\/ moduleAdded_(moduleName, realModule);\n printNetwork();\n return realModule;\n}\n\nModuleHandle NetworkEditorController::addModuleImpl(const std::string& moduleName)\n{\n \/\/TODO: should pass in entire info struct\n ModuleLookupInfo info;\n info.module_name_ = moduleName;\n ModuleHandle realModule = theNetwork_->add_module(info);\n return realModule;\n}\n\nvoid NetworkEditorController::removeModule(const ModuleId& id)\n{\n theNetwork_->remove_module(id);\n \/\/before or after?\n \/\/ deciding on after: ProvenanceWindow\/Manager wants the state *after* removal.\n \/*emit*\/ moduleRemoved_(id);\n \n printNetwork();\n}\n\nModuleHandle NetworkEditorController::duplicateModule(const ModuleHandle& module)\n{\n ENSURE_NOT_NULL(module, \"Cannot duplicate null module\");\n ModuleId id(module->get_id());\n auto newModule = addModuleImpl(id.name_);\n newModule->set_state(module->get_state()->clone());\n moduleAdded_(id.name_, newModule);\n\n \/\/TODO: probably a pretty poor way to deal with what I think is a race condition with signaling the GUI to place the module widget.\n boost::this_thread::sleep(boost::posix_time::milliseconds(1));\n \n for (size_t i = 0; i < module->num_input_ports(); ++i)\n {\n auto input = module->get_input_port(i);\n if (input->nconnections() == 1)\n {\n auto conn = input->connection(0);\n auto source = conn->oport_;\n requestConnection(source.get(), newModule->get_input_port(i).get());\n }\n }\n \n return newModule;\n}\n\nvoid NetworkEditorController::printNetwork() const\n{\n \/\/TODO: and make this switchable\n if (false)\n {\n \/\/TODO: use real logger here\n if (theNetwork_)\n std::cout << theNetwork_->toString() << std::endl;\n }\n}\n\nvoid NetworkEditorController::requestConnection(const SCIRun::Dataflow::Networks::PortDescriptionInterface* from, const SCIRun::Dataflow::Networks::PortDescriptionInterface* to)\n{\n ENSURE_NOT_NULL(from, \"from port\");\n ENSURE_NOT_NULL(to, \"to port\");\n\n auto out = from->isInput() ? to : from; \n auto in = from->isInput() ? from : to; \n\n ConnectionDescription desc(\n OutgoingConnectionDescription(out->getUnderlyingModuleId(), out->getIndex()), \n IncomingConnectionDescription(in->getUnderlyingModuleId(), in->getIndex()));\n\n PortConnectionDeterminer q;\n if (q.canBeConnected(*from, *to))\n {\n ConnectionId id = theNetwork_->connect(ConnectionOutputPort(theNetwork_->lookupModule(desc.out_.moduleId_), desc.out_.port_),\n ConnectionInputPort(theNetwork_->lookupModule(desc.in_.moduleId_), desc.in_.port_));\n if (!id.id_.empty())\n connectionAdded_(desc);\n \n printNetwork();\n }\n else\n {\n \/\/TODO: use real logger\n std::cout << \"Invalid Connection request: input port is full, or ports are different datatype or same i\/o type, or on the same module.\" << std::endl;\n invalidConnection_(desc);\n }\n}\n\nvoid NetworkEditorController::removeConnection(const ConnectionId& id)\n{\n if (theNetwork_->disconnect(id))\n connectionRemoved_(id);\n printNetwork();\n}\n\nboost::signals2::connection NetworkEditorController::connectModuleAdded(const ModuleAddedSignalType::slot_type& subscriber)\n{\n return moduleAdded_.connect(subscriber);\n}\n\nboost::signals2::connection NetworkEditorController::connectModuleRemoved(const ModuleRemovedSignalType::slot_type& subscriber)\n{\n return moduleRemoved_.connect(subscriber);\n}\n\nboost::signals2::connection NetworkEditorController::connectConnectionAdded(const ConnectionAddedSignalType::slot_type& subscriber)\n{\n return connectionAdded_.connect(subscriber);\n}\n\nboost::signals2::connection NetworkEditorController::connectConnectionRemoved(const ConnectionRemovedSignalType::slot_type& subscriber)\n{\n return connectionRemoved_.connect(subscriber);\n}\n\nboost::signals2::connection NetworkEditorController::connectInvalidConnection(const InvalidConnectionSignalType::slot_type& subscriber)\n{\n return invalidConnection_.connect(subscriber);\n}\n\nboost::signals2::connection NetworkEditorController::connectNetworkExecutionStarts(const ExecuteAllStartsSignalType::slot_type& subscriber)\n{\n return ExecutionStrategy::connectNetworkExecutionStarts(subscriber);\n}\n\nboost::signals2::connection NetworkEditorController::connectNetworkExecutionFinished(const ExecuteAllFinishesSignalType::slot_type& subscriber)\n{\n return ExecutionStrategy::connectNetworkExecutionFinished(subscriber);\n}\n\nNetworkFileHandle NetworkEditorController::saveNetwork() const\n{\n NetworkToXML conv(modulePositionEditor_);\n return conv.to_xml_data(theNetwork_);\n}\n\nvoid NetworkEditorController::loadNetwork(const NetworkFileHandle& xml)\n{\n if (xml)\n {\n NetworkXMLConverter conv(moduleFactory_, stateFactory_);\n theNetwork_ = conv.from_xml_data(xml->network);\n for (size_t i = 0; i < theNetwork_->nmodules(); ++i)\n {\n ModuleHandle module = theNetwork_->module(i);\n moduleAdded_(module->get_module_name(), module);\n }\n BOOST_FOREACH(const ConnectionDescription& cd, theNetwork_->connections())\n {\n ConnectionId id = ConnectionId::create(cd);\n connectionAdded_(cd);\n }\n if (modulePositionEditor_)\n modulePositionEditor_->moveModules(xml->modulePositions);\n else\n std::cout << \"module position editor is null\" << std::endl;\n }\n}\n\nvoid NetworkEditorController::clear()\n{\n \/\/std::cout << \"NetworkEditorController::clear()\" << std::endl;\n}\n\nvoid NetworkEditorController::executeAll(const ExecutableLookup* lookup)\n{\n if (!currentExecutor_)\n currentExecutor_ = executorFactory_->create(ExecutionStrategy::BASIC_PARALLEL); \/\/TODO: read some setting for default executor type\n\n currentExecutor_->executeAll(*theNetwork_, lookup ? *lookup : *theNetwork_);\n}\n\nNetworkHandle NetworkEditorController::getNetwork() const \n{\n return theNetwork_;\n}\n\nNetworkGlobalSettings& NetworkEditorController::getSettings() \n{\n return theNetwork_->settings();\n}\n\nvoid NetworkEditorController::setExecutorType(int type)\n{\n currentExecutor_ = executorFactory_->create((ExecutionStrategy::Type)type);\n}\n\n<commit_msg>There seems to be a log4cpp parsing bug on OS X 10.7, where even the default pattern specified in the log4cpp::PatternLayout class is failing. This is a preliminary attempt to report and recover, allowing the GUI to start up.<commit_after>\/*\n For more information, please see: http:\/\/software.sci.utah.edu\n\n The MIT License\n\n Copyright (c) 2012 Scientific Computing and Imaging Institute,\n University of Utah.\n\n License for the specific language governing rights and limitations under\n Permission is hereby granted, free of charge, to any person obtaining a\n copy of this software and associated documentation files (the \"Software\"),\n to deal in the Software without restriction, including without limitation\n the rights to use, copy, modify, merge, publish, distribute, sublicense,\n and\/or sell copies of the Software, and to permit persons to whom the\n Software is furnished to do so, subject to the following conditions:\n\n The above copyright notice and this permission notice shall be included\n in all copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n DEALINGS IN THE SOFTWARE.\n*\/\n\n#include <iostream>\n#include <boost\/thread.hpp>\n#include <Dataflow\/Engine\/Controller\/NetworkEditorController.h>\n\n#include <Dataflow\/Network\/Connection.h>\n#include <Dataflow\/Network\/Network.h>\n#include <Dataflow\/Network\/ModuleDescription.h>\n#include <Dataflow\/Network\/Module.h>\n#include <Dataflow\/Serialization\/Network\/NetworkXMLSerializer.h>\n#include <Dataflow\/Serialization\/Network\/NetworkDescriptionSerialization.h>\n#ifdef BUILD_WITH_PYTHON\n#include <Dataflow\/Engine\/Python\/NetworkEditorPythonAPI.h>\n#include <Dataflow\/Engine\/Controller\/PythonImpl.h>\n#endif\n\n\n#include <log4cpp\/Category.hh>\n#include <log4cpp\/Appender.hh>\n#include <log4cpp\/OstreamAppender.hh>\n#include <log4cpp\/FileAppender.hh>\n#include <log4cpp\/Layout.hh>\n#include <log4cpp\/BasicLayout.hh>\n#include <log4cpp\/PatternLayout.hh>\n#include <log4cpp\/Priority.hh>\n\nusing namespace SCIRun;\nusing namespace SCIRun::Dataflow::Engine;\nusing namespace SCIRun::Dataflow::Networks;\n\nNetworkEditorController::NetworkEditorController(ModuleFactoryHandle mf, ModuleStateFactoryHandle sf, ExecutionStrategyFactoryHandle executorFactory, ModulePositionEditor* mpg) : \n theNetwork_(new Network(mf, sf)),\n moduleFactory_(mf), \n stateFactory_(sf), \n executorFactory_(executorFactory),\n modulePositionEditor_(mpg)\n{\n \/\/TODO should this class own the network or just keep a reference?\n\n#ifdef BUILD_WITH_PYTHON\n NetworkEditorPythonAPI::setImpl(boost::make_shared<PythonImpl>(*this));\n#endif\n\n std::string pattern(\"%d{%Y-%m-%d %H:%M:%S.%l} [%p] %m%n\");\n\n log4cpp::Appender *appender1 = new log4cpp::OstreamAppender(\"console\", &std::cout);\n auto layout1 = new log4cpp::PatternLayout();\n std::string backupPattern1 = layout1->getConversionPattern();\n try\n {\n layout1->setConversionPattern(pattern);\n }\n catch (log4cpp::ConfigureFailure& exception)\n {\n \/\/ TODO: log?\n std::cerr << \"Caught ConfigureFailure exception: \" << exception.what() << std::endl\n << \"Restoring original pattern: (\" << backupPattern1 << \")\" << std::endl;\n layout1->setConversionPattern(backupPattern1);\n }\n appender1->setLayout(layout1);\n\n log4cpp::Appender *appender2 = new log4cpp::FileAppender(\"default\", \"scirun5.log\");\n auto layout2 = new log4cpp::PatternLayout();\n std::string backupPattern2 = layout1->getConversionPattern();\n try\n {\n layout2->setConversionPattern(pattern);\n }\n catch (log4cpp::ConfigureFailure& exception)\n {\n \/\/ TODO: log?\n std::cerr << \"Caught ConfigureFailure exception: \" << exception.what() << std::endl\n << \"Restoring original pattern: (\" << backupPattern2 << \")\" << std::endl;\n layout2->setConversionPattern(backupPattern2);\n }\n appender2->setLayout(layout2);\n\n log4cpp::Category& root = log4cpp::Category::getRoot();\n \/\/root.setPriority(log4cpp::Priority::WARN);\n root.addAppender(appender1);\n root.addAppender(appender2);\n}\n\nNetworkEditorController::NetworkEditorController(SCIRun::Dataflow::Networks::NetworkHandle network, ExecutionStrategyFactoryHandle executorFactory, ModulePositionEditor* mpg)\n : theNetwork_(network), executorFactory_(executorFactory), modulePositionEditor_(mpg)\n{\n}\n\nModuleHandle NetworkEditorController::addModule(const std::string& moduleName)\n{\n auto realModule = addModuleImpl(moduleName);\n \/*emit*\/ moduleAdded_(moduleName, realModule);\n printNetwork();\n return realModule;\n}\n\nModuleHandle NetworkEditorController::addModuleImpl(const std::string& moduleName)\n{\n \/\/TODO: should pass in entire info struct\n ModuleLookupInfo info;\n info.module_name_ = moduleName;\n ModuleHandle realModule = theNetwork_->add_module(info);\n return realModule;\n}\n\nvoid NetworkEditorController::removeModule(const ModuleId& id)\n{\n theNetwork_->remove_module(id);\n \/\/before or after?\n \/\/ deciding on after: ProvenanceWindow\/Manager wants the state *after* removal.\n \/*emit*\/ moduleRemoved_(id);\n \n printNetwork();\n}\n\nModuleHandle NetworkEditorController::duplicateModule(const ModuleHandle& module)\n{\n ENSURE_NOT_NULL(module, \"Cannot duplicate null module\");\n ModuleId id(module->get_id());\n auto newModule = addModuleImpl(id.name_);\n newModule->set_state(module->get_state()->clone());\n moduleAdded_(id.name_, newModule);\n\n \/\/TODO: probably a pretty poor way to deal with what I think is a race condition with signaling the GUI to place the module widget.\n boost::this_thread::sleep(boost::posix_time::milliseconds(1));\n \n for (size_t i = 0; i < module->num_input_ports(); ++i)\n {\n auto input = module->get_input_port(i);\n if (input->nconnections() == 1)\n {\n auto conn = input->connection(0);\n auto source = conn->oport_;\n requestConnection(source.get(), newModule->get_input_port(i).get());\n }\n }\n \n return newModule;\n}\n\nvoid NetworkEditorController::printNetwork() const\n{\n \/\/TODO: and make this switchable\n if (false)\n {\n \/\/TODO: use real logger here\n if (theNetwork_)\n std::cout << theNetwork_->toString() << std::endl;\n }\n}\n\nvoid NetworkEditorController::requestConnection(const SCIRun::Dataflow::Networks::PortDescriptionInterface* from, const SCIRun::Dataflow::Networks::PortDescriptionInterface* to)\n{\n ENSURE_NOT_NULL(from, \"from port\");\n ENSURE_NOT_NULL(to, \"to port\");\n\n auto out = from->isInput() ? to : from; \n auto in = from->isInput() ? from : to; \n\n ConnectionDescription desc(\n OutgoingConnectionDescription(out->getUnderlyingModuleId(), out->getIndex()), \n IncomingConnectionDescription(in->getUnderlyingModuleId(), in->getIndex()));\n\n PortConnectionDeterminer q;\n if (q.canBeConnected(*from, *to))\n {\n ConnectionId id = theNetwork_->connect(ConnectionOutputPort(theNetwork_->lookupModule(desc.out_.moduleId_), desc.out_.port_),\n ConnectionInputPort(theNetwork_->lookupModule(desc.in_.moduleId_), desc.in_.port_));\n if (!id.id_.empty())\n connectionAdded_(desc);\n \n printNetwork();\n }\n else\n {\n \/\/TODO: use real logger\n std::cout << \"Invalid Connection request: input port is full, or ports are different datatype or same i\/o type, or on the same module.\" << std::endl;\n invalidConnection_(desc);\n }\n}\n\nvoid NetworkEditorController::removeConnection(const ConnectionId& id)\n{\n if (theNetwork_->disconnect(id))\n connectionRemoved_(id);\n printNetwork();\n}\n\nboost::signals2::connection NetworkEditorController::connectModuleAdded(const ModuleAddedSignalType::slot_type& subscriber)\n{\n return moduleAdded_.connect(subscriber);\n}\n\nboost::signals2::connection NetworkEditorController::connectModuleRemoved(const ModuleRemovedSignalType::slot_type& subscriber)\n{\n return moduleRemoved_.connect(subscriber);\n}\n\nboost::signals2::connection NetworkEditorController::connectConnectionAdded(const ConnectionAddedSignalType::slot_type& subscriber)\n{\n return connectionAdded_.connect(subscriber);\n}\n\nboost::signals2::connection NetworkEditorController::connectConnectionRemoved(const ConnectionRemovedSignalType::slot_type& subscriber)\n{\n return connectionRemoved_.connect(subscriber);\n}\n\nboost::signals2::connection NetworkEditorController::connectInvalidConnection(const InvalidConnectionSignalType::slot_type& subscriber)\n{\n return invalidConnection_.connect(subscriber);\n}\n\nboost::signals2::connection NetworkEditorController::connectNetworkExecutionStarts(const ExecuteAllStartsSignalType::slot_type& subscriber)\n{\n return ExecutionStrategy::connectNetworkExecutionStarts(subscriber);\n}\n\nboost::signals2::connection NetworkEditorController::connectNetworkExecutionFinished(const ExecuteAllFinishesSignalType::slot_type& subscriber)\n{\n return ExecutionStrategy::connectNetworkExecutionFinished(subscriber);\n}\n\nNetworkFileHandle NetworkEditorController::saveNetwork() const\n{\n NetworkToXML conv(modulePositionEditor_);\n return conv.to_xml_data(theNetwork_);\n}\n\nvoid NetworkEditorController::loadNetwork(const NetworkFileHandle& xml)\n{\n if (xml)\n {\n NetworkXMLConverter conv(moduleFactory_, stateFactory_);\n theNetwork_ = conv.from_xml_data(xml->network);\n for (size_t i = 0; i < theNetwork_->nmodules(); ++i)\n {\n ModuleHandle module = theNetwork_->module(i);\n moduleAdded_(module->get_module_name(), module);\n }\n BOOST_FOREACH(const ConnectionDescription& cd, theNetwork_->connections())\n {\n ConnectionId id = ConnectionId::create(cd);\n connectionAdded_(cd);\n }\n if (modulePositionEditor_)\n modulePositionEditor_->moveModules(xml->modulePositions);\n else\n std::cout << \"module position editor is null\" << std::endl;\n }\n}\n\nvoid NetworkEditorController::clear()\n{\n \/\/std::cout << \"NetworkEditorController::clear()\" << std::endl;\n}\n\nvoid NetworkEditorController::executeAll(const ExecutableLookup* lookup)\n{\n if (!currentExecutor_)\n currentExecutor_ = executorFactory_->create(ExecutionStrategy::BASIC_PARALLEL); \/\/TODO: read some setting for default executor type\n\n currentExecutor_->executeAll(*theNetwork_, lookup ? *lookup : *theNetwork_);\n}\n\nNetworkHandle NetworkEditorController::getNetwork() const \n{\n return theNetwork_;\n}\n\nNetworkGlobalSettings& NetworkEditorController::getSettings() \n{\n return theNetwork_->settings();\n}\n\nvoid NetworkEditorController::setExecutorType(int type)\n{\n currentExecutor_ = executorFactory_->create((ExecutionStrategy::Type)type);\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ $Id$\n\/\/***************************************************************************\n\/\/ File:\n\/\/\tMachineInstr.cpp\n\/\/ \n\/\/ Purpose:\n\/\/\t\n\/\/ \n\/\/ Strategy:\n\/\/ \n\/\/ History:\n\/\/\t7\/2\/01\t - Vikram Adve - Created\n\/\/**************************************************************************\/\n\n#include \"llvm\/CodeGen\/MachineInstr.h\"\n#include \"llvm\/Value.h\"\n#include <iostream>\nusing std::cerr;\n\n\n\/\/************************ Class Implementations **************************\/\n\n\/\/ Constructor for instructions with fixed #operands (nearly all)\nMachineInstr::MachineInstr(MachineOpCode _opCode,\n\t\t\t OpCodeMask _opCodeMask)\n : opCode(_opCode),\n opCodeMask(_opCodeMask),\n operands(TargetInstrDescriptors[_opCode].numOperands)\n{\n assert(TargetInstrDescriptors[_opCode].numOperands >= 0);\n}\n\n\/\/ Constructor for instructions with variable #operands\nMachineInstr::MachineInstr(MachineOpCode _opCode,\n\t\t\t unsigned\t numOperands,\n\t\t\t OpCodeMask _opCodeMask)\n : opCode(_opCode),\n opCodeMask(_opCodeMask),\n operands(numOperands)\n{\n}\n\nvoid\nMachineInstr::SetMachineOperandVal(unsigned int i,\n MachineOperand::MachineOperandType opType,\n Value* _val,\n bool isdef=false,\n bool isDefAndUse=false)\n{\n assert(i < operands.size());\n operands[i].Initialize(opType, _val);\n operands[i].isDef = isdef ||\n TargetInstrDescriptors[opCode].resultPos == (int) i;\n operands[i].isDefAndUse = isDefAndUse;\n}\n\nvoid\nMachineInstr::SetMachineOperandConst(unsigned int i,\n\t\t\t\tMachineOperand::MachineOperandType operandType,\n int64_t intValue)\n{\n assert(i < operands.size());\n assert(TargetInstrDescriptors[opCode].resultPos != (int) i &&\n \"immed. constant cannot be defined\");\n operands[i].InitializeConst(operandType, intValue);\n operands[i].isDef = false;\n operands[i].isDefAndUse = false;\n}\n\nvoid\nMachineInstr::SetMachineOperandReg(unsigned int i,\n int regNum,\n bool isdef=false,\n bool isDefAndUse=false,\n bool isCCReg=false)\n{\n assert(i < operands.size());\n operands[i].InitializeReg(regNum, isCCReg);\n operands[i].isDef = isdef ||\n TargetInstrDescriptors[opCode].resultPos == (int) i;\n operands[i].isDefAndUse = isDefAndUse;\n regsUsed.insert(regNum);\n}\n\nvoid\nMachineInstr::SetRegForOperand(unsigned i, int regNum)\n{\n operands[i].setRegForValue(regNum);\n regsUsed.insert(regNum);\n}\n\n\nvoid\nMachineInstr::dump() const \n{\n cerr << \" \" << *this;\n}\n\nstatic inline std::ostream &OutputValue(std::ostream &os,\n const Value* val)\n{\n os << \"(val \";\n if (val && val->hasName())\n return os << val->getName();\n else\n return os << (void*) val; \/\/ print address only\n os << \")\";\n}\n\nstd::ostream &operator<<(std::ostream& os, const MachineInstr& minstr)\n{\n os << TargetInstrDescriptors[minstr.opCode].opCodeString;\n \n for (unsigned i=0, N=minstr.getNumOperands(); i < N; i++) {\n os << \"\\t\" << minstr.getOperand(i);\n if( minstr.operandIsDefined(i) ) \n os << \"*\";\n if( minstr.operandIsDefinedAndUsed(i) ) \n os << \"*\";\n }\n \n \/\/ code for printing implict references\n unsigned NumOfImpRefs = minstr.getNumImplicitRefs();\n if( NumOfImpRefs > 0 ) {\n os << \"\\tImplicit: \";\n for(unsigned z=0; z < NumOfImpRefs; z++) {\n OutputValue(os, minstr.getImplicitRef(z)); \n if( minstr.implicitRefIsDefined(z)) os << \"*\";\n if( minstr.implicitRefIsDefinedAndUsed(z)) os << \"*\";\n os << \"\\t\";\n }\n }\n \n return os << \"\\n\";\n}\n\nstatic inline std::ostream &OutputOperand(std::ostream &os,\n const MachineOperand &mop)\n{\n Value* val;\n switch (mop.getOperandType())\n {\n case MachineOperand::MO_CCRegister:\n case MachineOperand::MO_VirtualRegister:\n return OutputValue(os, mop.getVRegValue());\n case MachineOperand::MO_MachineRegister:\n return os << \"(\" << mop.getMachineRegNum() << \")\";\n default:\n assert(0 && \"Unknown operand type\");\n return os;\n }\n}\n\nstd::ostream &operator<<(std::ostream &os, const MachineOperand &mop)\n{\n switch(mop.opType)\n {\n case MachineOperand::MO_VirtualRegister:\n case MachineOperand::MO_MachineRegister:\n os << \"%reg\";\n return OutputOperand(os, mop);\n case MachineOperand::MO_CCRegister:\n os << \"%ccreg\";\n return OutputOperand(os, mop);\n case MachineOperand::MO_SignExtendedImmed:\n return os << (long)mop.immedVal;\n case MachineOperand::MO_UnextendedImmed:\n return os << (long)mop.immedVal;\n case MachineOperand::MO_PCRelativeDisp:\n {\n const Value* opVal = mop.getVRegValue();\n bool isLabel = isa<Function>(opVal) || isa<BasicBlock>(opVal);\n os << \"%disp(\" << (isLabel? \"label \" : \"addr-of-val \");\n if (opVal->hasName())\n os << opVal->getName();\n else\n os << (const void*) opVal;\n return os << \")\";\n }\n default:\n assert(0 && \"Unrecognized operand type\");\n break;\n }\n \n return os;\n}\n<commit_msg>Add support for marking each operand as a %hh, %hm, %lm or %lo. Represent previous bools and these ones with flags in a single byte per operand.<commit_after>\/\/ $Id$\n\/\/***************************************************************************\n\/\/ File:\n\/\/\tMachineInstr.cpp\n\/\/ \n\/\/ Purpose:\n\/\/\t\n\/\/ \n\/\/ Strategy:\n\/\/ \n\/\/ History:\n\/\/\t7\/2\/01\t - Vikram Adve - Created\n\/\/**************************************************************************\/\n\n#include \"llvm\/CodeGen\/MachineInstr.h\"\n#include \"llvm\/Value.h\"\n#include <iostream>\nusing std::cerr;\n\n\n\/\/************************ Class Implementations **************************\/\n\n\/\/ Constructor for instructions with fixed #operands (nearly all)\nMachineInstr::MachineInstr(MachineOpCode _opCode,\n\t\t\t OpCodeMask _opCodeMask)\n : opCode(_opCode),\n opCodeMask(_opCodeMask),\n operands(TargetInstrDescriptors[_opCode].numOperands)\n{\n assert(TargetInstrDescriptors[_opCode].numOperands >= 0);\n}\n\n\/\/ Constructor for instructions with variable #operands\nMachineInstr::MachineInstr(MachineOpCode _opCode,\n\t\t\t unsigned\t numOperands,\n\t\t\t OpCodeMask _opCodeMask)\n : opCode(_opCode),\n opCodeMask(_opCodeMask),\n operands(numOperands)\n{\n}\n\nvoid\nMachineInstr::SetMachineOperandVal(unsigned int i,\n MachineOperand::MachineOperandType opType,\n Value* _val,\n bool isdef=false,\n bool isDefAndUse=false)\n{\n assert(i < operands.size());\n operands[i].Initialize(opType, _val);\n if (isdef || TargetInstrDescriptors[opCode].resultPos == (int) i)\n operands[i].markDef();\n if (isDefAndUse)\n operands[i].markDefAndUse();\n}\n\nvoid\nMachineInstr::SetMachineOperandConst(unsigned int i,\n\t\t\t\tMachineOperand::MachineOperandType operandType,\n int64_t intValue)\n{\n assert(i < operands.size());\n assert(TargetInstrDescriptors[opCode].resultPos != (int) i &&\n \"immed. constant cannot be defined\");\n operands[i].InitializeConst(operandType, intValue);\n}\n\nvoid\nMachineInstr::SetMachineOperandReg(unsigned int i,\n int regNum,\n bool isdef=false,\n bool isDefAndUse=false,\n bool isCCReg=false)\n{\n assert(i < operands.size());\n operands[i].InitializeReg(regNum, isCCReg);\n if (isdef || TargetInstrDescriptors[opCode].resultPos == (int) i)\n operands[i].markDef();\n if (isDefAndUse)\n operands[i].markDefAndUse();\n regsUsed.insert(regNum);\n}\n\nvoid\nMachineInstr::SetRegForOperand(unsigned i, int regNum)\n{\n operands[i].setRegForValue(regNum);\n regsUsed.insert(regNum);\n}\n\n\nvoid\nMachineInstr::dump() const \n{\n cerr << \" \" << *this;\n}\n\nstatic inline std::ostream &OutputValue(std::ostream &os,\n const Value* val)\n{\n os << \"(val \";\n if (val && val->hasName())\n return os << val->getName() << \")\";\n else\n return os << (void*) val << \")\"; \/\/ print address only\n}\n\nstd::ostream &operator<<(std::ostream& os, const MachineInstr& minstr)\n{\n os << TargetInstrDescriptors[minstr.opCode].opCodeString;\n \n for (unsigned i=0, N=minstr.getNumOperands(); i < N; i++) {\n os << \"\\t\" << minstr.getOperand(i);\n if( minstr.operandIsDefined(i) ) \n os << \"*\";\n if( minstr.operandIsDefinedAndUsed(i) ) \n os << \"*\";\n }\n \n \/\/ code for printing implict references\n unsigned NumOfImpRefs = minstr.getNumImplicitRefs();\n if( NumOfImpRefs > 0 ) {\n os << \"\\tImplicit: \";\n for(unsigned z=0; z < NumOfImpRefs; z++) {\n OutputValue(os, minstr.getImplicitRef(z)); \n if( minstr.implicitRefIsDefined(z)) os << \"*\";\n if( minstr.implicitRefIsDefinedAndUsed(z)) os << \"*\";\n os << \"\\t\";\n }\n }\n \n return os << \"\\n\";\n}\n\nstd::ostream &operator<<(std::ostream &os, const MachineOperand &mop)\n{\n if (mop.opHiBits32())\n os << \"%lm(\";\n else if (mop.opLoBits32())\n os << \"%lo(\";\n else if (mop.opHiBits64())\n os << \"%hh(\";\n else if (mop.opLoBits64())\n os << \"%hm(\";\n \n switch(mop.opType)\n {\n case MachineOperand::MO_VirtualRegister:\n os << \"%reg\";\n OutputValue(os, mop.getVRegValue());\n break;\n case MachineOperand::MO_CCRegister:\n os << \"%ccreg\";\n OutputValue(os, mop.getVRegValue());\n break;\n case MachineOperand::MO_MachineRegister:\n os << \"%reg\";\n os << \"(\" << mop.getMachineRegNum() << \")\";\n break;\n case MachineOperand::MO_SignExtendedImmed:\n os << (long)mop.immedVal;\n break;\n case MachineOperand::MO_UnextendedImmed:\n os << (long)mop.immedVal;\n break;\n case MachineOperand::MO_PCRelativeDisp:\n {\n const Value* opVal = mop.getVRegValue();\n bool isLabel = isa<Function>(opVal) || isa<BasicBlock>(opVal);\n os << \"%disp(\" << (isLabel? \"label \" : \"addr-of-val \");\n if (opVal->hasName())\n os << opVal->getName();\n else\n os << (const void*) opVal;\n os << \")\";\n break;\n }\n default:\n assert(0 && \"Unrecognized operand type\");\n break;\n }\n \n if (mop.flags &\n (MachineOperand::HIFLAG32 | MachineOperand::LOFLAG32 | \n MachineOperand::HIFLAG64 | MachineOperand::LOFLAG64))\n os << \")\";\n \n return os;\n}\n<|endoftext|>"} {"text":"<commit_before>\n#include <ImageProcessor.hpp>\n\n\n#define cimg_use_jpeg\n#include <CImg.h>\n\nusing namespace cimg_library;\n\n\nnamespace VideoMatch {\n\nstatic CImg<float>* ph_dct_matrix(const int N) \n{\n CImg<float> *ptr_matrix = new CImg<float>(N,N,1,1,1\/sqrt((float)N));\n const float c1 = sqrt(2.0\/N);\n for (int x=0;x<N;x++){\n for (int y=1;y<N;y++){\n *ptr_matrix->data(x,y) = c1*cos((cimg::PI\/2\/N)*y*(2*x+1));\n }\n }\n return ptr_matrix;\n}\n\nint GetHashCode(const char *filename, uint64_t& result)\n{\n if (!filename) {\n\t return -1;\n }\n\n CImg<uint8_t> src;\n try {\n\t src.load(filename);\n } catch (CImgIOException ex){\n\t return -1;\n }\n\n CImg<float> meanfilter(7,7,1,1,1);\n CImg<float> img;\n\n if (src.spectrum() == 3){\n img = src.RGBtoYCbCr().channel(0).get_convolve(meanfilter);\n } else if (src.spectrum() == 4) {\n\t int width = img.width();\n int height = img.height();\n int depth = img.depth();\n\t img = src.crop(0,0,0,0,width-1,height-1,depth-1,2)\n .RGBtoYCbCr().channel(0).get_convolve(meanfilter);\n } else {\n\t img = src.channel(0).get_convolve(meanfilter);\n }\n\n img.resize(32,32);\n CImg<float> *C = ph_dct_matrix(32);\n CImg<float> Ctransp = C->get_transpose();\n CImg<float> dctImage = (*C)*img*Ctransp;\n CImg<float> subsec = dctImage.crop(1,1,8,8).unroll('x');;\n \n float median = subsec.median();\n uint64_t one = 0x0000000000000001;\n result = 0x0000000000000000;\n for (int i=0;i< 64;i++){\n\t float current = subsec(i);\n if (current > median)\n\t result |= one;\n\t one = one << 1;\n }\n \n delete C;\n\n return 0;\n}\n\n\n}\n\n<commit_msg>image border crop and mirror added<commit_after>\n#include <ImageProcessor.hpp>\n\n\n#define cimg_use_jpeg\n#include <CImg.h>\n\nusing namespace cimg_library;\n\n\nnamespace VideoMatch {\n\nstatic CImg<float>* ph_dct_matrix(const int N) \n{\n CImg<float> *ptr_matrix = new CImg<float>(N,N,1,1,1\/sqrt((float)N));\n const float c1 = sqrt(2.0\/N);\n for (int x=0;x<N;x++){\n for (int y=1;y<N;y++){\n *ptr_matrix->data(x,y) = c1*cos((cimg::PI\/2\/N)*y*(2*x+1));\n }\n }\n return ptr_matrix;\n}\n\nstatic void crop_border(CImg<float>& img)\n{\n static const float SD_DIFF_THRESHOLD = 10.0;\n static const float AVG_DIFF_THRESHOLD = 5.0;\n int x1, x2, y1, y2;\n float last_avg = 0;\n\n x1 = x2 = y1 = y2 = 0;\n for(int y = 0; y < img.height() \/ 4; y++) {\n float sum = 0, avg = 0; \n int count = img.width();\n for(int x = 0; x < img.width(); x++) {\n sum += *(img.data(x, y));\n }\n avg = sum \/ count;\n sum = 0;\n for(int x = 0; x < img.width(); x++) {\n sum += pow(avg - *(img.data(x, y)), 2);\n }\n sum \/= count;\n sum = sqrt(sum);\n float avg_diff = avg - last_avg;\n if (avg_diff < 0) avg_diff = -avg_diff;\n if (sum > SD_DIFF_THRESHOLD || \n (y != 0 && avg_diff > AVG_DIFF_THRESHOLD)) {\n y1 = y;\n break;\n }\n last_avg = avg;\n }\n\n for(int y = 0; y < img.height() \/ 4; y++) {\n float sum = 0, avg = 0; \n int count = img.width();\n for(int x = 0; x < img.width(); x++) {\n sum += *(img.data(x, img.height() - 1 - y));\n }\n avg = sum \/ count;\n sum = 0;\n for(int x = 0; x < img.width(); x++) {\n sum += pow(avg - *(img.data(x, img.height() - 1 - y)), 2);\n }\n sum \/= count;\n sum = sqrt(sum);\n float avg_diff = avg - last_avg;\n if (avg_diff < 0) avg_diff = -avg_diff;\n if (sum > SD_DIFF_THRESHOLD || \n (y != 0 && avg_diff > AVG_DIFF_THRESHOLD)) {\n y2 = img.height() - y;\n break;\n }\n last_avg = avg;\n }\n\n for(int x = 0; x < img.width() \/ 4; x++) {\n float sum = 0, avg = 0; \n int count = img.width();\n for(int y = 0; y < img.height(); y++) {\n sum += *(img.data(x, y));\n }\n avg = sum \/ count;\n sum = 0;\n for(int y = 0; y < img.height(); y++) {\n sum += pow(avg - *(img.data(x, y)), 2);\n }\n sum \/= count;\n sum = sqrt(sum);\n float avg_diff = avg - last_avg;\n if (avg_diff < 0) avg_diff = -avg_diff;\n if (sum > SD_DIFF_THRESHOLD || \n (x != 0 && avg_diff > AVG_DIFF_THRESHOLD)) {\n x1 = x;\n break;\n }\n last_avg = avg;\n }\n\n for(int x = 0; x < img.width() \/ 4; x++) {\n float sum = 0, avg = 0; \n int count = img.width();\n for(int y = 0; y < img.height(); y++) {\n sum += *(img.data(img.width() - 1 - x, y));\n }\n avg = sum \/ count;\n sum = 0;\n for(int y = 0; y < img.height(); y++) {\n sum += pow(avg - *(img.data(img.width() - 1 - x, y)), 2);\n }\n sum \/= count;\n sum = sqrt(sum);\n float avg_diff = avg - last_avg;\n if (avg_diff < 0) avg_diff = -avg_diff;\n if (sum > SD_DIFF_THRESHOLD || \n (x != 0 && avg_diff > AVG_DIFF_THRESHOLD)) {\n x2 = img.width() - x;\n break;\n }\n last_avg = avg;\n }\n\n int nw = x2 - x1;\n int nh = y2 - y1;\n x1 += nw * 0.1;\n x2 -= nw * 0.1;\n y1 += nh * 0.1;\n y2 -= nh * 0.1;\n\n img.crop(x1, y1, 0, x2, y2, 0);\n}\n\nstatic void mirror(CImg<float>& img)\n{\n float suma, sumb;\n \/*\n suma = sumb = 0;\n for(int y = 0; y < img.height() \/ 2; y++) {\n for(int x = 0; x < img.width(); x++) {\n suma += *(img.data(x, y));\n sumb += *(img.data(x, img.height() - 1 - y));\n }\n }\n if (suma < sumb) \n img.mirror('y');\n *\/\n\n suma = sumb = 0;\n for(int x = 0; x < img.width() \/ 2; x++) {\n for(int y = 0; y < img.height(); y++) {\n suma += *(img.data(x, y));\n sumb += *(img.data(img.width() - 1 - x, y));\n }\n }\n if (suma < sumb) \n img.mirror('x');\n}\n\nint GetHashCode(const char *filename, uint64_t& result)\n{\n if (!filename) {\n\t return -1;\n }\n\n CImg<uint8_t> src;\n try {\n\t src.load(filename);\n } catch (CImgIOException ex){\n\t return -1;\n }\n\n CImg<float> meanfilter(7,7,1,1,1);\n CImg<float> img;\n CImg<float> c0;\n\n if (src.spectrum() == 3){\n c0 = src.RGBtoYCbCr().channel(0);\n } else if (src.spectrum() == 4) {\n\t int width = img.width();\n int height = img.height();\n int depth = img.depth();\n\t c0 = src.crop(0,0,0,0,width-1,height-1,depth-1,2)\n .RGBtoYCbCr().channel(0);\n } else {\n\t c0 = src.channel(0);\n }\n\n crop_border(c0);\n mirror(c0);\n img = c0.get_convolve(meanfilter);\n img.resize(32,32);\n CImg<float> *C = ph_dct_matrix(32);\n CImg<float> Ctransp = C->get_transpose();\n CImg<float> dctImage = (*C)*img*Ctransp;\n CImg<float> subsec = dctImage.crop(1,1,8,8).unroll('x');;\n \n float median = subsec.median();\n uint64_t one = 0x0000000000000001;\n result = 0x0000000000000000;\n for (int i=0;i< 64;i++){\n\t float current = subsec(i);\n if (current > median)\n\t result |= one;\n\t one = one << 1;\n }\n \n delete C;\n\n return 0;\n}\n\n\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/*\r\n * Copyright (c) 2006, Mathieu Champlon\r\n * All rights reserved.\r\n *\r\n * Redistribution and use in source and binary forms, with or without\r\n * modification, are permitted provided that the following conditions are\r\n * met :\r\n *\r\n * . Redistributions of source code must retain the above copyright\r\n * notice, this list of conditions and the following disclaimer.\r\n *\r\n * . Redistributions in binary form must reproduce the above copyright\r\n * notice, this list of conditions and the following disclaimer in the\r\n * documentation and\/or other materials provided with the distribution.\r\n *\r\n * . Neither the name of the copyright holders nor the names of the\r\n * contributors may be used to endorse or promote products derived from\r\n * this software without specific prior written permission.\r\n *\r\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\r\n * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\r\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\r\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE THE COPYRIGHT\r\n * OWNERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\r\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\r\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\r\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\r\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\r\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\r\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\r\n *\/\r\n\r\n#ifndef xeumeuleu_locator_hpp\r\n#define xeumeuleu_locator_hpp\r\n\r\n#include <xeumeuleu\/bridges\/xerces\/detail\/xerces.hpp>\r\n#include <xeumeuleu\/bridges\/xerces\/detail\/translate.hpp>\r\n#include <xeumeuleu\/bridges\/xerces\/detail\/shared_string.hpp>\r\n#include <sstream>\r\n\r\nnamespace xml\r\n{\r\n\/\/ =============================================================================\r\n\/** @class locator\r\n @brief Locator implementation\r\n*\/\r\n\/\/ Created: MAT 2007-09-20\r\n\/\/ =============================================================================\r\nclass locator : public XERCES_CPP_NAMESPACE::DOMLocator\r\n{\r\npublic:\r\n \/\/! @name Constructors\/Destructor\r\n \/\/@{\r\n locator( const shared_string& uri, const XERCES_CPP_NAMESPACE::XMLScanner& scanner )\r\n : uri_ ( uri )\r\n , line_ ( scanner.getLocator()->getLineNumber() )\r\n , column_( scanner.getLocator()->getColumnNumber() )\r\n {}\r\n locator( const shared_string& uri )\r\n : uri_ ( uri )\r\n , line_ ( 0 )\r\n , column_( 0 )\r\n {}\r\n locator( const locator& rhs )\r\n : XERCES_CPP_NAMESPACE::DOMLocator()\r\n , uri_ ( rhs.uri_ )\r\n , line_ ( rhs.line_ )\r\n , column_( rhs.column_ )\r\n {}\r\n locator( const XERCES_CPP_NAMESPACE::DOMLocator& rhs )\r\n : uri_ ( translate( rhs.getURI() ) )\r\n , line_ ( rhs.getLineNumber() )\r\n , column_( rhs.getColumnNumber() )\r\n {}\r\n virtual ~locator()\r\n {}\r\n \/\/@}\r\n\r\n \/\/! @name Accessors\r\n \/\/@{\r\n virtual XMLFileLoc getLineNumber() const\r\n {\r\n return line_;\r\n }\r\n virtual XMLFileLoc getColumnNumber() const\r\n {\r\n return column_;\r\n }\r\n#if XERCES_VERSION_MAJOR == 3\r\n virtual XMLFilePos getByteOffset() const\r\n {\r\n return 0;\r\n }\r\n virtual XMLFilePos getUtf16Offset() const\r\n {\r\n return 0;\r\n }\r\n virtual XERCES_CPP_NAMESPACE::DOMNode* getRelatedNode() const\r\n {\r\n return 0;\r\n }\r\n#else\r\n virtual XMLFilePos getOffset() const\r\n {\r\n return -1;\r\n }\r\n virtual XERCES_CPP_NAMESPACE::DOMNode* getErrorNode() const\r\n {\r\n return 0;\r\n }\r\n#endif \/\/ XERCES_VERSION_MAJOR\r\n virtual const XMLCh* getURI() const\r\n {\r\n return 0;\r\n }\r\n \/\/@}\r\n\r\n \/\/! @name Operators\r\n \/\/@{\r\n operator std::string() const\r\n {\r\n std::stringstream stream;\r\n stream << \" (line \" << line_ << \", column \" << column_ << \") : \";\r\n return uri_ + stream.str();\r\n }\r\n \/\/@}\r\n\r\n \/\/! @name Modifiers\r\n \/\/@{\r\n#if XERCES_VERSION_MAJOR < 3\r\n virtual void setLineNumber( const XMLSSize_t \/*line*\/ )\r\n {}\r\n virtual void setColumnNumber( const XMLSSize_t \/*column*\/ )\r\n {}\r\n virtual void setOffset( const XMLSSize_t \/*offset*\/ )\r\n {}\r\n virtual void setErrorNode( XERCES_CPP_NAMESPACE::DOMNode* const \/*node*\/ )\r\n {}\r\n virtual void setURI( const XMLCh* const \/*uri*\/ )\r\n {}\r\n#endif \/\/ XERCES_VERSION_MAJOR\r\n \/\/@}\r\n\r\nprivate:\r\n \/\/! @name Copy\/Assignment\r\n \/\/@{\r\n locator& operator=( const locator& ); \/\/!< Assignment operator\r\n \/\/@}\r\n\r\nprivate:\r\n \/\/! @name Member data\r\n \/\/@{\r\n const shared_string uri_;\r\n const XMLFileLoc line_, column_;\r\n \/\/@}\r\n};\r\n\r\n}\r\n\r\n#endif \/\/ xeumeuleu_locator_hpp\r\n<commit_msg>Removed dead code<commit_after>\/*\r\n * Copyright (c) 2006, Mathieu Champlon\r\n * All rights reserved.\r\n *\r\n * Redistribution and use in source and binary forms, with or without\r\n * modification, are permitted provided that the following conditions are\r\n * met :\r\n *\r\n * . Redistributions of source code must retain the above copyright\r\n * notice, this list of conditions and the following disclaimer.\r\n *\r\n * . Redistributions in binary form must reproduce the above copyright\r\n * notice, this list of conditions and the following disclaimer in the\r\n * documentation and\/or other materials provided with the distribution.\r\n *\r\n * . Neither the name of the copyright holders nor the names of the\r\n * contributors may be used to endorse or promote products derived from\r\n * this software without specific prior written permission.\r\n *\r\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\r\n * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\r\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\r\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE THE COPYRIGHT\r\n * OWNERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\r\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\r\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\r\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\r\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\r\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\r\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\r\n *\/\r\n\r\n#ifndef xeumeuleu_locator_hpp\r\n#define xeumeuleu_locator_hpp\r\n\r\n#include <xeumeuleu\/bridges\/xerces\/detail\/xerces.hpp>\r\n#include <xeumeuleu\/bridges\/xerces\/detail\/translate.hpp>\r\n#include <xeumeuleu\/bridges\/xerces\/detail\/shared_string.hpp>\r\n#include <sstream>\r\n\r\nnamespace xml\r\n{\r\n\/\/ =============================================================================\r\n\/** @class locator\r\n @brief Locator implementation\r\n*\/\r\n\/\/ Created: MAT 2007-09-20\r\n\/\/ =============================================================================\r\nclass locator\r\n{\r\npublic:\r\n \/\/! @name Constructors\/Destructor\r\n \/\/@{\r\n locator( const shared_string& uri, const XERCES_CPP_NAMESPACE::XMLScanner& scanner )\r\n : uri_ ( uri )\r\n , line_ ( scanner.getLocator()->getLineNumber() )\r\n , column_( scanner.getLocator()->getColumnNumber() )\r\n {}\r\n locator( const shared_string& uri )\r\n : uri_ ( uri )\r\n , line_ ( 0 )\r\n , column_( 0 )\r\n {}\r\n locator( const locator& rhs )\r\n : uri_ ( rhs.uri_ )\r\n , line_ ( rhs.line_ )\r\n , column_( rhs.column_ )\r\n {}\r\n locator( const XERCES_CPP_NAMESPACE::DOMLocator& rhs )\r\n : uri_ ( translate( rhs.getURI() ) )\r\n , line_ ( rhs.getLineNumber() )\r\n , column_( rhs.getColumnNumber() )\r\n {}\r\n \/\/@}\r\n\r\n \/\/! @name Operators\r\n \/\/@{\r\n operator std::string() const\r\n {\r\n std::stringstream stream;\r\n stream << \" (line \" << line_ << \", column \" << column_ << \") : \";\r\n return uri_ + stream.str();\r\n }\r\n \/\/@}\r\n\r\nprivate:\r\n \/\/! @name Copy\/Assignment\r\n \/\/@{\r\n locator& operator=( const locator& ); \/\/!< Assignment operator\r\n \/\/@}\r\n\r\nprivate:\r\n \/\/! @name Member data\r\n \/\/@{\r\n const shared_string uri_;\r\n const XMLFileLoc line_, column_;\r\n \/\/@}\r\n};\r\n\r\n}\r\n\r\n#endif \/\/ xeumeuleu_locator_hpp\r\n<|endoftext|>"} {"text":"<commit_before>#include \"GraphicalUI.hpp\"\n#include \"defines.hpp\"\n#include \"Board.hpp\"\n#include \"Game.hpp\"\n\n#include <SFML\/Graphics.hpp>\n#include <iostream>\n\n\nui::GraphicalUI::GraphicalUI()\n{\n\twindowExists = false;\n\n if (!respawn.loadAndSetTexture(\"..\/assets\/respawn.png\"))\n {\n std::cout << \"No se pudo cargar respawn.png!\" << std::endl;\n }\n\n if (!tower.loadAndSetTexture(\"..\/assets\/tower.png\"))\n {\n std::cout << \"No se pudo cargar tower.png!\" << std::endl;\n }\n\n if (!attackers.loadAndSetTexture(\"..\/assets\/attackers.png\"))\n {\n std::cout << \"No se pudo cargar attackers.png!\" << std::endl;\n }\n\n if (!defenders.loadAndSetTexture(\"..\/assets\/defenders.png\"))\n {\n std::cout << \"No se pudo cargar defenders.png!\" << std::endl;\n }\n\n float scaleFactor = 0.5;\n \n \/\/ We multiply by a constant factor to make it a little bit smaller.\n float scaleX = (1 \/ (respawn.texture.getSize().x \/ GRID_W)) * scaleFactor;\n float scaleY = (1 \/ (respawn.texture.getSize().y \/ GRID_H)) * scaleFactor;\n\n respawn.sprite.scale(scaleX, scaleY);\n\n \/\/ We center the sprite.\n respawn.sprite.setPosition(\n (GRID_W - respawn.texture.getSize().x * scaleX) * 0.5,\n (GRID_H - respawn.texture.getSize().y * scaleY) * 0.5\n );\n\n \/\/ We multiply by a constant factor to make it a little bit smaller.\n scaleX = (1 \/ (tower.texture.getSize().x \/ GRID_W)) * scaleFactor;\n scaleY = (1 \/ (tower.texture.getSize().y \/ GRID_H)) * scaleFactor;\n\n tower.sprite.scale(scaleX, scaleY);\n\n tower.sprite.setPosition(\n WINDOW_W - (GRID_W + tower.texture.getSize().x * scaleX) * 0.5,\n WINDOW_H - (GRID_H + tower.texture.getSize().y * scaleY) * 0.5\n );\n\n scaleX = (1 \/ (attackers.texture.getSize().x \/ GRID_W)) * scaleFactor;\n scaleY = (1 \/ (attackers.texture.getSize().y \/ GRID_H)) * scaleFactor;\n\n attackers.sprite.scale(scaleX, scaleY);\n\n\n scaleX = (1 \/ (defenders.texture.getSize().x \/ GRID_W)) * scaleFactor;\n scaleY = (1 \/ (defenders.texture.getSize().y \/ GRID_H)) * scaleFactor;\n\n defenders.sprite.scale(scaleX, scaleY);\n}\n\nvoid ui::GraphicalUI::create(int w, int h, int bpp)\n{\n\tif (!windowExists)\n\t{\n\t\trenderWindow.create(sf::VideoMode(w, h, bpp), \"TowDef-AI\");\n\t\twindowExists = true;\n\t}\n}\n\nvoid ui::GraphicalUI::drawBoard()\n{\n float lineThickness = 1.5;\n\n sf::RectangleShape lineH(sf::Vector2f(WINDOW_W, lineThickness));\n sf::RectangleShape lineV(sf::Vector2f(lineThickness, WINDOW_H));\n\n lineH.setFillColor(sf::Color::Black);\n lineV.setFillColor(sf::Color::Black);\n\n renderWindow.clear(sf::Color(229, 229, 229));\n\n \/\/ The space between each horizontal and vertical line.\n float lineHSpace = WINDOW_H \/ BOARD_H;\n float lineVSpace = WINDOW_W \/ BOARD_W;\n\n for (float i = lineHSpace; i <= WINDOW_H; i += lineHSpace)\n {\n renderWindow.draw(lineH);\n lineH.setPosition(0, i);\n }\n\n for (float i = lineVSpace; i <= WINDOW_W; i += lineVSpace)\n {\n renderWindow.draw(lineV);\n lineV.setPosition(i, 0);\n }\n\n lineH.setPosition(0, WINDOW_H - lineThickness);\n renderWindow.draw(lineH);\n \n lineV.setPosition(WINDOW_W - lineThickness, 0);\n renderWindow.draw(lineV);\n\n renderWindow.draw(respawn.sprite);\n renderWindow.draw(tower.sprite);\n}\n\nvoid ui::GraphicalUI::show(logic::Game* gameInstance)\n{\n\tif (loopMethod == nullptr)\n\t{\n\t\tstd::cout << \"ui::show()==> No se establecio ningun metodo a ejecutar.\" << std::endl;\n\t\treturn;\n\t}\n\n\twhile (renderWindow.isOpen())\n {\n \/\/ check all the renderWindow's events that were triggered since the last iteration of the loop\n sf::Event event;\n while (renderWindow.pollEvent(event))\n {\n \/\/ \"close requested\" event: we close the renderWindow\n if (event.type == sf::Event::Closed)\n renderWindow.close();\n }\n\n \/\/ We execute the game loop from the logic part of the game.\n if (!(gameInstance->*loopMethod)())\n {\n renderWindow.close();\n }\n\n \/\/ draw everything here...\n\n drawBoard();\n drawDefenders(gameInstance);\n\n \/\/ end the current frame\n renderWindow.display();\n }\n}\n\nvoid ui::GraphicalUI::drawDefenders(logic::Game* gameInstance)\n{\n sf::Vector2f attScale = attackers.sprite.getScale();\n \n sf::Vector2f defScale = attackers.sprite.getScale();\n\n const logic::Board& board = gameInstance->getBoard();\n\n for (int i = 0; i < BOARD_W; i++)\n {\n for (int j = 0; j < BOARD_H; j++)\n {\n const std::vector<logic::Entity*>* entities = board.getEntitiesAt(i, j);\n\n if (entities == nullptr) continue;\n\n if (entities->size() != 0)\n {\n if ((*entities)[0]->getType() == logic::EntityType::ATTACK)\n {\n attackers.sprite.setPosition(\n (i * GRID_W) + (GRID_W - attackers.texture.getSize().x * attScale.x) * 0.5,\n (j * GRID_H) + (GRID_H - attackers.texture.getSize().y * attScale.y) * 0.5\n );\n\n renderWindow.draw(attackers.sprite);\n }\n else if ((*entities)[0]->getType() == logic::EntityType::DEFENSE)\n {\n defenders.sprite.setPosition(\n (i * GRID_W) + (GRID_W - defenders.texture.getSize().x * defScale.x) * 0.5,\n (j * GRID_H) + (GRID_H - defenders.texture.getSize().y * defScale.y) * 0.5\n );\n\n renderWindow.draw(defenders.sprite);\n }\n }\n }\n }\n}\n\nvoid ui::GraphicalUI::drawAttackers(logic::Game *gameInstance)\n{\n \n}<commit_msg>Now pressing Q will quit.<commit_after>#include \"GraphicalUI.hpp\"\n#include \"defines.hpp\"\n#include \"Board.hpp\"\n#include \"Game.hpp\"\n\n#include <SFML\/Graphics.hpp>\n#include <iostream>\n\n\nui::GraphicalUI::GraphicalUI()\n{\n\twindowExists = false;\n\n if (!respawn.loadAndSetTexture(\"..\/assets\/respawn.png\"))\n {\n std::cout << \"No se pudo cargar respawn.png!\" << std::endl;\n }\n\n if (!tower.loadAndSetTexture(\"..\/assets\/tower.png\"))\n {\n std::cout << \"No se pudo cargar tower.png!\" << std::endl;\n }\n\n if (!attackers.loadAndSetTexture(\"..\/assets\/attackers.png\"))\n {\n std::cout << \"No se pudo cargar attackers.png!\" << std::endl;\n }\n\n if (!defenders.loadAndSetTexture(\"..\/assets\/defenders.png\"))\n {\n std::cout << \"No se pudo cargar defenders.png!\" << std::endl;\n }\n\n float scaleFactor = 0.5;\n \n \/\/ We multiply by a constant factor to make it a little bit smaller.\n float scaleX = (1 \/ (respawn.texture.getSize().x \/ GRID_W)) * scaleFactor;\n float scaleY = (1 \/ (respawn.texture.getSize().y \/ GRID_H)) * scaleFactor;\n\n respawn.sprite.scale(scaleX, scaleY);\n\n \/\/ We center the sprite.\n respawn.sprite.setPosition(\n (GRID_W - respawn.texture.getSize().x * scaleX) * 0.5,\n (GRID_H - respawn.texture.getSize().y * scaleY) * 0.5\n );\n\n \/\/ We multiply by a constant factor to make it a little bit smaller.\n scaleX = (1 \/ (tower.texture.getSize().x \/ GRID_W)) * scaleFactor;\n scaleY = (1 \/ (tower.texture.getSize().y \/ GRID_H)) * scaleFactor;\n\n tower.sprite.scale(scaleX, scaleY);\n\n tower.sprite.setPosition(\n WINDOW_W - (GRID_W + tower.texture.getSize().x * scaleX) * 0.5,\n WINDOW_H - (GRID_H + tower.texture.getSize().y * scaleY) * 0.5\n );\n\n scaleX = (1 \/ (attackers.texture.getSize().x \/ GRID_W)) * scaleFactor;\n scaleY = (1 \/ (attackers.texture.getSize().y \/ GRID_H)) * scaleFactor;\n\n attackers.sprite.scale(scaleX, scaleY);\n\n\n scaleX = (1 \/ (defenders.texture.getSize().x \/ GRID_W)) * scaleFactor;\n scaleY = (1 \/ (defenders.texture.getSize().y \/ GRID_H)) * scaleFactor;\n\n defenders.sprite.scale(scaleX, scaleY);\n}\n\nvoid ui::GraphicalUI::create(int w, int h, int bpp)\n{\n\tif (!windowExists)\n\t{\n\t\trenderWindow.create(sf::VideoMode(w, h, bpp), \"TowDef-AI\");\n\t\twindowExists = true;\n\t}\n}\n\nvoid ui::GraphicalUI::drawBoard()\n{\n float lineThickness = 1.5;\n\n sf::RectangleShape lineH(sf::Vector2f(WINDOW_W, lineThickness));\n sf::RectangleShape lineV(sf::Vector2f(lineThickness, WINDOW_H));\n\n lineH.setFillColor(sf::Color::Black);\n lineV.setFillColor(sf::Color::Black);\n\n renderWindow.clear(sf::Color(229, 229, 229));\n\n \/\/ The space between each horizontal and vertical line.\n float lineHSpace = WINDOW_H \/ BOARD_H;\n float lineVSpace = WINDOW_W \/ BOARD_W;\n\n for (float i = lineHSpace; i <= WINDOW_H; i += lineHSpace)\n {\n renderWindow.draw(lineH);\n lineH.setPosition(0, i);\n }\n\n for (float i = lineVSpace; i <= WINDOW_W; i += lineVSpace)\n {\n renderWindow.draw(lineV);\n lineV.setPosition(i, 0);\n }\n\n lineH.setPosition(0, WINDOW_H - lineThickness);\n renderWindow.draw(lineH);\n \n lineV.setPosition(WINDOW_W - lineThickness, 0);\n renderWindow.draw(lineV);\n\n renderWindow.draw(respawn.sprite);\n renderWindow.draw(tower.sprite);\n}\n\nvoid ui::GraphicalUI::show(logic::Game* gameInstance)\n{\n\tif (loopMethod == nullptr)\n\t{\n\t\tstd::cout << \"ui::show()==> No se establecio ningun metodo a ejecutar.\" << std::endl;\n\t\treturn;\n\t}\n\n\twhile (renderWindow.isOpen())\n {\n \/\/ check all the renderWindow's events that were triggered since the last iteration of the loop\n sf::Event event;\n while (renderWindow.pollEvent(event))\n {\n \/\/ \"close requested\" event: we close the renderWindow\n if (event.type == sf::Event::Closed)\n renderWindow.close();\n \n if (event.type == sf::Event::KeyPressed)\n {\n if (event.key.code == sf::Keyboard::Q)\n {\n renderWindow.close();\n }\n }\n }\n\n \/\/ We execute the game loop from the logic part of the game.\n if (!(gameInstance->*loopMethod)())\n {\n renderWindow.close();\n }\n\n \/\/ draw everything here...\n\n drawBoard();\n drawDefenders(gameInstance);\n\n \/\/ end the current frame\n renderWindow.display();\n }\n}\n\nvoid ui::GraphicalUI::drawDefenders(logic::Game* gameInstance)\n{\n sf::Vector2f attScale = attackers.sprite.getScale();\n \n sf::Vector2f defScale = attackers.sprite.getScale();\n\n const logic::Board& board = gameInstance->getBoard();\n\n for (int i = 0; i < BOARD_W; i++)\n {\n for (int j = 0; j < BOARD_H; j++)\n {\n const std::vector<logic::Entity*>* entities = board.getEntitiesAt(i, j);\n\n if (entities == nullptr) continue;\n\n if (entities->size() != 0)\n {\n if ((*entities)[0]->getType() == logic::EntityType::ATTACK)\n {\n attackers.sprite.setPosition(\n (i * GRID_W) + (GRID_W - attackers.texture.getSize().x * attScale.x) * 0.5,\n (j * GRID_H) + (GRID_H - attackers.texture.getSize().y * attScale.y) * 0.5\n );\n\n renderWindow.draw(attackers.sprite);\n }\n else if ((*entities)[0]->getType() == logic::EntityType::DEFENSE)\n {\n defenders.sprite.setPosition(\n (i * GRID_W) + (GRID_W - defenders.texture.getSize().x * defScale.x) * 0.5,\n (j * GRID_H) + (GRID_H - defenders.texture.getSize().y * defScale.y) * 0.5\n );\n\n renderWindow.draw(defenders.sprite);\n }\n }\n }\n }\n}\n\nvoid ui::GraphicalUI::drawAttackers(logic::Game *gameInstance)\n{\n \n}<|endoftext|>"} {"text":"<commit_before>#include \"StateMachine.h\"\n#include <algorithm>\n#define THREADLESS_STATEMACHINE\nbool DriveInstruction::aimTarget(const ObjectPosition &target, Speed &speed, double errorMargin){\n\tdouble heading = target.getHeading();\n\tdouble distance = target.getDistance();\n\tif (fabs(heading) > errorMargin){\n\t\tspeed.rotation = -sign0(heading) * std::min(40.0, std::max(5*log(fabs(heading)), 5.0));\n\t\treturn false;\n\t}\n\telse return fabs(heading) < errorMargin;\n}\nbool DriveInstruction::catchTarget(const ObjectPosition &target, Speed &speed){\n\tif (m_pCom->BallInTribbler()) return true;\n\tdouble heading = target.getHeading();\n\tdouble dist = target.getDistance();\n\tspeed.velocity = 60;\n\tspeed.heading = 0;\n\treturn false;\n}\n\nbool DriveInstruction::driveToTarget(const ObjectPosition &target, Speed &speed, double maxDistance){\n\tdouble dist = target.getDistance();\n\tif (dist > maxDistance){\n\t\tspeed.velocity = std::max(20.0, dist);\n\t\treturn false;\n\t}\n\telse{\n\t\tspeed.velocity = 20;\n\t\treturn true;\n\t}\n}\n\nbool DriveInstruction::driveToTargetWithAngle(const ObjectPosition &target, Speed &speed, double maxDistance, double errorMargin){\n\tdouble heading = target.getHeading();\n\tdouble dist = target.getDistance();\n\tdouble velocity = 0;\n\tdouble direction = 0;\n\tdouble angularSpeed = 0;\n\tbool onPoint = false;\n\tif (fabs(heading) > errorMargin){\n\t\tif (dist > maxDistance){\n\t\t\tvelocity = std::max(30.0, dist); \/\/max speed is limited to 190 in wheelController.cpp \n\t\t\tdirection = heading; \/\/drive towards target\n\t\t\tangularSpeed = sign0(heading) * 20; \/\/meanwhile rotate slowly to face the target\n\t\t}\n\t\telse{ \/\/at location but facing wrong way\n\t\t\tangularSpeed = sign0(heading) * std::max(fabs(heading) * 0.5, 10.0); \/\/rotate\n\t\t}\n\t}\n\telse{\n\t\tif (dist > maxDistance){\n\t\t\tvelocity = std::max(30.0, dist);\n\t\t\tdirection = heading; \/\/drive towards target\n\t\t}\n\t\telse onPoint = true;\n\t}\n\tspeed.velocity = velocity;\n\tspeed.heading = direction;\n\tspeed.rotation = -angularSpeed;\n\treturn onPoint;\n}\n\n\nconst BallPosition &DriveInstruction::getClosestBall(bool includeHeading, bool reset){\n\treturn m_pFieldState->balls.getClosest();\n}\n\n\nStateMachine::StateMachine(ICommunicationModule *pComModule, FieldState *pState,\n\tconst std::map<DriveMode, DriveInstruction*> &driveModes) :driveModes(driveModes), ThreadedClass(\"Autopilot\/StateMachine\")\n{\n\tm_pComModule = pComModule;\n\tm_pFieldState = pState;\n\tfor (auto driveMode : driveModes) driveMode.second->Init(pComModule, pState);\n\tcurDriveMode = this->driveModes.find(DRIVEMODE_IDLE);\n\n}\n\nvoid StateMachine::setTestMode(DriveMode mode){ testDriveMode = mode; }\n\nvoid StateMachine::enableTestMode(bool enable)\n{\n\tsetTestMode(DRIVEMODE_IDLE);\n\ttestMode = enable;\n\tif (!testMode) m_pComModule->Drive(0, 0, 0);\n}\n\n\nvoid StateMachine::StepOnce()\n{\n#ifdef THREADLESS_STATEMACHINE\n\tif (!running) return;\n\n\tboost::posix_time::ptime time = boost::posix_time::microsec_clock::local_time();\n\t\tboost::posix_time::time_duration::tick_type dt = (time - lastStep).total_milliseconds();\n\t\tDriveMode newMode = testMode ? curDriveMode->second->step2(double(dt), newMode) : curDriveMode->second->step1(double(dt), newMode);\n\t\tauto old = curDriveMode;\n\t\tif (testMode){\n\t\t\tif (testDriveMode != DRIVEMODE_IDLE && newMode == DRIVEMODE_IDLE) newMode = testDriveMode;\n\t\t\telse if (newMode != testDriveMode) {\n\t\t\t\tnewMode = DRIVEMODE_IDLE;\n\t\t\t\ttestDriveMode = DRIVEMODE_IDLE;\n\t\t\t}\n\t\t}\n\n\t\tif (newMode != curDriveMode->first){\n\t\t\tboost::mutex::scoped_lock lock(mutex);\n\t\t\tstd::cout << \"state: \" << curDriveMode->second->name;\n\n\t\t\tcurDriveMode->second->onExit();\n\t\t\tcurDriveMode = driveModes.find(newMode);\n\t\t\tif (curDriveMode == driveModes.end()){\n\t\t\t\tcurDriveMode = driveModes.find(DRIVEMODE_IDLE);\n\t\t\t\tstd::cout << \"-> unknown state: \" << newMode << std::endl;\n\t\t\t}\n\t\t\tstd::cout << \" -> \" << curDriveMode->second->name << std::endl;\n\n\t\t\tcurDriveMode->second->onEnter1();\n\t\t}\n#else\n#endif\n}\n\n\nvoid StateMachine::Run()\n{\n\tlastStep = boost::posix_time::microsec_clock::local_time();\n\tDriveMode newMode = curDriveMode->first;\n\tcurDriveMode->second->onEnter();\n\twhile (!stop_thread) {\n#ifdef THREADLESS_STATEMACHINE\n\t\tSleep(100);\n\t\tcontinue;\n#else\n\t\t\/\/ StepOnce is called from FrontCameraVision\n\t\tboost::posix_time::ptime time = boost::posix_time::microsec_clock::local_time();\n\t\tboost::posix_time::time_duration::tick_type dt = (time - lastStep).total_milliseconds();\n\t\tnewMode = testMode ? curDriveMode->second->step2(double(dt), newMode) : curDriveMode->second->step1(double(dt), newMode);\n\t\tauto old = curDriveMode;\n\t\tif (testMode){\n\t\t\tif (testDriveMode != DRIVEMODE_IDLE && newMode == DRIVEMODE_IDLE) newMode = testDriveMode;\n\t\t\telse if (newMode != testDriveMode) {\n\t\t\t\t\/\/newMode = DRIVEMODE_IDLE;\n\t\t\t\t\/\/testDriveMode = DRIVEMODE_IDLE;\n\t\t\t}\n\t\t}\n\n\t\tif (newMode != curDriveMode->first){\n\t\t\tboost::mutex::scoped_lock lock(mutex);\n\t\t\tstd::cout << \"state: \" << curDriveMode->second->name;\n\n\t\t\tcurDriveMode->second->onExit();\n\t\t\tcurDriveMode = driveModes.find(newMode);\n\t\t\tif (curDriveMode == driveModes.end()){\n\t\t\t\tcurDriveMode = driveModes.find(DRIVEMODE_IDLE);\n\t\t\t\tstd::cout << \"-> unknown state: \" << newMode << std::endl;\n\t\t\t}\n\t\t\tstd::cout << \" -> \" << curDriveMode->second->name << std::endl;\n\n\t\t\tcurDriveMode->second->onEnter1();\n\t\t\tstd::this_thread::sleep_for(std::chrono::milliseconds(50)); \/\/ this seems to be neccecary\n\t\t}\n#endif\n\t}\n}\n\nstd::string StateMachine::GetDebugInfo(){\n\tstd::ostringstream oss;\n\tboost::mutex::scoped_lock lock(mutex);\n\toss << \"[StateMachine] State: \" << curDriveMode->second->name;\n\treturn oss.str();\n}\n\n\nStateMachine::~StateMachine()\n{\n\tWaitForStop();\n\tfor (auto &mode : driveModes){ delete mode.second; }\n}\n\nDriveMode DriveInstruction::prevDriveMode = DRIVEMODE_IDLE;\nDriveMode DriveInstruction::ACTIVE_DRIVE_TO_BALL_MODE = DRIVEMODE_IDLE;\ncv::Point2d DriveInstruction::lastBallPos = cv::Point2d(0,0);\n\n<commit_msg>newMode init restored in THREADLESS_STATREMACHINE<commit_after>#include \"StateMachine.h\"\n#include <algorithm>\n#define THREADLESS_STATEMACHINE\nbool DriveInstruction::aimTarget(const ObjectPosition &target, Speed &speed, double errorMargin){\n\tdouble heading = target.getHeading();\n\tdouble distance = target.getDistance();\n\tif (fabs(heading) > errorMargin){\n\t\tspeed.rotation = -sign0(heading) * std::min(40.0, std::max(5*log(fabs(heading)), 5.0));\n\t\treturn false;\n\t}\n\telse return fabs(heading) < errorMargin;\n}\nbool DriveInstruction::catchTarget(const ObjectPosition &target, Speed &speed){\n\tif (m_pCom->BallInTribbler()) return true;\n\tdouble heading = target.getHeading();\n\tdouble dist = target.getDistance();\n\tspeed.velocity = 60;\n\tspeed.heading = 0;\n\treturn false;\n}\n\nbool DriveInstruction::driveToTarget(const ObjectPosition &target, Speed &speed, double maxDistance){\n\tdouble dist = target.getDistance();\n\tif (dist > maxDistance){\n\t\tspeed.velocity = std::max(20.0, dist);\n\t\treturn false;\n\t}\n\telse{\n\t\tspeed.velocity = 20;\n\t\treturn true;\n\t}\n}\n\nbool DriveInstruction::driveToTargetWithAngle(const ObjectPosition &target, Speed &speed, double maxDistance, double errorMargin){\n\tdouble heading = target.getHeading();\n\tdouble dist = target.getDistance();\n\tdouble velocity = 0;\n\tdouble direction = 0;\n\tdouble angularSpeed = 0;\n\tbool onPoint = false;\n\tif (fabs(heading) > errorMargin){\n\t\tif (dist > maxDistance){\n\t\t\tvelocity = std::max(30.0, dist); \/\/max speed is limited to 190 in wheelController.cpp \n\t\t\tdirection = heading; \/\/drive towards target\n\t\t\tangularSpeed = sign0(heading) * 20; \/\/meanwhile rotate slowly to face the target\n\t\t}\n\t\telse{ \/\/at location but facing wrong way\n\t\t\tangularSpeed = sign0(heading) * std::max(fabs(heading) * 0.5, 10.0); \/\/rotate\n\t\t}\n\t}\n\telse{\n\t\tif (dist > maxDistance){\n\t\t\tvelocity = std::max(30.0, dist);\n\t\t\tdirection = heading; \/\/drive towards target\n\t\t}\n\t\telse onPoint = true;\n\t}\n\tspeed.velocity = velocity;\n\tspeed.heading = direction;\n\tspeed.rotation = -angularSpeed;\n\treturn onPoint;\n}\n\n\nconst BallPosition &DriveInstruction::getClosestBall(bool includeHeading, bool reset){\n\treturn m_pFieldState->balls.getClosest();\n}\n\n\nStateMachine::StateMachine(ICommunicationModule *pComModule, FieldState *pState,\n\tconst std::map<DriveMode, DriveInstruction*> &driveModes) :driveModes(driveModes), ThreadedClass(\"Autopilot\/StateMachine\")\n{\n\tm_pComModule = pComModule;\n\tm_pFieldState = pState;\n\tfor (auto driveMode : driveModes) driveMode.second->Init(pComModule, pState);\n\tcurDriveMode = this->driveModes.find(DRIVEMODE_IDLE);\n\n}\n\nvoid StateMachine::setTestMode(DriveMode mode){ testDriveMode = mode; }\n\nvoid StateMachine::enableTestMode(bool enable)\n{\n\tsetTestMode(DRIVEMODE_IDLE);\n\ttestMode = enable;\n\tif (!testMode) m_pComModule->Drive(0, 0, 0);\n}\n\n\nvoid StateMachine::StepOnce()\n{\n#ifdef THREADLESS_STATEMACHINE\n\n\tif (!running) return;\n\tDriveMode newMode = curDriveMode->first;\n\tcurDriveMode->second->onEnter();\n\n\tboost::posix_time::ptime time = boost::posix_time::microsec_clock::local_time();\n\tboost::posix_time::time_duration::tick_type dt = (time - lastStep).total_milliseconds();\n\tnewMode = testMode ? curDriveMode->second->step2(double(dt), newMode) : curDriveMode->second->step1(double(dt), newMode);\n\tauto old = curDriveMode;\n\tif (testMode){\n\t\tif (testDriveMode != DRIVEMODE_IDLE && newMode == DRIVEMODE_IDLE) newMode = testDriveMode;\n\t\telse if (newMode != testDriveMode) {\n\t\t\tnewMode = DRIVEMODE_IDLE;\n\t\t\ttestDriveMode = DRIVEMODE_IDLE;\n\t\t}\n\t}\n\n\tif (newMode != curDriveMode->first){\n\t\tboost::mutex::scoped_lock lock(mutex);\n\t\tstd::cout << \"state: \" << curDriveMode->second->name;\n\n\t\tcurDriveMode->second->onExit();\n\t\tcurDriveMode = driveModes.find(newMode);\n\t\tif (curDriveMode == driveModes.end()){\n\t\t\tcurDriveMode = driveModes.find(DRIVEMODE_IDLE);\n\t\t\tstd::cout << \"-> unknown state: \" << newMode << std::endl;\n\t\t}\n\t\tstd::cout << \" -> \" << curDriveMode->second->name << std::endl;\n\n\t\tcurDriveMode->second->onEnter1();\n\t}\n#else\n#endif\n}\n\n\nvoid StateMachine::Run()\n{\n\tlastStep = boost::posix_time::microsec_clock::local_time();\n\tDriveMode newMode = curDriveMode->first;\n\tcurDriveMode->second->onEnter();\n\twhile (!stop_thread) {\n#ifdef THREADLESS_STATEMACHINE\n\t\tSleep(100);\n\t\tcontinue;\n#else\n\t\t\/\/ StepOnce is called from FrontCameraVision\n\t\tboost::posix_time::ptime time = boost::posix_time::microsec_clock::local_time();\n\t\tboost::posix_time::time_duration::tick_type dt = (time - lastStep).total_milliseconds();\n\t\tnewMode = testMode ? curDriveMode->second->step2(double(dt), newMode) : curDriveMode->second->step1(double(dt), newMode);\n\t\tauto old = curDriveMode;\n\t\tif (testMode){\n\t\t\tif (testDriveMode != DRIVEMODE_IDLE && newMode == DRIVEMODE_IDLE) newMode = testDriveMode;\n\t\t\telse if (newMode != testDriveMode) {\n\t\t\t\t\/\/newMode = DRIVEMODE_IDLE;\n\t\t\t\t\/\/testDriveMode = DRIVEMODE_IDLE;\n\t\t\t}\n\t\t}\n\n\t\tif (newMode != curDriveMode->first){\n\t\t\tboost::mutex::scoped_lock lock(mutex);\n\t\t\tstd::cout << \"state: \" << curDriveMode->second->name;\n\n\t\t\tcurDriveMode->second->onExit();\n\t\t\tcurDriveMode = driveModes.find(newMode);\n\t\t\tif (curDriveMode == driveModes.end()){\n\t\t\t\tcurDriveMode = driveModes.find(DRIVEMODE_IDLE);\n\t\t\t\tstd::cout << \"-> unknown state: \" << newMode << std::endl;\n\t\t\t}\n\t\t\tstd::cout << \" -> \" << curDriveMode->second->name << std::endl;\n\n\t\t\tcurDriveMode->second->onEnter1();\n\t\t\tstd::this_thread::sleep_for(std::chrono::milliseconds(50)); \/\/ this seems to be neccecary\n\t\t}\n#endif\n\t}\n}\n\nstd::string StateMachine::GetDebugInfo(){\n\tstd::ostringstream oss;\n\tboost::mutex::scoped_lock lock(mutex);\n\toss << \"[StateMachine] State: \" << curDriveMode->second->name;\n\treturn oss.str();\n}\n\n\nStateMachine::~StateMachine()\n{\n\tWaitForStop();\n\tfor (auto &mode : driveModes){ delete mode.second; }\n}\n\nDriveMode DriveInstruction::prevDriveMode = DRIVEMODE_IDLE;\nDriveMode DriveInstruction::ACTIVE_DRIVE_TO_BALL_MODE = DRIVEMODE_IDLE;\ncv::Point2d DriveInstruction::lastBallPos = cv::Point2d(0,0);\n\n<|endoftext|>"} {"text":"<commit_before>#include \"antsUtilities.h\"\n#include <algorithm>\n\n#include \"itkBSplineScatteredDataPointSetToImageFilter.h\"\n#include \"itkContinuousIndex.h\"\n#include \"itkImageRegionConstIteratorWithIndex.h\"\n#include \"itkImportImageFilter.h\"\n#include \"itkPointSet.h\"\n#include \"itkTimeProbe.h\"\n#include \"itkVector.h\"\n#include \"itkVectorIndexSelectionCastImageFilter.h\"\n\n#include \"ReadWriteData.h\"\n\nnamespace ants\n{\ntemplate <unsigned int ImageDimension>\nint SuperResolution( unsigned int argc, char *argv[] )\n{\n\n typedef float RealType;\n typedef itk::Image<RealType, ImageDimension> ImageType;\n\n typedef itk::Vector<RealType, 1> ScalarType;\n typedef itk::Image<ScalarType, ImageDimension> ScalarImageType;\n typedef itk::PointSet<ScalarType, ImageDimension> PointSetType;\n typedef itk::BSplineScatteredDataPointSetToImageFilter\n <PointSetType, ScalarImageType> BSplineFilterType;\n\n typename ImageType::Pointer domainImage = ITK_NULLPTR;\n ReadImage<ImageType>( domainImage, argv[3] );\n\n typename BSplineFilterType::Pointer bspliner = BSplineFilterType::New();\n\n typename PointSetType::Pointer bsplinePoints = PointSetType::New();\n bsplinePoints->Initialize();\n\n typename BSplineFilterType::WeightsContainerType::Pointer weights =\n BSplineFilterType::WeightsContainerType::New();\n weights->Initialize();\n\n unsigned int splineOrder = 3;\n typename BSplineFilterType::ArrayType numberOfLevels;\n typename BSplineFilterType::ArrayType ncps;\n\n std::vector<unsigned int> nlevels = ConvertVector<unsigned int>( std::string( argv[5] ) );\n if ( nlevels.size() == 1 )\n {\n numberOfLevels.Fill( nlevels[0] );\n }\n else if ( nlevels.size() == ImageDimension )\n {\n for ( unsigned int d = 0; d < ImageDimension; d++ )\n {\n numberOfLevels[d] = nlevels[d];\n }\n }\n else\n {\n std::cerr << \"Invalid nlevels format.\" << std::endl;\n return EXIT_FAILURE;\n }\n\n std::vector<unsigned int> meshSize = ConvertVector<unsigned int>( std::string( argv[4] ) );\n if ( meshSize.size() == 1 )\n {\n ncps.Fill( meshSize[0] + splineOrder );\n }\n else if ( meshSize.size() == ImageDimension )\n {\n for ( unsigned int d = 0; d < ImageDimension; d++ )\n {\n ncps[d] = meshSize[d] + splineOrder;\n }\n }\n else\n {\n std::cerr << \"Invalid ncps format.\" << std::endl;\n return EXIT_FAILURE;\n }\n\n typename ScalarImageType::DirectionType identity;\n identity.SetIdentity();\n\n const typename ScalarImageType::RegionType & bufferedRegion = domainImage->GetBufferedRegion();\n const itk::SizeValueType numberOfPixels = bufferedRegion.GetNumberOfPixels();\n const bool filterHandlesMemory = false;\n\n typedef itk::ImportImageFilter<RealType, ImageDimension> ImporterType;\n typename ImporterType::Pointer importer = ImporterType::New();\n importer->SetImportPointer( domainImage->GetBufferPointer(), numberOfPixels, filterHandlesMemory );\n importer->SetRegion( domainImage->GetBufferedRegion() );\n importer->SetOrigin( domainImage->GetOrigin() );\n importer->SetSpacing( domainImage->GetSpacing() );\n importer->SetDirection( identity );\n importer->Update();\n\n typename ImageType::IndexType domainBeginIndex = domainImage->GetRequestedRegion().GetIndex();\n typename ImageType::IndexType domainEndIndex;\n for( unsigned int d = 0; d < ImageDimension; d++ )\n {\n domainEndIndex[d] = domainBeginIndex[d] + domainImage->GetRequestedRegion().GetSize()[d] - 1;\n }\n\n const typename ImporterType::OutputImageType * parametricDomainImage = importer->GetOutput();\n\n unsigned int N = 0;\n for( unsigned int n = 6; n < argc; n++ )\n {\n typename ImageType::Pointer inputImage = ITK_NULLPTR;\n ReadImage<ImageType>( inputImage, argv[n] );\n\n itk::ImageRegionConstIteratorWithIndex<ImageType> It( inputImage, inputImage->GetRequestedRegion() );\n for( It.GoToBegin(); !It.IsAtEnd(); ++It )\n {\n typename ImageType::PointType imagePoint;\n inputImage->TransformIndexToPhysicalPoint( It.GetIndex(), imagePoint );\n\n itk::ContinuousIndex<RealType, ImageDimension> cidx;\n bool isInside = domainImage->TransformPhysicalPointToContinuousIndex( imagePoint, cidx );\n\n if( isInside )\n {\n for( unsigned int d = 0; d < ImageDimension; d++ )\n {\n if( cidx[d] <= domainBeginIndex[d] || cidx[d] >= domainEndIndex[d] )\n {\n isInside = false;\n break;\n }\n }\n }\n\n if( !isInside )\n {\n continue;\n }\n\n\/\/ domainImage->SetPixel( index, 1 );\n\n parametricDomainImage->TransformContinuousIndexToPhysicalPoint( cidx, imagePoint );\n\n ScalarType scalar;\n scalar[0] = It.Get();\n\n bsplinePoints->SetPointData( N, scalar );\n bsplinePoints->SetPoint( N, imagePoint );\n weights->InsertElement( N, 1 );\n\n N++;\n }\n }\n\n std::cout << bsplinePoints->GetNumberOfPoints() << std::endl;\n\n itk::TimeProbe timer;\n timer.Start();\n\n typename ScalarImageType::PointType parametricOrigin = domainImage->GetOrigin();\n for( unsigned int d = 0; d < ImageDimension; d++ )\n {\n parametricOrigin[d] += (\n domainImage->GetSpacing()[d] *\n domainImage->GetLargestPossibleRegion().GetIndex()[d] );\n }\n\n bspliner->SetOrigin( parametricOrigin );\n bspliner->SetSpacing( domainImage->GetSpacing() );\n bspliner->SetSize( domainImage->GetRequestedRegion().GetSize() );\n bspliner->SetDirection( domainImage->GetDirection() );\n bspliner->SetGenerateOutputImage( true );\n bspliner->SetNumberOfLevels( numberOfLevels );\n bspliner->SetSplineOrder( splineOrder );\n bspliner->SetNumberOfControlPoints( ncps );\n bspliner->SetInput( bsplinePoints );\n bspliner->SetPointWeights( weights );\n bspliner->Update();\n\n timer.Stop();\n\n std::cout << \"Elapsed Time: \" << timer.GetMean() << std::endl;\n\n typedef itk::VectorIndexSelectionCastImageFilter<ScalarImageType, ImageType> SelectorType;\n typename SelectorType::Pointer selector = SelectorType::New();\n selector->SetInput( bspliner->GetOutput() );\n selector->SetIndex( 0 );\n selector->Update();\n\n WriteImage<ImageType>( selector->GetOutput(), argv[2] );\n\n return EXIT_SUCCESS;\n}\n\n\/\/ entry point for the library; parameter 'args' is equivalent to 'argv' in (argc,argv) of commandline parameters to\n\/\/ 'main()'\nint SuperResolution( std::vector<std::string> args, std::ostream* \/*out_stream = NULL *\/ )\n{\n \/\/ put the arguments coming in as 'args' into standard (argc,argv) format;\n \/\/ 'args' doesn't have the command name as first, argument, so add it manually;\n \/\/ 'args' may have adjacent arguments concatenated into one argument,\n \/\/ which the parser should handle\n args.insert( args.begin(), \"SuperResolution\" );\n\n int argc = args.size();\n char* * argv = new char *[args.size() + 1];\n for( unsigned int i = 0; i < args.size(); ++i )\n {\n \/\/ allocate space for the string plus a null character\n argv[i] = new char[args[i].length() + 1];\n std::strncpy( argv[i], args[i].c_str(), args[i].length() );\n \/\/ place the null character in the end\n argv[i][args[i].length()] = '\\0';\n }\n argv[argc] = ITK_NULLPTR;\n \/\/ class to automatically cleanup argv upon destruction\n class Cleanup_argv\n {\npublic:\n Cleanup_argv( char* * argv_, int argc_plus_one_ ) : argv( argv_ ), argc_plus_one( argc_plus_one_ )\n {\n }\n\n ~Cleanup_argv()\n {\n for( unsigned int i = 0; i < argc_plus_one; ++i )\n {\n delete[] argv[i];\n }\n delete[] argv;\n }\n\nprivate:\n char* * argv;\n unsigned int argc_plus_one;\n };\n Cleanup_argv cleanup_argv( argv, argc + 1 );\n\n \/\/ antscout->set_stream( out_stream );\n\n if ( argc < 7 )\n {\n std::cerr << argv[0] << \" imageDimension outputImage domainImage meshSize numberOfLevels inputImage1 ... inputImageN\" << std::endl;\n\n if( argc >= 2 &&\n ( std::string( argv[1] ) == std::string(\"--help\") || std::string( argv[1] ) == std::string(\"-h\") ) )\n {\n return EXIT_SUCCESS;\n }\n return EXIT_FAILURE;\n }\n\n const int ImageDimension = static_cast<int>( atoi( argv[1] ) );\n\n switch( ImageDimension )\n {\n case 2:\n return SuperResolution<2>( argc, argv );\n break;\n case 3:\n return SuperResolution<3>( argc, argv );\n break;\n case 4:\n return SuperResolution<4>( argc, argv );\n break;\n default:\n std::cerr << \"Unsupported dimension\" << std::endl;\n exit( EXIT_FAILURE );\n }\n return EXIT_SUCCESS;\n}\n} \/\/ namespace ants\n\n<commit_msg>BUG: Didn't get phyiscal domain correct.<commit_after>#include \"antsUtilities.h\"\n#include <algorithm>\n\n#include \"itkBSplineScatteredDataPointSetToImageFilter.h\"\n#include \"itkContinuousIndex.h\"\n#include \"itkImageRegionConstIteratorWithIndex.h\"\n#include \"itkImportImageFilter.h\"\n#include \"itkPointSet.h\"\n#include \"itkTimeProbe.h\"\n#include \"itkVector.h\"\n#include \"itkVectorIndexSelectionCastImageFilter.h\"\n\n#include \"ReadWriteData.h\"\n\nnamespace ants\n{\ntemplate <unsigned int ImageDimension>\nint SuperResolution( unsigned int argc, char *argv[] )\n{\n\n typedef float RealType;\n typedef itk::Image<RealType, ImageDimension> ImageType;\n\n typedef itk::Vector<RealType, 1> ScalarType;\n typedef itk::Image<ScalarType, ImageDimension> ScalarImageType;\n typedef itk::PointSet<ScalarType, ImageDimension> PointSetType;\n typedef itk::BSplineScatteredDataPointSetToImageFilter\n <PointSetType, ScalarImageType> BSplineFilterType;\n\n typename ImageType::Pointer domainImage = ITK_NULLPTR;\n ReadImage<ImageType>( domainImage, argv[3] );\n\n typename BSplineFilterType::Pointer bspliner = BSplineFilterType::New();\n\n typename PointSetType::Pointer bsplinePoints = PointSetType::New();\n bsplinePoints->Initialize();\n\n typename BSplineFilterType::WeightsContainerType::Pointer weights =\n BSplineFilterType::WeightsContainerType::New();\n weights->Initialize();\n\n unsigned int splineOrder = 3;\n typename BSplineFilterType::ArrayType numberOfLevels;\n typename BSplineFilterType::ArrayType ncps;\n\n std::vector<unsigned int> nlevels = ConvertVector<unsigned int>( std::string( argv[5] ) );\n if ( nlevels.size() == 1 )\n {\n numberOfLevels.Fill( nlevels[0] );\n }\n else if ( nlevels.size() == ImageDimension )\n {\n for ( unsigned int d = 0; d < ImageDimension; d++ )\n {\n numberOfLevels[d] = nlevels[d];\n }\n }\n else\n {\n std::cerr << \"Invalid nlevels format.\" << std::endl;\n return EXIT_FAILURE;\n }\n\n std::vector<unsigned int> meshSize = ConvertVector<unsigned int>( std::string( argv[4] ) );\n if ( meshSize.size() == 1 )\n {\n ncps.Fill( meshSize[0] + splineOrder );\n }\n else if ( meshSize.size() == ImageDimension )\n {\n for ( unsigned int d = 0; d < ImageDimension; d++ )\n {\n ncps[d] = meshSize[d] + splineOrder;\n }\n }\n else\n {\n std::cerr << \"Invalid ncps format.\" << std::endl;\n return EXIT_FAILURE;\n }\n\n typename ScalarImageType::DirectionType identity;\n identity.SetIdentity();\n\n const typename ScalarImageType::RegionType & bufferedRegion = domainImage->GetBufferedRegion();\n const itk::SizeValueType numberOfPixels = bufferedRegion.GetNumberOfPixels();\n const bool filterHandlesMemory = false;\n\n typedef itk::ImportImageFilter<RealType, ImageDimension> ImporterType;\n typename ImporterType::Pointer importer = ImporterType::New();\n importer->SetImportPointer( domainImage->GetBufferPointer(), numberOfPixels, filterHandlesMemory );\n importer->SetRegion( domainImage->GetBufferedRegion() );\n importer->SetOrigin( domainImage->GetOrigin() );\n importer->SetSpacing( domainImage->GetSpacing() );\n importer->SetDirection( identity );\n importer->Update();\n\n typename ImageType::IndexType domainBeginIndex = domainImage->GetRequestedRegion().GetIndex();\n typename ImageType::IndexType domainEndIndex;\n for( unsigned int d = 0; d < ImageDimension; d++ )\n {\n domainEndIndex[d] = domainBeginIndex[d] + domainImage->GetRequestedRegion().GetSize()[d] - 1;\n }\n\n const typename ImporterType::OutputImageType * parametricDomainImage = importer->GetOutput();\n\n unsigned int N = 0;\n for( unsigned int n = 6; n < argc; n++ )\n {\n typename ImageType::Pointer inputImage = ITK_NULLPTR;\n ReadImage<ImageType>( inputImage, argv[n] );\n\n itk::ImageRegionConstIteratorWithIndex<ImageType> It( inputImage, inputImage->GetRequestedRegion() );\n for( It.GoToBegin(); !It.IsAtEnd(); ++It )\n {\n typename ImageType::PointType imagePoint;\n inputImage->TransformIndexToPhysicalPoint( It.GetIndex(), imagePoint );\n\n itk::ContinuousIndex<RealType, ImageDimension> cidx;\n bool isInside = domainImage->TransformPhysicalPointToContinuousIndex( imagePoint, cidx );\n\n if( isInside )\n {\n for( unsigned int d = 0; d < ImageDimension; d++ )\n {\n if( cidx[d] <= domainBeginIndex[d] || cidx[d] >= domainEndIndex[d] )\n {\n isInside = false;\n break;\n }\n }\n }\n\n if( !isInside )\n {\n continue;\n }\n\n\/\/ domainImage->SetPixel( index, 1 );\n\n parametricDomainImage->TransformContinuousIndexToPhysicalPoint( cidx, imagePoint );\n\n ScalarType scalar;\n scalar[0] = It.Get();\n\n bsplinePoints->SetPointData( N, scalar );\n bsplinePoints->SetPoint( N, imagePoint );\n weights->InsertElement( N, 1 );\n\n N++;\n }\n }\n\n itk::TimeProbe timer;\n timer.Start();\n\n typename ScalarImageType::PointType parametricOrigin = domainImage->GetOrigin();\n for( unsigned int d = 0; d < ImageDimension; d++ )\n {\n parametricOrigin[d] += (\n domainImage->GetSpacing()[d] *\n domainImage->GetLargestPossibleRegion().GetIndex()[d] );\n }\n\n bspliner->SetOrigin( parametricOrigin );\n bspliner->SetSpacing( domainImage->GetSpacing() );\n bspliner->SetSize( domainImage->GetRequestedRegion().GetSize() );\n bspliner->SetDirection( domainImage->GetDirection() );\n bspliner->SetGenerateOutputImage( true );\n bspliner->SetNumberOfLevels( numberOfLevels );\n bspliner->SetSplineOrder( splineOrder );\n bspliner->SetNumberOfControlPoints( ncps );\n bspliner->SetInput( bsplinePoints );\n bspliner->SetPointWeights( weights );\n bspliner->Update();\n\n timer.Stop();\n\n std::cout << \"Elapsed Time: \" << timer.GetMean() << std::endl;\n\n typedef itk::VectorIndexSelectionCastImageFilter<ScalarImageType, ImageType> SelectorType;\n typename SelectorType::Pointer selector = SelectorType::New();\n selector->SetInput( bspliner->GetOutput() );\n selector->SetIndex( 0 );\n selector->Update();\n\n WriteImage<ImageType>( selector->GetOutput(), argv[2] );\n\n return EXIT_SUCCESS;\n}\n\n\/\/ entry point for the library; parameter 'args' is equivalent to 'argv' in (argc,argv) of commandline parameters to\n\/\/ 'main()'\nint SuperResolution( std::vector<std::string> args, std::ostream* \/*out_stream = NULL *\/ )\n{\n \/\/ put the arguments coming in as 'args' into standard (argc,argv) format;\n \/\/ 'args' doesn't have the command name as first, argument, so add it manually;\n \/\/ 'args' may have adjacent arguments concatenated into one argument,\n \/\/ which the parser should handle\n args.insert( args.begin(), \"SuperResolution\" );\n\n int argc = args.size();\n char* * argv = new char *[args.size() + 1];\n for( unsigned int i = 0; i < args.size(); ++i )\n {\n \/\/ allocate space for the string plus a null character\n argv[i] = new char[args[i].length() + 1];\n std::strncpy( argv[i], args[i].c_str(), args[i].length() );\n \/\/ place the null character in the end\n argv[i][args[i].length()] = '\\0';\n }\n argv[argc] = ITK_NULLPTR;\n \/\/ class to automatically cleanup argv upon destruction\n class Cleanup_argv\n {\npublic:\n Cleanup_argv( char* * argv_, int argc_plus_one_ ) : argv( argv_ ), argc_plus_one( argc_plus_one_ )\n {\n }\n\n ~Cleanup_argv()\n {\n for( unsigned int i = 0; i < argc_plus_one; ++i )\n {\n delete[] argv[i];\n }\n delete[] argv;\n }\n\nprivate:\n char* * argv;\n unsigned int argc_plus_one;\n };\n Cleanup_argv cleanup_argv( argv, argc + 1 );\n\n \/\/ antscout->set_stream( out_stream );\n\n if ( argc < 7 )\n {\n std::cerr << argv[0] << \" imageDimension outputImage domainImage meshSize numberOfLevels inputImage1 ... inputImageN\" << std::endl;\n\n if( argc >= 2 &&\n ( std::string( argv[1] ) == std::string(\"--help\") || std::string( argv[1] ) == std::string(\"-h\") ) )\n {\n return EXIT_SUCCESS;\n }\n return EXIT_FAILURE;\n }\n\n const int ImageDimension = static_cast<int>( atoi( argv[1] ) );\n\n switch( ImageDimension )\n {\n case 2:\n return SuperResolution<2>( argc, argv );\n break;\n case 3:\n return SuperResolution<3>( argc, argv );\n break;\n case 4:\n return SuperResolution<4>( argc, argv );\n break;\n default:\n std::cerr << \"Unsupported dimension\" << std::endl;\n exit( EXIT_FAILURE );\n }\n return EXIT_SUCCESS;\n}\n} \/\/ namespace ants\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright 2011 Google Inc.\n *\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n *\/\n\n#include \"SkEndian.h\"\n#include \"SkFontStream.h\"\n#include \"SkStream.h\"\n\nstruct SkSFNTHeader {\n uint32_t fVersion;\n uint16_t fNumTables;\n uint16_t fSearchRange;\n uint16_t fEntrySelector;\n uint16_t fRangeShift;\n};\n\nstruct SkTTCFHeader {\n uint32_t fTag;\n uint32_t fVersion;\n uint32_t fNumOffsets;\n uint32_t fOffset0; \/\/ the first of N (fNumOffsets)\n};\n\nunion SkSharedTTHeader {\n SkSFNTHeader fSingle;\n SkTTCFHeader fCollection;\n};\n\nstruct SkSFNTDirEntry {\n uint32_t fTag;\n uint32_t fChecksum;\n uint32_t fOffset;\n uint32_t fLength;\n};\n\nstatic bool read(SkStream* stream, void* buffer, size_t amount) {\n return stream->read(buffer, amount) == amount;\n}\n\nstatic bool skip(SkStream* stream, size_t amount) {\n return stream->skip(amount) == amount;\n}\n\n\/** Return the number of tables, or if this is a TTC (collection), return the\n number of tables in the first element of the collection. In either case,\n if offsetToDir is not-null, set it to the offset to the beginning of the\n table headers (SkSFNTDirEntry), relative to the start of the stream.\n\n On an error, return 0 for number of tables, and ignore offsetToDir\n *\/\nstatic int count_tables(SkStream* stream, int ttcIndex, size_t* offsetToDir) {\n SkASSERT(ttcIndex >= 0);\n\n SkAutoSMalloc<1024> storage(sizeof(SkSharedTTHeader));\n SkSharedTTHeader* header = (SkSharedTTHeader*)storage.get();\n\n if (!read(stream, header, sizeof(SkSharedTTHeader))) {\n return 0;\n }\n\n \/\/ by default, SkSFNTHeader is at the start of the stream\n size_t offset = 0;\n\n \/\/ if we're really a collection, the first 4-bytes will be 'ttcf'\n uint32_t tag = SkEndian_SwapBE32(header->fCollection.fTag);\n if (SkSetFourByteTag('t', 't', 'c', 'f') == tag) {\n unsigned count = SkEndian_SwapBE32(header->fCollection.fNumOffsets);\n if ((unsigned)ttcIndex >= count) {\n return 0;\n }\n\n if (ttcIndex > 0) { \/\/ need to read more of the shared header\n stream->rewind();\n size_t amount = sizeof(SkSharedTTHeader) + ttcIndex * sizeof(uint32_t);\n header = (SkSharedTTHeader*)storage.reset(amount);\n if (!read(stream, header, amount)) {\n return 0;\n }\n }\n \/\/ this is the offset to the local SkSFNTHeader\n offset = SkEndian_SwapBE32((&header->fCollection.fOffset0)[ttcIndex]);\n stream->rewind();\n if (!skip(stream, offset)) {\n return 0;\n }\n if (!read(stream, header, sizeof(SkSFNTHeader))) {\n return 0;\n }\n }\n\n if (offsetToDir) {\n \/\/ add the size of the header, so we will point to the DirEntries\n *offsetToDir = offset + sizeof(SkSFNTHeader);\n }\n return SkEndian_SwapBE16(header->fSingle.fNumTables);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstruct SfntHeader {\n SfntHeader() : fCount(0), fDir(NULL) {}\n ~SfntHeader() { sk_free(fDir); }\n\n \/** If it returns true, then fCount and fDir are properly initialized.\n Note: fDir will point to the raw array of SkSFNTDirEntry values,\n meaning they will still be in the file's native endianness (BE).\n\n fDir will be automatically freed when this object is destroyed\n *\/\n bool init(SkStream* stream, int ttcIndex) {\n stream->rewind();\n\n size_t offsetToDir;\n fCount = count_tables(stream, ttcIndex, &offsetToDir);\n if (0 == fCount) {\n return false;\n }\n\n stream->rewind();\n if (!skip(stream, offsetToDir)) {\n return false;\n }\n\n size_t size = fCount * sizeof(SkSFNTDirEntry);\n fDir = reinterpret_cast<SkSFNTDirEntry*>(sk_malloc_throw(size));\n return read(stream, fDir, size);\n }\n\n int fCount;\n SkSFNTDirEntry* fDir;\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nint SkFontStream::CountTTCEntries(SkStream* stream) {\n stream->rewind();\n\n SkSharedTTHeader shared;\n if (!read(stream, &shared, sizeof(shared))) {\n return 0;\n }\n\n \/\/ if we're really a collection, the first 4-bytes will be 'ttcf'\n uint32_t tag = SkEndian_SwapBE32(shared.fCollection.fTag);\n if (SkSetFourByteTag('t', 't', 'c', 'f') == tag) {\n return SkEndian_SwapBE32(shared.fCollection.fNumOffsets);\n } else {\n return 1; \/\/ normal 'sfnt' has 1 dir entry\n }\n}\n\nint SkFontStream::GetTableTags(SkStream* stream, int ttcIndex,\n SkFontTableTag tags[]) {\n SfntHeader header;\n if (!header.init(stream, ttcIndex)) {\n return 0;\n }\n\n if (tags) {\n for (int i = 0; i < header.fCount; i++) {\n tags[i] = SkEndian_SwapBE32(header.fDir[i].fTag);\n }\n }\n return header.fCount;\n}\n\nsize_t SkFontStream::GetTableData(SkStream* stream, int ttcIndex,\n SkFontTableTag tag,\n size_t offset, size_t length, void* data) {\n SfntHeader header;\n if (!header.init(stream, ttcIndex)) {\n return 0;\n }\n\n for (int i = 0; i < header.fCount; i++) {\n if (SkEndian_SwapBE32(header.fDir[i].fTag) == tag) {\n size_t realOffset = SkEndian_SwapBE32(header.fDir[i].fOffset);\n size_t realLength = SkEndian_SwapBE32(header.fDir[i].fLength);\n \/\/ now sanity check the caller's offset\/length\n if (offset >= realLength) {\n return 0;\n }\n \/\/ if the caller is trusting the length from the file, then a\n \/\/ hostile file might choose a value which would overflow offset +\n \/\/ length.\n if (offset + length < offset) {\n return 0;\n }\n if (length > realLength - offset) {\n length = realLength - offset;\n }\n if (data) {\n \/\/ skip the stream to the part of the table we want to copy from\n stream->rewind();\n size_t bytesToSkip = realOffset + offset;\n if (skip(stream, bytesToSkip)) {\n return 0;\n }\n if (!read(stream, data, length)) {\n return 0;\n }\n }\n return length;\n }\n }\n return 0;\n}\n<commit_msg>fix missing ! typo when we switched to skip() helper function. caught by linux unittests.<commit_after>\/*\n * Copyright 2011 Google Inc.\n *\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n *\/\n\n#include \"SkEndian.h\"\n#include \"SkFontStream.h\"\n#include \"SkStream.h\"\n\nstruct SkSFNTHeader {\n uint32_t fVersion;\n uint16_t fNumTables;\n uint16_t fSearchRange;\n uint16_t fEntrySelector;\n uint16_t fRangeShift;\n};\n\nstruct SkTTCFHeader {\n uint32_t fTag;\n uint32_t fVersion;\n uint32_t fNumOffsets;\n uint32_t fOffset0; \/\/ the first of N (fNumOffsets)\n};\n\nunion SkSharedTTHeader {\n SkSFNTHeader fSingle;\n SkTTCFHeader fCollection;\n};\n\nstruct SkSFNTDirEntry {\n uint32_t fTag;\n uint32_t fChecksum;\n uint32_t fOffset;\n uint32_t fLength;\n};\n\nstatic bool read(SkStream* stream, void* buffer, size_t amount) {\n return stream->read(buffer, amount) == amount;\n}\n\nstatic bool skip(SkStream* stream, size_t amount) {\n return stream->skip(amount) == amount;\n}\n\n\/** Return the number of tables, or if this is a TTC (collection), return the\n number of tables in the first element of the collection. In either case,\n if offsetToDir is not-null, set it to the offset to the beginning of the\n table headers (SkSFNTDirEntry), relative to the start of the stream.\n\n On an error, return 0 for number of tables, and ignore offsetToDir\n *\/\nstatic int count_tables(SkStream* stream, int ttcIndex, size_t* offsetToDir) {\n SkASSERT(ttcIndex >= 0);\n\n SkAutoSMalloc<1024> storage(sizeof(SkSharedTTHeader));\n SkSharedTTHeader* header = (SkSharedTTHeader*)storage.get();\n\n if (!read(stream, header, sizeof(SkSharedTTHeader))) {\n return 0;\n }\n\n \/\/ by default, SkSFNTHeader is at the start of the stream\n size_t offset = 0;\n\n \/\/ if we're really a collection, the first 4-bytes will be 'ttcf'\n uint32_t tag = SkEndian_SwapBE32(header->fCollection.fTag);\n if (SkSetFourByteTag('t', 't', 'c', 'f') == tag) {\n unsigned count = SkEndian_SwapBE32(header->fCollection.fNumOffsets);\n if ((unsigned)ttcIndex >= count) {\n return 0;\n }\n\n if (ttcIndex > 0) { \/\/ need to read more of the shared header\n stream->rewind();\n size_t amount = sizeof(SkSharedTTHeader) + ttcIndex * sizeof(uint32_t);\n header = (SkSharedTTHeader*)storage.reset(amount);\n if (!read(stream, header, amount)) {\n return 0;\n }\n }\n \/\/ this is the offset to the local SkSFNTHeader\n offset = SkEndian_SwapBE32((&header->fCollection.fOffset0)[ttcIndex]);\n stream->rewind();\n if (!skip(stream, offset)) {\n return 0;\n }\n if (!read(stream, header, sizeof(SkSFNTHeader))) {\n return 0;\n }\n }\n\n if (offsetToDir) {\n \/\/ add the size of the header, so we will point to the DirEntries\n *offsetToDir = offset + sizeof(SkSFNTHeader);\n }\n return SkEndian_SwapBE16(header->fSingle.fNumTables);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstruct SfntHeader {\n SfntHeader() : fCount(0), fDir(NULL) {}\n ~SfntHeader() { sk_free(fDir); }\n\n \/** If it returns true, then fCount and fDir are properly initialized.\n Note: fDir will point to the raw array of SkSFNTDirEntry values,\n meaning they will still be in the file's native endianness (BE).\n\n fDir will be automatically freed when this object is destroyed\n *\/\n bool init(SkStream* stream, int ttcIndex) {\n stream->rewind();\n\n size_t offsetToDir;\n fCount = count_tables(stream, ttcIndex, &offsetToDir);\n if (0 == fCount) {\n return false;\n }\n\n stream->rewind();\n if (!skip(stream, offsetToDir)) {\n return false;\n }\n\n size_t size = fCount * sizeof(SkSFNTDirEntry);\n fDir = reinterpret_cast<SkSFNTDirEntry*>(sk_malloc_throw(size));\n return read(stream, fDir, size);\n }\n\n int fCount;\n SkSFNTDirEntry* fDir;\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nint SkFontStream::CountTTCEntries(SkStream* stream) {\n stream->rewind();\n\n SkSharedTTHeader shared;\n if (!read(stream, &shared, sizeof(shared))) {\n return 0;\n }\n\n \/\/ if we're really a collection, the first 4-bytes will be 'ttcf'\n uint32_t tag = SkEndian_SwapBE32(shared.fCollection.fTag);\n if (SkSetFourByteTag('t', 't', 'c', 'f') == tag) {\n return SkEndian_SwapBE32(shared.fCollection.fNumOffsets);\n } else {\n return 1; \/\/ normal 'sfnt' has 1 dir entry\n }\n}\n\nint SkFontStream::GetTableTags(SkStream* stream, int ttcIndex,\n SkFontTableTag tags[]) {\n SfntHeader header;\n if (!header.init(stream, ttcIndex)) {\n return 0;\n }\n\n if (tags) {\n for (int i = 0; i < header.fCount; i++) {\n tags[i] = SkEndian_SwapBE32(header.fDir[i].fTag);\n }\n }\n return header.fCount;\n}\n\nsize_t SkFontStream::GetTableData(SkStream* stream, int ttcIndex,\n SkFontTableTag tag,\n size_t offset, size_t length, void* data) {\n SfntHeader header;\n if (!header.init(stream, ttcIndex)) {\n return 0;\n }\n\n for (int i = 0; i < header.fCount; i++) {\n if (SkEndian_SwapBE32(header.fDir[i].fTag) == tag) {\n size_t realOffset = SkEndian_SwapBE32(header.fDir[i].fOffset);\n size_t realLength = SkEndian_SwapBE32(header.fDir[i].fLength);\n \/\/ now sanity check the caller's offset\/length\n if (offset >= realLength) {\n return 0;\n }\n \/\/ if the caller is trusting the length from the file, then a\n \/\/ hostile file might choose a value which would overflow offset +\n \/\/ length.\n if (offset + length < offset) {\n return 0;\n }\n if (length > realLength - offset) {\n length = realLength - offset;\n }\n if (data) {\n \/\/ skip the stream to the part of the table we want to copy from\n stream->rewind();\n size_t bytesToSkip = realOffset + offset;\n if (!skip(stream, bytesToSkip)) {\n return 0;\n }\n if (!read(stream, data, length)) {\n return 0;\n }\n }\n return length;\n }\n }\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\n#include <iostream>\n#include <memory>\n#include <ctime>\n#include <math.h>\n\n#include \"dynamicmodel.h\"\n#include \"history.h\"\n#include \"modelstate.h\"\n#include \"config.h\"\n#include \"constants.h\"\n#include \"logging.h\"\n#include \"meteo.h\"\n#include \"surfacedensity.h\"\n#include \"metamorphism.h\"\n#include \"compaction.h\"\n#include \"heatsolver.h\"\n#include \"utils.h\"\n\nnamespace DSM{ \n\nDynamicModel::DynamicModel() : _nt(0) { }\n\nvoid DynamicModel::run(){\n \/* MAIN DRIVER ROUTINE\n initializes submodels, runs timeloop and writes output *\/\n const char * option_name;\n\n \/* read time step *\/\n option_name = \"general:dt\";\n _dt = (long) config.getInt(option_name, true, 1, (int)1e9, -1);\n const long dt_per_year = sec_in_year \/ _dt;\n logger << \"INFO: dt_per_year = \" << dt_per_year << std::endl;\n\n \/* read stopping criteria *\/\n option_name = \"stopping_criteria:which_stop\";\n const int which_stop = config.getInt(option_name, false, 0, 5, 0);\n bool stop_year = false;\n bool stop_dens = false;\n bool stop_depth = false;\n switch (which_stop) {\n case 0 : stop_year = true; break;\n case 1 : stop_dens = true; break;\n case 2 : stop_depth = true; break;\n case 3 : stop_year = true; stop_dens = true; break;\n case 4 : stop_year = true; stop_depth = true; break;\n case 5 : stop_year = true; stop_dens = true; stop_depth = true; break;\n default : \n logger << \"ERROR: unknown value: \" << which_stop << \" for config option \" << option_name << std::endl;\n std::abort();\n }\n int max_years;\n double max_dens, max_depth;\n if (stop_year) {\n option_name = \"stopping_criteria:years\";\n max_years = config.getInt(option_name, true, 1, (int)1e9, -1);\n logger << \"INFO: max_years = \" << max_years << std::endl;\n }\n if (stop_dens) {\n option_name = \"stopping_criteria:dens\";\n max_dens = config.getDouble(option_name, true, 1., 1000., -1.);\n logger << \"INFO: max_dens = \" << max_dens << std::endl;\n }\n if (stop_depth) {\n option_name = \"stopping_criteria:depth\";\n max_depth = config.getDouble(option_name, true, 1., 1000., -1.);\n logger << \"INFO: max_depth = \" << max_depth << std::endl;\n }\n\n \/* setup submodels *\/\n std::unique_ptr<Meteo> meteo = instantiate_meteo(*this);\n std::unique_ptr<SurfaceDensity> surf = instantiate_surfacedensity(*meteo);\n ModelState mstate(*meteo, *surf, *this);\n std::unique_ptr<Metamorphism> mm = instantiate_metamorphism(mstate, *this);\n std::unique_ptr<Compaction> comp = instantiate_compaction(mstate, *this);\n std::unique_ptr<HeatSolver> heat = instantiate_heatsolver(mstate, *this);\n History history(mstate);\n \n \/* print some meteo statistics *\/\n logger << \"INFO: initial surface temperature is: \" << meteo->surfaceTemperature() << std::endl;\n logger << \"INFO: initial surface wind is: \" << meteo->surfaceWind() << std::endl;\n logger << \"INFO: initial accumulation rate is: \" << meteo->accumulationRate() << std::endl;\n\n \/* start of the main time loop *\/\n std::clock_t start;\n int kYear = 0;\n while( \n (stop_year ? kYear < max_years : true)\n && (stop_dens ? !mstate.hasReachedDensity(max_dens) : true)\n && (stop_depth ? mstate.totalDepth() < max_depth : true) ){\n\n start = clock();\n for(int tstep = 0; tstep < dt_per_year; tstep++) {\n runTimeStep(mstate, *mm, *comp, *heat);\n history.update();\n }\n double elapsed = ((double)(clock() - start)) \/ CLOCKS_PER_SEC;\n\n logger << \"year=\" << kYear\n << \", Tmin=\" << mstate.minTemp() \n << \", Tmax=\" << mstate.maxTemp() \n << \", rho_max=\" << mstate.maxDens()\n << \", sec\/year=\" << elapsed \n << \", year\/hour=\" << 3600.\/elapsed << std::endl;\n kYear++; \n }\n mstate.printSummary();\n mstate.writeModelState();\n history.writeHistory();\n}\n\nvoid DynamicModel::runTimeStep(ModelState& mstate, Metamorphism& mm, Compaction& comp, HeatSolver& heat) {\n accumulate(mstate);\n mm.metamorphism();\n comp.compaction();\n doGridChecks(mstate);\n heat.heatdiffusion();\n _nt++;\n}\n\nvoid DynamicModel::doGridChecks(ModelState& mstate){\n \/* PERFORMS A NUMBER OF CHECKS ON THE CONSISTENCY AND EFFICIENCY OF THE GRID *\/\n\n \/* check minimum thickness, start with second layer (index N-2) *\/\n Grid& grid = mstate.getGrid();\n int i = grid.size()-2;\n while (i >= 0 ) { \/\/ Use while instead of for-loop as size may change during loop\n if (grid[i].dz < dzmin && mstate.gridsize() > 1){\n \/\/ Layer is too thin, combine with neighbor\n if (i == 0 || grid[i-1].dz > grid[i+1].dz ) {\n \/* CASE 1: Bottom layer can only be combined with the one above *\/\n \/* CASE 2: Determine smallest neighbour *\/\n mstate.combineLayers(grid[i+1], grid[i]);\n } else {\n mstate.combineLayers(grid[i-1], grid[i]);\n }\n grid.erase(grid.begin() + i); \/\/ NOTE: this is very inefficient\n }\n i--;\n }\n\n \/* check maximum layer thickness *\/\n Layer& top = grid.back();\n while (grid.back().dz > dzmax ) {\n \/* Split in unequal parts 4:1 \n all vars are identical except thickness *\/\n top = grid.back();\n Layer layer = top;\n layer.dz = top.dz\/5.;\n top.dz = top.dz * 4.\/5; \n grid.push_back(layer);\n }\n\n \/* remove bottom layers that have attained ice density *\/\n while(!grid.empty() && grid.front().dens > 900.) \n grid.erase(grid.begin());\n\n if (grid.empty()) {\n logger << \"ERROR: all layers turned to ice and were removed! This probably means that something is wrong with the compaction routine or the accumulation flux\" << std::endl;\n std::abort();\n }\n}\n\nvoid DynamicModel::accumulate(ModelState& mstate) {\n const double acc = mstate.getMeteo().accumulationRate();\n if ( doubles_equal(acc, 0.0)) {return;}\n if ( acc < 0.) {\n accumulateNegative(mstate);\n } else {\n accumulatePositive(mstate);\n }\n}\n\nvoid DynamicModel::accumulateNegative(ModelState& mstate) {\n Grid& grid = mstate.getGrid();\n const double evap = std::abs(mstate.getMeteo().accumulationRate() * 1e-3 * _dt);\n while (grid.back().dz * grid.back().dens \/ rho_w < evap) {\n if (grid.size() < 2) {\n logger << \"ERROR: not enough mass present for sublimation \/ evaporation\" << std::endl;\n std::abort();\n }\n logger << \"grid size = \" << grid.size() << std::endl;\n logger << \"DEBUG combining [ \" << (grid.end()[-2]).dz * (grid.end()[-2]).dens \/ rho_w << \", \"\n << grid.back().dz * grid.back().dens \/ rho_w << \" ] mm W.E. to meet \" << evap << \" mm W.E. of subl.\" << std::endl;\n mstate.combineLayers(grid.end()[-2], grid.back());\n grid.pop_back();\n }\n grid.back().dz -= evap * (rho_w\/grid.back().dens);\n\/\/ logger << \"DEBUG removing \" << evap * (rho_w\/grid.back().dens) << \" m from top layer\" << std::endl;\n if (grid.back().dz <= 0.) {\n logger << \"ERROR: negative layer thickness after evaporation (programmer error)\" << std::endl;\n std::abort();\n }\n return;\n}\n\nvoid DynamicModel::accumulatePositive(ModelState& mstate) {\n Grid& grid = mstate.getGrid();\n const double dens = mstate.getSurf().density();\n const double acc = mstate.getMeteo().accumulationRate() * 1e-3 * _dt; \/\/ convert from [mm\/s] to [m]\n const double dz = (rho_w\/dens) * acc;\n Layer& top = grid.back();\n\n \/\/ grain parameters are mass weighted\n const double U = mstate.getMeteo().surfaceWind();\n const double dfall = std::min(std::max(1.29-0.17*U, 0.20), 1.);\n const double sfall = std::min(std::max(0.08*U + 0.38, 0.5), 0.9);\n const double new_snow = dz*dens;\n const double old_snow = top.dz*top.dz;\n\n#ifdef DEBUG\n const double dold = top.dnd;\n const double sold = top.sph;\n#endif\n \n top.dnd = (top.dnd*old_snow + dfall*new_snow)\/(new_snow+old_snow);\n top.sph = (top.sph*old_snow + sfall*new_snow)\/(new_snow+old_snow);\n top.gs = (top.gs*old_snow + fs_gs*new_snow)\/(new_snow+old_snow);\n\n#ifdef DEBUG\n if (top.dnd > 1. || top.dnd < 0) {\n logger << \"DEBUG top.dnd = \" << top.dnd << \", U = \" << U << std::endl;\n logger << \"DEBUG dfall = \" << dfall << \", sfall = \" << sfall << std::endl;\n logger << \"DEBUG dold = \" << dold << \", sold = \" << sold << std::endl;\n logger << \"DEBUG new_snow = \" << new_snow << \", old_snow = \" << old_snow << std::endl;\n std::abort();\n }\n#endif\n\n top.dens = top.dz\/(top.dz+dz)*top.dens + dz\/(top.dz+dz)*dens;\n top.dz = top.dz + dz;\n\n}\n\n} \/\/ namespace\n<commit_msg>not enough mass for evaporation: warning i.s.o error<commit_after>\n#include <iostream>\n#include <memory>\n#include <ctime>\n#include <math.h>\n\n#include \"dynamicmodel.h\"\n#include \"history.h\"\n#include \"modelstate.h\"\n#include \"config.h\"\n#include \"constants.h\"\n#include \"logging.h\"\n#include \"meteo.h\"\n#include \"surfacedensity.h\"\n#include \"metamorphism.h\"\n#include \"compaction.h\"\n#include \"heatsolver.h\"\n#include \"utils.h\"\n\nnamespace DSM{ \n\nDynamicModel::DynamicModel() : _nt(0) { }\n\nvoid DynamicModel::run(){\n \/* MAIN DRIVER ROUTINE\n initializes submodels, runs timeloop and writes output *\/\n const char * option_name;\n\n \/* read time step *\/\n option_name = \"general:dt\";\n _dt = (long) config.getInt(option_name, true, 1, (int)1e9, -1);\n const long dt_per_year = sec_in_year \/ _dt;\n logger << \"INFO: dt_per_year = \" << dt_per_year << std::endl;\n\n \/* read stopping criteria *\/\n option_name = \"stopping_criteria:which_stop\";\n const int which_stop = config.getInt(option_name, false, 0, 5, 0);\n bool stop_year = false;\n bool stop_dens = false;\n bool stop_depth = false;\n switch (which_stop) {\n case 0 : stop_year = true; break;\n case 1 : stop_dens = true; break;\n case 2 : stop_depth = true; break;\n case 3 : stop_year = true; stop_dens = true; break;\n case 4 : stop_year = true; stop_depth = true; break;\n case 5 : stop_year = true; stop_dens = true; stop_depth = true; break;\n default : \n logger << \"ERROR: unknown value: \" << which_stop << \" for config option \" << option_name << std::endl;\n std::abort();\n }\n int max_years;\n double max_dens, max_depth;\n if (stop_year) {\n option_name = \"stopping_criteria:years\";\n max_years = config.getInt(option_name, true, 1, (int)1e9, -1);\n logger << \"INFO: max_years = \" << max_years << std::endl;\n }\n if (stop_dens) {\n option_name = \"stopping_criteria:dens\";\n max_dens = config.getDouble(option_name, true, 1., 1000., -1.);\n logger << \"INFO: max_dens = \" << max_dens << std::endl;\n }\n if (stop_depth) {\n option_name = \"stopping_criteria:depth\";\n max_depth = config.getDouble(option_name, true, 1., 1000., -1.);\n logger << \"INFO: max_depth = \" << max_depth << std::endl;\n }\n\n \/* setup submodels *\/\n std::unique_ptr<Meteo> meteo = instantiate_meteo(*this);\n std::unique_ptr<SurfaceDensity> surf = instantiate_surfacedensity(*meteo);\n ModelState mstate(*meteo, *surf, *this);\n std::unique_ptr<Metamorphism> mm = instantiate_metamorphism(mstate, *this);\n std::unique_ptr<Compaction> comp = instantiate_compaction(mstate, *this);\n std::unique_ptr<HeatSolver> heat = instantiate_heatsolver(mstate, *this);\n History history(mstate);\n \n \/* print some meteo statistics *\/\n logger << \"INFO: initial surface temperature is: \" << meteo->surfaceTemperature() << std::endl;\n logger << \"INFO: initial surface wind is: \" << meteo->surfaceWind() << std::endl;\n logger << \"INFO: initial accumulation rate is: \" << meteo->accumulationRate() << std::endl;\n\n \/* start of the main time loop *\/\n std::clock_t start;\n int kYear = 0;\n while( \n (stop_year ? kYear < max_years : true)\n && (stop_dens ? !mstate.hasReachedDensity(max_dens) : true)\n && (stop_depth ? mstate.totalDepth() < max_depth : true) ){\n\n start = clock();\n for(int tstep = 0; tstep < dt_per_year; tstep++) {\n runTimeStep(mstate, *mm, *comp, *heat);\n history.update();\n }\n double elapsed = ((double)(clock() - start)) \/ CLOCKS_PER_SEC;\n\n logger << \"year=\" << kYear\n << \", Tmin=\" << mstate.minTemp() \n << \", Tmax=\" << mstate.maxTemp() \n << \", rho_max=\" << mstate.maxDens()\n << \", sec\/year=\" << elapsed \n << \", year\/hour=\" << 3600.\/elapsed << std::endl;\n kYear++; \n }\n mstate.printSummary();\n mstate.writeModelState();\n history.writeHistory();\n}\n\nvoid DynamicModel::runTimeStep(ModelState& mstate, Metamorphism& mm, Compaction& comp, HeatSolver& heat) {\n accumulate(mstate);\n mm.metamorphism();\n comp.compaction();\n doGridChecks(mstate);\n heat.heatdiffusion();\n _nt++;\n}\n\nvoid DynamicModel::doGridChecks(ModelState& mstate){\n \/* PERFORMS A NUMBER OF CHECKS ON THE CONSISTENCY AND EFFICIENCY OF THE GRID *\/\n\n \/* check minimum thickness, start with second layer (index N-2) *\/\n Grid& grid = mstate.getGrid();\n int i = grid.size()-2;\n while (i >= 0 ) { \/\/ Use while instead of for-loop as size may change during loop\n if (grid[i].dz < dzmin && mstate.gridsize() > 1){\n \/\/ Layer is too thin, combine with neighbor\n if (i == 0 || grid[i-1].dz > grid[i+1].dz ) {\n \/* CASE 1: Bottom layer can only be combined with the one above *\/\n \/* CASE 2: Determine smallest neighbour *\/\n mstate.combineLayers(grid[i+1], grid[i]);\n } else {\n mstate.combineLayers(grid[i-1], grid[i]);\n }\n grid.erase(grid.begin() + i); \/\/ NOTE: this is very inefficient\n }\n i--;\n }\n\n \/* check maximum layer thickness *\/\n Layer& top = grid.back();\n while (grid.back().dz > dzmax ) {\n \/* Split in unequal parts 4:1 \n all vars are identical except thickness *\/\n top = grid.back();\n Layer layer = top;\n layer.dz = top.dz\/5.;\n top.dz = top.dz * 4.\/5; \n grid.push_back(layer);\n }\n\n \/* remove bottom layers that have attained ice density *\/\n while(!grid.empty() && grid.front().dens > 900.) \n grid.erase(grid.begin());\n\n if (grid.empty()) {\n logger << \"ERROR: all layers turned to ice and were removed! This probably means that something is wrong with the compaction routine or the accumulation flux\" << std::endl;\n std::abort();\n }\n}\n\nvoid DynamicModel::accumulate(ModelState& mstate) {\n const double acc = mstate.getMeteo().accumulationRate();\n if ( doubles_equal(acc, 0.0)) {return;}\n if ( acc < 0.) {\n accumulateNegative(mstate);\n } else {\n accumulatePositive(mstate);\n }\n}\n\nvoid DynamicModel::accumulateNegative(ModelState& mstate) {\n Grid& grid = mstate.getGrid();\n const double evap = std::abs(mstate.getMeteo().accumulationRate() * 1e-3 * _dt);\n while (grid.back().dz * grid.back().dens \/ rho_w < evap) {\n if (grid.size() < 2) {\n logger << \"WARNING: not enough mass present for sublimation \/ evaporation\" << std::endl;\n return;\n }\n logger << \"grid size = \" << grid.size() << std::endl;\n logger << \"DEBUG combining [ \" << (grid.end()[-2]).dz * (grid.end()[-2]).dens \/ rho_w << \", \"\n << grid.back().dz * grid.back().dens \/ rho_w << \" ] mm W.E. to meet \" << evap << \" mm W.E. of subl.\" << std::endl;\n mstate.combineLayers(grid.end()[-2], grid.back());\n grid.pop_back();\n }\n grid.back().dz -= evap * (rho_w\/grid.back().dens);\n\/\/ logger << \"DEBUG removing \" << evap * (rho_w\/grid.back().dens) << \" m from top layer\" << std::endl;\n if (grid.back().dz <= 0.) {\n logger << \"ERROR: negative layer thickness after evaporation (programmer error)\" << std::endl;\n std::abort();\n }\n return;\n}\n\nvoid DynamicModel::accumulatePositive(ModelState& mstate) {\n Grid& grid = mstate.getGrid();\n const double dens = mstate.getSurf().density();\n const double acc = mstate.getMeteo().accumulationRate() * 1e-3 * _dt; \/\/ convert from [mm\/s] to [m]\n const double dz = (rho_w\/dens) * acc;\n Layer& top = grid.back();\n\n \/\/ grain parameters are mass weighted\n const double U = mstate.getMeteo().surfaceWind();\n const double dfall = std::min(std::max(1.29-0.17*U, 0.20), 1.);\n const double sfall = std::min(std::max(0.08*U + 0.38, 0.5), 0.9);\n const double new_snow = dz*dens;\n const double old_snow = top.dz*top.dz;\n\n#ifdef DEBUG\n const double dold = top.dnd;\n const double sold = top.sph;\n#endif\n \n top.dnd = (top.dnd*old_snow + dfall*new_snow)\/(new_snow+old_snow);\n top.sph = (top.sph*old_snow + sfall*new_snow)\/(new_snow+old_snow);\n top.gs = (top.gs*old_snow + fs_gs*new_snow)\/(new_snow+old_snow);\n\n#ifdef DEBUG\n if (top.dnd > 1. || top.dnd < 0) {\n logger << \"DEBUG top.dnd = \" << top.dnd << \", U = \" << U << std::endl;\n logger << \"DEBUG dfall = \" << dfall << \", sfall = \" << sfall << std::endl;\n logger << \"DEBUG dold = \" << dold << \", sold = \" << sold << std::endl;\n logger << \"DEBUG new_snow = \" << new_snow << \", old_snow = \" << old_snow << std::endl;\n std::abort();\n }\n#endif\n\n top.dens = top.dz\/(top.dz+dz)*top.dens + dz\/(top.dz+dz)*dens;\n top.dz = top.dz + dz;\n\n}\n\n} \/\/ namespace\n<|endoftext|>"} {"text":"<commit_before>\/*=========================================================================\n *\n * Copyright RTK Consortium\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0.txt\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *=========================================================================*\/\n\n#ifndef __rtkIOFactories_cxx\n#define __rtkIOFactories_cxx\n\n\/\/ Varian Obi includes\n#include \"rtkHndImageIOFactory.h\"\n\n\/\/ Elekta Synergy includes\n#include \"rtkHisImageIOFactory.h\"\n\n\/\/ ImagX includes\n#include \"rtkImagXImageIOFactory.h\"\n\n\/\/ European Synchrotron Radiation Facility\n#include \"rtkEdfImageIOFactory.h\"\n\n\/\/ Xrad small animal scanner\n#include \"rtkXRadImageIOFactory.h\"\n\nnamespace rtk\n{\n\nvoid RegisterIOFactories()\n{\n rtk::HndImageIOFactory::RegisterOneFactory();\n rtk::HisImageIOFactory::RegisterOneFactory();\n rtk::ImagXImageIOFactory::RegisterOneFactory();\n rtk::EdfImageIOFactory::RegisterOneFactory();\n rtk::XRadImageIOFactory::RegisterOneFactory();\n#if ITK_VERSION_MAJOR <= 3\n itk::ImageIOFactory::RegisterBuiltInFactories();\n#endif\n}\n\n} \/\/namespace rtk\n\n#endif\n<commit_msg>Fix missing include<commit_after>\/*=========================================================================\n *\n * Copyright RTK Consortium\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0.txt\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *=========================================================================*\/\n\n#ifndef __rtkIOFactories_cxx\n#define __rtkIOFactories_cxx\n\n#include <itkImageIOFactory.h>\n\n\/\/ Varian Obi includes\n#include \"rtkHndImageIOFactory.h\"\n\n\/\/ Elekta Synergy includes\n#include \"rtkHisImageIOFactory.h\"\n\n\/\/ ImagX includes\n#include \"rtkImagXImageIOFactory.h\"\n\n\/\/ European Synchrotron Radiation Facility\n#include \"rtkEdfImageIOFactory.h\"\n\n\/\/ Xrad small animal scanner\n#include \"rtkXRadImageIOFactory.h\"\n\nnamespace rtk\n{\n\nvoid RegisterIOFactories()\n{\n rtk::HndImageIOFactory::RegisterOneFactory();\n rtk::HisImageIOFactory::RegisterOneFactory();\n rtk::ImagXImageIOFactory::RegisterOneFactory();\n rtk::EdfImageIOFactory::RegisterOneFactory();\n rtk::XRadImageIOFactory::RegisterOneFactory();\n#if ITK_VERSION_MAJOR <= 3\n itk::ImageIOFactory::RegisterBuiltInFactories();\n#endif\n}\n\n} \/\/namespace rtk\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- *\/\n\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2000, 2010 Oracle and\/or its affiliates.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * <http:\/\/www.openoffice.org\/license.html>\n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n\n#include \"warnings_guard_ne_locks.h\"\n#include <ne_uri.h>\n#include \"rtl\/ustring.hxx\"\n#include \"osl\/time.h\"\n#include \"osl\/thread.hxx\"\n#include \"salhelper\/thread.hxx\"\n#include \"NeonSession.hxx\"\n#include \"NeonLockStore.hxx\"\n\nusing namespace webdav_ucp;\n\nnamespace webdav_ucp {\n\nclass TickerThread : public salhelper::Thread\n{\n bool m_bFinish;\n NeonLockStore & m_rLockStore;\n\npublic:\n\n TickerThread( NeonLockStore & rLockStore )\n : Thread( \"NeonTickerThread\" ), m_bFinish( false ),\n m_rLockStore( rLockStore ) {}\n\n void finish() { m_bFinish = true; }\n\nprivate:\n\n virtual void execute();\n};\n\n} \/\/ namespace webdav_ucp\n\nvoid TickerThread::execute()\n{\n OSL_TRACE( \"TickerThread: start.\" );\n\n \/\/ we have to go through the loop more often to be able to finish ~quickly\n const int nNth = 25;\n\n int nCount = nNth;\n while ( !m_bFinish )\n {\n if ( nCount-- <= 0 )\n {\n m_rLockStore.refreshLocks();\n nCount = nNth;\n }\n\n TimeValue aTV;\n aTV.Seconds = 0;\n aTV.Nanosec = 1000000000 \/ nNth;\n salhelper::Thread::wait( aTV );\n }\n\n OSL_TRACE( \"TickerThread: stop.\" );\n}\n\nNeonLockStore::NeonLockStore()\n : m_pNeonLockStore( ne_lockstore_create() )\n{\n OSL_ENSURE( m_pNeonLockStore, \"Unable to create neon lock store!\" );\n}\n\nNeonLockStore::~NeonLockStore()\n{\n stopTicker();\n\n \/\/ release active locks, if any.\n OSL_ENSURE( m_aLockInfoMap.empty(),\n \"NeonLockStore::~NeonLockStore - Releasing active locks!\" );\n\n LockInfoMap::const_iterator it( m_aLockInfoMap.begin() );\n const LockInfoMap::const_iterator end( m_aLockInfoMap.end() );\n while ( it != end )\n {\n NeonLock * pLock = (*it).first;\n (*it).second.xSession->UNLOCK( pLock );\n\n ne_lockstore_remove( m_pNeonLockStore, pLock );\n ne_lock_destroy( pLock );\n\n ++it;\n }\n\n ne_lockstore_destroy( m_pNeonLockStore );\n}\n\nvoid NeonLockStore::startTicker()\n{\n osl::MutexGuard aGuard( m_aMutex );\n\n if ( !m_pTickerThread.is() )\n {\n m_pTickerThread = new TickerThread( *this );\n m_pTickerThread->launch();\n }\n}\n\nvoid NeonLockStore::stopTicker()\n{\n osl::MutexGuard aGuard( m_aMutex );\n\n if ( m_pTickerThread.is() )\n {\n m_pTickerThread->finish();\n m_pTickerThread->join();\n m_pTickerThread.clear();\n }\n}\n\nvoid NeonLockStore::registerSession( HttpSession * pHttpSession )\n{\n osl::MutexGuard aGuard( m_aMutex );\n\n ne_lockstore_register( m_pNeonLockStore, pHttpSession );\n}\n\nNeonLock * NeonLockStore::findByUri( OUString const & rUri )\n{\n osl::MutexGuard aGuard( m_aMutex );\n\n ne_uri aUri;\n ne_uri_parse( OUStringToOString(\n rUri, RTL_TEXTENCODING_UTF8 ).getStr(), &aUri );\n return ne_lockstore_findbyuri( m_pNeonLockStore, &aUri );\n}\n\nvoid NeonLockStore::addLock( NeonLock * pLock,\n rtl::Reference< NeonSession > const & xSession,\n sal_Int32 nLastChanceToSendRefreshRequest )\n{\n osl::MutexGuard aGuard( m_aMutex );\n\n ne_lockstore_add( m_pNeonLockStore, pLock );\n m_aLockInfoMap[ pLock ]\n = LockInfo( xSession, nLastChanceToSendRefreshRequest );\n\n startTicker();\n}\n\nvoid NeonLockStore::updateLock( NeonLock * pLock,\n sal_Int32 nLastChanceToSendRefreshRequest )\n{\n osl::MutexGuard aGuard( m_aMutex );\n\n LockInfoMap::iterator it( m_aLockInfoMap.find( pLock ) );\n OSL_ENSURE( it != m_aLockInfoMap.end(),\n \"NeonLockStore::updateLock: lock not found!\" );\n\n if ( it != m_aLockInfoMap.end() )\n {\n (*it).second.nLastChanceToSendRefreshRequest\n = nLastChanceToSendRefreshRequest;\n }\n}\n\nvoid NeonLockStore::removeLock( NeonLock * pLock )\n{\n osl::MutexGuard aGuard( m_aMutex );\n\n m_aLockInfoMap.erase( pLock );\n ne_lockstore_remove( m_pNeonLockStore, pLock );\n\n if ( m_aLockInfoMap.empty() )\n stopTicker();\n}\n\nvoid NeonLockStore::refreshLocks()\n{\n osl::MutexGuard aGuard( m_aMutex );\n\n LockInfoMap::iterator it( m_aLockInfoMap.begin() );\n const LockInfoMap::const_iterator end( m_aLockInfoMap.end() );\n while ( it != end )\n {\n LockInfo & rInfo = (*it).second;\n if ( rInfo.nLastChanceToSendRefreshRequest != -1 )\n {\n \/\/ 30 seconds or less remaining until lock expires?\n TimeValue t1;\n osl_getSystemTime( &t1 );\n if ( rInfo.nLastChanceToSendRefreshRequest - 30\n <= sal_Int32( t1.Seconds ) )\n {\n \/\/ refresh the lock.\n sal_Int32 nlastChanceToSendRefreshRequest = -1;\n if ( rInfo.xSession->LOCK(\n (*it).first,\n \/* out param *\/ nlastChanceToSendRefreshRequest ) )\n {\n rInfo.nLastChanceToSendRefreshRequest\n = nlastChanceToSendRefreshRequest;\n }\n else\n {\n \/\/ refresh failed. stop auto-refresh.\n rInfo.nLastChanceToSendRefreshRequest = -1;\n }\n }\n }\n ++it;\n }\n}\n\n\/* vim:set shiftwidth=4 softtabstop=4 expandtab: *\/\n<commit_msg>ucb: NeonLockStore::stopTicker(): avoid deadlock<commit_after>\/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- *\/\n\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2000, 2010 Oracle and\/or its affiliates.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * <http:\/\/www.openoffice.org\/license.html>\n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n\n#include \"warnings_guard_ne_locks.h\"\n#include <ne_uri.h>\n#include \"rtl\/ustring.hxx\"\n#include \"osl\/time.h\"\n#include \"osl\/thread.hxx\"\n#include \"salhelper\/thread.hxx\"\n#include \"NeonSession.hxx\"\n#include \"NeonLockStore.hxx\"\n\nusing namespace webdav_ucp;\n\nnamespace webdav_ucp {\n\nclass TickerThread : public salhelper::Thread\n{\n bool m_bFinish;\n NeonLockStore & m_rLockStore;\n\npublic:\n\n TickerThread( NeonLockStore & rLockStore )\n : Thread( \"NeonTickerThread\" ), m_bFinish( false ),\n m_rLockStore( rLockStore ) {}\n\n void finish() { m_bFinish = true; }\n\nprivate:\n\n virtual void execute();\n};\n\n} \/\/ namespace webdav_ucp\n\nvoid TickerThread::execute()\n{\n OSL_TRACE( \"TickerThread: start.\" );\n\n \/\/ we have to go through the loop more often to be able to finish ~quickly\n const int nNth = 25;\n\n int nCount = nNth;\n while ( !m_bFinish )\n {\n if ( nCount-- <= 0 )\n {\n m_rLockStore.refreshLocks();\n nCount = nNth;\n }\n\n TimeValue aTV;\n aTV.Seconds = 0;\n aTV.Nanosec = 1000000000 \/ nNth;\n salhelper::Thread::wait( aTV );\n }\n\n OSL_TRACE( \"TickerThread: stop.\" );\n}\n\nNeonLockStore::NeonLockStore()\n : m_pNeonLockStore( ne_lockstore_create() )\n{\n OSL_ENSURE( m_pNeonLockStore, \"Unable to create neon lock store!\" );\n}\n\nNeonLockStore::~NeonLockStore()\n{\n stopTicker();\n\n \/\/ release active locks, if any.\n OSL_ENSURE( m_aLockInfoMap.empty(),\n \"NeonLockStore::~NeonLockStore - Releasing active locks!\" );\n\n LockInfoMap::const_iterator it( m_aLockInfoMap.begin() );\n const LockInfoMap::const_iterator end( m_aLockInfoMap.end() );\n while ( it != end )\n {\n NeonLock * pLock = (*it).first;\n (*it).second.xSession->UNLOCK( pLock );\n\n ne_lockstore_remove( m_pNeonLockStore, pLock );\n ne_lock_destroy( pLock );\n\n ++it;\n }\n\n ne_lockstore_destroy( m_pNeonLockStore );\n}\n\nvoid NeonLockStore::startTicker()\n{\n osl::MutexGuard aGuard( m_aMutex );\n\n if ( !m_pTickerThread.is() )\n {\n m_pTickerThread = new TickerThread( *this );\n m_pTickerThread->launch();\n }\n}\n\nvoid NeonLockStore::stopTicker()\n{\n rtl::Reference<TickerThread> pTickerThread;\n {\n osl::MutexGuard aGuard( m_aMutex );\n\n if (!m_pTickerThread.is())\n {\n return; \/\/ nothing to do\n }\n m_pTickerThread->finish(); \/\/ needs mutex\n \/\/ the TickerThread may run refreshLocks() at most once after this\n pTickerThread = m_pTickerThread;\n m_pTickerThread.clear();\n }\n\n pTickerThread->join(); \/\/ without m_aMutex locked (to prevent deadlock)\n}\n\nvoid NeonLockStore::registerSession( HttpSession * pHttpSession )\n{\n osl::MutexGuard aGuard( m_aMutex );\n\n ne_lockstore_register( m_pNeonLockStore, pHttpSession );\n}\n\nNeonLock * NeonLockStore::findByUri( OUString const & rUri )\n{\n osl::MutexGuard aGuard( m_aMutex );\n\n ne_uri aUri;\n ne_uri_parse( OUStringToOString(\n rUri, RTL_TEXTENCODING_UTF8 ).getStr(), &aUri );\n return ne_lockstore_findbyuri( m_pNeonLockStore, &aUri );\n}\n\nvoid NeonLockStore::addLock( NeonLock * pLock,\n rtl::Reference< NeonSession > const & xSession,\n sal_Int32 nLastChanceToSendRefreshRequest )\n{\n osl::MutexGuard aGuard( m_aMutex );\n\n ne_lockstore_add( m_pNeonLockStore, pLock );\n m_aLockInfoMap[ pLock ]\n = LockInfo( xSession, nLastChanceToSendRefreshRequest );\n\n startTicker();\n}\n\nvoid NeonLockStore::updateLock( NeonLock * pLock,\n sal_Int32 nLastChanceToSendRefreshRequest )\n{\n osl::MutexGuard aGuard( m_aMutex );\n\n LockInfoMap::iterator it( m_aLockInfoMap.find( pLock ) );\n OSL_ENSURE( it != m_aLockInfoMap.end(),\n \"NeonLockStore::updateLock: lock not found!\" );\n\n if ( it != m_aLockInfoMap.end() )\n {\n (*it).second.nLastChanceToSendRefreshRequest\n = nLastChanceToSendRefreshRequest;\n }\n}\n\nvoid NeonLockStore::removeLock( NeonLock * pLock )\n{\n osl::MutexGuard aGuard( m_aMutex );\n\n m_aLockInfoMap.erase( pLock );\n ne_lockstore_remove( m_pNeonLockStore, pLock );\n\n if ( m_aLockInfoMap.empty() )\n stopTicker();\n}\n\nvoid NeonLockStore::refreshLocks()\n{\n osl::MutexGuard aGuard( m_aMutex );\n\n LockInfoMap::iterator it( m_aLockInfoMap.begin() );\n const LockInfoMap::const_iterator end( m_aLockInfoMap.end() );\n while ( it != end )\n {\n LockInfo & rInfo = (*it).second;\n if ( rInfo.nLastChanceToSendRefreshRequest != -1 )\n {\n \/\/ 30 seconds or less remaining until lock expires?\n TimeValue t1;\n osl_getSystemTime( &t1 );\n if ( rInfo.nLastChanceToSendRefreshRequest - 30\n <= sal_Int32( t1.Seconds ) )\n {\n \/\/ refresh the lock.\n sal_Int32 nlastChanceToSendRefreshRequest = -1;\n if ( rInfo.xSession->LOCK(\n (*it).first,\n \/* out param *\/ nlastChanceToSendRefreshRequest ) )\n {\n rInfo.nLastChanceToSendRefreshRequest\n = nlastChanceToSendRefreshRequest;\n }\n else\n {\n \/\/ refresh failed. stop auto-refresh.\n rInfo.nLastChanceToSendRefreshRequest = -1;\n }\n }\n }\n ++it;\n }\n}\n\n\/* vim:set shiftwidth=4 softtabstop=4 expandtab: *\/\n<|endoftext|>"} {"text":"<commit_before>\/\/ ref http:\/\/www.cnblogs.com\/easonliu\/p\/4563780.html\nclass Solution {\nprivate:\n bool isOK(char op1, char op2) {\n if (op1 == '*' || op1 == '\/' || op2 == ')') return true;\n else return op2 == '+' || op2 == '-';\n }\n int calc(int a, int b, char op) {\n if (op == '+') return a + b;\n else if (op == '-') return a - b;\n else if (op == '*') return a * b;\n else return a \/ b;\n }\npublic:\n int calculate(string s) {\n stack<int> stk_val;\n stack<char> stk_op;\n int res = 0, tmp;\n for (int i = 0; i <= s.length(); ++i) {\n \/\/操作数\n if (i < s.length() && isdigit(s[i])) {\n res = 0;\n while (i < s.length() && isdigit(s[i])) {\n res *= 10;\n res += s[i++] - '0';\n }\n stk_val.push(res);\n }\n \/\/运算符\n if (i == s.length() || s[i] == '+' || s[i] == '-' || s[i] == '*' || s[i] == '\/' || s[i] == ')') {\n while (!stk_op.empty() && stk_op.top() != '(' && (i == s.length() || isOK(stk_op.top(), s[i]))) {\n tmp = stk_val.top();\n stk_val.pop();\n stk_val.top() = calc(stk_val.top(), tmp, stk_op.top());\n stk_op.pop();\n }\n if (i == s.length()) break;\n else if (s[i] == ')') stk_op.pop();\n else stk_op.push(s[i]);\n } else if (s[i] == '(') {\n stk_op.push(s[i]);\n }\n }\n return stk_val.top();\n }\n};<commit_msg>add more<commit_after>\/\/ ref http:\/\/www.cnblogs.com\/easonliu\/p\/4563780.html\nclass Solution {\nprivate:\n bool isOK(char op1, char op2) {\n if (op1 == '*' || op1 == '\/' || op2 == ')') return true;\n else return op2 == '+' || op2 == '-';\n }\n int calc(int a, int b, char op) {\n if (op == '+') return a + b;\n else if (op == '-') return a - b;\n else if (op == '*') return a * b;\n else return a \/ b;\n }\npublic:\n int calculate(string s) {\n stack<int> stk_val;\n stack<char> stk_op;\n\n int res = 0, tmp;\n for (int i = 0; i <= s.length(); ++i) {\n \/\/操作数\n if (i < s.length() && isdigit(s[i])) {\n res = 0;\n while (i < s.length() && isdigit(s[i])) {\n res *= 10;\n res += s[i++] - '0';\n }\n stk_val.push(res);\n }\n \/\/运算符\n if (i == s.length() || s[i] == '+' || s[i] == '-' || s[i] == '*' || s[i] == '\/' || s[i] == ')') {\n while (!stk_op.empty() && stk_op.top() != '(' && (i == s.length() || isOK(stk_op.top(), s[i]))) {\n tmp = stk_val.top();\n stk_val.pop();\n stk_val.top() = calc(stk_val.top(), tmp, stk_op.top());\n stk_op.pop();\n }\n if (i == s.length()) {\n break;\n } else if (s[i] == ')') {\n stk_op.pop();\n }else{\n stk_op.push(s[i]);\n } \n } else if (s[i] == '(') {\n stk_op.push(s[i]);\n }\n }\n return stk_val.top();\n }\n};<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n#include <string>\n#include <vector>\n#include <algorithm>\nusing namespace std;\nint main(int argc, char const *argv[]) {\n\n\treturn 0;\n}\n<commit_msg>adding graph.gonna start<commit_after>\/\/http:\/\/codeforces.com\/problemset\/problem\/115\/A\n#include <iostream>\n#include <string>\n#include <vector>\n#include <algorithm>\nusing namespace std;\nint main(int argc, char const *argv[]) {\n\t\n\treturn 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * File: cogwheelftpcoreutil.cpp\n *\n * Author: Robert Tizzard\n *\n * Created on August 10, 2017\n *\n * Copyright 2017.\n *\n *\/\n\n\/\/\n\/\/ Namespace: CogWheelFTPCoreUtil\n\/\/\n\/\/ Description: CogWheelFTPCore utility functions.\n\/\/\n\n\/\/ =============\n\/\/ INCLUDE FILES\n\/\/ =============\n\n#include \"cogwheelftpcoreutil.h\"\n#include \"cogwheellogger.h\"\n\nnamespace CogWheelFTPCoreUtil {\n\n\/**\n * @brief mapPathToLocal\n *\n * Map a FTP root relative path to local filesystem.\n *\n * @param connection Pointer to control channel instance.\n * @param path Path to map to local filesystem.\n *\n * @return Local file system path string,\n *\/\nQString mapPathToLocal(CogWheelControlChannel *connection, const QString &path)\n{\n\n QString mappedPath;\n\n if (path.startsWith('\/')) {\n mappedPath = connection->rootDirectory()+path;\n } else {\n mappedPath = connection->rootDirectory()+connection->currentWorkingDirectory();\n if (connection->currentWorkingDirectory()==\"\/\") {\n mappedPath += path;\n } else {\n mappedPath += (\"\/\" + path);\n }\n }\n\n cogWheelInfo(connection->socketHandle(),\"Mapping local \"+path+\" to \"+mappedPath);\n\n return(mappedPath);\n}\n\n\/**\n * @brief mapPathFromLocal\n *\n * Map a given local filesystem path to a FTP root path.\n *\n * @param connection Pointer to control channel instance.\n * @param path Path to map from local filesystem.\n *\n * @return FTP root path.\n *\/\nQString mapPathFromLocal(CogWheelControlChannel *connection, const QString &path)\n{\n\n QString mappedPath { QFileInfo(path).absoluteFilePath()};\n\n cogWheelInfo(connection->socketHandle(),\"mapped path : \"+mappedPath);\n\n \/\/ Strip off root path\n\n if (mappedPath.startsWith(connection->rootDirectory())) {\n mappedPath = mappedPath.remove(0,connection->rootDirectory().length());\n\n \/\/ If trying to go above root then reset to root\n\n } else if (mappedPath.length() < connection->rootDirectory().length()){\n mappedPath = \"\";\n }\n\n cogWheelInfo(connection->socketHandle(),\"Mapping local from \"+path+\" to \"+mappedPath);\n\n return(mappedPath);\n}\n\n\/**\n * @brief buildFilePermissions\n *\n * Build files permissions (for LIST) into QString and return.\n *\n * @param fileInfo File to produce permissions for.\n *\n * @return Files permissions as a QString.\n *\/\nQString buildFilePermissions(const QFileInfo &fileInfo)\n{\n\n char permissions[10];\n\n permissions[0] = (fileInfo.permissions() & QFile::ReadUser) ? 'r' : '-';\n permissions[1] = (fileInfo.permissions() & QFile::WriteUser) ? 'w' : '-';\n permissions[2] = (fileInfo.permissions() & QFile::ExeUser) ? 'x' : '-';\n permissions[3] = (fileInfo.permissions() & QFile::ReadGroup) ? 'r' : '-';\n permissions[4] = (fileInfo.permissions() & QFile::WriteGroup) ? 'w' : '-';\n permissions[5] = (fileInfo.permissions() & QFile::ExeGroup) ? 'x' : '-';\n permissions[6] = (fileInfo.permissions() & QFile::ReadOther) ? 'r' : '-';\n permissions[7] = (fileInfo.permissions() & QFile::WriteOther) ? 'w' : '-';\n permissions[8] = (fileInfo.permissions() & QFile::ExeOther) ? 'x' : '-';\n permissions[9] = 0;\n\n return(permissions);\n\n}\n\n\/**\n * @brief buildUnixFilePermissions\n *\n * Build files unix permissions into octal QString and return.\n *\n * @param fileInfo File to produce permissions for.\n *\n * @return Files permissions as a octal QString.\n *\/\nQString buildUnixFilePermissions(const QFileInfo &fileInfo)\n{\n\n unsigned short permissions=0;\n\n permissions |= (fileInfo.permissions() & QFile::ReadUser) ? 0400 : 0;\n permissions |= (fileInfo.permissions() & QFile::WriteUser) ? 0200 : 0;\n permissions |= (fileInfo.permissions() & QFile::ExeUser) ? 0100 : 0;\n permissions |= (fileInfo.permissions() & QFile::ReadGroup) ? 0040 : 0;\n permissions |= (fileInfo.permissions() & QFile::WriteGroup) ? 0020 : 0;\n permissions |= (fileInfo.permissions() & QFile::ExeGroup) ? 0010 : 0;\n permissions |= (fileInfo.permissions() & QFile::ReadOther) ? 0004 : 0;\n permissions |= (fileInfo.permissions() & QFile::WriteOther) ? 0002 : 0;\n permissions |= (fileInfo.permissions() & QFile::ExeOther) ? 0001 : 0;\n\n return(\"0\"+QString::number(permissions,8));\n\n}\n\n\/**\n * @brief buildMLSDCommonLine\n *\n * Build common file facts to QString and return.\n *\n * @param fileInfo File to produce facts for.\n *\n * @return Common file facts as a QString.\n *\/\nQString buildMLSDCommonLine(const QFileInfo &fileInfo)\n{\n QString line;\n\n line.append(static_cast<QString>(\"Modify=\")+fileInfo.lastModified().toString(\"yyyyMMddhhmmss;\"));\n line.append(static_cast<QString>(\"Create=\")+fileInfo.created().toString(\"yyyyMMddhhmmss;\"));\n line.append(static_cast<QString>(\"UNIX.mode=\")+buildUnixFilePermissions(fileInfo)+\";\");\n line.append(static_cast<QString>(\"UNIX.owner=\")+QString::number(fileInfo.ownerId())+\";\");\n line.append(static_cast<QString>(\"UNIX.group=\")+QString::number(fileInfo.groupId())+\";\");\n\n return line;\n\n}\n\n\/**\n * @brief buildLISTLine\n *\n * Build list line for passed in QFileInfo. The format of which\n * is the same as given for the Linux 'ls -l' command.\n *\n * @param fileInfo File to produce list line for.\n *\n * @return List line QString.\n *\/\nQString buildLISTLine(const QFileInfo &fileInfo)\n{\n\n QChar fileType= '-';\n QString line;\n QString ownerGroup;\n\n if (fileInfo.isSymLink()) {\n fileType = 'l';\n } else if (fileInfo.isDir()){\n fileType = 'd';\n }\n\n line.append(fileType+buildFilePermissions(fileInfo)+\" 1 \");\n\n ownerGroup = fileInfo.owner();\n if(ownerGroup.isEmpty()) {\n ownerGroup = \"0\";\n }\n line.append(ownerGroup.leftJustified(10,' ',true)+\" \");\n\n ownerGroup = fileInfo.group();\n if(ownerGroup.isEmpty()) {\n ownerGroup = \"0\";\n }\n line.append(ownerGroup.leftJustified(10,' ',true)+\" \");\n\n line.append(QString::number(fileInfo.size()).rightJustified(10,' ',true)+\" \");\n line.append(fileInfo.lastModified().toString(\"MMM dd hh:mm\").rightJustified(12,' ',true)+\" \");\n line.append(fileInfo.fileName()+\"\\r\\n\");\n\n return(line);\n\n\n}\n\n\/**\n * @brief buildMLSDPathLine\n *\n * Build list line for requested path in MLSD.\n *\n * @param pathInfo Directory info to produce MLSD line for.\n * @param path Directory path.\n *\n * @return MLSD list line QString.\n *\/\nQString buildMLSDPathLine(const QFileInfo &pathInfo, const QString &path)\n{\n return (static_cast<QString>(\"Type=cdir;\")+buildMLSDCommonLine(pathInfo)+\" \"+path+\"\\r\\n\");\n}\n\n\/**\n * @brief buildMLSDLine\n *\n * Build list line for single file in MLSD list.\n *\n * @param fileInfo File information\n *\n * @return List line for file QString.\n *\/\nQString buildMLSDLine(const QFileInfo &fileInfo)\n{\n\n QString line;\n\n if(fileInfo.isDir()){\n line.append(\"Type=dir;\");\n }else {\n line.append((static_cast<QString>(\"Type=file;\")+\"Size=\")+QString::number(fileInfo.size())+\";\");\n }\n\n line.append(buildMLSDCommonLine(fileInfo)+\" \"+fileInfo.fileName()+\"\\r\\n\");\n\n return line;\n\n}\n\n} \/\/ namespace CogWheelFTPCoreUtil\n<commit_msg>Seperate out FTPCore utility functions into file CogWheelFTPCoreUtil.cpp<commit_after>\/*\n * File: cogwheelftpcoreutil.cpp\n *\n * Author: Robert Tizzard\n *\n * Created on August 10, 2017\n *\n * Copyright 2017.\n *\n *\/\n\n\/\/\n\/\/ Namespace: CogWheelFTPCoreUtil\n\/\/\n\/\/ Description: CogWheelFTPCore utility functions. This includes functions\n\/\/ for mapping to\/from the local file system (root relative) and for the creation\n\/\/ of list information\/fact lines for files returned in reponse to the various FTP\n\/\/ list commands.\n\/\/\n\n\/\/ =============\n\/\/ INCLUDE FILES\n\/\/ =============\n\n#include \"cogwheelftpcoreutil.h\"\n#include \"cogwheellogger.h\"\n\nnamespace CogWheelFTPCoreUtil {\n\n\/**\n * @brief mapPathToLocal\n *\n * Map a FTP root relative path to local filesystem.\n *\n * @param connection Pointer to control channel instance.\n * @param path Path to map to local filesystem.\n *\n * @return Local file system path string,\n *\/\nQString mapPathToLocal(CogWheelControlChannel *connection, const QString &path)\n{\n\n QString mappedPath;\n\n if (path.startsWith('\/')) {\n mappedPath = connection->rootDirectory()+path;\n } else {\n mappedPath = connection->rootDirectory()+connection->currentWorkingDirectory();\n if (connection->currentWorkingDirectory()==\"\/\") {\n mappedPath += path;\n } else {\n mappedPath += (\"\/\" + path);\n }\n }\n\n cogWheelInfo(connection->socketHandle(),\"Mapping local \"+path+\" to \"+mappedPath);\n\n return(mappedPath);\n}\n\n\/**\n * @brief mapPathFromLocal\n *\n * Map a given local filesystem path to a FTP root path.\n *\n * @param connection Pointer to control channel instance.\n * @param path Path to map from local filesystem.\n *\n * @return FTP root path.\n *\/\nQString mapPathFromLocal(CogWheelControlChannel *connection, const QString &path)\n{\n\n QString mappedPath { QFileInfo(path).absoluteFilePath()};\n\n cogWheelInfo(connection->socketHandle(),\"mapped path : \"+mappedPath);\n\n \/\/ Strip off root path\n\n if (mappedPath.startsWith(connection->rootDirectory())) {\n mappedPath = mappedPath.remove(0,connection->rootDirectory().length());\n\n \/\/ If trying to go above root then reset to root\n\n } else if (mappedPath.length() < connection->rootDirectory().length()){\n mappedPath = \"\";\n }\n\n cogWheelInfo(connection->socketHandle(),\"Mapping local from \"+path+\" to \"+mappedPath);\n\n return(mappedPath);\n}\n\n\/**\n * @brief buildFilePermissions\n *\n * Build files permissions (for LIST) into QString and return.\n *\n * @param fileInfo File to produce permissions for.\n *\n * @return Files permissions as a QString.\n *\/\nQString buildFilePermissions(const QFileInfo &fileInfo)\n{\n\n char permissions[10];\n\n permissions[0] = (fileInfo.permissions() & QFile::ReadUser) ? 'r' : '-';\n permissions[1] = (fileInfo.permissions() & QFile::WriteUser) ? 'w' : '-';\n permissions[2] = (fileInfo.permissions() & QFile::ExeUser) ? 'x' : '-';\n permissions[3] = (fileInfo.permissions() & QFile::ReadGroup) ? 'r' : '-';\n permissions[4] = (fileInfo.permissions() & QFile::WriteGroup) ? 'w' : '-';\n permissions[5] = (fileInfo.permissions() & QFile::ExeGroup) ? 'x' : '-';\n permissions[6] = (fileInfo.permissions() & QFile::ReadOther) ? 'r' : '-';\n permissions[7] = (fileInfo.permissions() & QFile::WriteOther) ? 'w' : '-';\n permissions[8] = (fileInfo.permissions() & QFile::ExeOther) ? 'x' : '-';\n permissions[9] = 0;\n\n return(permissions);\n\n}\n\n\/**\n * @brief buildUnixFilePermissions\n *\n * Build files unix permissions into octal QString and return.\n *\n * @param fileInfo File to produce permissions for.\n *\n * @return Files permissions as a octal QString.\n *\/\nQString buildUnixFilePermissions(const QFileInfo &fileInfo)\n{\n\n unsigned short permissions=0;\n\n permissions |= (fileInfo.permissions() & QFile::ReadUser) ? 0400 : 0;\n permissions |= (fileInfo.permissions() & QFile::WriteUser) ? 0200 : 0;\n permissions |= (fileInfo.permissions() & QFile::ExeUser) ? 0100 : 0;\n permissions |= (fileInfo.permissions() & QFile::ReadGroup) ? 0040 : 0;\n permissions |= (fileInfo.permissions() & QFile::WriteGroup) ? 0020 : 0;\n permissions |= (fileInfo.permissions() & QFile::ExeGroup) ? 0010 : 0;\n permissions |= (fileInfo.permissions() & QFile::ReadOther) ? 0004 : 0;\n permissions |= (fileInfo.permissions() & QFile::WriteOther) ? 0002 : 0;\n permissions |= (fileInfo.permissions() & QFile::ExeOther) ? 0001 : 0;\n\n return(\"0\"+QString::number(permissions,8));\n\n}\n\n\/**\n * @brief buildMLSDCommonLine\n *\n * Build common file facts to QString and return.\n *\n * @param fileInfo File to produce facts for.\n *\n * @return Common file facts as a QString.\n *\/\nQString buildMLSDCommonLine(const QFileInfo &fileInfo)\n{\n QString line;\n\n line.append(static_cast<QString>(\"Modify=\")+fileInfo.lastModified().toString(\"yyyyMMddhhmmss;\"));\n line.append(static_cast<QString>(\"Create=\")+fileInfo.created().toString(\"yyyyMMddhhmmss;\"));\n line.append(static_cast<QString>(\"UNIX.mode=\")+buildUnixFilePermissions(fileInfo)+\";\");\n line.append(static_cast<QString>(\"UNIX.owner=\")+QString::number(fileInfo.ownerId())+\";\");\n line.append(static_cast<QString>(\"UNIX.group=\")+QString::number(fileInfo.groupId())+\";\");\n\n return line;\n\n}\n\n\/**\n * @brief buildLISTLine\n *\n * Build list line for passed in QFileInfo. The format of which\n * is the same as given for the Linux 'ls -l' command.\n *\n * @param fileInfo File to produce list line for.\n *\n * @return List line QString.\n *\/\nQString buildLISTLine(const QFileInfo &fileInfo)\n{\n\n QChar fileType= '-';\n QString line;\n QString ownerGroup;\n\n if (fileInfo.isSymLink()) {\n fileType = 'l';\n } else if (fileInfo.isDir()){\n fileType = 'd';\n }\n\n line.append(fileType+buildFilePermissions(fileInfo)+\" 1 \");\n\n ownerGroup = fileInfo.owner();\n if(ownerGroup.isEmpty()) {\n ownerGroup = \"0\";\n }\n line.append(ownerGroup.leftJustified(10,' ',true)+\" \");\n\n ownerGroup = fileInfo.group();\n if(ownerGroup.isEmpty()) {\n ownerGroup = \"0\";\n }\n line.append(ownerGroup.leftJustified(10,' ',true)+\" \");\n\n line.append(QString::number(fileInfo.size()).rightJustified(10,' ',true)+\" \");\n line.append(fileInfo.lastModified().toString(\"MMM dd hh:mm\").rightJustified(12,' ',true)+\" \");\n line.append(fileInfo.fileName()+\"\\r\\n\");\n\n return(line);\n\n\n}\n\n\/**\n * @brief buildMLSDPathLine\n *\n * Build list line for requested path in MLSD.\n *\n * @param pathInfo Directory info to produce MLSD line for.\n * @param path Directory path.\n *\n * @return MLSD list line QString.\n *\/\nQString buildMLSDPathLine(const QFileInfo &pathInfo, const QString &path)\n{\n return (static_cast<QString>(\"Type=cdir;\")+buildMLSDCommonLine(pathInfo)+\" \"+path+\"\\r\\n\");\n}\n\n\/**\n * @brief buildMLSDLine\n *\n * Build list line for single file in MLSD list.\n *\n * @param fileInfo File information\n *\n * @return List line for file QString.\n *\/\nQString buildMLSDLine(const QFileInfo &fileInfo)\n{\n\n QString line;\n\n if(fileInfo.isDir()){\n line.append(\"Type=dir;\");\n }else {\n line.append((static_cast<QString>(\"Type=file;\")+\"Size=\")+QString::number(fileInfo.size())+\";\");\n }\n\n line.append(buildMLSDCommonLine(fileInfo)+\" \"+fileInfo.fileName()+\"\\r\\n\");\n\n return line;\n\n}\n\n} \/\/ namespace CogWheelFTPCoreUtil\n<|endoftext|>"} {"text":"<commit_before>\/\/===- ArchiveWriter.cpp - ar File Format implementation --------*- C++ -*-===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This file defines the writeArchive function.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/Object\/ArchiveWriter.h\"\n#include \"llvm\/ADT\/ArrayRef.h\"\n#include \"llvm\/ADT\/StringRef.h\"\n#include \"llvm\/IR\/LLVMContext.h\"\n#include \"llvm\/Object\/Archive.h\"\n#include \"llvm\/Object\/ObjectFile.h\"\n#include \"llvm\/Object\/SymbolicFile.h\"\n#include \"llvm\/Support\/Errc.h\"\n#include \"llvm\/Support\/ErrorHandling.h\"\n#include \"llvm\/Support\/Format.h\"\n#include \"llvm\/Support\/Path.h\"\n#include \"llvm\/Support\/ToolOutputFile.h\"\n#include \"llvm\/Support\/raw_ostream.h\"\n\n#if !defined(_MSC_VER) && !defined(__MINGW32__)\n#include <unistd.h>\n#else\n#include <io.h>\n#endif\n\nusing namespace llvm;\n\nNewArchiveIterator::NewArchiveIterator() {}\n\nNewArchiveIterator::NewArchiveIterator(object::Archive::child_iterator I,\n StringRef Name)\n : IsNewMember(false), Name(Name), OldI(I) {}\n\nNewArchiveIterator::NewArchiveIterator(StringRef NewFilename, StringRef Name)\n : IsNewMember(true), Name(Name), NewFilename(NewFilename) {}\n\nStringRef NewArchiveIterator::getName() const { return Name; }\n\nbool NewArchiveIterator::isNewMember() const { return IsNewMember; }\n\nobject::Archive::child_iterator NewArchiveIterator::getOld() const {\n assert(!IsNewMember);\n return OldI;\n}\n\nStringRef NewArchiveIterator::getNew() const {\n assert(IsNewMember);\n return NewFilename;\n}\n\nllvm::ErrorOr<int>\nNewArchiveIterator::getFD(sys::fs::file_status &NewStatus) const {\n assert(IsNewMember);\n int NewFD;\n if (auto EC = sys::fs::openFileForRead(NewFilename, NewFD))\n return EC;\n assert(NewFD != -1);\n\n if (auto EC = sys::fs::status(NewFD, NewStatus))\n return EC;\n\n \/\/ Opening a directory doesn't make sense. Let it fail.\n \/\/ Linux cannot open directories with open(2), although\n \/\/ cygwin and *bsd can.\n if (NewStatus.type() == sys::fs::file_type::directory_file)\n return make_error_code(errc::is_a_directory);\n\n return NewFD;\n}\n\ntemplate <typename T>\nstatic void printWithSpacePadding(raw_fd_ostream &OS, T Data, unsigned Size,\n\t\t\t\t bool MayTruncate = false) {\n uint64_t OldPos = OS.tell();\n OS << Data;\n unsigned SizeSoFar = OS.tell() - OldPos;\n if (Size > SizeSoFar) {\n unsigned Remaining = Size - SizeSoFar;\n for (unsigned I = 0; I < Remaining; ++I)\n OS << ' ';\n } else if (Size < SizeSoFar) {\n assert(MayTruncate && \"Data doesn't fit in Size\");\n \/\/ Some of the data this is used for (like UID) can be larger than the\n \/\/ space available in the archive format. Truncate in that case.\n OS.seek(OldPos + Size);\n }\n}\n\nstatic void print32BE(raw_fd_ostream &Out, unsigned Val) {\n \/\/ FIXME: Should use Endian.h here.\n for (int I = 3; I >= 0; --I) {\n char V = (Val >> (8 * I)) & 0xff;\n Out << V;\n }\n}\n\nstatic void printRestOfMemberHeader(raw_fd_ostream &Out,\n const sys::TimeValue &ModTime, unsigned UID,\n unsigned GID, unsigned Perms,\n unsigned Size) {\n printWithSpacePadding(Out, ModTime.toEpochTime(), 12);\n printWithSpacePadding(Out, UID, 6, true);\n printWithSpacePadding(Out, GID, 6, true);\n printWithSpacePadding(Out, format(\"%o\", Perms), 8);\n printWithSpacePadding(Out, Size, 10);\n Out << \"`\\n\";\n}\n\nstatic void printMemberHeader(raw_fd_ostream &Out, StringRef Name,\n const sys::TimeValue &ModTime, unsigned UID,\n unsigned GID, unsigned Perms, unsigned Size) {\n printWithSpacePadding(Out, Twine(Name) + \"\/\", 16);\n printRestOfMemberHeader(Out, ModTime, UID, GID, Perms, Size);\n}\n\nstatic void printMemberHeader(raw_fd_ostream &Out, unsigned NameOffset,\n const sys::TimeValue &ModTime, unsigned UID,\n unsigned GID, unsigned Perms, unsigned Size) {\n Out << '\/';\n printWithSpacePadding(Out, NameOffset, 15);\n printRestOfMemberHeader(Out, ModTime, UID, GID, Perms, Size);\n}\n\nstatic void writeStringTable(raw_fd_ostream &Out,\n ArrayRef<NewArchiveIterator> Members,\n std::vector<unsigned> &StringMapIndexes) {\n unsigned StartOffset = 0;\n for (ArrayRef<NewArchiveIterator>::iterator I = Members.begin(),\n E = Members.end();\n I != E; ++I) {\n StringRef Name = I->getName();\n if (Name.size() < 16)\n continue;\n if (StartOffset == 0) {\n printWithSpacePadding(Out, \"\/\/\", 58);\n Out << \"`\\n\";\n StartOffset = Out.tell();\n }\n StringMapIndexes.push_back(Out.tell() - StartOffset);\n Out << Name << \"\/\\n\";\n }\n if (StartOffset == 0)\n return;\n if (Out.tell() % 2)\n Out << '\\n';\n int Pos = Out.tell();\n Out.seek(StartOffset - 12);\n printWithSpacePadding(Out, Pos - StartOffset, 10);\n Out.seek(Pos);\n}\n\n\/\/ Returns the offset of the first reference to a member offset.\nstatic ErrorOr<unsigned>\nwriteSymbolTable(raw_fd_ostream &Out, ArrayRef<NewArchiveIterator> Members,\n ArrayRef<MemoryBufferRef> Buffers,\n std::vector<unsigned> &MemberOffsetRefs) {\n unsigned StartOffset = 0;\n unsigned MemberNum = 0;\n std::string NameBuf;\n raw_string_ostream NameOS(NameBuf);\n unsigned NumSyms = 0;\n LLVMContext Context;\n for (ArrayRef<NewArchiveIterator>::iterator I = Members.begin(),\n E = Members.end();\n I != E; ++I, ++MemberNum) {\n MemoryBufferRef MemberBuffer = Buffers[MemberNum];\n ErrorOr<std::unique_ptr<object::SymbolicFile>> ObjOrErr =\n object::SymbolicFile::createSymbolicFile(\n MemberBuffer, sys::fs::file_magic::unknown, &Context);\n if (!ObjOrErr)\n continue; \/\/ FIXME: check only for \"not an object file\" errors.\n object::SymbolicFile &Obj = *ObjOrErr.get();\n\n if (!StartOffset) {\n printMemberHeader(Out, \"\", sys::TimeValue::now(), 0, 0, 0, 0);\n StartOffset = Out.tell();\n print32BE(Out, 0);\n }\n\n for (const object::BasicSymbolRef &S : Obj.symbols()) {\n uint32_t Symflags = S.getFlags();\n if (Symflags & object::SymbolRef::SF_FormatSpecific)\n continue;\n if (!(Symflags & object::SymbolRef::SF_Global))\n continue;\n if (Symflags & object::SymbolRef::SF_Undefined)\n continue;\n if (auto EC = S.printName(NameOS))\n return EC;\n NameOS << '\\0';\n ++NumSyms;\n MemberOffsetRefs.push_back(MemberNum);\n print32BE(Out, 0);\n }\n }\n Out << NameOS.str();\n\n if (StartOffset == 0)\n return 0;\n\n if (Out.tell() % 2)\n Out << '\\0';\n\n unsigned Pos = Out.tell();\n Out.seek(StartOffset - 12);\n printWithSpacePadding(Out, Pos - StartOffset, 10);\n Out.seek(StartOffset);\n print32BE(Out, NumSyms);\n Out.seek(Pos);\n return StartOffset + 4;\n}\n\nstd::pair<StringRef, std::error_code>\nllvm::writeArchive(StringRef ArcName,\n std::vector<NewArchiveIterator> &NewMembers,\n bool WriteSymtab) {\n SmallString<128> TmpArchive;\n int TmpArchiveFD;\n if (auto EC = sys::fs::createUniqueFile(ArcName + \".temp-archive-%%%%%%%.a\",\n TmpArchiveFD, TmpArchive))\n return std::make_pair(ArcName, EC);\n\n tool_output_file Output(TmpArchive, TmpArchiveFD);\n raw_fd_ostream &Out = Output.os();\n Out << \"!<arch>\\n\";\n\n std::vector<unsigned> MemberOffsetRefs;\n\n std::vector<std::unique_ptr<MemoryBuffer>> Buffers;\n std::vector<MemoryBufferRef> Members;\n std::vector<sys::fs::file_status> NewMemberStatus;\n\n for (unsigned I = 0, N = NewMembers.size(); I < N; ++I) {\n NewArchiveIterator &Member = NewMembers[I];\n MemoryBufferRef MemberRef;\n\n if (Member.isNewMember()) {\n StringRef Filename = Member.getNew();\n NewMemberStatus.resize(NewMemberStatus.size() + 1);\n sys::fs::file_status &Status = NewMemberStatus.back();\n ErrorOr<int> FD = Member.getFD(Status);\n if (auto EC = FD.getError())\n return std::make_pair(Filename, EC);\n ErrorOr<std::unique_ptr<MemoryBuffer>> MemberBufferOrErr =\n MemoryBuffer::getOpenFile(FD.get(), Filename, Status.getSize(),\n false);\n if (auto EC = MemberBufferOrErr.getError())\n return std::make_pair(Filename, EC);\n if (close(FD.get()) != 0)\n return std::make_pair(Filename,\n std::error_code(errno, std::generic_category()));\n Buffers.push_back(std::move(MemberBufferOrErr.get()));\n MemberRef = Buffers.back()->getMemBufferRef();\n } else {\n object::Archive::child_iterator OldMember = Member.getOld();\n ErrorOr<MemoryBufferRef> MemberBufferOrErr =\n OldMember->getMemoryBufferRef();\n if (auto EC = MemberBufferOrErr.getError())\n return std::make_pair(\"\", EC);\n MemberRef = MemberBufferOrErr.get();\n }\n Members.push_back(MemberRef);\n }\n\n unsigned MemberReferenceOffset = 0;\n if (WriteSymtab) {\n ErrorOr<unsigned> MemberReferenceOffsetOrErr =\n writeSymbolTable(Out, NewMembers, Members, MemberOffsetRefs);\n if (auto EC = MemberReferenceOffsetOrErr.getError())\n return std::make_pair(ArcName, EC);\n MemberReferenceOffset = MemberReferenceOffsetOrErr.get();\n }\n\n std::vector<unsigned> StringMapIndexes;\n writeStringTable(Out, NewMembers, StringMapIndexes);\n\n unsigned MemberNum = 0;\n unsigned LongNameMemberNum = 0;\n unsigned NewMemberNum = 0;\n std::vector<unsigned> MemberOffset;\n for (std::vector<NewArchiveIterator>::iterator I = NewMembers.begin(),\n E = NewMembers.end();\n I != E; ++I, ++MemberNum) {\n\n unsigned Pos = Out.tell();\n MemberOffset.push_back(Pos);\n\n MemoryBufferRef File = Members[MemberNum];\n if (I->isNewMember()) {\n StringRef FileName = I->getNew();\n const sys::fs::file_status &Status = NewMemberStatus[NewMemberNum];\n NewMemberNum++;\n\n StringRef Name = sys::path::filename(FileName);\n if (Name.size() < 16)\n printMemberHeader(Out, Name, Status.getLastModificationTime(),\n Status.getUser(), Status.getGroup(),\n Status.permissions(), Status.getSize());\n else\n printMemberHeader(Out, StringMapIndexes[LongNameMemberNum++],\n Status.getLastModificationTime(), Status.getUser(),\n Status.getGroup(), Status.permissions(),\n Status.getSize());\n } else {\n object::Archive::child_iterator OldMember = I->getOld();\n StringRef Name = I->getName();\n\n if (Name.size() < 16)\n printMemberHeader(Out, Name, OldMember->getLastModified(),\n OldMember->getUID(), OldMember->getGID(),\n OldMember->getAccessMode(), OldMember->getSize());\n else\n printMemberHeader(Out, StringMapIndexes[LongNameMemberNum++],\n OldMember->getLastModified(), OldMember->getUID(),\n OldMember->getGID(), OldMember->getAccessMode(),\n OldMember->getSize());\n }\n\n Out << File.getBuffer();\n\n if (Out.tell() % 2)\n Out << '\\n';\n }\n\n if (MemberReferenceOffset) {\n Out.seek(MemberReferenceOffset);\n for (unsigned MemberNum : MemberOffsetRefs)\n print32BE(Out, MemberOffset[MemberNum]);\n }\n\n Output.keep();\n Out.close();\n sys::fs::rename(TmpArchive, ArcName);\n return std::make_pair(\"\", std::error_code());\n}\n<commit_msg>[ArchiveWriter] Use EndianStream. No functional change intended.<commit_after>\/\/===- ArchiveWriter.cpp - ar File Format implementation --------*- C++ -*-===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This file defines the writeArchive function.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/Object\/ArchiveWriter.h\"\n#include \"llvm\/ADT\/ArrayRef.h\"\n#include \"llvm\/ADT\/StringRef.h\"\n#include \"llvm\/IR\/LLVMContext.h\"\n#include \"llvm\/Object\/Archive.h\"\n#include \"llvm\/Object\/ObjectFile.h\"\n#include \"llvm\/Object\/SymbolicFile.h\"\n#include \"llvm\/Support\/EndianStream.h\"\n#include \"llvm\/Support\/Errc.h\"\n#include \"llvm\/Support\/ErrorHandling.h\"\n#include \"llvm\/Support\/Format.h\"\n#include \"llvm\/Support\/Path.h\"\n#include \"llvm\/Support\/ToolOutputFile.h\"\n#include \"llvm\/Support\/raw_ostream.h\"\n\n#if !defined(_MSC_VER) && !defined(__MINGW32__)\n#include <unistd.h>\n#else\n#include <io.h>\n#endif\n\nusing namespace llvm;\n\nNewArchiveIterator::NewArchiveIterator() {}\n\nNewArchiveIterator::NewArchiveIterator(object::Archive::child_iterator I,\n StringRef Name)\n : IsNewMember(false), Name(Name), OldI(I) {}\n\nNewArchiveIterator::NewArchiveIterator(StringRef NewFilename, StringRef Name)\n : IsNewMember(true), Name(Name), NewFilename(NewFilename) {}\n\nStringRef NewArchiveIterator::getName() const { return Name; }\n\nbool NewArchiveIterator::isNewMember() const { return IsNewMember; }\n\nobject::Archive::child_iterator NewArchiveIterator::getOld() const {\n assert(!IsNewMember);\n return OldI;\n}\n\nStringRef NewArchiveIterator::getNew() const {\n assert(IsNewMember);\n return NewFilename;\n}\n\nllvm::ErrorOr<int>\nNewArchiveIterator::getFD(sys::fs::file_status &NewStatus) const {\n assert(IsNewMember);\n int NewFD;\n if (auto EC = sys::fs::openFileForRead(NewFilename, NewFD))\n return EC;\n assert(NewFD != -1);\n\n if (auto EC = sys::fs::status(NewFD, NewStatus))\n return EC;\n\n \/\/ Opening a directory doesn't make sense. Let it fail.\n \/\/ Linux cannot open directories with open(2), although\n \/\/ cygwin and *bsd can.\n if (NewStatus.type() == sys::fs::file_type::directory_file)\n return make_error_code(errc::is_a_directory);\n\n return NewFD;\n}\n\ntemplate <typename T>\nstatic void printWithSpacePadding(raw_fd_ostream &OS, T Data, unsigned Size,\n\t\t\t\t bool MayTruncate = false) {\n uint64_t OldPos = OS.tell();\n OS << Data;\n unsigned SizeSoFar = OS.tell() - OldPos;\n if (Size > SizeSoFar) {\n OS.indent(Size - SizeSoFar);\n } else if (Size < SizeSoFar) {\n assert(MayTruncate && \"Data doesn't fit in Size\");\n \/\/ Some of the data this is used for (like UID) can be larger than the\n \/\/ space available in the archive format. Truncate in that case.\n OS.seek(OldPos + Size);\n }\n}\n\nstatic void print32BE(raw_ostream &Out, uint32_t Val) {\n support::endian::Writer<support::big>(Out).write(Val);\n}\n\nstatic void printRestOfMemberHeader(raw_fd_ostream &Out,\n const sys::TimeValue &ModTime, unsigned UID,\n unsigned GID, unsigned Perms,\n unsigned Size) {\n printWithSpacePadding(Out, ModTime.toEpochTime(), 12);\n printWithSpacePadding(Out, UID, 6, true);\n printWithSpacePadding(Out, GID, 6, true);\n printWithSpacePadding(Out, format(\"%o\", Perms), 8);\n printWithSpacePadding(Out, Size, 10);\n Out << \"`\\n\";\n}\n\nstatic void printMemberHeader(raw_fd_ostream &Out, StringRef Name,\n const sys::TimeValue &ModTime, unsigned UID,\n unsigned GID, unsigned Perms, unsigned Size) {\n printWithSpacePadding(Out, Twine(Name) + \"\/\", 16);\n printRestOfMemberHeader(Out, ModTime, UID, GID, Perms, Size);\n}\n\nstatic void printMemberHeader(raw_fd_ostream &Out, unsigned NameOffset,\n const sys::TimeValue &ModTime, unsigned UID,\n unsigned GID, unsigned Perms, unsigned Size) {\n Out << '\/';\n printWithSpacePadding(Out, NameOffset, 15);\n printRestOfMemberHeader(Out, ModTime, UID, GID, Perms, Size);\n}\n\nstatic void writeStringTable(raw_fd_ostream &Out,\n ArrayRef<NewArchiveIterator> Members,\n std::vector<unsigned> &StringMapIndexes) {\n unsigned StartOffset = 0;\n for (ArrayRef<NewArchiveIterator>::iterator I = Members.begin(),\n E = Members.end();\n I != E; ++I) {\n StringRef Name = I->getName();\n if (Name.size() < 16)\n continue;\n if (StartOffset == 0) {\n printWithSpacePadding(Out, \"\/\/\", 58);\n Out << \"`\\n\";\n StartOffset = Out.tell();\n }\n StringMapIndexes.push_back(Out.tell() - StartOffset);\n Out << Name << \"\/\\n\";\n }\n if (StartOffset == 0)\n return;\n if (Out.tell() % 2)\n Out << '\\n';\n int Pos = Out.tell();\n Out.seek(StartOffset - 12);\n printWithSpacePadding(Out, Pos - StartOffset, 10);\n Out.seek(Pos);\n}\n\n\/\/ Returns the offset of the first reference to a member offset.\nstatic ErrorOr<unsigned>\nwriteSymbolTable(raw_fd_ostream &Out, ArrayRef<NewArchiveIterator> Members,\n ArrayRef<MemoryBufferRef> Buffers,\n std::vector<unsigned> &MemberOffsetRefs) {\n unsigned StartOffset = 0;\n unsigned MemberNum = 0;\n std::string NameBuf;\n raw_string_ostream NameOS(NameBuf);\n unsigned NumSyms = 0;\n LLVMContext Context;\n for (ArrayRef<NewArchiveIterator>::iterator I = Members.begin(),\n E = Members.end();\n I != E; ++I, ++MemberNum) {\n MemoryBufferRef MemberBuffer = Buffers[MemberNum];\n ErrorOr<std::unique_ptr<object::SymbolicFile>> ObjOrErr =\n object::SymbolicFile::createSymbolicFile(\n MemberBuffer, sys::fs::file_magic::unknown, &Context);\n if (!ObjOrErr)\n continue; \/\/ FIXME: check only for \"not an object file\" errors.\n object::SymbolicFile &Obj = *ObjOrErr.get();\n\n if (!StartOffset) {\n printMemberHeader(Out, \"\", sys::TimeValue::now(), 0, 0, 0, 0);\n StartOffset = Out.tell();\n print32BE(Out, 0);\n }\n\n for (const object::BasicSymbolRef &S : Obj.symbols()) {\n uint32_t Symflags = S.getFlags();\n if (Symflags & object::SymbolRef::SF_FormatSpecific)\n continue;\n if (!(Symflags & object::SymbolRef::SF_Global))\n continue;\n if (Symflags & object::SymbolRef::SF_Undefined)\n continue;\n if (auto EC = S.printName(NameOS))\n return EC;\n NameOS << '\\0';\n ++NumSyms;\n MemberOffsetRefs.push_back(MemberNum);\n print32BE(Out, 0);\n }\n }\n Out << NameOS.str();\n\n if (StartOffset == 0)\n return 0;\n\n if (Out.tell() % 2)\n Out << '\\0';\n\n unsigned Pos = Out.tell();\n Out.seek(StartOffset - 12);\n printWithSpacePadding(Out, Pos - StartOffset, 10);\n Out.seek(StartOffset);\n print32BE(Out, NumSyms);\n Out.seek(Pos);\n return StartOffset + 4;\n}\n\nstd::pair<StringRef, std::error_code>\nllvm::writeArchive(StringRef ArcName,\n std::vector<NewArchiveIterator> &NewMembers,\n bool WriteSymtab) {\n SmallString<128> TmpArchive;\n int TmpArchiveFD;\n if (auto EC = sys::fs::createUniqueFile(ArcName + \".temp-archive-%%%%%%%.a\",\n TmpArchiveFD, TmpArchive))\n return std::make_pair(ArcName, EC);\n\n tool_output_file Output(TmpArchive, TmpArchiveFD);\n raw_fd_ostream &Out = Output.os();\n Out << \"!<arch>\\n\";\n\n std::vector<unsigned> MemberOffsetRefs;\n\n std::vector<std::unique_ptr<MemoryBuffer>> Buffers;\n std::vector<MemoryBufferRef> Members;\n std::vector<sys::fs::file_status> NewMemberStatus;\n\n for (unsigned I = 0, N = NewMembers.size(); I < N; ++I) {\n NewArchiveIterator &Member = NewMembers[I];\n MemoryBufferRef MemberRef;\n\n if (Member.isNewMember()) {\n StringRef Filename = Member.getNew();\n NewMemberStatus.resize(NewMemberStatus.size() + 1);\n sys::fs::file_status &Status = NewMemberStatus.back();\n ErrorOr<int> FD = Member.getFD(Status);\n if (auto EC = FD.getError())\n return std::make_pair(Filename, EC);\n ErrorOr<std::unique_ptr<MemoryBuffer>> MemberBufferOrErr =\n MemoryBuffer::getOpenFile(FD.get(), Filename, Status.getSize(),\n false);\n if (auto EC = MemberBufferOrErr.getError())\n return std::make_pair(Filename, EC);\n if (close(FD.get()) != 0)\n return std::make_pair(Filename,\n std::error_code(errno, std::generic_category()));\n Buffers.push_back(std::move(MemberBufferOrErr.get()));\n MemberRef = Buffers.back()->getMemBufferRef();\n } else {\n object::Archive::child_iterator OldMember = Member.getOld();\n ErrorOr<MemoryBufferRef> MemberBufferOrErr =\n OldMember->getMemoryBufferRef();\n if (auto EC = MemberBufferOrErr.getError())\n return std::make_pair(\"\", EC);\n MemberRef = MemberBufferOrErr.get();\n }\n Members.push_back(MemberRef);\n }\n\n unsigned MemberReferenceOffset = 0;\n if (WriteSymtab) {\n ErrorOr<unsigned> MemberReferenceOffsetOrErr =\n writeSymbolTable(Out, NewMembers, Members, MemberOffsetRefs);\n if (auto EC = MemberReferenceOffsetOrErr.getError())\n return std::make_pair(ArcName, EC);\n MemberReferenceOffset = MemberReferenceOffsetOrErr.get();\n }\n\n std::vector<unsigned> StringMapIndexes;\n writeStringTable(Out, NewMembers, StringMapIndexes);\n\n unsigned MemberNum = 0;\n unsigned LongNameMemberNum = 0;\n unsigned NewMemberNum = 0;\n std::vector<unsigned> MemberOffset;\n for (std::vector<NewArchiveIterator>::iterator I = NewMembers.begin(),\n E = NewMembers.end();\n I != E; ++I, ++MemberNum) {\n\n unsigned Pos = Out.tell();\n MemberOffset.push_back(Pos);\n\n MemoryBufferRef File = Members[MemberNum];\n if (I->isNewMember()) {\n StringRef FileName = I->getNew();\n const sys::fs::file_status &Status = NewMemberStatus[NewMemberNum];\n NewMemberNum++;\n\n StringRef Name = sys::path::filename(FileName);\n if (Name.size() < 16)\n printMemberHeader(Out, Name, Status.getLastModificationTime(),\n Status.getUser(), Status.getGroup(),\n Status.permissions(), Status.getSize());\n else\n printMemberHeader(Out, StringMapIndexes[LongNameMemberNum++],\n Status.getLastModificationTime(), Status.getUser(),\n Status.getGroup(), Status.permissions(),\n Status.getSize());\n } else {\n object::Archive::child_iterator OldMember = I->getOld();\n StringRef Name = I->getName();\n\n if (Name.size() < 16)\n printMemberHeader(Out, Name, OldMember->getLastModified(),\n OldMember->getUID(), OldMember->getGID(),\n OldMember->getAccessMode(), OldMember->getSize());\n else\n printMemberHeader(Out, StringMapIndexes[LongNameMemberNum++],\n OldMember->getLastModified(), OldMember->getUID(),\n OldMember->getGID(), OldMember->getAccessMode(),\n OldMember->getSize());\n }\n\n Out << File.getBuffer();\n\n if (Out.tell() % 2)\n Out << '\\n';\n }\n\n if (MemberReferenceOffset) {\n Out.seek(MemberReferenceOffset);\n for (unsigned MemberNum : MemberOffsetRefs)\n print32BE(Out, MemberOffset[MemberNum]);\n }\n\n Output.keep();\n Out.close();\n sys::fs::rename(TmpArchive, ArcName);\n return std::make_pair(\"\", std::error_code());\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Texan\n * 27.05.12\n *\/\n\n#include <iostream>\n#include <sstream>\n#include \"LoadProfile.hpp\"\n\nLoadProfile::LoadProfile(GameManager& game, std::vector<Profile *>& profiles, std::vector<std::string>& names)\n : AMenu(\"menu\/background\/backgroundLoadProfile.jpg\", \"menu\/background\/backgroundLoadProfile.jpg\", 0.0f, -1.0f, 800.0f, game),\n _profiles(profiles),\n _names(names),\n _index(0),\n _timerL(-1.0f),\n _timerR(-1.0f)\n{\n this->_tags.push_back(new Tag(\"menu\/LoadNormal.png\", \"menu\/LoadHighlit.png\", true, false, TokenMenu::LAST, 700.0f, 0.0f, 1200.0f));\n this->_tags.push_back(new Tag(\"menu\/BlackNormal.png\", \"menu\/BlackHighlit.png\", false, false, TokenMenu::LAST, 900.0f, 0.0f, 1200.0f));\n this->_tags.push_back(new Tag(\"menu\/BlackNormal.png\", \"menu\/BlackHighlit.png\", false, false, TokenMenu::LAST, 900.0f, 0.0f, 1250.0f));\n this->_tags.push_back(new Tag(\"menu\/DoneNormal.png\", \"menu\/DoneHighlit.png\", false, false, TokenMenu::PROFILE, 700.0f, 0.0f, 1300.0f));\n this->_tags.push_back(new Tag(\"menu\/BackNormal.png\", \"menu\/BackHighlit.png\", false, false, TokenMenu::MAINMENU, 700.0f, 0.0f, 1350.0f));\n\n}\n\nLoadProfile::~LoadProfile(void)\n{\n}\n\ndouble\tLoadProfile::getCenterX() const\n{\n return (800.0f);\n}\n\ndouble\tLoadProfile::getCenterY() const\n{\n return (1200.0f);\n}\n\nvoid\t\tLoadProfile::updateText() const\n{\n std::stringstream\tss;\n \n if (this->_profiles.size())\n {\n this->_tags[1]->createText(this->_names[this->_index], 20, 950, 270);\n ss << \" Skin : \" << this->_profiles[this->_index]->getSkin();\n this->_tags[2]->createText(ss.str(), 20, 950, 310);\n }\n else\n {\n this->_tags[1]->createText(\"\", 20, 950, 270);\n this->_tags[2]->createText(\"\", 20, 950, 310);\n }\n}\n\nvoid\t\tLoadProfile::changeProfile(gdl::GameClock const& clock, gdl::Input& input)\n{\n if (clock.getTotalGameTime() >= this->_timerL && input.isKeyDown(gdl::Keys::Left))\n {\n --this->_index;\n if (static_cast<int>(this->_index) < 0)\n\tthis->_index = this->_profiles.size() - 1;\n this->_timerL = clock.getTotalGameTime() + 0.15f;\n }\n else if (clock.getTotalGameTime() >= this->_timerR && input.isKeyDown(gdl::Keys::Right))\n {\n ++this->_index;\n if (this->_index >= this->_profiles.size())\n\tthis->_index = 0;\n this->_timerR = clock.getTotalGameTime() + 0.15f;\n }\n}\n\nvoid\tLoadProfile::update(gdl::GameClock const& clock, gdl::Input& input)\n{\n std::cout << this->_profiles.size() << std::endl;\n this->updateText();\n for (size_t i = 0; i < this->_keyEvent.size(); ++i)\n if (input.isKeyDown(this->_keyEvent[i].first))\n (this->*_keyEvent[i].second)(clock);\n if (this->_cursor == 0) \/\/TODO pointer function\n this->changeProfile(clock, input);\n else if (this->_cursor == 1)\n {\n this->_tags[this->_cursor]->setStatus(false);\n this->_cursor = 3;\n this->_tags[this->_cursor]->setStatus(true);\n \n }\n else if (this->_cursor == 2)\n {\n this->_tags[this->_cursor]->setStatus(false);\n this->_cursor = 0;\n this->_tags[this->_cursor]->setStatus(true);\n \n }\n\n if (this->_curToken == TokenMenu::PROFILE)\n if (this->_profiles.size())\n this->_gameManager._mainProfile = this->_profiles[this->_index];\n else\n this->_curToken = TokenMenu::LAST;\n}\n<commit_msg>Added braces between an if else to avoid warning<commit_after>\/*\n * Texan\n * 27.05.12\n *\/\n\n#include <iostream>\n#include <sstream>\n#include \"LoadProfile.hpp\"\n\nLoadProfile::LoadProfile(GameManager& game, std::vector<Profile *>& profiles, std::vector<std::string>& names)\n : AMenu(\"menu\/background\/backgroundLoadProfile.jpg\", \"menu\/background\/backgroundLoadProfile.jpg\", 0.0f, -1.0f, 800.0f, game),\n _profiles(profiles),\n _names(names),\n _index(0),\n _timerL(-1.0f),\n _timerR(-1.0f)\n{\n this->_tags.push_back(new Tag(\"menu\/LoadNormal.png\", \"menu\/LoadHighlit.png\", true, false, TokenMenu::LAST, 700.0f, 0.0f, 1200.0f));\n this->_tags.push_back(new Tag(\"menu\/BlackNormal.png\", \"menu\/BlackHighlit.png\", false, false, TokenMenu::LAST, 900.0f, 0.0f, 1200.0f));\n this->_tags.push_back(new Tag(\"menu\/BlackNormal.png\", \"menu\/BlackHighlit.png\", false, false, TokenMenu::LAST, 900.0f, 0.0f, 1250.0f));\n this->_tags.push_back(new Tag(\"menu\/DoneNormal.png\", \"menu\/DoneHighlit.png\", false, false, TokenMenu::PROFILE, 700.0f, 0.0f, 1300.0f));\n this->_tags.push_back(new Tag(\"menu\/BackNormal.png\", \"menu\/BackHighlit.png\", false, false, TokenMenu::MAINMENU, 700.0f, 0.0f, 1350.0f));\n\n}\n\nLoadProfile::~LoadProfile(void)\n{\n}\n\ndouble\tLoadProfile::getCenterX() const\n{\n return (800.0f);\n}\n\ndouble\tLoadProfile::getCenterY() const\n{\n return (1200.0f);\n}\n\nvoid\t\tLoadProfile::updateText() const\n{\n std::stringstream\tss;\n \n if (this->_profiles.size())\n {\n this->_tags[1]->createText(this->_names[this->_index], 20, 950, 270);\n ss << \" Skin : \" << this->_profiles[this->_index]->getSkin();\n this->_tags[2]->createText(ss.str(), 20, 950, 310);\n }\n else\n {\n this->_tags[1]->createText(\"\", 20, 950, 270);\n this->_tags[2]->createText(\"\", 20, 950, 310);\n }\n}\n\nvoid\t\tLoadProfile::changeProfile(gdl::GameClock const& clock, gdl::Input& input)\n{\n if (clock.getTotalGameTime() >= this->_timerL && input.isKeyDown(gdl::Keys::Left))\n {\n --this->_index;\n if (static_cast<int>(this->_index) < 0)\n\tthis->_index = this->_profiles.size() - 1;\n this->_timerL = clock.getTotalGameTime() + 0.15f;\n }\n else if (clock.getTotalGameTime() >= this->_timerR && input.isKeyDown(gdl::Keys::Right))\n {\n ++this->_index;\n if (this->_index >= this->_profiles.size())\n\tthis->_index = 0;\n this->_timerR = clock.getTotalGameTime() + 0.15f;\n }\n}\n\nvoid\tLoadProfile::update(gdl::GameClock const& clock, gdl::Input& input)\n{\n std::cout << this->_profiles.size() << std::endl;\n this->updateText();\n for (size_t i = 0; i < this->_keyEvent.size(); ++i)\n if (input.isKeyDown(this->_keyEvent[i].first))\n (this->*_keyEvent[i].second)(clock);\n if (this->_cursor == 0) \/\/TODO pointer function\n this->changeProfile(clock, input);\n else if (this->_cursor == 1)\n {\n this->_tags[this->_cursor]->setStatus(false);\n this->_cursor = 3;\n this->_tags[this->_cursor]->setStatus(true);\n \n }\n else if (this->_cursor == 2)\n {\n this->_tags[this->_cursor]->setStatus(false);\n this->_cursor = 0;\n this->_tags[this->_cursor]->setStatus(true);\n \n }\n\n if (this->_curToken == TokenMenu::PROFILE)\n {\n if (this->_profiles.size())\n\tthis->_gameManager._mainProfile = this->_profiles[this->_index];\n else\n\tthis->_curToken = TokenMenu::LAST;\n }\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"LuaGLWidget.h\"\n#include <QFile>\n#include <QVector3D>\n#include \"util.h\"\n#include \"LuaGlobal.hpp\"\n\n#include <cmath>\n\nstatic float func(const float& x, const float& z)\n{\n\treturn cos(x) * log(z);\n}\n\nLuaGLWidget::LuaGLWidget(QWidget* const parent) :\n\tGLWidget(parent),\n\ttimer(this, 1000 \/ 60)\n{\n\tconnect(&timer, SIGNAL(timeout(const float&)), this, SLOT(tick(const float&)));\n\tconnect(&timer, SIGNAL(timeout(const float&)), this, SLOT(updateGL()));\n\ttimer.startOnShow(this);\n\tupdate(func);\n}\n\nvoid LuaGLWidget::initializeGL()\n{\n\tglEnable(GL_DEPTH_TEST);\n\tglEnable(GL_CULL_FACE);\n\tglShadeModel(GL_SMOOTH);\n\tglEnable(GL_LIGHTING);\n\tglEnable(GL_LIGHT0);\n\tglEnable(GL_COLOR_MATERIAL);\n\tglColorMaterial(GL_FRONT, GL_AMBIENT_AND_DIFFUSE);\n\tsceneList = glGenLists(1);\n\tglNewList(sceneList, GL_COMPILE);\n\trenderScene();\n\tglEndList();\n}\n\nvoid LuaGLWidget::tick(const float&)\n{\n}\n\nvoid LuaGLWidget::renderScene()\n{\n\tglTranslatef(0, -HALFSIZE\/8, 0);\n\tglBegin(GL_QUADS);\n\tfor (int y = -HALFSIZE; y < HALFSIZE-1; y++) {\n\t\tfor (int x = -HALFSIZE; x < HALFSIZE-1; x++) {\n\t\t\t\/\/ XXX This code is recklessly inefficient; we either don't need\n\t\t\t\/\/ QVector3D's or we should reuse objects outside of this loop.\n\t\t\tQVector3D a(x, AMPLITUDE*get(x, y), y);\n\t\t\tQVector3D b(x, AMPLITUDE*get(x, y+1), y+1);\n\t\t\tQVector3D c(x+1, AMPLITUDE*get(x+1, y+1), y+1);\n\t\t\tQVector3D d(x+1, AMPLITUDE*get(x+1, y), y);\n\t\t\tQVector3D norm = normal(x,y);\n\t\t\t\/\/ FIXME These normals produce visible edges; I think the average\n\t\t\t\/\/ is generated incorrectly.\n\t\t\tQVector3D rnorm = average(norm, normal(x, y+1));\n\t\t\tQVector3D tnorm = average(norm, normal(x+1, y));\n\t\t\tQVector3D lnorm = average(norm, normal(x, y-1));\n\t\t\tQVector3D bnorm = average(norm, normal(x-1, y));\n\t\t\trenderNormal(average(rnorm, bnorm));\n\t\t\trenderVertex(b);\n\t\t\trenderNormal(average(rnorm, tnorm));\n\t\t\trenderVertex(c);\n\t\t\trenderNormal(average(lnorm, tnorm));\n\t\t\trenderVertex(d);\n\t\t\trenderNormal(average(lnorm, bnorm));\n\t\t\trenderVertex(a);\n\t\t}\n\t}\n\tglEnd();\n}\n\nvoid LuaGLWidget::render()\n{\n\tglClear(GL_DEPTH_BUFFER_BIT);\n\tglCallList(sceneList);\n}\n\nvoid LuaGLWidget::resizeGL(int width, int height)\n{\n\tglViewport(0, 0, width, height);\n\tglMatrixMode(GL_PROJECTION);\n\tglLoadIdentity();\n\tnt::setGLFrustrum(60, (float) width \/ height, 1, 800);\n\tglMatrixMode(GL_MODELVIEW);\n}\n\nLuaGLWidget::~LuaGLWidget()\n{\n\tglDeleteLists(sceneList, 1);\n}\n<commit_msg>Orient Lua's camera towards the action<commit_after>#include \"LuaGLWidget.h\"\n#include <QFile>\n#include <QVector3D>\n#include \"util.h\"\n#include \"LuaGlobal.hpp\"\n\n#include <cmath>\n\nstatic float func(const float& x, const float& z)\n{\n\treturn cos(x) * log(z);\n}\n\nLuaGLWidget::LuaGLWidget(QWidget* const parent) :\n\tGLWidget(parent),\n\ttimer(this, 1000 \/ 60)\n{\n\tconnect(&timer, SIGNAL(timeout(const float&)), this, SLOT(tick(const float&)));\n\tconnect(&timer, SIGNAL(timeout(const float&)), this, SLOT(updateGL()));\n\ttimer.startOnShow(this);\n\tupdate(func);\n}\n\nvoid LuaGLWidget::initializeGL()\n{\n\tglEnable(GL_DEPTH_TEST);\n\tglEnable(GL_CULL_FACE);\n\tglShadeModel(GL_SMOOTH);\n\tglEnable(GL_LIGHTING);\n\tglEnable(GL_LIGHT0);\n\tglEnable(GL_COLOR_MATERIAL);\n\tglColorMaterial(GL_FRONT, GL_AMBIENT_AND_DIFFUSE);\n\tsceneList = glGenLists(1);\n\tglNewList(sceneList, GL_COMPILE);\n\trenderScene();\n\tglEndList();\n}\n\nvoid LuaGLWidget::tick(const float&)\n{\n}\n\nvoid LuaGLWidget::renderScene()\n{\n\tglTranslatef(0, -HALFSIZE\/8, 0);\n\tglRotatef(-150, 0, 1, 0);\n\tglRotatef(-10, 1, 0, 0);\n\tglBegin(GL_QUADS);\n\tfor (int y = -HALFSIZE; y < HALFSIZE-1; y++) {\n\t\tfor (int x = -HALFSIZE; x < HALFSIZE-1; x++) {\n\t\t\t\/\/ XXX This code is recklessly inefficient; we either don't need\n\t\t\t\/\/ QVector3D's or we should reuse objects outside of this loop.\n\t\t\tQVector3D a(x, AMPLITUDE*get(x, y), y);\n\t\t\tQVector3D b(x, AMPLITUDE*get(x, y+1), y+1);\n\t\t\tQVector3D c(x+1, AMPLITUDE*get(x+1, y+1), y+1);\n\t\t\tQVector3D d(x+1, AMPLITUDE*get(x+1, y), y);\n\t\t\tQVector3D norm = normal(x,y);\n\t\t\t\/\/ FIXME These normals produce visible edges; I think the average\n\t\t\t\/\/ is generated incorrectly.\n\t\t\tQVector3D rnorm = average(norm, normal(x, y+1));\n\t\t\tQVector3D tnorm = average(norm, normal(x+1, y));\n\t\t\tQVector3D lnorm = average(norm, normal(x, y-1));\n\t\t\tQVector3D bnorm = average(norm, normal(x-1, y));\n\t\t\trenderNormal(average(rnorm, bnorm));\n\t\t\trenderVertex(b);\n\t\t\trenderNormal(average(rnorm, tnorm));\n\t\t\trenderVertex(c);\n\t\t\trenderNormal(average(lnorm, tnorm));\n\t\t\trenderVertex(d);\n\t\t\trenderNormal(average(lnorm, bnorm));\n\t\t\trenderVertex(a);\n\t\t}\n\t}\n\tglEnd();\n}\n\nvoid LuaGLWidget::render()\n{\n\tglClear(GL_DEPTH_BUFFER_BIT);\n\tglCallList(sceneList);\n}\n\nvoid LuaGLWidget::resizeGL(int width, int height)\n{\n\tglViewport(0, 0, width, height);\n\tglMatrixMode(GL_PROJECTION);\n\tglLoadIdentity();\n\tnt::setGLFrustrum(60, (float) width \/ height, 1, 800);\n\tglMatrixMode(GL_MODELVIEW);\n}\n\nLuaGLWidget::~LuaGLWidget()\n{\n\tglDeleteLists(sceneList, 1);\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * tcp_epoll.cpp\n *\n * Created on: Nov 10, 2014\n * Author: liao\n *\/\n#include <cstdlib>\n#include <climits>\n#include <cstdio>\n#include <cerrno>\n#include <netinet\/in.h>\n#include <arpa\/inet.h>\n#include <sys\/socket.h>\n#include <sys\/time.h>\n#include <sys\/epoll.h>\n#include <sys\/fcntl.h>\n#include <sys\/sysinfo.h>\n#include <unistd.h>\n\n#include \"simple_log.h\"\n#include \"epoll_socket.h\"\n\nEpollSocket::EpollSocket() {\n _thread_pool = NULL;\n _use_default_tp = true;\n _status = S_RUN;\n _epollfd = -1;\n _clients = 0;\n pthread_mutex_init(&_client_lock, NULL);\n}\n\nEpollSocket::~EpollSocket() {\n if (_thread_pool != NULL && _use_default_tp) {\n delete _thread_pool;\n _thread_pool = NULL;\n }\n}\n\nint EpollSocket::set_nonblocking(int fd) {\n int flags;\n\n if (-1 == (flags = fcntl(fd, F_GETFL, 0)))\n flags = 0;\n return fcntl(fd, F_SETFL, flags | O_NONBLOCK);\n};\n\nint EpollSocket::bind_on(unsigned int ip) {\n \/* listen on sock_fd, new connection on new_fd *\/\n int sockfd = socket(AF_INET, SOCK_STREAM, 0);\n if (sockfd == -1) {\n LOG_ERROR(\"socket error:%s\", strerror(errno));\n return -1;\n }\n int opt = 1;\n setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));\n\n struct sockaddr_in my_addr; \/* my address information *\/\n memset (&my_addr, 0, sizeof(my_addr));\n my_addr.sin_family = AF_INET; \/* host byte order *\/\n my_addr.sin_port = htons(_port); \/* short, network byte order *\/\n my_addr.sin_addr.s_addr = ip;\n\n if (bind(sockfd, (struct sockaddr *) &my_addr, sizeof(struct sockaddr)) == -1) {\n LOG_ERROR(\"bind error:%s\", strerror(errno));\n return -1;\n }\n if (listen(sockfd, _backlog) == -1) {\n LOG_ERROR(\"listen error:%s\", strerror(errno));\n return -1;\n }\n _listen_sockets.insert(sockfd);\n return 0;\n}\n\nint EpollSocket::listen_on() {\n if (_bind_ips.empty()) {\n int ret = bind_on(INADDR_ANY); \/* auto-fill with my IP *\/\n if (ret != 0) {\n return ret;\n }\n LOG_INFO(\"bind for all ip (0.0.0.0)!\");\n } else {\n for (size_t i = 0; i < _bind_ips.size(); i++) {\n unsigned ip = inet_addr(_bind_ips[i].c_str());\n int ret = bind_on(ip);\n if (ret != 0) {\n return ret;\n }\n LOG_INFO(\"bind for ip:%s success\", _bind_ips[i].c_str());\n }\n }\n\n LOG_INFO(\"start Server Socket on port : %d\", _port);\n return 0;\n}\n\nint EpollSocket::accept_socket(int sockfd, std::string &client_ip) {\n int new_fd;\n struct sockaddr_in their_addr; \/* connector's address information *\/\n socklen_t sin_size = sizeof(struct sockaddr_in);\n\n if ((new_fd = accept(sockfd, (struct sockaddr *) &their_addr, &sin_size)) == -1) {\n LOG_ERROR(\"accept error:%s\", strerror(errno));\n return -1;\n }\n\n client_ip = inet_ntoa(their_addr.sin_addr);\n LOG_DEBUG(\"server: got connection from %s\\n\", client_ip.c_str());\n return new_fd;\n}\n\nint EpollSocket::handle_accept_event(int &epollfd, epoll_event &event, EpollSocketWatcher &socket_handler) {\n int sockfd = event.data.fd;\n\n std::string client_ip;\n int conn_sock = accept_socket(sockfd, client_ip);\n if (conn_sock == -1) {\n return -1;\n }\n set_nonblocking(conn_sock);\n\n pthread_mutex_lock(&_client_lock);\n _clients++;\n pthread_mutex_unlock(&_client_lock);\n LOG_DEBUG(\"get accept socket which listen fd:%d, conn_sock_fd:%d\", sockfd, conn_sock);\n\n EpollContext *epoll_context = new EpollContext();\n epoll_context->fd = conn_sock;\n epoll_context->client_ip = client_ip;\n\n socket_handler.on_accept(*epoll_context);\n\n struct epoll_event conn_sock_ev;\n conn_sock_ev.events = EPOLLIN | EPOLLONESHOT;\n conn_sock_ev.data.ptr = epoll_context;\n\n if (epoll_ctl(_epollfd, EPOLL_CTL_ADD, conn_sock, &conn_sock_ev) == -1) {\n LOG_ERROR(\"epoll_ctl: conn_sock:%s\", strerror(errno));\n close_and_release(conn_sock_ev);\n return -1;\n }\n return 0;\n}\n\nvoid read_func(void *data) {\n TaskData *td = (TaskData *) data;\n td->es->handle_readable_event(td->event);\n delete td;\n}\n\nint EpollSocket::handle_readable_event(epoll_event &event) {\n EpollContext *epoll_context = (EpollContext *) event.data.ptr;\n int fd = epoll_context->fd;\n\n int ret = _watcher->on_readable(_epollfd, event);\n if (ret == READ_CLOSE) {\n return close_and_release(event);\n }\n if (ret == READ_CONTINUE) {\n event.events = EPOLLIN | EPOLLONESHOT;\n epoll_ctl(_epollfd, EPOLL_CTL_MOD, fd, &event);\n } else if (ret == READ_OVER) { \/\/ READ_OVER\n event.events = EPOLLOUT | EPOLLONESHOT;\n epoll_ctl(_epollfd, EPOLL_CTL_MOD, fd, &event);\n } else {\n LOG_ERROR(\"unkonw read ret:%d\", ret);\n }\n return 0;\n}\n\nint EpollSocket::handle_writeable_event(int &epollfd, epoll_event &event, EpollSocketWatcher &socket_handler) {\n EpollContext *epoll_context = (EpollContext *) event.data.ptr;\n int fd = epoll_context->fd;\n LOG_DEBUG(\"start write data\");\n\n int ret = socket_handler.on_writeable(*epoll_context);\n if(ret == WRITE_CONN_CLOSE) {\n return close_and_release(event);\n }\n\n if (ret == WRITE_CONN_CONTINUE) {\n event.events = EPOLLOUT | EPOLLONESHOT;\n } else if (ret == WRITE_CONN_ALIVE) {\n if (_status == S_REJECT_CONN) {\n return close_and_release(event);\n }\n \/\/ wait for next request\n event.events = EPOLLIN | EPOLLONESHOT;\n } else {\n LOG_ERROR(\"unkonw write ret:%d\", ret);\n }\n epoll_ctl(epollfd, EPOLL_CTL_MOD, fd, &event);\n\n return 0;\n}\n\nvoid EpollSocket::set_thread_pool(ThreadPool *tp) {\n this->_thread_pool = tp;\n _use_default_tp = false;\n}\n\nvoid EpollSocket::set_port(int port) {\n _port = port;\n}\n\nvoid EpollSocket::set_watcher(EpollSocketWatcher *w) {\n _watcher = w;\n}\n\nvoid EpollSocket::set_backlog(int backlog) {\n _backlog = backlog;\n}\n\nvoid EpollSocket::set_max_events(int me) {\n _max_events = me;\n}\n\nint EpollSocket::init_default_tp() {\n int core_size = get_nprocs();\n LOG_INFO(\"thread pool not set, we will build for core size:%d\", core_size);\n _thread_pool = new ThreadPool();\n _thread_pool->set_pool_size(core_size);\n\n return 0;\n}\n\nint EpollSocket::add_listen_sock_to_epoll() {\n for (std::set<int>::iterator i = _listen_sockets.begin(); i != _listen_sockets.end(); i++) {\n int sockfd = *i;\n struct epoll_event ev;\n ev.events = EPOLLIN;\n ev.data.fd = sockfd;\n if (epoll_ctl(_epollfd, EPOLL_CTL_ADD, sockfd, &ev) == -1) {\n LOG_ERROR(\"epoll_ctl: listen_sock:%s\", strerror(errno));\n return -1;\n }\n }\n return 0;\n}\n\nint EpollSocket::handle_event(epoll_event &e) {\n if (_listen_sockets.count(e.data.fd)) {\n \/\/ accept connection\n if (_status == S_RUN) {\n this->handle_accept_event(_epollfd, e, *_watcher);\n } else {\n LOG_INFO(\"current status:%d, not accept new connect\", _status);\n pthread_mutex_lock(&_client_lock);\n if (_clients == 0 && _status == S_REJECT_CONN) {\n _status = S_STOP;\n LOG_INFO(\"client is empty and ready for stop server!\");\n }\n pthread_mutex_unlock(&_client_lock);\n }\n } else if (e.events & EPOLLIN) {\n \/\/ handle readable async\n LOG_DEBUG(\"start handle readable event\");\n TaskData *tdata = new TaskData();\n tdata->event = e;\n tdata->es = this;\n\n Task *task = new Task(read_func, tdata);\n int ret = _thread_pool->add_task(task);\n if (ret != 0) {\n LOG_WARN(\"add read task fail:%d, we will close connect.\", ret);\n close_and_release(e);\n delete tdata;\n delete task;\n }\n } else if (e.events & EPOLLOUT) {\n \/\/ writeable\n this->handle_writeable_event(_epollfd, e, *_watcher);\n } else {\n LOG_INFO(\"unkonw events :%d\", e.events);\n }\n return 0;\n}\n\nint EpollSocket::create_epoll() {\n \/\/ The \"size\" parameter is a hint specifying the number of file\n \/\/ descriptors to be associated with the new instance.\n _epollfd = epoll_create(1024);\n if (_epollfd == -1) {\n LOG_ERROR(\"epoll_create:%s\", strerror(errno));\n return -1;\n }\n return 0;\n}\n\nint EpollSocket::init_tp() {\n if (_thread_pool == NULL) {\n init_default_tp();\n }\n int ret = _thread_pool->start_threadpool();\n return ret;\n}\n\nint EpollSocket::start_event_loop() {\n epoll_event *events = new epoll_event[_max_events];\n while (_status != S_STOP) {\n int fds_num = epoll_wait(_epollfd, events, _max_events, -1);\n if (fds_num == -1) {\n if (errno == EINTR) { \/*The call was interrupted by a signal handler*\/\n continue;\n }\n LOG_ERROR(\"epoll_wait error:%s\", strerror(errno));\n break;\n }\n\n for (int i = 0; i < fds_num; i++) {\n this->handle_event(events[i]);\n }\n }\n LOG_INFO(\"epoll wait loop stop ...\");\n if (events != NULL) {\n delete[] events;\n events = NULL;\n }\n return 0;\n}\n\nint EpollSocket::start_epoll() {\n int ret = init_tp();\n CHECK_RET(ret, \"thread pool start error:%d\", ret);\n\n ret = this->listen_on();\n CHECK_RET(ret, \"listen err:%d\", ret);\n\n ret = this->create_epoll();\n CHECK_RET(ret, \"create epoll err:%d\", ret);\n\n ret = this->add_listen_sock_to_epoll();\n CHECK_RET(ret , \"add listen sock to epoll fail:%d\", ret);\n\n return start_event_loop();\n}\n\nint EpollSocket::stop_epoll() {\n _status = S_REJECT_CONN;\n LOG_INFO(\"stop epoll , current clients:%u\", _clients);\n return 0;\n}\n\nint EpollSocket::close_and_release(epoll_event &epoll_event) {\n if (epoll_event.data.ptr == NULL) {\n return 0;\n }\n LOG_DEBUG(\"connect close\");\n\n EpollContext *hc = (EpollContext *) epoll_event.data.ptr;\n _watcher->on_close(*hc);\n\n int fd = hc->fd;\n epoll_event.events = EPOLLIN | EPOLLOUT;\n epoll_ctl(_epollfd, EPOLL_CTL_DEL, fd, &epoll_event);\n\n delete (EpollContext *) epoll_event.data.ptr;\n epoll_event.data.ptr = NULL;\n\n int ret = close(fd);\n\n pthread_mutex_lock(&_client_lock);\n _clients--;\n if (_clients == 0 && _status == S_REJECT_CONN) {\n _status = S_STOP;\n LOG_INFO(\"client is empty and ready for stop server!\");\n }\n pthread_mutex_unlock(&_client_lock);\n\n LOG_DEBUG(\"connect close complete which fd:%d, ret:%d\", fd, ret);\n return ret;\n}\n\nvoid EpollSocket::add_bind_ip(std::string ip) {\n _bind_ips.push_back(ip);\n}\n<commit_msg>ignore broken pipe signal<commit_after>\/*\n * tcp_epoll.cpp\n *\n * Created on: Nov 10, 2014\n * Author: liao\n *\/\n#include <cstdlib>\n#include <climits>\n#include <cstdio>\n#include <cerrno>\n#include <netinet\/in.h>\n#include <arpa\/inet.h>\n#include <sys\/socket.h>\n#include <sys\/time.h>\n#include <sys\/epoll.h>\n#include <sys\/fcntl.h>\n#include <sys\/sysinfo.h>\n#include <unistd.h>\n\n#include \"simple_log.h\"\n#include \"epoll_socket.h\"\n\nEpollSocket::EpollSocket() {\n _thread_pool = NULL;\n _use_default_tp = true;\n _status = S_RUN;\n _epollfd = -1;\n _clients = 0;\n pthread_mutex_init(&_client_lock, NULL);\n}\n\nEpollSocket::~EpollSocket() {\n if (_thread_pool != NULL && _use_default_tp) {\n delete _thread_pool;\n _thread_pool = NULL;\n }\n}\n\nint EpollSocket::set_nonblocking(int fd) {\n int flags;\n\n if (-1 == (flags = fcntl(fd, F_GETFL, 0)))\n flags = 0;\n return fcntl(fd, F_SETFL, flags | O_NONBLOCK);\n};\n\nint EpollSocket::bind_on(unsigned int ip) {\n \/* listen on sock_fd, new connection on new_fd *\/\n int sockfd = socket(AF_INET, SOCK_STREAM, 0);\n if (sockfd == -1) {\n LOG_ERROR(\"socket error:%s\", strerror(errno));\n return -1;\n }\n int opt = 1;\n setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));\n\n struct sockaddr_in my_addr; \/* my address information *\/\n memset (&my_addr, 0, sizeof(my_addr));\n my_addr.sin_family = AF_INET; \/* host byte order *\/\n my_addr.sin_port = htons(_port); \/* short, network byte order *\/\n my_addr.sin_addr.s_addr = ip;\n\n if (bind(sockfd, (struct sockaddr *) &my_addr, sizeof(struct sockaddr)) == -1) {\n LOG_ERROR(\"bind error:%s\", strerror(errno));\n return -1;\n }\n if (listen(sockfd, _backlog) == -1) {\n LOG_ERROR(\"listen error:%s\", strerror(errno));\n return -1;\n }\n _listen_sockets.insert(sockfd);\n return 0;\n}\n\nint EpollSocket::listen_on() {\n if (_bind_ips.empty()) {\n int ret = bind_on(INADDR_ANY); \/* auto-fill with my IP *\/\n if (ret != 0) {\n return ret;\n }\n LOG_INFO(\"bind for all ip (0.0.0.0)!\");\n } else {\n for (size_t i = 0; i < _bind_ips.size(); i++) {\n unsigned ip = inet_addr(_bind_ips[i].c_str());\n int ret = bind_on(ip);\n if (ret != 0) {\n return ret;\n }\n LOG_INFO(\"bind for ip:%s success\", _bind_ips[i].c_str());\n }\n }\n\n LOG_INFO(\"start Server Socket on port : %d\", _port);\n return 0;\n}\n\nint EpollSocket::accept_socket(int sockfd, std::string &client_ip) {\n int new_fd;\n struct sockaddr_in their_addr; \/* connector's address information *\/\n socklen_t sin_size = sizeof(struct sockaddr_in);\n\n if ((new_fd = accept(sockfd, (struct sockaddr *) &their_addr, &sin_size)) == -1) {\n LOG_ERROR(\"accept error:%s\", strerror(errno));\n return -1;\n }\n\n client_ip = inet_ntoa(their_addr.sin_addr);\n LOG_DEBUG(\"server: got connection from %s\\n\", client_ip.c_str());\n return new_fd;\n}\n\nint EpollSocket::handle_accept_event(int &epollfd, epoll_event &event, EpollSocketWatcher &socket_handler) {\n int sockfd = event.data.fd;\n\n std::string client_ip;\n int conn_sock = accept_socket(sockfd, client_ip);\n if (conn_sock == -1) {\n return -1;\n }\n set_nonblocking(conn_sock);\n\n pthread_mutex_lock(&_client_lock);\n _clients++;\n pthread_mutex_unlock(&_client_lock);\n LOG_DEBUG(\"get accept socket which listen fd:%d, conn_sock_fd:%d\", sockfd, conn_sock);\n\n EpollContext *epoll_context = new EpollContext();\n epoll_context->fd = conn_sock;\n epoll_context->client_ip = client_ip;\n\n socket_handler.on_accept(*epoll_context);\n\n struct epoll_event conn_sock_ev;\n conn_sock_ev.events = EPOLLIN | EPOLLONESHOT;\n conn_sock_ev.data.ptr = epoll_context;\n\n if (epoll_ctl(_epollfd, EPOLL_CTL_ADD, conn_sock, &conn_sock_ev) == -1) {\n LOG_ERROR(\"epoll_ctl: conn_sock:%s\", strerror(errno));\n close_and_release(conn_sock_ev);\n return -1;\n }\n return 0;\n}\n\nvoid read_func(void *data) {\n TaskData *td = (TaskData *) data;\n td->es->handle_readable_event(td->event);\n delete td;\n}\n\nint EpollSocket::handle_readable_event(epoll_event &event) {\n EpollContext *epoll_context = (EpollContext *) event.data.ptr;\n int fd = epoll_context->fd;\n\n int ret = _watcher->on_readable(_epollfd, event);\n if (ret == READ_CLOSE) {\n return close_and_release(event);\n }\n if (ret == READ_CONTINUE) {\n event.events = EPOLLIN | EPOLLONESHOT;\n epoll_ctl(_epollfd, EPOLL_CTL_MOD, fd, &event);\n } else if (ret == READ_OVER) { \/\/ READ_OVER\n event.events = EPOLLOUT | EPOLLONESHOT;\n epoll_ctl(_epollfd, EPOLL_CTL_MOD, fd, &event);\n } else {\n LOG_ERROR(\"unkonw read ret:%d\", ret);\n }\n return 0;\n}\n\nint EpollSocket::handle_writeable_event(int &epollfd, epoll_event &event, EpollSocketWatcher &socket_handler) {\n EpollContext *epoll_context = (EpollContext *) event.data.ptr;\n int fd = epoll_context->fd;\n LOG_DEBUG(\"start write data\");\n\n int ret = socket_handler.on_writeable(*epoll_context);\n if(ret == WRITE_CONN_CLOSE) {\n return close_and_release(event);\n }\n\n if (ret == WRITE_CONN_CONTINUE) {\n event.events = EPOLLOUT | EPOLLONESHOT;\n } else if (ret == WRITE_CONN_ALIVE) {\n if (_status == S_REJECT_CONN) {\n return close_and_release(event);\n }\n \/\/ wait for next request\n event.events = EPOLLIN | EPOLLONESHOT;\n } else {\n LOG_ERROR(\"unkonw write ret:%d\", ret);\n }\n epoll_ctl(epollfd, EPOLL_CTL_MOD, fd, &event);\n\n return 0;\n}\n\nvoid EpollSocket::set_thread_pool(ThreadPool *tp) {\n this->_thread_pool = tp;\n _use_default_tp = false;\n}\n\nvoid EpollSocket::set_port(int port) {\n _port = port;\n}\n\nvoid EpollSocket::set_watcher(EpollSocketWatcher *w) {\n _watcher = w;\n}\n\nvoid EpollSocket::set_backlog(int backlog) {\n _backlog = backlog;\n}\n\nvoid EpollSocket::set_max_events(int me) {\n _max_events = me;\n}\n\nint EpollSocket::init_default_tp() {\n int core_size = get_nprocs();\n LOG_INFO(\"thread pool not set, we will build for core size:%d\", core_size);\n _thread_pool = new ThreadPool();\n _thread_pool->set_pool_size(core_size);\n\n return 0;\n}\n\nint EpollSocket::add_listen_sock_to_epoll() {\n for (std::set<int>::iterator i = _listen_sockets.begin(); i != _listen_sockets.end(); i++) {\n int sockfd = *i;\n struct epoll_event ev;\n ev.events = EPOLLIN;\n ev.data.fd = sockfd;\n if (epoll_ctl(_epollfd, EPOLL_CTL_ADD, sockfd, &ev) == -1) {\n LOG_ERROR(\"epoll_ctl: listen_sock:%s\", strerror(errno));\n return -1;\n }\n }\n return 0;\n}\n\nint EpollSocket::handle_event(epoll_event &e) {\n if (_listen_sockets.count(e.data.fd)) {\n \/\/ accept connection\n if (_status == S_RUN) {\n this->handle_accept_event(_epollfd, e, *_watcher);\n } else {\n LOG_INFO(\"current status:%d, not accept new connect\", _status);\n pthread_mutex_lock(&_client_lock);\n if (_clients == 0 && _status == S_REJECT_CONN) {\n _status = S_STOP;\n LOG_INFO(\"client is empty and ready for stop server!\");\n }\n pthread_mutex_unlock(&_client_lock);\n }\n } else if (e.events & EPOLLIN) {\n \/\/ handle readable async\n LOG_DEBUG(\"start handle readable event\");\n TaskData *tdata = new TaskData();\n tdata->event = e;\n tdata->es = this;\n\n Task *task = new Task(read_func, tdata);\n int ret = _thread_pool->add_task(task);\n if (ret != 0) {\n LOG_WARN(\"add read task fail:%d, we will close connect.\", ret);\n close_and_release(e);\n delete tdata;\n delete task;\n }\n } else if (e.events & EPOLLOUT) {\n \/\/ writeable\n this->handle_writeable_event(_epollfd, e, *_watcher);\n } else {\n LOG_INFO(\"unkonw events :%d\", e.events);\n }\n return 0;\n}\n\nint EpollSocket::create_epoll() {\n \/\/ The \"size\" parameter is a hint specifying the number of file\n \/\/ descriptors to be associated with the new instance.\n _epollfd = epoll_create(1024);\n if (_epollfd == -1) {\n LOG_ERROR(\"epoll_create:%s\", strerror(errno));\n return -1;\n }\n return 0;\n}\n\nint EpollSocket::init_tp() {\n if (_thread_pool == NULL) {\n init_default_tp();\n }\n int ret = _thread_pool->start_threadpool();\n return ret;\n}\n\nint EpollSocket::start_event_loop() {\n epoll_event *events = new epoll_event[_max_events];\n while (_status != S_STOP) {\n int fds_num = epoll_wait(_epollfd, events, _max_events, -1);\n if (fds_num == -1) {\n if (errno == EINTR) { \/*The call was interrupted by a signal handler*\/\n continue;\n }\n LOG_ERROR(\"epoll_wait error:%s\", strerror(errno));\n break;\n }\n\n for (int i = 0; i < fds_num; i++) {\n this->handle_event(events[i]);\n }\n }\n LOG_INFO(\"epoll wait loop stop ...\");\n if (events != NULL) {\n delete[] events;\n events = NULL;\n }\n return 0;\n}\n\nint EpollSocket::start_epoll() {\n \/* Ignore broken pipe signal. *\/\n signal(SIGPIPE, SIG_IGN);\n\n int ret = init_tp();\n CHECK_RET(ret, \"thread pool start error:%d\", ret);\n\n ret = this->listen_on();\n CHECK_RET(ret, \"listen err:%d\", ret);\n\n ret = this->create_epoll();\n CHECK_RET(ret, \"create epoll err:%d\", ret);\n\n ret = this->add_listen_sock_to_epoll();\n CHECK_RET(ret , \"add listen sock to epoll fail:%d\", ret);\n\n return start_event_loop();\n}\n\nint EpollSocket::stop_epoll() {\n _status = S_REJECT_CONN;\n LOG_INFO(\"stop epoll , current clients:%u\", _clients);\n return 0;\n}\n\nint EpollSocket::close_and_release(epoll_event &epoll_event) {\n if (epoll_event.data.ptr == NULL) {\n return 0;\n }\n LOG_DEBUG(\"connect close\");\n\n EpollContext *hc = (EpollContext *) epoll_event.data.ptr;\n _watcher->on_close(*hc);\n\n int fd = hc->fd;\n epoll_event.events = EPOLLIN | EPOLLOUT;\n epoll_ctl(_epollfd, EPOLL_CTL_DEL, fd, &epoll_event);\n\n delete (EpollContext *) epoll_event.data.ptr;\n epoll_event.data.ptr = NULL;\n\n int ret = close(fd);\n\n pthread_mutex_lock(&_client_lock);\n _clients--;\n if (_clients == 0 && _status == S_REJECT_CONN) {\n _status = S_STOP;\n LOG_INFO(\"client is empty and ready for stop server!\");\n }\n pthread_mutex_unlock(&_client_lock);\n\n LOG_DEBUG(\"connect close complete which fd:%d, ret:%d\", fd, ret);\n return ret;\n}\n\nvoid EpollSocket::add_bind_ip(std::string ip) {\n _bind_ips.push_back(ip);\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/===--- SILMem2Reg.cpp - Promotes AllocStacks to registers ---------------===\/\/\n\/\/\n\/\/ This source file is part of the Swift.org open source project\n\/\/\n\/\/ Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors\n\/\/ Licensed under Apache License v2.0 with Runtime Library Exception\n\/\/\n\/\/ See http:\/\/swift.org\/LICENSE.txt for license information\n\/\/ See http:\/\/swift.org\/CONTRIBUTORS.txt for the list of Swift project authors\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#define DEBUG_TYPE \"sil-mem2reg\"\n#include \"swift\/SILPasses\/Passes.h\"\n#include \"swift\/AST\/DiagnosticEngine.h\"\n#include \"swift\/AST\/Diagnostics.h\"\n#include \"swift\/SIL\/SILCloner.h\"\n#include \"swift\/SIL\/SILFunction.h\"\n#include \"swift\/SIL\/SILInstruction.h\"\n#include \"swift\/SIL\/SILModule.h\"\n#include \"swift\/SILPasses\/Utils\/Local.h\"\n#include \"llvm\/ADT\/Statistic.h\"\n#include \"llvm\/ADT\/MapVector.h\"\n#include \"llvm\/ADT\/ImmutableSet.h\"\n#include \"llvm\/Support\/Debug.h\"\nusing namespace swift;\n\nSTATISTIC(NumAllocStackRemoved, \"Number of AllocStack promoted\");\nSTATISTIC(NumAllocStackFound, \"Number of AllocStack found\");\nSTATISTIC(NumAllocStackCaptured, \"Number of AllocStack captured\");\n\nnamespace {\n\n\/\/\/ Promote memory to registers\nclass MemoryToRegisters {\n \/\/\/ Holds all of the AllocStacks in the program.\n SmallVector<AllocStackInst*, 32> Allocations;\n\n \/\/\/ The function that we are optimizing.\n SILFunction &F;\n\npublic:\n \/\/\/ C'tor\n MemoryToRegisters(SILFunction &Func) : F(Func) {}\n\n \/\/\/ Promote memory to registers.\n void run();\n\nprivate:\n \/\/\/ Collect all of the AllocStacks in the program.\n void collectAllocStackInstructions();\n\n \/\/\/ Promote a single AllocStack instruction.\n void promoteAllocation(AllocStackInst *ASI);\n};\n\n} \/\/ end anonymous namespace.\n\n\/\/\/ Returns true if this AllocStacks is captured.\nstatic bool isCaptured(AllocStackInst *ASI) {\n \/\/ For all users of the AllocStack instruction.\n for (auto UI = ASI->use_begin(), E = ASI->use_end(); UI != E; ++UI) {\n SILInstruction *II = UI->getUser();\n\n \/\/ Loads are okay.\n if (isa<LoadInst>(II))\n continue;\n\n \/\/ We can store into an AllocStack (but not the pointer).\n if (StoreInst *SI = dyn_cast<StoreInst>(II))\n if (SI->getDest().getDef() == ASI)\n continue;\n\n \/\/ Deallocation is also okay.\n if (isa<DeallocStackInst>(II))\n continue;\n\n\n \/\/ Other instructions are assumed to capture the AllocStack.\n DEBUG(llvm::errs() << \"*** AllocStack is captured by: \" << *II << \"\\n\");\n return true;\n }\n\n \/\/ None of the users capture the AllocStack.\n return false;\n}\n\n\/\/\/ Returns true if the AllocStack is only stored into.\nstatic bool isWriteOnlyAllocation(AllocStackInst *ASI) {\n\n \/\/ For all users of the AllocStack:\n for (auto UI = ASI->use_begin(), E = ASI->use_end(); UI != E; ++UI) {\n SILInstruction *II = UI->getUser();\n\n \/\/ It is okay to store into this AllocStack.\n if (StoreInst *SI = dyn_cast<StoreInst>(II))\n if (!isa<AllocStackInst>(SI->getSrc()))\n continue;\n\n \/\/ It is also okay to deallocate.\n if (isa<DeallocStackInst>(II))\n continue;\n\n \/\/ Can't do anything else with it.\n DEBUG(llvm::errs() << \"*** AllocStack is loaded by: \" << *II << \"\\n\");\n return false;\n }\n\n return true;\n}\n\n\/\/\/ Returns true if this AllocStack is only used within a single basic block.\nstatic bool isSingleBlockUsage(AllocStackInst *ASI) {\n assert(!isCaptured(ASI) && \"This AllocStack must not be captured\");\n SILBasicBlock *BB = ASI->getParent();\n\n \/\/ All of the users of the AllocStack must be in the same block.\n for (auto UI = ASI->use_begin(), E = ASI->use_end(); UI != E; ++UI)\n if (UI->getUser()->getParent() != BB)\n return false;\n\n return true;\n}\n\nvoid MemoryToRegisters::collectAllocStackInstructions() {\n for (auto &BB : F)\n for (auto &II : BB)\n if (AllocStackInst *ASI = dyn_cast<AllocStackInst>(&II))\n Allocations.push_back(ASI);\n DEBUG(llvm::errs() << \"*** Found \" << Allocations.size() << \" AllocStacks\\n\");\n}\n\n\/\/\/ Promote all of the AllocStacks in a single basic block in one linear scan.\nstatic void promoteAllocationInBlock(AllocStackInst *ASI) {\n DEBUG(llvm::errs() << \"*** Promoting in-block: \" << *ASI << \"\\n\");\n\n SILBasicBlock *BB = ASI->getParent();\n\n \/\/ The default value of the AllocStack is NULL because we don't have\n \/\/ unilitialized variables in Swift.\n SILValue RunningVal = SILValue();\n\n \/\/ For all instructions in the block.\n for (auto BBI = BB->begin(), E = BB->end(); BBI != E;) {\n SILInstruction *Inst = BBI++;\n \/\/ Remove instructions that we are loading from. Replace the loaded value\n \/\/ with our running value.\n if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {\n if (LI->getOperand().getDef() == ASI) {\n assert(RunningVal.isValid() &&\n \"The AllocStack must be initialized before usage.\");\n SILValue(Inst, 0).replaceAllUsesWith(RunningVal);\n Inst->eraseFromParent();\n continue;\n }\n }\n\n \/\/ Remove stores and record the value that we are saving as the running\n \/\/ value.\n if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {\n if (SI->getDest().getDef() == ASI) {\n RunningVal = SI->getSrc();\n Inst->eraseFromParent();\n continue;\n }\n }\n\n \/\/ Remove deallocation.\n if (DeallocStackInst *DSI = dyn_cast<DeallocStackInst>(Inst)) {\n if (DSI->getOperand() == ASI)\n Inst->eraseFromParent();\n }\n }\n\n DEBUG(llvm::errs() << \"*** Deleting \" << *ASI << \"\\n\");\n ASI->eraseFromParent();\n NumAllocStackRemoved++;\n}\n\n\/\/\/ Delete the AllocStack and all of its users. This is used by write-only\n\/\/\/ AllocStacks.\nstatic void deleteAllocation(AllocStackInst *ASI) {\n DEBUG(llvm::errs() << \"*** Deleting \" << *ASI << \"\\n\");\n\n eraseUsesOfInstruction(ASI);\n ASI->eraseFromParent();\n\n NumAllocStackRemoved++;\n}\n\nvoid MemoryToRegisters::promoteAllocation(AllocStackInst *ASI) {\n DEBUG(llvm::errs() << \"*** Memory to register looking at: \" << *ASI << \"\\n\");\n NumAllocStackFound++;\n\n \/\/ Don't handle captured AllocStacks.\n if (isCaptured(ASI)) {\n NumAllocStackCaptured++;\n return;\n }\n\n \/\/ For AllocStacks that are only used within a single basic blocks, use the\n \/\/ linear sweep to remove the AllocStack.\n if (isSingleBlockUsage(ASI))\n return promoteAllocationInBlock(ASI);\n\n \/\/ Remove write-only AllocStacks.\n if (isWriteOnlyAllocation(ASI))\n return deleteAllocation(ASI);\n\n DEBUG(llvm::errs() << \"*** Need to insert PHIs for \" << *ASI << \"\\n\");\n \/\/ TODO: Replace AllocStacks with PHI-nodes ...\n}\n\nvoid MemoryToRegisters::run() {\n collectAllocStackInstructions();\n\n for (auto A : Allocations)\n promoteAllocation(A);\n}\n\nvoid promoteAllocasInFunction(SILFunction &F) {\n MemoryToRegisters(F).run();\n}\n\nvoid swift::performSILMem2Reg(SILModule *M) {\n for (auto &F : *M)\n promoteAllocasInFunction(F);\n\n}\n<commit_msg>Iterate over the AllocStack instructions in the function instead of collecting them before we optimize them.<commit_after>\/\/===--- SILMem2Reg.cpp - Promotes AllocStacks to registers ---------------===\/\/\n\/\/\n\/\/ This source file is part of the Swift.org open source project\n\/\/\n\/\/ Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors\n\/\/ Licensed under Apache License v2.0 with Runtime Library Exception\n\/\/\n\/\/ See http:\/\/swift.org\/LICENSE.txt for license information\n\/\/ See http:\/\/swift.org\/CONTRIBUTORS.txt for the list of Swift project authors\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#define DEBUG_TYPE \"sil-mem2reg\"\n#include \"swift\/SILPasses\/Passes.h\"\n#include \"swift\/AST\/DiagnosticEngine.h\"\n#include \"swift\/AST\/Diagnostics.h\"\n#include \"swift\/SIL\/SILCloner.h\"\n#include \"swift\/SIL\/SILFunction.h\"\n#include \"swift\/SIL\/SILInstruction.h\"\n#include \"swift\/SIL\/SILModule.h\"\n#include \"swift\/SILPasses\/Utils\/Local.h\"\n#include \"llvm\/ADT\/Statistic.h\"\n#include \"llvm\/ADT\/MapVector.h\"\n#include \"llvm\/ADT\/ImmutableSet.h\"\n#include \"llvm\/Support\/Debug.h\"\nusing namespace swift;\n\nSTATISTIC(NumAllocStackRemoved, \"Number of AllocStack promoted\");\nSTATISTIC(NumAllocStackFound, \"Number of AllocStack found\");\nSTATISTIC(NumAllocStackCaptured, \"Number of AllocStack captured\");\n\nnamespace {\n\n\/\/\/ Promote memory to registers\nclass MemoryToRegisters {\n \/\/\/ The function that we are optimizing.\n SILFunction &F;\n\npublic:\n \/\/\/ C'tor\n MemoryToRegisters(SILFunction &Func) : F(Func) {}\n\n \/\/\/ Promote memory to registers.\n void run();\n};\n\n} \/\/ end anonymous namespace.\n\n\/\/\/ Returns true if this AllocStacks is captured.\nstatic bool isCaptured(AllocStackInst *ASI) {\n \/\/ For all users of the AllocStack instruction.\n for (auto UI = ASI->use_begin(), E = ASI->use_end(); UI != E; ++UI) {\n SILInstruction *II = UI->getUser();\n\n \/\/ Loads are okay.\n if (isa<LoadInst>(II))\n continue;\n\n \/\/ We can store into an AllocStack (but not the pointer).\n if (StoreInst *SI = dyn_cast<StoreInst>(II))\n if (SI->getDest().getDef() == ASI)\n continue;\n\n \/\/ Deallocation is also okay.\n if (isa<DeallocStackInst>(II))\n continue;\n\n\n \/\/ Other instructions are assumed to capture the AllocStack.\n DEBUG(llvm::errs() << \"*** AllocStack is captured by: \" << *II << \"\\n\");\n return true;\n }\n\n \/\/ None of the users capture the AllocStack.\n return false;\n}\n\n\/\/\/ Returns true if the AllocStack is only stored into.\nstatic bool isWriteOnlyAllocation(AllocStackInst *ASI) {\n \/\/ For all users of the AllocStack:\n for (auto UI = ASI->use_begin(), E = ASI->use_end(); UI != E; ++UI) {\n SILInstruction *II = UI->getUser();\n\n \/\/ It is okay to store into this AllocStack.\n if (StoreInst *SI = dyn_cast<StoreInst>(II))\n if (!isa<AllocStackInst>(SI->getSrc()))\n continue;\n\n \/\/ It is also okay to deallocate.\n if (isa<DeallocStackInst>(II))\n continue;\n\n \/\/ Can't do anything else with it.\n DEBUG(llvm::errs() << \"*** AllocStack is loaded by: \" << *II << \"\\n\");\n return false;\n }\n\n return true;\n}\n\n\/\/\/ Returns true if this AllocStack is only used within a single basic block.\nstatic bool isSingleBlockUsage(AllocStackInst *ASI) {\n assert(!isCaptured(ASI) && \"This AllocStack must not be captured\");\n SILBasicBlock *BB = ASI->getParent();\n\n \/\/ All of the users of the AllocStack must be in the same block.\n for (auto UI = ASI->use_begin(), E = ASI->use_end(); UI != E; ++UI)\n if (UI->getUser()->getParent() != BB)\n return false;\n\n return true;\n}\n\n\/\/\/ Promote all of the AllocStacks in a single basic block in one linear scan.\n\/\/\/ Note: This function deletes all of the users of the AllocStackInst,\n\/\/\/ including the DeallocStackInst. However, it does not remove the\n\/\/ AllocStackInst itself!\nstatic void promoteAllocationInBlock(AllocStackInst *ASI) {\n DEBUG(llvm::errs() << \"*** Promoting in-block: \" << *ASI << \"\\n\");\n\n SILBasicBlock *BB = ASI->getParent();\n\n \/\/ The default value of the AllocStack is NULL because we don't have\n \/\/ unilitialized variables in Swift.\n SILValue RunningVal = SILValue();\n\n \/\/ For all instructions in the block.\n for (auto BBI = BB->begin(), E = BB->end(); BBI != E;) {\n SILInstruction *Inst = BBI++;\n \/\/ Remove instructions that we are loading from. Replace the loaded value\n \/\/ with our running value.\n if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {\n if (LI->getOperand().getDef() == ASI) {\n assert(RunningVal.isValid() &&\n \"The AllocStack must be initialized before usage.\");\n SILValue(Inst, 0).replaceAllUsesWith(RunningVal);\n Inst->eraseFromParent();\n continue;\n }\n }\n\n \/\/ Remove stores and record the value that we are saving as the running\n \/\/ value.\n if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {\n if (SI->getDest().getDef() == ASI) {\n RunningVal = SI->getSrc();\n Inst->eraseFromParent();\n continue;\n }\n }\n\n \/\/ Remove deallocation.\n if (DeallocStackInst *DSI = dyn_cast<DeallocStackInst>(Inst)) {\n if (DSI->getOperand() == ASI)\n Inst->eraseFromParent();\n }\n }\n}\n\nvoid MemoryToRegisters::run() {\n for (auto &BB : F) {\n auto I = BB.begin(), E = BB.end();\n while (I != E) {\n SILInstruction *Inst = I;\n AllocStackInst *ASI = dyn_cast<AllocStackInst>(Inst);\n if (!ASI) {\n ++I;\n continue;\n }\n\n DEBUG(llvm::errs()<< \"*** Memory to register looking at: \" << *I << \"\\n\");\n NumAllocStackFound++;\n\n \/\/ Don't handle captured AllocStacks.\n if (isCaptured(ASI)) {\n NumAllocStackCaptured++;\n ++I;\n continue;\n }\n\n \/\/ For AllocStacks that are only used within a single basic blocks, use\n \/\/ the linear sweep to remove the AllocStack.\n if (isSingleBlockUsage(ASI)) {\n promoteAllocationInBlock(ASI);\n\n DEBUG(llvm::errs() << \"*** Deleting single block AllocStackInst: \" <<\n *ASI << \"\\n\");\n I++;\n ASI->eraseFromParent();\n NumAllocStackRemoved++;\n continue;\n }\n\n \/\/ Remove write-only AllocStacks.\n if (isWriteOnlyAllocation(ASI)) {\n eraseUsesOfInstruction(ASI);\n\n DEBUG(llvm::errs() << \"*** Deleting store-only AllocStackInst: \" <<\n *ASI << \"\\n\");\n I++;\n ASI->eraseFromParent();\n NumAllocStackRemoved++;\n continue;\n }\n\n DEBUG(llvm::errs() << \"*** Need to insert PHIs for \" << *ASI << \"\\n\");\n \/\/ TODO: Replace AllocStacks with PHI-nodes ...\n\n \/\/ Move iterator to avoid invalidation.\n ++I;\n }\n }\n}\n\nvoid promoteAllocasInFunction(SILFunction &F) {\n MemoryToRegisters(F).run();\n}\n\nvoid swift::performSILMem2Reg(SILModule *M) {\n for (auto &F : *M)\n promoteAllocasInFunction(F);\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ This software is part of OpenMono, see http:\/\/developer.openmono.com\n\/\/ and is available under the MIT license, see LICENSE.txt\n\n#include \"application_context.h\"\n#include \"application_controller_interface.h\"\n#include <display_painter.h>\n#include \"consoles.h\"\n#include <mbed_interface.h>\n\nextern \"C\" {\n#include <project.h>\n}\n\n\nusing namespace mono;\n\nApplicationContext ApplicationContext::singleton;\nIApplicationContext *IApplicationContext::Instance = NULL; \/\/&(ApplicationContext::singleton);\n\nApplicationContext::ApplicationContext() : IApplicationContext(\n &pwrMgmt,\n &runLoop,\n &dispController,\n &touchSys,\n &UserButton,\n &at30ts64Sensor,\n &mmaAccelerometer),\n\n dispController(),\n UserButton(SW_USER, PullUp)\n{\n \/\/enable SWD \/ JTAG debug, by turning on VTARG\/VSYS voltage in expansion connector\n\/\/ CyPins_SetPinDriveMode(EXPANSION_PWR_ENABLE, CY_PINS_DM_STRONG);\n\/\/ CyPins_SetPin(EXPANSION_PWR_ENABLE);\n \n \/\/ BEEP\n PWM_Start();\n PWM_WriteCompare2(0);\n PWM_WriteCompare1(0);\n \n for (int i=10; i<100; i+=12) {\n PWM_WriteCompare2(i);\n CyDelay(30);\n }\n PWM_WriteCompare2(0);\n \n defaultSerial.printf(\"\");\n\n}\n\nint ApplicationContext::exec()\n{\n runLoop.exec();\n \n return 0;\n}\n\nvoid ApplicationContext::setMonoApplication(mono::IApplication *monoApp)\n{\n this->application = monoApp;\n \n CyIntSetSysVector(CY_INT_NMI_IRQN, &mbed_die);\n CyIntSetSysVector(CY_INT_HARD_FAULT_IRQN, &mbed_die);\n CyIntSetSysVector(CY_INT_MEM_MANAGE_IRQN, &mbed_die);\n CyIntSetSysVector(CY_INT_BUS_FAULT_IRQN, &mbed_die);\n CyIntSetSysVector(CY_INT_USAGE_FAULT_IRQN, &mbed_die);\n \n \/\/PowerSystem->onSystemPowerOnReset();\n pwrMgmt.processResetAwarenessQueue();\n \n \/\/defaultSerial.printf(\"Display init deactivated\\n\\t\");\n mono::IApplicationContext::Instance->DisplayController->init();\n \n touchSys.init();\n \n \/\/setup default user button handler\n UserButton.DeactivateUntilHandled(); \/\/ dont queue up pushes\n UserButton.setDebouncing(true);\n UserButton.fall<ApplicationContext>(this, &ApplicationContext::enterSleepMode);\n \n monoApp->monoWakeFromReset();\n \n}\n\nvoid ApplicationContext::sleepForMs(uint32_t ms)\n{\n uint8_t ticks = 1;\n while ((1u << ticks) < ms) {\n ticks++;\n }\n \n defaultSerial.printf(\"Setting CTW to: %i for ms: %i\\n\\r\",ticks, ms);\n *((reg8*)CYREG_PM_TW_CFG1) = 0x0F & ticks;\n PM_TW_CFG2 = PM_TW_CFG2 | 0x0C; \/\/ CTW enable and CTW interrupts\n defaultSerial.printf(\"CTW CFG Reg: 0x%x\\n\\r\",PM_TW_CFG2);\n enterSleepMode();\n}\n\nvoid ApplicationContext::enterSleepMode()\n{\n this->application->monoWillGotoSleep();\n \n PowerManager->EnterSleep();\n \n this->application->monoWakeFromSleep();\n \n}\n\nvoid ApplicationContext::_softwareReset()\n{\n Bootloadable_SET_RUN_TYPE(0); \/\/ force bootloader to run for 2 secs\n CySoftwareReset();\n while(1); \/\/ silence compiler warning\n}\n\nvoid ApplicationContext::_softwareResetToBootloader()\n{\n Bootloadable_SET_RUN_TYPE(Bootloadable_START_BTLDR);\n CySoftwareReset();\n while(1); \/\/ silence compiler warning\n}\n\nvoid ApplicationContext::_softwareResetToApplication()\n{\n Bootloadable_SET_RUN_TYPE(Bootloadable_START_APP);\n CySoftwareReset();\n while(1); \/\/ silence compiler warning\n}\n\nvoid ApplicationContext::resetOnUserButton()\n{\n debug(\"Mono will reset on user button!\\n\\r\");\n this->runLoop.setResetOnUserButton(true);\n}\n\n<commit_msg>Enabled external power lines<commit_after>\/\/ This software is part of OpenMono, see http:\/\/developer.openmono.com\n\/\/ and is available under the MIT license, see LICENSE.txt\n\n#include \"application_context.h\"\n#include \"application_controller_interface.h\"\n#include <display_painter.h>\n#include \"consoles.h\"\n#include <mbed_interface.h>\n\nextern \"C\" {\n#include <project.h>\n}\n\n\nusing namespace mono;\n\nApplicationContext ApplicationContext::singleton;\nIApplicationContext *IApplicationContext::Instance = NULL; \/\/&(ApplicationContext::singleton);\n\nApplicationContext::ApplicationContext() : IApplicationContext(\n &pwrMgmt,\n &runLoop,\n &dispController,\n &touchSys,\n &UserButton,\n &at30ts64Sensor,\n &mmaAccelerometer),\n\n dispController(),\n UserButton(SW_USER, PullUp)\n{\n \/\/enable SWD \/ JTAG debug, by turning on VTARG\/VSYS voltage in expansion connector\n \/\/ and set the pwr rail to 3.3V\n CyPins_SetPinDriveMode(EXPANSION_3V3_ENABLE, CY_PINS_DM_STRONG);\n CyPins_SetPin(EXPANSION_3V3_ENABLE);\n CyPins_SetPinDriveMode(EXPANSION_PWR_ENABLE, CY_PINS_DM_STRONG);\n CyPins_SetPin(EXPANSION_PWR_ENABLE);\n\n\n \/\/ BEEP\n PWM_Start();\n PWM_WriteCompare2(0);\n PWM_WriteCompare1(0);\n \n for (int i=10; i<100; i+=12) {\n PWM_WriteCompare2(i);\n CyDelay(30);\n }\n PWM_WriteCompare2(0);\n \n defaultSerial.printf(\"\");\n\n}\n\nint ApplicationContext::exec()\n{\n runLoop.exec();\n \n return 0;\n}\n\nvoid ApplicationContext::setMonoApplication(mono::IApplication *monoApp)\n{\n this->application = monoApp;\n \n CyIntSetSysVector(CY_INT_NMI_IRQN, &mbed_die);\n CyIntSetSysVector(CY_INT_HARD_FAULT_IRQN, &mbed_die);\n CyIntSetSysVector(CY_INT_MEM_MANAGE_IRQN, &mbed_die);\n CyIntSetSysVector(CY_INT_BUS_FAULT_IRQN, &mbed_die);\n CyIntSetSysVector(CY_INT_USAGE_FAULT_IRQN, &mbed_die);\n \n \/\/PowerSystem->onSystemPowerOnReset();\n pwrMgmt.processResetAwarenessQueue();\n \n \/\/defaultSerial.printf(\"Display init deactivated\\n\\t\");\n mono::IApplicationContext::Instance->DisplayController->init();\n \n touchSys.init();\n \n \/\/setup default user button handler\n UserButton.DeactivateUntilHandled(); \/\/ dont queue up pushes\n UserButton.setDebouncing(true);\n UserButton.fall<ApplicationContext>(this, &ApplicationContext::enterSleepMode);\n \n monoApp->monoWakeFromReset();\n \n}\n\nvoid ApplicationContext::sleepForMs(uint32_t ms)\n{\n uint8_t ticks = 1;\n while ((1u << ticks) < ms) {\n ticks++;\n }\n \n defaultSerial.printf(\"Setting CTW to: %i for ms: %i\\n\\r\",ticks, ms);\n *((reg8*)CYREG_PM_TW_CFG1) = 0x0F & ticks;\n PM_TW_CFG2 = PM_TW_CFG2 | 0x0C; \/\/ CTW enable and CTW interrupts\n defaultSerial.printf(\"CTW CFG Reg: 0x%x\\n\\r\",PM_TW_CFG2);\n enterSleepMode();\n}\n\nvoid ApplicationContext::enterSleepMode()\n{\n this->application->monoWillGotoSleep();\n \n PowerManager->EnterSleep();\n \n this->application->monoWakeFromSleep();\n \n}\n\nvoid ApplicationContext::_softwareReset()\n{\n Bootloadable_SET_RUN_TYPE(0); \/\/ force bootloader to run for 2 secs\n CySoftwareReset();\n while(1); \/\/ silence compiler warning\n}\n\nvoid ApplicationContext::_softwareResetToBootloader()\n{\n Bootloadable_SET_RUN_TYPE(Bootloadable_START_BTLDR);\n CySoftwareReset();\n while(1); \/\/ silence compiler warning\n}\n\nvoid ApplicationContext::_softwareResetToApplication()\n{\n Bootloadable_SET_RUN_TYPE(Bootloadable_START_APP);\n CySoftwareReset();\n while(1); \/\/ silence compiler warning\n}\n\nvoid ApplicationContext::resetOnUserButton()\n{\n debug(\"Mono will reset on user button!\\n\\r\");\n this->runLoop.setResetOnUserButton(true);\n}\n\n<|endoftext|>"} {"text":"<commit_before>#include <CodeAdapter\\EasyCA.h>\n#include <CodeAdapterSFML\\SFMLFactory.h>\n\n\n\n\nint main()\n{\n\tinitializeCA<SFMLFactory>();\n\n\n\ti32 button1ClickCount = 0;\n\n\n\tauto window1 = caFactory->createWindow();\n\twindow1->create(caDraw::Size(1024, 768), caUtil::String(\"Hello, World!\"));\n\n\n\tauto rect = canew<caDraw::DrawableRectangle>(-32, -64, 256, 128);\n\trect->edgeColor = caDraw::Color::Magenta;\n\trect->fillColor = caDraw::Color::Yellow;\n\trect->edgeWidth = 8.0f;\n\n\n\tauto ellipse = canew<caDraw::DrawableEllipse>(-32, -64, 256, 128);\n\tellipse->edgeColor = caDraw::Color::Yellow;\n\tellipse->fillColor = caDraw::Color::Magenta;\n\tellipse->edgeWidth = 2.0f;\n\n\n\tauto ellipse2 = canew<caDraw::DrawableEllipse>(-40, -70, 2, 2);\n\tellipse2->edgeColor = caDraw::Color::Red;\n\tellipse2->fillColor = caDraw::Color::Red;\n\tellipse2->edgeWidth = 1.0f;\n\n\n\tauto line1 = canew<caDraw::DrawableLine>(rect->x, rect->y,\n\t\trect->x + rect->width, rect->y + rect->height);\n\tline1->color = caDraw::Color::Cyan;\n\tline1->thickness = 8.0f;\n\n\n\tauto font1 = caFactory->createFont();\n\tfont1->loadFromFile(\"NanumGothic.ttf\");\n\tfont1->setCharacterSize(64);\n\tfont1->setStyle(caDraw::FontStyles::Underline | caDraw::FontStyles::Bold);\n\n\n\tauto text1 = canew<caDraw::DrawableText>();\n\ttext1->setFont(font1);\n\ttext1->text = L\"Hello, World!\\nȳ !\";\n\ttext1->location.setLocation(64, 8);\n\ttext1->color = caDraw::Color(34, 177, 76);\n\n\n\tauto texture1 = caFactory->createTexture();\n\ttexture1->loadFromFile(\"neurowhai.png\");\n\n\n\tauto sprite1 = canew<caDraw::DrawableTexture>();\n\tsprite1->setTexture(texture1);\n\tsprite1->location.setLocation(-512.f, -512.f);\n\tsprite1->color = caDraw::Color(caDraw::Color::Red, 85);\n\tsprite1->transform.scale.setVector(0.5f, 0.5f);\n\n\tauto sprite2 = canew<caDraw::DrawableTexture>();\n\tsprite2->setTexture(texture1);\n\tsprite2->location.setLocation(-512.f + 16.f, -512.f);\n\tsprite2->color = caDraw::Color(caDraw::Color::Green, 85);\n\tsprite2->transform.scale.setVector(0.5f, 0.5f);\n\n\tauto sprite3 = canew<caDraw::DrawableTexture>();\n\tsprite3->setTexture(texture1);\n\tsprite3->location.setLocation(-512.f + 8.f, -512.f + 13.85f);\n\tsprite3->color = caDraw::Color(caDraw::Color::Blue, 85);\n\tsprite3->transform.scale.setVector(0.5f, 0.5f);\n\n\tauto sprite4 = canew<caDraw::DrawableTexture>();\n\tsprite4->setTexture(texture1);\n\tsprite4->location.setLocation(-512.f, -512.f);\n\n\n\tauto label1 = canew<caUI::Label>();\n\tlabel1->setFont(font1);\n\tlabel1->setText(L\"label1 text\");\n\tlabel1->setTextMargin({ 8, 0 });\n\tlabel1->setBackColor(caDraw::Color::Gray);\n\tlabel1->setPosition({ 128, 128 });\n\tlabel1->setSize({ 330, 100 });\n\tlabel1->setSelectable(true);\n\tlabel1->WhenTouchDown = [&label1](const caUI::TouchEventArgs& args) {\n\t\tlabel1->setTextColor(caDraw::Color::Red);\n\t\tlabel1->setPosition({ static_cast<f32>(args.x) - 165,\n\t\t\tstatic_cast<f32>(args.y) - 50 });\n\t};\n\tlabel1->WhenTouchUp = [&label1](const caUI::TouchEventArgs& args) {\n\t\tlabel1->setTextColor(caDraw::Color::Black);\n\t};\n\tlabel1->WhenEnterFocus = [&label1](const caUI::EventArgs& args) {\n\t\tlabel1->setTextColor(caDraw::Color::Blue);\n\t};\n\tlabel1->WhenLeaveFocus = [&label1](const caUI::EventArgs& args) {\n\t\tlabel1->setTextColor(caDraw::Color::Black);\n\t};\n\tlabel1->WhenSelected = [&label1](const caUI::EventArgs& args) {\n\t\tlabel1->setBackColor(caDraw::Color::White);\n\t};\n\tlabel1->WhenDeselected = [&label1](const caUI::EventArgs& args) {\n\t\tlabel1->setBackColor(caDraw::Color::Gray);\n\t};\n\tlabel1->WhenKeyDown = [&label1](const caUI::KeyEventArgs& args) {\n\t\tswitch (args.key)\n\t\t{\n\t\tcase caSys::Keys::Space:\n\t\t\tlabel1->setPosition({ 128, 128 });\n\t\t\tbreak;\n\t\t}\n\t};\n\n\tauto label2 = canew<caUI::Label>(*label1);\n\tlabel2->WhenTouchDown = [&label2](const caUI::TouchEventArgs& args) {\n\t\tlabel2->setTextColor(caDraw::Color::Red);\n\t\tlabel2->setPosition({ static_cast<f32>(args.x) - 165,\n\t\t\tstatic_cast<f32>(args.y) - 50 });\n\t};\n\tlabel2->WhenTouchUp = [&label2](const caUI::TouchEventArgs& args) {\n\t\tlabel2->setTextColor(caDraw::Color::Black);\n\t};\n\tlabel2->WhenEnterFocus = [&label2](const caUI::EventArgs& args) {\n\t\tlabel2->setTextColor(caDraw::Color::Blue);\n\t};\n\tlabel2->WhenLeaveFocus = [&label2](const caUI::EventArgs& args) {\n\t\tlabel2->setTextColor(caDraw::Color::Black);\n\t};\n\tlabel2->WhenSelected = [&label2](const caUI::EventArgs& args) {\n\t\tlabel2->setBackColor(caDraw::Color::White);\n\t};\n\tlabel2->WhenDeselected = [&label2](const caUI::EventArgs& args) {\n\t\tlabel2->setBackColor(caDraw::Color::Gray);\n\t};\n\tlabel2->WhenKeyDown = [&label2](const caUI::KeyEventArgs& args) {\n\t\tswitch (args.key)\n\t\t{\n\t\tcase caSys::Keys::Space:\n\t\t\tlabel2->setPosition({ 128, 128 });\n\t\t\tbreak;\n\t\t}\n\t};\n\n\n\tauto button1 = canew<caUI::Button>();\n\tbutton1->setFont(font1);\n\tbutton1->setText(L\"button1\");\n\tbutton1->setBackColor(caDraw::Color::Gray);\n\tbutton1->setPosition({ 128, 300 });\n\tbutton1->setSize({ 330, 100 });\n\tbutton1->WhenClick = [&button1ClickCount, &label1](const caUI::EventArgs& args)\n\t{\n\t\t++button1ClickCount;\n\n\t\tlabel1->setText(std::to_string(button1ClickCount));\n\t};\n\n\n\tauto verticalScrollBar1 = canew<caUI::VerticalScrollBar>();\n\tverticalScrollBar1->transform.position = { 750, 32 };\n\tverticalScrollBar1->setSize({24, 256});\n\tverticalScrollBar1->setMaxValue(1024);\n\tverticalScrollBar1->WhenValueChanged = [&verticalScrollBar1, &label2](const caUI::EventArgs& args)\n\t{\n\t\tlabel2->setText(std::to_string(verticalScrollBar1->getValue()));\n\t};\n\n\n\tauto verticalScrollBar2 = canew<caUI::VerticalScrollBar>();\n\tverticalScrollBar2->transform.position = { 700, 32 };\n\tverticalScrollBar2->setSize({ 24, 256 });\n\tverticalScrollBar2->setMaxValue(1024);\n\tverticalScrollBar2->setMinBarLength(32);\n\tverticalScrollBar2->WhenValueChanged = [&verticalScrollBar2, &verticalScrollBar1](const caUI::EventArgs& args)\n\t{\n\t\tverticalScrollBar1->setMaxValue(verticalScrollBar2->getValue());\n\t};\n\n\n\tauto panel = caFactory->createPanel();\n\tpanel->transform.position = { 64, 64 };\n\tpanel->size = { 800, 600 };\n\n\tpanel->addDrawable(sprite4);\n\tpanel->addDrawable(sprite1);\n\tpanel->addDrawable(sprite2);\n\tpanel->addDrawable(sprite3);\n\tpanel->addDrawable(rect);\n\tpanel->addDrawable(ellipse);\n\tpanel->addDrawable(ellipse2);\n\tpanel->addDrawable(line1);\n\tpanel->addDrawable(text1);\n\tpanel->addDrawable(label1);\n\tpanel->addUpdatable(label1);\n\tpanel->addDrawable(button1);\n\tpanel->addUpdatable(button1);\n\tpanel->addDrawable(verticalScrollBar1);\n\tpanel->addUpdatable(verticalScrollBar1);\n\tpanel->addDrawable(verticalScrollBar2);\n\tpanel->addUpdatable(verticalScrollBar2);\n\n\twindow1->addPanel(panel);\n\n\n\tauto panel2 = caFactory->createPanel();\n\tpanel2->transform.position = { 512, 400 };\n\tpanel2->size = { 400, 300 };\n\n\tpanel2->addDrawable(sprite4);\n\tpanel2->addDrawable(sprite1);\n\tpanel2->addDrawable(sprite2);\n\tpanel2->addDrawable(sprite3);\n\tpanel2->addDrawable(rect);\n\tpanel2->addDrawable(ellipse);\n\tpanel2->addDrawable(line1);\n\tpanel2->addDrawable(text1);\n\tpanel2->addDrawable(label2);\n\tpanel2->addUpdatable(label2);\n\n\twindow1->addPanel(panel2);\n\n\n\tf32 myScale = 1.0f;\n\tf32 scaleDir = 1.0f;\n\n\n\twhile (window1->isRunning())\n\t{\n\t\tcaTouch->update();\n\n\n\t\tcaKeyboard->update();\n\n\t\tif (caKeyboard->isKeyPressed(caSys::Keys::W))\n\t\t{\n\t\t\tellipse2->y -= 0.4f;\n\t\t}\n\t\telse if (caKeyboard->isKeyPressed(caSys::Keys::S))\n\t\t{\n\t\t\tellipse2->y += 0.4f;\n\t\t}\n\n\t\tif (caKeyboard->isKeyPressed(caSys::Keys::A))\n\t\t{\n\t\t\tellipse2->x -= 0.4f;\n\t\t}\n\t\telse if (caKeyboard->isKeyPressed(caSys::Keys::D))\n\t\t{\n\t\t\tellipse2->x += 0.4f;\n\t\t}\n\n\n\t\tmyScale -= scaleDir * myScale \/ 64.0f;\n\t\tif (scaleDir > 0.0f && myScale < 0.1f)\n\t\t{\n\t\t\tscaleDir = -1.0f;\n\t\t}\n\t\telse if (scaleDir < 0.0f && myScale > 2.0f)\n\t\t{\n\t\t\tscaleDir = 1.0f;\n\t\t}\n\n\t\tsprite1->transform.scale.setVector(myScale, myScale);\n\t\tsprite2->transform.scale.setVector(myScale, myScale);\n\t\tsprite3->transform.scale.setVector(myScale, myScale);\n\n\t\tpanel2->transform.angle += 0.02f;\n\n\n\t\trect->setVisible(ellipse->containsPoint(ellipse2->x, ellipse2->y));\n\n\n\t\tauto invPoint = panel2->transform.inverseTransformPoint(caTouch->getPositionF(*window1));\n\t\tellipse2->setLocation(invPoint.x, invPoint.y);\n\n\n\t\tif (label1->isFocused())\n\t\t{\n\t\t\tlabel1->setPosition(label1->getPosition() + caDraw::PointF(0.4f, 0.0f));\n\t\t}\n\n\t\tif (label2->isFocused())\n\t\t{\n\t\t\tlabel2->setPosition(label2->getPosition() + caDraw::PointF(0.4f, 0.0f));\n\t\t}\n\n\n\t\twindow1->update();\n\t\twindow1->draw(caDraw::Color(230, 230, 230));\n\t}\n\n\n\treturn 0;\n}\n\n<commit_msg>Fix sample code.<commit_after>#include <CodeAdapter\\EasyCA.h>\n#include <CodeAdapterSFML\\SFMLFactory.h>\n\n\n\n\nint main()\n{\n\tinitializeCA<SFMLFactory>();\n\n\n\ti32 button1ClickCount = 0;\n\n\n\tauto window1 = caFactory->createWindow();\n\twindow1->create(caDraw::Size(1024, 768), caUtil::String(\"Hello, World!\"));\n\n\n\tauto rect = canew<caDraw::DrawableRectangle>(-32, -64, 256, 128);\n\trect->edgeColor = caDraw::Color::Magenta;\n\trect->fillColor = caDraw::Color::Yellow;\n\trect->edgeWidth = 8.0f;\n\n\n\tauto ellipse = canew<caDraw::DrawableEllipse>(-32, -64, 256, 128);\n\tellipse->edgeColor = caDraw::Color::Yellow;\n\tellipse->fillColor = caDraw::Color::Magenta;\n\tellipse->edgeWidth = 2.0f;\n\n\n\tauto ellipse2 = canew<caDraw::DrawableEllipse>(-40, -70, 2, 2);\n\tellipse2->edgeColor = caDraw::Color::Red;\n\tellipse2->fillColor = caDraw::Color::Red;\n\tellipse2->edgeWidth = 1.0f;\n\n\n\tauto line1 = canew<caDraw::DrawableLine>(rect->x, rect->y,\n\t\trect->x + rect->width, rect->y + rect->height);\n\tline1->color = caDraw::Color::Cyan;\n\tline1->thickness = 8.0f;\n\n\n\tauto font1 = caFactory->createFont();\n\tfont1->loadFromFile(\"NanumGothic.ttf\");\n\tfont1->setCharacterSize(64);\n\tfont1->setStyle(caDraw::FontStyles::Underline | caDraw::FontStyles::Bold);\n\n\n\tauto text1 = canew<caDraw::DrawableText>();\n\ttext1->setFont(font1);\n\ttext1->text = L\"Hello, World!\\nȳ !\";\n\ttext1->location.setLocation(64, 8);\n\ttext1->color = caDraw::Color(34, 177, 76);\n\n\n\tauto texture1 = caFactory->createTexture();\n\ttexture1->loadFromFile(\"neurowhai.png\");\n\n\n\tauto sprite1 = canew<caDraw::DrawableTexture>();\n\tsprite1->setTexture(texture1);\n\tsprite1->location.setLocation(-512.f, -512.f);\n\tsprite1->color = caDraw::Color(caDraw::Color::Red, 85);\n\tsprite1->transform.scale.setVector(0.5f, 0.5f);\n\n\tauto sprite2 = canew<caDraw::DrawableTexture>();\n\tsprite2->setTexture(texture1);\n\tsprite2->location.setLocation(-512.f + 16.f, -512.f);\n\tsprite2->color = caDraw::Color(caDraw::Color::Green, 85);\n\tsprite2->transform.scale.setVector(0.5f, 0.5f);\n\n\tauto sprite3 = canew<caDraw::DrawableTexture>();\n\tsprite3->setTexture(texture1);\n\tsprite3->location.setLocation(-512.f + 8.f, -512.f + 13.85f);\n\tsprite3->color = caDraw::Color(caDraw::Color::Blue, 85);\n\tsprite3->transform.scale.setVector(0.5f, 0.5f);\n\n\tauto sprite4 = canew<caDraw::DrawableTexture>();\n\tsprite4->setTexture(texture1);\n\tsprite4->location.setLocation(-512.f, -512.f);\n\n\n\tauto label1 = canew<caUI::Label>();\n\tlabel1->setFont(font1);\n\tlabel1->setText(L\"label1 text\");\n\tlabel1->setTextMargin({ 8, 0 });\n\tlabel1->setBackColor(caDraw::Color::Gray);\n\tlabel1->setPosition({ 128, 128 });\n\tlabel1->setSize({ 330, 100 });\n\tlabel1->setSelectable(true);\n\tlabel1->WhenTouchDown = [&label1](const caUI::TouchEventArgs& args) {\n\t\tlabel1->setTextColor(caDraw::Color::Red);\n\t\tlabel1->setPosition({ static_cast<f32>(args.x) - 165,\n\t\t\tstatic_cast<f32>(args.y) - 50 });\n\t};\n\tlabel1->WhenTouchUp = [&label1](const caUI::TouchEventArgs& args) {\n\t\tlabel1->setTextColor(caDraw::Color::Black);\n\t};\n\tlabel1->WhenEnterFocus = [&label1](const caUI::EventArgs& args) {\n\t\tlabel1->setTextColor(caDraw::Color::Blue);\n\t};\n\tlabel1->WhenLeaveFocus = [&label1](const caUI::EventArgs& args) {\n\t\tlabel1->setTextColor(caDraw::Color::Black);\n\t};\n\tlabel1->WhenSelected = [&label1](const caUI::EventArgs& args) {\n\t\tlabel1->setBackColor(caDraw::Color::White);\n\t};\n\tlabel1->WhenDeselected = [&label1](const caUI::EventArgs& args) {\n\t\tlabel1->setBackColor(caDraw::Color::Gray);\n\t};\n\tlabel1->WhenKeyDown = [&label1](const caUI::KeyEventArgs& args) {\n\t\tswitch (args.key)\n\t\t{\n\t\tcase caSys::Keys::Space:\n\t\t\tlabel1->setPosition({ 128, 128 });\n\t\t\tbreak;\n\t\t}\n\t};\n\n\tauto label2 = canew<caUI::Label>(*label1);\n\tlabel2->WhenTouchDown = [&label2](const caUI::TouchEventArgs& args) {\n\t\tlabel2->setTextColor(caDraw::Color::Red);\n\t\tlabel2->setPosition({ static_cast<f32>(args.x) - 165,\n\t\t\tstatic_cast<f32>(args.y) - 50 });\n\t};\n\tlabel2->WhenTouchUp = [&label2](const caUI::TouchEventArgs& args) {\n\t\tlabel2->setTextColor(caDraw::Color::Black);\n\t};\n\tlabel2->WhenEnterFocus = [&label2](const caUI::EventArgs& args) {\n\t\tlabel2->setTextColor(caDraw::Color::Blue);\n\t};\n\tlabel2->WhenLeaveFocus = [&label2](const caUI::EventArgs& args) {\n\t\tlabel2->setTextColor(caDraw::Color::Black);\n\t};\n\tlabel2->WhenSelected = [&label2](const caUI::EventArgs& args) {\n\t\tlabel2->setBackColor(caDraw::Color::White);\n\t};\n\tlabel2->WhenDeselected = [&label2](const caUI::EventArgs& args) {\n\t\tlabel2->setBackColor(caDraw::Color::Gray);\n\t};\n\tlabel2->WhenKeyDown = [&label2](const caUI::KeyEventArgs& args) {\n\t\tswitch (args.key)\n\t\t{\n\t\tcase caSys::Keys::Space:\n\t\t\tlabel2->setPosition({ 128, 128 });\n\t\t\tbreak;\n\t\t}\n\t};\n\n\n\tauto button1 = canew<caUI::Button>();\n\tbutton1->setFont(font1);\n\tbutton1->setText(L\"button1\");\n\tbutton1->setBackColor(caDraw::Color::Gray);\n\tbutton1->setPosition({ 128, 300 });\n\tbutton1->setSize({ 330, 100 });\n\tbutton1->WhenClick = [&button1ClickCount, &label1](const caUI::EventArgs& args)\n\t{\n\t\t++button1ClickCount;\n\n\t\tlabel1->setText(std::to_string(button1ClickCount));\n\t};\n\n\n\tauto verticalScrollBar1 = canew<caUI::VerticalScrollBar>();\n\tverticalScrollBar1->setPosition({ 750, 32 });\n\tverticalScrollBar1->setSize({24, 256});\n\tverticalScrollBar1->setMaxValue(1024);\n\tverticalScrollBar1->WhenValueChanged = [&verticalScrollBar1, &label2](const caUI::EventArgs& args)\n\t{\n\t\tlabel2->setText(std::to_string(verticalScrollBar1->getValue()));\n\t};\n\n\n\tauto verticalScrollBar2 = canew<caUI::VerticalScrollBar>();\n\tverticalScrollBar2->setPosition({ 700, 32 });\n\tverticalScrollBar2->setSize({ 24, 256 });\n\tverticalScrollBar2->setMaxValue(256);\n\tverticalScrollBar2->setMinBarLength(32);\n\tverticalScrollBar2->WhenValueChanged = [&verticalScrollBar2, &verticalScrollBar1](const caUI::EventArgs& args)\n\t{\n\t\tverticalScrollBar1->setMaxValue(verticalScrollBar2->getValue());\n\t};\n\n\tverticalScrollBar1->setMaxValue(verticalScrollBar2->getValue());\n\n\n\tauto panel = caFactory->createPanel();\n\tpanel->transform.position = { 64, 64 };\n\tpanel->size = { 800, 600 };\n\n\tpanel->addDrawable(sprite4);\n\tpanel->addDrawable(sprite1);\n\tpanel->addDrawable(sprite2);\n\tpanel->addDrawable(sprite3);\n\tpanel->addDrawable(rect);\n\tpanel->addDrawable(ellipse);\n\tpanel->addDrawable(ellipse2);\n\tpanel->addDrawable(line1);\n\tpanel->addDrawable(text1);\n\tpanel->addDrawable(label1);\n\tpanel->addUpdatable(label1);\n\tpanel->addDrawable(button1);\n\tpanel->addUpdatable(button1);\n\tpanel->addDrawable(verticalScrollBar1);\n\tpanel->addUpdatable(verticalScrollBar1);\n\tpanel->addDrawable(verticalScrollBar2);\n\tpanel->addUpdatable(verticalScrollBar2);\n\n\twindow1->addPanel(panel);\n\n\n\tauto panel2 = caFactory->createPanel();\n\tpanel2->transform.position = { 512, 400 };\n\tpanel2->size = { 400, 300 };\n\n\tpanel2->addDrawable(sprite4);\n\tpanel2->addDrawable(sprite1);\n\tpanel2->addDrawable(sprite2);\n\tpanel2->addDrawable(sprite3);\n\tpanel2->addDrawable(rect);\n\tpanel2->addDrawable(ellipse);\n\tpanel2->addDrawable(line1);\n\tpanel2->addDrawable(text1);\n\tpanel2->addDrawable(label2);\n\tpanel2->addUpdatable(label2);\n\n\twindow1->addPanel(panel2);\n\n\n\tf32 myScale = 1.0f;\n\tf32 scaleDir = 1.0f;\n\n\n\twhile (window1->isRunning())\n\t{\n\t\tcaTouch->update();\n\n\n\t\tcaKeyboard->update();\n\n\t\tif (caKeyboard->isKeyPressed(caSys::Keys::W))\n\t\t{\n\t\t\tellipse2->y -= 0.4f;\n\t\t}\n\t\telse if (caKeyboard->isKeyPressed(caSys::Keys::S))\n\t\t{\n\t\t\tellipse2->y += 0.4f;\n\t\t}\n\n\t\tif (caKeyboard->isKeyPressed(caSys::Keys::A))\n\t\t{\n\t\t\tellipse2->x -= 0.4f;\n\t\t}\n\t\telse if (caKeyboard->isKeyPressed(caSys::Keys::D))\n\t\t{\n\t\t\tellipse2->x += 0.4f;\n\t\t}\n\n\n\t\tmyScale -= scaleDir * myScale \/ 64.0f;\n\t\tif (scaleDir > 0.0f && myScale < 0.1f)\n\t\t{\n\t\t\tscaleDir = -1.0f;\n\t\t}\n\t\telse if (scaleDir < 0.0f && myScale > 2.0f)\n\t\t{\n\t\t\tscaleDir = 1.0f;\n\t\t}\n\n\t\tsprite1->transform.scale.setVector(myScale, myScale);\n\t\tsprite2->transform.scale.setVector(myScale, myScale);\n\t\tsprite3->transform.scale.setVector(myScale, myScale);\n\n\t\tpanel2->transform.angle += 0.02f;\n\n\n\t\trect->setVisible(ellipse->containsPoint(ellipse2->x, ellipse2->y));\n\n\n\t\tauto invPoint = panel2->transform.inverseTransformPoint(caTouch->getPositionF(*window1));\n\t\tellipse2->setLocation(invPoint.x, invPoint.y);\n\n\n\t\tif (label1->isFocused())\n\t\t{\n\t\t\tlabel1->setPosition(label1->getPosition() + caDraw::PointF(0.4f, 0.0f));\n\t\t}\n\n\t\tif (label2->isFocused())\n\t\t{\n\t\t\tlabel2->setPosition(label2->getPosition() + caDraw::PointF(0.4f, 0.0f));\n\t\t}\n\n\n\t\twindow1->update();\n\t\twindow1->draw(caDraw::Color(230, 230, 230));\n\t}\n\n\n\treturn 0;\n}\n\n<|endoftext|>"} {"text":"<commit_before>#ifndef COFFEE_MILL_DCD_MODE\n#define COFFEE_MILL_DCD_MODE\n\/\/ #include \"DCDtoMovie.hpp\"\n\/\/ #include \"SuperImpose.hpp\"\n#include <src\/mill_dcd_join.hpp>\n\/\/ #include \"mill_dcd_extract.hpp\"\n\/\/ #include \"mill_dcd_msd.hpp\"\n\/\/ #include \"mode_dcd_help.hpp\"\n\nnamespace mill\n{\n\n\/\/ argv := arrayof{ \"dcd\", \"command-name\", {rests...} }\ntemplate<typename vectorT>\nint mode_dcd(int argument_c, const char **argument_v)\n{\n if(argument_c < 2)\n {\n \/\/ no commands provided: {\"dcd\"}\n std::cerr << \"error: mill dcd-mode: too few arguments\\n\";\n mode_dcd_help(--argument_c, ++argument_v); \/\/ {}\n return 1;\n }\n\n const std::string command(argument_v[1]);\n if(command == \"join\")\n {\n \/\/ {\"join\", {\"args\"...}}\n return mill_dcd_join<vectorT>(--argument_c, ++argument_v);\n }\n\/\/ else if(command == \"make-movie\")\n\/\/ {\n\/\/ if(argument_c != 3)\n\/\/ {\n\/\/ std::cerr << \"usage: mill dcd make-movie [file.dcd | file.toml]\"\n\/\/ << std::endl;\n\/\/ return 1;\n\/\/ }\n\/\/ const std::string fname(argument_v[2]);\n\/\/ return dcd_to_movie<vectorT>(fname);\n\/\/ }\n\/\/ else if(command == \"impose\")\n\/\/ {\n\/\/ if(argument_c != 3)\n\/\/ {\n\/\/ std::cerr << \"usage: mill dcd impose [file.dcd | file.toml]\"\n\/\/ << std::endl;\n\/\/ return 1;\n\/\/ }\n\/\/ std::string fname(argument_v[2]);\n\/\/ return superimpose<vectorT>(fname);\n\/\/ }\n\/\/ else if(command == \"extract\")\n\/\/ {\n\/\/ if(argument_c < 3)\n\/\/ {\n\/\/ std::cerr << \"usage: mill dcd extract [file.dcd | file.toml]\"\n\/\/ << \" [begin, end]\" << std::endl;\n\/\/ return 1;\n\/\/ }\n\/\/ return mill_dcd_extract<vectorT>(argument_c - 1, argument_v+1);\n\/\/ }\n\/\/ else if(command == \"msd\")\n\/\/ {\n\/\/ if(argument_c < 3)\n\/\/ {\n\/\/ std::cerr << \"usage: mill dcd msd [file.dcd, ... | file.toml]\"\n\/\/ << std::endl;\n\/\/ return 1;\n\/\/ }\n\/\/ return mill_dcd_msd<vectorT>(argument_c - 1, argument_v+1);\n\/\/ }\n else if(command == \"help\")\n {\n \/\/ {\"dcd\", \"help\", {args...}} -> {\"help\", {args...}}\n return mode_dcd_help(--argument_c, ++argument_v);\n }\n else\n {\n std::cerr << \"error: mill dcd-mode: unknown command : \" << command << '\\n';\n return 1;\n }\n}\n\n} \/\/ mill\n\n#endif \/* COFFEE_MILL_PDB_MODE *\/\n<commit_msg>fix typo<commit_after>#ifndef COFFEE_MILL_DCD_MODE\n#define COFFEE_MILL_DCD_MODE\n\/\/ #include \"DCDtoMovie.hpp\"\n\/\/ #include \"SuperImpose.hpp\"\n#include <src\/mode_dcd_join.hpp>\n\/\/ #include \"mill_dcd_extract.hpp\"\n\/\/ #include \"mill_dcd_msd.hpp\"\n\/\/ #include \"mode_dcd_help.hpp\"\n\nnamespace mill\n{\n\n\/\/ argv := arrayof{ \"dcd\", \"command-name\", {rests...} }\ntemplate<typename vectorT>\nint mode_dcd(int argument_c, const char **argument_v)\n{\n if(argument_c < 2)\n {\n \/\/ no commands provided: {\"dcd\"}\n std::cerr << \"error: mill dcd-mode: too few arguments\\n\";\n mode_dcd_help(--argument_c, ++argument_v); \/\/ {}\n return 1;\n }\n\n const std::string command(argument_v[1]);\n if(command == \"join\")\n {\n \/\/ {\"join\", {\"args\"...}}\n return mode_dcd_join<vectorT>(--argument_c, ++argument_v);\n }\n\/\/ else if(command == \"make-movie\")\n\/\/ {\n\/\/ if(argument_c != 3)\n\/\/ {\n\/\/ std::cerr << \"usage: mill dcd make-movie [file.dcd | file.toml]\"\n\/\/ << std::endl;\n\/\/ return 1;\n\/\/ }\n\/\/ const std::string fname(argument_v[2]);\n\/\/ return dcd_to_movie<vectorT>(fname);\n\/\/ }\n\/\/ else if(command == \"impose\")\n\/\/ {\n\/\/ if(argument_c != 3)\n\/\/ {\n\/\/ std::cerr << \"usage: mill dcd impose [file.dcd | file.toml]\"\n\/\/ << std::endl;\n\/\/ return 1;\n\/\/ }\n\/\/ std::string fname(argument_v[2]);\n\/\/ return superimpose<vectorT>(fname);\n\/\/ }\n\/\/ else if(command == \"extract\")\n\/\/ {\n\/\/ if(argument_c < 3)\n\/\/ {\n\/\/ std::cerr << \"usage: mill dcd extract [file.dcd | file.toml]\"\n\/\/ << \" [begin, end]\" << std::endl;\n\/\/ return 1;\n\/\/ }\n\/\/ return mill_dcd_extract<vectorT>(argument_c - 1, argument_v+1);\n\/\/ }\n\/\/ else if(command == \"msd\")\n\/\/ {\n\/\/ if(argument_c < 3)\n\/\/ {\n\/\/ std::cerr << \"usage: mill dcd msd [file.dcd, ... | file.toml]\"\n\/\/ << std::endl;\n\/\/ return 1;\n\/\/ }\n\/\/ return mill_dcd_msd<vectorT>(argument_c - 1, argument_v+1);\n\/\/ }\n else if(command == \"help\")\n {\n \/\/ {\"dcd\", \"help\", {args...}} -> {\"help\", {args...}}\n return mode_dcd_help(--argument_c, ++argument_v);\n }\n else\n {\n std::cerr << \"error: mill dcd-mode: unknown command : \" << command << '\\n';\n return 1;\n }\n}\n\n} \/\/ mill\n\n#endif \/* COFFEE_MILL_PDB_MODE *\/\n<|endoftext|>"} {"text":"<commit_before>#ifndef KEYCODE_HPP\n#define KEYCODE_HPP\n\nnamespace org_pqrs_KeyRemap4MacBook {\n \/\/ ======================================================================\n class EventType {\n public:\n EventType(unsigned int v = 0) : value_(v) {}\n unsigned int get(void) const { return value_; }\n bool operator==(const EventType& other) const { return value_ == other.get(); }\n bool operator!=(const EventType& other) const { return ! (*this == other); }\n\n#include \"keycode\/output\/include.EventType.hpp\"\n\n private:\n unsigned int value_;\n };\n\n \/\/ ======================================================================\n class KeyboardType {\n public:\n KeyboardType(unsigned int v = 0) : value_(v) {}\n unsigned int get(void) const { return value_; }\n bool operator==(const KeyboardType& other) const { return value_ == other.get(); }\n bool operator!=(const KeyboardType& other) const { return ! (*this == other); }\n\n bool isInternalKeyboard(void) const;\n\n#include \"keycode\/output\/include.KeyboardType.hpp\"\n\n private:\n unsigned int value_;\n };\n\n \/\/ ======================================================================\n class KeyCode;\n class Flags;\n\n class ModifierFlag {\n public:\n unsigned int get(void) const { return value_; }\n bool operator==(const ModifierFlag& other) const { return value_ == other.get(); }\n bool operator!=(const ModifierFlag& other) const { return ! (*this == other); }\n\n unsigned int operator~(void) const { return ~value_; }\n\n const KeyCode& getKeyCode(void) const;\n\n#include \"keycode\/output\/include.ModifierFlag.hpp\"\n\n private:\n ModifierFlag(unsigned int v) : value_(v) {}\n unsigned int value_;\n };\n namespace ModifierFlagList {\n const ModifierFlag list[] = {\n ModifierFlag::CAPSLOCK,\n ModifierFlag::SHIFT_L,\n ModifierFlag::SHIFT_R,\n ModifierFlag::CONTROL_L,\n ModifierFlag::CONTROL_R,\n ModifierFlag::OPTION_L,\n ModifierFlag::OPTION_R,\n ModifierFlag::COMMAND_L,\n ModifierFlag::COMMAND_R,\n ModifierFlag::FN,\n };\n const int listsize = sizeof(list) \/ sizeof(list[0]);\n };\n class Flags {\n public:\n Flags(unsigned int v = 0) : value_(v) {}\n Flags(const ModifierFlag& v) : value_(v.get()) {}\n unsigned int get(void) const { return value_; }\n bool operator==(const Flags& other) const { return value_ == other.get(); }\n bool operator!=(const Flags& other) const { return ! (*this == other); }\n\n Flags operator|(const Flags& other) const { return value_ | other.get(); }\n Flags operator&(const Flags& other) const { return value_ & other.get(); }\n\n Flags& add(const Flags& flags) { value_ |= flags.get(); return *this; }\n Flags& stripFN(void) { value_ &= ~ModifierFlag::FN; return *this; }\n Flags& stripCURSOR(void) { value_ &= ~ModifierFlag::CURSOR; return *this; }\n Flags& stripKEYPAD(void) { value_ &= ~ModifierFlag::KEYPAD; return *this; }\n Flags& stripNONE(void) { value_ &= ~ModifierFlag::NONE; return *this; }\n\n bool isOn(const ModifierFlag& flag) const {\n return (value_ & flag.get()) == flag.get();\n }\n bool isOn(const Flags& flags) const {\n if (flags.isOn(ModifierFlag::NONE)) {\n return (value_ | ModifierFlag::NONE.get()) == flags.get();\n } else {\n return (value_ & flags.get()) == flags.get();\n }\n }\n\n private:\n unsigned int value_;\n };\n inline Flags operator|(const ModifierFlag& lhs, const ModifierFlag& rhs) { return lhs.get() | rhs.get(); }\n\n \/\/ ======================================================================\n class KeyCode {\n public:\n KeyCode(unsigned int v = 0) : value_(v) {}\n unsigned int get(void) const { return value_; }\n bool operator==(const KeyCode& other) const { return value_ == other.get(); }\n bool operator!=(const KeyCode& other) const { return ! (*this == other); }\n\n bool operator> (const KeyCode& other) const { return value_ > other.get(); }\n bool operator>=(const KeyCode& other) const { return value_ >= other.get(); }\n\n void normalizeKey(Flags & flags, const KeyboardType &keyboardType);\n void reverseNormalizeKey(Flags & flags, const KeyboardType &keyboardType);\n\n ModifierFlag getModifierFlag(void) const;\n bool isModifier(void) const { return getModifierFlag() != ModifierFlag::NONE; }\n\n#include \"keycode\/output\/include.KeyCode.hpp\"\n\n private:\n unsigned int value_;\n };\n\n \/\/ ======================================================================\n class ConsumerKeyCode {\n public:\n ConsumerKeyCode(unsigned int v = 0) : value_(v) {}\n unsigned int get(void) const { return value_; }\n bool operator==(const ConsumerKeyCode& other) const { return value_ == other.get(); }\n bool operator!=(const ConsumerKeyCode& other) const { return ! (*this == other); }\n\n bool operator> (const ConsumerKeyCode& other) const { return value_ > other.get(); }\n bool operator>=(const ConsumerKeyCode& other) const { return value_ >= other.get(); }\n\n#include \"keycode\/output\/include.ConsumerKeyCode.hpp\"\n\n private:\n unsigned int value_;\n };\n\n \/\/ ======================================================================\n class Buttons;\n\n class PointingButton {\n public:\n unsigned int get(void) const { return value_; }\n bool operator==(const PointingButton& other) const { return value_ == other.get(); }\n bool operator!=(const PointingButton& other) const { return ! (*this == other); }\n\n unsigned int operator~(void) const { return ~value_; }\n\n#include \"keycode\/output\/include.PointingButton.hpp\"\n\n private:\n PointingButton(unsigned int v) : value_(v) {}\n unsigned int value_;\n };\n class Buttons {\n public:\n Buttons(unsigned int v = 0) : value_(v) {}\n Buttons(const PointingButton& v) : value_(v.get()) {}\n unsigned int get(void) const { return value_; }\n bool operator==(const Buttons& other) const { return value_ == other.get(); }\n bool operator!=(const Buttons& other) const { return ! (*this == other); }\n\n Buttons& add(const PointingButton& button) { value_ |= button.get(); return *this; }\n Buttons& remove(const PointingButton& button) { value_ &= ~button; return *this; }\n\n bool isNONE(void) const { return value_ == 0; }\n bool isOn(const Buttons& buttons) {\n return (value_ & buttons.get()) == buttons.get();\n }\n\n private:\n unsigned int value_;\n };\n inline Buttons operator|(const PointingButton& lhs, const PointingButton& rhs) { return lhs.get() | rhs.get(); }\n}\n\n#endif\n<commit_msg>update keycode @ kext<commit_after>#ifndef KEYCODE_HPP\n#define KEYCODE_HPP\n\nnamespace org_pqrs_KeyRemap4MacBook {\n \/\/ ======================================================================\n class EventType {\n public:\n EventType(unsigned int v = 0) : value_(v) {}\n unsigned int get(void) const { return value_; }\n bool operator==(const EventType& other) const { return value_ == other.get(); }\n bool operator!=(const EventType& other) const { return ! (*this == other); }\n\n#include \"keycode\/output\/include.EventType.hpp\"\n\n private:\n unsigned int value_;\n };\n\n \/\/ ======================================================================\n class KeyboardType {\n public:\n KeyboardType(unsigned int v = 0) : value_(v) {}\n unsigned int get(void) const { return value_; }\n bool operator==(const KeyboardType& other) const { return value_ == other.get(); }\n bool operator!=(const KeyboardType& other) const { return ! (*this == other); }\n\n bool isInternalKeyboard(void) const;\n\n#include \"keycode\/output\/include.KeyboardType.hpp\"\n\n private:\n unsigned int value_;\n };\n\n \/\/ ======================================================================\n class KeyCode;\n class Flags;\n\n class ModifierFlag {\n public:\n unsigned int get(void) const { return value_; }\n bool operator==(const ModifierFlag& other) const { return value_ == other.get(); }\n bool operator!=(const ModifierFlag& other) const { return ! (*this == other); }\n\n unsigned int operator~(void) const { return ~value_; }\n\n const KeyCode& getKeyCode(void) const;\n\n#include \"keycode\/output\/include.ModifierFlag.hpp\"\n\n private:\n ModifierFlag(unsigned int v) : value_(v) {}\n unsigned int value_;\n };\n namespace ModifierFlagList {\n const ModifierFlag list[] = {\n ModifierFlag::CAPSLOCK,\n ModifierFlag::SHIFT_L,\n ModifierFlag::SHIFT_R,\n ModifierFlag::CONTROL_L,\n ModifierFlag::CONTROL_R,\n ModifierFlag::OPTION_L,\n ModifierFlag::OPTION_R,\n ModifierFlag::COMMAND_L,\n ModifierFlag::COMMAND_R,\n ModifierFlag::FN,\n };\n const int listsize = sizeof(list) \/ sizeof(list[0]);\n };\n class Flags {\n public:\n Flags(unsigned int v = 0) : value_(v) {}\n Flags(const ModifierFlag& v) : value_(v.get()) {}\n unsigned int get(void) const { return value_; }\n bool operator==(const Flags& other) const { return value_ == other.get(); }\n bool operator!=(const Flags& other) const { return ! (*this == other); }\n\n Flags operator|(const Flags& other) const { return value_ | other.get(); }\n Flags operator&(const Flags& other) const { return value_ & other.get(); }\n\n Flags& add(const Flags& flags) { value_ |= flags.get(); return *this; }\n Flags& stripFN(void) { value_ &= ~ModifierFlag::FN; return *this; }\n Flags& stripCURSOR(void) { value_ &= ~ModifierFlag::CURSOR; return *this; }\n Flags& stripKEYPAD(void) { value_ &= ~ModifierFlag::KEYPAD; return *this; }\n Flags& stripNONE(void) { value_ &= ~ModifierFlag::NONE; return *this; }\n\n bool isOn(const ModifierFlag& flag) const {\n return (value_ & flag.get()) == flag.get();\n }\n bool isOn(const Flags& flags) const {\n if (flags.isOn(ModifierFlag::NONE)) {\n return (value_ | ModifierFlag::NONE.get()) == flags.get();\n } else {\n return (value_ & flags.get()) == flags.get();\n }\n }\n\n private:\n unsigned int value_;\n };\n inline Flags operator|(const ModifierFlag& lhs, const ModifierFlag& rhs) { return lhs.get() | rhs.get(); }\n\n \/\/ ======================================================================\n class KeyCode {\n public:\n KeyCode(unsigned int v = 0) : value_(v) {}\n unsigned int get(void) const { return value_; }\n bool operator==(const KeyCode& other) const { return value_ == other.get(); }\n bool operator!=(const KeyCode& other) const { return ! (*this == other); }\n\n bool operator> (const KeyCode& other) const { return value_ > other.get(); }\n bool operator>=(const KeyCode& other) const { return value_ >= other.get(); }\n\n void normalizeKey(Flags & flags, const KeyboardType &keyboardType);\n void reverseNormalizeKey(Flags & flags, const KeyboardType &keyboardType);\n\n ModifierFlag getModifierFlag(void) const;\n bool isModifier(void) const { return getModifierFlag() != ModifierFlag::NONE; }\n\n#include \"keycode\/output\/include.KeyCode.hpp\"\n\n private:\n unsigned int value_;\n };\n\n \/\/ ======================================================================\n class ConsumerKeyCode {\n public:\n ConsumerKeyCode(unsigned int v = 0) : value_(v) {}\n unsigned int get(void) const { return value_; }\n bool operator==(const ConsumerKeyCode& other) const { return value_ == other.get(); }\n bool operator!=(const ConsumerKeyCode& other) const { return ! (*this == other); }\n\n bool operator> (const ConsumerKeyCode& other) const { return value_ > other.get(); }\n bool operator>=(const ConsumerKeyCode& other) const { return value_ >= other.get(); }\n\n#include \"keycode\/output\/include.ConsumerKeyCode.hpp\"\n\n private:\n unsigned int value_;\n };\n\n \/\/ ======================================================================\n class Buttons;\n\n class PointingButton {\n public:\n unsigned int get(void) const { return value_; }\n bool operator==(const PointingButton& other) const { return value_ == other.get(); }\n bool operator!=(const PointingButton& other) const { return ! (*this == other); }\n\n unsigned int operator~(void) const { return ~value_; }\n\n#include \"keycode\/output\/include.PointingButton.hpp\"\n\n private:\n PointingButton(unsigned int v) : value_(v) {}\n unsigned int value_;\n };\n class Buttons {\n public:\n Buttons(unsigned int v = 0) : value_(v) {}\n Buttons(const PointingButton& v) : value_(v.get()) {}\n unsigned int get(void) const { return value_; }\n bool operator==(const Buttons& other) const { return value_ == other.get(); }\n bool operator!=(const Buttons& other) const { return ! (*this == other); }\n\n Buttons operator|(const Buttons& other) const { return value_ | other.get(); }\n\n Buttons& add(const PointingButton& button) { value_ |= button.get(); return *this; }\n Buttons& remove(const PointingButton& button) { value_ &= ~button; return *this; }\n\n bool isNONE(void) const { return value_ == 0; }\n bool isOn(const Buttons& buttons) {\n return (value_ & buttons.get()) == buttons.get();\n }\n\n private:\n unsigned int value_;\n };\n inline Buttons operator|(const PointingButton& lhs, const PointingButton& rhs) { return lhs.get() | rhs.get(); }\n}\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/\/==- CGObjCRuntime.cpp - Interface to Shared Objective-C Runtime Features ==\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This abstract class defines the interface for Objective-C runtime-specific\n\/\/ code generation. It provides some concrete helper methods for functionality\n\/\/ shared between all (or most) of the Objective-C runtimes supported by clang.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"CGObjCRuntime.h\"\n\n#include \"CGRecordLayout.h\"\n#include \"CodeGenModule.h\"\n#include \"CodeGenFunction.h\"\n#include \"CGCleanup.h\"\n\n#include \"clang\/AST\/RecordLayout.h\"\n#include \"clang\/AST\/StmtObjC.h\"\n\n#include \"llvm\/Support\/CallSite.h\"\n\nusing namespace clang;\nusing namespace CodeGen;\n\nstatic uint64_t LookupFieldBitOffset(CodeGen::CodeGenModule &CGM,\n const ObjCInterfaceDecl *OID,\n const ObjCImplementationDecl *ID,\n const ObjCIvarDecl *Ivar) {\n const ObjCInterfaceDecl *Container = Ivar->getContainingInterface();\n\n \/\/ FIXME: We should eliminate the need to have ObjCImplementationDecl passed\n \/\/ in here; it should never be necessary because that should be the lexical\n \/\/ decl context for the ivar.\n\n \/\/ If we know have an implementation (and the ivar is in it) then\n \/\/ look up in the implementation layout.\n const ASTRecordLayout *RL;\n if (ID && declaresSameEntity(ID->getClassInterface(), Container))\n RL = &CGM.getContext().getASTObjCImplementationLayout(ID);\n else\n RL = &CGM.getContext().getASTObjCInterfaceLayout(Container);\n\n \/\/ Compute field index.\n \/\/\n \/\/ FIXME: The index here is closely tied to how ASTContext::getObjCLayout is\n \/\/ implemented. This should be fixed to get the information from the layout\n \/\/ directly.\n unsigned Index = 0;\n\n for (const ObjCIvarDecl *IVD = Container->all_declared_ivar_begin(); \n IVD; IVD = IVD->getNextIvar()) {\n if (Ivar == IVD)\n break;\n ++Index;\n }\n assert(Index < RL->getFieldCount() && \"Ivar is not inside record layout!\");\n\n return RL->getFieldOffset(Index);\n}\n\nuint64_t CGObjCRuntime::ComputeIvarBaseOffset(CodeGen::CodeGenModule &CGM,\n const ObjCInterfaceDecl *OID,\n const ObjCIvarDecl *Ivar) {\n return LookupFieldBitOffset(CGM, OID, 0, Ivar) \/ \n CGM.getContext().getCharWidth();\n}\n\nuint64_t CGObjCRuntime::ComputeIvarBaseOffset(CodeGen::CodeGenModule &CGM,\n const ObjCImplementationDecl *OID,\n const ObjCIvarDecl *Ivar) {\n return LookupFieldBitOffset(CGM, OID->getClassInterface(), OID, Ivar) \/ \n CGM.getContext().getCharWidth();\n}\n\nLValue CGObjCRuntime::EmitValueForIvarAtOffset(CodeGen::CodeGenFunction &CGF,\n const ObjCInterfaceDecl *OID,\n llvm::Value *BaseValue,\n const ObjCIvarDecl *Ivar,\n unsigned CVRQualifiers,\n llvm::Value *Offset) {\n \/\/ Compute (type*) ( (char *) BaseValue + Offset)\n llvm::Type *I8Ptr = CGF.Int8PtrTy;\n QualType IvarTy = Ivar->getType();\n llvm::Type *LTy = CGF.CGM.getTypes().ConvertTypeForMem(IvarTy);\n llvm::Value *V = CGF.Builder.CreateBitCast(BaseValue, I8Ptr);\n V = CGF.Builder.CreateInBoundsGEP(V, Offset, \"add.ptr\");\n V = CGF.Builder.CreateBitCast(V, llvm::PointerType::getUnqual(LTy));\n\n if (!Ivar->isBitField()) {\n LValue LV = CGF.MakeNaturalAlignAddrLValue(V, IvarTy);\n LV.getQuals().addCVRQualifiers(CVRQualifiers);\n return LV;\n }\n\n \/\/ We need to compute an access strategy for this bit-field. We are given the\n \/\/ offset to the first byte in the bit-field, the sub-byte offset is taken\n \/\/ from the original layout. We reuse the normal bit-field access strategy by\n \/\/ treating this as an access to a struct where the bit-field is in byte 0,\n \/\/ and adjust the containing type size as appropriate.\n \/\/\n \/\/ FIXME: Note that currently we make a very conservative estimate of the\n \/\/ alignment of the bit-field, because (a) it is not clear what guarantees the\n \/\/ runtime makes us, and (b) we don't have a way to specify that the struct is\n \/\/ at an alignment plus offset.\n \/\/\n \/\/ Note, there is a subtle invariant here: we can only call this routine on\n \/\/ non-synthesized ivars but we may be called for synthesized ivars. However,\n \/\/ a synthesized ivar can never be a bit-field, so this is safe.\n const ASTRecordLayout &RL =\n CGF.CGM.getContext().getASTObjCInterfaceLayout(OID);\n uint64_t TypeSizeInBits = CGF.CGM.getContext().toBits(RL.getSize());\n uint64_t FieldBitOffset = LookupFieldBitOffset(CGF.CGM, OID, 0, Ivar);\n uint64_t BitOffset = FieldBitOffset % CGF.CGM.getContext().getCharWidth();\n uint64_t ContainingTypeAlign = CGF.CGM.getContext().getTargetInfo().getCharAlign();\n uint64_t ContainingTypeSize = TypeSizeInBits - (FieldBitOffset - BitOffset);\n uint64_t BitFieldSize = Ivar->getBitWidthValue(CGF.getContext());\n\n \/\/ Allocate a new CGBitFieldInfo object to describe this access.\n \/\/\n \/\/ FIXME: This is incredibly wasteful, these should be uniqued or part of some\n \/\/ layout object. However, this is blocked on other cleanups to the\n \/\/ Objective-C code, so for now we just live with allocating a bunch of these\n \/\/ objects.\n CGBitFieldInfo *Info = new (CGF.CGM.getContext()) CGBitFieldInfo(\n CGBitFieldInfo::MakeInfo(CGF.CGM.getTypes(), Ivar, BitOffset, BitFieldSize,\n ContainingTypeSize, ContainingTypeAlign));\n\n return LValue::MakeBitfield(V, *Info,\n IvarTy.withCVRQualifiers(CVRQualifiers));\n}\n\nnamespace {\n struct CatchHandler {\n const VarDecl *Variable;\n const Stmt *Body;\n llvm::BasicBlock *Block;\n llvm::Value *TypeInfo;\n };\n\n struct CallObjCEndCatch : EHScopeStack::Cleanup {\n CallObjCEndCatch(bool MightThrow, llvm::Value *Fn) :\n MightThrow(MightThrow), Fn(Fn) {}\n bool MightThrow;\n llvm::Value *Fn;\n\n void Emit(CodeGenFunction &CGF, Flags flags) {\n if (!MightThrow) {\n CGF.Builder.CreateCall(Fn)->setDoesNotThrow();\n return;\n }\n\n CGF.EmitCallOrInvoke(Fn);\n }\n };\n}\n\n\nvoid CGObjCRuntime::EmitTryCatchStmt(CodeGenFunction &CGF,\n const ObjCAtTryStmt &S,\n llvm::Constant *beginCatchFn,\n llvm::Constant *endCatchFn,\n llvm::Constant *exceptionRethrowFn) {\n \/\/ Jump destination for falling out of catch bodies.\n CodeGenFunction::JumpDest Cont;\n if (S.getNumCatchStmts())\n Cont = CGF.getJumpDestInCurrentScope(\"eh.cont\");\n\n CodeGenFunction::FinallyInfo FinallyInfo;\n if (const ObjCAtFinallyStmt *Finally = S.getFinallyStmt())\n FinallyInfo.enter(CGF, Finally->getFinallyBody(),\n beginCatchFn, endCatchFn, exceptionRethrowFn);\n\n SmallVector<CatchHandler, 8> Handlers;\n\n \/\/ Enter the catch, if there is one.\n if (S.getNumCatchStmts()) {\n for (unsigned I = 0, N = S.getNumCatchStmts(); I != N; ++I) {\n const ObjCAtCatchStmt *CatchStmt = S.getCatchStmt(I);\n const VarDecl *CatchDecl = CatchStmt->getCatchParamDecl();\n\n Handlers.push_back(CatchHandler());\n CatchHandler &Handler = Handlers.back();\n Handler.Variable = CatchDecl;\n Handler.Body = CatchStmt->getCatchBody();\n Handler.Block = CGF.createBasicBlock(\"catch\");\n\n \/\/ @catch(...) always matches.\n if (!CatchDecl) {\n Handler.TypeInfo = 0; \/\/ catch-all\n \/\/ Don't consider any other catches.\n break;\n }\n\n Handler.TypeInfo = GetEHType(CatchDecl->getType());\n }\n\n EHCatchScope *Catch = CGF.EHStack.pushCatch(Handlers.size());\n for (unsigned I = 0, E = Handlers.size(); I != E; ++I)\n Catch->setHandler(I, Handlers[I].TypeInfo, Handlers[I].Block);\n }\n \n \/\/ Emit the try body.\n CGF.EmitStmt(S.getTryBody());\n\n \/\/ Leave the try.\n if (S.getNumCatchStmts())\n CGF.popCatchScope();\n\n \/\/ Remember where we were.\n CGBuilderTy::InsertPoint SavedIP = CGF.Builder.saveAndClearIP();\n\n \/\/ Emit the handlers.\n for (unsigned I = 0, E = Handlers.size(); I != E; ++I) {\n CatchHandler &Handler = Handlers[I];\n\n CGF.EmitBlock(Handler.Block);\n llvm::Value *RawExn = CGF.getExceptionFromSlot();\n\n \/\/ Enter the catch.\n llvm::Value *Exn = RawExn;\n if (beginCatchFn) {\n Exn = CGF.Builder.CreateCall(beginCatchFn, RawExn, \"exn.adjusted\");\n cast<llvm::CallInst>(Exn)->setDoesNotThrow();\n }\n\n CodeGenFunction::LexicalScope cleanups(CGF, Handler.Body->getSourceRange());\n\n if (endCatchFn) {\n \/\/ Add a cleanup to leave the catch.\n bool EndCatchMightThrow = (Handler.Variable == 0);\n\n CGF.EHStack.pushCleanup<CallObjCEndCatch>(NormalAndEHCleanup,\n EndCatchMightThrow,\n endCatchFn);\n }\n\n \/\/ Bind the catch parameter if it exists.\n if (const VarDecl *CatchParam = Handler.Variable) {\n llvm::Type *CatchType = CGF.ConvertType(CatchParam->getType());\n llvm::Value *CastExn = CGF.Builder.CreateBitCast(Exn, CatchType);\n\n CGF.EmitAutoVarDecl(*CatchParam);\n\n llvm::Value *CatchParamAddr = CGF.GetAddrOfLocalVar(CatchParam);\n\n switch (CatchParam->getType().getQualifiers().getObjCLifetime()) {\n case Qualifiers::OCL_Strong:\n CastExn = CGF.EmitARCRetainNonBlock(CastExn);\n \/\/ fallthrough\n\n case Qualifiers::OCL_None:\n case Qualifiers::OCL_ExplicitNone:\n case Qualifiers::OCL_Autoreleasing:\n CGF.Builder.CreateStore(CastExn, CatchParamAddr);\n break;\n\n case Qualifiers::OCL_Weak:\n CGF.EmitARCInitWeak(CatchParamAddr, CastExn);\n break;\n }\n }\n\n CGF.ObjCEHValueStack.push_back(Exn);\n CGF.EmitStmt(Handler.Body);\n CGF.ObjCEHValueStack.pop_back();\n\n \/\/ Leave any cleanups associated with the catch.\n cleanups.ForceCleanup();\n\n CGF.EmitBranchThroughCleanup(Cont);\n } \n\n \/\/ Go back to the try-statement fallthrough.\n CGF.Builder.restoreIP(SavedIP);\n\n \/\/ Pop out of the finally.\n if (S.getFinallyStmt())\n FinallyInfo.exit(CGF);\n\n if (Cont.isValid())\n CGF.EmitBlock(Cont.getBlock());\n}\n\nnamespace {\n struct CallSyncExit : EHScopeStack::Cleanup {\n llvm::Value *SyncExitFn;\n llvm::Value *SyncArg;\n CallSyncExit(llvm::Value *SyncExitFn, llvm::Value *SyncArg)\n : SyncExitFn(SyncExitFn), SyncArg(SyncArg) {}\n\n void Emit(CodeGenFunction &CGF, Flags flags) {\n CGF.Builder.CreateCall(SyncExitFn, SyncArg)->setDoesNotThrow();\n }\n };\n}\n\nvoid CGObjCRuntime::EmitAtSynchronizedStmt(CodeGenFunction &CGF,\n const ObjCAtSynchronizedStmt &S,\n llvm::Function *syncEnterFn,\n llvm::Function *syncExitFn) {\n CodeGenFunction::RunCleanupsScope cleanups(CGF);\n\n \/\/ Evaluate the lock operand. This is guaranteed to dominate the\n \/\/ ARC release and lock-release cleanups.\n const Expr *lockExpr = S.getSynchExpr();\n llvm::Value *lock;\n if (CGF.getLangOpts().ObjCAutoRefCount) {\n lock = CGF.EmitARCRetainScalarExpr(lockExpr);\n lock = CGF.EmitObjCConsumeObject(lockExpr->getType(), lock);\n } else {\n lock = CGF.EmitScalarExpr(lockExpr);\n }\n lock = CGF.Builder.CreateBitCast(lock, CGF.VoidPtrTy);\n\n \/\/ Acquire the lock.\n CGF.Builder.CreateCall(syncEnterFn, lock)->setDoesNotThrow();\n\n \/\/ Register an all-paths cleanup to release the lock.\n CGF.EHStack.pushCleanup<CallSyncExit>(NormalAndEHCleanup, syncExitFn, lock);\n\n \/\/ Emit the body of the statement.\n CGF.EmitStmt(S.getSynchBody());\n}\n\n\/\/\/ Compute the pointer-to-function type to which a message send\n\/\/\/ should be casted in order to correctly call the given method\n\/\/\/ with the given arguments.\n\/\/\/\n\/\/\/ \\param method - may be null\n\/\/\/ \\param resultType - the result type to use if there's no method\n\/\/\/ \\param argInfo - the actual arguments, including implicit ones\nCGObjCRuntime::MessageSendInfo\nCGObjCRuntime::getMessageSendInfo(const ObjCMethodDecl *method,\n QualType resultType,\n CallArgList &callArgs) {\n \/\/ If there's a method, use information from that.\n if (method) {\n const CGFunctionInfo &signature =\n CGM.getTypes().arrangeObjCMessageSendSignature(method, callArgs[0].Ty);\n\n llvm::PointerType *signatureType =\n CGM.getTypes().GetFunctionType(signature)->getPointerTo();\n\n \/\/ If that's not variadic, there's no need to recompute the ABI\n \/\/ arrangement.\n if (!signature.isVariadic())\n return MessageSendInfo(signature, signatureType);\n\n \/\/ Otherwise, there is.\n FunctionType::ExtInfo einfo = signature.getExtInfo();\n const CGFunctionInfo &argsInfo =\n CGM.getTypes().arrangeFunctionCall(resultType, callArgs, einfo,\n signature.getRequiredArgs());\n\n return MessageSendInfo(argsInfo, signatureType);\n }\n\n \/\/ There's no method; just use a default CC.\n const CGFunctionInfo &argsInfo =\n CGM.getTypes().arrangeFunctionCall(resultType, callArgs, \n FunctionType::ExtInfo(),\n RequiredArgs::All);\n\n \/\/ Derive the signature to call from that.\n llvm::PointerType *signatureType =\n CGM.getTypes().GetFunctionType(argsInfo)->getPointerTo();\n return MessageSendInfo(argsInfo, signatureType);\n}\n<commit_msg>Documentation fix: made the name given to \\param match the code.<commit_after>\/\/==- CGObjCRuntime.cpp - Interface to Shared Objective-C Runtime Features ==\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This abstract class defines the interface for Objective-C runtime-specific\n\/\/ code generation. It provides some concrete helper methods for functionality\n\/\/ shared between all (or most) of the Objective-C runtimes supported by clang.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"CGObjCRuntime.h\"\n\n#include \"CGRecordLayout.h\"\n#include \"CodeGenModule.h\"\n#include \"CodeGenFunction.h\"\n#include \"CGCleanup.h\"\n\n#include \"clang\/AST\/RecordLayout.h\"\n#include \"clang\/AST\/StmtObjC.h\"\n\n#include \"llvm\/Support\/CallSite.h\"\n\nusing namespace clang;\nusing namespace CodeGen;\n\nstatic uint64_t LookupFieldBitOffset(CodeGen::CodeGenModule &CGM,\n const ObjCInterfaceDecl *OID,\n const ObjCImplementationDecl *ID,\n const ObjCIvarDecl *Ivar) {\n const ObjCInterfaceDecl *Container = Ivar->getContainingInterface();\n\n \/\/ FIXME: We should eliminate the need to have ObjCImplementationDecl passed\n \/\/ in here; it should never be necessary because that should be the lexical\n \/\/ decl context for the ivar.\n\n \/\/ If we know have an implementation (and the ivar is in it) then\n \/\/ look up in the implementation layout.\n const ASTRecordLayout *RL;\n if (ID && declaresSameEntity(ID->getClassInterface(), Container))\n RL = &CGM.getContext().getASTObjCImplementationLayout(ID);\n else\n RL = &CGM.getContext().getASTObjCInterfaceLayout(Container);\n\n \/\/ Compute field index.\n \/\/\n \/\/ FIXME: The index here is closely tied to how ASTContext::getObjCLayout is\n \/\/ implemented. This should be fixed to get the information from the layout\n \/\/ directly.\n unsigned Index = 0;\n\n for (const ObjCIvarDecl *IVD = Container->all_declared_ivar_begin(); \n IVD; IVD = IVD->getNextIvar()) {\n if (Ivar == IVD)\n break;\n ++Index;\n }\n assert(Index < RL->getFieldCount() && \"Ivar is not inside record layout!\");\n\n return RL->getFieldOffset(Index);\n}\n\nuint64_t CGObjCRuntime::ComputeIvarBaseOffset(CodeGen::CodeGenModule &CGM,\n const ObjCInterfaceDecl *OID,\n const ObjCIvarDecl *Ivar) {\n return LookupFieldBitOffset(CGM, OID, 0, Ivar) \/ \n CGM.getContext().getCharWidth();\n}\n\nuint64_t CGObjCRuntime::ComputeIvarBaseOffset(CodeGen::CodeGenModule &CGM,\n const ObjCImplementationDecl *OID,\n const ObjCIvarDecl *Ivar) {\n return LookupFieldBitOffset(CGM, OID->getClassInterface(), OID, Ivar) \/ \n CGM.getContext().getCharWidth();\n}\n\nLValue CGObjCRuntime::EmitValueForIvarAtOffset(CodeGen::CodeGenFunction &CGF,\n const ObjCInterfaceDecl *OID,\n llvm::Value *BaseValue,\n const ObjCIvarDecl *Ivar,\n unsigned CVRQualifiers,\n llvm::Value *Offset) {\n \/\/ Compute (type*) ( (char *) BaseValue + Offset)\n llvm::Type *I8Ptr = CGF.Int8PtrTy;\n QualType IvarTy = Ivar->getType();\n llvm::Type *LTy = CGF.CGM.getTypes().ConvertTypeForMem(IvarTy);\n llvm::Value *V = CGF.Builder.CreateBitCast(BaseValue, I8Ptr);\n V = CGF.Builder.CreateInBoundsGEP(V, Offset, \"add.ptr\");\n V = CGF.Builder.CreateBitCast(V, llvm::PointerType::getUnqual(LTy));\n\n if (!Ivar->isBitField()) {\n LValue LV = CGF.MakeNaturalAlignAddrLValue(V, IvarTy);\n LV.getQuals().addCVRQualifiers(CVRQualifiers);\n return LV;\n }\n\n \/\/ We need to compute an access strategy for this bit-field. We are given the\n \/\/ offset to the first byte in the bit-field, the sub-byte offset is taken\n \/\/ from the original layout. We reuse the normal bit-field access strategy by\n \/\/ treating this as an access to a struct where the bit-field is in byte 0,\n \/\/ and adjust the containing type size as appropriate.\n \/\/\n \/\/ FIXME: Note that currently we make a very conservative estimate of the\n \/\/ alignment of the bit-field, because (a) it is not clear what guarantees the\n \/\/ runtime makes us, and (b) we don't have a way to specify that the struct is\n \/\/ at an alignment plus offset.\n \/\/\n \/\/ Note, there is a subtle invariant here: we can only call this routine on\n \/\/ non-synthesized ivars but we may be called for synthesized ivars. However,\n \/\/ a synthesized ivar can never be a bit-field, so this is safe.\n const ASTRecordLayout &RL =\n CGF.CGM.getContext().getASTObjCInterfaceLayout(OID);\n uint64_t TypeSizeInBits = CGF.CGM.getContext().toBits(RL.getSize());\n uint64_t FieldBitOffset = LookupFieldBitOffset(CGF.CGM, OID, 0, Ivar);\n uint64_t BitOffset = FieldBitOffset % CGF.CGM.getContext().getCharWidth();\n uint64_t ContainingTypeAlign = CGF.CGM.getContext().getTargetInfo().getCharAlign();\n uint64_t ContainingTypeSize = TypeSizeInBits - (FieldBitOffset - BitOffset);\n uint64_t BitFieldSize = Ivar->getBitWidthValue(CGF.getContext());\n\n \/\/ Allocate a new CGBitFieldInfo object to describe this access.\n \/\/\n \/\/ FIXME: This is incredibly wasteful, these should be uniqued or part of some\n \/\/ layout object. However, this is blocked on other cleanups to the\n \/\/ Objective-C code, so for now we just live with allocating a bunch of these\n \/\/ objects.\n CGBitFieldInfo *Info = new (CGF.CGM.getContext()) CGBitFieldInfo(\n CGBitFieldInfo::MakeInfo(CGF.CGM.getTypes(), Ivar, BitOffset, BitFieldSize,\n ContainingTypeSize, ContainingTypeAlign));\n\n return LValue::MakeBitfield(V, *Info,\n IvarTy.withCVRQualifiers(CVRQualifiers));\n}\n\nnamespace {\n struct CatchHandler {\n const VarDecl *Variable;\n const Stmt *Body;\n llvm::BasicBlock *Block;\n llvm::Value *TypeInfo;\n };\n\n struct CallObjCEndCatch : EHScopeStack::Cleanup {\n CallObjCEndCatch(bool MightThrow, llvm::Value *Fn) :\n MightThrow(MightThrow), Fn(Fn) {}\n bool MightThrow;\n llvm::Value *Fn;\n\n void Emit(CodeGenFunction &CGF, Flags flags) {\n if (!MightThrow) {\n CGF.Builder.CreateCall(Fn)->setDoesNotThrow();\n return;\n }\n\n CGF.EmitCallOrInvoke(Fn);\n }\n };\n}\n\n\nvoid CGObjCRuntime::EmitTryCatchStmt(CodeGenFunction &CGF,\n const ObjCAtTryStmt &S,\n llvm::Constant *beginCatchFn,\n llvm::Constant *endCatchFn,\n llvm::Constant *exceptionRethrowFn) {\n \/\/ Jump destination for falling out of catch bodies.\n CodeGenFunction::JumpDest Cont;\n if (S.getNumCatchStmts())\n Cont = CGF.getJumpDestInCurrentScope(\"eh.cont\");\n\n CodeGenFunction::FinallyInfo FinallyInfo;\n if (const ObjCAtFinallyStmt *Finally = S.getFinallyStmt())\n FinallyInfo.enter(CGF, Finally->getFinallyBody(),\n beginCatchFn, endCatchFn, exceptionRethrowFn);\n\n SmallVector<CatchHandler, 8> Handlers;\n\n \/\/ Enter the catch, if there is one.\n if (S.getNumCatchStmts()) {\n for (unsigned I = 0, N = S.getNumCatchStmts(); I != N; ++I) {\n const ObjCAtCatchStmt *CatchStmt = S.getCatchStmt(I);\n const VarDecl *CatchDecl = CatchStmt->getCatchParamDecl();\n\n Handlers.push_back(CatchHandler());\n CatchHandler &Handler = Handlers.back();\n Handler.Variable = CatchDecl;\n Handler.Body = CatchStmt->getCatchBody();\n Handler.Block = CGF.createBasicBlock(\"catch\");\n\n \/\/ @catch(...) always matches.\n if (!CatchDecl) {\n Handler.TypeInfo = 0; \/\/ catch-all\n \/\/ Don't consider any other catches.\n break;\n }\n\n Handler.TypeInfo = GetEHType(CatchDecl->getType());\n }\n\n EHCatchScope *Catch = CGF.EHStack.pushCatch(Handlers.size());\n for (unsigned I = 0, E = Handlers.size(); I != E; ++I)\n Catch->setHandler(I, Handlers[I].TypeInfo, Handlers[I].Block);\n }\n \n \/\/ Emit the try body.\n CGF.EmitStmt(S.getTryBody());\n\n \/\/ Leave the try.\n if (S.getNumCatchStmts())\n CGF.popCatchScope();\n\n \/\/ Remember where we were.\n CGBuilderTy::InsertPoint SavedIP = CGF.Builder.saveAndClearIP();\n\n \/\/ Emit the handlers.\n for (unsigned I = 0, E = Handlers.size(); I != E; ++I) {\n CatchHandler &Handler = Handlers[I];\n\n CGF.EmitBlock(Handler.Block);\n llvm::Value *RawExn = CGF.getExceptionFromSlot();\n\n \/\/ Enter the catch.\n llvm::Value *Exn = RawExn;\n if (beginCatchFn) {\n Exn = CGF.Builder.CreateCall(beginCatchFn, RawExn, \"exn.adjusted\");\n cast<llvm::CallInst>(Exn)->setDoesNotThrow();\n }\n\n CodeGenFunction::LexicalScope cleanups(CGF, Handler.Body->getSourceRange());\n\n if (endCatchFn) {\n \/\/ Add a cleanup to leave the catch.\n bool EndCatchMightThrow = (Handler.Variable == 0);\n\n CGF.EHStack.pushCleanup<CallObjCEndCatch>(NormalAndEHCleanup,\n EndCatchMightThrow,\n endCatchFn);\n }\n\n \/\/ Bind the catch parameter if it exists.\n if (const VarDecl *CatchParam = Handler.Variable) {\n llvm::Type *CatchType = CGF.ConvertType(CatchParam->getType());\n llvm::Value *CastExn = CGF.Builder.CreateBitCast(Exn, CatchType);\n\n CGF.EmitAutoVarDecl(*CatchParam);\n\n llvm::Value *CatchParamAddr = CGF.GetAddrOfLocalVar(CatchParam);\n\n switch (CatchParam->getType().getQualifiers().getObjCLifetime()) {\n case Qualifiers::OCL_Strong:\n CastExn = CGF.EmitARCRetainNonBlock(CastExn);\n \/\/ fallthrough\n\n case Qualifiers::OCL_None:\n case Qualifiers::OCL_ExplicitNone:\n case Qualifiers::OCL_Autoreleasing:\n CGF.Builder.CreateStore(CastExn, CatchParamAddr);\n break;\n\n case Qualifiers::OCL_Weak:\n CGF.EmitARCInitWeak(CatchParamAddr, CastExn);\n break;\n }\n }\n\n CGF.ObjCEHValueStack.push_back(Exn);\n CGF.EmitStmt(Handler.Body);\n CGF.ObjCEHValueStack.pop_back();\n\n \/\/ Leave any cleanups associated with the catch.\n cleanups.ForceCleanup();\n\n CGF.EmitBranchThroughCleanup(Cont);\n } \n\n \/\/ Go back to the try-statement fallthrough.\n CGF.Builder.restoreIP(SavedIP);\n\n \/\/ Pop out of the finally.\n if (S.getFinallyStmt())\n FinallyInfo.exit(CGF);\n\n if (Cont.isValid())\n CGF.EmitBlock(Cont.getBlock());\n}\n\nnamespace {\n struct CallSyncExit : EHScopeStack::Cleanup {\n llvm::Value *SyncExitFn;\n llvm::Value *SyncArg;\n CallSyncExit(llvm::Value *SyncExitFn, llvm::Value *SyncArg)\n : SyncExitFn(SyncExitFn), SyncArg(SyncArg) {}\n\n void Emit(CodeGenFunction &CGF, Flags flags) {\n CGF.Builder.CreateCall(SyncExitFn, SyncArg)->setDoesNotThrow();\n }\n };\n}\n\nvoid CGObjCRuntime::EmitAtSynchronizedStmt(CodeGenFunction &CGF,\n const ObjCAtSynchronizedStmt &S,\n llvm::Function *syncEnterFn,\n llvm::Function *syncExitFn) {\n CodeGenFunction::RunCleanupsScope cleanups(CGF);\n\n \/\/ Evaluate the lock operand. This is guaranteed to dominate the\n \/\/ ARC release and lock-release cleanups.\n const Expr *lockExpr = S.getSynchExpr();\n llvm::Value *lock;\n if (CGF.getLangOpts().ObjCAutoRefCount) {\n lock = CGF.EmitARCRetainScalarExpr(lockExpr);\n lock = CGF.EmitObjCConsumeObject(lockExpr->getType(), lock);\n } else {\n lock = CGF.EmitScalarExpr(lockExpr);\n }\n lock = CGF.Builder.CreateBitCast(lock, CGF.VoidPtrTy);\n\n \/\/ Acquire the lock.\n CGF.Builder.CreateCall(syncEnterFn, lock)->setDoesNotThrow();\n\n \/\/ Register an all-paths cleanup to release the lock.\n CGF.EHStack.pushCleanup<CallSyncExit>(NormalAndEHCleanup, syncExitFn, lock);\n\n \/\/ Emit the body of the statement.\n CGF.EmitStmt(S.getSynchBody());\n}\n\n\/\/\/ Compute the pointer-to-function type to which a message send\n\/\/\/ should be casted in order to correctly call the given method\n\/\/\/ with the given arguments.\n\/\/\/\n\/\/\/ \\param method - may be null\n\/\/\/ \\param resultType - the result type to use if there's no method\n\/\/\/ \\param callArgs - the actual arguments, including implicit ones\nCGObjCRuntime::MessageSendInfo\nCGObjCRuntime::getMessageSendInfo(const ObjCMethodDecl *method,\n QualType resultType,\n CallArgList &callArgs) {\n \/\/ If there's a method, use information from that.\n if (method) {\n const CGFunctionInfo &signature =\n CGM.getTypes().arrangeObjCMessageSendSignature(method, callArgs[0].Ty);\n\n llvm::PointerType *signatureType =\n CGM.getTypes().GetFunctionType(signature)->getPointerTo();\n\n \/\/ If that's not variadic, there's no need to recompute the ABI\n \/\/ arrangement.\n if (!signature.isVariadic())\n return MessageSendInfo(signature, signatureType);\n\n \/\/ Otherwise, there is.\n FunctionType::ExtInfo einfo = signature.getExtInfo();\n const CGFunctionInfo &argsInfo =\n CGM.getTypes().arrangeFunctionCall(resultType, callArgs, einfo,\n signature.getRequiredArgs());\n\n return MessageSendInfo(argsInfo, signatureType);\n }\n\n \/\/ There's no method; just use a default CC.\n const CGFunctionInfo &argsInfo =\n CGM.getTypes().arrangeFunctionCall(resultType, callArgs, \n FunctionType::ExtInfo(),\n RequiredArgs::All);\n\n \/\/ Derive the signature to call from that.\n llvm::PointerType *signatureType =\n CGM.getTypes().GetFunctionType(argsInfo)->getPointerTo();\n return MessageSendInfo(argsInfo, signatureType);\n}\n<|endoftext|>"} {"text":"<commit_before>\n\/*\n* The MIT License (MIT)\n*\n* Copyright (c) 2015 vmolsa <ville.molsa@gmail.com> (http:\/\/github.com\/vmolsa)\n*\n* Permission is hereby granted, free of charge, to any person obtaining a copy\n* of this software and associated documentation files (the \"Software\"), to deal\n* in the Software without restriction, including without limitation the rights\n* to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n* copies of the Software, and to permit persons to whom the Software is\n* furnished to do so, subject to the following conditions:\n*\n* The above copyright notice and this permission notice shall be included in\n* all copies or substantial portions of the Software.\n*\n* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n* THE SOFTWARE.\n*\n*\/\n\n#include \"Platform.h\"\n#include <webrtc\/base\/ssladapter.h>\n#include <webrtc\/base\/macsocketserver.h>\n#include <webrtc\/base\/maccocoasocketserver.h>\n\nusing namespace WebRTC;\n\nclass PlatformWorker : public rtc::Thread {\n public:\n explicit PlatformWorker(rtc::SocketServer* ss = nullptr); \n virtual void Run();\n};\n\nPlatformWorker::PlatformWorker(rtc::SocketServer* ss) : rtc::Thread(ss) { }\n\nvoid PlatformWorker::Run() {\n LOG(LS_INFO) << __PRETTY_FUNCTION__;\n bool running = false;\n \n do {\n running = rtc::Thread::ProcessMessages(1);\n } while(running);\n}\n\nrtc::MacCFSocketServer ss;\nPlatformWorker *worker;\n\nvoid Platform::Init() {\n LOG(LS_INFO) << __PRETTY_FUNCTION__;\n worker = new PlatformWorker(&ss);\n \n worker->Start();\n \n rtc::InitializeSSL();\n rtc::ThreadManager::Instance()->SetCurrentThread(worker);\n \n if (rtc::ThreadManager::Instance()->CurrentThread() != worker) {\n LOG(LS_ERROR) << \"Internal Thread Error!\";\n abort();\n }\n}\n\nvoid Platform::Dispose() {\n LOG(LS_INFO) << __PRETTY_FUNCTION__;\n \n worker->Stop();\n\n if (rtc::ThreadManager::Instance()->CurrentThread() == worker) {\n rtc::ThreadManager::Instance()->SetCurrentThread(NULL);\n } \n \n rtc::CleanupSSL();\n \n delete worker;\n}<commit_msg>Update OSX Platform<commit_after>\n\/*\n* The MIT License (MIT)\n*\n* Copyright (c) 2015 vmolsa <ville.molsa@gmail.com> (http:\/\/github.com\/vmolsa)\n*\n* Permission is hereby granted, free of charge, to any person obtaining a copy\n* of this software and associated documentation files (the \"Software\"), to deal\n* in the Software without restriction, including without limitation the rights\n* to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n* copies of the Software, and to permit persons to whom the Software is\n* furnished to do so, subject to the following conditions:\n*\n* The above copyright notice and this permission notice shall be included in\n* all copies or substantial portions of the Software.\n*\n* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n* THE SOFTWARE.\n*\n*\/\n\n#include \"Platform.h\"\n#include <webrtc\/base\/ssladapter.h>\n#include <webrtc\/base\/macsocketserver.h>\n#include <webrtc\/base\/maccocoasocketserver.h>\n\nusing namespace WebRTC;\n\nclass PlatformWorker : public rtc::Thread {\n public:\n explicit PlatformWorker(rtc::SocketServer* ss = nullptr); \n virtual void Run();\n};\n\nPlatformWorker::PlatformWorker(rtc::SocketServer* ss) : rtc::Thread(ss) {\n SetAllowBlockingCalls(true);\n}\n\nvoid PlatformWorker::Run() {\n LOG(LS_INFO) << __PRETTY_FUNCTION__;\n bool running = false;\n \n do {\n running = rtc::Thread::ProcessMessages(1);\n } while(running);\n}\n\nrtc::MacCFSocketServer ss;\nPlatformWorker *worker;\n\nvoid Platform::Init() {\n LOG(LS_INFO) << __PRETTY_FUNCTION__;\n worker = new PlatformWorker(&ss);\n \n worker->Start();\n \n rtc::InitializeSSL();\n rtc::ThreadManager::Instance()->SetCurrentThread(worker);\n \n if (rtc::ThreadManager::Instance()->CurrentThread() != worker) {\n LOG(LS_ERROR) << \"Internal Thread Error!\";\n abort();\n }\n}\n\nvoid Platform::Dispose() {\n LOG(LS_INFO) << __PRETTY_FUNCTION__;\n \n worker->Stop();\n\n if (rtc::ThreadManager::Instance()->CurrentThread() == worker) {\n rtc::ThreadManager::Instance()->SetCurrentThread(NULL);\n } \n \n rtc::CleanupSSL();\n \n delete worker;\n}<|endoftext|>"} {"text":"<commit_before>\/** \\file util.cc\n * \\brief Implementation of various utility functions.\n * \\author Dr. Johannes Ruscheinski\n *\/\n\n\/*\n Copyright (C) 2015,2017,2018 Library of the University of Tübingen\n\n This program is free software: you can redistribute it and\/or modify\n it under the terms of the GNU Affero General Public License as\n published by the Free Software Foundation, either version 3 of the\n License, or (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU Affero General Public License for more details.\n\n You should have received a copy of the GNU Affero General Public License\n along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n*\/\n#include \"util.h\"\n#include <iostream>\n#include <iterator>\n#include <stdexcept>\n#include <cctype>\n#include <cstdlib>\n#include <execinfo.h>\n#include <signal.h>\n#include \"Compiler.h\"\n#include \"FileLocker.h\"\n#include \"MiscUtil.h\"\n#include \"TimeUtil.h\"\n\n\n\/\/ Macro to determine the number of entries in a one-dimensional array:\n#define DIM(array) (sizeof(array) \/ sizeof(array[0]))\n\n\nchar *progname; \/\/ Must be set in main() with \"progname = argv[0];\";\n\n\nLogger::Logger(): fd_(STDERR_FILENO), log_process_pids_(false), log_no_decorations_(false), min_log_level_(LL_INFO) {\n const char * const min_log_level(::getenv(\"MIN_LOG_LEVEL\"));\n if (min_log_level != nullptr)\n min_log_level_ = Logger::StringToLogLevel(min_log_level);\n const char * const logger_format(::getenv(\"LOGGER_FORMAT\"));\n if (logger_format != nullptr) {\n if (std::strstr(logger_format, \"process_pids\") != 0)\n log_process_pids_ = true;\n else if (std::strstr(logger_format, \"no_decorations\") != 0)\n log_no_decorations_ = true;\n }\n}\n\n\nvoid Logger::error(const std::string &msg) {\n std::lock_guard<std::mutex> mutex_locker(mutex_);\n\n writeString(\"SEVERE\", msg);\n if (::getenv(\"BACKTRACE\") != nullptr) {\n const bool saved_log_no_decorations(log_no_decorations_);\n log_no_decorations_ = true;\n writeString(\"\", \"Backtrace:\");\n for (const auto &stack_entry : MiscUtil::GetCallStack())\n writeString(\"\", \" \" + stack_entry);\n log_no_decorations_ = saved_log_no_decorations;\n }\n\n std::exit(EXIT_FAILURE);\n}\n\n\nvoid Logger::warning(const std::string &msg) {\n if (min_log_level_ < LL_WARNING)\n return;\n\n std::lock_guard<std::mutex> mutex_locker(mutex_);\n writeString(\"WARN\", msg);\n}\n\n\nvoid Logger::info(const std::string &msg) {\n if (min_log_level_ < LL_INFO)\n return;\n\n std::lock_guard<std::mutex> mutex_locker(mutex_);\n writeString(\"INFO\", msg);\n}\n\n\nvoid Logger::debug(const std::string &msg) {\n if ((min_log_level_ < LL_DEBUG) and (MiscUtil::SafeGetEnv(\"UTIL_LOG_DEBUG\") != \"true\"))\n return;\n\n std::lock_guard<std::mutex> mutex_locker(mutex_);\n writeString(\"DEBUG\", msg);\n}\n\n\ninline Logger *LoggerInstantiator() {\n return new Logger();\n}\n\n\nLogger *logger(LoggerInstantiator());\n\n\nLogger::LogLevel Logger::StringToLogLevel(const std::string &level_candidate) {\n if (level_candidate == \"ERROR\")\n return Logger::LL_ERROR;\n if (level_candidate == \"WARNING\")\n return Logger::LL_WARNING;\n if (level_candidate == \"INFO\")\n return Logger::LL_INFO;\n if (level_candidate == \"DEBUG\")\n return Logger::LL_DEBUG;\n LOG_ERROR(\"not a valid minimum log level: \\\"\" + level_candidate + \"\\\"! (Use ERROR, WARNING, INFO or DEBUG)\");\n}\n\n\nstd::string Logger::LogLevelToString(const LogLevel log_level) {\n if (log_level == Logger::LL_ERROR)\n return \"ERROR\";\n if (log_level == Logger::LL_WARNING)\n return \"WARNING\";\n if (log_level == Logger::LL_INFO)\n return \"INFO\";\n if (log_level == Logger::LL_DEBUG)\n return \"DEBUG\";\n LOG_ERROR(\"unsupported log level, we should *never* get here!\");\n}\n\n\nvoid Logger::writeString(const std::string &level, std::string msg) {\n if (unlikely(::progname == nullptr))\n msg = \"You must set \\\"progname\\\" in main() with \\\"::progname = argv[0];\\\" in oder to use the Logger API!\";\n else if (not log_no_decorations_) {\n msg = TimeUtil::GetCurrentDateAndTime(TimeUtil::ISO_8601_FORMAT) + \" \" + level + \" \" + std::string(::progname) + \": \"\n + msg;\n if (log_process_pids_)\n msg += \" (PID: \" + std::to_string(::getpid()) + \")\";\n msg += '\\n';\n }\n \n FileLocker write_locker(fd_, FileLocker::WRITE_ONLY);\n if (unlikely(::write(fd_, reinterpret_cast<const void *>(msg.data()), msg.size()) == -1)) {\n const std::string error_message(\"in Logger::writeString(util.cc): write to file descriptor \" + std::to_string(fd_)\n + \" failed! (errno = \" + std::to_string(errno) + \")\");\n #pragma GCC diagnostic ignored \"-Wunused-result\"\n ::write(STDERR_FILENO, error_message.data(), error_message.size());\n #pragma GCC diagnostic warning \"-Wunused-result\"\n _exit(EXIT_FAILURE);\n }\n\n if (unlikely(::progname == nullptr))\n _exit(EXIT_FAILURE);\n}\n\n\nDSVReader::DSVReader(const std::string &filename, const char field_separator, const char field_delimiter)\n : field_separator_(field_separator), field_delimiter_(field_delimiter), line_no_(0), filename_(filename)\n{\n input_ = std::fopen(filename.c_str(), \"rm\");\n if (input_ == nullptr)\n throw std::runtime_error(\"in DSVReader::DSVReader: can't open \\\"\" + filename + \"\\\" for reading!\");\n}\n\n\nDSVReader::~DSVReader() {\n if (input_ != nullptr)\n std::fclose(input_);\n}\n\n\nnamespace {\n\n\nvoid SkipFieldPadding(FILE * const input) {\n int ch = std::fgetc(input);\n while (isblank(ch))\n ch = std::fgetc(input);\n std::ungetc(ch, input);\n}\n\n\nstd::string ReadQuotedValue(FILE * const input, const char field_delimiter) {\n std::string value;\n bool delimiter_seen(false);\n for (;;) {\n const int ch(std::fgetc(input));\n if (ch == EOF)\n throw std::runtime_error(\"unexpected EOF while reading a quoted DSV value!\");\n if (ch == field_delimiter) {\n if (delimiter_seen) {\n value += static_cast<char>(ch);\n delimiter_seen = false;\n } else\n delimiter_seen = true;\n } else if (delimiter_seen) {\n std::ungetc(ch, input);\n return value;\n } else\n value += static_cast<char>(ch);\n }\n}\n\n\n\/** \\brief Remove trailing spaces and tabs from \"s\". *\/\nstd::string TrimBlanks(std::string * s) {\n std::string::const_reverse_iterator it(s->crbegin());\n for (\/* Empty! *\/; it != s->crend() and std::isblank(*it); ++it)\n \/* Intentionally Empty! *\/;\n if (it != s->crbegin())\n *s = s->substr(0, std::distance(it, s->crend()));\n\n return *s;\n}\n\n\nstd::string ReadNonQuotedValue(FILE * const input, const char field_separator) {\n std::string value;\n for (;;) {\n const int ch(std::fgetc(input));\n if (ch == EOF or ch == '\\n' or ch == field_separator) {\n std::ungetc(ch, input);\n return TrimBlanks(&value);\n }\n value += static_cast<char>(ch);\n }\n}\n\n\nvoid BacktraceSignalHandler(int signal_no) {\n void *stack_return_addresses[20];\n const size_t number_of_addresses(::backtrace(stack_return_addresses, DIM(stack_return_addresses)));\n char err_msg[1024] = \"Caught signal \";\n char *cp = err_msg + std::strlen(err_msg);\n if (signal_no > 10)\n *cp++ = '0' + (signal_no \/ 10);\n *cp++ = '0' + (signal_no % 10);\n *cp++ = '.';\n *cp++ = '\\n';\n *cp = '\\0';\n ssize_t unused(::write(STDERR_FILENO, err_msg, std::strlen(err_msg)));\n (void)unused;\n ::backtrace_symbols_fd(stack_return_addresses, number_of_addresses, STDERR_FILENO);\n ::_exit(EXIT_FAILURE);\n}\n\n\nint InstallSegvSignalHandler(void handler(int)) {\n ::signal(SIGSEGV, handler);\n return 0;\n}\n\n\nvolatile int dummy = InstallSegvSignalHandler(BacktraceSignalHandler);\n\n\n} \/\/ unnamed namespace\n\n\nbool DSVReader::readLine(std::vector<std::string> * const values) {\n values->clear();\n ++line_no_;\n\n int ch;\n for (;;) {\n if (not values->empty()) {\n SkipFieldPadding(input_);\n ch = std::fgetc(input_);\n if (ch == EOF)\n return false;\n if (ch == '\\n')\n return true;\n if (ch != field_separator_)\n throw std::runtime_error(\"in DSVReader::readLine: on line \" + std::to_string(line_no_)\n + \": field separator expected, found '\"\n + std::string(1, static_cast<char>(ch)) + \"' instead!\");\n }\n\n SkipFieldPadding(input_);\n ch = std::fgetc(input_);\n if (ch == '\\n')\n return true;\n if (ch == EOF)\n return false;\n if (ch == field_separator_) {\n std::ungetc(ch, input_);\n values->emplace_back(\"\");\n } else if (ch == field_delimiter_)\n values->emplace_back(ReadQuotedValue(input_, field_delimiter_));\n else {\n std::ungetc(ch, input_);\n values->emplace_back(ReadNonQuotedValue(input_, field_separator_));\n }\n }\n}\n<commit_msg>Missing newlines are not a great idea.<commit_after>\/** \\file util.cc\n * \\brief Implementation of various utility functions.\n * \\author Dr. Johannes Ruscheinski\n *\/\n\n\/*\n Copyright (C) 2015,2017,2018 Library of the University of Tübingen\n\n This program is free software: you can redistribute it and\/or modify\n it under the terms of the GNU Affero General Public License as\n published by the Free Software Foundation, either version 3 of the\n License, or (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU Affero General Public License for more details.\n\n You should have received a copy of the GNU Affero General Public License\n along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n*\/\n#include \"util.h\"\n#include <iostream>\n#include <iterator>\n#include <stdexcept>\n#include <cctype>\n#include <cstdlib>\n#include <execinfo.h>\n#include <signal.h>\n#include \"Compiler.h\"\n#include \"FileLocker.h\"\n#include \"MiscUtil.h\"\n#include \"TimeUtil.h\"\n\n\n\/\/ Macro to determine the number of entries in a one-dimensional array:\n#define DIM(array) (sizeof(array) \/ sizeof(array[0]))\n\n\nchar *progname; \/\/ Must be set in main() with \"progname = argv[0];\";\n\n\nLogger::Logger(): fd_(STDERR_FILENO), log_process_pids_(false), log_no_decorations_(false), min_log_level_(LL_INFO) {\n const char * const min_log_level(::getenv(\"MIN_LOG_LEVEL\"));\n if (min_log_level != nullptr)\n min_log_level_ = Logger::StringToLogLevel(min_log_level);\n const char * const logger_format(::getenv(\"LOGGER_FORMAT\"));\n if (logger_format != nullptr) {\n if (std::strstr(logger_format, \"process_pids\") != 0)\n log_process_pids_ = true;\n else if (std::strstr(logger_format, \"no_decorations\") != 0)\n log_no_decorations_ = true;\n }\n}\n\n\nvoid Logger::error(const std::string &msg) {\n std::lock_guard<std::mutex> mutex_locker(mutex_);\n\n writeString(\"SEVERE\", msg);\n if (::getenv(\"BACKTRACE\") != nullptr) {\n const bool saved_log_no_decorations(log_no_decorations_);\n log_no_decorations_ = true;\n writeString(\"\", \"Backtrace:\");\n for (const auto &stack_entry : MiscUtil::GetCallStack())\n writeString(\"\", \" \" + stack_entry);\n log_no_decorations_ = saved_log_no_decorations;\n }\n\n std::exit(EXIT_FAILURE);\n}\n\n\nvoid Logger::warning(const std::string &msg) {\n if (min_log_level_ < LL_WARNING)\n return;\n\n std::lock_guard<std::mutex> mutex_locker(mutex_);\n writeString(\"WARN\", msg);\n}\n\n\nvoid Logger::info(const std::string &msg) {\n if (min_log_level_ < LL_INFO)\n return;\n\n std::lock_guard<std::mutex> mutex_locker(mutex_);\n writeString(\"INFO\", msg);\n}\n\n\nvoid Logger::debug(const std::string &msg) {\n if ((min_log_level_ < LL_DEBUG) and (MiscUtil::SafeGetEnv(\"UTIL_LOG_DEBUG\") != \"true\"))\n return;\n\n std::lock_guard<std::mutex> mutex_locker(mutex_);\n writeString(\"DEBUG\", msg);\n}\n\n\ninline Logger *LoggerInstantiator() {\n return new Logger();\n}\n\n\nLogger *logger(LoggerInstantiator());\n\n\nLogger::LogLevel Logger::StringToLogLevel(const std::string &level_candidate) {\n if (level_candidate == \"ERROR\")\n return Logger::LL_ERROR;\n if (level_candidate == \"WARNING\")\n return Logger::LL_WARNING;\n if (level_candidate == \"INFO\")\n return Logger::LL_INFO;\n if (level_candidate == \"DEBUG\")\n return Logger::LL_DEBUG;\n LOG_ERROR(\"not a valid minimum log level: \\\"\" + level_candidate + \"\\\"! (Use ERROR, WARNING, INFO or DEBUG)\");\n}\n\n\nstd::string Logger::LogLevelToString(const LogLevel log_level) {\n if (log_level == Logger::LL_ERROR)\n return \"ERROR\";\n if (log_level == Logger::LL_WARNING)\n return \"WARNING\";\n if (log_level == Logger::LL_INFO)\n return \"INFO\";\n if (log_level == Logger::LL_DEBUG)\n return \"DEBUG\";\n LOG_ERROR(\"unsupported log level, we should *never* get here!\");\n}\n\n\nvoid Logger::writeString(const std::string &level, std::string msg) {\n if (unlikely(::progname == nullptr))\n msg = \"You must set \\\"progname\\\" in main() with \\\"::progname = argv[0];\\\" in oder to use the Logger API!\";\n else if (not log_no_decorations_) {\n msg = TimeUtil::GetCurrentDateAndTime(TimeUtil::ISO_8601_FORMAT) + \" \" + level + \" \" + std::string(::progname) + \": \"\n + msg;\n if (log_process_pids_)\n msg += \" (PID: \" + std::to_string(::getpid()) + \")\";\n }\n msg += '\\n';\n \n FileLocker write_locker(fd_, FileLocker::WRITE_ONLY);\n if (unlikely(::write(fd_, reinterpret_cast<const void *>(msg.data()), msg.size()) == -1)) {\n const std::string error_message(\"in Logger::writeString(util.cc): write to file descriptor \" + std::to_string(fd_)\n + \" failed! (errno = \" + std::to_string(errno) + \")\");\n #pragma GCC diagnostic ignored \"-Wunused-result\"\n ::write(STDERR_FILENO, error_message.data(), error_message.size());\n #pragma GCC diagnostic warning \"-Wunused-result\"\n _exit(EXIT_FAILURE);\n }\n\n if (unlikely(::progname == nullptr))\n _exit(EXIT_FAILURE);\n}\n\n\nDSVReader::DSVReader(const std::string &filename, const char field_separator, const char field_delimiter)\n : field_separator_(field_separator), field_delimiter_(field_delimiter), line_no_(0), filename_(filename)\n{\n input_ = std::fopen(filename.c_str(), \"rm\");\n if (input_ == nullptr)\n throw std::runtime_error(\"in DSVReader::DSVReader: can't open \\\"\" + filename + \"\\\" for reading!\");\n}\n\n\nDSVReader::~DSVReader() {\n if (input_ != nullptr)\n std::fclose(input_);\n}\n\n\nnamespace {\n\n\nvoid SkipFieldPadding(FILE * const input) {\n int ch = std::fgetc(input);\n while (isblank(ch))\n ch = std::fgetc(input);\n std::ungetc(ch, input);\n}\n\n\nstd::string ReadQuotedValue(FILE * const input, const char field_delimiter) {\n std::string value;\n bool delimiter_seen(false);\n for (;;) {\n const int ch(std::fgetc(input));\n if (ch == EOF)\n throw std::runtime_error(\"unexpected EOF while reading a quoted DSV value!\");\n if (ch == field_delimiter) {\n if (delimiter_seen) {\n value += static_cast<char>(ch);\n delimiter_seen = false;\n } else\n delimiter_seen = true;\n } else if (delimiter_seen) {\n std::ungetc(ch, input);\n return value;\n } else\n value += static_cast<char>(ch);\n }\n}\n\n\n\/** \\brief Remove trailing spaces and tabs from \"s\". *\/\nstd::string TrimBlanks(std::string * s) {\n std::string::const_reverse_iterator it(s->crbegin());\n for (\/* Empty! *\/; it != s->crend() and std::isblank(*it); ++it)\n \/* Intentionally Empty! *\/;\n if (it != s->crbegin())\n *s = s->substr(0, std::distance(it, s->crend()));\n\n return *s;\n}\n\n\nstd::string ReadNonQuotedValue(FILE * const input, const char field_separator) {\n std::string value;\n for (;;) {\n const int ch(std::fgetc(input));\n if (ch == EOF or ch == '\\n' or ch == field_separator) {\n std::ungetc(ch, input);\n return TrimBlanks(&value);\n }\n value += static_cast<char>(ch);\n }\n}\n\n\nvoid BacktraceSignalHandler(int signal_no) {\n void *stack_return_addresses[20];\n const size_t number_of_addresses(::backtrace(stack_return_addresses, DIM(stack_return_addresses)));\n char err_msg[1024] = \"Caught signal \";\n char *cp = err_msg + std::strlen(err_msg);\n if (signal_no > 10)\n *cp++ = '0' + (signal_no \/ 10);\n *cp++ = '0' + (signal_no % 10);\n *cp++ = '.';\n *cp++ = '\\n';\n *cp = '\\0';\n ssize_t unused(::write(STDERR_FILENO, err_msg, std::strlen(err_msg)));\n (void)unused;\n ::backtrace_symbols_fd(stack_return_addresses, number_of_addresses, STDERR_FILENO);\n ::_exit(EXIT_FAILURE);\n}\n\n\nint InstallSegvSignalHandler(void handler(int)) {\n ::signal(SIGSEGV, handler);\n return 0;\n}\n\n\nvolatile int dummy = InstallSegvSignalHandler(BacktraceSignalHandler);\n\n\n} \/\/ unnamed namespace\n\n\nbool DSVReader::readLine(std::vector<std::string> * const values) {\n values->clear();\n ++line_no_;\n\n int ch;\n for (;;) {\n if (not values->empty()) {\n SkipFieldPadding(input_);\n ch = std::fgetc(input_);\n if (ch == EOF)\n return false;\n if (ch == '\\n')\n return true;\n if (ch != field_separator_)\n throw std::runtime_error(\"in DSVReader::readLine: on line \" + std::to_string(line_no_)\n + \": field separator expected, found '\"\n + std::string(1, static_cast<char>(ch)) + \"' instead!\");\n }\n\n SkipFieldPadding(input_);\n ch = std::fgetc(input_);\n if (ch == '\\n')\n return true;\n if (ch == EOF)\n return false;\n if (ch == field_separator_) {\n std::ungetc(ch, input_);\n values->emplace_back(\"\");\n } else if (ch == field_delimiter_)\n values->emplace_back(ReadQuotedValue(input_, field_delimiter_));\n else {\n std::ungetc(ch, input_);\n values->emplace_back(ReadNonQuotedValue(input_, field_separator_));\n }\n }\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"dataraptor.h\"\n#include \"routing.h\"\nnamespace navitia { namespace routing { namespace raptor {\n\nvoid dataRAPTOR::load(const type::PT_Data &data)\n{\n retour_constant.resize(data.stop_points.size());\n retour_constant_reverse.resize(data.stop_points.size());\n\n for(auto &r : retour_constant_reverse) {\n r.dt = DateTime::min;\n }\n\n for(auto &r : retour_constant) {\n r.dt = DateTime::inf;\n }\n \/\/Construction de la liste des marche à pied à partir des connections renseignées\n\n std::vector<list_connections> footpath_temp;\n footpath_temp.resize(data.stop_points.size());\n for(navitia::type::Connection connection : data.connections) {\n footpath_temp[connection.departure_stop_point_idx][connection.destination_stop_point_idx] = connection;\n navitia::type::Connection inverse;\n inverse.departure_stop_point_idx = connection.destination_stop_point_idx;\n inverse.destination_stop_point_idx = connection.departure_stop_point_idx;\n inverse.duration = connection.duration;\n footpath_temp[connection.destination_stop_point_idx][connection.departure_stop_point_idx] = inverse;\n }\n\n \/\/On rajoute des connexions entre les stops points d'un même stop area si elles n'existent pas\n footpath_index.resize(data.stop_points.size());\n footpath_index.resize(data.stop_points.size());\n for(navitia::type::StopPoint sp : data.stop_points) {\n navitia::type::StopArea sa = data.stop_areas[sp.stop_area_idx];\n footpath_index[sp.idx].first = foot_path.size();\n\n int size = 0;\n for(auto conn : footpath_temp[sp.idx]) {\n foot_path.push_back(conn.second);\n ++size;\n }\n\n for(navitia::type::idx_t spidx : sa.stop_point_list) {\n navitia::type::StopPoint sp2 = data.stop_points[spidx];\n if(sp.idx != sp2.idx) {\n if(footpath_temp[sp.idx].find(sp2.idx) == footpath_temp[sp.idx].end()) {\n navitia::type::Connection c;\n c.departure_stop_point_idx = sp.idx;\n c.destination_stop_point_idx = sp2.idx;\n c.duration = 2 * 60;\n foot_path.push_back(c);\n ++size;\n }\n }\n }\n footpath_index[sp.idx].second = size;\n }\n\n\n\n\n typedef std::unordered_map<navitia::type::idx_t, vector_idx> idx_vector_idx;\n idx_vector_idx ridx_route;\n for(auto & route : data.routes) {\n ridx_route[route.idx] = vector_idx();\n if(route.route_point_list.size() > 0) {\n idx_vector_idx vp_vj;\n \/\/Je regroupe entre elles les routes ayant le même validity pattern\n for(navitia::type::idx_t vjidx : route.vehicle_journey_list) {\n if(vp_vj.find(data.vehicle_journeys[vjidx].validity_pattern_idx) == vp_vj.end())\n vp_vj[data.vehicle_journeys[vjidx].validity_pattern_idx] = vector_idx();\n vp_vj[data.vehicle_journeys[vjidx].validity_pattern_idx].push_back(vjidx);\n }\n\n for(idx_vector_idx::value_type vec : vp_vj) {\n if(vec.second.size() > 0) {\n Route_t r;\n r.idx = route.idx;\n r.nbStops = route.route_point_list.size();\n r.nbTrips = vec.second.size();\n r.vp = data.validity_patterns[vec.first].idx;\n r.firstStopTime = stopTimes.size();\n for(auto vjidx : vec.second) {\n for(navitia::type::idx_t stidx : data.vehicle_journeys[vjidx].stop_time_list) {\n StopTime_t st = data.stop_times[stidx];\n stopTimes.push_back(st);\n }\n }\n ridx_route[route.idx].push_back(routes.size());\n routes.push_back(r);\n }\n }\n }\n }\n\n sp_indexrouteorder.resize(data.stop_points.size());\n sp_indexrouteorder_reverse.resize(data.stop_points.size());\n for(auto &sp : data.stop_points) {\n pair_int temp_index, temp_index_reverse;\n temp_index.first = sp_routeorder_const.size();\n temp_index_reverse.first = sp_routeorder_const_reverse.size();\n std::map<navitia::type::idx_t, int> temp, temp_reverse;\n for(navitia::type::idx_t idx_rp : sp.route_point_list) {\n auto &rp = data.route_points[idx_rp];\n for(auto rid : ridx_route[rp.route_idx]) {\n auto it = temp.find(rid), it_reverse = temp_reverse.find(rid);\n if(it == temp.end()) {\n temp[rid] = rp.order;\n } else if(temp[rp.route_idx] > rp.order) {\n temp[rid] = rp.order;\n }\n\n if(it_reverse == temp_reverse.end()) {\n temp_reverse[rid] = rp.order;\n } else if(temp_reverse[rp.route_idx] < rp.order) {\n temp_reverse[rid] = rp.order;\n }\n }\n\n }\n\n for(auto it : temp) {\n sp_routeorder_const.push_back(it);\n }\n\n for(auto it : temp_reverse) {\n sp_routeorder_const_reverse.push_back(it);\n }\n\n temp_index.second = sp_routeorder_const.size() - temp_index.first;\n temp_index_reverse.second = sp_routeorder_const_reverse.size() - temp_index_reverse.first;\n sp_indexrouteorder[sp.idx] = temp_index;\n sp_indexrouteorder_reverse[sp.idx] = temp_index_reverse;\n }\n\n\n std::cout << \"Nb data stop times : \" << data.stop_times.size() << \" stopTimes : \" << stopTimes.size()\n << \" nb foot path : \" << foot_path.size() << \" Nombre de stop points : \" << data.stop_points.size() << \"nb vp : \" << data.validity_patterns.size() << \" nb routes \" << routes.size() << std::endl;\n\n}\n\n\n}}}\n<commit_msg>dataraptor : On trie les routes par vp dans sp route order<commit_after>#include \"dataraptor.h\"\n#include \"routing.h\"\nnamespace navitia { namespace routing { namespace raptor {\n\nvoid dataRAPTOR::load(const type::PT_Data &data)\n{\n retour_constant.resize(data.stop_points.size());\n retour_constant_reverse.resize(data.stop_points.size());\n\n for(auto &r : retour_constant_reverse) {\n r.dt = DateTime::min;\n }\n\n for(auto &r : retour_constant) {\n r.dt = DateTime::inf;\n }\n \/\/Construction de la liste des marche à pied à partir des connections renseignées\n\n std::vector<list_connections> footpath_temp;\n footpath_temp.resize(data.stop_points.size());\n for(navitia::type::Connection connection : data.connections) {\n footpath_temp[connection.departure_stop_point_idx][connection.destination_stop_point_idx] = connection;\n navitia::type::Connection inverse;\n inverse.departure_stop_point_idx = connection.destination_stop_point_idx;\n inverse.destination_stop_point_idx = connection.departure_stop_point_idx;\n inverse.duration = connection.duration;\n footpath_temp[connection.destination_stop_point_idx][connection.departure_stop_point_idx] = inverse;\n }\n\n \/\/On rajoute des connexions entre les stops points d'un même stop area si elles n'existent pas\n footpath_index.resize(data.stop_points.size());\n footpath_index.resize(data.stop_points.size());\n for(navitia::type::StopPoint sp : data.stop_points) {\n navitia::type::StopArea sa = data.stop_areas[sp.stop_area_idx];\n footpath_index[sp.idx].first = foot_path.size();\n\n int size = 0;\n for(auto conn : footpath_temp[sp.idx]) {\n foot_path.push_back(conn.second);\n ++size;\n }\n\n for(navitia::type::idx_t spidx : sa.stop_point_list) {\n navitia::type::StopPoint sp2 = data.stop_points[spidx];\n if(sp.idx != sp2.idx) {\n if(footpath_temp[sp.idx].find(sp2.idx) == footpath_temp[sp.idx].end()) {\n navitia::type::Connection c;\n c.departure_stop_point_idx = sp.idx;\n c.destination_stop_point_idx = sp2.idx;\n c.duration = 2 * 60;\n foot_path.push_back(c);\n ++size;\n }\n }\n }\n footpath_index[sp.idx].second = size;\n }\n\n\n\n\n typedef std::unordered_map<navitia::type::idx_t, vector_idx> idx_vector_idx;\n idx_vector_idx ridx_route;\n for(auto & route : data.routes) {\n ridx_route[route.idx] = vector_idx();\n if(route.route_point_list.size() > 0) {\n idx_vector_idx vp_vj;\n \/\/Je regroupe entre elles les routes ayant le même validity pattern\n for(navitia::type::idx_t vjidx : route.vehicle_journey_list) {\n if(vp_vj.find(data.vehicle_journeys[vjidx].validity_pattern_idx) == vp_vj.end())\n vp_vj[data.vehicle_journeys[vjidx].validity_pattern_idx] = vector_idx();\n vp_vj[data.vehicle_journeys[vjidx].validity_pattern_idx].push_back(vjidx);\n }\n\n for(idx_vector_idx::value_type vec : vp_vj) {\n if(vec.second.size() > 0) {\n Route_t r;\n r.idx = route.idx;\n r.nbStops = route.route_point_list.size();\n r.nbTrips = vec.second.size();\n r.vp = data.validity_patterns[vec.first].idx;\n r.firstStopTime = stopTimes.size();\n for(auto vjidx : vec.second) {\n for(navitia::type::idx_t stidx : data.vehicle_journeys[vjidx].stop_time_list) {\n StopTime_t st = data.stop_times[stidx];\n stopTimes.push_back(st);\n }\n }\n ridx_route[route.idx].push_back(routes.size());\n routes.push_back(r);\n }\n }\n }\n }\n\n sp_indexrouteorder.resize(data.stop_points.size());\n sp_indexrouteorder_reverse.resize(data.stop_points.size());\n for(auto &sp : data.stop_points) {\n pair_int temp_index, temp_index_reverse;\n temp_index.first = sp_routeorder_const.size();\n temp_index_reverse.first = sp_routeorder_const_reverse.size();\n std::map<navitia::type::idx_t, int> temp, temp_reverse;\n for(navitia::type::idx_t idx_rp : sp.route_point_list) {\n auto &rp = data.route_points[idx_rp];\n for(auto rid : ridx_route[rp.route_idx]) {\n auto it = temp.find(rid), it_reverse = temp_reverse.find(rid);\n if(it == temp.end()) {\n temp[rid] = rp.order;\n } else if(temp[rp.route_idx] > rp.order) {\n temp[rid] = rp.order;\n }\n\n if(it_reverse == temp_reverse.end()) {\n temp_reverse[rid] = rp.order;\n } else if(temp_reverse[rp.route_idx] < rp.order) {\n temp_reverse[rid] = rp.order;\n }\n }\n\n }\n\n std::vector<pair_int> tmp;\n for(auto it : temp) {\n tmp.push_back(it);\n }\n std::sort(tmp.begin(), tmp.end(), [&](pair_int p1, pair_int p2){return routes[p1.first].vp < routes[p2.first].vp;});\n sp_routeorder_const.insert(sp_routeorder_const.end(), tmp.begin(), tmp.end());\n\n\n tmp.clear();\n\n for(auto it : temp_reverse) {\n tmp.push_back(it);\n }\n std::sort(tmp.begin(), tmp.end(), [&](pair_int p1, pair_int p2){return routes[p1.first].vp < routes[p2.first].vp;});\n sp_routeorder_const_reverse.insert(sp_routeorder_const_reverse.end(), tmp.begin(), tmp.end());\n\n temp_index.second = sp_routeorder_const.size() - temp_index.first;\n temp_index_reverse.second = sp_routeorder_const_reverse.size() - temp_index_reverse.first;\n sp_indexrouteorder[sp.idx] = temp_index;\n sp_indexrouteorder_reverse[sp.idx] = temp_index_reverse;\n }\n\n\n std::cout << \"Nb data stop times : \" << data.stop_times.size() << \" stopTimes : \" << stopTimes.size()\n << \" nb foot path : \" << foot_path.size() << \" Nombre de stop points : \" << data.stop_points.size() << \"nb vp : \" << data.validity_patterns.size() << \" nb routes \" << routes.size() << std::endl;\n\n}\n\n\n}}}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2014, German Neuroinformatics Node (G-Node)\n\/\/\n\/\/ All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted under the terms of the BSD License. See\n\/\/ LICENSE source in the root of the Project.\n\n#include <boost\/python.hpp>\n#include <boost\/optional.hpp>\n\n#include <nix.hpp>\n\n#include <accessors.hpp>\n#include <transmorgify.hpp>\n\n\/\/we want only the newest and freshest API\n#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION\n\n#include <numpy\/arrayobject.h>\n#include <numpy\/ndarrayobject.h>\n\n#include <PyEntity.hpp>\n\n#include <stdexcept>\n\nusing namespace nix;\nusing namespace boost::python;\n\nnamespace nixpy {\n\n\/\/ Label\n\nvoid setLabel(DataArray& da, const boost::optional<std::string>& label) {\n if (label)\n da.label(*label);\n else\n da.label(boost::none);\n}\n\n\/\/ Unit\n\nvoid setUnit(DataArray& da, const boost::optional<std::string> &unit) {\n if (unit)\n da.unit(*unit);\n else\n da.unit(boost::none);\n}\n\n\/\/ Expansion origin\n\nvoid setExpansionOrigin(DataArray& da, const boost::optional<double>& eo) {\n if (eo)\n da.expansionOrigin(*eo);\n else\n da.expansionOrigin(boost::none);\n}\n\n\/\/ Polynom coefficients\n\nvoid setPolynomCoefficients(DataArray& da, const std::vector<double>& pc) {\n if (!pc.empty())\n da.polynomCoefficients(pc);\n else\n da.polynomCoefficients(boost::none);\n}\n\n\/\/ Data\n\nstatic nix::DataType py_dtype_to_nix_dtype(const PyArray_Descr *dtype)\n{\n if (dtype == nullptr) {\n return nix::DataType::Nothing;\n }\n\n if (dtype->byteorder != '=' && dtype->byteorder != '|') {\n \/\/TODO: Handle case where specified byteorder *is*\n \/\/the native byteorder (via BOOST_BIG_ENDIAN macros)\n return nix::DataType::Nothing;\n }\n\n switch (dtype->kind) {\n\n case 'u':\n switch (dtype->elsize) {\n case 1: return nix::DataType::UInt8;\n case 2: return nix::DataType::UInt16;\n case 4: return nix::DataType::UInt32;\n case 8: return nix::DataType::UInt64;\n }\n break;\n\n case 'i':\n switch (dtype->elsize) {\n case 1: return nix::DataType::Int8;\n case 2: return nix::DataType::Int16;\n case 4: return nix::DataType::Int32;\n case 8: return nix::DataType::Int64;\n }\n break;\n\n case 'f':\n switch (dtype->elsize) {\n case 4: return nix::DataType::Float;\n case 8: return nix::DataType::Double;\n }\n break;\n\n default:\n break;\n }\n return nix::DataType::Nothing;\n}\n\nstatic nix::DataType array_desc_as_dtype(PyArrayObject *array) {\n nix::DataType nix_dtype = py_dtype_to_nix_dtype(PyArray_DESCR(array));\n\n if (nix_dtype == nix::DataType::Nothing) {\n throw std::invalid_argument(\"Unsupported dtype for data\");\n }\n\n return nix_dtype;\n}\n\nstatic PyArrayObject *make_array(PyObject *data, int requirements) {\n if (! PyArray_Check(data)) {\n throw std::invalid_argument(\"Data not a NumPy array\");\n }\n\n PyArrayObject *array = reinterpret_cast<PyArrayObject *>(data);\n\n if (! PyArray_CHKFLAGS(array, requirements)) {\n throw std::invalid_argument(\"data must be c-contiguous and aligned\");\n }\n\n return array;\n}\n\nstatic NDSize array_shape_as_ndsize(PyArrayObject *array) {\n int array_rank = PyArray_NDIM(array);\n npy_intp *array_shape = PyArray_SHAPE(array);\n\n nix::NDSize data_shape(array_rank);\n for (int i = 0; i < array_rank; i++) {\n data_shape[i] = array_shape[i];\n }\n\n return data_shape;\n}\n\n\nstatic void readData(DataArray& da, PyObject *data) {\n\n PyArrayObject *array = make_array(data, NPY_ARRAY_CARRAY);\n\n nix::DataType nix_dtype = array_desc_as_dtype(array);\n nix::NDSize data_shape = array_shape_as_ndsize(array);\n nix::NDSize offset(data_shape.size(), 0);\n\n da.getData(nix_dtype, PyArray_DATA(array), data_shape, offset);\n}\n\n\nstatic void writeData(DataArray& da, PyObject *data) {\n\n PyArrayObject *array = make_array(data, NPY_ARRAY_CARRAY_RO);\n\n nix::DataType nix_dtype = array_desc_as_dtype(array);\n nix::NDSize data_shape = array_shape_as_ndsize(array);\n nix::NDSize offset(data_shape.size(), 0);\n\n da.setData(nix_dtype, PyArray_DATA(array), data_shape, offset);\n}\n\n\nstatic void createData(DataArray& da, const NDSize &shape, PyObject *dtype_obj, PyObject *data) {\n PyArray_Descr* py_dtype = nullptr;\n\n if (! PyArray_DescrConverter(dtype_obj, &py_dtype)) {\n throw std::invalid_argument(\"Invalid dtype\");\n }\n\n nix::DataType nix_dtype = py_dtype_to_nix_dtype(py_dtype);\n if (nix_dtype == nix::DataType::Nothing) {\n throw std::invalid_argument(\"Unsupported dtype\");\n }\n\n da.createData(nix_dtype, shape);\n\n if (data != Py_None) {\n writeData(da, data);\n }\n\n Py_DECREF(py_dtype);\n}\n\n\/\/ Dimensions\n\nPyObject* getDimension(const DataArray& da, size_t index) {\n Dimension dim = da.getDimension(index);\n SetDimension set;\n RangeDimension range;\n SampledDimension sample;\n DimensionType type = dim.dimensionType();\n\n switch(type) {\n case DimensionType::Set:\n set = dim;\n return incref(object(set).ptr());\n case DimensionType::Range:\n range = dim;\n return incref(object(range).ptr());\n case DimensionType::Sample:\n sample = dim;\n return incref(object(sample).ptr());\n default:\n Py_RETURN_NONE;\n }\n}\n\nvoid PyDataArray::do_export() {\n\n \/\/ For numpy to work\n import_array();\n\n PyEntityWithSources<base::IDataArray>::do_export(\"DataArray\");\n class_<DataArray, bases<base::EntityWithSources<base::IDataArray>>>(\"DataArray\")\n .add_property(\"label\",\n OPT_GETTER(std::string, DataArray, label),\n setLabel,\n doc::data_array_label)\n .add_property(\"unit\",\n OPT_GETTER(std::string, DataArray, unit),\n setUnit,\n doc::data_array_unit)\n .add_property(\"expansion_origin\",\n OPT_GETTER(double, DataArray, expansionOrigin),\n setExpansionOrigin,\n doc::data_array_expansion_origin)\n .add_property(\"polynom_coefficients\",\n GETTER(std::vector<double>, DataArray, polynomCoefficients),\n setPolynomCoefficients,\n doc::data_array_polynom_coefficients)\n .add_property(\"data_extent\",\n GETTER(NDSize, DataArray, dataExtent),\n SETTER(NDSize&, DataArray, dataExtent),\n doc::data_array_data_extent)\n \/\/ Data\n .add_property(\"data_type\", &DataArray::dataType,\n doc::data_array_data_type)\n .def(\"has_data\", &DataArray::hasData,\n doc::data_array_has_data)\n\n .def(\"_create_data\", createData)\n .def(\"_write_data\", writeData)\n .def(\"_read_data\", readData)\n\n \/\/ Dimensions\n .def(\"create_set_dimension\", &DataArray::createSetDimension,\n doc::data_array_create_set_dimension)\n .def(\"create_sampled_dimension\", &DataArray::createSampledDimension,\n doc::data_array_create_sampled_dimension)\n .def(\"create_reange_dimension\", &DataArray::createRangeDimension,\n doc::data_array_create_range_dimension)\n .def(\"append_set_dimension\", &DataArray::appendSetDimension,\n doc::data_array_append_set_dimension)\n .def(\"append_sampled_dimension\", &DataArray::appendSampledDimension,\n doc::data_array_append_sampled_dimension)\n .def(\"append_range_dimension\", &DataArray::appendRangeDimension,\n doc::data_array_append_range_dimension)\n .def(\"_dimension_count\", &DataArray::dimensionCount)\n .def(\"_delete_dimension_by_pos\", &DataArray::deleteDimension)\n .def(\"_get_dimension_by_pos\", getDimension)\n \/\/ Other\n .def(\"__str__\", &toStr<DataArray>)\n .def(\"__repr__\", &toStr<DataArray>)\n ;\n\n to_python_converter<std::vector<DataArray>, vector_transmogrify<DataArray>>();\n vector_transmogrify<DataArray>::register_from_python();\n\n to_python_converter<boost::optional<DataArray>, option_transmogrify<DataArray>>();\n option_transmogrify<DataArray>::register_from_python();\n}\n\n}\n<commit_msg>PyDataArray: Add DataType -> numpy.dtype str conversion fn<commit_after>\/\/ Copyright (c) 2014, German Neuroinformatics Node (G-Node)\n\/\/\n\/\/ All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted under the terms of the BSD License. See\n\/\/ LICENSE source in the root of the Project.\n\n#include <boost\/python.hpp>\n#include <boost\/optional.hpp>\n\n#include <nix.hpp>\n\n#include <accessors.hpp>\n#include <transmorgify.hpp>\n\n\/\/we want only the newest and freshest API\n#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION\n\n#include <numpy\/arrayobject.h>\n#include <numpy\/ndarrayobject.h>\n\n#include <PyEntity.hpp>\n\n#include <stdexcept>\n\nusing namespace nix;\nusing namespace boost::python;\n\nnamespace nixpy {\n\n\/\/ Label\n\nvoid setLabel(DataArray& da, const boost::optional<std::string>& label) {\n if (label)\n da.label(*label);\n else\n da.label(boost::none);\n}\n\n\/\/ Unit\n\nvoid setUnit(DataArray& da, const boost::optional<std::string> &unit) {\n if (unit)\n da.unit(*unit);\n else\n da.unit(boost::none);\n}\n\n\/\/ Expansion origin\n\nvoid setExpansionOrigin(DataArray& da, const boost::optional<double>& eo) {\n if (eo)\n da.expansionOrigin(*eo);\n else\n da.expansionOrigin(boost::none);\n}\n\n\/\/ Polynom coefficients\n\nvoid setPolynomCoefficients(DataArray& da, const std::vector<double>& pc) {\n if (!pc.empty())\n da.polynomCoefficients(pc);\n else\n da.polynomCoefficients(boost::none);\n}\n\n\/\/ Data\n\nstatic nix::DataType py_dtype_to_nix_dtype(const PyArray_Descr *dtype)\n{\n if (dtype == nullptr) {\n return nix::DataType::Nothing;\n }\n\n if (dtype->byteorder != '=' && dtype->byteorder != '|') {\n \/\/TODO: Handle case where specified byteorder *is*\n \/\/the native byteorder (via BOOST_BIG_ENDIAN macros)\n return nix::DataType::Nothing;\n }\n\n switch (dtype->kind) {\n\n case 'u':\n switch (dtype->elsize) {\n case 1: return nix::DataType::UInt8;\n case 2: return nix::DataType::UInt16;\n case 4: return nix::DataType::UInt32;\n case 8: return nix::DataType::UInt64;\n }\n break;\n\n case 'i':\n switch (dtype->elsize) {\n case 1: return nix::DataType::Int8;\n case 2: return nix::DataType::Int16;\n case 4: return nix::DataType::Int32;\n case 8: return nix::DataType::Int64;\n }\n break;\n\n case 'f':\n switch (dtype->elsize) {\n case 4: return nix::DataType::Float;\n case 8: return nix::DataType::Double;\n }\n break;\n\n default:\n break;\n }\n return nix::DataType::Nothing;\n}\n\nstatic std::string nix_dtype_to_py_dtype_str(nix::DataType nix_dtype)\n{\n switch (nix_dtype) {\n case nix::DataType::UInt8: return \"<u1\";\n case nix::DataType::UInt16: return \"<u2\";\n case nix::DataType::UInt32: return \"<u4\";\n case nix::DataType::UInt64: return \"<u8\";\n case nix::DataType::Int8: return \"<i1\";\n case nix::DataType::Int16: return \"<i2\";\n case nix::DataType::Int32: return \"<i4\";\n case nix::DataType::Int64: return \"<i8\";\n case nix::DataType::Float: return \"<f4\";\n case nix::DataType::Double: return \"<f8\";\n default: return \"\";\n }\n}\n\nstatic nix::DataType array_desc_as_dtype(PyArrayObject *array) {\n nix::DataType nix_dtype = py_dtype_to_nix_dtype(PyArray_DESCR(array));\n\n if (nix_dtype == nix::DataType::Nothing) {\n throw std::invalid_argument(\"Unsupported dtype for data\");\n }\n\n return nix_dtype;\n}\n\nstatic PyArrayObject *make_array(PyObject *data, int requirements) {\n if (! PyArray_Check(data)) {\n throw std::invalid_argument(\"Data not a NumPy array\");\n }\n\n PyArrayObject *array = reinterpret_cast<PyArrayObject *>(data);\n\n if (! PyArray_CHKFLAGS(array, requirements)) {\n throw std::invalid_argument(\"data must be c-contiguous and aligned\");\n }\n\n return array;\n}\n\nstatic NDSize array_shape_as_ndsize(PyArrayObject *array) {\n int array_rank = PyArray_NDIM(array);\n npy_intp *array_shape = PyArray_SHAPE(array);\n\n nix::NDSize data_shape(array_rank);\n for (int i = 0; i < array_rank; i++) {\n data_shape[i] = array_shape[i];\n }\n\n return data_shape;\n}\n\n\nstatic void readData(DataArray& da, PyObject *data) {\n\n PyArrayObject *array = make_array(data, NPY_ARRAY_CARRAY);\n\n nix::DataType nix_dtype = array_desc_as_dtype(array);\n nix::NDSize data_shape = array_shape_as_ndsize(array);\n nix::NDSize offset(data_shape.size(), 0);\n\n da.getData(nix_dtype, PyArray_DATA(array), data_shape, offset);\n}\n\n\nstatic void writeData(DataArray& da, PyObject *data) {\n\n PyArrayObject *array = make_array(data, NPY_ARRAY_CARRAY_RO);\n\n nix::DataType nix_dtype = array_desc_as_dtype(array);\n nix::NDSize data_shape = array_shape_as_ndsize(array);\n nix::NDSize offset(data_shape.size(), 0);\n\n da.setData(nix_dtype, PyArray_DATA(array), data_shape, offset);\n}\n\n\nstatic void createData(DataArray& da, const NDSize &shape, PyObject *dtype_obj, PyObject *data) {\n PyArray_Descr* py_dtype = nullptr;\n\n if (! PyArray_DescrConverter(dtype_obj, &py_dtype)) {\n throw std::invalid_argument(\"Invalid dtype\");\n }\n\n nix::DataType nix_dtype = py_dtype_to_nix_dtype(py_dtype);\n if (nix_dtype == nix::DataType::Nothing) {\n throw std::invalid_argument(\"Unsupported dtype\");\n }\n\n da.createData(nix_dtype, shape);\n\n if (data != Py_None) {\n writeData(da, data);\n }\n\n Py_DECREF(py_dtype);\n}\n\n\/\/ Dimensions\n\nPyObject* getDimension(const DataArray& da, size_t index) {\n Dimension dim = da.getDimension(index);\n SetDimension set;\n RangeDimension range;\n SampledDimension sample;\n DimensionType type = dim.dimensionType();\n\n switch(type) {\n case DimensionType::Set:\n set = dim;\n return incref(object(set).ptr());\n case DimensionType::Range:\n range = dim;\n return incref(object(range).ptr());\n case DimensionType::Sample:\n sample = dim;\n return incref(object(sample).ptr());\n default:\n Py_RETURN_NONE;\n }\n}\n\nvoid PyDataArray::do_export() {\n\n \/\/ For numpy to work\n import_array();\n\n PyEntityWithSources<base::IDataArray>::do_export(\"DataArray\");\n class_<DataArray, bases<base::EntityWithSources<base::IDataArray>>>(\"DataArray\")\n .add_property(\"label\",\n OPT_GETTER(std::string, DataArray, label),\n setLabel,\n doc::data_array_label)\n .add_property(\"unit\",\n OPT_GETTER(std::string, DataArray, unit),\n setUnit,\n doc::data_array_unit)\n .add_property(\"expansion_origin\",\n OPT_GETTER(double, DataArray, expansionOrigin),\n setExpansionOrigin,\n doc::data_array_expansion_origin)\n .add_property(\"polynom_coefficients\",\n GETTER(std::vector<double>, DataArray, polynomCoefficients),\n setPolynomCoefficients,\n doc::data_array_polynom_coefficients)\n .add_property(\"data_extent\",\n GETTER(NDSize, DataArray, dataExtent),\n SETTER(NDSize&, DataArray, dataExtent),\n doc::data_array_data_extent)\n \/\/ Data\n .add_property(\"data_type\", &DataArray::dataType,\n doc::data_array_data_type)\n .def(\"has_data\", &DataArray::hasData,\n doc::data_array_has_data)\n\n .def(\"_create_data\", createData)\n .def(\"_write_data\", writeData)\n .def(\"_read_data\", readData)\n\n \/\/ Dimensions\n .def(\"create_set_dimension\", &DataArray::createSetDimension,\n doc::data_array_create_set_dimension)\n .def(\"create_sampled_dimension\", &DataArray::createSampledDimension,\n doc::data_array_create_sampled_dimension)\n .def(\"create_reange_dimension\", &DataArray::createRangeDimension,\n doc::data_array_create_range_dimension)\n .def(\"append_set_dimension\", &DataArray::appendSetDimension,\n doc::data_array_append_set_dimension)\n .def(\"append_sampled_dimension\", &DataArray::appendSampledDimension,\n doc::data_array_append_sampled_dimension)\n .def(\"append_range_dimension\", &DataArray::appendRangeDimension,\n doc::data_array_append_range_dimension)\n .def(\"_dimension_count\", &DataArray::dimensionCount)\n .def(\"_delete_dimension_by_pos\", &DataArray::deleteDimension)\n .def(\"_get_dimension_by_pos\", getDimension)\n \/\/ Other\n .def(\"__str__\", &toStr<DataArray>)\n .def(\"__repr__\", &toStr<DataArray>)\n ;\n\n to_python_converter<std::vector<DataArray>, vector_transmogrify<DataArray>>();\n vector_transmogrify<DataArray>::register_from_python();\n\n to_python_converter<boost::optional<DataArray>, option_transmogrify<DataArray>>();\n option_transmogrify<DataArray>::register_from_python();\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n#include <sstream>\n#include <fstream>\n#include <vector>\n#include <set>\n\n#include \"shingle.h\"\n#include \"word_idx.h\"\n#include \"parser.h\"\n\n#ifdef _OPENMP\n#include <omp.h>\n#endif\n\nusing namespace std;\n\nconst int WINDOW_SIZE = 300;\n\nstring output_filename_for_thread() {\n stringstream str;\n str << \"resemblance\";\n#ifdef _OPENMP\n str << \".\" << omp_get_thread_num();\n#endif\n str << \".out\";\n return str.str();\n}\n\nint main(int argc, char *argv[]) {\n\n const float min_resemblance = argc==1 ? 0 : atof(argv[1]);\n\n \/\/run_tests();\n\n \/\/ lookup from shingles to idx\n WordIdx word_idx;\n\n \/\/ list of shingles\n vector<Shingle*> shingles;\n\n \/\/ parse stdin\n Parser parser;\n parser.parse(shingles, word_idx);\n\n \/\/ build bit representation\n for (vector<Shingle*>::iterator iter=shingles.begin(); iter!=shingles.end(); ++iter)\n (*iter)->build_bit_representation(word_idx.max_idx());\n\n \/\/ convert from list back to array\n const int number_lines = shingles.size();\n Shingle **shingles_array = new Shingle*[number_lines];\n for (int i=0;i<number_lines;i++)\n shingles_array[i] = shingles[i];\n\n #pragma omp parallel num_threads(4)\n {\n\n ofstream file(output_filename_for_thread().c_str());\n\n for(int i=0;i<number_lines;i++) {\n\n int window_start = i+1;\n int window_finish = window_start + WINDOW_SIZE;\n if (window_finish > number_lines) window_finish = number_lines;\n\n \/\/ compare each pair output high resemblances\n #pragma omp for\n for (int j=window_start; j<window_finish; j++) {\n float resemblance = shingles_array[i]->resemblance_to(*shingles_array[j]);\n if (resemblance > min_resemblance)\n file << i << \" \" << j << \" \" << resemblance << endl;\n }\n }\n\n file.close();\n }\n}\n<commit_msg>move omp for pragma to outer loop and increase schedule size<commit_after>#include <iostream>\n#include <sstream>\n#include <fstream>\n#include <vector>\n#include <set>\n\n#include \"shingle.h\"\n#include \"word_idx.h\"\n#include \"parser.h\"\n\n#ifdef _OPENMP\n#include <omp.h>\n#endif\n\nusing namespace std;\n\nconst int WINDOW_SIZE = 300;\n\nstring output_filename_for_thread() {\n stringstream str;\n str << \"resemblance\";\n#ifdef _OPENMP\n str << \".\" << omp_get_thread_num();\n#endif\n str << \".out\";\n return str.str();\n}\n\nint main(int argc, char *argv[]) {\n\n const float min_resemblance = argc==1 ? 0 : atof(argv[1]);\n\n \/\/run_tests();\n\n \/\/ lookup from shingles to idx\n WordIdx word_idx;\n\n \/\/ list of shingles\n vector<Shingle*> shingles;\n\n \/\/ parse stdin\n Parser parser;\n parser.parse(shingles, word_idx);\n\n \/\/ build bit representation\n for (vector<Shingle*>::iterator iter=shingles.begin(); iter!=shingles.end(); ++iter)\n (*iter)->build_bit_representation(word_idx.max_idx());\n\n \/\/ convert from list back to array\n const int number_lines = shingles.size();\n Shingle **shingles_array = new Shingle*[number_lines];\n for (int i=0;i<number_lines;i++)\n shingles_array[i] = shingles[i];\n\n #pragma omp parallel num_threads(4)\n {\n\n ofstream file(output_filename_for_thread().c_str());\n\n #pragma omp for schedule(dynamic, 1000)\n for(int i=0;i<number_lines;i++) {\n\n int window_start = i+1;\n int window_finish = window_start + WINDOW_SIZE;\n if (window_finish > number_lines) window_finish = number_lines;\n\n \/\/ compare each pair output high resemblances\n for (int j=window_start; j<window_finish; j++) {\n float resemblance = shingles_array[i]->resemblance_to(*shingles_array[j]);\n if (resemblance > min_resemblance)\n file << i << \" \" << j << \" \" << resemblance << endl;\n }\n }\n\n file.close();\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/**\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n*\/\n\/*\n * encoder.hpp\n *\n\n#ifndef KAFKA_ENCODER_HPP_\n#define KAFKA_ENCODER_HPP_\n\n#include <boost\/foreach.hpp>\n#include \"encoder_helper.hpp\"\n\nnamespace kafkaconnect {\n\ntemplate <typename List>\nvoid encode(std::ostream& stream, const std::string& topic, const uint32_t partition, const List& messages)\n{\n\t\/\/ Pre-calculate size of message set\n\tuint32_t messageset_size = 0;\n\tBOOST_FOREACH(const std::string& message, messages)\n\t{\n\t\tmessageset_size += message_format_header_size + message.length();\n\t}\n\n\t\/\/ Packet format is ... packet size (4 bytes)\n\tencoder_helper::raw(stream, htonl(2 + 2 + topic.size() + 4 + 4 + messageset_size));\n\n\t\/\/ ... magic number (2 bytes)\n\tencoder_helper::raw(stream, htons(kafka_format_version));\n\n\t\/\/ ... topic string size (2 bytes) & topic string\n\tencoder_helper::raw(stream, htons(topic.size()));\n\tstream << topic;\n\n\t\/\/ ... partition (4 bytes)\n\tencoder_helper::raw(stream, htonl(partition));\n\n\t\/\/ ... message set size (4 bytes) and message set\n\tencoder_helper::raw(stream, htonl(messageset_size));\n\tBOOST_FOREACH(const std::string& message, messages)\n\t{\n\t\tencoder_helper::message(stream, message);\n\t}\n}\n\n}\n\n#endif \/* KAFKA_ENCODER_HPP_ *\/\n<commit_msg>Niek Sanders - KAFKA-284 fixed compilation issue for cpp client<commit_after>\/**\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n*\/\n\/*\n * encoder.hpp\n *\/\n\n#ifndef KAFKA_ENCODER_HPP_\n#define KAFKA_ENCODER_HPP_\n\n#include <boost\/foreach.hpp>\n#include \"encoder_helper.hpp\"\n\nnamespace kafkaconnect {\n\ntemplate <typename List>\nvoid encode(std::ostream& stream, const std::string& topic, const uint32_t partition, const List& messages)\n{\n\t\/\/ Pre-calculate size of message set\n\tuint32_t messageset_size = 0;\n\tBOOST_FOREACH(const std::string& message, messages)\n\t{\n\t\tmessageset_size += message_format_header_size + message.length();\n\t}\n\n\t\/\/ Packet format is ... packet size (4 bytes)\n\tencoder_helper::raw(stream, htonl(2 + 2 + topic.size() + 4 + 4 + messageset_size));\n\n\t\/\/ ... magic number (2 bytes)\n\tencoder_helper::raw(stream, htons(kafka_format_version));\n\n\t\/\/ ... topic string size (2 bytes) & topic string\n\tencoder_helper::raw(stream, htons(topic.size()));\n\tstream << topic;\n\n\t\/\/ ... partition (4 bytes)\n\tencoder_helper::raw(stream, htonl(partition));\n\n\t\/\/ ... message set size (4 bytes) and message set\n\tencoder_helper::raw(stream, htonl(messageset_size));\n\tBOOST_FOREACH(const std::string& message, messages)\n\t{\n\t\tencoder_helper::message(stream, message);\n\t}\n}\n\n}\n\n#endif \/* KAFKA_ENCODER_HPP_ *\/\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ Weasel Program, written in \"gone-full-retard\" C++14!\n\/\/\n\/\/ https:\/\/en.wikipedia.org\/wiki\/Weasel_program\n\/\/\n\/\/ The Weasel program is a thought experiment and a very rough simulation of\n\/\/ evolution, by starting with a random string of characters and gradually\n\/\/ \"evolving\" them into the text \"methinks it is like a weasel\".\n\/\/\n\/\/ The program can be easily modified to generate text that satisfies other\n\/\/ criteria, e.g. being a palindrome, thus not choosing one particular output.\n\/\/\n\/\/ The starting text is random and is mutated randomly (mutation) and it is\n\/\/ then scored for suitability (natural selection), resulting in a non-random\n\/\/ output (evolution).\n\/\/\n\n#include <algorithm>\n#include <chrono>\n#include <cstddef>\n#include <cstdlib>\n#include <functional>\n#include <iomanip>\n#include <iostream>\n#include <limits>\n#include <locale>\n#include <string>\n#include <random>\n#include <stdexcept>\n#include <string>\n#include <vector>\n\nnamespace\n{\n\n\/\/\/\n\/\/\/ @brief Global target string.\n\/\/\/ @todo Doesn't need to be in unnamed namespace: const's have static linkage.\n\/\/\/\nconst std::string methinks(\"methinks it is like a weasel\");\n\n\/\/\/\n\/\/\/ @brief Program modes.\n\/\/\/ @note Uncomment the one you want used, comment all the others.\n\/\/\/ @todo These should be strongly-typed `enum`s used together with a\n\/\/\/ \"static if\" mechanism, such as `if constexpr` in C++17.\n\/\/\/\n#define MODE_WEASEL\n\/\/#define MODE_PALINDROME\n\n\/\/\/\n\/\/\/ @brief Gives the suitability score of a candidate string.\n\/\/\/ @details A perfect score equals `0` (zero); the higher the worse.\n\/\/\/ @todo Use `if constexpr` instead of `#ifdef` once C++17 becomes available.\n\/\/\/ @note This function was designed to be general such that it can be modified\n\/\/\/ easily to score things other than resemblance to the \"weasel\" text, while\n\/\/\/ retaining the interface and usage: for example, it could score how good\n\/\/\/ a palindrome the `candidate` string is (as already implemented).\n\/\/\/ @param [in] candidate Candidate string.\n\/\/\/ @returns Suitability score.\n\/\/\/ @retval 0 Perfect score.\n\/\/\/\nstd::size_t score(const std::string &candidate)\ntry\n{\n#if defined MODE_WEASEL\n if (candidate.length() != methinks.length())\n return std::numeric_limits<std::size_t>::max();\n\n std::size_t r(methinks.length());\n\n for (std::size_t i(0); i < methinks.length(); ++i)\n if (candidate.at(i) == methinks.at(i))\n --r;\n\n return r;\n#elif defined MODE_PALINDROME\n auto ib (candidate.cbegin());\n const auto ie (candidate.cend());\n auto rib (candidate.crbegin());\n std::size_t r (candidate.length());\n\n for (; ib != ie; ++ib, ++rib)\n if (*ib == *rib)\n --r;\n\n return r;\n#endif\n}\ncatch (const std::out_of_range &e)\n{\n std::cerr << \"`std::out_of_range` exception in `\" << __func__ << \"`: \";\n std::cerr << e.what() << std::endl;\n throw;\n}\ncatch (...)\n{\n std::cerr << \"unknown exception in `\" << __func__ << '`' << std::endl;\n throw;\n}\n\n} \/\/ unnamed namespace\n\n\/\/\/\n\/\/\/ @brief Enters the program.\n\/\/\/ @returns Whether or not the operation was successful.\n\/\/\/ @retval EXIT_SUCCESS Operation success.\n\/\/\/ @retval EXIT_FAILURE Operation failure.\n\/\/\/\nint main()\ntry\n{\n \/\/ Number of Candidate strings in a Generation\n constexpr std::size_t num_cagen(100);\n\n std::size_t calen(0); \/\/ Candidate string Length\n\n#if defined MODE_WEASEL\n calen = methinks.length();\n#elif defined MODE_PALINDROME\n calen = 50;\n#endif\n\n \/\/\n \/\/ create a candidate string\n \/\/\n\n \/\/ Pseudo-Random Number Generator\n std::mt19937 prng(\n std::chrono::system_clock::now().time_since_epoch().count());\n\n \/\/ Random Character\n std::uniform_int_distribution<char> rand_char(\n std::numeric_limits<char>::min(),\n std::numeric_limits<char>::max());\n\n \/\/ Random chance to Mutate (0 == no, 1 == yes)\n std::discrete_distribution<unsigned long int> rand_mutate({\n 95.0, \/\/ 0\n 5.0}); \/\/ 1\n\n \/\/ Generate random Printable Character\n std::function<char (void)> gen_print_char =\n [&prng, &rand_char]() -> char\n {\n char c;\n\n do\n {\n c = rand_char(prng);\n }\n while (!std::isprint(c, std::locale::classic()));\n\n return c;\n };\n\n std::string candidate(calen, char(0)); \/\/ Candidate string\n\n std::generate(candidate.begin(), candidate.end(), gen_print_char);\n\n \/\/ the current Candidates Generation\n std::vector<std::string> cagen(num_cagen, candidate);\n\n \/\/ Value passed to `std::setw()` to prettify printing\n constexpr std::size_t val_setw(10);\n\n std::cout << std::setw(val_setw) << \"FIRST: \" << candidate << '\\n';\n\n std::size_t kgen(1); \/\/ Generation counter\n\n while (score(candidate) != 0)\n {\n for (std::string &ca: cagen)\n for (char &c: ca)\n if (rand_mutate(prng) != 0)\n c = gen_print_char();\n\n for (const std::string &ca: cagen)\n if (score(ca) < score(candidate))\n {\n candidate = ca;\n std::cout << std::setw(val_setw) << std::to_string(kgen) + \": \";\n std::cout << candidate << '\\n';\n }\n\n std::fill(cagen.begin(), cagen.end(), candidate);\n ++kgen;\n }\n\n std::cout << std::setw(val_setw) << \"LAST: \" << candidate << std::endl;\n return EXIT_SUCCESS;\n}\ncatch (const std::out_of_range &e)\n{\n std::cerr << \"`std::out_of_range` exception in `\" << __func__ << \"`: \";\n std::cerr << e.what() << std::endl;\n return EXIT_FAILURE;\n}\ncatch (...)\n{\n std::cerr << \"unknown exception in `\" << __func__ << '`' << std::endl;\n return EXIT_FAILURE;\n}\n<commit_msg>Update weasel.cpp<commit_after>\/\/\n\/\/ Weasel Program, written in \"gone-full-retard\" C++14!\n\/\/\n\/\/ https:\/\/en.wikipedia.org\/wiki\/Weasel_program\n\/\/\n\/\/ The Weasel program is a thought experiment and a very rough simulation of\n\/\/ evolution, by starting with a random string of characters and gradually\n\/\/ \"evolving\" them into the text \"methinks it is like a weasel\".\n\/\/\n\/\/ The program can be easily modified to generate text that satisfies other\n\/\/ criteria, e.g. being a palindrome, thus not choosing one particular output.\n\/\/\n\/\/ The starting text is random and is mutated randomly (mutation) and it is\n\/\/ then scored for suitability (natural selection), resulting in a non-random\n\/\/ output (evolution).\n\/\/\n\n#include <algorithm>\n#include <chrono>\n#include <cstddef>\n#include <cstdlib>\n#include <functional>\n#include <iomanip>\n#include <iostream>\n#include <limits>\n#include <locale>\n#include <random>\n#include <stdexcept>\n#include <string>\n#include <vector>\n\nnamespace\n{\n\n\/\/\/\n\/\/\/ @brief Global target string.\n\/\/\/ @todo Doesn't need to be in unnamed namespace: const's have static linkage.\n\/\/\/\nconst std::string methinks(\"methinks it is like a weasel\");\n\n\/\/\/\n\/\/\/ @brief Program modes.\n\/\/\/ @note Uncomment the one you want used, comment all the others.\n\/\/\/ @todo These should be strongly-typed `enum`s used together with a\n\/\/\/ \"static if\" mechanism, such as `if constexpr` in C++17.\n\/\/\/\n#define MODE_WEASEL\n\/\/#define MODE_PALINDROME\n\n\/\/\/\n\/\/\/ @brief Gives the suitability score of a candidate string.\n\/\/\/ @details A perfect score equals `0` (zero); the higher the worse.\n\/\/\/ @todo Use `if constexpr` instead of `#ifdef` once C++17 becomes available.\n\/\/\/ @note This function was designed to be general such that it can be modified\n\/\/\/ easily to score things other than resemblance to the \"weasel\" text, while\n\/\/\/ retaining the interface and usage: for example, it could score how good\n\/\/\/ a palindrome the `candidate` string is (as already implemented).\n\/\/\/ @param [in] candidate Candidate string.\n\/\/\/ @returns Suitability score.\n\/\/\/ @retval 0 Perfect score.\n\/\/\/\nstd::size_t score(const std::string &candidate)\ntry\n{\n#if defined MODE_WEASEL\n if (candidate.length() != methinks.length())\n return std::numeric_limits<std::size_t>::max();\n\n std::size_t r(methinks.length());\n\n for (std::size_t i(0); i < methinks.length(); ++i)\n if (candidate.at(i) == methinks.at(i))\n --r;\n\n return r;\n#elif defined MODE_PALINDROME\n auto ib (candidate.cbegin());\n const auto ie (candidate.cend());\n auto rib (candidate.crbegin());\n std::size_t r (candidate.length());\n\n for (; ib != ie; ++ib, ++rib)\n if (*ib == *rib)\n --r;\n\n return r;\n#endif\n}\ncatch (const std::out_of_range &e)\n{\n std::cerr << \"`std::out_of_range` exception in `\" << __func__ << \"`: \";\n std::cerr << e.what() << std::endl;\n throw;\n}\ncatch (...)\n{\n std::cerr << \"unknown exception in `\" << __func__ << '`' << std::endl;\n throw;\n}\n\n} \/\/ unnamed namespace\n\n\/\/\/\n\/\/\/ @brief Enters the program.\n\/\/\/ @returns Whether or not the operation was successful.\n\/\/\/ @retval EXIT_SUCCESS Operation success.\n\/\/\/ @retval EXIT_FAILURE Operation failure.\n\/\/\/\nint main()\ntry\n{\n \/\/ Number of Candidate strings in a Generation\n constexpr std::size_t num_cagen(100);\n\n std::size_t calen(0); \/\/ Candidate string Length\n\n#if defined MODE_WEASEL\n calen = methinks.length();\n#elif defined MODE_PALINDROME\n calen = 50;\n#endif\n\n \/\/\n \/\/ create a candidate string\n \/\/\n\n \/\/ Pseudo-Random Number Generator\n std::mt19937 prng(\n std::chrono::system_clock::now().time_since_epoch().count());\n\n \/\/ Random Character\n std::uniform_int_distribution<char> rand_char(\n std::numeric_limits<char>::min(),\n std::numeric_limits<char>::max());\n\n \/\/ Random chance to Mutate (0 == no, 1 == yes)\n std::discrete_distribution<unsigned long int> rand_mutate({\n 95.0, \/\/ 0\n 5.0}); \/\/ 1\n\n \/\/ Generate random Printable Character\n std::function<char (void)> gen_print_char =\n [&prng, &rand_char]() -> char\n {\n char c;\n\n do\n {\n c = rand_char(prng);\n }\n while (!std::isprint(c, std::locale::classic()));\n\n return c;\n };\n\n std::string candidate(calen, char(0)); \/\/ Candidate string\n\n std::generate(candidate.begin(), candidate.end(), gen_print_char);\n\n \/\/ the current Candidates Generation\n std::vector<std::string> cagen(num_cagen, candidate);\n\n \/\/ Value passed to `std::setw()` to prettify printing\n constexpr std::size_t val_setw(10);\n\n std::cout << std::setw(val_setw) << \"FIRST: \" << candidate << '\\n';\n\n std::size_t kgen(1); \/\/ Generation counter\n\n while (score(candidate) != 0)\n {\n for (std::string &ca: cagen)\n for (char &c: ca)\n if (rand_mutate(prng) != 0)\n c = gen_print_char();\n\n for (const std::string &ca: cagen)\n if (score(ca) < score(candidate))\n {\n candidate = ca;\n std::cout << std::setw(val_setw) << std::to_string(kgen) + \": \";\n std::cout << candidate << '\\n';\n }\n\n std::fill(cagen.begin(), cagen.end(), candidate);\n ++kgen;\n }\n\n std::cout << std::setw(val_setw) << \"LAST: \" << candidate << std::endl;\n return EXIT_SUCCESS;\n}\ncatch (const std::out_of_range &e)\n{\n std::cerr << \"`std::out_of_range` exception in `\" << __func__ << \"`: \";\n std::cerr << e.what() << std::endl;\n return EXIT_FAILURE;\n}\ncatch (...)\n{\n std::cerr << \"unknown exception in `\" << __func__ << '`' << std::endl;\n return EXIT_FAILURE;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"SRE\/Texture.hpp\"\n\n#include \"SRE\/impl\/GL.hpp\"\n#include <stdio.h>\n#include <SDL_surface.h>\n\n#include <SDL_image.h>\n#include <iostream>\n#include <vector>\n#include <fstream>\n#include <memory>\n\nnamespace {\n\tstatic std::vector<char> readAllBytes(char const* filename)\n\t{\n\t\tusing namespace std;\n\t\tifstream ifs(filename, std::ios::binary | std::ios::ate);\n\t\tifstream::pos_type pos = ifs.tellg();\n\t\tif (pos<0) {\n\t\t\tstd::cerr << \"Cannot read \" << filename << std::endl;\n\t\t\treturn std::vector<char>();\n\t\t}\n\t\tstd::vector<char> result((size_t)pos);\n\n\t\tifs.seekg(0, ios::beg);\n\t\tifs.read(&result[0], pos);\n\n\t\treturn result;\n\t}\n}\n\nnamespace SRE {\n\tTexture* Texture::whiteTexture = nullptr;\n\tTexture* Texture::sphereTexture = nullptr;\n\n\tTexture::Texture(const char *data, int width, int height, uint32_t format, bool generateMipmaps)\n\t\t: width{ width }, height{ height }, generateMipmap{ generateMipmaps } {\n\t\tglGenTextures(1, &textureId);\n\n\t\tGLenum target = GL_TEXTURE_2D;\n\t\tGLint mipmapLevel = 0;\n\t\tGLint internalFormat = GL_RGBA;\n\t\tGLint border = 0;\n\t\tGLenum type = GL_UNSIGNED_BYTE;\n\t\tglBindTexture(target, textureId);\n\t\tglTexImage2D(target, mipmapLevel, internalFormat, width, height, border, format, type, data);\n\t\tupdateTextureSampler();\n\t\tif (generateMipmaps) {\n\t\t\tglGenerateMipmap(GL_TEXTURE_2D);\n\t\t}\n\t}\n\n\tGLenum getFormat(SDL_Surface *image) {\n\t\tSDL_PixelFormat *format = image->format;\n\t\tauto pixelFormat = format->format;\n\t\tbool isBGR = format->Rshift == 16;\n\n#ifdef EMSCRIPTEN\n GLenum RGB = GL_RGB;\n GLenum RGBA = GL_RGBA;\n#else\n GLenum RGB = isBGR ? GL_BGR : GL_RGB;\n GLenum RGBA = isBGR ? GL_BGRA : GL_RGBA;\n#endif\n\t\tconst bool alpha = SDL_ISPIXELFORMAT_ALPHA(pixelFormat);\n\t\tif (alpha) {\n\t\t\treturn RGBA;\n\t\t}\n\t\telse {\n\t\t\tif (format->BytesPerPixel == 4) {\n\t\t\t\treturn RGBA;\n\t\t\t}\n\t\t\telse if (format->BytesPerPixel == 3) {\n\t\t\t\treturn RGB;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tSDL_SetError(\"Unknown image format. Only PNG-24 and JPEG is supported.\");\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t}\n\t}\n\n\tint invert_image(int width, int height, void *image_pixels) {\n\t\tauto temp_row = std::unique_ptr<char>(new char[width]);\n\t\tif (temp_row.get() == nullptr) {\n\t\t\tSDL_SetError(\"Not enough memory for image inversion\");\n\t\t\treturn -1;\n\t\t}\n\t\t\/\/if height is odd, don't need to swap middle row\n\t\tint height_div_2 = height \/ 2;\n\t\tfor (int index = 0; index < height_div_2; index++) {\n\t\t\t\/\/uses string.h\n\t\t\tmemcpy((Uint8 *)temp_row.get(),\n\t\t\t\t(Uint8 *)(image_pixels)+\n\t\t\t\twidth * index,\n\t\t\t\twidth);\n\n\t\t\tmemcpy(\n\t\t\t\t(Uint8 *)(image_pixels)+\n\t\t\t\twidth * index,\n\t\t\t\t(Uint8 *)(image_pixels)+\n\t\t\t\twidth * (height - index - 1),\n\t\t\t\twidth);\n\t\t\tmemcpy(\n\t\t\t\t(Uint8 *)(image_pixels)+\n\t\t\t\twidth * (height - index - 1),\n\t\t\t\ttemp_row.get(),\n\t\t\t\twidth);\n\t\t}\n\t\treturn 0;\n\t}\n\n\tbool isPowerOfTwo(unsigned int x) {\n\t\treturn ((x != 0) && !(x & (x - 1)));\n\t}\n\n\tTexture* Texture::createFromFile(const char *pngOrJpeg, bool generateMipmaps) {\n\t\tauto data = readAllBytes(pngOrJpeg);\n\t\treturn createFromMem(data.data(), data.size(), generateMipmaps);\n\t}\n\n\tTexture *Texture::createFromMem(const char *pngOrJpeg, int size, bool generateMipmaps) {\n\t\tstatic bool initialized = false;\n\t\tif (!initialized) {\n\t\t\tinitialized = true;\n\t\t\tint flags = IMG_INIT_PNG | IMG_INIT_JPG;\n\t\t\tint initted = IMG_Init(flags);\n\t\t\tif ((initted & flags) != flags) {\n\t\t\t\tstd::cerr << \"IMG_Init: Failed to init required jpg and png support!\" << std::endl;\n\t\t\t\tstd::cerr << \"IMG_Init: \" << IMG_GetError() << std::endl;\n\t\t\t\t\/\/ handle error\n\t\t\t}\n\t\t}\n\n\t\tSDL_RWops *source = SDL_RWFromConstMem(pngOrJpeg, size);\n\t\tSDL_Surface *res_texture = IMG_Load_RW(source, 1);\n\t\tif (res_texture == NULL) {\n\t\t\tstd::cerr << \"IMG_Load: \" << SDL_GetError() << std::endl;\n\t\t\treturn nullptr;\n\t\t}\n\t\tint w = res_texture->w;\n\t\tint h = res_texture->h;\n\t\tauto format = getFormat(res_texture);\n\n\t\tint bytesPerPixel = format == GL_BGR || format == GL_RGB ? 3 : 4;\n\t\tchar *pixels = static_cast<char *>(res_texture->pixels);\n\t\tinvert_image(w*bytesPerPixel, h, pixels);\n\t\tif (generateMipmaps && (!isPowerOfTwo((unsigned int)w) || !isPowerOfTwo((unsigned int)h))) {\n\t\t\tstd::cerr << \"Ignore mipmaps for textures not power of two\" << std::endl;\n\t\t\tgenerateMipmaps = false;\n\t\t}\n\t\tTexture *res = new Texture(pixels, w, h, format, generateMipmaps);\n\t\tSDL_FreeSurface(res_texture);\n\t\treturn res;\n\t}\n\n\tTexture *Texture::createFromRGBAMem(const char *data, int width, int height, bool generateMipmaps) {\n\t\treturn new Texture(data, width, height, GL_RGBA, generateMipmaps);\n\t}\n\n\t\/\/ returns true if texture sampling should be filtered (bi-linear or tri-linear sampling) otherwise use point sampling.\n\tbool Texture::isFilterSampling() {\n\t\treturn filterSampling;\n\t}\n\n\t\/\/ if true texture sampling is filtered (bi-linear or tri-linear sampling) otherwise use point sampling.\n\tvoid Texture::setFilterSampling(bool enable) {\n\t\tfilterSampling = enable;\n\t\tupdateTextureSampler();\n\t}\n\n\tbool Texture::isWrapTextureCoordinates() {\n\t\treturn filterSampling;\n\t}\n\n\tvoid Texture::setWrapTextureCoordinates(bool enable) {\n\t\twrapTextureCoordinates = enable;\n\t\tupdateTextureSampler();\n\t}\n\n\tint Texture::getWidth() {\n\t\treturn width;\n\t}\n\n\tint Texture::getHeight() {\n\t\treturn height;\n\t}\n\n\tvoid Texture::updateTextureSampler() {\n\t\tglBindTexture(GL_TEXTURE_2D, textureId);\n\t\tglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, wrapTextureCoordinates ? GL_REPEAT : GL_CLAMP_TO_EDGE);\n\t\tglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, wrapTextureCoordinates ? GL_REPEAT : GL_CLAMP_TO_EDGE);\n\t\tGLuint minification;\n\t\tGLuint magnification;\n\t\tif (!filterSampling) {\n\t\t\tminification = GL_NEAREST;\n\t\t\tmagnification = GL_NEAREST;\n\t\t}\n\t\telse if (generateMipmap) {\n\t\t\tminification = GL_LINEAR_MIPMAP_LINEAR;\n\t\t\tmagnification = GL_LINEAR;\n\t\t}\n\t\telse {\n\t\t\tminification = GL_LINEAR;\n\t\t\tmagnification = GL_LINEAR;\n\t\t}\n\t\tglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, magnification);\n\t\tglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, minification);\n\t}\n\n\tTexture *Texture::getWhiteTexture() {\n\t\tif (whiteTexture != nullptr) {\n\t\t\treturn whiteTexture;\n\t\t}\n\t\tchar one = (char)0xff;\n\t\tstd::vector<char> data(2 * 2 * 4, one);\n\t\twhiteTexture = createFromRGBAMem(data.data(), 2, 2, true);\n\t\treturn whiteTexture;\n\t}\n\n\tTexture *Texture::getSphereTexture() {\n\t\tif (sphereTexture != nullptr) {\n\t\t\treturn sphereTexture;\n\t\t}\n\t\tint size = 128;\n\t\tchar one = (char)0xff;\n\t\tstd::vector<char> data(size*size * 4, one);\n\t\tfor (int x = 0; x<size; x++) {\n\t\t\tfor (int y = 0; y<size; y++) {\n\t\t\t\tfloat distToCenter = glm::clamp(1.0f - 2.0f*glm::length(glm::vec2((x + 0.5f) \/ size, (y + 0.5f) \/ size) - glm::vec2(0.5f, 0.5f)), 0.0f, 1.0f);\n\t\t\t\tdata[x*size * 4 + y * 4 + 0] = (char)(255 * distToCenter);\n\t\t\t\tdata[x*size * 4 + y * 4 + 1] = (char)(255 * distToCenter);\n\t\t\t\tdata[x*size * 4 + y * 4 + 2] = (char)(255 * distToCenter);\n\t\t\t\tdata[x*size * 4 + y * 4 + 3] = (char)255;\n\t\t\t}\n\t\t}\n\t\tsphereTexture = createFromRGBAMem(data.data(), size, size, true);\n\t\treturn sphereTexture;\n\t}\n}\n<commit_msg>0.2.8 Add support for Emscripten<commit_after>#include \"SRE\/Texture.hpp\"\n\n#include \"SRE\/impl\/GL.hpp\"\n#include <stdio.h>\n#include <SDL_surface.h>\n\n#include <SDL_image.h>\n#include <iostream>\n#include <vector>\n#include <fstream>\n#include <memory>\n\nnamespace {\n\tstatic std::vector<char> readAllBytes(char const* filename)\n\t{\n\t\tusing namespace std;\n\t\tifstream ifs(filename, std::ios::binary | std::ios::ate);\n\t\tifstream::pos_type pos = ifs.tellg();\n\t\tif (pos<0) {\n\t\t\tstd::cerr << \"Cannot read \" << filename << std::endl;\n\t\t\treturn std::vector<char>();\n\t\t}\n\t\tstd::vector<char> result((size_t)pos);\n\n\t\tifs.seekg(0, ios::beg);\n\t\tifs.read(&result[0], pos);\n\n\t\treturn result;\n\t}\n}\n\nnamespace SRE {\n\tTexture* Texture::whiteTexture = nullptr;\n\tTexture* Texture::sphereTexture = nullptr;\n\n\tTexture::Texture(const char *data, int width, int height, uint32_t format, bool generateMipmaps)\n\t\t: width{ width }, height{ height }, generateMipmap{ generateMipmaps } {\n\t\tglGenTextures(1, &textureId);\n\n\t\tGLenum target = GL_TEXTURE_2D;\n\t\tGLint mipmapLevel = 0;\n\t\tGLint internalFormat = GL_RGBA;\n\t\tGLint border = 0;\n\t\tGLenum type = GL_UNSIGNED_BYTE;\n\t\tglBindTexture(target, textureId);\n\t\tglTexImage2D(target, mipmapLevel, internalFormat, width, height, border, format, type, data);\n\t\tupdateTextureSampler();\n\t\tif (generateMipmaps) {\n\t\t\tglGenerateMipmap(GL_TEXTURE_2D);\n\t\t}\n\t}\n\n\tGLenum getFormat(SDL_Surface *image) {\n\t\tSDL_PixelFormat *format = image->format;\n\t\tauto pixelFormat = format->format;\n\t\tbool isBGR = format->Rshift == 16;\n\n#ifdef EMSCRIPTEN\n GLenum RGB = GL_RGB;\n GLenum RGBA = GL_RGBA;\n#else\n GLenum RGB = isBGR ? GL_BGR : GL_RGB;\n GLenum RGBA = isBGR ? GL_BGRA : GL_RGBA;\n#endif\n\t\tconst bool alpha = SDL_ISPIXELFORMAT_ALPHA(pixelFormat);\n\t\tif (alpha) {\n\t\t\treturn RGBA;\n\t\t}\n\t\telse {\n\t\t\tif (format->BytesPerPixel == 4) {\n\t\t\t\treturn RGBA;\n\t\t\t}\n\t\t\telse if (format->BytesPerPixel == 3) {\n\t\t\t\treturn RGB;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tSDL_SetError(\"Unknown image format. Only PNG-24 and JPEG is supported.\");\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t}\n\t}\n\n\tint invert_image(int width, int height, void *image_pixels) {\n\t\tauto temp_row = std::unique_ptr<char>(new char[width]);\n\t\tif (temp_row.get() == nullptr) {\n\t\t\tSDL_SetError(\"Not enough memory for image inversion\");\n\t\t\treturn -1;\n\t\t}\n\t\t\/\/if height is odd, don't need to swap middle row\n\t\tint height_div_2 = height \/ 2;\n\t\tfor (int index = 0; index < height_div_2; index++) {\n\t\t\t\/\/uses string.h\n\t\t\tmemcpy((Uint8 *)temp_row.get(),\n\t\t\t\t(Uint8 *)(image_pixels)+\n\t\t\t\twidth * index,\n\t\t\t\twidth);\n\n\t\t\tmemcpy(\n\t\t\t\t(Uint8 *)(image_pixels)+\n\t\t\t\twidth * index,\n\t\t\t\t(Uint8 *)(image_pixels)+\n\t\t\t\twidth * (height - index - 1),\n\t\t\t\twidth);\n\t\t\tmemcpy(\n\t\t\t\t(Uint8 *)(image_pixels)+\n\t\t\t\twidth * (height - index - 1),\n\t\t\t\ttemp_row.get(),\n\t\t\t\twidth);\n\t\t}\n\t\treturn 0;\n\t}\n\n\tbool isPowerOfTwo(unsigned int x) {\n\t\treturn ((x != 0) && !(x & (x - 1)));\n\t}\n\n\tTexture* Texture::createFromFile(const char *pngOrJpeg, bool generateMipmaps) {\n\t\tauto data = readAllBytes(pngOrJpeg);\n\t\treturn createFromMem(data.data(), data.size(), generateMipmaps);\n\t}\n\n\tTexture *Texture::createFromMem(const char *pngOrJpeg, int size, bool generateMipmaps) {\n\t\tstatic bool initialized = false;\n\t\tif (!initialized) {\n\t\t\tinitialized = true;\n\t\t\tint flags = IMG_INIT_PNG | IMG_INIT_JPG;\n\t\t\tint initted = IMG_Init(flags);\n\t\t\tif ((initted & flags) != flags) {\n\t\t\t\tstd::cerr << \"IMG_Init: Failed to init required jpg and png support!\" << std::endl;\n\t\t\t\tstd::cerr << \"IMG_Init: \" << IMG_GetError() << std::endl;\n\t\t\t\t\/\/ handle error\n\t\t\t}\n\t\t}\n\n\t\tSDL_RWops *source = SDL_RWFromConstMem(pngOrJpeg, size);\n\t\tSDL_Surface *res_texture = IMG_Load_RW(source, 1);\n\t\tif (res_texture == NULL) {\n\t\t\tstd::cerr << \"IMG_Load: \" << SDL_GetError() << std::endl;\n\t\t\treturn nullptr;\n\t\t}\n\t\tint w = res_texture->w;\n\t\tint h = res_texture->h;\n\t\tauto format = getFormat(res_texture);\n\n\t\tint bytesPerPixel =\n#ifndef EMSCRIPTEN\n\t\t\t\tformat == GL_BGR ||\n#endif\n\t\t\t\t\t\tformat == GL_RGB ? 3 : 4;\n\t\tchar *pixels = static_cast<char *>(res_texture->pixels);\n\t\tinvert_image(w*bytesPerPixel, h, pixels);\n\t\tif (generateMipmaps && (!isPowerOfTwo((unsigned int)w) || !isPowerOfTwo((unsigned int)h))) {\n\t\t\tstd::cerr << \"Ignore mipmaps for textures not power of two\" << std::endl;\n\t\t\tgenerateMipmaps = false;\n\t\t}\n\t\tTexture *res = new Texture(pixels, w, h, format, generateMipmaps);\n\t\tSDL_FreeSurface(res_texture);\n\t\treturn res;\n\t}\n\n\tTexture *Texture::createFromRGBAMem(const char *data, int width, int height, bool generateMipmaps) {\n\t\treturn new Texture(data, width, height, GL_RGBA, generateMipmaps);\n\t}\n\n\t\/\/ returns true if texture sampling should be filtered (bi-linear or tri-linear sampling) otherwise use point sampling.\n\tbool Texture::isFilterSampling() {\n\t\treturn filterSampling;\n\t}\n\n\t\/\/ if true texture sampling is filtered (bi-linear or tri-linear sampling) otherwise use point sampling.\n\tvoid Texture::setFilterSampling(bool enable) {\n\t\tfilterSampling = enable;\n\t\tupdateTextureSampler();\n\t}\n\n\tbool Texture::isWrapTextureCoordinates() {\n\t\treturn filterSampling;\n\t}\n\n\tvoid Texture::setWrapTextureCoordinates(bool enable) {\n\t\twrapTextureCoordinates = enable;\n\t\tupdateTextureSampler();\n\t}\n\n\tint Texture::getWidth() {\n\t\treturn width;\n\t}\n\n\tint Texture::getHeight() {\n\t\treturn height;\n\t}\n\n\tvoid Texture::updateTextureSampler() {\n\t\tglBindTexture(GL_TEXTURE_2D, textureId);\n\t\tglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, wrapTextureCoordinates ? GL_REPEAT : GL_CLAMP_TO_EDGE);\n\t\tglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, wrapTextureCoordinates ? GL_REPEAT : GL_CLAMP_TO_EDGE);\n\t\tGLuint minification;\n\t\tGLuint magnification;\n\t\tif (!filterSampling) {\n\t\t\tminification = GL_NEAREST;\n\t\t\tmagnification = GL_NEAREST;\n\t\t}\n\t\telse if (generateMipmap) {\n\t\t\tminification = GL_LINEAR_MIPMAP_LINEAR;\n\t\t\tmagnification = GL_LINEAR;\n\t\t}\n\t\telse {\n\t\t\tminification = GL_LINEAR;\n\t\t\tmagnification = GL_LINEAR;\n\t\t}\n\t\tglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, magnification);\n\t\tglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, minification);\n\t}\n\n\tTexture *Texture::getWhiteTexture() {\n\t\tif (whiteTexture != nullptr) {\n\t\t\treturn whiteTexture;\n\t\t}\n\t\tchar one = (char)0xff;\n\t\tstd::vector<char> data(2 * 2 * 4, one);\n\t\twhiteTexture = createFromRGBAMem(data.data(), 2, 2, true);\n\t\treturn whiteTexture;\n\t}\n\n\tTexture *Texture::getSphereTexture() {\n\t\tif (sphereTexture != nullptr) {\n\t\t\treturn sphereTexture;\n\t\t}\n\t\tint size = 128;\n\t\tchar one = (char)0xff;\n\t\tstd::vector<char> data(size*size * 4, one);\n\t\tfor (int x = 0; x<size; x++) {\n\t\t\tfor (int y = 0; y<size; y++) {\n\t\t\t\tfloat distToCenter = glm::clamp(1.0f - 2.0f*glm::length(glm::vec2((x + 0.5f) \/ size, (y + 0.5f) \/ size) - glm::vec2(0.5f, 0.5f)), 0.0f, 1.0f);\n\t\t\t\tdata[x*size * 4 + y * 4 + 0] = (char)(255 * distToCenter);\n\t\t\t\tdata[x*size * 4 + y * 4 + 1] = (char)(255 * distToCenter);\n\t\t\t\tdata[x*size * 4 + y * 4 + 2] = (char)(255 * distToCenter);\n\t\t\t\tdata[x*size * 4 + y * 4 + 3] = (char)255;\n\t\t\t}\n\t\t}\n\t\tsphereTexture = createFromRGBAMem(data.data(), size, size, true);\n\t\treturn sphereTexture;\n\t}\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2013 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"xwalk\/application\/common\/application_data.h\"\n\n#include \"base\/base64.h\"\n#include \"base\/basictypes.h\"\n#include \"base\/command_line.h\"\n#include \"base\/file_util.h\"\n#include \"base\/files\/file_path.h\"\n#include \"base\/i18n\/rtl.h\"\n#include \"base\/logging.h\"\n#include \"base\/memory\/singleton.h\"\n#include \"base\/stl_util.h\"\n#include \"base\/strings\/string16.h\"\n#include \"base\/strings\/string_util.h\"\n#include \"base\/strings\/stringprintf.h\"\n#include \"base\/strings\/string_number_conversions.h\"\n#include \"base\/strings\/string_piece.h\"\n#include \"base\/strings\/utf_string_conversions.h\"\n#include \"base\/values.h\"\n#include \"base\/version.h\"\n#include \"xwalk\/application\/common\/application_manifest_constants.h\"\n#include \"xwalk\/application\/common\/id_util.h\"\n#include \"xwalk\/application\/common\/constants.h\"\n#include \"xwalk\/application\/common\/manifest.h\"\n#include \"xwalk\/application\/common\/manifest_handler.h\"\n#include \"xwalk\/application\/common\/manifest_handlers\/main_document_handler.h\"\n#include \"xwalk\/application\/common\/manifest_handlers\/permissions_handler.h\"\n#include \"xwalk\/application\/common\/permission_policy_manager.h\"\n#include \"content\/public\/common\/url_constants.h\"\n#include \"url\/url_util.h\"\n#include \"ui\/base\/l10n\/l10n_util.h\"\n\nnamespace keys = xwalk::application_manifest_keys;\nnamespace widget_keys = xwalk::application_widget_keys;\nnamespace errors = xwalk::application_manifest_errors;\n\nnamespace xwalk {\nnamespace application {\n\n\/\/ static\nscoped_refptr<ApplicationData> ApplicationData::Create(\n const base::FilePath& path,\n Manifest::SourceType source_type,\n const base::DictionaryValue& manifest_data,\n const std::string& explicit_id,\n std::string* error_message) {\n DCHECK(error_message);\n base::string16 error;\n scoped_ptr<xwalk::application::Manifest> manifest(\n new xwalk::application::Manifest(source_type,\n scoped_ptr<base::DictionaryValue>(manifest_data.DeepCopy())));\n\n if (!InitApplicationID(manifest.get(), path, explicit_id, &error)) {\n *error_message = base::UTF16ToUTF8(error);\n return NULL;\n }\n\n std::vector<InstallWarning> install_warnings;\n if (!manifest->ValidateManifest(error_message, &install_warnings)) {\n return NULL;\n }\n\n scoped_refptr<ApplicationData> application = new ApplicationData(path,\n manifest.Pass());\n application->install_warnings_.swap(install_warnings);\n\n if (!application->Init(&error)) {\n *error_message = base::UTF16ToUTF8(error);\n return NULL;\n }\n\n return application;\n}\n\n\/\/ static\nbool ApplicationData::IsIDValid(const std::string& id) {\n std::string temp = StringToLowerASCII(id);\n\n#if defined(OS_TIZEN)\n \/\/ An ID with 10 characters is most likely a legacy Tizen ID.\n if (temp.size() == kLegacyTizenIdSize) {\n for (size_t i = 0; i < kLegacyTizenIdSize; ++i) {\n const char c = temp[i];\n const bool valid = (c >= '0' && c <= '9') || (c >= 'a' && c <= 'z');\n if (!valid)\n return false;\n }\n\n return true;\n }\n#endif\n\n \/\/ Verify that the id is legal.\n if (temp.size() != (kIdSize * 2))\n return false;\n\n \/\/ We only support lowercase IDs, because IDs can be used as URL components\n \/\/ (where GURL will lowercase it).\n for (size_t i = 0; i < temp.size(); ++i)\n if (temp[i] < 'a' || temp[i] > 'p')\n return false;\n\n return true;\n}\n\n\/\/ static\nGURL ApplicationData::GetBaseURLFromApplicationId(\n const std::string& application_id) {\n return GURL(std::string(xwalk::application::kApplicationScheme) +\n content::kStandardSchemeSeparator + application_id + \"\/\");\n}\n\nApplicationData::ManifestData* ApplicationData::GetManifestData(\n const std::string& key) const {\n DCHECK(finished_parsing_manifest_ || thread_checker_.CalledOnValidThread());\n ManifestDataMap::const_iterator iter = manifest_data_.find(key);\n if (iter != manifest_data_.end())\n return iter->second.get();\n return NULL;\n}\n\nvoid ApplicationData::SetManifestData(const std::string& key,\n ApplicationData::ManifestData* data) {\n DCHECK(!finished_parsing_manifest_ && thread_checker_.CalledOnValidThread());\n manifest_data_[key] = linked_ptr<ManifestData>(data);\n}\n\nManifest::SourceType ApplicationData::GetSourceType() const {\n return manifest_->GetSourceType();\n}\n\nconst std::string& ApplicationData::ID() const {\n return manifest_->GetApplicationID();\n}\n\nconst std::string ApplicationData::VersionString() const {\n return Version()->GetString();\n}\n\nbool ApplicationData::IsPlatformApp() const {\n return manifest_->IsPackaged();\n}\n\nbool ApplicationData::IsHostedApp() const {\n return GetManifest()->IsHosted();\n}\n\nManifest::PackageType ApplicationData::GetPackageType() const {\n return manifest_->GetPackageType();\n}\n\nbool ApplicationData::HasMainDocument() const {\n MainDocumentInfo* main_info = ToMainDocumentInfo(\n GetManifestData(application_manifest_keys::kAppMainKey));\n\n return main_info != NULL;\n}\n\n\/\/ static\nbool ApplicationData::InitApplicationID(xwalk::application::Manifest* manifest,\n const base::FilePath& path,\n const std::string& explicit_id,\n base::string16* error) {\n std::string application_id;\n#if defined(OS_TIZEN)\n if (manifest->HasKey(keys::kTizenAppIdKey)) {\n if (!manifest->GetString(keys::kTizenAppIdKey, &application_id)) {\n NOTREACHED() << \"Could not get Tizen application key\";\n return false;\n }\n }\n\n if (!application_id.empty()) {\n manifest->SetApplicationID(application_id);\n return true;\n }\n#endif\n\n if (!explicit_id.empty()) {\n manifest->SetApplicationID(explicit_id);\n return true;\n }\n\n application_id = GenerateIdForPath(path);\n if (application_id.empty()) {\n NOTREACHED() << \"Could not create ID from path.\";\n return false;\n }\n manifest->SetApplicationID(application_id);\n return true;\n}\n\nApplicationData::ApplicationData(const base::FilePath& path,\n scoped_ptr<xwalk::application::Manifest> manifest)\n : manifest_version_(0),\n is_dirty_(false),\n manifest_(manifest.release()),\n finished_parsing_manifest_(false) {\n DCHECK(path.empty() || path.IsAbsolute());\n path_ = path;\n}\n\nApplicationData::~ApplicationData() {\n}\n\n\/\/ static\nGURL ApplicationData::GetResourceURL(const GURL& application_url,\n const std::string& relative_path) {\n DCHECK(application_url.SchemeIs(xwalk::application::kApplicationScheme));\n DCHECK_EQ(\"\/\", application_url.path());\n\n std::string path = relative_path;\n\n \/\/ If the relative path starts with \"\/\", it is \"absolute\" relative to the\n \/\/ application base directory, but application_url is already specified to\n \/\/ refer to that base directory, so strip the leading \"\/\" if present.\n if (relative_path.size() > 0 && relative_path[0] == '\/')\n path = relative_path.substr(1);\n\n GURL ret_val = GURL(application_url.spec() + path);\n DCHECK(StartsWithASCII(ret_val.spec(), application_url.spec(), false));\n\n return ret_val;\n}\n\nManifest::Type ApplicationData::GetType() const {\n return manifest_->GetType();\n}\n\nbool ApplicationData::Init(base::string16* error) {\n DCHECK(error);\n\n if (!LoadName(error))\n return false;\n if (!LoadVersion(error))\n return false;\n if (!LoadDescription(error))\n return false;\n if (!LoadManifestVersion(error))\n return false;\n\n application_url_ = ApplicationData::GetBaseURLFromApplicationId(ID());\n\n ManifestHandlerRegistry* registry =\n ManifestHandlerRegistry::GetInstance(GetPackageType());\n if (!registry->ParseAppManifest(this, error))\n return false;\n\n finished_parsing_manifest_ = true;\n return true;\n}\n\nbool ApplicationData::LoadName(base::string16* error) {\n DCHECK(error);\n base::string16 localized_name;\n std::string name_key(GetNameKey(GetPackageType()));\n\n if (!manifest_->GetString(name_key, &localized_name) &&\n manifest_->IsXPKPackaged()) {\n *error = base::ASCIIToUTF16(errors::kInvalidName);\n return false;\n }\n non_localized_name_ = base::UTF16ToUTF8(localized_name);\n base::i18n::AdjustStringForLocaleDirection(&localized_name);\n name_ = base::UTF16ToUTF8(localized_name);\n return true;\n}\n\nbool ApplicationData::LoadVersion(base::string16* error) {\n DCHECK(error);\n std::string version_str;\n std::string version_key(GetVersionKey(GetPackageType()));\n\n if (!manifest_->GetString(version_key, &version_str) &&\n manifest_->IsXPKPackaged()) {\n *error = base::ASCIIToUTF16(errors::kInvalidVersion);\n return false;\n }\n version_.reset(new base::Version(version_str));\n if (manifest_->IsXPKPackaged() &&\n (!version_->IsValid() || version_->components().size() > 4)) {\n *error = base::ASCIIToUTF16(errors::kInvalidVersion);\n return false;\n }\n return true;\n}\n\nbool ApplicationData::LoadDescription(base::string16* error) {\n DCHECK(error);\n if (manifest_->HasKey(keys::kDescriptionKey) &&\n !manifest_->GetString(keys::kDescriptionKey, &description_) &&\n manifest_->IsXPKPackaged()) {\n *error = base::ASCIIToUTF16(errors::kInvalidDescription);\n return false;\n }\n return true;\n}\n\nbool ApplicationData::LoadManifestVersion(base::string16* error) {\n DCHECK(error);\n \/\/ Get the original value out of the dictionary so that we can validate it\n \/\/ more strictly.\n if (manifest_->value()->HasKey(keys::kManifestVersionKey)) {\n int manifest_version = 1;\n if (!manifest_->GetInteger(keys::kManifestVersionKey, &manifest_version) ||\n manifest_version < 1) {\n if (manifest_->IsXPKPackaged()) {\n *error = base::ASCIIToUTF16(errors::kInvalidManifestVersion);\n return false;\n }\n }\n }\n\n manifest_version_ = manifest_->GetManifestVersion();\n return true;\n}\n\nvoid ApplicationData::SetEvents(const std::set<std::string>& events) {\n events_ = events;\n is_dirty_ = true;\n}\n\nconst std::set<std::string>& ApplicationData::GetEvents() const {\n return events_;\n}\n\nStoredPermission ApplicationData::GetPermission(\n std::string& permission_name) const {\n StoredPermissionMap::const_iterator iter =\n permission_map_.find(permission_name);\n if (iter == permission_map_.end())\n return UNDEFINED_STORED_PERM;\n return iter->second;\n}\n\nbool ApplicationData::SetPermission(const std::string& permission_name,\n StoredPermission perm) {\n if (perm != UNDEFINED_STORED_PERM) {\n permission_map_[permission_name] = perm;\n is_dirty_ = true;\n return true;\n }\n return false;\n}\n\nvoid ApplicationData::ClearPermissions() {\n permission_map_.clear();\n}\n\nPermissionSet ApplicationData::GetManifestPermissions() const {\n PermissionSet permissions;\n if (manifest_->value()->HasKey(keys::kPermissionsKey)) {\n const PermissionsInfo* perm_info = static_cast<PermissionsInfo*>(\n GetManifestData(keys::kPermissionsKey));\n permissions = perm_info->GetAPIPermissions();\n }\n return permissions;\n}\n\n} \/\/ namespace application\n} \/\/ namespace xwalk\n<commit_msg>[Tizen] [Runtime] Fix the issue that widget apps fails to install without version attribute.<commit_after>\/\/ Copyright (c) 2013 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"xwalk\/application\/common\/application_data.h\"\n\n#include \"base\/base64.h\"\n#include \"base\/basictypes.h\"\n#include \"base\/command_line.h\"\n#include \"base\/file_util.h\"\n#include \"base\/files\/file_path.h\"\n#include \"base\/i18n\/rtl.h\"\n#include \"base\/logging.h\"\n#include \"base\/memory\/singleton.h\"\n#include \"base\/stl_util.h\"\n#include \"base\/strings\/string16.h\"\n#include \"base\/strings\/string_util.h\"\n#include \"base\/strings\/stringprintf.h\"\n#include \"base\/strings\/string_number_conversions.h\"\n#include \"base\/strings\/string_piece.h\"\n#include \"base\/strings\/utf_string_conversions.h\"\n#include \"base\/values.h\"\n#include \"base\/version.h\"\n#include \"xwalk\/application\/common\/application_manifest_constants.h\"\n#include \"xwalk\/application\/common\/id_util.h\"\n#include \"xwalk\/application\/common\/constants.h\"\n#include \"xwalk\/application\/common\/manifest.h\"\n#include \"xwalk\/application\/common\/manifest_handler.h\"\n#include \"xwalk\/application\/common\/manifest_handlers\/main_document_handler.h\"\n#include \"xwalk\/application\/common\/manifest_handlers\/permissions_handler.h\"\n#include \"xwalk\/application\/common\/permission_policy_manager.h\"\n#include \"content\/public\/common\/url_constants.h\"\n#include \"url\/url_util.h\"\n#include \"ui\/base\/l10n\/l10n_util.h\"\n\nnamespace keys = xwalk::application_manifest_keys;\nnamespace widget_keys = xwalk::application_widget_keys;\nnamespace errors = xwalk::application_manifest_errors;\n\nnamespace xwalk {\nnamespace application {\n\n\/\/ static\nscoped_refptr<ApplicationData> ApplicationData::Create(\n const base::FilePath& path,\n Manifest::SourceType source_type,\n const base::DictionaryValue& manifest_data,\n const std::string& explicit_id,\n std::string* error_message) {\n DCHECK(error_message);\n base::string16 error;\n scoped_ptr<xwalk::application::Manifest> manifest(\n new xwalk::application::Manifest(source_type,\n scoped_ptr<base::DictionaryValue>(manifest_data.DeepCopy())));\n\n if (!InitApplicationID(manifest.get(), path, explicit_id, &error)) {\n *error_message = base::UTF16ToUTF8(error);\n return NULL;\n }\n\n std::vector<InstallWarning> install_warnings;\n if (!manifest->ValidateManifest(error_message, &install_warnings)) {\n return NULL;\n }\n\n scoped_refptr<ApplicationData> application = new ApplicationData(path,\n manifest.Pass());\n application->install_warnings_.swap(install_warnings);\n\n if (!application->Init(&error)) {\n *error_message = base::UTF16ToUTF8(error);\n return NULL;\n }\n\n return application;\n}\n\n\/\/ static\nbool ApplicationData::IsIDValid(const std::string& id) {\n std::string temp = StringToLowerASCII(id);\n\n#if defined(OS_TIZEN)\n \/\/ An ID with 10 characters is most likely a legacy Tizen ID.\n if (temp.size() == kLegacyTizenIdSize) {\n for (size_t i = 0; i < kLegacyTizenIdSize; ++i) {\n const char c = temp[i];\n const bool valid = (c >= '0' && c <= '9') || (c >= 'a' && c <= 'z');\n if (!valid)\n return false;\n }\n\n return true;\n }\n#endif\n\n \/\/ Verify that the id is legal.\n if (temp.size() != (kIdSize * 2))\n return false;\n\n \/\/ We only support lowercase IDs, because IDs can be used as URL components\n \/\/ (where GURL will lowercase it).\n for (size_t i = 0; i < temp.size(); ++i)\n if (temp[i] < 'a' || temp[i] > 'p')\n return false;\n\n return true;\n}\n\n\/\/ static\nGURL ApplicationData::GetBaseURLFromApplicationId(\n const std::string& application_id) {\n return GURL(std::string(xwalk::application::kApplicationScheme) +\n content::kStandardSchemeSeparator + application_id + \"\/\");\n}\n\nApplicationData::ManifestData* ApplicationData::GetManifestData(\n const std::string& key) const {\n DCHECK(finished_parsing_manifest_ || thread_checker_.CalledOnValidThread());\n ManifestDataMap::const_iterator iter = manifest_data_.find(key);\n if (iter != manifest_data_.end())\n return iter->second.get();\n return NULL;\n}\n\nvoid ApplicationData::SetManifestData(const std::string& key,\n ApplicationData::ManifestData* data) {\n DCHECK(!finished_parsing_manifest_ && thread_checker_.CalledOnValidThread());\n manifest_data_[key] = linked_ptr<ManifestData>(data);\n}\n\nManifest::SourceType ApplicationData::GetSourceType() const {\n return manifest_->GetSourceType();\n}\n\nconst std::string& ApplicationData::ID() const {\n return manifest_->GetApplicationID();\n}\n\nconst std::string ApplicationData::VersionString() const {\n if (!version_->components().empty())\n return Version()->GetString();\n\n return \"\";\n}\n\nbool ApplicationData::IsPlatformApp() const {\n return manifest_->IsPackaged();\n}\n\nbool ApplicationData::IsHostedApp() const {\n return GetManifest()->IsHosted();\n}\n\nManifest::PackageType ApplicationData::GetPackageType() const {\n return manifest_->GetPackageType();\n}\n\nbool ApplicationData::HasMainDocument() const {\n MainDocumentInfo* main_info = ToMainDocumentInfo(\n GetManifestData(application_manifest_keys::kAppMainKey));\n\n return main_info != NULL;\n}\n\n\/\/ static\nbool ApplicationData::InitApplicationID(xwalk::application::Manifest* manifest,\n const base::FilePath& path,\n const std::string& explicit_id,\n base::string16* error) {\n std::string application_id;\n#if defined(OS_TIZEN)\n if (manifest->HasKey(keys::kTizenAppIdKey)) {\n if (!manifest->GetString(keys::kTizenAppIdKey, &application_id)) {\n NOTREACHED() << \"Could not get Tizen application key\";\n return false;\n }\n }\n\n if (!application_id.empty()) {\n manifest->SetApplicationID(application_id);\n return true;\n }\n#endif\n\n if (!explicit_id.empty()) {\n manifest->SetApplicationID(explicit_id);\n return true;\n }\n\n application_id = GenerateIdForPath(path);\n if (application_id.empty()) {\n NOTREACHED() << \"Could not create ID from path.\";\n return false;\n }\n manifest->SetApplicationID(application_id);\n return true;\n}\n\nApplicationData::ApplicationData(const base::FilePath& path,\n scoped_ptr<xwalk::application::Manifest> manifest)\n : manifest_version_(0),\n is_dirty_(false),\n manifest_(manifest.release()),\n finished_parsing_manifest_(false) {\n DCHECK(path.empty() || path.IsAbsolute());\n path_ = path;\n}\n\nApplicationData::~ApplicationData() {\n}\n\n\/\/ static\nGURL ApplicationData::GetResourceURL(const GURL& application_url,\n const std::string& relative_path) {\n DCHECK(application_url.SchemeIs(xwalk::application::kApplicationScheme));\n DCHECK_EQ(\"\/\", application_url.path());\n\n std::string path = relative_path;\n\n \/\/ If the relative path starts with \"\/\", it is \"absolute\" relative to the\n \/\/ application base directory, but application_url is already specified to\n \/\/ refer to that base directory, so strip the leading \"\/\" if present.\n if (relative_path.size() > 0 && relative_path[0] == '\/')\n path = relative_path.substr(1);\n\n GURL ret_val = GURL(application_url.spec() + path);\n DCHECK(StartsWithASCII(ret_val.spec(), application_url.spec(), false));\n\n return ret_val;\n}\n\nManifest::Type ApplicationData::GetType() const {\n return manifest_->GetType();\n}\n\nbool ApplicationData::Init(base::string16* error) {\n DCHECK(error);\n\n if (!LoadName(error))\n return false;\n if (!LoadVersion(error))\n return false;\n if (!LoadDescription(error))\n return false;\n if (!LoadManifestVersion(error))\n return false;\n\n application_url_ = ApplicationData::GetBaseURLFromApplicationId(ID());\n\n ManifestHandlerRegistry* registry =\n ManifestHandlerRegistry::GetInstance(GetPackageType());\n if (!registry->ParseAppManifest(this, error))\n return false;\n\n finished_parsing_manifest_ = true;\n return true;\n}\n\nbool ApplicationData::LoadName(base::string16* error) {\n DCHECK(error);\n base::string16 localized_name;\n std::string name_key(GetNameKey(GetPackageType()));\n\n if (!manifest_->GetString(name_key, &localized_name) &&\n manifest_->IsXPKPackaged()) {\n *error = base::ASCIIToUTF16(errors::kInvalidName);\n return false;\n }\n non_localized_name_ = base::UTF16ToUTF8(localized_name);\n base::i18n::AdjustStringForLocaleDirection(&localized_name);\n name_ = base::UTF16ToUTF8(localized_name);\n return true;\n}\n\nbool ApplicationData::LoadVersion(base::string16* error) {\n DCHECK(error);\n std::string version_str;\n std::string version_key(GetVersionKey(GetPackageType()));\n\n if (!manifest_->GetString(version_key, &version_str) &&\n manifest_->IsXPKPackaged()) {\n *error = base::ASCIIToUTF16(errors::kInvalidVersion);\n return false;\n }\n version_.reset(new base::Version(version_str));\n if (manifest_->IsXPKPackaged() &&\n (!version_->IsValid() || version_->components().size() > 4)) {\n *error = base::ASCIIToUTF16(errors::kInvalidVersion);\n return false;\n }\n return true;\n}\n\nbool ApplicationData::LoadDescription(base::string16* error) {\n DCHECK(error);\n if (manifest_->HasKey(keys::kDescriptionKey) &&\n !manifest_->GetString(keys::kDescriptionKey, &description_) &&\n manifest_->IsXPKPackaged()) {\n *error = base::ASCIIToUTF16(errors::kInvalidDescription);\n return false;\n }\n return true;\n}\n\nbool ApplicationData::LoadManifestVersion(base::string16* error) {\n DCHECK(error);\n \/\/ Get the original value out of the dictionary so that we can validate it\n \/\/ more strictly.\n if (manifest_->value()->HasKey(keys::kManifestVersionKey)) {\n int manifest_version = 1;\n if (!manifest_->GetInteger(keys::kManifestVersionKey, &manifest_version) ||\n manifest_version < 1) {\n if (manifest_->IsXPKPackaged()) {\n *error = base::ASCIIToUTF16(errors::kInvalidManifestVersion);\n return false;\n }\n }\n }\n\n manifest_version_ = manifest_->GetManifestVersion();\n return true;\n}\n\nvoid ApplicationData::SetEvents(const std::set<std::string>& events) {\n events_ = events;\n is_dirty_ = true;\n}\n\nconst std::set<std::string>& ApplicationData::GetEvents() const {\n return events_;\n}\n\nStoredPermission ApplicationData::GetPermission(\n std::string& permission_name) const {\n StoredPermissionMap::const_iterator iter =\n permission_map_.find(permission_name);\n if (iter == permission_map_.end())\n return UNDEFINED_STORED_PERM;\n return iter->second;\n}\n\nbool ApplicationData::SetPermission(const std::string& permission_name,\n StoredPermission perm) {\n if (perm != UNDEFINED_STORED_PERM) {\n permission_map_[permission_name] = perm;\n is_dirty_ = true;\n return true;\n }\n return false;\n}\n\nvoid ApplicationData::ClearPermissions() {\n permission_map_.clear();\n}\n\nPermissionSet ApplicationData::GetManifestPermissions() const {\n PermissionSet permissions;\n if (manifest_->value()->HasKey(keys::kPermissionsKey)) {\n const PermissionsInfo* perm_info = static_cast<PermissionsInfo*>(\n GetManifestData(keys::kPermissionsKey));\n permissions = perm_info->GetAPIPermissions();\n }\n return permissions;\n}\n\n} \/\/ namespace application\n} \/\/ namespace xwalk\n<|endoftext|>"} {"text":"<commit_before>#include \"event_manager.hh\"\n\n#include <unistd.h>\n\nnamespace Kakoune\n{\n\nFDWatcher::FDWatcher(int fd, Callback callback)\n : m_fd{fd}, m_callback{std::move(callback)}\n{\n EventManager::instance().m_fd_watchers.insert(this);\n}\n\nFDWatcher::~FDWatcher()\n{\n EventManager::instance().m_fd_watchers.erase(this);\n}\n\nvoid FDWatcher::run(EventMode mode)\n{\n m_callback(*this, mode);\n}\n\nvoid FDWatcher::close_fd()\n{\n close(m_fd);\n m_fd = -1;\n}\n\nTimer::Timer(TimePoint date, Callback callback, EventMode mode)\n : m_date{date}, m_callback{std::move(callback)}, m_mode(mode)\n{\n if (EventManager::has_instance())\n EventManager::instance().m_timers.insert(this);\n}\n\nTimer::~Timer()\n{\n if (EventManager::has_instance())\n EventManager::instance().m_timers.erase(this);\n}\n\nvoid Timer::run(EventMode mode)\n{\n if (mode == m_mode)\n {\n m_date = TimePoint::max();\n m_callback(*this);\n }\n else \/\/ try again a little later\n m_date = Clock::now() + std::chrono::milliseconds{10};\n}\n\nEventManager::EventManager()\n{\n FD_ZERO(&m_forced_fd);\n}\n\nEventManager::~EventManager()\n{\n kak_assert(m_fd_watchers.empty());\n kak_assert(m_timers.empty());\n}\n\nvoid EventManager::handle_next_events(EventMode mode)\n{\n int max_fd = 0;\n fd_set rfds;\n FD_ZERO(&rfds);\n for (auto& watcher : m_fd_watchers)\n {\n const int fd = watcher->fd();\n if (fd != -1)\n {\n max_fd = std::max(fd, max_fd);\n FD_SET(fd, &rfds);\n }\n }\n\n TimePoint next_timer = TimePoint::max();\n for (auto& timer : m_timers)\n {\n if (timer->next_date() <= next_timer)\n next_timer = timer->next_date();\n }\n using namespace std::chrono;\n auto timeout = duration_cast<microseconds>(next_timer - Clock::now()).count();\n\n constexpr auto us = 1000000000ll;\n timeval tv{ (long)(timeout \/ us), (long)(timeout % us) };\n int res = select(max_fd + 1, &rfds, nullptr, nullptr, &tv);\n\n \/\/ copy forced fds *after* poll, so that signal handlers can write to\n \/\/ m_forced_fd, interupt poll, and directly be serviced.\n fd_set forced = m_forced_fd;\n FD_ZERO(&m_forced_fd);\n\n for (int fd = 0; fd < max_fd + 1; ++fd)\n {\n if ((res > 0 and FD_ISSET(fd, &rfds)) or FD_ISSET(fd, &forced))\n {\n auto it = find_if(m_fd_watchers,\n [fd](const FDWatcher* w){return w->fd() == fd; });\n if (it != m_fd_watchers.end())\n (*it)->run(mode);\n }\n }\n\n TimePoint now = Clock::now();\n for (auto& timer : m_timers)\n {\n if (timer->next_date() <= now)\n timer->run(mode);\n }\n}\n\nvoid EventManager::force_signal(int fd)\n{\n FD_SET(fd, &m_forced_fd);\n}\n\n}\n<commit_msg>Fix timeval field types<commit_after>#include \"event_manager.hh\"\n\n#include <unistd.h>\n\nnamespace Kakoune\n{\n\nFDWatcher::FDWatcher(int fd, Callback callback)\n : m_fd{fd}, m_callback{std::move(callback)}\n{\n EventManager::instance().m_fd_watchers.insert(this);\n}\n\nFDWatcher::~FDWatcher()\n{\n EventManager::instance().m_fd_watchers.erase(this);\n}\n\nvoid FDWatcher::run(EventMode mode)\n{\n m_callback(*this, mode);\n}\n\nvoid FDWatcher::close_fd()\n{\n close(m_fd);\n m_fd = -1;\n}\n\nTimer::Timer(TimePoint date, Callback callback, EventMode mode)\n : m_date{date}, m_callback{std::move(callback)}, m_mode(mode)\n{\n if (EventManager::has_instance())\n EventManager::instance().m_timers.insert(this);\n}\n\nTimer::~Timer()\n{\n if (EventManager::has_instance())\n EventManager::instance().m_timers.erase(this);\n}\n\nvoid Timer::run(EventMode mode)\n{\n if (mode == m_mode)\n {\n m_date = TimePoint::max();\n m_callback(*this);\n }\n else \/\/ try again a little later\n m_date = Clock::now() + std::chrono::milliseconds{10};\n}\n\nEventManager::EventManager()\n{\n FD_ZERO(&m_forced_fd);\n}\n\nEventManager::~EventManager()\n{\n kak_assert(m_fd_watchers.empty());\n kak_assert(m_timers.empty());\n}\n\nvoid EventManager::handle_next_events(EventMode mode)\n{\n int max_fd = 0;\n fd_set rfds;\n FD_ZERO(&rfds);\n for (auto& watcher : m_fd_watchers)\n {\n const int fd = watcher->fd();\n if (fd != -1)\n {\n max_fd = std::max(fd, max_fd);\n FD_SET(fd, &rfds);\n }\n }\n\n TimePoint next_timer = TimePoint::max();\n for (auto& timer : m_timers)\n {\n if (timer->next_date() <= next_timer)\n next_timer = timer->next_date();\n }\n using namespace std::chrono;\n auto timeout = duration_cast<microseconds>(next_timer - Clock::now()).count();\n\n constexpr auto us = 1000000000ll;\n timeval tv{ (time_t)(timeout \/ us), (suseconds_t)(timeout % us) };\n int res = select(max_fd + 1, &rfds, nullptr, nullptr, &tv);\n\n \/\/ copy forced fds *after* poll, so that signal handlers can write to\n \/\/ m_forced_fd, interupt poll, and directly be serviced.\n fd_set forced = m_forced_fd;\n FD_ZERO(&m_forced_fd);\n\n for (int fd = 0; fd < max_fd + 1; ++fd)\n {\n if ((res > 0 and FD_ISSET(fd, &rfds)) or FD_ISSET(fd, &forced))\n {\n auto it = find_if(m_fd_watchers,\n [fd](const FDWatcher* w){return w->fd() == fd; });\n if (it != m_fd_watchers.end())\n (*it)->run(mode);\n }\n }\n\n TimePoint now = Clock::now();\n for (auto& timer : m_timers)\n {\n if (timer->next_date() <= now)\n timer->run(mode);\n }\n}\n\nvoid EventManager::force_signal(int fd)\n{\n FD_SET(fd, &m_forced_fd);\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (C) 2014 Pelagicore AB\n * All rights reserved.\n *\/\n#include <unistd.h>\n#include <fcntl.h>\n#include <errno.h>\n#include <iostream>\n\n#include \"config.h\"\n#include \"controllerinterface.h\"\n\nControllerInterface::ControllerInterface(const std::string &gatewayDir):\n m_connected(false),\n m_socketPath(gatewayDir + \"\/ipc_socket\"),\n m_running(false),\n m_listenSocket(0),\n m_connectionSocket(0),\n m_highestFd(0),\n m_timeout(Config::instance()->controllerConnectionTimeout())\n{\n}\n\nControllerInterface::~ControllerInterface()\n{\n \/\/ Close both the sockets...\n if (m_connectionSocket) {\n if (close(m_connectionSocket) == -1) {\n log_error() << \"close:\" << strerror(errno);\n }\n }\n\n if (m_listenSocket) {\n if (close(m_listenSocket) == -1) {\n log_error() << \"close listen:\" << strerror(errno);\n }\n }\n\n \/\/ ...and unlink the file\n if (unlink(m_socketPath.c_str()) == -1) {\n log_error() << \"unlink:\" << strerror(errno);\n }\n}\n\nbool ControllerInterface::initialize()\n{\n if ((m_listenSocket = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) {\n log_error() << \"socket:\" << strerror(errno);\n return false;\n }\n\n struct sockaddr_un local;\n local.sun_family = AF_UNIX;\n strcpy(local.sun_path, m_socketPath.c_str());\n unlink(local.sun_path);\n\n int len = strlen(local.sun_path) * sizeof(local.sun_family);\n if (bind(m_listenSocket, (struct sockaddr *)&local, len) == -1) {\n log_error() << \"bind:\" << strerror(errno);\n return false;\n }\n\n if (listen(m_listenSocket, 1) == -1) {\n log_error() << \"listen:\" << strerror(errno);\n return false;\n }\n\n m_selectTimeout.tv_sec = m_timeout;\n m_selectTimeout.tv_usec = 0;\n\n if (!isControllerConnected()) {\n return false;\n }\n\n return true;\n}\n\nbool ControllerInterface::isControllerConnected()\n{\n fd_set readfds;\n FD_ZERO(&readfds);\n FD_SET(m_listenSocket, &readfds);\n\n log_debug() << \"Waiting for Controller, timeout value is \" << m_timeout << \" seconds...\";\n\n m_highestFd = m_listenSocket;\n\n struct timeval tv;\n tv.tv_sec = m_timeout;\n tv.tv_usec = 0;\n int ret = select(m_highestFd + 1, &readfds, 0, 0, &tv);\n if (ret == -1) {\n log_error() << \"select:\" << strerror(errno);\n return false;\n } else if (ret == 0) {\n log_error() << \"select reached timeout\";\n return false;\n }\n\n if (FD_ISSET(m_listenSocket, &readfds)) {\n socklen_t t = sizeof(m_remote);\n m_connectionSocket = accept(m_listenSocket, (struct sockaddr *)&m_remote, &t);\n if (m_connectionSocket == -1) {\n log_error() << \"accept:\" << strerror(errno);\n \/\/ TODO: We need to propagate failure here\n return false; \/\/ Disconnects the signal handler\n }\n\n log_debug() << \"Accepted connection from Controller\";\n m_connected = true;\n\n if (m_connectionSocket > m_highestFd) {\n m_highestFd = m_connectionSocket;\n }\n \/\/ We are connected, i.e. the Controller is there, now we should\n \/\/ be prepared to receive messages.\n sigc::slot<bool> checkForMessageSlot = sigc::mem_fun(this, &ControllerInterface::checkForMessage);\n sigc::connection conn = Glib::signal_timeout().connect(checkForMessageSlot, 10);\n }\n\n return true;\n}\n\nbool ControllerInterface::checkForMessage()\n{\n char str[1024];\n memset(str, '\\0', sizeof(char) * 1024);\n\n struct timeval tv;\n tv.tv_sec = 0;\n tv.tv_usec = 0;\n\n fd_set readfds;\n FD_ZERO(&readfds);\n FD_SET(m_connectionSocket, &readfds);\n select(m_highestFd + 1, &readfds, 0, 0, &tv);\n\n if (FD_ISSET(m_connectionSocket, &readfds)) {\n int received = recv(m_connectionSocket, str, 100, 0);\n if (received == -1) {\n log_error() << \"recv:\" << strerror(errno);\n \/\/ TODO: Do we need to propagate failure here?\n \/\/ TODO: Should we continue waiting for messages after this?\n return false; \/\/ Disconnects the signal handler\n } else if (received == 0) {\n \/\/ Controller has shut down, there will be no more messages\n return false; \/\/ Disconnects the signal handler\n }\n\n log_debug() << \"Pelagicontain received: \" << str;\n }\n\n return true; \/\/ Continue to let the signal handler call this method\n}\n\nbool ControllerInterface::startApp()\n{\n bool result = false;\n\n if (canSend()) {\n char msg[] = {'1', '\\0'};\n\n log_debug(\"Sending: \\\"%s\\\"\", msg);\n\n int ret = send(m_connectionSocket, msg, sizeof(msg), 0);\n if (ret == -1) {\n log_error() << \"send:\" << strerror(errno);\n } else {\n m_running = true;\n result = true;\n }\n }\n\n return result;\n}\n\nbool ControllerInterface::shutdown()\n{\n bool result = false;\n\n if (canSend()) {\n char msg[] = {'2', '\\0'};\n\n log_debug(\"Sending: \\\"%s\\\"\", msg);\n\n int ret = send(m_connectionSocket, msg, sizeof(msg), 0);\n if (ret == -1) {\n log_error() << \"send:\" << strerror(errno);\n } else {\n m_running = false;\n result = true;\n }\n }\n\n return result;\n}\n\nbool ControllerInterface::setEnvironmentVariable(const std::string &variable,\n const std::string &value)\n{\n bool result = false;\n\n if (canSend()) {\n std::string command = \"3 \" + variable + \" \" + value;\n char msg[command.size() + 1];\n\n memcpy(msg, command.c_str(), command.size());\n msg[command.size()] = '\\0';\n\n log_debug(\"Sending: \\\"%s\\\"\", msg);\n\n int ret = send(m_connectionSocket, msg, strlen(msg) + 1, 0);\n if (ret == -1) {\n log_error() << \"send:\" << strerror(errno);\n } else {\n result = true;\n }\n }\n\n return result;\n}\n\nbool ControllerInterface::systemCall(const std::string &cmd)\n{\n bool result = false;\n\n if (canSend()) {\n std::string command = \"4 \" + cmd;\n char msg[command.size() + 1];\n\n memcpy(msg, command.c_str(), command.size());\n msg[command.size()] = '\\0';\n\n log_debug(\"Sending: \\\"%s\\\"\", msg);\n\n int ret = send(m_connectionSocket, msg, strlen(msg) + 1, 0);\n if (ret == -1) {\n log_error() << \"send:\" << strerror(errno);\n } else {\n result = true;\n }\n }\n\n return result;\n}\n\nbool ControllerInterface::hasBeenStarted() const\n{\n return m_running;\n}\n\nbool ControllerInterface::canSend()\n{\n if (!m_connected) {\n log_error() << \"No connection to Controller\";\n return false;\n }\n\n fd_set sendfds;\n FD_ZERO(&sendfds);\n FD_SET(m_connectionSocket, &sendfds);\n\n int ret = select(m_highestFd + 1, 0, &sendfds, 0, &m_selectTimeout);\n if (ret == -1) {\n log_error() << \"select:\" << strerror(errno);\n return false;\n } else if (ret == 0) {\n log_error() << \"select reached timeout\";\n return false;\n }\n\n return FD_ISSET(m_connectionSocket, &sendfds) ? true : false;\n}\n<commit_msg>controllerinterface.cpp: fix type in calculation<commit_after>\/*\n * Copyright (C) 2014 Pelagicore AB\n * All rights reserved.\n *\/\n#include <unistd.h>\n#include <fcntl.h>\n#include <errno.h>\n#include <iostream>\n\n#include \"config.h\"\n#include \"controllerinterface.h\"\n\nControllerInterface::ControllerInterface(const std::string &gatewayDir):\n m_connected(false),\n m_socketPath(gatewayDir + \"\/ipc_socket\"),\n m_running(false),\n m_listenSocket(0),\n m_connectionSocket(0),\n m_highestFd(0),\n m_timeout(Config::instance()->controllerConnectionTimeout())\n{\n}\n\nControllerInterface::~ControllerInterface()\n{\n \/\/ Close both the sockets...\n if (m_connectionSocket) {\n if (close(m_connectionSocket) == -1) {\n log_error() << \"close:\" << strerror(errno);\n }\n }\n\n if (m_listenSocket) {\n if (close(m_listenSocket) == -1) {\n log_error() << \"close listen:\" << strerror(errno);\n }\n }\n\n \/\/ ...and unlink the file\n if (unlink(m_socketPath.c_str()) == -1) {\n log_error() << \"unlink:\" << strerror(errno);\n }\n}\n\nbool ControllerInterface::initialize()\n{\n if ((m_listenSocket = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) {\n log_error() << \"socket:\" << strerror(errno);\n return false;\n }\n\n struct sockaddr_un local;\n local.sun_family = AF_UNIX;\n strcpy(local.sun_path, m_socketPath.c_str());\n unlink(local.sun_path);\n\n int len = strlen(local.sun_path) + sizeof(local.sun_family);\n if (bind(m_listenSocket, (struct sockaddr *)&local, len) == -1) {\n log_error() << \"bind:\" << strerror(errno);\n return false;\n }\n\n if (listen(m_listenSocket, 1) == -1) {\n log_error() << \"listen:\" << strerror(errno);\n return false;\n }\n\n m_selectTimeout.tv_sec = m_timeout;\n m_selectTimeout.tv_usec = 0;\n\n if (!isControllerConnected()) {\n return false;\n }\n\n return true;\n}\n\nbool ControllerInterface::isControllerConnected()\n{\n fd_set readfds;\n FD_ZERO(&readfds);\n FD_SET(m_listenSocket, &readfds);\n\n log_debug() << \"Waiting for Controller, timeout value is \" << m_timeout << \" seconds...\";\n\n m_highestFd = m_listenSocket;\n\n struct timeval tv;\n tv.tv_sec = m_timeout;\n tv.tv_usec = 0;\n int ret = select(m_highestFd + 1, &readfds, 0, 0, &tv);\n if (ret == -1) {\n log_error() << \"select:\" << strerror(errno);\n return false;\n } else if (ret == 0) {\n log_error() << \"select reached timeout\";\n return false;\n }\n\n if (FD_ISSET(m_listenSocket, &readfds)) {\n socklen_t t = sizeof(m_remote);\n m_connectionSocket = accept(m_listenSocket, (struct sockaddr *)&m_remote, &t);\n if (m_connectionSocket == -1) {\n log_error() << \"accept:\" << strerror(errno);\n \/\/ TODO: We need to propagate failure here\n return false; \/\/ Disconnects the signal handler\n }\n\n log_debug() << \"Accepted connection from Controller\";\n m_connected = true;\n\n if (m_connectionSocket > m_highestFd) {\n m_highestFd = m_connectionSocket;\n }\n \/\/ We are connected, i.e. the Controller is there, now we should\n \/\/ be prepared to receive messages.\n sigc::slot<bool> checkForMessageSlot = sigc::mem_fun(this, &ControllerInterface::checkForMessage);\n sigc::connection conn = Glib::signal_timeout().connect(checkForMessageSlot, 10);\n }\n\n return true;\n}\n\nbool ControllerInterface::checkForMessage()\n{\n char str[1024];\n memset(str, '\\0', sizeof(char) * 1024);\n\n struct timeval tv;\n tv.tv_sec = 0;\n tv.tv_usec = 0;\n\n fd_set readfds;\n FD_ZERO(&readfds);\n FD_SET(m_connectionSocket, &readfds);\n select(m_highestFd + 1, &readfds, 0, 0, &tv);\n\n if (FD_ISSET(m_connectionSocket, &readfds)) {\n int received = recv(m_connectionSocket, str, 100, 0);\n if (received == -1) {\n log_error() << \"recv:\" << strerror(errno);\n \/\/ TODO: Do we need to propagate failure here?\n \/\/ TODO: Should we continue waiting for messages after this?\n return false; \/\/ Disconnects the signal handler\n } else if (received == 0) {\n \/\/ Controller has shut down, there will be no more messages\n return false; \/\/ Disconnects the signal handler\n }\n\n log_debug() << \"Pelagicontain received: \" << str;\n }\n\n return true; \/\/ Continue to let the signal handler call this method\n}\n\nbool ControllerInterface::startApp()\n{\n bool result = false;\n\n if (canSend()) {\n char msg[] = {'1', '\\0'};\n\n log_debug(\"Sending: \\\"%s\\\"\", msg);\n\n int ret = send(m_connectionSocket, msg, sizeof(msg), 0);\n if (ret == -1) {\n log_error() << \"send:\" << strerror(errno);\n } else {\n m_running = true;\n result = true;\n }\n }\n\n return result;\n}\n\nbool ControllerInterface::shutdown()\n{\n bool result = false;\n\n if (canSend()) {\n char msg[] = {'2', '\\0'};\n\n log_debug(\"Sending: \\\"%s\\\"\", msg);\n\n int ret = send(m_connectionSocket, msg, sizeof(msg), 0);\n if (ret == -1) {\n log_error() << \"send:\" << strerror(errno);\n } else {\n m_running = false;\n result = true;\n }\n }\n\n return result;\n}\n\nbool ControllerInterface::setEnvironmentVariable(const std::string &variable,\n const std::string &value)\n{\n bool result = false;\n\n if (canSend()) {\n std::string command = \"3 \" + variable + \" \" + value;\n char msg[command.size() + 1];\n\n memcpy(msg, command.c_str(), command.size());\n msg[command.size()] = '\\0';\n\n log_debug(\"Sending: \\\"%s\\\"\", msg);\n\n int ret = send(m_connectionSocket, msg, strlen(msg) + 1, 0);\n if (ret == -1) {\n log_error() << \"send:\" << strerror(errno);\n } else {\n result = true;\n }\n }\n\n return result;\n}\n\nbool ControllerInterface::systemCall(const std::string &cmd)\n{\n bool result = false;\n\n if (canSend()) {\n std::string command = \"4 \" + cmd;\n char msg[command.size() + 1];\n\n memcpy(msg, command.c_str(), command.size());\n msg[command.size()] = '\\0';\n\n log_debug(\"Sending: \\\"%s\\\"\", msg);\n\n int ret = send(m_connectionSocket, msg, strlen(msg) + 1, 0);\n if (ret == -1) {\n log_error() << \"send:\" << strerror(errno);\n } else {\n result = true;\n }\n }\n\n return result;\n}\n\nbool ControllerInterface::hasBeenStarted() const\n{\n return m_running;\n}\n\nbool ControllerInterface::canSend()\n{\n if (!m_connected) {\n log_error() << \"No connection to Controller\";\n return false;\n }\n\n fd_set sendfds;\n FD_ZERO(&sendfds);\n FD_SET(m_connectionSocket, &sendfds);\n\n int ret = select(m_highestFd + 1, 0, &sendfds, 0, &m_selectTimeout);\n if (ret == -1) {\n log_error() << \"select:\" << strerror(errno);\n return false;\n } else if (ret == 0) {\n log_error() << \"select reached timeout\";\n return false;\n }\n\n return FD_ISSET(m_connectionSocket, &sendfds) ? true : false;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"photoeffects.hpp\"\n#include <iostream>\n\nusing namespace cv;\nusing namespace std;\n\nconst char *ORIGINAL_IMAGE=\"Original image\";\nconst char *FILM_GRAIN_IMAGE=\"Film Grain image\";\nconst char *helper =\n\".\/filmGrain_sample <img> <value of grain>\\n\\\n\\t<img> - file name contained the processed image\\n\\\n\\t<value of grain> - degree graininess\\n\\\n\";\nint processArguments(int argc, char **argv, Mat &img, int &grainValue);\n\nint main(int argc, char** argv)\n{\n\n Mat src;\n int grainValue;\n if (processArguments(argc, argv, src, grainValue) != 0)\n {\n cout << helper << endl;\n return 1;\n }\n namedWindow(ORIGINAL_IMAGE, CV_WINDOW_AUTOSIZE);\n imshow(ORIGINAL_IMAGE, src);\n Mat dst;\n filmGrain(src, dst, grainValue, RNG(0));\n imshow(FILM_GRAIN_IMAGE, dst);\n cout << \"Press any key to EXIT\"<<endl;\n waitKey(0);\n return 0;\n}\n\nint processArguments(int argc, char **argv, Mat &img, int &grainValue)\n{\n if (argc < 3)\n {\n return 1;\n }\n img = imread(argv[1], CV_LOAD_IMAGE_COLOR);\n grainValue = atoi(argv[2]);\n return 0;\n}\n<commit_msg>some modification<commit_after>#include \"photoeffects.hpp\"\n#include <iostream>\n\nusing namespace cv;\nusing namespace std;\n\nconst char *ORIGINAL_IMAGE=\"Original image\";\nconst char *FILM_GRAIN_IMAGE=\"Film Grain image\";\nconst char *helper =\n\".\/filmGrain_sample <img> <value of grain>\\n\\\n\\t<img> - file name contained the processed image\\n\\\n\\t<value of grain> - degree graininess\\n\\\n\";\nint processArguments(int argc, char **argv, Mat &img, int &grainValue);\n\nint main(int argc, char** argv)\n{\n\n Mat src;\n int grainValue;\n if (processArguments(argc, argv, src, grainValue) != 0)\n {\n cout << helper << endl;\n return 1;\n }\n namedWindow(ORIGINAL_IMAGE, CV_WINDOW_AUTOSIZE);\n imshow(ORIGINAL_IMAGE, src);\n Mat dst;\n RNG rng=RNG(0);\n filmGrain(src, dst, grainValue, rng);\n imshow(FILM_GRAIN_IMAGE, dst);\n cout << \"Press any key to EXIT\"<<endl;\n waitKey(0);\n return 0;\n}\n\nint processArguments(int argc, char **argv, Mat &img, int &grainValue)\n{\n if (argc < 3)\n {\n return 1;\n }\n img = imread(argv[1], CV_LOAD_IMAGE_COLOR);\n grainValue = atoi(argv[2]);\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/=-- InstrProf.cpp - Instrumented profiling format support -----------------=\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This file contains support for clang's instrumentation based PGO and\n\/\/ coverage.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/IR\/Constants.h\"\n#include \"llvm\/IR\/Function.h\"\n#include \"llvm\/IR\/Module.h\"\n#include \"llvm\/IR\/GlobalVariable.h\"\n#include \"llvm\/ProfileData\/InstrProf.h\"\n#include \"llvm\/Support\/ErrorHandling.h\"\n#include \"llvm\/Support\/ManagedStatic.h\"\n\nusing namespace llvm;\n\nnamespace {\nclass InstrProfErrorCategoryType : public std::error_category {\n const char *name() const LLVM_NOEXCEPT override { return \"llvm.instrprof\"; }\n std::string message(int IE) const override {\n instrprof_error E = static_cast<instrprof_error>(IE);\n switch (E) {\n case instrprof_error::success:\n return \"Success\";\n case instrprof_error::eof:\n return \"End of File\";\n case instrprof_error::unrecognized_format:\n return \"Unrecognized instrumentation profile encoding format\";\n case instrprof_error::bad_magic:\n return \"Invalid instrumentation profile data (bad magic)\";\n case instrprof_error::bad_header:\n return \"Invalid instrumentation profile data (file header is corrupt)\";\n case instrprof_error::unsupported_version:\n return \"Unsupported instrumentation profile format version\";\n case instrprof_error::unsupported_hash_type:\n return \"Unsupported instrumentation profile hash type\";\n case instrprof_error::too_large:\n return \"Too much profile data\";\n case instrprof_error::truncated:\n return \"Truncated profile data\";\n case instrprof_error::malformed:\n return \"Malformed instrumentation profile data\";\n case instrprof_error::unknown_function:\n return \"No profile data available for function\";\n case instrprof_error::hash_mismatch:\n return \"Function control flow change detected (hash mismatch)\";\n case instrprof_error::count_mismatch:\n return \"Function basic block count change detected (counter mismatch)\";\n case instrprof_error::counter_overflow:\n return \"Counter overflow\";\n case instrprof_error::value_site_count_mismatch:\n return \"Function value site count change detected (counter mismatch)\";\n }\n llvm_unreachable(\"A value of instrprof_error has no message.\");\n }\n};\n}\n\nstatic ManagedStatic<InstrProfErrorCategoryType> ErrorCategory;\n\nconst std::error_category &llvm::instrprof_category() {\n return *ErrorCategory;\n}\n\nnamespace llvm {\n\nstd::string getPGOFuncName(StringRef RawFuncName,\n GlobalValue::LinkageTypes Linkage,\n StringRef FileName) {\n\n \/\/ Function names may be prefixed with a binary '1' to indicate\n \/\/ that the backend should not modify the symbols due to any platform\n \/\/ naming convention. Do not include that '1' in the PGO profile name.\n if (RawFuncName[0] == '\\1')\n RawFuncName = RawFuncName.substr(1);\n\n std::string FuncName = RawFuncName;\n if (llvm::GlobalValue::isLocalLinkage(Linkage)) {\n \/\/ For local symbols, prepend the main file name to distinguish them.\n \/\/ Do not include the full path in the file name since there's no guarantee\n \/\/ that it will stay the same, e.g., if the files are checked out from\n \/\/ version control in different locations.\n if (FileName.empty())\n FuncName = FuncName.insert(0, \"<unknown>:\");\n else\n FuncName = FuncName.insert(0, FileName.str() + \":\");\n }\n return FuncName;\n}\n\nstd::string getPGOFuncName(const Function &F) {\n return getPGOFuncName(F.getName(), F.getLinkage(), F.getParent()->getName());\n}\n\nGlobalVariable *createPGOFuncNameVar(Module &M,\n GlobalValue::LinkageTypes Linkage,\n StringRef FuncName) {\n\n \/\/ We generally want to match the function's linkage, but available_externally\n \/\/ and extern_weak both have the wrong semantics, and anything that doesn't\n \/\/ need to link across compilation units doesn't need to be visible at all.\n if (Linkage == GlobalValue::ExternalWeakLinkage)\n Linkage = GlobalValue::LinkOnceAnyLinkage;\n else if (Linkage == GlobalValue::AvailableExternallyLinkage)\n Linkage = GlobalValue::LinkOnceODRLinkage;\n else if (Linkage == GlobalValue::InternalLinkage ||\n Linkage == GlobalValue::ExternalLinkage)\n Linkage = GlobalValue::PrivateLinkage;\n\n auto *Value = ConstantDataArray::getString(M.getContext(), FuncName, false);\n auto FuncNameVar =\n new GlobalVariable(M, Value->getType(), true, Linkage, Value,\n Twine(getInstrProfNameVarPrefix()) + FuncName);\n\n \/\/ Hide the symbol so that we correctly get a copy for each executable.\n if (!GlobalValue::isLocalLinkage(FuncNameVar->getLinkage()))\n FuncNameVar->setVisibility(GlobalValue::HiddenVisibility);\n\n return FuncNameVar;\n}\n\nGlobalVariable *createPGOFuncNameVar(Function &F, StringRef FuncName) {\n return createPGOFuncNameVar(*F.getParent(), F.getLinkage(), FuncName);\n}\n\nuint64_t stringToHash(uint32_t ValueKind, uint64_t Value) {\n switch (ValueKind) {\n case IPVK_IndirectCallTarget:\n return IndexedInstrProf::ComputeHash(IndexedInstrProf::HashType,\n (const char *)Value);\n break;\n default:\n llvm_unreachable(\"value kind not handled !\");\n }\n return Value;\n}\n\nvoid ValueProfRecord::deserializeTo(InstrProfRecord &Record,\n InstrProfRecord::ValueMapType *VMap) {\n Record.reserveSites(Kind, NumValueSites);\n\n InstrProfValueData *ValueData = this->getValueData();\n for (uint64_t VSite = 0; VSite < NumValueSites; ++VSite) {\n uint8_t ValueDataCount = this->SiteCountArray[VSite];\n Record.addValueData(Kind, VSite, ValueData, ValueDataCount, VMap);\n ValueData += ValueDataCount;\n }\n}\n\nvoid ValueProfRecord::serializeFrom(const InstrProfRecord &Record,\n uint32_t ValueKind,\n uint32_t NumValueSites) {\n Kind = ValueKind;\n this->NumValueSites = NumValueSites;\n InstrProfValueData *DstVD = getValueData();\n for (uint32_t S = 0; S < NumValueSites; S++) {\n uint32_t ND = Record.getNumValueDataForSite(ValueKind, S);\n SiteCountArray[S] = ND;\n Record.getValueForSite(DstVD, ValueKind, S, stringToHash);\n DstVD += ND;\n }\n}\n\ntemplate <class T>\nstatic T swapToHostOrder(const unsigned char *&D, support::endianness Orig) {\n using namespace support;\n if (Orig == little)\n return endian::readNext<T, little, unaligned>(D);\n else\n return endian::readNext<T, big, unaligned>(D);\n}\n\n\/\/ For writing\/serializing, Old is the host endianness, and New is\n\/\/ byte order intended on disk. For Reading\/deserialization, Old\n\/\/ is the on-disk source endianness, and New is the host endianness.\nvoid ValueProfRecord::swapBytes(support::endianness Old,\n support::endianness New) {\n using namespace support;\n if (Old == New)\n return;\n\n if (getHostEndianness() != Old) {\n sys::swapByteOrder<uint32_t>(NumValueSites);\n sys::swapByteOrder<uint32_t>(Kind);\n }\n uint32_t ND = getNumValueData();\n InstrProfValueData *VD = getValueData();\n\n \/\/ No need to swap byte array: SiteCountArrray.\n for (uint32_t I = 0; I < ND; I++) {\n sys::swapByteOrder<uint64_t>(VD[I].Value);\n sys::swapByteOrder<uint64_t>(VD[I].Count);\n }\n if (getHostEndianness() == Old) {\n sys::swapByteOrder<uint32_t>(NumValueSites);\n sys::swapByteOrder<uint32_t>(Kind);\n }\n}\n\nuint32_t ValueProfData::getSize(const InstrProfRecord &Record) {\n uint32_t TotalSize = sizeof(ValueProfData);\n uint32_t NumValueKinds = Record.getNumValueKinds();\n if (NumValueKinds == 0)\n return TotalSize;\n\n for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; Kind++) {\n uint32_t NumValueSites = Record.getNumValueSites(Kind);\n if (!NumValueSites)\n continue;\n TotalSize +=\n getValueProfRecordSize(NumValueSites, Record.getNumValueData(Kind));\n }\n return TotalSize;\n}\n\nvoid ValueProfData::deserializeTo(InstrProfRecord &Record,\n InstrProfRecord::ValueMapType *VMap) {\n if (NumValueKinds == 0)\n return;\n\n ValueProfRecord *VR = getFirstValueProfRecord();\n for (uint32_t K = 0; K < NumValueKinds; K++) {\n VR->deserializeTo(Record, VMap);\n VR = VR->getNext();\n }\n}\n\nstatic std::unique_ptr<ValueProfData> AllocValueProfData(uint32_t TotalSize) {\n return std::unique_ptr<ValueProfData>(new (::operator new(TotalSize))\n ValueProfData());\n}\n\nstd::unique_ptr<ValueProfData>\nValueProfData::serializeFrom(const InstrProfRecord &Record) {\n uint32_t TotalSize = getSize(Record);\n\n std::unique_ptr<ValueProfData> VPD = AllocValueProfData(TotalSize);\n\n VPD->TotalSize = TotalSize;\n VPD->NumValueKinds = Record.getNumValueKinds();\n ValueProfRecord *VR = VPD->getFirstValueProfRecord();\n for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; Kind++) {\n uint32_t NumValueSites = Record.getNumValueSites(Kind);\n if (!NumValueSites)\n continue;\n VR->serializeFrom(Record, Kind, NumValueSites);\n VR = VR->getNext();\n }\n return VPD;\n}\n\nErrorOr<std::unique_ptr<ValueProfData>>\nValueProfData::getValueProfData(const unsigned char *D,\n const unsigned char *const BufferEnd,\n support::endianness Endianness) {\n using namespace support;\n if (D + sizeof(ValueProfData) > BufferEnd)\n return instrprof_error::truncated;\n\n const unsigned char *Header = D;\n uint32_t TotalSize = swapToHostOrder<uint32_t>(Header, Endianness);\n uint32_t NumValueKinds = swapToHostOrder<uint32_t>(Header, Endianness);\n\n if (D + TotalSize > BufferEnd)\n return instrprof_error::too_large;\n if (NumValueKinds > IPVK_Last + 1)\n return instrprof_error::malformed;\n \/\/ Total size needs to be mulltiple of quadword size.\n if (TotalSize % sizeof(uint64_t))\n return instrprof_error::malformed;\n\n std::unique_ptr<ValueProfData> VPD = AllocValueProfData(TotalSize);\n\n memcpy(VPD.get(), D, TotalSize);\n \/\/ Byte swap.\n VPD->swapBytesToHost(Endianness);\n\n \/\/ Data integrety check:\n ValueProfRecord *VR = VPD->getFirstValueProfRecord();\n for (uint32_t K = 0; K < VPD->NumValueKinds; K++) {\n if (VR->Kind > IPVK_Last)\n return instrprof_error::malformed;\n VR = VR->getNext();\n if ((char *)VR - (char *)VPD.get() > (ptrdiff_t)TotalSize)\n return instrprof_error::malformed;\n }\n\n return std::move(VPD);\n}\n\nvoid ValueProfData::swapBytesToHost(support::endianness Endianness) {\n using namespace support;\n if (Endianness == getHostEndianness())\n return;\n\n sys::swapByteOrder<uint32_t>(TotalSize);\n sys::swapByteOrder<uint32_t>(NumValueKinds);\n\n ValueProfRecord *VR = getFirstValueProfRecord();\n for (uint32_t K = 0; K < NumValueKinds; K++) {\n VR->swapBytes(Endianness, getHostEndianness());\n VR = VR->getNext();\n }\n}\n\nvoid ValueProfData::swapBytesFromHost(support::endianness Endianness) {\n using namespace support;\n if (Endianness == getHostEndianness())\n return;\n\n ValueProfRecord *VR = getFirstValueProfRecord();\n for (uint32_t K = 0; K < NumValueKinds; K++) {\n ValueProfRecord *NVR = VR->getNext();\n VR->swapBytes(getHostEndianness(), Endianness);\n VR = NVR;\n }\n sys::swapByteOrder<uint32_t>(TotalSize);\n sys::swapByteOrder<uint32_t>(NumValueKinds);\n}\n\nValueProfRecord *ValueProfData::getFirstValueProfRecord() {\n return reinterpret_cast<ValueProfRecord *>((char *)this +\n sizeof(ValueProfData));\n}\n\nuint32_t ValueProfRecord::getNumValueData() const {\n uint32_t NumValueData = 0;\n for (uint32_t I = 0; I < NumValueSites; I++)\n NumValueData += SiteCountArray[I];\n return NumValueData;\n}\n\nValueProfRecord *ValueProfRecord::getNext() {\n return reinterpret_cast<ValueProfRecord *>((char *)this + getSize());\n}\n\nInstrProfValueData *ValueProfRecord::getValueData() {\n return reinterpret_cast<InstrProfValueData *>(\n (char *)this + getValueProfRecordHeaderSize(NumValueSites));\n}\n}\n<commit_msg>Move member functions closer to others of the same class (NFC)<commit_after>\/\/=-- InstrProf.cpp - Instrumented profiling format support -----------------=\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This file contains support for clang's instrumentation based PGO and\n\/\/ coverage.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/IR\/Constants.h\"\n#include \"llvm\/IR\/Function.h\"\n#include \"llvm\/IR\/Module.h\"\n#include \"llvm\/IR\/GlobalVariable.h\"\n#include \"llvm\/ProfileData\/InstrProf.h\"\n#include \"llvm\/Support\/ErrorHandling.h\"\n#include \"llvm\/Support\/ManagedStatic.h\"\n\nusing namespace llvm;\n\nnamespace {\nclass InstrProfErrorCategoryType : public std::error_category {\n const char *name() const LLVM_NOEXCEPT override { return \"llvm.instrprof\"; }\n std::string message(int IE) const override {\n instrprof_error E = static_cast<instrprof_error>(IE);\n switch (E) {\n case instrprof_error::success:\n return \"Success\";\n case instrprof_error::eof:\n return \"End of File\";\n case instrprof_error::unrecognized_format:\n return \"Unrecognized instrumentation profile encoding format\";\n case instrprof_error::bad_magic:\n return \"Invalid instrumentation profile data (bad magic)\";\n case instrprof_error::bad_header:\n return \"Invalid instrumentation profile data (file header is corrupt)\";\n case instrprof_error::unsupported_version:\n return \"Unsupported instrumentation profile format version\";\n case instrprof_error::unsupported_hash_type:\n return \"Unsupported instrumentation profile hash type\";\n case instrprof_error::too_large:\n return \"Too much profile data\";\n case instrprof_error::truncated:\n return \"Truncated profile data\";\n case instrprof_error::malformed:\n return \"Malformed instrumentation profile data\";\n case instrprof_error::unknown_function:\n return \"No profile data available for function\";\n case instrprof_error::hash_mismatch:\n return \"Function control flow change detected (hash mismatch)\";\n case instrprof_error::count_mismatch:\n return \"Function basic block count change detected (counter mismatch)\";\n case instrprof_error::counter_overflow:\n return \"Counter overflow\";\n case instrprof_error::value_site_count_mismatch:\n return \"Function value site count change detected (counter mismatch)\";\n }\n llvm_unreachable(\"A value of instrprof_error has no message.\");\n }\n};\n}\n\nstatic ManagedStatic<InstrProfErrorCategoryType> ErrorCategory;\n\nconst std::error_category &llvm::instrprof_category() {\n return *ErrorCategory;\n}\n\nnamespace llvm {\n\nstd::string getPGOFuncName(StringRef RawFuncName,\n GlobalValue::LinkageTypes Linkage,\n StringRef FileName) {\n\n \/\/ Function names may be prefixed with a binary '1' to indicate\n \/\/ that the backend should not modify the symbols due to any platform\n \/\/ naming convention. Do not include that '1' in the PGO profile name.\n if (RawFuncName[0] == '\\1')\n RawFuncName = RawFuncName.substr(1);\n\n std::string FuncName = RawFuncName;\n if (llvm::GlobalValue::isLocalLinkage(Linkage)) {\n \/\/ For local symbols, prepend the main file name to distinguish them.\n \/\/ Do not include the full path in the file name since there's no guarantee\n \/\/ that it will stay the same, e.g., if the files are checked out from\n \/\/ version control in different locations.\n if (FileName.empty())\n FuncName = FuncName.insert(0, \"<unknown>:\");\n else\n FuncName = FuncName.insert(0, FileName.str() + \":\");\n }\n return FuncName;\n}\n\nstd::string getPGOFuncName(const Function &F) {\n return getPGOFuncName(F.getName(), F.getLinkage(), F.getParent()->getName());\n}\n\nGlobalVariable *createPGOFuncNameVar(Module &M,\n GlobalValue::LinkageTypes Linkage,\n StringRef FuncName) {\n\n \/\/ We generally want to match the function's linkage, but available_externally\n \/\/ and extern_weak both have the wrong semantics, and anything that doesn't\n \/\/ need to link across compilation units doesn't need to be visible at all.\n if (Linkage == GlobalValue::ExternalWeakLinkage)\n Linkage = GlobalValue::LinkOnceAnyLinkage;\n else if (Linkage == GlobalValue::AvailableExternallyLinkage)\n Linkage = GlobalValue::LinkOnceODRLinkage;\n else if (Linkage == GlobalValue::InternalLinkage ||\n Linkage == GlobalValue::ExternalLinkage)\n Linkage = GlobalValue::PrivateLinkage;\n\n auto *Value = ConstantDataArray::getString(M.getContext(), FuncName, false);\n auto FuncNameVar =\n new GlobalVariable(M, Value->getType(), true, Linkage, Value,\n Twine(getInstrProfNameVarPrefix()) + FuncName);\n\n \/\/ Hide the symbol so that we correctly get a copy for each executable.\n if (!GlobalValue::isLocalLinkage(FuncNameVar->getLinkage()))\n FuncNameVar->setVisibility(GlobalValue::HiddenVisibility);\n\n return FuncNameVar;\n}\n\nGlobalVariable *createPGOFuncNameVar(Function &F, StringRef FuncName) {\n return createPGOFuncNameVar(*F.getParent(), F.getLinkage(), FuncName);\n}\n\nuint64_t stringToHash(uint32_t ValueKind, uint64_t Value) {\n switch (ValueKind) {\n case IPVK_IndirectCallTarget:\n return IndexedInstrProf::ComputeHash(IndexedInstrProf::HashType,\n (const char *)Value);\n break;\n default:\n llvm_unreachable(\"value kind not handled !\");\n }\n return Value;\n}\n\nuint32_t ValueProfRecord::getNumValueData() const {\n uint32_t NumValueData = 0;\n for (uint32_t I = 0; I < NumValueSites; I++)\n NumValueData += SiteCountArray[I];\n return NumValueData;\n}\n\nValueProfRecord *ValueProfRecord::getNext() {\n return reinterpret_cast<ValueProfRecord *>((char *)this + getSize());\n}\n\nInstrProfValueData *ValueProfRecord::getValueData() {\n return reinterpret_cast<InstrProfValueData *>(\n (char *)this + getValueProfRecordHeaderSize(NumValueSites));\n}\n\nvoid ValueProfRecord::deserializeTo(InstrProfRecord &Record,\n InstrProfRecord::ValueMapType *VMap) {\n Record.reserveSites(Kind, NumValueSites);\n\n InstrProfValueData *ValueData = this->getValueData();\n for (uint64_t VSite = 0; VSite < NumValueSites; ++VSite) {\n uint8_t ValueDataCount = this->SiteCountArray[VSite];\n Record.addValueData(Kind, VSite, ValueData, ValueDataCount, VMap);\n ValueData += ValueDataCount;\n }\n}\n\nvoid ValueProfRecord::serializeFrom(const InstrProfRecord &Record,\n uint32_t ValueKind,\n uint32_t NumValueSites) {\n Kind = ValueKind;\n this->NumValueSites = NumValueSites;\n InstrProfValueData *DstVD = getValueData();\n for (uint32_t S = 0; S < NumValueSites; S++) {\n uint32_t ND = Record.getNumValueDataForSite(ValueKind, S);\n SiteCountArray[S] = ND;\n Record.getValueForSite(DstVD, ValueKind, S, stringToHash);\n DstVD += ND;\n }\n}\n\ntemplate <class T>\nstatic T swapToHostOrder(const unsigned char *&D, support::endianness Orig) {\n using namespace support;\n if (Orig == little)\n return endian::readNext<T, little, unaligned>(D);\n else\n return endian::readNext<T, big, unaligned>(D);\n}\n\n\/\/ For writing\/serializing, Old is the host endianness, and New is\n\/\/ byte order intended on disk. For Reading\/deserialization, Old\n\/\/ is the on-disk source endianness, and New is the host endianness.\nvoid ValueProfRecord::swapBytes(support::endianness Old,\n support::endianness New) {\n using namespace support;\n if (Old == New)\n return;\n\n if (getHostEndianness() != Old) {\n sys::swapByteOrder<uint32_t>(NumValueSites);\n sys::swapByteOrder<uint32_t>(Kind);\n }\n uint32_t ND = getNumValueData();\n InstrProfValueData *VD = getValueData();\n\n \/\/ No need to swap byte array: SiteCountArrray.\n for (uint32_t I = 0; I < ND; I++) {\n sys::swapByteOrder<uint64_t>(VD[I].Value);\n sys::swapByteOrder<uint64_t>(VD[I].Count);\n }\n if (getHostEndianness() == Old) {\n sys::swapByteOrder<uint32_t>(NumValueSites);\n sys::swapByteOrder<uint32_t>(Kind);\n }\n}\n\nuint32_t ValueProfData::getSize(const InstrProfRecord &Record) {\n uint32_t TotalSize = sizeof(ValueProfData);\n uint32_t NumValueKinds = Record.getNumValueKinds();\n if (NumValueKinds == 0)\n return TotalSize;\n\n for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; Kind++) {\n uint32_t NumValueSites = Record.getNumValueSites(Kind);\n if (!NumValueSites)\n continue;\n TotalSize +=\n getValueProfRecordSize(NumValueSites, Record.getNumValueData(Kind));\n }\n return TotalSize;\n}\n\nvoid ValueProfData::deserializeTo(InstrProfRecord &Record,\n InstrProfRecord::ValueMapType *VMap) {\n if (NumValueKinds == 0)\n return;\n\n ValueProfRecord *VR = getFirstValueProfRecord();\n for (uint32_t K = 0; K < NumValueKinds; K++) {\n VR->deserializeTo(Record, VMap);\n VR = VR->getNext();\n }\n}\n\nstatic std::unique_ptr<ValueProfData> AllocValueProfData(uint32_t TotalSize) {\n return std::unique_ptr<ValueProfData>(new (::operator new(TotalSize))\n ValueProfData());\n}\n\nstd::unique_ptr<ValueProfData>\nValueProfData::serializeFrom(const InstrProfRecord &Record) {\n uint32_t TotalSize = getSize(Record);\n\n std::unique_ptr<ValueProfData> VPD = AllocValueProfData(TotalSize);\n\n VPD->TotalSize = TotalSize;\n VPD->NumValueKinds = Record.getNumValueKinds();\n ValueProfRecord *VR = VPD->getFirstValueProfRecord();\n for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; Kind++) {\n uint32_t NumValueSites = Record.getNumValueSites(Kind);\n if (!NumValueSites)\n continue;\n VR->serializeFrom(Record, Kind, NumValueSites);\n VR = VR->getNext();\n }\n return VPD;\n}\n\nErrorOr<std::unique_ptr<ValueProfData>>\nValueProfData::getValueProfData(const unsigned char *D,\n const unsigned char *const BufferEnd,\n support::endianness Endianness) {\n using namespace support;\n if (D + sizeof(ValueProfData) > BufferEnd)\n return instrprof_error::truncated;\n\n const unsigned char *Header = D;\n uint32_t TotalSize = swapToHostOrder<uint32_t>(Header, Endianness);\n uint32_t NumValueKinds = swapToHostOrder<uint32_t>(Header, Endianness);\n\n if (D + TotalSize > BufferEnd)\n return instrprof_error::too_large;\n if (NumValueKinds > IPVK_Last + 1)\n return instrprof_error::malformed;\n \/\/ Total size needs to be mulltiple of quadword size.\n if (TotalSize % sizeof(uint64_t))\n return instrprof_error::malformed;\n\n std::unique_ptr<ValueProfData> VPD = AllocValueProfData(TotalSize);\n\n memcpy(VPD.get(), D, TotalSize);\n \/\/ Byte swap.\n VPD->swapBytesToHost(Endianness);\n\n \/\/ Data integrety check:\n ValueProfRecord *VR = VPD->getFirstValueProfRecord();\n for (uint32_t K = 0; K < VPD->NumValueKinds; K++) {\n if (VR->Kind > IPVK_Last)\n return instrprof_error::malformed;\n VR = VR->getNext();\n if ((char *)VR - (char *)VPD.get() > (ptrdiff_t)TotalSize)\n return instrprof_error::malformed;\n }\n\n return std::move(VPD);\n}\n\nvoid ValueProfData::swapBytesToHost(support::endianness Endianness) {\n using namespace support;\n if (Endianness == getHostEndianness())\n return;\n\n sys::swapByteOrder<uint32_t>(TotalSize);\n sys::swapByteOrder<uint32_t>(NumValueKinds);\n\n ValueProfRecord *VR = getFirstValueProfRecord();\n for (uint32_t K = 0; K < NumValueKinds; K++) {\n VR->swapBytes(Endianness, getHostEndianness());\n VR = VR->getNext();\n }\n}\n\nvoid ValueProfData::swapBytesFromHost(support::endianness Endianness) {\n using namespace support;\n if (Endianness == getHostEndianness())\n return;\n\n ValueProfRecord *VR = getFirstValueProfRecord();\n for (uint32_t K = 0; K < NumValueKinds; K++) {\n ValueProfRecord *NVR = VR->getNext();\n VR->swapBytes(getHostEndianness(), Endianness);\n VR = NVR;\n }\n sys::swapByteOrder<uint32_t>(TotalSize);\n sys::swapByteOrder<uint32_t>(NumValueKinds);\n}\n\nValueProfRecord *ValueProfData::getFirstValueProfRecord() {\n return reinterpret_cast<ValueProfRecord *>((char *)this +\n sizeof(ValueProfData));\n}\n\n}\n\n<|endoftext|>"} {"text":"<commit_before>#include <cmath>\n#include <iostream>\n#include <string>\n#include <vector>\n\n#define MAX_M 4096\n#define MAX_m 12\n\nusing namespace std;\n\nint main(int argc, char const *argv[]) {\n int t; \/\/ test cases\n int M, e, max_query_allowed; \/\/ a test case\n int the_real_M; \/\/ trick if M isn't power of 2\n\n string code[MAX_m][MAX_M]; \/\/ all the codewords\n bool is_code[MAX_m]; \/\/ has the codeword been made?\n int code_distance[MAX_m][MAX_M]; \/\/ only distance from 0 to 1..M\n int code_min[MAX_m]; \/\/ min distance\n int code_order[MAX_m][MAX_M]; \/\/ the best efficient order of code\n int code_order_pointer[MAX_m]; \/\/ how many codeword is sorted?\n bool code_order_check[MAX_m][MAX_M]; \/\/ is the codeword sorted?\n int code_minimal[MAX_m][MAX_M\/2+2]; \/\/ param: d needed; return: query\n\n cin >> t;\n while (t--) {\n cin >> M >> e >> max_query_allowed;\n\n the_real_M = M;\n M = pow(2, ceil(log2(M))); \/\/ M is the closest power(2)\n\n int m = log2(M); \/\/ log2(M)\n int d = (2*e + 1); \/\/ minimal distance\n\n \/* initial coding, if hasnt made yet *\/\n if (!is_code[m]) {\n is_code[m] = 1;\n \/* Make a perfect (M-1,M,M\/2) binary code *\/\n for (int i = 1; i < M; ++i) {\n string ans = \"\";\n \/* binary start from 0 to M *\/\n for (int j = 0; j < M; ++j) {\n int bitstring = i & j;\n short binary = 0;\n \/* counting bit set *\/\n for (binary = 0; bitstring; bitstring >>= 1) {\n binary ^= bitstring & 1;\n }\n ans += '0' + binary;\n }\n code[m][i] = ans;\n }\n\n \/* generate initial code order (m,M,1) *\/\n int two = 1; \/\/ power of two\n for (int i = 0; i < m; ++i, two <<= 1) {\n code_order[m][code_order_pointer[m]++] = two;\n code_order_check[m][two] = 1;\n for (int j = 1; j < M; ++j) { \/\/ update the distances\n code_distance[m][j] += (code[m][two][0] != code[m][two][j]);\n }\n }\n code_min[m] = 1;\n code_minimal[m][1] = code_order_pointer[m];\n }\n\n \/* find the best order *\/\n while (code_min[m] < d && code_min[m] < M\/2) {\n int best = 0;\n int delta = MAX_M;\n \/* each loop find the one best code order candidate *\/\n for (int i = 1; i < M; ++i) {\n int min = MAX_M;\n int max = 0;\n if (code_order_check[m][i]) continue;\n for (int j = 1; j < M; ++j) { \/\/ test the distance\n int local = code_distance[m][j] + (code[m][i][0] != code[m][i][j]);\n if (local > max) max = local;\n if (local < min) min = local;\n }\n if (max - min < delta) { \/\/ save the best\n best = i;\n delta = max - min;\n }\n }\n\n \/* update the distance *\/\n code_min[m] = MAX_M;\n for (int j = 1; j < M; ++j) {\n code_distance[m][j] += (code[m][best][0] != code[m][best][j]);\n if (code_distance[m][j] < code_min[m]) {\n code_min[m] = code_distance[m][j];\n }\n }\n\n \/* update the code order *\/\n code_order[m][code_order_pointer[m]++] = best;\n code_order_check[m][best] = 1;\n if (code_minimal[m][code_min[m]] == 0) {\n code_minimal[m][code_min[m]] = code_order_pointer[m];\n }\n }\n\n \/* Debug code_minimal *\n for (int i = 1; i < M\/2 + 1; ++i) {\n cout << code_minimal[m][i] << \"|\";\n }\n cout << endl;\n \/\/*\/\n\n \/* total query needed *\/\n int rounds = d \/ (M \/ 2);\n int mod = d % (M \/ 2);\n bool new_algo = code_minimal[m][mod] < mod * m;\n int total = rounds * (M - 1) + (new_algo ? code_minimal[m][mod] : mod * m);\n\n \/\/ cout << (new_algo? \"true \" : \"false \");\n cout << total << endl;\n\n for (int i = 0; i < rounds; ++i) { \/\/ round query\n for (int j = 1; j < M; ++j) {\n cout << code[m][j].substr(0, the_real_M) << endl;\n }\n }\n if (new_algo) {\n for (int i = 0; i < code_minimal[m][mod]; ++i) { \/\/ mod query\n cout << code[m][code_order[m][i]].substr(0, the_real_M) << endl;\n }\n } else {\n for (int i = 0; i < mod; ++i) { \/\/ old query\n for (int j = 0; j < m; ++j) {\n cout << code[m][code_order[m][j]].substr(0, the_real_M) << endl;\n }\n }\n }\n }\n return 0;\n}<commit_msg>bruteforce ordering: min then min_count<commit_after>#include <cmath>\n#include <cstdio>\n#include <cstdlib>\n#include <cstring>\n#include <string>\n#include <vector>\nusing namespace std;\n\n#define MAX_M 4096\n#define MAX_m 12\n\n\/**\n * Print first n bit of a code\n *\/\nvoid print_codeword(char *code, int n) {\n for (int i = 0; i < n; ++i) {\n putchar(code[i]);\n }\n putchar('\\n');\n}\n\nint main(int argc, char const *argv[]) {\n int t; \/\/ test cases\n int M, e, max_query_allowed; \/\/ a test case\n int the_real_M; \/\/ trick if M isn't power of 2\n\n \/\/ string code[MAX_m][MAX_M]; \/\/ all the codewords\n char **code[MAX_m]; \/\/ all the codewords\n bool is_code[MAX_m]; \/\/ has the codeword been made?\n int code_distance[MAX_m][MAX_M]; \/\/ only distance from 0 to 1..M\n int code_min[MAX_m]; \/\/ min distance\n int code_order[MAX_m][MAX_M]; \/\/ the best efficient order of code\n int code_order_pointer[MAX_m]; \/\/ how many codeword is sorted?\n bool code_order_check[MAX_m][MAX_M]; \/\/ is the codeword sorted?\n int code_minimal[MAX_m][MAX_M\/2+2]; \/\/ param: d needed; return: query\n\n scanf(\"%d\", &t);\n while (t--) {\n scanf(\"%d%d%d\", &M, &e, &max_query_allowed);\n int d = (2*e + 1); \/\/ minimal distance\n the_real_M = M; \/\/ save the real M for printing the query\n\n \/* M must be power of two *\/\n int m = ceil(log2(M)); \/\/ log2(M)\n M = pow(2, m); \/\/ M is the closest power(2)\n\n \/* initial coding, if hasnt made yet *\/\n if (!is_code[m]) {\n is_code[m] = 1;\n \/* Make a perfect (M-1,M,M\/2) binary code *\/\n code[m] = (char**) malloc(sizeof(char*) * M);\n char ans[M+1];\n for (int i = 1; i < M; ++i) {\n \/* binary start from 0 to M *\/\n for (int j = 0; j < M; ++j) {\n int bitstring = i & j;\n short binary = 0;\n \/* counting bit set *\/\n for (binary = 0; bitstring; bitstring >>= 1) {\n binary ^= bitstring & 1;\n }\n ans[j] = '0' + binary;\n }\n ans[M] = 0; \/\/ close the string\n code[m][i] = strdup(ans);\n }\n }\n\n \/* find the best order *\/\n while (code_min[m] < d && code_min[m] < M\/2) {\n int best = 0; \/\/ best candidate\n int best_min = 0; \/\/ most\n int best_max = MAX_M; \/\/ least\n int best_min_count = MAX_M; \/\/ least\n int best_max_count = MAX_M; \/\/ least\n \/* each loop find the one best code order candidate *\/\n for (int i = 1; i < M; ++i) {\n int min = MAX_M;\n int max = 0;\n int min_count, max_count;\n if (code_order_check[m][i]) continue; \/\/ skip used code\n for (int j = 1; j < M; ++j) { \/\/ test the distance\n int local = code_distance[m][j] + (code[m][i][0] != code[m][i][j]);\n if (local >= max) {\n if (local == max) {\n max_count++;\n } else {\n max = local;\n max_count = 1;\n }\n }\n if (local <= min) {\n if (local == min) {\n min_count++;\n } else {\n min = local;\n min_count = 1;\n }\n }\n }\n \/* save the best *\/\n if (min > best_min || (min == best_min && min_count < best_min_count)) {\n best = i;\n best_min = min;\n best_max = max;\n best_min_count = min_count;\n }\n }\n\n \/* update the distance *\/\n code_min[m] = MAX_M;\n for (int j = 1; j < M; ++j) {\n code_distance[m][j] += (code[m][best][0] != code[m][best][j]);\n if (code_distance[m][j] < code_min[m]) {\n code_min[m] = code_distance[m][j];\n }\n }\n\n \/* update the code order *\/\n code_order[m][code_order_pointer[m]++] = best;\n code_order_check[m][best] = 1;\n if (code_minimal[m][code_min[m]] == 0) {\n code_minimal[m][code_min[m]] = code_order_pointer[m];\n }\n }\n\n \/* Debug: show code_minimal *\n for (int i = 1; i < M\/2 + 1; ++i) {\n cout << code_minimal[m][i] << \"|\";\n }\n cout << endl;\n \/\/*\/\n\n \/* total query needed *\/\n int rounds = d \/ (M \/ 2);\n int mod = d % (M \/ 2);\n bool new_algo = code_minimal[m][mod] <= mod * m;\n int total = rounds * (M - 1) + (new_algo ? code_minimal[m][mod] : mod * m);\n\n printf(\"%d\\t%d\\t%s\\t\", M, e, new_algo? \"1\" : \"0\");\n printf(\"%d\\n\", total);\n\n continue; \/\/ Debug: skip print the codes\n for (int i = 0; i < rounds; ++i) { \/\/ round query\n for (int j = 1; j < M; ++j) {\n print_codeword(code[m][j], the_real_M);\n }\n }\n if (new_algo) {\n for (int i = 0; i < code_minimal[m][mod]; ++i) { \/\/ mod query\n print_codeword(code[m][code_order[m][i]], the_real_M);\n }\n } else {\n for (int i = 0; i < mod; ++i) { \/\/ old query\n for (int j = 0; j < m; ++j) {\n print_codeword(code[m][code_order[m][j]], the_real_M);\n }\n }\n }\n }\n int two = 1;\n for (int i = 0; i < MAX_m; ++i, two <<= 1) {\n free(code[i]);\n \/* Debug: show the generated code order *\/\n if (is_code[i]) {\n printf(\"%d:\", two);\n for (int j = 0; j < code_order_pointer[i]; ++j) {\n printf(\" %d\", code_order[i][j]);\n }\n printf(\"\\n\");\n }\n }\n return 0;\n}<|endoftext|>"} {"text":"<commit_before>\/******************************************************************************\n* SOFA, Simulation Open-Framework Architecture, version 1.0 RC 1 *\n* (c) 2006-2011 INRIA, USTL, UJF, CNRS, MGH *\n* *\n* This program is free software; you can redistribute it and\/or modify it *\n* under the terms of the GNU General Public License as published by the Free *\n* Software Foundation; either version 2 of the License, or (at your option) *\n* any later version. *\n* *\n* This program is distributed in the hope that it will be useful, but WITHOUT *\n* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or *\n* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for *\n* more details. *\n* *\n* You should have received a copy of the GNU General Public License along *\n* with this program; if not, write to the Free Software Foundation, Inc., 51 *\n* Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *\n*******************************************************************************\n* SOFA :: Applications *\n* *\n* Authors: The SOFA Team and external contributors (see Authors.txt) *\n* *\n* Contact information: contact@sofa-framework.org *\n******************************************************************************\/\n#include \"PieWidget.h\"\n#include <iostream>\n\n#include <QGridLayout>\n#include <QStringList>\n#include <QHeaderView>\n#include <QSplitter>\n\nnamespace sofa\n{\n\nnamespace gui\n{\n\nnamespace qt\n{\n\nstd::vector< defaulttype::Vec<3,int> > PieWidget::colorArray;\n\ndefaulttype::Vec<3,int> PieWidget::getColor(int i)\n{\n defaulttype::Vec<3,int> res=PieWidget::colorArray[i%PieWidget::colorArray.size()];\n float factor=1.0\/(1.0+(0.3*(i\/PieWidget::colorArray.size())));\n res[0] = (int)(res[0]*factor);\n res[1] = (int)(res[1]*factor);\n res[2] = (int)(res[2]*factor);\n return res;\n}\n\nPieWidget::PieWidget(QWidget *parent): QWidget(parent)\n{\n if (PieWidget::colorArray.empty())\n {\n colorArray.push_back( defaulttype::Vec<3,int>(250,125,70) );\n colorArray.push_back( defaulttype::Vec<3,int>(120,220,110) );\n colorArray.push_back( defaulttype::Vec<3,int>(215,90,215) );\n colorArray.push_back( defaulttype::Vec<3,int>(255,210,40) );\n colorArray.push_back( defaulttype::Vec<3,int>(75,210,210) );\n }\n}\nvoid PieWidget::paintEvent( QPaintEvent* )\n{\n sizePie = (int)(std::min(this->width(),this->height())*0.95);\n if (data.empty()) return;\n\n QPainter p( this );\n\n int initDraw=0;\n int startAngle=0;\n\n p.setBrush(Qt::SolidPattern);\n\n for (unsigned int i=0; i<data.size() && i<selection; ++i)\n {\n defaulttype::Vec<3,int> c=PieWidget::getColor(i);\n QColor color(c[0],c[1],c[2]);\n p.setBrush(color);\n int spanAngle=(int)(16*360*data[i].time\/totalTime);\n p.drawPie(initDraw,initDraw,sizePie,sizePie,startAngle,spanAngle);\n startAngle+= spanAngle;\n }\n}\n\nvoid PieWidget::setChart( std::vector< dataTime >& value, unsigned int s)\n{\n data=value;\n selection=s;\n totalTime=0;\n for (unsigned int i=0; i<value.size() && i<selection; ++i)\n {\n totalTime +=data[i].time;\n }\n}\n\nvoid PieWidget::clear()\n{\n data.clear();\n repaint();\n}\n\nChartsWidget::ChartsWidget(const std::string &name, QWidget *parent): QWidget(parent)\n{\n QSplitter *splitter=new QSplitter(this);\n splitter->setOrientation(Qt::Horizontal);\n QGridLayout *grid = new QGridLayout(this);\n pie = new PieWidget(splitter);\n\n table = new QTableWidget(0,3,splitter);\n table->horizontalHeader()->setSectionResizeMode(0,QHeaderView::Fixed);\n table->horizontalHeader()->resizeSection(0,30);\n table->horizontalHeader()->setSectionResizeMode(1,QHeaderView::ResizeToContents);\n table->horizontalHeader()->setSectionResizeMode(2,QHeaderView::ResizeToContents);\n QStringList list; list<<\"Id\" << name.c_str() << \"Time\";\n table->setHorizontalHeaderLabels(list);\n\n grid->addWidget(splitter,0,0);\n\n}\n\n\nvoid ChartsWidget::clear()\n{\n int rows=table->rowCount();\n\n for (int i=0; i<rows; ++i) table->removeRow(0);\n pie->clear();\n}\n\nvoid ChartsWidget::setChart( std::vector< dataTime >& value, unsigned int s)\n{\n clear();\n pie->setChart(value,s);\n selection=s;\n for (unsigned int i=0; i<value.size() && i<selection; ++i)\n {\n table->insertRow(i);\n\n defaulttype::Vec<3,int> c=PieWidget::getColor(i);\n QColor color(c[0],c[1],c[2]);\n\n QString text(value[i].name.c_str());\n QString time= QString::number(value[i].time);\n time += QString(\" ms\");\n if (!value[i].type.empty())\n {\n text+=\"(\";\n text+= QString(value[i].type.c_str());\n text+=\")\";\n }\n\n QTableWidgetItem *itemColor = new QTableWidgetItem();\n itemColor->setBackgroundColor(color);\n QTableWidgetItem *item = new QTableWidgetItem();\n QTableWidgetItem *itemTime = new QTableWidgetItem();\n table->setItem(i,0, itemColor);\n item->setText(text);\n table->setItem(i,1, item);\n itemTime->setText(time);\n table->setItem(i,2, itemTime);\n table->resizeColumnToContents(1);\n itemColor->setFlags(0);\n item->setFlags(0);\n itemTime->setFlags(0);\n\n }\n pie->repaint();\n\n}\n\n}\n}\n}\n<commit_msg>Fix compilation while using Qt4 and activating the macro SOFA_DUMP_VISITOR to get graphical profiling<commit_after>\/******************************************************************************\n* SOFA, Simulation Open-Framework Architecture, version 1.0 RC 1 *\n* (c) 2006-2011 INRIA, USTL, UJF, CNRS, MGH *\n* *\n* This program is free software; you can redistribute it and\/or modify it *\n* under the terms of the GNU General Public License as published by the Free *\n* Software Foundation; either version 2 of the License, or (at your option) *\n* any later version. *\n* *\n* This program is distributed in the hope that it will be useful, but WITHOUT *\n* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or *\n* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for *\n* more details. *\n* *\n* You should have received a copy of the GNU General Public License along *\n* with this program; if not, write to the Free Software Foundation, Inc., 51 *\n* Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *\n*******************************************************************************\n* SOFA :: Applications *\n* *\n* Authors: The SOFA Team and external contributors (see Authors.txt) *\n* *\n* Contact information: contact@sofa-framework.org *\n******************************************************************************\/\n#include \"PieWidget.h\"\n#include <iostream>\n\n#include <QGridLayout>\n#include <QStringList>\n#include <QHeaderView>\n#include <QSplitter>\n\nnamespace sofa\n{\n\nnamespace gui\n{\n\nnamespace qt\n{\n\nstd::vector< defaulttype::Vec<3,int> > PieWidget::colorArray;\n\ndefaulttype::Vec<3,int> PieWidget::getColor(int i)\n{\n defaulttype::Vec<3,int> res=PieWidget::colorArray[i%PieWidget::colorArray.size()];\n float factor=1.0\/(1.0+(0.3*(i\/PieWidget::colorArray.size())));\n res[0] = (int)(res[0]*factor);\n res[1] = (int)(res[1]*factor);\n res[2] = (int)(res[2]*factor);\n return res;\n}\n\nPieWidget::PieWidget(QWidget *parent): QWidget(parent)\n{\n if (PieWidget::colorArray.empty())\n {\n colorArray.push_back( defaulttype::Vec<3,int>(250,125,70) );\n colorArray.push_back( defaulttype::Vec<3,int>(120,220,110) );\n colorArray.push_back( defaulttype::Vec<3,int>(215,90,215) );\n colorArray.push_back( defaulttype::Vec<3,int>(255,210,40) );\n colorArray.push_back( defaulttype::Vec<3,int>(75,210,210) );\n }\n}\nvoid PieWidget::paintEvent( QPaintEvent* )\n{\n sizePie = (int)(std::min(this->width(),this->height())*0.95);\n if (data.empty()) return;\n\n QPainter p( this );\n\n int initDraw=0;\n int startAngle=0;\n\n p.setBrush(Qt::SolidPattern);\n\n for (unsigned int i=0; i<data.size() && i<selection; ++i)\n {\n defaulttype::Vec<3,int> c=PieWidget::getColor(i);\n QColor color(c[0],c[1],c[2]);\n p.setBrush(color);\n int spanAngle=(int)(16*360*data[i].time\/totalTime);\n p.drawPie(initDraw,initDraw,sizePie,sizePie,startAngle,spanAngle);\n startAngle+= spanAngle;\n }\n}\n\nvoid PieWidget::setChart( std::vector< dataTime >& value, unsigned int s)\n{\n data=value;\n selection=s;\n totalTime=0;\n for (unsigned int i=0; i<value.size() && i<selection; ++i)\n {\n totalTime +=data[i].time;\n }\n}\n\nvoid PieWidget::clear()\n{\n data.clear();\n repaint();\n}\n\nChartsWidget::ChartsWidget(const std::string &name, QWidget *parent): QWidget(parent)\n{\n QSplitter *splitter=new QSplitter(this);\n splitter->setOrientation(Qt::Horizontal);\n QGridLayout *grid = new QGridLayout(this);\n pie = new PieWidget(splitter);\n\n table = new QTableWidget(0,3,splitter);\n\n#if QT_VERSION < QT_VERSION_CHECK(5, 0, 0)\n table->horizontalHeader()->setResizeMode(0,QHeaderView::Fixed);\n table->horizontalHeader()->setResizeMode(1,QHeaderView::ResizeToContents);\n table->horizontalHeader()->setResizeMode(2,QHeaderView::ResizeToContents);\n#else\n table->horizontalHeader()->setSectionResizeMode(0,QHeaderView::Fixed);\n table->horizontalHeader()->setSectionResizeMode(1,QHeaderView::ResizeToContents);\n table->horizontalHeader()->setSectionResizeMode(2,QHeaderView::ResizeToContents);\n#endif \/\/ QT_VERSION < QT_VERSION_CHECK(5, 0, 0)\n\n table->horizontalHeader()->resizeSection(0,30);\n\n QStringList list; list<<\"Id\" << name.c_str() << \"Time\";\n table->setHorizontalHeaderLabels(list);\n\n grid->addWidget(splitter,0,0);\n\n}\n\n\nvoid ChartsWidget::clear()\n{\n int rows=table->rowCount();\n\n for (int i=0; i<rows; ++i) table->removeRow(0);\n pie->clear();\n}\n\nvoid ChartsWidget::setChart( std::vector< dataTime >& value, unsigned int s)\n{\n clear();\n pie->setChart(value,s);\n selection=s;\n for (unsigned int i=0; i<value.size() && i<selection; ++i)\n {\n table->insertRow(i);\n\n defaulttype::Vec<3,int> c=PieWidget::getColor(i);\n QColor color(c[0],c[1],c[2]);\n\n QString text(value[i].name.c_str());\n QString time= QString::number(value[i].time);\n time += QString(\" ms\");\n if (!value[i].type.empty())\n {\n text+=\"(\";\n text+= QString(value[i].type.c_str());\n text+=\")\";\n }\n\n QTableWidgetItem *itemColor = new QTableWidgetItem();\n itemColor->setBackgroundColor(color);\n QTableWidgetItem *item = new QTableWidgetItem();\n QTableWidgetItem *itemTime = new QTableWidgetItem();\n table->setItem(i,0, itemColor);\n item->setText(text);\n table->setItem(i,1, item);\n itemTime->setText(time);\n table->setItem(i,2, itemTime);\n table->resizeColumnToContents(1);\n itemColor->setFlags(0);\n item->setFlags(0);\n itemTime->setFlags(0);\n\n }\n pie->repaint();\n\n}\n\n}\n}\n}\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n * Copyright (c) 2014 eProsima. All rights reserved.\n *\n * This copy of eProsima RTPS is licensed to you under the terms described in the\n * EPROSIMARTPS_LIBRARY_LICENSE file included in this distribution.\n *\n *************************************************************************\/\n\n\/**\n * @file WriterQos.cpp\n *\n *\/\n\n#include \"eprosimartps\/qos\/WriterQos.h\"\n#include \"eprosimartps\/utils\/RTPSLog.h\"\n\nnamespace eprosima {\nnamespace dds {\n\nWriterQos::WriterQos()\n{\n\tthis->m_reliability.kind = RELIABLE_RELIABILITY_QOS;\n}\n\nWriterQos::~WriterQos()\n{\n\n}\n\n\nvoid WriterQos::setQos( WriterQos& qos, bool first_time)\n{\n\tif(first_time)\n\t{\n\t\tm_durability = qos.m_durability;\n\t\tm_durability.hasChanged = true;\n\t}\n\tif(m_deadline.period != qos.m_deadline.period)\n\t{\n\t\tm_deadline = qos.m_deadline;\n\t\tm_deadline.hasChanged = true;\n\t}\n\tif(m_latencyBudget.duration != qos.m_latencyBudget.duration)\n\t{\n\t\tm_latencyBudget = qos.m_latencyBudget;\n\t\tm_latencyBudget.hasChanged = true;\n\t}\n\tif(m_liveliness.lease_duration != qos.m_liveliness.lease_duration)\n\t{\n\t\tm_liveliness.lease_duration = qos.m_liveliness.lease_duration;\n\t\tm_liveliness.hasChanged = true;\n\t}\n\tif(first_time)\n\t{\n\t\tm_liveliness = qos.m_liveliness;\n\t\tm_liveliness.hasChanged = true;\n\t}\n\tif(first_time)\n\t{\n\t\tm_reliability = qos.m_reliability;\n\t\tm_reliability.hasChanged = true;\n\t}\n\tif(first_time)\n\t{\n\t\tm_ownership = qos.m_ownership;\n\t\tm_ownership.hasChanged = true;\n\t}\n\tif(m_destinationOrder.kind != qos.m_destinationOrder.kind )\n\t{\n\t\tm_destinationOrder = qos.m_destinationOrder;\n\t\tm_destinationOrder.hasChanged = true;\n\t}\n\tif(m_userData.data != qos.m_userData.data )\n\t{\n\t\tm_userData = qos.m_userData;\n\t\tm_userData.hasChanged = true;\n\t}\n\tif(m_timeBasedFilter.minimum_separation != qos.m_timeBasedFilter.minimum_separation )\n\t{\n\t\tm_timeBasedFilter = qos.m_timeBasedFilter;\n\t\tm_timeBasedFilter.hasChanged = true;\n\t}\n\tif(m_presentation.access_scope != qos.m_presentation.access_scope ||\n\t\t\tm_presentation.coherent_access != qos.m_presentation.coherent_access ||\n\t\t\tm_presentation.ordered_access != qos.m_presentation.ordered_access)\n\t{\n\t\tm_presentation = qos.m_presentation;\n\t\tm_presentation.hasChanged = true;\n\t}\n\tif(first_time)\n\t{\n\t\tm_partition = qos.m_partition;\n\t\tm_partition.hasChanged = true;\n\t}\n\tif(m_topicData.value != qos.m_topicData.value )\n\t{\n\t\tm_topicData = qos.m_topicData;\n\t\tm_topicData.hasChanged = true;\n\t}\n\tif(m_groupData.value != qos.m_groupData.value )\n\t{\n\t\tm_groupData = qos.m_groupData;\n\t\tm_groupData.hasChanged = true;\n\t}\n\tif(m_durabilityService.history_kind != qos.m_durabilityService.history_kind ||\n\t\t\tm_durabilityService.history_depth != qos.m_durabilityService.history_depth ||\n\t\t\tm_durabilityService.max_instances != qos.m_durabilityService.max_instances ||\n\t\t\tm_durabilityService.max_samples != qos.m_durabilityService.max_samples||\n\t\t\tm_durabilityService.max_samples_per_instance != qos.m_durabilityService.max_samples_per_instance ||\n\t\t\tm_durabilityService.service_cleanup_delay != qos.m_durabilityService.service_cleanup_delay\n\t)\n\t{\n\t\tm_durabilityService = qos.m_durabilityService;\n\t\tm_durabilityService.hasChanged = true;\n\t}\n\tif(m_lifespan.duration != qos.m_lifespan.duration )\n\t{\n\t\tm_lifespan = qos.m_lifespan;\n\t\tm_lifespan.hasChanged = true;\n\t}\n\tif(first_time)\n\t{\n\t\tm_ownershipStrength = qos.m_ownershipStrength;\n\t\tm_ownershipStrength.hasChanged = true;\n\t}\n}\n\nbool WriterQos::checkQos()\n{\n\tif(m_durability.kind == TRANSIENT_DURABILITY_QOS)\n\t{\n\t\tpError(\"TRANSIENT Durability not supported\"<<endl);\n\t\treturn false;\n\t}\n\tif(m_durability.kind == PERSISTENT_DURABILITY_QOS)\n\t{\n\t\tpError(\"PERSISTENT Durability not supported\"<<endl);\n\t\treturn false;\n\t}\n\tif(m_destinationOrder.kind == BY_SOURCE_TIMESTAMP_DESTINATIONORDER_QOS)\n\t{\n\t\tpError(\"BY SOURCE TIMESTAMP DestinationOrder not supported\"<<endl);\n\t\treturn false;\n\t}\n\tif(m_reliability.kind == BEST_EFFORT_RELIABILITY_QOS && m_ownership.kind == EXCLUSIVE_OWNERSHIP_QOS)\n\t{\n\t\tpError(\"BEST_EFFORT incompatible with EXCLUSIVE ownership\"<<endl);\n\t\treturn false;\n\t}\n\treturn true;\n}\n\n} \/* namespace dds *\/\n} \/* namespace eprosima *\/\n<commit_msg>Check that leaseDuration is > announcementPeriod<commit_after>\/*************************************************************************\n * Copyright (c) 2014 eProsima. All rights reserved.\n *\n * This copy of eProsima RTPS is licensed to you under the terms described in the\n * EPROSIMARTPS_LIBRARY_LICENSE file included in this distribution.\n *\n *************************************************************************\/\n\n\/**\n * @file WriterQos.cpp\n *\n *\/\n\n#include \"eprosimartps\/qos\/WriterQos.h\"\n#include \"eprosimartps\/utils\/RTPSLog.h\"\n\nnamespace eprosima {\nnamespace dds {\n\nWriterQos::WriterQos()\n{\n\tthis->m_reliability.kind = RELIABLE_RELIABILITY_QOS;\n}\n\nWriterQos::~WriterQos()\n{\n\n}\n\n\nvoid WriterQos::setQos( WriterQos& qos, bool first_time)\n{\n\tif(first_time)\n\t{\n\t\tm_durability = qos.m_durability;\n\t\tm_durability.hasChanged = true;\n\t}\n\tif(m_deadline.period != qos.m_deadline.period)\n\t{\n\t\tm_deadline = qos.m_deadline;\n\t\tm_deadline.hasChanged = true;\n\t}\n\tif(m_latencyBudget.duration != qos.m_latencyBudget.duration)\n\t{\n\t\tm_latencyBudget = qos.m_latencyBudget;\n\t\tm_latencyBudget.hasChanged = true;\n\t}\n\tif(m_liveliness.lease_duration != qos.m_liveliness.lease_duration)\n\t{\n\t\tm_liveliness.lease_duration = qos.m_liveliness.lease_duration;\n\t\tm_liveliness.hasChanged = true;\n\t}\n\tif(first_time)\n\t{\n\t\tm_liveliness = qos.m_liveliness;\n\t\tm_liveliness.hasChanged = true;\n\t}\n\tif(first_time)\n\t{\n\t\tm_reliability = qos.m_reliability;\n\t\tm_reliability.hasChanged = true;\n\t}\n\tif(first_time)\n\t{\n\t\tm_ownership = qos.m_ownership;\n\t\tm_ownership.hasChanged = true;\n\t}\n\tif(m_destinationOrder.kind != qos.m_destinationOrder.kind )\n\t{\n\t\tm_destinationOrder = qos.m_destinationOrder;\n\t\tm_destinationOrder.hasChanged = true;\n\t}\n\tif(m_userData.data != qos.m_userData.data )\n\t{\n\t\tm_userData = qos.m_userData;\n\t\tm_userData.hasChanged = true;\n\t}\n\tif(m_timeBasedFilter.minimum_separation != qos.m_timeBasedFilter.minimum_separation )\n\t{\n\t\tm_timeBasedFilter = qos.m_timeBasedFilter;\n\t\tm_timeBasedFilter.hasChanged = true;\n\t}\n\tif(m_presentation.access_scope != qos.m_presentation.access_scope ||\n\t\t\tm_presentation.coherent_access != qos.m_presentation.coherent_access ||\n\t\t\tm_presentation.ordered_access != qos.m_presentation.ordered_access)\n\t{\n\t\tm_presentation = qos.m_presentation;\n\t\tm_presentation.hasChanged = true;\n\t}\n\tif(first_time)\n\t{\n\t\tm_partition = qos.m_partition;\n\t\tm_partition.hasChanged = true;\n\t}\n\tif(m_topicData.value != qos.m_topicData.value )\n\t{\n\t\tm_topicData = qos.m_topicData;\n\t\tm_topicData.hasChanged = true;\n\t}\n\tif(m_groupData.value != qos.m_groupData.value )\n\t{\n\t\tm_groupData = qos.m_groupData;\n\t\tm_groupData.hasChanged = true;\n\t}\n\tif(m_durabilityService.history_kind != qos.m_durabilityService.history_kind ||\n\t\t\tm_durabilityService.history_depth != qos.m_durabilityService.history_depth ||\n\t\t\tm_durabilityService.max_instances != qos.m_durabilityService.max_instances ||\n\t\t\tm_durabilityService.max_samples != qos.m_durabilityService.max_samples||\n\t\t\tm_durabilityService.max_samples_per_instance != qos.m_durabilityService.max_samples_per_instance ||\n\t\t\tm_durabilityService.service_cleanup_delay != qos.m_durabilityService.service_cleanup_delay\n\t)\n\t{\n\t\tm_durabilityService = qos.m_durabilityService;\n\t\tm_durabilityService.hasChanged = true;\n\t}\n\tif(m_lifespan.duration != qos.m_lifespan.duration )\n\t{\n\t\tm_lifespan = qos.m_lifespan;\n\t\tm_lifespan.hasChanged = true;\n\t}\n\tif(first_time)\n\t{\n\t\tm_ownershipStrength = qos.m_ownershipStrength;\n\t\tm_ownershipStrength.hasChanged = true;\n\t}\n}\n\nbool WriterQos::checkQos()\n{\n\tif(m_durability.kind == TRANSIENT_DURABILITY_QOS)\n\t{\n\t\tpError(\"TRANSIENT Durability not supported\"<<endl);\n\t\treturn false;\n\t}\n\tif(m_durability.kind == PERSISTENT_DURABILITY_QOS)\n\t{\n\t\tpError(\"PERSISTENT Durability not supported\"<<endl);\n\t\treturn false;\n\t}\n\tif(m_destinationOrder.kind == BY_SOURCE_TIMESTAMP_DESTINATIONORDER_QOS)\n\t{\n\t\tpError(\"BY SOURCE TIMESTAMP DestinationOrder not supported\"<<endl);\n\t\treturn false;\n\t}\n\tif(m_reliability.kind == BEST_EFFORT_RELIABILITY_QOS && m_ownership.kind == EXCLUSIVE_OWNERSHIP_QOS)\n\t{\n\t\tpError(\"BEST_EFFORT incompatible with EXCLUSIVE ownership\"<<endl);\n\t\treturn false;\n\t}\n\tif(m_liveliness.kind == AUTOMATIC_LIVELINESS_QOS || m_liveliness.kind == MANUAL_BY_PARTICIPANT_LIVELINESS_QOS)\n\t{\n\t\tif(m_liveliness.lease_duration <= m_liveliness.announcement_period)\n\t\t{\n\t\t\tpError(\"WRITERQOS: LeaseDuration <= announcement period \" << endl;);\n\t\t\treturn false;\n\t\t}\n\t}\n\treturn true;\n}\n\n} \/* namespace dds *\/\n} \/* namespace eprosima *\/\n<|endoftext|>"} {"text":"<commit_before>\/*\n Copyright (c) 2012 Matthew Stump\n\n This file is part of libcql.\n\n libcql is free software; you can redistribute it and\/or modify it under\n the terms of the GNU Lesser General Public License as published by\n the Free Software Foundation; either version 3 of the License, or\n (at your option) any later version.\n\n libcql is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU Lesser General Public License for more details.\n\n You should have received a copy of the GNU Lesser General Public License\n along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n*\/\n\n#include <iomanip>\n#include <sstream>\n\n#include \"serialization.hpp\"\n#include \"util.hpp\"\n#include \"cql_message_query.hpp\"\n\n\ncql::cql_message_query_t::cql_message_query_t() :\n _consistency(0),\n _query()\n{}\n\ncql::cql_message_query_t::cql_message_query_t(const std::string& query,\n cql_short_t consistency) :\n _consistency(consistency),\n _query(query)\n{}\n\nconst std::string&\ncql::cql_message_query_t::query() const\n{\n return _query;\n}\n\ncql_short_t\ncql::cql_message_query_t::consistency() const\n{\n return _consistency;\n}\n\nvoid\ncql::cql_message_query_t::query(const std::string& q)\n{\n _query = q;\n}\n\nvoid\ncql::cql_message_query_t::consistency(cql_short_t consistency)\n{\n _consistency = consistency;\n}\n\ncql_byte_t\ncql::cql_message_query_t::opcode() const\n{\n return CQL_OPCODE_QUERY;\n}\n\ncql_int_t\ncql::cql_message_query_t::size() const\n{\n std::stringstream ss(std::stringstream::out);\n write(ss);\n return ss.str().size();\n}\n\nstd::string\ncql::cql_message_query_t::str() const\n{\n std::stringstream output;\n output << _query;\n output << \" \" << std::setfill('0') << std::string(\"0x\") << std::setw(2);\n output << cql::internal::hex(_consistency);\n return output.str();\n}\n\nstd::istream&\ncql::cql_message_query_t::read(std::istream& input)\n{\n cql::internal::decode_long_string(input, _query);\n input.read(reinterpret_cast<char*>(&_consistency), sizeof(_consistency));\n _consistency = ntohs(_consistency);\n return input;\n}\n\nstd::ostream&\ncql::cql_message_query_t::write(std::ostream& output) const\n{\n cql::internal::encode_long_string(output, _query);\n cql_short_t consistency = htons(_consistency);\n output.write(reinterpret_cast<char*>(&consistency), sizeof(consistency));\n return output;\n}\n<commit_msg>use the central serialization methods for encoding the consistency of a query message<commit_after>\/*\n Copyright (c) 2012 Matthew Stump\n\n This file is part of libcql.\n\n libcql is free software; you can redistribute it and\/or modify it under\n the terms of the GNU Lesser General Public License as published by\n the Free Software Foundation; either version 3 of the License, or\n (at your option) any later version.\n\n libcql is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU Lesser General Public License for more details.\n\n You should have received a copy of the GNU Lesser General Public License\n along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n*\/\n\n#include <iomanip>\n#include <sstream>\n\n#include \"serialization.hpp\"\n#include \"util.hpp\"\n#include \"cql_message_query.hpp\"\n\n\ncql::cql_message_query_t::cql_message_query_t() :\n _consistency(0),\n _query()\n{}\n\ncql::cql_message_query_t::cql_message_query_t(const std::string& query,\n cql_short_t consistency) :\n _consistency(consistency),\n _query(query)\n{}\n\nconst std::string&\ncql::cql_message_query_t::query() const\n{\n return _query;\n}\n\ncql_short_t\ncql::cql_message_query_t::consistency() const\n{\n return _consistency;\n}\n\nvoid\ncql::cql_message_query_t::query(const std::string& q)\n{\n _query = q;\n}\n\nvoid\ncql::cql_message_query_t::consistency(cql_short_t consistency)\n{\n _consistency = consistency;\n}\n\ncql_byte_t\ncql::cql_message_query_t::opcode() const\n{\n return CQL_OPCODE_QUERY;\n}\n\ncql_int_t\ncql::cql_message_query_t::size() const\n{\n std::stringstream ss(std::stringstream::out);\n write(ss);\n return ss.str().size();\n}\n\nstd::string\ncql::cql_message_query_t::str() const\n{\n std::stringstream output;\n output << _query;\n output << \" \" << std::setfill('0') << std::string(\"0x\") << std::setw(2);\n output << cql::internal::hex(_consistency);\n return output.str();\n}\n\nstd::istream&\ncql::cql_message_query_t::read(std::istream& input)\n{\n cql::internal::decode_long_string(input, _query);\n input.read(reinterpret_cast<char*>(&_consistency), sizeof(_consistency));\n _consistency = ntohs(_consistency);\n return input;\n}\n\nstd::ostream&\ncql::cql_message_query_t::write(std::ostream& output) const\n{\n cql::internal::encode_long_string(output, _query);\n cql::internal::encode_short(output, _consistency);\n return output;\n}\n<|endoftext|>"} {"text":"<commit_before>#pragma ident \"$Id:$\"\n\/**\n* ConstellationList - Produce comma separated list of PRN ID values for\n* the SVs that are in the constellation. In order to do this, the program\n* needs:\n* (1.) An input file that defines the GPS constellation at a given date\n* (or dates)\n* (2.) The year of interest (2-digit or 4-digit will do)\n* (3.) The day of year of interest (Julian day, 0-365\/366)\n* The user may also specify if they want the list in the \"baseline 24\", the\n* \"excess\" above the baseline, or both.\n*\n* USAGE:\n* >ConstellationList -i<definitionFile> -y<year> -j<DOY> [-b] [-x] [-n] [-O]\n* -i : Constellation defintion file\n* -y : year (2-digit or 4-digit)\n* -j : day of year (0-365|366)\n* -b : List \"baseline 24\" PRN IDs\n* -x : List PRN IDs \"in excess of\" the baseline 24, but in-use on orbit\n* -n : List PRN IDs that are current not in baseline 24, either on-orbit \n* \"excess\" or simply not in use at this time. \n* -O : Assume input file is in form of USCG Ops Advisory. By default a \n* comma separated value file is assumed.\n*\n*\/\n\/\/============================================================================\n\/\/\n\/\/ This file is part of GPSTk, the GPS Toolkit.\n\/\/\n\/\/ The GPSTk is free software; you can redistribute it and\/or modify\n\/\/ it under the terms of the GNU Lesser General Public License as published\n\/\/ by the Free Software Foundation; either version 2.1 of the License, or\n\/\/ any later version.\n\/\/\n\/\/ The GPSTk is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n\/\/ GNU Lesser General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License along with GPSTk; if not, write to the Free Software Foundation,\n\/\/ Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n\/\/\n\/\/ Copyright 2009, The University of Texas at Austin\n\/\/\n\/\/============================================================================\n\n\/\/============================================================================\n\/\/\n\/\/This software developed by Applied Research Laboratories at the University of\n\/\/Texas at Austin, under contract to an agency or agencies within the U.S.\n\/\/Department of Defense. The U.S. Government retains all rights to use,\n\/\/duplicate, distribute, disclose, or release this software.\n\/\/\n\/\/Pursuant to DoD Directive 523024\n\/\/\n\/\/ DISTRIBUTION STATEMENT A: This software has been approved for public\n\/\/ release, distribution is unlimited.\n\/\/\n\/\/=============================================================================\n\/\/ System\n#include <stdio.h>\n\n\/\/ Library\n#include \"BasicFramework.hpp\"\n#include \"DayTime.hpp\"\n#include \"icd_200_constants.hpp\"\n\n\/\/ Project\n#include \"ConstellationSet.hpp\"\n\nusing namespace std;\nusing namespace gpstk;\n\n\nclass ConstellationList : public gpstk::BasicFramework\n{\npublic:\n ConstellationList(const std::string& applName,\n const std::string& applDesc) throw();\n ~ConstellationList() {}\n virtual bool initialize(int argc, char *argv[]) throw();\n \nprotected:\n virtual void process();\n gpstk::CommandOptionWithAnyArg inputOption;\n gpstk::CommandOptionNoArg typeOption;\n gpstk::CommandOptionWithAnyArg yearOption;\n gpstk::CommandOptionWithAnyArg DOYOption;\n gpstk::CommandOptionNoArg base24Option;\n gpstk::CommandOptionNoArg excessOption;\n gpstk::CommandOptionNoArg notBase24Option;\n gpstk::CommandOptionNoArg SVNOption;\n\n FILE *logfp;\n ConstellationSet cs;\n \n bool outputPRN;\n};\n\nint main( int argc, char*argv[] )\n{\n try\n {\n ConstellationList fc(\"ConstellationList\", \"List the satellites in or out of the Base 24.\");\n if (!fc.initialize(argc, argv)) return(false);\n fc.run();\n }\n catch(gpstk::Exception& exc)\n {\n cout << exc << endl;\n return 1;\n }\n catch(...)\n {\n cout << \"Caught an unnamed exception. Exiting.\" << endl;\n return 1;\n }\n return 0;\n}\n\nConstellationList::ConstellationList(const std::string& applName, \n const std::string& applDesc) throw()\n :BasicFramework(applName, applDesc),\n inputOption('i', \"input-file\", \"The name of the ConstallationDefinition file(s) to read.\", true),\n typeOption('O', \"OpsAd\",\"Assume input file is Op Advisory format (CSV is default)\",false),\n yearOption('y', \"year\", \"Year of interest.\", true),\n DOYOption('j',\"day-of-year\",\"Day of year.\", true),\n SVNOption('s',\"SVN Output\",\"Output SVN in place of PRN (only valid fo -O)\",false),\n base24Option('b',\"Base24\", \"List PRNs in Base 24 constellation\", false),\n notBase24Option('n',\"notBase24\",\"List PRNs NOT used in Base 24 constellation\",false),\n excessOption('x',\"excessSVs\",\"List PRNs in use, but in excess of the Base 24 constellation\",false)\n{\n inputOption.setMaxCount(10);\n yearOption.setMaxCount(1);\n DOYOption.setMaxCount(1);\n}\n\nbool ConstellationList::initialize(int argc, char *argv[])\n throw()\n{\n if (!BasicFramework::initialize(argc, argv)) return false;\n\n \/\/ Load constellation defintions. \n int totalCount = 0;\n \n vector<string> values;\n\n ConstellationSet::FileType ft = ConstellationSet::CSV; \n if (typeOption.getCount()>0)\n {\n ft = ConstellationSet::OpAdvisory;\n } \n\n values = inputOption.getValue();\n vector<string>::const_iterator vi;\n for (vi=values.begin();vi!=values.end();++vi)\n {\n string filename = *vi;\n int count = cs.loadFile( filename, ft );\n totalCount += count;\n }\n if (totalCount<1) \n {\n cout << \"Failure reading input file.\" << endl;\n return false;\n }\n \n outputPRN = true;\n if (ft==ConstellationSet::CSV && SVNOption.getCount()>0) outputPRN = false;\n return true; \n}\n\nvoid ConstellationList::process()\n{\n \/\/ Get day of interest from command line arguments\n \/\/ Arrange so this'll work with either 2-digit or 4-digit year numbers\n int year = StringUtils::asInt( yearOption.getValue().front() );\n if (year>=0 && year<=70) year += 2000;\n if (year<100) year += 1900;\n \n int DOY = StringUtils::asInt( DOYOption.getValue().front() );\n \n DayTime dt = DayTime( (short) year, (short) DOY, (DayTime::SEC_DAY \/ 2));\n\n \/\/ Try some samples\n ConstellationDefinition cd = cs.findCD( dt );\n\n \/\/ Test each PRN ID in order and\n \/\/ output a comma separated list of those match the selected criteriaz\n bool first = true;\n for (int PRNID=1; PRNID<=gpstk::MAX_PRN; ++PRNID)\n {\n SatID SV = SatID( PRNID, SatID::systemGPS );\n try\n {\n bool inBase24 = cd.inBase24(SV);\n if (notBase24Option.getCount()!=0)\n {\n if (!inBase24) \n {\n if (!first) cout << \", \";\n \/\/cout << PRNID;\n if (outputPRN) cout << PRNID;\n else cout << cd.getSVN(SV); \n first = false;\n }\n }\n else\n {\n if ( ( inBase24 && base24Option.getCount()!=0) ||\n (!inBase24 && excessOption.getCount()!=0) )\n {\n if (!first) cout << \", \";\n \/\/cout << PRNID;\n if (outputPRN) cout << PRNID;\n else cout << cd.getSVN(SV); \n first = false;\n }\n }\n }\n catch(ConstellationDefinition::NoSlotFoundForSV e)\n { \/\/Do nothing but continue\n \/\/Except in case -n, in which we want to add this PRN ID to the list\n if (notBase24Option.getCount()!=0)\n {\n if (!first) cout << \", \";\n \/\/cout << PRNID;\n if (outputPRN) cout << PRNID;\n else cout << cd.getSVN(SV); \n first = false;\n }\n }\n }\n cout << endl;\n}\n<commit_msg>Minor argument updates to ConstellationList<commit_after>#pragma ident \"$Id:$\"\n\/**\n* ConstellationList - Produce comma separated list of PRN ID values for\n* the SVs that are in the constellation. In order to do this, the program\n* needs:\n* (1.) An input file that defines the GPS constellation at a given date\n* (or dates)\n* (2.) The year of interest (2-digit or 4-digit will do)\n* (3.) The day of year of interest (Julian day, 0-365\/366)\n* The user may also specify if they want the list in the \"baseline 24\", the\n* \"excess\" above the baseline, or both.\n*\n* USAGE:\n* >ConstellationList -i<definitionFile> -y<year> -j<DOY> [-b] [-x] [-n] [-O]\n* -i : Constellation defintion file\n* -y : year (2-digit or 4-digit)\n* -j : day of year (0-365|366)\n* -b : List \"baseline 24\" PRN IDs\n* -x : List PRN IDs \"in excess of\" the baseline 24, but in-use on orbit\n* -n : List PRN IDs that are current not in baseline 24, either on-orbit \n* \"excess\" or simply not in use at this time. \n* -O : Assume input file is in form of USCG Ops Advisory. By default a \n* comma separated value file is assumed.\n*\n*\/\n\/\/============================================================================\n\/\/\n\/\/ This file is part of GPSTk, the GPS Toolkit.\n\/\/\n\/\/ The GPSTk is free software; you can redistribute it and\/or modify\n\/\/ it under the terms of the GNU Lesser General Public License as published\n\/\/ by the Free Software Foundation; either version 2.1 of the License, or\n\/\/ any later version.\n\/\/\n\/\/ The GPSTk is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n\/\/ GNU Lesser General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License along with GPSTk; if not, write to the Free Software Foundation,\n\/\/ Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n\/\/\n\/\/ Copyright 2009, The University of Texas at Austin\n\/\/\n\/\/============================================================================\n\n\/\/============================================================================\n\/\/\n\/\/This software developed by Applied Research Laboratories at the University of\n\/\/Texas at Austin, under contract to an agency or agencies within the U.S.\n\/\/Department of Defense. The U.S. Government retains all rights to use,\n\/\/duplicate, distribute, disclose, or release this software.\n\/\/\n\/\/Pursuant to DoD Directive 523024\n\/\/\n\/\/ DISTRIBUTION STATEMENT A: This software has been approved for public\n\/\/ release, distribution is unlimited.\n\/\/\n\/\/=============================================================================\n\/\/ System\n#include <stdio.h>\n\n\/\/ Library\n#include \"BasicFramework.hpp\"\n#include \"DayTime.hpp\"\n#include \"icd_200_constants.hpp\"\n\n\/\/ Project\n#include \"ConstellationSet.hpp\"\n\nusing namespace std;\nusing namespace gpstk;\n\n\nclass ConstellationList : public gpstk::BasicFramework\n{\npublic:\n ConstellationList(const std::string& applName,\n const std::string& applDesc) throw();\n ~ConstellationList() {}\n virtual bool initialize(int argc, char *argv[]) throw();\n \nprotected:\n virtual void process();\n gpstk::CommandOptionWithAnyArg inputOption;\n gpstk::CommandOptionNoArg typeOption;\n gpstk::CommandOptionWithAnyArg yearOption;\n gpstk::CommandOptionWithAnyArg DOYOption;\n gpstk::CommandOptionNoArg base24Option;\n gpstk::CommandOptionNoArg excessOption;\n gpstk::CommandOptionNoArg notBase24Option;\n gpstk::CommandOptionNoArg SVNOption;\n\n FILE *logfp;\n ConstellationSet cs;\n \n bool outputPRN;\n};\n\nint main( int argc, char*argv[] )\n{\n try\n {\n ConstellationList fc(\"ConstellationList\", \"List the satellites in or out of the Base 24.\");\n if (!fc.initialize(argc, argv)) return(false);\n fc.run();\n }\n catch(gpstk::Exception& exc)\n {\n cout << exc << endl;\n return 1;\n }\n catch(...)\n {\n cout << \"Caught an unnamed exception. Exiting.\" << endl;\n return 1;\n }\n return 0;\n}\n\nConstellationList::ConstellationList(const std::string& applName, \n const std::string& applDesc) throw()\n :BasicFramework(applName, applDesc),\n inputOption('i', \"input-file\", \"The name of the ConstallationDefinition file(s) to read.\", true),\n typeOption('O', \"OpsAd\",\"Assume input file is Op Advisory format (CSV is default)\",false),\n yearOption('y', \"year\", \"Year of interest.\", true),\n DOYOption('j',\"day-of-year\",\"Day of year.\", true),\n SVNOption('s',\"SVN Output\",\"Output SVN in place of PRN (not valid for -O)\",false),\n base24Option('b',\"Base24\", \"List PRNs in Base 24 constellation\", false),\n notBase24Option('n',\"notBase24\",\"List PRNs NOT used in Base 24 constellation\",false),\n excessOption('x',\"excessSVs\",\"List PRNs in use, but in excess of the Base 24 constellation\",false)\n{\n inputOption.setMaxCount(10);\n yearOption.setMaxCount(1);\n DOYOption.setMaxCount(1);\n}\n\nbool ConstellationList::initialize(int argc, char *argv[])\n throw()\n{\n if (!BasicFramework::initialize(argc, argv)) return false;\n\n \/\/ Load constellation defintions. \n int totalCount = 0;\n \n vector<string> values;\n\n ConstellationSet::FileType ft = ConstellationSet::CSV; \n if (typeOption.getCount()>0)\n {\n ft = ConstellationSet::OpAdvisory;\n } \n\n values = inputOption.getValue();\n vector<string>::const_iterator vi;\n for (vi=values.begin();vi!=values.end();++vi)\n {\n string filename = *vi;\n int count = cs.loadFile( filename, ft );\n totalCount += count;\n }\n if (totalCount<1) \n {\n cout << \"Failure reading input file.\" << endl;\n return false;\n }\n \n outputPRN = true;\n if (ft==ConstellationSet::CSV && SVNOption.getCount()>0) outputPRN = false;\n return true; \n}\n\nvoid ConstellationList::process()\n{\n \/\/ Get day of interest from command line arguments\n \/\/ Arrange so this'll work with either 2-digit or 4-digit year numbers\n int year = StringUtils::asInt( yearOption.getValue().front() );\n if (year>=0 && year<=70) year += 2000;\n if (year<100) year += 1900;\n \n int DOY = StringUtils::asInt( DOYOption.getValue().front() );\n \n DayTime dt = DayTime( (short) year, (short) DOY, (DayTime::SEC_DAY \/ 2));\n\n \/\/ Try some samples\n ConstellationDefinition cd = cs.findCD( dt );\n\n \/\/ Test each PRN ID in order and\n \/\/ output a comma separated list of those match the selected criteriaz\n bool first = true;\n for (int PRNID=1; PRNID<=gpstk::MAX_PRN; ++PRNID)\n {\n SatID SV = SatID( PRNID, SatID::systemGPS );\n try\n {\n bool inBase24 = cd.inBase24(SV);\n if (notBase24Option.getCount()!=0)\n {\n if (!inBase24) \n {\n if (!first) cout << \", \";\n \/\/cout << PRNID;\n if (outputPRN) cout << PRNID;\n else cout << cd.getSVN(SV); \n first = false;\n }\n }\n else\n {\n if ( ( inBase24 && base24Option.getCount()!=0) ||\n (!inBase24 && excessOption.getCount()!=0) )\n {\n if (!first) cout << \", \";\n \/\/cout << PRNID;\n if (outputPRN) cout << PRNID;\n else cout << cd.getSVN(SV); \n first = false;\n }\n }\n }\n catch(ConstellationDefinition::NoSlotFoundForSV e)\n { \/\/Do nothing but continue\n \/\/Except in case -n, in which we want to add this PRN ID to the list\n if (notBase24Option.getCount()!=0)\n {\n if (!first) cout << \", \";\n \/\/cout << PRNID;\n if (outputPRN) cout << PRNID;\n else cout << cd.getSVN(SV); \n first = false;\n }\n }\n }\n cout << endl;\n}\n<|endoftext|>"} {"text":"<commit_before>\/* bzflag\n * Copyright (c) 1993 - 2003 Tim Riker\n *\n * This package is free software; you can redistribute it and\/or\n * modify it under the terms of the license found in the file\n * named COPYING that should have accompanied this file.\n *\n * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR\n * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED\n * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.\n *\/\n\/\/ todo make this turn off for .net\n#if defined(_WIN32)\n\t#pragma warning(disable: 4786)\n#endif\n\n\n#include <string.h>\n#include <math.h>\n#include <ctype.h>\n#include <fstream>\n#include \"common.h\"\n#include \"global.h\"\n#include \"Ping.h\"\n#include \"Protocol.h\"\n#include \"TimeKeeper.h\"\n#include \"bzfio.h\"\n\n\/\/ incessint rebuilding for current versioning\n#include \"version.h\"\n\n\n\/\/\n\/\/ PingPacket\n\/\/\n\nconst int\t\tPingPacket::PacketSize = ServerIdPLen + 52;\n\nPingPacket::PingPacket() : gameStyle(PlainGameStyle),\n\t\t\t\tmaxShots(1),\n\t\t\t\tshakeWins(0),\n\t\t\t\tshakeTimeout(0),\n\t\t\t\tmaxPlayerScore(0),\n\t\t\t\tmaxTeamScore(0),\n\t\t\t\tmaxTime(0),\n\t\t\t\tmaxPlayers(1),\n\t\t\t\trogueCount(0),\n\t\t\t\trogueMax(1),\n\t\t\t\tredCount(0),\n\t\t\t\tredMax(1),\n\t\t\t\tgreenCount(0),\n\t\t\t\tgreenMax(1),\n\t\t\t\tblueCount(0),\n\t\t\t\tblueMax(1),\n\t\t\t\tpurpleCount(0),\n\t\t\t\tpurpleMax(1),\n\t\t\t\tobserverCount(0),\n\t\t\t\tobserverMax(1)\n{\n \/\/ do nothing\n}\n\nPingPacket::~PingPacket()\n{\n \/\/ do nothing\n}\n\nbool\t\t\tPingPacket::read(int fd, struct sockaddr_in* addr)\n{\n char buffer[PacketSize], serverVersion[9];\n uint16_t len, code;\n\n \/\/ get packet\n int n = recvMulticast(fd, buffer, sizeof(buffer), addr);\n if (n < 4)\n return false;\n\n \/\/ decode header\n void* buf = buffer;\n buf = nboUnpackUShort(buf, len);\n buf = nboUnpackUShort(buf, code);\n\n \/\/ make sure we got the rest of the message\n if (len != n - 4)\n return false;\n\n \/\/ check that it's a reply\n if (code != MsgPingCodeReply)\n return false;\n\n \/\/ unpack body of reply\n buf = unpack(buf, serverVersion);\n\n \/\/ compare version against my version. ignore last character of\n \/\/ version number. that's only used to indicate compatible\n \/\/ client-side changes.\n return (strncmp(serverVersion, getServerVersion(), 7) == 0);\n}\n\nbool\t\t\tPingPacket::waitForReply(int fd,\n\t\t\t\tconst Address& from,\n\t\t\t\tint millisecondsToBlock)\n{\n \/\/ block waiting on input. if the incoming message is not from the\n \/\/ indicated source then ignore it and go back to waiting. if the\n \/\/ incoming message is not a ping then ignore it and go back to waiting.\n float blockTime = 0.0001f * (float)millisecondsToBlock;\n TimeKeeper startTime = TimeKeeper::getCurrent();\n TimeKeeper currentTime = startTime;\n do {\n \/\/ prepare timeout\n const float timeLeft = blockTime - (currentTime - startTime);\n struct timeval timeout;\n timeout.tv_sec = long(floorf(timeLeft));\n timeout.tv_usec = long(1.0e+6f * (timeLeft - floorf(timeLeft)));\n\n \/\/ wait for input\n fd_set read_set;\n FD_ZERO(&read_set);\n\/\/ turn off == signed\/unsigned mismatch on win32\n#if defined(_WIN32)\n#pragma warning(disable: 4018)\n#endif\n FD_SET(fd, &read_set);\n#if defined(_WIN32)\n#pragma warning(default: 4018)\n#endif\n int nfound = select(fd+1, (fd_set*)&read_set, NULL, NULL, &timeout);\n\n \/\/ if got a message read it. if a ping packet and from right\n \/\/ sender then return success.\n if (nfound < 0)\n return false;\n if (nfound > 0 && read(fd, NULL))\n if (sourceAddr == from)\n\treturn true;\n\n currentTime = TimeKeeper::getCurrent();\n } while (currentTime - startTime < blockTime);\n return false;\n}\n\nbool\t\t\tPingPacket::write(int fd,\n\t\t\t\t\tconst struct sockaddr_in* addr) const\n{\n char buffer[PacketSize];\n void* buf = buffer;\n buf = nboPackUShort(buf, PacketSize - 4);\n buf = nboPackUShort(buf, MsgPingCodeReply);\n buf = pack(buf, getServerVersion());\n return sendMulticast(fd, buffer, sizeof(buffer), addr) == sizeof(buffer);\n}\n\nbool\t\t\tPingPacket::isRequest(int fd,\n\t\t\t\tstruct sockaddr_in* addr)\n{\n if (fd < 0) return false;\n char buffer[6];\n void *msg = buffer;\n uint16_t len, code;\n int size = recvMulticast(fd, buffer, sizeof(buffer), addr);\n if (size < 2) return false;\n msg = nboUnpackUShort(msg, len);\n msg = nboUnpackUShort(msg, code);\n return code == MsgPingCodeRequest;\n}\n\nbool\t\t\tPingPacket::sendRequest(int fd,\n\t\t\t\t\tconst struct sockaddr_in* addr)\n{\n if (fd < 0 || !addr) return false;\n char buffer[6];\n void *msg = buffer;\n msg = nboPackUShort(msg, 2);\n msg = nboPackUShort(msg, MsgPingCodeRequest);\n msg = nboPackUShort(msg, (uint16_t) 0);\n return sendMulticast(fd, buffer, sizeof(buffer), addr) == sizeof(buffer);\n}\n\nvoid*\t\t\tPingPacket::unpack(void* buf, char* version)\n{\n buf = nboUnpackString(buf, version, 8);\n buf = serverId.unpack(buf);\n buf = sourceAddr.unpack(buf);\n buf = nboUnpackUShort(buf, gameStyle);\n buf = nboUnpackUShort(buf, maxShots);\n buf = nboUnpackUShort(buf, shakeWins);\n buf = nboUnpackUShort(buf, shakeTimeout);\n buf = nboUnpackUShort(buf, maxPlayerScore);\n buf = nboUnpackUShort(buf, maxTeamScore);\n buf = nboUnpackUShort(buf, maxTime);\n buf = nboUnpackUByte(buf, maxPlayers);\n buf = nboUnpackUByte(buf, rogueCount);\n buf = nboUnpackUByte(buf, rogueMax);\n buf = nboUnpackUByte(buf, redCount);\n buf = nboUnpackUByte(buf, redMax);\n buf = nboUnpackUByte(buf, greenCount);\n buf = nboUnpackUByte(buf, greenMax);\n buf = nboUnpackUByte(buf, blueCount);\n buf = nboUnpackUByte(buf, blueMax);\n buf = nboUnpackUByte(buf, purpleCount);\n buf = nboUnpackUByte(buf, purpleMax);\n buf = nboUnpackUByte(buf, observerCount);\n buf = nboUnpackUByte(buf, observerMax);\n return buf;\n}\n\nvoid*\t\t\tPingPacket::pack(void* buf, const char* version) const\n{\n buf = nboPackString(buf, version, 8);\n buf = serverId.pack(buf);\n buf = sourceAddr.pack(buf);\n buf = nboPackUShort(buf, gameStyle);\n buf = nboPackUShort(buf, maxShots);\n buf = nboPackUShort(buf, shakeWins);\n buf = nboPackUShort(buf, shakeTimeout);\t\/\/ 1\/10ths of second\n buf = nboPackUShort(buf, maxPlayerScore);\n buf = nboPackUShort(buf, maxTeamScore);\n buf = nboPackUShort(buf, maxTime);\n buf = nboPackUByte(buf, maxPlayers);\n buf = nboPackUByte(buf, rogueCount);\n buf = nboPackUByte(buf, rogueMax);\n buf = nboPackUByte(buf, redCount);\n buf = nboPackUByte(buf, redMax);\n buf = nboPackUByte(buf, greenCount);\n buf = nboPackUByte(buf, greenMax);\n buf = nboPackUByte(buf, blueCount);\n buf = nboPackUByte(buf, blueMax);\n buf = nboPackUByte(buf, purpleCount);\n buf = nboPackUByte(buf, purpleMax);\n buf = nboPackUByte(buf, observerCount);\n buf = nboPackUByte(buf, observerMax);\n return buf;\n}\n\nvoid\t\t\tPingPacket::packHex(char* buf) const\n{\n buf = packHex16(buf, gameStyle);\n buf = packHex16(buf, maxShots);\n buf = packHex16(buf, shakeWins);\n buf = packHex16(buf, shakeTimeout);\n buf = packHex16(buf, maxPlayerScore);\n buf = packHex16(buf, maxTeamScore);\n buf = packHex16(buf, maxTime);\n buf = packHex8(buf, maxPlayers);\n buf = packHex8(buf, rogueCount);\n buf = packHex8(buf, rogueMax);\n buf = packHex8(buf, redCount);\n buf = packHex8(buf, redMax);\n buf = packHex8(buf, greenCount);\n buf = packHex8(buf, greenMax);\n buf = packHex8(buf, blueCount);\n buf = packHex8(buf, blueMax);\n buf = packHex8(buf, purpleCount);\n buf = packHex8(buf, purpleMax);\n buf = packHex8(buf, observerCount);\n buf = packHex8(buf, observerMax);\n *buf = 0;\n}\n\nvoid\t\t\tPingPacket::unpackHex(char* buf)\n{\n buf = unpackHex16(buf, gameStyle);\n buf = unpackHex16(buf, maxShots);\n buf = unpackHex16(buf, shakeWins);\n buf = unpackHex16(buf, shakeTimeout);\n buf = unpackHex16(buf, maxPlayerScore);\n buf = unpackHex16(buf, maxTeamScore);\n buf = unpackHex16(buf, maxTime);\n buf = unpackHex8(buf, maxPlayers);\n buf = unpackHex8(buf, rogueCount);\n buf = unpackHex8(buf, rogueMax);\n buf = unpackHex8(buf, redCount);\n buf = unpackHex8(buf, redMax);\n buf = unpackHex8(buf, greenCount);\n buf = unpackHex8(buf, greenMax);\n buf = unpackHex8(buf, blueCount);\n buf = unpackHex8(buf, blueMax);\n buf = unpackHex8(buf, purpleCount);\n buf = unpackHex8(buf, purpleMax);\n buf = unpackHex8(buf, observerCount);\n buf = unpackHex8(buf, observerMax);\n}\n\nint\t\t\tPingPacket::hex2bin(char d)\n{\n switch (d) {\n case '0': return 0;\n case '1': return 1;\n case '2': return 2;\n case '3': return 3;\n case '4': return 4;\n case '5': return 5;\n case '6': return 6;\n case '7': return 7;\n case '8': return 8;\n case '9': return 9;\n case 'A':\n case 'a': return 10;\n case 'B':\n case 'b': return 11;\n case 'C':\n case 'c': return 12;\n case 'D':\n case 'd': return 13;\n case 'E':\n case 'e': return 14;\n case 'F':\n case 'f': return 15;\n }\n return 0;\n}\n\nchar\t\t\tPingPacket::bin2hex(int d)\n{\n static const char* digit = \"0123456789abcdef\";\n return digit[d];\n}\n\nchar*\t\t\tPingPacket::packHex16(char* buf, uint16_t v)\n{\n *buf++ = bin2hex((v >> 12) & 0xf);\n *buf++ = bin2hex((v >> 8) & 0xf);\n *buf++ = bin2hex((v >> 4) & 0xf);\n *buf++ = bin2hex( v & 0xf);\n return buf;\n}\n\nchar*\t\t\tPingPacket::unpackHex16(char* buf, uint16_t& v)\n{\n uint16_t d = 0;\n d = (d << 4) | hex2bin(*buf++);\n d = (d << 4) | hex2bin(*buf++);\n d = (d << 4) | hex2bin(*buf++);\n d = (d << 4) | hex2bin(*buf++);\n v = d;\n return buf;\n}\n\nchar*\t\t\tPingPacket::packHex8(char* buf, uint8_t v)\n{\n *buf++ = bin2hex((v >> 4) & 0xf);\n *buf++ = bin2hex( v & 0xf);\n return buf;\n}\n\nchar*\t\t\tPingPacket::unpackHex8(char* buf, uint8_t& v)\n{\n uint16_t d = 0;\n d = (d << 4) | hex2bin(*buf++);\n d = (d << 4) | hex2bin(*buf++);\n v = d;\n return buf;\n}\n\nvoid\t\t\t PingPacket::zeroPlayerCounts()\n{\n rogueCount = 0;\n redCount = 0;\n greenCount = 0;\n blueCount = 0;\n purpleCount = 0;\n observerCount = 0;\n}\n\n\/\/ serialize packet to file -- note lack of error checking\n\/\/ must write to a binary file if we use plain \"pack\"\nvoid\t\t\t PingPacket::writeToFile (std::ostream& out) const\n{\n if (!out) return;\n\n char buffer[PingPacket::PacketSize];\n void* buf = buffer;\n buf = nboPackUShort(buf, PingPacket::PacketSize - 4);\n buf = nboPackUShort(buf, MsgPingCodeReply);\n buf = pack(buf, getServerVersion());\n out.write(buffer,sizeof(buffer));\n}\n\n\/\/ de serialize packet from file\n\/\/ must read from a binary file if we use plain \"unpack\"\nbool\t\t\t PingPacket::readFromFile(std::istream& in)\n{\n if (!in) return false;\n\n char buffer[PingPacket::PacketSize], serverVersion[9];\n uint16_t len, code;\n\n \/\/ get packet\n in.read(buffer, sizeof(buffer));\n if ((size_t)in.gcount() < sizeof(buffer)){\n return false;\n }\n\n \/\/ decode header\n void* buf = buffer;\n buf = nboUnpackUShort(buf, len);\n buf = nboUnpackUShort(buf, code);\n\n \/\/ make sure we got the rest of the message\n if (len != in.gcount() - 4){\n return false;\n }\n\n \/\/ unpack body of reply\n buf = unpack(buf, serverVersion);\n\n \/\/ compare version against my version. ignore last character of\n \/\/ version number. that's only used to indicate compatible\n \/\/ client-side changes.\n return (strncmp(serverVersion, getServerVersion(), 7) == 0);\n}\n\n\/\/ Local variables: ***\n\/\/ mode:C++ ***\n\/\/ tab-width: 8 ***\n\/\/ c-basic-offset: 2 ***\n\/\/ indent-tabs-mode: t ***\n\/\/ End: ***\n\/\/ ex: shiftwidth=2 tabstop=8\n\n\n<commit_msg>typecast 2byte value to 1 byte value<commit_after>\/* bzflag\n * Copyright (c) 1993 - 2003 Tim Riker\n *\n * This package is free software; you can redistribute it and\/or\n * modify it under the terms of the license found in the file\n * named COPYING that should have accompanied this file.\n *\n * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR\n * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED\n * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.\n *\/\n\/\/ todo make this turn off for .net\n#if defined(_WIN32)\n\t#pragma warning(disable: 4786)\n#endif\n\n\n#include <string.h>\n#include <math.h>\n#include <ctype.h>\n#include <fstream>\n#include \"common.h\"\n#include \"global.h\"\n#include \"Ping.h\"\n#include \"Protocol.h\"\n#include \"TimeKeeper.h\"\n#include \"bzfio.h\"\n\n\/\/ incessint rebuilding for current versioning\n#include \"version.h\"\n\n\n\/\/\n\/\/ PingPacket\n\/\/\n\nconst int\t\tPingPacket::PacketSize = ServerIdPLen + 52;\n\nPingPacket::PingPacket() : gameStyle(PlainGameStyle),\n\t\t\t\tmaxShots(1),\n\t\t\t\tshakeWins(0),\n\t\t\t\tshakeTimeout(0),\n\t\t\t\tmaxPlayerScore(0),\n\t\t\t\tmaxTeamScore(0),\n\t\t\t\tmaxTime(0),\n\t\t\t\tmaxPlayers(1),\n\t\t\t\trogueCount(0),\n\t\t\t\trogueMax(1),\n\t\t\t\tredCount(0),\n\t\t\t\tredMax(1),\n\t\t\t\tgreenCount(0),\n\t\t\t\tgreenMax(1),\n\t\t\t\tblueCount(0),\n\t\t\t\tblueMax(1),\n\t\t\t\tpurpleCount(0),\n\t\t\t\tpurpleMax(1),\n\t\t\t\tobserverCount(0),\n\t\t\t\tobserverMax(1)\n{\n \/\/ do nothing\n}\n\nPingPacket::~PingPacket()\n{\n \/\/ do nothing\n}\n\nbool\t\t\tPingPacket::read(int fd, struct sockaddr_in* addr)\n{\n char buffer[PacketSize], serverVersion[9];\n uint16_t len, code;\n\n \/\/ get packet\n int n = recvMulticast(fd, buffer, sizeof(buffer), addr);\n if (n < 4)\n return false;\n\n \/\/ decode header\n void* buf = buffer;\n buf = nboUnpackUShort(buf, len);\n buf = nboUnpackUShort(buf, code);\n\n \/\/ make sure we got the rest of the message\n if (len != n - 4)\n return false;\n\n \/\/ check that it's a reply\n if (code != MsgPingCodeReply)\n return false;\n\n \/\/ unpack body of reply\n buf = unpack(buf, serverVersion);\n\n \/\/ compare version against my version. ignore last character of\n \/\/ version number. that's only used to indicate compatible\n \/\/ client-side changes.\n return (strncmp(serverVersion, getServerVersion(), 7) == 0);\n}\n\nbool\t\t\tPingPacket::waitForReply(int fd,\n\t\t\t\tconst Address& from,\n\t\t\t\tint millisecondsToBlock)\n{\n \/\/ block waiting on input. if the incoming message is not from the\n \/\/ indicated source then ignore it and go back to waiting. if the\n \/\/ incoming message is not a ping then ignore it and go back to waiting.\n float blockTime = 0.0001f * (float)millisecondsToBlock;\n TimeKeeper startTime = TimeKeeper::getCurrent();\n TimeKeeper currentTime = startTime;\n do {\n \/\/ prepare timeout\n const float timeLeft = blockTime - (currentTime - startTime);\n struct timeval timeout;\n timeout.tv_sec = long(floorf(timeLeft));\n timeout.tv_usec = long(1.0e+6f * (timeLeft - floorf(timeLeft)));\n\n \/\/ wait for input\n fd_set read_set;\n FD_ZERO(&read_set);\n\/\/ turn off == signed\/unsigned mismatch on win32\n#if defined(_WIN32)\n#pragma warning(disable: 4018)\n#endif\n FD_SET(fd, &read_set);\n#if defined(_WIN32)\n#pragma warning(default: 4018)\n#endif\n int nfound = select(fd+1, (fd_set*)&read_set, NULL, NULL, &timeout);\n\n \/\/ if got a message read it. if a ping packet and from right\n \/\/ sender then return success.\n if (nfound < 0)\n return false;\n if (nfound > 0 && read(fd, NULL))\n if (sourceAddr == from)\n\treturn true;\n\n currentTime = TimeKeeper::getCurrent();\n } while (currentTime - startTime < blockTime);\n return false;\n}\n\nbool\t\t\tPingPacket::write(int fd,\n\t\t\t\t\tconst struct sockaddr_in* addr) const\n{\n char buffer[PacketSize];\n void* buf = buffer;\n buf = nboPackUShort(buf, PacketSize - 4);\n buf = nboPackUShort(buf, MsgPingCodeReply);\n buf = pack(buf, getServerVersion());\n return sendMulticast(fd, buffer, sizeof(buffer), addr) == sizeof(buffer);\n}\n\nbool\t\t\tPingPacket::isRequest(int fd,\n\t\t\t\tstruct sockaddr_in* addr)\n{\n if (fd < 0) return false;\n char buffer[6];\n void *msg = buffer;\n uint16_t len, code;\n int size = recvMulticast(fd, buffer, sizeof(buffer), addr);\n if (size < 2) return false;\n msg = nboUnpackUShort(msg, len);\n msg = nboUnpackUShort(msg, code);\n return code == MsgPingCodeRequest;\n}\n\nbool\t\t\tPingPacket::sendRequest(int fd,\n\t\t\t\t\tconst struct sockaddr_in* addr)\n{\n if (fd < 0 || !addr) return false;\n char buffer[6];\n void *msg = buffer;\n msg = nboPackUShort(msg, 2);\n msg = nboPackUShort(msg, MsgPingCodeRequest);\n msg = nboPackUShort(msg, (uint16_t) 0);\n return sendMulticast(fd, buffer, sizeof(buffer), addr) == sizeof(buffer);\n}\n\nvoid*\t\t\tPingPacket::unpack(void* buf, char* version)\n{\n buf = nboUnpackString(buf, version, 8);\n buf = serverId.unpack(buf);\n buf = sourceAddr.unpack(buf);\n buf = nboUnpackUShort(buf, gameStyle);\n buf = nboUnpackUShort(buf, maxShots);\n buf = nboUnpackUShort(buf, shakeWins);\n buf = nboUnpackUShort(buf, shakeTimeout);\n buf = nboUnpackUShort(buf, maxPlayerScore);\n buf = nboUnpackUShort(buf, maxTeamScore);\n buf = nboUnpackUShort(buf, maxTime);\n buf = nboUnpackUByte(buf, maxPlayers);\n buf = nboUnpackUByte(buf, rogueCount);\n buf = nboUnpackUByte(buf, rogueMax);\n buf = nboUnpackUByte(buf, redCount);\n buf = nboUnpackUByte(buf, redMax);\n buf = nboUnpackUByte(buf, greenCount);\n buf = nboUnpackUByte(buf, greenMax);\n buf = nboUnpackUByte(buf, blueCount);\n buf = nboUnpackUByte(buf, blueMax);\n buf = nboUnpackUByte(buf, purpleCount);\n buf = nboUnpackUByte(buf, purpleMax);\n buf = nboUnpackUByte(buf, observerCount);\n buf = nboUnpackUByte(buf, observerMax);\n return buf;\n}\n\nvoid*\t\t\tPingPacket::pack(void* buf, const char* version) const\n{\n buf = nboPackString(buf, version, 8);\n buf = serverId.pack(buf);\n buf = sourceAddr.pack(buf);\n buf = nboPackUShort(buf, gameStyle);\n buf = nboPackUShort(buf, maxShots);\n buf = nboPackUShort(buf, shakeWins);\n buf = nboPackUShort(buf, shakeTimeout);\t\/\/ 1\/10ths of second\n buf = nboPackUShort(buf, maxPlayerScore);\n buf = nboPackUShort(buf, maxTeamScore);\n buf = nboPackUShort(buf, maxTime);\n buf = nboPackUByte(buf, maxPlayers);\n buf = nboPackUByte(buf, rogueCount);\n buf = nboPackUByte(buf, rogueMax);\n buf = nboPackUByte(buf, redCount);\n buf = nboPackUByte(buf, redMax);\n buf = nboPackUByte(buf, greenCount);\n buf = nboPackUByte(buf, greenMax);\n buf = nboPackUByte(buf, blueCount);\n buf = nboPackUByte(buf, blueMax);\n buf = nboPackUByte(buf, purpleCount);\n buf = nboPackUByte(buf, purpleMax);\n buf = nboPackUByte(buf, observerCount);\n buf = nboPackUByte(buf, observerMax);\n return buf;\n}\n\nvoid\t\t\tPingPacket::packHex(char* buf) const\n{\n buf = packHex16(buf, gameStyle);\n buf = packHex16(buf, maxShots);\n buf = packHex16(buf, shakeWins);\n buf = packHex16(buf, shakeTimeout);\n buf = packHex16(buf, maxPlayerScore);\n buf = packHex16(buf, maxTeamScore);\n buf = packHex16(buf, maxTime);\n buf = packHex8(buf, maxPlayers);\n buf = packHex8(buf, rogueCount);\n buf = packHex8(buf, rogueMax);\n buf = packHex8(buf, redCount);\n buf = packHex8(buf, redMax);\n buf = packHex8(buf, greenCount);\n buf = packHex8(buf, greenMax);\n buf = packHex8(buf, blueCount);\n buf = packHex8(buf, blueMax);\n buf = packHex8(buf, purpleCount);\n buf = packHex8(buf, purpleMax);\n buf = packHex8(buf, observerCount);\n buf = packHex8(buf, observerMax);\n *buf = 0;\n}\n\nvoid\t\t\tPingPacket::unpackHex(char* buf)\n{\n buf = unpackHex16(buf, gameStyle);\n buf = unpackHex16(buf, maxShots);\n buf = unpackHex16(buf, shakeWins);\n buf = unpackHex16(buf, shakeTimeout);\n buf = unpackHex16(buf, maxPlayerScore);\n buf = unpackHex16(buf, maxTeamScore);\n buf = unpackHex16(buf, maxTime);\n buf = unpackHex8(buf, maxPlayers);\n buf = unpackHex8(buf, rogueCount);\n buf = unpackHex8(buf, rogueMax);\n buf = unpackHex8(buf, redCount);\n buf = unpackHex8(buf, redMax);\n buf = unpackHex8(buf, greenCount);\n buf = unpackHex8(buf, greenMax);\n buf = unpackHex8(buf, blueCount);\n buf = unpackHex8(buf, blueMax);\n buf = unpackHex8(buf, purpleCount);\n buf = unpackHex8(buf, purpleMax);\n buf = unpackHex8(buf, observerCount);\n buf = unpackHex8(buf, observerMax);\n}\n\nint\t\t\tPingPacket::hex2bin(char d)\n{\n switch (d) {\n case '0': return 0;\n case '1': return 1;\n case '2': return 2;\n case '3': return 3;\n case '4': return 4;\n case '5': return 5;\n case '6': return 6;\n case '7': return 7;\n case '8': return 8;\n case '9': return 9;\n case 'A':\n case 'a': return 10;\n case 'B':\n case 'b': return 11;\n case 'C':\n case 'c': return 12;\n case 'D':\n case 'd': return 13;\n case 'E':\n case 'e': return 14;\n case 'F':\n case 'f': return 15;\n }\n return 0;\n}\n\nchar\t\t\tPingPacket::bin2hex(int d)\n{\n static const char* digit = \"0123456789abcdef\";\n return digit[d];\n}\n\nchar*\t\t\tPingPacket::packHex16(char* buf, uint16_t v)\n{\n *buf++ = bin2hex((v >> 12) & 0xf);\n *buf++ = bin2hex((v >> 8) & 0xf);\n *buf++ = bin2hex((v >> 4) & 0xf);\n *buf++ = bin2hex( v & 0xf);\n return buf;\n}\n\nchar*\t\t\tPingPacket::unpackHex16(char* buf, uint16_t& v)\n{\n uint16_t d = 0;\n d = (d << 4) | hex2bin(*buf++);\n d = (d << 4) | hex2bin(*buf++);\n d = (d << 4) | hex2bin(*buf++);\n d = (d << 4) | hex2bin(*buf++);\n v = d;\n return buf;\n}\n\nchar*\t\t\tPingPacket::packHex8(char* buf, uint8_t v)\n{\n *buf++ = bin2hex((v >> 4) & 0xf);\n *buf++ = bin2hex( v & 0xf);\n return buf;\n}\n\nchar*\t\t\tPingPacket::unpackHex8(char* buf, uint8_t& v)\n{\n uint16_t d = 0;\n d = (d << 4) | hex2bin(*buf++);\n d = (d << 4) | hex2bin(*buf++);\n v = (uint8_t)d;\n return buf;\n}\n\nvoid\t\t\t PingPacket::zeroPlayerCounts()\n{\n rogueCount = 0;\n redCount = 0;\n greenCount = 0;\n blueCount = 0;\n purpleCount = 0;\n observerCount = 0;\n}\n\n\/\/ serialize packet to file -- note lack of error checking\n\/\/ must write to a binary file if we use plain \"pack\"\nvoid\t\t\t PingPacket::writeToFile (std::ostream& out) const\n{\n if (!out) return;\n\n char buffer[PingPacket::PacketSize];\n void* buf = buffer;\n buf = nboPackUShort(buf, PingPacket::PacketSize - 4);\n buf = nboPackUShort(buf, MsgPingCodeReply);\n buf = pack(buf, getServerVersion());\n out.write(buffer,sizeof(buffer));\n}\n\n\/\/ de serialize packet from file\n\/\/ must read from a binary file if we use plain \"unpack\"\nbool\t\t\t PingPacket::readFromFile(std::istream& in)\n{\n if (!in) return false;\n\n char buffer[PingPacket::PacketSize], serverVersion[9];\n uint16_t len, code;\n\n \/\/ get packet\n in.read(buffer, sizeof(buffer));\n if ((size_t)in.gcount() < sizeof(buffer)){\n return false;\n }\n\n \/\/ decode header\n void* buf = buffer;\n buf = nboUnpackUShort(buf, len);\n buf = nboUnpackUShort(buf, code);\n\n \/\/ make sure we got the rest of the message\n if (len != in.gcount() - 4){\n return false;\n }\n\n \/\/ unpack body of reply\n buf = unpack(buf, serverVersion);\n\n \/\/ compare version against my version. ignore last character of\n \/\/ version number. that's only used to indicate compatible\n \/\/ client-side changes.\n return (strncmp(serverVersion, getServerVersion(), 7) == 0);\n}\n\n\/\/ Local variables: ***\n\/\/ mode:C++ ***\n\/\/ tab-width: 8 ***\n\/\/ c-basic-offset: 2 ***\n\/\/ indent-tabs-mode: t ***\n\/\/ End: ***\n\/\/ ex: shiftwidth=2 tabstop=8\n\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Scriptorium.cpp\n * openc2e\n *\n * Created by Alyssa Milburn on Wed 10 Nov 2004.\n * Copyright (c) 2004-2006 Alyssa Milburn. All rights reserved.\n * Copyright (c) 2005 Bryan Donlan. All rights reserved.\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n *\/\n\n#include \"Scriptorium.h\"\n#include <iostream>\n\ninline unsigned int Scriptorium::calculateValue(unsigned char family, unsigned char genus, unsigned short species) {\n\treturn (family + (genus << 8) + (species << 16));\n}\n\nvoid Scriptorium::addScript(unsigned char family, unsigned char genus, unsigned short species, unsigned short event, shared_ptr<script> s) {\n\tstd::map<unsigned short, shared_ptr<script> > &m = getScripts(calculateValue(family, genus, species));\n\tm[event] = s;\n}\n\nvoid Scriptorium::delScript(unsigned char family, unsigned char genus, unsigned short species, unsigned short event) {\n\t\/\/ Retrieve the list of scripts for the classifier, return if there aren't any.\n\tstd::map<unsigned int, std::map<unsigned short, shared_ptr<script> > >::iterator x = scripts.find(calculateValue(family, genus, species));\n\tif (x == scripts.end())\n\t\treturn;\n\n\t\/\/ Retrieve the script, return if it doesn't exist.\n\tstd::map<unsigned short, shared_ptr<script> >::iterator j = x->second.find(event);\n\tif (j == x->second.end())\n\t\treturn;\n\n\t\/\/ Erase the script.\n\tx->second.erase(j);\n\n\t\/\/ If there are no scripts left, erase the whole list of scripts for this classifier.\n\tif (x->second.size() == 0)\n\t\tscripts.erase(x);\n}\n\nshared_ptr<script> Scriptorium::getScript(unsigned char family, unsigned char genus, unsigned short species, unsigned short event) {\n\tstd::map<unsigned short, shared_ptr<script> > &x = getScripts(calculateValue(family, genus, species));\n\tif (x.find(event) == x.end()) {\n\t\tstd::map<unsigned short, shared_ptr<script> > &x = getScripts(calculateValue(family, genus, 0));\n\t\tif (x.find(event) == x.end()) {\n\t\t\tstd::map<unsigned short, shared_ptr<script> > &x = getScripts(calculateValue(family, 0, 0));\n\t\t\tif (x.find(event) == x.end())\n\t\t\t\treturn shared_ptr<script>();\n\t\t\telse\n\t\t\t\treturn x[event];\n\t\t} else return x[event];\n\t} else return x[event];\n}\n\n\/* vim: set noet: *\/\n<commit_msg>Scriptorium: match scripts with family\/genus\/species of 0\/0\/0 as a last resort<commit_after>\/*\n * Scriptorium.cpp\n * openc2e\n *\n * Created by Alyssa Milburn on Wed 10 Nov 2004.\n * Copyright (c) 2004-2006 Alyssa Milburn. All rights reserved.\n * Copyright (c) 2005 Bryan Donlan. All rights reserved.\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n *\/\n\n#include \"Scriptorium.h\"\n#include <iostream>\n\ninline unsigned int Scriptorium::calculateValue(unsigned char family, unsigned char genus, unsigned short species) {\n\treturn (family + (genus << 8) + (species << 16));\n}\n\nvoid Scriptorium::addScript(unsigned char family, unsigned char genus, unsigned short species, unsigned short event, shared_ptr<script> s) {\n\tstd::map<unsigned short, shared_ptr<script> > &m = getScripts(calculateValue(family, genus, species));\n\tm[event] = s;\n}\n\nvoid Scriptorium::delScript(unsigned char family, unsigned char genus, unsigned short species, unsigned short event) {\n\t\/\/ Retrieve the list of scripts for the classifier, return if there aren't any.\n\tstd::map<unsigned int, std::map<unsigned short, shared_ptr<script> > >::iterator x = scripts.find(calculateValue(family, genus, species));\n\tif (x == scripts.end())\n\t\treturn;\n\n\t\/\/ Retrieve the script, return if it doesn't exist.\n\tstd::map<unsigned short, shared_ptr<script> >::iterator j = x->second.find(event);\n\tif (j == x->second.end())\n\t\treturn;\n\n\t\/\/ Erase the script.\n\tx->second.erase(j);\n\n\t\/\/ If there are no scripts left, erase the whole list of scripts for this classifier.\n\tif (x->second.size() == 0)\n\t\tscripts.erase(x);\n}\n\nshared_ptr<script> Scriptorium::getScript(unsigned char family, unsigned char genus, unsigned short species, unsigned short event) {\n\tstd::map<unsigned short, shared_ptr<script> > &x = getScripts(calculateValue(family, genus, species));\n\tif (x.find(event) == x.end()) {\n\t\tstd::map<unsigned short, shared_ptr<script> > &x = getScripts(calculateValue(family, genus, 0));\n\t\tif (x.find(event) == x.end()) {\n\t\t\tstd::map<unsigned short, shared_ptr<script> > &x = getScripts(calculateValue(family, 0, 0));\n\t\t\tif (x.find(event) == x.end()) {\n\t\t\t\tstd::map<unsigned short, shared_ptr<script> > &x = getScripts(calculateValue(0, 0, 0));\n\t\t\t\tif (x.find(event) == x.end()) {\n\t\t\t\t\treturn shared_ptr<script>();\n\t\t\t\t} else return x[event];\n\t\t\t} else return x[event];\n\t\t} else return x[event];\n\t} else return x[event];\n}\n\n\/* vim: set noet: *\/\n<|endoftext|>"} {"text":"<commit_before>\/\/===-- DynamicLibrary.cpp - Runtime link\/load libraries --------*- C++ -*-===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file was developed by Reid Spencer and is distributed under the\n\/\/ University of Illinois Open Source License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This header file implements the operating system DynamicLibrary concept.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/System\/DynamicLibrary.h\"\n#include \"llvm\/Config\/config.h\"\n#include <map>\n\n\/\/ Collection of symbol name\/value pairs to be searched prior to any libraries.\nstatic std::map<std::string, void *> g_symbols;\n\nvoid llvm::sys::DynamicLibrary::AddSymbol(const char* symbolName,\n void *symbolValue) {\n g_symbols[symbolName] = symbolValue;\n}\n\n\/\/ It is not possible to use ltdl.c on VC++ builds as the terms of its LGPL\n\/\/ license and special exception would cause all of LLVM to be placed under\n\/\/ the LGPL. This is because the exception applies only when libtool is\n\/\/ used, and obviously libtool is not used with Visual Studio. An entirely\n\/\/ separate implementation is provided in win32\/DynamicLibrary.cpp.\n\n#ifdef LLVM_ON_WIN32\n\n#include \"Win32\/DynamicLibrary.inc\"\n\n#else\n\n#include \"ltdl.h\"\n#include <cassert>\nusing namespace llvm;\nusing namespace llvm::sys;\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/=== WARNING: Implementation here must contain only TRULY operating system\n\/\/=== independent code.\n\/\/===----------------------------------------------------------------------===\/\/\n\nstatic inline void check_ltdl_initialization() {\n static bool did_initialize_ltdl = false;\n if (!did_initialize_ltdl) {\n int Err = lt_dlinit();\n assert(0 == Err && \"Can't init the ltdl library\");\n did_initialize_ltdl = true;\n }\n}\n\nstatic std::vector<lt_dlhandle> OpenedHandles;\n\nDynamicLibrary::DynamicLibrary() : handle(0) {\n check_ltdl_initialization();\n\n lt_dlhandle a_handle = lt_dlopen(0);\n\n assert(a_handle == 0 || \"Can't open program as dynamic library\");\n\n handle = a_handle;\n OpenedHandles.push_back(a_handle);\n}\n\n\/*\nDynamicLibrary::DynamicLibrary(const char*filename) : handle(0) {\n check_ltdl_initialization();\n\n lt_dlhandle a_handle = lt_dlopen(filename);\n\n if (a_handle == 0)\n a_handle = lt_dlopenext(filename);\n\n if (a_handle == 0)\n throw std::string(\"Can't open :\") + filename + \": \" + lt_dlerror();\n\n handle = a_handle;\n OpenedHandles.push_back(a_handle);\n}\n*\/\n\nDynamicLibrary::~DynamicLibrary() {\n lt_dlhandle a_handle = (lt_dlhandle) handle;\n if (a_handle) {\n lt_dlclose(a_handle);\n\n for (std::vector<lt_dlhandle>::iterator I = OpenedHandles.begin(),\n E = OpenedHandles.end(); I != E; ++I) {\n if (*I == a_handle) {\n \/\/ Note: don't use the swap\/pop_back trick here. Order is important.\n OpenedHandles.erase(I);\n return;\n }\n }\n }\n}\n\nbool DynamicLibrary::LoadLibraryPermanently(const char *Filename,\n std::string *ErrMsg) {\n check_ltdl_initialization();\n lt_dlhandle a_handle = lt_dlopen(Filename);\n\n if (a_handle == 0)\n a_handle = lt_dlopenext(Filename);\n\n if (a_handle == 0) {\n if (ErrMsg)\n *ErrMsg = std::string(\"Can't open :\") +\n (Filename ? Filename : \"<current process>\") + \": \" + lt_dlerror();\n return true;\n }\n\n lt_dlmakeresident(a_handle);\n\n OpenedHandles.push_back(a_handle);\n return false;\n}\n\nvoid* DynamicLibrary::SearchForAddressOfSymbol(const char* symbolName) {\n check_ltdl_initialization();\n\n \/\/ First check symbols added via AddSymbol().\n std::map<std::string, void *>::iterator I = g_symbols.find(symbolName);\n if (I != g_symbols.end())\n return I->second;\n\n \/\/ Now search the libraries.\n for (std::vector<lt_dlhandle>::iterator I = OpenedHandles.begin(),\n E = OpenedHandles.end(); I != E; ++I) {\n lt_ptr ptr = lt_dlsym(*I, symbolName);\n if (ptr)\n return ptr;\n }\n\n \/\/ If this is darwin, it has some funky issues, try to solve them here. Some\n \/\/ important symbols are marked 'private external' which doesn't allow\n \/\/ SearchForAddressOfSymbol to find them. As such, we special case them here,\n \/\/ there is only a small handful of them.\n\n#ifdef __APPLE__\n#define EXPLICIT_SYMBOL(SYM) \\\n extern void *SYM; if (!strcmp(symbolName, #SYM)) return &SYM\n {\n EXPLICIT_SYMBOL(__ashldi3);\n EXPLICIT_SYMBOL(__ashrdi3);\n EXPLICIT_SYMBOL(__cmpdi2);\n EXPLICIT_SYMBOL(__divdi3);\n EXPLICIT_SYMBOL(__eprintf);\n EXPLICIT_SYMBOL(__fixdfdi);\n EXPLICIT_SYMBOL(__fixsfdi);\n EXPLICIT_SYMBOL(__fixunsdfdi);\n EXPLICIT_SYMBOL(__fixunssfdi);\n EXPLICIT_SYMBOL(__floatdidf);\n EXPLICIT_SYMBOL(__floatdisf);\n EXPLICIT_SYMBOL(__lshrdi3);\n EXPLICIT_SYMBOL(__moddi3);\n EXPLICIT_SYMBOL(__udivdi3);\n EXPLICIT_SYMBOL(__umoddi3);\n }\n#undef EXPLICIT_SYMBOL\n#endif\n\n\/\/ This macro returns the address of a well-known, explicit symbol\n#define EXPLICIT_SYMBOL(SYM) \\\n if (!strcmp(symbolName, #SYM)) return &SYM\n\n\/\/ On linux we have a weird situation. The stderr\/out\/in symbols are both\n\/\/ macros and global variables because of standards requirements. So, we \n\/\/ boldly use the EXPLICIT_SYMBOL macro without checking for a #define first.\n#if defined(__linux__)\n {\n EXPLICIT_SYMBOL(stderr);\n EXPLICIT_SYMBOL(stdout);\n EXPLICIT_SYMBOL(stdin);\n }\n#else\n \/\/ For everything else, we want to check to make sure the symbol isn't defined\n \/\/ as a macro before using EXPLICIT_SYMBOL.\n {\n#ifndef stdin\n EXPLICIT_SYMBOL(stdin);\n#endif\n#ifndef stdout\n EXPLICIT_SYMBOL(stdout);\n#endif\n#ifndef stderr\n EXPLICIT_SYMBOL(stderr);\n#endif\n }\n#endif\n#undef EXPLICIT_SYMBOL\n\n return 0;\n}\n\nvoid *DynamicLibrary::GetAddressOfSymbol(const char *symbolName) {\n assert(handle != 0 && \"Invalid DynamicLibrary handle\");\n return lt_dlsym((lt_dlhandle) handle, symbolName);\n}\n\n#endif \/\/ LLVM_ON_WIN32\n\nDEFINING_FILE_FOR(SystemDynamicLibrary)\n<commit_msg>silence warning<commit_after>\/\/===-- DynamicLibrary.cpp - Runtime link\/load libraries --------*- C++ -*-===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file was developed by Reid Spencer and is distributed under the\n\/\/ University of Illinois Open Source License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This header file implements the operating system DynamicLibrary concept.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/System\/DynamicLibrary.h\"\n#include \"llvm\/Config\/config.h\"\n#include <map>\n\n\/\/ Collection of symbol name\/value pairs to be searched prior to any libraries.\nstatic std::map<std::string, void *> g_symbols;\n\nvoid llvm::sys::DynamicLibrary::AddSymbol(const char* symbolName,\n void *symbolValue) {\n g_symbols[symbolName] = symbolValue;\n}\n\n\/\/ It is not possible to use ltdl.c on VC++ builds as the terms of its LGPL\n\/\/ license and special exception would cause all of LLVM to be placed under\n\/\/ the LGPL. This is because the exception applies only when libtool is\n\/\/ used, and obviously libtool is not used with Visual Studio. An entirely\n\/\/ separate implementation is provided in win32\/DynamicLibrary.cpp.\n\n#ifdef LLVM_ON_WIN32\n\n#include \"Win32\/DynamicLibrary.inc\"\n\n#else\n\n#include \"ltdl.h\"\n#include <cassert>\nusing namespace llvm;\nusing namespace llvm::sys;\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/=== WARNING: Implementation here must contain only TRULY operating system\n\/\/=== independent code.\n\/\/===----------------------------------------------------------------------===\/\/\n\nstatic inline void check_ltdl_initialization() {\n static bool did_initialize_ltdl = false;\n if (!did_initialize_ltdl) {\n int Err = lt_dlinit();\n Err = Err; \/\/ Silence warning.\n assert(0 == Err && \"Can't init the ltdl library\");\n did_initialize_ltdl = true;\n }\n}\n\nstatic std::vector<lt_dlhandle> OpenedHandles;\n\nDynamicLibrary::DynamicLibrary() : handle(0) {\n check_ltdl_initialization();\n\n lt_dlhandle a_handle = lt_dlopen(0);\n\n assert(a_handle == 0 || \"Can't open program as dynamic library\");\n\n handle = a_handle;\n OpenedHandles.push_back(a_handle);\n}\n\n\/*\nDynamicLibrary::DynamicLibrary(const char*filename) : handle(0) {\n check_ltdl_initialization();\n\n lt_dlhandle a_handle = lt_dlopen(filename);\n\n if (a_handle == 0)\n a_handle = lt_dlopenext(filename);\n\n if (a_handle == 0)\n throw std::string(\"Can't open :\") + filename + \": \" + lt_dlerror();\n\n handle = a_handle;\n OpenedHandles.push_back(a_handle);\n}\n*\/\n\nDynamicLibrary::~DynamicLibrary() {\n lt_dlhandle a_handle = (lt_dlhandle) handle;\n if (a_handle) {\n lt_dlclose(a_handle);\n\n for (std::vector<lt_dlhandle>::iterator I = OpenedHandles.begin(),\n E = OpenedHandles.end(); I != E; ++I) {\n if (*I == a_handle) {\n \/\/ Note: don't use the swap\/pop_back trick here. Order is important.\n OpenedHandles.erase(I);\n return;\n }\n }\n }\n}\n\nbool DynamicLibrary::LoadLibraryPermanently(const char *Filename,\n std::string *ErrMsg) {\n check_ltdl_initialization();\n lt_dlhandle a_handle = lt_dlopen(Filename);\n\n if (a_handle == 0)\n a_handle = lt_dlopenext(Filename);\n\n if (a_handle == 0) {\n if (ErrMsg)\n *ErrMsg = std::string(\"Can't open :\") +\n (Filename ? Filename : \"<current process>\") + \": \" + lt_dlerror();\n return true;\n }\n\n lt_dlmakeresident(a_handle);\n\n OpenedHandles.push_back(a_handle);\n return false;\n}\n\nvoid* DynamicLibrary::SearchForAddressOfSymbol(const char* symbolName) {\n check_ltdl_initialization();\n\n \/\/ First check symbols added via AddSymbol().\n std::map<std::string, void *>::iterator I = g_symbols.find(symbolName);\n if (I != g_symbols.end())\n return I->second;\n\n \/\/ Now search the libraries.\n for (std::vector<lt_dlhandle>::iterator I = OpenedHandles.begin(),\n E = OpenedHandles.end(); I != E; ++I) {\n lt_ptr ptr = lt_dlsym(*I, symbolName);\n if (ptr)\n return ptr;\n }\n\n \/\/ If this is darwin, it has some funky issues, try to solve them here. Some\n \/\/ important symbols are marked 'private external' which doesn't allow\n \/\/ SearchForAddressOfSymbol to find them. As such, we special case them here,\n \/\/ there is only a small handful of them.\n\n#ifdef __APPLE__\n#define EXPLICIT_SYMBOL(SYM) \\\n extern void *SYM; if (!strcmp(symbolName, #SYM)) return &SYM\n {\n EXPLICIT_SYMBOL(__ashldi3);\n EXPLICIT_SYMBOL(__ashrdi3);\n EXPLICIT_SYMBOL(__cmpdi2);\n EXPLICIT_SYMBOL(__divdi3);\n EXPLICIT_SYMBOL(__eprintf);\n EXPLICIT_SYMBOL(__fixdfdi);\n EXPLICIT_SYMBOL(__fixsfdi);\n EXPLICIT_SYMBOL(__fixunsdfdi);\n EXPLICIT_SYMBOL(__fixunssfdi);\n EXPLICIT_SYMBOL(__floatdidf);\n EXPLICIT_SYMBOL(__floatdisf);\n EXPLICIT_SYMBOL(__lshrdi3);\n EXPLICIT_SYMBOL(__moddi3);\n EXPLICIT_SYMBOL(__udivdi3);\n EXPLICIT_SYMBOL(__umoddi3);\n }\n#undef EXPLICIT_SYMBOL\n#endif\n\n\/\/ This macro returns the address of a well-known, explicit symbol\n#define EXPLICIT_SYMBOL(SYM) \\\n if (!strcmp(symbolName, #SYM)) return &SYM\n\n\/\/ On linux we have a weird situation. The stderr\/out\/in symbols are both\n\/\/ macros and global variables because of standards requirements. So, we \n\/\/ boldly use the EXPLICIT_SYMBOL macro without checking for a #define first.\n#if defined(__linux__)\n {\n EXPLICIT_SYMBOL(stderr);\n EXPLICIT_SYMBOL(stdout);\n EXPLICIT_SYMBOL(stdin);\n }\n#else\n \/\/ For everything else, we want to check to make sure the symbol isn't defined\n \/\/ as a macro before using EXPLICIT_SYMBOL.\n {\n#ifndef stdin\n EXPLICIT_SYMBOL(stdin);\n#endif\n#ifndef stdout\n EXPLICIT_SYMBOL(stdout);\n#endif\n#ifndef stderr\n EXPLICIT_SYMBOL(stderr);\n#endif\n }\n#endif\n#undef EXPLICIT_SYMBOL\n\n return 0;\n}\n\nvoid *DynamicLibrary::GetAddressOfSymbol(const char *symbolName) {\n assert(handle != 0 && \"Invalid DynamicLibrary handle\");\n return lt_dlsym((lt_dlhandle) handle, symbolName);\n}\n\n#endif \/\/ LLVM_ON_WIN32\n\nDEFINING_FILE_FOR(SystemDynamicLibrary)\n<|endoftext|>"} {"text":"<commit_before>\/***************************************************************\n *\n * Copyright (C) 1990-2007, Condor Team, Computer Sciences Department,\n * University of Wisconsin-Madison, WI.\n * \n * Licensed under the Apache License, Version 2.0 (the \"License\"); you\n * may not use this file except in compliance with the License. You may\n * obtain a copy of the License at\n * \n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n ***************************************************************\/\n\n\n#include \"condor_common.h\"\n#include \"condor_privsep_helper.h\"\n#include \"condor_debug.h\"\n\n\/\/ the methods in this file are all stubbed out for now, until we\n\/\/ have support for privilege separation on Windows\n\nbool CondorPrivSepHelper::s_instantiated = false;\n\nCondorPrivSepHelper::CondorPrivSepHelper() :\n\tm_user_initialized(false),\n\tm_user_name(NULL),\n\tm_sandbox_initialized(false),\n\tm_sandbox_path(NULL)\n{\n\tASSERT(!s_instantiated);\n\ts_instantiated = true;\n}\n\nCondorPrivSepHelper::~CondorPrivSepHelper()\n{\n\tif (m_sandbox_path != NULL) {\n\t\tfree(m_sandbox_path);\n\t}\n\tif( m_user_name ) {\n\t\tfree(m_user_name);\n\t}\n}\n\nvoid\nCondorPrivSepHelper::initialize_user(const char* name)\n{\n\tm_user_name = strdup(name);\n\n\tEXCEPT(\"CondorPrivSepHelper: Windows support not implemented\");\n}\n\nchar const *\nCondorPrivSepHelper::get_user_name()\n{\n\tEXCEPT(\"CondorPrivSepHelper: Windows support not implemented\");\n\treturn m_user_name;\n}\n\nvoid\nCondorPrivSepHelper::initialize_sandbox(const char* path)\n{\n\tEXCEPT(\"CondorPrivSepHelper: Windows support not implemented\");\n}\n\nbool\nCondorPrivSepHelper::chown_sandbox_to_user(PrivSepError &)\n{\n\tEXCEPT(\"CondorPrivSepHelper: Windows support not implemented\");\n\treturn false;\n}\n\nbool\nCondorPrivSepHelper::chown_sandbox_to_condor(PrivSepError &)\n{\n\tEXCEPT(\"CondorPrivSepHelper: Windows support not implemented\");\n\treturn false;\n}\n\nint\nCondorPrivSepHelper::create_process(const char*,\n ArgList&,\n Env&,\n const char*,\n int[3],\n const char*[3],\n int,\n size_t*,\n int,\n int,\n FamilyInfo*,\n int *affinity_mask,\n MyString * error_msg \/*= NULL*\/)\n{\n\tEXCEPT(\"CondorPrivSepHelper: Windows support not implemented\");\n\treturn 0;\n}\n<commit_msg>stub the CondorPrivSepHelper::get_exec_dir_usage method on Windows #3326<commit_after>\/***************************************************************\n *\n * Copyright (C) 1990-2007, Condor Team, Computer Sciences Department,\n * University of Wisconsin-Madison, WI.\n * \n * Licensed under the Apache License, Version 2.0 (the \"License\"); you\n * may not use this file except in compliance with the License. You may\n * obtain a copy of the License at\n * \n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n ***************************************************************\/\n\n\n#include \"condor_common.h\"\n#include \"condor_privsep_helper.h\"\n#include \"condor_debug.h\"\n\n\/\/ the methods in this file are all stubbed out for now, until we\n\/\/ have support for privilege separation on Windows\n\nbool CondorPrivSepHelper::s_instantiated = false;\n\nCondorPrivSepHelper::CondorPrivSepHelper() :\n\tm_user_initialized(false),\n\tm_user_name(NULL),\n\tm_sandbox_initialized(false),\n\tm_sandbox_path(NULL)\n{\n\tASSERT(!s_instantiated);\n\ts_instantiated = true;\n}\n\nCondorPrivSepHelper::~CondorPrivSepHelper()\n{\n\tif (m_sandbox_path != NULL) {\n\t\tfree(m_sandbox_path);\n\t}\n\tif( m_user_name ) {\n\t\tfree(m_user_name);\n\t}\n}\n\nvoid\nCondorPrivSepHelper::initialize_user(const char* name)\n{\n\tm_user_name = strdup(name);\n\n\tEXCEPT(\"CondorPrivSepHelper: Windows support not implemented\");\n}\n\nchar const *\nCondorPrivSepHelper::get_user_name()\n{\n\tEXCEPT(\"CondorPrivSepHelper: Windows support not implemented\");\n\treturn m_user_name;\n}\n\nvoid\nCondorPrivSepHelper::initialize_sandbox(const char* path)\n{\n\tEXCEPT(\"CondorPrivSepHelper: Windows support not implemented\");\n}\n\nbool\nCondorPrivSepHelper::get_exec_dir_usage(off_t *usage)\n{\n\tEXCEPT(\"CondorPrivSepHelper: Windows support not implemented\");\n}\n\n\nbool\nCondorPrivSepHelper::chown_sandbox_to_user(PrivSepError &)\n{\n\tEXCEPT(\"CondorPrivSepHelper: Windows support not implemented\");\n\treturn false;\n}\n\nbool\nCondorPrivSepHelper::chown_sandbox_to_condor(PrivSepError &)\n{\n\tEXCEPT(\"CondorPrivSepHelper: Windows support not implemented\");\n\treturn false;\n}\n\nint\nCondorPrivSepHelper::create_process(const char*,\n ArgList&,\n Env&,\n const char*,\n int[3],\n const char*[3],\n int,\n size_t*,\n int,\n int,\n FamilyInfo*,\n int *affinity_mask,\n MyString * error_msg \/*= NULL*\/)\n{\n\tEXCEPT(\"CondorPrivSepHelper: Windows support not implemented\");\n\treturn 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/===-- LanaiMemAluCombiner.cpp - Pass to combine memory & ALU operations -===\/\/\n\/\/\n\/\/ Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.\n\/\/ See https:\/\/llvm.org\/LICENSE.txt for license information.\n\/\/ SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ Simple pass to combine memory and ALU operations\n\/\/\n\/\/ The Lanai ISA supports instructions where a load\/store modifies the base\n\/\/ register used in the load\/store operation. This pass finds suitable\n\/\/ load\/store and ALU instructions and combines them into one instruction.\n\/\/\n\/\/ For example,\n\/\/ ld [ %r6 -- ], %r12\n\/\/ is a supported instruction that is not currently generated by the instruction\n\/\/ selection pass of this backend. This pass generates these instructions by\n\/\/ merging\n\/\/ add %r6, -4, %r6\n\/\/ followed by\n\/\/ ld [ %r6 ], %r12\n\/\/ in the same machine basic block into one machine instruction.\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"Lanai.h\"\n#include \"LanaiTargetMachine.h\"\n#include \"llvm\/ADT\/SmallSet.h\"\n#include \"llvm\/ADT\/Statistic.h\"\n#include \"llvm\/CodeGen\/MachineFunctionPass.h\"\n#include \"llvm\/CodeGen\/MachineInstrBuilder.h\"\n#include \"llvm\/CodeGen\/RegisterScavenging.h\"\n#include \"llvm\/CodeGen\/TargetInstrInfo.h\"\n#include \"llvm\/Support\/CommandLine.h\"\nusing namespace llvm;\n\n#define GET_INSTRMAP_INFO\n#include \"LanaiGenInstrInfo.inc\"\n\n#define DEBUG_TYPE \"lanai-mem-alu-combiner\"\n\nSTATISTIC(NumLdStAluCombined, \"Number of memory and ALU instructions combined\");\n\nstatic llvm::cl::opt<bool> DisableMemAluCombiner(\n \"disable-lanai-mem-alu-combiner\", llvm::cl::init(false),\n llvm::cl::desc(\"Do not combine ALU and memory operators\"),\n llvm::cl::Hidden);\n\nnamespace llvm {\nvoid initializeLanaiMemAluCombinerPass(PassRegistry &);\n} \/\/ namespace llvm\n\nnamespace {\ntypedef MachineBasicBlock::iterator MbbIterator;\ntypedef MachineFunction::iterator MfIterator;\n\nclass LanaiMemAluCombiner : public MachineFunctionPass {\npublic:\n static char ID;\n explicit LanaiMemAluCombiner() : MachineFunctionPass(ID) {\n initializeLanaiMemAluCombinerPass(*PassRegistry::getPassRegistry());\n }\n\n StringRef getPassName() const override {\n return \"Lanai load \/ store optimization pass\";\n }\n\n bool runOnMachineFunction(MachineFunction &F) override;\n\n MachineFunctionProperties getRequiredProperties() const override {\n return MachineFunctionProperties().set(\n MachineFunctionProperties::Property::NoVRegs);\n }\n\nprivate:\n MbbIterator findClosestSuitableAluInstr(MachineBasicBlock *BB,\n const MbbIterator &MemInstr,\n bool Decrement);\n void insertMergedInstruction(MachineBasicBlock *BB,\n const MbbIterator &MemInstr,\n const MbbIterator &AluInstr, bool Before);\n bool combineMemAluInBasicBlock(MachineBasicBlock *BB);\n\n \/\/ Target machine description which we query for register names, data\n \/\/ layout, etc.\n const TargetInstrInfo *TII;\n};\n} \/\/ namespace\n\nchar LanaiMemAluCombiner::ID = 0;\n\nINITIALIZE_PASS(LanaiMemAluCombiner, DEBUG_TYPE,\n \"Lanai memory ALU combiner pass\", false, false)\n\nnamespace {\nbool isSpls(uint16_t Opcode) { return Lanai::splsIdempotent(Opcode) == Opcode; }\n\n\/\/ Determine the opcode for the merged instruction created by considering the\n\/\/ old memory operation's opcode and whether the merged opcode will have an\n\/\/ immediate offset.\nunsigned mergedOpcode(unsigned OldOpcode, bool ImmediateOffset) {\n switch (OldOpcode) {\n case Lanai::LDW_RI:\n case Lanai::LDW_RR:\n if (ImmediateOffset)\n return Lanai::LDW_RI;\n return Lanai::LDW_RR;\n case Lanai::LDHs_RI:\n case Lanai::LDHs_RR:\n if (ImmediateOffset)\n return Lanai::LDHs_RI;\n return Lanai::LDHs_RR;\n case Lanai::LDHz_RI:\n case Lanai::LDHz_RR:\n if (ImmediateOffset)\n return Lanai::LDHz_RI;\n return Lanai::LDHz_RR;\n case Lanai::LDBs_RI:\n case Lanai::LDBs_RR:\n if (ImmediateOffset)\n return Lanai::LDBs_RI;\n return Lanai::LDBs_RR;\n case Lanai::LDBz_RI:\n case Lanai::LDBz_RR:\n if (ImmediateOffset)\n return Lanai::LDBz_RI;\n return Lanai::LDBz_RR;\n case Lanai::SW_RI:\n case Lanai::SW_RR:\n if (ImmediateOffset)\n return Lanai::SW_RI;\n return Lanai::SW_RR;\n case Lanai::STB_RI:\n case Lanai::STB_RR:\n if (ImmediateOffset)\n return Lanai::STB_RI;\n return Lanai::STB_RR;\n case Lanai::STH_RI:\n case Lanai::STH_RR:\n if (ImmediateOffset)\n return Lanai::STH_RI;\n return Lanai::STH_RR;\n default:\n return 0;\n }\n}\n\n\/\/ Check if the machine instruction has non-volatile memory operands of the type\n\/\/ supported for combining with ALU instructions.\nbool isNonVolatileMemoryOp(const MachineInstr &MI) {\n if (!MI.hasOneMemOperand())\n return false;\n\n \/\/ Determine if the machine instruction is a supported memory operation by\n \/\/ testing if the computed merge opcode is a valid memory operation opcode.\n if (mergedOpcode(MI.getOpcode(), false) == 0)\n return false;\n\n const MachineMemOperand *MemOperand = *MI.memoperands_begin();\n\n \/\/ Don't move volatile memory accesses\n \/\/ TODO: unclear if we need to be as conservative about atomics\n if (MemOperand->isVolatile() || MemOperand->isAtomic())\n return false;\n\n return true;\n}\n\n\/\/ Test to see if two machine operands are of the same type. This test is less\n\/\/ strict than the MachineOperand::isIdenticalTo function.\nbool isSameOperand(const MachineOperand &Op1, const MachineOperand &Op2) {\n if (Op1.getType() != Op2.getType())\n return false;\n\n switch (Op1.getType()) {\n case MachineOperand::MO_Register:\n return Op1.getReg() == Op2.getReg();\n case MachineOperand::MO_Immediate:\n return Op1.getImm() == Op2.getImm();\n default:\n return false;\n }\n}\n\nbool isZeroOperand(const MachineOperand &Op) {\n return ((Op.isReg() && Op.getReg() == Lanai::R0) ||\n (Op.isImm() && Op.getImm() == 0));\n}\n\n\/\/ Determines whether a register is used by an instruction.\nbool InstrUsesReg(const MbbIterator &Instr, const MachineOperand *Reg) {\n for (MachineInstr::const_mop_iterator Mop = Instr->operands_begin();\n Mop != Instr->operands_end(); ++Mop) {\n if (isSameOperand(*Mop, *Reg))\n return true;\n }\n return false;\n}\n\n\/\/ Converts between machine opcode and AluCode.\n\/\/ Flag using\/modifying ALU operations should not be considered for merging and\n\/\/ are omitted from this list.\nLPAC::AluCode mergedAluCode(unsigned AluOpcode) {\n switch (AluOpcode) {\n case Lanai::ADD_I_LO:\n case Lanai::ADD_R:\n return LPAC::ADD;\n case Lanai::SUB_I_LO:\n case Lanai::SUB_R:\n return LPAC::SUB;\n case Lanai::AND_I_LO:\n case Lanai::AND_R:\n return LPAC::AND;\n case Lanai::OR_I_LO:\n case Lanai::OR_R:\n return LPAC::OR;\n case Lanai::XOR_I_LO:\n case Lanai::XOR_R:\n return LPAC::XOR;\n case Lanai::SHL_R:\n return LPAC::SHL;\n case Lanai::SRL_R:\n return LPAC::SRL;\n case Lanai::SRA_R:\n return LPAC::SRA;\n case Lanai::SA_I:\n case Lanai::SL_I:\n default:\n return LPAC::UNKNOWN;\n }\n}\n\n\/\/ Insert a new combined memory and ALU operation instruction.\n\/\/\n\/\/ This function builds a new machine instruction using the MachineInstrBuilder\n\/\/ class and inserts it before the memory instruction.\nvoid LanaiMemAluCombiner::insertMergedInstruction(MachineBasicBlock *BB,\n const MbbIterator &MemInstr,\n const MbbIterator &AluInstr,\n bool Before) {\n \/\/ Insert new combined load\/store + alu operation\n MachineOperand Dest = MemInstr->getOperand(0);\n MachineOperand Base = MemInstr->getOperand(1);\n MachineOperand MemOffset = MemInstr->getOperand(2);\n MachineOperand AluOffset = AluInstr->getOperand(2);\n\n \/\/ Abort if ALU offset is not a register or immediate\n assert((AluOffset.isReg() || AluOffset.isImm()) &&\n \"Unsupported operand type in merge\");\n\n \/\/ Determined merged instructions opcode and ALU code\n LPAC::AluCode AluOpcode = mergedAluCode(AluInstr->getOpcode());\n unsigned NewOpc = mergedOpcode(MemInstr->getOpcode(), AluOffset.isImm());\n\n assert(AluOpcode != LPAC::UNKNOWN && \"Unknown ALU code in merging\");\n assert(NewOpc != 0 && \"Unknown merged node opcode\");\n\n \/\/ Build and insert new machine instruction\n MachineInstrBuilder InstrBuilder =\n BuildMI(*BB, MemInstr, MemInstr->getDebugLoc(), TII->get(NewOpc));\n InstrBuilder.addReg(Dest.getReg(), getDefRegState(true));\n InstrBuilder.addReg(Base.getReg(), getKillRegState(true));\n\n \/\/ Add offset to machine instruction\n if (AluOffset.isReg())\n InstrBuilder.addReg(AluOffset.getReg());\n else if (AluOffset.isImm())\n InstrBuilder.addImm(AluOffset.getImm());\n else\n llvm_unreachable(\"Unsupported ld\/st ALU merge.\");\n\n \/\/ Create a pre-op if the ALU operation preceded the memory operation or the\n \/\/ MemOffset is non-zero (i.e. the memory value should be adjusted before\n \/\/ accessing it), else create a post-op.\n if (Before || !isZeroOperand(MemOffset))\n InstrBuilder.addImm(LPAC::makePreOp(AluOpcode));\n else\n InstrBuilder.addImm(LPAC::makePostOp(AluOpcode));\n\n \/\/ Transfer memory operands.\n InstrBuilder.setMemRefs(MemInstr->memoperands());\n}\n\n\/\/ Function determines if ALU operation (in alu_iter) can be combined with\n\/\/ a load\/store with base and offset.\nbool isSuitableAluInstr(bool IsSpls, const MbbIterator &AluIter,\n const MachineOperand &Base,\n const MachineOperand &Offset) {\n \/\/ ALU operations have 3 operands\n if (AluIter->getNumOperands() != 3)\n return false;\n\n MachineOperand &Dest = AluIter->getOperand(0);\n MachineOperand &Op1 = AluIter->getOperand(1);\n MachineOperand &Op2 = AluIter->getOperand(2);\n\n \/\/ Only match instructions using the base register as destination and with the\n \/\/ base and first operand equal\n if (!isSameOperand(Dest, Base) || !isSameOperand(Dest, Op1))\n return false;\n\n if (Op2.isImm()) {\n \/\/ It is not a match if the 2nd operand in the ALU operation is an\n \/\/ immediate but the ALU operation is not an addition.\n if (AluIter->getOpcode() != Lanai::ADD_I_LO)\n return false;\n\n if (Offset.isReg() && Offset.getReg() == Lanai::R0)\n return true;\n\n if (Offset.isImm() &&\n ((Offset.getImm() == 0 &&\n \/\/ Check that the Op2 would fit in the immediate field of the\n \/\/ memory operation.\n ((IsSpls && isInt<10>(Op2.getImm())) ||\n (!IsSpls && isInt<16>(Op2.getImm())))) ||\n Offset.getImm() == Op2.getImm()))\n return true;\n } else if (Op2.isReg()) {\n \/\/ The Offset and 2nd operand are both registers and equal\n if (Offset.isReg() && Op2.getReg() == Offset.getReg())\n return true;\n } else\n \/\/ Only consider operations with register or immediate values\n return false;\n\n return false;\n}\n\nMbbIterator LanaiMemAluCombiner::findClosestSuitableAluInstr(\n MachineBasicBlock *BB, const MbbIterator &MemInstr, const bool Decrement) {\n MachineOperand *Base = &MemInstr->getOperand(1);\n MachineOperand *Offset = &MemInstr->getOperand(2);\n bool IsSpls = isSpls(MemInstr->getOpcode());\n\n MbbIterator First = MemInstr;\n MbbIterator Last = Decrement ? BB->begin() : BB->end();\n\n while (First != Last) {\n Decrement ? --First : ++First;\n\n if (First == Last)\n break;\n\n \/\/ Skip over debug instructions\n if (First->isDebugInstr())\n continue;\n\n if (isSuitableAluInstr(IsSpls, First, *Base, *Offset)) {\n return First;\n }\n\n \/\/ Usage of the base or offset register is not a form suitable for merging.\n if (First != Last) {\n if (InstrUsesReg(First, Base))\n break;\n if (Offset->isReg() && InstrUsesReg(First, Offset))\n break;\n }\n }\n\n return MemInstr;\n}\n\nbool LanaiMemAluCombiner::combineMemAluInBasicBlock(MachineBasicBlock *BB) {\n bool Modified = false;\n\n MbbIterator MBBIter = BB->begin(), End = BB->end();\n while (MBBIter != End) {\n bool IsMemOp = isNonVolatileMemoryOp(*MBBIter);\n\n if (IsMemOp) {\n MachineOperand AluOperand = MBBIter->getOperand(3);\n unsigned int DestReg = MBBIter->getOperand(0).getReg(),\n BaseReg = MBBIter->getOperand(1).getReg();\n assert(AluOperand.isImm() && \"Unexpected memory operator type\");\n LPAC::AluCode AluOpcode = static_cast<LPAC::AluCode>(AluOperand.getImm());\n\n \/\/ Skip memory operations that already modify the base register or if\n \/\/ the destination and base register are the same\n if (!LPAC::modifiesOp(AluOpcode) && DestReg != BaseReg) {\n for (int Inc = 0; Inc <= 1; ++Inc) {\n MbbIterator AluIter =\n findClosestSuitableAluInstr(BB, MBBIter, Inc == 0);\n if (AluIter != MBBIter) {\n insertMergedInstruction(BB, MBBIter, AluIter, Inc == 0);\n\n ++NumLdStAluCombined;\n Modified = true;\n\n \/\/ Erase the matching ALU instruction\n BB->erase(AluIter);\n \/\/ Erase old load\/store instruction\n BB->erase(MBBIter++);\n break;\n }\n }\n }\n }\n if (MBBIter == End)\n break;\n ++MBBIter;\n }\n\n return Modified;\n}\n\n\/\/ Driver function that iterates over the machine basic building blocks of a\n\/\/ machine function\nbool LanaiMemAluCombiner::runOnMachineFunction(MachineFunction &MF) {\n if (DisableMemAluCombiner)\n return false;\n\n TII = MF.getSubtarget<LanaiSubtarget>().getInstrInfo();\n bool Modified = false;\n for (MfIterator MFI = MF.begin(); MFI != MF.end(); ++MFI) {\n Modified |= combineMemAluInBasicBlock(&*MFI);\n }\n return Modified;\n}\n} \/\/ namespace\n\nFunctionPass *llvm::createLanaiMemAluCombinerPass() {\n return new LanaiMemAluCombiner();\n}\n<commit_msg>Include what you use in LanaiMemAluCombiner.cpp<commit_after>\/\/===-- LanaiMemAluCombiner.cpp - Pass to combine memory & ALU operations -===\/\/\n\/\/\n\/\/ Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.\n\/\/ See https:\/\/llvm.org\/LICENSE.txt for license information.\n\/\/ SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ Simple pass to combine memory and ALU operations\n\/\/\n\/\/ The Lanai ISA supports instructions where a load\/store modifies the base\n\/\/ register used in the load\/store operation. This pass finds suitable\n\/\/ load\/store and ALU instructions and combines them into one instruction.\n\/\/\n\/\/ For example,\n\/\/ ld [ %r6 -- ], %r12\n\/\/ is a supported instruction that is not currently generated by the instruction\n\/\/ selection pass of this backend. This pass generates these instructions by\n\/\/ merging\n\/\/ add %r6, -4, %r6\n\/\/ followed by\n\/\/ ld [ %r6 ], %r12\n\/\/ in the same machine basic block into one machine instruction.\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"LanaiAluCode.h\"\n#include \"LanaiTargetMachine.h\"\n#include \"llvm\/ADT\/SmallSet.h\"\n#include \"llvm\/ADT\/Statistic.h\"\n#include \"llvm\/CodeGen\/MachineFunctionPass.h\"\n#include \"llvm\/CodeGen\/MachineInstrBuilder.h\"\n#include \"llvm\/CodeGen\/RegisterScavenging.h\"\n#include \"llvm\/CodeGen\/TargetInstrInfo.h\"\n#include \"llvm\/Support\/CommandLine.h\"\nusing namespace llvm;\n\n#define GET_INSTRMAP_INFO\n#include \"LanaiGenInstrInfo.inc\"\n\n#define DEBUG_TYPE \"lanai-mem-alu-combiner\"\n\nSTATISTIC(NumLdStAluCombined, \"Number of memory and ALU instructions combined\");\n\nstatic llvm::cl::opt<bool> DisableMemAluCombiner(\n \"disable-lanai-mem-alu-combiner\", llvm::cl::init(false),\n llvm::cl::desc(\"Do not combine ALU and memory operators\"),\n llvm::cl::Hidden);\n\nnamespace llvm {\nvoid initializeLanaiMemAluCombinerPass(PassRegistry &);\n} \/\/ namespace llvm\n\nnamespace {\ntypedef MachineBasicBlock::iterator MbbIterator;\ntypedef MachineFunction::iterator MfIterator;\n\nclass LanaiMemAluCombiner : public MachineFunctionPass {\npublic:\n static char ID;\n explicit LanaiMemAluCombiner() : MachineFunctionPass(ID) {\n initializeLanaiMemAluCombinerPass(*PassRegistry::getPassRegistry());\n }\n\n StringRef getPassName() const override {\n return \"Lanai load \/ store optimization pass\";\n }\n\n bool runOnMachineFunction(MachineFunction &F) override;\n\n MachineFunctionProperties getRequiredProperties() const override {\n return MachineFunctionProperties().set(\n MachineFunctionProperties::Property::NoVRegs);\n }\n\nprivate:\n MbbIterator findClosestSuitableAluInstr(MachineBasicBlock *BB,\n const MbbIterator &MemInstr,\n bool Decrement);\n void insertMergedInstruction(MachineBasicBlock *BB,\n const MbbIterator &MemInstr,\n const MbbIterator &AluInstr, bool Before);\n bool combineMemAluInBasicBlock(MachineBasicBlock *BB);\n\n \/\/ Target machine description which we query for register names, data\n \/\/ layout, etc.\n const TargetInstrInfo *TII;\n};\n} \/\/ namespace\n\nchar LanaiMemAluCombiner::ID = 0;\n\nINITIALIZE_PASS(LanaiMemAluCombiner, DEBUG_TYPE,\n \"Lanai memory ALU combiner pass\", false, false)\n\nnamespace {\nbool isSpls(uint16_t Opcode) { return Lanai::splsIdempotent(Opcode) == Opcode; }\n\n\/\/ Determine the opcode for the merged instruction created by considering the\n\/\/ old memory operation's opcode and whether the merged opcode will have an\n\/\/ immediate offset.\nunsigned mergedOpcode(unsigned OldOpcode, bool ImmediateOffset) {\n switch (OldOpcode) {\n case Lanai::LDW_RI:\n case Lanai::LDW_RR:\n if (ImmediateOffset)\n return Lanai::LDW_RI;\n return Lanai::LDW_RR;\n case Lanai::LDHs_RI:\n case Lanai::LDHs_RR:\n if (ImmediateOffset)\n return Lanai::LDHs_RI;\n return Lanai::LDHs_RR;\n case Lanai::LDHz_RI:\n case Lanai::LDHz_RR:\n if (ImmediateOffset)\n return Lanai::LDHz_RI;\n return Lanai::LDHz_RR;\n case Lanai::LDBs_RI:\n case Lanai::LDBs_RR:\n if (ImmediateOffset)\n return Lanai::LDBs_RI;\n return Lanai::LDBs_RR;\n case Lanai::LDBz_RI:\n case Lanai::LDBz_RR:\n if (ImmediateOffset)\n return Lanai::LDBz_RI;\n return Lanai::LDBz_RR;\n case Lanai::SW_RI:\n case Lanai::SW_RR:\n if (ImmediateOffset)\n return Lanai::SW_RI;\n return Lanai::SW_RR;\n case Lanai::STB_RI:\n case Lanai::STB_RR:\n if (ImmediateOffset)\n return Lanai::STB_RI;\n return Lanai::STB_RR;\n case Lanai::STH_RI:\n case Lanai::STH_RR:\n if (ImmediateOffset)\n return Lanai::STH_RI;\n return Lanai::STH_RR;\n default:\n return 0;\n }\n}\n\n\/\/ Check if the machine instruction has non-volatile memory operands of the type\n\/\/ supported for combining with ALU instructions.\nbool isNonVolatileMemoryOp(const MachineInstr &MI) {\n if (!MI.hasOneMemOperand())\n return false;\n\n \/\/ Determine if the machine instruction is a supported memory operation by\n \/\/ testing if the computed merge opcode is a valid memory operation opcode.\n if (mergedOpcode(MI.getOpcode(), false) == 0)\n return false;\n\n const MachineMemOperand *MemOperand = *MI.memoperands_begin();\n\n \/\/ Don't move volatile memory accesses\n \/\/ TODO: unclear if we need to be as conservative about atomics\n if (MemOperand->isVolatile() || MemOperand->isAtomic())\n return false;\n\n return true;\n}\n\n\/\/ Test to see if two machine operands are of the same type. This test is less\n\/\/ strict than the MachineOperand::isIdenticalTo function.\nbool isSameOperand(const MachineOperand &Op1, const MachineOperand &Op2) {\n if (Op1.getType() != Op2.getType())\n return false;\n\n switch (Op1.getType()) {\n case MachineOperand::MO_Register:\n return Op1.getReg() == Op2.getReg();\n case MachineOperand::MO_Immediate:\n return Op1.getImm() == Op2.getImm();\n default:\n return false;\n }\n}\n\nbool isZeroOperand(const MachineOperand &Op) {\n return ((Op.isReg() && Op.getReg() == Lanai::R0) ||\n (Op.isImm() && Op.getImm() == 0));\n}\n\n\/\/ Determines whether a register is used by an instruction.\nbool InstrUsesReg(const MbbIterator &Instr, const MachineOperand *Reg) {\n for (MachineInstr::const_mop_iterator Mop = Instr->operands_begin();\n Mop != Instr->operands_end(); ++Mop) {\n if (isSameOperand(*Mop, *Reg))\n return true;\n }\n return false;\n}\n\n\/\/ Converts between machine opcode and AluCode.\n\/\/ Flag using\/modifying ALU operations should not be considered for merging and\n\/\/ are omitted from this list.\nLPAC::AluCode mergedAluCode(unsigned AluOpcode) {\n switch (AluOpcode) {\n case Lanai::ADD_I_LO:\n case Lanai::ADD_R:\n return LPAC::ADD;\n case Lanai::SUB_I_LO:\n case Lanai::SUB_R:\n return LPAC::SUB;\n case Lanai::AND_I_LO:\n case Lanai::AND_R:\n return LPAC::AND;\n case Lanai::OR_I_LO:\n case Lanai::OR_R:\n return LPAC::OR;\n case Lanai::XOR_I_LO:\n case Lanai::XOR_R:\n return LPAC::XOR;\n case Lanai::SHL_R:\n return LPAC::SHL;\n case Lanai::SRL_R:\n return LPAC::SRL;\n case Lanai::SRA_R:\n return LPAC::SRA;\n case Lanai::SA_I:\n case Lanai::SL_I:\n default:\n return LPAC::UNKNOWN;\n }\n}\n\n\/\/ Insert a new combined memory and ALU operation instruction.\n\/\/\n\/\/ This function builds a new machine instruction using the MachineInstrBuilder\n\/\/ class and inserts it before the memory instruction.\nvoid LanaiMemAluCombiner::insertMergedInstruction(MachineBasicBlock *BB,\n const MbbIterator &MemInstr,\n const MbbIterator &AluInstr,\n bool Before) {\n \/\/ Insert new combined load\/store + alu operation\n MachineOperand Dest = MemInstr->getOperand(0);\n MachineOperand Base = MemInstr->getOperand(1);\n MachineOperand MemOffset = MemInstr->getOperand(2);\n MachineOperand AluOffset = AluInstr->getOperand(2);\n\n \/\/ Abort if ALU offset is not a register or immediate\n assert((AluOffset.isReg() || AluOffset.isImm()) &&\n \"Unsupported operand type in merge\");\n\n \/\/ Determined merged instructions opcode and ALU code\n LPAC::AluCode AluOpcode = mergedAluCode(AluInstr->getOpcode());\n unsigned NewOpc = mergedOpcode(MemInstr->getOpcode(), AluOffset.isImm());\n\n assert(AluOpcode != LPAC::UNKNOWN && \"Unknown ALU code in merging\");\n assert(NewOpc != 0 && \"Unknown merged node opcode\");\n\n \/\/ Build and insert new machine instruction\n MachineInstrBuilder InstrBuilder =\n BuildMI(*BB, MemInstr, MemInstr->getDebugLoc(), TII->get(NewOpc));\n InstrBuilder.addReg(Dest.getReg(), getDefRegState(true));\n InstrBuilder.addReg(Base.getReg(), getKillRegState(true));\n\n \/\/ Add offset to machine instruction\n if (AluOffset.isReg())\n InstrBuilder.addReg(AluOffset.getReg());\n else if (AluOffset.isImm())\n InstrBuilder.addImm(AluOffset.getImm());\n else\n llvm_unreachable(\"Unsupported ld\/st ALU merge.\");\n\n \/\/ Create a pre-op if the ALU operation preceded the memory operation or the\n \/\/ MemOffset is non-zero (i.e. the memory value should be adjusted before\n \/\/ accessing it), else create a post-op.\n if (Before || !isZeroOperand(MemOffset))\n InstrBuilder.addImm(LPAC::makePreOp(AluOpcode));\n else\n InstrBuilder.addImm(LPAC::makePostOp(AluOpcode));\n\n \/\/ Transfer memory operands.\n InstrBuilder.setMemRefs(MemInstr->memoperands());\n}\n\n\/\/ Function determines if ALU operation (in alu_iter) can be combined with\n\/\/ a load\/store with base and offset.\nbool isSuitableAluInstr(bool IsSpls, const MbbIterator &AluIter,\n const MachineOperand &Base,\n const MachineOperand &Offset) {\n \/\/ ALU operations have 3 operands\n if (AluIter->getNumOperands() != 3)\n return false;\n\n MachineOperand &Dest = AluIter->getOperand(0);\n MachineOperand &Op1 = AluIter->getOperand(1);\n MachineOperand &Op2 = AluIter->getOperand(2);\n\n \/\/ Only match instructions using the base register as destination and with the\n \/\/ base and first operand equal\n if (!isSameOperand(Dest, Base) || !isSameOperand(Dest, Op1))\n return false;\n\n if (Op2.isImm()) {\n \/\/ It is not a match if the 2nd operand in the ALU operation is an\n \/\/ immediate but the ALU operation is not an addition.\n if (AluIter->getOpcode() != Lanai::ADD_I_LO)\n return false;\n\n if (Offset.isReg() && Offset.getReg() == Lanai::R0)\n return true;\n\n if (Offset.isImm() &&\n ((Offset.getImm() == 0 &&\n \/\/ Check that the Op2 would fit in the immediate field of the\n \/\/ memory operation.\n ((IsSpls && isInt<10>(Op2.getImm())) ||\n (!IsSpls && isInt<16>(Op2.getImm())))) ||\n Offset.getImm() == Op2.getImm()))\n return true;\n } else if (Op2.isReg()) {\n \/\/ The Offset and 2nd operand are both registers and equal\n if (Offset.isReg() && Op2.getReg() == Offset.getReg())\n return true;\n } else\n \/\/ Only consider operations with register or immediate values\n return false;\n\n return false;\n}\n\nMbbIterator LanaiMemAluCombiner::findClosestSuitableAluInstr(\n MachineBasicBlock *BB, const MbbIterator &MemInstr, const bool Decrement) {\n MachineOperand *Base = &MemInstr->getOperand(1);\n MachineOperand *Offset = &MemInstr->getOperand(2);\n bool IsSpls = isSpls(MemInstr->getOpcode());\n\n MbbIterator First = MemInstr;\n MbbIterator Last = Decrement ? BB->begin() : BB->end();\n\n while (First != Last) {\n Decrement ? --First : ++First;\n\n if (First == Last)\n break;\n\n \/\/ Skip over debug instructions\n if (First->isDebugInstr())\n continue;\n\n if (isSuitableAluInstr(IsSpls, First, *Base, *Offset)) {\n return First;\n }\n\n \/\/ Usage of the base or offset register is not a form suitable for merging.\n if (First != Last) {\n if (InstrUsesReg(First, Base))\n break;\n if (Offset->isReg() && InstrUsesReg(First, Offset))\n break;\n }\n }\n\n return MemInstr;\n}\n\nbool LanaiMemAluCombiner::combineMemAluInBasicBlock(MachineBasicBlock *BB) {\n bool Modified = false;\n\n MbbIterator MBBIter = BB->begin(), End = BB->end();\n while (MBBIter != End) {\n bool IsMemOp = isNonVolatileMemoryOp(*MBBIter);\n\n if (IsMemOp) {\n MachineOperand AluOperand = MBBIter->getOperand(3);\n unsigned int DestReg = MBBIter->getOperand(0).getReg(),\n BaseReg = MBBIter->getOperand(1).getReg();\n assert(AluOperand.isImm() && \"Unexpected memory operator type\");\n LPAC::AluCode AluOpcode = static_cast<LPAC::AluCode>(AluOperand.getImm());\n\n \/\/ Skip memory operations that already modify the base register or if\n \/\/ the destination and base register are the same\n if (!LPAC::modifiesOp(AluOpcode) && DestReg != BaseReg) {\n for (int Inc = 0; Inc <= 1; ++Inc) {\n MbbIterator AluIter =\n findClosestSuitableAluInstr(BB, MBBIter, Inc == 0);\n if (AluIter != MBBIter) {\n insertMergedInstruction(BB, MBBIter, AluIter, Inc == 0);\n\n ++NumLdStAluCombined;\n Modified = true;\n\n \/\/ Erase the matching ALU instruction\n BB->erase(AluIter);\n \/\/ Erase old load\/store instruction\n BB->erase(MBBIter++);\n break;\n }\n }\n }\n }\n if (MBBIter == End)\n break;\n ++MBBIter;\n }\n\n return Modified;\n}\n\n\/\/ Driver function that iterates over the machine basic building blocks of a\n\/\/ machine function\nbool LanaiMemAluCombiner::runOnMachineFunction(MachineFunction &MF) {\n if (DisableMemAluCombiner)\n return false;\n\n TII = MF.getSubtarget<LanaiSubtarget>().getInstrInfo();\n bool Modified = false;\n for (MfIterator MFI = MF.begin(); MFI != MF.end(); ++MFI) {\n Modified |= combineMemAluInBasicBlock(&*MFI);\n }\n return Modified;\n}\n} \/\/ namespace\n\nFunctionPass *llvm::createLanaiMemAluCombinerPass() {\n return new LanaiMemAluCombiner();\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/===-- PPCBranchSelector.cpp - Emit long conditional branches-----*- C++ -*-=\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file was developed by Nate Baegeman and is distributed under the\n\/\/ University of Illinois Open Source License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This file contains a pass that scans a machine function to determine which\n\/\/ conditional branches need more than 16 bits of displacement to reach their\n\/\/ target basic block. It does this in two passes; a calculation of basic block\n\/\/ positions pass, and a branch psuedo op to machine branch opcode pass. This\n\/\/ pass should be run last, just before the assembly printer.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"PPC.h\"\n#include \"PPCInstrBuilder.h\"\n#include \"PPCInstrInfo.h\"\n#include \"llvm\/CodeGen\/MachineFunctionPass.h\"\n#include \"llvm\/Target\/TargetMachine.h\"\n#include \"llvm\/Target\/TargetAsmInfo.h\"\n#include \"llvm\/ADT\/Statistic.h\"\n#include \"llvm\/Support\/Compiler.h\"\n#include <map>\nusing namespace llvm;\n\nstatic Statistic<> NumExpanded(\"ppc-branch-select\",\n \"Num branches expanded to long format\");\n\nnamespace {\n struct VISIBILITY_HIDDEN PPCBSel : public MachineFunctionPass {\n \/\/\/ OffsetMap - Mapping between BB and byte offset from start of function.\n \/\/\/ TODO: replace this with a vector, using the MBB idx as the key.\n std::map<MachineBasicBlock*, unsigned> OffsetMap;\n\n virtual bool runOnMachineFunction(MachineFunction &Fn);\n\n virtual const char *getPassName() const {\n return \"PowerPC Branch Selection\";\n }\n };\n}\n\n\/\/\/ createPPCBranchSelectionPass - returns an instance of the Branch Selection\n\/\/\/ Pass\n\/\/\/\nFunctionPass *llvm::createPPCBranchSelectionPass() {\n return new PPCBSel();\n}\n\n\/\/\/ getNumBytesForInstruction - Return the number of bytes of code the specified\n\/\/\/ instruction may be. This returns the maximum number of bytes.\n\/\/\/\nstatic unsigned getNumBytesForInstruction(MachineInstr *MI) {\n switch (MI->getOpcode()) {\n case PPC::COND_BRANCH:\n \/\/ while this will be 4 most of the time, if we emit 8 it is just a\n \/\/ minor pessimization that saves us from having to worry about\n \/\/ keeping the offsets up to date later when we emit long branch glue.\n return 8;\n case PPC::IMPLICIT_DEF_GPRC: \/\/ no asm emitted\n case PPC::IMPLICIT_DEF_G8RC: \/\/ no asm emitted\n case PPC::IMPLICIT_DEF_F4: \/\/ no asm emitted\n case PPC::IMPLICIT_DEF_F8: \/\/ no asm emitted\n return 0;\n case PPC::INLINEASM: { \/\/ Inline Asm: Variable size.\n MachineFunction *MF = MI->getParent()->getParent();\n const char *AsmStr = MI->getOperand(0).getSymbolName();\n return MF->getTarget().getTargetAsmInfo()->getInlineAsmLength(AsmStr);\n }\n default:\n return 4; \/\/ PowerPC instructions are all 4 bytes\n }\n}\n\n\nbool PPCBSel::runOnMachineFunction(MachineFunction &Fn) {\n \/\/ Running total of instructions encountered since beginning of function\n unsigned ByteCount = 0;\n \n \/\/ For each MBB, add its offset to the offset map, and count up its\n \/\/ instructions\n for (MachineFunction::iterator MFI = Fn.begin(), E = Fn.end(); MFI != E;\n ++MFI) {\n MachineBasicBlock *MBB = MFI;\n OffsetMap[MBB] = ByteCount;\n \n for (MachineBasicBlock::iterator MBBI = MBB->begin(), EE = MBB->end();\n MBBI != EE; ++MBBI)\n ByteCount += getNumBytesForInstruction(MBBI);\n }\n \n \/\/ We're about to run over the MBB's again, so reset the ByteCount\n ByteCount = 0;\n \n \/\/ For each MBB, find the conditional branch pseudo instructions, and\n \/\/ calculate the difference between the target MBB and the current ICount\n \/\/ to decide whether or not to emit a short or long branch.\n \/\/\n \/\/ short branch:\n \/\/ bCC .L_TARGET_MBB\n \/\/\n \/\/ long branch:\n \/\/ bInverseCC $PC+8\n \/\/ b .L_TARGET_MBB\n for (MachineFunction::iterator MFI = Fn.begin(), E = Fn.end(); MFI != E;\n ++MFI) {\n MachineBasicBlock *MBB = MFI;\n \n for (MachineBasicBlock::iterator MBBI = MBB->begin(), EE = MBB->end();\n MBBI != EE; ++MBBI) {\n \/\/ We may end up deleting the MachineInstr that MBBI points to, so\n \/\/ remember its opcode now so we can refer to it after calling erase()\n unsigned ByteSize = getNumBytesForInstruction(MBBI);\n if (MBBI->getOpcode() == PPC::COND_BRANCH) {\n MachineBasicBlock::iterator MBBJ = MBBI;\n ++MBBJ;\n \n \/\/ condbranch operands:\n \/\/ 0. CR0 register\n \/\/ 1. bc opcode\n \/\/ 2. target MBB\n \/\/ 3. fallthrough MBB\n MachineBasicBlock *trueMBB =\n MBBI->getOperand(2).getMachineBasicBlock();\n \n int Displacement = OffsetMap[trueMBB] - ByteCount;\n unsigned Opcode = MBBI->getOperand(1).getImmedValue();\n unsigned CRReg = MBBI->getOperand(0).getReg();\n unsigned Inverted = PPCInstrInfo::invertPPCBranchOpcode(Opcode);\n \n if (Displacement >= -32768 && Displacement <= 32767) {\n BuildMI(*MBB, MBBJ, Opcode, 2).addReg(CRReg).addMBB(trueMBB);\n } else {\n \/\/ Long branch, skip next branch instruction (i.e. $PC+8).\n ++NumExpanded;\n BuildMI(*MBB, MBBJ, Inverted, 2).addReg(CRReg).addImm(2);\n BuildMI(*MBB, MBBJ, PPC::B, 1).addMBB(trueMBB);\n }\n \n \/\/ Erase the psuedo COND_BRANCH instruction, and then back up the\n \/\/ iterator so that when the for loop increments it, we end up in\n \/\/ the correct place rather than iterating off the end.\n MBB->erase(MBBI);\n MBBI = --MBBJ;\n }\n ByteCount += ByteSize;\n }\n }\n \n OffsetMap.clear();\n return true;\n}\n\n<commit_msg>implicit_def_vrrc doesn't generate code.<commit_after>\/\/===-- PPCBranchSelector.cpp - Emit long conditional branches-----*- C++ -*-=\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file was developed by Nate Baegeman and is distributed under the\n\/\/ University of Illinois Open Source License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This file contains a pass that scans a machine function to determine which\n\/\/ conditional branches need more than 16 bits of displacement to reach their\n\/\/ target basic block. It does this in two passes; a calculation of basic block\n\/\/ positions pass, and a branch psuedo op to machine branch opcode pass. This\n\/\/ pass should be run last, just before the assembly printer.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"PPC.h\"\n#include \"PPCInstrBuilder.h\"\n#include \"PPCInstrInfo.h\"\n#include \"llvm\/CodeGen\/MachineFunctionPass.h\"\n#include \"llvm\/Target\/TargetMachine.h\"\n#include \"llvm\/Target\/TargetAsmInfo.h\"\n#include \"llvm\/ADT\/Statistic.h\"\n#include \"llvm\/Support\/Compiler.h\"\n#include <map>\nusing namespace llvm;\n\nstatic Statistic<> NumExpanded(\"ppc-branch-select\",\n \"Num branches expanded to long format\");\n\nnamespace {\n struct VISIBILITY_HIDDEN PPCBSel : public MachineFunctionPass {\n \/\/\/ OffsetMap - Mapping between BB and byte offset from start of function.\n \/\/\/ TODO: replace this with a vector, using the MBB idx as the key.\n std::map<MachineBasicBlock*, unsigned> OffsetMap;\n\n virtual bool runOnMachineFunction(MachineFunction &Fn);\n\n virtual const char *getPassName() const {\n return \"PowerPC Branch Selection\";\n }\n };\n}\n\n\/\/\/ createPPCBranchSelectionPass - returns an instance of the Branch Selection\n\/\/\/ Pass\n\/\/\/\nFunctionPass *llvm::createPPCBranchSelectionPass() {\n return new PPCBSel();\n}\n\n\/\/\/ getNumBytesForInstruction - Return the number of bytes of code the specified\n\/\/\/ instruction may be. This returns the maximum number of bytes.\n\/\/\/\nstatic unsigned getNumBytesForInstruction(MachineInstr *MI) {\n switch (MI->getOpcode()) {\n case PPC::COND_BRANCH:\n \/\/ while this will be 4 most of the time, if we emit 8 it is just a\n \/\/ minor pessimization that saves us from having to worry about\n \/\/ keeping the offsets up to date later when we emit long branch glue.\n return 8;\n case PPC::IMPLICIT_DEF_GPRC: \/\/ no asm emitted\n case PPC::IMPLICIT_DEF_G8RC: \/\/ no asm emitted\n case PPC::IMPLICIT_DEF_F4: \/\/ no asm emitted\n case PPC::IMPLICIT_DEF_F8: \/\/ no asm emitted\n case PPC::IMPLICIT_DEF_VRRC: \/\/ no asm emitted\n return 0;\n case PPC::INLINEASM: { \/\/ Inline Asm: Variable size.\n MachineFunction *MF = MI->getParent()->getParent();\n const char *AsmStr = MI->getOperand(0).getSymbolName();\n return MF->getTarget().getTargetAsmInfo()->getInlineAsmLength(AsmStr);\n }\n default:\n return 4; \/\/ PowerPC instructions are all 4 bytes\n }\n}\n\n\nbool PPCBSel::runOnMachineFunction(MachineFunction &Fn) {\n \/\/ Running total of instructions encountered since beginning of function\n unsigned ByteCount = 0;\n \n \/\/ For each MBB, add its offset to the offset map, and count up its\n \/\/ instructions\n for (MachineFunction::iterator MFI = Fn.begin(), E = Fn.end(); MFI != E;\n ++MFI) {\n MachineBasicBlock *MBB = MFI;\n OffsetMap[MBB] = ByteCount;\n \n for (MachineBasicBlock::iterator MBBI = MBB->begin(), EE = MBB->end();\n MBBI != EE; ++MBBI)\n ByteCount += getNumBytesForInstruction(MBBI);\n }\n \n \/\/ We're about to run over the MBB's again, so reset the ByteCount\n ByteCount = 0;\n \n \/\/ For each MBB, find the conditional branch pseudo instructions, and\n \/\/ calculate the difference between the target MBB and the current ICount\n \/\/ to decide whether or not to emit a short or long branch.\n \/\/\n \/\/ short branch:\n \/\/ bCC .L_TARGET_MBB\n \/\/\n \/\/ long branch:\n \/\/ bInverseCC $PC+8\n \/\/ b .L_TARGET_MBB\n for (MachineFunction::iterator MFI = Fn.begin(), E = Fn.end(); MFI != E;\n ++MFI) {\n MachineBasicBlock *MBB = MFI;\n \n for (MachineBasicBlock::iterator MBBI = MBB->begin(), EE = MBB->end();\n MBBI != EE; ++MBBI) {\n \/\/ We may end up deleting the MachineInstr that MBBI points to, so\n \/\/ remember its opcode now so we can refer to it after calling erase()\n unsigned ByteSize = getNumBytesForInstruction(MBBI);\n if (MBBI->getOpcode() != PPC::COND_BRANCH) {\n ByteCount += ByteSize;\n continue;\n }\n \n \/\/ condbranch operands:\n \/\/ 0. CR register\n \/\/ 1. PPC branch opcode\n \/\/ 2. Target MBB\n MachineBasicBlock *DestMBB = MBBI->getOperand(2).getMachineBasicBlock();\n unsigned Opcode = MBBI->getOperand(1).getImmedValue();\n unsigned CRReg = MBBI->getOperand(0).getReg();\n \n int Displacement = OffsetMap[DestMBB] - ByteCount;\n unsigned Inverted = PPCInstrInfo::invertPPCBranchOpcode(Opcode);\n \n MachineBasicBlock::iterator MBBJ;\n if (Displacement >= -32768 && Displacement <= 32767) {\n MBBJ = BuildMI(*MBB, MBBJ, Opcode, 2).addReg(CRReg).addMBB(DestMBB);\n } else {\n \/\/ Long branch, skip next branch instruction (i.e. $PC+8).\n ++NumExpanded;\n BuildMI(*MBB, MBBJ, Inverted, 2).addReg(CRReg).addImm(2);\n MBBJ = BuildMI(*MBB, MBBJ, PPC::B, 1).addMBB(DestMBB);\n }\n \n \/\/ Erase the psuedo COND_BRANCH instruction, and then back up the\n \/\/ iterator so that when the for loop increments it, we end up in\n \/\/ the correct place rather than iterating off the end.\n MBB->erase(MBBI);\n MBBI = MBBJ;\n ByteCount += ByteSize;\n }\n }\n \n OffsetMap.clear();\n return true;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/* The following code example is taken from the book\n * \"The C++ Standard Library - A Tutorial and Reference, 2nd Edition\"\n * by Nicolai M. Josuttis, Addison-Wesley, 2012\n *\n * (C) Copyright Nicolai M. Josuttis 2012.\n * Permission to copy, use, modify, sell and distribute this software\n * is granted provided this copyright notice appears in all copies.\n * This software is provided \"as is\" without express or implied\n * warranty, and with no claim as to its suitability for any purpose.\n *\/\n#include \"algostuff.hpp\"\nusing namespace std;\n\nint main()\n{\n vector<int> coll = { 5, 3, 9, 1, 3, 4, 8, 2, 6 };\n PRINT_ELEMENTS(coll,\"coll: \");\n\n \/\/ define predicate: check whether element is odd:\n auto isOdd = [](int elem) {\n return elem%2==1;\n };\n\n \/\/ check whether coll is partitioned in odd and even elements\n if (is_partitioned (coll.cbegin(), coll.cend(), \/\/ range\n isOdd)) { \/\/ predicate\n cout << \"coll is partitioned\" << endl;\n\n \/\/ find first even element:\n auto pos = partition_point (coll.cbegin(),coll.cend(),\n isOdd);\n cout << \"first even element: \" << *pos << endl;\n }\n else {\n cout << \"coll is not partitioned\" << endl;\n }\n}\n<commit_msg>test is_partitioned && partition_point<commit_after>\/* The following code example is taken from the book\n * \"The C++ Standard Library - A Tutorial and Reference, 2nd Edition\"\n * by Nicolai M. Josuttis, Addison-Wesley, 2012\n *\n * (C) Copyright Nicolai M. Josuttis 2012.\n * Permission to copy, use, modify, sell and distribute this software\n * is granted provided this copyright notice appears in all copies.\n * This software is provided \"as is\" without express or implied\n * warranty, and with no claim as to its suitability for any purpose.\n *\/\n#include \"algostuff.hpp\"\nusing namespace std;\n\nint main()\n{\n vector<int> coll = { 5, 3, 9, 1, 3, 4, 8, 2, 6 };\n PRINT_ELEMENTS(coll,\"coll: \");\n\n \/\/ define predicate: check whether element is odd:\n auto isOdd = [](int elem) {\n return elem%2==1;\n };\n\n \/\/ check whether coll is partitioned in odd and even elements\n if (is_partitioned(coll.cbegin(), coll.cend(), \/\/ range\n isOdd)) { \/\/ predicate\n cout << \"coll is partitioned\" << endl;\n\n \/\/ find first even element:\n \/\/ The iterator past the end of the first partition within [first, last) or last if all elements satisfy p.\n auto pos = partition_point(coll.cbegin(),coll.cend(),\n isOdd);\n cout << \"first even element: \" << *pos << endl;\n } else {\n cout << \"coll is not partitioned\" << endl;\n }\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"SoundEngine.h\"\n\nSoundEngine::SoundEngine()\n{\n sounds = new SoundManager();\n}\n\nvoid SoundEngine::init() {\n int flags = Mix_Init(MIX_INIT_MP3);\n SDL_assert(MIX_INIT_MP3 == flags);\n SDL_assert(Mix_OpenAudio(MIX_DEFAULT_FREQUENCY, MIX_DEFAULT_FORMAT, 2, 4096) == 0);\n\n SDL_Log(\"Sound engine loaded\");\n setMusicVolumePercent(100.0f);\n SDL_Log(\"Music volume initialized to %d\", Mix_VolumeMusic(-1));\n}\n\nSoundEngine::~SoundEngine()\n{\n delete(sounds);\n Mix_CloseAudio();\n}\n\nvoid SoundEngine::playSound(const std::string &name, int loops) const\n{\n SDL_Log(\"Playing %s sound\", name.c_str());\n Mix_Chunk *sound = sounds->getSoundWithName(name);\n SDL_assert(sound != nullptr);\n Mix_PlayChannel(-1, sound, loops);\n}\n\nvoid SoundEngine::playMusic(const std::string &name, int loops) const\n{\n if(Mix_PlayingMusic()) {\n SDL_Log(\"Halting previous music playing\");\n Mix_HaltMusic();\n }\n Mix_Music *sound = sounds->getMusicWithName(name);\n SDL_assert(sound != nullptr);\n int playing = Mix_PlayMusic(sound, loops);\n SDL_Log(\"Playing %s music\", name.c_str());\n SDL_Log(\"Can't play music: %s\", Mix_GetError());\n if(playing == -1) \n {\n SDL_Log(\"Can't play music: %s\", Mix_GetError());\n }\n}\n\nvoid SoundEngine::playMusicWithFade(const std::string &name, int fade, int loops) const\n{\n Mix_Music *sound = sounds->getMusicWithName(name);\n SDL_assert(sound != nullptr);\n Mix_FadeInMusic(sound, loops, fade);\n SDL_Log(\"Playing %s music with fade\", name.c_str());\n}\n<commit_msg>Removing mp3 check in the sound engine<commit_after>#include \"SoundEngine.h\"\n\nSoundEngine::SoundEngine()\n{\n sounds = new SoundManager();\n}\n\nvoid SoundEngine::init() {\n SDL_assert(Mix_OpenAudio(MIX_DEFAULT_FREQUENCY, MIX_DEFAULT_FORMAT, 2, 4096) == 0);\n\n SDL_Log(\"Sound engine loaded\");\n setMusicVolumePercent(100.0f);\n SDL_Log(\"Music volume initialized to %d\", Mix_VolumeMusic(-1));\n}\n\nSoundEngine::~SoundEngine()\n{\n delete(sounds);\n Mix_CloseAudio();\n}\n\nvoid SoundEngine::playSound(const std::string &name, int loops) const\n{\n SDL_Log(\"Playing %s sound\", name.c_str());\n Mix_Chunk *sound = sounds->getSoundWithName(name);\n SDL_assert(sound != nullptr);\n Mix_PlayChannel(-1, sound, loops);\n}\n\nvoid SoundEngine::playMusic(const std::string &name, int loops) const\n{\n if(Mix_PlayingMusic()) {\n SDL_Log(\"Halting previous music playing\");\n Mix_HaltMusic();\n }\n Mix_Music *sound = sounds->getMusicWithName(name);\n SDL_assert(sound != nullptr);\n int playing = Mix_PlayMusic(sound, loops);\n SDL_Log(\"Playing %s music\", name.c_str());\n SDL_Log(\"Can't play music: %s\", Mix_GetError());\n if(playing == -1) \n {\n SDL_Log(\"Can't play music: %s\", Mix_GetError());\n }\n}\n\nvoid SoundEngine::playMusicWithFade(const std::string &name, int fade, int loops) const\n{\n Mix_Music *sound = sounds->getMusicWithName(name);\n SDL_assert(sound != nullptr);\n Mix_FadeInMusic(sound, loops, fade);\n SDL_Log(\"Playing %s music with fade\", name.c_str());\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"osx_window_capture.h\"\n\n\/\/ remove the window title bar which we are not interested in\n#define OSX_WINDOW_TITLE_BAR_HEIGHT 22\n\nOSXWindowCapture::OSXWindowCapture(const string& windowName)\n :name(windowName)\n{\n Update();\n}\n\nvoid OSXWindowCapture::Update() {\n winId = FindWindow(name);\n rect = GetWindowRect(winId);\n}\n\nint OSXWindowCapture::GetWidth() {\n return CGRectGetWidth(rect);\n}\n\nint OSXWindowCapture::GetHeight() {\n int height = CGRectGetHeight(rect);\n return IsFullscreen() ? height : max<int>(height - OSX_WINDOW_TITLE_BAR_HEIGHT, 0);\n}\n\nQPixmap OSXWindowCapture::Capture(int x, int y, int w, int h) {\n Update();\n\n if(!w) w = GetWidth();\n if(!w) h = GetHeight();\n\n CGRect captureRect = CGRectMake(x + CGRectGetMinX(rect),\n y + CGRectGetMinY(rect) + (IsFullscreen() ? 0 : OSX_WINDOW_TITLE_BAR_HEIGHT),\n w,\n h);\n\n CGImageRef image = CGWindowListCreateImage(captureRect,\n kCGWindowListOptionIncludingWindow,\n winId,\n kCGWindowImageNominalResolution | kCGWindowImageBoundsIgnoreFraming);\n\n QPixmap pixmap = QPixmap::fromMacCGImageRef(image);\n\n CGImageRelease(image);\n\n return pixmap;\n}\n\nbool OSXWindowCapture::IsFullscreen() {\n \/\/ this is not the most elegant solution, but I couldn't find a better way\n return CGRectGetMinX(rect) == 0.0f &&\n CGRectGetMinY(rect) == 0.0f &&\n (int(CGRectGetHeight(rect)) & OSX_WINDOW_TITLE_BAR_HEIGHT) != OSX_WINDOW_TITLE_BAR_HEIGHT;\n}\n\nbool OSXWindowCapture::WindowFound() {\n Update();\n return winId != 0;\n}\n\nint OSXWindowCapture::FindWindow(const string& name) {\n int winId = 0;\n\n CFArrayRef windowList = CGWindowListCopyWindowInfo(kCGWindowListExcludeDesktopElements, kCGNullWindowID);\n CFIndex numWindows = CFArrayGetCount(windowList);\n\n CFStringRef nameRef = CFStringCreateWithCString(kCFAllocatorDefault, name.c_str(), kCFStringEncodingMacRoman);\n\n for( int i = 0; i < (int)numWindows; i++ ) {\n CFDictionaryRef info = (CFDictionaryRef)CFArrayGetValueAtIndex(windowList, i);\n CFStringRef thisWindowName = (CFStringRef)CFDictionaryGetValue(info, kCGWindowName);\n CFStringRef thisWindowOwnerName = (CFStringRef)CFDictionaryGetValue(info, kCGWindowOwnerName);\n CFNumberRef thisWindowNumber = (CFNumberRef)CFDictionaryGetValue(info, kCGWindowNumber);\n\n if(thisWindowOwnerName && CFStringCompare(thisWindowOwnerName, nameRef, 0) == kCFCompareEqualTo) {\n if(thisWindowName && CFStringCompare(thisWindowName, nameRef, 0) == kCFCompareEqualTo) {\n CFNumberGetValue(thisWindowNumber, kCFNumberIntType, &winId);\n break;\n }\n }\n }\n\n CFRelease(nameRef);\n\n return winId;\n}\n\nCGRect OSXWindowCapture::GetWindowRect(int windowId) {\n CGRect rect = CGRectMake(0, 0, 0, 0);\n\n CFArrayRef windowList = CGWindowListCopyWindowInfo(kCGWindowListOptionIncludingWindow, windowId);\n CFIndex numWindows = CFArrayGetCount(windowList);\n if( numWindows > 0 ) {\n CFDictionaryRef info = (CFDictionaryRef)CFArrayGetValueAtIndex(windowList, 0);\n CGRectMakeWithDictionaryRepresentation((CFDictionaryRef)CFDictionaryGetValue(info, kCGWindowBounds), &rect);\n }\n\n return rect;\n}\n<commit_msg>disable automatic update due to performance hit<commit_after>#include \"osx_window_capture.h\"\n\n\/\/ remove the window title bar which we are not interested in\n#define OSX_WINDOW_TITLE_BAR_HEIGHT 22\n\nOSXWindowCapture::OSXWindowCapture(const string& windowName)\n :name(windowName)\n{\n Update();\n}\n\nvoid OSXWindowCapture::Update() {\n winId = FindWindow(name);\n rect = GetWindowRect(winId);\n}\n\nint OSXWindowCapture::GetWidth() {\n return CGRectGetWidth(rect);\n}\n\nint OSXWindowCapture::GetHeight() {\n int height = CGRectGetHeight(rect);\n return IsFullscreen() ? height : max<int>(height - OSX_WINDOW_TITLE_BAR_HEIGHT, 0);\n}\n\nQPixmap OSXWindowCapture::Capture(int x, int y, int w, int h) {\n if(!w) w = GetWidth();\n if(!w) h = GetHeight();\n\n CGRect captureRect = CGRectMake(x + CGRectGetMinX(rect),\n y + CGRectGetMinY(rect) + (IsFullscreen() ? 0 : OSX_WINDOW_TITLE_BAR_HEIGHT),\n w,\n h);\n\n CGImageRef image = CGWindowListCreateImage(captureRect,\n kCGWindowListOptionIncludingWindow,\n winId,\n kCGWindowImageNominalResolution | kCGWindowImageBoundsIgnoreFraming);\n\n QPixmap pixmap = QPixmap::fromMacCGImageRef(image);\n\n CGImageRelease(image);\n\n return pixmap;\n}\n\nbool OSXWindowCapture::IsFullscreen() {\n \/\/ this is not the most elegant solution, but I couldn't find a better way\n return CGRectGetMinX(rect) == 0.0f &&\n CGRectGetMinY(rect) == 0.0f &&\n (int(CGRectGetHeight(rect)) & OSX_WINDOW_TITLE_BAR_HEIGHT) != OSX_WINDOW_TITLE_BAR_HEIGHT;\n}\n\nbool OSXWindowCapture::WindowFound() {\n return winId != 0;\n}\n\nint OSXWindowCapture::FindWindow(const string& name) {\n int winId = 0;\n\n CFArrayRef windowList = CGWindowListCopyWindowInfo(kCGWindowListExcludeDesktopElements, kCGNullWindowID);\n CFIndex numWindows = CFArrayGetCount(windowList);\n\n CFStringRef nameRef = CFStringCreateWithCString(kCFAllocatorDefault, name.c_str(), kCFStringEncodingMacRoman);\n\n for( int i = 0; i < (int)numWindows; i++ ) {\n CFDictionaryRef info = (CFDictionaryRef)CFArrayGetValueAtIndex(windowList, i);\n CFStringRef thisWindowName = (CFStringRef)CFDictionaryGetValue(info, kCGWindowName);\n CFStringRef thisWindowOwnerName = (CFStringRef)CFDictionaryGetValue(info, kCGWindowOwnerName);\n CFNumberRef thisWindowNumber = (CFNumberRef)CFDictionaryGetValue(info, kCGWindowNumber);\n\n if(thisWindowOwnerName && CFStringCompare(thisWindowOwnerName, nameRef, 0) == kCFCompareEqualTo) {\n if(thisWindowName && CFStringCompare(thisWindowName, nameRef, 0) == kCFCompareEqualTo) {\n CFNumberGetValue(thisWindowNumber, kCFNumberIntType, &winId);\n break;\n }\n }\n }\n\n CFRelease(nameRef);\n\n return winId;\n}\n\nCGRect OSXWindowCapture::GetWindowRect(int windowId) {\n CGRect rect = CGRectMake(0, 0, 0, 0);\n\n CFArrayRef windowList = CGWindowListCopyWindowInfo(kCGWindowListOptionIncludingWindow, windowId);\n CFIndex numWindows = CFArrayGetCount(windowList);\n if( numWindows > 0 ) {\n CFDictionaryRef info = (CFDictionaryRef)CFArrayGetValueAtIndex(windowList, 0);\n CGRectMakeWithDictionaryRepresentation((CFDictionaryRef)CFDictionaryGetValue(info, kCGWindowBounds), &rect);\n }\n\n return rect;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2015 The WebM project authors. All Rights Reserved.\n\/\/\n\/\/ Use of this source code is governed by a BSD-style license\n\/\/ that can be found in the LICENSE file in the root of the source\n\/\/ tree. An additional intellectual property rights grant can be found\n\/\/ in the file PATENTS. All contributing project authors may\n\/\/ be found in the AUTHORS file in the root of the source tree.\n#include \"common\/libwebm_utils.h\"\n\n#include <cstdint>\n#include <cstdio>\n\nnamespace libwebm {\n\nstd::int64_t NanosecondsTo90KhzTicks(std::int64_t nanoseconds) {\n const double kNanosecondsPerSecond = 1000000000.0;\n const double pts_seconds = nanoseconds \/ kNanosecondsPerSecond;\n return pts_seconds * 90000;\n}\n\nbool ParseVP9SuperFrameIndex(const std::uint8_t* frame,\n std::size_t length,\n Ranges* frame_ranges) {\n if (frame == nullptr || length == 0 || frame_ranges == nullptr)\n return false;\n\n bool parse_ok = false;\n const std::uint8_t marker = frame[length - 1];\n const std::uint32_t kHasSuperFrameIndexMask = 0xe0;\n const std::uint32_t kSuperFrameMarker = 0xc0;\n\n if ((marker & kHasSuperFrameIndexMask) == kSuperFrameMarker) {\n const std::uint32_t kFrameCountMask = 0x7;\n const int num_frames = (marker & kFrameCountMask) + 1;\n const int length_field_size = ((marker >> 3) & 0x3) + 1;\n const std::size_t index_length = 2 + length_field_size * num_frames;\n\n \/\/ Consume the super frame index.\n std::size_t frame_offset = index_length;\n\n if (length >= index_length && frame[length - index_length] == marker) {\n \/\/ Found a valid superframe index.\n const std::uint8_t* byte = frame + length - index_length + 1;\n\n for (int i = 0; i < num_frames; ++i) {\n std::uint32_t child_frame_length = 0;\n\n for (int j = 0; j < length_field_size; ++j) {\n child_frame_length |= (*byte++) << (j * 8);\n }\n\n frame_ranges->push_back(Range(frame_offset, child_frame_length));\n frame_offset += child_frame_length;\n }\n\n if (frame_ranges->size() != num_frames) {\n std::fprintf(stderr, \"Webm2Pes: superframe index parse failed.\\n\");\n return false;\n }\n\n parse_ok = true;\n } else {\n std::fprintf(stderr, \"Webm2Pes: Invalid superframe index.\\n\");\n }\n }\n return parse_ok;\n}\n\nbool WriteUint8(std::uint8_t val, std::FILE* fileptr) {\n if (fileptr == nullptr)\n return false;\n return (std::fputc(val, fileptr) == val);\n}\n\n} \/\/ namespace libwebm\n<commit_msg>webm2pes: Fix super frame splitting.<commit_after>\/\/ Copyright (c) 2015 The WebM project authors. All Rights Reserved.\n\/\/\n\/\/ Use of this source code is governed by a BSD-style license\n\/\/ that can be found in the LICENSE file in the root of the source\n\/\/ tree. An additional intellectual property rights grant can be found\n\/\/ in the file PATENTS. All contributing project authors may\n\/\/ be found in the AUTHORS file in the root of the source tree.\n#include \"common\/libwebm_utils.h\"\n\n#include <cstdint>\n#include <cstdio>\n\nnamespace libwebm {\n\nstd::int64_t NanosecondsTo90KhzTicks(std::int64_t nanoseconds) {\n const double kNanosecondsPerSecond = 1000000000.0;\n const double pts_seconds = nanoseconds \/ kNanosecondsPerSecond;\n return pts_seconds * 90000;\n}\n\nbool ParseVP9SuperFrameIndex(const std::uint8_t* frame,\n std::size_t frame_length,\n Ranges* frame_ranges) {\n if (frame == nullptr || frame_length == 0 || frame_ranges == nullptr)\n return false;\n\n bool parse_ok = false;\n const std::uint8_t marker = frame[frame_length - 1];\n const std::uint32_t kHasSuperFrameIndexMask = 0xe0;\n const std::uint32_t kSuperFrameMarker = 0xc0;\n const std::uint32_t kLengthFieldSizeMask = 0x3;\n\n if ((marker & kHasSuperFrameIndexMask) == kSuperFrameMarker) {\n const std::uint32_t kFrameCountMask = 0x7;\n const int num_frames = (marker & kFrameCountMask) + 1;\n const int length_field_size = ((marker >> 3) & kLengthFieldSizeMask) + 1;\n const std::size_t index_length = 2 + length_field_size * num_frames;\n\n if (frame_length < index_length) {\n std::fprintf(stderr, \"Webm2Pes: Invalid superframe index size.\\n\");\n return false;\n }\n\n \/\/ Consume the super frame index. Note: it's at the end of the super frame.\n const std::size_t length = frame_length - index_length;\n\n if (length >= index_length &&\n frame[frame_length - index_length] == marker) {\n \/\/ Found a valid superframe index.\n const std::uint8_t* byte = frame + length + 1;\n\n std::size_t frame_offset = 0;\n for (int i = 0; i < num_frames; ++i) {\n std::uint32_t child_frame_length = 0;\n\n for (int j = 0; j < length_field_size; ++j) {\n child_frame_length |= (*byte++) << (j * 8);\n }\n\n frame_ranges->push_back(Range(frame_offset, child_frame_length));\n frame_offset += child_frame_length;\n }\n\n if (frame_ranges->size() != num_frames) {\n std::fprintf(stderr, \"Webm2Pes: superframe index parse failed.\\n\");\n return false;\n }\n\n parse_ok = true;\n } else {\n std::fprintf(stderr, \"Webm2Pes: Invalid superframe index.\\n\");\n }\n }\n return parse_ok;\n}\n\nbool WriteUint8(std::uint8_t val, std::FILE* fileptr) {\n if (fileptr == nullptr)\n return false;\n return (std::fputc(val, fileptr) == val);\n}\n\n} \/\/ namespace libwebm\n<|endoftext|>"} {"text":"<commit_before>#include \"ui\/gl\/gl_implementation.h\"\n#include \"imx_gl_viv_direct_texture.h\"\n\n\nbool init_viv_direct_texture(gfx::GLContext &context, GLESVIVDirectTextureProcs &procs)\n{\n\tVLOG(1) << \"Initializing Vivante direct texture GLES extension\";\n\n\tgfx::GLImplementation glimpl = gfx::GetGLImplementation();\n\tif (glimpl != gfx::kGLImplementationEGLGLES2)\n\t{\n\t\tLOG(INFO) << \"Cannot initialize direct textures - GL implementation is \"\n\t\t << gfx::GetGLImplementationName(glimpl)\n\t\t << \", expected \" <<\n\t\t gfx::GetGLImplementationName(gfx::kGLImplementationEGLGLES2);\n\t\treturn false;\n\t}\n\n\tif (context.HasExtension(\"GL_VIV_direct_texture\"))\n\t\tVLOG(1) << \"GL_VIV_direct_texture supported\";\n\telse\n\t{\n\t\tVLOG(1) << \"GL_VIV_direct_texture not supported\";\n\t\treturn false;\n\t}\n\n\tprocs.TexDirectVIV = reinterpret_cast < PFNGLTEXDIRECTVIVPROC > (gfx::GetGLProcAddress(\"glTexDirectVIV\"));\n\tprocs.TexDirectVIVMap = reinterpret_cast < PFNGLTEXDIRECTVIVMAPPROC > (gfx::GetGLProcAddress(\"glTexDirectVIVMap\"));\n\tprocs.TexDirectTiledMapVIV = reinterpret_cast < PFNGLTEXDIRECTTILEDMAPVIVPROC > (gfx::GetGLProcAddress(\"glTexDirectTiledMapVIV\"));\n\tprocs.TexDirectInvalidateVIV = reinterpret_cast < PFNGLTEXDIRECTINVALIDATEVIVPROC > (gfx::GetGLProcAddress(\"glTexDirectInvalidateVIV\"));\n\n\treturn true;\n}\n\n<commit_msg>Let direct texture code correctly detect the extension with newer drivers<commit_after>#include \"ui\/gl\/gl_implementation.h\"\n#include \"imx_gl_viv_direct_texture.h\"\n\n\nbool init_viv_direct_texture(gfx::GLContext &context, GLESVIVDirectTextureProcs &procs)\n{\n\tVLOG(1) << \"Initializing Vivante direct texture GLES extension\";\n\n\tgfx::GLImplementation glimpl = gfx::GetGLImplementation();\n\tif (glimpl != gfx::kGLImplementationEGLGLES2)\n\t{\n\t\tLOG(INFO) << \"Cannot initialize direct textures - GL implementation is \"\n\t\t << gfx::GetGLImplementationName(glimpl)\n\t\t << \", expected \" <<\n\t\t gfx::GetGLImplementationName(gfx::kGLImplementationEGLGLES2);\n\t\treturn false;\n\t}\n\n\t\/\/ Newer Vivante drivers call the extension GL_VIV_tex_direct instead of GL_VIV_direct_texture,\n\t\/\/ even though it is the same extension\n\tif (context.HasExtension(\"GL_VIV_direct_texture\"))\n\t\tVLOG(1) << \"GL_VIV_direct_texture supported\";\n\telse if (context.HasExtension(\"GL_VIV_tex_direct\"))\n\t\tVLOG(1) << \"GL_VIV_tex_direct supported\";\n\telse\n\t{\n\t\tVLOG(1) << \"Neither GL_VIV_direct_texture nor GL_VIV_tex_direct supported\";\n\t\treturn false;\n\t}\n\n\tprocs.TexDirectVIV = reinterpret_cast < PFNGLTEXDIRECTVIVPROC > (gfx::GetGLProcAddress(\"glTexDirectVIV\"));\n\tprocs.TexDirectVIVMap = reinterpret_cast < PFNGLTEXDIRECTVIVMAPPROC > (gfx::GetGLProcAddress(\"glTexDirectVIVMap\"));\n\tprocs.TexDirectTiledMapVIV = reinterpret_cast < PFNGLTEXDIRECTTILEDMAPVIVPROC > (gfx::GetGLProcAddress(\"glTexDirectTiledMapVIV\"));\n\tprocs.TexDirectInvalidateVIV = reinterpret_cast < PFNGLTEXDIRECTINVALIDATEVIVPROC > (gfx::GetGLProcAddress(\"glTexDirectInvalidateVIV\"));\n\n\treturn true;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/*++\nCopyright (c) 2014 Microsoft Corporation\n\nModule Name:\n\n wmax.cpp\n\nAbstract:\n\n Theory based MaxSAT.\n\nAuthor:\n\n Nikolaj Bjorner (nbjorner) 2014-4-17\n\nNotes:\n\n--*\/\n#include \"wmax.h\"\n#include \"uint_set.h\"\n#include \"ast_pp.h\"\n#include \"model_smt2_pp.h\"\n#include \"smt_theory.h\"\n#include \"smt_context.h\"\n#include \"theory_wmaxsat.h\"\n#include \"opt_context.h\"\n\nnamespace opt {\n class maxsmt_solver_wbase : public maxsmt_solver_base {\n smt::context& ctx;\n public:\n maxsmt_solver_wbase(context& c,\n vector<rational> const& ws, expr_ref_vector const& soft): \n maxsmt_solver_base(c, ws, soft), ctx(c.smt_context()) {}\n ~maxsmt_solver_wbase() {}\n\n class scoped_ensure_theory {\n smt::theory_wmaxsat* m_wth;\n public:\n scoped_ensure_theory(maxsmt_solver_wbase& s) {\n m_wth = s.ensure_theory();\n }\n ~scoped_ensure_theory() {\n m_wth->reset();\n }\n smt::theory_wmaxsat& operator()() { return *m_wth; }\n };\n \n smt::theory_wmaxsat* ensure_theory() {\n smt::theory_wmaxsat* wth = get_theory();\n if (wth) {\n wth->reset();\n }\n else {\n wth = alloc(smt::theory_wmaxsat, m, m_c.fm());\n ctx.register_plugin(wth);\n }\n return wth;\n }\n smt::theory_wmaxsat* get_theory() const {\n smt::theory_id th_id = m.get_family_id(\"weighted_maxsat\");\n smt::theory* th = ctx.get_theory(th_id); \n if (th) {\n return dynamic_cast<smt::theory_wmaxsat*>(th);\n }\n else {\n return 0;\n }\n }\n };\n\n \/\/ ----------------------------------------------------------\n \/\/ weighted max-sat using a custom theory solver for max-sat.\n \/\/ NB. it is quite similar to pseudo-Boolean propagation.\n\n\n class wmax : public maxsmt_solver_wbase {\n public:\n wmax(context& c,\n vector<rational> const& ws, expr_ref_vector const& soft): \n maxsmt_solver_wbase(c, ws, soft) {}\n virtual ~wmax() {}\n\n lbool operator()() {\n TRACE(\"opt\", tout << \"weighted maxsat\\n\";);\n scoped_ensure_theory wth(*this);\n solver::scoped_push _s1(s());\n lbool is_sat = l_true;\n bool was_sat = false;\n for (unsigned i = 0; i < m_soft.size(); ++i) {\n wth().assert_weighted(m_soft[i].get(), m_weights[i]);\n }\n solver::scoped_push _s2(s());\n while (l_true == is_sat) {\n is_sat = s().check_sat(0,0);\n if (m_cancel) {\n is_sat = l_undef;\n }\n if (is_sat == l_true) {\n if (wth().is_optimal()) {\n m_upper = wth().get_min_cost();\n s().get_model(m_model);\n }\n expr_ref fml = wth().mk_block();\n s().assert_expr(fml);\n was_sat = true;\n }\n IF_VERBOSE(1, verbose_stream() << \"(opt.wmax [\" << m_lower << \":\" << m_upper << \"])\\n\";);\n }\n if (was_sat) {\n wth().get_assignment(m_assignment);\n }\n if (is_sat == l_false && was_sat) {\n is_sat = l_true;\n }\n m_upper = wth().get_min_cost();\n if (is_sat == l_true) {\n m_lower = m_upper;\n }\n TRACE(\"opt\", tout << \"min cost: \" << m_upper << \"\\n\";);\n return is_sat;\n }\n };\n\n maxsmt_solver_base* opt::mk_wmax(context& c, \n vector<rational> const& ws, expr_ref_vector const& soft) {\n return alloc(wmax, c, ws, soft);\n }\n\n}\n<commit_msg>remove extra qualifier<commit_after>\/*++\nCopyright (c) 2014 Microsoft Corporation\n\nModule Name:\n\n wmax.cpp\n\nAbstract:\n\n Theory based MaxSAT.\n\nAuthor:\n\n Nikolaj Bjorner (nbjorner) 2014-4-17\n\nNotes:\n\n--*\/\n#include \"wmax.h\"\n#include \"uint_set.h\"\n#include \"ast_pp.h\"\n#include \"model_smt2_pp.h\"\n#include \"smt_theory.h\"\n#include \"smt_context.h\"\n#include \"theory_wmaxsat.h\"\n#include \"opt_context.h\"\n\nnamespace opt {\n class maxsmt_solver_wbase : public maxsmt_solver_base {\n smt::context& ctx;\n public:\n maxsmt_solver_wbase(context& c,\n vector<rational> const& ws, expr_ref_vector const& soft): \n maxsmt_solver_base(c, ws, soft), ctx(c.smt_context()) {}\n ~maxsmt_solver_wbase() {}\n\n class scoped_ensure_theory {\n smt::theory_wmaxsat* m_wth;\n public:\n scoped_ensure_theory(maxsmt_solver_wbase& s) {\n m_wth = s.ensure_theory();\n }\n ~scoped_ensure_theory() {\n m_wth->reset();\n }\n smt::theory_wmaxsat& operator()() { return *m_wth; }\n };\n \n smt::theory_wmaxsat* ensure_theory() {\n smt::theory_wmaxsat* wth = get_theory();\n if (wth) {\n wth->reset();\n }\n else {\n wth = alloc(smt::theory_wmaxsat, m, m_c.fm());\n ctx.register_plugin(wth);\n }\n return wth;\n }\n smt::theory_wmaxsat* get_theory() const {\n smt::theory_id th_id = m.get_family_id(\"weighted_maxsat\");\n smt::theory* th = ctx.get_theory(th_id); \n if (th) {\n return dynamic_cast<smt::theory_wmaxsat*>(th);\n }\n else {\n return 0;\n }\n }\n };\n\n \/\/ ----------------------------------------------------------\n \/\/ weighted max-sat using a custom theory solver for max-sat.\n \/\/ NB. it is quite similar to pseudo-Boolean propagation.\n\n\n class wmax : public maxsmt_solver_wbase {\n public:\n wmax(context& c,\n vector<rational> const& ws, expr_ref_vector const& soft): \n maxsmt_solver_wbase(c, ws, soft) {}\n virtual ~wmax() {}\n\n lbool operator()() {\n TRACE(\"opt\", tout << \"weighted maxsat\\n\";);\n scoped_ensure_theory wth(*this);\n solver::scoped_push _s1(s());\n lbool is_sat = l_true;\n bool was_sat = false;\n for (unsigned i = 0; i < m_soft.size(); ++i) {\n wth().assert_weighted(m_soft[i].get(), m_weights[i]);\n }\n solver::scoped_push _s2(s());\n while (l_true == is_sat) {\n is_sat = s().check_sat(0,0);\n if (m_cancel) {\n is_sat = l_undef;\n }\n if (is_sat == l_true) {\n if (wth().is_optimal()) {\n m_upper = wth().get_min_cost();\n s().get_model(m_model);\n }\n expr_ref fml = wth().mk_block();\n s().assert_expr(fml);\n was_sat = true;\n }\n IF_VERBOSE(1, verbose_stream() << \"(opt.wmax [\" << m_lower << \":\" << m_upper << \"])\\n\";);\n }\n if (was_sat) {\n wth().get_assignment(m_assignment);\n }\n if (is_sat == l_false && was_sat) {\n is_sat = l_true;\n }\n m_upper = wth().get_min_cost();\n if (is_sat == l_true) {\n m_lower = m_upper;\n }\n TRACE(\"opt\", tout << \"min cost: \" << m_upper << \"\\n\";);\n return is_sat;\n }\n };\n\n maxsmt_solver_base* mk_wmax(context& c, \n vector<rational> const& ws, expr_ref_vector const& soft) {\n return alloc(wmax, c, ws, soft);\n }\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ main.cpp\n\/\/ Unit Tests\n\/\/\n\/\/ Created by Evan McCartney-Melstad on 12\/31\/14.\n\/\/ Copyright (c) 2014 Evan McCartney-Melstad. All rights reserved.\n\/\/\n\n#define CATCH_CONFIG_MAIN \/\/ This tells Catch to provide a main() - only do this in one cpp file\n#include \"..\/cPWP\/generateSimulatedData.h\"\n#include \"..\/cPWP\/bamsToBin.h\"\n\/\/#include \"..\/cPWP\/calcPWP.h\"\n#include \"..\/cPWP\/calcPWPchunks.h\"\n#include \"..\/cPWP\/calcCOVARchunks.h\"\n#include \"catch.hpp\"\n#include <string>\n#include <iostream>\n#include <fstream>\n\n\n\/*\nTEST_CASE( \"Simulated reads are generated\", \"[generateReads]\" ) {\n \/\/ Make sure that the read simulation finishes\n REQUIRE( generateReadsAndMap(1, 0.01, \"0.0\", \"300\", \"50\", \"1000000\", \"100\", \"1234\", \"scaffold_0.fasta\") == 0);\n}\n *\/\n\nTEST_CASE( \"Generate reference genome for simulation tests\", \"[generateReference]\") {\n REQUIRE( createReferenceGenome(1000000, 0.42668722, \"simulatedReferenceGenome.fasta\") == 0 );\n \/\/createReferenceGenome (int totalBases, double gcContent, std::string genomeOutFile) \n}\n\nTEST_CASE ( \"Mutate a reference genome\", \"[mutateRefGenome]\") {\n REQUIRE( createMutatedGenome(\"simulatedReferenceGenome.fasta\", \"simulatedReferenceGenomeMutated.fasta\", 0.01) == 0);\n \/\/createMutatedGenome (std::string reference, std::string mutatedReferenceFile, float percDivergent) \n}\n\n\n\nTEST_CASE( \"Generate sequence reads 5\", \"[perfectReads]\") {\n REQUIRE( generatePerfectReads (\"simulatedReferenceGenome.fasta\", 5, 100, 300, \"normalRef5\") == 0);\n \/\/generatePerfectReads (std::string reference, unsigned int stagger, unsigned int readLengths, unsigned int fragmentLengths, std::string readPrefix);\n}\n\n\n\/\/ We need to create a set of reads that are half as dense as the first set, because when we concatenate the heterozygous chromosome reads to them we don't\n\/\/ want the coverage to be twice as high.\nTEST_CASE( \"Generate sequence reads 10\", \"[perfectReads]\") {\n REQUIRE( generatePerfectReads (\"simulatedReferenceGenome.fasta\", 10, 100, 300, \"normalRef10\") == 0);\n \/\/generatePerfectReads (std::string reference, unsigned int stagger, unsigned int readLengths, unsigned int fragmentLengths, std::string readPrefix);\n}\n\n\n\/\/ Map the reads for the homozygous individual\nTEST_CASE( \" Mapping first set of reads\", \"[mapReads]\") {\n REQUIRE( mapReads(\"simulatedReferenceGenome.fasta\", \"normalRef5_R1.fastq\", \"normalRef5_R2.fastq\", \"normal.bam\", \"5\") == 0);\n \/\/mapReads (std::string reference, std::string R1file, std::string R2file, std::string outBam, std::string threads)\n}\n\n\n\/\/ Generate the reads from the mutated reference chromosome\nTEST_CASE( \"Generate sequence reads 2\", \"[perfectReads2]\") {\n REQUIRE( generatePerfectReads (\"simulatedReferenceGenomeMutated.fasta\", 10, 100, 300, \"mutatedRef\") == 0);\n \/\/generatePerfectReads (std::string reference, unsigned int stagger, unsigned int readLengths, unsigned int fragmentLengths, std::string readPrefix);\n}\n\n\n\/\/ Concatenate the het-reference reads to the homozygous reads reference for R1\nTEST_CASE( \"Create heterozygous R1\", \"[createHetR1]\") {\n REQUIRE( createHeterozygousGenome(\"normalRef10_R1.fastq\", \"mutatedRef_R1.fastq\", \"hetRef_R1.fastq\") == 0);\n \/\/createHeterozygousGenome(std::string firstFile, std::string secondFile, std::string outputGenome)\n}\n\n\/\/ Concatenate the het-reference reads to the homozygous reads reference for R2\nTEST_CASE( \"Create heterozygous R2\", \"[createHetR1]\") {\n REQUIRE( createHeterozygousGenome(\"normalRef10_R2.fastq\", \"mutatedRef_R2.fastq\", \"hetRef_R2.fastq\") == 0);\n \/\/createHeterozygousGenome(std::string firstFile, std::string secondFile, std::string outputGenome)\n}\n\n\/\/ Map the reads for the heterozygous individual\nTEST_CASE( \" Mapping het reads\", \"[mapReads2]\") {\n REQUIRE( mapReads(\"simulatedReferenceGenome.fasta\", \"hetRef_R1.fastq\", \"hetRef_R2.fastq\", \"het.bam\", \"5\") == 0);\n \/\/mapReads (std::string reference, std::string R1file, std::string R2file, std::string outBam, std::string threads)\n}\n\n\n\/\/ Use angsd to generate the read counts for the two individuals\nTEST_CASE( \"Run ANGSD on simulated reads\", \"[runANGSD]\" ) {\n REQUIRE( runANGSDforReadCounts(\"bamlist.txt\", \"angsdOut\", \"5\", \"angsdOutLog.txt\") == 0);\n \/\/runANGSDforReadCounts (std::string bamlist, std::string angsdPrefix, std::string nThreads, std::string angsdOutputLog)\n}\n\n\/\/ Convert read counts to binary\nTEST_CASE( \"Convert ANGSD read counts to unsigned chars for major and minor counts\", \"[convertCountsToBinary]\") {\n REQUIRE( convertANGSDcountsToBinary(\"angsdOut\", \"angsdOut.readCounts.binary\", 2, 250) == 0);\n \/\/convertANGSDcountsToBinary(std::string angsdPrefix, std::string binaryOutputFileName, int numIndividuals, int readDepthMax)\n}\n\n\/\/ Run the PWP calculation\nTEST_CASE( \"Calculate PWP from the binary representations of the ANGSD readcounts\", \"[calcPWP]\") {\n REQUIRE( calcPWPfromBinaryFile(\"angsdOut.readCounts.binary\", 999990, 2, \"testingOut.pwp\", 1000, 5) == 0);\n \/\/int calcPWPfromBinaryFile (std::string binaryFile, unsigned long long int numLoci, const int numIndividuals, std::string outFile, int lociChunkSize, int numThreads=30);\n}\n\n\n\n\n\n\n\n\/* \n Covariance unit tests are below. They require different reference genomes to be used. In the example above, the homozygous reference genome\n has no variance in the major allele frequencies (they're always 1). The genomes created by this example have \n \n \n \n \n *\/\n\n\nTEST_CASE( \"Generate reference genome for the covariance tests\", \"[generateReferenceCovar]\") {\n REQUIRE( createReferenceGenome(10000000, 0.42668722, \"simulatedReferenceGenome10mil.fasta\") == 0 );\n \/\/createReferenceGenome (int totalBases, double gcContent, std::string genomeOutFile)\n}\n\n\nTEST_CASE ( \"Mutate a reference genome\", \"[mutateRefGenomeCovar]\") {\n REQUIRE( createMutatedGenomesForCovar(\"simulatedReferenceGenome10mil.fasta\", \"simulatedReferenceGenomeMutatedRef1.fasta\", \"simulatedReferenceGenomeMutatedRef2.fasta\", 0.01) == 0);\n \/\/createMutatedGenomesForCovar (std::string reference, std::string mutatedReferenceFile1, std::string mutatedReferenceFile2, float percDivergent)\n}\n\n\nTEST_CASE( \"Generate nonmutated chromosome covariance sequence reads for ind1 and ind2\", \"[perfectReadsCovarNoMut]\") {\n REQUIRE( generatePerfectReads (\"simulatedReferenceGenome10mil.fasta\", 10, 100, 300, \"covarRef\") == 0);\n \/\/generatePerfectReads (std::string reference, unsigned int stagger, unsigned int readLengths, unsigned int fragmentLengths, std::string readPrefix);\n}\n\n\n\nTEST_CASE( \"Generate mutated chromosome covariance sequence reads for ind1\", \"[perfectReadsCovarInd1]\") {\n REQUIRE( generatePerfectReads (\"simulatedReferenceGenomeMutatedRef1.fasta\", 10, 100, 300, \"covarMutRef1\") == 0);\n \/\/generatePerfectReads (std::string reference, unsigned int stagger, unsigned int readLengths, unsigned int fragmentLengths, std::string readPrefix);\n}\n\n\nTEST_CASE( \"Generate mutated chromosome covariance sequence reads for ind2\", \"[perfectReadsCovarInd2]\") {\n REQUIRE( generatePerfectReads (\"simulatedReferenceGenomeMutatedRef2.fasta\", 10, 100, 300, \"covarMutRef2\") == 0);\n \/\/generatePerfectReads (std::string reference, unsigned int stagger, unsigned int readLengths, unsigned int fragmentLengths, std::string readPrefix);\n}\n\n\n\n\/\/ Combine the mutated and non-mutated chromosome reads for each individual\n\/\/ Concatenate the het-reference reads to the homozygous reads reference for R1\nTEST_CASE( \"Create heterozygous R1covar1\", \"[createHetR1covar1]\") {\n REQUIRE( createHeterozygousGenome(\"covarRef_R1.fastq\", \"covarMutRef1_R1.fastq\", \"covarRef1_R1.fastq\") == 0);\n \/\/createHeterozygousGenome(std::string firstFile, std::string secondFile, std::string outputGenome)\n}\n\n\/\/ Concatenate the het-reference reads to the homozygous reads reference for R2\nTEST_CASE( \"Create heterozygous R2covar1\", \"[createHetR2covar1]\") {\n REQUIRE( createHeterozygousGenome(\"covarRef_R2.fastq\", \"covarMutRef1_R2.fastq\", \"covarRef1_R2.fastq\") == 0);\n \/\/createHeterozygousGenome(std::string firstFile, std::string secondFile, std::string outputGenome)\n}\n\n\/\/ Concatenate the het-reference reads to the homozygous reads reference for R1\nTEST_CASE( \"Create heterozygous R1covar2\", \"[createHetR1covar2]\") {\n REQUIRE( createHeterozygousGenome(\"covarRef_R1.fastq\", \"covarMutRef2_R1.fastq\", \"covarRef2_R1.fastq\") == 0);\n \/\/createHeterozygousGenome(std::string firstFile, std::string secondFile, std::string outputGenome)\n}\n\n\/\/ Concatenate the het-reference reads to the homozygous reads reference for R2\nTEST_CASE( \"Create heterozygous R2covar2\", \"[createHetR2covar2]\") {\n REQUIRE( createHeterozygousGenome(\"covarRef_R2.fastq\", \"covarMutRef2_R2.fastq\", \"covarRef2_R2.fastq\") == 0);\n \/\/createHeterozygousGenome(std::string firstFile, std::string secondFile, std::string outputGenome)\n}\n\n\n\/\/ Map the reads for individual 1\nTEST_CASE( \" Mapping reads for covariance ind1\", \"[mapReadsCovar1]\") {\n REQUIRE( mapReads(\"simulatedReferenceGenome10mil.fasta\", \"covarRef1_R1.fastq\", \"covarRef1_R2.fastq\", \"covarInd1.bam\", \"5\") == 0);\n \/\/mapReads (std::string reference, std::string R1file, std::string R2file, std::string outBam, std::string threads)\n}\n\n\n\/\/ Map the reads for individual 2\nTEST_CASE( \" Mapping reads for covariance ind2\", \"[mapReadsCovar2]\") {\n REQUIRE( mapReads(\"simulatedReferenceGenome10mil.fasta\", \"covarRef2_R1.fastq\", \"covarRef2_R2.fastq\", \"covarInd2.bam\", \"5\") == 0);\n \/\/mapReads (std::string reference, std::string R1file, std::string R2file, std::string outBam, std::string threads)\n}\n\n\n\n\/\/ Use angsd to generate the read counts for the two individuals\nTEST_CASE( \"Run ANGSD on simulated reads\", \"[runANGSD]\" ) {\n REQUIRE( runANGSDforReadCounts(\"covarBamlist.txt\", \"covarAngsdOut\", \"5\", \"covarAngsdOutLog.txt\") == 0);\n \/\/runANGSDforReadCounts (std::string bamlist, std::string angsdPrefix, std::string nThreads, std::string angsdOutputLog)\n}\n\n\/\/ Convert read counts to binary\nTEST_CASE( \"Convert ANGSD read counts to unsigned chars for major and minor counts\", \"[convertCountsToBinary]\") {\n REQUIRE( convertANGSDcountsToBinary(\"covarAngsdOut\", \"covarAngsdOut.readCounts.binary\", 2, 250) == 0);\n \/\/convertANGSDcountsToBinary(std::string angsdPrefix, std::string binaryOutputFileName, int numIndividuals, int readDepthMax)\n}\n\n\nTEST_CASE( \"Calculate covariances from the same representations of the ANGSD readcounts\", \"[calcCovar]\") {\n REQUIRE( calcCOVARfromBinaryFile(\"covarAngsdOut.readCounts.binary\", 9999990, 2, \"testingOut.covar\", 1000, 5)== 0);\n \/\/calcCOVARfromBinaryFile (std::string binaryFile, long long int numLoci, const int numIndividuals, std::string outFile, int lociChunkSize, const int numThreads)\n}\n\n\n<commit_msg>Minor change<commit_after>\/\/\n\/\/ main.cpp\n\/\/ Unit Tests\n\/\/\n\/\/ Created by Evan McCartney-Melstad on 12\/31\/14.\n\/\/ Copyright (c) 2014 Evan McCartney-Melstad. All rights reserved.\n\/\/\n\n#define CATCH_CONFIG_MAIN \/\/ This tells Catch to provide a main() - only do this in one cpp file\n#include \"..\/cPWP\/generateSimulatedData.h\"\n#include \"..\/cPWP\/bamsToBin.h\"\n\/\/#include \"..\/cPWP\/calcPWP.h\"\n#include \"..\/cPWP\/calcPWPchunks.h\"\n#include \"..\/cPWP\/calcCOVARchunks.h\"\n#include \"catch.hpp\"\n#include <string>\n#include <iostream>\n#include <fstream>\n\n\n\/*\nTEST_CASE( \"Simulated reads are generated\", \"[generateReads]\" ) {\n \/\/ Make sure that the read simulation finishes\n REQUIRE( generateReadsAndMap(1, 0.01, \"0.0\", \"300\", \"50\", \"1000000\", \"100\", \"1234\", \"scaffold_0.fasta\") == 0);\n}\n *\/\n\nTEST_CASE( \"Generate reference genome for simulation tests\", \"[generateReference]\") {\n REQUIRE( createReferenceGenome(1000000, 0.42668722, \"simulatedReferenceGenome.fasta\") == 0 );\n \/\/createReferenceGenome (int totalBases, double gcContent, std::string genomeOutFile) \n}\n\nTEST_CASE ( \"Mutate a reference genome\", \"[mutateRefGenome]\") {\n REQUIRE( createMutatedGenome(\"simulatedReferenceGenome.fasta\", \"simulatedReferenceGenomeMutated.fasta\", 0.01) == 0);\n \/\/createMutatedGenome (std::string reference, std::string mutatedReferenceFile, float percDivergent) \n}\n\n\n\nTEST_CASE( \"Generate sequence reads 5\", \"[perfectReads]\") {\n REQUIRE( generatePerfectReads (\"simulatedReferenceGenome.fasta\", 5, 100, 300, \"normalRef5\") == 0);\n \/\/generatePerfectReads (std::string reference, unsigned int stagger, unsigned int readLengths, unsigned int fragmentLengths, std::string readPrefix);\n}\n\n\n\/\/ We need to create a set of reads that are half as dense as the first set, because when we concatenate the heterozygous chromosome reads to them we don't\n\/\/ want the coverage to be twice as high.\nTEST_CASE( \"Generate sequence reads 10\", \"[perfectReads]\") {\n REQUIRE( generatePerfectReads (\"simulatedReferenceGenome.fasta\", 10, 100, 300, \"normalRef10\") == 0);\n \/\/generatePerfectReads (std::string reference, unsigned int stagger, unsigned int readLengths, unsigned int fragmentLengths, std::string readPrefix);\n}\n\n\n\/\/ Map the reads for the homozygous individual\nTEST_CASE( \" Mapping first set of reads\", \"[mapReads]\") {\n REQUIRE( mapReads(\"simulatedReferenceGenome.fasta\", \"normalRef5_R1.fastq\", \"normalRef5_R2.fastq\", \"normal.bam\", \"5\") == 0);\n \/\/mapReads (std::string reference, std::string R1file, std::string R2file, std::string outBam, std::string threads)\n}\n\n\n\/\/ Generate the reads from the mutated reference chromosome\nTEST_CASE( \"Generate sequence reads 2\", \"[perfectReads2]\") {\n REQUIRE( generatePerfectReads (\"simulatedReferenceGenomeMutated.fasta\", 10, 100, 300, \"mutatedRef\") == 0);\n \/\/generatePerfectReads (std::string reference, unsigned int stagger, unsigned int readLengths, unsigned int fragmentLengths, std::string readPrefix);\n}\n\n\n\/\/ Concatenate the het-reference reads to the homozygous reads reference for R1\nTEST_CASE( \"Create heterozygous R1\", \"[createHetR1]\") {\n REQUIRE( createHeterozygousGenome(\"normalRef10_R1.fastq\", \"mutatedRef_R1.fastq\", \"hetRef_R1.fastq\") == 0);\n \/\/createHeterozygousGenome(std::string firstFile, std::string secondFile, std::string outputGenome)\n}\n\n\/\/ Concatenate the het-reference reads to the homozygous reads reference for R2\nTEST_CASE( \"Create heterozygous R2\", \"[createHetR1]\") {\n REQUIRE( createHeterozygousGenome(\"normalRef10_R2.fastq\", \"mutatedRef_R2.fastq\", \"hetRef_R2.fastq\") == 0);\n \/\/createHeterozygousGenome(std::string firstFile, std::string secondFile, std::string outputGenome)\n}\n\n\/\/ Map the reads for the heterozygous individual\nTEST_CASE( \" Mapping het reads\", \"[mapReads2]\") {\n REQUIRE( mapReads(\"simulatedReferenceGenome.fasta\", \"hetRef_R1.fastq\", \"hetRef_R2.fastq\", \"het.bam\", \"5\") == 0);\n \/\/mapReads (std::string reference, std::string R1file, std::string R2file, std::string outBam, std::string threads)\n}\n\n\n\/\/ Use angsd to generate the read counts for the two individuals\nTEST_CASE( \"Run ANGSD on simulated reads\", \"[runANGSD]\" ) {\n REQUIRE( runANGSDforReadCounts(\"bamlist.txt\", \"angsdOut\", \"5\", \"angsdOutLog.txt\") == 0);\n \/\/runANGSDforReadCounts (std::string bamlist, std::string angsdPrefix, std::string nThreads, std::string angsdOutputLog)\n}\n\n\/\/ Convert read counts to binary\nTEST_CASE( \"Convert ANGSD read counts to unsigned chars for major and minor counts\", \"[convertCountsToBinary]\") {\n REQUIRE( convertANGSDcountsToBinary(\"angsdOut\", \"angsdOut.readCounts.binary\", 2, 250) == 0);\n \/\/convertANGSDcountsToBinary(std::string angsdPrefix, std::string binaryOutputFileName, int numIndividuals, int readDepthMax)\n}\n\n\/\/ Run the PWP calculation\nTEST_CASE( \"Calculate PWP from the binary representations of the ANGSD readcounts\", \"[calcPWP]\") {\n REQUIRE( calcPWPfromBinaryFile(\"angsdOut.readCounts.binary\", 999990, 2, \"testingOut.pwp\", 1000, 5) == 0);\n \/\/int calcPWPfromBinaryFile (std::string binaryFile, unsigned long long int numLoci, const int numIndividuals, std::string outFile, int lociChunkSize, int numThreads=30);\n}\n\n\n\n\n\n\n\n\/* \n Covariance unit tests are below. They require different reference genomes to be used. In the example above, the homozygous reference genome\n has no variance in the major allele frequencies (they're always 1). The genomes created by this example have \n \n \n \n \n *\/\n\n\nTEST_CASE( \"Generate reference genome for the covariance tests\", \"[generateReferenceCovar]\") {\n REQUIRE( createReferenceGenome(10000000, 0.42668722, \"simulatedReferenceGenome10mil.fasta\") == 0 );\n \/\/createReferenceGenome (int totalBases, double gcContent, std::string genomeOutFile)\n}\n\n\nTEST_CASE ( \"Mutate a reference genome for the covariance test\", \"[mutateRefGenomeCovar]\") {\n REQUIRE( createMutatedGenomesForCovar(\"simulatedReferenceGenome10mil.fasta\", \"simulatedReferenceGenomeMutatedRef1.fasta\", \"simulatedReferenceGenomeMutatedRef2.fasta\", 0.01) == 0);\n \/\/createMutatedGenomesForCovar (std::string reference, std::string mutatedReferenceFile1, std::string mutatedReferenceFile2, float percDivergent)\n}\n\n\nTEST_CASE( \"Generate nonmutated chromosome covariance sequence reads for ind1 and ind2\", \"[perfectReadsCovarNoMut]\") {\n REQUIRE( generatePerfectReads (\"simulatedReferenceGenome10mil.fasta\", 10, 100, 300, \"covarRef\") == 0);\n \/\/generatePerfectReads (std::string reference, unsigned int stagger, unsigned int readLengths, unsigned int fragmentLengths, std::string readPrefix);\n}\n\n\n\nTEST_CASE( \"Generate mutated chromosome covariance sequence reads for ind1\", \"[perfectReadsCovarInd1]\") {\n REQUIRE( generatePerfectReads (\"simulatedReferenceGenomeMutatedRef1.fasta\", 10, 100, 300, \"covarMutRef1\") == 0);\n \/\/generatePerfectReads (std::string reference, unsigned int stagger, unsigned int readLengths, unsigned int fragmentLengths, std::string readPrefix);\n}\n\n\nTEST_CASE( \"Generate mutated chromosome covariance sequence reads for ind2\", \"[perfectReadsCovarInd2]\") {\n REQUIRE( generatePerfectReads (\"simulatedReferenceGenomeMutatedRef2.fasta\", 10, 100, 300, \"covarMutRef2\") == 0);\n \/\/generatePerfectReads (std::string reference, unsigned int stagger, unsigned int readLengths, unsigned int fragmentLengths, std::string readPrefix);\n}\n\n\n\n\/\/ Combine the mutated and non-mutated chromosome reads for each individual\n\/\/ Concatenate the het-reference reads to the homozygous reads reference for R1\nTEST_CASE( \"Create heterozygous R1covar1\", \"[createHetR1covar1]\") {\n REQUIRE( createHeterozygousGenome(\"covarRef_R1.fastq\", \"covarMutRef1_R1.fastq\", \"covarRef1_R1.fastq\") == 0);\n \/\/createHeterozygousGenome(std::string firstFile, std::string secondFile, std::string outputGenome)\n}\n\n\/\/ Concatenate the het-reference reads to the homozygous reads reference for R2\nTEST_CASE( \"Create heterozygous R2covar1\", \"[createHetR2covar1]\") {\n REQUIRE( createHeterozygousGenome(\"covarRef_R2.fastq\", \"covarMutRef1_R2.fastq\", \"covarRef1_R2.fastq\") == 0);\n \/\/createHeterozygousGenome(std::string firstFile, std::string secondFile, std::string outputGenome)\n}\n\n\/\/ Concatenate the het-reference reads to the homozygous reads reference for R1\nTEST_CASE( \"Create heterozygous R1covar2\", \"[createHetR1covar2]\") {\n REQUIRE( createHeterozygousGenome(\"covarRef_R1.fastq\", \"covarMutRef2_R1.fastq\", \"covarRef2_R1.fastq\") == 0);\n \/\/createHeterozygousGenome(std::string firstFile, std::string secondFile, std::string outputGenome)\n}\n\n\/\/ Concatenate the het-reference reads to the homozygous reads reference for R2\nTEST_CASE( \"Create heterozygous R2covar2\", \"[createHetR2covar2]\") {\n REQUIRE( createHeterozygousGenome(\"covarRef_R2.fastq\", \"covarMutRef2_R2.fastq\", \"covarRef2_R2.fastq\") == 0);\n \/\/createHeterozygousGenome(std::string firstFile, std::string secondFile, std::string outputGenome)\n}\n\n\n\/\/ Map the reads for individual 1\nTEST_CASE( \" Mapping reads for covariance ind1\", \"[mapReadsCovar1]\") {\n REQUIRE( mapReads(\"simulatedReferenceGenome10mil.fasta\", \"covarRef1_R1.fastq\", \"covarRef1_R2.fastq\", \"covarInd1.bam\", \"5\") == 0);\n \/\/mapReads (std::string reference, std::string R1file, std::string R2file, std::string outBam, std::string threads)\n}\n\n\n\/\/ Map the reads for individual 2\nTEST_CASE( \" Mapping reads for covariance ind2\", \"[mapReadsCovar2]\") {\n REQUIRE( mapReads(\"simulatedReferenceGenome10mil.fasta\", \"covarRef2_R1.fastq\", \"covarRef2_R2.fastq\", \"covarInd2.bam\", \"5\") == 0);\n \/\/mapReads (std::string reference, std::string R1file, std::string R2file, std::string outBam, std::string threads)\n}\n\n\n\n\/\/ Use angsd to generate the read counts for the two individuals\nTEST_CASE( \"Run ANGSD on simulated reads\", \"[runANGSD]\" ) {\n REQUIRE( runANGSDforReadCounts(\"covarBamlist.txt\", \"covarAngsdOut\", \"5\", \"covarAngsdOutLog.txt\") == 0);\n \/\/runANGSDforReadCounts (std::string bamlist, std::string angsdPrefix, std::string nThreads, std::string angsdOutputLog)\n}\n\n\/\/ Convert read counts to binary\nTEST_CASE( \"Convert ANGSD read counts to unsigned chars for major and minor counts\", \"[convertCountsToBinary]\") {\n REQUIRE( convertANGSDcountsToBinary(\"covarAngsdOut\", \"covarAngsdOut.readCounts.binary\", 2, 250) == 0);\n \/\/convertANGSDcountsToBinary(std::string angsdPrefix, std::string binaryOutputFileName, int numIndividuals, int readDepthMax)\n}\n\n\nTEST_CASE( \"Calculate covariances from the same representations of the ANGSD readcounts\", \"[calcCovar]\") {\n REQUIRE( calcCOVARfromBinaryFile(\"covarAngsdOut.readCounts.binary\", 9999990, 2, \"testingOut.covar\", 1000, 5)== 0);\n \/\/calcCOVARfromBinaryFile (std::string binaryFile, long long int numLoci, const int numIndividuals, std::string outFile, int lociChunkSize, const int numThreads)\n}\n\n\n<|endoftext|>"} {"text":"<commit_before>#include \"Graphics\/TextureSet.h\"\n\n#include \"TextureSets.h\"\n#include \"vulkan\/EngineInternal.h\"\n\n#include \"DataCompression\/LosslessCompression.h\"\n#include \"core\/Log.h\"\n\n#include \"tsl\/robin_map.h\"\n\n#include <bitset>\n#include <unordered_map>\n\nusing namespace std;\nusing namespace CR;\nusing namespace CR::Graphics;\n\nnamespace {\n\tconstexpr uint16_t c_maxTextureSets{8};\n\tconstexpr uint16_t c_idSetShift{10};\n\tconstexpr uint16_t c_maxTexturesPerSet{1024};\n\tstatic_assert((1 << c_idSetShift) == c_maxTexturesPerSet);\n\tstatic_assert(c_maxTextureSets * c_maxTexturesPerSet < numeric_limits<uint16_t>::max(),\n\t \"textures use a 16 bit id, some bits hold the texture set, some hold the index inside the set\");\n\n\t\/\/ Must match whats in TextureProcessor, assuming dont need this every frame.\n#pragma pack(4)\n\tstruct Header {\n\t\tuint16_t Width{0};\n\t\tuint16_t Height{0};\n\t};\n#pragma pack()\n\n\tstruct TextureSetImpl {\n\t\tvector<string> m_names;\n\t\tvector<Header> m_headers;\n\t\tvector<vk::Image> m_images;\n\t\tvector<vk::ImageView> m_views;\n\t\tvk::DeviceMemory m_ImageMemory;\n\t};\n\n\tbitset<c_maxTextureSets> g_used;\n\tTextureSetImpl g_textureSets[c_maxTextureSets];\n\ttsl::robin_map<string, uint16_t> g_lookup;\n\n\tuint16_t CalcID(uint16_t a_set, uint16_t a_slot) {\n\t\tCore::Log::Assert(a_set < c_maxTextureSets, \"invalid set\");\n\t\tCore::Log::Assert(a_slot < c_maxTexturesPerSet, \"invalid slot\");\n\t\treturn (a_set << c_idSetShift) | a_slot;\n\t}\n\tuint16_t GetSet(uint16_t a_id) { return a_id >> c_idSetShift; }\n} \/\/ namespace\n\nTextureSet ::~TextureSet() {\n\tif(m_id != c_unused) {\n\t\tuint16_t set = GetSet(m_id);\n\t\t\/\/ for(auto& view : g_textureSets[set].m_views) { GetDevice().destroyImageView(view); }\n\t\tfor(auto& img : g_textureSets[set].m_images) { GetDevice().destroyImage(img); }\n\t\tg_used[m_id] = false;\n\t}\n}\n\nTextureSet::TextureSet(TextureSet&& a_other) {\n\t*this = move(a_other);\n}\n\nTextureSet& TextureSet::operator=(TextureSet&& a_other) {\n\tm_id = a_other.m_id;\n\n\ta_other.m_id = c_unused;\n\treturn *this;\n}\n\nTextureSet Graphics::CreateTextureSet(const Core::Span<TextureCreateInfo> a_textures) {\n\tif(a_textures.size() > c_maxTexturesPerSet) {\n\t\tCore::Log::Fail(\"Texture Sets have a maximum size of {}. {} were requested\", c_maxTexturesPerSet,\n\t\t a_textures.size());\n\t}\n\tuint16_t set = c_maxTextureSets;\n\tfor(uint16_t i = 0; i < c_maxTextureSets; ++i) {\n\t\tif(!g_used[i]) {\n\t\t\tset = i;\n\t\t\tbreak;\n\t\t}\n\t}\n\tif(set == c_maxTextureSets) { Core::Log::Fail(\"Ran out of available texture sets\"); }\n\n\tg_used[set] = true;\n\n\tg_textureSets[set].m_names.reserve(a_textures.size());\n\tg_textureSets[set].m_headers.reserve(a_textures.size());\n\tfor(uint32_t slot = 0; slot < a_textures.size(); ++slot) {\n\t\tvector<byte> textureData = DataCompression::Decompress(a_textures[slot].TextureData.data(),\n\t\t (uint32_t)(a_textures[slot].TextureData.size()));\n\t\tif(textureData.size() < sizeof(Header)) { Core::Log::Fail(\"corrupt crtex file {}\", a_textures[slot].Name); }\n\t\tHeader& header = g_textureSets[set].m_headers.emplace_back();\n\t\tmemcpy(&header, textureData.data(), sizeof(Header));\n\n\t\tg_textureSets[set].m_names.push_back(a_textures[slot].Name);\n\t\tg_lookup.emplace(a_textures[slot].Name, CalcID(set, slot));\n\n\t\tvk::ImageCreateInfo createInfo;\n\t\tcreateInfo.extent.width = header.Width;\n\t\tcreateInfo.extent.height = header.Height;\n\t\tcreateInfo.extent.depth = 1;\n\t\tcreateInfo.arrayLayers = 1;\n\t\tcreateInfo.mipLevels = 1;\n\t\tcreateInfo.tiling = vk::ImageTiling::eOptimal;\n\t\tcreateInfo.sharingMode = vk::SharingMode::eExclusive;\n\t\tcreateInfo.usage = vk::ImageUsageFlagBits::eSampled | vk::ImageUsageFlagBits::eTransferDst;\n\t\tcreateInfo.initialLayout = vk::ImageLayout::eUndefined;\n\t\tcreateInfo.imageType = vk::ImageType::e2D;\n\t\tcreateInfo.flags = vk::ImageCreateFlags{0};\n\t\tcreateInfo.format = vk::Format::eBc7SrgbBlock;\n\n\t\tg_textureSets[set].m_images.push_back(GetDevice().createImage(createInfo));\n\n\t\t\/*vk::ImageViewCreateInfo viewInfo;\n\t\tviewInfo.image = g_textureSets[set].m_images.back();\n\t\tviewInfo.viewType = vk::ImageViewType::e2D;\n\t\tviewInfo.format = createInfo.format;\n\t\tviewInfo.subresourceRange.aspectMask = vk::ImageAspectFlagBits::eColor;\n\t\tviewInfo.subresourceRange.baseMipLevel = 0;\n\t\tviewInfo.subresourceRange.levelCount = 1;\n\t\tviewInfo.subresourceRange.baseArrayLayer = 0;\n\t\tviewInfo.subresourceRange.layerCount = 1;\n\n\t\tg_textureSets[set].m_views.push_back(GetDevice().createImageView(viewInfo));*\/\n\t}\n\n\tTextureSet result{set};\n\treturn result;\n}\n\nvoid TexturePool::Init() {\n\tg_used.reset();\n}\n\nvoid TexturePool::Shutdown() {}\n<commit_msg>allocate memory for the textures. I need to move some of this to the background thread. and as it is, this is going to use a ton of memory. Going to have to synchronize access to the device to fix though, which is a large refactoring.<commit_after>#include \"Graphics\/TextureSet.h\"\n\n#include \"TextureSets.h\"\n#include \"vulkan\/EngineInternal.h\"\n\n#include \"DataCompression\/LosslessCompression.h\"\n#include \"core\/Log.h\"\n\n#include \"tsl\/robin_map.h\"\n\n#include <bitset>\n#include <unordered_map>\n\nusing namespace std;\nusing namespace CR;\nusing namespace CR::Graphics;\n\nnamespace {\n\tconstexpr uint16_t c_maxTextureSets{8};\n\tconstexpr uint16_t c_idSetShift{10};\n\tconstexpr uint16_t c_maxTexturesPerSet{1024};\n\tstatic_assert((1 << c_idSetShift) == c_maxTexturesPerSet);\n\tstatic_assert(c_maxTextureSets * c_maxTexturesPerSet < numeric_limits<uint16_t>::max(),\n\t \"textures use a 16 bit id, some bits hold the texture set, some hold the index inside the set\");\n\n\t\/\/ Must match whats in TextureProcessor, assuming dont need this every frame.\n#pragma pack(4)\n\tstruct Header {\n\t\tuint16_t Width{0};\n\t\tuint16_t Height{0};\n\t};\n#pragma pack()\n\n\tstruct TextureSetImpl {\n\t\tvector<string> m_names;\n\t\tvector<Header> m_headers;\n\t\tvector<vk::Image> m_images;\n\t\tvector<vk::ImageView> m_views;\n\t\tvk::DeviceMemory m_imageMemory;\n\n\t\tvector<vk::Buffer> m_stagingBuffer;\n\t\tvk::DeviceMemory m_stagingMemory;\n\t};\n\n\tbitset<c_maxTextureSets> g_used;\n\tTextureSetImpl g_textureSets[c_maxTextureSets];\n\ttsl::robin_map<string, uint16_t> g_lookup;\n\n\tuint16_t CalcID(uint16_t a_set, uint16_t a_slot) {\n\t\tCore::Log::Assert(a_set < c_maxTextureSets, \"invalid set\");\n\t\tCore::Log::Assert(a_slot < c_maxTexturesPerSet, \"invalid slot\");\n\t\treturn (a_set << c_idSetShift) | a_slot;\n\t}\n\tuint16_t GetSet(uint16_t a_id) { return a_id >> c_idSetShift; }\n\tuint16_t GetSlot(uint16_t a_id) { return a_id & (c_maxTexturesPerSet - 1); }\n} \/\/ namespace\n\nTextureSet ::~TextureSet() {\n\tif(m_id != c_unused) {\n\t\tuint16_t set = GetSet(m_id);\n\t\tfor(auto& view : g_textureSets[set].m_views) { GetDevice().destroyImageView(view); }\n\t\tfor(auto& img : g_textureSets[set].m_images) { GetDevice().destroyImage(img); }\n\t\tfor(auto& buf : g_textureSets[set].m_stagingBuffer) {\n\t\t\tif(buf) { GetDevice().destroyBuffer(buf); }\n\t\t}\n\t\tGetDevice().freeMemory(g_textureSets[set].m_imageMemory);\n\t\tif(g_textureSets[set].m_stagingMemory) { GetDevice().freeMemory(g_textureSets[set].m_stagingMemory); }\n\t\tg_used[m_id] = false;\n\t}\n}\n\nTextureSet::TextureSet(TextureSet&& a_other) {\n\t*this = move(a_other);\n}\n\nTextureSet& TextureSet::operator=(TextureSet&& a_other) {\n\tm_id = a_other.m_id;\n\n\ta_other.m_id = c_unused;\n\treturn *this;\n}\n\nTextureSet Graphics::CreateTextureSet(const Core::Span<TextureCreateInfo> a_textures) {\n\tif(a_textures.size() > c_maxTexturesPerSet) {\n\t\tCore::Log::Fail(\"Texture Sets have a maximum size of {}. {} were requested\", c_maxTexturesPerSet,\n\t\t a_textures.size());\n\t}\n\tuint16_t set = c_maxTextureSets;\n\tfor(uint16_t i = 0; i < c_maxTextureSets; ++i) {\n\t\tif(!g_used[i]) {\n\t\t\tset = i;\n\t\t\tbreak;\n\t\t}\n\t}\n\tif(set == c_maxTextureSets) { Core::Log::Fail(\"Ran out of available texture sets\"); }\n\n\tg_used[set] = true;\n\n\tvector<uint32_t> memOffsets;\n\tmemOffsets.reserve(a_textures.size());\n\tuint32_t memOffset{0};\n\n\tvector<uint32_t> stagOffsets;\n\tstagOffsets.reserve(a_textures.size());\n\tuint32_t stagOffset{0};\n\n\tg_textureSets[set].m_names.reserve(a_textures.size());\n\tg_textureSets[set].m_headers.reserve(a_textures.size());\n\tfor(uint32_t slot = 0; slot < a_textures.size(); ++slot) {\n\t\tvector<byte> textureData = DataCompression::Decompress(a_textures[slot].TextureData.data(),\n\t\t (uint32_t)(a_textures[slot].TextureData.size()));\n\t\tif(textureData.size() < sizeof(Header)) { Core::Log::Fail(\"corrupt crtex file {}\", a_textures[slot].Name); }\n\t\tHeader& header = g_textureSets[set].m_headers.emplace_back();\n\t\tmemcpy(&header, textureData.data(), sizeof(Header));\n\n\t\tg_textureSets[set].m_names.push_back(a_textures[slot].Name);\n\t\tg_lookup.emplace(a_textures[slot].Name, CalcID(set, slot));\n\n\t\tvk::ImageCreateInfo createInfo;\n\t\tcreateInfo.extent.width = header.Width;\n\t\tcreateInfo.extent.height = header.Height;\n\t\tcreateInfo.extent.depth = 1;\n\t\tcreateInfo.arrayLayers = 1;\n\t\tcreateInfo.mipLevels = 1;\n\t\tcreateInfo.tiling = vk::ImageTiling::eOptimal;\n\t\tcreateInfo.sharingMode = vk::SharingMode::eExclusive;\n\t\tcreateInfo.usage = vk::ImageUsageFlagBits::eSampled | vk::ImageUsageFlagBits::eTransferDst;\n\t\tcreateInfo.initialLayout = vk::ImageLayout::eUndefined;\n\t\tcreateInfo.imageType = vk::ImageType::e2D;\n\t\tcreateInfo.flags = vk::ImageCreateFlags{0};\n\t\tcreateInfo.format = vk::Format::eBc7SrgbBlock;\n\n\t\tg_textureSets[set].m_images.push_back(GetDevice().createImage(createInfo));\n\n\t\tauto imageRequirements = GetDevice().getImageMemoryRequirements(g_textureSets[set].m_images.back());\n\t\tmemOffset = (uint32_t)((memOffset + (imageRequirements.alignment - 1)) & ~(imageRequirements.alignment - 1));\n\t\tmemOffsets.push_back(memOffset);\n\t\tmemOffset += (uint32_t)imageRequirements.size;\n\n\t\tvk::BufferCreateInfo stagInfo;\n\t\tstagInfo.flags = vk::BufferCreateFlags{};\n\t\tstagInfo.sharingMode = vk::SharingMode::eExclusive;\n\t\tstagInfo.size = a_textures[slot].TextureData.size() - sizeof(Header);\n\t\tstagInfo.usage = vk::BufferUsageFlagBits::eTransferSrc;\n\n\t\tg_textureSets[set].m_stagingBuffer.push_back(GetDevice().createBuffer(stagInfo));\n\t\tauto bufferRequirements = GetDevice().getBufferMemoryRequirements(g_textureSets[set].m_stagingBuffer.back());\n\t\tstagOffset =\n\t\t (uint32_t)((stagOffset + (bufferRequirements.alignment - 1)) & ~(bufferRequirements.alignment - 1));\n\t\tstagOffsets.push_back(stagOffset);\n\t\tstagOffset += (uint32_t)bufferRequirements.size;\n\t}\n\n\tvk::MemoryAllocateInfo allocInfo;\n\tallocInfo.memoryTypeIndex = GetDeviceMemoryIndex();\n\tallocInfo.allocationSize = memOffset;\n\tg_textureSets[set].m_imageMemory = GetDevice().allocateMemory(allocInfo);\n\n\tallocInfo.memoryTypeIndex = GetHostMemoryIndex();\n\tallocInfo.allocationSize = stagOffset;\n\tg_textureSets[set].m_stagingMemory = GetDevice().allocateMemory(allocInfo);\n\n\tfor(uint32_t slot = 0; slot < a_textures.size(); ++slot) {\n\t\tGetDevice().bindImageMemory(g_textureSets[set].m_images[slot], g_textureSets[set].m_imageMemory,\n\t\t memOffsets[slot]);\n\t\tvk::ImageViewCreateInfo viewInfo;\n\t\tviewInfo.image = g_textureSets[set].m_images[slot];\n\t\tviewInfo.viewType = vk::ImageViewType::e2D;\n\t\tviewInfo.format = vk::Format::eBc7SrgbBlock;\n\t\tviewInfo.subresourceRange.aspectMask = vk::ImageAspectFlagBits::eColor;\n\t\tviewInfo.subresourceRange.baseMipLevel = 0;\n\t\tviewInfo.subresourceRange.levelCount = 1;\n\t\tviewInfo.subresourceRange.baseArrayLayer = 0;\n\t\tviewInfo.subresourceRange.layerCount = 1;\n\n\t\tg_textureSets[set].m_views.push_back(GetDevice().createImageView(viewInfo));\n\n\t\tGetDevice().bindBufferMemory(g_textureSets[set].m_stagingBuffer[slot], g_textureSets[set].m_stagingMemory,\n\t\t stagOffsets[slot]);\n\t}\n\n\tTextureSet result{set};\n\treturn result;\n}\n\nvoid TexturePool::Init() {\n\tg_used.reset();\n}\n\nvoid TexturePool::Shutdown() {}\n<|endoftext|>"} {"text":"<commit_before><commit_msg>Update VideoDevice.cpp<commit_after>#include \"VideoDevice.hpp\"\r\n#include <opencv2\/opencv.hpp>\r\nusing namespace cv;\r\n\r\nVideoDevice::VideoDevice(){\r\n \/\/does absolutely nothing\r\n}\r\n\r\nvoid VideoDevice::startCapture(int id){\r\n camera = VideoCapture(id);\r\n}\r\n\r\nMat VideoDevice:: getImage(){\r\n takeImage();\r\n return image;\r\n}\r\n\r\nvoid VideoDevice::takeImage(){\r\n camera >> image;\r\n}\r\n<|endoftext|>"} {"text":"<commit_before>#include <stdio.h>\n#include <stdlib.h>\n#include <string>\n#include <iostream>\n\n\/\/ git.cpp - source file for functions related to git tree parsing and pulling\nstd::string gitLogCommand = \"git log \"\n \"--pretty=format:user:%aN%n%ct \"\n \"--reverse --raw --encoding=UTF-8 \"\n \"--no-renames\";\n \n\nint getCustomGitLog(std::string directory,std::string outfile)\n{\n\tprintf(\"\\nmaking an outfile %s \\n\",outfile.c_str());\n\tint commandReturnValue = 0;\n\tstd::string gitLogWithOutput = gitLogCommand + \" > \" + outfile;\n\tcommandReturnValue = system(gitLogCommand.c_str());\n\treturn commandReturnValue;\n}\n\n<commit_msg>updated function call<commit_after>#include <stdio.h>\n#include <stdlib.h>\n#include <string>\n#include <iostream>\n\n\/\/ git.cpp - source file for functions related to git tree parsing and pulling\nstd::string gitLogCommand = \"git log --pretty=format:user:%aN%n%ct --reverse --raw --encoding=UTF-8 --no-renames\";\n \n\nint getCustomGitLog(std::string directory,std::string outfile)\n{\n\tprintf(\"\\nmaking an outfile %s \\n\",outfile.c_str());\n\tint commandReturnValue = 0;\n\tstd::string gitLogWithOutput = gitLogCommand + \" > \" + outfile;\n printf(\"\\n%s\\n\",gitLogWithOutput.c_str());\n\tcommandReturnValue = system(gitLogWithOutput.c_str());\n\treturn commandReturnValue;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/**\n ** \\file parser\/metavar-map.hxx\n ** \\brief Implementation of parse::MetavarMap.\n *\/\n\n#ifndef PARSER_METAVAR_MAP_HXX\n# define PARSER_METAVAR_MAP_HXX\n\n# include <sstream>\n# include <parser\/metavar-map.hh>\n\nnamespace parser\n{\n\n template <typename Data>\n MetavarMap<Data>::MetavarMap (const std::string& name)\n : name_ (name), map_ ()\n {\n }\n\n template <typename Data>\n MetavarMap<Data>::~MetavarMap ()\n {\n \/\/ All the values must have been used.\n passert (map_, empty_ ());\n }\n\n template <typename Data>\n std::ostream&\n MetavarMap<Data>::dump (std::ostream& o) const\n {\n return o\n << name_ << \" map:\"\n << libport::incendl << map_ << libport::decendl;\n }\n\n template <typename Data>\n std::string\n MetavarMap<Data>::append_ (unsigned& count, Data data)\n {\n map_[count] = data;\n std::string s = \"_\" + name_ + \" (\" +\n boost::lexical_cast<std::string> (count++) + \")\";\n return s;\n }\n\n template <typename Data>\n Data\n MetavarMap<Data>::take_ (unsigned key) throw (std::range_error)\n {\n return map_.take (key);\n }\n\n\n template <typename Data>\n void\n MetavarMap<Data>::insert_(MetavarMap<Data>& other)\n {\n return map_.insert(other.map_);\n }\n\n\n template <typename Data>\n bool\n MetavarMap<Data>::must_be_unique_ (Data) const\n {\n return true;\n }\n\n template <typename Data>\n bool\n MetavarMap<Data>::empty_ () const\n {\n return map_.empty();\n }\n\n\n \/*--------------------------.\n | Free standing functions. |\n `--------------------------*\/\n\n template <typename Data>\n std::ostream&\n operator<< (std::ostream& o, const MetavarMap<Data>& t)\n {\n return t.dump (o);\n }\n\n}\n\n#endif \/\/ !PARSER_METAVAR_MAP_HXX\n<commit_msg>Assert that enough parameters are given to parametric asts.<commit_after>\/**\n ** \\file parser\/metavar-map.hxx\n ** \\brief Implementation of parse::MetavarMap.\n *\/\n\n#ifndef PARSER_METAVAR_MAP_HXX\n# define PARSER_METAVAR_MAP_HXX\n\n# include <sstream>\n# include <parser\/metavar-map.hh>\n\nnamespace parser\n{\n\n template <typename Data>\n MetavarMap<Data>::MetavarMap (const std::string& name)\n : name_ (name), map_ ()\n {\n }\n\n template <typename Data>\n MetavarMap<Data>::~MetavarMap ()\n {\n \/\/ All the values must have been used.\n passert (map_, empty_ ());\n }\n\n template <typename Data>\n std::ostream&\n MetavarMap<Data>::dump (std::ostream& o) const\n {\n return o\n << name_ << \" map:\"\n << libport::incendl << map_ << libport::decendl;\n }\n\n template <typename Data>\n std::string\n MetavarMap<Data>::append_ (unsigned& count, Data data)\n {\n map_[count] = data;\n std::string s = \"_\" + name_ + \" (\" +\n boost::lexical_cast<std::string> (count++) + \")\";\n return s;\n }\n\n template <typename Data>\n Data\n MetavarMap<Data>::take_ (unsigned key) throw (std::range_error)\n {\n assert(libport::mhas(map_, key));\n return map_.take (key);\n }\n\n\n template <typename Data>\n void\n MetavarMap<Data>::insert_(MetavarMap<Data>& other)\n {\n return map_.insert(other.map_);\n }\n\n\n template <typename Data>\n bool\n MetavarMap<Data>::must_be_unique_ (Data) const\n {\n return true;\n }\n\n template <typename Data>\n bool\n MetavarMap<Data>::empty_ () const\n {\n return map_.empty();\n }\n\n\n \/*--------------------------.\n | Free standing functions. |\n `--------------------------*\/\n\n template <typename Data>\n std::ostream&\n operator<< (std::ostream& o, const MetavarMap<Data>& t)\n {\n return t.dump (o);\n }\n\n}\n\n#endif \/\/ !PARSER_METAVAR_MAP_HXX\n<|endoftext|>"} {"text":"<commit_before>\/* IBM_PROLOG_BEGIN_TAG *\/\n\/* This is an automatically generated prolog. *\/\n\/* *\/\n\/* $Source: src\/import\/chips\/p9\/procedures\/hwp\/nest\/p9_npu_scominit.C $ *\/\n\/* *\/\n\/* OpenPOWER HostBoot Project *\/\n\/* *\/\n\/* Contributors Listed Below - COPYRIGHT 2015,2019 *\/\n\/* [+] International Business Machines Corp. *\/\n\/* *\/\n\/* *\/\n\/* Licensed under the Apache License, Version 2.0 (the \"License\"); *\/\n\/* you may not use this file except in compliance with the License. *\/\n\/* You may obtain a copy of the License at *\/\n\/* *\/\n\/* http:\/\/www.apache.org\/licenses\/LICENSE-2.0 *\/\n\/* *\/\n\/* Unless required by applicable law or agreed to in writing, software *\/\n\/* distributed under the License is distributed on an \"AS IS\" BASIS, *\/\n\/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or *\/\n\/* implied. See the License for the specific language governing *\/\n\/* permissions and limitations under the License. *\/\n\/* *\/\n\/* IBM_PROLOG_END_TAG *\/\n\/\/\/\n\/\/\/ @file p9_npu_scominit.C\n\/\/\/ @brief Apply SCOM overrides for the NPU unit via an init file\n\/\/\/\n\/\/ *HWP HWP Owner: Joe McGill <jmcgill@us.ibm.com>\n\/\/ *HWP FW Owner: Thi Tran <thi@us.ibm.com>\n\/\/ *HWP Team: Nest\n\/\/ *HWP Level: 2\n\/\/ *HWP Consumed by: HB\n\n\/\/------------------------------------------------------------------------------\n\/\/ Includes\n\/\/------------------------------------------------------------------------------\n#include <p9_npu_scominit.H>\n#include <p9_npu_scom.H>\n#include <p9_nv_ref_clk_enable.H>\n\n\/\/\/\n\/\/\/ p9_npu_scominit HWP entry point (Defined in .H file)\n\/\/\/\nfapi2::ReturnCode p9_npu_scominit(const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>\n & i_target)\n{\n fapi2::ReturnCode l_rc;\n const fapi2::Target<fapi2::TARGET_TYPE_SYSTEM> FAPI_SYSTEM;\n auto l_nv_targets = i_target.getChildren<fapi2::TARGET_TYPE_NV>();\n\n FAPI_DBG(\"Entering ...\");\n\n if (l_nv_targets.size())\n {\n FAPI_DBG(\"Invoking p9.npu.scom.initfile...\");\n FAPI_EXEC_HWP(l_rc, p9_npu_scom, i_target, FAPI_SYSTEM);\n\n if (l_rc)\n {\n FAPI_ERR(\"Error from p9.npu.scom.initfile\");\n fapi2::current_err = l_rc;\n goto fapi_try_exit;\n }\n\n FAPI_DBG(\"Invoking p9_nv_ref_clk_enable...\");\n FAPI_EXEC_HWP(l_rc, p9_nv_ref_clk_enable, i_target);\n\n if (l_rc)\n {\n FAPI_ERR(\"Error from p9_nv_ref_clk_enable\");\n fapi2::current_err = l_rc;\n goto fapi_try_exit;\n }\n }\n else\n {\n FAPI_DBG(\"Skipping NPU initialization\");\n }\n\nfapi_try_exit:\n FAPI_DBG(\"Exiting ...\");\n return fapi2::current_err;\n}\n<commit_msg>NPU scan\/scom init updates<commit_after>\/* IBM_PROLOG_BEGIN_TAG *\/\n\/* This is an automatically generated prolog. *\/\n\/* *\/\n\/* $Source: src\/import\/chips\/p9\/procedures\/hwp\/nest\/p9_npu_scominit.C $ *\/\n\/* *\/\n\/* OpenPOWER HostBoot Project *\/\n\/* *\/\n\/* Contributors Listed Below - COPYRIGHT 2015,2019 *\/\n\/* [+] International Business Machines Corp. *\/\n\/* *\/\n\/* *\/\n\/* Licensed under the Apache License, Version 2.0 (the \"License\"); *\/\n\/* you may not use this file except in compliance with the License. *\/\n\/* You may obtain a copy of the License at *\/\n\/* *\/\n\/* http:\/\/www.apache.org\/licenses\/LICENSE-2.0 *\/\n\/* *\/\n\/* Unless required by applicable law or agreed to in writing, software *\/\n\/* distributed under the License is distributed on an \"AS IS\" BASIS, *\/\n\/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or *\/\n\/* implied. See the License for the specific language governing *\/\n\/* permissions and limitations under the License. *\/\n\/* *\/\n\/* IBM_PROLOG_END_TAG *\/\n\/\/\/\n\/\/\/ @file p9_npu_scominit.C\n\/\/\/ @brief Apply SCOM overrides for the NPU unit via an init file\n\/\/\/\n\/\/ *HWP HWP Owner: Joe McGill <jmcgill@us.ibm.com>\n\/\/ *HWP FW Owner: Thi Tran <thi@us.ibm.com>\n\/\/ *HWP Team: Nest\n\/\/ *HWP Level: 2\n\/\/ *HWP Consumed by: HB\n\n\/\/------------------------------------------------------------------------------\n\/\/ Includes\n\/\/------------------------------------------------------------------------------\n#include <p9_npu_scominit.H>\n#include <p9_npu_scom.H>\n#include <p9_nv_ref_clk_enable.H>\n#include <p9_misc_scom_addresses.H>\n#include <p9_misc_scom_addresses_fld.H>\n\n\n\/\/\/\n\/\/\/ p9_npu_scominit HWP entry point (Defined in .H file)\n\/\/\/\nfapi2::ReturnCode p9_npu_scominit(const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>\n & i_target)\n{\n fapi2::ReturnCode l_rc;\n const fapi2::Target<fapi2::TARGET_TYPE_SYSTEM> FAPI_SYSTEM;\n auto l_nv_targets = i_target.getChildren<fapi2::TARGET_TYPE_NV>();\n fapi2::buffer<uint64_t> l_atrmiss = 0;\n\n FAPI_DBG(\"Entering ...\");\n\n if (l_nv_targets.size())\n {\n FAPI_DBG(\"Invoking p9.npu.scom.initfile...\");\n FAPI_EXEC_HWP(l_rc, p9_npu_scom, i_target, FAPI_SYSTEM);\n\n if (l_rc)\n {\n FAPI_ERR(\"Error from p9.npu.scom.initfile\");\n fapi2::current_err = l_rc;\n goto fapi_try_exit;\n }\n\n l_atrmiss.setBit<PU_NPU_SM2_XTS_ATRMISS_FLAG_MAP>()\n .setBit<PU_NPU_SM2_XTS_ATRMISS_ENA>();\n FAPI_TRY(fapi2::putScomUnderMask(i_target, PU_NPU_SM2_XTS_ATRMISS, l_atrmiss, l_atrmiss),\n \"Error from putScomUnderMask (PU_NPU_SM2_XTS_ATRMISS)\");\n\n FAPI_DBG(\"Invoking p9_nv_ref_clk_enable...\");\n FAPI_EXEC_HWP(l_rc, p9_nv_ref_clk_enable, i_target);\n\n if (l_rc)\n {\n FAPI_ERR(\"Error from p9_nv_ref_clk_enable\");\n fapi2::current_err = l_rc;\n goto fapi_try_exit;\n }\n }\n else\n {\n FAPI_DBG(\"Skipping NPU initialization\");\n }\n\nfapi_try_exit:\n FAPI_DBG(\"Exiting ...\");\n return fapi2::current_err;\n}\n<|endoftext|>"} {"text":"<commit_before>\/* IBM_PROLOG_BEGIN_TAG *\/\n\/* This is an automatically generated prolog. *\/\n\/* *\/\n\/* $Source: src\/import\/chips\/p9\/procedures\/hwp\/perv\/p9_spr_name_map.C $ *\/\n\/* *\/\n\/* OpenPOWER HostBoot Project *\/\n\/* *\/\n\/* Contributors Listed Below - COPYRIGHT 2016,2019 *\/\n\/* [+] International Business Machines Corp. *\/\n\/* *\/\n\/* *\/\n\/* Licensed under the Apache License, Version 2.0 (the \"License\"); *\/\n\/* you may not use this file except in compliance with the License. *\/\n\/* You may obtain a copy of the License at *\/\n\/* *\/\n\/* http:\/\/www.apache.org\/licenses\/LICENSE-2.0 *\/\n\/* *\/\n\/* Unless required by applicable law or agreed to in writing, software *\/\n\/* distributed under the License is distributed on an \"AS IS\" BASIS, *\/\n\/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or *\/\n\/* implied. See the License for the specific language governing *\/\n\/* permissions and limitations under the License. *\/\n\/* *\/\n\/* IBM_PROLOG_END_TAG *\/\n\/\/-----------------------------------------------------------------------------------\n\/\/\/\n\/\/\/ @file p9_spr_name_map.C\n\/\/\/ @brief Utility to map SPR name to SPR number\n\/\/\/\n\/\/-----------------------------------------------------------------------------------\n\/\/ *HWP HWP Owner : Liu Yang Fan <shliuyf@cn.ibm.com>\n\/\/ *HWP HWP Backup Owner : Gou Peng Fei <shgoupf@cn.ibm.com>\n\/\/ *HWP FW Owner : Thi Tran <thi@us.ibm.com>\n\/\/ *HWP Team : Perv\n\/\/ *HWP Level : 2\n\/\/ *HWP Consumed by : None (Cronus test only)\n\/\/-----------------------------------------------------------------------------------\n\n\n\/\/-----------------------------------------------------------------------------------\n\/\/ Includes\n\/\/-----------------------------------------------------------------------------------\n#include <p9_spr_name_map.H>\n\n\/\/-----------------------------------------------------------------------------------\n\/\/ Function definitions\n\/\/-----------------------------------------------------------------------------------\nstd::map<std::string, SPRMapEntry> spr_map;\n\nfapi2::ReturnCode p9_spr_name_map_init()\n{\n FAPI_INF(\"Start SPR name map init\");\n\n FAPI_ASSERT(spr_map.empty(),\n fapi2::P9_SPR_NAME_MAP_INIT_ERR(),\n \"SPR name map is not empty when initialization\");\n\n {\n LIST_SPR_REG(DO_SPR_MAP)\n }\n\nfapi_try_exit:\n FAPI_INF(\"Exiting SPR name map init\");\n return fapi2::current_err;\n}\n\n\/\/-----------------------------------------------------------------------------------\nbool p9_spr_name_map_check_flag(unsigned char i_reg_flag, bool i_write)\n{\n unsigned char op_flag = ((unsigned char)i_write) + 0x1;\n\n return (bool)(i_reg_flag & op_flag);\n}\n\n\/\/-----------------------------------------------------------------------------------\nfapi2::ReturnCode p9_spr_name_map(const std::string i_name, const bool i_write, uint32_t& o_number)\n{\n FAPI_INF(\"Start SPR name map\");\n bool l_check_flag = false;\n\n if(spr_map.find(i_name) != spr_map.end())\n {\n l_check_flag = p9_spr_name_map_check_flag(spr_map[i_name].flag, i_write);\n\n FAPI_ASSERT(l_check_flag,\n fapi2::P9_SPR_INVALID_RW_MODE_ACCESS_ERR()\n .set_REGNAME(i_name)\n .set_RWFLAG(spr_map[i_name].flag),\n \"SPR RW mode check failed\");\n\n o_number = spr_map[i_name].number;\n }\n else\n {\n FAPI_ASSERT(false,\n fapi2::P9_SPR_INVALID_NAME_ACCESS_ERR()\n .set_REGNAME(i_name),\n \"SPR name is invalid\");\n }\n\nfapi_try_exit:\n FAPI_INF(\"Exiting SPR name map\");\n return fapi2::current_err;\n}\n<commit_msg>Update RAM procedures.<commit_after>\/* IBM_PROLOG_BEGIN_TAG *\/\n\/* This is an automatically generated prolog. *\/\n\/* *\/\n\/* $Source: src\/import\/chips\/p9\/procedures\/hwp\/perv\/p9_spr_name_map.C $ *\/\n\/* *\/\n\/* OpenPOWER HostBoot Project *\/\n\/* *\/\n\/* Contributors Listed Below - COPYRIGHT 2016,2019 *\/\n\/* [+] International Business Machines Corp. *\/\n\/* *\/\n\/* *\/\n\/* Licensed under the Apache License, Version 2.0 (the \"License\"); *\/\n\/* you may not use this file except in compliance with the License. *\/\n\/* You may obtain a copy of the License at *\/\n\/* *\/\n\/* http:\/\/www.apache.org\/licenses\/LICENSE-2.0 *\/\n\/* *\/\n\/* Unless required by applicable law or agreed to in writing, software *\/\n\/* distributed under the License is distributed on an \"AS IS\" BASIS, *\/\n\/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or *\/\n\/* implied. See the License for the specific language governing *\/\n\/* permissions and limitations under the License. *\/\n\/* *\/\n\/* IBM_PROLOG_END_TAG *\/\n\/\/-----------------------------------------------------------------------------------\n\/\/\/\n\/\/\/ @file p9_spr_name_map.C\n\/\/\/ @brief Utility to map SPR name to SPR number\n\/\/\/\n\/\/-----------------------------------------------------------------------------------\n\/\/ *HWP HWP Owner : Liu Yang Fan <shliuyf@cn.ibm.com>\n\/\/ *HWP HWP Backup Owner : Gou Peng Fei <shgoupf@cn.ibm.com>\n\/\/ *HWP FW Owner : Thi Tran <thi@us.ibm.com>\n\/\/ *HWP Team : Perv\n\/\/ *HWP Level : 2\n\/\/ *HWP Consumed by : None (Cronus test only)\n\/\/-----------------------------------------------------------------------------------\n\n\n\/\/-----------------------------------------------------------------------------------\n\/\/ Includes\n\/\/-----------------------------------------------------------------------------------\n#include <p9_spr_name_map.H>\n\nstd::map<std::string, SPRMapEntry> SPR_MAP;\nbool spr_map_initialized = false;\n\n\/\/-----------------------------------------------------------------------------------\n\/\/ Function definitions\n\/\/-----------------------------------------------------------------------------------\nbool p9_spr_name_map_init()\n{\n if (spr_map_initialized)\n {\n return true;\n }\n\n if (!SPR_MAP.empty())\n {\n return false;\n }\n\n LIST_SPR_REG(DO_SPR_MAP)\n spr_map_initialized = true;\n\n return true;\n}\n\n\/\/-----------------------------------------------------------------------------------\nbool p9_spr_name_map_check_flag(unsigned char i_reg_flag, bool i_write)\n{\n unsigned char op_flag = ((unsigned char)i_write) + 0x1;\n\n return (bool)(i_reg_flag & op_flag);\n}\n\n\/\/-----------------------------------------------------------------------------------\nbool p9_spr_name_map(const std::string i_name, const bool i_write, uint32_t& o_number)\n{\n bool l_check_flag = false;\n\n if(SPR_MAP.find(i_name) != SPR_MAP.end())\n {\n l_check_flag = p9_spr_name_map_check_flag(SPR_MAP[i_name].flag, i_write);\n\n if(l_check_flag)\n {\n o_number = SPR_MAP[i_name].number;\n }\n }\n\n return l_check_flag;\n}\n\n\/\/-----------------------------------------------------------------------------------\nbool p9_get_share_type(const std::string i_name, Enum_ShareType& o_share_type)\n{\n bool l_rc = false;\n\n if(SPR_MAP.find(i_name) != SPR_MAP.end())\n {\n o_share_type = SPR_MAP[i_name].share_type;\n l_rc = true;\n }\n\n return l_rc;\n}\n\n\/\/-----------------------------------------------------------------------------------\nbool p9_get_bit_length(const std::string i_name, uint8_t& o_bit_length)\n{\n bool l_rc = false;\n\n if(SPR_MAP.find(i_name) != SPR_MAP.end())\n {\n o_bit_length = SPR_MAP[i_name].bit_length;\n l_rc = true;\n }\n\n return l_rc;\n}\n\n\/\/-----------------------------------------------------------------------------------\nbool p9_get_spr_entry(const std::string i_name, SPRMapEntry& o_spr_entry)\n{\n bool l_rc = false;\n\n if(SPR_MAP.find(i_name) != SPR_MAP.end())\n {\n o_spr_entry = SPR_MAP[i_name];\n l_rc = true;\n }\n\n return l_rc;\n}\n<|endoftext|>"} {"text":"<commit_before>\/* IBM_PROLOG_BEGIN_TAG *\/\n\/* This is an automatically generated prolog. *\/\n\/* *\/\n\/* $Source: src\/import\/chips\/p9\/procedures\/hwp\/pm\/p9_quad_power_off.C $ *\/\n\/* *\/\n\/* OpenPOWER HostBoot Project *\/\n\/* *\/\n\/* Contributors Listed Below - COPYRIGHT 2015,2019 *\/\n\/* [+] International Business Machines Corp. *\/\n\/* *\/\n\/* *\/\n\/* Licensed under the Apache License, Version 2.0 (the \"License\"); *\/\n\/* you may not use this file except in compliance with the License. *\/\n\/* You may obtain a copy of the License at *\/\n\/* *\/\n\/* http:\/\/www.apache.org\/licenses\/LICENSE-2.0 *\/\n\/* *\/\n\/* Unless required by applicable law or agreed to in writing, software *\/\n\/* distributed under the License is distributed on an \"AS IS\" BASIS, *\/\n\/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or *\/\n\/* implied. See the License for the specific language governing *\/\n\/* permissions and limitations under the License. *\/\n\/* *\/\n\/* IBM_PROLOG_END_TAG *\/\n\/\/\/\n\/\/\/ @file p9_quad_power_off.C\n\/\/\/ @brief Power off the EQ -- including the functional cores associatated\n\/\/\/ with it.\n\/\/\/\n\/\/ *HWP HWP Owner: Amit Kumar <akumar3@us.ibm.com>\n\/\/ *HWP HWP Backup Owner: Greg Still <stillgs@us.ibm.com>\n\/\/ *HWP FW Owner: Sangeetha T S <sangeet2@in.ibm.com>\n\/\/ *HWP Team: PM\n\/\/ *HWP Level: 1\n\/\/ *HWP Consumed by: FSP:HS\n\/\/\/\n\/\/\/ @verbatim\n\/\/\/ High-level procedure flow:\n\/\/\/ - for each good EC associated with the targeted EQ, power it off\n\/\/\/ - power off the EQ\n\/\/\/ @endverbatim\n\/\/\/\n\/\/------------------------------------------------------------------------------\n\n\n\/\/ ----------------------------------------------------------------------\n\/\/ Includes\n\/\/ ----------------------------------------------------------------------\n\n#include <p9_quad_power_off.H>\n\n\/\/ ----------------------------------------------------------------------\n\/\/ Procedure Function\n\/\/ ----------------------------------------------------------------------\n\nfapi2::ReturnCode\np9_quad_power_off(\n const fapi2::Target<fapi2::TARGET_TYPE_EQ>& i_eq_target)\n{\n FAPI_INF(\"> p9_quad_power_off...\");\n\n\n\/\/fapi_try_exit:\n FAPI_INF(\"< p9_quad_power_off...\");\n return fapi2::current_err;\n}\n<commit_msg>L2 HWP p9_quad_power_off<commit_after>\/* IBM_PROLOG_BEGIN_TAG *\/\n\/* This is an automatically generated prolog. *\/\n\/* *\/\n\/* $Source: src\/import\/chips\/p9\/procedures\/hwp\/pm\/p9_quad_power_off.C $ *\/\n\/* *\/\n\/* OpenPOWER HostBoot Project *\/\n\/* *\/\n\/* Contributors Listed Below - COPYRIGHT 2015,2019 *\/\n\/* [+] International Business Machines Corp. *\/\n\/* *\/\n\/* *\/\n\/* Licensed under the Apache License, Version 2.0 (the \"License\"); *\/\n\/* you may not use this file except in compliance with the License. *\/\n\/* You may obtain a copy of the License at *\/\n\/* *\/\n\/* http:\/\/www.apache.org\/licenses\/LICENSE-2.0 *\/\n\/* *\/\n\/* Unless required by applicable law or agreed to in writing, software *\/\n\/* distributed under the License is distributed on an \"AS IS\" BASIS, *\/\n\/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or *\/\n\/* implied. See the License for the specific language governing *\/\n\/* permissions and limitations under the License. *\/\n\/* *\/\n\/* IBM_PROLOG_END_TAG *\/\n\/\/\/\n\/\/\/ @file p9_quad_power_off.C\n\/\/\/ @brief Power off the EQ including the functional cores associatated with it.\n\/\/\/\n\/\/----------------------------------------------------------------------------\n\/\/ *HWP HWP Owner : Greg Still <stillgs@us.ibm.com>\n\/\/ *HWP FW Owner : Sumit Kumar <sumit_kumar@in.ibm.com>\n\/\/ *HWP Team : PM\n\/\/ *HWP Level : 2\n\/\/ *HWP Consumed by : OCC:CME:FSP\n\/\/----------------------------------------------------------------------------\n\/\/\n\/\/ @verbatim\n\/\/ High-level procedure flow:\n\/\/ - For each good EC associated with the targeted EQ, power it off.\n\/\/ - Power off the EQ.\n\/\/ @endverbatim\n\/\/\n\/\/------------------------------------------------------------------------------\n\n\n\/\/ ----------------------------------------------------------------------\n\/\/ Includes\n\/\/ ----------------------------------------------------------------------\n#include <p9_quad_power_off.H>\n\n\/\/ ----------------------------------------------------------------------\n\/\/ Function definitions\n\/\/ ----------------------------------------------------------------------\n\n\/\/ Procedure p9_quad_power_off entry point, comments in header\nfapi2::ReturnCode p9_quad_power_off(\n const fapi2::Target<fapi2::TARGET_TYPE_EQ>& i_target)\n{\n fapi2::ReturnCode rc = fapi2::FAPI2_RC_SUCCESS;\n uint8_t l_unit_pos = 0;\n\n FAPI_INF(\"p9_quad_power_off: Entering...\");\n\n \/\/ Get chiplet position\n FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_CHIP_UNIT_POS, i_target, l_unit_pos));\n FAPI_INF(\"Quad power off chiplet no.%d\", l_unit_pos);\n\n \/\/ Call the procedure\n p9_pm_pfet_control_eq(i_target,\n PM_PFET_TYPE_C::BOTH,\n PM_PFET_TYPE_C::OFF);\n\n\n FAPI_INF(\"p9_quad_power_off: ...Exiting\");\n\nfapi_try_exit:\n return fapi2::current_err;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\nThe MIT License (MIT)\n\nCopyright (c) 2014-2017 Oleg Linkin <maledictusdemagog@gmail.com>\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n*\/\n\n#include \"getpocketapi.h\"\n#include <QJsonArray>\n#include <QJsonObject>\n#include <QJsonValue>\n#include <QNetworkAccessManager>\n#include <QNetworkRequest>\n#include <QSettings>\n#include <QStandardPaths>\n\n#include \"settings\/accountsettings.h\"\n\nnamespace LinksBag\n{\nGetPocketApi::GetPocketApi(QObject *parent)\n: QObject(parent)\n, m_ConsumerKey(\"36050-db8157de51cbb0c5f72edc33\")\n, m_NAM(new QNetworkAccessManager(this))\n{\n}\n\nnamespace\n{\n QNetworkRequest CreateRequest(const QString& path)\n {\n QNetworkRequest request(QUrl(QString(\"https:\/\/getpocket.com\/v3\") +\n path));\n request.setHeader(QNetworkRequest::ContentTypeHeader,\n \"application\/json; charset=UTF-8\");\n request.setRawHeader(\"X-Accept\", \"application\/json\");\n\n return request;\n }\n}\n\nvoid GetPocketApi::ObtainRequestToken()\n{\n QVariantMap params;\n params[\"consumer_key\"] = m_ConsumerKey;\n params[\"redirect_uri\"] = \"linksbag:\/\/authorizationFinished\";\n\n QJsonDocument doc(QJsonObject::fromVariantMap(params));\n\n QNetworkReply *reply = m_NAM->post(CreateRequest(\"\/oauth\/request\"),\n doc.toJson());\n\n connect(reply,\n &QNetworkReply::finished,\n this,\n &GetPocketApi::handleObtainRequestToken);\n}\n\nvoid GetPocketApi::RequestAccessToken()\n{\n QVariantMap params;\n params[\"consumer_key\"] = m_ConsumerKey;\n params[\"code\"] = m_RequestToken;\n\n QJsonDocument doc(QJsonObject::fromVariantMap(params));\n\n QNetworkReply *reply = m_NAM->post(CreateRequest(\"\/oauth\/authorize\"),\n doc.toJson());\n\n connect(reply,\n &QNetworkReply::finished,\n this,\n &GetPocketApi::handleRequestAccessToken);\n}\n\nvoid GetPocketApi::LoadBookmarks(int lastUpdate)\n{\n QVariantMap params;\n params[\"consumer_key\"] = m_ConsumerKey;\n params[\"access_token\"] = AccountSettings::Instance(this)->value(\"access_token\");\n params[\"state\"] = \"all\";\n params[\"sort\"] = \"oldest\";\n params[\"detailType\"] = \"complete\";\n params[\"since\"] = lastUpdate;\n\n QJsonDocument doc(QJsonObject::fromVariantMap(params));\n\n QNetworkReply *reply = m_NAM->post(CreateRequest(\"\/get\"),\n doc.toJson());\n\n connect(reply,\n &QNetworkReply::finished,\n this,\n &GetPocketApi::handleLoadBookmarks);\n}\n\nvoid GetPocketApi::RemoveBookmark(const QString& id)\n{\n QVariantMap params;\n params[\"consumer_key\"] = m_ConsumerKey;\n params[\"access_token\"] = AccountSettings::Instance(this)->value(\"access_token\");\n QVariantList actions;\n QVariantMap action;\n action[\"action\"] = \"delete\";\n action[\"item_id\"] = id;\n actions.append(action);\n params[\"actions\"] = actions;\n\n QJsonDocument doc(QJsonObject::fromVariantMap(params));\n\n QNetworkReply *reply = m_NAM->post(CreateRequest(\"\/send\"),\n doc.toJson());\n connect(reply,\n &QNetworkReply::finished,\n this,\n [=]()\n {\n handleRemoveBookmark(id);\n });\n}\n\nvoid GetPocketApi::MarkBookmarkAsFavorite(const QString& id, bool favorite)\n{\n QVariantMap params;\n params[\"consumer_key\"] = m_ConsumerKey;\n params[\"access_token\"] = AccountSettings::Instance(this)->value(\"access_token\");\n QVariantList actions;\n QVariantMap action;\n action[\"action\"] = favorite ? \"favorite\" : \"unfavorite\";\n action[\"item_id\"] = id;\n actions.append(action);\n params[\"actions\"] = actions;\n\n QJsonDocument doc(QJsonObject::fromVariantMap(params));\n\n QNetworkReply *reply = m_NAM->post(CreateRequest(\"\/send\"),\n doc.toJson());\n connect(reply,\n &QNetworkReply::finished,\n this,\n [this, id, favorite]()\n {\n handleMarkBookmarkAsFavorite(id, favorite);\n });\n}\n\nvoid GetPocketApi::MarkBookmarkAsRead(const QString& id, bool read)\n{\n QVariantMap params;\n params[\"consumer_key\"] = m_ConsumerKey;\n params[\"access_token\"] = AccountSettings::Instance(this)->value(\"access_token\");\n QVariantList actions;\n QVariantMap action;\n action[\"action\"] = read ? \"archive\" : \"readd\";\n action[\"item_id\"] = id;\n actions.append(action);\n params [\"actions\"] = actions;\n\n QJsonDocument doc(QJsonObject::fromVariantMap(params));\n\n QNetworkReply *reply = m_NAM->post(CreateRequest(\"\/send\"),\n doc.toJson());\n connect(reply,\n &QNetworkReply::finished,\n this,\n [this, id, read]()\n {\n handleMarkBookmarkAsRead(id, read);\n });\n}\n\nvoid GetPocketApi::UpdateTags(const QString& id, const QString& tags)\n{\n QVariantMap params;\n params[\"consumer_key\"] = m_ConsumerKey;\n params[\"access_token\"] = AccountSettings::Instance(this)->value(\"access_token\");\n QVariantList actions;\n QVariantMap action;\n action[\"action\"] = \"tags_replace\";\n action[\"item_id\"] = id;\n action[\"tags\"] = tags;\n actions.append(action);\n params [\"actions\"] = actions;\n\n QJsonDocument doc(QJsonObject::fromVariantMap(params));\n\n QNetworkReply *reply = m_NAM->post(CreateRequest(\"\/send\"),\n doc.toJson());\n connect(reply,\n &QNetworkReply::finished,\n this,\n [this, id, tags]()\n {\n handleTagsUpdated(id, tags);\n });\n}\n\nvoid GetPocketApi::ResetAccount()\n{\n m_RequestToken.clear();\n}\n\nQJsonDocument GetPocketApi::PreparsingReply(QObject *sender, bool& ok)\n{\n QJsonDocument doc;\n auto reply = qobject_cast<QNetworkReply*> (sender);\n if (!reply)\n {\n qDebug() << \"Invalid reply\";\n emit requestFinished(false, tr(\"General error\"));\n ok = false;\n return doc;\n }\n reply->deleteLater();\n\n if (reply->error() != QNetworkReply::NoError &&\n reply->error() != QNetworkReply::UnknownContentError &&\n reply->error() != QNetworkReply::UnknownNetworkError &&\n reply->error() != m_InvalidRequestError &&\n reply->error() != m_AuthError &&\n reply->error() != m_PermissionsRateError &&\n reply->error() != m_MaintenanceError)\n {\n qDebug() << Q_FUNC_INFO << \"There is network error: \"\n << reply->error() << reply->errorString();\n emit requestFinished(false, tr(\"Network error %1: %2\")\n .arg(reply->error())\n .arg(reply->errorString()));\n ok = false;\n return doc;\n }\n else if (reply->error() != QNetworkReply::NoError)\n {\n const int errorCode = reply->rawHeader(\"X-Error-Code\").toInt();\n const QString errorString = reply->rawHeader(\"X-Error\");\n qDebug() << Q_FUNC_INFO << \"There is getpocket error: \"\n << errorCode << errorString;\n emit error(errorString, errorCode, ETGetPocket);\n ok = false;\n return doc;\n }\n\n ok = false;\n QJsonParseError error;\n doc = QJsonDocument::fromJson(reply->readAll(), &error);\n if (error.error != QJsonParseError::NoError)\n {\n qDebug() << \"Unable to generate json from reply\";\n emit requestFinished(false, tr(\"Reply data is corrupted\"));\n return doc;\n }\n\n ok = true;\n return doc;\n}\n\nvoid GetPocketApi::handleObtainRequestToken()\n{\n bool ok = false;\n QJsonDocument doc = PreparsingReply(sender(), ok);\n if (!ok)\n {\n qDebug() << Q_FUNC_INFO << \"Failed preparsing reply phase\";\n return;\n }\n\n m_RequestToken = doc.object()[\"code\"].toString();\n emit requestTokenChanged(m_RequestToken);\n emit requestFinished(true);\n}\n\nvoid GetPocketApi::handleRequestAccessToken()\n{\n bool ok = false;\n QJsonDocument doc = PreparsingReply(sender(), ok);\n if (!ok)\n {\n qDebug() << Q_FUNC_INFO << \"Failed preparsing reply phase\";\n return;\n }\n\n const auto& accessToken = doc.object()[\"access_token\"].toString();\n const auto& userName = doc.object()[\"username\"].toString();\n emit logged(!accessToken.isEmpty() && !userName.isEmpty(),\n accessToken, userName);\n emit requestFinished(true);\n}\n\nvoid GetPocketApi::handleLoadBookmarks()\n{\n bool ok = false;\n QJsonDocument doc = PreparsingReply(sender(), ok);\n if (!ok)\n {\n qDebug() << Q_FUNC_INFO << \"Failed preparsing reply phase\";\n return;\n }\n\n QJsonObject rootObject = doc.object();\n const quint64 since = rootObject[\"since\"].toDouble();\n\n const auto& listObject = rootObject[\"list\"].toObject();\n Bookmarks_t bookmarks;\n for(const auto& key : listObject.keys())\n {\n QJsonObject bookmarkObject = listObject[key].toObject();\n\n Bookmark bm;\n bm.SetID(bookmarkObject[\"item_id\"].toString());\n bm.SetUrl(bookmarkObject[\"resolved_url\"].toString());\n QString title = bookmarkObject[\"resolved_title\"].toString();\n if(title.isEmpty())\n {\n title = bookmarkObject[\"given_title\"].toString();\n }\n if(title.isEmpty())\n {\n title = bm.GetUrl().toString();\n }\n bm.SetTitle(title);\n bm.SetDescription(bookmarkObject[\"excerpt\"].toString());\n bm.SetIsFavorite(bookmarkObject[\"favorite\"].toString() != \"0\" ||\n bookmarkObject[\"time_favorited\"].toString() != \"0\");\n bm.SetIsRead(bookmarkObject[\"read\"].toString() == \"1\" ||\n bookmarkObject[\"time_read\"].toString() != \"0\");\n bm.SetAddTime(QDateTime::fromTime_t(bookmarkObject[\"time_added\"]\n .toString().toLongLong()));\n bm.SetUpdateTime(QDateTime::fromTime_t(bookmarkObject[\"time_updated\"]\n .toString().toLongLong()));\n const auto& tagsObject = bookmarkObject[\"tags\"].toObject();\n bm.SetTags(tagsObject.keys());\n bm.SetImageUrl(bookmarkObject[\"image\"].toObject()[\"src\"].toString());\n bm.SetStatus(static_cast<Bookmark::Status>(bookmarkObject[\"status\"]\n .toString().toInt()));\n\n bookmarks << bm;\n }\n\n emit gotBookmarks(bookmarks, since);\n emit requestFinished(true);\n}\n\nvoid GetPocketApi::handleRemoveBookmark(const QString& id)\n{\n bool ok = false;\n QJsonDocument doc = PreparsingReply(sender(), ok);\n if (!ok)\n {\n qDebug() << Q_FUNC_INFO << \"Failed preparsing reply phase\";\n return;\n }\n\n const auto& rootObject = doc.object();\n if(rootObject [\"status\"].toInt() == 1)\n {\n emit bookmarkRemoved(id);\n emit requestFinished(true);\n }\n else\n {\n emit requestFinished(false, tr(\"Unable to remove bookamark\"));\n }\n}\n\nvoid GetPocketApi::handleMarkBookmarkAsFavorite(const QString& id, bool favorite)\n{\n bool ok = false;\n QJsonDocument doc = PreparsingReply(sender(), ok);\n if (!ok)\n {\n qDebug() << Q_FUNC_INFO << \"Failed preparsing reply phase\";\n return;\n }\n\n const auto& rootObject = doc.object();\n if(rootObject [\"status\"].toInt() == 1)\n {\n emit bookmarkMarkedAsFavorite(id, favorite);\n emit requestFinished(true);\n }\n else\n {\n emit requestFinished(false, tr(\"Unable to mark bookamark as %1\")\n .arg(favorite ? tr(\"favorite\") : tr(\"unfavorite\")));\n }\n}\n\nvoid GetPocketApi::handleMarkBookmarkAsRead(const QString& id, bool read)\n{\n bool ok = false;\n QJsonDocument doc = PreparsingReply(sender(), ok);\n if (!ok)\n {\n qDebug() << Q_FUNC_INFO << \"Failed preparsing reply phase\";\n return;\n }\n\n const auto& rootObject = doc.object();\n if(rootObject [\"status\"].toInt() == 1)\n {\n emit bookmarkMarkedAsRead(id, read);\n emit requestFinished(true);\n }\n else\n {\n emit requestFinished(false, tr(\"Unable to mark bookamark as %1\")\n .arg(read ? tr(\"read\") : tr(\"unread\")));\n }\n}\n\nvoid GetPocketApi::handleTagsUpdated(const QString& id, const QString& tags)\n{\n bool ok = false;\n QJsonDocument doc = PreparsingReply(sender(), ok);\n if (!ok)\n {\n qDebug() << Q_FUNC_INFO << \"Failed preparsing reply phase\";\n return;\n }\n\n const auto& rootObject = doc.object();\n if(rootObject [\"status\"].toInt() == 1)\n {\n emit tagsUpdated(id, tags);\n emit requestFinished(true);\n }\n else\n {\n emit requestFinished(false, tr(\"Unable to update tags\"));\n }\n}\n} \/\/ namespace LinksBag\n<commit_msg>Style fix<commit_after>\/*\nThe MIT License (MIT)\n\nCopyright (c) 2014-2017 Oleg Linkin <maledictusdemagog@gmail.com>\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n*\/\n\n#include \"getpocketapi.h\"\n#include <QJsonArray>\n#include <QJsonObject>\n#include <QJsonValue>\n#include <QNetworkAccessManager>\n#include <QNetworkRequest>\n#include <QSettings>\n#include <QStandardPaths>\n\n#include \"settings\/accountsettings.h\"\n\nnamespace LinksBag\n{\nGetPocketApi::GetPocketApi(QObject *parent)\n: QObject(parent)\n, m_ConsumerKey(\"36050-db8157de51cbb0c5f72edc33\")\n, m_NAM(new QNetworkAccessManager(this))\n{\n}\n\nnamespace\n{\n QNetworkRequest CreateRequest(const QString& path)\n {\n QNetworkRequest request(QUrl(QString(\"https:\/\/getpocket.com\/v3\") +\n path));\n request.setHeader(QNetworkRequest::ContentTypeHeader,\n \"application\/json; charset=UTF-8\");\n request.setRawHeader(\"X-Accept\", \"application\/json\");\n\n return request;\n }\n}\n\nvoid GetPocketApi::ObtainRequestToken()\n{\n QVariantMap params;\n params[\"consumer_key\"] = m_ConsumerKey;\n params[\"redirect_uri\"] = \"linksbag:\/\/authorizationFinished\";\n\n QJsonDocument doc(QJsonObject::fromVariantMap(params));\n\n QNetworkReply *reply = m_NAM->post(CreateRequest(\"\/oauth\/request\"),\n doc.toJson());\n\n connect(reply,\n &QNetworkReply::finished,\n this,\n &GetPocketApi::handleObtainRequestToken);\n}\n\nvoid GetPocketApi::RequestAccessToken()\n{\n QVariantMap params;\n params[\"consumer_key\"] = m_ConsumerKey;\n params[\"code\"] = m_RequestToken;\n\n QJsonDocument doc(QJsonObject::fromVariantMap(params));\n\n QNetworkReply *reply = m_NAM->post(CreateRequest(\"\/oauth\/authorize\"),\n doc.toJson());\n\n connect(reply,\n &QNetworkReply::finished,\n this,\n &GetPocketApi::handleRequestAccessToken);\n}\n\nvoid GetPocketApi::LoadBookmarks(int lastUpdate)\n{\n QVariantMap params;\n params[\"consumer_key\"] = m_ConsumerKey;\n params[\"access_token\"] = AccountSettings::Instance(this)->value(\"access_token\");\n params[\"state\"] = \"all\";\n params[\"sort\"] = \"oldest\";\n params[\"detailType\"] = \"complete\";\n params[\"since\"] = lastUpdate;\n\n QJsonDocument doc(QJsonObject::fromVariantMap(params));\n\n QNetworkReply *reply = m_NAM->post(CreateRequest(\"\/get\"),\n doc.toJson());\n\n connect(reply,\n &QNetworkReply::finished,\n this,\n &GetPocketApi::handleLoadBookmarks);\n}\n\nvoid GetPocketApi::RemoveBookmark(const QString& id)\n{\n QVariantMap params;\n params[\"consumer_key\"] = m_ConsumerKey;\n params[\"access_token\"] = AccountSettings::Instance(this)->value(\"access_token\");\n QVariantList actions;\n QVariantMap action;\n action[\"action\"] = \"delete\";\n action[\"item_id\"] = id;\n actions.append(action);\n params[\"actions\"] = actions;\n\n QJsonDocument doc(QJsonObject::fromVariantMap(params));\n\n QNetworkReply *reply = m_NAM->post(CreateRequest(\"\/send\"),\n doc.toJson());\n connect(reply,\n &QNetworkReply::finished,\n this,\n [=]()\n {\n handleRemoveBookmark(id);\n });\n}\n\nvoid GetPocketApi::MarkBookmarkAsFavorite(const QString& id, bool favorite)\n{\n QVariantMap params;\n params[\"consumer_key\"] = m_ConsumerKey;\n params[\"access_token\"] = AccountSettings::Instance(this)->value(\"access_token\");\n QVariantList actions;\n QVariantMap action;\n action[\"action\"] = favorite ? \"favorite\" : \"unfavorite\";\n action[\"item_id\"] = id;\n actions.append(action);\n params[\"actions\"] = actions;\n\n QJsonDocument doc(QJsonObject::fromVariantMap(params));\n\n QNetworkReply *reply = m_NAM->post(CreateRequest(\"\/send\"),\n doc.toJson());\n connect(reply,\n &QNetworkReply::finished,\n this,\n [this, id, favorite]()\n {\n handleMarkBookmarkAsFavorite(id, favorite);\n });\n}\n\nvoid GetPocketApi::MarkBookmarkAsRead(const QString& id, bool read)\n{\n QVariantMap params;\n params[\"consumer_key\"] = m_ConsumerKey;\n params[\"access_token\"] = AccountSettings::Instance(this)->value(\"access_token\");\n QVariantList actions;\n QVariantMap action;\n action[\"action\"] = read ? \"archive\" : \"readd\";\n action[\"item_id\"] = id;\n actions.append(action);\n params [\"actions\"] = actions;\n\n QJsonDocument doc(QJsonObject::fromVariantMap(params));\n\n QNetworkReply *reply = m_NAM->post(CreateRequest(\"\/send\"),\n doc.toJson());\n connect(reply,\n &QNetworkReply::finished,\n this,\n [this, id, read]()\n {\n handleMarkBookmarkAsRead(id, read);\n });\n}\n\nvoid GetPocketApi::UpdateTags(const QString& id, const QString& tags)\n{\n QVariantMap params;\n params[\"consumer_key\"] = m_ConsumerKey;\n params[\"access_token\"] = AccountSettings::Instance(this)->value(\"access_token\");\n QVariantList actions;\n QVariantMap action;\n action[\"action\"] = \"tags_replace\";\n action[\"item_id\"] = id;\n action[\"tags\"] = tags;\n actions.append(action);\n params [\"actions\"] = actions;\n\n QJsonDocument doc(QJsonObject::fromVariantMap(params));\n\n QNetworkReply *reply = m_NAM->post(CreateRequest(\"\/send\"),\n doc.toJson());\n connect(reply,\n &QNetworkReply::finished,\n this,\n [this, id, tags]()\n {\n handleTagsUpdated(id, tags);\n });\n}\n\nvoid GetPocketApi::ResetAccount()\n{\n m_RequestToken.clear();\n}\n\nQJsonDocument GetPocketApi::PreparsingReply(QObject *sender, bool& ok)\n{\n QJsonDocument doc;\n auto reply = qobject_cast<QNetworkReply*> (sender);\n if (!reply)\n {\n qDebug() << \"Invalid reply\";\n emit requestFinished(false, tr(\"General error\"));\n ok = false;\n return doc;\n }\n reply->deleteLater();\n\n if (reply->error() != QNetworkReply::NoError &&\n reply->error() != QNetworkReply::UnknownContentError &&\n reply->error() != QNetworkReply::UnknownNetworkError &&\n reply->error() != m_InvalidRequestError &&\n reply->error() != m_AuthError &&\n reply->error() != m_PermissionsRateError &&\n reply->error() != m_MaintenanceError)\n {\n qDebug() << Q_FUNC_INFO << \"There is network error: \"\n << reply->error() << reply->errorString();\n emit requestFinished(false, tr(\"Network error %1: %2\")\n .arg(reply->error())\n .arg(reply->errorString()));\n ok = false;\n return doc;\n }\n else if (reply->error() != QNetworkReply::NoError)\n {\n const int errorCode = reply->rawHeader(\"X-Error-Code\").toInt();\n const QString errorString = reply->rawHeader(\"X-Error\");\n qDebug() << Q_FUNC_INFO << \"There is getpocket error: \"\n << errorCode << errorString;\n emit error(errorString, errorCode, ETGetPocket);\n ok = false;\n return doc;\n }\n\n ok = false;\n QJsonParseError error;\n doc = QJsonDocument::fromJson(reply->readAll(), &error);\n if (error.error != QJsonParseError::NoError)\n {\n qDebug() << \"Unable to generate json from reply\";\n emit requestFinished(false, tr(\"Reply data is corrupted\"));\n return doc;\n }\n\n ok = true;\n return doc;\n}\n\nvoid GetPocketApi::handleObtainRequestToken()\n{\n bool ok = false;\n QJsonDocument doc = PreparsingReply(sender(), ok);\n if (!ok)\n {\n qDebug() << Q_FUNC_INFO << \"Failed preparsing reply phase\";\n return;\n }\n\n m_RequestToken = doc.object()[\"code\"].toString();\n emit requestTokenChanged(m_RequestToken);\n emit requestFinished(true);\n}\n\nvoid GetPocketApi::handleRequestAccessToken()\n{\n bool ok = false;\n QJsonDocument doc = PreparsingReply(sender(), ok);\n if (!ok)\n {\n qDebug() << Q_FUNC_INFO << \"Failed preparsing reply phase\";\n return;\n }\n\n const auto& accessToken = doc.object()[\"access_token\"].toString();\n const auto& userName = doc.object()[\"username\"].toString();\n emit logged(!accessToken.isEmpty() && !userName.isEmpty(),\n accessToken, userName);\n emit requestFinished(true);\n}\n\nvoid GetPocketApi::handleLoadBookmarks()\n{\n bool ok = false;\n QJsonDocument doc = PreparsingReply(sender(), ok);\n if (!ok)\n {\n qDebug() << Q_FUNC_INFO << \"Failed preparsing reply phase\";\n return;\n }\n\n QJsonObject rootObject = doc.object();\n const quint64 since = rootObject[\"since\"].toDouble();\n\n const auto& listObject = rootObject[\"list\"].toObject();\n Bookmarks_t bookmarks;\n for(const auto& key : listObject.keys())\n {\n QJsonObject bookmarkObject = listObject[key].toObject();\n\n Bookmark bm;\n bm.SetID(bookmarkObject[\"item_id\"].toString());\n bm.SetUrl(bookmarkObject[\"resolved_url\"].toString());\n QString title = bookmarkObject[\"resolved_title\"].toString();\n if(title.isEmpty())\n {\n title = bookmarkObject[\"given_title\"].toString();\n }\n if(title.isEmpty())\n {\n title = bm.GetUrl().toString();\n }\n bm.SetTitle(title);\n bm.SetDescription(bookmarkObject[\"excerpt\"].toString());\n bm.SetIsFavorite(bookmarkObject[\"favorite\"].toString() != \"0\" ||\n bookmarkObject[\"time_favorited\"].toString() != \"0\");\n bm.SetIsRead(bookmarkObject[\"read\"].toString() == \"1\" ||\n bookmarkObject[\"time_read\"].toString() != \"0\");\n bm.SetAddTime(QDateTime::fromTime_t(bookmarkObject[\"time_added\"]\n .toString().toLongLong()));\n bm.SetUpdateTime(QDateTime::fromTime_t(bookmarkObject[\"time_updated\"]\n .toString().toLongLong()));\n const auto& tagsObject = bookmarkObject[\"tags\"].toObject();\n bm.SetTags(tagsObject.keys());\n bm.SetImageUrl(bookmarkObject[\"image\"].toObject()[\"src\"].toString());\n bm.SetStatus(static_cast<Bookmark::Status>(bookmarkObject[\"status\"]\n .toString().toInt()));\n\n bookmarks << bm;\n }\n\n emit gotBookmarks(bookmarks, since);\n emit requestFinished(true);\n}\n\nvoid GetPocketApi::handleRemoveBookmark(const QString& id)\n{\n bool ok = false;\n QJsonDocument doc = PreparsingReply(sender(), ok);\n if (!ok)\n {\n qDebug() << Q_FUNC_INFO << \"Failed preparsing reply phase\";\n return;\n }\n\n const auto& rootObject = doc.object();\n if(rootObject [\"status\"].toInt() == 1)\n {\n emit bookmarkRemoved(id);\n emit requestFinished(true);\n }\n else\n {\n emit requestFinished(false, tr(\"Unable to remove bookamark\"));\n }\n}\n\nvoid GetPocketApi::handleMarkBookmarkAsFavorite(const QString& id, bool favorite)\n{\n bool ok = false;\n QJsonDocument doc = PreparsingReply(sender(), ok);\n if (!ok)\n {\n qDebug() << Q_FUNC_INFO << \"Failed preparsing reply phase\";\n return;\n }\n\n const auto& rootObject = doc.object();\n if(rootObject [\"status\"].toInt() == 1)\n {\n emit bookmarkMarkedAsFavorite(id, favorite);\n emit requestFinished(true);\n }\n else\n {\n emit requestFinished(false, tr(\"Unable to mark bookamark as %1\")\n .arg(favorite ? tr(\"favorite\") : tr(\"unfavorite\")));\n }\n}\n\nvoid GetPocketApi::handleMarkBookmarkAsRead(const QString& id, bool read)\n{\n bool ok = false;\n QJsonDocument doc = PreparsingReply(sender(), ok);\n if (!ok)\n {\n qDebug() << Q_FUNC_INFO << \"Failed preparsing reply phase\";\n return;\n }\n\n const auto& rootObject = doc.object();\n if(rootObject [\"status\"].toInt() == 1)\n {\n emit bookmarkMarkedAsRead(id, read);\n emit requestFinished(true);\n }\n else\n {\n emit requestFinished(false, tr(\"Unable to mark bookamark as %1\")\n .arg(read ? tr(\"read\") : tr(\"unread\")));\n }\n}\n\nvoid GetPocketApi::handleTagsUpdated(const QString& id, const QString& tags)\n{\n bool ok = false;\n QJsonDocument doc = PreparsingReply(sender(), ok);\n if (!ok)\n {\n qDebug() << Q_FUNC_INFO << \"Failed preparsing reply phase\";\n return;\n }\n\n const auto& rootObject = doc.object();\n if(rootObject [\"status\"].toInt() == 1)\n {\n emit tagsUpdated(id, tags);\n emit requestFinished(true);\n }\n else\n {\n emit requestFinished(false, tr(\"Unable to update tags\"));\n }\n}\n} \/\/ namespace LinksBag\n<|endoftext|>"} {"text":"<commit_before>\/\/ SA:MP Profiler plugin\n\/\/\n\/\/ Copyright (c) 2011 Zeex\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include <algorithm>\n#include <fstream>\n#include <iomanip>\n#include <iostream>\n#include <numeric>\n\n#include \"amxprofiler.h\"\n\n#include \"amx\/amx.h\"\n#include \"amx\/amxdbg.h\"\n\nstd::map<AMX*, AmxProfiler*> AmxProfiler::instances_;\n\nAmxProfiler::AmxProfiler() {}\n\n\/\/ Extracts the names of native functions from the native table.\nstatic void GetNatives(AMX *amx, std::vector<AmxProfiler::Function> &names) {\n AMX_HEADER *hdr = reinterpret_cast<AMX_HEADER*>(amx->base);\n AMX_FUNCSTUBNT *natives = reinterpret_cast<AMX_FUNCSTUBNT*>(amx->base + hdr->natives);\n\n int numberOfNatives;\n amx_NumNatives(amx, &numberOfNatives);\n\n for (int i = 0; i < numberOfNatives; i++) {\n names.push_back(AmxProfiler::Function(natives[i].address,\n reinterpret_cast<char*>(amx->base + natives[i].nameofs)));\n }\n}\n\n\/\/ Extracts the names of public functions from the native table.\nstatic void GetPublics(AMX *amx, std::vector<AmxProfiler::Function> &names) {\n AMX_HEADER *hdr = reinterpret_cast<AMX_HEADER*>(amx->base);\n AMX_FUNCSTUBNT *publics = reinterpret_cast<AMX_FUNCSTUBNT*>(amx->base + hdr->publics);\n\n int numberOfPublics;\n amx_NumPublics(amx, &numberOfPublics);\n\n for (int i = 0; i < numberOfPublics; i++) {\n names.push_back(AmxProfiler::Function(publics[i].address, \n reinterpret_cast<char*>(amx->base + publics[i].nameofs)));\n }\n}\n\n\/\/ Reads from a code section at a given location.\nstatic inline cell ReadAmxCode(AMX *amx, cell where) {\n AMX_HEADER *hdr = reinterpret_cast<AMX_HEADER*>(amx->base);\n return *reinterpret_cast<cell*>(amx->base + hdr->cod + where);\n}\n\n\/\/ Comparison functiosn for different stats sorting modes\nstatic bool ByCalls(const std::pair<cell, AmxPerformanceCounter> &op1, \n const std::pair<cell, AmxPerformanceCounter> &op2) {\n return op1.second.GetCalls() > op2.second.GetCalls();\n}\n\nstatic bool ByTime(const std::pair<cell, AmxPerformanceCounter> &op1, \n const std::pair<cell, AmxPerformanceCounter> &op2) {\n return op1.second.GetTime() > op2.second.GetTime();\n}\n\nstatic bool ByTimePerCall(const std::pair<cell, AmxPerformanceCounter> &op1, \n const std::pair<cell, AmxPerformanceCounter> &op2) {\n return static_cast<double>(op1.second.GetTime()) \/ static_cast<double>(op1.second.GetCalls())\n > static_cast<double>(op2.second.GetTime()) \/ static_cast<double>(op2.second.GetCalls());\n}\n\nAmxProfiler::AmxProfiler(AMX *amx) \n : amx_(amx),\n debug_(amx->debug),\n callback_(amx->callback),\n active_(false),\n haveDbg_(false)\n{\n \/\/ Since PrintStats is done in AmxUnload and amx->base is already freed before\n \/\/ AmxUnload gets called, therefore both native and public tables are not accessible, \n \/\/ from there, so they must be stored separately in some global place.\n GetNatives(amx, natives_);\n GetPublics(amx, publics_);\n}\n\nAmxProfiler::AmxProfiler(AMX *amx, AMX_DBG amxdbg) \n : amx_(amx),\n amxdbg_(amxdbg),\n debug_(amx->debug),\n callback_(amx->callback),\n active_(false),\n haveDbg_(true)\n{\n GetNatives(amx, natives_);\n GetPublics(amx, publics_);\n}\n\nvoid AmxProfiler::Attach(AMX *amx) {\n AmxProfiler *prof = new AmxProfiler(amx);\n instances_[amx] = prof;\n prof->Activate();\n}\n\nvoid AmxProfiler::Attach(AMX *amx, AMX_DBG amxdbg) {\n AmxProfiler *prof = new AmxProfiler(amx, amxdbg);\n instances_[amx] = prof;\n prof->Activate();\n}\n\nvoid AmxProfiler::Detach(AMX *amx) {\n AmxProfiler *prof = AmxProfiler::Get(amx);\n if (prof != 0) {\n prof->Deactivate();\n delete prof;\n }\n instances_.erase(amx);\n}\n\nAmxProfiler *AmxProfiler::Get(AMX *amx) {\n std::map<AMX*, AmxProfiler*>::iterator it = instances_.find(amx);\n if (it != instances_.end()) {\n return it->second;\n }\n return 0;\n}\n\nstatic int AMXAPI Debug(AMX *amx) {\n return AmxProfiler::Get(amx)->Debug();\n}\n\nstatic int AMXAPI Callback(AMX *amx, cell index, cell *result, cell *params) {\n return AmxProfiler::Get(amx)->Callback(index, result, params);\n}\n\nvoid AmxProfiler::Activate() {\n if (!active_) {\n active_ = true;\n amx_SetDebugHook(amx_, ::Debug);\n amx_SetCallback(amx_, ::Callback);\n }\n}\n\nbool AmxProfiler::IsActive() const {\n return active_;\n}\n\nvoid AmxProfiler::Deactivate() {\n if (active_) {\n active_ = false;\n amx_SetDebugHook(amx_, debug_);\n amx_SetCallback(amx_, callback_);\n }\n}\n\nvoid AmxProfiler::ResetStats() {\n counters_.clear();\n}\n\nbool AmxProfiler::PrintStats(const std::string &filename, StatsPrintOrder order) {\n std::ofstream stream(filename.c_str());\n\n if (stream.is_open()) {\n std::vector<std::pair<cell, AmxPerformanceCounter> > stats(counters_.begin(), \n counters_.end());\n switch (order) {\n case ORDER_BY_CALLS:\n std::sort(stats.begin(), stats.end(), ByCalls);\n break;\n case ORDER_BY_TIME:\n std::sort(stats.begin(), stats.end(), ByTime);\n break;\n case ORDER_BY_TIME_PER_CALL:\n std::sort(stats.begin(), stats.end(), ByTimePerCall);\n break;\n default:\n \/\/ leave as is\n break;\n }\n\n stream << \"<table>\\n\"\n << \"\\t<tr>\\n\"\n << \"\\t\\t<td>Function<\/td>\\n\"\n << \"\\t\\t<td>Calls<\/td>\\n\"\n << \"\\t\\t<td>Time per call, µs<\/td>\\n\"\n << \"\\t\\t<td>Overall time, µs<\/td>\\n\"\n << \"\\t\\t<td>Overall time, %<\/td>\\n\"\n << \"\\t<\/tr>\\n\";\n\n platformstl::int64_t totalTime = 0;\n\n for (std::vector<std::pair<cell, AmxPerformanceCounter> >::iterator it = stats.begin(); \n it != stats.end(); ++it) \n {\n totalTime += it->second.GetTime();\n } \n\n for (std::vector<std::pair<cell, AmxPerformanceCounter> >::iterator it = stats.begin(); \n it != stats.end(); ++it) \n {\n stream << \"\\t<tr>\\n\";\n\n cell address = it->first;\n\n if (address <= 0) {\n stream << \"\\t\\t<td>\" << natives_[-address].name() << \"<\/td>\\n\";\n } else {\n const char *name = 0;\n if (haveDbg_ && dbg_LookupFunction(&amxdbg_, address, &name) == AMX_ERR_NONE) {\n stream << \"\\t\\t<td>\" << name << \"<\/td>\\n\";\n } else {\n bool found = false;\n for (std::vector<AmxProfiler::Function>::iterator pubIt = publics_.begin(); \n pubIt != publics_.end(); ++pubIt) \n {\n if (pubIt->address() == address) {\n stream << \"\\t\\t<td>\" << pubIt->name() << \"<\/td>\\n\";\n found = true;\n break;\n }\n }\n if (!found) {\n \/\/ OK we tried all means but still don't know the name, so just print the address.\n stream << \"\\t\\t<td>\" << \"0x\" << std::hex << address << std::dec << \"<\/td>\\n\";\n }\n }\n }\n\n AmxPerformanceCounter &counter = it->second;\n\n stream << \"\\t\\t<td>\" << counter.GetCalls() << \"<\/td>\\n\"\n << \"\\t\\t<td>\" << std::fixed << std::setprecision(0)\n << static_cast<double>(counter.GetTime()) \/ \n static_cast<double>(counter.GetCalls()) << \"<\/td>\\n\"\n << \"\\t\\t<td>\" << counter.GetTime() << \"<\/td>\\n\"\n << \"\\t\\t<td>\" << std::setprecision(2)\n << static_cast<double>(counter.GetTime() * 100) \/ \n static_cast<double>(totalTime) << \"<\/td>\\n\";\n stream << \"\\t<\/tr>\\n\";\n }\n\n stream << \"<\/table>\\n\";\n\n return true;\n }\n\n return false;\n}\n\nint AmxProfiler::Debug() {\n \/\/ Get previous stack frame.\n cell prevFrame = amx_->stp;\n if (!calls_.empty()) {\n prevFrame = calls_.top().frame();\n }\n\n \/\/ Check whether current frame is different.\n if (amx_->frm < prevFrame) {\n \/\/ Probably entered a function body (first BREAK after PROC).\n cell address = amx_->cip - 2*sizeof(cell); \n \/\/ Check if we have a PROC opcode behind.\n if (ReadAmxCode(amx_, address) == 46) {\n calls_.push(CallInfo(amx_->frm, address, false));\n if (active_) {\n counters_[address].Start();\n }\n \/\/logprintf(\"==> %x | frame = %x\", address, amx_->frm);\n }\n } else if (amx_->frm > prevFrame) {\n if (!calls_.top().entryPoint()) { \/\/ entry points are handled by Exec\n \/\/ Left the function\n cell address = calls_.top().address();\n if (active_) {\n counters_[address].Stop();\n }\n calls_.pop();\n \/\/logprintf(\"<== %x | frame = %x\", address, amx_->frm);\n }\n }\n\n if (debug_ != 0) {\n \/\/ Others could set their own debug hooks\n return debug_(amx_);\n } \n\n return AMX_ERR_NONE; \n}\n\nint AmxProfiler::Callback(cell index, cell *result, cell *params) {\n \/\/ The default AMX callback (amx_Callback) can replace SYSREQ.C opcodes\n \/\/ with SYSREQ.D for better performance. \n amx_->sysreq_d = 0; \n\n if (active_) counters_[-index].Start();; \/\/ Notice negative index\n int error = callback_(amx_, index, result, params);\n if (active_) counters_[-index].Stop();\n\n return error;\n}\n\nint AmxProfiler::Exec(cell *retval, int index) {\n if (index >= 0 || index == AMX_EXEC_MAIN) {\n AMX_HEADER *hdr = reinterpret_cast<AMX_HEADER*>(amx_->base);\n cell address = 0;\n\n if (index == AMX_EXEC_MAIN) {\n address = hdr->cip;\n } else {\n AMX_FUNCSTUBNT *publics = reinterpret_cast<AMX_FUNCSTUBNT*>(amx_->base + hdr->publics);\n address = publics[index].address;\n }\n \n calls_.push(CallInfo(amx_->stk - 3*sizeof(cell), address, true));\n\n if (active_) counters_[address].Start();\n int error = amx_Exec(amx_, retval, index);\n if (active_) counters_[address].Stop();\n\n calls_.pop();\n\n return error;\n } else {\n return amx_Exec(amx_, retval, index);\n }\n}\n\n<commit_msg>Rename last parameters of GetNatives and GetPublics<commit_after>\/\/ SA:MP Profiler plugin\n\/\/\n\/\/ Copyright (c) 2011 Zeex\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include <algorithm>\n#include <fstream>\n#include <iomanip>\n#include <iostream>\n#include <numeric>\n\n#include \"amxprofiler.h\"\n\n#include \"amx\/amx.h\"\n#include \"amx\/amxdbg.h\"\n\nstd::map<AMX*, AmxProfiler*> AmxProfiler::instances_;\n\nAmxProfiler::AmxProfiler() {}\n\n\/\/ Extracts the names of native functions from the native table.\nstatic void GetNatives(AMX *amx, std::vector<AmxProfiler::Function> &natives) {\n AMX_HEADER *hdr = reinterpret_cast<AMX_HEADER*>(amx->base);\n AMX_FUNCSTUBNT *nativeTable = reinterpret_cast<AMX_FUNCSTUBNT*>(amx->base + hdr->natives);\n\n int numberOfNatives;\n amx_NumNatives(amx, &numberOfNatives);\n\n for (int i = 0; i < numberOfNatives; i++) {\n natives.push_back(AmxProfiler::Function(nativeTable[i].address,\n reinterpret_cast<char*>(amx->base + nativeTable[i].nameofs)));\n }\n}\n\n\/\/ Extracts the names of public functions from the native table.\nstatic void GetPublics(AMX *amx, std::vector<AmxProfiler::Function> &publics) {\n AMX_HEADER *hdr = reinterpret_cast<AMX_HEADER*>(amx->base);\n AMX_FUNCSTUBNT *publicTable = reinterpret_cast<AMX_FUNCSTUBNT*>(amx->base + hdr->publics);\n\n int numberOfPublics;\n amx_NumPublics(amx, &numberOfPublics);\n\n for (int i = 0; i < numberOfPublics; i++) {\n publics.push_back(AmxProfiler::Function(publicTable[i].address, \n reinterpret_cast<char*>(amx->base + publicTable[i].nameofs)));\n }\n}\n\n\/\/ Reads from a code section at a given location.\nstatic inline cell ReadAmxCode(AMX *amx, cell where) {\n AMX_HEADER *hdr = reinterpret_cast<AMX_HEADER*>(amx->base);\n return *reinterpret_cast<cell*>(amx->base + hdr->cod + where);\n}\n\n\/\/ Comparison functiosn for different stats sorting modes\nstatic bool ByCalls(const std::pair<cell, AmxPerformanceCounter> &op1, \n const std::pair<cell, AmxPerformanceCounter> &op2) {\n return op1.second.GetCalls() > op2.second.GetCalls();\n}\n\nstatic bool ByTime(const std::pair<cell, AmxPerformanceCounter> &op1, \n const std::pair<cell, AmxPerformanceCounter> &op2) {\n return op1.second.GetTime() > op2.second.GetTime();\n}\n\nstatic bool ByTimePerCall(const std::pair<cell, AmxPerformanceCounter> &op1, \n const std::pair<cell, AmxPerformanceCounter> &op2) {\n return static_cast<double>(op1.second.GetTime()) \/ static_cast<double>(op1.second.GetCalls())\n > static_cast<double>(op2.second.GetTime()) \/ static_cast<double>(op2.second.GetCalls());\n}\n\nAmxProfiler::AmxProfiler(AMX *amx) \n : amx_(amx),\n debug_(amx->debug),\n callback_(amx->callback),\n active_(false),\n haveDbg_(false)\n{\n \/\/ Since PrintStats is done in AmxUnload and amx->base is already freed before\n \/\/ AmxUnload gets called, therefore both native and public tables are not accessible, \n \/\/ from there, so they must be stored separately in some global place.\n GetNatives(amx, natives_);\n GetPublics(amx, publics_);\n}\n\nAmxProfiler::AmxProfiler(AMX *amx, AMX_DBG amxdbg) \n : amx_(amx),\n amxdbg_(amxdbg),\n debug_(amx->debug),\n callback_(amx->callback),\n active_(false),\n haveDbg_(true)\n{\n GetNatives(amx, natives_);\n GetPublics(amx, publics_);\n}\n\nvoid AmxProfiler::Attach(AMX *amx) {\n AmxProfiler *prof = new AmxProfiler(amx);\n instances_[amx] = prof;\n prof->Activate();\n}\n\nvoid AmxProfiler::Attach(AMX *amx, AMX_DBG amxdbg) {\n AmxProfiler *prof = new AmxProfiler(amx, amxdbg);\n instances_[amx] = prof;\n prof->Activate();\n}\n\nvoid AmxProfiler::Detach(AMX *amx) {\n AmxProfiler *prof = AmxProfiler::Get(amx);\n if (prof != 0) {\n prof->Deactivate();\n delete prof;\n }\n instances_.erase(amx);\n}\n\nAmxProfiler *AmxProfiler::Get(AMX *amx) {\n std::map<AMX*, AmxProfiler*>::iterator it = instances_.find(amx);\n if (it != instances_.end()) {\n return it->second;\n }\n return 0;\n}\n\nstatic int AMXAPI Debug(AMX *amx) {\n return AmxProfiler::Get(amx)->Debug();\n}\n\nstatic int AMXAPI Callback(AMX *amx, cell index, cell *result, cell *params) {\n return AmxProfiler::Get(amx)->Callback(index, result, params);\n}\n\nvoid AmxProfiler::Activate() {\n if (!active_) {\n active_ = true;\n amx_SetDebugHook(amx_, ::Debug);\n amx_SetCallback(amx_, ::Callback);\n }\n}\n\nbool AmxProfiler::IsActive() const {\n return active_;\n}\n\nvoid AmxProfiler::Deactivate() {\n if (active_) {\n active_ = false;\n amx_SetDebugHook(amx_, debug_);\n amx_SetCallback(amx_, callback_);\n }\n}\n\nvoid AmxProfiler::ResetStats() {\n counters_.clear();\n}\n\nbool AmxProfiler::PrintStats(const std::string &filename, StatsPrintOrder order) {\n std::ofstream stream(filename.c_str());\n\n if (stream.is_open()) {\n std::vector<std::pair<cell, AmxPerformanceCounter> > stats(counters_.begin(), \n counters_.end());\n switch (order) {\n case ORDER_BY_CALLS:\n std::sort(stats.begin(), stats.end(), ByCalls);\n break;\n case ORDER_BY_TIME:\n std::sort(stats.begin(), stats.end(), ByTime);\n break;\n case ORDER_BY_TIME_PER_CALL:\n std::sort(stats.begin(), stats.end(), ByTimePerCall);\n break;\n default:\n \/\/ leave as is\n break;\n }\n\n stream << \"<table>\\n\"\n << \"\\t<tr>\\n\"\n << \"\\t\\t<td>Function<\/td>\\n\"\n << \"\\t\\t<td>Calls<\/td>\\n\"\n << \"\\t\\t<td>Time per call, µs<\/td>\\n\"\n << \"\\t\\t<td>Overall time, µs<\/td>\\n\"\n << \"\\t\\t<td>Overall time, %<\/td>\\n\"\n << \"\\t<\/tr>\\n\";\n\n platformstl::int64_t totalTime = 0;\n\n for (std::vector<std::pair<cell, AmxPerformanceCounter> >::iterator it = stats.begin(); \n it != stats.end(); ++it) \n {\n totalTime += it->second.GetTime();\n } \n\n for (std::vector<std::pair<cell, AmxPerformanceCounter> >::iterator it = stats.begin(); \n it != stats.end(); ++it) \n {\n stream << \"\\t<tr>\\n\";\n\n cell address = it->first;\n\n if (address <= 0) {\n stream << \"\\t\\t<td>\" << natives_[-address].name() << \"<\/td>\\n\";\n } else {\n const char *name = 0;\n if (haveDbg_ && dbg_LookupFunction(&amxdbg_, address, &name) == AMX_ERR_NONE) {\n stream << \"\\t\\t<td>\" << name << \"<\/td>\\n\";\n } else {\n bool found = false;\n for (std::vector<AmxProfiler::Function>::iterator pubIt = publics_.begin(); \n pubIt != publics_.end(); ++pubIt) \n {\n if (pubIt->address() == address) {\n stream << \"\\t\\t<td>\" << pubIt->name() << \"<\/td>\\n\";\n found = true;\n break;\n }\n }\n if (!found) {\n \/\/ OK we tried all means but still don't know the name, so just print the address.\n stream << \"\\t\\t<td>\" << \"0x\" << std::hex << address << std::dec << \"<\/td>\\n\";\n }\n }\n }\n\n AmxPerformanceCounter &counter = it->second;\n\n stream << \"\\t\\t<td>\" << counter.GetCalls() << \"<\/td>\\n\"\n << \"\\t\\t<td>\" << std::fixed << std::setprecision(0)\n << static_cast<double>(counter.GetTime()) \/ \n static_cast<double>(counter.GetCalls()) << \"<\/td>\\n\"\n << \"\\t\\t<td>\" << counter.GetTime() << \"<\/td>\\n\"\n << \"\\t\\t<td>\" << std::setprecision(2)\n << static_cast<double>(counter.GetTime() * 100) \/ \n static_cast<double>(totalTime) << \"<\/td>\\n\";\n stream << \"\\t<\/tr>\\n\";\n }\n\n stream << \"<\/table>\\n\";\n\n return true;\n }\n\n return false;\n}\n\nint AmxProfiler::Debug() {\n \/\/ Get previous stack frame.\n cell prevFrame = amx_->stp;\n if (!calls_.empty()) {\n prevFrame = calls_.top().frame();\n }\n\n \/\/ Check whether current frame is different.\n if (amx_->frm < prevFrame) {\n \/\/ Probably entered a function body (first BREAK after PROC).\n cell address = amx_->cip - 2*sizeof(cell); \n \/\/ Check if we have a PROC opcode behind.\n if (ReadAmxCode(amx_, address) == 46) {\n calls_.push(CallInfo(amx_->frm, address, false));\n if (active_) {\n counters_[address].Start();\n }\n \/\/logprintf(\"==> %x | frame = %x\", address, amx_->frm);\n }\n } else if (amx_->frm > prevFrame) {\n if (!calls_.top().entryPoint()) { \/\/ entry points are handled by Exec\n \/\/ Left the function\n cell address = calls_.top().address();\n if (active_) {\n counters_[address].Stop();\n }\n calls_.pop();\n \/\/logprintf(\"<== %x | frame = %x\", address, amx_->frm);\n }\n }\n\n if (debug_ != 0) {\n \/\/ Others could set their own debug hooks\n return debug_(amx_);\n } \n\n return AMX_ERR_NONE; \n}\n\nint AmxProfiler::Callback(cell index, cell *result, cell *params) {\n \/\/ The default AMX callback (amx_Callback) can replace SYSREQ.C opcodes\n \/\/ with SYSREQ.D for better performance. \n amx_->sysreq_d = 0; \n\n if (active_) counters_[-index].Start();; \/\/ Notice negative index\n int error = callback_(amx_, index, result, params);\n if (active_) counters_[-index].Stop();\n\n return error;\n}\n\nint AmxProfiler::Exec(cell *retval, int index) {\n if (index >= 0 || index == AMX_EXEC_MAIN) {\n AMX_HEADER *hdr = reinterpret_cast<AMX_HEADER*>(amx_->base);\n cell address = 0;\n\n if (index == AMX_EXEC_MAIN) {\n address = hdr->cip;\n } else {\n AMX_FUNCSTUBNT *publics = reinterpret_cast<AMX_FUNCSTUBNT*>(amx_->base + hdr->publics);\n address = publics[index].address;\n }\n \n calls_.push(CallInfo(amx_->stk - 3*sizeof(cell), address, true));\n\n if (active_) counters_[address].Start();\n int error = amx_Exec(amx_, retval, index);\n if (active_) counters_[address].Stop();\n\n calls_.pop();\n\n return error;\n } else {\n return amx_Exec(amx_, retval, index);\n }\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements. See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership. The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n * \n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied. See the License for the\n * specific language governing permissions and limitations\n * under the License.\n *\/\n\n\/*!\n * Copyright (c) 2017 by Contributors\n * Exposre of pass functions.\n * \\file api_pass.cc\n *\/\n#include <tvm\/expr.h>\n#include <tvm\/ir.h>\n#include <tvm\/attrs.h>\n#include <tvm\/ir_pass.h>\n#include <tvm\/ir_visitor.h>\n#include <tvm\/ir_mutator.h>\n#include <tvm\/api_registry.h>\n\nnamespace tvm {\nnamespace ir {\n\nTVM_REGISTER_API(\"ir_pass.Simplify\")\n.set_body([](TVMArgs args, TVMRetValue *ret) {\n if (args[0].IsNodeType<Stmt>()) {\n if (args.size() > 1) {\n *ret = Simplify(args[0].operator Stmt(), args[1]);\n } else {\n *ret = Simplify(args[0].operator Stmt());\n }\n } else {\n if (args.size() > 1) {\n *ret = Simplify(args[0].operator Expr(), args[1]);\n } else {\n *ret = Simplify(args[0].operator Expr());\n }\n }\n });\n\nTVM_REGISTER_API(\"ir_pass.CanonicalSimplify\")\n.set_body([](TVMArgs args, TVMRetValue *ret) {\n if (args[0].IsNodeType<Stmt>()) {\n if (args.size() > 1) {\n *ret = CanonicalSimplify(args[0].operator Stmt(), args[1]);\n } else {\n *ret = CanonicalSimplify(args[0].operator Stmt());\n }\n } else {\n if (args.size() > 1) {\n *ret = CanonicalSimplify(args[0].operator Expr(), args[1]);\n } else {\n *ret = CanonicalSimplify(args[0].operator Expr());\n }\n }\n });\n\nTVM_REGISTER_API(\"ir_pass.Substitute\")\n.set_body([](TVMArgs args, TVMRetValue *ret) {\n if (args[0].IsNodeType<Stmt>()) {\n *ret = Substitute(args[0].operator Stmt(), args[1].operator Map<Var, Expr>());\n } else {\n *ret = Substitute(args[0].operator Expr(), args[1].operator Map<Var, Expr>());\n }\n });\n\nTVM_REGISTER_API(\"ir_pass.Equal\")\n.set_body([](TVMArgs args, TVMRetValue *ret) {\n if (args[0].IsNodeType<Stmt>()) {\n *ret = Equal(args[0].operator Stmt(), args[1].operator Stmt());\n } else {\n *ret = Equal(args[0].operator Expr(), args[1].operator Expr());\n }\n });\n\nTVM_REGISTER_API(\"ir_pass.StorageFlatten\")\n.set_body([](TVMArgs args, TVMRetValue *ret) {\n if (args.size() <= 3) {\n *ret = StorageFlatten(args[0], args[1], args[2]);\n } else {\n *ret = StorageFlatten(args[0], args[1], args[2], args[3]);\n }\n });\n\nTVM_REGISTER_API(\"ir_pass.AttrsEqual\")\n.set_body_typed<bool(const NodeRef&, const NodeRef&)>([](const NodeRef& lhs, const NodeRef& rhs) {\n return AttrsEqual()(lhs, rhs);\n });\n\nTVM_REGISTER_API(\"ir_pass.AttrsHash\")\n.set_body_typed<int64_t(const NodeRef&)>([](const NodeRef &node) {\n return AttrsHash()(node);\n });\n\n\nTVM_REGISTER_API(\"ir_pass.ExprUseVar\")\n.set_body([](TVMArgs args, TVMRetValue *ret) {\n *ret = ExprUseVar(args[0].operator Expr(), args[1].operator Var());\n });\n\nTVM_REGISTER_API(\"ir_pass.PostOrderVisit\")\n.set_body([](TVMArgs args, TVMRetValue *ret) {\n PackedFunc f = args[1];\n ir::PostOrderVisit(args[0], [f](const NodeRef& n) {\n f(n);\n });\n });\n\n\/\/ make from two arguments\n#define REGISTER_PASS(PassName) \\\n TVM_REGISTER_API(\"ir_pass.\"#PassName) \\\n .set_body_typed(PassName); \\\n\n\nREGISTER_PASS(ConvertSSA);\nREGISTER_PASS(VerifySSA);\nREGISTER_PASS(RewriteUnsafeSelect);\nREGISTER_PASS(Inline);\nREGISTER_PASS(IRTransform);\nREGISTER_PASS(VectorizeLoop);\nREGISTER_PASS(UnrollLoop);\nREGISTER_PASS(InjectCopyIntrin);\nREGISTER_PASS(ThreadSync);\nREGISTER_PASS(MakeAPI);\nREGISTER_PASS(BindDeviceType);\nREGISTER_PASS(SplitHostDevice);\nREGISTER_PASS(StorageRewrite);\nREGISTER_PASS(CoProcSync);\nREGISTER_PASS(LowerStorageAccessInfo);\nREGISTER_PASS(InjectVirtualThread);\nREGISTER_PASS(InjectPrefetch);\nREGISTER_PASS(InjectDoubleBuffer);\nREGISTER_PASS(LoopPartition);\nREGISTER_PASS(RemoveNoOp);\nREGISTER_PASS(SplitPipeline);\nREGISTER_PASS(LiftAttrScope);\nREGISTER_PASS(NarrowChannelAccess);\nREGISTER_PASS(LowerThreadAllreduce);\nREGISTER_PASS(LowerWarpMemory);\nREGISTER_PASS(RemapThreadAxis);\nREGISTER_PASS(LowerIntrin);\nREGISTER_PASS(LowerCustomDatatypes);\nREGISTER_PASS(LowerTVMBuiltin);\nREGISTER_PASS(CombineContextCall);\nREGISTER_PASS(VerifyMemory);\nREGISTER_PASS(VerifyGPUCode);\nREGISTER_PASS(DecorateDeviceScope);\nREGISTER_PASS(InstrumentBoundCheckers);\n} \/\/ namespace ir\n} \/\/ namespace tvm\n<commit_msg>Register SkipVectorize (#3228)<commit_after>\/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements. See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership. The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n * \n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied. See the License for the\n * specific language governing permissions and limitations\n * under the License.\n *\/\n\n\/*!\n * Copyright (c) 2017 by Contributors\n * Exposre of pass functions.\n * \\file api_pass.cc\n *\/\n#include <tvm\/expr.h>\n#include <tvm\/ir.h>\n#include <tvm\/attrs.h>\n#include <tvm\/ir_pass.h>\n#include <tvm\/ir_visitor.h>\n#include <tvm\/ir_mutator.h>\n#include <tvm\/api_registry.h>\n\nnamespace tvm {\nnamespace ir {\n\nTVM_REGISTER_API(\"ir_pass.Simplify\")\n.set_body([](TVMArgs args, TVMRetValue *ret) {\n if (args[0].IsNodeType<Stmt>()) {\n if (args.size() > 1) {\n *ret = Simplify(args[0].operator Stmt(), args[1]);\n } else {\n *ret = Simplify(args[0].operator Stmt());\n }\n } else {\n if (args.size() > 1) {\n *ret = Simplify(args[0].operator Expr(), args[1]);\n } else {\n *ret = Simplify(args[0].operator Expr());\n }\n }\n });\n\nTVM_REGISTER_API(\"ir_pass.CanonicalSimplify\")\n.set_body([](TVMArgs args, TVMRetValue *ret) {\n if (args[0].IsNodeType<Stmt>()) {\n if (args.size() > 1) {\n *ret = CanonicalSimplify(args[0].operator Stmt(), args[1]);\n } else {\n *ret = CanonicalSimplify(args[0].operator Stmt());\n }\n } else {\n if (args.size() > 1) {\n *ret = CanonicalSimplify(args[0].operator Expr(), args[1]);\n } else {\n *ret = CanonicalSimplify(args[0].operator Expr());\n }\n }\n });\n\nTVM_REGISTER_API(\"ir_pass.Substitute\")\n.set_body([](TVMArgs args, TVMRetValue *ret) {\n if (args[0].IsNodeType<Stmt>()) {\n *ret = Substitute(args[0].operator Stmt(), args[1].operator Map<Var, Expr>());\n } else {\n *ret = Substitute(args[0].operator Expr(), args[1].operator Map<Var, Expr>());\n }\n });\n\nTVM_REGISTER_API(\"ir_pass.Equal\")\n.set_body([](TVMArgs args, TVMRetValue *ret) {\n if (args[0].IsNodeType<Stmt>()) {\n *ret = Equal(args[0].operator Stmt(), args[1].operator Stmt());\n } else {\n *ret = Equal(args[0].operator Expr(), args[1].operator Expr());\n }\n });\n\nTVM_REGISTER_API(\"ir_pass.StorageFlatten\")\n.set_body([](TVMArgs args, TVMRetValue *ret) {\n if (args.size() <= 3) {\n *ret = StorageFlatten(args[0], args[1], args[2]);\n } else {\n *ret = StorageFlatten(args[0], args[1], args[2], args[3]);\n }\n });\n\nTVM_REGISTER_API(\"ir_pass.AttrsEqual\")\n.set_body_typed<bool(const NodeRef&, const NodeRef&)>([](const NodeRef& lhs, const NodeRef& rhs) {\n return AttrsEqual()(lhs, rhs);\n });\n\nTVM_REGISTER_API(\"ir_pass.AttrsHash\")\n.set_body_typed<int64_t(const NodeRef&)>([](const NodeRef &node) {\n return AttrsHash()(node);\n });\n\n\nTVM_REGISTER_API(\"ir_pass.ExprUseVar\")\n.set_body([](TVMArgs args, TVMRetValue *ret) {\n *ret = ExprUseVar(args[0].operator Expr(), args[1].operator Var());\n });\n\nTVM_REGISTER_API(\"ir_pass.PostOrderVisit\")\n.set_body([](TVMArgs args, TVMRetValue *ret) {\n PackedFunc f = args[1];\n ir::PostOrderVisit(args[0], [f](const NodeRef& n) {\n f(n);\n });\n });\n\n\/\/ make from two arguments\n#define REGISTER_PASS(PassName) \\\n TVM_REGISTER_API(\"ir_pass.\"#PassName) \\\n .set_body_typed(PassName); \\\n\n\nREGISTER_PASS(ConvertSSA);\nREGISTER_PASS(VerifySSA);\nREGISTER_PASS(RewriteUnsafeSelect);\nREGISTER_PASS(Inline);\nREGISTER_PASS(IRTransform);\nREGISTER_PASS(VectorizeLoop);\nREGISTER_PASS(SkipVectorize);\nREGISTER_PASS(UnrollLoop);\nREGISTER_PASS(InjectCopyIntrin);\nREGISTER_PASS(ThreadSync);\nREGISTER_PASS(MakeAPI);\nREGISTER_PASS(BindDeviceType);\nREGISTER_PASS(SplitHostDevice);\nREGISTER_PASS(StorageRewrite);\nREGISTER_PASS(CoProcSync);\nREGISTER_PASS(LowerStorageAccessInfo);\nREGISTER_PASS(InjectVirtualThread);\nREGISTER_PASS(InjectPrefetch);\nREGISTER_PASS(InjectDoubleBuffer);\nREGISTER_PASS(LoopPartition);\nREGISTER_PASS(RemoveNoOp);\nREGISTER_PASS(SplitPipeline);\nREGISTER_PASS(LiftAttrScope);\nREGISTER_PASS(NarrowChannelAccess);\nREGISTER_PASS(LowerThreadAllreduce);\nREGISTER_PASS(LowerWarpMemory);\nREGISTER_PASS(RemapThreadAxis);\nREGISTER_PASS(LowerIntrin);\nREGISTER_PASS(LowerCustomDatatypes);\nREGISTER_PASS(LowerTVMBuiltin);\nREGISTER_PASS(CombineContextCall);\nREGISTER_PASS(VerifyMemory);\nREGISTER_PASS(VerifyGPUCode);\nREGISTER_PASS(DecorateDeviceScope);\nREGISTER_PASS(InstrumentBoundCheckers);\n} \/\/ namespace ir\n} \/\/ namespace tvm\n<|endoftext|>"} {"text":"<commit_before>\/*******************************************************\n * Copyright (c) 2014, ArrayFire\n * All rights reserved.\n *\n * This file is distributed under 3-clause BSD license.\n * The complete license agreement can be obtained at:\n * http:\/\/arrayfire.com\/licenses\/BSD-3-Clause\n ********************************************************\/\n\n#include <vector>\n#include <cassert>\n\n#include <af\/array.h>\n#include <af\/index.h>\n#include <ArrayInfo.hpp>\n#include <err_common.hpp>\n#include <handle.hpp>\n#include <backend.hpp>\n#include <Array.hpp>\n\nusing namespace detail;\nusing std::vector;\nusing std::swap;\n\ntemplate<typename T>\nstatic void indexArray(af_array &dest, const af_array &src, const unsigned ndims, const af_seq *index)\n{\n using af::toOffset;\n using af::toDims;\n using af::toStride;\n\n const Array<T> &parent = getArray<T>(src);\n vector<af_seq> index_(index, index+ndims);\n Array<T>* dst = createSubArray( parent,\n toDims(index_, parent.dims()),\n toOffset(index_, parent.dims()),\n toStride(index_, parent.dims()) );\n dest = getHandle(*dst);\n}\n\naf_err af_index(af_array *result, const af_array in, const unsigned ndims, const af_seq* index)\n{\n \/\/TODO: Check ndims agains max_dims\n af_err ret = AF_ERR_INTERNAL;\n af_array out;\n try {\n if(result) { out = *result; }\n\n switch(getInfo(in).getType()) {\n case f32: indexArray<float> (out, in, ndims, index); break;\n case c32: indexArray<cfloat> (out, in, ndims, index); break;\n case f64: indexArray<double> (out, in, ndims, index); break;\n case c64: indexArray<cdouble> (out, in, ndims, index); break;\n case b8: indexArray<char> (out, in, ndims, index); break;\n case s32: indexArray<int> (out, in, ndims, index); break;\n case u32: indexArray<unsigned>(out, in, ndims, index); break;\n case u8: indexArray<uchar> (out, in, ndims, index); break;\n default: ret = AF_ERR_NOT_SUPPORTED; break;\n }\n if(ret !=AF_ERR_NOT_SUPPORTED)\n ret = AF_SUCCESS;\n }\n CATCHALL\n\n swap(*result, out);\n return ret;\n}\n<commit_msg>Adding proper error checking macros to src\/api\/c\/index.cpp<commit_after>\/*******************************************************\n * Copyright (c) 2014, ArrayFire\n * All rights reserved.\n *\n * This file is distributed under 3-clause BSD license.\n * The complete license agreement can be obtained at:\n * http:\/\/arrayfire.com\/licenses\/BSD-3-Clause\n ********************************************************\/\n\n#include <vector>\n#include <cassert>\n\n#include <af\/array.h>\n#include <af\/index.h>\n#include <ArrayInfo.hpp>\n#include <err_common.hpp>\n#include <handle.hpp>\n#include <backend.hpp>\n#include <Array.hpp>\n\nusing namespace detail;\nusing std::vector;\nusing std::swap;\n\ntemplate<typename T>\nstatic void indexArray(af_array &dest, const af_array &src, const unsigned ndims, const af_seq *index)\n{\n using af::toOffset;\n using af::toDims;\n using af::toStride;\n\n const Array<T> &parent = getArray<T>(src);\n vector<af_seq> index_(index, index+ndims);\n Array<T>* dst = createSubArray( parent,\n toDims(index_, parent.dims()),\n toOffset(index_, parent.dims()),\n toStride(index_, parent.dims()) );\n dest = getHandle(*dst);\n}\n\naf_err af_index(af_array *result, const af_array in, const unsigned ndims, const af_seq* index)\n{\n af_array out;\n try {\n if(result) { out = *result; }\n\n af_dtype in_type = getInfo(in).getType();\n\n switch(in_type) {\n case f32: indexArray<float> (out, in, ndims, index); break;\n case c32: indexArray<cfloat> (out, in, ndims, index); break;\n case f64: indexArray<double> (out, in, ndims, index); break;\n case c64: indexArray<cdouble> (out, in, ndims, index); break;\n case b8: indexArray<char> (out, in, ndims, index); break;\n case s32: indexArray<int> (out, in, ndims, index); break;\n case u32: indexArray<unsigned>(out, in, ndims, index); break;\n case u8: indexArray<uchar> (out, in, ndims, index); break;\n default: TYPE_ERROR(1, in_type);\n }\n }\n CATCHALL\n\n swap(*result, out);\n return AF_SUCCESS;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (C) 2011 Scientific Computation Research Center\n *\n * This work is open source software, licensed under the terms of the\n * BSD license as described in the LICENSE file in the top-level directory.\n *\/\n\n\/* see Bousetta et al.\n \"Adaptive remeshing based on a posteriori error estimation\n for forging simulation\" *\/\n\n#include \"spr.h\"\n\n#include <PCU.h>\n#include <apfMesh.h>\n#include <apfShape.h>\n#include <apfCavityOp.h>\n\n#include <limits>\n#include <cassert>\n\nnamespace spr {\nnamespace target {\n\nstruct Estimation {\n apf::Mesh* mesh;\n int integration_order;\n int recovered_order;\n apf::Field* eps;\n apf::Field* eps_star;\n size_t target_number;\n double size_factor;\n double alpha;\n double beta;\n apf::Field* elem_size;\n apf::Field* vtx_size;\n};\n\nstatic void setupEstimation(\n Estimation* e,\n apf::Field* eps,\n size_t target,\n double alpha,\n double beta)\n{\n e->mesh = apf::getMesh(eps);\n e->integration_order = apf::getShape(eps)->getOrder();\n e->recovered_order = e->mesh->getShape()->getOrder();\n e->eps = eps;\n e->eps_star = 0;\n e->target_number = target;\n e->size_factor = 0;\n e->alpha = alpha;\n e->beta = beta;\n e->elem_size = 0;\n e->vtx_size = 0;\n}\n\nclass ScalarIntegrator : public apf::Integrator\n{\n public:\n ScalarIntegrator(int order):\n apf::Integrator(order),\n result(0)\n {\n }\n void parallelReduce()\n {\n PCU_Add_Doubles(&result,1);\n }\n double result;\n};\n\nclass ElementError : public ScalarIntegrator\n{\n public:\n ElementError(Estimation* e):\n ScalarIntegrator(e->integration_order),\n estimation(e),\n element(0),\n entity(0),\n sum(0),\n ip(0)\n {\n v1.setSize(apf::countComponents(e->eps));\n v2.setSize(apf::countComponents(e->eps_star));\n }\n void inElement(apf::MeshElement* meshElement)\n {\n element = apf::createElement(estimation->eps_star, meshElement);\n entity = apf::getMeshEntity(meshElement);\n sum = 0;\n ip = 0;\n }\n void outElement()\n {\n apf::destroyElement(element);\n }\n void atPoint(apf::Vector3 const& xi, double w, double dv)\n {\n apf::getComponents(estimation->eps, entity, ip, &v1[0]);\n apf::getComponents(element, xi, &v2[0]);\n apf::DynamicVector& diff = v1;\n diff -= v2;\n sum += (diff*diff)*w*dv;\n ++ip;\n }\n Estimation* estimation;\n apf::Element* element;\n apf::MeshEntity* entity;\n double sum;\n int ip;\n apf::DynamicVector v1,v2;\n};\n\nclass GlobalErrorTerm : public ElementError\n{\n public:\n GlobalErrorTerm(Estimation* e) : ElementError(e) {}\n void outElement()\n {\n ElementError::outElement();\n double d = estimation->mesh->getDimension();\n double p = estimation->recovered_order;\n result += pow(sqrt(sum), ((2*d)\/(2*p+d)));\n }\n};\n\nstatic void computeSizeFactor(Estimation* e)\n{\n GlobalErrorTerm globalError(e);\n globalError.process(e->mesh);\n int d = e->mesh->getDimension();\n double G = globalError.result;\n double N = e->target_number;\n e->size_factor = pow((G\/N), (1.0\/d));\n}\n\nstatic double getCurrentSize(apf::Mesh* m, apf::MeshEntity* e)\n{\n double h=0;\n apf::Downward edges;\n int ne = m->getDownward(e,1,edges);\n for (int i=0; i < ne; ++i)\n h = std::max(h, apf::measure(m, edges[i]));\n return h;\n}\n\nstatic double getNewSize(Estimation* e, apf::MeshEntity* ent)\n{\n ElementError elemError(e);\n apf::MeshElement* elem = apf::createMeshElement(e->mesh, ent);\n elemError.process(elem);\n int p = e->recovered_order;\n int d = e->mesh->getDimension();\n double h = getCurrentSize(e->mesh, ent);\n double theta_e = sqrt(elemError.sum);\n double r = pow(theta_e, ((-2.0)\/(2.0*p+d)));\n double h_new = e->size_factor * r * h;\n if (h_new < e->alpha*h) h_new = e->alpha*h;\n if (h_new > e->beta*h) h_new = e->beta*h;\n return h_new;\n}\n\nstatic void getElemSizeField(Estimation* e)\n{\n apf::Field* esize = apf::createStepField(e->mesh,\"esize\",apf::SCALAR);\n int d = e->mesh->getDimension();\n apf::MeshEntity* elem;\n apf::MeshIterator* elems = e->mesh->begin(d);\n while ((elem = e->mesh->iterate(elems))) {\n double h = getNewSize(e, elem);\n apf::setScalar(esize, elem, 0, h);\n }\n e->mesh->end(elems);\n e->elem_size = esize;\n}\n\nstatic void avgToVtx(apf::Field* ef, apf::Field* vf, apf::MeshEntity* ent)\n{\n apf::Mesh* m = apf::getMesh(ef);\n apf::Adjacent elems;\n m->getAdjacent(ent, m->getDimension(), elems);\n double s = 0;\n for (size_t i=0; i < elems.getSize(); ++i)\n s += apf::getScalar(ef, elems[i], 0);\n s \/= elems.getSize();\n apf::setScalar(vf, ent, 0, s);\n}\n\nclass AverageOp : public apf::CavityOp\n{\n public:\n AverageOp(Estimation* est):\n apf::CavityOp(est->mesh),\n estimation(est),\n entity(0)\n {\n }\n virtual Outcome setEntity(apf::MeshEntity* e)\n {\n entity = e;\n if (apf::hasEntity(estimation->vtx_size, entity))\n return SKIP;\n if ( ! requestLocality(&entity, 1))\n return REQUEST;\n return OK;\n }\n virtual void apply()\n {\n avgToVtx(\n estimation->elem_size,\n estimation->vtx_size,\n entity);\n }\n Estimation* estimation;\n apf::MeshEntity* entity;\n};\n\nstatic void averageSizeField(Estimation* e)\n{\n e->vtx_size =\n apf::createLagrangeField(e->mesh, \"size\", apf::SCALAR, 1);\n AverageOp op(e);\n op.applyToDimension(0);\n}\n\nstatic void estimateError(Estimation* e)\n{\n e->eps_star = recoverField(e->eps);\n computeSizeFactor(e);\n getElemSizeField(e);\n apf::destroyField(e->eps_star);\n averageSizeField(e);\n apf::destroyField(e->elem_size);\n}\n\n}\n\napf::Field* getTargetSPRSizeField(\n apf::Field* eps,\n size_t target,\n double alpha,\n double beta)\n{\n double t0 = PCU_Time();\n assert(target > 0);\n assert(alpha < beta);\n target::Estimation e;\n target::setupEstimation(&e, eps, target, alpha, beta);\n target::estimateError(&e);\n double t1 = PCU_Time();\n if (!PCU_Comm_Self())\n fprintf(stderr, \"SPR (target): error estimated in %f seconds\\n\",t1-t0);\n return e.vtx_size;\n}\n\n}\n<commit_msg>spr: more correct citation<commit_after>\/*\n * Copyright (C) 2011 Scientific Computation Research Center\n *\n * This work is open source software, licensed under the terms of the\n * BSD license as described in the LICENSE file in the top-level directory.\n *\/\n\n\/* see Boussetta, Ramzy et al.\n \"Adaptive remeshing based on a posteriori error estimation\n for forging simulation.\" Computer methods in applied mechanics\n and engineering 195.48 (2006): 6626-6645. *\/\n\n#include \"spr.h\"\n\n#include <PCU.h>\n#include <apfMesh.h>\n#include <apfShape.h>\n#include <apfCavityOp.h>\n\n#include <limits>\n#include <cassert>\n\nnamespace spr {\nnamespace target {\n\nstruct Estimation {\n apf::Mesh* mesh;\n int integration_order;\n int recovered_order;\n apf::Field* eps;\n apf::Field* eps_star;\n size_t target_number;\n double size_factor;\n double alpha;\n double beta;\n apf::Field* elem_size;\n apf::Field* vtx_size;\n};\n\nstatic void setupEstimation(\n Estimation* e,\n apf::Field* eps,\n size_t target,\n double alpha,\n double beta)\n{\n e->mesh = apf::getMesh(eps);\n e->integration_order = apf::getShape(eps)->getOrder();\n e->recovered_order = e->mesh->getShape()->getOrder();\n e->eps = eps;\n e->eps_star = 0;\n e->target_number = target;\n e->size_factor = 0;\n e->alpha = alpha;\n e->beta = beta;\n e->elem_size = 0;\n e->vtx_size = 0;\n}\n\nclass ScalarIntegrator : public apf::Integrator\n{\n public:\n ScalarIntegrator(int order):\n apf::Integrator(order),\n result(0)\n {\n }\n void parallelReduce()\n {\n PCU_Add_Doubles(&result,1);\n }\n double result;\n};\n\nclass ElementError : public ScalarIntegrator\n{\n public:\n ElementError(Estimation* e):\n ScalarIntegrator(e->integration_order),\n estimation(e),\n element(0),\n entity(0),\n sum(0),\n ip(0)\n {\n v1.setSize(apf::countComponents(e->eps));\n v2.setSize(apf::countComponents(e->eps_star));\n }\n void inElement(apf::MeshElement* meshElement)\n {\n element = apf::createElement(estimation->eps_star, meshElement);\n entity = apf::getMeshEntity(meshElement);\n sum = 0;\n ip = 0;\n }\n void outElement()\n {\n apf::destroyElement(element);\n }\n void atPoint(apf::Vector3 const& xi, double w, double dv)\n {\n apf::getComponents(estimation->eps, entity, ip, &v1[0]);\n apf::getComponents(element, xi, &v2[0]);\n apf::DynamicVector& diff = v1;\n diff -= v2;\n sum += (diff*diff)*w*dv;\n ++ip;\n }\n Estimation* estimation;\n apf::Element* element;\n apf::MeshEntity* entity;\n double sum;\n int ip;\n apf::DynamicVector v1,v2;\n};\n\nclass GlobalErrorTerm : public ElementError\n{\n public:\n GlobalErrorTerm(Estimation* e) : ElementError(e) {}\n void outElement()\n {\n ElementError::outElement();\n double d = estimation->mesh->getDimension();\n double p = estimation->recovered_order;\n result += pow(sqrt(sum), ((2*d)\/(2*p+d)));\n }\n};\n\nstatic void computeSizeFactor(Estimation* e)\n{\n GlobalErrorTerm globalError(e);\n globalError.process(e->mesh);\n int d = e->mesh->getDimension();\n double G = globalError.result;\n double N = e->target_number;\n e->size_factor = pow((G\/N), (1.0\/d));\n}\n\nstatic double getCurrentSize(apf::Mesh* m, apf::MeshEntity* e)\n{\n double h=0;\n apf::Downward edges;\n int ne = m->getDownward(e,1,edges);\n for (int i=0; i < ne; ++i)\n h = std::max(h, apf::measure(m, edges[i]));\n return h;\n}\n\nstatic double getNewSize(Estimation* e, apf::MeshEntity* ent)\n{\n ElementError elemError(e);\n apf::MeshElement* elem = apf::createMeshElement(e->mesh, ent);\n elemError.process(elem);\n int p = e->recovered_order;\n int d = e->mesh->getDimension();\n double h = getCurrentSize(e->mesh, ent);\n double theta_e = sqrt(elemError.sum);\n double r = pow(theta_e, ((-2.0)\/(2.0*p+d)));\n double h_new = e->size_factor * r * h;\n if (h_new < e->alpha*h) h_new = e->alpha*h;\n if (h_new > e->beta*h) h_new = e->beta*h;\n return h_new;\n}\n\nstatic void getElemSizeField(Estimation* e)\n{\n apf::Field* esize = apf::createStepField(e->mesh,\"esize\",apf::SCALAR);\n int d = e->mesh->getDimension();\n apf::MeshEntity* elem;\n apf::MeshIterator* elems = e->mesh->begin(d);\n while ((elem = e->mesh->iterate(elems))) {\n double h = getNewSize(e, elem);\n apf::setScalar(esize, elem, 0, h);\n }\n e->mesh->end(elems);\n e->elem_size = esize;\n}\n\nstatic void avgToVtx(apf::Field* ef, apf::Field* vf, apf::MeshEntity* ent)\n{\n apf::Mesh* m = apf::getMesh(ef);\n apf::Adjacent elems;\n m->getAdjacent(ent, m->getDimension(), elems);\n double s = 0;\n for (size_t i=0; i < elems.getSize(); ++i)\n s += apf::getScalar(ef, elems[i], 0);\n s \/= elems.getSize();\n apf::setScalar(vf, ent, 0, s);\n}\n\nclass AverageOp : public apf::CavityOp\n{\n public:\n AverageOp(Estimation* est):\n apf::CavityOp(est->mesh),\n estimation(est),\n entity(0)\n {\n }\n virtual Outcome setEntity(apf::MeshEntity* e)\n {\n entity = e;\n if (apf::hasEntity(estimation->vtx_size, entity))\n return SKIP;\n if ( ! requestLocality(&entity, 1))\n return REQUEST;\n return OK;\n }\n virtual void apply()\n {\n avgToVtx(\n estimation->elem_size,\n estimation->vtx_size,\n entity);\n }\n Estimation* estimation;\n apf::MeshEntity* entity;\n};\n\nstatic void averageSizeField(Estimation* e)\n{\n e->vtx_size =\n apf::createLagrangeField(e->mesh, \"size\", apf::SCALAR, 1);\n AverageOp op(e);\n op.applyToDimension(0);\n}\n\nstatic void estimateError(Estimation* e)\n{\n e->eps_star = recoverField(e->eps);\n computeSizeFactor(e);\n getElemSizeField(e);\n apf::destroyField(e->eps_star);\n averageSizeField(e);\n apf::destroyField(e->elem_size);\n}\n\n}\n\napf::Field* getTargetSPRSizeField(\n apf::Field* eps,\n size_t target,\n double alpha,\n double beta)\n{\n double t0 = PCU_Time();\n assert(target > 0);\n assert(alpha < beta);\n target::Estimation e;\n target::setupEstimation(&e, eps, target, alpha, beta);\n target::estimateError(&e);\n double t1 = PCU_Time();\n if (!PCU_Comm_Self())\n fprintf(stderr, \"SPR (target): error estimated in %f seconds\\n\",t1-t0);\n return e.vtx_size;\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n\nThis file is part of VROOM.\n\nCopyright (c) 2015-2022, Julien Coupey.\nAll rights reserved (see LICENSE).\n\n*\/\n\n#include <mutex>\n#include <set>\n#include <thread>\n\n#include \"algorithms\/heuristics\/heuristics.h\"\n#include \"algorithms\/local_search\/local_search.h\"\n#include \"problems\/cvrp\/cvrp.h\"\n#include \"problems\/cvrp\/operators\/cross_exchange.h\"\n#include \"problems\/cvrp\/operators\/intra_cross_exchange.h\"\n#include \"problems\/cvrp\/operators\/intra_exchange.h\"\n#include \"problems\/cvrp\/operators\/intra_mixed_exchange.h\"\n#include \"problems\/cvrp\/operators\/intra_or_opt.h\"\n#include \"problems\/cvrp\/operators\/intra_relocate.h\"\n#include \"problems\/cvrp\/operators\/intra_two_opt.h\"\n#include \"problems\/cvrp\/operators\/mixed_exchange.h\"\n#include \"problems\/cvrp\/operators\/or_opt.h\"\n#include \"problems\/cvrp\/operators\/pd_shift.h\"\n#include \"problems\/cvrp\/operators\/relocate.h\"\n#include \"problems\/cvrp\/operators\/reverse_two_opt.h\"\n#include \"problems\/cvrp\/operators\/route_exchange.h\"\n#include \"problems\/cvrp\/operators\/swap_star.h\"\n#include \"problems\/cvrp\/operators\/two_opt.h\"\n#include \"problems\/cvrp\/operators\/unassigned_exchange.h\"\n#include \"problems\/tsp\/tsp.h\"\n#include \"utils\/helpers.h\"\n\nnamespace vroom {\n\nusing RawSolution = std::vector<RawRoute>;\n\nnamespace cvrp {\n\nusing LocalSearch = ls::LocalSearch<RawRoute,\n cvrp::UnassignedExchange,\n cvrp::SwapStar,\n cvrp::CrossExchange,\n cvrp::MixedExchange,\n cvrp::TwoOpt,\n cvrp::ReverseTwoOpt,\n cvrp::Relocate,\n cvrp::OrOpt,\n cvrp::IntraExchange,\n cvrp::IntraCrossExchange,\n cvrp::IntraMixedExchange,\n cvrp::IntraRelocate,\n cvrp::IntraOrOpt,\n cvrp::IntraTwoOpt,\n cvrp::PDShift,\n cvrp::RouteExchange>;\n} \/\/ namespace cvrp\n\nconst std::vector<HeuristicParameters> CVRP::homogeneous_parameters =\n {HeuristicParameters(HEURISTIC::BASIC, INIT::NONE, 0.3),\n HeuristicParameters(HEURISTIC::BASIC, INIT::HIGHER_AMOUNT, 0.1),\n HeuristicParameters(HEURISTIC::BASIC, INIT::HIGHER_AMOUNT, 0.5),\n HeuristicParameters(HEURISTIC::BASIC, INIT::FURTHEST, 0.3),\n\n HeuristicParameters(HEURISTIC::BASIC, INIT::NONE, 0.7),\n HeuristicParameters(HEURISTIC::BASIC, INIT::HIGHER_AMOUNT, 0.3),\n HeuristicParameters(HEURISTIC::BASIC, INIT::HIGHER_AMOUNT, 2.1),\n HeuristicParameters(HEURISTIC::BASIC, INIT::FURTHEST, 0.2),\n\n HeuristicParameters(HEURISTIC::BASIC, INIT::NONE, 0.1),\n HeuristicParameters(HEURISTIC::BASIC, INIT::NONE, 0.6),\n HeuristicParameters(HEURISTIC::BASIC, INIT::NONE, 0.9),\n HeuristicParameters(HEURISTIC::BASIC, INIT::HIGHER_AMOUNT, 2.4),\n\n HeuristicParameters(HEURISTIC::BASIC, INIT::HIGHER_AMOUNT, 0.2),\n HeuristicParameters(HEURISTIC::BASIC, INIT::HIGHER_AMOUNT, 0.8),\n HeuristicParameters(HEURISTIC::BASIC, INIT::HIGHER_AMOUNT, 1.2),\n HeuristicParameters(HEURISTIC::BASIC, INIT::FURTHEST, 0.4),\n\n HeuristicParameters(HEURISTIC::BASIC, INIT::NONE, 1.2),\n HeuristicParameters(HEURISTIC::BASIC, INIT::HIGHER_AMOUNT, 1),\n HeuristicParameters(HEURISTIC::BASIC, INIT::HIGHER_AMOUNT, 1.1),\n HeuristicParameters(HEURISTIC::BASIC, INIT::FURTHEST, 2.4),\n\n HeuristicParameters(HEURISTIC::BASIC, INIT::NONE, 0.2),\n HeuristicParameters(HEURISTIC::BASIC, INIT::HIGHER_AMOUNT, 0),\n HeuristicParameters(HEURISTIC::BASIC, INIT::HIGHER_AMOUNT, 0.9),\n HeuristicParameters(HEURISTIC::BASIC, INIT::FURTHEST, 1.5),\n\n HeuristicParameters(HEURISTIC::BASIC, INIT::NONE, 0.5),\n HeuristicParameters(HEURISTIC::BASIC, INIT::NONE, 1.3),\n HeuristicParameters(HEURISTIC::BASIC, INIT::HIGHER_AMOUNT, 1.5),\n HeuristicParameters(HEURISTIC::BASIC, INIT::FURTHEST, 0.1),\n\n HeuristicParameters(HEURISTIC::BASIC, INIT::NONE, 0.4),\n HeuristicParameters(HEURISTIC::BASIC, INIT::NONE, 1.6),\n HeuristicParameters(HEURISTIC::BASIC, INIT::HIGHER_AMOUNT, 0.6),\n HeuristicParameters(HEURISTIC::BASIC, INIT::FURTHEST, 0.5)};\n\nconst std::vector<HeuristicParameters> CVRP::heterogeneous_parameters =\n {HeuristicParameters(HEURISTIC::DYNAMIC, INIT::NONE, 0.4),\n HeuristicParameters(HEURISTIC::DYNAMIC, INIT::HIGHER_AMOUNT, 0.2),\n HeuristicParameters(HEURISTIC::DYNAMIC, INIT::FURTHEST, 0.1),\n HeuristicParameters(HEURISTIC::DYNAMIC, INIT::FURTHEST, 0.3),\n\n HeuristicParameters(HEURISTIC::DYNAMIC, INIT::NONE, 0.3),\n HeuristicParameters(HEURISTIC::DYNAMIC, INIT::NONE, 0.6),\n HeuristicParameters(HEURISTIC::DYNAMIC, INIT::HIGHER_AMOUNT, 0.1),\n HeuristicParameters(HEURISTIC::DYNAMIC, INIT::FURTHEST, 0.2),\n\n HeuristicParameters(HEURISTIC::DYNAMIC, INIT::NONE, 0.2),\n HeuristicParameters(HEURISTIC::DYNAMIC, INIT::NONE, 0.9),\n HeuristicParameters(HEURISTIC::DYNAMIC, INIT::HIGHER_AMOUNT, 0.3),\n HeuristicParameters(HEURISTIC::DYNAMIC, INIT::FURTHEST, 0.4),\n\n HeuristicParameters(HEURISTIC::DYNAMIC, INIT::NONE, 0.1),\n HeuristicParameters(HEURISTIC::DYNAMIC, INIT::NONE, 0.5),\n HeuristicParameters(HEURISTIC::DYNAMIC, INIT::HIGHER_AMOUNT, 1.4),\n HeuristicParameters(HEURISTIC::DYNAMIC, INIT::FURTHEST, 0),\n\n HeuristicParameters(HEURISTIC::DYNAMIC, INIT::NONE, 2.1),\n HeuristicParameters(HEURISTIC::DYNAMIC, INIT::HIGHER_AMOUNT, 0),\n HeuristicParameters(HEURISTIC::DYNAMIC, INIT::HIGHER_AMOUNT, 0.8),\n HeuristicParameters(HEURISTIC::DYNAMIC, INIT::FURTHEST, 0.6),\n\n HeuristicParameters(HEURISTIC::DYNAMIC, INIT::NONE, 0),\n HeuristicParameters(HEURISTIC::DYNAMIC, INIT::NONE, 0.8),\n HeuristicParameters(HEURISTIC::DYNAMIC, INIT::HIGHER_AMOUNT, 0.4),\n HeuristicParameters(HEURISTIC::DYNAMIC, INIT::HIGHER_AMOUNT, 0.5),\n\n HeuristicParameters(HEURISTIC::DYNAMIC, INIT::HIGHER_AMOUNT, 0.6),\n HeuristicParameters(HEURISTIC::DYNAMIC, INIT::HIGHER_AMOUNT, 0.7),\n HeuristicParameters(HEURISTIC::DYNAMIC, INIT::HIGHER_AMOUNT, 1.2),\n HeuristicParameters(HEURISTIC::DYNAMIC, INIT::FURTHEST, 0.5),\n\n HeuristicParameters(HEURISTIC::DYNAMIC, INIT::NONE, 0.7),\n HeuristicParameters(HEURISTIC::DYNAMIC, INIT::HIGHER_AMOUNT, 1),\n HeuristicParameters(HEURISTIC::DYNAMIC, INIT::FURTHEST, 1.7),\n HeuristicParameters(HEURISTIC::DYNAMIC, INIT::FURTHEST, 2.2)};\n\nCVRP::CVRP(const Input& input) : VRP(input) {\n}\n\nSolution CVRP::solve(unsigned exploration_level,\n unsigned nb_threads,\n const Timeout& timeout,\n const std::vector<HeuristicParameters>& h_param) const {\n if (_input.vehicles.size() == 1 and !_input.has_skills() and\n _input.zero_amount().size() == 0 and !_input.has_shipments() and\n (_input.jobs.size() <= _input.vehicles[0].max_tasks) and\n _input.vehicles[0].steps.empty()) {\n \/\/ This is a plain TSP, no need to go through the trouble below.\n std::vector<Index> job_ranks(_input.jobs.size());\n std::iota(job_ranks.begin(), job_ranks.end(), 0);\n\n TSP p(_input, job_ranks, 0);\n\n RawRoute r(_input, 0, 0);\n r.set_route(_input, p.raw_solve(nb_threads, timeout));\n\n return utils::format_solution(_input, {r});\n }\n\n \/\/ Use vector of parameters when passed for debugging, else use\n \/\/ predefined parameter set.\n const auto& parameters = (!h_param.empty())\n ? h_param\n : (_input.has_homogeneous_locations())\n ? homogeneous_parameters\n : heterogeneous_parameters;\n unsigned max_nb_jobs_removal = exploration_level;\n unsigned nb_init_solutions = h_param.size();\n\n if (nb_init_solutions == 0) {\n \/\/ Local search parameter.\n nb_init_solutions = 4 * (exploration_level + 1);\n if (exploration_level >= 4) {\n nb_init_solutions += 4;\n }\n if (exploration_level >= 5) {\n nb_init_solutions += 4;\n }\n }\n assert(nb_init_solutions <= parameters.size());\n\n std::vector<RawSolution> solutions(nb_init_solutions);\n\n \/\/ Split the heuristic parameters among threads.\n std::vector<std::vector<std::size_t>>\n thread_ranks(nb_threads, std::vector<std::size_t>());\n for (std::size_t i = 0; i < nb_init_solutions; ++i) {\n thread_ranks[i % nb_threads].push_back(i);\n }\n\n std::exception_ptr ep = nullptr;\n std::mutex ep_m;\n\n auto run_heuristics = [&](const std::vector<std::size_t>& param_ranks) {\n try {\n for (auto rank : param_ranks) {\n auto& p = parameters[rank];\n\n switch (p.heuristic) {\n case HEURISTIC::INIT_ROUTES:\n solutions[rank] = heuristics::initial_routes<RawSolution>(_input);\n break;\n case HEURISTIC::BASIC:\n solutions[rank] =\n heuristics::basic<RawSolution>(_input, p.init, p.regret_coeff);\n break;\n case HEURISTIC::DYNAMIC:\n solutions[rank] =\n heuristics::dynamic_vehicle_choice<RawSolution>(_input,\n p.init,\n p.regret_coeff);\n break;\n }\n }\n } catch (...) {\n ep_m.lock();\n ep = std::current_exception();\n ep_m.unlock();\n }\n };\n\n std::vector<std::thread> heuristics_threads;\n\n for (const auto& param_ranks : thread_ranks) {\n if (!param_ranks.empty()) {\n heuristics_threads.emplace_back(run_heuristics, param_ranks);\n }\n }\n\n for (auto& t : heuristics_threads) {\n t.join();\n }\n\n if (ep != nullptr) {\n std::rethrow_exception(ep);\n }\n\n \/\/ Filter out duplicate heuristics solutions.\n std::set<utils::SolutionIndicators<RawRoute>> unique_indicators;\n std::vector<unsigned> to_remove;\n for (unsigned i = 0; i < solutions.size(); ++i) {\n const auto result = unique_indicators.emplace(_input, solutions[i]);\n if (!result.second) {\n \/\/ No insertion means an equivalent solution already exists.\n to_remove.push_back(i);\n }\n }\n\n for (auto remove_rank = to_remove.rbegin(); remove_rank != to_remove.rend();\n remove_rank++) {\n solutions.erase(solutions.begin() + *remove_rank);\n }\n\n \/\/ Split local searches across threads.\n unsigned nb_solutions = solutions.size();\n std::vector<utils::SolutionIndicators<RawRoute>> sol_indicators(nb_solutions);\n#ifdef LOG_LS_OPERATORS\n std::vector<std::array<ls::OperatorStats, OperatorName::MAX>> ls_stats(\n nb_solutions);\n#endif\n\n std::fill(thread_ranks.begin(),\n thread_ranks.end(),\n std::vector<std::size_t>());\n for (std::size_t i = 0; i < nb_solutions; ++i) {\n thread_ranks[i % nb_threads].push_back(i);\n }\n\n auto run_ls = [&](const std::vector<std::size_t>& sol_ranks) {\n try {\n \/\/ Decide time allocated for each search.\n Timeout search_time;\n if (timeout.has_value()) {\n search_time = timeout.value() \/ sol_ranks.size();\n }\n\n for (auto rank : sol_ranks) {\n \/\/ Local search phase.\n cvrp::LocalSearch ls(_input,\n solutions[rank],\n max_nb_jobs_removal,\n search_time);\n ls.run();\n\n \/\/ Store solution indicators.\n sol_indicators[rank] = ls.indicators();\n#ifdef LOG_LS_OPERATORS\n ls_stats[rank] = ls.get_stats();\n#endif\n }\n } catch (...) {\n ep_m.lock();\n ep = std::current_exception();\n ep_m.unlock();\n }\n };\n\n std::vector<std::thread> ls_threads;\n\n for (const auto& sol_ranks : thread_ranks) {\n if (!sol_ranks.empty()) {\n ls_threads.emplace_back(run_ls, sol_ranks);\n }\n }\n\n for (auto& t : ls_threads) {\n t.join();\n }\n\n if (ep != nullptr) {\n std::rethrow_exception(ep);\n }\n\n#ifdef LOG_LS_OPERATORS\n utils::log_LS_operators(ls_stats);\n#endif\n\n auto best_indic =\n std::min_element(sol_indicators.cbegin(), sol_indicators.cend());\n\n return utils::format_solution(_input,\n solutions[std::distance(sol_indicators.cbegin(),\n best_indic)]);\n}\n\n} \/\/ namespace vroom\n<commit_msg>Change CVRP to use VRP::solve()<commit_after>\/*\n\nThis file is part of VROOM.\n\nCopyright (c) 2015-2022, Julien Coupey.\nAll rights reserved (see LICENSE).\n\n*\/\n\n#include <mutex>\n#include <set>\n#include <thread>\n\n#include \"algorithms\/heuristics\/heuristics.h\"\n#include \"algorithms\/local_search\/local_search.h\"\n#include \"problems\/cvrp\/cvrp.h\"\n#include \"problems\/cvrp\/operators\/cross_exchange.h\"\n#include \"problems\/cvrp\/operators\/intra_cross_exchange.h\"\n#include \"problems\/cvrp\/operators\/intra_exchange.h\"\n#include \"problems\/cvrp\/operators\/intra_mixed_exchange.h\"\n#include \"problems\/cvrp\/operators\/intra_or_opt.h\"\n#include \"problems\/cvrp\/operators\/intra_relocate.h\"\n#include \"problems\/cvrp\/operators\/intra_two_opt.h\"\n#include \"problems\/cvrp\/operators\/mixed_exchange.h\"\n#include \"problems\/cvrp\/operators\/or_opt.h\"\n#include \"problems\/cvrp\/operators\/pd_shift.h\"\n#include \"problems\/cvrp\/operators\/relocate.h\"\n#include \"problems\/cvrp\/operators\/reverse_two_opt.h\"\n#include \"problems\/cvrp\/operators\/route_exchange.h\"\n#include \"problems\/cvrp\/operators\/swap_star.h\"\n#include \"problems\/cvrp\/operators\/two_opt.h\"\n#include \"problems\/cvrp\/operators\/unassigned_exchange.h\"\n#include \"problems\/tsp\/tsp.h\"\n#include \"utils\/helpers.h\"\n\nnamespace vroom {\n\nusing RawSolution = std::vector<RawRoute>;\n\nnamespace cvrp {\n\nusing LocalSearch = ls::LocalSearch<RawRoute,\n cvrp::UnassignedExchange,\n cvrp::SwapStar,\n cvrp::CrossExchange,\n cvrp::MixedExchange,\n cvrp::TwoOpt,\n cvrp::ReverseTwoOpt,\n cvrp::Relocate,\n cvrp::OrOpt,\n cvrp::IntraExchange,\n cvrp::IntraCrossExchange,\n cvrp::IntraMixedExchange,\n cvrp::IntraRelocate,\n cvrp::IntraOrOpt,\n cvrp::IntraTwoOpt,\n cvrp::PDShift,\n cvrp::RouteExchange>;\n} \/\/ namespace cvrp\n\nconst std::vector<HeuristicParameters> CVRP::homogeneous_parameters =\n {HeuristicParameters(HEURISTIC::BASIC, INIT::NONE, 0.3),\n HeuristicParameters(HEURISTIC::BASIC, INIT::HIGHER_AMOUNT, 0.1),\n HeuristicParameters(HEURISTIC::BASIC, INIT::HIGHER_AMOUNT, 0.5),\n HeuristicParameters(HEURISTIC::BASIC, INIT::FURTHEST, 0.3),\n\n HeuristicParameters(HEURISTIC::BASIC, INIT::NONE, 0.7),\n HeuristicParameters(HEURISTIC::BASIC, INIT::HIGHER_AMOUNT, 0.3),\n HeuristicParameters(HEURISTIC::BASIC, INIT::HIGHER_AMOUNT, 2.1),\n HeuristicParameters(HEURISTIC::BASIC, INIT::FURTHEST, 0.2),\n\n HeuristicParameters(HEURISTIC::BASIC, INIT::NONE, 0.1),\n HeuristicParameters(HEURISTIC::BASIC, INIT::NONE, 0.6),\n HeuristicParameters(HEURISTIC::BASIC, INIT::NONE, 0.9),\n HeuristicParameters(HEURISTIC::BASIC, INIT::HIGHER_AMOUNT, 2.4),\n\n HeuristicParameters(HEURISTIC::BASIC, INIT::HIGHER_AMOUNT, 0.2),\n HeuristicParameters(HEURISTIC::BASIC, INIT::HIGHER_AMOUNT, 0.8),\n HeuristicParameters(HEURISTIC::BASIC, INIT::HIGHER_AMOUNT, 1.2),\n HeuristicParameters(HEURISTIC::BASIC, INIT::FURTHEST, 0.4),\n\n HeuristicParameters(HEURISTIC::BASIC, INIT::NONE, 1.2),\n HeuristicParameters(HEURISTIC::BASIC, INIT::HIGHER_AMOUNT, 1),\n HeuristicParameters(HEURISTIC::BASIC, INIT::HIGHER_AMOUNT, 1.1),\n HeuristicParameters(HEURISTIC::BASIC, INIT::FURTHEST, 2.4),\n\n HeuristicParameters(HEURISTIC::BASIC, INIT::NONE, 0.2),\n HeuristicParameters(HEURISTIC::BASIC, INIT::HIGHER_AMOUNT, 0),\n HeuristicParameters(HEURISTIC::BASIC, INIT::HIGHER_AMOUNT, 0.9),\n HeuristicParameters(HEURISTIC::BASIC, INIT::FURTHEST, 1.5),\n\n HeuristicParameters(HEURISTIC::BASIC, INIT::NONE, 0.5),\n HeuristicParameters(HEURISTIC::BASIC, INIT::NONE, 1.3),\n HeuristicParameters(HEURISTIC::BASIC, INIT::HIGHER_AMOUNT, 1.5),\n HeuristicParameters(HEURISTIC::BASIC, INIT::FURTHEST, 0.1),\n\n HeuristicParameters(HEURISTIC::BASIC, INIT::NONE, 0.4),\n HeuristicParameters(HEURISTIC::BASIC, INIT::NONE, 1.6),\n HeuristicParameters(HEURISTIC::BASIC, INIT::HIGHER_AMOUNT, 0.6),\n HeuristicParameters(HEURISTIC::BASIC, INIT::FURTHEST, 0.5)};\n\nconst std::vector<HeuristicParameters> CVRP::heterogeneous_parameters =\n {HeuristicParameters(HEURISTIC::DYNAMIC, INIT::NONE, 0.4),\n HeuristicParameters(HEURISTIC::DYNAMIC, INIT::HIGHER_AMOUNT, 0.2),\n HeuristicParameters(HEURISTIC::DYNAMIC, INIT::FURTHEST, 0.1),\n HeuristicParameters(HEURISTIC::DYNAMIC, INIT::FURTHEST, 0.3),\n\n HeuristicParameters(HEURISTIC::DYNAMIC, INIT::NONE, 0.3),\n HeuristicParameters(HEURISTIC::DYNAMIC, INIT::NONE, 0.6),\n HeuristicParameters(HEURISTIC::DYNAMIC, INIT::HIGHER_AMOUNT, 0.1),\n HeuristicParameters(HEURISTIC::DYNAMIC, INIT::FURTHEST, 0.2),\n\n HeuristicParameters(HEURISTIC::DYNAMIC, INIT::NONE, 0.2),\n HeuristicParameters(HEURISTIC::DYNAMIC, INIT::NONE, 0.9),\n HeuristicParameters(HEURISTIC::DYNAMIC, INIT::HIGHER_AMOUNT, 0.3),\n HeuristicParameters(HEURISTIC::DYNAMIC, INIT::FURTHEST, 0.4),\n\n HeuristicParameters(HEURISTIC::DYNAMIC, INIT::NONE, 0.1),\n HeuristicParameters(HEURISTIC::DYNAMIC, INIT::NONE, 0.5),\n HeuristicParameters(HEURISTIC::DYNAMIC, INIT::HIGHER_AMOUNT, 1.4),\n HeuristicParameters(HEURISTIC::DYNAMIC, INIT::FURTHEST, 0),\n\n HeuristicParameters(HEURISTIC::DYNAMIC, INIT::NONE, 2.1),\n HeuristicParameters(HEURISTIC::DYNAMIC, INIT::HIGHER_AMOUNT, 0),\n HeuristicParameters(HEURISTIC::DYNAMIC, INIT::HIGHER_AMOUNT, 0.8),\n HeuristicParameters(HEURISTIC::DYNAMIC, INIT::FURTHEST, 0.6),\n\n HeuristicParameters(HEURISTIC::DYNAMIC, INIT::NONE, 0),\n HeuristicParameters(HEURISTIC::DYNAMIC, INIT::NONE, 0.8),\n HeuristicParameters(HEURISTIC::DYNAMIC, INIT::HIGHER_AMOUNT, 0.4),\n HeuristicParameters(HEURISTIC::DYNAMIC, INIT::HIGHER_AMOUNT, 0.5),\n\n HeuristicParameters(HEURISTIC::DYNAMIC, INIT::HIGHER_AMOUNT, 0.6),\n HeuristicParameters(HEURISTIC::DYNAMIC, INIT::HIGHER_AMOUNT, 0.7),\n HeuristicParameters(HEURISTIC::DYNAMIC, INIT::HIGHER_AMOUNT, 1.2),\n HeuristicParameters(HEURISTIC::DYNAMIC, INIT::FURTHEST, 0.5),\n\n HeuristicParameters(HEURISTIC::DYNAMIC, INIT::NONE, 0.7),\n HeuristicParameters(HEURISTIC::DYNAMIC, INIT::HIGHER_AMOUNT, 1),\n HeuristicParameters(HEURISTIC::DYNAMIC, INIT::FURTHEST, 1.7),\n HeuristicParameters(HEURISTIC::DYNAMIC, INIT::FURTHEST, 2.2)};\n\nCVRP::CVRP(const Input& input) : VRP(input) {\n}\n\nSolution CVRP::solve(unsigned exploration_level,\n unsigned nb_threads,\n const Timeout& timeout,\n const std::vector<HeuristicParameters>& h_param) const {\n if (_input.vehicles.size() == 1 and !_input.has_skills() and\n _input.zero_amount().size() == 0 and !_input.has_shipments() and\n (_input.jobs.size() <= _input.vehicles[0].max_tasks) and\n _input.vehicles[0].steps.empty()) {\n \/\/ This is a plain TSP, no need to go through the trouble below.\n std::vector<Index> job_ranks(_input.jobs.size());\n std::iota(job_ranks.begin(), job_ranks.end(), 0);\n\n TSP p(_input, job_ranks, 0);\n\n RawRoute r(_input, 0, 0);\n r.set_route(_input, p.raw_solve(nb_threads, timeout));\n\n return utils::format_solution(_input, {r});\n }\n\n return VRP::solve<RawRoute, RawSolution, cvrp::LocalSearch>(exploration_level, nb_threads, timeout, h_param, homogeneous_parameters, heterogeneous_parameters);\n}\n\n} \/\/ namespace vroom\n<|endoftext|>"} {"text":"<commit_before>#pragma once\n\n#include <unordered_set>\n\n#include \"types.hpp\"\n\nnamespace opossum {\n\n\/**\n * Abstract container class for the definition of table constraints based on a set of column ids.\n * Subclasses should leverage the OOP structure to add additional fields. In case of CHECK and FOREIGN KEY constraint\n * implementations, these fields may include check definitions and referenced keys.\n *\/\nclass AbstractTableConstraint {\n public:\n explicit AbstractTableConstraint(std::unordered_set<ColumnID> init_columns);\n virtual ~AbstractTableConstraint() = default;\n\n const std::unordered_set<ColumnID>& columns() const;\n\n bool operator==(const AbstractTableConstraint& rhs) const;\n bool operator!=(const AbstractTableConstraint& rhs) const;\n\n protected:\n \/**\n * Compare two table constraints of the same type. Only additional fields have to be compared since column ids are\n * already compared by the caller.\n *\/\n virtual bool _on_equals(const AbstractTableConstraint& table_constraint) const = 0;\n\n private:\n std::unordered_set<ColumnID> _columns;\n};\n\n} \/\/ namespace opossum\n<commit_msg>Fix missing constructors for AbstractTableConstraint (#2166)<commit_after>#pragma once\n\n#include <unordered_set>\n\n#include \"types.hpp\"\n\nnamespace opossum {\n\n\/**\n * Abstract container class for the definition of table constraints based on a set of column ids.\n * Subclasses should leverage the OOP structure to add additional fields. In case of CHECK and FOREIGN KEY constraint\n * implementations, these fields may include check definitions and referenced keys.\n *\/\nclass AbstractTableConstraint {\n public:\n explicit AbstractTableConstraint(std::unordered_set<ColumnID> init_columns);\n\n AbstractTableConstraint(const AbstractTableConstraint&) = default;\n AbstractTableConstraint(AbstractTableConstraint&&) = default;\n AbstractTableConstraint& operator=(const AbstractTableConstraint&) = default;\n AbstractTableConstraint& operator=(AbstractTableConstraint&&) = default;\n\n virtual ~AbstractTableConstraint() = default;\n\n const std::unordered_set<ColumnID>& columns() const;\n\n bool operator==(const AbstractTableConstraint& rhs) const;\n bool operator!=(const AbstractTableConstraint& rhs) const;\n\n protected:\n \/**\n * Compare two table constraints of the same type. Only additional fields have to be compared since column ids are\n * already compared by the caller.\n *\/\n virtual bool _on_equals(const AbstractTableConstraint& table_constraint) const = 0;\n\n private:\n std::unordered_set<ColumnID> _columns;\n};\n\n} \/\/ namespace opossum\n<|endoftext|>"} {"text":"<commit_before>\/*\n RawSpeed - RAW file decoder.\n\n Copyright (C) 2019 LibRaw LLC (info@libraw.org)\n Copyright (C) 2020 Roman Lebedev\n\n This library is free software; you can redistribute it and\/or\n modify it under the terms of the GNU Lesser General Public\n License as published by the Free Software Foundation; either\n version 2.1 of the License, or (at your option) any later version.\n\n This library is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n Lesser General Public License for more details.\n\n You should have received a copy of the GNU Lesser General Public\n License along with this library; if not, write to the Free Software\n Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n*\/\n\n#include \"decompressors\/PanasonicDecompressorV6.h\" \/\/ for PanasonicDecompre...\n#include \"common\/Point.h\" \/\/ for iPoint2D\n#include \"common\/RawImage.h\" \/\/ for RawImage, RawImag...\n#include \"decoders\/RawDecoderException.h\" \/\/ for ThrowRDE\n#include <algorithm> \/\/ for copy_n\n#include <array>\n#include <cstdint> \/\/ for uint16_t, uint32_t\n#include <cstdlib> \/\/ for free, malloc\n\nnamespace rawspeed {\n\nnamespace {\nstruct pana_cs6_page_decoder {\n std::array<unsigned int, 14> pixelbuffer;\n unsigned lastoffset, maxoffset;\n unsigned char current;\n const unsigned char* buffer;\n pana_cs6_page_decoder(const unsigned char* _buffer, unsigned int bsize)\n : lastoffset(0), maxoffset(bsize), current(0), buffer(_buffer) {}\n void read_page(); \/\/ will throw IO error if not enough space in buffer\n unsigned int nextpixel() { return current < 14 ? pixelbuffer[current++] : 0; }\n};\n\nvoid pana_cs6_page_decoder::read_page() {\n if (!buffer || (maxoffset - lastoffset < 16))\n ThrowRDE(\"Input failure\");\n auto wbuffer = [&](int i) {\n return static_cast<uint16_t>(buffer[lastoffset + 15 - i]);\n };\n pixelbuffer[0] = (wbuffer(0) << 6) | (wbuffer(1) >> 2); \/\/ 14 bit\n pixelbuffer[1] =\n (((wbuffer(1) & 0x3) << 12) | (wbuffer(2) << 4) | (wbuffer(3) >> 4)) &\n 0x3fff;\n pixelbuffer[2] = (wbuffer(3) >> 2) & 0x3;\n pixelbuffer[3] = ((wbuffer(3) & 0x3) << 8) | wbuffer(4);\n pixelbuffer[4] = (wbuffer(5) << 2) | (wbuffer(6) >> 6);\n pixelbuffer[5] = ((wbuffer(6) & 0x3f) << 4) | (wbuffer(7) >> 4);\n pixelbuffer[6] = (wbuffer(7) >> 2) & 0x3;\n pixelbuffer[7] = ((wbuffer(7) & 0x3) << 8) | wbuffer(8);\n pixelbuffer[8] = ((wbuffer(9) << 2) & 0x3fc) | (wbuffer(10) >> 6);\n pixelbuffer[9] = ((wbuffer(10) << 4) | (wbuffer(11) >> 4)) & 0x3ff;\n pixelbuffer[10] = (wbuffer(11) >> 2) & 0x3;\n pixelbuffer[11] = ((wbuffer(11) & 0x3) << 8) | wbuffer(12);\n pixelbuffer[12] = (((wbuffer(13) << 2) & 0x3fc) | wbuffer(14) >> 6) & 0x3ff;\n pixelbuffer[13] = ((wbuffer(14) << 4) | (wbuffer(15) >> 4)) & 0x3ff;\n#undef wbuffer\n current = 0;\n lastoffset += 16;\n}\n} \/\/ namespace\n\nPanasonicDecompressorV6::PanasonicDecompressorV6(const RawImage& img,\n ByteStream input_,\n uint32_t bps_)\n : mRaw(img), input(std::move(input_)) {\n if (mRaw->getCpp() != 1 || mRaw->getDataType() != TYPE_USHORT16 ||\n mRaw->getBpp() != sizeof(uint16_t))\n ThrowRDE(\"Unexpected component count \/ data type\");\n\n if (!mRaw->dim.hasPositiveArea()) {\n ThrowRDE(\"Unexpected image dimensions found: (%i; %i)\", mRaw->dim.x,\n mRaw->dim.y);\n }\n\n const int blocksperrow = mRaw->dim.x \/ 11;\n const int bytesPerRow = 16 * blocksperrow;\n const int bytesTotal = bytesPerRow * mRaw->dim.y;\n input = input_.peekStream(bytesTotal);\n}\n\nvoid PanasonicDecompressorV6::decompressBlock(ByteStream* rowInput, int row,\n int col) const {\n auto* rowptr = reinterpret_cast<uint16_t*>(mRaw->getDataUncropped(0, row));\n pana_cs6_page_decoder page(rowInput->getData(16), 16);\n page.read_page();\n std::array<unsigned int, 2> oddeven = {0, 0};\n std::array<unsigned int, 2> nonzero = {0, 0};\n unsigned pmul = 0;\n unsigned pixel_base = 0;\n for (int pix = 0; pix < 11; pix++) {\n if (pix % 3 == 2) {\n unsigned base = page.nextpixel();\n if (base > 3)\n ThrowRDE(\"Invariant failure\");\n if (base == 3)\n base = 4;\n pixel_base = 0x200 << base;\n pmul = 1 << base;\n }\n unsigned epixel = page.nextpixel();\n if (oddeven[pix % 2]) {\n epixel *= pmul;\n if (pixel_base < 0x2000 && nonzero[pix % 2] > pixel_base)\n epixel += nonzero[pix % 2] - pixel_base;\n nonzero[pix % 2] = epixel;\n } else {\n oddeven[pix % 2] = epixel;\n if (epixel)\n nonzero[pix % 2] = epixel;\n else\n epixel = nonzero[pix % 2];\n }\n auto spix = static_cast<unsigned>(static_cast<int>(epixel) - 0xf);\n if (spix <= 0xffff)\n rowptr[col++] = spix & 0xffff;\n else {\n epixel = static_cast<signed int>(epixel + 0x7ffffff1) >> 0x1f;\n rowptr[col++] = epixel & 0x3fff;\n }\n }\n}\n\nvoid PanasonicDecompressorV6::decompressRow(int row) const {\n const int blocksperrow = mRaw->dim.x \/ 11;\n const int bytesPerRow = 16 * blocksperrow;\n\n ByteStream rowInput = input.getSubStream(bytesPerRow * row, bytesPerRow);\n for (int rblock = 0, col = 0; rblock < blocksperrow; rblock++, col += 11)\n decompressBlock(&rowInput, row, col);\n}\n\nvoid PanasonicDecompressorV6::decompress() const {\n#ifdef HAVE_OPENMP\n#pragma omp parallel for num_threads(rawspeed_get_number_of_processor_cores()) \\\n schedule(static) default(none)\n#endif\n for (int row = 0; row < mRaw->dim.y; ++row) {\n try {\n decompressRow(row);\n } catch (RawspeedException& err) {\n \/\/ Propagate the exception out of OpenMP magic.\n mRaw->setError(err.what());\n }\n }\n\n std::string firstErr;\n if (mRaw->isTooManyErrors(1, &firstErr)) {\n ThrowRDE(\"Too many errors encountered. Giving up. First Error:\\n%s\",\n firstErr.c_str());\n }\n}\n\n} \/\/ namespace rawspeed\n<commit_msg>PanasonicDecompressorV6: use Array2DRef abstraction (-5%)<commit_after>\/*\n RawSpeed - RAW file decoder.\n\n Copyright (C) 2019 LibRaw LLC (info@libraw.org)\n Copyright (C) 2020 Roman Lebedev\n\n This library is free software; you can redistribute it and\/or\n modify it under the terms of the GNU Lesser General Public\n License as published by the Free Software Foundation; either\n version 2.1 of the License, or (at your option) any later version.\n\n This library is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n Lesser General Public License for more details.\n\n You should have received a copy of the GNU Lesser General Public\n License along with this library; if not, write to the Free Software\n Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n*\/\n\n#include \"decompressors\/PanasonicDecompressorV6.h\" \/\/ for PanasonicDecompre...\n#include \"common\/Array2DRef.h\" \/\/ for Array2DRef\n#include \"common\/Point.h\" \/\/ for iPoint2D\n#include \"common\/RawImage.h\" \/\/ for RawImage, RawImag...\n#include \"decoders\/RawDecoderException.h\" \/\/ for ThrowRDE\n#include <algorithm> \/\/ for copy_n\n#include <array>\n#include <cstdint> \/\/ for uint16_t, uint32_t\n#include <cstdlib> \/\/ for free, malloc\n\nnamespace rawspeed {\n\nnamespace {\nstruct pana_cs6_page_decoder {\n std::array<unsigned int, 14> pixelbuffer;\n unsigned lastoffset, maxoffset;\n unsigned char current;\n const unsigned char* buffer;\n pana_cs6_page_decoder(const unsigned char* _buffer, unsigned int bsize)\n : lastoffset(0), maxoffset(bsize), current(0), buffer(_buffer) {}\n void read_page(); \/\/ will throw IO error if not enough space in buffer\n unsigned int nextpixel() { return current < 14 ? pixelbuffer[current++] : 0; }\n};\n\nvoid pana_cs6_page_decoder::read_page() {\n if (!buffer || (maxoffset - lastoffset < 16))\n ThrowRDE(\"Input failure\");\n auto wbuffer = [&](int i) {\n return static_cast<uint16_t>(buffer[lastoffset + 15 - i]);\n };\n pixelbuffer[0] = (wbuffer(0) << 6) | (wbuffer(1) >> 2); \/\/ 14 bit\n pixelbuffer[1] =\n (((wbuffer(1) & 0x3) << 12) | (wbuffer(2) << 4) | (wbuffer(3) >> 4)) &\n 0x3fff;\n pixelbuffer[2] = (wbuffer(3) >> 2) & 0x3;\n pixelbuffer[3] = ((wbuffer(3) & 0x3) << 8) | wbuffer(4);\n pixelbuffer[4] = (wbuffer(5) << 2) | (wbuffer(6) >> 6);\n pixelbuffer[5] = ((wbuffer(6) & 0x3f) << 4) | (wbuffer(7) >> 4);\n pixelbuffer[6] = (wbuffer(7) >> 2) & 0x3;\n pixelbuffer[7] = ((wbuffer(7) & 0x3) << 8) | wbuffer(8);\n pixelbuffer[8] = ((wbuffer(9) << 2) & 0x3fc) | (wbuffer(10) >> 6);\n pixelbuffer[9] = ((wbuffer(10) << 4) | (wbuffer(11) >> 4)) & 0x3ff;\n pixelbuffer[10] = (wbuffer(11) >> 2) & 0x3;\n pixelbuffer[11] = ((wbuffer(11) & 0x3) << 8) | wbuffer(12);\n pixelbuffer[12] = (((wbuffer(13) << 2) & 0x3fc) | wbuffer(14) >> 6) & 0x3ff;\n pixelbuffer[13] = ((wbuffer(14) << 4) | (wbuffer(15) >> 4)) & 0x3ff;\n#undef wbuffer\n current = 0;\n lastoffset += 16;\n}\n} \/\/ namespace\n\nPanasonicDecompressorV6::PanasonicDecompressorV6(const RawImage& img,\n ByteStream input_,\n uint32_t bps_)\n : mRaw(img), input(std::move(input_)) {\n if (mRaw->getCpp() != 1 || mRaw->getDataType() != TYPE_USHORT16 ||\n mRaw->getBpp() != sizeof(uint16_t))\n ThrowRDE(\"Unexpected component count \/ data type\");\n\n if (!mRaw->dim.hasPositiveArea()) {\n ThrowRDE(\"Unexpected image dimensions found: (%i; %i)\", mRaw->dim.x,\n mRaw->dim.y);\n }\n\n const int blocksperrow = mRaw->dim.x \/ 11;\n const int bytesPerRow = 16 * blocksperrow;\n const int bytesTotal = bytesPerRow * mRaw->dim.y;\n input = input_.peekStream(bytesTotal);\n}\n\nvoid PanasonicDecompressorV6::decompressBlock(ByteStream* rowInput, int row,\n int col) const {\n const Array2DRef<uint16_t> out(mRaw->getU16DataAsUncroppedArray2DRef());\n\n pana_cs6_page_decoder page(rowInput->getData(16), 16);\n page.read_page();\n std::array<unsigned int, 2> oddeven = {0, 0};\n std::array<unsigned int, 2> nonzero = {0, 0};\n unsigned pmul = 0;\n unsigned pixel_base = 0;\n for (int pix = 0; pix < 11; pix++, col++) {\n if (pix % 3 == 2) {\n unsigned base = page.nextpixel();\n if (base > 3)\n ThrowRDE(\"Invariant failure\");\n if (base == 3)\n base = 4;\n pixel_base = 0x200 << base;\n pmul = 1 << base;\n }\n unsigned epixel = page.nextpixel();\n if (oddeven[pix % 2]) {\n epixel *= pmul;\n if (pixel_base < 0x2000 && nonzero[pix % 2] > pixel_base)\n epixel += nonzero[pix % 2] - pixel_base;\n nonzero[pix % 2] = epixel;\n } else {\n oddeven[pix % 2] = epixel;\n if (epixel)\n nonzero[pix % 2] = epixel;\n else\n epixel = nonzero[pix % 2];\n }\n auto spix = static_cast<unsigned>(static_cast<int>(epixel) - 0xf);\n if (spix <= 0xffff)\n out(row, col) = spix & 0xffff;\n else {\n epixel = static_cast<signed int>(epixel + 0x7ffffff1) >> 0x1f;\n out(row, col) = epixel & 0x3fff;\n }\n }\n}\n\nvoid PanasonicDecompressorV6::decompressRow(int row) const {\n const int blocksperrow = mRaw->dim.x \/ 11;\n const int bytesPerRow = 16 * blocksperrow;\n\n ByteStream rowInput = input.getSubStream(bytesPerRow * row, bytesPerRow);\n for (int rblock = 0, col = 0; rblock < blocksperrow; rblock++, col += 11)\n decompressBlock(&rowInput, row, col);\n}\n\nvoid PanasonicDecompressorV6::decompress() const {\n#ifdef HAVE_OPENMP\n#pragma omp parallel for num_threads(rawspeed_get_number_of_processor_cores()) \\\n schedule(static) default(none)\n#endif\n for (int row = 0; row < mRaw->dim.y; ++row) {\n try {\n decompressRow(row);\n } catch (RawspeedException& err) {\n \/\/ Propagate the exception out of OpenMP magic.\n mRaw->setError(err.what());\n }\n }\n\n std::string firstErr;\n if (mRaw->isTooManyErrors(1, &firstErr)) {\n ThrowRDE(\"Too many errors encountered. Giving up. First Error:\\n%s\",\n firstErr.c_str());\n }\n}\n\n} \/\/ namespace rawspeed\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2009 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"app\/gfx\/canvas.h\"\n\n#include <cairo\/cairo.h>\n#include <pango\/pango.h>\n#include <pango\/pangocairo.h>\n\n#include \"app\/gfx\/font.h\"\n#include \"base\/gfx\/rect.h\"\n#include \"base\/logging.h\"\n#include \"base\/string_util.h\"\n\nnamespace {\n\n\/\/ Returns a new pango font, free with pango_font_description_free().\nPangoFontDescription* PangoFontFromGfxFont(const gfx::Font& gfx_font) {\n gfx::Font font = gfx_font; \/\/ Copy so we can call non-const methods.\n PangoFontDescription* pfd = pango_font_description_new();\n pango_font_description_set_family(pfd, WideToUTF8(font.FontName()).c_str());\n pango_font_description_set_size(pfd, font.FontSize() * PANGO_SCALE);\n\n switch (font.style()) {\n case gfx::Font::NORMAL:\n \/\/ Nothing to do, should already be PANGO_STYLE_NORMAL.\n break;\n case gfx::Font::BOLD:\n pango_font_description_set_weight(pfd, PANGO_WEIGHT_BOLD);\n break;\n case gfx::Font::ITALIC:\n pango_font_description_set_style(pfd, PANGO_STYLE_ITALIC);\n break;\n case gfx::Font::UNDERLINED:\n \/\/ TODO(deanm): How to do underlined? Where do we use it? Probably have\n \/\/ to paint it ourselves, see pango_font_metrics_get_underline_position.\n break;\n }\n\n return pfd;\n}\n\n} \/\/ namespace\n\nnamespace gfx {\n\nCanvas::Canvas(int width, int height, bool is_opaque)\n : skia::PlatformCanvas(width, height, is_opaque) {\n}\n\nCanvas::Canvas() : skia::PlatformCanvas() {\n}\n\nCanvas::~Canvas() {\n}\n\n\/\/ static\nvoid Canvas::SizeStringInt(const std::wstring& text,\n const gfx::Font& font,\n int* width, int* height, int flags) {\n cairo_surface_t* surface =\n cairo_image_surface_create(CAIRO_FORMAT_ARGB32, 0, 0);\n cairo_t* cr = cairo_create(surface);\n PangoLayout* layout = pango_cairo_create_layout(cr);\n\n if (flags & NO_ELLIPSIS) {\n pango_layout_set_ellipsize(layout, PANGO_ELLIPSIZE_NONE);\n } else {\n pango_layout_set_ellipsize(layout, PANGO_ELLIPSIZE_END);\n }\n\n if (flags & TEXT_ALIGN_CENTER) {\n pango_layout_set_alignment(layout, PANGO_ALIGN_CENTER);\n } else if (flags & TEXT_ALIGN_RIGHT) {\n pango_layout_set_alignment(layout, PANGO_ALIGN_RIGHT);\n }\n\n if (flags & MULTI_LINE) {\n pango_layout_set_wrap(layout,\n (flags & CHARACTER_BREAK) ? PANGO_WRAP_WORD_CHAR : PANGO_WRAP_WORD);\n }\n\n std::string utf8 = WideToUTF8(text);\n pango_layout_set_text(layout, utf8.data(), utf8.size());\n PangoFontDescription* desc = PangoFontFromGfxFont(font);\n pango_layout_set_font_description(layout, desc);\n\n pango_layout_get_size(layout, width, height);\n *width \/= PANGO_SCALE;\n *height \/= PANGO_SCALE;\n g_object_unref(layout);\n pango_font_description_free(desc);\n cairo_destroy(cr);\n cairo_surface_destroy(surface);\n}\n\nvoid Canvas::DrawStringInt(const std::wstring& text,\n const gfx::Font& font,\n const SkColor& color, int x, int y, int w, int h,\n int flags) {\n cairo_t* cr = beginPlatformPaint();\n PangoLayout* layout = pango_cairo_create_layout(cr);\n\n \/\/ Callers of DrawStringInt handle RTL layout themselves, so tell pango to not\n \/\/ scope out RTL characters.\n pango_layout_set_auto_dir(layout, FALSE);\n\n cairo_set_source_rgb(cr,\n SkColorGetR(color) \/ 255.0,\n SkColorGetG(color) \/ 255.0,\n SkColorGetB(color) \/ 255.0);\n\n \/\/ TODO(deanm): Implement the rest of the Canvas flags.\n if (!(flags & Canvas::NO_ELLIPSIS))\n pango_layout_set_ellipsize(layout, PANGO_ELLIPSIZE_END);\n\n pango_layout_set_width(layout, w * PANGO_SCALE);\n pango_layout_set_height(layout, h * PANGO_SCALE);\n\n if (flags & TEXT_ALIGN_CENTER) {\n pango_layout_set_alignment(layout, PANGO_ALIGN_CENTER);\n } else if (flags & TEXT_ALIGN_RIGHT) {\n pango_layout_set_alignment(layout, PANGO_ALIGN_RIGHT);\n }\n\n if (flags & MULTI_LINE) {\n pango_layout_set_wrap(layout,\n (flags & CHARACTER_BREAK) ? PANGO_WRAP_WORD_CHAR : PANGO_WRAP_WORD);\n }\n\n if (flags & NO_ELLIPSIS)\n pango_layout_set_ellipsize(layout, PANGO_ELLIPSIZE_NONE);\n\n std::string utf8 = WideToUTF8(text);\n pango_layout_set_text(layout, utf8.data(), utf8.size());\n\n PangoFontDescription* desc = PangoFontFromGfxFont(font);\n pango_layout_set_font_description(layout, desc);\n pango_font_description_free(desc);\n\n int width, height;\n pango_layout_get_size(layout, &width, &height);\n\n if (flags & Canvas::TEXT_VALIGN_TOP) {\n \/\/ Cairo should draw from the top left corner already.\n } else if (flags & Canvas::TEXT_VALIGN_BOTTOM) {\n y = y + (h - (height \/ PANGO_SCALE));\n } else {\n \/\/ Vertically centered.\n y = y + ((h - (height \/ PANGO_SCALE)) \/ 2);\n }\n\n cairo_move_to(cr, x, y);\n pango_cairo_show_layout(cr, layout);\n\n g_object_unref(layout);\n \/\/ NOTE: beginPlatformPaint returned its surface, we shouldn't destroy it.\n}\n\n} \/\/ namespace gfx\n<commit_msg>Linux: make gfx::Canvas honor GTK font settings.<commit_after>\/\/ Copyright (c) 2009 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"app\/gfx\/canvas.h\"\n\n#include <cairo\/cairo.h>\n#include <gtk\/gtk.h>\n#include <pango\/pango.h>\n#include <pango\/pangocairo.h>\n\n#include \"app\/gfx\/font.h\"\n#include \"base\/gfx\/rect.h\"\n#include \"base\/logging.h\"\n#include \"base\/string_util.h\"\n\nnamespace {\n\n\/\/ Font settings that we initialize once and then use when drawing text in\n\/\/ DrawStringInt().\nstatic cairo_font_options_t* cairo_font_options = NULL;\n\n\/\/ Returns a new pango font, free with pango_font_description_free().\nPangoFontDescription* PangoFontFromGfxFont(const gfx::Font& gfx_font) {\n gfx::Font font = gfx_font; \/\/ Copy so we can call non-const methods.\n PangoFontDescription* pfd = pango_font_description_new();\n pango_font_description_set_family(pfd, WideToUTF8(font.FontName()).c_str());\n pango_font_description_set_size(pfd, font.FontSize() * PANGO_SCALE);\n\n switch (font.style()) {\n case gfx::Font::NORMAL:\n \/\/ Nothing to do, should already be PANGO_STYLE_NORMAL.\n break;\n case gfx::Font::BOLD:\n pango_font_description_set_weight(pfd, PANGO_WEIGHT_BOLD);\n break;\n case gfx::Font::ITALIC:\n pango_font_description_set_style(pfd, PANGO_STYLE_ITALIC);\n break;\n case gfx::Font::UNDERLINED:\n \/\/ TODO(deanm): How to do underlined? Where do we use it? Probably have\n \/\/ to paint it ourselves, see pango_font_metrics_get_underline_position.\n break;\n }\n\n return pfd;\n}\n\n\/\/ Update |cairo_font_options| based on GtkSettings, allocating it if needed.\nstatic void UpdateCairoFontOptions() {\n if (!cairo_font_options)\n cairo_font_options = cairo_font_options_create();\n\n GtkSettings* gtk_settings = gtk_settings_get_default();\n gint antialias = 0;\n gint hinting = 0;\n gchar* hint_style = NULL;\n gchar* rgba_style = NULL;\n g_object_get(gtk_settings,\n \"gtk-xft-antialias\", &antialias,\n \"gtk-xft-hinting\", &hinting,\n \"gtk-xft-hintstyle\", &hint_style,\n \"gtk-xft-rgba\", &rgba_style,\n NULL);\n\n \/\/ g_object_get() doesn't tell us whether the properties were present or not,\n \/\/ but if they aren't (because gnome-settings-daemon isn't running), we'll get\n \/\/ NULL values for the strings.\n if (hint_style && rgba_style) {\n if (!antialias) {\n cairo_font_options_set_antialias(cairo_font_options,\n CAIRO_ANTIALIAS_NONE);\n } else if (strcmp(rgba_style, \"none\") == 0) {\n cairo_font_options_set_antialias(cairo_font_options,\n CAIRO_ANTIALIAS_GRAY);\n } else {\n cairo_font_options_set_antialias(cairo_font_options,\n CAIRO_ANTIALIAS_SUBPIXEL);\n cairo_subpixel_order_t cairo_subpixel_order =\n CAIRO_SUBPIXEL_ORDER_DEFAULT;\n if (strcmp(rgba_style, \"rgb\") == 0) {\n cairo_subpixel_order = CAIRO_SUBPIXEL_ORDER_RGB;\n } else if (strcmp(rgba_style, \"bgr\") == 0) {\n cairo_subpixel_order = CAIRO_SUBPIXEL_ORDER_BGR;\n } else if (strcmp(rgba_style, \"vrgb\") == 0) {\n cairo_subpixel_order = CAIRO_SUBPIXEL_ORDER_VRGB;\n } else if (strcmp(rgba_style, \"vbgr\") == 0) {\n cairo_subpixel_order = CAIRO_SUBPIXEL_ORDER_VBGR;\n }\n cairo_font_options_set_subpixel_order(cairo_font_options,\n cairo_subpixel_order);\n }\n\n cairo_hint_style_t cairo_hint_style = CAIRO_HINT_STYLE_DEFAULT;\n if (hinting == 0 || strcmp(hint_style, \"hintnone\") == 0) {\n cairo_hint_style = CAIRO_HINT_STYLE_NONE;\n } else if (strcmp(hint_style, \"hintslight\") == 0) {\n cairo_hint_style = CAIRO_HINT_STYLE_SLIGHT;\n } else if (strcmp(hint_style, \"hintmedium\") == 0) {\n cairo_hint_style = CAIRO_HINT_STYLE_MEDIUM;\n } else if (strcmp(hint_style, \"hintfull\") == 0) {\n cairo_hint_style = CAIRO_HINT_STYLE_FULL;\n }\n cairo_font_options_set_hint_style(cairo_font_options, cairo_hint_style);\n }\n\n if (hint_style)\n g_free(hint_style);\n if (rgba_style)\n g_free(rgba_style);\n}\n\n} \/\/ namespace\n\nnamespace gfx {\n\nCanvas::Canvas(int width, int height, bool is_opaque)\n : skia::PlatformCanvas(width, height, is_opaque) {\n}\n\nCanvas::Canvas() : skia::PlatformCanvas() {\n}\n\nCanvas::~Canvas() {\n}\n\n\/\/ static\nvoid Canvas::SizeStringInt(const std::wstring& text,\n const gfx::Font& font,\n int* width, int* height, int flags) {\n cairo_surface_t* surface =\n cairo_image_surface_create(CAIRO_FORMAT_ARGB32, 0, 0);\n cairo_t* cr = cairo_create(surface);\n PangoLayout* layout = pango_cairo_create_layout(cr);\n\n if (flags & NO_ELLIPSIS) {\n pango_layout_set_ellipsize(layout, PANGO_ELLIPSIZE_NONE);\n } else {\n pango_layout_set_ellipsize(layout, PANGO_ELLIPSIZE_END);\n }\n\n if (flags & TEXT_ALIGN_CENTER) {\n pango_layout_set_alignment(layout, PANGO_ALIGN_CENTER);\n } else if (flags & TEXT_ALIGN_RIGHT) {\n pango_layout_set_alignment(layout, PANGO_ALIGN_RIGHT);\n }\n\n if (flags & MULTI_LINE) {\n pango_layout_set_wrap(layout,\n (flags & CHARACTER_BREAK) ? PANGO_WRAP_WORD_CHAR : PANGO_WRAP_WORD);\n }\n\n std::string utf8 = WideToUTF8(text);\n pango_layout_set_text(layout, utf8.data(), utf8.size());\n PangoFontDescription* desc = PangoFontFromGfxFont(font);\n pango_layout_set_font_description(layout, desc);\n\n pango_layout_get_size(layout, width, height);\n *width \/= PANGO_SCALE;\n *height \/= PANGO_SCALE;\n g_object_unref(layout);\n pango_font_description_free(desc);\n cairo_destroy(cr);\n cairo_surface_destroy(surface);\n}\n\nvoid Canvas::DrawStringInt(const std::wstring& text,\n const gfx::Font& font,\n const SkColor& color, int x, int y, int w, int h,\n int flags) {\n cairo_t* cr = beginPlatformPaint();\n PangoLayout* layout = pango_cairo_create_layout(cr);\n\n if (!cairo_font_options)\n UpdateCairoFontOptions();\n \/\/ This needs to be done early on; it has no effect when called just before\n \/\/ pango_cairo_show_layout().\n pango_cairo_context_set_font_options(\n pango_layout_get_context(layout), cairo_font_options);\n\n \/\/ Callers of DrawStringInt handle RTL layout themselves, so tell pango to not\n \/\/ scope out RTL characters.\n pango_layout_set_auto_dir(layout, FALSE);\n\n cairo_set_source_rgb(cr,\n SkColorGetR(color) \/ 255.0,\n SkColorGetG(color) \/ 255.0,\n SkColorGetB(color) \/ 255.0);\n\n \/\/ TODO(deanm): Implement the rest of the Canvas flags.\n if (!(flags & Canvas::NO_ELLIPSIS))\n pango_layout_set_ellipsize(layout, PANGO_ELLIPSIZE_END);\n\n pango_layout_set_width(layout, w * PANGO_SCALE);\n pango_layout_set_height(layout, h * PANGO_SCALE);\n\n if (flags & TEXT_ALIGN_CENTER) {\n pango_layout_set_alignment(layout, PANGO_ALIGN_CENTER);\n } else if (flags & TEXT_ALIGN_RIGHT) {\n pango_layout_set_alignment(layout, PANGO_ALIGN_RIGHT);\n }\n\n if (flags & MULTI_LINE) {\n pango_layout_set_wrap(layout,\n (flags & CHARACTER_BREAK) ? PANGO_WRAP_WORD_CHAR : PANGO_WRAP_WORD);\n }\n\n if (flags & NO_ELLIPSIS)\n pango_layout_set_ellipsize(layout, PANGO_ELLIPSIZE_NONE);\n\n std::string utf8 = WideToUTF8(text);\n pango_layout_set_text(layout, utf8.data(), utf8.size());\n\n PangoFontDescription* desc = PangoFontFromGfxFont(font);\n pango_layout_set_font_description(layout, desc);\n pango_font_description_free(desc);\n\n int width, height;\n pango_layout_get_size(layout, &width, &height);\n\n if (flags & Canvas::TEXT_VALIGN_TOP) {\n \/\/ Cairo should draw from the top left corner already.\n } else if (flags & Canvas::TEXT_VALIGN_BOTTOM) {\n y = y + (h - (height \/ PANGO_SCALE));\n } else {\n \/\/ Vertically centered.\n y = y + ((h - (height \/ PANGO_SCALE)) \/ 2);\n }\n\n cairo_move_to(cr, x, y);\n pango_cairo_show_layout(cr, layout);\n\n g_object_unref(layout);\n \/\/ NOTE: beginPlatformPaint returned its surface, we shouldn't destroy it.\n}\n\n} \/\/ namespace gfx\n<|endoftext|>"} {"text":"<commit_before>\/\/ coding: utf-8\n\/\/ ----------------------------------------------------------------------------\n\/* Copyright (c) 2009, Roboterclub Aachen e.V.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution.\n * * Neither the name of the Roboterclub Aachen e.V. nor the\n * names of its contributors may be used to endorse or promote products\n * derived from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY ROBOTERCLUB AACHEN E.V. ''AS IS'' AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL ROBOTERCLUB AACHEN E.V. BE LIABLE FOR ANY\n * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF\n * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n * $Id$\n *\/\n\/\/ ----------------------------------------------------------------------------\n\n#ifndef XPCC__CAN_CONNECTOR_HPP\n\t#error\t\"Don't include this file directly, use 'can_connector.hpp' instead!\"\n#endif\n\n#include <xpcc\/math\/utils\/bit_operation.hpp>\n#include <xpcc\/driver\/can\/message.hpp>\n\n\/\/ ----------------------------------------------------------------------------\ntemplate<typename Driver>\nxpcc::CanConnector<Driver>::CanConnector(Driver *driver) :\n\tcanDriver(driver)\n{\n}\n\ntemplate<typename Driver>\nxpcc::CanConnector<Driver>::~CanConnector()\n{\n}\n\n\/\/ ----------------------------------------------------------------------------\ntemplate<typename Driver>\nbool\nxpcc::CanConnector<Driver>::isPacketAvailable() const\n{\n\treturn !this->receivedMessages.isEmpty();\n}\n\ntemplate<typename Driver>\nconst xpcc::Header&\nxpcc::CanConnector<Driver>::getPacketHeader() const\n{\n\treturn this->receivedMessages.getFront().header;\n}\n\ntemplate<typename Driver>\nconst xpcc::SmartPointer\nxpcc::CanConnector<Driver>::getPacketPayload() const\n{\n\treturn this->receivedMessages.getFront().payload;\n}\n\n\/\/ ----------------------------------------------------------------------------\ntemplate<typename Driver>\nvoid\nxpcc::CanConnector<Driver>::sendPacket(const Header &header, SmartPointer payload)\n{\n\tbool successfull = false;\n\tbool fragmented = (payload.getSize() > 8);\n\t\n\tuint32_t identifier = convertToIdentifier(header, fragmented);\n\tif (!fragmented && this->canDriver->isReadyToSend())\n\t{\n\t\t\/\/ try to send the message directly\n\t\tsuccessfull = this->sendMessage(identifier,\n\t\t\t\tpayload.getPointer(), payload.getSize());\n\t}\n\t\n\tif (!successfull)\n\t{\n\t\t\/\/ append the message to the list of waiting messages\n\t\tthis->sendList.append(SendListItem(identifier, payload));\n\t}\n}\n\n\/\/ ----------------------------------------------------------------------------\ntemplate<typename Driver>\nvoid\nxpcc::CanConnector<Driver>::dropPacket()\n{\n\tthis->receivedMessages.removeFront();\n}\n\n\/\/ ----------------------------------------------------------------------------\ntemplate<typename Driver>\nvoid\nxpcc::CanConnector<Driver>::update()\n{\n\tthis->checkAndReceiveMessages();\n\tthis->sendWaitingMessages();\n}\n\n\/\/ ----------------------------------------------------------------------------\n\/\/ protected\n\/\/ ----------------------------------------------------------------------------\n\ntemplate<typename Driver>\nbool\nxpcc::CanConnector<Driver>::sendMessage(const uint32_t & identifier,\n\t\tconst uint8_t *data, uint8_t size)\n{\n\txpcc::can::Message message(identifier, size);\n\t\n\t\/\/ copy payload data\n\tstd::memcpy(message.data, data, size);\n\t\n\treturn this->canDriver->sendMessage(message);\n}\n\ntemplate<typename Driver>\nvoid\nxpcc::CanConnector<Driver>::sendWaitingMessages()\n{\n\tif (this->sendList.isEmpty()) {\n\t\t\/\/ no message in the queue\n\t\treturn;\n\t}\n\t\n\tSendListItem& message = this->sendList.getFront();\n\t\n\tuint8_t messageSize = message.payload.getSize();\n\tif (messageSize > 8)\n\t{\n\t\t\/\/ fragmented message\n\t\tuint8_t data[8];\n\t\t\n\t\tdata[0] = message.fragmentIndex | (this->messageCounter & 0xf0);\n\t\tdata[1] = messageSize; \t\/\/ size of the complete message\n\t\t\n\t\tbool sendFinished = true;\n\t\tuint8_t offset = message.fragmentIndex * 6;\n\t\tuint8_t fragmentSize = messageSize - offset;\n\t\tif (fragmentSize > 6)\n\t\t{\n\t\t\tfragmentSize = 6;\n\t\t\tsendFinished = false;\n\t\t}\n\t\t\/\/ otherwise fragmentSize is smaller or equal to six, so the last\n\t\t\/\/ fragment is about to be sent.\n\n\t\tmemcpy(data + 2, message.payload.getPointer() + offset, fragmentSize);\n\t\t\n\t\tif (sendMessage(message.identifier, data, fragmentSize + 2))\n\t\t{\n\t\t\tmessage.fragmentIndex++;\n\t\t\tif (sendFinished)\n\t\t\t{\n\t\t\t\t\/\/ message was the last fragment\n\t\t\t\t\/\/ => remove it from the list\n\t\t\t\tthis->sendList.removeFront();\n\t\t\t\tthis->messageCounter += 0x10;\n\t\t\t}\n\t\t}\n\t}\n\telse\n\t{\n\t\tif (this->sendMessage(message.identifier, message.payload.getPointer(),\n\t\t\t\tmessageSize))\n\t\t{\n\t\t\tthis->sendList.removeFront();\n\t\t}\n\t}\n}\n\ntemplate<typename Driver>\nbool\nxpcc::CanConnector<Driver>::retrieveMessage()\n{\n\tcan::Message message;\n\tif (this->canDriver->getMessage(message))\n\t{\n\t\txpcc::Header header;\n\t\tbool isFragment = convertToHeader(message.identifier, header);\n\t\t\n\t\tif (!isFragment)\n\t\t{\n\t\t\tthis->receivedMessages.append(ReceiveListItem(message.length, header));\n\t\t\tstd::memcpy(this->receivedMessages.getBack().payload.getPointer(),\n\t\t\t\t\tmessage.data,\n\t\t\t\t\tmessage.length);\n\t\t}\n\t\telse\n\t\t{\n\t\t\t\/\/ find existing container otherwise create a new one\n\t\t\tconst uint8_t fragmentIndex = message.data[0] & 0x0f;\n\t\t\tconst uint8_t counter = message.data[0] & 0xf0;\n\t\t\tconst uint8_t messageSize = message.data[1];\n\t\t\t\n\t\t\t\/\/ calculate the number of messages need to send messageSize-bytes\n\t\t\tuint8_t numberOfFragments = this->getNumberOfFragments(messageSize);\n\t\t\t\n\t\t\tif (message.length < 4 || messageSize > 48 ||\n\t\t\t\t\tfragmentIndex >= numberOfFragments)\n\t\t\t{\n\t\t\t\t\/\/ illegal format:\n\t\t\t\t\/\/ fragmented messages need to have at least 3 byte payload,\n\t\t\t\t\/\/ \t the maximum size is 48 Bytes and the fragment number\n\t\t\t\t\/\/\t should not be higher than the number of fragments.\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\t\/\/ check the length of the fragment (all fragments except the\n\t\t\t\/\/ last one need to have a payload-length of 6 bytes + 2 byte\n\t\t\t\/\/ fragment information)\n\t\t\tuint8_t offset = fragmentIndex * 6;\n\t\t\tif (fragmentIndex + 1 == numberOfFragments)\n\t\t\t{\n\t\t\t\t\/\/ this one is the last fragment\n\t\t\t\tif (messageSize - offset != message.length - 2)\n\t\t\t\t{\n\t\t\t\t\t\/\/ illegal format\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (message.length != 8)\n\t\t\t{\n\t\t\t\t\/\/ illegal format\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\t\n\t\t\t\/\/ Check if other parts of this message are already in the\n\t\t\t\/\/ list of receiving messages.\n\t\t\ttypename ReceiveList::iterator packet = this->pendingMessages.begin();\n\t\t\tfor ( ; packet != this->pendingMessages.end(); ++packet)\n\t\t\t{\n\t\t\t\tif (packet->header == header &&\n\t\t\t\t\tpacket->counter == counter)\n\t\t\t\t{\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\tif (packet == this->pendingMessages.end()) {\n\t\t\t\t\/\/ message not found => first part of this message,\n\t\t\t\t\/\/ prepend it to the list\n\t\t\t\tthis->pendingMessages.prepend(ReceiveListItem(messageSize, header, counter));\n\t\t\t\tpacket = this->pendingMessages.begin();\n\t\t\t}\n\t\t\t\n\t\t\t\/\/ create a marker for the currently received fragment and\n\t\t\t\/\/ test if the fragment was already received\n\t\t\tconst uint8_t currentFragment = (1 << fragmentIndex);\n\t\t\tif (currentFragment & packet->receivedFragments)\n\t\t\t{\n\t\t\t\t\/\/ error: received fragment twice -> most likely a new message -> delete the old one\n\t\t\t\t\/\/XPCC_LOG_WARNING << \"lost fragment\" << xpcc::flush;\n\t\t\t\tpacket->receivedFragments = 0;\n\t\t\t}\n\t\t\tpacket->receivedFragments |= currentFragment;\n\t\t\t\n\t\t\tstd::memcpy(packet->payload.getPointer() + offset,\n\t\t\t\t\tmessage.data + 2,\n\t\t\t\t\tmessage.length - 2);\n\t\t\t\n\t\t\t\/\/ test if this was the last segment, otherwise we have to wait\n\t\t\t\/\/ for more messages\n\t\t\tif (xpcc::bitCount(packet->receivedFragments) == numberOfFragments)\n\t\t\t{\n\t\t\t\tthis->receivedMessages.append(*packet);\n\t\t\t\tthis->pendingMessages.remove(packet);\n\t\t\t}\n\t\t}\n\t\t\n\t\treturn true;\n\t}\n\telse {\n\t\treturn false;\n\t}\n}\n\ntemplate<typename Driver>\nvoid\nxpcc::CanConnector<Driver>::checkAndReceiveMessages()\n{\n\twhile (this->canDriver->isMessageAvailable()) {\n\t\tthis->retrieveMessage();\n\t}\n}\n<commit_msg>good joke not to accept messages with length of 13!<commit_after>\/\/ coding: utf-8\n\/\/ ----------------------------------------------------------------------------\n\/* Copyright (c) 2009, Roboterclub Aachen e.V.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution.\n * * Neither the name of the Roboterclub Aachen e.V. nor the\n * names of its contributors may be used to endorse or promote products\n * derived from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY ROBOTERCLUB AACHEN E.V. ''AS IS'' AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL ROBOTERCLUB AACHEN E.V. BE LIABLE FOR ANY\n * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF\n * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n * $Id$\n *\/\n\/\/ ----------------------------------------------------------------------------\n\n#ifndef XPCC__CAN_CONNECTOR_HPP\n\t#error\t\"Don't include this file directly, use 'can_connector.hpp' instead!\"\n#endif\n\n#include <xpcc\/math\/utils\/bit_operation.hpp>\n#include <xpcc\/driver\/can\/message.hpp>\n\n\/\/ ----------------------------------------------------------------------------\ntemplate<typename Driver>\nxpcc::CanConnector<Driver>::CanConnector(Driver *driver) :\n\tcanDriver(driver)\n{\n}\n\ntemplate<typename Driver>\nxpcc::CanConnector<Driver>::~CanConnector()\n{\n}\n\n\/\/ ----------------------------------------------------------------------------\ntemplate<typename Driver>\nbool\nxpcc::CanConnector<Driver>::isPacketAvailable() const\n{\n\treturn !this->receivedMessages.isEmpty();\n}\n\ntemplate<typename Driver>\nconst xpcc::Header&\nxpcc::CanConnector<Driver>::getPacketHeader() const\n{\n\treturn this->receivedMessages.getFront().header;\n}\n\ntemplate<typename Driver>\nconst xpcc::SmartPointer\nxpcc::CanConnector<Driver>::getPacketPayload() const\n{\n\treturn this->receivedMessages.getFront().payload;\n}\n\n\/\/ ----------------------------------------------------------------------------\ntemplate<typename Driver>\nvoid\nxpcc::CanConnector<Driver>::sendPacket(const Header &header, SmartPointer payload)\n{\n\tbool successfull = false;\n\tbool fragmented = (payload.getSize() > 8);\n\t\n\tuint32_t identifier = convertToIdentifier(header, fragmented);\n\tif (!fragmented && this->canDriver->isReadyToSend())\n\t{\n\t\t\/\/ try to send the message directly\n\t\tsuccessfull = this->sendMessage(identifier,\n\t\t\t\tpayload.getPointer(), payload.getSize());\n\t}\n\t\n\tif (!successfull)\n\t{\n\t\t\/\/ append the message to the list of waiting messages\n\t\tthis->sendList.append(SendListItem(identifier, payload));\n\t}\n}\n\n\/\/ ----------------------------------------------------------------------------\ntemplate<typename Driver>\nvoid\nxpcc::CanConnector<Driver>::dropPacket()\n{\n\tthis->receivedMessages.removeFront();\n}\n\n\/\/ ----------------------------------------------------------------------------\ntemplate<typename Driver>\nvoid\nxpcc::CanConnector<Driver>::update()\n{\n\tthis->checkAndReceiveMessages();\n\tthis->sendWaitingMessages();\n}\n\n\/\/ ----------------------------------------------------------------------------\n\/\/ protected\n\/\/ ----------------------------------------------------------------------------\n\ntemplate<typename Driver>\nbool\nxpcc::CanConnector<Driver>::sendMessage(const uint32_t & identifier,\n\t\tconst uint8_t *data, uint8_t size)\n{\n\txpcc::can::Message message(identifier, size);\n\t\n\t\/\/ copy payload data\n\tstd::memcpy(message.data, data, size);\n\t\n\treturn this->canDriver->sendMessage(message);\n}\n\ntemplate<typename Driver>\nvoid\nxpcc::CanConnector<Driver>::sendWaitingMessages()\n{\n\tif (this->sendList.isEmpty()) {\n\t\t\/\/ no message in the queue\n\t\treturn;\n\t}\n\t\n\tSendListItem& message = this->sendList.getFront();\n\t\n\tuint8_t messageSize = message.payload.getSize();\n\tif (messageSize > 8)\n\t{\n\t\t\/\/ fragmented message\n\t\tuint8_t data[8];\n\t\t\n\t\tdata[0] = message.fragmentIndex | (this->messageCounter & 0xf0);\n\t\tdata[1] = messageSize; \t\/\/ size of the complete message\n\t\t\n\t\tbool sendFinished = true;\n\t\tuint8_t offset = message.fragmentIndex * 6;\n\t\tuint8_t fragmentSize = messageSize - offset;\n\t\tif (fragmentSize > 6)\n\t\t{\n\t\t\tfragmentSize = 6;\n\t\t\tsendFinished = false;\n\t\t}\n\t\t\/\/ otherwise fragmentSize is smaller or equal to six, so the last\n\t\t\/\/ fragment is about to be sent.\n\n\t\tmemcpy(data + 2, message.payload.getPointer() + offset, fragmentSize);\n\t\t\n\t\tif (sendMessage(message.identifier, data, fragmentSize + 2))\n\t\t{\n\t\t\tmessage.fragmentIndex++;\n\t\t\tif (sendFinished)\n\t\t\t{\n\t\t\t\t\/\/ message was the last fragment\n\t\t\t\t\/\/ => remove it from the list\n\t\t\t\tthis->sendList.removeFront();\n\t\t\t\tthis->messageCounter += 0x10;\n\t\t\t}\n\t\t}\n\t}\n\telse\n\t{\n\t\tif (this->sendMessage(message.identifier, message.payload.getPointer(),\n\t\t\t\tmessageSize))\n\t\t{\n\t\t\tthis->sendList.removeFront();\n\t\t}\n\t}\n}\n\ntemplate<typename Driver>\nbool\nxpcc::CanConnector<Driver>::retrieveMessage()\n{\n\tcan::Message message;\n\tif (this->canDriver->getMessage(message))\n\t{\n\t\txpcc::Header header;\n\t\tbool isFragment = convertToHeader(message.identifier, header);\n\t\t\n\t\tif (!isFragment)\n\t\t{\n\t\t\tthis->receivedMessages.append(ReceiveListItem(message.length, header));\n\t\t\tstd::memcpy(this->receivedMessages.getBack().payload.getPointer(),\n\t\t\t\t\tmessage.data,\n\t\t\t\t\tmessage.length);\n\t\t}\n\t\telse\n\t\t{\n\t\t\t\/\/ find existing container otherwise create a new one\n\t\t\tconst uint8_t fragmentIndex = message.data[0] & 0x0f;\n\t\t\tconst uint8_t counter = message.data[0] & 0xf0;\n\t\t\tconst uint8_t messageSize = message.data[1];\n\t\t\t\n\t\t\t\/\/ calculate the number of messages need to send messageSize-bytes\n\t\t\tuint8_t numberOfFragments = this->getNumberOfFragments(messageSize);\n\t\t\t\n\t\t\tif (message.length < 3 || messageSize > 48 ||\n\t\t\t\t\tfragmentIndex >= numberOfFragments)\n\t\t\t{\n\t\t\t\t\/\/ illegal format:\n\t\t\t\t\/\/ fragmented messages need to have at least 3 byte payload,\n\t\t\t\t\/\/ \t the maximum size is 48 Bytes and the fragment number\n\t\t\t\t\/\/\t should not be higher than the number of fragments.\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\t\/\/ check the length of the fragment (all fragments except the\n\t\t\t\/\/ last one need to have a payload-length of 6 bytes + 2 byte\n\t\t\t\/\/ fragment information)\n\t\t\tuint8_t offset = fragmentIndex * 6;\n\t\t\tif (fragmentIndex + 1 == numberOfFragments)\n\t\t\t{\n\t\t\t\t\/\/ this one is the last fragment\n\t\t\t\tif (messageSize - offset != message.length - 2)\n\t\t\t\t{\n\t\t\t\t\t\/\/ illegal format\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (message.length != 8)\n\t\t\t{\n\t\t\t\t\/\/ illegal format\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\t\n\t\t\t\/\/ Check if other parts of this message are already in the\n\t\t\t\/\/ list of receiving messages.\n\t\t\ttypename ReceiveList::iterator packet = this->pendingMessages.begin();\n\t\t\tfor ( ; packet != this->pendingMessages.end(); ++packet)\n\t\t\t{\n\t\t\t\tif (packet->header == header &&\n\t\t\t\t\tpacket->counter == counter)\n\t\t\t\t{\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\tif (packet == this->pendingMessages.end()) {\n\t\t\t\t\/\/ message not found => first part of this message,\n\t\t\t\t\/\/ prepend it to the list\n\t\t\t\tthis->pendingMessages.prepend(ReceiveListItem(messageSize, header, counter));\n\t\t\t\tpacket = this->pendingMessages.begin();\n\t\t\t}\n\t\t\t\n\t\t\t\/\/ create a marker for the currently received fragment and\n\t\t\t\/\/ test if the fragment was already received\n\t\t\tconst uint8_t currentFragment = (1 << fragmentIndex);\n\t\t\tif (currentFragment & packet->receivedFragments)\n\t\t\t{\n\t\t\t\t\/\/ error: received fragment twice -> most likely a new message -> delete the old one\n\t\t\t\t\/\/XPCC_LOG_WARNING << \"lost fragment\" << xpcc::flush;\n\t\t\t\tpacket->receivedFragments = 0;\n\t\t\t}\n\t\t\tpacket->receivedFragments |= currentFragment;\n\t\t\t\n\t\t\tstd::memcpy(packet->payload.getPointer() + offset,\n\t\t\t\t\tmessage.data + 2,\n\t\t\t\t\tmessage.length - 2);\n\t\t\t\n\t\t\t\/\/ test if this was the last segment, otherwise we have to wait\n\t\t\t\/\/ for more messages\n\t\t\tif (xpcc::bitCount(packet->receivedFragments) == numberOfFragments)\n\t\t\t{\n\t\t\t\tthis->receivedMessages.append(*packet);\n\t\t\t\tthis->pendingMessages.remove(packet);\n\t\t\t}\n\t\t}\n\t\t\n\t\treturn true;\n\t}\n\telse {\n\t\treturn false;\n\t}\n}\n\ntemplate<typename Driver>\nvoid\nxpcc::CanConnector<Driver>::checkAndReceiveMessages()\n{\n\twhile (this->canDriver->isMessageAvailable()) {\n\t\tthis->retrieveMessage();\n\t}\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"aliastablemodel.h\"\n\n#include \"guiutil.h\"\n#include \"walletmodel.h\"\n\n#include \"wallet.h\"\n#include \"base58.h\"\n\n#include <QFont>\n\nusing namespace std;\nbool GetValueOfAliasTxHash(const uint256 &txHash, vector<unsigned char>& vchValue, uint256& hash, int& nHeight);\n\nconst QString AliasTableModel::Alias = \"A\";\nconst QString AliasTableModel::DataAlias = \"D\";\n\nclass CAliasDB;\n\nextern CAliasDB *paliasdb;\n\nint GetAliasExpirationDepth(int nHeight);\nint GetAliasTxHashHeight(const uint256 txHash);\nstruct AliasTableEntry\n{\n enum Type {\n Alias,\n DataAlias\n };\n\n Type type;\n QString value;\n QString alias;\n QString expirationdepth;\n\n AliasTableEntry() {}\n AliasTableEntry(Type type, const QString &value, const QString &alias, const QString &expirationdepth):\n type(type), value(value), alias(alias), expirationdepth(expirationdepth) {}\n};\n\nstruct AliasTableEntryLessThan\n{\n bool operator()(const AliasTableEntry &a, const AliasTableEntry &b) const\n {\n return a.alias < b.alias;\n }\n bool operator()(const AliasTableEntry &a, const QString &b) const\n {\n return a.alias < b;\n }\n bool operator()(const QString &a, const AliasTableEntry &b) const\n {\n return a < b.alias;\n }\n};\n\n#define NAMEMAPTYPE map<vector<unsigned char>, uint256>\n\n\/\/ Private implementation\nclass AliasTablePriv\n{\npublic:\n CWallet *wallet;\n QList<AliasTableEntry> cachedAliasTable;\n AliasTableModel *parent;\n\n AliasTablePriv(CWallet *wallet, AliasTableModel *parent):\n wallet(wallet), parent(parent) {}\n\n void refreshAliasTable(AliasModelType type)\n {\n\n cachedAliasTable.clear();\n {\n TRY_LOCK(wallet->cs_wallet, cs_trywallet);\n\t\t\tBOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, wallet->mapWallet)\n\t\t\t{\n\t\t\t\t\t\/\/ get txn hash, read txn index\n\t\t\t\t\tCTransaction &tx = item.second;\n\t\t\t\t\tCTransaction lastTx;\n\t\t\t\t\t\/\/ skip non-syscoin txns\n\t\t\t\t\tif (tx.nVersion != SYSCOIN_TX_VERSION)\n\t\t\t\t\t\tcontinue;\n\n int op, nOut, nHeight;\n\t\t\t\t\t\n vector<vector<unsigned char> > vvchArgs;\n\t\t\t\t\tvector<unsigned char> vchValue;\n bool o = DecodeAliasTx(tx, op, nOut, vvchArgs, -1);\n\t\t\t\t\t\/\/ prune out this tx if its not an alias that is yours\n if (type != MyAlias || !o || !IsAliasOp(op) || !IsAliasMine(tx)) continue;\n if (op == OP_ALIAS_NEW) continue;\n\t\t\t\t\t \n\t\t\t\t\t\/\/ check for alias existence in DB (check that the alias wasn't transferred)\n\t\t\t\t\tvector<CAliasIndex> vtxPos;\n\t\t\t\t\tif (!paliasdb->ReadAlias(vvchArgs[0], vtxPos))\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\tif (vtxPos.size() < 1)\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\tuint256 hashBlock;\n\t\t\t\t\tuint256 txHash = vtxPos.back().txHash;\n\t\t\t\t\tif (!GetTransaction(txHash, lastTx, hashBlock, true))\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\/\/ alias was transferred because it was mine before, but the last alias address isn't yours\n\t\t\t\t\tif (!IsAliasMine(lastTx)) continue; \n\t\t\t\t\t\/\/ get alias data\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\tif (!GetValueOfAliasTxHash(txHash, vchValue, hashBlock, nHeight))\n\t\t\t\t\t\tcontinue;\n\n\t\t\t\t\tunsigned long nExpDepth = nHeight + GetAliasExpirationDepth(nHeight) - pindexBest->nHeight;\n\t\t\t\t\tstd::string strExpDepth;\n\t\t\t\t\tif(nExpDepth <= 0) \n\t\t\t\t\t\tstrExpDepth = \"Expired\";\n\t\t\t\t\telse\n\t\t\t\t\t\tstrExpDepth = strprintf(\"%lu\", nExpDepth);\n\t\t\t\t\tupdateEntry(QString::fromStdString(stringFromVch(vvchArgs[0])), QString::fromStdString(stringFromVch(vchValue)), QString::fromStdString(strExpDepth),type, CT_NEW); \n\t\t\t\t\t\n\t\t\n\n }\n }\n \/\/ qLowerBound() and qUpperBound() require our cachedAliasTable list to be sorted in asc order\n qSort(cachedAliasTable.begin(), cachedAliasTable.end(), AliasTableEntryLessThan());\n }\n\n void updateEntry(const QString &alias, const QString &value, const QString &exp, AliasModelType type, int status)\n {\n\t\tif(!parent || parent->modelType != type)\n\t\t{\n\t\t\treturn;\n\t\t}\n \/\/ Find alias \/ value in model\n QList<AliasTableEntry>::iterator lower = qLowerBound(\n cachedAliasTable.begin(), cachedAliasTable.end(), alias, AliasTableEntryLessThan());\n QList<AliasTableEntry>::iterator upper = qUpperBound(\n cachedAliasTable.begin(), cachedAliasTable.end(), alias, AliasTableEntryLessThan());\n int lowerIndex = (lower - cachedAliasTable.begin());\n int upperIndex = (upper - cachedAliasTable.begin());\n bool inModel = (lower != upper);\n\t\tint index;\n AliasTableEntry::Type newEntryType = \/*isData ? AliasTableEntry::DataAlias :*\/ AliasTableEntry::Alias;\n\n switch(status)\n {\n case CT_NEW:\n\t\t\tindex = parent->lookupAlias(alias);\n if(inModel || index != -1)\n {\n OutputDebugStringF(\"Warning: AliasTablePriv::updateEntry: Got CT_NOW, but entry is already in model\\n\");\n break;\n \n }\n parent->beginInsertRows(QModelIndex(), lowerIndex, lowerIndex);\n cachedAliasTable.insert(lowerIndex, AliasTableEntry(newEntryType, value, alias, exp));\n parent->endInsertRows();\n break;\n case CT_UPDATED:\n if(!inModel)\n {\n OutputDebugStringF(\"Warning: AliasTablePriv::updateEntry: Got CT_UPDATED, but entry is not in model\\n\");\n break;\n }\n lower->type = newEntryType;\n lower->value = value;\n lower->expirationdepth = exp;\n parent->emitDataChanged(lowerIndex);\n break;\n case CT_DELETED:\n if(!inModel)\n {\n OutputDebugStringF(\"Warning: AliasTablePriv::updateEntry: Got CT_DELETED, but entry is not in model\\n\");\n break;\n }\n parent->beginRemoveRows(QModelIndex(), lowerIndex, upperIndex-1);\n cachedAliasTable.erase(lower, upper);\n parent->endRemoveRows();\n break;\n }\n }\n\n int size()\n {\n return cachedAliasTable.size();\n }\n\n AliasTableEntry *index(int idx)\n {\n if(idx >= 0 && idx < cachedAliasTable.size())\n {\n return &cachedAliasTable[idx];\n }\n else\n {\n return 0;\n }\n }\n};\n\nAliasTableModel::AliasTableModel(CWallet *wallet, WalletModel *parent, AliasModelType type) :\n QAbstractTableModel(parent),walletModel(parent),wallet(wallet),priv(0), modelType(type)\n{\n\n\tcolumns << tr(\"Alias\") << tr(\"Value\") << tr(\"Expires In\");\t\t \n priv = new AliasTablePriv(wallet, this);\n}\n\nAliasTableModel::~AliasTableModel()\n{\n delete priv;\n}\nvoid AliasTableModel::refreshAliasTable() \n{\n\tclear();\n\tpriv->refreshAliasTable(modelType);\n}\nint AliasTableModel::rowCount(const QModelIndex &parent) const\n{\n Q_UNUSED(parent);\n return priv->size();\n}\n\nint AliasTableModel::columnCount(const QModelIndex &parent) const\n{\n Q_UNUSED(parent);\n return columns.length();\n}\n\nQVariant AliasTableModel::data(const QModelIndex &index, int role) const\n{\n if(!index.isValid())\n return QVariant();\n\n AliasTableEntry *rec = static_cast<AliasTableEntry*>(index.internalPointer());\n\n if(role == Qt::DisplayRole || role == Qt::EditRole)\n {\n switch(index.column())\n {\n case Value:\n return rec->value;\n case Name:\n return rec->alias;\n case ExpirationDepth:\n return rec->expirationdepth;\n }\n }\n else if (role == Qt::FontRole)\n {\n QFont font;\n if(index.column() == Value)\n {\n font = GUIUtil::bitcoinAddressFont();\n }\n return font;\n }\n else if (role == TypeRole)\n {\n switch(rec->type)\n {\n case AliasTableEntry::Alias:\n return Alias;\n case AliasTableEntry::DataAlias:\n return DataAlias;\n default: break;\n }\n }\n return QVariant();\n}\n\nbool AliasTableModel::setData(const QModelIndex &index, const QVariant &value, int role)\n{\n if(!index.isValid())\n return false;\n AliasTableEntry *rec = static_cast<AliasTableEntry*>(index.internalPointer());\n\n editStatus = OK;\n\n if(role == Qt::EditRole)\n {\n switch(index.column())\n {\n case ExpirationDepth:\n \/\/ Do nothing, if old value == new value\n if(rec->expirationdepth == value.toString())\n {\n editStatus = NO_CHANGES;\n return false;\n }\n \/\/wallet->SetAddressBookName(CBitcoinAlias(rec->alias.toStdString()).Get(), value.toString().toStdString());\n break;\n case Value:\n \/\/ Do nothing, if old value == new value\n if(rec->value == value.toString())\n {\n editStatus = NO_CHANGES;\n return false;\n }\n \/\/wallet->SetAddressBookName(CBitcoinAlias(rec->alias.toStdString()).Get(), value.toString().toStdString());\n break;\n case Name:\n \/\/ Do nothing, if old alias == new alias\n if(rec->alias == value.toString())\n {\n editStatus = NO_CHANGES;\n return false;\n }\n \/\/ Check for duplicate aliases to prevent accidental deletion of aliases, if you try\n \/\/ to paste an existing alias over another alias (with a different label)\n else if(lookupAlias(rec->alias) != -1)\n {\n editStatus = DUPLICATE_ALIAS;\n return false;\n }\n \/\/ Double-check that we're not overwriting a receiving alias\n else if(rec->type == AliasTableEntry::Alias)\n {\n {\n \/\/ update alias\n }\n }\n break;\n }\n return true;\n }\n return false;\n}\n\nQVariant AliasTableModel::headerData(int section, Qt::Orientation orientation, int role) const\n{\n if(orientation == Qt::Horizontal)\n {\n if(role == Qt::DisplayRole)\n {\n return columns[section];\n }\n }\n return QVariant();\n}\n\nQt::ItemFlags AliasTableModel::flags(const QModelIndex &index) const\n{\n if(!index.isValid())\n return 0;\n Qt::ItemFlags retval = Qt::ItemIsSelectable | Qt::ItemIsEnabled;\n return retval;\n}\n\nQModelIndex AliasTableModel::index(int row, int column, const QModelIndex &parent) const\n{\n Q_UNUSED(parent);\n AliasTableEntry *data = priv->index(row);\n if(data)\n {\n return createIndex(row, column, priv->index(row));\n }\n else\n {\n return QModelIndex();\n }\n}\n\nvoid AliasTableModel::updateEntry(const QString &alias, const QString &value, const QString &exp, AliasModelType type, int status)\n{\n \/\/ Update alias book model from Bitcoin core\n priv->updateEntry(alias, value, exp, type, status);\n}\n\nQString AliasTableModel::addRow(const QString &type, const QString &value, const QString &alias, const QString &exp)\n{\n std::string strValue = value.toStdString();\n std::string strAlias = alias.toStdString();\n std::string strExp = exp.toStdString();\n\n editStatus = OK;\n \/\/ Check for duplicate aliases\n {\n LOCK(wallet->cs_wallet);\n if(lookupAlias(alias) != -1)\n {\n editStatus = DUPLICATE_ALIAS;\n return QString();\n }\n }\n\n \/\/ Add entry\n\n return QString::fromStdString(strAlias);\n}\nvoid AliasTableModel::clear()\n{\n\tbeginResetModel();\n priv->cachedAliasTable.clear();\n\tendResetModel();\n}\n\n\/* Look up value for alias, if not found return empty string.\n *\/\nQString AliasTableModel::valueForAlias(const QString &alias) const\n{\n\tCBitcoinAddress address_parsed(alias.toStdString());\n\tif(address_parsed.IsValid() && address_parsed.isAlias)\n\t\treturn QString::fromStdString(address_parsed.ToString());\n return QString::fromStdString(\"{}\");\n}\n\nint AliasTableModel::lookupAlias(const QString &alias) const\n{\n QModelIndexList lst = match(index(0, Name, QModelIndex()),\n Qt::EditRole, alias, 1, Qt::MatchExactly);\n if(lst.isEmpty())\n {\n return -1;\n }\n else\n {\n return lst.at(0).row();\n }\n}\n\nvoid AliasTableModel::emitDataChanged(int idx)\n{\n emit dataChanged(index(idx, 0, QModelIndex()), index(idx, columns.length()-1, QModelIndex()));\n}\n<commit_msg>fixed extern function signature in assettablemodel<commit_after>#include \"aliastablemodel.h\"\n\n#include \"guiutil.h\"\n#include \"walletmodel.h\"\n\n#include \"wallet.h\"\n#include \"base58.h\"\n\n#include <QFont>\n\nusing namespace std;\nbool GetValueOfAliasTxHash(const uint256 &txHash, vector<unsigned char>& vchValue, uint256& hash, int64& nHeight);\n\nconst QString AliasTableModel::Alias = \"A\";\nconst QString AliasTableModel::DataAlias = \"D\";\n\nclass CAliasDB;\n\nextern CAliasDB *paliasdb;\n\nint64 GetAliasExpirationDepth(int64 nHeight);\nint64 GetAliasTxHashHeight(const uint256 txHash);\nstruct AliasTableEntry\n{\n enum Type {\n Alias,\n DataAlias\n };\n\n Type type;\n QString value;\n QString alias;\n QString expirationdepth;\n\n AliasTableEntry() {}\n AliasTableEntry(Type type, const QString &value, const QString &alias, const QString &expirationdepth):\n type(type), value(value), alias(alias), expirationdepth(expirationdepth) {}\n};\n\nstruct AliasTableEntryLessThan\n{\n bool operator()(const AliasTableEntry &a, const AliasTableEntry &b) const\n {\n return a.alias < b.alias;\n }\n bool operator()(const AliasTableEntry &a, const QString &b) const\n {\n return a.alias < b;\n }\n bool operator()(const QString &a, const AliasTableEntry &b) const\n {\n return a < b.alias;\n }\n};\n\n#define NAMEMAPTYPE map<vector<unsigned char>, uint256>\n\n\/\/ Private implementation\nclass AliasTablePriv\n{\npublic:\n CWallet *wallet;\n QList<AliasTableEntry> cachedAliasTable;\n AliasTableModel *parent;\n\n AliasTablePriv(CWallet *wallet, AliasTableModel *parent):\n wallet(wallet), parent(parent) {}\n\n void refreshAliasTable(AliasModelType type)\n {\n\n cachedAliasTable.clear();\n {\n TRY_LOCK(wallet->cs_wallet, cs_trywallet);\n\t\t\tBOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, wallet->mapWallet)\n\t\t\t{\n\t\t\t\t\t\/\/ get txn hash, read txn index\n\t\t\t\t\tCTransaction &tx = item.second;\n\t\t\t\t\tCTransaction lastTx;\n\t\t\t\t\t\/\/ skip non-syscoin txns\n\t\t\t\t\tif (tx.nVersion != SYSCOIN_TX_VERSION)\n\t\t\t\t\t\tcontinue;\n\n int op, nOut, nHeight;\n\t\t\t\t\t\n vector<vector<unsigned char> > vvchArgs;\n\t\t\t\t\tvector<unsigned char> vchValue;\n bool o = DecodeAliasTx(tx, op, nOut, vvchArgs, -1);\n\t\t\t\t\t\/\/ prune out this tx if its not an alias that is yours\n if (type != MyAlias || !o || !IsAliasOp(op) || !IsAliasMine(tx)) continue;\n if (op == OP_ALIAS_NEW) continue;\n\t\t\t\t\t \n\t\t\t\t\t\/\/ check for alias existence in DB (check that the alias wasn't transferred)\n\t\t\t\t\tvector<CAliasIndex> vtxPos;\n\t\t\t\t\tif (!paliasdb->ReadAlias(vvchArgs[0], vtxPos))\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\tif (vtxPos.size() < 1)\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\tuint256 hashBlock;\n\t\t\t\t\tuint256 txHash = vtxPos.back().txHash;\n\t\t\t\t\tif (!GetTransaction(txHash, lastTx, hashBlock, true))\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\/\/ alias was transferred because it was mine before, but the last alias address isn't yours\n\t\t\t\t\tif (!IsAliasMine(lastTx)) continue; \n\t\t\t\t\t\/\/ get alias data\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\tif (!GetValueOfAliasTxHash(txHash, vchValue, hashBlock, nHeight))\n\t\t\t\t\t\tcontinue;\n\n\t\t\t\t\tunsigned long nExpDepth = nHeight + GetAliasExpirationDepth(nHeight) - pindexBest->nHeight;\n\t\t\t\t\tstd::string strExpDepth;\n\t\t\t\t\tif(nExpDepth <= 0) \n\t\t\t\t\t\tstrExpDepth = \"Expired\";\n\t\t\t\t\telse\n\t\t\t\t\t\tstrExpDepth = strprintf(\"%lu\", nExpDepth);\n\t\t\t\t\tupdateEntry(QString::fromStdString(stringFromVch(vvchArgs[0])), QString::fromStdString(stringFromVch(vchValue)), QString::fromStdString(strExpDepth),type, CT_NEW); \n\t\t\t\t\t\n\t\t\n\n }\n }\n \/\/ qLowerBound() and qUpperBound() require our cachedAliasTable list to be sorted in asc order\n qSort(cachedAliasTable.begin(), cachedAliasTable.end(), AliasTableEntryLessThan());\n }\n\n void updateEntry(const QString &alias, const QString &value, const QString &exp, AliasModelType type, int status)\n {\n\t\tif(!parent || parent->modelType != type)\n\t\t{\n\t\t\treturn;\n\t\t}\n \/\/ Find alias \/ value in model\n QList<AliasTableEntry>::iterator lower = qLowerBound(\n cachedAliasTable.begin(), cachedAliasTable.end(), alias, AliasTableEntryLessThan());\n QList<AliasTableEntry>::iterator upper = qUpperBound(\n cachedAliasTable.begin(), cachedAliasTable.end(), alias, AliasTableEntryLessThan());\n int lowerIndex = (lower - cachedAliasTable.begin());\n int upperIndex = (upper - cachedAliasTable.begin());\n bool inModel = (lower != upper);\n\t\tint index;\n AliasTableEntry::Type newEntryType = \/*isData ? AliasTableEntry::DataAlias :*\/ AliasTableEntry::Alias;\n\n switch(status)\n {\n case CT_NEW:\n\t\t\tindex = parent->lookupAlias(alias);\n if(inModel || index != -1)\n {\n OutputDebugStringF(\"Warning: AliasTablePriv::updateEntry: Got CT_NOW, but entry is already in model\\n\");\n break;\n \n }\n parent->beginInsertRows(QModelIndex(), lowerIndex, lowerIndex);\n cachedAliasTable.insert(lowerIndex, AliasTableEntry(newEntryType, value, alias, exp));\n parent->endInsertRows();\n break;\n case CT_UPDATED:\n if(!inModel)\n {\n OutputDebugStringF(\"Warning: AliasTablePriv::updateEntry: Got CT_UPDATED, but entry is not in model\\n\");\n break;\n }\n lower->type = newEntryType;\n lower->value = value;\n lower->expirationdepth = exp;\n parent->emitDataChanged(lowerIndex);\n break;\n case CT_DELETED:\n if(!inModel)\n {\n OutputDebugStringF(\"Warning: AliasTablePriv::updateEntry: Got CT_DELETED, but entry is not in model\\n\");\n break;\n }\n parent->beginRemoveRows(QModelIndex(), lowerIndex, upperIndex-1);\n cachedAliasTable.erase(lower, upper);\n parent->endRemoveRows();\n break;\n }\n }\n\n int size()\n {\n return cachedAliasTable.size();\n }\n\n AliasTableEntry *index(int idx)\n {\n if(idx >= 0 && idx < cachedAliasTable.size())\n {\n return &cachedAliasTable[idx];\n }\n else\n {\n return 0;\n }\n }\n};\n\nAliasTableModel::AliasTableModel(CWallet *wallet, WalletModel *parent, AliasModelType type) :\n QAbstractTableModel(parent),walletModel(parent),wallet(wallet),priv(0), modelType(type)\n{\n\n\tcolumns << tr(\"Alias\") << tr(\"Value\") << tr(\"Expires In\");\t\t \n priv = new AliasTablePriv(wallet, this);\n}\n\nAliasTableModel::~AliasTableModel()\n{\n delete priv;\n}\nvoid AliasTableModel::refreshAliasTable() \n{\n\tclear();\n\tpriv->refreshAliasTable(modelType);\n}\nint AliasTableModel::rowCount(const QModelIndex &parent) const\n{\n Q_UNUSED(parent);\n return priv->size();\n}\n\nint AliasTableModel::columnCount(const QModelIndex &parent) const\n{\n Q_UNUSED(parent);\n return columns.length();\n}\n\nQVariant AliasTableModel::data(const QModelIndex &index, int role) const\n{\n if(!index.isValid())\n return QVariant();\n\n AliasTableEntry *rec = static_cast<AliasTableEntry*>(index.internalPointer());\n\n if(role == Qt::DisplayRole || role == Qt::EditRole)\n {\n switch(index.column())\n {\n case Value:\n return rec->value;\n case Name:\n return rec->alias;\n case ExpirationDepth:\n return rec->expirationdepth;\n }\n }\n else if (role == Qt::FontRole)\n {\n QFont font;\n if(index.column() == Value)\n {\n font = GUIUtil::bitcoinAddressFont();\n }\n return font;\n }\n else if (role == TypeRole)\n {\n switch(rec->type)\n {\n case AliasTableEntry::Alias:\n return Alias;\n case AliasTableEntry::DataAlias:\n return DataAlias;\n default: break;\n }\n }\n return QVariant();\n}\n\nbool AliasTableModel::setData(const QModelIndex &index, const QVariant &value, int role)\n{\n if(!index.isValid())\n return false;\n AliasTableEntry *rec = static_cast<AliasTableEntry*>(index.internalPointer());\n\n editStatus = OK;\n\n if(role == Qt::EditRole)\n {\n switch(index.column())\n {\n case ExpirationDepth:\n \/\/ Do nothing, if old value == new value\n if(rec->expirationdepth == value.toString())\n {\n editStatus = NO_CHANGES;\n return false;\n }\n \/\/wallet->SetAddressBookName(CBitcoinAlias(rec->alias.toStdString()).Get(), value.toString().toStdString());\n break;\n case Value:\n \/\/ Do nothing, if old value == new value\n if(rec->value == value.toString())\n {\n editStatus = NO_CHANGES;\n return false;\n }\n \/\/wallet->SetAddressBookName(CBitcoinAlias(rec->alias.toStdString()).Get(), value.toString().toStdString());\n break;\n case Name:\n \/\/ Do nothing, if old alias == new alias\n if(rec->alias == value.toString())\n {\n editStatus = NO_CHANGES;\n return false;\n }\n \/\/ Check for duplicate aliases to prevent accidental deletion of aliases, if you try\n \/\/ to paste an existing alias over another alias (with a different label)\n else if(lookupAlias(rec->alias) != -1)\n {\n editStatus = DUPLICATE_ALIAS;\n return false;\n }\n \/\/ Double-check that we're not overwriting a receiving alias\n else if(rec->type == AliasTableEntry::Alias)\n {\n {\n \/\/ update alias\n }\n }\n break;\n }\n return true;\n }\n return false;\n}\n\nQVariant AliasTableModel::headerData(int section, Qt::Orientation orientation, int role) const\n{\n if(orientation == Qt::Horizontal)\n {\n if(role == Qt::DisplayRole)\n {\n return columns[section];\n }\n }\n return QVariant();\n}\n\nQt::ItemFlags AliasTableModel::flags(const QModelIndex &index) const\n{\n if(!index.isValid())\n return 0;\n Qt::ItemFlags retval = Qt::ItemIsSelectable | Qt::ItemIsEnabled;\n return retval;\n}\n\nQModelIndex AliasTableModel::index(int row, int column, const QModelIndex &parent) const\n{\n Q_UNUSED(parent);\n AliasTableEntry *data = priv->index(row);\n if(data)\n {\n return createIndex(row, column, priv->index(row));\n }\n else\n {\n return QModelIndex();\n }\n}\n\nvoid AliasTableModel::updateEntry(const QString &alias, const QString &value, const QString &exp, AliasModelType type, int status)\n{\n \/\/ Update alias book model from Bitcoin core\n priv->updateEntry(alias, value, exp, type, status);\n}\n\nQString AliasTableModel::addRow(const QString &type, const QString &value, const QString &alias, const QString &exp)\n{\n std::string strValue = value.toStdString();\n std::string strAlias = alias.toStdString();\n std::string strExp = exp.toStdString();\n\n editStatus = OK;\n \/\/ Check for duplicate aliases\n {\n LOCK(wallet->cs_wallet);\n if(lookupAlias(alias) != -1)\n {\n editStatus = DUPLICATE_ALIAS;\n return QString();\n }\n }\n\n \/\/ Add entry\n\n return QString::fromStdString(strAlias);\n}\nvoid AliasTableModel::clear()\n{\n\tbeginResetModel();\n priv->cachedAliasTable.clear();\n\tendResetModel();\n}\n\n\/* Look up value for alias, if not found return empty string.\n *\/\nQString AliasTableModel::valueForAlias(const QString &alias) const\n{\n\tCBitcoinAddress address_parsed(alias.toStdString());\n\tif(address_parsed.IsValid() && address_parsed.isAlias)\n\t\treturn QString::fromStdString(address_parsed.ToString());\n return QString::fromStdString(\"{}\");\n}\n\nint AliasTableModel::lookupAlias(const QString &alias) const\n{\n QModelIndexList lst = match(index(0, Name, QModelIndex()),\n Qt::EditRole, alias, 1, Qt::MatchExactly);\n if(lst.isEmpty())\n {\n return -1;\n }\n else\n {\n return lst.at(0).row();\n }\n}\n\nvoid AliasTableModel::emitDataChanged(int idx)\n{\n emit dataChanged(index(idx, 0, QModelIndex()), index(idx, columns.length()-1, QModelIndex()));\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"aliastablemodel.h\"\n\n#include \"guiutil.h\"\n#include \"walletmodel.h\"\n\n#include \"wallet.h\"\n#include \"base58.h\"\n\n#include <QFont>\n\nusing namespace std;\nbool GetValueOfAliasTxHash(const uint256 &txHash, vector<unsigned char>& vchValue, uint256& hash, int& nHeight);\n\nconst QString AliasTableModel::Alias = \"A\";\nconst QString AliasTableModel::DataAlias = \"D\";\n\nclass CAliasDB;\n\nextern CAliasDB *paliasdb;\n\nint GetAliasExpirationDepth(int nHeight);\nint GetAliasTxHashHeight(const uint256 txHash);\nstruct AliasTableEntry\n{\n enum Type {\n Alias,\n DataAlias\n };\n\n Type type;\n QString value;\n QString alias;\n QString expirationdepth;\n\n AliasTableEntry() {}\n AliasTableEntry(Type type, const QString &value, const QString &alias, const QString &expirationdepth):\n type(type), value(value), alias(alias), expirationdepth(expirationdepth) {}\n};\n\nstruct AliasTableEntryLessThan\n{\n bool operator()(const AliasTableEntry &a, const AliasTableEntry &b) const\n {\n return a.alias < b.alias;\n }\n bool operator()(const AliasTableEntry &a, const QString &b) const\n {\n return a.alias < b;\n }\n bool operator()(const QString &a, const AliasTableEntry &b) const\n {\n return a < b.alias;\n }\n};\n\n#define NAMEMAPTYPE map<vector<unsigned char>, uint256>\n\n\/\/ Private implementation\nclass AliasTablePriv\n{\npublic:\n CWallet *wallet;\n QList<AliasTableEntry> cachedAliasTable;\n AliasTableModel *parent;\n\n AliasTablePriv(CWallet *wallet, AliasTableModel *parent):\n wallet(wallet), parent(parent) {}\n\n void refreshAliasTable(AliasModelType type)\n {\n\n cachedAliasTable.clear();\n {\n TRY_LOCK(wallet->cs_wallet, cs_trywallet);\n\t\t\tBOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, wallet->mapWallet)\n\t\t\t{\n\t\t\t\t\t\/\/ get txn hash, read txn index\n\t\t\t\t\tCTransaction &tx = item.second;\n\t\t\t\t\tCTransaction lastTx;\n\t\t\t\t\t\/\/ skip non-syscoin txns\n\t\t\t\t\tif (tx.nVersion != SYSCOIN_TX_VERSION)\n\t\t\t\t\t\tcontinue;\n\n int op, nOut, nHeight;\n\t\t\t\t\t\n vector<vector<unsigned char> > vvchArgs;\n\t\t\t\t\tvector<unsigned char> vchValue;\n bool o = DecodeAliasTx(tx, op, nOut, vvchArgs, -1);\n\t\t\t\t\t\/\/ prune out this tx if its not an alias that is yours\n if (type != MyAlias || !o || !IsAliasOp(op) || !IsAliasMine(tx)) continue;\n if (op == OP_ALIAS_NEW) continue;\n\t\t\t\t\t \n\t\t\t\t\t\/\/ check for alias existence in DB (check that the alias wasn't transferred)\n\t\t\t\t\tvector<CAliasIndex> vtxPos;\n\t\t\t\t\tif (!paliasdb->ReadAlias(vvchArgs[0], vtxPos))\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\tif (vtxPos.size() < 1)\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\/\/ alias was transferred because it was mine before, but the last alias address isn't yours\n\t\t\t\t\tif (!IsAliasMine(tx)) continue; \n\t\t\t\t\t\/\/ get alias data\n\t\t\t\t\tuint256 hash;\n\t\t\t\t\tuint256 txHash = vtxPos.back().txHash;\n\t\t\t\t\tif (!GetValueOfAliasTxHash(txHash, vchValue, hash, nHeight))\n\t\t\t\t\t\tcontinue;\n\n\t\t\t\t\tunsigned long nExpDepth = nHeight + GetAliasExpirationDepth(nHeight) - pindexBest->nHeight;\n\t\t\t\t\tstd::string strExpDepth;\n\t\t\t\t\tif(nExpDepth <= 0) \n\t\t\t\t\t\tstrExpDepth = \"Expired\";\n\t\t\t\t\telse\n\t\t\t\t\t\tstrExpDepth = strprintf(\"%lu\", nExpDepth);\n\t\t\t\t\tupdateEntry(QString::fromStdString(stringFromVch(vvchArgs[0])), QString::fromStdString(stringFromVch(vchValue)), QString::fromStdString(strExpDepth),type, CT_NEW); \n\t\t\t\t\t\n\t\t\n\n }\n }\n \/\/ qLowerBound() and qUpperBound() require our cachedAliasTable list to be sorted in asc order\n qSort(cachedAliasTable.begin(), cachedAliasTable.end(), AliasTableEntryLessThan());\n }\n\n void updateEntry(const QString &alias, const QString &value, const QString &exp, AliasModelType type, int status)\n {\n\t\tif(!parent || parent->modelType != type)\n\t\t{\n\t\t\treturn;\n\t\t}\n \/\/ Find alias \/ value in model\n QList<AliasTableEntry>::iterator lower = qLowerBound(\n cachedAliasTable.begin(), cachedAliasTable.end(), alias, AliasTableEntryLessThan());\n QList<AliasTableEntry>::iterator upper = qUpperBound(\n cachedAliasTable.begin(), cachedAliasTable.end(), alias, AliasTableEntryLessThan());\n int lowerIndex = (lower - cachedAliasTable.begin());\n int upperIndex = (upper - cachedAliasTable.begin());\n bool inModel = (lower != upper);\n\t\tint index;\n AliasTableEntry::Type newEntryType = \/*isData ? AliasTableEntry::DataAlias :*\/ AliasTableEntry::Alias;\n\n switch(status)\n {\n case CT_NEW:\n\t\t\tindex = parent->lookupAlias(alias);\n if(inModel || index != -1)\n {\n\t\t\t\tlower->type = newEntryType;\n\t\t\t\tlower->value = value;\n\t\t\t\tlower->expirationdepth = exp;\n\t\t\t\tif(inModel)\n\t\t\t\t\tparent->emitDataChanged(lowerIndex);\n\t\t\t\telse\n\t\t\t\t\tparent->emitDataChanged(index);\n\t\t\t\tbreak;\n }\n parent->beginInsertRows(QModelIndex(), lowerIndex, lowerIndex);\n cachedAliasTable.insert(lowerIndex, AliasTableEntry(newEntryType, value, alias, exp));\n parent->endInsertRows();\n break;\n case CT_UPDATED:\n if(!inModel)\n {\n OutputDebugStringF(\"Warning: AliasTablePriv::updateEntry: Got CT_UPDATED, but entry is not in model\\n\");\n break;\n }\n lower->type = newEntryType;\n lower->value = value;\n lower->expirationdepth = exp;\n parent->emitDataChanged(lowerIndex);\n break;\n case CT_DELETED:\n if(!inModel)\n {\n OutputDebugStringF(\"Warning: AliasTablePriv::updateEntry: Got CT_DELETED, but entry is not in model\\n\");\n break;\n }\n parent->beginRemoveRows(QModelIndex(), lowerIndex, upperIndex-1);\n cachedAliasTable.erase(lower, upper);\n parent->endRemoveRows();\n break;\n }\n }\n\n int size()\n {\n return cachedAliasTable.size();\n }\n\n AliasTableEntry *index(int idx)\n {\n if(idx >= 0 && idx < cachedAliasTable.size())\n {\n return &cachedAliasTable[idx];\n }\n else\n {\n return 0;\n }\n }\n};\n\nAliasTableModel::AliasTableModel(CWallet *wallet, WalletModel *parent, AliasModelType type) :\n QAbstractTableModel(parent),walletModel(parent),wallet(wallet),priv(0), modelType(type)\n{\n\n\tcolumns << tr(\"Alias\") << tr(\"Value\") << tr(\"Expires In\");\t\t \n priv = new AliasTablePriv(wallet, this);\n}\n\nAliasTableModel::~AliasTableModel()\n{\n delete priv;\n}\nvoid AliasTableModel::refreshAliasTable() \n{\n\tclear();\n\tpriv->refreshAliasTable(modelType);\n}\nint AliasTableModel::rowCount(const QModelIndex &parent) const\n{\n Q_UNUSED(parent);\n return priv->size();\n}\n\nint AliasTableModel::columnCount(const QModelIndex &parent) const\n{\n Q_UNUSED(parent);\n return columns.length();\n}\n\nQVariant AliasTableModel::data(const QModelIndex &index, int role) const\n{\n if(!index.isValid())\n return QVariant();\n\n AliasTableEntry *rec = static_cast<AliasTableEntry*>(index.internalPointer());\n\n if(role == Qt::DisplayRole || role == Qt::EditRole)\n {\n switch(index.column())\n {\n case Value:\n return rec->value;\n case Name:\n return rec->alias;\n case ExpirationDepth:\n return rec->expirationdepth;\n }\n }\n else if (role == Qt::FontRole)\n {\n QFont font;\n if(index.column() == Value)\n {\n font = GUIUtil::bitcoinAddressFont();\n }\n return font;\n }\n else if (role == TypeRole)\n {\n switch(rec->type)\n {\n case AliasTableEntry::Alias:\n return Alias;\n case AliasTableEntry::DataAlias:\n return DataAlias;\n default: break;\n }\n }\n return QVariant();\n}\n\nbool AliasTableModel::setData(const QModelIndex &index, const QVariant &value, int role)\n{\n if(!index.isValid())\n return false;\n AliasTableEntry *rec = static_cast<AliasTableEntry*>(index.internalPointer());\n\n editStatus = OK;\n\n if(role == Qt::EditRole)\n {\n switch(index.column())\n {\n case ExpirationDepth:\n \/\/ Do nothing, if old value == new value\n if(rec->expirationdepth == value.toString())\n {\n editStatus = NO_CHANGES;\n return false;\n }\n \/\/wallet->SetAddressBookName(CBitcoinAlias(rec->alias.toStdString()).Get(), value.toString().toStdString());\n break;\n case Value:\n \/\/ Do nothing, if old value == new value\n if(rec->value == value.toString())\n {\n editStatus = NO_CHANGES;\n return false;\n }\n \/\/wallet->SetAddressBookName(CBitcoinAlias(rec->alias.toStdString()).Get(), value.toString().toStdString());\n break;\n case Name:\n \/\/ Do nothing, if old alias == new alias\n if(rec->alias == value.toString())\n {\n editStatus = NO_CHANGES;\n return false;\n }\n \/\/ Check for duplicate aliases to prevent accidental deletion of aliases, if you try\n \/\/ to paste an existing alias over another alias (with a different label)\n else if(lookupAlias(rec->alias) != -1)\n {\n editStatus = DUPLICATE_ALIAS;\n return false;\n }\n \/\/ Double-check that we're not overwriting a receiving alias\n else if(rec->type == AliasTableEntry::Alias)\n {\n {\n \/\/ update alias\n }\n }\n break;\n }\n return true;\n }\n return false;\n}\n\nQVariant AliasTableModel::headerData(int section, Qt::Orientation orientation, int role) const\n{\n if(orientation == Qt::Horizontal)\n {\n if(role == Qt::DisplayRole)\n {\n return columns[section];\n }\n }\n return QVariant();\n}\n\nQt::ItemFlags AliasTableModel::flags(const QModelIndex &index) const\n{\n if(!index.isValid())\n return 0;\n Qt::ItemFlags retval = Qt::ItemIsSelectable | Qt::ItemIsEnabled;\n return retval;\n}\n\nQModelIndex AliasTableModel::index(int row, int column, const QModelIndex &parent) const\n{\n Q_UNUSED(parent);\n AliasTableEntry *data = priv->index(row);\n if(data)\n {\n return createIndex(row, column, priv->index(row));\n }\n else\n {\n return QModelIndex();\n }\n}\n\nvoid AliasTableModel::updateEntry(const QString &alias, const QString &value, const QString &exp, AliasModelType type, int status)\n{\n \/\/ Update alias book model from Bitcoin core\n priv->updateEntry(alias, value, exp, type, status);\n}\n\nQString AliasTableModel::addRow(const QString &type, const QString &value, const QString &alias, const QString &exp)\n{\n std::string strValue = value.toStdString();\n std::string strAlias = alias.toStdString();\n std::string strExp = exp.toStdString();\n\n editStatus = OK;\n \/\/ Check for duplicate aliases\n {\n LOCK(wallet->cs_wallet);\n if(lookupAlias(alias) != -1)\n {\n editStatus = DUPLICATE_ALIAS;\n return QString();\n }\n }\n\n \/\/ Add entry\n\n return QString::fromStdString(strAlias);\n}\nvoid AliasTableModel::clear()\n{\n\tbeginResetModel();\n priv->cachedAliasTable.clear();\n\tendResetModel();\n}\n\n\/* Look up value for alias, if not found return empty string.\n *\/\nQString AliasTableModel::valueForAlias(const QString &alias) const\n{\n\tCBitcoinAddress address_parsed(alias.toStdString());\n\tif(address_parsed.IsValid() && address_parsed.isAlias)\n\t\treturn QString::fromStdString(address_parsed.ToString());\n return QString::fromStdString(\"{}\");\n}\n\nint AliasTableModel::lookupAlias(const QString &alias) const\n{\n QModelIndexList lst = match(index(0, Name, QModelIndex()),\n Qt::EditRole, alias, 1, Qt::MatchExactly);\n if(lst.isEmpty())\n {\n return -1;\n }\n else\n {\n return lst.at(0).row();\n }\n}\n\nvoid AliasTableModel::emitDataChanged(int idx)\n{\n emit dataChanged(index(idx, 0, QModelIndex()), index(idx, columns.length()-1, QModelIndex()));\n}\n<commit_msg>Part of last commit<commit_after>#include \"aliastablemodel.h\"\n\n#include \"guiutil.h\"\n#include \"walletmodel.h\"\n\n#include \"wallet.h\"\n#include \"base58.h\"\n\n#include <QFont>\n\nusing namespace std;\nbool GetValueOfAliasTxHash(const uint256 &txHash, vector<unsigned char>& vchValue, uint256& hash, int& nHeight);\n\nconst QString AliasTableModel::Alias = \"A\";\nconst QString AliasTableModel::DataAlias = \"D\";\n\nclass CAliasDB;\n\nextern CAliasDB *paliasdb;\n\nint GetAliasExpirationDepth(int nHeight);\nint GetAliasTxHashHeight(const uint256 txHash);\nstruct AliasTableEntry\n{\n enum Type {\n Alias,\n DataAlias\n };\n\n Type type;\n QString value;\n QString alias;\n QString expirationdepth;\n\n AliasTableEntry() {}\n AliasTableEntry(Type type, const QString &value, const QString &alias, const QString &expirationdepth):\n type(type), value(value), alias(alias), expirationdepth(expirationdepth) {}\n};\n\nstruct AliasTableEntryLessThan\n{\n bool operator()(const AliasTableEntry &a, const AliasTableEntry &b) const\n {\n return a.alias < b.alias;\n }\n bool operator()(const AliasTableEntry &a, const QString &b) const\n {\n return a.alias < b;\n }\n bool operator()(const QString &a, const AliasTableEntry &b) const\n {\n return a < b.alias;\n }\n};\n\n#define NAMEMAPTYPE map<vector<unsigned char>, uint256>\n\n\/\/ Private implementation\nclass AliasTablePriv\n{\npublic:\n CWallet *wallet;\n QList<AliasTableEntry> cachedAliasTable;\n AliasTableModel *parent;\n\n AliasTablePriv(CWallet *wallet, AliasTableModel *parent):\n wallet(wallet), parent(parent) {}\n\n void refreshAliasTable(AliasModelType type)\n {\n\n cachedAliasTable.clear();\n {\n TRY_LOCK(wallet->cs_wallet, cs_trywallet);\n\t\t\tBOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, wallet->mapWallet)\n\t\t\t{\n\t\t\t\t\t\/\/ get txn hash, read txn index\n\t\t\t\t\tCTransaction &tx = item.second;\n\t\t\t\t\tCTransaction lastTx;\n\t\t\t\t\t\/\/ skip non-syscoin txns\n\t\t\t\t\tif (tx.nVersion != SYSCOIN_TX_VERSION)\n\t\t\t\t\t\tcontinue;\n\n int op, nOut, nHeight;\n\t\t\t\t\t\n vector<vector<unsigned char> > vvchArgs;\n\t\t\t\t\tvector<unsigned char> vchValue;\n bool o = DecodeAliasTx(tx, op, nOut, vvchArgs, -1);\n\t\t\t\t\t\/\/ prune out this tx if its not an alias that is yours\n if (type != MyAlias || !o || !IsAliasOp(op) || !IsAliasMine(tx)) continue;\n if (op == OP_ALIAS_NEW) continue;\n\t\t\t\t\t \n\t\t\t\t\t\/\/ check for alias existence in DB (check that the alias wasn't transferred)\n\t\t\t\t\tvector<CAliasIndex> vtxPos;\n\t\t\t\t\tif (!paliasdb->ReadAlias(vvchArgs[0], vtxPos))\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\tif (vtxPos.size() < 1)\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\tuint256 hashBlock;\n\t\t\t\t\tuint256 txHash = vtxPos.back().txHash;\n\t\t\t\t\tif (!GetTransaction(txHash, lastTx, hashBlock, true))\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\/\/ alias was transferred because it was mine before, but the last alias address isn't yours\n\t\t\t\t\tif (!IsAliasMine(lastTx)) continue; \n\t\t\t\t\t\/\/ get alias data\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\tif (!GetValueOfAliasTxHash(txHash, vchValue, hashBlock, nHeight))\n\t\t\t\t\t\tcontinue;\n\n\t\t\t\t\tunsigned long nExpDepth = nHeight + GetAliasExpirationDepth(nHeight) - pindexBest->nHeight;\n\t\t\t\t\tstd::string strExpDepth;\n\t\t\t\t\tif(nExpDepth <= 0) \n\t\t\t\t\t\tstrExpDepth = \"Expired\";\n\t\t\t\t\telse\n\t\t\t\t\t\tstrExpDepth = strprintf(\"%lu\", nExpDepth);\n\t\t\t\t\tupdateEntry(QString::fromStdString(stringFromVch(vvchArgs[0])), QString::fromStdString(stringFromVch(vchValue)), QString::fromStdString(strExpDepth),type, CT_NEW); \n\t\t\t\t\t\n\t\t\n\n }\n }\n \/\/ qLowerBound() and qUpperBound() require our cachedAliasTable list to be sorted in asc order\n qSort(cachedAliasTable.begin(), cachedAliasTable.end(), AliasTableEntryLessThan());\n }\n\n void updateEntry(const QString &alias, const QString &value, const QString &exp, AliasModelType type, int status)\n {\n\t\tif(!parent || parent->modelType != type)\n\t\t{\n\t\t\treturn;\n\t\t}\n \/\/ Find alias \/ value in model\n QList<AliasTableEntry>::iterator lower = qLowerBound(\n cachedAliasTable.begin(), cachedAliasTable.end(), alias, AliasTableEntryLessThan());\n QList<AliasTableEntry>::iterator upper = qUpperBound(\n cachedAliasTable.begin(), cachedAliasTable.end(), alias, AliasTableEntryLessThan());\n int lowerIndex = (lower - cachedAliasTable.begin());\n int upperIndex = (upper - cachedAliasTable.begin());\n bool inModel = (lower != upper);\n\t\tint index;\n AliasTableEntry::Type newEntryType = \/*isData ? AliasTableEntry::DataAlias :*\/ AliasTableEntry::Alias;\n\n switch(status)\n {\n case CT_NEW:\n\t\t\tindex = parent->lookupAlias(alias);\n if(inModel || index != -1)\n {\n OutputDebugStringF(\"Warning: AliasTablePriv::updateEntry: Got CT_NOW, but entry is already in model\\n\");\n break;\n \n }\n parent->beginInsertRows(QModelIndex(), lowerIndex, lowerIndex);\n cachedAliasTable.insert(lowerIndex, AliasTableEntry(newEntryType, value, alias, exp));\n parent->endInsertRows();\n break;\n case CT_UPDATED:\n if(!inModel)\n {\n OutputDebugStringF(\"Warning: AliasTablePriv::updateEntry: Got CT_UPDATED, but entry is not in model\\n\");\n break;\n }\n lower->type = newEntryType;\n lower->value = value;\n lower->expirationdepth = exp;\n parent->emitDataChanged(lowerIndex);\n break;\n case CT_DELETED:\n if(!inModel)\n {\n OutputDebugStringF(\"Warning: AliasTablePriv::updateEntry: Got CT_DELETED, but entry is not in model\\n\");\n break;\n }\n parent->beginRemoveRows(QModelIndex(), lowerIndex, upperIndex-1);\n cachedAliasTable.erase(lower, upper);\n parent->endRemoveRows();\n break;\n }\n }\n\n int size()\n {\n return cachedAliasTable.size();\n }\n\n AliasTableEntry *index(int idx)\n {\n if(idx >= 0 && idx < cachedAliasTable.size())\n {\n return &cachedAliasTable[idx];\n }\n else\n {\n return 0;\n }\n }\n};\n\nAliasTableModel::AliasTableModel(CWallet *wallet, WalletModel *parent, AliasModelType type) :\n QAbstractTableModel(parent),walletModel(parent),wallet(wallet),priv(0), modelType(type)\n{\n\n\tcolumns << tr(\"Alias\") << tr(\"Value\") << tr(\"Expires In\");\t\t \n priv = new AliasTablePriv(wallet, this);\n}\n\nAliasTableModel::~AliasTableModel()\n{\n delete priv;\n}\nvoid AliasTableModel::refreshAliasTable() \n{\n\tclear();\n\tpriv->refreshAliasTable(modelType);\n}\nint AliasTableModel::rowCount(const QModelIndex &parent) const\n{\n Q_UNUSED(parent);\n return priv->size();\n}\n\nint AliasTableModel::columnCount(const QModelIndex &parent) const\n{\n Q_UNUSED(parent);\n return columns.length();\n}\n\nQVariant AliasTableModel::data(const QModelIndex &index, int role) const\n{\n if(!index.isValid())\n return QVariant();\n\n AliasTableEntry *rec = static_cast<AliasTableEntry*>(index.internalPointer());\n\n if(role == Qt::DisplayRole || role == Qt::EditRole)\n {\n switch(index.column())\n {\n case Value:\n return rec->value;\n case Name:\n return rec->alias;\n case ExpirationDepth:\n return rec->expirationdepth;\n }\n }\n else if (role == Qt::FontRole)\n {\n QFont font;\n if(index.column() == Value)\n {\n font = GUIUtil::bitcoinAddressFont();\n }\n return font;\n }\n else if (role == TypeRole)\n {\n switch(rec->type)\n {\n case AliasTableEntry::Alias:\n return Alias;\n case AliasTableEntry::DataAlias:\n return DataAlias;\n default: break;\n }\n }\n return QVariant();\n}\n\nbool AliasTableModel::setData(const QModelIndex &index, const QVariant &value, int role)\n{\n if(!index.isValid())\n return false;\n AliasTableEntry *rec = static_cast<AliasTableEntry*>(index.internalPointer());\n\n editStatus = OK;\n\n if(role == Qt::EditRole)\n {\n switch(index.column())\n {\n case ExpirationDepth:\n \/\/ Do nothing, if old value == new value\n if(rec->expirationdepth == value.toString())\n {\n editStatus = NO_CHANGES;\n return false;\n }\n \/\/wallet->SetAddressBookName(CBitcoinAlias(rec->alias.toStdString()).Get(), value.toString().toStdString());\n break;\n case Value:\n \/\/ Do nothing, if old value == new value\n if(rec->value == value.toString())\n {\n editStatus = NO_CHANGES;\n return false;\n }\n \/\/wallet->SetAddressBookName(CBitcoinAlias(rec->alias.toStdString()).Get(), value.toString().toStdString());\n break;\n case Name:\n \/\/ Do nothing, if old alias == new alias\n if(rec->alias == value.toString())\n {\n editStatus = NO_CHANGES;\n return false;\n }\n \/\/ Check for duplicate aliases to prevent accidental deletion of aliases, if you try\n \/\/ to paste an existing alias over another alias (with a different label)\n else if(lookupAlias(rec->alias) != -1)\n {\n editStatus = DUPLICATE_ALIAS;\n return false;\n }\n \/\/ Double-check that we're not overwriting a receiving alias\n else if(rec->type == AliasTableEntry::Alias)\n {\n {\n \/\/ update alias\n }\n }\n break;\n }\n return true;\n }\n return false;\n}\n\nQVariant AliasTableModel::headerData(int section, Qt::Orientation orientation, int role) const\n{\n if(orientation == Qt::Horizontal)\n {\n if(role == Qt::DisplayRole)\n {\n return columns[section];\n }\n }\n return QVariant();\n}\n\nQt::ItemFlags AliasTableModel::flags(const QModelIndex &index) const\n{\n if(!index.isValid())\n return 0;\n Qt::ItemFlags retval = Qt::ItemIsSelectable | Qt::ItemIsEnabled;\n return retval;\n}\n\nQModelIndex AliasTableModel::index(int row, int column, const QModelIndex &parent) const\n{\n Q_UNUSED(parent);\n AliasTableEntry *data = priv->index(row);\n if(data)\n {\n return createIndex(row, column, priv->index(row));\n }\n else\n {\n return QModelIndex();\n }\n}\n\nvoid AliasTableModel::updateEntry(const QString &alias, const QString &value, const QString &exp, AliasModelType type, int status)\n{\n \/\/ Update alias book model from Bitcoin core\n priv->updateEntry(alias, value, exp, type, status);\n}\n\nQString AliasTableModel::addRow(const QString &type, const QString &value, const QString &alias, const QString &exp)\n{\n std::string strValue = value.toStdString();\n std::string strAlias = alias.toStdString();\n std::string strExp = exp.toStdString();\n\n editStatus = OK;\n \/\/ Check for duplicate aliases\n {\n LOCK(wallet->cs_wallet);\n if(lookupAlias(alias) != -1)\n {\n editStatus = DUPLICATE_ALIAS;\n return QString();\n }\n }\n\n \/\/ Add entry\n\n return QString::fromStdString(strAlias);\n}\nvoid AliasTableModel::clear()\n{\n\tbeginResetModel();\n priv->cachedAliasTable.clear();\n\tendResetModel();\n}\n\n\/* Look up value for alias, if not found return empty string.\n *\/\nQString AliasTableModel::valueForAlias(const QString &alias) const\n{\n\tCBitcoinAddress address_parsed(alias.toStdString());\n\tif(address_parsed.IsValid() && address_parsed.isAlias)\n\t\treturn QString::fromStdString(address_parsed.ToString());\n return QString::fromStdString(\"{}\");\n}\n\nint AliasTableModel::lookupAlias(const QString &alias) const\n{\n QModelIndexList lst = match(index(0, Name, QModelIndex()),\n Qt::EditRole, alias, 1, Qt::MatchExactly);\n if(lst.isEmpty())\n {\n return -1;\n }\n else\n {\n return lst.at(0).row();\n }\n}\n\nvoid AliasTableModel::emitDataChanged(int idx)\n{\n emit dataChanged(index(idx, 0, QModelIndex()), index(idx, columns.length()-1, QModelIndex()));\n}\n<|endoftext|>"} {"text":"<commit_before>#include <cassert>\n#include <cstdint>\n#include <string>\n\n#include <napi.h>\n#include \"..\/argon2\/include\/argon2.h\"\n\n#include <ciso646>\n\nusing namespace Napi;\n\n#ifndef _MSC_VER\nnamespace {\n#endif\n\nusing ustring = std::basic_string<uint8_t>;\nconst char* type2string(argon2_type type) { return argon2_type2string(type, false); };\n\nustring from_buffer(const Value& value)\n{\n const auto& buf = value.As<Buffer<uint8_t>>();\n return {buf.Data(), buf.Length()};\n}\n\nBuffer<uint8_t> to_buffer(const Env& env, const ustring& str)\n{\n return Buffer<uint8_t>::Copy(env, str.data(), str.size());\n}\n\nstruct Options {\n \/\/ TODO: remove ctors and initializers when GCC<5 stops shipping\n Options(Options&&) = default;\n\n ustring secret;\n ustring ad;\n\n uint32_t hash_length;\n uint32_t time_cost;\n uint32_t memory_cost;\n uint32_t parallelism;\n uint32_t version;\n\n argon2_type type;\n};\n\nargon2_context make_context(uint8_t* buf, const ustring& plain, const ustring& salt, const Options& opts)\n{\n argon2_context ctx;\n\n ctx.out = buf;\n ctx.outlen = opts.hash_length;\n ctx.pwd = const_cast<uint8_t*>(plain.data());\n ctx.pwdlen = plain.size();\n ctx.salt = const_cast<uint8_t*>(salt.data());\n ctx.saltlen = salt.length();\n ctx.secret = opts.secret.empty() ? nullptr : const_cast<uint8_t*>(opts.secret.data());\n ctx.secretlen = opts.secret.size();\n ctx.ad = opts.ad.empty() ? nullptr : const_cast<uint8_t*>(opts.ad.data());\n ctx.adlen = opts.ad.size();\n ctx.t_cost = opts.time_cost;\n ctx.m_cost = opts.memory_cost;\n ctx.lanes = opts.parallelism;\n ctx.threads = opts.parallelism;\n ctx.allocate_cbk = nullptr;\n ctx.free_cbk = nullptr;\n ctx.flags = ARGON2_DEFAULT_FLAGS;\n ctx.version = opts.version;\n\n return ctx;\n}\n\nclass HashWorker final: public AsyncWorker {\npublic:\n HashWorker(const Function& callback, ustring&& plain, ustring&& salt, Options&& opts):\n \/\/ TODO: use brackets when GCC <5 stops shipping\n AsyncWorker(callback, \"argon2:HashWorker\"),\n plain(std::move(plain)),\n salt(std::move(salt)),\n opts(std::move(opts))\n {}\n\n void Execute() override\n {\n uint8_t* buf = new uint8_t[opts.hash_length];\n\n auto ctx = make_context(buf, plain, salt, opts);\n int result = argon2_ctx(&ctx, opts.type);\n\n if (result != ARGON2_OK) {\n \/* LCOV_EXCL_START *\/\n SetError(argon2_error_message(result));\n \/* LCOV_EXCL_STOP *\/\n } else {\n hash.assign(buf, opts.hash_length);\n }\n\n std::fill_n(buf, opts.hash_length, 0);\n\n delete[] buf;\n }\n\n void OnOK() override\n {\n const auto& env = Env();\n HandleScope scope{env};\n Callback()({env.Undefined(), to_buffer(env, hash)});\n }\n\nprivate:\n ustring plain;\n ustring salt;\n Options opts;\n\n ustring hash;\n};\n\nOptions extract_opts(const Object& opts)\n{\n return {\n opts.Has(\"secret\") ? from_buffer(opts[\"secret\"]) : ustring{},\n opts.Has(\"associatedData\") ? from_buffer(opts[\"associatedData\"]) : ustring{},\n opts[\"hashLength\"].ToNumber(),\n opts[\"timeCost\"].ToNumber(),\n opts[\"memoryCost\"].ToNumber(),\n opts[\"parallelism\"].ToNumber(),\n opts[\"version\"].ToNumber(),\n argon2_type(int(opts[\"type\"].ToNumber())),\n };\n}\n\n#ifndef _MSC_VER\n}\n#endif\n\nValue Hash(const CallbackInfo& info)\n{\n assert(info.Length() == 4 and info[0].IsBuffer() and info[1].IsBuffer() and info[2].IsObject() and info[3].IsFunction());\n\n auto worker = new HashWorker{\n info[3].As<Function>(), from_buffer(info[0]), from_buffer(info[1]), extract_opts(info[2].As<Object>())\n };\n\n worker->Queue();\n return info.Env().Undefined();\n}\n\nconstexpr uint32_t max(uint32_t a, uint32_t b) {\n return a > b ? a : b;\n}\n\nObject init(Env env, Object exports)\n{\n auto limits = Object::New(env);\n\n const auto& setMaxMin = [&](const char* name, uint32_t max, uint32_t min) {\n auto obj = Object::New(env);\n obj[\"max\"] = max;\n obj[\"min\"] = min;\n limits[name] = obj;\n };\n\n setMaxMin(\"hashLength\", ARGON2_MAX_OUTLEN, ARGON2_MIN_OUTLEN);\n setMaxMin(\"memoryCost\", ARGON2_MAX_MEMORY, max(ARGON2_MIN_MEMORY, 2048));\n setMaxMin(\"timeCost\", ARGON2_MAX_TIME, max(ARGON2_MIN_TIME, 2));\n setMaxMin(\"parallelism\", ARGON2_MAX_LANES, ARGON2_MIN_LANES);\n\n auto types = Object::New(env);\n types[type2string(Argon2_d)] = uint32_t(Argon2_d);\n types[type2string(Argon2_i)] = uint32_t(Argon2_i);\n types[type2string(Argon2_id)] = uint32_t(Argon2_id);\n\n auto names = Object::New(env);\n names[uint32_t(Argon2_d)] = type2string(Argon2_d);\n names[uint32_t(Argon2_i)] = type2string(Argon2_i);\n names[uint32_t(Argon2_id)] = type2string(Argon2_id);\n\n exports[\"limits\"] = limits;\n exports[\"types\"] = types;\n exports[\"names\"] = names;\n exports[\"version\"] = int(ARGON2_VERSION_NUMBER);\n exports[\"hash\"] = Function::New(env, Hash);\n return exports;\n}\n\nNODE_API_MODULE(argon2_lib, init);\n<commit_msg>Reduce minimum memory cost to 1024 (#304)<commit_after>#include <cassert>\n#include <cstdint>\n#include <string>\n\n#include <napi.h>\n#include \"..\/argon2\/include\/argon2.h\"\n\n#include <ciso646>\n\nusing namespace Napi;\n\n#ifndef _MSC_VER\nnamespace {\n#endif\n\nusing ustring = std::basic_string<uint8_t>;\nconst char* type2string(argon2_type type) { return argon2_type2string(type, false); };\n\nustring from_buffer(const Value& value)\n{\n const auto& buf = value.As<Buffer<uint8_t>>();\n return {buf.Data(), buf.Length()};\n}\n\nBuffer<uint8_t> to_buffer(const Env& env, const ustring& str)\n{\n return Buffer<uint8_t>::Copy(env, str.data(), str.size());\n}\n\nstruct Options {\n \/\/ TODO: remove ctors and initializers when GCC<5 stops shipping\n Options(Options&&) = default;\n\n ustring secret;\n ustring ad;\n\n uint32_t hash_length;\n uint32_t time_cost;\n uint32_t memory_cost;\n uint32_t parallelism;\n uint32_t version;\n\n argon2_type type;\n};\n\nargon2_context make_context(uint8_t* buf, const ustring& plain, const ustring& salt, const Options& opts)\n{\n argon2_context ctx;\n\n ctx.out = buf;\n ctx.outlen = opts.hash_length;\n ctx.pwd = const_cast<uint8_t*>(plain.data());\n ctx.pwdlen = plain.size();\n ctx.salt = const_cast<uint8_t*>(salt.data());\n ctx.saltlen = salt.length();\n ctx.secret = opts.secret.empty() ? nullptr : const_cast<uint8_t*>(opts.secret.data());\n ctx.secretlen = opts.secret.size();\n ctx.ad = opts.ad.empty() ? nullptr : const_cast<uint8_t*>(opts.ad.data());\n ctx.adlen = opts.ad.size();\n ctx.t_cost = opts.time_cost;\n ctx.m_cost = opts.memory_cost;\n ctx.lanes = opts.parallelism;\n ctx.threads = opts.parallelism;\n ctx.allocate_cbk = nullptr;\n ctx.free_cbk = nullptr;\n ctx.flags = ARGON2_DEFAULT_FLAGS;\n ctx.version = opts.version;\n\n return ctx;\n}\n\nclass HashWorker final: public AsyncWorker {\npublic:\n HashWorker(const Function& callback, ustring&& plain, ustring&& salt, Options&& opts):\n \/\/ TODO: use brackets when GCC <5 stops shipping\n AsyncWorker(callback, \"argon2:HashWorker\"),\n plain(std::move(plain)),\n salt(std::move(salt)),\n opts(std::move(opts))\n {}\n\n void Execute() override\n {\n uint8_t* buf = new uint8_t[opts.hash_length];\n\n auto ctx = make_context(buf, plain, salt, opts);\n int result = argon2_ctx(&ctx, opts.type);\n\n if (result != ARGON2_OK) {\n \/* LCOV_EXCL_START *\/\n SetError(argon2_error_message(result));\n \/* LCOV_EXCL_STOP *\/\n } else {\n hash.assign(buf, opts.hash_length);\n }\n\n std::fill_n(buf, opts.hash_length, 0);\n\n delete[] buf;\n }\n\n void OnOK() override\n {\n const auto& env = Env();\n HandleScope scope{env};\n Callback()({env.Undefined(), to_buffer(env, hash)});\n }\n\nprivate:\n ustring plain;\n ustring salt;\n Options opts;\n\n ustring hash;\n};\n\nOptions extract_opts(const Object& opts)\n{\n return {\n opts.Has(\"secret\") ? from_buffer(opts[\"secret\"]) : ustring{},\n opts.Has(\"associatedData\") ? from_buffer(opts[\"associatedData\"]) : ustring{},\n opts[\"hashLength\"].ToNumber(),\n opts[\"timeCost\"].ToNumber(),\n opts[\"memoryCost\"].ToNumber(),\n opts[\"parallelism\"].ToNumber(),\n opts[\"version\"].ToNumber(),\n argon2_type(int(opts[\"type\"].ToNumber())),\n };\n}\n\n#ifndef _MSC_VER\n}\n#endif\n\nValue Hash(const CallbackInfo& info)\n{\n assert(info.Length() == 4 and info[0].IsBuffer() and info[1].IsBuffer() and info[2].IsObject() and info[3].IsFunction());\n\n auto worker = new HashWorker{\n info[3].As<Function>(), from_buffer(info[0]), from_buffer(info[1]), extract_opts(info[2].As<Object>())\n };\n\n worker->Queue();\n return info.Env().Undefined();\n}\n\nconstexpr uint32_t max(uint32_t a, uint32_t b) {\n return a > b ? a : b;\n}\n\nObject init(Env env, Object exports)\n{\n auto limits = Object::New(env);\n\n const auto& setMaxMin = [&](const char* name, uint32_t max, uint32_t min) {\n auto obj = Object::New(env);\n obj[\"max\"] = max;\n obj[\"min\"] = min;\n limits[name] = obj;\n };\n\n setMaxMin(\"hashLength\", ARGON2_MAX_OUTLEN, ARGON2_MIN_OUTLEN);\n setMaxMin(\"memoryCost\", ARGON2_MAX_MEMORY, max(ARGON2_MIN_MEMORY, 1024));\n setMaxMin(\"timeCost\", ARGON2_MAX_TIME, max(ARGON2_MIN_TIME, 2));\n setMaxMin(\"parallelism\", ARGON2_MAX_LANES, ARGON2_MIN_LANES);\n\n auto types = Object::New(env);\n types[type2string(Argon2_d)] = uint32_t(Argon2_d);\n types[type2string(Argon2_i)] = uint32_t(Argon2_i);\n types[type2string(Argon2_id)] = uint32_t(Argon2_id);\n\n auto names = Object::New(env);\n names[uint32_t(Argon2_d)] = type2string(Argon2_d);\n names[uint32_t(Argon2_i)] = type2string(Argon2_i);\n names[uint32_t(Argon2_id)] = type2string(Argon2_id);\n\n exports[\"limits\"] = limits;\n exports[\"types\"] = types;\n exports[\"names\"] = names;\n exports[\"version\"] = int(ARGON2_VERSION_NUMBER);\n exports[\"hash\"] = Function::New(env, Hash);\n return exports;\n}\n\nNODE_API_MODULE(argon2_lib, init);\n<|endoftext|>"} {"text":"<commit_before>#include \"sendcoinsdialog.h\"\n#include \"ui_sendcoinsdialog.h\"\n#include \"walletmodel.h\"\n#include \"bitcoinunits.h\"\n#include \"addressbookpage.h\"\n#include \"optionsmodel.h\"\n#include \"sendcoinsentry.h\"\n\n\n#include <QMessageBox>\n#include <QLocale>\n#include <QDebug>\n\nSendCoinsDialog::SendCoinsDialog(QWidget *parent) :\n QDialog(parent),\n ui(new Ui::SendCoinsDialog),\n model(0)\n{\n ui->setupUi(this);\n\n addEntry();\n\n connect(ui->addButton, SIGNAL(clicked()), this, SLOT(addEntry()));\n}\n\nvoid SendCoinsDialog::setModel(WalletModel *model)\n{\n this->model = model;\n\n for(int i = 0; i < ui->entries->count(); ++i)\n {\n SendCoinsEntry *entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget());\n if(entry)\n {\n entry->setModel(model);\n }\n }\n}\n\nSendCoinsDialog::~SendCoinsDialog()\n{\n delete ui;\n}\n\nvoid SendCoinsDialog::on_sendButton_clicked()\n{\n QList<SendCoinsRecipient> recipients;\n bool valid = true;\n for(int i = 0; i < ui->entries->count(); ++i)\n {\n SendCoinsEntry *entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget());\n if(entry)\n {\n if(entry->validate())\n {\n recipients.append(entry->getValue());\n }\n else\n {\n valid = false;\n }\n }\n }\n\n if(!valid || recipients.isEmpty())\n {\n return;\n }\n\n \/\/ Format confirmation message\n QStringList formatted;\n foreach(const SendCoinsRecipient &rcp, recipients)\n {\n formatted.append(tr(\"%1 to %2 (%3)\").arg(BitcoinUnits::formatWithUnit(BitcoinUnits::BTC, rcp.amount), rcp.label, rcp.address));\n }\n\n QMessageBox::StandardButton retval = QMessageBox::question(this, tr(\"Confirm send coins\"),\n tr(\"Are you sure you want to send %1?\").arg(formatted.join(tr(\" and \"))),\n QMessageBox::Yes|QMessageBox::Cancel,\n QMessageBox::Cancel);\n\n if(retval != QMessageBox::Yes)\n {\n return;\n }\n\n WalletModel::SendCoinsReturn sendstatus = model->sendCoins(recipients);\n switch(sendstatus.status)\n {\n case WalletModel::InvalidAddress:\n QMessageBox::warning(this, tr(\"Send Coins\"),\n tr(\"The recepient address is not valid, please recheck.\"),\n QMessageBox::Ok, QMessageBox::Ok);\n break;\n case WalletModel::InvalidAmount:\n QMessageBox::warning(this, tr(\"Send Coins\"),\n tr(\"The amount to pay must be larger than 0.\"),\n QMessageBox::Ok, QMessageBox::Ok);\n break;\n case WalletModel::AmountExceedsBalance:\n QMessageBox::warning(this, tr(\"Send Coins\"),\n tr(\"Amount exceeds your balance\"),\n QMessageBox::Ok, QMessageBox::Ok);\n break;\n case WalletModel::AmountWithFeeExceedsBalance:\n QMessageBox::warning(this, tr(\"Send Coins\"),\n tr(\"Total exceeds your balance when the %1 transaction fee is included\").\n arg(BitcoinUnits::formatWithUnit(BitcoinUnits::BTC, sendstatus.fee)),\n QMessageBox::Ok, QMessageBox::Ok);\n break;\n case WalletModel::DuplicateAddress:\n QMessageBox::warning(this, tr(\"Send Coins\"),\n tr(\"Duplicate address found, can only send to each address once in one send operation\"),\n QMessageBox::Ok, QMessageBox::Ok);\n break;\n case WalletModel::TransactionCreationFailed:\n QMessageBox::warning(this, tr(\"Send Coins\"),\n tr(\"Error: Transaction creation failed \"),\n QMessageBox::Ok, QMessageBox::Ok);\n break;\n break;\n case WalletModel::TransactionCommitFailed:\n QMessageBox::warning(this, tr(\"Send Coins\"),\n tr(\"Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.\"),\n QMessageBox::Ok, QMessageBox::Ok);\n break;\n case WalletModel::OK:\n accept();\n break;\n }\n}\n\nvoid SendCoinsDialog::clear()\n{\n \/\/ Remove entries until only one left\n while(ui->entries->count() > 1)\n {\n delete ui->entries->takeAt(0)->widget();\n }\n\n \/\/ Reset the entry that is left to empty\n SendCoinsEntry *entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(0)->widget());\n if(entry)\n {\n entry->clear();\n }\n\n updateRemoveEnabled();\n\n ui->sendButton->setDefault(true);\n}\n\nvoid SendCoinsDialog::reject()\n{\n clear();\n}\n\nvoid SendCoinsDialog::accept()\n{\n clear();\n}\n\nvoid SendCoinsDialog::addEntry()\n{\n SendCoinsEntry *entry = new SendCoinsEntry(this);\n entry->setModel(model);\n ui->entries->addWidget(entry);\n connect(entry, SIGNAL(removeEntry(SendCoinsEntry*)), this, SLOT(removeEntry(SendCoinsEntry*)));\n\n updateRemoveEnabled();\n\n \/\/ Focus the field, so that entry can start immediately\n entry->clear();\n}\n\nvoid SendCoinsDialog::updateRemoveEnabled()\n{\n \/\/ Remove buttons are enabled as soon as there is more than one send-entry\n bool enabled = (ui->entries->count() > 1);\n for(int i = 0; i < ui->entries->count(); ++i)\n {\n SendCoinsEntry *entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget());\n if(entry)\n {\n entry->setRemoveEnabled(enabled);\n }\n }\n setupTabChain(0);\n}\n\nvoid SendCoinsDialog::removeEntry(SendCoinsEntry* entry)\n{\n delete entry;\n updateRemoveEnabled();\n}\n\nQWidget *SendCoinsDialog::setupTabChain(QWidget *prev)\n{\n for(int i = 0; i < ui->entries->count(); ++i)\n {\n SendCoinsEntry *entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget());\n if(entry)\n {\n prev = entry->setupTabChain(prev);\n }\n }\n QWidget::setTabOrder(prev, ui->addButton);\n QWidget::setTabOrder(ui->addButton, ui->sendButton);\n return ui->sendButton;\n}\n<commit_msg>show amounts in <b>bold<\/b> in confirmation dialog<commit_after>#include \"sendcoinsdialog.h\"\n#include \"ui_sendcoinsdialog.h\"\n#include \"walletmodel.h\"\n#include \"bitcoinunits.h\"\n#include \"addressbookpage.h\"\n#include \"optionsmodel.h\"\n#include \"sendcoinsentry.h\"\n\n\n#include <QMessageBox>\n#include <QLocale>\n#include <QDebug>\n\nSendCoinsDialog::SendCoinsDialog(QWidget *parent) :\n QDialog(parent),\n ui(new Ui::SendCoinsDialog),\n model(0)\n{\n ui->setupUi(this);\n\n addEntry();\n\n connect(ui->addButton, SIGNAL(clicked()), this, SLOT(addEntry()));\n}\n\nvoid SendCoinsDialog::setModel(WalletModel *model)\n{\n this->model = model;\n\n for(int i = 0; i < ui->entries->count(); ++i)\n {\n SendCoinsEntry *entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget());\n if(entry)\n {\n entry->setModel(model);\n }\n }\n}\n\nSendCoinsDialog::~SendCoinsDialog()\n{\n delete ui;\n}\n\nvoid SendCoinsDialog::on_sendButton_clicked()\n{\n QList<SendCoinsRecipient> recipients;\n bool valid = true;\n for(int i = 0; i < ui->entries->count(); ++i)\n {\n SendCoinsEntry *entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget());\n if(entry)\n {\n if(entry->validate())\n {\n recipients.append(entry->getValue());\n }\n else\n {\n valid = false;\n }\n }\n }\n\n if(!valid || recipients.isEmpty())\n {\n return;\n }\n\n \/\/ Format confirmation message\n QStringList formatted;\n foreach(const SendCoinsRecipient &rcp, recipients)\n {\n formatted.append(tr(\"<b>%1<\/b> to %2 (%3)\").arg(BitcoinUnits::formatWithUnit(BitcoinUnits::BTC, rcp.amount), rcp.label, rcp.address));\n }\n\n QMessageBox::StandardButton retval = QMessageBox::question(this, tr(\"Confirm send coins\"),\n tr(\"Are you sure you want to send %1?\").arg(formatted.join(tr(\" and \"))),\n QMessageBox::Yes|QMessageBox::Cancel,\n QMessageBox::Cancel);\n\n if(retval != QMessageBox::Yes)\n {\n return;\n }\n\n WalletModel::SendCoinsReturn sendstatus = model->sendCoins(recipients);\n switch(sendstatus.status)\n {\n case WalletModel::InvalidAddress:\n QMessageBox::warning(this, tr(\"Send Coins\"),\n tr(\"The recepient address is not valid, please recheck.\"),\n QMessageBox::Ok, QMessageBox::Ok);\n break;\n case WalletModel::InvalidAmount:\n QMessageBox::warning(this, tr(\"Send Coins\"),\n tr(\"The amount to pay must be larger than 0.\"),\n QMessageBox::Ok, QMessageBox::Ok);\n break;\n case WalletModel::AmountExceedsBalance:\n QMessageBox::warning(this, tr(\"Send Coins\"),\n tr(\"Amount exceeds your balance\"),\n QMessageBox::Ok, QMessageBox::Ok);\n break;\n case WalletModel::AmountWithFeeExceedsBalance:\n QMessageBox::warning(this, tr(\"Send Coins\"),\n tr(\"Total exceeds your balance when the %1 transaction fee is included\").\n arg(BitcoinUnits::formatWithUnit(BitcoinUnits::BTC, sendstatus.fee)),\n QMessageBox::Ok, QMessageBox::Ok);\n break;\n case WalletModel::DuplicateAddress:\n QMessageBox::warning(this, tr(\"Send Coins\"),\n tr(\"Duplicate address found, can only send to each address once in one send operation\"),\n QMessageBox::Ok, QMessageBox::Ok);\n break;\n case WalletModel::TransactionCreationFailed:\n QMessageBox::warning(this, tr(\"Send Coins\"),\n tr(\"Error: Transaction creation failed \"),\n QMessageBox::Ok, QMessageBox::Ok);\n break;\n break;\n case WalletModel::TransactionCommitFailed:\n QMessageBox::warning(this, tr(\"Send Coins\"),\n tr(\"Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.\"),\n QMessageBox::Ok, QMessageBox::Ok);\n break;\n case WalletModel::OK:\n accept();\n break;\n }\n}\n\nvoid SendCoinsDialog::clear()\n{\n \/\/ Remove entries until only one left\n while(ui->entries->count() > 1)\n {\n delete ui->entries->takeAt(0)->widget();\n }\n\n \/\/ Reset the entry that is left to empty\n SendCoinsEntry *entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(0)->widget());\n if(entry)\n {\n entry->clear();\n }\n\n updateRemoveEnabled();\n\n ui->sendButton->setDefault(true);\n}\n\nvoid SendCoinsDialog::reject()\n{\n clear();\n}\n\nvoid SendCoinsDialog::accept()\n{\n clear();\n}\n\nvoid SendCoinsDialog::addEntry()\n{\n SendCoinsEntry *entry = new SendCoinsEntry(this);\n entry->setModel(model);\n ui->entries->addWidget(entry);\n connect(entry, SIGNAL(removeEntry(SendCoinsEntry*)), this, SLOT(removeEntry(SendCoinsEntry*)));\n\n updateRemoveEnabled();\n\n \/\/ Focus the field, so that entry can start immediately\n entry->clear();\n}\n\nvoid SendCoinsDialog::updateRemoveEnabled()\n{\n \/\/ Remove buttons are enabled as soon as there is more than one send-entry\n bool enabled = (ui->entries->count() > 1);\n for(int i = 0; i < ui->entries->count(); ++i)\n {\n SendCoinsEntry *entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget());\n if(entry)\n {\n entry->setRemoveEnabled(enabled);\n }\n }\n setupTabChain(0);\n}\n\nvoid SendCoinsDialog::removeEntry(SendCoinsEntry* entry)\n{\n delete entry;\n updateRemoveEnabled();\n}\n\nQWidget *SendCoinsDialog::setupTabChain(QWidget *prev)\n{\n for(int i = 0; i < ui->entries->count(); ++i)\n {\n SendCoinsEntry *entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget());\n if(entry)\n {\n prev = entry->setupTabChain(prev);\n }\n }\n QWidget::setTabOrder(prev, ui->addButton);\n QWidget::setTabOrder(ui->addButton, ui->sendButton);\n return ui->sendButton;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"transactionview.h\"\n\n\/\/ Temp includes for filtering prototype\n\/\/ Move to TransactionFilterRow class\n#include \"transactionfilterproxy.h\"\n#include \"transactionrecord.h\"\n#include \"transactiontablemodel.h\"\n#include \"guiutil.h\"\n\n#include <QScrollBar>\n#include <QComboBox>\n#include <QDoubleValidator>\n#include <QHBoxLayout>\n#include <QVBoxLayout>\n#include <QLineEdit>\n#include <QTableView>\n#include <QHeaderView>\n\n#include <QDebug>\n\nTransactionView::TransactionView(QWidget *parent) :\n QWidget(parent), model(0), transactionProxyModel(0),\n transactionView(0)\n{\n \/\/ Build filter row\n QHBoxLayout *hlayout = new QHBoxLayout();\n hlayout->setContentsMargins(QMargins(0,0,0,0));\n hlayout->setSpacing(0);\n\n hlayout->addSpacing(23);\n\n dateWidget = new QComboBox(this);\n dateWidget->setMaximumWidth(120);\n dateWidget->setMinimumWidth(120);\n dateWidget->addItem(tr(\"All\"), All);\n dateWidget->addItem(tr(\"Today\"), Today);\n dateWidget->addItem(tr(\"This week\"), ThisWeek);\n dateWidget->addItem(tr(\"This month\"), ThisMonth);\n dateWidget->addItem(tr(\"Last month\"), LastMonth);\n dateWidget->addItem(tr(\"This year\"), ThisYear);\n dateWidget->addItem(tr(\"Range...\"), Range);\n hlayout->addWidget(dateWidget);\n\n typeWidget = new QComboBox(this);\n typeWidget->setMaximumWidth(120);\n typeWidget->setMinimumWidth(120);\n\n typeWidget->addItem(tr(\"All\"), TransactionFilterProxy::ALL_TYPES);\n typeWidget->addItem(tr(\"Received with\"), TransactionFilterProxy::TYPE(TransactionRecord::RecvWithAddress) |\n TransactionFilterProxy::TYPE(TransactionRecord::RecvFromIP));\n typeWidget->addItem(tr(\"Sent to\"), TransactionFilterProxy::TYPE(TransactionRecord::SendToAddress) |\n TransactionFilterProxy::TYPE(TransactionRecord::SendToIP));\n typeWidget->addItem(tr(\"To yourself\"), TransactionFilterProxy::TYPE(TransactionRecord::SendToSelf));\n typeWidget->addItem(tr(\"Generated\"), TransactionFilterProxy::TYPE(TransactionRecord::Generated));\n typeWidget->addItem(tr(\"Other\"), TransactionFilterProxy::TYPE(TransactionRecord::Other));\n\n hlayout->addWidget(typeWidget);\n\n addressWidget = new QLineEdit(this);\n addressWidget->setPlaceholderText(\"Enter address or label to search\");\n hlayout->addWidget(addressWidget);\n\n amountWidget = new QLineEdit(this);\n amountWidget->setPlaceholderText(\"Min amount\");\n amountWidget->setMaximumWidth(100);\n amountWidget->setMinimumWidth(100);\n amountWidget->setValidator(new QDoubleValidator(0, 1e20, 8, this));\n hlayout->addWidget(amountWidget);\n\n QVBoxLayout *vlayout = new QVBoxLayout(this);\n\n QTableView *view = new QTableView(this);\n vlayout->addLayout(hlayout);\n vlayout->addWidget(view);\n vlayout->setSpacing(0);\n int width = view->verticalScrollBar()->sizeHint().width();\n \/\/ Cover scroll bar width with spacing\n hlayout->addSpacing(width);\n \/\/ Always show scroll bar\n view->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);\n\n transactionView = view;\n\n connect(dateWidget, SIGNAL(activated(int)), this, SLOT(chooseDate(int)));\n connect(typeWidget, SIGNAL(activated(int)), this, SLOT(chooseType(int)));\n connect(addressWidget, SIGNAL(textChanged(const QString&)), this, SLOT(changedPrefix(const QString&)));\n connect(amountWidget, SIGNAL(textChanged(const QString&)), this, SLOT(changedAmount(const QString&)));\n\n connect(view, SIGNAL(doubleClicked(const QModelIndex&)), this, SIGNAL(doubleClicked(const QModelIndex&)));\n}\n\nvoid TransactionView::setModel(TransactionTableModel *model)\n{\n this->model = model;\n\n transactionProxyModel = new TransactionFilterProxy(this);\n transactionProxyModel->setSourceModel(model);\n transactionProxyModel->setDynamicSortFilter(true);\n\n transactionProxyModel->setSortRole(Qt::EditRole);\n\n transactionView->setModel(transactionProxyModel);\n transactionView->setAlternatingRowColors(true);\n transactionView->setSelectionBehavior(QAbstractItemView::SelectRows);\n transactionView->setSelectionMode(QAbstractItemView::ExtendedSelection);\n transactionView->setSortingEnabled(true);\n transactionView->sortByColumn(TransactionTableModel::Status, Qt::DescendingOrder);\n transactionView->verticalHeader()->hide();\n\n transactionView->horizontalHeader()->resizeSection(\n TransactionTableModel::Status, 23);\n transactionView->horizontalHeader()->resizeSection(\n TransactionTableModel::Date, 120);\n transactionView->horizontalHeader()->resizeSection(\n TransactionTableModel::Type, 120);\n transactionView->horizontalHeader()->setResizeMode(\n TransactionTableModel::ToAddress, QHeaderView::Stretch);\n transactionView->horizontalHeader()->resizeSection(\n TransactionTableModel::Amount, 100);\n\n}\n\nvoid TransactionView::chooseDate(int idx)\n{\n QDate current = QDate::currentDate();\n switch(dateWidget->itemData(idx).toInt())\n {\n case All:\n transactionProxyModel->setDateRange(\n TransactionFilterProxy::MIN_DATE,\n TransactionFilterProxy::MAX_DATE);\n break;\n case Today:\n transactionProxyModel->setDateRange(\n QDateTime(current),\n TransactionFilterProxy::MAX_DATE);\n break;\n case ThisWeek: {\n \/\/ Find last monday\n QDate startOfWeek = current.addDays(-(current.dayOfWeek()-1));\n transactionProxyModel->setDateRange(\n QDateTime(startOfWeek),\n TransactionFilterProxy::MAX_DATE);\n\n } break;\n case ThisMonth:\n transactionProxyModel->setDateRange(\n QDateTime(QDate(current.year(), current.month(), 1)),\n TransactionFilterProxy::MAX_DATE);\n break;\n case LastMonth:\n transactionProxyModel->setDateRange(\n QDateTime(QDate(current.year(), current.month()-1, 1)),\n QDateTime(QDate(current.year(), current.month(), 1)));\n break;\n case ThisYear:\n transactionProxyModel->setDateRange(\n QDateTime(QDate(current.year(), 1, 1)),\n TransactionFilterProxy::MAX_DATE);\n break;\n case Range:\n \/\/ TODO ask specific range\n break;\n }\n\n}\n\nvoid TransactionView::chooseType(int idx)\n{\n transactionProxyModel->setTypeFilter(\n typeWidget->itemData(idx).toInt());\n}\n\nvoid TransactionView::changedPrefix(const QString &prefix)\n{\n transactionProxyModel->setAddressPrefix(prefix);\n}\n\nvoid TransactionView::changedAmount(const QString &amount)\n{\n qint64 amount_parsed = 0;\n if(GUIUtil::parseMoney(amount, &amount_parsed))\n {\n transactionProxyModel->setMinAmount(amount_parsed);\n }\n else\n {\n transactionProxyModel->setMinAmount(0);\n }\n}\n<commit_msg>Placeholder text can only be used for Qt 4.7+<commit_after>#include \"transactionview.h\"\n\n\/\/ Temp includes for filtering prototype\n\/\/ Move to TransactionFilterRow class\n#include \"transactionfilterproxy.h\"\n#include \"transactionrecord.h\"\n#include \"transactiontablemodel.h\"\n#include \"guiutil.h\"\n\n#include <QScrollBar>\n#include <QComboBox>\n#include <QDoubleValidator>\n#include <QHBoxLayout>\n#include <QVBoxLayout>\n#include <QLineEdit>\n#include <QTableView>\n#include <QHeaderView>\n\n#include <QDebug>\n\nTransactionView::TransactionView(QWidget *parent) :\n QWidget(parent), model(0), transactionProxyModel(0),\n transactionView(0)\n{\n \/\/ Build filter row\n QHBoxLayout *hlayout = new QHBoxLayout();\n hlayout->setContentsMargins(QMargins(0,0,0,0));\n hlayout->setSpacing(0);\n\n hlayout->addSpacing(23);\n\n dateWidget = new QComboBox(this);\n dateWidget->setMaximumWidth(120);\n dateWidget->setMinimumWidth(120);\n dateWidget->addItem(tr(\"All\"), All);\n dateWidget->addItem(tr(\"Today\"), Today);\n dateWidget->addItem(tr(\"This week\"), ThisWeek);\n dateWidget->addItem(tr(\"This month\"), ThisMonth);\n dateWidget->addItem(tr(\"Last month\"), LastMonth);\n dateWidget->addItem(tr(\"This year\"), ThisYear);\n dateWidget->addItem(tr(\"Range...\"), Range);\n hlayout->addWidget(dateWidget);\n\n typeWidget = new QComboBox(this);\n typeWidget->setMaximumWidth(120);\n typeWidget->setMinimumWidth(120);\n\n typeWidget->addItem(tr(\"All\"), TransactionFilterProxy::ALL_TYPES);\n typeWidget->addItem(tr(\"Received with\"), TransactionFilterProxy::TYPE(TransactionRecord::RecvWithAddress) |\n TransactionFilterProxy::TYPE(TransactionRecord::RecvFromIP));\n typeWidget->addItem(tr(\"Sent to\"), TransactionFilterProxy::TYPE(TransactionRecord::SendToAddress) |\n TransactionFilterProxy::TYPE(TransactionRecord::SendToIP));\n typeWidget->addItem(tr(\"To yourself\"), TransactionFilterProxy::TYPE(TransactionRecord::SendToSelf));\n typeWidget->addItem(tr(\"Generated\"), TransactionFilterProxy::TYPE(TransactionRecord::Generated));\n typeWidget->addItem(tr(\"Other\"), TransactionFilterProxy::TYPE(TransactionRecord::Other));\n\n hlayout->addWidget(typeWidget);\n\n addressWidget = new QLineEdit(this);\n#if QT_VERSION >= 0x040700\n addressWidget->setPlaceholderText(\"Enter address or label to search\");\n#endif\n hlayout->addWidget(addressWidget);\n\n amountWidget = new QLineEdit(this);\n#if QT_VERSION >= 0x040700\n amountWidget->setPlaceholderText(\"Min amount\");\n#endif\n amountWidget->setMaximumWidth(100);\n amountWidget->setMinimumWidth(100);\n amountWidget->setValidator(new QDoubleValidator(0, 1e20, 8, this));\n hlayout->addWidget(amountWidget);\n\n QVBoxLayout *vlayout = new QVBoxLayout(this);\n\n QTableView *view = new QTableView(this);\n vlayout->addLayout(hlayout);\n vlayout->addWidget(view);\n vlayout->setSpacing(0);\n int width = view->verticalScrollBar()->sizeHint().width();\n \/\/ Cover scroll bar width with spacing\n hlayout->addSpacing(width);\n \/\/ Always show scroll bar\n view->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);\n\n transactionView = view;\n\n connect(dateWidget, SIGNAL(activated(int)), this, SLOT(chooseDate(int)));\n connect(typeWidget, SIGNAL(activated(int)), this, SLOT(chooseType(int)));\n connect(addressWidget, SIGNAL(textChanged(const QString&)), this, SLOT(changedPrefix(const QString&)));\n connect(amountWidget, SIGNAL(textChanged(const QString&)), this, SLOT(changedAmount(const QString&)));\n\n connect(view, SIGNAL(doubleClicked(const QModelIndex&)), this, SIGNAL(doubleClicked(const QModelIndex&)));\n}\n\nvoid TransactionView::setModel(TransactionTableModel *model)\n{\n this->model = model;\n\n transactionProxyModel = new TransactionFilterProxy(this);\n transactionProxyModel->setSourceModel(model);\n transactionProxyModel->setDynamicSortFilter(true);\n\n transactionProxyModel->setSortRole(Qt::EditRole);\n\n transactionView->setModel(transactionProxyModel);\n transactionView->setAlternatingRowColors(true);\n transactionView->setSelectionBehavior(QAbstractItemView::SelectRows);\n transactionView->setSelectionMode(QAbstractItemView::ExtendedSelection);\n transactionView->setSortingEnabled(true);\n transactionView->sortByColumn(TransactionTableModel::Status, Qt::DescendingOrder);\n transactionView->verticalHeader()->hide();\n\n transactionView->horizontalHeader()->resizeSection(\n TransactionTableModel::Status, 23);\n transactionView->horizontalHeader()->resizeSection(\n TransactionTableModel::Date, 120);\n transactionView->horizontalHeader()->resizeSection(\n TransactionTableModel::Type, 120);\n transactionView->horizontalHeader()->setResizeMode(\n TransactionTableModel::ToAddress, QHeaderView::Stretch);\n transactionView->horizontalHeader()->resizeSection(\n TransactionTableModel::Amount, 100);\n\n}\n\nvoid TransactionView::chooseDate(int idx)\n{\n QDate current = QDate::currentDate();\n switch(dateWidget->itemData(idx).toInt())\n {\n case All:\n transactionProxyModel->setDateRange(\n TransactionFilterProxy::MIN_DATE,\n TransactionFilterProxy::MAX_DATE);\n break;\n case Today:\n transactionProxyModel->setDateRange(\n QDateTime(current),\n TransactionFilterProxy::MAX_DATE);\n break;\n case ThisWeek: {\n \/\/ Find last monday\n QDate startOfWeek = current.addDays(-(current.dayOfWeek()-1));\n transactionProxyModel->setDateRange(\n QDateTime(startOfWeek),\n TransactionFilterProxy::MAX_DATE);\n\n } break;\n case ThisMonth:\n transactionProxyModel->setDateRange(\n QDateTime(QDate(current.year(), current.month(), 1)),\n TransactionFilterProxy::MAX_DATE);\n break;\n case LastMonth:\n transactionProxyModel->setDateRange(\n QDateTime(QDate(current.year(), current.month()-1, 1)),\n QDateTime(QDate(current.year(), current.month(), 1)));\n break;\n case ThisYear:\n transactionProxyModel->setDateRange(\n QDateTime(QDate(current.year(), 1, 1)),\n TransactionFilterProxy::MAX_DATE);\n break;\n case Range:\n \/\/ TODO ask specific range\n break;\n }\n\n}\n\nvoid TransactionView::chooseType(int idx)\n{\n transactionProxyModel->setTypeFilter(\n typeWidget->itemData(idx).toInt());\n}\n\nvoid TransactionView::changedPrefix(const QString &prefix)\n{\n transactionProxyModel->setAddressPrefix(prefix);\n}\n\nvoid TransactionView::changedAmount(const QString &amount)\n{\n qint64 amount_parsed = 0;\n if(GUIUtil::parseMoney(amount, &amount_parsed))\n {\n transactionProxyModel->setMinAmount(amount_parsed);\n }\n else\n {\n transactionProxyModel->setMinAmount(0);\n }\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"rosplan_planning_system\/PlannerInterface\/FFPlannerInterface.h\"\n\nnamespace KCL_rosplan {\n\n\t\/*-------------*\/\n\t\/* constructor *\/\n\t\/*-------------*\/\n\n\tFFPlannerInterface::FFPlannerInterface(ros::NodeHandle& nh)\n\t{\n\t\tnode_handle = &nh;\n\n\t\tplan_server = new actionlib::SimpleActionServer<rosplan_dispatch_msgs::PlanAction>((*node_handle), \"start_planning\", boost::bind(&PlannerInterface::runPlanningServerAction, this, _1), false);\n\n\t\t\/\/ publishing raw planner output\n\t\tstd::string plannerTopic = \"planner_output\";\n\t\tnode_handle->getParam(\"planner_topic\", plannerTopic);\n\t\tplan_publisher = node_handle->advertise<std_msgs::String>(plannerTopic, 1, true);\n\n\t\tnode_handle->param<bool>(\"use_ffha\", this->use_ffha, false);\n\n\t\t\/\/ start planning action server\n\t\tplan_server->start();\n\t}\n\n\tFFPlannerInterface::~FFPlannerInterface()\n\t{\n\t\tdelete plan_server;\n\t}\n\n\t\/**\n\t * Runs external commands\n\t *\/\n\tstd::string FFPlannerInterface::runCommand(std::string cmd) {\n\t\tstd::string data;\n\t\tFILE *stream;\n\t\tchar buffer[1000];\n\t\tstream = popen(cmd.c_str(), \"r\");\n\t\twhile ( fgets(buffer, 1000, stream) != NULL )\n\t\t\tdata.append(buffer);\n\t\tpclose(stream);\n\t\treturn data;\n\t}\n\n\t\/*------------------*\/\n\t\/* Plan and process *\/\n\t\/*------------------*\/\n\n\t\/**\n\t * passes the problem to the Planner; the plan to post-processing.\n\t *\/\n\tbool FFPlannerInterface::runPlanner() {\n\t\tplanner_output.clear(); \/\/ Clear previous plan\n\t\t\/\/ save problem to file for planner\n\t\tif(use_problem_topic && problem_instance_received) {\n\t\t\tROS_INFO(\"KCL: (%s) (%s) Writing problem to file.\", ros::this_node::getName().c_str(), problem_name.c_str());\n\t\t\tstd::ofstream dest;\n\t\t\tdest.open((problem_path).c_str());\n\t\t\tdest << problem_instance;\n\t\t\tdest.close();\n\t\t}\n\n\t\t\/\/ prepare the planner command line\n\t\tstd::string str = planner_command;\n\t\tstd::size_t dit = str.find(\"DOMAIN\");\n\t\tif(dit!=std::string::npos) str.replace(dit,6,domain_path);\n\t\tstd::size_t pit = str.find(\"PROBLEM\");\n\t\tif(pit!=std::string::npos) str.replace(pit,7,problem_path);\n\t\tstd::string commandString = str + \" > \" + data_path + \"plan.pddl\";\n\n\t\t\/\/ call the planer\n\t\tROS_INFO(\"KCL: (%s) (%s) Running: %s\", ros::this_node::getName().c_str(), problem_name.c_str(), commandString.c_str());\n\t\tstd::string plan = runCommand(commandString.c_str());\n\t\tROS_INFO(\"KCL: (%s) (%s) Planning complete\", ros::this_node::getName().c_str(), problem_name.c_str());\n\n\t\t\/\/ check the planner solved the problem\n\t\tstd::ifstream planfile;\n\t\tplanfile.open((data_path + \"plan.pddl\").c_str());\n\t\tstd::string line;\n\n\t\tbool solved = false;\n\t\twhile (not solved and std::getline(planfile, line)) {\n\t\t\t\/\/ skip lines until there is a plan\n\t\t\tif (line.find(\"ff: found legal plan\") != line.npos) {\n\t\t\t\tsolved = true;\n\t\t\t}\n\t\t}\n\n\t\t\/\/ Parse the solved plan\n\t\tif (solved) {\n\t\t\tif (this->use_ffha)\n\t\t\t{\n\t\t\t\tstd::getline(planfile, line); \/\/go to first action line\n\t\t\t} else {\n\t\t\t\/\/ actions look like this:\n\t\t\t\/\/ step 0: got_place C1\n\t\t\t\/\/ 1: find_object V1 C1\n\t\t\t\/\/ plan cost: XX\n\t\t\t\twhile (std::getline(planfile, line)) { \/\/ Move to the beginning of the plan\n\t\t\t\t\tif (line.substr(0, 4) == \"step\") {\n\t\t\t\t\t\tline = line.substr(4); \/\/ Remove the step\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t\/\/ First iteration line will be like 0: got_place C1\n\t\t\twhile (line.find(\"Total cost\") == line.npos and line.find(\"time spend\") == line.npos and line.size() > 0) {\n\t\t\t\tstd::stringstream ss(line); \/\/ To trim whitespaces\n\t\t\t\tstd::string aux;\n\t\t\t\t\/\/ Read the action number X:\n\t\t\t\tss >> aux;\n\t\t\t\tstd::string add = (use_ffha) ? \" \" : \" (\";\n\t\t\t\tplanner_output += aux + add; \/\/ Add parenthesis before the action\n\t\t\t\twhile (ss >> aux) { \/\/ Read the rest\n\t\t\t\t\tplanner_output += aux;\n\t\t\t\t\tif (ss.good()) planner_output += \" \"; \/\/ Add a whitespace unless we have processed all the line\n\t\t\t\t}\n\t\t\t\tadd = (use_ffha) ? \" [0.001]\\n\" : \") [0.001]\\n\";\n\t\t\t\tplanner_output += add; \/\/ Close parenthesis and add duration\n\t\t\t\tstd::getline(planfile, line);\n\t\t\t}\n\t\t\t\/\/ Convert to lowercase as FF prints all the actions and parameters in uppercase\n\t\t\tstd::transform(planner_output.begin(), planner_output.end(), planner_output.begin(), ::tolower);\n\t\t}\n\t\tplanfile.close();\n\n\t\tif(!solved) ROS_INFO(\"KCL: (%s) (%s) Plan was unsolvable.\", ros::this_node::getName().c_str(), problem_name.c_str());\n\t\telse ROS_INFO(\"KCL: (%s) (%s) Plan was solved.\", ros::this_node::getName().c_str(), problem_name.c_str());\n\n\t\treturn solved;\n\t}\n\n} \/\/ close namespace\n\n\t\/*-------------*\/\n\t\/* Main method *\/\n\t\/*-------------*\/\n\n\tint main(int argc, char **argv) {\n\n\t\tsrand (static_cast <unsigned> (time(0)));\n\n\t\tros::init(argc,argv,\"rosplan_planner_interface\");\n\t\tros::NodeHandle nh(\"~\");\n\n\t\tKCL_rosplan::FFPlannerInterface pi(nh);\n\n\t\t\/\/ subscribe to problem instance\n\t\tstd::string problemTopic = \"problem_instance\";\n\t\tnh.getParam(\"problem_topic\", problemTopic);\n\t\tros::Subscriber problem_sub = nh.subscribe(problemTopic, 1, &KCL_rosplan::PlannerInterface::problemCallback, dynamic_cast<KCL_rosplan::PlannerInterface*>(&pi));\n\n\t\t\/\/ start the planning services\n\t\tros::ServiceServer service1 = nh.advertiseService(\"planning_server\", &KCL_rosplan::PlannerInterface::runPlanningServerDefault, dynamic_cast<KCL_rosplan::PlannerInterface*>(&pi));\n\t\tros::ServiceServer service2 = nh.advertiseService(\"planning_server_params\", &KCL_rosplan::PlannerInterface::runPlanningServerParams, dynamic_cast<KCL_rosplan::PlannerInterface*>(&pi));\n\n\t\tROS_INFO(\"KCL: (%s) Ready to receive\", ros::this_node::getName().c_str());\n\t\tros::spin();\n\n\t\treturn 0;\n\t}\n<commit_msg>Update FFPlannerInterface.cpp<commit_after>#include \"rosplan_planning_system\/PlannerInterface\/FFPlannerInterface.h\"\n\nnamespace KCL_rosplan {\n\n\t\/*-------------*\/\n\t\/* constructor *\/\n\t\/*-------------*\/\n\n\tFFPlannerInterface::FFPlannerInterface(ros::NodeHandle& nh)\n\t{\n\t\tnode_handle = &nh;\n\n\t\tplan_server = new actionlib::SimpleActionServer<rosplan_dispatch_msgs::PlanAction>((*node_handle), \"start_planning\", boost::bind(&PlannerInterface::runPlanningServerAction, this, _1), false);\n\n\t\t\/\/ publishing raw planner output\n\t\tstd::string plannerTopic = \"planner_output\";\n\t\tnode_handle->getParam(\"planner_topic\", plannerTopic);\n\t\tplan_publisher = node_handle->advertise<std_msgs::String>(plannerTopic, 1, true);\n\n\t\tnode_handle->param<bool>(\"use_ffha\", this->use_ffha, false);\n\n\t\t\/\/ start planning action server\n\t\tplan_server->start();\n\t}\n\n\tFFPlannerInterface::~FFPlannerInterface()\n\t{\n\t\tdelete plan_server;\n\t}\n\n\t\/**\n\t * Runs external commands\n\t *\/\n\tstd::string FFPlannerInterface::runCommand(std::string cmd) {\n\t\tstd::string data;\n\t\tFILE *stream;\n\t\tchar buffer[1000];\n\t\tstream = popen(cmd.c_str(), \"r\");\n\t\twhile ( fgets(buffer, 1000, stream) != NULL )\n\t\t\tdata.append(buffer);\n\t\tpclose(stream);\n\t\treturn data;\n\t}\n\n\t\/*------------------*\/\n\t\/* Plan and process *\/\n\t\/*------------------*\/\n\n\t\/**\n\t * passes the problem to the Planner; the plan to post-processing.\n\t *\/\n\tbool FFPlannerInterface::runPlanner() {\n\t\tplanner_output.clear(); \/\/ Clear previous plan\n\t\t\/\/ save problem to file for planner\n\t\tif(use_problem_topic && problem_instance_received) {\n\t\t\tROS_INFO(\"KCL: (%s) (%s) Writing problem to file.\", ros::this_node::getName().c_str(), problem_name.c_str());\n\t\t\tstd::ofstream dest;\n\t\t\tdest.open((problem_path).c_str());\n\t\t\tdest << problem_instance;\n\t\t\tdest.close();\n\t\t}\n\n\t\t\/\/ prepare the planner command line\n\t\tstd::string str = planner_command;\n\t\tstd::size_t dit = str.find(\"DOMAIN\");\n\t\tif(dit!=std::string::npos) str.replace(dit,6,domain_path);\n\t\tstd::size_t pit = str.find(\"PROBLEM\");\n\t\tif(pit!=std::string::npos) str.replace(pit,7,problem_path);\n\t\tstd::string commandString = str + \" > \" + data_path + \"plan.pddl\";\n\n\t\t\/\/ call the planer\n\t\tROS_INFO(\"KCL: (%s) (%s) Running: %s\", ros::this_node::getName().c_str(), problem_name.c_str(), commandString.c_str());\n\t\tstd::string plan = runCommand(commandString.c_str());\n\t\tROS_INFO(\"KCL: (%s) (%s) Planning complete\", ros::this_node::getName().c_str(), problem_name.c_str());\n\n\t\t\/\/ check the planner solved the problem\n\t\tstd::ifstream planfile;\n\t\tplanfile.open((data_path + \"plan.pddl\").c_str());\n\t\tstd::string line;\n\n\t\tbool solved = false;\n\t\twhile (not solved and std::getline(planfile, line)) {\n\t\t\t\/\/ skip lines until there is a plan\n\t\t\tif (line.find(\"ff: found legal plan\") != line.npos) {\n\t\t\t\tsolved = true;\n\t\t\t}\n\t\t}\n\n\t\t\/\/ Parse the solved plan\n\t\tif (solved) {\n\t\t\tif (this->use_ffha)\n\t\t\t{\n\t\t\t\tstd::getline(planfile, line); \/\/go to first action line\n\t\t\t} else {\n\t\t\t\/\/ actions look like this:\n\t\t\t\/\/ step 0: got_place C1\n\t\t\t\/\/ 1: find_object V1 C1\n\t\t\t\/\/ plan cost: XX\n\t\t\t\twhile (std::getline(planfile, line)) { \/\/ Move to the beginning of the plan\n\t\t\t\t\tif (line.substr(0, 4) == \"step\") {\n\t\t\t\t\t\tline = line.substr(4); \/\/ Remove the step\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t\/\/ First iteration line will be like 0: got_place C1\n\t\t\twhile (line.find(\"plan cost\") == line.npos and line.find(\"Total cost\") == line.npos and line.find(\"time spend\") == line.npos and line.size() > 0) {\n\t\t\t\tstd::stringstream ss(line); \/\/ To trim whitespaces\n\t\t\t\tstd::string aux;\n\t\t\t\t\/\/ Read the action number X:\n\t\t\t\tss >> aux;\n\t\t\t\tstd::string add = (use_ffha) ? \" \" : \" (\";\n\t\t\t\tplanner_output += aux + add; \/\/ Add parenthesis before the action\n\t\t\t\twhile (ss >> aux) { \/\/ Read the rest\n\t\t\t\t\tplanner_output += aux;\n\t\t\t\t\tif (ss.good()) planner_output += \" \"; \/\/ Add a whitespace unless we have processed all the line\n\t\t\t\t}\n\t\t\t\tadd = (use_ffha) ? \" [0.001]\\n\" : \") [0.001]\\n\";\n\t\t\t\tplanner_output += add; \/\/ Close parenthesis and add duration\n\t\t\t\tstd::getline(planfile, line);\n\t\t\t}\n\t\t\t\/\/ Convert to lowercase as FF prints all the actions and parameters in uppercase\n\t\t\tstd::transform(planner_output.begin(), planner_output.end(), planner_output.begin(), ::tolower);\n\t\t}\n\t\tplanfile.close();\n\n\t\tif(!solved) ROS_INFO(\"KCL: (%s) (%s) Plan was unsolvable.\", ros::this_node::getName().c_str(), problem_name.c_str());\n\t\telse ROS_INFO(\"KCL: (%s) (%s) Plan was solved.\", ros::this_node::getName().c_str(), problem_name.c_str());\n\n\t\treturn solved;\n\t}\n\n} \/\/ close namespace\n\n\t\/*-------------*\/\n\t\/* Main method *\/\n\t\/*-------------*\/\n\n\tint main(int argc, char **argv) {\n\n\t\tsrand (static_cast <unsigned> (time(0)));\n\n\t\tros::init(argc,argv,\"rosplan_planner_interface\");\n\t\tros::NodeHandle nh(\"~\");\n\n\t\tKCL_rosplan::FFPlannerInterface pi(nh);\n\n\t\t\/\/ subscribe to problem instance\n\t\tstd::string problemTopic = \"problem_instance\";\n\t\tnh.getParam(\"problem_topic\", problemTopic);\n\t\tros::Subscriber problem_sub = nh.subscribe(problemTopic, 1, &KCL_rosplan::PlannerInterface::problemCallback, dynamic_cast<KCL_rosplan::PlannerInterface*>(&pi));\n\n\t\t\/\/ start the planning services\n\t\tros::ServiceServer service1 = nh.advertiseService(\"planning_server\", &KCL_rosplan::PlannerInterface::runPlanningServerDefault, dynamic_cast<KCL_rosplan::PlannerInterface*>(&pi));\n\t\tros::ServiceServer service2 = nh.advertiseService(\"planning_server_params\", &KCL_rosplan::PlannerInterface::runPlanningServerParams, dynamic_cast<KCL_rosplan::PlannerInterface*>(&pi));\n\n\t\tROS_INFO(\"KCL: (%s) Ready to receive\", ros::this_node::getName().c_str());\n\t\tros::spin();\n\n\t\treturn 0;\n\t}\n<|endoftext|>"} {"text":"<commit_before>#include \"static.h\"\n#include \"page.h\"\n#include \"..\/render.h\"\n\nusing namespace Render;\n\nvoid Html::quickStart(){\n header(\"Thanks\");\n o << \"<div class=\\\"message\\\">Now that you've registered you can upload your tracks and follow artists: just click your name at the top right corner of the page.<\/div>\"\n \"<div class=\\\"message\\\">Don't submit any tracks but your own, though.<\/div>\";\n footer();\n}\n\nvoid Html::faq(){\n header(\"FAQ\");\n o << \"<h2>Frequently Asked Questions<\/h2><div class=\\\"faq\\\">\"\n\n \"<h3>General<\/h3>\"\n\n \"<div><h4>What is this?<\/h4>\"\n \"<p>A place for artists to publish their MLP-related music, and get in touch with their audience.<\/p><\/div>\"\n\n \"<div><h4>Why?<\/h4>\"\n \"<p>Because there is no other central repository for MLP music.<\/p><\/div>\"\n\n \"<div><h4>Why not [INSERT SITE HERE]?<\/h4>\"\n \"<p>Because we try to make the publishing and listening process as smooth as can be. No ads, no limits, no downsides.<\/p><\/div>\"\n\n \"<div><h4>So how do I get on the list of artists? I wanna be one of the cool kids!<\/h4>\"\n \"<p><a href=\\\"\/register\\\">Sign up<\/a> for an account. Log in, get to your user page, and upload a track, then publish it. <i>Voilà<\/i>, you're on the list.<\/p><\/div>\"\n\n \"<h3 id=\\\"youtube\\\">YouTube<\/h3>\"\n\n \"<h4>Why would I want to link my YouTube account to my EqBeats account?<\/h4>\"\n \"<p>When your YouTube account is linked, by the click of a button, we'll create a video out of your track and its cover art, upload it to your YouTube channel, and stick a direct download link in the description. \"\n \"Basically it allows you to reach both your YouTube audience and your audience here in a single upload.<\/p>\"\n\n \"<h4>How do I link my YouTube account?<\/h4>\"\n \"<p>Look for a button on your <a href=\\\"\/account\\\">account edition<\/a> page, as well as any of your tracks. Google will ask you to verify that you trust us. Then, you're done!<\/p>\"\n\n \"<h4>How do I unlink my YouTube account?<\/h4>\"\n \"<p>There is a button on your <a href=\\\"\/account\\\">account edition<\/a> page.<\/p>\"\n\n \"<h3>Technical stuff<\/h3>\"\n\n \"<h4>What quality or bitrate are the audio files on EqBeats?<\/h4>\"\n \"<p>OGG Vorbis files are ~128kbps.<\/p>\"\n \"<p>We do not re-encode MP3 files, we only update the title and artist tags. This means they are exactly the same quality as the artist's original MP3 file.<\/p>\"\n \"<p>Your browser will stream either depending on its capabilities. \"\n \"As of today (April 19 2012), Firefox will only play OGG, Chrome can play either and will prefer OGG, and Safari and IE will only play MP3.<\/p>\"\n \"<p>And before you ask, the cover art files are left untouched as well. We just make a few thumbnails.<\/p>\"\n\n \"<h4>Do you have an API?<\/h4>\"\n \"<p><a href=\\\"\/api\\\">We do.<\/a><\/p>\"\n\n \"<h3>Contact<\/h3>\"\n\n \"<div><h4>Who are you anyway?<\/h4>\"\n \"<p>We're two developers: <a href=\\\"\/user\/1\\\">codl<\/a> and <a href=\\\"\/user\/2\\\">fmang<\/a>. For more information check the <a href=\\\"\/credits\\\">credits<\/a>.<\/p><\/div>\"\n\n \"<div><h4>I've got a question\/problem\/idea!<\/h4>\"\n \"<p>What are you waiting for? Drop us a line at contact@eqbeats.org.<\/p>\"\n \"<p>Or <a href=\\\"http:\/\/iris.ponychat.net\/?nick=pony_......&channels=eqbeats&prompt=1\\\">come chat with us<\/a> in <tt>#eqbeats<\/tt> on <tt>irc.ponychat.net<\/tt>. Don't be shy, we're friendly!<\/p><\/div>\"\n\n \"<\/div>\";\n footer();\n}\n\nvoid Html::credits(){\n header(\"Credits\");\n o << \"<h2>Credits<\/h2><div class=\\\"credits\\\">\"\n \"<h4>Staff<\/h4>\"\n \"<ul>\"\n \"<li><a href=\\\"\/user\/1\\\">codl<\/a><\/li>\"\n \"<li><a href=\\\"\/user\/2\\\">fmang<\/a><\/li>\"\n \"<\/ul>\"\n \"<h4>Support<\/h4>\"\n \"<ul>\"\n \"<li><a href=\\\"\/user\/3\\\">AspectOfTheStorm<\/a><\/li>\"\n \"<li><a href=\\\"\/user\/6\\\">Makkon<\/a><\/li>\"\n \"<li><a href=\\\"\/user\/68\\\">Karai<\/a><\/li>\"\n \"<\/ul>\"\n \"<h4>Design<\/h4>\"\n \"<ul>\"\n \"<li><a href=\\\"http:\/\/www.slt.fr\\\">SLT<\/a> - Logo<\/li>\"\n \"<li><a href=\\\"http:\/\/blackm3sh.deviantart.com\/art\/Rarity-Filly-203377463\\\">BlackM3sh<\/a> - Filly Rarity<\/li>\"\n \"<li><a href=\\\"http:\/\/p.yusukekamiyamane.com\/\\\">Yusuke Kamiyamane<\/a> - Fugue icon set<\/li>\"\n \"<\/ul><\/div>\";\n footer();\n}\n\nvoid Html::apiDoc(){\n header(\"API\");\n o << \"<div id=\\\"api\\\">\"\n \"<h2>API<\/h2>\"\n \"<h3>Quickstart<\/h3>\"\n \"<p>We have a read-only JSON\/JSONP api to access user and track data.<br\/>\"\n \"Just add <tt>\/json<\/tt> to most urls to get a JSON representation of that page.<br\/>\"\n \"Adding a <tt>jsonp<\/tt> parameter will insert the JSON data as an argument to a function named by the <tt>jsonp<\/tt> parameter. It can then be run by loading it in a <script> tag. <small><a href=\\\"https:\/\/en.wikipedia.org\/wiki\/JSONP\\\">More info on JSONP.<\/a><\/small><br\/>\"\n \"Compare <a href=\\\"http:\/\/eqbeats.org\/tracks\/latest\/json\\\">\/tracks\/latest\/json<\/a> and <a href=\\\"http:\/\/eqbeats.org\/tracks\/latest\/json?jsonp=myCallback\\\">\/tracks\/latest\/json?jsonp=myCallback<\/a>.<\/p>\"\n \"<h3 id=\\\"user\\\">User object<\/h3>\"\n \"<table>\"\n \"<tr><td><tt>id<\/tt><\/td><td>Unique numerical id for this user.<\/td><\/tr>\"\n \"<tr><td><tt>name<\/tt><\/td><td>User name.<\/td><\/tr>\"\n \"<tr><td><tt>description<\/tt><\/td><td>User's description of themselves, raw. This member will not exist if there is no description.<\/td><\/tr>\"\n \"<tr><td><tt>html_description<\/tt><\/td><td>Same as above, formatted to HTML.<\/td><\/tr>\"\n \"<tr><td><tt>tracks<\/tt><\/td><td>An array of <a href=\\\"#track\\\">Track objects<\/a> for all tracks published by the user.<\/td><\/tr>\"\n \"<tr><td><tt>playlists<\/tt><\/td><td>Array of <a href=\\\"#playlist\\\">Playlist objects<\/a> (id, name, author and link only).<\/td><\/tr>\"\n \"<tr><td><tt>link<\/tt><\/td><td>Permalink to the user's page.<\/td><\/tr>\"\n \"<\/table>\"\n \"<pre>{<br\/>\"\n \" \\\"id\\\": 123,<br\/>\"\n \" \\\"name\\\": \\\"Foo Bar\\\",<br\/>\"\n \" \\\"description\\\": \\\"Just some dude making [b]music[\/b].\\\",<br\/>\"\n \" \\\"html_description\\\": \\\"Just some dude making <b>music<\/b>.\\\",<br\/>\"\n \" \\\"tracks\\\": [{\\\"id\\\": 456, ...}, ...],<br\/>\"\n \" \\\"playlists\\\": [{\\\"id\\\": 789, ...}, ...],<br\/>\"\n \" \\\"link\\\": \\\"http:\/\/eqbeats.org\/user\/123\\\"<br\/>\"\n \"}<\/pre>\"\n \"<h3 id=\\\"track\\\">Track object<\/h3>\"\n \"<table>\"\n \"<tr><td><tt>id<\/tt><\/td><td>Unique numerical id for the track.<\/td><\/tr>\"\n \"<tr><td><tt>title<\/tt><\/td><td>Track title.<\/td><\/tr>\"\n \"<tr><td><tt>description<\/tt><\/td><td>Track notes, raw. This member will not exist if there are no notes.<\/td><\/tr>\"\n \"<tr><td><tt>html_description<\/tt><\/td><td>Same as above, formatted to HTML.<\/td><\/tr>\"\n \"<tr><td><tt>artist<\/tt><\/td><td>A <a href=\\\"#user\\\">user object<\/a> for the artist (excluding the track array).<\/td><\/tr>\"\n \"<tr><td><tt>link<\/tt><\/td><td>Permalink to the track's page.<\/td><\/tr>\"\n \"<tr><td><tt>download<\/tt><\/td><td>Permalinks to the downloadable \/ streamable audio files.<\/td><\/tr>\"\n \"<\/table>\"\n \"<pre>{<br\/>\"\n \" \\\"id\\\": 456,<br\/>\"\n \" \\\"title\\\": \\\"Baz Quux\\\",<br\/>\"\n \" \\\"description\\\": \\\"A track about bazing while you quux.\\\",<br\/>\"\n \" \\\"html_description\\\": \\\"A track about bazing while you quux.\\\",<br\/>\"\n \" \\\"artist\\\": {\\\"id\\\": 123, \\\"name\\\": \\\"Foo Bar\\\",...}<br\/>\"\n \" \\\"link\\\": \\\"http:\/\/eqbeats.org\/track\/456\\\",<br\/>\"\n \" \\\"download\\\": {\\\"mp3\\\":\\\"http:\/\/eqbeats.org\/track\/456\/mp3\\\",<br\/>\"\n \" \\\"vorbis\\\":\\\"http:\/\/eqbeats.org\/track\/456\/vorbis\\\"}<br\/>\"\n \"}<\/pre>\"\n \"<h3 id=\\\"playlist\\\">Playlist object<\/h3>\"\n \"<table>\"\n \"<tr><td><tt>id<\/tt><\/td><td>Unique numerical id for the playlist.<\/td><\/tr>\"\n \"<tr><td><tt>name<\/tt><\/td><td>Playlist name.<\/td><\/tr>\"\n \"<tr><td><tt>description<\/tt><\/td><td>Description, raw. This member will not exist if there is no description.<\/td><\/tr>\"\n \"<tr><td><tt>html_description<\/tt><\/td><td>Same as above, formatted to HTML.<\/td><\/tr>\"\n \"<tr><td><tt>author<\/tt><\/td><td>A <a href=\\\"#user\\\">user object<\/a> for the author.<\/td><\/tr>\"\n \"<tr><td><tt>tracks<\/tt><\/td><td>An array of <a href=\\\"#track\\\">Track objects<\/a>.<\/td><\/tr>\"\n \"<tr><td><tt>link<\/tt><\/td><td>Permalink to the playlist's page.<\/td><\/tr>\"\n \"<\/table>\"\n \"<h3>Resources<\/h3>\"\n \"<table>\"\n \"<tr><td><tt>\/user\/<var>{id}<\/var>\/json<\/tt><\/td><td>One <a href=\\\"#user\\\">user object<\/a>.<\/td><\/tr>\"\n \"<tr><td><tt>\/users\/search\/json?q=<var>{query}<\/var><\/tt><\/td><td>[Array] <a href=\\\"#user\\\">User objects<\/a> matching the query.<\/td><\/tr>\"\n \"<tr><td><tt>\/user\/<var>{id}<\/var>\/favorites\/json<\/tt><\/td><td>[Array] Favorite tracks.<\/td><\/tr>\"\n \"<tr><td><tt>\/artists\/json<\/tt><\/td><td>[Array] All artists (as shortened <a href=\\\"#user\\\">user objects<\/a>, without their tracks).<\/td><\/tr>\"\n \"<tr><td><tt>\/track\/<var>{id}<\/var>\/json<\/tt><\/td><td>One <a href=\\\"#track\\\">track object<\/a>.<\/td><\/tr>\"\n \"<tr><td><tt>\/tracks\/search\/json?q=<var>{query}<\/var><\/tt><\/td><td>[Array] <a href=\\\"#track\\\">Track objects<\/a> matching the query.<\/td><\/tr>\"\n \"<tr><td><tt>\/tracks\/search\/exact\/json?artist=<var>{artist}<\/var>&track=<var>{track}<\/var><\/tt><\/td><td>[Array] <a href=\\\"#track\\\">Track object<\/a> matching the artist and track name exactly (case sensitive).<\/td><\/tr>\"\n \"<tr><td><tt>\/tracks\/latest\/json<\/tt><\/td><td>[Array] The latest 50 tracks.<\/td><\/tr>\"\n \"<tr><td><tt>\/tracks\/featured\/json<\/tt><\/td><td>[Array] The latest 50 featured tracks.<\/td><\/tr>\"\n \"<tr><td><tt>\/tracks\/random\/json<\/tt><\/td><td>[Array] 50 random tracks.<\/td><\/tr>\"\n \"<tr><td><tt>\/playlist\/<var>{id}<\/var>\/json<\/tt><\/td><td>One <a href=\\\"#playlist\\\">playlist object<\/a>.<\/td><\/tr>\"\n \"<\/table>\"\n \"<\/div>\"\n ;\n footer();\n}\n<commit_msg>gravatar FAQ entry<commit_after>#include \"static.h\"\n#include \"page.h\"\n#include \"..\/render.h\"\n\nusing namespace Render;\n\nvoid Html::quickStart(){\n header(\"Thanks\");\n o << \"<div class=\\\"message\\\">Now that you've registered you can upload your tracks and follow artists: just click your name at the top right corner of the page.<\/div>\"\n \"<div class=\\\"message\\\">Don't submit any tracks but your own, though.<\/div>\";\n footer();\n}\n\nvoid Html::faq(){\n header(\"FAQ\");\n o << \"<h2>Frequently Asked Questions<\/h2><div class=\\\"faq\\\">\"\n\n \"<h3>General<\/h3>\"\n\n \"<div><h4>What is this?<\/h4>\"\n \"<p>A place for artists to publish their MLP-related music, and get in touch with their audience.<\/p><\/div>\"\n\n \"<div><h4>Why?<\/h4>\"\n \"<p>Because there is no other central repository for MLP music.<\/p><\/div>\"\n\n \"<div><h4>Why not [INSERT SITE HERE]?<\/h4>\"\n \"<p>Because we try to make the publishing and listening process as smooth as can be. No ads, no limits, no downsides.<\/p><\/div>\"\n\n \"<div><h4>So how do I get on the list of artists? I wanna be one of the cool kids!<\/h4>\"\n \"<p><a href=\\\"\/register\\\">Sign up<\/a> for an account. Log in, get to your user page, and upload a track, then publish it. <i>Voilà<\/i>, you're on the list.<\/p><\/div>\"\n\n \"<h4>How do I set my avatar up?<\/h4>\"\n \"<p>Go to <a href=\\\"http:\/\/gravatar.com\/emails\/\\\">Gravatar.com<\/a> and create an account with the same email address as here. Upload your avatar there, it will show up here, and on other gravatar-enabled sites.<\/p>\"\n\n \"<h3 id=\\\"youtube\\\">YouTube<\/h3>\"\n\n \"<h4>Why would I want to link my YouTube account to my EqBeats account?<\/h4>\"\n \"<p>When your YouTube account is linked, by the click of a button, we'll create a video out of your track and its cover art, upload it to your YouTube channel, and stick a direct download link in the description. \"\n \"Basically it allows you to reach both your YouTube audience and your audience here in a single upload.<\/p>\"\n\n \"<h4>How do I link my YouTube account?<\/h4>\"\n \"<p>Look for a button on your <a href=\\\"\/account\\\">account edition<\/a> page, as well as any of your tracks. Google will ask you to verify that you trust us. Then, you're done!<\/p>\"\n\n \"<h4>How do I unlink my YouTube account?<\/h4>\"\n \"<p>There is a button on your <a href=\\\"\/account\\\">account edition<\/a> page.<\/p>\"\n\n \"<h3>Technical stuff<\/h3>\"\n\n \"<h4>What quality or bitrate are the audio files on EqBeats?<\/h4>\"\n \"<p>OGG Vorbis files are ~128kbps.<\/p>\"\n \"<p>We do not re-encode MP3 files, we only update the title and artist tags. This means they are exactly the same quality as the artist's original MP3 file.<\/p>\"\n \"<p>Your browser will stream either depending on its capabilities. \"\n \"As of today (April 19 2012), Firefox will only play OGG, Chrome can play either and will prefer OGG, and Safari and IE will only play MP3.<\/p>\"\n \"<p>And before you ask, the cover art files are left untouched as well. We just make a few thumbnails.<\/p>\"\n\n \"<h4>Do you have an API?<\/h4>\"\n \"<p><a href=\\\"\/api\\\">We do.<\/a><\/p>\"\n\n \"<h3>Contact<\/h3>\"\n\n \"<div><h4>Who are you anyway?<\/h4>\"\n \"<p>We're two developers: <a href=\\\"\/user\/1\\\">codl<\/a> and <a href=\\\"\/user\/2\\\">fmang<\/a>. For more information check the <a href=\\\"\/credits\\\">credits<\/a>.<\/p><\/div>\"\n\n \"<div><h4>I've got a question\/problem\/idea!<\/h4>\"\n \"<p>What are you waiting for? Drop us a line at contact@eqbeats.org.<\/p>\"\n \"<p>Or <a href=\\\"http:\/\/iris.ponychat.net\/?nick=pony_......&channels=eqbeats&prompt=1\\\">come chat with us<\/a> in <tt>#eqbeats<\/tt> on <tt>irc.ponychat.net<\/tt>. Don't be shy, we're friendly!<\/p><\/div>\"\n\n \"<\/div>\";\n footer();\n}\n\nvoid Html::credits(){\n header(\"Credits\");\n o << \"<h2>Credits<\/h2><div class=\\\"credits\\\">\"\n \"<h4>Staff<\/h4>\"\n \"<ul>\"\n \"<li><a href=\\\"\/user\/1\\\">codl<\/a><\/li>\"\n \"<li><a href=\\\"\/user\/2\\\">fmang<\/a><\/li>\"\n \"<\/ul>\"\n \"<h4>Support<\/h4>\"\n \"<ul>\"\n \"<li><a href=\\\"\/user\/3\\\">AspectOfTheStorm<\/a><\/li>\"\n \"<li><a href=\\\"\/user\/6\\\">Makkon<\/a><\/li>\"\n \"<li><a href=\\\"\/user\/68\\\">Karai<\/a><\/li>\"\n \"<\/ul>\"\n \"<h4>Design<\/h4>\"\n \"<ul>\"\n \"<li><a href=\\\"http:\/\/www.slt.fr\\\">SLT<\/a> - Logo<\/li>\"\n \"<li><a href=\\\"http:\/\/blackm3sh.deviantart.com\/art\/Rarity-Filly-203377463\\\">BlackM3sh<\/a> - Filly Rarity<\/li>\"\n \"<li><a href=\\\"http:\/\/p.yusukekamiyamane.com\/\\\">Yusuke Kamiyamane<\/a> - Fugue icon set<\/li>\"\n \"<\/ul><\/div>\";\n footer();\n}\n\nvoid Html::apiDoc(){\n header(\"API\");\n o << \"<div id=\\\"api\\\">\"\n \"<h2>API<\/h2>\"\n \"<h3>Quickstart<\/h3>\"\n \"<p>We have a read-only JSON\/JSONP api to access user and track data.<br\/>\"\n \"Just add <tt>\/json<\/tt> to most urls to get a JSON representation of that page.<br\/>\"\n \"Adding a <tt>jsonp<\/tt> parameter will insert the JSON data as an argument to a function named by the <tt>jsonp<\/tt> parameter. It can then be run by loading it in a <script> tag. <small><a href=\\\"https:\/\/en.wikipedia.org\/wiki\/JSONP\\\">More info on JSONP.<\/a><\/small><br\/>\"\n \"Compare <a href=\\\"http:\/\/eqbeats.org\/tracks\/latest\/json\\\">\/tracks\/latest\/json<\/a> and <a href=\\\"http:\/\/eqbeats.org\/tracks\/latest\/json?jsonp=myCallback\\\">\/tracks\/latest\/json?jsonp=myCallback<\/a>.<\/p>\"\n \"<h3 id=\\\"user\\\">User object<\/h3>\"\n \"<table>\"\n \"<tr><td><tt>id<\/tt><\/td><td>Unique numerical id for this user.<\/td><\/tr>\"\n \"<tr><td><tt>name<\/tt><\/td><td>User name.<\/td><\/tr>\"\n \"<tr><td><tt>description<\/tt><\/td><td>User's description of themselves, raw. This member will not exist if there is no description.<\/td><\/tr>\"\n \"<tr><td><tt>html_description<\/tt><\/td><td>Same as above, formatted to HTML.<\/td><\/tr>\"\n \"<tr><td><tt>tracks<\/tt><\/td><td>An array of <a href=\\\"#track\\\">Track objects<\/a> for all tracks published by the user.<\/td><\/tr>\"\n \"<tr><td><tt>playlists<\/tt><\/td><td>Array of <a href=\\\"#playlist\\\">Playlist objects<\/a> (id, name, author and link only).<\/td><\/tr>\"\n \"<tr><td><tt>link<\/tt><\/td><td>Permalink to the user's page.<\/td><\/tr>\"\n \"<\/table>\"\n \"<pre>{<br\/>\"\n \" \\\"id\\\": 123,<br\/>\"\n \" \\\"name\\\": \\\"Foo Bar\\\",<br\/>\"\n \" \\\"description\\\": \\\"Just some dude making [b]music[\/b].\\\",<br\/>\"\n \" \\\"html_description\\\": \\\"Just some dude making <b>music<\/b>.\\\",<br\/>\"\n \" \\\"tracks\\\": [{\\\"id\\\": 456, ...}, ...],<br\/>\"\n \" \\\"playlists\\\": [{\\\"id\\\": 789, ...}, ...],<br\/>\"\n \" \\\"link\\\": \\\"http:\/\/eqbeats.org\/user\/123\\\"<br\/>\"\n \"}<\/pre>\"\n \"<h3 id=\\\"track\\\">Track object<\/h3>\"\n \"<table>\"\n \"<tr><td><tt>id<\/tt><\/td><td>Unique numerical id for the track.<\/td><\/tr>\"\n \"<tr><td><tt>title<\/tt><\/td><td>Track title.<\/td><\/tr>\"\n \"<tr><td><tt>description<\/tt><\/td><td>Track notes, raw. This member will not exist if there are no notes.<\/td><\/tr>\"\n \"<tr><td><tt>html_description<\/tt><\/td><td>Same as above, formatted to HTML.<\/td><\/tr>\"\n \"<tr><td><tt>artist<\/tt><\/td><td>A <a href=\\\"#user\\\">user object<\/a> for the artist (excluding the track array).<\/td><\/tr>\"\n \"<tr><td><tt>link<\/tt><\/td><td>Permalink to the track's page.<\/td><\/tr>\"\n \"<tr><td><tt>download<\/tt><\/td><td>Permalinks to the downloadable \/ streamable audio files.<\/td><\/tr>\"\n \"<\/table>\"\n \"<pre>{<br\/>\"\n \" \\\"id\\\": 456,<br\/>\"\n \" \\\"title\\\": \\\"Baz Quux\\\",<br\/>\"\n \" \\\"description\\\": \\\"A track about bazing while you quux.\\\",<br\/>\"\n \" \\\"html_description\\\": \\\"A track about bazing while you quux.\\\",<br\/>\"\n \" \\\"artist\\\": {\\\"id\\\": 123, \\\"name\\\": \\\"Foo Bar\\\",...}<br\/>\"\n \" \\\"link\\\": \\\"http:\/\/eqbeats.org\/track\/456\\\",<br\/>\"\n \" \\\"download\\\": {\\\"mp3\\\":\\\"http:\/\/eqbeats.org\/track\/456\/mp3\\\",<br\/>\"\n \" \\\"vorbis\\\":\\\"http:\/\/eqbeats.org\/track\/456\/vorbis\\\"}<br\/>\"\n \"}<\/pre>\"\n \"<h3 id=\\\"playlist\\\">Playlist object<\/h3>\"\n \"<table>\"\n \"<tr><td><tt>id<\/tt><\/td><td>Unique numerical id for the playlist.<\/td><\/tr>\"\n \"<tr><td><tt>name<\/tt><\/td><td>Playlist name.<\/td><\/tr>\"\n \"<tr><td><tt>description<\/tt><\/td><td>Description, raw. This member will not exist if there is no description.<\/td><\/tr>\"\n \"<tr><td><tt>html_description<\/tt><\/td><td>Same as above, formatted to HTML.<\/td><\/tr>\"\n \"<tr><td><tt>author<\/tt><\/td><td>A <a href=\\\"#user\\\">user object<\/a> for the author.<\/td><\/tr>\"\n \"<tr><td><tt>tracks<\/tt><\/td><td>An array of <a href=\\\"#track\\\">Track objects<\/a>.<\/td><\/tr>\"\n \"<tr><td><tt>link<\/tt><\/td><td>Permalink to the playlist's page.<\/td><\/tr>\"\n \"<\/table>\"\n \"<h3>Resources<\/h3>\"\n \"<table>\"\n \"<tr><td><tt>\/user\/<var>{id}<\/var>\/json<\/tt><\/td><td>One <a href=\\\"#user\\\">user object<\/a>.<\/td><\/tr>\"\n \"<tr><td><tt>\/users\/search\/json?q=<var>{query}<\/var><\/tt><\/td><td>[Array] <a href=\\\"#user\\\">User objects<\/a> matching the query.<\/td><\/tr>\"\n \"<tr><td><tt>\/user\/<var>{id}<\/var>\/favorites\/json<\/tt><\/td><td>[Array] Favorite tracks.<\/td><\/tr>\"\n \"<tr><td><tt>\/artists\/json<\/tt><\/td><td>[Array] All artists (as shortened <a href=\\\"#user\\\">user objects<\/a>, without their tracks).<\/td><\/tr>\"\n \"<tr><td><tt>\/track\/<var>{id}<\/var>\/json<\/tt><\/td><td>One <a href=\\\"#track\\\">track object<\/a>.<\/td><\/tr>\"\n \"<tr><td><tt>\/tracks\/search\/json?q=<var>{query}<\/var><\/tt><\/td><td>[Array] <a href=\\\"#track\\\">Track objects<\/a> matching the query.<\/td><\/tr>\"\n \"<tr><td><tt>\/tracks\/search\/exact\/json?artist=<var>{artist}<\/var>&track=<var>{track}<\/var><\/tt><\/td><td>[Array] <a href=\\\"#track\\\">Track object<\/a> matching the artist and track name exactly (case sensitive).<\/td><\/tr>\"\n \"<tr><td><tt>\/tracks\/latest\/json<\/tt><\/td><td>[Array] The latest 50 tracks.<\/td><\/tr>\"\n \"<tr><td><tt>\/tracks\/featured\/json<\/tt><\/td><td>[Array] The latest 50 featured tracks.<\/td><\/tr>\"\n \"<tr><td><tt>\/tracks\/random\/json<\/tt><\/td><td>[Array] 50 random tracks.<\/td><\/tr>\"\n \"<tr><td><tt>\/playlist\/<var>{id}<\/var>\/json<\/tt><\/td><td>One <a href=\\\"#playlist\\\">playlist object<\/a>.<\/td><\/tr>\"\n \"<\/table>\"\n \"<\/div>\"\n ;\n footer();\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2011-2014 Zeex\n\/\/ All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are met:\n\/\/\n\/\/ 1. Redistributions of source code must retain the above copyright notice,\n\/\/ this list of conditions and the following disclaimer.\n\/\/ 2. Redistributions in binary form must reproduce the above copyright notice,\n\/\/ this list of conditions and the following disclaimer in the documentation\n\/\/ and\/or other materials provided with the distribution.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n\/\/ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\/\/ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\/\/ ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\n\/\/ LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n\/\/ CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n\/\/ SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n\/\/ INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n\/\/ CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n\/\/ ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n\/\/ POSSIBILITY OF SUCH DAMAGE.\n\n#include <algorithm>\n#include <cassert>\n#include <cstdarg>\n#include <exception>\n#include <fstream>\n#include <iterator>\n#include <sstream>\n#include <string>\n#include <amxprof\/call_graph_writer_dot.h>\n#include <amxprof\/function.h>\n#include <amxprof\/function_statistics.h>\n#include <amxprof\/statistics_writer_html.h>\n#include <amxprof\/statistics_writer_json.h>\n#include <amxprof\/statistics_writer_text.h>\n#include \"amxpath.h\"\n#include \"fileutils.h\"\n#include \"logprintf.h\"\n#include \"profiler.h\"\n\n#define logprintf Use_Printf_isntead_of_logprintf\n\nnamespace {\nnamespace cfg {\n\nConfigReader server_cfg(\"server.cfg\");\n\nstd::string gamemodes =\n server_cfg.GetValueWithDefault(\"profiler_gamemodes\");\nstd::vector<std::string> filterscripts =\n server_cfg.GetValues<std::string>(\"profiler_filterscripts\");\nstd::string output_format =\n server_cfg.GetValueWithDefault(\"profiler_outputformat\", \"html\");\nbool call_graph =\n server_cfg.GetValueWithDefault(\"profiler_callgraph\", false);\nstd::string call_graph_format =\n server_cfg.GetValueWithDefault(\"profiler_callgraphformat\", \"dot\");\n\nnamespace old {\n\n\/\/ old config variables.\nbool profile_gamemode =\n server_cfg.GetValueWithDefault(\"profile_gamemode\", false);\nstd::vector<std::string> profile_filterscripts =\n server_cfg.GetValues<std::string>(\"profile_filterscripts\");\nstd::string profile_format =\n server_cfg.GetValueWithDefault(\"profile_format\", \"html\");\nbool call_graph =\n server_cfg.GetValueWithDefault(\"call_graph\", false);\nstd::string call_graph_format =\n server_cfg.GetValueWithDefault(\"call_graph_format\", \"dot\");\n\n} \/\/ namespace old\n} \/\/ namespace cfg\n\nvoid Printf(const char *format, ...) {\n std::va_list va;\n va_start(va, format);\n\n std::string new_format;\n new_format.append(\"[profiler] \");\n new_format.append(format);\n\n vlogprintf(new_format.c_str(), va);\n va_end(va);\n}\n\nvoid PrintException(const std::exception &e) {\n Printf(\"Error: %s\", e.what());\n}\n\nvoid SplitString(const std::string &s,\n char delim,\n std::vector<std::string> &comps) {\n std::string::size_type begin = 0;\n std::string::size_type end;\n\n while (begin < s.length()) {\n end = s.find(delim, begin);\n end = (end == std::string::npos) ? s.length() : end;\n comps.push_back(std::string(s.begin() + begin, s.begin() + end));\n begin = end + 1;\n }\n}\n\nvoid ToLower(std::string &s) {\n std::transform(s.begin(), s.end(), s.begin(), ::tolower);\n}\n\nstd::string ToUnixPath(std::string path) {\n std::replace(path.begin(), path.end(), '\\\\', '\/');\n return path;\n}\n\nbool IsCallGraphEnabled() {\n return cfg::call_graph || cfg::old::call_graph;\n}\n\nbool IsGameMode(const std::string &amx_path) {\n return amx_path.find(\"gamemodes\/\") != std::string::npos;\n}\n\nbool IsFilterScript(const std::string &amx_path) {\n return amx_path.find(\"filterscripts\/\") != std::string::npos;\n}\n\nbool ShouldBeProfiled(const std::string amx_path) {\n if (IsGameMode(amx_path)) {\n if (cfg::old::profile_gamemode) {\n return true;\n }\n std::vector<std::string> gm_names;\n SplitString(cfg::gamemodes, ' ', gm_names);\n for (std::vector<std::string>::const_iterator iterator = gm_names.begin();\n iterator != gm_names.end(); ++iterator) {\n const std::string &gm_name = *iterator;\n if (fileutils::SameFile(amx_path, \"gamemodes\/\" + gm_name + \".amx\") ||\n fileutils::SameFile(amx_path, \"gamemodes\/\" + gm_name)) {\n return true;\n }\n }\n }\n if (IsFilterScript(amx_path)) {\n std::vector<std::string> fs_names;\n std::copy(cfg::old::profile_filterscripts.begin(),\n cfg::old::profile_filterscripts.end(),\n std::back_inserter(fs_names));\n std::copy(cfg::filterscripts.begin(),\n cfg::filterscripts.end(),\n std::back_inserter(fs_names));\n for (std::vector<std::string>::const_iterator iterator = fs_names.begin();\n iterator != fs_names.end(); ++iterator) {\n const std::string &fs_name = *iterator;\n if (fileutils::SameFile(amx_path, \"filterscripts\/\" + fs_name + \".amx\") ||\n fileutils::SameFile(amx_path, \"filterscripts\/\" + fs_name)) {\n return true;\n }\n }\n }\n return false;\n}\n\n} \/\/ anonymous namespace\n\nProfiler::Profiler(AMX *amx)\n : AMXService<Profiler>(amx),\n prev_debug_(amx->debug),\n prev_callback_(amx->callback),\n profiler_(amx, IsCallGraphEnabled()),\n state_(PROFILER_DISABLED)\n{\n AmxPathFinder amx_path_finder;\n amx_path_finder.AddSearchDirectory(\"gamemodes\");\n amx_path_finder.AddSearchDirectory(\"filterscripts\");\n\n const char *amx_search_path = getenv(\"AMX_PATH\");\n if (amx_search_path != 0) {\n std::vector<std::string> dirs;\n SplitString(amx_search_path, fileutils::kNativePathListSepChar, dirs);\n for (std::vector<std::string>::const_iterator iterator = dirs.begin();\n iterator != dirs.end(); ++iterator) {\n amx_path_finder.AddSearchDirectory(*iterator);\n }\n }\n\n amx_path_ = ToUnixPath(amx_path_finder.FindAmxPath(amx));\n amx_name_ = fileutils::GetDirectory(amx_path_)\n + \"\/\"\n + fileutils::GetBaseName(amx_path_);\n\n if (amx_path_.empty()) {\n Printf(\"Could not find AMX file (try setting AMX_PATH?)\");\n }\n}\n\nint Profiler::Load() {\n if (ShouldBeProfiled(amx_path_)) {\n Attach();\n }\n return AMX_ERR_NONE;\n}\n\nint Profiler::Unload() {\n return AMX_ERR_NONE;\n}\n\nint Profiler::Debug() {\n if (state_ == PROFILER_STARTED) {\n try {\n return profiler_.DebugHook(prev_debug_);\n } catch (const std::exception &e) {\n PrintException(e);\n }\n }\n if (prev_debug_ != 0) {\n return prev_debug_(amx());\n }\n return AMX_ERR_NONE;\n}\n\nint Profiler::Callback(cell index, cell *result, cell *params) {\n if (state_ == PROFILER_STARTED) {\n try {\n return profiler_.CallbackHook(index, result, params, prev_callback_);\n } catch (const std::exception &e) {\n PrintException(e);\n }\n }\n return prev_callback_(amx(), index, result, params);\n}\n\nint Profiler::Exec(cell *retval, int index) {\n if (profiler_.call_stack()->is_empty()) {\n switch (state_) {\n case PROFILER_ATTACHING:\n if (!Attach()) {\n break;\n }\n \/\/ fallthrough\n case PROFILER_STARTING:\n CompleteStart();\n break;\n }\n }\n if (state_ == PROFILER_STARTED) {\n try {\n int error = profiler_.ExecHook(retval, index, amx_Exec);\n if (state_ == PROFILER_STOPPING\n && profiler_.call_stack()->is_empty()) {\n CompleteStop();\n }\n return error;\n } catch (const std::exception &e) {\n PrintException(e);\n }\n }\n return amx_Exec(amx(), retval, index);\n}\n\nProfilerState Profiler::GetState() const {\n return state_;\n}\n\nbool Profiler::Attach() {\n try {\n if (amx_path_.empty()) {\n return false;\n }\n if (state_ >= PROFILER_ATTACHED) {\n return false;\n }\n\n if (amxprof::HasDebugInfo(amx())) {\n if (debug_info_.Load(amx_path_)) {\n profiler_.set_debug_info(&debug_info_);\n } else {\n Printf(\"Error loading debug info: %s\",\n aux_StrError(debug_info_.last_error()));\n }\n }\n\n if (debug_info_.is_loaded()) {\n Printf(\"Attached profiler to %s\", amx_name_.c_str());\n } else {\n Printf(\"Attached profiler to %s (no debug info)\", amx_name_.c_str());\n }\n\n state_ = PROFILER_ATTACHED;\n return true;\n }\n catch (const std::exception &e) {\n PrintException(e);\n }\n return false;\n}\n\nbool Profiler::Start() {\n if (state_ < PROFILER_ATTACHED) {\n state_ = PROFILER_ATTACHING;\n return true;\n }\n if (state_ >= PROFILER_ATTACHED) {\n state_ = PROFILER_STARTING;\n return true;\n }\n return false;\n}\n\nvoid Profiler::CompleteStart() {\n Printf(\"Started profiling %s\", amx_name_.c_str());\n state_ = PROFILER_STARTED;\n}\n\nbool Profiler::Stop() {\n if (state_ >= PROFILER_STARTED) {\n state_ = PROFILER_STOPPING;\n return true;\n }\n return false;\n}\n\nvoid Profiler::CompleteStop() {\n Printf(\"Stopped profiling %s\", amx_name_.c_str());\n state_ = PROFILER_STOPPED;\n}\n\nbool Profiler::Dump() const {\n try {\n if (state_ < PROFILER_ATTACHED) {\n return false;\n }\n\n Printf(\"Dumping profiling statistics for %s\", amx_name_.c_str());\n\n std::vector<amxprof::FunctionStatistics*> fn_stats;\n profiler_.stats()->GetStatistics(fn_stats);\n\n int num_native_functions = 0;\n int num_public_functions = 0;\n int num_other_functions = 0;\n long num_calls = 0;\n\n for (std::vector<amxprof::FunctionStatistics*>::const_iterator\n iterator = fn_stats.begin();\n iterator != fn_stats.end();\n ++iterator) {\n amxprof::Function *fn = (*iterator)->function();\n if (fn->type() == amxprof::Function::NATIVE) {\n num_native_functions++;\n } else if (fn->type() == amxprof::Function::PUBLIC) {\n num_public_functions++;\n } else {\n num_other_functions++;\n }\n num_calls += (*iterator)->num_calls();\n }\n\n Printf(\"Total functions logged: %zu (native: %d, public: %d, other: %d)\",\n fn_stats.size(),\n num_native_functions,\n num_public_functions,\n num_other_functions);\n Printf(\"Total function calls logged: %ld\", num_calls);\n\n std::string output_format = cfg::output_format;\n if (output_format.empty()) {\n output_format = cfg::old::profile_format;\n }\n ToLower(output_format);\n std::string profile_filename =\n amx_name_ + \"-profile.\" + output_format;\n std::ofstream profile_stream(profile_filename.c_str());\n\n if (profile_stream.is_open()) {\n amxprof::StatisticsWriter *writer = 0;\n\n if (output_format == \"html\") {\n writer = new amxprof::StatisticsWriterHtml;\n } else if (output_format == \"txt\" || output_format == \"text\") {\n writer = new amxprof::StatisticsWriterText;\n } else if (output_format == \"json\") {\n writer = new amxprof::StatisticsWriterJson;\n } else {\n Printf(\"Unsupported output format '%s'\", output_format.c_str());\n }\n\n if (writer != 0) {\n Printf(\"Writing profile to %s\", profile_filename.c_str());\n writer->set_stream(&profile_stream);\n writer->set_script_name(amx_path_);\n writer->set_print_date(true);\n writer->set_print_run_time(true);\n writer->Write(profiler_.stats());\n delete writer;\n }\n\n profile_stream.close();\n } else {\n Printf(\"Error opening '%s' for writing\", profile_filename.c_str());\n }\n\n if (IsCallGraphEnabled()) {\n std::string call_graph_format = cfg::call_graph_format;\n if (call_graph_format.empty()) {\n call_graph_format = cfg::old::call_graph_format;\n }\n ToLower(call_graph_format);\n std::string call_graph_filename =\n amx_name_ + \"-calls.\" + call_graph_format;\n std::ofstream call_graph_stream(call_graph_filename.c_str());\n\n if (call_graph_stream.is_open()) {\n amxprof::CallGraphWriterDot *writer = 0;\n\n if (call_graph_format == \"dot\") {\n writer = new amxprof::CallGraphWriterDot;\n } else {\n Printf(\"Unsupported call graph format '%s'\",\n call_graph_format.c_str());\n }\n\n if (writer != 0) {\n Printf(\"Writing call graph to %s\", call_graph_filename.c_str());\n writer->set_stream(&call_graph_stream);\n writer->set_script_name(amx_path_);\n writer->set_root_node_name(\"SA-MP Server\");\n writer->Write(profiler_.call_graph());\n delete writer;\n }\n\n call_graph_stream.close();\n } else {\n Printf(\"Error opening %s for writing\", call_graph_filename.c_str());\n }\n }\n return true;\n }\n catch (const std::exception &e) {\n PrintException(e);\n }\n return false;\n}\n<commit_msg>Replace %zu with %llu<commit_after>\/\/ Copyright (c) 2011-2014 Zeex\n\/\/ All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are met:\n\/\/\n\/\/ 1. Redistributions of source code must retain the above copyright notice,\n\/\/ this list of conditions and the following disclaimer.\n\/\/ 2. Redistributions in binary form must reproduce the above copyright notice,\n\/\/ this list of conditions and the following disclaimer in the documentation\n\/\/ and\/or other materials provided with the distribution.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n\/\/ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\/\/ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\/\/ ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\n\/\/ LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n\/\/ CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n\/\/ SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n\/\/ INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n\/\/ CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n\/\/ ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n\/\/ POSSIBILITY OF SUCH DAMAGE.\n\n#include <algorithm>\n#include <cassert>\n#include <cstdarg>\n#include <exception>\n#include <fstream>\n#include <iterator>\n#include <sstream>\n#include <string>\n#include <amxprof\/call_graph_writer_dot.h>\n#include <amxprof\/function.h>\n#include <amxprof\/function_statistics.h>\n#include <amxprof\/statistics_writer_html.h>\n#include <amxprof\/statistics_writer_json.h>\n#include <amxprof\/statistics_writer_text.h>\n#include \"amxpath.h\"\n#include \"fileutils.h\"\n#include \"logprintf.h\"\n#include \"profiler.h\"\n\n#define logprintf Use_Printf_isntead_of_logprintf\n\nnamespace {\nnamespace cfg {\n\nConfigReader server_cfg(\"server.cfg\");\n\nstd::string gamemodes =\n server_cfg.GetValueWithDefault(\"profiler_gamemodes\");\nstd::vector<std::string> filterscripts =\n server_cfg.GetValues<std::string>(\"profiler_filterscripts\");\nstd::string output_format =\n server_cfg.GetValueWithDefault(\"profiler_outputformat\", \"html\");\nbool call_graph =\n server_cfg.GetValueWithDefault(\"profiler_callgraph\", false);\nstd::string call_graph_format =\n server_cfg.GetValueWithDefault(\"profiler_callgraphformat\", \"dot\");\n\nnamespace old {\n\n\/\/ old config variables.\nbool profile_gamemode =\n server_cfg.GetValueWithDefault(\"profile_gamemode\", false);\nstd::vector<std::string> profile_filterscripts =\n server_cfg.GetValues<std::string>(\"profile_filterscripts\");\nstd::string profile_format =\n server_cfg.GetValueWithDefault(\"profile_format\", \"html\");\nbool call_graph =\n server_cfg.GetValueWithDefault(\"call_graph\", false);\nstd::string call_graph_format =\n server_cfg.GetValueWithDefault(\"call_graph_format\", \"dot\");\n\n} \/\/ namespace old\n} \/\/ namespace cfg\n\nvoid Printf(const char *format, ...) {\n std::va_list va;\n va_start(va, format);\n\n std::string new_format;\n new_format.append(\"[profiler] \");\n new_format.append(format);\n\n vlogprintf(new_format.c_str(), va);\n va_end(va);\n}\n\nvoid PrintException(const std::exception &e) {\n Printf(\"Error: %s\", e.what());\n}\n\nvoid SplitString(const std::string &s,\n char delim,\n std::vector<std::string> &comps) {\n std::string::size_type begin = 0;\n std::string::size_type end;\n\n while (begin < s.length()) {\n end = s.find(delim, begin);\n end = (end == std::string::npos) ? s.length() : end;\n comps.push_back(std::string(s.begin() + begin, s.begin() + end));\n begin = end + 1;\n }\n}\n\nvoid ToLower(std::string &s) {\n std::transform(s.begin(), s.end(), s.begin(), ::tolower);\n}\n\nstd::string ToUnixPath(std::string path) {\n std::replace(path.begin(), path.end(), '\\\\', '\/');\n return path;\n}\n\nbool IsCallGraphEnabled() {\n return cfg::call_graph || cfg::old::call_graph;\n}\n\nbool IsGameMode(const std::string &amx_path) {\n return amx_path.find(\"gamemodes\/\") != std::string::npos;\n}\n\nbool IsFilterScript(const std::string &amx_path) {\n return amx_path.find(\"filterscripts\/\") != std::string::npos;\n}\n\nbool ShouldBeProfiled(const std::string amx_path) {\n if (IsGameMode(amx_path)) {\n if (cfg::old::profile_gamemode) {\n return true;\n }\n std::vector<std::string> gm_names;\n SplitString(cfg::gamemodes, ' ', gm_names);\n for (std::vector<std::string>::const_iterator iterator = gm_names.begin();\n iterator != gm_names.end(); ++iterator) {\n const std::string &gm_name = *iterator;\n if (fileutils::SameFile(amx_path, \"gamemodes\/\" + gm_name + \".amx\") ||\n fileutils::SameFile(amx_path, \"gamemodes\/\" + gm_name)) {\n return true;\n }\n }\n }\n if (IsFilterScript(amx_path)) {\n std::vector<std::string> fs_names;\n std::copy(cfg::old::profile_filterscripts.begin(),\n cfg::old::profile_filterscripts.end(),\n std::back_inserter(fs_names));\n std::copy(cfg::filterscripts.begin(),\n cfg::filterscripts.end(),\n std::back_inserter(fs_names));\n for (std::vector<std::string>::const_iterator iterator = fs_names.begin();\n iterator != fs_names.end(); ++iterator) {\n const std::string &fs_name = *iterator;\n if (fileutils::SameFile(amx_path, \"filterscripts\/\" + fs_name + \".amx\") ||\n fileutils::SameFile(amx_path, \"filterscripts\/\" + fs_name)) {\n return true;\n }\n }\n }\n return false;\n}\n\n} \/\/ anonymous namespace\n\nProfiler::Profiler(AMX *amx)\n : AMXService<Profiler>(amx),\n prev_debug_(amx->debug),\n prev_callback_(amx->callback),\n profiler_(amx, IsCallGraphEnabled()),\n state_(PROFILER_DISABLED)\n{\n AmxPathFinder amx_path_finder;\n amx_path_finder.AddSearchDirectory(\"gamemodes\");\n amx_path_finder.AddSearchDirectory(\"filterscripts\");\n\n const char *amx_search_path = getenv(\"AMX_PATH\");\n if (amx_search_path != 0) {\n std::vector<std::string> dirs;\n SplitString(amx_search_path, fileutils::kNativePathListSepChar, dirs);\n for (std::vector<std::string>::const_iterator iterator = dirs.begin();\n iterator != dirs.end(); ++iterator) {\n amx_path_finder.AddSearchDirectory(*iterator);\n }\n }\n\n amx_path_ = ToUnixPath(amx_path_finder.FindAmxPath(amx));\n amx_name_ = fileutils::GetDirectory(amx_path_)\n + \"\/\"\n + fileutils::GetBaseName(amx_path_);\n\n if (amx_path_.empty()) {\n Printf(\"Could not find AMX file (try setting AMX_PATH?)\");\n }\n}\n\nint Profiler::Load() {\n if (ShouldBeProfiled(amx_path_)) {\n Attach();\n }\n return AMX_ERR_NONE;\n}\n\nint Profiler::Unload() {\n return AMX_ERR_NONE;\n}\n\nint Profiler::Debug() {\n if (state_ == PROFILER_STARTED) {\n try {\n return profiler_.DebugHook(prev_debug_);\n } catch (const std::exception &e) {\n PrintException(e);\n }\n }\n if (prev_debug_ != 0) {\n return prev_debug_(amx());\n }\n return AMX_ERR_NONE;\n}\n\nint Profiler::Callback(cell index, cell *result, cell *params) {\n if (state_ == PROFILER_STARTED) {\n try {\n return profiler_.CallbackHook(index, result, params, prev_callback_);\n } catch (const std::exception &e) {\n PrintException(e);\n }\n }\n return prev_callback_(amx(), index, result, params);\n}\n\nint Profiler::Exec(cell *retval, int index) {\n if (profiler_.call_stack()->is_empty()) {\n switch (state_) {\n case PROFILER_ATTACHING:\n if (!Attach()) {\n break;\n }\n \/\/ fallthrough\n case PROFILER_STARTING:\n CompleteStart();\n break;\n }\n }\n if (state_ == PROFILER_STARTED) {\n try {\n int error = profiler_.ExecHook(retval, index, amx_Exec);\n if (state_ == PROFILER_STOPPING\n && profiler_.call_stack()->is_empty()) {\n CompleteStop();\n }\n return error;\n } catch (const std::exception &e) {\n PrintException(e);\n }\n }\n return amx_Exec(amx(), retval, index);\n}\n\nProfilerState Profiler::GetState() const {\n return state_;\n}\n\nbool Profiler::Attach() {\n try {\n if (amx_path_.empty()) {\n return false;\n }\n if (state_ >= PROFILER_ATTACHED) {\n return false;\n }\n\n if (amxprof::HasDebugInfo(amx())) {\n if (debug_info_.Load(amx_path_)) {\n profiler_.set_debug_info(&debug_info_);\n } else {\n Printf(\"Error loading debug info: %s\",\n aux_StrError(debug_info_.last_error()));\n }\n }\n\n if (debug_info_.is_loaded()) {\n Printf(\"Attached profiler to %s\", amx_name_.c_str());\n } else {\n Printf(\"Attached profiler to %s (no debug info)\", amx_name_.c_str());\n }\n\n state_ = PROFILER_ATTACHED;\n return true;\n }\n catch (const std::exception &e) {\n PrintException(e);\n }\n return false;\n}\n\nbool Profiler::Start() {\n if (state_ < PROFILER_ATTACHED) {\n state_ = PROFILER_ATTACHING;\n return true;\n }\n if (state_ >= PROFILER_ATTACHED) {\n state_ = PROFILER_STARTING;\n return true;\n }\n return false;\n}\n\nvoid Profiler::CompleteStart() {\n Printf(\"Started profiling %s\", amx_name_.c_str());\n state_ = PROFILER_STARTED;\n}\n\nbool Profiler::Stop() {\n if (state_ >= PROFILER_STARTED) {\n state_ = PROFILER_STOPPING;\n return true;\n }\n return false;\n}\n\nvoid Profiler::CompleteStop() {\n Printf(\"Stopped profiling %s\", amx_name_.c_str());\n state_ = PROFILER_STOPPED;\n}\n\nbool Profiler::Dump() const {\n try {\n if (state_ < PROFILER_ATTACHED) {\n return false;\n }\n\n Printf(\"Dumping profiling statistics for %s\", amx_name_.c_str());\n\n std::vector<amxprof::FunctionStatistics*> fn_stats;\n profiler_.stats()->GetStatistics(fn_stats);\n\n int num_native_functions = 0;\n int num_public_functions = 0;\n int num_other_functions = 0;\n long num_calls = 0;\n\n for (std::vector<amxprof::FunctionStatistics*>::const_iterator\n iterator = fn_stats.begin();\n iterator != fn_stats.end();\n ++iterator) {\n amxprof::Function *fn = (*iterator)->function();\n if (fn->type() == amxprof::Function::NATIVE) {\n num_native_functions++;\n } else if (fn->type() == amxprof::Function::PUBLIC) {\n num_public_functions++;\n } else {\n num_other_functions++;\n }\n num_calls += (*iterator)->num_calls();\n }\n\n Printf(\"Total functions logged: %llu (native: %d, public: %d, other: %d)\",\n (unsigned long long)fn_stats.size(),\n num_native_functions,\n num_public_functions,\n num_other_functions);\n Printf(\"Total function calls logged: %ld\", num_calls);\n\n std::string output_format = cfg::output_format;\n if (output_format.empty()) {\n output_format = cfg::old::profile_format;\n }\n ToLower(output_format);\n std::string profile_filename =\n amx_name_ + \"-profile.\" + output_format;\n std::ofstream profile_stream(profile_filename.c_str());\n\n if (profile_stream.is_open()) {\n amxprof::StatisticsWriter *writer = 0;\n\n if (output_format == \"html\") {\n writer = new amxprof::StatisticsWriterHtml;\n } else if (output_format == \"txt\" || output_format == \"text\") {\n writer = new amxprof::StatisticsWriterText;\n } else if (output_format == \"json\") {\n writer = new amxprof::StatisticsWriterJson;\n } else {\n Printf(\"Unsupported output format '%s'\", output_format.c_str());\n }\n\n if (writer != 0) {\n Printf(\"Writing profile to %s\", profile_filename.c_str());\n writer->set_stream(&profile_stream);\n writer->set_script_name(amx_path_);\n writer->set_print_date(true);\n writer->set_print_run_time(true);\n writer->Write(profiler_.stats());\n delete writer;\n }\n\n profile_stream.close();\n } else {\n Printf(\"Error opening '%s' for writing\", profile_filename.c_str());\n }\n\n if (IsCallGraphEnabled()) {\n std::string call_graph_format = cfg::call_graph_format;\n if (call_graph_format.empty()) {\n call_graph_format = cfg::old::call_graph_format;\n }\n ToLower(call_graph_format);\n std::string call_graph_filename =\n amx_name_ + \"-calls.\" + call_graph_format;\n std::ofstream call_graph_stream(call_graph_filename.c_str());\n\n if (call_graph_stream.is_open()) {\n amxprof::CallGraphWriterDot *writer = 0;\n\n if (call_graph_format == \"dot\") {\n writer = new amxprof::CallGraphWriterDot;\n } else {\n Printf(\"Unsupported call graph format '%s'\",\n call_graph_format.c_str());\n }\n\n if (writer != 0) {\n Printf(\"Writing call graph to %s\", call_graph_filename.c_str());\n writer->set_stream(&call_graph_stream);\n writer->set_script_name(amx_path_);\n writer->set_root_node_name(\"SA-MP Server\");\n writer->Write(profiler_.call_graph());\n delete writer;\n }\n\n call_graph_stream.close();\n } else {\n Printf(\"Error opening %s for writing\", call_graph_filename.c_str());\n }\n }\n return true;\n }\n catch (const std::exception &e) {\n PrintException(e);\n }\n return false;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ SA:MP Profiler plugin\r\n\/\/\r\n\/\/ Copyright (c) 2011 Zeex\r\n\/\/\r\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\r\n\/\/ you may not use this file except in compliance with the License.\r\n\/\/ You may obtain a copy of the License at\r\n\/\/\r\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\r\n\/\/\r\n\/\/ Unless required by applicable law or agreed to in writing, software\r\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\r\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n\/\/ See the License for the specific language governing permissions and\r\n\/\/ limitations under the License.\r\n\r\n#include <algorithm>\r\n#include <cassert>\r\n#include <map>\r\n#include <numeric>\r\n#include <sstream>\r\n#include <string>\r\n\r\n#include \"abstract_printer.h\"\r\n#include \"function.h\"\r\n#include \"profile.h\"\r\n#include \"profiler.h\"\r\n\r\n#include \"amx\/amx.h\"\r\n#include \"amx\/amxdbg.h\"\r\n\r\nnamespace {\r\n\r\nint AMXAPI Debug(AMX *amx) {\r\n\treturn samp_profiler::Profiler::Get(amx)->Debug();\r\n}\r\n\r\n\/\/ Reads from a code section at a given location.\r\ninline cell ReadAmxCode(AMX *amx, cell where) {\r\n\tAMX_HEADER *hdr = reinterpret_cast<AMX_HEADER*>(amx->base);\r\n\treturn *reinterpret_cast<cell*>(amx->base + hdr->cod + where);\r\n}\r\n\r\n} \/\/ anonymous namespace\r\n\r\nnamespace samp_profiler {\r\n\r\n\/\/ statics\r\nstd::map<AMX*, Profiler*> Profiler::instances_;\r\n\r\nProfiler::Profiler() {}\r\n\r\nbool Profiler::IsScriptProfilable(AMX *amx) {\r\n\tuint16_t flags;\r\n\tamx_Flags(amx, &flags);\r\n\r\n\tif ((flags & AMX_FLAG_DEBUG) != 0) {\r\n\t\treturn true;\r\n\t}\r\n\r\n\tif ((flags & AMX_FLAG_NOCHECKS) == 0) {\r\n\t\treturn true;\r\n\t}\r\n\r\n\treturn false;\r\n}\r\n\r\n\/\/ static\r\nvoid Profiler::Attach(AMX *amx) {\r\n\tProfiler *prof = new Profiler(amx);\r\n\tinstances_[amx] = prof;\r\n\tprof->Activate();\r\n}\r\n\r\n\/\/ static\r\nvoid Profiler::Attach(AMX *amx, const DebugInfo &debug_info) {\r\n\tAttach(amx);\r\n\tGet(amx)->SetDebugInfo(debug_info);\r\n}\r\n\r\n\/\/ static\r\nvoid Profiler::Detach(AMX *amx) {\r\n\tProfiler *prof = Profiler::Get(amx);\r\n\tif (prof != 0) {\r\n\t\tprof->Deactivate();\r\n\t\tdelete prof;\r\n\t}\r\n\tinstances_.erase(amx);\r\n}\r\n\r\n\/\/ static\r\nProfiler *Profiler::Get(AMX *amx) {\r\n\tstd::map<AMX*, Profiler*>::iterator it = instances_.find(amx);\r\n\tif (it != instances_.end()) {\r\n\t\treturn it->second;\r\n\t}\r\n\treturn 0;\r\n}\r\n\r\nProfiler::Profiler(AMX *amx) \r\n\t: active_(false)\r\n\t, amx_(amx)\r\n\t, debug_(amx->debug)\r\n{\r\n\t\/\/ Since PrintStats is done in AmxUnload and amx->base is already freed before\r\n\t\/\/ AmxUnload gets called, therefore both native and public tables are not accessible, \r\n\t\/\/ from there, so they must be stored separately in some global place.\r\n\tAMX_HEADER *hdr = reinterpret_cast<AMX_HEADER*>(amx->base);\r\n\tAMX_FUNCSTUBNT *publics = reinterpret_cast<AMX_FUNCSTUBNT*>(amx->base + hdr->publics);\r\n\tAMX_FUNCSTUBNT *natives = reinterpret_cast<AMX_FUNCSTUBNT*>(amx->base + hdr->natives);\r\n\tint num_publics;\r\n\tamx_NumPublics(amx_, &num_publics);\r\n\tfor (int i = 0; i < num_publics; i++) {\r\n\t\tpublic_names_.push_back(reinterpret_cast<char*>(amx->base + publics[i].nameofs));\r\n\t}\r\n\tint num_natives;\r\n\tamx_NumNatives(amx_, &num_natives);\r\n\tfor (int i = 0; i < num_natives; i++) {\r\n\t\tnative_names_.push_back(reinterpret_cast<char*>(amx->base + natives[i].nameofs));\r\n\t}\r\n}\r\n\r\nvoid Profiler::SetDebugInfo(const DebugInfo &info) {\r\n\tdebug_info_ = info;\r\n}\r\n\r\nvoid Profiler::Activate() {\r\n\tif (!active_) {\r\n\t\tactive_ = true;\r\n\t\tamx_SetDebugHook(amx_, ::Debug);\r\n\t}\r\n}\r\n\r\nbool Profiler::IsActive() const {\r\n\treturn active_;\r\n}\r\n\r\nvoid Profiler::Deactivate() {\r\n\tif (active_) {\r\n\t\tactive_ = false;\r\n\t\tamx_SetDebugHook(amx_, debug_);\r\n\t}\r\n}\r\n\r\nvoid Profiler::ResetStats() {\r\n\tfunctions_.clear();\r\n}\r\n\r\nvoid Profiler::PrintStats(std::ostream &stream, AbstractPrinter *printer) const {\r\n\tProfile profile;\r\n\r\n\tfor (std::set<Function>::const_iterator iterator = functions_.begin(); \r\n\t\t\titerator != functions_.end(); ++iterator) \r\n\t{\r\n\t\tstd::string name;\r\n\t\tstd::string type;\r\n\r\n\t\tswitch (iterator->type()) {\r\n\t\tcase Function::NATIVE: {\r\n\t\t\tname = native_names_[iterator->index()];\r\n\t\t\ttype = \"native\";\r\n\t\t\tbreak;\r\n\t\t}\r\n\t\tcase Function::PUBLIC: {\r\n\t\t\tif (iterator->index() >= 0) {\r\n\t\t\t\tname = public_names_[iterator->index()];\r\n\t\t\t\ttype = \"public\";\r\n\t\t\t} else if (iterator->index() == AMX_EXEC_MAIN) {\r\n\t\t\t\tname = \"main\";\r\n\t\t\t\ttype = \"main\";\r\n\t\t\t}\t\r\n\t\t\tbreak;\r\n\t\t}\r\n\t\tcase Function::NORMAL: {\r\n\t\t\ttype = \"normal\";\r\n\t\t\tbool name_found = false;\r\n\t\t\tif (debug_info_.IsLoaded()) {\r\n\t\t\t\tname = debug_info_.GetFunction(iterator->address());\r\n\t\t\t\tif (!name.empty()) {\t\t\t\t\t\t\t\r\n\t\t\t\t\tname_found = true;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tif (!name_found) {\r\n\t\t\t\tstd::stringstream ss;\r\n\t\t\t\tss << \"unknown@0x\" << std::hex << iterator->address();\r\n\t\t\t\tss >> name;\r\n\t\t\t}\t\t\t\t\r\n\t\t\tbreak;\r\n\t\t}\r\n\t\tdefault:\r\n\t\t\tassert(0 && \"Invalid function type\");\r\n\t\t} \r\n\r\n\t\tprofile.push_back(ProfileEntry(name, type, iterator->time(), iterator->child_time(), \r\n\t\t\t\titerator->num_calls()));\r\n\t}\r\n\r\n\tprinter->Print(stream, profile);\r\n}\r\n\r\nint Profiler::Debug() {\r\n\tcell prevFrame = amx_->stp;\r\n\tif (!call_stack_.IsEmpty()) {\r\n\t\tprevFrame = call_stack_.GetTop().frame();\r\n\t}\r\n\r\n\tif (amx_->frm < prevFrame) {\r\n\t\tcell address = amx_->cip - 2*sizeof(cell); \r\n\t\tstd::string name = debug_info_.GetFunction(address);\r\n\t\tif (call_stack_.GetTop().frame() != amx_->frm) {\r\n\t\t\tEnterFunction(CallInfo(Function::Normal(address), amx_->frm));\r\n\t\t}\r\n\t} else if (amx_->frm > prevFrame) {\r\n\t\tFunction top_fn = call_stack_.GetTop().function();\r\n\t\tif (top_fn.type() == Function::NORMAL) {\r\n\t\t\tLeaveFunction(top_fn);\r\n\t\t}\r\n\t}\r\n\r\n\tif (debug_ != 0) {\r\n\t\treturn debug_(amx_);\r\n\t} \r\n\treturn AMX_ERR_NONE; \r\n}\r\n\r\nint Profiler::Callback(cell index, cell *result, cell *params) {\r\n\tEnterFunction(CallInfo(Function::Native(index), amx_->frm));\r\n\tint error = amx_Callback(amx_, index, result, params);\r\n\tLeaveFunction(Function::Native(index));\r\n\treturn error;\r\n}\r\n\r\nint Profiler::Exec(cell *retval, int index) {\t\r\n\tif (index >= 0 || index == AMX_EXEC_MAIN) {\t\t\r\n\t\tAMX_HEADER *hdr = reinterpret_cast<AMX_HEADER*>(amx_->base);\r\n\t\tcell address = 0;\r\n\t\tif (index == AMX_EXEC_MAIN) {\r\n\t\t\taddress = hdr->cip;\r\n\t\t} else {\r\n\t\t\tAMX_FUNCSTUBNT *publics = reinterpret_cast<AMX_FUNCSTUBNT*>(amx_->base + hdr->publics);\r\n\t\t\taddress = publics[index].address;\r\n\t\t} \r\n\t\tEnterFunction(CallInfo(Function::Public(index), \r\n\t\t\tamx_->stk - 3*sizeof(cell)));\r\n\t\t\/\/ Why 3?\r\n\t\t\/\/ - one for parameter count (amx->paramcount)\r\n\t\t\/\/ - another is zero return address\r\n\t\t\/\/ - stk is the third, pushed by PROC opcode\r\n\t\tint error = amx_Exec(amx_, retval, index);\r\n\t\tLeaveFunction(Function::Public(index));\r\n\t\treturn error;\r\n\t} else {\r\n\t\treturn amx_Exec(amx_, retval, index);\r\n\t}\r\n}\r\n\r\nvoid Profiler::EnterFunction(const CallInfo &call) {\r\n\tcall_stack_.Push(call);\r\n\tstd::set<Function>::iterator iterator = functions_.find(call.function());\r\n\tif (iterator == functions_.end()) {\r\n\t\tFunction f = call.function();\r\n\t\tf.IncreaseCalls();\r\n\t\tfunctions_.insert(f);\r\n\t} else {\r\n\t\titerator->IncreaseCalls();\r\n\t}\r\n}\r\n\r\nvoid Profiler::LeaveFunction(const Function &function) {\r\n\twhile (true) {\r\n\t\tCallInfo current = call_stack_.Pop();\r\n\t\tstd::set<Function>::iterator current_it = functions_.find(current.function());\r\n\t\tif (current_it != functions_.end()) {\r\n\t\t\tcurrent_it->AdjustTime(current.timer().total_time());\r\n\t\t}\r\n\t\tif (!call_stack_.IsEmpty()) {\r\n\t\t\t\/\/ Adjust caller's child_time\r\n\t\t\tCallInfo top = call_stack_.GetTop();\r\n\t\t\tstd::set<Function>::iterator top_it = functions_.find(top.function());\r\n\t\t\tif (top_it != functions_.end()) {\r\n\t\t\t\ttop_it->AdjustChildTime(current.timer().total_time());\r\n\t\t\t}\r\n\t\t}\r\n\t\tif (current.function() == function) {\r\n\t\t\tbreak;\r\n\t\t}\r\n\t}\r\n}\r\n\r\n} \/\/ namespace samp_profiler\r\n<commit_msg>Delete a forgotten line of code used to debug Profielr::Debug<commit_after>\/\/ SA:MP Profiler plugin\r\n\/\/\r\n\/\/ Copyright (c) 2011 Zeex\r\n\/\/\r\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\r\n\/\/ you may not use this file except in compliance with the License.\r\n\/\/ You may obtain a copy of the License at\r\n\/\/\r\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\r\n\/\/\r\n\/\/ Unless required by applicable law or agreed to in writing, software\r\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\r\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n\/\/ See the License for the specific language governing permissions and\r\n\/\/ limitations under the License.\r\n\r\n#include <algorithm>\r\n#include <cassert>\r\n#include <map>\r\n#include <numeric>\r\n#include <sstream>\r\n#include <string>\r\n\r\n#include \"abstract_printer.h\"\r\n#include \"function.h\"\r\n#include \"profile.h\"\r\n#include \"profiler.h\"\r\n\r\n#include \"amx\/amx.h\"\r\n#include \"amx\/amxdbg.h\"\r\n\r\nnamespace {\r\n\r\nint AMXAPI Debug(AMX *amx) {\r\n\treturn samp_profiler::Profiler::Get(amx)->Debug();\r\n}\r\n\r\n\/\/ Reads from a code section at a given location.\r\ninline cell ReadAmxCode(AMX *amx, cell where) {\r\n\tAMX_HEADER *hdr = reinterpret_cast<AMX_HEADER*>(amx->base);\r\n\treturn *reinterpret_cast<cell*>(amx->base + hdr->cod + where);\r\n}\r\n\r\n} \/\/ anonymous namespace\r\n\r\nnamespace samp_profiler {\r\n\r\n\/\/ statics\r\nstd::map<AMX*, Profiler*> Profiler::instances_;\r\n\r\nProfiler::Profiler() {}\r\n\r\nbool Profiler::IsScriptProfilable(AMX *amx) {\r\n\tuint16_t flags;\r\n\tamx_Flags(amx, &flags);\r\n\r\n\tif ((flags & AMX_FLAG_DEBUG) != 0) {\r\n\t\treturn true;\r\n\t}\r\n\r\n\tif ((flags & AMX_FLAG_NOCHECKS) == 0) {\r\n\t\treturn true;\r\n\t}\r\n\r\n\treturn false;\r\n}\r\n\r\n\/\/ static\r\nvoid Profiler::Attach(AMX *amx) {\r\n\tProfiler *prof = new Profiler(amx);\r\n\tinstances_[amx] = prof;\r\n\tprof->Activate();\r\n}\r\n\r\n\/\/ static\r\nvoid Profiler::Attach(AMX *amx, const DebugInfo &debug_info) {\r\n\tAttach(amx);\r\n\tGet(amx)->SetDebugInfo(debug_info);\r\n}\r\n\r\n\/\/ static\r\nvoid Profiler::Detach(AMX *amx) {\r\n\tProfiler *prof = Profiler::Get(amx);\r\n\tif (prof != 0) {\r\n\t\tprof->Deactivate();\r\n\t\tdelete prof;\r\n\t}\r\n\tinstances_.erase(amx);\r\n}\r\n\r\n\/\/ static\r\nProfiler *Profiler::Get(AMX *amx) {\r\n\tstd::map<AMX*, Profiler*>::iterator it = instances_.find(amx);\r\n\tif (it != instances_.end()) {\r\n\t\treturn it->second;\r\n\t}\r\n\treturn 0;\r\n}\r\n\r\nProfiler::Profiler(AMX *amx) \r\n\t: active_(false)\r\n\t, amx_(amx)\r\n\t, debug_(amx->debug)\r\n{\r\n\t\/\/ Since PrintStats is done in AmxUnload and amx->base is already freed before\r\n\t\/\/ AmxUnload gets called, therefore both native and public tables are not accessible, \r\n\t\/\/ from there, so they must be stored separately in some global place.\r\n\tAMX_HEADER *hdr = reinterpret_cast<AMX_HEADER*>(amx->base);\r\n\tAMX_FUNCSTUBNT *publics = reinterpret_cast<AMX_FUNCSTUBNT*>(amx->base + hdr->publics);\r\n\tAMX_FUNCSTUBNT *natives = reinterpret_cast<AMX_FUNCSTUBNT*>(amx->base + hdr->natives);\r\n\tint num_publics;\r\n\tamx_NumPublics(amx_, &num_publics);\r\n\tfor (int i = 0; i < num_publics; i++) {\r\n\t\tpublic_names_.push_back(reinterpret_cast<char*>(amx->base + publics[i].nameofs));\r\n\t}\r\n\tint num_natives;\r\n\tamx_NumNatives(amx_, &num_natives);\r\n\tfor (int i = 0; i < num_natives; i++) {\r\n\t\tnative_names_.push_back(reinterpret_cast<char*>(amx->base + natives[i].nameofs));\r\n\t}\r\n}\r\n\r\nvoid Profiler::SetDebugInfo(const DebugInfo &info) {\r\n\tdebug_info_ = info;\r\n}\r\n\r\nvoid Profiler::Activate() {\r\n\tif (!active_) {\r\n\t\tactive_ = true;\r\n\t\tamx_SetDebugHook(amx_, ::Debug);\r\n\t}\r\n}\r\n\r\nbool Profiler::IsActive() const {\r\n\treturn active_;\r\n}\r\n\r\nvoid Profiler::Deactivate() {\r\n\tif (active_) {\r\n\t\tactive_ = false;\r\n\t\tamx_SetDebugHook(amx_, debug_);\r\n\t}\r\n}\r\n\r\nvoid Profiler::ResetStats() {\r\n\tfunctions_.clear();\r\n}\r\n\r\nvoid Profiler::PrintStats(std::ostream &stream, AbstractPrinter *printer) const {\r\n\tProfile profile;\r\n\r\n\tfor (std::set<Function>::const_iterator iterator = functions_.begin(); \r\n\t\t\titerator != functions_.end(); ++iterator) \r\n\t{\r\n\t\tstd::string name;\r\n\t\tstd::string type;\r\n\r\n\t\tswitch (iterator->type()) {\r\n\t\tcase Function::NATIVE: {\r\n\t\t\tname = native_names_[iterator->index()];\r\n\t\t\ttype = \"native\";\r\n\t\t\tbreak;\r\n\t\t}\r\n\t\tcase Function::PUBLIC: {\r\n\t\t\tif (iterator->index() >= 0) {\r\n\t\t\t\tname = public_names_[iterator->index()];\r\n\t\t\t\ttype = \"public\";\r\n\t\t\t} else if (iterator->index() == AMX_EXEC_MAIN) {\r\n\t\t\t\tname = \"main\";\r\n\t\t\t\ttype = \"main\";\r\n\t\t\t}\t\r\n\t\t\tbreak;\r\n\t\t}\r\n\t\tcase Function::NORMAL: {\r\n\t\t\ttype = \"normal\";\r\n\t\t\tbool name_found = false;\r\n\t\t\tif (debug_info_.IsLoaded()) {\r\n\t\t\t\tname = debug_info_.GetFunction(iterator->address());\r\n\t\t\t\tif (!name.empty()) {\t\t\t\t\t\t\t\r\n\t\t\t\t\tname_found = true;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tif (!name_found) {\r\n\t\t\t\tstd::stringstream ss;\r\n\t\t\t\tss << \"unknown@0x\" << std::hex << iterator->address();\r\n\t\t\t\tss >> name;\r\n\t\t\t}\t\t\t\t\r\n\t\t\tbreak;\r\n\t\t}\r\n\t\tdefault:\r\n\t\t\tassert(0 && \"Invalid function type\");\r\n\t\t} \r\n\r\n\t\tprofile.push_back(ProfileEntry(name, type, iterator->time(), iterator->child_time(), \r\n\t\t\t\titerator->num_calls()));\r\n\t}\r\n\r\n\tprinter->Print(stream, profile);\r\n}\r\n\r\nint Profiler::Debug() {\r\n\tcell prevFrame = amx_->stp;\r\n\tif (!call_stack_.IsEmpty()) {\r\n\t\tprevFrame = call_stack_.GetTop().frame();\r\n\t}\r\n\r\n\tif (amx_->frm < prevFrame) {\r\n\t\tcell address = amx_->cip - 2*sizeof(cell); \r\n\t\tif (call_stack_.GetTop().frame() != amx_->frm) {\r\n\t\t\tEnterFunction(CallInfo(Function::Normal(address), amx_->frm));\r\n\t\t}\r\n\t} else if (amx_->frm > prevFrame) {\r\n\t\tFunction top_fn = call_stack_.GetTop().function();\r\n\t\tif (top_fn.type() == Function::NORMAL) {\r\n\t\t\tLeaveFunction(top_fn);\r\n\t\t}\r\n\t}\r\n\r\n\tif (debug_ != 0) {\r\n\t\treturn debug_(amx_);\r\n\t} \r\n\treturn AMX_ERR_NONE; \r\n}\r\n\r\nint Profiler::Callback(cell index, cell *result, cell *params) {\r\n\tEnterFunction(CallInfo(Function::Native(index), amx_->frm));\r\n\tint error = amx_Callback(amx_, index, result, params);\r\n\tLeaveFunction(Function::Native(index));\r\n\treturn error;\r\n}\r\n\r\nint Profiler::Exec(cell *retval, int index) {\t\r\n\tif (index >= 0 || index == AMX_EXEC_MAIN) {\t\t\r\n\t\tAMX_HEADER *hdr = reinterpret_cast<AMX_HEADER*>(amx_->base);\r\n\t\tcell address = 0;\r\n\t\tif (index == AMX_EXEC_MAIN) {\r\n\t\t\taddress = hdr->cip;\r\n\t\t} else {\r\n\t\t\tAMX_FUNCSTUBNT *publics = reinterpret_cast<AMX_FUNCSTUBNT*>(amx_->base + hdr->publics);\r\n\t\t\taddress = publics[index].address;\r\n\t\t} \r\n\t\tEnterFunction(CallInfo(Function::Public(index), \r\n\t\t\tamx_->stk - 3*sizeof(cell)));\r\n\t\t\/\/ Why 3?\r\n\t\t\/\/ - one for parameter count (amx->paramcount)\r\n\t\t\/\/ - another is zero return address\r\n\t\t\/\/ - stk is the third, pushed by PROC opcode\r\n\t\tint error = amx_Exec(amx_, retval, index);\r\n\t\tLeaveFunction(Function::Public(index));\r\n\t\treturn error;\r\n\t} else {\r\n\t\treturn amx_Exec(amx_, retval, index);\r\n\t}\r\n}\r\n\r\nvoid Profiler::EnterFunction(const CallInfo &call) {\r\n\tcall_stack_.Push(call);\r\n\tstd::set<Function>::iterator iterator = functions_.find(call.function());\r\n\tif (iterator == functions_.end()) {\r\n\t\tFunction f = call.function();\r\n\t\tf.IncreaseCalls();\r\n\t\tfunctions_.insert(f);\r\n\t} else {\r\n\t\titerator->IncreaseCalls();\r\n\t}\r\n}\r\n\r\nvoid Profiler::LeaveFunction(const Function &function) {\r\n\twhile (true) {\r\n\t\tCallInfo current = call_stack_.Pop();\r\n\t\tstd::set<Function>::iterator current_it = functions_.find(current.function());\r\n\t\tif (current_it != functions_.end()) {\r\n\t\t\tcurrent_it->AdjustTime(current.timer().total_time());\r\n\t\t}\r\n\t\tif (!call_stack_.IsEmpty()) {\r\n\t\t\t\/\/ Adjust caller's child_time\r\n\t\t\tCallInfo top = call_stack_.GetTop();\r\n\t\t\tstd::set<Function>::iterator top_it = functions_.find(top.function());\r\n\t\t\tif (top_it != functions_.end()) {\r\n\t\t\t\ttop_it->AdjustChildTime(current.timer().total_time());\r\n\t\t\t}\r\n\t\t}\r\n\t\tif (current.function() == function) {\r\n\t\t\tbreak;\r\n\t\t}\r\n\t}\r\n}\r\n\r\n} \/\/ namespace samp_profiler\r\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2010-2012 RethinkDB, all rights reserved.\n\n#include <time.h>\n\n#include <string>\n\n#include \"errors.hpp\"\n#include <boost\/bind.hpp>\n\n#include \"debug.hpp\"\n#include \"arch\/runtime\/thread_pool.hpp\" \/* for `run_in_blocker_pool()` *\/\n#include \"containers\/archive\/file_stream.hpp\"\n#include \"http\/file_app.hpp\"\n#include \"logger.hpp\"\n#include \"stl_utils.hpp\"\n#include \"time.hpp\"\n#include \"http\/web_assets.hpp\"\n\nfile_http_app_t::file_http_app_t(std::string _asset_dir)\n : asset_dir(_asset_dir)\n{ }\n\nbool ends_with(const std::string& str, const std::string& end) {\n return str.rfind(end) == str.length() - end.length();\n}\n\nvoid file_http_app_t::handle(const http_req_t &req, http_res_t *result, signal_t *) {\n if (req.method != GET) {\n *result = http_res_t(HTTP_METHOD_NOT_ALLOWED);\n return;\n }\n\n std::string resource(req.resource.as_string());\n\n std::string filename;\n\n if (resource == \"\/\" || resource == \"\") {\n filename = \"\/index.html\";\n } else {\n filename = resource;\n }\n\n std::pair<const char *, size_t> resource_data;\n try {\n resource_data = static_web_assets.at(filename);\n } catch (std::out_of_range) {\n printf_buffer_t resource_buffer;\n debug_print_quoted_string(&resource_buffer,\n reinterpret_cast<const uint8_t *>(resource.data()),\n resource.length());\n logNTC(\"Someone asked for the nonwhitelisted file %s. If this should be \"\n \"accessible, add it to the static web assets.\", resource_buffer.c_str());\n *result = http_res_t(HTTP_FORBIDDEN);\n return;\n }\n\n time_t expires;\n#ifndef NDEBUG\n \/\/ In debug mode, do not cache static web assets\n expires = get_secs() - 31536000; \/\/ Some time in the past (one year ago)\n#else\n \/\/ In release mode, cache static web assets except index.html\n if (filename == \"\/index.html\") {\n expires = get_secs() - 31536000; \/\/ Some time in the past (one year ago)\n } else {\n expires = get_secs() + 31536000; \/\/ One year from now\n }\n#endif\n result->add_header_line(\"Expires\", http_format_date(expires));\n\n \/\/ TODO more robust mimetype detection?\n std::string mimetype = \"text\/plain\";\n if (ends_with(filename, \".js\")) {\n mimetype = \"text\/javascript\";\n } else if (ends_with(filename, \".css\")) {\n mimetype = \"text\/css\";\n } else if (ends_with(filename, \".html\")) {\n mimetype = \"text\/html\";\n } else if (ends_with(filename, \".woff\")) {\n mimetype = \"application\/font-woff\";\n } else if (ends_with(filename, \".eot\")) {\n mimetype = \"application\/vnd.ms-fontobject\";\n } else if (ends_with(filename, \".ttf\")) {\n mimetype = \"application\/x-font-ttf\";\n } else if (ends_with(filename, \".svg\")) {\n mimetype = \"image\/svg+xml\";\n } else if (ends_with(filename, \".ico\")) {\n mimetype = \"image\/vnd.microsoft.icon\";\n } else if (ends_with(filename, \".png\")) {\n mimetype = \"image\/png\";\n } else if (ends_with(filename, \".gif\")) {\n mimetype = \"image\/gif\";\n }\n result->add_header_line(\"Content-Type\", mimetype);\n\n if (asset_dir.empty()) {\n result->body.assign(resource_data.first, resource_data.second);\n result->code = 200;\n } else {\n thread_pool_t::run_in_blocker_pool(boost::bind(&file_http_app_t::handle_blocking, this, filename, result));\n\n if (result->code == 404) {\n logNTC(\"File %s was requested and is on the whitelist but we didn't find it in the directory.\", (asset_dir + filename).c_str());\n }\n }\n}\n\nvoid file_http_app_t::handle_blocking(std::string filename, http_res_t *res_out) {\n\n \/\/ FIXME: make sure that we won't walk out of our sandbox! Check symbolic links, etc.\n blocking_read_file_stream_t stream;\n bool initialized = stream.init((asset_dir + filename).c_str());\n\n if (!initialized) {\n res_out->code = 404;\n return;\n }\n\n std::vector<char> body;\n\n for (;;) {\n const int bufsize = 4096;\n char buf[bufsize];\n int64_t res = stream.read(buf, bufsize);\n\n if (res > 0) {\n body.insert(body.end(), buf, buf + res);\n } else if (res == 0) {\n break;\n } else {\n res_out->code = 500;\n return;\n }\n }\n\n res_out->body.assign(body.begin(), body.end());\n res_out->code = 200;\n}\n<commit_msg>use map::find instead of map::at<commit_after>\/\/ Copyright 2010-2012 RethinkDB, all rights reserved.\n\n#include <time.h>\n\n#include <string>\n\n#include \"errors.hpp\"\n#include <boost\/bind.hpp>\n\n#include \"debug.hpp\"\n#include \"arch\/runtime\/thread_pool.hpp\" \/* for `run_in_blocker_pool()` *\/\n#include \"containers\/archive\/file_stream.hpp\"\n#include \"http\/file_app.hpp\"\n#include \"logger.hpp\"\n#include \"stl_utils.hpp\"\n#include \"time.hpp\"\n#include \"http\/web_assets.hpp\"\n\nfile_http_app_t::file_http_app_t(std::string _asset_dir)\n : asset_dir(_asset_dir)\n{ }\n\nbool ends_with(const std::string& str, const std::string& end) {\n return str.rfind(end) == str.length() - end.length();\n}\n\nvoid file_http_app_t::handle(const http_req_t &req, http_res_t *result, signal_t *) {\n if (req.method != GET) {\n *result = http_res_t(HTTP_METHOD_NOT_ALLOWED);\n return;\n }\n\n std::string resource(req.resource.as_string());\n\n std::string filename;\n\n if (resource == \"\/\" || resource == \"\") {\n filename = \"\/index.html\";\n } else {\n filename = resource;\n }\n\n auto it = static_web_assets.find(filename);\n if (it == static_web_assets.end()) {\n printf_buffer_t resource_buffer;\n debug_print_quoted_string(&resource_buffer,\n reinterpret_cast<const uint8_t *>(resource.data()),\n resource.length());\n logNTC(\"Someone asked for the nonwhitelisted file %s. If this should be \"\n \"accessible, add it to the static web assets.\", resource_buffer.c_str());\n *result = http_res_t(HTTP_FORBIDDEN);\n return;\n }\n\n const std::pair<const char *, size_t> &resource_data = it->second;\n\n time_t expires;\n#ifndef NDEBUG\n \/\/ In debug mode, do not cache static web assets\n expires = get_secs() - 31536000; \/\/ Some time in the past (one year ago)\n#else\n \/\/ In release mode, cache static web assets except index.html\n if (filename == \"\/index.html\") {\n expires = get_secs() - 31536000; \/\/ Some time in the past (one year ago)\n } else {\n expires = get_secs() + 31536000; \/\/ One year from now\n }\n#endif\n result->add_header_line(\"Expires\", http_format_date(expires));\n\n \/\/ TODO more robust mimetype detection?\n std::string mimetype = \"text\/plain\";\n if (ends_with(filename, \".js\")) {\n mimetype = \"text\/javascript\";\n } else if (ends_with(filename, \".css\")) {\n mimetype = \"text\/css\";\n } else if (ends_with(filename, \".html\")) {\n mimetype = \"text\/html\";\n } else if (ends_with(filename, \".woff\")) {\n mimetype = \"application\/font-woff\";\n } else if (ends_with(filename, \".eot\")) {\n mimetype = \"application\/vnd.ms-fontobject\";\n } else if (ends_with(filename, \".ttf\")) {\n mimetype = \"application\/x-font-ttf\";\n } else if (ends_with(filename, \".svg\")) {\n mimetype = \"image\/svg+xml\";\n } else if (ends_with(filename, \".ico\")) {\n mimetype = \"image\/vnd.microsoft.icon\";\n } else if (ends_with(filename, \".png\")) {\n mimetype = \"image\/png\";\n } else if (ends_with(filename, \".gif\")) {\n mimetype = \"image\/gif\";\n }\n result->add_header_line(\"Content-Type\", mimetype);\n\n if (asset_dir.empty()) {\n result->body.assign(resource_data.first, resource_data.second);\n result->code = 200;\n } else {\n thread_pool_t::run_in_blocker_pool(boost::bind(&file_http_app_t::handle_blocking, this, filename, result));\n\n if (result->code == 404) {\n logNTC(\"File %s was requested and is on the whitelist but we didn't find it in the directory.\", (asset_dir + filename).c_str());\n }\n }\n}\n\nvoid file_http_app_t::handle_blocking(std::string filename, http_res_t *res_out) {\n\n \/\/ FIXME: make sure that we won't walk out of our sandbox! Check symbolic links, etc.\n blocking_read_file_stream_t stream;\n bool initialized = stream.init((asset_dir + filename).c_str());\n\n if (!initialized) {\n res_out->code = 404;\n return;\n }\n\n std::vector<char> body;\n\n for (;;) {\n const int bufsize = 4096;\n char buf[bufsize];\n int64_t res = stream.read(buf, bufsize);\n\n if (res > 0) {\n body.insert(body.end(), buf, buf + res);\n } else if (res == 0) {\n break;\n } else {\n res_out->code = 500;\n return;\n }\n }\n\n res_out->body.assign(body.begin(), body.end());\n res_out->code = 200;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"eteditor.h\"\n\nvoid eteditor::setetype(etype* e) {\n entitytype=e;\n}\n\nvoid eteditor::setfont(font* fontset) {\n f=fontset;\n}\n\nvoid eteditor::setrenderer(SDL_Renderer* renderer) {\n r=renderer;\n}\n\nvoid eteditor::draw() {\n f->drawf(256,256,{255,255,255,255},0,0,\"%d\",(entitytype==NULL));\n if (entitytype!=NULL) {\n f->draw(w-128, offY+2, color[0], 1, 0, false, \"Events\");\n SDL_RenderDrawLine(r, w, offY+20, w-256, offY+20);\n SDL_RenderDrawLine(r, w-256, offY, w-256, h);\n }\n}\n\nvoid eteditor::setcolor(int colindex, SDL_Color colcol) {\n color[colindex]=colcol;\n}\n\neteditor::eteditor() {\n entitytype=NULL;\n}<commit_msg>event editor buttons layout<commit_after>#include \"eteditor.h\"\n\nvoid eteditor::setetype(etype* e) {\n entitytype=e;\n}\n\nvoid eteditor::setfont(font* fontset) {\n f=fontset;\n}\n\nvoid eteditor::setrenderer(SDL_Renderer* renderer) {\n r=renderer;\n}\n\nvoid eteditor::draw() {\n f->drawf(256,256,{255,255,255,255},0,0,\"%d\",(entitytype==NULL));\n if (entitytype!=NULL) {\n f->draw(w-128, offY+2, color[0], 1, 0, false, \"Events\");\n SDL_RenderDrawLine(r, w, offY+20, w-256, offY+20);\n SDL_RenderDrawLine(r, w, offY+40, w-256, offY+40);\n SDL_RenderDrawLine(r, w-256, offY, w-256, h);\n \n SDL_RenderDrawLine(r, w-85, offY+20, w-85, offY+40);\n SDL_RenderDrawLine(r, w-171, offY+20, w-171, offY+40);\n \n f->draw(w-214, offY+22, color[0], 1, 0, 0, \"Add\");\n f->draw(w-128, offY+22, color[0], 1, 0, 0, \"Change\");\n f->draw(w-43, offY+22, color[0], 1, 0, 0, \"Remove\");\n }\n}\n\nvoid eteditor::setcolor(int colindex, SDL_Color colcol) {\n color[colindex]=colcol;\n}\n\neteditor::eteditor() {\n entitytype=NULL;\n}<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n#include <ctime>\n\n#include \"search.hpp\"\n#include \"movegen.hpp\"\n#include \"perft.hpp\"\n#include \"rollout.hpp\"\n#include \"eval.hpp\"\n#include \"makemove.hpp\"\n#include \"score.hpp\"\n#include \"other.hpp\"\n\nvoid messageLoop()\n{\n Position pos;\n setBoard(pos, \"startpos\");\n\n Hashtable tt;\n tableInit(&tt);\n create(&tt, 128);\n\n bool quit = false;\n while(quit == false)\n {\n std::string input;\n getline(std::cin, input);\n\n std::vector<std::string> tokens = split(input, ' ');\n\n for(unsigned int n = 0; n < tokens.size(); ++n)\n {\n if(tokens[n] == \"isready\")\n {\n std::cout << \"readyok\" << std::endl;\n }\n else if(tokens[n] == \"go\")\n {\n \/\/ Default subcommands\n int depth = 5;\n int movetime = 0;\n\n \/\/ Subcommands\n for(unsigned int i = n+1; i < tokens.size(); ++i)\n {\n if(tokens[i] == \"infinite\")\n {\n depth = 20;\n n += 1;\n }\n else if(tokens[i] == \"depth\")\n {\n depth = stoi(tokens[i+1]);\n movetime = 0;\n n += 2;\n i += 1;\n }\n else if(tokens[i] == \"movetime\")\n {\n depth = 0;\n movetime = stoi(tokens[i+1]);\n n += 2;\n i += 1;\n }\n }\n\n search(&tt, pos, depth, movetime);\n }\n else if(tokens[n] == \"mcts\")\n {\n \/\/ Default subcommands\n int numSimulations = 100000;\n int movetime = 0;\n int searchType = 1;\n\n \/\/ Subcommands\n for(unsigned int i = n+1; i < tokens.size(); ++i)\n {\n if(tokens[i] == \"pure\")\n {\n searchType = 0;\n n += 1;\n }\n else if(tokens[i] == \"uct\")\n {\n searchType = 1;\n n += 1;\n }\n else if(tokens[i] == \"movetime\")\n {\n numSimulations = 0;\n movetime = stoi(tokens[i+1]);\n n += 2;\n i += 1;\n }\n else if(tokens[i] == \"simulations\")\n {\n numSimulations = stoi(tokens[i+1]);\n movetime = 0;\n n += 2;\n i += 1;\n }\n }\n\n if(searchType == 0)\n {\n mctsPure(pos, numSimulations, movetime);\n }\n else if(searchType == 1)\n {\n mctsUct(pos, numSimulations, movetime);\n }\n }\n else if(tokens[n] == \"perft\")\n {\n int depth = 5;\n\n \/\/ Subcommands\n if(n+1 < tokens.size())\n {\n depth = stoi(tokens[n+1]);\n n += 1;\n }\n\n \/\/ Subcommand checking\n if(depth < 1)\n {\n depth = 1;\n }\n else if(depth > 12)\n {\n std::cout << \"WARNING: perft(\" << depth << \") may take a long time to finish\" << std::endl;\n }\n\n perft(&tt, pos, depth);\n }\n else if(tokens[n] == \"result\")\n {\n Move moves[256];\n int numMoves = movegen(pos, moves);\n\n if(numMoves > 0)\n {\n std::cout << \"result none\" << std::endl;\n }\n else\n {\n int r = score(pos);\n\n if(r == 0) {std::cout << \"result draw\" << std::endl; continue;}\n\n if(pos.turn == SIDE::CROSS)\n {\n if(r > 0) {std::cout << \"result X\" << std::endl;}\n else {std::cout << \"result O\" << std::endl;}\n }\n else\n {\n if(r > 0) {std::cout << \"result O\" << std::endl;}\n else {std::cout << \"result X\" << std::endl;}\n }\n }\n }\n else if(tokens[n] == \"split\")\n {\n int depth = 5;\n\n \/\/ Subcommands\n if(n+1 < tokens.size())\n {\n depth = stoi(tokens[n+1]);\n n += 1;\n }\n\n \/\/ Subcommand checking\n if(depth < 1)\n {\n depth = 1;\n }\n else if(depth > 12)\n {\n std::cout << \"WARNING: split perft(\" << depth << \") may take a long time to finish\" << std::endl;\n }\n\n splitPerft(&tt, pos, depth);\n }\n else if(tokens[n] == \"rollout\")\n {\n if(n+1 >= tokens.size()) {continue;}\n\n \/\/ Subcommands\n int numGames = stoi(tokens[n+1]);\n n += 1;\n\n \/\/ Subcommand checking\n if(numGames <= 1)\n {\n numGames = 1;\n }\n\n int wins = 0;\n int losses = 0;\n int draws = 0;\n\n clock_t start = clock();\n for(int g = 0; g < numGames; ++g)\n {\n int r = rollout(pos, 300);\n if(r == 1) {wins++;}\n else if(r == -1) {losses++;}\n else {draws++;}\n\n if((g+1) % 100 == 0)\n {\n std::cout << \"info\"\n << \" wins \" << wins\n << \" draws \" << draws\n << \" losses \" << losses\n << \" winrate \" << 100.0*(double)wins\/(wins + draws + losses) << \"%\"\n << \" time \" << 1000.0*(double)(clock() - start)\/CLOCKS_PER_SEC\n << std::endl;\n }\n }\n\n std::cout << \"winrate \"\n << 100.0*(double)wins\/(wins + draws + losses) << \"%\"\n << std::endl;\n }\n else if(tokens[n] == \"hashtable\")\n {\n if(n+1 >= tokens.size()) {continue;}\n\n if(tokens[n+1] == \"clear\")\n {\n n += 1;\n clear(&tt);\n }\n else if(tokens[n+1] == \"print\")\n {\n n += 1;\n printDetails(&tt);\n }\n }\n else if(tokens[n] == \"print\")\n {\n print(pos);\n }\n else if(tokens[n] == \"setpos\")\n {\n if(n+2 < tokens.size())\n {\n int r = setBoard(pos, tokens[n+1] + \" \" + tokens[n+2]);\n if(r != 0)\n {\n std::cout << \"WARNING: set position error (\" << r << \")\" << std::endl;\n }\n\n n += 2;\n }\n else if(n+1 < tokens.size())\n {\n if(tokens[n+1] != \"startpos\") {tokens[n+1] += \" X\";}\n\n int r = setBoard(pos, tokens[n+1]);\n if(r != 0)\n {\n std::cout << \"WARNING: set position error (\" << r << \")\" << std::endl;\n }\n\n n += 1;\n }\n }\n else if(tokens[n] == \"eval\")\n {\n splitEval(pos);\n }\n else if(tokens[n] == \"movegen\")\n {\n printMoves(pos);\n }\n else if(tokens[n] == \"moves\")\n {\n for(unsigned int i = n+1; i < tokens.size(); ++i)\n {\n if(legalMove(pos, tokens[i]) == false) {break;}\n\n makemove(pos, tokens[i]);\n n += 1;\n }\n }\n else if(tokens[n] == \"help\")\n {\n std::cout << \"Commands:\" << std::endl;\n std::cout << \"-- go [depth] [movetime]\" << std::endl;\n std::cout << \"-- perft [depth]\" << std::endl;\n std::cout << \"-- split [depth]\" << std::endl;\n std::cout << \"-- rollout [games]\" << std::endl;\n std::cout << \"-- hashtable [clear\/print]\" << std::endl;\n std::cout << \"-- print\" << std::endl;\n std::cout << \"-- setpos [position]\" << std::endl;\n std::cout << \"-- eval\" << std::endl;\n std::cout << \"-- movegen\" << std::endl;\n std::cout << \"-- moves [moves]\" << std::endl;\n std::cout << \"-- isready\" << std::endl;\n std::cout << \"-- help\" << std::endl;\n std::cout << \"-- about\" << std::endl;\n std::cout << \"-- quit\" << std::endl;\n }\n else if(tokens[n] == \"about\")\n {\n std::cout << \"An Ataxx engine written in C++\" << std::endl;\n std::cout << \"https:\/\/github.com\/kz04px\/ataxx-engine\" << std::endl;\n }\n else if(tokens[n] == \"quit\")\n {\n quit = true;\n break;\n }\n else\n {\n std::cout << \"Unknown token (\" << tokens[n] << \")\" << std::endl;\n }\n }\n }\n\n clear(&tt);\n tableRemove(&tt);\n}\n<commit_msg>Added \"newgame\" command<commit_after>#include <iostream>\n#include <ctime>\n\n#include \"search.hpp\"\n#include \"movegen.hpp\"\n#include \"perft.hpp\"\n#include \"rollout.hpp\"\n#include \"eval.hpp\"\n#include \"makemove.hpp\"\n#include \"score.hpp\"\n#include \"other.hpp\"\n\nvoid messageLoop()\n{\n Position pos;\n setBoard(pos, \"startpos\");\n\n Hashtable tt;\n tableInit(&tt);\n create(&tt, 128);\n\n bool quit = false;\n while(quit == false)\n {\n std::string input;\n getline(std::cin, input);\n\n std::vector<std::string> tokens = split(input, ' ');\n\n for(unsigned int n = 0; n < tokens.size(); ++n)\n {\n if(tokens[n] == \"isready\")\n {\n std::cout << \"readyok\" << std::endl;\n }\n else if(tokens[n] == \"newgame\")\n {\n setBoard(pos, \"startpos\");\n clear(&tt);\n }\n else if(tokens[n] == \"go\")\n {\n \/\/ Default subcommands\n int depth = 5;\n int movetime = 0;\n\n \/\/ Subcommands\n for(unsigned int i = n+1; i < tokens.size(); ++i)\n {\n if(tokens[i] == \"infinite\")\n {\n depth = 20;\n n += 1;\n }\n else if(tokens[i] == \"depth\")\n {\n depth = stoi(tokens[i+1]);\n movetime = 0;\n n += 2;\n i += 1;\n }\n else if(tokens[i] == \"movetime\")\n {\n depth = 0;\n movetime = stoi(tokens[i+1]);\n n += 2;\n i += 1;\n }\n }\n\n search(&tt, pos, depth, movetime);\n }\n else if(tokens[n] == \"mcts\")\n {\n \/\/ Default subcommands\n int numSimulations = 100000;\n int movetime = 0;\n int searchType = 1;\n\n \/\/ Subcommands\n for(unsigned int i = n+1; i < tokens.size(); ++i)\n {\n if(tokens[i] == \"pure\")\n {\n searchType = 0;\n n += 1;\n }\n else if(tokens[i] == \"uct\")\n {\n searchType = 1;\n n += 1;\n }\n else if(tokens[i] == \"movetime\")\n {\n numSimulations = 0;\n movetime = stoi(tokens[i+1]);\n n += 2;\n i += 1;\n }\n else if(tokens[i] == \"simulations\")\n {\n numSimulations = stoi(tokens[i+1]);\n movetime = 0;\n n += 2;\n i += 1;\n }\n }\n\n if(searchType == 0)\n {\n mctsPure(pos, numSimulations, movetime);\n }\n else if(searchType == 1)\n {\n mctsUct(pos, numSimulations, movetime);\n }\n }\n else if(tokens[n] == \"perft\")\n {\n int depth = 5;\n\n \/\/ Subcommands\n if(n+1 < tokens.size())\n {\n depth = stoi(tokens[n+1]);\n n += 1;\n }\n\n \/\/ Subcommand checking\n if(depth < 1)\n {\n depth = 1;\n }\n else if(depth > 12)\n {\n std::cout << \"WARNING: perft(\" << depth << \") may take a long time to finish\" << std::endl;\n }\n\n perft(&tt, pos, depth);\n }\n else if(tokens[n] == \"result\")\n {\n Move moves[256];\n int numMoves = movegen(pos, moves);\n\n if(numMoves > 0)\n {\n std::cout << \"result none\" << std::endl;\n }\n else\n {\n int r = score(pos);\n\n if(r == 0) {std::cout << \"result draw\" << std::endl; continue;}\n\n if(pos.turn == SIDE::CROSS)\n {\n if(r > 0) {std::cout << \"result X\" << std::endl;}\n else {std::cout << \"result O\" << std::endl;}\n }\n else\n {\n if(r > 0) {std::cout << \"result O\" << std::endl;}\n else {std::cout << \"result X\" << std::endl;}\n }\n }\n }\n else if(tokens[n] == \"split\")\n {\n int depth = 5;\n\n \/\/ Subcommands\n if(n+1 < tokens.size())\n {\n depth = stoi(tokens[n+1]);\n n += 1;\n }\n\n \/\/ Subcommand checking\n if(depth < 1)\n {\n depth = 1;\n }\n else if(depth > 12)\n {\n std::cout << \"WARNING: split perft(\" << depth << \") may take a long time to finish\" << std::endl;\n }\n\n splitPerft(&tt, pos, depth);\n }\n else if(tokens[n] == \"rollout\")\n {\n if(n+1 >= tokens.size()) {continue;}\n\n \/\/ Subcommands\n int numGames = stoi(tokens[n+1]);\n n += 1;\n\n \/\/ Subcommand checking\n if(numGames <= 1)\n {\n numGames = 1;\n }\n\n int wins = 0;\n int losses = 0;\n int draws = 0;\n\n clock_t start = clock();\n for(int g = 0; g < numGames; ++g)\n {\n int r = rollout(pos, 300);\n if(r == 1) {wins++;}\n else if(r == -1) {losses++;}\n else {draws++;}\n\n if((g+1) % 100 == 0)\n {\n std::cout << \"info\"\n << \" wins \" << wins\n << \" draws \" << draws\n << \" losses \" << losses\n << \" winrate \" << 100.0*(double)wins\/(wins + draws + losses) << \"%\"\n << \" time \" << 1000.0*(double)(clock() - start)\/CLOCKS_PER_SEC\n << std::endl;\n }\n }\n\n std::cout << \"winrate \"\n << 100.0*(double)wins\/(wins + draws + losses) << \"%\"\n << std::endl;\n }\n else if(tokens[n] == \"hashtable\")\n {\n if(n+1 >= tokens.size()) {continue;}\n\n if(tokens[n+1] == \"clear\")\n {\n n += 1;\n clear(&tt);\n }\n else if(tokens[n+1] == \"print\")\n {\n n += 1;\n printDetails(&tt);\n }\n }\n else if(tokens[n] == \"print\")\n {\n print(pos);\n }\n else if(tokens[n] == \"setpos\")\n {\n if(n+2 < tokens.size())\n {\n int r = setBoard(pos, tokens[n+1] + \" \" + tokens[n+2]);\n if(r != 0)\n {\n std::cout << \"WARNING: set position error (\" << r << \")\" << std::endl;\n }\n\n n += 2;\n }\n else if(n+1 < tokens.size())\n {\n if(tokens[n+1] != \"startpos\") {tokens[n+1] += \" X\";}\n\n int r = setBoard(pos, tokens[n+1]);\n if(r != 0)\n {\n std::cout << \"WARNING: set position error (\" << r << \")\" << std::endl;\n }\n\n n += 1;\n }\n }\n else if(tokens[n] == \"eval\")\n {\n splitEval(pos);\n }\n else if(tokens[n] == \"movegen\")\n {\n printMoves(pos);\n }\n else if(tokens[n] == \"moves\")\n {\n for(unsigned int i = n+1; i < tokens.size(); ++i)\n {\n if(legalMove(pos, tokens[i]) == false) {break;}\n\n makemove(pos, tokens[i]);\n n += 1;\n }\n }\n else if(tokens[n] == \"help\")\n {\n std::cout << \"Commands:\" << std::endl;\n std::cout << \"-- go [depth] [movetime]\" << std::endl;\n std::cout << \"-- perft [depth]\" << std::endl;\n std::cout << \"-- split [depth]\" << std::endl;\n std::cout << \"-- rollout [games]\" << std::endl;\n std::cout << \"-- hashtable [clear\/print]\" << std::endl;\n std::cout << \"-- print\" << std::endl;\n std::cout << \"-- setpos [position]\" << std::endl;\n std::cout << \"-- eval\" << std::endl;\n std::cout << \"-- movegen\" << std::endl;\n std::cout << \"-- moves [moves]\" << std::endl;\n std::cout << \"-- isready\" << std::endl;\n std::cout << \"-- help\" << std::endl;\n std::cout << \"-- about\" << std::endl;\n std::cout << \"-- quit\" << std::endl;\n }\n else if(tokens[n] == \"about\")\n {\n std::cout << \"An Ataxx engine written in C++\" << std::endl;\n std::cout << \"https:\/\/github.com\/kz04px\/ataxx-engine\" << std::endl;\n }\n else if(tokens[n] == \"quit\")\n {\n quit = true;\n break;\n }\n else\n {\n std::cout << \"Unknown token (\" << tokens[n] << \")\" << std::endl;\n }\n }\n }\n\n clear(&tt);\n tableRemove(&tt);\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2009-2010 Satoshi Nakamoto\n\/\/ Copyright (c) 2009-2012 The Bitcoin developers\n\/\/ Distributed under the MIT\/X11 software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \"protocol.h\"\n#include \"util.h\"\n#include \"netbase.h\"\n\n#ifndef WIN32\n# include <arpa\/inet.h>\n#endif\n\nstatic const char* ppszTypeName[] =\n{\n \"ERROR\",\n \"tx\",\n \"dstx\",\n \"block\",\n \"filtered block\",\n \"tx lock request\",\n \"tx lock vote\",\n \"spork\",\n \"masternode winner\",\n \"unknown\",\n \"unknown\",\n \"unknown\",\n \"unknown\",\n \"unknown\",\n \"unknown\"\n};\n\nCMessageHeader::CMessageHeader()\n{\n memcpy(pchMessageStart, Params().MessageStart(), MESSAGE_START_SIZE);\n memset(pchCommand, 0, sizeof(pchCommand));\n pchCommand[1] = 1;\n nMessageSize = -1;\n nChecksum = 0;\n}\n\nCMessageHeader::CMessageHeader(const char* pszCommand, unsigned int nMessageSizeIn)\n{\n memcpy(pchMessageStart, Params().MessageStart(), MESSAGE_START_SIZE);\n memset(pchCommand, 0, sizeof(pchCommand));\n strncpy(pchCommand, pszCommand, COMMAND_SIZE);\n nMessageSize = nMessageSizeIn;\n nChecksum = 0;\n}\n\nstd::string CMessageHeader::GetCommand() const\n{\n return std::string(pchCommand, pchCommand + strnlen(pchCommand, COMMAND_SIZE));\n}\n\nbool CMessageHeader::IsValid() const\n{\n \/\/ Check start string\n if (memcmp(pchMessageStart, Params().MessageStart(), MESSAGE_START_SIZE) != 0)\n return false;\n\n \/\/ Check the command string for errors\n for (const char* p1 = pchCommand; p1 < pchCommand + COMMAND_SIZE; p1++)\n {\n if (*p1 == 0)\n {\n \/\/ Must be all zeros after the first zero\n for (; p1 < pchCommand + COMMAND_SIZE; p1++)\n if (*p1 != 0)\n return false;\n }\n else if (*p1 < ' ' || *p1 > 0x7E)\n return false;\n }\n\n \/\/ Message size\n if (nMessageSize > MAX_SIZE)\n {\n LogPrintf(\"CMessageHeader::IsValid() : (%s, %u bytes) nMessageSize > MAX_SIZE\\n\", GetCommand(), nMessageSize);\n return false;\n }\n\n return true;\n}\n\n\n\nCAddress::CAddress() : CService()\n{\n Init();\n}\n\nCAddress::CAddress(CService ipIn, uint64_t nServicesIn) : CService(ipIn)\n{\n Init();\n nServices = nServicesIn;\n}\n\nvoid CAddress::Init()\n{\n nServices = NODE_NETWORK;\n nTime = 100000000;\n nLastTry = 0;\n}\n\nCInv::CInv()\n{\n type = 0;\n hash = 0;\n}\n\nCInv::CInv(int typeIn, const uint256& hashIn)\n{\n type = typeIn;\n hash = hashIn;\n}\n\nCInv::CInv(const std::string& strType, const uint256& hashIn)\n{\n unsigned int i;\n for (i = 1; i < ARRAYLEN(ppszTypeName); i++)\n {\n if (strType == ppszTypeName[i])\n {\n type = i;\n break;\n }\n }\n if (i == ARRAYLEN(ppszTypeName))\n throw std::out_of_range(strprintf(\"CInv::CInv(string, uint256) : unknown type '%s'\", strType));\n hash = hashIn;\n}\n\nbool operator<(const CInv& a, const CInv& b)\n{\n return (a.type < b.type || (a.type == b.type && a.hash < b.hash));\n}\n\nbool CInv::IsKnownType() const\n{\n return (type >= 1 && type < (int)ARRAYLEN(ppszTypeName));\n}\n\nconst char* CInv::GetCommand() const\n{\n if (!IsKnownType())\n throw std::out_of_range(strprintf(\"CInv::GetCommand() : type=%d unknown type\", type));\n return ppszTypeName[type];\n}\n\nstd::string CInv::ToString() const\n{\n return strprintf(\"%s %s\", GetCommand(), hash.ToString());\n}\n<commit_msg>MessageHeader correction<commit_after>\/\/ Copyright (c) 2009-2010 Satoshi Nakamoto\n\/\/ Copyright (c) 2009-2012 The Bitcoin developers\n\/\/ Distributed under the MIT\/X11 software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \"protocol.h\"\n#include \"util.h\"\n#include \"netbase.h\"\n\n#ifndef WIN32\n# include <arpa\/inet.h>\n#endif\n\nstatic const char* ppszTypeName[] =\n{\n \"ERROR\",\n \"tx\",\n \"dstx\",\n \"block\",\n \"filtered block\",\n \"tx lock request\",\n \"tx lock vote\",\n \"spork\",\n \"masternode winner\",\n \"unknown\",\n \"unknown\",\n \"unknown\",\n \"unknown\",\n \"unknown\",\n \"unknown\"\n};\n\nCMessageHeader::CMessageHeader()\n{\n memcpy(pchMessageStart, Params().MessageStart(), MESSAGE_START_SIZE);\n pchCommand[1] = 1;\n nMessageSize = -1;\n nChecksum = 0;\n}\n\nCMessageHeader::CMessageHeader(const char* pszCommand, unsigned int nMessageSizeIn)\n{\n memcpy(pchMessageStart, Params().MessageStart(), MESSAGE_START_SIZE);\n memset(pchCommand, 0, sizeof(pchCommand));\n strncpy(pchCommand, pszCommand, COMMAND_SIZE);\n nMessageSize = nMessageSizeIn;\n nChecksum = 0;\n}\n\nstd::string CMessageHeader::GetCommand() const\n{\n return std::string(pchCommand, pchCommand + strnlen(pchCommand, COMMAND_SIZE));\n}\n\nbool CMessageHeader::IsValid() const\n{\n \/\/ Check start string\n if (memcmp(pchMessageStart, Params().MessageStart(), MESSAGE_START_SIZE) != 0)\n return false;\n\n \/\/ Check the command string for errors\n for (const char* p1 = pchCommand; p1 < pchCommand + COMMAND_SIZE; p1++)\n {\n if (*p1 == 0)\n {\n \/\/ Must be all zeros after the first zero\n for (; p1 < pchCommand + COMMAND_SIZE; p1++)\n if (*p1 != 0)\n return false;\n }\n else if (*p1 < ' ' || *p1 > 0x7E)\n return false;\n }\n\n \/\/ Message size\n if (nMessageSize > MAX_SIZE)\n {\n LogPrintf(\"CMessageHeader::IsValid() : (%s, %u bytes) nMessageSize > MAX_SIZE\\n\", GetCommand(), nMessageSize);\n return false;\n }\n\n return true;\n}\n\n\n\nCAddress::CAddress() : CService()\n{\n Init();\n}\n\nCAddress::CAddress(CService ipIn, uint64_t nServicesIn) : CService(ipIn)\n{\n Init();\n nServices = nServicesIn;\n}\n\nvoid CAddress::Init()\n{\n nServices = NODE_NETWORK;\n nTime = 100000000;\n nLastTry = 0;\n}\n\nCInv::CInv()\n{\n type = 0;\n hash = 0;\n}\n\nCInv::CInv(int typeIn, const uint256& hashIn)\n{\n type = typeIn;\n hash = hashIn;\n}\n\nCInv::CInv(const std::string& strType, const uint256& hashIn)\n{\n unsigned int i;\n for (i = 1; i < ARRAYLEN(ppszTypeName); i++)\n {\n if (strType == ppszTypeName[i])\n {\n type = i;\n break;\n }\n }\n if (i == ARRAYLEN(ppszTypeName))\n throw std::out_of_range(strprintf(\"CInv::CInv(string, uint256) : unknown type '%s'\", strType));\n hash = hashIn;\n}\n\nbool operator<(const CInv& a, const CInv& b)\n{\n return (a.type < b.type || (a.type == b.type && a.hash < b.hash));\n}\n\nbool CInv::IsKnownType() const\n{\n return (type >= 1 && type < (int)ARRAYLEN(ppszTypeName));\n}\n\nconst char* CInv::GetCommand() const\n{\n if (!IsKnownType())\n throw std::out_of_range(strprintf(\"CInv::GetCommand() : type=%d unknown type\", type));\n return ppszTypeName[type];\n}\n\nstd::string CInv::ToString() const\n{\n return strprintf(\"%s %s\", GetCommand(), hash.ToString());\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2015-2016 Nathan Bass \"IngCr3at1on\"\n\/\/ Distributed under the MIT\/X11 software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \"base58.h\"\n#include \"util.h\"\n#include \"reactors.h\"\n\nusing namespace std;\n\nint CURRENT_REACTOR_VERSION = -2; \/\/ Test version\n\nbool maybeWipeReactorDB(string strFileName) {\n int dbversion;\n if (CReactorDB(strFileName).CheckReactorDBVersion(dbversion)) {\n if (dbversion == CURRENT_REACTOR_VERSION)\n return false;\n }\n\n \/\/ No version set or version is invalid, wipe the DB.\n printf(\"maybeWipeReactorDB() : reactor databse is outdated, removing for recreation\\n\");\n CReactorDB(strFileName).Close();\n bitdb.CloseDb(\"reactors.dat\");\n boost::filesystem::remove(strFileName);\n \/\/ Return true so we know to re-inflate the DB.\n return true;\n}\n\n\/* This function should not be called by tests (is not currently required for\n * them) as it will use the reactor.dat found in the datadir instead of the\n * mockdb. *\/\nvoid InitReactors() {\n bool inflatedb = false;\n \/\/ Check if the reactor database exists and check the version if it does.\n string reactordbfile = GetReactorDBFile();\n if (boost::filesystem::exists(boost::filesystem::path(reactordbfile))) {\n if (maybeWipeReactorDB(reactordbfile))\n inflatedb = true;\n\n if (!inflatedb) {\n \/\/ TODO Replace with correct first and last reactor addresses.\n if (!fTestNet && (!CReactorDB(reactordbfile).CheckReactorAddr(string(\"dMajkjpXzy2KTk21JkFx8aDtUVoaXmeMEZ\"))\n || !CReactorDB(reactordbfile).CheckReactorAddr(string(\"dK8Sh1R81YxaFrwwMmYEH1QET6ejhUw3pQ\"))))\n inflatedb = true;\n else if (fTestNet && (!CReactorDB(reactordbfile).CheckReactorAddr(string(\"muLhTBAfaS2ro2fhDFh6D7MArg6qGv1j1i\"))\n || !CReactorDB(reactordbfile).CheckReactorAddr(string(\"mkB4XAhFZmG5rNuhs4mnnBFWN3jKD2rXw2\"))))\n inflatedb = true;\n }\n } else {\n inflatedb = true;\n }\n\n if (inflatedb)\n InflateReactorDB(reactordbfile);\n}\n\nbool CTransaction::IsReactorStake(string strFileName, CScript scriptPubKeyType, CScript scriptPubKeyAddress, unsigned int nTime, int64 nValueIn, int64 nValueOut, uint64 nCoinAge, unsigned int nBits, int nHeight) {\n int64 nStakeReward = nValueOut - nValueIn;\n\n \/\/ Should never be anything else.\n if (scriptPubKeyType[0] == OP_REACTOR) {\n unsigned int valid_starting;\n unsigned int valid_until;\n int64 reactorStakeValue;\n\n \/* Destination address is stored in the CScript for vout[1] of the input\n * so extract it against our database. *\/\n if (!CReactorDB(strFileName).IsReactor(strFileName, scriptPubKeyAddress, reactorStakeValue, valid_starting, valid_until))\n return DoS(100, error(\"IsReactorStake() : invalid reactor address, HAXORS!!!\"));\n\n if (nTime < valid_starting)\n return DoS(100, error(\"IsReactorStake() : reactor is not valid yet\"));\n\n if (nTime >= valid_until && valid_until != (unsigned int)-1)\n return DoS(100, error(\"IsReactorStake() : reactor is expired\"));\n\n \/* If this is a reactor check that the size of the stake matches the\n * requirements of the given reactor.*\/\n if (reactorStakeValue == 3000 || reactorStakeValue == 15000) {\n if (nValueIn < (reactorStakeValue * COIN))\n return DoS(100, error(\"IsReactorStake() : nValueIn doesn't meet requirement for reactor stake; credit %\" PRI64d \"; reactor size %d or %d\", nValueIn, 3000, 15000));\n\n if (nValueIn > (reactorStakeValue * COIN))\n return DoS(100, error(\"IsReactorStake() : nValueIn exceeds value of reactor; credit %\" PRI64d \"; reactor size %d or %d\", nValueIn, 3000, 15000));\n } else {\n if (nValueIn < (reactorStakeValue * COIN))\n return DoS(100, error(\"IsReactorStake() : credit doesn't meet requirement for reactor stake; credit %\" PRI64d \"; reactor size %\" PRI64d \"\", nValueIn, reactorStakeValue));\n\n if (nValueIn > (reactorStakeValue * COIN))\n return DoS(100, error(\"IsReactorStake() : credit exceeds value of reactor; credit %\" PRI64d \"; reactor size %\" PRI64d \"\", nValueIn, reactorStakeValue));\n }\n\n if (nStakeReward > GetProofOfStakeReward(nCoinAge, nBits, nTime, nHeight, GetReactorRate(reactorStakeValue, nValueIn)) - GetMinFee() + MIN_TX_FEE)\n return DoS(100, error(\"IsReactorStake() : %s stake reward exceeded\", GetHash().ToString().substr(0, 10).c_str()));\n\n return true;\n }\n\n return false;\n}\n\n\/\/ Inflate the reactor table in the reactorDB\nvoid InflateReactorDB(string strFileName) {\n printf(\"InflateReactorDB() : inflating reactor database.\\n\");\n\n fTestNet ? CReactorDB(strFileName, \"cw+\").WriteTestReactorDB() : CReactorDB(strFileName, \"cw+\").WriteReactorDB();\n}\n\nint GetReactorRate(int64 reactorStakeValue, int64 nValueIn) {\n if (reactorStakeValue == 1000 || reactorStakeValue == 10000)\n return 2;\n\n \/* We store the max value of the Legendaries in the database and override\n * the rate for 3000 coin stakes here. *\/\n if (reactorStakeValue == 15000 && nValueIn == 3000)\n return 2;\n\n if (reactorStakeValue == 15000 && nValueIn == 15000)\n return 1.5;\n\n return 0;\n}\n\nbool CReactorDB::WriteReactorDBVersion(int version)\n{\n return Write(string(\"dbversion\"), version);\n}\n\nbool CReactorDB::WriteReactorAddr(const string address, unsigned int valid_starting, unsigned int valid_until, int64 reactorStakeValue)\n{\n return Write(make_pair(string(\"reactor\"), address), boost::make_tuple(valid_starting, valid_until, reactorStakeValue));\n}\n\nbool CReactorDB::CheckReactorDBVersion(int &version)\n{\n if (!Exists(string(\"dbversion\")))\n return false;\n\n Read(string(\"dbversion\"), version);\n return true;\n}\n\nbool CReactorDB::CheckReactorAddr(const string address)\n{\n return Exists(make_pair(string(\"reactor\"), address));\n}\n\nbool CReactorDB::IsReactor(std::string strFileName, CScript scriptPubKeyAddress, int64 &reactorStakeValue, unsigned int &valid_starting, unsigned int &valid_until)\n{\n CTxDestination address;\n ExtractDestination(scriptPubKeyAddress, address);\n CBitcoinAddress addr(address);\n\n \/\/ Check if the address exists in the reactor database.\n if (!CReactorDB(strFileName).CheckReactorAddr(addr.ToString()))\n return false;\n\n boost::tuple<unsigned int, unsigned int, int64> t;\n Read(make_pair(string(\"reactor\"), addr.ToString()), t);\n\n valid_starting = t.get<0>();\n valid_until = t.get<1>();\n\n reactorStakeValue = t.get<2>();\n return true;\n}\n<commit_msg>Fix legendary reactor rate and add staisybit rate<commit_after>\/\/ Copyright (c) 2015-2016 Nathan Bass \"IngCr3at1on\"\n\/\/ Distributed under the MIT\/X11 software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \"base58.h\"\n#include \"util.h\"\n#include \"reactors.h\"\n\nusing namespace std;\n\nint CURRENT_REACTOR_VERSION = -2; \/\/ Test version\n\nbool maybeWipeReactorDB(string strFileName) {\n int dbversion;\n if (CReactorDB(strFileName).CheckReactorDBVersion(dbversion)) {\n if (dbversion == CURRENT_REACTOR_VERSION)\n return false;\n }\n\n \/\/ No version set or version is invalid, wipe the DB.\n printf(\"maybeWipeReactorDB() : reactor databse is outdated, removing for recreation\\n\");\n CReactorDB(strFileName).Close();\n bitdb.CloseDb(\"reactors.dat\");\n boost::filesystem::remove(strFileName);\n \/\/ Return true so we know to re-inflate the DB.\n return true;\n}\n\n\/* This function should not be called by tests (is not currently required for\n * them) as it will use the reactor.dat found in the datadir instead of the\n * mockdb. *\/\nvoid InitReactors() {\n bool inflatedb = false;\n \/\/ Check if the reactor database exists and check the version if it does.\n string reactordbfile = GetReactorDBFile();\n if (boost::filesystem::exists(boost::filesystem::path(reactordbfile))) {\n if (maybeWipeReactorDB(reactordbfile))\n inflatedb = true;\n\n if (!inflatedb) {\n \/\/ TODO Replace with correct first and last reactor addresses.\n if (!fTestNet && (!CReactorDB(reactordbfile).CheckReactorAddr(string(\"dMajkjpXzy2KTk21JkFx8aDtUVoaXmeMEZ\"))\n || !CReactorDB(reactordbfile).CheckReactorAddr(string(\"dK8Sh1R81YxaFrwwMmYEH1QET6ejhUw3pQ\"))))\n inflatedb = true;\n else if (fTestNet && (!CReactorDB(reactordbfile).CheckReactorAddr(string(\"muLhTBAfaS2ro2fhDFh6D7MArg6qGv1j1i\"))\n || !CReactorDB(reactordbfile).CheckReactorAddr(string(\"mkB4XAhFZmG5rNuhs4mnnBFWN3jKD2rXw2\"))))\n inflatedb = true;\n }\n } else {\n inflatedb = true;\n }\n\n if (inflatedb)\n InflateReactorDB(reactordbfile);\n}\n\nbool CTransaction::IsReactorStake(string strFileName, CScript scriptPubKeyType, CScript scriptPubKeyAddress, unsigned int nTime, int64 nValueIn, int64 nValueOut, uint64 nCoinAge, unsigned int nBits, int nHeight) {\n int64 nStakeReward = nValueOut - nValueIn;\n\n \/\/ Should never be anything else.\n if (scriptPubKeyType[0] == OP_REACTOR) {\n unsigned int valid_starting;\n unsigned int valid_until;\n int64 reactorStakeValue;\n\n \/* Destination address is stored in the CScript for vout[1] of the input\n * so extract it against our database. *\/\n if (!CReactorDB(strFileName).IsReactor(strFileName, scriptPubKeyAddress, reactorStakeValue, valid_starting, valid_until))\n return DoS(100, error(\"IsReactorStake() : invalid reactor address, HAXORS!!!\"));\n\n if (nTime < valid_starting)\n return DoS(100, error(\"IsReactorStake() : reactor is not valid yet\"));\n\n if (nTime >= valid_until && valid_until != (unsigned int)-1)\n return DoS(100, error(\"IsReactorStake() : reactor is expired\"));\n\n \/* If this is a reactor check that the size of the stake matches the\n * requirements of the given reactor.*\/\n if (reactorStakeValue == 3000 || reactorStakeValue == 15000) {\n if (nValueIn < (reactorStakeValue * COIN))\n return DoS(100, error(\"IsReactorStake() : nValueIn doesn't meet requirement for reactor stake; credit %\" PRI64d \"; reactor size %d or %d\", nValueIn, 3000, 15000));\n\n if (nValueIn > (reactorStakeValue * COIN))\n return DoS(100, error(\"IsReactorStake() : nValueIn exceeds value of reactor; credit %\" PRI64d \"; reactor size %d or %d\", nValueIn, 3000, 15000));\n } else {\n if (nValueIn < (reactorStakeValue * COIN))\n return DoS(100, error(\"IsReactorStake() : credit doesn't meet requirement for reactor stake; credit %\" PRI64d \"; reactor size %\" PRI64d \"\", nValueIn, reactorStakeValue));\n\n if (nValueIn > (reactorStakeValue * COIN))\n return DoS(100, error(\"IsReactorStake() : credit exceeds value of reactor; credit %\" PRI64d \"; reactor size %\" PRI64d \"\", nValueIn, reactorStakeValue));\n }\n\n if (nStakeReward > GetProofOfStakeReward(nCoinAge, nBits, nTime, nHeight, GetReactorRate(reactorStakeValue, nValueIn)) - GetMinFee() + MIN_TX_FEE)\n return DoS(100, error(\"IsReactorStake() : %s stake reward exceeded\", GetHash().ToString().substr(0, 10).c_str()));\n\n return true;\n }\n\n return false;\n}\n\n\/\/ Inflate the reactor table in the reactorDB\nvoid InflateReactorDB(string strFileName) {\n printf(\"InflateReactorDB() : inflating reactor database.\\n\");\n\n fTestNet ? CReactorDB(strFileName, \"cw+\").WriteTestReactorDB() : CReactorDB(strFileName, \"cw+\").WriteReactorDB();\n}\n\nint GetReactorRate(int64 reactorStakeValue, int64 nValueIn) {\n if (reactorStakeValue == 100)\n return 1.05;\n\n if (reactorStakeValue == 1000 || reactorStakeValue == 10000)\n return 2;\n\n \/* We store the max value of the Legendaries in the database and override\n * the rate for 3000 coin stakes here. *\/\n if (reactorStakeValue == 15000 && nValueIn == 3000 * COIN)\n return 2;\n\n if (reactorStakeValue == 15000 && nValueIn == 15000 * COIN)\n return 1.25;\n\n return 0;\n}\n\nbool CReactorDB::WriteReactorDBVersion(int version)\n{\n return Write(string(\"dbversion\"), version);\n}\n\nbool CReactorDB::WriteReactorAddr(const string address, unsigned int valid_starting, unsigned int valid_until, int64 reactorStakeValue)\n{\n return Write(make_pair(string(\"reactor\"), address), boost::make_tuple(valid_starting, valid_until, reactorStakeValue));\n}\n\nbool CReactorDB::CheckReactorDBVersion(int &version)\n{\n if (!Exists(string(\"dbversion\")))\n return false;\n\n Read(string(\"dbversion\"), version);\n return true;\n}\n\nbool CReactorDB::CheckReactorAddr(const string address)\n{\n return Exists(make_pair(string(\"reactor\"), address));\n}\n\nbool CReactorDB::IsReactor(std::string strFileName, CScript scriptPubKeyAddress, int64 &reactorStakeValue, unsigned int &valid_starting, unsigned int &valid_until)\n{\n CTxDestination address;\n ExtractDestination(scriptPubKeyAddress, address);\n CBitcoinAddress addr(address);\n\n \/\/ Check if the address exists in the reactor database.\n if (!CReactorDB(strFileName).CheckReactorAddr(addr.ToString()))\n return false;\n\n boost::tuple<unsigned int, unsigned int, int64> t;\n Read(make_pair(string(\"reactor\"), addr.ToString()), t);\n\n valid_starting = t.get<0>();\n valid_until = t.get<1>();\n\n reactorStakeValue = t.get<2>();\n return true;\n}\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n#include <thread>\n#include <stdlib.h>\n#include <stdio.h>\n#include <unistd.h>\n#include <string.h>\n#include <netdb.h>\n#include <sys\/socket.h>\n#include <arpa\/inet.h>\n\n#include \"dcomm.h\"\n#include \"frame.cpp\"\n#include \"crc32.h\"\nusing namespace std;\n\n\nstruct sockaddr_in myaddr;\nstruct sockaddr_in remaddr;\nsocklen_t addrlen = sizeof(remaddr);\nint s;\nint msgcnt = 0;\nchar sent_frame[DATASIZE + 15];\nframe frame_buffer[RXQSIZE];\n\n\nvoid receiveMessage(){\n\tprintf(\"waiting on port 9999\\n\");\n\tfor (;;) {\n\t\tint recvlen = recvfrom(s, sent_frame, sizeof(sent_frame), 0, (struct sockaddr *)&remaddr, &addrlen);\n\t\tif (recvlen > 0) {\n\t\t\t\n\t\t\tframe f(sent_frame);\n\t\t\tframe_buffer[f.getFrameNumber() % WINDOWSIZE] = f;\n\t\t}\n\t\t\n\t}\n}\n\nvoid consumeMessage(){\n\tint j = 0;\n\tfor (;;){\n\t\tj++;\n\t\tfor (int i = 0; i < RXQSIZE; i++) {\n\t\t\tif (frame_buffer[i].getFrameNumber() != -1){\n\t\t\t\t\n\t\t\t\tCRC32 crc32;\n\t\t\t\tstring tmp;\n\n\t\t\t\tif (1) { \/\/ jika checksum sama\n\t\t\t\t\tcout << frame_buffer[i].getData() << endl;\n\t\t\t\t\t\n\t\t\t\t\tint frameNumber = frame_buffer[i].getFrameNumber();\n\t\t\t\t\tchar buf[10];\n\t\t\t\t\tsprintf(buf, \"%d\", frameNumber);\n\t\t\t\t\tif (sendto(s, buf, sizeof(buf), 0, (struct sockaddr *)&remaddr, addrlen)==-1) {\n\t\t\t\t\t perror(\"sendto\");\n\t\t\t\t\t exit(1);\n\t\t\t\t\t}\n\n\t\t\t\t\tusleep(50);\n\t\t\t\t\tframe_buffer[i].empty();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\n\n#define BUFSIZE 32\n\nint main(int argc, char const *argv[]) {\n\n\t\/\/ Create UDP socket\n\tif ((s = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {\n\t\tperror(\"cannot create socket\\n\");\n\t\treturn 0;\n\t}\n\n\t\/\/ Bind the socket to any valid IP address and a specific port\n\tmemset((char *)&myaddr, 0, sizeof(myaddr));\n\tmyaddr.sin_family = AF_INET;\n\tmyaddr.sin_addr.s_addr = htonl(INADDR_ANY);\n\tmyaddr.sin_port = htons(atoi(argv[1]));\n\n\tif (bind(s, (struct sockaddr *)&myaddr, sizeof(myaddr)) < 0) {\n\t\tperror(\"bind failed\");\n\t\treturn 0;\n\t}\n\tthread receive_t(receiveMessage);\n\tthread consume_t(consumeMessage);\n\tconsume_t.join();\n\treceive_t.join();\n\t\/\/ Everything is configured and ready to receive message\n\t\n}\n<commit_msg>Add to do<commit_after>#include <iostream>\n#include <thread>\n#include <stdlib.h>\n#include <stdio.h>\n#include <unistd.h>\n#include <string.h>\n#include <netdb.h>\n#include <sys\/socket.h>\n#include <arpa\/inet.h>\n\n#include \"dcomm.h\"\n#include \"frame.cpp\"\n#include \"crc32.h\"\nusing namespace std;\n\n\nstruct sockaddr_in myaddr;\nstruct sockaddr_in remaddr;\nsocklen_t addrlen = sizeof(remaddr);\nint s;\nint msgcnt = 0;\nchar sent_frame[DATASIZE + 15];\nframe frame_buffer[RXQSIZE];\n\n\nvoid receiveMessage(){\n\tprintf(\"waiting on port 9999\\n\");\n\tfor (;;) {\n\t\tint recvlen = recvfrom(s, sent_frame, sizeof(sent_frame), 0, (struct sockaddr *)&remaddr, &addrlen);\n\t\tif (recvlen > 0) {\n\t\t\t\n\t\t\tframe f(sent_frame);\n\t\t\tframe_buffer[f.getFrameNumber() % WINDOWSIZE] = f;\n\t\t}\n\t\t\n\t}\n}\n\nvoid consumeMessage(){\n\tfor (;;){\n\t\tfor (int i = 0; i < RXQSIZE; i++) {\n\t\t\tif (frame_buffer[i].getFrameNumber() != -1) { \/\/ jika frame buffer tidak kosong\n\t\t\t\tif (1) { \/\/ jika checksum sama\n\n\t\t\t\t\t\/\/ kirim ACK\n\t\t\t\t\tcout << frame_buffer[i].getData() << endl;\n\t\t\t\t\tint frameNumber = frame_buffer[i].getFrameNumber();\n\t\t\t\t\tchar buf[10];\n\t\t\t\t\tsprintf(buf, \"%d\", frameNumber);\n\t\t\t\t\tif (sendto(s, buf, sizeof(buf), 0, (struct sockaddr *)&remaddr, addrlen)==-1) {\n\t\t\t\t\t perror(\"sendto\");\n\t\t\t\t\t exit(1);\n\t\t\t\t\t}\n\n\t\t\t\t} else { \/\/ checksum tidak sama\n\t\t\t\t\t\/\/ kirim NAK\n\t\t\t\t}\n\n\t\t\t\t\/\/ Hapus frame yang sudah diproses\n\t\t\t\tusleep(50);\n\t\t\t\tframe_buffer[i].empty();\n\t\t\t}\n\t\t}\n\t}\n}\n\n\n#define BUFSIZE 32\n\nint main(int argc, char const *argv[]) {\n\n\t\/\/ Create UDP socket\n\tif ((s = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {\n\t\tperror(\"cannot create socket\\n\");\n\t\treturn 0;\n\t}\n\n\t\/\/ Bind the socket to any valid IP address and a specific port\n\tmemset((char *)&myaddr, 0, sizeof(myaddr));\n\tmyaddr.sin_family = AF_INET;\n\tmyaddr.sin_addr.s_addr = htonl(INADDR_ANY);\n\tmyaddr.sin_port = htons(atoi(argv[1]));\n\n\tif (bind(s, (struct sockaddr *)&myaddr, sizeof(myaddr)) < 0) {\n\t\tperror(\"bind failed\");\n\t\treturn 0;\n\t}\n\tthread receive_t(receiveMessage);\n\tthread consume_t(consumeMessage);\n\tconsume_t.join();\n\treceive_t.join();\n\t\/\/ Everything is configured and ready to receive message\n\t\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright 2020-2021 INRIA\n *\/\n\n#include \"eigenpy\/register.hpp\"\n\nnamespace eigenpy\n{\n\n PyArray_Descr * Register::getPyArrayDescr(PyTypeObject * py_type_ptr)\n {\n MapDescr::iterator it = instance().py_array_descr_bindings.find(py_type_ptr);\n if(it != instance().py_array_descr_bindings.end())\n return it->second;\n else\n return NULL;\n }\n \n bool Register::isRegistered(PyTypeObject * py_type_ptr)\n {\n if(getPyArrayDescr(py_type_ptr) != NULL)\n return true;\n else\n return false;\n }\n \n int Register::getTypeCode(PyTypeObject * py_type_ptr)\n {\n MapCode::iterator it = instance().py_array_code_bindings.find(py_type_ptr);\n if(it != instance().py_array_code_bindings.end())\n return it->second;\n else\n return PyArray_TypeNum(py_type_ptr);\n }\n\n int Register::registerNewType(PyTypeObject * py_type_ptr,\n const std::type_info * type_info_ptr,\n const int type_size,\n const int alignement,\n PyArray_GetItemFunc * getitem,\n PyArray_SetItemFunc * setitem,\n PyArray_NonzeroFunc * nonzero,\n PyArray_CopySwapFunc * copyswap,\n PyArray_CopySwapNFunc * copyswapn,\n PyArray_DotFunc * dotfunc,\n PyArray_FillWithScalarFunc * fillwithscalar)\n {\n namespace bp = boost::python;\n bp::list bases(bp::handle<>(bp::borrowed(py_type_ptr->tp_bases)));\n bases.append((bp::handle<>(bp::borrowed(&PyGenericArrType_Type))));\n\n bp::tuple tp_bases_extended(bases);\n Py_INCREF(tp_bases_extended.ptr());\n py_type_ptr->tp_bases = tp_bases_extended.ptr();\n\n py_type_ptr->tp_flags &= ~Py_TPFLAGS_READY; \/\/ to force the rebuild\n if(PyType_Ready(py_type_ptr) < 0) \/\/ Force rebuilding of the __bases__ and mro\n {\n throw std::invalid_argument(\"PyType_Ready fails to initialize input type.\");\n }\n\n PyArray_Descr * descr_ptr = new PyArray_Descr(*call_PyArray_DescrFromType(NPY_OBJECT));\n PyArray_Descr & descr = *descr_ptr;\n descr.typeobj = py_type_ptr;\n descr.kind = 'V';\n descr.byteorder = '=';\n descr.type = 'r';\n descr.elsize = type_size;\n descr.flags = NPY_NEEDS_PYAPI | NPY_USE_GETITEM | NPY_USE_SETITEM;\n descr.type_num = 0;\n descr.names = 0;\n descr.fields = 0;\n descr.alignment = alignement; \/\/call_PyArray_DescrFromType(NPY_OBJECT)->alignment;\n \n PyArray_ArrFuncs * funcs_ptr = new PyArray_ArrFuncs;\n PyArray_ArrFuncs & funcs = *funcs_ptr;\n descr.f = funcs_ptr;\n call_PyArray_InitArrFuncs(funcs_ptr);\n funcs.getitem = getitem;\n funcs.setitem = setitem;\n funcs.nonzero = nonzero;\n funcs.copyswap = copyswap;\n funcs.copyswapn = copyswapn;\n funcs.dotfunc = dotfunc;\n funcs.fillwithscalar = fillwithscalar;\n \/\/ f->cast = cast;\n \n const int code = call_PyArray_RegisterDataType(descr_ptr);\n assert(code >= 0 && \"The return code should be positive\");\n PyArray_Descr * new_descr = call_PyArray_DescrFromType(code);\n\n if(PyDict_SetItemString(py_type_ptr->tp_dict,\"dtype\",(PyObject*)descr_ptr) < 0)\n {\n throw std::invalid_argument(\"PyDict_SetItemString fails.\");\n }\n \n instance().type_to_py_type_bindings.insert(std::make_pair(type_info_ptr,py_type_ptr));\n instance().py_array_descr_bindings[py_type_ptr] = new_descr;\n instance().py_array_code_bindings[py_type_ptr] = code;\n \n \/\/ PyArray_RegisterCanCast(descr,NPY_OBJECT,NPY_NOSCALAR);\n return code;\n }\n\n Register & Register::instance()\n {\n static Register self;\n return self;\n }\n\n} \/\/ namespace eigenpy\n<commit_msg>register: handle fill<commit_after>\/*\n * Copyright 2020-2021 INRIA\n *\/\n\n#include \"eigenpy\/register.hpp\"\n\nnamespace eigenpy\n{\n\n PyArray_Descr * Register::getPyArrayDescr(PyTypeObject * py_type_ptr)\n {\n MapDescr::iterator it = instance().py_array_descr_bindings.find(py_type_ptr);\n if(it != instance().py_array_descr_bindings.end())\n return it->second;\n else\n return NULL;\n }\n \n bool Register::isRegistered(PyTypeObject * py_type_ptr)\n {\n if(getPyArrayDescr(py_type_ptr) != NULL)\n return true;\n else\n return false;\n }\n \n int Register::getTypeCode(PyTypeObject * py_type_ptr)\n {\n MapCode::iterator it = instance().py_array_code_bindings.find(py_type_ptr);\n if(it != instance().py_array_code_bindings.end())\n return it->second;\n else\n return PyArray_TypeNum(py_type_ptr);\n }\n\n int Register::registerNewType(PyTypeObject * py_type_ptr,\n const std::type_info * type_info_ptr,\n const int type_size,\n const int alignement,\n PyArray_GetItemFunc * getitem,\n PyArray_SetItemFunc * setitem,\n PyArray_NonzeroFunc * nonzero,\n PyArray_CopySwapFunc * copyswap,\n PyArray_CopySwapNFunc * copyswapn,\n PyArray_DotFunc * dotfunc,\n PyArray_FillFunc * fill,\n PyArray_FillWithScalarFunc * fillwithscalar)\n {\n namespace bp = boost::python;\n bp::list bases(bp::handle<>(bp::borrowed(py_type_ptr->tp_bases)));\n bases.append((bp::handle<>(bp::borrowed(&PyGenericArrType_Type))));\n\n bp::tuple tp_bases_extended(bases);\n Py_INCREF(tp_bases_extended.ptr());\n py_type_ptr->tp_bases = tp_bases_extended.ptr();\n\n py_type_ptr->tp_flags &= ~Py_TPFLAGS_READY; \/\/ to force the rebuild\n if(PyType_Ready(py_type_ptr) < 0) \/\/ Force rebuilding of the __bases__ and mro\n {\n throw std::invalid_argument(\"PyType_Ready fails to initialize input type.\");\n }\n\n PyArray_Descr * descr_ptr = new PyArray_Descr(*call_PyArray_DescrFromType(NPY_OBJECT));\n PyArray_Descr & descr = *descr_ptr;\n descr.typeobj = py_type_ptr;\n descr.kind = 'V';\n descr.byteorder = '=';\n descr.type = 'r';\n descr.elsize = type_size;\n descr.flags = NPY_NEEDS_PYAPI | NPY_USE_GETITEM | NPY_USE_SETITEM;\n descr.type_num = 0;\n descr.names = 0;\n descr.fields = 0;\n descr.alignment = alignement; \/\/call_PyArray_DescrFromType(NPY_OBJECT)->alignment;\n \n PyArray_ArrFuncs * funcs_ptr = new PyArray_ArrFuncs;\n PyArray_ArrFuncs & funcs = *funcs_ptr;\n descr.f = funcs_ptr;\n call_PyArray_InitArrFuncs(funcs_ptr);\n funcs.getitem = getitem;\n funcs.setitem = setitem;\n funcs.nonzero = nonzero;\n funcs.copyswap = copyswap;\n funcs.copyswapn = copyswapn;\n funcs.dotfunc = dotfunc;\n funcs.fill = fill;\n funcs.fillwithscalar = fillwithscalar;\n \/\/ f->cast = cast;\n \n const int code = call_PyArray_RegisterDataType(descr_ptr);\n assert(code >= 0 && \"The return code should be positive\");\n PyArray_Descr * new_descr = call_PyArray_DescrFromType(code);\n\n if(PyDict_SetItemString(py_type_ptr->tp_dict,\"dtype\",(PyObject*)descr_ptr) < 0)\n {\n throw std::invalid_argument(\"PyDict_SetItemString fails.\");\n }\n \n instance().type_to_py_type_bindings.insert(std::make_pair(type_info_ptr,py_type_ptr));\n instance().py_array_descr_bindings[py_type_ptr] = new_descr;\n instance().py_array_code_bindings[py_type_ptr] = code;\n \n \/\/ PyArray_RegisterCanCast(descr,NPY_OBJECT,NPY_NOSCALAR);\n return code;\n }\n\n Register & Register::instance()\n {\n static Register self;\n return self;\n }\n\n} \/\/ namespace eigenpy\n<|endoftext|>"} {"text":"<commit_before>\/\/ ======================================================================== \/\/\n\/\/ Copyright 2009-2018 Intel Corporation \/\/\n\/\/ \/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\"); \/\/\n\/\/ you may not use this file except in compliance with the License. \/\/\n\/\/ You may obtain a copy of the License at \/\/\n\/\/ \/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0 \/\/\n\/\/ \/\/\n\/\/ Unless required by applicable law or agreed to in writing, software \/\/\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS, \/\/\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. \/\/\n\/\/ See the License for the specific language governing permissions and \/\/\n\/\/ limitations under the License. \/\/\n\/\/ ======================================================================== \/\/\n\n#include \"regression.h\"\n\nnamespace embree\n{\n static std::unique_ptr<std::vector<RegressionTest*>> regression_tests;\n\n void registerRegressionTest(RegressionTest* test) \n {\n if (!regression_tests) \n regression_tests = std::unique_ptr<std::vector<RegressionTest*>>(new std::vector<RegressionTest*>);\n\n regression_tests->push_back(test);\n }\n\n RegressionTest* getRegressionTest(size_t index)\n {\n if (!regression_tests) \n return nullptr;\n\n if (index >= regression_tests->size())\n return nullptr;\n \n return (*regression_tests)[index];\n }\n}\n<commit_msg>fixed issues with static variable initialization order causing a memory leak in regression.cpp<commit_after>\/\/ ======================================================================== \/\/\n\/\/ Copyright 2009-2018 Intel Corporation \/\/\n\/\/ \/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\"); \/\/\n\/\/ you may not use this file except in compliance with the License. \/\/\n\/\/ You may obtain a copy of the License at \/\/\n\/\/ \/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0 \/\/\n\/\/ \/\/\n\/\/ Unless required by applicable law or agreed to in writing, software \/\/\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS, \/\/\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. \/\/\n\/\/ See the License for the specific language governing permissions and \/\/\n\/\/ limitations under the License. \/\/\n\/\/ ======================================================================== \/\/\n\n#include \"regression.h\"\n\nnamespace embree\n{\n \/* registerRegressionTest is invoked from static initializers, thus\n * we cannot have the regression_tests variable as global static\n * variable due to issues with static variable initialization\n * order. *\/\n std::vector<RegressionTest*>& get_regression_tests()\n {\n static std::vector<RegressionTest*> regression_tests;\n return regression_tests;\n } \n\n void registerRegressionTest(RegressionTest* test) \n {\n get_regression_tests().push_back(test);\n }\n\n RegressionTest* getRegressionTest(size_t index)\n {\n if (index >= get_regression_tests().size())\n return nullptr;\n \n return get_regression_tests()[index];\n }\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"CUDADenseGraphBFSolver.h\"\n#include \"CUDAFormulas.h\"\n#include \"Device.h\"\n#include <cmath>\n#include <float.h>\n#include <algorithm>\n#include <limits>\n\n\nusing namespace sqaod_cuda;\nnamespace sq = sqaod;\n\ntemplate<class real>\nCUDADenseGraphBFSolver<real>::CUDADenseGraphBFSolver() {\n tileSize_ = 16384; \/* FIXME: give a correct size *\/\n}\n\ntemplate<class real>\nCUDADenseGraphBFSolver<real>::CUDADenseGraphBFSolver(Device &device) {\n tileSize_ = 16384; \/* FIXME: give a correct size *\/\n assignDevice(device);\n}\n\ntemplate<class real>\nCUDADenseGraphBFSolver<real>::~CUDADenseGraphBFSolver() {\n}\n\ntemplate<class real>\nvoid CUDADenseGraphBFSolver<real>::assignDevice(Device &device) {\n batchSearch_.assignDevice(device);\n devCopy_.assignDevice(device);\n}\n\ntemplate<class real>\nvoid CUDADenseGraphBFSolver<real>::getProblemSize(sqaod::SizeType *N) const {\n *N = N_;\n}\n\ntemplate<class real>\nvoid CUDADenseGraphBFSolver<real>::setProblem(const Matrix &W, sq::OptimizeMethod om) {\n throwErrorIf(!isSymmetric(W), \"W is not symmetric.\");\n N_ = W.rows;\n W_ = W;\n om_ = om;\n if (om_ == sq::optMaximize)\n W_ *= real(-1.);\n}\n\ntemplate<class real>\nvoid CUDADenseGraphBFSolver<real>::setTileSize(sqaod::SizeType tileSize) {\n tileSize_ = tileSize;\n}\n\ntemplate<class real>\nconst sq::BitsArray &CUDADenseGraphBFSolver<real>::get_x() const {\n return xList_;\n}\n\ntemplate<class real>\nconst sq::VectorType<real> &CUDADenseGraphBFSolver<real>::get_E() const {\n return E_;\n}\n\ntemplate<class real>\nvoid CUDADenseGraphBFSolver<real>::initSearch() {\n batchSearch_.setProblem(W_, tileSize_);\n HostObjectAllocator().allocate(&h_packedXmin_, tileSize_);\n\n Emin_ = std::numeric_limits<real>::max();\n xList_.clear();\n xMax_ = 1ull << N_;\n}\n\n\ntemplate<class real>\nvoid CUDADenseGraphBFSolver<real>::finSearch() {\n batchSearch_.synchronize();\n const DevicePackedBitsArray &dPackedXmin = batchSearch_.get_xMins();\n sqaod::SizeType nXMin = std::min(tileSize_, dPackedXmin.size);\n devCopy_(&h_packedXmin_, dPackedXmin);\n devCopy_.synchronize();\n \n xList_.clear();\n E_.resize(nXMin);\n if (om_ == sq::optMaximize)\n E_ *= real(-1.);\n for (sqaod::IdxType idx = 0; idx < (sqaod::IdxType)nXMin; ++idx) {\n sq::Bits bits;\n unpackBits(&bits, h_packedXmin_[idx], N_);\n xList_.pushBack(bits); \/\/ FIXME: apply move\n }\n}\n\ntemplate<class real>\nvoid CUDADenseGraphBFSolver<real>::searchRange(sq::PackedBits xBegin, sq::PackedBits xEnd) {\n \/* FIXME: Use multiple searchers, multi GPU *\/\n throwErrorIf(xBegin > xEnd, \"xBegin should be larger than xEnd\");\n xBegin = std::min(std::max(0ULL, xBegin), xMax_);\n xEnd = std::min(std::max(0ULL, xEnd), xMax_);\n if (xBegin == xEnd)\n return; \/* Nothing to do *\/\n\n batchSearch_.calculate_E(xBegin, xEnd);\n batchSearch_.synchronize();\n\n real newEmin = batchSearch_.get_Emin();\n if (newEmin < Emin_) {\n batchSearch_.partition_xMins(false);\n Emin_ = newEmin;\n }\n else if (newEmin == Emin_) {\n batchSearch_.partition_xMins(true);\n }\n}\n\n\ntemplate<class real>\nvoid CUDADenseGraphBFSolver<real>::search() {\n initSearch();\n int iStep = (int)std::min((unsigned long long)tileSize_, xMax_);\n for (sq::PackedBits iTile = 0; iTile < xMax_; iTile += iStep) {\n searchRange(iTile, iTile + iStep);\n }\n finSearch();\n}\n\ntemplate class sqaod_cuda::CUDADenseGraphBFSolver<float>;\ntemplate class sqaod_cuda::CUDADenseGraphBFSolver<double>;\n<commit_msg>Fix: Emin_ is not copied to E_.<commit_after>#include \"CUDADenseGraphBFSolver.h\"\n#include \"CUDAFormulas.h\"\n#include \"Device.h\"\n#include <cmath>\n#include <float.h>\n#include <algorithm>\n#include <limits>\n\n\nusing namespace sqaod_cuda;\nnamespace sq = sqaod;\n\ntemplate<class real>\nCUDADenseGraphBFSolver<real>::CUDADenseGraphBFSolver() {\n tileSize_ = 16384; \/* FIXME: give a correct size *\/\n}\n\ntemplate<class real>\nCUDADenseGraphBFSolver<real>::CUDADenseGraphBFSolver(Device &device) {\n tileSize_ = 16384; \/* FIXME: give a correct size *\/\n assignDevice(device);\n}\n\ntemplate<class real>\nCUDADenseGraphBFSolver<real>::~CUDADenseGraphBFSolver() {\n}\n\ntemplate<class real>\nvoid CUDADenseGraphBFSolver<real>::assignDevice(Device &device) {\n batchSearch_.assignDevice(device);\n devCopy_.assignDevice(device);\n}\n\ntemplate<class real>\nvoid CUDADenseGraphBFSolver<real>::getProblemSize(sqaod::SizeType *N) const {\n *N = N_;\n}\n\ntemplate<class real>\nvoid CUDADenseGraphBFSolver<real>::setProblem(const Matrix &W, sq::OptimizeMethod om) {\n throwErrorIf(!isSymmetric(W), \"W is not symmetric.\");\n N_ = W.rows;\n W_ = W;\n om_ = om;\n if (om_ == sq::optMaximize)\n W_ *= real(-1.);\n}\n\ntemplate<class real>\nvoid CUDADenseGraphBFSolver<real>::setTileSize(sqaod::SizeType tileSize) {\n tileSize_ = tileSize;\n}\n\ntemplate<class real>\nconst sq::BitsArray &CUDADenseGraphBFSolver<real>::get_x() const {\n return xList_;\n}\n\ntemplate<class real>\nconst sq::VectorType<real> &CUDADenseGraphBFSolver<real>::get_E() const {\n return E_;\n}\n\ntemplate<class real>\nvoid CUDADenseGraphBFSolver<real>::initSearch() {\n batchSearch_.setProblem(W_, tileSize_);\n HostObjectAllocator().allocate(&h_packedXmin_, tileSize_);\n\n Emin_ = std::numeric_limits<real>::max();\n xList_.clear();\n xMax_ = 1ull << N_;\n}\n\n\ntemplate<class real>\nvoid CUDADenseGraphBFSolver<real>::finSearch() {\n batchSearch_.synchronize();\n const DevicePackedBitsArray &dPackedXmin = batchSearch_.get_xMins();\n sqaod::SizeType nXMin = std::min(tileSize_, dPackedXmin.size);\n devCopy_(&h_packedXmin_, dPackedXmin);\n devCopy_.synchronize();\n \n xList_.clear();\n E_.resize(nXMin);\n E_ = Emin_;\n if (om_ == sq::optMaximize)\n E_ *= real(-1.);\n for (sqaod::IdxType idx = 0; idx < (sqaod::IdxType)nXMin; ++idx) {\n sq::Bits bits;\n unpackBits(&bits, h_packedXmin_[idx], N_);\n xList_.pushBack(bits); \/\/ FIXME: apply move\n }\n}\n\ntemplate<class real>\nvoid CUDADenseGraphBFSolver<real>::searchRange(sq::PackedBits xBegin, sq::PackedBits xEnd) {\n \/* FIXME: Use multiple searchers, multi GPU *\/\n throwErrorIf(xBegin > xEnd, \"xBegin should be larger than xEnd\");\n xBegin = std::min(std::max(0ULL, xBegin), xMax_);\n xEnd = std::min(std::max(0ULL, xEnd), xMax_);\n if (xBegin == xEnd)\n return; \/* Nothing to do *\/\n\n batchSearch_.calculate_E(xBegin, xEnd);\n batchSearch_.synchronize();\n\n real newEmin = batchSearch_.get_Emin();\n if (newEmin < Emin_) {\n batchSearch_.partition_xMins(false);\n Emin_ = newEmin;\n }\n else if (newEmin == Emin_) {\n batchSearch_.partition_xMins(true);\n }\n}\n\n\ntemplate<class real>\nvoid CUDADenseGraphBFSolver<real>::search() {\n initSearch();\n int iStep = (int)std::min((unsigned long long)tileSize_, xMax_);\n for (sq::PackedBits iTile = 0; iTile < xMax_; iTile += iStep) {\n searchRange(iTile, iTile + iStep);\n }\n finSearch();\n}\n\ntemplate class sqaod_cuda::CUDADenseGraphBFSolver<float>;\ntemplate class sqaod_cuda::CUDADenseGraphBFSolver<double>;\n<|endoftext|>"} {"text":"<commit_before>\/\/ -*- C++ -*-\n\/\/\n\/\/ ----------------------------------------------------------------------\n\/\/\n\/\/ Brad T. Aagaard, U.S. Geological Survey\n\/\/\n\/\/ This code was developed as part of the Computational Infrastructure\n\/\/ for Geodynamics (http:\/\/geodynamics.org).\n\/\/\n\/\/ Copyright (c) 2010-2015 University of California, Davis\n\/\/\n\/\/ See COPYING for license information.\n\/\/\n\/\/ ----------------------------------------------------------------------\n\/\/\n\n#include <portinfo>\n\n#include \"SpatialDB.hh\" \/\/ ISA SpatialDB object\n#include \"SimpleDB.hh\" \/\/ Implementation of class methods\n\n#include \"SimpleIO.hh\" \/\/ USES SimpleIO\n#include \"SimpleDBData.hh\" \/\/ USES SimpleDBData\n#include \"SimpleDBQuery.hh\" \/\/ USES SimpleDBQuery\n\n#include \"spatialdata\/geocoords\/CoordSys.hh\" \/\/ USES CoordSys\n\n#include <stdexcept> \/\/ USES std::runtime_error\n#include \"Exception.hh\" \/\/ USES OutOfBounds\n\n#include <sstream> \/\/ USES std::ostringsgream\n#include <assert.h> \/\/ USES assert()\n\n\/\/ ----------------------------------------------------------------------\n\/\/\/ Default constructor\nspatialdata::spatialdb::SimpleDB::SimpleDB(void) :\n _data(0),\n _iohandler(0),\n _query(0),\n _cs(0)\n{ \/\/ constructor\n} \/\/ constructor\n\n\/\/ ----------------------------------------------------------------------\n\/\/\/ Constructor with label\nspatialdata::spatialdb::SimpleDB::SimpleDB(const char* label) :\n SpatialDB(label),\n _data(0),\n _iohandler(0),\n _query(0),\n _cs(0)\n{ \/\/ constructor\n} \/\/ constructor\n\n\/\/ ----------------------------------------------------------------------\n\/\/\/ Default destructor\nspatialdata::spatialdb::SimpleDB::~SimpleDB(void)\n{ \/\/ destructor\n delete _data; _data = 0;\n delete _iohandler; _iohandler = 0;\n delete _query; _query = 0;\n delete _cs; _cs = 0;\n} \/\/ destructor\n\n\/\/ ----------------------------------------------------------------------\n\/\/\/ Open the database and prepare for querying.\nvoid\nspatialdata::spatialdb::SimpleDB::open(void)\n{ \/\/ open\n assert(_iohandler);\n\n \/\/ Read data\n if (!_data) {\n _data = new SimpleDBData;\n _iohandler->read(_data, &_cs);\n } \/\/ if\n\n \/\/ Create query object\n if (!_query)\n _query = new SimpleDBQuery(*this);\n} \/\/ open\n\n\/\/ ----------------------------------------------------------------------\n\/\/\/ Close the database.\nvoid\nspatialdata::spatialdb::SimpleDB::close(void)\n{ \/\/ close\n delete _data; _data = 0;\n\n assert(_query);\n _query->deallocate();\n} \/\/ close\n\n\/\/ ----------------------------------------------------------------------\n\/\/ Set query type.\nvoid\nspatialdata::spatialdb::SimpleDB::queryType(const SimpleDB::QueryEnum queryType)\n{ \/\/ queryType\n if (0 == _query)\n _query = new SimpleDBQuery(*this);\n _query->queryType(queryType);\n} \/\/ QueryType\n\n\/\/ ----------------------------------------------------------------------\n\/\/ Set values to be returned by queries.\nvoid\nspatialdata::spatialdb::SimpleDB::queryVals(const char* const* names,\n\t\t\t\t\t const int numVals)\n{ \/\/ queryVals\n if (0 == _query) {\n std::ostringstream msg;\n msg\n << \"Spatial database \" << label() << \" has not been opened.\\n\"\n << \"Please call Open() before calling QueryVals().\";\n throw std::runtime_error(msg.str());\n } \/\/ if\n _query->queryVals(names, numVals);\n} \/\/ queryVals\n\n\/\/ ----------------------------------------------------------------------\n\/\/ Set the I\/O handler.\nvoid\nspatialdata::spatialdb::SimpleDB::ioHandler(const SimpleIO* iohandler)\n{ \/\/ ioHandler\n delete _iohandler; _iohandler = (0 != iohandler) ? iohandler->clone() : 0;\n} \/\/ ioHandler\n\n\/\/ ----------------------------------------------------------------------\n\/\/ Query the database.\nint\nspatialdata::spatialdb::SimpleDB::query(double* vals,\n\t\t\t\t\tconst int numVals,\n\t\t\t\t\tconst double* coords,\n\t\t\t\t\tconst int numDims,\n\t\t\t const spatialdata::geocoords::CoordSys* pCSQuery)\n{ \/\/ query\n try {\n if (0 == _query) {\n std::ostringstream msg;\n msg\n\t<< \"Spatial database \" << label() << \" has not been opened.\\n\"\n\t<< \"Please call open() before calling query().\";\n throw std::runtime_error(msg.str());\n } \/\/ if\n else if (0 == _data) {\n std::ostringstream msg;\n msg\n\t<< \"Spatial database \" << label() << \" does not contain any data.\\n\"\n\t<< \"Database query aborted.\";\n throw std::runtime_error(msg.str());\n } \/\/ if\n _query->query(vals, numVals, coords, numDims, pCSQuery);\n } catch(const OutOfBounds& err) {\n std::fill(vals, vals+numVals, 0);\n return 1;\n } catch(const std::exception& err) {\n throw std::runtime_error(err.what());\n } catch(...) {\n throw std::runtime_error(\"Unknown error in SpatialDB query\");\n } \/\/ catch\n return 0;\n} \/\/ query\n\n\n\/\/ End of file \n<commit_msg>Made SimpleDB::close() more robust. Don't insist on query being non-null.<commit_after>\/\/ -*- C++ -*-\n\/\/\n\/\/ ----------------------------------------------------------------------\n\/\/\n\/\/ Brad T. Aagaard, U.S. Geological Survey\n\/\/\n\/\/ This code was developed as part of the Computational Infrastructure\n\/\/ for Geodynamics (http:\/\/geodynamics.org).\n\/\/\n\/\/ Copyright (c) 2010-2015 University of California, Davis\n\/\/\n\/\/ See COPYING for license information.\n\/\/\n\/\/ ----------------------------------------------------------------------\n\/\/\n\n#include <portinfo>\n\n#include \"SpatialDB.hh\" \/\/ ISA SpatialDB object\n#include \"SimpleDB.hh\" \/\/ Implementation of class methods\n\n#include \"SimpleIO.hh\" \/\/ USES SimpleIO\n#include \"SimpleDBData.hh\" \/\/ USES SimpleDBData\n#include \"SimpleDBQuery.hh\" \/\/ USES SimpleDBQuery\n\n#include \"spatialdata\/geocoords\/CoordSys.hh\" \/\/ USES CoordSys\n\n#include <stdexcept> \/\/ USES std::runtime_error\n#include \"Exception.hh\" \/\/ USES OutOfBounds\n\n#include <sstream> \/\/ USES std::ostringsgream\n#include <assert.h> \/\/ USES assert()\n\n\/\/ ----------------------------------------------------------------------\n\/\/\/ Default constructor\nspatialdata::spatialdb::SimpleDB::SimpleDB(void) :\n _data(0),\n _iohandler(0),\n _query(0),\n _cs(0)\n{ \/\/ constructor\n} \/\/ constructor\n\n\/\/ ----------------------------------------------------------------------\n\/\/\/ Constructor with label\nspatialdata::spatialdb::SimpleDB::SimpleDB(const char* label) :\n SpatialDB(label),\n _data(0),\n _iohandler(0),\n _query(0),\n _cs(0)\n{ \/\/ constructor\n} \/\/ constructor\n\n\/\/ ----------------------------------------------------------------------\n\/\/\/ Default destructor\nspatialdata::spatialdb::SimpleDB::~SimpleDB(void)\n{ \/\/ destructor\n delete _data; _data = 0;\n delete _iohandler; _iohandler = 0;\n delete _query; _query = 0;\n delete _cs; _cs = 0;\n} \/\/ destructor\n\n\/\/ ----------------------------------------------------------------------\n\/\/\/ Open the database and prepare for querying.\nvoid\nspatialdata::spatialdb::SimpleDB::open(void)\n{ \/\/ open\n assert(_iohandler);\n\n \/\/ Read data\n if (!_data) {\n _data = new SimpleDBData;\n _iohandler->read(_data, &_cs);\n } \/\/ if\n\n \/\/ Create query object\n if (!_query)\n _query = new SimpleDBQuery(*this);\n} \/\/ open\n\n\/\/ ----------------------------------------------------------------------\n\/\/\/ Close the database.\nvoid\nspatialdata::spatialdb::SimpleDB::close(void)\n{ \/\/ close\n delete _data; _data = 0;\n\n if (_query) {\n _query->deallocate();\n } \/\/ if\n} \/\/ close\n\n\/\/ ----------------------------------------------------------------------\n\/\/ Set query type.\nvoid\nspatialdata::spatialdb::SimpleDB::queryType(const SimpleDB::QueryEnum queryType)\n{ \/\/ queryType\n if (0 == _query)\n _query = new SimpleDBQuery(*this);\n _query->queryType(queryType);\n} \/\/ QueryType\n\n\/\/ ----------------------------------------------------------------------\n\/\/ Set values to be returned by queries.\nvoid\nspatialdata::spatialdb::SimpleDB::queryVals(const char* const* names,\n\t\t\t\t\t const int numVals)\n{ \/\/ queryVals\n if (0 == _query) {\n std::ostringstream msg;\n msg\n << \"Spatial database \" << label() << \" has not been opened.\\n\"\n << \"Please call Open() before calling QueryVals().\";\n throw std::runtime_error(msg.str());\n } \/\/ if\n _query->queryVals(names, numVals);\n} \/\/ queryVals\n\n\/\/ ----------------------------------------------------------------------\n\/\/ Set the I\/O handler.\nvoid\nspatialdata::spatialdb::SimpleDB::ioHandler(const SimpleIO* iohandler)\n{ \/\/ ioHandler\n delete _iohandler; _iohandler = (0 != iohandler) ? iohandler->clone() : 0;\n} \/\/ ioHandler\n\n\/\/ ----------------------------------------------------------------------\n\/\/ Query the database.\nint\nspatialdata::spatialdb::SimpleDB::query(double* vals,\n\t\t\t\t\tconst int numVals,\n\t\t\t\t\tconst double* coords,\n\t\t\t\t\tconst int numDims,\n\t\t\t const spatialdata::geocoords::CoordSys* pCSQuery)\n{ \/\/ query\n try {\n if (0 == _query) {\n std::ostringstream msg;\n msg\n\t<< \"Spatial database \" << label() << \" has not been opened.\\n\"\n\t<< \"Please call open() before calling query().\";\n throw std::runtime_error(msg.str());\n } \/\/ if\n else if (0 == _data) {\n std::ostringstream msg;\n msg\n\t<< \"Spatial database \" << label() << \" does not contain any data.\\n\"\n\t<< \"Database query aborted.\";\n throw std::runtime_error(msg.str());\n } \/\/ if\n _query->query(vals, numVals, coords, numDims, pCSQuery);\n } catch(const OutOfBounds& err) {\n std::fill(vals, vals+numVals, 0);\n return 1;\n } catch(const std::exception& err) {\n throw std::runtime_error(err.what());\n } catch(...) {\n throw std::runtime_error(\"Unknown error in SpatialDB query\");\n } \/\/ catch\n return 0;\n} \/\/ query\n\n\n\/\/ End of file \n<|endoftext|>"} {"text":"<commit_before>#include \"reloader.h\"\n\n#include <algorithm>\n#include <cinttypes>\n#include <iostream>\n#include <ncurses.h>\n#include <thread>\n\n#include \"controller.h\"\n#include \"curlhandle.h\"\n#include \"dbexception.h\"\n#include \"downloadthread.h\"\n#include \"fmtstrformatter.h\"\n#include \"reloadrangethread.h\"\n#include \"reloadthread.h\"\n#include \"rss\/exception.h\"\n#include \"rssfeed.h\"\n#include \"rssparser.h\"\n#include \"scopemeasure.h\"\n#include \"utils.h\"\n#include \"view.h\"\n\nnamespace newsboat {\n\nReloader::Reloader(Controller* c, Cache* cc, ConfigContainer* cfg)\n\t: ctrl(c)\n\t, rsscache(cc)\n\t, cfg(cfg)\n{\n}\n\nvoid Reloader::spawn_reloadthread()\n{\n\tstd::thread t{ReloadThread(ctrl, cfg)};\n\tt.detach();\n}\n\nvoid Reloader::start_reload_all_thread(std::vector<int>* indexes)\n{\n\tLOG(Level::INFO, \"starting reload all thread\");\n\tstd::thread t(DownloadThread(*this, indexes));\n\tt.detach();\n}\n\nbool Reloader::trylock_reload_mutex()\n{\n\tif (reload_mutex.try_lock()) {\n\t\tLOG(Level::DEBUG, \"Reloader::trylock_reload_mutex succeeded\");\n\t\treturn true;\n\t}\n\tLOG(Level::DEBUG, \"Reloader::trylock_reload_mutex failed\");\n\treturn false;\n}\n\nvoid Reloader::reload(unsigned int pos,\n\tunsigned int max,\n\tbool unattended,\n\tCurlHandle* easyhandle)\n{\n\tLOG(Level::DEBUG, \"Reloader::reload: pos = %u max = %u\", pos, max);\n\tif (pos < ctrl->get_feedcontainer()->feeds.size()) {\n\t\tstd::shared_ptr<RssFeed> oldfeed =\n\t\t\tctrl->get_feedcontainer()->feeds[pos];\n\t\tstd::string errmsg;\n\t\tif (!unattended) {\n\t\t\tctrl->get_view()->set_status(\n\t\t\t\tstrprintf::fmt(_(\"%sLoading %s...\"),\n\t\t\t\t\tprepare_message(pos + 1, max),\n\t\t\t\t\tutils::censor_url(oldfeed->rssurl())));\n\t\t}\n\n\t\tbool ignore_dl =\n\t\t\t(cfg->get_configvalue(\"ignore-mode\") == \"download\");\n\n\t\tRssParser parser(oldfeed->rssurl(),\n\t\t\trsscache,\n\t\t\tcfg,\n\t\t\tignore_dl ? ctrl->get_ignores() : nullptr,\n\t\t\tctrl->get_api());\n\t\tparser.set_easyhandle(easyhandle);\n\t\tLOG(Level::DEBUG, \"Reloader::reload: created parser\");\n\t\ttry {\n\t\t\toldfeed->set_status(DlStatus::DURING_DOWNLOAD);\n\t\t\tstd::shared_ptr<RssFeed> newfeed = parser.parse();\n\t\t\tctrl->replace_feed(\n\t\t\t\toldfeed, newfeed, pos, unattended);\n\t\t\tif (newfeed->total_item_count() == 0) {\n\t\t\t\tLOG(Level::DEBUG,\n\t\t\t\t\t\"Reloader::reload: feed is empty\");\n\t\t\t}\n\t\t\toldfeed->set_status(DlStatus::SUCCESS);\n\t\t\tctrl->get_view()->set_status(\"\");\n\t\t} catch (const DbException& e) {\n\t\t\terrmsg = strprintf::fmt(\n\t\t\t\t\t_(\"Error while retrieving %s: %s\"),\n\t\t\t\t\tutils::censor_url(oldfeed->rssurl()),\n\t\t\t\t\te.what());\n\t\t} catch (const std::string& emsg) {\n\t\t\terrmsg = strprintf::fmt(\n\t\t\t\t\t_(\"Error while retrieving %s: %s\"),\n\t\t\t\t\tutils::censor_url(oldfeed->rssurl()),\n\t\t\t\t\temsg);\n\t\t} catch (rsspp::Exception& e) {\n\t\t\terrmsg = strprintf::fmt(\n\t\t\t\t\t_(\"Error while retrieving %s: %s\"),\n\t\t\t\t\tutils::censor_url(oldfeed->rssurl()),\n\t\t\t\t\te.what());\n\t\t}\n\t\tif (errmsg != \"\") {\n\t\t\toldfeed->set_status(DlStatus::DL_ERROR);\n\t\t\tctrl->get_view()->set_status(errmsg);\n\t\t\tLOG(Level::USERERROR, \"%s\", errmsg);\n\t\t}\n\t} else {\n\t\tctrl->get_view()->show_error(_(\"Error: invalid feed!\"));\n\t}\n}\n\nstd::string Reloader::prepare_message(unsigned int pos, unsigned int max)\n{\n\tif (max > 0) {\n\t\treturn strprintf::fmt(\"(%u\/%u) \", pos, max);\n\t}\n\treturn \"\";\n}\n\nvoid Reloader::reload_all(bool unattended)\n{\n\tconst auto unread_feeds =\n\t\tctrl->get_feedcontainer()->unread_feed_count();\n\tconst auto unread_articles =\n\t\tctrl->get_feedcontainer()->unread_item_count();\n\tint num_threads = cfg->get_configvalue_as_int(\"reload-threads\");\n\ttime_t t1, t2, dt;\n\n\tctrl->get_feedcontainer()->reset_feeds_status();\n\tconst auto num_feeds = ctrl->get_feedcontainer()->feeds_size();\n\n\t\/\/ TODO: change to std::clamp in C++17\n\tconst int min_threads = 1;\n\tconst int max_threads = num_feeds;\n\tnum_threads = std::max(min_threads, std::min(num_threads, max_threads));\n\n\tt1 = time(nullptr);\n\n\tLOG(Level::DEBUG, \"Reloader::reload_all: starting with reload all...\");\n\tif (num_threads == 1) {\n\t\treload_range(0, num_feeds - 1, num_feeds, unattended);\n\t} else {\n\t\tstd::vector<std::pair<unsigned int, unsigned int>> partitions =\n\t\t\t\tutils::partition_indexes(0, num_feeds - 1, num_threads);\n\t\tstd::vector<std::thread> threads;\n\t\tLOG(Level::DEBUG,\n\t\t\t\"Reloader::reload_all: starting reload threads...\");\n\t\tfor (int i = 0; i < num_threads - 1; i++) {\n\t\t\tthreads.push_back(std::thread(ReloadRangeThread(*this,\n\t\t\t\t\t\tpartitions[i].first,\n\t\t\t\t\t\tpartitions[i].second,\n\t\t\t\t\t\tnum_feeds,\n\t\t\t\t\t\tunattended)));\n\t\t}\n\t\tLOG(Level::DEBUG,\n\t\t\t\"Reloader::reload_all: starting my own reload...\");\n\t\treload_range(partitions[num_threads - 1].first,\n\t\t\tpartitions[num_threads - 1].second,\n\t\t\tnum_feeds,\n\t\t\tunattended);\n\t\tLOG(Level::DEBUG,\n\t\t\t\"Reloader::reload_all: joining other threads...\");\n\t\tfor (size_t i = 0; i < threads.size(); i++) {\n\t\t\tthreads[i].join();\n\t\t}\n\t}\n\n\t\/\/ refresh query feeds (update and sort)\n\tLOG(Level::DEBUG, \"Reloader::reload_all: refresh query feeds\");\n\tfor (const auto& feed : ctrl->get_feedcontainer()->feeds) {\n\t\tctrl->get_view()->prepare_query_feed(feed);\n\t}\n\tctrl->get_view()->force_redraw();\n\n\tctrl->get_feedcontainer()->sort_feeds(cfg->get_feed_sort_strategy());\n\tctrl->update_feedlist();\n\n\tt2 = time(nullptr);\n\tdt = t2 - t1;\n\t\/\/ On GCC, `time_t` is `long int`, which is at least 32 bits. On x86_64,\n\t\/\/ it's 64 bits. Thus, this cast is either a no-op, or an up-cast which are\n\t\/\/ always safe.\n\tLOG(Level::INFO,\n\t\t\"Reloader::reload_all: reload took %\" PRId64 \" seconds\",\n\t\tstatic_cast<int64_t>(dt));\n\n\tconst auto unread_feeds2 =\n\t\tctrl->get_feedcontainer()->unread_feed_count();\n\tconst auto unread_articles2 =\n\t\tctrl->get_feedcontainer()->unread_item_count();\n\tbool notify_always = cfg->get_configvalue_as_bool(\"notify-always\");\n\tif (notify_always || unread_feeds2 > unread_feeds ||\n\t\tunread_articles2 > unread_articles) {\n\t\tint article_count = unread_articles2 - unread_articles;\n\t\tint feed_count = unread_feeds2 - unread_feeds;\n\n\t\tLOG(Level::DEBUG, \"unread article count: %d\", article_count);\n\t\tLOG(Level::DEBUG, \"unread feed count: %d\", feed_count);\n\n\t\tFmtStrFormatter fmt;\n\t\tfmt.register_fmt('f', std::to_string(unread_feeds2));\n\t\tfmt.register_fmt('n', std::to_string(unread_articles2));\n\t\tfmt.register_fmt('d',\n\t\t\tstd::to_string(article_count >= 0 ? article_count : 0));\n\t\tfmt.register_fmt(\n\t\t\t'D', std::to_string(feed_count >= 0 ? feed_count : 0));\n\t\tnotify(fmt.do_format(cfg->get_configvalue(\"notify-format\")));\n\t}\n}\n\nvoid Reloader::reload_indexes(const std::vector<int>& indexes, bool unattended)\n{\n\tScopeMeasure m1(\"Reloader::reload_indexes\");\n\tconst auto unread_feeds =\n\t\tctrl->get_feedcontainer()->unread_feed_count();\n\tconst auto unread_articles =\n\t\tctrl->get_feedcontainer()->unread_item_count();\n\tconst auto size = ctrl->get_feedcontainer()->feeds_size();\n\n\tfor (const auto& idx : indexes) {\n\t\treload(idx, size, unattended);\n\t}\n\n\tconst auto unread_feeds2 =\n\t\tctrl->get_feedcontainer()->unread_feed_count();\n\tconst auto unread_articles2 =\n\t\tctrl->get_feedcontainer()->unread_item_count();\n\tbool notify_always = cfg->get_configvalue_as_bool(\"notify-always\");\n\tif (notify_always || unread_feeds2 != unread_feeds ||\n\t\tunread_articles2 != unread_articles) {\n\t\tFmtStrFormatter fmt;\n\t\tfmt.register_fmt('f', std::to_string(unread_feeds2));\n\t\tfmt.register_fmt('n', std::to_string(unread_articles2));\n\t\tfmt.register_fmt('d',\n\t\t\tstd::to_string(unread_articles2 - unread_articles));\n\t\tfmt.register_fmt(\n\t\t\t'D', std::to_string(unread_feeds2 - unread_feeds));\n\t\tnotify(fmt.do_format(cfg->get_configvalue(\"notify-format\")));\n\t}\n\tif (!unattended) {\n\t\tctrl->get_view()->set_status(\"\");\n\t}\n}\n\nvoid Reloader::reload_range(unsigned int start,\n\tunsigned int end,\n\tunsigned int size,\n\tbool unattended)\n{\n\tstd::vector<unsigned int> v;\n\tfor (unsigned int i = start; i <= end; ++i) {\n\t\tv.push_back(i);\n\t}\n\n\tauto extract = [](std::string& s, const std::string& url) {\n\t\tsize_t p = url.find(\"\/\/\");\n\t\tp = (p == std::string::npos) ? 0 : p + 2;\n\t\tstd::string suff(url.substr(p));\n\t\tp = suff.find('\/');\n\t\ts = suff.substr(0, p);\n\t};\n\n\tstd::sort(v.begin(), v.end(), [&](unsigned int a, unsigned int b) {\n\t\tstd::string domain1, domain2;\n\t\textract(domain1, ctrl->get_feedcontainer()->feeds[a]->rssurl());\n\t\textract(domain2, ctrl->get_feedcontainer()->feeds[b]->rssurl());\n\t\tstd::reverse(domain1.begin(), domain1.end());\n\t\tstd::reverse(domain2.begin(), domain2.end());\n\t\treturn domain1 < domain2;\n\t});\n\n\tCurlHandle easyhandle;\n\n\tfor (const auto& i : v) {\n\t\tLOG(Level::DEBUG,\n\t\t\t\"Reloader::reload_range: reloading feed #%u\",\n\t\t\ti);\n\t\treload(i, size, unattended, &easyhandle);\n\t}\n}\n\nvoid Reloader::notify(const std::string& msg)\n{\n\tif (cfg->get_configvalue_as_bool(\"notify-screen\")) {\n\t\tLOG(Level::DEBUG, \"reloader:notify: notifying screen\");\n\t\tstd::cout << \"\\033^\" << msg << \"\\033\\\\\";\n\t\tstd::cout.flush();\n\t}\n\tif (cfg->get_configvalue_as_bool(\"notify-xterm\")) {\n\t\tLOG(Level::DEBUG, \"reloader:notify: notifying xterm\");\n\t\tstd::cout << \"\\033]2;\" << msg << \"\\033\\\\\";\n\t\tstd::cout.flush();\n\t}\n\tif (cfg->get_configvalue_as_bool(\"notify-beep\")) {\n\t\tLOG(Level::DEBUG, \"reloader:notify: notifying beep\");\n\t\t::beep();\n\t}\n\tif (cfg->get_configvalue(\"notify-program\").length() > 0) {\n\t\tstd::string prog = cfg->get_configvalue(\"notify-program\");\n\t\tLOG(Level::DEBUG,\n\t\t\t\"reloader:notify: notifying external program `%s'\",\n\t\t\tprog);\n\t\tutils::run_command(prog, msg);\n\t}\n}\n\n} \/\/ namespace newsboat\n<commit_msg>Don't replace_feed for query feeds during reload<commit_after>#include \"reloader.h\"\n\n#include <algorithm>\n#include <cinttypes>\n#include <iostream>\n#include <ncurses.h>\n#include <thread>\n\n#include \"controller.h\"\n#include \"curlhandle.h\"\n#include \"dbexception.h\"\n#include \"downloadthread.h\"\n#include \"fmtstrformatter.h\"\n#include \"reloadrangethread.h\"\n#include \"reloadthread.h\"\n#include \"rss\/exception.h\"\n#include \"rssfeed.h\"\n#include \"rssparser.h\"\n#include \"scopemeasure.h\"\n#include \"utils.h\"\n#include \"view.h\"\n\nnamespace newsboat {\n\nReloader::Reloader(Controller* c, Cache* cc, ConfigContainer* cfg)\n\t: ctrl(c)\n\t, rsscache(cc)\n\t, cfg(cfg)\n{\n}\n\nvoid Reloader::spawn_reloadthread()\n{\n\tstd::thread t{ReloadThread(ctrl, cfg)};\n\tt.detach();\n}\n\nvoid Reloader::start_reload_all_thread(std::vector<int>* indexes)\n{\n\tLOG(Level::INFO, \"starting reload all thread\");\n\tstd::thread t(DownloadThread(*this, indexes));\n\tt.detach();\n}\n\nbool Reloader::trylock_reload_mutex()\n{\n\tif (reload_mutex.try_lock()) {\n\t\tLOG(Level::DEBUG, \"Reloader::trylock_reload_mutex succeeded\");\n\t\treturn true;\n\t}\n\tLOG(Level::DEBUG, \"Reloader::trylock_reload_mutex failed\");\n\treturn false;\n}\n\nvoid Reloader::reload(unsigned int pos,\n\tunsigned int max,\n\tbool unattended,\n\tCurlHandle* easyhandle)\n{\n\tLOG(Level::DEBUG, \"Reloader::reload: pos = %u max = %u\", pos, max);\n\tif (pos < ctrl->get_feedcontainer()->feeds.size()) {\n\t\tstd::shared_ptr<RssFeed> oldfeed =\n\t\t\tctrl->get_feedcontainer()->feeds[pos];\n\t\tstd::string errmsg;\n\t\tif (!unattended) {\n\t\t\tctrl->get_view()->set_status(\n\t\t\t\tstrprintf::fmt(_(\"%sLoading %s...\"),\n\t\t\t\t\tprepare_message(pos + 1, max),\n\t\t\t\t\tutils::censor_url(oldfeed->rssurl())));\n\t\t}\n\n\t\tbool ignore_dl =\n\t\t\t(cfg->get_configvalue(\"ignore-mode\") == \"download\");\n\n\t\tRssParser parser(oldfeed->rssurl(),\n\t\t\trsscache,\n\t\t\tcfg,\n\t\t\tignore_dl ? ctrl->get_ignores() : nullptr,\n\t\t\tctrl->get_api());\n\t\tparser.set_easyhandle(easyhandle);\n\t\tLOG(Level::DEBUG, \"Reloader::reload: created parser\");\n\t\ttry {\n\t\t\toldfeed->set_status(DlStatus::DURING_DOWNLOAD);\n\t\t\tstd::shared_ptr<RssFeed> newfeed = parser.parse();\n\t\t\tif (!newfeed->is_query_feed()) {\n\t\t\t\tctrl->replace_feed(\n\t\t\t\t\toldfeed, newfeed, pos, unattended);\n\t\t\t}\n\t\t\tif (newfeed->total_item_count() == 0) {\n\t\t\t\tLOG(Level::DEBUG,\n\t\t\t\t\t\"Reloader::reload: feed is empty\");\n\t\t\t}\n\t\t\toldfeed->set_status(DlStatus::SUCCESS);\n\t\t\tctrl->get_view()->set_status(\"\");\n\t\t} catch (const DbException& e) {\n\t\t\terrmsg = strprintf::fmt(\n\t\t\t\t\t_(\"Error while retrieving %s: %s\"),\n\t\t\t\t\tutils::censor_url(oldfeed->rssurl()),\n\t\t\t\t\te.what());\n\t\t} catch (const std::string& emsg) {\n\t\t\terrmsg = strprintf::fmt(\n\t\t\t\t\t_(\"Error while retrieving %s: %s\"),\n\t\t\t\t\tutils::censor_url(oldfeed->rssurl()),\n\t\t\t\t\temsg);\n\t\t} catch (rsspp::Exception& e) {\n\t\t\terrmsg = strprintf::fmt(\n\t\t\t\t\t_(\"Error while retrieving %s: %s\"),\n\t\t\t\t\tutils::censor_url(oldfeed->rssurl()),\n\t\t\t\t\te.what());\n\t\t}\n\t\tif (errmsg != \"\") {\n\t\t\toldfeed->set_status(DlStatus::DL_ERROR);\n\t\t\tctrl->get_view()->set_status(errmsg);\n\t\t\tLOG(Level::USERERROR, \"%s\", errmsg);\n\t\t}\n\t} else {\n\t\tctrl->get_view()->show_error(_(\"Error: invalid feed!\"));\n\t}\n}\n\nstd::string Reloader::prepare_message(unsigned int pos, unsigned int max)\n{\n\tif (max > 0) {\n\t\treturn strprintf::fmt(\"(%u\/%u) \", pos, max);\n\t}\n\treturn \"\";\n}\n\nvoid Reloader::reload_all(bool unattended)\n{\n\tconst auto unread_feeds =\n\t\tctrl->get_feedcontainer()->unread_feed_count();\n\tconst auto unread_articles =\n\t\tctrl->get_feedcontainer()->unread_item_count();\n\tint num_threads = cfg->get_configvalue_as_int(\"reload-threads\");\n\ttime_t t1, t2, dt;\n\n\tctrl->get_feedcontainer()->reset_feeds_status();\n\tconst auto num_feeds = ctrl->get_feedcontainer()->feeds_size();\n\n\t\/\/ TODO: change to std::clamp in C++17\n\tconst int min_threads = 1;\n\tconst int max_threads = num_feeds;\n\tnum_threads = std::max(min_threads, std::min(num_threads, max_threads));\n\n\tt1 = time(nullptr);\n\n\tLOG(Level::DEBUG, \"Reloader::reload_all: starting with reload all...\");\n\tif (num_threads == 1) {\n\t\treload_range(0, num_feeds - 1, num_feeds, unattended);\n\t} else {\n\t\tstd::vector<std::pair<unsigned int, unsigned int>> partitions =\n\t\t\t\tutils::partition_indexes(0, num_feeds - 1, num_threads);\n\t\tstd::vector<std::thread> threads;\n\t\tLOG(Level::DEBUG,\n\t\t\t\"Reloader::reload_all: starting reload threads...\");\n\t\tfor (int i = 0; i < num_threads - 1; i++) {\n\t\t\tthreads.push_back(std::thread(ReloadRangeThread(*this,\n\t\t\t\t\t\tpartitions[i].first,\n\t\t\t\t\t\tpartitions[i].second,\n\t\t\t\t\t\tnum_feeds,\n\t\t\t\t\t\tunattended)));\n\t\t}\n\t\tLOG(Level::DEBUG,\n\t\t\t\"Reloader::reload_all: starting my own reload...\");\n\t\treload_range(partitions[num_threads - 1].first,\n\t\t\tpartitions[num_threads - 1].second,\n\t\t\tnum_feeds,\n\t\t\tunattended);\n\t\tLOG(Level::DEBUG,\n\t\t\t\"Reloader::reload_all: joining other threads...\");\n\t\tfor (size_t i = 0; i < threads.size(); i++) {\n\t\t\tthreads[i].join();\n\t\t}\n\t}\n\n\t\/\/ refresh query feeds (update and sort)\n\tLOG(Level::DEBUG, \"Reloader::reload_all: refresh query feeds\");\n\tfor (const auto& feed : ctrl->get_feedcontainer()->feeds) {\n\t\tctrl->get_view()->prepare_query_feed(feed);\n\t}\n\tctrl->get_view()->force_redraw();\n\n\tctrl->get_feedcontainer()->sort_feeds(cfg->get_feed_sort_strategy());\n\tctrl->update_feedlist();\n\n\tt2 = time(nullptr);\n\tdt = t2 - t1;\n\t\/\/ On GCC, `time_t` is `long int`, which is at least 32 bits. On x86_64,\n\t\/\/ it's 64 bits. Thus, this cast is either a no-op, or an up-cast which are\n\t\/\/ always safe.\n\tLOG(Level::INFO,\n\t\t\"Reloader::reload_all: reload took %\" PRId64 \" seconds\",\n\t\tstatic_cast<int64_t>(dt));\n\n\tconst auto unread_feeds2 =\n\t\tctrl->get_feedcontainer()->unread_feed_count();\n\tconst auto unread_articles2 =\n\t\tctrl->get_feedcontainer()->unread_item_count();\n\tbool notify_always = cfg->get_configvalue_as_bool(\"notify-always\");\n\tif (notify_always || unread_feeds2 > unread_feeds ||\n\t\tunread_articles2 > unread_articles) {\n\t\tint article_count = unread_articles2 - unread_articles;\n\t\tint feed_count = unread_feeds2 - unread_feeds;\n\n\t\tLOG(Level::DEBUG, \"unread article count: %d\", article_count);\n\t\tLOG(Level::DEBUG, \"unread feed count: %d\", feed_count);\n\n\t\tFmtStrFormatter fmt;\n\t\tfmt.register_fmt('f', std::to_string(unread_feeds2));\n\t\tfmt.register_fmt('n', std::to_string(unread_articles2));\n\t\tfmt.register_fmt('d',\n\t\t\tstd::to_string(article_count >= 0 ? article_count : 0));\n\t\tfmt.register_fmt(\n\t\t\t'D', std::to_string(feed_count >= 0 ? feed_count : 0));\n\t\tnotify(fmt.do_format(cfg->get_configvalue(\"notify-format\")));\n\t}\n}\n\nvoid Reloader::reload_indexes(const std::vector<int>& indexes, bool unattended)\n{\n\tScopeMeasure m1(\"Reloader::reload_indexes\");\n\tconst auto unread_feeds =\n\t\tctrl->get_feedcontainer()->unread_feed_count();\n\tconst auto unread_articles =\n\t\tctrl->get_feedcontainer()->unread_item_count();\n\tconst auto size = ctrl->get_feedcontainer()->feeds_size();\n\n\tfor (const auto& idx : indexes) {\n\t\treload(idx, size, unattended);\n\t}\n\n\tconst auto unread_feeds2 =\n\t\tctrl->get_feedcontainer()->unread_feed_count();\n\tconst auto unread_articles2 =\n\t\tctrl->get_feedcontainer()->unread_item_count();\n\tbool notify_always = cfg->get_configvalue_as_bool(\"notify-always\");\n\tif (notify_always || unread_feeds2 != unread_feeds ||\n\t\tunread_articles2 != unread_articles) {\n\t\tFmtStrFormatter fmt;\n\t\tfmt.register_fmt('f', std::to_string(unread_feeds2));\n\t\tfmt.register_fmt('n', std::to_string(unread_articles2));\n\t\tfmt.register_fmt('d',\n\t\t\tstd::to_string(unread_articles2 - unread_articles));\n\t\tfmt.register_fmt(\n\t\t\t'D', std::to_string(unread_feeds2 - unread_feeds));\n\t\tnotify(fmt.do_format(cfg->get_configvalue(\"notify-format\")));\n\t}\n\tif (!unattended) {\n\t\tctrl->get_view()->set_status(\"\");\n\t}\n}\n\nvoid Reloader::reload_range(unsigned int start,\n\tunsigned int end,\n\tunsigned int size,\n\tbool unattended)\n{\n\tstd::vector<unsigned int> v;\n\tfor (unsigned int i = start; i <= end; ++i) {\n\t\tv.push_back(i);\n\t}\n\n\tauto extract = [](std::string& s, const std::string& url) {\n\t\tsize_t p = url.find(\"\/\/\");\n\t\tp = (p == std::string::npos) ? 0 : p + 2;\n\t\tstd::string suff(url.substr(p));\n\t\tp = suff.find('\/');\n\t\ts = suff.substr(0, p);\n\t};\n\n\tstd::sort(v.begin(), v.end(), [&](unsigned int a, unsigned int b) {\n\t\tstd::string domain1, domain2;\n\t\textract(domain1, ctrl->get_feedcontainer()->feeds[a]->rssurl());\n\t\textract(domain2, ctrl->get_feedcontainer()->feeds[b]->rssurl());\n\t\tstd::reverse(domain1.begin(), domain1.end());\n\t\tstd::reverse(domain2.begin(), domain2.end());\n\t\treturn domain1 < domain2;\n\t});\n\n\tCurlHandle easyhandle;\n\n\tfor (const auto& i : v) {\n\t\tLOG(Level::DEBUG,\n\t\t\t\"Reloader::reload_range: reloading feed #%u\",\n\t\t\ti);\n\t\treload(i, size, unattended, &easyhandle);\n\t}\n}\n\nvoid Reloader::notify(const std::string& msg)\n{\n\tif (cfg->get_configvalue_as_bool(\"notify-screen\")) {\n\t\tLOG(Level::DEBUG, \"reloader:notify: notifying screen\");\n\t\tstd::cout << \"\\033^\" << msg << \"\\033\\\\\";\n\t\tstd::cout.flush();\n\t}\n\tif (cfg->get_configvalue_as_bool(\"notify-xterm\")) {\n\t\tLOG(Level::DEBUG, \"reloader:notify: notifying xterm\");\n\t\tstd::cout << \"\\033]2;\" << msg << \"\\033\\\\\";\n\t\tstd::cout.flush();\n\t}\n\tif (cfg->get_configvalue_as_bool(\"notify-beep\")) {\n\t\tLOG(Level::DEBUG, \"reloader:notify: notifying beep\");\n\t\t::beep();\n\t}\n\tif (cfg->get_configvalue(\"notify-program\").length() > 0) {\n\t\tstd::string prog = cfg->get_configvalue(\"notify-program\");\n\t\tLOG(Level::DEBUG,\n\t\t\t\"reloader:notify: notifying external program `%s'\",\n\t\t\tprog);\n\t\tutils::run_command(prog, msg);\n\t}\n}\n\n} \/\/ namespace newsboat\n<|endoftext|>"} {"text":"<commit_before>#include \"renderer.hpp\"\r\n\r\n#include <algorithm>\r\n#include <fstream>\r\n#include <iostream>\r\n#include <string>\r\n#include <vector>\r\n\r\n#include \"addr_space.hpp\"\r\n#include \"address.hpp\"\r\n#include \"const.hpp\"\r\n#include \"cpu.hpp\"\r\n#include \"cursor.hpp\"\r\n#include \"drawing2D.hpp\"\r\n#include \"drawing3D.hpp\"\r\n#include \"instruction.hpp\"\r\n#include \"printer.hpp\"\r\n#include \"ram.hpp\"\r\n#include \"util.hpp\"\r\n\r\nusing namespace std;\r\n\r\n\/*\r\n * Only public method. Also static. It creates new object every time \r\n * it gets called.\r\n *\/\r\nvector<vector<string>> Renderer::renderState(const Printer &printerIn,\r\n const Ram &ramIn, \r\n const Cpu &cpuIn, \r\n const Cursor &cursorIn,\r\n const View &viewIn) {\r\n Renderer instance(printerIn, ramIn, cpuIn, cursorIn, viewIn);\r\n vector<vector<string>> out;\r\n for (vector<string> line : viewIn.lines) {\r\n out.push_back(instance.insertActualValues(line));\r\n }\r\n return out;\r\n}\r\n\r\nvector<string> Renderer::insertActualValues(vector<string> lineIn) {\r\n vector<bool> highlightedChars = getHighlightedLocations(lineIn);\r\n vector<string> lineOut;\r\n for (string cIn : lineIn) {\r\n string sOut;\r\n bool charIsALightbulb = ALL_INDICATORS.count(cIn);\r\n if (charIsALightbulb) {\r\n sOut = getLightbulb(cIn);\r\n } else {\r\n sOut = cIn;\r\n }\r\n lineOut.push_back(sOut);\r\n }\r\n return insertEscSeqences(lineOut, highlightedChars);\r\n}\r\n\r\nvector<string> Renderer::insertEscSeqences(\r\n vector<string> lineWithoutEscapeSeqences, vector<bool> highlightedChars) {\r\n vector<string> lineOut;\r\n bool insideHighlightBlock = false;\r\n for (size_t i = 0; i < lineWithoutEscapeSeqences.size(); i++) {\r\n bool firstCharInsideBlock = highlightedChars[i] && !insideHighlightBlock;\r\n if (firstCharInsideBlock) {\r\n vector<string> highlightEsc = Util::stringToVecOfString(HIGHLIGHT_ESC);\r\n lineOut.insert(lineOut.end(), highlightEsc.begin(), highlightEsc.end());\r\n insideHighlightBlock = true;\r\n }\r\n bool firstCharOutsideBlock = !highlightedChars[i] && insideHighlightBlock;\r\n if (firstCharOutsideBlock) {\r\n vector<string> highlightEscEnd = \r\n Util::stringToVecOfString(HIGHLIGHT_END_ESC);\r\n lineOut.insert(lineOut.end(), highlightEscEnd.begin(), \r\n highlightEscEnd.end());\r\n insideHighlightBlock = false;\r\n }\r\n lineOut.push_back(lineWithoutEscapeSeqences[i]);\r\n }\r\n return lineOut;\r\n}\r\n\r\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\/\/\/ GET HIGHLIGHTED LOCATIONS \/\/\/\r\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\r\nvector<bool> Renderer::getHighlightedLocations(vector<string> lineIn) {\r\n vector<bool> highlightedLocations (lineIn.size(), false);\r\n highlightPc(highlightedLocations, lineIn);\r\n highlightCursor(highlightedLocations, lineIn);\r\n Instruction *inst = getInstruction();\r\n if (inst == NULL) {\r\n highlightPointingInstructions(highlightedLocations, lineIn);\r\n return highlightedLocations;\r\n }\r\n highlightOperator(highlightedLocations, lineIn, inst);\r\n if (inst->adr.space == CODE) {\r\n highlightCodeWord(highlightedLocations, lineIn, inst);\r\n } else if (inst->adr.space == DATA) {\r\n highlightDataWord(highlightedLocations, lineIn, inst);\r\n }\r\n return highlightedLocations;\r\n}\r\n\r\nvoid Renderer::highlightPc(vector<bool> &highlightedLocations,\r\n vector<string> &lineIn) {\r\n if (!machineActive() || pcHighlighted) {\r\n return;\r\n }\r\n for (size_t i = 0; i < lineIn.size(); i++) {\r\n if (lineIn[i] == CODE_ADR_INDICATOR) {\r\n int index = switchIndex[CODE_ADR_INDICATOR];\r\n if (pcPointingToAddress(index)) {\r\n highlightedLocations[i] = true;\r\n pcHighlighted = true;\r\n return;\r\n }\r\n }\r\n }\r\n}\r\n\r\nvoid Renderer::highlightCursor(vector<bool> &highlightedLocations,\r\n vector<string> &lineIn) {\r\n if (machineActive() || cursorHighlighted) {\r\n return;\r\n }\r\n if (cursor.getAddressSpace() == CODE) {\r\n findCursor(highlightedLocations, lineIn, CODE_INDICATOR);\r\n } else if (cursor.getAddressSpace() == DATA) {\r\n findCursor(highlightedLocations, lineIn, DATA_INDICATOR);\r\n }\r\n}\r\n\r\nvoid Renderer::findCursor(vector<bool> &highlightedLocations,\r\n vector<string> &lineIn, string c) {\r\n int indexDelta = 0;\r\n for (size_t i = 0; i < lineIn.size(); i++) {\r\n if (lineIn[i] == c) {\r\n int lightbulbIndex = switchIndex[c] + indexDelta++;\r\n if (cursor.getAbsoluteBitIndex() == lightbulbIndex) {\r\n highlightedLocations[i] = true;\r\n cursorHighlighted = true;\r\n return;\r\n }\r\n }\r\n }\r\n}\r\n\r\nvoid Renderer::highlightPointingInstructions(vector<bool> &highlightedLocations,\r\n vector<string> &lineIn) {\r\n set<int> *pointingInstructions = getIndexesOfPointingInstructions();\r\n for (size_t i = 0; i < lineIn.size(); i++) {\r\n if (lineIn[i] == CODE_INDICATOR) {\r\n int addressValue = switchIndex[CODE_INDICATOR] \/ WORD_SIZE;\r\n if (pointingInstructions->count(addressValue)) {\r\n highlightedLocations[i] = true;\r\n }\r\n }\r\n }\r\n}\r\n\r\nvoid Renderer::highlightOperator(vector<bool> &highlightedLocations,\r\n vector<string> &lineIn,\r\n Instruction *inst) {\r\n string exclude;\r\n if (inst->isLogic()) {\r\n exclude = LOGIC_OPS_INDICATOR[min(inst->logicIndex, 8)];\r\n }\r\n if (inst->index == INC_DEC_OPS_INDEX) {\r\n if (inst->logicIndex <= 7) {\r\n exclude = \"INC\";\r\n } else {\r\n exclude = \"DEC\";\r\n }\r\n }\r\n string label = \" \" + inst->label;\r\n label.append(11 - inst->label.length(), ' '); \r\n highlightLabel(highlightedLocations, lineIn, Util::stringToVecOfString(label), \r\n Util::stringToVecOfString(exclude));\r\n}\r\n\r\nvoid Renderer::highlightCodeWord(vector<bool> &highlightedLocations,\r\n vector<string> &lineIn,\r\n Instruction *inst) {\r\n if (inst->adr.val == LAST_ADDRESS) {\r\n vector<string> stopLabel = Util::stringToVecOfString(LAST_CODE_ADDR_LABEL);\r\n highlightLabel(highlightedLocations, lineIn, stopLabel, {});\r\n return;\r\n }\r\n highlightWord(highlightedLocations, lineIn, CODE_INDICATOR, CODE);\r\n}\r\n\r\nvoid Renderer::highlightDataWord(vector<bool> &highlightedLocations,\r\n vector<string> &lineIn,\r\n Instruction *inst) {\r\n if (inst->adr.val == LAST_ADDRESS) {\r\n vector<string> inOutLabel = Util::stringToVecOfString(LAST_DATA_ADDR_LABEL);\r\n highlightLabel(highlightedLocations, lineIn, inOutLabel, {});\r\n return;\r\n }\r\n highlightWord(highlightedLocations, lineIn, DATA_INDICATOR, DATA);\r\n}\r\n\r\nvoid Renderer::highlightWord(vector<bool> &highlightedLocations,\r\n vector<string> &lineIn, string indicator,\r\n AddrSpace addrSpace) {\r\n for (size_t i = 0; i < lineIn.size(); i++) {\r\n if (lineIn[i] == indicator) {\r\n int addressValue = switchIndex[indicator] \/ WORD_SIZE;\r\n Address adr = Address(addrSpace, Util::getBoolNibb(addressValue));\r\n if (instructionPointingToAddress(adr)) {\r\n highlightedLocations[i] = true;\r\n }\r\n }\r\n }\r\n}\r\n\r\nvoid Renderer::highlightLabel(vector<bool> &highlightedLocations,\r\n vector<string> &lineIn,\r\n vector<string> label,\r\n vector<string> exclude) {\r\n auto it = search(begin(lineIn), end(lineIn), begin(label), end(label));\r\n int labelPosition = it - lineIn.begin();\r\n bool notFound = it == end(lineIn);\r\n if (notFound) {\r\n return;\r\n }\r\n size_t excludePosition = numeric_limits<size_t>::max();\r\n if (!exclude.empty()) {\r\n it = search(begin(label), end(label), begin(exclude), end(exclude));\r\n excludePosition = it - label.begin();\r\n }\r\n for (size_t i = labelPosition; i < labelPosition + label.size(); i++) {\r\n bool highlight = (i < labelPosition + excludePosition ||\r\n i >= labelPosition + excludePosition + exclude.size());\r\n if (highlight) {\r\n highlightedLocations[i] = true;\r\n }\r\n }\r\n}\r\n\r\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\/\/\/ GET LIGHTBULB \/\/\/\r\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\r\nstring Renderer::getLightbulb(string cIn) {\r\n int i = switchIndex[cIn]++;\r\n if (cIn == CODE_INDICATOR) {\r\n return getCodeBit(i);\r\n } else if (cIn == DATA_INDICATOR) {\r\n return getDataBit(i);\r\n } else if (cIn == REGISTER_INDICATOR) {\r\n return view.getLightbulb(cpu.getRegister().at(i));\r\n } else if (cIn == CODE_ADR_INDICATOR) {\r\n return getAdrIndicator(CODE, i);\r\n } else if (cIn == DATA_ADR_INDICATOR) {\r\n return getAdrIndicator(DATA, i);\r\n } else if (cIn == OUTPUT_INDICATOR) {\r\n return getFormattedOutput(i);\r\n }\r\n cerr << \"There was an error parsing a drawing file.\";\r\n cerr << \" Problem with char\" << cIn << \". Will ignore it.\";\r\n return \" \";\r\n}\r\n\r\nstring Renderer::getCodeBit(int i) {\r\n return getCharAt(i, &ram.state[CODE]);\r\n}\r\n\r\nstring Renderer::getDataBit(int i) {\r\n return getCharAt(i, &ram.state[DATA]);\r\n}\r\n\r\nstring Renderer::getCharAt(int i, vector<vector<bool>>* matrix) {\r\n int j = i \/ WORD_SIZE;\r\n i = i % WORD_SIZE;\r\n return view.getLightbulb((*matrix).at(j).at(i));\r\n}\r\n\r\nbool Renderer::pcPointingToAddress(int adr) {\r\n bool executionHasntStarted = cpu.getCycle() == 0;\r\n if (executionHasntStarted) {\r\n return false;\r\n }\r\n return Util::getInt(cpu.getPc()) == adr;\r\n}\r\n\r\nstring Renderer::getAdrIndicator(AddrSpace addrSpace, int index) {\r\n Address indicatorsAddress = Address(addrSpace, Util::getBoolNibb(index));\r\n bool addressReferenced = isAddressReferenced(indicatorsAddress);\r\n return view.getLightbulb(addressReferenced);\r\n}\r\n\r\nstring Renderer::getFormattedOutput(int i) {\r\n if (printer.getPrinterOutput().length() <= (unsigned) i) {\r\n return \" \";\r\n } else {\r\n return string(1, printer.getPrinterOutput().at(i));\r\n }\r\n}\r\n\r\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\/\/\/ GET INSTRUCTION \/\/\/\r\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\r\nInstruction* Renderer::getInstruction() {\r\n bool noActiveInstruction = !machineActive() &&\r\n cursor.getAddressSpace() == DATA;\r\n if (noActiveInstruction) {\r\n return NULL;\r\n }\r\n if (instruction.size() == 0) {\r\n instruction.push_back(initializeInstruction());\r\n }\r\n return &instruction[0];\r\n}\r\n\r\nbool Renderer::machineActive() {\r\n bool executionHasntStarted = cpu.getCycle() == 0;\r\n bool executionEnded = Util::getInt(cpu.getPc()) == RAM_SIZE;\r\n return !(executionHasntStarted || executionEnded);\r\n}\r\n\r\nInstruction Renderer::initializeInstruction() {\r\n if (machineActive()) {\r\n return cpu.getInstruction();\r\n } else {\r\n return Instruction(cursor.getWord(), EMPTY_WORD, ram);\r\n }\r\n}\r\n\r\nbool Renderer::instructionHasId(int id) {\r\n Instruction *inst = getInstruction();\r\n if (inst == NULL) {\r\n return false;\r\n }\r\n return inst->index == id;\r\n}\r\n\r\n\/*\r\n * Is instruction pointing to passed address in passed address space.\r\n *\/\r\nbool Renderer::instructionPointingToAddress(Address adr) {\r\n Instruction *inst = getInstruction();\r\n if (inst == NULL) {\r\n return false;\r\n }\r\n return inst->adr == adr;\r\n}\r\n\r\nset<int>* Renderer::getIndexesOfPointingInstructions() {\r\n if (pointingInstructions.empty()) {\r\n pointingInstructions = generatePointingInstructions();\r\n if (pointingInstructions.empty()) {\r\n pointingInstructions.insert(-1);\r\n }\r\n }\r\n return &pointingInstructions;\r\n}\r\n\r\nset<int> Renderer::generatePointingInstructions() {\r\n vector<Instruction> *allInstructions = getAllInstructions();\r\n set<int> out;\r\n int i = 0;\r\n for (Instruction inst : *allInstructions) {\r\n if (inst.adr == cursor.getAddress()) {\r\n out.insert(i);\r\n }\r\n i++;\r\n }\r\n return out;\r\n}\r\n\r\nvector<Instruction>* Renderer::getAllInstructions() {\r\n if (allInstructions.empty()) {\r\n for (vector<bool> word : ram.state.at(CODE)) {\r\n Instruction inst = Instruction(word, cpu.getRegister(), ram);\r\n allInstructions.push_back(inst);\r\n }\r\n }\r\n return &allInstructions;\r\n}\r\n\r\nbool Renderer::isAddressReferenced(Address adr) {\r\n vector<Instruction> *instructions = getAllInstructions();\r\n for (Instruction inst : *instructions) {\r\n if (inst.adr == adr) {\r\n return true;\r\n }\r\n }\r\n return false;\r\n}<commit_msg>If word with cursor is highlighted, cursor gets inverted<commit_after>#include \"renderer.hpp\"\r\n\r\n#include <algorithm>\r\n#include <fstream>\r\n#include <iostream>\r\n#include <string>\r\n#include <vector>\r\n\r\n#include \"addr_space.hpp\"\r\n#include \"address.hpp\"\r\n#include \"const.hpp\"\r\n#include \"cpu.hpp\"\r\n#include \"cursor.hpp\"\r\n#include \"drawing2D.hpp\"\r\n#include \"drawing3D.hpp\"\r\n#include \"instruction.hpp\"\r\n#include \"printer.hpp\"\r\n#include \"ram.hpp\"\r\n#include \"util.hpp\"\r\n\r\nusing namespace std;\r\n\r\n\/*\r\n * Only public method. Also static. It creates new object every time \r\n * it gets called.\r\n *\/\r\nvector<vector<string>> Renderer::renderState(const Printer &printerIn,\r\n const Ram &ramIn, \r\n const Cpu &cpuIn, \r\n const Cursor &cursorIn,\r\n const View &viewIn) {\r\n Renderer instance(printerIn, ramIn, cpuIn, cursorIn, viewIn);\r\n vector<vector<string>> out;\r\n for (vector<string> line : viewIn.lines) {\r\n out.push_back(instance.insertActualValues(line));\r\n }\r\n return out;\r\n}\r\n\r\nvector<string> Renderer::insertActualValues(vector<string> lineIn) {\r\n vector<bool> highlightedChars = getHighlightedLocations(lineIn);\r\n vector<string> lineOut;\r\n for (string cIn : lineIn) {\r\n string sOut;\r\n bool charIsALightbulb = ALL_INDICATORS.count(cIn);\r\n if (charIsALightbulb) {\r\n sOut = getLightbulb(cIn);\r\n } else {\r\n sOut = cIn;\r\n }\r\n lineOut.push_back(sOut);\r\n }\r\n return insertEscSeqences(lineOut, highlightedChars);\r\n}\r\n\r\nvector<string> Renderer::insertEscSeqences(\r\n vector<string> lineWithoutEscapeSeqences, vector<bool> highlightedChars) {\r\n vector<string> lineOut;\r\n bool insideHighlightBlock = false;\r\n for (size_t i = 0; i < lineWithoutEscapeSeqences.size(); i++) {\r\n bool firstCharInsideBlock = highlightedChars[i] && !insideHighlightBlock;\r\n if (firstCharInsideBlock) {\r\n vector<string> highlightEsc = Util::stringToVecOfString(HIGHLIGHT_ESC);\r\n lineOut.insert(lineOut.end(), highlightEsc.begin(), highlightEsc.end());\r\n insideHighlightBlock = true;\r\n }\r\n bool firstCharOutsideBlock = !highlightedChars[i] && insideHighlightBlock;\r\n if (firstCharOutsideBlock) {\r\n vector<string> highlightEscEnd = \r\n Util::stringToVecOfString(HIGHLIGHT_END_ESC);\r\n lineOut.insert(lineOut.end(), highlightEscEnd.begin(), \r\n highlightEscEnd.end());\r\n insideHighlightBlock = false;\r\n }\r\n lineOut.push_back(lineWithoutEscapeSeqences[i]);\r\n }\r\n return lineOut;\r\n}\r\n\r\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\/\/\/ GET HIGHLIGHTED LOCATIONS \/\/\/\r\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\r\nvector<bool> Renderer::getHighlightedLocations(vector<string> lineIn) {\r\n vector<bool> highlightedLocations (lineIn.size(), false);\r\n highlightPc(highlightedLocations, lineIn);\r\n highlightCursor(highlightedLocations, lineIn);\r\n Instruction *inst = getInstruction();\r\n if (inst == NULL) {\r\n highlightPointingInstructions(highlightedLocations, lineIn);\r\n return highlightedLocations;\r\n }\r\n highlightOperator(highlightedLocations, lineIn, inst);\r\n if (inst->adr.space == CODE) {\r\n highlightCodeWord(highlightedLocations, lineIn, inst);\r\n } else if (inst->adr.space == DATA) {\r\n highlightDataWord(highlightedLocations, lineIn, inst);\r\n }\r\n return highlightedLocations;\r\n}\r\n\r\nvoid Renderer::highlightPc(vector<bool> &highlightedLocations,\r\n vector<string> &lineIn) {\r\n if (!machineActive() || pcHighlighted) {\r\n return;\r\n }\r\n for (size_t i = 0; i < lineIn.size(); i++) {\r\n if (lineIn[i] == CODE_ADR_INDICATOR) {\r\n int index = switchIndex[CODE_ADR_INDICATOR];\r\n if (pcPointingToAddress(index)) {\r\n highlightedLocations[i] = true;\r\n pcHighlighted = true;\r\n return;\r\n }\r\n }\r\n }\r\n}\r\n\r\nvoid Renderer::highlightCursor(vector<bool> &highlightedLocations,\r\n vector<string> &lineIn) {\r\n if (machineActive() || cursorHighlighted) {\r\n return;\r\n }\r\n if (cursor.getAddressSpace() == CODE) {\r\n findCursor(highlightedLocations, lineIn, CODE_INDICATOR);\r\n } else if (cursor.getAddressSpace() == DATA) {\r\n findCursor(highlightedLocations, lineIn, DATA_INDICATOR);\r\n }\r\n}\r\n\r\nvoid Renderer::findCursor(vector<bool> &highlightedLocations,\r\n vector<string> &lineIn, string c) {\r\n int indexDelta = 0;\r\n for (size_t i = 0; i < lineIn.size(); i++) {\r\n if (lineIn[i] == c) {\r\n int lightbulbIndex = switchIndex[c] + indexDelta++;\r\n if (cursor.getAbsoluteBitIndex() == lightbulbIndex) {\r\n highlightedLocations[i] = true;\r\n cursorHighlighted = true;\r\n return;\r\n }\r\n }\r\n }\r\n}\r\n\r\nvoid Renderer::highlightPointingInstructions(vector<bool> &highlightedLocations,\r\n vector<string> &lineIn) {\r\n set<int> *pointingInstructions = getIndexesOfPointingInstructions();\r\n for (size_t i = 0; i < lineIn.size(); i++) {\r\n if (lineIn[i] == CODE_INDICATOR) {\r\n int addressValue = switchIndex[CODE_INDICATOR] \/ WORD_SIZE;\r\n if (pointingInstructions->count(addressValue)) {\r\n highlightedLocations[i] = true;\r\n }\r\n }\r\n }\r\n}\r\n\r\nvoid Renderer::highlightOperator(vector<bool> &highlightedLocations,\r\n vector<string> &lineIn,\r\n Instruction *inst) {\r\n string exclude;\r\n if (inst->isLogic()) {\r\n exclude = LOGIC_OPS_INDICATOR[min(inst->logicIndex, 8)];\r\n }\r\n if (inst->index == INC_DEC_OPS_INDEX) {\r\n if (inst->logicIndex <= 7) {\r\n exclude = \"INC\";\r\n } else {\r\n exclude = \"DEC\";\r\n }\r\n }\r\n string label = \" \" + inst->label;\r\n label.append(11 - inst->label.length(), ' '); \r\n highlightLabel(highlightedLocations, lineIn, Util::stringToVecOfString(label), \r\n Util::stringToVecOfString(exclude));\r\n}\r\n\r\nvoid Renderer::highlightCodeWord(vector<bool> &highlightedLocations,\r\n vector<string> &lineIn,\r\n Instruction *inst) {\r\n if (inst->adr.val == LAST_ADDRESS) {\r\n vector<string> stopLabel = Util::stringToVecOfString(LAST_CODE_ADDR_LABEL);\r\n highlightLabel(highlightedLocations, lineIn, stopLabel, {});\r\n return;\r\n }\r\n highlightWord(highlightedLocations, lineIn, CODE_INDICATOR, CODE);\r\n}\r\n\r\nvoid Renderer::highlightDataWord(vector<bool> &highlightedLocations,\r\n vector<string> &lineIn,\r\n Instruction *inst) {\r\n if (inst->adr.val == LAST_ADDRESS) {\r\n vector<string> inOutLabel = Util::stringToVecOfString(LAST_DATA_ADDR_LABEL);\r\n highlightLabel(highlightedLocations, lineIn, inOutLabel, {});\r\n return;\r\n }\r\n highlightWord(highlightedLocations, lineIn, DATA_INDICATOR, DATA);\r\n}\r\n\r\nvoid Renderer::highlightWord(vector<bool> &highlightedLocations,\r\n vector<string> &lineIn, string indicator,\r\n AddrSpace addrSpace) {\r\n for (size_t i = 0; i < lineIn.size(); i++) {\r\n if (lineIn[i] == indicator) {\r\n int addressValue = switchIndex[indicator] \/ WORD_SIZE;\r\n Address adr = Address(addrSpace, Util::getBoolNibb(addressValue));\r\n if (instructionPointingToAddress(adr)) {\r\n highlightedLocations[i] = !highlightedLocations[i];\r\n }\r\n }\r\n }\r\n}\r\n\r\nvoid Renderer::highlightLabel(vector<bool> &highlightedLocations,\r\n vector<string> &lineIn,\r\n vector<string> label,\r\n vector<string> exclude) {\r\n auto it = search(begin(lineIn), end(lineIn), begin(label), end(label));\r\n int labelPosition = it - lineIn.begin();\r\n bool notFound = it == end(lineIn);\r\n if (notFound) {\r\n return;\r\n }\r\n size_t excludePosition = numeric_limits<size_t>::max();\r\n if (!exclude.empty()) {\r\n it = search(begin(label), end(label), begin(exclude), end(exclude));\r\n excludePosition = it - label.begin();\r\n }\r\n for (size_t i = labelPosition; i < labelPosition + label.size(); i++) {\r\n bool highlight = (i < labelPosition + excludePosition ||\r\n i >= labelPosition + excludePosition + exclude.size());\r\n if (highlight) {\r\n highlightedLocations[i] = true;\r\n }\r\n }\r\n}\r\n\r\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\/\/\/ GET LIGHTBULB \/\/\/\r\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\r\nstring Renderer::getLightbulb(string cIn) {\r\n int i = switchIndex[cIn]++;\r\n if (cIn == CODE_INDICATOR) {\r\n return getCodeBit(i);\r\n } else if (cIn == DATA_INDICATOR) {\r\n return getDataBit(i);\r\n } else if (cIn == REGISTER_INDICATOR) {\r\n return view.getLightbulb(cpu.getRegister().at(i));\r\n } else if (cIn == CODE_ADR_INDICATOR) {\r\n return getAdrIndicator(CODE, i);\r\n } else if (cIn == DATA_ADR_INDICATOR) {\r\n return getAdrIndicator(DATA, i);\r\n } else if (cIn == OUTPUT_INDICATOR) {\r\n return getFormattedOutput(i);\r\n }\r\n cerr << \"There was an error parsing a drawing file.\";\r\n cerr << \" Problem with char\" << cIn << \". Will ignore it.\";\r\n return \" \";\r\n}\r\n\r\nstring Renderer::getCodeBit(int i) {\r\n return getCharAt(i, &ram.state[CODE]);\r\n}\r\n\r\nstring Renderer::getDataBit(int i) {\r\n return getCharAt(i, &ram.state[DATA]);\r\n}\r\n\r\nstring Renderer::getCharAt(int i, vector<vector<bool>>* matrix) {\r\n int j = i \/ WORD_SIZE;\r\n i = i % WORD_SIZE;\r\n return view.getLightbulb((*matrix).at(j).at(i));\r\n}\r\n\r\nbool Renderer::pcPointingToAddress(int adr) {\r\n bool executionHasntStarted = cpu.getCycle() == 0;\r\n if (executionHasntStarted) {\r\n return false;\r\n }\r\n return Util::getInt(cpu.getPc()) == adr;\r\n}\r\n\r\nstring Renderer::getAdrIndicator(AddrSpace addrSpace, int index) {\r\n Address indicatorsAddress = Address(addrSpace, Util::getBoolNibb(index));\r\n bool addressReferenced = isAddressReferenced(indicatorsAddress);\r\n return view.getLightbulb(addressReferenced);\r\n}\r\n\r\nstring Renderer::getFormattedOutput(int i) {\r\n if (printer.getPrinterOutput().length() <= (unsigned) i) {\r\n return \" \";\r\n } else {\r\n return string(1, printer.getPrinterOutput().at(i));\r\n }\r\n}\r\n\r\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\/\/\/ GET INSTRUCTION \/\/\/\r\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\r\nInstruction* Renderer::getInstruction() {\r\n bool noActiveInstruction = !machineActive() &&\r\n cursor.getAddressSpace() == DATA;\r\n if (noActiveInstruction) {\r\n return NULL;\r\n }\r\n if (instruction.size() == 0) {\r\n instruction.push_back(initializeInstruction());\r\n }\r\n return &instruction[0];\r\n}\r\n\r\nbool Renderer::machineActive() {\r\n bool executionHasntStarted = cpu.getCycle() == 0;\r\n bool executionEnded = Util::getInt(cpu.getPc()) == RAM_SIZE;\r\n return !(executionHasntStarted || executionEnded);\r\n}\r\n\r\nInstruction Renderer::initializeInstruction() {\r\n if (machineActive()) {\r\n return cpu.getInstruction();\r\n } else {\r\n return Instruction(cursor.getWord(), EMPTY_WORD, ram);\r\n }\r\n}\r\n\r\nbool Renderer::instructionHasId(int id) {\r\n Instruction *inst = getInstruction();\r\n if (inst == NULL) {\r\n return false;\r\n }\r\n return inst->index == id;\r\n}\r\n\r\n\/*\r\n * Is instruction pointing to passed address in passed address space.\r\n *\/\r\nbool Renderer::instructionPointingToAddress(Address adr) {\r\n Instruction *inst = getInstruction();\r\n if (inst == NULL) {\r\n return false;\r\n }\r\n return inst->adr == adr;\r\n}\r\n\r\nset<int>* Renderer::getIndexesOfPointingInstructions() {\r\n if (pointingInstructions.empty()) {\r\n pointingInstructions = generatePointingInstructions();\r\n if (pointingInstructions.empty()) {\r\n pointingInstructions.insert(-1);\r\n }\r\n }\r\n return &pointingInstructions;\r\n}\r\n\r\nset<int> Renderer::generatePointingInstructions() {\r\n vector<Instruction> *allInstructions = getAllInstructions();\r\n set<int> out;\r\n int i = 0;\r\n for (Instruction inst : *allInstructions) {\r\n if (inst.adr == cursor.getAddress()) {\r\n out.insert(i);\r\n }\r\n i++;\r\n }\r\n return out;\r\n}\r\n\r\nvector<Instruction>* Renderer::getAllInstructions() {\r\n if (allInstructions.empty()) {\r\n for (vector<bool> word : ram.state.at(CODE)) {\r\n Instruction inst = Instruction(word, cpu.getRegister(), ram);\r\n allInstructions.push_back(inst);\r\n }\r\n }\r\n return &allInstructions;\r\n}\r\n\r\nbool Renderer::isAddressReferenced(Address adr) {\r\n vector<Instruction> *instructions = getAllInstructions();\r\n for (Instruction inst : *instructions) {\r\n if (inst.adr == adr) {\r\n return true;\r\n }\r\n }\r\n return false;\r\n}<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2014 MongoDB Inc.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include <bsoncxx\/oid.hpp>\n\n#include <cstring>\n\n#include <bson.h>\n\n#include <bsoncxx\/config\/prelude.hpp>\n\nnamespace bsoncxx {\nBSONCXX_INLINE_NAMESPACE_BEGIN\n\noid::oid() : _is_valid(false) {\n}\n\noid::oid(init_tag_t) : _is_valid(true) {\n bson_oid_t oid;\n bson_oid_init(&oid, nullptr);\n\n std::memcpy(_bytes, oid.bytes, sizeof(oid.bytes));\n}\n\noid::oid(stdx::string_view str) : _is_valid(bson_oid_is_valid(str.data(), str.length())) {\n if (_is_valid) {\n bson_oid_t oid;\n bson_oid_init_from_string(&oid, str.data());\n memcpy(_bytes, oid.bytes, sizeof(_bytes));\n }\n}\n\noid::oid(const char* bytes, std::size_t len) : _is_valid(len == 12) {\n if (_is_valid) {\n std::memcpy(_bytes, bytes, sizeof(_bytes));\n }\n}\n\nstd::string oid::to_string() const {\n bson_oid_t oid;\n std::memcpy(oid.bytes, _bytes, sizeof(oid.bytes));\n char str[25];\n\n bson_oid_to_string(&oid, str);\n\n return std::string(str);\n}\n\noid::operator bool() const {\n return _is_valid;\n}\n\nstd::time_t oid::get_time_t() const {\n bson_oid_t oid;\n std::memcpy(oid.bytes, _bytes, sizeof(oid.bytes));\n\n return bson_oid_get_time_t(&oid);\n}\n\nconst char* oid::bytes() const {\n return _bytes;\n}\n\nint oid_compare(const oid& lhs, const oid& rhs) {\n if (!lhs._is_valid || !rhs._is_valid) {\n if (lhs._is_valid) {\n return 1;\n } else if (rhs._is_valid) {\n return -1;\n } else {\n return 0;\n }\n }\n\n bson_oid_t lhs_oid;\n bson_oid_t rhs_oid;\n\n std::memcpy(lhs_oid.bytes, lhs.bytes(), sizeof(lhs_oid.bytes));\n std::memcpy(rhs_oid.bytes, rhs.bytes(), sizeof(rhs_oid.bytes));\n\n return bson_oid_compare(&lhs_oid, &rhs_oid);\n}\n\nbool operator<(const oid& lhs, const oid& rhs) {\n return oid_compare(lhs, rhs) < 0;\n}\n\nbool operator>(const oid& lhs, const oid& rhs) {\n return oid_compare(lhs, rhs) > 0;\n}\n\nbool operator<=(const oid& lhs, const oid& rhs) {\n return oid_compare(lhs, rhs) <= 0;\n}\n\nbool operator>=(const oid& lhs, const oid& rhs) {\n return oid_compare(lhs, rhs) >= 0;\n}\n\nbool operator==(const oid& lhs, const oid& rhs) {\n return oid_compare(lhs, rhs) == 0;\n}\n\nbool operator!=(const oid& lhs, const oid& rhs) {\n return oid_compare(lhs, rhs) != 0;\n}\n\nstd::ostream& operator<<(std::ostream& out, const oid& rhs) {\n bson_oid_t oid;\n std::memcpy(oid.bytes, rhs._bytes, sizeof(oid.bytes));\n char str[25];\n\n bson_oid_to_string(&oid, str);\n\n out << str;\n\n return out;\n}\n\nBSONCXX_INLINE_NAMESPACE_END\n} \/\/ namespace bsoncxx\n<commit_msg>minor: add <ostream> header to bsoncxx\/oid.cpp<commit_after>\/\/ Copyright 2014 MongoDB Inc.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include <bsoncxx\/oid.hpp>\n\n#include <cstring>\n#include <ostream>\n\n#include <bson.h>\n\n#include <bsoncxx\/config\/prelude.hpp>\n\nnamespace bsoncxx {\nBSONCXX_INLINE_NAMESPACE_BEGIN\n\noid::oid() : _is_valid(false) {\n}\n\noid::oid(init_tag_t) : _is_valid(true) {\n bson_oid_t oid;\n bson_oid_init(&oid, nullptr);\n\n std::memcpy(_bytes, oid.bytes, sizeof(oid.bytes));\n}\n\noid::oid(stdx::string_view str) : _is_valid(bson_oid_is_valid(str.data(), str.length())) {\n if (_is_valid) {\n bson_oid_t oid;\n bson_oid_init_from_string(&oid, str.data());\n memcpy(_bytes, oid.bytes, sizeof(_bytes));\n }\n}\n\noid::oid(const char* bytes, std::size_t len) : _is_valid(len == 12) {\n if (_is_valid) {\n std::memcpy(_bytes, bytes, sizeof(_bytes));\n }\n}\n\nstd::string oid::to_string() const {\n bson_oid_t oid;\n std::memcpy(oid.bytes, _bytes, sizeof(oid.bytes));\n char str[25];\n\n bson_oid_to_string(&oid, str);\n\n return std::string(str);\n}\n\noid::operator bool() const {\n return _is_valid;\n}\n\nstd::time_t oid::get_time_t() const {\n bson_oid_t oid;\n std::memcpy(oid.bytes, _bytes, sizeof(oid.bytes));\n\n return bson_oid_get_time_t(&oid);\n}\n\nconst char* oid::bytes() const {\n return _bytes;\n}\n\nint oid_compare(const oid& lhs, const oid& rhs) {\n if (!lhs._is_valid || !rhs._is_valid) {\n if (lhs._is_valid) {\n return 1;\n } else if (rhs._is_valid) {\n return -1;\n } else {\n return 0;\n }\n }\n\n bson_oid_t lhs_oid;\n bson_oid_t rhs_oid;\n\n std::memcpy(lhs_oid.bytes, lhs.bytes(), sizeof(lhs_oid.bytes));\n std::memcpy(rhs_oid.bytes, rhs.bytes(), sizeof(rhs_oid.bytes));\n\n return bson_oid_compare(&lhs_oid, &rhs_oid);\n}\n\nbool operator<(const oid& lhs, const oid& rhs) {\n return oid_compare(lhs, rhs) < 0;\n}\n\nbool operator>(const oid& lhs, const oid& rhs) {\n return oid_compare(lhs, rhs) > 0;\n}\n\nbool operator<=(const oid& lhs, const oid& rhs) {\n return oid_compare(lhs, rhs) <= 0;\n}\n\nbool operator>=(const oid& lhs, const oid& rhs) {\n return oid_compare(lhs, rhs) >= 0;\n}\n\nbool operator==(const oid& lhs, const oid& rhs) {\n return oid_compare(lhs, rhs) == 0;\n}\n\nbool operator!=(const oid& lhs, const oid& rhs) {\n return oid_compare(lhs, rhs) != 0;\n}\n\nstd::ostream& operator<<(std::ostream& out, const oid& rhs) {\n bson_oid_t oid;\n std::memcpy(oid.bytes, rhs._bytes, sizeof(oid.bytes));\n char str[25];\n\n bson_oid_to_string(&oid, str);\n\n out << str;\n\n return out;\n}\n\nBSONCXX_INLINE_NAMESPACE_END\n} \/\/ namespace bsoncxx\n<|endoftext|>"} {"text":"<commit_before>\/*!\n * This file is part of CameraPlus.\n *\n * Copyright (C) 2012-2014 Mohammed Sameer <msameer@foolab.org>\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n *\/\n\n#include \"settings.h\"\n#include <QSettings>\n#include <QDir>\n#include \"devicesettings.h\"\n\n#ifdef SAILFISH\n#define PATH QString(\"%1%2.config%2harbour-cameraplus%2harbour-cameraplus.conf\").arg(QDir::homePath()).arg(QDir::separator())\n#else\n#define PATH QString(\"%1%2.config%2cameraplus.conf\").arg(QDir::homePath()).arg(QDir::separator())\n#endif\n\n#define DEFAULT_MODE 1\n#define DEFAULT_USE_GPS true\n#define DEFAULT_USE_GEOTAGS true\n#define DEFAULT_SOUND_ENABLED true\n#define DEFAULT_SHOW_TOOL_BAR false\n#define DEFAULT_VIDEO_MUTE false\n#define DEFAULT_GRID_ENABLED false\n#define DEFAULT_FACE_DETECTION_ENABLED true\n#define DEFAULT_ZOOM_AS_SHUTTER false\n#define DEFAULT_PROXIMITY_AS_SHUTTER false\n#define DEFAULT_DEVICE 0\n#define DEFAULT_ENABLE_PREVIEW true\n#define DEFAULT_NIGHT_MODE false\n#define DEFAULT_PLUGIN \"org.foolab.cameraplus.image\"\n#define DEFAULT_CAPTURE_TIMER_DELAY 5\n#define DEFAULT_LEFT_HANDED_MODE false\n#define DEFAULT_SEQUENTIAL_SHOTS_COUNT 5\n#define DEFAULT_SEQUENTIAL_SHOTS_INTERVAL 5\n#define DEFAULT_SEQUENTIAL_SHOTS_DELAY 5\n#define DEFAULT_SEQUENTIAL_SHOTS_FOCUS true\n\nSettings::Settings(QObject *parent) :\n QObject(parent),\n m_settings(new QSettings(PATH, QSettings::IniFormat, this)) {\n\n}\n\nSettings::~Settings() {\n delete m_settings; m_settings = 0;\n}\n\nint Settings::mode() const {\n return m_settings->value(\"camera\/mode\", DEFAULT_MODE).toInt();\n}\n\nvoid Settings::setMode(int mode) {\n if (mode != Settings::mode()) {\n m_settings->setValue(\"camera\/mode\", mode);\n\n emit modeChanged();\n }\n}\n\nQString Settings::creatorName() const {\n return m_settings->value(\"camera\/creatorName\").toString();\n}\n\nvoid Settings::setCreatorName(const QString& name) {\n if (name != creatorName()) {\n m_settings->setValue(\"camera\/creatorName\", name);\n\n emit creatorNameChanged();\n }\n}\n\nbool Settings::useGps() const {\n return m_settings->value(\"camera\/useGps\", DEFAULT_USE_GPS).toBool();\n}\n\nvoid Settings::setUseGps(bool enable) {\n if (enable != useGps()) {\n m_settings->setValue(\"camera\/useGps\", enable);\n\n emit useGpsChanged();\n }\n}\n\nbool Settings::useGeotags() const {\n return m_settings->value(\"camera\/useGeotags\", DEFAULT_USE_GEOTAGS).toBool();\n}\n\nvoid Settings::setUseGeotags(bool enable) {\n if (enable != useGeotags()) {\n m_settings->setValue(\"camera\/useGeotags\", enable);\n\n emit useGeotagsChanged();\n }\n}\n\nbool Settings::isSoundEnabled() const {\n return m_settings->value(\"camera\/soundEnabled\", DEFAULT_SOUND_ENABLED).toBool();\n}\n\nvoid Settings::setSoundEnabled(bool enabled) {\n if (isSoundEnabled() != enabled) {\n m_settings->setValue(\"camera\/soundEnabled\", enabled);\n emit soundEnabledChanged();\n }\n}\n\nbool Settings::isToolBarShown() const {\n return m_settings->value(\"camera\/showToolBar\", DEFAULT_SHOW_TOOL_BAR).toBool();\n}\n\nvoid Settings::setToolBarShown(bool shown) {\n if (isToolBarShown() != shown) {\n m_settings->setValue(\"camera\/showToolBar\", shown);\n\n emit toolBarShownChanged();\n }\n}\n\nbool Settings::isGridEnabled() const {\n return m_settings->value(\"camera\/gridEnabled\", DEFAULT_GRID_ENABLED).toBool();\n}\n\nvoid Settings::setGridEnabled(bool enabled) {\n if (enabled != isGridEnabled()) {\n m_settings->setValue(\"camera\/gridEnabled\", enabled);\n emit gridEnabledChanged();\n }\n}\n\nbool Settings::isFaceDetectionEnabled() const {\n return m_settings->value(\"image\/faceDetectionEnabled\", DEFAULT_FACE_DETECTION_ENABLED).toBool();\n}\n\nvoid Settings::setFaceDetectionEnabled(bool enabled) {\n if (isFaceDetectionEnabled() != enabled) {\n m_settings->setValue(\"image\/faceDetectionEnabled\", enabled);\n emit faceDetectionEnabledChanged();\n }\n}\n\nbool Settings::isZoomAsShutterEnabled() const {\n return m_settings->value(\"camera\/zoomAsShutter\", DEFAULT_ZOOM_AS_SHUTTER).toBool();\n}\n\nvoid Settings::setZoomAsShutterEnabled(bool enabled) {\n if (isZoomAsShutterEnabled() != enabled) {\n m_settings->setValue(\"camera\/zoomAsShutter\", enabled);\n\n emit zoomAsShutterChanged();\n }\n}\n\nbool Settings::isProximityAsShutterEnabled() const {\n return m_settings->value(\"camera\/proximityAsShutter\", DEFAULT_PROXIMITY_AS_SHUTTER).toBool();\n}\n\nvoid Settings::setProximityAsShutterEnabled(bool enabled) {\n if (isProximityAsShutterEnabled() != enabled) {\n m_settings->setValue(\"camera\/proximityAsShutter\", enabled);\n\n emit proximityAsShutterChanged();\n }\n}\n\nint Settings::device() const {\n return m_settings->value(\"camera\/device\", DEFAULT_DEVICE).toInt();\n}\n\nvoid Settings::setDevice(int device) {\n if (device != Settings::device()) {\n m_settings->setValue(\"camera\/device\", device);\n emit deviceChanged();\n }\n}\n\nQVariant Settings::value(const QString& key, const QVariant& defaultValue) const {\n return m_settings->value(key, defaultValue);\n}\n\nvoid Settings::setValue(const QString& key, const QVariant& value) {\n m_settings->setValue(key, value);\n}\n\nQString Settings::fileNamingStamp(const QString& id) const {\n QString key = QString(\"fileNaming\/%1\").arg(id);\n return m_settings->value(key).toString();\n}\n\nvoid Settings::setFileNamingStamp(const QString& id, const QString& stamp) {\n QString key = QString(\"fileNaming\/%1\").arg(id);\n m_settings->setValue(key, stamp);\n}\n\nint Settings::fileNamingCounter(const QString& id) const {\n QString key = QString(\"fileNaming\/%1\").arg(id);\n return m_settings->value(key).toInt();\n}\n\nvoid Settings::setFileNamingCounter(const QString& id, int counter) {\n QString key = QString(\"fileNaming\/%1\").arg(id);\n m_settings->setValue(key, counter);\n}\n\nbool Settings::isPreviewEnabled() const {\n return m_settings->value(\"camera\/enablePreview\", DEFAULT_ENABLE_PREVIEW).toBool();\n}\n\nvoid Settings::setPreviewEnabled(bool enabled) {\n if (enabled != isPreviewEnabled()) {\n m_settings->setValue(\"camera\/enablePreview\", enabled);\n\n emit previewEnabledChanged();\n }\n}\n\nbool Settings::isNightModeEnabled() const {\n return m_settings->value(\"camera\/nightMode\", DEFAULT_NIGHT_MODE).toBool();\n}\n\nvoid Settings::setNightModeEnabled(bool enabled) {\n if (isNightModeEnabled() != enabled) {\n m_settings->setValue(\"camera\/nightMode\", enabled);\n emit nightModeChanged();\n }\n}\n\nQString Settings::plugin() const {\n return m_settings->value(\"camera\/plugin\", DEFAULT_PLUGIN).toString();\n}\n\nvoid Settings::setPlugin(const QString& plugin) {\n if (Settings::plugin() != plugin) {\n m_settings->setValue(\"camera\/plugin\", plugin);\n emit pluginChanged();\n }\n}\n\nint Settings::captureTimerDelay() const {\n return m_settings->value(\"captureTimer\/delay\", DEFAULT_CAPTURE_TIMER_DELAY).toInt();\n}\n\nvoid Settings::setCaptureTimerDelay(int delay) {\n if (delay != captureTimerDelay()) {\n m_settings->setValue(\"captureTimer\/delay\", delay);\n emit captureTimerDelayChanged();\n }\n}\n\nbool Settings::isLeftHandedModeEnabled() {\n return m_settings->value(\"camera\/leftHandedMode\", DEFAULT_LEFT_HANDED_MODE).toBool();\n}\n\nvoid Settings::setLeftHandedModeEnabled(bool enabled) {\n if (isLeftHandedModeEnabled() != enabled) {\n m_settings->setValue(\"camera\/leftHandedMode\", enabled);\n\n emit leftHandedModeChanged();\n }\n}\n\nint Settings::sequentialShotsCount() const {\n return m_settings->value(\"sequentialShots\/count\", DEFAULT_SEQUENTIAL_SHOTS_COUNT).toInt();\n}\n\nvoid Settings::setSequentialShotsCount(int count) {\n if (sequentialShotsCount() != count) {\n m_settings->setValue(\"sequentialShots\/count\", count);\n emit sequentialShotsCountChanged();\n }\n}\n\nint Settings::sequentialShotsInterval() const {\n return m_settings->value(\"sequentialShots\/interval\", DEFAULT_SEQUENTIAL_SHOTS_INTERVAL).toInt();\n}\n\nvoid Settings::setSequentialShotsInterval(int interval) {\n if (sequentialShotsInterval() != interval) {\n m_settings->setValue(\"sequentialShots\/interval\", interval);\n emit sequentialShotsIntervalChanged();\n }\n}\n\nint Settings::sequentialShotsDelay() const {\n return m_settings->value(\"sequentialShots\/delay\", DEFAULT_SEQUENTIAL_SHOTS_DELAY).toInt();\n}\n\nvoid Settings::setSequentialShotsDelay(int delay) {\n if (sequentialShotsDelay() != delay) {\n m_settings->setValue(\"sequentialShots\/delay\", delay);\n emit sequentialShotsDelayChanged();\n }\n}\n\nbool Settings::isFocusBeforeSequentialShotsEnabled() const {\n return m_settings->value(\"sequentialShots\/focus\", DEFAULT_SEQUENTIAL_SHOTS_FOCUS).toBool();\n}\n\nvoid Settings::setFocusBeforeSequentialShotsEnabled(bool enabled) {\n if (isFocusBeforeSequentialShotsEnabled() != enabled) {\n m_settings->setValue(\"sequentialShots\/focus\", enabled);\n emit focusBeforeSequentialShotsChanged();\n }\n}\n<commit_msg>sequential: change DEFAULT_SEQUENTIAL_SHOTS_DELAY to 0<commit_after>\/*!\n * This file is part of CameraPlus.\n *\n * Copyright (C) 2012-2014 Mohammed Sameer <msameer@foolab.org>\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n *\/\n\n#include \"settings.h\"\n#include <QSettings>\n#include <QDir>\n#include \"devicesettings.h\"\n\n#ifdef SAILFISH\n#define PATH QString(\"%1%2.config%2harbour-cameraplus%2harbour-cameraplus.conf\").arg(QDir::homePath()).arg(QDir::separator())\n#else\n#define PATH QString(\"%1%2.config%2cameraplus.conf\").arg(QDir::homePath()).arg(QDir::separator())\n#endif\n\n#define DEFAULT_MODE 1\n#define DEFAULT_USE_GPS true\n#define DEFAULT_USE_GEOTAGS true\n#define DEFAULT_SOUND_ENABLED true\n#define DEFAULT_SHOW_TOOL_BAR false\n#define DEFAULT_VIDEO_MUTE false\n#define DEFAULT_GRID_ENABLED false\n#define DEFAULT_FACE_DETECTION_ENABLED true\n#define DEFAULT_ZOOM_AS_SHUTTER false\n#define DEFAULT_PROXIMITY_AS_SHUTTER false\n#define DEFAULT_DEVICE 0\n#define DEFAULT_ENABLE_PREVIEW true\n#define DEFAULT_NIGHT_MODE false\n#define DEFAULT_PLUGIN \"org.foolab.cameraplus.image\"\n#define DEFAULT_CAPTURE_TIMER_DELAY 5\n#define DEFAULT_LEFT_HANDED_MODE false\n#define DEFAULT_SEQUENTIAL_SHOTS_COUNT 5\n#define DEFAULT_SEQUENTIAL_SHOTS_INTERVAL 5\n#define DEFAULT_SEQUENTIAL_SHOTS_DELAY 0\n#define DEFAULT_SEQUENTIAL_SHOTS_FOCUS true\n\nSettings::Settings(QObject *parent) :\n QObject(parent),\n m_settings(new QSettings(PATH, QSettings::IniFormat, this)) {\n\n}\n\nSettings::~Settings() {\n delete m_settings; m_settings = 0;\n}\n\nint Settings::mode() const {\n return m_settings->value(\"camera\/mode\", DEFAULT_MODE).toInt();\n}\n\nvoid Settings::setMode(int mode) {\n if (mode != Settings::mode()) {\n m_settings->setValue(\"camera\/mode\", mode);\n\n emit modeChanged();\n }\n}\n\nQString Settings::creatorName() const {\n return m_settings->value(\"camera\/creatorName\").toString();\n}\n\nvoid Settings::setCreatorName(const QString& name) {\n if (name != creatorName()) {\n m_settings->setValue(\"camera\/creatorName\", name);\n\n emit creatorNameChanged();\n }\n}\n\nbool Settings::useGps() const {\n return m_settings->value(\"camera\/useGps\", DEFAULT_USE_GPS).toBool();\n}\n\nvoid Settings::setUseGps(bool enable) {\n if (enable != useGps()) {\n m_settings->setValue(\"camera\/useGps\", enable);\n\n emit useGpsChanged();\n }\n}\n\nbool Settings::useGeotags() const {\n return m_settings->value(\"camera\/useGeotags\", DEFAULT_USE_GEOTAGS).toBool();\n}\n\nvoid Settings::setUseGeotags(bool enable) {\n if (enable != useGeotags()) {\n m_settings->setValue(\"camera\/useGeotags\", enable);\n\n emit useGeotagsChanged();\n }\n}\n\nbool Settings::isSoundEnabled() const {\n return m_settings->value(\"camera\/soundEnabled\", DEFAULT_SOUND_ENABLED).toBool();\n}\n\nvoid Settings::setSoundEnabled(bool enabled) {\n if (isSoundEnabled() != enabled) {\n m_settings->setValue(\"camera\/soundEnabled\", enabled);\n emit soundEnabledChanged();\n }\n}\n\nbool Settings::isToolBarShown() const {\n return m_settings->value(\"camera\/showToolBar\", DEFAULT_SHOW_TOOL_BAR).toBool();\n}\n\nvoid Settings::setToolBarShown(bool shown) {\n if (isToolBarShown() != shown) {\n m_settings->setValue(\"camera\/showToolBar\", shown);\n\n emit toolBarShownChanged();\n }\n}\n\nbool Settings::isGridEnabled() const {\n return m_settings->value(\"camera\/gridEnabled\", DEFAULT_GRID_ENABLED).toBool();\n}\n\nvoid Settings::setGridEnabled(bool enabled) {\n if (enabled != isGridEnabled()) {\n m_settings->setValue(\"camera\/gridEnabled\", enabled);\n emit gridEnabledChanged();\n }\n}\n\nbool Settings::isFaceDetectionEnabled() const {\n return m_settings->value(\"image\/faceDetectionEnabled\", DEFAULT_FACE_DETECTION_ENABLED).toBool();\n}\n\nvoid Settings::setFaceDetectionEnabled(bool enabled) {\n if (isFaceDetectionEnabled() != enabled) {\n m_settings->setValue(\"image\/faceDetectionEnabled\", enabled);\n emit faceDetectionEnabledChanged();\n }\n}\n\nbool Settings::isZoomAsShutterEnabled() const {\n return m_settings->value(\"camera\/zoomAsShutter\", DEFAULT_ZOOM_AS_SHUTTER).toBool();\n}\n\nvoid Settings::setZoomAsShutterEnabled(bool enabled) {\n if (isZoomAsShutterEnabled() != enabled) {\n m_settings->setValue(\"camera\/zoomAsShutter\", enabled);\n\n emit zoomAsShutterChanged();\n }\n}\n\nbool Settings::isProximityAsShutterEnabled() const {\n return m_settings->value(\"camera\/proximityAsShutter\", DEFAULT_PROXIMITY_AS_SHUTTER).toBool();\n}\n\nvoid Settings::setProximityAsShutterEnabled(bool enabled) {\n if (isProximityAsShutterEnabled() != enabled) {\n m_settings->setValue(\"camera\/proximityAsShutter\", enabled);\n\n emit proximityAsShutterChanged();\n }\n}\n\nint Settings::device() const {\n return m_settings->value(\"camera\/device\", DEFAULT_DEVICE).toInt();\n}\n\nvoid Settings::setDevice(int device) {\n if (device != Settings::device()) {\n m_settings->setValue(\"camera\/device\", device);\n emit deviceChanged();\n }\n}\n\nQVariant Settings::value(const QString& key, const QVariant& defaultValue) const {\n return m_settings->value(key, defaultValue);\n}\n\nvoid Settings::setValue(const QString& key, const QVariant& value) {\n m_settings->setValue(key, value);\n}\n\nQString Settings::fileNamingStamp(const QString& id) const {\n QString key = QString(\"fileNaming\/%1\").arg(id);\n return m_settings->value(key).toString();\n}\n\nvoid Settings::setFileNamingStamp(const QString& id, const QString& stamp) {\n QString key = QString(\"fileNaming\/%1\").arg(id);\n m_settings->setValue(key, stamp);\n}\n\nint Settings::fileNamingCounter(const QString& id) const {\n QString key = QString(\"fileNaming\/%1\").arg(id);\n return m_settings->value(key).toInt();\n}\n\nvoid Settings::setFileNamingCounter(const QString& id, int counter) {\n QString key = QString(\"fileNaming\/%1\").arg(id);\n m_settings->setValue(key, counter);\n}\n\nbool Settings::isPreviewEnabled() const {\n return m_settings->value(\"camera\/enablePreview\", DEFAULT_ENABLE_PREVIEW).toBool();\n}\n\nvoid Settings::setPreviewEnabled(bool enabled) {\n if (enabled != isPreviewEnabled()) {\n m_settings->setValue(\"camera\/enablePreview\", enabled);\n\n emit previewEnabledChanged();\n }\n}\n\nbool Settings::isNightModeEnabled() const {\n return m_settings->value(\"camera\/nightMode\", DEFAULT_NIGHT_MODE).toBool();\n}\n\nvoid Settings::setNightModeEnabled(bool enabled) {\n if (isNightModeEnabled() != enabled) {\n m_settings->setValue(\"camera\/nightMode\", enabled);\n emit nightModeChanged();\n }\n}\n\nQString Settings::plugin() const {\n return m_settings->value(\"camera\/plugin\", DEFAULT_PLUGIN).toString();\n}\n\nvoid Settings::setPlugin(const QString& plugin) {\n if (Settings::plugin() != plugin) {\n m_settings->setValue(\"camera\/plugin\", plugin);\n emit pluginChanged();\n }\n}\n\nint Settings::captureTimerDelay() const {\n return m_settings->value(\"captureTimer\/delay\", DEFAULT_CAPTURE_TIMER_DELAY).toInt();\n}\n\nvoid Settings::setCaptureTimerDelay(int delay) {\n if (delay != captureTimerDelay()) {\n m_settings->setValue(\"captureTimer\/delay\", delay);\n emit captureTimerDelayChanged();\n }\n}\n\nbool Settings::isLeftHandedModeEnabled() {\n return m_settings->value(\"camera\/leftHandedMode\", DEFAULT_LEFT_HANDED_MODE).toBool();\n}\n\nvoid Settings::setLeftHandedModeEnabled(bool enabled) {\n if (isLeftHandedModeEnabled() != enabled) {\n m_settings->setValue(\"camera\/leftHandedMode\", enabled);\n\n emit leftHandedModeChanged();\n }\n}\n\nint Settings::sequentialShotsCount() const {\n return m_settings->value(\"sequentialShots\/count\", DEFAULT_SEQUENTIAL_SHOTS_COUNT).toInt();\n}\n\nvoid Settings::setSequentialShotsCount(int count) {\n if (sequentialShotsCount() != count) {\n m_settings->setValue(\"sequentialShots\/count\", count);\n emit sequentialShotsCountChanged();\n }\n}\n\nint Settings::sequentialShotsInterval() const {\n return m_settings->value(\"sequentialShots\/interval\", DEFAULT_SEQUENTIAL_SHOTS_INTERVAL).toInt();\n}\n\nvoid Settings::setSequentialShotsInterval(int interval) {\n if (sequentialShotsInterval() != interval) {\n m_settings->setValue(\"sequentialShots\/interval\", interval);\n emit sequentialShotsIntervalChanged();\n }\n}\n\nint Settings::sequentialShotsDelay() const {\n return m_settings->value(\"sequentialShots\/delay\", DEFAULT_SEQUENTIAL_SHOTS_DELAY).toInt();\n}\n\nvoid Settings::setSequentialShotsDelay(int delay) {\n if (sequentialShotsDelay() != delay) {\n m_settings->setValue(\"sequentialShots\/delay\", delay);\n emit sequentialShotsDelayChanged();\n }\n}\n\nbool Settings::isFocusBeforeSequentialShotsEnabled() const {\n return m_settings->value(\"sequentialShots\/focus\", DEFAULT_SEQUENTIAL_SHOTS_FOCUS).toBool();\n}\n\nvoid Settings::setFocusBeforeSequentialShotsEnabled(bool enabled) {\n if (isFocusBeforeSequentialShotsEnabled() != enabled) {\n m_settings->setValue(\"sequentialShots\/focus\", enabled);\n emit focusBeforeSequentialShotsChanged();\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/**\n * @file decision_stump_impl.hpp\n * @author Udit Saxena\n *\n * Implementation of DecisionStump class.\n *\/\n\n#ifndef __MLPACK_METHODS_DECISION_STUMP_DECISION_STUMP_IMPL_HPP\n#define __MLPACK_METHODS_DECISION_STUMP_DECISION_STUMP_IMPL_HPP\n\n\/\/ In case it hasn't been included yet.\n#include \"decision_stump.hpp\"\n\n#include <set>\n#include <algorithm>\n\nnamespace mlpack {\nnamespace decision_stump {\n\n\/**\n * Constructor. Train on the provided data. Generate a decision stump from data.\n *\n * @param data Input, training data.\n * @param labels Labels of data.\n * @param classes Number of distinct classes in labels.\n * @param inpBucketSize Minimum size of bucket when splitting.\n *\/\ntemplate<typename MatType>\nDecisionStump<MatType>::DecisionStump(const MatType& data,\n const arma::Row<size_t>& labels,\n const size_t classes,\n size_t inpBucketSize)\n{\n arma::Row<size_t> zLabels(labels.n_elem);\n zLabels.fill(0);\n classLabels = labels + zLabels;\n\n numClass = classes;\n bucketSize = inpBucketSize;\n\n \/* Check whether the input labels are not all identical. *\/\n if (!isDistinct<size_t>(classLabels))\n {\n \/\/ If the classLabels are all identical, the default class is the only\n \/\/ class.\n oneClass = true;\n defaultClass = classLabels(0);\n }\n\n else\n {\n \/\/ If classLabels are not all identical, proceed with training.\n oneClass = false;\n int bestAtt = -1;\n double entropy;\n double bestEntropy = DBL_MAX;\n\n \/\/ Set the default class to handle attribute values which are not present in\n \/\/ the training data.\n defaultClass = CountMostFreq<size_t>(classLabels);\n\n for (int i = 0; i < data.n_rows; i++)\n {\n \/\/ Go through each attribute of the data.\n if (isDistinct<double>(data.row(i)))\n {\n \/\/ For each attribute with non-identical values, treat it as a potential\n \/\/ splitting attribute and calculate entropy if split on it.\n entropy = SetupSplitAttribute(data.row(i));\n\n \/\/ Find the attribute with the bestEntropy so that the gain is\n \/\/ maximized.\n if (entropy < bestEntropy)\n {\n bestAtt = i;\n bestEntropy = entropy;\n }\n }\n }\n splitCol = bestAtt;\n\n \/\/ Once the splitting column\/attribute has been decided, train on it.\n TrainOnAtt<double>(data.row(splitCol));\n }\n}\n\n\/**\n * Classification function. After training, classify test, and put the predicted\n * classes in predictedLabels.\n *\n * @param test Testing data or data to classify.\n * @param predictedLabels Vector to store the predicted classes after\n * classifying test\n *\/\ntemplate<typename MatType>\nvoid DecisionStump<MatType>::Classify(const MatType& test,\n arma::Row<size_t>& predictedLabels)\n{\n bool flag;\n double val;\n if (!oneClass)\n {\n for (int i = 0; i < test.n_cols; i++)\n {\n int j = 0;\n flag = false;\n\n val = test(splitCol,i);\n while ((j < split.n_rows) && (!flag))\n {\n if (val < split(j, 0) && (!j))\n {\n predictedLabels(i) = split(0, 1);\n flag = true;\n }\n else if (val >= split(j, 0))\n {\n if (j == split.n_rows - 1)\n {\n predictedLabels(i) = split(split.n_rows - 1, 1);\n flag = true;\n }\n else if (val < split(j + 1, 0))\n {\n predictedLabels(i) = split(j, 1);\n flag = true;\n }\n }\n j++;\n }\n }\n }\n else\n {\n for (int i = 0; i < test.n_cols; i++)\n predictedLabels(i) = defaultClass;\n }\n}\n\n\/**\n * Sets up attribute as if it were splitting on it and finds entropy when\n * splitting on attribute.\n *\n * @param attribute A row from the training data, which might be a candidate for\n * the splitting attribute.\n *\/\ntemplate <typename MatType>\ndouble DecisionStump<MatType>::SetupSplitAttribute(const arma::rowvec& attribute)\n{\n int i, count, begin, end;\n double entropy = 0.0;\n\n \/\/ Sort the attribute in order to calculate splitting ranges.\n arma::rowvec sortedAtt = arma::sort(attribute);\n\n \/\/ Store the indices of the sorted attribute to build a vector of sorted\n \/\/ labels. This sort is stable.\n arma::uvec sortedIndexAtt = arma::stable_sort_index(attribute.t());\n\n arma::Row<size_t> sortedLabels(attribute.n_elem);\n sortedLabels.fill(0);\n\n for (i = 0; i < attribute.n_elem; i++)\n sortedLabels(i) = classLabels(sortedIndexAtt(i));\n\n arma::rowvec subColLabels;\n arma::rowvec subColAtts;\n\n i = 0;\n count = 0;\n\n \/\/ This splits the sorted into buckets of size greater than or equal to\n \/\/ inpBucketSize.\n while (i < sortedLabels.n_elem)\n {\n count++;\n if (i == sortedLabels.n_elem - 1)\n {\n begin = i - count + 1;\n end = i;\n\n arma::rowvec zSubColLabels((sortedLabels.cols(begin, end)).n_elem);\n zSubColLabels.fill(0.0);\n\n arma::rowvec zSubColAtts((sortedAtt.cols(begin, end)).n_elem);\n zSubColAtts.fill(0.0);\n\n subColLabels = sortedLabels.cols(begin, end) + zSubColLabels;\n\n subColAtts = sortedAtt.cols(begin, end) + zSubColAtts;\n\n entropy += CalculateEntropy(subColAtts, subColLabels);\n i++;\n }\n else if (sortedLabels(i) != sortedLabels(i + 1))\n {\n if (count < bucketSize)\n {\n begin = i - count + 1;\n end = begin + bucketSize - 1;\n\n if (end > sortedLabels.n_elem - 1)\n end = sortedLabels.n_elem - 1;\n }\n else\n {\n begin = i - count + 1;\n end = i;\n }\n\n arma::rowvec zSubColLabels((sortedLabels.cols(begin, end)).n_elem);\n zSubColLabels.fill(0.0);\n\n arma::rowvec zSubColAtts((sortedAtt.cols(begin, end)).n_elem);\n zSubColAtts.fill(0.0);\n\n subColLabels = sortedLabels.cols(begin, end) + zSubColLabels;\n\n subColAtts = sortedAtt.cols(begin, end) + zSubColAtts;\n\n \/\/ Now use subColLabels and subColAtts to calculate entropy.\n entropy += CalculateEntropy(subColAtts, subColLabels);\n\n i = end + 1;\n count = 0;\n }\n else\n i++;\n }\n return entropy;\n}\n\n\/**\n * After having decided the attribute on which to split, train on that\n * attribute.\n *\n * @param attribute Attribute is the attribute decided by the constructor on\n * which we now train the decision stump.\n *\/\ntemplate <typename MatType>\ntemplate <typename rType>\nvoid DecisionStump<MatType>::TrainOnAtt(const arma::rowvec& attribute)\n{\n int i, count, begin, end;\n\n arma::rowvec sortedSplitAtt = arma::sort(attribute);\n arma::uvec sortedSplitIndexAtt = arma::stable_sort_index(attribute.t());\n arma::Row<size_t> sortedLabels(attribute.n_elem);\n sortedLabels.fill(0);\n arma::mat tempSplit;\n\n for (i = 0; i < attribute.n_elem; i++)\n sortedLabels(i) = classLabels(sortedSplitIndexAtt(i));\n\n arma::rowvec subCols;\n rType mostFreq;\n i = 0;\n count = 0;\n while (i < sortedLabels.n_elem)\n {\n count++;\n if (i == sortedLabels.n_elem - 1)\n {\n begin = i - count + 1;\n end = i;\n\n arma::rowvec zSubCols((sortedLabels.cols(begin, end)).n_elem);\n zSubCols.fill(0.0);\n\n subCols = sortedLabels.cols(begin, end) + zSubCols;\n\n mostFreq = CountMostFreq<double>(subCols);\n\n tempSplit << sortedSplitAtt(begin)<< mostFreq << arma::endr;\n split = arma::join_cols(split, tempSplit);\n\n i++;\n }\n else if (sortedLabels(i) != sortedLabels(i + 1))\n {\n if (count < bucketSize)\n {\n \/\/ Test for different values of bucketSize, especially extreme cases.\n begin = i - count + 1;\n end = begin + bucketSize - 1;\n\n if (end > sortedLabels.n_elem - 1)\n end = sortedLabels.n_elem - 1;\n }\n else\n {\n begin = i - count + 1;\n end = i;\n }\n arma::rowvec zSubCols((sortedLabels.cols(begin, end)).n_elem);\n zSubCols.fill(0.0);\n\n subCols = sortedLabels.cols(begin, end) + zSubCols;\n\n \/\/ Find the most frequent element in subCols so as to assign a label to\n \/\/ the bucket of subCols.\n mostFreq = CountMostFreq<double>(subCols);\n\n tempSplit << sortedSplitAtt(begin) << mostFreq << arma::endr;\n split = arma::join_cols(split, tempSplit);\n\n i = end + 1;\n count = 0;\n }\n else\n i++;\n }\n\n \/\/ Now trim the split matrix so that buckets one after the after which point\n \/\/ to the same classLabel are merged as one big bucket.\n MergeRanges();\n}\n\n\/**\n * After the \"split\" matrix has been set up, merge ranges with identical class\n * labels.\n *\/\ntemplate <typename MatType>\nvoid DecisionStump<MatType>::MergeRanges()\n{\n for (int i = 1; i < split.n_rows; i++)\n {\n if (split(i, 1) == split(i - 1, 1))\n {\n \/\/ Remove this row, as it has the same label as the previous bucket.\n split.shed_row(i);\n \/\/ Go back to previous row.\n i--;\n }\n }\n}\n\ntemplate <typename MatType>\ntemplate <typename rType>\nrType DecisionStump<MatType>::CountMostFreq(const arma::Row<rType>& subCols)\n{\n \/\/ Sort subCols for easier processing.\n arma::Row<rType> sortCounts = arma::sort(subCols);\n rType element;\n int count = 0, localCount = 0;\n\n \/\/ An O(n) loop which counts the most frequent element in sortCounts\n for (int i = 0; i < sortCounts.n_elem; ++i)\n {\n if (i == sortCounts.n_elem - 1)\n {\n if (sortCounts(i - 1) == sortCounts(i))\n {\n \/\/ element = sortCounts(i - 1);\n localCount++;\n }\n else if (localCount > count)\n count = localCount;\n }\n else if (sortCounts(i) != sortCounts(i + 1))\n {\n localCount = 0;\n count++;\n }\n else\n {\n localCount++;\n if (localCount > count)\n {\n count = localCount;\n if (localCount == 1)\n element = sortCounts(i);\n }\n }\n }\n return element;\n}\n\n\/**\n * Returns 1 if all the values of featureRow are not same.\n *\n * @param featureRow The attribute which is checked for identical values.\n *\/\ntemplate <typename MatType>\ntemplate <typename rType>\nint DecisionStump<MatType>::isDistinct(const arma::Row<rType>& featureRow)\n{\n if (featureRow.max() - featureRow.min() > 0)\n return 1;\n else\n return 0;\n}\n\n\/**\n * Calculating Entropy of attribute.\n *\n * @param attribute The attribute for which we calculate the entropy.\n * @param labels Corresponding labels of the attribute.\n *\/\ntemplate<typename MatType>\ndouble DecisionStump<MatType>::CalculateEntropy(const arma::rowvec& attribute,\n const arma::rowvec& labels)\n{\n double entropy = 0.0;\n\n arma::rowvec uniqueAtt = arma::unique(attribute);\n arma::rowvec uniqueLabel = arma::unique(labels);\n arma::Row<size_t> numElem(uniqueAtt.n_elem);\n numElem.fill(0);\n arma::Mat<size_t> entropyArray(uniqueAtt.n_elem,numClass);\n entropyArray.fill(0);\n\n \/\/ Populate entropyArray and numElem; they are used as helpers to calculate\n \/\/ entropy.\n for (int j = 0; j < uniqueAtt.n_elem; j++)\n {\n for (int i = 0; i < attribute.n_elem; i++)\n {\n if (uniqueAtt[j] == attribute[i])\n {\n entropyArray(j,labels(i))++;\n numElem(j)++;\n }\n }\n }\n\n for (int j = 0; j < uniqueAtt.size(); j++)\n {\n const double p1 = ((double) numElem(j) \/ attribute.n_elem);\n\n for (int i = 0; i < numClass; i++)\n {\n const double p2 = ((double) entropyArray(j, i) \/ numElem(j));\n const double p3 = (p2 == 0) ? 0 : p2 * log2(p2);\n\n entropy += p1 * p3;\n }\n }\n\n return entropy;\n}\n\n}; \/\/ namespace decision_stump\n}; \/\/ namespace mlpack\n\n#endif\n<commit_msg>Use const double where possible instead of having a variable used throughout the function. This is only for clarity and consistency and is not likely to make any runtime difference.<commit_after>\/**\n * @file decision_stump_impl.hpp\n * @author Udit Saxena\n *\n * Implementation of DecisionStump class.\n *\/\n\n#ifndef __MLPACK_METHODS_DECISION_STUMP_DECISION_STUMP_IMPL_HPP\n#define __MLPACK_METHODS_DECISION_STUMP_DECISION_STUMP_IMPL_HPP\n\n\/\/ In case it hasn't been included yet.\n#include \"decision_stump.hpp\"\n\n#include <set>\n#include <algorithm>\n\nnamespace mlpack {\nnamespace decision_stump {\n\n\/**\n * Constructor. Train on the provided data. Generate a decision stump from data.\n *\n * @param data Input, training data.\n * @param labels Labels of data.\n * @param classes Number of distinct classes in labels.\n * @param inpBucketSize Minimum size of bucket when splitting.\n *\/\ntemplate<typename MatType>\nDecisionStump<MatType>::DecisionStump(const MatType& data,\n const arma::Row<size_t>& labels,\n const size_t classes,\n size_t inpBucketSize)\n{\n arma::Row<size_t> zLabels(labels.n_elem);\n zLabels.fill(0);\n classLabels = labels + zLabels;\n\n numClass = classes;\n bucketSize = inpBucketSize;\n\n \/\/ Check whether the input labels are not all identical.\n if (!isDistinct<size_t>(classLabels))\n {\n \/\/ If the classLabels are all identical, the default class is the only\n \/\/ class.\n oneClass = true;\n defaultClass = classLabels(0);\n }\n else\n {\n \/\/ If classLabels are not all identical, proceed with training.\n oneClass = false;\n int bestAtt = -1;\n double entropy;\n double bestEntropy = DBL_MAX;\n\n \/\/ Set the default class to handle attribute values which are not present in\n \/\/ the training data.\n defaultClass = CountMostFreq<size_t>(classLabels);\n\n for (int i = 0; i < data.n_rows; i++)\n {\n \/\/ Go through each attribute of the data.\n if (isDistinct<double>(data.row(i)))\n {\n \/\/ For each attribute with non-identical values, treat it as a potential\n \/\/ splitting attribute and calculate entropy if split on it.\n entropy = SetupSplitAttribute(data.row(i));\n\n \/\/ Find the attribute with the bestEntropy so that the gain is\n \/\/ maximized.\n if (entropy < bestEntropy)\n {\n bestAtt = i;\n bestEntropy = entropy;\n }\n }\n }\n splitCol = bestAtt;\n\n \/\/ Once the splitting column\/attribute has been decided, train on it.\n TrainOnAtt<double>(data.row(splitCol));\n }\n}\n\n\/**\n * Classification function. After training, classify test, and put the predicted\n * classes in predictedLabels.\n *\n * @param test Testing data or data to classify.\n * @param predictedLabels Vector to store the predicted classes after\n * classifying test\n *\/\ntemplate<typename MatType>\nvoid DecisionStump<MatType>::Classify(const MatType& test,\n arma::Row<size_t>& predictedLabels)\n{\n if (!oneClass)\n {\n for (int i = 0; i < test.n_cols; i++)\n {\n int j = 0;\n\n const double val = test(splitCol, i);\n while (j < split.n_rows)\n {\n if (val < split(j, 0) && (!j))\n {\n predictedLabels(i) = split(0, 1);\n break;\n }\n else if (val >= split(j, 0))\n {\n if (j == split.n_rows - 1)\n {\n predictedLabels(i) = split(split.n_rows - 1, 1);\n break;\n }\n else if (val < split(j + 1, 0))\n {\n predictedLabels(i) = split(j, 1);\n break;\n }\n }\n j++;\n }\n }\n }\n else\n {\n for (int i = 0; i < test.n_cols; i++)\n predictedLabels(i) = defaultClass;\n }\n}\n\n\/**\n * Sets up attribute as if it were splitting on it and finds entropy when\n * splitting on attribute.\n *\n * @param attribute A row from the training data, which might be a candidate for\n * the splitting attribute.\n *\/\ntemplate <typename MatType>\ndouble DecisionStump<MatType>::SetupSplitAttribute(const arma::rowvec& attribute)\n{\n int i, count, begin, end;\n double entropy = 0.0;\n\n \/\/ Sort the attribute in order to calculate splitting ranges.\n arma::rowvec sortedAtt = arma::sort(attribute);\n\n \/\/ Store the indices of the sorted attribute to build a vector of sorted\n \/\/ labels. This sort is stable.\n arma::uvec sortedIndexAtt = arma::stable_sort_index(attribute.t());\n\n arma::Row<size_t> sortedLabels(attribute.n_elem);\n sortedLabels.fill(0);\n\n for (i = 0; i < attribute.n_elem; i++)\n sortedLabels(i) = classLabels(sortedIndexAtt(i));\n\n arma::rowvec subColLabels;\n arma::rowvec subColAtts;\n\n i = 0;\n count = 0;\n\n \/\/ This splits the sorted into buckets of size greater than or equal to\n \/\/ inpBucketSize.\n while (i < sortedLabels.n_elem)\n {\n count++;\n if (i == sortedLabels.n_elem - 1)\n {\n begin = i - count + 1;\n end = i;\n\n arma::rowvec zSubColLabels((sortedLabels.cols(begin, end)).n_elem);\n zSubColLabels.fill(0.0);\n\n arma::rowvec zSubColAtts((sortedAtt.cols(begin, end)).n_elem);\n zSubColAtts.fill(0.0);\n\n subColLabels = sortedLabels.cols(begin, end) + zSubColLabels;\n\n subColAtts = sortedAtt.cols(begin, end) + zSubColAtts;\n\n entropy += CalculateEntropy(subColAtts, subColLabels);\n i++;\n }\n else if (sortedLabels(i) != sortedLabels(i + 1))\n {\n if (count < bucketSize)\n {\n begin = i - count + 1;\n end = begin + bucketSize - 1;\n\n if (end > sortedLabels.n_elem - 1)\n end = sortedLabels.n_elem - 1;\n }\n else\n {\n begin = i - count + 1;\n end = i;\n }\n\n arma::rowvec zSubColLabels((sortedLabels.cols(begin, end)).n_elem);\n zSubColLabels.fill(0.0);\n\n arma::rowvec zSubColAtts((sortedAtt.cols(begin, end)).n_elem);\n zSubColAtts.fill(0.0);\n\n subColLabels = sortedLabels.cols(begin, end) + zSubColLabels;\n\n subColAtts = sortedAtt.cols(begin, end) + zSubColAtts;\n\n \/\/ Now use subColLabels and subColAtts to calculate entropy.\n entropy += CalculateEntropy(subColAtts, subColLabels);\n\n i = end + 1;\n count = 0;\n }\n else\n i++;\n }\n return entropy;\n}\n\n\/**\n * After having decided the attribute on which to split, train on that\n * attribute.\n *\n * @param attribute Attribute is the attribute decided by the constructor on\n * which we now train the decision stump.\n *\/\ntemplate <typename MatType>\ntemplate <typename rType>\nvoid DecisionStump<MatType>::TrainOnAtt(const arma::rowvec& attribute)\n{\n int i, count, begin, end;\n\n arma::rowvec sortedSplitAtt = arma::sort(attribute);\n arma::uvec sortedSplitIndexAtt = arma::stable_sort_index(attribute.t());\n arma::Row<size_t> sortedLabels(attribute.n_elem);\n sortedLabels.fill(0);\n arma::mat tempSplit;\n\n for (i = 0; i < attribute.n_elem; i++)\n sortedLabels(i) = classLabels(sortedSplitIndexAtt(i));\n\n arma::rowvec subCols;\n rType mostFreq;\n i = 0;\n count = 0;\n while (i < sortedLabels.n_elem)\n {\n count++;\n if (i == sortedLabels.n_elem - 1)\n {\n begin = i - count + 1;\n end = i;\n\n arma::rowvec zSubCols((sortedLabels.cols(begin, end)).n_elem);\n zSubCols.fill(0.0);\n\n subCols = sortedLabels.cols(begin, end) + zSubCols;\n\n mostFreq = CountMostFreq<double>(subCols);\n\n tempSplit << sortedSplitAtt(begin)<< mostFreq << arma::endr;\n split = arma::join_cols(split, tempSplit);\n\n i++;\n }\n else if (sortedLabels(i) != sortedLabels(i + 1))\n {\n if (count < bucketSize)\n {\n \/\/ Test for different values of bucketSize, especially extreme cases.\n begin = i - count + 1;\n end = begin + bucketSize - 1;\n\n if (end > sortedLabels.n_elem - 1)\n end = sortedLabels.n_elem - 1;\n }\n else\n {\n begin = i - count + 1;\n end = i;\n }\n arma::rowvec zSubCols((sortedLabels.cols(begin, end)).n_elem);\n zSubCols.fill(0.0);\n\n subCols = sortedLabels.cols(begin, end) + zSubCols;\n\n \/\/ Find the most frequent element in subCols so as to assign a label to\n \/\/ the bucket of subCols.\n mostFreq = CountMostFreq<double>(subCols);\n\n tempSplit << sortedSplitAtt(begin) << mostFreq << arma::endr;\n split = arma::join_cols(split, tempSplit);\n\n i = end + 1;\n count = 0;\n }\n else\n i++;\n }\n\n \/\/ Now trim the split matrix so that buckets one after the after which point\n \/\/ to the same classLabel are merged as one big bucket.\n MergeRanges();\n}\n\n\/**\n * After the \"split\" matrix has been set up, merge ranges with identical class\n * labels.\n *\/\ntemplate <typename MatType>\nvoid DecisionStump<MatType>::MergeRanges()\n{\n for (int i = 1; i < split.n_rows; i++)\n {\n if (split(i, 1) == split(i - 1, 1))\n {\n \/\/ Remove this row, as it has the same label as the previous bucket.\n split.shed_row(i);\n \/\/ Go back to previous row.\n i--;\n }\n }\n}\n\ntemplate <typename MatType>\ntemplate <typename rType>\nrType DecisionStump<MatType>::CountMostFreq(const arma::Row<rType>& subCols)\n{\n \/\/ Sort subCols for easier processing.\n arma::Row<rType> sortCounts = arma::sort(subCols);\n rType element;\n int count = 0, localCount = 0;\n\n \/\/ An O(n) loop which counts the most frequent element in sortCounts\n for (int i = 0; i < sortCounts.n_elem; ++i)\n {\n if (i == sortCounts.n_elem - 1)\n {\n if (sortCounts(i - 1) == sortCounts(i))\n {\n \/\/ element = sortCounts(i - 1);\n localCount++;\n }\n else if (localCount > count)\n count = localCount;\n }\n else if (sortCounts(i) != sortCounts(i + 1))\n {\n localCount = 0;\n count++;\n }\n else\n {\n localCount++;\n if (localCount > count)\n {\n count = localCount;\n if (localCount == 1)\n element = sortCounts(i);\n }\n }\n }\n return element;\n}\n\n\/**\n * Returns 1 if all the values of featureRow are not same.\n *\n * @param featureRow The attribute which is checked for identical values.\n *\/\ntemplate <typename MatType>\ntemplate <typename rType>\nint DecisionStump<MatType>::isDistinct(const arma::Row<rType>& featureRow)\n{\n if (featureRow.max() - featureRow.min() > 0)\n return 1;\n else\n return 0;\n}\n\n\/**\n * Calculate entropy of attribute.\n *\n * @param attribute The attribute for which we calculate the entropy.\n * @param labels Corresponding labels of the attribute.\n *\/\ntemplate<typename MatType>\ndouble DecisionStump<MatType>::CalculateEntropy(const arma::rowvec& attribute,\n const arma::rowvec& labels)\n{\n double entropy = 0.0;\n\n arma::rowvec uniqueAtt = arma::unique(attribute);\n arma::rowvec uniqueLabel = arma::unique(labels);\n arma::Row<size_t> numElem(uniqueAtt.n_elem);\n numElem.fill(0);\n arma::Mat<size_t> entropyArray(uniqueAtt.n_elem,numClass);\n entropyArray.fill(0);\n\n \/\/ Populate entropyArray and numElem; they are used as helpers to calculate\n \/\/ entropy.\n for (int j = 0; j < uniqueAtt.n_elem; j++)\n {\n for (int i = 0; i < attribute.n_elem; i++)\n {\n if (uniqueAtt[j] == attribute[i])\n {\n entropyArray(j,labels(i))++;\n numElem(j)++;\n }\n }\n }\n\n for (int j = 0; j < uniqueAtt.size(); j++)\n {\n const double p1 = ((double) numElem(j) \/ attribute.n_elem);\n\n for (int i = 0; i < numClass; i++)\n {\n const double p2 = ((double) entropyArray(j, i) \/ numElem(j));\n const double p3 = (p2 == 0) ? 0 : p2 * log2(p2);\n\n entropy += p1 * p3;\n }\n }\n\n return entropy;\n}\n\n}; \/\/ namespace decision_stump\n}; \/\/ namespace mlpack\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2016 Alexander Gallego. All rights reserved.\n\/\/\n#include <experimental\/optional>\n#include <iostream>\n#include <memory>\n#include <vector>\n\n#include <boost\/algorithm\/string.hpp>\n#include <boost\/filesystem.hpp>\n#include <flatbuffers\/flatbuffers.h>\n#include <flatbuffers\/util.h>\n#include <gflags\/gflags.h>\n#include <glog\/logging.h>\n\n#include \"codegen.h\"\n\nDEFINE_string(filename, \"\", \"filename to parse\");\nDEFINE_string(include_dirs, \"\", \"extra include directories\");\nDEFINE_string(language, \"cpp\",\n \"coma separated list of language to generate: go, cpp\");\nDEFINE_string(output_path, \".\", \"output path of the generated files\");\n\nstd::vector<std::string>\nsplit_coma(const std::string &dirs) {\n std::vector<std::string> retval;\n boost::algorithm::split(retval, dirs, boost::is_any_of(\",\"));\n if (retval.empty() && !dirs.empty()) { retval.push_back(dirs); }\n for (auto &s : retval) {\n boost::algorithm::trim(s);\n }\n return retval;\n}\n\nstd::vector<smf_gen::language>\nsplit_langs(const std::string &lang) {\n \/\/ Note: be sure to add the generator in codegen.cc\n std::vector<smf_gen::language> retval;\n auto str_langs = split_coma(lang);\n for (auto &l : str_langs) {\n if (l == \"cpp\") {\n retval.push_back(smf_gen::language::cpp);\n } else if (l == \"go\") {\n retval.push_back(smf_gen::language::go);\n } else {\n LOG(ERROR) << \"Skipping unknown language: \" << l;\n }\n }\n return retval;\n}\n\nint\nmain(int argc, char **argv, char **env) {\n google::SetUsageMessage(\"Generate smf services\");\n google::ParseCommandLineFlags(&argc, &argv, true);\n google::InstallFailureSignalHandler();\n google::InitGoogleLogging(argv[0]);\n\n \/\/ validate flags\n if (FLAGS_filename.empty()) {\n LOG(ERROR) << \"No filename to parse\";\n std::exit(1);\n }\n if (!boost::filesystem::exists(FLAGS_filename)) {\n LOG(ERROR) << \" ` \" << FLAGS_filename\n << \" ' - does not exists or could not be found\";\n std::exit(1);\n }\n if (FLAGS_output_path.empty()) {\n LOG(ERROR) << \" ` \" << FLAGS_output_path << \" ' - empty output path\";\n std::exit(1);\n }\n FLAGS_output_path =\n boost::filesystem::canonical(FLAGS_output_path.c_str()).string();\n if (!flatbuffers::DirExists(FLAGS_output_path.c_str())) {\n LOG(ERROR) << \"--output_path specified, but directory: \"\n << FLAGS_output_path << \" does not exist;\";\n std::exit(1);\n }\n\n auto codegenerator = std::make_unique<smf_gen::codegen>(\n FLAGS_filename, FLAGS_output_path, split_coma(FLAGS_include_dirs),\n split_langs(FLAGS_language));\n \/\/ generate code!\n auto status = codegenerator->parse();\n if (status) {\n LOG(ERROR) << \"Failed to parse file: \" << status.value();\n std::exit(1);\n }\n if (codegenerator->service_count() == 0) {\n LOG(INFO) << \"No services need to be generated\";\n return 0;\n }\n status = codegenerator->gen();\n if (status) {\n LOG(ERROR) << \"Errors generating code: \" << *status;\n std::exit(1);\n }\n VLOG(1) << \"Success\";\n return 0;\n}\n<commit_msg>smfc: always generate output files<commit_after>\/\/ Copyright (c) 2016 Alexander Gallego. All rights reserved.\n\/\/\n#include <experimental\/optional>\n#include <iostream>\n#include <memory>\n#include <vector>\n\n#include <boost\/algorithm\/string.hpp>\n#include <boost\/filesystem.hpp>\n#include <flatbuffers\/flatbuffers.h>\n#include <flatbuffers\/util.h>\n#include <gflags\/gflags.h>\n#include <glog\/logging.h>\n\n#include \"codegen.h\"\n\nDEFINE_string(filename, \"\", \"filename to parse\");\nDEFINE_string(include_dirs, \"\", \"extra include directories\");\nDEFINE_string(language, \"cpp\",\n \"coma separated list of language to generate: go, cpp\");\nDEFINE_string(output_path, \".\", \"output path of the generated files\");\n\nstd::vector<std::string>\nsplit_coma(const std::string &dirs) {\n std::vector<std::string> retval;\n boost::algorithm::split(retval, dirs, boost::is_any_of(\",\"));\n if (retval.empty() && !dirs.empty()) { retval.push_back(dirs); }\n for (auto &s : retval) {\n boost::algorithm::trim(s);\n }\n return retval;\n}\n\nstd::vector<smf_gen::language>\nsplit_langs(const std::string &lang) {\n \/\/ Note: be sure to add the generator in codegen.cc\n std::vector<smf_gen::language> retval;\n auto str_langs = split_coma(lang);\n for (auto &l : str_langs) {\n if (l == \"cpp\") {\n retval.push_back(smf_gen::language::cpp);\n } else if (l == \"go\") {\n retval.push_back(smf_gen::language::go);\n } else {\n LOG(ERROR) << \"Skipping unknown language: \" << l;\n }\n }\n return retval;\n}\n\nint\nmain(int argc, char **argv, char **env) {\n google::SetUsageMessage(\"Generate smf services\");\n google::ParseCommandLineFlags(&argc, &argv, true);\n google::InstallFailureSignalHandler();\n google::InitGoogleLogging(argv[0]);\n\n \/\/ validate flags\n if (FLAGS_filename.empty()) {\n LOG(ERROR) << \"No filename to parse\";\n std::exit(1);\n }\n if (!boost::filesystem::exists(FLAGS_filename)) {\n LOG(ERROR) << \" ` \" << FLAGS_filename\n << \" ' - does not exists or could not be found\";\n std::exit(1);\n }\n if (FLAGS_output_path.empty()) {\n LOG(ERROR) << \" ` \" << FLAGS_output_path << \" ' - empty output path\";\n std::exit(1);\n }\n FLAGS_output_path =\n boost::filesystem::canonical(FLAGS_output_path.c_str()).string();\n if (!flatbuffers::DirExists(FLAGS_output_path.c_str())) {\n LOG(ERROR) << \"--output_path specified, but directory: \"\n << FLAGS_output_path << \" does not exist;\";\n std::exit(1);\n }\n\n auto codegenerator = std::make_unique<smf_gen::codegen>(\n FLAGS_filename, FLAGS_output_path, split_coma(FLAGS_include_dirs),\n split_langs(FLAGS_language));\n \/\/ generate code!\n auto status = codegenerator->parse();\n if (status) {\n LOG(ERROR) << \"Failed to parse file: \" << status.value();\n std::exit(1);\n }\n if (codegenerator->service_count() == 0) {\n LOG(INFO) << \"No services need to be generated\";\n \/\/ if we return 0, the cmake module cannot detect if we generate a file or not\n \/\/ and always calls smfc\n \/\/ return 0;\n }\n status = codegenerator->gen();\n if (status) {\n LOG(ERROR) << \"Errors generating code: \" << *status;\n std::exit(1);\n }\n VLOG(1) << \"Success\";\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"dsa_common.h\"\n\n#include \"variant.h\"\n\nnamespace dsa {\nVariant::Variant(int64_t v) : BaseVariant(v) {}\n\nVariant::Variant(double v) : BaseVariant(v) {}\n\nVariant::Variant(bool v) : BaseVariant(v) {}\n\nVariant::Variant(const char* v, size_t size)\n : BaseVariant(std::string(v, size)) {}\nVariant::Variant(const std::string& v) : BaseVariant(v) {}\nVariant::Variant(const std::string* p)\n : BaseVariant(intrusive_ptr_<VariantString>(new VariantString(*p))) {}\n\nVariant::Variant(const uint8_t* v, size_t size)\n : BaseVariant(std::vector<uint8_t>(v, v + size)) {}\nVariant::Variant(const std::vector<uint8_t>& v) : BaseVariant(v) {}\nVariant::Variant(const std::vector<uint8_t>* p)\n : BaseVariant(intrusive_ptr_<VariantBinary>(new VariantBinary(*p))) {}\n\nVariant::Variant() : BaseVariant(boost::blank()) {}\nVariant::Variant(VariantMap* p) : BaseVariant(intrusive_ptr_<VariantMap>(p)) {}\nVariant::Variant(VariantArray* p)\n : BaseVariant(intrusive_ptr_<VariantArray>(new VariantArray(*p))) {}\n\nVariant* Variant::new_map() { return new Variant(new VariantMap()); }\nVariant* Variant::new_array() { return new Variant(new VariantArray()); }\n\nVariant* Variant::copy() const {\n switch (which()) {\n case Map: {\n auto new_map = new VariantMap();\n VariantMap& map = get_map();\n\n for (auto &it : map) {\n (*new_map)[it.first] = Variant(it.second);\n }\n return new Variant(new_map);\n }\n case Array: {\n auto new_array = new VariantArray();\n VariantArray& array = get_array();\n new_array->reserve(array.size());\n\n for (auto &it : array) {\n new_array->push_back(Variant(it));\n }\n return new Variant(new_array);\n }\n default:\n return new Variant(*this);\n }\n}\n\nVariant* Variant::deep_copy() const {\n switch (which()) {\n case Map: {\n auto new_map = new VariantMap();\n VariantMap& map = get_map();\n\n for (auto &it : map) {\n (*new_map)[it.first] = *(it.second.deep_copy());\n }\n return new Variant(new_map);\n }\n case Array: {\n auto new_array = new VariantArray();\n VariantArray& array = get_array();\n new_array->reserve(array.size());\n\n for (auto &it : array) {\n new_array->push_back(*(it.deep_copy()));\n }\n return new Variant(new_array);\n }\n default:\n return new Variant(*this);\n }\n}\n\n} \/\/ namespace dsa\n<commit_msg>Change VariantArray constructor code<commit_after>#include \"dsa_common.h\"\n\n#include \"variant.h\"\n\nnamespace dsa {\nVariant::Variant(int64_t v) : BaseVariant(v) {}\n\nVariant::Variant(double v) : BaseVariant(v) {}\n\nVariant::Variant(bool v) : BaseVariant(v) {}\n\nVariant::Variant(const char* v, size_t size)\n : BaseVariant(std::string(v, size)) {}\nVariant::Variant(const std::string& v) : BaseVariant(v) {}\nVariant::Variant(const std::string* p)\n : BaseVariant(intrusive_ptr_<VariantString>(new VariantString(*p))) {}\n\nVariant::Variant(const uint8_t* v, size_t size)\n : BaseVariant(std::vector<uint8_t>(v, v + size)) {}\nVariant::Variant(const std::vector<uint8_t>& v) : BaseVariant(v) {}\nVariant::Variant(const std::vector<uint8_t>* p)\n : BaseVariant(intrusive_ptr_<VariantBinary>(new VariantBinary(*p))) {}\n\nVariant::Variant() : BaseVariant(boost::blank()) {}\nVariant::Variant(VariantMap* p) : BaseVariant(intrusive_ptr_<VariantMap>(p)) {}\nVariant::Variant(VariantArray* p)\n : BaseVariant(intrusive_ptr_<VariantArray>(p)) {}\n\nVariant* Variant::new_map() { return new Variant(new VariantMap()); }\nVariant* Variant::new_array() { return new Variant(new VariantArray()); }\n\nVariant* Variant::copy() const {\n switch (which()) {\n case Map: {\n auto new_map = new VariantMap();\n VariantMap& map = get_map();\n\n for (auto &it : map) {\n (*new_map)[it.first] = Variant(it.second);\n }\n return new Variant(new_map);\n }\n case Array: {\n auto new_array = new VariantArray();\n VariantArray& array = get_array();\n new_array->reserve(array.size());\n\n for (auto &it : array) {\n new_array->push_back(Variant(it));\n }\n return new Variant(new_array);\n }\n default:\n return new Variant(*this);\n }\n}\n\nVariant* Variant::deep_copy() const {\n switch (which()) {\n case Map: {\n auto new_map = new VariantMap();\n VariantMap& map = get_map();\n\n for (auto &it : map) {\n (*new_map)[it.first] = *(it.second.deep_copy());\n }\n return new Variant(new_map);\n }\n case Array: {\n auto new_array = new VariantArray();\n VariantArray& array = get_array();\n new_array->reserve(array.size());\n\n for (auto &it : array) {\n new_array->push_back(*(it.deep_copy()));\n }\n return new Variant(new_array);\n }\n default:\n return new Variant(*this);\n }\n}\n\n} \/\/ namespace dsa\n<|endoftext|>"} {"text":"<commit_before>\/*\n Copyright 2014 Software Reliability Lab, ETH Zurich\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n *\/\n\n#include \"nice2server.h\"\n\n#include \"glog\/logging.h\"\n#include \"jsoncpp\/json\/json.h\"\n#include \"jsonrpccpp\/server.h\"\n#include \"jsonrpccpp\/server\/connectors\/httpserver.h\"\n#include \"jsonrpccpp\/common\/exception.h\"\n\n#include \"stringprintf.h\"\n\n#include \"graph_inference.h\"\n#include \"server_log.h\"\n#include \"inference.h\"\n\nDEFINE_string(model, \"model\", \"Input model files\");\nDEFINE_string(model_version, \"\", \"Version of the current model\");\n\nDEFINE_string(logfile_prefix, \"\", \"File where to log all requests and responses\");\n\nnamespace {\nvoid DropTrainingNewLine(std::string* s) {\n if (s->empty()) return;\n if ((*s)[s->size() - 1] == '\\n') s->erase(s->begin() + s->size() - 1, s->end());\n}\n}\n\nclass Nice2ServerInternal : public jsonrpc::AbstractServer<Nice2ServerInternal> {\npublic:\n Nice2ServerInternal(jsonrpc::HttpServer* server) : jsonrpc::AbstractServer<Nice2ServerInternal>(*server) {\n bindAndAddMethod(\n jsonrpc::Procedure(\"infer\", jsonrpc::PARAMS_BY_NAME, jsonrpc::JSON_ARRAY,\n \/\/ Parameters:\n \"query\", jsonrpc::JSON_ARRAY,\n \"assign\", jsonrpc::JSON_ARRAY,\n NULL),\n &Nice2ServerInternal::infer);\n bindAndAddMethod(\n jsonrpc::Procedure(\"nbest\", jsonrpc::PARAMS_BY_NAME, jsonrpc::JSON_ARRAY,\n \/\/ Parameters:\n \"n\", jsonrpc::JSON_INTEGER,\n \"query\", jsonrpc::JSON_ARRAY,\n \"assign\", jsonrpc::JSON_ARRAY,\n NULL),\n &Nice2ServerInternal::nbest);\n\n bindAndAddMethod(\n jsonrpc::Procedure(\"showgraph\", jsonrpc::PARAMS_BY_NAME, jsonrpc::JSON_OBJECT,\n \/\/ Parameters:\n \"query\", jsonrpc::JSON_ARRAY,\n \"assign\", jsonrpc::JSON_ARRAY,\n NULL),\n &Nice2ServerInternal::showgraph);\n\n inference_.LoadModel(FLAGS_model);\n\n if (!FLAGS_logfile_prefix.empty()) {\n logging_.reset(new Nice2ServerLog(FLAGS_logfile_prefix));\n }\n }\n\n void verifyVersion(const Json::Value& request){\n VLOG(3) << \"Current version: \" << FLAGS_model_version << \". Request version: \" << request[\"version\"];\n if (FLAGS_model_version.empty()){\n return;\n }\n\n if (!request.isMember(\"version\") ||\n strcmp(request[\"version\"].asCString(), FLAGS_model_version.c_str()) != 0){\n std::ostringstream stringStream;\n stringStream << \"The version of client '\" << request[\"version\"].asString() <<\n \"' does not match the server version '\" << FLAGS_model_version << \"'. \" <<\n \"Please update the client to the latest version by running 'npm update -g unuglify-js'.\";\n throw jsonrpc::JsonRpcException(-31001, stringStream.str());\n }\n }\n\n\n void MaybeLogQuery(const char* method, const Json::Value& request, const Json::Value& response) {\n if (logging_.get() == NULL) {\n return;\n }\n\n Json::FastWriter writer;\n std::string rs1 = writer.write(request);\n std::string rs2 = writer.write(response);\n DropTrainingNewLine(&rs1);\n DropTrainingNewLine(&rs2);\n logging_->LogRecord(StringPrintf(\n \"\\\"method\\\":\\\"%s\\\", \"\n \"\\\"request\\\":%s, \"\n \"\\\"reply\\\":%s\",\n method, rs1.c_str(), rs2.c_str()));\n }\n\n\n void infer(const Json::Value& request, Json::Value& response)\n {\n VLOG(3) << request.toStyledString();\n verifyVersion(request);\n std::unique_ptr<Nice2Query> query(inference_.CreateQuery());\n query->FromJSON(request[\"query\"]);\n std::unique_ptr<Nice2Assignment> assignment(inference_.CreateAssignment(query.get()));\n assignment->FromJSON(request[\"assign\"]);\n inference_.MapInference(query.get(), assignment.get());\n assignment->ToJSON(&response);\n\n MaybeLogQuery(\"infer\", request, response);\n }\n\n void nbest(const Json::Value& request, Json::Value& response)\n {\n int n = request[\"n\"].asInt();\n int v = request[\"v\"].asInt();\n\n VLOG(3) << request.toStyledString();\n verifyVersion(request);\n std::unique_ptr<Nice2Query> query(inference_.CreateQuery());\n query->FromJSON(request[\"query\"]);\n std::unique_ptr<Nice2Assignment> assignment(inference_.CreateAssignment(query.get()));\n assignment->FromJSON(request[\"assign\"]);\n inference_.MapInference(query.get(), assignment.get());\n assignment->GetCandidates(inference_, v, n, &response);\n\n MaybeLogQuery(\"nbest\", request, response);\n }\n\n void showgraph(const Json::Value& request, Json::Value& response)\n {\n VLOG(3) << request.toStyledString();\n std::unique_ptr<Nice2Query> query(inference_.CreateQuery());\n query->FromJSON(request[\"query\"]);\n std::unique_ptr<Nice2Assignment> assignment(inference_.CreateAssignment(query.get()));\n assignment->FromJSON(request[\"assign\"]);\n if (request.isMember(\"infer\") && request[\"infer\"].asBool() == true) {\n inference_.MapInference(query.get(), assignment.get());\n }\n inference_.DisplayGraph(query.get(), assignment.get(), &response);\n\n MaybeLogQuery(\"showgraph\", request, response);\n }\n\nprivate:\n GraphInference inference_;\n std::unique_ptr<Nice2ServerLog> logging_;\n};\n\nNice2Server::Nice2Server(jsonrpc::HttpServer* server)\n : internal_(new Nice2ServerInternal(server)) {\n}\n\nNice2Server::~Nice2Server() {\n delete internal_;\n}\n\nvoid Nice2Server::Listen() {\n internal_->StartListening();\n LOG(INFO) << \"Nice2Server started.\";\n for (;;) {\n sleep(1);\n }\n internal_->StopListening();\n}\n<commit_msg>adding \"infer\" (true\/false) parameter to nbest<commit_after>\/*\n Copyright 2014 Software Reliability Lab, ETH Zurich\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n *\/\n\n#include \"nice2server.h\"\n\n#include \"glog\/logging.h\"\n#include \"jsoncpp\/json\/json.h\"\n#include \"jsonrpccpp\/server.h\"\n#include \"jsonrpccpp\/server\/connectors\/httpserver.h\"\n#include \"jsonrpccpp\/common\/exception.h\"\n\n#include \"stringprintf.h\"\n\n#include \"graph_inference.h\"\n#include \"server_log.h\"\n#include \"inference.h\"\n\nDEFINE_string(model, \"model\", \"Input model files\");\nDEFINE_string(model_version, \"\", \"Version of the current model\");\n\nDEFINE_string(logfile_prefix, \"\", \"File where to log all requests and responses\");\n\nnamespace {\nvoid DropTrainingNewLine(std::string* s) {\n if (s->empty()) return;\n if ((*s)[s->size() - 1] == '\\n') s->erase(s->begin() + s->size() - 1, s->end());\n}\n}\n\nclass Nice2ServerInternal : public jsonrpc::AbstractServer<Nice2ServerInternal> {\npublic:\n Nice2ServerInternal(jsonrpc::HttpServer* server) : jsonrpc::AbstractServer<Nice2ServerInternal>(*server) {\n bindAndAddMethod(\n jsonrpc::Procedure(\"infer\", jsonrpc::PARAMS_BY_NAME, jsonrpc::JSON_ARRAY,\n \/\/ Parameters:\n \"query\", jsonrpc::JSON_ARRAY,\n \"assign\", jsonrpc::JSON_ARRAY,\n NULL),\n &Nice2ServerInternal::infer);\n bindAndAddMethod(\n jsonrpc::Procedure(\"nbest\", jsonrpc::PARAMS_BY_NAME, jsonrpc::JSON_ARRAY,\n \/\/ Parameters:\n \"n\", jsonrpc::JSON_INTEGER,\n \"query\", jsonrpc::JSON_ARRAY,\n \"assign\", jsonrpc::JSON_ARRAY,\n NULL),\n &Nice2ServerInternal::nbest);\n\n bindAndAddMethod(\n jsonrpc::Procedure(\"showgraph\", jsonrpc::PARAMS_BY_NAME, jsonrpc::JSON_OBJECT,\n \/\/ Parameters:\n \"query\", jsonrpc::JSON_ARRAY,\n \"assign\", jsonrpc::JSON_ARRAY,\n NULL),\n &Nice2ServerInternal::showgraph);\n\n inference_.LoadModel(FLAGS_model);\n\n if (!FLAGS_logfile_prefix.empty()) {\n logging_.reset(new Nice2ServerLog(FLAGS_logfile_prefix));\n }\n }\n\n void verifyVersion(const Json::Value& request){\n VLOG(3) << \"Current version: \" << FLAGS_model_version << \". Request version: \" << request[\"version\"];\n if (FLAGS_model_version.empty()){\n return;\n }\n\n if (!request.isMember(\"version\") ||\n strcmp(request[\"version\"].asCString(), FLAGS_model_version.c_str()) != 0){\n std::ostringstream stringStream;\n stringStream << \"The version of client '\" << request[\"version\"].asString() <<\n \"' does not match the server version '\" << FLAGS_model_version << \"'. \" <<\n \"Please update the client to the latest version by running 'npm update -g unuglify-js'.\";\n throw jsonrpc::JsonRpcException(-31001, stringStream.str());\n }\n }\n\n\n void MaybeLogQuery(const char* method, const Json::Value& request, const Json::Value& response) {\n if (logging_.get() == NULL) {\n return;\n }\n\n Json::FastWriter writer;\n std::string rs1 = writer.write(request);\n std::string rs2 = writer.write(response);\n DropTrainingNewLine(&rs1);\n DropTrainingNewLine(&rs2);\n logging_->LogRecord(StringPrintf(\n \"\\\"method\\\":\\\"%s\\\", \"\n \"\\\"request\\\":%s, \"\n \"\\\"reply\\\":%s\",\n method, rs1.c_str(), rs2.c_str()));\n }\n\n\n void infer(const Json::Value& request, Json::Value& response)\n {\n VLOG(3) << request.toStyledString();\n verifyVersion(request);\n std::unique_ptr<Nice2Query> query(inference_.CreateQuery());\n query->FromJSON(request[\"query\"]);\n std::unique_ptr<Nice2Assignment> assignment(inference_.CreateAssignment(query.get()));\n assignment->FromJSON(request[\"assign\"]);\n inference_.MapInference(query.get(), assignment.get());\n assignment->ToJSON(&response);\n\n MaybeLogQuery(\"infer\", request, response);\n }\n\n void nbest(const Json::Value& request, Json::Value& response)\n {\n int n = request[\"n\"].asInt();\n int v = request[\"v\"].asInt();\n bool shouldInfer = request[\"infer\"].asBool();\n\n VLOG(3) << request.toStyledString();\n verifyVersion(request);\n std::unique_ptr<Nice2Query> query(inference_.CreateQuery());\n query->FromJSON(request[\"query\"]);\n std::unique_ptr<Nice2Assignment> assignment(inference_.CreateAssignment(query.get()));\n assignment->FromJSON(request[\"assign\"]);\n if (shouldInfer) {\n inference_.MapInference(query.get(), assignment.get());\n }\n assignment->GetCandidates(inference_, v, n, &response);\n\n MaybeLogQuery(\"nbest\", request, response);\n }\n\n void showgraph(const Json::Value& request, Json::Value& response)\n {\n VLOG(3) << request.toStyledString();\n std::unique_ptr<Nice2Query> query(inference_.CreateQuery());\n query->FromJSON(request[\"query\"]);\n std::unique_ptr<Nice2Assignment> assignment(inference_.CreateAssignment(query.get()));\n assignment->FromJSON(request[\"assign\"]);\n if (request.isMember(\"infer\") && request[\"infer\"].asBool() == true) {\n inference_.MapInference(query.get(), assignment.get());\n }\n inference_.DisplayGraph(query.get(), assignment.get(), &response);\n\n MaybeLogQuery(\"showgraph\", request, response);\n }\n\nprivate:\n GraphInference inference_;\n std::unique_ptr<Nice2ServerLog> logging_;\n};\n\nNice2Server::Nice2Server(jsonrpc::HttpServer* server)\n : internal_(new Nice2ServerInternal(server)) {\n}\n\nNice2Server::~Nice2Server() {\n delete internal_;\n}\n\nvoid Nice2Server::Listen() {\n internal_->StartListening();\n LOG(INFO) << \"Nice2Server started.\";\n for (;;) {\n sleep(1);\n }\n internal_->StopListening();\n}\n<|endoftext|>"} {"text":"<commit_before>#include <SFML\/Graphics.hpp>\n#include <iostream>\n#include <chrono>\n#include <thread>\nusing namespace std;\n\nstatic const string textureNames[]{\"spaceship1.png\",\n \"spaceship2.png\",\n \"spaceship3.png\",\n \"Spaceship-Drakir1.png\",\n \"Spaceship-Drakir2.png\",\n \"Spaceship-Drakir3.png\",\n \"Spaceship-Drakir4.png\",\n \"Spaceship-Drakir5.png\",\n \"Spaceship-Drakir6.png\",\n \"Spaceship-Drakir7.png\",\n \"bullet.png\"};\n\nstatic sf::Texture *textures[11];\n\nstatic const string filepath = \"..\\\\res\/img\/\";\n\n#define MAX_ENEMIES 255\nstatic unsigned int currentEnemies = 0;\nstatic sf::Sprite enemies[MAX_ENEMIES];\n\nstatic sf::Vector2f GetNewEnemyPos() {\n return sf::Vector2f(rand() % 1024, -128.0f);\n}\n\nsf::Sprite playerSprite;\nsf::Texture *playerTexture;\nsf::Sprite bulletsprite;\nsf::Texture *bulletTexture;\nvoid Loadcontent() {\n\n for (size_t i = 0; i < 11; i++) {\n textures[i] = new sf::Texture();\n if (!textures[i]->loadFromFile(filepath + textureNames[i])) {\n throw invalid_argument(\"Loading error!\");\n }\n }\n\n playerSprite.setTexture(*textures[0]);\n playerSprite.setPosition(512, 256);\n bulletsprite.setTexture(*textures[10]);\n\n for (size_t i = 0; i < MAX_ENEMIES; i++) {\n enemies[i].setTexture(*textures[(i % 7) + 3]);\n enemies[i].setPosition(GetNewEnemyPos());\n }\n}\n\nstatic chrono::high_resolution_clock::time_point previous;\nstatic unsigned int score;\n\nvoid Update(sf::RenderWindow &window) {\n\n chrono::high_resolution_clock::time_point now =\n chrono::high_resolution_clock::now();\n const unsigned int delta =\n (std::chrono::duration_cast<std::chrono::duration<int, std::nano>>(\n now - previous))\n .count();\n\n const double deltaPercent =\n (((double)delta) \/ 1000000000.0); \/\/ delta as a percentage of 1 second\n previous = now;\n\n static float tick = 0.0f;\n tick += deltaPercent;\n score = (unsigned int)ceil(tick);\n currentEnemies = (unsigned int)ceil(tick * 0.6f) + 1;\n\n cout << score << \" - \" << currentEnemies << \" - \" << delta << \" - \"\n << deltaPercent << endl;\n\n sf::Event e;\n\n while (window.pollEvent(e)) {\n if (e.type == sf::Event::Closed)\n window.close();\n\n \/\/ keyboard event handling\n if (e.type == sf::Event::KeyPressed) {\n if (e.key.code == sf::Keyboard::Escape) {\n window.close();\n }\n\n if (e.key.code == sf::Keyboard::W) {\n playerSprite.setPosition(playerSprite.getPosition().x,\n playerSprite.getPosition().y - tick);\n }\n\n if (e.key.code == sf::Keyboard::S) {\n playerSprite.setPosition(playerSprite.getPosition().x,\n playerSprite.getPosition().y + tick);\n }\n if (e.key.code == sf::Keyboard::A) {\n playerSprite.setPosition(playerSprite.getPosition().x - tick,\n playerSprite.getPosition().y);\n }\n if (e.key.code == sf::Keyboard::D) {\n playerSprite.setPosition(playerSprite.getPosition().x + tick,\n playerSprite.getPosition().y);\n }\n }\n \/\/ joystick input\n if (sf::Joystick::isConnected(0)) {\n float joystickX = sf::Joystick::getAxisPosition(0, sf::Joystick::X);\n float joystickY = sf::Joystick::getAxisPosition(0, sf::Joystick::Y);\n\n playerSprite.setPosition(playerSprite.getPosition().x + (joystickX * 0.1),\n playerSprite.getPosition().y +\n (joystickY * 0.1));\n\n \/\/ if the B button is pressed fire a bullet\n if (e.JoystickButtonPressed) {\n if (e.joystickButton.button == 0) {\n bulletsprite.setPosition(playerSprite.getPosition().x + 30,\n playerSprite.getPosition().y - 1);\n }\n }\n\n bulletsprite.setPosition(bulletsprite.getPosition().x,\n bulletsprite.getPosition().y - tick);\n }\n }\n\n for (size_t i = 0; i < MAX_ENEMIES; i++) {\n if (i < currentEnemies) {\n \/\/ if not dead, move\n if (enemies[i].getPosition().y < 700.0) {\n enemies[i].setPosition(\n enemies[i].getPosition() +\n sf::Vector2f(sinf(tick + i) * 100.0 * deltaPercent,\n 100.0 * deltaPercent));\n } else {\n \/\/ ofscreen kill\n enemies[i].setPosition(GetNewEnemyPos());\n }\n } else {\n \/\/ if alive\n if (enemies[i].getPosition().y != -128.0f) {\n \/\/ kill\n enemies[i].setPosition(GetNewEnemyPos());\n }\n }\n }\n}\n\nvoid Render(sf::RenderWindow &window) {\n window.clear();\n\n window.draw(playerSprite);\n window.draw(bulletsprite);\n for (size_t i = 0; i < MAX_ENEMIES; i++) {\n window.draw(enemies[i]);\n }\n\n window.display();\n}\n\nint main() {\n Loadcontent();\n sf::RenderWindow window(sf::VideoMode(1024, 768), \"Main Window\");\n window.setVerticalSyncEnabled(true);\n previous = chrono::high_resolution_clock::now();\n while (window.isOpen()) {\n Update(window);\n Render(window);\n }\n return 0;\n}<commit_msg>movement speed fixes<commit_after>#include <SFML\/Graphics.hpp>\n#include <SFML\/System\/Vector2.hpp>\n#include <iostream>\n#include <chrono>\n#include <thread>\nusing namespace std;\n\nstatic const string textureNames[]{\"spaceship1.png\",\n \"spaceship2.png\",\n \"spaceship3.png\",\n \"Spaceship-Drakir1.png\",\n \"Spaceship-Drakir2.png\",\n \"Spaceship-Drakir3.png\",\n \"Spaceship-Drakir4.png\",\n \"Spaceship-Drakir5.png\",\n \"Spaceship-Drakir6.png\",\n \"Spaceship-Drakir7.png\",\n \"bullet.png\"};\n\nstatic sf::Texture *textures[11];\n\nstatic const string filepath = \"..\\\\res\/img\/\";\n\n#define MAX_ENEMIES 255\nstatic unsigned int currentEnemies = 0;\nstatic sf::Sprite enemies[MAX_ENEMIES];\n\nfloat playerMoveSpeed = 600.0f;\n\nstatic sf::Vector2f GetNewEnemyPos() {\n return sf::Vector2f(rand() % 1024, -128.0f);\n}\n\nsf::Sprite playerSprite;\nsf::Texture *playerTexture;\nsf::Sprite bulletsprite;\nsf::Texture *bulletTexture;\nvoid Loadcontent() {\n\n for (size_t i = 0; i < 11; i++) {\n textures[i] = new sf::Texture();\n if (!textures[i]->loadFromFile(filepath + textureNames[i])) {\n throw invalid_argument(\"Loading error!\");\n }\n }\n\n playerSprite.setTexture(*textures[0]);\n playerSprite.setPosition(512, 256);\n bulletsprite.setTexture(*textures[10]);\n\n for (size_t i = 0; i < MAX_ENEMIES; i++) {\n enemies[i].setTexture(*textures[(i % 7) + 3]);\n enemies[i].setPosition(GetNewEnemyPos());\n }\n}\nvoid Normalize(sf::Vector2f &v) {\n auto length = sqrt(v.x * v.x + v.y * v.y);\n if (length == 0.0f) {\n return;\n }\n \/\/ normalize vector\n v.x \/= length;\n v.y \/= length;\n}\n\nstatic chrono::high_resolution_clock::time_point previous;\nstatic unsigned int score;\n\nvoid Update(sf::RenderWindow &window) {\n\n chrono::high_resolution_clock::time_point now =\n chrono::high_resolution_clock::now();\n const unsigned int delta =\n (std::chrono::duration_cast<std::chrono::duration<int, std::nano>>(\n now - previous))\n .count();\n\n const double deltaPercent =\n (((double)delta) \/ 1000000000.0); \/\/ delta as a percentage of 1 second\n previous = now;\n\n static float tick = 0.0f;\n tick += deltaPercent;\n score = (unsigned int)ceil(tick);\n currentEnemies = (unsigned int)ceil(tick * 0.6f) + 1;\n\n \/\/ cout << score << \" - \" << currentEnemies << \" - \" << delta << \" - \" <<\n \/\/ deltaPercent << endl;\n\n sf::Event e;\n sf::Vector2f moveDirection(0, 0);\n\n while (window.pollEvent(e)) {\n if (e.type == sf::Event::Closed)\n window.close();\n\n \/\/ keyboard event handling\n if (e.type == sf::Event::KeyPressed) {\n if (e.key.code == sf::Keyboard::Escape) {\n window.close();\n }\n if (e.key.code == sf::Keyboard::W || e.key.code == sf::Keyboard::Up) {\n moveDirection += sf::Vector2f(0, -1);\n }\n if (e.key.code == sf::Keyboard::S || e.key.code == sf::Keyboard::Down) {\n moveDirection += sf::Vector2f(0, 1);\n }\n if (e.key.code == sf::Keyboard::A || e.key.code == sf::Keyboard::Left) {\n moveDirection += sf::Vector2f(-1, 0);\n }\n if (e.key.code == sf::Keyboard::D || e.key.code == sf::Keyboard::Right) {\n moveDirection += sf::Vector2f(1, 0);\n }\n }\n \/\/ if the B button is pressed fire a bullet\n if (e.JoystickButtonPressed) {\n\n if (sf::Joystick::isButtonPressed(0, 1)) {\n bulletsprite.setPosition(playerSprite.getPosition().x + 30,\n playerSprite.getPosition().y - 1);\n }\n }\n }\n \/\/ joystick input\n if (sf::Joystick::isConnected(0)) {\n float joystickX = sf::Joystick::getAxisPosition(0, sf::Joystick::X);\n float joystickY = sf::Joystick::getAxisPosition(0, sf::Joystick::Y);\n\n if (abs(joystickX) > 40.0f) {\n moveDirection += sf::Vector2f(((signbit(joystickX)) * -2) + 1, 0);\n }\n if (abs(joystickY) > 40.0f) {\n moveDirection += sf::Vector2f(0, ((signbit(joystickY)) * -2) + 1);\n }\n\n Normalize(moveDirection);\n moveDirection = (moveDirection * playerMoveSpeed) * (float)deltaPercent;\n\n playerSprite.setPosition(playerSprite.getPosition() + moveDirection);\n\n bulletsprite.setPosition(bulletsprite.getPosition().x,\n bulletsprite.getPosition().y - tick);\n }\n\n for (size_t i = 0; i < MAX_ENEMIES; i++) {\n if (i < currentEnemies) {\n \/\/ if not dead, move\n if (enemies[i].getPosition().y < 700.0) {\n enemies[i].setPosition(\n enemies[i].getPosition() +\n sf::Vector2f(sinf(tick + i) * 100.0 * deltaPercent,\n 100.0 * deltaPercent));\n } else {\n \/\/ ofscreen kill\n enemies[i].setPosition(GetNewEnemyPos());\n }\n } else {\n \/\/ if alive\n if (enemies[i].getPosition().y != -128.0f) {\n \/\/ kill\n enemies[i].setPosition(GetNewEnemyPos());\n }\n }\n }\n}\n\nvoid Render(sf::RenderWindow &window) {\n window.clear();\n\n window.draw(playerSprite);\n window.draw(bulletsprite);\n for (size_t i = 0; i < MAX_ENEMIES; i++) {\n window.draw(enemies[i]);\n }\n\n window.display();\n}\n\nint main() {\n Loadcontent();\n sf::RenderWindow window(sf::VideoMode(1024, 768), \"Main Window\");\n window.setVerticalSyncEnabled(true);\n previous = chrono::high_resolution_clock::now();\n while (window.isOpen()) {\n Update(window);\n Render(window);\n }\n return 0;\n}<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2010 Satoshi Nakamoto\n\/\/ Copyright (c) 2009-2012 The Bitcoin developers\n\/\/ Distributed under the MIT\/X11 software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \"assert.h\"\n\n#include \"chainparams.h\"\n#include \"main.h\"\n#include \"util.h\"\n\n#include <boost\/assign\/list_of.hpp>\n\nusing namespace boost::assign;\n\nstruct SeedSpec6 {\n uint8_t addr[16];\n uint16_t port;\n};\n\n#include \"chainparamsseeds.h\"\n\n\/\/\n\/\/ Main network\n\/\/\n\n\/\/ Convert the pnSeeds6 array into usable address objects.\nstatic void convertSeed6(std::vector<CAddress> &vSeedsOut, const SeedSpec6 *data, unsigned int count)\n{\n \/\/ It'll only connect to one or two seed nodes because once it connects,\n \/\/ it'll get a pile of addresses with newer timestamps.\n \/\/ Seed nodes are given a random 'last seen time' of between one and two\n \/\/ weeks ago.\n const int64_t nOneWeek = 7*24*60*60;\n for (unsigned int i = 0; i < count; i++)\n {\n struct in6_addr ip;\n memcpy(&ip, data[i].addr, sizeof(ip));\n CAddress addr(CService(ip, data[i].port));\n addr.nTime = GetTime() - GetRand(nOneWeek) - nOneWeek;\n vSeedsOut.push_back(addr);\n }\n}\n\nclass CMainParams : public CChainParams {\npublic:\n CMainParams() {\n \/\/ The message start string is designed to be unlikely to occur in normal data.\n \/\/ The characters are rarely used upper ASCII, not valid as UTF-8, and produce\n \/\/ a large 4-byte int at any alignment.\n pchMessageStart[0] = 0x2a;\n pchMessageStart[1] = 0x7c;\n pchMessageStart[2] = 0xcb;\n pchMessageStart[3] = 0xab;\n vAlertPubKey = ParseHex(\"04de6a97a9b475c3b0c9bc30a0f42a5a34aa295e53230ef3a726ba7e981bd2546c42f4ff44d929c2e9ea23d21b12846254cda4747380f14a5c674063afedf47a2c\");\n nDefaultPort = 27913;\n nRPCPort = 27914;\n bnProofOfWorkLimit = CBigNum(~uint256(0) >> 20);\n\n \/\/ Build the genesis block. Note that the output of the genesis coinbase cannot\n \/\/ be spent as it did not originally exist in the database.\n \/\/\n \/\/CBlock(hash=000001faef25dec4fbcf906e6242621df2c183bf232f263d0ba5b101911e4563, ver=1, hashPrevBlock=0000000000000000000000000000000000000000000000000000000000000000, hashMerkleRoot=12630d16a97f24b287c8c2594dda5fb98c9e6c70fc61d44191931ea2aa08dc90, nTime=1429442154, nBits=1e0fffff, nNonce=164482, vtx=1, vchBlockSig=)\n \/\/ Coinbase(hash=12630d16a9, nTime=1431857735, ver=1, vin.size=1, vout.size=1, nLockTime=0)\n \/\/ CTxIn(COutPoint(0000000000, 4294967295), coinbase 00012a24323020466562203230313420426974636f696e2041544d7320636f6d6520746f20555341)\n \/\/ CTxOut(empty)\n \/\/ vMerkleTree: 12630d16a9\n const char* pszTimestamp = \"2015 xRadon coin.!\";\n std::vector<CTxIn> vin;\n vin.resize(1);\n vin[0].scriptSig = CScript() << 0 << CBigNum(42) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp));\n std::vector<CTxOut> vout;\n vout.resize(1);\n vout[0].SetEmpty();\n\t\tCTransaction txNew(1, 1431857735, vin, vout, 0);\n genesis.vtx.push_back(txNew);\n genesis.hashPrevBlock = 0;\n genesis.hashMerkleRoot = genesis.BuildMerkleTree();\n genesis.nVersion = 1;\n genesis.nTime = 1431857735;\n genesis.nBits = bnProofOfWorkLimit.GetCompact();\n genesis.nNonce = 109996;\n\n hashGenesisBlock = genesis.GetHash();\n assert(hashGenesisBlock == uint256(\"0x000000770c6aea829bb1ace7b06497f71799a6358e0e292740c4f9443a17bfb6\"));\n assert(genesis.hashMerkleRoot == uint256(\"0xa02b3388d9e8529bb0136ed3e1b823e808cbe128050e5986bf2a5a0d2c71a826\"));\n\n vSeeds.push_back(CDNSSeedData(\"194.135.82.244\", \"194.135.82.244\"));\n vSeeds.push_back(CDNSSeedData(\"useast.projectradium.org\", \"useast.projectradium.org\"));\n vSeeds.push_back(CDNSSeedData(\"asia.projectradium.org\", \"asia.projectradium.org\"));\n vSeeds.push_back(CDNSSeedData(\"eu.projectradium.org\", \"eu.projectradium.org\"));\n\n\n base58Prefixes[PUBKEY_ADDRESS] = std::vector<unsigned char>(1,76);\n base58Prefixes[SCRIPT_ADDRESS] = std::vector<unsigned char>(1,58);\n base58Prefixes[SECRET_KEY] = std::vector<unsigned char>(1,121);\n base58Prefixes[EXT_PUBLIC_KEY] = boost::assign::list_of(0x04)(0x73)(0xAA)(0xA1).convert_to_container<std::vector<unsigned char> >();\n base58Prefixes[EXT_SECRET_KEY] = boost::assign::list_of(0x04)(0x73)(0x44)(0x77).convert_to_container<std::vector<unsigned char> >();\n\n convertSeed6(vFixedSeeds, pnSeed6_main, ARRAYLEN(pnSeed6_main));\n\n nLastPOWBlock = 20160;\n }\n\n virtual const CBlock& GenesisBlock() const { return genesis; }\n virtual Network NetworkID() const { return CChainParams::MAIN; }\n\n virtual const vector<CAddress>& FixedSeeds() const {\n return vFixedSeeds;\n }\nprotected:\n CBlock genesis;\n vector<CAddress> vFixedSeeds;\n};\nstatic CMainParams mainParams;\n\n\n\/\/\n\/\/ Testnet\n\/\/\n\nclass CTestNetParams : public CMainParams {\npublic:\n CTestNetParams() {\n \/\/ The message start string is designed to be unlikely to occur in normal data.\n \/\/ The characters are rarely used upper ASCII, not valid as UTF-8, and produce\n \/\/ a large 4-byte int at any alignment.\n pchMessageStart[0] = 0xc3;\n pchMessageStart[1] = 0x77;\n pchMessageStart[2] = 0xcc;\n pchMessageStart[3] = 0x77;\n bnProofOfWorkLimit = CBigNum(~uint256(0) >> 16);\n vAlertPubKey = ParseHex(\"04593b5288f912a74491e7f36d7a1dd210a8e21b6e1933e9a98c7edb68da67cb5b248e1cd01a5c255c939ad53f441875a33c92135724863753fe5068f339cc189a\");\n nDefaultPort = 47963;\n nRPCPort = 47993;\n strDataDir = \"testnet\";\n\n \/\/ Modify the testnet genesis block so the timestamp is valid for a later start.\n genesis.nBits = bnProofOfWorkLimit.GetCompact();\n genesis.nNonce = 65880;\n hashGenesisBlock = genesis.GetHash();\n assert(hashGenesisBlock == uint256(\"0x0000dedd0118550f474631b30cfc8b9d260706d59ea89118d81d1a292a5681d9\"));\n\n vFixedSeeds.clear();\n vSeeds.clear();\n\n base58Prefixes[PUBKEY_ADDRESS] = std::vector<unsigned char>(1,110);\n base58Prefixes[SCRIPT_ADDRESS] = std::vector<unsigned char>(1,129);\n base58Prefixes[SECRET_KEY] = std::vector<unsigned char>(1,239);\n base58Prefixes[EXT_PUBLIC_KEY] = boost::assign::list_of(0x04)(0x35)(0x17)(0xFF).convert_to_container<std::vector<unsigned char> >();\n base58Prefixes[EXT_SECRET_KEY] = boost::assign::list_of(0x04)(0x35)(0x43)(0x99).convert_to_container<std::vector<unsigned char> >();\n\n convertSeed6(vFixedSeeds, pnSeed6_test, ARRAYLEN(pnSeed6_test));\n\n nLastPOWBlock = 0x7fffffff;\n }\n virtual Network NetworkID() const { return CChainParams::TESTNET; }\n};\nstatic CTestNetParams testNetParams;\n\n\n\/\/\n\/\/ Regression test\n\/\/\nclass CRegTestParams : public CTestNetParams {\npublic:\n CRegTestParams() {\n pchMessageStart[0] = 0xa1;\n pchMessageStart[1] = 0x4b;\n pchMessageStart[2] = 0x52;\n pchMessageStart[3] = 0xd7;\n bnProofOfWorkLimit = CBigNum(~uint256(0) >> 1);\n genesis.nTime = 1412222222;\n genesis.nBits = bnProofOfWorkLimit.GetCompact();\n genesis.nNonce = 0;\n hashGenesisBlock = genesis.GetHash();\n nDefaultPort = 57992;\n strDataDir = \"regtest\";\n assert(hashGenesisBlock == uint256(\"0x0a38e67a2863693c343acf471518744dc9c72e4f130916e5d27451685ed5e280\"));\n\n vSeeds.clear(); \/\/ Regtest mode doesn't have any DNS seeds.\n }\n\n virtual bool RequireRPCPassword() const { return false; }\n virtual Network NetworkID() const { return CChainParams::REGTEST; }\n};\nstatic CRegTestParams regTestParams;\n\nstatic CChainParams *pCurrentParams = &mainParams;\n\nconst CChainParams &Params() {\n return *pCurrentParams;\n}\n\nvoid SelectParams(CChainParams::Network network) {\n switch (network) {\n case CChainParams::MAIN:\n pCurrentParams = &mainParams;\n break;\n case CChainParams::TESTNET:\n pCurrentParams = &testNetParams;\n break;\n case CChainParams::REGTEST:\n pCurrentParams = ®TestParams;\n break;\n default:\n assert(false && \"Unimplemented network\");\n return;\n }\n}\n\nbool SelectParamsFromCommandLine() {\n bool fRegTest = GetBoolArg(\"-regtest\", false);\n bool fTestNet = GetBoolArg(\"-testnet\", false);\n\n if (fTestNet && fRegTest) {\n return false;\n }\n\n if (fRegTest) {\n SelectParams(CChainParams::REGTEST);\n } else if (fTestNet) {\n SelectParams(CChainParams::TESTNET);\n } else {\n SelectParams(CChainParams::MAIN);\n }\n return true;\n}\n<commit_msg>Update seed nodes<commit_after>\/\/ Copyright (c) 2010 Satoshi Nakamoto\n\/\/ Copyright (c) 2009-2012 The Bitcoin developers\n\/\/ Distributed under the MIT\/X11 software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \"assert.h\"\n\n#include \"chainparams.h\"\n#include \"main.h\"\n#include \"util.h\"\n\n#include <boost\/assign\/list_of.hpp>\n\nusing namespace boost::assign;\n\nstruct SeedSpec6 {\n uint8_t addr[16];\n uint16_t port;\n};\n\n#include \"chainparamsseeds.h\"\n\n\/\/\n\/\/ Main network\n\/\/\n\n\/\/ Convert the pnSeeds6 array into usable address objects.\nstatic void convertSeed6(std::vector<CAddress> &vSeedsOut, const SeedSpec6 *data, unsigned int count)\n{\n \/\/ It'll only connect to one or two seed nodes because once it connects,\n \/\/ it'll get a pile of addresses with newer timestamps.\n \/\/ Seed nodes are given a random 'last seen time' of between one and two\n \/\/ weeks ago.\n const int64_t nOneWeek = 7*24*60*60;\n for (unsigned int i = 0; i < count; i++)\n {\n struct in6_addr ip;\n memcpy(&ip, data[i].addr, sizeof(ip));\n CAddress addr(CService(ip, data[i].port));\n addr.nTime = GetTime() - GetRand(nOneWeek) - nOneWeek;\n vSeedsOut.push_back(addr);\n }\n}\n\nclass CMainParams : public CChainParams {\npublic:\n CMainParams() {\n \/\/ The message start string is designed to be unlikely to occur in normal data.\n \/\/ The characters are rarely used upper ASCII, not valid as UTF-8, and produce\n \/\/ a large 4-byte int at any alignment.\n pchMessageStart[0] = 0x2a;\n pchMessageStart[1] = 0x7c;\n pchMessageStart[2] = 0xcb;\n pchMessageStart[3] = 0xab;\n vAlertPubKey = ParseHex(\"04de6a97a9b475c3b0c9bc30a0f42a5a34aa295e53230ef3a726ba7e981bd2546c42f4ff44d929c2e9ea23d21b12846254cda4747380f14a5c674063afedf47a2c\");\n nDefaultPort = 27913;\n nRPCPort = 27914;\n bnProofOfWorkLimit = CBigNum(~uint256(0) >> 20);\n\n \/\/ Build the genesis block. Note that the output of the genesis coinbase cannot\n \/\/ be spent as it did not originally exist in the database.\n \/\/\n \/\/CBlock(hash=000001faef25dec4fbcf906e6242621df2c183bf232f263d0ba5b101911e4563, ver=1, hashPrevBlock=0000000000000000000000000000000000000000000000000000000000000000, hashMerkleRoot=12630d16a97f24b287c8c2594dda5fb98c9e6c70fc61d44191931ea2aa08dc90, nTime=1429442154, nBits=1e0fffff, nNonce=164482, vtx=1, vchBlockSig=)\n \/\/ Coinbase(hash=12630d16a9, nTime=1431857735, ver=1, vin.size=1, vout.size=1, nLockTime=0)\n \/\/ CTxIn(COutPoint(0000000000, 4294967295), coinbase 00012a24323020466562203230313420426974636f696e2041544d7320636f6d6520746f20555341)\n \/\/ CTxOut(empty)\n \/\/ vMerkleTree: 12630d16a9\n const char* pszTimestamp = \"2015 xRadon coin.!\";\n std::vector<CTxIn> vin;\n vin.resize(1);\n vin[0].scriptSig = CScript() << 0 << CBigNum(42) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp));\n std::vector<CTxOut> vout;\n vout.resize(1);\n vout[0].SetEmpty();\n\t\tCTransaction txNew(1, 1431857735, vin, vout, 0);\n genesis.vtx.push_back(txNew);\n genesis.hashPrevBlock = 0;\n genesis.hashMerkleRoot = genesis.BuildMerkleTree();\n genesis.nVersion = 1;\n genesis.nTime = 1431857735;\n genesis.nBits = bnProofOfWorkLimit.GetCompact();\n genesis.nNonce = 109996;\n\n hashGenesisBlock = genesis.GetHash();\n assert(hashGenesisBlock == uint256(\"0x000000770c6aea829bb1ace7b06497f71799a6358e0e292740c4f9443a17bfb6\"));\n assert(genesis.hashMerkleRoot == uint256(\"0xa02b3388d9e8529bb0136ed3e1b823e808cbe128050e5986bf2a5a0d2c71a826\"));\n\n vSeeds.push_back(CDNSSeedData(\"us.radiumcore.org\", \"us.radiumcore.org\"));\n vSeeds.push_back(CDNSSeedData(\"eu.radiumcore.org\", \"eu.radiumcore.org\"));\n vSeeds.push_back(CDNSSeedData(\"useast.projectradium.org\", \"useast.projectradium.org\"));\n vSeeds.push_back(CDNSSeedData(\"asia.projectradium.org\", \"asia.projectradium.org\"));\n vSeeds.push_back(CDNSSeedData(\"eu.projectradium.org\", \"eu.projectradium.org\"));\n\n\n base58Prefixes[PUBKEY_ADDRESS] = std::vector<unsigned char>(1,76);\n base58Prefixes[SCRIPT_ADDRESS] = std::vector<unsigned char>(1,58);\n base58Prefixes[SECRET_KEY] = std::vector<unsigned char>(1,121);\n base58Prefixes[EXT_PUBLIC_KEY] = boost::assign::list_of(0x04)(0x73)(0xAA)(0xA1).convert_to_container<std::vector<unsigned char> >();\n base58Prefixes[EXT_SECRET_KEY] = boost::assign::list_of(0x04)(0x73)(0x44)(0x77).convert_to_container<std::vector<unsigned char> >();\n\n convertSeed6(vFixedSeeds, pnSeed6_main, ARRAYLEN(pnSeed6_main));\n\n nLastPOWBlock = 20160;\n }\n\n virtual const CBlock& GenesisBlock() const { return genesis; }\n virtual Network NetworkID() const { return CChainParams::MAIN; }\n\n virtual const vector<CAddress>& FixedSeeds() const {\n return vFixedSeeds;\n }\nprotected:\n CBlock genesis;\n vector<CAddress> vFixedSeeds;\n};\nstatic CMainParams mainParams;\n\n\n\/\/\n\/\/ Testnet\n\/\/\n\nclass CTestNetParams : public CMainParams {\npublic:\n CTestNetParams() {\n \/\/ The message start string is designed to be unlikely to occur in normal data.\n \/\/ The characters are rarely used upper ASCII, not valid as UTF-8, and produce\n \/\/ a large 4-byte int at any alignment.\n pchMessageStart[0] = 0xc3;\n pchMessageStart[1] = 0x77;\n pchMessageStart[2] = 0xcc;\n pchMessageStart[3] = 0x77;\n bnProofOfWorkLimit = CBigNum(~uint256(0) >> 16);\n vAlertPubKey = ParseHex(\"04593b5288f912a74491e7f36d7a1dd210a8e21b6e1933e9a98c7edb68da67cb5b248e1cd01a5c255c939ad53f441875a33c92135724863753fe5068f339cc189a\");\n nDefaultPort = 47963;\n nRPCPort = 47993;\n strDataDir = \"testnet\";\n\n \/\/ Modify the testnet genesis block so the timestamp is valid for a later start.\n genesis.nBits = bnProofOfWorkLimit.GetCompact();\n genesis.nNonce = 65880;\n hashGenesisBlock = genesis.GetHash();\n assert(hashGenesisBlock == uint256(\"0x0000dedd0118550f474631b30cfc8b9d260706d59ea89118d81d1a292a5681d9\"));\n\n vFixedSeeds.clear();\n vSeeds.clear();\n\n base58Prefixes[PUBKEY_ADDRESS] = std::vector<unsigned char>(1,110);\n base58Prefixes[SCRIPT_ADDRESS] = std::vector<unsigned char>(1,129);\n base58Prefixes[SECRET_KEY] = std::vector<unsigned char>(1,239);\n base58Prefixes[EXT_PUBLIC_KEY] = boost::assign::list_of(0x04)(0x35)(0x17)(0xFF).convert_to_container<std::vector<unsigned char> >();\n base58Prefixes[EXT_SECRET_KEY] = boost::assign::list_of(0x04)(0x35)(0x43)(0x99).convert_to_container<std::vector<unsigned char> >();\n\n convertSeed6(vFixedSeeds, pnSeed6_test, ARRAYLEN(pnSeed6_test));\n\n nLastPOWBlock = 0x7fffffff;\n }\n virtual Network NetworkID() const { return CChainParams::TESTNET; }\n};\nstatic CTestNetParams testNetParams;\n\n\n\/\/\n\/\/ Regression test\n\/\/\nclass CRegTestParams : public CTestNetParams {\npublic:\n CRegTestParams() {\n pchMessageStart[0] = 0xa1;\n pchMessageStart[1] = 0x4b;\n pchMessageStart[2] = 0x52;\n pchMessageStart[3] = 0xd7;\n bnProofOfWorkLimit = CBigNum(~uint256(0) >> 1);\n genesis.nTime = 1412222222;\n genesis.nBits = bnProofOfWorkLimit.GetCompact();\n genesis.nNonce = 0;\n hashGenesisBlock = genesis.GetHash();\n nDefaultPort = 57992;\n strDataDir = \"regtest\";\n assert(hashGenesisBlock == uint256(\"0x0a38e67a2863693c343acf471518744dc9c72e4f130916e5d27451685ed5e280\"));\n\n vSeeds.clear(); \/\/ Regtest mode doesn't have any DNS seeds.\n }\n\n virtual bool RequireRPCPassword() const { return false; }\n virtual Network NetworkID() const { return CChainParams::REGTEST; }\n};\nstatic CRegTestParams regTestParams;\n\nstatic CChainParams *pCurrentParams = &mainParams;\n\nconst CChainParams &Params() {\n return *pCurrentParams;\n}\n\nvoid SelectParams(CChainParams::Network network) {\n switch (network) {\n case CChainParams::MAIN:\n pCurrentParams = &mainParams;\n break;\n case CChainParams::TESTNET:\n pCurrentParams = &testNetParams;\n break;\n case CChainParams::REGTEST:\n pCurrentParams = ®TestParams;\n break;\n default:\n assert(false && \"Unimplemented network\");\n return;\n }\n}\n\nbool SelectParamsFromCommandLine() {\n bool fRegTest = GetBoolArg(\"-regtest\", false);\n bool fTestNet = GetBoolArg(\"-testnet\", false);\n\n if (fTestNet && fRegTest) {\n return false;\n }\n\n if (fRegTest) {\n SelectParams(CChainParams::REGTEST);\n } else if (fTestNet) {\n SelectParams(CChainParams::TESTNET);\n } else {\n SelectParams(CChainParams::MAIN);\n }\n return true;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2010 Satoshi Nakamoto\n\/\/ Copyright (c) 2009-2014 The Bitcoin Core developers\n\/\/ Copyright (c) 2015 The Hivemind Core developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \"chainparams.h\"\n#include \"random.h\"\n#include \"util.h\"\n#include \"utilstrencodings.h\"\n#include <assert.h>\n#include <boost\/assign\/list_of.hpp>\n\nusing namespace std;\n\nstruct SeedSpec6 {\n uint8_t addr[16];\n uint16_t port;\n};\n\n#include \"chainparamsseeds.h\"\n\n\/**\n * Main network\n *\/\n\n\/\/! Convert the pnSeeds6 array into usable address objects.\nstatic void convertSeed6(std::vector<CAddress> &vSeedsOut, const SeedSpec6 *data, unsigned int count)\n{\n \/\/ It'll only connect to one or two seed nodes because once it connects,\n \/\/ it'll get a pile of addresses with newer timestamps.\n \/\/ Seed nodes are given a random 'last seen time' of between one and two\n \/\/ weeks ago.\n const int64_t nOneWeek = 7*24*60*60;\n for (unsigned int i = 0; i < count; i++)\n {\n struct in6_addr ip;\n memcpy(&ip, data[i].addr, sizeof(ip));\n CAddress addr(CService(ip, data[i].port));\n addr.nTime = GetTime() - GetRand(nOneWeek) - nOneWeek;\n vSeedsOut.push_back(addr);\n }\n}\n\n\/**\n * What makes a good checkpoint block?\n * + Is surrounded by blocks with reasonable timestamps\n * (no blocks before with a timestamp after, none after with\n * timestamp before)\n * + Contains no strange transactions\n *\/\nstatic Checkpoints::MapCheckpoints mapCheckpoints;\nstatic const Checkpoints::CCheckpointData data = {\n &mapCheckpoints,\n 1397080064, \/\/ * UNIX timestamp of last checkpoint block\n 36544669, \/\/ * total number of transactions between genesis and last checkpoint\n \/\/ (the tx=... number in the SetBestChain debug.log lines)\n 60000.0 \/\/ * estimated number of transactions per day after checkpoint\n };\nstatic Checkpoints::MapCheckpoints mapCheckpointsTestnet;\nstatic const Checkpoints::CCheckpointData dataTestnet = {\n &mapCheckpointsTestnet,\n 0,\n 0,\n 0\n };\nstatic Checkpoints::MapCheckpoints mapCheckpointsRegtest;\nstatic const Checkpoints::CCheckpointData dataRegtest = {\n &mapCheckpointsRegtest,\n 0,\n 0,\n 0\n };\n\nclass CMainParams : public CChainParams {\npublic:\n CMainParams() {\n strNetworkID = \"main\";\n \/**\n * The message start string is designed to be unlikely to occur in normal data.\n * The characters are rarely used upper ASCII, not valid as UTF-8, and produce\n * a large 4-byte int at any alignment.\n *\/\n pchMessageStart[0] = 0xf9;\n pchMessageStart[1] = 0xbe;\n pchMessageStart[2] = 0xb4;\n pchMessageStart[3] = 0xd9;\n vAlertPubKey = ParseHex(\"04fc9702847840aaf195de8442ebecedf5b095cdbb9bc716bda9110971b28a49e0ead8564ff0db22209e0374782c093bb899692d524e9d6a6956e7c5ecbcd68284\");\n nDefaultPort = 59533;\n bnProofOfWorkLimit = ~arith_uint256(0) >> 32;\n nSubsidyHalvingInterval = 210000;\n nEnforceBlockUpgradeMajority = 750;\n nRejectBlockOutdatedMajority = 950;\n nToCheckBlockUpgradeMajority = 1000;\n nMinerThreads = 0;\n nTargetTimespan = 14 * 24 * 60 * 60; \/\/ two weeks\n nTargetSpacing = 10 * 60; \/\/ 10 Minutes\n\n \/**\n * Build the genesis block. Note that the output of the genesis coinbase cannot\n * be spent as it did not originally exist in the database.\n *\/\n CMutableTransaction txNew;\n txNew.vin.resize(1);\n txNew.vout.resize(2);\n\n \/* vin[0]: *\/\n txNew.vin[0].scriptSig = CScript() << ParseHex(\"ffff001d\") << ParseHex(\"84\");\n\n \/* vout[0]: first branch *\/\n genesisBranch.marketop = 'B';\n genesisBranch.nHeight = 0;\n genesisBranch.name = \"Main\";\n genesisBranch.description = \"Main Branch\";\n genesisBranch.baseListingFee = COIN \/ 100;\n genesisBranch.freeDecisions = 10;\n genesisBranch.targetDecisions = 20;\n genesisBranch.maxDecisions = 30;\n genesisBranch.minTradingFee = COIN \/ 100;\n genesisBranch.alpha = COIN \/ 10;\n genesisBranch.tol = COIN \/ 5;\n genesisBranch.tau = 7*40;\n genesisBranch.ballotTime = 2*40;\n genesisBranch.unsealTime = 2*40;\n genesisBranch.consensusThreshold = COIN \/ 100;\n\n txNew.vout[0].nValue = 0;\n txNew.vout[0].scriptPubKey = genesisBranch.GetScript();\n\n \/* Genesis branch votecoins *\/\n txNew.vout[1].nValue = 100000000;\n txNew.vout[1].scriptPubKey = CScript() << ParseHex(\"04E7ED3A17EB571C8159DC97F16158F464CABA5FE2878DFBF584AC8A65DA72D4B7B03381E809A59001AD2F13B2A50095434AD009FE2E812A66BE46B873AD39159A\") << OP_CHECKSIG;\n\n genesis.vtx.push_back(txNew);\n genesis.hashPrevBlock.SetNull();\n genesis.hashMerkleRoot = genesis.BuildMerkleTree();\n genesis.nVersion = 0x00000001;\n genesis.nTime = 1461108410;\n genesis.nBits = 0x1d00ffff;\n genesis.nNonce = 0x0145160c;\n\n genesisBranch.txid = txNew.GetHash();\n hashGenesisBlock = genesis.GetHash();\n\n vSeeds.push_back(CDNSSeedData(\"162.243.37.30\", \"162.243.37.30\"));\n\n assert(genesis.hashMerkleRoot == uint256S(\"0xf58856467b9b49880c8697792348bf0a0f04060047fb8b76eaa689a5ec888074\"));\n assert(hashGenesisBlock == uint256S(\"0xd1103326dea04900c6b31e7da2881181a4c3dd0b140c7604ec944f071aace03e\"));\n\n base58Prefixes[PUBKEY_ADDRESS] = boost::assign::list_of(0);\n base58Prefixes[VPUBKEY_ADDRESS] = boost::assign::list_of(71);\n base58Prefixes[SCRIPT_ADDRESS] = boost::assign::list_of(5);\n base58Prefixes[SECRET_KEY] = boost::assign::list_of(128);\n base58Prefixes[EXT_PUBLIC_KEY] = boost::assign::list_of(0x04)(0x88)(0xB2)(0x1E);\n base58Prefixes[EXT_SECRET_KEY] = boost::assign::list_of(0x04)(0x88)(0xAD)(0xE4);\n\n convertSeed6(vFixedSeeds, pnSeed6_main, ARRAYLEN(pnSeed6_main));\n\n fRequireRPCPassword = true;\n fMiningRequiresPeers = false;\n fDefaultCheckMemPool = false;\n fAllowMinDifficultyBlocks = false;\n fRequireStandard = true;\n fMineBlocksOnDemand = false;\n fSkipProofOfWorkCheck = false;\n\/* TODO: take out *\/\nfSkipProofOfWorkCheck = true;\n fTestnetToBeDeprecatedFieldRPC = false;\n }\n\n const Checkpoints::CCheckpointData& Checkpoints() const\n {\n return data;\n }\n};\nstatic CMainParams mainParams;\n\n\/**\n * Hivemind Testnet\n *\/\nclass CTestNetParams : public CMainParams {\npublic:\n CTestNetParams() {\n strNetworkID = \"test\";\n\n pchMessageStart[0] = 0x0b;\n pchMessageStart[1] = 0x11;\n pchMessageStart[2] = 0x09;\n pchMessageStart[3] = 0x07;\n vAlertPubKey = ParseHex(\"04302390343f91cc401d56d68b123028bf52e5fca1939df127f63c6467cdf9c8e2c14b61104cf817d0b780da337893ecc4aaff1309e536162dabbdb45200ca2b0a\");\n nDefaultPort = 64533;\n nTargetTimespan = 10 * 60; \/\/ 10 minutes\n nTargetSpacing = 1 * 60; \/\/ 1 minute\n\n bnProofOfWorkLimit = ~arith_uint256(0) >> 10;\n\n \/\/! Modify the testnet genesis block so the timestamp is valid for a later start.\n genesis.nTime = 1461109020;\n genesis.nNonce = 3;\n hashGenesisBlock = genesis.GetHash();\n\n assert(hashGenesisBlock == uint256S(\"0xb5614154f0ed19d582c4d8eaf5a3b639811447d94f8baf70d235890ff029edc1\"));\n\n convertSeed6(vFixedSeeds, pnSeed6_test, ARRAYLEN(pnSeed6_test));\n\n fAllowMinDifficultyBlocks = true;\n fRequireStandard = false;\n fMineBlocksOnDemand = false;\n fTestnetToBeDeprecatedFieldRPC = true;\n }\n const Checkpoints::CCheckpointData& Checkpoints() const\n {\n return dataTestnet;\n }\n};\nstatic CTestNetParams testNetParams;\n\n\/**\n * Regression test\n *\/\nclass CRegTestParams : public CTestNetParams {\npublic:\n CRegTestParams() {\n strNetworkID = \"regtest\";\n pchMessageStart[0] = 0xfa;\n pchMessageStart[1] = 0xbf;\n pchMessageStart[2] = 0xb5;\n pchMessageStart[3] = 0xda;\n nSubsidyHalvingInterval = 150;\n nEnforceBlockUpgradeMajority = 750;\n nRejectBlockOutdatedMajority = 950;\n nToCheckBlockUpgradeMajority = 1000;\n nMinerThreads = 1;\n nTargetTimespan = 14 * 24 * 60 * 60; \/\/! two weeks\n nTargetSpacing = 10 * 60;\n bnProofOfWorkLimit = ~arith_uint256(0) >> 1;\n genesis.nTime = 1461108410;\n genesis.nBits = 0x207fffff;\n genesis.nNonce = 2;\n hashGenesisBlock = genesis.GetHash();\n nDefaultPort = 18444;\n\/\/ assert(hashGenesisBlock == uint256S(\"0x0f9188f13cb7b2c71f2a335e3a4fc328bf5beb436012afca590b1a11466e2206\"));\n\n vFixedSeeds.clear(); \/\/! Regtest mode doesn't have any fixed seeds.\n vSeeds.clear(); \/\/! Regtest mode doesn't have any DNS seeds.\n\n fRequireRPCPassword = false;\n fMiningRequiresPeers = false;\n fDefaultCheckMemPool = true;\n fAllowMinDifficultyBlocks = true;\n fRequireStandard = false;\n fMineBlocksOnDemand = true;\n fTestnetToBeDeprecatedFieldRPC = false;\n }\n const Checkpoints::CCheckpointData& Checkpoints() const\n {\n return dataRegtest;\n }\n};\nstatic CRegTestParams regTestParams;\n\n\/**\n * Unit test\n *\/\nclass CUnitTestParams : public CMainParams, public CModifiableParams {\npublic:\n CUnitTestParams() {\n strNetworkID = \"unittest\";\n nDefaultPort = 18445;\n vFixedSeeds.clear(); \/\/! Unit test mode doesn't have any fixed seeds.\n vSeeds.clear(); \/\/! Unit test mode doesn't have any DNS seeds.\n\n fRequireRPCPassword = false;\n fMiningRequiresPeers = false;\n fDefaultCheckMemPool = true;\n fAllowMinDifficultyBlocks = false;\n fMineBlocksOnDemand = true;\n }\n\n const Checkpoints::CCheckpointData& Checkpoints() const\n {\n \/\/ UnitTest share the same checkpoints as MAIN\n return data;\n }\n\n \/\/! Published setters to allow changing values in unit test cases\n virtual void setSubsidyHalvingInterval(int anSubsidyHalvingInterval) { nSubsidyHalvingInterval=anSubsidyHalvingInterval; }\n virtual void setEnforceBlockUpgradeMajority(int anEnforceBlockUpgradeMajority) { nEnforceBlockUpgradeMajority=anEnforceBlockUpgradeMajority; }\n virtual void setRejectBlockOutdatedMajority(int anRejectBlockOutdatedMajority) { nRejectBlockOutdatedMajority=anRejectBlockOutdatedMajority; }\n virtual void setToCheckBlockUpgradeMajority(int anToCheckBlockUpgradeMajority) { nToCheckBlockUpgradeMajority=anToCheckBlockUpgradeMajority; }\n virtual void setDefaultCheckMemPool(bool afDefaultCheckMemPool) { fDefaultCheckMemPool=afDefaultCheckMemPool; }\n virtual void setAllowMinDifficultyBlocks(bool afAllowMinDifficultyBlocks) { fAllowMinDifficultyBlocks=afAllowMinDifficultyBlocks; }\n virtual void setSkipProofOfWorkCheck(bool afSkipProofOfWorkCheck) { fSkipProofOfWorkCheck = afSkipProofOfWorkCheck; }\n};\nstatic CUnitTestParams unitTestParams;\n\n\nstatic CChainParams *pCurrentParams = 0;\n\nCModifiableParams *ModifiableParams()\n{\n assert(pCurrentParams);\n assert(pCurrentParams==&unitTestParams);\n return (CModifiableParams*)&unitTestParams;\n}\n\nconst CChainParams &Params() {\n assert(pCurrentParams);\n return *pCurrentParams;\n}\n\nCChainParams &Params(CBaseChainParams::Network network) {\n switch (network) {\n case CBaseChainParams::MAIN:\n return mainParams;\n case CBaseChainParams::TESTNET:\n return testNetParams;\n case CBaseChainParams::REGTEST:\n return regTestParams;\n case CBaseChainParams::UNITTEST:\n return unitTestParams;\n default:\n assert(false && \"Unimplemented network\");\n return mainParams;\n }\n}\n\nvoid SelectParams(CBaseChainParams::Network network) {\n SelectBaseParams(network);\n pCurrentParams = &Params(network);\n}\n\nbool SelectParamsFromCommandLine()\n{\n CBaseChainParams::Network network = NetworkIdFromCommandLine();\n if (network == CBaseChainParams::MAX_NETWORK_TYPES)\n return false;\n\n SelectParams(network);\n return true;\n}\n<commit_msg>New genesis blocks and votecoin payout scripts<commit_after>\/\/ Copyright (c) 2010 Satoshi Nakamoto\n\/\/ Copyright (c) 2009-2014 The Bitcoin Core developers\n\/\/ Copyright (c) 2015 The Hivemind Core developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \"chainparams.h\"\n#include \"random.h\"\n#include \"util.h\"\n#include \"utilstrencodings.h\"\n#include <assert.h>\n#include <boost\/assign\/list_of.hpp>\n\nusing namespace std;\n\nstruct SeedSpec6 {\n uint8_t addr[16];\n uint16_t port;\n};\n\n#include \"chainparamsseeds.h\"\n\n\/**\n * Main network\n *\/\n\n\/\/! Convert the pnSeeds6 array into usable address objects.\nstatic void convertSeed6(std::vector<CAddress> &vSeedsOut, const SeedSpec6 *data, unsigned int count)\n{\n \/\/ It'll only connect to one or two seed nodes because once it connects,\n \/\/ it'll get a pile of addresses with newer timestamps.\n \/\/ Seed nodes are given a random 'last seen time' of between one and two\n \/\/ weeks ago.\n const int64_t nOneWeek = 7*24*60*60;\n for (unsigned int i = 0; i < count; i++)\n {\n struct in6_addr ip;\n memcpy(&ip, data[i].addr, sizeof(ip));\n CAddress addr(CService(ip, data[i].port));\n addr.nTime = GetTime() - GetRand(nOneWeek) - nOneWeek;\n vSeedsOut.push_back(addr);\n }\n}\n\n\/**\n * What makes a good checkpoint block?\n * + Is surrounded by blocks with reasonable timestamps\n * (no blocks before with a timestamp after, none after with\n * timestamp before)\n * + Contains no strange transactions\n *\/\nstatic Checkpoints::MapCheckpoints mapCheckpoints;\nstatic const Checkpoints::CCheckpointData data = {\n &mapCheckpoints,\n 0, \/\/ * UNIX timestamp of last checkpoint block\n 0, \/\/ * total number of transactions between genesis and last checkpoint\n \/\/ (the tx=... number in the SetBestChain debug.log lines)\n 0 \/\/ * estimated number of transactions per day after checkpoint\n };\nstatic Checkpoints::MapCheckpoints mapCheckpointsTestnet;\nstatic const Checkpoints::CCheckpointData dataTestnet = {\n &mapCheckpointsTestnet,\n 0,\n 0,\n 0\n };\nstatic Checkpoints::MapCheckpoints mapCheckpointsRegtest;\nstatic const Checkpoints::CCheckpointData dataRegtest = {\n &mapCheckpointsRegtest,\n 0,\n 0,\n 0\n };\n\nclass CMainParams : public CChainParams {\npublic:\n CMainParams() {\n strNetworkID = \"main\";\n \/**\n * The message start string is designed to be unlikely to occur in normal data.\n * The characters are rarely used upper ASCII, not valid as UTF-8, and produce\n * a large 4-byte int at any alignment.\n *\/\n pchMessageStart[0] = 0xf9;\n pchMessageStart[1] = 0xbe;\n pchMessageStart[2] = 0xb4;\n pchMessageStart[3] = 0xd9;\n vAlertPubKey = ParseHex(\"04fc9702847840aaf195de8442ebecedf5b095cdbb9bc716bda9110971b28a49e0ead8564ff0db22209e0374782c093bb899692d524e9d6a6956e7c5ecbcd68284\");\n nDefaultPort = 59533;\n bnProofOfWorkLimit = ~arith_uint256(0) >> 32;\n nSubsidyHalvingInterval = 210000;\n nEnforceBlockUpgradeMajority = 750;\n nRejectBlockOutdatedMajority = 950;\n nToCheckBlockUpgradeMajority = 1000;\n nMinerThreads = 0;\n nTargetTimespan = 14 * 24 * 60 * 60; \/\/ two weeks\n nTargetSpacing = 10 * 60; \/\/ 10 Minutes\n\n \/**\n * Build the genesis block. Note that the output of the genesis coinbase cannot\n * be spent as it did not originally exist in the database.\n *\/\n CMutableTransaction txNew;\n txNew.vin.resize(1);\n txNew.vout.resize(3);\n\n \/* vin[0]: *\/\n txNew.vin[0].scriptSig = CScript() << ParseHex(\"ffff001d\") << ParseHex(\"84\");\n\n \/* vout[0]: first branch *\/\n genesisBranch.marketop = 'B';\n genesisBranch.nHeight = 0;\n genesisBranch.name = \"Main\";\n genesisBranch.description = \"Main Branch\";\n genesisBranch.baseListingFee = COIN \/ 100;\n genesisBranch.freeDecisions = 10;\n genesisBranch.targetDecisions = 20;\n genesisBranch.maxDecisions = 30;\n genesisBranch.minTradingFee = COIN \/ 100;\n genesisBranch.alpha = COIN \/ 10;\n genesisBranch.tol = COIN \/ 5;\n genesisBranch.tau = 7*40;\n genesisBranch.ballotTime = 2*40;\n genesisBranch.unsealTime = 2*40;\n genesisBranch.consensusThreshold = COIN \/ 100;\n\n txNew.vout[0].nValue = 0;\n txNew.vout[0].scriptPubKey = genesisBranch.GetScript();\n\n \/* Genesis branch votecoins *\/\n \/\/ 1 votecoin to Va21XbkLRmjs6ajLcR2dkzdhu1Lc5SLAUF\n txNew.vout[1].nValue = 100000000;\n txNew.vout[1].scriptPubKey = CScript() << OP_DUP << OP_HASH160 << ParseHex(\"003947b2fe63ced9f1a8d685be6fe506972a6ddd\") << OP_EQUALVERIFY << OP_CHECKSIG;\n\n \/\/ 1 votecoin to VdSQB5w3f66UtrsizDJ7vAFRnv5DTBYKZP\n txNew.vout[2].nValue = 100000000;\n txNew.vout[2].scriptPubKey = CScript() << OP_DUP << OP_HASH160 << ParseHex(\"25be8b7137608126cde868ea55720ee8ebc1d5e1\") << OP_EQUALVERIFY << OP_CHECKSIG;\n\n genesis.vtx.push_back(txNew);\n genesis.hashPrevBlock.SetNull();\n genesis.hashMerkleRoot = genesis.BuildMerkleTree();\n genesis.nVersion = 0x00000001;\n genesis.nTime = 1461280589;\n genesis.nBits = 0x1d00ffff;\n genesis.nNonce = 0x0145160c;\n\n genesisBranch.txid = txNew.GetHash();\n hashGenesisBlock = genesis.GetHash();\n\n vSeeds.push_back(CDNSSeedData(\"162.243.37.30\", \"162.243.37.30\"));\n\n assert(genesis.hashMerkleRoot == uint256S(\"0x1dd1b501318ca1dc8e2f32c6833fd3d6272822782cf8dfcaea232b623ca70a39\"));\n assert(hashGenesisBlock == uint256S(\"0x8331ba684254a659fa2454e0c8e262cc68c011f229bfffae318e3b0e2cc33ffe\"));\n\n base58Prefixes[PUBKEY_ADDRESS] = boost::assign::list_of(0);\n base58Prefixes[VPUBKEY_ADDRESS] = boost::assign::list_of(71);\n base58Prefixes[SCRIPT_ADDRESS] = boost::assign::list_of(5);\n base58Prefixes[SECRET_KEY] = boost::assign::list_of(128);\n base58Prefixes[EXT_PUBLIC_KEY] = boost::assign::list_of(0x04)(0x88)(0xB2)(0x1E);\n base58Prefixes[EXT_SECRET_KEY] = boost::assign::list_of(0x04)(0x88)(0xAD)(0xE4);\n\n convertSeed6(vFixedSeeds, pnSeed6_main, ARRAYLEN(pnSeed6_main));\n\n fRequireRPCPassword = true;\n fMiningRequiresPeers = false;\n fDefaultCheckMemPool = false;\n fAllowMinDifficultyBlocks = false;\n fRequireStandard = true;\n fMineBlocksOnDemand = false;\n fSkipProofOfWorkCheck = false;\n\/* TODO: take out *\/\nfSkipProofOfWorkCheck = true;\n fTestnetToBeDeprecatedFieldRPC = false;\n }\n\n const Checkpoints::CCheckpointData& Checkpoints() const\n {\n return data;\n }\n};\nstatic CMainParams mainParams;\n\n\/**\n * Hivemind Testnet\n *\/\nclass CTestNetParams : public CMainParams {\npublic:\n CTestNetParams() {\n strNetworkID = \"test\";\n\n pchMessageStart[0] = 0x0b;\n pchMessageStart[1] = 0x11;\n pchMessageStart[2] = 0x09;\n pchMessageStart[3] = 0x07;\n vAlertPubKey = ParseHex(\"04302390343f91cc401d56d68b123028bf52e5fca1939df127f63c6467cdf9c8e2c14b61104cf817d0b780da337893ecc4aaff1309e536162dabbdb45200ca2b0a\");\n nDefaultPort = 64533;\n nTargetTimespan = 10 * 60; \/\/ 10 minutes\n nTargetSpacing = 1 * 60; \/\/ 1 minute\n\n bnProofOfWorkLimit = ~arith_uint256(0) >> 10;\n\n \/\/! Modify the testnet genesis block so the timestamp is valid for a later start.\n genesis.nTime = 1461281589;\n genesis.nNonce = 3;\n hashGenesisBlock = genesis.GetHash();\n\n assert(hashGenesisBlock == uint256S(\"0x804e2603231613625239a9c16a87c24ca09946a8890efba502878b57681baf7f\"));\n\n convertSeed6(vFixedSeeds, pnSeed6_test, ARRAYLEN(pnSeed6_test));\n\n fAllowMinDifficultyBlocks = true;\n fRequireStandard = false;\n fMineBlocksOnDemand = false;\n fTestnetToBeDeprecatedFieldRPC = true;\n }\n const Checkpoints::CCheckpointData& Checkpoints() const\n {\n return dataTestnet;\n }\n};\nstatic CTestNetParams testNetParams;\n\n\/**\n * Regression test\n *\/\nclass CRegTestParams : public CTestNetParams {\npublic:\n CRegTestParams() {\n strNetworkID = \"regtest\";\n pchMessageStart[0] = 0xfa;\n pchMessageStart[1] = 0xbf;\n pchMessageStart[2] = 0xb5;\n pchMessageStart[3] = 0xda;\n nSubsidyHalvingInterval = 150;\n nEnforceBlockUpgradeMajority = 750;\n nRejectBlockOutdatedMajority = 950;\n nToCheckBlockUpgradeMajority = 1000;\n nMinerThreads = 1;\n nTargetTimespan = 14 * 24 * 60 * 60; \/\/! two weeks\n nTargetSpacing = 10 * 60;\n bnProofOfWorkLimit = ~arith_uint256(0) >> 1;\n genesis.nTime = 1461108410;\n genesis.nBits = 0x207fffff;\n genesis.nNonce = 2;\n hashGenesisBlock = genesis.GetHash();\n nDefaultPort = 18444;\n\/\/ assert(hashGenesisBlock == uint256S(\"0x0f9188f13cb7b2c71f2a335e3a4fc328bf5beb436012afca590b1a11466e2206\"));\n\n vFixedSeeds.clear(); \/\/! Regtest mode doesn't have any fixed seeds.\n vSeeds.clear(); \/\/! Regtest mode doesn't have any DNS seeds.\n\n fRequireRPCPassword = false;\n fMiningRequiresPeers = false;\n fDefaultCheckMemPool = true;\n fAllowMinDifficultyBlocks = true;\n fRequireStandard = false;\n fMineBlocksOnDemand = true;\n fTestnetToBeDeprecatedFieldRPC = false;\n }\n const Checkpoints::CCheckpointData& Checkpoints() const\n {\n return dataRegtest;\n }\n};\nstatic CRegTestParams regTestParams;\n\n\/**\n * Unit test\n *\/\nclass CUnitTestParams : public CMainParams, public CModifiableParams {\npublic:\n CUnitTestParams() {\n strNetworkID = \"unittest\";\n nDefaultPort = 18445;\n vFixedSeeds.clear(); \/\/! Unit test mode doesn't have any fixed seeds.\n vSeeds.clear(); \/\/! Unit test mode doesn't have any DNS seeds.\n\n fRequireRPCPassword = false;\n fMiningRequiresPeers = false;\n fDefaultCheckMemPool = true;\n fAllowMinDifficultyBlocks = false;\n fMineBlocksOnDemand = true;\n }\n\n const Checkpoints::CCheckpointData& Checkpoints() const\n {\n \/\/ UnitTest share the same checkpoints as MAIN\n return data;\n }\n\n \/\/! Published setters to allow changing values in unit test cases\n virtual void setSubsidyHalvingInterval(int anSubsidyHalvingInterval) { nSubsidyHalvingInterval=anSubsidyHalvingInterval; }\n virtual void setEnforceBlockUpgradeMajority(int anEnforceBlockUpgradeMajority) { nEnforceBlockUpgradeMajority=anEnforceBlockUpgradeMajority; }\n virtual void setRejectBlockOutdatedMajority(int anRejectBlockOutdatedMajority) { nRejectBlockOutdatedMajority=anRejectBlockOutdatedMajority; }\n virtual void setToCheckBlockUpgradeMajority(int anToCheckBlockUpgradeMajority) { nToCheckBlockUpgradeMajority=anToCheckBlockUpgradeMajority; }\n virtual void setDefaultCheckMemPool(bool afDefaultCheckMemPool) { fDefaultCheckMemPool=afDefaultCheckMemPool; }\n virtual void setAllowMinDifficultyBlocks(bool afAllowMinDifficultyBlocks) { fAllowMinDifficultyBlocks=afAllowMinDifficultyBlocks; }\n virtual void setSkipProofOfWorkCheck(bool afSkipProofOfWorkCheck) { fSkipProofOfWorkCheck = afSkipProofOfWorkCheck; }\n};\nstatic CUnitTestParams unitTestParams;\n\n\nstatic CChainParams *pCurrentParams = 0;\n\nCModifiableParams *ModifiableParams()\n{\n assert(pCurrentParams);\n assert(pCurrentParams==&unitTestParams);\n return (CModifiableParams*)&unitTestParams;\n}\n\nconst CChainParams &Params() {\n assert(pCurrentParams);\n return *pCurrentParams;\n}\n\nCChainParams &Params(CBaseChainParams::Network network) {\n switch (network) {\n case CBaseChainParams::MAIN:\n return mainParams;\n case CBaseChainParams::TESTNET:\n return testNetParams;\n case CBaseChainParams::REGTEST:\n return regTestParams;\n case CBaseChainParams::UNITTEST:\n return unitTestParams;\n default:\n assert(false && \"Unimplemented network\");\n return mainParams;\n }\n}\n\nvoid SelectParams(CBaseChainParams::Network network) {\n SelectBaseParams(network);\n pCurrentParams = &Params(network);\n}\n\nbool SelectParamsFromCommandLine()\n{\n CBaseChainParams::Network network = NetworkIdFromCommandLine();\n if (network == CBaseChainParams::MAX_NETWORK_TYPES)\n return false;\n\n SelectParams(network);\n return true;\n}\n<|endoftext|>"} {"text":"<commit_before>#include <execinfo.h>\n#include <string.h>\n\n#include \"debugging.h\"\n\nnamespace base {\n\nvoid __attribute__((noinline)) print_stack_trace(FILE* fp \/* =? *\/) {\n void* callstack[1024];\n memset(callstack, 0, sizeof(callstack));\n int frames = backtrace(callstack, 1024);\n\n fprintf(fp, \" *** begin stack trace ***\\n\");\n \/\/ note that we ignore the first frame: print_stack_trace should not be displayed\n backtrace_symbols_fd(callstack + 1, frames - 1, fileno(fp));\n fprintf(fp, \" *** end stack trace ***\\n\");\n}\n\n} \/\/ namespace base\n<commit_msg>demangle the C++ function names in print_stack_trace()<commit_after>#include <execinfo.h>\n#include <string.h>\n\n#include <string>\n\n#include \"debugging.h\"\n#include \"strop.h\"\n\nusing namespace std;\n\nnamespace base {\n\n#ifdef __APPLE__\n\nvoid __attribute__((noinline)) print_stack_trace(FILE* fp \/* =? *\/) {\n const int max_trace = 1024;\n void* callstack[max_trace];\n memset(callstack, 0, sizeof(callstack));\n int frames = backtrace(callstack, max_trace);\n\n \/\/ note that we ignore the first frame: print_stack_trace should not be displayed\n char **str_frames = backtrace_symbols(callstack + 1, frames - 1);\n if (str_frames == nullptr) {\n fprintf(fp, \" *** failed to obtain stack trace!\\n\");\n return;\n }\n\n fprintf(fp, \" *** begin stack trace ***\\n\");\n \/\/ demangle C++ function names with c++filt\n auto demangle = popen(\"c++filt -n\", \"r+\");\n size_t demangled_size = 1024;\n char* demangled = nullptr;\n if (demangle) {\n fprintf(fp, \" *** demangled C++ code using c++filt ***\\n\");\n demangled = (char *) malloc(demangled_size);\n }\n for (int i = 0; i < frames - 1; i++) {\n if (demangle) {\n string trace = str_frames[i];\n size_t idx = trace.rfind(' ');\n size_t idx2 = trace.rfind(' ', idx - 1);\n idx = trace.rfind(' ', idx2 - 1) + 1;\n string mangled = trace.substr(idx, idx2 - idx);\n string left = trace.substr(0, idx);\n string right = trace.substr(idx2);\n if (mangled.size() + 1 > demangled_size) {\n demangled_size = mangled.size() + 1;\n demangled = (char *) realloc(demangled, demangled_size);\n }\n fprintf(demangle, \"%s\\n\", mangled.c_str());\n\n ssize_t n_read = ::getline(&demangled, &demangled_size, demangle);\n demangled[n_read - 1] = '\\0';\n\n fprintf(fp, \"%s%s%s\\n\", left.c_str(), demangled, right.c_str());\n } else {\n fprintf(fp, \"%s\\n\", str_frames[i]);\n }\n }\n if (demangle) {\n free(demangled);\n pclose(demangle);\n }\n fprintf(fp, \" *** end stack trace ***\\n\");\n\n free(str_frames);\n}\n\n#else \/\/ no __APPLE__\n\nvoid __attribute__((noinline)) print_stack_trace(FILE* fp \/* =? *\/) {\n const int max_trace = 1024;\n void* callstack[max_trace];\n memset(callstack, 0, sizeof(callstack));\n int frames = backtrace(callstack, max_trace);\n\n fprintf(fp, \" *** begin stack trace ***\\n\");\n \/\/ note that we ignore the first frame: print_stack_trace should not be displayed\n backtrace_symbols_fd(callstack + 1, frames - 1, fileno(fp));\n fprintf(fp, \" *** end stack trace ***\\n\");\n}\n\n#endif \/\/ ifdef __APPLE__\n\n} \/\/ namespace base\n<|endoftext|>"} {"text":"<commit_before>\n#pragma once\n\n\/\/ This code comes from:\n\/\/ https:\/\/github.com\/google\/protobuf\/blob\/master\/src\/google\/protobuf\/stubs\/map_util.h\n\/\/ and was adapted to Visual Studio 2013 and to the needs of this project.\n\n\/\/ Protocol Buffers - Google's data interchange format\n\/\/ Copyright 2014 Google Inc. All rights reserved.\n\/\/ https:\/\/developers.google.com\/protocol-buffers\/\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are\n\/\/ met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright\n\/\/ notice, this list of conditions and the following disclaimer.\n\/\/ * Redistributions in binary form must reproduce the above\n\/\/ copyright notice, this list of conditions and the following disclaimer\n\/\/ in the documentation and\/or other materials provided with the\n\/\/ distribution.\n\/\/ * Neither the name of Google Inc. nor the names of its\n\/\/ contributors may be used to endorse or promote products derived from\n\/\/ this software without specific prior written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\/\/ \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n\/\/ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n\/\/ A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n\/\/ OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n\/\/ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n\/\/ LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n\/\/ DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n\/\/ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n\/\/ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n\/\/ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n\/\/ from google3\/util\/gtl\/map_util.h\n\/\/ Author: Anton Carver\n\n#include \"glog\/logging.h\"\n\nnamespace principia {\nnamespace base {\n\n\/\/ Returns true if and only if the given collection contains the given key.\ntemplate <class Collection>\nbool Contains(Collection const& collection,\n typename Collection::key_type const key) {\n return collection.count(key) > 0;\n}\n\ntemplate<class Collection>\nconst typename Collection::value_type::second_type& FindOrDie(\n Collection const& collection,\n typename Collection::value_type::first_type const& key) {\n typename Collection::const_iterator it = collection.find(key);\n CHECK(it != collection.end()) << \"Map key not found: \" << key;\n return it->second;\n}\n\n\/\/ Same as above, but returns a non-const reference.\ntemplate<class Collection>\ntypename Collection::value_type::second_type& FindOrDie(\n Collection& collection,\n typename Collection::value_type::first_type const& key) {\n typename Collection::iterator it = collection.find(key);\n CHECK(it != collection.end()) << \"Map key not found: \" << key;\n return it->second;\n}\n\n} \/\/ namespace base\n} \/\/ namespace principia\n<commit_msg>After egg's review.<commit_after>\n#pragma once\n\n\/\/ This code comes from:\n\/\/ https:\/\/github.com\/google\/protobuf\/blob\/master\/src\/google\/protobuf\/stubs\/map_util.h\n\/\/ and was adapted to Visual Studio 2013 and to the needs of this project.\n\n\/\/ Protocol Buffers - Google's data interchange format\n\/\/ Copyright 2014 Google Inc. All rights reserved.\n\/\/ https:\/\/developers.google.com\/protocol-buffers\/\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are\n\/\/ met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright\n\/\/ notice, this list of conditions and the following disclaimer.\n\/\/ * Redistributions in binary form must reproduce the above\n\/\/ copyright notice, this list of conditions and the following disclaimer\n\/\/ in the documentation and\/or other materials provided with the\n\/\/ distribution.\n\/\/ * Neither the name of Google Inc. nor the names of its\n\/\/ contributors may be used to endorse or promote products derived from\n\/\/ this software without specific prior written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\/\/ \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n\/\/ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n\/\/ A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n\/\/ OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n\/\/ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n\/\/ LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n\/\/ DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n\/\/ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n\/\/ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n\/\/ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n\/\/ from google3\/util\/gtl\/map_util.h\n\/\/ Author: Anton Carver\n\n#include \"glog\/logging.h\"\n\nnamespace principia {\nnamespace base {\n\n\/\/ Returns true if and only if the given collection contains the given key.\ntemplate <class Collection>\nbool Contains(Collection const& collection,\n typename Collection::key_type const key) {\n return collection.find(key) != collection.end();\n}\n\ntemplate<class Collection>\nconst typename Collection::value_type::second_type& FindOrDie(\n Collection const& collection,\n typename Collection::value_type::first_type const& key) {\n typename Collection::const_iterator it = collection.find(key);\n CHECK(it != collection.end()) << \"Map key not found: \" << key;\n return it->second;\n}\n\n\/\/ Same as above, but returns a non-const reference.\ntemplate<class Collection>\ntypename Collection::value_type::second_type& FindOrDie(\n Collection& collection,\n typename Collection::value_type::first_type const& key) {\n typename Collection::iterator it = collection.find(key);\n CHECK(it != collection.end()) << \"Map key not found: \" << key;\n return it->second;\n}\n\n} \/\/ namespace base\n} \/\/ namespace principia\n<|endoftext|>"} {"text":"<commit_before>#include \"dom.hpp\"\n\n#include <vector>\n\n#include <ting\/debug.hpp>\n#include <ting\/Array.hpp>\n\n#include \"parser.hpp\"\n\n\n\nusing namespace stob;\n\n\n\nnamespace{\nting::MemoryPool<sizeof(Node), 1024> memoryPool;\n}\n\n\n\nvoid* Node::operator new(size_t size){\n\tASSERT(size == sizeof(Node))\n\n\treturn memoryPool.Alloc_ts();\n}\n\n\n\nvoid Node::operator delete(void* p)throw(){\n\tmemoryPool.Free_ts(p);\n}\n\n\n\nstob::Node::NodeAndPrev Node::Next(const char* value)throw(){\n\tNode* prev = this;\n\tfor(Node* n = this->Next(); n; prev = n, n = n->Next()){\n\t\tif(n->operator==(value)){\n\t\t\treturn NodeAndPrev(prev, n);\n\t\t}\n\t}\n\treturn NodeAndPrev(prev, 0);\n}\n\n\n\nstob::Node::NodeAndPrev Node::Child(const char* value)throw(){\n\tif(this->children.IsNotValid()){\n\t\treturn NodeAndPrev(0, 0);\n\t}\n\n\tif(this->children->operator==(value)){\n\t\treturn NodeAndPrev(0, this->children.operator->());\n\t}\n\n\treturn this->children->Next(value);\n}\n\n\n\nstob::Node::NodeAndPrev Node::ChildNonProperty()throw(){\n\tif(this->children.IsNotValid()){\n\t\treturn NodeAndPrev(0, 0);\n\t}\n\n\tif(!this->children->IsProperty()){\n\t\treturn NodeAndPrev(0, this->children.operator->());\n\t}\n\n\treturn this->children->NextNonProperty();\n}\n\n\n\nstob::Node::NodeAndPrev Node::ChildProperty()throw(){\n\tif(this->children.IsNotValid()){\n\t\treturn NodeAndPrev(0, 0);\n\t}\n\n\tif(this->children->IsProperty()){\n\t\treturn NodeAndPrev(0, this->children.operator->());\n\t}\n\n\treturn this->children->NextProperty();\n}\n\n\n\nstob::Node::NodeAndPrev Node::NextNonProperty()throw(){\n\tNode* prev = this;\n\tfor(Node* n = this->Next(); n; prev = n, n = n->Next()){\n\t\tif(!n->IsProperty()){\n\t\t\treturn NodeAndPrev(prev, n);\n\t\t}\n\t}\n\treturn NodeAndPrev(prev, 0);\n}\n\n\n\nstob::Node::NodeAndPrev Node::NextProperty()throw(){\n\tNode* prev = this;\n\tfor(Node* n = this->Next(); n; prev = n, n = n->Next()){\n\t\tif(n->IsProperty()){\n\t\t\treturn NodeAndPrev(prev, n);\n\t\t}\n\t}\n\treturn NodeAndPrev(prev, 0);\n}\n\n\n\nNode* Node::AddProperty(const char* propName){\n\tting::Ptr<Node> p = Node::New();\n\tp->SetValue(propName);\n\tp->SetNext(this->RemoveChildren());\n\tthis->SetChildren(p);\n\n\tthis->Child()->SetChildren(Node::New());\n\n\treturn this->Child()->Child();\n}\n\n\n\nnamespace{\n\nbool CanStringBeUnquoted(const char* s, size_t& out_length, unsigned& out_numEscapes){\n\/\/\tTRACE(<< \"CanStringBeUnquoted(): enter\" << std::endl)\n\n\tout_numEscapes = 0;\n\tout_length = 0;\n\n\tif(s == 0){\/\/empty string is can be unquoted when it has children, so return true.\n\t\treturn true;\n\t}\n\n\tbool ret = true;\n\tfor(; *s != 0; ++s, ++out_length){\n\/\/\t\tTRACE(<< \"CanStringBeUnquoted(): c = \" << (*c) << std::endl)\n\t\tswitch(*s){\n\t\t\tcase '\\t':\n\t\t\tcase '\\n':\n\t\t\tcase '\\r':\n\t\t\tcase '\\\\':\n\t\t\tcase '\"':\n\t\t\t\t++out_numEscapes;\n\t\t\tcase '{':\n\t\t\tcase '}':\n\t\t\tcase ' ':\n\t\t\t\tret = false;\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tbreak;\n\t\t}\n\t}\n\treturn ret;\n}\n\n\nvoid MakeEscapedString(const char* str, ting::Buffer<ting::u8>& out){\n\tting::u8 *p = out.Begin();\n\tfor(const char* c = str; *c != 0; ++c){\n\t\tASSERT(p != out.End())\n\n\t\tswitch(*c){\n\t\t\tcase '\\t':\n\t\t\t\t*p = '\\\\';\n\t\t\t\t++p;\n\t\t\t\tASSERT(p != out.End())\n\t\t\t\t*p = 't';\n\t\t\t\tbreak;\n\t\t\tcase '\\n':\n\t\t\t\t*p = '\\\\';\n\t\t\t\t++p;\n\t\t\t\tASSERT(p != out.End())\n\t\t\t\t*p = 'n';\n\t\t\t\tbreak;\n\t\t\tcase '\\r':\n\t\t\t\t*p = '\\\\';\n\t\t\t\t++p;\n\t\t\t\tASSERT(p != out.End())\n\t\t\t\t*p = 'r';\n\t\t\t\tbreak;\n\t\t\tcase '\\\\':\n\t\t\t\t*p = '\\\\';\n\t\t\t\t++p;\n\t\t\t\tASSERT(p != out.End())\n\t\t\t\t*p = '\\\\';\n\t\t\t\tbreak;\n\t\t\tcase '\"':\n\t\t\t\t*p = '\\\\';\n\t\t\t\t++p;\n\t\t\t\tASSERT(p != out.End())\n\t\t\t\t*p = '\"';\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\t*p = *c;\n\t\t\t\tbreak;\n\t\t}\n\t\t++p;\n\t}\n}\n\n\nvoid WriteNode(const stob::Node* node, ting::fs::File& fi, bool formatted, unsigned indentation){\n\tASSERT(node)\n\n\tting::StaticBuffer<ting::u8, 1> quote;\n\tquote[0] = '\"';\n\n\tting::StaticBuffer<ting::u8, 1> lcurly;\n\tlcurly[0] = '{';\n\n\tting::StaticBuffer<ting::u8, 1> rcurly;\n\trcurly[0] = '}';\n\n\tting::StaticBuffer<ting::u8, 1> space;\n\tspace[0] = ' ';\n\n\tting::StaticBuffer<ting::u8, 1> tab;\n\ttab[0] = '\\t';\n\n\tting::StaticBuffer<ting::u8, 1> newLine;\n\tnewLine[0] = '\\n';\n\n\t\/\/used to detect case of two adjacent unquoted strings without children, need to insert space between them\n\tbool prevWasUnquotedWithoutChildren = false;\n\t\n\tbool prevHadChildren = true;\n\n\tfor(const Node* n = node->Child(); n; n = n->Next()){\n\t\t\/\/indent\n\t\tif(formatted){\n\t\t\tfor(unsigned i = 0; i != indentation; ++i){\n\t\t\t\tfi.Write(tab);\n\t\t\t}\n\t\t}\n\n\t\t\/\/write node value\n\n\t\tunsigned numEscapes;\n\t\tsize_t length;\n\t\tbool unqouted = CanStringBeUnquoted(n->Value(), length, numEscapes);\n\n\t\tif(!unqouted){\n\t\t\tfi.Write(quote);\n\n\t\t\tif(numEscapes == 0){\n\t\t\t\tfi.Write(ting::Buffer<ting::u8>(\n\t\t\t\t\t\tconst_cast<ting::u8*>(reinterpret_cast<const ting::u8*>(n->Value())),\n\t\t\t\t\t\tlength\n\t\t\t\t\t));\n\t\t\t}else{\n\t\t\t\tting::Array<ting::u8> buf(length + numEscapes);\n\n\t\t\t\tMakeEscapedString(n->Value(), buf);\n\n\t\t\t\tfi.Write(buf);\n\t\t\t}\n\n\t\t\tfi.Write(quote);\n\t\t}else{\n\t\t\tbool isQuotedEmptyString = false;\n\t\t\tif(n->ValueLength() == 0){\/\/if empty string\n\t\t\t\tif(!n->Child() || !prevHadChildren){\n\t\t\t\t\tisQuotedEmptyString = true;\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\t\/\/unquoted string\n\t\t\tif(!formatted && prevWasUnquotedWithoutChildren && !isQuotedEmptyString){\n\t\t\t\tfi.Write(space);\n\t\t\t}\n\n\t\t\tif(n->ValueLength() == 0){\/\/if empty string\n\t\t\t\tif(isQuotedEmptyString){\n\t\t\t\t\tfi.Write(quote);\n\t\t\t\t\tfi.Write(quote);\n\t\t\t\t}\n\t\t\t}else{\n\t\t\t\tASSERT(numEscapes == 0)\n\t\t\t\tfi.Write(ting::Buffer<ting::u8>(\n\t\t\t\t\t\tconst_cast<ting::u8*>(reinterpret_cast<const ting::u8*>(n->Value())),\n\t\t\t\t\t\tlength\n\t\t\t\t\t));\n\t\t\t}\n\t\t}\n\n\t\tprevHadChildren = (n->Child() != 0);\n\t\tif(n->Child() == 0){\n\t\t\t\n\t\t\tif(formatted){\n\t\t\t\tfi.Write(newLine);\n\t\t\t}\n\t\t\tprevWasUnquotedWithoutChildren = (unqouted && n->ValueLength() != 0);\n\t\t\tcontinue;\n\t\t}else{\n\t\t\tprevWasUnquotedWithoutChildren = false;\n\t\t}\n\n\t\tif(!formatted){\n\t\t\tfi.Write(lcurly);\n\n\t\t\tWriteNode(n, fi, false, 0);\n\n\t\t\tfi.Write(rcurly);\n\t\t}else{\n\t\t\tif(n->Child()->Next() == 0 && n->Child()->Child() == 0){\n\t\t\t\t\/\/if only one child and that child has no children\n\t\t\t\tif(n->ValueLength() != 0){\n\t\t\t\t\tfi.Write(space);\n\t\t\t\t}\n\t\t\t\tfi.Write(lcurly);\n\t\t\t\tWriteNode(n, fi, false, 0);\n\t\t\t\tfi.Write(rcurly);\n\t\t\t\tfi.Write(newLine);\n\t\t\t}else{\n\t\t\t\tfi.Write(lcurly);\n\t\t\t\tfi.Write(newLine);\n\t\t\t\tWriteNode(n, fi, true, indentation + 1);\n\n\t\t\t\t\/\/indent\n\t\t\t\tfor(unsigned i = 0; i != indentation; ++i){\n\t\t\t\t\tfi.Write(tab);\n\t\t\t\t}\n\t\t\t\tfi.Write(rcurly);\n\t\t\t\tfi.Write(newLine);\n\t\t\t}\n\t\t}\n\t}\/\/~for()\n}\n}\/\/~namespace\n\n\n\nvoid Node::Write(ting::fs::File& fi, bool formatted){\n\tting::fs::File::Guard fileGuard(fi, ting::fs::File::CREATE);\n\n\tWriteNode(this, fi, formatted, 0);\n}\n\n\n\nting::Ptr<stob::Node> stob::Load(ting::fs::File& fi){\n\tclass Listener : public stob::ParseListener{\n\t\ttypedef std::pair<ting::Ptr<Node>, Node*> T_Pair;\n\t\tstd::vector<T_Pair> stack;\n\n\tpublic:\n\t\tting::Ptr<Node> chains;\n\t\tNode* lastChain;\n\t\t\n\t\t\/\/override\n\t\tvoid OnChildrenParseFinished(){\n\t\t\tthis->stack.back().second->SetChildren(this->chains);\n\t\t\tthis->chains = this->stack.back().first;\n\t\t\tthis->lastChain = this->stack.back().second;\n\t\t\tthis->stack.pop_back();\n\t\t}\n\n\t\t\/\/override\n\t\tvoid OnChildrenParseStarted(){\n\t\t\tthis->stack.push_back(\n\t\t\t\t\tT_Pair(this->chains, this->lastChain)\n\t\t\t\t);\n\t\t}\n\n\t\t\/\/override\n\t\tvoid OnStringParsed(const char* s, ting::u32 size){\n\t\t\tting::Ptr<Node> node = Node::New(s, size);\n\n\t\t\tif(this->chains.IsNotValid()){\n\t\t\t\tthis->chains = node;\n\t\t\t\tthis->lastChain = this->chains.operator->();\n\t\t\t}else{\n\t\t\t\tthis->lastChain->InsertNext(node);\n\t\t\t\tthis->lastChain = this->lastChain->Next();\n\t\t\t}\n\t\t}\n\n\t\tListener() :\n\t\t\t\tchains(Node::New()),\/\/create root node\n\t\t\t\tlastChain(this->chains.operator->())\n\t\t{}\n\n\t\t~Listener()throw(){}\n\t} listener;\n\n\tlistener.OnChildrenParseStarted();\n\tstob::Parse(fi, listener);\n\tlistener.OnChildrenParseFinished();\n\n\treturn listener.chains;\n}\n\n\n\nting::Ptr<stob::Node> Node::Clone()const{\n\tting::Ptr<Node> ret = Node::New(this->Value());\n\n\tif(!this->Child()){\n\t\treturn ret;\n\t}\n\n\tting::Ptr<stob::Node> c = this->Child()->Clone();\n\n\t{\n\t\tstob::Node* curChild = c.operator->();\n\t\tfor(const stob::Node *p = this->Child()->Next(); p; p = p->Next(), curChild = curChild->Next()){\n\t\t\tASSERT(curChild)\n\t\t\tcurChild->InsertNext(p->Clone());\n\t\t}\n\t}\n\n\tret->SetChildren(c);\n\treturn ret;\n}\n\n\n\nbool Node::operator==(const Node& n)const throw(){\n\tif(!this->operator==(n.Value())){\n\t\treturn false;\n\t}\n\t\n\tconst stob::Node* c = this->Child();\n\tconst stob::Node* cn = n.Child();\n\tfor(; c && cn; c = c->Next(), cn = cn->Next()){\n\t\tif(!c->operator==(cn->Value())){\n\t\t\treturn false;\n\t\t}\n\t}\n\t\n\t\/\/if not equal number of children\n\tif((c && !cn) || (!c && cn)){\n\t\treturn false;\n\t}\n\t\n\treturn true;\n}\n\n\n<commit_msg>removed space<commit_after>#include \"dom.hpp\"\n\n#include <vector>\n\n#include <ting\/debug.hpp>\n#include <ting\/Array.hpp>\n\n#include \"parser.hpp\"\n\n\n\nusing namespace stob;\n\n\n\nnamespace{\nting::MemoryPool<sizeof(Node), 1024> memoryPool;\n}\n\n\n\nvoid* Node::operator new(size_t size){\n\tASSERT(size == sizeof(Node))\n\n\treturn memoryPool.Alloc_ts();\n}\n\n\n\nvoid Node::operator delete(void* p)throw(){\n\tmemoryPool.Free_ts(p);\n}\n\n\n\nstob::Node::NodeAndPrev Node::Next(const char* value)throw(){\n\tNode* prev = this;\n\tfor(Node* n = this->Next(); n; prev = n, n = n->Next()){\n\t\tif(n->operator==(value)){\n\t\t\treturn NodeAndPrev(prev, n);\n\t\t}\n\t}\n\treturn NodeAndPrev(prev, 0);\n}\n\n\n\nstob::Node::NodeAndPrev Node::Child(const char* value)throw(){\n\tif(this->children.IsNotValid()){\n\t\treturn NodeAndPrev(0, 0);\n\t}\n\n\tif(this->children->operator==(value)){\n\t\treturn NodeAndPrev(0, this->children.operator->());\n\t}\n\n\treturn this->children->Next(value);\n}\n\n\n\nstob::Node::NodeAndPrev Node::ChildNonProperty()throw(){\n\tif(this->children.IsNotValid()){\n\t\treturn NodeAndPrev(0, 0);\n\t}\n\n\tif(!this->children->IsProperty()){\n\t\treturn NodeAndPrev(0, this->children.operator->());\n\t}\n\n\treturn this->children->NextNonProperty();\n}\n\n\n\nstob::Node::NodeAndPrev Node::ChildProperty()throw(){\n\tif(this->children.IsNotValid()){\n\t\treturn NodeAndPrev(0, 0);\n\t}\n\n\tif(this->children->IsProperty()){\n\t\treturn NodeAndPrev(0, this->children.operator->());\n\t}\n\n\treturn this->children->NextProperty();\n}\n\n\n\nstob::Node::NodeAndPrev Node::NextNonProperty()throw(){\n\tNode* prev = this;\n\tfor(Node* n = this->Next(); n; prev = n, n = n->Next()){\n\t\tif(!n->IsProperty()){\n\t\t\treturn NodeAndPrev(prev, n);\n\t\t}\n\t}\n\treturn NodeAndPrev(prev, 0);\n}\n\n\n\nstob::Node::NodeAndPrev Node::NextProperty()throw(){\n\tNode* prev = this;\n\tfor(Node* n = this->Next(); n; prev = n, n = n->Next()){\n\t\tif(n->IsProperty()){\n\t\t\treturn NodeAndPrev(prev, n);\n\t\t}\n\t}\n\treturn NodeAndPrev(prev, 0);\n}\n\n\n\nNode* Node::AddProperty(const char* propName){\n\tting::Ptr<Node> p = Node::New();\n\tp->SetValue(propName);\n\tp->SetNext(this->RemoveChildren());\n\tthis->SetChildren(p);\n\n\tthis->Child()->SetChildren(Node::New());\n\n\treturn this->Child()->Child();\n}\n\n\n\nnamespace{\n\nbool CanStringBeUnquoted(const char* s, size_t& out_length, unsigned& out_numEscapes){\n\/\/\tTRACE(<< \"CanStringBeUnquoted(): enter\" << std::endl)\n\n\tout_numEscapes = 0;\n\tout_length = 0;\n\n\tif(s == 0){\/\/empty string is can be unquoted when it has children, so return true.\n\t\treturn true;\n\t}\n\n\tbool ret = true;\n\tfor(; *s != 0; ++s, ++out_length){\n\/\/\t\tTRACE(<< \"CanStringBeUnquoted(): c = \" << (*c) << std::endl)\n\t\tswitch(*s){\n\t\t\tcase '\\t':\n\t\t\tcase '\\n':\n\t\t\tcase '\\r':\n\t\t\tcase '\\\\':\n\t\t\tcase '\"':\n\t\t\t\t++out_numEscapes;\n\t\t\tcase '{':\n\t\t\tcase '}':\n\t\t\tcase ' ':\n\t\t\t\tret = false;\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tbreak;\n\t\t}\n\t}\n\treturn ret;\n}\n\n\nvoid MakeEscapedString(const char* str, ting::Buffer<ting::u8>& out){\n\tting::u8 *p = out.Begin();\n\tfor(const char* c = str; *c != 0; ++c){\n\t\tASSERT(p != out.End())\n\n\t\tswitch(*c){\n\t\t\tcase '\\t':\n\t\t\t\t*p = '\\\\';\n\t\t\t\t++p;\n\t\t\t\tASSERT(p != out.End())\n\t\t\t\t*p = 't';\n\t\t\t\tbreak;\n\t\t\tcase '\\n':\n\t\t\t\t*p = '\\\\';\n\t\t\t\t++p;\n\t\t\t\tASSERT(p != out.End())\n\t\t\t\t*p = 'n';\n\t\t\t\tbreak;\n\t\t\tcase '\\r':\n\t\t\t\t*p = '\\\\';\n\t\t\t\t++p;\n\t\t\t\tASSERT(p != out.End())\n\t\t\t\t*p = 'r';\n\t\t\t\tbreak;\n\t\t\tcase '\\\\':\n\t\t\t\t*p = '\\\\';\n\t\t\t\t++p;\n\t\t\t\tASSERT(p != out.End())\n\t\t\t\t*p = '\\\\';\n\t\t\t\tbreak;\n\t\t\tcase '\"':\n\t\t\t\t*p = '\\\\';\n\t\t\t\t++p;\n\t\t\t\tASSERT(p != out.End())\n\t\t\t\t*p = '\"';\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\t*p = *c;\n\t\t\t\tbreak;\n\t\t}\n\t\t++p;\n\t}\n}\n\n\nvoid WriteNode(const stob::Node* node, ting::fs::File& fi, bool formatted, unsigned indentation){\n\tASSERT(node)\n\n\tting::StaticBuffer<ting::u8, 1> quote;\n\tquote[0] = '\"';\n\n\tting::StaticBuffer<ting::u8, 1> lcurly;\n\tlcurly[0] = '{';\n\n\tting::StaticBuffer<ting::u8, 1> rcurly;\n\trcurly[0] = '}';\n\n\tting::StaticBuffer<ting::u8, 1> space;\n\tspace[0] = ' ';\n\n\tting::StaticBuffer<ting::u8, 1> tab;\n\ttab[0] = '\\t';\n\n\tting::StaticBuffer<ting::u8, 1> newLine;\n\tnewLine[0] = '\\n';\n\n\t\/\/used to detect case of two adjacent unquoted strings without children, need to insert space between them\n\tbool prevWasUnquotedWithoutChildren = false;\n\t\n\tbool prevHadChildren = true;\n\n\tfor(const Node* n = node->Child(); n; n = n->Next()){\n\t\t\/\/indent\n\t\tif(formatted){\n\t\t\tfor(unsigned i = 0; i != indentation; ++i){\n\t\t\t\tfi.Write(tab);\n\t\t\t}\n\t\t}\n\n\t\t\/\/write node value\n\n\t\tunsigned numEscapes;\n\t\tsize_t length;\n\t\tbool unqouted = CanStringBeUnquoted(n->Value(), length, numEscapes);\n\n\t\tif(!unqouted){\n\t\t\tfi.Write(quote);\n\n\t\t\tif(numEscapes == 0){\n\t\t\t\tfi.Write(ting::Buffer<ting::u8>(\n\t\t\t\t\t\tconst_cast<ting::u8*>(reinterpret_cast<const ting::u8*>(n->Value())),\n\t\t\t\t\t\tlength\n\t\t\t\t\t));\n\t\t\t}else{\n\t\t\t\tting::Array<ting::u8> buf(length + numEscapes);\n\n\t\t\t\tMakeEscapedString(n->Value(), buf);\n\n\t\t\t\tfi.Write(buf);\n\t\t\t}\n\n\t\t\tfi.Write(quote);\n\t\t}else{\n\t\t\tbool isQuotedEmptyString = false;\n\t\t\tif(n->ValueLength() == 0){\/\/if empty string\n\t\t\t\tif(!n->Child() || !prevHadChildren){\n\t\t\t\t\tisQuotedEmptyString = true;\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\t\/\/unquoted string\n\t\t\tif(!formatted && prevWasUnquotedWithoutChildren && !isQuotedEmptyString){\n\t\t\t\tfi.Write(space);\n\t\t\t}\n\n\t\t\tif(n->ValueLength() == 0){\/\/if empty string\n\t\t\t\tif(isQuotedEmptyString){\n\t\t\t\t\tfi.Write(quote);\n\t\t\t\t\tfi.Write(quote);\n\t\t\t\t}\n\t\t\t}else{\n\t\t\t\tASSERT(numEscapes == 0)\n\t\t\t\tfi.Write(ting::Buffer<ting::u8>(\n\t\t\t\t\t\tconst_cast<ting::u8*>(reinterpret_cast<const ting::u8*>(n->Value())),\n\t\t\t\t\t\tlength\n\t\t\t\t\t));\n\t\t\t}\n\t\t}\n\n\t\tprevHadChildren = (n->Child() != 0);\n\t\tif(n->Child() == 0){\n\t\t\t\n\t\t\tif(formatted){\n\t\t\t\tfi.Write(newLine);\n\t\t\t}\n\t\t\tprevWasUnquotedWithoutChildren = (unqouted && n->ValueLength() != 0);\n\t\t\tcontinue;\n\t\t}else{\n\t\t\tprevWasUnquotedWithoutChildren = false;\n\t\t}\n\n\t\tif(!formatted){\n\t\t\tfi.Write(lcurly);\n\n\t\t\tWriteNode(n, fi, false, 0);\n\n\t\t\tfi.Write(rcurly);\n\t\t}else{\n\t\t\tif(n->Child()->Next() == 0 && n->Child()->Child() == 0){\n\t\t\t\t\/\/if only one child and that child has no children\n\n\t\t\t\tfi.Write(lcurly);\n\t\t\t\tWriteNode(n, fi, false, 0);\n\t\t\t\tfi.Write(rcurly);\n\t\t\t\tfi.Write(newLine);\n\t\t\t}else{\n\t\t\t\tfi.Write(lcurly);\n\t\t\t\tfi.Write(newLine);\n\t\t\t\tWriteNode(n, fi, true, indentation + 1);\n\n\t\t\t\t\/\/indent\n\t\t\t\tfor(unsigned i = 0; i != indentation; ++i){\n\t\t\t\t\tfi.Write(tab);\n\t\t\t\t}\n\t\t\t\tfi.Write(rcurly);\n\t\t\t\tfi.Write(newLine);\n\t\t\t}\n\t\t}\n\t}\/\/~for()\n}\n}\/\/~namespace\n\n\n\nvoid Node::Write(ting::fs::File& fi, bool formatted){\n\tting::fs::File::Guard fileGuard(fi, ting::fs::File::CREATE);\n\n\tWriteNode(this, fi, formatted, 0);\n}\n\n\n\nting::Ptr<stob::Node> stob::Load(ting::fs::File& fi){\n\tclass Listener : public stob::ParseListener{\n\t\ttypedef std::pair<ting::Ptr<Node>, Node*> T_Pair;\n\t\tstd::vector<T_Pair> stack;\n\n\tpublic:\n\t\tting::Ptr<Node> chains;\n\t\tNode* lastChain;\n\t\t\n\t\t\/\/override\n\t\tvoid OnChildrenParseFinished(){\n\t\t\tthis->stack.back().second->SetChildren(this->chains);\n\t\t\tthis->chains = this->stack.back().first;\n\t\t\tthis->lastChain = this->stack.back().second;\n\t\t\tthis->stack.pop_back();\n\t\t}\n\n\t\t\/\/override\n\t\tvoid OnChildrenParseStarted(){\n\t\t\tthis->stack.push_back(\n\t\t\t\t\tT_Pair(this->chains, this->lastChain)\n\t\t\t\t);\n\t\t}\n\n\t\t\/\/override\n\t\tvoid OnStringParsed(const char* s, ting::u32 size){\n\t\t\tting::Ptr<Node> node = Node::New(s, size);\n\n\t\t\tif(this->chains.IsNotValid()){\n\t\t\t\tthis->chains = node;\n\t\t\t\tthis->lastChain = this->chains.operator->();\n\t\t\t}else{\n\t\t\t\tthis->lastChain->InsertNext(node);\n\t\t\t\tthis->lastChain = this->lastChain->Next();\n\t\t\t}\n\t\t}\n\n\t\tListener() :\n\t\t\t\tchains(Node::New()),\/\/create root node\n\t\t\t\tlastChain(this->chains.operator->())\n\t\t{}\n\n\t\t~Listener()throw(){}\n\t} listener;\n\n\tlistener.OnChildrenParseStarted();\n\tstob::Parse(fi, listener);\n\tlistener.OnChildrenParseFinished();\n\n\treturn listener.chains;\n}\n\n\n\nting::Ptr<stob::Node> Node::Clone()const{\n\tting::Ptr<Node> ret = Node::New(this->Value());\n\n\tif(!this->Child()){\n\t\treturn ret;\n\t}\n\n\tting::Ptr<stob::Node> c = this->Child()->Clone();\n\n\t{\n\t\tstob::Node* curChild = c.operator->();\n\t\tfor(const stob::Node *p = this->Child()->Next(); p; p = p->Next(), curChild = curChild->Next()){\n\t\t\tASSERT(curChild)\n\t\t\tcurChild->InsertNext(p->Clone());\n\t\t}\n\t}\n\n\tret->SetChildren(c);\n\treturn ret;\n}\n\n\n\nbool Node::operator==(const Node& n)const throw(){\n\tif(!this->operator==(n.Value())){\n\t\treturn false;\n\t}\n\t\n\tconst stob::Node* c = this->Child();\n\tconst stob::Node* cn = n.Child();\n\tfor(; c && cn; c = c->Next(), cn = cn->Next()){\n\t\tif(!c->operator==(cn->Value())){\n\t\t\treturn false;\n\t\t}\n\t}\n\t\n\t\/\/if not equal number of children\n\tif((c && !cn) || (!c && cn)){\n\t\treturn false;\n\t}\n\t\n\treturn true;\n}\n\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2010 Satoshi Nakamoto\n\/\/ Copyright (c) 2009-2012 The Bitcoin developers\n\/\/ Copyright (c) 2013 The Zetacoin developers\n\/\/ Copyright (c) 2014 The Mazacoin developers\n\/\/ Distributed under the MIT\/X11 software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \"assert.h\"\n\n#include \"chainparams.h\"\n#include \"core.h\"\n#include \"protocol.h\"\n#include \"util.h\"\n\n\/\/\n\/\/ Main network\n\/\/\n\nunsigned int pnSeed[] =\n{\n 0x12345678\n};\n\nclass CMainParams : public CChainParams {\npublic:\n CMainParams() {\n \/\/ The message start string is designed to be unlikely to occur in normal data.\n pchMessageStart[0] = 0xf8;\n pchMessageStart[1] = 0xb5;\n pchMessageStart[2] = 0x03;\n pchMessageStart[3] = 0xdf;\n vAlertPubKey = ParseHex(\"04f09702847840aaf195de8442ebecedf5b095cdbb9bc716bda9110971b28a49e0ead8564ff0db22209e0374782c093bb899692d524e9d6a6956e7c5ecbcd68284\");\n nDefaultPort = 12835;\n nRPCPort = 12832;\n bnProofOfWorkLimit = CBigNum(~uint256(0) >> 20);\n nSubsidyHalvingInterval = 950000;\n\n \/\/ Build the genesis block. Note that the output of the genesis coinbase cannot\n \/\/ be spent as it did not originally exist in the database.\n\n const char* pszTimestamp = \"February 5, 2014: The Black Hills are not for sale - 1868 Is The LAW!\";\n CTransaction txNew;\n txNew.vin.resize(1);\n txNew.vout.resize(1);\n txNew.vin[0].scriptSig = CScript() << 486604799 << CBigNum(4) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp));\n txNew.vout[0].nValue = 5000 * COIN;\n txNew.vout[0].scriptPubKey = CScript() << ParseHex(\"04678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5f\") << OP_CHECKSIG;\n genesis.vtx.push_back(txNew);\n genesis.hashPrevBlock = 0;\n genesis.hashMerkleRoot = genesis.BuildMerkleTree();\n genesis.nVersion = 1;\n genesis.nTime = 1390747675;\n genesis.nBits = 0x1e0ffff0;\n genesis.nNonce = 2091390249;\n\n \/\/\/\/ debug print\n hashGenesisBlock = genesis.GetHash();\n \/\/while (hashGenesisBlock > bnProofOfWorkLimit.getuint256()){\n \/\/ if (++genesis.nNonce==0) break;\n \/\/ hashGenesisBlock = genesis.GetHash();\n \/\/}\n\n printf(\"%s\\n\", hashGenesisBlock.ToString().c_str());\n printf(\"%s\\n\", genesis.hashMerkleRoot.ToString().c_str());\n printf(\"%x\\n\", bnProofOfWorkLimit.GetCompact());\n genesis.print();\n\n\n assert(hashGenesisBlock == uint256(\"0x00000c7c73d8ce604178dae13f0fc6ec0be3275614366d44b1b4b5c6e238c60c\"));\n assert(genesis.hashMerkleRoot == uint256(\"0x62d496378e5834989dd9594cfc168dbb76f84a39bbda18286cddc7d1d1589f4f\"));\n\n vSeeds.push_back(CDNSSeedData(\"node.mazacoin.org\", \"node.mazacoin.org\"));\n vSeeds.push_back(CDNSSeedData(\"node.mazacoin.cf\", \"node.mazacoin.cf\"));\n vSeeds.push_back(CDNSSeedData(\"mazacoin.no-ip.org\", \"mazacoin.no-ip.org\"));\n\n base58Prefixes[PUBKEY_ADDRESS] = 50;\n base58Prefixes[SCRIPT_ADDRESS] = 9;\n base58Prefixes[SECRET_KEY] = 224;\n\n \/\/ Convert the pnSeeds array into usable address objects.\n for (unsigned int i = 0; i < ARRAYLEN(pnSeed); i++)\n {\n \/\/ It'll only connect to one or two seed nodes because once it connects,\n \/\/ it'll get a pile of addresses with newer timestamps.\n \/\/ Seed nodes are given a random 'last seen time'\n const int64 nTwoDays = 2 * 24 * 60 * 60;\n struct in_addr ip;\n memcpy(&ip, &pnSeed[i], sizeof(ip));\n CAddress addr(CService(ip, GetDefaultPort()));\n addr.nTime = GetTime() - GetRand(nTwoDays) - nTwoDays;\n vFixedSeeds.push_back(addr);\n }\n }\n\n virtual const CBlock& GenesisBlock() const { return genesis; }\n virtual Network NetworkID() const { return CChainParams::MAIN; }\n\n virtual const vector<CAddress>& FixedSeeds() const {\n return vFixedSeeds;\n }\nprotected:\n CBlock genesis;\n vector<CAddress> vFixedSeeds;\n};\nstatic CMainParams mainParams;\n\n\n\/\/\n\/\/ Testnet (v3)\n\/\/\nclass CTestNetParams : public CMainParams {\npublic:\n CTestNetParams() {\n \/\/ The message start string is designed to be unlikely to occur in normal data.\n pchMessageStart[0] = 0x05;\n pchMessageStart[1] = 0xfe;\n pchMessageStart[2] = 0xa9;\n pchMessageStart[3] = 0x01;\n vAlertPubKey = ParseHex(\"04303390343f91cc401d56d68b123028bf52e5fca1939df127f63c6467cdf9c8e2c14b61104cf817d0b780da337893ecc4aaff1309e536162dabbdb45200ca2b0a\");\n nDefaultPort = 11835;\n nRPCPort = 11832;\n strDataDir = \"testnet\";\n\n \/\/ Modify the testnet genesis block so the timestamp is valid for a later start.\n genesis.nTime = 1390747675;\n genesis.nNonce = 2091390249;\n\n\n \/\/\/\/ debug print\n hashGenesisBlock = genesis.GetHash();\n \/\/ while (hashGenesisBlock > bnProofOfWorkLimit.getuint256()){\n \/\/ if (++genesis.nNonce==0) break;\n \/\/ hashGenesisBlock = genesis.GetHash();\n \/\/ }\n\n printf(\"%s\\n\", hashGenesisBlock.ToString().c_str());\n printf(\"%s\\n\", genesis.hashMerkleRoot.ToString().c_str());\n genesis.print();\n\n assert(hashGenesisBlock == uint256(\"0x00000c7c73d8ce604178dae13f0fc6ec0be3275614366d44b1b4b5c6e238c60c\"));\n\t\t\n vFixedSeeds.clear();\n vSeeds.clear();\n \/\/ vSeeds.push_back(CDNSSeedData(\"mazacoin.test\", \"test.mazacoin.org\"));\n\n base58Prefixes[PUBKEY_ADDRESS] = 88;\n base58Prefixes[SCRIPT_ADDRESS] = 188;\n base58Prefixes[SECRET_KEY] = 239;\n\n }\n virtual Network NetworkID() const { return CChainParams::TESTNET; }\n};\n\/\/static CTestNetParams testNetParams;\n\n\n\/\/\n\/\/ Regression test\n\/\/\nclass CRegTestParams : public CTestNetParams {\npublic:\n CRegTestParams() {\n pchMessageStart[0] = 0xfa;\n pchMessageStart[1] = 0x0f;\n pchMessageStart[2] = 0xa5;\n pchMessageStart[3] = 0x5a;\n nSubsidyHalvingInterval = 150;\n bnProofOfWorkLimit = CBigNum(~uint256(0) >> 1);\n genesis.nTime = 1390748221;\n genesis.nBits = 0x207fffff;\n genesis.nNonce = 4;\n hashGenesisBlock = genesis.GetHash();\n nDefaultPort = 11444;\n strDataDir = \"regtest\";\n\n \/\/ debug print\n hashGenesisBlock = genesis.GetHash();\n while (hashGenesisBlock > bnProofOfWorkLimit.getuint256()){\n if (++genesis.nNonce==0) break;\n hashGenesisBlock = genesis.GetHash();\n }\n\n printf(\"%s\\n\", hashGenesisBlock.ToString().c_str());\n printf(\"%s\\n\", genesis.hashMerkleRoot.ToString().c_str());\n genesis.print();\n\n assert(hashGenesisBlock == uint256(\"0x57939ce0a96bf42965fee5956528a456d0edfb879b8bd699bcbb4786d27b979d\"));\n\n vSeeds.clear(); \/\/ Regtest mode doesn't have any DNS seeds.\n\n base58Prefixes[PUBKEY_ADDRESS] = 0;\n base58Prefixes[SCRIPT_ADDRESS] = 5;\n base58Prefixes[SECRET_KEY] = 128;\n }\n\n virtual bool RequireRPCPassword() const { return false; }\n virtual Network NetworkID() const { return CChainParams::REGTEST; }\n};\n\/\/static CRegTestParams regTestParams;\n\nstatic CChainParams *pCurrentParams = &mainParams;\n\nconst CChainParams &Params() {\n return *pCurrentParams;\n}\n\nvoid SelectParams(CChainParams::Network network) {\n switch (network) {\n case CChainParams::MAIN:\n pCurrentParams = &mainParams;\n break;\n \/\/case CChainParams::TESTNET:\n \/\/ pCurrentParams = &testNetParams;\n \/\/ break;\n \/\/case CChainParams::REGTEST:\n \/\/ pCurrentParams = ®TestParams;\n \/\/ break;\n default:\n assert(false && \"Unimplemented network\");\n return;\n }\n}\n\nbool SelectParamsFromCommandLine() {\n bool fRegTest = GetBoolArg(\"-regtest\", false);\n bool fTestNet = GetBoolArg(\"-testnet\", false);\n\n if (fTestNet && fRegTest) {\n return false;\n }\n\n if (fRegTest) {\n SelectParams(CChainParams::REGTEST);\n } else if (fTestNet) {\n SelectParams(CChainParams::TESTNET);\n } else {\n SelectParams(CChainParams::MAIN);\n }\n return true;\n}\n<commit_msg>Don't print Genesis block info on every RPC call<commit_after>\/\/ Copyright (c) 2010 Satoshi Nakamoto\n\/\/ Copyright (c) 2009-2012 The Bitcoin developers\n\/\/ Copyright (c) 2013 The Zetacoin developers\n\/\/ Copyright (c) 2014 The Mazacoin developers\n\/\/ Distributed under the MIT\/X11 software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \"assert.h\"\n\n#include \"chainparams.h\"\n#include \"core.h\"\n#include \"protocol.h\"\n#include \"util.h\"\n\n\/\/\n\/\/ Main network\n\/\/\n\nunsigned int pnSeed[] =\n{\n 0x12345678\n};\n\nclass CMainParams : public CChainParams {\npublic:\n CMainParams() {\n \/\/ The message start string is designed to be unlikely to occur in normal data.\n pchMessageStart[0] = 0xf8;\n pchMessageStart[1] = 0xb5;\n pchMessageStart[2] = 0x03;\n pchMessageStart[3] = 0xdf;\n vAlertPubKey = ParseHex(\"04f09702847840aaf195de8442ebecedf5b095cdbb9bc716bda9110971b28a49e0ead8564ff0db22209e0374782c093bb899692d524e9d6a6956e7c5ecbcd68284\");\n nDefaultPort = 12835;\n nRPCPort = 12832;\n bnProofOfWorkLimit = CBigNum(~uint256(0) >> 20);\n nSubsidyHalvingInterval = 950000;\n\n \/\/ Build the genesis block. Note that the output of the genesis coinbase cannot\n \/\/ be spent as it did not originally exist in the database.\n\n const char* pszTimestamp = \"February 5, 2014: The Black Hills are not for sale - 1868 Is The LAW!\";\n CTransaction txNew;\n txNew.vin.resize(1);\n txNew.vout.resize(1);\n txNew.vin[0].scriptSig = CScript() << 486604799 << CBigNum(4) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp));\n txNew.vout[0].nValue = 5000 * COIN;\n txNew.vout[0].scriptPubKey = CScript() << ParseHex(\"04678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5f\") << OP_CHECKSIG;\n genesis.vtx.push_back(txNew);\n genesis.hashPrevBlock = 0;\n genesis.hashMerkleRoot = genesis.BuildMerkleTree();\n genesis.nVersion = 1;\n genesis.nTime = 1390747675;\n genesis.nBits = 0x1e0ffff0;\n genesis.nNonce = 2091390249;\n\n \/\/\/\/ debug print\n hashGenesisBlock = genesis.GetHash();\n \/\/while (hashGenesisBlock > bnProofOfWorkLimit.getuint256()){\n \/\/ if (++genesis.nNonce==0) break;\n \/\/ hashGenesisBlock = genesis.GetHash();\n \/\/}\n\n \/\/printf(\"%s\\n\", hashGenesisBlock.ToString().c_str());\n \/\/printf(\"%s\\n\", genesis.hashMerkleRoot.ToString().c_str());\n \/\/printf(\"%x\\n\", bnProofOfWorkLimit.GetCompact());\n \/\/genesis.print();\n\n\n assert(hashGenesisBlock == uint256(\"0x00000c7c73d8ce604178dae13f0fc6ec0be3275614366d44b1b4b5c6e238c60c\"));\n assert(genesis.hashMerkleRoot == uint256(\"0x62d496378e5834989dd9594cfc168dbb76f84a39bbda18286cddc7d1d1589f4f\"));\n\n vSeeds.push_back(CDNSSeedData(\"node.mazacoin.org\", \"node.mazacoin.org\"));\n vSeeds.push_back(CDNSSeedData(\"node.mazacoin.cf\", \"node.mazacoin.cf\"));\n vSeeds.push_back(CDNSSeedData(\"mazacoin.no-ip.org\", \"mazacoin.no-ip.org\"));\n\n base58Prefixes[PUBKEY_ADDRESS] = 50;\n base58Prefixes[SCRIPT_ADDRESS] = 9;\n base58Prefixes[SECRET_KEY] = 224;\n\n \/\/ Convert the pnSeeds array into usable address objects.\n for (unsigned int i = 0; i < ARRAYLEN(pnSeed); i++)\n {\n \/\/ It'll only connect to one or two seed nodes because once it connects,\n \/\/ it'll get a pile of addresses with newer timestamps.\n \/\/ Seed nodes are given a random 'last seen time'\n const int64 nTwoDays = 2 * 24 * 60 * 60;\n struct in_addr ip;\n memcpy(&ip, &pnSeed[i], sizeof(ip));\n CAddress addr(CService(ip, GetDefaultPort()));\n addr.nTime = GetTime() - GetRand(nTwoDays) - nTwoDays;\n vFixedSeeds.push_back(addr);\n }\n }\n\n virtual const CBlock& GenesisBlock() const { return genesis; }\n virtual Network NetworkID() const { return CChainParams::MAIN; }\n\n virtual const vector<CAddress>& FixedSeeds() const {\n return vFixedSeeds;\n }\nprotected:\n CBlock genesis;\n vector<CAddress> vFixedSeeds;\n};\nstatic CMainParams mainParams;\n\n\n\/\/\n\/\/ Testnet (v3)\n\/\/\nclass CTestNetParams : public CMainParams {\npublic:\n CTestNetParams() {\n \/\/ The message start string is designed to be unlikely to occur in normal data.\n pchMessageStart[0] = 0x05;\n pchMessageStart[1] = 0xfe;\n pchMessageStart[2] = 0xa9;\n pchMessageStart[3] = 0x01;\n vAlertPubKey = ParseHex(\"04303390343f91cc401d56d68b123028bf52e5fca1939df127f63c6467cdf9c8e2c14b61104cf817d0b780da337893ecc4aaff1309e536162dabbdb45200ca2b0a\");\n nDefaultPort = 11835;\n nRPCPort = 11832;\n strDataDir = \"testnet\";\n\n \/\/ Modify the testnet genesis block so the timestamp is valid for a later start.\n genesis.nTime = 1390747675;\n genesis.nNonce = 2091390249;\n\n\n \/\/\/\/ debug print\n hashGenesisBlock = genesis.GetHash();\n \/\/ while (hashGenesisBlock > bnProofOfWorkLimit.getuint256()){\n \/\/ if (++genesis.nNonce==0) break;\n \/\/ hashGenesisBlock = genesis.GetHash();\n \/\/ }\n\n printf(\"%s\\n\", hashGenesisBlock.ToString().c_str());\n printf(\"%s\\n\", genesis.hashMerkleRoot.ToString().c_str());\n genesis.print();\n\n assert(hashGenesisBlock == uint256(\"0x00000c7c73d8ce604178dae13f0fc6ec0be3275614366d44b1b4b5c6e238c60c\"));\n\t\t\n vFixedSeeds.clear();\n vSeeds.clear();\n \/\/ vSeeds.push_back(CDNSSeedData(\"mazacoin.test\", \"test.mazacoin.org\"));\n\n base58Prefixes[PUBKEY_ADDRESS] = 88;\n base58Prefixes[SCRIPT_ADDRESS] = 188;\n base58Prefixes[SECRET_KEY] = 239;\n\n }\n virtual Network NetworkID() const { return CChainParams::TESTNET; }\n};\n\/\/static CTestNetParams testNetParams;\n\n\n\/\/\n\/\/ Regression test\n\/\/\nclass CRegTestParams : public CTestNetParams {\npublic:\n CRegTestParams() {\n pchMessageStart[0] = 0xfa;\n pchMessageStart[1] = 0x0f;\n pchMessageStart[2] = 0xa5;\n pchMessageStart[3] = 0x5a;\n nSubsidyHalvingInterval = 150;\n bnProofOfWorkLimit = CBigNum(~uint256(0) >> 1);\n genesis.nTime = 1390748221;\n genesis.nBits = 0x207fffff;\n genesis.nNonce = 4;\n hashGenesisBlock = genesis.GetHash();\n nDefaultPort = 11444;\n strDataDir = \"regtest\";\n\n \/\/ debug print\n hashGenesisBlock = genesis.GetHash();\n while (hashGenesisBlock > bnProofOfWorkLimit.getuint256()){\n if (++genesis.nNonce==0) break;\n hashGenesisBlock = genesis.GetHash();\n }\n\n printf(\"%s\\n\", hashGenesisBlock.ToString().c_str());\n printf(\"%s\\n\", genesis.hashMerkleRoot.ToString().c_str());\n genesis.print();\n\n assert(hashGenesisBlock == uint256(\"0x57939ce0a96bf42965fee5956528a456d0edfb879b8bd699bcbb4786d27b979d\"));\n\n vSeeds.clear(); \/\/ Regtest mode doesn't have any DNS seeds.\n\n base58Prefixes[PUBKEY_ADDRESS] = 0;\n base58Prefixes[SCRIPT_ADDRESS] = 5;\n base58Prefixes[SECRET_KEY] = 128;\n }\n\n virtual bool RequireRPCPassword() const { return false; }\n virtual Network NetworkID() const { return CChainParams::REGTEST; }\n};\n\/\/static CRegTestParams regTestParams;\n\nstatic CChainParams *pCurrentParams = &mainParams;\n\nconst CChainParams &Params() {\n return *pCurrentParams;\n}\n\nvoid SelectParams(CChainParams::Network network) {\n switch (network) {\n case CChainParams::MAIN:\n pCurrentParams = &mainParams;\n break;\n \/\/case CChainParams::TESTNET:\n \/\/ pCurrentParams = &testNetParams;\n \/\/ break;\n \/\/case CChainParams::REGTEST:\n \/\/ pCurrentParams = ®TestParams;\n \/\/ break;\n default:\n assert(false && \"Unimplemented network\");\n return;\n }\n}\n\nbool SelectParamsFromCommandLine() {\n bool fRegTest = GetBoolArg(\"-regtest\", false);\n bool fTestNet = GetBoolArg(\"-testnet\", false);\n\n if (fTestNet && fRegTest) {\n return false;\n }\n\n if (fRegTest) {\n SelectParams(CChainParams::REGTEST);\n } else if (fTestNet) {\n SelectParams(CChainParams::TESTNET);\n } else {\n SelectParams(CChainParams::MAIN);\n }\n return true;\n}\n<|endoftext|>"} {"text":"<commit_before>\n#include\t<string>\n#include\t<memory>\n\n#include\t\"simple\/third\/MimeCodes.cpp\"\n\nstatic inline bool is_base64_char(unsigned char c) {\n return (isalnum(c) || (c == '+') || (c == '\/'));\n}\n\nbool string_is_base64(const std::string& s) {\n size_t nLen\t= s.size();\n\n if(nLen < 3) {\n return false;\n }\n\n if('=' == s[nLen - 1])nLen--;\n if('=' == s[nLen - 1])nLen--;\n\n size_t i = 0;\n for(; i < nLen; ++i) {\n if(!is_base64_char(s[i])) {\n return false;\n }\n }\n return true;\n}\n\nstd::string\t\tstring_base64_encode(const unsigned char* str, unsigned long len) {\n std::string ret;\n ret.reserve(len * 2);\n base64_encode(str, str + len, std::back_inserter(ret));\n return ret;\n}\n\nstd::string\t\tstring_base64_decode(const unsigned char* str, unsigned long len) {\n std::string ret;\n ret.reserve(len);\n base64_decode(str, str + len, std::back_inserter(ret));\n return ret;\n}\n\nstd::string\t\tstring_qp_encode(const unsigned char* str, unsigned long len) {\n std::string ret;\n ret.reserve(len * 2);\n QpEncoder<const unsigned char*, std::back_insert_iterator<std::string> > e;\n e.Filter(std::back_inserter(ret), str, str + len);\n return ret;\n}\n\nstd::string\t\tstring_qp_decode(const unsigned char* str, unsigned long len) {\n std::string ret;\n ret.reserve(len);\n qp_decode(str, str + len, std::back_inserter(ret));\n return ret;\n}\n<commit_msg>string_mime 实现,增加 vc 编译兼容性。<commit_after>\n#include\t<string>\n#include\t<memory>\n#include <iterator>\n\n#include\t\"simple\/third\/MimeCodes.cpp\"\n\nstatic inline bool is_base64_char(unsigned char c) {\n return (isalnum(c) || (c == '+') || (c == '\/'));\n}\n\nbool string_is_base64(const std::string& s) {\n size_t nLen\t= s.size();\n\n if(nLen < 3) {\n return false;\n }\n\n if('=' == s[nLen - 1])nLen--;\n if('=' == s[nLen - 1])nLen--;\n\n size_t i = 0;\n for(; i < nLen; ++i) {\n if(!is_base64_char(s[i])) {\n return false;\n }\n }\n return true;\n}\n\nstd::string\t\tstring_base64_encode(const unsigned char* str, unsigned long len) {\n std::string ret;\n ret.reserve(len * 2);\n base64_encode(str, str + len, std::back_inserter(ret));\n return ret;\n}\n\nstd::string\t\tstring_base64_decode(const unsigned char* str, unsigned long len) {\n std::string ret;\n ret.reserve(len);\n base64_decode(str, str + len, std::back_inserter(ret));\n return ret;\n}\n\nstd::string\t\tstring_qp_encode(const unsigned char* str, unsigned long len) {\n std::string ret;\n ret.reserve(len * 2);\n QpEncoder<const unsigned char*, std::back_insert_iterator<std::string> > e;\n e.Filter(std::back_inserter(ret), str, str + len);\n return ret;\n}\n\nstd::string\t\tstring_qp_decode(const unsigned char* str, unsigned long len) {\n std::string ret;\n ret.reserve(len);\n qp_decode(str, str + len, std::back_inserter(ret));\n return ret;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n\nMIT License\n\nCopyright (c) 2016 Mark Allender\n\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n\n*\/\n\n\/\/ Emulator.cpp : Defines the entry point for the console application.\n\/\/\n#include <algorithm>\n#include <string>\n#include <stdlib.h>\n\n#include \"6502\/cpu.h\"\n#include \"6502\/assemble.h\"\n#include \"6502\/video.h\"\n#include \"6502\/disk.h\"\n#include \"6502\/keyboard.h\"\n#include \"6502\/speaker.h\"\n#include \"debugger\/debugger.h\"\n#include \"utils\/path_utils.h\"\n\n#include \"SDL.h\"\n\n#if defined(_MSC_VER)\n#pragma warning(disable:4996) \/\/ disable the deprecated warnings for fopen\n#endif\n\nINITIALIZE_EASYLOGGINGPP\n\n#define MEMORY_SIZE (64 * 1024 * 1024)\nint8_t memory_buffer[MEMORY_SIZE];\n\nstatic const double Render_time = 500; \/\/ roughly 30 fps\n\nstatic void configure_logging()\n{\n\tel::Configurations conf;\n\n\tconf.setToDefault();\n\tconf.set(el::Level::Global, el::ConfigurationType::Enabled, \"true\");\n\tconf.set(el::Level::Global, el::ConfigurationType::LogFileTruncate, \"true\");\n\tconf.set(el::Level::Global, el::ConfigurationType::ToStandardOutput, \"false\");\n\tconf.set(el::Level::Global, el::ConfigurationType::Format, \"%msg\");\n\tel::Loggers::reconfigureLogger(\"default\", conf);\n\n\t\/\/ set some options on the logger\n\tel::Loggers::addFlag(el::LoggingFlag::ImmediateFlush);\n\tel::Loggers::addFlag(el::LoggingFlag::NewLineForContainer);\n\tel::Loggers::addFlag(el::LoggingFlag::ColoredTerminalOutput);\n}\n\n\nstatic char *get_cmdline_option(char **start, char **end, const std::string &short_option, const std::string &long_option = \"\")\n{\n\tchar **iter = std::find(start, end, short_option);\n\tif (iter == end) {\n\t\titer = std::find(start, end, long_option);\n\t}\n\tif ((iter != end) && (iter++ != end) ) {\n\t\treturn *iter;\n\t}\n\n\treturn nullptr;\n}\n\nstatic bool cmdline_option_exists(char **start, char **end, const std::string &short_option, const std::string &long_option = \"\")\n{\n\tchar **iter = std::find(start, end, short_option);\n\tif (iter == end) {\n\t\titer = std::find(start, end, long_option);\n\t}\n\tif (iter == end) {\n\t\treturn false;\n\t}\n\treturn true;\n}\n\nbool dissemble_6502(const char *filename)\n{\n\treturn true;\n}\n\nint main(int argc, char* argv[])\n{\n\t\/\/ configure logging before anything else\n\tconfigure_logging();\n\n\tmemory mem(MEMORY_SIZE, memory_buffer);\n\tcpu_6502 cpu(mem);\n\tcpu.init();\n\n\tdebugger_init();\n\tdisk_init(mem);\n\n\t\/\/\/\/ get command line options\n\t\/\/const char *assembly_file = nullptr;\n\t\/\/const char *dissembly_file = nullptr;\n\t\/\/assembly_file = get_cmdline_option(argv, argv+argc, \"-a\", \"--assemble\");\n\n\t\/\/\/\/ let's test assembler\n\t\/\/if (assembly_file != nullptr) {\n\t\/\/\tassemble_6502(assembly_file);\n\t\/\/\treturn 0;\n\t\/\/}\n\n\t\/\/dissembly_file = get_cmdline_option(argv, argv+argc, \"-d\", \"--disassemble\");\n\t\/\/if (dissembly_file != nullptr) {\n\t\/\/\tdissemble_6502(dissembly_file);\n\t\/\/}\n\t\n\t\/\/FILE *fp = fopen(\"test.bin\", \"rb\");\n\t\/\/fseek(fp, 0, SEEK_END);\n\t\/\/uint32_t buffer_size = ftell(fp);\n\t\/\/fseek(fp, 0, SEEK_SET);\n\n\t\/\/\/\/ allocate the memory buffer\n\t\/\/uint8_t *buffer = new uint8_t[buffer_size];\n\t\/\/if (buffer == nullptr) {\n\t\/\/\tprintf(\"Unable to allocate %d bytes for source code file buffer\\n\", buffer_size);\n\t\/\/\tfclose(fp);\n\t\/\/\texit(-1);\n\t\/\/}\n\t\/\/fread(buffer, 1, buffer_size, fp);\n\t\/\/fclose(fp);\n\n\tuint16_t prog_start = 0x600;\n\tuint16_t load_addr = 0x0;\n\n\tconst char *prog_start_string = get_cmdline_option(argv, argv+argc, \"-p\", \"--pc\");\n\tif (prog_start_string != nullptr) {\n\t\tprog_start = (uint16_t)strtol(prog_start_string, nullptr, 16);\n\t}\n\n\tconst char *load_addr_string = get_cmdline_option(argv, argv+argc, \"-b\", \"--base\");\n\tif (load_addr_string != nullptr) {\n\t\tload_addr = (uint16_t)strtol(load_addr_string, nullptr, 16);\n\t}\n\n\tconst char *binary_file = nullptr;\n\tbinary_file = get_cmdline_option(argv, argv+argc, \"-b\", \"--binary\");\n\tif (binary_file != nullptr) {\n\t\tFILE *fp = fopen(binary_file, \"rb\");\n\t\tif (fp == nullptr) {\n\t\t\tprintf(\"Unable to open %s for reading: %d\\n\", binary_file, errno);\n\t\t\texit(-1);\n\t\t}\n\t\tfseek(fp, 0, SEEK_END);\n\t\tuint32_t buffer_size = ftell(fp);\n\t\tfseek(fp, 0, SEEK_SET);\n\n\t\t\/\/ allocate the memory buffer\n\t\tuint8_t *buffer = new uint8_t[buffer_size];\n\t\tif (buffer == nullptr) {\n\t\t\tprintf(\"Unable to allocate %d bytes for source code file buffer\\n\", buffer_size);\n\t\t\tfclose(fp);\n\t\t\texit(-1);\n\t\t}\n\t\tfread(buffer, 1, buffer_size, fp);\n\t\tfclose(fp);\n\t\tmem.load_memory(buffer, buffer_size, load_addr);\n\t\tcpu.set_pc(prog_start);\n\n\t\/\/ load up the ROMs\n\t} else {\n\t\tcpu.set_pc(mem[0xfffc] | mem[0xfffd] << 8);\n\n\t\t\/\/ see if there is disk imace\n\t\tconst char *disk_image_filename = get_cmdline_option(argv, argv+argc, \"-d\", \"--disk\"); \/\/ will always go to drive one for now\n\t\tif (disk_image_filename != nullptr) {\n\t\t\tdisk_insert(disk_image_filename, 1);\n\t\t}\n\t}\n\tvideo_init(mem);\n\tspeaker_init(mem);\n\tkeyboard_init();\n\n\tbool quit = false;\n\tuint32_t total_cycles = 0;\n\tdouble last_time = SDL_GetTicks();\n\tdouble processed_time = 0;\n\n\twhile (!quit) {\n\t\tSDL_Event evt;\n\n\t\twhile (SDL_PollEvent(&evt)) {\n\t\t\tswitch (evt.type) {\n\t\t\tcase SDL_KEYDOWN:\n\t\t\tcase SDL_KEYUP:\n\t\t\t\tkeyboard_handle_event(evt);\n\t\t\t\tbreak;\n\n\t\t\tcase SDL_WINDOWEVENT:\n\t\t\t\tif (evt.window.event == SDL_WINDOWEVENT_CLOSE) {\n\t\t\t\t\tquit = true;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\t\/\/ process debugger (before opcode processing so that we can break on\n\t\t\/\/ specific addresses properly\n\t\tdebugger_process(cpu, mem);\n\n\t\t\/\/ process the next opcode\n\t\tuint32_t cycles = cpu.process_opcode();\n\t\ttotal_cycles += cycles;\n\n\t\tif (total_cycles > 17030) {\n\t\t\t\/\/video_render_frame(mem);\n\t\t\ttotal_cycles -= 17030;\n\t\t}\n\n\t\t\/\/ determine whether to render or not. Calculate diff\n\t\t\/\/ between last frame.\n\t\tdouble cur_time = SDL_GetTicks();\n\t\tdouble diff_time = cur_time - last_time;\n\t\tlast_time = cur_time;\n\n\t\tbool should_render = false;\n\t\tprocessed_time += diff_time;\n\t\twhile (processed_time > Render_time) {\n\t\t\tshould_render = true;\n\t\t\tprocessed_time -= Render_time;\n\t\t}\n\n\t\tif (should_render == true) {\n\t\t\tvideo_render_frame(mem);\n\t\t}\n\n\t}\n\n\tvideo_shutdown();\n\tkeyboard_shutdown();\n debugger_shutdown();\n\n\treturn 0;\n}\n\n<commit_msg>Move event processing to every 33mx.<commit_after>\/*\n\nMIT License\n\nCopyright (c) 2016 Mark Allender\n\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n\n*\/\n\n\/\/ Emulator.cpp : Defines the entry point for the console application.\n\/\/\n#include <algorithm>\n#include <string>\n#include <stdlib.h>\n\n#include \"6502\/cpu.h\"\n#include \"6502\/assemble.h\"\n#include \"6502\/video.h\"\n#include \"6502\/disk.h\"\n#include \"6502\/keyboard.h\"\n#include \"6502\/speaker.h\"\n#include \"debugger\/debugger.h\"\n#include \"utils\/path_utils.h\"\n\n#include \"SDL.h\"\n\n#if defined(_MSC_VER)\n#pragma warning(disable:4996) \/\/ disable the deprecated warnings for fopen\n#endif\n\nINITIALIZE_EASYLOGGINGPP\n\n#define MEMORY_SIZE (64 * 1024 * 1024)\nint8_t memory_buffer[MEMORY_SIZE];\n\nstatic const double Render_time = 33; \/\/ roughly 30 fps\n\nstatic void configure_logging()\n{\n\tel::Configurations conf;\n\n\tconf.setToDefault();\n\tconf.set(el::Level::Global, el::ConfigurationType::Enabled, \"true\");\n\tconf.set(el::Level::Global, el::ConfigurationType::LogFileTruncate, \"true\");\n\tconf.set(el::Level::Global, el::ConfigurationType::ToStandardOutput, \"false\");\n\tconf.set(el::Level::Global, el::ConfigurationType::Format, \"%msg\");\n\tel::Loggers::reconfigureLogger(\"default\", conf);\n\n\t\/\/ set some options on the logger\n\tel::Loggers::addFlag(el::LoggingFlag::ImmediateFlush);\n\tel::Loggers::addFlag(el::LoggingFlag::NewLineForContainer);\n\tel::Loggers::addFlag(el::LoggingFlag::ColoredTerminalOutput);\n}\n\n\nstatic char *get_cmdline_option(char **start, char **end, const std::string &short_option, const std::string &long_option = \"\")\n{\n\tchar **iter = std::find(start, end, short_option);\n\tif (iter == end) {\n\t\titer = std::find(start, end, long_option);\n\t}\n\tif ((iter != end) && (iter++ != end) ) {\n\t\treturn *iter;\n\t}\n\n\treturn nullptr;\n}\n\nstatic bool cmdline_option_exists(char **start, char **end, const std::string &short_option, const std::string &long_option = \"\")\n{\n\tchar **iter = std::find(start, end, short_option);\n\tif (iter == end) {\n\t\titer = std::find(start, end, long_option);\n\t}\n\tif (iter == end) {\n\t\treturn false;\n\t}\n\treturn true;\n}\n\nbool dissemble_6502(const char *filename)\n{\n\treturn true;\n}\n\nint main(int argc, char* argv[])\n{\n\t\/\/ configure logging before anything else\n\tconfigure_logging();\n\n\tmemory mem(MEMORY_SIZE, memory_buffer);\n\tcpu_6502 cpu(mem);\n\tcpu.init();\n\n\tdebugger_init();\n\tdisk_init(mem);\n\n\t\/\/\/\/ get command line options\n\t\/\/const char *assembly_file = nullptr;\n\t\/\/const char *dissembly_file = nullptr;\n\t\/\/assembly_file = get_cmdline_option(argv, argv+argc, \"-a\", \"--assemble\");\n\n\t\/\/\/\/ let's test assembler\n\t\/\/if (assembly_file != nullptr) {\n\t\/\/\tassemble_6502(assembly_file);\n\t\/\/\treturn 0;\n\t\/\/}\n\n\t\/\/dissembly_file = get_cmdline_option(argv, argv+argc, \"-d\", \"--disassemble\");\n\t\/\/if (dissembly_file != nullptr) {\n\t\/\/\tdissemble_6502(dissembly_file);\n\t\/\/}\n\t\n\t\/\/FILE *fp = fopen(\"test.bin\", \"rb\");\n\t\/\/fseek(fp, 0, SEEK_END);\n\t\/\/uint32_t buffer_size = ftell(fp);\n\t\/\/fseek(fp, 0, SEEK_SET);\n\n\t\/\/\/\/ allocate the memory buffer\n\t\/\/uint8_t *buffer = new uint8_t[buffer_size];\n\t\/\/if (buffer == nullptr) {\n\t\/\/\tprintf(\"Unable to allocate %d bytes for source code file buffer\\n\", buffer_size);\n\t\/\/\tfclose(fp);\n\t\/\/\texit(-1);\n\t\/\/}\n\t\/\/fread(buffer, 1, buffer_size, fp);\n\t\/\/fclose(fp);\n\n\tuint16_t prog_start = 0x600;\n\tuint16_t load_addr = 0x0;\n\n\tconst char *prog_start_string = get_cmdline_option(argv, argv+argc, \"-p\", \"--pc\");\n\tif (prog_start_string != nullptr) {\n\t\tprog_start = (uint16_t)strtol(prog_start_string, nullptr, 16);\n\t}\n\n\tconst char *load_addr_string = get_cmdline_option(argv, argv+argc, \"-b\", \"--base\");\n\tif (load_addr_string != nullptr) {\n\t\tload_addr = (uint16_t)strtol(load_addr_string, nullptr, 16);\n\t}\n\n\tconst char *binary_file = nullptr;\n\tbinary_file = get_cmdline_option(argv, argv+argc, \"-b\", \"--binary\");\n\tif (binary_file != nullptr) {\n\t\tFILE *fp = fopen(binary_file, \"rb\");\n\t\tif (fp == nullptr) {\n\t\t\tprintf(\"Unable to open %s for reading: %d\\n\", binary_file, errno);\n\t\t\texit(-1);\n\t\t}\n\t\tfseek(fp, 0, SEEK_END);\n\t\tuint32_t buffer_size = ftell(fp);\n\t\tfseek(fp, 0, SEEK_SET);\n\n\t\t\/\/ allocate the memory buffer\n\t\tuint8_t *buffer = new uint8_t[buffer_size];\n\t\tif (buffer == nullptr) {\n\t\t\tprintf(\"Unable to allocate %d bytes for source code file buffer\\n\", buffer_size);\n\t\t\tfclose(fp);\n\t\t\texit(-1);\n\t\t}\n\t\tfread(buffer, 1, buffer_size, fp);\n\t\tfclose(fp);\n\t\tmem.load_memory(buffer, buffer_size, load_addr);\n\t\tcpu.set_pc(prog_start);\n\n\t\/\/ load up the ROMs\n\t} else {\n\t\tcpu.set_pc(mem[0xfffc] | mem[0xfffd] << 8);\n\n\t\t\/\/ see if there is disk imace\n\t\tconst char *disk_image_filename = get_cmdline_option(argv, argv+argc, \"-d\", \"--disk\"); \/\/ will always go to drive one for now\n\t\tif (disk_image_filename != nullptr) {\n\t\t\tdisk_insert(disk_image_filename, 1);\n\t\t}\n\t}\n\tvideo_init(mem);\n\tspeaker_init(mem);\n\tkeyboard_init();\n\n\tbool quit = false;\n\tuint32_t total_cycles = 0;\n\tdouble last_time = SDL_GetTicks();\n\tdouble processed_time = 0;\n\n\twhile (!quit) {\n\n\t\t\/\/ process debugger (before opcode processing so that we can break on\n\t\t\/\/ specific addresses properly\n\t\tdebugger_process(cpu, mem);\n\n\t\t\/\/ process the next opcode\n\t\tuint32_t cycles = cpu.process_opcode();\n\t\ttotal_cycles += cycles;\n\n\t\tif (total_cycles > 17030) {\n\t\t\t\/\/video_render_frame(mem);\n\t\t\ttotal_cycles -= 17030;\n\t\t}\n\n\t\t\/\/ determine whether to render or not. Calculate diff\n\t\t\/\/ between last frame.\n\t\tdouble cur_time = SDL_GetTicks();\n\t\tdouble diff_time = cur_time - last_time;\n\t\tlast_time = cur_time;\n\n\t\tbool should_render = false;\n\t\tprocessed_time += diff_time;\n\t\twhile (processed_time > Render_time) {\n\t\t\tshould_render = true;\n\t\t\tprocessed_time -= Render_time;\n\t\t}\n\n\t\tif (should_render == true) {\n SDL_Event evt;\n\n SDL_PollEvent(&evt);\n switch (evt.type) {\n case SDL_KEYDOWN:\n case SDL_KEYUP:\n keyboard_handle_event(evt);\n break;\n\n case SDL_WINDOWEVENT:\n if (evt.window.event == SDL_WINDOWEVENT_CLOSE) {\n quit = true;\n }\n break;\n }\n\t\t\tvideo_render_frame(mem);\n\t\t}\n\n\t}\n\n\tvideo_shutdown();\n\tkeyboard_shutdown();\n debugger_shutdown();\n\n\treturn 0;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 2008-2018 SLIBIO <https:\/\/github.com\/SLIBIO>\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n *\/\n\n#include \"slib\/ui\/mobile_app.h\"\n\n#include \"slib\/ui\/view.h\"\n#include \"slib\/ui\/resource.h\"\n#include \"slib\/ui\/animation.h\"\n\nnamespace slib\n{\n\n\tSLIB_DEFINE_OBJECT(MobileApp, UIApp)\n\n\tMobileApp::MobileApp()\n\t{\n\t\tSLIB_REFERABLE_CONSTRUCTOR\n\t\t\n\t\tRef<MobileMainWindow> window = new MobileMainWindow;\n\t\tsetMainWindow(window);\n\t\t\n\t\tm_contentView = window->getContentView();\n\t\t\n\t\tm_navigationController = new ViewPageNavigationController;\n\t\tm_navigationController->setWidthFilling(1, UIUpdateMode::Init);\n\t\tm_navigationController->setHeightFilling(1, UIUpdateMode::Init);\n\t\tm_navigationController->setOpaque(sl_true, UIUpdateMode::Init);\n\t\tm_navigationController->setBackgroundColor(Color::White);\n\t\tm_navigationController->setVisibility(Visibility::Hidden, UIUpdateMode::Init);\n\t\tm_contentView->addChild(m_navigationController, UIUpdateMode::Init);\n\n\t\tm_callbackOnChangeLocale = SLIB_FUNCTION_CLASS(MobileApp, dispatchChangeCurrentLocale, this);\n\t\tLocale::addOnChangeCurrentLocale(m_callbackOnChangeLocale);\n\t}\n\t\n\tMobileApp::~MobileApp()\n\t{\n\t\tLocale::removeOnChangeCurrentLocale(m_callbackOnChangeLocale);\n\t}\n\n\tRef<MobileApp> MobileApp::getApp()\n\t{\n\t\treturn CastRef<MobileApp>(Application::getApp());\n\t}\n\t\n\tRef<MobileMainWindow> MobileApp::getMainWindow()\n\t{\n\t\treturn CastRef<MobileMainWindow>(UIApp::getMainWindow());\n\t}\n\t\n\tsl_bool MobileApp::m_flagPaused = sl_false;\n\t\n\tsl_bool MobileApp::isPaused()\n\t{\n\t\treturn m_flagPaused;\n\t}\n\t\n\tRef<View> MobileApp::getRootView()\n\t{\n\t\tRef<Window> window = UIApp::getMainWindow();\n\t\tif (window.isNotNull()) {\n\t\t\treturn window->getContentView();\n\t\t}\n\t\treturn sl_null;\n\t}\n\t\n\tRef<View> MobileApp::getContentView()\n\t{\n\t\treturn m_contentView;\n\t}\n\t\n\tRef<ViewPageNavigationController> MobileApp::getNavigationController()\n\t{\n\t\treturn m_navigationController;\n\t}\n\t\n\tRef<View> MobileApp::getLoadingPage()\n\t{\n\t\treturn getStartupPage();\n\t}\n\n\tRef<View> MobileApp::getStartupPage()\n\t{\n\t\treturn sl_null;\n\t}\n\t\n\tvoid MobileApp::addViewToRoot(const Ref<View>& view)\n\t{\n\t\tRef<MobileMainWindow> window = getMainWindow();\n\t\tif (window.isNotNull()) {\n\t\t\twindow->addView(view);\n\t\t}\n\t}\n\t\n\tvoid MobileApp::addViewToContent(const Ref<View>& view)\n\t{\n\t\tRef<View> content = m_contentView;\n\t\tif (content.isNotNull()) {\n\t\t\tcontent->addChild(view);\n\t\t}\n\t}\n\t\n\tvoid MobileApp::openPage(const Ref<View>& page, const Transition& transition)\n\t{\n\t\tm_navigationController->push(page, transition);\n\t}\n\t\n\tvoid MobileApp::openPage(const Ref<View>& page)\n\t{\n\t\tm_navigationController->push(page);\n\t}\n\t\n\tvoid MobileApp::openHomePage(const Ref<View>& page, const Transition& transition)\n\t{\n\t\tm_navigationController->pushPageAfterPopAllPages(page, transition);\n\t}\n\t\n\tvoid MobileApp::openHomePage(const Ref<View>& page)\n\t{\n\t\tm_navigationController->pushPageAfterPopAllPages(page);\n\t}\n\t\n\tvoid MobileApp::closePage(const Ref<View>& page, const Transition& transition)\n\t{\n\t\tm_navigationController->pop(page, transition);\n\t}\n\t\n\tvoid MobileApp::closePage(const Ref<View>& page)\n\t{\n\t\tm_navigationController->pop(page);\n\t}\n\t\n\tvoid MobileApp::closePage(const Transition& transition)\n\t{\n\t\tm_navigationController->pop(transition);\n\t}\n\t\n\tvoid MobileApp::closePage()\n\t{\n\t\tm_navigationController->pop();\n\t}\n\t\n\tvoid MobileApp::popupPage(const Ref<ViewPage>& page, const Transition& transition, sl_bool flagFillParentBackground)\n\t{\n\t\tif (page.isNull()) {\n\t\t\treturn;\n\t\t}\n\t\tRef<View> content = m_contentView;\n\t\tif (content.isNotNull()) {\n\t\t\tpage->popup(content, transition, flagFillParentBackground);\n\t\t}\n\t}\n\t\n\tvoid MobileApp::popupPage(const Ref<ViewPage>& page, sl_bool flagFillParentBackground)\n\t{\n\t\tpopupPage(page, Transition(), flagFillParentBackground);\n\t}\n\t\n\tvoid MobileApp::closePopup(const Ref<ViewPage>& page, const Transition& transition)\n\t{\n\t\tif (page.isNull()) {\n\t\t\treturn;\n\t\t}\n\t\tListLocker< Ref<ViewPage> > popups(m_popupPages);\n\t\tif (popups.count > 0) {\n\t\t\tif (page == popups[popups.count-1]) {\n\t\t\t\tpage->close(transition);\n\t\t\t}\n\t\t}\n\t}\n\t\n\tvoid MobileApp::closePopup(const Ref<ViewPage>& page)\n\t{\n\t\tclosePopup(page, Transition());\n\t}\n\t\n\tvoid MobileApp::closePopup(const Transition& transition)\n\t{\n\t\tListLocker< Ref<ViewPage> > popups(m_popupPages);\n\t\tif (popups.count > 0) {\n\t\t\tRef<ViewPage> page = popups[popups.count-1];\n\t\t\tif (page.isNotNull()) {\n\t\t\t\tpage->close(transition);\n\t\t\t}\n\t\t}\n\t}\n\t\n\tvoid MobileApp::closePopup()\n\t{\n\t\tclosePopup(Transition());\n\t}\n\t\n\tvoid MobileApp::openStartupPage()\n\t{\n\t\tRef<View> page = getStartupPage();\n\t\tif (page.isNotNull()) {\n\t\t\topenHomePage(page, TransitionType::None);\n\t\t}\n\t}\n\t\n\tvoid MobileApp::dispatchStart()\n\t{\n\t\tUIApp::dispatchStart();\n#ifdef SLIB_PLATFORM_IS_DESKTOP\n\t\tRef<MobileMainWindow> window = getMainWindow();\n\t\tif (window.isNotNull()) {\n\t\t\twindow->forceCreate();\n\t\t}\n#endif\n\t}\n\t\n\tSLIB_DEFINE_EVENT_HANDLER(MobileApp, Pause)\n\n\tvoid MobileApp::dispatchPause()\n\t{\n\t\tSLIB_INVOKE_EVENT_HANDLER(Pause)\n\t\t\n\t\tRef<ViewPageNavigationController> controller = m_navigationController;\n\t\tif (controller.isNotNull()) {\n\t\t\tRef<View> page = controller->getCurrentPage();\n\t\t\tif (ViewPage* _page = CastInstance<ViewPage>(page.get())) {\n\t\t\t\t_page->dispatchPause();\n\t\t\t}\n\t\t}\n\t\tListLocker< Ref<ViewPage> > popups(m_popupPages);\n\t\tfor (sl_size i = 0; i < popups.count; i++) {\n\t\t\tRef<ViewPage> page = popups[i];\n\t\t\tif (page.isNotNull()) {\n\t\t\t\tpage->dispatchPause();\n\t\t\t}\n\t\t}\n\t}\n\t\n\tvoid MobileApp::dispatchPauseToApp()\n\t{\n\t\tm_flagPaused = sl_true;\n\t\tRef<MobileApp> app = getApp();\n\t\tif (app.isNotNull()) {\n\t\t\tapp->dispatchPause();\n\t\t}\n\t\t{\n\t\t\tRef<UIAnimationLoop> al = UIAnimationLoop::getInstance();\n\t\t\tif (al.isNotNull()) {\n\t\t\t\tal->pause();\n\t\t\t}\n\t\t}\n\t\t{\n\t\t\tRef<AnimationLoop> al = AnimationLoop::getDefault();\n\t\t\tif (al.isNotNull()) {\n\t\t\t\tal->pause();\n\t\t\t}\n\t\t}\n\t}\n\t\n\tSLIB_DEFINE_EVENT_HANDLER(MobileApp, Resume)\n\n\tvoid MobileApp::dispatchResume()\n\t{\n\t\tSLIB_INVOKE_EVENT_HANDLER(Resume)\n\t\t\n\t\tRef<ViewPageNavigationController> controller = m_navigationController;\n\t\tif (controller.isNotNull()) {\n\t\t\tRef<View> page = controller->getCurrentPage();\n\t\t\tif (ViewPage* _page = CastInstance<ViewPage>(page.get())) {\n\t\t\t\t_page->dispatchResume();\n\t\t\t}\n\t\t}\n\t\tListLocker< Ref<ViewPage> > popups(m_popupPages);\n\t\tfor (sl_size i = 0; i < popups.count; i++) {\n\t\t\tRef<ViewPage> page = popups[i];\n\t\t\tif (page.isNotNull()) {\n\t\t\t\tpage->dispatchResume();\n\t\t\t}\n\t\t}\n\t}\n\t\n\tvoid MobileApp::dispatchResumeToApp()\n\t{\n\t\tm_flagPaused = sl_false;\n\t\tRef<MobileApp> app = getApp();\n\t\tif (app.isNotNull()) {\n\t\t\tapp->dispatchResume();\n\t\t}\n\t\t{\n\t\t\tRef<UIAnimationLoop> al = UIAnimationLoop::getInstance();\n\t\t\tif (al.isNotNull()) {\n\t\t\t\tal->resume();\n\t\t\t}\n\t\t}\n\t\t{\n\t\t\tRef<AnimationLoop> al = AnimationLoop::getDefault();\n\t\t\tif (al.isNotNull()) {\n\t\t\t\tal->resume();\n\t\t\t}\n\t\t}\n\t}\n\t\n\tSLIB_DEFINE_EVENT_HANDLER(MobileApp, BackPressed, UIEvent* ev)\n\n\tvoid MobileApp::dispatchBackPressed(UIEvent* ev)\n\t{\n\t\tSLIB_INVOKE_EVENT_HANDLER(BackPressed, ev)\n\t\t\n\t\tif (ev->isPreventedDefault()) {\n\t\t\treturn;\n\t\t}\n\t\t{\n\t\t\tListLocker< Ref<ViewPage> > popups(m_popupPages);\n\t\t\tif (popups.count > 0) {\n\t\t\t\tRef<ViewPage> page = popups[popups.count-1];\n\t\t\t\tif (page.isNotNull()) {\n\t\t\t\t\tpage->dispatchBackPressed(ev);\n\t\t\t\t\tif (!(ev->isPreventedDefault())) {\n\t\t\t\t\t\tpage->close();\n\t\t\t\t\t\tev->preventDefault();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t\tRef<ViewPageNavigationController> controller = m_navigationController;\n\t\tif (controller.isNotNull()) {\n\t\t\tRef<View> _page = controller->getCurrentPage();\n\t\t\tif (ViewPage* page = CastInstance<ViewPage>(_page.get())) {\n\t\t\t\tpage->dispatchBackPressed(ev);\n\t\t\t\tif (!(ev->isPreventedDefault())) {\n\t\t\t\t\tif (controller->getPagesCount() > 1) {\n\t\t\t\t\t\tpage->close();\n\t\t\t\t\t\tev->preventDefault();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t\n\tsl_bool MobileApp::dispatchBackPressedToApp()\n\t{\n\t\tRef<MobileApp> app = getApp();\n\t\tif (app.isNotNull()) {\n\t\t\tRef<UIEvent> ev = UIEvent::create(UIAction::Unknown);\n\t\t\tif (ev.isNotNull()) {\n\t\t\t\tapp->dispatchBackPressed(ev.get());\n\t\t\t\tif (ev->isPreventedDefault()) {\n\t\t\t\t\treturn sl_false;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn sl_true;\n\t}\n\t\n\tSLIB_DEFINE_EVENT_HANDLER(MobileApp, CreateActivity)\n\n\tvoid MobileApp::dispatchCreateActivity()\n\t{\n\t\tRef<MobileMainWindow> window = getMainWindow();\n\t\tif (window.isNotNull()) {\n\t\t\twindow->forceCreate();\n\t\t}\n\t\t\n\t\tSLIB_INVOKE_EVENT_HANDLER(CreateActivity)\n\t}\n\t\n\tvoid MobileApp::dispatchCreateActivityToApp()\n\t{\n\t\tRef<MobileApp> app = getApp();\n\t\tif (app.isNotNull()) {\n\t\t\tapp->dispatchCreateActivity();\n\t\t}\n\t}\n\t\n\tSLIB_DEFINE_EVENT_HANDLER(MobileApp, DestroyActivity)\n\t\n\tvoid MobileApp::dispatchDestroyActivity()\n\t{\n\t\tSLIB_INVOKE_EVENT_HANDLER(DestroyActivity)\n\t}\n\t\n\tvoid MobileApp::dispatchDestroyActivityToApp()\n\t{\n\t\tRef<MobileApp> app = getApp();\n\t\tif (app.isNotNull()) {\n\t\t\tapp->dispatchDestroyActivity();\n\t\t}\n\t}\n\t\n\tSLIB_DEFINE_EVENT_HANDLER(MobileApp, Resize, sl_ui_len width, sl_ui_len height)\n\n\tvoid MobileApp::dispatchResize(sl_ui_len width, sl_ui_len height)\n\t{\n\t\tUIResource::updateDefaultScreenSize();\n\t\t\n\t\tif (m_navigationController->getPagesCount() == 0) {\n\t\t\tRef<View> page = getLoadingPage();\n\t\t\tif (page.isNotNull()) {\n\t\t\t\tm_navigationController->setVisibility(Visibility::Visible);\n\t\t\t\topenHomePage(page, TransitionType::None);\n\t\t\t}\n\t\t}\n\t\t\n\t\tSLIB_INVOKE_EVENT_HANDLER(Resize, width, height);\n\t}\n\t\n\tvoid MobileApp::dispatchResizeToApp(sl_ui_len width, sl_ui_len height)\n\t{\n\t\tRef<MobileApp> app = getApp();\n\t\tif (app.isNotNull()) {\n\t\t\tapp->dispatchResize(width, height);\n\t\t}\n\t}\n\t\n\tSLIB_DEFINE_EVENT_HANDLER(MobileApp, ChangeCurrentLocale)\n\n\tvoid MobileApp::dispatchChangeCurrentLocale()\n\t{\n\t\tif (m_navigationController->getPagesCount() > 0) {\n\t\t\topenStartupPage();\n\t\t}\n\t\t\n\t\tSLIB_INVOKE_EVENT_HANDLER(ChangeCurrentLocale)\n\t}\n\t\n\t\n\tSLIB_DEFINE_OBJECT(MobileMainWindow, Window)\n\t\n\tMobileMainWindow::MobileMainWindow()\n\t{\n\t\tSLIB_REFERABLE_CONSTRUCTOR;\n\t}\n\t\n\tMobileMainWindow::~MobileMainWindow()\n\t{\n\t}\n\n\tvoid MobileMainWindow::onResize(sl_ui_len width, sl_ui_len height)\n\t{\n\t\tMobileApp::dispatchResizeToApp(width, height);\n\t}\n\n}\n<commit_msg>ui\/MobileApp: improved popup page transition<commit_after>\/*\n * Copyright (c) 2008-2018 SLIBIO <https:\/\/github.com\/SLIBIO>\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n *\/\n\n#include \"slib\/ui\/mobile_app.h\"\n\n#include \"slib\/ui\/view.h\"\n#include \"slib\/ui\/resource.h\"\n#include \"slib\/ui\/animation.h\"\n\nnamespace slib\n{\n\n\tSLIB_DEFINE_OBJECT(MobileApp, UIApp)\n\n\tMobileApp::MobileApp()\n\t{\n\t\tSLIB_REFERABLE_CONSTRUCTOR\n\t\t\n\t\tRef<MobileMainWindow> window = new MobileMainWindow;\n\t\tsetMainWindow(window);\n\t\t\n\t\tm_contentView = window->getContentView();\n\t\t\n\t\tm_navigationController = new ViewPageNavigationController;\n\t\tm_navigationController->setWidthFilling(1, UIUpdateMode::Init);\n\t\tm_navigationController->setHeightFilling(1, UIUpdateMode::Init);\n\t\tm_navigationController->setOpaque(sl_true, UIUpdateMode::Init);\n\t\tm_navigationController->setBackgroundColor(Color::White);\n\t\tm_navigationController->setVisibility(Visibility::Hidden, UIUpdateMode::Init);\n\t\tm_contentView->addChild(m_navigationController, UIUpdateMode::Init);\n\n\t\tm_callbackOnChangeLocale = SLIB_FUNCTION_CLASS(MobileApp, dispatchChangeCurrentLocale, this);\n\t\tLocale::addOnChangeCurrentLocale(m_callbackOnChangeLocale);\n\t}\n\t\n\tMobileApp::~MobileApp()\n\t{\n\t\tLocale::removeOnChangeCurrentLocale(m_callbackOnChangeLocale);\n\t}\n\n\tRef<MobileApp> MobileApp::getApp()\n\t{\n\t\treturn CastRef<MobileApp>(Application::getApp());\n\t}\n\t\n\tRef<MobileMainWindow> MobileApp::getMainWindow()\n\t{\n\t\treturn CastRef<MobileMainWindow>(UIApp::getMainWindow());\n\t}\n\t\n\tsl_bool MobileApp::m_flagPaused = sl_false;\n\t\n\tsl_bool MobileApp::isPaused()\n\t{\n\t\treturn m_flagPaused;\n\t}\n\t\n\tRef<View> MobileApp::getRootView()\n\t{\n\t\tRef<Window> window = UIApp::getMainWindow();\n\t\tif (window.isNotNull()) {\n\t\t\treturn window->getContentView();\n\t\t}\n\t\treturn sl_null;\n\t}\n\t\n\tRef<View> MobileApp::getContentView()\n\t{\n\t\treturn m_contentView;\n\t}\n\t\n\tRef<ViewPageNavigationController> MobileApp::getNavigationController()\n\t{\n\t\treturn m_navigationController;\n\t}\n\t\n\tRef<View> MobileApp::getLoadingPage()\n\t{\n\t\treturn getStartupPage();\n\t}\n\n\tRef<View> MobileApp::getStartupPage()\n\t{\n\t\treturn sl_null;\n\t}\n\t\n\tvoid MobileApp::addViewToRoot(const Ref<View>& view)\n\t{\n\t\tRef<MobileMainWindow> window = getMainWindow();\n\t\tif (window.isNotNull()) {\n\t\t\twindow->addView(view);\n\t\t}\n\t}\n\t\n\tvoid MobileApp::addViewToContent(const Ref<View>& view)\n\t{\n\t\tRef<View> content = m_contentView;\n\t\tif (content.isNotNull()) {\n\t\t\tcontent->addChild(view);\n\t\t}\n\t}\n\t\n\tvoid MobileApp::openPage(const Ref<View>& page, const Transition& transition)\n\t{\n\t\tm_navigationController->push(page, transition);\n\t}\n\t\n\tvoid MobileApp::openPage(const Ref<View>& page)\n\t{\n\t\tm_navigationController->push(page);\n\t}\n\t\n\tvoid MobileApp::openHomePage(const Ref<View>& page, const Transition& transition)\n\t{\n\t\tm_navigationController->pushPageAfterPopAllPages(page, transition);\n\t}\n\t\n\tvoid MobileApp::openHomePage(const Ref<View>& page)\n\t{\n\t\tm_navigationController->pushPageAfterPopAllPages(page);\n\t}\n\t\n\tvoid MobileApp::closePage(const Ref<View>& page, const Transition& transition)\n\t{\n\t\tm_navigationController->pop(page, transition);\n\t}\n\t\n\tvoid MobileApp::closePage(const Ref<View>& page)\n\t{\n\t\tm_navigationController->pop(page);\n\t}\n\t\n\tvoid MobileApp::closePage(const Transition& transition)\n\t{\n\t\tm_navigationController->pop(transition);\n\t}\n\t\n\tvoid MobileApp::closePage()\n\t{\n\t\tm_navigationController->pop();\n\t}\n\t\n\tvoid MobileApp::popupPage(const Ref<ViewPage>& page, const Transition& transition, sl_bool flagFillParentBackground)\n\t{\n\t\tif (page.isNull()) {\n\t\t\treturn;\n\t\t}\n\t\tRef<View> content = m_contentView;\n\t\tif (content.isNotNull()) {\n\t\t\tpage->popup(content, transition, flagFillParentBackground);\n\t\t}\n\t}\n\t\n\tvoid MobileApp::popupPage(const Ref<ViewPage>& page, sl_bool flagFillParentBackground)\n\t{\n\t\tif (page.isNull()) {\n\t\t\treturn;\n\t\t}\n\t\tRef<View> content = m_contentView;\n\t\tif (content.isNotNull()) {\n\t\t\tpage->popup(content, flagFillParentBackground);\n\t\t}\n\t}\n\t\n\tvoid MobileApp::closePopup(const Ref<ViewPage>& page, const Transition& transition)\n\t{\n\t\tif (page.isNull()) {\n\t\t\treturn;\n\t\t}\n\t\tListLocker< Ref<ViewPage> > popups(m_popupPages);\n\t\tif (popups.count > 0) {\n\t\t\tif (page == popups[popups.count-1]) {\n\t\t\t\tpage->close(transition);\n\t\t\t}\n\t\t}\n\t}\n\t\n\tvoid MobileApp::closePopup(const Ref<ViewPage>& page)\n\t{\n\t\tif (page.isNull()) {\n\t\t\treturn;\n\t\t}\n\t\tListLocker< Ref<ViewPage> > popups(m_popupPages);\n\t\tif (popups.count > 0) {\n\t\t\tif (page == popups[popups.count-1]) {\n\t\t\t\tpage->close();\n\t\t\t}\n\t\t}\n\t}\n\t\n\tvoid MobileApp::closePopup(const Transition& transition)\n\t{\n\t\tListLocker< Ref<ViewPage> > popups(m_popupPages);\n\t\tif (popups.count > 0) {\n\t\t\tRef<ViewPage> page = popups[popups.count-1];\n\t\t\tif (page.isNotNull()) {\n\t\t\t\tpage->close(transition);\n\t\t\t}\n\t\t}\n\t}\n\t\n\tvoid MobileApp::closePopup()\n\t{\n\t\tListLocker< Ref<ViewPage> > popups(m_popupPages);\n\t\tif (popups.count > 0) {\n\t\t\tRef<ViewPage> page = popups[popups.count-1];\n\t\t\tif (page.isNotNull()) {\n\t\t\t\tpage->close();\n\t\t\t}\n\t\t}\n\t}\n\t\n\tvoid MobileApp::openStartupPage()\n\t{\n\t\tRef<View> page = getStartupPage();\n\t\tif (page.isNotNull()) {\n\t\t\topenHomePage(page, TransitionType::None);\n\t\t}\n\t}\n\t\n\tvoid MobileApp::dispatchStart()\n\t{\n\t\tUIApp::dispatchStart();\n#ifdef SLIB_PLATFORM_IS_DESKTOP\n\t\tRef<MobileMainWindow> window = getMainWindow();\n\t\tif (window.isNotNull()) {\n\t\t\twindow->forceCreate();\n\t\t}\n#endif\n\t}\n\t\n\tSLIB_DEFINE_EVENT_HANDLER(MobileApp, Pause)\n\n\tvoid MobileApp::dispatchPause()\n\t{\n\t\tSLIB_INVOKE_EVENT_HANDLER(Pause)\n\t\t\n\t\tRef<ViewPageNavigationController> controller = m_navigationController;\n\t\tif (controller.isNotNull()) {\n\t\t\tRef<View> page = controller->getCurrentPage();\n\t\t\tif (ViewPage* _page = CastInstance<ViewPage>(page.get())) {\n\t\t\t\t_page->dispatchPause();\n\t\t\t}\n\t\t}\n\t\tListLocker< Ref<ViewPage> > popups(m_popupPages);\n\t\tfor (sl_size i = 0; i < popups.count; i++) {\n\t\t\tRef<ViewPage> page = popups[i];\n\t\t\tif (page.isNotNull()) {\n\t\t\t\tpage->dispatchPause();\n\t\t\t}\n\t\t}\n\t}\n\t\n\tvoid MobileApp::dispatchPauseToApp()\n\t{\n\t\tm_flagPaused = sl_true;\n\t\tRef<MobileApp> app = getApp();\n\t\tif (app.isNotNull()) {\n\t\t\tapp->dispatchPause();\n\t\t}\n\t\t{\n\t\t\tRef<UIAnimationLoop> al = UIAnimationLoop::getInstance();\n\t\t\tif (al.isNotNull()) {\n\t\t\t\tal->pause();\n\t\t\t}\n\t\t}\n\t\t{\n\t\t\tRef<AnimationLoop> al = AnimationLoop::getDefault();\n\t\t\tif (al.isNotNull()) {\n\t\t\t\tal->pause();\n\t\t\t}\n\t\t}\n\t}\n\t\n\tSLIB_DEFINE_EVENT_HANDLER(MobileApp, Resume)\n\n\tvoid MobileApp::dispatchResume()\n\t{\n\t\tSLIB_INVOKE_EVENT_HANDLER(Resume)\n\t\t\n\t\tRef<ViewPageNavigationController> controller = m_navigationController;\n\t\tif (controller.isNotNull()) {\n\t\t\tRef<View> page = controller->getCurrentPage();\n\t\t\tif (ViewPage* _page = CastInstance<ViewPage>(page.get())) {\n\t\t\t\t_page->dispatchResume();\n\t\t\t}\n\t\t}\n\t\tListLocker< Ref<ViewPage> > popups(m_popupPages);\n\t\tfor (sl_size i = 0; i < popups.count; i++) {\n\t\t\tRef<ViewPage> page = popups[i];\n\t\t\tif (page.isNotNull()) {\n\t\t\t\tpage->dispatchResume();\n\t\t\t}\n\t\t}\n\t}\n\t\n\tvoid MobileApp::dispatchResumeToApp()\n\t{\n\t\tm_flagPaused = sl_false;\n\t\tRef<MobileApp> app = getApp();\n\t\tif (app.isNotNull()) {\n\t\t\tapp->dispatchResume();\n\t\t}\n\t\t{\n\t\t\tRef<UIAnimationLoop> al = UIAnimationLoop::getInstance();\n\t\t\tif (al.isNotNull()) {\n\t\t\t\tal->resume();\n\t\t\t}\n\t\t}\n\t\t{\n\t\t\tRef<AnimationLoop> al = AnimationLoop::getDefault();\n\t\t\tif (al.isNotNull()) {\n\t\t\t\tal->resume();\n\t\t\t}\n\t\t}\n\t}\n\t\n\tSLIB_DEFINE_EVENT_HANDLER(MobileApp, BackPressed, UIEvent* ev)\n\n\tvoid MobileApp::dispatchBackPressed(UIEvent* ev)\n\t{\n\t\tSLIB_INVOKE_EVENT_HANDLER(BackPressed, ev)\n\t\t\n\t\tif (ev->isPreventedDefault()) {\n\t\t\treturn;\n\t\t}\n\t\t{\n\t\t\tListLocker< Ref<ViewPage> > popups(m_popupPages);\n\t\t\tif (popups.count > 0) {\n\t\t\t\tRef<ViewPage> page = popups[popups.count-1];\n\t\t\t\tif (page.isNotNull()) {\n\t\t\t\t\tpage->dispatchBackPressed(ev);\n\t\t\t\t\tif (!(ev->isPreventedDefault())) {\n\t\t\t\t\t\tpage->close();\n\t\t\t\t\t\tev->preventDefault();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t\tRef<ViewPageNavigationController> controller = m_navigationController;\n\t\tif (controller.isNotNull()) {\n\t\t\tRef<View> _page = controller->getCurrentPage();\n\t\t\tif (ViewPage* page = CastInstance<ViewPage>(_page.get())) {\n\t\t\t\tpage->dispatchBackPressed(ev);\n\t\t\t\tif (!(ev->isPreventedDefault())) {\n\t\t\t\t\tif (controller->getPagesCount() > 1) {\n\t\t\t\t\t\tpage->close();\n\t\t\t\t\t\tev->preventDefault();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t\n\tsl_bool MobileApp::dispatchBackPressedToApp()\n\t{\n\t\tRef<MobileApp> app = getApp();\n\t\tif (app.isNotNull()) {\n\t\t\tRef<UIEvent> ev = UIEvent::create(UIAction::Unknown);\n\t\t\tif (ev.isNotNull()) {\n\t\t\t\tapp->dispatchBackPressed(ev.get());\n\t\t\t\tif (ev->isPreventedDefault()) {\n\t\t\t\t\treturn sl_false;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn sl_true;\n\t}\n\t\n\tSLIB_DEFINE_EVENT_HANDLER(MobileApp, CreateActivity)\n\n\tvoid MobileApp::dispatchCreateActivity()\n\t{\n\t\tRef<MobileMainWindow> window = getMainWindow();\n\t\tif (window.isNotNull()) {\n\t\t\twindow->forceCreate();\n\t\t}\n\t\t\n\t\tSLIB_INVOKE_EVENT_HANDLER(CreateActivity)\n\t}\n\t\n\tvoid MobileApp::dispatchCreateActivityToApp()\n\t{\n\t\tRef<MobileApp> app = getApp();\n\t\tif (app.isNotNull()) {\n\t\t\tapp->dispatchCreateActivity();\n\t\t}\n\t}\n\t\n\tSLIB_DEFINE_EVENT_HANDLER(MobileApp, DestroyActivity)\n\t\n\tvoid MobileApp::dispatchDestroyActivity()\n\t{\n\t\tSLIB_INVOKE_EVENT_HANDLER(DestroyActivity)\n\t}\n\t\n\tvoid MobileApp::dispatchDestroyActivityToApp()\n\t{\n\t\tRef<MobileApp> app = getApp();\n\t\tif (app.isNotNull()) {\n\t\t\tapp->dispatchDestroyActivity();\n\t\t}\n\t}\n\t\n\tSLIB_DEFINE_EVENT_HANDLER(MobileApp, Resize, sl_ui_len width, sl_ui_len height)\n\n\tvoid MobileApp::dispatchResize(sl_ui_len width, sl_ui_len height)\n\t{\n\t\tUIResource::updateDefaultScreenSize();\n\t\t\n\t\tif (m_navigationController->getPagesCount() == 0) {\n\t\t\tRef<View> page = getLoadingPage();\n\t\t\tif (page.isNotNull()) {\n\t\t\t\tm_navigationController->setVisibility(Visibility::Visible);\n\t\t\t\topenHomePage(page, TransitionType::None);\n\t\t\t}\n\t\t}\n\t\t\n\t\tSLIB_INVOKE_EVENT_HANDLER(Resize, width, height);\n\t}\n\t\n\tvoid MobileApp::dispatchResizeToApp(sl_ui_len width, sl_ui_len height)\n\t{\n\t\tRef<MobileApp> app = getApp();\n\t\tif (app.isNotNull()) {\n\t\t\tapp->dispatchResize(width, height);\n\t\t}\n\t}\n\t\n\tSLIB_DEFINE_EVENT_HANDLER(MobileApp, ChangeCurrentLocale)\n\n\tvoid MobileApp::dispatchChangeCurrentLocale()\n\t{\n\t\tif (m_navigationController->getPagesCount() > 0) {\n\t\t\topenStartupPage();\n\t\t}\n\t\t\n\t\tSLIB_INVOKE_EVENT_HANDLER(ChangeCurrentLocale)\n\t}\n\t\n\t\n\tSLIB_DEFINE_OBJECT(MobileMainWindow, Window)\n\t\n\tMobileMainWindow::MobileMainWindow()\n\t{\n\t\tSLIB_REFERABLE_CONSTRUCTOR;\n\t}\n\t\n\tMobileMainWindow::~MobileMainWindow()\n\t{\n\t}\n\n\tvoid MobileMainWindow::onResize(sl_ui_len width, sl_ui_len height)\n\t{\n\t\tMobileApp::dispatchResizeToApp(width, height);\n\t}\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2009-2012 The Bitcoin developers\n\/\/ Distributed under the MIT\/X11 software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include <boost\/assign\/list_of.hpp> \/\/ for 'map_list_of()'\n#include <boost\/foreach.hpp>\n\n#include \"checkpoints.h\"\n\n#include \"main.h\"\n#include \"uint256.h\"\n\nnamespace Checkpoints\n{\n typedef std::map<int, uint256> MapCheckpoints;\n\n \/\/ How many times we expect transactions after the last checkpoint to\n \/\/ be slower. This number is a compromise, as it can't be accurate for\n \/\/ every system. When reindexing from a fast disk with a slow CPU, it\n \/\/ can be up to 20, while when downloading from a slow network with a\n \/\/ fast multicore CPU, it won't be much higher than 1.\n static const double fSigcheckVerificationFactor = 5.0;\n\n struct CCheckpointData {\n const MapCheckpoints *mapCheckpoints;\n int64 nTimeLastCheckpoint;\n int64 nTransactionsLastCheckpoint;\n double fTransactionsPerDay;\n };\n\n const std::string CSyncCheckpoint::strMasterPubKey = 04d95f5e7f4129baa8e20cc3d40ed04abd63c951e384df133cac68e97ff748533136567e3d838221f3676bcc7000d557d1b777c05472d190b05bf7ba4fd310d32e\n bool fEnabled = true;\n\n \/\/ What makes a good checkpoint block?\n \/\/ + Is surrounded by blocks with reasonable timestamps\n \/\/ (no blocks before with a timestamp after, none after with\n \/\/ timestamp before)\n \/\/ + Contains no strange transactions\n static MapCheckpoints mapCheckpoints =\n boost::assign::map_list_of\n ( 0, uint256(\"0x000001328ca4babaa49f1da4ad93486dc3cac63b2ceec532cba19ad6fc475dc4\"))\n (1039000, uint256(\"0x00000000000447876e13eaec573a52101f39292ca2a83b890a4360aa4282e439\"))\n ;\n static const CCheckpointData data = {\n &mapCheckpoints,\n 1446294715, \/\/ * UNIX timestamp of last checkpoint block\n 1131610, \/\/ * total number of transactions between genesis and last checkpoint\n \/\/ (the tx=... number in the SetBestChain debug.log lines)\n 2880 \/\/ * estimated number of transactions per day after checkpoint\n };\n\n static MapCheckpoints mapCheckpointsTestnet =\n boost::assign::map_list_of\n ( 0, uint256(\"0x0000017ce2a79c8bddafbbe47c004aa92b20678c354b34085f62b762084b9788\"))\n ;\n static const CCheckpointData dataTestnet = {\n &mapCheckpointsTestnet,\n 1392876393,\n 0,\n 2880\n };\n\n const CCheckpointData &Checkpoints() {\n if (TestNet())\n return dataTestnet;\n else\n return data;\n }\n\n bool CheckBlock(int nHeight, const uint256& hash)\n {\n if (!fEnabled)\n return true;\n\n const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints;\n\n MapCheckpoints::const_iterator i = checkpoints.find(nHeight);\n if (i == checkpoints.end()) return true;\n return hash == i->second;\n }\n\n \/\/ Guess how far we are in the verification process at the given block index\n double GuessVerificationProgress(CBlockIndex *pindex) {\n if (pindex==NULL)\n return 0.0;\n\n int64 nNow = time(NULL);\n\n double fWorkBefore = 0.0; \/\/ Amount of work done before pindex\n double fWorkAfter = 0.0; \/\/ Amount of work left after pindex (estimated)\n \/\/ Work is defined as: 1.0 per transaction before the last checkoint, and\n \/\/ fSigcheckVerificationFactor per transaction after.\n\n const CCheckpointData &data = Checkpoints();\n\n if (pindex->nChainTx <= data.nTransactionsLastCheckpoint) {\n double nCheapBefore = pindex->nChainTx;\n double nCheapAfter = data.nTransactionsLastCheckpoint - pindex->nChainTx;\n double nExpensiveAfter = (nNow - data.nTimeLastCheckpoint)\/86400.0*data.fTransactionsPerDay;\n fWorkBefore = nCheapBefore;\n fWorkAfter = nCheapAfter + nExpensiveAfter*fSigcheckVerificationFactor;\n } else {\n double nCheapBefore = data.nTransactionsLastCheckpoint;\n double nExpensiveBefore = pindex->nChainTx - data.nTransactionsLastCheckpoint;\n double nExpensiveAfter = (nNow - pindex->nTime)\/86400.0*data.fTransactionsPerDay;\n fWorkBefore = nCheapBefore + nExpensiveBefore*fSigcheckVerificationFactor;\n fWorkAfter = nExpensiveAfter*fSigcheckVerificationFactor;\n }\n\n return fWorkBefore \/ (fWorkBefore + fWorkAfter);\n }\n\n int GetTotalBlocksEstimate()\n {\n if (!fEnabled)\n return 0;\n\n const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints;\n\n return checkpoints.rbegin()->first;\n }\n\n CBlockIndex* GetLastCheckpoint(const std::map<uint256, CBlockIndex*>& mapBlockIndex)\n {\n if (!fEnabled)\n return NULL;\n\n const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints;\n\n BOOST_REVERSE_FOREACH(const MapCheckpoints::value_type& i, checkpoints)\n {\n const uint256& hash = i.second;\n std::map<uint256, CBlockIndex*>::const_iterator t = mapBlockIndex.find(hash);\n if (t != mapBlockIndex.end())\n return t->second;\n }\n return NULL;\n }\n}\n<commit_msg>Update checkpoints.cpp<commit_after>\/\/ Copyright (c) 2009-2012 The Bitcoin developers\n\/\/ Distributed under the MIT\/X11 software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include <boost\/assign\/list_of.hpp> \/\/ for 'map_list_of()'\n#include <boost\/foreach.hpp>\n\n#include \"checkpoints.h\"\n\n#include \"main.h\"\n#include \"uint256.h\"\n\nnamespace Checkpoints\n{\n typedef std::map<int, uint256> MapCheckpoints;\n\n \/\/ How many times we expect transactions after the last checkpoint to\n \/\/ be slower. This number is a compromise, as it can't be accurate for\n \/\/ every system. When reindexing from a fast disk with a slow CPU, it\n \/\/ can be up to 20, while when downloading from a slow network with a\n \/\/ fast multicore CPU, it won't be much higher than 1.\n static const double fSigcheckVerificationFactor = 5.0;\n\n struct CCheckpointData {\n const MapCheckpoints *mapCheckpoints;\n int64 nTimeLastCheckpoint;\n int64 nTransactionsLastCheckpoint;\n double fTransactionsPerDay;\n };\n\n const std::string CSyncCheckpoint::strMasterPubKey = 04d95f5e7f4129baa8e20cc3d40ed04abd63c951e384df133cac68e97ff748533136567e3d838221f3676bcc7000d557d1b777c05472d190b05bf7ba4fd310d32e\n bool fEnabled = true;\n\n \/\/ What makes a good checkpoint block?\n \/\/ + Is surrounded by blocks with reasonable timestamps\n \/\/ (no blocks before with a timestamp after, none after with\n \/\/ timestamp before)\n \/\/ + Contains no strange transactions\n static MapCheckpoints mapCheckpoints =\n boost::assign::map_list_of\n ( 0, uint256(\"0x000001328ca4babaa49f1da4ad93486dc3cac63b2ceec532cba19ad6fc475dc4\"))\n (1039000, uint256(\"0x00000000000447876e13eaec573a52101f39292ca2a83b890a4360aa4282e439\"))\n (1096791, uint256(\"0x00000000000139713d7b94d5c028eba6bff83bf845025229b4aa1ac965030800\"))\n ;\n static const CCheckpointData data = {\n &mapCheckpoints,\n 1446294715, \/\/ * UNIX timestamp of last checkpoint block\n 1131610, \/\/ * total number of transactions between genesis and last checkpoint\n \/\/ (the tx=... number in the SetBestChain debug.log lines)\n 2880 \/\/ * estimated number of transactions per day after checkpoint\n };\n\n static MapCheckpoints mapCheckpointsTestnet =\n boost::assign::map_list_of\n ( 0, uint256(\"0x0000017ce2a79c8bddafbbe47c004aa92b20678c354b34085f62b762084b9788\"))\n ;\n static const CCheckpointData dataTestnet = {\n &mapCheckpointsTestnet,\n 1392876393,\n 0,\n 2880\n };\n\n const CCheckpointData &Checkpoints() {\n if (TestNet())\n return dataTestnet;\n else\n return data;\n }\n\n bool CheckBlock(int nHeight, const uint256& hash)\n {\n if (!fEnabled)\n return true;\n\n const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints;\n\n MapCheckpoints::const_iterator i = checkpoints.find(nHeight);\n if (i == checkpoints.end()) return true;\n return hash == i->second;\n }\n\n \/\/ Guess how far we are in the verification process at the given block index\n double GuessVerificationProgress(CBlockIndex *pindex) {\n if (pindex==NULL)\n return 0.0;\n\n int64 nNow = time(NULL);\n\n double fWorkBefore = 0.0; \/\/ Amount of work done before pindex\n double fWorkAfter = 0.0; \/\/ Amount of work left after pindex (estimated)\n \/\/ Work is defined as: 1.0 per transaction before the last checkoint, and\n \/\/ fSigcheckVerificationFactor per transaction after.\n\n const CCheckpointData &data = Checkpoints();\n\n if (pindex->nChainTx <= data.nTransactionsLastCheckpoint) {\n double nCheapBefore = pindex->nChainTx;\n double nCheapAfter = data.nTransactionsLastCheckpoint - pindex->nChainTx;\n double nExpensiveAfter = (nNow - data.nTimeLastCheckpoint)\/86400.0*data.fTransactionsPerDay;\n fWorkBefore = nCheapBefore;\n fWorkAfter = nCheapAfter + nExpensiveAfter*fSigcheckVerificationFactor;\n } else {\n double nCheapBefore = data.nTransactionsLastCheckpoint;\n double nExpensiveBefore = pindex->nChainTx - data.nTransactionsLastCheckpoint;\n double nExpensiveAfter = (nNow - pindex->nTime)\/86400.0*data.fTransactionsPerDay;\n fWorkBefore = nCheapBefore + nExpensiveBefore*fSigcheckVerificationFactor;\n fWorkAfter = nExpensiveAfter*fSigcheckVerificationFactor;\n }\n\n return fWorkBefore \/ (fWorkBefore + fWorkAfter);\n }\n\n int GetTotalBlocksEstimate()\n {\n if (!fEnabled)\n return 0;\n\n const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints;\n\n return checkpoints.rbegin()->first;\n }\n\n CBlockIndex* GetLastCheckpoint(const std::map<uint256, CBlockIndex*>& mapBlockIndex)\n {\n if (!fEnabled)\n return NULL;\n\n const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints;\n\n BOOST_REVERSE_FOREACH(const MapCheckpoints::value_type& i, checkpoints)\n {\n const uint256& hash = i.second;\n std::map<uint256, CBlockIndex*>::const_iterator t = mapBlockIndex.find(hash);\n if (t != mapBlockIndex.end())\n return t->second;\n }\n return NULL;\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2011 The Bitcoin developers\n\/\/ Copyright (c) 2011-2012 The PPCoin developers\n\/\/ Distributed under the MIT\/X11 software license, see the accompanying\n\/\/ file license.txt or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include <boost\/assign\/list_of.hpp> \/\/ for 'map_list_of()'\n#include <boost\/foreach.hpp>\n\n#include \"headers.h\"\n#include \"checkpoints.h\"\n\nnamespace Checkpoints\n{\n typedef std::map<int, uint256> MapCheckpoints; \/\/ hardened checkpoints\n\n \/\/\n \/\/ What makes a good checkpoint block?\n \/\/ + Is surrounded by blocks with reasonable timestamps\n \/\/ (no blocks before with a timestamp after, none after with\n \/\/ timestamp before)\n \/\/ + Contains no strange transactions\n \/\/\n static MapCheckpoints mapCheckpoints =\n boost::assign::map_list_of\n ( 0, hashGenesisBlock )\n ; \/\/ ppcoin: no checkpoint yet; to be created in future releases\n\n bool CheckHardened(int nHeight, const uint256& hash)\n {\n if (fTestNet) return true; \/\/ Testnet has no checkpoints\n\n MapCheckpoints::const_iterator i = mapCheckpoints.find(nHeight);\n if (i == mapCheckpoints.end()) return true;\n return hash == i->second;\n }\n\n int GetTotalBlocksEstimate()\n {\n if (fTestNet) return 0;\n\n return mapCheckpoints.rbegin()->first;\n }\n\n CBlockIndex* GetLastCheckpoint(const std::map<uint256, CBlockIndex*>& mapBlockIndex)\n {\n if (fTestNet) return NULL;\n\n int64 nResult;\n BOOST_REVERSE_FOREACH(const MapCheckpoints::value_type& i, mapCheckpoints)\n {\n const uint256& hash = i.second;\n std::map<uint256, CBlockIndex*>::const_iterator t = mapBlockIndex.find(hash);\n if (t != mapBlockIndex.end())\n return t->second;\n }\n return NULL;\n }\n\n \/\/ ppcoin: synchronized checkpoint (centrally broadcasted)\n uint256 hashSyncCheckpoint;\n CSyncCheckpoint checkpointMessage;\n CSyncCheckpoint checkpointMessagePending;\n CCriticalSection cs_hashSyncCheckpoint;\n\n \/\/ ppcoin: only descendant of current sync-checkpoint is allowed\n bool ValidateSyncCheckpoint(uint256 hashCheckpoint)\n {\n if (!mapBlockIndex.count(hashSyncCheckpoint))\n return error(\"ValidateSyncCheckpoint: block index missing for current sync-checkpoint %s\", hashSyncCheckpoint.ToString().c_str());\n if (!mapBlockIndex.count(hashCheckpoint))\n return error(\"ValidateSyncCheckpoint: block index missing for received sync-checkpoint %s\", hashCheckpoint.ToString().c_str());\n\n CBlockIndex* pindexSyncCheckpoint = mapBlockIndex[hashSyncCheckpoint];\n CBlockIndex* pindexCheckpointRecv = mapBlockIndex[hashCheckpoint];\n if (pindexCheckpointRecv->nHeight <= pindexSyncCheckpoint->nHeight)\n return false; \/\/ this is an older checkpoint, ignore\n\n CBlockIndex* pindex = pindexCheckpointRecv;\n while (pindex->nHeight > pindexSyncCheckpoint->nHeight)\n if (!(pindex = pindex->pprev))\n return error(\"ValidateSyncCheckpoint: pprev null - block index structure failure\");\n if (pindex->GetBlockHash() != hashSyncCheckpoint)\n return error(\"ValidateSyncCheckpoint: new sync-checkpoint %s is not a descendant of current sync-checkpoint %s\", hashCheckpoint.ToString().c_str(), hashSyncCheckpoint.ToString().c_str());\n return true;\n }\n\n bool AcceptPendingSyncCheckpoint()\n {\n bool fAccepted = false;\n uint256 hashCheckpoint = 0;\n CTxDB txdb;\n\n CRITICAL_BLOCK(cs_hashSyncCheckpoint)\n {\n if ((!checkpointMessagePending.IsNull()) && mapBlockIndex.count(checkpointMessagePending.hashCheckpoint))\n {\n if (!ValidateSyncCheckpoint(checkpointMessagePending.hashCheckpoint))\n {\n checkpointMessagePending.SetNull();\n return false;\n }\n\n txdb.TxnBegin();\n if (!txdb.WriteSyncCheckpoint(checkpointMessagePending.hashCheckpoint))\n {\n txdb.TxnAbort();\n return error(\"AcceptPendingSyncCheckpoint() : failed to write to db sync checkpoint %s\\n\", checkpointMessagePending.hashCheckpoint.ToString().c_str());\n }\n if (!txdb.TxnCommit())\n return error(\"AcceptPendingSyncCheckpoint() : failed to commit to db sync checkpoint %s\\n\", checkpointMessagePending.hashCheckpoint.ToString().c_str());\n\n hashSyncCheckpoint = checkpointMessagePending.hashCheckpoint;\n checkpointMessage = checkpointMessagePending;\n checkpointMessagePending.SetNull();\n printf(\"AcceptPendingSyncCheckpoint : sync-checkpoint at %s\\n\", hashSyncCheckpoint.ToString().c_str());\n fAccepted = true;\n hashCheckpoint = hashSyncCheckpoint;\n }\n }\n\n if (fAccepted)\n {\n CBlockIndex* pindexCheckpoint = mapBlockIndex[hashCheckpoint];\n if (!pindexCheckpoint->IsInMainChain())\n {\n txdb.TxnBegin();\n if (!Reorganize(txdb, pindexCheckpoint))\n {\n txdb.TxnAbort();\n return error(\"ProcessSyncCheckpoint: Reorganize failed for sync checkpoint %s\", hashCheckpoint.ToString().c_str());\n }\n }\n }\n txdb.Close();\n\n \/\/ relay the checkpoint\n CRITICAL_BLOCK(cs_hashSyncCheckpoint)\n BOOST_FOREACH(CNode* pnode, vNodes)\n checkpointMessage.RelayTo(pnode);\n\n return fAccepted;\n }\n\n uint256 AutoSelectSyncCheckpoint()\n {\n \/\/ select block roughly 8 hours ago\n CBlockIndex *pindex = mapBlockIndex[hashSyncCheckpoint];\n while (pindex->pnext && pindex->pnext->GetBlockTime() + AUTO_CHECKPOINT_MIN_SPAN <= GetAdjustedTime())\n pindex = pindex->pnext;\n return pindex->GetBlockHash();\n }\n\n \/\/ Check against synchronized checkpoint\n bool CheckSync(const uint256& hashBlock, const CBlockIndex* pindexPrev)\n {\n if (fTestNet) return true; \/\/ Testnet has no checkpoints\n int nHeight = pindexPrev->nHeight + 1;\n\n CRITICAL_BLOCK(cs_hashSyncCheckpoint)\n {\n \/\/ sync-checkpoint should always be accepted block\n assert(mapBlockIndex.count(hashSyncCheckpoint));\n const CBlockIndex* pindexSync = mapBlockIndex[hashSyncCheckpoint];\n\n if (nHeight > pindexSync->nHeight)\n {\n \/\/ trace back to same height as sync-checkpoint\n const CBlockIndex* pindex = pindexPrev;\n while (pindex->nHeight > pindexSync->nHeight)\n if (!(pindex = pindex->pprev))\n return error(\"CheckSync: pprev null - block index structure failure\");\n if (pindex->nHeight < pindexSync->nHeight || pindex->GetBlockHash() != hashSyncCheckpoint)\n return false; \/\/ only descendant of sync-checkpoint can pass check\n }\n if (nHeight == pindexSync->nHeight && hashBlock != hashSyncCheckpoint)\n return false; \/\/ same height with sync-checkpoint\n if (nHeight < pindexSync->nHeight && !mapBlockIndex.count(hashBlock))\n return false; \/\/ lower height than sync-checkpoint\n }\n return true;\n }\n\n \/\/ ppcoin: automatic checkpoint (represented by height of checkpoint)\n int nAutoCheckpoint = 0;\n int nBranchPoint = 0; \/\/ branch point to alternative branch\n\n \/\/ ppcoin: check automatic checkpoint\n \/\/ To pass the check:\n \/\/ - All ancestors (including the block itself) have block index already\n \/\/ - The immediate ancestor in main chain must not have height less than\n \/\/ checkpoint height\n bool CheckAuto(const CBlockIndex *pindex)\n {\n while (pindex)\n {\n if (pindex->IsInMainChain())\n {\n if (pindex->nHeight >= nAutoCheckpoint)\n return true;\n else\n {\n nBranchPoint = pindex->nHeight;\n return error(\"Checkpoints: new block on alternative branch at height=%d before auto checkpoint at height=%d\", pindex->nHeight, nAutoCheckpoint);\n }\n }\n else\n pindex = pindex->pprev;\n }\n return error(\"Checkpoints: failed to find any ancestor on main chain for the new block - internal error\");\n }\n\n \/\/ ppcoin: get next chain checkpoint\n int GetNextChainCheckpoint(const CBlockIndex *pindexLast)\n {\n CBigNum bnTarget;\n CBigNum bnTargetMax = 0; \/\/ max target of all blocks since checkpoint\n CBigNum bnTargetMin = 0; \/\/ min target of all candidate checkpoints\n int nMinTargetHeight = 0; \/\/ min target height of candidate checkpoints\n int nCheckpointMin = 0; \/\/ minimum candidate checkpoint\n int nCheckpointMax = 0; \/\/ maximum candidate checkpoint\n int nDepth = pindexLast->nHeight - pindexLast->nCheckpoint;\n const CBlockIndex *pindex = pindexLast;\n while (nDepth >= 0 && pindex)\n {\n bnTarget.SetCompact(pindex->nBits);\n if (bnTarget > bnTargetMax)\n bnTargetMax = bnTarget;\n if (nCheckpointMax > 0 && bnTarget < bnTargetMin)\n {\n bnTargetMin = bnTarget;\n nMinTargetHeight = pindex->nHeight;\n }\n if (nCheckpointMax == 0 && pindexLast->GetBlockTime() - pindex->GetBlockTime() > AUTO_CHECKPOINT_MIN_SPAN)\n {\n nCheckpointMax = pindex->nHeight;\n bnTargetMin.SetCompact(pindex->nBits);\n nMinTargetHeight = pindex->nHeight;\n }\n if (pindexLast->GetBlockTime() - pindex->GetBlockTime() < AUTO_CHECKPOINT_MAX_SPAN)\n nCheckpointMin = pindex->nHeight;\n pindex = pindex->pprev;\n nDepth--;\n }\n\n assert (nDepth == -1); \/\/ arrive at chain checkpoint now\n\n printf(\"Checkpoints: min=%d max=%d tminheight=%d tmin=0x%08x tmax=0x%08x\\n\",\n nCheckpointMin, nCheckpointMax, nMinTargetHeight,\n bnTargetMin.GetCompact(), bnTargetMax.GetCompact());\n if (nCheckpointMax == 0) \/\/ checkpoint stays if max candidate not found\n return pindexLast->nCheckpoint;\n\n if (bnTargetMin * 100 > bnTargetMax * 90)\n return nCheckpointMax;\n if (bnTarget * 100 > bnTargetMax * 90)\n return nMinTargetHeight;\n else\n return nCheckpointMin;\n }\n\n \/\/ ppcoin: get next auto checkpoint from the new chain checkpoint\n int GetNextAutoCheckpoint(int nCheckpoint)\n {\n return (std::max(nAutoCheckpoint, nCheckpoint));\n }\n\n \/\/ ppcoin: advance to next automatic checkpoint\n void AdvanceAutoCheckpoint(int nCheckpoint)\n {\n nAutoCheckpoint = GetNextAutoCheckpoint(nCheckpoint);\n printf(\"Checkpoints: auto checkpoint now at height=%d\\n\", nAutoCheckpoint);\n }\n\n \/\/ ppcoin: reset auto checkpoint\n bool ResetAutoCheckpoint(int nCheckpoint)\n {\n if (nCheckpoint <= 0 || nCheckpoint > nBestHeight)\n return error(\"ResetAutoCheckpoint() : new checkpoint invalid\");\n if (nCheckpoint >= nAutoCheckpoint)\n return error(\"ResetAutoCheckpoint() : new checkpoint not earlier than current auto checkpoint\");\n CTxDB txdb;\n txdb.TxnBegin();\n if (!txdb.WriteAutoCheckpoint(nCheckpoint, true))\n return error(\"ResetAutoCheckpoint() : database write failed\");\n if (!txdb.TxnCommit())\n return error(\"ResetAutoCheckpoint() : database commit failed\");\n nAutoCheckpoint = nCheckpoint;\n nBranchPoint = 0; \/\/ clear branch point\n\n \/\/ clear ban list to accept alternative branches\n CRITICAL_BLOCK(cs_vNodes)\n {\n BOOST_FOREACH(CNode* pnode, vNodes)\n pnode->ClearBanned();\n }\n\n return true;\n }\n}\n\n\/\/ ppcoin: process synchronized checkpoint\nbool CSyncCheckpoint::ProcessSyncCheckpoint(CNode* pfrom)\n{\n if (!CheckSignature())\n return false;\n\n CTxDB txdb;\n CRITICAL_BLOCK(Checkpoints::cs_hashSyncCheckpoint)\n {\n if (!mapBlockIndex.count(hashCheckpoint))\n {\n \/\/ We haven't accepted this block, keep the checkpoint as pending\n Checkpoints::checkpointMessagePending = *this;\n printf(\"ProcessSyncCheckpoint: pending for sync-checkpoint %s\\n\", hashCheckpoint.ToString().c_str());\n \/\/ Ask this guy to fill in what we're missing\n if (pfrom)\n pfrom->PushGetBlocks(pindexBest, hashCheckpoint);\n return false;\n }\n if (!Checkpoints::ValidateSyncCheckpoint(hashCheckpoint))\n return false;\n\n txdb.TxnBegin();\n if (!txdb.WriteSyncCheckpoint(hashCheckpoint))\n {\n txdb.TxnAbort();\n return error(\"ProcessSyncCheckpoint(): failed to write to db sync checkpoint %s\", hashCheckpoint.ToString().c_str());\n }\n if (!txdb.TxnCommit())\n return error(\"ProcessSyncCheckpoint(): failed to commit to db sync checkpoint %s\", hashCheckpoint.ToString().c_str());\n\n Checkpoints::hashSyncCheckpoint = hashCheckpoint;\n Checkpoints::checkpointMessage = *this;\n Checkpoints::checkpointMessagePending.SetNull();\n printf(\"ProcessSyncCheckpoint: sync-checkpoint at %s\\n\", hashCheckpoint.ToString().c_str());\n }\n\n CBlockIndex* pindexCheckpoint = mapBlockIndex[hashCheckpoint];\n if (!pindexCheckpoint->IsInMainChain())\n {\n txdb.TxnBegin();\n if (!Reorganize(txdb, pindexCheckpoint))\n {\n txdb.TxnAbort();\n return error(\"ProcessSyncCheckpoint: Reorganize failed for sync checkpoint %s\", hashCheckpoint.ToString().c_str());\n }\n }\n txdb.Close();\n return true;\n}\n<commit_msg>PPCoin: Reorganize first before accepting synchronized checkpoint<commit_after>\/\/ Copyright (c) 2011 The Bitcoin developers\n\/\/ Copyright (c) 2011-2012 The PPCoin developers\n\/\/ Distributed under the MIT\/X11 software license, see the accompanying\n\/\/ file license.txt or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include <boost\/assign\/list_of.hpp> \/\/ for 'map_list_of()'\n#include <boost\/foreach.hpp>\n\n#include \"headers.h\"\n#include \"checkpoints.h\"\n\nnamespace Checkpoints\n{\n typedef std::map<int, uint256> MapCheckpoints; \/\/ hardened checkpoints\n\n \/\/\n \/\/ What makes a good checkpoint block?\n \/\/ + Is surrounded by blocks with reasonable timestamps\n \/\/ (no blocks before with a timestamp after, none after with\n \/\/ timestamp before)\n \/\/ + Contains no strange transactions\n \/\/\n static MapCheckpoints mapCheckpoints =\n boost::assign::map_list_of\n ( 0, hashGenesisBlock )\n ; \/\/ ppcoin: no checkpoint yet; to be created in future releases\n\n bool CheckHardened(int nHeight, const uint256& hash)\n {\n if (fTestNet) return true; \/\/ Testnet has no checkpoints\n\n MapCheckpoints::const_iterator i = mapCheckpoints.find(nHeight);\n if (i == mapCheckpoints.end()) return true;\n return hash == i->second;\n }\n\n int GetTotalBlocksEstimate()\n {\n if (fTestNet) return 0;\n\n return mapCheckpoints.rbegin()->first;\n }\n\n CBlockIndex* GetLastCheckpoint(const std::map<uint256, CBlockIndex*>& mapBlockIndex)\n {\n if (fTestNet) return NULL;\n\n int64 nResult;\n BOOST_REVERSE_FOREACH(const MapCheckpoints::value_type& i, mapCheckpoints)\n {\n const uint256& hash = i.second;\n std::map<uint256, CBlockIndex*>::const_iterator t = mapBlockIndex.find(hash);\n if (t != mapBlockIndex.end())\n return t->second;\n }\n return NULL;\n }\n\n \/\/ ppcoin: synchronized checkpoint (centrally broadcasted)\n uint256 hashSyncCheckpoint;\n CSyncCheckpoint checkpointMessage;\n CSyncCheckpoint checkpointMessagePending;\n CCriticalSection cs_hashSyncCheckpoint;\n\n \/\/ ppcoin: only descendant of current sync-checkpoint is allowed\n bool ValidateSyncCheckpoint(uint256 hashCheckpoint)\n {\n if (!mapBlockIndex.count(hashSyncCheckpoint))\n return error(\"ValidateSyncCheckpoint: block index missing for current sync-checkpoint %s\", hashSyncCheckpoint.ToString().c_str());\n if (!mapBlockIndex.count(hashCheckpoint))\n return error(\"ValidateSyncCheckpoint: block index missing for received sync-checkpoint %s\", hashCheckpoint.ToString().c_str());\n\n CBlockIndex* pindexSyncCheckpoint = mapBlockIndex[hashSyncCheckpoint];\n CBlockIndex* pindexCheckpointRecv = mapBlockIndex[hashCheckpoint];\n if (pindexCheckpointRecv->nHeight <= pindexSyncCheckpoint->nHeight)\n return false; \/\/ this is an older checkpoint, ignore\n\n CBlockIndex* pindex = pindexCheckpointRecv;\n while (pindex->nHeight > pindexSyncCheckpoint->nHeight)\n if (!(pindex = pindex->pprev))\n return error(\"ValidateSyncCheckpoint: pprev null - block index structure failure\");\n if (pindex->GetBlockHash() != hashSyncCheckpoint)\n return error(\"ValidateSyncCheckpoint: new sync-checkpoint %s is not a descendant of current sync-checkpoint %s\", hashCheckpoint.ToString().c_str(), hashSyncCheckpoint.ToString().c_str());\n return true;\n }\n\n bool AcceptPendingSyncCheckpoint()\n {\n CRITICAL_BLOCK(cs_hashSyncCheckpoint)\n {\n if ((!checkpointMessagePending.IsNull()) && mapBlockIndex.count(checkpointMessagePending.hashCheckpoint))\n {\n if (!ValidateSyncCheckpoint(checkpointMessagePending.hashCheckpoint))\n {\n checkpointMessagePending.SetNull();\n return false;\n }\n\n CTxDB txdb;\n CBlockIndex* pindexCheckpoint = mapBlockIndex[checkpointMessagePending.hashCheckpoint];\n if (!pindexCheckpoint->IsInMainChain())\n {\n txdb.TxnBegin();\n if (!Reorganize(txdb, pindexCheckpoint))\n {\n txdb.TxnAbort();\n return error(\"ProcessSyncCheckpoint: Reorganize failed for sync checkpoint %s\", checkpointMessagePending.hashCheckpoint.ToString().c_str());\n }\n }\n\n txdb.TxnBegin();\n if (!txdb.WriteSyncCheckpoint(checkpointMessagePending.hashCheckpoint))\n {\n txdb.TxnAbort();\n return error(\"AcceptPendingSyncCheckpoint() : failed to write to db sync checkpoint %s\\n\", checkpointMessagePending.hashCheckpoint.ToString().c_str());\n }\n if (!txdb.TxnCommit())\n return error(\"AcceptPendingSyncCheckpoint() : failed to commit to db sync checkpoint %s\\n\", checkpointMessagePending.hashCheckpoint.ToString().c_str());\n txdb.Close();\n\n hashSyncCheckpoint = checkpointMessagePending.hashCheckpoint;\n checkpointMessage = checkpointMessagePending;\n checkpointMessagePending.SetNull();\n printf(\"AcceptPendingSyncCheckpoint : sync-checkpoint at %s\\n\", hashSyncCheckpoint.ToString().c_str());\n \/\/ relay the checkpoint\n CRITICAL_BLOCK(cs_hashSyncCheckpoint)\n BOOST_FOREACH(CNode* pnode, vNodes)\n checkpointMessage.RelayTo(pnode);\n return true;\n }\n }\n\n return false;\n }\n\n uint256 AutoSelectSyncCheckpoint()\n {\n \/\/ select block roughly 8 hours ago\n CBlockIndex *pindex = mapBlockIndex[hashSyncCheckpoint];\n while (pindex->pnext && pindex->pnext->GetBlockTime() + AUTO_CHECKPOINT_MIN_SPAN <= GetAdjustedTime())\n pindex = pindex->pnext;\n return pindex->GetBlockHash();\n }\n\n \/\/ Check against synchronized checkpoint\n bool CheckSync(const uint256& hashBlock, const CBlockIndex* pindexPrev)\n {\n if (fTestNet) return true; \/\/ Testnet has no checkpoints\n int nHeight = pindexPrev->nHeight + 1;\n\n CRITICAL_BLOCK(cs_hashSyncCheckpoint)\n {\n \/\/ sync-checkpoint should always be accepted block\n assert(mapBlockIndex.count(hashSyncCheckpoint));\n const CBlockIndex* pindexSync = mapBlockIndex[hashSyncCheckpoint];\n\n if (nHeight > pindexSync->nHeight)\n {\n \/\/ trace back to same height as sync-checkpoint\n const CBlockIndex* pindex = pindexPrev;\n while (pindex->nHeight > pindexSync->nHeight)\n if (!(pindex = pindex->pprev))\n return error(\"CheckSync: pprev null - block index structure failure\");\n if (pindex->nHeight < pindexSync->nHeight || pindex->GetBlockHash() != hashSyncCheckpoint)\n return false; \/\/ only descendant of sync-checkpoint can pass check\n }\n if (nHeight == pindexSync->nHeight && hashBlock != hashSyncCheckpoint)\n return false; \/\/ same height with sync-checkpoint\n if (nHeight < pindexSync->nHeight && !mapBlockIndex.count(hashBlock))\n return false; \/\/ lower height than sync-checkpoint\n }\n return true;\n }\n\n \/\/ ppcoin: automatic checkpoint (represented by height of checkpoint)\n int nAutoCheckpoint = 0;\n int nBranchPoint = 0; \/\/ branch point to alternative branch\n\n \/\/ ppcoin: check automatic checkpoint\n \/\/ To pass the check:\n \/\/ - All ancestors (including the block itself) have block index already\n \/\/ - The immediate ancestor in main chain must not have height less than\n \/\/ checkpoint height\n bool CheckAuto(const CBlockIndex *pindex)\n {\n while (pindex)\n {\n if (pindex->IsInMainChain())\n {\n if (pindex->nHeight >= nAutoCheckpoint)\n return true;\n else\n {\n nBranchPoint = pindex->nHeight;\n return error(\"Checkpoints: new block on alternative branch at height=%d before auto checkpoint at height=%d\", pindex->nHeight, nAutoCheckpoint);\n }\n }\n else\n pindex = pindex->pprev;\n }\n return error(\"Checkpoints: failed to find any ancestor on main chain for the new block - internal error\");\n }\n\n \/\/ ppcoin: get next chain checkpoint\n int GetNextChainCheckpoint(const CBlockIndex *pindexLast)\n {\n CBigNum bnTarget;\n CBigNum bnTargetMax = 0; \/\/ max target of all blocks since checkpoint\n CBigNum bnTargetMin = 0; \/\/ min target of all candidate checkpoints\n int nMinTargetHeight = 0; \/\/ min target height of candidate checkpoints\n int nCheckpointMin = 0; \/\/ minimum candidate checkpoint\n int nCheckpointMax = 0; \/\/ maximum candidate checkpoint\n int nDepth = pindexLast->nHeight - pindexLast->nCheckpoint;\n const CBlockIndex *pindex = pindexLast;\n while (nDepth >= 0 && pindex)\n {\n bnTarget.SetCompact(pindex->nBits);\n if (bnTarget > bnTargetMax)\n bnTargetMax = bnTarget;\n if (nCheckpointMax > 0 && bnTarget < bnTargetMin)\n {\n bnTargetMin = bnTarget;\n nMinTargetHeight = pindex->nHeight;\n }\n if (nCheckpointMax == 0 && pindexLast->GetBlockTime() - pindex->GetBlockTime() > AUTO_CHECKPOINT_MIN_SPAN)\n {\n nCheckpointMax = pindex->nHeight;\n bnTargetMin.SetCompact(pindex->nBits);\n nMinTargetHeight = pindex->nHeight;\n }\n if (pindexLast->GetBlockTime() - pindex->GetBlockTime() < AUTO_CHECKPOINT_MAX_SPAN)\n nCheckpointMin = pindex->nHeight;\n pindex = pindex->pprev;\n nDepth--;\n }\n\n assert (nDepth == -1); \/\/ arrive at chain checkpoint now\n\n printf(\"Checkpoints: min=%d max=%d tminheight=%d tmin=0x%08x tmax=0x%08x\\n\",\n nCheckpointMin, nCheckpointMax, nMinTargetHeight,\n bnTargetMin.GetCompact(), bnTargetMax.GetCompact());\n if (nCheckpointMax == 0) \/\/ checkpoint stays if max candidate not found\n return pindexLast->nCheckpoint;\n\n if (bnTargetMin * 100 > bnTargetMax * 90)\n return nCheckpointMax;\n if (bnTarget * 100 > bnTargetMax * 90)\n return nMinTargetHeight;\n else\n return nCheckpointMin;\n }\n\n \/\/ ppcoin: get next auto checkpoint from the new chain checkpoint\n int GetNextAutoCheckpoint(int nCheckpoint)\n {\n return (std::max(nAutoCheckpoint, nCheckpoint));\n }\n\n \/\/ ppcoin: advance to next automatic checkpoint\n void AdvanceAutoCheckpoint(int nCheckpoint)\n {\n nAutoCheckpoint = GetNextAutoCheckpoint(nCheckpoint);\n printf(\"Checkpoints: auto checkpoint now at height=%d\\n\", nAutoCheckpoint);\n }\n\n \/\/ ppcoin: reset auto checkpoint\n bool ResetAutoCheckpoint(int nCheckpoint)\n {\n if (nCheckpoint <= 0 || nCheckpoint > nBestHeight)\n return error(\"ResetAutoCheckpoint() : new checkpoint invalid\");\n if (nCheckpoint >= nAutoCheckpoint)\n return error(\"ResetAutoCheckpoint() : new checkpoint not earlier than current auto checkpoint\");\n CTxDB txdb;\n txdb.TxnBegin();\n if (!txdb.WriteAutoCheckpoint(nCheckpoint, true))\n return error(\"ResetAutoCheckpoint() : database write failed\");\n if (!txdb.TxnCommit())\n return error(\"ResetAutoCheckpoint() : database commit failed\");\n nAutoCheckpoint = nCheckpoint;\n nBranchPoint = 0; \/\/ clear branch point\n\n \/\/ clear ban list to accept alternative branches\n CRITICAL_BLOCK(cs_vNodes)\n {\n BOOST_FOREACH(CNode* pnode, vNodes)\n pnode->ClearBanned();\n }\n\n return true;\n }\n}\n\n\/\/ ppcoin: process synchronized checkpoint\nbool CSyncCheckpoint::ProcessSyncCheckpoint(CNode* pfrom)\n{\n if (!CheckSignature())\n return false;\n\n CRITICAL_BLOCK(Checkpoints::cs_hashSyncCheckpoint)\n {\n if (!mapBlockIndex.count(hashCheckpoint))\n {\n \/\/ We haven't received the checkpoint chain, keep the checkpoint as pending\n Checkpoints::checkpointMessagePending = *this;\n printf(\"ProcessSyncCheckpoint: pending for sync-checkpoint %s\\n\", hashCheckpoint.ToString().c_str());\n \/\/ Ask this guy to fill in what we're missing\n if (pfrom)\n pfrom->PushGetBlocks(pindexBest, hashCheckpoint);\n return false;\n }\n\n if (!Checkpoints::ValidateSyncCheckpoint(hashCheckpoint))\n return false;\n\n CTxDB txdb;\n CBlockIndex* pindexCheckpoint = mapBlockIndex[hashCheckpoint];\n if (!pindexCheckpoint->IsInMainChain())\n {\n \/\/ checkpoint chain received but not yet main chain\n txdb.TxnBegin();\n if (!Reorganize(txdb, pindexCheckpoint))\n {\n txdb.TxnAbort();\n return error(\"ProcessSyncCheckpoint: Reorganize failed for sync checkpoint %s\", hashCheckpoint.ToString().c_str());\n }\n }\n\n txdb.TxnBegin();\n if (!txdb.WriteSyncCheckpoint(hashCheckpoint))\n {\n txdb.TxnAbort();\n return error(\"ProcessSyncCheckpoint(): failed to write to db sync checkpoint %s\", hashCheckpoint.ToString().c_str());\n }\n if (!txdb.TxnCommit())\n return error(\"ProcessSyncCheckpoint(): failed to commit to db sync checkpoint %s\", hashCheckpoint.ToString().c_str());\n txdb.Close();\n\n Checkpoints::hashSyncCheckpoint = hashCheckpoint;\n Checkpoints::checkpointMessage = *this;\n Checkpoints::checkpointMessagePending.SetNull();\n printf(\"ProcessSyncCheckpoint: sync-checkpoint at %s\\n\", hashCheckpoint.ToString().c_str());\n }\n return true;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2009-2012 The Bitcoin developers\n\/\/ Distributed under the MIT\/X11 software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include <boost\/assign\/list_of.hpp> \/\/ for 'map_list_of()'\n#include <boost\/foreach.hpp>\n\n#include \"checkpoints.h\"\n\n#include \"main.h\"\n#include \"uint256.h\"\n\nnamespace Checkpoints\n{\n typedef std::map<int, uint256> MapCheckpoints;\n\n \/\/ How many times we expect transactions after the last checkpoint to\n \/\/ be slower. This number is a compromise, as it can't be accurate for\n \/\/ every system. When reindexing from a fast disk with a slow CPU, it\n \/\/ can be up to 20, while when downloading from a slow network with a\n \/\/ fast multicore CPU, it won't be much higher than 1.\n static const double fSigcheckVerificationFactor = 5.0;\n\n struct CCheckpointData {\n const MapCheckpoints *mapCheckpoints;\n int64 nTimeLastCheckpoint;\n int64 nTransactionsLastCheckpoint;\n double fTransactionsPerDay;\n };\n\n \/\/ What makes a good checkpoint block?\n \/\/ + Is surrounded by blocks with reasonable timestamps\n \/\/ (no blocks before with a timestamp after, none after with\n \/\/ timestamp before)\n \/\/ + Contains no strange transactions\n static MapCheckpoints mapCheckpoints =\n boost::assign::map_list_of\n ( 0, uint256(\"0x\")) \n ;\n static const CCheckpointData data = {\n &mapCheckpoints,\n \/\/1410516073, \/\/ * UNIX timestamp of last checkpoint block\n \/\/4896865, \/\/ * total number of transactions between genesis and last checkpoint\n \/\/ (the tx=... number in the SetBestChain debug.log lines)\n \/\/7000.0 \/\/ * estimated number of transactions per day after checkpoint\n };\n\n static MapCheckpoints mapCheckpointsTestnet =\n boost::assign::map_list_of\n ( 0, uint256(\"0x\"))\n ;\n static const CCheckpointData dataTestnet = {\n &mapCheckpointsTestnet,\n \/\/1365458829,\n \/\/547,\n \/\/576\n };\n\n const CCheckpointData &Checkpoints() {\n if (fTestNet)\n return dataTestnet;\n else\n return data;\n }\n\n bool CheckBlock(int nHeight, const uint256& hash)\n {\n if (!GetBoolArg(\"-checkpoints\", true))\n return true;\n\n const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints;\n\n MapCheckpoints::const_iterator i = checkpoints.find(nHeight);\n if (i == checkpoints.end()) return true;\n return hash == i->second;\n }\n\n \/\/ Guess how far we are in the verification process at the given block index\n double GuessVerificationProgress(CBlockIndex *pindex) {\n if (pindex==NULL)\n return 0.0;\n\n int64 nNow = time(NULL);\n\n double fWorkBefore = 0.0; \/\/ Amount of work done before pindex\n double fWorkAfter = 0.0; \/\/ Amount of work left after pindex (estimated)\n \/\/ Work is defined as: 1.0 per transaction before the last checkoint, and\n \/\/ fSigcheckVerificationFactor per transaction after.\n\n const CCheckpointData &data = Checkpoints();\n\n if (pindex->nChainTx <= data.nTransactionsLastCheckpoint) {\n double nCheapBefore = pindex->nChainTx;\n double nCheapAfter = data.nTransactionsLastCheckpoint - pindex->nChainTx;\n double nExpensiveAfter = (nNow - data.nTimeLastCheckpoint)\/86400.0*data.fTransactionsPerDay;\n fWorkBefore = nCheapBefore;\n fWorkAfter = nCheapAfter + nExpensiveAfter*fSigcheckVerificationFactor;\n } else {\n double nCheapBefore = data.nTransactionsLastCheckpoint;\n double nExpensiveBefore = pindex->nChainTx - data.nTransactionsLastCheckpoint;\n double nExpensiveAfter = (nNow - pindex->nTime)\/86400.0*data.fTransactionsPerDay;\n fWorkBefore = nCheapBefore + nExpensiveBefore*fSigcheckVerificationFactor;\n fWorkAfter = nExpensiveAfter*fSigcheckVerificationFactor;\n }\n\n return fWorkBefore \/ (fWorkBefore + fWorkAfter);\n }\n\n int GetTotalBlocksEstimate()\n {\n if (!GetBoolArg(\"-checkpoints\", true))\n return 0;\n\n const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints;\n\n return checkpoints.rbegin()->first;\n }\n\n CBlockIndex* GetLastCheckpoint(const std::map<uint256, CBlockIndex*>& mapBlockIndex)\n {\n if (!GetBoolArg(\"-checkpoints\", true))\n return NULL;\n\n const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints;\n\n BOOST_REVERSE_FOREACH(const MapCheckpoints::value_type& i, checkpoints)\n {\n const uint256& hash = i.second;\n std::map<uint256, CBlockIndex*>::const_iterator t = mapBlockIndex.find(hash);\n if (t != mapBlockIndex.end())\n return t->second;\n }\n return NULL;\n }\n}\n<commit_msg>Update checkpoints.cpp<commit_after>\/\/ Copyright (c) 2009-2012 The Bitcoin developers\n\/\/ Distributed under the MIT\/X11 software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include <boost\/assign\/list_of.hpp> \/\/ for 'map_list_of()'\n#include <boost\/foreach.hpp>\n\n#include \"checkpoints.h\"\n\n#include \"main.h\"\n#include \"uint256.h\"\n\nnamespace Checkpoints\n{\n typedef std::map<int, uint256> MapCheckpoints;\n\n \/\/ How many times we expect transactions after the last checkpoint to\n \/\/ be slower. This number is a compromise, as it can't be accurate for\n \/\/ every system. When reindexing from a fast disk with a slow CPU, it\n \/\/ can be up to 20, while when downloading from a slow network with a\n \/\/ fast multicore CPU, it won't be much higher than 1.\n static const double fSigcheckVerificationFactor = 5.0;\n\n struct CCheckpointData {\n const MapCheckpoints *mapCheckpoints;\n int64 nTimeLastCheckpoint;\n int64 nTransactionsLastCheckpoint;\n double fTransactionsPerDay;\n };\n\n \/\/ What makes a good checkpoint block?\n \/\/ + Is surrounded by blocks with reasonable timestamps\n \/\/ (no blocks before with a timestamp after, none after with\n \/\/ timestamp before)\n \/\/ + Contains no strange transactions\n static MapCheckpoints mapCheckpoints =\n boost::assign::map_list_of\n ( 0, uint256(\"0xedf060880a41f8fe9c7521d663272673a510dfd193b0fdd918f2b34fdab34546\")) \n ;\n static const CCheckpointData data = {\n &mapCheckpoints,\n \/\/1410516073, \/\/ * UNIX timestamp of last checkpoint block\n \/\/4896865, \/\/ * total number of transactions between genesis and last checkpoint\n \/\/ (the tx=... number in the SetBestChain debug.log lines)\n \/\/7000.0 \/\/ * estimated number of transactions per day after checkpoint\n };\n\n static MapCheckpoints mapCheckpointsTestnet =\n boost::assign::map_list_of\n ( 0, uint256(\"0x\"))\n ;\n static const CCheckpointData dataTestnet = {\n &mapCheckpointsTestnet,\n \/\/1365458829,\n \/\/547,\n \/\/576\n };\n\n const CCheckpointData &Checkpoints() {\n if (fTestNet)\n return dataTestnet;\n else\n return data;\n }\n\n bool CheckBlock(int nHeight, const uint256& hash)\n {\n if (!GetBoolArg(\"-checkpoints\", true))\n return true;\n\n const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints;\n\n MapCheckpoints::const_iterator i = checkpoints.find(nHeight);\n if (i == checkpoints.end()) return true;\n return hash == i->second;\n }\n\n \/\/ Guess how far we are in the verification process at the given block index\n double GuessVerificationProgress(CBlockIndex *pindex) {\n if (pindex==NULL)\n return 0.0;\n\n int64 nNow = time(NULL);\n\n double fWorkBefore = 0.0; \/\/ Amount of work done before pindex\n double fWorkAfter = 0.0; \/\/ Amount of work left after pindex (estimated)\n \/\/ Work is defined as: 1.0 per transaction before the last checkoint, and\n \/\/ fSigcheckVerificationFactor per transaction after.\n\n const CCheckpointData &data = Checkpoints();\n\n if (pindex->nChainTx <= data.nTransactionsLastCheckpoint) {\n double nCheapBefore = pindex->nChainTx;\n double nCheapAfter = data.nTransactionsLastCheckpoint - pindex->nChainTx;\n double nExpensiveAfter = (nNow - data.nTimeLastCheckpoint)\/86400.0*data.fTransactionsPerDay;\n fWorkBefore = nCheapBefore;\n fWorkAfter = nCheapAfter + nExpensiveAfter*fSigcheckVerificationFactor;\n } else {\n double nCheapBefore = data.nTransactionsLastCheckpoint;\n double nExpensiveBefore = pindex->nChainTx - data.nTransactionsLastCheckpoint;\n double nExpensiveAfter = (nNow - pindex->nTime)\/86400.0*data.fTransactionsPerDay;\n fWorkBefore = nCheapBefore + nExpensiveBefore*fSigcheckVerificationFactor;\n fWorkAfter = nExpensiveAfter*fSigcheckVerificationFactor;\n }\n\n return fWorkBefore \/ (fWorkBefore + fWorkAfter);\n }\n\n int GetTotalBlocksEstimate()\n {\n if (!GetBoolArg(\"-checkpoints\", true))\n return 0;\n\n const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints;\n\n return checkpoints.rbegin()->first;\n }\n\n CBlockIndex* GetLastCheckpoint(const std::map<uint256, CBlockIndex*>& mapBlockIndex)\n {\n if (!GetBoolArg(\"-checkpoints\", true))\n return NULL;\n\n const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints;\n\n BOOST_REVERSE_FOREACH(const MapCheckpoints::value_type& i, checkpoints)\n {\n const uint256& hash = i.second;\n std::map<uint256, CBlockIndex*>::const_iterator t = mapBlockIndex.find(hash);\n if (t != mapBlockIndex.end())\n return t->second;\n }\n return NULL;\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2009-2012 The Bitcoin developers\n\/\/ Distributed under the MIT\/X11 software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include <boost\/assign\/list_of.hpp> \/\/ for 'map_list_of()'\n#include <boost\/foreach.hpp>\n\n#include \"checkpoints.h\"\n\n#include \"main.h\"\n#include \"uint256.h\"\n\nnamespace Checkpoints\n{\n typedef std::map<int, uint256> MapCheckpoints;\n\n \/\/ How many times we expect transactions after the last checkpoint to\n \/\/ be slower. This number is a compromise, as it can't be accurate for\n \/\/ every system. When reindexing from a fast disk with a slow CPU, it\n \/\/ can be up to 20, while when downloading from a slow network with a\n \/\/ fast multicore CPU, it won't be much higher than 1.\n static const double fSigcheckVerificationFactor = 5.0;\n\n struct CCheckpointData {\n const MapCheckpoints *mapCheckpoints;\n int64 nTimeLastCheckpoint;\n int64 nTransactionsLastCheckpoint;\n double fTransactionsPerDay;\n };\n\n \/\/ What makes a good checkpoint block?\n \/\/ + Is surrounded by blocks with reasonable timestamps\n \/\/ (no blocks before with a timestamp after, none after with\n \/\/ timestamp before)\n \/\/ + Contains no strange transactions\n static MapCheckpoints mapCheckpoints =\n boost::assign::map_list_of\n ( 10000, uint256(\"0xd675420779ce0e4f96199e2378fd6be4a671869a379aab9bf2d1ddda995c4afe\"))\n ;\n static const CCheckpointData data = {\n &mapCheckpoints,\n 1389093420, \/\/ * UNIX timestamp of last checkpoint block\n 10000, \/\/ * total number of transactions between genesis and last checkpoint\n \/\/ (the tx=... number in the SetBestChain debug.log lines)\n 8000.0 \/\/ * estimated number of transactions per day after checkpoint\n };\n\n static MapCheckpoints mapCheckpointsTestnet = \n boost::assign::map_list_of\n ( 0, uint256(\"0x\"))\n ;\n static const CCheckpointData dataTestnet = {\n &mapCheckpointsTestnet,\n 1369685559,\n 37581,\n 300\n };\n\n const CCheckpointData &Checkpoints() {\n if (fTestNet)\n return dataTestnet;\n else\n return data;\n }\n\n bool CheckBlock(int nHeight, const uint256& hash)\n {\n\n if (fTestNet) return true; \/\/ Testnet has no checkpoints\n if (!GetBoolArg(\"-checkpoints\", true))\n return true;\n\n const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints;\n\n MapCheckpoints::const_iterator i = checkpoints.find(nHeight);\n if (i == checkpoints.end()) return true;\n \/\/return hash == i->second;\n return true; \/\/disable checkpoints for now\n }\n\n \/\/ Guess how far we are in the verification process at the given block index\n double GuessVerificationProgress(CBlockIndex *pindex) {\n if (pindex==NULL)\n return 0.0;\n\n int64 nNow = time(NULL);\n\n double fWorkBefore = 0.0; \/\/ Amount of work done before pindex\n double fWorkAfter = 0.0; \/\/ Amount of work left after pindex (estimated)\n \/\/ Work is defined as: 1.0 per transaction before the last checkoint, and\n \/\/ fSigcheckVerificationFactor per transaction after.\n\n const CCheckpointData &data = Checkpoints();\n\n if (pindex->nChainTx <= data.nTransactionsLastCheckpoint) {\n double nCheapBefore = pindex->nChainTx;\n double nCheapAfter = data.nTransactionsLastCheckpoint - pindex->nChainTx;\n double nExpensiveAfter = (nNow - data.nTimeLastCheckpoint)\/86400.0*data.fTransactionsPerDay;\n fWorkBefore = nCheapBefore;\n fWorkAfter = nCheapAfter + nExpensiveAfter*fSigcheckVerificationFactor;\n } else {\n double nCheapBefore = data.nTransactionsLastCheckpoint;\n double nExpensiveBefore = pindex->nChainTx - data.nTransactionsLastCheckpoint;\n double nExpensiveAfter = (nNow - pindex->nTime)\/86400.0*data.fTransactionsPerDay;\n fWorkBefore = nCheapBefore + nExpensiveBefore*fSigcheckVerificationFactor;\n fWorkAfter = nExpensiveAfter*fSigcheckVerificationFactor;\n }\n\n return fWorkBefore \/ (fWorkBefore + fWorkAfter);\n }\n\n int GetTotalBlocksEstimate()\n {\n\n if (fTestNet) return 0; \/\/ Testnet has no checkpoints\n if (!GetBoolArg(\"-checkpoints\", true))\n return 0;\n\n const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints;\n\n \/\/return checkpoints.rbegin()->first;\n return true; \/\/return true for now\n }\n\n CBlockIndex* GetLastCheckpoint(const std::map<uint256, CBlockIndex*>& mapBlockIndex)\n {\n\n if (fTestNet) return NULL; \/\/ Testnet has no checkpoints\n if (!GetBoolArg(\"-checkpoints\", true))\n return NULL;\n\n const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints;\n\n BOOST_REVERSE_FOREACH(const MapCheckpoints::value_type& i, checkpoints)\n {\n const uint256& hash = i.second;\n std::map<uint256, CBlockIndex*>::const_iterator t = mapBlockIndex.find(hash);\n if (t != mapBlockIndex.end())\n return t->second;\n }\n return NULL;\n }\n\n uint256 GetLatestHardenedCheckpoint()\n {\n const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints;\n return (checkpoints.rbegin()->second);\n }\n}\n<commit_msg>updated checkpoints and put checkpoints code back<commit_after>\/\/ Copyright (c) 2009-2012 The Bitcoin developers\n\/\/ Distributed under the MIT\/X11 software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include <boost\/assign\/list_of.hpp> \/\/ for 'map_list_of()'\n#include <boost\/foreach.hpp>\n\n#include \"checkpoints.h\"\n\n#include \"main.h\"\n#include \"uint256.h\"\n\nnamespace Checkpoints\n{\n typedef std::map<int, uint256> MapCheckpoints;\n\n \/\/ How many times we expect transactions after the last checkpoint to\n \/\/ be slower. This number is a compromise, as it can't be accurate for\n \/\/ every system. When reindexing from a fast disk with a slow CPU, it\n \/\/ can be up to 20, while when downloading from a slow network with a\n \/\/ fast multicore CPU, it won't be much higher than 1.\n static const double fSigcheckVerificationFactor = 5.0;\n\n struct CCheckpointData {\n const MapCheckpoints *mapCheckpoints;\n int64 nTimeLastCheckpoint;\n int64 nTransactionsLastCheckpoint;\n double fTransactionsPerDay;\n };\n\n \/\/ What makes a good checkpoint block?\n \/\/ + Is surrounded by blocks with reasonable timestamps\n \/\/ (no blocks before with a timestamp after, none after with\n \/\/ timestamp before)\n \/\/ + Contains no strange transactions\n static MapCheckpoints mapCheckpoints =\n boost::assign::map_list_of\n ( 9, uint256(\"0x37789e5af50e27cbc62ced734ced9f6f47b8b1f1c86d4287ade112c8ba4dbbd6\"))\n ( 20, uint256(\"0x80f891ea4012c9744c23a97bb63e310c406113e1f01210499a2d07444898d3f6\") )\n ( 92, uint256(\"0x0b3f654bb6944d8419e69270c231a8b3125833522c1630b5723d62c1e183f317\") );\n static const CCheckpointData data = {\n &mapCheckpoints,\n 1389093420, \/\/ * UNIX timestamp of last checkpoint block\n 10000, \/\/ * total number of transactions between genesis and last checkpoint\n \/\/ (the tx=... number in the SetBestChain debug.log lines)\n 8000.0 \/\/ * estimated number of transactions per day after checkpoint\n };\n\n static MapCheckpoints mapCheckpointsTestnet = \n boost::assign::map_list_of\n ( 0, uint256(\"0x\"))\n ;\n static const CCheckpointData dataTestnet = {\n &mapCheckpointsTestnet,\n 1369685559,\n 37581,\n 300\n };\n\n const CCheckpointData &Checkpoints() {\n if (fTestNet)\n return dataTestnet;\n else\n return data;\n }\n\n bool CheckBlock(int nHeight, const uint256& hash)\n {\n\n if (fTestNet) return true; \/\/ Testnet has no checkpoints\n if (!GetBoolArg(\"-checkpoints\", true))\n return true;\n\n const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints;\n\n MapCheckpoints::const_iterator i = checkpoints.find(nHeight);\n if (i == checkpoints.end()) return true;\n return hash == i->second;\n \/\/return true; \/\/disable checkpoints for now\n }\n\n \/\/ Guess how far we are in the verification process at the given block index\n double GuessVerificationProgress(CBlockIndex *pindex) {\n if (pindex==NULL)\n return 0.0;\n\n int64 nNow = time(NULL);\n\n double fWorkBefore = 0.0; \/\/ Amount of work done before pindex\n double fWorkAfter = 0.0; \/\/ Amount of work left after pindex (estimated)\n \/\/ Work is defined as: 1.0 per transaction before the last checkoint, and\n \/\/ fSigcheckVerificationFactor per transaction after.\n\n const CCheckpointData &data = Checkpoints();\n\n if (pindex->nChainTx <= data.nTransactionsLastCheckpoint) {\n double nCheapBefore = pindex->nChainTx;\n double nCheapAfter = data.nTransactionsLastCheckpoint - pindex->nChainTx;\n double nExpensiveAfter = (nNow - data.nTimeLastCheckpoint)\/86400.0*data.fTransactionsPerDay;\n fWorkBefore = nCheapBefore;\n fWorkAfter = nCheapAfter + nExpensiveAfter*fSigcheckVerificationFactor;\n } else {\n double nCheapBefore = data.nTransactionsLastCheckpoint;\n double nExpensiveBefore = pindex->nChainTx - data.nTransactionsLastCheckpoint;\n double nExpensiveAfter = (nNow - pindex->nTime)\/86400.0*data.fTransactionsPerDay;\n fWorkBefore = nCheapBefore + nExpensiveBefore*fSigcheckVerificationFactor;\n fWorkAfter = nExpensiveAfter*fSigcheckVerificationFactor;\n }\n\n return fWorkBefore \/ (fWorkBefore + fWorkAfter);\n }\n\n int GetTotalBlocksEstimate()\n {\n\n if (fTestNet) return 0; \/\/ Testnet has no checkpoints\n if (!GetBoolArg(\"-checkpoints\", true))\n return 0;\n\n const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints;\n\n return checkpoints.rbegin()->first;\n \/\/return true; \/\/return true for now\n }\n\n CBlockIndex* GetLastCheckpoint(const std::map<uint256, CBlockIndex*>& mapBlockIndex)\n {\n\n if (fTestNet) return NULL; \/\/ Testnet has no checkpoints\n if (!GetBoolArg(\"-checkpoints\", true))\n return NULL;\n\n const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints;\n\n BOOST_REVERSE_FOREACH(const MapCheckpoints::value_type& i, checkpoints)\n {\n const uint256& hash = i.second;\n std::map<uint256, CBlockIndex*>::const_iterator t = mapBlockIndex.find(hash);\n if (t != mapBlockIndex.end())\n return t->second;\n }\n return NULL;\n }\n\n uint256 GetLatestHardenedCheckpoint()\n {\n const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints;\n return (checkpoints.rbegin()->second);\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2009-2012 The Bitcoin developers\n\/\/ Distributed under the MIT\/X11 software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include <boost\/assign\/list_of.hpp> \/\/ for 'map_list_of()'\n#include <boost\/foreach.hpp>\n\n#include \"checkpoints.h\"\n\n#include \"txdb.h\"\n#include \"main.h\"\n#include \"uint256.h\"\n\n\nstatic const int nCheckpointSpan = 500;\n\nnamespace Checkpoints\n{\n typedef std::map<int, uint256> MapCheckpoints;\n\n \/\/\n \/\/ What makes a good checkpoint block?\n \/\/ + Is surrounded by blocks with reasonable timestamps\n \/\/ (no blocks before with a timestamp after, none after with\n \/\/ timestamp before)\n \/\/ + Contains no strange transactions\n \/\/\n \n static MapCheckpoints mapCheckpoints =\n boost::assign::map_list_of\n ( 15000, uint256(\"0xca3548f27e851f563008cfd79b3f97b555002ade6d6d1abf82af5161b3e5b0df\") )\n ( 55000, uint256(\"0xb12293afc8d69f285cf0f7c1767b55d27c571c499ac91bdb47a5bccfa76b63b8\") )\n ( 110000, uint256(\"0x92f5e226fb7bcc58f9933fa1c4836b5e2bf029bdb8e9eae366d80b14017841bc\") )\n ( 300500, uint256(\"0x09d9bd6b9002bf66527e098f0e620a6f59c6a3b244bc0bc8f4c4879e19b8fbfa\") )\n ;\n \n \/\/ TestNet has no checkpoints\n static MapCheckpoints mapCheckpointsTestnet;\n\n bool CheckHardened(int nHeight, const uint256& hash)\n {\n MapCheckpoints& checkpoints = (TestNet() ? mapCheckpointsTestnet : mapCheckpoints);\n\n MapCheckpoints::const_iterator i = checkpoints.find(nHeight);\n if (i == checkpoints.end()) return true;\n return hash == i->second;\n }\n\n int GetTotalBlocksEstimate()\n {\n MapCheckpoints& checkpoints = (TestNet() ? mapCheckpointsTestnet : mapCheckpoints);\n\n if (checkpoints.empty())\n return 0;\n return checkpoints.rbegin()->first;\n }\n\n CBlockIndex* GetLastCheckpoint(const std::map<uint256, CBlockIndex*>& mapBlockIndex)\n {\n MapCheckpoints& checkpoints = (TestNet() ? mapCheckpointsTestnet : mapCheckpoints);\n\n BOOST_REVERSE_FOREACH(const MapCheckpoints::value_type& i, checkpoints)\n {\n const uint256& hash = i.second;\n std::map<uint256, CBlockIndex*>::const_iterator t = mapBlockIndex.find(hash);\n if (t != mapBlockIndex.end())\n return t->second;\n }\n return NULL;\n }\n\n \/\/ Automatically select a suitable sync-checkpoint \n const CBlockIndex* AutoSelectSyncCheckpoint()\n {\n const CBlockIndex *pindex = pindexBest;\n \/\/ Search backward for a block within max span and maturity window\n while (pindex->pprev && pindex->nHeight + nCheckpointSpan > pindexBest->nHeight)\n pindex = pindex->pprev;\n return pindex;\n }\n\n \/\/ Check against synchronized checkpoint\n bool CheckSync(int nHeight)\n {\n const CBlockIndex* pindexSync = AutoSelectSyncCheckpoint();\n\n if (nHeight <= pindexSync->nHeight)\n return false;\n return true;\n }\n}\n<commit_msg>Added checkpoint at block 345000<commit_after>\/\/ Copyright (c) 2009-2012 The Bitcoin developers\n\/\/ Distributed under the MIT\/X11 software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include <boost\/assign\/list_of.hpp> \/\/ for 'map_list_of()'\n#include <boost\/foreach.hpp>\n\n#include \"checkpoints.h\"\n\n#include \"txdb.h\"\n#include \"main.h\"\n#include \"uint256.h\"\n\n\nstatic const int nCheckpointSpan = 500;\n\nnamespace Checkpoints\n{\n typedef std::map<int, uint256> MapCheckpoints;\n\n \/\/\n \/\/ What makes a good checkpoint block?\n \/\/ + Is surrounded by blocks with reasonable timestamps\n \/\/ (no blocks before with a timestamp after, none after with\n \/\/ timestamp before)\n \/\/ + Contains no strange transactions\n \/\/\n \n static MapCheckpoints mapCheckpoints =\n boost::assign::map_list_of\n ( 15000, uint256(\"0xca3548f27e851f563008cfd79b3f97b555002ade6d6d1abf82af5161b3e5b0df\") )\n ( 55000, uint256(\"0xb12293afc8d69f285cf0f7c1767b55d27c571c499ac91bdb47a5bccfa76b63b8\") )\n ( 110000, uint256(\"0x92f5e226fb7bcc58f9933fa1c4836b5e2bf029bdb8e9eae366d80b14017841bc\") )\n ( 300500, uint256(\"0x09d9bd6b9002bf66527e098f0e620a6f59c6a3b244bc0bc8f4c4879e19b8fbfa\") )\n ( 345000, uint256(\"0x251f44f94e369ebebc51304ce1a7b367ecad8025e822a5a28407085915542a47\") )\n ;\n \n \/\/ TestNet has no checkpoints\n static MapCheckpoints mapCheckpointsTestnet;\n\n bool CheckHardened(int nHeight, const uint256& hash)\n {\n MapCheckpoints& checkpoints = (TestNet() ? mapCheckpointsTestnet : mapCheckpoints);\n\n MapCheckpoints::const_iterator i = checkpoints.find(nHeight);\n if (i == checkpoints.end()) return true;\n return hash == i->second;\n }\n\n int GetTotalBlocksEstimate()\n {\n MapCheckpoints& checkpoints = (TestNet() ? mapCheckpointsTestnet : mapCheckpoints);\n\n if (checkpoints.empty())\n return 0;\n return checkpoints.rbegin()->first;\n }\n\n CBlockIndex* GetLastCheckpoint(const std::map<uint256, CBlockIndex*>& mapBlockIndex)\n {\n MapCheckpoints& checkpoints = (TestNet() ? mapCheckpointsTestnet : mapCheckpoints);\n\n BOOST_REVERSE_FOREACH(const MapCheckpoints::value_type& i, checkpoints)\n {\n const uint256& hash = i.second;\n std::map<uint256, CBlockIndex*>::const_iterator t = mapBlockIndex.find(hash);\n if (t != mapBlockIndex.end())\n return t->second;\n }\n return NULL;\n }\n\n \/\/ Automatically select a suitable sync-checkpoint \n const CBlockIndex* AutoSelectSyncCheckpoint()\n {\n const CBlockIndex *pindex = pindexBest;\n \/\/ Search backward for a block within max span and maturity window\n while (pindex->pprev && pindex->nHeight + nCheckpointSpan > pindexBest->nHeight)\n pindex = pindex->pprev;\n return pindex;\n }\n\n \/\/ Check against synchronized checkpoint\n bool CheckSync(int nHeight)\n {\n const CBlockIndex* pindexSync = AutoSelectSyncCheckpoint();\n\n if (nHeight <= pindexSync->nHeight)\n return false;\n return true;\n }\n}\n<|endoftext|>"} {"text":"<commit_before>#include <sys\/types.h>\n#include <sys\/endian.h>\n#include <stdio.h>\n#include <iostream>\n#include <map>\n#include <string>\n\n#include \"uvxbridge.h\"\n\nstatic int\ncmdmap_get_num(cmdmap_t &map, const char *key, uint64_t &val)\n{\n\t\tauto it = map.find(string(key));\n\n\t\tif (it == map.end())\n\t\t\t\treturn EINVAL;\n\t\tif (it->second.tag != TAG_NUMERIC)\n\t\t\t\treturn EINVAL;\n\t\tval = it->second.value.numeric;\n\n\t\treturn 0;\n}\n\nstatic int\ncmdmap_get_str(cmdmap_t &map, const char *key, char **val)\n{\n\t\tauto it = map.find(string(key));\n\n\t\tif (it == map.end())\n\t\t\t\treturn EINVAL;\n\t\tif (it->second.tag != TAG_STRING)\n\t\t\t\treturn EINVAL;\n\t\t*val = it->second.value.text;\n\n\t\treturn 0;\n}\n\nstatic string\ndefault_result(uint64_t seqno)\n{\n\t\tchar buf[32];\n\t\tsnprintf(buf, 32, \"(result:0x%lX)\", seqno);\n\t\treturn string(buf);\n}\nparse_value::parse_value(uint64_t numeric)\n{\n\t\tthis->tag = TAG_NUMERIC;\n\t\tthis->value.numeric = numeric;\n}\n\nparse_value::parse_value(char *text)\n{\n\t\tthis->tag = TAG_STRING;\n\t\tthis->value.text = strdup(text);\n}\n\nparse_value::~parse_value()\n{\n\t\tswitch(this->tag) {\n\t\tcase TAG_STRING:\n\t\t\t\tfree(this->value.text);\n\t\t\t\tbreak;\n\t\tcase TAG_NUMERIC:\n\t\t\t\tbreak;\n\t\t}\n}\n\ntypedef int (*cmdhandler_t)(cmdmap_t &map, uint64_t seqno, vxstate_t&, string&);\n\nstatic int\nfte_update_handler(cmdmap_t &map __unused, uint64_t seqno, vxstate_t &state, string &result)\n{\n\t\tuint64_t mac, expire;\n\t\tchar *ip;\n\t\tint gen;\n\n\t\tif (cmdmap_get_num(map, \"mac\", mac))\n\t\t\t\treturn EINVAL;\n\t\tif (cmdmap_get_num(map, \"expire\", expire))\n\t\t\t\treturn EINVAL;\n\t\tif (cmdmap_get_str(map, \"raddr\", &ip))\n\t\t\t\treturn EINVAL;\n\t\tauto fe = vxlan_ftable_entry(ip, expire);\n\t\tauto it = state.vs_ftable.find(mac);\n\t\tif (it == state.vs_ftable.end())\n\t\t\t\tgen = 0;\n\t\telse\n\t\t\t\tgen = it->second.vfe_gen + 1;\n\t\tstate.vs_ftable.insert(fwdent(mac, fe));\n\t\t\t\t\n\t\treturn 0;\n}\n\nstatic int\nfte_remove_handler(cmdmap_t &map __unused, uint64_t seqno, vxstate_t &state, string &result)\n{\n\n\t\tresult = default_result(seqno);\n\t\treturn 0;\n}\n\nstatic int\nfte_get_handler(cmdmap_t &map __unused, uint64_t seqno, vxstate_t &state, string &result)\n{\n\n\t\treturn 0;\n}\n\nstatic int\nfte_get_all_handler(cmdmap_t &map __unused, uint64_t seqno, vxstate_t &state, string &result)\n{\n\n\t\treturn 0;\n}\n\n\nstatic int\nnd_phys_get_handler(cmdmap_t &map __unused, uint64_t seqno, vxstate_t &state, string &result)\n{\n\t\t\n\t\treturn 0;\n}\n\nstatic int\nnd_phys_set_handler(cmdmap_t &map __unused, uint64_t seqno, vxstate_t &state, string &result)\n{\n\t\t\n\t\treturn 0;\n}\n\nstatic int\nnd_phys_del_handler(cmdmap_t &map __unused, uint64_t seqno, vxstate_t &state, string &result)\n{\n\t\t\n\t\treturn 0;\n}\n\nstatic int\nnd_phys_get_all_handler(cmdmap_t &map __unused, uint64_t seqno, vxstate_t &state, string &result)\n{\n\t\t\n\t\treturn 0;\n}\n\n\nstatic int\nnd_vx_get_handler(cmdmap_t &map __unused, uint64_t seqno, vxstate_t &state, string &result)\n{\n\t\t\n\t\treturn 0;\n}\n\nstatic int\nnd_vx_set_handler(cmdmap_t &map __unused, uint64_t seqno, vxstate_t &state, string &result)\n{\n\t\t\n\t\treturn 0;\n}\n\nstatic int\nnd_vx_del_handler(cmdmap_t &map __unused, uint64_t seqno, vxstate_t &state, string &result)\n{\n\t\t\n\t\treturn 0;\n}\n\nstatic int\nnd_vx_get_all_handler(cmdmap_t &map __unused, uint64_t seqno, vxstate_t &state, string &result)\n{\n\t\t\n\t\treturn 0;\n}\n\n\nstatic int\nvm_vni_update_handler(cmdmap_t &map __unused, uint64_t seqno, vxstate_t &state, string &result)\n{\n\t\t\n\t\treturn 0;\n}\n\nstatic int\nvm_vni_remove_handler(cmdmap_t &map __unused, uint64_t seqno, vxstate_t &state, string &result)\n{\n\t\t\n\t\treturn 0;\n}\n\nstatic int\nvm_vni_get_handler(cmdmap_t &map __unused, uint64_t seqno, vxstate_t &state, string &result)\n{\n\t\treturn 0;\n}\n\nstatic int\nvm_vni_get_all_handler(cmdmap_t &map __unused, uint64_t seqno, vxstate_t &state, string &result)\n{\n\t\treturn 0;\n}\n\nstatic int\nroute_update_handler(cmdmap_t &map __unused, uint64_t seqno, vxstate_t &state, string &result)\n{\n\t\treturn 0;\n}\n\nstatic int\nroute_remove_handler(cmdmap_t &map __unused, uint64_t seqno, vxstate_t &state, string &result)\n{\n\t\treturn 0;\n}\n\ntypedef struct _ent {\n\t\tconst char *ent;\n\t\tcmdhandler_t handler;\n\t\tenum verb action;\n\t\tint pad0;\n} ent_t;\n\n#define KEYENT(action, handler) {#action, handler, action, 0} \n\n\nstatic ent_t ent_list[] = {\n\t\tKEYENT(VERB_UPDATE_FTE, fte_update_handler),\n\t\tKEYENT(VERB_REMOVE_FTE, fte_remove_handler),\n\t\tKEYENT(VERB_GET_FTE, fte_get_handler),\n\t\tKEYENT(VERB_GET_ALL_FTE, fte_get_all_handler),\n\n\t\tKEYENT(VERB_GET_PHYS_ND, nd_phys_get_handler),\n\t\tKEYENT(VERB_SET_PHYS_ND, nd_phys_set_handler),\n\t\tKEYENT(VERB_DEL_PHYS_ND, nd_phys_del_handler),\n\t\tKEYENT(VERB_GET_ALL_PHYS_ND, nd_phys_get_all_handler),\n\n\t\tKEYENT(VERB_UPDATE_VM_VNI, vm_vni_update_handler),\n\t\tKEYENT(VERB_REMOVE_VM_VNI, vm_vni_remove_handler),\n\t\tKEYENT(VERB_GET_VM_VNI, vm_vni_get_handler),\n\t\tKEYENT(VERB_GET_ALL_VM_VNI, vm_vni_get_all_handler),\n\n\t\tKEYENT(VERB_GET_VX_ND, nd_vx_get_handler),\n\t\tKEYENT(VERB_SET_VX_ND, nd_vx_set_handler),\n\t\tKEYENT(VERB_DEL_VX_ND, nd_vx_del_handler),\n\t\tKEYENT(VERB_GET_ALL_VX_ND, nd_vx_get_all_handler),\n\n\t\t\n\t\tKEYENT(VERB_UPDATE_DEFAULT_ROUTE, route_update_handler),\n\t\tKEYENT(VERB_REMOVE_DEFAULT_ROUTE, route_remove_handler),\n\n\t\tKEYENT(VERB_BAD, NULL) \/* must be last *\/\n};\n\nstatic void\ngather_args(cmdmap_t &map, char *input)\n{\n\t\tchar *indexp, *k, *tmp;\n\t\tconst char *delim = \" \";\n\t\tconst char *kvdelim = \":\";\n\n\t\twhile (input != NULL) {\n\t\t\t\tindexp = strsep(&input, delim);\n\t\t\t\tk = strsep(&indexp, kvdelim);\n\t\t\t\t\/* badly formed K:V pair *\/\n\t\t\t\tif (indexp == NULL)\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\/* STRING *\/\n\t\t\t\tif (indexp[0] == '\"') {\n\t\t\t\t\t\tindexp++;\n\t\t\t\t\t\tif ((tmp = index(indexp, '\"')) == NULL)\n\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t*tmp = '\\0';\n\t\t\t\t\t\tmap.insert(cmdent(string(k), parse_value(indexp)));\n\t\t\t\t}\n\t\t\t\t\/* NUMBER *\/\n\t\t\t\telse if (indexp[0] == '0' && indexp[1] == 'x') {\n\t\t\t\t\t\tuint64_t v;\n\t\t\t\t\t\tindexp += 2;\n\t\t\t\t\t\tv = static_cast<uint64_t>(strtoll(indexp, NULL, 16));\n\t\t\t\t\t\tmap.insert(cmdent(string(k), parse_value(v)));\n\t\t\t\t\t\t\n\t\t\t\t}\n\t\t\t\t\/* UNKNOWN *\/\n\t\t\t\telse\n\t\t\t\t\t\tcontinue;\n\t\t}\t\t\n}\n\nint\nparse_input(char *input, struct vxlan_state &state, string &result)\n{\n\t\tcmdmap_t map;\n\t\tconst char *delim = \" \";\n\t\tconst char *kvdelim = \":\";\n\t\tchar *indexp, *verbstr;\n\t\tent_t *verbent = ent_list;\n\t\tenum verb verb;\n\t\tuint64_t seqno;\n\n\t\tindexp = strsep(&input, delim);\n\t\tverbstr = strsep(&indexp, kvdelim);\n\t\tif (indexp == NULL || indexp[0] != '0' || indexp[1] != 'x')\n\t\t\t\treturn EINVAL;\n\t\tindexp += 2;\n\t\tseqno = static_cast<uint64_t>(strtoll(indexp, NULL, 16));\n\t\t\n\t\tfor (verbent = ent_list; verbent->action != VERB_BAD; verbent++) {\n\t\t\t\tif (!strcmp(verbent->ent, verbstr))\n\t\t\t\t\t\tbreak;\n\t\t}\n\t\tverb = verbent->action;\n\t\tif (verb == VERB_BAD)\n\t\t\t\treturn EINVAL;\n\t\tgather_args(map, input);\n\t\treturn verbent->handler(map, seqno, state, result);\n}\n\n<commit_msg>finish update<commit_after>#include <sys\/types.h>\n#include <sys\/endian.h>\n#include <stdio.h>\n#include <iostream>\n#include <map>\n#include <string>\n\n#include <sys\/socket.h>\n#include <arpa\/inet.h>\n#include \"uvxbridge.h\"\n\nstatic int\ncmdmap_get_num(cmdmap_t &map, const char *key, uint64_t &val)\n{\n\t\tauto it = map.find(string(key));\n\n\t\tif (it == map.end())\n\t\t\t\treturn EINVAL;\n\t\tif (it->second.tag != TAG_NUMERIC)\n\t\t\t\treturn EINVAL;\n\t\tval = it->second.value.numeric;\n\n\t\treturn 0;\n}\n\nstatic int\ncmdmap_get_str(cmdmap_t &map, const char *key, char **val)\n{\n\t\tauto it = map.find(string(key));\n\n\t\tif (it == map.end())\n\t\t\t\treturn EINVAL;\n\t\tif (it->second.tag != TAG_STRING)\n\t\t\t\treturn EINVAL;\n\t\t*val = it->second.value.text;\n\n\t\treturn 0;\n}\n\nstatic string\ndefault_result(uint64_t seqno)\n{\n\t\tchar buf[32];\n\t\tsnprintf(buf, 32, \"(result:0x%lX)\", seqno);\n\t\treturn string(buf);\n}\nparse_value::parse_value(uint64_t numeric)\n{\n\t\tthis->tag = TAG_NUMERIC;\n\t\tthis->value.numeric = numeric;\n}\n\nparse_value::parse_value(char *text)\n{\n\t\tthis->tag = TAG_STRING;\n\t\tthis->value.text = strdup(text);\n}\n\nparse_value::~parse_value()\n{\n\t\tswitch(this->tag) {\n\t\tcase TAG_STRING:\n\t\t\t\tfree(this->value.text);\n\t\t\t\tbreak;\n\t\tcase TAG_NUMERIC:\n\t\t\t\tbreak;\n\t\t}\n}\n\ntypedef int (*cmdhandler_t)(cmdmap_t &map, uint64_t seqno, vxstate_t&, string&);\n\nstatic int\nfte_update_handler(cmdmap_t &map, uint64_t seqno, vxstate_t &state, string &result)\n{\n\t\tuint64_t mac, expire;\n\t\tchar *ip;\n\t\tint gen;\n\n\t\tif (cmdmap_get_num(map, \"mac\", mac))\n\t\t\t\treturn EINVAL;\n\t\tif (cmdmap_get_num(map, \"expire\", expire))\n\t\t\t\treturn EINVAL;\n\t\tif (cmdmap_get_str(map, \"raddr\", &ip))\n\t\t\t\treturn EINVAL;\n\t\tauto it = state.vs_ftable.find(mac);\n\t\tif (it == state.vs_ftable.end()) {\n\t\t\t\tauto fe = vxlan_ftable_entry(ip, expire);\n\t\t\t\tstate.vs_ftable.insert(fwdent(mac, fe));\n\t\t} else {\n\t\t\t\tauto fe = &it->second;\n\t\t\t\tint is_v6 = (index(ip, ':') != NULL);\n\t\t\t\tfe->vfe_gen++;\n\t\t\t\tfe->vfe_expire = expire;\n\t\t\t\tif (is_v6) {\n\t\t\t\t\t\tfe->vfe_v6 = 1;\n\t\t\t\t\t\tif (inet_pton(AF_INET6, ip, &fe->vfe_raddr.in6)) {\n\t\t\t\t\t\t\t\tstate.vs_ftable.erase(mac);\n\t\t\t\t\t\t\t\treturn EINVAL;\n\t\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\t\tfe->vfe_v6 = 0;\n\t\t\t\t\t\tif (inet_aton(ip, &fe->vfe_raddr.in4)) {\n\t\t\t\t\t\t\t\tstate.vs_ftable.erase(mac);\n\t\t\t\t\t\t\t\treturn EINVAL;\n\t\t\t\t\t\t}\n\t\t\t\t}\n\t\t}\n\t\treturn 0;\n}\n\nstatic int\nfte_remove_handler(cmdmap_t &map __unused, uint64_t seqno, vxstate_t &state, string &result)\n{\n\n\t\tresult = default_result(seqno);\n\t\treturn 0;\n}\n\nstatic int\nfte_get_handler(cmdmap_t &map __unused, uint64_t seqno, vxstate_t &state, string &result)\n{\n\n\t\treturn 0;\n}\n\nstatic int\nfte_get_all_handler(cmdmap_t &map __unused, uint64_t seqno, vxstate_t &state, string &result)\n{\n\n\t\treturn 0;\n}\n\n\nstatic int\nnd_phys_get_handler(cmdmap_t &map __unused, uint64_t seqno, vxstate_t &state, string &result)\n{\n\t\t\n\t\treturn 0;\n}\n\nstatic int\nnd_phys_set_handler(cmdmap_t &map __unused, uint64_t seqno, vxstate_t &state, string &result)\n{\n\t\t\n\t\treturn 0;\n}\n\nstatic int\nnd_phys_del_handler(cmdmap_t &map __unused, uint64_t seqno, vxstate_t &state, string &result)\n{\n\t\t\n\t\treturn 0;\n}\n\nstatic int\nnd_phys_get_all_handler(cmdmap_t &map __unused, uint64_t seqno, vxstate_t &state, string &result)\n{\n\t\t\n\t\treturn 0;\n}\n\n\nstatic int\nnd_vx_get_handler(cmdmap_t &map __unused, uint64_t seqno, vxstate_t &state, string &result)\n{\n\t\t\n\t\treturn 0;\n}\n\nstatic int\nnd_vx_set_handler(cmdmap_t &map __unused, uint64_t seqno, vxstate_t &state, string &result)\n{\n\t\t\n\t\treturn 0;\n}\n\nstatic int\nnd_vx_del_handler(cmdmap_t &map __unused, uint64_t seqno, vxstate_t &state, string &result)\n{\n\t\t\n\t\treturn 0;\n}\n\nstatic int\nnd_vx_get_all_handler(cmdmap_t &map __unused, uint64_t seqno, vxstate_t &state, string &result)\n{\n\t\t\n\t\treturn 0;\n}\n\n\nstatic int\nvm_vni_update_handler(cmdmap_t &map __unused, uint64_t seqno, vxstate_t &state, string &result)\n{\n\t\t\n\t\treturn 0;\n}\n\nstatic int\nvm_vni_remove_handler(cmdmap_t &map __unused, uint64_t seqno, vxstate_t &state, string &result)\n{\n\t\t\n\t\treturn 0;\n}\n\nstatic int\nvm_vni_get_handler(cmdmap_t &map __unused, uint64_t seqno, vxstate_t &state, string &result)\n{\n\t\treturn 0;\n}\n\nstatic int\nvm_vni_get_all_handler(cmdmap_t &map __unused, uint64_t seqno, vxstate_t &state, string &result)\n{\n\t\treturn 0;\n}\n\nstatic int\nroute_update_handler(cmdmap_t &map __unused, uint64_t seqno, vxstate_t &state, string &result)\n{\n\t\treturn 0;\n}\n\nstatic int\nroute_remove_handler(cmdmap_t &map __unused, uint64_t seqno, vxstate_t &state, string &result)\n{\n\t\treturn 0;\n}\n\ntypedef struct _ent {\n\t\tconst char *ent;\n\t\tcmdhandler_t handler;\n\t\tenum verb action;\n\t\tint pad0;\n} ent_t;\n\n#define KEYENT(action, handler) {#action, handler, action, 0} \n\n\nstatic ent_t ent_list[] = {\n\t\tKEYENT(VERB_UPDATE_FTE, fte_update_handler),\n\t\tKEYENT(VERB_REMOVE_FTE, fte_remove_handler),\n\t\tKEYENT(VERB_GET_FTE, fte_get_handler),\n\t\tKEYENT(VERB_GET_ALL_FTE, fte_get_all_handler),\n\n\t\tKEYENT(VERB_GET_PHYS_ND, nd_phys_get_handler),\n\t\tKEYENT(VERB_SET_PHYS_ND, nd_phys_set_handler),\n\t\tKEYENT(VERB_DEL_PHYS_ND, nd_phys_del_handler),\n\t\tKEYENT(VERB_GET_ALL_PHYS_ND, nd_phys_get_all_handler),\n\n\t\tKEYENT(VERB_UPDATE_VM_VNI, vm_vni_update_handler),\n\t\tKEYENT(VERB_REMOVE_VM_VNI, vm_vni_remove_handler),\n\t\tKEYENT(VERB_GET_VM_VNI, vm_vni_get_handler),\n\t\tKEYENT(VERB_GET_ALL_VM_VNI, vm_vni_get_all_handler),\n\n\t\tKEYENT(VERB_GET_VX_ND, nd_vx_get_handler),\n\t\tKEYENT(VERB_SET_VX_ND, nd_vx_set_handler),\n\t\tKEYENT(VERB_DEL_VX_ND, nd_vx_del_handler),\n\t\tKEYENT(VERB_GET_ALL_VX_ND, nd_vx_get_all_handler),\n\n\t\t\n\t\tKEYENT(VERB_UPDATE_DEFAULT_ROUTE, route_update_handler),\n\t\tKEYENT(VERB_REMOVE_DEFAULT_ROUTE, route_remove_handler),\n\n\t\tKEYENT(VERB_BAD, NULL) \/* must be last *\/\n};\n\nstatic void\ngather_args(cmdmap_t &map, char *input)\n{\n\t\tchar *indexp, *k, *tmp;\n\t\tconst char *delim = \" \";\n\t\tconst char *kvdelim = \":\";\n\n\t\twhile (input != NULL) {\n\t\t\t\tindexp = strsep(&input, delim);\n\t\t\t\tk = strsep(&indexp, kvdelim);\n\t\t\t\t\/* badly formed K:V pair *\/\n\t\t\t\tif (indexp == NULL)\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\/* STRING *\/\n\t\t\t\tif (indexp[0] == '\"') {\n\t\t\t\t\t\tindexp++;\n\t\t\t\t\t\tif ((tmp = index(indexp, '\"')) == NULL)\n\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t*tmp = '\\0';\n\t\t\t\t\t\tmap.insert(cmdent(string(k), parse_value(indexp)));\n\t\t\t\t}\n\t\t\t\t\/* NUMBER *\/\n\t\t\t\telse if (indexp[0] == '0' && indexp[1] == 'x') {\n\t\t\t\t\t\tuint64_t v;\n\t\t\t\t\t\tindexp += 2;\n\t\t\t\t\t\tv = static_cast<uint64_t>(strtoll(indexp, NULL, 16));\n\t\t\t\t\t\tmap.insert(cmdent(string(k), parse_value(v)));\n\t\t\t\t\t\t\n\t\t\t\t}\n\t\t\t\t\/* UNKNOWN *\/\n\t\t\t\telse\n\t\t\t\t\t\tcontinue;\n\t\t}\t\t\n}\n\nint\nparse_input(char *input, struct vxlan_state &state, string &result)\n{\n\t\tcmdmap_t map;\n\t\tconst char *delim = \" \";\n\t\tconst char *kvdelim = \":\";\n\t\tchar *indexp, *verbstr;\n\t\tent_t *verbent = ent_list;\n\t\tenum verb verb;\n\t\tuint64_t seqno;\n\n\t\tindexp = strsep(&input, delim);\n\t\tverbstr = strsep(&indexp, kvdelim);\n\t\tif (indexp == NULL || indexp[0] != '0' || indexp[1] != 'x')\n\t\t\t\treturn EINVAL;\n\t\tindexp += 2;\n\t\tseqno = static_cast<uint64_t>(strtoll(indexp, NULL, 16));\n\t\t\n\t\tfor (verbent = ent_list; verbent->action != VERB_BAD; verbent++) {\n\t\t\t\tif (!strcmp(verbent->ent, verbstr))\n\t\t\t\t\t\tbreak;\n\t\t}\n\t\tverb = verbent->action;\n\t\tif (verb == VERB_BAD)\n\t\t\t\treturn EINVAL;\n\t\tgather_args(map, input);\n\t\treturn verbent->handler(map, seqno, state, result);\n}\n\n<|endoftext|>"} {"text":"<commit_before>#include <karl\/storage.hpp>\n\n#include <karl\/util\/guard.hpp>\n\nnamespace supermarx\n{\n\nstorage::storage(std::string const& embedded_dir)\n{\n\tconst char *server_options[] = \\\n\t{\"test\", \"--innodb=OFF\", \"-h\", embedded_dir.c_str(), NULL};\n\tint num_options = (sizeof(server_options)\/sizeof(char*)) - 1;\n\tmysql_library_init(num_options, const_cast<char**>(server_options), NULL);\n\n\t{\n\t\tauto db = std::make_shared<rusql::Database>(rusql::Database::ConstructionInfo());\n\n\t\tauto result = db->select_query(\"show databases\");\n\t\tbool found_karl = false;\n\t\twhile(result){\n\t\t\tif(result.get<std::string>(\"Database\") == \"karl\"){\n\t\t\t\tfound_karl = true;\n\t\t\t}\n\t\t\tresult.next();\n\t\t}\n\t\tif(!found_karl){\n\t\t\tdb->execute(\"create database karl\");\n\t\t}\n\t}\n\n\tdatabase = std::make_shared<rusql::Database>(rusql::Database::ConstructionInfo(\"karl\"));\n\n\tupdate_database_schema();\n\tprepare_statements();\n}\n\nstorage::storage(const std::string &host, const std::string &user, const std::string &password, const std::string& db)\n\t: database(std::make_shared<rusql::Database>(rusql::Database::ConstructionInfo(host, 3306, user, password, db)))\n\t, prepared_statements()\n{\n\tupdate_database_schema();\n\tprepare_statements();\n}\n\nstorage::~storage()\n{\n\tprepared_statements.clear();\n\tdatabase.reset();\n\tmysql_library_end();\n}\n\nvoid storage::lock_products_read()\n{\n\t\/\/ LibRUSQL does not support grabbing a specific connection (yet), do not lock for now\n\t\/\/database->query(\"lock tables product read\");\n}\n\nvoid\nstorage::lock_products_write()\n{\n\t\/\/ LibRUSQL does not support grabbing a specific connection (yet), do not lock for now\n\t\/\/database->query(\"lock tables product write\");\n}\n\nvoid storage::unlock_all()\n{\n\t\/\/ LibRUSQL does not support grabbing a specific connection (yet), do not lock for now\n\t\/\/database->query(\"unlock tables\");\n}\n\nboost::optional<id_t> storage::find_product_unsafe(std::string const& identifier, id_t supermarket_id)\n{\n\tauto& qselect = *prepared_statements.at(statement::get_product_by_identifier);\n\tqselect.execute(identifier, supermarket_id);\n\n\tid_t product_id;\n\tqselect.bind_results(product_id);\n\n\tif(qselect.fetch())\n\t\treturn product_id;\n\n\treturn boost::none;\n}\n\nboost::optional<std::pair<id_t, product>> storage::fetch_last_productdetails_unsafe(id_t product_id)\n{\n\tauto& qolder = *prepared_statements.at(statement::get_last_productdetails_by_product);\n\tqolder.execute(product_id);\n\n\tid_t id;\n\tproduct p;\n\tstd::string raw_discount_condition, raw_valid_on, raw_retrieved_on;\n\n\tqolder.bind_results(id, p.identifier, p.name, p.orig_price, p.price, raw_discount_condition, raw_valid_on, raw_retrieved_on);\n\tif(!qolder.fetch())\n\t\treturn boost::none;\n\n\tp.discount_condition = to_condition(raw_discount_condition);\n\tp.valid_on = to_date(raw_valid_on);\n\tp.retrieved_on = to_datetime(raw_retrieved_on);\n\n\treturn std::make_pair(id, p);\n}\n\nid_t storage::find_add_product(std::string const& identifier, id_t supermarket_id)\n{\n\t{\n\t\tlock_products_read();\n\t\tguard unlocker([&]() {\n\t\t\tunlock_all();\n\t\t});\n\n\t\tauto product_id = find_product_unsafe(identifier, supermarket_id);\n\t\tif(product_id)\n\t\t\treturn product_id.get();\n\t}\n\n\t{\n\t\tlock_products_write();\n\t\tguard unlocker([&]() {\n\t\t\tunlock_all();\n\t\t});\n\n\t\tauto product_id = find_product_unsafe(identifier, supermarket_id);\n\t\tif(product_id)\n\t\t\treturn product_id.get();\n\n\t\tauto& qinsert = *prepared_statements.at(statement::add_product);\n\t\tqinsert.execute(identifier, supermarket_id);\n\t\treturn qinsert.insert_id();\n\t}\n}\n\nvoid storage::register_productdetailsrecord(id_t productdetails_id, datetime retrieved_on)\n{\n\tauto& q = *prepared_statements.at(statement::add_productdetailsrecord);\n\tq.execute(productdetails_id, to_string(retrieved_on));\n}\n\nvoid storage::add_product(product const& p, id_t supermarket_id)\n{\n\tid_t product_id = find_add_product(p.identifier, supermarket_id);\n\n\t\/\/ TODO Does not need locks, but does require a transaction\n\n\t\/\/ Check if an older version of the product exactly matches what we've got\n\tauto p_old_opt_kvp = fetch_last_productdetails_unsafe(product_id);\n\tif(p_old_opt_kvp)\n\t{\n\t\tproduct const& p_old = p_old_opt_kvp->second;\n\t\tbool similar = (\n\t\t\tp.discount_condition == p_old.discount_condition &&\n\t\t\tp.name == p_old.name &&\n\t\t\tp.orig_price == p_old.orig_price &&\n\t\t\tp.price == p_old.price\n\t\t);\n\n\t\tif(similar)\n\t\t{\n\t\t\tregister_productdetailsrecord(p_old_opt_kvp->first, p.retrieved_on);\n\t\t\treturn;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tauto& qinvalidate = *prepared_statements.at(statement::invalidate_productdetails);\n\t\t\tqinvalidate.execute(to_string(p.valid_on), product_id);\n\t\t}\n\t}\n\n\t\/\/TODO check if a newer entry is already entered. Perhaps invalidate that entry in such a case.\n\n\tauto& qadd = *prepared_statements.at(statement::add_productdetails);\n\tqadd.execute(product_id, p.name, p.orig_price, p.price, to_string(p.discount_condition), to_string(p.valid_on), to_string(p.retrieved_on));\n\tid_t productdetails_id = qadd.insert_id();\n\tstd::cerr << \"Inserted new productdetails \" << productdetails_id << \" for product \" << p.identifier << \" [\" << product_id << ']' << std::endl;\n\n\tregister_productdetailsrecord(productdetails_id, p.retrieved_on);\n}\n\nstd::vector<product> storage::get_products_by_name(std::string const& name, id_t supermarket_id)\n{\n\tlock_products_read();\n\tguard unlocker([&]() {\n\t\tunlock_all();\n\t});\n\n\trusql::PreparedStatement& query = *prepared_statements.at(statement::get_last_productdetails_by_name);\n\tquery.execute(std::string(\"%\") + name + \"%\", supermarket_id);\n\n\tstd::vector<product> products;\n\tproduct row;\n\tstd::string raw_discount_condition, raw_valid_on, raw_retrieved_on;\n\n\tquery.bind_results(row.identifier, row.name, row.orig_price, row.price, raw_discount_condition, raw_valid_on, raw_retrieved_on);\n\twhile(query.fetch())\n\t{\n\t\trow.discount_condition = to_condition(raw_discount_condition);\n\t\trow.valid_on = to_date(raw_valid_on);\n\t\trow.retrieved_on = to_datetime(raw_retrieved_on);\n\n\t\tproducts.push_back(row);\n\t}\n\n\treturn products;\n}\n\nvoid storage::update_database_schema()\n{\n\tbool product_found = false;\n\tbool productdetails_found = false;\n\tbool productdetailsrecord_found = false;\n\tbool supermarket_found = false;\n\n\tauto result = database->select_query(\"show tables\");\n\twhile(result)\n\t{\n\t\tstd::string tablename = result.get<std::string>(0);\n\t\tif(tablename == \"product\")\n\t\t\tproduct_found = true;\n\t\telse if(tablename == \"productdetails\")\n\t\t\tproductdetails_found = true;\n\t\telse if(tablename == \"productdetailsrecord\")\n\t\t\tproductdetailsrecord_found = true;\n\t\telse if(tablename == \"supermarket\")\n\t\t\tsupermarket_found = true;\n\n\t\tresult.next();\n\t}\n\n\tif(!product_found)\n\t\tdatabase->execute(std::string() +\n\t\t\t\"create table `product` (\"+\n\t\t\t\"`id` int(11) unsigned not null auto_increment,\"+\n\t\t\t\"`identifier` varchar(1024) not null,\"+\n\t\t\t\"`supermarket_id` int(11) unsigned null,\"+\n\t\t\t\"primary key (`id`),\"+\n\t\t\t\"key `supermarket_id` (`supermarket_id`)\"+\n\t\t\t\") character set utf8 collate utf8_bin\");\n\n\tif(!productdetails_found)\n\t\tdatabase->execute(std::string() +\n\t\t\t\"create table `productdetails` (\" +\n\t\t\t\"`id` int(10) unsigned not null auto_increment,\" +\n\t\t\t\"`product_id` int(10) unsigned not null,\" +\n\t\t\t\"`name` varchar(1024) character set utf8 not null,\" +\n\t\t\t\"`orig_price` int not null,\" +\n\t\t\t\"`price` int not null,\" +\n\t\t\t\"`discount_condition` enum('ALWAYS','AT_TWO','AT_THREE') not null,\" +\n\t\t\t\"`valid_on` date not null,\" +\n\t\t\t\"`valid_until` date,\" +\n\t\t\t\"`retrieved_on` datetime not null,\" +\n\t\t\t\"primary key (`id`),\" +\n\t\t\t\"key `product_id` (`product_id`)\" +\n\t\t\t\") character set utf8 collate utf8_bin\");\n\n\tif(!productdetailsrecord_found)\n\t\tdatabase->execute(std::string() +\n\t\t\t\"create table `productdetailsrecord` (\" +\n\t\t\t\"`id` int(10) unsigned not null auto_increment,\" +\n\t\t\t\"`productdetails_id` int(10) unsigned not null,\" +\n\t\t\t\"`retrieved_on` datetime not null,\" +\n\t\t\t\"primary key (`id`),\" +\n\t\t\t\"key `productdetails_id` (`productdetails_id`)\" +\n\t\t\t\") character set utf8 collate utf8_bin\");\n\n\tif(!supermarket_found)\n\t\tdatabase->execute(std::string() +\n\t\t\t\"create table `supermarket` (\" +\n\t\t\t\"`id` int(11) unsigned not null auto_increment,\" +\n\t\t\t\"`name` varchar(1024) not null,\" +\n\t\t\t\"primary key (`id`)\" +\n\t\t\t\") character set utf8 collate utf8_bin\");\n}\n\nvoid storage::prepare_statements()\n{\n\tauto create_statement =\n\t\t\t[&](statement const& s, std::string const& query)\n\t{\n\t\tprepared_statements[s] = std::make_shared<rusql::PreparedStatement>(database->prepare(query));\n\t};\n\n\tdatabase->query(\"SET NAMES 'utf8'\");\n\tdatabase->query(\"SET CHARACTER SET utf8\");\n\n\tcreate_statement(statement::add_product, \"insert into product (identifier, supermarket_id) values (?, ?)\");\n\tcreate_statement(statement::get_product_by_identifier, \"select product.id from product where product.identifier = ? and product.supermarket_id = ?\");\n\n\tcreate_statement(statement::add_productdetails, \"insert into productdetails (product_id, name, orig_price, price, discount_condition, valid_on, valid_until, retrieved_on) values(?, ?, ?, ?, ?, ?, NULL, ?)\");\n\tcreate_statement(statement::add_productdetailsrecord, \"insert into productdetailsrecord (productdetails_id, retrieved_on) values(?, ?)\");\n\n\tcreate_statement(statement::get_last_productdetails_by_product, \"select productdetails.id, product.identifier, productdetails.name, productdetails.orig_price, productdetails.price, productdetails.discount_condition, productdetails.valid_on, productdetails.retrieved_on from product inner join productdetails on (product.id = productdetails.product_id) where productdetails.product_id = ? AND productdetails.valid_until is NULL\");\n\tcreate_statement(statement::get_last_productdetails_by_name, \"select product.identifier, productdetails.name, productdetails.orig_price, productdetails.price, productdetails.discount_condition, productdetails.valid_on, productdetails.retrieved_on from product inner join productdetails on (product.id = productdetails.product_id) where productdetails.name LIKE ? AND productdetails.valid_until is NULL AND product.supermarket_id = ?\");\n\tcreate_statement(statement::invalidate_productdetails, \"update productdetails set productdetails.valid_until = ? where productdetails.valid_until is null and productdetails.product_id = ?\");\n}\n\n}\n<commit_msg>Added ci collation<commit_after>#include <karl\/storage.hpp>\n\n#include <karl\/util\/guard.hpp>\n\nnamespace supermarx\n{\n\nstorage::storage(std::string const& embedded_dir)\n{\n\tconst char *server_options[] = \\\n\t{\"test\", \"--innodb=OFF\", \"-h\", embedded_dir.c_str(), NULL};\n\tint num_options = (sizeof(server_options)\/sizeof(char*)) - 1;\n\tmysql_library_init(num_options, const_cast<char**>(server_options), NULL);\n\n\t{\n\t\tauto db = std::make_shared<rusql::Database>(rusql::Database::ConstructionInfo());\n\n\t\tauto result = db->select_query(\"show databases\");\n\t\tbool found_karl = false;\n\t\twhile(result){\n\t\t\tif(result.get<std::string>(\"Database\") == \"karl\"){\n\t\t\t\tfound_karl = true;\n\t\t\t}\n\t\t\tresult.next();\n\t\t}\n\t\tif(!found_karl){\n\t\t\tdb->execute(\"create database karl\");\n\t\t}\n\t}\n\n\tdatabase = std::make_shared<rusql::Database>(rusql::Database::ConstructionInfo(\"karl\"));\n\n\tupdate_database_schema();\n\tprepare_statements();\n}\n\nstorage::storage(const std::string &host, const std::string &user, const std::string &password, const std::string& db)\n\t: database(std::make_shared<rusql::Database>(rusql::Database::ConstructionInfo(host, 3306, user, password, db)))\n\t, prepared_statements()\n{\n\tupdate_database_schema();\n\tprepare_statements();\n}\n\nstorage::~storage()\n{\n\tprepared_statements.clear();\n\tdatabase.reset();\n\tmysql_library_end();\n}\n\nvoid storage::lock_products_read()\n{\n\t\/\/ LibRUSQL does not support grabbing a specific connection (yet), do not lock for now\n\t\/\/database->query(\"lock tables product read\");\n}\n\nvoid\nstorage::lock_products_write()\n{\n\t\/\/ LibRUSQL does not support grabbing a specific connection (yet), do not lock for now\n\t\/\/database->query(\"lock tables product write\");\n}\n\nvoid storage::unlock_all()\n{\n\t\/\/ LibRUSQL does not support grabbing a specific connection (yet), do not lock for now\n\t\/\/database->query(\"unlock tables\");\n}\n\nboost::optional<id_t> storage::find_product_unsafe(std::string const& identifier, id_t supermarket_id)\n{\n\tauto& qselect = *prepared_statements.at(statement::get_product_by_identifier);\n\tqselect.execute(identifier, supermarket_id);\n\n\tid_t product_id;\n\tqselect.bind_results(product_id);\n\n\tif(qselect.fetch())\n\t\treturn product_id;\n\n\treturn boost::none;\n}\n\nboost::optional<std::pair<id_t, product>> storage::fetch_last_productdetails_unsafe(id_t product_id)\n{\n\tauto& qolder = *prepared_statements.at(statement::get_last_productdetails_by_product);\n\tqolder.execute(product_id);\n\n\tid_t id;\n\tproduct p;\n\tstd::string raw_discount_condition, raw_valid_on, raw_retrieved_on;\n\n\tqolder.bind_results(id, p.identifier, p.name, p.orig_price, p.price, raw_discount_condition, raw_valid_on, raw_retrieved_on);\n\tif(!qolder.fetch())\n\t\treturn boost::none;\n\n\tp.discount_condition = to_condition(raw_discount_condition);\n\tp.valid_on = to_date(raw_valid_on);\n\tp.retrieved_on = to_datetime(raw_retrieved_on);\n\n\treturn std::make_pair(id, p);\n}\n\nid_t storage::find_add_product(std::string const& identifier, id_t supermarket_id)\n{\n\t{\n\t\tlock_products_read();\n\t\tguard unlocker([&]() {\n\t\t\tunlock_all();\n\t\t});\n\n\t\tauto product_id = find_product_unsafe(identifier, supermarket_id);\n\t\tif(product_id)\n\t\t\treturn product_id.get();\n\t}\n\n\t{\n\t\tlock_products_write();\n\t\tguard unlocker([&]() {\n\t\t\tunlock_all();\n\t\t});\n\n\t\tauto product_id = find_product_unsafe(identifier, supermarket_id);\n\t\tif(product_id)\n\t\t\treturn product_id.get();\n\n\t\tauto& qinsert = *prepared_statements.at(statement::add_product);\n\t\tqinsert.execute(identifier, supermarket_id);\n\t\treturn qinsert.insert_id();\n\t}\n}\n\nvoid storage::register_productdetailsrecord(id_t productdetails_id, datetime retrieved_on)\n{\n\tauto& q = *prepared_statements.at(statement::add_productdetailsrecord);\n\tq.execute(productdetails_id, to_string(retrieved_on));\n}\n\nvoid storage::add_product(product const& p, id_t supermarket_id)\n{\n\tid_t product_id = find_add_product(p.identifier, supermarket_id);\n\n\t\/\/ TODO Does not need locks, but does require a transaction\n\n\t\/\/ Check if an older version of the product exactly matches what we've got\n\tauto p_old_opt_kvp = fetch_last_productdetails_unsafe(product_id);\n\tif(p_old_opt_kvp)\n\t{\n\t\tproduct const& p_old = p_old_opt_kvp->second;\n\t\tbool similar = (\n\t\t\tp.discount_condition == p_old.discount_condition &&\n\t\t\tp.name == p_old.name &&\n\t\t\tp.orig_price == p_old.orig_price &&\n\t\t\tp.price == p_old.price\n\t\t);\n\n\t\tif(similar)\n\t\t{\n\t\t\tregister_productdetailsrecord(p_old_opt_kvp->first, p.retrieved_on);\n\t\t\treturn;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tauto& qinvalidate = *prepared_statements.at(statement::invalidate_productdetails);\n\t\t\tqinvalidate.execute(to_string(p.valid_on), product_id);\n\t\t}\n\t}\n\n\t\/\/TODO check if a newer entry is already entered. Perhaps invalidate that entry in such a case.\n\n\tauto& qadd = *prepared_statements.at(statement::add_productdetails);\n\tqadd.execute(product_id, p.name, p.orig_price, p.price, to_string(p.discount_condition), to_string(p.valid_on), to_string(p.retrieved_on));\n\tid_t productdetails_id = qadd.insert_id();\n\tstd::cerr << \"Inserted new productdetails \" << productdetails_id << \" for product \" << p.identifier << \" [\" << product_id << ']' << std::endl;\n\n\tregister_productdetailsrecord(productdetails_id, p.retrieved_on);\n}\n\nstd::vector<product> storage::get_products_by_name(std::string const& name, id_t supermarket_id)\n{\n\tlock_products_read();\n\tguard unlocker([&]() {\n\t\tunlock_all();\n\t});\n\n\trusql::PreparedStatement& query = *prepared_statements.at(statement::get_last_productdetails_by_name);\n\tquery.execute(std::string(\"%\") + name + \"%\", supermarket_id);\n\n\tstd::vector<product> products;\n\tproduct row;\n\tstd::string raw_discount_condition, raw_valid_on, raw_retrieved_on;\n\n\tquery.bind_results(row.identifier, row.name, row.orig_price, row.price, raw_discount_condition, raw_valid_on, raw_retrieved_on);\n\twhile(query.fetch())\n\t{\n\t\trow.discount_condition = to_condition(raw_discount_condition);\n\t\trow.valid_on = to_date(raw_valid_on);\n\t\trow.retrieved_on = to_datetime(raw_retrieved_on);\n\n\t\tproducts.push_back(row);\n\t}\n\n\treturn products;\n}\n\nvoid storage::update_database_schema()\n{\n\tbool product_found = false;\n\tbool productdetails_found = false;\n\tbool productdetailsrecord_found = false;\n\tbool supermarket_found = false;\n\n\tauto result = database->select_query(\"show tables\");\n\twhile(result)\n\t{\n\t\tstd::string tablename = result.get<std::string>(0);\n\t\tif(tablename == \"product\")\n\t\t\tproduct_found = true;\n\t\telse if(tablename == \"productdetails\")\n\t\t\tproductdetails_found = true;\n\t\telse if(tablename == \"productdetailsrecord\")\n\t\t\tproductdetailsrecord_found = true;\n\t\telse if(tablename == \"supermarket\")\n\t\t\tsupermarket_found = true;\n\n\t\tresult.next();\n\t}\n\n\tif(!product_found)\n\t\tdatabase->execute(std::string() +\n\t\t\t\"create table `product` (\"+\n\t\t\t\"`id` int(11) unsigned not null auto_increment,\"+\n\t\t\t\"`identifier` varchar(1024) not null,\"+\n\t\t\t\"`supermarket_id` int(11) unsigned null,\"+\n\t\t\t\"primary key (`id`),\"+\n\t\t\t\"key `supermarket_id` (`supermarket_id`)\"+\n\t\t\t\") character set utf8 collate utf8_bin\");\n\n\tif(!productdetails_found)\n\t\tdatabase->execute(std::string() +\n\t\t\t\"create table `productdetails` (\" +\n\t\t\t\"`id` int(10) unsigned not null auto_increment,\" +\n\t\t\t\"`product_id` int(10) unsigned not null,\" +\n\t\t\t\"`name` varchar(1024) character set utf8 not null,\" +\n\t\t\t\"`orig_price` int not null,\" +\n\t\t\t\"`price` int not null,\" +\n\t\t\t\"`discount_condition` enum('ALWAYS','AT_TWO','AT_THREE') not null,\" +\n\t\t\t\"`valid_on` date not null,\" +\n\t\t\t\"`valid_until` date,\" +\n\t\t\t\"`retrieved_on` datetime not null,\" +\n\t\t\t\"primary key (`id`),\" +\n\t\t\t\"key `product_id` (`product_id`)\" +\n\t\t\t\") character set utf8 collate utf8_bin\");\n\n\tif(!productdetailsrecord_found)\n\t\tdatabase->execute(std::string() +\n\t\t\t\"create table `productdetailsrecord` (\" +\n\t\t\t\"`id` int(10) unsigned not null auto_increment,\" +\n\t\t\t\"`productdetails_id` int(10) unsigned not null,\" +\n\t\t\t\"`retrieved_on` datetime not null,\" +\n\t\t\t\"primary key (`id`),\" +\n\t\t\t\"key `productdetails_id` (`productdetails_id`)\" +\n\t\t\t\") character set utf8 collate utf8_bin\");\n\n\tif(!supermarket_found)\n\t\tdatabase->execute(std::string() +\n\t\t\t\"create table `supermarket` (\" +\n\t\t\t\"`id` int(11) unsigned not null auto_increment,\" +\n\t\t\t\"`name` varchar(1024) not null,\" +\n\t\t\t\"primary key (`id`)\" +\n\t\t\t\") character set utf8 collate utf8_bin\");\n}\n\nvoid storage::prepare_statements()\n{\n\tauto create_statement =\n\t\t\t[&](statement const& s, std::string const& query)\n\t{\n\t\tprepared_statements[s] = std::make_shared<rusql::PreparedStatement>(database->prepare(query));\n\t};\n\n\tdatabase->query(\"SET NAMES 'utf8'\");\n\tdatabase->query(\"SET CHARACTER SET utf8\");\n\n\tcreate_statement(statement::add_product, \"insert into product (identifier, supermarket_id) values (?, ?)\");\n\tcreate_statement(statement::get_product_by_identifier, \"select product.id from product where product.identifier = ? and product.supermarket_id = ?\");\n\n\tcreate_statement(statement::add_productdetails, \"insert into productdetails (product_id, name, orig_price, price, discount_condition, valid_on, valid_until, retrieved_on) values(?, ?, ?, ?, ?, ?, NULL, ?)\");\n\tcreate_statement(statement::add_productdetailsrecord, \"insert into productdetailsrecord (productdetails_id, retrieved_on) values(?, ?)\");\n\n\tcreate_statement(statement::get_last_productdetails_by_product, \"select productdetails.id, product.identifier, productdetails.name, productdetails.orig_price, productdetails.price, productdetails.discount_condition, productdetails.valid_on, productdetails.retrieved_on from product inner join productdetails on (product.id = productdetails.product_id) where productdetails.product_id = ? AND productdetails.valid_until is NULL\");\n\tcreate_statement(statement::get_last_productdetails_by_name, \"select product.identifier, productdetails.name, productdetails.orig_price, productdetails.price, productdetails.discount_condition, productdetails.valid_on, productdetails.retrieved_on from product inner join productdetails on (product.id = productdetails.product_id) where productdetails.name like ? collate utf8_general_ci AND productdetails.valid_until is NULL AND product.supermarket_id = ?\");\n\tcreate_statement(statement::invalidate_productdetails, \"update productdetails set productdetails.valid_until = ? where productdetails.valid_until is null and productdetails.product_id = ?\");\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2014 The Bitcoin developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \"timedata.h\"\n\n#include \"netbase.h\"\n#include \"sync.h\"\n#include \"ui_interface.h\"\n#include \"util.h\"\n#include \"utilstrencodings.h\"\n\n#include <boost\/foreach.hpp>\n\nusing namespace std;\n\nstatic CCriticalSection cs_nTimeOffset;\nstatic int64_t nTimeOffset = 0;\n\n\/**\n * \"Never go to sea with two chronometers; take one or three.\"\n * Our three time sources are:\n * - System clock\n * - Median of other nodes clocks\n * - The user (asking the user to fix the system clock if the first two disagree)\n *\/\nint64_t GetTimeOffset()\n{\n LOCK(cs_nTimeOffset);\n return nTimeOffset;\n}\n\nint64_t GetAdjustedTime()\n{\n return GetTime() + GetTimeOffset();\n}\n\nstatic int64_t abs64(int64_t n)\n{\n return (n >= 0 ? n : -n);\n}\n\nvoid AddTimeData(const CNetAddr& ip, int64_t nTime)\n{\n int64_t nOffsetSample = nTime - GetTime();\n\n LOCK(cs_nTimeOffset);\n \/\/ Ignore duplicates\n static set<CNetAddr> setKnown;\n if (!setKnown.insert(ip).second)\n return;\n\n \/\/ Add data\n static CMedianFilter<int64_t> vTimeOffsets(200,0);\n vTimeOffsets.input(nOffsetSample);\n LogPrintf(\"Added time data, samples %d, offset %+d (%+d minutes)\\n\", vTimeOffsets.size(), nOffsetSample, nOffsetSample\/60);\n\n \/\/ There is a known issue here (see issue #4521):\n \/\/\n \/\/ - The structure vTimeOffsets contains up to 200 elements, after which\n \/\/ any new element added to it will not increase its size, replacing the\n \/\/ oldest element.\n \/\/\n \/\/ - The condition to update nTimeOffset includes checking whether the\n \/\/ number of elements in vTimeOffsets is odd, which will never happen after\n \/\/ there are 200 elements.\n \/\/\n \/\/ But in this case the 'bug' is protective against some attacks, and may\n \/\/ actually explain why we've never seen attacks which manipulate the\n \/\/ clock offset.\n \/\/\n \/\/ So we should hold off on fixing this and clean it up as part of\n \/\/ a timing cleanup that strengthens it in a number of other ways.\n \/\/\n if (vTimeOffsets.size() >= 5 && vTimeOffsets.size() % 2 == 1)\n {\n int64_t nMedian = vTimeOffsets.median();\n std::vector<int64_t> vSorted = vTimeOffsets.sorted();\n \/\/ Only let other nodes change our time by so much\n if (abs64(nMedian) < 70 * 60)\n {\n nTimeOffset = nMedian;\n }\n else\n {\n nTimeOffset = 0;\n\n static bool fDone;\n if (!fDone)\n {\n \/\/ If nobody has a time different than ours but within 5 minutes of ours, give a warning\n bool fMatch = false;\n BOOST_FOREACH(int64_t nOffset, vSorted)\n if (nOffset != 0 && abs64(nOffset) < 5 * 60)\n fMatch = true;\n\n if (!fMatch)\n {\n fDone = true;\n string strMessage = _(\"Warning: Please check that your computer's date and time are correct! If your clock is wrong Bitcoin Core will not work properly.\");\n strMiscWarning = strMessage;\n LogPrintf(\"*** %s\\n\", strMessage);\n uiInterface.ThreadSafeMessageBox(strMessage, \"\", CClientUIInterface::MSG_WARNING);\n }\n }\n }\n if (fDebug) {\n BOOST_FOREACH(int64_t n, vSorted)\n LogPrintf(\"%+d \", n);\n LogPrintf(\"| \");\n }\n LogPrintf(\"nTimeOffset = %+d (%+d minutes)\\n\", nTimeOffset, nTimeOffset\/60);\n }\n}\n<commit_msg>Do not store more than 200 timedata samples.<commit_after>\/\/ Copyright (c) 2014 The Bitcoin developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \"timedata.h\"\n\n#include \"netbase.h\"\n#include \"sync.h\"\n#include \"ui_interface.h\"\n#include \"util.h\"\n#include \"utilstrencodings.h\"\n\n#include <boost\/foreach.hpp>\n\nusing namespace std;\n\nstatic CCriticalSection cs_nTimeOffset;\nstatic int64_t nTimeOffset = 0;\n\n\/**\n * \"Never go to sea with two chronometers; take one or three.\"\n * Our three time sources are:\n * - System clock\n * - Median of other nodes clocks\n * - The user (asking the user to fix the system clock if the first two disagree)\n *\/\nint64_t GetTimeOffset()\n{\n LOCK(cs_nTimeOffset);\n return nTimeOffset;\n}\n\nint64_t GetAdjustedTime()\n{\n return GetTime() + GetTimeOffset();\n}\n\nstatic int64_t abs64(int64_t n)\n{\n return (n >= 0 ? n : -n);\n}\n\n#define BITCOIN_TIMEDATA_MAX_SAMPLES 200\n\nvoid AddTimeData(const CNetAddr& ip, int64_t nTime)\n{\n int64_t nOffsetSample = nTime - GetTime();\n\n LOCK(cs_nTimeOffset);\n \/\/ Ignore duplicates\n static set<CNetAddr> setKnown;\n if (setKnown.size() == BITCOIN_TIMEDATA_MAX_SAMPLES)\n return;\n if (!setKnown.insert(ip).second)\n return;\n\n \/\/ Add data\n static CMedianFilter<int64_t> vTimeOffsets(BITCOIN_TIMEDATA_MAX_SAMPLES, 0);\n vTimeOffsets.input(nOffsetSample);\n LogPrintf(\"Added time data, samples %d, offset %+d (%+d minutes)\\n\", vTimeOffsets.size(), nOffsetSample, nOffsetSample\/60);\n\n \/\/ There is a known issue here (see issue #4521):\n \/\/\n \/\/ - The structure vTimeOffsets contains up to 200 elements, after which\n \/\/ any new element added to it will not increase its size, replacing the\n \/\/ oldest element.\n \/\/\n \/\/ - The condition to update nTimeOffset includes checking whether the\n \/\/ number of elements in vTimeOffsets is odd, which will never happen after\n \/\/ there are 200 elements.\n \/\/\n \/\/ But in this case the 'bug' is protective against some attacks, and may\n \/\/ actually explain why we've never seen attacks which manipulate the\n \/\/ clock offset.\n \/\/\n \/\/ So we should hold off on fixing this and clean it up as part of\n \/\/ a timing cleanup that strengthens it in a number of other ways.\n \/\/\n if (vTimeOffsets.size() >= 5 && vTimeOffsets.size() % 2 == 1)\n {\n int64_t nMedian = vTimeOffsets.median();\n std::vector<int64_t> vSorted = vTimeOffsets.sorted();\n \/\/ Only let other nodes change our time by so much\n if (abs64(nMedian) < 70 * 60)\n {\n nTimeOffset = nMedian;\n }\n else\n {\n nTimeOffset = 0;\n\n static bool fDone;\n if (!fDone)\n {\n \/\/ If nobody has a time different than ours but within 5 minutes of ours, give a warning\n bool fMatch = false;\n BOOST_FOREACH(int64_t nOffset, vSorted)\n if (nOffset != 0 && abs64(nOffset) < 5 * 60)\n fMatch = true;\n\n if (!fMatch)\n {\n fDone = true;\n string strMessage = _(\"Warning: Please check that your computer's date and time are correct! If your clock is wrong Bitcoin Core will not work properly.\");\n strMiscWarning = strMessage;\n LogPrintf(\"*** %s\\n\", strMessage);\n uiInterface.ThreadSafeMessageBox(strMessage, \"\", CClientUIInterface::MSG_WARNING);\n }\n }\n }\n if (fDebug) {\n BOOST_FOREACH(int64_t n, vSorted)\n LogPrintf(\"%+d \", n);\n LogPrintf(\"| \");\n }\n LogPrintf(\"nTimeOffset = %+d (%+d minutes)\\n\", nTimeOffset, nTimeOffset\/60);\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * The Apache Software License, Version 1.1\n *\n * Copyright (c) 2001 The Apache Software Foundation. All rights\n * reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n *\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in\n * the documentation and\/or other materials provided with the\n * distribution.\n *\n * 3. The end-user documentation included with the redistribution,\n * if any, must include the following acknowledgment:\n * \"This product includes software developed by the\n * Apache Software Foundation (http:\/\/www.apache.org\/).\"\n * Alternately, this acknowledgment may appear in the software itself,\n * if and wherever such third-party acknowledgments normally appear.\n *\n * 4. The names \"Xerces\" and \"Apache Software Foundation\" must\n * not be used to endorse or promote products derived from this\n * software without prior written permission. For written\n * permission, please contact apache\\@apache.org.\n *\n * 5. Products derived from this software may not be called \"Apache\",\n * nor may \"Apache\" appear in their name, without prior written\n * permission of the Apache Software Foundation.\n *\n * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED\n * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR\n * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF\n * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT\n * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n * ====================================================================\n *\n * This software consists of voluntary contributions made by many\n * individuals on behalf of the Apache Software Foundation, and was\n * originally based on software copyright (c) 1999, International\n * Business Machines, Inc., http:\/\/www.ibm.com . For more information\n * on the Apache Software Foundation, please see\n * <http:\/\/www.apache.org\/>.\n *\/\n\n\/*\n * $Log$\n * Revision 1.7 2003\/12\/17 00:18:41 cargilld\n * Update to memory management so that the static memory manager (one used to call Initialize) is only for static data.\n *\n * Revision 1.6 2003\/12\/16 18:41:15 knoaman\n * Make IC_Field stateless\n *\n * Revision 1.5 2003\/05\/22 02:10:52 knoaman\n * Default the memory manager.\n *\n * Revision 1.4 2003\/05\/15 18:59:34 knoaman\n * Partial implementation of the configurable memory manager.\n *\n * Revision 1.3 2002\/11\/04 14:47:41 tng\n * C++ Namespace Support.\n *\n * Revision 1.2 2002\/08\/27 05:56:19 knoaman\n * Identity Constraint: handle case of recursive elements.\n *\n * Revision 1.1.1.1 2002\/02\/01 22:22:50 peiyongz\n * sane_include\n *\n * Revision 1.1 2001\/11\/02 14:08:40 knoaman\n * Add support for identity constraints.\n *\n *\/\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ Includes\n\/\/ ---------------------------------------------------------------------------\n#include <xercesc\/validators\/schema\/identity\/FieldActivator.hpp>\n#include <xercesc\/validators\/schema\/identity\/ValueStore.hpp>\n#include <xercesc\/validators\/schema\/identity\/ValueStoreCache.hpp>\n#include <xercesc\/validators\/schema\/identity\/XPathMatcherStack.hpp>\n#include <xercesc\/util\/HashPtr.hpp>\n\nXERCES_CPP_NAMESPACE_BEGIN\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ FieldActivator: Constructors and Destructor\n\/\/ ---------------------------------------------------------------------------\nFieldActivator::FieldActivator(ValueStoreCache* const valueStoreCache,\n XPathMatcherStack* const matcherStack,\n MemoryManager* const manager)\n : fValueStoreCache(valueStoreCache)\n , fMatcherStack(matcherStack)\n , fMayMatch(0)\n , fMemoryManager(manager)\n{\n fMayMatch = new (manager) ValueHashTableOf<bool>(29, new (manager) HashPtr(), manager);\n}\n\nFieldActivator::FieldActivator(const FieldActivator& other)\n : fValueStoreCache(other.fValueStoreCache)\n , fMatcherStack(other.fMatcherStack)\n , fMayMatch(0)\n , fMemoryManager(other.fMemoryManager)\n{\n fMayMatch = new (fMemoryManager) ValueHashTableOf<bool>(29, new (fMemoryManager) HashPtr(), fMemoryManager);\n ValueHashTableOfEnumerator<bool> mayMatchEnum(other.fMayMatch, false, fMemoryManager);\n\n \/\/ Build key set\n while (mayMatchEnum.hasMoreElements())\n {\n IC_Field* field = (IC_Field*) mayMatchEnum.nextElementKey();\n fMayMatch->put(field, other.fMayMatch->get(field));\n }\n}\n\n\nFieldActivator::~FieldActivator()\n{\n}\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ FieldActivator: Operator methods\n\/\/ ---------------------------------------------------------------------------\nFieldActivator& FieldActivator::operator =(const FieldActivator& other) {\n\n if (this == &other) {\n return *this;\n }\n\n fValueStoreCache = other.fValueStoreCache;\n fMatcherStack = other.fMatcherStack;\n return *this;\n}\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ FieldActivator: Operator methods\n\/\/ ---------------------------------------------------------------------------\nXPathMatcher* FieldActivator::activateField(IC_Field* const field, const int initialDepth) {\n\n ValueStore* valueStore = fValueStoreCache->getValueStoreFor(field, initialDepth);\n XPathMatcher* matcher = field->createMatcher(this, valueStore, fMemoryManager);\n\n setMayMatch(field, true);\n fMatcherStack->addMatcher(matcher);\n matcher->startDocumentFragment();\n\n return matcher;\n}\n\nvoid FieldActivator::startValueScopeFor(const IdentityConstraint* const ic,\n const int initialDepth) {\n\n unsigned int fieldCount = ic->getFieldCount();\n\n for(unsigned int i=0; i<fieldCount; i++) {\n\n const IC_Field* field = ic->getFieldAt(i);\n ValueStore* valueStore = fValueStoreCache->getValueStoreFor(field, initialDepth);\n\n valueStore->startValueScope();\n }\n}\n\nvoid FieldActivator::endValueScopeFor(const IdentityConstraint* const ic, const int initialDepth) {\n\n ValueStore* valueStore = fValueStoreCache->getValueStoreFor(ic, initialDepth);\n\n valueStore->endValueScope();\n}\n\nXERCES_CPP_NAMESPACE_END\n\n\/**\n * End of file FieldActivator.cpp\n *\/\n\n<commit_msg>Fix memhandlertest failure (memory not deleted).<commit_after>\/*\n * The Apache Software License, Version 1.1\n *\n * Copyright (c) 2001 The Apache Software Foundation. All rights\n * reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n *\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in\n * the documentation and\/or other materials provided with the\n * distribution.\n *\n * 3. The end-user documentation included with the redistribution,\n * if any, must include the following acknowledgment:\n * \"This product includes software developed by the\n * Apache Software Foundation (http:\/\/www.apache.org\/).\"\n * Alternately, this acknowledgment may appear in the software itself,\n * if and wherever such third-party acknowledgments normally appear.\n *\n * 4. The names \"Xerces\" and \"Apache Software Foundation\" must\n * not be used to endorse or promote products derived from this\n * software without prior written permission. For written\n * permission, please contact apache\\@apache.org.\n *\n * 5. Products derived from this software may not be called \"Apache\",\n * nor may \"Apache\" appear in their name, without prior written\n * permission of the Apache Software Foundation.\n *\n * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED\n * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR\n * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF\n * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT\n * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n * ====================================================================\n *\n * This software consists of voluntary contributions made by many\n * individuals on behalf of the Apache Software Foundation, and was\n * originally based on software copyright (c) 1999, International\n * Business Machines, Inc., http:\/\/www.ibm.com . For more information\n * on the Apache Software Foundation, please see\n * <http:\/\/www.apache.org\/>.\n *\/\n\n\/*\n * $Log$\n * Revision 1.8 2003\/12\/17 01:13:10 cargilld\n * Fix memhandlertest failure (memory not deleted).\n *\n * Revision 1.7 2003\/12\/17 00:18:41 cargilld\n * Update to memory management so that the static memory manager (one used to call Initialize) is only for static data.\n *\n * Revision 1.6 2003\/12\/16 18:41:15 knoaman\n * Make IC_Field stateless\n *\n * Revision 1.5 2003\/05\/22 02:10:52 knoaman\n * Default the memory manager.\n *\n * Revision 1.4 2003\/05\/15 18:59:34 knoaman\n * Partial implementation of the configurable memory manager.\n *\n * Revision 1.3 2002\/11\/04 14:47:41 tng\n * C++ Namespace Support.\n *\n * Revision 1.2 2002\/08\/27 05:56:19 knoaman\n * Identity Constraint: handle case of recursive elements.\n *\n * Revision 1.1.1.1 2002\/02\/01 22:22:50 peiyongz\n * sane_include\n *\n * Revision 1.1 2001\/11\/02 14:08:40 knoaman\n * Add support for identity constraints.\n *\n *\/\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ Includes\n\/\/ ---------------------------------------------------------------------------\n#include <xercesc\/validators\/schema\/identity\/FieldActivator.hpp>\n#include <xercesc\/validators\/schema\/identity\/ValueStore.hpp>\n#include <xercesc\/validators\/schema\/identity\/ValueStoreCache.hpp>\n#include <xercesc\/validators\/schema\/identity\/XPathMatcherStack.hpp>\n#include <xercesc\/util\/HashPtr.hpp>\n\nXERCES_CPP_NAMESPACE_BEGIN\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ FieldActivator: Constructors and Destructor\n\/\/ ---------------------------------------------------------------------------\nFieldActivator::FieldActivator(ValueStoreCache* const valueStoreCache,\n XPathMatcherStack* const matcherStack,\n MemoryManager* const manager)\n : fValueStoreCache(valueStoreCache)\n , fMatcherStack(matcherStack)\n , fMayMatch(0)\n , fMemoryManager(manager)\n{\n fMayMatch = new (manager) ValueHashTableOf<bool>(29, new (manager) HashPtr(), manager);\n}\n\nFieldActivator::FieldActivator(const FieldActivator& other)\n : fValueStoreCache(other.fValueStoreCache)\n , fMatcherStack(other.fMatcherStack)\n , fMayMatch(0)\n , fMemoryManager(other.fMemoryManager)\n{\n fMayMatch = new (fMemoryManager) ValueHashTableOf<bool>(29, new (fMemoryManager) HashPtr(), fMemoryManager);\n ValueHashTableOfEnumerator<bool> mayMatchEnum(other.fMayMatch, false, fMemoryManager);\n\n \/\/ Build key set\n while (mayMatchEnum.hasMoreElements())\n {\n IC_Field* field = (IC_Field*) mayMatchEnum.nextElementKey();\n fMayMatch->put(field, other.fMayMatch->get(field));\n }\n}\n\n\nFieldActivator::~FieldActivator()\n{\n delete fMayMatch;\n}\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ FieldActivator: Operator methods\n\/\/ ---------------------------------------------------------------------------\nFieldActivator& FieldActivator::operator =(const FieldActivator& other) {\n\n if (this == &other) {\n return *this;\n }\n\n fValueStoreCache = other.fValueStoreCache;\n fMatcherStack = other.fMatcherStack;\n return *this;\n}\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ FieldActivator: Operator methods\n\/\/ ---------------------------------------------------------------------------\nXPathMatcher* FieldActivator::activateField(IC_Field* const field, const int initialDepth) {\n\n ValueStore* valueStore = fValueStoreCache->getValueStoreFor(field, initialDepth);\n XPathMatcher* matcher = field->createMatcher(this, valueStore, fMemoryManager);\n\n setMayMatch(field, true);\n fMatcherStack->addMatcher(matcher);\n matcher->startDocumentFragment();\n\n return matcher;\n}\n\nvoid FieldActivator::startValueScopeFor(const IdentityConstraint* const ic,\n const int initialDepth) {\n\n unsigned int fieldCount = ic->getFieldCount();\n\n for(unsigned int i=0; i<fieldCount; i++) {\n\n const IC_Field* field = ic->getFieldAt(i);\n ValueStore* valueStore = fValueStoreCache->getValueStoreFor(field, initialDepth);\n\n valueStore->startValueScope();\n }\n}\n\nvoid FieldActivator::endValueScopeFor(const IdentityConstraint* const ic, const int initialDepth) {\n\n ValueStore* valueStore = fValueStoreCache->getValueStoreFor(ic, initialDepth);\n\n valueStore->endValueScope();\n}\n\nXERCES_CPP_NAMESPACE_END\n\n\/**\n * End of file FieldActivator.cpp\n *\/\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2010-2012 RethinkDB, all rights reserved.\n#ifndef CONFIG_ARGS_HPP_\n#define CONFIG_ARGS_HPP_\n\n#define KILOBYTE 1024LL\n#define MEGABYTE (KILOBYTE * 1024LL)\n#define GIGABYTE (MEGABYTE * 1024LL)\n#define TERABYTE (GIGABYTE * 1024LL)\n\n#define THOUSAND 1000LL\n#define MILLION (THOUSAND * THOUSAND)\n#define BILLION (THOUSAND * MILLION)\n\n\/*!\n * Version strings\n *\/\n\n#define SOFTWARE_NAME_STRING \"RethinkDB\"\n#define SERIALIZER_VERSION_STRING \"1.6\"\n\n\/**\n * Basic configuration parameters.\n *\/\n\n\/\/ Defines the maximum size of the batch of IO events to process on\n\/\/ each loop iteration. A larger number will increase throughput but\n\/\/ decrease concurrency\n#define MAX_IO_EVENT_PROCESSING_BATCH_SIZE 50\n\n\/\/ The io batch factor ensures a minimum number of i\/o operations\n\/\/ which are picked from any specific i\/o account consecutively.\n\/\/ A higher value might be advantageous for throughput if seek times\n\/\/ matter on the underlying i\/o system. A low value improves latency.\n\/\/ The advantage only holds as long as each account has a tendentially\n\/\/ sequential set of i\/o operations though. If access patterns are random\n\/\/ for all accounts, a low io batch factor does just as well (as bad) when it comes\n\/\/ to the number of random seeks, but might still provide a lower latency\n\/\/ than a high batch factor. Our serializer writes usually generate a sequential\n\/\/ access pattern and therefore take considerable advantage from a high io batch\n\/\/ factor.\n#define DEFAULT_IO_BATCH_FACTOR 8\n\n\/\/ Currently, each cache uses two IO accounts:\n\/\/ one account for writes, and one account for reads.\n\/\/ By adjusting the priorities of these accounts, reads\n\/\/ can be prioritized over writes or the other way around.\n\/\/\n\/\/ This is a one-per-serializer\/file priority.\n\/\/ The per-cache priorities are dynamically derived by dividing these priorities\n\/\/ by the number of slices on a specific file.\n#define CACHE_READS_IO_PRIORITY 512\n#define CACHE_WRITES_IO_PRIORITY 64\n\n\/\/ Garbage Colletion uses its own two IO accounts.\n\/\/ There is one low-priority account that is meant to guarantee\n\/\/ (performance-wise) unintrusive garbage collection.\n\/\/ If the garbage ratio keeps growing,\n\/\/ GC starts using the high priority account instead, which\n\/\/ might have a negative influence on database performance\n\/\/ under i\/o heavy workloads but guarantees that the database\n\/\/ doesn't grow indefinitely.\n\/\/\n\/\/ This is a one-per-serializer\/file priority.\n#define GC_IO_PRIORITY_NICE 8\n#define GC_IO_PRIORITY_HIGH (4 * CACHE_WRITES_IO_PRIORITY)\n\n\/\/ Size of the buffer used to perform IO operations (in bytes).\n#define IO_BUFFER_SIZE (4 * KILOBYTE)\n\n\/\/ Size of the device block size (in bytes)\n#define DEVICE_BLOCK_SIZE (4 * KILOBYTE)\n\n\/\/ Size of each btree node (in bytes) on disk\n#define DEFAULT_BTREE_BLOCK_SIZE (4 * KILOBYTE)\n\n\/\/ Maximum number of data blocks\n#define MAX_DATA_EXTENTS (TERABYTE \/ (16 * KILOBYTE))\n\n\/\/ Size of each extent (in bytes)\n#define DEFAULT_EXTENT_SIZE (512 * KILOBYTE)\n\n\/\/ Max number of blocks which can be read ahead in one i\/o transaction (if enabled)\n\n\/\/ Ratio of free ram to use for the cache by default\n\/\/ TODO: DEFAULT_MAX_CACHE_RATIO is unused. Should it be deleted?\n#define DEFAULT_MAX_CACHE_RATIO 0.5\n\n\n\/\/ Maximum number of threads we support\n\/\/ TODO: make this dynamic where possible\n#define MAX_THREADS 128\n\n\/\/ Ticks (in milliseconds) the internal timed tasks are performed at\n#define TIMER_TICKS_IN_MS 5\n\n\/\/ How many milliseconds to allow changes to sit in memory before flushing to disk\n#define DEFAULT_FLUSH_TIMER_MS 1000\n\n\/\/ If non-null disk_ack_signals are present, concurrent flushing can be used to reduce the\n\/\/ latency of each single flush. max_concurrent_flushes controls how many flushes can be active\n\/\/ on a specific slice at any given time.\n#define DEFAULT_MAX_CONCURRENT_FLUSHES 1\n\n\/\/ If more than this many bytes of dirty data accumulate in the cache, then write\n\/\/ transactions will be throttled. A value of 0 means that it will automatically be\n\/\/ set to MAX_UNSAVED_DATA_LIMIT_FRACTION times the max cache size\n#define DEFAULT_UNSAVED_DATA_LIMIT (4096 * MEGABYTE)\n\n\/\/ The unsaved data limit cannot exceed this fraction of the max cache size\n#define MAX_UNSAVED_DATA_LIMIT_FRACTION 0.9\n\n\/\/ We start flushing dirty pages as soon as we hit this fraction of the unsaved data limit\n#define FLUSH_AT_FRACTION_OF_UNSAVED_DATA_LIMIT 0.2\n\n\/\/ How many times the page replacement algorithm tries to find an eligible page before giving up.\n\/\/ Note that (MAX_UNSAVED_DATA_LIMIT_FRACTION ** PAGE_REPL_NUM_TRIES) is the probability that the\n\/\/ page replacement algorithm will succeed on a given try, and if that probability is less than 1\/2\n\/\/ then the page replacement algorithm will on average be unable to evict pages from the cache.\n#define PAGE_REPL_NUM_TRIES 10\n\n\/\/ How large can the key be, in bytes? This value needs to fit in a byte.\n#define MAX_KEY_SIZE 250\n\n\/\/ Any values of this size or less will be directly stored in btree leaf nodes.\n\/\/ Values greater than this size will be stored in overflow blocks. This value\n\/\/ needs to fit in a byte.\n#define MAX_IN_NODE_VALUE_SIZE 250\n\n\/\/ memcached specifies the maximum value size to be 1MB, but customers asked this to be much higher\n#define MAX_VALUE_SIZE (10 * MEGABYTE)\n\n\/\/ Values larger than this will be streamed in a get operation\n#define MAX_BUFFERED_GET_SIZE MAX_VALUE_SIZE \/\/ streaming is too slow for now, so we disable it completely\n\n\/\/ If a single connection sends this many 'noreply' commands, the next command will\n\/\/ have to wait until the first one finishes\n#define MAX_CONCURRENT_QUERIES_PER_CONNECTION 500\n\n\/\/ The number of concurrent queries when loading memcached operations from a file.\n#define MAX_CONCURRENT_QUEURIES_ON_IMPORT 1000\n\n\/\/ How many timestamps we store in a leaf node. We store the\n\/\/ NUM_LEAF_NODE_EARLIER_TIMES+1 most-recent timestamps.\n#define NUM_LEAF_NODE_EARLIER_TIMES 4\n\n\/\/ We assume there will never be more than this many blocks. The value\n\/\/ is computed by dividing 1 TB by the smallest reasonable block size.\n\/\/ This value currently fits in 32 bits, and so block_id_t is a uint32_t.\n#define MAX_BLOCK_ID (TERABYTE \/ KILOBYTE)\n\n\/\/ We assume that there will never be more than this many blocks held in memory by the cache at\n\/\/ any one time. The value is computed by dividing 50 GB by the smallest reasonable block size.\n#define MAX_BLOCKS_IN_MEMORY (50 * GIGABYTE \/ KILOBYTE)\n\n\n\/\/ Special block IDs. These don't really belong here because they're\n\/\/ more magic constants than tunable parameters.\n\n\/\/ The btree superblock, which has a reference to the root node block\n\/\/ id.\n#define SUPERBLOCK_ID 0\n\n\/\/ The ratio at which we should start GCing. (HEY: What's the extra\n\/\/ 0.000001 in MAX_GC_HIGH_RATIO for? Is it because we told the user\n\/\/ that 0.99 was too high?)\n#define DEFAULT_GC_HIGH_RATIO 0.20\n\/\/ TODO: MAX_GC_HIGH_RATIO is unused. Use it!\n\/\/ TODO: Probably this value is way too high.\n\/\/ - Keeping this around because if it becomes configurable again, we\n\/\/ should have these limits. Before then at least rassert it.\n#define MAX_GC_HIGH_RATIO 0.990001\n\n\/\/ The ratio at which we don't want to keep GC'ing.\n#define DEFAULT_GC_LOW_RATIO 0.15\n\/\/ TODO: MIN_GC_LOW_RATIO is unused. Use it!\n\/\/ - Keeping this around because if it becomes configurable again, we\n\/\/ should have these limits. Before then at least rassert it.\n#define MIN_GC_LOW_RATIO 0.099999\n\n\n\/\/ What's the maximum number of \"young\" extents we can have?\n#define GC_YOUNG_EXTENT_MAX_SIZE 50\n\/\/ What's the definition of a \"young\" extent in microseconds?\n#define GC_YOUNG_EXTENT_TIMELIMIT_MICROS 50000\n\n\/\/ If the size of the LBA on a given disk exceeds LBA_MIN_SIZE_FOR_GC, then the fraction of the\n\/\/ entries that are live and not garbage should be at least LBA_MIN_UNGARBAGE_FRACTION.\n\/\/ TODO: Maybe change this back to 20 megabytes?\n#define LBA_MIN_SIZE_FOR_GC (MEGABYTE * 1)\n\/\/ TODO: This used to be 0.15 but we figured why not do the opposite of our well-tested parameter?\n#define LBA_MIN_UNGARBAGE_FRACTION 0.85\n\n\/\/ How many LBA structures to have for each file\n\/\/ TODO: LBA_SHARD_FACTOR used to be 16.\n#define LBA_SHARD_FACTOR 4\n\n\/\/ How many bytes of buffering space we can use per disk when reading the LBA. If it's set\n\/\/ too high, then RethinkDB will eat a lot of memory at startup. This is bad because tcmalloc\n\/\/ doesn't return memory to the OS. If it's set too low, startup will take a longer time.\n#define LBA_READ_BUFFER_SIZE GIGABYTE\n\n#define COROUTINE_STACK_SIZE 131072\n\n#define MAX_COROS_PER_THREAD 10000\n\n\n\/\/ Size of a cache line (used in cache_line_padded_t).\n#define CACHE_LINE_SIZE 64\n\n#endif \/\/ CONFIG_ARGS_HPP_\n\n<commit_msg>Set DEVICE_BLOCK_SIZE to 512.<commit_after>\/\/ Copyright 2010-2012 RethinkDB, all rights reserved.\n#ifndef CONFIG_ARGS_HPP_\n#define CONFIG_ARGS_HPP_\n\n#define KILOBYTE 1024LL\n#define MEGABYTE (KILOBYTE * 1024LL)\n#define GIGABYTE (MEGABYTE * 1024LL)\n#define TERABYTE (GIGABYTE * 1024LL)\n\n#define THOUSAND 1000LL\n#define MILLION (THOUSAND * THOUSAND)\n#define BILLION (THOUSAND * MILLION)\n\n\/*!\n * Version strings\n *\/\n\n#define SOFTWARE_NAME_STRING \"RethinkDB\"\n#define SERIALIZER_VERSION_STRING \"1.6\"\n\n\/**\n * Basic configuration parameters.\n *\/\n\n\/\/ Defines the maximum size of the batch of IO events to process on\n\/\/ each loop iteration. A larger number will increase throughput but\n\/\/ decrease concurrency\n#define MAX_IO_EVENT_PROCESSING_BATCH_SIZE 50\n\n\/\/ The io batch factor ensures a minimum number of i\/o operations\n\/\/ which are picked from any specific i\/o account consecutively.\n\/\/ A higher value might be advantageous for throughput if seek times\n\/\/ matter on the underlying i\/o system. A low value improves latency.\n\/\/ The advantage only holds as long as each account has a tendentially\n\/\/ sequential set of i\/o operations though. If access patterns are random\n\/\/ for all accounts, a low io batch factor does just as well (as bad) when it comes\n\/\/ to the number of random seeks, but might still provide a lower latency\n\/\/ than a high batch factor. Our serializer writes usually generate a sequential\n\/\/ access pattern and therefore take considerable advantage from a high io batch\n\/\/ factor.\n#define DEFAULT_IO_BATCH_FACTOR 8\n\n\/\/ Currently, each cache uses two IO accounts:\n\/\/ one account for writes, and one account for reads.\n\/\/ By adjusting the priorities of these accounts, reads\n\/\/ can be prioritized over writes or the other way around.\n\/\/\n\/\/ This is a one-per-serializer\/file priority.\n\/\/ The per-cache priorities are dynamically derived by dividing these priorities\n\/\/ by the number of slices on a specific file.\n#define CACHE_READS_IO_PRIORITY 512\n#define CACHE_WRITES_IO_PRIORITY 64\n\n\/\/ Garbage Colletion uses its own two IO accounts.\n\/\/ There is one low-priority account that is meant to guarantee\n\/\/ (performance-wise) unintrusive garbage collection.\n\/\/ If the garbage ratio keeps growing,\n\/\/ GC starts using the high priority account instead, which\n\/\/ might have a negative influence on database performance\n\/\/ under i\/o heavy workloads but guarantees that the database\n\/\/ doesn't grow indefinitely.\n\/\/\n\/\/ This is a one-per-serializer\/file priority.\n#define GC_IO_PRIORITY_NICE 8\n#define GC_IO_PRIORITY_HIGH (4 * CACHE_WRITES_IO_PRIORITY)\n\n\/\/ Size of the buffer used to perform IO operations (in bytes).\n#define IO_BUFFER_SIZE (4 * KILOBYTE)\n\n\/\/ Size of the device block size (in bytes)\n#define DEVICE_BLOCK_SIZE 512\n\n\/\/ Size of each btree node (in bytes) on disk\n#define DEFAULT_BTREE_BLOCK_SIZE (4 * KILOBYTE)\n\n\/\/ Maximum number of data blocks\n#define MAX_DATA_EXTENTS (TERABYTE \/ (16 * KILOBYTE))\n\n\/\/ Size of each extent (in bytes)\n#define DEFAULT_EXTENT_SIZE (512 * KILOBYTE)\n\n\/\/ Max number of blocks which can be read ahead in one i\/o transaction (if enabled)\n\n\/\/ Ratio of free ram to use for the cache by default\n\/\/ TODO: DEFAULT_MAX_CACHE_RATIO is unused. Should it be deleted?\n#define DEFAULT_MAX_CACHE_RATIO 0.5\n\n\n\/\/ Maximum number of threads we support\n\/\/ TODO: make this dynamic where possible\n#define MAX_THREADS 128\n\n\/\/ Ticks (in milliseconds) the internal timed tasks are performed at\n#define TIMER_TICKS_IN_MS 5\n\n\/\/ How many milliseconds to allow changes to sit in memory before flushing to disk\n#define DEFAULT_FLUSH_TIMER_MS 1000\n\n\/\/ If non-null disk_ack_signals are present, concurrent flushing can be used to reduce the\n\/\/ latency of each single flush. max_concurrent_flushes controls how many flushes can be active\n\/\/ on a specific slice at any given time.\n#define DEFAULT_MAX_CONCURRENT_FLUSHES 1\n\n\/\/ If more than this many bytes of dirty data accumulate in the cache, then write\n\/\/ transactions will be throttled. A value of 0 means that it will automatically be\n\/\/ set to MAX_UNSAVED_DATA_LIMIT_FRACTION times the max cache size\n#define DEFAULT_UNSAVED_DATA_LIMIT (4096 * MEGABYTE)\n\n\/\/ The unsaved data limit cannot exceed this fraction of the max cache size\n#define MAX_UNSAVED_DATA_LIMIT_FRACTION 0.9\n\n\/\/ We start flushing dirty pages as soon as we hit this fraction of the unsaved data limit\n#define FLUSH_AT_FRACTION_OF_UNSAVED_DATA_LIMIT 0.2\n\n\/\/ How many times the page replacement algorithm tries to find an eligible page before giving up.\n\/\/ Note that (MAX_UNSAVED_DATA_LIMIT_FRACTION ** PAGE_REPL_NUM_TRIES) is the probability that the\n\/\/ page replacement algorithm will succeed on a given try, and if that probability is less than 1\/2\n\/\/ then the page replacement algorithm will on average be unable to evict pages from the cache.\n#define PAGE_REPL_NUM_TRIES 10\n\n\/\/ How large can the key be, in bytes? This value needs to fit in a byte.\n#define MAX_KEY_SIZE 250\n\n\/\/ Any values of this size or less will be directly stored in btree leaf nodes.\n\/\/ Values greater than this size will be stored in overflow blocks. This value\n\/\/ needs to fit in a byte.\n#define MAX_IN_NODE_VALUE_SIZE 250\n\n\/\/ memcached specifies the maximum value size to be 1MB, but customers asked this to be much higher\n#define MAX_VALUE_SIZE (10 * MEGABYTE)\n\n\/\/ Values larger than this will be streamed in a get operation\n#define MAX_BUFFERED_GET_SIZE MAX_VALUE_SIZE \/\/ streaming is too slow for now, so we disable it completely\n\n\/\/ If a single connection sends this many 'noreply' commands, the next command will\n\/\/ have to wait until the first one finishes\n#define MAX_CONCURRENT_QUERIES_PER_CONNECTION 500\n\n\/\/ The number of concurrent queries when loading memcached operations from a file.\n#define MAX_CONCURRENT_QUEURIES_ON_IMPORT 1000\n\n\/\/ How many timestamps we store in a leaf node. We store the\n\/\/ NUM_LEAF_NODE_EARLIER_TIMES+1 most-recent timestamps.\n#define NUM_LEAF_NODE_EARLIER_TIMES 4\n\n\/\/ We assume there will never be more than this many blocks. The value\n\/\/ is computed by dividing 1 TB by the smallest reasonable block size.\n\/\/ This value currently fits in 32 bits, and so block_id_t is a uint32_t.\n#define MAX_BLOCK_ID (TERABYTE \/ KILOBYTE)\n\n\/\/ We assume that there will never be more than this many blocks held in memory by the cache at\n\/\/ any one time. The value is computed by dividing 50 GB by the smallest reasonable block size.\n#define MAX_BLOCKS_IN_MEMORY (50 * GIGABYTE \/ KILOBYTE)\n\n\n\/\/ Special block IDs. These don't really belong here because they're\n\/\/ more magic constants than tunable parameters.\n\n\/\/ The btree superblock, which has a reference to the root node block\n\/\/ id.\n#define SUPERBLOCK_ID 0\n\n\/\/ The ratio at which we should start GCing. (HEY: What's the extra\n\/\/ 0.000001 in MAX_GC_HIGH_RATIO for? Is it because we told the user\n\/\/ that 0.99 was too high?)\n#define DEFAULT_GC_HIGH_RATIO 0.20\n\/\/ TODO: MAX_GC_HIGH_RATIO is unused. Use it!\n\/\/ TODO: Probably this value is way too high.\n\/\/ - Keeping this around because if it becomes configurable again, we\n\/\/ should have these limits. Before then at least rassert it.\n#define MAX_GC_HIGH_RATIO 0.990001\n\n\/\/ The ratio at which we don't want to keep GC'ing.\n#define DEFAULT_GC_LOW_RATIO 0.15\n\/\/ TODO: MIN_GC_LOW_RATIO is unused. Use it!\n\/\/ - Keeping this around because if it becomes configurable again, we\n\/\/ should have these limits. Before then at least rassert it.\n#define MIN_GC_LOW_RATIO 0.099999\n\n\n\/\/ What's the maximum number of \"young\" extents we can have?\n#define GC_YOUNG_EXTENT_MAX_SIZE 50\n\/\/ What's the definition of a \"young\" extent in microseconds?\n#define GC_YOUNG_EXTENT_TIMELIMIT_MICROS 50000\n\n\/\/ If the size of the LBA on a given disk exceeds LBA_MIN_SIZE_FOR_GC, then the fraction of the\n\/\/ entries that are live and not garbage should be at least LBA_MIN_UNGARBAGE_FRACTION.\n\/\/ TODO: Maybe change this back to 20 megabytes?\n#define LBA_MIN_SIZE_FOR_GC (MEGABYTE * 1)\n\/\/ TODO: This used to be 0.15 but we figured why not do the opposite of our well-tested parameter?\n#define LBA_MIN_UNGARBAGE_FRACTION 0.85\n\n\/\/ How many LBA structures to have for each file\n\/\/ TODO: LBA_SHARD_FACTOR used to be 16.\n#define LBA_SHARD_FACTOR 4\n\n\/\/ How many bytes of buffering space we can use per disk when reading the LBA. If it's set\n\/\/ too high, then RethinkDB will eat a lot of memory at startup. This is bad because tcmalloc\n\/\/ doesn't return memory to the OS. If it's set too low, startup will take a longer time.\n#define LBA_READ_BUFFER_SIZE GIGABYTE\n\n#define COROUTINE_STACK_SIZE 131072\n\n#define MAX_COROS_PER_THREAD 10000\n\n\n\/\/ Size of a cache line (used in cache_line_padded_t).\n#define CACHE_LINE_SIZE 64\n\n#endif \/\/ CONFIG_ARGS_HPP_\n\n<|endoftext|>"} {"text":"<commit_before>\/* Copyright 2017 The TensorFlow Authors. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*\/\n\n#include \"tensorflow\/compiler\/xla\/service\/gpu\/instruction_fusion.h\"\n\n#include \"tensorflow\/compiler\/xla\/service\/gpu\/ir_emission_utils.h\"\n#include \"tensorflow\/compiler\/xla\/service\/hlo_opcode.h\"\n#include \"tensorflow\/compiler\/xla\/service\/pattern_matcher.h\"\n#include \"tensorflow\/compiler\/xla\/shape_util.h\"\n#include \"tensorflow\/compiler\/xla\/xla_data.pb.h\"\n\nnamespace xla {\nnamespace gpu {\n\nnamespace {\n\nbool IsFusile(const HloInstruction& hlo) {\n \/\/ Don't fuse get-tuple-element on GPU: We can, but it's slower than not\n \/\/ fusing. We never generate kernels for unfused GTEs. Instead, if an\n \/\/ unfused GTE is an input to a kernel (including a fusion kernel), we\n \/\/ compute the address of the GTE at the top of the kernel. Often we know the\n \/\/ address of the GTE result statically, so we can do this without chasing any\n \/\/ pointers.\n return (hlo.IsElementwise() && hlo.operand_count() > 0) ||\n hlo.opcode() == HloOpcode::kBitcast ||\n hlo.opcode() == HloOpcode::kBroadcast ||\n hlo.opcode() == HloOpcode::kConcatenate ||\n hlo.opcode() == HloOpcode::kDynamicSlice ||\n hlo.opcode() == HloOpcode::kDynamicUpdateSlice ||\n hlo.opcode() == HloOpcode::kFusion ||\n hlo.opcode() == HloOpcode::kPad ||\n hlo.opcode() == HloOpcode::kReduce ||\n hlo.opcode() == HloOpcode::kReduceWindow ||\n hlo.opcode() == HloOpcode::kReshape ||\n hlo.opcode() == HloOpcode::kSlice ||\n hlo.opcode() == HloOpcode::kTranspose;\n}\n\nbool IsIEEEFloatingPointScalarConstant(const HloInstruction* constant) {\n if (constant->opcode() != HloOpcode::kConstant ||\n !ShapeUtil::IsScalar(constant->shape())) {\n return false;\n }\n auto type = constant->shape().element_type();\n return type == F16 || type == F32 || type == F64;\n}\n\n} \/\/ namespace\n\n\/*static*\/ bool GpuInstructionFusion::IsExpensive(\n const HloInstruction& instruction) {\n switch (instruction.opcode()) {\n \/\/ We say that floating-point division is cheap on the GPU.\n case HloOpcode::kDivide:\n return !ShapeUtil::ElementIsFloating(instruction.shape()) &&\n InstructionFusion::IsExpensive(instruction);\n\n default:\n return InstructionFusion::IsExpensive(instruction);\n }\n}\n\nbool GpuInstructionFusion::ShouldFuse(HloInstruction* consumer,\n int64 operand_index) {\n HloInstruction* producer = consumer->mutable_operand(operand_index);\n\n \/\/ Check if we can use output fusion for (A @ B) * alpha\n if (producer->opcode() == HloOpcode::kDot ||\n (producer->opcode() == HloOpcode::kFusion &&\n producer->fused_expression_root()->opcode() == HloOpcode::kDot)) {\n int64 other_operand_index = 1 - operand_index;\n HloInstruction* op1 = nullptr;\n HloInstruction* op2 = nullptr;\n if (consumer->operand_count() == 1 &&\n consumer->opcode() == HloOpcode::kFusion &&\n consumer->fusion_kind() == HloInstruction::FusionKind::kLoop &&\n Match(consumer->fused_expression_root(),\n match::Op()\n .WithOpcode(HloOpcode::kMultiply)\n .WithOperand(0, match::Op(&op1))\n .WithOperand(1, match::Op(&op2)))) {\n CHECK(op1 != nullptr && op2 != nullptr);\n \/\/ If 'consumer' is a fusion node, it should consist of a broadcast of a\n \/\/ scalar constant fused into a multiply, but nothing more. So one operand\n \/\/ should be a parameter, and the other should be a broadcast.\n if (op1->opcode() != HloOpcode::kParameter) {\n std::swap(op1, op2);\n }\n if (op1->opcode() != HloOpcode::kParameter ||\n op2->opcode() != HloOpcode::kBroadcast) {\n return false;\n }\n if (IsIEEEFloatingPointScalarConstant(op2->operand(0))) {\n return true;\n }\n } else if (consumer->operand_count() == 2 &&\n consumer->opcode() == HloOpcode::kMultiply) {\n const HloInstruction* alpha = consumer->operand(other_operand_index);\n \/\/ Fuse if 'alpha' is a broadcast of a scalar constant.\n if (alpha->opcode() == HloOpcode::kBroadcast &&\n alpha->dimensions().empty() &&\n IsIEEEFloatingPointScalarConstant(alpha->operand(0))) {\n return true;\n }\n }\n }\n\n \/\/ Only allow fusing transpose or broadcast into an output fusion that is\n \/\/ implemented as a Gemm call.\n if (consumer->opcode() == HloOpcode::kFusion &&\n consumer->fusion_kind() == HloInstruction::FusionKind::kOutput &&\n ImplementedAsGemm(*consumer)) {\n auto producer_operand_index = consumer->operand_index(producer);\n auto fused_parameter = consumer->fused_parameter(producer_operand_index);\n const std::vector<HloInstruction*>& fused_parameter_users =\n fused_parameter->users();\n if (fused_parameter_users.size() != 1) {\n return false;\n }\n if (producer->opcode() == HloOpcode::kTranspose) {\n \/\/ Check that the transpose is an operand of a dot.\n return fused_parameter_users[0]->opcode() == HloOpcode::kDot;\n }\n if (producer->opcode() == HloOpcode::kBroadcast) {\n \/\/ Check that the broadcast is a broadcast of a scalar constant into a\n \/\/ multiply.\n return producer->dimensions().empty() &&\n IsIEEEFloatingPointScalarConstant(producer->operand(0)) &&\n fused_parameter_users[0]->opcode() == HloOpcode::kMultiply;\n }\n }\n\n \/\/ Other output fusions are not currently supported on GPUs.\n if (producer->opcode() == HloOpcode::kFusion) {\n return false;\n }\n\n \/\/ RNG operations are not currently parallel-friendly on GPU.\n if (producer->opcode() == HloOpcode::kRng) {\n return false;\n }\n\n \/\/ Do not fuse to-vector reduction into other consumers. They should be\n \/\/ unfused or the root of a kInput fusion.\n if (IsReductionToVector(*producer)) {\n return false;\n }\n\n \/\/ We can't fuse library calls, so if a user of such an op could become a\n \/\/ bitcast, leave it unfused. See `xla::InstructionFusion::ShouldFuse` for\n \/\/ further rationale.\n if (producer->CouldBeBitcast() &&\n ImplementedAsLibraryCall(*producer->operand(0))) {\n return false;\n }\n\n \/\/ Cost condition: not fuse (simple, expensive producers) and (consumers who\n \/\/ reuse operand elements).\n if (producer->opcode() != HloOpcode::kFusion &&\n consumer->ReusesOperandElements(operand_index) &&\n is_expensive(*producer)) {\n return false;\n }\n\n \/\/ Fuse scalar constants into loop fusion nodes, this reduces the number of\n \/\/ parameters and makes matching scalar broadcasts easier.\n if (ShapeUtil::IsEffectiveScalar(producer->shape()) &&\n consumer->opcode() == HloOpcode::kFusion &&\n producer->opcode() == HloOpcode::kConstant) {\n return true;\n }\n\n return IsFusile(*producer) && IsFusile(*consumer) &&\n InstructionFusion::ShouldFuse(consumer, operand_index);\n}\n\nbool GpuInstructionFusion::ShouldFuseIntoMultiOutput(HloInstruction* consumer,\n int64 operand_index) {\n const HloInstruction* producer = consumer->operand(operand_index);\n \/\/ The IR emitter has limited support for non-loop fusions with multi output\n \/\/ at present.\n \/\/ TODO(tjoerg): Relax this constraint to allow for arbitraty kinds of fusion.\n if (consumer->opcode() == HloOpcode::kFusion &&\n consumer->fusion_kind() != HloInstruction::FusionKind::kLoop) {\n return false;\n }\n \/\/ Multi-output fusion requires instructions with compatible shapes.\n if (!ShapeUtil::Compatible(producer->shape(), consumer->shape())) {\n return false;\n }\n \/\/ TODO(tjoerg): Stop calling `ShouldFuse` to relax the criteria for\n \/\/ multi-output fusion. In particular, do not check whether an instruction is\n \/\/ expensive to duplicate, since this doesn't matter here.\n return GpuInstructionFusion::ShouldFuse(consumer, operand_index);\n}\n\nHloInstruction::FusionKind GpuInstructionFusion::ChooseKind(\n const HloInstruction* producer, const HloInstruction* consumer) {\n if (IsReductionToVector(*consumer)) {\n return HloInstruction::FusionKind::kInput;\n }\n if (producer->opcode() == HloOpcode::kDot ||\n (producer->opcode() == HloOpcode::kFusion &&\n producer->fused_expression_root()->opcode() == HloOpcode::kDot)) {\n return HloInstruction::FusionKind::kOutput;\n }\n if (HloOpcode::kFusion == consumer->opcode()) {\n return consumer->fusion_kind();\n }\n return InstructionFusion::ChooseKind(producer, consumer);\n}\n\n} \/\/ namespace gpu\n} \/\/ namespace xla\n<commit_msg>Mark Gather as fusile.<commit_after>\/* Copyright 2017 The TensorFlow Authors. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*\/\n\n#include \"tensorflow\/compiler\/xla\/service\/gpu\/instruction_fusion.h\"\n\n#include \"tensorflow\/compiler\/xla\/service\/gpu\/ir_emission_utils.h\"\n#include \"tensorflow\/compiler\/xla\/service\/hlo_opcode.h\"\n#include \"tensorflow\/compiler\/xla\/service\/pattern_matcher.h\"\n#include \"tensorflow\/compiler\/xla\/shape_util.h\"\n#include \"tensorflow\/compiler\/xla\/xla_data.pb.h\"\n\nnamespace xla {\nnamespace gpu {\n\nnamespace {\n\nbool IsFusile(const HloInstruction& hlo) {\n \/\/ Don't fuse get-tuple-element on GPU: We can, but it's slower than not\n \/\/ fusing. We never generate kernels for unfused GTEs. Instead, if an\n \/\/ unfused GTE is an input to a kernel (including a fusion kernel), we\n \/\/ compute the address of the GTE at the top of the kernel. Often we know the\n \/\/ address of the GTE result statically, so we can do this without chasing any\n \/\/ pointers.\n return (hlo.IsElementwise() && hlo.operand_count() > 0) ||\n hlo.opcode() == HloOpcode::kBitcast ||\n hlo.opcode() == HloOpcode::kBroadcast ||\n hlo.opcode() == HloOpcode::kConcatenate ||\n hlo.opcode() == HloOpcode::kDynamicSlice ||\n hlo.opcode() == HloOpcode::kDynamicUpdateSlice ||\n hlo.opcode() == HloOpcode::kFusion ||\n hlo.opcode() == HloOpcode::kGather ||\n hlo.opcode() == HloOpcode::kPad ||\n hlo.opcode() == HloOpcode::kReduce ||\n hlo.opcode() == HloOpcode::kReduceWindow ||\n hlo.opcode() == HloOpcode::kReshape ||\n hlo.opcode() == HloOpcode::kSlice ||\n hlo.opcode() == HloOpcode::kTranspose;\n}\n\nbool IsIEEEFloatingPointScalarConstant(const HloInstruction* constant) {\n if (constant->opcode() != HloOpcode::kConstant ||\n !ShapeUtil::IsScalar(constant->shape())) {\n return false;\n }\n auto type = constant->shape().element_type();\n return type == F16 || type == F32 || type == F64;\n}\n\n} \/\/ namespace\n\n\/*static*\/ bool GpuInstructionFusion::IsExpensive(\n const HloInstruction& instruction) {\n switch (instruction.opcode()) {\n \/\/ We say that floating-point division is cheap on the GPU.\n case HloOpcode::kDivide:\n return !ShapeUtil::ElementIsFloating(instruction.shape()) &&\n InstructionFusion::IsExpensive(instruction);\n\n default:\n return InstructionFusion::IsExpensive(instruction);\n }\n}\n\nbool GpuInstructionFusion::ShouldFuse(HloInstruction* consumer,\n int64 operand_index) {\n HloInstruction* producer = consumer->mutable_operand(operand_index);\n\n \/\/ Check if we can use output fusion for (A @ B) * alpha\n if (producer->opcode() == HloOpcode::kDot ||\n (producer->opcode() == HloOpcode::kFusion &&\n producer->fused_expression_root()->opcode() == HloOpcode::kDot)) {\n int64 other_operand_index = 1 - operand_index;\n HloInstruction* op1 = nullptr;\n HloInstruction* op2 = nullptr;\n if (consumer->operand_count() == 1 &&\n consumer->opcode() == HloOpcode::kFusion &&\n consumer->fusion_kind() == HloInstruction::FusionKind::kLoop &&\n Match(consumer->fused_expression_root(),\n match::Op()\n .WithOpcode(HloOpcode::kMultiply)\n .WithOperand(0, match::Op(&op1))\n .WithOperand(1, match::Op(&op2)))) {\n CHECK(op1 != nullptr && op2 != nullptr);\n \/\/ If 'consumer' is a fusion node, it should consist of a broadcast of a\n \/\/ scalar constant fused into a multiply, but nothing more. So one operand\n \/\/ should be a parameter, and the other should be a broadcast.\n if (op1->opcode() != HloOpcode::kParameter) {\n std::swap(op1, op2);\n }\n if (op1->opcode() != HloOpcode::kParameter ||\n op2->opcode() != HloOpcode::kBroadcast) {\n return false;\n }\n if (IsIEEEFloatingPointScalarConstant(op2->operand(0))) {\n return true;\n }\n } else if (consumer->operand_count() == 2 &&\n consumer->opcode() == HloOpcode::kMultiply) {\n const HloInstruction* alpha = consumer->operand(other_operand_index);\n \/\/ Fuse if 'alpha' is a broadcast of a scalar constant.\n if (alpha->opcode() == HloOpcode::kBroadcast &&\n alpha->dimensions().empty() &&\n IsIEEEFloatingPointScalarConstant(alpha->operand(0))) {\n return true;\n }\n }\n }\n\n \/\/ Only allow fusing transpose or broadcast into an output fusion that is\n \/\/ implemented as a Gemm call.\n if (consumer->opcode() == HloOpcode::kFusion &&\n consumer->fusion_kind() == HloInstruction::FusionKind::kOutput &&\n ImplementedAsGemm(*consumer)) {\n auto producer_operand_index = consumer->operand_index(producer);\n auto fused_parameter = consumer->fused_parameter(producer_operand_index);\n const std::vector<HloInstruction*>& fused_parameter_users =\n fused_parameter->users();\n if (fused_parameter_users.size() != 1) {\n return false;\n }\n if (producer->opcode() == HloOpcode::kTranspose) {\n \/\/ Check that the transpose is an operand of a dot.\n return fused_parameter_users[0]->opcode() == HloOpcode::kDot;\n }\n if (producer->opcode() == HloOpcode::kBroadcast) {\n \/\/ Check that the broadcast is a broadcast of a scalar constant into a\n \/\/ multiply.\n return producer->dimensions().empty() &&\n IsIEEEFloatingPointScalarConstant(producer->operand(0)) &&\n fused_parameter_users[0]->opcode() == HloOpcode::kMultiply;\n }\n }\n\n \/\/ Other output fusions are not currently supported on GPUs.\n if (producer->opcode() == HloOpcode::kFusion) {\n return false;\n }\n\n \/\/ RNG operations are not currently parallel-friendly on GPU.\n if (producer->opcode() == HloOpcode::kRng) {\n return false;\n }\n\n \/\/ Do not fuse to-vector reduction into other consumers. They should be\n \/\/ unfused or the root of a kInput fusion.\n if (IsReductionToVector(*producer)) {\n return false;\n }\n\n \/\/ We can't fuse library calls, so if a user of such an op could become a\n \/\/ bitcast, leave it unfused. See `xla::InstructionFusion::ShouldFuse` for\n \/\/ further rationale.\n if (producer->CouldBeBitcast() &&\n ImplementedAsLibraryCall(*producer->operand(0))) {\n return false;\n }\n\n \/\/ Cost condition: not fuse (simple, expensive producers) and (consumers who\n \/\/ reuse operand elements).\n if (producer->opcode() != HloOpcode::kFusion &&\n consumer->ReusesOperandElements(operand_index) &&\n is_expensive(*producer)) {\n return false;\n }\n\n \/\/ Fuse scalar constants into loop fusion nodes, this reduces the number of\n \/\/ parameters and makes matching scalar broadcasts easier.\n if (ShapeUtil::IsEffectiveScalar(producer->shape()) &&\n consumer->opcode() == HloOpcode::kFusion &&\n producer->opcode() == HloOpcode::kConstant) {\n return true;\n }\n\n return IsFusile(*producer) && IsFusile(*consumer) &&\n InstructionFusion::ShouldFuse(consumer, operand_index);\n}\n\nbool GpuInstructionFusion::ShouldFuseIntoMultiOutput(HloInstruction* consumer,\n int64 operand_index) {\n const HloInstruction* producer = consumer->operand(operand_index);\n \/\/ The IR emitter has limited support for non-loop fusions with multi output\n \/\/ at present.\n \/\/ TODO(tjoerg): Relax this constraint to allow for arbitraty kinds of fusion.\n if (consumer->opcode() == HloOpcode::kFusion &&\n consumer->fusion_kind() != HloInstruction::FusionKind::kLoop) {\n return false;\n }\n \/\/ Multi-output fusion requires instructions with compatible shapes.\n if (!ShapeUtil::Compatible(producer->shape(), consumer->shape())) {\n return false;\n }\n \/\/ TODO(tjoerg): Stop calling `ShouldFuse` to relax the criteria for\n \/\/ multi-output fusion. In particular, do not check whether an instruction is\n \/\/ expensive to duplicate, since this doesn't matter here.\n return GpuInstructionFusion::ShouldFuse(consumer, operand_index);\n}\n\nHloInstruction::FusionKind GpuInstructionFusion::ChooseKind(\n const HloInstruction* producer, const HloInstruction* consumer) {\n if (IsReductionToVector(*consumer)) {\n return HloInstruction::FusionKind::kInput;\n }\n if (producer->opcode() == HloOpcode::kDot ||\n (producer->opcode() == HloOpcode::kFusion &&\n producer->fused_expression_root()->opcode() == HloOpcode::kDot)) {\n return HloInstruction::FusionKind::kOutput;\n }\n if (HloOpcode::kFusion == consumer->opcode()) {\n return consumer->fusion_kind();\n }\n return InstructionFusion::ChooseKind(producer, consumer);\n}\n\n} \/\/ namespace gpu\n} \/\/ namespace xla\n<|endoftext|>"} {"text":"<commit_before>#pragma once\n\n#include <cassert>\n#include <map>\n#include <omp.h>\n\n#include \"global_config.hpp\"\n\nnamespace mocc {\n \/**\n * The \\ref Timer class provides functionality for measuring the amount of\n * runtime spent on various tasks. Each \\ref Timer can have a number of\n * \"children,\" which comprise sub-\\ref Timer for individual tasks of\n * interest.\n *\n * Every \\ref Timer maintains a total elapsed time, which may be accessed\n * via the \\ref Timer::time() method. A \\ref Timer can be thought of as a\n * stopwatch that is started with the \\ref Timer::tic() method, and stopped\n * with the \\ref Timer::toc() method. The elapsed time is a sum of all time\n * spent between calls the \\ref Timer::tic() and \\ref Timer::toc().\n *\n * There is a global \\ref RootTimer, which is treated as the parent \\ref\n * Timer for the entire executable.\n *\/\n class Timer {\n public:\n \/**\n * \\brief Create a new \\ref Timer object.\n *\/\n Timer(std::string name);\n\n \/**\n * \\brief Create a new \\ref Timer object and possibly start it.\n *\n * \\param name the name of the \\ref Timer\n * \\param start whether or not to start the timer at construction-time.\n *\n * This will create a new \\ref Timer and possibly start the \\ref Timer\n * automatically if \\p start is \\c true. This is useful for\n * instrumenting constructor time for objects with lots of heavy lifting\n * to do in their initialization list. In such cases, starting the \\ref\n * Timer in the body of the initializer will miss much of the time spent\n * constructing the objects in the initializer list. Placing a \\ref\n * Timer object at the top of the initializer list will allow\n * measurement of this type of code.\n *\/\n Timer(std::string name, bool start );\n\n \/**\n * \\brief Start the \\ref Timer\n *\n * This starts the \\ref Timer \"running,\" by logging the wall time at\n * which the \\ref tic() function was called. The timer can then be\n * stopped with a call to \\ref toc().\n *\/\n void tic();\n\n \/**\n * \\brief Stop the \\ref Timer\n *\n * This stops the \\ref Timer and returns the amount of time that elapsed\n * between the calls to \\ref tic() and the \\ref toc(). The running\n * sum of time for the \\ref Timer is also incremented by this duration.\n *\/\n real_t toc();\n\n \/**\n * \\brief Return a reference the child Timer of the passed name\n *\/\n Timer &operator[]( const std::string &name ) {\n return children_.at(name);\n }\n\n \/**\n * \\brief Return a const reference the child Timer of the passed name\n *\/\n const Timer &operator[]( const std::string &name ) const {\n return children_.at(name);\n }\n\n \/**\n * \\brief Print the entire \\ref Timer tree to the provided output\n * stream.\n *\/\n void print( std::ostream &os, int level=0 ) const;\n\n \/**\n * \\brief Create a new child \\ref Timer and return a reference to it.\n *\/\n Timer &new_timer( const std::string &name ) {\n children_.emplace( name, Timer(name) );\n return children_.at(name);\n }\n \n \/**\n * \\brief Create and return a new child \\ref Timer, possibly starting it\n * automatically\n *\/\n Timer &new_timer( const std::string &name, bool start ) {\n children_.emplace( name, Timer(name, start) );\n return children_.at(name);\n }\n\n friend std::ostream &operator<<( std::ostream &os,\n const Timer &timer );\n\n private:\n std::string name_;\n real_t time_;\n bool running_;\n real_t wtime_;\n std::map<std::string, Timer> children_;\n };\n\n extern Timer RootTimer;\n\n}\n<commit_msg>Fix docs, add time() to Timer<commit_after>#pragma once\n\n#include <cassert>\n#include <map>\n#include <omp.h>\n\n#include \"global_config.hpp\"\n\nnamespace mocc {\n \/**\n * The \\ref Timer class provides functionality for measuring the amount of\n * runtime spent on various tasks. Each \\ref Timer can have a number of\n * \"children,\" which comprise sub-\\ref Timer for individual tasks of\n * interest.\n *\n * Every \\ref Timer maintains a total elapsed time, which may be accessed\n * via the \\ref Timer::time() method. A \\ref Timer can be thought of as a\n * stopwatch that is started with the \\ref Timer::tic() method, and stopped\n * with the \\ref Timer::toc() method. The elapsed time is a sum of all time\n * spent between calls the \\ref Timer::tic() and \\ref Timer::toc().\n *\n * There is a global \\ref RootTimer, which is treated as the parent \\ref\n * Timer for the entire executable.\n *\/\n class Timer {\n public:\n \/**\n * \\brief Create a new \\ref Timer object.\n *\/\n Timer(std::string name);\n\n \/**\n * \\brief Create a new \\ref Timer object and possibly start it.\n *\n * \\param name the name of the \\ref Timer\n * \\param start whether or not to start the timer at construction-time.\n *\n * This will create a new \\ref Timer and possibly start the \\ref Timer\n * automatically if \\p start is \\c true. This is useful for\n * instrumenting constructor time for objects with lots of heavy lifting\n * to do in their initialization list. In such cases, starting the \\ref\n * Timer in the body of the initializer will miss much of the time spent\n * constructing the objects in the initializer list. Placing a \\ref\n * Timer object at the top of the initializer list will allow\n * measurement of this type of code.\n *\/\n Timer(std::string name, bool start );\n\n \/**\n * \\brief Start the \\ref Timer\n *\n * This starts the \\ref Timer \"running,\" by logging the wall time at\n * which the \\ref tic() function was called. The timer can then be\n * stopped with a call to \\ref toc().\n *\/\n void tic();\n\n \/**\n * \\brief Stop the \\ref Timer\n *\n * This stops the \\ref Timer and returns the amount of time that elapsed\n * between the calls to \\ref tic() and the \\ref toc(). The running\n * sum of time for the \\ref Timer is also incremented by this duration.\n *\/\n real_t toc();\n\n \/**\n * \\brief Return the time accumulated so far for the timer.\n *\n * If the timer is currently running, this will not include time since\n * last call to \\ref tic().\n *\/\n real_t time() const {\n return time_;\n }\n\n \/**\n * \\brief Return a reference the child Timer of the passed name\n *\/\n Timer &operator[]( const std::string &name ) {\n return children_.at(name);\n }\n\n \/**\n * \\brief Return a const reference the child Timer of the passed name\n *\/\n const Timer &operator[]( const std::string &name ) const {\n return children_.at(name);\n }\n\n \/**\n * \\brief Print the entire \\ref Timer tree to the provided output\n * stream.\n *\/\n void print( std::ostream &os, int level=0 ) const;\n\n \/**\n * \\brief Create a new child \\ref Timer and return a reference to it.\n *\/\n Timer &new_timer( const std::string &name ) {\n children_.emplace( name, Timer(name) );\n return children_.at(name);\n }\n \n \/**\n * \\brief Create and return a new child \\ref Timer, possibly starting it\n * automatically\n *\/\n Timer &new_timer( const std::string &name, bool start ) {\n children_.emplace( name, Timer(name, start) );\n return children_.at(name);\n }\n\n friend std::ostream &operator<<( std::ostream &os,\n const Timer &timer );\n\n private:\n std::string name_;\n real_t time_;\n bool running_;\n real_t wtime_;\n std::map<std::string, Timer> children_;\n };\n\n extern Timer RootTimer;\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/* Copyright 2020 The TensorFlow Authors. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*\/\n\n#include \"tensorflow\/core\/profiler\/convert\/xplane_to_step_events.h\"\n\n#include \"tensorflow\/core\/lib\/strings\/str_util.h\"\n#include \"tensorflow\/core\/profiler\/utils\/metadata_matcher.h\"\n#include \"tensorflow\/core\/profiler\/utils\/trace_utils.h\"\n#include \"tensorflow\/core\/profiler\/utils\/xplane_schema.h\"\n\nnamespace tensorflow {\nnamespace profiler {\nnamespace {\n\n\/\/ Returns true if the given event_name is a step marker.\ninline bool IsStepMarker(absl::string_view event_name) {\n return (str_util::StartsWith(event_name, \"train\") ||\n str_util::StartsWith(event_name, \"test\") ||\n str_util::StartsWith(event_name, \"TraceContext\")) &&\n !str_util::StrContains(event_name, \"\/\");\n}\n\n\/\/ Returns true if the given event_name should be considered as real computation\n\/\/ on CPU.\ninline bool IsRealCpuCompute(absl::string_view event_name) {\n bool not_real = str_util::StartsWith(event_name, \"EagerExecute\") ||\n str_util::StartsWith(event_name, \"EagerLocalExecute\") ||\n str_util::StartsWith(event_name, \"EagerKernelExecute\") ||\n str_util::StartsWith(event_name, \"FunctionRun\") ||\n IsStepMarker(event_name);\n return !not_real;\n}\n\n} \/\/ namespace\n\nStepEvents ConvertHostThreadsXLineToStepEvents(\n const XLineVisitor& line, bool use_device_step_events,\n const StepEvents& device_step_events) {\n StepEvents result;\n line.ForEachEvent([&](const XEventVisitor& event) {\n int64 correlation_id = -1;\n int64 group_id = -1;\n event.ForEachStat([&](const XStatVisitor& stat) {\n if (stat.Type() == StatType::kCorrelationId) {\n correlation_id = stat.IntValue();\n } else if (stat.Type() == StatType::kGroupId) {\n group_id = stat.IntValue();\n }\n });\n if (group_id < 0) return;\n \/\/ Don't add CPU events when (1) it includes device step events and (2) it\n \/\/ doesn't have a device and that the group_id (i.e. step number) already\n \/\/ appears on the device. This will filter out all cpu events that do not\n \/\/ correspond to any steps executed on the device.\n if (use_device_step_events &&\n device_step_events.find(group_id) == device_step_events.end())\n return;\n Timespan timespan = Timespan(event.TimestampPs(), event.DurationPs());\n if (IsStepMarker(event.Name())) {\n result[group_id].AddMarker(\n StepMarker(\/*device=*\/false, event.Name(), timespan));\n } else if (IsRealCpuCompute(event.Name())) {\n EventTypeSpan event_type_span(\n ClassifyCpuEvent(event.Name(), correlation_id), timespan);\n result[group_id].AddEvent(event_type_span);\n }\n });\n return result;\n}\n\nStepEvents ConvertHostThreadsXPlaneToStepEvents(\n const XPlane& host_trace, bool use_device_step_events,\n const StepEvents& device_step_events) {\n StepEvents result;\n XPlaneVisitor plane(&host_trace);\n plane.ForEachLine([&](const XLineVisitor& line) {\n CombineStepEvents(ConvertHostThreadsXLineToStepEvents(\n line, use_device_step_events, device_step_events),\n &result);\n });\n return result;\n}\n\nStepEvents ConvertDeviceTraceXLineToStepEvents(const XLineVisitor& line) {\n int64 correlation_id = -1;\n int64 group_id = -1;\n StepEvents result;\n line.ForEachEvent([&](const XEventVisitor& event) {\n event.ForEachStat([&](const XStatVisitor& stat) {\n if (stat.Type() == StatType::kCorrelationId) {\n correlation_id = stat.IntValue();\n } else if (stat.Type() == StatType::kGroupId) {\n group_id = stat.IntValue();\n }\n });\n if (correlation_id >= 0 && group_id >= 0) {\n EventTypeSpan event_type_span(\n ClassifyGpuEvent(event.Name()),\n Timespan(event.TimestampPs(), event.DurationPs()));\n result[group_id].AddEvent(event_type_span);\n }\n });\n return result;\n}\n\nStepEvents ConvertDeviceTraceXPlaneToStepEvents(const XPlane& device_trace) {\n StepEvents result;\n XPlaneVisitor plane(&device_trace);\n plane.ForEachLine([&](const XLineVisitor& line) {\n if (IsDerivedThreadId(line.Id())) return;\n CombineStepEvents(ConvertDeviceTraceXLineToStepEvents(line), &result);\n });\n return result;\n}\n\n} \/\/ namespace profiler\n} \/\/ namespace tensorflow\n<commit_msg>Fix a bug that kernel launch events are over calculated.<commit_after>\/* Copyright 2020 The TensorFlow Authors. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*\/\n\n#include \"tensorflow\/core\/profiler\/convert\/xplane_to_step_events.h\"\n\n#include \"tensorflow\/core\/lib\/strings\/str_util.h\"\n#include \"tensorflow\/core\/profiler\/utils\/metadata_matcher.h\"\n#include \"tensorflow\/core\/profiler\/utils\/trace_utils.h\"\n#include \"tensorflow\/core\/profiler\/utils\/xplane_schema.h\"\n\nnamespace tensorflow {\nnamespace profiler {\nnamespace {\n\n\/\/ Returns true if the given event_name is a step marker.\ninline bool IsStepMarker(absl::string_view event_name) {\n return (str_util::StartsWith(event_name, \"train\") ||\n str_util::StartsWith(event_name, \"test\") ||\n str_util::StartsWith(event_name, \"TraceContext\")) &&\n !str_util::StrContains(event_name, \"\/\");\n}\n\n\/\/ Returns true if the given event_name should be considered as real computation\n\/\/ on CPU.\ninline bool IsRealCpuCompute(absl::string_view event_name) {\n bool not_real = str_util::StartsWith(event_name, \"EagerExecute\") ||\n str_util::StartsWith(event_name, \"EagerLocalExecute\") ||\n str_util::StartsWith(event_name, \"EagerKernelExecute\") ||\n str_util::StartsWith(event_name, \"FunctionRun\") ||\n IsStepMarker(event_name);\n return !not_real;\n}\n\n} \/\/ namespace\n\nStepEvents ConvertHostThreadsXLineToStepEvents(\n const XLineVisitor& line, bool use_device_step_events,\n const StepEvents& device_step_events) {\n StepEvents result;\n line.ForEachEvent([&](const XEventVisitor& event) {\n int64 correlation_id = -1;\n int64 group_id = -1;\n event.ForEachStat([&](const XStatVisitor& stat) {\n if (stat.Type() == StatType::kCorrelationId) {\n correlation_id = stat.IntValue();\n } else if (stat.Type() == StatType::kGroupId) {\n group_id = stat.IntValue();\n }\n });\n if (group_id < 0) return;\n \/\/ Don't add CPU events when (1) it includes device step events and (2) it\n \/\/ doesn't have a device and that the group_id (i.e. step number) already\n \/\/ appears on the device. This will filter out all cpu events that do not\n \/\/ correspond to any steps executed on the device.\n if (use_device_step_events &&\n device_step_events.find(group_id) == device_step_events.end())\n return;\n Timespan timespan = Timespan(event.TimestampPs(), event.DurationPs());\n if (IsStepMarker(event.Name())) {\n result[group_id].AddMarker(\n StepMarker(\/*device=*\/false, event.Name(), timespan));\n } else if (IsRealCpuCompute(event.Name())) {\n EventTypeSpan event_type_span(\n ClassifyCpuEvent(event.Name(), correlation_id), timespan);\n result[group_id].AddEvent(event_type_span);\n }\n });\n return result;\n}\n\nStepEvents ConvertHostThreadsXPlaneToStepEvents(\n const XPlane& host_trace, bool use_device_step_events,\n const StepEvents& device_step_events) {\n StepEvents result;\n XPlaneVisitor plane(&host_trace);\n plane.ForEachLine([&](const XLineVisitor& line) {\n CombineStepEvents(ConvertHostThreadsXLineToStepEvents(\n line, use_device_step_events, device_step_events),\n &result);\n });\n return result;\n}\n\nStepEvents ConvertDeviceTraceXLineToStepEvents(const XLineVisitor& line) {\n StepEvents result;\n line.ForEachEvent([&](const XEventVisitor& event) {\n int64 correlation_id = -1;\n int64 group_id = -1;\n event.ForEachStat([&](const XStatVisitor& stat) {\n if (stat.Type() == StatType::kCorrelationId) {\n correlation_id = stat.IntValue();\n } else if (stat.Type() == StatType::kGroupId) {\n group_id = stat.IntValue();\n }\n });\n if (correlation_id >= 0 && group_id >= 0) {\n EventTypeSpan event_type_span(\n ClassifyGpuEvent(event.Name()),\n Timespan(event.TimestampPs(), event.DurationPs()));\n result[group_id].AddEvent(event_type_span);\n }\n });\n return result;\n}\n\nStepEvents ConvertDeviceTraceXPlaneToStepEvents(const XPlane& device_trace) {\n StepEvents result;\n XPlaneVisitor plane(&device_trace);\n plane.ForEachLine([&](const XLineVisitor& line) {\n if (IsDerivedThreadId(line.Id())) return;\n CombineStepEvents(ConvertDeviceTraceXLineToStepEvents(line), &result);\n });\n return result;\n}\n\n} \/\/ namespace profiler\n} \/\/ namespace tensorflow\n<|endoftext|>"} {"text":"<commit_before>\/*\n Copyright (c) 2018 Anon authors, see AUTHORS file.\n \n Permission is hereby granted, free of charge, to any person obtaining a copy\n of this software and associated documentation files (the \"Software\"), to deal\n in the Software without restriction, including without limitation the rights\n to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n copies of the Software, and to permit persons to whom the Software is\n furnished to do so, subject to the following conditions:\n \n The above copyright notice and this permission notice shall be included in\n all copies or substantial portions of the Software.\n \n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n THE SOFTWARE.\n*\/\n\n#include \"aws_sqs.h\"\n#include <aws\/sqs\/model\/QueueAttributeName.h>\n#include <aws\/sqs\/model\/SendMessageRequest.h>\n\nusing namespace Aws::SQS;\nusing json = nlohmann::json;\n\naws_sqs_listener::aws_sqs_listener(const std::shared_ptr<Aws::Auth::AWSCredentialsProvider> &provider,\n const Aws::Client::ClientConfiguration &client_config,\n const Aws::String &queue_url,\n const std::function<bool(const Aws::SQS::Model::Message &m)> &handler,\n bool single_concurrent_message,\n size_t stack_size)\n : _client(provider, client_config),\n _queue_url(queue_url),\n _num_fibers(0),\n _exit_now(false),\n _process_msg(handler),\n _consecutive_errors(0),\n _single_concurrent_message(single_concurrent_message),\n _stack_size(stack_size),\n _continue_after_timeout([]{return true;})\n{\n}\n\naws_sqs_listener::aws_sqs_listener(const std::shared_ptr<Aws::Auth::AWSCredentialsProvider> &provider,\n const Aws::Client::ClientConfiguration &client_config,\n const Aws::String &queue_url,\n const std::function<bool(const Aws::SQS::Model::Message &m, const std::function<void(bool delete_it)>&)> &handler,\n bool single_concurrent_message,\n size_t stack_size)\n : _client(provider, client_config),\n _queue_url(queue_url),\n _num_fibers(0),\n _exit_now(false),\n _process_msg_del(handler),\n _consecutive_errors(0),\n _single_concurrent_message(single_concurrent_message),\n _stack_size(stack_size),\n _continue_after_timeout([]{return true;})\n{\n}\n\nvoid aws_sqs_listener::start()\n{\n std::weak_ptr<aws_sqs_listener> wp = shared_from_this();\n\n fiber::run_in_fiber(\n [wp] {\n auto ths = wp.lock();\n if (ths)\n ths->start_listen();\n },\n aws_sqs_listener::_simple_stack_size, \"aws_sqs_listener::aws_sqs_listener, start_listen\");\n\n #if defined(ANON_DEBUG_TIMERS)\n anon_log(\"io_dispatch::schedule_task, aws_sqs_listener::start\");\n #endif\n _timer_task = io_dispatch::schedule_task(\n [wp] {\n fiber::run_in_fiber(\n [wp] {\n auto ths = wp.lock();\n if (ths)\n ths->set_visibility_timeout();\n },\n aws_sqs_listener::_simple_stack_size, \"aws_sqs_listener, set_visibility_timeout sweeper\");\n },\n cur_time() + visibility_sweep_time);\n}\n\naws_sqs_listener::~aws_sqs_listener()\n{\n {\n _exit_now = true;\n fiber_lock l(_mtx);\n while (_num_fibers > 0)\n _num_fibers_cond.wait(l);\n }\n io_dispatch::remove_task(_timer_task);\n}\n\nstd::function<bool(const Aws::SQS::Model::Message &m)> aws_sqs_listener::js_wrap(const std::function<bool(const Aws::SQS::Model::Message &m, const nlohmann::json &body)> &fn)\n{\n return [fn](const Aws::SQS::Model::Message &m) -> bool {\n std::string body = get_body(m);\n try\n {\n json body_js = json::parse(body.begin(), body.end());\n try\n {\n return fn(m, body_js);\n }\n catch (const inval_message& exc)\n {\n anon_log_error(\"caught exception processing message: \" << exc.what() << \", message body: '\" << body << \"'\");\n return true;\n }\n catch (const std::exception &exc)\n {\n anon_log_error(\"caught exception processing message: \" << exc.what() << \", message body: '\" << body << \"'\");\n return false;\n }\n catch (...)\n {\n anon_log_error(\"caught unknown exception processing message, message body: '\" << body << \"'\");\n return false;\n }\n }\n catch (const std::exception &exc)\n {\n anon_log_error(\"caught exception parsing message: \" << exc.what() << \", message body: '\" << body << \"'\");\n return true;\n }\n catch (...)\n {\n anon_log_error(\"caught unknown exception parsing message, message body: '\" << body << \"'\");\n return true;\n }\n };\n}\n\nstd::function<bool(const Aws::SQS::Model::Message &m, const std::function<void(bool delete_it)>& del)> aws_sqs_listener::js_wrap(const std::function<bool(const Aws::SQS::Model::Message &m, const std::function<void(bool delete_it)>& del, const nlohmann::json &body)> &fn)\n{\n return [fn](const Aws::SQS::Model::Message &m, const std::function<void(bool delete_it)>& del) -> bool {\n std::string body = get_body(m);\n try\n {\n json body_js = json::parse(body.begin(), body.end());\n try\n {\n return fn(m, del, body_js);\n }\n catch (const inval_message& exc)\n {\n anon_log_error(\"caught exception processing message: \" << exc.what() << \", message body: '\" << body << \"'\");\n del(true);\n return true;\n }\n catch (const std::exception &exc)\n {\n anon_log_error(\"caught exception processing message: \" << exc.what() << \", message body: '\" << body << \"'\");\n return false;\n }\n catch (...)\n {\n anon_log_error(\"caught unknown exception processing message, message body: '\" << body << \"'\");\n return false;\n }\n }\n catch (const std::exception &exc)\n {\n anon_log_error(\"caught exception parsing message: \" << exc.what() << \", message body: '\" << body << \"'\");\n del(true);\n return true;\n }\n catch (...)\n {\n anon_log_error(\"caught unknown exception parsing message, message body: '\" << body << \"'\");\n del(true);\n return true;\n }\n };\n}\n\nvoid aws_sqs_listener::start_listen()\n{\n Model::ReceiveMessageRequest req;\n req.WithQueueUrl(_queue_url).WithMaxNumberOfMessages(_single_concurrent_message ? 1 : max_messages_per_read).WithWaitTimeSeconds(read_wait_time);\n Aws::Vector<Model::QueueAttributeName> att;\n att.push_back(Model::QueueAttributeName::All);\n req.WithAttributeNames(std::move(att));\n std::weak_ptr<aws_sqs_listener> wp = shared_from_this();\n _client.ReceiveMessageAsync(req, [wp](const SQSClient *, const Model::ReceiveMessageRequest &, const Model::ReceiveMessageOutcome &out, const std::shared_ptr<const Aws::Client::AsyncCallerContext> &) {\n auto ths = wp.lock();\n if (!ths)\n return;\n fiber::rename_fiber(\"aws_sqs_listener::start_listen, ReceiveMessageAsync\");\n if (!out.IsSuccess())\n {\n ++ths->_consecutive_errors;\n if (ths->_consecutive_errors > 10)\n {\n anon_log_error(\"SQS ReceiveMessage failed, _consecutive_errors: \" << ths->_consecutive_errors << \"\\n\"\n << out.GetError());\n }\n else\n {\n anon_log(\"SQS ReceiveMessage failed, _consecutive_errors: \" << ths->_consecutive_errors);\n }\n \n fiber::msleep(2000);\n }\n else\n {\n ths->_consecutive_errors = 0;\n auto &messages = out.GetResult().GetMessages();\n auto num_messages = messages.size();\n\n if (num_messages > 0)\n {\n ths->_num_fibers += num_messages;\n for (auto &m : messages)\n fiber::run_in_fiber(\n [wp, m] {\n auto ths = wp.lock();\n if (!ths)\n return;\n anon_log(\"adding message \" << m.GetMessageId() << \" to keep_alive\");\n ths->add_to_keep_alive(m);\n bool success;\n if (ths->_process_msg) {\n success = ths->_process_msg(m);\n if (success)\n ths->delete_message(m);\n if (ths->_single_concurrent_message && !ths->_exit_now)\n ths->start_listen();\n }\n else\n success = ths->_process_msg_del(m, [wp, m](bool delete_it) {\n auto ths = wp.lock();\n if (ths) {\n if (delete_it)\n ths->delete_message(m);\n else\n ths->remove_from_keep_alive(m, true);\n }\n });\n if (!success)\n ths->remove_from_keep_alive(m, true);\n },\n ths->_stack_size, \"aws_sqs_listener, process_msg\");\n } else {\n if (!ths->_continue_after_timeout())\n ths->_exit_now = true;\n }\n }\n\n if (ths->_consecutive_errors < 1000)\n {\n if (!ths->_single_concurrent_message && !ths->_exit_now)\n {\n fiber_lock l(ths->_mtx);\n while (ths->_num_fibers >= max_in_flight_fibers)\n ths->_num_fibers_cond.wait(l);\n fiber::run_in_fiber(\n [wp] {\n auto ths = wp.lock();\n if (ths)\n ths->start_listen();\n },\n aws_sqs_listener::_simple_stack_size, \"aws_sqs_listener, restart_listen\");\n }\n }\n else\n anon_log_error(\"too many consecutive errors, giving up...\");\n });\n}\n\nvoid aws_sqs_listener::set_visibility_timeout()\n{\n fiber_lock l(_mtx);\n auto numMessages = _alive_set.size();\n if (numMessages > 0)\n {\n Model::ChangeMessageVisibilityBatchRequest req;\n Aws::Vector<Aws::Vector<Model::ChangeMessageVisibilityBatchRequestEntry>> entries_v;\n int index = 0;\n for (auto it : _alive_set)\n {\n Model::ChangeMessageVisibilityBatchRequestEntry ent;\n std::ostringstream str;\n if (index % 10 == 0)\n entries_v.push_back(Aws::Vector<Model::ChangeMessageVisibilityBatchRequestEntry>());\n str << \"message_\" << ++index;\n ent.WithReceiptHandle(it.first).WithVisibilityTimeout(visibility_time).WithId(str.str());\n entries_v.back().push_back(ent);\n }\n for (auto &entries : entries_v)\n {\n req.WithQueueUrl(_queue_url).WithEntries(entries);\n auto nMessages = entries.size();\n _client.ChangeMessageVisibilityBatchAsync(req, [nMessages](const SQSClient *, const Model::ChangeMessageVisibilityBatchRequest &, const Model::ChangeMessageVisibilityBatchOutcome &out, const std::shared_ptr<const Aws::Client::AsyncCallerContext> &) {\n fiber::rename_fiber(\"aws_sqs_listener::set_visibility_timeout, ChangeMessageVisibilityBatchAsync\");\n if (out.IsSuccess())\n {\n anon_log(\"batch visibilty reset for \" << nMessages << \" messages\");\n }\n else\n {\n do_error(\"batch reset visibility for \" << nMessages << \" messages: \" << out.GetError().GetMessage());\n }\n });\n }\n }\n\n \/\/ schedule the sweep to run again in visibility_sweep_time seconds\n std::weak_ptr<aws_sqs_listener> wp = shared_from_this();\n #if defined(ANON_DEBUG_TIMERS)\n anon_log(\"io_dispatch::schedule_task, aws_sqs_listener::set_visibility_timeout\");\n #endif\n _timer_task = io_dispatch::schedule_task(\n [wp] {\n fiber::run_in_fiber(\n [wp] {\n auto ths = wp.lock();\n if (ths)\n ths->set_visibility_timeout();\n },\n aws_sqs_listener::_simple_stack_size, \"aws_sqs_listener, set_visibility_timeout sweeper\");\n },\n cur_time() + visibility_sweep_time);\n}\n\nvoid aws_sqs_listener::add_to_keep_alive(const Model::Message &m)\n{\n fiber_lock l(_mtx);\n _alive_set[m.GetReceiptHandle()] = m.GetMessageId();\n}\n\nvoid aws_sqs_listener::remove_from_keep_alive(const Model::Message &m, bool reset_visibility)\n{\n {\n fiber_lock l(_mtx);\n _alive_set.erase(m.GetReceiptHandle());\n }\n if (reset_visibility)\n {\n \/\/ encourage the system to try this message again soon by resetting its visility near 0\n Model::ChangeMessageVisibilityRequest req;\n req.WithQueueUrl(_queue_url).WithReceiptHandle(m.GetReceiptHandle()).WithVisibilityTimeout(visibility_immediate_retry_time);\n auto messageId = m.GetMessageId();\n _client.ChangeMessageVisibilityAsync(req, [messageId](const SQSClient *, const Model::ChangeMessageVisibilityRequest &, const Model::ChangeMessageVisibilityOutcome &out, const std::shared_ptr<const Aws::Client::AsyncCallerContext> &) {\n fiber::rename_fiber(\"aws_sqs_listener::remove_from_keep_alive, ChangeMessageVisibilityAsync\");\n if (out.IsSuccess())\n {\n anon_log(\"reset message visibility near 0 for \" << messageId);\n }\n else\n {\n do_error(\"reset message visibility near 0 for \" << messageId << \", \" << out.GetError().GetMessage());\n }\n });\n }\n}\n\nvoid aws_sqs_listener::delete_message(const Model::Message &m)\n{\n Model::DeleteMessageRequest req;\n req.WithQueueUrl(_queue_url).WithReceiptHandle(m.GetReceiptHandle());\n auto messageId = m.GetMessageId();\n std::weak_ptr<aws_sqs_listener> wp = shared_from_this();\n _client.DeleteMessageAsync(req, [messageId, wp, m](const SQSClient *, const Model::DeleteMessageRequest &, const Model::DeleteMessageOutcome &out, const std::shared_ptr<const Aws::Client::AsyncCallerContext> &) {\n fiber::rename_fiber(\"aws_sqs_listener::delete_message, DeleteMessageAsync\");\n if (out.IsSuccess())\n {\n anon_log(\"deleted SQS message \" << messageId);\n }\n else\n {\n anon_log(\"delete SQS message failed, messageId:\" << messageId << \", \" << out.GetError().GetMessage());\n }\n auto ths = wp.lock();\n if (ths)\n ths->remove_from_keep_alive(m, false);\n });\n}\n\naws_sqs_sender::aws_sqs_sender(const std::shared_ptr<Aws::Auth::AWSCredentialsProvider> &provider,\n const Aws::Client::ClientConfiguration &client_config,\n const Aws::String &queue_url)\n : _client(provider, client_config),\n _queue_url(queue_url)\n{\n}\n\nvoid aws_sqs_sender::send(const json &body,\n const std::function<void(const bool success, const std::string &id, const std::string &errorReason)> &response)\n{\n Model::SendMessageRequest req;\n req.WithQueueUrl(_queue_url).WithMessageBody(Aws::String(body.dump()));\n _client.SendMessageAsync(req, [response](const SQSClient *, const Model::SendMessageRequest &, const Model::SendMessageOutcome &outcome, const std::shared_ptr<const Aws::Client::AsyncCallerContext> &) {\n fiber::rename_fiber(\"aws_sqs_sender::send, SendMessageAsync\");\n response(outcome.IsSuccess(),\n std::string(outcome.GetResult().GetMessageId()),\n std::string(outcome.GetError().GetMessage()));\n });\n}\n<commit_msg>less logging<commit_after>\/*\n Copyright (c) 2018 Anon authors, see AUTHORS file.\n \n Permission is hereby granted, free of charge, to any person obtaining a copy\n of this software and associated documentation files (the \"Software\"), to deal\n in the Software without restriction, including without limitation the rights\n to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n copies of the Software, and to permit persons to whom the Software is\n furnished to do so, subject to the following conditions:\n \n The above copyright notice and this permission notice shall be included in\n all copies or substantial portions of the Software.\n \n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n THE SOFTWARE.\n*\/\n\n#include \"aws_sqs.h\"\n#include <aws\/sqs\/model\/QueueAttributeName.h>\n#include <aws\/sqs\/model\/SendMessageRequest.h>\n\nusing namespace Aws::SQS;\nusing json = nlohmann::json;\n\naws_sqs_listener::aws_sqs_listener(const std::shared_ptr<Aws::Auth::AWSCredentialsProvider> &provider,\n const Aws::Client::ClientConfiguration &client_config,\n const Aws::String &queue_url,\n const std::function<bool(const Aws::SQS::Model::Message &m)> &handler,\n bool single_concurrent_message,\n size_t stack_size)\n : _client(provider, client_config),\n _queue_url(queue_url),\n _num_fibers(0),\n _exit_now(false),\n _process_msg(handler),\n _consecutive_errors(0),\n _single_concurrent_message(single_concurrent_message),\n _stack_size(stack_size),\n _continue_after_timeout([]{return true;})\n{\n}\n\naws_sqs_listener::aws_sqs_listener(const std::shared_ptr<Aws::Auth::AWSCredentialsProvider> &provider,\n const Aws::Client::ClientConfiguration &client_config,\n const Aws::String &queue_url,\n const std::function<bool(const Aws::SQS::Model::Message &m, const std::function<void(bool delete_it)>&)> &handler,\n bool single_concurrent_message,\n size_t stack_size)\n : _client(provider, client_config),\n _queue_url(queue_url),\n _num_fibers(0),\n _exit_now(false),\n _process_msg_del(handler),\n _consecutive_errors(0),\n _single_concurrent_message(single_concurrent_message),\n _stack_size(stack_size),\n _continue_after_timeout([]{return true;})\n{\n}\n\nvoid aws_sqs_listener::start()\n{\n std::weak_ptr<aws_sqs_listener> wp = shared_from_this();\n\n fiber::run_in_fiber(\n [wp] {\n auto ths = wp.lock();\n if (ths)\n ths->start_listen();\n },\n aws_sqs_listener::_simple_stack_size, \"aws_sqs_listener::aws_sqs_listener, start_listen\");\n\n #if defined(ANON_DEBUG_TIMERS)\n anon_log(\"io_dispatch::schedule_task, aws_sqs_listener::start\");\n #endif\n _timer_task = io_dispatch::schedule_task(\n [wp] {\n fiber::run_in_fiber(\n [wp] {\n auto ths = wp.lock();\n if (ths)\n ths->set_visibility_timeout();\n },\n aws_sqs_listener::_simple_stack_size, \"aws_sqs_listener, set_visibility_timeout sweeper\");\n },\n cur_time() + visibility_sweep_time);\n}\n\naws_sqs_listener::~aws_sqs_listener()\n{\n {\n _exit_now = true;\n fiber_lock l(_mtx);\n while (_num_fibers > 0)\n _num_fibers_cond.wait(l);\n }\n io_dispatch::remove_task(_timer_task);\n}\n\nstd::function<bool(const Aws::SQS::Model::Message &m)> aws_sqs_listener::js_wrap(const std::function<bool(const Aws::SQS::Model::Message &m, const nlohmann::json &body)> &fn)\n{\n return [fn](const Aws::SQS::Model::Message &m) -> bool {\n std::string body = get_body(m);\n try\n {\n json body_js = json::parse(body.begin(), body.end());\n try\n {\n return fn(m, body_js);\n }\n catch (const inval_message& exc)\n {\n anon_log_error(\"caught exception processing message: \" << exc.what() << \", message body: '\" << body << \"'\");\n return true;\n }\n catch (const std::exception &exc)\n {\n anon_log_error(\"caught exception processing message: \" << exc.what() << \", message body: '\" << body << \"'\");\n return false;\n }\n catch (...)\n {\n anon_log_error(\"caught unknown exception processing message, message body: '\" << body << \"'\");\n return false;\n }\n }\n catch (const std::exception &exc)\n {\n anon_log_error(\"caught exception parsing message: \" << exc.what() << \", message body: '\" << body << \"'\");\n return true;\n }\n catch (...)\n {\n anon_log_error(\"caught unknown exception parsing message, message body: '\" << body << \"'\");\n return true;\n }\n };\n}\n\nstd::function<bool(const Aws::SQS::Model::Message &m, const std::function<void(bool delete_it)>& del)> aws_sqs_listener::js_wrap(const std::function<bool(const Aws::SQS::Model::Message &m, const std::function<void(bool delete_it)>& del, const nlohmann::json &body)> &fn)\n{\n return [fn](const Aws::SQS::Model::Message &m, const std::function<void(bool delete_it)>& del) -> bool {\n std::string body = get_body(m);\n try\n {\n json body_js = json::parse(body.begin(), body.end());\n try\n {\n return fn(m, del, body_js);\n }\n catch (const inval_message& exc)\n {\n anon_log_error(\"caught exception processing message: \" << exc.what() << \", message body: '\" << body << \"'\");\n del(true);\n return true;\n }\n catch (const std::exception &exc)\n {\n anon_log_error(\"caught exception processing message: \" << exc.what() << \", message body: '\" << body << \"'\");\n return false;\n }\n catch (...)\n {\n anon_log_error(\"caught unknown exception processing message, message body: '\" << body << \"'\");\n return false;\n }\n }\n catch (const std::exception &exc)\n {\n anon_log_error(\"caught exception parsing message: \" << exc.what() << \", message body: '\" << body << \"'\");\n del(true);\n return true;\n }\n catch (...)\n {\n anon_log_error(\"caught unknown exception parsing message, message body: '\" << body << \"'\");\n del(true);\n return true;\n }\n };\n}\n\nvoid aws_sqs_listener::start_listen()\n{\n Model::ReceiveMessageRequest req;\n req.WithQueueUrl(_queue_url).WithMaxNumberOfMessages(_single_concurrent_message ? 1 : max_messages_per_read).WithWaitTimeSeconds(read_wait_time);\n Aws::Vector<Model::QueueAttributeName> att;\n att.push_back(Model::QueueAttributeName::All);\n req.WithAttributeNames(std::move(att));\n std::weak_ptr<aws_sqs_listener> wp = shared_from_this();\n _client.ReceiveMessageAsync(req, [wp](const SQSClient *, const Model::ReceiveMessageRequest &, const Model::ReceiveMessageOutcome &out, const std::shared_ptr<const Aws::Client::AsyncCallerContext> &) {\n auto ths = wp.lock();\n if (!ths)\n return;\n fiber::rename_fiber(\"aws_sqs_listener::start_listen, ReceiveMessageAsync\");\n if (!out.IsSuccess())\n {\n ++ths->_consecutive_errors;\n if (ths->_consecutive_errors > 10)\n {\n anon_log_error(\"SQS ReceiveMessage failed, _consecutive_errors: \" << ths->_consecutive_errors << \"\\n\"\n << out.GetError());\n }\n else\n {\n anon_log(\"SQS ReceiveMessage failed, _consecutive_errors: \" << ths->_consecutive_errors);\n }\n \n fiber::msleep(2000);\n }\n else\n {\n ths->_consecutive_errors = 0;\n auto &messages = out.GetResult().GetMessages();\n auto num_messages = messages.size();\n\n if (num_messages > 0)\n {\n ths->_num_fibers += num_messages;\n for (auto &m : messages)\n fiber::run_in_fiber(\n [wp, m] {\n auto ths = wp.lock();\n if (!ths)\n return;\n anon_log(\"adding message \" << m.GetMessageId() << \" to keep_alive\");\n ths->add_to_keep_alive(m);\n bool success;\n if (ths->_process_msg) {\n success = ths->_process_msg(m);\n if (success)\n ths->delete_message(m);\n if (ths->_single_concurrent_message && !ths->_exit_now)\n ths->start_listen();\n }\n else\n success = ths->_process_msg_del(m, [wp, m](bool delete_it) {\n auto ths = wp.lock();\n if (ths) {\n if (delete_it)\n ths->delete_message(m);\n else\n ths->remove_from_keep_alive(m, true);\n }\n });\n if (!success)\n ths->remove_from_keep_alive(m, true);\n },\n ths->_stack_size, \"aws_sqs_listener, process_msg\");\n } else {\n if (!ths->_continue_after_timeout())\n ths->_exit_now = true;\n }\n }\n\n if (ths->_consecutive_errors < 1000)\n {\n if (!ths->_single_concurrent_message && !ths->_exit_now)\n {\n fiber_lock l(ths->_mtx);\n while (ths->_num_fibers >= max_in_flight_fibers)\n ths->_num_fibers_cond.wait(l);\n fiber::run_in_fiber(\n [wp] {\n auto ths = wp.lock();\n if (ths)\n ths->start_listen();\n },\n aws_sqs_listener::_simple_stack_size, \"aws_sqs_listener, restart_listen\");\n }\n }\n else\n anon_log_error(\"too many consecutive errors, giving up...\");\n });\n}\n\nvoid aws_sqs_listener::set_visibility_timeout()\n{\n fiber_lock l(_mtx);\n auto numMessages = _alive_set.size();\n if (numMessages > 0)\n {\n Model::ChangeMessageVisibilityBatchRequest req;\n Aws::Vector<Aws::Vector<Model::ChangeMessageVisibilityBatchRequestEntry>> entries_v;\n int index = 0;\n for (auto it : _alive_set)\n {\n Model::ChangeMessageVisibilityBatchRequestEntry ent;\n std::ostringstream str;\n if (index % 10 == 0)\n entries_v.push_back(Aws::Vector<Model::ChangeMessageVisibilityBatchRequestEntry>());\n str << \"message_\" << ++index;\n ent.WithReceiptHandle(it.first).WithVisibilityTimeout(visibility_time).WithId(str.str());\n entries_v.back().push_back(ent);\n }\n for (auto &entries : entries_v)\n {\n req.WithQueueUrl(_queue_url).WithEntries(entries);\n auto nMessages = entries.size();\n _client.ChangeMessageVisibilityBatchAsync(req, [nMessages](const SQSClient *, const Model::ChangeMessageVisibilityBatchRequest &, const Model::ChangeMessageVisibilityBatchOutcome &out, const std::shared_ptr<const Aws::Client::AsyncCallerContext> &) {\n fiber::rename_fiber(\"aws_sqs_listener::set_visibility_timeout, ChangeMessageVisibilityBatchAsync\");\n if (out.IsSuccess())\n {\n \/\/ anon_log(\"batch visibilty reset for \" << nMessages << \" message\" << (nMessages > 1 ? \"s\" : \"\"));\n }\n else\n {\n do_error(\"batch reset visibility for \" << nMessages << \" messages: \" << out.GetError().GetMessage());\n }\n });\n }\n }\n\n \/\/ schedule the sweep to run again in visibility_sweep_time seconds\n std::weak_ptr<aws_sqs_listener> wp = shared_from_this();\n #if defined(ANON_DEBUG_TIMERS)\n anon_log(\"io_dispatch::schedule_task, aws_sqs_listener::set_visibility_timeout\");\n #endif\n _timer_task = io_dispatch::schedule_task(\n [wp] {\n fiber::run_in_fiber(\n [wp] {\n auto ths = wp.lock();\n if (ths)\n ths->set_visibility_timeout();\n },\n aws_sqs_listener::_simple_stack_size, \"aws_sqs_listener, set_visibility_timeout sweeper\");\n },\n cur_time() + visibility_sweep_time);\n}\n\nvoid aws_sqs_listener::add_to_keep_alive(const Model::Message &m)\n{\n fiber_lock l(_mtx);\n _alive_set[m.GetReceiptHandle()] = m.GetMessageId();\n}\n\nvoid aws_sqs_listener::remove_from_keep_alive(const Model::Message &m, bool reset_visibility)\n{\n {\n fiber_lock l(_mtx);\n _alive_set.erase(m.GetReceiptHandle());\n }\n if (reset_visibility)\n {\n \/\/ encourage the system to try this message again soon by resetting its visility near 0\n Model::ChangeMessageVisibilityRequest req;\n req.WithQueueUrl(_queue_url).WithReceiptHandle(m.GetReceiptHandle()).WithVisibilityTimeout(visibility_immediate_retry_time);\n auto messageId = m.GetMessageId();\n _client.ChangeMessageVisibilityAsync(req, [messageId](const SQSClient *, const Model::ChangeMessageVisibilityRequest &, const Model::ChangeMessageVisibilityOutcome &out, const std::shared_ptr<const Aws::Client::AsyncCallerContext> &) {\n fiber::rename_fiber(\"aws_sqs_listener::remove_from_keep_alive, ChangeMessageVisibilityAsync\");\n if (out.IsSuccess())\n {\n anon_log(\"reset message visibility near 0 for \" << messageId);\n }\n else\n {\n do_error(\"reset message visibility near 0 for \" << messageId << \", \" << out.GetError().GetMessage());\n }\n });\n }\n}\n\nvoid aws_sqs_listener::delete_message(const Model::Message &m)\n{\n Model::DeleteMessageRequest req;\n req.WithQueueUrl(_queue_url).WithReceiptHandle(m.GetReceiptHandle());\n auto messageId = m.GetMessageId();\n std::weak_ptr<aws_sqs_listener> wp = shared_from_this();\n _client.DeleteMessageAsync(req, [messageId, wp, m](const SQSClient *, const Model::DeleteMessageRequest &, const Model::DeleteMessageOutcome &out, const std::shared_ptr<const Aws::Client::AsyncCallerContext> &) {\n fiber::rename_fiber(\"aws_sqs_listener::delete_message, DeleteMessageAsync\");\n if (out.IsSuccess())\n {\n anon_log(\"deleted SQS message \" << messageId);\n }\n else\n {\n anon_log(\"delete SQS message failed, messageId:\" << messageId << \", \" << out.GetError().GetMessage());\n }\n auto ths = wp.lock();\n if (ths)\n ths->remove_from_keep_alive(m, false);\n });\n}\n\naws_sqs_sender::aws_sqs_sender(const std::shared_ptr<Aws::Auth::AWSCredentialsProvider> &provider,\n const Aws::Client::ClientConfiguration &client_config,\n const Aws::String &queue_url)\n : _client(provider, client_config),\n _queue_url(queue_url)\n{\n}\n\nvoid aws_sqs_sender::send(const json &body,\n const std::function<void(const bool success, const std::string &id, const std::string &errorReason)> &response)\n{\n Model::SendMessageRequest req;\n req.WithQueueUrl(_queue_url).WithMessageBody(Aws::String(body.dump()));\n _client.SendMessageAsync(req, [response](const SQSClient *, const Model::SendMessageRequest &, const Model::SendMessageOutcome &outcome, const std::shared_ptr<const Aws::Client::AsyncCallerContext> &) {\n fiber::rename_fiber(\"aws_sqs_sender::send, SendMessageAsync\");\n response(outcome.IsSuccess(),\n std::string(outcome.GetResult().GetMessageId()),\n std::string(outcome.GetError().GetMessage()));\n });\n}\n<|endoftext|>"} {"text":"<commit_before>\/*********************************************************************\n *\n * Copyright 2012 the original author or authors.\n * See the NOTICE file distributed with this work for additional\n * information regarding copyright ownership.\n * \n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * \n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *********************************************************************\/\n#include \"resizer.h\"\n\n#include<ros\/ros.h>\n#include<sensor_msgs\/CompressedImage.h>\n\nextern \"C\" {\n#include <libswscale\/swscale.h>\n#include <libavutil\/mem.h>\n#if LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(55,28,1)\n#include <libavutil\/frame.h>\n#endif\n}\n\n#if LIBAVCODEC_VERSION_INT < AV_VERSION_INT(55,28,1)\n#define av_frame_alloc avcodec_alloc_frame\n#define av_frame_free av_free\n#endif\n\nnamespace rospilot {\n\nusing std::vector;\nusing sensor_msgs::CompressedImage;\n\nbool Resizer::resizeInPlace(sensor_msgs::CompressedImage *image)\n{\n if (originalWidth == targetWidth && originalHeight == targetHeight) {\n return true;\n }\n\n avpicture_fill(\n (AVPicture*) sourceFrame,\n image->data.data(),\n pixelFormat,\n originalWidth,\n originalHeight);\n\n sws_scale(\n context,\n sourceFrame->data,\n sourceFrame->linesize,\n 0,\n originalHeight, \n outputFrame->data, \n outputFrame->linesize);\n\n\n int size = avpicture_layout(\n (AVPicture *) outputFrame,\n pixelFormat,\n targetWidth,\n targetHeight,\n outputBuffer,\n outputBufferSize);\n if (size != outputBufferSize) {\n ROS_ERROR(\"avpicture_layout failed: %d\",size);\n return false;\n }\n\n image->data.clear();\n image->data.reserve(outputBufferSize);\n image->data.insert(image->data.begin(), outputBuffer, outputBuffer + outputBufferSize);\n\n return true;\n}\n\nResizer::Resizer(\n int originalWidth,\n int originalHeight,\n int targetWidth,\n int targetHeight,\n PixelFormat pixelFormat)\n{\n this->pixelFormat = pixelFormat;\n this->originalWidth = originalWidth;\n this->originalHeight = originalHeight;\n this->targetWidth = targetWidth;\n this->targetHeight = targetHeight;\n \n outputBufferSize = avpicture_get_size(pixelFormat, targetWidth, targetHeight);\n outputBuffer = new uint8_t[outputBufferSize];\n\n outputFrame = av_frame_alloc();\n avpicture_alloc((AVPicture*) outputFrame, pixelFormat, targetWidth, targetHeight);\n \n sourceFrame = av_frame_alloc();\n sourceFrame->width = originalWidth;\n sourceFrame->height = originalHeight;\n sourceFrame->format = pixelFormat;\n\n context = sws_getContext(\n originalWidth,\n originalHeight,\n pixelFormat, \n targetWidth, \n targetHeight,\n pixelFormat,\n SWS_BICUBIC,\n nullptr,\n nullptr, \n nullptr);\n}\n\nResizer::~Resizer()\n{\n av_frame_free(sourceFrame);\n av_frame_free(outputFrame);\n sws_freeContext(context); \n delete[] outputBuffer;\n}\n\n}\n<commit_msg>Fix compilation error on vivid and utopic<commit_after>\/*********************************************************************\n *\n * Copyright 2012 the original author or authors.\n * See the NOTICE file distributed with this work for additional\n * information regarding copyright ownership.\n * \n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * \n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *********************************************************************\/\n#include \"resizer.h\"\n\n#include<ros\/ros.h>\n#include<sensor_msgs\/CompressedImage.h>\n\nextern \"C\" {\n#include <libswscale\/swscale.h>\n#include <libavutil\/mem.h>\n#if LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(55,28,1)\n#include <libavutil\/frame.h>\n#endif\n}\n\n#if LIBAVCODEC_VERSION_INT < AV_VERSION_INT(55,28,1)\n#define av_frame_alloc avcodec_alloc_frame\n#define av_frame_free av_free\n#endif\n\nnamespace rospilot {\n\nusing std::vector;\nusing sensor_msgs::CompressedImage;\n\nbool Resizer::resizeInPlace(sensor_msgs::CompressedImage *image)\n{\n if (originalWidth == targetWidth && originalHeight == targetHeight) {\n return true;\n }\n\n avpicture_fill(\n (AVPicture*) sourceFrame,\n image->data.data(),\n pixelFormat,\n originalWidth,\n originalHeight);\n\n sws_scale(\n context,\n sourceFrame->data,\n sourceFrame->linesize,\n 0,\n originalHeight, \n outputFrame->data, \n outputFrame->linesize);\n\n\n int size = avpicture_layout(\n (AVPicture *) outputFrame,\n pixelFormat,\n targetWidth,\n targetHeight,\n outputBuffer,\n outputBufferSize);\n if (size != outputBufferSize) {\n ROS_ERROR(\"avpicture_layout failed: %d\",size);\n return false;\n }\n\n image->data.clear();\n image->data.reserve(outputBufferSize);\n image->data.insert(image->data.begin(), outputBuffer, outputBuffer + outputBufferSize);\n\n return true;\n}\n\nResizer::Resizer(\n int originalWidth,\n int originalHeight,\n int targetWidth,\n int targetHeight,\n PixelFormat pixelFormat)\n{\n this->pixelFormat = pixelFormat;\n this->originalWidth = originalWidth;\n this->originalHeight = originalHeight;\n this->targetWidth = targetWidth;\n this->targetHeight = targetHeight;\n \n outputBufferSize = avpicture_get_size(pixelFormat, targetWidth, targetHeight);\n outputBuffer = new uint8_t[outputBufferSize];\n\n outputFrame = av_frame_alloc();\n avpicture_alloc((AVPicture*) outputFrame, pixelFormat, targetWidth, targetHeight);\n \n sourceFrame = av_frame_alloc();\n sourceFrame->width = originalWidth;\n sourceFrame->height = originalHeight;\n sourceFrame->format = pixelFormat;\n\n context = sws_getContext(\n originalWidth,\n originalHeight,\n pixelFormat, \n targetWidth, \n targetHeight,\n pixelFormat,\n SWS_BICUBIC,\n nullptr,\n nullptr, \n nullptr);\n}\n\nResizer::~Resizer()\n{\n av_frame_free(&sourceFrame);\n av_frame_free(&outputFrame);\n sws_freeContext(context); \n delete[] outputBuffer;\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * tripolar.cpp\n *\n * Created: 5\/12\/2015 4:02:05 PM\n * Author: Alan\n *\/ \n\n\n\n\/*\n&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&\n&&& USER SETUP\n&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&\n\t*\/\n\n\t#define F_CPU 16000000UL\n\t\/\/#define DO_DEBUG\n\/*\n&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&\n&&& INCLUDES\n&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&\n*\/\n\n#include <avr\/io.h>\n#include \"bldcGimbal.h\"\n\n#include \"afro_nfet.h\"\n#include \"fets.h\"\n\n#include <util\/delay.h>\n#include \"millis.h\"\n#include <stdlib.h>\n\n\n\/*\n&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&\n&&& FUNCTION PROTOTYPES\n&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&\n*\/\n\nvoid setup(void);\nvoid loop(void);\n\n\n\n\/*\n&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&\n&&& STRUCTURES\n&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&\n*\/\n\n\/*****************************************************************************************************\/\n\/* STRUCT: servoIsrData_S\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t *\/\n\/** Data structure used to interact with the Servo Interrupt service routine\t\t\t\t\t\t *\/\n\/*****************************************************************************************************\/\ntypedef struct servoIsrData_S\n{\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\n\tvolatile uint16_t startTimeStamp;\n\tvolatile uint16_t stopTimeStamp;\n\tbool dataReady;\n\tbool waitRising; \/\/If true, we are waiting for a rising edge, otherwise a falling\n\t\n}servoIsrData_T; \n\n\n\/*\n&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&\n&&& VARIABLES\n&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&\n*\/\n\nbldcGimbal gimbal;\nstatic servoIsrData_T servoIsrData;\n\n\n\/*\n&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&\n&&& INTERRUPT SERVICE ROUTINES\n&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&\n*\/\n\nISR(TIMER1_CAPT_vect)\n{\n\tsei();\n\tvolatile uint16_t timeStamp;\t\n\ttimeStamp = micros();\n\tif (servoIsrData.dataReady) return; \/\/we already have a reading, so don't collect a new one till this one is read.\n \n\tif (servoIsrData.waitRising) {\n\t\tservoIsrData.startTimeStamp = timeStamp; \/\/If Rising Edge, record the start time\t\t\t\t\t\t\n\t\tTCCR1B &= ~_BV(ICES1);\/\/Set interrupt for falling edge\n\t\tservoIsrData.waitRising = false;\n\t}\n\telse \/\/Otherwise its a falling edge so ..\t\n\t{\n\t\tservoIsrData.stopTimeStamp = timeStamp;\t\/\/Record the stop time..\n\t\tservoIsrData.dataReady = true;\t\t\t\/\/And signal that we have a value\n\t\tservoIsrData.waitRising = true;\n\t\tTCCR1B |= _BV(ICES1); \/\/Set interrupt for rising edge\t\t\t\t\n\t}\n}\n\n\n\n\/*\n&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&\n&&& SERVO ISR SUPPORT FUNCTIONS\n&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&\n*\/\n\n\ninline void servo_begin(void)\n{\n\tsei(); \/\/Enable nested interrupts\n\tservoIsrData.dataReady = false;\n\tservoIsrData.waitRising = true;\n\t\n\t\/\/Configure PCINT0 PIN (PB0) as an input\n\tDDRB &= ~_BV(DDB0);\n\t\n\t\/\/DISABLE PULLUP RESISTOR (PB0)\n\tPORTB &= ~_BV(PORTB0);\n\t\n\t\/\/Rising Edge Detect\n\tTCCR1B |= _BV(ICES1);\n\t\n\t\/\/Enable Input Compare Interrupt\n\tTIMSK |= _BV(TICIE1);\n\t\n\t\n}\n\n\n\ninline bool servo_changed(void)\n{\n\tif (servoIsrData.dataReady)\n\t{\t\t\n\t\tif (gimbal.motorPwm().icr1Conflict()) {\n\t\t\tTIMSK &= ~_BV(TICIE1);\n\t\t\tservoIsrData.dataReady = false;\t\t\n\t\t\tTIMSK |= _BV(TICIE1);\n\t\t\tredOn();\t\t\t\t\n\t\t}\n\t}\t\t\t\t\t\t \t\n\treturn servoIsrData.dataReady;\t\n}\n\n\ninline uint16_t servo_value_uS(void)\n{\n\tTIMSK &= ~_BV(TICIE1);\n\tuint16_t retVal = servoIsrData.stopTimeStamp - servoIsrData.startTimeStamp;\t\n\tTIMSK |= _BV(TICIE1);\n\tredOff();\t\n\tservoIsrData.dataReady = false;\n\t\n\treturn retVal;\n}\n\n\n\/*\n&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&\n&&& FUNCTIONS\n&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&\n*\/\n\nint main(void)\n{\t\n\tsetup();\t\t\n while(1) loop(); \n}\n\n\nvoid setup(void)\n{\n\t\n\tboardInit();\n\tcli();\n\tredOff();\n\tgreenOn();\n\tmillis_init();\n\tgimbal.begin();\n\tservo_begin();\n}\n\n\ntypedef enum accState_E\n{\n\teAccState_START,\n\teAccState_INITIAL_RAMP,\n\teAccState_HOLD,\n\teAccState_NEXT_SPEED\t\n}accState_T;\n\nvoid loop(void)\n{\n\tstatic int16_t currentSpeed = 0;\n\tstatic uint16_t lastServo = 0;\n\tuint16_t currentServo;\n\tstatic int16_t averageSpeed = 0;\n\t\n\t\n\tif (servo_changed()) \n\t{\n\t\tcurrentServo = servo_value_uS();\t\n\t\tif ((currentServo-1500)>0)\n\t\t{\n\t\t\tasm(\"NOP\");\n\t\t}\t\n\t\tif (currentServo != lastServo)\n\t\t{\n\t\t\tif (currentServo < 2000 && currentServo > 1000) \n\t\t\t{\n\t\t\t\tcurrentSpeed = (currentServo - 1500)*2;\n\t\t\t\taverageSpeed = ((averageSpeed*7) + (currentSpeed*3))\/10;\n\t\t\t\tlastServo = currentServo;\n\t\t\t\tuint8_t powerScale = 1 + (3*abs(currentSpeed) \/350);\n\t\t\t\t\/\/uint8_t powerScale = 4;\n\t\t\t\t\n\t\t\t\tgimbal.set_PowerScale(powerScale);\n\t\t\t\t\n\t\t\t \tgimbal.set_speed_rpm(currentSpeed);\t\t\n\t\t\t\t\/\/gimbal.set_speed_rpm(currentSpeed);\t\t\n\t\t\t}\n\t\t}\n\t}\n\t\t\t\t\t\t\n\tgimbal.tickle();\t\n}\n\n\n<commit_msg>tripolar - scaled speed up<commit_after>\/*\n * tripolar.cpp\n *\n * Created: 5\/12\/2015 4:02:05 PM\n * Author: Alan\n *\/ \n\n\n\n\/*\n&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&\n&&& USER SETUP\n&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&\n\t*\/\n\n\t#define F_CPU 16000000UL\n\t\/\/#define DO_DEBUG\n\/*\n&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&\n&&& INCLUDES\n&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&\n*\/\n\n#include <avr\/io.h>\n#include \"bldcGimbal.h\"\n\n#include \"afro_nfet.h\"\n#include \"fets.h\"\n\n#include <util\/delay.h>\n#include \"millis.h\"\n#include <stdlib.h>\n\n\n\/*\n&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&\n&&& FUNCTION PROTOTYPES\n&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&\n*\/\n\nvoid setup(void);\nvoid loop(void);\n\n\n\n\/*\n&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&\n&&& STRUCTURES\n&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&\n*\/\n\n\/*****************************************************************************************************\/\n\/* STRUCT: servoIsrData_S\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t *\/\n\/** Data structure used to interact with the Servo Interrupt service routine\t\t\t\t\t\t *\/\n\/*****************************************************************************************************\/\ntypedef struct servoIsrData_S\n{\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\n\tvolatile uint16_t startTimeStamp;\n\tvolatile uint16_t stopTimeStamp;\n\tbool dataReady;\n\tbool waitRising; \/\/If true, we are waiting for a rising edge, otherwise a falling\n\t\n}servoIsrData_T; \n\n\n\/*\n&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&\n&&& VARIABLES\n&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&\n*\/\n\nbldcGimbal gimbal;\nstatic servoIsrData_T servoIsrData;\n\n\n\/*\n&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&\n&&& INTERRUPT SERVICE ROUTINES\n&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&\n*\/\n\nISR(TIMER1_CAPT_vect)\n{\n\tsei();\n\tvolatile uint16_t timeStamp;\t\n\ttimeStamp = micros();\n\tif (servoIsrData.dataReady) return; \/\/we already have a reading, so don't collect a new one till this one is read.\n \n\tif (servoIsrData.waitRising) {\n\t\tservoIsrData.startTimeStamp = timeStamp; \/\/If Rising Edge, record the start time\t\t\t\t\t\t\n\t\tTCCR1B &= ~_BV(ICES1);\/\/Set interrupt for falling edge\n\t\tservoIsrData.waitRising = false;\n\t}\n\telse \/\/Otherwise its a falling edge so ..\t\n\t{\n\t\tservoIsrData.stopTimeStamp = timeStamp;\t\/\/Record the stop time..\n\t\tservoIsrData.dataReady = true;\t\t\t\/\/And signal that we have a value\n\t\tservoIsrData.waitRising = true;\n\t\tTCCR1B |= _BV(ICES1); \/\/Set interrupt for rising edge\t\t\t\t\n\t}\n}\n\n\n\n\/*\n&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&\n&&& SERVO ISR SUPPORT FUNCTIONS\n&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&\n*\/\n\n\ninline void servo_begin(void)\n{\n\tsei(); \/\/Enable nested interrupts\n\tservoIsrData.dataReady = false;\n\tservoIsrData.waitRising = true;\n\t\n\t\/\/Configure PCINT0 PIN (PB0) as an input\n\tDDRB &= ~_BV(DDB0);\n\t\n\t\/\/DISABLE PULLUP RESISTOR (PB0)\n\tPORTB &= ~_BV(PORTB0);\n\t\n\t\/\/Rising Edge Detect\n\tTCCR1B |= _BV(ICES1);\n\t\n\t\/\/Enable Input Compare Interrupt\n\tTIMSK |= _BV(TICIE1);\n\t\n\t\n}\n\n\n\ninline bool servo_changed(void)\n{\n\tif (servoIsrData.dataReady)\n\t{\t\t\n\t\tif (gimbal.motorPwm().icr1Conflict()) {\n\t\t\tTIMSK &= ~_BV(TICIE1);\n\t\t\tservoIsrData.dataReady = false;\t\t\n\t\t\tTIMSK |= _BV(TICIE1);\n\t\t\tredOn();\t\t\t\t\n\t\t}\n\t}\t\t\t\t\t\t \t\n\treturn servoIsrData.dataReady;\t\n}\n\n\ninline uint16_t servo_value_uS(void)\n{\n\tTIMSK &= ~_BV(TICIE1);\n\tuint16_t retVal = servoIsrData.stopTimeStamp - servoIsrData.startTimeStamp;\t\n\tTIMSK |= _BV(TICIE1);\n\tredOff();\t\n\tservoIsrData.dataReady = false;\n\t\n\treturn retVal;\n}\n\n\n\/*\n&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&\n&&& FUNCTIONS\n&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&\n*\/\n\nint main(void)\n{\t\n\tsetup();\t\t\n while(1) loop(); \n}\n\n\nvoid setup(void)\n{\n\t\n\tboardInit();\n\tcli();\n\tredOff();\n\tgreenOn();\n\tmillis_init();\n\tgimbal.begin();\n\tservo_begin();\n}\n\n\ntypedef enum accState_E\n{\n\teAccState_START,\n\teAccState_INITIAL_RAMP,\n\teAccState_HOLD,\n\teAccState_NEXT_SPEED\t\n}accState_T;\n\nvoid loop(void)\n{\n\tstatic int16_t currentSpeed = 0;\n\tstatic int16_t lastServo = 0;\n\tint16_t currentServo;\n\tstatic int16_t averageSpeed = 0;\n\t\n\t\n\tif (servo_changed()) \n\t{\n\t\tcurrentServo = servo_value_uS();\t\n\t\tif (abs(currentServo-1500)>1)\n\t\t{\n\t\t\tasm(\"NOP\");\n\t\t}\t\n\t\tif (currentServo != lastServo)\n\t\t{\n\t\t\tif (currentServo < 2000 && currentServo > 1000) \n\t\t\t{\n\t\t\t\tcurrentSpeed = (11*(currentServo - 1500))\/10;\n\t\t\t\taverageSpeed = ((averageSpeed*7) + (currentSpeed*3))\/10;\n\t\t\t\tlastServo = currentServo;\n\t\t\t\tuint8_t powerScale = 1 + (3*abs(currentSpeed) \/350);\n\t\t\t\t\/\/uint8_t powerScale = 4;\n\t\t\t\t\n\t\t\t\tgimbal.set_PowerScale(powerScale);\n\t\t\t\t\n\t\t\t \tgimbal.set_speed_rpm(currentSpeed);\t\t\n\t\t\t\t\/\/gimbal.set_speed_rpm(currentSpeed);\t\t\n\t\t\t}\n\t\t}\n\t}\n\t\t\t\t\t\t\n\tgimbal.tickle();\t\n}\n\n\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n#include <cassert>\n\n#include \"base64.h\"\n\nvoid runEncodeTests ()\n{\n \/\/test1, encode3({'a','a','a'}) == \"YWFh\"\n char testStr3[3];\n testStr3[0] = 'a';\n testStr3[1] = 'a';\n testStr3[2] = 'a';\n assert(base64Encode3Bytes(testStr3) == \"YWFh\");\n\n \/\/test2, encode3({'x','y','z'}) == \"eHl6\"\n testStr3[0] = 'x';\n testStr3[1] = 'y';\n testStr3[2] = 'z';\n assert(base64Encode3Bytes(testStr3) == \"eHl6\");\n\n \/\/test3, encode2({'a','a'}) == \"YWE=\"\n char testStr2[2];\n testStr2[0] = 'a';\n testStr2[1] = 'a';\n assert(base64Encode2Bytes(testStr2) == \"YWE=\");\n assert(base64Encode(testStr2, 2) == \"YWE=\");\n\n \/\/test4, encode2({'x','y'}) == \"eHk=\"\"\n testStr2[0] = 'x';\n testStr2[1] = 'y';\n assert(base64Encode2Bytes(testStr2) == \"eHk=\");\n assert(base64Encode(testStr2, 2) == \"eHk=\");\n\n \/\/test5, encode1('a') == \"YQ==\"\n char testStr1[1];\n testStr1[0] = 'a';\n assert(base64Encode1Byte(testStr1[0]) == \"YQ==\");\n assert(base64Encode(testStr1, 1) == \"YQ==\");\n\n \/\/test6, encode1('z') == \"eg==\"\n testStr1[0] = 'z';\n assert(base64Encode1Byte(testStr1[0]) == \"eg==\");\n assert(base64Encode(testStr1, 1) == \"eg==\");\n\n \/\/test7, encodeStr({'a','b','c','d','e','f'}) == \"YWJjZGVm\"\n char testStr6[6];\n testStr6[0] = 'a';\n testStr6[1] = 'b';\n testStr6[2] = 'c';\n testStr6[3] = 'd';\n testStr6[4] = 'e';\n testStr6[5] = 'f';\n assert(base64Encode(testStr6, 6) == \"YWJjZGVm\");\n\n \/\/test8, encodeStr({'u','v','w','x','y','z'}) == \"dXZ3eHl6\"\n testStr6[0] = 'u';\n testStr6[1] = 'v';\n testStr6[2] = 'w';\n testStr6[3] = 'x';\n testStr6[4] = 'y';\n testStr6[5] = 'z';\n assert(base64Encode(testStr6, 6) == \"dXZ3eHl6\");\n\n \/\/test9, encodeStr({'a','b','c','d','e','f','g'}) == \"YWJjZGVmZw==\"\n char testStr7[7];\n testStr7[0] = 'a';\n testStr7[1] = 'b';\n testStr7[2] = 'c';\n testStr7[3] = 'd';\n testStr7[4] = 'e';\n testStr7[5] = 'f';\n testStr7[6] = 'g';\n assert(base64Encode(testStr7, 7) == \"YWJjZGVmZw==\");\n\n \/\/test10, encodeStr({'t','u','v','w','x','y','z'}) == \"dHV2d3h5eg==\"\n testStr7[0] = 't';\n testStr7[1] = 'u';\n testStr7[2] = 'v';\n testStr7[3] = 'w';\n testStr7[4] = 'x';\n testStr7[5] = 'y';\n testStr7[6] = 'z';\n assert(base64Encode(testStr7, 7) == \"dHV2d3h5eg==\");\n\n \/\/test11, encodeStr({'a','b','c','d','e','f','g','h'}) == \"YWJjZGVmZ2g=\"\n char testStr8[8];\n testStr8[0] = 'a';\n testStr8[1] = 'b';\n testStr8[2] = 'c';\n testStr8[3] = 'd';\n testStr8[4] = 'e';\n testStr8[5] = 'f';\n testStr8[6] = 'g';\n testStr8[7] = 'h';\n assert(base64Encode(testStr8, 8) == \"YWJjZGVmZ2g=\");\n\n \/\/test12, encodeStr({'s','t','u','v','w','x','y','z'}) == \"c3R1dnd4eXo=\"\n testStr8[0] = 's';\n testStr8[1] = 't';\n testStr8[2] = 'u';\n testStr8[3] = 'v';\n testStr8[4] = 'w';\n testStr8[5] = 'x';\n testStr8[6] = 'y';\n testStr8[7] = 'z';\n assert(base64Encode(testStr8, 8) == \"c3R1dnd4eXo=\");\n\n std::cout << \"Encode tests pass!\" << std::endl;\n}\n\nvoid runDecodeTests ()\n{\n \/\/test1, test decode table\n std::string base64CharsNoEquals = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n \"abcdefghijklmnopqrstuvwxyz\"\n \"0123456789+\/\";\n for ( unsigned int i = 0; i < base64CharsNoEquals.length(); i++ )\n {\n unsigned int base64Code =\n getDecodedBase64Char(base64CharsNoEquals[i]);\n assert(i == base64Code);\n }\n\n \/\/test2, decode4({'Y','W','F','h'}) == \"aaa\"\n char testStr4[4];\n testStr4[0] = 'Y';\n testStr4[1] = 'W';\n testStr4[2] = 'F';\n testStr4[3] = 'h';\n assert(base64Decode4Bytes(testStr4) == \"aaa\");\n assert(base64Decode(\"YWFh\") == \"aaa\");\n\n \/\/test3, decode4({'Y','W','F','='}) == \"aa\"\n testStr4[0] = 'Y';\n testStr4[1] = 'W';\n testStr4[2] = 'F';\n testStr4[3] = '=';\n assert(base64Decode4Bytes(testStr4) == \"aa\");\n assert(base64Decode(\"YWF=\") == \"aa\");\n\n \/\/test4, decode4({'Y','W','=','='}) == \"a\"\n testStr4[0] = 'Y';\n testStr4[1] = 'W';\n testStr4[2] = '=';\n testStr4[3] = '=';\n assert(base64Decode4Bytes(testStr4) == \"a\");\n assert(base64Decode(\"YW==\") == \"a\");\n\n \/\/test5, decode({'e','H','l','6'}) == \"xyz\"\n testStr4[0] = 'e';\n testStr4[1] = 'H';\n testStr4[2] = 'l';\n testStr4[3] = '6';\n assert(base64Decode4Bytes(testStr4) == \"xyz\");\n assert(base64Decode(\"eHl6\") == \"xyz\");\n\n \/\/test6, decode({'e','H','l','='}) == \"xy\"\n testStr4[0] = 'e';\n testStr4[1] = 'H';\n testStr4[2] = 'l';\n testStr4[3] = '=';\n assert(base64Decode4Bytes(testStr4) == \"xy\");\n assert(base64Decode(\"eHl=\") == \"xy\");\n\n \/\/test7, decode({'e','H','=','='}) == \"x\"\n testStr4[0] = 'e';\n testStr4[1] = 'H';\n testStr4[2] = '=';\n testStr4[3] = '=';\n assert(base64Decode4Bytes(testStr4) == \"x\");\n assert(base64Decode(\"eH==\") == \"x\");\n\n \/\/test8, decode(\"YWJjZGVm\") == \"abcdef\"\n assert(base64Decode(\"YWJjZGVm\") == \"abcdef\");\n\n \/\/test9, decode(\"dXZ3eHl6\") = \"uvwxyz\"\n assert(base64Decode(\"dXZ3eHl6\") == \"uvwxyz\");\n\n \/\/test10, decode(\"dnd4eXo=\") == \"vwxyz\"\n assert(base64Decode(\"dnd4eXo=\") == \"vwxyz\");\n\n \/\/test11, decode(\"d3h5eg==\") = \"wxyz\"\n assert(base64Decode(\"d3h5eg==\") == \"wxyz\");\n\n std::cout << \"Decode tests pass!\" << std::endl;\n}\n\nvoid runCombinedTests()\n{\n std::string resultStr;\n\n \/\/test1, encode and decode the alphabet in lover case\n std::string alphabet0 = \"abcdefghijklmnopqrstuvwxyz\";\n resultStr =\n base64Decode(\n base64Encode( alphabet0.c_str(), alphabet0.length() )\n );\n assert(resultStr == alphabet0);\n\n \/\/test2, encode and decode more characters\n std::string alphabet1 = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n \"abcdefghijklmnopqrstuvwxyz\"\n \"0123456789\"\n \"!@#$^&*()-_=+[]{}:;<>,.?\/|~`\";\n resultStr =\n base64Decode(\n base64Encode(alphabet1.c_str(), alphabet1.length() )\n );\n\n assert(resultStr == alphabet1);\n\n std::cout << \"Combined tests pass!\" << std::endl;\n}\n\nint main ( )\n{\n runEncodeTests();\n runDecodeTests();\n runCombinedTests();\n\n return 0;\n}<commit_msg>eof \\n<commit_after>#include <iostream>\n#include <cassert>\n\n#include \"base64.h\"\n\nvoid runEncodeTests ()\n{\n \/\/test1, encode3({'a','a','a'}) == \"YWFh\"\n char testStr3[3];\n testStr3[0] = 'a';\n testStr3[1] = 'a';\n testStr3[2] = 'a';\n assert(base64Encode3Bytes(testStr3) == \"YWFh\");\n\n \/\/test2, encode3({'x','y','z'}) == \"eHl6\"\n testStr3[0] = 'x';\n testStr3[1] = 'y';\n testStr3[2] = 'z';\n assert(base64Encode3Bytes(testStr3) == \"eHl6\");\n\n \/\/test3, encode2({'a','a'}) == \"YWE=\"\n char testStr2[2];\n testStr2[0] = 'a';\n testStr2[1] = 'a';\n assert(base64Encode2Bytes(testStr2) == \"YWE=\");\n assert(base64Encode(testStr2, 2) == \"YWE=\");\n\n \/\/test4, encode2({'x','y'}) == \"eHk=\"\"\n testStr2[0] = 'x';\n testStr2[1] = 'y';\n assert(base64Encode2Bytes(testStr2) == \"eHk=\");\n assert(base64Encode(testStr2, 2) == \"eHk=\");\n\n \/\/test5, encode1('a') == \"YQ==\"\n char testStr1[1];\n testStr1[0] = 'a';\n assert(base64Encode1Byte(testStr1[0]) == \"YQ==\");\n assert(base64Encode(testStr1, 1) == \"YQ==\");\n\n \/\/test6, encode1('z') == \"eg==\"\n testStr1[0] = 'z';\n assert(base64Encode1Byte(testStr1[0]) == \"eg==\");\n assert(base64Encode(testStr1, 1) == \"eg==\");\n\n \/\/test7, encodeStr({'a','b','c','d','e','f'}) == \"YWJjZGVm\"\n char testStr6[6];\n testStr6[0] = 'a';\n testStr6[1] = 'b';\n testStr6[2] = 'c';\n testStr6[3] = 'd';\n testStr6[4] = 'e';\n testStr6[5] = 'f';\n assert(base64Encode(testStr6, 6) == \"YWJjZGVm\");\n\n \/\/test8, encodeStr({'u','v','w','x','y','z'}) == \"dXZ3eHl6\"\n testStr6[0] = 'u';\n testStr6[1] = 'v';\n testStr6[2] = 'w';\n testStr6[3] = 'x';\n testStr6[4] = 'y';\n testStr6[5] = 'z';\n assert(base64Encode(testStr6, 6) == \"dXZ3eHl6\");\n\n \/\/test9, encodeStr({'a','b','c','d','e','f','g'}) == \"YWJjZGVmZw==\"\n char testStr7[7];\n testStr7[0] = 'a';\n testStr7[1] = 'b';\n testStr7[2] = 'c';\n testStr7[3] = 'd';\n testStr7[4] = 'e';\n testStr7[5] = 'f';\n testStr7[6] = 'g';\n assert(base64Encode(testStr7, 7) == \"YWJjZGVmZw==\");\n\n \/\/test10, encodeStr({'t','u','v','w','x','y','z'}) == \"dHV2d3h5eg==\"\n testStr7[0] = 't';\n testStr7[1] = 'u';\n testStr7[2] = 'v';\n testStr7[3] = 'w';\n testStr7[4] = 'x';\n testStr7[5] = 'y';\n testStr7[6] = 'z';\n assert(base64Encode(testStr7, 7) == \"dHV2d3h5eg==\");\n\n \/\/test11, encodeStr({'a','b','c','d','e','f','g','h'}) == \"YWJjZGVmZ2g=\"\n char testStr8[8];\n testStr8[0] = 'a';\n testStr8[1] = 'b';\n testStr8[2] = 'c';\n testStr8[3] = 'd';\n testStr8[4] = 'e';\n testStr8[5] = 'f';\n testStr8[6] = 'g';\n testStr8[7] = 'h';\n assert(base64Encode(testStr8, 8) == \"YWJjZGVmZ2g=\");\n\n \/\/test12, encodeStr({'s','t','u','v','w','x','y','z'}) == \"c3R1dnd4eXo=\"\n testStr8[0] = 's';\n testStr8[1] = 't';\n testStr8[2] = 'u';\n testStr8[3] = 'v';\n testStr8[4] = 'w';\n testStr8[5] = 'x';\n testStr8[6] = 'y';\n testStr8[7] = 'z';\n assert(base64Encode(testStr8, 8) == \"c3R1dnd4eXo=\");\n\n std::cout << \"Encode tests pass!\" << std::endl;\n}\n\nvoid runDecodeTests ()\n{\n \/\/test1, test decode table\n std::string base64CharsNoEquals = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n \"abcdefghijklmnopqrstuvwxyz\"\n \"0123456789+\/\";\n for ( unsigned int i = 0; i < base64CharsNoEquals.length(); i++ )\n {\n unsigned int base64Code =\n getDecodedBase64Char(base64CharsNoEquals[i]);\n assert(i == base64Code);\n }\n\n \/\/test2, decode4({'Y','W','F','h'}) == \"aaa\"\n char testStr4[4];\n testStr4[0] = 'Y';\n testStr4[1] = 'W';\n testStr4[2] = 'F';\n testStr4[3] = 'h';\n assert(base64Decode4Bytes(testStr4) == \"aaa\");\n assert(base64Decode(\"YWFh\") == \"aaa\");\n\n \/\/test3, decode4({'Y','W','F','='}) == \"aa\"\n testStr4[0] = 'Y';\n testStr4[1] = 'W';\n testStr4[2] = 'F';\n testStr4[3] = '=';\n assert(base64Decode4Bytes(testStr4) == \"aa\");\n assert(base64Decode(\"YWF=\") == \"aa\");\n\n \/\/test4, decode4({'Y','W','=','='}) == \"a\"\n testStr4[0] = 'Y';\n testStr4[1] = 'W';\n testStr4[2] = '=';\n testStr4[3] = '=';\n assert(base64Decode4Bytes(testStr4) == \"a\");\n assert(base64Decode(\"YW==\") == \"a\");\n\n \/\/test5, decode({'e','H','l','6'}) == \"xyz\"\n testStr4[0] = 'e';\n testStr4[1] = 'H';\n testStr4[2] = 'l';\n testStr4[3] = '6';\n assert(base64Decode4Bytes(testStr4) == \"xyz\");\n assert(base64Decode(\"eHl6\") == \"xyz\");\n\n \/\/test6, decode({'e','H','l','='}) == \"xy\"\n testStr4[0] = 'e';\n testStr4[1] = 'H';\n testStr4[2] = 'l';\n testStr4[3] = '=';\n assert(base64Decode4Bytes(testStr4) == \"xy\");\n assert(base64Decode(\"eHl=\") == \"xy\");\n\n \/\/test7, decode({'e','H','=','='}) == \"x\"\n testStr4[0] = 'e';\n testStr4[1] = 'H';\n testStr4[2] = '=';\n testStr4[3] = '=';\n assert(base64Decode4Bytes(testStr4) == \"x\");\n assert(base64Decode(\"eH==\") == \"x\");\n\n \/\/test8, decode(\"YWJjZGVm\") == \"abcdef\"\n assert(base64Decode(\"YWJjZGVm\") == \"abcdef\");\n\n \/\/test9, decode(\"dXZ3eHl6\") = \"uvwxyz\"\n assert(base64Decode(\"dXZ3eHl6\") == \"uvwxyz\");\n\n \/\/test10, decode(\"dnd4eXo=\") == \"vwxyz\"\n assert(base64Decode(\"dnd4eXo=\") == \"vwxyz\");\n\n \/\/test11, decode(\"d3h5eg==\") = \"wxyz\"\n assert(base64Decode(\"d3h5eg==\") == \"wxyz\");\n\n std::cout << \"Decode tests pass!\" << std::endl;\n}\n\nvoid runCombinedTests()\n{\n std::string resultStr;\n\n \/\/test1, encode and decode the alphabet in lover case\n std::string alphabet0 = \"abcdefghijklmnopqrstuvwxyz\";\n resultStr =\n base64Decode(\n base64Encode( alphabet0.c_str(), alphabet0.length() )\n );\n assert(resultStr == alphabet0);\n\n \/\/test2, encode and decode more characters\n std::string alphabet1 = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n \"abcdefghijklmnopqrstuvwxyz\"\n \"0123456789\"\n \"!@#$^&*()-_=+[]{}:;<>,.?\/|~`\";\n resultStr =\n base64Decode(\n base64Encode(alphabet1.c_str(), alphabet1.length() )\n );\n\n assert(resultStr == alphabet1);\n\n std::cout << \"Combined tests pass!\" << std::endl;\n}\n\nint main ( )\n{\n runEncodeTests();\n runDecodeTests();\n runCombinedTests();\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/-----------------------------------------------------------------------------\n\/\/\n\/\/ Copyright (C) 2015 David Hill\n\/\/\n\/\/ See COPYING for license information.\n\/\/\n\/\/-----------------------------------------------------------------------------\n\/\/\n\/\/ PrintBuf class.\n\/\/\n\/\/-----------------------------------------------------------------------------\n\n#include \"PrintBuf.hpp\"\n\n#include \"BinaryIO.hpp\"\n\n#include <cstdio>\n#include <cstdlib>\n#include <new>\n\n\n\/\/----------------------------------------------------------------------------|\n\/\/ Extern Functions |\n\/\/\n\nnamespace ACSVM\n{\n \/\/\n \/\/ PrintBuf constructor\n \/\/\n PrintBuf::PrintBuf() :\n buffer{nullptr},\n bufEnd{nullptr},\n bufBeg{nullptr},\n bufPtr{nullptr}\n {\n }\n\n \/\/\n \/\/ PrintBuf destructor\n \/\/\n PrintBuf::~PrintBuf()\n {\n std::free(buffer);\n }\n\n \/\/\n \/\/ PrintBuf::drop\n \/\/\n void PrintBuf::drop()\n {\n if(bufBeg != buffer)\n {\n bufPtr = bufBeg - 4;\n bufBeg = bufPtr - ReadLE4(reinterpret_cast<Byte *>(bufPtr));\n }\n else\n bufPtr = bufBeg;\n }\n\n \/\/\n \/\/ PrintBuf::format\n \/\/\n void PrintBuf::format(char const *fmt, ...)\n {\n va_list arg;\n va_start(arg, fmt);\n formatv(fmt, arg);\n va_end(arg);\n }\n\n \/\/\n \/\/ PrintBuf::formatv\n \/\/\n void PrintBuf::formatv(char const *fmt, va_list arg)\n {\n bufPtr += std::vsprintf(bufPtr, fmt, arg);\n }\n\n \/\/\n \/\/ PrintBuf::push\n \/\/\n void PrintBuf::push()\n {\n reserve(4);\n WriteLE4(reinterpret_cast<Byte *>(bufPtr), bufPtr - bufBeg);\n bufBeg = bufPtr += 4;\n }\n\n \/\/\n \/\/ PrintBuf::reserve\n \/\/\n void PrintBuf::reserve(std::size_t count)\n {\n if(static_cast<std::size_t>(bufEnd - bufPtr) > count)\n return;\n\n \/\/ Allocate extra to anticipate further reserves. +1 for null.\n count = count * 2 + 1;\n\n std::size_t idxEnd = bufEnd - buffer;\n std::size_t idxBeg = bufBeg - buffer;\n std::size_t idxPtr = bufPtr - buffer;\n\n \/\/ Check for size overflow.\n if(SIZE_MAX - idxEnd < count)\n throw std::bad_alloc();\n\n \/\/ Check that the current segment won't pass the push limit.\n if(UINT32_MAX - (idxEnd - idxBeg) < count)\n throw std::bad_alloc();\n\n idxEnd += count;\n\n if(!(buffer = static_cast<char *>(std::realloc(buffer, idxEnd))))\n throw std::bad_alloc();\n\n bufEnd = buffer + idxEnd;\n bufBeg = buffer + idxBeg;\n bufPtr = buffer + idxPtr;\n }\n}\n\n\/\/ EOF\n\n<commit_msg>Fixed memory leak on realloc failure in PrintBuf::reserve.<commit_after>\/\/-----------------------------------------------------------------------------\n\/\/\n\/\/ Copyright (C) 2015 David Hill\n\/\/\n\/\/ See COPYING for license information.\n\/\/\n\/\/-----------------------------------------------------------------------------\n\/\/\n\/\/ PrintBuf class.\n\/\/\n\/\/-----------------------------------------------------------------------------\n\n#include \"PrintBuf.hpp\"\n\n#include \"BinaryIO.hpp\"\n\n#include <cstdio>\n#include <cstdlib>\n#include <new>\n\n\n\/\/----------------------------------------------------------------------------|\n\/\/ Extern Functions |\n\/\/\n\nnamespace ACSVM\n{\n \/\/\n \/\/ PrintBuf constructor\n \/\/\n PrintBuf::PrintBuf() :\n buffer{nullptr},\n bufEnd{nullptr},\n bufBeg{nullptr},\n bufPtr{nullptr}\n {\n }\n\n \/\/\n \/\/ PrintBuf destructor\n \/\/\n PrintBuf::~PrintBuf()\n {\n std::free(buffer);\n }\n\n \/\/\n \/\/ PrintBuf::drop\n \/\/\n void PrintBuf::drop()\n {\n if(bufBeg != buffer)\n {\n bufPtr = bufBeg - 4;\n bufBeg = bufPtr - ReadLE4(reinterpret_cast<Byte *>(bufPtr));\n }\n else\n bufPtr = bufBeg;\n }\n\n \/\/\n \/\/ PrintBuf::format\n \/\/\n void PrintBuf::format(char const *fmt, ...)\n {\n va_list arg;\n va_start(arg, fmt);\n formatv(fmt, arg);\n va_end(arg);\n }\n\n \/\/\n \/\/ PrintBuf::formatv\n \/\/\n void PrintBuf::formatv(char const *fmt, va_list arg)\n {\n bufPtr += std::vsprintf(bufPtr, fmt, arg);\n }\n\n \/\/\n \/\/ PrintBuf::push\n \/\/\n void PrintBuf::push()\n {\n reserve(4);\n WriteLE4(reinterpret_cast<Byte *>(bufPtr), bufPtr - bufBeg);\n bufBeg = bufPtr += 4;\n }\n\n \/\/\n \/\/ PrintBuf::reserve\n \/\/\n void PrintBuf::reserve(std::size_t count)\n {\n if(static_cast<std::size_t>(bufEnd - bufPtr) > count)\n return;\n\n \/\/ Allocate extra to anticipate further reserves. +1 for null.\n count = count * 2 + 1;\n\n std::size_t idxEnd = bufEnd - buffer;\n std::size_t idxBeg = bufBeg - buffer;\n std::size_t idxPtr = bufPtr - buffer;\n\n \/\/ Check for size overflow.\n if(SIZE_MAX - idxEnd < count)\n throw std::bad_alloc();\n\n \/\/ Check that the current segment won't pass the push limit.\n if(UINT32_MAX - (idxEnd - idxBeg) < count)\n throw std::bad_alloc();\n\n idxEnd += count;\n\n char *bufNew;\n if(!(bufNew = static_cast<char *>(std::realloc(buffer, idxEnd))))\n throw std::bad_alloc();\n\n buffer = bufNew;\n bufEnd = buffer + idxEnd;\n bufBeg = buffer + idxBeg;\n bufPtr = buffer + idxPtr;\n }\n}\n\n\/\/ EOF\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 2011 James Peach\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include <ts\/ts.h>\n#include <spdy\/spdy.h>\n#include <platform\/logging.h>\n#include \"io.h\"\n\nstatic int spdy_session_io(TSCont, TSEvent, void *);\nstatic TSMLoc make_ts_http_request(TSMBuffer, const spdy::key_value_block&);\nstatic void print_ts_http_header(TSMBuffer, TSMLoc);\n\ntypedef scoped_ts_object<TSMBuffer, TSMBufferCreate, TSMBufferDestroy> scoped_mbuffer;\n\nstruct scoped_http_header\n{\n explicit scoped_http_header(TSMBuffer b)\n : header(TS_NULL_MLOC), buffer(b) {\n header = TSHttpHdrCreate(buffer);\n }\n\n ~scoped_http_header() {\n TSHttpHdrDestroy(buffer, header);\n TSHandleMLocRelease(buffer, TS_NULL_MLOC, header);\n }\n\n operator bool() const { return header != TS_NULL_MLOC; }\n TSMLoc get() { return header; }\n\nprivate:\n TSMLoc header;\n TSMBuffer buffer;\n};\n\nstatic void\nresolve_host_name(spdy_io_stream * stream, const std::string& hostname)\n{\n TSCont contp;\n\n contp = TSContCreate(spdy_session_io, TSMutexCreate());\n TSContDataSet(contp, stream);\n\n \/\/ XXX split the host and port and stash the port in the resulting sockaddr\n stream->action = TSHostLookup(contp, hostname.c_str(), hostname.size());\n}\n\nstatic bool\ninitiate_client_request(\n spdy_io_stream * stream)\n{\n scoped_mbuffer buffer;\n TSMLoc header;\n\n header = make_ts_http_request(buffer.get(), stream->kvblock);\n if (header == TS_NULL_MLOC) {\n return false;\n }\n\n print_ts_http_header(buffer.get(), header);\n\n \/\/ Need the kv:version and kv:method to actually make the request. It looks\n \/\/ like the most straightforward way is to build the HTTP request by hand\n \/\/ and pump it into TSFetchUrl().\n\n \/\/ Apparantly TSFetchUrl may have performance problems,\n \/\/ see https:\/\/issues.apache.org\/jira\/browse\/TS-912\n\n \/\/ We probably need to manually do the caching, using\n \/\/ TSCacheRead\/TSCacheWrite.\n\n \/\/ For POST requests which may contain a lot of data, we probably need to\n \/\/ do a bunch of work. Looks like the recommended path is\n \/\/ TSHttpConnect()\n \/\/ TSVConnWrite() to send an HTTP request.\n \/\/ TSVConnRead() to get the HTTP response.\n \/\/ TSHttpParser to parse the response (if needed).\n\n return true;\n}\n\nstatic int\nspdy_session_io(TSCont contp, TSEvent ev, void * edata)\n{\n TSHostLookupResult dns = (TSHostLookupResult)edata;\n spdy_io_stream * stream = spdy_io_stream::get(contp);\n\n switch (ev) {\n case TS_EVENT_HOST_LOOKUP:\n if (dns) {\n const struct sockaddr * addr;\n addr = TSHostLookupResultAddrGet(dns);\n debug_http(\"resolved %s => %s\",\n stream->kvblock.url().hostport.c_str(), cstringof(*addr));\n initiate_client_request(stream);\n } else {\n \/\/ XXX\n \/\/ Experimentally, if the DNS lookup fails, web proxies return 502\n \/\/ Bad Gateway. We should cobble up a HTTP response to tunnel back\n \/\/ in a SYN_REPLY.\n }\n\n stream->action = NULL;\n break;\n\n default:\n debug_plugin(\"unexpected accept event %s\", cstringof(ev));\n }\n\n return TS_EVENT_NONE;\n}\n\nstatic void\nprint_ts_http_header(TSMBuffer buffer, TSMLoc header)\n{\n spdy_io_control::buffered_stream iobuf;\n int64_t nbytes;\n int64_t avail;\n const char * ptr;\n TSIOBufferBlock blk;\n\n TSHttpHdrPrint(buffer, header, iobuf.buffer);\n blk = TSIOBufferStart(iobuf.buffer);\n avail = TSIOBufferBlockReadAvail(blk, iobuf.reader);\n ptr = (const char *)TSIOBufferBlockReadStart(blk, iobuf.reader, &nbytes);\n\n debug_http(\"http request (%zu of %zu bytes):\\n%*.*s\",\n nbytes, avail, (int)nbytes, (int)nbytes, ptr);\n}\n\nstatic void\nmake_ts_http_url(\n TSMBuffer buffer,\n TSMLoc header,\n const spdy::key_value_block& kvblock)\n{\n TSReturnCode tstatus;\n TSMLoc url;\n\n tstatus = TSHttpHdrUrlGet(buffer, header, &url);\n if (tstatus == TS_ERROR) {\n tstatus = TSUrlCreate(buffer, &url);\n }\n\n TSUrlSchemeSet(buffer, url,\n kvblock.url().scheme.data(), kvblock.url().scheme.size());\n TSUrlHostSet(buffer, url,\n kvblock.url().hostport.data(), kvblock.url().hostport.size());\n TSUrlPathSet(buffer, url,\n kvblock.url().path.data(), kvblock.url().path.size());\n TSHttpHdrMethodSet(buffer, header,\n kvblock.url().method.data(), kvblock.url().method.size());\n\n TSHttpHdrUrlSet(buffer, header, url);\n\n TSAssert(tstatus == TS_SUCCESS);\n}\n\nstatic TSMLoc\nmake_ts_http_request(\n TSMBuffer buffer,\n const spdy::key_value_block& kvblock)\n{\n\n TSMLoc header = TSHttpHdrCreate(buffer);\n\n TSHttpHdrTypeSet(buffer, header, TS_HTTP_TYPE_REQUEST);\n\n \/\/ XXX extract the real HTTP version header from kvblock.url()\n TSHttpHdrVersionSet(buffer, header, TS_HTTP_VERSION(1, 1));\n make_ts_http_url(buffer, header, kvblock);\n\n \/\/ Duplicate the header fields into the MIME header for the HTTP request we\n \/\/ are building.\n for (auto ptr(kvblock.begin()); ptr != kvblock.end(); ++ptr) {\n if (ptr->first[0] != ':') {\n TSMLoc field;\n\n \/\/ XXX Need special handling for duplicate headers; we should\n \/\/ append them as a multi-value\n\n TSMimeHdrFieldCreateNamed(buffer, header,\n ptr->first.c_str(), -1, &field);\n TSMimeHdrFieldValueStringInsert(buffer, header, field,\n -1, ptr->second.c_str(), -1);\n TSMimeHdrFieldAppend(buffer, header, field);\n }\n }\n\n return header;\n}\n\nspdy_io_stream::spdy_io_stream(unsigned s)\n : stream_id(s), action(NULL), kvblock()\n{\n}\n\nspdy_io_stream::~spdy_io_stream()\n{\n if (action) {\n TSActionCancel(action);\n }\n}\n\nvoid\nspdy_io_stream::start()\n{\n resolve_host_name(this, kvblock.url().hostport);\n}\n\n\/* vim: set sw=4 ts=4 tw=79 et : *\/\n<commit_msg>Send the SPDY request through the ATS client machinery.<commit_after>\/*\n * Copyright (c) 2011 James Peach\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include <ts\/ts.h>\n#include <spdy\/spdy.h>\n#include <platform\/logging.h>\n#include <netinet\/in.h>\n#include \"io.h\"\n\n#define SPDY_EVENT_HTTP_SUCCESS 90000\n#define SPDY_EVENT_HTTP_FAILURE 90001\n#define SPDY_EVENT_HTTP_TIMEOUT 90002\n\nstatic int spdy_session_io(TSCont, TSEvent, void *);\nstatic TSMLoc make_ts_http_request(TSMBuffer, const spdy::key_value_block&);\nstatic void print_ts_http_header(TSMBuffer, TSMLoc);\n\ntypedef scoped_ts_object<TSMBuffer, TSMBufferCreate, TSMBufferDestroy> scoped_mbuffer;\n\nstruct scoped_http_header\n{\n explicit scoped_http_header(TSMBuffer b)\n : header(TS_NULL_MLOC), buffer(b) {\n header = TSHttpHdrCreate(buffer);\n }\n\n scoped_http_header(TSMBuffer b, TSMLoc h)\n : header(h), buffer(b) {\n }\n\n ~scoped_http_header() {\n if (header != TS_NULL_MLOC) {\n TSHttpHdrDestroy(buffer, header);\n TSHandleMLocRelease(buffer, TS_NULL_MLOC, header);\n }\n }\n\n operator bool() const {\n return header != TS_NULL_MLOC;\n }\n\n operator TSMLoc() const {\n return header;\n }\n\n TSMLoc get() {\n return header;\n }\n\n TSMLoc release() {\n TSMLoc tmp = TS_NULL_MLOC;\n std::swap(tmp, header);\n return tmp;\n }\n\nprivate:\n TSMLoc header;\n TSMBuffer buffer;\n};\n\nstruct inet_address\n{\n explicit inet_address(const struct sockaddr * addr) {\n memcpy(&sa.storage, addr, addr->sa_len);\n }\n\n uint16_t& port() {\n switch (sa.storage.ss_family) {\n case AF_INET:\n return sa.in.sin_port;\n case AF_INET6:\n return sa.in6.sin6_port;\n default:\n TSReleaseAssert(\"invalid inet address type\");\n return sa.in.sin_port;\n }\n }\n\n const sockaddr * saddr() const {\n return &sa.sa;\n }\n\nprivate:\n union {\n struct sockaddr_in in;\n struct sockaddr_in6 in6;\n struct sockaddr sa;\n struct sockaddr_storage storage;\n } sa;\n};\n\ntemplate <> std::string\nstringof<inet_address>(const inet_address& inaddr) {\n return cstringof(*inaddr.saddr());\n}\n\nstatic void\nresolve_host_name(spdy_io_stream * stream, const std::string& hostname)\n{\n TSCont contp;\n\n contp = TSContCreate(spdy_session_io, TSMutexCreate());\n TSContDataSet(contp, stream);\n\n \/\/ XXX split the host and port and stash the port in the resulting sockaddr\n stream->action = TSHostLookup(contp, hostname.c_str(), hostname.size());\n}\n\nstatic bool\ninitiate_client_request(\n spdy_io_stream * stream,\n const struct sockaddr * addr,\n TSCont contp)\n\n{\n scoped_mbuffer buffer;\n spdy_io_control::buffered_stream iobuf;\n int64_t nbytes;\n const char * ptr;\n TSIOBufferBlock blk;\n\n scoped_http_header header(\n buffer.get(), make_ts_http_request(buffer.get(), stream->kvblock));\n if (!header) {\n return false;\n }\n\n print_ts_http_header(buffer.get(), header);\n\n \/\/ Need the kv:version and kv:method to actually make the request. It looks\n \/\/ like the most straightforward way is to build the HTTP request by hand\n \/\/ and pump it into TSFetchUrl().\n\n \/\/ Apparantly TSFetchUrl may have performance problems,\n \/\/ see https:\/\/issues.apache.org\/jira\/browse\/TS-912\n\n \/\/ We probably need to manually do the caching, using\n \/\/ TSCacheRead\/TSCacheWrite.\n\n \/\/ For POST requests which may contain a lot of data, we probably need to\n \/\/ do a bunch of work. Looks like the recommended path is\n \/\/ TSHttpConnect()\n \/\/ TSVConnWrite() to send an HTTP request.\n \/\/ TSVConnRead() to get the HTTP response.\n \/\/ TSHttpParser to parse the response (if needed).\n\n TSFetchEvent events = {\n \/* success_event_id *\/ SPDY_EVENT_HTTP_SUCCESS,\n \/* failure_event_id *\/ SPDY_EVENT_HTTP_FAILURE,\n \/* timeout_event_id *\/ SPDY_EVENT_HTTP_TIMEOUT\n };\n\n TSHttpHdrPrint(buffer.get(), header, iobuf.buffer);\n blk = TSIOBufferStart(iobuf.buffer);\n ptr = (const char *)TSIOBufferBlockReadStart(blk, iobuf.reader, &nbytes);\n\n TSFetchUrl(ptr, nbytes, addr, contp, AFTER_BODY, events);\n return true;\n}\n\nstatic int\nspdy_session_io(TSCont contp, TSEvent ev, void * edata)\n{\n TSHostLookupResult dns = (TSHostLookupResult)edata;\n spdy_io_stream * stream = spdy_io_stream::get(contp);\n\n switch (ev) {\n case TS_EVENT_HOST_LOOKUP:\n if (dns) {\n inet_address addr(TSHostLookupResultAddrGet(dns));\n debug_http(\"resolved %s => %s\",\n stream->kvblock.url().hostport.c_str(), cstringof(addr));\n addr.port() = htons(80); \/\/ XXX should be parsed from hostport\n initiate_client_request(stream, addr.saddr(), contp);\n } else {\n \/\/ XXX\n \/\/ Experimentally, if the DNS lookup fails, web proxies return 502\n \/\/ Bad Gateway. We should cobble up a HTTP response to tunnel back\n \/\/ in a SYN_REPLY.\n }\n\n stream->action = NULL;\n break;\n\n case SPDY_EVENT_HTTP_SUCCESS:\n debug_http(\"HTTP success event\");\n break;\n\n case SPDY_EVENT_HTTP_FAILURE:\n debug_http(\"HTTP failure event\");\n break;\n\n case SPDY_EVENT_HTTP_TIMEOUT:\n debug_http(\"HTTP timeout event\");\n break;\n\n default:\n debug_plugin(\"unexpected accept event %s\", cstringof(ev));\n }\n\n return TS_EVENT_NONE;\n}\n\nstatic void\nprint_ts_http_header(TSMBuffer buffer, TSMLoc header)\n{\n spdy_io_control::buffered_stream iobuf;\n int64_t nbytes;\n int64_t avail;\n const char * ptr;\n TSIOBufferBlock blk;\n\n TSHttpHdrPrint(buffer, header, iobuf.buffer);\n blk = TSIOBufferStart(iobuf.buffer);\n avail = TSIOBufferBlockReadAvail(blk, iobuf.reader);\n ptr = (const char *)TSIOBufferBlockReadStart(blk, iobuf.reader, &nbytes);\n\n debug_http(\"http request (%zu of %zu bytes):\\n%*.*s\",\n nbytes, avail, (int)nbytes, (int)nbytes, ptr);\n}\n\nstatic void\nmake_ts_http_url(\n TSMBuffer buffer,\n TSMLoc header,\n const spdy::key_value_block& kvblock)\n{\n TSReturnCode tstatus;\n TSMLoc url;\n\n tstatus = TSHttpHdrUrlGet(buffer, header, &url);\n if (tstatus == TS_ERROR) {\n tstatus = TSUrlCreate(buffer, &url);\n }\n\n TSUrlSchemeSet(buffer, url,\n kvblock.url().scheme.data(), kvblock.url().scheme.size());\n TSUrlHostSet(buffer, url,\n kvblock.url().hostport.data(), kvblock.url().hostport.size());\n TSUrlPathSet(buffer, url,\n kvblock.url().path.data(), kvblock.url().path.size());\n TSHttpHdrMethodSet(buffer, header,\n kvblock.url().method.data(), kvblock.url().method.size());\n\n TSHttpHdrUrlSet(buffer, header, url);\n\n TSAssert(tstatus == TS_SUCCESS);\n}\n\nstatic TSMLoc\nmake_ts_http_request(\n TSMBuffer buffer,\n const spdy::key_value_block& kvblock)\n{\n\n scoped_http_header header(buffer);\n\n TSHttpHdrTypeSet(buffer, header, TS_HTTP_TYPE_REQUEST);\n\n \/\/ XXX extract the real HTTP version header from kvblock.url()\n TSHttpHdrVersionSet(buffer, header, TS_HTTP_VERSION(1, 1));\n make_ts_http_url(buffer, header, kvblock);\n\n \/\/ Duplicate the header fields into the MIME header for the HTTP request we\n \/\/ are building.\n for (auto ptr(kvblock.begin()); ptr != kvblock.end(); ++ptr) {\n if (ptr->first[0] != ':') {\n TSMLoc field;\n\n \/\/ XXX Need special handling for duplicate headers; we should\n \/\/ append them as a multi-value\n\n TSMimeHdrFieldCreateNamed(buffer, header,\n ptr->first.c_str(), -1, &field);\n TSMimeHdrFieldValueStringInsert(buffer, header, field,\n -1, ptr->second.c_str(), -1);\n TSMimeHdrFieldAppend(buffer, header, field);\n }\n }\n\n return header.release();\n}\n\nspdy_io_stream::spdy_io_stream(unsigned s)\n : stream_id(s), action(NULL), kvblock()\n{\n}\n\nspdy_io_stream::~spdy_io_stream()\n{\n if (action) {\n TSActionCancel(action);\n }\n}\n\nvoid\nspdy_io_stream::start()\n{\n resolve_host_name(this, kvblock.url().hostport);\n}\n\n\/* vim: set sw=4 ts=4 tw=79 et : *\/\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2013-2015 The Bitcoin Core developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \"consensus\/validation.h\"\n#include \"data\/sighash.json.h\"\n#include \"hash.h\"\n#include \"main.h\" \/\/ For CheckTransaction\n#include \"random.h\"\n#include \"script\/interpreter.h\"\n#include \"script\/script.h\"\n#include \"serialize.h\"\n#include \"streams.h\"\n#include \"test\/test_bitcoin.h\"\n#include \"util.h\"\n#include \"utilstrencodings.h\"\n#include \"version.h\"\n\n#include <iostream>\n\n#include <boost\/test\/unit_test.hpp>\n\n#include <univalue.h>\n\nextern UniValue read_json(const std::string& jsondata);\n\n\/\/ Old script.cpp SignatureHash function\nuint256 static SignatureHashOld(CScript scriptCode, const CTransaction& txTo, unsigned int nIn, int nHashType)\n{\n static const uint256 one(uint256S(\"0000000000000000000000000000000000000000000000000000000000000001\"));\n if (nIn >= txTo.vin.size())\n {\n printf(\"ERROR: SignatureHash(): nIn=%d out of range\\n\", nIn);\n return one;\n }\n CMutableTransaction txTmp(txTo);\n\n \/\/ In case concatenating two scripts ends up with two codeseparators,\n \/\/ or an extra one at the end, this prevents all those possible incompatibilities.\n scriptCode.FindAndDelete(CScript(OP_CODESEPARATOR));\n\n \/\/ Blank out other inputs' signatures\n for (unsigned int i = 0; i < txTmp.vin.size(); i++)\n txTmp.vin[i].scriptSig = CScript();\n txTmp.vin[nIn].scriptSig = scriptCode;\n\n \/\/ Blank out some of the outputs\n if ((nHashType & 0x1f) == SIGHASH_NONE)\n {\n \/\/ Wildcard payee\n txTmp.vout.clear();\n\n \/\/ Let the others update at will\n for (unsigned int i = 0; i < txTmp.vin.size(); i++)\n if (i != nIn)\n txTmp.vin[i].nSequence = 0;\n }\n else if ((nHashType & 0x1f) == SIGHASH_SINGLE)\n {\n \/\/ Only lock-in the txout payee at same index as txin\n unsigned int nOut = nIn;\n if (nOut >= txTmp.vout.size())\n {\n printf(\"ERROR: SignatureHash(): nOut=%d out of range\\n\", nOut);\n return one;\n }\n txTmp.vout.resize(nOut+1);\n for (unsigned int i = 0; i < nOut; i++)\n txTmp.vout[i].SetNull();\n\n \/\/ Let the others update at will\n for (unsigned int i = 0; i < txTmp.vin.size(); i++)\n if (i != nIn)\n txTmp.vin[i].nSequence = 0;\n }\n\n \/\/ Blank out other inputs completely, not recommended for open transactions\n if (nHashType & SIGHASH_ANYONECANPAY)\n {\n txTmp.vin[0] = txTmp.vin[nIn];\n txTmp.vin.resize(1);\n }\n\n \/\/ Serialize and hash\n CHashWriter ss(SER_GETHASH, 0);\n ss << txTmp << nHashType;\n return ss.GetHash();\n}\n\nvoid static RandomScript(CScript &script) {\n static const opcodetype oplist[] = {OP_FALSE, OP_1, OP_2, OP_3, OP_CHECKSIG, OP_IF, OP_VERIF, OP_RETURN, OP_CODESEPARATOR};\n script = CScript();\n int ops = (insecure_rand() % 10);\n for (int i=0; i<ops; i++)\n script << oplist[insecure_rand() % (sizeof(oplist)\/sizeof(oplist[0]))];\n}\n\nvoid static RandomTransaction(CMutableTransaction &tx, bool fSingle) {\n tx.nVersion = insecure_rand();\n tx.vin.clear();\n tx.vout.clear();\n tx.nLockTime = (insecure_rand() % 2) ? insecure_rand() : 0;\n int ins = (insecure_rand() % 4) + 1;\n int outs = fSingle ? ins : (insecure_rand() % 4) + 1;\n for (int in = 0; in < ins; in++) {\n tx.vin.push_back(CTxIn());\n CTxIn &txin = tx.vin.back();\n txin.prevout.hash = GetRandHash();\n txin.prevout.n = insecure_rand() % 4;\n RandomScript(txin.scriptSig);\n txin.nSequence = (insecure_rand() % 2) ? insecure_rand() : (unsigned int)-1;\n }\n for (int out = 0; out < outs; out++) {\n tx.vout.push_back(CTxOut());\n CTxOut &txout = tx.vout.back();\n txout.nValue = insecure_rand() % 100000000;\n RandomScript(txout.scriptPubKey);\n }\n}\n\nBOOST_FIXTURE_TEST_SUITE(sighash_tests, BasicTestingSetup)\n\nBOOST_AUTO_TEST_CASE(sighash_test)\n{\n seed_insecure_rand(false);\n\n #if defined(PRINT_SIGHASH_JSON)\n std::cout << \"[\\n\";\n std::cout << \"\\t[\\\"raw_transaction, script, input_index, hashType, signature_hash (result)\\\"],\\n\";\n #endif\n int nRandomTests = 50000;\n\n #if defined(PRINT_SIGHASH_JSON)\n nRandomTests = 500;\n #endif\n for (int i=0; i<nRandomTests; i++) {\n int nHashType = insecure_rand();\n CMutableTransaction txTo;\n RandomTransaction(txTo, (nHashType & 0x1f) == SIGHASH_SINGLE);\n CScript scriptCode;\n RandomScript(scriptCode);\n int nIn = insecure_rand() % txTo.vin.size();\n\n uint256 sh, sho;\n sho = SignatureHashOld(scriptCode, txTo, nIn, nHashType);\n sh = SignatureHash(scriptCode, txTo, nIn, nHashType);\n #if defined(PRINT_SIGHASH_JSON)\n CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);\n ss << txTo;\n\n std::cout << \"\\t[\\\"\" ;\n std::cout << HexStr(ss.begin(), ss.end()) << \"\\\", \\\"\";\n std::cout << HexStr(scriptCode) << \"\\\", \";\n std::cout << nIn << \", \";\n std::cout << nHashType << \", \\\"\";\n std::cout << sho.GetHex() << \"\\\"]\";\n if (i+1 != nRandomTests) {\n std::cout << \",\";\n }\n std::cout << \"\\n\";\n #endif\n BOOST_CHECK(sh == sho);\n }\n #if defined(PRINT_SIGHASH_JSON)\n std::cout << \"]\\n\";\n #endif\n}\n\n\/\/ Goal: check that SignatureHash generates correct hash\nBOOST_AUTO_TEST_CASE(sighash_from_data)\n{\n UniValue tests = read_json(std::string(json_tests::sighash, json_tests::sighash + sizeof(json_tests::sighash)));\n\n for (unsigned int idx = 0; idx < tests.size(); idx++) {\n UniValue test = tests[idx];\n std::string strTest = test.write();\n if (test.size() < 1) \/\/ Allow for extra stuff (useful for comments)\n {\n BOOST_ERROR(\"Bad test: \" << strTest);\n continue;\n }\n if (test.size() == 1) continue; \/\/ comment\n\n std::string raw_tx, raw_script, sigHashHex;\n int nIn, nHashType;\n uint256 sh;\n CTransaction tx;\n CScript scriptCode = CScript();\n\n try {\n \/\/ deserialize test data\n raw_tx = test[0].get_str();\n raw_script = test[1].get_str();\n nIn = test[2].get_int();\n nHashType = test[3].get_int();\n sigHashHex = test[4].get_str();\n\n uint256 sh;\n CDataStream stream(ParseHex(raw_tx), SER_NETWORK, PROTOCOL_VERSION);\n stream >> tx;\n\n CValidationState state;\n BOOST_CHECK_MESSAGE(CheckTransaction(tx, state), strTest);\n BOOST_CHECK(state.IsValid());\n\n std::vector<unsigned char> raw = ParseHex(raw_script);\n scriptCode.insert(scriptCode.end(), raw.begin(), raw.end());\n } catch (...) {\n BOOST_ERROR(\"Bad test, couldn't deserialize data: \" << strTest);\n continue;\n }\n\n sh = SignatureHash(scriptCode, tx, nIn, nHashType);\n BOOST_CHECK_MESSAGE(sh.GetHex() == sigHashHex, strTest);\n }\n}\nBOOST_AUTO_TEST_SUITE_END()\n<commit_msg>Remove unused local variable shadowing upper local<commit_after>\/\/ Copyright (c) 2013-2015 The Bitcoin Core developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \"consensus\/validation.h\"\n#include \"data\/sighash.json.h\"\n#include \"hash.h\"\n#include \"main.h\" \/\/ For CheckTransaction\n#include \"random.h\"\n#include \"script\/interpreter.h\"\n#include \"script\/script.h\"\n#include \"serialize.h\"\n#include \"streams.h\"\n#include \"test\/test_bitcoin.h\"\n#include \"util.h\"\n#include \"utilstrencodings.h\"\n#include \"version.h\"\n\n#include <iostream>\n\n#include <boost\/test\/unit_test.hpp>\n\n#include <univalue.h>\n\nextern UniValue read_json(const std::string& jsondata);\n\n\/\/ Old script.cpp SignatureHash function\nuint256 static SignatureHashOld(CScript scriptCode, const CTransaction& txTo, unsigned int nIn, int nHashType)\n{\n static const uint256 one(uint256S(\"0000000000000000000000000000000000000000000000000000000000000001\"));\n if (nIn >= txTo.vin.size())\n {\n printf(\"ERROR: SignatureHash(): nIn=%d out of range\\n\", nIn);\n return one;\n }\n CMutableTransaction txTmp(txTo);\n\n \/\/ In case concatenating two scripts ends up with two codeseparators,\n \/\/ or an extra one at the end, this prevents all those possible incompatibilities.\n scriptCode.FindAndDelete(CScript(OP_CODESEPARATOR));\n\n \/\/ Blank out other inputs' signatures\n for (unsigned int i = 0; i < txTmp.vin.size(); i++)\n txTmp.vin[i].scriptSig = CScript();\n txTmp.vin[nIn].scriptSig = scriptCode;\n\n \/\/ Blank out some of the outputs\n if ((nHashType & 0x1f) == SIGHASH_NONE)\n {\n \/\/ Wildcard payee\n txTmp.vout.clear();\n\n \/\/ Let the others update at will\n for (unsigned int i = 0; i < txTmp.vin.size(); i++)\n if (i != nIn)\n txTmp.vin[i].nSequence = 0;\n }\n else if ((nHashType & 0x1f) == SIGHASH_SINGLE)\n {\n \/\/ Only lock-in the txout payee at same index as txin\n unsigned int nOut = nIn;\n if (nOut >= txTmp.vout.size())\n {\n printf(\"ERROR: SignatureHash(): nOut=%d out of range\\n\", nOut);\n return one;\n }\n txTmp.vout.resize(nOut+1);\n for (unsigned int i = 0; i < nOut; i++)\n txTmp.vout[i].SetNull();\n\n \/\/ Let the others update at will\n for (unsigned int i = 0; i < txTmp.vin.size(); i++)\n if (i != nIn)\n txTmp.vin[i].nSequence = 0;\n }\n\n \/\/ Blank out other inputs completely, not recommended for open transactions\n if (nHashType & SIGHASH_ANYONECANPAY)\n {\n txTmp.vin[0] = txTmp.vin[nIn];\n txTmp.vin.resize(1);\n }\n\n \/\/ Serialize and hash\n CHashWriter ss(SER_GETHASH, 0);\n ss << txTmp << nHashType;\n return ss.GetHash();\n}\n\nvoid static RandomScript(CScript &script) {\n static const opcodetype oplist[] = {OP_FALSE, OP_1, OP_2, OP_3, OP_CHECKSIG, OP_IF, OP_VERIF, OP_RETURN, OP_CODESEPARATOR};\n script = CScript();\n int ops = (insecure_rand() % 10);\n for (int i=0; i<ops; i++)\n script << oplist[insecure_rand() % (sizeof(oplist)\/sizeof(oplist[0]))];\n}\n\nvoid static RandomTransaction(CMutableTransaction &tx, bool fSingle) {\n tx.nVersion = insecure_rand();\n tx.vin.clear();\n tx.vout.clear();\n tx.nLockTime = (insecure_rand() % 2) ? insecure_rand() : 0;\n int ins = (insecure_rand() % 4) + 1;\n int outs = fSingle ? ins : (insecure_rand() % 4) + 1;\n for (int in = 0; in < ins; in++) {\n tx.vin.push_back(CTxIn());\n CTxIn &txin = tx.vin.back();\n txin.prevout.hash = GetRandHash();\n txin.prevout.n = insecure_rand() % 4;\n RandomScript(txin.scriptSig);\n txin.nSequence = (insecure_rand() % 2) ? insecure_rand() : (unsigned int)-1;\n }\n for (int out = 0; out < outs; out++) {\n tx.vout.push_back(CTxOut());\n CTxOut &txout = tx.vout.back();\n txout.nValue = insecure_rand() % 100000000;\n RandomScript(txout.scriptPubKey);\n }\n}\n\nBOOST_FIXTURE_TEST_SUITE(sighash_tests, BasicTestingSetup)\n\nBOOST_AUTO_TEST_CASE(sighash_test)\n{\n seed_insecure_rand(false);\n\n #if defined(PRINT_SIGHASH_JSON)\n std::cout << \"[\\n\";\n std::cout << \"\\t[\\\"raw_transaction, script, input_index, hashType, signature_hash (result)\\\"],\\n\";\n #endif\n int nRandomTests = 50000;\n\n #if defined(PRINT_SIGHASH_JSON)\n nRandomTests = 500;\n #endif\n for (int i=0; i<nRandomTests; i++) {\n int nHashType = insecure_rand();\n CMutableTransaction txTo;\n RandomTransaction(txTo, (nHashType & 0x1f) == SIGHASH_SINGLE);\n CScript scriptCode;\n RandomScript(scriptCode);\n int nIn = insecure_rand() % txTo.vin.size();\n\n uint256 sh, sho;\n sho = SignatureHashOld(scriptCode, txTo, nIn, nHashType);\n sh = SignatureHash(scriptCode, txTo, nIn, nHashType);\n #if defined(PRINT_SIGHASH_JSON)\n CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);\n ss << txTo;\n\n std::cout << \"\\t[\\\"\" ;\n std::cout << HexStr(ss.begin(), ss.end()) << \"\\\", \\\"\";\n std::cout << HexStr(scriptCode) << \"\\\", \";\n std::cout << nIn << \", \";\n std::cout << nHashType << \", \\\"\";\n std::cout << sho.GetHex() << \"\\\"]\";\n if (i+1 != nRandomTests) {\n std::cout << \",\";\n }\n std::cout << \"\\n\";\n #endif\n BOOST_CHECK(sh == sho);\n }\n #if defined(PRINT_SIGHASH_JSON)\n std::cout << \"]\\n\";\n #endif\n}\n\n\/\/ Goal: check that SignatureHash generates correct hash\nBOOST_AUTO_TEST_CASE(sighash_from_data)\n{\n UniValue tests = read_json(std::string(json_tests::sighash, json_tests::sighash + sizeof(json_tests::sighash)));\n\n for (unsigned int idx = 0; idx < tests.size(); idx++) {\n UniValue test = tests[idx];\n std::string strTest = test.write();\n if (test.size() < 1) \/\/ Allow for extra stuff (useful for comments)\n {\n BOOST_ERROR(\"Bad test: \" << strTest);\n continue;\n }\n if (test.size() == 1) continue; \/\/ comment\n\n std::string raw_tx, raw_script, sigHashHex;\n int nIn, nHashType;\n uint256 sh;\n CTransaction tx;\n CScript scriptCode = CScript();\n\n try {\n \/\/ deserialize test data\n raw_tx = test[0].get_str();\n raw_script = test[1].get_str();\n nIn = test[2].get_int();\n nHashType = test[3].get_int();\n sigHashHex = test[4].get_str();\n\n CDataStream stream(ParseHex(raw_tx), SER_NETWORK, PROTOCOL_VERSION);\n stream >> tx;\n\n CValidationState state;\n BOOST_CHECK_MESSAGE(CheckTransaction(tx, state), strTest);\n BOOST_CHECK(state.IsValid());\n\n std::vector<unsigned char> raw = ParseHex(raw_script);\n scriptCode.insert(scriptCode.end(), raw.begin(), raw.end());\n } catch (...) {\n BOOST_ERROR(\"Bad test, couldn't deserialize data: \" << strTest);\n continue;\n }\n\n sh = SignatureHash(scriptCode, tx, nIn, nHashType);\n BOOST_CHECK_MESSAGE(sh.GetHex() == sigHashHex, strTest);\n }\n}\nBOOST_AUTO_TEST_SUITE_END()\n<|endoftext|>"} {"text":"<commit_before>\/*****************************************************************************\n * main.cpp: ActiveX control for VLC\n *****************************************************************************\n * Copyright (C) 2005 the VideoLAN team\n *\n * Authors: Damien Fouilleul <Damien.Fouilleul@laposte.net>\n *\n * This program is free software; you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.\n *****************************************************************************\/\n\n#include \"plugin.h\"\n#include \"utils.h\"\n\n#include <stdio.h>\n\n#include <comcat.h>\n#include <windows.h>\n#include <shlwapi.h>\n\nusing namespace std;\n\n#define COMPANY_STR \"VideoLAN\"\n#define PROGRAM_STR \"VLCPlugin\"\n#define DESCRIPTION \"VideoLAN VLC ActiveX Plugin\"\n\n#define THREADING_MODEL \"Apartment\"\n#define MISC_STATUS \"131473\"\n\n#define PROGID_STR COMPANY_STR\".\"PROGRAM_STR\n\n#define GUID_STRLEN 39\n\n\/*\n** MingW headers do not declare those\n*\/\nextern const CATID CATID_SafeForInitializing;\nextern const CATID CATID_SafeForScripting;\n\nstatic LONG i_class_ref= 0;\nstatic HINSTANCE h_instance= 0;\n\nHMODULE DllGetModule()\n{\n return h_instance;\n};\n\nSTDAPI DllGetClassObject(REFCLSID rclsid, REFIID riid, LPVOID *ppv)\n{\n HRESULT hr = CLASS_E_CLASSNOTAVAILABLE;\n\n *ppv = NULL;\n\n if( (CLSID_VLCPlugin == rclsid )\n || ( CLSID_VLCPlugin2 == rclsid) )\n {\n VLCPluginClass *plugin = new VLCPluginClass(&i_class_ref, h_instance, rclsid);\n hr = plugin->QueryInterface(riid, ppv);\n plugin->Release();\n }\n return hr;\n};\n\nSTDAPI DllCanUnloadNow(VOID)\n{\n return (0 == i_class_ref) ? S_OK: S_FALSE;\n};\n\nstatic inline HKEY keyCreate(HKEY parentKey, LPCSTR keyName)\n{\n HKEY childKey;\n if( ERROR_SUCCESS == RegCreateKeyExA(parentKey, keyName, 0, NULL,\n REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, NULL, &childKey, NULL) )\n {\n return childKey;\n }\n return NULL;\n};\n\nstatic inline HKEY keySet(HKEY hKey, LPCSTR valueName, const void *s, size_t len)\n{\n if( NULL != hKey )\n {\n RegSetValueExA(hKey, valueName, 0, REG_SZ,\n (const BYTE*)s, len);\n }\n return hKey;\n};\n\nstatic inline HKEY keySetDef(HKEY hKey, const void *s, size_t len)\n{\n return keySet(hKey, NULL, s, len);\n};\n\nstatic inline HKEY keySetDef(HKEY hKey, LPCSTR s)\n{\n return keySetDef(hKey, s, strlen(s)+1);\n};\n\nstatic inline HKEY keyClose(HKEY hKey)\n{\n if( NULL != hKey )\n {\n RegCloseKey(hKey);\n }\n return NULL;\n};\n\nstatic HRESULT UnregisterProgID(REFCLSID rclsid, unsigned int version)\n{\n LPCSTR psz_CLSID = CStrFromGUID(rclsid);\n\n if( NULL == psz_CLSID )\n return E_OUTOFMEMORY;\n\n char progId[sizeof(PROGID_STR)+16];\n sprintf(progId, \"%s.%u\", PROGID_STR, version);\n\n SHDeleteKeyA(HKEY_CLASSES_ROOT, progId);\n\n HKEY hClsIDKey;\n if( ERROR_SUCCESS == RegOpenKeyExA(HKEY_CLASSES_ROOT, \"CLSID\", 0, KEY_WRITE, &hClsIDKey) )\n {\n SHDeleteKey(hClsIDKey, psz_CLSID);\n RegCloseKey(hClsIDKey);\n }\n CoTaskMemFree((void *)psz_CLSID);\n};\n\nSTDAPI DllUnregisterServer(VOID)\n{\n \/\/ unregister type lib from the registry\n UnRegisterTypeLib(LIBID_AXVLC, 1, 0, LOCALE_NEUTRAL, SYS_WIN32);\n\n \/\/ remove component categories we supports\n ICatRegister *pcr;\n if( SUCCEEDED(CoCreateInstance(CLSID_StdComponentCategoriesMgr, \n NULL, CLSCTX_INPROC_SERVER, IID_ICatRegister, (void**)&pcr)) ) {\n CATID implCategories[] = {\n CATID_Control,\n CATID_PersistsToPropertyBag,\n CATID_SafeForInitializing,\n CATID_SafeForScripting,\n };\n\n pcr->UnRegisterClassImplCategories(CLSID_VLCPlugin,\n sizeof(implCategories)\/sizeof(CATID), implCategories);\n pcr->UnRegisterClassImplCategories(CLSID_VLCPlugin2,\n sizeof(implCategories)\/sizeof(CATID), implCategories);\n pcr->Release();\n }\n\n SHDeleteKey(HKEY_CLASSES_ROOT, TEXT(PROGID_STR));\n\n UnregisterProgID(CLSID_VLCPlugin, 2);\n UnregisterProgID(CLSID_VLCPlugin2, 1);\n\n return S_OK;\n};\n\nstatic HRESULT RegisterClassID(HKEY hParent, REFCLSID rclsid, unsigned int version, BOOL isDefault, const char *path, size_t pathLen)\n{\n char progId[sizeof(PROGID_STR)+16];\n sprintf(progId, \"%s.%u\", PROGID_STR, version);\n\n char description[sizeof(DESCRIPTION)+16];\n sprintf(description, \"%s v%u\", DESCRIPTION, version);\n\n HKEY hClassKey;\n {\n LPCSTR psz_CLSID = CStrFromGUID(rclsid);\n\n if( NULL == psz_CLSID )\n return E_OUTOFMEMORY;\n\n HKEY hProgKey = keyCreate(HKEY_CLASSES_ROOT, progId);\n if( NULL != hProgKey )\n {\n \/\/ default key value\n keySetDef(hProgKey, description);\n\n keyClose(keySetDef(keyCreate(hProgKey, \"CLSID\"),\n psz_CLSID,\n GUID_STRLEN));\n\n \/\/hSubKey = keyClose(keyCreate(hBaseKey, \"Insertable\"));\n \n RegCloseKey(hProgKey);\n }\n if( isDefault )\n {\n hProgKey = keyCreate(HKEY_CLASSES_ROOT, PROGID_STR);\n if( NULL != hProgKey )\n {\n \/\/ default key value\n keySetDef(hProgKey, description);\n\n keyClose(keySetDef(keyCreate(hProgKey, \"CLSID\"),\n psz_CLSID,\n GUID_STRLEN));\n\n keyClose(keySetDef(keyCreate(hProgKey, \"CurVer\"),\n progId));\n }\n }\n hClassKey = keyCreate(hParent, psz_CLSID);\n CoTaskMemFree((void *)psz_CLSID);\n }\n if( NULL != hClassKey )\n {\n \/\/ default key value\n keySetDef(hClassKey, description);\n\n \/\/ Control key value\n keyClose(keyCreate(hClassKey, \"Control\"));\n\n \/\/ Insertable key value\n \/\/keyClose(keyCreate(hClassKey, \"Insertable\"));\n\n \/\/ ToolboxBitmap32 key value\n {\n char iconPath[pathLen+3];\n memcpy(iconPath, path, pathLen);\n strcpy(iconPath+pathLen, \",1\");\n keyClose(keySetDef(keyCreate(hClassKey,\n \"ToolboxBitmap32\"),\n iconPath, sizeof(iconPath)));\n }\n\n#ifdef BUILD_LOCALSERVER\n \/\/ LocalServer32 key value\n keyClose(keySetDef(keyCreate(hClassKey,\n \"LocalServer32\", path, pathLen+1)));\n#else\n \/\/ InprocServer32 key value\n {\n HKEY hSubKey = keySetDef(keyCreate(hClassKey,\n \"InprocServer32\"),\n path, pathLen+1);\n keySet(hSubKey,\n \"ThreadingModel\",\n THREADING_MODEL, sizeof(THREADING_MODEL));\n keyClose(hSubKey);\n }\n#endif\n\n \/\/ MiscStatus key value\n keyClose(keySetDef(keyCreate(hClassKey,\n \"MiscStatus\\\\1\"),\n MISC_STATUS, sizeof(MISC_STATUS)));\n\n \/\/ Programmable key value\n keyClose(keyCreate(hClassKey, \"Programmable\"));\n\n \/\/ ProgID key value\n keyClose(keySetDef(keyCreate(hClassKey,\n TEXT(\"ProgID\")),\n progId));\n\n \/\/ VersionIndependentProgID key value\n keyClose(keySetDef(keyCreate(hClassKey,\n \"VersionIndependentProgID\"),\n PROGID_STR, sizeof(PROGID_STR)));\n\n \/\/ Version key value\n keyClose(keySetDef(keyCreate(hClassKey,\n \"Version\"),\n \"1.0\"));\n\n \/\/ TypeLib key value\n LPCSTR psz_LIBID = CStrFromGUID(LIBID_AXVLC);\n if( NULL != psz_LIBID )\n {\n keyClose(keySetDef(keyCreate(hClassKey,\n \"TypeLib\"),\n psz_LIBID, GUID_STRLEN));\n CoTaskMemFree((void *)psz_LIBID);\n }\n RegCloseKey(hClassKey);\n }\n return S_OK;\n}\n\nSTDAPI DllRegisterServer(VOID)\n{\n DllUnregisterServer();\n\n char DllPath[MAX_PATH];\n DWORD DllPathLen=GetModuleFileNameA(h_instance, DllPath, sizeof(DllPath)) ;\n if( 0 == DllPathLen )\n return E_UNEXPECTED;\n\n HKEY hBaseKey;\n\n if( ERROR_SUCCESS != RegOpenKeyExA(HKEY_CLASSES_ROOT, \"CLSID\", 0, KEY_CREATE_SUB_KEY, &hBaseKey) )\n return SELFREG_E_CLASS;\n\n RegisterClassID(hBaseKey, CLSID_VLCPlugin, 1, FALSE, DllPath, DllPathLen);\n RegisterClassID(hBaseKey, CLSID_VLCPlugin2, 2, TRUE, DllPath, DllPathLen);\n\n RegCloseKey(hBaseKey);\n\n \/\/ indicate which component categories we support\n ICatRegister *pcr;\n if( SUCCEEDED(CoCreateInstance(CLSID_StdComponentCategoriesMgr, \n NULL, CLSCTX_INPROC_SERVER, IID_ICatRegister, (void**)&pcr)) ) {\n CATID implCategories[] = {\n CATID_Control,\n CATID_PersistsToPropertyBag,\n CATID_SafeForInitializing,\n CATID_SafeForScripting,\n };\n\n pcr->RegisterClassImplCategories(CLSID_VLCPlugin,\n sizeof(implCategories)\/sizeof(CATID), implCategories);\n pcr->RegisterClassImplCategories(CLSID_VLCPlugin2,\n sizeof(implCategories)\/sizeof(CATID), implCategories);\n pcr->Release();\n }\n\n \/\/ register type lib into the registry\n ITypeLib *typeLib;\n\n#ifdef BUILD_LOCALSERVER\n \/\/ replace .exe by .tlb\n strcpy(DllPath+DllPathLen-4, \".tlb\");\n#endif\n\n#ifndef OLE2ANSI\n size_t typeLibPathLen = MultiByteToWideChar(CP_ACP, 0, DllPath, -1, NULL, 0);\n if( typeLibPathLen > 0 )\n {\n LPOLESTR typeLibPath = (LPOLESTR)CoTaskMemAlloc(typeLibPathLen*sizeof(wchar_t));\n MultiByteToWideChar(CP_ACP, 0, DllPath, DllPathLen, typeLibPath, typeLibPathLen);\n if( FAILED(LoadTypeLibEx(typeLibPath, REGKIND_REGISTER, &typeLib)) )\n#ifndef BUILD_LOCALSERVER\n return SELFREG_E_TYPELIB;\n typeLib->Release();\n#endif\n CoTaskMemFree((void *)typeLibPath);\n }\n#else\n if( FAILED(LoadTypeLibEx((LPOLESTR)DllPath, REGKIND_REGISTER, &typeLib)) )\n return SELFREG_E_TYPELIB;\n typeLib->Release();\n#endif\n\n return S_OK;\n};\n\n#ifdef BUILD_LOCALSERVER\n\n\/*\n** easier to debug an application than a DLL on cygwin GDB :)\n*\/\n#include <iostream>\n\nSTDAPI_(int) WinMain(HINSTANCE hInst, HINSTANCE hPrev, LPSTR szCmdLine, int sw)\n{\n MSG msg;\n\n if( FAILED(OleInitialize(NULL)) )\n {\n cerr << \"cannot initialize OLE\" << endl;\n return 1;\n }\n\n h_instance = hInst;\n\n if( FAILED(DllRegisterServer()) )\n {\n cerr << \"cannot register Local Server\" << endl;\n return 1;\n }\n\n IUnknown *classProc = NULL;\n\n if( FAILED(DllGetClassObject(CLSID_VLCPlugin, IID_IUnknown, (LPVOID *)&classProc)) )\n return 0;\n \n DWORD dwRegisterClassObject;\n DWORD dwRegisterClassObject2;\n\n if( FAILED(CoRegisterClassObject(CLSID_VLCPlugin, classProc,\n CLSCTX_LOCAL_SERVER, REGCLS_MULTIPLEUSE, &dwRegisterClassObject)) )\n return 0;\n\n DWORD dwRegisterActiveObject;\n\n if( FAILED(RegisterActiveObject(classProc, CLSID_VLCPlugin,\n ACTIVEOBJECT_WEAK, &dwRegisterActiveObject)) )\n return 0;\n\n if( FAILED(RegisterActiveObject(classProc, CLSID_VLCPlugin2,\n ACTIVEOBJECT_WEAK, &dwRegisterActiveObject2)) )\n return 0;\n\n classProc->Release();\n\n \/*\n * Polling messages from event queue\n *\/\n while( S_FALSE == DllCanUnloadNow() )\n {\n while( PeekMessage(&msg, NULL, 0, 0, PM_REMOVE) )\n {\n if( msg.message == WM_QUIT )\n break; \/\/ break out PeekMessage loop\n\n \/*if(TranslateAccelerator(ghwndApp, ghAccel, &msg))\n continue;*\/\n\n TranslateMessage(&msg);\n DispatchMessage(&msg);\n }\n\n if(msg.message == WM_QUIT)\n break; \/\/ break out main loop\n\n WaitMessage();\n }\n\n if( SUCCEEDED(RevokeActiveObject(dwRegisterActiveObject, NULL)) )\n CoRevokeClassObject(dwRegisterClassObject);\n\n if( SUCCEEDED(RevokeActiveObject(dwRegisterActiveObject2, NULL)) )\n CoRevokeClassObject(dwRegisterClassObject2);\n\n \/\/ Reached on WM_QUIT message\n OleUninitialize();\n return ((int) msg.wParam);\n};\n\n#else\n\nSTDAPI_(BOOL) DllMain(HANDLE hModule, DWORD fdwReason, LPVOID lpReserved )\n{\n switch( fdwReason )\n {\n case DLL_PROCESS_ATTACH:\n h_instance = (HINSTANCE)hModule;\n break;\n\n default:\n break;\n }\n return TRUE;\n};\n\n#endif\n\n<commit_msg>- latest mingw headers removed some category definitions<commit_after>\/*****************************************************************************\n * main.cpp: ActiveX control for VLC\n *****************************************************************************\n * Copyright (C) 2005 the VideoLAN team\n *\n * Authors: Damien Fouilleul <Damien.Fouilleul@laposte.net>\n *\n * This program is free software; you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.\n *****************************************************************************\/\n\n#include \"plugin.h\"\n#include \"utils.h\"\n\n#include <stdio.h>\n\n#include <comcat.h>\n#include <windows.h>\n#include <shlwapi.h>\n\n#include <guiddef.h>\n\nusing namespace std;\n\n#define COMPANY_STR \"VideoLAN\"\n#define PROGRAM_STR \"VLCPlugin\"\n#define DESCRIPTION \"VideoLAN VLC ActiveX Plugin\"\n\n#define THREADING_MODEL \"Apartment\"\n#define MISC_STATUS \"131473\"\n\n#define PROGID_STR COMPANY_STR\".\"PROGRAM_STR\n\n#define GUID_STRLEN 39\n\n\/*\n** MingW headers & libs do not declare those\n*\/\nDEFINE_GUID(CATID_InternetAware, 0x0DE86A58, 0x2BAA, 0x11CF, 0xA2, 0x29, 0x00,0xAA,0x00,0x3D,0x73,0x52);\nDEFINE_GUID(CATID_SafeForInitializing, 0x7DD95802, 0x9882, 0x11CF, 0x9F, 0xA9, 0x00,0xAA,0x00,0x6C,0x42,0xC4);\nDEFINE_GUID(CATID_SafeForScripting, 0x7DD95801, 0x9882, 0x11CF, 0x9F, 0xA9, 0x00,0xAA,0x00,0x6C,0x42,0xC4);\n\nstatic LONG i_class_ref= 0;\nstatic HINSTANCE h_instance= 0;\n\nHMODULE DllGetModule()\n{\n return h_instance;\n};\n\nSTDAPI DllGetClassObject(REFCLSID rclsid, REFIID riid, LPVOID *ppv)\n{\n HRESULT hr = CLASS_E_CLASSNOTAVAILABLE;\n\n *ppv = NULL;\n\n if( (CLSID_VLCPlugin == rclsid )\n || ( CLSID_VLCPlugin2 == rclsid) )\n {\n VLCPluginClass *plugin = new VLCPluginClass(&i_class_ref, h_instance, rclsid);\n hr = plugin->QueryInterface(riid, ppv);\n plugin->Release();\n }\n return hr;\n};\n\nSTDAPI DllCanUnloadNow(VOID)\n{\n return (0 == i_class_ref) ? S_OK: S_FALSE;\n};\n\nstatic inline HKEY keyCreate(HKEY parentKey, LPCSTR keyName)\n{\n HKEY childKey;\n if( ERROR_SUCCESS == RegCreateKeyExA(parentKey, keyName, 0, NULL,\n REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, NULL, &childKey, NULL) )\n {\n return childKey;\n }\n return NULL;\n};\n\nstatic inline HKEY keySet(HKEY hKey, LPCSTR valueName, const void *s, size_t len)\n{\n if( NULL != hKey )\n {\n RegSetValueExA(hKey, valueName, 0, REG_SZ,\n (const BYTE*)s, len);\n }\n return hKey;\n};\n\nstatic inline HKEY keySetDef(HKEY hKey, const void *s, size_t len)\n{\n return keySet(hKey, NULL, s, len);\n};\n\nstatic inline HKEY keySetDef(HKEY hKey, LPCSTR s)\n{\n return keySetDef(hKey, s, strlen(s)+1);\n};\n\nstatic inline HKEY keyClose(HKEY hKey)\n{\n if( NULL != hKey )\n {\n RegCloseKey(hKey);\n }\n return NULL;\n};\n\nstatic HRESULT UnregisterProgID(REFCLSID rclsid, unsigned int version)\n{\n LPCSTR psz_CLSID = CStrFromGUID(rclsid);\n\n if( NULL == psz_CLSID )\n return E_OUTOFMEMORY;\n\n char progId[sizeof(PROGID_STR)+16];\n sprintf(progId, \"%s.%u\", PROGID_STR, version);\n\n SHDeleteKeyA(HKEY_CLASSES_ROOT, progId);\n\n HKEY hClsIDKey;\n if( ERROR_SUCCESS == RegOpenKeyExA(HKEY_CLASSES_ROOT, \"CLSID\", 0, KEY_WRITE, &hClsIDKey) )\n {\n SHDeleteKey(hClsIDKey, psz_CLSID);\n RegCloseKey(hClsIDKey);\n }\n CoTaskMemFree((void *)psz_CLSID);\n};\n\nSTDAPI DllUnregisterServer(VOID)\n{\n \/\/ unregister type lib from the registry\n UnRegisterTypeLib(LIBID_AXVLC, 1, 0, LOCALE_NEUTRAL, SYS_WIN32);\n\n \/\/ remove component categories we supports\n ICatRegister *pcr;\n if( SUCCEEDED(CoCreateInstance(CLSID_StdComponentCategoriesMgr, \n NULL, CLSCTX_INPROC_SERVER, IID_ICatRegister, (void**)&pcr)) ) {\n CATID implCategories[] = {\n CATID_Control,\n CATID_PersistsToPropertyBag,\n CATID_InternetAware,\n CATID_SafeForInitializing,\n CATID_SafeForScripting,\n };\n\n pcr->UnRegisterClassImplCategories(CLSID_VLCPlugin,\n sizeof(implCategories)\/sizeof(CATID), implCategories);\n pcr->UnRegisterClassImplCategories(CLSID_VLCPlugin2,\n sizeof(implCategories)\/sizeof(CATID), implCategories);\n pcr->Release();\n }\n\n SHDeleteKey(HKEY_CLASSES_ROOT, TEXT(PROGID_STR));\n\n UnregisterProgID(CLSID_VLCPlugin, 2);\n UnregisterProgID(CLSID_VLCPlugin2, 1);\n\n return S_OK;\n};\n\nstatic HRESULT RegisterClassID(HKEY hParent, REFCLSID rclsid, unsigned int version, BOOL isDefault, const char *path, size_t pathLen)\n{\n char progId[sizeof(PROGID_STR)+16];\n sprintf(progId, \"%s.%u\", PROGID_STR, version);\n\n char description[sizeof(DESCRIPTION)+16];\n sprintf(description, \"%s v%u\", DESCRIPTION, version);\n\n HKEY hClassKey;\n {\n LPCSTR psz_CLSID = CStrFromGUID(rclsid);\n\n if( NULL == psz_CLSID )\n return E_OUTOFMEMORY;\n\n HKEY hProgKey = keyCreate(HKEY_CLASSES_ROOT, progId);\n if( NULL != hProgKey )\n {\n \/\/ default key value\n keySetDef(hProgKey, description);\n\n keyClose(keySetDef(keyCreate(hProgKey, \"CLSID\"),\n psz_CLSID,\n GUID_STRLEN));\n\n \/\/hSubKey = keyClose(keyCreate(hBaseKey, \"Insertable\"));\n \n RegCloseKey(hProgKey);\n }\n if( isDefault )\n {\n hProgKey = keyCreate(HKEY_CLASSES_ROOT, PROGID_STR);\n if( NULL != hProgKey )\n {\n \/\/ default key value\n keySetDef(hProgKey, description);\n\n keyClose(keySetDef(keyCreate(hProgKey, \"CLSID\"),\n psz_CLSID,\n GUID_STRLEN));\n\n keyClose(keySetDef(keyCreate(hProgKey, \"CurVer\"),\n progId));\n }\n }\n hClassKey = keyCreate(hParent, psz_CLSID);\n CoTaskMemFree((void *)psz_CLSID);\n }\n if( NULL != hClassKey )\n {\n \/\/ default key value\n keySetDef(hClassKey, description);\n\n \/\/ Control key value\n keyClose(keyCreate(hClassKey, \"Control\"));\n\n \/\/ Insertable key value\n \/\/keyClose(keyCreate(hClassKey, \"Insertable\"));\n\n \/\/ ToolboxBitmap32 key value\n {\n char iconPath[pathLen+3];\n memcpy(iconPath, path, pathLen);\n strcpy(iconPath+pathLen, \",1\");\n keyClose(keySetDef(keyCreate(hClassKey,\n \"ToolboxBitmap32\"),\n iconPath, sizeof(iconPath)));\n }\n\n#ifdef BUILD_LOCALSERVER\n \/\/ LocalServer32 key value\n keyClose(keySetDef(keyCreate(hClassKey,\n \"LocalServer32\", path, pathLen+1)));\n#else\n \/\/ InprocServer32 key value\n {\n HKEY hSubKey = keySetDef(keyCreate(hClassKey,\n \"InprocServer32\"),\n path, pathLen+1);\n keySet(hSubKey,\n \"ThreadingModel\",\n THREADING_MODEL, sizeof(THREADING_MODEL));\n keyClose(hSubKey);\n }\n#endif\n\n \/\/ MiscStatus key value\n keyClose(keySetDef(keyCreate(hClassKey,\n \"MiscStatus\\\\1\"),\n MISC_STATUS, sizeof(MISC_STATUS)));\n\n \/\/ Programmable key value\n keyClose(keyCreate(hClassKey, \"Programmable\"));\n\n \/\/ ProgID key value\n keyClose(keySetDef(keyCreate(hClassKey,\n TEXT(\"ProgID\")),\n progId));\n\n \/\/ VersionIndependentProgID key value\n keyClose(keySetDef(keyCreate(hClassKey,\n \"VersionIndependentProgID\"),\n PROGID_STR, sizeof(PROGID_STR)));\n\n \/\/ Version key value\n keyClose(keySetDef(keyCreate(hClassKey,\n \"Version\"),\n \"1.0\"));\n\n \/\/ TypeLib key value\n LPCSTR psz_LIBID = CStrFromGUID(LIBID_AXVLC);\n if( NULL != psz_LIBID )\n {\n keyClose(keySetDef(keyCreate(hClassKey,\n \"TypeLib\"),\n psz_LIBID, GUID_STRLEN));\n CoTaskMemFree((void *)psz_LIBID);\n }\n RegCloseKey(hClassKey);\n }\n return S_OK;\n}\n\nSTDAPI DllRegisterServer(VOID)\n{\n DllUnregisterServer();\n\n char DllPath[MAX_PATH];\n DWORD DllPathLen=GetModuleFileNameA(h_instance, DllPath, sizeof(DllPath)) ;\n if( 0 == DllPathLen )\n return E_UNEXPECTED;\n\n HKEY hBaseKey;\n\n if( ERROR_SUCCESS != RegOpenKeyExA(HKEY_CLASSES_ROOT, \"CLSID\", 0, KEY_CREATE_SUB_KEY, &hBaseKey) )\n return SELFREG_E_CLASS;\n\n RegisterClassID(hBaseKey, CLSID_VLCPlugin, 1, FALSE, DllPath, DllPathLen);\n RegisterClassID(hBaseKey, CLSID_VLCPlugin2, 2, TRUE, DllPath, DllPathLen);\n\n RegCloseKey(hBaseKey);\n\n \/\/ indicate which component categories we support\n ICatRegister *pcr;\n if( SUCCEEDED(CoCreateInstance(CLSID_StdComponentCategoriesMgr, \n NULL, CLSCTX_INPROC_SERVER, IID_ICatRegister, (void**)&pcr)) ) {\n CATID implCategories[] = {\n CATID_Control,\n CATID_PersistsToPropertyBag,\n CATID_InternetAware,\n CATID_SafeForInitializing,\n CATID_SafeForScripting,\n };\n\n pcr->RegisterClassImplCategories(CLSID_VLCPlugin,\n sizeof(implCategories)\/sizeof(CATID), implCategories);\n pcr->RegisterClassImplCategories(CLSID_VLCPlugin2,\n sizeof(implCategories)\/sizeof(CATID), implCategories);\n pcr->Release();\n }\n\n \/\/ register type lib into the registry\n ITypeLib *typeLib;\n\n#ifdef BUILD_LOCALSERVER\n \/\/ replace .exe by .tlb\n strcpy(DllPath+DllPathLen-4, \".tlb\");\n#endif\n\n#ifndef OLE2ANSI\n size_t typeLibPathLen = MultiByteToWideChar(CP_ACP, 0, DllPath, -1, NULL, 0);\n if( typeLibPathLen > 0 )\n {\n LPOLESTR typeLibPath = (LPOLESTR)CoTaskMemAlloc(typeLibPathLen*sizeof(wchar_t));\n MultiByteToWideChar(CP_ACP, 0, DllPath, DllPathLen, typeLibPath, typeLibPathLen);\n if( FAILED(LoadTypeLibEx(typeLibPath, REGKIND_REGISTER, &typeLib)) )\n#ifndef BUILD_LOCALSERVER\n return SELFREG_E_TYPELIB;\n typeLib->Release();\n#endif\n CoTaskMemFree((void *)typeLibPath);\n }\n#else\n if( FAILED(LoadTypeLibEx((LPOLESTR)DllPath, REGKIND_REGISTER, &typeLib)) )\n return SELFREG_E_TYPELIB;\n typeLib->Release();\n#endif\n\n return S_OK;\n};\n\n#ifdef BUILD_LOCALSERVER\n\n\/*\n** easier to debug an application than a DLL on cygwin GDB :)\n*\/\n#include <iostream>\n\nSTDAPI_(int) WinMain(HINSTANCE hInst, HINSTANCE hPrev, LPSTR szCmdLine, int sw)\n{\n MSG msg;\n\n if( FAILED(OleInitialize(NULL)) )\n {\n cerr << \"cannot initialize OLE\" << endl;\n return 1;\n }\n\n h_instance = hInst;\n\n if( FAILED(DllRegisterServer()) )\n {\n cerr << \"cannot register Local Server\" << endl;\n return 1;\n }\n\n IUnknown *classProc = NULL;\n\n if( FAILED(DllGetClassObject(CLSID_VLCPlugin, IID_IUnknown, (LPVOID *)&classProc)) )\n return 0;\n \n DWORD dwRegisterClassObject;\n DWORD dwRegisterClassObject2;\n\n if( FAILED(CoRegisterClassObject(CLSID_VLCPlugin, classProc,\n CLSCTX_LOCAL_SERVER, REGCLS_MULTIPLEUSE, &dwRegisterClassObject)) )\n return 0;\n\n DWORD dwRegisterActiveObject;\n\n if( FAILED(RegisterActiveObject(classProc, CLSID_VLCPlugin,\n ACTIVEOBJECT_WEAK, &dwRegisterActiveObject)) )\n return 0;\n\n if( FAILED(RegisterActiveObject(classProc, CLSID_VLCPlugin2,\n ACTIVEOBJECT_WEAK, &dwRegisterActiveObject2)) )\n return 0;\n\n classProc->Release();\n\n \/*\n * Polling messages from event queue\n *\/\n while( S_FALSE == DllCanUnloadNow() )\n {\n while( PeekMessage(&msg, NULL, 0, 0, PM_REMOVE) )\n {\n if( msg.message == WM_QUIT )\n break; \/\/ break out PeekMessage loop\n\n \/*if(TranslateAccelerator(ghwndApp, ghAccel, &msg))\n continue;*\/\n\n TranslateMessage(&msg);\n DispatchMessage(&msg);\n }\n\n if(msg.message == WM_QUIT)\n break; \/\/ break out main loop\n\n WaitMessage();\n }\n\n if( SUCCEEDED(RevokeActiveObject(dwRegisterActiveObject, NULL)) )\n CoRevokeClassObject(dwRegisterClassObject);\n\n if( SUCCEEDED(RevokeActiveObject(dwRegisterActiveObject2, NULL)) )\n CoRevokeClassObject(dwRegisterClassObject2);\n\n \/\/ Reached on WM_QUIT message\n OleUninitialize();\n return ((int) msg.wParam);\n};\n\n#else\n\nSTDAPI_(BOOL) DllMain(HANDLE hModule, DWORD fdwReason, LPVOID lpReserved )\n{\n switch( fdwReason )\n {\n case DLL_PROCESS_ATTACH:\n h_instance = (HINSTANCE)hModule;\n break;\n\n default:\n break;\n }\n return TRUE;\n};\n\n#endif\n\n<|endoftext|>"} {"text":"<commit_before>\n#include \"utils.h\"\n\n#include <functional>\n#include <chrono>\n#include <cstring>\n\n#ifdef _WIN32\n#include <direct.h>\n#else\n#include <unistd.h>\n#endif\n\nnamespace utils\n{\n void RunLoop(float deltaSec, std::function<bool(double, float)> loopFunc)\n {\n using namespace std::chrono;\n using DoubleDuration = duration<double>;\n using DoubleTimePoint = time_point<high_resolution_clock, DoubleDuration>;\n\n const auto period = duration_cast<high_resolution_clock::duration>(duration<float>(deltaSec));\n\n auto currentTime = high_resolution_clock::now();\n auto accumulator = high_resolution_clock::duration();\n auto userTime = high_resolution_clock::duration();\n\n const auto MAX_FRAME_DURATION = duration_cast<high_resolution_clock::duration>(milliseconds(250));\n\n bool keepLooping = true;\n while (keepLooping)\n {\n auto now = high_resolution_clock::now();\n auto frameTime = (now - currentTime);\n if (frameTime > MAX_FRAME_DURATION)\n {\n frameTime = MAX_FRAME_DURATION;\n }\n currentTime = now;\n accumulator += frameTime;\n while (accumulator >= period)\n {\n DoubleDuration curTimeDouble = duration_cast<DoubleDuration>(userTime);\n keepLooping = loopFunc(curTimeDouble.count(), deltaSec) && keepLooping;\n accumulator -= period;\n userTime += period;\n }\n\n }\n }\n\n void FixWorkingDirectory()\n {\n char temp[128] = {};\n const char *dir = getcwd(temp, sizeof(temp));\n const char *bin_pos = strstr(dir, \"bin\");\n const char *build_pos = strstr(dir, \"premake\");\n if (bin_pos)\n {\n chdir(\"..\");\n }\n else if (build_pos)\n {\n chdir(\"..\/..\/..\");\n }\n }\n}\n<commit_msg>Changed FixWorkingDir() to just back up one dir level. The binaries should only be run from the bin directory.<commit_after>\n#include \"utils.h\"\n\n#include <functional>\n#include <chrono>\n#include <cstring>\n\n#ifdef _WIN32\n#include <direct.h>\n#else\n#include <unistd.h>\n#endif\n\nnamespace utils\n{\n void RunLoop(float deltaSec, std::function<bool(double, float)> loopFunc)\n {\n using namespace std::chrono;\n using DoubleDuration = duration<double>;\n using DoubleTimePoint = time_point<high_resolution_clock, DoubleDuration>;\n\n const auto period = duration_cast<high_resolution_clock::duration>(duration<float>(deltaSec));\n\n auto currentTime = high_resolution_clock::now();\n auto accumulator = high_resolution_clock::duration();\n auto userTime = high_resolution_clock::duration();\n\n const auto MAX_FRAME_DURATION = duration_cast<high_resolution_clock::duration>(milliseconds(250));\n\n bool keepLooping = true;\n while (keepLooping)\n {\n auto now = high_resolution_clock::now();\n auto frameTime = (now - currentTime);\n if (frameTime > MAX_FRAME_DURATION)\n {\n frameTime = MAX_FRAME_DURATION;\n }\n currentTime = now;\n accumulator += frameTime;\n while (accumulator >= period)\n {\n DoubleDuration curTimeDouble = duration_cast<DoubleDuration>(userTime);\n keepLooping = loopFunc(curTimeDouble.count(), deltaSec) && keepLooping;\n accumulator -= period;\n userTime += period;\n }\n\n }\n }\n\n void FixWorkingDirectory()\n {\n chdir(\"..\");\n }\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"util\/log.hpp\"\n#include \"util\/isatty.hpp\"\n#include <boost\/algorithm\/string\/predicate.hpp>\n#include <cstdio>\n#include <iostream>\n#include <mutex>\n#include <string>\n\nnamespace osrm\n{\nnamespace util\n{\n\nnamespace\n{\nstatic const char COL_RESET[]{\"\\x1b[0m\"};\nstatic const char RED[]{\"\\x1b[31m\"};\nstatic const char YELLOW[]{\"\\x1b[33m\"};\nstatic const char MAGENTA[]{\"\\x1b[35m\"};\n\/\/ static const char GREEN[] { \"\\x1b[32m\"};\n\/\/ static const char BLUE[] { \"\\x1b[34m\"};\n\/\/ static const char CYAN[] { \"\\x1b[36m\"};\n}\n\nvoid LogPolicy::Unmute() { m_is_mute = false; }\n\nvoid LogPolicy::Mute() { m_is_mute = true; }\n\nbool LogPolicy::IsMute() const { return m_is_mute; }\n\nLogLevel LogPolicy::GetLevel() const { return m_level; }\n\nvoid LogPolicy::SetLevel(LogLevel level) { m_level = level; }\n\nvoid LogPolicy::SetLevel(std::string const &level)\n{\n \/\/ Keep in sync with LogLevel definition\n if (boost::iequals(level, \"NONE\"))\n m_level = logNONE;\n else if (boost::iequals(level, \"ERROR\"))\n m_level = logERROR;\n else if (boost::iequals(level, \"WARNING\"))\n m_level = logWARNING;\n else if (boost::iequals(level, \"INFO\"))\n m_level = logINFO;\n else if (boost::iequals(level, \"DEBUG\"))\n m_level = logDEBUG;\n else\n m_level = logINFO;\n}\n\nLogPolicy &LogPolicy::GetInstance()\n{\n static LogPolicy runningInstance;\n return runningInstance;\n}\n\nstd::string LogPolicy::GetLevels()\n{\n \/\/ Keep in sync with LogLevel definition\n return \"NONE, ERROR, WARNING, INFO, DEBUG\";\n}\n\nLog::Log(LogLevel level_, std::ostream &ostream) : level(level_), stream(ostream)\n{\n std::lock_guard<std::mutex> lock(get_mutex());\n if (!LogPolicy::GetInstance().IsMute() && level <= LogPolicy::GetInstance().GetLevel())\n {\n const bool is_terminal = IsStdoutATTY();\n switch (level)\n {\n case logNONE:\n break;\n case logWARNING:\n stream << (is_terminal ? YELLOW : \"\") << \"[warn] \";\n break;\n case logERROR:\n stream << (is_terminal ? RED : \"\") << \"[error] \";\n break;\n case logDEBUG:\n stream << (is_terminal ? MAGENTA : \"\") << \"[debug] \";\n break;\n default: \/\/ logINFO:\n stream << \"[info] \";\n break;\n }\n }\n}\n\nLog::Log(LogLevel level_) : Log(level_, buffer) {}\n\nstd::mutex &Log::get_mutex()\n{\n static std::mutex mtx;\n return mtx;\n}\n\n\/**\n * Close down this logging instance.\n * This destructor is responsible for flushing any buffered data,\n * and printing a newline character (each logger object is responsible for only one line)\n * Because sub-classes can replace the `stream` object - we need to verify whether\n * we're writing to std::cerr\/cout, or whether we should write to the stream\n *\/\nLog::~Log()\n{\n std::lock_guard<std::mutex> lock(get_mutex());\n if (!LogPolicy::GetInstance().IsMute() && level <= LogPolicy::GetInstance().GetLevel())\n {\n const bool usestd = (&stream == &buffer);\n const bool is_terminal = IsStdoutATTY();\n if (usestd)\n {\n switch (level)\n {\n case logNONE:\n break;\n case logWARNING:\n case logERROR:\n std::cerr << buffer.str();\n std::cerr << (is_terminal ? COL_RESET : \"\");\n std::cerr << std::endl;\n break;\n case logDEBUG:\n case logINFO:\n default:\n std::cout << buffer.str();\n std::cout << (is_terminal ? COL_RESET : \"\");\n std::cout << std::endl;\n break;\n }\n }\n else\n {\n stream << (is_terminal ? COL_RESET : \"\");\n stream << std::endl;\n }\n }\n}\n\nUnbufferedLog::UnbufferedLog(LogLevel level_)\n : Log(level_, (level_ == logWARNING || level_ == logERROR) ? std::cerr : std::cout)\n{\n stream.flags(std::ios_base::unitbuf);\n}\n}\n}\n<commit_msg>Revert \"chore: remove compile time debug log control\"<commit_after>#include \"util\/log.hpp\"\n#include \"util\/isatty.hpp\"\n#include <boost\/algorithm\/string\/predicate.hpp>\n#include <cstdio>\n#include <iostream>\n#include <mutex>\n#include <string>\n\nnamespace osrm\n{\nnamespace util\n{\n\nnamespace\n{\nstatic const char COL_RESET[]{\"\\x1b[0m\"};\nstatic const char RED[]{\"\\x1b[31m\"};\nstatic const char YELLOW[]{\"\\x1b[33m\"};\n#ifndef NDEBUG\nstatic const char MAGENTA[]{\"\\x1b[35m\"};\n#endif\n\/\/ static const char GREEN[] { \"\\x1b[32m\"};\n\/\/ static const char BLUE[] { \"\\x1b[34m\"};\n\/\/ static const char CYAN[] { \"\\x1b[36m\"};\n}\n\nvoid LogPolicy::Unmute() { m_is_mute = false; }\n\nvoid LogPolicy::Mute() { m_is_mute = true; }\n\nbool LogPolicy::IsMute() const { return m_is_mute; }\n\nLogLevel LogPolicy::GetLevel() const { return m_level; }\n\nvoid LogPolicy::SetLevel(LogLevel level) { m_level = level; }\n\nvoid LogPolicy::SetLevel(std::string const &level)\n{\n \/\/ Keep in sync with LogLevel definition\n if (boost::iequals(level, \"NONE\"))\n m_level = logNONE;\n else if (boost::iequals(level, \"ERROR\"))\n m_level = logERROR;\n else if (boost::iequals(level, \"WARNING\"))\n m_level = logWARNING;\n else if (boost::iequals(level, \"INFO\"))\n m_level = logINFO;\n else if (boost::iequals(level, \"DEBUG\"))\n m_level = logDEBUG;\n else\n m_level = logINFO;\n}\n\nLogPolicy &LogPolicy::GetInstance()\n{\n static LogPolicy runningInstance;\n return runningInstance;\n}\n\nstd::string LogPolicy::GetLevels()\n{\n \/\/ Keep in sync with LogLevel definition\n return \"NONE, ERROR, WARNING, INFO, DEBUG\";\n}\n\nLog::Log(LogLevel level_, std::ostream &ostream) : level(level_), stream(ostream)\n{\n std::lock_guard<std::mutex> lock(get_mutex());\n if (!LogPolicy::GetInstance().IsMute() && level <= LogPolicy::GetInstance().GetLevel())\n {\n const bool is_terminal = IsStdoutATTY();\n switch (level)\n {\n case logNONE:\n break;\n case logWARNING:\n stream << (is_terminal ? YELLOW : \"\") << \"[warn] \";\n break;\n case logERROR:\n stream << (is_terminal ? RED : \"\") << \"[error] \";\n break;\n case logDEBUG:\n#ifndef NDEBUG\n stream << (is_terminal ? MAGENTA : \"\") << \"[debug] \";\n#endif\n break;\n default: \/\/ logINFO:\n stream << \"[info] \";\n break;\n }\n }\n}\n\nLog::Log(LogLevel level_) : Log(level_, buffer) {}\n\nstd::mutex &Log::get_mutex()\n{\n static std::mutex mtx;\n return mtx;\n}\n\n\/**\n * Close down this logging instance.\n * This destructor is responsible for flushing any buffered data,\n * and printing a newline character (each logger object is responsible for only one line)\n * Because sub-classes can replace the `stream` object - we need to verify whether\n * we're writing to std::cerr\/cout, or whether we should write to the stream\n *\/\nLog::~Log()\n{\n std::lock_guard<std::mutex> lock(get_mutex());\n if (!LogPolicy::GetInstance().IsMute() && level <= LogPolicy::GetInstance().GetLevel())\n {\n const bool usestd = (&stream == &buffer);\n const bool is_terminal = IsStdoutATTY();\n if (usestd)\n {\n switch (level)\n {\n case logNONE:\n break;\n case logWARNING:\n case logERROR:\n std::cerr << buffer.str();\n std::cerr << (is_terminal ? COL_RESET : \"\");\n std::cerr << std::endl;\n break;\n case logDEBUG:\n#ifdef NDEBUG\n break;\n#endif\n case logINFO:\n default:\n std::cout << buffer.str();\n std::cout << (is_terminal ? COL_RESET : \"\");\n std::cout << std::endl;\n break;\n }\n }\n else\n {\n stream << (is_terminal ? COL_RESET : \"\");\n stream << std::endl;\n }\n }\n}\n\nUnbufferedLog::UnbufferedLog(LogLevel level_)\n : Log(level_, (level_ == logWARNING || level_ == logERROR) ? std::cerr : std::cout)\n{\n stream.flags(std::ios_base::unitbuf);\n}\n}\n}\n<|endoftext|>"} {"text":"<commit_before>#include <assert.h>\n#include <stdio.h>\n#include <atomic>\n#include <new>\n#include <stdlib.h>\n#include <string.h>\n#include <unistd.h>\n#include <limits.h>\n#include <pthread.h>\n#include <signal.h>\n#include <setjmp.h>\n#include <errno.h>\n#include <sys\/wait.h>\n#include <sys\/mman.h>\n#include \"mtrace.h\"\n#include \"fstest.h\"\n#include \"libutil.h\"\n#include \"spinbarrier.hh\"\n\nextern char _end[];\n__thread sigjmp_buf pf_jmpbuf;\n__thread int pf_active;\n\nclass double_barrier {\n spin_barrier enter_;\n spin_barrier exit_;\n\npublic:\n double_barrier() : enter_(2), exit_(2) {}\n void sync() { enter(); exit(); }\n void enter() { enter_.join(); }\n void exit() { exit_.join(); }\n};\n\nstruct testproc {\n double_barrier setup;\n std::atomic<void (*)(void)> setupf1;\n std::atomic<void (*)(void)> setupf2;\n\n testproc(void (*s1)(void), void (*s2)(void)) : setupf1(s1), setupf2(s2) {}\n void run() {\n setup.enter();\n setupf1();\n setupf2();\n setup.exit();\n }\n};\n\nstruct testfunc {\n double_barrier start;\n double_barrier stop;\n\n std::atomic<int (*)(void)> func;\n std::atomic<int> retval;\n\n testfunc(int (*f)(void)) : func(f) {}\n void run() {\n#ifndef XV6_USER\n errno = 0;\n#endif\n start.sync();\n retval = func();\n stop.sync();\n }\n};\n\nstatic void*\ntestfunc_thread(void* arg)\n{\n madvise(0, (size_t) _end, MADV_WILLNEED);\n testfunc* f = (testfunc*) arg;\n f->run();\n return nullptr;\n}\n\nstatic void\nrun_test(testproc* tp, testfunc* tf, fstest* t, int first_func, bool do_pin)\n{\n assert(first_func == 0 || first_func == 1);\n if (do_pin)\n setaffinity(2);\n\n for (int i = 0; i < 2; i++)\n new (&tp[i]) testproc(t->proc[i].setup_proc, t->setup_procfinal);\n for (int i = 0; i < 2; i++)\n new (&tf[i]) testfunc(t->func[i].call);\n\n t->setup_common();\n\n pid_t pids[2] = { 0, 0 };\n for (int p = 0; p < 2; p++) {\n int nfunc = 0;\n for (int f = 0; f < 2; f++)\n if (t->func[f].callproc == p)\n nfunc++;\n if (nfunc == 0)\n continue;\n\n fflush(stdout);\n pids[p] = fork();\n assert(pids[p] >= 0);\n\n if (pids[p] == 0) {\n \/\/ Get all text and data structures\n madvise(0, (size_t) _end, MADV_WILLNEED);\n \/\/ Prime the VM system (this must be kept in sync with\n \/\/ fs_testgen.py)\n void *r = mmap((void*)0x12345600000, 4 * 4096, PROT_READ, MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED, -1, 0);\n if (r == (void*)-1)\n setup_error(\"mmap\");\n munmap(r, 4 * 4096);\n\n \/\/ Run setup\n tp[p].run();\n\n int ndone = 0;\n pthread_t tid[2];\n for (int f = 0; f < 2; f++) {\n if (t->func[f].callproc == p) {\n if (do_pin)\n setaffinity(f);\n ndone++;\n if (ndone == nfunc)\n testfunc_thread(&tf[f]);\n else\n pthread_create(&tid[f], 0, testfunc_thread, (void*) &tf[f]);\n }\n }\n\n if (nfunc == 2)\n pthread_join(tid[0], nullptr);\n exit(0);\n }\n }\n\n for (int p = 0; p < 2; p++) if (pids[p]) tp[p].setup.sync();\n t->setup_final();\n\n for (int i = 0; i < 2; i++) tf[i].start.enter();\n\n char mtname[64];\n snprintf(mtname, sizeof(mtname), \"%s\", t->testname);\n mtenable_type(mtrace_record_ascope, mtname);\n\n for (int i = 0; i < 2; i++) {\n tf[first_func ^ i].start.exit();\n tf[first_func ^ i].stop.enter();\n }\n\n mtdisable(mtname);\n\n for (int i = 0; i < 2; i++) tf[i].stop.exit();\n\n for (int p = 0; p < 2; p++)\n if (pids[p])\n assert(waitpid(pids[p], nullptr, 0) >= 0);\n\n t->cleanup();\n}\n\nstatic void\npf_handler(int signo)\n{\n if (pf_active)\n siglongjmp(pf_jmpbuf, signo);\n \/\/ Let the error happen\n signal(signo, SIG_DFL);\n}\n\nstatic bool verbose = false;\nstatic bool check_commutativity = false;\nstatic bool run_threads = false;\nstatic bool check_results = false;\nstatic fstest *cur_test = nullptr;\n\nvoid\nexpect_result(const char *varname, long got, long expect)\n{\n if (!check_results) return;\n if (got == expect) return;\n auto name = cur_test->testname;\n#ifdef XV6_USER\n printf(\"%s: expected %s == %ld, got %ld\\n\",\n name, varname, expect, got);\n#else\n printf(\"%s: expected %s == %ld, got %ld (errno %s)\\n\",\n name, varname, expect, got, strerror(errno));\n#endif\n}\n\nvoid\nexpect_errno(int expect)\n{\n#ifndef XV6_USER\n if (!check_results) return;\n if (errno == expect) return;\n auto name = cur_test->testname;\n printf(\"%s: expected errno == %s, got %s\\n\",\n name, strerror(expect), strerror(errno));\n#endif\n}\n\nstatic void\nusage(const char* prog)\n{\n fprintf(stderr, \"Usage: %s [-v] [-c] [-t] [-r] [-n NPARTS] [-p THISPART] [min[-max]]\\n\", prog);\n}\n\nint\nmain(int ac, char** av)\n{\n uint32_t min = 0;\n uint32_t max;\n int nparts = -1;\n int thispart = -1;\n\n uint32_t ntests = 0;\n for (ntests = min; fstests[ntests].testname; ntests++)\n ;\n max = ntests - 1;\n\n for (;;) {\n int opt = getopt(ac, av, \"vctrp:n:\");\n if (opt == -1)\n break;\n\n switch (opt) {\n case 'v':\n verbose = true;\n break;\n\n case 'c':\n check_commutativity = true;\n break;\n\n case 't':\n run_threads = true;\n break;\n\n case 'r':\n run_threads = true;\n check_results = true;\n break;\n\n case 'n':\n nparts = atoi(optarg);\n break;\n\n case 'p':\n thispart = atoi(optarg);\n break;\n\n default:\n usage(av[0]);\n return -1;\n }\n }\n\n if (optind < ac) {\n char* dash = strchr(av[optind], '-');\n if (!dash) {\n min = max = atoi(av[optind]);\n } else {\n *dash = '\\0';\n if (av[optind])\n min = atoi(av[optind]);\n if (*(dash + 1))\n max = atoi(dash + 1);\n }\n } else if (nparts >= 0 || thispart >= 0) {\n if (nparts < 0 || thispart < 0) {\n usage(av[0]);\n return -1;\n }\n\n uint32_t partsize = (ntests + nparts - 1) \/nparts;\n min = partsize * thispart;\n max = partsize * (thispart + 1) - 1;\n }\n\n if (!check_commutativity && !run_threads) {\n fprintf(stderr, \"Must specify one of -c or -t\\n\");\n usage(av[0]);\n return -1;\n }\n\n printf(\"fstest:\");\n if (verbose)\n printf(\" verbose\");\n if (check_commutativity)\n printf(\" check\");\n if (run_threads)\n printf(\" threads\");\n if (check_results)\n printf(\" results\");\n if (min == 0 && max == ntests - 1)\n printf(\" all\");\n else if (min == max)\n printf(\" %d\", min);\n else\n printf(\" %d-%d\", min, max);\n printf(\"\\n\");\n\n testproc* tp = (testproc*) mmap(nullptr, 4096, PROT_READ | PROT_WRITE,\n MAP_SHARED | MAP_ANONYMOUS, -1, 0);\n assert(tp != MAP_FAILED);\n assert(2*sizeof(*tp) <= 4096);\n\n testfunc* tf = (testfunc*) mmap(nullptr, 4096, PROT_READ | PROT_WRITE,\n MAP_SHARED | MAP_ANONYMOUS, -1, 0);\n assert(tf != MAP_FAILED);\n assert(2*sizeof(*tf) <= 4096);\n\n madvise(0, (size_t) _end, MADV_WILLNEED);\n\n signal(SIGPIPE, SIG_IGN);\n signal(SIGBUS, pf_handler);\n signal(SIGSEGV, pf_handler);\n\n for (uint32_t t = min; t <= max && t < ntests; t++) {\n cur_test = &fstests[t];\n\n if (verbose)\n printf(\"%s (test %d) starting\\n\", fstests[t].testname, t);\n\n if (check_commutativity) {\n run_test(tp, tf, &fstests[t], 0, false);\n int ra0 = tf[0].retval;\n int ra1 = tf[1].retval;\n\n run_test(tp, tf, &fstests[t], 1, false);\n int rb0 = tf[0].retval;\n int rb1 = tf[1].retval;\n\n if (ra0 == rb0 && ra1 == rb1) {\n if (verbose)\n printf(\"%s: commutes: %s->%d %s->%d\\n\",\n fstests[t].testname,\n fstests[t].func[0].callname, ra0, fstests[t].func[1].callname, ra1);\n } else {\n printf(\"%s: diverges: %s->%d %s->%d vs %s->%d %s->%d\\n\",\n fstests[t].testname,\n fstests[t].func[0].callname, ra0, fstests[t].func[1].callname, ra1,\n fstests[t].func[1].callname, rb1, fstests[t].func[0].callname, rb0);\n }\n }\n\n if (run_threads) {\n run_test(tp, tf, &fstests[t], 0, true);\n }\n }\n\n printf(\"fstest: done\\n\");\n}\n<commit_msg>fstest: Prime non-fixed mmap region<commit_after>#include <assert.h>\n#include <stdio.h>\n#include <atomic>\n#include <new>\n#include <stdlib.h>\n#include <string.h>\n#include <unistd.h>\n#include <limits.h>\n#include <pthread.h>\n#include <signal.h>\n#include <setjmp.h>\n#include <errno.h>\n#include <sys\/wait.h>\n#include <sys\/mman.h>\n#include \"mtrace.h\"\n#include \"fstest.h\"\n#include \"libutil.h\"\n#include \"spinbarrier.hh\"\n\nextern char _end[];\n__thread sigjmp_buf pf_jmpbuf;\n__thread int pf_active;\n\nclass double_barrier {\n spin_barrier enter_;\n spin_barrier exit_;\n\npublic:\n double_barrier() : enter_(2), exit_(2) {}\n void sync() { enter(); exit(); }\n void enter() { enter_.join(); }\n void exit() { exit_.join(); }\n};\n\nstruct testproc {\n double_barrier setup;\n std::atomic<void (*)(void)> setupf1;\n std::atomic<void (*)(void)> setupf2;\n\n testproc(void (*s1)(void), void (*s2)(void)) : setupf1(s1), setupf2(s2) {}\n void run() {\n setup.enter();\n setupf1();\n setupf2();\n setup.exit();\n }\n};\n\nstruct testfunc {\n double_barrier start;\n double_barrier stop;\n\n std::atomic<int (*)(void)> func;\n std::atomic<int> retval;\n\n testfunc(int (*f)(void)) : func(f) {}\n void run() {\n#ifndef XV6_USER\n errno = 0;\n#endif\n start.sync();\n retval = func();\n stop.sync();\n }\n};\n\nstatic void*\ntestfunc_thread(void* arg)\n{\n madvise(0, (size_t) _end, MADV_WILLNEED);\n testfunc* f = (testfunc*) arg;\n f->run();\n return nullptr;\n}\n\nstatic void\nrun_test(testproc* tp, testfunc* tf, fstest* t, int first_func, bool do_pin)\n{\n assert(first_func == 0 || first_func == 1);\n if (do_pin)\n setaffinity(2);\n\n for (int i = 0; i < 2; i++)\n new (&tp[i]) testproc(t->proc[i].setup_proc, t->setup_procfinal);\n for (int i = 0; i < 2; i++)\n new (&tf[i]) testfunc(t->func[i].call);\n\n t->setup_common();\n\n pid_t pids[2] = { 0, 0 };\n for (int p = 0; p < 2; p++) {\n int nfunc = 0;\n for (int f = 0; f < 2; f++)\n if (t->func[f].callproc == p)\n nfunc++;\n if (nfunc == 0)\n continue;\n\n fflush(stdout);\n pids[p] = fork();\n assert(pids[p] >= 0);\n\n if (pids[p] == 0) {\n \/\/ Get all text and data structures\n madvise(0, (size_t) _end, MADV_WILLNEED);\n\n \/\/ Prime the VM system (this must be kept in sync with\n \/\/ fs_testgen.py)\n void *r = mmap((void*)0x12345600000, 4 * 4096, PROT_READ, MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED, -1, 0);\n if (r == (void*)-1)\n setup_error(\"mmap (fixed)\");\n munmap(r, 4 * 4096);\n\n r = mmap(0, 4 * 4096, PROT_READ, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);\n if (r == (void*)-1)\n setup_error(\"mmap (non-fixed)\");\n munmap(r, 4 * 4096);\n\n \/\/ Run setup\n tp[p].run();\n\n int ndone = 0;\n pthread_t tid[2];\n for (int f = 0; f < 2; f++) {\n if (t->func[f].callproc == p) {\n if (do_pin)\n setaffinity(f);\n ndone++;\n if (ndone == nfunc)\n testfunc_thread(&tf[f]);\n else\n pthread_create(&tid[f], 0, testfunc_thread, (void*) &tf[f]);\n }\n }\n\n if (nfunc == 2)\n pthread_join(tid[0], nullptr);\n exit(0);\n }\n }\n\n for (int p = 0; p < 2; p++) if (pids[p]) tp[p].setup.sync();\n t->setup_final();\n\n for (int i = 0; i < 2; i++) tf[i].start.enter();\n\n char mtname[64];\n snprintf(mtname, sizeof(mtname), \"%s\", t->testname);\n mtenable_type(mtrace_record_ascope, mtname);\n\n for (int i = 0; i < 2; i++) {\n tf[first_func ^ i].start.exit();\n tf[first_func ^ i].stop.enter();\n }\n\n mtdisable(mtname);\n\n for (int i = 0; i < 2; i++) tf[i].stop.exit();\n\n for (int p = 0; p < 2; p++)\n if (pids[p])\n assert(waitpid(pids[p], nullptr, 0) >= 0);\n\n t->cleanup();\n}\n\nstatic void\npf_handler(int signo)\n{\n if (pf_active)\n siglongjmp(pf_jmpbuf, signo);\n \/\/ Let the error happen\n signal(signo, SIG_DFL);\n}\n\nstatic bool verbose = false;\nstatic bool check_commutativity = false;\nstatic bool run_threads = false;\nstatic bool check_results = false;\nstatic fstest *cur_test = nullptr;\n\nvoid\nexpect_result(const char *varname, long got, long expect)\n{\n if (!check_results) return;\n if (got == expect) return;\n auto name = cur_test->testname;\n#ifdef XV6_USER\n printf(\"%s: expected %s == %ld, got %ld\\n\",\n name, varname, expect, got);\n#else\n printf(\"%s: expected %s == %ld, got %ld (errno %s)\\n\",\n name, varname, expect, got, strerror(errno));\n#endif\n}\n\nvoid\nexpect_errno(int expect)\n{\n#ifndef XV6_USER\n if (!check_results) return;\n if (errno == expect) return;\n auto name = cur_test->testname;\n printf(\"%s: expected errno == %s, got %s\\n\",\n name, strerror(expect), strerror(errno));\n#endif\n}\n\nstatic void\nusage(const char* prog)\n{\n fprintf(stderr, \"Usage: %s [-v] [-c] [-t] [-r] [-n NPARTS] [-p THISPART] [min[-max]]\\n\", prog);\n}\n\nint\nmain(int ac, char** av)\n{\n uint32_t min = 0;\n uint32_t max;\n int nparts = -1;\n int thispart = -1;\n\n uint32_t ntests = 0;\n for (ntests = min; fstests[ntests].testname; ntests++)\n ;\n max = ntests - 1;\n\n for (;;) {\n int opt = getopt(ac, av, \"vctrp:n:\");\n if (opt == -1)\n break;\n\n switch (opt) {\n case 'v':\n verbose = true;\n break;\n\n case 'c':\n check_commutativity = true;\n break;\n\n case 't':\n run_threads = true;\n break;\n\n case 'r':\n run_threads = true;\n check_results = true;\n break;\n\n case 'n':\n nparts = atoi(optarg);\n break;\n\n case 'p':\n thispart = atoi(optarg);\n break;\n\n default:\n usage(av[0]);\n return -1;\n }\n }\n\n if (optind < ac) {\n char* dash = strchr(av[optind], '-');\n if (!dash) {\n min = max = atoi(av[optind]);\n } else {\n *dash = '\\0';\n if (av[optind])\n min = atoi(av[optind]);\n if (*(dash + 1))\n max = atoi(dash + 1);\n }\n } else if (nparts >= 0 || thispart >= 0) {\n if (nparts < 0 || thispart < 0) {\n usage(av[0]);\n return -1;\n }\n\n uint32_t partsize = (ntests + nparts - 1) \/nparts;\n min = partsize * thispart;\n max = partsize * (thispart + 1) - 1;\n }\n\n if (!check_commutativity && !run_threads) {\n fprintf(stderr, \"Must specify one of -c or -t\\n\");\n usage(av[0]);\n return -1;\n }\n\n printf(\"fstest:\");\n if (verbose)\n printf(\" verbose\");\n if (check_commutativity)\n printf(\" check\");\n if (run_threads)\n printf(\" threads\");\n if (check_results)\n printf(\" results\");\n if (min == 0 && max == ntests - 1)\n printf(\" all\");\n else if (min == max)\n printf(\" %d\", min);\n else\n printf(\" %d-%d\", min, max);\n printf(\"\\n\");\n\n testproc* tp = (testproc*) mmap(nullptr, 4096, PROT_READ | PROT_WRITE,\n MAP_SHARED | MAP_ANONYMOUS, -1, 0);\n assert(tp != MAP_FAILED);\n assert(2*sizeof(*tp) <= 4096);\n\n testfunc* tf = (testfunc*) mmap(nullptr, 4096, PROT_READ | PROT_WRITE,\n MAP_SHARED | MAP_ANONYMOUS, -1, 0);\n assert(tf != MAP_FAILED);\n assert(2*sizeof(*tf) <= 4096);\n\n madvise(0, (size_t) _end, MADV_WILLNEED);\n\n signal(SIGPIPE, SIG_IGN);\n signal(SIGBUS, pf_handler);\n signal(SIGSEGV, pf_handler);\n\n for (uint32_t t = min; t <= max && t < ntests; t++) {\n cur_test = &fstests[t];\n\n if (verbose)\n printf(\"%s (test %d) starting\\n\", fstests[t].testname, t);\n\n if (check_commutativity) {\n run_test(tp, tf, &fstests[t], 0, false);\n int ra0 = tf[0].retval;\n int ra1 = tf[1].retval;\n\n run_test(tp, tf, &fstests[t], 1, false);\n int rb0 = tf[0].retval;\n int rb1 = tf[1].retval;\n\n if (ra0 == rb0 && ra1 == rb1) {\n if (verbose)\n printf(\"%s: commutes: %s->%d %s->%d\\n\",\n fstests[t].testname,\n fstests[t].func[0].callname, ra0, fstests[t].func[1].callname, ra1);\n } else {\n printf(\"%s: diverges: %s->%d %s->%d vs %s->%d %s->%d\\n\",\n fstests[t].testname,\n fstests[t].func[0].callname, ra0, fstests[t].func[1].callname, ra1,\n fstests[t].func[1].callname, rb1, fstests[t].func[0].callname, rb0);\n }\n }\n\n if (run_threads) {\n run_test(tp, tf, &fstests[t], 0, true);\n }\n }\n\n printf(\"fstest: done\\n\");\n}\n<|endoftext|>"} {"text":"<commit_before>\/**************************************************************************\n**\n** This file is part of Qt Creator\n**\n** Copyright (c) 2009 Nokia Corporation and\/or its subsidiary(-ies).\n**\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n** Commercial Usage\n**\n** Licensees holding valid Qt Commercial licenses may use this file in\n** accordance with the Qt Commercial License Agreement provided with the\n** Software or, alternatively, in accordance with the terms contained in\n** a written agreement between you and Nokia.\n**\n** GNU Lesser General Public License Usage\n**\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** If you are unsure which license is appropriate for your use, please\n** contact the sales department at http:\/\/qt.nokia.com\/contact.\n**\n**************************************************************************\/\n\n#include \"navigatortreemodel.h\"\n\n#include <nodeabstractproperty.h>\n#include <nodelistproperty.h>\n#include <abstractview.h>\n#include <qmlitemnode.h>\n#include <invalididexception.h>\n\n#include <QMimeData>\n\nnamespace QmlDesigner {\n\nNavigatorTreeModel::NavigatorTreeModel(QObject *parent)\n : QStandardItemModel(parent),\n m_blockItemChangedSignal(false)\n{\n invisibleRootItem()->setFlags(Qt::NoItemFlags);\n\n #ifdef _LOCK_ITEMS_\n setColumnCount(3);\n #else\n setColumnCount(2);\n #endif\n\n setSupportedDragActions(Qt::LinkAction);\n\n connect(this, SIGNAL(itemChanged(QStandardItem*)),\n this, SLOT(handleChangedItem(QStandardItem*)));\n}\n\nNavigatorTreeModel::~NavigatorTreeModel()\n{\n}\n\nQt::DropActions NavigatorTreeModel::supportedDropActions() const\n{\n return Qt::LinkAction;\n}\n\nQStringList NavigatorTreeModel::mimeTypes() const\n{\n QStringList types;\n types << \"application\/vnd.modelnode.list\";\n return types;\n}\n\nQMimeData *NavigatorTreeModel::mimeData(const QModelIndexList &indexList) const\n{\n QMimeData *mimeData = new QMimeData();\n QByteArray encodedData;\n\n QSet<QModelIndex> rowAlreadyUsedSet;\n\n QDataStream stream(&encodedData, QIODevice::WriteOnly);\n\n foreach (const QModelIndex &index, indexList) {\n if (!index.isValid())\n continue;\n QModelIndex idIndex = index.sibling(index.row(), 0);\n if (rowAlreadyUsedSet.contains(idIndex))\n continue;\n\n rowAlreadyUsedSet.insert(idIndex);\n stream << idIndex.data(Qt::UserRole).toUInt();\n }\n\n mimeData->setData(\"application\/vnd.modelnode.list\", encodedData);\n\n return mimeData;\n}\n\nstatic bool isAnchestorInList(const ModelNode &node, const QList<ModelNode> &nodeList)\n{\n foreach (const ModelNode &nodeInList, nodeList) {\n if (nodeInList.isAncestorOf(node))\n return true;\n }\n\n return false;\n}\n\nbool NavigatorTreeModel::dropMimeData(const QMimeData *data,\n Qt::DropAction action,\n int row,\n int column,\n const QModelIndex &parentIndex)\n{\n if (action == Qt::IgnoreAction)\n return true;\n if (action != Qt::LinkAction)\n return false;\n if (!data->hasFormat(\"application\/vnd.modelnode.list\"))\n return false;\n if (column > 1)\n return false;\n if (parentIndex.model() != this)\n return false;\n\n\n QModelIndex parentIdIndex = parentIndex;\n parentIdIndex = parentIdIndex.sibling(parentIdIndex.row(), 0);\n\n Q_ASSERT(parentIdIndex.isValid());\n\n int targetIndex = 0;\n if (row > -1) {\n targetIndex = row;\n } else {\n targetIndex = rowCount(parentIdIndex);\n }\n\n QByteArray encodedData = data->data(\"application\/vnd.modelnode.list\");\n QDataStream stream(&encodedData, QIODevice::ReadOnly);\n\n QmlItemNode parentItemNode(nodeForIndex(parentIdIndex));\n\n QList<ModelNode> nodeList;\n\n while (!stream.atEnd()) {\n uint nodeHash;\n stream >> nodeHash;\n ModelNode node(nodeForHash(nodeHash));\n if (!node.isValid() || (parentItemNode == node) || node.isAncestorOf(parentItemNode))\n continue;\n nodeList.append(node);\n }\n\n RewriterTransaction transaction = m_view->beginRewriterTransaction();\n foreach (const ModelNode &node, nodeList) {\n if (!isAnchestorInList(node, nodeList)) {\n if (node.parentProperty().parentModelNode() != parentItemNode) {\n QmlItemNode itemNode(node);\n if (node != parentItemNode) {\n itemNode.setParent(parentItemNode);\n }\n }\n\n if (node.parentProperty().isNodeListProperty()) {\n int index = node.parentProperty().toNodeListProperty().toModelNodeList().indexOf(node);\n if (index < targetIndex) { \/\/ item is first removed from oldIndex, then inserted at new index\n --targetIndex;\n }\n if (index != targetIndex) {\n node.parentProperty().toNodeListProperty().slide(index, targetIndex);\n }\n }\n }\n }\n\n propagateInvisible(parentItemNode, isNodeInvisible(parentItemNode));\n\n return false; \/\/ don't let the view do drag&drop on its own\n}\n\nNavigatorTreeModel::ItemRow NavigatorTreeModel::createItemRow(const ModelNode &node)\n{\n Q_ASSERT(node.isValid());\n\n uint hash = qHash(node);\n\n QStandardItem *idItem = new QStandardItem;\n idItem->setDragEnabled(true);\n idItem->setDropEnabled(node.metaInfo().isContainer());\n idItem->setEditable(true);\n idItem->setData(hash, Qt::UserRole);\n\n #ifdef _LOCK_ITEMS_\n QStandardItem *lockItem = new QStandardItem;\n lockItem->setDragEnabled(true);\n lockItem->setDropEnabled(node.metaInfo().isContainer());\n lockItem->setEditable(false);\n lockItem->setCheckable(true);\n lockItem->setData(hash, Qt::UserRole);\n #endif\n\n QStandardItem *visibilityItem = new QStandardItem;\n visibilityItem->setDropEnabled(node.metaInfo().isContainer());\n visibilityItem->setCheckable(true);\n visibilityItem->setEditable(false);\n visibilityItem->setData(hash, Qt::UserRole);\n\n #ifdef _LOCK_ITEMS_\n return ItemRow(idItem, lockItem, visibilityItem);\n #else\n return ItemRow(idItem, visibilityItem);\n #endif\n}\n\nvoid NavigatorTreeModel::updateItemRow(const ModelNode &node, ItemRow items)\n{\n bool blockSignal = blockItemChangedSignal(true);\n\n items.idItem->setText(node.id());\n \/\/items.idItem->setToolTip(!node.id().isEmpty()?node.type():\"\");\n items.idItem->setToolTip(node.type());\n items.visibilityItem->setCheckState(node.auxiliaryData(\"invisible\").toBool() ? Qt::Unchecked : Qt::Checked);\n\n blockItemChangedSignal(blockSignal);\n}\n\n\/**\n Update the information shown for a node \/ property\n *\/\nvoid NavigatorTreeModel::updateItemRow(const ModelNode &node)\n{\n if (!containsNode(node))\n return;\n\n updateItemRow(node, itemRowForNode(node));\n}\n\n\/**\n Updates the sibling position of the item, depending on the position in the model.\n *\/\nvoid NavigatorTreeModel::updateItemRowOrder(const ModelNode &node)\n{\n if (!containsNode(node))\n return;\n\n ItemRow itemRow = itemRowForNode(node);\n int currentRow = itemRow.idItem->row();\n int newRow = currentRow;\n if (node.parentProperty().parentModelNode().isValid())\n newRow = modelNodeChildren(node.parentProperty().parentModelNode()).indexOf(node);\n Q_ASSERT(newRow >= 0);\n\n if (currentRow != newRow) {\n QStandardItem *parentIdItem = itemRow.idItem->parent();\n QList<QStandardItem*> items = parentIdItem->takeRow(currentRow);\n parentIdItem->insertRow(newRow, items);\n }\n}\n\nvoid NavigatorTreeModel::handleChangedItem(QStandardItem *item)\n{\n if (m_blockItemChangedSignal)\n return;\n\n uint nodeHash = item->data(Qt::UserRole).toUInt();\n Q_ASSERT(nodeHash && containsNodeHash(nodeHash));\n ModelNode node = nodeForHash(nodeHash);\n\n ItemRow itemRow = itemRowForNode(node);\n if (item == itemRow.idItem) {\n try {\n if (ModelNode::isValidId(item->text()))\n node.setId(item->text());\n else\n item->setText(node.id());\n } catch (InvalidIdException &) {\n item->setText(node.id());\n }\n } else if (item == itemRow.visibilityItem) {\n bool invisible = (item->checkState() == Qt::Unchecked);\n\n node.setAuxiliaryData(\"invisible\", invisible);\n propagateInvisible(node,isNodeInvisible(node));\n }\n}\n\nvoid NavigatorTreeModel::propagateInvisible(const ModelNode &node, const bool &invisible)\n{\n QList <ModelNode> children = node.allDirectSubModelNodes();\n foreach (ModelNode child, children) {\n child.setAuxiliaryData(\"childOfInvisible\",invisible);\n if (!child.auxiliaryData(\"invisible\").toBool())\n propagateInvisible(child,invisible);\n }\n}\n\nModelNode NavigatorTreeModel::nodeForHash(uint hash) const\n{\n ModelNode node = m_nodeHash.value(hash);\n Q_ASSERT(node.isValid());\n return node;\n}\n\nbool NavigatorTreeModel::containsNodeHash(uint hash) const\n{\n return m_nodeHash.contains(hash);\n}\n\nbool NavigatorTreeModel::containsNode(const ModelNode &node) const\n{\n return m_nodeItemHash.contains(node);\n}\n\nNavigatorTreeModel::ItemRow NavigatorTreeModel::itemRowForNode(const ModelNode &node)\n{\n Q_ASSERT(node.isValid());\n return m_nodeItemHash.value(node);\n}\n\nvoid NavigatorTreeModel::setView(AbstractView *view)\n{\n m_view = view;\n addSubTree(view->rootModelNode());\n}\n\nvoid NavigatorTreeModel::clearView()\n{\n m_view.clear();\n m_nodeHash.clear();\n m_nodeItemHash.clear();\n clear();\n}\n\nQModelIndex NavigatorTreeModel::indexForNode(const ModelNode &node) const\n{\n Q_ASSERT(node.isValid());\n if (!containsNode(node))\n return QModelIndex();\n ItemRow row = m_nodeItemHash.value(node);\n return row.idItem->index();\n}\n\nModelNode NavigatorTreeModel::nodeForIndex(const QModelIndex &index) const\n{\n Q_ASSERT(index.isValid());\n uint hash = index.data(Qt::UserRole).toUInt();\n Q_ASSERT(hash);\n Q_ASSERT(containsNodeHash(hash));\n return nodeForHash(hash);\n}\n\nbool NavigatorTreeModel::isInTree(const ModelNode &node) const\n{\n return m_nodeHash.keys().contains(qHash(node));\n}\n\nbool NavigatorTreeModel::isNodeInvisible(const QModelIndex &index) const\n{\n return isNodeInvisible(nodeForIndex(index));\n}\n\nbool NavigatorTreeModel::isNodeInvisible(const ModelNode &node) const\n{\n bool nodeInvisible = node.auxiliaryData(\"invisible\").toBool();\n if (node.hasAuxiliaryData(\"childOfInvisible\"))\n nodeInvisible = nodeInvisible || node.auxiliaryData(\"childOfInvisible\").toBool();\n return nodeInvisible;\n}\n\n\/**\n Adds node & all children to the visible tree hierarchy (if node should be visible at all).\n\n It always adds the node to the _end_ of the list of items.\n *\/\nvoid NavigatorTreeModel::addSubTree(const ModelNode &node)\n{\n Q_ASSERT(node.isValid());\n Q_ASSERT(!containsNodeHash(qHash(node)));\n\n \/\/ only add items that are in the modelNodeChildren list (that means, visible in the editor)\n if (!node.isRootNode()\n && !modelNodeChildren(node.parentProperty().parentModelNode()).contains(node)) {\n return;\n }\n\n ItemRow newRow = createItemRow(node);\n m_nodeHash.insert(qHash(node), node);\n m_nodeItemHash.insert(node, newRow);\n\n updateItemRow(node, newRow);\n\n foreach (const ModelNode &childNode, modelNodeChildren(node))\n addSubTree(childNode);\n\n \/\/ We assume that the node is always added to the _end_ of the property list.\n if (node.hasParentProperty()) {\n ItemRow parentRow = itemRowForNode(node.parentProperty().parentModelNode());\n if (parentRow.idItem)\n parentRow.idItem->appendRow(newRow.toList());\n } else {\n appendRow(newRow.toList());\n }\n}\n\n\/**\n Deletes visual representation for the node (subtree).\n *\/\nvoid NavigatorTreeModel::removeSubTree(const ModelNode &node)\n{\n Q_ASSERT(node.isValid());\n\n if (!containsNode(node))\n return;\n\n QList<QStandardItem*> rowList;\n ItemRow itemRow = itemRowForNode(node);\n if (itemRow.idItem->parent()) {\n rowList = itemRow.idItem->parent()->takeRow(itemRow.idItem->row());\n }\n\n foreach (const ModelNode &node, modelNodeChildren(node)) {\n removeSubTree(node);\n }\n\n qDeleteAll(rowList);\n\n m_nodeHash.remove(qHash(node));\n m_nodeItemHash.remove(node);\n}\n\nQList<ModelNode> NavigatorTreeModel::modelNodeChildren(const ModelNode &parentNode)\n{\n QList<ModelNode> children;\n if (QmlItemNode(parentNode).isValid())\n foreach (const QmlItemNode &childNode, QmlItemNode(parentNode).children())\n children << childNode.modelNode();\n return children;\n}\n\n\/\/ along the lines of QObject::blockSignals\nbool NavigatorTreeModel::blockItemChangedSignal(bool block)\n{\n bool oldValue = m_blockItemChangedSignal;\n m_blockItemChangedSignal = block;\n return oldValue;\n}\n\n\n}\n\n<commit_msg>QmlDesigner.Navigator: removed tooltips<commit_after>\/**************************************************************************\n**\n** This file is part of Qt Creator\n**\n** Copyright (c) 2009 Nokia Corporation and\/or its subsidiary(-ies).\n**\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n** Commercial Usage\n**\n** Licensees holding valid Qt Commercial licenses may use this file in\n** accordance with the Qt Commercial License Agreement provided with the\n** Software or, alternatively, in accordance with the terms contained in\n** a written agreement between you and Nokia.\n**\n** GNU Lesser General Public License Usage\n**\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** If you are unsure which license is appropriate for your use, please\n** contact the sales department at http:\/\/qt.nokia.com\/contact.\n**\n**************************************************************************\/\n\n#include \"navigatortreemodel.h\"\n\n#include <nodeabstractproperty.h>\n#include <nodelistproperty.h>\n#include <abstractview.h>\n#include <qmlitemnode.h>\n#include <invalididexception.h>\n\n#include <QMimeData>\n\nnamespace QmlDesigner {\n\nNavigatorTreeModel::NavigatorTreeModel(QObject *parent)\n : QStandardItemModel(parent),\n m_blockItemChangedSignal(false)\n{\n invisibleRootItem()->setFlags(Qt::NoItemFlags);\n\n #ifdef _LOCK_ITEMS_\n setColumnCount(3);\n #else\n setColumnCount(2);\n #endif\n\n setSupportedDragActions(Qt::LinkAction);\n\n connect(this, SIGNAL(itemChanged(QStandardItem*)),\n this, SLOT(handleChangedItem(QStandardItem*)));\n}\n\nNavigatorTreeModel::~NavigatorTreeModel()\n{\n}\n\nQt::DropActions NavigatorTreeModel::supportedDropActions() const\n{\n return Qt::LinkAction;\n}\n\nQStringList NavigatorTreeModel::mimeTypes() const\n{\n QStringList types;\n types << \"application\/vnd.modelnode.list\";\n return types;\n}\n\nQMimeData *NavigatorTreeModel::mimeData(const QModelIndexList &indexList) const\n{\n QMimeData *mimeData = new QMimeData();\n QByteArray encodedData;\n\n QSet<QModelIndex> rowAlreadyUsedSet;\n\n QDataStream stream(&encodedData, QIODevice::WriteOnly);\n\n foreach (const QModelIndex &index, indexList) {\n if (!index.isValid())\n continue;\n QModelIndex idIndex = index.sibling(index.row(), 0);\n if (rowAlreadyUsedSet.contains(idIndex))\n continue;\n\n rowAlreadyUsedSet.insert(idIndex);\n stream << idIndex.data(Qt::UserRole).toUInt();\n }\n\n mimeData->setData(\"application\/vnd.modelnode.list\", encodedData);\n\n return mimeData;\n}\n\nstatic bool isAnchestorInList(const ModelNode &node, const QList<ModelNode> &nodeList)\n{\n foreach (const ModelNode &nodeInList, nodeList) {\n if (nodeInList.isAncestorOf(node))\n return true;\n }\n\n return false;\n}\n\nbool NavigatorTreeModel::dropMimeData(const QMimeData *data,\n Qt::DropAction action,\n int row,\n int column,\n const QModelIndex &parentIndex)\n{\n if (action == Qt::IgnoreAction)\n return true;\n if (action != Qt::LinkAction)\n return false;\n if (!data->hasFormat(\"application\/vnd.modelnode.list\"))\n return false;\n if (column > 1)\n return false;\n if (parentIndex.model() != this)\n return false;\n\n\n QModelIndex parentIdIndex = parentIndex;\n parentIdIndex = parentIdIndex.sibling(parentIdIndex.row(), 0);\n\n Q_ASSERT(parentIdIndex.isValid());\n\n int targetIndex = 0;\n if (row > -1) {\n targetIndex = row;\n } else {\n targetIndex = rowCount(parentIdIndex);\n }\n\n QByteArray encodedData = data->data(\"application\/vnd.modelnode.list\");\n QDataStream stream(&encodedData, QIODevice::ReadOnly);\n\n QmlItemNode parentItemNode(nodeForIndex(parentIdIndex));\n\n QList<ModelNode> nodeList;\n\n while (!stream.atEnd()) {\n uint nodeHash;\n stream >> nodeHash;\n ModelNode node(nodeForHash(nodeHash));\n if (!node.isValid() || (parentItemNode == node) || node.isAncestorOf(parentItemNode))\n continue;\n nodeList.append(node);\n }\n\n RewriterTransaction transaction = m_view->beginRewriterTransaction();\n foreach (const ModelNode &node, nodeList) {\n if (!isAnchestorInList(node, nodeList)) {\n if (node.parentProperty().parentModelNode() != parentItemNode) {\n QmlItemNode itemNode(node);\n if (node != parentItemNode) {\n itemNode.setParent(parentItemNode);\n }\n }\n\n if (node.parentProperty().isNodeListProperty()) {\n int index = node.parentProperty().toNodeListProperty().toModelNodeList().indexOf(node);\n if (index < targetIndex) { \/\/ item is first removed from oldIndex, then inserted at new index\n --targetIndex;\n }\n if (index != targetIndex) {\n node.parentProperty().toNodeListProperty().slide(index, targetIndex);\n }\n }\n }\n }\n\n propagateInvisible(parentItemNode, isNodeInvisible(parentItemNode));\n\n return false; \/\/ don't let the view do drag&drop on its own\n}\n\nNavigatorTreeModel::ItemRow NavigatorTreeModel::createItemRow(const ModelNode &node)\n{\n Q_ASSERT(node.isValid());\n\n uint hash = qHash(node);\n\n QStandardItem *idItem = new QStandardItem;\n idItem->setDragEnabled(true);\n idItem->setDropEnabled(node.metaInfo().isContainer());\n idItem->setEditable(true);\n idItem->setData(hash, Qt::UserRole);\n\n #ifdef _LOCK_ITEMS_\n QStandardItem *lockItem = new QStandardItem;\n lockItem->setDragEnabled(true);\n lockItem->setDropEnabled(node.metaInfo().isContainer());\n lockItem->setEditable(false);\n lockItem->setCheckable(true);\n lockItem->setData(hash, Qt::UserRole);\n #endif\n\n QStandardItem *visibilityItem = new QStandardItem;\n visibilityItem->setDropEnabled(node.metaInfo().isContainer());\n visibilityItem->setCheckable(true);\n visibilityItem->setEditable(false);\n visibilityItem->setData(hash, Qt::UserRole);\n\n #ifdef _LOCK_ITEMS_\n return ItemRow(idItem, lockItem, visibilityItem);\n #else\n return ItemRow(idItem, visibilityItem);\n #endif\n}\n\nvoid NavigatorTreeModel::updateItemRow(const ModelNode &node, ItemRow items)\n{\n bool blockSignal = blockItemChangedSignal(true);\n\n items.idItem->setText(node.id());\n items.visibilityItem->setCheckState(node.auxiliaryData(\"invisible\").toBool() ? Qt::Unchecked : Qt::Checked);\n\n blockItemChangedSignal(blockSignal);\n}\n\n\/**\n Update the information shown for a node \/ property\n *\/\nvoid NavigatorTreeModel::updateItemRow(const ModelNode &node)\n{\n if (!containsNode(node))\n return;\n\n updateItemRow(node, itemRowForNode(node));\n}\n\n\/**\n Updates the sibling position of the item, depending on the position in the model.\n *\/\nvoid NavigatorTreeModel::updateItemRowOrder(const ModelNode &node)\n{\n if (!containsNode(node))\n return;\n\n ItemRow itemRow = itemRowForNode(node);\n int currentRow = itemRow.idItem->row();\n int newRow = currentRow;\n if (node.parentProperty().parentModelNode().isValid())\n newRow = modelNodeChildren(node.parentProperty().parentModelNode()).indexOf(node);\n Q_ASSERT(newRow >= 0);\n\n if (currentRow != newRow) {\n QStandardItem *parentIdItem = itemRow.idItem->parent();\n QList<QStandardItem*> items = parentIdItem->takeRow(currentRow);\n parentIdItem->insertRow(newRow, items);\n }\n}\n\nvoid NavigatorTreeModel::handleChangedItem(QStandardItem *item)\n{\n if (m_blockItemChangedSignal)\n return;\n\n uint nodeHash = item->data(Qt::UserRole).toUInt();\n Q_ASSERT(nodeHash && containsNodeHash(nodeHash));\n ModelNode node = nodeForHash(nodeHash);\n\n ItemRow itemRow = itemRowForNode(node);\n if (item == itemRow.idItem) {\n try {\n if (ModelNode::isValidId(item->text()))\n node.setId(item->text());\n else\n item->setText(node.id());\n } catch (InvalidIdException &) {\n item->setText(node.id());\n }\n } else if (item == itemRow.visibilityItem) {\n bool invisible = (item->checkState() == Qt::Unchecked);\n\n node.setAuxiliaryData(\"invisible\", invisible);\n propagateInvisible(node,isNodeInvisible(node));\n }\n}\n\nvoid NavigatorTreeModel::propagateInvisible(const ModelNode &node, const bool &invisible)\n{\n QList <ModelNode> children = node.allDirectSubModelNodes();\n foreach (ModelNode child, children) {\n child.setAuxiliaryData(\"childOfInvisible\",invisible);\n if (!child.auxiliaryData(\"invisible\").toBool())\n propagateInvisible(child,invisible);\n }\n}\n\nModelNode NavigatorTreeModel::nodeForHash(uint hash) const\n{\n ModelNode node = m_nodeHash.value(hash);\n Q_ASSERT(node.isValid());\n return node;\n}\n\nbool NavigatorTreeModel::containsNodeHash(uint hash) const\n{\n return m_nodeHash.contains(hash);\n}\n\nbool NavigatorTreeModel::containsNode(const ModelNode &node) const\n{\n return m_nodeItemHash.contains(node);\n}\n\nNavigatorTreeModel::ItemRow NavigatorTreeModel::itemRowForNode(const ModelNode &node)\n{\n Q_ASSERT(node.isValid());\n return m_nodeItemHash.value(node);\n}\n\nvoid NavigatorTreeModel::setView(AbstractView *view)\n{\n m_view = view;\n addSubTree(view->rootModelNode());\n}\n\nvoid NavigatorTreeModel::clearView()\n{\n m_view.clear();\n m_nodeHash.clear();\n m_nodeItemHash.clear();\n clear();\n}\n\nQModelIndex NavigatorTreeModel::indexForNode(const ModelNode &node) const\n{\n Q_ASSERT(node.isValid());\n if (!containsNode(node))\n return QModelIndex();\n ItemRow row = m_nodeItemHash.value(node);\n return row.idItem->index();\n}\n\nModelNode NavigatorTreeModel::nodeForIndex(const QModelIndex &index) const\n{\n Q_ASSERT(index.isValid());\n uint hash = index.data(Qt::UserRole).toUInt();\n Q_ASSERT(hash);\n Q_ASSERT(containsNodeHash(hash));\n return nodeForHash(hash);\n}\n\nbool NavigatorTreeModel::isInTree(const ModelNode &node) const\n{\n return m_nodeHash.keys().contains(qHash(node));\n}\n\nbool NavigatorTreeModel::isNodeInvisible(const QModelIndex &index) const\n{\n return isNodeInvisible(nodeForIndex(index));\n}\n\nbool NavigatorTreeModel::isNodeInvisible(const ModelNode &node) const\n{\n bool nodeInvisible = node.auxiliaryData(\"invisible\").toBool();\n if (node.hasAuxiliaryData(\"childOfInvisible\"))\n nodeInvisible = nodeInvisible || node.auxiliaryData(\"childOfInvisible\").toBool();\n return nodeInvisible;\n}\n\n\/**\n Adds node & all children to the visible tree hierarchy (if node should be visible at all).\n\n It always adds the node to the _end_ of the list of items.\n *\/\nvoid NavigatorTreeModel::addSubTree(const ModelNode &node)\n{\n Q_ASSERT(node.isValid());\n Q_ASSERT(!containsNodeHash(qHash(node)));\n\n \/\/ only add items that are in the modelNodeChildren list (that means, visible in the editor)\n if (!node.isRootNode()\n && !modelNodeChildren(node.parentProperty().parentModelNode()).contains(node)) {\n return;\n }\n\n ItemRow newRow = createItemRow(node);\n m_nodeHash.insert(qHash(node), node);\n m_nodeItemHash.insert(node, newRow);\n\n updateItemRow(node, newRow);\n\n foreach (const ModelNode &childNode, modelNodeChildren(node))\n addSubTree(childNode);\n\n \/\/ We assume that the node is always added to the _end_ of the property list.\n if (node.hasParentProperty()) {\n ItemRow parentRow = itemRowForNode(node.parentProperty().parentModelNode());\n if (parentRow.idItem)\n parentRow.idItem->appendRow(newRow.toList());\n } else {\n appendRow(newRow.toList());\n }\n}\n\n\/**\n Deletes visual representation for the node (subtree).\n *\/\nvoid NavigatorTreeModel::removeSubTree(const ModelNode &node)\n{\n Q_ASSERT(node.isValid());\n\n if (!containsNode(node))\n return;\n\n QList<QStandardItem*> rowList;\n ItemRow itemRow = itemRowForNode(node);\n if (itemRow.idItem->parent()) {\n rowList = itemRow.idItem->parent()->takeRow(itemRow.idItem->row());\n }\n\n foreach (const ModelNode &node, modelNodeChildren(node)) {\n removeSubTree(node);\n }\n\n qDeleteAll(rowList);\n\n m_nodeHash.remove(qHash(node));\n m_nodeItemHash.remove(node);\n}\n\nQList<ModelNode> NavigatorTreeModel::modelNodeChildren(const ModelNode &parentNode)\n{\n QList<ModelNode> children;\n if (QmlItemNode(parentNode).isValid())\n foreach (const QmlItemNode &childNode, QmlItemNode(parentNode).children())\n children << childNode.modelNode();\n return children;\n}\n\n\/\/ along the lines of QObject::blockSignals\nbool NavigatorTreeModel::blockItemChangedSignal(bool block)\n{\n bool oldValue = m_blockItemChangedSignal;\n m_blockItemChangedSignal = block;\n return oldValue;\n}\n\n\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2008 Paul Hodge\n\n#include \"common_headers.h\"\n\n#include \"testing.h\"\n#include \"circa.h\"\n\nnamespace circa {\nnamespace parser_tests {\n\nvoid literal_float()\n{\n token_stream::TokenStream tokens(\"1.0\");\n ast::Expression *expr = parser::atom(tokens);\n ast::LiteralFloat *literal = dynamic_cast<ast::LiteralFloat*>(expr);\n test_assert(literal != NULL);\n test_assert(literal->text == \"1.0\");\n test_assert(literal->toString() == \"1.0\");\n test_assert(literal->hasQuestionMark == false);\n\n delete expr;\n\n tokens.reset(\"5.0?\");\n expr = parser::atom(tokens);\n literal = dynamic_cast<ast::LiteralFloat*>(expr);\n test_assert(literal != NULL);\n test_assert(literal->text == \"5.0\");\n test_assert(literal->toString() == \"5.0\");\n test_assert(literal->hasQuestionMark == true);\n\n delete expr;\n}\n\nvoid literal_string()\n{\n token_stream::TokenStream tokens(\"\\\"quoted string\\\"\");\n ast::Expression *expr = parser::atom(tokens);\n ast::LiteralString *literal = dynamic_cast<ast::LiteralString*>(expr);\n test_assert(literal != NULL);\n test_assert(literal->text == \"quoted string\");\n test_assert(literal->toString() == \"\\\"quoted string\\\"\");\n\n delete expr;\n}\n\nvoid function_call()\n{\n token_stream::TokenStream tokens(\"add(1,2)\");\n ast::FunctionCall *functionCall = parser::functionCall(tokens);\n test_assert(functionCall != NULL);\n test_assert(functionCall->functionName == \"add\");\n\n ast::LiteralInteger *arg1 =\n dynamic_cast<ast::LiteralInteger*>(functionCall->arguments[0]->expression);\n test_assert(arg1 != NULL);\n test_assert(arg1->text == \"1\");\n ast::LiteralInteger *arg2 =\n dynamic_cast<ast::LiteralInteger*>(functionCall->arguments[1]->expression);\n test_assert(arg2 != NULL);\n test_assert(arg2->text == \"2\");\n test_assert(functionCall->toString() == \"add(1,2)\");\n\n delete functionCall;\n}\n\nvoid name_binding_expression()\n{\n token_stream::TokenStream tokens(\"name = hi(2,u)\");\n ast::ExpressionStatement *statement = parser::expressionStatement(tokens);\n\n test_assert(statement->nameBinding == \"name\");\n\n ast::FunctionCall *functionCall =\n dynamic_cast<ast::FunctionCall*>(statement->expression);\n\n test_assert(functionCall->functionName == \"hi\");\n test_assert(functionCall->toString() == \"hi(2,u)\");\n test_assert(statement->toString() == \"name = hi(2,u)\");\n\n delete statement;\n}\n\nvoid test_to_string()\n{\n \/\/ Build an AST programatically so that the toString function\n \/\/ can't cheat.\n ast::FunctionCall *functionCall = new ast::FunctionCall(\"something\");\n functionCall->addArgument(new ast::LiteralString(\"input0\"), \" \", \"\");\n functionCall->addArgument(new ast::LiteralInteger(\"4\"), \"\", \" \");\n test_assert(functionCall->toString() == \"something( \\\"input0\\\",4 )\");\n delete functionCall;\n}\n\nvoid create_literals()\n{\n Branch branch;\n\n ast::LiteralInteger *lint = new ast::LiteralInteger(\"13\");\n Term *int_t = lint->createTerm(branch);\n test_assert(int_t->type == INT_TYPE);\n test_assert(as_int(int_t) == 13);\n delete lint;\n\n ast::LiteralFloat *lfloat = new ast::LiteralFloat(\"1.432\");\n Term *float_t = lfloat->createTerm(branch);\n test_assert(float_t->type == FLOAT_TYPE);\n test_assert(as_float(float_t) > 1.431 && as_float(float_t) < 1.433);\n delete lfloat;\n\n ast::LiteralString *lstr = new ast::LiteralString(\"hello\");\n Term *str_t = lstr->createTerm(branch);\n test_assert(str_t->type == STRING_TYPE);\n test_assert(as_string(str_t) == \"hello\");\n delete lstr;\n}\n\nvoid create_function_call()\n{\n Branch branch;\n\n ast::FunctionCall *functionCall = new ast::FunctionCall(\"add\");\n functionCall->addArgument(new ast::LiteralFloat(\"2\"), \"\", \"\");\n functionCall->addArgument(new ast::LiteralFloat(\"3\"), \"\", \"\");\n\n Term *term = functionCall->createTerm(branch);\n test_assert(as_function(term->function).name == \"add\");\n\n \/\/ make sure this term is not evaluated yet\n test_assert(term->needsUpdate);\n\n evaluate_term(term);\n\n test_assert(!term->needsUpdate);\n test_assert(as_float(term) == 5);\n\n delete functionCall;\n}\n\nvoid test_apply_statement()\n{\n Branch branch;\n\n Term* result = apply_statement(branch, \"something = add(5.0,3.0)\");\n\n test_assert(result != NULL);\n test_assert(result->name == \"something\");\n test_assert(as_function(result->function).name == \"add\");\n test_assert(result->needsUpdate);\n evaluate_term(result);\n test_assert(as_float(result) == 8);\n test_assert(!result->needsUpdate);\n}\n\nvoid function_decl_ast()\n{\n \/\/ Create a FunctionDecl from scratch\n ast::FunctionDecl decl;\n\n decl.header = new ast::FunctionHeader();\n decl.header->functionName = \"add\";\n decl.header->outputType = \"float\";\n decl.header->addArgument(\"float\",\"arg1\");\n decl.header->addArgument(\"float\",\"arg2\");\n\n decl.statements = new ast::StatementList();\n\n token_stream::TokenStream tokens(\"x = add(arg1,arg2)\");\n decl.statements->push(parser::statement(tokens));\n\n test_assert(decl.toString() == \"function add(float arg1, float arg2)\\nx = add(arg1,arg2)\\nend\");\n}\n\nvoid function_header()\n{\n ast::FunctionHeader header = eval_as<ast::FunctionHeader>(\n \"'function test(int a, float, string b , int) -> float'.tokenize.parse-function-header\");\n\n test_assert(header.functionName == \"test\");\n test_assert(header.arguments[0].type == \"int\");\n test_assert(header.arguments[0].name == \"a\");\n test_assert(header.arguments[1].type == \"float\");\n test_assert(header.arguments[1].name == \"\");\n test_assert(header.arguments[2].type == \"string\");\n test_assert(header.arguments[2].name == \"b\");\n test_assert(header.arguments[3].type == \"int\");\n test_assert(header.arguments[3].name == \"\");\n test_assert(header.outputType == \"float\");\n}\n\nvoid function_decl_parse()\n{\n token_stream::TokenStream tokens(\"function func(string a, int b) -> void\\n\"\n \"concat(a, to-string(b)) -> print\\n\"\n \"end\");\n ast::Statement* statement = parser::statement(tokens);\n\n test_assert(statement->typeName() == \"FunctionDecl\");\n\n tokens.reset(\"function func2()\\n\"\n \"print(\\\"hello\\\")\\n\"\n \"end\\n\"\n \"some-function(1,2)\\n\");\n\n \/*ast::StatementList* statementList = *\/parser::statementList(tokens);\n}\n\nvoid rebind_operator()\n{\n token_stream::TokenStream tokens(\"@cheese\");\n ast::Expression* expr = parser::atom(tokens);\n\n ast::Identifier* id = dynamic_cast<ast::Identifier*>(expr);\n test_assert(id != NULL);\n test_assert(id->text == \"cheese\");\n test_assert(id->hasRebindOperator);\n\n delete expr;\n\n tokens.reset(\"gouda\");\n expr = parser::atom(tokens);\n id = dynamic_cast<ast::Identifier*>(expr);\n test_assert(id != NULL);\n test_assert(id->text == \"gouda\");\n test_assert(!id->hasRebindOperator);\n\n delete expr;\n\n Branch branch;\n Term* a = int_var(branch, 2, \"a\");\n Term* b = int_var(branch, 5, \"b\");\n\n test_assert(branch.getNamed(\"a\") == a);\n test_assert(branch.getNamed(\"b\") == b);\n\n Term* result = apply_statement(branch, \"add(@a, b)\");\n\n test_assert(branch.getNamed(\"a\") == result);\n test_assert(branch.getNamed(\"b\") == b);\n}\n\nvoid ast_walk()\n{\n token_stream::TokenStream tokens(\"concat(to-string(add(1,2.0)), \\\"cheese\\\")\");\n ast::Expression* expr = parser::infixExpression(tokens);\n\n std::vector<std::string> expected;\n expected.push_back(\"concat(to-string(add(1,2.0)), \\\"cheese\\\")\");\n expected.push_back(\"to-string(add(1,2.0))\");\n expected.push_back(\"add(1,2.0)\");\n expected.push_back(\"1\");\n expected.push_back(\"2.0\");\n expected.push_back(\"\\\"cheese\\\"\");\n\n struct MyWalker : public ast::ExpressionWalker\n {\n std::vector<std::string> found;\n\n virtual void visit(ast::Expression* expr)\n {\n found.push_back(expr->toString());\n }\n } walker;\n\n expr->walk(walker);\n\n for (int i=0; i < (int) expected.size(); i++) {\n test_assert(expected[i] == walker.found[i]);\n }\n\n delete expr;\n}\n\nvoid test_eval_statement()\n{\n Branch b;\n\n test_assert(eval_statement(b, \"5\")->asInt() == 5);\n test_assert(eval_statement(b, \"-2\")->asInt() == -2);\n test_assert(eval_statement(b, \"1.0\")->asFloat() == 1.0);\n \/\/test_assert(eval_statement(b, \"-.123\")->asFloat() == -0.123);FIXME\n test_assert(eval_statement(b, \"\\\"apple\\\"\")->asString() == \"apple\");\n test_assert(eval_statement(b, \"\\\"\\\"\")->asString() == \"\");\n}\n\nvoid comment_statement()\n{\n token_stream::TokenStream tokens(\"-- this is a comment\");\n\n ast::Statement* statement = parser::statement(tokens);\n test_assert(dynamic_cast<ast::IgnorableStatement*>(statement) != NULL);\n\n test_assert(tokens.finished());\n}\n\nvoid test_type_decl()\n{\n token_stream::TokenStream tokens(\"type Vector {\\nfloat x\\nint y\\n}\");\n\n ast::TypeDecl* typeDecl = parser::typeDecl(tokens);\n test_assert(typeDecl != NULL);\n test_assert(typeDecl->name == \"Vector\");\n test_assert(typeDecl->members[0].type == \"float\");\n test_assert(typeDecl->members[0].name == \"x\");\n test_assert(typeDecl->members[1].type == \"int\");\n test_assert(typeDecl->members[1].name == \"y\");\n}\n\nvoid test_type_decl_statement()\n{\n token_stream::TokenStream tokens(\"type Mytype\\n{\\nstring str\\nfloat asdf\\n}\");\n ast::Statement* statement = parser::statement(tokens);\n\n test_assert(dynamic_cast<ast::TypeDecl*>(statement) != NULL);\n}\n\nvoid test_type_decl_full_trip()\n{\n Branch branch;\n Term *t = eval_statement(branch, \"type Mytype\\n{\\nstring s\\nfloat a\\n}\");\n\n test_assert(!t->hasError());\n\n test_assert(t->name == \"Mytype\");\n test_assert(as_type(t).fields[0].type == STRING_TYPE);\n test_assert(as_type(t).fields[0].name == \"s\");\n test_assert(as_type(t).fields[1].type == FLOAT_TYPE);\n test_assert(as_type(t).fields[1].name == \"a\");\n}\n\nvoid test_parse_if_block()\n{\n token_stream::TokenStream tokens(\n \"if (x > 2) \\n print('yes') \\n else \\n print('no') \\n end\");\n\n ast::IfStatement* ifStatement = parser::ifStatement(tokens);\n\n test_assert(ifStatement != NULL);\n\n \/\/ these lines will need to be fixed when there is better whitespace preservation\n test_assert(ifStatement->condition->toString() == \"x>2\");\n test_assert(ifStatement->positiveBranch->toString() == \"print(\\\"yes\\\")\\n\");\n test_assert(ifStatement->negativeBranch->toString() == \"print(\\\"no\\\")\\n\");\n}\n\n} \/\/ namespace parser_tests\n\nvoid register_parser_tests()\n{\n REGISTER_TEST_CASE(parser_tests::literal_float);\n REGISTER_TEST_CASE(parser_tests::literal_string);\n REGISTER_TEST_CASE(parser_tests::function_call);\n REGISTER_TEST_CASE(parser_tests::name_binding_expression);\n REGISTER_TEST_CASE(parser_tests::test_to_string);\n REGISTER_TEST_CASE(parser_tests::create_literals);\n REGISTER_TEST_CASE(parser_tests::create_function_call);\n REGISTER_TEST_CASE(parser_tests::test_apply_statement);\n REGISTER_TEST_CASE(parser_tests::function_decl_ast);\n REGISTER_TEST_CASE(parser_tests::function_header);\n REGISTER_TEST_CASE(parser_tests::function_decl_parse);\n REGISTER_TEST_CASE(parser_tests::rebind_operator);\n REGISTER_TEST_CASE(parser_tests::ast_walk);\n REGISTER_TEST_CASE(parser_tests::test_eval_statement);\n REGISTER_TEST_CASE(parser_tests::comment_statement);\n REGISTER_TEST_CASE(parser_tests::test_type_decl);\n REGISTER_TEST_CASE(parser_tests::test_type_decl_statement);\n REGISTER_TEST_CASE(parser_tests::test_type_decl_full_trip);\n REGISTER_TEST_CASE(parser_tests::test_parse_if_block);\n}\n\n} \/\/ namespace circa\n<commit_msg>Add to if block parsing test<commit_after>\/\/ Copyright 2008 Paul Hodge\n\n#include \"common_headers.h\"\n\n#include \"testing.h\"\n#include \"circa.h\"\n\nnamespace circa {\nnamespace parser_tests {\n\nvoid literal_float()\n{\n token_stream::TokenStream tokens(\"1.0\");\n ast::Expression *expr = parser::atom(tokens);\n ast::LiteralFloat *literal = dynamic_cast<ast::LiteralFloat*>(expr);\n test_assert(literal != NULL);\n test_assert(literal->text == \"1.0\");\n test_assert(literal->toString() == \"1.0\");\n test_assert(literal->hasQuestionMark == false);\n\n delete expr;\n\n tokens.reset(\"5.0?\");\n expr = parser::atom(tokens);\n literal = dynamic_cast<ast::LiteralFloat*>(expr);\n test_assert(literal != NULL);\n test_assert(literal->text == \"5.0\");\n test_assert(literal->toString() == \"5.0\");\n test_assert(literal->hasQuestionMark == true);\n\n delete expr;\n}\n\nvoid literal_string()\n{\n token_stream::TokenStream tokens(\"\\\"quoted string\\\"\");\n ast::Expression *expr = parser::atom(tokens);\n ast::LiteralString *literal = dynamic_cast<ast::LiteralString*>(expr);\n test_assert(literal != NULL);\n test_assert(literal->text == \"quoted string\");\n test_assert(literal->toString() == \"\\\"quoted string\\\"\");\n\n delete expr;\n}\n\nvoid function_call()\n{\n token_stream::TokenStream tokens(\"add(1,2)\");\n ast::FunctionCall *functionCall = parser::functionCall(tokens);\n test_assert(functionCall != NULL);\n test_assert(functionCall->functionName == \"add\");\n\n ast::LiteralInteger *arg1 =\n dynamic_cast<ast::LiteralInteger*>(functionCall->arguments[0]->expression);\n test_assert(arg1 != NULL);\n test_assert(arg1->text == \"1\");\n ast::LiteralInteger *arg2 =\n dynamic_cast<ast::LiteralInteger*>(functionCall->arguments[1]->expression);\n test_assert(arg2 != NULL);\n test_assert(arg2->text == \"2\");\n test_assert(functionCall->toString() == \"add(1,2)\");\n\n delete functionCall;\n}\n\nvoid name_binding_expression()\n{\n token_stream::TokenStream tokens(\"name = hi(2,u)\");\n ast::ExpressionStatement *statement = parser::expressionStatement(tokens);\n\n test_assert(statement->nameBinding == \"name\");\n\n ast::FunctionCall *functionCall =\n dynamic_cast<ast::FunctionCall*>(statement->expression);\n\n test_assert(functionCall->functionName == \"hi\");\n test_assert(functionCall->toString() == \"hi(2,u)\");\n test_assert(statement->toString() == \"name = hi(2,u)\");\n\n delete statement;\n}\n\nvoid test_to_string()\n{\n \/\/ Build an AST programatically so that the toString function\n \/\/ can't cheat.\n ast::FunctionCall *functionCall = new ast::FunctionCall(\"something\");\n functionCall->addArgument(new ast::LiteralString(\"input0\"), \" \", \"\");\n functionCall->addArgument(new ast::LiteralInteger(\"4\"), \"\", \" \");\n test_assert(functionCall->toString() == \"something( \\\"input0\\\",4 )\");\n delete functionCall;\n}\n\nvoid create_literals()\n{\n Branch branch;\n\n ast::LiteralInteger *lint = new ast::LiteralInteger(\"13\");\n Term *int_t = lint->createTerm(branch);\n test_assert(int_t->type == INT_TYPE);\n test_assert(as_int(int_t) == 13);\n delete lint;\n\n ast::LiteralFloat *lfloat = new ast::LiteralFloat(\"1.432\");\n Term *float_t = lfloat->createTerm(branch);\n test_assert(float_t->type == FLOAT_TYPE);\n test_assert(as_float(float_t) > 1.431 && as_float(float_t) < 1.433);\n delete lfloat;\n\n ast::LiteralString *lstr = new ast::LiteralString(\"hello\");\n Term *str_t = lstr->createTerm(branch);\n test_assert(str_t->type == STRING_TYPE);\n test_assert(as_string(str_t) == \"hello\");\n delete lstr;\n}\n\nvoid create_function_call()\n{\n Branch branch;\n\n ast::FunctionCall *functionCall = new ast::FunctionCall(\"add\");\n functionCall->addArgument(new ast::LiteralFloat(\"2\"), \"\", \"\");\n functionCall->addArgument(new ast::LiteralFloat(\"3\"), \"\", \"\");\n\n Term *term = functionCall->createTerm(branch);\n test_assert(as_function(term->function).name == \"add\");\n\n \/\/ make sure this term is not evaluated yet\n test_assert(term->needsUpdate);\n\n evaluate_term(term);\n\n test_assert(!term->needsUpdate);\n test_assert(as_float(term) == 5);\n\n delete functionCall;\n}\n\nvoid test_apply_statement()\n{\n Branch branch;\n\n Term* result = apply_statement(branch, \"something = add(5.0,3.0)\");\n\n test_assert(result != NULL);\n test_assert(result->name == \"something\");\n test_assert(as_function(result->function).name == \"add\");\n test_assert(result->needsUpdate);\n evaluate_term(result);\n test_assert(as_float(result) == 8);\n test_assert(!result->needsUpdate);\n}\n\nvoid function_decl_ast()\n{\n \/\/ Create a FunctionDecl from scratch\n ast::FunctionDecl decl;\n\n decl.header = new ast::FunctionHeader();\n decl.header->functionName = \"add\";\n decl.header->outputType = \"float\";\n decl.header->addArgument(\"float\",\"arg1\");\n decl.header->addArgument(\"float\",\"arg2\");\n\n decl.statements = new ast::StatementList();\n\n token_stream::TokenStream tokens(\"x = add(arg1,arg2)\");\n decl.statements->push(parser::statement(tokens));\n\n test_assert(decl.toString() == \"function add(float arg1, float arg2)\\nx = add(arg1,arg2)\\nend\");\n}\n\nvoid function_header()\n{\n ast::FunctionHeader header = eval_as<ast::FunctionHeader>(\n \"'function test(int a, float, string b , int) -> float'.tokenize.parse-function-header\");\n\n test_assert(header.functionName == \"test\");\n test_assert(header.arguments[0].type == \"int\");\n test_assert(header.arguments[0].name == \"a\");\n test_assert(header.arguments[1].type == \"float\");\n test_assert(header.arguments[1].name == \"\");\n test_assert(header.arguments[2].type == \"string\");\n test_assert(header.arguments[2].name == \"b\");\n test_assert(header.arguments[3].type == \"int\");\n test_assert(header.arguments[3].name == \"\");\n test_assert(header.outputType == \"float\");\n}\n\nvoid function_decl_parse()\n{\n token_stream::TokenStream tokens(\"function func(string a, int b) -> void\\n\"\n \"concat(a, to-string(b)) -> print\\n\"\n \"end\");\n ast::Statement* statement = parser::statement(tokens);\n\n test_assert(statement->typeName() == \"FunctionDecl\");\n\n tokens.reset(\"function func2()\\n\"\n \"print(\\\"hello\\\")\\n\"\n \"end\\n\"\n \"some-function(1,2)\\n\");\n\n \/*ast::StatementList* statementList = *\/parser::statementList(tokens);\n}\n\nvoid rebind_operator()\n{\n token_stream::TokenStream tokens(\"@cheese\");\n ast::Expression* expr = parser::atom(tokens);\n\n ast::Identifier* id = dynamic_cast<ast::Identifier*>(expr);\n test_assert(id != NULL);\n test_assert(id->text == \"cheese\");\n test_assert(id->hasRebindOperator);\n\n delete expr;\n\n tokens.reset(\"gouda\");\n expr = parser::atom(tokens);\n id = dynamic_cast<ast::Identifier*>(expr);\n test_assert(id != NULL);\n test_assert(id->text == \"gouda\");\n test_assert(!id->hasRebindOperator);\n\n delete expr;\n\n Branch branch;\n Term* a = int_var(branch, 2, \"a\");\n Term* b = int_var(branch, 5, \"b\");\n\n test_assert(branch.getNamed(\"a\") == a);\n test_assert(branch.getNamed(\"b\") == b);\n\n Term* result = apply_statement(branch, \"add(@a, b)\");\n\n test_assert(branch.getNamed(\"a\") == result);\n test_assert(branch.getNamed(\"b\") == b);\n}\n\nvoid ast_walk()\n{\n token_stream::TokenStream tokens(\"concat(to-string(add(1,2.0)), \\\"cheese\\\")\");\n ast::Expression* expr = parser::infixExpression(tokens);\n\n std::vector<std::string> expected;\n expected.push_back(\"concat(to-string(add(1,2.0)), \\\"cheese\\\")\");\n expected.push_back(\"to-string(add(1,2.0))\");\n expected.push_back(\"add(1,2.0)\");\n expected.push_back(\"1\");\n expected.push_back(\"2.0\");\n expected.push_back(\"\\\"cheese\\\"\");\n\n struct MyWalker : public ast::ExpressionWalker\n {\n std::vector<std::string> found;\n\n virtual void visit(ast::Expression* expr)\n {\n found.push_back(expr->toString());\n }\n } walker;\n\n expr->walk(walker);\n\n for (int i=0; i < (int) expected.size(); i++) {\n test_assert(expected[i] == walker.found[i]);\n }\n\n delete expr;\n}\n\nvoid test_eval_statement()\n{\n Branch b;\n\n test_assert(eval_statement(b, \"5\")->asInt() == 5);\n test_assert(eval_statement(b, \"-2\")->asInt() == -2);\n test_assert(eval_statement(b, \"1.0\")->asFloat() == 1.0);\n \/\/test_assert(eval_statement(b, \"-.123\")->asFloat() == -0.123);FIXME\n test_assert(eval_statement(b, \"\\\"apple\\\"\")->asString() == \"apple\");\n test_assert(eval_statement(b, \"\\\"\\\"\")->asString() == \"\");\n}\n\nvoid comment_statement()\n{\n token_stream::TokenStream tokens(\"-- this is a comment\");\n\n ast::Statement* statement = parser::statement(tokens);\n test_assert(dynamic_cast<ast::IgnorableStatement*>(statement) != NULL);\n\n test_assert(tokens.finished());\n}\n\nvoid test_type_decl()\n{\n token_stream::TokenStream tokens(\"type Vector {\\nfloat x\\nint y\\n}\");\n\n ast::TypeDecl* typeDecl = parser::typeDecl(tokens);\n test_assert(typeDecl != NULL);\n test_assert(typeDecl->name == \"Vector\");\n test_assert(typeDecl->members[0].type == \"float\");\n test_assert(typeDecl->members[0].name == \"x\");\n test_assert(typeDecl->members[1].type == \"int\");\n test_assert(typeDecl->members[1].name == \"y\");\n}\n\nvoid test_type_decl_statement()\n{\n token_stream::TokenStream tokens(\"type Mytype\\n{\\nstring str\\nfloat asdf\\n}\");\n ast::Statement* statement = parser::statement(tokens);\n\n test_assert(dynamic_cast<ast::TypeDecl*>(statement) != NULL);\n}\n\nvoid test_type_decl_full_trip()\n{\n Branch branch;\n Term *t = eval_statement(branch, \"type Mytype\\n{\\nstring s\\nfloat a\\n}\");\n\n test_assert(!t->hasError());\n\n test_assert(t->name == \"Mytype\");\n test_assert(as_type(t).fields[0].type == STRING_TYPE);\n test_assert(as_type(t).fields[0].name == \"s\");\n test_assert(as_type(t).fields[1].type == FLOAT_TYPE);\n test_assert(as_type(t).fields[1].name == \"a\");\n}\n\nvoid test_parse_if_block()\n{\n token_stream::TokenStream tokens(\n \"if (x > 2) \\n print('yes') \\n else \\n print('no') \\n end\");\n\n ast::IfStatement* ifStatement = parser::ifStatement(tokens);\n\n test_assert(ifStatement != NULL);\n\n \/\/ these lines will need to be fixed when there is better whitespace preservation\n test_assert(ifStatement->condition->toString() == \"x>2\");\n test_assert(ifStatement->positiveBranch->toString() == \"print(\\\"yes\\\")\\n\");\n test_assert(ifStatement->negativeBranch->toString() == \"print(\\\"no\\\")\\n\");\n\n delete ifStatement;\n\n tokens.reset(\"if (false) \\n print('blah') \\n end\");\n\n ifStatement = parser::ifStatement(tokens);\n\n test_assert(ifStatement->condition->toString() == \"false\");\n test_assert(ifStatement->positiveBranch->toString() == \"print(\\\"blah\\\")\\n\");\n test_assert(ifStatement->negativeBranch == NULL);\n\n delete ifStatement;\n}\n\n} \/\/ namespace parser_tests\n\nvoid register_parser_tests()\n{\n REGISTER_TEST_CASE(parser_tests::literal_float);\n REGISTER_TEST_CASE(parser_tests::literal_string);\n REGISTER_TEST_CASE(parser_tests::function_call);\n REGISTER_TEST_CASE(parser_tests::name_binding_expression);\n REGISTER_TEST_CASE(parser_tests::test_to_string);\n REGISTER_TEST_CASE(parser_tests::create_literals);\n REGISTER_TEST_CASE(parser_tests::create_function_call);\n REGISTER_TEST_CASE(parser_tests::test_apply_statement);\n REGISTER_TEST_CASE(parser_tests::function_decl_ast);\n REGISTER_TEST_CASE(parser_tests::function_header);\n REGISTER_TEST_CASE(parser_tests::function_decl_parse);\n REGISTER_TEST_CASE(parser_tests::rebind_operator);\n REGISTER_TEST_CASE(parser_tests::ast_walk);\n REGISTER_TEST_CASE(parser_tests::test_eval_statement);\n REGISTER_TEST_CASE(parser_tests::comment_statement);\n REGISTER_TEST_CASE(parser_tests::test_type_decl);\n REGISTER_TEST_CASE(parser_tests::test_type_decl_statement);\n REGISTER_TEST_CASE(parser_tests::test_type_decl_full_trip);\n REGISTER_TEST_CASE(parser_tests::test_parse_if_block);\n}\n\n} \/\/ namespace circa\n<|endoftext|>"} {"text":"<commit_before>\/*! @file selector.cc\n * @brief Select the specified part of input.\n * @author Markovtsev Vadim <v.markovtsev@samsung.com>\n * @version 1.0\n *\n * @section Notes\n * This code partially conforms to <a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml\">Google C++ Style Guide<\/a>.\n *\n * @section Copyright\n * Copyright 2013 Samsung R&D Institute Russia\n *\/\n\n#include \"src\/transforms\/selector.h\"\n#include <string>\n\nnamespace SpeechFeatureExtraction {\nnamespace Transforms {\n\nSelector::Selector()\n : UniformFormatTransform(SupportedParameters()),\n length_(12),\n from_(ANCHOR_RIGHT) {\n}\n\nvoid Selector::SetParameter(const std::string& name,\n const std::string& value) {\n if (name == \"length\") {\n int length = Parse<int>(name, value);\n if (length < 1) {\n throw InvalidParameterValueException(name, value, Name());\n }\n length_ = length;\n } else if (name == \"from\") {\n if (value == \"left\") {\n from_ = ANCHOR_LEFT;\n } else if (value == \"right\") {\n from_ = ANCHOR_RIGHT;\n } else {\n throw InvalidParameterValueException(name, value, Name());\n }\n }\n}\n\nvoid Selector::OnFormatChanged() {\n outputFormat_->SetSize(\n std::min(length_, static_cast<int>(inputFormat_->Size())));\n}\n\nvoid Selector::TypeSafeInitializeBuffers(\n const BuffersBase<Formats::WindowF>& in,\n BuffersBase<Formats::WindowF>* buffers) const noexcept {\n buffers->Initialize(in.Size(), outputFormat_->Size());\n}\n\nvoid Selector::TypeSafeDo(\n const BuffersBase<Formats::WindowF>& in,\n BuffersBase<Formats::WindowF> *out) const noexcept {\n for (size_t i = 0; i < in.Size(); i++) {\n auto input = in[i]->Data.get();\n auto output = (*out)[i]->Data.get();\n if (input != output) {\n memcpy(output,\n input +\n (from_ == ANCHOR_LEFT? 0 : inputFormat_->Size() - length_),\n length_ * sizeof(input[0]));\n } else {\n memmove(output,\n input +\n (from_ == ANCHOR_LEFT? 0 : inputFormat_->Size() - length_),\n length_ * sizeof(input[0]));\n }\n }\n}\n\nREGISTER_TRANSFORM(Selector);\n\n} \/\/ namespace Transforms\n} \/\/ namespace SpeechFeatureExtraction\n<commit_msg>Fixed a bug in Selector<commit_after>\/*! @file selector.cc\n * @brief Select the specified part of input.\n * @author Markovtsev Vadim <v.markovtsev@samsung.com>\n * @version 1.0\n *\n * @section Notes\n * This code partially conforms to <a href=\"http:\/\/google-styleguide.googlecode.com\/svn\/trunk\/cppguide.xml\">Google C++ Style Guide<\/a>.\n *\n * @section Copyright\n * Copyright 2013 Samsung R&D Institute Russia\n *\/\n\n#include \"src\/transforms\/selector.h\"\n#include <string>\n\nnamespace SpeechFeatureExtraction {\nnamespace Transforms {\n\nSelector::Selector()\n : UniformFormatTransform(SupportedParameters()),\n length_(12),\n from_(ANCHOR_RIGHT) {\n}\n\nvoid Selector::SetParameter(const std::string& name,\n const std::string& value) {\n if (name == \"length\") {\n int length = Parse<int>(name, value);\n if (length < 1) {\n throw InvalidParameterValueException(name, value, Name());\n }\n length_ = length;\n } else if (name == \"from\") {\n if (value == \"left\") {\n from_ = ANCHOR_LEFT;\n } else if (value == \"right\") {\n from_ = ANCHOR_RIGHT;\n } else {\n throw InvalidParameterValueException(name, value, Name());\n }\n }\n}\n\nvoid Selector::OnFormatChanged() {\n outputFormat_->SetSize(\n std::min(length_, static_cast<int>(inputFormat_->Size())));\n}\n\nvoid Selector::TypeSafeInitializeBuffers(\n const BuffersBase<Formats::WindowF>& in,\n BuffersBase<Formats::WindowF>* buffers) const noexcept {\n buffers->Initialize(in.Size(), outputFormat_->Size());\n}\n\nvoid Selector::TypeSafeDo(\n const BuffersBase<Formats::WindowF>& in,\n BuffersBase<Formats::WindowF> *out) const noexcept {\n int length = outputFormat_->Size();\n for (size_t i = 0; i < in.Size(); i++) {\n auto input = in[i]->Data.get();\n auto output = (*out)[i]->Data.get();\n if (input != output) {\n memcpy(output,\n input + (from_ == ANCHOR_LEFT? 0 : inputFormat_->Size() - length),\n length * sizeof(input[0]));\n } else {\n memmove(output,\n input + (from_ == ANCHOR_LEFT? 0 : inputFormat_->Size() - length),\n length * sizeof(input[0]));\n }\n }\n}\n\nREGISTER_TRANSFORM(Selector);\n\n} \/\/ namespace Transforms\n} \/\/ namespace SpeechFeatureExtraction\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.\n\n#include \"persistencemessagetracker.h\"\n#include <vespa\/storage\/common\/vectorprinter.h>\n#include <vespa\/storageapi\/message\/persistence.h>\n#include \"distributor_bucket_space_repo.h\"\n#include \"distributor_bucket_space.h\"\n\n#include <vespa\/log\/log.h>\n\nLOG_SETUP(\".persistencemessagetracker\");\n\nnamespace storage::distributor {\n\nPersistenceMessageTrackerImpl::PersistenceMessageTrackerImpl(\n PersistenceOperationMetricSet& metric,\n std::shared_ptr<api::BucketInfoReply> reply,\n DistributorNodeContext& node_ctx,\n DistributorOperationContext& op_ctx,\n api::Timestamp revertTimestamp)\n : MessageTracker(node_ctx.cluster_name()),\n _metric(metric),\n _reply(std::move(reply)),\n _op_ctx(op_ctx),\n _revertTimestamp(revertTimestamp),\n _trace(_reply->getTrace().getLevel()),\n _requestTimer(node_ctx.clock()),\n _n_persistence_replies_total(0),\n _n_successful_persistence_replies(0),\n _priority(_reply->getPriority()),\n _success(true)\n{\n}\n\nPersistenceMessageTrackerImpl::~PersistenceMessageTrackerImpl() = default;\n\nvoid\nPersistenceMessageTrackerImpl::updateDB()\n{\n for (const auto & entry : _bucketInfo) {\n _op_ctx.update_bucket_database(entry.first, entry.second);\n }\n\n for (const auto & entry : _remapBucketInfo){\n _op_ctx.update_bucket_database(entry.first, entry.second, DatabaseUpdate::CREATE_IF_NONEXISTING);\n }\n}\n\nvoid\nPersistenceMessageTrackerImpl::updateMetrics()\n{\n const api::ReturnCode& result(_reply->getResult());\n _metric.updateFromResult(result);\n _metric.latency.addValue(_requestTimer.getElapsedTimeAsDouble());\n}\n\nvoid\nPersistenceMessageTrackerImpl::fail(MessageSender& sender, const api::ReturnCode& result) {\n if (_reply.get()) {\n _reply->setResult(result);\n updateMetrics();\n sender.sendReply(_reply);\n _reply.reset();\n }\n}\n\nuint16_t\nPersistenceMessageTrackerImpl::receiveReply(\n MessageSender& sender,\n api::BucketInfoReply& reply)\n{\n uint16_t node = handleReply(reply);\n\n if (node != (uint16_t)-1) {\n updateFromReply(sender, reply, node);\n }\n\n return node;\n}\n\nvoid\nPersistenceMessageTrackerImpl::revert(\n MessageSender& sender,\n const std::vector<BucketNodePair>& revertNodes)\n{\n if (_revertTimestamp != 0) {\n \/\/ Since we're reverting, all received bucket info is voided.\n _bucketInfo.clear();\n\n std::vector<api::Timestamp> reverts;\n reverts.push_back(_revertTimestamp);\n\n for (const auto & revertNode : revertNodes) {\n auto toRevert = std::make_shared<api::RevertCommand>(revertNode.first, reverts);\n toRevert->setPriority(_priority);\n queueCommand(std::move(toRevert), revertNode.second);\n }\n\n flushQueue(sender);\n }\n}\n\nvoid\nPersistenceMessageTrackerImpl::queueMessageBatch(const std::vector<MessageTracker::ToSend>& messages) {\n _messageBatches.emplace_back();\n for (const auto & message : messages) {\n if (_reply) {\n message._msg->getTrace().setLevel(_reply->getTrace().getLevel());\n }\n\n _messageBatches.back().push_back(message._msg->getMsgId());\n queueCommand(message._msg, message._target);\n }\n}\n\nbool\nPersistenceMessageTrackerImpl::canSendReplyEarly() const\n{\n if (!_reply.get() || !_reply->getResult().success()) {\n LOG(spam, \"Can't return early because we have already replied or failed\");\n return false;\n }\n auto &bucketSpaceRepo(_op_ctx.bucket_space_repo());\n auto &bucketSpace(bucketSpaceRepo.get(_reply->getBucket().getBucketSpace()));\n const lib::Distribution& distribution = bucketSpace.getDistribution();\n\n if (distribution.getInitialRedundancy() == 0) {\n LOG(spam, \"Not returning early because initial redundancy wasn't set\");\n return false;\n }\n\n for (const MessageBatch & batch : _messageBatches) {\n uint32_t messagesDone = 0;\n\n for (uint32_t i = 0; i < batch.size(); i++) {\n if (_sentMessages.find(batch[i]) == _sentMessages.end()) {\n messagesDone++;\n } else if (distribution.ensurePrimaryPersisted() && i == 0) {\n \/\/ Primary must always be written.\n LOG(debug, \"Not returning early because primary node wasn't done\");\n return false;\n }\n }\n\n if (messagesDone < distribution.getInitialRedundancy()) {\n LOG(spam, \"Not returning early because only %d messages out of %d are done\",\n messagesDone, distribution.getInitialRedundancy());\n return false;\n }\n }\n\n return true;\n}\n\nvoid\nPersistenceMessageTrackerImpl::addBucketInfoFromReply(\n uint16_t node,\n const api::BucketInfoReply& reply)\n{\n document::Bucket bucket(reply.getBucket());\n const api::BucketInfo& bucketInfo(reply.getBucketInfo());\n\n if (reply.hasBeenRemapped()) {\n LOG(debug, \"Bucket %s: Received remapped bucket info %s from node %d\",\n bucket.toString().c_str(),\n bucketInfo.toString().c_str(),\n node);\n _remapBucketInfo[bucket].emplace_back(_op_ctx.generate_unique_timestamp(), node, bucketInfo);\n } else {\n LOG(debug, \"Bucket %s: Received bucket info %s from node %d\",\n bucket.toString().c_str(),\n bucketInfo.toString().c_str(),\n node);\n _bucketInfo[bucket].emplace_back(_op_ctx.generate_unique_timestamp(), node, bucketInfo);\n }\n}\n\nvoid\nPersistenceMessageTrackerImpl::logSuccessfulReply(uint16_t node, const api::BucketInfoReply& reply) const\n{\n LOG(spam, \"Bucket %s: Received successful reply %s\",\n reply.getBucketId().toString().c_str(),\n reply.toString().c_str());\n \n if (!reply.getBucketInfo().valid()) {\n LOG(error,\n \"Reply %s from node %d contained invalid bucket \"\n \"information %s. This is a bug! Please report \"\n \"this to the Vespa team\",\n reply.toString().c_str(),\n node,\n reply.getBucketInfo().toString().c_str());\n }\n}\n\nbool\nPersistenceMessageTrackerImpl::shouldRevert() const\n{\n return _op_ctx.distributor_config().enable_revert()\n && !_revertNodes.empty() && !_success && _reply;\n}\n\nbool PersistenceMessageTrackerImpl::has_majority_successful_replies() const noexcept {\n \/\/ FIXME this has questionable interaction with early client ACK since we only count\n \/\/ the number of observed replies rather than the number of total requests sent.\n \/\/ ... but the early ACK-feature dearly needs a redesign anyway.\n return (_n_successful_persistence_replies >= (_n_persistence_replies_total \/ 2 + 1));\n}\n\nbool PersistenceMessageTrackerImpl::has_minority_test_and_set_failure() const noexcept {\n return ((_reply->getResult().getResult() == api::ReturnCode::TEST_AND_SET_CONDITION_FAILED)\n && has_majority_successful_replies());\n}\n\nvoid\nPersistenceMessageTrackerImpl::sendReply(MessageSender& sender)\n{\n \/\/ If we've observed _partial_ TaS failures but have had a majority of good ACKs,\n \/\/ treat the reply as successful. This is because the ACKed write(s) will eventually\n \/\/ become visible across all nodes.\n if (has_minority_test_and_set_failure()) {\n _reply->setResult(api::ReturnCode());\n }\n\n updateMetrics();\n _trace.setStrict(false);\n if ( ! _trace.isEmpty()) {\n _reply->getTrace().addChild(std::move(_trace));\n }\n \n sender.sendReply(_reply);\n _reply = std::shared_ptr<api::BucketInfoReply>();\n}\n\nvoid\nPersistenceMessageTrackerImpl::updateFailureResult(const api::BucketInfoReply& reply)\n{\n LOG(debug, \"Bucket %s: Received failed reply %s with result %s\",\n reply.getBucketId().toString().c_str(),\n reply.toString().c_str(),\n reply.getResult().toString().c_str());\n if (reply.getResult().getResult() >\n _reply->getResult().getResult())\n {\n _reply->setResult(reply.getResult());\n }\n \n _success = false;\n}\n\nvoid\nPersistenceMessageTrackerImpl::handleCreateBucketReply(\n api::BucketInfoReply& reply,\n uint16_t node)\n{\n LOG(spam, \"Received CreateBucket reply for %s from node %u\",\n reply.getBucketId().toString().c_str(), node);\n if (!reply.getResult().success()\n && reply.getResult().getResult() != api::ReturnCode::EXISTS)\n {\n LOG(spam, \"Create bucket reply failed, so deleting it from bucket db\");\n _op_ctx.remove_node_from_bucket_database(reply.getBucket(), node);\n }\n}\n\nvoid\nPersistenceMessageTrackerImpl::handlePersistenceReply(\n api::BucketInfoReply& reply,\n uint16_t node)\n{\n ++_n_persistence_replies_total;\n if (reply.getBucketInfo().valid()) {\n addBucketInfoFromReply(node, reply);\n }\n if (reply.getResult().success()) {\n logSuccessfulReply(node, reply);\n _revertNodes.emplace_back(reply.getBucket(), node);\n ++_n_successful_persistence_replies;\n } else if (!hasSentReply()) {\n updateFailureResult(reply);\n }\n}\n\nvoid\nPersistenceMessageTrackerImpl::updateFromReply(\n MessageSender& sender,\n api::BucketInfoReply& reply,\n uint16_t node)\n{\n _trace.addChild(reply.steal_trace());\n\n if (reply.getType() == api::MessageType::CREATEBUCKET_REPLY) {\n handleCreateBucketReply(reply, node);\n } else {\n handlePersistenceReply(reply, node);\n }\n\n if (finished()) {\n bool doRevert(shouldRevert());\n\n updateDB();\n\n if (!hasSentReply()) {\n sendReply(sender);\n }\n if (doRevert) {\n revert(sender, _revertNodes);\n }\n } else if (canSendReplyEarly()) {\n LOG(debug, \"Sending reply early because initial redundancy has been reached\");\n sendReply(sender);\n }\n}\n\n}\n<commit_msg>Avoid constructing a TraceNode (via ensureRoot) when tracing is disabled.<commit_after>\/\/ Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.\n\n#include \"persistencemessagetracker.h\"\n#include <vespa\/storage\/common\/vectorprinter.h>\n#include <vespa\/storageapi\/message\/persistence.h>\n#include \"distributor_bucket_space_repo.h\"\n#include \"distributor_bucket_space.h\"\n\n#include <vespa\/log\/log.h>\n\nLOG_SETUP(\".persistencemessagetracker\");\n\nnamespace storage::distributor {\n\nPersistenceMessageTrackerImpl::PersistenceMessageTrackerImpl(\n PersistenceOperationMetricSet& metric,\n std::shared_ptr<api::BucketInfoReply> reply,\n DistributorNodeContext& node_ctx,\n DistributorOperationContext& op_ctx,\n api::Timestamp revertTimestamp)\n : MessageTracker(node_ctx.cluster_name()),\n _metric(metric),\n _reply(std::move(reply)),\n _op_ctx(op_ctx),\n _revertTimestamp(revertTimestamp),\n _trace(_reply->getTrace().getLevel()),\n _requestTimer(node_ctx.clock()),\n _n_persistence_replies_total(0),\n _n_successful_persistence_replies(0),\n _priority(_reply->getPriority()),\n _success(true)\n{\n}\n\nPersistenceMessageTrackerImpl::~PersistenceMessageTrackerImpl() = default;\n\nvoid\nPersistenceMessageTrackerImpl::updateDB()\n{\n for (const auto & entry : _bucketInfo) {\n _op_ctx.update_bucket_database(entry.first, entry.second);\n }\n\n for (const auto & entry : _remapBucketInfo){\n _op_ctx.update_bucket_database(entry.first, entry.second, DatabaseUpdate::CREATE_IF_NONEXISTING);\n }\n}\n\nvoid\nPersistenceMessageTrackerImpl::updateMetrics()\n{\n const api::ReturnCode& result(_reply->getResult());\n _metric.updateFromResult(result);\n _metric.latency.addValue(_requestTimer.getElapsedTimeAsDouble());\n}\n\nvoid\nPersistenceMessageTrackerImpl::fail(MessageSender& sender, const api::ReturnCode& result) {\n if (_reply.get()) {\n _reply->setResult(result);\n updateMetrics();\n sender.sendReply(_reply);\n _reply.reset();\n }\n}\n\nuint16_t\nPersistenceMessageTrackerImpl::receiveReply(\n MessageSender& sender,\n api::BucketInfoReply& reply)\n{\n uint16_t node = handleReply(reply);\n\n if (node != (uint16_t)-1) {\n updateFromReply(sender, reply, node);\n }\n\n return node;\n}\n\nvoid\nPersistenceMessageTrackerImpl::revert(\n MessageSender& sender,\n const std::vector<BucketNodePair>& revertNodes)\n{\n if (_revertTimestamp != 0) {\n \/\/ Since we're reverting, all received bucket info is voided.\n _bucketInfo.clear();\n\n std::vector<api::Timestamp> reverts;\n reverts.push_back(_revertTimestamp);\n\n for (const auto & revertNode : revertNodes) {\n auto toRevert = std::make_shared<api::RevertCommand>(revertNode.first, reverts);\n toRevert->setPriority(_priority);\n queueCommand(std::move(toRevert), revertNode.second);\n }\n\n flushQueue(sender);\n }\n}\n\nvoid\nPersistenceMessageTrackerImpl::queueMessageBatch(const std::vector<MessageTracker::ToSend>& messages) {\n _messageBatches.emplace_back();\n for (const auto & message : messages) {\n if (_reply) {\n message._msg->getTrace().setLevel(_reply->getTrace().getLevel());\n }\n\n _messageBatches.back().push_back(message._msg->getMsgId());\n queueCommand(message._msg, message._target);\n }\n}\n\nbool\nPersistenceMessageTrackerImpl::canSendReplyEarly() const\n{\n if (!_reply.get() || !_reply->getResult().success()) {\n LOG(spam, \"Can't return early because we have already replied or failed\");\n return false;\n }\n auto &bucketSpaceRepo(_op_ctx.bucket_space_repo());\n auto &bucketSpace(bucketSpaceRepo.get(_reply->getBucket().getBucketSpace()));\n const lib::Distribution& distribution = bucketSpace.getDistribution();\n\n if (distribution.getInitialRedundancy() == 0) {\n LOG(spam, \"Not returning early because initial redundancy wasn't set\");\n return false;\n }\n\n for (const MessageBatch & batch : _messageBatches) {\n uint32_t messagesDone = 0;\n\n for (uint32_t i = 0; i < batch.size(); i++) {\n if (_sentMessages.find(batch[i]) == _sentMessages.end()) {\n messagesDone++;\n } else if (distribution.ensurePrimaryPersisted() && i == 0) {\n \/\/ Primary must always be written.\n LOG(debug, \"Not returning early because primary node wasn't done\");\n return false;\n }\n }\n\n if (messagesDone < distribution.getInitialRedundancy()) {\n LOG(spam, \"Not returning early because only %d messages out of %d are done\",\n messagesDone, distribution.getInitialRedundancy());\n return false;\n }\n }\n\n return true;\n}\n\nvoid\nPersistenceMessageTrackerImpl::addBucketInfoFromReply(\n uint16_t node,\n const api::BucketInfoReply& reply)\n{\n document::Bucket bucket(reply.getBucket());\n const api::BucketInfo& bucketInfo(reply.getBucketInfo());\n\n if (reply.hasBeenRemapped()) {\n LOG(debug, \"Bucket %s: Received remapped bucket info %s from node %d\",\n bucket.toString().c_str(),\n bucketInfo.toString().c_str(),\n node);\n _remapBucketInfo[bucket].emplace_back(_op_ctx.generate_unique_timestamp(), node, bucketInfo);\n } else {\n LOG(debug, \"Bucket %s: Received bucket info %s from node %d\",\n bucket.toString().c_str(),\n bucketInfo.toString().c_str(),\n node);\n _bucketInfo[bucket].emplace_back(_op_ctx.generate_unique_timestamp(), node, bucketInfo);\n }\n}\n\nvoid\nPersistenceMessageTrackerImpl::logSuccessfulReply(uint16_t node, const api::BucketInfoReply& reply) const\n{\n LOG(spam, \"Bucket %s: Received successful reply %s\",\n reply.getBucketId().toString().c_str(),\n reply.toString().c_str());\n \n if (!reply.getBucketInfo().valid()) {\n LOG(error,\n \"Reply %s from node %d contained invalid bucket \"\n \"information %s. This is a bug! Please report \"\n \"this to the Vespa team\",\n reply.toString().c_str(),\n node,\n reply.getBucketInfo().toString().c_str());\n }\n}\n\nbool\nPersistenceMessageTrackerImpl::shouldRevert() const\n{\n return _op_ctx.distributor_config().enable_revert()\n && !_revertNodes.empty() && !_success && _reply;\n}\n\nbool PersistenceMessageTrackerImpl::has_majority_successful_replies() const noexcept {\n \/\/ FIXME this has questionable interaction with early client ACK since we only count\n \/\/ the number of observed replies rather than the number of total requests sent.\n \/\/ ... but the early ACK-feature dearly needs a redesign anyway.\n return (_n_successful_persistence_replies >= (_n_persistence_replies_total \/ 2 + 1));\n}\n\nbool PersistenceMessageTrackerImpl::has_minority_test_and_set_failure() const noexcept {\n return ((_reply->getResult().getResult() == api::ReturnCode::TEST_AND_SET_CONDITION_FAILED)\n && has_majority_successful_replies());\n}\n\nvoid\nPersistenceMessageTrackerImpl::sendReply(MessageSender& sender)\n{\n \/\/ If we've observed _partial_ TaS failures but have had a majority of good ACKs,\n \/\/ treat the reply as successful. This is because the ACKed write(s) will eventually\n \/\/ become visible across all nodes.\n if (has_minority_test_and_set_failure()) {\n _reply->setResult(api::ReturnCode());\n }\n\n updateMetrics();\n if ( ! _trace.isEmpty()) {\n _trace.setStrict(false);\n _reply->getTrace().addChild(std::move(_trace));\n }\n \n sender.sendReply(_reply);\n _reply = std::shared_ptr<api::BucketInfoReply>();\n}\n\nvoid\nPersistenceMessageTrackerImpl::updateFailureResult(const api::BucketInfoReply& reply)\n{\n LOG(debug, \"Bucket %s: Received failed reply %s with result %s\",\n reply.getBucketId().toString().c_str(),\n reply.toString().c_str(),\n reply.getResult().toString().c_str());\n if (reply.getResult().getResult() >\n _reply->getResult().getResult())\n {\n _reply->setResult(reply.getResult());\n }\n \n _success = false;\n}\n\nvoid\nPersistenceMessageTrackerImpl::handleCreateBucketReply(\n api::BucketInfoReply& reply,\n uint16_t node)\n{\n LOG(spam, \"Received CreateBucket reply for %s from node %u\",\n reply.getBucketId().toString().c_str(), node);\n if (!reply.getResult().success()\n && reply.getResult().getResult() != api::ReturnCode::EXISTS)\n {\n LOG(spam, \"Create bucket reply failed, so deleting it from bucket db\");\n _op_ctx.remove_node_from_bucket_database(reply.getBucket(), node);\n }\n}\n\nvoid\nPersistenceMessageTrackerImpl::handlePersistenceReply(\n api::BucketInfoReply& reply,\n uint16_t node)\n{\n ++_n_persistence_replies_total;\n if (reply.getBucketInfo().valid()) {\n addBucketInfoFromReply(node, reply);\n }\n if (reply.getResult().success()) {\n logSuccessfulReply(node, reply);\n _revertNodes.emplace_back(reply.getBucket(), node);\n ++_n_successful_persistence_replies;\n } else if (!hasSentReply()) {\n updateFailureResult(reply);\n }\n}\n\nvoid\nPersistenceMessageTrackerImpl::updateFromReply(\n MessageSender& sender,\n api::BucketInfoReply& reply,\n uint16_t node)\n{\n _trace.addChild(reply.steal_trace());\n\n if (reply.getType() == api::MessageType::CREATEBUCKET_REPLY) {\n handleCreateBucketReply(reply, node);\n } else {\n handlePersistenceReply(reply, node);\n }\n\n if (finished()) {\n bool doRevert(shouldRevert());\n\n updateDB();\n\n if (!hasSentReply()) {\n sendReply(sender);\n }\n if (doRevert) {\n revert(sender, _revertNodes);\n }\n } else if (canSendReplyEarly()) {\n LOG(debug, \"Sending reply early because initial redundancy has been reached\");\n sendReply(sender);\n }\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/* IBM_PROLOG_BEGIN_TAG *\/\n\/* This is an automatically generated prolog. *\/\n\/* *\/\n\/* $Source: src\/usr\/pnor\/pnoraltsync.C $ *\/\n\/* *\/\n\/* OpenPOWER HostBoot Project *\/\n\/* *\/\n\/* Contributors Listed Below - COPYRIGHT 2021 *\/\n\/* [+] International Business Machines Corp. *\/\n\/* *\/\n\/* *\/\n\/* Licensed under the Apache License, Version 2.0 (the \"License\"); *\/\n\/* you may not use this file except in compliance with the License. *\/\n\/* You may obtain a copy of the License at *\/\n\/* *\/\n\/* http:\/\/www.apache.org\/licenses\/LICENSE-2.0 *\/\n\/* *\/\n\/* Unless required by applicable law or agreed to in writing, software *\/\n\/* distributed under the License is distributed on an \"AS IS\" BASIS, *\/\n\/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or *\/\n\/* implied. See the License for the specific language governing *\/\n\/* permissions and limitations under the License. *\/\n\/* *\/\n\/* IBM_PROLOG_END_TAG *\/\n\/**\n * @file pnoraltsync.C\n *\n * @brief Implements PNOR::copyPnorPartitionToAlt() to synchronize\n * partitions between the active and alternate PNORs\n *\/\n\n\/*****************************************************************************\/\n\/\/ I n c l u d e s\n\/*****************************************************************************\/\n#include <trace\/interface.H>\n#include <devicefw\/driverif.H>\n#include <errl\/errlentry.H>\n#include <errl\/errlmanager.H>\n#include <targeting\/common\/targetservice.H>\n#include <targeting\/common\/utilFilter.H>\n#include <attributeenums.H>\n#include \"ffs.h\"\n#include \"common\/ffs_hb.H\"\n#include \"pnorrp.H\"\n#include <pnor\/pnorif.H>\n#include <pnor\/pnor_reasoncodes.H>\n#include <lpc\/lpcif.H>\n\n#if defined(CONFIG_PNORDD_IS_SFC)\n#include \"pnor_sfcdd.H\"\nusing PnorDD = PnorSfcDD;\n#elif (defined(CONFIG_PNORDD_IS_BMCMBOX) || defined(CONFIG_PNORDD_IS_IPMI))\n#include \"pnor_hiomapdd.H\"\nusing PnorDD = PnorHiomapDD;\n#else\n#error \"No PNOR DD configured\"\n#endif\n\nextern trace_desc_t* g_trac_pnor;\n\nnamespace PNOR\n{\n\n\/**\n * @brief Copy a given PNOR partition from the active PNOR into the\n * alternate copy\n *\/\nerrlHndl_t copyPnorPartitionToAlt( PNOR::SectionId i_section )\n{\n errlHndl_t l_errhdl = nullptr;\n const char* l_sectionName = PNOR::SectionIdToString(i_section);\n TRACFCOMP( g_trac_pnor, ENTER_MRK\"PNOR::copyPnorPartitionToAlt(%d=%s)> \",\n i_section, l_sectionName );\n\n \/\/ Algorithm is:\n \/\/ 0. Check if there is an alt-pnor to update, exit if not\n \/\/ 1. Instantiate an alt-pnordd to access the alternate PNOR.\n \/\/ 2. Find the flash offset and full size (including ECC) of the\n \/\/ target section on the active PNOR.\n \/\/ 3. Find the flash offset and full size (including ECC) of the\n \/\/ target section on the alternate PNOR.\n \/\/ 4. If size+offset match, bulk copy the complete section from\n \/\/ the active PNOR to the alternate.\n\n PnorDD* altpnordd = nullptr;\n\n \/\/ When reading PNOR TOC assume a single page and no ECC\n uint8_t* tocBuffer = new uint8_t[PAGESIZE];\n const uint64_t toc0_offset = PnorRP::getInstance().getTocOffset(TOC_0);\n\n do{\n \/\/--------------------------------\n \/\/ 0. Check if there is an alt-pnor to update, exit if not\n\n \/\/ Get list of all processors\n TARGETING::TargetHandleList procList;\n TARGETING::getAllChips(procList,\n TARGETING::TYPE_PROC,\n true); \/\/ true: return functional targets\n\n if( ( 0 == procList.size() ) ||\n ( nullptr == procList[0] ) )\n {\n TRACFCOMP( g_trac_pnor, INFO_MRK\"PNOR::copyPnorPartitionToAlt()> No functional processors Found! Validation skipped\" );\n break;\n }\n\n \/\/ Loop through all processors to find the alt-proc\n TARGETING::Target* l_altProc = nullptr;\n for(uint32_t i=0; i<procList.size(); i++)\n {\n \/\/ Check if processor is MASTER_CANDIDATE\n TARGETING::ATTR_PROC_MASTER_TYPE_type type_enum =\n procList[i]->getAttr<TARGETING::ATTR_PROC_MASTER_TYPE>();\n\n if ( type_enum != TARGETING::PROC_MASTER_TYPE_MASTER_CANDIDATE )\n {\n TRACDCOMP( g_trac_pnor, INFO_MRK\"PNOR::copyPnorPartitionToAlt> Skipping Processor 0x%X (PROC_MASTER_TYPE=%d)\",\n TARGETING::get_huid(procList[i]), type_enum);\n continue;\n }\n\n TRACFCOMP( g_trac_pnor, INFO_MRK\"PNOR::copyPnorPartitionToAlt> Validating Processor 0x%X (PROC_MASTER_TYPE=%d)\",\n TARGETING::get_huid(procList[i]), type_enum);\n l_altProc = procList[i];\n break;\n }\n if( !l_altProc )\n {\n TRACFCOMP( g_trac_pnor, INFO_MRK\"PNOR::copyPnorPartitionToAlt> There are no alternate PNORs to update\" );\n break;\n }\n\n\n \/\/--------------------------------\n \/\/ 1. Instantiate an alt-pnordd to access the alternate PNOR.\n\n \/\/ Create the LPC objects we're going to use\n l_errhdl = LPC::create_altmaster_objects( true, l_altProc );\n if ( l_errhdl )\n {\n \/\/ Commit Error Log, but continue the test\n TRACFCOMP( g_trac_pnor, INFO_MRK\"PNOR::copyPnorPartitionToAlt> Could not create LPC objects for %.8X.\", TARGETING::get_huid(l_altProc) );\n break;\n }\n\n \/\/ Create and initialize custom PNOR DD class for this target\n altpnordd = new PnorDD(l_altProc);\n\n\n \/\/--------------------------------\n \/\/ 2. Find the flash offset and full size (including ECC) of the\n \/\/ target section on the active PNOR.\n\n PNOR::SectionInfo_t l_activePnor;\n l_errhdl = PNOR::getSectionInfo(i_section, l_activePnor);\n if( l_errhdl )\n {\n TRACFCOMP( g_trac_pnor, INFO_MRK\"PNOR::copyPnorPartitionToAlt> Error getting data for section %d(%s)\", i_section, l_sectionName );\n break;\n }\n TRACFCOMP( g_trac_pnor, INFO_MRK\"PNOR::copyPnorPartitionToAlt> Section %d(%s) located at 0x%.X for 0x%X bytes\", i_section, l_sectionName, l_activePnor.flashAddr, l_activePnor.sizeActual );\n\n\n \/\/--------------------------------\n \/\/ 3. Find the flash offset and full size (including ECC) of the\n \/\/ target section on the alternate PNOR.\n\n size_t read_size = PAGESIZE;\n l_errhdl = altpnordd->readFlash(tocBuffer, read_size, toc0_offset);\n if ( l_errhdl )\n {\n TRACFCOMP( g_trac_pnor, INFO_MRK\"PNOR::copyPnorPartitionToAlt> readFlash fail for 0x%X.\",\n TARGETING::get_huid(l_altProc) );\n break;\n }\n\n PNOR::SectionData_t l_altTOC[PNOR::NUM_SECTIONS+1];\n l_errhdl = parseTOC( tocBuffer, l_altTOC );\n if( l_errhdl )\n {\n TRACFCOMP( g_trac_pnor, INFO_MRK\"PNOR::copyPnorPartitionToAlt> parseTOC fail for 0x%X.\",\n TARGETING::get_huid(l_altProc) );\n break;\n }\n\n\n \/\/--------------------------------\n \/\/ 4. If size+offset match, bulk copy the complete section from\n \/\/ the active PNOR to the alternate.\n if( l_activePnor.sizeActual != l_altTOC[i_section].size )\n {\n TRACFCOMP( g_trac_pnor, INFO_MRK\"PNOR::copyPnorPartitionToAlt> Size mismatch between active (0x%X) and alt (0x%X) sections\",\n l_activePnor.sizeActual,\n l_altTOC[i_section].size );\n break;\n }\n\n TRACFCOMP( g_trac_pnor, INFO_MRK\"PNOR::copyPnorPartitionToAlt> About to copy 0x%X bytes\", l_altTOC[i_section].size );\n \/\/ loop through to write a few KB at a time so we don't\n \/\/ need to allocate a giant chunk of memory\n constexpr size_t TRANSFER_SIZE = 4*PAGESIZE;\n uint8_t l_buffer[TRANSFER_SIZE] = {0};\n for( size_t loop = 0; loop < l_altTOC[i_section].size; loop += TRANSFER_SIZE )\n {\n size_t l_readSize = std::min( TRANSFER_SIZE, l_altTOC[i_section].size-loop );\n\n \/\/ read the data off the active pnor\n l_errhdl = DeviceFW::deviceRead(\n TARGETING::MASTER_PROCESSOR_CHIP_TARGET_SENTINEL,\n l_buffer,\n l_readSize,\n DEVICE_PNOR_ADDRESS(0,l_activePnor.flashAddr+loop) );\n if( l_errhdl )\n {\n TRACFCOMP( g_trac_pnor, INFO_MRK\"PNOR::copyPnorPartitionToAlt> Failed to read 0x%X from active PNOR\", loop+l_activePnor.flashAddr );\n break;\n }\n\n \/\/ write the data into the alternate pnor\n l_errhdl = altpnordd->writeFlash(l_buffer,\n l_readSize,\n l_altTOC[i_section].flashAddr+loop);\n if( l_errhdl )\n {\n TRACFCOMP( g_trac_pnor, INFO_MRK\"PNOR::copyPnorPartitionToAlt> Failed to write 0x%X into alternate PNOR\", l_altTOC[i_section].flashAddr+loop );\n break;\n }\n }\n if( l_errhdl ) { break; }\n\n }while(0);\n\n if( l_errhdl )\n {\n l_errhdl->collectTrace(PNOR_COMP_NAME);\n }\n\n \/\/ Delete PNOR DD class and memory buffer\n if ( altpnordd )\n {\n delete altpnordd;\n altpnordd = nullptr;\n\n \/\/ Delete the LPC objects we used\n errlHndl_t l_errhdl2 = LPC::create_altmaster_objects( false, nullptr );\n if ( l_errhdl2 )\n {\n \/\/ Commit Error Log, but don't kill the istep because we can recover from being\n \/\/ out of sync on a later IPL\n TRACFCOMP( g_trac_pnor, INFO_MRK\"PNOR::copyPnorPartitionToAlt> Could not delete LPC objects. eid=0x%X, rc=0x%X. Committing log as info\", l_errhdl2->eid(), l_errhdl2->reasonCode());\n\n l_errhdl->collectTrace(PNOR_COMP_NAME);\n l_errhdl2->setSev(ERRORLOG::ERRL_SEV_INFORMATIONAL);\n errlCommit(l_errhdl2,PNOR_COMP_ID);\n }\n }\n\n if(tocBuffer != nullptr)\n {\n delete[] tocBuffer;\n tocBuffer = nullptr;\n }\n\n TRACFCOMP( g_trac_pnor, EXIT_MRK\"PNOR::copyPnorPartitionToAlt(%d=%s)> \",\n i_section, l_sectionName );\n return l_errhdl;\n}\n\n\n\n}; \/\/namespace PNOR\n\n<commit_msg>Ignore TOC errors when syncing EECACHE to alternate pnor<commit_after>\/* IBM_PROLOG_BEGIN_TAG *\/\n\/* This is an automatically generated prolog. *\/\n\/* *\/\n\/* $Source: src\/usr\/pnor\/pnoraltsync.C $ *\/\n\/* *\/\n\/* OpenPOWER HostBoot Project *\/\n\/* *\/\n\/* Contributors Listed Below - COPYRIGHT 2021 *\/\n\/* [+] International Business Machines Corp. *\/\n\/* *\/\n\/* *\/\n\/* Licensed under the Apache License, Version 2.0 (the \"License\"); *\/\n\/* you may not use this file except in compliance with the License. *\/\n\/* You may obtain a copy of the License at *\/\n\/* *\/\n\/* http:\/\/www.apache.org\/licenses\/LICENSE-2.0 *\/\n\/* *\/\n\/* Unless required by applicable law or agreed to in writing, software *\/\n\/* distributed under the License is distributed on an \"AS IS\" BASIS, *\/\n\/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or *\/\n\/* implied. See the License for the specific language governing *\/\n\/* permissions and limitations under the License. *\/\n\/* *\/\n\/* IBM_PROLOG_END_TAG *\/\n\/**\n * @file pnoraltsync.C\n *\n * @brief Implements PNOR::copyPnorPartitionToAlt() to synchronize\n * partitions between the active and alternate PNORs\n *\/\n\n\/*****************************************************************************\/\n\/\/ I n c l u d e s\n\/*****************************************************************************\/\n#include <trace\/interface.H>\n#include <devicefw\/driverif.H>\n#include <errl\/errlentry.H>\n#include <errl\/errlmanager.H>\n#include <targeting\/common\/targetservice.H>\n#include <targeting\/common\/utilFilter.H>\n#include <attributeenums.H>\n#include \"ffs.h\"\n#include \"common\/ffs_hb.H\"\n#include \"pnorrp.H\"\n#include <pnor\/pnorif.H>\n#include <pnor\/pnor_reasoncodes.H>\n#include <lpc\/lpcif.H>\n\n#if defined(CONFIG_PNORDD_IS_SFC)\n#include \"pnor_sfcdd.H\"\nusing PnorDD = PnorSfcDD;\n#elif (defined(CONFIG_PNORDD_IS_BMCMBOX) || defined(CONFIG_PNORDD_IS_IPMI))\n#include \"pnor_hiomapdd.H\"\nusing PnorDD = PnorHiomapDD;\n#else\n#error \"No PNOR DD configured\"\n#endif\n\nextern trace_desc_t* g_trac_pnor;\n\nnamespace PNOR\n{\n\n\/**\n * @brief Copy a given PNOR partition from the active PNOR into the\n * alternate copy\n *\/\nerrlHndl_t copyPnorPartitionToAlt( PNOR::SectionId i_section )\n{\n errlHndl_t l_errhdl = nullptr;\n const char* l_sectionName = PNOR::SectionIdToString(i_section);\n TRACFCOMP( g_trac_pnor, ENTER_MRK\"PNOR::copyPnorPartitionToAlt(%d=%s)> \",\n i_section, l_sectionName );\n\n \/\/ Algorithm is:\n \/\/ 0. Check if there is an alt-pnor to update, exit if not\n \/\/ 1. Instantiate an alt-pnordd to access the alternate PNOR.\n \/\/ 2. Find the flash offset and full size (including ECC) of the\n \/\/ target section on the active PNOR.\n \/\/ 3. Find the flash offset and full size (including ECC) of the\n \/\/ target section on the alternate PNOR.\n \/\/ 4. If size+offset match, bulk copy the complete section from\n \/\/ the active PNOR to the alternate.\n\n PnorDD* altpnordd = nullptr;\n\n \/\/ When reading PNOR TOC assume a single page and no ECC\n uint8_t* tocBuffer = new uint8_t[PAGESIZE];\n const uint64_t toc0_offset = PnorRP::getInstance().getTocOffset(TOC_0);\n\n do{\n \/\/--------------------------------\n \/\/ 0. Check if there is an alt-pnor to update, exit if not\n\n \/\/ Get list of all processors\n TARGETING::TargetHandleList procList;\n TARGETING::getAllChips(procList,\n TARGETING::TYPE_PROC,\n true); \/\/ true: return functional targets\n\n if( ( 0 == procList.size() ) ||\n ( nullptr == procList[0] ) )\n {\n TRACFCOMP( g_trac_pnor, INFO_MRK\"PNOR::copyPnorPartitionToAlt()> No functional processors Found! Validation skipped\" );\n break;\n }\n\n \/\/ Loop through all processors to find the alt-proc\n TARGETING::Target* l_altProc = nullptr;\n for(uint32_t i=0; i<procList.size(); i++)\n {\n \/\/ Check if processor is MASTER_CANDIDATE\n TARGETING::ATTR_PROC_MASTER_TYPE_type type_enum =\n procList[i]->getAttr<TARGETING::ATTR_PROC_MASTER_TYPE>();\n\n if ( type_enum != TARGETING::PROC_MASTER_TYPE_MASTER_CANDIDATE )\n {\n TRACDCOMP( g_trac_pnor, INFO_MRK\"PNOR::copyPnorPartitionToAlt> Skipping Processor 0x%X (PROC_MASTER_TYPE=%d)\",\n TARGETING::get_huid(procList[i]), type_enum);\n continue;\n }\n\n TRACFCOMP( g_trac_pnor, INFO_MRK\"PNOR::copyPnorPartitionToAlt> Validating Processor 0x%X (PROC_MASTER_TYPE=%d)\",\n TARGETING::get_huid(procList[i]), type_enum);\n l_altProc = procList[i];\n break;\n }\n if( !l_altProc )\n {\n TRACFCOMP( g_trac_pnor, INFO_MRK\"PNOR::copyPnorPartitionToAlt> There are no alternate PNORs to update\" );\n break;\n }\n\n\n \/\/--------------------------------\n \/\/ 1. Instantiate an alt-pnordd to access the alternate PNOR.\n\n \/\/ Create the LPC objects we're going to use\n l_errhdl = LPC::create_altmaster_objects( true, l_altProc );\n if ( l_errhdl )\n {\n \/\/ Commit Error Log, but continue the test\n TRACFCOMP( g_trac_pnor, INFO_MRK\"PNOR::copyPnorPartitionToAlt> Could not create LPC objects for %.8X.\", TARGETING::get_huid(l_altProc) );\n break;\n }\n\n \/\/ Create and initialize custom PNOR DD class for this target\n altpnordd = new PnorDD(l_altProc);\n\n\n \/\/--------------------------------\n \/\/ 2. Find the flash offset and full size (including ECC) of the\n \/\/ target section on the active PNOR.\n\n PNOR::SectionInfo_t l_activePnor;\n l_errhdl = PNOR::getSectionInfo(i_section, l_activePnor);\n if( l_errhdl )\n {\n TRACFCOMP( g_trac_pnor, INFO_MRK\"PNOR::copyPnorPartitionToAlt> Error getting data for section %d(%s)\", i_section, l_sectionName );\n break;\n }\n TRACFCOMP( g_trac_pnor, INFO_MRK\"PNOR::copyPnorPartitionToAlt> Section %d(%s) located at 0x%.X for 0x%X bytes\", i_section, l_sectionName, l_activePnor.flashAddr, l_activePnor.sizeActual );\n\n\n \/\/--------------------------------\n \/\/ 3. Find the flash offset and full size (including ECC) of the\n \/\/ target section on the alternate PNOR.\n\n size_t read_size = PAGESIZE;\n l_errhdl = altpnordd->readFlash(tocBuffer, read_size, toc0_offset);\n if ( l_errhdl )\n {\n TRACFCOMP( g_trac_pnor, INFO_MRK\"PNOR::copyPnorPartitionToAlt> readFlash fail for 0x%X.\",\n TARGETING::get_huid(l_altProc) );\n break;\n }\n\n PNOR::SectionData_t l_altTOC[PNOR::NUM_SECTIONS+1];\n l_errhdl = parseTOC( tocBuffer, l_altTOC );\n if( l_errhdl )\n {\n TRACFCOMP( g_trac_pnor, INFO_MRK\"PNOR::copyPnorPartitionToAlt> parseTOC fail for 0x%X.\",\n TARGETING::get_huid(l_altProc) );\n \/\/ This can be caused by a genesis boot where the alt side has never been IPLed.\n \/\/ Need to just ignore this error and move on.\n l_errhdl->setSev(ERRORLOG::ERRL_SEV_INFORMATIONAL);\n errlCommit(l_errhdl,PNOR_COMP_ID);\n break;\n }\n\n\n \/\/--------------------------------\n \/\/ 4. If size+offset match, bulk copy the complete section from\n \/\/ the active PNOR to the alternate.\n if( l_activePnor.sizeActual != l_altTOC[i_section].size )\n {\n TRACFCOMP( g_trac_pnor, INFO_MRK\"PNOR::copyPnorPartitionToAlt> Size mismatch between active (0x%X) and alt (0x%X) sections\",\n l_activePnor.sizeActual,\n l_altTOC[i_section].size );\n break;\n }\n\n TRACFCOMP( g_trac_pnor, INFO_MRK\"PNOR::copyPnorPartitionToAlt> About to copy 0x%X bytes\", l_altTOC[i_section].size );\n \/\/ loop through to write a few KB at a time so we don't\n \/\/ need to allocate a giant chunk of memory\n constexpr size_t TRANSFER_SIZE = 4*PAGESIZE;\n uint8_t l_buffer[TRANSFER_SIZE] = {0};\n for( size_t loop = 0; loop < l_altTOC[i_section].size; loop += TRANSFER_SIZE )\n {\n size_t l_readSize = std::min( TRANSFER_SIZE, l_altTOC[i_section].size-loop );\n\n \/\/ read the data off the active pnor\n l_errhdl = DeviceFW::deviceRead(\n TARGETING::MASTER_PROCESSOR_CHIP_TARGET_SENTINEL,\n l_buffer,\n l_readSize,\n DEVICE_PNOR_ADDRESS(0,l_activePnor.flashAddr+loop) );\n if( l_errhdl )\n {\n TRACFCOMP( g_trac_pnor, INFO_MRK\"PNOR::copyPnorPartitionToAlt> Failed to read 0x%X from active PNOR\", loop+l_activePnor.flashAddr );\n break;\n }\n\n \/\/ write the data into the alternate pnor\n l_errhdl = altpnordd->writeFlash(l_buffer,\n l_readSize,\n l_altTOC[i_section].flashAddr+loop);\n if( l_errhdl )\n {\n TRACFCOMP( g_trac_pnor, INFO_MRK\"PNOR::copyPnorPartitionToAlt> Failed to write 0x%X into alternate PNOR\", l_altTOC[i_section].flashAddr+loop );\n break;\n }\n }\n if( l_errhdl ) { break; }\n\n }while(0);\n\n if( l_errhdl )\n {\n l_errhdl->collectTrace(PNOR_COMP_NAME);\n }\n\n \/\/ Delete PNOR DD class and memory buffer\n if ( altpnordd )\n {\n delete altpnordd;\n altpnordd = nullptr;\n\n \/\/ Delete the LPC objects we used\n errlHndl_t l_errhdl2 = LPC::create_altmaster_objects( false, nullptr );\n if ( l_errhdl2 )\n {\n \/\/ Commit Error Log, but don't kill the istep because we can recover from being\n \/\/ out of sync on a later IPL\n TRACFCOMP( g_trac_pnor, INFO_MRK\"PNOR::copyPnorPartitionToAlt> Could not delete LPC objects. eid=0x%X, rc=0x%X. Committing log as info\", l_errhdl2->eid(), l_errhdl2->reasonCode());\n\n l_errhdl->collectTrace(PNOR_COMP_NAME);\n l_errhdl2->setSev(ERRORLOG::ERRL_SEV_INFORMATIONAL);\n errlCommit(l_errhdl2,PNOR_COMP_ID);\n }\n }\n\n if(tocBuffer != nullptr)\n {\n delete[] tocBuffer;\n tocBuffer = nullptr;\n }\n\n TRACFCOMP( g_trac_pnor, EXIT_MRK\"PNOR::copyPnorPartitionToAlt(%d=%s)> \",\n i_section, l_sectionName );\n return l_errhdl;\n}\n\n\n\n}; \/\/namespace PNOR\n\n<|endoftext|>"} {"text":"<commit_before>\/* Copyright 2017 The TensorFlow Authors. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*\/\n#include <memory>\n#include <string>\n#include <vector>\n\n#include \"tensorflow\/contrib\/lite\/toco\/graph_transformations\/graph_transformations.h\"\n#include \"tensorflow\/contrib\/lite\/toco\/model.h\"\n#include \"tensorflow\/contrib\/lite\/toco\/tooling_util.h\"\n\nnamespace toco {\n\nnamespace {\n\nstd::vector<std::unique_ptr<Operator>>::iterator FindOperator(\n Model* model, const Operator& op) {\n auto it = model->operators.begin();\n for (; it != model->operators.end(); ++it) {\n if (it->get() == &op) {\n break;\n }\n }\n return it;\n}\n\nbool GetStateArrayForBackEdge(const Model& model,\n const string& back_edge_source_array,\n string* state_array = nullptr) {\n for (const auto& rnn_state : model.flags.rnn_states()) {\n if (back_edge_source_array == rnn_state.back_edge_source_array()) {\n \/\/ Found LSTM cell output\n if (state_array) {\n *state_array = rnn_state.state_array();\n }\n return true;\n }\n }\n return false;\n}\n\n\/\/ Returns true if the given operator has exactly 1 input, and is connected to\n\/\/ the given op_type.\n\/\/ We use kNone to indicate an input unattached to an operator output. Usually\n\/\/ these are the static input arrays.\nbool MatchOperatorInputs(const Operator& op, const Model& model,\n OperatorType op_type, Operator** connected_op) {\n \/\/ Check for required number of inputs\n if (op.inputs.size() != 1) {\n return false;\n }\n\n \/\/ Check if first input is disconnected\/connected to an operator\n Operator* x = GetOpWithOutput(model, op.inputs[0]);\n if ((op_type == OperatorType::kNone) && (x != nullptr)) {\n return false;\n }\n if ((op_type != OperatorType::kNone) && (x == nullptr)) {\n return false;\n }\n\n \/\/ Check that first operator, if connected, is of correct type\n if ((x != nullptr) && (x->type != op_type)) {\n return false;\n }\n\n \/\/ Successfully matched. Optionally return matching input operators.\n if (connected_op) {\n *connected_op = x;\n }\n\n return true;\n}\n\n\/\/ Returns true if the given operator has exactly 2 inputs, which are connected\n\/\/ to the given op_types.\n\/\/ We use kNone to indicate an input unattached to an operator output. Usually\n\/\/ these are the static input arrays.\nbool MatchOperatorInputs(const Operator& op, const Model& model,\n OperatorType a_op_type, Operator** a_op,\n OperatorType b_op_type, Operator** b_op) {\n \/\/ Check for required number of inputs\n if (op.inputs.size() != 2) {\n return false;\n }\n\n \/\/ Check if first input is disconnected\/connected to an operator\n Operator* x = GetOpWithOutput(model, op.inputs[0]);\n if ((a_op_type == OperatorType::kNone) && (x != nullptr)) {\n return false;\n }\n if ((a_op_type != OperatorType::kNone) && (x == nullptr)) {\n return false;\n }\n\n \/\/ Check that first operator, if connected, is of correct type\n if ((x != nullptr) && (x->type != a_op_type)) {\n return false;\n }\n\n \/\/ Check if second input is disconnected\/connected to an operator\n Operator* y = GetOpWithOutput(model, op.inputs[1]);\n if ((b_op_type == OperatorType::kNone) && (y != nullptr)) {\n return false;\n }\n if ((b_op_type != OperatorType::kNone) && (y == nullptr)) {\n return false;\n }\n\n \/\/ Check that second operator, if connected, is of correct type\n if ((y != nullptr) && (y->type != b_op_type)) {\n return false;\n }\n\n \/\/ Successfully matched. Optionally return matching input operators.\n if (a_op != nullptr) {\n *a_op = x;\n }\n if (b_op != nullptr) {\n *b_op = y;\n }\n return true;\n}\n\n\/\/ Returns true if the given operator has exactly 3 inputs, which are connected\n\/\/ to the given op_types.\n\/\/ We use kNone to indicate an input unattached to an operator output. Usually\n\/\/ these are the static input arrays.\nbool MatchOperatorInputs(const Operator& op, const Model& model,\n OperatorType a_op_type, Operator** a_op,\n OperatorType b_op_type, Operator** b_op,\n OperatorType c_op_type, Operator** c_op) {\n \/\/ Check for required number of inputs\n if (op.inputs.size() != 3) {\n return false;\n }\n\n \/\/ Check if first input is disconnected\/connected to an operator\n Operator* x = GetOpWithOutput(model, op.inputs[0]);\n if ((a_op_type == OperatorType::kNone) && (x != nullptr)) {\n return false;\n }\n if ((a_op_type != OperatorType::kNone) && (x == nullptr)) {\n return false;\n }\n\n \/\/ Check that first operator, if connected, is of correct type\n if ((x != nullptr) && (x->type != a_op_type)) {\n return false;\n }\n\n \/\/ Check if second input is disconnected\/connected to an operator\n Operator* y = GetOpWithOutput(model, op.inputs[1]);\n if ((b_op_type == OperatorType::kNone) && (y != nullptr)) {\n return false;\n }\n if ((b_op_type != OperatorType::kNone) && (y == nullptr)) {\n return false;\n }\n\n \/\/ Check that second operator, if connected, is of correct type\n if ((y != nullptr) && (y->type != b_op_type)) {\n return false;\n }\n\n \/\/ Check if third input is disconnected\/connected to an operator\n Operator* z = GetOpWithOutput(model, op.inputs[2]);\n if ((c_op_type == OperatorType::kNone) && (z != nullptr)) {\n return false;\n }\n if ((c_op_type != OperatorType::kNone) && (z == nullptr)) {\n return false;\n }\n\n \/\/ Check that third operator, if connected, is of correct type\n if ((z != nullptr) && (z->type != c_op_type)) {\n return false;\n }\n\n \/\/ Successfully matched. Optionally return matching input operators.\n if (a_op != nullptr) {\n *a_op = x;\n }\n if (b_op != nullptr) {\n *b_op = y;\n }\n if (c_op != nullptr) {\n *c_op = z;\n }\n return true;\n}\n\n} \/\/ namespace\n\nbool IdentifyLstmCell::Run(Model* model, std::size_t op_index) {\n \/\/ This LSTM cell identification method is not invariant to commutation of\n \/\/ commutative operator inputs. For example, if input[0] and input[1] of the\n \/\/ final output multiplication were swapped, this method would not identify it\n \/\/ as an LSTM cell. This is OK in most cases, because\n \/\/ tf.rnn.contrib.BasicLSTMCell always generates LSTM cells the same way.\n\n \/\/ Final output multiply\n auto op_it = model->operators.begin() + op_index;\n Operator* final_output_mul = op_it->get();\n if (final_output_mul->type != OperatorType::kMul) {\n return false;\n }\n Operator *state_output_tanh, *fc_output_sig;\n if (!MatchOperatorInputs(*final_output_mul, *model, OperatorType::kTanh,\n &state_output_tanh, OperatorType::kLogistic,\n &fc_output_sig)) {\n return false;\n }\n\n \/\/ State output TanH\n \/\/ (We don't count an operator as ID'd until we verify it has the correct\n \/\/ operator types feeding into it.)\n Operator* state_combine_add;\n if (!MatchOperatorInputs(*state_output_tanh, *model, OperatorType::kAdd,\n &state_combine_add)) {\n return false;\n }\n string prev_state;\n if (!GetStateArrayForBackEdge(*model, state_output_tanh->inputs[0],\n &prev_state)) {\n return false;\n }\n\n \/\/ State forget & remember addition\n Operator *state_forget_mul, *state_remember_mul;\n if (!MatchOperatorInputs(*state_combine_add, *model, OperatorType::kMul,\n &state_forget_mul, OperatorType::kMul,\n &state_remember_mul)) {\n return false;\n }\n if (state_forget_mul->inputs[0] != prev_state) {\n return false;\n }\n\n \/\/ State forget gate\n Operator* state_forget_sig;\n if (!MatchOperatorInputs(*state_forget_mul, *model, OperatorType::kNone,\n nullptr, OperatorType::kLogistic,\n &state_forget_sig)) {\n return false;\n }\n\n \/\/ State remember gate\n Operator *state_remember_sig, *state_info_tanh;\n if (!MatchOperatorInputs(*state_remember_mul, *model, OperatorType::kLogistic,\n &state_remember_sig, OperatorType::kTanh,\n &state_info_tanh)) {\n return false;\n }\n\n \/\/ State remember \"information\" activation function\n Operator* fc_output_split;\n if (!MatchOperatorInputs(*state_info_tanh, *model, OperatorType::kSplit,\n &fc_output_split)) {\n return false;\n }\n \/\/ State remember gate activation function\n Operator* tmp;\n if (!MatchOperatorInputs(*state_remember_sig, *model, OperatorType::kSplit,\n &tmp) ||\n (tmp != fc_output_split)) {\n return false;\n }\n \/\/ State forget gate activation function\n if (!MatchOperatorInputs(*state_forget_sig, *model, OperatorType::kSplit,\n &tmp) ||\n (tmp != fc_output_split)) {\n return false;\n }\n \/\/ Fully connected output activation function\n if (!MatchOperatorInputs(*fc_output_sig, *model, OperatorType::kSplit,\n &tmp) ||\n (tmp != fc_output_split)) {\n return false;\n }\n \/\/ Fully connected output split\n Operator* fully_connected;\n if (!MatchOperatorInputs(*fc_output_split, *model, OperatorType::kNone,\n nullptr, OperatorType::kFullyConnected,\n &fully_connected)) {\n return false;\n }\n\n \/\/ Fully connected op\n Operator* concat_inputs;\n if (!MatchOperatorInputs(*fully_connected, *model,\n OperatorType::kConcatenation, &concat_inputs,\n OperatorType::kNone, nullptr, OperatorType::kNone,\n nullptr)) {\n return false;\n }\n\n if (static_cast<FullyConnectedOperator*>(fully_connected)->weights_format !=\n FullyConnectedWeightsFormat::kDefault) {\n \/\/ Not yet implemented: experimental shuffled weights in fused LSTM cell.\n return false;\n }\n\n \/\/ Emplace a new LSTM cell operator\n auto* lstm_cell_op = new LstmCellOperator;\n lstm_cell_op->inputs.resize(LstmCellOperator::NUM_INPUTS);\n lstm_cell_op->inputs[LstmCellOperator::DATA_INPUT] = concat_inputs->inputs[0];\n lstm_cell_op->inputs[LstmCellOperator::PREV_ACTIV_INPUT] =\n concat_inputs->inputs[1];\n lstm_cell_op->inputs[LstmCellOperator::WEIGHTS_INPUT] =\n fully_connected->inputs[1];\n lstm_cell_op->inputs[LstmCellOperator::BIASES_INPUT] =\n fully_connected->inputs[2];\n lstm_cell_op->inputs[LstmCellOperator::PREV_STATE_INPUT] = prev_state;\n lstm_cell_op->outputs.resize(LstmCellOperator::NUM_OUTPUTS);\n lstm_cell_op->outputs[LstmCellOperator::STATE_OUTPUT] =\n state_output_tanh->inputs[0];\n lstm_cell_op->outputs[LstmCellOperator::ACTIV_OUTPUT] =\n final_output_mul->outputs[0];\n model->operators.emplace(op_it, lstm_cell_op);\n AddMessageF(\"Creating %s replacing equivalent subgraph\",\n LogName(*lstm_cell_op));\n\n \/\/ Create temp arrays used internally during runtime.\n const string base_name(FindLongestCommonPrefix(\n lstm_cell_op->outputs[LstmCellOperator::STATE_OUTPUT],\n lstm_cell_op->outputs[LstmCellOperator::ACTIV_OUTPUT]));\n const string& concat_temp_array_name =\n AvailableArrayName(*model, base_name + \"concat_temp\");\n model->GetOrCreateArray(concat_temp_array_name);\n lstm_cell_op->outputs[LstmCellOperator::CONCAT_TEMP] = concat_temp_array_name;\n const string& activ_temp_array_name =\n AvailableArrayName(*model, base_name + \"activ_temp\");\n model->GetOrCreateArray(activ_temp_array_name);\n lstm_cell_op->outputs[LstmCellOperator::ACTIV_TEMP] = activ_temp_array_name;\n AddMessageF(\"Created temp outputs %s and %s on operator %s\",\n concat_temp_array_name, activ_temp_array_name,\n LogName(*lstm_cell_op));\n\n \/\/ Delete arrays and operators replaced by the LSTM cell operator. Order is\n \/\/ important - DeleteArrayIfUnused() only succeeds if dependent operators\n \/\/ have been removed first. Start at the output and work towards the input.\n model->operators.erase(FindOperator(model, *final_output_mul));\n DeleteArrayIfUnused(state_output_tanh->outputs[0], model);\n DeleteArrayIfUnused(fc_output_sig->outputs[0], model);\n model->operators.erase(FindOperator(model, *state_output_tanh));\n model->operators.erase(FindOperator(model, *fc_output_sig));\n model->operators.erase(FindOperator(model, *state_combine_add));\n DeleteArrayIfUnused(state_forget_mul->outputs[0], model);\n DeleteArrayIfUnused(state_remember_mul->outputs[0], model);\n model->operators.erase(FindOperator(model, *state_forget_mul));\n model->operators.erase(FindOperator(model, *state_remember_mul));\n DeleteArrayIfUnused(state_forget_sig->outputs[0], model);\n DeleteArrayIfUnused(state_info_tanh->outputs[0], model);\n DeleteArrayIfUnused(state_remember_sig->outputs[0], model);\n model->operators.erase(FindOperator(model, *state_forget_sig));\n model->operators.erase(FindOperator(model, *state_info_tanh));\n model->operators.erase(FindOperator(model, *state_remember_sig));\n DeleteArrayIfUnused(fc_output_split->outputs[0], model);\n DeleteArrayIfUnused(fc_output_split->outputs[1], model);\n DeleteArrayIfUnused(fc_output_split->outputs[2], model);\n DeleteArrayIfUnused(fc_output_split->outputs[3], model);\n string dims_array = fc_output_split->inputs[0];\n model->operators.erase(FindOperator(model, *fc_output_split));\n DeleteArrayIfUnused(dims_array, model);\n DeleteArrayIfUnused(fully_connected->outputs[0], model);\n model->operators.erase(FindOperator(model, *fully_connected));\n DeleteArrayIfUnused(concat_inputs->outputs[0], model);\n model->operators.erase(FindOperator(model, *concat_inputs));\n return true;\n}\n\n} \/\/ namespace toco\n<commit_msg>make identify_lstm independent of rnn_states<commit_after>\/* Copyright 2017 The TensorFlow Authors. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*\/\n#include <memory>\n#include <string>\n#include <vector>\n\n#include \"tensorflow\/contrib\/lite\/toco\/graph_transformations\/graph_transformations.h\"\n#include \"tensorflow\/contrib\/lite\/toco\/model.h\"\n#include \"tensorflow\/contrib\/lite\/toco\/tooling_util.h\"\n\nnamespace toco {\n\nnamespace {\n\nstd::vector<std::unique_ptr<Operator>>::iterator FindOperator(\n Model* model, const Operator& op) {\n auto it = model->operators.begin();\n for (; it != model->operators.end(); ++it) {\n if (it->get() == &op) {\n break;\n }\n }\n return it;\n}\n\n\/\/ Returns true if the given operator has exactly 1 input, and is connected to\n\/\/ the given op_type.\n\/\/ We use kNone to indicate an input unattached to an operator output. Usually\n\/\/ these are the static input arrays.\nbool MatchOperatorInputs(const Operator& op, const Model& model,\n OperatorType op_type, Operator** connected_op) {\n \/\/ Check for required number of inputs\n if (op.inputs.size() != 1) {\n return false;\n }\n\n \/\/ Check if first input is disconnected\/connected to an operator\n Operator* x = GetOpWithOutput(model, op.inputs[0]);\n if ((op_type == OperatorType::kNone) && (x != nullptr)) {\n return false;\n }\n if ((op_type != OperatorType::kNone) && (x == nullptr)) {\n return false;\n }\n\n \/\/ Check that first operator, if connected, is of correct type\n if ((x != nullptr) && (x->type != op_type)) {\n return false;\n }\n\n \/\/ Successfully matched. Optionally return matching input operators.\n if (connected_op) {\n *connected_op = x;\n }\n\n return true;\n}\n\n\/\/ Returns true if the given operator has exactly 2 inputs, which are connected\n\/\/ to the given op_types.\n\/\/ We use kNone to indicate an input unattached to an operator output. Usually\n\/\/ these are the static input arrays.\nbool MatchOperatorInputs(const Operator& op, const Model& model,\n OperatorType a_op_type, Operator** a_op,\n OperatorType b_op_type, Operator** b_op) {\n \/\/ Check for required number of inputs\n if (op.inputs.size() != 2) {\n return false;\n }\n\n \/\/ Check if first input is disconnected\/connected to an operator\n Operator* x = GetOpWithOutput(model, op.inputs[0]);\n if ((a_op_type == OperatorType::kNone) && (x != nullptr)) {\n return false;\n }\n if ((a_op_type != OperatorType::kNone) && (x == nullptr)) {\n return false;\n }\n\n \/\/ Check that first operator, if connected, is of correct type\n if ((x != nullptr) && (x->type != a_op_type)) {\n return false;\n }\n\n \/\/ Check if second input is disconnected\/connected to an operator\n Operator* y = GetOpWithOutput(model, op.inputs[1]);\n if ((b_op_type == OperatorType::kNone) && (y != nullptr)) {\n return false;\n }\n if ((b_op_type != OperatorType::kNone) && (y == nullptr)) {\n return false;\n }\n\n \/\/ Check that second operator, if connected, is of correct type\n if ((y != nullptr) && (y->type != b_op_type)) {\n return false;\n }\n\n \/\/ Successfully matched. Optionally return matching input operators.\n if (a_op != nullptr) {\n *a_op = x;\n }\n if (b_op != nullptr) {\n *b_op = y;\n }\n return true;\n}\n\n\/\/ Returns true if the given operator has exactly 3 inputs, which are connected\n\/\/ to the given op_types.\n\/\/ We use kNone to indicate an input unattached to an operator output. Usually\n\/\/ these are the static input arrays.\nbool MatchOperatorInputs(const Operator& op, const Model& model,\n OperatorType a_op_type, Operator** a_op,\n OperatorType b_op_type, Operator** b_op,\n OperatorType c_op_type, Operator** c_op) {\n \/\/ Check for required number of inputs\n if (op.inputs.size() != 3) {\n return false;\n }\n\n \/\/ Check if first input is disconnected\/connected to an operator\n Operator* x = GetOpWithOutput(model, op.inputs[0]);\n if ((a_op_type == OperatorType::kNone) && (x != nullptr)) {\n return false;\n }\n if ((a_op_type != OperatorType::kNone) && (x == nullptr)) {\n return false;\n }\n\n \/\/ Check that first operator, if connected, is of correct type\n if ((x != nullptr) && (x->type != a_op_type)) {\n return false;\n }\n\n \/\/ Check if second input is disconnected\/connected to an operator\n Operator* y = GetOpWithOutput(model, op.inputs[1]);\n if ((b_op_type == OperatorType::kNone) && (y != nullptr)) {\n return false;\n }\n if ((b_op_type != OperatorType::kNone) && (y == nullptr)) {\n return false;\n }\n\n \/\/ Check that second operator, if connected, is of correct type\n if ((y != nullptr) && (y->type != b_op_type)) {\n return false;\n }\n\n \/\/ Check if third input is disconnected\/connected to an operator\n Operator* z = GetOpWithOutput(model, op.inputs[2]);\n if ((c_op_type == OperatorType::kNone) && (z != nullptr)) {\n return false;\n }\n if ((c_op_type != OperatorType::kNone) && (z == nullptr)) {\n return false;\n }\n\n \/\/ Check that third operator, if connected, is of correct type\n if ((z != nullptr) && (z->type != c_op_type)) {\n return false;\n }\n\n \/\/ Successfully matched. Optionally return matching input operators.\n if (a_op != nullptr) {\n *a_op = x;\n }\n if (b_op != nullptr) {\n *b_op = y;\n }\n if (c_op != nullptr) {\n *c_op = z;\n }\n return true;\n}\n\n} \/\/ namespace\n\nbool IdentifyLstmCell::Run(Model* model, std::size_t op_index) {\n \/\/ This LSTM cell identification method is not invariant to commutation of\n \/\/ commutative operator inputs. For example, if input[0] and input[1] of the\n \/\/ final output multiplication were swapped, this method would not identify it\n \/\/ as an LSTM cell. This is OK in most cases, because\n \/\/ tf.rnn.contrib.BasicLSTMCell always generates LSTM cells the same way.\n\n \/\/ Final output multiply\n auto op_it = model->operators.begin() + op_index;\n Operator* final_output_mul = op_it->get();\n if (final_output_mul->type != OperatorType::kMul) {\n return false;\n }\n Operator *state_output_tanh, *fc_output_sig;\n if (!MatchOperatorInputs(*final_output_mul, *model, OperatorType::kTanh,\n &state_output_tanh, OperatorType::kLogistic,\n &fc_output_sig)) {\n return false;\n }\n\n \/\/ State output TanH\n \/\/ (We don't count an operator as ID'd until we verify it has the correct\n \/\/ operator types feeding into it.)\n Operator* state_combine_add;\n if (!MatchOperatorInputs(*state_output_tanh, *model, OperatorType::kAdd,\n &state_combine_add)) {\n return false;\n }\n\n \/\/ State forget & remember addition\n Operator *state_forget_mul, *state_remember_mul;\n if (!MatchOperatorInputs(*state_combine_add, *model, OperatorType::kMul,\n &state_forget_mul, OperatorType::kMul,\n &state_remember_mul)) {\n return false;\n }\n const string prev_state = state_forget_mul->inputs[0];\n\n \/\/ State forget gate\n Operator* state_forget_sig;\n if (!MatchOperatorInputs(*state_forget_mul, *model, OperatorType::kNone,\n nullptr, OperatorType::kLogistic,\n &state_forget_sig)) {\n return false;\n }\n\n \/\/ State remember gate\n Operator *state_remember_sig, *state_info_tanh;\n if (!MatchOperatorInputs(*state_remember_mul, *model, OperatorType::kLogistic,\n &state_remember_sig, OperatorType::kTanh,\n &state_info_tanh)) {\n return false;\n }\n\n \/\/ State remember \"information\" activation function\n Operator* fc_output_split;\n if (!MatchOperatorInputs(*state_info_tanh, *model, OperatorType::kSplit,\n &fc_output_split)) {\n return false;\n }\n \/\/ State remember gate activation function\n Operator* tmp;\n if (!MatchOperatorInputs(*state_remember_sig, *model, OperatorType::kSplit,\n &tmp) ||\n (tmp != fc_output_split)) {\n return false;\n }\n \/\/ State forget gate activation function\n if (!MatchOperatorInputs(*state_forget_sig, *model, OperatorType::kSplit,\n &tmp) ||\n (tmp != fc_output_split)) {\n return false;\n }\n \/\/ Fully connected output activation function\n if (!MatchOperatorInputs(*fc_output_sig, *model, OperatorType::kSplit,\n &tmp) ||\n (tmp != fc_output_split)) {\n return false;\n }\n \/\/ Fully connected output split\n Operator* fully_connected;\n if (!MatchOperatorInputs(*fc_output_split, *model, OperatorType::kNone,\n nullptr, OperatorType::kFullyConnected,\n &fully_connected)) {\n return false;\n }\n\n \/\/ Fully connected op\n Operator* concat_inputs;\n if (!MatchOperatorInputs(*fully_connected, *model,\n OperatorType::kConcatenation, &concat_inputs,\n OperatorType::kNone, nullptr, OperatorType::kNone,\n nullptr)) {\n return false;\n }\n\n if (static_cast<FullyConnectedOperator*>(fully_connected)->weights_format !=\n FullyConnectedWeightsFormat::kDefault) {\n \/\/ Not yet implemented: experimental shuffled weights in fused LSTM cell.\n return false;\n }\n\n \/\/ Emplace a new LSTM cell operator\n auto* lstm_cell_op = new LstmCellOperator;\n lstm_cell_op->inputs.resize(LstmCellOperator::NUM_INPUTS);\n lstm_cell_op->inputs[LstmCellOperator::DATA_INPUT] = concat_inputs->inputs[0];\n lstm_cell_op->inputs[LstmCellOperator::PREV_ACTIV_INPUT] =\n concat_inputs->inputs[1];\n lstm_cell_op->inputs[LstmCellOperator::WEIGHTS_INPUT] =\n fully_connected->inputs[1];\n lstm_cell_op->inputs[LstmCellOperator::BIASES_INPUT] =\n fully_connected->inputs[2];\n lstm_cell_op->inputs[LstmCellOperator::PREV_STATE_INPUT] = prev_state;\n lstm_cell_op->outputs.resize(LstmCellOperator::NUM_OUTPUTS);\n lstm_cell_op->outputs[LstmCellOperator::STATE_OUTPUT] =\n state_output_tanh->inputs[0];\n lstm_cell_op->outputs[LstmCellOperator::ACTIV_OUTPUT] =\n final_output_mul->outputs[0];\n model->operators.emplace(op_it, lstm_cell_op);\n AddMessageF(\"Creating %s replacing equivalent subgraph\",\n LogName(*lstm_cell_op));\n\n \/\/ Create temp arrays used internally during runtime.\n const string base_name(FindLongestCommonPrefix(\n lstm_cell_op->outputs[LstmCellOperator::STATE_OUTPUT],\n lstm_cell_op->outputs[LstmCellOperator::ACTIV_OUTPUT]));\n const string& concat_temp_array_name =\n AvailableArrayName(*model, base_name + \"concat_temp\");\n model->GetOrCreateArray(concat_temp_array_name);\n lstm_cell_op->outputs[LstmCellOperator::CONCAT_TEMP] = concat_temp_array_name;\n const string& activ_temp_array_name =\n AvailableArrayName(*model, base_name + \"activ_temp\");\n model->GetOrCreateArray(activ_temp_array_name);\n lstm_cell_op->outputs[LstmCellOperator::ACTIV_TEMP] = activ_temp_array_name;\n AddMessageF(\"Created temp outputs %s and %s on operator %s\",\n concat_temp_array_name, activ_temp_array_name,\n LogName(*lstm_cell_op));\n\n \/\/ Delete arrays and operators replaced by the LSTM cell operator. Order is\n \/\/ important - DeleteArrayIfUnused() only succeeds if dependent operators\n \/\/ have been removed first. Start at the output and work towards the input.\n model->operators.erase(FindOperator(model, *final_output_mul));\n DeleteArrayIfUnused(state_output_tanh->outputs[0], model);\n DeleteArrayIfUnused(fc_output_sig->outputs[0], model);\n model->operators.erase(FindOperator(model, *state_output_tanh));\n model->operators.erase(FindOperator(model, *fc_output_sig));\n model->operators.erase(FindOperator(model, *state_combine_add));\n DeleteArrayIfUnused(state_forget_mul->outputs[0], model);\n DeleteArrayIfUnused(state_remember_mul->outputs[0], model);\n model->operators.erase(FindOperator(model, *state_forget_mul));\n model->operators.erase(FindOperator(model, *state_remember_mul));\n DeleteArrayIfUnused(state_forget_sig->outputs[0], model);\n DeleteArrayIfUnused(state_info_tanh->outputs[0], model);\n DeleteArrayIfUnused(state_remember_sig->outputs[0], model);\n model->operators.erase(FindOperator(model, *state_forget_sig));\n model->operators.erase(FindOperator(model, *state_info_tanh));\n model->operators.erase(FindOperator(model, *state_remember_sig));\n DeleteArrayIfUnused(fc_output_split->outputs[0], model);\n DeleteArrayIfUnused(fc_output_split->outputs[1], model);\n DeleteArrayIfUnused(fc_output_split->outputs[2], model);\n DeleteArrayIfUnused(fc_output_split->outputs[3], model);\n string dims_array = fc_output_split->inputs[0];\n model->operators.erase(FindOperator(model, *fc_output_split));\n DeleteArrayIfUnused(dims_array, model);\n DeleteArrayIfUnused(fully_connected->outputs[0], model);\n model->operators.erase(FindOperator(model, *fully_connected));\n DeleteArrayIfUnused(concat_inputs->outputs[0], model);\n model->operators.erase(FindOperator(model, *concat_inputs));\n return true;\n}\n\n} \/\/ namespace toco\n<|endoftext|>"} {"text":"<commit_before>\/* Copyright 2019 The TensorFlow Authors. All Rights Reserved.\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*\/\n#include \"tensorflow\/core\/kernels\/data\/fixed_length_record_dataset_op.h\"\n\n#include \"tensorflow\/core\/kernels\/data\/dataset_test_base.h\"\n\nnamespace tensorflow {\nnamespace data {\nnamespace {\n\nconstexpr char kNodeName[] = \"fixed_length_record_dataset\";\nconstexpr int kOpVersion = 2;\n\nclass FixedLengthRecordDatasetParams : public DatasetParams {\n public:\n FixedLengthRecordDatasetParams(const std::vector<tstring>& filenames,\n int64 header_bytes, int64 record_bytes,\n int64 footer_bytes, int64 buffer_size,\n CompressionType compression_type,\n string node_name)\n : DatasetParams({DT_STRING}, {PartialTensorShape({})},\n std::move(node_name)),\n filenames_(filenames),\n header_bytes_(header_bytes),\n record_bytes_(record_bytes),\n footer_bytes_(footer_bytes),\n buffer_size_(buffer_size),\n compression_type_(compression_type) {\n op_version_ = 2;\n }\n\n std::vector<Tensor> GetInputTensors() const override {\n int num_files = filenames_.size();\n return {\n CreateTensor<tstring>(TensorShape({num_files}), filenames_),\n CreateTensor<int64>(TensorShape({}), {header_bytes_}),\n CreateTensor<int64>(TensorShape({}), {record_bytes_}),\n CreateTensor<int64>(TensorShape({}), {footer_bytes_}),\n CreateTensor<int64>(TensorShape({}), {buffer_size_}),\n CreateTensor<tstring>(TensorShape({}), {ToString(compression_type_)})};\n }\n\n Status GetInputNames(std::vector<string>* input_names) const override {\n input_names->clear();\n *input_names = {FixedLengthRecordDatasetOp::kFileNames,\n FixedLengthRecordDatasetOp::kHeaderBytes,\n FixedLengthRecordDatasetOp::kRecordBytes,\n FixedLengthRecordDatasetOp::kFooterBytes,\n FixedLengthRecordDatasetOp::kBufferSize,\n FixedLengthRecordDatasetOp::kCompressionType};\n return Status::OK();\n }\n\n Status GetAttributes(AttributeVector* attr_vector) const override {\n *attr_vector = {};\n return Status::OK();\n }\n\n string dataset_type() const override {\n return FixedLengthRecordDatasetOp::kDatasetType;\n }\n\n private:\n std::vector<tstring> filenames_;\n int64 header_bytes_;\n int64 record_bytes_;\n int64 footer_bytes_;\n int64 buffer_size_;\n CompressionType compression_type_;\n};\n\nclass FixedLengthRecordDatasetOpTest : public DatasetOpsTestBase {};\n\nStatus CreateTestFiles(const std::vector<tstring>& filenames,\n const std::vector<string>& contents,\n CompressionType compression_type) {\n if (filenames.size() != contents.size()) {\n return tensorflow::errors::InvalidArgument(\n \"The number of files does not match with the contents\");\n }\n if (compression_type == CompressionType::UNCOMPRESSED) {\n for (int i = 0; i < filenames.size(); ++i) {\n TF_RETURN_IF_ERROR(WriteDataToFile(filenames[i], contents[i].data()));\n }\n } else {\n CompressionParams params;\n params.output_buffer_size = 10;\n params.compression_type = compression_type;\n for (int i = 0; i < filenames.size(); ++i) {\n TF_RETURN_IF_ERROR(\n WriteDataToFile(filenames[i], contents[i].data(), params));\n }\n }\n return Status::OK();\n}\n\n\/\/ Test case 1: multiple fixed-length record files with ZLIB compression.\nFixedLengthRecordDatasetParams FixedLengthRecordDatasetParams1() {\n std::vector<tstring> filenames = {\n absl::StrCat(testing::TmpDir(), \"\/text_line_ZLIB_1\"),\n absl::StrCat(testing::TmpDir(), \"\/text_line_ZLIB_2\")};\n std::vector<string> contents = {\n absl::StrCat(\"HHHHH\", \"111\", \"222\", \"333\", \"FF\"),\n absl::StrCat(\"HHHHH\", \"aaa\", \"bbb\", \"FF\")};\n CompressionType compression_type = CompressionType::ZLIB;\n if (!CreateTestFiles(filenames, contents, compression_type).ok()) {\n VLOG(WARNING) << \"Failed to create the test files: \"\n << absl::StrJoin(filenames, \", \");\n }\n\n return FixedLengthRecordDatasetParams(filenames,\n \/*header_bytes=*\/5,\n \/*record_bytes=*\/3,\n \/*footer_bytes=*\/2,\n \/*buffer_size=*\/10,\n \/*compression_type=*\/compression_type,\n \/*node_name=*\/kNodeName);\n}\n\n\/\/ Test case 2: multiple fixed-length record files with GZIP compression.\nFixedLengthRecordDatasetParams FixedLengthRecordDatasetParams2() {\n std::vector<tstring> filenames = {\n absl::StrCat(testing::TmpDir(), \"\/text_line_GZIP_1\"),\n absl::StrCat(testing::TmpDir(), \"\/text_line_GZIP_2\")};\n std::vector<string> contents = {\n absl::StrCat(\"HHHHH\", \"111\", \"222\", \"333\", \"FF\"),\n absl::StrCat(\"HHHHH\", \"aaa\", \"bbb\", \"FF\")};\n CompressionType compression_type = CompressionType::GZIP;\n if (!CreateTestFiles(filenames, contents, compression_type).ok()) {\n VLOG(WARNING) << \"Failed to create the test files: \"\n << absl::StrJoin(filenames, \", \");\n }\n return FixedLengthRecordDatasetParams(filenames,\n \/*header_bytes=*\/5,\n \/*record_bytes=*\/3,\n \/*footer_bytes=*\/2,\n \/*buffer_size=*\/10,\n \/*compression_type=*\/compression_type,\n \/*node_name=*\/kNodeName);\n}\n\n\/\/ Test case 3: multiple fixed-length record files without compression.\nFixedLengthRecordDatasetParams FixedLengthRecordDatasetParams3() {\n std::vector<tstring> filenames = {\n absl::StrCat(testing::TmpDir(), \"\/text_line_UNCOMPRESSED_1\"),\n absl::StrCat(testing::TmpDir(), \"\/text_line_UNCOMPRESSED_2\")};\n std::vector<string> contents = {\n absl::StrCat(\"HHHHH\", \"111\", \"222\", \"333\", \"FF\"),\n absl::StrCat(\"HHHHH\", \"aaa\", \"bbb\", \"FF\")};\n CompressionType compression_type = CompressionType::UNCOMPRESSED;\n if (!CreateTestFiles(filenames, contents, compression_type).ok()) {\n VLOG(WARNING) << \"Failed to create the test files: \"\n << absl::StrJoin(filenames, \", \");\n }\n return FixedLengthRecordDatasetParams(filenames,\n \/*header_bytes=*\/5,\n \/*record_bytes=*\/3,\n \/*footer_bytes=*\/2,\n \/*buffer_size=*\/10,\n \/*compression_type=*\/compression_type,\n \/*node_name=*\/kNodeName);\n}\n\nstd::vector<GetNextTestCase<FixedLengthRecordDatasetParams>>\nGetNextTestCases() {\n return {\n {\/*dataset_params=*\/FixedLengthRecordDatasetParams1(),\n \/*expected_outputs=*\/\n CreateTensors<tstring>(TensorShape({}),\n {{\"111\"}, {\"222\"}, {\"333\"}, {\"aaa\"}, {\"bbb\"}})},\n {\/*dataset_params=*\/FixedLengthRecordDatasetParams2(),\n CreateTensors<tstring>(TensorShape({}),\n {{\"111\"}, {\"222\"}, {\"333\"}, {\"aaa\"}, {\"bbb\"}})},\n {\/*dataset_params=*\/FixedLengthRecordDatasetParams3(),\n CreateTensors<tstring>(TensorShape({}),\n {{\"111\"}, {\"222\"}, {\"333\"}, {\"aaa\"}, {\"bbb\"}})}};\n}\n\nITERATOR_GET_NEXT_TEST_P(FixedLengthRecordDatasetOpTest,\n FixedLengthRecordDatasetParams, GetNextTestCases())\n\nTEST_F(FixedLengthRecordDatasetOpTest, DatasetNodeName) {\n auto dataset_params = FixedLengthRecordDatasetParams1();\n TF_ASSERT_OK(Initialize(dataset_params));\n TF_ASSERT_OK(CheckDatasetNodeName(dataset_params.node_name()));\n}\n\nTEST_F(FixedLengthRecordDatasetOpTest, DatasetTypeString) {\n auto dataset_params = FixedLengthRecordDatasetParams1();\n TF_ASSERT_OK(Initialize(dataset_params));\n name_utils::OpNameParams params;\n params.op_version = kOpVersion;\n TF_ASSERT_OK(CheckDatasetTypeString(\n name_utils::OpName(FixedLengthRecordDatasetOp::kDatasetType, params)));\n}\n\nTEST_F(FixedLengthRecordDatasetOpTest, DatasetOutputDtypes) {\n auto dataset_params = FixedLengthRecordDatasetParams1();\n TF_ASSERT_OK(Initialize(dataset_params));\n TF_ASSERT_OK(CheckDatasetOutputDtypes({DT_STRING}));\n}\n\nTEST_F(FixedLengthRecordDatasetOpTest, DatasetOutputShapes) {\n auto dataset_params = FixedLengthRecordDatasetParams1();\n TF_ASSERT_OK(Initialize(dataset_params));\n TF_ASSERT_OK(CheckDatasetOutputShapes({PartialTensorShape({})}));\n}\n\nTEST_F(FixedLengthRecordDatasetOpTest, Cardinality) {\n auto dataset_params = FixedLengthRecordDatasetParams1();\n TF_ASSERT_OK(Initialize(dataset_params));\n TF_ASSERT_OK(CheckDatasetCardinality(kUnknownCardinality));\n}\n\nTEST_F(FixedLengthRecordDatasetOpTest, IteratorOutputDtypes) {\n auto dataset_params = FixedLengthRecordDatasetParams1();\n TF_ASSERT_OK(Initialize(dataset_params));\n TF_ASSERT_OK(CheckIteratorOutputDtypes({DT_STRING}));\n}\n\nTEST_F(FixedLengthRecordDatasetOpTest, IteratorOutputShapes) {\n auto dataset_params = FixedLengthRecordDatasetParams1();\n TF_ASSERT_OK(Initialize(dataset_params));\n TF_ASSERT_OK(CheckIteratorOutputShapes({PartialTensorShape({})}));\n}\n\nTEST_F(FixedLengthRecordDatasetOpTest, IteratorPrefix) {\n auto dataset_params = FixedLengthRecordDatasetParams1();\n TF_ASSERT_OK(Initialize(dataset_params));\n name_utils::IteratorPrefixParams iterator_prefix_params;\n iterator_prefix_params.op_version = kOpVersion;\n TF_ASSERT_OK(CheckIteratorPrefix(name_utils::IteratorPrefix(\n FixedLengthRecordDatasetOp::kDatasetType,\n dataset_params.iterator_prefix(), iterator_prefix_params)));\n}\n\nstd::vector<IteratorSaveAndRestoreTestCase<FixedLengthRecordDatasetParams>>\nIteratorSaveAndRestoreTestCases() {\n return {\n {\/*dataset_params=*\/FixedLengthRecordDatasetParams1(),\n \/*breakpoints=*\/{0, 2, 6},\n \/*expected_outputs=*\/\n CreateTensors<tstring>(TensorShape({}),\n {{\"111\"}, {\"222\"}, {\"333\"}, {\"aaa\"}, {\"bbb\"}})},\n {\/*dataset_params=*\/FixedLengthRecordDatasetParams2(),\n \/*breakpoints=*\/{0, 2, 6},\n CreateTensors<tstring>(TensorShape({}),\n {{\"111\"}, {\"222\"}, {\"333\"}, {\"aaa\"}, {\"bbb\"}})},\n {\/*dataset_params=*\/FixedLengthRecordDatasetParams3(),\n \/*breakpoints=*\/{0, 2, 6},\n CreateTensors<tstring>(TensorShape({}),\n {{\"111\"}, {\"222\"}, {\"333\"}, {\"aaa\"}, {\"bbb\"}})}};\n}\n\nITERATOR_SAVE_AND_RESTORE_TEST_P(FixedLengthRecordDatasetOpTest,\n FixedLengthRecordDatasetParams,\n IteratorSaveAndRestoreTestCases())\n\n} \/\/ namespace\n} \/\/ namespace data\n} \/\/ namespace tensorflow\n<commit_msg>Use Env::LocalTempFilename for a temp filename.<commit_after>\/* Copyright 2019 The TensorFlow Authors. All Rights Reserved.\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*\/\n#include \"tensorflow\/core\/kernels\/data\/fixed_length_record_dataset_op.h\"\n\n#include \"tensorflow\/core\/kernels\/data\/dataset_test_base.h\"\n\nnamespace tensorflow {\nnamespace data {\nnamespace {\n\nconstexpr char kNodeName[] = \"fixed_length_record_dataset\";\nconstexpr int kOpVersion = 2;\n\ntstring LocalTempFilename() {\n std::string path;\n CHECK(Env::Default()->LocalTempFilename(&path));\n return tstring(path);\n}\n\nclass FixedLengthRecordDatasetParams : public DatasetParams {\n public:\n FixedLengthRecordDatasetParams(const std::vector<tstring>& filenames,\n int64 header_bytes, int64 record_bytes,\n int64 footer_bytes, int64 buffer_size,\n CompressionType compression_type,\n string node_name)\n : DatasetParams({DT_STRING}, {PartialTensorShape({})},\n std::move(node_name)),\n filenames_(filenames),\n header_bytes_(header_bytes),\n record_bytes_(record_bytes),\n footer_bytes_(footer_bytes),\n buffer_size_(buffer_size),\n compression_type_(compression_type) {\n op_version_ = 2;\n }\n\n std::vector<Tensor> GetInputTensors() const override {\n int num_files = filenames_.size();\n return {\n CreateTensor<tstring>(TensorShape({num_files}), filenames_),\n CreateTensor<int64>(TensorShape({}), {header_bytes_}),\n CreateTensor<int64>(TensorShape({}), {record_bytes_}),\n CreateTensor<int64>(TensorShape({}), {footer_bytes_}),\n CreateTensor<int64>(TensorShape({}), {buffer_size_}),\n CreateTensor<tstring>(TensorShape({}), {ToString(compression_type_)})};\n }\n\n Status GetInputNames(std::vector<string>* input_names) const override {\n input_names->clear();\n *input_names = {FixedLengthRecordDatasetOp::kFileNames,\n FixedLengthRecordDatasetOp::kHeaderBytes,\n FixedLengthRecordDatasetOp::kRecordBytes,\n FixedLengthRecordDatasetOp::kFooterBytes,\n FixedLengthRecordDatasetOp::kBufferSize,\n FixedLengthRecordDatasetOp::kCompressionType};\n return Status::OK();\n }\n\n Status GetAttributes(AttributeVector* attr_vector) const override {\n *attr_vector = {};\n return Status::OK();\n }\n\n string dataset_type() const override {\n return FixedLengthRecordDatasetOp::kDatasetType;\n }\n\n private:\n std::vector<tstring> filenames_;\n int64 header_bytes_;\n int64 record_bytes_;\n int64 footer_bytes_;\n int64 buffer_size_;\n CompressionType compression_type_;\n};\n\nclass FixedLengthRecordDatasetOpTest : public DatasetOpsTestBase {};\n\nStatus CreateTestFiles(const std::vector<tstring>& filenames,\n const std::vector<string>& contents,\n CompressionType compression_type) {\n if (filenames.size() != contents.size()) {\n return tensorflow::errors::InvalidArgument(\n \"The number of files does not match with the contents\");\n }\n if (compression_type == CompressionType::UNCOMPRESSED) {\n for (int i = 0; i < filenames.size(); ++i) {\n TF_RETURN_IF_ERROR(WriteDataToFile(filenames[i], contents[i].data()));\n }\n } else {\n CompressionParams params;\n params.output_buffer_size = 10;\n params.compression_type = compression_type;\n for (int i = 0; i < filenames.size(); ++i) {\n TF_RETURN_IF_ERROR(\n WriteDataToFile(filenames[i], contents[i].data(), params));\n }\n }\n return Status::OK();\n}\n\n\/\/ Test case 1: multiple fixed-length record files with ZLIB compression.\nFixedLengthRecordDatasetParams FixedLengthRecordDatasetParams1() {\n std::vector<tstring> filenames = {LocalTempFilename(), LocalTempFilename()};\n std::vector<string> contents = {\n absl::StrCat(\"HHHHH\", \"111\", \"222\", \"333\", \"FF\"),\n absl::StrCat(\"HHHHH\", \"aaa\", \"bbb\", \"FF\")};\n CompressionType compression_type = CompressionType::ZLIB;\n if (!CreateTestFiles(filenames, contents, compression_type).ok()) {\n VLOG(WARNING) << \"Failed to create the test files: \"\n << absl::StrJoin(filenames, \", \");\n }\n\n return FixedLengthRecordDatasetParams(filenames,\n \/*header_bytes=*\/5,\n \/*record_bytes=*\/3,\n \/*footer_bytes=*\/2,\n \/*buffer_size=*\/10,\n \/*compression_type=*\/compression_type,\n \/*node_name=*\/kNodeName);\n}\n\n\/\/ Test case 2: multiple fixed-length record files with GZIP compression.\nFixedLengthRecordDatasetParams FixedLengthRecordDatasetParams2() {\n std::vector<tstring> filenames = {LocalTempFilename(), LocalTempFilename()};\n std::vector<string> contents = {\n absl::StrCat(\"HHHHH\", \"111\", \"222\", \"333\", \"FF\"),\n absl::StrCat(\"HHHHH\", \"aaa\", \"bbb\", \"FF\")};\n CompressionType compression_type = CompressionType::GZIP;\n if (!CreateTestFiles(filenames, contents, compression_type).ok()) {\n VLOG(WARNING) << \"Failed to create the test files: \"\n << absl::StrJoin(filenames, \", \");\n }\n return FixedLengthRecordDatasetParams(filenames,\n \/*header_bytes=*\/5,\n \/*record_bytes=*\/3,\n \/*footer_bytes=*\/2,\n \/*buffer_size=*\/10,\n \/*compression_type=*\/compression_type,\n \/*node_name=*\/kNodeName);\n}\n\n\/\/ Test case 3: multiple fixed-length record files without compression.\nFixedLengthRecordDatasetParams FixedLengthRecordDatasetParams3() {\n std::vector<tstring> filenames = {LocalTempFilename(), LocalTempFilename()};\n std::vector<string> contents = {\n absl::StrCat(\"HHHHH\", \"111\", \"222\", \"333\", \"FF\"),\n absl::StrCat(\"HHHHH\", \"aaa\", \"bbb\", \"FF\")};\n CompressionType compression_type = CompressionType::UNCOMPRESSED;\n if (!CreateTestFiles(filenames, contents, compression_type).ok()) {\n VLOG(WARNING) << \"Failed to create the test files: \"\n << absl::StrJoin(filenames, \", \");\n }\n return FixedLengthRecordDatasetParams(filenames,\n \/*header_bytes=*\/5,\n \/*record_bytes=*\/3,\n \/*footer_bytes=*\/2,\n \/*buffer_size=*\/10,\n \/*compression_type=*\/compression_type,\n \/*node_name=*\/kNodeName);\n}\n\nstd::vector<GetNextTestCase<FixedLengthRecordDatasetParams>>\nGetNextTestCases() {\n return {\n {\/*dataset_params=*\/FixedLengthRecordDatasetParams1(),\n \/*expected_outputs=*\/\n CreateTensors<tstring>(TensorShape({}),\n {{\"111\"}, {\"222\"}, {\"333\"}, {\"aaa\"}, {\"bbb\"}})},\n {\/*dataset_params=*\/FixedLengthRecordDatasetParams2(),\n CreateTensors<tstring>(TensorShape({}),\n {{\"111\"}, {\"222\"}, {\"333\"}, {\"aaa\"}, {\"bbb\"}})},\n {\/*dataset_params=*\/FixedLengthRecordDatasetParams3(),\n CreateTensors<tstring>(TensorShape({}),\n {{\"111\"}, {\"222\"}, {\"333\"}, {\"aaa\"}, {\"bbb\"}})}};\n}\n\nITERATOR_GET_NEXT_TEST_P(FixedLengthRecordDatasetOpTest,\n FixedLengthRecordDatasetParams, GetNextTestCases())\n\nTEST_F(FixedLengthRecordDatasetOpTest, DatasetNodeName) {\n auto dataset_params = FixedLengthRecordDatasetParams1();\n TF_ASSERT_OK(Initialize(dataset_params));\n TF_ASSERT_OK(CheckDatasetNodeName(dataset_params.node_name()));\n}\n\nTEST_F(FixedLengthRecordDatasetOpTest, DatasetTypeString) {\n auto dataset_params = FixedLengthRecordDatasetParams1();\n TF_ASSERT_OK(Initialize(dataset_params));\n name_utils::OpNameParams params;\n params.op_version = kOpVersion;\n TF_ASSERT_OK(CheckDatasetTypeString(\n name_utils::OpName(FixedLengthRecordDatasetOp::kDatasetType, params)));\n}\n\nTEST_F(FixedLengthRecordDatasetOpTest, DatasetOutputDtypes) {\n auto dataset_params = FixedLengthRecordDatasetParams1();\n TF_ASSERT_OK(Initialize(dataset_params));\n TF_ASSERT_OK(CheckDatasetOutputDtypes({DT_STRING}));\n}\n\nTEST_F(FixedLengthRecordDatasetOpTest, DatasetOutputShapes) {\n auto dataset_params = FixedLengthRecordDatasetParams1();\n TF_ASSERT_OK(Initialize(dataset_params));\n TF_ASSERT_OK(CheckDatasetOutputShapes({PartialTensorShape({})}));\n}\n\nTEST_F(FixedLengthRecordDatasetOpTest, Cardinality) {\n auto dataset_params = FixedLengthRecordDatasetParams1();\n TF_ASSERT_OK(Initialize(dataset_params));\n TF_ASSERT_OK(CheckDatasetCardinality(kUnknownCardinality));\n}\n\nTEST_F(FixedLengthRecordDatasetOpTest, IteratorOutputDtypes) {\n auto dataset_params = FixedLengthRecordDatasetParams1();\n TF_ASSERT_OK(Initialize(dataset_params));\n TF_ASSERT_OK(CheckIteratorOutputDtypes({DT_STRING}));\n}\n\nTEST_F(FixedLengthRecordDatasetOpTest, IteratorOutputShapes) {\n auto dataset_params = FixedLengthRecordDatasetParams1();\n TF_ASSERT_OK(Initialize(dataset_params));\n TF_ASSERT_OK(CheckIteratorOutputShapes({PartialTensorShape({})}));\n}\n\nTEST_F(FixedLengthRecordDatasetOpTest, IteratorPrefix) {\n auto dataset_params = FixedLengthRecordDatasetParams1();\n TF_ASSERT_OK(Initialize(dataset_params));\n name_utils::IteratorPrefixParams iterator_prefix_params;\n iterator_prefix_params.op_version = kOpVersion;\n TF_ASSERT_OK(CheckIteratorPrefix(name_utils::IteratorPrefix(\n FixedLengthRecordDatasetOp::kDatasetType,\n dataset_params.iterator_prefix(), iterator_prefix_params)));\n}\n\nstd::vector<IteratorSaveAndRestoreTestCase<FixedLengthRecordDatasetParams>>\nIteratorSaveAndRestoreTestCases() {\n return {\n {\/*dataset_params=*\/FixedLengthRecordDatasetParams1(),\n \/*breakpoints=*\/{0, 2, 6},\n \/*expected_outputs=*\/\n CreateTensors<tstring>(TensorShape({}),\n {{\"111\"}, {\"222\"}, {\"333\"}, {\"aaa\"}, {\"bbb\"}})},\n {\/*dataset_params=*\/FixedLengthRecordDatasetParams2(),\n \/*breakpoints=*\/{0, 2, 6},\n CreateTensors<tstring>(TensorShape({}),\n {{\"111\"}, {\"222\"}, {\"333\"}, {\"aaa\"}, {\"bbb\"}})},\n {\/*dataset_params=*\/FixedLengthRecordDatasetParams3(),\n \/*breakpoints=*\/{0, 2, 6},\n CreateTensors<tstring>(TensorShape({}),\n {{\"111\"}, {\"222\"}, {\"333\"}, {\"aaa\"}, {\"bbb\"}})}};\n}\n\nITERATOR_SAVE_AND_RESTORE_TEST_P(FixedLengthRecordDatasetOpTest,\n FixedLengthRecordDatasetParams,\n IteratorSaveAndRestoreTestCases())\n\n} \/\/ namespace\n} \/\/ namespace data\n} \/\/ namespace tensorflow\n<|endoftext|>"} {"text":"<commit_before>\n#include <cstdio>\n#include <functional>\n#include <map>\n#include <queue>\n#include <string>\n#include <vector>\n#include <utility>\n\n#include \"Eigen\/Dense\"\n#include \"math\/math.h\"\n#include \"nn\/nn_analysis.h\"\n#include \"nn\/dnn.h\"\n#include \"nn\/dnn2.h\"\n#include \"nn\/dnn3.h\"\n#include \"rng\/well_1024.h\"\n#include \"rng\/normal.h\"\n#include \"util\/timer.h\"\n#include \"util\/mnist.h\"\n\nusing Eigen::Matrix;\nusing Eigen::Dynamic;\nusing nn::NN_Analyzer;\nusing nn::DNN;\nusing nn::DNN2;\nusing nn::DNN3;\nusing rng::Well_1024;\nusing rng::Random;\nusing rng::Normal;\nusing std::greater;\nusing std::map;\nusing std::multimap;\nusing std::pair;\nusing std::priority_queue;\nusing std::string;\nusing std::vector;\nusing util::MNIST;\nusing util::Timer;\n\nint main ( int argc, char *argv[] ) {\n\n\/\/ -------------------------------------------------------------\n\/\/ Begin Configuration Parameters\n\n const int size_in = 784;\n const int size_h1 = 392;\n const int size_h2 = 0;\n const int size_h3 = 0;\n const int size_h4 = 0;\n const int size_out = 10;\n const int size_mini_batch = 100;\n const int max_num_mini_batch = -1;\n const int size_validation = 1000;\n const float lambda = 0.0e-0;\n const float learning_rate_rbm = 0.05;\n const float learning_rate_bp = 0.1;\n const float momentum_rbm = 0.50;\n const float momentum_bp = 0.5;\n const int rbm_epochs = 10;\n const int bp_epochs = 20;\n int depth_rbm = -1;\n int depth_bp = -1;\n int replicas = 1;\n const int seed = 17439073;\n \/\/const int seed = 508203299;\n\n const string train_data_file = \"data\/train-images-idx3-ubyte\";\n const string train_labels_file = \"data\/train-labels-idx1-ubyte\";\n const string test_data_file = \"data\/t10k-images-idx3-ubyte\";\n const string test_labels_file = \"data\/t10k-labels-idx1-ubyte\";\n\n printf(\"#size_in: %d\\n\",size_in);\n printf(\"#size_h1: %d\\n\",size_h1);\n printf(\"#size_h2: %d\\n\",size_h2);\n printf(\"#size_h3: %d\\n\",size_h3);\n printf(\"#size_h4: %d\\n\",size_h4);\n printf(\"#size_out: %d\\n\",size_out);\n printf(\"#size_mini_batch: %d\\n\",size_mini_batch);\n printf(\"#max_num_mini_batch: %d\\n\",max_num_mini_batch);\n printf(\"#size_validation: %d\\n\",size_validation);\n printf(\"#lambda: %f\\n\",lambda);\n printf(\"#learning rate BP: %f\\n\",learning_rate_bp);\n printf(\"#learning rate RBM: %f\\n\",learning_rate_rbm);\n printf(\"#momentum BP: %f\\n\",momentum_bp);\n printf(\"#momentum RBM: %f\\n\",momentum_rbm);\n printf(\"#BP epoch: %d\\n\",bp_epochs);\n printf(\"#RBM epoch: %d\\n\",rbm_epochs);\n printf(\"#depth BP: %d\\n\",depth_bp);\n printf(\"#depth RBM: %d\\n\",depth_rbm);\n printf(\"#number of data distortions: %d\\n\",replicas);\n printf(\"#seed: %d\\n\",seed);\n\n\/\/ End Configuration Parameters\n\/\/ -------------------------------------------------------------\n\n \/\/ read in the data\n\n fprintf(stderr,\"Creating data...\\n\");\n MNIST<float> mnist_data( train_data_file, train_labels_file, \n test_data_file, test_labels_file );\n\n\n \/\/ create the mini-batches used for training\n\n Well_1024 rand(seed);\n\n vector<Matrix<float,Dynamic,Dynamic>> mini_batch_inputs;\n vector<Matrix<float,Dynamic,Dynamic>> mini_batch_outputs;\n\n mnist_data.get_mini_batches( size_mini_batch, replicas, \n max_num_mini_batch, rand,\n mini_batch_inputs, mini_batch_outputs );\n\n int num_mini_batch = mini_batch_inputs.size();\n fprintf(stderr,\"Number of mini batches: %d\\n\",num_mini_batch);\n vector<int> schedule;\n for ( int i = 0; i < num_mini_batch; ++i ) schedule.push_back(i); \n\n rng::shuffle( schedule.begin(), schedule.end(), rand );\n\n \/\/ get a subset of the test data for testing\n\n Matrix<float,Dynamic,Dynamic> val_inputs;\n Matrix<float,Dynamic,Dynamic> val_outputs;\n\n int num_validation = size_validation;\n mnist_data.get_validation_set( num_validation, rand,\n val_inputs, val_outputs );\n\n\n \/\/ create the network\n\n vector<unsigned> layers;\n layers.push_back( size_in );\n layers.push_back( size_h1 );\n if ( size_h2 > 0 ) layers.push_back( size_h2 );\n if ( size_h3 > 0 ) layers.push_back( size_h3 );\n if ( size_h4 > 0 ) layers.push_back( size_h4 );\n layers.push_back( size_out );\n\n fprintf(stderr,\"Creating network...\\n\");\n DNN<math::logistic<float>> dnn( layers );\n \/\/DNN<math::tanh<float>> dnn( layers );\n \/\/DNN2<float> dnn( size_in, size_h1, size_out );\n \/\/DNN3<float> dnn( size_in, size_h1, size_h2, size_out );\n\n fprintf(stdout,\"#Number of neuron layers: %d\\n\",\n dnn.get_num_neuron_layers());\n fprintf(stdout,\"#Number of weight layers: %d\\n\",\n dnn.get_num_weight_layers());\n\n if ( depth_bp == -1 ) {\n depth_bp = dnn.get_num_weight_layers();\n }\n if ( depth_rbm == -1 ) {\n depth_rbm = dnn.get_num_weight_layers() - 1;\n }\n\n Normal normal( &rand );\n fprintf(stderr,\"initialize network...\\n\");\n dnn.init( normal );\n \/\/dnn.init( rand );\n\n double loss = 0.0;\n double val_loss = 0.0;\n\n\n \/\/ perform the RBM learning for the first depth_rbm number of layers\n \/\/ (count from the first layer)\n fprintf(stderr,\"start RBM learning ...\\n\");\n\n int mb_count = 0;\n\n vector<Matrix<float,Dynamic,Dynamic>> rbm_mini_batches;\n\n for ( int drbm = 0; drbm < depth_rbm; ++drbm ) {\n\n fprintf(stderr,\"sampling ...\\n\");\n dnn.sample_states( drbm, rand, mini_batch_inputs, rbm_mini_batches );\n\n double var_lr = learning_rate_rbm;\n double var_mom = momentum_rbm;\n\n fprintf(stdout,\"#weights: %d\\n\",drbm);\n for ( int step = 0; step < rbm_epochs*num_mini_batch; ++step ) {\n int mb = schedule[mb_count];\n\n loss = dnn.cd1( drbm, var_lr, var_mom, rand, rbm_mini_batches[mb] );\n fprintf(stdout,\"%5d %f \\n\", step, loss);\n\n var_mom *= 1.0003;\n if ( var_mom > 0.90 ) var_mom = 0.90;\n \/\/var_lr *= 0.9993;\n \/\/if ( var_lr < 0.01 ) var_lr = 0.01;\n\n ++mb_count;\n if ( mb_count == num_mini_batch ) {\n mb_count = 0;\n rng::shuffle( schedule.begin(), schedule.end(), rand ); \n }\n\n }\n fprintf(stdout,\"\\n#weights: %d\\n\",drbm);\n\n }\n\/*\n*\/\n\n fprintf(stderr,\"start BP learning ...\\n\");\n\n mb_count = 0;\n double var_lr = learning_rate_bp;\n double var_mom = momentum_bp;\n \/\/dnn.reset_mom();\n for ( int step = 0; step < bp_epochs*num_mini_batch; ++step ) {\n\n int mb = schedule[mb_count];\n\n \/\/ perform the BP learning for the depth_bp number of layers (counting\n \/\/ from the last layer)\n\n loss = dnn.back_prop( var_lr, var_mom, lambda, depth_bp,\n mini_batch_inputs[mb], \n mini_batch_outputs[mb] );\n\n if ( (step % 500 ) == 0 ) {\n val_loss = dnn.loss( val_inputs, val_outputs, 0.0 ); \n }\n fprintf(stdout,\"%5d %f %f\\n\", step, loss, val_loss);\n\n ++mb_count;\n if ( mb_count == num_mini_batch ) {\n mb_count = 0;\n rng::shuffle( schedule.begin(), schedule.end(), rand ); \n }\n\n var_mom *= 1.0003;\n if ( var_mom > 0.95 ) var_mom = 0.95;\n\/\/ var_lr *= 0.9999;\n \/\/ if ( var_lr < 0.001 ) var_lr = 0.001;\n\n }\n\n \/\/ Determine how well the network performs on all the test data.\n\n fprintf(stderr,\"start Testing phase ...\\n\");\n\n num_validation = -1;\n mnist_data.get_validation_set( num_validation, rand,\n val_inputs, val_outputs );\n\n val_loss = dnn.loss( val_inputs, val_outputs, 0.0 ); \n fprintf(stdout,\"#final val: loss %f\\n\", val_loss);\n\n Matrix<float,Dynamic,Dynamic> pred_outputs;\n\n dnn.forward_prop( val_inputs, pred_outputs );\n\n vector<double> val_error = \n NN_Analyzer::Error_Analyis( pred_outputs, val_outputs );\n for (size_t r = 0; r < val_error.size(); ++r ) {\n fprintf(stdout,\"#%2zd %f\\n\", r, val_error[r]);\n }\n\n fprintf(stdout,\"#final error: %f\\n\", (1.0-val_error[val_error.size()-1]));\n\n}\n<commit_msg>minor correction in main.cc<commit_after>\n#include <cstdio>\n#include <functional>\n#include <map>\n#include <queue>\n#include <string>\n#include <vector>\n#include <utility>\n\n#include \"Eigen\/Dense\"\n#include \"math\/math.h\"\n#include \"nn\/nn_analysis.h\"\n#include \"nn\/dnn.h\"\n#include \"nn\/dnn2.h\"\n#include \"nn\/dnn3.h\"\n#include \"rng\/well_1024.h\"\n#include \"rng\/normal.h\"\n#include \"util\/timer.h\"\n#include \"util\/mnist.h\"\n\nusing Eigen::Matrix;\nusing Eigen::Dynamic;\nusing nn::NN_Analyzer;\nusing nn::DNN;\nusing nn::DNN2;\nusing nn::DNN3;\nusing rng::Well_1024;\nusing rng::Random;\nusing rng::Normal;\nusing std::greater;\nusing std::map;\nusing std::multimap;\nusing std::pair;\nusing std::priority_queue;\nusing std::string;\nusing std::vector;\nusing util::MNIST;\nusing util::Timer;\n\nint main ( int argc, char *argv[] ) {\n\n\/\/ -------------------------------------------------------------\n\/\/ Begin Configuration Parameters\n\n const int size_in = 784;\n const int size_h1 = 392;\n const int size_h2 = 0;\n const int size_h3 = 0;\n const int size_h4 = 0;\n const int size_out = 10;\n const int size_mini_batch = 100;\n const int max_num_mini_batch = -1;\n const int size_validation = 1000;\n const float lambda = 0.0e-0;\n const float learning_rate_rbm = 0.05;\n const float learning_rate_bp = 0.5;\n const float momentum_rbm = 0.50;\n const float momentum_bp = 0.5;\n const int rbm_epochs = 10;\n const int bp_epochs = 20;\n int depth_rbm = -1;\n int depth_bp = -1;\n int replicas = 1;\n const int seed = 17439073;\n \/\/const int seed = 508203299;\n\n const string train_data_file = \"data\/train-images-idx3-ubyte\";\n const string train_labels_file = \"data\/train-labels-idx1-ubyte\";\n const string test_data_file = \"data\/t10k-images-idx3-ubyte\";\n const string test_labels_file = \"data\/t10k-labels-idx1-ubyte\";\n\n printf(\"#size_in: %d\\n\",size_in);\n printf(\"#size_h1: %d\\n\",size_h1);\n printf(\"#size_h2: %d\\n\",size_h2);\n printf(\"#size_h3: %d\\n\",size_h3);\n printf(\"#size_h4: %d\\n\",size_h4);\n printf(\"#size_out: %d\\n\",size_out);\n printf(\"#size_mini_batch: %d\\n\",size_mini_batch);\n printf(\"#max_num_mini_batch: %d\\n\",max_num_mini_batch);\n printf(\"#size_validation: %d\\n\",size_validation);\n printf(\"#lambda: %f\\n\",lambda);\n printf(\"#learning rate BP: %f\\n\",learning_rate_bp);\n printf(\"#learning rate RBM: %f\\n\",learning_rate_rbm);\n printf(\"#momentum BP: %f\\n\",momentum_bp);\n printf(\"#momentum RBM: %f\\n\",momentum_rbm);\n printf(\"#BP epoch: %d\\n\",bp_epochs);\n printf(\"#RBM epoch: %d\\n\",rbm_epochs);\n printf(\"#depth BP: %d\\n\",depth_bp);\n printf(\"#depth RBM: %d\\n\",depth_rbm);\n printf(\"#number of data distortions: %d\\n\",replicas);\n printf(\"#seed: %d\\n\",seed);\n\n\/\/ End Configuration Parameters\n\/\/ -------------------------------------------------------------\n\n \/\/ read in the data\n\n fprintf(stderr,\"Creating data...\\n\");\n MNIST<float> mnist_data( train_data_file, train_labels_file, \n test_data_file, test_labels_file );\n\n\n \/\/ create the mini-batches used for training\n\n Well_1024 rand(seed);\n\n vector<Matrix<float,Dynamic,Dynamic>> mini_batch_inputs;\n vector<Matrix<float,Dynamic,Dynamic>> mini_batch_outputs;\n\n mnist_data.get_mini_batches( size_mini_batch, replicas, \n max_num_mini_batch, rand,\n mini_batch_inputs, mini_batch_outputs );\n\n int num_mini_batch = mini_batch_inputs.size();\n fprintf(stderr,\"Number of mini batches: %d\\n\",num_mini_batch);\n vector<int> schedule;\n for ( int i = 0; i < num_mini_batch; ++i ) schedule.push_back(i); \n\n rng::shuffle( schedule.begin(), schedule.end(), rand );\n\n \/\/ get a subset of the test data for testing\n\n Matrix<float,Dynamic,Dynamic> val_inputs;\n Matrix<float,Dynamic,Dynamic> val_outputs;\n\n int num_validation = size_validation;\n mnist_data.get_validation_set( num_validation, rand,\n val_inputs, val_outputs );\n\n\n \/\/ create the network\n\n vector<unsigned> layers;\n layers.push_back( size_in );\n layers.push_back( size_h1 );\n if ( size_h2 > 0 ) layers.push_back( size_h2 );\n if ( size_h3 > 0 ) layers.push_back( size_h3 );\n if ( size_h4 > 0 ) layers.push_back( size_h4 );\n layers.push_back( size_out );\n\n fprintf(stderr,\"Creating network...\\n\");\n DNN<math::logistic<float>> dnn( layers );\n \/\/DNN<math::tanh<float>> dnn( layers );\n \/\/DNN2<float> dnn( size_in, size_h1, size_out );\n \/\/DNN3<float> dnn( size_in, size_h1, size_h2, size_out );\n\n fprintf(stdout,\"#Number of neuron layers: %d\\n\",\n dnn.get_num_neuron_layers());\n fprintf(stdout,\"#Number of weight layers: %d\\n\",\n dnn.get_num_weight_layers());\n\n if ( depth_bp == -1 ) {\n depth_bp = dnn.get_num_weight_layers();\n }\n if ( depth_rbm == -1 ) {\n depth_rbm = dnn.get_num_weight_layers() - 1;\n }\n\n Normal normal( &rand );\n fprintf(stderr,\"initialize network...\\n\");\n dnn.init( normal );\n \/\/dnn.init( rand );\n\n double loss = 0.0;\n double val_loss = 0.0;\n\n\n \/\/ perform the RBM learning for the first depth_rbm number of layers\n \/\/ (count from the first layer)\n fprintf(stderr,\"start RBM learning ...\\n\");\n\n int mb_count = 0;\n\n vector<Matrix<float,Dynamic,Dynamic>> rbm_mini_batches;\n\n for ( int drbm = 0; drbm < depth_rbm; ++drbm ) {\n\n fprintf(stderr,\"sampling ...\\n\");\n dnn.sample_states( drbm, rand, mini_batch_inputs, rbm_mini_batches );\n\n double var_lr = learning_rate_rbm;\n double var_mom = momentum_rbm;\n\n fprintf(stdout,\"#weights: %d\\n\",drbm);\n for ( int step = 0; step < rbm_epochs*num_mini_batch; ++step ) {\n int mb = schedule[mb_count];\n\n loss = dnn.cd1( drbm, var_lr, var_mom, rand, rbm_mini_batches[mb] );\n fprintf(stdout,\"%5d %f \\n\", step, loss);\n\n var_mom *= 1.0003;\n if ( var_mom > 0.90 ) var_mom = 0.90;\n \/\/var_lr *= 0.9993;\n \/\/if ( var_lr < 0.01 ) var_lr = 0.01;\n\n ++mb_count;\n if ( mb_count == num_mini_batch ) {\n mb_count = 0;\n rng::shuffle( schedule.begin(), schedule.end(), rand ); \n }\n\n }\n fprintf(stdout,\"\\n#weights: %d\\n\",drbm);\n\n }\n\/*\n*\/\n\n fprintf(stderr,\"start BP learning ...\\n\");\n\n mb_count = 0;\n double var_lr = learning_rate_bp;\n double var_mom = momentum_bp;\n \/\/dnn.reset_mom();\n for ( int step = 0; step < bp_epochs*num_mini_batch; ++step ) {\n\n int mb = schedule[mb_count];\n\n \/\/ perform the BP learning for the depth_bp number of layers (counting\n \/\/ from the last layer)\n\n loss = dnn.back_prop( var_lr, var_mom, lambda, depth_bp,\n mini_batch_inputs[mb], \n mini_batch_outputs[mb] );\n\n if ( (step % 500 ) == 0 ) {\n val_loss = dnn.loss( val_inputs, val_outputs, 0.0 ); \n }\n fprintf(stdout,\"%5d %f %f\\n\", step, loss, val_loss);\n\n ++mb_count;\n if ( mb_count == num_mini_batch ) {\n mb_count = 0;\n rng::shuffle( schedule.begin(), schedule.end(), rand ); \n }\n\n var_mom *= 1.0003;\n if ( var_mom > 0.95 ) var_mom = 0.95;\n\/\/ var_lr *= 0.9999;\n \/\/ if ( var_lr < 0.001 ) var_lr = 0.001;\n\n }\n\n \/\/ Determine how well the network performs on all the test data.\n\n fprintf(stderr,\"start Testing phase ...\\n\");\n\n num_validation = -1;\n mnist_data.get_validation_set( num_validation, rand,\n val_inputs, val_outputs );\n\n val_loss = dnn.loss( val_inputs, val_outputs, 0.0 ); \n fprintf(stdout,\"#final val: loss %f\\n\", val_loss);\n\n Matrix<float,Dynamic,Dynamic> pred_outputs;\n\n dnn.forward_prop( val_inputs, pred_outputs );\n\n vector<double> val_error = \n NN_Analyzer::Error_Analyis( pred_outputs, val_outputs );\n for (size_t r = 0; r < val_error.size(); ++r ) {\n fprintf(stdout,\"#%2zd %f\\n\", r, val_error[r]);\n }\n\n fprintf(stdout,\"#final error: %f\\n\", (1.0-val_error[val_error.size()-1]));\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright Hugh Perkins (hughperkins at gmail), Josef Moudrik 2015\n\/\/\n\/\/ This Source Code Form is subject to the terms of the Mozilla Public License, \n\/\/ v. 2.0. If a copy of the MPL was not distributed with this file, You can \n\/\/ obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n\n\n#include \"DeepCL.h\"\n#include \"loss\/SoftMaxLayer.h\"\n#ifdef _WIN32\n#include <stdio.h>\n#include <fcntl.h>\n#include <io.h>\n#endif \/\/ _WIN32\n\nusing namespace std;\n\n\/* [[[cog\n # These are used in the later cog sections in this file:\n options = [\n {'name': 'gpuIndex', 'type': 'int', 'description': 'gpu device index; default value is gpu if present, cpu otw.', 'default': -1, 'ispublicapi': True},\n\n {'name': 'weightsFile', 'type': 'string', 'description': 'file to read weights from', 'default': 'weights.dat', 'ispublicapi': True},\n # removing loadondemand for now, let's always load exactly one batch at a time for now\n # ('loadOnDemand', 'int', 'load data on demand [1|0]', 0, [0,1], True},\n {'name': 'batchSize', 'type': 'int', 'description': 'batch size', 'default': 128, 'ispublicapi': True},\n\n # lets go with pipe for now, and then somehow shoehorn files in later?\n {'name': 'inputFile', 'type': 'string', 'description': 'file to read inputs from, if empty, read stdin (default)', 'default': ''},\n {'name': 'outputFile', 'type': 'string', 'description': 'file to write outputs to, if empty, write to stdout', 'default': ''},\n {'name': 'outputLayer', 'type': 'int', 'description': 'layer to write output from, default -1 means: last layer', 'default': -1},\n {'name': 'writeLabels', 'type': 'int', 'description': 'write integer labels, instead of probabilities etc (default 0)', 'default': 0},\n {'name': 'outputFormat', 'type': 'string', 'description': 'output format [binary|text]', 'default': 'text'}\n ]\n*\/\/\/]]]\n\/\/ [[[end]]]\n\nclass Config {\npublic:\n \/* [[[cog\n cog.outl('\/\/ generated using cog:')\n for option in options:\n cog.outl( option['type'] + ' ' + option['name'] + ';')\n *\/\/\/ ]]]\n \/\/ generated using cog:\n int gpuIndex;\n string weightsFile;\n int batchSize;\n string inputFile;\n string outputFile;\n int outputLayer;\n int writeLabels;\n string outputFormat;\n \/\/ [[[end]]]\n\n Config() {\n \/* [[[cog\n cog.outl('\/\/ generated using cog:')\n for option in options:\n defaultString = ''\n default = option['default']\n type = option['type']\n if type == 'string':\n defaultString = '\"' + default + '\"'\n elif type == 'int':\n defaultString = str(default)\n elif type == 'float':\n defaultString = str(default)\n if '.' not in defaultString:\n defaultString += '.0'\n defaultString += 'f'\n cog.outl( option['name'] + ' = ' + defaultString + ';')\n *\/\/\/ ]]]\n \/\/ generated using cog:\n gpuIndex = -1;\n weightsFile = \"weights.dat\";\n batchSize = 128;\n inputFile = \"\";\n outputFile = \"\";\n outputLayer = -1;\n writeLabels = 0;\n outputFormat = \"text\";\n \/\/ [[[end]]]\n }\n};\n\nvoid go(Config config) {\n bool verbose = true;\n if( config.outputFile == \"\" ) {\n verbose = false;\n }\n\n int N = -1;\n int numPlanes;\n int imageSize;\n int imageSizeCheck;\n if( config.inputFile == \"\" ) {\n int dims[3];\n cin.read( reinterpret_cast< char * >( dims ), 3 * 4l );\n numPlanes = dims[0];\n imageSize = dims[1];\n imageSizeCheck = dims[2];\n if( imageSize != imageSizeCheck ) {\n throw std::runtime_error( \"imageSize doesnt match imageSizeCheck, image not square\" );\n }\n } else {\n GenericLoader::getDimensions( config.inputFile, &N, &numPlanes, &imageSize );\n if( verbose ) cout << \"N \" << N << \" planes \" << numPlanes << \" size \" << imageSize << endl;\n }\n\n const long inputCubeSize = numPlanes * imageSize * imageSize ;\n\n \/\/\n \/\/ ## Set up the Network\n \/\/\n\n EasyCL *cl = 0;\n if( config.gpuIndex >= 0 ) {\n cl = EasyCL::createForIndexedGpu( config.gpuIndex, verbose );\n } else {\n cl = EasyCL::createForFirstGpuOtherwiseCpu( verbose );\n }\n\n NeuralNet *net;\n net = new NeuralNet(cl);\n\n \/\/ just use the default for net creation, weights are overriden from the weightsFile\n WeightsInitializer *weightsInitializer = new OriginalInitializer();\n\n if( config.weightsFile == \"\" ) {\n cout << \"weightsFile not specified\" << endl;\n return;\n }\n\n string netDef;\n if ( !WeightsPersister::loadConfigString( config.weightsFile, netDef ) ){\n cout << \"Cannot load network definition from weightsFile.\" << endl;\n return;\n }\n\/\/ cout << \"net def from weights file: \" << netDef << endl;\n\n net->addLayer( InputLayerMaker::instance()->numPlanes(numPlanes)->imageSize(imageSize) );\n net->addLayer( NormalizationLayerMaker::instance()->translate( 0.0f )->scale( 1.0f ) ); \/\/ This will be read from weights file\n\n if( !NetdefToNet::createNetFromNetdef( net, netDef, weightsInitializer ) ) {\n return;\n }\n\n \/\/ ignored int and float, s.t. we can use loadWeights\n int ignI;\n float ignF;\n\n \/\/ weights file contains normalization layer parameters as 'weights' now. We should probably rename weights to parameters\n \/\/ sooner or later ,but anyway, tehcnically, works for onw\n if( !WeightsPersister::loadWeights( config.weightsFile, string(\"netDef=\")+netDef, net, &ignI, &ignI, &ignF, &ignI, &ignF ) ){\n cout << \"Cannot load network weights from weightsFile.\" << endl;\n return;\n }\n\n if( verbose ) {\n net->print();\n }\n net->setBatchSize(config.batchSize);\n if( verbose ) cout << \"batchSize: \" << config.batchSize << endl;\n\n\n \/\/\n \/\/ ## All is set up now\n \/\/ \n\n float *inputData = new float[ inputCubeSize * config.batchSize];\n\n int *labels = new int[config.batchSize];\n int n = 0;\n bool more = true;\n ostream *outFile = 0;\n if( config.outputFile == \"\" ) {\n outFile = &cout;\n } else {\n if( config.outputFormat == \"text\" ) {\n outFile = new ofstream( config.outputFile, ios::out );\n } else if( config.outputFormat == \"binary\" ) {\n outFile = new ofstream( config.outputFile, ios::out | std::ios::binary );\n } else {\n throw runtime_error( \"outputFormat \" + config.outputFormat + \" not recognized\" );\n }\n }\n if( config.outputLayer == -1 ) {\n config.outputLayer = net->getNumLayers() - 1;\n }\n if( config.inputFile == \"\" ) {\n #ifdef _WIN32\n \/\/ refs:\n \/\/ http:\/\/www.thecodingforums.com\/threads\/binary-output-to-stdout-in-windows.317367\/\n \/\/ http:\/\/www.cplusplus.com\/forum\/windows\/77812\/\n _setmode( _fileno( stdout ), _O_BINARY ); \n #endif\n cin.read( reinterpret_cast< char * >( inputData ), inputCubeSize * config.batchSize * 4l );\n more = !cin.eof();\n } else {\n \/\/ pass 0 for labels, and this will cause GenericLoader to simply not try to load any labels\n \/\/ now, after modifying GenericLoader to have this new behavior\n GenericLoader::load( config.inputFile, inputData, 0, n, config.batchSize );\n }\n while( more ) {\n \/\/ no point in forwarding through all, so forward through each, one by one\n if( config.outputLayer < 0 || config.outputLayer > net->getNumLayers() ) {\n throw runtime_error( \"outputLayer should be the layer number of one of the layers in the network\" ); \n }\n dynamic_cast<InputLayer *>( net->getLayer(0) )->in( inputData );\n for( int layerId = 0; layerId <= config.outputLayer; layerId++ ) {\n StatefulTimer::setPrefix(\"layer\" + toString(layerId) + \" \" );\n net->getLayer( layerId )->forward();\n StatefulTimer::setPrefix(\"\" );\n }\n\n if( !config.writeLabels ) {\n if( config.outputFormat == \"text\" ) {\n float const*output = net->getLayer( config.outputLayer )->getOutput();\n const int numFields = net->getLayer( config.outputLayer )->getOutputCubeSize();\n for( int i = 0; i < config.batchSize; i++ ) {\n for( int f = 0; f < numFields; f++ ) {\n if( f > 0 ) {\n *outFile << \" \";\n }\n *outFile << output[ i * numFields + f ];\n }\n *outFile << \"\\n\";\n }\n } else {\n outFile->write( reinterpret_cast<const char *>(net->getOutput()), net->getOutputSize() * 4 * config.batchSize);\n }\n } else {\n SoftMaxLayer *softMaxLayer = dynamic_cast< SoftMaxLayer *>(net->getLayer( config.outputLayer ) );\n if( softMaxLayer == 0 ) {\n cout << \"must choose softmaxlayer, if want to output labels\" << endl;\n return;\n }\n softMaxLayer->getLabels(labels);\n if( config.outputFormat == \"text\" ) {\n for( int i = 0; i < config.batchSize; i++ ) {\n *outFile << labels[i] << \"\\n\";\n }\n } else {\n outFile->write( reinterpret_cast< char * >( labels ), config.batchSize * 4l );\n }\n outFile->flush();\n }\n n += config.batchSize;\n if( config.inputFile == \"\" ) {\n cin.read( reinterpret_cast< char * >( inputData ), inputCubeSize * config.batchSize * 4l );\n more = !cin.eof();\n } else {\n if( n + config.batchSize < N ) {\n GenericLoader::load( config.inputFile, inputData, 0, n, config.batchSize );\n } else {\n more = false;\n if( n != N ) {\n cout << \"breaking prematurely, since file is not an exact multiple of batchsize, and we didnt handle this yet\" << endl;\n }\n }\n }\n }\n if( config.outputFile != \"\" ) {\n delete outFile;\n }\n\n delete[] inputData;\n delete[] labels;\n delete weightsInitializer;\n delete net;\n delete cl;\n}\n\nvoid printUsage( char *argv[], Config config ) {\n cout << \"Usage: \" << argv[0] << \" [key]=[value] [[key]=[value]] ...\" << endl;\n cout << endl;\n cout << \"Possible key=value pairs:\" << endl;\n \/* [[[cog\n cog.outl('\/\/ generated using cog:')\n cog.outl('cout << \"public api, shouldnt change within major version:\" << endl;')\n for option in options:\n name = option['name']\n description = option['description']\n if 'ispublicapi' in option and option['ispublicapi']:\n cog.outl( 'cout << \" ' + name.lower() + '=[' + description + '] (\" << config.' + name + ' << \")\" << endl;')\n cog.outl('cout << \"\" << endl; ')\n cog.outl('cout << \"unstable, might change within major version:\" << endl; ')\n for option in options:\n if 'ispublicapi' not in option or not option['ispublicapi']:\n name = option['name']\n description = option['description']\n cog.outl( 'cout << \" ' + name.lower() + '=[' + description + '] (\" << config.' + name + ' << \")\" << endl;')\n *\/\/\/]]]\n \/\/ generated using cog:\n cout << \"public api, shouldnt change within major version:\" << endl;\n cout << \" gpuindex=[gpu device index; default value is gpu if present, cpu otw.] (\" << config.gpuIndex << \")\" << endl;\n cout << \" weightsfile=[file to read weights from] (\" << config.weightsFile << \")\" << endl;\n cout << \" batchsize=[batch size] (\" << config.batchSize << \")\" << endl;\n cout << \"\" << endl; \n cout << \"unstable, might change within major version:\" << endl; \n cout << \" inputfile=[file to read inputs from, if empty, read stdin (default)] (\" << config.inputFile << \")\" << endl;\n cout << \" outputfile=[file to write outputs to, if empty, write to stdout] (\" << config.outputFile << \")\" << endl;\n cout << \" outputlayer=[layer to write output from, default -1 means: last layer] (\" << config.outputLayer << \")\" << endl;\n cout << \" writelabels=[write integer labels, instead of probabilities etc (default 0)] (\" << config.writeLabels << \")\" << endl;\n cout << \" outputformat=[output format [binary|text]] (\" << config.outputFormat << \")\" << endl;\n \/\/ [[[end]]]\n}\n\nint main( int argc, char *argv[] ) {\n Config config;\n if( argc == 2 && ( string(argv[1]) == \"--help\" || string(argv[1]) == \"--?\" || string(argv[1]) == \"-?\" || string(argv[1]) == \"-h\" ) ) {\n printUsage( argv, config );\n } \n for( int i = 1; i < argc; i++ ) {\n vector<string> splitkeyval = split( argv[i], \"=\" );\n if( splitkeyval.size() != 2 ) {\n cout << \"Usage: \" << argv[0] << \" [key]=[value] [[key]=[value]] ...\" << endl;\n exit(1);\n } else {\n string key = splitkeyval[0];\n string value = splitkeyval[1];\n\/\/ cout << \"key [\" << key << \"]\" << endl;\n \/* [[[cog\n cog.outl('\/\/ generated using cog:')\n cog.outl('if( false ) {')\n for option in options:\n name = option['name']\n type = option['type']\n cog.outl( '} else if( key == \"' + name.lower() + '\" ) {')\n converter = '';\n if type == 'int':\n converter = 'atoi';\n elif type == 'float':\n converter = 'atof';\n cog.outl( ' config.' + name + ' = ' + converter + '(value);')\n *\/\/\/ ]]]\n \/\/ generated using cog:\n if( false ) {\n } else if( key == \"gpuindex\" ) {\n config.gpuIndex = atoi(value);\n } else if( key == \"weightsfile\" ) {\n config.weightsFile = (value);\n } else if( key == \"batchsize\" ) {\n config.batchSize = atoi(value);\n } else if( key == \"inputfile\" ) {\n config.inputFile = (value);\n } else if( key == \"outputfile\" ) {\n config.outputFile = (value);\n } else if( key == \"outputlayer\" ) {\n config.outputLayer = atoi(value);\n } else if( key == \"writelabels\" ) {\n config.writeLabels = atoi(value);\n } else if( key == \"outputformat\" ) {\n config.outputFormat = (value);\n \/\/ [[[end]]]\n } else {\n cout << endl;\n cout << \"Error: key '\" << key << \"' not recognised\" << endl;\n cout << endl;\n printUsage( argv, config );\n cout << endl;\n return -1;\n }\n }\n }\n if( config.outputFormat != \"text\" && config.outputFormat != \"binary\" ) {\n cout << endl;\n cout << \"outputformat must be 'text' or 'binary'\" << endl;\n cout << endl;\n return -1;\n }\n try {\n go( config );\n } catch( runtime_error e ) {\n cout << \"Something went wrong: \" << e.what() << endl;\n return -1;\n }\n}\n\n\n<commit_msg>predict: extend debug messages, print inputFile and outputFile names.<commit_after>\/\/ Copyright Hugh Perkins (hughperkins at gmail), Josef Moudrik 2015\n\/\/\n\/\/ This Source Code Form is subject to the terms of the Mozilla Public License, \n\/\/ v. 2.0. If a copy of the MPL was not distributed with this file, You can \n\/\/ obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n\n\n#include \"DeepCL.h\"\n#include \"loss\/SoftMaxLayer.h\"\n#ifdef _WIN32\n#include <stdio.h>\n#include <fcntl.h>\n#include <io.h>\n#endif \/\/ _WIN32\n\nusing namespace std;\n\n\/* [[[cog\n # These are used in the later cog sections in this file:\n options = [\n {'name': 'gpuIndex', 'type': 'int', 'description': 'gpu device index; default value is gpu if present, cpu otw.', 'default': -1, 'ispublicapi': True},\n\n {'name': 'weightsFile', 'type': 'string', 'description': 'file to read weights from', 'default': 'weights.dat', 'ispublicapi': True},\n # removing loadondemand for now, let's always load exactly one batch at a time for now\n # ('loadOnDemand', 'int', 'load data on demand [1|0]', 0, [0,1], True},\n {'name': 'batchSize', 'type': 'int', 'description': 'batch size', 'default': 128, 'ispublicapi': True},\n\n # lets go with pipe for now, and then somehow shoehorn files in later?\n {'name': 'inputFile', 'type': 'string', 'description': 'file to read inputs from, if empty, read stdin (default)', 'default': ''},\n {'name': 'outputFile', 'type': 'string', 'description': 'file to write outputs to, if empty, write to stdout', 'default': ''},\n {'name': 'outputLayer', 'type': 'int', 'description': 'layer to write output from, default -1 means: last layer', 'default': -1},\n {'name': 'writeLabels', 'type': 'int', 'description': 'write integer labels, instead of probabilities etc (default 0)', 'default': 0},\n {'name': 'outputFormat', 'type': 'string', 'description': 'output format [binary|text]', 'default': 'text'}\n ]\n*\/\/\/]]]\n\/\/ [[[end]]]\n\nclass Config {\npublic:\n \/* [[[cog\n cog.outl('\/\/ generated using cog:')\n for option in options:\n cog.outl( option['type'] + ' ' + option['name'] + ';')\n *\/\/\/ ]]]\n \/\/ generated using cog:\n int gpuIndex;\n string weightsFile;\n int batchSize;\n string inputFile;\n string outputFile;\n int outputLayer;\n int writeLabels;\n string outputFormat;\n \/\/ [[[end]]]\n\n Config() {\n \/* [[[cog\n cog.outl('\/\/ generated using cog:')\n for option in options:\n defaultString = ''\n default = option['default']\n type = option['type']\n if type == 'string':\n defaultString = '\"' + default + '\"'\n elif type == 'int':\n defaultString = str(default)\n elif type == 'float':\n defaultString = str(default)\n if '.' not in defaultString:\n defaultString += '.0'\n defaultString += 'f'\n cog.outl( option['name'] + ' = ' + defaultString + ';')\n *\/\/\/ ]]]\n \/\/ generated using cog:\n gpuIndex = -1;\n weightsFile = \"weights.dat\";\n batchSize = 128;\n inputFile = \"\";\n outputFile = \"\";\n outputLayer = -1;\n writeLabels = 0;\n outputFormat = \"text\";\n \/\/ [[[end]]]\n }\n};\n\nvoid go(Config config) {\n bool verbose = true;\n if( config.outputFile == \"\" ) {\n verbose = false;\n }\n\n int N = -1;\n int numPlanes;\n int imageSize;\n int imageSizeCheck;\n if( config.inputFile == \"\" ) {\n int dims[3];\n cin.read( reinterpret_cast< char * >( dims ), 3 * 4l );\n numPlanes = dims[0];\n imageSize = dims[1];\n imageSizeCheck = dims[2];\n if( imageSize != imageSizeCheck ) {\n throw std::runtime_error( \"imageSize doesnt match imageSizeCheck, image not square\" );\n }\n } else {\n GenericLoader::getDimensions( config.inputFile, &N, &numPlanes, &imageSize );\n if( verbose ) cout << \"N \" << N << \" planes \" << numPlanes << \" size \" << imageSize << endl;\n }\n\n const long inputCubeSize = numPlanes * imageSize * imageSize ;\n\n \/\/\n \/\/ ## Set up the Network\n \/\/\n\n EasyCL *cl = 0;\n if( config.gpuIndex >= 0 ) {\n cl = EasyCL::createForIndexedGpu( config.gpuIndex, verbose );\n } else {\n cl = EasyCL::createForFirstGpuOtherwiseCpu( verbose );\n }\n\n NeuralNet *net;\n net = new NeuralNet(cl);\n\n \/\/ just use the default for net creation, weights are overriden from the weightsFile\n WeightsInitializer *weightsInitializer = new OriginalInitializer();\n\n if( config.weightsFile == \"\" ) {\n cout << \"weightsFile not specified\" << endl;\n return;\n }\n\n string netDef;\n if ( !WeightsPersister::loadConfigString( config.weightsFile, netDef ) ){\n cout << \"Cannot load network definition from weightsFile.\" << endl;\n return;\n }\n\/\/ cout << \"net def from weights file: \" << netDef << endl;\n\n net->addLayer( InputLayerMaker::instance()->numPlanes(numPlanes)->imageSize(imageSize) );\n net->addLayer( NormalizationLayerMaker::instance()->translate( 0.0f )->scale( 1.0f ) ); \/\/ This will be read from weights file\n\n if( !NetdefToNet::createNetFromNetdef( net, netDef, weightsInitializer ) ) {\n return;\n }\n\n \/\/ ignored int and float, s.t. we can use loadWeights\n int ignI;\n float ignF;\n\n \/\/ weights file contains normalization layer parameters as 'weights' now. We should probably rename weights to parameters\n \/\/ sooner or later ,but anyway, tehcnically, works for onw\n if( !WeightsPersister::loadWeights( config.weightsFile, string(\"netDef=\")+netDef, net, &ignI, &ignI, &ignF, &ignI, &ignF ) ){\n cout << \"Cannot load network weights from weightsFile.\" << endl;\n return;\n }\n\n if( verbose ) {\n net->print();\n }\n net->setBatchSize(config.batchSize);\n if( verbose ) cout << \"batchSize: \" << config.batchSize << endl;\n\n\n \/\/\n \/\/ ## All is set up now\n \/\/ \n\n float *inputData = new float[ inputCubeSize * config.batchSize];\n\n int *labels = new int[config.batchSize];\n int n = 0;\n bool more = true;\n ostream *outFile = 0;\n if( verbose ) cout << \"outputFile: '\" << config.outputFile << \"'\"<< endl;\n if( config.outputFile == \"\" ) {\n outFile = &cout;\n } else {\n if( config.outputFormat == \"text\" ) {\n outFile = new ofstream( config.outputFile, ios::out );\n } else if( config.outputFormat == \"binary\" ) {\n outFile = new ofstream( config.outputFile, ios::out | std::ios::binary );\n } else {\n throw runtime_error( \"outputFormat \" + config.outputFormat + \" not recognized\" );\n }\n }\n if( config.outputLayer == -1 ) {\n config.outputLayer = net->getNumLayers() - 1;\n }\n if( verbose ) cout << \"inputFile: '\" << config.inputFile << \"'\"<< endl;\n if( config.inputFile == \"\" ) {\n #ifdef _WIN32\n \/\/ refs:\n \/\/ http:\/\/www.thecodingforums.com\/threads\/binary-output-to-stdout-in-windows.317367\/\n \/\/ http:\/\/www.cplusplus.com\/forum\/windows\/77812\/\n _setmode( _fileno( stdout ), _O_BINARY ); \n #endif\n cin.read( reinterpret_cast< char * >( inputData ), inputCubeSize * config.batchSize * 4l );\n more = !cin.eof();\n } else {\n \/\/ pass 0 for labels, and this will cause GenericLoader to simply not try to load any labels\n \/\/ now, after modifying GenericLoader to have this new behavior\n GenericLoader::load( config.inputFile, inputData, 0, n, config.batchSize );\n }\n while( more ) {\n \/\/ no point in forwarding through all, so forward through each, one by one\n if( config.outputLayer < 0 || config.outputLayer > net->getNumLayers() ) {\n throw runtime_error( \"outputLayer should be the layer number of one of the layers in the network\" ); \n }\n dynamic_cast<InputLayer *>( net->getLayer(0) )->in( inputData );\n for( int layerId = 0; layerId <= config.outputLayer; layerId++ ) {\n StatefulTimer::setPrefix(\"layer\" + toString(layerId) + \" \" );\n net->getLayer( layerId )->forward();\n StatefulTimer::setPrefix(\"\" );\n }\n\n if( !config.writeLabels ) {\n if( config.outputFormat == \"text\" ) {\n float const*output = net->getLayer( config.outputLayer )->getOutput();\n const int numFields = net->getLayer( config.outputLayer )->getOutputCubeSize();\n for( int i = 0; i < config.batchSize; i++ ) {\n for( int f = 0; f < numFields; f++ ) {\n if( f > 0 ) {\n *outFile << \" \";\n }\n *outFile << output[ i * numFields + f ];\n }\n *outFile << \"\\n\";\n }\n } else {\n outFile->write( reinterpret_cast<const char *>(net->getOutput()), net->getOutputSize() * 4 * config.batchSize);\n }\n } else {\n SoftMaxLayer *softMaxLayer = dynamic_cast< SoftMaxLayer *>(net->getLayer( config.outputLayer ) );\n if( softMaxLayer == 0 ) {\n cout << \"must choose softmaxlayer, if want to output labels\" << endl;\n return;\n }\n softMaxLayer->getLabels(labels);\n if( config.outputFormat == \"text\" ) {\n for( int i = 0; i < config.batchSize; i++ ) {\n *outFile << labels[i] << \"\\n\";\n }\n } else {\n outFile->write( reinterpret_cast< char * >( labels ), config.batchSize * 4l );\n }\n outFile->flush();\n }\n n += config.batchSize;\n if( config.inputFile == \"\" ) {\n cin.read( reinterpret_cast< char * >( inputData ), inputCubeSize * config.batchSize * 4l );\n more = !cin.eof();\n } else {\n if( n + config.batchSize < N ) {\n GenericLoader::load( config.inputFile, inputData, 0, n, config.batchSize );\n } else {\n more = false;\n if( n != N ) {\n cout << \"breaking prematurely, since file is not an exact multiple of batchsize, and we didnt handle this yet\" << endl;\n }\n }\n }\n }\n if( config.outputFile != \"\" ) {\n delete outFile;\n }\n\n delete[] inputData;\n delete[] labels;\n delete weightsInitializer;\n delete net;\n delete cl;\n}\n\nvoid printUsage( char *argv[], Config config ) {\n cout << \"Usage: \" << argv[0] << \" [key]=[value] [[key]=[value]] ...\" << endl;\n cout << endl;\n cout << \"Possible key=value pairs:\" << endl;\n \/* [[[cog\n cog.outl('\/\/ generated using cog:')\n cog.outl('cout << \"public api, shouldnt change within major version:\" << endl;')\n for option in options:\n name = option['name']\n description = option['description']\n if 'ispublicapi' in option and option['ispublicapi']:\n cog.outl( 'cout << \" ' + name.lower() + '=[' + description + '] (\" << config.' + name + ' << \")\" << endl;')\n cog.outl('cout << \"\" << endl; ')\n cog.outl('cout << \"unstable, might change within major version:\" << endl; ')\n for option in options:\n if 'ispublicapi' not in option or not option['ispublicapi']:\n name = option['name']\n description = option['description']\n cog.outl( 'cout << \" ' + name.lower() + '=[' + description + '] (\" << config.' + name + ' << \")\" << endl;')\n *\/\/\/]]]\n \/\/ generated using cog:\n cout << \"public api, shouldnt change within major version:\" << endl;\n cout << \" gpuindex=[gpu device index; default value is gpu if present, cpu otw.] (\" << config.gpuIndex << \")\" << endl;\n cout << \" weightsfile=[file to read weights from] (\" << config.weightsFile << \")\" << endl;\n cout << \" batchsize=[batch size] (\" << config.batchSize << \")\" << endl;\n cout << \"\" << endl; \n cout << \"unstable, might change within major version:\" << endl; \n cout << \" inputfile=[file to read inputs from, if empty, read stdin (default)] (\" << config.inputFile << \")\" << endl;\n cout << \" outputfile=[file to write outputs to, if empty, write to stdout] (\" << config.outputFile << \")\" << endl;\n cout << \" outputlayer=[layer to write output from, default -1 means: last layer] (\" << config.outputLayer << \")\" << endl;\n cout << \" writelabels=[write integer labels, instead of probabilities etc (default 0)] (\" << config.writeLabels << \")\" << endl;\n cout << \" outputformat=[output format [binary|text]] (\" << config.outputFormat << \")\" << endl;\n \/\/ [[[end]]]\n}\n\nint main( int argc, char *argv[] ) {\n Config config;\n if( argc == 2 && ( string(argv[1]) == \"--help\" || string(argv[1]) == \"--?\" || string(argv[1]) == \"-?\" || string(argv[1]) == \"-h\" ) ) {\n printUsage( argv, config );\n } \n for( int i = 1; i < argc; i++ ) {\n vector<string> splitkeyval = split( argv[i], \"=\" );\n if( splitkeyval.size() != 2 ) {\n cout << \"Usage: \" << argv[0] << \" [key]=[value] [[key]=[value]] ...\" << endl;\n exit(1);\n } else {\n string key = splitkeyval[0];\n string value = splitkeyval[1];\n\/\/ cout << \"key [\" << key << \"]\" << endl;\n \/* [[[cog\n cog.outl('\/\/ generated using cog:')\n cog.outl('if( false ) {')\n for option in options:\n name = option['name']\n type = option['type']\n cog.outl( '} else if( key == \"' + name.lower() + '\" ) {')\n converter = '';\n if type == 'int':\n converter = 'atoi';\n elif type == 'float':\n converter = 'atof';\n cog.outl( ' config.' + name + ' = ' + converter + '(value);')\n *\/\/\/ ]]]\n \/\/ generated using cog:\n if( false ) {\n } else if( key == \"gpuindex\" ) {\n config.gpuIndex = atoi(value);\n } else if( key == \"weightsfile\" ) {\n config.weightsFile = (value);\n } else if( key == \"batchsize\" ) {\n config.batchSize = atoi(value);\n } else if( key == \"inputfile\" ) {\n config.inputFile = (value);\n } else if( key == \"outputfile\" ) {\n config.outputFile = (value);\n } else if( key == \"outputlayer\" ) {\n config.outputLayer = atoi(value);\n } else if( key == \"writelabels\" ) {\n config.writeLabels = atoi(value);\n } else if( key == \"outputformat\" ) {\n config.outputFormat = (value);\n \/\/ [[[end]]]\n } else {\n cout << endl;\n cout << \"Error: key '\" << key << \"' not recognised\" << endl;\n cout << endl;\n printUsage( argv, config );\n cout << endl;\n return -1;\n }\n }\n }\n if( config.outputFormat != \"text\" && config.outputFormat != \"binary\" ) {\n cout << endl;\n cout << \"outputformat must be 'text' or 'binary'\" << endl;\n cout << endl;\n return -1;\n }\n try {\n go( config );\n } catch( runtime_error e ) {\n cout << \"Something went wrong: \" << e.what() << endl;\n return -1;\n }\n}\n\n\n<|endoftext|>"} {"text":"<commit_before>\/**\n * Copyright (c) 2011-2015 libbitcoin developers (see AUTHORS)\n *\n * This file is part of libbitcoin.\n *\n * libbitcoin is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License with\n * additional permissions to the one published by the Free Software\n * Foundation, either version 3 of the License, or (at your option)\n * any later version. For more information see LICENSE.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Affero General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public License\n * along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n#include <bitcoin\/bitcoin\/utility\/threadpool.hpp>\n\n#include <new>\n#include <thread>\n#include <bitcoin\/bitcoin\/network\/asio.hpp>\n#include <bitcoin\/bitcoin\/utility\/thread.hpp>\n\nnamespace libbitcoin {\n\nthreadpool::threadpool(size_t number_threads, thread_priority priority)\n{\n spawn(number_threads, priority);\n}\n\nthreadpool::~threadpool()\n{\n shutdown();\n}\n\nvoid threadpool::spawn(size_t number_threads, thread_priority priority)\n{\n for (size_t i = 0; i < number_threads; ++i)\n spawn_once(priority);\n}\n\nvoid threadpool::spawn_once(thread_priority priority)\n{\n \/\/ Work prevents the service from running out of work and terminating.\n if (!work_)\n work_ = std::make_unique<asio::service::work>(service_);\n\n const auto action = [this, priority]\n {\n set_thread_priority(priority);\n service_.run();\n };\n\n threads_.push_back(std::thread(action));\n}\n\nvoid threadpool::stop()\n{\n \/\/ TODO: don't call this on shutdown, instead signal the application.\n \/\/ Signals the service to stop. Calls will return immediately without\n \/\/ invoking any handlers.\n service_.stop();\n}\n\nvoid threadpool::shutdown()\n{\n \/\/ This does not terminate outstanding calls, it just allows service to\n \/\/ terminate once all outstanding calls are complete.\n work_ = nullptr;\n}\n\nvoid threadpool::join()\n{\n \/\/ TODO: join the threadpool on destruct?\n for (auto& thread: threads_)\n if (thread.joinable())\n thread.join();\n}\n\nasio::service& threadpool::service()\n{\n return service_;\n}\n\nconst asio::service& threadpool::service() const\n{\n return service_;\n}\n\n} \/\/ namespace libbitcoin\n\n<commit_msg>Add missing include.<commit_after>\/**\n * Copyright (c) 2011-2015 libbitcoin developers (see AUTHORS)\n *\n * This file is part of libbitcoin.\n *\n * libbitcoin is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License with\n * additional permissions to the one published by the Free Software\n * Foundation, either version 3 of the License, or (at your option)\n * any later version. For more information see LICENSE.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Affero General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public License\n * along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n#include <bitcoin\/bitcoin\/utility\/threadpool.hpp>\n\n#include <memory>\n#include <new>\n#include <thread>\n#include <bitcoin\/bitcoin\/network\/asio.hpp>\n#include <bitcoin\/bitcoin\/utility\/thread.hpp>\n\nnamespace libbitcoin {\n\nthreadpool::threadpool(size_t number_threads, thread_priority priority)\n{\n spawn(number_threads, priority);\n}\n\nthreadpool::~threadpool()\n{\n shutdown();\n}\n\nvoid threadpool::spawn(size_t number_threads, thread_priority priority)\n{\n for (size_t i = 0; i < number_threads; ++i)\n spawn_once(priority);\n}\n\nvoid threadpool::spawn_once(thread_priority priority)\n{\n \/\/ Work prevents the service from running out of work and terminating.\n if (!work_)\n work_ = std::make_unique<asio::service::work>(service_);\n\n const auto action = [this, priority]\n {\n set_thread_priority(priority);\n service_.run();\n };\n\n threads_.push_back(std::thread(action));\n}\n\nvoid threadpool::stop()\n{\n \/\/ TODO: don't call this on shutdown, instead signal the application.\n \/\/ Signals the service to stop. Calls will return immediately without\n \/\/ invoking any handlers.\n service_.stop();\n}\n\nvoid threadpool::shutdown()\n{\n \/\/ This does not terminate outstanding calls, it just allows service to\n \/\/ terminate once all outstanding calls are complete.\n work_ = nullptr;\n}\n\nvoid threadpool::join()\n{\n \/\/ TODO: join the threadpool on destruct?\n for (auto& thread: threads_)\n if (thread.joinable())\n thread.join();\n}\n\nasio::service& threadpool::service()\n{\n return service_;\n}\n\nconst asio::service& threadpool::service() const\n{\n return service_;\n}\n\n} \/\/ namespace libbitcoin\n\n<|endoftext|>"} {"text":"<commit_before>#ifndef __NODE_MAPNIK_IMAGE_H__\n#define __NODE_MAPNIK_IMAGE_H__\n\n#include <v8.h>\n#include <node.h>\n#include <node_object_wrap.h>\n#include <mapnik\/graphics.hpp>\n#include <boost\/shared_ptr.hpp>\n\nusing namespace v8;\nusing namespace node;\n\ntypedef boost::shared_ptr<mapnik::image_32> image_ptr;\n\nclass Image: public node::ObjectWrap {\n public:\n static Persistent<FunctionTemplate> constructor;\n static void Initialize(Handle<Object> target);\n static Handle<Value> New(const Arguments &args);\n static Handle<Value> toString(const Arguments &args);\n static Handle<Value> open(const Arguments &args);\n\n Image(unsigned int width, unsigned int height);\n Image(image_ptr this_);\n\n private:\n ~Image();\n image_ptr this_;\n};\n\n#endif\n<commit_msg>expose shared pointer on mapnik.Image<commit_after>#ifndef __NODE_MAPNIK_IMAGE_H__\n#define __NODE_MAPNIK_IMAGE_H__\n\n#include <v8.h>\n#include <node.h>\n#include <node_object_wrap.h>\n#include <mapnik\/graphics.hpp>\n#include <boost\/shared_ptr.hpp>\n\nusing namespace v8;\nusing namespace node;\n\ntypedef boost::shared_ptr<mapnik::image_32> image_ptr;\n\nclass Image: public node::ObjectWrap {\n public:\n static Persistent<FunctionTemplate> constructor;\n static void Initialize(Handle<Object> target);\n static Handle<Value> New(const Arguments &args);\n static Handle<Value> toString(const Arguments &args);\n static Handle<Value> open(const Arguments &args);\n\n Image(unsigned int width, unsigned int height);\n Image(image_ptr this_);\n inline image_ptr get() { return this_; }\n\n private:\n ~Image();\n image_ptr this_;\n};\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/\/ __BEGIN_LICENSE__\n\/\/ Copyright (C) 2006-2010 United States Government as represented by\n\/\/ the Administrator of the National Aeronautics and Space Administration.\n\/\/ All Rights Reserved.\n\/\/ __END_LICENSE__\n\n\n#ifdef _MSC_VER\n#pragma warning(disable:4244)\n#pragma warning(disable:4267)\n#pragma warning(disable:4996)\n#endif\n\n#include <stdlib.h>\n#include <iostream>\n#include <fstream>\n\n#include <boost\/program_options.hpp>\nnamespace po = boost::program_options;\n\n#include <vw\/Core\/Cache.h>\n#include <vw\/Core\/ProgressCallback.h>\n#include <vw\/Math\/Matrix.h>\n#include <vw\/Image\/Transform.h>\n#include <vw\/Image\/Palette.h>\n#include <vw\/FileIO\/DiskImageResource.h>\n#include <vw\/FileIO\/DiskImageResourceJPEG.h>\n#include <vw\/FileIO\/DiskImageResourcePNG.h>\n#include <vw\/FileIO\/DiskImageResourceGDAL.h>\n#include <vw\/FileIO\/DiskImageView.h>\n#include <vw\/Cartography\/GeoReference.h>\n#include <vw\/Cartography\/GeoTransform.h>\n#include <vw\/Cartography\/FileIO.h>\n#include <vw\/Mosaic\/ImageComposite.h>\n#include <vw\/Mosaic\/QuadTreeGenerator.h>\n#include <vw\/Mosaic\/KMLQuadTreeConfig.h>\n\nusing namespace vw;\nusing namespace vw::cartography;\nusing namespace vw::mosaic;\n\nclass uint16_to_rgba8 : public ReturnFixedType<PixelRGBA<uint8> > {\n uint16 minval, maxval;\n double scale;\npublic:\n uint16_to_rgba8( uint16 minval, uint16 maxval ) : minval(minval), maxval(maxval), scale(255.0\/(maxval-minval)) {}\n PixelRGBA<uint8> operator()( uint16 pix ) const {\n if( pix == 0 ) return PixelRGBA<uint8>();\n uint8 val = (uint8) ( scale * (pix - minval) );\n if( pix < minval ) val = 0;\n else if( pix > maxval ) val = 255;\n return PixelRGBA<uint8>( val, val, val, 255 );\n }\n};\n\nclass rgb16_to_rgba8 : public ReturnFixedType<PixelRGBA<uint8> > {\n uint16 minval_r, maxval_r;\n double scale_r;\n uint16 minval_g, maxval_g;\n double scale_g;\n uint16 minval_b, maxval_b;\n double scale_b;\npublic:\n rgb16_to_rgba8( uint16 minval_r, uint16 maxval_r, uint16 minval_g, uint16 maxval_g, uint16 minval_b, uint16 maxval_b )\n : minval_r(minval_r), maxval_r(maxval_r), scale_r(255.0\/(maxval_r-minval_r)),\n minval_g(minval_g), maxval_g(maxval_g), scale_g(255.0\/(maxval_g-minval_g)),\n minval_b(minval_b), maxval_b(maxval_b), scale_b(255.0\/(maxval_b-minval_b))\n {}\n PixelRGBA<uint8> operator()( PixelRGB<uint16> const& pix ) const {\n if( pix.r()==0 || pix.g()==0 || pix.b()==0 ) return PixelRGBA<uint8>();\n PixelRGBA<uint8> result( (uint8)(scale_r*(pix.r()-minval_r)), (uint8)(scale_g*(pix.g()-minval_g)), (uint8)(scale_b*(pix.b()-minval_b)), 255 );\n if( pix.r() < minval_r ) result.r() = 0;\n else if( pix.r() > maxval_r ) result.r() = 255;\n if( pix.g() < minval_g ) result.g() = 0;\n else if( pix.g() > maxval_g ) result.g() = 255;\n if( pix.b() < minval_b ) result.b() = 0;\n else if( pix.b() > maxval_b ) result.b() = 255;\n return result;\n }\n};\n\nPixelRGB<uint8> rgba8_to_rgb8( PixelRGBA<uint8> const& rgba ) {\n if( rgba.a() != 255 ) return PixelRGB<uint8>();\n else return PixelRGB<uint8>( rgba );\n}\n\n\nint main( int argc, char *argv[] ) {\n\n std::vector<std::string> image_files;\n std::string output_file_name;\n std::string output_file_type;\n float jpeg_quality;\n int png_compression;\n unsigned cache_size;\n int draw_order_offset;\n int max_lod_pixels;\n int levels=0;\n int aspect_ratio=0;\n\n po::options_description general_options(\"General Options\");\n general_options.add_options()\n (\"output-name,o\", po::value<std::string>(&output_file_name)->default_value(\"output\"), \"Specify the base output filename\")\n (\"quiet,q\", \"Quiet output\")\n (\"verbose,v\", \"Verbose output\")\n (\"cache\", po::value<unsigned>(&cache_size)->default_value(768), \"Cache size, in megabytes\")\n (\"help\", \"Display this help message\");\n\n po::options_description output_options(\"Output Options\");\n output_options.add_options()\n (\"file-type\", po::value<std::string>(&output_file_type)->default_value(\"auto\"), \"Output file type\")\n (\"jpeg-quality\", po::value<float>(&jpeg_quality)->default_value(0.95), \"JPEG quality factor (0.0 to 1.0)\")\n (\"png-compression\", po::value<int>(&png_compression)->default_value(3), \"PNG compression level (0 to 9)\")\n (\"draw-order-offset\", po::value<int>(&draw_order_offset)->default_value(0), \"Set an offset for the KML <drawOrder> tag for this overlay\")\n (\"max-lod-pixels\", po::value<int>(&max_lod_pixels)->default_value(1024), \"Max LoD in pixels, or -1 for none (kml only)\")\n (\"levels\", po::value<int>(&levels), \"Number of levels in the global quadtree\")\n (\"alpha\", \"Output an alpha-masked geotiff\")\n (\"aspect-ratio\", po::value<int>(&aspect_ratio)->default_value(1),\"Pixel aspect ratio (for polar overlays; should be a power of two)\");\n\n po::options_description hidden_options(\"\");\n hidden_options.add_options()\n (\"input-file\", po::value<std::vector<std::string> >(&image_files));\n\n po::options_description options(\"Allowed Options\");\n options.add(general_options).add(output_options).add(hidden_options);\n\n po::positional_options_description p;\n p.add(\"input-file\", -1);\n\n po::variables_map vm;\n po::store( po::command_line_parser( argc, argv ).options(options).positional(p).run(), vm );\n po::notify( vm );\n\n std::ostringstream usage;\n usage << \"Usage: image2kml [options] <filename>...\" << std::endl << std::endl;\n usage << general_options << std::endl;\n usage << output_options << std::endl;\n\n if( vm.count(\"help\") ) {\n std::cout << usage.str();\n return 1;\n }\n\n if( vm.count(\"input-file\") < 1 ) {\n std::cout << \"Error: Must specify at least one input file!\" << std::endl << std::endl;\n std::cout << usage.str();\n return 1;\n }\n\n TerminalProgressCallback tpc(\"plate.tools.hirise2tif\", \"\");\n const ProgressCallback *progress = &tpc;\n if( vm.count(\"verbose\") ) {\n set_debug_level(VerboseDebugMessage);\n progress = &ProgressCallback::dummy_instance();\n }\n else if( vm.count(\"quiet\") ) {\n set_debug_level(WarningMessage);\n }\n\n DiskImageResourceJPEG::set_default_quality( jpeg_quality );\n DiskImageResourcePNG::set_default_compression_level( png_compression );\n vw_settings().set_system_cache_size( cache_size*1024*1024 );\n\n uint16 min_gray=1024, max_gray=0, min_i=1024, max_i=0, min_r=1024, max_r=0, min_b=1024, max_b=0;\n\n int filter = 128;\n if( image_files.size() > 1 ) {\n std::cout << \"Scanning IRB image for autoscaling...\" << std::endl;\n DiskImageView<PixelRGB<uint16> > image( image_files[1] );\n ImageView<PixelRGB<uint16> > stripe( image.cols(), filter );\n TerminalProgressCallback progress(\"plate.tools.hirise2tif\", \"\");\n for( int y=0; y+filter-1<image.rows(); y+=filter ) {\n progress.report_progress( (double)y \/ image.rows() );\n stripe = crop( image, 0, y, image.cols(), filter );\n ImageView<PixelRGB<uint16> >::pixel_accessor col = stripe.origin();\n for( int x=0; x+filter-1<image.cols(); x+=filter ) {\n int i=0,r=0,b=0,n=0;\n ImageView<PixelRGB<uint16> >::pixel_accessor row = col;\n for( int yy=0; yy<filter; ++yy ) {\n ImageView<PixelRGB<uint16> >::pixel_accessor pos = row;\n for( int xx=0; xx<filter; ++xx ) {\n PixelRGB<uint16> &val = *pos;\n pos.next_col();\n if( val.r()==0 || val.g()==0 || val.b()==0 ) continue;\n i += val.r();\n r += val.g();\n b += val.b();\n n ++;\n }\n row.next_row();\n }\n col.advance(filter,0);\n if( n < filter*filter\/4 ) continue;\n if( i\/n > max_i ) max_i = i\/n;\n if( i\/n < min_i ) min_i = i\/n;\n if( r\/n > max_r ) max_r = r\/n;\n if( r\/n < min_r ) min_r = r\/n;\n if( b\/n > max_b ) max_b = b\/n;\n if( b\/n < min_b ) min_b = b\/n;\n }\n }\n progress.report_finished();\n }\n {\n std::cout << \"Scanning red image for autoscaling...\" << std::endl;\n DiskImageView<uint16> image( image_files[0] );\n ImageView<uint16> stripe( image.cols(), filter );\n TerminalProgressCallback progress;\n for( int y=0; y+filter-1<image.rows(); y+=filter ) {\n progress.report_progress( (double)y \/ image.rows() );\n stripe = crop( image, 0, y, image.cols(), filter );\n ImageView<uint16>::pixel_accessor col = stripe.origin();\n for( int x=0; x+filter-1<image.cols(); x+=filter ) {\n int r=0,n=0;\n ImageView<uint16>::pixel_accessor row = col;\n for( int yy=0; yy<filter; ++yy ) {\n ImageView<uint16>::pixel_accessor pos = row;\n for( int xx=0; xx<filter; ++xx ) {\n uint16 &val = *pos;\n pos.next_col();\n if( val == 0 ) continue;\n r += val;\n n ++;\n }\n row.next_row();\n }\n col.advance(filter,0);\n if( n < filter*filter\/4 ) continue;\n if( r\/n > max_gray ) max_gray = r\/n;\n if( r\/n < min_gray ) min_gray = r\/n;\n }\n }\n progress.report_finished();\n }\n\n std::cout << \"Pixel ranges:\\n\";\n std::cout << \"\\tGRAY: \" << min_gray << \" - \" << max_gray << std::endl;\n std::cout << \"\\tIR: \" << min_i << \" - \" << max_i << std::endl;\n std::cout << \"\\tRED: \" << min_r << \" - \" << max_r << std::endl;\n std::cout << \"\\tBLUE: \" << min_b << \" - \" << max_b << std::endl;\n\n \/\/ Add the transformed input files to the composite\n ImageComposite<PixelRGBA<uint8> > composite;\n GeoReference master_georef;\n for( unsigned i=0; i<image_files.size(); ++i ) {\n DiskImageResourceGDAL *r = new DiskImageResourceGDAL( image_files[i] );\n GeoReference georef;\n read_georeference( georef, *r );\n if( i==0 ) master_georef = georef;\n Vector2 position = master_georef.lonlat_to_pixel( georef.pixel_to_lonlat( Vector2() ) );\n std::cout << position << std::endl;\n if( r->pixel_format() == VW_PIXEL_GRAY ) {\n composite.insert( per_pixel_filter( DiskImageView<uint16>( r ), uint16_to_rgba8(min_gray,max_gray) ),\n math::impl::_round(position.x()), math::impl::_round(position.y()) );\n }\n else {\n composite.insert( per_pixel_filter( DiskImageView<PixelRGB<uint16> >( r ), rgb16_to_rgba8(min_i,max_i,min_r,max_r,min_b,max_b) ),\n math::impl::_round(position.x()), math::impl::_round(position.y()) );\n }\n }\n\n \/\/ Update the georeference\n BBox2i pixel_bbox = composite.bbox();\n Vector2 offset = master_georef.pixel_to_point( pixel_bbox.min() ) - master_georef.pixel_to_point( Vector2() );\n Matrix3x3 M = master_georef.transform();\n M(0,2) += offset.x();\n M(1,2) += offset.y();\n if( ! master_georef.is_projected() ) {\n if( M(0,2) > 180 ) M(0,2) -= 360;\n }\n master_georef.set_transform( M );\n\n \/\/ Prepare the composite\n composite.set_draft_mode( true );\n composite.prepare();\n\n std::cout << \"Generating output GeoTIFF...\" << std::endl;\n DiskImageResourceGDAL::Options gdal_options;\n gdal_options[\"COMPRESS\"] = \"NONE\";\n gdal_options[\"BIGTIFF\"] = \"YES\";\n\n std::cout << \"NAME: \" << output_file_name << std::endl;\n ImageFormat format = composite.format();\n if( vm.count(\"alpha\") ) {\n DiskImageResourceGDAL output_resource( output_file_name, format, Vector2i(256,256), gdal_options );\n write_georeference( output_resource, master_georef );\n std::cout << \"Retaining alpha channel!\" << std::endl;\n write_image( output_resource, composite, TerminalProgressCallback() );\n } else {\n format.pixel_format = VW_PIXEL_RGB;\n DiskImageResourceGDAL output_resource( output_file_name, format, Vector2i(256,256), gdal_options );\n write_georeference( output_resource, master_georef );\n std::cout << \"Replacing alpha with black!\" << std::endl;\n write_image( output_resource, per_pixel_filter(composite,&rgba8_to_rgb8), TerminalProgressCallback() );\n }\n\n return 0;\n}\n<commit_msg>warning fixes<commit_after>\/\/ __BEGIN_LICENSE__\n\/\/ Copyright (C) 2006-2010 United States Government as represented by\n\/\/ the Administrator of the National Aeronautics and Space Administration.\n\/\/ All Rights Reserved.\n\/\/ __END_LICENSE__\n\n\n#ifdef _MSC_VER\n#pragma warning(disable:4244)\n#pragma warning(disable:4267)\n#pragma warning(disable:4996)\n#endif\n\n#include <stdlib.h>\n#include <iostream>\n#include <fstream>\n\n#include <boost\/program_options.hpp>\nnamespace po = boost::program_options;\n\n#include <vw\/Core\/Cache.h>\n#include <vw\/Core\/ProgressCallback.h>\n#include <vw\/Math\/Matrix.h>\n#include <vw\/Image\/Transform.h>\n#include <vw\/Image\/Palette.h>\n#include <vw\/FileIO\/DiskImageResource.h>\n#include <vw\/FileIO\/DiskImageResourceJPEG.h>\n#include <vw\/FileIO\/DiskImageResourcePNG.h>\n#include <vw\/FileIO\/DiskImageResourceGDAL.h>\n#include <vw\/FileIO\/DiskImageView.h>\n#include <vw\/Cartography\/GeoReference.h>\n#include <vw\/Cartography\/GeoTransform.h>\n#include <vw\/Cartography\/FileIO.h>\n#include <vw\/Mosaic\/ImageComposite.h>\n#include <vw\/Mosaic\/QuadTreeGenerator.h>\n#include <vw\/Mosaic\/KMLQuadTreeConfig.h>\n\nusing namespace vw;\nusing namespace vw::cartography;\nusing namespace vw::mosaic;\n\nclass uint16_to_rgba8 : public ReturnFixedType<PixelRGBA<uint8> > {\n uint16 minval, maxval;\n double scale;\npublic:\n uint16_to_rgba8( uint16 minval, uint16 maxval ) : minval(minval), maxval(maxval), scale(255.0\/(maxval-minval)) {}\n PixelRGBA<uint8> operator()( uint16 pix ) const {\n if( pix == 0 ) return PixelRGBA<uint8>();\n uint8 val = (uint8) ( scale * (pix - minval) );\n if( pix < minval ) val = 0;\n else if( pix > maxval ) val = 255;\n return PixelRGBA<uint8>( val, val, val, 255 );\n }\n};\n\nclass rgb16_to_rgba8 : public ReturnFixedType<PixelRGBA<uint8> > {\n uint16 minval_r, maxval_r;\n double scale_r;\n uint16 minval_g, maxval_g;\n double scale_g;\n uint16 minval_b, maxval_b;\n double scale_b;\npublic:\n rgb16_to_rgba8( uint16 minval_r, uint16 maxval_r, uint16 minval_g, uint16 maxval_g, uint16 minval_b, uint16 maxval_b )\n : minval_r(minval_r), maxval_r(maxval_r), scale_r(255.0\/(maxval_r-minval_r)),\n minval_g(minval_g), maxval_g(maxval_g), scale_g(255.0\/(maxval_g-minval_g)),\n minval_b(minval_b), maxval_b(maxval_b), scale_b(255.0\/(maxval_b-minval_b))\n {}\n PixelRGBA<uint8> operator()( PixelRGB<uint16> const& pix ) const {\n if( pix.r()==0 || pix.g()==0 || pix.b()==0 ) return PixelRGBA<uint8>();\n PixelRGBA<uint8> result( (uint8)(scale_r*(pix.r()-minval_r)), (uint8)(scale_g*(pix.g()-minval_g)), (uint8)(scale_b*(pix.b()-minval_b)), 255 );\n if( pix.r() < minval_r ) result.r() = 0;\n else if( pix.r() > maxval_r ) result.r() = 255;\n if( pix.g() < minval_g ) result.g() = 0;\n else if( pix.g() > maxval_g ) result.g() = 255;\n if( pix.b() < minval_b ) result.b() = 0;\n else if( pix.b() > maxval_b ) result.b() = 255;\n return result;\n }\n};\n\nPixelRGB<uint8> rgba8_to_rgb8( PixelRGBA<uint8> const& rgba ) {\n if( rgba.a() != 255 ) return PixelRGB<uint8>();\n else return PixelRGB<uint8>( rgba );\n}\n\n\nint main( int argc, char *argv[] ) {\n\n std::vector<std::string> image_files;\n std::string output_file_name;\n std::string output_file_type;\n float jpeg_quality;\n int png_compression;\n unsigned cache_size;\n int draw_order_offset;\n int max_lod_pixels;\n int levels=0;\n int aspect_ratio=0;\n\n po::options_description general_options(\"General Options\");\n general_options.add_options()\n (\"output-name,o\", po::value<std::string>(&output_file_name)->default_value(\"output\"), \"Specify the base output filename\")\n (\"quiet,q\", \"Quiet output\")\n (\"verbose,v\", \"Verbose output\")\n (\"cache\", po::value<unsigned>(&cache_size)->default_value(768), \"Cache size, in megabytes\")\n (\"help\", \"Display this help message\");\n\n po::options_description output_options(\"Output Options\");\n output_options.add_options()\n (\"file-type\", po::value<std::string>(&output_file_type)->default_value(\"auto\"), \"Output file type\")\n (\"jpeg-quality\", po::value<float>(&jpeg_quality)->default_value(0.95), \"JPEG quality factor (0.0 to 1.0)\")\n (\"png-compression\", po::value<int>(&png_compression)->default_value(3), \"PNG compression level (0 to 9)\")\n (\"draw-order-offset\", po::value<int>(&draw_order_offset)->default_value(0), \"Set an offset for the KML <drawOrder> tag for this overlay\")\n (\"max-lod-pixels\", po::value<int>(&max_lod_pixels)->default_value(1024), \"Max LoD in pixels, or -1 for none (kml only)\")\n (\"levels\", po::value<int>(&levels), \"Number of levels in the global quadtree\")\n (\"alpha\", \"Output an alpha-masked geotiff\")\n (\"aspect-ratio\", po::value<int>(&aspect_ratio)->default_value(1),\"Pixel aspect ratio (for polar overlays; should be a power of two)\");\n\n po::options_description hidden_options(\"\");\n hidden_options.add_options()\n (\"input-file\", po::value<std::vector<std::string> >(&image_files));\n\n po::options_description options(\"Allowed Options\");\n options.add(general_options).add(output_options).add(hidden_options);\n\n po::positional_options_description p;\n p.add(\"input-file\", -1);\n\n po::variables_map vm;\n po::store( po::command_line_parser( argc, argv ).options(options).positional(p).run(), vm );\n po::notify( vm );\n\n std::ostringstream usage;\n usage << \"Usage: image2kml [options] <filename>...\" << std::endl << std::endl;\n usage << general_options << std::endl;\n usage << output_options << std::endl;\n\n if( vm.count(\"help\") ) {\n std::cout << usage.str();\n return 1;\n }\n\n if( vm.count(\"input-file\") < 1 ) {\n std::cout << \"Error: Must specify at least one input file!\" << std::endl << std::endl;\n std::cout << usage.str();\n return 1;\n }\n\n TerminalProgressCallback tpc(\"plate.tools.hirise2tif\", \"\");\n const ProgressCallback *progress = &tpc;\n if( vm.count(\"verbose\") ) {\n set_debug_level(VerboseDebugMessage);\n progress = &ProgressCallback::dummy_instance();\n }\n else if( vm.count(\"quiet\") ) {\n set_debug_level(WarningMessage);\n }\n\n DiskImageResourceJPEG::set_default_quality( jpeg_quality );\n DiskImageResourcePNG::set_default_compression_level( png_compression );\n vw_settings().set_system_cache_size( cache_size*1024*1024 );\n\n uint16 min_gray=1024, max_gray=0, min_i=1024, max_i=0, min_r=1024, max_r=0, min_b=1024, max_b=0;\n\n int filter = 128;\n if( image_files.size() > 1 ) {\n std::cout << \"Scanning IRB image for autoscaling...\" << std::endl;\n DiskImageView<PixelRGB<uint16> > image( image_files[1] );\n ImageView<PixelRGB<uint16> > stripe( image.cols(), filter );\n TerminalProgressCallback progress(\"plate.tools.hirise2tif\", \"\");\n for( int y=0; y+filter-1<image.rows(); y+=filter ) {\n progress.report_progress( (double)y \/ image.rows() );\n stripe = crop( image, 0, y, image.cols(), filter );\n ImageView<PixelRGB<uint16> >::pixel_accessor col = stripe.origin();\n for( int x=0; x+filter-1<image.cols(); x+=filter ) {\n int i=0,r=0,b=0,n=0;\n ImageView<PixelRGB<uint16> >::pixel_accessor row = col;\n for( int yy=0; yy<filter; ++yy ) {\n ImageView<PixelRGB<uint16> >::pixel_accessor pos = row;\n for( int xx=0; xx<filter; ++xx ) {\n PixelRGB<uint16> &val = *pos;\n pos.next_col();\n if( val.r()==0 || val.g()==0 || val.b()==0 ) continue;\n i += val.r();\n r += val.g();\n b += val.b();\n n ++;\n }\n row.next_row();\n }\n col.advance(filter,0);\n if( n < filter*filter\/4 ) continue;\n if( i\/n > max_i ) max_i = i\/n;\n if( i\/n < min_i ) min_i = i\/n;\n if( r\/n > max_r ) max_r = r\/n;\n if( r\/n < min_r ) min_r = r\/n;\n if( b\/n > max_b ) max_b = b\/n;\n if( b\/n < min_b ) min_b = b\/n;\n }\n }\n progress.report_finished();\n }\n {\n std::cout << \"Scanning red image for autoscaling...\" << std::endl;\n DiskImageView<uint16> image( image_files[0] );\n ImageView<uint16> stripe( image.cols(), filter );\n TerminalProgressCallback progress(\"plate.tools.hirise2tif\", \"\");\n for( int y=0; y+filter-1<image.rows(); y+=filter ) {\n progress.report_progress( (double)y \/ image.rows() );\n stripe = crop( image, 0, y, image.cols(), filter );\n ImageView<uint16>::pixel_accessor col = stripe.origin();\n for( int x=0; x+filter-1<image.cols(); x+=filter ) {\n int r=0,n=0;\n ImageView<uint16>::pixel_accessor row = col;\n for( int yy=0; yy<filter; ++yy ) {\n ImageView<uint16>::pixel_accessor pos = row;\n for( int xx=0; xx<filter; ++xx ) {\n uint16 &val = *pos;\n pos.next_col();\n if( val == 0 ) continue;\n r += val;\n n ++;\n }\n row.next_row();\n }\n col.advance(filter,0);\n if( n < filter*filter\/4 ) continue;\n if( r\/n > max_gray ) max_gray = r\/n;\n if( r\/n < min_gray ) min_gray = r\/n;\n }\n }\n progress.report_finished();\n }\n\n std::cout << \"Pixel ranges:\\n\";\n std::cout << \"\\tGRAY: \" << min_gray << \" - \" << max_gray << std::endl;\n std::cout << \"\\tIR: \" << min_i << \" - \" << max_i << std::endl;\n std::cout << \"\\tRED: \" << min_r << \" - \" << max_r << std::endl;\n std::cout << \"\\tBLUE: \" << min_b << \" - \" << max_b << std::endl;\n\n \/\/ Add the transformed input files to the composite\n ImageComposite<PixelRGBA<uint8> > composite;\n GeoReference master_georef;\n for( unsigned i=0; i<image_files.size(); ++i ) {\n DiskImageResourceGDAL *r = new DiskImageResourceGDAL( image_files[i] );\n GeoReference georef;\n read_georeference( georef, *r );\n if( i==0 ) master_georef = georef;\n Vector2 position = master_georef.lonlat_to_pixel( georef.pixel_to_lonlat( Vector2() ) );\n std::cout << position << std::endl;\n if( r->pixel_format() == VW_PIXEL_GRAY ) {\n composite.insert( per_pixel_filter( DiskImageView<uint16>( r ), uint16_to_rgba8(min_gray,max_gray) ),\n math::impl::_round(position.x()), math::impl::_round(position.y()) );\n }\n else {\n composite.insert( per_pixel_filter( DiskImageView<PixelRGB<uint16> >( r ), rgb16_to_rgba8(min_i,max_i,min_r,max_r,min_b,max_b) ),\n math::impl::_round(position.x()), math::impl::_round(position.y()) );\n }\n }\n\n \/\/ Update the georeference\n BBox2i pixel_bbox = composite.bbox();\n Vector2 offset = master_georef.pixel_to_point( pixel_bbox.min() ) - master_georef.pixel_to_point( Vector2() );\n Matrix3x3 M = master_georef.transform();\n M(0,2) += offset.x();\n M(1,2) += offset.y();\n if( ! master_georef.is_projected() ) {\n if( M(0,2) > 180 ) M(0,2) -= 360;\n }\n master_georef.set_transform( M );\n\n \/\/ Prepare the composite\n composite.set_draft_mode( true );\n composite.prepare();\n\n std::cout << \"Generating output GeoTIFF...\" << std::endl;\n DiskImageResourceGDAL::Options gdal_options;\n gdal_options[\"COMPRESS\"] = \"NONE\";\n gdal_options[\"BIGTIFF\"] = \"YES\";\n\n std::cout << \"NAME: \" << output_file_name << std::endl;\n ImageFormat format = composite.format();\n if( vm.count(\"alpha\") ) {\n DiskImageResourceGDAL output_resource( output_file_name, format, Vector2i(256,256), gdal_options );\n write_georeference( output_resource, master_georef );\n std::cout << \"Retaining alpha channel!\" << std::endl;\n write_image( output_resource, composite, TerminalProgressCallback(\"plate.tools.hirise2tif\", \"\") );\n } else {\n format.pixel_format = VW_PIXEL_RGB;\n DiskImageResourceGDAL output_resource( output_file_name, format, Vector2i(256,256), gdal_options );\n write_georeference( output_resource, master_georef );\n std::cout << \"Replacing alpha with black!\" << std::endl;\n write_image( output_resource, per_pixel_filter(composite,&rgba8_to_rgb8), TerminalProgressCallback(\"plate.tools.hirise2tif\", \"\") );\n }\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"x11\/extensions\/xkb.hpp\"\n\n#include \"errors.hpp\"\n#include \"utils\/string.hpp\"\n#include \"x11\/connection.hpp\"\n#include \"x11\/extensions\/all.hpp\"\n\nPOLYBAR_NS\n\n\/**\n * Get next layout index\n *\/\nconst keyboard::indicator& keyboard::get(const indicator::type& i) const {\n return indicators.at(i);\n}\n\n\/**\n * Update indicator states\n *\/\nvoid keyboard::set(unsigned int state) {\n for (auto& i : indicators) {\n i.second.enabled = state & i.second.mask;\n }\n}\n\n\/**\n * Get state for the given class\n *\/\nbool keyboard::on(const indicator::type& i) const {\n return indicators.at(i).enabled;\n}\n\n\/**\n * Set current group number\n *\/\nvoid keyboard::current(unsigned char group) {\n current_group = group;\n}\n\n\/**\n * Get current group number\n *\/\nunsigned char keyboard::current() const {\n return current_group;\n}\n\n\/**\n * Get current group name\n *\/\nconst string keyboard::group_name(size_t index) const {\n if (!layouts.empty() && index < layouts.size()) {\n return layouts[index].group_name;\n }\n return \"\";\n}\n\n\/**\n * Get current layout name\n *\/\nconst string keyboard::layout_name(size_t index) const {\n if (index >= layouts.size() || index >= layouts[index].symbols.size()) {\n return \"\";\n }\n return layouts[index].symbols[index];\n}\n\n\/**\n * Get indicator name\n *\/\nconst string keyboard::indicator_name(const indicator::type& i) const {\n return indicators.at(i).name;\n}\n\nsize_t keyboard::size() const {\n return layouts.size();\n}\n\nnamespace xkb_util {\n \/**\n * Query for the XKB extension\n *\/\n void query_extension(connection& conn) {\n conn.xkb().use_extension(XCB_XKB_MAJOR_VERSION, XCB_XKB_MINOR_VERSION);\n\n if (!conn.extension<xpp::xkb::extension>()->present) {\n throw application_error(\"Missing X extension: XKb\");\n }\n }\n\n \/**\n * Get current group number\n *\/\n void switch_layout(connection& conn, xcb_xkb_device_spec_t device, unsigned char index) {\n xcb_xkb_latch_lock_state(conn, device, 0, 0, true, index, 0, 0, 0);\n xcb_flush(conn);\n }\n\n \/**\n * Get current group number\n *\/\n unsigned char get_current_group(connection& conn, xcb_xkb_device_spec_t device) {\n unsigned char result{0};\n auto reply = xcb_xkb_get_state_reply(conn, xcb_xkb_get_state(conn, device), nullptr);\n if (reply != nullptr) {\n result = reply->group;\n free(reply);\n }\n return result;\n }\n\n \/**\n * Get keyboard layouts\n *\/\n vector<keyboard::layout> get_layouts(connection& conn, xcb_xkb_device_spec_t device) {\n vector<keyboard::layout> results;\n\n unsigned int mask{XCB_XKB_NAME_DETAIL_GROUP_NAMES | XCB_XKB_NAME_DETAIL_SYMBOLS};\n auto reply = xcb_xkb_get_names_reply(conn, xcb_xkb_get_names(conn, device, mask), nullptr);\n\n if (reply == nullptr) {\n return results;\n }\n\n xcb_xkb_get_names_value_list_t values{};\n void* buffer = xcb_xkb_get_names_value_list(reply);\n xcb_xkb_get_names_value_list_unpack(buffer, reply->nTypes, reply->indicators, reply->virtualMods, reply->groupNames,\n reply->nKeys, reply->nKeyAliases, reply->nRadioGroups, reply->which, &values);\n\n using get_atom_name_reply = xpp::x::reply::checked::get_atom_name<connection&>;\n vector<get_atom_name_reply> replies;\n for (int i = 0; i < xcb_xkb_get_names_value_list_groups_length(reply, &values); i++) {\n replies.emplace_back(xpp::x::get_atom_name(conn, values.groups[i]));\n }\n\n for (const auto& reply : replies) {\n vector<string> sym_names;\n\n for (auto&& sym : string_util::split(conn.get_atom_name(values.symbolsName).name(), '+')) {\n if (!(sym = parse_layout_symbol(move(sym))).empty()) {\n sym_names.emplace_back(move(sym));\n }\n }\n\n results.emplace_back(keyboard::layout{static_cast<get_atom_name_reply>(reply).name(), sym_names});\n }\n\n free(reply);\n\n return results;\n }\n\n \/**\n * Get keyboard indicators\n *\/\n map<keyboard::indicator::type, keyboard::indicator> get_indicators(connection& conn, xcb_xkb_device_spec_t device) {\n map<keyboard::indicator::type, keyboard::indicator> results;\n\n unsigned int mask{XCB_XKB_NAME_DETAIL_INDICATOR_NAMES};\n auto reply = xcb_xkb_get_names_reply(conn, xcb_xkb_get_names(conn, device, mask), nullptr);\n\n if (reply == nullptr) {\n return results;\n }\n\n xcb_xkb_get_names_value_list_t values{};\n void* buffer = xcb_xkb_get_names_value_list(reply);\n xcb_xkb_get_names_value_list_unpack(buffer, reply->nTypes, reply->indicators, reply->virtualMods, reply->groupNames,\n reply->nKeys, reply->nKeyAliases, reply->nRadioGroups, reply->which, &values);\n\n using get_atom_name_reply = xpp::x::reply::checked::get_atom_name<connection&>;\n map<xcb_atom_t, get_atom_name_reply> entries;\n for (int i = 0; i < xcb_xkb_get_names_value_list_indicator_names_length(reply, &values); i++) {\n entries.emplace(values.indicatorNames[i], xpp::x::get_atom_name(conn, values.indicatorNames[i]));\n }\n\n for (const auto& entry : entries) {\n auto name = static_cast<get_atom_name_reply>(entry.second).name();\n auto type = keyboard::indicator::type::NONE;\n\n if (string_util::compare(name, \"caps lock\")) {\n type = keyboard::indicator::type::CAPS_LOCK;\n } else if (string_util::compare(name, \"num lock\")) {\n type = keyboard::indicator::type::NUM_LOCK;\n } else {\n continue;\n }\n\n auto data = conn.xkb().get_named_indicator(device, 0, 0, entry.first);\n auto mask = (*conn.xkb().get_indicator_map(device, 1 << data->ndx).maps().begin()).mods;\n auto enabled = static_cast<bool>(data->on);\n\n results.emplace(type, keyboard::indicator{entry.first, mask, name, enabled});\n }\n\n free(reply);\n\n return results;\n }\n\n \/**\n * Parse symbol name and exclude entries blacklisted entries\n *\/\n string parse_layout_symbol(string&& name) {\n size_t pos;\n while ((pos = name.find_first_of({'(', ':'})) != string::npos) {\n name.erase(pos);\n }\n if (string_util::contains(LAYOUT_SYMBOL_BLACKLIST, \";\" + name + \";\")) {\n return \"\";\n }\n return name;\n }\n}\n\nPOLYBAR_NS_END\n<commit_msg>fix: Move return value of parse_layout_symbol<commit_after>#include \"x11\/extensions\/xkb.hpp\"\n\n#include \"errors.hpp\"\n#include \"utils\/string.hpp\"\n#include \"x11\/connection.hpp\"\n#include \"x11\/extensions\/all.hpp\"\n\nPOLYBAR_NS\n\n\/**\n * Get next layout index\n *\/\nconst keyboard::indicator& keyboard::get(const indicator::type& i) const {\n return indicators.at(i);\n}\n\n\/**\n * Update indicator states\n *\/\nvoid keyboard::set(unsigned int state) {\n for (auto& i : indicators) {\n i.second.enabled = state & i.second.mask;\n }\n}\n\n\/**\n * Get state for the given class\n *\/\nbool keyboard::on(const indicator::type& i) const {\n return indicators.at(i).enabled;\n}\n\n\/**\n * Set current group number\n *\/\nvoid keyboard::current(unsigned char group) {\n current_group = group;\n}\n\n\/**\n * Get current group number\n *\/\nunsigned char keyboard::current() const {\n return current_group;\n}\n\n\/**\n * Get current group name\n *\/\nconst string keyboard::group_name(size_t index) const {\n if (!layouts.empty() && index < layouts.size()) {\n return layouts[index].group_name;\n }\n return \"\";\n}\n\n\/**\n * Get current layout name\n *\/\nconst string keyboard::layout_name(size_t index) const {\n if (index >= layouts.size() || index >= layouts[index].symbols.size()) {\n return \"\";\n }\n return layouts[index].symbols[index];\n}\n\n\/**\n * Get indicator name\n *\/\nconst string keyboard::indicator_name(const indicator::type& i) const {\n return indicators.at(i).name;\n}\n\nsize_t keyboard::size() const {\n return layouts.size();\n}\n\nnamespace xkb_util {\n \/**\n * Query for the XKB extension\n *\/\n void query_extension(connection& conn) {\n conn.xkb().use_extension(XCB_XKB_MAJOR_VERSION, XCB_XKB_MINOR_VERSION);\n\n if (!conn.extension<xpp::xkb::extension>()->present) {\n throw application_error(\"Missing X extension: XKb\");\n }\n }\n\n \/**\n * Get current group number\n *\/\n void switch_layout(connection& conn, xcb_xkb_device_spec_t device, unsigned char index) {\n xcb_xkb_latch_lock_state(conn, device, 0, 0, true, index, 0, 0, 0);\n xcb_flush(conn);\n }\n\n \/**\n * Get current group number\n *\/\n unsigned char get_current_group(connection& conn, xcb_xkb_device_spec_t device) {\n unsigned char result{0};\n auto reply = xcb_xkb_get_state_reply(conn, xcb_xkb_get_state(conn, device), nullptr);\n if (reply != nullptr) {\n result = reply->group;\n free(reply);\n }\n return result;\n }\n\n \/**\n * Get keyboard layouts\n *\/\n vector<keyboard::layout> get_layouts(connection& conn, xcb_xkb_device_spec_t device) {\n vector<keyboard::layout> results;\n\n unsigned int mask{XCB_XKB_NAME_DETAIL_GROUP_NAMES | XCB_XKB_NAME_DETAIL_SYMBOLS};\n auto reply = xcb_xkb_get_names_reply(conn, xcb_xkb_get_names(conn, device, mask), nullptr);\n\n if (reply == nullptr) {\n return results;\n }\n\n xcb_xkb_get_names_value_list_t values{};\n void* buffer = xcb_xkb_get_names_value_list(reply);\n xcb_xkb_get_names_value_list_unpack(buffer, reply->nTypes, reply->indicators, reply->virtualMods, reply->groupNames,\n reply->nKeys, reply->nKeyAliases, reply->nRadioGroups, reply->which, &values);\n\n using get_atom_name_reply = xpp::x::reply::checked::get_atom_name<connection&>;\n vector<get_atom_name_reply> replies;\n for (int i = 0; i < xcb_xkb_get_names_value_list_groups_length(reply, &values); i++) {\n replies.emplace_back(xpp::x::get_atom_name(conn, values.groups[i]));\n }\n\n for (const auto& reply : replies) {\n vector<string> sym_names;\n\n for (auto&& sym : string_util::split(conn.get_atom_name(values.symbolsName).name(), '+')) {\n if (!(sym = parse_layout_symbol(move(sym))).empty()) {\n sym_names.emplace_back(move(sym));\n }\n }\n\n results.emplace_back(keyboard::layout{static_cast<get_atom_name_reply>(reply).name(), sym_names});\n }\n\n free(reply);\n\n return results;\n }\n\n \/**\n * Get keyboard indicators\n *\/\n map<keyboard::indicator::type, keyboard::indicator> get_indicators(connection& conn, xcb_xkb_device_spec_t device) {\n map<keyboard::indicator::type, keyboard::indicator> results;\n\n unsigned int mask{XCB_XKB_NAME_DETAIL_INDICATOR_NAMES};\n auto reply = xcb_xkb_get_names_reply(conn, xcb_xkb_get_names(conn, device, mask), nullptr);\n\n if (reply == nullptr) {\n return results;\n }\n\n xcb_xkb_get_names_value_list_t values{};\n void* buffer = xcb_xkb_get_names_value_list(reply);\n xcb_xkb_get_names_value_list_unpack(buffer, reply->nTypes, reply->indicators, reply->virtualMods, reply->groupNames,\n reply->nKeys, reply->nKeyAliases, reply->nRadioGroups, reply->which, &values);\n\n using get_atom_name_reply = xpp::x::reply::checked::get_atom_name<connection&>;\n map<xcb_atom_t, get_atom_name_reply> entries;\n for (int i = 0; i < xcb_xkb_get_names_value_list_indicator_names_length(reply, &values); i++) {\n entries.emplace(values.indicatorNames[i], xpp::x::get_atom_name(conn, values.indicatorNames[i]));\n }\n\n for (const auto& entry : entries) {\n auto name = static_cast<get_atom_name_reply>(entry.second).name();\n auto type = keyboard::indicator::type::NONE;\n\n if (string_util::compare(name, \"caps lock\")) {\n type = keyboard::indicator::type::CAPS_LOCK;\n } else if (string_util::compare(name, \"num lock\")) {\n type = keyboard::indicator::type::NUM_LOCK;\n } else {\n continue;\n }\n\n auto data = conn.xkb().get_named_indicator(device, 0, 0, entry.first);\n auto mask = (*conn.xkb().get_indicator_map(device, 1 << data->ndx).maps().begin()).mods;\n auto enabled = static_cast<bool>(data->on);\n\n results.emplace(type, keyboard::indicator{entry.first, mask, name, enabled});\n }\n\n free(reply);\n\n return results;\n }\n\n \/**\n * Parse symbol name and exclude entries blacklisted entries\n *\/\n string parse_layout_symbol(string&& name) {\n size_t pos;\n while ((pos = name.find_first_of({'(', ':'})) != string::npos) {\n name.erase(pos);\n }\n if (string_util::contains(LAYOUT_SYMBOL_BLACKLIST, \";\" + name + \";\")) {\n return \"\";\n }\n return move(name);\n }\n}\n\nPOLYBAR_NS_END\n<|endoftext|>"} {"text":"<commit_before>#include \"message_entry.h\"\n#include <iostream>\n\nMessageEntry::MessageEntry(const api_client& api_client,\n const std::string& channel_id)\n : api_client_(api_client), channel_id_(channel_id) {\n}\n\nMessageEntry::~MessageEntry() {\n}\n\nvoid MessageEntry::on_activate() {\n const Glib::ustring text = get_text();\n set_text(\"\");\n std::cout << \"Post to \" << channel_id_ << \": \" << text << std::endl;\n std::map<std::string, std::string> params;\n params[\"channel\"] = channel_id_;\n params[\"text\"] = text.raw();\n params[\"as_user\"] = \"true\";\n auto result = api_client_.post(\"chat.postMessage\", params);\n if (result) {\n std::cout << result.get() << std::endl;\n }\n}\n<commit_msg>parse=full<commit_after>#include \"message_entry.h\"\n#include <iostream>\n\nMessageEntry::MessageEntry(const api_client& api_client,\n const std::string& channel_id)\n : api_client_(api_client), channel_id_(channel_id) {\n}\n\nMessageEntry::~MessageEntry() {\n}\n\nvoid MessageEntry::on_activate() {\n const Glib::ustring text = get_text();\n set_text(\"\");\n std::cout << \"Post to \" << channel_id_ << \": \" << text << std::endl;\n std::map<std::string, std::string> params;\n params[\"channel\"] = channel_id_;\n params[\"text\"] = text.raw();\n params[\"as_user\"] = \"true\";\n params[\"parse\"] = \"full\";\n auto result = api_client_.post(\"chat.postMessage\", params);\n if (result) {\n std::cout << result.get() << std::endl;\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/**\n ******************************************************************************\n * Xenia : Xbox 360 Emulator Research Project *\n ******************************************************************************\n * Copyright 2014 Ben Vanik. All rights reserved. *\n * Released under the BSD license - see LICENSE in the root for more details. *\n ******************************************************************************\n *\/\n\n#include \"xenia\/base\/main.h\"\n\n#include <fcntl.h>\n#include <gflags\/gflags.h>\n#include <io.h>\n\n#include <cstdlib>\n\n\/\/ Autogenerated by `xb premake`.\n#include \"build\/version.h\"\n\n#include \"xenia\/base\/logging.h\"\n#include \"xenia\/base\/platform_win.h\"\n#include \"xenia\/base\/string.h\"\n\n#include <bcrypt.h>\n\nDEFINE_bool(win32_high_freq, true,\n \"Requests high performance from the NT kernel\");\n\nnamespace xe {\n\nbool has_console_attached_ = true;\n\nbool has_console_attached() { return has_console_attached_; }\n\nvoid AttachConsole() {\n bool has_console = ::AttachConsole(ATTACH_PARENT_PROCESS) == TRUE;\n if (!has_console) {\n \/\/ We weren't launched from a console, so just return.\n \/\/ We could alloc our own console, but meh:\n \/\/ has_console = AllocConsole() == TRUE;\n has_console_attached_ = false;\n return;\n }\n has_console_attached_ = true;\n\n FILE* dummy;\n freopen_s(&dummy, \"CONIN$\", \"rb\", stdin);\n freopen_s(&dummy, \"CONOUT$\", \"wb\", stdout);\n freopen_s(&dummy, \"CONOUT$\", \"wb\", stderr);\n\n setvbuf(stdout, nullptr, _IONBF, 0);\n setvbuf(stderr, nullptr, _IONBF, 0);\n}\n\nstatic void RequestHighPerformance() {\n#if XE_PLATFORM_WIN32\n NTSTATUS(*NtQueryTimerResolution)\n (OUT PULONG MinimumResolution, OUT PULONG MaximumResolution,\n OUT PULONG CurrentResolution);\n\n NTSTATUS(*NtSetTimerResolution)\n (IN ULONG DesiredResolution, IN BOOLEAN SetResolution,\n OUT PULONG CurrentResolution);\n\n NtQueryTimerResolution = (decltype(NtQueryTimerResolution))GetProcAddress(\n GetModuleHandle(L\"ntdll.dll\"), \"NtQueryTimerResolution\");\n NtSetTimerResolution = (decltype(NtSetTimerResolution))GetProcAddress(\n GetModuleHandle(L\"ntdll.dll\"), \"NtSetTimerResolution\");\n if (!NtQueryTimerResolution || !NtSetTimerResolution) {\n return;\n }\n\n ULONG minimum_resolution, maximum_resolution, current_resolution;\n NtQueryTimerResolution(&minimum_resolution, &maximum_resolution,\n ¤t_resolution);\n NtSetTimerResolution(maximum_resolution, TRUE, ¤t_resolution);\n#endif\n}\n\nint Main() {\n auto entry_info = xe::GetEntryInfo();\n\n \/\/ Request high performance timing.\n if (FLAGS_win32_high_freq) {\n RequestHighPerformance();\n }\n\n \/\/ Convert command line to an argv-like format so we can share code\/use\n \/\/ gflags.\n auto command_line = GetCommandLineW();\n int argc;\n wchar_t** argv = CommandLineToArgvW(command_line, &argc);\n if (!argv) {\n return 1;\n }\n\n google::SetUsageMessage(std::string(\"usage: \") +\n xe::to_string(entry_info.usage));\n google::SetVersionString(\"1.0\");\n\n \/\/ Convert all args to narrow, as gflags doesn't support wchar.\n int argca = argc;\n char** argva = reinterpret_cast<char**>(alloca(sizeof(char*) * argca));\n for (int n = 0; n < argca; n++) {\n size_t len = std::wcstombs(nullptr, argv[n], 0);\n argva[n] = reinterpret_cast<char*>(alloca(sizeof(char) * (len + 1)));\n std::wcstombs(argva[n], argv[n], len + 1);\n }\n\n \/\/ Parse flags; this may delete some of them.\n google::ParseCommandLineFlags(&argc, &argva, true);\n\n \/\/ Widen all remaining flags and convert to usable strings.\n std::vector<std::wstring> args;\n for (int n = 0; n < argc; n++) {\n size_t len = std::mbstowcs(nullptr, argva[n], 0);\n auto argvw =\n reinterpret_cast<wchar_t*>(alloca(sizeof(wchar_t) * (len + 1)));\n std::mbstowcs(argvw, argva[n], len + 1);\n args.push_back(std::wstring(argvw));\n }\n\n \/\/ Setup COM on the main thread.\n \/\/ NOTE: this may fail if COM has already been initialized - that's OK.\n CoInitializeEx(nullptr, COINIT_MULTITHREADED);\n\n \/\/ Initialize logging. Needs parsed FLAGS.\n xe::InitializeLogging(entry_info.name);\n\n \/\/ Print version info.\n XELOGI(\"Build: %s \/ %s on %s\", XE_BUILD_BRANCH, XE_BUILD_COMMIT,\n XE_BUILD_DATE);\n\n \/\/ Call app-provided entry point.\n int result = entry_info.entry_point(args);\n\n xe::ShutdownLogging();\n google::ShutDownCommandLineFlags();\n LocalFree(argv);\n return result;\n}\n\n} \/\/ namespace xe\n\n\/\/ Used in console mode apps; automatically picked based on subsystem.\nint main(int argc_ignored, char** argv_ignored) { return xe::Main(); }\n\n\/\/ Used in windowed apps; automatically picked based on subsystem.\nint WINAPI wWinMain(HINSTANCE, HINSTANCE, LPWSTR command_line, int) {\n \/\/ Attach a console so we can write output to stdout. If the user hasn't\n \/\/ redirected output themselves it'll pop up a window.\n xe::AttachConsole();\n\n \/\/ Run normal entry point.\n return xe::Main();\n}\n\n#if defined _M_IX86\n#pragma comment( \\\n linker, \\\n \"\/manifestdependency:\\\"type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='x86' publicKeyToken='6595b64144ccf1df' language='*'\\\"\") \/\/ NOLINT(whitespace\/line_length)\n#elif defined _M_IA64\n#pragma comment( \\\n linker, \\\n \"\/manifestdependency:\\\"type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='ia64' publicKeyToken='6595b64144ccf1df' language='*'\\\"\") \/\/ NOLINT(whitespace\/line_length)\n#elif defined _M_X64\n#pragma comment( \\\n linker, \\\n \"\/manifestdependency:\\\"type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='amd64' publicKeyToken='6595b64144ccf1df' language='*'\\\"\") \/\/ NOLINT(whitespace\/line_length)\n#else\n#pragma comment( \\\n linker, \\\n \"\/manifestdependency:\\\"type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='*' publicKeyToken='6595b64144ccf1df' language='*'\\\"\") \/\/ NOLINT(whitespace\/line_length)\n#endif\n<commit_msg>[Base] Undo last commit because it breaks file redirection.<commit_after>\/**\n ******************************************************************************\n * Xenia : Xbox 360 Emulator Research Project *\n ******************************************************************************\n * Copyright 2014 Ben Vanik. All rights reserved. *\n * Released under the BSD license - see LICENSE in the root for more details. *\n ******************************************************************************\n *\/\n\n#include \"xenia\/base\/main.h\"\n\n#include <fcntl.h>\n#include <gflags\/gflags.h>\n#include <io.h>\n\n#include <cstdlib>\n\n\/\/ Autogenerated by `xb premake`.\n#include \"build\/version.h\"\n\n#include \"xenia\/base\/logging.h\"\n#include \"xenia\/base\/platform_win.h\"\n#include \"xenia\/base\/string.h\"\n\n#include <bcrypt.h>\n\nDEFINE_bool(win32_high_freq, true,\n \"Requests high performance from the NT kernel\");\n\nnamespace xe {\n\nbool has_console_attached_ = true;\n\nbool has_console_attached() { return has_console_attached_; }\n\nvoid AttachConsole() {\n bool has_console = ::AttachConsole(ATTACH_PARENT_PROCESS) == TRUE;\n if (!has_console) {\n \/\/ We weren't launched from a console, so just return.\n \/\/ We could alloc our own console, but meh:\n \/\/ has_console = AllocConsole() == TRUE;\n has_console_attached_ = false;\n return;\n }\n has_console_attached_ = true;\n\n auto std_handle = (intptr_t)GetStdHandle(STD_OUTPUT_HANDLE);\n auto con_handle = _open_osfhandle(std_handle, _O_TEXT);\n auto fp = _fdopen(con_handle, \"w\");\n *stdout = *fp;\n setvbuf(stdout, nullptr, _IONBF, 0);\n\n std_handle = (intptr_t)GetStdHandle(STD_ERROR_HANDLE);\n con_handle = _open_osfhandle(std_handle, _O_TEXT);\n fp = _fdopen(con_handle, \"w\");\n *stderr = *fp;\n setvbuf(stderr, nullptr, _IONBF, 0);\n}\n\nstatic void RequestHighPerformance() {\n#if XE_PLATFORM_WIN32\n NTSTATUS(*NtQueryTimerResolution)\n (OUT PULONG MinimumResolution, OUT PULONG MaximumResolution,\n OUT PULONG CurrentResolution);\n\n NTSTATUS(*NtSetTimerResolution)\n (IN ULONG DesiredResolution, IN BOOLEAN SetResolution,\n OUT PULONG CurrentResolution);\n\n NtQueryTimerResolution = (decltype(NtQueryTimerResolution))GetProcAddress(\n GetModuleHandle(L\"ntdll.dll\"), \"NtQueryTimerResolution\");\n NtSetTimerResolution = (decltype(NtSetTimerResolution))GetProcAddress(\n GetModuleHandle(L\"ntdll.dll\"), \"NtSetTimerResolution\");\n if (!NtQueryTimerResolution || !NtSetTimerResolution) {\n return;\n }\n\n ULONG minimum_resolution, maximum_resolution, current_resolution;\n NtQueryTimerResolution(&minimum_resolution, &maximum_resolution,\n ¤t_resolution);\n NtSetTimerResolution(maximum_resolution, TRUE, ¤t_resolution);\n#endif\n}\n\nint Main() {\n auto entry_info = xe::GetEntryInfo();\n\n \/\/ Request high performance timing.\n if (FLAGS_win32_high_freq) {\n RequestHighPerformance();\n }\n\n \/\/ Convert command line to an argv-like format so we can share code\/use\n \/\/ gflags.\n auto command_line = GetCommandLineW();\n int argc;\n wchar_t** argv = CommandLineToArgvW(command_line, &argc);\n if (!argv) {\n return 1;\n }\n\n google::SetUsageMessage(std::string(\"usage: \") +\n xe::to_string(entry_info.usage));\n google::SetVersionString(\"1.0\");\n\n \/\/ Convert all args to narrow, as gflags doesn't support wchar.\n int argca = argc;\n char** argva = reinterpret_cast<char**>(alloca(sizeof(char*) * argca));\n for (int n = 0; n < argca; n++) {\n size_t len = std::wcstombs(nullptr, argv[n], 0);\n argva[n] = reinterpret_cast<char*>(alloca(sizeof(char) * (len + 1)));\n std::wcstombs(argva[n], argv[n], len + 1);\n }\n\n \/\/ Parse flags; this may delete some of them.\n google::ParseCommandLineFlags(&argc, &argva, true);\n\n \/\/ Widen all remaining flags and convert to usable strings.\n std::vector<std::wstring> args;\n for (int n = 0; n < argc; n++) {\n size_t len = std::mbstowcs(nullptr, argva[n], 0);\n auto argvw =\n reinterpret_cast<wchar_t*>(alloca(sizeof(wchar_t) * (len + 1)));\n std::mbstowcs(argvw, argva[n], len + 1);\n args.push_back(std::wstring(argvw));\n }\n\n \/\/ Setup COM on the main thread.\n \/\/ NOTE: this may fail if COM has already been initialized - that's OK.\n CoInitializeEx(nullptr, COINIT_MULTITHREADED);\n\n \/\/ Initialize logging. Needs parsed FLAGS.\n xe::InitializeLogging(entry_info.name);\n\n \/\/ Print version info.\n XELOGI(\"Build: %s \/ %s on %s\", XE_BUILD_BRANCH, XE_BUILD_COMMIT,\n XE_BUILD_DATE);\n\n \/\/ Call app-provided entry point.\n int result = entry_info.entry_point(args);\n\n xe::ShutdownLogging();\n google::ShutDownCommandLineFlags();\n LocalFree(argv);\n return result;\n}\n\n} \/\/ namespace xe\n\n\/\/ Used in console mode apps; automatically picked based on subsystem.\nint main(int argc_ignored, char** argv_ignored) { return xe::Main(); }\n\n\/\/ Used in windowed apps; automatically picked based on subsystem.\nint WINAPI wWinMain(HINSTANCE, HINSTANCE, LPWSTR command_line, int) {\n \/\/ Attach a console so we can write output to stdout. If the user hasn't\n \/\/ redirected output themselves it'll pop up a window.\n xe::AttachConsole();\n\n \/\/ Run normal entry point.\n return xe::Main();\n}\n\n#if defined _M_IX86\n#pragma comment( \\\n linker, \\\n \"\/manifestdependency:\\\"type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='x86' publicKeyToken='6595b64144ccf1df' language='*'\\\"\") \/\/ NOLINT(whitespace\/line_length)\n#elif defined _M_IA64\n#pragma comment( \\\n linker, \\\n \"\/manifestdependency:\\\"type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='ia64' publicKeyToken='6595b64144ccf1df' language='*'\\\"\") \/\/ NOLINT(whitespace\/line_length)\n#elif defined _M_X64\n#pragma comment( \\\n linker, \\\n \"\/manifestdependency:\\\"type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='amd64' publicKeyToken='6595b64144ccf1df' language='*'\\\"\") \/\/ NOLINT(whitespace\/line_length)\n#else\n#pragma comment( \\\n linker, \\\n \"\/manifestdependency:\\\"type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='*' publicKeyToken='6595b64144ccf1df' language='*'\\\"\") \/\/ NOLINT(whitespace\/line_length)\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/*\nThis file is part of khmer, https:\/\/github.com\/dib-lab\/khmer\/, and is\nCopyright (C) 2015-2016, The Regents of the University of California.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are\nmet:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n\n * Redistributions in binary form must reproduce the above\n copyright notice, this list of conditions and the following\n disclaimer in the documentation and\/or other materials provided\n with the distribution.\n\n * Neither the name of the Michigan State University nor the names\n of its contributors may be used to endorse or promote products\n derived from this software without specific prior written\n permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\nLIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\nA PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\nHOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\nSPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\nLIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\nDATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\nTHEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\nLICENSE (END)\n\nContact: khmer-project@idyll.org\n*\/\n#include \"khmer.hh\"\n#include \"hashtable.hh\"\n#include \"traversal.hh\"\n#include \"symbols.hh\"\n#include \"kmer_hash.hh\"\n\n#define DEBUG 1\n\nusing namespace std;\n\nnamespace khmer {\n\n\nTraverser::Traverser(const Hashtable * ht) :\n KmerFactory(ht->ksize()), graph(ht)\n{\n bitmask = 0;\n for (unsigned int i = 0; i < _ksize; i++) {\n bitmask = (bitmask << 2) | 3;\n }\n rc_left_shift = _ksize * 2 - 2;\n}\n\nKmer Traverser::get_left(const Kmer& node, const char ch)\n const\n{\n HashIntoType kmer_f, kmer_r;\n kmer_f = ((node.kmer_f) >> 2 | twobit_repr(ch) << rc_left_shift);\n kmer_r = (((node.kmer_r) << 2) & bitmask) | (twobit_comp(ch));\n return build_kmer(kmer_f, kmer_r);\n}\n\n\nKmer Traverser::get_right(const Kmer& node, const char ch)\n const\n{\n HashIntoType kmer_f, kmer_r;\n kmer_f = (((node.kmer_f) << 2) & bitmask) | (twobit_repr(ch));\n kmer_r = ((node.kmer_r) >> 2) | (twobit_comp(ch) << rc_left_shift);\n return build_kmer(kmer_f, kmer_r);\n}\n\n\nunsigned int Traverser::traverse_left(Kmer& node,\n KmerQueue & node_q,\n std::function<bool (Kmer&)> filter,\n unsigned short max_neighbors)\n const\n{\n unsigned int found = 0;\n char * base = alphabets::DNA_SIMPLE;\n\n while(*base != '\\0') {\n Kmer prev_node = get_left(node, *base);\n if (graph->get_count(prev_node) && (!filter || filter(prev_node))) {\n node_q.push(prev_node);\n ++found;\n if (found > max_neighbors) {\n return found;\n }\n }\n ++base;\n }\n\n return found;\n}\n\nunsigned int Traverser::traverse_right(Kmer& node,\n KmerQueue & node_q,\n std::function<bool (Kmer&)> filter,\n unsigned short max_neighbors)\n const\n{\n unsigned int found = 0;\n char * base = alphabets::DNA_SIMPLE;\n\n while(*base != '\\0') {\n Kmer next_node = get_right(node, *base);\n if (graph->get_count(next_node) && (!filter || filter(next_node))) {\n node_q.push(next_node);\n ++found;\n if (found > max_neighbors) {\n return found;\n }\n }\n ++base;\n }\n\n return found;\n}\n\nunsigned int Traverser::degree_left(const Kmer& node)\n const\n{\n unsigned int degree = 0;\n char * base = alphabets::DNA_SIMPLE;\n\n while(*base != '\\0') {\n Kmer prev_node = get_left(node, *base);\n if (graph->get_count(prev_node)) {\n ++degree;\n }\n ++base;\n }\n\n return degree;\n}\n\nunsigned int Traverser::degree_right(const Kmer& node)\n const\n{\n unsigned int degree = 0;\n char * base = alphabets::DNA_SIMPLE;\n\n while(*base != '\\0') {\n Kmer next_node = get_right(node, *base);\n if (graph->get_count(next_node)) {\n ++degree;\n }\n ++base;\n }\n\n return degree;\n}\n\nunsigned int Traverser::degree(const Kmer& node)\n const\n{\n return degree_right(node) + degree_left(node);\n}\n\n\n\ntemplate<bool direction>\nAssemblerTraverser<direction>::AssemblerTraverser(const Hashtable * ht,\n Kmer start_kmer,\n KmerFilterList filters) :\n Traverser(ht), filters(filters)\n{\n cursor = start_kmer;\n}\n\ntemplate<>\nKmer AssemblerTraverser<LEFT>::get_neighbor(Kmer& node,\n const char symbol) {\n return get_left(node, symbol);\n}\n\ntemplate<>\nKmer AssemblerTraverser<RIGHT>::get_neighbor(Kmer& node,\n const char symbol) {\n return get_right(node, symbol);\n}\n\ntemplate<>\nunsigned int AssemblerTraverser<LEFT>::cursor_degree()\n const\n{\n return degree_left(cursor);\n}\n\ntemplate<>\nunsigned int AssemblerTraverser<RIGHT>::cursor_degree()\n const\n{\n return degree_right(cursor);\n}\n\ntemplate <>\nstd::string AssemblerTraverser<RIGHT>::join_contigs(std::string& contig_a,\n std::string& contig_b)\n const\n{\n return contig_a + contig_b.substr(_ksize);\n}\n\ntemplate <>\nstd::string AssemblerTraverser<LEFT>::join_contigs(std::string& contig_a,\n std::string& contig_b)\n const\n{\n return contig_b + contig_a.substr(_ksize);\n}\n\ntemplate<bool direction>\nchar AssemblerTraverser<direction>::next_symbol()\n{\n char * symbol_ptr = alphabets::DNA_SIMPLE;\n char base;\n short found = 0;\n Kmer neighbor;\n Kmer cursor_next;\n\n while(*symbol_ptr != '\\0') {\n neighbor = get_neighbor(cursor, *symbol_ptr);\n\n if (graph->get_count(neighbor) &&\n !apply_kmer_filters(neighbor, filters)) {\n\n found++;\n if (found > 1) {\n return '\\0';\n }\n base = *symbol_ptr;\n cursor_next = neighbor;\n }\n symbol_ptr++;\n }\n\n if (!found) {\n return '\\0';\n } else {\n cursor = cursor_next;\n return base;\n }\n}\n\n\ntemplate<bool direction>\nbool AssemblerTraverser<direction>::set_cursor(Kmer& node)\n{\n if(!apply_kmer_filters(node, filters)) {\n cursor = node;\n return true;\n }\n return false;\n}\n\ntemplate<bool direction>\nvoid AssemblerTraverser<direction>::push_filter(KmerFilter filter)\n{\n filters.push_back(filter);\n}\n\ntemplate<bool direction>\nKmerFilter AssemblerTraverser<direction>::pop_filter()\n{\n KmerFilter back = filters.back();\n filters.pop_back();\n return back;\n}\n\ntemplate<bool direction>\nNonLoopingAT<direction>::NonLoopingAT(const Hashtable * ht,\n Kmer start_kmer,\n KmerFilterList filters,\n SeenSet * visited) :\n AssemblerTraverser<direction>(ht, start_kmer, filters), visited(visited)\n{\n AssemblerTraverser<direction>::push_filter(get_visited_filter(visited));\n}\n\ntemplate<bool direction>\nchar NonLoopingAT<direction>::next_symbol()\n{\n visited->insert(this->cursor);\n return AssemblerTraverser<direction>::next_symbol();\n}\n\n\ntemplate class AssemblerTraverser<RIGHT>;\ntemplate class AssemblerTraverser<LEFT>;\ntemplate class NonLoopingAT<RIGHT>;\ntemplate class NonLoopingAT<LEFT>;\n\n\n} \/\/ namespace khmer\n<commit_msg>Remove -Wmaybe-uninitialized compiler warning at traversal.cc 225<commit_after>\/*\nThis file is part of khmer, https:\/\/github.com\/dib-lab\/khmer\/, and is\nCopyright (C) 2015-2016, The Regents of the University of California.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are\nmet:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n\n * Redistributions in binary form must reproduce the above\n copyright notice, this list of conditions and the following\n disclaimer in the documentation and\/or other materials provided\n with the distribution.\n\n * Neither the name of the Michigan State University nor the names\n of its contributors may be used to endorse or promote products\n derived from this software without specific prior written\n permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\nLIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\nA PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\nHOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\nSPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\nLIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\nDATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\nTHEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\nLICENSE (END)\n\nContact: khmer-project@idyll.org\n*\/\n#include \"khmer.hh\"\n#include \"hashtable.hh\"\n#include \"traversal.hh\"\n#include \"symbols.hh\"\n#include \"kmer_hash.hh\"\n\n#define DEBUG 1\n\nusing namespace std;\n\nnamespace khmer {\n\n\nTraverser::Traverser(const Hashtable * ht) :\n KmerFactory(ht->ksize()), graph(ht)\n{\n bitmask = 0;\n for (unsigned int i = 0; i < _ksize; i++) {\n bitmask = (bitmask << 2) | 3;\n }\n rc_left_shift = _ksize * 2 - 2;\n}\n\nKmer Traverser::get_left(const Kmer& node, const char ch)\n const\n{\n HashIntoType kmer_f, kmer_r;\n kmer_f = ((node.kmer_f) >> 2 | twobit_repr(ch) << rc_left_shift);\n kmer_r = (((node.kmer_r) << 2) & bitmask) | (twobit_comp(ch));\n return build_kmer(kmer_f, kmer_r);\n}\n\n\nKmer Traverser::get_right(const Kmer& node, const char ch)\n const\n{\n HashIntoType kmer_f, kmer_r;\n kmer_f = (((node.kmer_f) << 2) & bitmask) | (twobit_repr(ch));\n kmer_r = ((node.kmer_r) >> 2) | (twobit_comp(ch) << rc_left_shift);\n return build_kmer(kmer_f, kmer_r);\n}\n\n\nunsigned int Traverser::traverse_left(Kmer& node,\n KmerQueue & node_q,\n std::function<bool (Kmer&)> filter,\n unsigned short max_neighbors)\n const\n{\n unsigned int found = 0;\n char * base = alphabets::DNA_SIMPLE;\n\n while(*base != '\\0') {\n Kmer prev_node = get_left(node, *base);\n if (graph->get_count(prev_node) && (!filter || filter(prev_node))) {\n node_q.push(prev_node);\n ++found;\n if (found > max_neighbors) {\n return found;\n }\n }\n ++base;\n }\n\n return found;\n}\n\nunsigned int Traverser::traverse_right(Kmer& node,\n KmerQueue & node_q,\n std::function<bool (Kmer&)> filter,\n unsigned short max_neighbors)\n const\n{\n unsigned int found = 0;\n char * base = alphabets::DNA_SIMPLE;\n\n while(*base != '\\0') {\n Kmer next_node = get_right(node, *base);\n if (graph->get_count(next_node) && (!filter || filter(next_node))) {\n node_q.push(next_node);\n ++found;\n if (found > max_neighbors) {\n return found;\n }\n }\n ++base;\n }\n\n return found;\n}\n\nunsigned int Traverser::degree_left(const Kmer& node)\n const\n{\n unsigned int degree = 0;\n char * base = alphabets::DNA_SIMPLE;\n\n while(*base != '\\0') {\n Kmer prev_node = get_left(node, *base);\n if (graph->get_count(prev_node)) {\n ++degree;\n }\n ++base;\n }\n\n return degree;\n}\n\nunsigned int Traverser::degree_right(const Kmer& node)\n const\n{\n unsigned int degree = 0;\n char * base = alphabets::DNA_SIMPLE;\n\n while(*base != '\\0') {\n Kmer next_node = get_right(node, *base);\n if (graph->get_count(next_node)) {\n ++degree;\n }\n ++base;\n }\n\n return degree;\n}\n\nunsigned int Traverser::degree(const Kmer& node)\n const\n{\n return degree_right(node) + degree_left(node);\n}\n\n\n\ntemplate<bool direction>\nAssemblerTraverser<direction>::AssemblerTraverser(const Hashtable * ht,\n Kmer start_kmer,\n KmerFilterList filters) :\n Traverser(ht), filters(filters)\n{\n cursor = start_kmer;\n}\n\ntemplate<>\nKmer AssemblerTraverser<LEFT>::get_neighbor(Kmer& node,\n const char symbol) {\n return get_left(node, symbol);\n}\n\ntemplate<>\nKmer AssemblerTraverser<RIGHT>::get_neighbor(Kmer& node,\n const char symbol) {\n return get_right(node, symbol);\n}\n\ntemplate<>\nunsigned int AssemblerTraverser<LEFT>::cursor_degree()\n const\n{\n return degree_left(cursor);\n}\n\ntemplate<>\nunsigned int AssemblerTraverser<RIGHT>::cursor_degree()\n const\n{\n return degree_right(cursor);\n}\n\ntemplate <>\nstd::string AssemblerTraverser<RIGHT>::join_contigs(std::string& contig_a,\n std::string& contig_b)\n const\n{\n return contig_a + contig_b.substr(_ksize);\n}\n\ntemplate <>\nstd::string AssemblerTraverser<LEFT>::join_contigs(std::string& contig_a,\n std::string& contig_b)\n const\n{\n return contig_b + contig_a.substr(_ksize);\n}\n\ntemplate<bool direction>\nchar AssemblerTraverser<direction>::next_symbol()\n{\n char * symbol_ptr = alphabets::DNA_SIMPLE;\n char base = *symbol_ptr; \/\/ kill -Wmaybe-uninitialized warning\n short found = 0;\n Kmer neighbor;\n Kmer cursor_next;\n\n while(*symbol_ptr != '\\0') {\n neighbor = get_neighbor(cursor, *symbol_ptr);\n\n if (graph->get_count(neighbor) &&\n !apply_kmer_filters(neighbor, filters)) {\n\n found++;\n if (found > 1) {\n return '\\0';\n }\n base = *symbol_ptr;\n cursor_next = neighbor;\n }\n symbol_ptr++;\n }\n\n if (!found) {\n return '\\0';\n } else {\n cursor = cursor_next;\n return base;\n }\n}\n\n\ntemplate<bool direction>\nbool AssemblerTraverser<direction>::set_cursor(Kmer& node)\n{\n if(!apply_kmer_filters(node, filters)) {\n cursor = node;\n return true;\n }\n return false;\n}\n\ntemplate<bool direction>\nvoid AssemblerTraverser<direction>::push_filter(KmerFilter filter)\n{\n filters.push_back(filter);\n}\n\ntemplate<bool direction>\nKmerFilter AssemblerTraverser<direction>::pop_filter()\n{\n KmerFilter back = filters.back();\n filters.pop_back();\n return back;\n}\n\ntemplate<bool direction>\nNonLoopingAT<direction>::NonLoopingAT(const Hashtable * ht,\n Kmer start_kmer,\n KmerFilterList filters,\n SeenSet * visited) :\n AssemblerTraverser<direction>(ht, start_kmer, filters), visited(visited)\n{\n AssemblerTraverser<direction>::push_filter(get_visited_filter(visited));\n}\n\ntemplate<bool direction>\nchar NonLoopingAT<direction>::next_symbol()\n{\n visited->insert(this->cursor);\n return AssemblerTraverser<direction>::next_symbol();\n}\n\n\ntemplate class AssemblerTraverser<RIGHT>;\ntemplate class AssemblerTraverser<LEFT>;\ntemplate class NonLoopingAT<RIGHT>;\ntemplate class NonLoopingAT<LEFT>;\n\n\n} \/\/ namespace khmer\n<|endoftext|>"} {"text":"<commit_before>#ifndef STATIC_ARRAY_HPP\n# define STATIC_ARRAY_HPP\n# pragma once\n\n#include <algorithm>\n\ntemplate <typename A>\nclass static_array\n{\n A* p_;\n std::size_t const N_;\n\n template <auto, std::size_t N>\n static constinit inline A storage_[N];\n\n static constinit inline std::size_t c_; \/\/ instance counter\n\npublic:\n template <std::size_t N>\n static_array(A (&&a)[N]):\n N_(N)\n {\n [&]<auto ...I>(auto const c, std::index_sequence<I...>)\n {\n (\n (\n I == c ? p_ = storage_<I, N> : nullptr\n ),\n ...\n );\n }(c_++, std::make_index_sequence<128>());\n\n std::move(std::begin(a), std::end(a), begin());\n }\n\n static_array(static_array const&) = default;\n static_array(static_array&&) = default;\n\n \/\/\n static_array& operator=(static_array const&) = delete;\n static_array& operator=(static_array&&) = delete;\n\n \/\/\n auto begin() const noexcept { return p_; }\n auto end() const noexcept { return p_ + N_; }\n auto size() const noexcept { return N_; }\n};\n\n#endif \/\/ STATIC_ARRAY_HPP\n<commit_msg>some fixes<commit_after>#ifndef STATIC_ARRAY_HPP\n# define STATIC_ARRAY_HPP\n# pragma once\n\n#include <algorithm> \/\/ std::move()\n#include <iterator> \/\/ std::begin(), std::end()\n\nnamespace gnr\n{\n\ntemplate <typename A>\nclass static_array\n{\n A* p_;\n std::size_t const N_;\n\n template <auto, std::size_t N>\n static constinit inline A storage_[N];\n\n static constinit inline std::size_t c_; \/\/ instance counter\n\npublic:\n template <std::size_t N>\n static_array(A (&&a)[N]):\n N_(N)\n {\n [&]<auto ...I>(auto const c, std::index_sequence<I...>)\n {\n (\n (\n I == c ? p_ = storage_<I, N> : nullptr\n ),\n ...\n );\n }(c_++, std::make_index_sequence<128>());\n\n std::move(std::begin(a), std::end(a), begin());\n }\n\n static_array(static_array const&) = default;\n static_array(static_array&&) = default;\n\n \/\/\n static_array& operator=(static_array const&) = delete;\n static_array& operator=(static_array&&) = delete;\n\n \/\/\n auto begin() const noexcept { return p_; }\n auto end() const noexcept { return p_ + N_; }\n auto size() const noexcept { return N_; }\n};\n\n}\n\n#endif \/\/ STATIC_ARRAY_HPP\n<|endoftext|>"} {"text":"<commit_before>#include \"natstat_util.hpp\"\r\n\r\n#include <iomanip>\r\n#include <iostream>\r\n#include <sstream>\r\n\r\nvoid print_human(const natstat_t& natstat)\r\n{\r\n\tbool V6=false;\r\n\tif(natstat.proto.substr(3,1)==\"6\")\r\n\t\tV6=true;\r\n\tstd::ostringstream lstr;\r\n\tif(V6)\r\n\t\tlstr<<\"[\"<<natstat.laddr<<\"]:\"<<natstat.lport;\r\n\telse\r\n\t\tlstr<<natstat.laddr<<\":\"<<natstat.fport;\r\n\tstd::ostringstream rstr;\r\n\tif(V6)\r\n\t\trstr<<\"[\"<<natstat.faddr<<\"]:\"<<natstat.fport;\r\n\telse\r\n\t\trstr<<natstat.faddr<<\":\"<<natstat.fport;\r\n\tstd::cout<<\r\n\t\tstd::setw(5)<<natstat.proto<<\r\n\t\tstd::setw(46)<<lstr.str()<<\r\n\t\tstd::setw(46)<<rstr.str()<<\r\n\t\tstd::setw(16)<<natstat.state<<\r\n\t\tstd::setw(8)<<natstat.pid<<\r\n\t\tstd::endl;\r\n}\r\n\r\nvoid print_human(const natstat_list_t& natstats)\r\n{\r\n\tstd::cout<<\r\n\t\tstd::setw(5)<<\"proto\"<<\r\n\t\tstd::setw(46)<<\"local address\"<<\r\n\t\tstd::setw(46)<<\"foreign address\"<<\r\n\t\tstd::setw(16)<<\"state\"<<\r\n\t\tstd::setw(8)<<\"pid\"<<\r\n\t\tstd::endl;\r\n\tfor(size_t ii=0;ii<natstats.size();++ii)\r\n\t\t\tprint_human(natstats[ii]);\r\n}\r\n\r\nvoid print_wof(const natstat_t& natstat)\r\n{\r\n\tstd::cout<<natstat.proto.substr(0,3)<<\" \";\r\n\tbool V6=false;\r\n\tif(natstat.proto.substr(3,1)==\"6\")\r\n\t\tV6=true;\r\n\tif(V6)\r\n\t\tstd::cout<<\"[\"<<natstat.laddr<<\"]\";\r\n\telse\r\n\t\tstd::cout<<natstat.laddr;\r\n\tstd::cout<<\":\"<<natstat.lport;\r\n\tif(natstat.state==\"ESTABLISHED\")\r\n\t\tstd::cout<<\">\";\r\n\telse if(natstat.state==\"LISTEN\")\r\n\t\tstd::cout<<\"<\";\r\n\telse if(natstat.proto.substr(0,3)==\"udp\"&&natstat.state==\"-\")\r\n\t\tstd::cout<<\"<>\";\r\n\tif(V6)\r\n\t\tstd::cout<<\"[\"<<natstat.faddr<<\"]\";\r\n\telse\r\n\t\tstd::cout<<natstat.faddr;\r\n\tstd::cout<<\":\"<<natstat.fport;\r\n\tstd::cout<<\" #pid \"<<natstat.pid;\r\n\tstd::cout<<std::endl;\r\n}\r\n\r\nvoid print_wof(const natstat_list_t& natstats)\r\n{\r\n\tfor(size_t ii=0;ii<natstats.size();++ii)\r\n\t\tprint_wof(natstats[ii]);\r\n}<commit_msg>Auto sizing columns for human readable output.<commit_after>#include \"natstat_util.hpp\"\r\n\r\n#include <iomanip>\r\n#include <iostream>\r\n#include <sstream>\r\n\r\nvoid print_human(const natstat_t& natstat,std::vector<size_t> cols)\r\n{\r\n\tif(cols.size()<4)\r\n\t{\r\n\t\tcols.clear();\r\n\t\tcols.push_back(5);\r\n\t\tcols.push_back(46);\r\n\t\tcols.push_back(46);\r\n\t\tcols.push_back(16);\r\n\t\tcols.push_back(8);\r\n\t}\r\n\tbool V6=false;\r\n\tif(natstat.proto.substr(3,1)==\"6\")\r\n\t\tV6=true;\r\n\tstd::ostringstream lstr;\r\n\tif(V6)\r\n\t\tlstr<<\"[\"<<natstat.laddr<<\"]:\"<<natstat.lport;\r\n\telse\r\n\t\tlstr<<natstat.laddr<<\":\"<<natstat.fport;\r\n\tstd::ostringstream rstr;\r\n\tif(V6)\r\n\t\trstr<<\"[\"<<natstat.faddr<<\"]:\"<<natstat.fport;\r\n\telse\r\n\t\trstr<<natstat.faddr<<\":\"<<natstat.fport;\r\n\tstd::cout<<\r\n\t\tstd::setw(cols[0])<<natstat.proto<<\r\n\t\tstd::setw(cols[1])<<lstr.str()<<\r\n\t\tstd::setw(cols[2])<<rstr.str()<<\r\n\t\tstd::setw(cols[3])<<natstat.state<<\r\n\t\tstd::setw(cols[4])<<natstat.pid<<\r\n\t\tstd::endl;\r\n}\r\n\r\nvoid print_human(const natstat_list_t& natstats)\r\n{\r\n\tsize_t pad=1;\r\n\tstd::vector<size_t> cols;\r\n\tcols.push_back(5+pad);\r\n\tcols.push_back(15+pad);\r\n\tcols.push_back(15+pad);\r\n\tcols.push_back(5+pad);\r\n\tcols.push_back(3+pad);\r\n\tfor(size_t ii=0;ii<natstats.size();++ii)\r\n\t{\r\n\t\tif(natstats[ii].proto.size()+pad>cols[0])\r\n\t\t\tcols[0]=natstats[ii].proto.size()+pad;\r\n\t\tif(natstats[ii].laddr.size()+7+pad>cols[1])\r\n\t\t\tcols[1]=natstats[ii].laddr.size()+7+pad;\r\n\t\tif(natstats[ii].faddr.size()+7>cols[2])\r\n\t\t\tcols[2]=natstats[ii].faddr.size()+7+pad;\r\n\t\tif(natstats[ii].state.size()+pad>cols[3])\r\n\t\t\tcols[3]=natstats[ii].state.size()+pad;\r\n\t\tif(natstats[ii].pid.size()+pad>cols[4])\r\n\t\t\tcols[4]=natstats[ii].pid.size()+pad;\r\n\t}\r\n\tstd::cout<<\r\n\t\tstd::setw(cols[0])<<\"proto\"<<\r\n\t\tstd::setw(cols[1])<<\"local address\"<<\r\n\t\tstd::setw(cols[2])<<\"foreign address\"<<\r\n\t\tstd::setw(cols[3])<<\"state\"<<\r\n\t\tstd::setw(cols[4])<<\"pid\"<<\r\n\t\tstd::endl;\r\n\tfor(size_t ii=0;ii<natstats.size();++ii)\r\n\t\tprint_human(natstats[ii],cols);\r\n}\r\n\r\nvoid print_wof(const natstat_t& natstat)\r\n{\r\n\tstd::cout<<natstat.proto.substr(0,3)<<\" \";\r\n\tbool V6=false;\r\n\tif(natstat.proto.substr(3,1)==\"6\")\r\n\t\tV6=true;\r\n\tif(V6)\r\n\t\tstd::cout<<\"[\"<<natstat.laddr<<\"]\";\r\n\telse\r\n\t\tstd::cout<<natstat.laddr;\r\n\tstd::cout<<\":\"<<natstat.lport;\r\n\tif(natstat.state==\"ESTABLISHED\")\r\n\t\tstd::cout<<\">\";\r\n\telse if(natstat.state==\"LISTEN\")\r\n\t\tstd::cout<<\"<\";\r\n\telse if(natstat.proto.substr(0,3)==\"udp\"&&natstat.state==\"-\")\r\n\t\tstd::cout<<\"<>\";\r\n\tif(V6)\r\n\t\tstd::cout<<\"[\"<<natstat.faddr<<\"]\";\r\n\telse\r\n\t\tstd::cout<<natstat.faddr;\r\n\tstd::cout<<\":\"<<natstat.fport;\r\n\tstd::cout<<\" #pid \"<<natstat.pid;\r\n\tstd::cout<<std::endl;\r\n}\r\n\r\nvoid print_wof(const natstat_list_t& natstats)\r\n{\r\n\tfor(size_t ii=0;ii<natstats.size();++ii)\r\n\t\tprint_wof(natstats[ii]);\r\n}<|endoftext|>"} {"text":"<commit_before>\/* BEGIN_COMMON_COPYRIGHT_HEADER\n * (c)LGPL2+\n *\n * LXDE-Qt - a lightweight, Qt based, desktop toolset\n * http:\/\/razor-qt.org\n *\n * Copyright: 2012 Razor team\n * Authors:\n * Petr Vanek <petr@scribus.info>\n *\n * This program or library is free software; you can redistribute it\n * and\/or modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n\n * You should have received a copy of the GNU Lesser General\n * Public License along with this library; if not, write to the\n * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,\n * Boston, MA 02110-1301 USA\n *\n * END_COMMON_COPYRIGHT_HEADER *\/\n\n#include <QPainter>\n#include <QUrl>\n#include <QFile>\n#include <QDateTime>\n#include <QtDBus\/QDBusArgument>\n\n#include <XdgIcon>\n\n#include \"notification.h\"\n#include \"notificationwidgets.h\"\n\n#include <QtDebug>\n\/\/ this *must* go last due Qt's moc\n#include <LXQt\/XfitMan>\n\n\n#define ICONSIZE QSize(32, 32)\n\n\nNotification::Notification(const QString &application,\n const QString &summary, const QString &body,\n const QString &icon, int timeout,\n const QStringList& actions, const QVariantMap& hints,\n QWidget *parent)\n : QWidget(parent),\n m_timer(0),\n m_actionWidget(0)\n{\n setupUi(this);\n setObjectName(\"Notification\");\n setMouseTracking(true);\n \n setMaximumWidth(parent->width());\n setMinimumWidth(parent->width());\n\n setValues(application, summary, body, icon, timeout, actions, hints);\n\n connect(closeButton, SIGNAL(clicked()), this, SLOT(closeButton_clicked()));\n}\n\nvoid Notification::setValues(const QString &application,\n const QString &summary, const QString &body,\n const QString &icon, int timeout,\n const QStringList& actions, const QVariantMap& hints)\n{\n \/\/ Basic properties *********************\n\n \/\/ Notifications spec set real order here:\n \/\/ An implementation which only displays one image or icon must\n \/\/ choose which one to display using the following order:\n \/\/ - \"image-data\"\n \/\/ - \"image-path\"\n \/\/ - app_icon parameter\n \/\/ - for compatibility reason, \"icon_data\"\n if (!hints[\"image_data\"].isNull())\n {\n m_pixmap = getPixmapFromHint(hints[\"image_data\"]);\n\/\/ qDebug() << application << \"from image_data\" << m_pixmap.isNull();\n }\n else if (!hints[\"image_path\"].isNull())\n {\n m_pixmap = getPixmapFromString(hints[\"image_path\"].toString());\n\/\/ qDebug() << application << \"from image_path\" << m_pixmap.isNull();\n }\n else if (!icon.isEmpty())\n {\n m_pixmap = getPixmapFromString(icon);\n\/\/ qDebug() << application << \"from icon\" << icon << m_pixmap.isNull();\n }\n else if (!hints[\"icon_data\"].isNull())\n {\n m_pixmap = getPixmapFromHint(hints[\"icon_data\"]);\n\/\/ qDebug() << application << \"from icon_data\" << m_pixmap.isNull();\n }\n \/\/ issue #325: Do not display icon if it's not found...\n if (m_pixmap.isNull())\n {\n iconLabel->hide();\n }\n else\n {\n if (m_pixmap.size().width() > ICONSIZE.width()\n || m_pixmap.size().height() > ICONSIZE.height())\n {\n m_pixmap = m_pixmap.scaled(ICONSIZE, Qt::KeepAspectRatio, Qt::SmoothTransformation);\n }\n iconLabel->setPixmap(m_pixmap);\n iconLabel->show();\n }\n\n \/\/ application\n\tappLabel->setVisible(!application.isEmpty());\n appLabel->setText(application);\n\n \/\/ summary\n summaryLabel->setVisible(!summary.isEmpty());\n summaryLabel->setText(summary);\n\n if (application == summary)\n summaryLabel->setVisible(false);\n\n \/\/ body\n bodyLabel->setVisible(!body.isEmpty());\n bodyLabel->setText(body);\n\n \/\/ Timeout\n \/\/ Special values:\n \/\/ < 0: server decides timeout\n \/\/ 0: infifite\n if (m_timer)\n {\n m_timer->stop();\n m_timer->deleteLater();\n }\n\n \/\/ -1 for server decides is handled in notifyd to save QSettings instance\n if (timeout > 0)\n {\n m_timer = new NotificationTimer(this);\n connect(m_timer, SIGNAL(timeout()), this, SIGNAL(timeout()));\n m_timer->start(timeout);\n }\n\n \/\/ Categories *********************\n \/\/ TODO\/FIXME: Categories - how to handle it?\n if (!hints[\"category\"].isNull())\n {\n qDebug() << \"Notification\" << application << \"category\" << hints[\"category\"];\n }\n\n \/\/ Urgency Levels *********************\n \/\/ Type Description\n \/\/ 0 Low\n \/\/ 1 Normal\n \/\/ 2 Critical\n \/\/ TODO\/FIXME: Urgencies - how to handle it?\n if (!hints[\"urgency\"].isNull())\n {\n qDebug() << \"Notification\" << application << \"urgency\" << hints[\"urgency\"];\n }\n\n \/\/ Actions\n if (actions.count() && m_actionWidget == 0)\n {\n if (actions.count()\/2 < 4)\n m_actionWidget = new NotificationActionsButtonsWidget(actions, this);\n else\n m_actionWidget = new NotificationActionsComboWidget(actions, this);\n connect(m_actionWidget, SIGNAL(actionTriggered(const QString &)),\n this, SIGNAL(actionTriggered(const QString &)));\n actionsLayout->addWidget(m_actionWidget);\n m_actionWidget->show();\n }\n\n adjustSize();\n \/\/ ensure layout expansion\n setMinimumHeight(qMax(rect().height(), childrenRect().height()));\n}\n\nQString Notification::application() const\n{\n return appLabel->text();\n}\n\nQString Notification::summary() const\n{\n return summaryLabel->text();\n}\n\nQString Notification::body() const\n{\n return bodyLabel->text();\n}\n\nvoid Notification::closeButton_clicked()\n{\n if (m_timer)\n m_timer->stop();\n emit userCanceled();\n}\n\nvoid Notification::paintEvent(QPaintEvent *)\n{\n QStyleOption opt;\n opt.init(this);\n QPainter p(this);\n style()->drawPrimitive(QStyle::PE_Widget, &opt, &p, this);\n}\n\nQPixmap Notification::getPixmapFromHint(const QVariant &argument) const\n{\n int width, height, rowstride, bitsPerSample, channels;\n bool hasAlpha;\n QByteArray data;\n\n const QDBusArgument arg = argument.value<QDBusArgument>();\n arg.beginStructure();\n arg >> width;\n arg >> height;\n arg >> rowstride;\n arg >> hasAlpha;\n arg >> bitsPerSample;\n arg >> channels;\n arg >> data;\n arg.endStructure();\n QImage img = QImage((uchar*)data.constData(), width, height, QImage::Format_ARGB32).rgbSwapped();\n\n return QPixmap::fromImage(img);\n}\n\nQPixmap Notification::getPixmapFromString(const QString &str) const\n{\n QUrl url(str);\n if (url.isValid() && QFile::exists(url.toLocalFile()))\n {\n\/\/ qDebug() << \" getPixmapFromString by URL\" << url;\n return QPixmap(url.toLocalFile());\n }\n else\n {\n\/\/ qDebug() << \" getPixmapFromString by XdgIcon theme\" << str << ICONSIZE << XdgIcon::themeName();\n\/\/ qDebug() << \" \" << XdgIcon::fromTheme(str) << \"isnull:\" << XdgIcon::fromTheme(str).isNull();\n \/\/ They say: do not display an icon if it;s not found - see #325\n return XdgIcon::fromTheme(str\/*, XdgIcon::defaultApplicationIcon()*\/).pixmap(ICONSIZE);\n }\n}\n\nvoid Notification::enterEvent(QEvent * event)\n{\n if (m_timer)\n m_timer->pause();\n}\n\nvoid Notification::leaveEvent(QEvent * event)\n{\n if (m_timer)\n m_timer->resume();\n}\n\nvoid Notification::mouseReleaseEvent(QMouseEvent * event)\n{\n\/\/ qDebug() << \"CLICKED\" << event;\n QString appName;\n QString windowTitle;\n\n if (m_actionWidget && m_actionWidget->hasDefaultAction())\n {\n emit actionTriggered(m_actionWidget->defaultAction());\n return;\n }\n\n foreach (Window i, LxQt::xfitMan().getClientList())\n {\n appName = LxQt::xfitMan().getApplicationName(i);\n windowTitle = LxQt::xfitMan().getWindowTitle(i);\n \/\/qDebug() << \" \" << i << \"APPNAME\" << appName << \"TITLE\" << windowTitle;\n if (appName.isEmpty())\n {\n QWidget::mouseReleaseEvent(event);\n return;\n }\n if (appName == appLabel->text() || windowTitle == appLabel->text())\n {\n\/\/ qDebug() << \" FOUND!\";\n LxQt::xfitMan().raiseWindow(i);\n closeButton_clicked();\n return;\n }\n }\n}\n\nNotificationTimer::NotificationTimer(QObject *parent)\n : QTimer(parent),\n m_intervalMsec(-1)\n{\n}\n\nvoid NotificationTimer::start(int msec)\n{\n m_startTime = QDateTime::currentDateTime();\n m_intervalMsec = msec;\n QTimer::start(msec);\n}\n\nvoid NotificationTimer::pause()\n{\n if (!isActive())\n return;\n\n stop();\n#if QT_VERSION >= 0x040700\n m_intervalMsec = m_startTime.msecsTo(QDateTime());\n#else\n QDate currentDate = QDate::currentDate();\n QTime currentTime = QTime::currentTime();\n qint64 MSECS_PER_DAY = 86400000;\n m_intervalMsec = static_cast<qint64>(m_startTime.date().daysTo(currentDate)) * MSECS_PER_DAY\n + static_cast<qint64>(m_startTime.time().msecsTo(currentTime));\n#endif\n}\n\nvoid NotificationTimer::resume()\n{\n if (isActive())\n return;\n\n start(m_intervalMsec);\n}\n<commit_msg>Drop Qt4 support in code<commit_after>\/* BEGIN_COMMON_COPYRIGHT_HEADER\n * (c)LGPL2+\n *\n * LXDE-Qt - a lightweight, Qt based, desktop toolset\n * http:\/\/razor-qt.org\n *\n * Copyright: 2012 Razor team\n * Authors:\n * Petr Vanek <petr@scribus.info>\n *\n * This program or library is free software; you can redistribute it\n * and\/or modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n\n * You should have received a copy of the GNU Lesser General\n * Public License along with this library; if not, write to the\n * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,\n * Boston, MA 02110-1301 USA\n *\n * END_COMMON_COPYRIGHT_HEADER *\/\n\n#include <QPainter>\n#include <QUrl>\n#include <QFile>\n#include <QDateTime>\n#include <QtDBus\/QDBusArgument>\n\n#include <XdgIcon>\n\n#include \"notification.h\"\n#include \"notificationwidgets.h\"\n\n#include <QtDebug>\n\/\/ this *must* go last due Qt's moc\n#include <LXQt\/XfitMan>\n\n\n#define ICONSIZE QSize(32, 32)\n\n\nNotification::Notification(const QString &application,\n const QString &summary, const QString &body,\n const QString &icon, int timeout,\n const QStringList& actions, const QVariantMap& hints,\n QWidget *parent)\n : QWidget(parent),\n m_timer(0),\n m_actionWidget(0)\n{\n setupUi(this);\n setObjectName(\"Notification\");\n setMouseTracking(true);\n\n setMaximumWidth(parent->width());\n setMinimumWidth(parent->width());\n\n setValues(application, summary, body, icon, timeout, actions, hints);\n\n connect(closeButton, SIGNAL(clicked()), this, SLOT(closeButton_clicked()));\n}\n\nvoid Notification::setValues(const QString &application,\n const QString &summary, const QString &body,\n const QString &icon, int timeout,\n const QStringList& actions, const QVariantMap& hints)\n{\n \/\/ Basic properties *********************\n\n \/\/ Notifications spec set real order here:\n \/\/ An implementation which only displays one image or icon must\n \/\/ choose which one to display using the following order:\n \/\/ - \"image-data\"\n \/\/ - \"image-path\"\n \/\/ - app_icon parameter\n \/\/ - for compatibility reason, \"icon_data\"\n if (!hints[\"image_data\"].isNull())\n {\n m_pixmap = getPixmapFromHint(hints[\"image_data\"]);\n\/\/ qDebug() << application << \"from image_data\" << m_pixmap.isNull();\n }\n else if (!hints[\"image_path\"].isNull())\n {\n m_pixmap = getPixmapFromString(hints[\"image_path\"].toString());\n\/\/ qDebug() << application << \"from image_path\" << m_pixmap.isNull();\n }\n else if (!icon.isEmpty())\n {\n m_pixmap = getPixmapFromString(icon);\n\/\/ qDebug() << application << \"from icon\" << icon << m_pixmap.isNull();\n }\n else if (!hints[\"icon_data\"].isNull())\n {\n m_pixmap = getPixmapFromHint(hints[\"icon_data\"]);\n\/\/ qDebug() << application << \"from icon_data\" << m_pixmap.isNull();\n }\n \/\/ issue #325: Do not display icon if it's not found...\n if (m_pixmap.isNull())\n {\n iconLabel->hide();\n }\n else\n {\n if (m_pixmap.size().width() > ICONSIZE.width()\n || m_pixmap.size().height() > ICONSIZE.height())\n {\n m_pixmap = m_pixmap.scaled(ICONSIZE, Qt::KeepAspectRatio, Qt::SmoothTransformation);\n }\n iconLabel->setPixmap(m_pixmap);\n iconLabel->show();\n }\n\n \/\/ application\n\tappLabel->setVisible(!application.isEmpty());\n appLabel->setText(application);\n\n \/\/ summary\n summaryLabel->setVisible(!summary.isEmpty());\n summaryLabel->setText(summary);\n\n if (application == summary)\n summaryLabel->setVisible(false);\n\n \/\/ body\n bodyLabel->setVisible(!body.isEmpty());\n bodyLabel->setText(body);\n\n \/\/ Timeout\n \/\/ Special values:\n \/\/ < 0: server decides timeout\n \/\/ 0: infifite\n if (m_timer)\n {\n m_timer->stop();\n m_timer->deleteLater();\n }\n\n \/\/ -1 for server decides is handled in notifyd to save QSettings instance\n if (timeout > 0)\n {\n m_timer = new NotificationTimer(this);\n connect(m_timer, SIGNAL(timeout()), this, SIGNAL(timeout()));\n m_timer->start(timeout);\n }\n\n \/\/ Categories *********************\n \/\/ TODO\/FIXME: Categories - how to handle it?\n if (!hints[\"category\"].isNull())\n {\n qDebug() << \"Notification\" << application << \"category\" << hints[\"category\"];\n }\n\n \/\/ Urgency Levels *********************\n \/\/ Type Description\n \/\/ 0 Low\n \/\/ 1 Normal\n \/\/ 2 Critical\n \/\/ TODO\/FIXME: Urgencies - how to handle it?\n if (!hints[\"urgency\"].isNull())\n {\n qDebug() << \"Notification\" << application << \"urgency\" << hints[\"urgency\"];\n }\n\n \/\/ Actions\n if (actions.count() && m_actionWidget == 0)\n {\n if (actions.count()\/2 < 4)\n m_actionWidget = new NotificationActionsButtonsWidget(actions, this);\n else\n m_actionWidget = new NotificationActionsComboWidget(actions, this);\n connect(m_actionWidget, SIGNAL(actionTriggered(const QString &)),\n this, SIGNAL(actionTriggered(const QString &)));\n actionsLayout->addWidget(m_actionWidget);\n m_actionWidget->show();\n }\n\n adjustSize();\n \/\/ ensure layout expansion\n setMinimumHeight(qMax(rect().height(), childrenRect().height()));\n}\n\nQString Notification::application() const\n{\n return appLabel->text();\n}\n\nQString Notification::summary() const\n{\n return summaryLabel->text();\n}\n\nQString Notification::body() const\n{\n return bodyLabel->text();\n}\n\nvoid Notification::closeButton_clicked()\n{\n if (m_timer)\n m_timer->stop();\n emit userCanceled();\n}\n\nvoid Notification::paintEvent(QPaintEvent *)\n{\n QStyleOption opt;\n opt.init(this);\n QPainter p(this);\n style()->drawPrimitive(QStyle::PE_Widget, &opt, &p, this);\n}\n\nQPixmap Notification::getPixmapFromHint(const QVariant &argument) const\n{\n int width, height, rowstride, bitsPerSample, channels;\n bool hasAlpha;\n QByteArray data;\n\n const QDBusArgument arg = argument.value<QDBusArgument>();\n arg.beginStructure();\n arg >> width;\n arg >> height;\n arg >> rowstride;\n arg >> hasAlpha;\n arg >> bitsPerSample;\n arg >> channels;\n arg >> data;\n arg.endStructure();\n QImage img = QImage((uchar*)data.constData(), width, height, QImage::Format_ARGB32).rgbSwapped();\n\n return QPixmap::fromImage(img);\n}\n\nQPixmap Notification::getPixmapFromString(const QString &str) const\n{\n QUrl url(str);\n if (url.isValid() && QFile::exists(url.toLocalFile()))\n {\n\/\/ qDebug() << \" getPixmapFromString by URL\" << url;\n return QPixmap(url.toLocalFile());\n }\n else\n {\n\/\/ qDebug() << \" getPixmapFromString by XdgIcon theme\" << str << ICONSIZE << XdgIcon::themeName();\n\/\/ qDebug() << \" \" << XdgIcon::fromTheme(str) << \"isnull:\" << XdgIcon::fromTheme(str).isNull();\n \/\/ They say: do not display an icon if it;s not found - see #325\n return XdgIcon::fromTheme(str\/*, XdgIcon::defaultApplicationIcon()*\/).pixmap(ICONSIZE);\n }\n}\n\nvoid Notification::enterEvent(QEvent * event)\n{\n if (m_timer)\n m_timer->pause();\n}\n\nvoid Notification::leaveEvent(QEvent * event)\n{\n if (m_timer)\n m_timer->resume();\n}\n\nvoid Notification::mouseReleaseEvent(QMouseEvent * event)\n{\n\/\/ qDebug() << \"CLICKED\" << event;\n QString appName;\n QString windowTitle;\n\n if (m_actionWidget && m_actionWidget->hasDefaultAction())\n {\n emit actionTriggered(m_actionWidget->defaultAction());\n return;\n }\n\n foreach (Window i, LxQt::xfitMan().getClientList())\n {\n appName = LxQt::xfitMan().getApplicationName(i);\n windowTitle = LxQt::xfitMan().getWindowTitle(i);\n \/\/qDebug() << \" \" << i << \"APPNAME\" << appName << \"TITLE\" << windowTitle;\n if (appName.isEmpty())\n {\n QWidget::mouseReleaseEvent(event);\n return;\n }\n if (appName == appLabel->text() || windowTitle == appLabel->text())\n {\n\/\/ qDebug() << \" FOUND!\";\n LxQt::xfitMan().raiseWindow(i);\n closeButton_clicked();\n return;\n }\n }\n}\n\nNotificationTimer::NotificationTimer(QObject *parent)\n : QTimer(parent),\n m_intervalMsec(-1)\n{\n}\n\nvoid NotificationTimer::start(int msec)\n{\n m_startTime = QDateTime::currentDateTime();\n m_intervalMsec = msec;\n QTimer::start(msec);\n}\n\nvoid NotificationTimer::pause()\n{\n if (!isActive())\n return;\n\n stop();\n m_intervalMsec = m_startTime.msecsTo(QDateTime());\n}\n\nvoid NotificationTimer::resume()\n{\n if (isActive())\n return;\n\n start(m_intervalMsec);\n}\n<|endoftext|>"} {"text":"<commit_before>\/**\n ** \\file object\/object.cc\n ** \\brief Implementation of object::Object.\n *\/\n\n#include <algorithm>\n\n#include <boost\/bind.hpp>\n#include <boost\/lexical_cast.hpp>\n#include <boost\/lambda\/lambda.hpp>\n\n#include <libport\/containers.hh>\n#include <libport\/foreach.hh>\n\n#include \"object\/object.hh\"\n#include \"object\/atom.hh\"\n#include \"object\/global-class.hh\"\n#include \"object\/hash-slots.hh\"\n#include \"object\/urbi-exception.hh\"\n\n#include \"runner\/runner.hh\"\n\nnamespace object\n{\n\n \/*---------.\n | Callers. |\n `---------*\/\n\n rObject urbi_call(runner::Runner& r,\n\t\t rObject self,\n\t\t libport::Symbol msg,\n\t\t objects_type args)\n {\n assertion(self);\n rObject message = self->slot_get(msg);\n if (!message)\n throw LookupError(msg);\n args.insert(args.begin(), self);\n rObject res = r.apply(message, msg, args);\n assertion(res);\n return res;\n }\n\n rObject urbi_call(runner::Runner& r,\n\t\t rObject self,\n\t\t libport::Symbol msg)\n {\n objects_type args; \/\/ Call with no args.\n return urbi_call(r, self, msg, args);\n }\n\n \/*-------.\n | kind. |\n `-------*\/\n\n const char*\n Object::string_of (Object::kind_type k)\n {\n switch (k)\n {\n#define CASE(What, Name) case kind_ ## What: return #Name; break;\n APPLY_ON_ALL_PRIMITIVES(CASE);\n#undef CASE\n }\n pabort(\"unreachable\");\n }\n\n \/*---------.\n | Scopes. |\n `---------*\/\n\n \/\/ Typedef for lookups that return rObject\n typedef boost::optional<rObject> lookup_result;\n typedef boost::function1<lookup_result, rObject> lookup_action;\n\n namespace\n {\n using std::make_pair;\n using boost::bind;\n using boost::optional;\n\n static lookup_result\n targetLookup(rObject obj,\n\t\t const object::Slots::key_type& slotName)\n {\n \/\/ First, check if the object has the slot locally. We do not\n \/\/ handle 'self' here, since we first want to see whether it has\n \/\/ been captured in the context.\n if (slotName != SYMBOL(self) && obj->own_slot_get(slotName, 0))\n\t\/\/ Return a nonempty optional containing an empty rObject, to\n\t\/\/ indicate to target that the lookup is successful, and the\n\t\/\/ target is the initial object.\n\treturn optional<rObject>(rObject());\n \/\/ If this is a method outer scope, perform special lookup in\n \/\/ self and context.\n if (rObject self = obj->own_slot_get(SYMBOL(self), 0))\n {\n\t\/\/ FIXME: The 'code' slot is *always* set by the scoping\n\t\/\/ system, yet the user can still delete it. What kind of\n\t\/\/ error should we raise when this problem occurs? For now,\n\t\/\/ just ignore it:\n\tif (rObject code = obj->own_slot_get(SYMBOL(code), 0))\n\t \/\/ Likewise.\n\t if (rObject captured = code->own_slot_get(SYMBOL(capturedVars), 0))\n\t {\n\t if (captured == nil_class)\n\t return target(code->own_slot_get(SYMBOL(context)), slotName);\n\t else\n\t foreach (const rObject& var, captured->value<object::List>())\n\t\tif (var->value<object::String>() == slotName)\n\t\t return target(code->own_slot_get(SYMBOL(context)), slotName);\n\t }\n\t\/\/ If we were looking for 'self' and it wasn't captured in the\n\t\/\/ context, we found it here.\n\tif (slotName == SYMBOL(self))\n\t return optional<rObject>(rObject());\n\t\/\/ Check whether self has the slot. We do not use the\n\t\/\/ 'fallback' method here: only calls with explicit target are\n\t\/\/ subject to fallback.\n\tif (self->slot_locate(slotName, false))\n\t return self;\n }\n return optional<rObject>();\n }\n }\n\n rObject\n target(rObject where, const libport::Symbol& name)\n {\n boost::function1<boost::optional<rObject>, rObject> lookup =\n boost::bind(targetLookup, _1, name);\n boost::optional<rObject> res = where->lookup(lookup);\n if (!res)\n throw object::LookupError(name);\n if (!res.get())\n return where;\n return res.get();\n }\n\n rObject\n Object::make_scope(const rObject& parent)\n {\n rObject res = object::Object::fresh();\n res->locals_set(true);\n res->proto_add(parent);\n return res;\n }\n\n namespace\n {\n \/\/ helper for make_method_scope and make_do_scope\n static rObject\n make_outer_scope(const rObject& parent, const rObject& self)\n {\n rObject res = Object::make_scope(parent);\n res->slot_copy(SYMBOL(getSlot), scope_class);\n res->slot_copy(SYMBOL(locateSlot), scope_class);\n res->slot_copy(SYMBOL(removeSlot), scope_class);\n res->slot_copy(SYMBOL(updateSlot), scope_class);\n res->slot_set(SYMBOL(self), self);\n \/\/ We really need to copy 'locals' in every scope, or else\n \/\/ Scope's methods will get completely fubared: 'locals' will be\n \/\/ found in 'self' and will thus not be the local scope!\n res->slot_copy(SYMBOL(locals), scope_class);\n return res;\n }\n }\n\n rObject\n Object::make_method_scope(const rObject& self)\n {\n rObject res = make_outer_scope(global_class, self);\n res->slot_copy(SYMBOL(setSlot), scope_class);\n return res;\n }\n\n rObject\n Object::make_do_scope(const rObject& parent, const rObject& self)\n {\n rObject res = make_outer_scope (parent ? parent : global_class, self);\n res->slot_set(SYMBOL(setSlot), scope_class->slot_get(SYMBOL(doSetSlot)));\n return res;\n }\n\n \/*--------.\n | Slots. |\n `--------*\/\n\n rObject\n Object::urbi_protos_get ()\n {\n if (!protos_cache_)\n {\n rList protos = List::fresh (*protos_);\n protos_cache_ = protos;\n delete protos_;\n protos_ = &protos->value_get ();\n }\n return protos_cache_;\n }\n\n void\n Object::protos_set (rObject l)\n {\n if (!protos_cache_)\n delete protos_;\n protos_cache_ = l;\n protos_ = &l.unsafe_cast<object::List>()->value_get ();\n }\n\n template <typename R>\n boost::optional<R>\n Object::lookup(boost::function1<boost::optional<R>, rObject> action,\n\t\t objects_set_type& marks) const\n {\n if (!libport::mhas(marks, this))\n {\n marks.insert(this);\n assertion(self());\n boost::optional<R> res = action(self());\n if (res)\n\treturn res;\n else\n\tforeach (const rObject& proto, protos_get())\n\t if (boost::optional<R> res = proto->lookup(action, marks))\n\t return res;\n }\n return boost::optional<R>();\n }\n\n template <typename R>\n boost::optional<R>\n Object::lookup(boost::function1<boost::optional<R>, rObject> action) const\n {\n objects_set_type marks;\n return lookup(action, marks);\n }\n\n namespace\n {\n class SlotLookup\n {\n public:\n lookup_result\n slot_lookup(rObject obj, const Slots::key_type& k, bool value)\n {\n\tassertion(obj);\n\tif (rObject x = obj->own_slot_get(k, 0))\n\t return value ? x : obj;\n\tif (!fallback)\n if (rObject f = obj->own_slot_get(SYMBOL(fallback), 0))\n fallback = value ? f : obj;\n\treturn boost::optional<rObject>();\n }\n rObject fallback;\n };\n }\n\n rObject Object::slot_locate(const Slots::key_type& k,\n bool fallback, bool value) const\n {\n SlotLookup looker;\n lookup_action action = boost::bind(&SlotLookup::slot_lookup, &looker, _1, k, value);\n boost::optional<rObject> res = lookup(action);\n if (!res && fallback && looker.fallback)\n res = looker.fallback;\n return res ? res.get() : 0;\n }\n\n rObject\n Object::safe_slot_locate(const Slots::key_type& k, bool value) const\n {\n rObject r = slot_locate(k, true, value);\n if (!r)\n throw LookupError(k);\n return iassertion(r);\n }\n\n rObject\n Object::slot_get (const Slots::key_type& k, boost::optional<rObject> def) const\n {\n rObject value;\n if (def)\n value = slot_locate(k, true, true);\n else\n value = safe_slot_locate(k, true);\n if (value)\n return value;\n else\n return def.get();\n }\n\n\n Object&\n Object::slot_set (const Slots::key_type& k, rObject o)\n {\n if (!slots_.set(k, o))\n throw RedefinitionError(k);\n return *this;\n }\n\n Object&\n Object::slot_copy (const Slots::key_type& name, rObject from)\n {\n this->slot_set(name, from->slot_get(name));\n return *this;\n }\n\n void\n Object::slot_update (runner::Runner& r,\n\t\t const Slots::key_type& k,\n\t\t rObject o,\n\t\t bool hook)\n {\n \/\/ The target of updateSlot\n rObject context = self();\n \/\/ The owner of the updated slot\n rObject owner = context->safe_slot_locate(k);\n\n \/\/ We have to determine where the new value must be stored,\n \/\/ depending on whether the slot owner and the context are scopes.\n rObject effective_target;\n\n \/\/ If both are scopes, update the original scope.\n if (context->locals_ && owner->locals_get())\n effective_target = owner;\n else if (context->locals_ && !owner->locals_get())\n {\n \/\/ Local->class: copyonwrite to \"self\" after evaluating it.\n rObject self = urbi_call(r, context, SYMBOL(self));\n assertion(self);\n effective_target = self;\n }\n else \/\/ Class->class: copy on write.\n effective_target = context;\n \/\/ Check hook, only if we are not create-on-writing.\n \/* If the current value in the slot to be written in has a slot named\n * 'updateHook', call it, passing the object owning the slot, the slot name\n * and the target.\n *\/\n if (hook && effective_target == owner)\n \/\/ FIXME: We probably want helper to access properties\n if (rObject properties = effective_target->slot_get(SYMBOL(properties), rObject()))\n if (rObject slotProperties = properties->slot_get(k, rObject()))\n if (rObject hook = slotProperties->slot_get(SYMBOL(updateHook), rObject()))\n {\n objects_type args;\n args.push_back(effective_target);\n args.push_back(String::fresh(k));\n args.push_back(o);\n rObject ret = r.apply(hook, SYMBOL(updateHook), args);\n \/\/ If the updateHook returned void, do nothing. Otherwise let\n \/\/ the slot be overwritten.\n if (ret == object::void_class)\n\treturn;\n }\n \/\/ If return-value of hook is not void, write it to slot.\n effective_target->own_slot_update(k, o);\n };\n\n void\n Object::own_slot_update (const Slots::key_type& k, rObject v)\n {\n slots_.update(k, v);\n }\n\n rObject\n Object::own_slot_get (const Slots::key_type& k, rObject def)\n {\n rObject res = slots_.get(k);\n return res ? res : def;\n }\n\n void\n Object::all_slots_copy(const rObject& other)\n {\n foreach (Slots::slot_type slot, other->slots_get())\n if (!own_slot_get(slot.first, 0))\n slot_set(slot.first, slot.second);\n }\n\n \/*-----------.\n | Printing. |\n `-----------*\/\n\n std::ostream&\n Object::special_slots_dump (std::ostream& o, runner::Runner&) const\n {\n return o;\n }\n\n bool\n Object::operator< (const Object& rhs) const\n {\n return this < &rhs;\n }\n\n std::ostream&\n Object::id_dump(std::ostream& o, runner::Runner& r) const\n {\n rObject data = urbi_call(r, self(), SYMBOL(id));\n std::string s = data->value<String>().name_get();\n return o << s;\n }\n\n\n std::ostream&\n Object::protos_dump(std::ostream& o, runner::Runner& runner) const\n {\n if (!protos_->empty())\n {\n o << \"protos = \";\n bool tail = false;\n foreach (rObject p, *protos_)\n {\n\tif (tail++)\n\t o << \", \";\n\tp->id_dump (o, runner);\n }\n o << libport::iendl;\n }\n return o;\n }\n\n std::ostream&\n Object::dump (std::ostream& o, runner::Runner& runner) const\n {\n id_dump(o, runner);\n \/\/\/ Use xalloc\/iword to store our current depth within the stream object.\n static const long idx = o.xalloc();\n long& current_depth = o.iword(idx);\n\n \/\/ Stop recursion at depth_max.\n enum { depth_max = 3 };\n if (current_depth > depth_max)\n return o << \" <...>\";\n ++current_depth;\n o << \" {\" << libport::incendl;\n protos_dump(o, runner);\n special_slots_dump (o, runner);\n foreach(Slots::slot_type s, slots_.container())\n {\n o << s.first << \" = \";\n s.second->dump(o, runner) << libport::iendl;\n }\n\n o << libport::decindent << '}';\n \/\/We can not reuse current_depth variable above according to spec.\n o.iword(idx)--;\n return o;\n }\n\n std::ostream&\n Object::print(std::ostream& o, runner::Runner& runner) const\n {\n try\n {\n rObject s = urbi_call(runner, self(), SYMBOL(asString));\n o << s->value<String>().name_get();\n return o;\n }\n \/\/ Check if asString was found, especially for bootstrap: asString\n \/\/ is implemented in urbi\/urbi.u, but print is called to show\n \/\/ result in the toplevel before its definition.\n catch (LookupError&)\n {\n \/\/ If no asString method is supplied, print the unique id\n return o << std::hex << this;\n }\n }\n\n bool\n is_a(const rObject& c, const rObject& p)\n {\n return for_all_protos(c, boost::lambda::_1 == p);\n }\n\n bool\n is_true(const rObject& o)\n {\n \/\/ FIXME: should nil be true? It should probably be false.\n if (o == nil_class)\n return true;\n if (o->type_is<object::Float>())\n return o.unsafe_cast<object::Float>()->value_get();\n return false;\n }\n\n} \/\/ namespace object\n<commit_msg>Fix mindo.<commit_after>\/**\n ** \\file object\/object.cc\n ** \\brief Implementation of object::Object.\n *\/\n\n#include <algorithm>\n\n#include <boost\/bind.hpp>\n#include <boost\/lexical_cast.hpp>\n#include <boost\/lambda\/lambda.hpp>\n\n#include <libport\/containers.hh>\n#include <libport\/foreach.hh>\n\n#include \"object\/object.hh\"\n#include \"object\/atom.hh\"\n#include \"object\/global-class.hh\"\n#include \"object\/hash-slots.hh\"\n#include \"object\/urbi-exception.hh\"\n\n#include \"runner\/runner.hh\"\n\nnamespace object\n{\n\n \/*---------.\n | Callers. |\n `---------*\/\n\n rObject urbi_call(runner::Runner& r,\n\t\t rObject self,\n\t\t libport::Symbol msg,\n\t\t objects_type args)\n {\n assertion(self);\n rObject message = self->slot_get(msg);\n if (!message)\n throw LookupError(msg);\n args.insert(args.begin(), self);\n rObject res = r.apply(message, msg, args);\n assertion(res);\n return res;\n }\n\n rObject urbi_call(runner::Runner& r,\n\t\t rObject self,\n\t\t libport::Symbol msg)\n {\n objects_type args; \/\/ Call with no args.\n return urbi_call(r, self, msg, args);\n }\n\n \/*-------.\n | kind. |\n `-------*\/\n\n const char*\n Object::string_of (Object::kind_type k)\n {\n switch (k)\n {\n#define CASE(What, Name) case kind_ ## What: return #Name; break;\n APPLY_ON_ALL_PRIMITIVES(CASE);\n#undef CASE\n }\n pabort(\"unreachable\");\n }\n\n \/*---------.\n | Scopes. |\n `---------*\/\n\n \/\/ Typedef for lookups that return rObject\n typedef boost::optional<rObject> lookup_result;\n typedef boost::function1<lookup_result, rObject> lookup_action;\n\n namespace\n {\n using std::make_pair;\n using boost::bind;\n using boost::optional;\n\n static lookup_result\n targetLookup(rObject obj,\n\t\t const object::Slots::key_type& slotName)\n {\n \/\/ First, check if the object has the slot locally. We do not\n \/\/ handle 'self' here, since we first want to see whether it has\n \/\/ been captured in the context.\n if (slotName != SYMBOL(self) && obj->own_slot_get(slotName, 0))\n\t\/\/ Return a nonempty optional containing an empty rObject, to\n\t\/\/ indicate to target that the lookup is successful, and the\n\t\/\/ target is the initial object.\n\treturn optional<rObject>(rObject());\n \/\/ If this is a method outer scope, perform special lookup in\n \/\/ self and context.\n if (rObject self = obj->own_slot_get(SYMBOL(self), 0))\n {\n\t\/\/ FIXME: The 'code' slot is *always* set by the scoping\n\t\/\/ system, yet the user can still delete it. What kind of\n\t\/\/ error should we raise when this problem occurs? For now,\n\t\/\/ just ignore it:\n\tif (rObject code = obj->own_slot_get(SYMBOL(code), 0))\n\t \/\/ Likewise.\n\t if (rObject captured = code->own_slot_get(SYMBOL(capturedVars), 0))\n\t {\n\t if (captured == nil_class)\n\t return target(code->own_slot_get(SYMBOL(context)), slotName);\n\t else\n\t foreach (const rObject& var, captured->value<object::List>())\n\t\tif (var->value<object::String>() == slotName)\n\t\t return target(code->own_slot_get(SYMBOL(context)), slotName);\n\t }\n\t\/\/ If we were looking for 'self' and it wasn't captured in the\n\t\/\/ context, we found it here.\n\tif (slotName == SYMBOL(self))\n\t return optional<rObject>(rObject());\n\t\/\/ Check whether self has the slot. We do not use the\n\t\/\/ 'fallback' method here: only calls with explicit target are\n\t\/\/ subject to fallback.\n\tif (self->slot_locate(slotName, false))\n\t return self;\n }\n return optional<rObject>();\n }\n }\n\n rObject\n target(rObject where, const libport::Symbol& name)\n {\n boost::function1<boost::optional<rObject>, rObject> lookup =\n boost::bind(targetLookup, _1, name);\n boost::optional<rObject> res = where->lookup(lookup);\n if (!res)\n throw object::LookupError(name);\n if (!res.get())\n return where;\n return res.get();\n }\n\n rObject\n Object::make_scope(const rObject& parent)\n {\n rObject res = object::Object::fresh();\n res->locals_set(true);\n res->proto_add(parent);\n return res;\n }\n\n namespace\n {\n \/\/ helper for make_method_scope and make_do_scope\n static rObject\n make_outer_scope(const rObject& parent, const rObject& self)\n {\n rObject res = Object::make_scope(parent);\n res->slot_copy(SYMBOL(getSlot), scope_class);\n res->slot_copy(SYMBOL(locateSlot), scope_class);\n res->slot_copy(SYMBOL(removeSlot), scope_class);\n res->slot_copy(SYMBOL(updateSlot), scope_class);\n res->slot_set(SYMBOL(self), self);\n \/\/ We really need to copy 'locals' in every scope, or else\n \/\/ Scope's methods will get completely fubared: 'locals' will be\n \/\/ found in 'self' and will thus not be the local scope!\n res->slot_copy(SYMBOL(locals), scope_class);\n return res;\n }\n }\n\n rObject\n Object::make_method_scope(const rObject& self)\n {\n rObject res = make_outer_scope(global_class, self);\n res->slot_copy(SYMBOL(setSlot), scope_class);\n return res;\n }\n\n rObject\n Object::make_do_scope(const rObject& parent, const rObject& self)\n {\n rObject res = make_outer_scope (parent ? parent : global_class, self);\n res->slot_set(SYMBOL(setSlot), scope_class->slot_get(SYMBOL(doSetSlot)));\n return res;\n }\n\n \/*--------.\n | Slots. |\n `--------*\/\n\n rObject\n Object::urbi_protos_get ()\n {\n if (!protos_cache_)\n {\n rList protos = List::fresh (*protos_);\n protos_cache_ = protos;\n delete protos_;\n protos_ = &protos->value_get ();\n }\n return protos_cache_;\n }\n\n void\n Object::protos_set (rObject l)\n {\n if (!protos_cache_)\n delete protos_;\n protos_cache_ = l;\n protos_ = &l.unsafe_cast<object::List>()->value_get ();\n }\n\n template <typename R>\n boost::optional<R>\n Object::lookup(boost::function1<boost::optional<R>, rObject> action,\n\t\t objects_set_type& marks) const\n {\n if (!libport::mhas(marks, this))\n {\n marks.insert(this);\n assertion(self());\n boost::optional<R> res = action(self());\n if (res)\n\treturn res;\n else\n\tforeach (const rObject& proto, protos_get())\n\t if (boost::optional<R> res = proto->lookup(action, marks))\n\t return res;\n }\n return boost::optional<R>();\n }\n\n template <typename R>\n boost::optional<R>\n Object::lookup(boost::function1<boost::optional<R>, rObject> action) const\n {\n objects_set_type marks;\n return lookup(action, marks);\n }\n\n namespace\n {\n class SlotLookup\n {\n public:\n lookup_result\n slot_lookup(rObject obj, const Slots::key_type& k, bool value)\n {\n\tassertion(obj);\n\tif (rObject x = obj->own_slot_get(k, 0))\n\t return value ? x : obj;\n\tif (!fallback)\n if (rObject f = obj->own_slot_get(SYMBOL(fallback), 0))\n fallback = value ? f : obj;\n\treturn boost::optional<rObject>();\n }\n rObject fallback;\n };\n }\n\n rObject Object::slot_locate(const Slots::key_type& k,\n bool fallback, bool value) const\n {\n SlotLookup looker;\n lookup_action action = boost::bind(&SlotLookup::slot_lookup, &looker, _1, k, value);\n boost::optional<rObject> res = lookup(action);\n if (!res && fallback && looker.fallback)\n res = looker.fallback;\n return res ? res.get() : 0;\n }\n\n rObject\n Object::safe_slot_locate(const Slots::key_type& k, bool value) const\n {\n rObject r = slot_locate(k, true, value);\n if (!r)\n throw LookupError(k);\n return iassertion(r);\n }\n\n rObject\n Object::slot_get (const Slots::key_type& k, boost::optional<rObject> def) const\n {\n rObject value;\n if (def)\n value = slot_locate(k, true, true);\n else\n value = safe_slot_locate(k, true);\n if (value)\n return value;\n else\n return def.get();\n }\n\n\n Object&\n Object::slot_set (const Slots::key_type& k, rObject o)\n {\n if (!slots_.set(k, o))\n throw RedefinitionError(k);\n return *this;\n }\n\n Object&\n Object::slot_copy (const Slots::key_type& name, rObject from)\n {\n this->slot_set(name, from->slot_get(name));\n return *this;\n }\n\n void\n Object::slot_update (runner::Runner& r,\n\t\t const Slots::key_type& k,\n\t\t rObject o,\n\t\t bool hook)\n {\n \/\/ The target of updateSlot\n rObject context = self();\n \/\/ The owner of the updated slot\n rObject owner = context->safe_slot_locate(k);\n\n \/\/ We have to determine where the new value must be stored,\n \/\/ depending on whether the slot owner and the context are scopes.\n rObject effective_target;\n\n \/\/ If both are scopes, update the original scope.\n if (context->locals_ && owner->locals_get())\n effective_target = owner;\n else if (context->locals_ && !owner->locals_get())\n {\n \/\/ Local->class: copyonwrite to \"self\" after evaluating it.\n rObject self = urbi_call(r, context, SYMBOL(self));\n assertion(self);\n effective_target = self;\n }\n else \/\/ Class->class: copy on write.\n effective_target = context;\n \/\/ Check hook, only if we are not create-on-writing.\n \/* If the current value in the slot to be written in has a slot named\n * 'updateHook', call it, passing the object owning the slot, the slot name\n * and the target.\n *\/\n if (hook && effective_target == owner)\n \/\/ FIXME: We probably want helper to access properties\n if (rObject properties = effective_target->slot_get(SYMBOL(properties), rObject()))\n if (rObject slotProperties = properties->slot_get(k, rObject()))\n if (rObject hook = slotProperties->slot_get(SYMBOL(updateHook), rObject()))\n {\n objects_type args;\n args.push_back(effective_target);\n args.push_back(String::fresh(k));\n args.push_back(o);\n rObject ret = r.apply(hook, SYMBOL(updateHook), args);\n \/\/ If the updateHook returned void, do nothing. Otherwise let\n \/\/ the slot be overwritten.\n if (ret == object::void_class)\n\treturn;\n }\n \/\/ If return-value of hook is not void, write it to slot.\n effective_target->own_slot_update(k, o);\n };\n\n void\n Object::own_slot_update (const Slots::key_type& k, rObject v)\n {\n slots_.update(k, v);\n }\n\n rObject\n Object::own_slot_get (const Slots::key_type& k, rObject def)\n {\n rObject res = slots_.get(k);\n return res ? res : def;\n }\n\n void\n Object::all_slots_copy(const rObject& other)\n {\n foreach (Slots::slot_type slot, other->slots_get())\n if (!own_slot_get(slot.first, 0))\n slot_set(slot.first, slot.second);\n }\n\n \/*-----------.\n | Printing. |\n `-----------*\/\n\n std::ostream&\n Object::special_slots_dump (std::ostream& o, runner::Runner&) const\n {\n return o;\n }\n\n bool\n Object::operator< (const Object& rhs) const\n {\n return this < &rhs;\n }\n\n std::ostream&\n Object::id_dump(std::ostream& o, runner::Runner& r) const\n {\n rObject data = urbi_call(r, self(), SYMBOL(id));\n std::string s = data->value<String>().name_get();\n return o << s;\n }\n\n\n std::ostream&\n Object::protos_dump(std::ostream& o, runner::Runner& runner) const\n {\n if (!protos_->empty())\n {\n o << \"protos = \";\n bool tail = false;\n foreach (rObject p, *protos_)\n {\n\tif (tail++)\n\t o << \", \";\n\tp->id_dump (o, runner);\n }\n o << libport::iendl;\n }\n return o;\n }\n\n std::ostream&\n Object::dump (std::ostream& o, runner::Runner& runner) const\n {\n id_dump(o, runner);\n \/\/\/ Use xalloc\/iword to store our current depth within the stream object.\n static const long idx = o.xalloc();\n long& current_depth = o.iword(idx);\n\n \/\/ Stop recursion at depth_max.\n enum { depth_max = 3 };\n if (current_depth > depth_max)\n return o << \" <...>\";\n ++current_depth;\n o << \" {\" << libport::incendl;\n protos_dump(o, runner);\n special_slots_dump (o, runner);\n foreach(Slots::slot_type s, slots_.container())\n {\n o << s.first << \" = \";\n s.second->dump(o, runner) << libport::iendl;\n }\n\n o << libport::decindent << '}';\n \/\/We can not reuse current_depth variable above according to spec.\n o.iword(idx)--;\n return o;\n }\n\n std::ostream&\n Object::print(std::ostream& o, runner::Runner& runner) const\n {\n try\n {\n rObject s = urbi_call(runner, self(), SYMBOL(asString));\n o << s->value<String>().name_get();\n return o;\n }\n \/\/ Check if asString was found, especially for bootstrap: asString\n \/\/ is implemented in urbi\/urbi.u, but print is called to show\n \/\/ result in the toplevel before its definition.\n catch (LookupError&)\n {\n \/\/ If no asString method is supplied, print the unique id\n return o << std::hex << this;\n }\n }\n\n bool\n is_a(const rObject& c, const rObject& p)\n {\n return for_all_protos(c, boost::lambda::_1 == p);\n }\n\n bool\n is_true(const rObject& o)\n {\n \/\/ FIXME: should nil be true? It should probably be false.\n if (o == nil_class)\n return true;\n if (o->type_is<object::Float>())\n return o.unsafe_cast<object::Float>()->value_get();\n return true;\n }\n\n} \/\/ namespace object\n<|endoftext|>"} {"text":"<commit_before>\/**\n ** \\file object\/system-class.cc\n ** \\brief Creation of the URBI object system.\n *\/\n\n#include <ltdl.h>\n\n\/\/#define ENABLE_DEBUG_TRACES\n#include <libport\/compiler.hh>\n#include <libport\/cstdlib>\n#include <libport\/format.hh>\n#include <libport\/program-name.hh>\n\n#include <memory>\n#include <sstream>\n\n#include <kernel\/uconnection.hh>\n#include <kernel\/uobject.hh>\n#include <kernel\/userver.hh>\n\n#include <object\/code.hh>\n#include <object\/cxx-primitive.hh>\n#include <object\/dictionary.hh>\n#include <object\/float.hh>\n#include <object\/global.hh>\n#include <object\/list.hh>\n#include <object\/lobby.hh>\n#include <object\/path.hh>\n#include <object\/symbols.hh>\n#include <object\/system.hh>\n#include <object\/tag.hh>\n#include <object\/task.hh>\n#include <parser\/transform.hh>\n#include <runner\/at-handler.hh>\n#include <runner\/interpreter.hh>\n#include <runner\/raise.hh>\n#include <runner\/runner.hh>\n\n#include <ast\/nary.hh>\n#include <ast\/routine.hh>\n\nnamespace object\n{\n using kernel::urbiserver;\n\n\n static inline\n runner::Runner&\n runner()\n {\n return ::kernel::urbiserver->getCurrentRunner();\n }\n\n static inline\n runner::Interpreter&\n interpreter()\n {\n return dynamic_cast<runner::Interpreter&>(runner());\n }\n\n \/\/ Extract a filename from a String or a Path object\n static std::string\n filename_get(const rObject& o)\n {\n if (o.is_a<Path>())\n return o->as<Path>()->as_string();\n type_check<String>(o);\n return o->as<String>()->value_get();\n }\n\n\n rObject\n execute_parsed(parser::parse_result_type p,\n libport::Symbol fun, std::string e)\n {\n runner::Interpreter& run = interpreter();\n\n \/\/ Report potential errors\n {\n ast::rNary errs = new ast::Nary();\n p->process_errors(*errs);\n run(errs.get());\n }\n\n ast::rConstAst ast = parser::transform(p->ast_get());\n if (!ast)\n RAISE(e);\n\n runner::Interpreter* sub = new runner::Interpreter(run, ast, fun);\n \/\/ So that it will resist to the call to yield_until_terminated,\n \/\/ and will be reclaimed at the end of the scope.\n sched::rJob job = sub;\n libport::Finally finally;\n runner().register_child(sub, finally);\n sub->start_job();\n try\n {\n run.yield_until_terminated(*job);\n }\n catch (const sched::ChildException& ce)\n {\n \/\/ Kill the sub-job and propagate.\n ce.rethrow_child_exception();\n }\n return sub->result_get();\n }\n\n\n rObject system_class;\n\n \/*--------------------.\n | System primitives. |\n `--------------------*\/\n\n\n#define SERVER_FUNCTION(Function) \\\n static void \\\n system_ ## Function() \\\n { \\\n urbiserver->Function(); \\\n }\n\n SERVER_FUNCTION(reboot)\n SERVER_FUNCTION(shutdown)\n\n#undef SERVER_FUNCTION\n\n\n static void\n system_sleep(const rObject&, libport::ufloat seconds)\n {\n runner::Runner& r = runner();\n if (seconds == std::numeric_limits<ufloat>::infinity())\n r.yield_until_terminated(r);\n else\n r.yield_until(r.scheduler_get().get_time()\n + static_cast<libport::utime_t>(seconds * 1000000.0));\n }\n\n static float\n system_time()\n {\n return runner().scheduler_get().get_time() \/ 1000000.0;\n }\n\n static float\n system_shiftedTime()\n {\n runner::Runner& r = runner();\n return (r.scheduler_get().get_time() - r.time_shift_get()) \/ 1000000.0;\n }\n\n static void\n system_assert_(const rObject&,\n const rObject& value, const std::string& assertion)\n {\n if (!is_true(value))\n RAISE(\"failed assertion: \" + assertion);\n }\n\n static rObject\n system_eval(const rObject&, const std::string& code)\n {\n return execute_parsed(parser::parse(code, ast::loc()),\n SYMBOL(eval),\n \"error executing command: \" + code);\n }\n\n static void\n system_registerAtJob(const rObject&,\n const rObject& condition,\n const rObject& clause,\n const rObject& on_leave)\n {\n runner::register_at_job(interpreter(),\n\t\t\t condition, clause, on_leave);\n }\n\n static rObject\n system_scopeTag()\n {\n return new Tag(interpreter().scope_tag());\n }\n\n static rObject\n system_searchFile(const rObject&, const rObject& f)\n {\n const std::string& filename = filename_get(f);\n try\n {\n return new Path(urbiserver->find_file(filename));\n }\n catch (libport::file_library::Not_found&)\n {\n runner::raise_urbi(SYMBOL(FileNotFound), to_urbi(filename));\n \/\/ Never reached\n assertion(false);\n return 0;\n }\n }\n\n static List::value_type\n system_searchPath()\n {\n List::value_type res;\n foreach (const libport::path& p, urbiserver->search_path.search_path_get())\n res.push_back(new Path(p));\n return res;\n }\n\n static rObject\n system_loadFile(const rObject&, const rObject& f)\n {\n const std::string& filename = filename_get(f);\n if (!libport::path(filename).exists())\n runner::raise_urbi(SYMBOL(FileNotFound), to_urbi(filename));\n return\n execute_parsed(parser::parse_file(filename),\n SYMBOL(loadFile),\n\t\t \"error loading file: \" + filename);\n }\n\n static rObject\n system_currentRunner()\n {\n return runner().as_task();\n }\n\n static float\n system_cycle()\n {\n return runner().scheduler_get().cycle_get();\n }\n\n static libport::Symbol\n system_fresh()\n {\n return libport::Symbol::fresh();\n }\n\n static rObject\n system_lobby()\n {\n return runner().lobby_get();\n }\n\n static void\n system_nonInterruptible()\n {\n runner().non_interruptible_set(true);\n }\n\n static void\n system_quit()\n {\n runner().lobby_get()->connection_get().close();\n }\n\n static void\n system_spawn(const rObject&,\n\t const rCode& code,\n const rObject& clear_tags)\n {\n runner::Runner& r = runner();\n runner::Interpreter* new_runner =\n new runner::Interpreter(interpreter(),\n rObject(code),\n libport::Symbol::fresh(r.name_get()));\n\n if (is_true(clear_tags))\n new_runner->tag_stack_clear();\n\n new_runner->time_shift_set(r.time_shift_get());\n new_runner->start_job();\n }\n\n static rObject\n system_stats()\n {\n Dictionary::value_type res;\n const sched::scheduler_stats_type& stats =\n runner().scheduler_get().stats_get();\n\n \/\/ If statistics have just been reset, return \"nil\" since we cannot\n \/\/ return anything significant.\n if (stats.empty())\n return nil_class;\n\n \/\/ The space after \"Symbol(\" is mandatory to avoid triggering an error in\n \/\/ symbol generation code\n#define ADDSTAT(Suffix, Function, Divisor) \\\n res[libport::Symbol(\"cycles\" # Suffix)] = \\\n new Float(stats.Function() \/ Divisor)\n ADDSTAT(, size, 1);\n ADDSTAT(Max, max, 1e6);\n ADDSTAT(Mean, mean, 1e6);\n ADDSTAT(Min, min, 1e6);\n ADDSTAT(StdDev, standard_deviation, 1e6);\n ADDSTAT(Variance, variance, 1e3);\n#undef ADDSTAT\n return new Dictionary(res);\n }\n\n static void\n system_resetStats()\n {\n runner().scheduler_get().stats_reset();\n }\n\n \/\/ This should give a backtrace as an urbi object.\n static void\n system_backtrace()\n {\n \/\/ FIXME: This method sucks a bit, because show_backtrace sucks a\n \/\/ bit, because our channeling\/message-sending system sucks a lot.\n runner::Runner::backtrace_type bt = runner().backtrace_get();\n bt.pop_back();\n foreach (const runner::Runner::frame_type& elt,\n\t boost::make_iterator_range(boost::rbegin(bt),\n\t\t\t\t\tboost::rend(bt)))\n runner().send_message(\"backtrace\", elt.first + \" (\" + elt.second + \")\");\n }\n\n static List::value_type\n system_jobs()\n {\n List::value_type res;\n foreach(sched::rJob job, runner().scheduler_get().jobs_get())\n res.push_back(dynamic_cast<runner::Runner*>(job.get())->as_task());\n return res;\n }\n\n static int\n system_aliveJobs()\n {\n return sched::Job::alive_jobs();\n }\n\n static void\n system_breakpoint()\n {\n return;\n }\n\n#define SERVER_SET_VAR(Function, Variable, Value) \\\n static void \\\n system_ ## Function () \\\n { \\\n urbiserver->Variable = Value; \\\n }\n\n SERVER_SET_VAR(stopall, stopall, true)\n\n#undef SERVER_SET_VAR\n\n static rObject\n system_getenv(const rObject&, const std::string& name)\n {\n char* res = getenv(name.c_str());\n return res ? new String(res) : nil_class;\n }\n\n static rObject\n system_setenv(const rObject&, const std::string& name, rObject value)\n {\n rString v = value->call(SYMBOL(asString))->as<String>();\n setenv(name.c_str(), v->value_get().c_str(), 1);\n return v;\n }\n\n static rObject\n system_unsetenv(const rObject&, const std::string& name)\n {\n rObject res = system_getenv(0, name);\n unsetenv(name.c_str());\n return res;\n }\n\n static libport::InstanceTracker<Lobby>::set_type\n system_lobbies()\n {\n return Lobby::instances_get();\n }\n\n\n static void\n system_loadModule(const rObject&, const std::string& name)\n {\n static bool initialized = false;\n\n if (!initialized)\n {\n initialized = true;\n lt_dlinit();\n }\n lt_dlhandle handle = lt_dlopenext(name.c_str());\n if (!handle)\n RAISE(\"Failed to open `\" + name + \"': \" + lt_dlerror());\n\n \/\/ Reload uobjects\n uobjects_reload();\n\n \/\/ Reload CxxObjects\n CxxObject::create();\n CxxObject::initialize(global_class);\n CxxObject::cleanup();\n }\n\n static libport::cli_args_type urbi_arguments_;\n static boost::optional<std::string> urbi_program_name_;\n\n void\n system_push_argument(const std::string& arg)\n {\n urbi_arguments_.push_back(arg);\n }\n\n void\n system_set_program_name(const std::string& name)\n {\n urbi_program_name_ = name;\n }\n\n static const libport::cli_args_type&\n system_arguments()\n {\n return urbi_arguments_;\n }\n\n static boost::optional<std::string>\n system_programName()\n {\n return urbi_program_name_;\n }\n\n static void\n system__exit(const rObject&, int status)\n {\n exit(status);\n }\n\n static int\n system_system(const rObject&, const std::string& s)\n {\n int res = system(s.c_str());\n switch (res)\n {\n case -1:\n \/\/ FIXME: This is potentially widly used, see also path.cc.\n RAISE(libport::format(\"%1%: %2%\", strerror(errno), s));\n break;\n case 127:\n RAISE(libport::format(\"shell failed: %1%\", s));\n break;\n }\n return res;\n }\n\n void\n system_class_initialize()\n {\n#define DECLARE(Name) \\\n system_class->slot_set(SYMBOL(Name), \\\n make_primitive(&system_##Name)) \\\n\n DECLARE(_exit);\n DECLARE(aliveJobs);\n DECLARE(arguments);\n DECLARE(assert_);\n DECLARE(backtrace);\n DECLARE(breakpoint);\n DECLARE(currentRunner);\n DECLARE(cycle);\n DECLARE(eval);\n DECLARE(fresh);\n DECLARE(getenv);\n DECLARE(jobs);\n DECLARE(loadFile);\n DECLARE(loadModule);\n DECLARE(lobbies);\n DECLARE(lobby);\n DECLARE(nonInterruptible);\n DECLARE(programName);\n DECLARE(quit);\n DECLARE(reboot);\n DECLARE(registerAtJob);\n DECLARE(resetStats);\n DECLARE(scopeTag);\n DECLARE(searchFile);\n DECLARE(searchPath);\n DECLARE(setenv);\n DECLARE(shiftedTime);\n DECLARE(shutdown);\n DECLARE(sleep);\n DECLARE(spawn);\n DECLARE(stats);\n DECLARE(stopall);\n DECLARE(system);\n DECLARE(time);\n DECLARE(unsetenv);\n\n#undef DECLARE\n }\n\n} \/\/ namespace object\n<commit_msg>Missing include.<commit_after>\/**\n ** \\file object\/system-class.cc\n ** \\brief Creation of the URBI object system.\n *\/\n\n#include <ltdl.h>\n\n\/\/#define ENABLE_DEBUG_TRACES\n#include <libport\/compiler.hh>\n#include <libport\/cstdlib>\n#include <libport\/format.hh>\n#include <libport\/program-name.hh>\n\n#include <cerrno>\n#include <memory>\n#include <sstream>\n\n#include <kernel\/uconnection.hh>\n#include <kernel\/uobject.hh>\n#include <kernel\/userver.hh>\n\n#include <object\/code.hh>\n#include <object\/cxx-primitive.hh>\n#include <object\/dictionary.hh>\n#include <object\/float.hh>\n#include <object\/global.hh>\n#include <object\/list.hh>\n#include <object\/lobby.hh>\n#include <object\/path.hh>\n#include <object\/symbols.hh>\n#include <object\/system.hh>\n#include <object\/tag.hh>\n#include <object\/task.hh>\n#include <parser\/transform.hh>\n#include <runner\/at-handler.hh>\n#include <runner\/interpreter.hh>\n#include <runner\/raise.hh>\n#include <runner\/runner.hh>\n\n#include <ast\/nary.hh>\n#include <ast\/routine.hh>\n\nnamespace object\n{\n using kernel::urbiserver;\n\n\n static inline\n runner::Runner&\n runner()\n {\n return ::kernel::urbiserver->getCurrentRunner();\n }\n\n static inline\n runner::Interpreter&\n interpreter()\n {\n return dynamic_cast<runner::Interpreter&>(runner());\n }\n\n \/\/ Extract a filename from a String or a Path object\n static std::string\n filename_get(const rObject& o)\n {\n if (o.is_a<Path>())\n return o->as<Path>()->as_string();\n type_check<String>(o);\n return o->as<String>()->value_get();\n }\n\n\n rObject\n execute_parsed(parser::parse_result_type p,\n libport::Symbol fun, std::string e)\n {\n runner::Interpreter& run = interpreter();\n\n \/\/ Report potential errors\n {\n ast::rNary errs = new ast::Nary();\n p->process_errors(*errs);\n run(errs.get());\n }\n\n ast::rConstAst ast = parser::transform(p->ast_get());\n if (!ast)\n RAISE(e);\n\n runner::Interpreter* sub = new runner::Interpreter(run, ast, fun);\n \/\/ So that it will resist to the call to yield_until_terminated,\n \/\/ and will be reclaimed at the end of the scope.\n sched::rJob job = sub;\n libport::Finally finally;\n runner().register_child(sub, finally);\n sub->start_job();\n try\n {\n run.yield_until_terminated(*job);\n }\n catch (const sched::ChildException& ce)\n {\n \/\/ Kill the sub-job and propagate.\n ce.rethrow_child_exception();\n }\n return sub->result_get();\n }\n\n\n rObject system_class;\n\n \/*--------------------.\n | System primitives. |\n `--------------------*\/\n\n\n#define SERVER_FUNCTION(Function) \\\n static void \\\n system_ ## Function() \\\n { \\\n urbiserver->Function(); \\\n }\n\n SERVER_FUNCTION(reboot)\n SERVER_FUNCTION(shutdown)\n\n#undef SERVER_FUNCTION\n\n\n static void\n system_sleep(const rObject&, libport::ufloat seconds)\n {\n runner::Runner& r = runner();\n if (seconds == std::numeric_limits<ufloat>::infinity())\n r.yield_until_terminated(r);\n else\n r.yield_until(r.scheduler_get().get_time()\n + static_cast<libport::utime_t>(seconds * 1000000.0));\n }\n\n static float\n system_time()\n {\n return runner().scheduler_get().get_time() \/ 1000000.0;\n }\n\n static float\n system_shiftedTime()\n {\n runner::Runner& r = runner();\n return (r.scheduler_get().get_time() - r.time_shift_get()) \/ 1000000.0;\n }\n\n static void\n system_assert_(const rObject&,\n const rObject& value, const std::string& assertion)\n {\n if (!is_true(value))\n RAISE(\"failed assertion: \" + assertion);\n }\n\n static rObject\n system_eval(const rObject&, const std::string& code)\n {\n return execute_parsed(parser::parse(code, ast::loc()),\n SYMBOL(eval),\n \"error executing command: \" + code);\n }\n\n static void\n system_registerAtJob(const rObject&,\n const rObject& condition,\n const rObject& clause,\n const rObject& on_leave)\n {\n runner::register_at_job(interpreter(),\n\t\t\t condition, clause, on_leave);\n }\n\n static rObject\n system_scopeTag()\n {\n return new Tag(interpreter().scope_tag());\n }\n\n static rObject\n system_searchFile(const rObject&, const rObject& f)\n {\n const std::string& filename = filename_get(f);\n try\n {\n return new Path(urbiserver->find_file(filename));\n }\n catch (libport::file_library::Not_found&)\n {\n runner::raise_urbi(SYMBOL(FileNotFound), to_urbi(filename));\n \/\/ Never reached\n assertion(false);\n return 0;\n }\n }\n\n static List::value_type\n system_searchPath()\n {\n List::value_type res;\n foreach (const libport::path& p, urbiserver->search_path.search_path_get())\n res.push_back(new Path(p));\n return res;\n }\n\n static rObject\n system_loadFile(const rObject&, const rObject& f)\n {\n const std::string& filename = filename_get(f);\n if (!libport::path(filename).exists())\n runner::raise_urbi(SYMBOL(FileNotFound), to_urbi(filename));\n return\n execute_parsed(parser::parse_file(filename),\n SYMBOL(loadFile),\n\t\t \"error loading file: \" + filename);\n }\n\n static rObject\n system_currentRunner()\n {\n return runner().as_task();\n }\n\n static float\n system_cycle()\n {\n return runner().scheduler_get().cycle_get();\n }\n\n static libport::Symbol\n system_fresh()\n {\n return libport::Symbol::fresh();\n }\n\n static rObject\n system_lobby()\n {\n return runner().lobby_get();\n }\n\n static void\n system_nonInterruptible()\n {\n runner().non_interruptible_set(true);\n }\n\n static void\n system_quit()\n {\n runner().lobby_get()->connection_get().close();\n }\n\n static void\n system_spawn(const rObject&,\n\t const rCode& code,\n const rObject& clear_tags)\n {\n runner::Runner& r = runner();\n runner::Interpreter* new_runner =\n new runner::Interpreter(interpreter(),\n rObject(code),\n libport::Symbol::fresh(r.name_get()));\n\n if (is_true(clear_tags))\n new_runner->tag_stack_clear();\n\n new_runner->time_shift_set(r.time_shift_get());\n new_runner->start_job();\n }\n\n static rObject\n system_stats()\n {\n Dictionary::value_type res;\n const sched::scheduler_stats_type& stats =\n runner().scheduler_get().stats_get();\n\n \/\/ If statistics have just been reset, return \"nil\" since we cannot\n \/\/ return anything significant.\n if (stats.empty())\n return nil_class;\n\n \/\/ The space after \"Symbol(\" is mandatory to avoid triggering an error in\n \/\/ symbol generation code\n#define ADDSTAT(Suffix, Function, Divisor) \\\n res[libport::Symbol(\"cycles\" # Suffix)] = \\\n new Float(stats.Function() \/ Divisor)\n ADDSTAT(, size, 1);\n ADDSTAT(Max, max, 1e6);\n ADDSTAT(Mean, mean, 1e6);\n ADDSTAT(Min, min, 1e6);\n ADDSTAT(StdDev, standard_deviation, 1e6);\n ADDSTAT(Variance, variance, 1e3);\n#undef ADDSTAT\n return new Dictionary(res);\n }\n\n static void\n system_resetStats()\n {\n runner().scheduler_get().stats_reset();\n }\n\n \/\/ This should give a backtrace as an urbi object.\n static void\n system_backtrace()\n {\n \/\/ FIXME: This method sucks a bit, because show_backtrace sucks a\n \/\/ bit, because our channeling\/message-sending system sucks a lot.\n runner::Runner::backtrace_type bt = runner().backtrace_get();\n bt.pop_back();\n foreach (const runner::Runner::frame_type& elt,\n\t boost::make_iterator_range(boost::rbegin(bt),\n\t\t\t\t\tboost::rend(bt)))\n runner().send_message(\"backtrace\", elt.first + \" (\" + elt.second + \")\");\n }\n\n static List::value_type\n system_jobs()\n {\n List::value_type res;\n foreach(sched::rJob job, runner().scheduler_get().jobs_get())\n res.push_back(dynamic_cast<runner::Runner*>(job.get())->as_task());\n return res;\n }\n\n static int\n system_aliveJobs()\n {\n return sched::Job::alive_jobs();\n }\n\n static void\n system_breakpoint()\n {\n return;\n }\n\n#define SERVER_SET_VAR(Function, Variable, Value) \\\n static void \\\n system_ ## Function () \\\n { \\\n urbiserver->Variable = Value; \\\n }\n\n SERVER_SET_VAR(stopall, stopall, true)\n\n#undef SERVER_SET_VAR\n\n static rObject\n system_getenv(const rObject&, const std::string& name)\n {\n char* res = getenv(name.c_str());\n return res ? new String(res) : nil_class;\n }\n\n static rObject\n system_setenv(const rObject&, const std::string& name, rObject value)\n {\n rString v = value->call(SYMBOL(asString))->as<String>();\n setenv(name.c_str(), v->value_get().c_str(), 1);\n return v;\n }\n\n static rObject\n system_unsetenv(const rObject&, const std::string& name)\n {\n rObject res = system_getenv(0, name);\n unsetenv(name.c_str());\n return res;\n }\n\n static libport::InstanceTracker<Lobby>::set_type\n system_lobbies()\n {\n return Lobby::instances_get();\n }\n\n\n static void\n system_loadModule(const rObject&, const std::string& name)\n {\n static bool initialized = false;\n\n if (!initialized)\n {\n initialized = true;\n lt_dlinit();\n }\n lt_dlhandle handle = lt_dlopenext(name.c_str());\n if (!handle)\n RAISE(\"Failed to open `\" + name + \"': \" + lt_dlerror());\n\n \/\/ Reload uobjects\n uobjects_reload();\n\n \/\/ Reload CxxObjects\n CxxObject::create();\n CxxObject::initialize(global_class);\n CxxObject::cleanup();\n }\n\n static libport::cli_args_type urbi_arguments_;\n static boost::optional<std::string> urbi_program_name_;\n\n void\n system_push_argument(const std::string& arg)\n {\n urbi_arguments_.push_back(arg);\n }\n\n void\n system_set_program_name(const std::string& name)\n {\n urbi_program_name_ = name;\n }\n\n static const libport::cli_args_type&\n system_arguments()\n {\n return urbi_arguments_;\n }\n\n static boost::optional<std::string>\n system_programName()\n {\n return urbi_program_name_;\n }\n\n static void\n system__exit(const rObject&, int status)\n {\n exit(status);\n }\n\n static int\n system_system(const rObject&, const std::string& s)\n {\n int res = system(s.c_str());\n switch (res)\n {\n case -1:\n \/\/ FIXME: This is potentially widly used, see also path.cc.\n RAISE(libport::format(\"%1%: %2%\", strerror(errno), s));\n break;\n case 127:\n RAISE(libport::format(\"shell failed: %1%\", s));\n break;\n }\n return res;\n }\n\n void\n system_class_initialize()\n {\n#define DECLARE(Name) \\\n system_class->slot_set(SYMBOL(Name), \\\n make_primitive(&system_##Name)) \\\n\n DECLARE(_exit);\n DECLARE(aliveJobs);\n DECLARE(arguments);\n DECLARE(assert_);\n DECLARE(backtrace);\n DECLARE(breakpoint);\n DECLARE(currentRunner);\n DECLARE(cycle);\n DECLARE(eval);\n DECLARE(fresh);\n DECLARE(getenv);\n DECLARE(jobs);\n DECLARE(loadFile);\n DECLARE(loadModule);\n DECLARE(lobbies);\n DECLARE(lobby);\n DECLARE(nonInterruptible);\n DECLARE(programName);\n DECLARE(quit);\n DECLARE(reboot);\n DECLARE(registerAtJob);\n DECLARE(resetStats);\n DECLARE(scopeTag);\n DECLARE(searchFile);\n DECLARE(searchPath);\n DECLARE(setenv);\n DECLARE(shiftedTime);\n DECLARE(shutdown);\n DECLARE(sleep);\n DECLARE(spawn);\n DECLARE(stats);\n DECLARE(stopall);\n DECLARE(system);\n DECLARE(time);\n DECLARE(unsetenv);\n\n#undef DECLARE\n }\n\n} \/\/ namespace object\n<|endoftext|>"} {"text":"<commit_before>#include <cstdlib>\n#include <cstdio>\n\n#include \"parser.h\"\n#include \"..\/fancy_exception.h\"\n#include \"..\/utils.h\"\n#include \"..\/bootstrap\/core_classes.h\"\n\n\/* prototype of bison-generated parser function *\/\nextern int yyparse();\nextern void yyrestart(FILE*);\nextern yy_buffer_state* yy_create_buffer(FILE*, int);\nextern yy_buffer_state* yy_scan_string(const char*);\nextern int yy_switch_to_buffer(yy_buffer_state*);\nextern int yy_delete_buffer(yy_buffer_state*);\n\nnamespace fancy {\n namespace parser {\n \n string current_file;\n stack<parser_buffer> parse_buffers;\n list<string> load_path;\n FancyObject* last_value = nil;\n\n void parse_file(string &filename)\n {\n \/\/ put the path of the file into the load_path vector\n \/\/ this makes requiring files in the same directory easier\n string filepath = dirname_for_path(filename);\n if(!is_whitespace(filepath)) {\n load_path.push_back(filepath);\n load_path.unique(); \/\/ remove double entries\n }\n\n if(push_buffer(filename)) {\n try {\n yyparse();\n } catch(FancyException* ex) {\n errorln(\"GOT UNCAUGHT EXCEPTION, ABORTING.\");\n errorln(ex->to_s());\n exit(1);\n }\n\n pop_buffer();\n }\n }\n\n FancyObject* parse_string(const string &code)\n {\n parser_buffer buf;\n buf.buffstate = yy_scan_string(code.c_str());\n buf.lineno = yylineno;\n buf.file = NULL;\n buf.filename = \"\";\n\n yylineno = 1;\n yy_switch_to_buffer(buf.buffstate);\n\n try {\n yyparse();\n } catch(FancyException* ex) {\n errorln(\"GOT UNCAUGHT EXCEPTION, ABORTING.\");\n errorln(ex->to_s());\n exit(1);\n }\n\n \/\/ delete string buffer\n yy_delete_buffer(buf.buffstate);\n\n \/\/ reset to what we had before\n if(!parse_buffers.empty()) {\n parser_buffer prev = parse_buffers.top();\n yy_switch_to_buffer(prev.buffstate);\n yylineno = prev.lineno;\n current_file = prev.filename;\n }\n\n \/\/ finally, return the last evaluated value\n return last_value;\n }\n\n bool push_buffer(const string &filename)\n {\n parser_buffer buf;\n FILE *f = find_open_file(filename);\n if(!f) {\n error(\"\");\n perror(filename.c_str());\n return false;\n } \n buf.buffstate = yy_create_buffer(f, YY_BUF_SIZE);\n buf.file = f;\n buf.filename = filename;\n buf.lineno = yylineno;\n parse_buffers.push(buf);\n \n current_file = filename;\n yylineno = 1;\n \n yy_switch_to_buffer(buf.buffstate);\n return true;\n }\n\n void pop_buffer()\n {\n if(!parse_buffers.empty()) {\n parser_buffer buf = parse_buffers.top();\n parse_buffers.pop();\n \n fclose(buf.file);\n yy_delete_buffer(buf.buffstate);\n\n if(!parse_buffers.empty()) {\n parser_buffer prev = parse_buffers.top();\n yy_switch_to_buffer(prev.buffstate);\n yylineno = prev.lineno;\n current_file = prev.filename;\n }\n }\n }\n\n FILE* find_open_file(const string &filename)\n {\n FILE *f = 0;\n\n \/\/ try direct filename first\n f = fopen(filename.c_str(), \"r\");\n\n \/\/ if that failed, try with each path in load_path prepended to\n \/\/ the filename until we succeed\n if(!f) {\n for(list<string>::iterator it = load_path.begin();\n it != load_path.end();\n it++) {\n f = fopen(((*it) + \"\/\" + filename).c_str(), \"r\");\n if(f) {\n return f;\n }\n }\n }\n \/\/ at this point we failed and f = 0\n return f;\n }\n\n string dirname_for_path(const string &path)\n {\n size_t found = path.find_last_of(\"\/\\\\\");\n return path.substr(0,found);\n }\n string filename_for_path(const string &path)\n {\n size_t found = path.find_last_of(\"\/\\\\\");\n return path.substr(found + 1);\n }\n\n bool is_whitespace(const string &str)\n {\n size_t found = str.find_first_not_of(\" \\t\\r\\n\");\n return str.substr(found) == \"\";\n }\n\n }\n}\n\n<commit_msg>parser\/parser.cc: removed unnecessary try-catch block around yyparse() call<commit_after>#include <cstdlib>\n#include <cstdio>\n\n#include \"parser.h\"\n#include \"..\/fancy_exception.h\"\n#include \"..\/utils.h\"\n#include \"..\/bootstrap\/core_classes.h\"\n\n\/* prototype of bison-generated parser function *\/\nextern int yyparse();\nextern void yyrestart(FILE*);\nextern yy_buffer_state* yy_create_buffer(FILE*, int);\nextern yy_buffer_state* yy_scan_string(const char*);\nextern int yy_switch_to_buffer(yy_buffer_state*);\nextern int yy_delete_buffer(yy_buffer_state*);\n\nnamespace fancy {\n namespace parser {\n \n string current_file;\n stack<parser_buffer> parse_buffers;\n list<string> load_path;\n FancyObject* last_value = nil;\n\n void parse_file(string &filename)\n {\n \/\/ put the path of the file into the load_path vector\n \/\/ this makes requiring files in the same directory easier\n string filepath = dirname_for_path(filename);\n if(!is_whitespace(filepath)) {\n load_path.push_back(filepath);\n load_path.unique(); \/\/ remove double entries\n }\n\n if(push_buffer(filename)) {\n try {\n yyparse();\n } catch(FancyException* ex) {\n errorln(\"GOT UNCAUGHT EXCEPTION, ABORTING.\");\n errorln(ex->to_s());\n exit(1);\n }\n\n pop_buffer();\n }\n }\n\n FancyObject* parse_string(const string &code)\n {\n parser_buffer buf;\n buf.buffstate = yy_scan_string(code.c_str());\n buf.lineno = yylineno;\n buf.file = NULL;\n buf.filename = \"\";\n\n yylineno = 1;\n yy_switch_to_buffer(buf.buffstate);\n\n yyparse();\n\n \/\/ delete string buffer\n yy_delete_buffer(buf.buffstate);\n\n \/\/ reset to what we had before\n if(!parse_buffers.empty()) {\n parser_buffer prev = parse_buffers.top();\n yy_switch_to_buffer(prev.buffstate);\n yylineno = prev.lineno;\n current_file = prev.filename;\n }\n\n \/\/ finally, return the last evaluated value\n return last_value;\n }\n\n bool push_buffer(const string &filename)\n {\n parser_buffer buf;\n FILE *f = find_open_file(filename);\n if(!f) {\n error(\"\");\n perror(filename.c_str());\n return false;\n } \n buf.buffstate = yy_create_buffer(f, YY_BUF_SIZE);\n buf.file = f;\n buf.filename = filename;\n buf.lineno = yylineno;\n parse_buffers.push(buf);\n \n current_file = filename;\n yylineno = 1;\n \n yy_switch_to_buffer(buf.buffstate);\n return true;\n }\n\n void pop_buffer()\n {\n if(!parse_buffers.empty()) {\n parser_buffer buf = parse_buffers.top();\n parse_buffers.pop();\n \n fclose(buf.file);\n yy_delete_buffer(buf.buffstate);\n\n if(!parse_buffers.empty()) {\n parser_buffer prev = parse_buffers.top();\n yy_switch_to_buffer(prev.buffstate);\n yylineno = prev.lineno;\n current_file = prev.filename;\n }\n }\n }\n\n FILE* find_open_file(const string &filename)\n {\n FILE *f = 0;\n\n \/\/ try direct filename first\n f = fopen(filename.c_str(), \"r\");\n\n \/\/ if that failed, try with each path in load_path prepended to\n \/\/ the filename until we succeed\n if(!f) {\n for(list<string>::iterator it = load_path.begin();\n it != load_path.end();\n it++) {\n f = fopen(((*it) + \"\/\" + filename).c_str(), \"r\");\n if(f) {\n return f;\n }\n }\n }\n \/\/ at this point we failed and f = 0\n return f;\n }\n\n string dirname_for_path(const string &path)\n {\n size_t found = path.find_last_of(\"\/\\\\\");\n return path.substr(0,found);\n }\n string filename_for_path(const string &path)\n {\n size_t found = path.find_last_of(\"\/\\\\\");\n return path.substr(found + 1);\n }\n\n bool is_whitespace(const string &str)\n {\n size_t found = str.find_first_not_of(\" \\t\\r\\n\");\n return str.substr(found) == \"\";\n }\n\n }\n}\n\n<|endoftext|>"} {"text":"<commit_before>#include <istream>\n\n#include \"parsers\/bpn.hh\"\n#include \"parsers\/parse.hh\"\n#include \"parsers\/prod.hh\"\n#include \"parsers\/tina.hh\"\n#include \"parsers\/xml.hh\"\n\nnamespace pnmc { namespace parsers {\n \n\/*------------------------------------------------------------------------------------------------*\/\n\nstd::shared_ptr<pn::net>\nparse(const conf::pnmc_configuration& conf, std::istream& in)\n{\n std::shared_ptr<pn::net> net_ptr;\n\n switch (conf.file_type)\n {\n case (conf::input_format::bpn) : return parsers::bpn(in);\n case (conf::input_format::prod) : return parsers::prod(in);\n case (conf::input_format::tina) : return parsers::tina(in);\n case (conf::input_format::xml) : return parsers::xml(in);\n }\n}\n\n\/*------------------------------------------------------------------------------------------------*\/\n\n}} \/\/ namespace pnmc::parsers\n<commit_msg>Avoid (useless) warning about a non-void function returning nothing.<commit_after>#include <istream>\n\n#include \"parsers\/bpn.hh\"\n#include \"parsers\/parse.hh\"\n#include \"parsers\/prod.hh\"\n#include \"parsers\/tina.hh\"\n#include \"parsers\/xml.hh\"\n\nnamespace pnmc { namespace parsers {\n \n\/*------------------------------------------------------------------------------------------------*\/\n\nstd::shared_ptr<pn::net>\nparse(const conf::pnmc_configuration& conf, std::istream& in)\n{\n std::shared_ptr<pn::net> net_ptr;\n\n switch (conf.file_type)\n {\n case (conf::input_format::bpn) : return parsers::bpn(in);\n case (conf::input_format::prod) : return parsers::prod(in);\n case (conf::input_format::tina) : return parsers::tina(in);\n case (conf::input_format::xml) : break;\n }\n return parsers::xml(in);\n}\n\n\/*------------------------------------------------------------------------------------------------*\/\n\n}} \/\/ namespace pnmc::parsers\n<|endoftext|>"} {"text":"<commit_before>\/*\r\n * linker32.cpp\r\n *\r\n * Created on: Jul 23, 2014\r\n * Author: Pimenta\r\n *\/\r\n\r\n#include <cstdint>\r\n#include <cstring>\r\n#include <cstdio>\r\n#include <fstream>\r\n#include <set>\r\n#include <map>\r\n#include <string>\r\n\r\nusing namespace std;\r\n\r\ntypedef uint32_t uword_t;\r\n\r\n#ifndef MEM_WORDS\r\n#define MEM_WORDS 0x2000\r\n#endif\r\n\r\n#ifndef WORD_WIDTH\r\n#define WORD_WIDTH 32\r\n#endif\r\n\r\nstruct ObjectFile32 {\r\n uword_t offset;\r\n uword_t text_offset;\r\n map<string, uword_t> exported;\r\n map<string, set<uword_t>> imported;\r\n set<uword_t> absolute;\r\n uword_t mem_size;\r\n uword_t* mem;\r\n \r\n ~ObjectFile32() {\r\n delete[] mem;\r\n }\r\n \r\n void initStart() {\r\n offset = 0;\r\n text_offset = 0;\r\n imported[\"start\"].emplace(2);\r\n mem_size = 3;\r\n mem = new uword_t[3];\r\n mem[0] = 0;\r\n mem[1] = 0;\r\n mem[2] = 0;\r\n }\r\n \r\n void read(const char* fn, uword_t offs) {\r\n offset = offs;\r\n \r\n fstream f(fn, fstream::in | fstream::binary);\r\n \r\n uword_t tmp;\r\n \r\n \/\/ read text section offset\r\n f.read((char*)&text_offset, sizeof(uword_t));\r\n \r\n \/\/ read number of exported symbols\r\n f.read((char*)&tmp, sizeof(uword_t));\r\n \r\n \/\/ read exported symbols\r\n for (uword_t i = 0; i < tmp; ++i) {\r\n string sym;\r\n uword_t addr;\r\n \r\n \/\/ string\r\n {\r\n char c;\r\n f.read(&c, sizeof(char));\r\n while (c != '\\0') {\r\n sym += c;\r\n f.read(&c, sizeof(char));\r\n }\r\n }\r\n \r\n \/\/ address\r\n f.read((char*)&addr, sizeof(uword_t));\r\n \r\n exported[sym] = addr;\r\n }\r\n \r\n \/\/ read number of symbols of pending references\r\n f.read((char*)&tmp, sizeof(uword_t));\r\n \r\n \/\/ read symbols of pending references\r\n for (uword_t i = 0; i < tmp; ++i) {\r\n string sym;\r\n \r\n \/\/ string\r\n {\r\n char c;\r\n f.read(&c, sizeof(char));\r\n while (c != '\\0') {\r\n sym += c;\r\n f.read(&c, sizeof(char));\r\n }\r\n }\r\n \r\n uword_t tmp2;\r\n \r\n \/\/ read number of references to current symbol\r\n f.read((char*)&tmp2, sizeof(uword_t));\r\n \r\n \/\/ read references to current symbol\r\n for (uword_t j = 0; j < tmp2; ++j) {\r\n uword_t addr;\r\n f.read((char*)&addr, sizeof(uword_t));\r\n imported[sym].emplace(addr);\r\n }\r\n }\r\n \r\n \/\/ read number of absolute addresses\r\n f.read((char*)&tmp, sizeof(uword_t));\r\n \r\n \/\/ read absolute addresses\r\n for (uword_t i = 0; i < tmp; ++i) {\r\n uword_t addr;\r\n f.read((char*)&addr, sizeof(uword_t));\r\n absolute.emplace(addr);\r\n }\r\n \r\n \/\/ read assembled code size\r\n f.read((char*)&mem_size, sizeof(uword_t));\r\n \r\n \/\/ read assembled code\r\n mem = new uword_t[mem_size];\r\n f.read((char*)mem, sizeof(uword_t)*mem_size);\r\n \r\n f.close();\r\n }\r\n};\r\n\r\nint linker32(int argc, char* argv[]) {\r\n if (argc < 3) {\r\n fprintf(stderr, \"Usage mode: subleq-ld <object_files...> <meminit_file>\\n\");\r\n return 0;\r\n }\r\n \r\n \/\/ read object files\r\n ObjectFile32 files[argc - 1];\r\n files[0].initStart();\r\n for (int i = 1; i < argc - 1; ++i)\r\n files[i].read(argv[i], files[i - 1].offset + files[i - 1].mem_size);\r\n \r\n uword_t mem_size = 0;\r\n uword_t* mem = new uword_t[MEM_WORDS];\r\n map<string, uword_t> symbols;\r\n map<string, set<uword_t>> references;\r\n set<uword_t> absolutes;\r\n \r\n for (auto& file : files) {\r\n \/\/ assemble global symbol table\r\n for (auto& sym : file.exported) {\r\n symbols[sym.first] = sym.second + file.offset;\r\n }\r\n \r\n \/\/ assemble global reference table\r\n for (auto& sym : file.imported) {\r\n set<uword_t>& refs = references[sym.first];\r\n for (auto addr : sym.second) {\r\n refs.emplace(addr + file.offset);\r\n }\r\n }\r\n \r\n \/\/ assemble global absolute address table\r\n for (auto addr : file.absolute) {\r\n absolutes.emplace(addr + file.offset);\r\n }\r\n \r\n \/\/ relocate addresses\r\n for (uword_t i = file.text_offset; i < file.mem_size; ++i) {\r\n auto it = file.absolute.find(i);\r\n if (it == file.absolute.end()) {\r\n file.mem[i] += file.offset;\r\n }\r\n }\r\n \r\n \/\/ copy object code\r\n memcpy(&mem[mem_size], file.mem, file.mem_size*sizeof(uword_t));\r\n mem_size += file.mem_size;\r\n }\r\n \r\n \/\/ solve references\r\n for (auto ref = references.begin(); ref != references.end();) {\r\n auto sym = symbols.find(ref->first);\r\n if (sym == symbols.end()) {\r\n ref++;\r\n }\r\n else {\r\n for (auto addr : ref->second) {\r\n mem[addr] = sym->second;\r\n }\r\n references.erase(ref++);\r\n }\r\n }\r\n \r\n \/\/ output mif\r\n fstream f(argv[argc - 1], fstream::out);\r\n char buf[20];\r\n f << \"DEPTH = \" << MEM_WORDS << \";\\n\";\r\n f << \"WIDTH = \" << WORD_WIDTH << \";\\n\";\r\n f << \"ADDRESS_RADIX = HEX;\\n\";\r\n f << \"DATA_RADIX = HEX;\\n\";\r\n f << \"CONTENT\\n\";\r\n f << \"BEGIN\\n\";\r\n f << \"\\n\";\r\n for (uword_t i = 0; i < mem_size; ++i) {\r\n sprintf(buf, \"%08x\", i);\r\n f << buf;\r\n sprintf(buf, \"%08x\", mem[i]);\r\n f << \" : \" << buf << \";\\n\";\r\n }\r\n f << \"\\n\";\r\n f << \"END;\\n\";\r\n f.close();\r\n \r\n delete[] mem;\r\n \r\n return 0;\r\n}\r\n<commit_msg>Now the linker subleq32 takes and outputs relative address table instead of absolute<commit_after>\/*\r\n * linker32.cpp\r\n *\r\n * Created on: Jul 23, 2014\r\n * Author: Pimenta\r\n *\/\r\n\r\n#include <cstdint>\r\n#include <cstring>\r\n#include <cstdio>\r\n#include <fstream>\r\n#include <set>\r\n#include <map>\r\n#include <string>\r\n\r\nusing namespace std;\r\n\r\ntypedef uint32_t uword_t;\r\n\r\n#ifndef MEM_WORDS\r\n#define MEM_WORDS 0x2000\r\n#endif\r\n\r\n#ifndef WORD_WIDTH\r\n#define WORD_WIDTH 32\r\n#endif\r\n\r\nstruct ObjectFile32 {\r\n uword_t offset;\r\n map<string, uword_t> exported;\r\n map<string, set<uword_t>> imported;\r\n set<uword_t> relative;\r\n uword_t mem_size;\r\n uword_t* mem;\r\n \r\n ~ObjectFile32() {\r\n delete[] mem;\r\n }\r\n \r\n void read(const char* fn, uword_t offs) {\r\n offset = offs;\r\n \r\n fstream f(fn, fstream::in | fstream::binary);\r\n \r\n uword_t tmp;\r\n \r\n \/\/ read number of exported symbols\r\n f.read((char*)&tmp, sizeof(uword_t));\r\n \r\n \/\/ read exported symbols\r\n for (uword_t i = 0; i < tmp; ++i) {\r\n string sym;\r\n uword_t addr;\r\n \r\n \/\/ string\r\n {\r\n char c;\r\n f.read(&c, sizeof(char));\r\n while (c != '\\0') {\r\n sym += c;\r\n f.read(&c, sizeof(char));\r\n }\r\n }\r\n \r\n \/\/ address\r\n f.read((char*)&addr, sizeof(uword_t));\r\n \r\n exported[sym] = addr;\r\n }\r\n \r\n \/\/ read number of symbols of pending references\r\n f.read((char*)&tmp, sizeof(uword_t));\r\n \r\n \/\/ read symbols of pending references\r\n for (uword_t i = 0; i < tmp; ++i) {\r\n string sym;\r\n \r\n \/\/ string\r\n {\r\n char c;\r\n f.read(&c, sizeof(char));\r\n while (c != '\\0') {\r\n sym += c;\r\n f.read(&c, sizeof(char));\r\n }\r\n }\r\n \r\n uword_t tmp2;\r\n \r\n \/\/ read number of references to current symbol\r\n f.read((char*)&tmp2, sizeof(uword_t));\r\n \r\n \/\/ read references to current symbol\r\n for (uword_t j = 0; j < tmp2; ++j) {\r\n uword_t addr;\r\n f.read((char*)&addr, sizeof(uword_t));\r\n imported[sym].emplace(addr);\r\n }\r\n }\r\n \r\n \/\/ read number of relative addresses\r\n f.read((char*)&tmp, sizeof(uword_t));\r\n \r\n \/\/ read relative addresses\r\n for (uword_t i = 0; i < tmp; ++i) {\r\n uword_t addr;\r\n f.read((char*)&addr, sizeof(uword_t));\r\n relative.emplace(addr);\r\n }\r\n \r\n \/\/ read assembled code size\r\n f.read((char*)&mem_size, sizeof(uword_t));\r\n \r\n \/\/ read assembled code\r\n mem = new uword_t[mem_size];\r\n f.read((char*)mem, sizeof(uword_t)*mem_size);\r\n \r\n f.close();\r\n }\r\n};\r\n\r\nint linker32(int argc, char* argv[]) {\r\n if (argc < 3) {\r\n fprintf(stderr, \"Usage mode: subleq-ld <object_files...> <meminit_file>\\n\");\r\n return 0;\r\n }\r\n \r\n \/\/ read object files\r\n ObjectFile32 files[argc - 2];\r\n files[0].read(argv[1], 0);\r\n for (int i = 2; i < argc - 1; ++i)\r\n files[i].read(argv[i], files[i - 1].offset + files[i - 1].mem_size);\r\n \r\n uword_t mem_size = 0;\r\n uword_t* mem = new uword_t[MEM_WORDS];\r\n map<string, uword_t> symbols;\r\n map<string, set<uword_t>> references;\r\n set<uword_t> relatives;\r\n \r\n for (auto& file : files) {\r\n \/\/ assemble global symbol table\r\n for (auto& sym : file.exported) {\r\n symbols[sym.first] = sym.second + file.offset;\r\n }\r\n \r\n \/\/ assemble global reference table\r\n for (auto& sym : file.imported) {\r\n set<uword_t>& refs = references[sym.first];\r\n for (auto addr : sym.second) {\r\n refs.emplace(addr + file.offset);\r\n }\r\n }\r\n \r\n \/\/ assemble global relative address table\r\n for (auto addr : file.relative) {\r\n relatives.emplace(addr + file.offset);\r\n file.mem[addr] += file.offset; \/\/ relocating\r\n }\r\n \r\n \/\/ copy object code\r\n memcpy(&mem[mem_size], file.mem, file.mem_size*sizeof(uword_t));\r\n mem_size += file.mem_size;\r\n }\r\n \r\n \/\/ solve references\r\n for (auto ref = references.begin(); ref != references.end();) {\r\n auto sym = symbols.find(ref->first);\r\n if (sym == symbols.end()) {\r\n ref++;\r\n }\r\n else {\r\n for (auto addr : ref->second) {\r\n mem[addr] = sym->second;\r\n }\r\n references.erase(ref++);\r\n }\r\n }\r\n \r\n \/\/ output mif\r\n fstream f(argv[argc - 1], fstream::out);\r\n char buf[20];\r\n f << \"DEPTH = \" << MEM_WORDS << \";\\n\";\r\n f << \"WIDTH = \" << WORD_WIDTH << \";\\n\";\r\n f << \"ADDRESS_RADIX = HEX;\\n\";\r\n f << \"DATA_RADIX = HEX;\\n\";\r\n f << \"CONTENT\\n\";\r\n f << \"BEGIN\\n\";\r\n f << \"\\n\";\r\n for (uword_t i = 0; i < mem_size; ++i) {\r\n sprintf(buf, \"%08x\", i);\r\n f << buf;\r\n sprintf(buf, \"%08x\", mem[i]);\r\n f << \" : \" << buf << \";\\n\";\r\n }\r\n f << \"\\n\";\r\n f << \"END;\\n\";\r\n f.close();\r\n \r\n delete[] mem;\r\n \r\n return 0;\r\n}\r\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2012 Roman Neuhauser\n\/\/ Distributed under the MIT license (see LICENSE file)\n\/\/ vim: sw=2 sts=2 ts=2 fdm=marker cms=\\ \/\/\\ %s\n\n\/\/ shared_ptr\n#include <memory>\n\n#include <iostream>\n#include <istream>\n#include <ostream>\n#include <fstream>\n#include <string>\n#include <vector>\n\n#define EX_OK 0 \/* successful termination *\/\n#define EX_USAGE 64 \/* command line usage error *\/\n#define EX_DATAERR 65 \/* data format error *\/\n#define EX_NOINPUT 66 \/* cannot open input *\/\n\n#include \"boost\/ref.hpp\"\n#include \"boost\/foreach.hpp\"\n#include \"boost\/format.hpp\"\n#include \"boost\/date_time\/gregorian\/gregorian.hpp\"\n#include \"boost\/regex.hpp\"\n\n#include \"iniphile\/input.hpp\"\n#include \"iniphile\/ast.hpp\"\n#include \"iniphile\/output.hpp\"\n\n#define foreach BOOST_FOREACH\n\nusing std::shared_ptr;\n\nusing std::cin;\nusing std::cerr;\nusing std::endl;\nusing std::ios;\nusing std::getline;\nusing std::ostream;\nusing std::ifstream;\nusing std::ofstream;\nusing std::string;\nusing std::vector;\n\nusing boost::cref;\nusing boost::format;\nusing namespace boost::gregorian;\nusing boost::regex;\nusing boost::smatch;\n\nnamespace\n{\n\nstruct expand_sink \/\/ {{{\n{\n expand_sink(string const &prefix, date const &today)\n : prefix(prefix)\n , today(today)\n {}\nprivate:\n string const &prefix;\n date const &today;\npublic:\n string\n operator()(smatch const &expando) const\n {\n auto sexpando = expando.str();\n if (sexpando == \"%D\") return to_iso_extended_string(today);\n if (sexpando == \"%P\") return prefix;\n return \"LOGDEMUX-BUG\";\n }\n}; \/\/ }}}\n\nclass rule\n{\npublic:\n rule(string const &prefix, string const &match, string const &sink, bool final, ostream &diag) \/\/ {{{\n : sink(sink)\n , prefix(prefix)\n , final(final)\n , pat(regex(match, regex::perl))\n , opened_on()\n , os()\n , diag(diag)\n {\n } \/\/ }}}\n bool\n handle(date const &today, string const &line) \/\/ {{{\n {\n if (!regex_search(line, pat))\n return false;\n if (opened_on != today)\n reopen(today);\n os << line << endl;\n return final;\n } \/\/ }}}\nprivate:\n string const sink;\n string const prefix;\n bool final;\n regex pat;\n date opened_on;\n ofstream os;\n ostream &diag;\n\n void\n reopen(date const &today) \/\/ {{{\n {\n if (os.is_open()) os.close();\n os.clear();\n auto fname = expand(sink, today);\n os.open(fname.c_str(), ios::app | ios::binary);\n if (os.fail())\n diag << \"failed to open \" << fname << endl;\n opened_on = today;\n } \/\/ }}}\n string\n expand(string fmt, date const &d) const \/\/ {{{\n {\n return regex_replace(\n fmt\n , regex(\"%[DP]\\\\>\")\n , cref(expand_sink(prefix, d))\n );\n } \/\/ }}}\n};\n\nclass ruleset\n{\npublic:\n ruleset(iniphile::ast::node const &ini, string const &prefix, ostream &diag)\n {\n foreach (auto const &rname, iniphile::get(ini, \"rules.order\", vector<string>()))\n rules.push_back(shared_ptr<rule>(new rule(\n prefix\n , iniphile::get(ini, rname + \".match\", string(\"\")) \n , iniphile::get(ini, rname + \".sink\", string(\"\")) \n , iniphile::get(ini, rname + \".final\", false) \n , diag\n )));\n }\n void\n handle(date const &now, string const &line) \/\/ {{{\n {\n foreach (auto &r, rules)\n if (r->handle(now, line))\n break;\n } \/\/ }}}\nprivate:\n vector<shared_ptr<rule>> rules;\n};\n\ndate\ntoday() \/\/ {{{\n{\n return day_clock::local_day();\n} \/\/ }}}\n\ntemplate<class Fmt>\nint\ncomplain(int exitcode, Fmt msg)\n{\n cerr << msg << endl;\n return exitcode;\n}\n\n}\n\nint\nmain(int argc, char **argv)\n{\n string self = argc > 0 ? argv[0] : \"logdemux\";\n string bself = regex_replace(\n self\n , regex(\"^(.*\/)?([^\/]+)(.exe)?$\", regex::perl)\n , \"$2\"\n );\n\n if (argc < 3)\n return complain(\n EX_USAGE\n , format(\"usage: %1% rules prefix\") % bself\n );\n\n string ini = argv[1];\n string prefix = argv[2];\n ifstream sini;\n sini.open(ini);\n if (sini.fail())\n return complain(\n EX_NOINPUT\n , format(\"%1%: rules file '%2%' missing\") % bself % ini\n );\n\n auto cfg = iniphile::parse(sini, cerr);\n sini.close();\n if (!cfg)\n return complain(\n EX_DATAERR\n , format(\"%1%: rules file '%2%' broken\") % bself % ini\n );\n\n ruleset rules(iniphile::normalize(*cfg), prefix, cerr);\n\n string line;\n while (cin.good()) {\n while (getline(cin, line)) {\n rules.handle(today(), line);\n }\n }\n\n return EX_OK;\n}\n<commit_msg>rule::pat initialization w\/o a redundant copy<commit_after>\/\/ Copyright (c) 2012 Roman Neuhauser\n\/\/ Distributed under the MIT license (see LICENSE file)\n\/\/ vim: sw=2 sts=2 ts=2 fdm=marker cms=\\ \/\/\\ %s\n\n\/\/ shared_ptr\n#include <memory>\n\n#include <iostream>\n#include <istream>\n#include <ostream>\n#include <fstream>\n#include <string>\n#include <vector>\n\n#define EX_OK 0 \/* successful termination *\/\n#define EX_USAGE 64 \/* command line usage error *\/\n#define EX_DATAERR 65 \/* data format error *\/\n#define EX_NOINPUT 66 \/* cannot open input *\/\n\n#include \"boost\/ref.hpp\"\n#include \"boost\/foreach.hpp\"\n#include \"boost\/format.hpp\"\n#include \"boost\/date_time\/gregorian\/gregorian.hpp\"\n#include \"boost\/regex.hpp\"\n\n#include \"iniphile\/input.hpp\"\n#include \"iniphile\/ast.hpp\"\n#include \"iniphile\/output.hpp\"\n\n#define foreach BOOST_FOREACH\n\nusing std::shared_ptr;\n\nusing std::cin;\nusing std::cerr;\nusing std::endl;\nusing std::ios;\nusing std::getline;\nusing std::ostream;\nusing std::ifstream;\nusing std::ofstream;\nusing std::string;\nusing std::vector;\n\nusing boost::cref;\nusing boost::format;\nusing namespace boost::gregorian;\nusing boost::regex;\nusing boost::smatch;\n\nnamespace\n{\n\nstruct expand_sink \/\/ {{{\n{\n expand_sink(string const &prefix, date const &today)\n : prefix(prefix)\n , today(today)\n {}\nprivate:\n string const &prefix;\n date const &today;\npublic:\n string\n operator()(smatch const &expando) const\n {\n auto sexpando = expando.str();\n if (sexpando == \"%D\") return to_iso_extended_string(today);\n if (sexpando == \"%P\") return prefix;\n return \"LOGDEMUX-BUG\";\n }\n}; \/\/ }}}\n\nclass rule\n{\npublic:\n rule(string const &prefix, string const &match, string const &sink, bool final, ostream &diag) \/\/ {{{\n : sink(sink)\n , prefix(prefix)\n , final(final)\n , pat(match, regex::perl)\n , opened_on()\n , os()\n , diag(diag)\n {\n } \/\/ }}}\n bool\n handle(date const &today, string const &line) \/\/ {{{\n {\n if (!regex_search(line, pat))\n return false;\n if (opened_on != today)\n reopen(today);\n os << line << endl;\n return final;\n } \/\/ }}}\nprivate:\n string const sink;\n string const prefix;\n bool final;\n regex pat;\n date opened_on;\n ofstream os;\n ostream &diag;\n\n void\n reopen(date const &today) \/\/ {{{\n {\n if (os.is_open()) os.close();\n os.clear();\n auto fname = expand(sink, today);\n os.open(fname.c_str(), ios::app | ios::binary);\n if (os.fail())\n diag << \"failed to open \" << fname << endl;\n opened_on = today;\n } \/\/ }}}\n string\n expand(string fmt, date const &d) const \/\/ {{{\n {\n return regex_replace(\n fmt\n , regex(\"%[DP]\\\\>\")\n , cref(expand_sink(prefix, d))\n );\n } \/\/ }}}\n};\n\nclass ruleset\n{\npublic:\n ruleset(iniphile::ast::node const &ini, string const &prefix, ostream &diag)\n {\n foreach (auto const &rname, iniphile::get(ini, \"rules.order\", vector<string>()))\n rules.push_back(shared_ptr<rule>(new rule(\n prefix\n , iniphile::get(ini, rname + \".match\", string(\"\")) \n , iniphile::get(ini, rname + \".sink\", string(\"\")) \n , iniphile::get(ini, rname + \".final\", false) \n , diag\n )));\n }\n void\n handle(date const &now, string const &line) \/\/ {{{\n {\n foreach (auto &r, rules)\n if (r->handle(now, line))\n break;\n } \/\/ }}}\nprivate:\n vector<shared_ptr<rule>> rules;\n};\n\ndate\ntoday() \/\/ {{{\n{\n return day_clock::local_day();\n} \/\/ }}}\n\ntemplate<class Fmt>\nint\ncomplain(int exitcode, Fmt msg)\n{\n cerr << msg << endl;\n return exitcode;\n}\n\n}\n\nint\nmain(int argc, char **argv)\n{\n string self = argc > 0 ? argv[0] : \"logdemux\";\n string bself = regex_replace(\n self\n , regex(\"^(.*\/)?([^\/]+)(.exe)?$\", regex::perl)\n , \"$2\"\n );\n\n if (argc < 3)\n return complain(\n EX_USAGE\n , format(\"usage: %1% rules prefix\") % bself\n );\n\n string ini = argv[1];\n string prefix = argv[2];\n ifstream sini;\n sini.open(ini);\n if (sini.fail())\n return complain(\n EX_NOINPUT\n , format(\"%1%: rules file '%2%' missing\") % bself % ini\n );\n\n auto cfg = iniphile::parse(sini, cerr);\n sini.close();\n if (!cfg)\n return complain(\n EX_DATAERR\n , format(\"%1%: rules file '%2%' broken\") % bself % ini\n );\n\n ruleset rules(iniphile::normalize(*cfg), prefix, cerr);\n\n string line;\n while (cin.good()) {\n while (getline(cin, line)) {\n rules.handle(today(), line);\n }\n }\n\n return EX_OK;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2012 Roman Neuhauser\n\/\/ Distributed under the MIT license (see LICENSE file)\n\/\/ vim: sw=2 sts=2 ts=2 fdm=marker cms=\\ \/\/\\ %s\n\n\/\/ shared_ptr\n#include <memory>\n\n#include <iostream>\n#include <istream>\n#include <ostream>\n#include <fstream>\n#include <string>\n#include <vector>\n\n#define EX_OK 0 \/* successful termination *\/\n#define EX_USAGE 64 \/* command line usage error *\/\n#define EX_DATAERR 65 \/* data format error *\/\n#define EX_NOINPUT 66 \/* cannot open input *\/\n\n#include \"boost\/foreach.hpp\"\n#include \"boost\/format.hpp\"\n#include \"boost\/date_time\/gregorian\/gregorian.hpp\"\n#include \"boost\/regex.hpp\"\n\n#include \"iniphile\/input.hpp\"\n#include \"iniphile\/ast.hpp\"\n#include \"iniphile\/output.hpp\"\n\n#define foreach BOOST_FOREACH\n\nusing std::shared_ptr;\n\nusing std::cin;\nusing std::cerr;\nusing std::endl;\nusing std::ios;\nusing std::getline;\nusing std::ifstream;\nusing std::ofstream;\nusing std::string;\nusing std::vector;\n\nusing boost::format;\n\nusing namespace boost::gregorian;\n\nusing boost::regex;\n\nnamespace\n{\n\nclass rule\n{\npublic:\n rule(string const &prefix, string const &match, string const &sink, bool final) \/\/ {{{\n : sink(sink)\n , prefix(prefix)\n , final(final)\n , pat(regex(match, regex::perl))\n , opened_on()\n , os()\n {\n } \/\/ }}}\n bool\n handle(date const &today, string const &line) \/\/ {{{\n {\n if (!regex_search(line, pat))\n return false;\n if (opened_on != today)\n reopen(os, today);\n os << line << endl;\n return final;\n } \/\/ }}}\nprivate:\n string const sink;\n string const prefix;\n bool final;\n regex pat;\n date opened_on;\n ofstream os;\n\n void\n reopen(ofstream &os, date const &today) \/\/ {{{\n {\n if (os.is_open()) os.close();\n os.open(expand(sink, today).c_str(), ios::app | ios::binary);\n opened_on = today;\n } \/\/ }}}\n string\n expand(string fmt, date const &d) const \/\/ {{{\n {\n fmt = regex_replace(fmt, regex(\"%D\"), to_iso_extended_string(d));\n fmt = regex_replace(fmt, regex(\"%P\"), prefix);\n return fmt;\n } \/\/ }}}\n};\n\ntemplate<class Ini = iniphile::ast::node>\nclass ruleset\n{\npublic:\n ruleset(Ini const &ini, string const &prefix)\n : ini(ini)\n , prefix(prefix)\n {\n foreach (auto const &rname, iniphile::get(ini, \"rules.order\", vector<string>()))\n create_rule(rname);\n }\n void\n handle(date const &now, string const &line) \/\/ {{{\n {\n foreach (auto &r, rules)\n if (r->handle(now, line))\n break;\n } \/\/ }}}\nprivate:\n Ini const &ini;\n string const &prefix;\n vector<shared_ptr<rule>> rules;\n\n void\n create_rule(string const &rname) \/\/ {{{\n {\n rules.push_back(shared_ptr<rule>(new rule(\n prefix\n , iniphile::get(ini, rname + \".match\", string(\"\")) \n , iniphile::get(ini, rname + \".sink\", string(\"\")) \n , iniphile::get(ini, rname + \".final\", false) \n )));\n } \/\/ }}}\n};\n\ndate\ntoday() \/\/ {{{\n{\n return day_clock::local_day();\n} \/\/ }}}\n\ntemplate<class Fmt>\nint\ncomplain(int exitcode, Fmt msg)\n{\n cerr << msg << endl;\n return exitcode;\n}\n\n}\n\nint\nmain(int argc, char **argv)\n{\n string self = argc > 0 ? argv[0] : \"logdemux\";\n string bself = self.substr(self.find_last_of(\"\\\\\/\") + 1);\n\n if (argc < 3)\n return complain(\n EX_USAGE\n , format(\"usage: %1% rules prefix\") % bself\n );\n\n string ini = argv[1];\n string prefix = argv[2];\n ifstream sini;\n sini.open(ini);\n if (sini.fail())\n return complain(\n EX_NOINPUT\n , format(\"%1%: rules file '%2%' missing\") % bself % ini\n );\n\n auto cfg = iniphile::parse(sini, cerr);\n if (!cfg)\n return complain(\n EX_DATAERR\n , format(\"%1%: rules file '%2%' broken\") % bself % ini\n );\n\n ruleset<> rules(iniphile::normalize(*cfg), prefix);\n\n string line;\n while (cin.good()) {\n while (getline(cin, line)) {\n rules.handle(today(), line);\n }\n }\n\n return EX_OK;\n}\n<commit_msg>ruleset need not be a template<commit_after>\/\/ Copyright (c) 2012 Roman Neuhauser\n\/\/ Distributed under the MIT license (see LICENSE file)\n\/\/ vim: sw=2 sts=2 ts=2 fdm=marker cms=\\ \/\/\\ %s\n\n\/\/ shared_ptr\n#include <memory>\n\n#include <iostream>\n#include <istream>\n#include <ostream>\n#include <fstream>\n#include <string>\n#include <vector>\n\n#define EX_OK 0 \/* successful termination *\/\n#define EX_USAGE 64 \/* command line usage error *\/\n#define EX_DATAERR 65 \/* data format error *\/\n#define EX_NOINPUT 66 \/* cannot open input *\/\n\n#include \"boost\/foreach.hpp\"\n#include \"boost\/format.hpp\"\n#include \"boost\/date_time\/gregorian\/gregorian.hpp\"\n#include \"boost\/regex.hpp\"\n\n#include \"iniphile\/input.hpp\"\n#include \"iniphile\/ast.hpp\"\n#include \"iniphile\/output.hpp\"\n\n#define foreach BOOST_FOREACH\n\nusing std::shared_ptr;\n\nusing std::cin;\nusing std::cerr;\nusing std::endl;\nusing std::ios;\nusing std::getline;\nusing std::ifstream;\nusing std::ofstream;\nusing std::string;\nusing std::vector;\n\nusing boost::format;\n\nusing namespace boost::gregorian;\n\nusing boost::regex;\n\nnamespace\n{\n\nclass rule\n{\npublic:\n rule(string const &prefix, string const &match, string const &sink, bool final) \/\/ {{{\n : sink(sink)\n , prefix(prefix)\n , final(final)\n , pat(regex(match, regex::perl))\n , opened_on()\n , os()\n {\n } \/\/ }}}\n bool\n handle(date const &today, string const &line) \/\/ {{{\n {\n if (!regex_search(line, pat))\n return false;\n if (opened_on != today)\n reopen(os, today);\n os << line << endl;\n return final;\n } \/\/ }}}\nprivate:\n string const sink;\n string const prefix;\n bool final;\n regex pat;\n date opened_on;\n ofstream os;\n\n void\n reopen(ofstream &os, date const &today) \/\/ {{{\n {\n if (os.is_open()) os.close();\n os.open(expand(sink, today).c_str(), ios::app | ios::binary);\n opened_on = today;\n } \/\/ }}}\n string\n expand(string fmt, date const &d) const \/\/ {{{\n {\n fmt = regex_replace(fmt, regex(\"%D\"), to_iso_extended_string(d));\n fmt = regex_replace(fmt, regex(\"%P\"), prefix);\n return fmt;\n } \/\/ }}}\n};\n\nclass ruleset\n{\npublic:\n ruleset(iniphile::ast::node const &ini, string const &prefix)\n : ini(ini)\n , prefix(prefix)\n {\n foreach (auto const &rname, iniphile::get(ini, \"rules.order\", vector<string>()))\n create_rule(rname);\n }\n void\n handle(date const &now, string const &line) \/\/ {{{\n {\n foreach (auto &r, rules)\n if (r->handle(now, line))\n break;\n } \/\/ }}}\nprivate:\n iniphile::ast::node const &ini;\n string const &prefix;\n vector<shared_ptr<rule>> rules;\n\n void\n create_rule(string const &rname) \/\/ {{{\n {\n rules.push_back(shared_ptr<rule>(new rule(\n prefix\n , iniphile::get(ini, rname + \".match\", string(\"\")) \n , iniphile::get(ini, rname + \".sink\", string(\"\")) \n , iniphile::get(ini, rname + \".final\", false) \n )));\n } \/\/ }}}\n};\n\ndate\ntoday() \/\/ {{{\n{\n return day_clock::local_day();\n} \/\/ }}}\n\ntemplate<class Fmt>\nint\ncomplain(int exitcode, Fmt msg)\n{\n cerr << msg << endl;\n return exitcode;\n}\n\n}\n\nint\nmain(int argc, char **argv)\n{\n string self = argc > 0 ? argv[0] : \"logdemux\";\n string bself = self.substr(self.find_last_of(\"\\\\\/\") + 1);\n\n if (argc < 3)\n return complain(\n EX_USAGE\n , format(\"usage: %1% rules prefix\") % bself\n );\n\n string ini = argv[1];\n string prefix = argv[2];\n ifstream sini;\n sini.open(ini);\n if (sini.fail())\n return complain(\n EX_NOINPUT\n , format(\"%1%: rules file '%2%' missing\") % bself % ini\n );\n\n auto cfg = iniphile::parse(sini, cerr);\n if (!cfg)\n return complain(\n EX_DATAERR\n , format(\"%1%: rules file '%2%' broken\") % bself % ini\n );\n\n ruleset rules(iniphile::normalize(*cfg), prefix);\n\n string line;\n while (cin.good()) {\n while (getline(cin, line)) {\n rules.handle(today(), line);\n }\n }\n\n return EX_OK;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: ndole.hxx,v $\n *\n * $Revision: 1.9 $\n *\n * last change: $Author: rt $ $Date: 2004-11-26 16:25:39 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n#ifndef _NDOLE_HXX\n#define _NDOLE_HXX\n\n#ifndef _NDNOTXT_HXX\n#include <ndnotxt.hxx>\n#endif\n\n#include <svtools\/embedhlp.hxx>\n\nclass SwGrfFmtColl;\nclass SwDoc;\nclass SwOLENode;\nclass SwOLELink;\n\nclass SwOLEListener_Impl;\nclass SwOLEObj\n{\n friend class SwOLENode;\n\n const SwOLENode* pOLENd;\n SwOLEListener_Impl* pListener;\n\n \/\/Entweder Ref oder Name sind bekannt, wenn nur der Name bekannt ist, wird\n \/\/dir Ref bei Anforderung durch GetOleRef() vom Sfx besorgt.\n svt::EmbeddedObjectRef xOLERef;\n String aName;\n\n SwOLEObj( const SwOLEObj& rObj ); \/\/nicht erlaubt.\n SwOLEObj();\n\n void SetNode( SwOLENode* pNode );\n\npublic:\n SwOLEObj( const svt::EmbeddedObjectRef& pObj );\n SwOLEObj( const String &rName );\n ~SwOLEObj();\n\n BOOL UnloadObject();\n String GetDescription();\n\n#ifndef _FESHVIEW_ONLY_INLINE_NEEDED\n com::sun::star::uno::Reference < com::sun::star::embed::XEmbeddedObject > GetOleRef();\n svt::EmbeddedObjectRef& GetObject();\n const String& GetCurrentPersistName() const { return aName; }\n BOOL IsOleRef() const; \/\/Damit das Objekt nicht unnoetig geladen werden muss.\n#endif\n};\n\n\n\/\/ --------------------\n\/\/ SwOLENode\n\/\/ --------------------\n\nclass SwOLENode: public SwNoTxtNode\n{\n friend class SwNodes;\n mutable SwOLEObj aOLEObj;\n Graphic* pGraphic;\n sal_Int64 nViewAspect;\n String sChartTblName; \/\/ bei Chart Objecten: Name der ref. Tabelle\n BOOL bOLESizeInvalid; \/\/Soll beim SwDoc::PrtOLENotify beruecksichtig\n \/\/werden (zum Beispiel kopiert). Ist nicht\n \/\/Persistent.\n\n SwOLENode( const SwNodeIndex &rWhere,\n const svt::EmbeddedObjectRef&,\n SwGrfFmtColl *pGrfColl,\n SwAttrSet* pAutoAttr = 0 );\n\n SwOLENode( const SwNodeIndex &rWhere,\n const String &rName,\n SwGrfFmtColl *pGrfColl,\n SwAttrSet* pAutoAttr = 0 );\n\n \/\/ aOLEObj besitzt einen privaten Copy-CTOR, wir brauchen auch einen:\n SwOLENode( const SwOLENode & );\n\npublic:\n const SwOLEObj& GetOLEObj() const { return aOLEObj; }\n SwOLEObj& GetOLEObj() { return aOLEObj; }\n ~SwOLENode();\n\n virtual SwCntntNode *SplitNode( const SwPosition & );\n \/\/ steht in ndcopy.cxx\n virtual SwCntntNode* MakeCopy( SwDoc*, const SwNodeIndex& ) const;\n\n virtual Size GetTwipSize() const;\n Graphic* GetGraphic();\n void GetNewReplacement();\n\n virtual BOOL SavePersistentData();\n virtual BOOL RestorePersistentData();\n\n BOOL IsInGlobalDocSection() const;\n BOOL IsOLEObjectDeleted() const;\n\n BOOL IsOLESizeInvalid() const { return bOLESizeInvalid; }\n void SetOLESizeInvalid( BOOL b ){ bOLESizeInvalid = b; }\n\n sal_Int64 GetAspect() const { return nViewAspect; }\n void SetAspect( sal_Int64 nAspect) { nViewAspect = nAspect; }\n\n \/\/ OLE-Object aus dem \"Speicher\" entfernen\n \/\/ inline void Unload() { aOLEObj.Unload(); }\n String GetDescription() const { return aOLEObj.GetDescription(); }\n\n#ifndef _FESHVIEW_ONLY_INLINE_NEEDED\n const String& GetChartTblName() const { return sChartTblName; }\n void SetChartTblName( const String& rNm ) { sChartTblName = rNm; }\n#endif\n};\n\n\n\/\/ Inline Metoden aus Node.hxx - erst hier ist der TxtNode bekannt !!\ninline SwOLENode *SwNode::GetOLENode()\n{\n return ND_OLENODE == nNodeType ? (SwOLENode*)this : 0;\n}\ninline const SwOLENode *SwNode::GetOLENode() const\n{\n return ND_OLENODE == nNodeType ? (const SwOLENode*)this : 0;\n}\n\n#endif \/\/ _NDOLE_HXX\n\n<commit_msg>INTEGRATION: CWS mav14 (1.8.158); FILE MERGED 2005\/01\/06 14:07:41 mav 1.8.158.4: #i35475# support embedded links 2005\/01\/06 13:19:37 mav 1.8.158.3: #i35475# support embedded links 2004\/12\/09 20:28:43 mav 1.8.158.2: RESYNC: (1.8-1.9); FILE MERGED 2004\/12\/01 11:20:22 mav 1.8.158.1: #i35475# handle embedded links by link dialog<commit_after>\/*************************************************************************\n *\n * $RCSfile: ndole.hxx,v $\n *\n * $Revision: 1.10 $\n *\n * last change: $Author: kz $ $Date: 2005-01-18 14:57:51 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n#ifndef _NDOLE_HXX\n#define _NDOLE_HXX\n\n#ifndef _NDNOTXT_HXX\n#include <ndnotxt.hxx>\n#endif\n\n#include <svtools\/embedhlp.hxx>\n\nclass SwGrfFmtColl;\nclass SwDoc;\nclass SwOLENode;\nclass SwOLELink;\n\nclass SwOLEListener_Impl;\nclass SwEmbedObjectLink;\nclass SwOLEObj\n{\n friend class SwOLENode;\n\n const SwOLENode* pOLENd;\n SwOLEListener_Impl* pListener;\n\n \/\/Entweder Ref oder Name sind bekannt, wenn nur der Name bekannt ist, wird\n \/\/dir Ref bei Anforderung durch GetOleRef() vom Sfx besorgt.\n svt::EmbeddedObjectRef xOLERef;\n String aName;\n\n SwOLEObj( const SwOLEObj& rObj ); \/\/nicht erlaubt.\n SwOLEObj();\n\n void SetNode( SwOLENode* pNode );\n\npublic:\n SwOLEObj( const svt::EmbeddedObjectRef& pObj );\n SwOLEObj( const String &rName );\n ~SwOLEObj();\n\n BOOL UnloadObject();\n String GetDescription();\n\n#ifndef _FESHVIEW_ONLY_INLINE_NEEDED\n com::sun::star::uno::Reference < com::sun::star::embed::XEmbeddedObject > GetOleRef();\n svt::EmbeddedObjectRef& GetObject();\n const String& GetCurrentPersistName() const { return aName; }\n BOOL IsOleRef() const; \/\/Damit das Objekt nicht unnoetig geladen werden muss.\n#endif\n};\n\n\n\/\/ --------------------\n\/\/ SwOLENode\n\/\/ --------------------\n\nclass SwOLENode: public SwNoTxtNode\n{\n friend class SwNodes;\n mutable SwOLEObj aOLEObj;\n Graphic* pGraphic;\n sal_Int64 nViewAspect;\n String sChartTblName; \/\/ bei Chart Objecten: Name der ref. Tabelle\n BOOL bOLESizeInvalid; \/\/Soll beim SwDoc::PrtOLENotify beruecksichtig\n \/\/werden (zum Beispiel kopiert). Ist nicht\n \/\/Persistent.\n\n SwEmbedObjectLink* mpObjectLink;\n String maLinkURL;\n\n SwOLENode( const SwNodeIndex &rWhere,\n const svt::EmbeddedObjectRef&,\n SwGrfFmtColl *pGrfColl,\n SwAttrSet* pAutoAttr = 0 );\n\n SwOLENode( const SwNodeIndex &rWhere,\n const String &rName,\n SwGrfFmtColl *pGrfColl,\n SwAttrSet* pAutoAttr = 0 );\n\n \/\/ aOLEObj besitzt einen privaten Copy-CTOR, wir brauchen auch einen:\n SwOLENode( const SwOLENode & );\n\npublic:\n const SwOLEObj& GetOLEObj() const { return aOLEObj; }\n SwOLEObj& GetOLEObj() { return aOLEObj; }\n ~SwOLENode();\n\n virtual SwCntntNode *SplitNode( const SwPosition & );\n \/\/ steht in ndcopy.cxx\n virtual SwCntntNode* MakeCopy( SwDoc*, const SwNodeIndex& ) const;\n\n virtual Size GetTwipSize() const;\n Graphic* GetGraphic();\n void GetNewReplacement();\n\n virtual BOOL SavePersistentData();\n virtual BOOL RestorePersistentData();\n\n BOOL IsInGlobalDocSection() const;\n BOOL IsOLEObjectDeleted() const;\n\n BOOL IsOLESizeInvalid() const { return bOLESizeInvalid; }\n void SetOLESizeInvalid( BOOL b ){ bOLESizeInvalid = b; }\n\n sal_Int64 GetAspect() const { return nViewAspect; }\n void SetAspect( sal_Int64 nAspect) { nViewAspect = nAspect; }\n\n \/\/ OLE-Object aus dem \"Speicher\" entfernen\n \/\/ inline void Unload() { aOLEObj.Unload(); }\n String GetDescription() const { return aOLEObj.GetDescription(); }\n\n sal_Bool UpdateLinkURL_Impl();\n void BreakFileLink_Impl();\n void DisconnectFileLink_Impl();\n\n void CheckFileLink_Impl();\n\n#ifndef _FESHVIEW_ONLY_INLINE_NEEDED\n const String& GetChartTblName() const { return sChartTblName; }\n void SetChartTblName( const String& rNm ) { sChartTblName = rNm; }\n#endif\n};\n\n\n\/\/ Inline Metoden aus Node.hxx - erst hier ist der TxtNode bekannt !!\ninline SwOLENode *SwNode::GetOLENode()\n{\n return ND_OLENODE == nNodeType ? (SwOLENode*)this : 0;\n}\ninline const SwOLENode *SwNode::GetOLENode() const\n{\n return ND_OLENODE == nNodeType ? (const SwOLENode*)this : 0;\n}\n\n#endif \/\/ _NDOLE_HXX\n\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: ndtyp.hxx,v $\n *\n * $Revision: 1.2 $\n *\n * last change: $Author: rt $ $Date: 2005-09-09 02:02:50 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef _NDTYP_HXX\n#define _NDTYP_HXX\n\n#ifndef _SOLAR_H\n#include <tools\/solar.h>\n#endif\n\n\/\/ Ids fuer die verschiedenden Nodes; in der Basisklasse steht der Member,\n\/\/ der angibt, um was fuer einen es sich handelt\nconst BYTE ND_ENDNODE = 0x01;\nconst BYTE ND_STARTNODE = 0x02;\nconst BYTE ND_TABLENODE = 0x06;\nconst BYTE ND_TEXTNODE = 0x08;\nconst BYTE ND_GRFNODE = 0x10;\nconst BYTE ND_OLENODE = 0x20;\n\nconst BYTE ND_CONTENTNODE = 0x38; \/\/ ContentNode (eines von den 3 Bits)\nconst BYTE ND_NOTXTNODE = 0x30; \/\/ NoTxtNode (eines von den 2 Bits)\n\nconst BYTE ND_SECTIONNODE = 0x42;\n\/\/ nur fuer internen Gebrauch!!\nconst BYTE ND_SECTIONDUMMY = 0x40; \/\/(ND_SECTIONNODE & ~ND_STARTNODE);\n\n\/\/ spezielle Types der StartNodes, die keine Ableitungen sind, aber\n\/\/ \"Bereiche\" zusammenhalten.\nenum SwStartNodeType\n{\n SwNormalStartNode = 0,\n SwTableBoxStartNode,\n SwFlyStartNode,\n SwFootnoteStartNode,\n SwHeaderStartNode,\n SwFooterStartNode\n};\n\n\/\/ is the node the first and\/or last node of a section?\n\/\/ This information is used for the export filters. Our layout never have a\n\/\/ distance before or after if the node is the first or last in a section.\nconst BYTE ND_HAS_PREV_LAYNODE = 0x01;\nconst BYTE ND_HAS_NEXT_LAYNODE = 0x02;\n\n\n\n#endif\n<commit_msg>INTEGRATION: CWS changefileheader (1.2.1202); FILE MERGED 2008\/04\/01 15:56:16 thb 1.2.1202.2: #i85898# Stripping all external header guards 2008\/03\/31 16:52:40 rt 1.2.1202.1: #i87441# Change license header to LPGL v3.<commit_after>\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2008 by Sun Microsystems, Inc.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: ndtyp.hxx,v $\n * $Revision: 1.3 $\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * <http:\/\/www.openoffice.org\/license.html>\n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n#ifndef _NDTYP_HXX\n#define _NDTYP_HXX\n\n#include <tools\/solar.h>\n\n\/\/ Ids fuer die verschiedenden Nodes; in der Basisklasse steht der Member,\n\/\/ der angibt, um was fuer einen es sich handelt\nconst BYTE ND_ENDNODE = 0x01;\nconst BYTE ND_STARTNODE = 0x02;\nconst BYTE ND_TABLENODE = 0x06;\nconst BYTE ND_TEXTNODE = 0x08;\nconst BYTE ND_GRFNODE = 0x10;\nconst BYTE ND_OLENODE = 0x20;\n\nconst BYTE ND_CONTENTNODE = 0x38; \/\/ ContentNode (eines von den 3 Bits)\nconst BYTE ND_NOTXTNODE = 0x30; \/\/ NoTxtNode (eines von den 2 Bits)\n\nconst BYTE ND_SECTIONNODE = 0x42;\n\/\/ nur fuer internen Gebrauch!!\nconst BYTE ND_SECTIONDUMMY = 0x40; \/\/(ND_SECTIONNODE & ~ND_STARTNODE);\n\n\/\/ spezielle Types der StartNodes, die keine Ableitungen sind, aber\n\/\/ \"Bereiche\" zusammenhalten.\nenum SwStartNodeType\n{\n SwNormalStartNode = 0,\n SwTableBoxStartNode,\n SwFlyStartNode,\n SwFootnoteStartNode,\n SwHeaderStartNode,\n SwFooterStartNode\n};\n\n\/\/ is the node the first and\/or last node of a section?\n\/\/ This information is used for the export filters. Our layout never have a\n\/\/ distance before or after if the node is the first or last in a section.\nconst BYTE ND_HAS_PREV_LAYNODE = 0x01;\nconst BYTE ND_HAS_NEXT_LAYNODE = 0x02;\n\n\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ This file is part of Grappa, a system for scaling irregular\n\/\/ applications on commodity clusters. \n\n\/\/ Copyright (C) 2010-2014 University of Washington and Battelle\n\/\/ Memorial Institute. University of Washington authorizes use of this\n\/\/ Grappa software.\n\n\/\/ Grappa is free software: you can redistribute it and\/or modify it\n\/\/ under the terms of the Affero General Public License as published\n\/\/ by Affero, Inc., either version 1 of the License, or (at your\n\/\/ option) any later version.\n\n\/\/ Grappa is distributed in the hope that it will be useful, but\n\/\/ WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n\/\/ Affero General Public License for more details.\n\n\/\/ You should have received a copy of the Affero General Public\n\/\/ License along with this program. If not, you may obtain one from\n\/\/ http:\/\/www.affero.org\/oagpl.html.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n#pragma once\n\n#include \"Addressing.hpp\"\n#include \"Communicator.hpp\"\n#include \"Collective.hpp\"\n#include \"Cache.hpp\"\n#include \"GlobalCompletionEvent.hpp\"\n#include \"ParallelLoop.hpp\"\n#include \"GlobalAllocator.hpp\"\n#include <type_traits>\n#include \"Delegate.hpp\"\n\nnamespace Grappa {\n\/\/\/ @addtogroup Containers\n\/\/\/ @{\n \n\/\/\/ Initialize an array of elements of generic type with a given value.\n\/\/\/ \n\/\/\/ This version sends a large number of active messages, the same way as the Incoherent\n\/\/\/ releaser, to set each part of a global array. In theory, this version should be able\n\/\/\/ to be called from multiple locations at the same time (to initialize different regions of global memory).\n\/\/\/ \n\/\/\/ @param base Base address of the array to be set.\n\/\/\/ @param value Value to set every element of array to (will be copied to all the nodes)\n\/\/\/ @param count Number of elements to set, starting at the base address.\ntemplate< typename T, typename S >\nvoid memset(GlobalAddress<T> base, S value, size_t count) {\n call_on_all_cores([base,count,value]{\n T * local_base = base.localize();\n T * local_end = (base+count).localize();\n for (size_t i=0; i<local_end-local_base; i++) {\n local_base[i] = value;\n }\n });\n}\n\nnamespace impl {\n \/\/\/ Copy elements of array (src..src+nelem) that are local to corresponding locations in dst\n template< typename T >\n void do_memcpy_locally(GlobalAddress<T> dst, GlobalAddress<T> src, size_t nelem) {\n typedef typename Incoherent<T>::WO Writeback;\n auto src_end = src+nelem;\n \/\/ T * local_base = src.localize(), * local_end = (src+nelem).localize();\n int64_t nfirstcore = src.block_max() - src;\n int64_t nlastcore = src_end - src_end.block_min();\n int64_t nmiddle = nelem - nfirstcore - nlastcore;\n \n const size_t nblock = block_size \/ sizeof(T);\n \n CHECK_EQ(nmiddle % nblock, 0);\n\n auto src_start = src;\n if (src.core() == mycore()) {\n int64_t nfirstcore = src.block_max() - src;\n if (nfirstcore > 0 && nlastcore != nblock) {\n DVLOG(3) << \"nfirstcore = \" << nfirstcore;\n Writeback w(dst, nfirstcore, src.pointer());\n src_start += nfirstcore;\n }\n }\n if ((src_end-1).core() == mycore()) {\n int64_t nlastcore = src_end - src_end.block_min();\n int64_t index = nelem - nlastcore;\n if (nlastcore > 0 && nlastcore != nblock) {\n DVLOG(3) << \"nlastcore = \" << nlastcore << \", index = \" << index;\n CHECK((src+index).core() == mycore());\n Writeback w(dst+index, nlastcore, (src+index).pointer());\n src_end -= nlastcore;\n }\n }\n \n auto * local_base = src_start.localize();\n size_t nlocal_trimmed = src_end.localize() - local_base;\n CHECK_EQ((nlocal_trimmed) % nblock, 0);\n size_t nlocalblocks = nlocal_trimmed\/nblock;\n Writeback * ws = locale_alloc<Writeback>(nlocalblocks);\n for (size_t i=0; i<nlocalblocks; i++) {\n size_t j = make_linear(local_base+(i*nblock))-src;\n new (ws+i) Writeback(dst+j, nblock, local_base+(i*nblock));\n ws[i].start_release();\n }\n for (size_t i=0; i<nlocalblocks; i++) { ws[i].block_until_released(); }\n locale_free(ws);\n }\n}\n\n\/\/\/ Memcpy over Grappa global arrays. Arguments `dst` and `src` must point into global arrays \n\/\/\/ (so must be linear addresses) and be non-overlapping, and both must have at least `nelem`\n\/\/\/ elements.\ntemplate< typename T >\nvoid memcpy(GlobalAddress<T> dst, GlobalAddress<T> src, size_t nelem) {\n on_all_cores([dst,src,nelem]{\n impl::do_memcpy_locally(dst,src,nelem);\n });\n}\n\n\/\/\/ Helper so we don't have to change the code if we change a Global pointer to a normal pointer (in theory).\ntemplate< typename T >\nvoid memcpy(T* dst, T* src, size_t nelem) {\n ::memcpy(dst, src, nelem*sizeof(T));\n}\n\n\n\/\/\/ Asynchronous version of memcpy, spawns only on cores with array elements. Synchronizes\n\/\/\/ with given GlobalCompletionEvent, so memcpy's are known to be complete after GCE->wait().\n\/\/\/ Note: same restrictions on `dst` and `src` as Grappa::memcpy).\ntemplate< GlobalCompletionEvent * GCE = &impl::local_gce, typename T = void >\nvoid memcpy_async(GlobalAddress<T> dst, GlobalAddress<T> src, size_t nelem) {\n on_cores_localized_async<GCE>(src, nelem, [dst,src,nelem](T* base, size_t nlocal){\n impl::do_memcpy_locally(dst,src,nelem);\n });\n}\n\n\/\/\/ not implemented yet\ntemplate< typename T >\nvoid prefix_sum(GlobalAddress<T> array, size_t nelem) {\n \/\/ not implemented\n CHECK(false) << \"prefix_sum is currently unimplemented!\";\n}\n\nnamespace util {\n \/\/\/ String representation of a local array, matches form of Grappa::array_str that takes a global array.\n template<typename T>\n inline std::string array_str(const char * name, T * base, size_t nelem, int width = 10) {\n std::stringstream ss; ss << \"\\n\" << name << \": [\";\n for (size_t i=0; i<nelem; i++) {\n if (i % width == 0) ss << \"\\n \";\n ss << \" \" << base[i];\n }\n ss << \"\\n]\";\n return ss.str();\n }\n \n \/\/\/ String representation of a global array.\n \/\/\/ @example\n \/\/\/ @code\n \/\/\/ GlobalAddress<int> xs;\n \/\/\/ DVLOG(2) << array_str(\"x\", xs, 4);\n \/\/\/ \/\/ (if DEBUG=1 and --v=2)\n \/\/\/ \/\/> x: [\n \/\/\/ \/\/> 7 4 2 3\n \/\/\/ \/\/> ]\n \/\/\/ @endcode\n template<typename T>\n inline std::string array_str(const char * name, GlobalAddress<T> base, size_t nelem, int width = 10) {\n std::stringstream ss; ss << \"\\n\" << name << \": [\";\n for (size_t i=0; i<nelem; i++) {\n if (i % width == 0) ss << \"\\n \";\n ss << \" \" << delegate::read(base+i);\n }\n ss << \"\\n]\";\n return ss.str();\n }\n\n template< typename ArrayT, class = typename std::enable_if<std::is_array<ArrayT>::value>::type >\n inline std::string array_str(const char * name, ArrayT array, int width = 10) {\n std::stringstream ss; ss << \"\\n\" << name << \": [\";\n long i=0;\n for (auto e : array) {\n if (i % width == 0) ss << \"\\n \";\n ss << \" \" << e;\n i++;\n }\n ss << \"\\n]\";\n return ss.str();\n }\n \n template<typename T>\n struct SimpleIterator {\n T * base;\n size_t nelem;\n T * begin() { return base; }\n T * end() { return base+nelem; }\n };\n \n \/\/\/ Easier C++11 iteration over local array. Similar idea to Addressing::iterate_local().\n \/\/\/\n \/\/\/ @code\n \/\/\/ auto array = new long[N];\n \/\/\/ for (auto& v : util::iterate(array,N)) {\n \/\/\/ v++;\n \/\/\/ }\n \/\/\/ @endcode\n template<typename T>\n SimpleIterator<T> iterate(T* base = nullptr, size_t nelem = 0) { return SimpleIterator<T>{base, nelem}; }\n \n} \/\/ namespace util\n\n\/\/\/ @}\n} \/\/ namespace Grappa\n<commit_msg>fix Grappa::memcpy to handle void*<commit_after>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ This file is part of Grappa, a system for scaling irregular\n\/\/ applications on commodity clusters. \n\n\/\/ Copyright (C) 2010-2014 University of Washington and Battelle\n\/\/ Memorial Institute. University of Washington authorizes use of this\n\/\/ Grappa software.\n\n\/\/ Grappa is free software: you can redistribute it and\/or modify it\n\/\/ under the terms of the Affero General Public License as published\n\/\/ by Affero, Inc., either version 1 of the License, or (at your\n\/\/ option) any later version.\n\n\/\/ Grappa is distributed in the hope that it will be useful, but\n\/\/ WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n\/\/ Affero General Public License for more details.\n\n\/\/ You should have received a copy of the Affero General Public\n\/\/ License along with this program. If not, you may obtain one from\n\/\/ http:\/\/www.affero.org\/oagpl.html.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n#pragma once\n\n#include \"Addressing.hpp\"\n#include \"Communicator.hpp\"\n#include \"Collective.hpp\"\n#include \"Cache.hpp\"\n#include \"GlobalCompletionEvent.hpp\"\n#include \"ParallelLoop.hpp\"\n#include \"GlobalAllocator.hpp\"\n#include <type_traits>\n#include \"Delegate.hpp\"\n\nnamespace Grappa {\n\/\/\/ @addtogroup Containers\n\/\/\/ @{\n \n\/\/\/ Initialize an array of elements of generic type with a given value.\n\/\/\/ \n\/\/\/ This version sends a large number of active messages, the same way as the Incoherent\n\/\/\/ releaser, to set each part of a global array. In theory, this version should be able\n\/\/\/ to be called from multiple locations at the same time (to initialize different regions of global memory).\n\/\/\/ \n\/\/\/ @param base Base address of the array to be set.\n\/\/\/ @param value Value to set every element of array to (will be copied to all the nodes)\n\/\/\/ @param count Number of elements to set, starting at the base address.\ntemplate< typename T, typename S >\nvoid memset(GlobalAddress<T> base, S value, size_t count) {\n call_on_all_cores([base,count,value]{\n T * local_base = base.localize();\n T * local_end = (base+count).localize();\n for (size_t i=0; i<local_end-local_base; i++) {\n local_base[i] = value;\n }\n });\n}\n\nnamespace impl {\n \/\/\/ Copy elements of array (src..src+nelem) that are local to corresponding locations in dst\n template< typename T >\n void do_memcpy_locally(GlobalAddress<T> dst, GlobalAddress<T> src, size_t nelem) {\n typedef typename Incoherent<T>::WO Writeback;\n auto src_end = src+nelem;\n \/\/ T * local_base = src.localize(), * local_end = (src+nelem).localize();\n int64_t nfirstcore = src.block_max() - src;\n int64_t nlastcore = src_end - src_end.block_min();\n int64_t nmiddle = nelem - nfirstcore - nlastcore;\n \n const size_t nblock = block_size \/ sizeof(T);\n \n CHECK_EQ(nmiddle % nblock, 0);\n\n auto src_start = src;\n if (src.core() == mycore()) {\n int64_t nfirstcore = src.block_max() - src;\n if (nfirstcore > 0 && nlastcore != nblock) {\n DVLOG(3) << \"nfirstcore = \" << nfirstcore;\n Writeback w(dst, nfirstcore, src.pointer());\n src_start += nfirstcore;\n }\n }\n if ((src_end-1).core() == mycore()) {\n int64_t nlastcore = src_end - src_end.block_min();\n int64_t index = nelem - nlastcore;\n if (nlastcore > 0 && nlastcore != nblock) {\n DVLOG(3) << \"nlastcore = \" << nlastcore << \", index = \" << index;\n CHECK((src+index).core() == mycore());\n Writeback w(dst+index, nlastcore, (src+index).pointer());\n src_end -= nlastcore;\n }\n }\n \n auto * local_base = src_start.localize();\n size_t nlocal_trimmed = src_end.localize() - local_base;\n CHECK_EQ((nlocal_trimmed) % nblock, 0);\n size_t nlocalblocks = nlocal_trimmed\/nblock;\n Writeback * ws = locale_alloc<Writeback>(nlocalblocks);\n for (size_t i=0; i<nlocalblocks; i++) {\n size_t j = make_linear(local_base+(i*nblock))-src;\n new (ws+i) Writeback(dst+j, nblock, local_base+(i*nblock));\n ws[i].start_release();\n }\n for (size_t i=0; i<nlocalblocks; i++) { ws[i].block_until_released(); }\n locale_free(ws);\n }\n}\n\n\/\/\/ Memcpy over Grappa global arrays. Arguments `dst` and `src` must point into global arrays \n\/\/\/ (so must be linear addresses) and be non-overlapping, and both must have at least `nelem`\n\/\/\/ elements.\ntemplate< typename T >\nvoid memcpy(GlobalAddress<T> dst, GlobalAddress<T> src, size_t nelem) {\n on_all_cores([dst,src,nelem]{\n impl::do_memcpy_locally(dst,src,nelem);\n });\n}\n\n\/\/\/ Helper so we don't have to change the code if we change a Global pointer to a normal pointer (in theory).\ntemplate< typename T >\ninline void memcpy(T* dst, T* src, size_t nelem) {\n ::memcpy(dst, src, nelem*sizeof(T));\n}\n\ntemplate<>\ninline void memcpy<void>(void* dst, void* src, size_t nelem) {\n ::memcpy(dst, src, nelem);\n}\n\n \n\n\/\/\/ Asynchronous version of memcpy, spawns only on cores with array elements. Synchronizes\n\/\/\/ with given GlobalCompletionEvent, so memcpy's are known to be complete after GCE->wait().\n\/\/\/ Note: same restrictions on `dst` and `src` as Grappa::memcpy).\ntemplate< GlobalCompletionEvent * GCE = &impl::local_gce, typename T = void >\nvoid memcpy_async(GlobalAddress<T> dst, GlobalAddress<T> src, size_t nelem) {\n on_cores_localized_async<GCE>(src, nelem, [dst,src,nelem](T* base, size_t nlocal){\n impl::do_memcpy_locally(dst,src,nelem);\n });\n}\n\n\/\/\/ not implemented yet\ntemplate< typename T >\nvoid prefix_sum(GlobalAddress<T> array, size_t nelem) {\n \/\/ not implemented\n CHECK(false) << \"prefix_sum is currently unimplemented!\";\n}\n\nnamespace util {\n \/\/\/ String representation of a local array, matches form of Grappa::array_str that takes a global array.\n template<typename T>\n inline std::string array_str(const char * name, T * base, size_t nelem, int width = 10) {\n std::stringstream ss; ss << \"\\n\" << name << \": [\";\n for (size_t i=0; i<nelem; i++) {\n if (i % width == 0) ss << \"\\n \";\n ss << \" \" << base[i];\n }\n ss << \"\\n]\";\n return ss.str();\n }\n \n \/\/\/ String representation of a global array.\n \/\/\/ @example\n \/\/\/ @code\n \/\/\/ GlobalAddress<int> xs;\n \/\/\/ DVLOG(2) << array_str(\"x\", xs, 4);\n \/\/\/ \/\/ (if DEBUG=1 and --v=2)\n \/\/\/ \/\/> x: [\n \/\/\/ \/\/> 7 4 2 3\n \/\/\/ \/\/> ]\n \/\/\/ @endcode\n template<typename T>\n inline std::string array_str(const char * name, GlobalAddress<T> base, size_t nelem, int width = 10) {\n std::stringstream ss; ss << \"\\n\" << name << \": [\";\n for (size_t i=0; i<nelem; i++) {\n if (i % width == 0) ss << \"\\n \";\n ss << \" \" << delegate::read(base+i);\n }\n ss << \"\\n]\";\n return ss.str();\n }\n\n template< typename ArrayT, class = typename std::enable_if<std::is_array<ArrayT>::value>::type >\n inline std::string array_str(const char * name, ArrayT array, int width = 10) {\n std::stringstream ss; ss << \"\\n\" << name << \": [\";\n long i=0;\n for (auto e : array) {\n if (i % width == 0) ss << \"\\n \";\n ss << \" \" << e;\n i++;\n }\n ss << \"\\n]\";\n return ss.str();\n }\n \n template<typename T>\n struct SimpleIterator {\n T * base;\n size_t nelem;\n T * begin() { return base; }\n T * end() { return base+nelem; }\n };\n \n \/\/\/ Easier C++11 iteration over local array. Similar idea to Addressing::iterate_local().\n \/\/\/\n \/\/\/ @code\n \/\/\/ auto array = new long[N];\n \/\/\/ for (auto& v : util::iterate(array,N)) {\n \/\/\/ v++;\n \/\/\/ }\n \/\/\/ @endcode\n template<typename T>\n SimpleIterator<T> iterate(T* base = nullptr, size_t nelem = 0) { return SimpleIterator<T>{base, nelem}; }\n \n} \/\/ namespace util\n\n\/\/\/ @}\n} \/\/ namespace Grappa\n<|endoftext|>"} {"text":"<commit_before>\/\/ This file is part of Eigen, a lightweight C++ template library\n\/\/ for linear algebra.\n\/\/\n\/\/ Copyright (C) 2008 Gael Guennebaud <gael.guennebaud@inria.fr>\n\/\/ Copyright (C) 2006-2008 Benoit Jacob <jacob.benoit.1@gmail.com>\n\/\/\n\/\/ This Source Code Form is subject to the terms of the Mozilla\n\/\/ Public License v. 2.0. If a copy of the MPL was not distributed\n\/\/ with this file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n\n#define EIGEN2_SUPPORT\n#define EIGEN_NO_STATIC_ASSERT\n#include \"main.h\"\n#include <functional>\n\n#ifdef min\n#undef min\n#endif\n\n#ifdef max\n#undef max\n#endif\n\nusing namespace std;\n\ntemplate<typename Scalar> struct AddIfNull {\n const Scalar operator() (const Scalar a, const Scalar b) const {return a<=1e-3 ? b : a;}\n enum { Cost = NumTraits<Scalar>::AddCost };\n};\n\ntemplate<typename MatrixType>\ntypename Eigen::internal::enable_if<!NumTraits<typename MatrixType::Scalar>::IsInteger,typename MatrixType::Scalar>::type\ncwiseops_real_only(MatrixType& m1, MatrixType& m2, MatrixType& m3, MatrixType& mones)\n{\n typedef typename MatrixType::Scalar Scalar;\n typedef typename NumTraits<Scalar>::Real RealScalar;\n \n VERIFY_IS_APPROX(m1.cwise() \/ m2, m1.cwise() * (m2.cwise().inverse()));\n m3 = m1.cwise().abs().cwise().sqrt();\n VERIFY_IS_APPROX(m3.cwise().square(), m1.cwise().abs());\n VERIFY_IS_APPROX(m1.cwise().square().cwise().sqrt(), m1.cwise().abs());\n VERIFY_IS_APPROX(m1.cwise().abs().cwise().log().cwise().exp() , m1.cwise().abs());\n\n VERIFY_IS_APPROX(m1.cwise().pow(2), m1.cwise().square());\n m3 = (m1.cwise().abs().cwise()<=RealScalar(0.01)).select(mones,m1);\n VERIFY_IS_APPROX(m3.cwise().pow(-1), m3.cwise().inverse());\n m3 = m1.cwise().abs();\n VERIFY_IS_APPROX(m3.cwise().pow(RealScalar(0.5)), m3.cwise().sqrt());\n\n\/\/ VERIFY_IS_APPROX(m1.cwise().tan(), m1.cwise().sin().cwise() \/ m1.cwise().cos());\n VERIFY_IS_APPROX(mones, m1.cwise().sin().cwise().square() + m1.cwise().cos().cwise().square());\n m3 = m1;\n m3.cwise() \/= m2;\n VERIFY_IS_APPROX(m3, m1.cwise() \/ m2);\n \n return Scalar(0);\n}\n\ntemplate<typename MatrixType>\ntypename Eigen::internal::enable_if<NumTraits<typename MatrixType::Scalar>::IsInteger,typename MatrixType::Scalar>::type\ncwiseops_real_only(MatrixType& , MatrixType& , MatrixType& , MatrixType& )\n{\n typedef typename MatrixType::Scalar Scalar;\n return 0;\n}\n\ntemplate<typename MatrixType> void cwiseops(const MatrixType& m)\n{\n typedef typename MatrixType::Index Index;\n typedef typename MatrixType::Scalar Scalar;\n typedef typename NumTraits<Scalar>::Real RealScalar;\n typedef Matrix<Scalar, MatrixType::RowsAtCompileTime, 1> VectorType;\n\n Index rows = m.rows();\n Index cols = m.cols();\n\n MatrixType m1 = MatrixType::Random(rows, cols),\n m2 = MatrixType::Random(rows, cols),\n m3(rows, cols),\n m4(rows, cols),\n mzero = MatrixType::Zero(rows, cols),\n mones = MatrixType::Ones(rows, cols),\n identity = Matrix<Scalar, MatrixType::RowsAtCompileTime, MatrixType::RowsAtCompileTime>\n ::Identity(rows, rows);\n VectorType vzero = VectorType::Zero(rows),\n vones = VectorType::Ones(rows),\n v3(rows);\n\n Index r = internal::random<Index>(0, rows-1),\n c = internal::random<Index>(0, cols-1);\n\n Scalar s1 = internal::random<Scalar>();\n\n \/\/ test Zero, Ones, Constant, and the set* variants\n m3 = MatrixType::Constant(rows, cols, s1);\n for (int j=0; j<cols; ++j)\n for (int i=0; i<rows; ++i)\n {\n VERIFY_IS_APPROX(mzero(i,j), Scalar(0));\n VERIFY_IS_APPROX(mones(i,j), Scalar(1));\n VERIFY_IS_APPROX(m3(i,j), s1);\n }\n VERIFY(mzero.isZero());\n VERIFY(mones.isOnes());\n VERIFY(m3.isConstant(s1));\n VERIFY(identity.isIdentity());\n VERIFY_IS_APPROX(m4.setConstant(s1), m3);\n VERIFY_IS_APPROX(m4.setConstant(rows,cols,s1), m3);\n VERIFY_IS_APPROX(m4.setZero(), mzero);\n VERIFY_IS_APPROX(m4.setZero(rows,cols), mzero);\n VERIFY_IS_APPROX(m4.setOnes(), mones);\n VERIFY_IS_APPROX(m4.setOnes(rows,cols), mones);\n m4.fill(s1);\n VERIFY_IS_APPROX(m4, m3);\n\n VERIFY_IS_APPROX(v3.setConstant(rows, s1), VectorType::Constant(rows,s1));\n VERIFY_IS_APPROX(v3.setZero(rows), vzero);\n VERIFY_IS_APPROX(v3.setOnes(rows), vones);\n\n m2 = m2.template binaryExpr<AddIfNull<Scalar> >(mones);\n\n VERIFY_IS_APPROX(m1.cwise().pow(2), m1.cwise().abs2());\n VERIFY_IS_APPROX(m1.cwise().pow(2), m1.cwise().square());\n VERIFY_IS_APPROX(m1.cwise().pow(3), m1.cwise().cube());\n\n VERIFY_IS_APPROX(m1 + mones, m1.cwise()+Scalar(1));\n VERIFY_IS_APPROX(m1 - mones, m1.cwise()-Scalar(1));\n m3 = m1; m3.cwise() += 1;\n VERIFY_IS_APPROX(m1 + mones, m3);\n m3 = m1; m3.cwise() -= 1;\n VERIFY_IS_APPROX(m1 - mones, m3);\n\n VERIFY_IS_APPROX(m2, m2.cwise() * mones);\n VERIFY_IS_APPROX(m1.cwise() * m2, m2.cwise() * m1);\n m3 = m1;\n m3.cwise() *= m2;\n VERIFY_IS_APPROX(m3, m1.cwise() * m2);\n\n VERIFY_IS_APPROX(mones, m2.cwise()\/m2);\n\n \/\/ check min\n VERIFY_IS_APPROX( m1.cwise().min(m2), m2.cwise().min(m1) );\n VERIFY_IS_APPROX( m1.cwise().min(m1+mones), m1 );\n VERIFY_IS_APPROX( m1.cwise().min(m1-mones), m1-mones );\n\n \/\/ check max\n VERIFY_IS_APPROX( m1.cwise().max(m2), m2.cwise().max(m1) );\n VERIFY_IS_APPROX( m1.cwise().max(m1-mones), m1 );\n VERIFY_IS_APPROX( m1.cwise().max(m1+mones), m1+mones );\n\n VERIFY( (m1.cwise() == m1).all() );\n VERIFY( (m1.cwise() != m2).any() );\n VERIFY(!(m1.cwise() == (m1+mones)).any() );\n if (rows*cols>1)\n {\n m3 = m1;\n m3(r,c) += 1;\n VERIFY( (m1.cwise() == m3).any() );\n VERIFY( !(m1.cwise() == m3).all() );\n }\n VERIFY( (m1.cwise().min(m2).cwise() <= m2).all() );\n VERIFY( (m1.cwise().max(m2).cwise() >= m2).all() );\n VERIFY( (m1.cwise().min(m2).cwise() < (m1+mones)).all() );\n VERIFY( (m1.cwise().max(m2).cwise() > (m1-mones)).all() );\n\n VERIFY( (m1.cwise()<m1.unaryExpr(bind2nd(plus<Scalar>(), Scalar(1)))).all() );\n VERIFY( !(m1.cwise()<m1.unaryExpr(bind2nd(minus<Scalar>(), Scalar(1)))).all() );\n VERIFY( !(m1.cwise()>m1.unaryExpr(bind2nd(plus<Scalar>(), Scalar(1)))).any() );\n \n cwiseops_real_only(m1, m2, m3, mones);\n}\n\nvoid test_cwiseop()\n{\n for(int i = 0; i < g_repeat ; i++) {\n CALL_SUBTEST_1( cwiseops(Matrix<float, 1, 1>()) );\n CALL_SUBTEST_2( cwiseops(Matrix4d()) );\n CALL_SUBTEST_3( cwiseops(MatrixXf(internal::random<int>(1,EIGEN_TEST_MAX_SIZE), internal::random<int>(1,EIGEN_TEST_MAX_SIZE))) );\n CALL_SUBTEST_4( cwiseops(MatrixXf(internal::random<int>(1,EIGEN_TEST_MAX_SIZE), internal::random<int>(1,EIGEN_TEST_MAX_SIZE))) );\n CALL_SUBTEST_5( cwiseops(MatrixXi(internal::random<int>(1,EIGEN_TEST_MAX_SIZE), internal::random<int>(1,EIGEN_TEST_MAX_SIZE))) );\n CALL_SUBTEST_6( cwiseops(MatrixXd(internal::random<int>(1,EIGEN_TEST_MAX_SIZE), internal::random<int>(1,EIGEN_TEST_MAX_SIZE))) );\n }\n}\n<commit_msg>Workaround warning: assuming signed overflow does not occur when...<commit_after>\/\/ This file is part of Eigen, a lightweight C++ template library\n\/\/ for linear algebra.\n\/\/\n\/\/ Copyright (C) 2008 Gael Guennebaud <gael.guennebaud@inria.fr>\n\/\/ Copyright (C) 2006-2008 Benoit Jacob <jacob.benoit.1@gmail.com>\n\/\/\n\/\/ This Source Code Form is subject to the terms of the Mozilla\n\/\/ Public License v. 2.0. If a copy of the MPL was not distributed\n\/\/ with this file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n\n#define EIGEN2_SUPPORT\n#define EIGEN_NO_STATIC_ASSERT\n#include \"main.h\"\n#include <functional>\n\n#ifdef min\n#undef min\n#endif\n\n#ifdef max\n#undef max\n#endif\n\nusing namespace std;\n\ntemplate<typename Scalar> struct AddIfNull {\n const Scalar operator() (const Scalar a, const Scalar b) const {return a<=1e-3 ? b : a;}\n enum { Cost = NumTraits<Scalar>::AddCost };\n};\n\ntemplate<typename MatrixType>\ntypename Eigen::internal::enable_if<!NumTraits<typename MatrixType::Scalar>::IsInteger,typename MatrixType::Scalar>::type\ncwiseops_real_only(MatrixType& m1, MatrixType& m2, MatrixType& m3, MatrixType& mones)\n{\n typedef typename MatrixType::Scalar Scalar;\n typedef typename NumTraits<Scalar>::Real RealScalar;\n \n VERIFY_IS_APPROX(m1.cwise() \/ m2, m1.cwise() * (m2.cwise().inverse()));\n m3 = m1.cwise().abs().cwise().sqrt();\n VERIFY_IS_APPROX(m3.cwise().square(), m1.cwise().abs());\n VERIFY_IS_APPROX(m1.cwise().square().cwise().sqrt(), m1.cwise().abs());\n VERIFY_IS_APPROX(m1.cwise().abs().cwise().log().cwise().exp() , m1.cwise().abs());\n\n VERIFY_IS_APPROX(m1.cwise().pow(2), m1.cwise().square());\n m3 = (m1.cwise().abs().cwise()<=RealScalar(0.01)).select(mones,m1);\n VERIFY_IS_APPROX(m3.cwise().pow(-1), m3.cwise().inverse());\n m3 = m1.cwise().abs();\n VERIFY_IS_APPROX(m3.cwise().pow(RealScalar(0.5)), m3.cwise().sqrt());\n\n\/\/ VERIFY_IS_APPROX(m1.cwise().tan(), m1.cwise().sin().cwise() \/ m1.cwise().cos());\n VERIFY_IS_APPROX(mones, m1.cwise().sin().cwise().square() + m1.cwise().cos().cwise().square());\n m3 = m1;\n m3.cwise() \/= m2;\n VERIFY_IS_APPROX(m3, m1.cwise() \/ m2);\n \n return Scalar(0);\n}\n\ntemplate<typename MatrixType>\ntypename Eigen::internal::enable_if<NumTraits<typename MatrixType::Scalar>::IsInteger,typename MatrixType::Scalar>::type\ncwiseops_real_only(MatrixType& , MatrixType& , MatrixType& , MatrixType& )\n{\n typedef typename MatrixType::Scalar Scalar;\n return 0;\n}\n\ntemplate<typename MatrixType> void cwiseops(const MatrixType& m)\n{\n typedef typename MatrixType::Index Index;\n typedef typename MatrixType::Scalar Scalar;\n typedef typename NumTraits<Scalar>::Real RealScalar;\n typedef Matrix<Scalar, MatrixType::RowsAtCompileTime, 1> VectorType;\n\n Index rows = m.rows();\n Index cols = m.cols();\n\n MatrixType m1 = MatrixType::Random(rows, cols),\n m1bis = m1,\n m2 = MatrixType::Random(rows, cols),\n m3(rows, cols),\n m4(rows, cols),\n mzero = MatrixType::Zero(rows, cols),\n mones = MatrixType::Ones(rows, cols),\n identity = Matrix<Scalar, MatrixType::RowsAtCompileTime, MatrixType::RowsAtCompileTime>\n ::Identity(rows, rows);\n VectorType vzero = VectorType::Zero(rows),\n vones = VectorType::Ones(rows),\n v3(rows);\n\n Index r = internal::random<Index>(0, rows-1),\n c = internal::random<Index>(0, cols-1);\n\n Scalar s1 = internal::random<Scalar>();\n\n \/\/ test Zero, Ones, Constant, and the set* variants\n m3 = MatrixType::Constant(rows, cols, s1);\n for (int j=0; j<cols; ++j)\n for (int i=0; i<rows; ++i)\n {\n VERIFY_IS_APPROX(mzero(i,j), Scalar(0));\n VERIFY_IS_APPROX(mones(i,j), Scalar(1));\n VERIFY_IS_APPROX(m3(i,j), s1);\n }\n VERIFY(mzero.isZero());\n VERIFY(mones.isOnes());\n VERIFY(m3.isConstant(s1));\n VERIFY(identity.isIdentity());\n VERIFY_IS_APPROX(m4.setConstant(s1), m3);\n VERIFY_IS_APPROX(m4.setConstant(rows,cols,s1), m3);\n VERIFY_IS_APPROX(m4.setZero(), mzero);\n VERIFY_IS_APPROX(m4.setZero(rows,cols), mzero);\n VERIFY_IS_APPROX(m4.setOnes(), mones);\n VERIFY_IS_APPROX(m4.setOnes(rows,cols), mones);\n m4.fill(s1);\n VERIFY_IS_APPROX(m4, m3);\n\n VERIFY_IS_APPROX(v3.setConstant(rows, s1), VectorType::Constant(rows,s1));\n VERIFY_IS_APPROX(v3.setZero(rows), vzero);\n VERIFY_IS_APPROX(v3.setOnes(rows), vones);\n\n m2 = m2.template binaryExpr<AddIfNull<Scalar> >(mones);\n\n VERIFY_IS_APPROX(m1.cwise().pow(2), m1.cwise().abs2());\n VERIFY_IS_APPROX(m1.cwise().pow(2), m1.cwise().square());\n VERIFY_IS_APPROX(m1.cwise().pow(3), m1.cwise().cube());\n\n VERIFY_IS_APPROX(m1 + mones, m1.cwise()+Scalar(1));\n VERIFY_IS_APPROX(m1 - mones, m1.cwise()-Scalar(1));\n m3 = m1; m3.cwise() += 1;\n VERIFY_IS_APPROX(m1 + mones, m3);\n m3 = m1; m3.cwise() -= 1;\n VERIFY_IS_APPROX(m1 - mones, m3);\n\n VERIFY_IS_APPROX(m2, m2.cwise() * mones);\n VERIFY_IS_APPROX(m1.cwise() * m2, m2.cwise() * m1);\n m3 = m1;\n m3.cwise() *= m2;\n VERIFY_IS_APPROX(m3, m1.cwise() * m2);\n\n VERIFY_IS_APPROX(mones, m2.cwise()\/m2);\n\n \/\/ check min\n VERIFY_IS_APPROX( m1.cwise().min(m2), m2.cwise().min(m1) );\n VERIFY_IS_APPROX( m1.cwise().min(m1+mones), m1 );\n VERIFY_IS_APPROX( m1.cwise().min(m1-mones), m1-mones );\n\n \/\/ check max\n VERIFY_IS_APPROX( m1.cwise().max(m2), m2.cwise().max(m1) );\n VERIFY_IS_APPROX( m1.cwise().max(m1-mones), m1 );\n VERIFY_IS_APPROX( m1.cwise().max(m1+mones), m1+mones );\n\n VERIFY( (m1.cwise() == m1).all() );\n VERIFY( (m1.cwise() != m2).any() );\n VERIFY(!(m1.cwise() == (m1+mones)).any() );\n if (rows*cols>1)\n {\n m3 = m1;\n m3(r,c) += 1;\n VERIFY( (m1.cwise() == m3).any() );\n VERIFY( !(m1.cwise() == m3).all() );\n }\n VERIFY( (m1.cwise().min(m2).cwise() <= m2).all() );\n VERIFY( (m1.cwise().max(m2).cwise() >= m2).all() );\n VERIFY( (m1.cwise().min(m2).cwise() < (m1+mones)).all() );\n VERIFY( (m1.cwise().max(m2).cwise() > (m1-mones)).all() );\n\n VERIFY( (m1.cwise()<m1.unaryExpr(bind2nd(plus<Scalar>(), Scalar(1)))).all() );\n VERIFY( !(m1.cwise()<m1bis.unaryExpr(bind2nd(minus<Scalar>(), Scalar(1)))).all() );\n VERIFY( !(m1.cwise()>m1bis.unaryExpr(bind2nd(plus<Scalar>(), Scalar(1)))).any() );\n \n cwiseops_real_only(m1, m2, m3, mones);\n}\n\nvoid test_cwiseop()\n{\n for(int i = 0; i < g_repeat ; i++) {\n CALL_SUBTEST_1( cwiseops(Matrix<float, 1, 1>()) );\n CALL_SUBTEST_2( cwiseops(Matrix4d()) );\n CALL_SUBTEST_3( cwiseops(MatrixXf(internal::random<int>(1,EIGEN_TEST_MAX_SIZE), internal::random<int>(1,EIGEN_TEST_MAX_SIZE))) );\n CALL_SUBTEST_4( cwiseops(MatrixXf(internal::random<int>(1,EIGEN_TEST_MAX_SIZE), internal::random<int>(1,EIGEN_TEST_MAX_SIZE))) );\n CALL_SUBTEST_5( cwiseops(MatrixXi(internal::random<int>(1,EIGEN_TEST_MAX_SIZE), internal::random<int>(1,EIGEN_TEST_MAX_SIZE))) );\n CALL_SUBTEST_6( cwiseops(MatrixXd(internal::random<int>(1,EIGEN_TEST_MAX_SIZE), internal::random<int>(1,EIGEN_TEST_MAX_SIZE))) );\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright 2007-2017 Content Management AG\n * All rights reserved.\n *\n * author: Max Kellermann <mk@cm4all.com>\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * - Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n *\n * - Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the\n * distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,\n * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED\n * OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \"was\/Client.hxx\"\n#include \"was\/Launch.hxx\"\n#include \"was\/Lease.hxx\"\n#include \"stopwatch.hxx\"\n#include \"lease.hxx\"\n#include \"HttpResponseHandler.hxx\"\n#include \"direct.hxx\"\n#include \"strmap.hxx\"\n#include \"istream\/Handler.hxx\"\n#include \"istream\/Pointer.hxx\"\n#include \"istream\/UnusedPtr.hxx\"\n#include \"istream\/FileIstream.hxx\"\n#include \"fb_pool.hxx\"\n#include \"PInstance.hxx\"\n#include \"spawn\/Config.hxx\"\n#include \"spawn\/ChildOptions.hxx\"\n#include \"spawn\/Registry.hxx\"\n#include \"spawn\/Local.hxx\"\n#include \"io\/Logger.hxx\"\n#include \"util\/ConstBuffer.hxx\"\n#include \"util\/Cancellable.hxx\"\n#include \"util\/PrintException.hxx\"\n#include \"util\/StaticArray.hxx\"\n\n#include <sys\/types.h>\n#include <sys\/stat.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <unistd.h>\n#include <signal.h>\n\nstruct Context final\n : PInstance, WasLease, IstreamHandler, HttpResponseHandler {\n\n WasProcess process;\n\n IstreamPointer body;\n bool error;\n\n CancellablePointer cancel_ptr;\n\n Context():body(nullptr) {}\n\n \/* virtual methods from class IstreamHandler *\/\n\n size_t OnData(const void *data, size_t length) noexcept override;\n\n void OnEof() noexcept override {\n body.Clear();\n }\n\n void OnError(std::exception_ptr ep) noexcept override {\n PrintException(ep);\n\n body.Clear();\n error = true;\n }\n\n \/* virtual methods from class Lease *\/\n void ReleaseWas(gcc_unused bool reuse) override {\n kill(process.pid, SIGTERM);\n\n process.Close();\n }\n\n void ReleaseWasStop(gcc_unused uint64_t input_received) override {\n ReleaseWas(false);\n }\n\n \/* virtual methods from class HttpResponseHandler *\/\n void OnHttpResponse(http_status_t status, StringMap &&headers,\n UnusedIstreamPtr body) noexcept override;\n void OnHttpError(std::exception_ptr ep) noexcept override;\n};\n\n\/*\n * istream handler\n *\n *\/\n\nsize_t\nContext::OnData(const void *data, size_t length) noexcept\n{\n ssize_t nbytes = write(1, data, length);\n if (nbytes <= 0) {\n error = true;\n body.ClearAndClose();\n return 0;\n }\n\n return (size_t)nbytes;\n}\n\n\/*\n * http_response_handler\n *\n *\/\n\nvoid\nContext::OnHttpResponse(http_status_t status,\n gcc_unused StringMap &&headers,\n UnusedIstreamPtr _body) noexcept\n{\n fprintf(stderr, \"status: %s\\n\", http_status_to_string(status));\n\n if (_body)\n body.Set(std::move(_body), *this);\n}\n\nvoid\nContext::OnHttpError(std::exception_ptr ep) noexcept\n{\n PrintException(ep);\n\n error = true;\n}\n\nstatic Istream *\nrequest_body(EventLoop &event_loop, struct pool &pool)\n{\n struct stat st;\n return fstat(0, &st) == 0 && S_ISREG(st.st_mode)\n ? istream_file_fd_new(event_loop, pool,\n \"\/dev\/stdin\", UniqueFileDescriptor(STDIN_FILENO),\n FdType::FD_FILE, -1)\n : nullptr;\n}\n\nint\nmain(int argc, char **argv)\ntry {\n SetLogLevel(5);\n\n StaticArray<const char *, 64> params;\n\n if (argc < 3) {\n fprintf(stderr, \"Usage: run_was PATH URI [--parameter a=b ...]\\n\");\n return EXIT_FAILURE;\n }\n\n const char *uri = argv[2];\n\n for (int i = 3; i < argc;) {\n if (strcmp(argv[i], \"--parameter\") == 0 ||\n strcmp(argv[i], \"-p\") == 0) {\n ++i;\n if (i >= argc)\n throw std::runtime_error(\"Parameter value missing\");\n\n if (params.full())\n throw std::runtime_error(\"Too many parameters\");\n\n params.push_back(argv[i++]);\n } else\n throw std::runtime_error(\"Unrecognized parameter\");\n }\n\n direct_global_init();\n\n SpawnConfig spawn_config;\n\n const ScopeFbPoolInit fb_pool_init;\n\n ChildOptions child_options;\n\n Context context;\n ChildProcessRegistry child_process_registry(context.event_loop);\n child_process_registry.SetVolatile();\n LocalSpawnService spawn_service(spawn_config, child_process_registry);\n\n context.process = was_launch(spawn_service, \"was\",\n argv[1], nullptr,\n child_options, {}, nullptr);\n\n was_client_request(context.root_pool, context.event_loop, nullptr,\n context.process.control,\n context.process.input,\n context.process.output,\n context,\n HTTP_METHOD_GET, uri,\n nullptr,\n nullptr, nullptr,\n *strmap_new(context.root_pool),\n UnusedIstreamPtr(request_body(context.event_loop,\n context.root_pool)),\n { (const char *const*)params.raw(), params.size() },\n context, context.cancel_ptr);\n\n context.event_loop.Dispatch();\n\n return context.error;\n} catch (const std::exception &e) {\n PrintException(e);\n return EXIT_FAILURE;\n}\n<commit_msg>test\/run_was: use sink_fd instead of rolling our own IstreamHandler<commit_after>\/*\n * Copyright 2007-2017 Content Management AG\n * All rights reserved.\n *\n * author: Max Kellermann <mk@cm4all.com>\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * - Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n *\n * - Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the\n * distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,\n * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED\n * OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \"was\/Client.hxx\"\n#include \"was\/Launch.hxx\"\n#include \"was\/Lease.hxx\"\n#include \"stopwatch.hxx\"\n#include \"lease.hxx\"\n#include \"HttpResponseHandler.hxx\"\n#include \"direct.hxx\"\n#include \"strmap.hxx\"\n#include \"istream\/sink_fd.hxx\"\n#include \"istream\/Pointer.hxx\"\n#include \"istream\/UnusedPtr.hxx\"\n#include \"istream\/FileIstream.hxx\"\n#include \"fb_pool.hxx\"\n#include \"PInstance.hxx\"\n#include \"spawn\/Config.hxx\"\n#include \"spawn\/ChildOptions.hxx\"\n#include \"spawn\/Registry.hxx\"\n#include \"spawn\/Local.hxx\"\n#include \"io\/Logger.hxx\"\n#include \"util\/ConstBuffer.hxx\"\n#include \"util\/Cancellable.hxx\"\n#include \"util\/PrintException.hxx\"\n#include \"util\/StaticArray.hxx\"\n\n#include <sys\/types.h>\n#include <sys\/stat.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <unistd.h>\n#include <signal.h>\n\nstruct Context final\n : PInstance, WasLease, HttpResponseHandler {\n\n WasProcess process;\n\n SinkFd *body = nullptr;\n bool error;\n\n CancellablePointer cancel_ptr;\n\n Context():body(nullptr) {}\n\n \/* virtual methods from class Lease *\/\n void ReleaseWas(gcc_unused bool reuse) override {\n kill(process.pid, SIGTERM);\n\n process.Close();\n }\n\n void ReleaseWasStop(gcc_unused uint64_t input_received) override {\n ReleaseWas(false);\n }\n\n \/* virtual methods from class HttpResponseHandler *\/\n void OnHttpResponse(http_status_t status, StringMap &&headers,\n UnusedIstreamPtr body) noexcept override;\n void OnHttpError(std::exception_ptr ep) noexcept override;\n};\n\n\/*\n * SinkFdHandler\n *\n *\/\n\nstatic void\nmy_sink_fd_input_eof(void *ctx)\n{\n auto &c = *(Context *)ctx;\n\n c.body = nullptr;\n}\n\nstatic void\nmy_sink_fd_input_error(std::exception_ptr ep, void *ctx)\n{\n auto &c = *(Context *)ctx;\n\n PrintException(ep);\n\n c.body = nullptr;\n c.error = true;\n}\n\nstatic bool\nmy_sink_fd_send_error(int error, void *ctx)\n{\n auto &c = *(Context *)ctx;\n\n fprintf(stderr, \"%s\\n\", strerror(error));\n\n c.body = nullptr;\n c.error = true;\n\n return true;\n}\n\nstatic constexpr SinkFdHandler my_sink_fd_handler = {\n .input_eof = my_sink_fd_input_eof,\n .input_error = my_sink_fd_input_error,\n .send_error = my_sink_fd_send_error,\n};\n\n\n\/*\n * http_response_handler\n *\n *\/\n\nvoid\nContext::OnHttpResponse(http_status_t status,\n gcc_unused StringMap &&headers,\n UnusedIstreamPtr _body) noexcept\n{\n fprintf(stderr, \"status: %s\\n\", http_status_to_string(status));\n\n if (_body) {\n struct pool &pool = root_pool;\n body = sink_fd_new(event_loop, pool,\n std::move(_body),\n FileDescriptor(STDOUT_FILENO),\n guess_fd_type(STDOUT_FILENO),\n my_sink_fd_handler, this);\n sink_fd_read(body);\n }\n}\n\nvoid\nContext::OnHttpError(std::exception_ptr ep) noexcept\n{\n PrintException(ep);\n\n error = true;\n}\n\nstatic Istream *\nrequest_body(EventLoop &event_loop, struct pool &pool)\n{\n struct stat st;\n return fstat(0, &st) == 0 && S_ISREG(st.st_mode)\n ? istream_file_fd_new(event_loop, pool,\n \"\/dev\/stdin\", UniqueFileDescriptor(STDIN_FILENO),\n FdType::FD_FILE, -1)\n : nullptr;\n}\n\nint\nmain(int argc, char **argv)\ntry {\n SetLogLevel(5);\n\n StaticArray<const char *, 64> params;\n\n if (argc < 3) {\n fprintf(stderr, \"Usage: run_was PATH URI [--parameter a=b ...]\\n\");\n return EXIT_FAILURE;\n }\n\n const char *uri = argv[2];\n\n for (int i = 3; i < argc;) {\n if (strcmp(argv[i], \"--parameter\") == 0 ||\n strcmp(argv[i], \"-p\") == 0) {\n ++i;\n if (i >= argc)\n throw std::runtime_error(\"Parameter value missing\");\n\n if (params.full())\n throw std::runtime_error(\"Too many parameters\");\n\n params.push_back(argv[i++]);\n } else\n throw std::runtime_error(\"Unrecognized parameter\");\n }\n\n direct_global_init();\n\n SpawnConfig spawn_config;\n\n const ScopeFbPoolInit fb_pool_init;\n\n ChildOptions child_options;\n\n Context context;\n ChildProcessRegistry child_process_registry(context.event_loop);\n child_process_registry.SetVolatile();\n LocalSpawnService spawn_service(spawn_config, child_process_registry);\n\n context.process = was_launch(spawn_service, \"was\",\n argv[1], nullptr,\n child_options, {}, nullptr);\n\n was_client_request(context.root_pool, context.event_loop, nullptr,\n context.process.control,\n context.process.input,\n context.process.output,\n context,\n HTTP_METHOD_GET, uri,\n nullptr,\n nullptr, nullptr,\n *strmap_new(context.root_pool),\n UnusedIstreamPtr(request_body(context.event_loop,\n context.root_pool)),\n { (const char *const*)params.raw(), params.size() },\n context, context.cancel_ptr);\n\n context.event_loop.Dispatch();\n\n return context.error;\n} catch (const std::exception &e) {\n PrintException(e);\n return EXIT_FAILURE;\n}\n<|endoftext|>"} {"text":"<commit_before>#ifndef STAN_MATH_PRIM_FUN_LOG_SUM_EXP_SIGNED_HPP\n#define STAN_MATH_PRIM_FUN_LOG_SUM_EXP_SIGNED_HPP\n\n#include <stan\/math\/prim\/meta.hpp>\n#include <stan\/math\/prim\/fun\/constants.hpp>\n#include <stan\/math\/prim\/fun\/Eigen.hpp>\n#include <stan\/math\/prim\/fun\/log1p_exp.hpp>\n#include <cmath>\n#include <vector>\n\nnamespace stan {\nnamespace math {\n\ntemplate <typename T1, typename T2,\n require_all_stan_scalar_t<T1, T2>* = nullptr>\ninline std::tuple<return_type_t<T1, T2>, int>\n log_sum_exp_signed(const T1& a, int a_sign, const T2& b, int b_sign) {\n if (a_sign == b_sign) {\n return std::make_tuple(log_sum_exp(a, b), a_sign);\n }\n bool a_larger = (value_of_rec(a) > value_of_rec(b));\n return std::make_tuple(\n a_larger ? log_diff_exp(a, b) : log_diff_exp(b, a),\n a_larger ? a_sign : b_sign);\n}\n\n} \/\/ namespace math\n} \/\/ namespace stan\n\n#endif\n<commit_msg>Update doc<commit_after>#ifndef STAN_MATH_PRIM_FUN_LOG_SUM_EXP_SIGNED_HPP\n#define STAN_MATH_PRIM_FUN_LOG_SUM_EXP_SIGNED_HPP\n\n#include <stan\/math\/prim\/meta.hpp>\n#include <stan\/math\/prim\/fun\/constants.hpp>\n#include <stan\/math\/prim\/fun\/Eigen.hpp>\n#include <stan\/math\/prim\/fun\/log1p_exp.hpp>\n#include <cmath>\n#include <vector>\n\nnamespace stan {\nnamespace math {\n\n\/**\n * Calculates the log sum of exponentials without overflow,\n * accounting for the signs of the inputs\n *\n * @tparam T1 type of the first variable\n * @tparam T2 type of the second variable\n * @param a the first variable\n * @param a_sign sign of the first variable\n * @param b the second variable\n * @param b_sign sign of the second variable\n *\/\ntemplate <typename T1, typename T2,\n require_all_stan_scalar_t<T1, T2>* = nullptr>\ninline std::tuple<return_type_t<T1, T2>, int>\n log_sum_exp_signed(const T1& a, int a_sign, const T2& b, int b_sign) {\n if (a_sign == b_sign) {\n return std::make_tuple(log_sum_exp(a, b), a_sign);\n }\n bool a_larger = (a > b);\n return std::make_tuple(\n a_larger ? log_diff_exp(a, b) : log_diff_exp(b, a),\n a_larger ? a_sign : b_sign);\n}\n\n} \/\/ namespace math\n} \/\/ namespace stan\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>#include <stan\/math\/prim\/scal.hpp>\n#include <test\/unit\/util.hpp>\n#include <gtest\/gtest.h>\n#include <limits>\n\nTEST(prob_transform, locscale) {\n EXPECT_FLOAT_EQ(2.0 - 5.0 * 1.0,\n stan::math::locscale_constrain(-1.0, 2.0, 5.0));\n\n EXPECT_FLOAT_EQ(1.7, stan::math::locscale_constrain(\n 1.7, 0,\n 1));\n}\nTEST(prob_transform, locscale_j) {\n double lp = -17.0;\n double L = 2.0;\n double U = 5.0;\n double x = -1.0;\n EXPECT_FLOAT_EQ(L + U * x,\n stan::math::locscale_constrain(x, L, U, lp));\n EXPECT_FLOAT_EQ(-17.0 + log(U),\n lp);\n\n double lp1 = -12.9;\n EXPECT_FLOAT_EQ(1.7, stan::math::locscale_constrain(\n 1.7, 0, 1, lp1));\n EXPECT_FLOAT_EQ(-12.9, lp1);\n}\nTEST(ProbTransform, locscaleException) {\n using stan::math::locscale_constrain;\n EXPECT_THROW(locscale_constrain(5.0, 1.0, 0.0), std::domain_error);\n EXPECT_NO_THROW(locscale_constrain(5.0, 1.0, 0.01));\n double lp = 12;\n EXPECT_THROW(locscale_constrain(5.0, 1.0, 0.0, lp), std::domain_error);\n EXPECT_NO_THROW(locscale_constrain(5.0, 1.0, 0.01, lp));\n}\nTEST(prob_transform, locscale_f) {\n double L = -10.0;\n double U = 27.0;\n double y = 3.0;\n EXPECT_FLOAT_EQ(y,\n stan::math::locscale_constrain(\n stan::math::locscale_free(y, L, U), L, U));\n EXPECT_FLOAT_EQ(y,\n stan::math::locscale_free(\n stan::math::locscale_constrain(y, L, U), L, U));\n L = 0.0;\n U = 1.0;\n y = 3.0;\n EXPECT_FLOAT_EQ(y,\n stan::math::locscale_constrain(\n stan::math::locscale_free(y, L, U), L, U));\n EXPECT_FLOAT_EQ(y,\n stan::math::locscale_free(\n stan::math::locscale_constrain(y, L, U), L, U));\n}\nTEST(prob_transform, locscale_f_exception) {\n double L = -10.0;\n double U = -27.0;\n EXPECT_THROW(stan::math::locscale_free(L - 0.01, L, U), std::domain_error);\n}\n<commit_msg>[Jenkins] auto-formatting by clang-format version 5.0.0-3~16.04.1 (tags\/RELEASE_500\/final)<commit_after>#include <stan\/math\/prim\/scal.hpp>\n#include <test\/unit\/util.hpp>\n#include <gtest\/gtest.h>\n#include <limits>\n\nTEST(prob_transform, locscale) {\n EXPECT_FLOAT_EQ(2.0 - 5.0 * 1.0,\n stan::math::locscale_constrain(-1.0, 2.0, 5.0));\n\n EXPECT_FLOAT_EQ(1.7, stan::math::locscale_constrain(1.7, 0, 1));\n}\nTEST(prob_transform, locscale_j) {\n double lp = -17.0;\n double L = 2.0;\n double U = 5.0;\n double x = -1.0;\n EXPECT_FLOAT_EQ(L + U * x, stan::math::locscale_constrain(x, L, U, lp));\n EXPECT_FLOAT_EQ(-17.0 + log(U), lp);\n\n double lp1 = -12.9;\n EXPECT_FLOAT_EQ(1.7, stan::math::locscale_constrain(1.7, 0, 1, lp1));\n EXPECT_FLOAT_EQ(-12.9, lp1);\n}\nTEST(ProbTransform, locscaleException) {\n using stan::math::locscale_constrain;\n EXPECT_THROW(locscale_constrain(5.0, 1.0, 0.0), std::domain_error);\n EXPECT_NO_THROW(locscale_constrain(5.0, 1.0, 0.01));\n double lp = 12;\n EXPECT_THROW(locscale_constrain(5.0, 1.0, 0.0, lp), std::domain_error);\n EXPECT_NO_THROW(locscale_constrain(5.0, 1.0, 0.01, lp));\n}\nTEST(prob_transform, locscale_f) {\n double L = -10.0;\n double U = 27.0;\n double y = 3.0;\n EXPECT_FLOAT_EQ(y, stan::math::locscale_constrain(\n stan::math::locscale_free(y, L, U), L, U));\n EXPECT_FLOAT_EQ(y, stan::math::locscale_free(\n stan::math::locscale_constrain(y, L, U), L, U));\n L = 0.0;\n U = 1.0;\n y = 3.0;\n EXPECT_FLOAT_EQ(y, stan::math::locscale_constrain(\n stan::math::locscale_free(y, L, U), L, U));\n EXPECT_FLOAT_EQ(y, stan::math::locscale_free(\n stan::math::locscale_constrain(y, L, U), L, U));\n}\nTEST(prob_transform, locscale_f_exception) {\n double L = -10.0;\n double U = -27.0;\n EXPECT_THROW(stan::math::locscale_free(L - 0.01, L, U), std::domain_error);\n}\n<|endoftext|>"} {"text":"<commit_before>#include <limits.h>\n#include <iostream>\n#include <fstream>\n#include <set>\n#include <utility>\n#include \"pt.h\"\n#include \"species.h\"\n#include \"stratum.h\"\n#include \"forest.h\"\n#include \"location.h\"\n#include \"ffm_io.h\"\n#include \"layer.h\"\n#include \"ffm_settings.h\"\n#include \"ffm_util.h\"\n\nusing namespace ffm_settings;\nusing std::vector;\nusing std::set;\nusing std::cout;\nusing std::endl;\n\nvoid process(std::string inPath, std::ostream &outputStream, bool paramsFlag) {\n\n std::pair<Results::OutputLevelType, int> prelimPars = prelimParseInputTextFile(inPath);\n\n Results::OutputLevelType outputLevel = std::get<0>(prelimPars);\n int numIter = std::get<1>(prelimPars);\n \n bool monteCarlo = (outputLevel == Results::MONTE_CARLO);\n \n if (!monteCarlo) {\n Location loc = parseInputTextFile(inPath, false);\n\n if (paramsFlag) \n outputStream << loc.printToString() << endl;\n \n Results res = loc.results();\n\n outputStream << res.printToString(outputLevel) << endl;\n }\n else {\n for (int i = 0; i < numIter; ) {\n Location loc = parseInputTextFile(inPath, true);\n\n if (!loc.empty()) {\n if (i == 0) outputStream << printMonteCarloHeader(loc);\n\n Results res = loc.results();\n\n outputStream << printMonteCarloInputs(loc);\n outputStream << printMonteCarloResults(res) << endl;\n\n i++ ;\n }\n }\n }\n\n}\n\nint main(int argc, char *argv[]) {\n std::string usage(\"usage: ffm input_file [output_file] [-p]\"); \n\n if (argc < 2) {\n cout << usage << endl;\n return 0;\n }\n\n \/\/ collect the inPath and the optional outPath and flag arguments\n bool paramsFlag;\n std::string flag_str(\"-p\");\n std::string inPath;\n std::string outPath;\n\n for (int i = 1; i < argc; i++) {\n std::string arg( argv[i] );\n\n if (arg.compare(0, flag_str.size(), flag_str) == 0)\n paramsFlag = true;\n else if (inPath.empty())\n inPath = arg;\n else if (outPath.empty())\n outPath = arg;\n }\n\n if (inPath.empty()) {\n cout << usage << endl;\n return 0;\n }\n\n std::ostream* fp = &cout;\n std::ofstream fout;\n if( !outPath.empty()) {\n fout.open(outPath); \n fp = &fout;\n }\n\n process(inPath, *fp, paramsFlag);\n if (!outPath.empty()) fout.close();\n\n return 0;\n}\n\n<commit_msg>Added -d command line flag. When this is supplied, and it is a monte-carlo run, the program writes the current generated parameters to the file debug_mc_params.csv before processing that iteration.<commit_after>#include <limits.h>\n#include <iostream>\n#include <fstream>\n#include <set>\n#include <utility>\n#include \"pt.h\"\n#include \"species.h\"\n#include \"stratum.h\"\n#include \"forest.h\"\n#include \"location.h\"\n#include \"ffm_io.h\"\n#include \"layer.h\"\n#include \"ffm_settings.h\"\n#include \"ffm_util.h\"\n\nusing namespace ffm_settings;\nusing std::vector;\nusing std::set;\nusing std::cout;\nusing std::endl;\n\nvoid process(std::string inPath, std::ostream &outputStream, bool paramsFlag, bool debugFlag) {\n\n std::pair<Results::OutputLevelType, int> prelimPars = prelimParseInputTextFile(inPath);\n\n Results::OutputLevelType outputLevel = std::get<0>(prelimPars);\n int numIter = std::get<1>(prelimPars);\n \n bool monteCarlo = (outputLevel == Results::MONTE_CARLO);\n \n if (!monteCarlo) {\n Location loc = parseInputTextFile(inPath, false);\n\n if (paramsFlag) \n outputStream << loc.printToString() << endl;\n \n Results res = loc.results();\n\n outputStream << res.printToString(outputLevel) << endl;\n }\n else {\n for (int i = 0; i < numIter; ) {\n Location loc = parseInputTextFile(inPath, true);\n\n if (!loc.empty()) {\n if (i == 0) outputStream << printMonteCarloHeader(loc);\n\n Results res = loc.results();\n\n outputStream << printMonteCarloInputs(loc);\n\n if (debugFlag) {\n std::ofstream debugstrm(\"debug_mc_params.csv\", std::ofstream::out);\n debugstrm << printMonteCarloHeader(loc);\n debugstrm << printMonteCarloInputs(loc);\n debugstrm.close();\n }\n\n outputStream << printMonteCarloResults(res) << endl;\n\n i++ ;\n }\n }\n }\n\n}\n\nint main(int argc, char *argv[]) {\n std::string usage(\"usage: ffm input_file [output_file] [-p] [-d]\"); \n\n if (argc < 2) {\n cout << usage << endl;\n return 0;\n }\n\n \/\/ collect the inPath and the optional outPath and flag arguments\n bool paramsFlag = false;\n bool debugFlag = false;\n std::string params_flag_str(\"-p\");\n std::string debug_flag_str(\"-d\");\n std::string inPath;\n std::string outPath;\n\n for (int i = 1; i < argc; i++) {\n std::string arg( argv[i] );\n\n if (arg.compare(0, params_flag_str.size(), params_flag_str) == 0)\n paramsFlag = true;\n else if (arg.compare(0, debug_flag_str.size(), debug_flag_str) == 0)\n debugFlag = true;\n else if (inPath.empty())\n inPath = arg;\n else if (outPath.empty())\n outPath = arg;\n }\n\n if (inPath.empty()) {\n cout << usage << endl;\n return 0;\n }\n\n std::ostream* fp = &cout;\n std::ofstream fout;\n if( !outPath.empty()) {\n fout.open(outPath); \n fp = &fout;\n }\n\n process(inPath, *fp, paramsFlag, debugFlag);\n if (!outPath.empty()) fout.close();\n\n return 0;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2014 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"ui\/events\/ozone\/evdev\/touch_event_converter_evdev.h\"\n\n#include <errno.h>\n#include <fcntl.h>\n#include <linux\/input.h>\n#include <poll.h>\n#include <stdio.h>\n#include <unistd.h>\n\n#include <cmath>\n#include <limits>\n\n#include \"base\/bind.h\"\n#include \"base\/callback.h\"\n#include \"base\/command_line.h\"\n#include \"base\/logging.h\"\n#include \"base\/memory\/scoped_vector.h\"\n#include \"base\/message_loop\/message_loop.h\"\n#include \"base\/strings\/string_number_conversions.h\"\n#include \"base\/strings\/string_util.h\"\n#include \"base\/strings\/stringprintf.h\"\n#include \"ui\/events\/devices\/device_data_manager.h\"\n#include \"ui\/events\/devices\/device_util_linux.h\"\n#include \"ui\/events\/event.h\"\n#include \"ui\/events\/event_constants.h\"\n#include \"ui\/events\/event_switches.h\"\n#include \"ui\/events\/ozone\/evdev\/device_event_dispatcher_evdev.h\"\n#include \"ui\/events\/ozone\/evdev\/touch_evdev_types.h\"\n#include \"ui\/events\/ozone\/evdev\/touch_noise\/touch_noise_finder.h\"\n\nnamespace {\n\nconst int kMaxTrackingId = 0xffff; \/\/ TRKID_MAX in kernel.\n\nstruct TouchCalibration {\n int bezel_left;\n int bezel_right;\n int bezel_top;\n int bezel_bottom;\n};\n\nvoid GetTouchCalibration(TouchCalibration* cal) {\n std::vector<std::string> parts;\n if (Tokenize(base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII(\n switches::kTouchCalibration),\n \",\", &parts) >= 4) {\n if (!base::StringToInt(parts[0], &cal->bezel_left))\n LOG(ERROR) << \"Incorrect left border calibration value passed.\";\n if (!base::StringToInt(parts[1], &cal->bezel_right))\n LOG(ERROR) << \"Incorrect right border calibration value passed.\";\n if (!base::StringToInt(parts[2], &cal->bezel_top))\n LOG(ERROR) << \"Incorrect top border calibration value passed.\";\n if (!base::StringToInt(parts[3], &cal->bezel_bottom))\n LOG(ERROR) << \"Incorrect bottom border calibration value passed.\";\n }\n}\n\nint32_t AbsCodeToMtCode(int32_t code) {\n switch (code) {\n case ABS_X:\n return ABS_MT_POSITION_X;\n case ABS_Y:\n return ABS_MT_POSITION_Y;\n case ABS_PRESSURE:\n return ABS_MT_PRESSURE;\n case ABS_DISTANCE:\n return ABS_MT_DISTANCE;\n default:\n return -1;\n }\n}\n\n} \/\/ namespace\n\nnamespace ui {\n\nTouchEventConverterEvdev::TouchEventConverterEvdev(\n int fd,\n base::FilePath path,\n int id,\n InputDeviceType type,\n const EventDeviceInfo& devinfo,\n DeviceEventDispatcherEvdev* dispatcher)\n : EventConverterEvdev(fd,\n path,\n id,\n type,\n devinfo.name(),\n devinfo.vendor_id(),\n devinfo.product_id()),\n dispatcher_(dispatcher),\n syn_dropped_(false),\n has_mt_(false),\n touch_points_(0),\n next_tracking_id_(0),\n current_slot_(0) {\n if (base::CommandLine::ForCurrentProcess()->HasSwitch(\n switches::kExtraTouchNoiseFiltering)) {\n touch_noise_finder_.reset(new TouchNoiseFinder);\n }\n}\n\nTouchEventConverterEvdev::~TouchEventConverterEvdev() {\n Stop();\n close(fd_);\n}\n\nvoid TouchEventConverterEvdev::Initialize(const EventDeviceInfo& info) {\n has_mt_ = info.HasMultitouch();\n\n if (has_mt_) {\n pressure_min_ = info.GetAbsMinimum(ABS_MT_PRESSURE);\n pressure_max_ = info.GetAbsMaximum(ABS_MT_PRESSURE);\n x_min_tuxels_ = info.GetAbsMinimum(ABS_MT_POSITION_X);\n x_num_tuxels_ = info.GetAbsMaximum(ABS_MT_POSITION_X) - x_min_tuxels_ + 1;\n y_min_tuxels_ = info.GetAbsMinimum(ABS_MT_POSITION_Y);\n y_num_tuxels_ = info.GetAbsMaximum(ABS_MT_POSITION_Y) - y_min_tuxels_ + 1;\n touch_points_ =\n std::min<int>(info.GetAbsMaximum(ABS_MT_SLOT) + 1, kNumTouchEvdevSlots);\n current_slot_ = info.GetAbsValue(ABS_MT_SLOT);\n } else {\n pressure_min_ = info.GetAbsMinimum(ABS_PRESSURE);\n pressure_max_ = info.GetAbsMaximum(ABS_PRESSURE);\n x_min_tuxels_ = info.GetAbsMinimum(ABS_X);\n x_num_tuxels_ = info.GetAbsMaximum(ABS_X) - x_min_tuxels_ + 1;\n y_min_tuxels_ = info.GetAbsMinimum(ABS_Y);\n y_num_tuxels_ = info.GetAbsMaximum(ABS_Y) - y_min_tuxels_ + 1;\n touch_points_ = 1;\n current_slot_ = 0;\n }\n\n \/\/ Apply --touch-calibration.\n if (type() == INPUT_DEVICE_INTERNAL) {\n TouchCalibration cal = {};\n GetTouchCalibration(&cal);\n x_min_tuxels_ += cal.bezel_left;\n x_num_tuxels_ -= cal.bezel_left + cal.bezel_right;\n y_min_tuxels_ += cal.bezel_top;\n y_num_tuxels_ -= cal.bezel_top + cal.bezel_bottom;\n\n VLOG(1) << \"applying touch calibration: \"\n << base::StringPrintf(\"[%d, %d, %d, %d]\", cal.bezel_left,\n cal.bezel_right, cal.bezel_top,\n cal.bezel_bottom);\n }\n\n events_.resize(touch_points_);\n\n if (has_mt_) {\n for (size_t i = 0; i < events_.size(); ++i) {\n events_[i].x = info.GetAbsMtSlotValue(ABS_MT_POSITION_X, i);\n events_[i].y = info.GetAbsMtSlotValue(ABS_MT_POSITION_Y, i);\n events_[i].tracking_id = info.GetAbsMtSlotValue(ABS_MT_TRACKING_ID, i);\n events_[i].touching = (events_[i].tracking_id >= 0);\n events_[i].slot = i;\n\n \/\/ Dirty the slot so we'll update the consumer at the first opportunity.\n \/\/ We can't dispatch here as this is currently called on the worker pool.\n \/\/ TODO(spang): Move initialization off worker pool.\n events_[i].altered = true;\n\n \/\/ Optional bits.\n events_[i].radius_x =\n info.GetAbsMtSlotValueWithDefault(ABS_MT_TOUCH_MAJOR, i, 0) \/ 2.0f;\n events_[i].radius_y =\n info.GetAbsMtSlotValueWithDefault(ABS_MT_TOUCH_MINOR, i, 0) \/ 2.0f;\n events_[i].pressure =\n ScalePressure(info.GetAbsMtSlotValue(ABS_MT_PRESSURE, i));\n }\n } else {\n \/\/ TODO(spang): Add key state to EventDeviceInfo to allow initial contact.\n events_[0].x = 0;\n events_[0].y = 0;\n events_[0].tracking_id = -1;\n events_[0].touching = false;\n events_[0].slot = 0;\n events_[0].radius_x = 0;\n events_[0].radius_y = 0;\n events_[0].pressure = 0;\n }\n}\n\nbool TouchEventConverterEvdev::Reinitialize() {\n EventDeviceInfo info;\n if (info.Initialize(fd_)) {\n Initialize(info);\n return true;\n }\n return false;\n}\n\nbool TouchEventConverterEvdev::HasTouchscreen() const {\n return true;\n}\n\ngfx::Size TouchEventConverterEvdev::GetTouchscreenSize() const {\n return gfx::Size(x_num_tuxels_, y_num_tuxels_);\n}\n\nint TouchEventConverterEvdev::GetTouchPoints() const {\n return touch_points_;\n}\n\nvoid TouchEventConverterEvdev::OnFileCanReadWithoutBlocking(int fd) {\n input_event inputs[kNumTouchEvdevSlots * 6 + 1];\n ssize_t read_size = read(fd, inputs, sizeof(inputs));\n if (read_size < 0) {\n if (errno == EINTR || errno == EAGAIN)\n return;\n if (errno != ENODEV)\n PLOG(ERROR) << \"error reading device \" << path_.value();\n Stop();\n return;\n }\n\n if (ignore_events_)\n return;\n\n for (unsigned i = 0; i < read_size \/ sizeof(*inputs); i++) {\n if (!has_mt_) {\n \/\/ Emulate the device as an MT device with only 1 slot by inserting extra\n \/\/ MT protocol events in the stream.\n EmulateMultitouchEvent(inputs[i]);\n }\n\n ProcessMultitouchEvent(inputs[i]);\n }\n}\n\nvoid TouchEventConverterEvdev::ProcessMultitouchEvent(\n const input_event& input) {\n if (input.type == EV_SYN) {\n ProcessSyn(input);\n } else if (syn_dropped_) {\n \/\/ Do nothing. This branch indicates we have lost sync with the driver.\n } else if (input.type == EV_ABS) {\n if (events_.size() <= current_slot_) {\n LOG(ERROR) << \"current_slot_ (\" << current_slot_\n << \") >= events_.size() (\" << events_.size() << \")\";\n } else {\n ProcessAbs(input);\n }\n } else if (input.type == EV_KEY) {\n ProcessKey(input);\n } else {\n NOTIMPLEMENTED() << \"invalid type: \" << input.type;\n }\n}\n\nvoid TouchEventConverterEvdev::EmulateMultitouchEvent(\n const input_event& event) {\n input_event emulated_event = event;\n\n if (event.type == EV_ABS) {\n emulated_event.code = AbsCodeToMtCode(event.code);\n if (emulated_event.code >= 0)\n ProcessMultitouchEvent(emulated_event);\n } else if (event.type == EV_KEY && event.code == BTN_TOUCH) {\n emulated_event.type = EV_ABS;\n emulated_event.code = ABS_MT_TRACKING_ID;\n emulated_event.value = event.value ? NextTrackingId() : -1;\n ProcessMultitouchEvent(emulated_event);\n }\n}\n\nvoid TouchEventConverterEvdev::ProcessKey(const input_event& input) {\n switch (input.code) {\n case BTN_TOUCH:\n break;\n default:\n NOTIMPLEMENTED() << \"invalid code for EV_KEY: \" << input.code;\n }\n}\n\nvoid TouchEventConverterEvdev::ProcessAbs(const input_event& input) {\n switch (input.code) {\n case ABS_MT_TOUCH_MAJOR:\n \/\/ TODO(spang): If we have all of major, minor, and orientation,\n \/\/ we can scale the ellipse correctly. However on the Pixel we get\n \/\/ neither minor nor orientation, so this is all we can do.\n events_[current_slot_].radius_x = input.value \/ 2.0f;\n break;\n case ABS_MT_TOUCH_MINOR:\n events_[current_slot_].radius_y = input.value \/ 2.0f;\n break;\n case ABS_MT_POSITION_X:\n events_[current_slot_].x = input.value;\n break;\n case ABS_MT_POSITION_Y:\n events_[current_slot_].y = input.value;\n break;\n case ABS_MT_TRACKING_ID:\n if (input.value < 0) {\n events_[current_slot_].touching = false;\n } else {\n events_[current_slot_].touching = true;\n events_[current_slot_].cancelled = false;\n }\n events_[current_slot_].tracking_id = input.value;\n break;\n case ABS_MT_PRESSURE:\n events_[current_slot_].pressure = ScalePressure(input.value);\n break;\n case ABS_MT_SLOT:\n if (input.value >= 0 &&\n static_cast<size_t>(input.value) < events_.size()) {\n current_slot_ = input.value;\n } else {\n LOG(ERROR) << \"invalid touch event index: \" << input.value;\n return;\n }\n break;\n default:\n DVLOG(5) << \"unhandled code for EV_ABS: \" << input.code;\n return;\n }\n events_[current_slot_].altered = true;\n}\n\nvoid TouchEventConverterEvdev::ProcessSyn(const input_event& input) {\n switch (input.code) {\n case SYN_REPORT:\n if (syn_dropped_) {\n \/\/ Have to re-initialize.\n if (Reinitialize()) {\n syn_dropped_ = false;\n } else {\n LOG(ERROR) << \"failed to re-initialize device info\";\n }\n } else {\n ReportEvents(EventConverterEvdev::TimeDeltaFromInputEvent(input));\n }\n break;\n case SYN_DROPPED:\n \/\/ Some buffer has overrun. We ignore all events up to and\n \/\/ including the next SYN_REPORT.\n syn_dropped_ = true;\n break;\n default:\n NOTIMPLEMENTED() << \"invalid code for EV_SYN: \" << input.code;\n }\n}\n\nEventType TouchEventConverterEvdev::GetEventTypeForTouch(\n const InProgressTouchEvdev& touch) {\n if (touch.cancelled)\n return ET_UNKNOWN;\n\n if (touch_noise_finder_ && touch_noise_finder_->SlotHasNoise(touch.slot)) {\n if (touch.touching && !touch.was_touching)\n return ET_UNKNOWN;\n return ET_TOUCH_CANCELLED;\n }\n\n if (touch.touching)\n return touch.was_touching ? ET_TOUCH_MOVED : ET_TOUCH_PRESSED;\n return touch.was_touching ? ET_TOUCH_RELEASED : ET_UNKNOWN;\n}\n\nvoid TouchEventConverterEvdev::ReportEvent(const InProgressTouchEvdev& event,\n EventType event_type,\n const base::TimeDelta& timestamp) {\n dispatcher_->DispatchTouchEvent(TouchEventParams(\n input_device_.id, event.slot, event_type, gfx::PointF(event.x, event.y),\n gfx::Vector2dF(event.radius_x, event.radius_y), event.pressure,\n timestamp));\n}\n\nvoid TouchEventConverterEvdev::ReportEvents(base::TimeDelta delta) {\n if (touch_noise_finder_)\n touch_noise_finder_->HandleTouches(events_, delta);\n\n for (size_t i = 0; i < events_.size(); i++) {\n InProgressTouchEvdev* event = &events_[i];\n if (!event->altered)\n continue;\n\n EventType event_type = GetEventTypeForTouch(*event);\n if (event_type == ET_UNKNOWN || event_type == ET_TOUCH_CANCELLED)\n event->cancelled = true;\n\n if (event_type != ET_UNKNOWN)\n ReportEvent(*event, event_type, delta);\n\n event->was_touching = event->touching;\n event->altered = false;\n }\n}\n\nfloat TouchEventConverterEvdev::ScalePressure(int32_t value) {\n float pressure = value - pressure_min_;\n if (pressure_max_ - pressure_min_)\n pressure \/= pressure_max_ - pressure_min_;\n return pressure;\n}\n\nint TouchEventConverterEvdev::NextTrackingId() {\n return next_tracking_id_++ & kMaxTrackingId;\n}\n\n} \/\/ namespace ui\n<commit_msg>ozone: evdev: Always supply a default value for touch axes<commit_after>\/\/ Copyright 2014 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"ui\/events\/ozone\/evdev\/touch_event_converter_evdev.h\"\n\n#include <errno.h>\n#include <fcntl.h>\n#include <linux\/input.h>\n#include <poll.h>\n#include <stdio.h>\n#include <unistd.h>\n\n#include <cmath>\n#include <limits>\n\n#include \"base\/bind.h\"\n#include \"base\/callback.h\"\n#include \"base\/command_line.h\"\n#include \"base\/logging.h\"\n#include \"base\/memory\/scoped_vector.h\"\n#include \"base\/message_loop\/message_loop.h\"\n#include \"base\/strings\/string_number_conversions.h\"\n#include \"base\/strings\/string_util.h\"\n#include \"base\/strings\/stringprintf.h\"\n#include \"ui\/events\/devices\/device_data_manager.h\"\n#include \"ui\/events\/devices\/device_util_linux.h\"\n#include \"ui\/events\/event.h\"\n#include \"ui\/events\/event_constants.h\"\n#include \"ui\/events\/event_switches.h\"\n#include \"ui\/events\/ozone\/evdev\/device_event_dispatcher_evdev.h\"\n#include \"ui\/events\/ozone\/evdev\/touch_evdev_types.h\"\n#include \"ui\/events\/ozone\/evdev\/touch_noise\/touch_noise_finder.h\"\n\nnamespace {\n\nconst int kMaxTrackingId = 0xffff; \/\/ TRKID_MAX in kernel.\n\nstruct TouchCalibration {\n int bezel_left;\n int bezel_right;\n int bezel_top;\n int bezel_bottom;\n};\n\nvoid GetTouchCalibration(TouchCalibration* cal) {\n std::vector<std::string> parts;\n if (Tokenize(base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII(\n switches::kTouchCalibration),\n \",\", &parts) >= 4) {\n if (!base::StringToInt(parts[0], &cal->bezel_left))\n LOG(ERROR) << \"Incorrect left border calibration value passed.\";\n if (!base::StringToInt(parts[1], &cal->bezel_right))\n LOG(ERROR) << \"Incorrect right border calibration value passed.\";\n if (!base::StringToInt(parts[2], &cal->bezel_top))\n LOG(ERROR) << \"Incorrect top border calibration value passed.\";\n if (!base::StringToInt(parts[3], &cal->bezel_bottom))\n LOG(ERROR) << \"Incorrect bottom border calibration value passed.\";\n }\n}\n\nint32_t AbsCodeToMtCode(int32_t code) {\n switch (code) {\n case ABS_X:\n return ABS_MT_POSITION_X;\n case ABS_Y:\n return ABS_MT_POSITION_Y;\n case ABS_PRESSURE:\n return ABS_MT_PRESSURE;\n case ABS_DISTANCE:\n return ABS_MT_DISTANCE;\n default:\n return -1;\n }\n}\n\n} \/\/ namespace\n\nnamespace ui {\n\nTouchEventConverterEvdev::TouchEventConverterEvdev(\n int fd,\n base::FilePath path,\n int id,\n InputDeviceType type,\n const EventDeviceInfo& devinfo,\n DeviceEventDispatcherEvdev* dispatcher)\n : EventConverterEvdev(fd,\n path,\n id,\n type,\n devinfo.name(),\n devinfo.vendor_id(),\n devinfo.product_id()),\n dispatcher_(dispatcher),\n syn_dropped_(false),\n has_mt_(false),\n touch_points_(0),\n next_tracking_id_(0),\n current_slot_(0) {\n if (base::CommandLine::ForCurrentProcess()->HasSwitch(\n switches::kExtraTouchNoiseFiltering)) {\n touch_noise_finder_.reset(new TouchNoiseFinder);\n }\n}\n\nTouchEventConverterEvdev::~TouchEventConverterEvdev() {\n Stop();\n close(fd_);\n}\n\nvoid TouchEventConverterEvdev::Initialize(const EventDeviceInfo& info) {\n has_mt_ = info.HasMultitouch();\n\n if (has_mt_) {\n pressure_min_ = info.GetAbsMinimum(ABS_MT_PRESSURE);\n pressure_max_ = info.GetAbsMaximum(ABS_MT_PRESSURE);\n x_min_tuxels_ = info.GetAbsMinimum(ABS_MT_POSITION_X);\n x_num_tuxels_ = info.GetAbsMaximum(ABS_MT_POSITION_X) - x_min_tuxels_ + 1;\n y_min_tuxels_ = info.GetAbsMinimum(ABS_MT_POSITION_Y);\n y_num_tuxels_ = info.GetAbsMaximum(ABS_MT_POSITION_Y) - y_min_tuxels_ + 1;\n touch_points_ =\n std::min<int>(info.GetAbsMaximum(ABS_MT_SLOT) + 1, kNumTouchEvdevSlots);\n current_slot_ = info.GetAbsValue(ABS_MT_SLOT);\n } else {\n pressure_min_ = info.GetAbsMinimum(ABS_PRESSURE);\n pressure_max_ = info.GetAbsMaximum(ABS_PRESSURE);\n x_min_tuxels_ = info.GetAbsMinimum(ABS_X);\n x_num_tuxels_ = info.GetAbsMaximum(ABS_X) - x_min_tuxels_ + 1;\n y_min_tuxels_ = info.GetAbsMinimum(ABS_Y);\n y_num_tuxels_ = info.GetAbsMaximum(ABS_Y) - y_min_tuxels_ + 1;\n touch_points_ = 1;\n current_slot_ = 0;\n }\n\n \/\/ Apply --touch-calibration.\n if (type() == INPUT_DEVICE_INTERNAL) {\n TouchCalibration cal = {};\n GetTouchCalibration(&cal);\n x_min_tuxels_ += cal.bezel_left;\n x_num_tuxels_ -= cal.bezel_left + cal.bezel_right;\n y_min_tuxels_ += cal.bezel_top;\n y_num_tuxels_ -= cal.bezel_top + cal.bezel_bottom;\n\n VLOG(1) << \"applying touch calibration: \"\n << base::StringPrintf(\"[%d, %d, %d, %d]\", cal.bezel_left,\n cal.bezel_right, cal.bezel_top,\n cal.bezel_bottom);\n }\n\n events_.resize(touch_points_);\n\n if (has_mt_) {\n for (size_t i = 0; i < events_.size(); ++i) {\n events_[i].x = info.GetAbsMtSlotValueWithDefault(ABS_MT_POSITION_X, i, 0);\n events_[i].y = info.GetAbsMtSlotValueWithDefault(ABS_MT_POSITION_Y, i, 0);\n events_[i].tracking_id =\n info.GetAbsMtSlotValueWithDefault(ABS_MT_TRACKING_ID, i, -1);\n events_[i].touching = (events_[i].tracking_id >= 0);\n events_[i].slot = i;\n\n \/\/ Dirty the slot so we'll update the consumer at the first opportunity.\n \/\/ We can't dispatch here as this is currently called on the worker pool.\n \/\/ TODO(spang): Move initialization off worker pool.\n events_[i].altered = true;\n\n \/\/ Optional bits.\n events_[i].radius_x =\n info.GetAbsMtSlotValueWithDefault(ABS_MT_TOUCH_MAJOR, i, 0) \/ 2.0f;\n events_[i].radius_y =\n info.GetAbsMtSlotValueWithDefault(ABS_MT_TOUCH_MINOR, i, 0) \/ 2.0f;\n events_[i].pressure = ScalePressure(\n info.GetAbsMtSlotValueWithDefault(ABS_MT_PRESSURE, i, 0));\n }\n } else {\n \/\/ TODO(spang): Add key state to EventDeviceInfo to allow initial contact.\n events_[0].x = 0;\n events_[0].y = 0;\n events_[0].tracking_id = -1;\n events_[0].touching = false;\n events_[0].slot = 0;\n events_[0].radius_x = 0;\n events_[0].radius_y = 0;\n events_[0].pressure = 0;\n }\n}\n\nbool TouchEventConverterEvdev::Reinitialize() {\n EventDeviceInfo info;\n if (info.Initialize(fd_)) {\n Initialize(info);\n return true;\n }\n return false;\n}\n\nbool TouchEventConverterEvdev::HasTouchscreen() const {\n return true;\n}\n\ngfx::Size TouchEventConverterEvdev::GetTouchscreenSize() const {\n return gfx::Size(x_num_tuxels_, y_num_tuxels_);\n}\n\nint TouchEventConverterEvdev::GetTouchPoints() const {\n return touch_points_;\n}\n\nvoid TouchEventConverterEvdev::OnFileCanReadWithoutBlocking(int fd) {\n input_event inputs[kNumTouchEvdevSlots * 6 + 1];\n ssize_t read_size = read(fd, inputs, sizeof(inputs));\n if (read_size < 0) {\n if (errno == EINTR || errno == EAGAIN)\n return;\n if (errno != ENODEV)\n PLOG(ERROR) << \"error reading device \" << path_.value();\n Stop();\n return;\n }\n\n if (ignore_events_)\n return;\n\n for (unsigned i = 0; i < read_size \/ sizeof(*inputs); i++) {\n if (!has_mt_) {\n \/\/ Emulate the device as an MT device with only 1 slot by inserting extra\n \/\/ MT protocol events in the stream.\n EmulateMultitouchEvent(inputs[i]);\n }\n\n ProcessMultitouchEvent(inputs[i]);\n }\n}\n\nvoid TouchEventConverterEvdev::ProcessMultitouchEvent(\n const input_event& input) {\n if (input.type == EV_SYN) {\n ProcessSyn(input);\n } else if (syn_dropped_) {\n \/\/ Do nothing. This branch indicates we have lost sync with the driver.\n } else if (input.type == EV_ABS) {\n if (events_.size() <= current_slot_) {\n LOG(ERROR) << \"current_slot_ (\" << current_slot_\n << \") >= events_.size() (\" << events_.size() << \")\";\n } else {\n ProcessAbs(input);\n }\n } else if (input.type == EV_KEY) {\n ProcessKey(input);\n } else {\n NOTIMPLEMENTED() << \"invalid type: \" << input.type;\n }\n}\n\nvoid TouchEventConverterEvdev::EmulateMultitouchEvent(\n const input_event& event) {\n input_event emulated_event = event;\n\n if (event.type == EV_ABS) {\n emulated_event.code = AbsCodeToMtCode(event.code);\n if (emulated_event.code >= 0)\n ProcessMultitouchEvent(emulated_event);\n } else if (event.type == EV_KEY && event.code == BTN_TOUCH) {\n emulated_event.type = EV_ABS;\n emulated_event.code = ABS_MT_TRACKING_ID;\n emulated_event.value = event.value ? NextTrackingId() : -1;\n ProcessMultitouchEvent(emulated_event);\n }\n}\n\nvoid TouchEventConverterEvdev::ProcessKey(const input_event& input) {\n switch (input.code) {\n case BTN_TOUCH:\n break;\n default:\n NOTIMPLEMENTED() << \"invalid code for EV_KEY: \" << input.code;\n }\n}\n\nvoid TouchEventConverterEvdev::ProcessAbs(const input_event& input) {\n switch (input.code) {\n case ABS_MT_TOUCH_MAJOR:\n \/\/ TODO(spang): If we have all of major, minor, and orientation,\n \/\/ we can scale the ellipse correctly. However on the Pixel we get\n \/\/ neither minor nor orientation, so this is all we can do.\n events_[current_slot_].radius_x = input.value \/ 2.0f;\n break;\n case ABS_MT_TOUCH_MINOR:\n events_[current_slot_].radius_y = input.value \/ 2.0f;\n break;\n case ABS_MT_POSITION_X:\n events_[current_slot_].x = input.value;\n break;\n case ABS_MT_POSITION_Y:\n events_[current_slot_].y = input.value;\n break;\n case ABS_MT_TRACKING_ID:\n if (input.value < 0) {\n events_[current_slot_].touching = false;\n } else {\n events_[current_slot_].touching = true;\n events_[current_slot_].cancelled = false;\n }\n events_[current_slot_].tracking_id = input.value;\n break;\n case ABS_MT_PRESSURE:\n events_[current_slot_].pressure = ScalePressure(input.value);\n break;\n case ABS_MT_SLOT:\n if (input.value >= 0 &&\n static_cast<size_t>(input.value) < events_.size()) {\n current_slot_ = input.value;\n } else {\n LOG(ERROR) << \"invalid touch event index: \" << input.value;\n return;\n }\n break;\n default:\n DVLOG(5) << \"unhandled code for EV_ABS: \" << input.code;\n return;\n }\n events_[current_slot_].altered = true;\n}\n\nvoid TouchEventConverterEvdev::ProcessSyn(const input_event& input) {\n switch (input.code) {\n case SYN_REPORT:\n if (syn_dropped_) {\n \/\/ Have to re-initialize.\n if (Reinitialize()) {\n syn_dropped_ = false;\n } else {\n LOG(ERROR) << \"failed to re-initialize device info\";\n }\n } else {\n ReportEvents(EventConverterEvdev::TimeDeltaFromInputEvent(input));\n }\n break;\n case SYN_DROPPED:\n \/\/ Some buffer has overrun. We ignore all events up to and\n \/\/ including the next SYN_REPORT.\n syn_dropped_ = true;\n break;\n default:\n NOTIMPLEMENTED() << \"invalid code for EV_SYN: \" << input.code;\n }\n}\n\nEventType TouchEventConverterEvdev::GetEventTypeForTouch(\n const InProgressTouchEvdev& touch) {\n if (touch.cancelled)\n return ET_UNKNOWN;\n\n if (touch_noise_finder_ && touch_noise_finder_->SlotHasNoise(touch.slot)) {\n if (touch.touching && !touch.was_touching)\n return ET_UNKNOWN;\n return ET_TOUCH_CANCELLED;\n }\n\n if (touch.touching)\n return touch.was_touching ? ET_TOUCH_MOVED : ET_TOUCH_PRESSED;\n return touch.was_touching ? ET_TOUCH_RELEASED : ET_UNKNOWN;\n}\n\nvoid TouchEventConverterEvdev::ReportEvent(const InProgressTouchEvdev& event,\n EventType event_type,\n const base::TimeDelta& timestamp) {\n dispatcher_->DispatchTouchEvent(TouchEventParams(\n input_device_.id, event.slot, event_type, gfx::PointF(event.x, event.y),\n gfx::Vector2dF(event.radius_x, event.radius_y), event.pressure,\n timestamp));\n}\n\nvoid TouchEventConverterEvdev::ReportEvents(base::TimeDelta delta) {\n if (touch_noise_finder_)\n touch_noise_finder_->HandleTouches(events_, delta);\n\n for (size_t i = 0; i < events_.size(); i++) {\n InProgressTouchEvdev* event = &events_[i];\n if (!event->altered)\n continue;\n\n EventType event_type = GetEventTypeForTouch(*event);\n if (event_type == ET_UNKNOWN || event_type == ET_TOUCH_CANCELLED)\n event->cancelled = true;\n\n if (event_type != ET_UNKNOWN)\n ReportEvent(*event, event_type, delta);\n\n event->was_touching = event->touching;\n event->altered = false;\n }\n}\n\nfloat TouchEventConverterEvdev::ScalePressure(int32_t value) {\n float pressure = value - pressure_min_;\n if (pressure_max_ - pressure_min_)\n pressure \/= pressure_max_ - pressure_min_;\n return pressure;\n}\n\nint TouchEventConverterEvdev::NextTrackingId() {\n return next_tracking_id_++ & kMaxTrackingId;\n}\n\n} \/\/ namespace ui\n<|endoftext|>"} {"text":"<commit_before>\n#pragma once\n\n\/**\n * AttributeModel.hpp\n * Purpose: An abstract base model for indexed attributes.\n *\n * @author Kevin A. Naudé\n * @version 1.1\n *\/\n\n#include <string>\n#include <vector>\n#include <cstdlib>\n#include <Random.hpp>\n\nnamespace kn\n{\n\n class AttributeModel\n {\n public:\n virtual ~AttributeModel() {}\n\n virtual std::size_t count() const\n {\n return 0;\n }\n\n virtual int relation(std::size_t idA, std::size_t idB) const\n {\n return 0;\n }\n\n virtual double similarity(std::size_t idA, std::size_t idB) const\n {\n return (relation(idA, idB) == 0) ? 1.0 : 0.0;\n }\n };\n\n class NullAttributeModel : public AttributeModel {};\n\n template <typename T>\n class VectorAttributeModel : public AttributeModel\n {\n private:\n std::vector<T> attributes;\n\n public:\n VectorAttributeModel(std::vector<T> attrs)\n : attributes(attrs)\n {\n }\n\n virtual int relation(std::size_t idA, std::size_t idB) const\n {\n if ((idA == idB) || (attributes[idA] == attributes[idB]))\n return 0;\n else\n if (attributes[idA] < attributes[idB])\n return -1;\n else\n return +1;\n }\n };\n\n}\n<commit_msg>Improved compatibility to remove warnings.<commit_after>\n#pragma once\n\n\/**\n * AttributeModel.hpp\n * Purpose: An abstract base model for indexed attributes.\n *\n * @author Kevin A. Naudé\n * @version 1.1\n *\/\n\n#include <string>\n#include <vector>\n#include <cstdlib>\n#include <Random.hpp>\n\nnamespace kn\n{\n\n class AttributeModel\n {\n public:\n virtual ~AttributeModel() {}\n\n virtual std::size_t count() const\n {\n return 0;\n }\n\n virtual int relation(std::size_t idA, std::size_t idB) const\n {\n if (idA == idB)\n return 0;\n else\n if (idA < idB)\n return -1;\n else\n return +1;\n }\n\n virtual double similarity(std::size_t idA, std::size_t idB) const\n {\n return (relation(idA, idB) == 0) ? 1.0 : 0.0;\n }\n };\n\n class NullAttributeModel : public AttributeModel {};\n\n template <typename T>\n class VectorAttributeModel : public AttributeModel\n {\n private:\n std::vector<T> attributes;\n\n public:\n VectorAttributeModel(std::vector<T> attrs)\n : attributes(attrs)\n {\n }\n\n virtual int relation(std::size_t idA, std::size_t idB) const\n {\n if ((idA == idB) || (attributes[idA] == attributes[idB]))\n return 0;\n else\n if (attributes[idA] < attributes[idB])\n return -1;\n else\n return +1;\n }\n };\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Hossein Moein\n\/\/ September 12, 2017\n\/\/ Copyright (C) 2018-2019 Hossein Moein\n\/\/ Distributed under the BSD Software License (see file License)\n\n#include \"DataFrame.h\"\n#include <tuple>\n\n\/\/ ----------------------------------------------------------------------------\n\nnamespace hmdf\n{\n\n\/\/ ----------------------------------------------------------------------------\n\ntemplate<typename TS, typename HETERO>\ntemplate<typename RHS_T, typename ... types>\nStdDataFrame<TS> DataFrame<TS, HETERO>::\njoin_by_index (const RHS_T &rhs, join_policy mp) const {\n\n static_assert(std::is_base_of<StdDataFrame<TS>, RHS_T>::value or\n std::is_base_of<DataFrameView<TS>, RHS_T>::value,\n \"The rhs argument to join_by_index() can only be \"\n \"StdDataFrame<TS> or DataFrameView<TS>\");\n\n switch(mp) {\n case join_policy::inner_join:\n return (index_inner_join_\n <decltype(*this), decltype(rhs), types ...>\n (*this, rhs));\n break;\n case join_policy::left_join:\n return (index_left_join_\n <decltype(*this), decltype(rhs), types ...>\n (*this, rhs));\n break;\n case join_policy::right_join:\n return (index_right_join_\n <decltype(*this), decltype(rhs), types ...>\n (*this, rhs));\n break;\n case join_policy::left_right_join:\n default:\n return (index_left_right_join_\n <decltype(*this), decltype(rhs), types ...>\n (*this, rhs));\n break;\n }\n}\n\n\/\/ ----------------------------------------------------------------------------\n\ntemplate<typename TS, typename HETERO>\ntemplate<typename RHS_T, typename T, typename ... types>\nStdDataFrame<TS> DataFrame<TS, HETERO>::\njoin_by_column (const RHS_T &rhs,\n const char *col_name,\n join_policy mp) const {\n\n static_assert(std::is_base_of<StdDataFrame<TS>, RHS_T>::value or\n std::is_base_of<DataFrameView<TS>, RHS_T>::value,\n \"The rhs argument to join_by_column() can only be \"\n \"StdDataFrame<TS> or DataFrameView<TS>\");\n\n switch(mp) {\n case join_policy::inner_join:\n return (column_inner_join_\n <decltype(*this), decltype(rhs), T, types ...>\n (col_name, *this, rhs));\n break;\n case join_policy::left_join:\n return (column_left_join_\n <decltype(*this), decltype(rhs), T, types ...>\n (col_name, *this, rhs));\n break;\n case join_policy::right_join:\n return (column_right_join_\n <decltype(*this), decltype(rhs), T, types ...>\n (col_name, *this, rhs));\n break;\n case join_policy::left_right_join:\n default:\n return (column_left_right_join_\n <decltype(*this), decltype(rhs), T, types ...>\n (col_name, *this, rhs));\n break;\n }\n}\n\n\/\/ ----------------------------------------------------------------------------\n\ntemplate<typename TS, typename HETERO>\ntemplate<typename LHS_T, typename RHS_T, typename ... types>\nStdDataFrame<TS> DataFrame<TS, HETERO>::\njoin_helper_(const LHS_T &lhs,\n const RHS_T &rhs,\n const IndexIdxVector &joined_index_idx) {\n\n StdDataFrame<TS> result;\n std::vector<TS> result_index;\n\n \/\/ Load the index\n result_index.reserve(joined_index_idx.size());\n for (const auto &citer : joined_index_idx) {\n const size_type left_i = std::get<0>(citer);\n\n result_index.push_back(\n left_i != std::numeric_limits<size_type>::max()\n ? lhs.indices_[left_i] : rhs.indices_[std::get<1>(citer)]);\n }\n result.load_index(std::move(result_index));\n\n \/\/ Load the common and lhs columns\n for (auto &iter : lhs.data_tb_) {\n auto rhs_citer = rhs.data_tb_.find(iter.first);\n\n \/\/ Common column between two frames\n if (rhs_citer != rhs.data_tb_.end()) {\n index_join_functor_common_<types ...> functor (iter.first.c_str(),\n rhs,\n joined_index_idx,\n result);\n\n lhs.data_[iter.second].change(functor);\n\n }\n else { \/\/ lhs only column\n \/\/ 0 = Left\n index_join_functor_oneside_<0, types ...> functor (\n iter.first.c_str(),\n joined_index_idx,\n result);\n\n lhs.data_[iter.second].change(functor);\n }\n }\n\n \/\/ Load the rhs columns\n for (auto &iter : rhs.data_tb_) {\n auto lhs_citer = lhs.data_tb_.find(iter.first);\n\n if (lhs_citer == lhs.data_tb_.end()) { \/\/ rhs only column\n \/\/ 1 = Right\n index_join_functor_oneside_<1, types ...> functor (\n iter.first.c_str(),\n joined_index_idx,\n result);\n\n rhs.data_[iter.second].change(functor);\n }\n }\n\n return(result);\n}\n\n\/\/ ----------------------------------------------------------------------------\n\ntemplate<typename TS, typename HETERO>\ntemplate<typename LHS_T, typename RHS_T, typename ... types>\nStdDataFrame<TS> DataFrame<TS, HETERO>::\nindex_inner_join_(const LHS_T &lhs, const RHS_T &rhs) {\n\n size_type lhs_current = 0;\n const size_type lhs_end = lhs.indices_.size();\n size_type rhs_current = 0;\n const size_type rhs_end = rhs.indices_.size();\n\n IndexIdxVector joined_index_idx;\n\n joined_index_idx.reserve(std::min(lhs_end, rhs_end));\n while (lhs_current != lhs_end && rhs_current != rhs_end) {\n if (lhs.indices_[lhs_current] < rhs.indices_[rhs_current])\n lhs_current += 1;\n else {\n if (lhs.indices_[lhs_current] == rhs.indices_[rhs_current])\n joined_index_idx.emplace_back(lhs_current++, rhs_current);\n rhs_current += 1;\n }\n }\n\n return (join_helper_<LHS_T, RHS_T, types ...>(lhs, rhs, joined_index_idx));\n}\n\n\/\/ ----------------------------------------------------------------------------\n\ntemplate<typename TS, typename HETERO>\ntemplate<typename LHS_T, typename RHS_T, typename ... types>\nStdDataFrame<TS> DataFrame<TS, HETERO>::\nindex_left_join_(const LHS_T &lhs, const RHS_T &rhs) {\n\n size_type lhs_current = 0;\n const size_type lhs_end = lhs.indices_.size();\n size_type rhs_current = 0;\n const size_type rhs_end = rhs.indices_.size();\n\n IndexIdxVector joined_index_idx;\n\n joined_index_idx.reserve(lhs_end);\n while (lhs_current != lhs_end && rhs_current != rhs_end) {\n if (lhs.indices_[lhs_current] < rhs.indices_[rhs_current])\n joined_index_idx.emplace_back(\n lhs_current++,\n std::numeric_limits<size_type>::max());\n else {\n if (lhs.indices_[lhs_current] == rhs.indices_[rhs_current])\n joined_index_idx.emplace_back(lhs_current++, rhs_current);\n rhs_current += 1;\n }\n }\n\n return (join_helper_<LHS_T, RHS_T, types ...>(lhs, rhs, joined_index_idx));\n}\n\n\/\/ ----------------------------------------------------------------------------\n\ntemplate<typename TS, typename HETERO>\ntemplate<typename LHS_T, typename RHS_T, typename ... types>\nStdDataFrame<TS> DataFrame<TS, HETERO>::\nindex_right_join_(const LHS_T &lhs, const RHS_T &rhs) {\n\n size_type lhs_current = 0;\n const size_type lhs_end = lhs.indices_.size();\n size_type rhs_current = 0;\n const size_type rhs_end = rhs.indices_.size();\n\n IndexIdxVector joined_index_idx;\n\n joined_index_idx.reserve(rhs_end);\n while (lhs_current != lhs_end && rhs_current != rhs_end) {\n if (lhs.indices_[lhs_current] < rhs.indices_[rhs_current]) {\n joined_index_idx.emplace_back(\n std::numeric_limits<size_type>::max(),\n rhs_current++);\n lhs_current += 1;\n }\n else {\n if (lhs.indices_[lhs_current] == rhs.indices_[rhs_current])\n joined_index_idx.emplace_back(lhs_current++, rhs_current++);\n else\n joined_index_idx.emplace_back(\n std::numeric_limits<size_type>::max(),\n rhs_current++);\n }\n }\n\n return (join_helper_<LHS_T, RHS_T, types ...>(lhs, rhs, joined_index_idx));\n}\n\n\/\/ ----------------------------------------------------------------------------\n\ntemplate<typename TS, typename HETERO>\ntemplate<typename LHS_T, typename RHS_T, typename ... types>\nStdDataFrame<TS> DataFrame<TS, HETERO>::\nindex_left_right_join_(const LHS_T &lhs, const RHS_T &rhs) {\n\n StdDataFrame<TS> result;\n\n return(result);\n}\n\n\/\/ ----------------------------------------------------------------------------\n\ntemplate<typename TS, typename HETERO>\ntemplate<typename LHS_T, typename RHS_T, typename COL_T, typename ... types>\nStdDataFrame<TS> DataFrame<TS, HETERO>::\ncolumn_inner_join_(const char *col_name, const LHS_T &lhs, const RHS_T &rhs) {\n\n StdDataFrame<TS> result;\n\n return(result);\n}\n\n\/\/ ----------------------------------------------------------------------------\n\ntemplate<typename TS, typename HETERO>\ntemplate<typename LHS_T, typename RHS_T, typename COL_T, typename ... types>\nStdDataFrame<TS> DataFrame<TS, HETERO>::\ncolumn_left_join_(const char *col_name, const LHS_T &lhs, const RHS_T &rhs) {\n\n StdDataFrame<TS> result;\n\n return(result);\n}\n\n\/\/ ----------------------------------------------------------------------------\n\ntemplate<typename TS, typename HETERO>\ntemplate<typename LHS_T, typename RHS_T, typename COL_T, typename ... types>\nStdDataFrame<TS> DataFrame<TS, HETERO>::\ncolumn_right_join_(const char *col_name, const LHS_T &lhs, const RHS_T &rhs) {\n\n StdDataFrame<TS> result;\n\n return(result);\n}\n\n\/\/ ----------------------------------------------------------------------------\n\ntemplate<typename TS, typename HETERO>\ntemplate<typename LHS_T, typename RHS_T, typename COL_T, typename ... types>\nStdDataFrame<TS> DataFrame<TS, HETERO>::\ncolumn_left_right_join_(const char *col_name,\n const LHS_T &lhs,\n const RHS_T &rhs) {\n\n StdDataFrame<TS> result;\n\n return(result);\n}\n\n} \/\/ namespace hmdf\n\n\/\/ ----------------------------------------------------------------------------\n\n\/\/ Local Variables:\n\/\/ mode:C++\n\/\/ tab-width:4\n\/\/ c-basic-offset:4\n\/\/ End:\n<commit_msg>Small correction<commit_after>\/\/ Hossein Moein\n\/\/ September 12, 2017\n\/\/ Copyright (C) 2018-2019 Hossein Moein\n\/\/ Distributed under the BSD Software License (see file License)\n\n#include \"DataFrame.h\"\n#include <tuple>\n\n\/\/ ----------------------------------------------------------------------------\n\nnamespace hmdf\n{\n\n\/\/ ----------------------------------------------------------------------------\n\ntemplate<typename TS, typename HETERO>\ntemplate<typename RHS_T, typename ... types>\nStdDataFrame<TS> DataFrame<TS, HETERO>::\njoin_by_index (const RHS_T &rhs, join_policy mp) const {\n\n static_assert(std::is_base_of<StdDataFrame<TS>, RHS_T>::value or\n std::is_base_of<DataFrameView<TS>, RHS_T>::value,\n \"The rhs argument to join_by_index() can only be \"\n \"StdDataFrame<TS> or DataFrameView<TS>\");\n\n switch(mp) {\n case join_policy::inner_join:\n return (index_inner_join_\n <decltype(*this), decltype(rhs), types ...>\n (*this, rhs));\n break;\n case join_policy::left_join:\n return (index_left_join_\n <decltype(*this), decltype(rhs), types ...>\n (*this, rhs));\n break;\n case join_policy::right_join:\n return (index_right_join_\n <decltype(*this), decltype(rhs), types ...>\n (*this, rhs));\n break;\n case join_policy::left_right_join:\n default:\n return (index_left_right_join_\n <decltype(*this), decltype(rhs), types ...>\n (*this, rhs));\n break;\n }\n}\n\n\/\/ ----------------------------------------------------------------------------\n\ntemplate<typename TS, typename HETERO>\ntemplate<typename RHS_T, typename T, typename ... types>\nStdDataFrame<TS> DataFrame<TS, HETERO>::\njoin_by_column (const RHS_T &rhs,\n const char *col_name,\n join_policy mp) const {\n\n static_assert(std::is_base_of<StdDataFrame<TS>, RHS_T>::value or\n std::is_base_of<DataFrameView<TS>, RHS_T>::value,\n \"The rhs argument to join_by_column() can only be \"\n \"StdDataFrame<TS> or DataFrameView<TS>\");\n\n switch(mp) {\n case join_policy::inner_join:\n return (column_inner_join_\n <decltype(*this), decltype(rhs), T, types ...>\n (col_name, *this, rhs));\n break;\n case join_policy::left_join:\n return (column_left_join_\n <decltype(*this), decltype(rhs), T, types ...>\n (col_name, *this, rhs));\n break;\n case join_policy::right_join:\n return (column_right_join_\n <decltype(*this), decltype(rhs), T, types ...>\n (col_name, *this, rhs));\n break;\n case join_policy::left_right_join:\n default:\n return (column_left_right_join_\n <decltype(*this), decltype(rhs), T, types ...>\n (col_name, *this, rhs));\n break;\n }\n}\n\n\/\/ ----------------------------------------------------------------------------\n\ntemplate<typename TS, typename HETERO>\ntemplate<typename LHS_T, typename RHS_T, typename ... types>\nStdDataFrame<TS> DataFrame<TS, HETERO>::\njoin_helper_(const LHS_T &lhs,\n const RHS_T &rhs,\n const IndexIdxVector &joined_index_idx) {\n\n StdDataFrame<TS> result;\n std::vector<TS> result_index;\n\n \/\/ Load the index\n result_index.reserve(joined_index_idx.size());\n for (const auto &citer : joined_index_idx) {\n const size_type left_i = std::get<0>(citer);\n\n result_index.push_back(\n left_i != std::numeric_limits<size_type>::max()\n ? lhs.indices_[left_i] : rhs.indices_[std::get<1>(citer)]);\n }\n result.load_index(std::move(result_index));\n\n \/\/ Load the common and lhs columns\n for (auto &iter : lhs.data_tb_) {\n auto rhs_citer = rhs.data_tb_.find(iter.first);\n\n \/\/ Common column between two frames\n if (rhs_citer != rhs.data_tb_.end()) {\n index_join_functor_common_<types ...> functor (iter.first.c_str(),\n rhs,\n joined_index_idx,\n result);\n\n lhs.data_[iter.second].change(functor);\n\n }\n else { \/\/ lhs only column\n \/\/ 0 = Left\n index_join_functor_oneside_<0, types ...> functor (\n iter.first.c_str(),\n joined_index_idx,\n result);\n\n lhs.data_[iter.second].change(functor);\n }\n }\n\n \/\/ Load the rhs columns\n for (auto &iter : rhs.data_tb_) {\n auto lhs_citer = lhs.data_tb_.find(iter.first);\n\n if (lhs_citer == lhs.data_tb_.end()) { \/\/ rhs only column\n \/\/ 1 = Right\n index_join_functor_oneside_<1, types ...> functor (\n iter.first.c_str(),\n joined_index_idx,\n result);\n\n rhs.data_[iter.second].change(functor);\n }\n }\n\n return(result);\n}\n\n\/\/ ----------------------------------------------------------------------------\n\ntemplate<typename TS, typename HETERO>\ntemplate<typename LHS_T, typename RHS_T, typename ... types>\nStdDataFrame<TS> DataFrame<TS, HETERO>::\nindex_inner_join_(const LHS_T &lhs, const RHS_T &rhs) {\n\n size_type lhs_current = 0;\n const size_type lhs_end = lhs.indices_.size();\n size_type rhs_current = 0;\n const size_type rhs_end = rhs.indices_.size();\n\n IndexIdxVector joined_index_idx;\n\n joined_index_idx.reserve(std::min(lhs_end, rhs_end));\n while (lhs_current != lhs_end && rhs_current != rhs_end) {\n if (lhs.indices_[lhs_current] < rhs.indices_[rhs_current])\n lhs_current += 1;\n else {\n if (lhs.indices_[lhs_current] == rhs.indices_[rhs_current])\n joined_index_idx.emplace_back(lhs_current++, rhs_current);\n rhs_current += 1;\n }\n }\n\n return (join_helper_<LHS_T, RHS_T, types ...>(lhs, rhs, joined_index_idx));\n}\n\n\/\/ ----------------------------------------------------------------------------\n\ntemplate<typename TS, typename HETERO>\ntemplate<typename LHS_T, typename RHS_T, typename ... types>\nStdDataFrame<TS> DataFrame<TS, HETERO>::\nindex_left_join_(const LHS_T &lhs, const RHS_T &rhs) {\n\n size_type lhs_current = 0;\n const size_type lhs_end = lhs.indices_.size();\n size_type rhs_current = 0;\n const size_type rhs_end = rhs.indices_.size();\n\n IndexIdxVector joined_index_idx;\n\n joined_index_idx.reserve(lhs_end);\n while (lhs_current != lhs_end && rhs_current != rhs_end) {\n if (lhs.indices_[lhs_current] < rhs.indices_[rhs_current])\n joined_index_idx.emplace_back(\n lhs_current++,\n std::numeric_limits<size_type>::max());\n else {\n if (lhs.indices_[lhs_current] == rhs.indices_[rhs_current])\n joined_index_idx.emplace_back(lhs_current++, rhs_current++);\n else {\n joined_index_idx.emplace_back(\n lhs_current++,\n std::numeric_limits<size_type>::max());\n rhs_current += 1;\n }\n }\n }\n\n return (join_helper_<LHS_T, RHS_T, types ...>(lhs, rhs, joined_index_idx));\n}\n\n\/\/ ----------------------------------------------------------------------------\n\ntemplate<typename TS, typename HETERO>\ntemplate<typename LHS_T, typename RHS_T, typename ... types>\nStdDataFrame<TS> DataFrame<TS, HETERO>::\nindex_right_join_(const LHS_T &lhs, const RHS_T &rhs) {\n\n size_type lhs_current = 0;\n const size_type lhs_end = lhs.indices_.size();\n size_type rhs_current = 0;\n const size_type rhs_end = rhs.indices_.size();\n\n IndexIdxVector joined_index_idx;\n\n joined_index_idx.reserve(rhs_end);\n while (lhs_current != lhs_end && rhs_current != rhs_end) {\n if (lhs.indices_[lhs_current] < rhs.indices_[rhs_current]) {\n joined_index_idx.emplace_back(\n std::numeric_limits<size_type>::max(),\n rhs_current++);\n lhs_current += 1;\n }\n else {\n if (lhs.indices_[lhs_current] == rhs.indices_[rhs_current])\n joined_index_idx.emplace_back(lhs_current++, rhs_current++);\n else\n joined_index_idx.emplace_back(\n std::numeric_limits<size_type>::max(),\n rhs_current++);\n }\n }\n\n return (join_helper_<LHS_T, RHS_T, types ...>(lhs, rhs, joined_index_idx));\n}\n\n\/\/ ----------------------------------------------------------------------------\n\ntemplate<typename TS, typename HETERO>\ntemplate<typename LHS_T, typename RHS_T, typename ... types>\nStdDataFrame<TS> DataFrame<TS, HETERO>::\nindex_left_right_join_(const LHS_T &lhs, const RHS_T &rhs) {\n\n StdDataFrame<TS> result;\n\n return(result);\n}\n\n\/\/ ----------------------------------------------------------------------------\n\ntemplate<typename TS, typename HETERO>\ntemplate<typename LHS_T, typename RHS_T, typename COL_T, typename ... types>\nStdDataFrame<TS> DataFrame<TS, HETERO>::\ncolumn_inner_join_(const char *col_name, const LHS_T &lhs, const RHS_T &rhs) {\n\n StdDataFrame<TS> result;\n\n return(result);\n}\n\n\/\/ ----------------------------------------------------------------------------\n\ntemplate<typename TS, typename HETERO>\ntemplate<typename LHS_T, typename RHS_T, typename COL_T, typename ... types>\nStdDataFrame<TS> DataFrame<TS, HETERO>::\ncolumn_left_join_(const char *col_name, const LHS_T &lhs, const RHS_T &rhs) {\n\n StdDataFrame<TS> result;\n\n return(result);\n}\n\n\/\/ ----------------------------------------------------------------------------\n\ntemplate<typename TS, typename HETERO>\ntemplate<typename LHS_T, typename RHS_T, typename COL_T, typename ... types>\nStdDataFrame<TS> DataFrame<TS, HETERO>::\ncolumn_right_join_(const char *col_name, const LHS_T &lhs, const RHS_T &rhs) {\n\n StdDataFrame<TS> result;\n\n return(result);\n}\n\n\/\/ ----------------------------------------------------------------------------\n\ntemplate<typename TS, typename HETERO>\ntemplate<typename LHS_T, typename RHS_T, typename COL_T, typename ... types>\nStdDataFrame<TS> DataFrame<TS, HETERO>::\ncolumn_left_right_join_(const char *col_name,\n const LHS_T &lhs,\n const RHS_T &rhs) {\n\n StdDataFrame<TS> result;\n\n return(result);\n}\n\n} \/\/ namespace hmdf\n\n\/\/ ----------------------------------------------------------------------------\n\n\/\/ Local Variables:\n\/\/ mode:C++\n\/\/ tab-width:4\n\/\/ c-basic-offset:4\n\/\/ End:\n<|endoftext|>"} {"text":"<commit_before>\n\/\/\n\/\/ This source file is part of appleseed.\n\/\/ Visit https:\/\/appleseedhq.net\/ for additional information and resources.\n\/\/\n\/\/ This software is released under the MIT license.\n\/\/\n\/\/ Copyright (c) 2014-2018 Luis B. Barrancos, The appleseedhq Organization\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n\/\/ THE SOFTWARE.\n\/\/\n\n\/\/ Interface header.\n#include \"orennayarbrdf.h\"\n\n\/\/ appleseed.renderer headers.\n#include \"renderer\/kernel\/lighting\/scatteringmode.h\"\n#include \"renderer\/kernel\/shading\/directshadingcomponents.h\"\n#include \"renderer\/modeling\/bsdf\/bsdf.h\"\n#include \"renderer\/modeling\/bsdf\/bsdfsample.h\"\n#include \"renderer\/modeling\/bsdf\/bsdfwrapper.h\"\n\n\/\/ appleseed.foundation headers.\n#include \"foundation\/math\/basis.h\"\n#include \"foundation\/math\/sampling\/mappings.h\"\n#include \"foundation\/math\/scalar.h\"\n#include \"foundation\/math\/vector.h\"\n#include \"foundation\/utility\/api\/specializedapiarrays.h\"\n#include \"foundation\/utility\/containers\/dictionary.h\"\n\n\/\/ Standard headers.\n#include <algorithm>\n#include <cmath>\n\n\/\/ Forward declarations.\nnamespace foundation { class IAbortSwitch; }\nnamespace renderer { class Assembly; }\nnamespace renderer { class Project; }\n\nusing namespace foundation;\nusing namespace std;\n\nnamespace renderer\n{\n\nnamespace\n{\n \/\/\n \/\/ Oren-Nayar BRDF.\n \/\/\n \/\/ Reference:\n \/\/\n \/\/ Generalization of Lambert's Reflectance Model\n \/\/ http:\/\/www1.cs.columbia.edu\/CAVE\/publications\/pdfs\/Oren_SIGGRAPH94.pdf\n \/\/\n\n const char* Model = \"orennayar_brdf\";\n\n class OrenNayarBRDFImpl\n : public BSDF\n {\n public:\n OrenNayarBRDFImpl(\n const char* name,\n const ParamArray& params)\n : BSDF(name, Reflective, ScatteringMode::Diffuse, params)\n {\n m_inputs.declare(\"reflectance\", InputFormatSpectralReflectance);\n m_inputs.declare(\"reflectance_multiplier\", InputFormatFloat, \"1.0\");\n m_inputs.declare(\"roughness\" , InputFormatFloat, \"0.1\");\n }\n\n void release() override\n {\n delete this;\n }\n\n const char* get_model() const override\n {\n return Model;\n }\n\n void sample(\n SamplingContext& sampling_context,\n const void* data,\n const bool adjoint,\n const bool cosine_mult,\n const int modes,\n BSDFSample& sample) const override\n {\n if (!ScatteringMode::has_diffuse(modes))\n return;\n\n \/\/ Compute the incoming direction.\n sampling_context.split_in_place(2, 1);\n const Vector2f s = sampling_context.next2<Vector2f>();\n const Vector3f wi = sample_hemisphere_cosine(s);\n const Vector3f incoming = sample.m_shading_basis.transform_to_parent(wi);\n sample.m_incoming = Dual3f(incoming);\n\n \/\/ Compute the probability density of the sampled direction.\n const float probability = wi.y * RcpPi<float>();\n assert(probability > 0.0f);\n\n if (probability > 1.0e-6f)\n {\n \/\/ Set the scattering mode.\n sample.set_to_scattering(ScatteringMode::Diffuse, probability);\n\n \/\/ Compute the BRDF value.\n const InputValues* values = static_cast<const InputValues*>(data);\n if (values->m_roughness != 0.0f)\n {\n const Vector3f& n = sample.m_shading_basis.get_normal();\n\n \/\/ No reflection below the shading surface.\n const float cos_in = dot(incoming, n);\n if (cos_in < 0.0f)\n return;\n\n const Vector3f& outgoing = sample.m_outgoing.get_value();\n const float cos_on = abs(dot(outgoing, n));\n oren_nayar_qualitative(\n cos_on,\n cos_in,\n values->m_roughness,\n values->m_reflectance,\n values->m_reflectance_multiplier,\n outgoing,\n incoming,\n n,\n sample.m_value.m_diffuse);\n }\n else\n {\n \/\/ Revert to Lambertian when roughness is zero.\n sample.m_value.m_diffuse = values->m_reflectance;\n sample.m_value.m_diffuse *= values->m_reflectance_multiplier * RcpPi<float>();\n }\n\n sample.m_aov_components.m_albedo = values->m_reflectance;\n sample.m_aov_components.m_albedo *= values->m_reflectance_multiplier;\n\n sample.m_value.m_beauty = sample.m_value.m_diffuse;\n sample.m_min_roughness = 1.0f;\n\n sample.compute_reflected_differentials();\n }\n }\n\n float evaluate(\n const void* data,\n const bool adjoint,\n const bool cosine_mult,\n const Vector3f& geometric_normal,\n const Basis3f& shading_basis,\n const Vector3f& outgoing,\n const Vector3f& incoming,\n const int modes,\n DirectShadingComponents& value) const override\n {\n if (!ScatteringMode::has_diffuse(modes))\n return 0.0f;\n\n const Vector3f& n = shading_basis.get_normal();\n const float cos_in = abs(dot(incoming, n));\n\n \/\/ Compute the BRDF value.\n const InputValues* values = static_cast<const InputValues*>(data);\n if (values->m_roughness != 0.0f)\n {\n const float cos_on = abs(dot(outgoing, n));\n oren_nayar_qualitative(\n cos_on,\n cos_in,\n values->m_roughness,\n values->m_reflectance,\n values->m_reflectance_multiplier,\n outgoing,\n incoming,\n n,\n value.m_diffuse);\n }\n else\n {\n \/\/ Revert to Lambertian when roughness is zero.\n value.m_diffuse = values->m_reflectance;\n value.m_diffuse *= values->m_reflectance_multiplier * RcpPi<float>();\n }\n value.m_beauty = value.m_diffuse;\n\n \/\/ Compute the probability density of the sampled direction.\n const float pdf = cos_in * RcpPi<float>();\n assert(pdf >= 0.0f);\n\n return pdf;\n }\n\n float evaluate_pdf(\n const void* data,\n const bool adjoint,\n const Vector3f& geometric_normal,\n const Basis3f& shading_basis,\n const Vector3f& outgoing,\n const Vector3f& incoming,\n const int modes) const override\n {\n if (!ScatteringMode::has_diffuse(modes))\n return 0.0f;\n\n const Vector3f& n = shading_basis.get_normal();\n const float cos_in = abs(dot(incoming, n));\n\n \/\/ Compute the probability density of the sampled direction.\n const float pdf = cos_in * RcpPi<float>();\n assert(pdf >= 0.f);\n\n return pdf;\n }\n\n private:\n typedef OrenNayarBRDFInputValues InputValues;\n\n static void oren_nayar_qualitative(\n const float cos_on,\n const float cos_in,\n const float roughness,\n const Spectrum& reflectance,\n const float reflectance_multiplier,\n const Vector3f& outgoing,\n const Vector3f& incoming,\n const Vector3f& n,\n Spectrum& value)\n {\n const float sigma2 = square(roughness);\n const float theta_r = min(acos(cos_on), HalfPi<float>());\n const float theta_i = acos(cos_in);\n const float alpha = max(theta_r, theta_i);\n const float beta = min(theta_r, theta_i);\n\n \/\/ Project outgoing and incoming vectors onto the tangent plane\n \/\/ and compute the cosine of the angle between them.\n const Vector3f V_perp_N = normalize(project(outgoing, n));\n const Vector3f I_perp_N = normalize(incoming - n * cos_in);\n const float delta_cos_phi = dot(V_perp_N, I_perp_N);\n\n \/\/ Compute C1 coefficient.\n const float C1 = 1.0f - 0.5f * (sigma2 \/ (sigma2 + 0.33f));\n\n \/\/ Compute C2 coefficient.\n const float sigma2_009 = sigma2 \/ (sigma2 + 0.09f);\n const float C2 =\n 0.45f\n * sigma2_009\n * (delta_cos_phi >= 0.0f\n ? sin(alpha)\n : sin(alpha) - pow_int<3>(2.0f * beta * RcpPi<float>()));\n assert(C2 >= 0.0f);\n\n \/\/ Compute C3 coefficient.\n const float C3 =\n 0.125f\n * sigma2_009\n * square(4.0f * alpha * beta * RcpPiSquare<float>());\n assert(C3 >= 0.0f);\n\n \/\/ Direct illumination component.\n value = reflectance;\n value *=\n reflectance_multiplier *\n RcpPi<float>() * (\n C1\n + delta_cos_phi * C2 * tan(beta)\n + (1.0f - abs(delta_cos_phi)) * C3 * tan(0.5f * (alpha + beta)));\n\n \/\/ Add interreflection component.\n Spectrum r2 = reflectance;\n r2 *= r2;\n r2 *=\n 0.17f\n * square(reflectance_multiplier) * RcpPi<float>()\n * sigma2 \/ (sigma2 + 0.13f)\n * (1.0f - delta_cos_phi * square(2.0f * beta * RcpPi<float>()));\n value += r2;\n clamp_low_in_place(value, 0.0f);\n }\n };\n\n typedef BSDFWrapper<OrenNayarBRDFImpl> OrenNayarBRDF;\n}\n\n\n\/\/\n\/\/ OrenNayarBRDFFactory class implementation.\n\/\/\n\nvoid OrenNayarBRDFFactory::release()\n{\n delete this;\n}\n\nconst char* OrenNayarBRDFFactory::get_model() const\n{\n return Model;\n}\n\nDictionary OrenNayarBRDFFactory::get_model_metadata() const\n{\n return\n Dictionary()\n .insert(\"name\", Model)\n .insert(\"label\", \"Oren-Nayar BRDF\");\n}\n\nDictionaryArray OrenNayarBRDFFactory::get_input_metadata() const\n{\n DictionaryArray metadata;\n\n metadata.push_back(\n Dictionary()\n .insert(\"name\", \"reflectance\")\n .insert(\"label\", \"Reflectance\")\n .insert(\"type\", \"colormap\")\n .insert(\"entity_types\",\n Dictionary()\n .insert(\"color\", \"Colors\")\n .insert(\"texture_instance\", \"Texture Instances\"))\n .insert(\"use\", \"required\")\n .insert(\"default\", \"0.5\"));\n\n metadata.push_back(\n Dictionary()\n .insert(\"name\", \"reflectance_multiplier\")\n .insert(\"label\", \"Reflectance Multiplier\")\n .insert(\"type\", \"colormap\")\n .insert(\"entity_types\",\n Dictionary().insert(\"texture_instance\", \"Texture Instances\"))\n .insert(\"use\", \"optional\")\n .insert(\"default\", \"1.0\"));\n\n metadata.push_back(\n Dictionary()\n .insert(\"name\", \"roughness\")\n .insert(\"label\", \"Roughness\")\n .insert(\"type\", \"colormap\")\n .insert(\"entity_types\",\n Dictionary().insert(\"texture_instance\", \"Texture Instances\"))\n .insert(\"use\", \"required\")\n .insert(\"default\", \"0.1\"));\n\n return metadata;\n}\n\nauto_release_ptr<BSDF> OrenNayarBRDFFactory::create(\n const char* name,\n const ParamArray& params) const\n{\n return auto_release_ptr<BSDF>(new OrenNayarBRDF(name, params));\n}\n\n} \/\/ namespace renderer\n<commit_msg>Renamings<commit_after>\n\/\/\n\/\/ This source file is part of appleseed.\n\/\/ Visit https:\/\/appleseedhq.net\/ for additional information and resources.\n\/\/\n\/\/ This software is released under the MIT license.\n\/\/\n\/\/ Copyright (c) 2014-2018 Luis B. Barrancos, The appleseedhq Organization\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n\/\/ THE SOFTWARE.\n\/\/\n\n\/\/ Interface header.\n#include \"orennayarbrdf.h\"\n\n\/\/ appleseed.renderer headers.\n#include \"renderer\/kernel\/lighting\/scatteringmode.h\"\n#include \"renderer\/kernel\/shading\/directshadingcomponents.h\"\n#include \"renderer\/modeling\/bsdf\/bsdf.h\"\n#include \"renderer\/modeling\/bsdf\/bsdfsample.h\"\n#include \"renderer\/modeling\/bsdf\/bsdfwrapper.h\"\n\n\/\/ appleseed.foundation headers.\n#include \"foundation\/math\/basis.h\"\n#include \"foundation\/math\/sampling\/mappings.h\"\n#include \"foundation\/math\/scalar.h\"\n#include \"foundation\/math\/vector.h\"\n#include \"foundation\/utility\/api\/specializedapiarrays.h\"\n#include \"foundation\/utility\/containers\/dictionary.h\"\n\n\/\/ Standard headers.\n#include <algorithm>\n#include <cmath>\n\n\/\/ Forward declarations.\nnamespace foundation { class IAbortSwitch; }\nnamespace renderer { class Assembly; }\nnamespace renderer { class Project; }\n\nusing namespace foundation;\nusing namespace std;\n\nnamespace renderer\n{\n\nnamespace\n{\n \/\/\n \/\/ Oren-Nayar BRDF.\n \/\/\n \/\/ Reference:\n \/\/\n \/\/ Generalization of Lambert's Reflectance Model\n \/\/ http:\/\/www1.cs.columbia.edu\/CAVE\/publications\/pdfs\/Oren_SIGGRAPH94.pdf\n \/\/\n\n const char* Model = \"orennayar_brdf\";\n\n class OrenNayarBRDFImpl\n : public BSDF\n {\n public:\n OrenNayarBRDFImpl(\n const char* name,\n const ParamArray& params)\n : BSDF(name, Reflective, ScatteringMode::Diffuse, params)\n {\n m_inputs.declare(\"reflectance\", InputFormatSpectralReflectance);\n m_inputs.declare(\"reflectance_multiplier\", InputFormatFloat, \"1.0\");\n m_inputs.declare(\"roughness\" , InputFormatFloat, \"0.1\");\n }\n\n void release() override\n {\n delete this;\n }\n\n const char* get_model() const override\n {\n return Model;\n }\n\n void sample(\n SamplingContext& sampling_context,\n const void* data,\n const bool adjoint,\n const bool cosine_mult,\n const int modes,\n BSDFSample& sample) const override\n {\n if (!ScatteringMode::has_diffuse(modes))\n return;\n\n \/\/ Compute the incoming direction.\n sampling_context.split_in_place(2, 1);\n const Vector2f s = sampling_context.next2<Vector2f>();\n const Vector3f wi = sample_hemisphere_cosine(s);\n const Vector3f incoming = sample.m_shading_basis.transform_to_parent(wi);\n sample.m_incoming = Dual3f(incoming);\n\n \/\/ Compute the probability density of the sampled direction.\n const float probability = wi.y * RcpPi<float>();\n assert(probability > 0.0f);\n\n if (probability > 1.0e-6f)\n {\n \/\/ Set the scattering mode.\n sample.set_to_scattering(ScatteringMode::Diffuse, probability);\n\n \/\/ Compute the BRDF value.\n const InputValues* values = static_cast<const InputValues*>(data);\n if (values->m_roughness != 0.0f)\n {\n const Vector3f& n = sample.m_shading_basis.get_normal();\n\n \/\/ No reflection below the shading surface.\n const float cos_in = dot(incoming, n);\n if (cos_in < 0.0f)\n return;\n\n const Vector3f& outgoing = sample.m_outgoing.get_value();\n const float cos_on = abs(dot(outgoing, n));\n oren_nayar(\n cos_on,\n cos_in,\n values->m_roughness,\n values->m_reflectance,\n values->m_reflectance_multiplier,\n outgoing,\n incoming,\n n,\n sample.m_value.m_diffuse);\n }\n else\n {\n \/\/ Revert to Lambertian when roughness is zero.\n sample.m_value.m_diffuse = values->m_reflectance;\n sample.m_value.m_diffuse *= values->m_reflectance_multiplier * RcpPi<float>();\n }\n\n sample.m_aov_components.m_albedo = values->m_reflectance;\n sample.m_aov_components.m_albedo *= values->m_reflectance_multiplier;\n\n sample.m_value.m_beauty = sample.m_value.m_diffuse;\n sample.m_min_roughness = 1.0f;\n\n sample.compute_reflected_differentials();\n }\n }\n\n float evaluate(\n const void* data,\n const bool adjoint,\n const bool cosine_mult,\n const Vector3f& geometric_normal,\n const Basis3f& shading_basis,\n const Vector3f& outgoing,\n const Vector3f& incoming,\n const int modes,\n DirectShadingComponents& value) const override\n {\n if (!ScatteringMode::has_diffuse(modes))\n return 0.0f;\n\n const Vector3f& n = shading_basis.get_normal();\n const float cos_in = abs(dot(incoming, n));\n\n \/\/ Compute the BRDF value.\n const InputValues* values = static_cast<const InputValues*>(data);\n if (values->m_roughness != 0.0f)\n {\n const float cos_on = abs(dot(outgoing, n));\n oren_nayar(\n cos_on,\n cos_in,\n values->m_roughness,\n values->m_reflectance,\n values->m_reflectance_multiplier,\n outgoing,\n incoming,\n n,\n value.m_diffuse);\n }\n else\n {\n \/\/ Revert to Lambertian when roughness is zero.\n value.m_diffuse = values->m_reflectance;\n value.m_diffuse *= values->m_reflectance_multiplier * RcpPi<float>();\n }\n value.m_beauty = value.m_diffuse;\n\n \/\/ Compute the probability density of the sampled direction.\n const float pdf = cos_in * RcpPi<float>();\n assert(pdf >= 0.0f);\n\n return pdf;\n }\n\n float evaluate_pdf(\n const void* data,\n const bool adjoint,\n const Vector3f& geometric_normal,\n const Basis3f& shading_basis,\n const Vector3f& outgoing,\n const Vector3f& incoming,\n const int modes) const override\n {\n if (!ScatteringMode::has_diffuse(modes))\n return 0.0f;\n\n const Vector3f& n = shading_basis.get_normal();\n const float cos_in = abs(dot(incoming, n));\n\n \/\/ Compute the probability density of the sampled direction.\n const float pdf = cos_in * RcpPi<float>();\n assert(pdf >= 0.f);\n\n return pdf;\n }\n\n private:\n typedef OrenNayarBRDFInputValues InputValues;\n\n static void oren_nayar(\n const float cos_on,\n const float cos_in,\n const float roughness,\n const Spectrum& reflectance,\n const float reflectance_multiplier,\n const Vector3f& outgoing,\n const Vector3f& incoming,\n const Vector3f& n,\n Spectrum& value)\n {\n const float sigma2 = square(roughness);\n const float theta_r = min(acos(cos_on), HalfPi<float>());\n const float theta_i = acos(cos_in);\n const float alpha = max(theta_r, theta_i);\n const float beta = min(theta_r, theta_i);\n\n \/\/ Project outgoing and incoming vectors onto the tangent plane\n \/\/ and compute the cosine of the angle between them.\n const Vector3f V_perp_N = normalize(project(outgoing, n));\n const Vector3f I_perp_N = normalize(incoming - n * cos_in);\n const float delta_cos_phi = dot(V_perp_N, I_perp_N);\n\n \/\/ Compute C1 coefficient.\n const float C1 = 1.0f - 0.5f * (sigma2 \/ (sigma2 + 0.33f));\n\n \/\/ Compute C2 coefficient.\n const float sigma2_009 = sigma2 \/ (sigma2 + 0.09f);\n const float C2 =\n 0.45f\n * sigma2_009\n * (delta_cos_phi >= 0.0f\n ? sin(alpha)\n : sin(alpha) - pow_int<3>(2.0f * beta * RcpPi<float>()));\n assert(C2 >= 0.0f);\n\n \/\/ Compute C3 coefficient.\n const float C3 =\n 0.125f\n * sigma2_009\n * square(4.0f * alpha * beta * RcpPiSquare<float>());\n assert(C3 >= 0.0f);\n\n \/\/ Direct illumination component.\n value = reflectance;\n value *=\n reflectance_multiplier *\n RcpPi<float>() * (\n C1\n + delta_cos_phi * C2 * tan(beta)\n + (1.0f - abs(delta_cos_phi)) * C3 * tan(0.5f * (alpha + beta)));\n\n \/\/ Add interreflection component.\n Spectrum ir = reflectance;\n ir *= ir;\n ir *=\n 0.17f\n * square(reflectance_multiplier)\n * RcpPi<float>()\n * sigma2 \/ (sigma2 + 0.13f)\n * (1.0f - delta_cos_phi * square(2.0f * beta * RcpPi<float>()));\n value += ir;\n\n clamp_low_in_place(value, 0.0f);\n }\n };\n\n typedef BSDFWrapper<OrenNayarBRDFImpl> OrenNayarBRDF;\n}\n\n\n\/\/\n\/\/ OrenNayarBRDFFactory class implementation.\n\/\/\n\nvoid OrenNayarBRDFFactory::release()\n{\n delete this;\n}\n\nconst char* OrenNayarBRDFFactory::get_model() const\n{\n return Model;\n}\n\nDictionary OrenNayarBRDFFactory::get_model_metadata() const\n{\n return\n Dictionary()\n .insert(\"name\", Model)\n .insert(\"label\", \"Oren-Nayar BRDF\");\n}\n\nDictionaryArray OrenNayarBRDFFactory::get_input_metadata() const\n{\n DictionaryArray metadata;\n\n metadata.push_back(\n Dictionary()\n .insert(\"name\", \"reflectance\")\n .insert(\"label\", \"Reflectance\")\n .insert(\"type\", \"colormap\")\n .insert(\"entity_types\",\n Dictionary()\n .insert(\"color\", \"Colors\")\n .insert(\"texture_instance\", \"Texture Instances\"))\n .insert(\"use\", \"required\")\n .insert(\"default\", \"0.5\"));\n\n metadata.push_back(\n Dictionary()\n .insert(\"name\", \"reflectance_multiplier\")\n .insert(\"label\", \"Reflectance Multiplier\")\n .insert(\"type\", \"colormap\")\n .insert(\"entity_types\",\n Dictionary().insert(\"texture_instance\", \"Texture Instances\"))\n .insert(\"use\", \"optional\")\n .insert(\"default\", \"1.0\"));\n\n metadata.push_back(\n Dictionary()\n .insert(\"name\", \"roughness\")\n .insert(\"label\", \"Roughness\")\n .insert(\"type\", \"colormap\")\n .insert(\"entity_types\",\n Dictionary().insert(\"texture_instance\", \"Texture Instances\"))\n .insert(\"use\", \"required\")\n .insert(\"default\", \"0.1\"));\n\n return metadata;\n}\n\nauto_release_ptr<BSDF> OrenNayarBRDFFactory::create(\n const char* name,\n const ParamArray& params) const\n{\n return auto_release_ptr<BSDF>(new OrenNayarBRDF(name, params));\n}\n\n} \/\/ namespace renderer\n<|endoftext|>"} {"text":"<commit_before>\/* bzflag\n * Copyright (c) 1993 - 2004 Tim Riker\n *\n * This package is free software; you can redistribute it and\/or\n * modify it under the terms of the license found in the file\n * named COPYING that should have accompanied this file.\n *\n * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR\n * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED\n * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.\n *\/\n\n\/* common headers *\/\n#include \"common.h\"\n\n\/* interface header *\/\n#include \"WinJoystick.h\"\n\n\/* implementation headers *\/\n#include <mmsystem.h>\n#include \"ErrorHandler.h\"\n#include \"TextUtils.h\"\n\nWinJoystick::WinJoystick()\n{\n}\n\nWinJoystick::~WinJoystick()\n{\n}\n\nvoid\t WinJoystick::initJoystick(const char* joystickName)\n{\n if (strlen(joystickName) > 11)\n return;\n\n if (joystickName[10] == '1')\n JoystickID = JOYSTICKID1;\n else if (joystickName[10] == '2')\n JoystickID = JOYSTICKID2;\n\n JOYINFO joyInfo;\n JOYCAPS joyCaps;\n if ((joyGetPos(JoystickID, &joyInfo) != JOYERR_NOERROR) ||\n (joyGetDevCaps(JoystickID, &joyCaps, sizeof(joyCaps)) != JOYERR_NOERROR)) {\n printError(\"Unable to initialize joystick. Perhaps it is not plugged in?\");\n inited = false;\n return;\n }\n\n xMin = (float)joyCaps.wXmin;\n xMax = (float)joyCaps.wXmax;\n yMin = (float)joyCaps.wYmin;\n yMax = (float)joyCaps.wYmax;\n \n inited = true;\n}\n\nbool\t WinJoystick::joystick() const\n{\n return inited;\n}\n\nvoid\t WinJoystick::getJoy(int& x, int& y) const\n{\n if (!inited)\n return;\n\n JOYINFOEX joyInfo;\n \/\/ we're only interested in position\n joyInfo.dwFlags = JOY_RETURNX | JOY_RETURNY | JOY_USEDEADZONE;\n\n \/\/ check for errors\n if (joyGetPosEx(JoystickID, &joyInfo) != JOYERR_NOERROR) {\n printError(\"Could not get extended info from joystick\");\n return;\n }\n\n \/\/ adjust X and Y to scale\n x = (joyInfo.dwXpos \/ xMax) * 2000 - 1000;\n y = (joyInfo.dwYpos \/ yMax) * 2000 - 1000;\n\n \/\/ ballistic\n x = (x * abs(x)) \/ 1000;\n y = (y * abs(y)) \/ 1000;\n\n}\n\nunsigned long WinJoystick::getJoyButtons() const\n{\n if (!inited)\n return 0;\n\n \/\/ FIXME - Should use joyGetPosEx and JOYINFOEX, to get the rest of the buttons,\n \/\/ but wasn't working for me.\n JOYINFO joyInfo;\n\n \/\/ check for errors\n if (joyGetPos(JoystickID, &joyInfo) != JOYERR_NOERROR) {\n printError(\"Could not get extended info from joystick\");\n return 0;\n }\n\n unsigned long retbuts = joyInfo.wButtons; \n unsigned long buttons = 0;\n if (retbuts & JOY_BUTTON1) buttons = buttons | 0x00001;\n if (retbuts & JOY_BUTTON2) buttons = buttons | 0x00002;\n if (retbuts & JOY_BUTTON3) buttons = buttons | 0x00004;\n if (retbuts & JOY_BUTTON4) buttons = buttons | 0x00008;\n\/* if (retbuts & JOY_BUTTON5) buttons = buttons | 0x00010;\n if (retbuts & JOY_BUTTON6) buttons = buttons | 0x00020;\n if (retbuts & JOY_BUTTON7) buttons = buttons | 0x00040;\n if (retbuts & JOY_BUTTON8) buttons = buttons | 0x00080;\n if (retbuts & JOY_BUTTON9) buttons = buttons | 0x00100;\n if (retbuts & JOY_BUTTON10) buttons = buttons | 0x00200; *\/\n\n return buttons;\n}\n\nvoid\t WinJoystick::getJoyDevices(std::vector<std::string> &list) const\n{\n list.clear();\n if (joyGetNumDevs() != 0) {\n \/\/ we have at least one joystick driver, get the name of both joystick IDs if they exist.\n JOYCAPS joyCaps;\n if (joyGetDevCaps(JOYSTICKID1, &joyCaps, sizeof(joyCaps)) == JOYERR_NOERROR) {\n list.push_back(string_util::format(\"Joystick 1 (%s)\", joyCaps.szOEMVxD));\n }\n if (joyGetDevCaps(JOYSTICKID2, &joyCaps, sizeof(joyCaps)) == JOYERR_NOERROR) {\n list.push_back(string_util::format(\"Joystick 2 (%s)\", joyCaps.szOEMVxD));\n }\n }\n}\n\n\n\n\/\/ Local Variables: ***\n\/\/ mode:C++ ***\n\/\/ tab-width: 8 ***\n\/\/ c-basic-offset: 2 ***\n\/\/ indent-tabs-mode: t ***\n\/\/ End: ***\n\/\/ ex: shiftwidth=2 tabstop=8\n<commit_msg>Make native win joystick recognize \"off\" and turn off, and make it initialize the first time initJoystick is called instead of the second.<commit_after>\/* bzflag\n * Copyright (c) 1993 - 2004 Tim Riker\n *\n * This package is free software; you can redistribute it and\/or\n * modify it under the terms of the license found in the file\n * named COPYING that should have accompanied this file.\n *\n * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR\n * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED\n * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.\n *\/\n\n\/* common headers *\/\n#include \"common.h\"\n\n\/* interface header *\/\n#include \"WinJoystick.h\"\n\n\/* implementation headers *\/\n#include <mmsystem.h>\n#include \"ErrorHandler.h\"\n#include \"TextUtils.h\"\n\nWinJoystick::WinJoystick()\n{\n}\n\nWinJoystick::~WinJoystick()\n{\n}\n\nvoid\t WinJoystick::initJoystick(const char* joystickName)\n{\n inited = false;\n\n if (!strcmp(joystickName, \"off\") || !strcmp(joystickName, \"\")) {\n return;\n }\n\n if (strlen(joystickName) < 11) {\n printError(\"Invalid joystick name.\");\n return;\n }\n\n if (joystickName[10] == '1')\n JoystickID = JOYSTICKID1;\n else if (joystickName[10] == '2')\n JoystickID = JOYSTICKID2;\n\n JOYINFO joyInfo;\n JOYCAPS joyCaps;\n if ((joyGetPos(JoystickID, &joyInfo) != JOYERR_NOERROR) ||\n (joyGetDevCaps(JoystickID, &joyCaps, sizeof(joyCaps)) != JOYERR_NOERROR)) {\n printError(\"Unable to initialize joystick. Perhaps it is not plugged in?\");\n return;\n }\n\n xMin = (float)joyCaps.wXmin;\n xMax = (float)joyCaps.wXmax;\n yMin = (float)joyCaps.wYmin;\n yMax = (float)joyCaps.wYmax;\n \n inited = true;\n}\n\nbool\t WinJoystick::joystick() const\n{\n return inited;\n}\n\nvoid\t WinJoystick::getJoy(int& x, int& y) const\n{\n if (!inited)\n return;\n\n JOYINFOEX joyInfo;\n \/\/ we're only interested in position\n joyInfo.dwFlags = JOY_RETURNX | JOY_RETURNY | JOY_USEDEADZONE;\n\n \/\/ check for errors\n if (joyGetPosEx(JoystickID, &joyInfo) != JOYERR_NOERROR) {\n printError(\"Could not get extended info from joystick\");\n return;\n }\n\n \/\/ adjust X and Y to scale\n x = (joyInfo.dwXpos \/ xMax) * 2000 - 1000;\n y = (joyInfo.dwYpos \/ yMax) * 2000 - 1000;\n\n \/\/ ballistic\n x = (x * abs(x)) \/ 1000;\n y = (y * abs(y)) \/ 1000;\n\n}\n\nunsigned long WinJoystick::getJoyButtons() const\n{\n if (!inited)\n return 0;\n\n \/\/ FIXME - Should use joyGetPosEx and JOYINFOEX, to get the rest of the buttons,\n \/\/ but wasn't working for me.\n JOYINFO joyInfo;\n\n \/\/ check for errors\n if (joyGetPos(JoystickID, &joyInfo) != JOYERR_NOERROR) {\n printError(\"Could not get extended info from joystick\");\n return 0;\n }\n\n unsigned long retbuts = joyInfo.wButtons; \n unsigned long buttons = 0;\n if (retbuts & JOY_BUTTON1) buttons = buttons | 0x00001;\n if (retbuts & JOY_BUTTON2) buttons = buttons | 0x00002;\n if (retbuts & JOY_BUTTON3) buttons = buttons | 0x00004;\n if (retbuts & JOY_BUTTON4) buttons = buttons | 0x00008;\n\/* if (retbuts & JOY_BUTTON5) buttons = buttons | 0x00010;\n if (retbuts & JOY_BUTTON6) buttons = buttons | 0x00020;\n if (retbuts & JOY_BUTTON7) buttons = buttons | 0x00040;\n if (retbuts & JOY_BUTTON8) buttons = buttons | 0x00080;\n if (retbuts & JOY_BUTTON9) buttons = buttons | 0x00100;\n if (retbuts & JOY_BUTTON10) buttons = buttons | 0x00200; *\/\n\n return buttons;\n}\n\nvoid\t WinJoystick::getJoyDevices(std::vector<std::string> &list) const\n{\n list.clear();\n if (joyGetNumDevs() != 0) {\n \/\/ we have at least one joystick driver, get the name of both joystick IDs if they exist.\n JOYCAPS joyCaps;\n if (joyGetDevCaps(JOYSTICKID1, &joyCaps, sizeof(joyCaps)) == JOYERR_NOERROR) {\n list.push_back(string_util::format(\"Joystick 1 (%s)\", joyCaps.szOEMVxD));\n }\n if (joyGetDevCaps(JOYSTICKID2, &joyCaps, sizeof(joyCaps)) == JOYERR_NOERROR) {\n list.push_back(string_util::format(\"Joystick 2 (%s)\", joyCaps.szOEMVxD));\n }\n }\n}\n\n\n\n\/\/ Local Variables: ***\n\/\/ mode:C++ ***\n\/\/ tab-width: 8 ***\n\/\/ c-basic-offset: 2 ***\n\/\/ indent-tabs-mode: t ***\n\/\/ End: ***\n\/\/ ex: shiftwidth=2 tabstop=8\n<|endoftext|>"} {"text":"<commit_before>#include \"interface\/usb.h\"\n#include <stdio.h>\n#include \"util\/log.h\"\n#include \"util\/bytebuffer.h\"\n#include \"gpio.h\"\n#include \"usb_config.h\"\n#include \"emqueue.h\"\n\n#include \"LPC17xx.h\"\n#include \"lpc17xx_pinsel.h\"\n\nextern \"C\" {\n#include \"bsp.h\"\n}\n\n#define VBUS_PORT 1\n#define VBUS_PIN 30\n#define VBUS_FUNCNUM 2\n\n#define USB_DM_PORT 0\n#define USB_DM_PIN 30\n#define USB_DM_FUNCNUM 1\n\n#define USB_HOST_DETECT_INACTIVE_VALUE 400\n#define USB_HOST_DETECT_ACTIVE_VALUE 50\n\n#define USB_CONNECT_PORT 2\n#define USB_CONNECT_PIN 9\n\nnamespace gpio = openxc::gpio;\n\nusing openxc::util::log::debug;\nusing openxc::interface::usb::UsbDevice;\nusing openxc::interface::usb::UsbEndpoint;\nusing openxc::interface::usb::UsbEndpointDirection;\nusing openxc::util::bytebuffer::processQueue;\nusing openxc::gpio::GPIO_VALUE_HIGH;\nusing openxc::gpio::GPIO_VALUE_LOW;\n\nextern UsbDevice USB_DEVICE;\nextern bool handleControlRequest(uint8_t, uint8_t[], int);\n\nvoid configureEndpoints() {\n for(int i = 0; i < ENDPOINT_COUNT; i++) {\n UsbEndpoint* endpoint = &USB_DEVICE.endpoints[i];\n Endpoint_ConfigureEndpoint(endpoint->address,\n EP_TYPE_BULK,\n endpoint->direction == UsbEndpointDirection::USB_ENDPOINT_DIRECTION_OUT ?\n ENDPOINT_DIR_OUT : ENDPOINT_DIR_IN,\n endpoint->size, ENDPOINT_BANK_DOUBLE);\n }\n}\n\nextern \"C\" {\n\nvoid EVENT_USB_Device_Disconnect() {\n debug(\"USB no longer detected - marking unconfigured\");\n USB_DEVICE.configured = false;\n}\n\nvoid EVENT_USB_Device_ControlRequest() {\n if(!(Endpoint_IsSETUPReceived())) {\n return;\n }\n\n QUEUE_TYPE(uint8_t) payloadQueue;\n QUEUE_INIT(uint8_t, &payloadQueue);\n debug(\"Rq: 0x%x, length: 0x%x\", USB_ControlRequest.bRequest,\n USB_ControlRequest.wLength);\n\n \/\/ Don't try and read payload of system-level control requests\n if((USB_ControlRequest.bmRequestType >> 7 == 0) &&\n USB_ControlRequest.bRequest >= 0x80) {\n Endpoint_ClearSETUP();\n\n for(int i = 0; i < USB_ControlRequest.wLength; i++) {\n while (!(Endpoint_IsOUTReceived()));\n if(!QUEUE_PUSH(uint8_t, &payloadQueue, Endpoint_Read_8())) {\n debug(\"Dropped control command write from host -- queue is full\");\n break;\n }\n }\n\n Endpoint_ClearOUT();\n Endpoint_ClearStatusStage();\n }\n\n int length = QUEUE_LENGTH(uint8_t, &payloadQueue);\n uint8_t snapshot[length];\n if(length > 0) {\n QUEUE_SNAPSHOT(uint8_t, &payloadQueue, snapshot, length);\n }\n\n handleControlRequest(USB_ControlRequest.bRequest, snapshot, length);\n}\n\nvoid EVENT_USB_Device_ConfigurationChanged(void) {\n USB_DEVICE.configured = false;\n configureEndpoints();\n debug(\"USB configured\");\n USB_DEVICE.configured = true;\n}\n\n}\n\n\/* Private: Flush any queued data out to the USB host. *\/\nstatic void flushQueueToHost(UsbDevice* usbDevice, UsbEndpoint* endpoint) {\n if(!usbDevice->configured || QUEUE_EMPTY(uint8_t, &endpoint->queue)) {\n return;\n }\n\n uint8_t previousEndpoint = Endpoint_GetCurrentEndpoint();\n Endpoint_SelectEndpoint(endpoint->address);\n if(Endpoint_IsINReady()) {\n \/\/ get bytes from transmit FIFO into intermediate buffer\n int byteCount = 0;\n while(!QUEUE_EMPTY(uint8_t, &endpoint->queue)\n && byteCount < USB_SEND_BUFFER_SIZE) {\n endpoint->sendBuffer[byteCount++] = QUEUE_POP(uint8_t,\n &endpoint->queue);\n }\n\n if(byteCount > 0) {\n Endpoint_Write_Stream_LE(endpoint->sendBuffer, byteCount, NULL);\n }\n Endpoint_ClearIN();\n }\n Endpoint_SelectEndpoint(previousEndpoint);\n}\n\n\/* Private: Detect if USB VBUS is active.\n *\n * This isn't useful if there's no diode between an external 12v\/9v power supply\n * (e.g. vehicle power from OBD-II) and the 5v rail, because then VBUS high when\n * the power is powered on regardless of the status of USB. In that situation,\n * you can fall back to the usbHostDetected() function instead.\n *\n * Returns true if VBUS is high.\n *\/\nbool vbusDetected() {\n return gpio::getValue(VBUS_PORT, VBUS_PIN) != GPIO_VALUE_LOW;\n}\n\n\/* Private: Detect if a USB host is actually attached, regardless of VBUS.\n *\n * This is a bit hacky, as normally you should rely on VBUS to detect if USB is\n * connected. See vbusDetected() for reasons why we need this workaround on the\n * current prototype.\n *\n * Returns true of there is measurable activity on the D- USB line.\n *\/\nbool usbHostDetected(UsbDevice* usbDevice) {\n static int debounce = 0;\n static float average = USB_HOST_DETECT_INACTIVE_VALUE \/ 2;\n\n if(gpio::getValue(USB_DM_PORT, USB_DM_PIN) == GPIO_VALUE_LOW) {\n ++debounce;\n } else {\n average = average * .9 + debounce * .1;\n debounce = 0;\n }\n\n if(!usbDevice->configured && average < USB_HOST_DETECT_ACTIVE_VALUE) {\n EVENT_USB_Device_ConfigurationChanged();\n }\n\n if(average > USB_HOST_DETECT_INACTIVE_VALUE) {\n debounce = 0;\n average = USB_HOST_DETECT_INACTIVE_VALUE \/ 2;\n return false;\n }\n return true;\n}\n\n\/* Private: Configure I\/O pins used to detect if USB is connected to a host. *\/\nvoid configureUsbDetection() {\n PINSEL_CFG_Type vbusPinConfig;\n vbusPinConfig.Funcnum = VBUS_FUNCNUM;\n vbusPinConfig.Portnum = VBUS_PORT;\n vbusPinConfig.Pinnum = VBUS_PIN;\n vbusPinConfig.Pinmode = PINSEL_PINMODE_TRISTATE;\n PINSEL_ConfigPin(&vbusPinConfig);\n\n PINSEL_CFG_Type hostDetectPinConfig;\n hostDetectPinConfig.Funcnum = USB_DM_FUNCNUM;\n hostDetectPinConfig.Portnum = USB_DM_PORT;\n hostDetectPinConfig.Pinnum = USB_DM_PIN;\n hostDetectPinConfig.Pinmode = PINSEL_PINMODE_TRISTATE;\n PINSEL_ConfigPin(&hostDetectPinConfig);\n}\n\nvoid openxc::interface::usb::sendControlMessage(uint8_t* data, uint8_t length) {\n uint8_t previousEndpoint = Endpoint_GetCurrentEndpoint();\n Endpoint_SelectEndpoint(ENDPOINT_CONTROLEP);\n\n Endpoint_ClearSETUP();\n Endpoint_Write_Control_Stream_LE(data, length);\n \/\/ TODO I think it needs to be ClearIN since this is a device -> host\n \/\/ request, but a simple switch breaks it\n Endpoint_ClearOUT();\n\n Endpoint_SelectEndpoint(previousEndpoint);\n}\n\n\nvoid openxc::interface::usb::processSendQueue(UsbDevice* usbDevice) {\n USB_USBTask();\n\n if(!usbDevice->configured) {\n usbHostDetected(usbDevice);\n }\n\n if(usbDevice->configured) {\n if((USB_DeviceState != DEVICE_STATE_Configured || !vbusDetected())\n || !usbHostDetected(usbDevice)) {\n \/\/ On Windows the USB device will be configured when plugged in for\n \/\/ the first time, regardless of if you are actively using it in an\n \/\/ application. Windows will *not* send the USB configured event\n \/\/ when an application connects.\n \/\/\n \/\/ On Linux and Mac, the USB configured event triggers each time a\n \/\/ new connection is made to the device.\n \/\/\n \/\/ This means that if vbus is high (i.e. USB *might* be connected),\n \/\/ that's the only time we should check the usbHostDetected()\n \/\/ workaround. If we call that on Windows when USB is attached, it\n \/\/ will *unconfigure* the USB device from the VI side but not\n \/\/ reconfigure it until you disconnect and reconnect the device to\n \/\/ the PC! If the debounce value is small (which is ideal...) that\n \/\/ could happen even before your app has a chance to load the\n \/\/ device.\n EVENT_USB_Device_Disconnect();\n } else {\n for(int i = 0; i < ENDPOINT_COUNT; i++) {\n UsbEndpoint* endpoint = &usbDevice->endpoints[i];\n if(endpoint->direction == UsbEndpointDirection::USB_ENDPOINT_DIRECTION_IN) {\n flushQueueToHost(usbDevice, endpoint);\n }\n }\n }\n }\n}\n\nvoid openxc::interface::usb::initialize(UsbDevice* usbDevice) {\n usb::initializeCommon(usbDevice);\n USB_Init();\n ::USB_Connect();\n configureUsbDetection();\n}\n\nvoid openxc::interface::usb::read(UsbDevice* device, UsbEndpoint* endpoint,\n bool (*callback)(uint8_t*)) {\n uint8_t previousEndpoint = Endpoint_GetCurrentEndpoint();\n Endpoint_SelectEndpoint(endpoint->address);\n\n while(Endpoint_IsOUTReceived()) {\n while(Endpoint_BytesInEndpoint()) {\n if(!QUEUE_PUSH(uint8_t, &endpoint->queue, Endpoint_Read_8())) {\n debug(\"Dropped write from host -- queue is full\");\n }\n }\n processQueue(&endpoint->queue, callback);\n Endpoint_ClearOUT();\n }\n Endpoint_SelectEndpoint(previousEndpoint);\n}\n\nvoid openxc::interface::usb::deinitialize(UsbDevice* usbDevice) {\n usb::initializeCommon(usbDevice);\n \/\/ Turn off USB connection status LED\n gpio::setValue(USB_CONNECT_PORT, USB_CONNECT_PIN, GPIO_VALUE_HIGH);\n}\n<commit_msg>Fix reading multiple USB frames for a single control transfer.<commit_after>#include \"interface\/usb.h\"\n#include <stdio.h>\n#include \"util\/log.h\"\n#include \"util\/bytebuffer.h\"\n#include \"gpio.h\"\n#include \"usb_config.h\"\n#include \"emqueue.h\"\n\n#include \"LPC17xx.h\"\n#include \"lpc17xx_pinsel.h\"\n\nextern \"C\" {\n#include \"bsp.h\"\n}\n\n#define VBUS_PORT 1\n#define VBUS_PIN 30\n#define VBUS_FUNCNUM 2\n\n#define USB_DM_PORT 0\n#define USB_DM_PIN 30\n#define USB_DM_FUNCNUM 1\n\n#define USB_HOST_DETECT_INACTIVE_VALUE 400\n#define USB_HOST_DETECT_ACTIVE_VALUE 50\n\n#define USB_CONNECT_PORT 2\n#define USB_CONNECT_PIN 9\n\nnamespace gpio = openxc::gpio;\n\nusing openxc::util::log::debug;\nusing openxc::interface::usb::UsbDevice;\nusing openxc::interface::usb::UsbEndpoint;\nusing openxc::interface::usb::UsbEndpointDirection;\nusing openxc::util::bytebuffer::processQueue;\nusing openxc::gpio::GPIO_VALUE_HIGH;\nusing openxc::gpio::GPIO_VALUE_LOW;\n\nextern UsbDevice USB_DEVICE;\nextern bool handleControlRequest(uint8_t, uint8_t[], int);\n\nvoid configureEndpoints() {\n for(int i = 0; i < ENDPOINT_COUNT; i++) {\n UsbEndpoint* endpoint = &USB_DEVICE.endpoints[i];\n Endpoint_ConfigureEndpoint(endpoint->address,\n EP_TYPE_BULK,\n endpoint->direction == UsbEndpointDirection::USB_ENDPOINT_DIRECTION_OUT ?\n ENDPOINT_DIR_OUT : ENDPOINT_DIR_IN,\n endpoint->size, ENDPOINT_BANK_DOUBLE);\n }\n}\n\nextern \"C\" {\n\nvoid EVENT_USB_Device_Disconnect() {\n debug(\"USB no longer detected - marking unconfigured\");\n USB_DEVICE.configured = false;\n}\n\nvoid EVENT_USB_Device_ControlRequest() {\n if(!(Endpoint_IsSETUPReceived())) {\n return;\n }\n\n QUEUE_TYPE(uint8_t) payloadQueue;\n QUEUE_INIT(uint8_t, &payloadQueue);\n\n \/\/ Don't try and read payload of system-level control requests\n if((USB_ControlRequest.bmRequestType >> 7 == 0) &&\n USB_ControlRequest.bRequest >= 0x80) {\n Endpoint_ClearSETUP();\n\n int bytesReceived = 0;\n while(bytesReceived < USB_ControlRequest.wLength) {\n \/\/ TODO could this get stuck?\n while(!Endpoint_IsOUTReceived());\n while(Endpoint_BytesInEndpoint()) {\n uint8_t byte = Endpoint_Read_8();\n if(!QUEUE_PUSH(uint8_t, &payloadQueue, byte)) {\n debug(\"Dropped control command write from host -- queue is full\");\n break;\n }\n ++bytesReceived;\n }\n Endpoint_ClearOUT();\n }\n\n Endpoint_ClearStatusStage();\n }\n\n int length = QUEUE_LENGTH(uint8_t, &payloadQueue);\n uint8_t snapshot[length];\n if(length > 0) {\n QUEUE_SNAPSHOT(uint8_t, &payloadQueue, snapshot, length);\n }\n\n handleControlRequest(USB_ControlRequest.bRequest, snapshot, length);\n}\n\nvoid EVENT_USB_Device_ConfigurationChanged(void) {\n USB_DEVICE.configured = false;\n configureEndpoints();\n debug(\"USB configured\");\n USB_DEVICE.configured = true;\n}\n\n}\n\n\/* Private: Flush any queued data out to the USB host. *\/\nstatic void flushQueueToHost(UsbDevice* usbDevice, UsbEndpoint* endpoint) {\n if(!usbDevice->configured || QUEUE_EMPTY(uint8_t, &endpoint->queue)) {\n return;\n }\n\n uint8_t previousEndpoint = Endpoint_GetCurrentEndpoint();\n Endpoint_SelectEndpoint(endpoint->address);\n if(Endpoint_IsINReady()) {\n \/\/ get bytes from transmit FIFO into intermediate buffer\n int byteCount = 0;\n while(!QUEUE_EMPTY(uint8_t, &endpoint->queue)\n && byteCount < USB_SEND_BUFFER_SIZE) {\n endpoint->sendBuffer[byteCount++] = QUEUE_POP(uint8_t,\n &endpoint->queue);\n }\n\n if(byteCount > 0) {\n Endpoint_Write_Stream_LE(endpoint->sendBuffer, byteCount, NULL);\n }\n Endpoint_ClearIN();\n }\n Endpoint_SelectEndpoint(previousEndpoint);\n}\n\n\/* Private: Detect if USB VBUS is active.\n *\n * This isn't useful if there's no diode between an external 12v\/9v power supply\n * (e.g. vehicle power from OBD-II) and the 5v rail, because then VBUS high when\n * the power is powered on regardless of the status of USB. In that situation,\n * you can fall back to the usbHostDetected() function instead.\n *\n * Returns true if VBUS is high.\n *\/\nbool vbusDetected() {\n return gpio::getValue(VBUS_PORT, VBUS_PIN) != GPIO_VALUE_LOW;\n}\n\n\/* Private: Detect if a USB host is actually attached, regardless of VBUS.\n *\n * This is a bit hacky, as normally you should rely on VBUS to detect if USB is\n * connected. See vbusDetected() for reasons why we need this workaround on the\n * current prototype.\n *\n * Returns true of there is measurable activity on the D- USB line.\n *\/\nbool usbHostDetected(UsbDevice* usbDevice) {\n static int debounce = 0;\n static float average = USB_HOST_DETECT_INACTIVE_VALUE \/ 2;\n\n if(gpio::getValue(USB_DM_PORT, USB_DM_PIN) == GPIO_VALUE_LOW) {\n ++debounce;\n } else {\n average = average * .9 + debounce * .1;\n debounce = 0;\n }\n\n if(!usbDevice->configured && average < USB_HOST_DETECT_ACTIVE_VALUE) {\n EVENT_USB_Device_ConfigurationChanged();\n }\n\n if(average > USB_HOST_DETECT_INACTIVE_VALUE) {\n debounce = 0;\n average = USB_HOST_DETECT_INACTIVE_VALUE \/ 2;\n return false;\n }\n return true;\n}\n\n\/* Private: Configure I\/O pins used to detect if USB is connected to a host. *\/\nvoid configureUsbDetection() {\n PINSEL_CFG_Type vbusPinConfig;\n vbusPinConfig.Funcnum = VBUS_FUNCNUM;\n vbusPinConfig.Portnum = VBUS_PORT;\n vbusPinConfig.Pinnum = VBUS_PIN;\n vbusPinConfig.Pinmode = PINSEL_PINMODE_TRISTATE;\n PINSEL_ConfigPin(&vbusPinConfig);\n\n PINSEL_CFG_Type hostDetectPinConfig;\n hostDetectPinConfig.Funcnum = USB_DM_FUNCNUM;\n hostDetectPinConfig.Portnum = USB_DM_PORT;\n hostDetectPinConfig.Pinnum = USB_DM_PIN;\n hostDetectPinConfig.Pinmode = PINSEL_PINMODE_TRISTATE;\n PINSEL_ConfigPin(&hostDetectPinConfig);\n}\n\nvoid openxc::interface::usb::sendControlMessage(uint8_t* data, uint8_t length) {\n uint8_t previousEndpoint = Endpoint_GetCurrentEndpoint();\n Endpoint_SelectEndpoint(ENDPOINT_CONTROLEP);\n\n Endpoint_ClearSETUP();\n Endpoint_Write_Control_Stream_LE(data, length);\n \/\/ TODO I think it needs to be ClearIN since this is a device -> host\n \/\/ request, but a simple switch breaks it\n Endpoint_ClearOUT();\n\n Endpoint_SelectEndpoint(previousEndpoint);\n}\n\n\nvoid openxc::interface::usb::processSendQueue(UsbDevice* usbDevice) {\n USB_USBTask();\n\n if(!usbDevice->configured) {\n usbHostDetected(usbDevice);\n }\n\n if(usbDevice->configured) {\n if((USB_DeviceState != DEVICE_STATE_Configured || !vbusDetected())\n || !usbHostDetected(usbDevice)) {\n \/\/ On Windows the USB device will be configured when plugged in for\n \/\/ the first time, regardless of if you are actively using it in an\n \/\/ application. Windows will *not* send the USB configured event\n \/\/ when an application connects.\n \/\/\n \/\/ On Linux and Mac, the USB configured event triggers each time a\n \/\/ new connection is made to the device.\n \/\/\n \/\/ This means that if vbus is high (i.e. USB *might* be connected),\n \/\/ that's the only time we should check the usbHostDetected()\n \/\/ workaround. If we call that on Windows when USB is attached, it\n \/\/ will *unconfigure* the USB device from the VI side but not\n \/\/ reconfigure it until you disconnect and reconnect the device to\n \/\/ the PC! If the debounce value is small (which is ideal...) that\n \/\/ could happen even before your app has a chance to load the\n \/\/ device.\n EVENT_USB_Device_Disconnect();\n } else {\n for(int i = 0; i < ENDPOINT_COUNT; i++) {\n UsbEndpoint* endpoint = &usbDevice->endpoints[i];\n if(endpoint->direction == UsbEndpointDirection::USB_ENDPOINT_DIRECTION_IN) {\n flushQueueToHost(usbDevice, endpoint);\n }\n }\n }\n }\n}\n\nvoid openxc::interface::usb::initialize(UsbDevice* usbDevice) {\n usb::initializeCommon(usbDevice);\n USB_Init();\n ::USB_Connect();\n configureUsbDetection();\n}\n\nvoid openxc::interface::usb::read(UsbDevice* device, UsbEndpoint* endpoint,\n bool (*callback)(uint8_t*)) {\n uint8_t previousEndpoint = Endpoint_GetCurrentEndpoint();\n Endpoint_SelectEndpoint(endpoint->address);\n\n while(Endpoint_IsOUTReceived()) {\n while(Endpoint_BytesInEndpoint()) {\n if(!QUEUE_PUSH(uint8_t, &endpoint->queue, Endpoint_Read_8())) {\n debug(\"Dropped write from host -- queue is full\");\n }\n }\n processQueue(&endpoint->queue, callback);\n Endpoint_ClearOUT();\n }\n Endpoint_SelectEndpoint(previousEndpoint);\n}\n\nvoid openxc::interface::usb::deinitialize(UsbDevice* usbDevice) {\n usb::initializeCommon(usbDevice);\n \/\/ Turn off USB connection status LED\n gpio::setValue(USB_CONNECT_PORT, USB_CONNECT_PIN, GPIO_VALUE_HIGH);\n}\n<|endoftext|>"} {"text":"<commit_before>\/* Copyright 2010 Thomas McGuire <mcguire@kde.org>\n Copyright 2011 Alexander Potashev <aspotashev@gmail.com>\n\n This library is free software; you can redistribute it and\/or modify\n it under the terms of the GNU Library General Public License as published\n by the Free Software Foundation; either version 2 of the License or\n ( at your option ) version 3 or, at the discretion of KDE e.V.\n ( which shall act as a proxy as in section 14 of the GPLv3 ), any later version.\n\n This library is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n Library General Public License for more details.\n\n You should have received a copy of the GNU Library General Public License\n along with this library; see the file COPYING.LIB. If not, write to\n the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,\n Boston, MA 02110-1301, USA.\n*\/\n#include \"userinfojob.moc\"\n\n#include <qjson\/qobjecthelper.h>\n#include <KIO\/Job>\n#include <KDebug>\n#include <KLocale>\n\nnamespace Vkontakte\n{\n\nclass UserInfoJob::Private\n{\npublic:\n QList<UserInfoPtr> userInfo;\n QStringList fields;\n};\n\n\/\/ http:\/\/vk.com\/dev\/users.get\nUserInfoJob::UserInfoJob(const QString &accessToken)\n : VkontakteJob(accessToken, \"users.get\")\n , d(new Private)\n{\n \/\/ The complete list of fields\n setFields(UserInfo::allQueryFields());\n\n \/\/ TODO: support \"counters\" request (probably in another KJob)\n}\n\nUserInfoJob::UserInfoJob(const QString &accessToken, int uid)\n : VkontakteJob(accessToken, \"users.get\")\n , d(new Private)\n{\n setFields(UserInfo::allQueryFields());\n addQueryItem(\"user_ids\", QString::number(uid));\n}\n\nUserInfoJob::UserInfoJob(const QString &accessToken, const QIntList &uids)\n : VkontakteJob(accessToken, \"users.get\")\n , d(new Private)\n{\n setFields(UserInfo::allQueryFields());\n addQueryItem(\"user_ids\", uids.join());\n\n \/\/ TODO: make this working for more than 1000 uids\n \/\/ (\"users.get\" allows requesting only 1000 users at once)\n}\n\nUserInfoJob::~UserInfoJob()\n{\n delete d;\n}\n\nQList<UserInfoPtr> UserInfoJob::userInfo() const\n{\n return d->userInfo;\n}\n\nvoid UserInfoJob::setFields(const QStringList &fields)\n{\n d->fields = fields;\n}\n\nvoid UserInfoJob::prepareQueryItems()\n{\n if (!d->fields.isEmpty())\n addQueryItem(\"fields\", d->fields.join(\",\"));\n}\n\nUserInfoPtr UserInfoJob::handleSingleData(const QVariant &data)\n{\n UserInfoPtr userInfo = UserInfoPtr(new UserInfo());\n QJson::QObjectHelper::qvariant2qobject(data.toMap(), userInfo.data());\n return userInfo;\n}\n\nvoid UserInfoJob::handleData(const QVariant &data)\n{\n foreach(const QVariant &item, data.toList())\n d->userInfo.append(handleSingleData(item));\n}\n\n} \/* namespace Vkontakte *\/\n<commit_msg>UserInfoJob: Add comments<commit_after>\/* Copyright 2010 Thomas McGuire <mcguire@kde.org>\n Copyright 2011 Alexander Potashev <aspotashev@gmail.com>\n\n This library is free software; you can redistribute it and\/or modify\n it under the terms of the GNU Library General Public License as published\n by the Free Software Foundation; either version 2 of the License or\n ( at your option ) version 3 or, at the discretion of KDE e.V.\n ( which shall act as a proxy as in section 14 of the GPLv3 ), any later version.\n\n This library is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n Library General Public License for more details.\n\n You should have received a copy of the GNU Library General Public License\n along with this library; see the file COPYING.LIB. If not, write to\n the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,\n Boston, MA 02110-1301, USA.\n*\/\n#include \"userinfojob.moc\"\n\n#include <qjson\/qobjecthelper.h>\n#include <KIO\/Job>\n#include <KDebug>\n#include <KLocale>\n\nnamespace Vkontakte\n{\n\nclass UserInfoJob::Private\n{\npublic:\n QList<UserInfoPtr> userInfo;\n QStringList fields;\n};\n\n\/\/ http:\/\/vk.com\/dev\/users.get\nUserInfoJob::UserInfoJob(const QString &accessToken)\n : VkontakteJob(accessToken, \"users.get\")\n , d(new Private)\n{\n \/\/ The complete list of fields\n setFields(UserInfo::allQueryFields()); \/\/ TODO: do not pull extra fields by default\n\n \/\/ TODO: support \"counters\" request (probably in another KJob)\n}\n\nUserInfoJob::UserInfoJob(const QString &accessToken, int uid)\n : VkontakteJob(accessToken, \"users.get\")\n , d(new Private)\n{\n setFields(UserInfo::allQueryFields()); \/\/ TODO: do not pull extra fields by default\n addQueryItem(\"user_ids\", QString::number(uid));\n}\n\nUserInfoJob::UserInfoJob(const QString &accessToken, const QIntList &uids)\n : VkontakteJob(accessToken, \"users.get\")\n , d(new Private)\n{\n setFields(UserInfo::allQueryFields()); \/\/ TODO: do not pull extra fields by default\n addQueryItem(\"user_ids\", uids.join());\n\n \/\/ TODO: make this working for more than 1000 uids\n \/\/ (\"users.get\" allows requesting only 1000 users at once)\n}\n\nUserInfoJob::~UserInfoJob()\n{\n delete d;\n}\n\nQList<UserInfoPtr> UserInfoJob::userInfo() const\n{\n return d->userInfo;\n}\n\nvoid UserInfoJob::setFields(const QStringList &fields)\n{\n d->fields = fields;\n}\n\nvoid UserInfoJob::prepareQueryItems()\n{\n if (!d->fields.isEmpty())\n addQueryItem(\"fields\", d->fields.join(\",\"));\n}\n\nUserInfoPtr UserInfoJob::handleSingleData(const QVariant &data)\n{\n UserInfoPtr userInfo = UserInfoPtr(new UserInfo());\n QJson::QObjectHelper::qvariant2qobject(data.toMap(), userInfo.data());\n return userInfo;\n}\n\nvoid UserInfoJob::handleData(const QVariant &data)\n{\n foreach(const QVariant &item, data.toList())\n d->userInfo.append(handleSingleData(item));\n}\n\n} \/* namespace Vkontakte *\/\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright 2017 Pavel Bludov <pbludov@gmail.com>\n *\n * This program is free software; you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License along\n * with this program; if not, write to the Free Software Foundation, Inc.,\n * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.\n *\/\n\n#include \"qhiddevice.h\"\n#include \"qhiddevice_hidapi.h\"\n\n#include <QDebug>\n\n#include <errno.h>\n\n#ifdef WITH_LIBUSB_1_0\n#include <libusb.h>\n\nstatic bool findUsagePage(int usagePage, const uint8_t *desc, size_t size)\n{\n unsigned int i = 0;\n int dataLen, keySize;\n\n while (i < size)\n {\n int key = desc[i];\n\n if ((key & 0xf0) == 0xf0)\n {\n \/* This is a Long Item. The next byte contains the\n length of the data section (value) for this key.\n See the HID specification, version 1.11, section\n 6.2.2.3, titled \"Long Items.\" *\/\n dataLen = i + 1 < size ? desc[i + 1] : 0;\n keySize = 3;\n }\n else\n {\n \/* This is a Short Item. The bottom two bits of the\n key contain the size code for the data section\n (value) for this key. Refer to the HID\n specification, version 1.11, section 6.2.2.2,\n titled \"Short Items.\" *\/\n dataLen = key & 0x3;\n if (dataLen == 3)\n ++dataLen; \/\/ 0,1,2,4\n keySize = 1;\n }\n\n if ((key & 0xfc) == 0x04)\n {\n if (i + dataLen >= size)\n {\n \/\/ Truncated report?\n return false;\n }\n\n int page = 0;\n for (int offset = dataLen; offset > 0; --offset)\n {\n page <<= 8;\n page |= desc[i + offset];\n }\n\n if (page == usagePage)\n return true;\n }\n\n \/\/ Skip over this key and it's associated data.\n i += dataLen + keySize;\n }\n\n return false;\n}\n\nstatic void hidapiMissingFeatures(\n int vendorId, int deviceId, int usagePage, int *interfaceNumber, int *inBufferLength, int *outBufferLength)\n{\n libusb_context *ctx = nullptr;\n int rc = libusb_init(&ctx);\n if (LIBUSB_SUCCESS != rc)\n {\n qWarning() << \"libusb_init failed\" << rc << libusb_error_name(rc);\n return;\n }\n\n libusb_device **devs;\n auto count = libusb_get_device_list(ctx, &devs);\n\n for (ssize_t i = 0; i < count; ++i)\n {\n auto dev = devs[i];\n libusb_device_descriptor desc;\n\n if (libusb_get_device_descriptor(dev, &desc) < 0)\n continue;\n\n if (desc.idVendor != vendorId || desc.idProduct != deviceId)\n continue;\n\n libusb_config_descriptor *confDesc = nullptr;\n\n if (libusb_get_active_config_descriptor(dev, &confDesc) < 0)\n continue;\n\n libusb_device_handle *handle;\n if (libusb_open(dev, &handle) < 0)\n continue;\n\n unsigned char buffer[256];\n for (int iface = 0; iface < confDesc->bNumInterfaces; ++iface)\n {\n bool detached = false;\n bool match = false;\n\n rc = libusb_kernel_driver_active(handle, iface);\n if (rc == 1)\n {\n rc = libusb_detach_kernel_driver(handle, iface);\n if (rc < 0)\n {\n qWarning() << \"Failed to detach kernel driver\" << rc << libusb_error_name(rc);\n continue;\n }\n detached = true;\n }\n\n if (libusb_claim_interface(handle, iface) >= 0)\n {\n \/\/ Get the HID Report Descriptor.\n rc = libusb_control_transfer(handle, LIBUSB_ENDPOINT_IN | LIBUSB_RECIPIENT_INTERFACE,\n LIBUSB_REQUEST_GET_DESCRIPTOR, LIBUSB_DT_REPORT << 8, iface, buffer, sizeof(buffer), 1000);\n\n if (rc < 0)\n {\n qWarning() << \"Failed to read HID report descriptor\" << rc << libusb_error_name(rc);\n }\n else\n {\n match = findUsagePage(usagePage, buffer, rc);\n }\n\n libusb_release_interface(handle, iface);\n }\n\n if (detached)\n {\n \/\/ Re-attach kernel driver if necessary.\n rc = libusb_attach_kernel_driver(handle, iface);\n if (rc < 0)\n {\n qWarning() << \"Failed to re-attach kernel driver\" << rc << libusb_error_name(rc);\n }\n }\n\n if (!match)\n continue;\n\n *interfaceNumber = iface;\n auto interface = confDesc->interface[iface];\n\n for (int ifIdx = 0; ifIdx < interface.num_altsetting; ++ifIdx)\n {\n auto intfDesc = interface.altsetting[ifIdx];\n\n for (int epIdx = 0; epIdx < intfDesc.bNumEndpoints; ++epIdx)\n {\n auto ep = intfDesc.endpoint[epIdx];\n\n if ((ep.bEndpointAddress & LIBUSB_ENDPOINT_DIR_MASK) == LIBUSB_ENDPOINT_IN)\n *inBufferLength = ep.wMaxPacketSize;\n else if ((ep.bEndpointAddress & LIBUSB_ENDPOINT_DIR_MASK) == LIBUSB_ENDPOINT_OUT)\n *outBufferLength = ep.wMaxPacketSize;\n }\n }\n\n break;\n }\n libusb_close(handle);\n\n libusb_free_config_descriptor(confDesc);\n break;\n }\n\n libusb_free_device_list(devs, 1);\n libusb_exit(ctx);\n}\n#endif\n\nQHIDDevicePrivate::QHIDDevicePrivate(QHIDDevice *q_ptr, int vendorId, int deviceId, int usagePage)\n : device(nullptr)\n , q_ptr(q_ptr)\n{\n if (hid_init() != 0)\n {\n qWarning() << \"hid_init failed, error\" << errno;\n return;\n }\n\n int interfaceNumber = -1;\n#ifdef WITH_LIBUSB_1_0\n hidapiMissingFeatures(\n vendorId, deviceId, usagePage, &interfaceNumber, &q_ptr->inputBufferLength, &q_ptr->outputBufferLength);\n#endif\n auto devices = hid_enumerate(vendorId, deviceId);\n\n for (auto dev = devices; dev != nullptr; dev = dev->next)\n {\n if ((dev->usage_page > 0 && dev->usage_page == usagePage)\n || (dev->interface_number >= 0 && dev->interface_number == interfaceNumber))\n {\n device = hid_open_path(dev->path);\n\n if (device != nullptr)\n {\n break;\n }\n\n qWarning() << \"Failed to open\" << dev->path << \"error\" << errno;\n }\n }\n\n hid_free_enumeration(devices);\n\n if (device == nullptr)\n {\n qWarning() << \"No such device\" << vendorId << deviceId << usagePage;\n }\n}\n\nQHIDDevicePrivate::~QHIDDevicePrivate()\n{\n if (device)\n {\n hid_close(device);\n device = nullptr;\n }\n\n hid_exit();\n}\n\nbool QHIDDevicePrivate::isValid() const\n{\n return !!device;\n}\n\nint QHIDDevicePrivate::sendFeatureReport(const char *buffer, int length)\n{\n return device == nullptr ? -1 : hid_send_feature_report(device, (const unsigned char *)buffer, length);\n}\n\nint QHIDDevicePrivate::getFeatureReport(char *buffer, int length)\n{\n return device == nullptr ? -1 : hid_get_feature_report(device, (unsigned char *)buffer, length);\n}\n\nint QHIDDevicePrivate::write(const char *buffer, int length)\n{\n return hid_write(device, (const unsigned char *)buffer, length);\n}\n\nint QHIDDevicePrivate::read(char *buffer, int length)\n{\n return hid_read_timeout(device, (unsigned char *)buffer, length, 30000);\n}\n<commit_msg>Do not reattach the kernel driver for requested interface<commit_after>\/*\n * Copyright 2017 Pavel Bludov <pbludov@gmail.com>\n *\n * This program is free software; you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License along\n * with this program; if not, write to the Free Software Foundation, Inc.,\n * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.\n *\/\n\n#include \"qhiddevice.h\"\n#include \"qhiddevice_hidapi.h\"\n\n#include <QDebug>\n\n#include <errno.h>\n\n#ifdef WITH_LIBUSB_1_0\n#include <libusb.h>\n\nstatic bool findUsagePage(int usagePage, const uint8_t *desc, size_t size)\n{\n unsigned int i = 0;\n int dataLen, keySize;\n\n while (i < size)\n {\n int key = desc[i];\n\n if ((key & 0xf0) == 0xf0)\n {\n \/* This is a Long Item. The next byte contains the\n length of the data section (value) for this key.\n See the HID specification, version 1.11, section\n 6.2.2.3, titled \"Long Items.\" *\/\n dataLen = i + 1 < size ? desc[i + 1] : 0;\n keySize = 3;\n }\n else\n {\n \/* This is a Short Item. The bottom two bits of the\n key contain the size code for the data section\n (value) for this key. Refer to the HID\n specification, version 1.11, section 6.2.2.2,\n titled \"Short Items.\" *\/\n dataLen = key & 0x3;\n if (dataLen == 3)\n ++dataLen; \/\/ 0,1,2,4\n keySize = 1;\n }\n\n if ((key & 0xfc) == 0x04)\n {\n if (i + dataLen >= size)\n {\n \/\/ Truncated report?\n return false;\n }\n\n int page = 0;\n for (int offset = dataLen; offset > 0; --offset)\n {\n page <<= 8;\n page |= desc[i + offset];\n }\n\n if (page == usagePage)\n return true;\n }\n\n \/\/ Skip over this key and it's associated data.\n i += dataLen + keySize;\n }\n\n return false;\n}\n\nstatic void hidapiMissingFeatures(\n int vendorId, int deviceId, int usagePage, int *interfaceNumber, int *inBufferLength, int *outBufferLength)\n{\n libusb_context *ctx = nullptr;\n int rc = libusb_init(&ctx);\n if (LIBUSB_SUCCESS != rc)\n {\n qWarning() << \"libusb_init failed\" << rc << libusb_error_name(rc);\n return;\n }\n\n libusb_device **devs;\n auto count = libusb_get_device_list(ctx, &devs);\n\n for (ssize_t i = 0; i < count; ++i)\n {\n auto dev = devs[i];\n libusb_device_descriptor desc;\n\n if (libusb_get_device_descriptor(dev, &desc) < 0)\n continue;\n\n if (desc.idVendor != vendorId || desc.idProduct != deviceId)\n continue;\n\n libusb_config_descriptor *confDesc = nullptr;\n\n if (libusb_get_active_config_descriptor(dev, &confDesc) < 0)\n continue;\n\n libusb_device_handle *handle;\n if (libusb_open(dev, &handle) < 0)\n continue;\n\n unsigned char buffer[256];\n for (int iface = 0; iface < confDesc->bNumInterfaces; ++iface)\n {\n bool detached = false;\n bool match = false;\n\n rc = libusb_kernel_driver_active(handle, iface);\n if (rc == 1)\n {\n rc = libusb_detach_kernel_driver(handle, iface);\n if (rc < 0)\n {\n qWarning() << \"Failed to detach kernel driver\" << rc << libusb_error_name(rc);\n continue;\n }\n detached = true;\n }\n\n if (libusb_claim_interface(handle, iface) >= 0)\n {\n \/\/ Get the HID Report Descriptor.\n rc = libusb_control_transfer(handle, LIBUSB_ENDPOINT_IN | LIBUSB_RECIPIENT_INTERFACE,\n LIBUSB_REQUEST_GET_DESCRIPTOR, LIBUSB_DT_REPORT << 8, iface, buffer, sizeof(buffer), 1000);\n\n if (rc < 0)\n {\n qWarning() << \"Failed to read HID report descriptor\" << rc << libusb_error_name(rc);\n }\n else\n {\n match = findUsagePage(usagePage, buffer, rc);\n }\n\n libusb_release_interface(handle, iface);\n }\n\n if (match)\n {\n *interfaceNumber = iface;\n auto interface = confDesc->interface[iface];\n\n for (int ifIdx = 0; ifIdx < interface.num_altsetting; ++ifIdx)\n {\n auto intfDesc = interface.altsetting[ifIdx];\n\n for (int epIdx = 0; epIdx < intfDesc.bNumEndpoints; ++epIdx)\n {\n auto ep = intfDesc.endpoint[epIdx];\n\n if ((ep.bEndpointAddress & LIBUSB_ENDPOINT_DIR_MASK) == LIBUSB_ENDPOINT_IN)\n *inBufferLength = ep.wMaxPacketSize;\n else if ((ep.bEndpointAddress & LIBUSB_ENDPOINT_DIR_MASK) == LIBUSB_ENDPOINT_OUT)\n *outBufferLength = ep.wMaxPacketSize;\n }\n }\n\n \/\/ Note that the kernel driver is still detached.\n break;\n }\n else if (detached)\n {\n \/\/ Re-attach kernel driver for non-mached devices.\n rc = libusb_attach_kernel_driver(handle, iface);\n if (rc < 0)\n {\n qWarning() << \"Failed to re-attach kernel driver\" << rc << libusb_error_name(rc);\n }\n }\n }\n libusb_close(handle);\n\n libusb_free_config_descriptor(confDesc);\n break;\n }\n\n libusb_free_device_list(devs, 1);\n libusb_exit(ctx);\n}\n#endif\n\nQHIDDevicePrivate::QHIDDevicePrivate(QHIDDevice *q_ptr, int vendorId, int deviceId, int usagePage)\n : device(nullptr)\n , q_ptr(q_ptr)\n{\n if (hid_init() != 0)\n {\n qWarning() << \"hid_init failed, error\" << errno;\n return;\n }\n\n int interfaceNumber = -1;\n#ifdef WITH_LIBUSB_1_0\n hidapiMissingFeatures(\n vendorId, deviceId, usagePage, &interfaceNumber, &q_ptr->inputBufferLength, &q_ptr->outputBufferLength);\n#endif\n auto devices = hid_enumerate(vendorId, deviceId);\n\n for (auto dev = devices; dev != nullptr; dev = dev->next)\n {\n if ((dev->usage_page > 0 && dev->usage_page == usagePage)\n || (dev->interface_number >= 0 && dev->interface_number == interfaceNumber))\n {\n device = hid_open_path(dev->path);\n\n if (device != nullptr)\n {\n break;\n }\n\n qWarning() << \"Failed to open\" << dev->path << \"error\" << errno;\n }\n }\n\n hid_free_enumeration(devices);\n\n if (device == nullptr)\n {\n qWarning() << \"No such device\" << vendorId << deviceId << usagePage;\n }\n}\n\nQHIDDevicePrivate::~QHIDDevicePrivate()\n{\n if (device)\n {\n hid_close(device);\n device = nullptr;\n }\n\n hid_exit();\n}\n\nbool QHIDDevicePrivate::isValid() const\n{\n return !!device;\n}\n\nint QHIDDevicePrivate::sendFeatureReport(const char *buffer, int length)\n{\n return device == nullptr ? -1 : hid_send_feature_report(device, (const unsigned char *)buffer, length);\n}\n\nint QHIDDevicePrivate::getFeatureReport(char *buffer, int length)\n{\n return device == nullptr ? -1 : hid_get_feature_report(device, (unsigned char *)buffer, length);\n}\n\nint QHIDDevicePrivate::write(const char *buffer, int length)\n{\n return hid_write(device, (const unsigned char *)buffer, length);\n}\n\nint QHIDDevicePrivate::read(char *buffer, int length)\n{\n return hid_read_timeout(device, (unsigned char *)buffer, length, 30000);\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2013, Facebook, Inc. All rights reserved.\n\/\/ This source code is licensed under the BSD-style license found in the\n\/\/ LICENSE file in the root directory of this source tree. An additional grant\n\/\/ of patent rights can be found in the PATENTS file in the same directory.\n\/\/\n#ifndef ROCKSDB_LITE\n#include <gflags\/gflags.h>\n#include <atomic>\n#include <functional>\n#include <memory>\n#include <sstream>\n#include <unordered_map>\n\n#include \"rocksdb\/env.h\"\n\n#include \"utilities\/persistent_cache\/block_cache_tier.h\"\n#include \"utilities\/persistent_cache\/persistent_cache_tier.h\"\n#include \"utilities\/persistent_cache\/volatile_tier_impl.h\"\n\n#include \"port\/port_posix.h\"\n#include \"table\/block_builder.h\"\n#include \"util\/histogram.h\"\n#include \"util\/mutexlock.h\"\n#include \"util\/stop_watch.h\"\n\nDEFINE_int32(nsec, 10, \"nsec\");\nDEFINE_int32(nthread_write, 1, \"Insert threads\");\nDEFINE_int32(nthread_read, 1, \"Lookup threads\");\nDEFINE_string(path, \"\/tmp\/microbench\/blkcache\", \"Path for cachefile\");\nDEFINE_string(log_path, \"\/tmp\/log\", \"Path for the log file\");\nDEFINE_uint64(cache_size, std::numeric_limits<uint64_t>::max(), \"Cache size\");\nDEFINE_int32(iosize, 4 * 1024, \"Read IO size\");\nDEFINE_int32(writer_iosize, 4 * 1024, \"File writer IO size\");\nDEFINE_int32(writer_qdepth, 1, \"File writer qdepth\");\nDEFINE_bool(enable_pipelined_writes, false, \"Enable async writes\");\nDEFINE_string(cache_type, \"block_cache\",\n \"Cache type. (block_cache, volatile, tiered)\");\nDEFINE_bool(benchmark, false, \"Benchmark mode\");\nDEFINE_int32(volatile_cache_pct, 10, \"Percentage of cache in memory tier.\");\n\nnamespace rocksdb {\n\nstd::unique_ptr<PersistentCacheTier> NewVolatileCache() {\n assert(FLAGS_cache_size != std::numeric_limits<uint64_t>::max());\n std::unique_ptr<PersistentCacheTier> pcache(\n new VolatileCacheTier(FLAGS_cache_size));\n return pcache;\n}\n\nstd::unique_ptr<PersistentCacheTier> NewBlockCache() {\n std::shared_ptr<Logger> log;\n if (!Env::Default()->NewLogger(FLAGS_log_path, &log).ok()) {\n fprintf(stderr, \"Error creating log %s \\n\", FLAGS_log_path.c_str());\n return nullptr;\n }\n\n PersistentCacheConfig opt(Env::Default(), FLAGS_path, FLAGS_cache_size, log);\n opt.writer_dispatch_size = FLAGS_writer_iosize;\n opt.writer_qdepth = FLAGS_writer_qdepth;\n opt.pipeline_writes = FLAGS_enable_pipelined_writes;\n opt.max_write_pipeline_backlog_size = std::numeric_limits<uint64_t>::max();\n std::unique_ptr<PersistentCacheTier> cache(new BlockCacheTier(opt));\n Status status = cache->Open();\n return cache;\n}\n\n\/\/ create a new cache tier\n\/\/ construct a tiered RAM+Block cache\nstd::unique_ptr<PersistentTieredCache> NewTieredCache(\n const size_t mem_size, const PersistentCacheConfig& opt) {\n std::unique_ptr<PersistentTieredCache> tcache(new PersistentTieredCache());\n \/\/ create primary tier\n assert(mem_size);\n auto pcache =\n std::shared_ptr<PersistentCacheTier>(new VolatileCacheTier(mem_size));\n tcache->AddTier(pcache);\n \/\/ create secondary tier\n auto scache = std::shared_ptr<PersistentCacheTier>(new BlockCacheTier(opt));\n tcache->AddTier(scache);\n\n Status s = tcache->Open();\n assert(s.ok());\n return tcache;\n}\n\nstd::unique_ptr<PersistentTieredCache> NewTieredCache() {\n std::shared_ptr<Logger> log;\n if (!Env::Default()->NewLogger(FLAGS_log_path, &log).ok()) {\n fprintf(stderr, \"Error creating log %s \\n\", FLAGS_log_path.c_str());\n abort();\n }\n\n auto pct = FLAGS_volatile_cache_pct \/ static_cast<double>(100);\n PersistentCacheConfig opt(Env::Default(), FLAGS_path,\n (1 - pct) * FLAGS_cache_size, log);\n opt.writer_dispatch_size = FLAGS_writer_iosize;\n opt.writer_qdepth = FLAGS_writer_qdepth;\n opt.pipeline_writes = FLAGS_enable_pipelined_writes;\n opt.max_write_pipeline_backlog_size = std::numeric_limits<uint64_t>::max();\n return NewTieredCache(FLAGS_cache_size * pct, opt);\n}\n\n\/\/\n\/\/ Benchmark driver\n\/\/\nclass CacheTierBenchmark {\n public:\n explicit CacheTierBenchmark(std::shared_ptr<PersistentCacheTier>&& cache)\n : cache_(cache) {\n if (FLAGS_nthread_read) {\n fprintf(stdout, \"Pre-populating\\n\");\n Prepop();\n fprintf(stdout, \"Pre-population completed\\n\");\n }\n\n stats_.Clear();\n\n \/\/ Start IO threads\n std::list<std::thread> threads;\n Spawn(FLAGS_nthread_write, &threads,\n std::bind(&CacheTierBenchmark::Write, this));\n Spawn(FLAGS_nthread_read, &threads,\n std::bind(&CacheTierBenchmark::Read, this));\n\n \/\/ Wait till FLAGS_nsec and then signal to quit\n StopWatchNano t(Env::Default(), \/*auto_start=*\/true);\n size_t sec = t.ElapsedNanos() \/ 1000000000ULL;\n while (!quit_) {\n sec = t.ElapsedNanos() \/ 1000000000ULL;\n quit_ = sec > size_t(FLAGS_nsec);\n \/* sleep override *\/ sleep(1);\n }\n\n \/\/ Wait for threads to exit\n Join(&threads);\n \/\/ Print stats\n PrintStats(sec);\n \/\/ Close the cache\n cache_->TEST_Flush();\n cache_->Close();\n }\n\n private:\n void PrintStats(const size_t sec) {\n std::ostringstream msg;\n msg << \"Test stats\" << std::endl\n << \"* Elapsed: \" << sec << \" s\" << std::endl\n << \"* Write Latency:\" << std::endl\n << stats_.write_latency_.ToString() << std::endl\n << \"* Read Latency:\" << std::endl\n << stats_.read_latency_.ToString() << std::endl\n << \"* Bytes written:\" << std::endl\n << stats_.bytes_written_.ToString() << std::endl\n << \"* Bytes read:\" << std::endl\n << stats_.bytes_read_.ToString() << std::endl\n << \"Cache stats:\" << std::endl\n << cache_->PrintStats() << std::endl;\n fprintf(stderr, \"%s\\n\", msg.str().c_str());\n }\n\n \/\/\n \/\/ Insert implementation and corresponding helper functions\n \/\/\n void Prepop() {\n for (uint64_t i = 0; i < 1024 * 1024; ++i) {\n InsertKey(i);\n insert_key_limit_++;\n read_key_limit_++;\n }\n\n \/\/ Wait until data is flushed\n cache_->TEST_Flush();\n \/\/ warmup the cache\n for (uint64_t i = 0; i < 1024 * 1024; ReadKey(i++)) {\n }\n }\n\n void Write() {\n while (!quit_) {\n InsertKey(insert_key_limit_++);\n }\n }\n\n void InsertKey(const uint64_t key) {\n \/\/ construct key\n uint64_t k[3];\n Slice block_key = FillKey(k, key);\n\n \/\/ construct value\n auto block = NewBlock(key);\n\n \/\/ insert\n StopWatchNano timer(Env::Default(), \/*auto_start=*\/true);\n while (true) {\n Status status = cache_->Insert(block_key, block.get(), FLAGS_iosize);\n if (status.ok()) {\n break;\n }\n\n \/\/ transient error is possible if we run without pipelining\n assert(!FLAGS_enable_pipelined_writes);\n }\n\n \/\/ adjust stats\n const size_t elapsed_micro = timer.ElapsedNanos() \/ 1000;\n stats_.write_latency_.Add(elapsed_micro);\n stats_.bytes_written_.Add(FLAGS_iosize);\n }\n\n \/\/\n \/\/ Read implementation\n \/\/\n void Read() {\n while (!quit_) {\n ReadKey(random() % read_key_limit_);\n }\n }\n\n void ReadKey(const uint64_t val) {\n \/\/ construct key\n uint64_t k[3];\n Slice key = FillKey(k, val);\n\n \/\/ Lookup in cache\n StopWatchNano timer(Env::Default(), \/*auto_start=*\/true);\n std::unique_ptr<char[]> block;\n uint64_t size;\n Status status = cache_->Lookup(key, &block, &size);\n if (!status.ok()) {\n fprintf(stderr, \"%s\\n\", status.ToString().c_str());\n }\n assert(status.ok());\n assert(size == (uint64_t)FLAGS_iosize);\n\n \/\/ adjust stats\n const size_t elapsed_micro = timer.ElapsedNanos() \/ 1000;\n stats_.read_latency_.Add(elapsed_micro);\n stats_.bytes_read_.Add(FLAGS_iosize);\n\n \/\/ verify content\n if (!FLAGS_benchmark) {\n auto expected_block = NewBlock(val);\n assert(memcmp(block.get(), expected_block.get(), FLAGS_iosize) == 0);\n }\n }\n\n \/\/ create data for a key by filling with a certain pattern\n std::unique_ptr<char[]> NewBlock(const uint64_t val) {\n unique_ptr<char[]> data(new char[FLAGS_iosize]);\n memset(data.get(), val % 255, FLAGS_iosize);\n return data;\n }\n\n \/\/ spawn threads\n void Spawn(const size_t n, std::list<std::thread>* threads,\n const std::function<void()>& fn) {\n for (size_t i = 0; i < n; ++i) {\n threads->emplace_back(fn);\n }\n }\n\n \/\/ join threads\n void Join(std::list<std::thread>* threads) {\n for (auto& th : *threads) {\n th.join();\n }\n }\n\n \/\/ construct key\n Slice FillKey(uint64_t (&k)[3], const uint64_t val) {\n k[0] = k[1] = 0;\n k[2] = val;\n void* p = static_cast<void*>(&k);\n return Slice(static_cast<char*>(p), sizeof(k));\n }\n\n \/\/ benchmark stats\n struct Stats {\n void Clear() {\n bytes_written_.Clear();\n bytes_read_.Clear();\n read_latency_.Clear();\n write_latency_.Clear();\n }\n\n HistogramImpl bytes_written_;\n HistogramImpl bytes_read_;\n HistogramImpl read_latency_;\n HistogramImpl write_latency_;\n };\n\n std::shared_ptr<PersistentCacheTier> cache_; \/\/ cache implementation\n std::atomic<uint64_t> insert_key_limit_{0}; \/\/ data inserted upto\n std::atomic<uint64_t> read_key_limit_{0}; \/\/ data can be read safely upto\n bool quit_ = false; \/\/ Quit thread ?\n mutable Stats stats_; \/\/ Stats\n};\n\n} \/\/ namespace rocksdb\n\n\/\/\n\/\/ main\n\/\/\nint main(int argc, char** argv) {\n google::SetUsageMessage(std::string(\"\\nUSAGE:\\n\") + std::string(argv[0]) +\n \" [OPTIONS]...\");\n google::ParseCommandLineFlags(&argc, &argv, false);\n\n std::ostringstream msg;\n msg << \"Config\" << std::endl\n << \"======\" << std::endl\n << \"* nsec=\" << FLAGS_nsec << std::endl\n << \"* nthread_write=\" << FLAGS_nthread_write << std::endl\n << \"* path=\" << FLAGS_path << std::endl\n << \"* cache_size=\" << FLAGS_cache_size << std::endl\n << \"* iosize=\" << FLAGS_iosize << std::endl\n << \"* writer_iosize=\" << FLAGS_writer_iosize << std::endl\n << \"* writer_qdepth=\" << FLAGS_writer_qdepth << std::endl\n << \"* enable_pipelined_writes=\" << FLAGS_enable_pipelined_writes\n << std::endl\n << \"* cache_type=\" << FLAGS_cache_type << std::endl\n << \"* benchmark=\" << FLAGS_benchmark << std::endl\n << \"* volatile_cache_pct=\" << FLAGS_volatile_cache_pct << std::endl;\n\n fprintf(stderr, \"%s\\n\", msg.str().c_str());\n\n std::shared_ptr<rocksdb::PersistentCacheTier> cache;\n if (FLAGS_cache_type == \"block_cache\") {\n fprintf(stderr, \"Using block cache implementation\\n\");\n cache = rocksdb::NewBlockCache();\n } else if (FLAGS_cache_type == \"volatile\") {\n fprintf(stderr, \"Using volatile cache implementation\\n\");\n cache = rocksdb::NewVolatileCache();\n } else if (FLAGS_cache_type == \"tiered\") {\n fprintf(stderr, \"Using tiered cache implementation\\n\");\n cache = rocksdb::NewTieredCache();\n } else {\n fprintf(stderr, \"Unknown option for cache\\n\");\n }\n\n assert(cache);\n if (!cache) {\n fprintf(stderr, \"Error creating cache\\n\");\n abort();\n }\n\n std::unique_ptr<rocksdb::CacheTierBenchmark> benchmark(\n new rocksdb::CacheTierBenchmark(std::move(cache)));\n\n return 0;\n}\n#else\nint main(int, char**) { return 0; }\n#endif\n<commit_msg>Fix Mac build failure (#1309)<commit_after>\/\/ Copyright (c) 2013, Facebook, Inc. All rights reserved.\n\/\/ This source code is licensed under the BSD-style license found in the\n\/\/ LICENSE file in the root directory of this source tree. An additional grant\n\/\/ of patent rights can be found in the PATENTS file in the same directory.\n\/\/\n#ifndef ROCKSDB_LITE\n#include <gflags\/gflags.h>\n#include <atomic>\n#include <functional>\n#include <memory>\n#include <sstream>\n#include <unordered_map>\n\n#include \"rocksdb\/env.h\"\n\n#include \"utilities\/persistent_cache\/block_cache_tier.h\"\n#include \"utilities\/persistent_cache\/persistent_cache_tier.h\"\n#include \"utilities\/persistent_cache\/volatile_tier_impl.h\"\n\n#include \"port\/port_posix.h\"\n#include \"table\/block_builder.h\"\n#include \"util\/histogram.h\"\n#include \"util\/mutexlock.h\"\n#include \"util\/stop_watch.h\"\n\nDEFINE_int32(nsec, 10, \"nsec\");\nDEFINE_int32(nthread_write, 1, \"Insert threads\");\nDEFINE_int32(nthread_read, 1, \"Lookup threads\");\nDEFINE_string(path, \"\/tmp\/microbench\/blkcache\", \"Path for cachefile\");\nDEFINE_string(log_path, \"\/tmp\/log\", \"Path for the log file\");\nDEFINE_uint64(cache_size, std::numeric_limits<uint64_t>::max(), \"Cache size\");\nDEFINE_int32(iosize, 4 * 1024, \"Read IO size\");\nDEFINE_int32(writer_iosize, 4 * 1024, \"File writer IO size\");\nDEFINE_int32(writer_qdepth, 1, \"File writer qdepth\");\nDEFINE_bool(enable_pipelined_writes, false, \"Enable async writes\");\nDEFINE_string(cache_type, \"block_cache\",\n \"Cache type. (block_cache, volatile, tiered)\");\nDEFINE_bool(benchmark, false, \"Benchmark mode\");\nDEFINE_int32(volatile_cache_pct, 10, \"Percentage of cache in memory tier.\");\n\nnamespace rocksdb {\n\nstd::unique_ptr<PersistentCacheTier> NewVolatileCache() {\n assert(FLAGS_cache_size != std::numeric_limits<uint64_t>::max());\n std::unique_ptr<PersistentCacheTier> pcache(\n new VolatileCacheTier(FLAGS_cache_size));\n return pcache;\n}\n\nstd::unique_ptr<PersistentCacheTier> NewBlockCache() {\n std::shared_ptr<Logger> log;\n if (!Env::Default()->NewLogger(FLAGS_log_path, &log).ok()) {\n fprintf(stderr, \"Error creating log %s \\n\", FLAGS_log_path.c_str());\n return nullptr;\n }\n\n PersistentCacheConfig opt(Env::Default(), FLAGS_path, FLAGS_cache_size, log);\n opt.writer_dispatch_size = FLAGS_writer_iosize;\n opt.writer_qdepth = FLAGS_writer_qdepth;\n opt.pipeline_writes = FLAGS_enable_pipelined_writes;\n opt.max_write_pipeline_backlog_size = std::numeric_limits<uint64_t>::max();\n std::unique_ptr<PersistentCacheTier> cache(new BlockCacheTier(opt));\n Status status = cache->Open();\n return cache;\n}\n\n\/\/ create a new cache tier\n\/\/ construct a tiered RAM+Block cache\nstd::unique_ptr<PersistentTieredCache> NewTieredCache(\n const size_t mem_size, const PersistentCacheConfig& opt) {\n std::unique_ptr<PersistentTieredCache> tcache(new PersistentTieredCache());\n \/\/ create primary tier\n assert(mem_size);\n auto pcache =\n std::shared_ptr<PersistentCacheTier>(new VolatileCacheTier(mem_size));\n tcache->AddTier(pcache);\n \/\/ create secondary tier\n auto scache = std::shared_ptr<PersistentCacheTier>(new BlockCacheTier(opt));\n tcache->AddTier(scache);\n\n Status s = tcache->Open();\n assert(s.ok());\n return tcache;\n}\n\nstd::unique_ptr<PersistentTieredCache> NewTieredCache() {\n std::shared_ptr<Logger> log;\n if (!Env::Default()->NewLogger(FLAGS_log_path, &log).ok()) {\n fprintf(stderr, \"Error creating log %s \\n\", FLAGS_log_path.c_str());\n abort();\n }\n\n auto pct = FLAGS_volatile_cache_pct \/ static_cast<double>(100);\n PersistentCacheConfig opt(Env::Default(), FLAGS_path,\n (1 - pct) * FLAGS_cache_size, log);\n opt.writer_dispatch_size = FLAGS_writer_iosize;\n opt.writer_qdepth = FLAGS_writer_qdepth;\n opt.pipeline_writes = FLAGS_enable_pipelined_writes;\n opt.max_write_pipeline_backlog_size = std::numeric_limits<uint64_t>::max();\n return NewTieredCache(FLAGS_cache_size * pct, opt);\n}\n\n\/\/\n\/\/ Benchmark driver\n\/\/\nclass CacheTierBenchmark {\n public:\n explicit CacheTierBenchmark(std::shared_ptr<PersistentCacheTier>&& cache)\n : cache_(cache) {\n if (FLAGS_nthread_read) {\n fprintf(stdout, \"Pre-populating\\n\");\n Prepop();\n fprintf(stdout, \"Pre-population completed\\n\");\n }\n\n stats_.Clear();\n\n \/\/ Start IO threads\n std::list<std::thread> threads;\n Spawn(FLAGS_nthread_write, &threads,\n std::bind(&CacheTierBenchmark::Write, this));\n Spawn(FLAGS_nthread_read, &threads,\n std::bind(&CacheTierBenchmark::Read, this));\n\n \/\/ Wait till FLAGS_nsec and then signal to quit\n StopWatchNano t(Env::Default(), \/*auto_start=*\/true);\n size_t sec = t.ElapsedNanos() \/ 1000000000ULL;\n while (!quit_) {\n sec = t.ElapsedNanos() \/ 1000000000ULL;\n quit_ = sec > size_t(FLAGS_nsec);\n \/* sleep override *\/ sleep(1);\n }\n\n \/\/ Wait for threads to exit\n Join(&threads);\n \/\/ Print stats\n PrintStats(sec);\n \/\/ Close the cache\n cache_->TEST_Flush();\n cache_->Close();\n }\n\n private:\n void PrintStats(const size_t sec) {\n std::ostringstream msg;\n msg << \"Test stats\" << std::endl\n << \"* Elapsed: \" << sec << \" s\" << std::endl\n << \"* Write Latency:\" << std::endl\n << stats_.write_latency_.ToString() << std::endl\n << \"* Read Latency:\" << std::endl\n << stats_.read_latency_.ToString() << std::endl\n << \"* Bytes written:\" << std::endl\n << stats_.bytes_written_.ToString() << std::endl\n << \"* Bytes read:\" << std::endl\n << stats_.bytes_read_.ToString() << std::endl\n << \"Cache stats:\" << std::endl\n << cache_->PrintStats() << std::endl;\n fprintf(stderr, \"%s\\n\", msg.str().c_str());\n }\n\n \/\/\n \/\/ Insert implementation and corresponding helper functions\n \/\/\n void Prepop() {\n for (uint64_t i = 0; i < 1024 * 1024; ++i) {\n InsertKey(i);\n insert_key_limit_++;\n read_key_limit_++;\n }\n\n \/\/ Wait until data is flushed\n cache_->TEST_Flush();\n \/\/ warmup the cache\n for (uint64_t i = 0; i < 1024 * 1024; ReadKey(i++)) {\n }\n }\n\n void Write() {\n while (!quit_) {\n InsertKey(insert_key_limit_++);\n }\n }\n\n void InsertKey(const uint64_t key) {\n \/\/ construct key\n uint64_t k[3];\n Slice block_key = FillKey(k, key);\n\n \/\/ construct value\n auto block = NewBlock(key);\n\n \/\/ insert\n StopWatchNano timer(Env::Default(), \/*auto_start=*\/true);\n while (true) {\n Status status = cache_->Insert(block_key, block.get(), FLAGS_iosize);\n if (status.ok()) {\n break;\n }\n\n \/\/ transient error is possible if we run without pipelining\n assert(!FLAGS_enable_pipelined_writes);\n }\n\n \/\/ adjust stats\n const size_t elapsed_micro = timer.ElapsedNanos() \/ 1000;\n stats_.write_latency_.Add(elapsed_micro);\n stats_.bytes_written_.Add(FLAGS_iosize);\n }\n\n \/\/\n \/\/ Read implementation\n \/\/\n void Read() {\n while (!quit_) {\n ReadKey(random() % read_key_limit_);\n }\n }\n\n void ReadKey(const uint64_t val) {\n \/\/ construct key\n uint64_t k[3];\n Slice key = FillKey(k, val);\n\n \/\/ Lookup in cache\n StopWatchNano timer(Env::Default(), \/*auto_start=*\/true);\n std::unique_ptr<char[]> block;\n size_t size;\n Status status = cache_->Lookup(key, &block, &size);\n if (!status.ok()) {\n fprintf(stderr, \"%s\\n\", status.ToString().c_str());\n }\n assert(status.ok());\n assert(size == (size_t) FLAGS_iosize);\n\n \/\/ adjust stats\n const size_t elapsed_micro = timer.ElapsedNanos() \/ 1000;\n stats_.read_latency_.Add(elapsed_micro);\n stats_.bytes_read_.Add(FLAGS_iosize);\n\n \/\/ verify content\n if (!FLAGS_benchmark) {\n auto expected_block = NewBlock(val);\n assert(memcmp(block.get(), expected_block.get(), FLAGS_iosize) == 0);\n }\n }\n\n \/\/ create data for a key by filling with a certain pattern\n std::unique_ptr<char[]> NewBlock(const uint64_t val) {\n unique_ptr<char[]> data(new char[FLAGS_iosize]);\n memset(data.get(), val % 255, FLAGS_iosize);\n return data;\n }\n\n \/\/ spawn threads\n void Spawn(const size_t n, std::list<std::thread>* threads,\n const std::function<void()>& fn) {\n for (size_t i = 0; i < n; ++i) {\n threads->emplace_back(fn);\n }\n }\n\n \/\/ join threads\n void Join(std::list<std::thread>* threads) {\n for (auto& th : *threads) {\n th.join();\n }\n }\n\n \/\/ construct key\n Slice FillKey(uint64_t (&k)[3], const uint64_t val) {\n k[0] = k[1] = 0;\n k[2] = val;\n void* p = static_cast<void*>(&k);\n return Slice(static_cast<char*>(p), sizeof(k));\n }\n\n \/\/ benchmark stats\n struct Stats {\n void Clear() {\n bytes_written_.Clear();\n bytes_read_.Clear();\n read_latency_.Clear();\n write_latency_.Clear();\n }\n\n HistogramImpl bytes_written_;\n HistogramImpl bytes_read_;\n HistogramImpl read_latency_;\n HistogramImpl write_latency_;\n };\n\n std::shared_ptr<PersistentCacheTier> cache_; \/\/ cache implementation\n std::atomic<uint64_t> insert_key_limit_{0}; \/\/ data inserted upto\n std::atomic<uint64_t> read_key_limit_{0}; \/\/ data can be read safely upto\n bool quit_ = false; \/\/ Quit thread ?\n mutable Stats stats_; \/\/ Stats\n};\n\n} \/\/ namespace rocksdb\n\n\/\/\n\/\/ main\n\/\/\nint main(int argc, char** argv) {\n google::SetUsageMessage(std::string(\"\\nUSAGE:\\n\") + std::string(argv[0]) +\n \" [OPTIONS]...\");\n google::ParseCommandLineFlags(&argc, &argv, false);\n\n std::ostringstream msg;\n msg << \"Config\" << std::endl\n << \"======\" << std::endl\n << \"* nsec=\" << FLAGS_nsec << std::endl\n << \"* nthread_write=\" << FLAGS_nthread_write << std::endl\n << \"* path=\" << FLAGS_path << std::endl\n << \"* cache_size=\" << FLAGS_cache_size << std::endl\n << \"* iosize=\" << FLAGS_iosize << std::endl\n << \"* writer_iosize=\" << FLAGS_writer_iosize << std::endl\n << \"* writer_qdepth=\" << FLAGS_writer_qdepth << std::endl\n << \"* enable_pipelined_writes=\" << FLAGS_enable_pipelined_writes\n << std::endl\n << \"* cache_type=\" << FLAGS_cache_type << std::endl\n << \"* benchmark=\" << FLAGS_benchmark << std::endl\n << \"* volatile_cache_pct=\" << FLAGS_volatile_cache_pct << std::endl;\n\n fprintf(stderr, \"%s\\n\", msg.str().c_str());\n\n std::shared_ptr<rocksdb::PersistentCacheTier> cache;\n if (FLAGS_cache_type == \"block_cache\") {\n fprintf(stderr, \"Using block cache implementation\\n\");\n cache = rocksdb::NewBlockCache();\n } else if (FLAGS_cache_type == \"volatile\") {\n fprintf(stderr, \"Using volatile cache implementation\\n\");\n cache = rocksdb::NewVolatileCache();\n } else if (FLAGS_cache_type == \"tiered\") {\n fprintf(stderr, \"Using tiered cache implementation\\n\");\n cache = rocksdb::NewTieredCache();\n } else {\n fprintf(stderr, \"Unknown option for cache\\n\");\n }\n\n assert(cache);\n if (!cache) {\n fprintf(stderr, \"Error creating cache\\n\");\n abort();\n }\n\n std::unique_ptr<rocksdb::CacheTierBenchmark> benchmark(\n new rocksdb::CacheTierBenchmark(std::move(cache)));\n\n return 0;\n}\n#else\nint main(int, char**) { return 0; }\n#endif\n<|endoftext|>"} {"text":"<commit_before>#pragma once\n\/**\n\t@file\n\t@brief int type definition and macros\n\n\tCopyright (C) 2008-2012 Cybozu Labs, Inc., all rights reserved.\n*\/\n\n#if defined(_MSC_VER) && (MSC_VER <= 1500)\n\ttypedef __int64 int64_t;\n\ttypedef unsigned __int64 uint64_t;\n\ttypedef unsigned int uint32_t;\n\ttypedef int int32_t;\n\ttypedef unsigned short uint16_t;\n\ttypedef short int16_t;\n\ttypedef unsigned char uint8_t;\n\ttypedef signed char int8_t;\n#else\n\t#include <stdint.h>\n#endif\n\n#ifdef _MSC_VER\n\t#ifndef CYBOZU_DEFINED_SSIZE_T\n\t\t#define CYBOZU_DEFINED_SSIZE_T\n\t\t#ifdef _WIN64\n\t\t\ttypedef int64_t ssize_t;\n\t\t#else\n\t\t\ttypedef int32_t ssize_t;\n\t\t#endif\n\t#endif\n#else\n\t#include <unistd.h> \/\/ for ssize_t\n#endif\n\n\/\/ std::vector<int> v; CYBOZU_FOREACH(auto x, v) {...}\n#if defined(_MSC_VER) && (_MSC_VER >= 1400)\n\t#define CYBOZU_FOREACH(type_x, xs) for each (type_x in xs)\n#elif defined(__GNUC__)\n\t#define CYBOZU_FOREACH(type_x, xs) for (type_x : xs)\n#endif\n\n#define CYBOZU_NUM_OF_ARRAY(x) (sizeof(x) \/ sizeof(*x))\n\n#ifdef _MSC_VER\n\t#define CYBOZU_SNPRINTF _snprintf_s\n#else\n\t#define CYBOZU_SNPRINTF snprintf\n#endif\n\nnamespace cybozu {\ntemplate<class T>\nvoid disable_warning_unused_variable(const T&) { }\n} \/\/ cybozu\n\n<commit_msg>add align macro<commit_after>#pragma once\n\/**\n\t@file\n\t@brief int type definition and macros\n\n\tCopyright (C) 2008-2012 Cybozu Labs, Inc., all rights reserved.\n*\/\n\n#if defined(_MSC_VER) && (MSC_VER <= 1500)\n\ttypedef __int64 int64_t;\n\ttypedef unsigned __int64 uint64_t;\n\ttypedef unsigned int uint32_t;\n\ttypedef int int32_t;\n\ttypedef unsigned short uint16_t;\n\ttypedef short int16_t;\n\ttypedef unsigned char uint8_t;\n\ttypedef signed char int8_t;\n#else\n\t#include <stdint.h>\n#endif\n\n#ifdef _MSC_VER\n\t#ifndef CYBOZU_DEFINED_SSIZE_T\n\t\t#define CYBOZU_DEFINED_SSIZE_T\n\t\t#ifdef _WIN64\n\t\t\ttypedef int64_t ssize_t;\n\t\t#else\n\t\t\ttypedef int32_t ssize_t;\n\t\t#endif\n\t#endif\n#else\n\t#include <unistd.h> \/\/ for ssize_t\n#endif\n\n#ifndef CYBOZU_ALIGN\n\t#ifdef _MSC_VER\n\t\t#define CYBOZU_ALIGN(x) __declspec(align(x))\n\t#else\n\t\t#define CYBOZU_ALIGN(x) __attribute__((aligned(x)))\n\t#endif\n#endif\n\n\/\/ std::vector<int> v; CYBOZU_FOREACH(auto x, v) {...}\n#if defined(_MSC_VER) && (_MSC_VER >= 1400)\n\t#define CYBOZU_FOREACH(type_x, xs) for each (type_x in xs)\n#elif defined(__GNUC__)\n\t#define CYBOZU_FOREACH(type_x, xs) for (type_x : xs)\n#endif\n\n#define CYBOZU_NUM_OF_ARRAY(x) (sizeof(x) \/ sizeof(*x))\n\n#ifdef _MSC_VER\n\t#define CYBOZU_SNPRINTF _snprintf_s\n#else\n\t#define CYBOZU_SNPRINTF snprintf\n#endif\n\nnamespace cybozu {\ntemplate<class T>\nvoid disable_warning_unused_variable(const T&) { }\n} \/\/ cybozu\n\n<|endoftext|>"} {"text":"<commit_before>#ifndef __FENWICK_NAIVE_HPP__\n#define __FENWICK_NAIVE_HPP__\n\n#include \"fenwick_tree.hpp\"\n\nnamespace hft::fenwick {\n\n\/**\n * class FixedF - no compression and classical node layout.\n * @sequence: sequence of integers.\n * @size: number of elements.\n * @BOUND: maximum value that @sequence can store.\n *\n *\/\ntemplate <size_t BOUND> class FixedF : public FenwickTree {\npublic:\n static constexpr size_t BOUNDSIZE = log2(BOUND);\n static_assert(BOUNDSIZE >= 1 && BOUNDSIZE <= 64,\n \"Leaves can't be stored in a 64-bit word\");\n\nprotected:\n DArray<uint64_t> Tree;\n\npublic:\n FixedF(uint64_t sequence[], size_t size) : Tree(size) {\n std::copy_n(sequence, size, Tree.get());\n\n for (size_t m = 2; m <= size; m <<= 1) {\n for (size_t idx = m; idx <= size; idx += m)\n Tree[idx - 1] += Tree[idx - m \/ 2 - 1];\n }\n }\n\n virtual uint64_t prefix(size_t idx) const {\n uint64_t sum = 0;\n\n while (idx != 0) {\n sum += Tree[idx - 1];\n idx = clear_rho(idx);\n }\n\n return sum;\n }\n\n virtual void add(size_t idx, int64_t inc) {\n size_t treeSize = Tree.size();\n while (idx <= treeSize) {\n Tree[idx - 1] += inc;\n idx += mask_rho(idx);\n }\n }\n\n using FenwickTree::find;\n virtual size_t find(uint64_t *val) const {\n size_t treeSize = Tree.size();\n size_t node = 0;\n\n for (size_t m = mask_lambda(treeSize); m != 0; m >>= 1) {\n if (node + m - 1 >= treeSize)\n continue;\n\n uint64_t value = Tree[node + m - 1];\n\n if (*val >= value) {\n node += m;\n *val -= value;\n }\n }\n\n return node;\n }\n\n using FenwickTree::compFind;\n virtual size_t compFind(uint64_t *val) const {\n size_t node = 0, treeSize = Tree.size();\n\n for (size_t m = mask_lambda(treeSize); m != 0; m >>= 1) {\n if (node + m - 1 >= treeSize)\n continue;\n\n uint64_t value = (BOUND << rho(node + m)) - Tree[node + m - 1];\n\n if (*val >= value) {\n node += m;\n *val -= value;\n }\n }\n\n return node;\n }\n\n virtual size_t size() const { return Tree.size(); }\n\n virtual size_t bitCount() const {\n return sizeof(FixedF<BOUNDSIZE>) * 8 + Tree.bitCount() - sizeof(Tree);\n }\n};\n\n} \/\/ namespace hft::fenwick\n\n#endif \/\/ __FENWICK_NAIVE_HPP__\n<commit_msg>Introducing holes in the classic Fenwick tree, removed -1's<commit_after>#ifndef __FENWICK_NAIVE_HPP__\n#define __FENWICK_NAIVE_HPP__\n\n#include \"fenwick_tree.hpp\"\n\nnamespace hft::fenwick {\n\n\/**\n * class FixedF - no compression and classical node layout.\n * @sequence: sequence of integers.\n * @size: number of elements.\n * @BOUND: maximum value that @sequence can store.\n *\n *\/\ntemplate <size_t BOUND> class FixedF : public FenwickTree {\npublic:\n static constexpr size_t BOUNDSIZE = log2(BOUND);\n static_assert(BOUNDSIZE >= 1 && BOUNDSIZE <= 64,\n \"Leaves can't be stored in a 64-bit word\");\n\nprotected:\n DArray<uint64_t> Tree;\n\npublic:\n FixedF(uint64_t sequence[], size_t size) : Tree(pos(size) + 1) {\n std::copy_n(sequence, size, Tree.get());\n\n for (size_t m = 2; m <= size; m <<= 1) {\n for (size_t idx = m; idx <= size; idx += m)\n Tree[pos(idx)] += Tree[pos(idx - m \/ 2)];\n }\n }\n\n virtual uint64_t prefix(size_t idx) const {\n uint64_t sum = 0;\n\n while (idx != 0) {\n sum += Tree[pos(idx)];\n idx = clear_rho(idx);\n }\n\n return sum;\n }\n\n virtual void add(size_t idx, int64_t inc) {\n size_t treeSize = Tree.size();\n while (idx <= treeSize) {\n Tree[pos(idx)] += inc;\n idx += mask_rho(idx);\n }\n }\n\n using FenwickTree::find;\n virtual size_t find(uint64_t *val) const {\n size_t treeSize = Tree.size();\n size_t node = 0;\n\n for (size_t m = mask_lambda(treeSize); m != 0; m >>= 1) {\n if (node + m > treeSize) continue;\n\n uint64_t value = Tree[pos(node + m)];\n\n if (*val >= value) {\n node += m;\n *val -= value;\n }\n }\n\n return node;\n }\n\n using FenwickTree::compFind;\n virtual size_t compFind(uint64_t *val) const {\n size_t node = 0, treeSize = Tree.size();\n\n for (size_t m = mask_lambda(treeSize); m != 0; m >>= 1) {\n if (node + m > treeSize) continue;\n\n uint64_t value = (BOUND << rho(node + m)) - Tree[pos(node + m)];\n\n if (*val >= value) {\n node += m;\n *val -= value;\n }\n }\n\n return node;\n }\n\n virtual size_t size() const { return Tree.size(); }\n\n virtual size_t bitCount() const {\n return sizeof(FixedF<BOUNDSIZE>) * 8 + Tree.bitCount() - sizeof(Tree);\n }\n\nprivate:\n static inline size_t pos(size_t index) {\n return index + index \/ 1024;\n }\n};\n\n} \/\/ namespace hft::fenwick\n\n#endif \/\/ __FENWICK_NAIVE_HPP__\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (C) 2010-2012 Jeremy Lainé\n * Contact: http:\/\/code.google.com\/p\/qdjango\/\n *\n * This file is part of the QDjango Library.\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\/\n\n#include <QNetworkAccessManager>\n#include <QNetworkReply>\n#include <QNetworkRequest>\n#include <QtTest>\n#include <QUrl>\n\n#include \"QDjangoHttpController.h\"\n#include \"QDjangoHttpRequest.h\"\n#include \"QDjangoHttpResponse.h\"\n#include \"QDjangoUrlResolver.h\"\n\nclass tst_QDjangoUrlHelper : public QObject\n{\n Q_OBJECT\n\nprivate slots:\n QDjangoHttpResponse* _q_index(const QDjangoHttpRequest &request);\n QDjangoHttpResponse* _q_test(const QDjangoHttpRequest &request);\n};\n\nclass tst_QDjangoUrlResolver : public QObject\n{\n Q_OBJECT\n\nprivate slots:\n void cleanupTestCase();\n void initTestCase();\n void testRespond_data();\n void testRespond();\n void testReverse_data();\n void testReverse();\n\n QDjangoHttpResponse* _q_index(const QDjangoHttpRequest &request);\n QDjangoHttpResponse* _q_noArgs(const QDjangoHttpRequest &request);\n QDjangoHttpResponse* _q_oneArg(const QDjangoHttpRequest &request, const QString &id);\n QDjangoHttpResponse* _q_twoArgs(const QDjangoHttpRequest &request, const QString &id, const QString &action);\n\nprivate:\n tst_QDjangoUrlHelper *urlHelper;\n QDjangoUrlResolver *urlResolver;\n QDjangoUrlResolver *urlSub;\n};\n\nQDjangoHttpResponse* tst_QDjangoUrlHelper::_q_index(const QDjangoHttpRequest &request)\n{\n Q_UNUSED(request);\n\n QDjangoHttpResponse *response = new QDjangoHttpResponse;\n response->setHeader(QLatin1String(\"Content-Type\"), QLatin1String(\"text\/plain\"));\n response->setBody(\"sub index\");\n return response;\n}\n\nQDjangoHttpResponse* tst_QDjangoUrlHelper::_q_test(const QDjangoHttpRequest &request)\n{\n Q_UNUSED(request);\n\n QDjangoHttpResponse *response = new QDjangoHttpResponse;\n response->setHeader(QLatin1String(\"Content-Type\"), QLatin1String(\"text\/plain\"));\n response->setBody(\"sub test\");\n return response;\n}\n\nvoid tst_QDjangoUrlResolver::cleanupTestCase()\n{\n delete urlResolver;\n}\n\nvoid tst_QDjangoUrlResolver::initTestCase()\n{\n urlHelper = new tst_QDjangoUrlHelper;\n urlSub = new QDjangoUrlResolver;\n QVERIFY(urlSub->set(QRegExp(QLatin1String(\"^$\")), urlHelper, \"_q_index\"));\n QVERIFY(urlSub->set(QRegExp(QLatin1String(\"^test\/$\")), urlHelper, \"_q_test\"));\n\n urlResolver = new QDjangoUrlResolver;\n QVERIFY(urlResolver->set(QRegExp(QLatin1String(\"^$\")), this, \"_q_index\"));\n QVERIFY(urlResolver->set(QRegExp(QLatin1String(\"^test\/$\")), this, \"_q_noArgs\"));\n QVERIFY(urlResolver->set(QRegExp(QLatin1String(\"^test\/([0-9]+)\/$\")), this, \"_q_oneArg\"));\n QVERIFY(urlResolver->set(QRegExp(QLatin1String(\"^test\/([0-9]+)\/([a-z]+)\/$\")), this, \"_q_twoArgs\"));\n QVERIFY(urlResolver->include(QRegExp(QLatin1String(\"^recurse\/\")), urlSub));\n}\n\nvoid tst_QDjangoUrlResolver::testRespond_data()\n{\n QTest::addColumn<QString>(\"path\");\n QTest::addColumn<int>(\"err\");\n QTest::addColumn<QString>(\"body\");\n\n QTest::newRow(\"root\") << \"\/\" << 200 << \"\";\n QTest::newRow(\"not-found\") << \"\/non-existent\/\" << 404 << \"\";\n QTest::newRow(\"no-args\") << \"\/test\/\" << 200 << \"\";\n QTest::newRow(\"one-args\") << \"\/test\/123\/\" << 200 << \"\";\n QTest::newRow(\"two-args\") << \"\/test\/123\/delete\/\" << 200 << \"\";\n QTest::newRow(\"three-args\") << \"\/test\/123\/delete\/zoo\/\" << 404 << \"\";\n QTest::newRow(\"recurse-not-found\") << \"\/recurse\/non-existent\/\" << 404 << \"\";\n QTest::newRow(\"recurse-index\") << \"\/recurse\/\" << 200 << \"\";\n QTest::newRow(\"recurse-test\") << \"\/recurse\/test\/\" << 200 << \"\";\n}\n\nvoid tst_QDjangoUrlResolver::testRespond()\n{\n QFETCH(QString, path);\n QFETCH(int, err);\n QFETCH(QString, body);\n\n QDjangoHttpTestRequest request(QLatin1String(\"GET\"), path);\n QDjangoHttpResponse *response = urlResolver->respond(request, path);\n QVERIFY(response);\n QCOMPARE(int(response->statusCode()), err);\n}\n\nvoid tst_QDjangoUrlResolver::testReverse_data()\n{\n QTest::addColumn<QString>(\"path\");\n QTest::addColumn<QObject*>(\"receiver\");\n QTest::addColumn<QString>(\"member\");\n QTest::addColumn<QString>(\"args\");\n\n QObject *receiver = this;\n QTest::newRow(\"root\") << \"\/\" << receiver << \"_q_index\" << \"\";\n QTest::newRow(\"no-args\") << \"\/test\/\" << receiver << \"_q_noArgs\" << \"\";\n QTest::newRow(\"one-arg\") << \"\/test\/123\/\" << receiver << \"_q_oneArg\" << \"123\";\n QTest::newRow(\"two-args\") << \"\/test\/123\/delete\/\" << receiver << \"_q_twoArgs\" << \"123|delete\";\n QTest::newRow(\"too-few-args\") << \"\" << receiver << \"_q_oneArg\" << \"\";\n QTest::newRow(\"too-many-args\") << \"\" << receiver << \"_q_noArgs\" << \"123\";\n\n receiver = urlHelper;\n QTest::newRow(\"recurse-index\") << \"\/recurse\/\" << receiver << \"_q_index\" << \"\";\n QTest::newRow(\"recurse-test\") << \"\/recurse\/test\/\" << receiver << \"_q_test\" << \"\";\n}\n\nvoid tst_QDjangoUrlResolver::testReverse()\n{\n QFETCH(QString, path);\n QFETCH(QObject*, receiver);\n QFETCH(QString, member);\n QFETCH(QString, args);\n\n QVariantList varArgs;\n if (!args.isEmpty()) {\n foreach (const QString &bit, args.split(QLatin1Char('|')))\n varArgs << bit;\n }\n QCOMPARE(urlResolver->reverse(receiver, member.toLatin1(), varArgs), path);\n}\n\nQDjangoHttpResponse* tst_QDjangoUrlResolver::_q_index(const QDjangoHttpRequest &request)\n{\n Q_UNUSED(request);\n\n return new QDjangoHttpResponse;\n}\n\nQDjangoHttpResponse* tst_QDjangoUrlResolver::_q_noArgs(const QDjangoHttpRequest &request)\n{\n Q_UNUSED(request);\n\n return new QDjangoHttpResponse;\n}\n\nQDjangoHttpResponse* tst_QDjangoUrlResolver::_q_oneArg(const QDjangoHttpRequest &request, const QString &id)\n{\n Q_UNUSED(request);\n Q_UNUSED(id);\n\n return new QDjangoHttpResponse;\n}\n\nQDjangoHttpResponse* tst_QDjangoUrlResolver::_q_twoArgs(const QDjangoHttpRequest &request, const QString &id, const QString &action)\n{\n Q_UNUSED(request);\n Q_UNUSED(id);\n Q_UNUSED(action);\n\n return new QDjangoHttpResponse;\n}\n\nQTEST_MAIN(tst_QDjangoUrlResolver)\n#include \"tst_qdjangourlresolver.moc\"\n<commit_msg>explicitly test QDjangoUrlResolver warnings<commit_after>\/*\n * Copyright (C) 2010-2012 Jeremy Lainé\n * Contact: http:\/\/code.google.com\/p\/qdjango\/\n *\n * This file is part of the QDjango Library.\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\/\n\n#include <QNetworkAccessManager>\n#include <QNetworkReply>\n#include <QNetworkRequest>\n#include <QtTest>\n#include <QUrl>\n\n#include \"QDjangoHttpController.h\"\n#include \"QDjangoHttpRequest.h\"\n#include \"QDjangoHttpResponse.h\"\n#include \"QDjangoUrlResolver.h\"\n\nclass tst_QDjangoUrlHelper : public QObject\n{\n Q_OBJECT\n\nprivate slots:\n QDjangoHttpResponse* _q_index(const QDjangoHttpRequest &request);\n QDjangoHttpResponse* _q_test(const QDjangoHttpRequest &request);\n};\n\nclass tst_QDjangoUrlResolver : public QObject\n{\n Q_OBJECT\n\nprivate slots:\n void cleanupTestCase();\n void initTestCase();\n void testRespond_data();\n void testRespond();\n void testReverse_data();\n void testReverse();\n\n QDjangoHttpResponse* _q_index(const QDjangoHttpRequest &request);\n QDjangoHttpResponse* _q_noArgs(const QDjangoHttpRequest &request);\n QDjangoHttpResponse* _q_oneArg(const QDjangoHttpRequest &request, const QString &id);\n QDjangoHttpResponse* _q_twoArgs(const QDjangoHttpRequest &request, const QString &id, const QString &action);\n\nprivate:\n tst_QDjangoUrlHelper *urlHelper;\n QDjangoUrlResolver *urlResolver;\n QDjangoUrlResolver *urlSub;\n};\n\nQDjangoHttpResponse* tst_QDjangoUrlHelper::_q_index(const QDjangoHttpRequest &request)\n{\n Q_UNUSED(request);\n\n QDjangoHttpResponse *response = new QDjangoHttpResponse;\n response->setHeader(QLatin1String(\"Content-Type\"), QLatin1String(\"text\/plain\"));\n response->setBody(\"sub index\");\n return response;\n}\n\nQDjangoHttpResponse* tst_QDjangoUrlHelper::_q_test(const QDjangoHttpRequest &request)\n{\n Q_UNUSED(request);\n\n QDjangoHttpResponse *response = new QDjangoHttpResponse;\n response->setHeader(QLatin1String(\"Content-Type\"), QLatin1String(\"text\/plain\"));\n response->setBody(\"sub test\");\n return response;\n}\n\nvoid tst_QDjangoUrlResolver::cleanupTestCase()\n{\n delete urlResolver;\n}\n\nvoid tst_QDjangoUrlResolver::initTestCase()\n{\n urlHelper = new tst_QDjangoUrlHelper;\n urlSub = new QDjangoUrlResolver;\n QVERIFY(urlSub->set(QRegExp(QLatin1String(\"^$\")), urlHelper, \"_q_index\"));\n QVERIFY(urlSub->set(QRegExp(QLatin1String(\"^test\/$\")), urlHelper, \"_q_test\"));\n\n urlResolver = new QDjangoUrlResolver;\n QVERIFY(urlResolver->set(QRegExp(QLatin1String(\"^$\")), this, \"_q_index\"));\n QVERIFY(urlResolver->set(QRegExp(QLatin1String(\"^test\/$\")), this, \"_q_noArgs\"));\n QVERIFY(urlResolver->set(QRegExp(QLatin1String(\"^test\/([0-9]+)\/$\")), this, \"_q_oneArg\"));\n QVERIFY(urlResolver->set(QRegExp(QLatin1String(\"^test\/([0-9]+)\/([a-z]+)\/$\")), this, \"_q_twoArgs\"));\n QVERIFY(urlResolver->include(QRegExp(QLatin1String(\"^recurse\/\")), urlSub));\n}\n\nvoid tst_QDjangoUrlResolver::testRespond_data()\n{\n QTest::addColumn<QString>(\"path\");\n QTest::addColumn<int>(\"err\");\n QTest::addColumn<QString>(\"body\");\n\n QTest::newRow(\"root\") << \"\/\" << 200 << \"\";\n QTest::newRow(\"not-found\") << \"\/non-existent\/\" << 404 << \"\";\n QTest::newRow(\"no-args\") << \"\/test\/\" << 200 << \"\";\n QTest::newRow(\"one-args\") << \"\/test\/123\/\" << 200 << \"\";\n QTest::newRow(\"two-args\") << \"\/test\/123\/delete\/\" << 200 << \"\";\n QTest::newRow(\"three-args\") << \"\/test\/123\/delete\/zoo\/\" << 404 << \"\";\n QTest::newRow(\"recurse-not-found\") << \"\/recurse\/non-existent\/\" << 404 << \"\";\n QTest::newRow(\"recurse-index\") << \"\/recurse\/\" << 200 << \"\";\n QTest::newRow(\"recurse-test\") << \"\/recurse\/test\/\" << 200 << \"\";\n}\n\nvoid tst_QDjangoUrlResolver::testRespond()\n{\n QFETCH(QString, path);\n QFETCH(int, err);\n QFETCH(QString, body);\n\n QDjangoHttpTestRequest request(QLatin1String(\"GET\"), path);\n QDjangoHttpResponse *response = urlResolver->respond(request, path);\n QVERIFY(response);\n QCOMPARE(int(response->statusCode()), err);\n}\n\nvoid tst_QDjangoUrlResolver::testReverse_data()\n{\n QTest::addColumn<QString>(\"path\");\n QTest::addColumn<QObject*>(\"receiver\");\n QTest::addColumn<QString>(\"member\");\n QTest::addColumn<QString>(\"args\");\n QTest::addColumn<QString>(\"warning\");\n\n QObject *receiver = this;\n QTest::newRow(\"root\") << \"\/\" << receiver << \"_q_index\" << \"\" << \"\";\n QTest::newRow(\"no-args\") << \"\/test\/\" << receiver << \"_q_noArgs\" << \"\" << \"\";\n QTest::newRow(\"one-arg\") << \"\/test\/123\/\" << receiver << \"_q_oneArg\" << \"123\" << \"\";\n QTest::newRow(\"two-args\") << \"\/test\/123\/delete\/\" << receiver << \"_q_twoArgs\" << \"123|delete\" << \"\";\n QTest::newRow(\"too-few-args\") << \"\" << receiver << \"_q_oneArg\" << \"\" << \"Too few arguments for '_q_oneArg'\";\n QTest::newRow(\"too-many-args\") << \"\" << receiver << \"_q_noArgs\" << \"123\" << \"Too many arguments for '_q_noArgs'\";\n\n receiver = urlHelper;\n QTest::newRow(\"recurse-index\") << \"\/recurse\/\" << receiver << \"_q_index\" << \"\" << \"\";\n QTest::newRow(\"recurse-test\") << \"\/recurse\/test\/\" << receiver << \"_q_test\" << \"\" << \"\";\n}\n\nvoid tst_QDjangoUrlResolver::testReverse()\n{\n QFETCH(QString, path);\n QFETCH(QObject*, receiver);\n QFETCH(QString, member);\n QFETCH(QString, args);\n QFETCH(QString, warning);\n\n QVariantList varArgs;\n if (!args.isEmpty()) {\n foreach (const QString &bit, args.split(QLatin1Char('|')))\n varArgs << bit;\n }\n if (!warning.isEmpty())\n QTest::ignoreMessage(QtWarningMsg, warning.toLatin1());\n QCOMPARE(urlResolver->reverse(receiver, member.toLatin1(), varArgs), path);\n}\n\nQDjangoHttpResponse* tst_QDjangoUrlResolver::_q_index(const QDjangoHttpRequest &request)\n{\n Q_UNUSED(request);\n\n return new QDjangoHttpResponse;\n}\n\nQDjangoHttpResponse* tst_QDjangoUrlResolver::_q_noArgs(const QDjangoHttpRequest &request)\n{\n Q_UNUSED(request);\n\n return new QDjangoHttpResponse;\n}\n\nQDjangoHttpResponse* tst_QDjangoUrlResolver::_q_oneArg(const QDjangoHttpRequest &request, const QString &id)\n{\n Q_UNUSED(request);\n Q_UNUSED(id);\n\n return new QDjangoHttpResponse;\n}\n\nQDjangoHttpResponse* tst_QDjangoUrlResolver::_q_twoArgs(const QDjangoHttpRequest &request, const QString &id, const QString &action)\n{\n Q_UNUSED(request);\n Q_UNUSED(id);\n Q_UNUSED(action);\n\n return new QDjangoHttpResponse;\n}\n\nQTEST_MAIN(tst_QDjangoUrlResolver)\n#include \"tst_qdjangourlresolver.moc\"\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2017-2018 Global Phasing Ltd.\n\/\/\n\/\/ Heuristic methods for working with chains and polymers.\n\/\/ Includes also a few well-defined functions, such as removal of hydrogens.\n\n#ifndef GEMMI_POLYHEUR_HPP_\n#define GEMMI_POLYHEUR_HPP_\n\n#include <vector>\n#include \"model.hpp\"\n#include \"resinfo.hpp\" \/\/ for find_tabulated_residue\n#include \"util.hpp\" \/\/ for vector_remove_if\n\nnamespace gemmi {\n\n\/\/ A simplistic classification. It may change in the future.\n\/\/ It returns PolymerType which corresponds to _entity_poly.type,\n\/\/ but here we use only PeptideL, Rna, Dna, DnaRnaHybrid and Unknown.\ninline PolymerType check_polymer_type(const ConstResidueSpan& polymer) {\n if (polymer.size() < 2)\n return PolymerType::Unknown;\n size_t counts[ResidueInfo::ELS+1] = {0};\n size_t aa = 0;\n size_t na = 0;\n for (const Residue& r : polymer)\n if (r.entity_type == EntityType::Unknown ||\n r.entity_type == EntityType::Polymer) {\n ResidueInfo info = find_tabulated_residue(r.name);\n if (info.found())\n counts[info.kind]++;\n else if (r.get_ca())\n ++aa;\n else if (r.get_p())\n ++na;\n }\n aa += counts[ResidueInfo::AA] + counts[ResidueInfo::AAD] +\n counts[ResidueInfo::PAA] + counts[ResidueInfo::MAA];\n na += counts[ResidueInfo::RNA] + counts[ResidueInfo::DNA];\n if (aa == polymer.size() || (aa > 10 && 2 * aa > polymer.size()))\n return counts[ResidueInfo::AA] >= counts[ResidueInfo::AAD]\n ? PolymerType::PeptideL : PolymerType::PeptideD;\n if (na == polymer.size() || (na > 10 && 2 * na > polymer.size())) {\n if (counts[ResidueInfo::DNA] == 0)\n return PolymerType::Rna;\n else if (counts[ResidueInfo::RNA] == 0)\n return PolymerType::Dna;\n else\n return PolymerType::DnaRnaHybrid;\n }\n return PolymerType::Unknown;\n}\n\ninline double calculate_sequence_weight(const std::vector<std::string>& seq,\n double unknown=0.) {\n double weight = 0.;\n for (const std::string& item : seq) {\n ResidueInfo res_info = find_tabulated_residue(Entity::first_mon(item));\n weight += res_info.found() ? res_info.weight : unknown;\n }\n return weight;\n}\n\ninline bool is_polymer_residue(const Residue& res, PolymerType ptype) {\n ResidueInfo info = find_tabulated_residue(res.name);\n \/\/ If a standard residue is HETATM we assume that it is in the buffer.\n if (info.found() && info.is_standard() && res.het_flag == 'H')\n return false;\n switch (ptype) {\n case PolymerType::PeptideL:\n case PolymerType::PeptideD:\n \/\/ here we don't mind mixing D- and L- peptides\n return info.found() ? info.is_amino_acid() : !!res.get_ca();\n case PolymerType::Dna:\n return info.found() ? info.is_dna() : !!res.get_p();\n case PolymerType::Rna:\n return info.found() ? info.is_rna() : !!res.get_p();\n case PolymerType::DnaRnaHybrid:\n return info.found() ? info.is_nucleic_acid() : !!res.get_p();\n default:\n return false;\n }\n}\n\ninline bool are_connected(const Residue& r1, const Residue& r2,\n PolymerType ptype) {\n if (is_polypeptide(ptype)) {\n \/\/ similar to has_peptide_bond_to()\n const Atom* a1 = r1.get_c();\n const Atom* a2 = r2.get_n();\n return a1 && a2 && a1->pos.dist_sq(a2->pos) < sq(1.341 * 1.5);\n }\n if (is_polynucleotide(ptype)) {\n const Atom* a1 = r1.get_o3prim();\n const Atom* a2 = r2.get_p();\n return a1 && a2 && a1->pos.dist_sq(a2->pos) < sq(1.6 * 1.5);\n }\n return false;\n}\n\n\/\/ not a good check, but requires only CA (or P) atoms\ninline bool are_connected2(const Residue& r1, const Residue& r2,\n PolymerType ptype) {\n if (is_polypeptide(ptype)) {\n const Atom* a1 = r1.get_ca();\n const Atom* a2 = r2.get_ca();\n return a1 && a2 && a1->pos.dist_sq(a2->pos) < sq(5.0);\n }\n if (is_polynucleotide(ptype)) {\n const Atom* a1 = r1.get_p();\n const Atom* a2 = r2.get_p();\n return a1 && a2 && a1->pos.dist_sq(a2->pos) < sq(7.5);\n }\n return false;\n}\n\n\/\/ are_connected3() = are_connected() + fallback to are_connected2()\ninline bool are_connected3(const Residue& r1, const Residue& r2,\n PolymerType ptype) {\n if (is_polypeptide(ptype)) {\n if (const Atom* a1 = r1.get_c())\n if (const Atom* a2 = r2.get_n())\n return a1->pos.dist_sq(a2->pos) < sq(1.341 * 1.5);\n if (const Atom* a1 = r1.get_ca())\n if (const Atom* a2 = r2.get_ca())\n return a1 && a2 && a1->pos.dist_sq(a2->pos) < sq(5.0);\n } else if (is_polynucleotide(ptype)) {\n if (const Atom* a1 = r1.get_o3prim())\n if (const Atom* a2 = r2.get_p())\n return a1->pos.dist_sq(a2->pos) < sq(1.6 * 1.5);\n if (const Atom* a1 = r1.get_p())\n if (const Atom* a2 = r2.get_p())\n return a1->pos.dist_sq(a2->pos) < sq(7.5);\n }\n return false;\n}\n\ninline std::string make_one_letter_sequence(const ConstResidueSpan& polymer) {\n std::string seq;\n const Residue* prev = nullptr;\n PolymerType ptype = check_polymer_type(polymer);\n for (const Residue& residue : polymer.first_conformer()) {\n ResidueInfo info = find_tabulated_residue(residue.name);\n if (prev && !are_connected2(*prev, residue, ptype))\n seq += '-';\n seq += (info.one_letter_code != ' ' ? info.one_letter_code : 'X');\n prev = &residue;\n }\n return seq;\n}\n\ninline bool has_subchains_assigned(const Chain& chain) {\n return std::all_of(chain.residues.begin(), chain.residues.end(),\n [](const Residue& r) { return !r.subchain.empty(); });\n}\n\ninline void add_entity_types(Chain& chain, bool overwrite) {\n PolymerType ptype = check_polymer_type(chain.whole());\n auto it = chain.residues.begin();\n for (; it != chain.residues.end(); ++it)\n if (overwrite || it->entity_type == EntityType::Unknown) {\n if (!is_polymer_residue(*it, ptype))\n break;\n it->entity_type = EntityType::Polymer;\n } else if (it->entity_type != EntityType::Polymer) {\n break;\n }\n for (; it != chain.residues.end(); ++it)\n if (overwrite || it->entity_type == EntityType::Unknown)\n it->entity_type = it->is_water() ? EntityType::Water\n : EntityType::NonPolymer;\n}\n\ninline void add_entity_types(Structure& st, bool overwrite) {\n for (Model& model : st.models)\n for (Chain& chain : model.chains)\n add_entity_types(chain, overwrite);\n}\n\n\/\/ The subchain field in the residue is where we store_atom_site.label_asym_id\n\/\/ from mmCIF files. As of 2018 wwPDB software splits author's chains\n\/\/ (auth_asym_id) into label_asym_id units:\n\/\/ * linear polymer,\n\/\/ * non-polymers (each residue has different separate label_asym_id),\n\/\/ * and waters.\n\/\/ Refmac\/makecif is doing similar thing but using different naming and\n\/\/ somewhat different rules (it was written in 1990's before PDBx\/mmCIF).\n\/\/\n\/\/ Here we use naming and rules different from both wwPDB and makecif.\ninline void assign_subchain_names(Chain& chain) {\n for (Residue& res : chain.residues) {\n res.subchain = chain.name;\n switch (res.entity_type) {\n case EntityType::Polymer: res.subchain += \"poly\"; break;\n case EntityType::NonPolymer: res.subchain += res.seqid.str(); break;\n case EntityType::Water: res.subchain += \"wat\"; break;\n case EntityType::Unknown: break; \/\/ should not happen\n }\n }\n}\n\ninline void assign_subchains(Structure& st, bool force) {\n for (Model& model : st.models)\n for (Chain& chain : model.chains)\n if (force || !has_subchains_assigned(chain)) {\n add_entity_types(chain, false);\n assign_subchain_names(chain);\n }\n}\n\ninline void ensure_entities(Structure& st) {\n for (Model& model : st.models)\n for (Chain& chain : model.chains)\n for (ResidueSpan& sub : chain.subchains()) {\n Entity* ent = st.get_entity_of(sub);\n if (!ent) {\n EntityType etype = sub[0].entity_type;\n std::string name;\n if (etype == EntityType::Polymer)\n name = chain.name;\n else if (etype == EntityType::NonPolymer)\n name = sub[0].name + \"!\";\n else if (etype == EntityType::Water)\n name = \"water\";\n if (!name.empty()) {\n ent = &impl::find_or_add(st.entities, name);\n ent->entity_type = etype;\n ent->subchains.push_back(sub.subchain_id());\n }\n }\n \/\/ ensure we have polymer_type set where needed\n if (ent && ent->entity_type == EntityType::Polymer &&\n ent->polymer_type == PolymerType::Unknown)\n ent->polymer_type = check_polymer_type(sub);\n }\n}\n\n\ninline void deduplicate_entities(Structure& st) {\n for (auto i = st.entities.begin(); i != st.entities.end(); ++i)\n if (!i->full_sequence.empty())\n for (auto j = i + 1; j != st.entities.end(); ++j)\n if (j->polymer_type == i->polymer_type &&\n j->full_sequence == i->full_sequence) {\n vector_move_extend(i->subchains, std::move(j->subchains));\n st.entities.erase(j--);\n }\n}\n\ninline void setup_entities(Structure& st) {\n assign_subchains(st, false);\n ensure_entities(st);\n deduplicate_entities(st);\n}\n\n\/\/ Remove hydrogens.\ntemplate<class T> void remove_hydrogens(T& obj) {\n for (auto& child : obj.children())\n remove_hydrogens(child);\n}\ntemplate<> inline void remove_hydrogens(Residue& res) {\n vector_remove_if(res.atoms, [](const Atom& a) {\n return a.element == El::H || a.element == El::D;\n });\n}\n\n\/\/ Remove waters. It may leave empty chains.\ntemplate<class T> void remove_waters(T& obj) {\n for (auto& child : obj.children())\n remove_waters(child);\n}\ntemplate<> inline void remove_waters(Chain& ch) {\n vector_remove_if(ch.residues,\n [](const Residue& res) { return res.is_water(); });\n}\n\n\/\/ Remove ligands and waters. It may leave empty chains.\ninline void remove_ligands_and_waters(Chain& ch) {\n PolymerType ptype = check_polymer_type(ch.whole());\n vector_remove_if(ch.residues, [&](const Residue& res) {\n if (res.entity_type == EntityType::Unknown) {\n \/\/ TODO: check connectivity\n return !is_polymer_residue(res, ptype);\n }\n return res.entity_type != EntityType::Polymer;\n });\n}\n\ninline void remove_ligands_and_waters(Structure& st) {\n for (Model& model : st.models)\n for (Chain& chain : model.chains)\n remove_ligands_and_waters(chain);\n}\n\n\/\/ Remove empty chains.\ninline void remove_empty_chains(Model& m) {\n vector_remove_if(m.chains,\n [](const Chain& chain) { return chain.residues.empty(); });\n}\ninline void remove_empty_chains(Structure& st) {\n for (Model& model : st.models)\n remove_empty_chains(model);\n}\n\n\/\/ Trim to alanine. Returns true if trimmed, false if it's (likely) not AA.\ninline bool trim_to_alanine(Residue& res) {\n static const std::pair<std::string, El> ala_atoms[6] = {\n {\"N\", El::N}, {\"CA\", El::C}, {\"C\", El::C}, {\"O\", El::O}, {\"CB\", El::C},\n {\"OXT\", El::O}\n };\n if (res.get_ca() == nullptr)\n return false;\n vector_remove_if(res.atoms, [](const Atom& a) {\n for (const auto& name_el : ala_atoms)\n if (a.name == name_el.first && a.element == name_el.second)\n return false;\n return true;\n });\n return true;\n}\n\ninline void trim_to_alanine(Chain& chain) {\n for (Residue& res : chain.residues)\n trim_to_alanine(res);\n}\n\n} \/\/ namespace gemmi\n#endif\n<commit_msg>one_letter_code()<commit_after>\/\/ Copyright 2017-2018 Global Phasing Ltd.\n\/\/\n\/\/ Heuristic methods for working with chains and polymers.\n\/\/ Includes also a few well-defined functions, such as removal of hydrogens.\n\n#ifndef GEMMI_POLYHEUR_HPP_\n#define GEMMI_POLYHEUR_HPP_\n\n#include <vector>\n#include \"model.hpp\"\n#include \"resinfo.hpp\" \/\/ for find_tabulated_residue\n#include \"util.hpp\" \/\/ for vector_remove_if\n\nnamespace gemmi {\n\n\/\/ A simplistic classification. It may change in the future.\n\/\/ It returns PolymerType which corresponds to _entity_poly.type,\n\/\/ but here we use only PeptideL, Rna, Dna, DnaRnaHybrid and Unknown.\ninline PolymerType check_polymer_type(const ConstResidueSpan& polymer) {\n if (polymer.size() < 2)\n return PolymerType::Unknown;\n size_t counts[ResidueInfo::ELS+1] = {0};\n size_t aa = 0;\n size_t na = 0;\n for (const Residue& r : polymer)\n if (r.entity_type == EntityType::Unknown ||\n r.entity_type == EntityType::Polymer) {\n ResidueInfo info = find_tabulated_residue(r.name);\n if (info.found())\n counts[info.kind]++;\n else if (r.get_ca())\n ++aa;\n else if (r.get_p())\n ++na;\n }\n aa += counts[ResidueInfo::AA] + counts[ResidueInfo::AAD] +\n counts[ResidueInfo::PAA] + counts[ResidueInfo::MAA];\n na += counts[ResidueInfo::RNA] + counts[ResidueInfo::DNA];\n if (aa == polymer.size() || (aa > 10 && 2 * aa > polymer.size()))\n return counts[ResidueInfo::AA] >= counts[ResidueInfo::AAD]\n ? PolymerType::PeptideL : PolymerType::PeptideD;\n if (na == polymer.size() || (na > 10 && 2 * na > polymer.size())) {\n if (counts[ResidueInfo::DNA] == 0)\n return PolymerType::Rna;\n else if (counts[ResidueInfo::RNA] == 0)\n return PolymerType::Dna;\n else\n return PolymerType::DnaRnaHybrid;\n }\n return PolymerType::Unknown;\n}\n\ninline double calculate_sequence_weight(const std::vector<std::string>& seq,\n double unknown=0.) {\n double weight = 0.;\n for (const std::string& item : seq) {\n ResidueInfo res_info = find_tabulated_residue(Entity::first_mon(item));\n weight += res_info.found() ? res_info.weight : unknown;\n }\n return weight;\n}\n\ninline std::string one_letter_code(const std::vector<std::string>& seq) {\n std::string r;\n for (const std::string& item : seq)\n r += find_tabulated_residue(Entity::first_mon(item)).fasta_code();\n return r;\n}\n\ninline std::string one_letter_code(const ConstResidueSpan& polymer) {\n std::string r;\n for (const Residue& res : polymer.first_conformer())\n r += find_tabulated_residue(res.name).fasta_code();\n return r;\n}\n\ninline bool is_polymer_residue(const Residue& res, PolymerType ptype) {\n ResidueInfo info = find_tabulated_residue(res.name);\n \/\/ If a standard residue is HETATM we assume that it is in the buffer.\n if (info.found() && info.is_standard() && res.het_flag == 'H')\n return false;\n switch (ptype) {\n case PolymerType::PeptideL:\n case PolymerType::PeptideD:\n \/\/ here we don't mind mixing D- and L- peptides\n return info.found() ? info.is_amino_acid() : !!res.get_ca();\n case PolymerType::Dna:\n return info.found() ? info.is_dna() : !!res.get_p();\n case PolymerType::Rna:\n return info.found() ? info.is_rna() : !!res.get_p();\n case PolymerType::DnaRnaHybrid:\n return info.found() ? info.is_nucleic_acid() : !!res.get_p();\n default:\n return false;\n }\n}\n\ninline bool are_connected(const Residue& r1, const Residue& r2,\n PolymerType ptype) {\n if (is_polypeptide(ptype)) {\n \/\/ similar to has_peptide_bond_to()\n const Atom* a1 = r1.get_c();\n const Atom* a2 = r2.get_n();\n return a1 && a2 && a1->pos.dist_sq(a2->pos) < sq(1.341 * 1.5);\n }\n if (is_polynucleotide(ptype)) {\n const Atom* a1 = r1.get_o3prim();\n const Atom* a2 = r2.get_p();\n return a1 && a2 && a1->pos.dist_sq(a2->pos) < sq(1.6 * 1.5);\n }\n return false;\n}\n\n\/\/ not a good check, but requires only CA (or P) atoms\ninline bool are_connected2(const Residue& r1, const Residue& r2,\n PolymerType ptype) {\n if (is_polypeptide(ptype)) {\n const Atom* a1 = r1.get_ca();\n const Atom* a2 = r2.get_ca();\n return a1 && a2 && a1->pos.dist_sq(a2->pos) < sq(5.0);\n }\n if (is_polynucleotide(ptype)) {\n const Atom* a1 = r1.get_p();\n const Atom* a2 = r2.get_p();\n return a1 && a2 && a1->pos.dist_sq(a2->pos) < sq(7.5);\n }\n return false;\n}\n\n\/\/ are_connected3() = are_connected() + fallback to are_connected2()\ninline bool are_connected3(const Residue& r1, const Residue& r2,\n PolymerType ptype) {\n if (is_polypeptide(ptype)) {\n if (const Atom* a1 = r1.get_c())\n if (const Atom* a2 = r2.get_n())\n return a1->pos.dist_sq(a2->pos) < sq(1.341 * 1.5);\n if (const Atom* a1 = r1.get_ca())\n if (const Atom* a2 = r2.get_ca())\n return a1 && a2 && a1->pos.dist_sq(a2->pos) < sq(5.0);\n } else if (is_polynucleotide(ptype)) {\n if (const Atom* a1 = r1.get_o3prim())\n if (const Atom* a2 = r2.get_p())\n return a1->pos.dist_sq(a2->pos) < sq(1.6 * 1.5);\n if (const Atom* a1 = r1.get_p())\n if (const Atom* a2 = r2.get_p())\n return a1->pos.dist_sq(a2->pos) < sq(7.5);\n }\n return false;\n}\n\ninline std::string make_one_letter_sequence(const ConstResidueSpan& polymer) {\n std::string seq;\n const Residue* prev = nullptr;\n PolymerType ptype = check_polymer_type(polymer);\n for (const Residue& residue : polymer.first_conformer()) {\n ResidueInfo info = find_tabulated_residue(residue.name);\n if (prev && !are_connected2(*prev, residue, ptype))\n seq += '-';\n seq += (info.one_letter_code != ' ' ? info.one_letter_code : 'X');\n prev = &residue;\n }\n return seq;\n}\n\ninline bool has_subchains_assigned(const Chain& chain) {\n return std::all_of(chain.residues.begin(), chain.residues.end(),\n [](const Residue& r) { return !r.subchain.empty(); });\n}\n\ninline void add_entity_types(Chain& chain, bool overwrite) {\n PolymerType ptype = check_polymer_type(chain.whole());\n auto it = chain.residues.begin();\n for (; it != chain.residues.end(); ++it)\n if (overwrite || it->entity_type == EntityType::Unknown) {\n if (!is_polymer_residue(*it, ptype))\n break;\n it->entity_type = EntityType::Polymer;\n } else if (it->entity_type != EntityType::Polymer) {\n break;\n }\n for (; it != chain.residues.end(); ++it)\n if (overwrite || it->entity_type == EntityType::Unknown)\n it->entity_type = it->is_water() ? EntityType::Water\n : EntityType::NonPolymer;\n}\n\ninline void add_entity_types(Structure& st, bool overwrite) {\n for (Model& model : st.models)\n for (Chain& chain : model.chains)\n add_entity_types(chain, overwrite);\n}\n\n\/\/ The subchain field in the residue is where we store_atom_site.label_asym_id\n\/\/ from mmCIF files. As of 2018 wwPDB software splits author's chains\n\/\/ (auth_asym_id) into label_asym_id units:\n\/\/ * linear polymer,\n\/\/ * non-polymers (each residue has different separate label_asym_id),\n\/\/ * and waters.\n\/\/ Refmac\/makecif is doing similar thing but using different naming and\n\/\/ somewhat different rules (it was written in 1990's before PDBx\/mmCIF).\n\/\/\n\/\/ Here we use naming and rules different from both wwPDB and makecif.\ninline void assign_subchain_names(Chain& chain) {\n for (Residue& res : chain.residues) {\n res.subchain = chain.name;\n switch (res.entity_type) {\n case EntityType::Polymer: res.subchain += \"poly\"; break;\n case EntityType::NonPolymer: res.subchain += res.seqid.str(); break;\n case EntityType::Water: res.subchain += \"wat\"; break;\n case EntityType::Unknown: break; \/\/ should not happen\n }\n }\n}\n\ninline void assign_subchains(Structure& st, bool force) {\n for (Model& model : st.models)\n for (Chain& chain : model.chains)\n if (force || !has_subchains_assigned(chain)) {\n add_entity_types(chain, false);\n assign_subchain_names(chain);\n }\n}\n\ninline void ensure_entities(Structure& st) {\n for (Model& model : st.models)\n for (Chain& chain : model.chains)\n for (ResidueSpan& sub : chain.subchains()) {\n Entity* ent = st.get_entity_of(sub);\n if (!ent) {\n EntityType etype = sub[0].entity_type;\n std::string name;\n if (etype == EntityType::Polymer)\n name = chain.name;\n else if (etype == EntityType::NonPolymer)\n name = sub[0].name + \"!\";\n else if (etype == EntityType::Water)\n name = \"water\";\n if (!name.empty()) {\n ent = &impl::find_or_add(st.entities, name);\n ent->entity_type = etype;\n ent->subchains.push_back(sub.subchain_id());\n }\n }\n \/\/ ensure we have polymer_type set where needed\n if (ent && ent->entity_type == EntityType::Polymer &&\n ent->polymer_type == PolymerType::Unknown)\n ent->polymer_type = check_polymer_type(sub);\n }\n}\n\n\ninline void deduplicate_entities(Structure& st) {\n for (auto i = st.entities.begin(); i != st.entities.end(); ++i)\n if (!i->full_sequence.empty())\n for (auto j = i + 1; j != st.entities.end(); ++j)\n if (j->polymer_type == i->polymer_type &&\n j->full_sequence == i->full_sequence) {\n vector_move_extend(i->subchains, std::move(j->subchains));\n st.entities.erase(j--);\n }\n}\n\ninline void setup_entities(Structure& st) {\n assign_subchains(st, false);\n ensure_entities(st);\n deduplicate_entities(st);\n}\n\n\/\/ Remove hydrogens.\ntemplate<class T> void remove_hydrogens(T& obj) {\n for (auto& child : obj.children())\n remove_hydrogens(child);\n}\ntemplate<> inline void remove_hydrogens(Residue& res) {\n vector_remove_if(res.atoms, [](const Atom& a) {\n return a.element == El::H || a.element == El::D;\n });\n}\n\n\/\/ Remove waters. It may leave empty chains.\ntemplate<class T> void remove_waters(T& obj) {\n for (auto& child : obj.children())\n remove_waters(child);\n}\ntemplate<> inline void remove_waters(Chain& ch) {\n vector_remove_if(ch.residues,\n [](const Residue& res) { return res.is_water(); });\n}\n\n\/\/ Remove ligands and waters. It may leave empty chains.\ninline void remove_ligands_and_waters(Chain& ch) {\n PolymerType ptype = check_polymer_type(ch.whole());\n vector_remove_if(ch.residues, [&](const Residue& res) {\n if (res.entity_type == EntityType::Unknown) {\n \/\/ TODO: check connectivity\n return !is_polymer_residue(res, ptype);\n }\n return res.entity_type != EntityType::Polymer;\n });\n}\n\ninline void remove_ligands_and_waters(Structure& st) {\n for (Model& model : st.models)\n for (Chain& chain : model.chains)\n remove_ligands_and_waters(chain);\n}\n\n\/\/ Remove empty chains.\ninline void remove_empty_chains(Model& m) {\n vector_remove_if(m.chains,\n [](const Chain& chain) { return chain.residues.empty(); });\n}\ninline void remove_empty_chains(Structure& st) {\n for (Model& model : st.models)\n remove_empty_chains(model);\n}\n\n\/\/ Trim to alanine. Returns true if trimmed, false if it's (likely) not AA.\ninline bool trim_to_alanine(Residue& res) {\n static const std::pair<std::string, El> ala_atoms[6] = {\n {\"N\", El::N}, {\"CA\", El::C}, {\"C\", El::C}, {\"O\", El::O}, {\"CB\", El::C},\n {\"OXT\", El::O}\n };\n if (res.get_ca() == nullptr)\n return false;\n vector_remove_if(res.atoms, [](const Atom& a) {\n for (const auto& name_el : ala_atoms)\n if (a.name == name_el.first && a.element == name_el.second)\n return false;\n return true;\n });\n return true;\n}\n\ninline void trim_to_alanine(Chain& chain) {\n for (Residue& res : chain.residues)\n trim_to_alanine(res);\n}\n\n} \/\/ namespace gemmi\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 2015 David Wicks, sansumbrella.com\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or\n * without modification, are permitted provided that the following\n * conditions are met:\n *\n * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \"SimpleMarkov.h\"\n<commit_msg>Remove unused cpp file.<commit_after><|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: fmcontrolbordermanager.hxx,v $\n *\n * $Revision: 1.4 $\n *\n * last change: $Author: obo $ $Date: 2005-01-05 12:22:58 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef SVX_SOURCE_INC_FMCONTROLBORDERMANAGER_HXX\n#define SVX_SOURCE_INC_FMCONTROLBORDERMANAGER_HXX\n\n\/** === begin UNO includes === **\/\n#ifndef _COM_SUN_STAR_AWT_VISUALEFFECT_HPP_\n#include <com\/sun\/star\/awt\/VisualEffect.hpp>\n#endif\n#ifndef _COM_SUN_STAR_AWT_FONTUNDERLINE_HPP_\n#include <com\/sun\/star\/awt\/FontUnderline.hpp>\n#endif\n#ifndef _COM_SUN_STAR_AWT_XCONTROL_HPP_\n#include <com\/sun\/star\/awt\/XControl.hpp>\n#endif\n#ifndef _COM_SUN_STAR_AWT_XVCLWINDOWPEER_HPP_\n#include <com\/sun\/star\/awt\/XVclWindowPeer.hpp>\n#endif\n\/** === end UNO includes === **\/\n#ifndef _COMPHELPER_STLTYPES_HXX_\n#include <comphelper\/stl_types.hxx>\n#endif\n\n#ifndef _COMPHELPER_STLTYPES_HXX_\n#include <comphelper\/stl_types.hxx>\n#endif\n\n#include <set>\n\nnamespace com { namespace sun { namespace star { namespace form { namespace validation {\n class XValidatableFormComponent;\n} } } } }\n\n\/\/........................................................................\nnamespace svxform\n{\n\/\/........................................................................\n\n typedef sal_Int16 ControlStatus;\n\n #define CONTROL_STATUS_NONE 0x00\n #define CONTROL_STATUS_FOCUSED 0x01\n #define CONTROL_STATUS_MOUSE_HOVER 0x02\n #define CONTROL_STATUS_INVALID 0x04\n\n \/\/====================================================================\n \/\/= BorderDescriptor\n \/\/====================================================================\n struct BorderDescriptor\n {\n sal_Int16 nBorderType;\n sal_Int32 nBorderColor;\n\n BorderDescriptor()\n :nBorderType( ::com::sun::star::awt::VisualEffect::FLAT )\n ,nBorderColor( 0x00000000 )\n {\n }\n inline void clear()\n {\n nBorderType = ::com::sun::star::awt::VisualEffect::FLAT;\n nBorderColor = 0x00000000;\n }\n };\n\n \/\/====================================================================\n \/\/= UnderlineDescriptor\n \/\/====================================================================\n struct UnderlineDescriptor\n {\n sal_Int16 nUnderlineType;\n sal_Int32 nUnderlineColor;\n\n UnderlineDescriptor()\n :nUnderlineType( ::com::sun::star::awt::FontUnderline::NONE )\n ,nUnderlineColor( 0x00000000 )\n {\n }\n\n UnderlineDescriptor( sal_Int16 _nUnderlineType, sal_Int32 _nUnderlineColor )\n :nUnderlineType( _nUnderlineType )\n ,nUnderlineColor( _nUnderlineColor )\n {\n }\n\n inline void clear()\n {\n nUnderlineType = ::com::sun::star::awt::FontUnderline::NONE;\n nUnderlineColor = 0x00000000;\n }\n };\n\n \/\/====================================================================\n \/\/= ControlData\n \/\/====================================================================\n struct ControlData : public BorderDescriptor, UnderlineDescriptor\n {\n ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControl > xControl;\n ::rtl::OUString sOriginalHelpText;\n\n ControlData() : BorderDescriptor() { }\n ControlData( const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControl >& _rxControl )\n :xControl( _rxControl )\n {\n }\n void clear()\n {\n BorderDescriptor::clear();\n UnderlineDescriptor::clear();\n xControl.clear();\n sOriginalHelpText = ::rtl::OUString();\n }\n };\n\n \/\/====================================================================\n \/\/= ControlBorderManager\n \/\/====================================================================\n \/** manages the dynamic border color for form controls\n\n Used by the <type>FmXFormController<\/type>, this class manages the dynamic changes in the\n border color of form controls. For this a set of events have to be forwarded to the manager\n instance, which then will switch the border color depending on the mouse and focus status\n of the controls.\n *\/\n class ControlBorderManager\n {\n private:\n struct ControlDataCompare : public ::std::binary_function< ControlData, ControlData, bool >\n {\n bool operator()( const ControlData& _rLHS, const ControlData& _rRHS ) const\n {\n return _rLHS.xControl.get() < _rRHS.xControl.get();\n }\n };\n\n typedef ::std::set< ControlData, ControlDataCompare > ControlBag;\n typedef ::com::sun::star::awt::XVclWindowPeer WindowPeer;\n typedef ::com::sun::star::uno::Reference< ::com::sun::star::awt::XVclWindowPeer > WindowPeerRef;\n typedef ::std::set< WindowPeerRef, ::comphelper::OInterfaceCompare< WindowPeer > > PeerBag;\n\n PeerBag m_aColorableControls;\n PeerBag m_aNonColorableControls;\n\n ControlData m_aFocusControl;\n ControlData m_aMouseHoverControl;\n ControlBag m_aInvalidControls;\n\n \/\/ ----------------\n \/\/ attributes\n sal_Int32 m_nFocusColor;\n sal_Int32 m_nMouseHoveColor;\n sal_Int32 m_nInvalidColor;\n bool m_bDynamicBorderColors;\n\n public:\n ControlBorderManager();\n ~ControlBorderManager();\n\n public:\n void focusGained( const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& _rxControl ) SAL_THROW(());\n void focusLost( const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& _rxControl ) SAL_THROW(());\n void mouseEntered( const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& _rxControl ) SAL_THROW(());\n void mouseExited( const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& _rxControl ) SAL_THROW(());\n\n void validityChanged(\n const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControl >& _rxControl,\n const ::com::sun::star::uno::Reference< ::com::sun::star::form::validation::XValidatableFormComponent >& _rxValidatable\n ) SAL_THROW(());\n\n \/\/\/ enables dynamic border color for the controls\n void enableDynamicBorderColor( );\n \/\/\/ disables dynamic border color for the controls\n void disableDynamicBorderColor( );\n\n \/** sets a color to be used for a given status\n @param _nStatus\n the status which the color should be applied for. Must not be CONTROL_STATUS_NONE\n @param _nColor\n the color to apply for the given status\n *\/\n void setStatusColor( ControlStatus _nStatus, sal_Int32 _nColor );\n\n \/** restores all colors of all controls where we possibly changed them\n *\/\n void restoreAll();\n\n private:\n \/** called when a control got one of the two possible stati (focused, and hovered with the mouse)\n @param _rxControl\n the control which gained the status\n @param _rControlData\n the control's status data, as a reference to our respective member\n *\/\n void controlStatusGained(\n const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& _rxControl,\n ControlData& _rControlData\n ) SAL_THROW(());\n\n \/** called when a control lost one of the two possible stati (focused, and hovered with the mouse)\n @param _rxControl\n the control which lost the status\n @param _rControlData\n the control's status data, as a reference to our respective member\n *\/\n void controlStatusLost( const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& _rxControl, ControlData& _rControlData ) SAL_THROW(());\n\n \/** determines whether the border of a given peer can be colored\n @param _rxPeer\n the peer to examine. Must not be <NULL\/>\n *\/\n bool canColorBorder( const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XVclWindowPeer >& _rxPeer );\n\n \/** determines the status of the given control\n *\/\n ControlStatus getControlStatus( const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControl >& _rxControl ) SAL_THROW(());\n\n \/** retrieves the color associated with a given ControlStatus\n @param _eStatus\n the status of the control. Must not be <member>ControlStatus::none<\/member>\n *\/\n sal_Int32 getControlColorByStatus( ControlStatus _eStatus );\n\n \/** sets the border color for a given control, depending on its status\n @param _rxControl\n the control to set the border color for. Must not be <NULL\/>\n @param _rxPeer\n the peer of the control, to be passed herein for optimization the caller usually needs it, anyway).\n Must not be <NULL\/>\n @param _rFallback\n the color\/type to use when the control has the status CONTROL_STATUS_NONE\n *\/\n void updateBorderStyle(\n const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControl >& _rxControl,\n const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XVclWindowPeer >& _rxPeer,\n const BorderDescriptor& _rFallback\n ) SAL_THROW(());\n\n \/** determines the to-be-remembered original border color and type for a control\n\n The method also takes into account that the control may currently have an overwritten\n border style\n\n @param _rxControl\n the control to examine. Must not be <NULL\/>, and have a non-<NULL\/> peer\n *\/\n void determineOriginalBorderStyle(\n const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControl >& _rxControl,\n BorderDescriptor& _rData\n ) const;\n };\n\n\/\/........................................................................\n} \/\/ namespace svxform\n\/\/........................................................................\n\n#endif \/\/ SVX_SOURCE_INC_FMCONTROLBORDERMANAGER_HXX\n<commit_msg>INTEGRATION: CWS ooo19126 (1.4.486); FILE MERGED 2005\/09\/05 14:25:04 rt 1.4.486.1: #i54170# Change license header: remove SISSL<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: fmcontrolbordermanager.hxx,v $\n *\n * $Revision: 1.5 $\n *\n * last change: $Author: rt $ $Date: 2005-09-08 23:14:36 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef SVX_SOURCE_INC_FMCONTROLBORDERMANAGER_HXX\n#define SVX_SOURCE_INC_FMCONTROLBORDERMANAGER_HXX\n\n\/** === begin UNO includes === **\/\n#ifndef _COM_SUN_STAR_AWT_VISUALEFFECT_HPP_\n#include <com\/sun\/star\/awt\/VisualEffect.hpp>\n#endif\n#ifndef _COM_SUN_STAR_AWT_FONTUNDERLINE_HPP_\n#include <com\/sun\/star\/awt\/FontUnderline.hpp>\n#endif\n#ifndef _COM_SUN_STAR_AWT_XCONTROL_HPP_\n#include <com\/sun\/star\/awt\/XControl.hpp>\n#endif\n#ifndef _COM_SUN_STAR_AWT_XVCLWINDOWPEER_HPP_\n#include <com\/sun\/star\/awt\/XVclWindowPeer.hpp>\n#endif\n\/** === end UNO includes === **\/\n#ifndef _COMPHELPER_STLTYPES_HXX_\n#include <comphelper\/stl_types.hxx>\n#endif\n\n#ifndef _COMPHELPER_STLTYPES_HXX_\n#include <comphelper\/stl_types.hxx>\n#endif\n\n#include <set>\n\nnamespace com { namespace sun { namespace star { namespace form { namespace validation {\n class XValidatableFormComponent;\n} } } } }\n\n\/\/........................................................................\nnamespace svxform\n{\n\/\/........................................................................\n\n typedef sal_Int16 ControlStatus;\n\n #define CONTROL_STATUS_NONE 0x00\n #define CONTROL_STATUS_FOCUSED 0x01\n #define CONTROL_STATUS_MOUSE_HOVER 0x02\n #define CONTROL_STATUS_INVALID 0x04\n\n \/\/====================================================================\n \/\/= BorderDescriptor\n \/\/====================================================================\n struct BorderDescriptor\n {\n sal_Int16 nBorderType;\n sal_Int32 nBorderColor;\n\n BorderDescriptor()\n :nBorderType( ::com::sun::star::awt::VisualEffect::FLAT )\n ,nBorderColor( 0x00000000 )\n {\n }\n inline void clear()\n {\n nBorderType = ::com::sun::star::awt::VisualEffect::FLAT;\n nBorderColor = 0x00000000;\n }\n };\n\n \/\/====================================================================\n \/\/= UnderlineDescriptor\n \/\/====================================================================\n struct UnderlineDescriptor\n {\n sal_Int16 nUnderlineType;\n sal_Int32 nUnderlineColor;\n\n UnderlineDescriptor()\n :nUnderlineType( ::com::sun::star::awt::FontUnderline::NONE )\n ,nUnderlineColor( 0x00000000 )\n {\n }\n\n UnderlineDescriptor( sal_Int16 _nUnderlineType, sal_Int32 _nUnderlineColor )\n :nUnderlineType( _nUnderlineType )\n ,nUnderlineColor( _nUnderlineColor )\n {\n }\n\n inline void clear()\n {\n nUnderlineType = ::com::sun::star::awt::FontUnderline::NONE;\n nUnderlineColor = 0x00000000;\n }\n };\n\n \/\/====================================================================\n \/\/= ControlData\n \/\/====================================================================\n struct ControlData : public BorderDescriptor, UnderlineDescriptor\n {\n ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControl > xControl;\n ::rtl::OUString sOriginalHelpText;\n\n ControlData() : BorderDescriptor() { }\n ControlData( const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControl >& _rxControl )\n :xControl( _rxControl )\n {\n }\n void clear()\n {\n BorderDescriptor::clear();\n UnderlineDescriptor::clear();\n xControl.clear();\n sOriginalHelpText = ::rtl::OUString();\n }\n };\n\n \/\/====================================================================\n \/\/= ControlBorderManager\n \/\/====================================================================\n \/** manages the dynamic border color for form controls\n\n Used by the <type>FmXFormController<\/type>, this class manages the dynamic changes in the\n border color of form controls. For this a set of events have to be forwarded to the manager\n instance, which then will switch the border color depending on the mouse and focus status\n of the controls.\n *\/\n class ControlBorderManager\n {\n private:\n struct ControlDataCompare : public ::std::binary_function< ControlData, ControlData, bool >\n {\n bool operator()( const ControlData& _rLHS, const ControlData& _rRHS ) const\n {\n return _rLHS.xControl.get() < _rRHS.xControl.get();\n }\n };\n\n typedef ::std::set< ControlData, ControlDataCompare > ControlBag;\n typedef ::com::sun::star::awt::XVclWindowPeer WindowPeer;\n typedef ::com::sun::star::uno::Reference< ::com::sun::star::awt::XVclWindowPeer > WindowPeerRef;\n typedef ::std::set< WindowPeerRef, ::comphelper::OInterfaceCompare< WindowPeer > > PeerBag;\n\n PeerBag m_aColorableControls;\n PeerBag m_aNonColorableControls;\n\n ControlData m_aFocusControl;\n ControlData m_aMouseHoverControl;\n ControlBag m_aInvalidControls;\n\n \/\/ ----------------\n \/\/ attributes\n sal_Int32 m_nFocusColor;\n sal_Int32 m_nMouseHoveColor;\n sal_Int32 m_nInvalidColor;\n bool m_bDynamicBorderColors;\n\n public:\n ControlBorderManager();\n ~ControlBorderManager();\n\n public:\n void focusGained( const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& _rxControl ) SAL_THROW(());\n void focusLost( const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& _rxControl ) SAL_THROW(());\n void mouseEntered( const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& _rxControl ) SAL_THROW(());\n void mouseExited( const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& _rxControl ) SAL_THROW(());\n\n void validityChanged(\n const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControl >& _rxControl,\n const ::com::sun::star::uno::Reference< ::com::sun::star::form::validation::XValidatableFormComponent >& _rxValidatable\n ) SAL_THROW(());\n\n \/\/\/ enables dynamic border color for the controls\n void enableDynamicBorderColor( );\n \/\/\/ disables dynamic border color for the controls\n void disableDynamicBorderColor( );\n\n \/** sets a color to be used for a given status\n @param _nStatus\n the status which the color should be applied for. Must not be CONTROL_STATUS_NONE\n @param _nColor\n the color to apply for the given status\n *\/\n void setStatusColor( ControlStatus _nStatus, sal_Int32 _nColor );\n\n \/** restores all colors of all controls where we possibly changed them\n *\/\n void restoreAll();\n\n private:\n \/** called when a control got one of the two possible stati (focused, and hovered with the mouse)\n @param _rxControl\n the control which gained the status\n @param _rControlData\n the control's status data, as a reference to our respective member\n *\/\n void controlStatusGained(\n const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& _rxControl,\n ControlData& _rControlData\n ) SAL_THROW(());\n\n \/** called when a control lost one of the two possible stati (focused, and hovered with the mouse)\n @param _rxControl\n the control which lost the status\n @param _rControlData\n the control's status data, as a reference to our respective member\n *\/\n void controlStatusLost( const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& _rxControl, ControlData& _rControlData ) SAL_THROW(());\n\n \/** determines whether the border of a given peer can be colored\n @param _rxPeer\n the peer to examine. Must not be <NULL\/>\n *\/\n bool canColorBorder( const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XVclWindowPeer >& _rxPeer );\n\n \/** determines the status of the given control\n *\/\n ControlStatus getControlStatus( const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControl >& _rxControl ) SAL_THROW(());\n\n \/** retrieves the color associated with a given ControlStatus\n @param _eStatus\n the status of the control. Must not be <member>ControlStatus::none<\/member>\n *\/\n sal_Int32 getControlColorByStatus( ControlStatus _eStatus );\n\n \/** sets the border color for a given control, depending on its status\n @param _rxControl\n the control to set the border color for. Must not be <NULL\/>\n @param _rxPeer\n the peer of the control, to be passed herein for optimization the caller usually needs it, anyway).\n Must not be <NULL\/>\n @param _rFallback\n the color\/type to use when the control has the status CONTROL_STATUS_NONE\n *\/\n void updateBorderStyle(\n const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControl >& _rxControl,\n const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XVclWindowPeer >& _rxPeer,\n const BorderDescriptor& _rFallback\n ) SAL_THROW(());\n\n \/** determines the to-be-remembered original border color and type for a control\n\n The method also takes into account that the control may currently have an overwritten\n border style\n\n @param _rxControl\n the control to examine. Must not be <NULL\/>, and have a non-<NULL\/> peer\n *\/\n void determineOriginalBorderStyle(\n const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControl >& _rxControl,\n BorderDescriptor& _rData\n ) const;\n };\n\n\/\/........................................................................\n} \/\/ namespace svxform\n\/\/........................................................................\n\n#endif \/\/ SVX_SOURCE_INC_FMCONTROLBORDERMANAGER_HXX\n<|endoftext|>"} {"text":"<commit_before>#ifndef IMQUE_ALLOCATOR_HH\n#define IMQUE_ALLOCATOR_HH\n\n#include <inttypes.h>\n#include <cassert>\n\nnamespace imque {\n \/**\n * 複数プロセス・複数スレッドで共有されているメモリ領域の割り当てに使えるアロケータ\n *\/\n class Allocator {\n \/** \n * 補助構造体・クラス群\n *\/\n \/\/ 空き領域を管理するリンクリストのノード\n struct Node {\n uint32_t next; \/\/ 次のノードのインデックス\n uint32_t count:30; \/\/ このノードが管理する空きチャンク数: sizeof(Chunk)*count = 割り当て可能なバイト数\n uint32_t status:2; \/\/ ノードのステータス\n\n enum STATUS {\n FREE = 0, \/\/ 割り当て可能\n JOIN_HEAD = 1, \/\/ 後ろのノードとの結合待ち\n JOIN_TAIL = 2 \/\/ 前のノードとの結合待ち\n };\n\n uint64_t* uint64_ptr() { return reinterpret_cast<uint64_t*>(this); }\n uint64_t uint64() const { return *reinterpret_cast<const uint64_t*>(this); }\n } __attribute__((__packed__));\n\n \/\/ 実際に割り当てられるチャンク領域\n \/\/ インデックスが1のノードは、インデックスが1のチャンクを管理している\n struct Chunk {\n char padding[32];\n };\n \n \/\/ ノードの特定時点でのスナップショットを保持するクラス\n class Snapshot {\n public:\n Snapshot() : ptr_(NULL) {}\n Snapshot(Node* ptr) { update(ptr); }\n \n void update(Node* ptr) {\n ptr_ = ptr;\n\n uint64_t val = __sync_add_and_fetch(ptr->uint64_ptr(), 0); \/\/ atomicなロード関数がないので、その代替\n val_ = *reinterpret_cast<Node*>(&val);\n }\n\n const Node& node() const { return val_; }\n bool isModified() const { return ptr_->uint64() != val_.uint64(); }\n bool isJoinable(Node* head) const { return val_.next == index(head) + val_.count; }\n \n bool compare_and_swap(const Node& new_val) {\n if(isModified() == false &&\n __sync_bool_compare_and_swap(ptr_->uint64_ptr(), val_.uint64(), new_val.uint64())) {\n val_ = new_val;\n return true;\n }\n return false;\n }\n\n uint32_t index(Node* head) const { return ptr_ - head; }\n \n private:\n Node* ptr_;\n Node val_;\n };\n \n private:\n static const uint32_t MAX_RETRY_COUNT = 512; \n\n public:\n \/\/ コンストラクタ\n \/\/ \n \/\/ region: 割り当て可能なメモリ領域\n \/\/ size: 割り当て可能なメモリ領域のバイト数\n \/\/\n \/\/ [スペースに関する注意事項]\n \/\/ - 渡されたメモリ領域の内の 1\/5 は空き領域の管理用に使用される。\n \/\/ - また、一つの割り当てごとに平均して 16byte のオーバーヘッドがある。\n Allocator(void* region, uint32_t size) \n : node_count_(size\/(sizeof(Node)+sizeof(Chunk))),\n nodes_(reinterpret_cast<Node*>(region)),\n chunks_(reinterpret_cast<Chunk*>(nodes_+node_count_)) {\n }\n\n operator bool() const { return node_count_ > 2; }\n \n void init() {\n nodes_[0].next = 1;\n nodes_[0].count = 0;\n nodes_[0].status = Node::FREE;\n\n nodes_[1].next = node_count_;\n nodes_[1].count = node_count_-1;\n nodes_[1].status = Node::FREE;\n }\n\n \/\/ メモリ割り当てを行う。\n \/\/ 失敗した場合は 0 を、成功した場合は割り当てたメモリ領域参照用のID値を返す。\n \/\/ ※ ID値を ptr() メソッドに渡すことで、実際に利用可能なメモリ領域を取得できる\n uint32_t allocate(uint32_t size) {\n if(size == 0) {\n return 0; \/\/ invalid argument\n }\n\n uint32_t required_chunk_count = (size+sizeof(Chunk)-1) \/ sizeof(Chunk);\n \n Snapshot cand;\n if(find_candidate(IsEnoughChunk(required_chunk_count), cand) == false) {\n return 0; \/\/ out of memory\n }\n\n Node new_node = {cand.node().next,\n cand.node().count - required_chunk_count,\n Node::FREE};\n \n if(cand.compare_and_swap(new_node) == false) {\n return allocate(size);\n }\n \n uint32_t alloced_node_index = cand.index(nodes_) + new_node.count;\n nodes_[alloced_node_index].count = required_chunk_count;\n\n return alloced_node_index;\n }\n\n bool release(uint32_t index) {\n if(index == 0 || index >= node_count_) {\n assert(index < node_count_);\n return true;\n }\n\n uint32_t node_index = index;\n Snapshot pred;\n if(find_candidate(IsPredecessor(node_index), pred) == false) {\n return false;\n }\n\n assert(node_index >= pred.index(nodes_)+pred.node().count);\n assert(pred.node().status == Node::FREE);\n\n Node* node = &nodes_[node_index];\n Node new_pred_node = {0, 0, Node::FREE};\n if(node_index == pred.index(nodes_) + pred.node().count) { \n new_pred_node.next = pred.node().next;\n new_pred_node.count = pred.node().count + node->count;\n } else {\n node->next = pred.node().next;\n node->status = Node::FREE;\n \n new_pred_node.next = node_index;\n new_pred_node.count = pred.node().count;\n }\n \n if(pred.compare_and_swap(new_pred_node) == false) {\n return release(index);\n }\n \n return true;\n }\n\n template<typename T>\n T* ptr(uint32_t index) const { return reinterpret_cast<T*>(chunks_ + index); }\n\n template<typename T>\n T* ptr(uint32_t index, uint32_t offset) const { return reinterpret_cast<T*>(ptr<char>(index)+offset); }\n\n \/\/ sizeバイトを利用(割当)可能にするためには、何バイト分の領域をコンストラクタに渡せば良いかを返す\n \/\/ ※ あくまでも目安である程度の誤差はある\n static size_t calc_need_byte_size(size_t size) {\n return (sizeof(Node)+sizeof(Chunk))*size \/ sizeof(Chunk);\n }\n\n \/\/ テスト用メソッド: 他と競合が発生するような状況で実行したら、結果が不正になることがあるので注意\n uint32_t allocatedNodeCount() const {\n uint32_t allocated_count = 0;\n \n Snapshot pred(&nodes_[0]);\n Snapshot curr;\n while(get_next_snapshot(pred, curr)) {\n allocated_count += (curr.node().next - curr.index(nodes_)) - curr.node().count;\n pred = curr;\n }\n allocated_count += (node_count_ - curr.node().next);\n\n return allocated_count;\n }\n \n private:\n \/\/ 現在のノードが、十分な(要求以上の)空き領域を管理しているかどうかを判定するためのコールバック\n class IsEnoughChunk {\n public:\n IsEnoughChunk(uint32_t required_chunk_count) : count_(required_chunk_count) {}\n \n bool operator()(const Snapshot& curr) const {\n \/\/ NOTE: '>='ではなく'>'で比較していることに注意\n \/\/ ※ ノードの先頭部分も割り当ててしまうとリンクリストが壊れるので、そこは除外している\n return curr.node().status == Node::FREE && curr.node().count > count_;\n }\n\n private:\n const uint32_t count_;\n };\n\n \/\/ 現在のノードが、指定されたインデックス(のノード)の直前となるものかを判定するためのコールバック\n class IsPredecessor {\n public:\n IsPredecessor(uint32_t node_index) : node_index_(node_index) {}\n\n bool operator()(const Snapshot& curr) const {\n return node_index_ < curr.node().next;\n }\n\n private:\n uint32_t node_index_;\n };\n\n template<class Callback>\n bool find_candidate(const Callback& fn, Snapshot& node, uint32_t retry=0) {\n Snapshot head(&nodes_[0]);\n return find_candidate(fn, head, node, retry);\n }\n\n template<class Callback>\n bool find_candidate(const Callback& fn, Snapshot& pred, Snapshot& curr, uint32_t retry) {\n if(retry > MAX_RETRY_COUNT) {\n assert(retry <= MAX_RETRY_COUNT);\n return false;\n }\n \n if(pred.node().next == node_count_) { \/\/ 終端ノードに達した\n return false;\n }\n \n if(get_next_snapshot(pred, curr) == false || \n update_node_status(pred, curr) == false ||\n join_nodes_if_need(pred, curr) == false) { \n usleep(retry+1);\n return find_candidate(fn, curr, retry+1);\n }\n\n if(fn(curr)) {\n return true;\n }\n \n pred = curr;\n return find_candidate(fn, pred, curr, retry);\n }\n\n \/\/ predの次のノード(のスナップショット)を取得して curr に設定する\n bool get_next_snapshot(Snapshot& pred, Snapshot& curr) const {\n if(pred.node().next == node_count_) {\n return false;\n }\n\n curr.update(&nodes_[pred.node().next]);\n\n if(pred.isModified()) {\n return false;\n }\n\n assert(! (curr.node().status & Node::JOIN_HEAD && curr.isJoinable(nodes_)==false));\n \n if((! pred.node().status & Node::JOIN_HEAD) && curr.node().status & Node::JOIN_TAIL) {\n \/\/ 前半のノードが結合可能状態になっていないのに、後半のノードだけ結合可能にマークされている\n \/\/ => pred がその一つ前のノードと結合されてしまった場合は、ここに来る可能性あり\n \/\/ 1) predを取得 => predにはNode::JOIN_TAILマークのみが付いている\n \/\/ 2) predとその前のノード(predpred)が結合 => この時点でpredの内容は実質無効になる (ただし値は変わらない)\n \/\/ 3) predpredとcurrは結合可能 => currにNode::JOIN_TAILマークが付く\n \/\/ 4) predからcurrを取得 => predは無効になっているけど、値は以前から変わっていないのでそれを検出できない\n \/\/ => この時点で、上のif文を満たす条件が成立する\n return false;\n }\n \n return true;\n }\n\n bool update_node_status(Snapshot& pred, Snapshot& curr) {\n if(pred.isJoinable(nodes_) == false) {\n return true;\n }\n\n Node new_pred_node = {pred.node().next,\n pred.node().count,\n pred.node().status | Node::JOIN_HEAD};\n if(pred.compare_and_swap(new_pred_node) == false) {\n return false;\n }\n \n Node new_curr_node = {curr.node().next,\n curr.node().count,\n curr.node().status | Node::JOIN_TAIL};\n if(curr.compare_and_swap(new_curr_node) == false) {\n return false;\n }\n \n return true;\n }\n \n bool join_nodes_if_need(Snapshot& pred, Snapshot& curr) {\n if(! (pred.node().status & Node::JOIN_HEAD &&\n curr.node().status & Node::JOIN_TAIL)) {\n assert(!(curr.node().status & Node::JOIN_TAIL));\n return true;\n }\n assert(pred.node().next == curr.index(nodes_));\n assert(pred.isJoinable(nodes_));\n uint32_t curr_status = curr.node().status;\n Node new_pred_node = {curr.node().next,\n pred.node().count + curr.node().count,\n (pred.node().status & ~Node::JOIN_HEAD) |\n (curr.node().status & ~Node::JOIN_TAIL)};\n if(pred.compare_and_swap(new_pred_node) == false) {\n return false;\n }\n if(! (curr_status & Node::JOIN_HEAD)) {\n assert(! (pred.node().status & Node::JOIN_HEAD));\n }\n curr = pred;\n return true;\n }\n\n private:\n const uint32_t node_count_;\n Node* nodes_;\n Chunk* chunks_;\n };\n}\n\n#endif\n<commit_msg>TODOコメント追加<commit_after>#ifndef IMQUE_ALLOCATOR_HH\n#define IMQUE_ALLOCATOR_HH\n\n#include <inttypes.h>\n#include <cassert>\n\nnamespace imque {\n \/**\n * 複数プロセス・複数スレッドで共有されているメモリ領域の割り当てに使えるアロケータ\n *\/\n \/\/ TODO: Chunkのサイズはtemplateで指定可能にしても良いかもしれない\n class Allocator {\n \/** \n * 補助構造体・クラス群\n *\/\n \/\/ 空き領域を管理するリンクリストのノード\n struct Node {\n uint32_t next; \/\/ 次のノードのインデックス\n uint32_t count:30; \/\/ このノードが管理する空きチャンク数: sizeof(Chunk)*count = 割り当て可能なバイト数\n uint32_t status:2; \/\/ ノードのステータス\n\n enum STATUS {\n FREE = 0, \/\/ 割り当て可能\n JOIN_HEAD = 1, \/\/ 後ろのノードとの結合待ち\n JOIN_TAIL = 2 \/\/ 前のノードとの結合待ち\n };\n\n uint64_t* uint64_ptr() { return reinterpret_cast<uint64_t*>(this); }\n uint64_t uint64() const { return *reinterpret_cast<const uint64_t*>(this); }\n } __attribute__((__packed__));\n\n \/\/ 実際に割り当てられるチャンク領域\n \/\/ インデックスが1のノードは、インデックスが1のチャンクを管理している\n struct Chunk {\n char padding[32];\n };\n \n \/\/ ノードの特定時点でのスナップショットを保持するクラス\n class Snapshot {\n public:\n Snapshot() : ptr_(NULL) {}\n Snapshot(Node* ptr) { update(ptr); }\n \n void update(Node* ptr) {\n ptr_ = ptr;\n\n uint64_t val = __sync_add_and_fetch(ptr->uint64_ptr(), 0); \/\/ atomicなロード関数がないので、その代替\n val_ = *reinterpret_cast<Node*>(&val);\n }\n\n const Node& node() const { return val_; }\n bool isModified() const { return ptr_->uint64() != val_.uint64(); }\n bool isJoinable(Node* head) const { return val_.next == index(head) + val_.count; }\n \n bool compare_and_swap(const Node& new_val) {\n if(isModified() == false &&\n __sync_bool_compare_and_swap(ptr_->uint64_ptr(), val_.uint64(), new_val.uint64())) {\n val_ = new_val;\n return true;\n }\n return false;\n }\n\n uint32_t index(Node* head) const { return ptr_ - head; }\n \n private:\n Node* ptr_;\n Node val_;\n };\n \n private:\n static const uint32_t MAX_RETRY_COUNT = 512; \n\n public:\n \/\/ コンストラクタ\n \/\/ \n \/\/ region: 割り当て可能なメモリ領域\n \/\/ size: 割り当て可能なメモリ領域のバイト数\n \/\/\n \/\/ [スペースに関する注意事項]\n \/\/ - 渡されたメモリ領域の内の 1\/5 は空き領域の管理用に使用される。\n \/\/ - また、一つの割り当てごとに平均して 16byte のオーバーヘッドがある。\n Allocator(void* region, uint32_t size) \n : node_count_(size\/(sizeof(Node)+sizeof(Chunk))),\n nodes_(reinterpret_cast<Node*>(region)),\n chunks_(reinterpret_cast<Chunk*>(nodes_+node_count_)) {\n }\n\n operator bool() const { return node_count_ > 2; }\n \n void init() {\n nodes_[0].next = 1;\n nodes_[0].count = 0;\n nodes_[0].status = Node::FREE;\n\n nodes_[1].next = node_count_;\n nodes_[1].count = node_count_-1;\n nodes_[1].status = Node::FREE;\n }\n\n \/\/ メモリ割り当てを行う。\n \/\/ 失敗した場合は 0 を、成功した場合は割り当てたメモリ領域参照用のID値を返す。\n \/\/ ※ ID値を ptr() メソッドに渡すことで、実際に利用可能なメモリ領域を取得できる\n uint32_t allocate(uint32_t size) {\n if(size == 0) {\n return 0; \/\/ invalid argument\n }\n\n uint32_t required_chunk_count = (size+sizeof(Chunk)-1) \/ sizeof(Chunk);\n \n Snapshot cand;\n if(find_candidate(IsEnoughChunk(required_chunk_count), cand) == false) {\n return 0; \/\/ out of memory\n }\n\n Node new_node = {cand.node().next,\n cand.node().count - required_chunk_count,\n Node::FREE};\n \n if(cand.compare_and_swap(new_node) == false) {\n return allocate(size);\n }\n \n uint32_t alloced_node_index = cand.index(nodes_) + new_node.count;\n nodes_[alloced_node_index].count = required_chunk_count;\n\n return alloced_node_index;\n }\n\n bool release(uint32_t index) {\n if(index == 0 || index >= node_count_) {\n assert(index < node_count_);\n return true;\n }\n\n uint32_t node_index = index;\n Snapshot pred;\n if(find_candidate(IsPredecessor(node_index), pred) == false) {\n return false;\n }\n\n assert(node_index >= pred.index(nodes_)+pred.node().count);\n assert(pred.node().status == Node::FREE);\n\n Node* node = &nodes_[node_index];\n Node new_pred_node = {0, 0, Node::FREE};\n if(node_index == pred.index(nodes_) + pred.node().count) { \n new_pred_node.next = pred.node().next;\n new_pred_node.count = pred.node().count + node->count;\n } else {\n node->next = pred.node().next;\n node->status = Node::FREE;\n \n new_pred_node.next = node_index;\n new_pred_node.count = pred.node().count;\n }\n \n if(pred.compare_and_swap(new_pred_node) == false) {\n return release(index);\n }\n \n return true;\n }\n\n template<typename T>\n T* ptr(uint32_t index) const { return reinterpret_cast<T*>(chunks_ + index); }\n\n template<typename T>\n T* ptr(uint32_t index, uint32_t offset) const { return reinterpret_cast<T*>(ptr<char>(index)+offset); }\n\n \/\/ sizeバイトを利用(割当)可能にするためには、何バイト分の領域をコンストラクタに渡せば良いかを返す\n \/\/ ※ あくまでも目安である程度の誤差はある\n static size_t calc_need_byte_size(size_t size) {\n return (sizeof(Node)+sizeof(Chunk))*size \/ sizeof(Chunk);\n }\n\n \/\/ テスト用メソッド: 他と競合が発生するような状況で実行したら、結果が不正になることがあるので注意\n uint32_t allocatedNodeCount() const {\n uint32_t allocated_count = 0;\n \n Snapshot pred(&nodes_[0]);\n Snapshot curr;\n while(get_next_snapshot(pred, curr)) {\n allocated_count += (curr.node().next - curr.index(nodes_)) - curr.node().count;\n pred = curr;\n }\n allocated_count += (node_count_ - curr.node().next);\n\n return allocated_count;\n }\n \n private:\n \/\/ 現在のノードが、十分な(要求以上の)空き領域を管理しているかどうかを判定するためのコールバック\n class IsEnoughChunk {\n public:\n IsEnoughChunk(uint32_t required_chunk_count) : count_(required_chunk_count) {}\n \n bool operator()(const Snapshot& curr) const {\n \/\/ NOTE: '>='ではなく'>'で比較していることに注意\n \/\/ ※ ノードの先頭部分も割り当ててしまうとリンクリストが壊れるので、そこは除外している\n return curr.node().status == Node::FREE && curr.node().count > count_;\n }\n\n private:\n const uint32_t count_;\n };\n\n \/\/ 現在のノードが、指定されたインデックス(のノード)の直前となるものかを判定するためのコールバック\n class IsPredecessor {\n public:\n IsPredecessor(uint32_t node_index) : node_index_(node_index) {}\n\n bool operator()(const Snapshot& curr) const {\n return node_index_ < curr.node().next;\n }\n\n private:\n uint32_t node_index_;\n };\n\n template<class Callback>\n bool find_candidate(const Callback& fn, Snapshot& node, uint32_t retry=0) {\n Snapshot head(&nodes_[0]);\n return find_candidate(fn, head, node, retry);\n }\n\n template<class Callback>\n bool find_candidate(const Callback& fn, Snapshot& pred, Snapshot& curr, uint32_t retry) {\n if(retry > MAX_RETRY_COUNT) {\n assert(retry <= MAX_RETRY_COUNT);\n return false;\n }\n \n if(pred.node().next == node_count_) { \/\/ 終端ノードに達した\n return false;\n }\n \n if(get_next_snapshot(pred, curr) == false || \n update_node_status(pred, curr) == false ||\n join_nodes_if_need(pred, curr) == false) { \n usleep(retry+1);\n return find_candidate(fn, curr, retry+1);\n }\n\n if(fn(curr)) {\n return true;\n }\n \n pred = curr;\n return find_candidate(fn, pred, curr, retry);\n }\n\n \/\/ predの次のノード(のスナップショット)を取得して curr に設定する\n bool get_next_snapshot(Snapshot& pred, Snapshot& curr) const {\n if(pred.node().next == node_count_) {\n return false;\n }\n\n curr.update(&nodes_[pred.node().next]);\n\n if(pred.isModified()) {\n return false;\n }\n\n assert(! (curr.node().status & Node::JOIN_HEAD && curr.isJoinable(nodes_)==false));\n \n if((! pred.node().status & Node::JOIN_HEAD) && curr.node().status & Node::JOIN_TAIL) {\n \/\/ 前半のノードが結合可能状態になっていないのに、後半のノードだけ結合可能にマークされている\n \/\/ => pred がその一つ前のノードと結合されてしまった場合は、ここに来る可能性あり\n \/\/ 1) predを取得 => predにはNode::JOIN_TAILマークのみが付いている\n \/\/ 2) predとその前のノード(predpred)が結合 => この時点でpredの内容は実質無効になる (ただし値は変わらない)\n \/\/ 3) predpredとcurrは結合可能 => currにNode::JOIN_TAILマークが付く\n \/\/ 4) predからcurrを取得 => predは無効になっているけど、値は以前から変わっていないのでそれを検出できない\n \/\/ => この時点で、上のif文を満たす条件が成立する\n return false;\n }\n \n return true;\n }\n\n bool update_node_status(Snapshot& pred, Snapshot& curr) {\n if(pred.isJoinable(nodes_) == false) {\n return true;\n }\n\n Node new_pred_node = {pred.node().next,\n pred.node().count,\n pred.node().status | Node::JOIN_HEAD};\n if(pred.compare_and_swap(new_pred_node) == false) {\n return false;\n }\n \n Node new_curr_node = {curr.node().next,\n curr.node().count,\n curr.node().status | Node::JOIN_TAIL};\n if(curr.compare_and_swap(new_curr_node) == false) {\n return false;\n }\n \n return true;\n }\n \n bool join_nodes_if_need(Snapshot& pred, Snapshot& curr) {\n if(! (pred.node().status & Node::JOIN_HEAD &&\n curr.node().status & Node::JOIN_TAIL)) {\n assert(!(curr.node().status & Node::JOIN_TAIL));\n return true;\n }\n assert(pred.node().next == curr.index(nodes_));\n assert(pred.isJoinable(nodes_));\n \n uint32_t curr_status = curr.node().status;\n Node new_pred_node = {curr.node().next,\n pred.node().count + curr.node().count,\n (pred.node().status & ~Node::JOIN_HEAD) |\n (curr.node().status & ~Node::JOIN_TAIL)};\n if(pred.compare_and_swap(new_pred_node) == false) {\n return false;\n }\n if(! (curr_status & Node::JOIN_HEAD)) {\n assert(! (pred.node().status & Node::JOIN_HEAD));\n }\n curr = pred;\n return true;\n }\n\n private:\n const uint32_t node_count_;\n Node* nodes_;\n Chunk* chunks_;\n };\n}\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: pe_tydef.hxx,v $\n *\n * $Revision: 1.1.1.1 $\n *\n * last change: $Author: np $ $Date: 2002-03-08 14:45:31 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef ADC_CPP_PE_TYDEF_HXX\n#define ADC_CPP_PE_TYDEF_HXX\n\n\n\n\/\/ USED SERVICES\n \/\/ BASE CLASSES\n#include \"cpp_pe.hxx\"\n \/\/ COMPONENTS\n#include <semantic\/callf.hxx>\n#include <semantic\/sub_peu.hxx>\n \/\/ PARAMETERS\n\n\nnamespace cpp {\n\nclass PE_Type;\n\n\nclass PE_Typedef : public cpp::Cpp_PE\n{\n public:\n enum E_State\n {\n start,\n expectName,\n afterName,\n size_of_states\n };\n PE_Typedef(\n Cpp_PE * i_pParent );\n ~PE_Typedef();\n\n virtual void Call_Handler(\n const cpp::Token & i_rTok );\n private:\n typedef SubPe< PE_Typedef, PE_Type > SP_Type;\n typedef SubPeUse< PE_Typedef, PE_Type> SPU_Type;\n\n void Setup_StatusFunctions();\n virtual void InitData();\n virtual void TransferData();\n void Hdl_SyntaxError( const char *);\n\n void SpReturn_Type();\n\n void On_start_typedef( const char * );\n void On_expectName_Identifier( const char * );\n void On_afterName_Semicolon( const char * );\n\n \/\/ DATA\n Dyn< PeStatusArray<PE_Typedef> >\n pStati;\n Dyn<SP_Type> pSpType;\n Dyn<SPU_Type> pSpuType;\n\n udmstri sName;\n ary::Tid nType;\n};\n\n\n\n\/\/ IMPLEMENTATION\n\n\n} \/\/ namespace cpp\n\n\n#endif\n\n<commit_msg>INTEGRATION: CWS ooo19126 (1.1.1.1.146); FILE MERGED 2005\/09\/05 13:11:50 rt 1.1.1.1.146.1: #i54170# Change license header: remove SISSL<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: pe_tydef.hxx,v $\n *\n * $Revision: 1.2 $\n *\n * last change: $Author: rt $ $Date: 2005-09-07 18:29:40 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef ADC_CPP_PE_TYDEF_HXX\n#define ADC_CPP_PE_TYDEF_HXX\n\n\n\n\/\/ USED SERVICES\n \/\/ BASE CLASSES\n#include \"cpp_pe.hxx\"\n \/\/ COMPONENTS\n#include <semantic\/callf.hxx>\n#include <semantic\/sub_peu.hxx>\n \/\/ PARAMETERS\n\n\nnamespace cpp {\n\nclass PE_Type;\n\n\nclass PE_Typedef : public cpp::Cpp_PE\n{\n public:\n enum E_State\n {\n start,\n expectName,\n afterName,\n size_of_states\n };\n PE_Typedef(\n Cpp_PE * i_pParent );\n ~PE_Typedef();\n\n virtual void Call_Handler(\n const cpp::Token & i_rTok );\n private:\n typedef SubPe< PE_Typedef, PE_Type > SP_Type;\n typedef SubPeUse< PE_Typedef, PE_Type> SPU_Type;\n\n void Setup_StatusFunctions();\n virtual void InitData();\n virtual void TransferData();\n void Hdl_SyntaxError( const char *);\n\n void SpReturn_Type();\n\n void On_start_typedef( const char * );\n void On_expectName_Identifier( const char * );\n void On_afterName_Semicolon( const char * );\n\n \/\/ DATA\n Dyn< PeStatusArray<PE_Typedef> >\n pStati;\n Dyn<SP_Type> pSpType;\n Dyn<SPU_Type> pSpuType;\n\n udmstri sName;\n ary::Tid nType;\n};\n\n\n\n\/\/ IMPLEMENTATION\n\n\n} \/\/ namespace cpp\n\n\n#endif\n\n<|endoftext|>"} {"text":"<commit_before>\/*=========================================================================\n\nProgram: Medical Imaging & Interaction Toolkit\nModule: $RCSfile$\nLanguage: C++\nDate: $Date$\nVersion: $Revision$\n\nCopyright (c) German Cancer Research Center, Division of Medical and\nBiological Informatics. All rights reserved.\nSee MITKCopyright.txt or http:\/\/www.mitk.org\/copyright.html for details.\n\nThis software is distributed WITHOUT ANY WARRANTY; without even\nthe implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\nPURPOSE. See the above copyright notices for more information.\n\n=========================================================================*\/\n\n\n#include <mitkGL.h>\n#include \"mitkGeometry2DDataMapper2D.h\"\n\n#include \"mitkBaseRenderer.h\"\n\n#include \"mitkPlaneGeometry.h\"\n\n#include \"mitkColorProperty.h\"\n#include \"mitkProperties.h\"\n#include \"mitkSmartPointerProperty.h\"\n\n#include \"mitkGeometry2DDataToSurfaceFilter.h\"\n#include \"mitkSurfaceMapper2D.h\"\n\n\/\/##ModelId=3E639E100243\nmitk::Geometry2DDataMapper2D::Geometry2DDataMapper2D() : m_SurfaceMapper(NULL)\n{\n}\n\n\/\/##ModelId=3E639E100257\nmitk::Geometry2DDataMapper2D::~Geometry2DDataMapper2D()\n{\n}\n\n\/\/##ModelId=3E6423D20341\nconst mitk::Geometry2DData *mitk::Geometry2DDataMapper2D::GetInput(void)\n{\n return static_cast<const mitk::Geometry2DData * > ( GetData() );\n}\n\nvoid mitk::Geometry2DDataMapper2D::SetDataIteratorToOtherGeometry2Ds(const mitk::DataTreeIteratorBase* iterator)\n{\n if(m_IteratorToOtherGeometry2Ds != iterator)\n {\n m_IteratorToOtherGeometry2Ds = iterator;\n Modified();\n }\n}\n\nvoid mitk::Geometry2DDataMapper2D::GenerateData()\n{\n \/\/collect all Geometry2DData's accessible by traversing m_IteratorToOtherGeometry2Ds\n m_OtherGeometry2Ds.clear();\n if(m_IteratorToOtherGeometry2Ds.IsNull()) return;\n\n mitk::DataTreeIteratorClone it = m_IteratorToOtherGeometry2Ds;\n while(!it->IsAtEnd())\n {\n if(it->Get().IsNotNull())\n {\n mitk::BaseData* data = it->Get()->GetData();\n if(data != NULL)\n {\n mitk::Geometry2DData* geometry2dData = dynamic_cast<mitk::Geometry2DData*>(data);\n if(geometry2dData!=NULL)\n {\n mitk::PlaneGeometry* planegeometry = dynamic_cast<mitk::PlaneGeometry*>(geometry2dData->GetGeometry2D());\n if(planegeometry!=NULL)\n m_OtherGeometry2Ds.push_back(it->Get());\n }\n }\n }\n ++it;\n }\n}\n\n\/\/##ModelId=3E67D77A0109\nvoid mitk::Geometry2DDataMapper2D::Paint(mitk::BaseRenderer * renderer)\n{\n if(IsVisible(renderer)==false) return;\n \n \/\/\t@FIXME: Logik fuer update\n bool updateNeccesary=true;\n \n if (updateNeccesary) {\n \/\/ ok, das ist aus GenerateData kopiert\n \n mitk::Geometry2DData::Pointer input = const_cast<mitk::Geometry2DData*>(this->GetInput());\n \n \/\/intersecting with ourself?\n if(input->GetGeometry2D()==renderer->GetCurrentWorldGeometry2D())\n return; \/\/do nothing!\n \n PlaneGeometry::ConstPointer input_planeGeometry = dynamic_cast<const PlaneGeometry *>(input->GetGeometry2D());\n PlaneGeometry::ConstPointer worldPlaneGeometry = dynamic_cast<const PlaneGeometry*>(renderer->GetCurrentWorldGeometry2D()); \n \n if(worldPlaneGeometry.IsNotNull() && (input_planeGeometry.IsNotNull()))\n {\n mitk::DisplayGeometry::Pointer displayGeometry = renderer->GetDisplayGeometry();\n assert(displayGeometry);\n\n \/\/calculate intersection of the plane data with the border of the world geometry rectangle\n Point2D lineFrom, lineTo;\n bool intersecting = worldPlaneGeometry->IntersectWithPlane2D( input_planeGeometry, lineFrom, lineTo ) > 0;\n\n if(intersecting)\n {\n mitk::Line<ScalarType, 2> line, tmpLine;\n line.SetPoints(lineFrom, lineTo);\n\n displayGeometry->WorldToDisplay(lineFrom, lineFrom);\n displayGeometry->WorldToDisplay(lineTo, lineTo);\n Vector2D l;\n l=lineTo-lineFrom;\n ScalarType lengthInDisplayUnits = l.GetNorm();\n\n std::vector<ScalarType> lineParams;\n lineParams.reserve(m_OtherGeometry2Ds.size()+2);\n lineParams.push_back(0);\n lineParams.push_back(1);\n\n Vector2D d, dOrth;\n NodesVectorType::iterator otherPlanesIt = m_OtherGeometry2Ds.begin();\n NodesVectorType::iterator otherPlanesEnd = m_OtherGeometry2Ds.end();\n while(otherPlanesIt != otherPlanesEnd)\n {\n mitk::PlaneGeometry* otherPlane = static_cast<PlaneGeometry*>(static_cast<Geometry2DData*>((*otherPlanesIt)->GetData())->GetGeometry2D());\n if(otherPlane != input_planeGeometry)\n {\n bool otherIntersecting = worldPlaneGeometry->IntersectWithPlane2D( otherPlane, lineFrom, lineTo ) > 0;\n if(otherIntersecting)\n {\n tmpLine.SetPoints(lineFrom, lineTo);\n d = tmpLine.GetDirection();\n dOrth[0] = -d[1]; dOrth[1] = d[0];\n ScalarType t = (tmpLine.GetPoint1()-line.GetPoint1())*(dOrth);\n ScalarType norm = line.GetDirection()*dOrth;\n if(fabs(norm) > mitk::eps)\n {\n t \/= norm;\n lineParams.push_back(t);\n }\n }\n }\n\n ++otherPlanesIt;\n }\n\n \/\/apply color and opacity read from the PropertyList\n ApplyProperties(renderer);\n\n ScalarType gapSizeInPixel = 10;\n ScalarType gapSizeInParamUnits = 1.0\/lengthInDisplayUnits*gapSizeInPixel;\n\n std::sort(lineParams.begin(), lineParams.end());\n\n Point2D p1, p2;\n ScalarType p1Param, p2Param; \n \n p1Param = lineParams[0];\n p1 = line.GetPoint(p1Param);\n displayGeometry->WorldToDisplay(p1, p1);\n\n unsigned int i, preLastLineParam = lineParams.size()-1;\n for(i=1; i < preLastLineParam; ++i)\n {\n p2Param = lineParams[i]-gapSizeInParamUnits*0.5;\n p2 = line.GetPoint(p2Param);\n if(p2Param > p1Param)\n {\n \/\/convert intersection points (until now mm) to display coordinates (units )\n displayGeometry->WorldToDisplay(p2, p2);\n\n \/\/draw\n glBegin (GL_LINES);\n glVertex2f(p1[0],p1[1]);\n glVertex2f(p2[0],p2[1]);\n glEnd ();\n }\n p1Param = p2Param+gapSizeInParamUnits;\n p1 = line.GetPoint(p1Param);\n displayGeometry->WorldToDisplay(p1, p1);\n }\n \/\/draw last line segment\n p2Param = lineParams[i];\n p2 = line.GetPoint(p2Param);\n displayGeometry->WorldToDisplay(p2, p2);\n glBegin (GL_LINES);\n glVertex2f(p1[0],p1[1]);\n glVertex2f(p2[0],p2[1]);\n glEnd ();\n }\n }\n else\n {\n mitk::Geometry2DDataToSurfaceFilter::Pointer surfaceCreator;\n mitk::SmartPointerProperty::Pointer surfacecreatorprop;\n surfacecreatorprop=dynamic_cast<mitk::SmartPointerProperty*>(GetDataTreeNode()->GetProperty(\"surfacegeometry\", renderer).GetPointer());\n if( (surfacecreatorprop.IsNull()) || \n (surfacecreatorprop->GetSmartPointer().IsNull()) ||\n ((surfaceCreator=dynamic_cast<mitk::Geometry2DDataToSurfaceFilter*>(surfacecreatorprop->GetSmartPointer().GetPointer())).IsNull())\n )\n {\n surfaceCreator = mitk::Geometry2DDataToSurfaceFilter::New();\n surfacecreatorprop=new mitk::SmartPointerProperty(surfaceCreator);\n surfaceCreator->PlaceByGeometryOn();\n GetDataTreeNode()->SetProperty(\"surfacegeometry\", surfacecreatorprop);\n }\n \n surfaceCreator->SetInput(input);\n \n int res;\n bool usegeometryparametricbounds=true;\n if(GetDataTreeNode()->GetIntProperty(\"xresolution\", res, renderer))\n {\n surfaceCreator->SetXResolution(res);\n usegeometryparametricbounds=false; \n }\n if(GetDataTreeNode()->GetIntProperty(\"yresolution\", res, renderer))\n {\n surfaceCreator->SetYResolution(res);\n usegeometryparametricbounds=false; \n }\n surfaceCreator->SetUseGeometryParametricBounds(usegeometryparametricbounds);\n\n surfaceCreator->Update(); \/\/@FIXME ohne das crash\n \n if(m_SurfaceMapper.IsNull())\n m_SurfaceMapper=mitk::SurfaceMapper2D::New();\n m_SurfaceMapper->SetSurface(surfaceCreator->GetOutput());\n m_SurfaceMapper->SetDataTreeNode(GetDataTreeNode());\n \n m_SurfaceMapper->Paint(renderer);\n }\n }\n}\n<commit_msg>COMP: Added missing #include<commit_after>\/*=========================================================================\n\nProgram: Medical Imaging & Interaction Toolkit\nModule: $RCSfile$\nLanguage: C++\nDate: $Date$\nVersion: $Revision$\n\nCopyright (c) German Cancer Research Center, Division of Medical and\nBiological Informatics. All rights reserved.\nSee MITKCopyright.txt or http:\/\/www.mitk.org\/copyright.html for details.\n\nThis software is distributed WITHOUT ANY WARRANTY; without even\nthe implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\nPURPOSE. See the above copyright notices for more information.\n\n=========================================================================*\/\n\n\n#include <mitkGL.h>\n#include \"mitkGeometry2DDataMapper2D.h\"\n#include \"mitkLine.h\"\n#include \"mitkBaseRenderer.h\"\n\n#include \"mitkPlaneGeometry.h\"\n\n#include \"mitkColorProperty.h\"\n#include \"mitkProperties.h\"\n#include \"mitkSmartPointerProperty.h\"\n\n#include \"mitkGeometry2DDataToSurfaceFilter.h\"\n#include \"mitkSurfaceMapper2D.h\"\n\n\/\/##ModelId=3E639E100243\nmitk::Geometry2DDataMapper2D::Geometry2DDataMapper2D() : m_SurfaceMapper(NULL)\n{\n}\n\n\/\/##ModelId=3E639E100257\nmitk::Geometry2DDataMapper2D::~Geometry2DDataMapper2D()\n{\n}\n\n\/\/##ModelId=3E6423D20341\nconst mitk::Geometry2DData *mitk::Geometry2DDataMapper2D::GetInput(void)\n{\n return static_cast<const mitk::Geometry2DData * > ( GetData() );\n}\n\nvoid mitk::Geometry2DDataMapper2D::SetDataIteratorToOtherGeometry2Ds(const mitk::DataTreeIteratorBase* iterator)\n{\n if(m_IteratorToOtherGeometry2Ds != iterator)\n {\n m_IteratorToOtherGeometry2Ds = iterator;\n Modified();\n }\n}\n\nvoid mitk::Geometry2DDataMapper2D::GenerateData()\n{\n \/\/collect all Geometry2DData's accessible by traversing m_IteratorToOtherGeometry2Ds\n m_OtherGeometry2Ds.clear();\n if(m_IteratorToOtherGeometry2Ds.IsNull()) return;\n\n mitk::DataTreeIteratorClone it = m_IteratorToOtherGeometry2Ds;\n while(!it->IsAtEnd())\n {\n if(it->Get().IsNotNull())\n {\n mitk::BaseData* data = it->Get()->GetData();\n if(data != NULL)\n {\n mitk::Geometry2DData* geometry2dData = dynamic_cast<mitk::Geometry2DData*>(data);\n if(geometry2dData!=NULL)\n {\n mitk::PlaneGeometry* planegeometry = dynamic_cast<mitk::PlaneGeometry*>(geometry2dData->GetGeometry2D());\n if(planegeometry!=NULL)\n m_OtherGeometry2Ds.push_back(it->Get());\n }\n }\n }\n ++it;\n }\n}\n\n\/\/##ModelId=3E67D77A0109\nvoid mitk::Geometry2DDataMapper2D::Paint(mitk::BaseRenderer * renderer)\n{\n if(IsVisible(renderer)==false) return;\n \n \/\/\t@FIXME: Logik fuer update\n bool updateNeccesary=true;\n \n if (updateNeccesary) {\n \/\/ ok, das ist aus GenerateData kopiert\n \n mitk::Geometry2DData::Pointer input = const_cast<mitk::Geometry2DData*>(this->GetInput());\n \n \/\/intersecting with ourself?\n if(input->GetGeometry2D()==renderer->GetCurrentWorldGeometry2D())\n return; \/\/do nothing!\n \n PlaneGeometry::ConstPointer input_planeGeometry = dynamic_cast<const PlaneGeometry *>(input->GetGeometry2D());\n PlaneGeometry::ConstPointer worldPlaneGeometry = dynamic_cast<const PlaneGeometry*>(renderer->GetCurrentWorldGeometry2D()); \n \n if(worldPlaneGeometry.IsNotNull() && (input_planeGeometry.IsNotNull()))\n {\n mitk::DisplayGeometry::Pointer displayGeometry = renderer->GetDisplayGeometry();\n assert(displayGeometry);\n\n \/\/calculate intersection of the plane data with the border of the world geometry rectangle\n Point2D lineFrom, lineTo;\n bool intersecting = worldPlaneGeometry->IntersectWithPlane2D( input_planeGeometry, lineFrom, lineTo ) > 0;\n\n if(intersecting)\n {\n mitk::Line<ScalarType, 2> line, tmpLine;\n line.SetPoints(lineFrom, lineTo);\n\n displayGeometry->WorldToDisplay(lineFrom, lineFrom);\n displayGeometry->WorldToDisplay(lineTo, lineTo);\n Vector2D l;\n l=lineTo-lineFrom;\n ScalarType lengthInDisplayUnits = l.GetNorm();\n\n std::vector<ScalarType> lineParams;\n lineParams.reserve(m_OtherGeometry2Ds.size()+2);\n lineParams.push_back(0);\n lineParams.push_back(1);\n\n Vector2D d, dOrth;\n NodesVectorType::iterator otherPlanesIt = m_OtherGeometry2Ds.begin();\n NodesVectorType::iterator otherPlanesEnd = m_OtherGeometry2Ds.end();\n while(otherPlanesIt != otherPlanesEnd)\n {\n mitk::PlaneGeometry* otherPlane = static_cast<PlaneGeometry*>(static_cast<Geometry2DData*>((*otherPlanesIt)->GetData())->GetGeometry2D());\n if(otherPlane != input_planeGeometry)\n {\n bool otherIntersecting = worldPlaneGeometry->IntersectWithPlane2D( otherPlane, lineFrom, lineTo ) > 0;\n if(otherIntersecting)\n {\n tmpLine.SetPoints(lineFrom, lineTo);\n d = tmpLine.GetDirection();\n dOrth[0] = -d[1]; dOrth[1] = d[0];\n ScalarType t = (tmpLine.GetPoint1()-line.GetPoint1())*(dOrth);\n ScalarType norm = line.GetDirection()*dOrth;\n if(fabs(norm) > mitk::eps)\n {\n t \/= norm;\n lineParams.push_back(t);\n }\n }\n }\n\n ++otherPlanesIt;\n }\n\n \/\/apply color and opacity read from the PropertyList\n ApplyProperties(renderer);\n\n ScalarType gapSizeInPixel = 10;\n ScalarType gapSizeInParamUnits = 1.0\/lengthInDisplayUnits*gapSizeInPixel;\n\n std::sort(lineParams.begin(), lineParams.end());\n\n Point2D p1, p2;\n ScalarType p1Param, p2Param; \n \n p1Param = lineParams[0];\n p1 = line.GetPoint(p1Param);\n displayGeometry->WorldToDisplay(p1, p1);\n\n unsigned int i, preLastLineParam = lineParams.size()-1;\n for(i=1; i < preLastLineParam; ++i)\n {\n p2Param = lineParams[i]-gapSizeInParamUnits*0.5;\n p2 = line.GetPoint(p2Param);\n if(p2Param > p1Param)\n {\n \/\/convert intersection points (until now mm) to display coordinates (units )\n displayGeometry->WorldToDisplay(p2, p2);\n\n \/\/draw\n glBegin (GL_LINES);\n glVertex2f(p1[0],p1[1]);\n glVertex2f(p2[0],p2[1]);\n glEnd ();\n }\n p1Param = p2Param+gapSizeInParamUnits;\n p1 = line.GetPoint(p1Param);\n displayGeometry->WorldToDisplay(p1, p1);\n }\n \/\/draw last line segment\n p2Param = lineParams[i];\n p2 = line.GetPoint(p2Param);\n displayGeometry->WorldToDisplay(p2, p2);\n glBegin (GL_LINES);\n glVertex2f(p1[0],p1[1]);\n glVertex2f(p2[0],p2[1]);\n glEnd ();\n }\n }\n else\n {\n mitk::Geometry2DDataToSurfaceFilter::Pointer surfaceCreator;\n mitk::SmartPointerProperty::Pointer surfacecreatorprop;\n surfacecreatorprop=dynamic_cast<mitk::SmartPointerProperty*>(GetDataTreeNode()->GetProperty(\"surfacegeometry\", renderer).GetPointer());\n if( (surfacecreatorprop.IsNull()) || \n (surfacecreatorprop->GetSmartPointer().IsNull()) ||\n ((surfaceCreator=dynamic_cast<mitk::Geometry2DDataToSurfaceFilter*>(surfacecreatorprop->GetSmartPointer().GetPointer())).IsNull())\n )\n {\n surfaceCreator = mitk::Geometry2DDataToSurfaceFilter::New();\n surfacecreatorprop=new mitk::SmartPointerProperty(surfaceCreator);\n surfaceCreator->PlaceByGeometryOn();\n GetDataTreeNode()->SetProperty(\"surfacegeometry\", surfacecreatorprop);\n }\n \n surfaceCreator->SetInput(input);\n \n int res;\n bool usegeometryparametricbounds=true;\n if(GetDataTreeNode()->GetIntProperty(\"xresolution\", res, renderer))\n {\n surfaceCreator->SetXResolution(res);\n usegeometryparametricbounds=false; \n }\n if(GetDataTreeNode()->GetIntProperty(\"yresolution\", res, renderer))\n {\n surfaceCreator->SetYResolution(res);\n usegeometryparametricbounds=false; \n }\n surfaceCreator->SetUseGeometryParametricBounds(usegeometryparametricbounds);\n\n surfaceCreator->Update(); \/\/@FIXME ohne das crash\n \n if(m_SurfaceMapper.IsNull())\n m_SurfaceMapper=mitk::SurfaceMapper2D::New();\n m_SurfaceMapper->SetSurface(surfaceCreator->GetOutput());\n m_SurfaceMapper->SetDataTreeNode(GetDataTreeNode());\n \n m_SurfaceMapper->Paint(renderer);\n }\n }\n}\n<|endoftext|>"} {"text":"<commit_before>#pragma once\n#include<string>\n#include<cstdint>\n#include<fstream>\n#include<array>\n#include<vector>\n#include<algorithm>\nnamespace bmslib {\n\n\tstd::vector<std::string> split_naive(const std::string &s, char delim) {\n\t\tstd::vector<std::string> elems;\n\t\tstd::string item;\n\t\tfor (char ch : s) {\n\t\t\tif (ch == delim) {\n\t\t\t\tif (!item.empty())\n\t\t\t\t\telems.push_back(item);\n\t\t\t\titem.clear();\n\t\t\t}\n\t\t\telse {\n\t\t\t\titem += ch;\n\t\t\t}\n\t\t}\n\t\tif (!item.empty())\n\t\t\telems.push_back(item);\n\t\treturn elems;\n\t}\n\n\tstd::string trim(const std::string& string, const char* trimCharacterList = \" \\t\\v\\r\")\n\t{\n\t\tstd::string result;\n\n\t\t\/\/ g镶ȊO‚ʒu܂B\n\t\tstd::string::size_type left = string.find_first_not_of(trimCharacterList);\n\n\t\tif (left != std::string::npos)\n\t\t{\n\t\t\t\/\/ g镶ȊO‚ꍇ́A悤ɉE܂B\n\t\t\tstd::string::size_type right = string.find_last_not_of(trimCharacterList);\n\n\t\t\t\/\/ ߂l肵܂Bł͉E猟ĂAg镶ȊOK݂̂ŔsvłB\n\t\t\tresult = string.substr(left, right - left + 1);\n\t\t}\n\n\t\treturn result;\n\t}\n\n\tenum Player {\n\t\tNone,\n\t\tSingle,\n\t\tCouple,\n\t\tDouble,\n\t\tBattle\n\t};\n\n\tenum Rank {\n\t\tVeryhard,\n\t\tHard,\n\t\tNormal,\n\t\tEasy\n\t};\n\n\tstruct Header\n\t{\n\t\tPlayer player;\n\t\tstd::string genre, title, artist, stagefile;\n\t\tdouble bpm;\n\t\tunsigned int level, volume, total;\n\t\tRank rank;\n\t\tstd::array<std::string, 575> wav, bmp;\n\t};\n\n\tenum Channel {\n\t\tNone1,\n\t\tBackwav,\n\t\tShortening,\n\t\tChangebpm,\n\t\tBga,\n\t\tNone2,\n\t\tPooranim,\n\t\tBgalayer,\n\t\texBPM,\n\t\tStop,\n\t\tNone3,\n\t\tKey1,\n\t\tKey2,\n\t\tKey3,\n\t\tKey4,\n\t\tKey5,\n\t\tKey6,\n\t\tKey7,\n\t\tKey8,\n\t\tKey9,\n\t\tNone4,\n\t\tKey1_2P,\n\t\tKey2_2P,\n\t\tKey3_2P,\n\t\tKey4_2P,\n\t\tKey5_2P,\n\t\tKey6_2P,\n\t\tKey7_2P,\n\t\tKey8_2P,\n\t\tKey9_2P,\n\t};\n\n\tstruct Bar {\n\t\tChannel channel;\n\t\tint backchorus; \/\/ Set WAV number\n\t\tint length = 1000; \/\/ Default Value = 1000\n\t\tstd::vector<double> bpms;\n\t\tint bga, pooranim, layerbga;\n\t\tstd::array<std::vector<bool>, 9> objects;\n\t};\n\n\tstruct Object {\n\t\tint data;\n\t\tlong time;\n\t\tChannel channel;\n\n\t\tbool operator<(const Object obj) {\n\t\t\treturn time < obj.time;\n\t\t}\n\t};\n\n\n\tstruct Bms {\n\t\tHeader header;\n\t\tstd::vector<Object> bar;\n\t};\n\n\tBms load_data(std::string bmsfile) {\n\t\tstd::ifstream file(bmsfile);\n\t\tstd::string line;\n\t\tif (file.fail())\n\t\t{\n\t\t\treturn Bms();\n\t\t}\n\t\tBms bms;\n\t\twhile (getline(file, line))\n\t\t{\n\t\t\ttrim(line);\n\t\t\tif (line[0] == '#') {\n\t\t\t\tif (isdigit(line[1])) {\n\t\t\t\t\tauto str = split_naive(line,':');\n\t\t\t\t\t\n\t\t\t\t\tauto command = str[0];\n\t\t\t\t\tauto data = str[1];\n\n\t\t\t\t\tif (bms.bar.size() < std::stoi(command.substr(1, 3)) + 1){\n\t\t\t\t\t\tbms.bar.reserve(std::stoi(command.substr(1, 3)) + 1);\n\t\t\t\t\t}\n\t\t\t\t\tauto channel = static_cast<Channel>(std::stoi(command.substr(4, 2)));\n\t\t\t\t\tint num_bar = std::stoi(command.substr(0, 3));\n\t\t\t\t\tint num_note = data.size() \/ 2;\n\t\t\t\t\tfor (int i = 0; i < num_note - 1; i++) {\n\t\t\t\t\t\tObject obj;\n\t\t\t\t\t\tobj.time = 9600 * num_bar + i*(9600 \/ num_note);\n\t\t\t\t\t\tobj.data = std::stoi(data.substr(i, 2));\n\t\t\t\t\t\tobj.channel = channel;\n\t\t\t\t\t\tbms.bar.push_back(obj);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tstd::sort(bms.bar.begin(), bms.bar.end());\n\t}\n\n\tBms loadheader(std::string bmsfile) {\n\t\tstd::ifstream file(bmsfile);\n\t\tstd::string line;\n\t\tif (file.fail())\n\t\t{\n\t\t\treturn Bms();\n\t\t}\n\t\tBms bms;\n\n\t\twhile (getline(file, line))\n\t\t{\n\n\t\t\tif (line[0] == '#') {\n\n\t\t\t\tif (!isdigit(line[1])) {\n\n\t\t\t\t\tauto strs = split_naive(line, ' ');\n\t\t\t\t\tstd::string command = strs[0].substr(1);\n\t\t\t\t\tstd::string arg1;\n\t\t\t\t\tif (strs.size() == 1) {\n\t\t\t\t\t\targ1 = \"\";\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\targ1 = strs[1];\n\t\t\t\t\t}\n\n\t\t\t\t\tif (!std::strcmp(command.c_str(), \"PLAYER\")) {\n\n\t\t\t\t\t\tbms.header.player = static_cast<Player>(std::stoi(arg1.c_str()));\n\t\t\t\t\t}\n\t\t\t\t\tif (!std::strcmp(command.c_str(), \"GENRE\")) {\n\t\t\t\t\t\tbms.header.genre = arg1;\n\t\t\t\t\t}\n\t\t\t\t\tif (!std::strcmp(command.c_str(), \"TITLE\")) {\n\t\t\t\t\t\tstd::string rs;\n\t\t\t\t\t\tfor (int i = 1; i < strs.size() - 1; i++) {\n\t\t\t\t\t\t\trs += strs[i];\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbms.header.title = rs;\n\t\t\t\t\t}\n\t\t\t\t\tif (!std::strcmp(command.c_str(), \"ARTIST\")) {\n\t\t\t\t\t\tbms.header.artist = arg1;\n\t\t\t\t\t}\n\t\t\t\t\tif (!std::strcmp(command.c_str(), \"BPM\")) {\n\t\t\t\t\t\tbms.header.bpm = std::stof(arg1);\n\t\t\t\t\t}\n\t\t\t\t\tif (!std::strcmp(command.c_str(), \"PLAYLEVEL\")) {\n\t\t\t\t\t\tbms.header.level = std::stoi(arg1);\n\t\t\t\t\t}\n\t\t\t\t\tif (!std::strcmp(command.c_str(), \"RANK\")) {\n\t\t\t\t\t\tbms.header.rank = static_cast<Rank>(std::stoi(arg1));\n\t\t\t\t\t}\n\t\t\t\t\tif (!std::strcmp(command.c_str(), \"VOLWAV\")) {\n\t\t\t\t\t\tbms.header.volume = std::stoi(arg1);\n\t\t\t\t\t}\n\t\t\t\t\tif (!std::strcmp(command.c_str(), \"TOTAL\")) {\n\t\t\t\t\t\tbms.header.total = std::stoi(arg1);\n\t\t\t\t\t}\n\t\t\t\t\tif (!std::strcmp(command.substr(0, 3).c_str(), \"WAV\")) {\n\t\t\t\t\t\tbms.header.wav[std::stoi(command.substr(3, 2), nullptr, 36)] = arg1;\n\t\t\t\t\t}\n\t\t\t\t\tif (!std::strcmp(command.substr(0, 3).c_str(), \"BMP\")) {\n\t\t\t\t\t\tbms.header.bmp[std::stoi(command.substr(3, 2), nullptr, 36)] = arg1;\n\t\t\t\t\t}\n\t\t\t\t\tif (!std::strcmp(command.c_str(), \"StageFile\")) {\n\t\t\t\t\t\tbms.header.stagefile = arg1;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn bms;\n\t}\n\n\tvoid save(std::string filename, const Bms& bms) {\n\n\t}\n}<commit_msg>直ってなかったてへぺろ<commit_after>#pragma once\n#include<string>\n#include<cstdint>\n#include<fstream>\n#include<array>\n#include<vector>\n#include<algorithm>\nnamespace bmslib {\n\n\tstd::vector<std::string> split_naive(const std::string &s, char delim) {\n\t\tstd::vector<std::string> elems;\n\t\tstd::string item;\n\t\tfor (char ch : s) {\n\t\t\tif (ch == delim) {\n\t\t\t\tif (!item.empty())\n\t\t\t\t\telems.push_back(item);\n\t\t\t\titem.clear();\n\t\t\t}\n\t\t\telse {\n\t\t\t\titem += ch;\n\t\t\t}\n\t\t}\n\t\tif (!item.empty())\n\t\t\telems.push_back(item);\n\t\treturn elems;\n\t}\n\n\tstd::string trim(const std::string& string, const char* trimCharacterList = \" \\t\\v\\r\")\n\t{\n\t\tstd::string result;\n\n\t\t\/\/ g镶ȊO‚ʒu܂B\n\t\tstd::string::size_type left = string.find_first_not_of(trimCharacterList);\n\n\t\tif (left != std::string::npos)\n\t\t{\n\t\t\t\/\/ g镶ȊO‚ꍇ́A悤ɉE܂B\n\t\t\tstd::string::size_type right = string.find_last_not_of(trimCharacterList);\n\n\t\t\t\/\/ ߂l肵܂Bł͉E猟ĂAg镶ȊOK݂̂ŔsvłB\n\t\t\tresult = string.substr(left, right - left + 1);\n\t\t}\n\n\t\treturn result;\n\t}\n\n\tenum Player {\n\t\tNone,\n\t\tSingle,\n\t\tCouple,\n\t\tDouble,\n\t\tBattle\n\t};\n\n\tenum Rank {\n\t\tVeryhard,\n\t\tHard,\n\t\tNormal,\n\t\tEasy\n\t};\n\n\tstruct Header\n\t{\n\t\tPlayer player;\n\t\tstd::string genre, title, artist, stagefile;\n\t\tdouble bpm;\n\t\tunsigned int level, volume, total;\n\t\tRank rank;\n\t\tstd::array<std::string, 575> wav, bmp;\n\t};\n\n\tenum Channel {\n\t\tNone1,\n\t\tBackwav,\n\t\tShortening,\n\t\tChangebpm,\n\t\tBga,\n\t\tNone2,\n\t\tPooranim,\n\t\tBgalayer,\n\t\texBPM,\n\t\tStop,\n\t\tNone3,\n\t\tKey1,\n\t\tKey2,\n\t\tKey3,\n\t\tKey4,\n\t\tKey5,\n\t\tKey6,\n\t\tKey7,\n\t\tKey8,\n\t\tKey9,\n\t\tNone4,\n\t\tKey1_2P,\n\t\tKey2_2P,\n\t\tKey3_2P,\n\t\tKey4_2P,\n\t\tKey5_2P,\n\t\tKey6_2P,\n\t\tKey7_2P,\n\t\tKey8_2P,\n\t\tKey9_2P,\n\t};\n\n\tstruct Bar {\n\t\tChannel channel;\n\t\tint backchorus; \/\/ Set WAV number\n\t\tint length = 1000; \/\/ Default Value = 1000\n\t\tstd::vector<double> bpms;\n\t\tint bga, pooranim, layerbga;\n\t\tstd::array<std::vector<bool>, 9> objects;\n\t};\n\n\tstruct Object {\n\t\tint data;\n\t\tlong time;\n\t\tChannel channel;\n\n\t\tbool operator<(const Object obj) {\n\t\t\treturn time < obj.time;\n\t\t}\n\t};\n\n\n\tstruct Bms {\n\t\tHeader header;\n\t\tstd::vector<Object> bar;\n\t};\n\n\tBms load_data(std::string bmsfile) {\n\t\tstd::ifstream file(bmsfile);\n\t\tstd::string line;\n\t\tif (file.fail())\n\t\t{\n\t\t\treturn Bms();\n\t\t}\n\t\tBms bms;\n\t\twhile (getline(file, line))\n\t\t{\n\t\t\ttrim(line);\n\t\t\tif (line[0] == '#') {\n\t\t\t\tif (isdigit(line[1])) {\n\t\t\t\t\tauto str = split_naive(line,':');\n\t\t\t\t\t\n\t\t\t\t\tauto command = str[0];\n\t\t\t\t\tauto data = str[1];\n\n\t\t\t\t\tif (bms.bar.size() < std::stoi(command.substr(1, 3)) + 1){\n\t\t\t\t\t\tbms.bar.reserve(std::stoi(command.substr(1, 3)) + 1);\n\t\t\t\t\t}\n\t\t\t\t\tauto channel = static_cast<Channel>(std::stoi(command.substr(4, 2)));\n\t\t\t\t\tint num_bar = std::stoi(command.substr(0, 3));\n\t\t\t\t\tint num_note = data.size() \/ 2;\n\t\t\t\t\tfor (int i = 0; i < num_note - 1; i++) {\n\t\t\t\t\t\tObject obj;\n\t\t\t\t\t\tobj.time = 9600 * num_bar + i*(9600 \/ num_note);\n\t\t\t\t\t\tobj.data = std::stoi(data.substr(i, 2));\n\t\t\t\t\t\tobj.channel = channel;\n\t\t\t\t\t\tbms.bar.push_back(obj);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tstd::sort(bms.bar.begin(), bms.bar.end());\n\t}\n\n\tBms loadheader(std::string bmsfile) {\n\t\tstd::ifstream file(bmsfile);\n\t\tstd::string line;\n\t\tif (file.fail())\n\t\t{\n\t\t\treturn Bms();\n\t\t}\n\t\tBms bms;\n\n\t\twhile (getline(file, line))\n\t\t{\n\n\t\t\tif (line[0] == '#') {\n\n\t\t\t\tif (!isdigit(line[1])) {\n\n\t\t\t\t\tauto strs = split_naive(line, ' ');\n\t\t\t\t\tstd::string command = strs[0].substr(1);\n\t\t\t\t\tstd::string arg1;\n\t\t\t\t\tif (strs.size() == 1) {\n\t\t\t\t\t\targ1 = \"\";\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\targ1 = strs[1];\n\t\t\t\t\t}\n\n\t\t\t\t\tif (!std::strcmp(command.c_str(), \"PLAYER\")) {\n\n\t\t\t\t\t\tbms.header.player = static_cast<Player>(std::stoi(arg1.c_str()));\n\t\t\t\t\t}\n\t\t\t\t\tif (!std::strcmp(command.c_str(), \"GENRE\")) {\n\t\t\t\t\t\tbms.header.genre = arg1;\n\t\t\t\t\t}\n\t\t\t\t\tif (!std::strcmp(command.c_str(), \"TITLE\")) {\n\t\t\t\t\t\tstd::string rs;\n\t\t\t\t\t\tfor (int i = 1; i < strs.size() - 1; i++) {\n\t\t\t\t\t\t\trs += strs[i];\n\t\t\t\t\t\t\trs += \"\";\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbms.header.title = rs;\n\t\t\t\t\t}\n\t\t\t\t\tif (!std::strcmp(command.c_str(), \"ARTIST\")) {\n\t\t\t\t\t\tbms.header.artist = arg1;\n\t\t\t\t\t}\n\t\t\t\t\tif (!std::strcmp(command.c_str(), \"BPM\")) {\n\t\t\t\t\t\tbms.header.bpm = std::stof(arg1);\n\t\t\t\t\t}\n\t\t\t\t\tif (!std::strcmp(command.c_str(), \"PLAYLEVEL\")) {\n\t\t\t\t\t\tbms.header.level = std::stoi(arg1);\n\t\t\t\t\t}\n\t\t\t\t\tif (!std::strcmp(command.c_str(), \"RANK\")) {\n\t\t\t\t\t\tbms.header.rank = static_cast<Rank>(std::stoi(arg1));\n\t\t\t\t\t}\n\t\t\t\t\tif (!std::strcmp(command.c_str(), \"VOLWAV\")) {\n\t\t\t\t\t\tbms.header.volume = std::stoi(arg1);\n\t\t\t\t\t}\n\t\t\t\t\tif (!std::strcmp(command.c_str(), \"TOTAL\")) {\n\t\t\t\t\t\tbms.header.total = std::stoi(arg1);\n\t\t\t\t\t}\n\t\t\t\t\tif (!std::strcmp(command.substr(0, 3).c_str(), \"WAV\")) {\n\t\t\t\t\t\tbms.header.wav[std::stoi(command.substr(3, 2), nullptr, 36)] = arg1;\n\t\t\t\t\t}\n\t\t\t\t\tif (!std::strcmp(command.substr(0, 3).c_str(), \"BMP\")) {\n\t\t\t\t\t\tbms.header.bmp[std::stoi(command.substr(3, 2), nullptr, 36)] = arg1;\n\t\t\t\t\t}\n\t\t\t\t\tif (!std::strcmp(command.c_str(), \"StageFile\")) {\n\t\t\t\t\t\tbms.header.stagefile = arg1;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn bms;\n\t}\n\n\tvoid save(std::string filename, const Bms& bms) {\n\n\t}\n}<|endoftext|>"} {"text":"<commit_before>\/************************************************************************\r\n*\r\n* Flood Project (2008-201x)\r\n* Licensed under the simplified BSD license. All rights reserved.\r\n*\r\n************************************************************************\/\r\n\r\n#include \"Core\/API.h\"\r\n\r\n#ifdef ENABLE_ARCHIVE_DIR\r\n\r\n#include \"Core\/Archive.h\"\r\n#include \"Core\/Stream.h\"\r\n#include \"Core\/Memory.h\"\r\n#include \"Core\/Log.h\"\r\n#include \"Core\/Utilities.h\"\r\n\r\nNAMESPACE_CORE_BEGIN\r\n\r\n\/\/-----------------------------------\/\/\r\n\r\nstatic bool DirArchiveOpen(Archive*, const String&);\r\nstatic bool DirArchiveClose(Archive*);\r\nstatic Stream* DirArchiveOpenFile(Archive*, const Path&, Allocator*);\r\nstatic void DirArchiveEnumerateFiles(Archive*, std::vector<Path>&);\r\nstatic void DirArchiveEnumerateDirectories(Archive*, std::vector<Path>&);\r\nstatic bool DirArchiveExistsFile(Archive*, const Path&);\r\nstatic bool DirArchiveExistsDir(Archive*, const Path&);\r\nstatic bool DirArchiveMonitor(Archive*);\r\n\r\nstatic ArchiveFuncs gs_DirArchiveFuncs =\r\n{\r\n\tDirArchiveOpen,\r\n\tDirArchiveClose,\r\n\tDirArchiveOpenFile,\r\n\tDirArchiveExistsFile,\r\n\tDirArchiveExistsDir,\r\n\tDirArchiveEnumerateFiles,\r\n\tDirArchiveEnumerateDirectories,\r\n\tDirArchiveMonitor,\r\n};\r\n\r\n\/\/-----------------------------------\/\/\r\n\r\nArchive* ArchiveCreateFromDirectory(Allocator* alloc, const Path& path)\r\n{\r\n\tArchive* archive = Allocate(alloc, Archive);\r\n\t\r\n\tarchive->path = path;\r\n\tarchive->handle = nullptr;\r\n\tarchive->scheme = \"fs\";\r\n\tarchive->fn = &gs_DirArchiveFuncs;\r\n\r\n\tif( !ArchiveOpen(archive, path) )\r\n\t{\r\n\t\tLogDebug(\"Error opening archive: %s\", path.c_str());\r\n\t\tDeallocate(archive);\r\n\t\treturn nullptr;\r\n\t}\r\n\r\n\treturn archive;\r\n}\r\n\r\n\/\/-----------------------------------\/\/\r\n\r\nstatic bool DirArchiveOpen(Archive* archive, const String& path)\r\n{\r\n\tif( !archive ) return false;\r\n\treturn true;\r\n}\r\n\r\n\/\/-----------------------------------\/\/\r\n\r\nstatic bool DirArchiveClose(Archive* archive)\r\n{\r\n\tif( !archive ) return false;\r\n\r\n\tif(archive->watchId != 0)\r\n\t{\r\n\t\t\/\/ Remove the archive from the watch list.\r\n\t\tGetFileWatcher()->removeWatch(archive->watchId);\r\n\t}\r\n\r\n\treturn true;\r\n}\r\n\r\n\/\/-----------------------------------\/\/\r\n\r\nstatic Stream* DirArchiveOpenFile(Archive* archive, const Path& file, Allocator* alloc)\r\n{\r\n\tif( !archive ) return nullptr;\r\n\t\r\n\tPath fullPath = ArchiveCombinePath(archive, file);\r\n\tStream* stream = AllocateHeap(FileStream, fullPath, StreamOpenMode::Read);\r\n\r\n\treturn stream;\r\n}\r\n\r\n\/\/-----------------------------------\/\/\r\n\r\nstatic void DirArchiveEnumerate(std::vector<String>&, Path, Path, bool);\r\n\r\nstatic void DirArchiveEnumerateFiles(Archive* archive, std::vector<Path>& paths)\r\n{\r\n\tif( !archive ) return;\r\n\tFileEnumerateFiles(archive->path, paths);\r\n}\r\n\r\n\/\/-----------------------------------\/\/\r\n\r\nstatic void DirArchiveEnumerateDirectories(Archive* archive, std::vector<Path>& paths)\r\n{\r\n\tif( !archive ) return;\r\n\tFileEnumerateDirectories(archive->path, paths);\r\n}\r\n\r\n\/\/-----------------------------------\/\/\r\n\r\nstatic bool DirArchiveExistsFile(Archive* archive, const Path& file)\r\n{\r\n\tif( !archive ) return false;\r\n\t\r\n\tconst Path& fullPath = ArchiveCombinePath(archive, file);\r\n\treturn FileExists(fullPath);\r\n}\r\n\r\n\/\/-----------------------------------\/\/\r\n\r\nstatic bool DirArchiveExistsDir(Archive* archive, const Path& path)\r\n{\r\n\tstd::vector<Path> dirs;\r\n\tArchiveEnumerateDirectories(archive, dirs);\r\n\r\n\tfor(size_t i = 0; i < dirs.size(); i++)\r\n\t{\r\n\t\tPath normalized = PathNormalize(dirs[i]);\r\n\t\tPath dir = StringTrim(normalized, \"\/\");\r\n\t\tif(dir == path) return true;\r\n\t}\r\n\r\n\treturn false;\r\n}\r\n\r\n\/\/-----------------------------------\/\/\r\n\r\nstatic void HandleFileWatch(const FileWatchEvent& event)\r\n{\r\n\tArchive* archive = (Archive*) event.userdata;\r\n\tassert( archive != nullptr );\r\n\r\n\tarchive->watch(archive, event);\r\n}\r\n\r\n\/\/-----------------------------------\/\/\r\n\r\nstatic bool DirArchiveMonitor(Archive* archive)\r\n{\r\n\tif( !archive ) return false;\r\n\r\n\tGetFileWatcher()->onFileWatchEvent.Connect(&HandleFileWatch);\r\n\r\n\tif(archive->watchId == 0)\r\n\t{\r\n\t\t\/\/ Add the archive to the watch list.\r\n\t\tarchive->watchId = GetFileWatcher()->addWatch(archive->path, archive);\r\n\t}\r\n\r\n\tGetFileWatcher()->update();\r\n\r\n\treturn true;\r\n}\r\n\r\n#endif\r\n\r\n\/\/-----------------------------------\/\/\r\n\r\nNAMESPACE_CORE_END<commit_msg>Check if the file exists when opening a new file from a directory.<commit_after>\/************************************************************************\r\n*\r\n* Flood Project (2008-201x)\r\n* Licensed under the simplified BSD license. All rights reserved.\r\n*\r\n************************************************************************\/\r\n\r\n#include \"Core\/API.h\"\r\n\r\n#ifdef ENABLE_ARCHIVE_DIR\r\n\r\n#include \"Core\/Archive.h\"\r\n#include \"Core\/Stream.h\"\r\n#include \"Core\/Memory.h\"\r\n#include \"Core\/Log.h\"\r\n#include \"Core\/Utilities.h\"\r\n\r\nNAMESPACE_CORE_BEGIN\r\n\r\n\/\/-----------------------------------\/\/\r\n\r\nstatic bool DirArchiveOpen(Archive*, const String&);\r\nstatic bool DirArchiveClose(Archive*);\r\nstatic Stream* DirArchiveOpenFile(Archive*, const Path&, Allocator*);\r\nstatic void DirArchiveEnumerateFiles(Archive*, std::vector<Path>&);\r\nstatic void DirArchiveEnumerateDirectories(Archive*, std::vector<Path>&);\r\nstatic bool DirArchiveExistsFile(Archive*, const Path&);\r\nstatic bool DirArchiveExistsDir(Archive*, const Path&);\r\nstatic bool DirArchiveMonitor(Archive*);\r\n\r\nstatic ArchiveFuncs gs_DirArchiveFuncs =\r\n{\r\n\tDirArchiveOpen,\r\n\tDirArchiveClose,\r\n\tDirArchiveOpenFile,\r\n\tDirArchiveExistsFile,\r\n\tDirArchiveExistsDir,\r\n\tDirArchiveEnumerateFiles,\r\n\tDirArchiveEnumerateDirectories,\r\n\tDirArchiveMonitor,\r\n};\r\n\r\n\/\/-----------------------------------\/\/\r\n\r\nArchive* ArchiveCreateFromDirectory(Allocator* alloc, const Path& path)\r\n{\r\n\tArchive* archive = Allocate(alloc, Archive);\r\n\t\r\n\tarchive->path = path;\r\n\tarchive->handle = nullptr;\r\n\tarchive->scheme = \"fs\";\r\n\tarchive->fn = &gs_DirArchiveFuncs;\r\n\r\n\tif( !ArchiveOpen(archive, path) )\r\n\t{\r\n\t\tLogDebug(\"Error opening archive: %s\", path.c_str());\r\n\t\tDeallocate(archive);\r\n\t\treturn nullptr;\r\n\t}\r\n\r\n\treturn archive;\r\n}\r\n\r\n\/\/-----------------------------------\/\/\r\n\r\nstatic bool DirArchiveOpen(Archive* archive, const String& path)\r\n{\r\n\tif( !archive ) return false;\r\n\treturn true;\r\n}\r\n\r\n\/\/-----------------------------------\/\/\r\n\r\nstatic bool DirArchiveClose(Archive* archive)\r\n{\r\n\tif( !archive ) return false;\r\n\r\n\tif(archive->watchId != 0)\r\n\t{\r\n\t\t\/\/ Remove the archive from the watch list.\r\n\t\tGetFileWatcher()->removeWatch(archive->watchId);\r\n\t}\r\n\r\n\treturn true;\r\n}\r\n\r\n\/\/-----------------------------------\/\/\r\n\r\nstatic Stream* DirArchiveOpenFile(Archive* archive, const Path& file, Allocator* alloc)\r\n{\r\n\tif( !archive ) return nullptr;\r\n\t\r\n\tPath fullPath = ArchiveCombinePath(archive, file);\r\n\r\n\tif (!FileExists(fullPath))\r\n\t\treturn nullptr;\r\n\r\n\tStream* stream = AllocateHeap(FileStream, fullPath, StreamOpenMode::Read);\r\n\r\n\treturn stream;\r\n}\r\n\r\n\/\/-----------------------------------\/\/\r\n\r\nstatic void DirArchiveEnumerate(std::vector<String>&, Path, Path, bool);\r\n\r\nstatic void DirArchiveEnumerateFiles(Archive* archive, std::vector<Path>& paths)\r\n{\r\n\tif( !archive ) return;\r\n\tFileEnumerateFiles(archive->path, paths);\r\n}\r\n\r\n\/\/-----------------------------------\/\/\r\n\r\nstatic void DirArchiveEnumerateDirectories(Archive* archive, std::vector<Path>& paths)\r\n{\r\n\tif( !archive ) return;\r\n\tFileEnumerateDirectories(archive->path, paths);\r\n}\r\n\r\n\/\/-----------------------------------\/\/\r\n\r\nstatic bool DirArchiveExistsFile(Archive* archive, const Path& file)\r\n{\r\n\tif( !archive ) return false;\r\n\t\r\n\tconst Path& fullPath = ArchiveCombinePath(archive, file);\r\n\treturn FileExists(fullPath);\r\n}\r\n\r\n\/\/-----------------------------------\/\/\r\n\r\nstatic bool DirArchiveExistsDir(Archive* archive, const Path& path)\r\n{\r\n\tstd::vector<Path> dirs;\r\n\tArchiveEnumerateDirectories(archive, dirs);\r\n\r\n\tfor(size_t i = 0; i < dirs.size(); i++)\r\n\t{\r\n\t\tPath normalized = PathNormalize(dirs[i]);\r\n\t\tPath dir = StringTrim(normalized, \"\/\");\r\n\t\tif(dir == path) return true;\r\n\t}\r\n\r\n\treturn false;\r\n}\r\n\r\n\/\/-----------------------------------\/\/\r\n\r\nstatic void HandleFileWatch(const FileWatchEvent& event)\r\n{\r\n\tArchive* archive = (Archive*) event.userdata;\r\n\tassert( archive != nullptr );\r\n\r\n\tarchive->watch(archive, event);\r\n}\r\n\r\n\/\/-----------------------------------\/\/\r\n\r\nstatic bool DirArchiveMonitor(Archive* archive)\r\n{\r\n\tif( !archive ) return false;\r\n\r\n\tGetFileWatcher()->onFileWatchEvent.Connect(&HandleFileWatch);\r\n\r\n\tif(archive->watchId == 0)\r\n\t{\r\n\t\t\/\/ Add the archive to the watch list.\r\n\t\tarchive->watchId = GetFileWatcher()->addWatch(archive->path, archive);\r\n\t}\r\n\r\n\tGetFileWatcher()->update();\r\n\r\n\treturn true;\r\n}\r\n\r\n#endif\r\n\r\n\/\/-----------------------------------\/\/\r\n\r\nNAMESPACE_CORE_END<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2017, Joseph Mirabel\n\/\/ Authors: Joseph Mirabel (joseph.mirabel@laas.fr)\n\/\/\n\/\/ This file is part of hpp-pinocchio.\n\/\/ hpp-pinocchio is free software: you can redistribute it\n\/\/ and\/or modify it under the terms of the GNU Lesser General Public\n\/\/ License as published by the Free Software Foundation, either version\n\/\/ 3 of the License, or (at your option) any later version.\n\/\/\n\/\/ hpp-pinocchio is distributed in the hope that it will be\n\/\/ useful, but WITHOUT ANY WARRANTY; without even the implied warranty\n\/\/ of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ General Lesser Public License for more details. You should have\n\/\/ received a copy of the GNU Lesser General Public License along with\n\/\/ hpp-pinocchio. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n\n#define BOOST_TEST_MODULE tframe\n\n#include <boost\/test\/unit_test.hpp>\n\n#include <hpp\/pinocchio\/joint.hh>\n#include <hpp\/pinocchio\/device.hh>\n#include <hpp\/pinocchio\/simple-device.hh>\n#include <hpp\/pinocchio\/humanoid-robot.hh>\n#include <hpp\/pinocchio\/urdf\/util.hh>\n#include <hpp\/pinocchio\/liegroup-space.hh>\n#include <hpp\/pinocchio\/configuration.hh>\nstatic bool verbose = true;\n\nusing namespace hpp::pinocchio;\n\nvoid displayAABB(const fcl::AABB& aabb)\n{\n std::cout << \"Bounding box is\\n\"\n << aabb.min_.transpose() << '\\n'\n << aabb.max_.transpose() << std::endl;\n}\n\nBOOST_AUTO_TEST_CASE (computeAABB)\n{\n DevicePtr_t robot = unittest::makeDevice(unittest::HumanoidSimple);\n BOOST_REQUIRE(robot);\n\n robot->rootJoint()->lowerBounds(vector3_t::Constant(-0));\n robot->rootJoint()->upperBounds(vector3_t::Constant( 0));\n fcl::AABB aabb0 = robot->computeAABB();\n if (verbose) displayAABB(aabb0);\n\n robot->rootJoint()->lowerBounds(vector3_t(-1, -1, 0));\n robot->rootJoint()->upperBounds(vector3_t( 1, 1, 0));\n fcl::AABB aabb1 = robot->computeAABB();\n if (verbose) displayAABB(aabb1);\n\n robot->rootJoint()->lowerBounds(vector3_t(-2, -2, 0));\n robot->rootJoint()->upperBounds(vector3_t(-1, -1, 0));\n fcl::AABB aabb2 = robot->computeAABB();\n if (verbose) displayAABB(aabb2);\n}\n\/* -------------------------------------------------------------------------- *\/\nBOOST_AUTO_TEST_CASE (unit_test_device)\n{\n DevicePtr_t robot;\n LiegroupSpacePtr_t space;\n\n robot = unittest::makeDevice (unittest::HumanoidSimple);\n space = LiegroupSpace::createCopy(robot->configSpace());\n space->mergeVectorSpaces();\n BOOST_CHECK_EQUAL (space->name(), \"SE(3)*R^26\");\n\n space = LiegroupSpace::createCopy(robot->RnxSOnConfigSpace());\n space->mergeVectorSpaces();\n BOOST_CHECK_EQUAL (space->name(), \"R^3*SO(3)*R^26\");\n\n robot->setDimensionExtraConfigSpace(3);\n BOOST_CHECK_EQUAL(robot->numberDof(), 32+3);\n BOOST_CHECK_EQUAL(robot->configSize(), 33+3);\n\n space = LiegroupSpace::createCopy(robot->configSpace());\n space->mergeVectorSpaces();\n BOOST_CHECK_EQUAL (space->name(), \"SE(3)*R^29\");\n\n robot = unittest::makeDevice (unittest::CarLike);\n space = LiegroupSpace::createCopy(robot->configSpace());\n space->mergeVectorSpaces();\n BOOST_CHECK_EQUAL (space->name(), \"SE(2)*R^2\");\n\n robot = unittest::makeDevice (unittest::ManipulatorArm2);\n space = LiegroupSpace::createCopy(robot->configSpace());\n space->mergeVectorSpaces();\n BOOST_CHECK_EQUAL (space->name(), \"R^19\");\n}\n\n\/\/ TODO When neutral configuration can be read from XML string, this test should be updated in order to\n\/\/ read a URDF and SRDF string rather than a file in a different package.\nBOOST_AUTO_TEST_CASE(load_neutral_configuration){\n std::string robotName(\"romeo\");\n std::string packageName(\"romeo_description\");\n std::string rootJointType(\"freeflyer\");\n std::string modelName(\"romeo\");\n std::string urdfSuffix(\"_small\");\n std::string srdfSuffix(\"\");\n\n DevicePtr_t device = Device::create(robotName);\n urdf::loadRobotModel (device,\n rootJointType, packageName,modelName, urdfSuffix,srdfSuffix);\n BOOST_CHECK(device);\n BOOST_CHECK_EQUAL(device->neutralConfiguration().size(),device->configSize());\n Eigen::VectorXd expected(device->configSize());\n \/\/ values fond in the srdf file, if the file change this test need to be updated :\n expected << 0,0,0,0,0,0,1,0,0,-0.3490658,0.6981317,-0.3490658,0,0,0,-0.3490658,0.6981317,-0.3490658,0,0,1.5,0.6,-0.5,-1.05,-0.4,-0.3,-0.2,0,0,0,0,1.5,-0.6,0.5,1.05,-0.4,-0.3,-0.2;\n if(verbose)\n std::cout<<\"neutral configuration after loading romeo : \"<<displayConfig(device->neutralConfiguration())<<std::endl;\n BOOST_CHECK_MESSAGE(device->neutralConfiguration().isApprox(expected, 1e-12), \"neutral configuration - wrong results\");\n}\n\n<commit_msg>Update unit-test to hpp::fcl namespace.<commit_after>\/\/ Copyright (c) 2017, Joseph Mirabel\n\/\/ Authors: Joseph Mirabel (joseph.mirabel@laas.fr)\n\/\/\n\/\/ This file is part of hpp-pinocchio.\n\/\/ hpp-pinocchio is free software: you can redistribute it\n\/\/ and\/or modify it under the terms of the GNU Lesser General Public\n\/\/ License as published by the Free Software Foundation, either version\n\/\/ 3 of the License, or (at your option) any later version.\n\/\/\n\/\/ hpp-pinocchio is distributed in the hope that it will be\n\/\/ useful, but WITHOUT ANY WARRANTY; without even the implied warranty\n\/\/ of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ General Lesser Public License for more details. You should have\n\/\/ received a copy of the GNU Lesser General Public License along with\n\/\/ hpp-pinocchio. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n\n#define BOOST_TEST_MODULE tframe\n\n#include <boost\/test\/unit_test.hpp>\n\n#include <hpp\/pinocchio\/joint.hh>\n#include <hpp\/pinocchio\/device.hh>\n#include <hpp\/pinocchio\/simple-device.hh>\n#include <hpp\/pinocchio\/humanoid-robot.hh>\n#include <hpp\/pinocchio\/urdf\/util.hh>\n#include <hpp\/pinocchio\/liegroup-space.hh>\n#include <hpp\/pinocchio\/configuration.hh>\nstatic bool verbose = true;\n\nusing namespace hpp::pinocchio;\n\nvoid displayAABB(const hpp::fcl::AABB& aabb)\n{\n std::cout << \"Bounding box is\\n\"\n << aabb.min_.transpose() << '\\n'\n << aabb.max_.transpose() << std::endl;\n}\n\nBOOST_AUTO_TEST_CASE (computeAABB)\n{\n DevicePtr_t robot = unittest::makeDevice(unittest::HumanoidSimple);\n BOOST_REQUIRE(robot);\n\n robot->rootJoint()->lowerBounds(vector3_t::Constant(-0));\n robot->rootJoint()->upperBounds(vector3_t::Constant( 0));\n hpp::fcl::AABB aabb0 = robot->computeAABB();\n if (verbose) displayAABB(aabb0);\n\n robot->rootJoint()->lowerBounds(vector3_t(-1, -1, 0));\n robot->rootJoint()->upperBounds(vector3_t( 1, 1, 0));\n hpp::fcl::AABB aabb1 = robot->computeAABB();\n if (verbose) displayAABB(aabb1);\n\n robot->rootJoint()->lowerBounds(vector3_t(-2, -2, 0));\n robot->rootJoint()->upperBounds(vector3_t(-1, -1, 0));\n hpp::fcl::AABB aabb2 = robot->computeAABB();\n if (verbose) displayAABB(aabb2);\n}\n\/* -------------------------------------------------------------------------- *\/\nBOOST_AUTO_TEST_CASE (unit_test_device)\n{\n DevicePtr_t robot;\n LiegroupSpacePtr_t space;\n\n robot = unittest::makeDevice (unittest::HumanoidSimple);\n space = LiegroupSpace::createCopy(robot->configSpace());\n space->mergeVectorSpaces();\n BOOST_CHECK_EQUAL (space->name(), \"SE(3)*R^26\");\n\n space = LiegroupSpace::createCopy(robot->RnxSOnConfigSpace());\n space->mergeVectorSpaces();\n BOOST_CHECK_EQUAL (space->name(), \"R^3*SO(3)*R^26\");\n\n robot->setDimensionExtraConfigSpace(3);\n BOOST_CHECK_EQUAL(robot->numberDof(), 32+3);\n BOOST_CHECK_EQUAL(robot->configSize(), 33+3);\n\n space = LiegroupSpace::createCopy(robot->configSpace());\n space->mergeVectorSpaces();\n BOOST_CHECK_EQUAL (space->name(), \"SE(3)*R^29\");\n\n robot = unittest::makeDevice (unittest::CarLike);\n space = LiegroupSpace::createCopy(robot->configSpace());\n space->mergeVectorSpaces();\n BOOST_CHECK_EQUAL (space->name(), \"SE(2)*R^2\");\n\n robot = unittest::makeDevice (unittest::ManipulatorArm2);\n space = LiegroupSpace::createCopy(robot->configSpace());\n space->mergeVectorSpaces();\n BOOST_CHECK_EQUAL (space->name(), \"R^19\");\n}\n\n\/\/ TODO When neutral configuration can be read from XML string, this test should be updated in order to\n\/\/ read a URDF and SRDF string rather than a file in a different package.\nBOOST_AUTO_TEST_CASE(load_neutral_configuration){\n std::string robotName(\"romeo\");\n std::string packageName(\"romeo_description\");\n std::string rootJointType(\"freeflyer\");\n std::string modelName(\"romeo\");\n std::string urdfSuffix(\"_small\");\n std::string srdfSuffix(\"\");\n\n DevicePtr_t device = Device::create(robotName);\n urdf::loadRobotModel (device,\n rootJointType, packageName,modelName, urdfSuffix,srdfSuffix);\n BOOST_CHECK(device);\n BOOST_CHECK_EQUAL(device->neutralConfiguration().size(),device->configSize());\n Eigen::VectorXd expected(device->configSize());\n \/\/ values fond in the srdf file, if the file change this test need to be updated :\n expected << 0,0,0,0,0,0,1,0,0,-0.3490658,0.6981317,-0.3490658,0,0,0,-0.3490658,0.6981317,-0.3490658,0,0,1.5,0.6,-0.5,-1.05,-0.4,-0.3,-0.2,0,0,0,0,1.5,-0.6,0.5,1.05,-0.4,-0.3,-0.2;\n if(verbose)\n std::cout<<\"neutral configuration after loading romeo : \"<<displayConfig(device->neutralConfiguration())<<std::endl;\n BOOST_CHECK_MESSAGE(device->neutralConfiguration().isApprox(expected, 1e-12), \"neutral configuration - wrong results\");\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/\/version : 1.1\r\n\/\/02.01.2013\r\n\r\n#include \"dialogPreferences.hpp\"\r\n#include \"dialogShortcutPreferences.hpp\"\r\n#include \"shortcut.hpp\"\r\n\r\n#include <wx\/msgdlg.h>\r\n#include <wx\/menu.h>\r\n\r\n\/\/TEST\r\n#include <iostream>\r\n\r\n\/\/! ****************************************************************************\r\n\/\/! Class DialogPreferences\r\n\/\/! ****************************************************************************\r\n\r\nDialogPreferences::DialogPreferences(ActionManager *actionManager)\r\n: GuiDialogPreferences(nullptr), _actionManager(actionManager)\r\n{\t\r\n \/\/Magnifier \r\n _staticTextSetting->SetLabelMarkup(\"<b>\"+_(\"Setting\")+\"<\/b>\");\r\n\t_staticTextShutdown->SetLabelMarkup(\"<b>\"+_(\"Shutdown this application\")+\"<\/b>\");\r\n\t\r\n\t\/\/_listCtrlAction->EnableAlternateRowColours();\r\n\t_listCtrlAction->AppendColumn(_(\"Shortcut\"), wxLIST_FORMAT_LEFT, 100);\r\n\t_listCtrlAction->AppendColumn(_(\"Action\"), wxLIST_FORMAT_LEFT, 100);\r\n\t_listCtrlAction->AppendColumn(_(\"Preferences\"), wxLIST_FORMAT_LEFT, 170);\r\n\t\r\n\t\/\/Rempli la list.\r\n\tfor(auto it: *_actionManager->getAction())\r\n\t{\r\n\t\t_listCtrlAction->InsertItem(0, ShortcutKey::shortcutKeyToString(it.first));\r\n\t\t_listCtrlAction->SetItem(0, 1, it.second->getName());\r\n\t\t_listCtrlAction->SetItem(0, 2, it.second->getStringPreferences());\r\n\t}\r\n}\r\n\r\nDialogPreferences::~DialogPreferences()\r\n{\r\n}\r\n\r\nvoid DialogPreferences::OnButtonClickActDelete(wxCommandEvent&)\r\n{\r\n\twxMessageDialog *dlg = nullptr;\r\n\t\r\n\tif(_listItemSelected.size() > 1)\r\n\t\tdlg = new wxMessageDialog(this, _(\"Do you want really delete this actions ?\"), _(\"Delete actions\"), wxYES_NO|wxCENTRE);\r\n\telse\r\n\t\tdlg = new wxMessageDialog(this, _(\"Do you want really delete an action ?\"), _(\"Delete action\"), wxYES_NO|wxCENTRE);\r\n \r\n if(dlg->ShowModal() == wxID_OK )\r\n\t{\r\n\t}\r\n\t\r\n dlg->Destroy();\r\n}\r\n\r\nvoid DialogPreferences::OnButtonClickActPreferences(wxCommandEvent&)\r\n{\r\n\tstd::cout << \"OnButtonClickActPreferences\" << std::endl;\r\n}\r\n\r\nvoid DialogPreferences::OnButtonClickActAdd(wxCommandEvent&)\r\n{\r\n\tstd::cout << \"OnButtonClickActAdd\" << std::endl;\r\n\t\r\n\t\/\/DialogShortcutPreferences *dlg = new DialogShortcutPreferences(this);\r\n\t\/\/dlg->ShowModal();\r\n\t\/\/delete dlg;\r\n}\r\n\r\nvoid DialogPreferences::OnButtonClickOK(wxCommandEvent& event)\r\n{\t\r\n\tevent.Skip();\r\n}\r\n\r\nvoid DialogPreferences::OnButtonClickApply(wxCommandEvent& event)\r\n{\t\r\n\tevent.Skip();\r\n}\r\n\r\nvoid DialogPreferences::OnListItemDeselectedAction(wxListEvent& event)\r\n{\r\n\t\/\/Recherche et suppression de l'item désélectionner.\r\n\tfor(size_t i = 0; i<_listItemSelected.size(); i++)\r\n\t{\r\n\t\tif(_listItemSelected[i] == event.GetItem())\r\n\t\t{\r\n\t\t\t_listItemSelected.erase(_listItemSelected.begin()+i);\r\n\t\t\tbreak;\r\n\t\t}\r\n\t}\r\n\t\r\n\t\/\/Si rien n'est sélectionner on désactive les boutons delete.\r\n\tif(_listItemSelected.size() <= 0)\r\n\t{\r\n\t\t_buttonActDelete->Enable(false);\r\n\t\t_menuItemListDelete->Enable(false);\r\n\t}\r\n\t\t\r\n\t\/\/On désactive le bouton Préférence soft si il y a un seul item de sélectionner.\r\n\tif(_listItemSelected.size() != 1)\r\n\t{\r\n\t\t_buttonActPreferences->Enable(false);\r\n\t\t_menuItemListPreferences->Enable(false);\r\n\t}\r\n\telse\r\n\t{\r\n\t\t_buttonActPreferences->Enable();\r\n\t\t_menuItemListPreferences->Enable();\r\n\t}\r\n}\r\n\r\nvoid DialogPreferences::OnListItemSelectedAction(wxListEvent& event)\r\n{\r\n\t_listItemSelected.push_back(event.GetItem());\r\n\t\r\n\t\/\/activation du bouton delete\r\n\t_buttonActDelete->Enable();\r\n\t_menuItemListDelete->Enable();\r\n\t\r\n\t\/\/on active le bouton préférence seulement si il y a qu'un item de sélectionner.\r\n\tif(_listItemSelected.size() == 1)\r\n\t{\r\n\t\t_buttonActPreferences->Enable();\r\n\t\t_menuItemListPreferences->Enable();\r\n\t}\r\n\telse\r\n\t{\r\n\t\t_buttonActPreferences->Enable(false);\r\n\t\t_menuItemListPreferences->Enable(false);\r\n\t}\r\n}\r\n\r\nbool DialogPreferences::shutdownIsToggle()const\r\n{\r\n\treturn _toggleBtnTurnOff->GetValue();\r\n}\r\n\r\nbool DialogPreferences::showIcon()const\r\n{\r\n\treturn _checkBoxShowMenu->GetValue();\r\n}\r\n\t\t\r\n<commit_msg>change test<commit_after>\/\/version : 1.1\r\n\/\/02.01.2013\r\n\r\n#include \"dialogPreferences.hpp\"\r\n#include \"dialogShortcutPreferences.hpp\"\r\n#include \"shortcut.hpp\"\r\n\r\n#include <wx\/msgdlg.h>\r\n#include <wx\/menu.h>\r\n\r\n\/\/TEST\r\n#include <iostream>\r\n\r\n\/\/! ****************************************************************************\r\n\/\/! Class DialogPreferences\r\n\/\/! ****************************************************************************\r\n\r\nDialogPreferences::DialogPreferences(ActionManager *actionManager)\r\n: GuiDialogPreferences(nullptr), _actionManager(actionManager)\r\n{\t\r\n \/\/Magnifier \r\n _staticTextSetting->SetLabelMarkup(\"<b>\"+_(\"Setting\")+\"<\/b>\");\r\n\t_staticTextShutdown->SetLabelMarkup(\"<b>\"+_(\"Shutdown this application\")+\"<\/b>\");\r\n\t\r\n\t\/\/_listCtrlAction->EnableAlternateRowColours();\r\n\t_listCtrlAction->AppendColumn(_(\"Shortcut\"), wxLIST_FORMAT_LEFT, 100);\r\n\t_listCtrlAction->AppendColumn(_(\"Action\"), wxLIST_FORMAT_LEFT, 100);\r\n\t_listCtrlAction->AppendColumn(_(\"Preferences\"), wxLIST_FORMAT_LEFT, 170);\r\n\t\r\n\t\/\/Rempli la list.\r\n\tfor(auto it: *_actionManager->getAction())\r\n\t{\r\n\t\t_listCtrlAction->InsertItem(0, ShortcutKey::shortcutKeyToString(it.first));\r\n\t\t_listCtrlAction->SetItem(0, 1, it.second->getName());\r\n\t\t_listCtrlAction->SetItem(0, 2, it.second->getStringPreferences());\r\n\t}\r\n}\r\n\r\nDialogPreferences::~DialogPreferences()\r\n{\r\n}\r\n\r\nvoid DialogPreferences::OnButtonClickActDelete(wxCommandEvent&)\r\n{\r\n\twxMessageDialog *dlg = nullptr;\r\n\t\r\n\tif(_listItemSelected.size() > 1)\r\n\t\tdlg = new wxMessageDialog(this, _(\"Do you want really delete this actions ?\"), _(\"Delete actions\"), wxYES_NO|wxCENTRE);\r\n\telse\r\n\t\tdlg = new wxMessageDialog(this, _(\"Do you want really delete this action ?\"), _(\"Delete action\"), wxYES_NO|wxCENTRE);\r\n \r\n if(dlg->ShowModal() == wxID_OK )\r\n\t{\r\n\t}\r\n\t\r\n dlg->Destroy();\r\n}\r\n\r\nvoid DialogPreferences::OnButtonClickActPreferences(wxCommandEvent&)\r\n{\r\n\tstd::cout << \"OnButtonClickActPreferences\" << std::endl;\r\n}\r\n\r\nvoid DialogPreferences::OnButtonClickActAdd(wxCommandEvent&)\r\n{\r\n\tstd::cout << \"OnButtonClickActAdd\" << std::endl;\r\n\t\r\n\t\/\/DialogShortcutPreferences *dlg = new DialogShortcutPreferences(this);\r\n\t\/\/dlg->ShowModal();\r\n\t\/\/delete dlg;\r\n}\r\n\r\nvoid DialogPreferences::OnButtonClickOK(wxCommandEvent& event)\r\n{\t\r\n\tevent.Skip();\r\n}\r\n\r\nvoid DialogPreferences::OnButtonClickApply(wxCommandEvent& event)\r\n{\t\r\n\tevent.Skip();\r\n}\r\n\r\nvoid DialogPreferences::OnListItemDeselectedAction(wxListEvent& event)\r\n{\r\n\t\/\/Recherche et suppression de l'item désélectionner.\r\n\tfor(size_t i = 0; i<_listItemSelected.size(); i++)\r\n\t{\r\n\t\tif(_listItemSelected[i] == event.GetItem())\r\n\t\t{\r\n\t\t\t_listItemSelected.erase(_listItemSelected.begin()+i);\r\n\t\t\tbreak;\r\n\t\t}\r\n\t}\r\n\t\r\n\t\/\/Si rien n'est sélectionner on désactive les boutons delete.\r\n\tif(_listItemSelected.size() <= 0)\r\n\t{\r\n\t\t_buttonActDelete->Enable(false);\r\n\t\t_menuItemListDelete->Enable(false);\r\n\t}\r\n\t\t\r\n\t\/\/On désactive le bouton Préférence soft si il y a un seul item de sélectionner.\r\n\tif(_listItemSelected.size() != 1)\r\n\t{\r\n\t\t_buttonActPreferences->Enable(false);\r\n\t\t_menuItemListPreferences->Enable(false);\r\n\t}\r\n\telse\r\n\t{\r\n\t\t_buttonActPreferences->Enable();\r\n\t\t_menuItemListPreferences->Enable();\r\n\t}\r\n}\r\n\r\nvoid DialogPreferences::OnListItemSelectedAction(wxListEvent& event)\r\n{\r\n\t_listItemSelected.push_back(event.GetItem());\r\n\t\r\n\t\/\/activation du bouton delete\r\n\t_buttonActDelete->Enable();\r\n\t_menuItemListDelete->Enable();\r\n\t\r\n\t\/\/on active le bouton préférence seulement si il y a qu'un item de sélectionner.\r\n\tif(_listItemSelected.size() == 1)\r\n\t{\r\n\t\t_buttonActPreferences->Enable();\r\n\t\t_menuItemListPreferences->Enable();\r\n\t}\r\n\telse\r\n\t{\r\n\t\t_buttonActPreferences->Enable(false);\r\n\t\t_menuItemListPreferences->Enable(false);\r\n\t}\r\n}\r\n\r\nbool DialogPreferences::shutdownIsToggle()const\r\n{\r\n\treturn _toggleBtnTurnOff->GetValue();\r\n}\r\n\r\nbool DialogPreferences::showIcon()const\r\n{\r\n\treturn _checkBoxShowMenu->GetValue();\r\n}\r\n\t\t\r\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: numberingtypelistbox.hxx,v $\n *\n * $Revision: 1.2 $\n *\n * last change: $Author: rt $ $Date: 2004-08-23 09:00:32 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n#ifndef _NUMBERINGTYPELISTBOX_HXX\n#define _NUMBERINGTYPELISTBOX_HXX\n\n#ifndef _SV_LSTBOX_HXX \/\/autogen\n#include <vcl\/lstbox.hxx>\n#endif\n\n#ifndef INCLUDED_SWDLLAPI_H\n#include \"swdllapi.h\"\n#endif\n\n#define INSERT_NUM_TYPE_NO_NUMBERING 0x01\n#define INSERT_NUM_TYPE_PAGE_STYLE_NUMBERING 0x02\n#define INSERT_NUM_TYPE_BITMAP 0x04\n#define INSERT_NUM_TYPE_BULLET 0x08\n#define INSERT_NUM_EXTENDED_TYPES 0x10\n\nstruct SwNumberingTypeListBox_Impl;\n\nclass SW_DLLPUBLIC SwNumberingTypeListBox : public ListBox\n{\n SwNumberingTypeListBox_Impl* pImpl;\n\npublic:\n SwNumberingTypeListBox( Window* pWin, const ResId& rResId,\n USHORT nTypeFlags = INSERT_NUM_TYPE_PAGE_STYLE_NUMBERING|INSERT_NUM_TYPE_NO_NUMBERING|INSERT_NUM_EXTENDED_TYPES );\n ~SwNumberingTypeListBox();\n\n void Reload(USHORT nTypeFlags);\n\n sal_Int16 GetSelectedNumberingType();\n sal_Bool SelectNumberingType(sal_Int16 nType);\n};\n\n\n#endif\n\n<commit_msg>INTEGRATION: CWS ooo19126 (1.2.596); FILE MERGED 2005\/09\/05 13:45:28 rt 1.2.596.1: #i54170# Change license header: remove SISSL<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: numberingtypelistbox.hxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: rt $ $Date: 2005-09-09 09:52:52 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n#ifndef _NUMBERINGTYPELISTBOX_HXX\n#define _NUMBERINGTYPELISTBOX_HXX\n\n#ifndef _SV_LSTBOX_HXX \/\/autogen\n#include <vcl\/lstbox.hxx>\n#endif\n\n#ifndef INCLUDED_SWDLLAPI_H\n#include \"swdllapi.h\"\n#endif\n\n#define INSERT_NUM_TYPE_NO_NUMBERING 0x01\n#define INSERT_NUM_TYPE_PAGE_STYLE_NUMBERING 0x02\n#define INSERT_NUM_TYPE_BITMAP 0x04\n#define INSERT_NUM_TYPE_BULLET 0x08\n#define INSERT_NUM_EXTENDED_TYPES 0x10\n\nstruct SwNumberingTypeListBox_Impl;\n\nclass SW_DLLPUBLIC SwNumberingTypeListBox : public ListBox\n{\n SwNumberingTypeListBox_Impl* pImpl;\n\npublic:\n SwNumberingTypeListBox( Window* pWin, const ResId& rResId,\n USHORT nTypeFlags = INSERT_NUM_TYPE_PAGE_STYLE_NUMBERING|INSERT_NUM_TYPE_NO_NUMBERING|INSERT_NUM_EXTENDED_TYPES );\n ~SwNumberingTypeListBox();\n\n void Reload(USHORT nTypeFlags);\n\n sal_Int16 GetSelectedNumberingType();\n sal_Bool SelectNumberingType(sal_Int16 nType);\n};\n\n\n#endif\n\n<|endoftext|>"} {"text":"<commit_before>#include \"Database.h\"\n\n#include <iostream>\n#include <fstream>\n#include <string>\n#include <sqlite3.h>\n\n#include \"Table.h\"\n#include \"CycException.h\"\n#include \"Logger.h\"\n\nusing namespace std;\n\n\/\/ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \nDatabase::Database(std::string filename){\n database_ = NULL;\n exists_ = true;\n isOpen_ = false;\n name_ = filename;\n}\n\n\/\/ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \nDatabase::Database(std::string filename, std::string file_path){\n database_ = NULL;\n exists_ = true;\n isOpen_ = false;\n name_ = filename;\n path_ = file_path;\n}\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\nbool Database::fexists(const char *filename) {\n ifstream ifile(filename);\n return ifile;\n}\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\nstring Database::path() {\n string full_path = \"\";\n if ( !path_.empty() ) {\n full_path += path_ + \"\/\";\n }\n return full_path;\n}\n\n\/\/ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \nbool Database::open() {\n if ( dbExists() ) {\n string path_to_file = path() + name_;\n if(sqlite3_open(path_to_file.c_str(), &database_) == SQLITE_OK) {\n isOpen_ = true;\n return true;\n }\n else {\n throw CycIOException(\"Unable to open database \" + path_to_file); \n }\n } \/\/ end if ( dbExists() )\n else {\n throw CycIOException(\"Trying to open a non-existant Database\"); \n }\n return false;\n}\n\n\/\/ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \nbool Database::close() {\n if ( isOpen() ) {\n if (sqlite3_close(database_) == SQLITE_OK) {\n isOpen_ = false;\n return true;\n }\n else {\n throw CycIOException(\"Error closing existing database: \" + name_);\n return false;\n }\n } \/\/ endif ( isOpen() )\n else {\n throw CycIOException(\"Trying to close an already-closed database: \" + name_);\n return false;\n }\n}\n\n\/\/ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \nbool Database::isOpen() {\n string err;\n if ( dbExists() )\n return isOpen_;\n else {\n err = \"Database \" + name_ + \" is not open because it does not exist.\";\n throw CycIOException(err);\n }\n return false;\n}\n\n\/\/ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \nbool Database::dbExists() {\n if (this != NULL) {\n return true;\n }\n else {\n return false;\n }\n}\n\n\/\/ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \nvoid Database::registerTable(table_ptr t) {\n if ( dbExists() ) {\n tables_.push_back(t);\n }\n}\n\n\/\/ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \nvoid Database::removeTable(table_ptr t) {\n if ( dbExists() ) {\n tables_.erase(find(tables_.begin(), tables_.end(), t));\n }\n}\n\n\/\/ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \nvoid Database::createTable(table_ptr t){\n if ( isOpen() ) {\n bool tExists = tableExists(t);\n if (tExists) {\n \/\/ declare members\n string query = t->create();\n this->issueCommand(query);\n }\n }\n}\n\n\/\/ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \nbool Database::tableExists(table_ptr t) {\n \/\/ make sure the table exists before it is accessed\n bool isPresent = false;\n string err;\n \n \/\/ case: the database is not null\n if ( dbExists() ) {\n \/\/ case: the table pointer is null\n if ( t == NULL ) \n err = \"Database \" + this->name() \n\t+ \" was asked to interact with a non-existant table.\";\n \/\/ case: the table pointer is NOT null but the table is not created\n else if ( !t->defined() )\n err = \"Database \" + this->name() \n\t+ \" was asked to interact with a existant, but non-defined table.\";\n \/\/ case: table is defined, search for it\n else {\n isPresent = \n\t(find(tables_.begin(), tables_.end(), t) != tables_.end());\n if (!isPresent)\n\terr = \"Table: \" + t->name() \n\t + \" is not registered with Database \" + this->name() + \".\";\n }\n }\n \/\/ case: the database is null\n else\n err = \"An attempt was made to interact with a non existant Database.\";\n\n \/\/ found, return true\n if(isPresent)\n return true;\n else {\n \/\/ not found, throw an error and return false\n throw CycIOException(err);\n return false;\n }\n}\n\n\/\/ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \nvoid Database::issueCommand(std::string cmd){ \n if ( isOpen() ) {\n sqlite3_stmt *statement;\n \/\/ query the database\n int check_query = \n sqlite3_prepare_v2(database_, cmd.c_str(), -1, &statement, 0);\n if(check_query == SQLITE_OK) {\n int result = sqlite3_step(statement);\n sqlite3_finalize(statement);\n }\n \/\/ collect errors\n string error = sqlite3_errmsg(database_);\n if(error != \"not an error\") \n throw CycIOException(\"SQL error: \" + cmd + \" \" + error);\n }\n else\n throw CycIOException(\"Tried to issue command to closed table: \" + name_);\n}\n\n\/\/ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \nvoid Database::writeRows(table_ptr t){\n if ( isOpen() ) {\n bool exists = tableExists(t);\n if (exists) {\n \/\/ write each row in the Table's row commands\n int nRows = t->nRows();\n for (int i = 0; i < nRows; i++){\n\tstring cmd_str = t->row_command(i)->str();\n\tthis->issueCommand(cmd_str);\n\tLOG(LEV_DEBUG4,\"db\") << \"Issued writeRows command to table: \" \n\t\t\t << t->name() << \" with the command being \" \n\t\t\t << cmd_str;\n }\n }\n }\n}\n\n\/\/ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \nvoid Database::flush(table_ptr t){\n if ( isOpen() ) {\n bool exists = tableExists(t);\n if (exists) {\n t->flush();\n }\n }\n}\n\n\/\/ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \nquery_result Database::query(std::string query){\n \/\/ declare members\n sqlite3_stmt *statement;\n query_result results;\n \n if ( isOpen() ) {\n \/\/ query the database\n int check_query = \n sqlite3_prepare_v2(database_, query.c_str(), -1, &statement, 0);\n if(check_query == SQLITE_OK){\n int cols = sqlite3_column_count(statement);\n int result = 0;\n while(true){\n\tresult = sqlite3_step(statement);\n\t\/\/ access the rows\n\tif(result == SQLITE_ROW){\n\t query_row values;\n\t for(int col = 0; col < cols; col++){\n\t string val;\n\t char * ptr = (char*)sqlite3_column_text(statement, col);\n\t if(ptr)\n\t val = ptr;\n\t else \n\t val = \"\";\n\t values.push_back(val); \/\/ now we will never push NULL\n\t }\n\t results.push_back(values);\n\t}\n\telse\n\t break; \n } \n sqlite3_finalize(statement);\n }\n \/\/ collect errors\n string error = sqlite3_errmsg(database_);\n if(error != \"not an error\") \n throw CycIOException(\"SQL error: \" + query + \" \" + error);\n }\n else\n throw CycIOException(\"Attempted to query the closed database: \" + name_);\n return results; \n}\n<commit_msg>added proper indentation to code (formatting change only)<commit_after>#include \"Database.h\"\n\n#include <iostream>\n#include <fstream>\n#include <string>\n#include <sqlite3.h>\n\n#include \"Table.h\"\n#include \"CycException.h\"\n#include \"Logger.h\"\n\nusing namespace std;\n\n\/\/ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \nDatabase::Database(std::string filename){\n database_ = NULL;\n exists_ = true;\n isOpen_ = false;\n name_ = filename;\n}\n\n\/\/ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \nDatabase::Database(std::string filename, std::string file_path){\n database_ = NULL;\n exists_ = true;\n isOpen_ = false;\n name_ = filename;\n path_ = file_path;\n}\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\nbool Database::fexists(const char *filename) {\n ifstream ifile(filename);\n return ifile;\n}\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\nstring Database::path() {\n string full_path = \"\";\n if ( !path_.empty() ) {\n full_path += path_ + \"\/\";\n }\n return full_path;\n}\n\n\/\/ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \nbool Database::open() {\n if ( dbExists() ) {\n string path_to_file = path() + name_;\n if(sqlite3_open(path_to_file.c_str(), &database_) == SQLITE_OK) {\n isOpen_ = true;\n return true;\n }\n else {\n throw CycIOException(\"Unable to open database \" + path_to_file); \n }\n } \/\/ end if ( dbExists() )\n else {\n throw CycIOException(\"Trying to open a non-existant Database\"); \n }\n return false;\n}\n\n\/\/ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \nbool Database::close() {\n if ( isOpen() ) {\n if (sqlite3_close(database_) == SQLITE_OK) {\n isOpen_ = false;\n return true;\n }\n else {\n throw CycIOException(\"Error closing existing database: \" + name_);\n return false;\n }\n } \/\/ endif ( isOpen() )\n else {\n throw CycIOException(\"Trying to close an already-closed database: \" + name_);\n return false;\n }\n}\n\n\/\/ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \nbool Database::isOpen() {\n string err;\n if ( dbExists() )\n return isOpen_;\n else {\n err = \"Database \" + name_ + \" is not open because it does not exist.\";\n throw CycIOException(err);\n }\n return false;\n}\n\n\/\/ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \nbool Database::dbExists() {\n if (this != NULL) {\n return true;\n }\n else {\n return false;\n }\n}\n\n\/\/ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \nvoid Database::registerTable(table_ptr t) {\n if ( dbExists() ) {\n tables_.push_back(t);\n }\n}\n\n\/\/ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \nvoid Database::removeTable(table_ptr t) {\n if ( dbExists() ) {\n tables_.erase(find(tables_.begin(), tables_.end(), t));\n }\n}\n\n\/\/ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \nvoid Database::createTable(table_ptr t){\n if ( isOpen() ) {\n bool tExists = tableExists(t);\n if (tExists) {\n \/\/ declare members\n string query = t->create();\n this->issueCommand(query);\n }\n }\n}\n\n\/\/ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \nbool Database::tableExists(table_ptr t) {\n \/\/ make sure the table exists before it is accessed\n bool isPresent = false;\n string err;\n \n \/\/ case: the database is not null\n if ( dbExists() ) {\n \/\/ case: the table pointer is null\n if ( t == NULL ) \n err = \"Database \" + this->name() \n\t+ \" was asked to interact with a non-existant table.\";\n \/\/ case: the table pointer is NOT null but the table is not created\n else if ( !t->defined() )\n err = \"Database \" + this->name() \n\t+ \" was asked to interact with a existant, but non-defined table.\";\n \/\/ case: table is defined, search for it\n else {\n isPresent = \n\t(find(tables_.begin(), tables_.end(), t) != tables_.end());\n if (!isPresent)\n\terr = \"Table: \" + t->name() \n\t + \" is not registered with Database \" + this->name() + \".\";\n }\n }\n \/\/ case: the database is null\n else\n err = \"An attempt was made to interact with a non existant Database.\";\n\n \/\/ found, return true\n if(isPresent)\n return true;\n else {\n \/\/ not found, throw an error and return false\n throw CycIOException(err);\n return false;\n }\n}\n\n\/\/ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \nvoid Database::issueCommand(std::string cmd){ \n if ( isOpen() ) {\n sqlite3_stmt *statement;\n \/\/ query the database\n int check_query = \n sqlite3_prepare_v2(database_, cmd.c_str(), -1, &statement, 0);\n if(check_query == SQLITE_OK) {\n int result = sqlite3_step(statement);\n sqlite3_finalize(statement);\n }\n \/\/ collect errors\n string error = sqlite3_errmsg(database_);\n if(error != \"not an error\") \n throw CycIOException(\"SQL error: \" + cmd + \" \" + error);\n }\n else\n throw CycIOException(\"Tried to issue command to closed table: \" + name_);\n}\n\n\/\/ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \nvoid Database::writeRows(table_ptr t){\n if ( isOpen() ) {\n bool exists = tableExists(t);\n if (exists) {\n \/\/ write each row in the Table's row commands\n int nRows = t->nRows();\n for (int i = 0; i < nRows; i++){\n\tstring cmd_str = t->row_command(i)->str();\n\tthis->issueCommand(cmd_str);\n\tLOG(LEV_DEBUG4,\"db\") << \"Issued writeRows command to table: \" \n\t\t\t << t->name() << \" with the command being \" \n\t\t\t << cmd_str;\n }\n }\n }\n}\n\n\/\/ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \nvoid Database::flush(table_ptr t){\n if ( isOpen() ) {\n bool exists = tableExists(t);\n if (exists) {\n t->flush();\n }\n }\n}\n\n\/\/ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \nquery_result Database::query(std::string query){\n \/\/ declare members\n sqlite3_stmt *statement;\n query_result results;\n \n if ( isOpen() ) {\n \/\/ query the database\n int check_query = \n sqlite3_prepare_v2(database_, query.c_str(), -1, &statement, 0);\n if(check_query == SQLITE_OK){\n int cols = sqlite3_column_count(statement);\n int result = 0;\n while(true){\n result = sqlite3_step(statement);\n \/\/ access the rows\n if(result == SQLITE_ROW){\n query_row values;\n for(int col = 0; col < cols; col++){\n string val;\n char * ptr = (char*)sqlite3_column_text(statement, col);\n if(ptr)\n val = ptr;\n else \n val = \"\";\n values.push_back(val); \/\/ now we will never push NULL\n }\n results.push_back(values);\n }\n else\n break; \n } \n sqlite3_finalize(statement);\n }\n \/\/ collect errors\n string error = sqlite3_errmsg(database_);\n if(error != \"not an error\") \n throw CycIOException(\"SQL error: \" + query + \" \" + error);\n }\n else\n throw CycIOException(\"Attempted to query the closed database: \" + name_);\n return results; \n}\n<|endoftext|>"} {"text":"<commit_before>\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.\n\/\/ See https:\/\/llvm.org\/LICENSE.txt for license information.\n\/\/ SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ UNSUPPORTED: c++03, c++11, c++14, c++17\n\n\/\/ <vector>\n\n\/\/ template <class T, class Allocator, class Predicate>\n\/\/ typename vector<T, Allocator>::size_type\n\/\/ erase_if(vector<T, Allocator>& c, Predicate pred);\n\n\/\/#include <vector>\n\n\/\/#include \"test_macros.h\"\n\/\/#include \"test_allocator.h\"\n\/\/#include \"min_allocator.h\"\n\ntemplate <class S, class Pred>\nvoid test0(S s, Pred p, S expected, size_t expected_erased_count) {\n ASSERT_SAME_TYPE(typename S::size_type, decltype(erase_if(s, p)));\n assert(expected_erased_count == erase_if(s, p));\n assert(s == expected);\n}\n\ntemplate <typename S>\nvoid test()\n{\n auto is1 = [](auto v) { return v == 1;};\n auto is2 = [](auto v) { return v == 2;};\n auto is3 = [](auto v) { return v == 3;};\n auto is4 = [](auto v) { return v == 4;};\n auto True = [](auto) { return true; };\n auto False = [](auto) { return false; };\n\n test0(S(), is1, S(), 0);\n\n test0(S({1}), is1, S(), 1);\n test0(S({1}), is2, S({1}), 0);\n\n test0(S({1, 2}), is1, S({2}), 1);\n test0(S({1, 2}), is2, S({1}), 1);\n test0(S({1, 2}), is3, S({1, 2}), 0);\n test0(S({1, 1}), is1, S(), 2);\n test0(S({1, 1}), is3, S({1, 1}), 0);\n\n test0(S({1, 2, 3}), is1, S({2, 3}), 1);\n test0(S({1, 2, 3}), is2, S({1, 3}), 1);\n test0(S({1, 2, 3}), is3, S({1, 2}), 1);\n test0(S({1, 2, 3}), is4, S({1, 2, 3}), 0);\n\n test0(S({1, 1, 1}), is1, S(), 3);\n test0(S({1, 1, 1}), is2, S({1, 1, 1}), 0);\n test0(S({1, 1, 2}), is1, S({2}), 2);\n test0(S({1, 1, 2}), is2, S({1, 1}), 1);\n test0(S({1, 1, 2}), is3, S({1, 1, 2}), 0);\n test0(S({1, 2, 2}), is1, S({2, 2}), 1);\n test0(S({1, 2, 2}), is2, S({1}), 2);\n test0(S({1, 2, 2}), is3, S({1, 2, 2}), 0);\n\n test0(S({1, 2, 3}), True, S(), 3);\n test0(S({1, 2, 3}), False, S({1, 2, 3}), 0);\n}\n\nvoid main()\n{\n test<vector<int>>();\n#ifdef LIBCPP_TEST_MIN_ALLOCATOR\n test<vector<int, min_allocator<int>>> ();\n#endif\n test<vector<int, test_allocator<int>>> ();\n\n test<vector<long>>();\n test<vector<double>>();\n}\n<commit_msg>Consistent container erasure<commit_after>\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.\n\/\/ See https:\/\/llvm.org\/LICENSE.txt for license information.\n\/\/ SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ UNSUPPORTED: c++03, c++11, c++14, c++17\n\n\/\/ <vector>\n\n\/\/ template <class T, class Allocator, class Predicate>\n\/\/ typename vector<T, Allocator>::size_type\n\/\/ erase_if(vector<T, Allocator>& c, Predicate pred);\n\n\/\/#include <vector>\n\n\/\/#include \"test_macros.h\"\n\/\/#include \"test_allocator.h\"\n\/\/#include \"min_allocator.h\"\n\ntemplate <class S, class Pred>\nvoid test0(S s, Pred p, S expected, size_t expected_erased_count) {\n ASSERT_SAME_TYPE(typename S::size_type, decltype(erase_if(s, p)));\n assert(expected_erased_count == erase_if(s, p));\n assert(s == expected);\n}\n\ntemplate <typename S>\nvoid test()\n{\n using V = typename S::value_type;\n auto is1 = [](V v) { return v == 1;};\n auto is2 = [](V v) { return v == 2;};\n auto is3 = [](V v) { return v == 3;};\n auto is4 = [](V v) { return v == 4;};\n auto True = [](V) { return true; };\n auto False = [](V) { return false; };\n\n test0(S(), is1, S(), 0);\n\n test0(S({1}), is1, S(), 1);\n test0(S({1}), is2, S({1}), 0);\n\n test0(S({1, 2}), is1, S({2}), 1);\n test0(S({1, 2}), is2, S({1}), 1);\n test0(S({1, 2}), is3, S({1, 2}), 0);\n test0(S({1, 1}), is1, S(), 2);\n test0(S({1, 1}), is3, S({1, 1}), 0);\n\n test0(S({1, 2, 3}), is1, S({2, 3}), 1);\n test0(S({1, 2, 3}), is2, S({1, 3}), 1);\n test0(S({1, 2, 3}), is3, S({1, 2}), 1);\n test0(S({1, 2, 3}), is4, S({1, 2, 3}), 0);\n\n test0(S({1, 1, 1}), is1, S(), 3);\n test0(S({1, 1, 1}), is2, S({1, 1, 1}), 0);\n test0(S({1, 1, 2}), is1, S({2}), 2);\n test0(S({1, 1, 2}), is2, S({1, 1}), 1);\n test0(S({1, 1, 2}), is3, S({1, 1, 2}), 0);\n test0(S({1, 2, 2}), is1, S({2, 2}), 1);\n test0(S({1, 2, 2}), is2, S({1}), 2);\n test0(S({1, 2, 2}), is3, S({1, 2, 2}), 0);\n\n test0(S({1, 2, 3}), True, S(), 3);\n test0(S({1, 2, 3}), False, S({1, 2, 3}), 0);\n}\n\nvoid main()\n{\n test<vector<int>>();\n#ifdef LIBCPP_TEST_MIN_ALLOCATOR\n test<vector<int, min_allocator<int>>> ();\n#endif\n test<vector<int, test_allocator<int>>> ();\n\n test<vector<long>>();\n test<vector<double>>();\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"SelectSpritesOP.h\"\n\n#include \"common\/Rect.h\"\n#include \"dataset\/TextSprite.h\"\n#include \"dataset\/FontSprite.h\"\n#include \"dataset\/SymbolMgr.h\"\n#include \"dataset\/SpriteFactory.h\"\n#include \"component\/AbstractEditCMPT.h\"\n#include \"view\/PropertySettingPanel.h\"\n#include \"view\/SpritePropertySetting.h\"\n#include \"view\/MultiSpritesPropertySetting.h\"\n#include \"view\/TextPropertySetting.h\"\n#include \"view\/FontPropertySetting.h\"\n#include \"view\/MultiSpritesImpl.h\"\n#include \"view\/GLCanvas.h\"\n#include \"render\/DrawSelectedSpriteVisitor.h\"\n#include \"render\/PrimitiveDraw.h\"\n#include \"render\/style_config.h\"\n\n#include <wx\/clipbrd.h>\n#include <sstream>\n\nnamespace d2d\n{\n\nSelectSpritesOP::SelectSpritesOP(EditPanel* editPanel, MultiSpritesImpl* spritesImpl, \n\t\t\t\t\t\t\t\t PropertySettingPanel* propertyPanel\/* = NULL*\/, AbstractEditCMPT* callback\/* = NULL*\/)\n\t: DrawRectangleOP(editPanel)\n\t, m_callback(callback)\n\t, m_spritesImpl(spritesImpl)\n\t, m_propertyPanel(propertyPanel)\n\t, m_bDraggable(true)\n{\n\tm_selection = spritesImpl->getSpriteSelection();\n\tm_selection->Retain();\n\n\tm_firstPos.setInvalid();\n}\n\nSelectSpritesOP::~SelectSpritesOP()\n{\n\tm_selection->Clear();\n\tm_selection->Release();\n}\n\nbool SelectSpritesOP::onKeyDown(int keyCode)\n{\n\tif (DrawRectangleOP::onKeyDown(keyCode)) return true;\n\n\tif (wxGetKeyState(WXK_CONTROL) && wxGetKeyState(WXK_CONTROL_X))\n\t{\n\t\tpasteToSelection();\n\t\tm_spritesImpl->removeSpriteSelection();\n\t\treturn true;\n\t}\n\telse if (wxGetKeyState(WXK_CONTROL) && (keyCode == 'c' || keyCode == 'C'))\n\t{\n\t\tpasteToSelection();\n\t\treturn true;\n\t}\n\telse if (wxGetKeyState(WXK_CONTROL) && wxGetKeyState(WXK_CONTROL_V))\n\t{\n\t\tcopyFromSelection();\n\t\treturn true;\n\t}\n\n\treturn false;\n}\n\nbool SelectSpritesOP::onMouseLeftDown(int x, int y)\n{\n \tm_bDraggable = true;\n\n\tVector pos = m_editPanel->transPosScreenToProject(x, y);\n\tISprite* selected = selectByPos(pos);\n\tif (selected && selected->editable)\n\t{\n\t\tif (wxGetKeyState(WXK_CONTROL))\n\t\t{\n\t\t\tif (m_selection->IsExist(selected))\n\t\t\t\tm_selection->Remove(selected);\n\t\t\telse\n\t\t\t{\n\t\t\t\tm_selection->Add(selected);\n\t\t\t\tif (m_propertyPanel)\n\t\t\t\t{\n\t\t\t\t\tif (m_selection->Size() == 1)\n\t\t\t\t\t\tm_propertyPanel->setPropertySetting(createPropertySetting(selected));\n\t\t\t\t\telse if (m_selection->Size() > 1)\n\t\t\t\t\t{\n\t\t\t\t\t\tstd::vector<ISprite*> sprites;\n\t\t\t\t\t\tm_selection->Traverse(FetchAllVisitor<ISprite>(sprites));\n\t\t\t\t\t\tm_propertyPanel->setPropertySetting(createPropertySetting(sprites));\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t\tm_propertyPanel->setPropertySetting(createPropertySetting(NULL));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif (!m_selection->IsExist(selected) && !wxGetKeyState(WXK_SPACE))\n\t\t\t{\n\t\t\t\tm_selection->Clear();\n\t\t\t\tm_selection->Add(selected);\n\t\t\t\tif (m_propertyPanel)\n\t\t\t\t\tm_propertyPanel->setPropertySetting(createPropertySetting(selected));\n\t\t\t}\n\t\t}\n\t\tm_firstPos.setInvalid();\n\n\t\tif (m_callback)\n\t\t\tm_callback->updateControlValue();\n\t}\n\telse\n\t{\n\t\tDrawRectangleOP::onMouseLeftDown(x, y);\n\t\tm_firstPos = pos;\n\t\tif (wxGetKeyState(WXK_CONTROL))\n\t\t\tm_bDraggable = false;\n\t\telse\n\t\t\tm_selection->Clear();\n\t\tm_editPanel->Refresh();\n\t}\n\n\treturn false;\n}\n\nbool SelectSpritesOP::onMouseLeftUp(int x, int y)\n{\n\tif (DrawRectangleOP::onMouseLeftUp(x, y)) return true;\n\n\tm_bDraggable = true;\n\n\tif (m_firstPos.isValid())\n\t{\n\t\tVector end = m_editPanel->transPosScreenToProject(x, y);\n\t\tRect rect(m_firstPos, end);\n\t\tstd::vector<ISprite*> sprites;\n\t\tm_spritesImpl->querySpritesByRect(rect, m_firstPos.x < end.x, sprites);\n\t\tif (wxGetKeyState(WXK_CONTROL))\n\t\t{\n\t\t\tfor (size_t i = 0, n = sprites.size(); i < n; ++i) \n\t\t\t{\n\t\t\t\td2d::ISprite* sprite = sprites[i];\n\t\t\t\tif (m_selection->IsExist(sprite)) {\n\t\t\t\t\tm_selection->Remove(sprites[i]);\n\t\t\t\t} else {\n\t\t\t\t\tm_selection->Add(sprites[i]);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tfor (size_t i = 0, n = sprites.size(); i < n; ++i) {\n\t\t\t\tm_selection->Add(sprites[i]);\n\t\t\t}\n\t\t}\n\n\t\tif (m_propertyPanel)\n\t\t{\n\t\t\tif (m_selection->Size() == 1)\n\t\t\t\tm_propertyPanel->setPropertySetting(createPropertySetting(sprites[0]));\n\t\t\telse if (m_selection->Size() > 1)\n\t\t\t\tm_propertyPanel->setPropertySetting(createPropertySetting(sprites));\n\t\t\telse\n\t\t\t\tm_propertyPanel->setPropertySetting(createPropertySetting(NULL));\n\t\t}\n\n\t\tm_firstPos.setInvalid();\n\n\t\tif (m_callback)\n\t\t\tm_callback->updateControlValue();\n\t}\n\n\/\/\tenableRightTap(m_selection->empty());\n\n\treturn false;\n}\n\nbool SelectSpritesOP::onMouseRightDown(int x, int y)\n{\n\tm_rightFirstScrPos.set(x, y);\n\n\tenableRightTap(m_selection->IsEmpty());\n\n\tif (DrawRectangleOP::onMouseRightDown(x, y)) return true;\n\n\treturn false;\n}\n\nbool SelectSpritesOP::onMouseRightUp(int x, int y)\n{\n\t\/\/ select\n\tif (m_rightFirstScrPos == Vector(x, y))\n\t{\n\t\tVector pos = m_editPanel->transPosScreenToProject(x, y);\n\t\td2d::ISprite* sprite = m_spritesImpl->querySpriteByPos(pos);\n\t\tif (sprite)\n\t\t{\n\t\t\tm_selection->Clear();\n\t\t\tm_selection->Add(sprite);\n\t\t\tenableRightTap(m_selection->IsEmpty());\n\t\t\tm_editPanel->Refresh();\n\t\t}\n\t}\n\n\tif (DrawRectangleOP::onMouseRightUp(x, y)) return true;\n\n\treturn false;\n}\n\nbool SelectSpritesOP::onMouseDrag(int x, int y)\n{\n\tif (DrawRectangleOP::onMouseDrag(x, y)) return true;\n\n\treturn !m_bDraggable;\n}\n\nbool SelectSpritesOP::onDraw() const\n{\n\tm_selection->Traverse(DrawSelectedSpriteVisitor(Colorf(1, 0, 0)));\n\n\tif (m_firstPos.isValid() && m_currPos.isValid())\n\t{\n\t\tif (m_currPos.x > m_firstPos.x)\n\t\t{\n\t\t\tPrimitiveDraw::rect(m_firstPos, m_currPos, SELECT_ALL);\n\t\t\tPrimitiveDraw::rect(m_firstPos, m_currPos, SELECT_BOUND);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tPrimitiveDraw::rect(m_firstPos, m_currPos, SELECT_PART);\n\t\t\tPrimitiveDraw::rect(m_firstPos, m_currPos, SELECT_BOUND);\n\t\t}\n\t}\n\n\/\/ \tif (DrawRectangleOP::onDraw()) return true;\n\n\treturn false;\n}\n\nbool SelectSpritesOP::clear()\n{\n\tif (DrawRectangleOP::clear()) return true;\n\n\tm_selection->Clear();\n\tm_firstPos.setInvalid();\n\n\treturn false;\n}\n\nIPropertySetting* SelectSpritesOP::createPropertySetting(ISprite* sprite) const\n{\n\tif (TextSprite* text = dynamic_cast<TextSprite*>(sprite))\n\t\treturn new TextPropertySetting(m_editPanel, text);\n\telse if (FontSprite* font = dynamic_cast<FontSprite*>(sprite))\n\t\treturn new FontPropertySetting(m_editPanel, font);\n\telse if (sprite)\n\t\treturn new SpritePropertySetting(m_editPanel, sprite);\n\telse \n\t\treturn NULL;\n}\n\nIPropertySetting* SelectSpritesOP::createPropertySetting(const std::vector<ISprite*>& sprites) const\n{\n\treturn new MultiSpritesPropertySetting(m_editPanel, sprites);\n}\n\nISprite* SelectSpritesOP::selectByPos(const Vector& pos) const\n{\n\tISprite* selected = NULL;\n\tstd::vector<ISprite*> sprites;\n\tm_spritesImpl->getSpriteSelection()->Traverse(FetchAllVisitor<ISprite>(sprites));\n\tfor (int i = 0, n = sprites.size(); i < n; ++i)\n\t{\n\t\tif (sprites[i]->isContain(pos)) {\n\t\t\tselected = sprites[i];\n\t\t\tbreak;\n\t\t}\n\t}\n\tif (!selected) {\n\t\tselected = m_spritesImpl->querySpriteByPos(pos);\n\t}\n\treturn selected;\n}\n\nvoid SelectSpritesOP::pasteToSelection() const\n{\n\tstd::vector<ISprite*> sprites;\n\tm_selection->Traverse(FetchAllVisitor<ISprite>(sprites));\n\tJson::Value value;\n\tfor (int i = 0, n = sprites.size(); i < n; ++i)\n\t{\n\t\tJson::Value& sval = value[\"sprite\"][i];\n\t\td2d::ISprite* s = sprites[i];\n\t\tif (wxTheClipboard->Open())\n\t\t{\n\t\t\tsval[\"filename\"] = s->getSymbol().getFilepath().ToStdString();\n\t\t\ts->store(sval);\n\t\t\tsval[\"name\"] = s->name;\n\t\t}\n\t}\n\tJson::StyledStreamWriter writer;\n\tstd::stringstream ss;\n\twriter.write(ss, value);\n\twxTheClipboard->SetData(new wxTextDataObject(ss.str()));\n\twxTheClipboard->Close();\n}\n\nvoid SelectSpritesOP::copyFromSelection()\n{\n\tif (wxTheClipboard->Open())\n\t{\n\t\tif (wxTheClipboard->IsSupported( wxDF_TEXT ))\n\t\t{\n\t\t\twxTextDataObject data;\n\t\t\twxTheClipboard->GetData( data );\n\n\t\t\tJson::Value value;\n\t\t\tJson::Reader reader;\n\t\t\tstd::string test = data.GetText().ToStdString();\n\t\t\treader.parse(data.GetText().ToStdString(), value);\n\n\t\t\tm_selection->Clear();\n\n\t\t\tint i = 0;\n\t\t\tJson::Value sval = value[\"sprite\"][i++];\n\t\t\twhile (!sval.isNull()) {\n\t\t\t\tstd::string filepath = sval[\"filename\"].asString();\n\t\t\t\tISymbol* symbol = SymbolMgr::Instance()->fetchSymbol(filepath);\n\t\t\t\t\/\/ for snapshoot\n\t\t\t\tsymbol->RefreshThumbnail(filepath);\n\t\t\t\tISprite* sprite = SpriteFactory::Instance()->create(symbol);\n\t\t\t\tsprite->name = sval[\"name\"].asString();\n\t\t\t\tsymbol->Release();\n\t\t\t\tsprite->load(sval);\n\t\t\t\tm_spritesImpl->insertSprite(sprite);\n\t\t\t\tm_selection->Add(sprite);\n\t\t\t\tm_propertyPanel->setPropertySetting(createPropertySetting(sprite));\n\n\t\t\t\tsval = value[\"sprite\"][i++];\n\t\t\t}\n\n\t\t\tm_editPanel->getCanvas()->resetViewport();\n\t\t}\n\t\twxTheClipboard->Close();\n\t}\n}\n\n} \/\/ d2d<commit_msg>[FIXED] 选择时没有过滤掉!editable的,IDataContainer不止被ISprite继承<commit_after>#include \"SelectSpritesOP.h\"\n\n#include \"common\/Rect.h\"\n#include \"dataset\/TextSprite.h\"\n#include \"dataset\/FontSprite.h\"\n#include \"dataset\/SymbolMgr.h\"\n#include \"dataset\/SpriteFactory.h\"\n#include \"component\/AbstractEditCMPT.h\"\n#include \"view\/PropertySettingPanel.h\"\n#include \"view\/SpritePropertySetting.h\"\n#include \"view\/MultiSpritesPropertySetting.h\"\n#include \"view\/TextPropertySetting.h\"\n#include \"view\/FontPropertySetting.h\"\n#include \"view\/MultiSpritesImpl.h\"\n#include \"view\/GLCanvas.h\"\n#include \"render\/DrawSelectedSpriteVisitor.h\"\n#include \"render\/PrimitiveDraw.h\"\n#include \"render\/style_config.h\"\n\n#include <wx\/clipbrd.h>\n#include <sstream>\n\nnamespace d2d\n{\n\nSelectSpritesOP::SelectSpritesOP(EditPanel* editPanel, MultiSpritesImpl* spritesImpl, \n\t\t\t\t\t\t\t\t PropertySettingPanel* propertyPanel\/* = NULL*\/, AbstractEditCMPT* callback\/* = NULL*\/)\n\t: DrawRectangleOP(editPanel)\n\t, m_callback(callback)\n\t, m_spritesImpl(spritesImpl)\n\t, m_propertyPanel(propertyPanel)\n\t, m_bDraggable(true)\n{\n\tm_selection = spritesImpl->getSpriteSelection();\n\tm_selection->Retain();\n\n\tm_firstPos.setInvalid();\n}\n\nSelectSpritesOP::~SelectSpritesOP()\n{\n\tm_selection->Clear();\n\tm_selection->Release();\n}\n\nbool SelectSpritesOP::onKeyDown(int keyCode)\n{\n\tif (DrawRectangleOP::onKeyDown(keyCode)) return true;\n\n\tif (wxGetKeyState(WXK_CONTROL) && wxGetKeyState(WXK_CONTROL_X))\n\t{\n\t\tpasteToSelection();\n\t\tm_spritesImpl->removeSpriteSelection();\n\t\treturn true;\n\t}\n\telse if (wxGetKeyState(WXK_CONTROL) && (keyCode == 'c' || keyCode == 'C'))\n\t{\n\t\tpasteToSelection();\n\t\treturn true;\n\t}\n\telse if (wxGetKeyState(WXK_CONTROL) && wxGetKeyState(WXK_CONTROL_V))\n\t{\n\t\tcopyFromSelection();\n\t\treturn true;\n\t}\n\n\treturn false;\n}\n\nbool SelectSpritesOP::onMouseLeftDown(int x, int y)\n{\n \tm_bDraggable = true;\n\n\tVector pos = m_editPanel->transPosScreenToProject(x, y);\n\tISprite* selected = selectByPos(pos);\n\tif (selected)\n\t{\n\t\tassert(selected->editable);\n\t\tif (wxGetKeyState(WXK_CONTROL))\n\t\t{\n\t\t\tif (m_selection->IsExist(selected))\n\t\t\t\tm_selection->Remove(selected);\n\t\t\telse\n\t\t\t{\n\t\t\t\tm_selection->Add(selected);\n\t\t\t\tif (m_propertyPanel)\n\t\t\t\t{\n\t\t\t\t\tif (m_selection->Size() == 1)\n\t\t\t\t\t\tm_propertyPanel->setPropertySetting(createPropertySetting(selected));\n\t\t\t\t\telse if (m_selection->Size() > 1)\n\t\t\t\t\t{\n\t\t\t\t\t\tstd::vector<ISprite*> sprites;\n\t\t\t\t\t\tm_selection->Traverse(FetchAllVisitor<ISprite>(sprites));\n\t\t\t\t\t\tm_propertyPanel->setPropertySetting(createPropertySetting(sprites));\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t\tm_propertyPanel->setPropertySetting(createPropertySetting(NULL));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif (!m_selection->IsExist(selected) && !wxGetKeyState(WXK_SPACE))\n\t\t\t{\n\t\t\t\tm_selection->Clear();\n\t\t\t\tm_selection->Add(selected);\n\t\t\t\tif (m_propertyPanel)\n\t\t\t\t\tm_propertyPanel->setPropertySetting(createPropertySetting(selected));\n\t\t\t}\n\t\t}\n\t\tm_firstPos.setInvalid();\n\n\t\tif (m_callback)\n\t\t\tm_callback->updateControlValue();\n\t}\n\telse\n\t{\n\t\tDrawRectangleOP::onMouseLeftDown(x, y);\n\t\tm_firstPos = pos;\n\t\tif (wxGetKeyState(WXK_CONTROL))\n\t\t\tm_bDraggable = false;\n\t\telse\n\t\t\tm_selection->Clear();\n\t\tm_editPanel->Refresh();\n\t}\n\n\treturn false;\n}\n\nbool SelectSpritesOP::onMouseLeftUp(int x, int y)\n{\n\tif (DrawRectangleOP::onMouseLeftUp(x, y)) return true;\n\n\tm_bDraggable = true;\n\n\tif (m_firstPos.isValid())\n\t{\n\t\tVector end = m_editPanel->transPosScreenToProject(x, y);\n\t\tRect rect(m_firstPos, end);\n\t\tstd::vector<ISprite*> sprites;\n\t\tm_spritesImpl->querySpritesByRect(rect, m_firstPos.x < end.x, sprites);\n\t\tif (wxGetKeyState(WXK_CONTROL))\n\t\t{\n\t\t\tfor (size_t i = 0, n = sprites.size(); i < n; ++i) \n\t\t\t{\n\t\t\t\td2d::ISprite* sprite = sprites[i];\n\t\t\t\tif (m_selection->IsExist(sprite)) {\n\t\t\t\t\tm_selection->Remove(sprites[i]);\n\t\t\t\t} else {\n\t\t\t\t\tm_selection->Add(sprites[i]);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tfor (size_t i = 0, n = sprites.size(); i < n; ++i) {\n\t\t\t\tm_selection->Add(sprites[i]);\n\t\t\t}\n\t\t}\n\n\t\tif (m_propertyPanel)\n\t\t{\n\t\t\tif (m_selection->Size() == 1)\n\t\t\t\tm_propertyPanel->setPropertySetting(createPropertySetting(sprites[0]));\n\t\t\telse if (m_selection->Size() > 1)\n\t\t\t\tm_propertyPanel->setPropertySetting(createPropertySetting(sprites));\n\t\t\telse\n\t\t\t\tm_propertyPanel->setPropertySetting(createPropertySetting(NULL));\n\t\t}\n\n\t\tm_firstPos.setInvalid();\n\n\t\tif (m_callback)\n\t\t\tm_callback->updateControlValue();\n\t}\n\n\/\/\tenableRightTap(m_selection->empty());\n\n\treturn false;\n}\n\nbool SelectSpritesOP::onMouseRightDown(int x, int y)\n{\n\tm_rightFirstScrPos.set(x, y);\n\n\tenableRightTap(m_selection->IsEmpty());\n\n\tif (DrawRectangleOP::onMouseRightDown(x, y)) return true;\n\n\treturn false;\n}\n\nbool SelectSpritesOP::onMouseRightUp(int x, int y)\n{\n\t\/\/ select\n\tif (m_rightFirstScrPos == Vector(x, y))\n\t{\n\t\tVector pos = m_editPanel->transPosScreenToProject(x, y);\n\t\td2d::ISprite* sprite = m_spritesImpl->querySpriteByPos(pos);\n\t\tif (sprite)\n\t\t{\n\t\t\tm_selection->Clear();\n\t\t\tm_selection->Add(sprite);\n\t\t\tenableRightTap(m_selection->IsEmpty());\n\t\t\tm_editPanel->Refresh();\n\t\t}\n\t}\n\n\tif (DrawRectangleOP::onMouseRightUp(x, y)) return true;\n\n\treturn false;\n}\n\nbool SelectSpritesOP::onMouseDrag(int x, int y)\n{\n\tif (DrawRectangleOP::onMouseDrag(x, y)) return true;\n\n\treturn !m_bDraggable;\n}\n\nbool SelectSpritesOP::onDraw() const\n{\n\tm_selection->Traverse(DrawSelectedSpriteVisitor(Colorf(1, 0, 0)));\n\n\tif (m_firstPos.isValid() && m_currPos.isValid())\n\t{\n\t\tif (m_currPos.x > m_firstPos.x)\n\t\t{\n\t\t\tPrimitiveDraw::rect(m_firstPos, m_currPos, SELECT_ALL);\n\t\t\tPrimitiveDraw::rect(m_firstPos, m_currPos, SELECT_BOUND);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tPrimitiveDraw::rect(m_firstPos, m_currPos, SELECT_PART);\n\t\t\tPrimitiveDraw::rect(m_firstPos, m_currPos, SELECT_BOUND);\n\t\t}\n\t}\n\n\/\/ \tif (DrawRectangleOP::onDraw()) return true;\n\n\treturn false;\n}\n\nbool SelectSpritesOP::clear()\n{\n\tif (DrawRectangleOP::clear()) return true;\n\n\tm_selection->Clear();\n\tm_firstPos.setInvalid();\n\n\treturn false;\n}\n\nIPropertySetting* SelectSpritesOP::createPropertySetting(ISprite* sprite) const\n{\n\tif (TextSprite* text = dynamic_cast<TextSprite*>(sprite))\n\t\treturn new TextPropertySetting(m_editPanel, text);\n\telse if (FontSprite* font = dynamic_cast<FontSprite*>(sprite))\n\t\treturn new FontPropertySetting(m_editPanel, font);\n\telse if (sprite)\n\t\treturn new SpritePropertySetting(m_editPanel, sprite);\n\telse \n\t\treturn NULL;\n}\n\nIPropertySetting* SelectSpritesOP::createPropertySetting(const std::vector<ISprite*>& sprites) const\n{\n\treturn new MultiSpritesPropertySetting(m_editPanel, sprites);\n}\n\nISprite* SelectSpritesOP::selectByPos(const Vector& pos) const\n{\n\tISprite* selected = NULL;\n\tstd::vector<ISprite*> sprites;\n\tm_spritesImpl->getSpriteSelection()->Traverse(FetchAllVisitor<ISprite>(sprites));\n\tfor (int i = 0, n = sprites.size(); i < n; ++i)\n\t{\n\t\tif (sprites[i]->isContain(pos)) {\n\t\t\tselected = sprites[i];\n\t\t\tbreak;\n\t\t}\n\t}\n\tif (!selected) {\n\t\tISprite* spr = m_spritesImpl->querySpriteByPos(pos);\n\t\tif (!spr || !spr->editable) {\n\t\t\tstd::vector<ISprite*> sprites;\n\t\t\tm_spritesImpl->querySpritesByRect(Rect(pos, 1, 1), false, sprites);\n\t\t\tif (!sprites.empty()) {\n\t\t\t\tselected = sprites.back();\n\t\t\t}\n\t\t} else {\n\t\t\tselected = spr;\n\t\t}\n\t}\n\treturn selected;\n}\n\nvoid SelectSpritesOP::pasteToSelection() const\n{\n\tstd::vector<ISprite*> sprites;\n\tm_selection->Traverse(FetchAllVisitor<ISprite>(sprites));\n\tJson::Value value;\n\tfor (int i = 0, n = sprites.size(); i < n; ++i)\n\t{\n\t\tJson::Value& sval = value[\"sprite\"][i];\n\t\td2d::ISprite* s = sprites[i];\n\t\tif (wxTheClipboard->Open())\n\t\t{\n\t\t\tsval[\"filename\"] = s->getSymbol().getFilepath().ToStdString();\n\t\t\ts->store(sval);\n\t\t\tsval[\"name\"] = s->name;\n\t\t}\n\t}\n\tJson::StyledStreamWriter writer;\n\tstd::stringstream ss;\n\twriter.write(ss, value);\n\twxTheClipboard->SetData(new wxTextDataObject(ss.str()));\n\twxTheClipboard->Close();\n}\n\nvoid SelectSpritesOP::copyFromSelection()\n{\n\tif (wxTheClipboard->Open())\n\t{\n\t\tif (wxTheClipboard->IsSupported( wxDF_TEXT ))\n\t\t{\n\t\t\twxTextDataObject data;\n\t\t\twxTheClipboard->GetData( data );\n\n\t\t\tJson::Value value;\n\t\t\tJson::Reader reader;\n\t\t\tstd::string test = data.GetText().ToStdString();\n\t\t\treader.parse(data.GetText().ToStdString(), value);\n\n\t\t\tm_selection->Clear();\n\n\t\t\tint i = 0;\n\t\t\tJson::Value sval = value[\"sprite\"][i++];\n\t\t\twhile (!sval.isNull()) {\n\t\t\t\tstd::string filepath = sval[\"filename\"].asString();\n\t\t\t\tISymbol* symbol = SymbolMgr::Instance()->fetchSymbol(filepath);\n\t\t\t\t\/\/ for snapshoot\n\t\t\t\tsymbol->RefreshThumbnail(filepath);\n\t\t\t\tISprite* sprite = SpriteFactory::Instance()->create(symbol);\n\t\t\t\tsprite->name = sval[\"name\"].asString();\n\t\t\t\tsymbol->Release();\n\t\t\t\tsprite->load(sval);\n\t\t\t\tm_spritesImpl->insertSprite(sprite);\n\t\t\t\tm_selection->Add(sprite);\n\t\t\t\tm_propertyPanel->setPropertySetting(createPropertySetting(sprite));\n\n\t\t\t\tsval = value[\"sprite\"][i++];\n\t\t\t}\n\n\t\t\tm_editPanel->getCanvas()->resetViewport();\n\t\t}\n\t\twxTheClipboard->Close();\n\t}\n}\n\n} \/\/ d2d<|endoftext|>"} {"text":"<commit_before>#include \"FontPropertySetting.h\"\n#include \"PropertySettingPanel.h\"\n\n#include \"dataset\/FontSprite.h\"\n\n#include <wx\/propgrid\/advprops.h>\n\nnamespace d2d\n{\n\nconst wxChar* FontPropertySetting::HORI_ALIGN_LABELS[] = { \n\twxT(\"left\"), wxT(\"right\"), wxT(\"center\"), wxT(\"auto\"), NULL };\nconst wxChar* FontPropertySetting::VERT_ALIGN_LABELS[] = { \n\twxT(\"top\"), wxT(\"bottom\"), wxT(\"center\"), wxT(\"auto\"), NULL };\n\nFontPropertySetting::FontPropertySetting(EditPanel* editPanel, FontSprite* sprite)\n\t: SpritePropertySetting(editPanel, sprite)\n{\n\tm_type = wxT(\"Font\");\n}\n\nvoid FontPropertySetting::onPropertyGridChange(const wxString& name, const wxAny& value)\n{\n\tSpritePropertySetting::onPropertyGridChange(name, value);\n\n\tFontSprite* sprite = static_cast<FontSprite*>(m_sprite);\n\tif (name == wxT(\"Font\"))\n\t\tsprite->font = wxANY_AS(value, wxString);\n\telse if (name == wxT(\"Edge\")) {\n\t\tsprite->has_edge = wxANY_AS(value, bool);\n\t}\n\telse if (name == wxT(\"FontColor\")) {\n\t\twxColour col = wxANY_AS(value, wxColour);\n\t\tsprite->color.set(col.Red() \/ 255.0f, col.Green() \/ 255.0f, col.Blue() \/ 255.0f, col.Alpha() \/ 255.0f);\n\t}\n\telse if (name == wxT(\"AlignHori\")) \n\t\tsprite->align_hori = HoriAlignType(wxANY_AS(value, int));\n\telse if (name == wxT(\"AlignVert\"))\n\t\tsprite->align_vert = VertAlignType(wxANY_AS(value, int));\n\telse if (name == wxT(\"FontSize\"))\n\t\tsprite->size = wxANY_AS(value, float);\n\telse if (name == wxT(\"LabelWidth\")) {\n\t\tsprite->width = wxANY_AS(value, float);\n\t\tsprite->buildBounding();\n\t}\n\telse if (name == wxT(\"LabelHeight\")) {\n\t\tsprite->height = wxANY_AS(value, float);\n\t\tsprite->buildBounding();\n\t} else if (name == wxT(\"Filename\")) {\n\t\tstd::string str = wxANY_AS(value, wxString);\n\t\tsprite->loadFont(str);\n\t} else if (name == wxT(\"TextContent\")) {\n\t\tstd::string str = wxANY_AS(value, wxString);\n\t\tsprite->SetTextContent(str);\n\t}\n}\n\nvoid FontPropertySetting::enablePropertyGrid(PropertySettingPanel* panel, bool bEnable)\n{\n\tSpritePropertySetting::enablePropertyGrid(panel, bEnable);\n\n\twxPropertyGrid* pg = panel->getPG();\n\tpg->GetProperty(wxT(\"Font\"))->Enable(bEnable);\n\tpg->GetProperty(wxT(\"FontColor\"))->Enable(bEnable);\n\tpg->GetProperty(wxT(\"AlignHori\"))->Enable(bEnable);\n\tpg->GetProperty(wxT(\"AlignVert\"))->Enable(bEnable);\n\tpg->GetProperty(wxT(\"FontSize\"))->Enable(bEnable);\n\tpg->GetProperty(wxT(\"LabelWidth\"))->Enable(bEnable);\n\tpg->GetProperty(wxT(\"LabelHeight\"))->Enable(bEnable);\n\tpg->GetProperty(wxT(\"Filename\"))->Enable(bEnable);\n\tpg->GetProperty(wxT(\"TextContent\"))->Enable(bEnable);\n}\n\nvoid FontPropertySetting::updateProperties(wxPropertyGrid* pg)\n{\n\tSpritePropertySetting::updateProperties(pg);\n\n\tFontSprite* sprite = static_cast<FontSprite*>(m_sprite);\n\tpg->GetProperty(wxT(\"Font\"))->SetValue(sprite->font);\n\n\twxColour col = wxColour(sprite->color.r*255, sprite->color.g*255, sprite->color.b*255, sprite->color.a*255);\n\tpg->SetPropertyValueString(wxT(\"FontColor\"), col.GetAsString());\n\n\tpg->GetProperty(wxT(\"AlignHori\"))->SetValue(HORI_ALIGN_LABELS[sprite->align_hori]);\n\tpg->GetProperty(wxT(\"AlignVert\"))->SetValue(VERT_ALIGN_LABELS[sprite->align_vert]);\n\tpg->GetProperty(wxT(\"FontSize\"))->SetValue(sprite->size);\n\tpg->GetProperty(wxT(\"LabelWidth\"))->SetValue(sprite->width);\n\tpg->GetProperty(wxT(\"LabelHeight\"))->SetValue(sprite->height);\n\tpg->GetProperty(wxT(\"Filename\"))->SetValue(sprite->filename);\n\tpg->GetProperty(wxT(\"TextContent\"))->SetValue(sprite->GetTextContext());\n}\n\nvoid FontPropertySetting::initProperties(wxPropertyGrid* pg)\n{\n\tSpritePropertySetting::initProperties(pg);\n\n\tpg->Append(new wxPropertyCategory(\"FONT\", wxPG_LABEL));\n\n\tFontSprite* sprite = static_cast<FontSprite*>(m_sprite);\n\tpg->Append(new wxStringProperty(wxT(\"Font\"), wxPG_LABEL, sprite->font));\n\n\tpg->Append(new wxBoolProperty(wxT(\"Edge\"), wxPG_LABEL, sprite->has_edge));\n\n\twxColour col = wxColour(sprite->addCol.r*255, sprite->addCol.g*255, sprite->addCol.b*255, sprite->addCol.a*255);\n\tpg->Append(new wxColourProperty(wxT(\"FontColor\"), wxPG_LABEL, col));\n\tpg->SetPropertyAttribute(\"FontColor\", \"HasAlpha\", true);\n\n\twxEnumProperty* horiAlignProp = new wxEnumProperty(wxT(\"AlignHori\"), wxPG_LABEL, HORI_ALIGN_LABELS);\n\thoriAlignProp->SetValue(HORI_ALIGN_LABELS[sprite->align_hori]);\n\tpg->Append(horiAlignProp);\n\n\twxEnumProperty* vertAlignProp = new wxEnumProperty(wxT(\"AlignVert\"), wxPG_LABEL, VERT_ALIGN_LABELS);\n\tvertAlignProp->SetValue(VERT_ALIGN_LABELS[sprite->align_vert]);\n\tpg->Append(vertAlignProp);\n\n\tpg->Append(new wxFloatProperty(wxT(\"FontSize\"), wxPG_LABEL, sprite->size));\n\tpg->Append(new wxFloatProperty(wxT(\"LabelWidth\"), wxPG_LABEL, sprite->width));\n\tpg->Append(new wxFloatProperty(wxT(\"LabelHeight\"), wxPG_LABEL, sprite->height));\n\tpg->Append(new wxStringProperty(wxT(\"Filename\"), wxPG_LABEL, sprite->filename));\n\tpg->Append(new wxStringProperty(wxT(\"TextContent\"), wxPG_LABEL, sprite->GetTextContext()));\n}\n\n}<commit_msg>[FIXED] FontPropertySetting Edge项<commit_after>#include \"FontPropertySetting.h\"\n#include \"PropertySettingPanel.h\"\n\n#include \"dataset\/FontSprite.h\"\n\n#include <wx\/propgrid\/advprops.h>\n\nnamespace d2d\n{\n\nconst wxChar* FontPropertySetting::HORI_ALIGN_LABELS[] = { \n\twxT(\"left\"), wxT(\"right\"), wxT(\"center\"), wxT(\"auto\"), NULL };\nconst wxChar* FontPropertySetting::VERT_ALIGN_LABELS[] = { \n\twxT(\"top\"), wxT(\"bottom\"), wxT(\"center\"), wxT(\"auto\"), NULL };\n\nFontPropertySetting::FontPropertySetting(EditPanel* editPanel, FontSprite* sprite)\n\t: SpritePropertySetting(editPanel, sprite)\n{\n\tm_type = wxT(\"Font\");\n}\n\nvoid FontPropertySetting::onPropertyGridChange(const wxString& name, const wxAny& value)\n{\n\tSpritePropertySetting::onPropertyGridChange(name, value);\n\n\tFontSprite* sprite = static_cast<FontSprite*>(m_sprite);\n\tif (name == wxT(\"Font\"))\n\t\tsprite->font = wxANY_AS(value, wxString);\n\telse if (name == wxT(\"Edge\")) {\n\t\tsprite->has_edge = wxANY_AS(value, bool);\n\t}\n\telse if (name == wxT(\"FontColor\")) {\n\t\twxColour col = wxANY_AS(value, wxColour);\n\t\tsprite->color.set(col.Red() \/ 255.0f, col.Green() \/ 255.0f, col.Blue() \/ 255.0f, col.Alpha() \/ 255.0f);\n\t}\n\telse if (name == wxT(\"AlignHori\")) \n\t\tsprite->align_hori = HoriAlignType(wxANY_AS(value, int));\n\telse if (name == wxT(\"AlignVert\"))\n\t\tsprite->align_vert = VertAlignType(wxANY_AS(value, int));\n\telse if (name == wxT(\"FontSize\"))\n\t\tsprite->size = wxANY_AS(value, float);\n\telse if (name == wxT(\"LabelWidth\")) {\n\t\tsprite->width = wxANY_AS(value, float);\n\t\tsprite->buildBounding();\n\t}\n\telse if (name == wxT(\"LabelHeight\")) {\n\t\tsprite->height = wxANY_AS(value, float);\n\t\tsprite->buildBounding();\n\t} else if (name == wxT(\"Filename\")) {\n\t\tstd::string str = wxANY_AS(value, wxString);\n\t\tsprite->loadFont(str);\n\t} else if (name == wxT(\"TextContent\")) {\n\t\tstd::string str = wxANY_AS(value, wxString);\n\t\tsprite->SetTextContent(str);\n\t}\n}\n\nvoid FontPropertySetting::enablePropertyGrid(PropertySettingPanel* panel, bool bEnable)\n{\n\tSpritePropertySetting::enablePropertyGrid(panel, bEnable);\n\n\twxPropertyGrid* pg = panel->getPG();\n\tpg->GetProperty(wxT(\"Font\"))->Enable(bEnable);\n\tpg->GetProperty(wxT(\"Edge\"))->Enable(bEnable);\n\tpg->GetProperty(wxT(\"FontColor\"))->Enable(bEnable);\n\tpg->GetProperty(wxT(\"AlignHori\"))->Enable(bEnable);\n\tpg->GetProperty(wxT(\"AlignVert\"))->Enable(bEnable);\n\tpg->GetProperty(wxT(\"FontSize\"))->Enable(bEnable);\n\tpg->GetProperty(wxT(\"LabelWidth\"))->Enable(bEnable);\n\tpg->GetProperty(wxT(\"LabelHeight\"))->Enable(bEnable);\n\tpg->GetProperty(wxT(\"Filename\"))->Enable(bEnable);\n\tpg->GetProperty(wxT(\"TextContent\"))->Enable(bEnable);\n}\n\nvoid FontPropertySetting::updateProperties(wxPropertyGrid* pg)\n{\n\tSpritePropertySetting::updateProperties(pg);\n\n\tFontSprite* sprite = static_cast<FontSprite*>(m_sprite);\n\tpg->GetProperty(wxT(\"Font\"))->SetValue(sprite->font);\n\n\tpg->GetProperty(wxT(\"Edge\"))->SetValue(sprite->has_edge);\n\n\twxColour col = wxColour(sprite->color.r*255, sprite->color.g*255, sprite->color.b*255, sprite->color.a*255);\n\tpg->SetPropertyValueString(wxT(\"FontColor\"), col.GetAsString());\n\n\tpg->GetProperty(wxT(\"AlignHori\"))->SetValue(HORI_ALIGN_LABELS[sprite->align_hori]);\n\tpg->GetProperty(wxT(\"AlignVert\"))->SetValue(VERT_ALIGN_LABELS[sprite->align_vert]);\n\tpg->GetProperty(wxT(\"FontSize\"))->SetValue(sprite->size);\n\tpg->GetProperty(wxT(\"LabelWidth\"))->SetValue(sprite->width);\n\tpg->GetProperty(wxT(\"LabelHeight\"))->SetValue(sprite->height);\n\tpg->GetProperty(wxT(\"Filename\"))->SetValue(sprite->filename);\n\tpg->GetProperty(wxT(\"TextContent\"))->SetValue(sprite->GetTextContext());\n}\n\nvoid FontPropertySetting::initProperties(wxPropertyGrid* pg)\n{\n\tSpritePropertySetting::initProperties(pg);\n\n\tpg->Append(new wxPropertyCategory(\"FONT\", wxPG_LABEL));\n\n\tFontSprite* sprite = static_cast<FontSprite*>(m_sprite);\n\tpg->Append(new wxStringProperty(wxT(\"Font\"), wxPG_LABEL, sprite->font));\n\n\tpg->Append(new wxBoolProperty(wxT(\"Edge\"), wxPG_LABEL, sprite->has_edge));\n\n\twxColour col = wxColour(sprite->addCol.r*255, sprite->addCol.g*255, sprite->addCol.b*255, sprite->addCol.a*255);\n\tpg->Append(new wxColourProperty(wxT(\"FontColor\"), wxPG_LABEL, col));\n\tpg->SetPropertyAttribute(\"FontColor\", \"HasAlpha\", true);\n\n\twxEnumProperty* horiAlignProp = new wxEnumProperty(wxT(\"AlignHori\"), wxPG_LABEL, HORI_ALIGN_LABELS);\n\thoriAlignProp->SetValue(HORI_ALIGN_LABELS[sprite->align_hori]);\n\tpg->Append(horiAlignProp);\n\n\twxEnumProperty* vertAlignProp = new wxEnumProperty(wxT(\"AlignVert\"), wxPG_LABEL, VERT_ALIGN_LABELS);\n\tvertAlignProp->SetValue(VERT_ALIGN_LABELS[sprite->align_vert]);\n\tpg->Append(vertAlignProp);\n\n\tpg->Append(new wxFloatProperty(wxT(\"FontSize\"), wxPG_LABEL, sprite->size));\n\tpg->Append(new wxFloatProperty(wxT(\"LabelWidth\"), wxPG_LABEL, sprite->width));\n\tpg->Append(new wxFloatProperty(wxT(\"LabelHeight\"), wxPG_LABEL, sprite->height));\n\tpg->Append(new wxStringProperty(wxT(\"Filename\"), wxPG_LABEL, sprite->filename));\n\tpg->Append(new wxStringProperty(wxT(\"TextContent\"), wxPG_LABEL, sprite->GetTextContext()));\n}\n\n}<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n#include \"ros\/ros.h\"\n#include \"sensor_msgs\/PointCloud2.h\"\n#include \"sensor_msgs\/NavSatFix.h\"\n#include \"sensor_msgs\/Imu.h\"\n#include \"nav_msgs\/Odometry.h\"\n#include \"laser_transform_core.h\"\n\nusing std::string;\n\nint main (int argc, char **argv)\n{\n ros::init(argc, argv, \"laser_transform\");\n ros::NodeHandle n;\n \n \/\/ Declare variables thar can be modified by launch file or command line.\n int rate;\n bool imu_msgs;\n bool gps_msgs;\n string pcl_in_topic;\n string pcl_out_topic;\n string imu_topic;\n string gps_topic;\n \/\/string odo_topic;\n \n \/\/ Create a new LaserTransformer object.\n LaserTransform *node_lt = new LaserTransform();\n\n node_lt->init();\n\n \/\/ while using different parameters.\n ros::NodeHandle private_node_handle_(\"~\");\n private_node_handle_.param(\"rate\", rate, int(10));\n private_node_handle_.param(\"imu_msgs\", imu_msgs, bool(false));\n private_node_handle_.param(\"gps_msgs\", gps_msgs, bool(false));\n private_node_handle_.param(\"pcl_in_topic\", pcl_in_topic, string(\"\/cloud\"));\n private_node_handle_.param(\"pcl_out_topic\", pcl_out_topic, string(\"\/cloud_world\"));\n private_node_handle_.param(\"imu_topic\", imu_topic, string(\"\/imu\/data\"));\n private_node_handle_.param(\"gps_topic\", gps_topic, string(\"\/gps\/fix\"));\n\n \/\/ Create a subscriber\n ros::Subscriber sub_message = n.subscribe(pcl_in_topic.c_str(), 1000, &LaserTransform::messageCallback, node_lt);\n\n \/\/ Create odometry subscriber\n ros::Subscriber sub_odometry = n.subscribe(\"\/odometry\/filtered\", 50, &LaserTransform::odometryCallback, node_lt);\n\n \/\/ Create a publisher and name the topic\n ros::Publisher pub_message = n.advertise<sensor_msgs::PointCloud2>(pcl_out_topic.c_str(), 50);\n\n \/\/ Create a publisher for IMU msgs\n ros::Publisher imu_pub = n.advertise<sensor_msgs::Imu>(imu_topic.c_str(), 50);\n\n \/\/ Create a publisher for GPS msgs\n ros::Publisher gps_pub = n.advertise<sensor_msgs::NavSatFix>(gps_topic.c_str(), 50);\n\n ros::Rate r(rate);\n\n while (n.ok())\n {\n node_lt->publishMessage(&pub_message);\n if (imu_msgs)\n node_lt->publishImuMessage(&imu_pub);\n if (gps_msgs)\n node_lt->publishNavSatFixMessage(&gps_pub);\n ros::spinOnce();\n r.sleep();\n }\n\n return 0;\n \/\/ end main\n}\n<commit_msg>add imu convergence parameter<commit_after>#include <iostream>\n#include \"ros\/ros.h\"\n#include \"sensor_msgs\/PointCloud2.h\"\n#include \"sensor_msgs\/NavSatFix.h\"\n#include \"sensor_msgs\/Imu.h\"\n#include \"nav_msgs\/Odometry.h\"\n#include \"laser_transform_core.h\"\n\nusing std::string;\n\nint main (int argc, char **argv)\n{\n ros::init(argc, argv, \"laser_transform\");\n ros::NodeHandle n;\n\n \/\/ Declare variables thar can be modified by launch file or command line.\n int rate;\n int imu_convergence_speed;\n bool imu_msgs;\n bool gps_msgs;\n string pcl_in_topic;\n string pcl_out_topic;\n string imu_topic;\n string gps_topic;\n \/\/string odo_topic;\n\n \/\/ Create a new LaserTransformer object.\n LaserTransform *node_lt = new LaserTransform();\n\n node_lt->init();\n\n \/\/ while using different parameters.\n ros::NodeHandle private_node_handle_(\"~\");\n private_node_handle_.param(\"rate\", rate, int(10));\n private_node_handle_.param(\"imu_msgs\", imu_msgs, bool(true));\n private_node_handle_.param(\"gps_msgs\", gps_msgs, bool(false));\n private_node_handle_.param(\"pcl_in_topic\", pcl_in_topic, string(\"\/cloud\"));\n private_node_handle_.param(\"pcl_out_topic\", pcl_out_topic, string(\"\/cloud_world\"));\n private_node_handle_.param(\"imu_topic\", imu_topic, string(\"\/imu\/data\"));\n private_node_handle_.param(\"gps_topic\", gps_topic, string(\"\/gps\/fix\"));\n private_node_handle_.param(\"imu_convergence_speed\", imu_convergence_speed, int(20));\n\n \/\/ Create a subscriber\n ros::Subscriber sub_message = n.subscribe(pcl_in_topic.c_str(), 1000, &LaserTransform::pclCallback, node_lt);\n\n \/\/ Create odometry subscriber\n ros::Subscriber sub_odometry = n.subscribe(\"\/odometry\/filtered\", 50, &LaserTransform::odometryCallback, node_lt);\n\n \/\/ Create a publisher and name the topic\n ros::Publisher pub_message = n.advertise<sensor_msgs::PointCloud2>(pcl_out_topic.c_str(), 50);\n\n \/\/ Create a publisher for IMU msgs\n ros::Publisher imu_pub = n.advertise<sensor_msgs::Imu>(imu_topic.c_str(), 50);\n\n \/\/ Create a publisher for GPS msgs\n ros::Publisher gps_pub = n.advertise<sensor_msgs::NavSatFix>(gps_topic.c_str(), 50);\n\n ros::Rate r(rate);\n\n while (n.ok())\n {\n node_lt->publishPclMessage(&pub_message);\n if (imu_msgs)\n node_lt->publishImuMessage(&imu_pub);\n if (gps_msgs)\n node_lt->publishNavSatFixMessage(&gps_pub);\n ros::spinOnce();\n r.sleep();\n }\n\n return 0;\n \/\/ end main\n}\n<|endoftext|>"} {"text":"<commit_before>#include <agency\/future.hpp>\n#include <agency\/new_executor_traits.hpp>\n#include <iostream>\n#include <cassert>\n\n#include \"test_executors.hpp\"\n\ntemplate<class Executor>\nvoid test()\n{\n using executor_type = Executor;\n \n size_t n = 1;\n \n auto int_ready = agency::detail::make_ready_future(0);\n auto void_ready = agency::detail::make_ready_future();\n \n auto futures = std::make_tuple(std::move(void_ready), std::move(int_ready));\n \n std::mutex mut;\n executor_type exec;\n std::future<int> fut = agency::new_executor_traits<executor_type>::template when_all_execute_and_select<1>(exec, [&mut](int& x)\n {\n mut.lock();\n x += 1;\n mut.unlock();\n },\n std::move(futures));\n \n auto got = fut.get();\n \n assert(got == n);\n assert(exec.valid());\n}\n\nint main()\n{\n using namespace test_executors;\n\n test<empty_executor>();\n test<single_agent_when_all_execute_and_select_executor>();\n test<multi_agent_when_all_execute_and_select_executor>();\n test<single_agent_then_execute_executor>();\n\n test<multi_agent_execute_returning_user_defined_container_executor>();\n test<multi_agent_execute_returning_default_container_executor>();\n test<multi_agent_execute_returning_void_executor>();\n\n test<multi_agent_async_execute_returning_user_defined_container_executor>();\n test<multi_agent_async_execute_returning_default_container_executor>();\n test<multi_agent_async_execute_returning_void_executor>();\n\n test<multi_agent_execute_with_shared_inits_returning_user_defined_container_executor>();\n test<multi_agent_execute_with_shared_inits_returning_default_container_executor>();\n\n std::cout << \"OK\" << std::endl;\n\n return 0;\n}\n\n<commit_msg>Test multi_agent_execute_with_shared_inits_returning_void_executor with test_single_agent_when_all_execute_and_select.cpp<commit_after>#include <agency\/future.hpp>\n#include <agency\/new_executor_traits.hpp>\n#include <iostream>\n#include <cassert>\n\n#include \"test_executors.hpp\"\n\ntemplate<class Executor>\nvoid test()\n{\n using executor_type = Executor;\n \n size_t n = 1;\n \n auto int_ready = agency::detail::make_ready_future(0);\n auto void_ready = agency::detail::make_ready_future();\n \n auto futures = std::make_tuple(std::move(void_ready), std::move(int_ready));\n \n std::mutex mut;\n executor_type exec;\n std::future<int> fut = agency::new_executor_traits<executor_type>::template when_all_execute_and_select<1>(exec, [&mut](int& x)\n {\n mut.lock();\n x += 1;\n mut.unlock();\n },\n std::move(futures));\n \n auto got = fut.get();\n \n assert(got == n);\n assert(exec.valid());\n}\n\nint main()\n{\n using namespace test_executors;\n\n test<empty_executor>();\n test<single_agent_when_all_execute_and_select_executor>();\n test<multi_agent_when_all_execute_and_select_executor>();\n test<single_agent_then_execute_executor>();\n\n test<multi_agent_execute_returning_user_defined_container_executor>();\n test<multi_agent_execute_returning_default_container_executor>();\n test<multi_agent_execute_returning_void_executor>();\n\n test<multi_agent_async_execute_returning_user_defined_container_executor>();\n test<multi_agent_async_execute_returning_default_container_executor>();\n test<multi_agent_async_execute_returning_void_executor>();\n\n test<multi_agent_execute_with_shared_inits_returning_user_defined_container_executor>();\n test<multi_agent_execute_with_shared_inits_returning_default_container_executor>();\n test<multi_agent_execute_with_shared_inits_returning_void_executor>();\n\n std::cout << \"OK\" << std::endl;\n\n return 0;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/*=========================================================================\n\n Program: ORFEO Toolbox\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n\n Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.\n See OTBCopyright.txt for details.\n\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notices for more information.\n\n=========================================================================*\/\n#if defined(_MSC_VER)\n#pragma warning ( disable : 4786 )\n#endif\n\n#ifdef __BORLANDC__\n#define ITK_LEAN_AND_MEAN\n#endif\n\n\/\/ Software Guide : BeginCommandLineArgs\n\/\/ INPUT: {ADS40RoiSmall.png}\n\/\/ OUTPUT: {TextureOutput.tif}, {pretty_TextureOutput.png}\n\/\/ 2 1 1\n\/\/ Software Guide : EndCommandLineArgs\n\n#include \"itkExceptionObject.h\"\n#include \"otbImage.h\"\n#include \"itkVector.h\"\n#include \"itkConstNeighborhoodIterator.h\"\n#include \"otbImageFileReader.h\"\n#include \"otbImageFileWriter.h\"\n#include \"itkRescaleIntensityImageFilter.h\"\n\n\n\n#include \"otbTextureFunctors.h\"\n#include \"otbFunctionWithNeighborhoodToImageFilter.h\"\n#include \"otbTextureImageFunction.h\"\n\n\nint main(int argc, char * argv[])\n{\n \/\/ Parse command line parameters\n if ( argc != 7 )\n {\n std::cerr << \"Usage: \" << argv[0] << \" <inputImage> \";\n std::cerr << \" <outputImage> <outputRescaled> \";\n std::cerr << \" <radius> <xOffset> <yOffset> \";\n std::cerr << std::endl;\n return EXIT_FAILURE;\n }\n\n const char* infname = argv[1];\n const char* outfname = argv[2];\n const char* outprettyfname = argv[3];\n\n const unsigned int radius = static_cast<unsigned int>(atoi(argv[4]));\n const unsigned int xOffset = static_cast<unsigned int>(atoi(argv[5]));\n const unsigned int yOffset = static_cast<unsigned int>(atoi(argv[6]));\n\n\n typedef double PixelType;\n const int Dimension = 2;\n typedef otb::Image<PixelType,Dimension> ImageType;\n typedef itk::ConstNeighborhoodIterator<ImageType> IteratorType;\n typedef itk::Vector< PixelType > VectorType;\n\n\n typedef otb::Functor::ContrastTextureFunctor<IteratorType, VectorType>\n FunctorType;\n\n typedef otb::TextureImageFunction<ImageType, FunctorType> FunctionType;\n typedef otb::FunctionWithNeighborhoodToImageFilter<ImageType,\n ImageType, FunctionType> FilterType;\n typedef ImageType::OffsetType OffsetType;\n typedef otb::ImageFileReader<ImageType> ReaderType;\n typedef otb::ImageFileWriter<ImageType> WriterType;\n\n\n \/\/ Instantiating object\n FilterType::Pointer textureFilter = FilterType::New();\n ReaderType::Pointer reader = ReaderType::New();\n WriterType::Pointer writer = WriterType::New();\n\n reader->SetFileName(infname);\n writer->SetFileName(outfname);\n\n textureFilter->SetInput(reader->GetOutput());\n ImageType::SizeType tRadius;\n tRadius[0] = radius;\n tRadius[1] = radius;\n textureFilter->SetRadius(tRadius);\n OffsetType offset;\n offset[0] = xOffset;\n offset[1] = yOffset;\n\n textureFilter->SetOffset(offset);\n writer->SetInput(textureFilter->GetOutput());\n\n writer->Update();\n\n \/\/ Pretty image creation for printing\n\n typedef otb::Image<unsigned char, Dimension> OutputPrettyImageType;\n typedef otb::ImageFileWriter<OutputPrettyImageType> WriterPrettyOutputType;\n typedef itk::RescaleIntensityImageFilter< ImageType, OutputPrettyImageType> RescalerOutputType;\n\n RescalerOutputType::Pointer outputRescaler = RescalerOutputType::New();\n WriterPrettyOutputType::Pointer prettyOutputWriter = WriterPrettyOutputType::New();\n outputRescaler->SetInput( textureFilter->GetOutput() );\n outputRescaler->SetOutputMinimum(0);\n outputRescaler->SetOutputMaximum(255);\n prettyOutputWriter->SetFileName( outprettyfname );\n prettyOutputWriter->SetInput( outputRescaler->GetOutput() );\n\n prettyOutputWriter->Update();\n\n\n return EXIT_SUCCESS;\n}\n<commit_msg>ENH : change texture call in example after template change<commit_after>\/*=========================================================================\n\n Program: ORFEO Toolbox\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n\n Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.\n See OTBCopyright.txt for details.\n\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notices for more information.\n\n=========================================================================*\/\n#if defined(_MSC_VER)\n#pragma warning ( disable : 4786 )\n#endif\n\n#ifdef __BORLANDC__\n#define ITK_LEAN_AND_MEAN\n#endif\n\n\/\/ Software Guide : BeginCommandLineArgs\n\/\/ INPUT: {ADS40RoiSmall.png}\n\/\/ OUTPUT: {TextureOutput.tif}, {pretty_TextureOutput.png}\n\/\/ 2 1 1\n\/\/ Software Guide : EndCommandLineArgs\n\n#include \"itkExceptionObject.h\"\n#include \"otbImage.h\"\n#include \"itkVector.h\"\n#include \"itkConstNeighborhoodIterator.h\"\n#include \"otbImageFileReader.h\"\n#include \"otbImageFileWriter.h\"\n#include \"itkRescaleIntensityImageFilter.h\"\n\n\n\n#include \"otbTextureFunctors.h\"\n#include \"otbFunctionWithNeighborhoodToImageFilter.h\"\n#include \"otbTextureImageFunction.h\"\n\n\nint main(int argc, char * argv[])\n{\n \/\/ Parse command line parameters\n if ( argc != 7 )\n {\n std::cerr << \"Usage: \" << argv[0] << \" <inputImage> \";\n std::cerr << \" <outputImage> <outputRescaled> \";\n std::cerr << \" <radius> <xOffset> <yOffset> \";\n std::cerr << std::endl;\n return EXIT_FAILURE;\n }\n\n const char* infname = argv[1];\n const char* outfname = argv[2];\n const char* outprettyfname = argv[3];\n\n const unsigned int radius = static_cast<unsigned int>(atoi(argv[4]));\n const unsigned int xOffset = static_cast<unsigned int>(atoi(argv[5]));\n const unsigned int yOffset = static_cast<unsigned int>(atoi(argv[6]));\n\n\n typedef double PixelType;\n const int Dimension = 2;\n typedef otb::Image<PixelType,Dimension> ImageType;\n typedef itk::ConstNeighborhoodIterator<ImageType> IteratorType;\n typedef itk::Vector< PixelType > VectorType;\n\n\n typedef otb::Functor::ContrastTextureFunctor<PixelType, PixelType> FunctorType;\n\n typedef otb::TextureImageFunction<ImageType, FunctorType> FunctionType;\n typedef otb::FunctionWithNeighborhoodToImageFilter<ImageType,\n ImageType, FunctionType> FilterType;\n typedef ImageType::OffsetType OffsetType;\n typedef otb::ImageFileReader<ImageType> ReaderType;\n typedef otb::ImageFileWriter<ImageType> WriterType;\n\n\n \/\/ Instantiating object\n FilterType::Pointer textureFilter = FilterType::New();\n ReaderType::Pointer reader = ReaderType::New();\n WriterType::Pointer writer = WriterType::New();\n\n reader->SetFileName(infname);\n writer->SetFileName(outfname);\n\n textureFilter->SetInput(reader->GetOutput());\n ImageType::SizeType tRadius;\n tRadius[0] = radius;\n tRadius[1] = radius;\n textureFilter->SetRadius(tRadius);\n OffsetType offset;\n offset[0] = xOffset;\n offset[1] = yOffset;\n\n textureFilter->SetOffset(offset);\n writer->SetInput(textureFilter->GetOutput());\n\n writer->Update();\n\n \/\/ Pretty image creation for printing\n\n typedef otb::Image<unsigned char, Dimension> OutputPrettyImageType;\n typedef otb::ImageFileWriter<OutputPrettyImageType> WriterPrettyOutputType;\n typedef itk::RescaleIntensityImageFilter< ImageType, OutputPrettyImageType> RescalerOutputType;\n\n RescalerOutputType::Pointer outputRescaler = RescalerOutputType::New();\n WriterPrettyOutputType::Pointer prettyOutputWriter = WriterPrettyOutputType::New();\n outputRescaler->SetInput( textureFilter->GetOutput() );\n outputRescaler->SetOutputMinimum(0);\n outputRescaler->SetOutputMaximum(255);\n prettyOutputWriter->SetFileName( outprettyfname );\n prettyOutputWriter->SetInput( outputRescaler->GetOutput() );\n\n prettyOutputWriter->Update();\n\n\n return EXIT_SUCCESS;\n}\n<|endoftext|>"} {"text":"<commit_before>\/**\n@copyright MIT license; see @ref index or the accompanying LICENSE file.\n*\/\n\n#include <Beard\/utility.hpp>\n#include <Beard\/ui\/packing.hpp>\n#include <Beard\/ui\/Root.hpp>\n#include <Beard\/ui\/Widget\/Base.hpp>\n#include <Beard\/ui\/debug.hpp>\n\n#include <utility>\n\nnamespace Beard {\nnamespace ui {\nnamespace Widget {\n\n\/\/ class Base implementation\n\nBase::~Base() noexcept = default;\n\n\/\/ implementation\n\nvoid\nBase::push_action_graph_impl(\n\tui::Widget::set_type& \/*set*\/\n) noexcept {\n\t\/* Do nothing. *\/\n}\n\nvoid\nBase::set_input_control_impl(\n\tbool const enabled\n) noexcept {\n\tm_flags.set(ui::Widget::Flags::input_control, enabled);\n}\n\nvoid\nBase::cache_geometry_impl() noexcept {\n\t\/* Do nothing. *\/\n}\n\nvoid\nBase::reflow_impl(\n\tRect const& area,\n\tbool const cache\n) noexcept {\n\tif (cache) {\n\t\tcache_geometry();\n\t}\n\tui::reflow(area, get_geometry());\n}\n\nbool\nBase::handle_event_impl(\n\tui::Event const& \/*event*\/\n) noexcept {\n\treturn false;\n}\n\nvoid\nBase::render_impl(\n\tui::Widget::RenderData& \/*rd*\/\n) noexcept {\n\t\/* Do nothing. *\/\n}\n\nsigned\nBase::num_children_impl() const noexcept {\n\treturn 0;\n}\n\nui::Widget::SPtr\nBase::get_child_impl(\n\tindex_type const \/*index*\/\n) {\n\treturn nullptr;\n}\n\nbool\nBase::handle_event(\n\tui::Event const& event\n) noexcept {\n\tif (\n\t\t\/\/ Avoid SPtr construction if we can\n\t\tsignal_event_filter.is_bound() &&\n\t\tsignal_event_filter(\n\t\t\tstd::move(shared_from_this()),\n\t\t\tevent\n\t\t)\n\t) {\n\t\treturn true;\n\t}\n\treturn handle_event_impl(event);\n}\n\nvoid\nBase::render(\n\tui::Widget::RenderData& rd\n) noexcept {\n\tif (!is_visible()) {\n\t\treturn;\n\t}\n\tif (rd.get_boolean(ui::property_frame_debug_enabled)) {\n\t\tui::geom_debug_render(\n\t\t\trd.terminal,\n\t\t\tget_geometry(),\n\t\t\ttty::Color::term_default,\n\t\t\tis_focused()\n\t\t);\n\t}\n\trender_impl(rd);\n}\n\n\/\/ properties\n\nvoid\nBase::update_depth(\n\tui::Widget::SPtr const& parent\n) noexcept {\n\tif (type == ui::Widget::Type::Root) {\n\t\tm_depth = -1;\n\t\treturn;\n\t} else if (parent) {\n\t\tm_depth = parent->get_depth() + 1;\n\t} else {\n\t\tm_depth = 0;\n\t}\n\tfor (signed index = 0; index < num_children(); ++index) {\n\t\tauto const child = get_child(index);\n\t\tif (child) {\n\t\t\tchild->update_depth(shared_from_this());\n\t\t}\n\t}\n}\n\nvoid\nBase::set_parent(\n\tui::Widget::SPtr const& widget\n) noexcept {\n\tm_parent = widget;\n\tupdate_depth(widget);\n}\n\nvoid\nBase::set_visible(\n\tbool const visible\n) noexcept {\n\tif (is_visible() != visible) {\n\t\tm_flags.set(ui::Widget::Flags::visible, visible);\n\t\tqueue_actions(\n\t\t\tui::UpdateActions::flag_parent |\n\t\t\tui::UpdateActions::reflow |\n\t\t\tui::UpdateActions::render\n\t\t);\n\t}\n}\n\nvoid\nBase::set_focused(\n\tbool const focused\n) noexcept {\n\tif (is_focused() != focused) {\n\t\tui::Event event;\n\t\tevent.type = ui::EventType::focus_changed;\n\t\tevent.focus_changed.previous = is_focused();\n\t\tm_flags.set(ui::Widget::Flags::focused, focused);\n\t\tif (!handle_event(event)) {\n\t\t\tqueue_actions(\n\t\t\t\tui::UpdateActions::flag_noclear |\n\t\t\t\tui::UpdateActions::render\n\t\t\t);\n\t\t}\n\t}\n}\n\n\/\/ operations\n\ninline constexpr bool\nis_clearing_render(\n\tui::UpdateActions const actions\n) noexcept {\n\treturn\n\t\tui::UpdateActions::render\n\t\t== (actions & (ui::UpdateActions::render | ui::UpdateActions::flag_noclear))\n\t;\n}\n\ninline ui::UpdateActions\njoin_actions(\n\tui::UpdateActions const x,\n\tui::UpdateActions const y\n) {\n\tif (is_clearing_render(x) || is_clearing_render(y)) {\n\t\treturn (x | y) & ~ui::UpdateActions::flag_noclear;\n\t} else {\n\t\treturn x | y;\n\t}\n}\n\nvoid\nBase::queue_actions(\n\tui::UpdateActions actions\n) {\n\tif (enum_cast(actions & ui::UpdateActions::mask_actions)) {\n\t\tif (!is_action_queued()) {\n\t\t\tget_root()->get_context().enqueue_widget(shared_from_this());\n\t\t}\n\t\tactions = join_actions(actions, get_queued_actions());\n\t\tif (enum_cast(actions & ui::UpdateActions::flag_parent) && has_parent()) {\n\t\t\tget_parent()->queue_actions(\n\t\t\t\tactions & ~ui::UpdateActions::flag_parent\n\t\t\t);\n\t\t}\n\t\tm_flags.set_masked(\n\t\t\tmask_ua,\n\t\t\tstatic_cast<ui::Widget::Flags>(enum_cast(actions) << shift_ua)\n\t\t);\n\t\tset_action_queued(true);\n\t}\n}\n\nvoid\nBase::clear_actions(\n\tbool const dequeue\n) {\n\tif (dequeue) {\n\t\tget_root()->get_context().dequeue_widget(shared_from_this());\n\t}\n\tm_flags.remove(mask_ua);\n\tset_action_queued(false);\n}\n\nvoid\nBase::push_action_graph(\n\tui::Widget::set_type& set,\n\tui::UpdateActions actions\n) noexcept {\n\tactions &= ~ui::UpdateActions::flag_parent;\n\tauto const prev_actions = get_queued_actions() & ~ui::UpdateActions::flag_parent;\n\tm_flags.set_masked(\n\t\tmask_ua,\n\t\tstatic_cast<ui::Widget::Flags>(enum_cast(actions) << shift_ua)\n\t);\n\tif (set.insert(this).second || actions != prev_actions) {\n\t\tpush_action_graph_impl(set);\n\t}\n}\n\n} \/\/ namespace Widget\n} \/\/ namespace ui\n} \/\/ namespace Beard\n<commit_msg>ui::Widget::Base: corrected type comparison in update_depth().¹<commit_after>\/**\n@copyright MIT license; see @ref index or the accompanying LICENSE file.\n*\/\n\n#include <Beard\/utility.hpp>\n#include <Beard\/ui\/packing.hpp>\n#include <Beard\/ui\/Root.hpp>\n#include <Beard\/ui\/Widget\/Base.hpp>\n#include <Beard\/ui\/debug.hpp>\n\n#include <utility>\n\nnamespace Beard {\nnamespace ui {\nnamespace Widget {\n\n\/\/ class Base implementation\n\nBase::~Base() noexcept = default;\n\n\/\/ implementation\n\nvoid\nBase::push_action_graph_impl(\n\tui::Widget::set_type& \/*set*\/\n) noexcept {\n\t\/* Do nothing. *\/\n}\n\nvoid\nBase::set_input_control_impl(\n\tbool const enabled\n) noexcept {\n\tm_flags.set(ui::Widget::Flags::input_control, enabled);\n}\n\nvoid\nBase::cache_geometry_impl() noexcept {\n\t\/* Do nothing. *\/\n}\n\nvoid\nBase::reflow_impl(\n\tRect const& area,\n\tbool const cache\n) noexcept {\n\tif (cache) {\n\t\tcache_geometry();\n\t}\n\tui::reflow(area, get_geometry());\n}\n\nbool\nBase::handle_event_impl(\n\tui::Event const& \/*event*\/\n) noexcept {\n\treturn false;\n}\n\nvoid\nBase::render_impl(\n\tui::Widget::RenderData& \/*rd*\/\n) noexcept {\n\t\/* Do nothing. *\/\n}\n\nsigned\nBase::num_children_impl() const noexcept {\n\treturn 0;\n}\n\nui::Widget::SPtr\nBase::get_child_impl(\n\tindex_type const \/*index*\/\n) {\n\treturn nullptr;\n}\n\nbool\nBase::handle_event(\n\tui::Event const& event\n) noexcept {\n\tif (\n\t\t\/\/ Avoid SPtr construction if we can\n\t\tsignal_event_filter.is_bound() &&\n\t\tsignal_event_filter(\n\t\t\tstd::move(shared_from_this()),\n\t\t\tevent\n\t\t)\n\t) {\n\t\treturn true;\n\t}\n\treturn handle_event_impl(event);\n}\n\nvoid\nBase::render(\n\tui::Widget::RenderData& rd\n) noexcept {\n\tif (!is_visible()) {\n\t\treturn;\n\t}\n\tif (rd.get_boolean(ui::property_frame_debug_enabled)) {\n\t\tui::geom_debug_render(\n\t\t\trd.terminal,\n\t\t\tget_geometry(),\n\t\t\ttty::Color::term_default,\n\t\t\tis_focused()\n\t\t);\n\t}\n\trender_impl(rd);\n}\n\n\/\/ properties\n\nvoid\nBase::update_depth(\n\tui::Widget::SPtr const& parent\n) noexcept {\n\tif (m_type == ui::Widget::Type::Root) {\n\t\tm_depth = -1;\n\t\treturn;\n\t} else if (parent) {\n\t\tm_depth = parent->get_depth() + 1;\n\t} else {\n\t\tm_depth = 0;\n\t}\n\tfor (signed index = 0; index < num_children(); ++index) {\n\t\tauto const child = get_child(index);\n\t\tif (child) {\n\t\t\tchild->update_depth(shared_from_this());\n\t\t}\n\t}\n}\n\nvoid\nBase::set_parent(\n\tui::Widget::SPtr const& widget\n) noexcept {\n\tm_parent = widget;\n\tupdate_depth(widget);\n}\n\nvoid\nBase::set_visible(\n\tbool const visible\n) noexcept {\n\tif (is_visible() != visible) {\n\t\tm_flags.set(ui::Widget::Flags::visible, visible);\n\t\tqueue_actions(\n\t\t\tui::UpdateActions::flag_parent |\n\t\t\tui::UpdateActions::reflow |\n\t\t\tui::UpdateActions::render\n\t\t);\n\t}\n}\n\nvoid\nBase::set_focused(\n\tbool const focused\n) noexcept {\n\tif (is_focused() != focused) {\n\t\tui::Event event;\n\t\tevent.type = ui::EventType::focus_changed;\n\t\tevent.focus_changed.previous = is_focused();\n\t\tm_flags.set(ui::Widget::Flags::focused, focused);\n\t\tif (!handle_event(event)) {\n\t\t\tqueue_actions(\n\t\t\t\tui::UpdateActions::flag_noclear |\n\t\t\t\tui::UpdateActions::render\n\t\t\t);\n\t\t}\n\t}\n}\n\n\/\/ operations\n\ninline constexpr bool\nis_clearing_render(\n\tui::UpdateActions const actions\n) noexcept {\n\treturn\n\t\tui::UpdateActions::render\n\t\t== (actions & (ui::UpdateActions::render | ui::UpdateActions::flag_noclear))\n\t;\n}\n\ninline ui::UpdateActions\njoin_actions(\n\tui::UpdateActions const x,\n\tui::UpdateActions const y\n) {\n\tif (is_clearing_render(x) || is_clearing_render(y)) {\n\t\treturn (x | y) & ~ui::UpdateActions::flag_noclear;\n\t} else {\n\t\treturn x | y;\n\t}\n}\n\nvoid\nBase::queue_actions(\n\tui::UpdateActions actions\n) {\n\tif (enum_cast(actions & ui::UpdateActions::mask_actions)) {\n\t\tif (!is_action_queued()) {\n\t\t\tget_root()->get_context().enqueue_widget(shared_from_this());\n\t\t}\n\t\tactions = join_actions(actions, get_queued_actions());\n\t\tif (enum_cast(actions & ui::UpdateActions::flag_parent) && has_parent()) {\n\t\t\tget_parent()->queue_actions(\n\t\t\t\tactions & ~ui::UpdateActions::flag_parent\n\t\t\t);\n\t\t}\n\t\tm_flags.set_masked(\n\t\t\tmask_ua,\n\t\t\tstatic_cast<ui::Widget::Flags>(enum_cast(actions) << shift_ua)\n\t\t);\n\t\tset_action_queued(true);\n\t}\n}\n\nvoid\nBase::clear_actions(\n\tbool const dequeue\n) {\n\tif (dequeue) {\n\t\tget_root()->get_context().dequeue_widget(shared_from_this());\n\t}\n\tm_flags.remove(mask_ua);\n\tset_action_queued(false);\n}\n\nvoid\nBase::push_action_graph(\n\tui::Widget::set_type& set,\n\tui::UpdateActions actions\n) noexcept {\n\tactions &= ~ui::UpdateActions::flag_parent;\n\tauto const prev_actions = get_queued_actions() & ~ui::UpdateActions::flag_parent;\n\tm_flags.set_masked(\n\t\tmask_ua,\n\t\tstatic_cast<ui::Widget::Flags>(enum_cast(actions) << shift_ua)\n\t);\n\tif (set.insert(this).second || actions != prev_actions) {\n\t\tpush_action_graph_impl(set);\n\t}\n}\n\n} \/\/ namespace Widget\n} \/\/ namespace ui\n} \/\/ namespace Beard\n<|endoftext|>"} {"text":"<commit_before>\/**\n * @file\n * @brief Implementation of ROOT data file writer module\n * @copyright Copyright (c) 2017 CERN and the Allpix Squared authors.\n * This software is distributed under the terms of the MIT License, copied verbatim in the file \"LICENSE.md\".\n * In applying this license, CERN does not waive the privileges and immunities granted to it by virtue of its status as an\n * Intergovernmental Organization or submit itself to any jurisdiction.\n *\/\n\n#include \"ROOTObjectWriterModule.hpp\"\n\n#include <fstream>\n#include <string>\n#include <utility>\n\n#include <TBranchElement.h>\n#include <TClass.h>\n\n#include \"core\/config\/ConfigReader.hpp\"\n#include \"core\/utils\/file.h\"\n#include \"core\/utils\/log.h\"\n#include \"core\/utils\/type.h\"\n\n#include \"objects\/Object.hpp\"\n#include \"objects\/objects.h\"\n\nusing namespace allpix;\n\nROOTObjectWriterModule::ROOTObjectWriterModule(Configuration& config, Messenger* messenger, GeometryManager* geo_mgr)\n : Module(config), geo_mgr_(geo_mgr) {\n \/\/ Bind to all messages\n messenger->registerListener(this, &ROOTObjectWriterModule::receive);\n}\n\/**\n * @note Objects cannot be stored in smart pointers due to internal ROOT logic\n *\/\nROOTObjectWriterModule::~ROOTObjectWriterModule() {\n \/\/ Delete all object pointers\n for(auto& index_data : write_list_) {\n delete index_data.second;\n }\n}\n\nvoid ROOTObjectWriterModule::init() {\n \/\/ Create output file\n output_file_name_ =\n createOutputFile(allpix::add_file_extension(config_.get<std::string>(\"file_name\", \"data\"), \"root\"), true);\n output_file_ = std::make_unique<TFile>(output_file_name_.c_str(), \"RECREATE\");\n output_file_->cd();\n\n \/\/ Read include and exclude list\n if(config_.has(\"include\") && config_.has(\"exclude\")) {\n throw InvalidValueError(config_, \"exclude\", \"include and exclude parameter are mutually exclusive\");\n } else if(config_.has(\"include\")) {\n auto inc_arr = config_.getArray<std::string>(\"include\");\n include_.insert(inc_arr.begin(), inc_arr.end());\n } else if(config_.has(\"exclude\")) {\n auto exc_arr = config_.getArray<std::string>(\"exclude\");\n exclude_.insert(exc_arr.begin(), exc_arr.end());\n }\n}\n\nvoid ROOTObjectWriterModule::receive(std::shared_ptr<BaseMessage> message, std::string message_name) { \/\/ NOLINT\n try {\n const BaseMessage* inst = message.get();\n std::string name_str = \" without a name\";\n if(!message_name.empty()) {\n name_str = \" named \" + message_name;\n }\n LOG(TRACE) << \"ROOT object writer received \" << allpix::demangle(typeid(*inst).name()) << name_str;\n\n \/\/ Get the detector name\n std::string detector_name;\n if(message->getDetector() != nullptr) {\n detector_name = message->getDetector()->getName();\n }\n\n \/\/ Read the object\n auto object_array = message->getObjectArray();\n if(!object_array.empty()) {\n keep_messages_.push_back(message);\n\n const Object& first_object = object_array[0];\n std::type_index type_idx = typeid(first_object);\n\n \/\/ Create a new branch of the correct type if this message was not received before\n auto index_tuple = std::make_tuple(type_idx, detector_name, message_name);\n if(write_list_.find(index_tuple) == write_list_.end()) {\n\n auto* cls = TClass::GetClass(typeid(first_object));\n\n \/\/ Remove the allpix prefix\n std::string class_name = cls->GetName();\n std::string apx_namespace = \"allpix::\";\n size_t ap_idx = class_name.find(apx_namespace);\n if(ap_idx != std::string::npos) {\n class_name.replace(ap_idx, apx_namespace.size(), \"\");\n }\n\n \/\/ Check if this message should be kept\n if((!include_.empty() && include_.find(class_name) == include_.end()) ||\n (!exclude_.empty() && exclude_.find(class_name) != exclude_.end())) {\n LOG(TRACE) << \"ROOT object writer ignored message with object \" << allpix::demangle(typeid(*inst).name())\n << \" because it has been excluded or not explicitly included\";\n return;\n }\n\n \/\/ Add vector of objects to write to the write list\n write_list_[index_tuple] = new std::vector<Object*>();\n auto addr = &write_list_[index_tuple];\n\n if(trees_.find(class_name) == trees_.end()) {\n \/\/ Create new tree\n output_file_->cd();\n trees_.emplace(\n class_name,\n std::make_unique<TTree>(class_name.c_str(), (std::string(\"Tree of \") + class_name).c_str()));\n }\n\n std::string branch_name = detector_name;\n if(!message_name.empty()) {\n branch_name += \"_\";\n branch_name += message_name;\n }\n\n trees_[class_name]->Bronch(\n branch_name.c_str(), (std::string(\"std::vector<\") + cls->GetName() + \"*>\").c_str(), addr);\n }\n\n \/\/ Fill the branch vector\n for(Object& object : object_array) {\n ++write_cnt_;\n write_list_[index_tuple]->push_back(&object);\n }\n }\n\n } catch(MessageWithoutObjectException& e) {\n const BaseMessage* inst = message.get();\n LOG(WARNING) << \"ROOT object writer cannot process message of type\" << allpix::demangle(typeid(*inst).name())\n << \" with name \" << message_name;\n }\n}\n\nvoid ROOTObjectWriterModule::run(unsigned int) {\n LOG(TRACE) << \"Writing new objects to tree\";\n output_file_->cd();\n\n \/\/ Fill the tree with the current received messages\n for(auto& tree : trees_) {\n tree.second->Fill();\n }\n\n \/\/ Clear the current message list\n for(auto& index_data : write_list_) {\n index_data.second->clear();\n }\n \/\/ Clear the messages we have to keep because they contain the internal pointers\n keep_messages_.clear();\n}\n\nvoid ROOTObjectWriterModule::finalize() {\n LOG(TRACE) << \"Writing objects to file\";\n output_file_->cd();\n\n int branch_count = 0;\n for(auto& tree : trees_) {\n \/\/ Update statistics\n branch_count += tree.second->GetListOfBranches()->GetEntries();\n }\n\n \/\/ Create main config directory\n TDirectory* config_dir = output_file_->mkdir(\"config\");\n config_dir->cd();\n\n \/\/ Get the config manager\n ConfigManager* conf_manager = getConfigManager();\n\n \/\/ Save the main configuration to the output file\n auto global_dir = config_dir->mkdir(\"Allpix\");\n LOG(TRACE) << \"Writing global configuration\";\n\n \/\/ Loop over all values in the global configuration\n for(auto& key_value : conf_manager->getGlobalConfiguration().getAll()) {\n global_dir->WriteObject(&key_value.second, key_value.first.c_str());\n }\n\n \/\/ Save the instance configuration to the output file\n for(auto& config : conf_manager->getInstanceConfigurations()) {\n \/\/ Create a new directory per section, using the unique module name\n auto unique_name = config.get<std::string>(\"unique_name\");\n auto section_dir = config_dir->mkdir(unique_name.c_str());\n LOG(TRACE) << \"Writing configuration for: \" << unique_name;\n\n \/\/ Loop over all values in the section\n for(auto& key_value : config.getAll()) {\n \/\/ Skip the unique name and input \/ output if empty\n if(key_value.first == \"unique_name\") {\n continue;\n }\n if((key_value.first == \"input\" || key_value.first == \"output\") && key_value.second.empty()) {\n continue;\n }\n section_dir->WriteObject(&key_value.second, key_value.first.c_str());\n }\n }\n\n \/\/ Save the detectors to the output file\n \/\/ FIXME Possibly the format to save the geometry should be more flexible\n auto detectors_dir = output_file_->mkdir(\"detectors\");\n detectors_dir->cd();\n for(auto& detector : geo_mgr_->getDetectors()) {\n auto detector_dir = detectors_dir->mkdir(detector->getName().c_str());\n\n auto position = detector->getPosition();\n detector_dir->WriteObject(&position, \"position\");\n auto orientation = detector->getOrientation();\n detector_dir->WriteObject(&orientation, \"orientation\");\n\n auto model_dir = detector_dir->mkdir(\"model\");\n \/\/ FIXME This saves the model every time again also for models that appear multiple times\n auto model_configs = detector->getModel()->getConfigurations();\n std::map<std::string, int> count_configs;\n for(auto& model_config : model_configs) {\n auto model_config_dir = model_dir;\n if(!model_config.getName().empty()) {\n model_config_dir = model_dir->mkdir(\n (model_config.getName() + \"_\" + std::to_string(count_configs[model_config.getName()])).c_str());\n count_configs[model_config.getName()]++;\n }\n\n for(auto& key_value : model_config.getAll()) {\n model_config_dir->WriteObject(&key_value.second, key_value.first.c_str());\n }\n }\n }\n\n \/\/ Finish writing to output file\n output_file_->Write();\n\n \/\/ Print statistics\n LOG(STATUS) << \"Wrote \" << write_cnt_ << \" objects to \" << branch_count << \" branches in file:\" << std::endl\n << output_file_name_;\n}\n<commit_msg>ROOTObjectWriter: store detector models in separate directory<commit_after>\/**\n * @file\n * @brief Implementation of ROOT data file writer module\n * @copyright Copyright (c) 2017 CERN and the Allpix Squared authors.\n * This software is distributed under the terms of the MIT License, copied verbatim in the file \"LICENSE.md\".\n * In applying this license, CERN does not waive the privileges and immunities granted to it by virtue of its status as an\n * Intergovernmental Organization or submit itself to any jurisdiction.\n *\/\n\n#include \"ROOTObjectWriterModule.hpp\"\n\n#include <fstream>\n#include <string>\n#include <utility>\n\n#include <TBranchElement.h>\n#include <TClass.h>\n\n#include \"core\/config\/ConfigReader.hpp\"\n#include \"core\/utils\/file.h\"\n#include \"core\/utils\/log.h\"\n#include \"core\/utils\/type.h\"\n\n#include \"objects\/Object.hpp\"\n#include \"objects\/objects.h\"\n\nusing namespace allpix;\n\nROOTObjectWriterModule::ROOTObjectWriterModule(Configuration& config, Messenger* messenger, GeometryManager* geo_mgr)\n : Module(config), geo_mgr_(geo_mgr) {\n \/\/ Bind to all messages\n messenger->registerListener(this, &ROOTObjectWriterModule::receive);\n}\n\/**\n * @note Objects cannot be stored in smart pointers due to internal ROOT logic\n *\/\nROOTObjectWriterModule::~ROOTObjectWriterModule() {\n \/\/ Delete all object pointers\n for(auto& index_data : write_list_) {\n delete index_data.second;\n }\n}\n\nvoid ROOTObjectWriterModule::init() {\n \/\/ Create output file\n output_file_name_ =\n createOutputFile(allpix::add_file_extension(config_.get<std::string>(\"file_name\", \"data\"), \"root\"), true);\n output_file_ = std::make_unique<TFile>(output_file_name_.c_str(), \"RECREATE\");\n output_file_->cd();\n\n \/\/ Read include and exclude list\n if(config_.has(\"include\") && config_.has(\"exclude\")) {\n throw InvalidValueError(config_, \"exclude\", \"include and exclude parameter are mutually exclusive\");\n } else if(config_.has(\"include\")) {\n auto inc_arr = config_.getArray<std::string>(\"include\");\n include_.insert(inc_arr.begin(), inc_arr.end());\n } else if(config_.has(\"exclude\")) {\n auto exc_arr = config_.getArray<std::string>(\"exclude\");\n exclude_.insert(exc_arr.begin(), exc_arr.end());\n }\n}\n\nvoid ROOTObjectWriterModule::receive(std::shared_ptr<BaseMessage> message, std::string message_name) { \/\/ NOLINT\n try {\n const BaseMessage* inst = message.get();\n std::string name_str = \" without a name\";\n if(!message_name.empty()) {\n name_str = \" named \" + message_name;\n }\n LOG(TRACE) << \"ROOT object writer received \" << allpix::demangle(typeid(*inst).name()) << name_str;\n\n \/\/ Get the detector name\n std::string detector_name;\n if(message->getDetector() != nullptr) {\n detector_name = message->getDetector()->getName();\n }\n\n \/\/ Read the object\n auto object_array = message->getObjectArray();\n if(!object_array.empty()) {\n keep_messages_.push_back(message);\n\n const Object& first_object = object_array[0];\n std::type_index type_idx = typeid(first_object);\n\n \/\/ Create a new branch of the correct type if this message was not received before\n auto index_tuple = std::make_tuple(type_idx, detector_name, message_name);\n if(write_list_.find(index_tuple) == write_list_.end()) {\n\n auto* cls = TClass::GetClass(typeid(first_object));\n\n \/\/ Remove the allpix prefix\n std::string class_name = cls->GetName();\n std::string apx_namespace = \"allpix::\";\n size_t ap_idx = class_name.find(apx_namespace);\n if(ap_idx != std::string::npos) {\n class_name.replace(ap_idx, apx_namespace.size(), \"\");\n }\n\n \/\/ Check if this message should be kept\n if((!include_.empty() && include_.find(class_name) == include_.end()) ||\n (!exclude_.empty() && exclude_.find(class_name) != exclude_.end())) {\n LOG(TRACE) << \"ROOT object writer ignored message with object \" << allpix::demangle(typeid(*inst).name())\n << \" because it has been excluded or not explicitly included\";\n return;\n }\n\n \/\/ Add vector of objects to write to the write list\n write_list_[index_tuple] = new std::vector<Object*>();\n auto addr = &write_list_[index_tuple];\n\n if(trees_.find(class_name) == trees_.end()) {\n \/\/ Create new tree\n output_file_->cd();\n trees_.emplace(\n class_name,\n std::make_unique<TTree>(class_name.c_str(), (std::string(\"Tree of \") + class_name).c_str()));\n }\n\n std::string branch_name = detector_name;\n if(!message_name.empty()) {\n branch_name += \"_\";\n branch_name += message_name;\n }\n\n trees_[class_name]->Bronch(\n branch_name.c_str(), (std::string(\"std::vector<\") + cls->GetName() + \"*>\").c_str(), addr);\n }\n\n \/\/ Fill the branch vector\n for(Object& object : object_array) {\n ++write_cnt_;\n write_list_[index_tuple]->push_back(&object);\n }\n }\n\n } catch(MessageWithoutObjectException& e) {\n const BaseMessage* inst = message.get();\n LOG(WARNING) << \"ROOT object writer cannot process message of type\" << allpix::demangle(typeid(*inst).name())\n << \" with name \" << message_name;\n }\n}\n\nvoid ROOTObjectWriterModule::run(unsigned int) {\n LOG(TRACE) << \"Writing new objects to tree\";\n output_file_->cd();\n\n \/\/ Fill the tree with the current received messages\n for(auto& tree : trees_) {\n tree.second->Fill();\n }\n\n \/\/ Clear the current message list\n for(auto& index_data : write_list_) {\n index_data.second->clear();\n }\n \/\/ Clear the messages we have to keep because they contain the internal pointers\n keep_messages_.clear();\n}\n\nvoid ROOTObjectWriterModule::finalize() {\n LOG(TRACE) << \"Writing objects to file\";\n output_file_->cd();\n\n int branch_count = 0;\n for(auto& tree : trees_) {\n \/\/ Update statistics\n branch_count += tree.second->GetListOfBranches()->GetEntries();\n }\n\n \/\/ Create main config directory\n TDirectory* config_dir = output_file_->mkdir(\"config\");\n config_dir->cd();\n\n \/\/ Get the config manager\n ConfigManager* conf_manager = getConfigManager();\n\n \/\/ Save the main configuration to the output file\n auto global_dir = config_dir->mkdir(\"Allpix\");\n LOG(TRACE) << \"Writing global configuration\";\n\n \/\/ Loop over all values in the global configuration\n for(auto& key_value : conf_manager->getGlobalConfiguration().getAll()) {\n global_dir->WriteObject(&key_value.second, key_value.first.c_str());\n }\n\n \/\/ Save the instance configuration to the output file\n for(auto& config : conf_manager->getInstanceConfigurations()) {\n \/\/ Create a new directory per section, using the unique module name\n auto unique_name = config.get<std::string>(\"unique_name\");\n auto section_dir = config_dir->mkdir(unique_name.c_str());\n LOG(TRACE) << \"Writing configuration for: \" << unique_name;\n\n \/\/ Loop over all values in the section\n for(auto& key_value : config.getAll()) {\n \/\/ Skip the unique name and input \/ output if empty\n if(key_value.first == \"unique_name\") {\n continue;\n }\n if((key_value.first == \"input\" || key_value.first == \"output\") && key_value.second.empty()) {\n continue;\n }\n section_dir->WriteObject(&key_value.second, key_value.first.c_str());\n }\n }\n\n \/\/ Save the detectors to the output file\n auto detectors_dir = output_file_->mkdir(\"detectors\");\n auto models_dir = output_file_->mkdir(\"models\");\n for(auto& detector : geo_mgr_->getDetectors()) {\n detectors_dir->cd();\n auto detector_dir = detectors_dir->mkdir(detector->getName().c_str());\n\n auto position = detector->getPosition();\n detector_dir->WriteObject(&position, \"position\");\n auto orientation = detector->getOrientation();\n detector_dir->WriteObject(&orientation, \"orientation\");\n\n \/\/ Store the detector model\n std::string model_name = \"model_\" + detector->getName();\n detector_dir->WriteObject(&model_name, \"type\");\n models_dir->cd();\n auto model_dir = models_dir->mkdir(model_name.c_str());\n\n \/\/ FIXME This saves the model every time again also for models that appear multiple times\n auto model_configs = detector->getModel()->getConfigurations();\n std::map<std::string, int> count_configs;\n for(auto& model_config : model_configs) {\n auto model_config_dir = model_dir;\n if(!model_config.getName().empty()) {\n model_config_dir = model_dir->mkdir(\n (model_config.getName() + \"_\" + std::to_string(count_configs[model_config.getName()])).c_str());\n count_configs[model_config.getName()]++;\n }\n\n for(auto& key_value : model_config.getAll()) {\n model_config_dir->WriteObject(&key_value.second, key_value.first.c_str());\n }\n }\n }\n\n \/\/ Finish writing to output file\n output_file_->Write();\n\n \/\/ Print statistics\n LOG(STATUS) << \"Wrote \" << write_cnt_ << \" objects to \" << branch_count << \" branches in file:\" << std::endl\n << output_file_name_;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ Copyright (c) 2017 The nanoFramework project contributors\n\/\/ Portions Copyright (c) Microsoft Corporation. All rights reserved.\n\/\/ See LICENSE file in the project root for full license information.\n\/\/\n\n\n#include <ch.h>\n#include <hal.h>\n#include <cmsis_os.h>\n\n#include <targetPAL.h>\n#include \"win_dev_gpio_native.h\"\n#include \"nf_rt_events_native.h\"\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ !!! KEEP IN SYNC WITH Windows.Devices.Gpio.GpioPinDriveMode (in managed code) !!! \/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nenum GpioPinDriveMode\n{\n GpioPinDriveMode_Input = 0,\n GpioPinDriveMode_InputPullDown,\n GpioPinDriveMode_InputPullUp,\n GpioPinDriveMode_Output,\n GpioPinDriveMode_OutputOpenDrain,\n GpioPinDriveMode_OutputOpenDrainPullUp,\n GpioPinDriveMode_OutputOpenSource,\n GpioPinDriveMode_OutputOpenSourcePullDown\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ !!! KEEP IN SYNC WITH Windows.Devices.Gpio.GpioPinValue (in managed code) !!! \/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nenum GpioPinValue\n{\n GpioPinValue_Low = 0,\n GpioPinValue_High,\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/ this timer is used to handle the debounce time\nstatic virtual_timer_t debounceTimer;\n\nvolatile uint16_t lastPadValue;\n\n\/\/ this is an utility function to get a ChibiOS PAL IoLine from our \"encoded\" pin number\nioline_t GetIoLine(int16_t pinNumber)\n{\n stm32_gpio_t* port = GPIO_PORT(pinNumber);\n int16_t pad = pinNumber % 16;\n\n return PAL_LINE(port, pad);\n\n}\n\nstatic void debounceTimer_Callback( void* arg )\n{\n CLR_RT_HeapBlock* pThis = (CLR_RT_HeapBlock*)arg;\n\n if(pThis == NULL)\n {\n \/\/ no Gpio pin here, leave now\n chSysUnlockFromISR();\n return;\n }\n\n \/\/ check if object has been disposed\n if(pThis[ Library_win_dev_gpio_native_Windows_Devices_Gpio_GpioPin::FIELD___disposedValue ].NumericByRef().u1 != 0)\n {\n \/\/ object has been disposed, leave now\n chSysUnlockFromISR();\n return;\n }\n \n \/\/ get pin number\n int16_t pinNumber = pThis[ Library_win_dev_gpio_native_Windows_Devices_Gpio_GpioPin::FIELD___pinNumber ].NumericByRefConst().s4;\n\n \/\/ read line\n uint16_t currentValue = palReadLine(GetIoLine(pinNumber));\n\n if(lastPadValue == currentValue)\n {\n \/\/ value hasn't change for debounce interval so this is a valid change\n \/\/ post a managed event with the current pin value\n PostManagedEvent( EVENT_GPIO, 0, pinNumber, currentValue );\n }\n}\n\nstatic void GpioEventCallback(void *arg)\n{\n CLR_RT_HeapBlock* pThis = (CLR_RT_HeapBlock*)arg;\n\n NATIVE_INTERRUPT_START\n\n chSysLockFromISR();\n\n \/\/CLR_RT_HeapBlock* pThis = channelPinMapping[channel];\n\n if(pThis == NULL)\n {\n \/\/ no Gpio pin here, leave now\n chSysUnlockFromISR();\n return;\n }\n\n \/\/ check if object has been disposed\n if(pThis[ Library_win_dev_gpio_native_Windows_Devices_Gpio_GpioPin::FIELD___disposedValue ].NumericByRef().u1 != 0)\n {\n \/\/ object has been disposed, leave now\n chSysUnlockFromISR();\n\n NATIVE_INTERRUPT_END\n\n return;\n }\n \n \/\/ get pin number and take the port and pad references from that one\n int16_t pinNumber = pThis[ Library_win_dev_gpio_native_Windows_Devices_Gpio_GpioPin::FIELD___pinNumber ].NumericByRefConst().s4;\n\n \/\/ get IoLine from pin number\n ioline_t ioLine = GetIoLine(pinNumber);\n\n \/\/ check if there is a debounce time set\n int64_t debounceTimeoutMilsec = (CLR_INT64_TEMP_CAST) pThis[ Library_win_dev_gpio_native_Windows_Devices_Gpio_GpioPin::FIELD___debounceTimeout ].NumericByRefConst().s8 \/ TIME_CONVERSION__TO_MILLISECONDS;\n \n if(debounceTimeoutMilsec > 0)\n {\n \/\/ debounce set, need to handle it\n\n if(chVTIsArmed(&debounceTimer))\n {\n \/\/ there is a debounce timer already running so this change in pin value should be discarded \n chSysUnlockFromISR();\n\n NATIVE_INTERRUPT_END\n \n return;\n }\n\n \/\/ read pad\n lastPadValue = palReadLine(ioLine);\n\n \/\/ setup timer\n chVTSetI(&debounceTimer, TIME_MS2I(debounceTimeoutMilsec), debounceTimer_Callback, pThis);\n }\n else\n {\n \/\/ post a managed event with the current pin reading\n PostManagedEvent( EVENT_GPIO, 0, pinNumber, palReadLine(ioLine) );\n }\n\n chSysUnlockFromISR();\n\n NATIVE_INTERRUPT_END\n \n}\n\nHRESULT Library_win_dev_gpio_native_Windows_Devices_Gpio_GpioPin::Read___WindowsDevicesGpioGpioPinValue( CLR_RT_StackFrame& stack )\n{\n NANOCLR_HEADER();\n {\n CLR_RT_HeapBlock* pThis = stack.This(); FAULT_ON_NULL(pThis);\n\n \/\/ check if object has been disposed\n if(pThis[ Library_win_dev_gpio_native_Windows_Devices_Gpio_GpioPin::FIELD___disposedValue ].NumericByRef().u1 != 0)\n {\n NANOCLR_SET_AND_LEAVE(CLR_E_OBJECT_DISPOSED);\n }\n\n stack.SetResult_I4( GetIoLine(pThis[ FIELD___pinNumber ].NumericByRefConst().s4) );\n }\n NANOCLR_NOCLEANUP();\n}\n\nHRESULT Library_win_dev_gpio_native_Windows_Devices_Gpio_GpioPin::DisposeNative___VOID( CLR_RT_StackFrame& stack )\n{\n NANOCLR_HEADER();\n {\n CLR_RT_HeapBlock* pThis = stack.This(); FAULT_ON_NULL(pThis);\n\n \/\/ get IoLine from pin number\n ioline_t ioLine = GetIoLine(pThis[ FIELD___pinNumber ].NumericByRefConst().s4);\n\n \/\/ disable the EXT interrupt channel\n \/\/ it's OK to do always this, no matter if it's enabled or not\n palDisableLineEvent(ioLine);\n\n \/\/ set pin to input to save power\n palSetLineMode(ioLine, PAL_MODE_INPUT);\n }\n NANOCLR_NOCLEANUP();\n}\n\nHRESULT Library_win_dev_gpio_native_Windows_Devices_Gpio_GpioPin::NativeIsDriveModeSupported___BOOLEAN__WindowsDevicesGpioGpioPinDriveMode( CLR_RT_StackFrame& stack )\n{\n NANOCLR_HEADER();\n {\n GpioPinDriveMode driveMode = (GpioPinDriveMode)stack.Arg1().NumericByRef().s4;\n\n bool driveModeSupported = false;\n\n \/\/ check if the requested drive mode is support by ChibiOS config\n if ((driveMode == GpioPinDriveMode_Input) ||\n (driveMode == GpioPinDriveMode_InputPullDown) ||\n (driveMode == GpioPinDriveMode_InputPullUp) ||\n (driveMode == GpioPinDriveMode_Output) ||\n (driveMode == GpioPinDriveMode_OutputOpenDrain))\n {\n driveModeSupported = true;\n }\n\n \/\/ Return value to the managed application\n stack.SetResult_Boolean( driveModeSupported ) ;\n }\n NANOCLR_NOCLEANUP();\n}\n\nHRESULT Library_win_dev_gpio_native_Windows_Devices_Gpio_GpioPin::NativeSetDriveMode___VOID__WindowsDevicesGpioGpioPinDriveMode( CLR_RT_StackFrame& stack )\n{\n NANOCLR_HEADER();\n {\n CLR_RT_HeapBlock* pThis = stack.This(); FAULT_ON_NULL(pThis);\n\n if(pThis[ Library_win_dev_gpio_native_Windows_Devices_Gpio_GpioPin::FIELD___disposedValue ].NumericByRef().u1 != 0)\n {\n NANOCLR_SET_AND_LEAVE(CLR_E_OBJECT_DISPOSED);\n }\n\n \/\/ get IoLine from pin number\n ioline_t ioLine = GetIoLine(pThis[ FIELD___pinNumber ].NumericByRefConst().s4);\n \n \/\/ it's better cast this this to the appropriate enum\n GpioPinDriveMode driveMode = (GpioPinDriveMode)stack.Arg1().NumericByRef().s4;\n\n \/\/ check if drive mode is input\n bool driveModeIsInput = false;\n\n if( driveMode == GpioPinDriveMode_Input ||\n driveMode == GpioPinDriveMode_InputPullDown ||\n driveMode == GpioPinDriveMode_InputPullUp)\n {\n driveModeIsInput = true;\n }\n\n \/\/ flag to signal that interrupts need to be setup\n bool setupInterrupt = false;\n\n \/\/ flag to determine if there are any callbacks registered in managed code\n bool callbacksRegistered = (pThis[ FIELD___callbacks ].Dereference() != NULL);\n\n switch (driveMode)\n {\n case GpioPinDriveMode_Input:\n palSetLineMode(ioLine, PAL_MODE_INPUT);\n setupInterrupt = true;\n break;\n\n case GpioPinDriveMode_InputPullDown:\n palSetLineMode(ioLine, PAL_MODE_INPUT_PULLDOWN);\n setupInterrupt = true;\n break;\n\n case GpioPinDriveMode_InputPullUp:\n palSetLineMode(ioLine, PAL_MODE_INPUT_PULLUP);\n setupInterrupt = true;\n break;\n\n case GpioPinDriveMode_Output:\n palSetLineMode(ioLine, PAL_MODE_OUTPUT_PUSHPULL);\n break;\n\n case GpioPinDriveMode_OutputOpenDrain:\n palSetLineMode(ioLine, PAL_MODE_OUTPUT_OPENDRAIN);\n break;\n\n default:\n \/\/ all other modes are NOT supported\n NANOCLR_SET_AND_LEAVE(CLR_E_INVALID_PARAMETER);\n break;\n }\n\n \/\/ if drive mode is output, read the pad to update the managed field _lastOutputValue\n if(!driveModeIsInput)\n {\n pThis[ FIELD___lastOutputValue ].NumericByRef().s4 = palReadLine(ioLine);\n }\n\n if(callbacksRegistered && setupInterrupt)\n {\n \/\/ there are callbacks registered and...\n \/\/ the drive mode is input so need to setup the interrupt\n\n \/\/ save pin\n \/\/channelPinMapping[pad] = pThis;\n\n palEnableLineEvent(ioLine, PAL_EVENT_MODE_BOTH_EDGES);\n palSetLineCallback(ioLine, GpioEventCallback, pThis);\n\n \/\/ protect this from GC so that the callback is where it's supposed to\n CLR_RT_ProtectFromGC gc( *pThis );\n \n \/\/ read pad and store current value to check on debounce callback\n lastPadValue = palReadLine(ioLine);\n }\n }\n NANOCLR_NOCLEANUP();\n}\n\nHRESULT Library_win_dev_gpio_native_Windows_Devices_Gpio_GpioPin::NativeInit___BOOLEAN__I4( CLR_RT_StackFrame& stack )\n{\n NANOCLR_HEADER();\n {\n int16_t pinNumber = stack.Arg1().NumericByRef().s4;\n\n \/\/ TODO is probably a good idea keep track of the used pins, so we can check that here\n \/\/ TODO is probably a good idea to check if this pin exists\n\n \/\/ Return value to the managed application\n stack.SetResult_Boolean(true );\n }\n NANOCLR_NOCLEANUP();\n}\n\nHRESULT Library_win_dev_gpio_native_Windows_Devices_Gpio_GpioPin::NativeSetDebounceTimeout___VOID( CLR_RT_StackFrame& stack )\n{\n NANOCLR_HEADER();\n\n \/\/ nothing to do here as the debounce timeout is grabbed from the managed object when required\n\n NANOCLR_NOCLEANUP();\n}\n\nHRESULT Library_win_dev_gpio_native_Windows_Devices_Gpio_GpioPin::WriteNative___VOID__WindowsDevicesGpioGpioPinValue( CLR_RT_StackFrame& stack )\n{\n NANOCLR_HEADER();\n {\n CLR_RT_HeapBlock* pThis = stack.This(); FAULT_ON_NULL(pThis);\n\n \/\/ check if object has been disposed\n if(pThis[ Library_win_dev_gpio_native_Windows_Devices_Gpio_GpioPin::FIELD___disposedValue ].NumericByRef().u1 != 0)\n {\n NANOCLR_SET_AND_LEAVE(CLR_E_OBJECT_DISPOSED);\n }\n\n \/\/ get IoLine from pin number\n ioline_t ioLine = GetIoLine(pThis[ FIELD___pinNumber ].NumericByRefConst().s4);\n\n GpioPinDriveMode driveMode = (GpioPinDriveMode)pThis[ FIELD___driveMode ].NumericByRefConst().s4;\n\n GpioPinValue state = (GpioPinValue)stack.Arg1().NumericByRef().s4;\n\n \/\/ sanity check for drive mode set to output so we don't mess up writing to an input pin\n if ((driveMode == GpioPinDriveMode_Output) ||\n (driveMode == GpioPinDriveMode_OutputOpenDrain) ||\n (driveMode == GpioPinDriveMode_OutputOpenDrainPullUp) ||\n (driveMode == GpioPinDriveMode_OutputOpenSource) ||\n (driveMode == GpioPinDriveMode_OutputOpenSourcePullDown))\n {\n palWriteLine(ioLine, state);\n }\n else\n {\n NANOCLR_SET_AND_LEAVE(CLR_E_INVALID_PARAMETER);\n }\n }\n NANOCLR_NOCLEANUP();\n}\n\nHRESULT Library_win_dev_gpio_native_Windows_Devices_Gpio_GpioPin::NativeSetAlternateFunction___VOID__I4( CLR_RT_StackFrame& stack )\n{\n NANOCLR_HEADER();\n {\n CLR_RT_HeapBlock* pThis = stack.This(); FAULT_ON_NULL(pThis);\n\n \/\/ check if object has been disposed\n if(pThis[ Library_win_dev_gpio_native_Windows_Devices_Gpio_GpioPin::FIELD___disposedValue ].NumericByRef().u1 != 0)\n {\n NANOCLR_SET_AND_LEAVE(CLR_E_OBJECT_DISPOSED);\n }\n\n \/\/ get IoLine from pin number\n ioline_t ioLine = GetIoLine(pThis[ FIELD___pinNumber ].NumericByRefConst().s4);\n\n \/\/ get alternate function argument\n\t\tint32_t alternateFunction = stack.Arg1().NumericByRef().s4;\n\n palSetLineMode(ioLine, PAL_MODE_ALTERNATE(alternateFunction));\n\n }\n NANOCLR_NOCLEANUP();\n}\n<commit_msg>Correct code reading Gpio value (#635)<commit_after>\/\/\n\/\/ Copyright (c) 2017 The nanoFramework project contributors\n\/\/ Portions Copyright (c) Microsoft Corporation. All rights reserved.\n\/\/ See LICENSE file in the project root for full license information.\n\/\/\n\n\n#include <ch.h>\n#include <hal.h>\n#include <cmsis_os.h>\n\n#include <targetPAL.h>\n#include \"win_dev_gpio_native.h\"\n#include \"nf_rt_events_native.h\"\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ !!! KEEP IN SYNC WITH Windows.Devices.Gpio.GpioPinDriveMode (in managed code) !!! \/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nenum GpioPinDriveMode\n{\n GpioPinDriveMode_Input = 0,\n GpioPinDriveMode_InputPullDown,\n GpioPinDriveMode_InputPullUp,\n GpioPinDriveMode_Output,\n GpioPinDriveMode_OutputOpenDrain,\n GpioPinDriveMode_OutputOpenDrainPullUp,\n GpioPinDriveMode_OutputOpenSource,\n GpioPinDriveMode_OutputOpenSourcePullDown\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ !!! KEEP IN SYNC WITH Windows.Devices.Gpio.GpioPinValue (in managed code) !!! \/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nenum GpioPinValue\n{\n GpioPinValue_Low = 0,\n GpioPinValue_High,\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/ this timer is used to handle the debounce time\nstatic virtual_timer_t debounceTimer;\n\nvolatile uint16_t lastPadValue;\n\n\/\/ this is an utility function to get a ChibiOS PAL IoLine from our \"encoded\" pin number\nioline_t GetIoLine(int16_t pinNumber)\n{\n stm32_gpio_t* port = GPIO_PORT(pinNumber);\n int16_t pad = pinNumber % 16;\n\n return PAL_LINE(port, pad);\n\n}\n\nstatic void debounceTimer_Callback( void* arg )\n{\n CLR_RT_HeapBlock* pThis = (CLR_RT_HeapBlock*)arg;\n\n if(pThis == NULL)\n {\n \/\/ no Gpio pin here, leave now\n chSysUnlockFromISR();\n return;\n }\n\n \/\/ check if object has been disposed\n if(pThis[ Library_win_dev_gpio_native_Windows_Devices_Gpio_GpioPin::FIELD___disposedValue ].NumericByRef().u1 != 0)\n {\n \/\/ object has been disposed, leave now\n chSysUnlockFromISR();\n return;\n }\n \n \/\/ get pin number\n int16_t pinNumber = pThis[ Library_win_dev_gpio_native_Windows_Devices_Gpio_GpioPin::FIELD___pinNumber ].NumericByRefConst().s4;\n\n \/\/ read line\n uint16_t currentValue = palReadLine(GetIoLine(pinNumber));\n\n if(lastPadValue == currentValue)\n {\n \/\/ value hasn't change for debounce interval so this is a valid change\n \/\/ post a managed event with the current pin value\n PostManagedEvent( EVENT_GPIO, 0, pinNumber, currentValue );\n }\n}\n\nstatic void GpioEventCallback(void *arg)\n{\n CLR_RT_HeapBlock* pThis = (CLR_RT_HeapBlock*)arg;\n\n NATIVE_INTERRUPT_START\n\n chSysLockFromISR();\n\n \/\/CLR_RT_HeapBlock* pThis = channelPinMapping[channel];\n\n if(pThis == NULL)\n {\n \/\/ no Gpio pin here, leave now\n chSysUnlockFromISR();\n return;\n }\n\n \/\/ check if object has been disposed\n if(pThis[ Library_win_dev_gpio_native_Windows_Devices_Gpio_GpioPin::FIELD___disposedValue ].NumericByRef().u1 != 0)\n {\n \/\/ object has been disposed, leave now\n chSysUnlockFromISR();\n\n NATIVE_INTERRUPT_END\n\n return;\n }\n \n \/\/ get pin number and take the port and pad references from that one\n int16_t pinNumber = pThis[ Library_win_dev_gpio_native_Windows_Devices_Gpio_GpioPin::FIELD___pinNumber ].NumericByRefConst().s4;\n\n \/\/ get IoLine from pin number\n ioline_t ioLine = GetIoLine(pinNumber);\n\n \/\/ check if there is a debounce time set\n int64_t debounceTimeoutMilsec = (CLR_INT64_TEMP_CAST) pThis[ Library_win_dev_gpio_native_Windows_Devices_Gpio_GpioPin::FIELD___debounceTimeout ].NumericByRefConst().s8 \/ TIME_CONVERSION__TO_MILLISECONDS;\n \n if(debounceTimeoutMilsec > 0)\n {\n \/\/ debounce set, need to handle it\n\n if(chVTIsArmed(&debounceTimer))\n {\n \/\/ there is a debounce timer already running so this change in pin value should be discarded \n chSysUnlockFromISR();\n\n NATIVE_INTERRUPT_END\n \n return;\n }\n\n \/\/ read pad\n lastPadValue = palReadLine(ioLine);\n\n \/\/ setup timer\n chVTSetI(&debounceTimer, TIME_MS2I(debounceTimeoutMilsec), debounceTimer_Callback, pThis);\n }\n else\n {\n \/\/ post a managed event with the current pin reading\n PostManagedEvent( EVENT_GPIO, 0, pinNumber, palReadLine(ioLine) );\n }\n\n chSysUnlockFromISR();\n\n NATIVE_INTERRUPT_END\n \n}\n\nHRESULT Library_win_dev_gpio_native_Windows_Devices_Gpio_GpioPin::Read___WindowsDevicesGpioGpioPinValue( CLR_RT_StackFrame& stack )\n{\n NANOCLR_HEADER();\n {\n CLR_RT_HeapBlock* pThis = stack.This(); FAULT_ON_NULL(pThis);\n\n \/\/ check if object has been disposed\n if(pThis[ Library_win_dev_gpio_native_Windows_Devices_Gpio_GpioPin::FIELD___disposedValue ].NumericByRef().u1 != 0)\n {\n NANOCLR_SET_AND_LEAVE(CLR_E_OBJECT_DISPOSED);\n }\n\n stack.SetResult_I4( palReadLine(GetIoLine(pThis[ FIELD___pinNumber ].NumericByRefConst().s4)) );\n }\n NANOCLR_NOCLEANUP();\n}\n\nHRESULT Library_win_dev_gpio_native_Windows_Devices_Gpio_GpioPin::DisposeNative___VOID( CLR_RT_StackFrame& stack )\n{\n NANOCLR_HEADER();\n {\n CLR_RT_HeapBlock* pThis = stack.This(); FAULT_ON_NULL(pThis);\n\n \/\/ get IoLine from pin number\n ioline_t ioLine = GetIoLine(pThis[ FIELD___pinNumber ].NumericByRefConst().s4);\n\n \/\/ disable the EXT interrupt channel\n \/\/ it's OK to do always this, no matter if it's enabled or not\n palDisableLineEvent(ioLine);\n\n \/\/ set pin to input to save power\n palSetLineMode(ioLine, PAL_MODE_INPUT);\n }\n NANOCLR_NOCLEANUP();\n}\n\nHRESULT Library_win_dev_gpio_native_Windows_Devices_Gpio_GpioPin::NativeIsDriveModeSupported___BOOLEAN__WindowsDevicesGpioGpioPinDriveMode( CLR_RT_StackFrame& stack )\n{\n NANOCLR_HEADER();\n {\n GpioPinDriveMode driveMode = (GpioPinDriveMode)stack.Arg1().NumericByRef().s4;\n\n bool driveModeSupported = false;\n\n \/\/ check if the requested drive mode is support by ChibiOS config\n if ((driveMode == GpioPinDriveMode_Input) ||\n (driveMode == GpioPinDriveMode_InputPullDown) ||\n (driveMode == GpioPinDriveMode_InputPullUp) ||\n (driveMode == GpioPinDriveMode_Output) ||\n (driveMode == GpioPinDriveMode_OutputOpenDrain))\n {\n driveModeSupported = true;\n }\n\n \/\/ Return value to the managed application\n stack.SetResult_Boolean( driveModeSupported ) ;\n }\n NANOCLR_NOCLEANUP();\n}\n\nHRESULT Library_win_dev_gpio_native_Windows_Devices_Gpio_GpioPin::NativeSetDriveMode___VOID__WindowsDevicesGpioGpioPinDriveMode( CLR_RT_StackFrame& stack )\n{\n NANOCLR_HEADER();\n {\n CLR_RT_HeapBlock* pThis = stack.This(); FAULT_ON_NULL(pThis);\n\n if(pThis[ Library_win_dev_gpio_native_Windows_Devices_Gpio_GpioPin::FIELD___disposedValue ].NumericByRef().u1 != 0)\n {\n NANOCLR_SET_AND_LEAVE(CLR_E_OBJECT_DISPOSED);\n }\n\n \/\/ get IoLine from pin number\n ioline_t ioLine = GetIoLine(pThis[ FIELD___pinNumber ].NumericByRefConst().s4);\n \n \/\/ it's better cast this this to the appropriate enum\n GpioPinDriveMode driveMode = (GpioPinDriveMode)stack.Arg1().NumericByRef().s4;\n\n \/\/ check if drive mode is input\n bool driveModeIsInput = false;\n\n if( driveMode == GpioPinDriveMode_Input ||\n driveMode == GpioPinDriveMode_InputPullDown ||\n driveMode == GpioPinDriveMode_InputPullUp)\n {\n driveModeIsInput = true;\n }\n\n \/\/ flag to signal that interrupts need to be setup\n bool setupInterrupt = false;\n\n \/\/ flag to determine if there are any callbacks registered in managed code\n bool callbacksRegistered = (pThis[ FIELD___callbacks ].Dereference() != NULL);\n\n switch (driveMode)\n {\n case GpioPinDriveMode_Input:\n palSetLineMode(ioLine, PAL_MODE_INPUT);\n setupInterrupt = true;\n break;\n\n case GpioPinDriveMode_InputPullDown:\n palSetLineMode(ioLine, PAL_MODE_INPUT_PULLDOWN);\n setupInterrupt = true;\n break;\n\n case GpioPinDriveMode_InputPullUp:\n palSetLineMode(ioLine, PAL_MODE_INPUT_PULLUP);\n setupInterrupt = true;\n break;\n\n case GpioPinDriveMode_Output:\n palSetLineMode(ioLine, PAL_MODE_OUTPUT_PUSHPULL);\n break;\n\n case GpioPinDriveMode_OutputOpenDrain:\n palSetLineMode(ioLine, PAL_MODE_OUTPUT_OPENDRAIN);\n break;\n\n default:\n \/\/ all other modes are NOT supported\n NANOCLR_SET_AND_LEAVE(CLR_E_INVALID_PARAMETER);\n break;\n }\n\n \/\/ if drive mode is output, read the pad to update the managed field _lastOutputValue\n if(!driveModeIsInput)\n {\n pThis[ FIELD___lastOutputValue ].NumericByRef().s4 = palReadLine(ioLine);\n }\n\n if(callbacksRegistered && setupInterrupt)\n {\n \/\/ there are callbacks registered and...\n \/\/ the drive mode is input so need to setup the interrupt\n\n \/\/ save pin\n \/\/channelPinMapping[pad] = pThis;\n\n palEnableLineEvent(ioLine, PAL_EVENT_MODE_BOTH_EDGES);\n palSetLineCallback(ioLine, GpioEventCallback, pThis);\n\n \/\/ protect this from GC so that the callback is where it's supposed to\n CLR_RT_ProtectFromGC gc( *pThis );\n \n \/\/ read pad and store current value to check on debounce callback\n lastPadValue = palReadLine(ioLine);\n }\n }\n NANOCLR_NOCLEANUP();\n}\n\nHRESULT Library_win_dev_gpio_native_Windows_Devices_Gpio_GpioPin::NativeInit___BOOLEAN__I4( CLR_RT_StackFrame& stack )\n{\n NANOCLR_HEADER();\n {\n int16_t pinNumber = stack.Arg1().NumericByRef().s4;\n\n \/\/ TODO is probably a good idea keep track of the used pins, so we can check that here\n \/\/ TODO is probably a good idea to check if this pin exists\n\n \/\/ Return value to the managed application\n stack.SetResult_Boolean(true );\n }\n NANOCLR_NOCLEANUP();\n}\n\nHRESULT Library_win_dev_gpio_native_Windows_Devices_Gpio_GpioPin::NativeSetDebounceTimeout___VOID( CLR_RT_StackFrame& stack )\n{\n NANOCLR_HEADER();\n\n \/\/ nothing to do here as the debounce timeout is grabbed from the managed object when required\n\n NANOCLR_NOCLEANUP();\n}\n\nHRESULT Library_win_dev_gpio_native_Windows_Devices_Gpio_GpioPin::WriteNative___VOID__WindowsDevicesGpioGpioPinValue( CLR_RT_StackFrame& stack )\n{\n NANOCLR_HEADER();\n {\n CLR_RT_HeapBlock* pThis = stack.This(); FAULT_ON_NULL(pThis);\n\n \/\/ check if object has been disposed\n if(pThis[ Library_win_dev_gpio_native_Windows_Devices_Gpio_GpioPin::FIELD___disposedValue ].NumericByRef().u1 != 0)\n {\n NANOCLR_SET_AND_LEAVE(CLR_E_OBJECT_DISPOSED);\n }\n\n \/\/ get IoLine from pin number\n ioline_t ioLine = GetIoLine(pThis[ FIELD___pinNumber ].NumericByRefConst().s4);\n\n GpioPinDriveMode driveMode = (GpioPinDriveMode)pThis[ FIELD___driveMode ].NumericByRefConst().s4;\n\n GpioPinValue state = (GpioPinValue)stack.Arg1().NumericByRef().s4;\n\n \/\/ sanity check for drive mode set to output so we don't mess up writing to an input pin\n if ((driveMode == GpioPinDriveMode_Output) ||\n (driveMode == GpioPinDriveMode_OutputOpenDrain) ||\n (driveMode == GpioPinDriveMode_OutputOpenDrainPullUp) ||\n (driveMode == GpioPinDriveMode_OutputOpenSource) ||\n (driveMode == GpioPinDriveMode_OutputOpenSourcePullDown))\n {\n palWriteLine(ioLine, state);\n }\n else\n {\n NANOCLR_SET_AND_LEAVE(CLR_E_INVALID_PARAMETER);\n }\n }\n NANOCLR_NOCLEANUP();\n}\n\nHRESULT Library_win_dev_gpio_native_Windows_Devices_Gpio_GpioPin::NativeSetAlternateFunction___VOID__I4( CLR_RT_StackFrame& stack )\n{\n NANOCLR_HEADER();\n {\n CLR_RT_HeapBlock* pThis = stack.This(); FAULT_ON_NULL(pThis);\n\n \/\/ check if object has been disposed\n if(pThis[ Library_win_dev_gpio_native_Windows_Devices_Gpio_GpioPin::FIELD___disposedValue ].NumericByRef().u1 != 0)\n {\n NANOCLR_SET_AND_LEAVE(CLR_E_OBJECT_DISPOSED);\n }\n\n \/\/ get IoLine from pin number\n ioline_t ioLine = GetIoLine(pThis[ FIELD___pinNumber ].NumericByRefConst().s4);\n\n \/\/ get alternate function argument\n\t\tint32_t alternateFunction = stack.Arg1().NumericByRef().s4;\n\n palSetLineMode(ioLine, PAL_MODE_ALTERNATE(alternateFunction));\n\n }\n NANOCLR_NOCLEANUP();\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ RemotePhotoTool - remote camera control software\n\/\/ Copyright (C) 2008-2014 Michael Fink\n\/\/\n\/\/\/ \\file Variant.cpp Canon control - Variant data\n\/\/\n\n\/\/ includes\n#include \"StdAfx.h\"\n#include \"Variant.hpp\"\n\nVariant::Variant() throw()\n:m_enType(typeInvalid),\n m_bIsArray(false)\n{\n}\n\nCString Variant::ToString() const\n{\n CString cszValue;\n\n if (m_bIsArray)\n {\n switch (m_enType)\n {\n case typeUInt8:\n {\n CString cszTemp;\n std::vector<unsigned char> vecData = GetArray<unsigned char>();\n for (size_t i=0, iMax = vecData.size(); i<iMax; i++)\n {\n cszTemp.Format(_T(\"%s%02x\"), i == 0 ? _T(\"\") : _T(\" \"), vecData[i]);\n cszValue += cszTemp;\n }\n }\n break;\n\n case typeUInt16:\n {\n CString cszTemp;\n std::vector<unsigned short> vecData = GetArray<unsigned short>();\n for (size_t i = 0, iMax = vecData.size(); i<iMax; i++)\n {\n cszTemp.Format(_T(\"%s%04x\"), i == 0 ? _T(\"\") : _T(\" \"), vecData[i]);\n cszValue += cszTemp;\n }\n }\n break;\n\n case typeUInt32:\n {\n CString cszTemp;\n std::vector<unsigned int> vecData = GetArray<unsigned int>();\n for (size_t i=0, iMax = vecData.size(); i<iMax; i++)\n {\n cszTemp.Format(_T(\"%s%08x\"), i == 0 ? _T(\"\") : _T(\" \"), vecData[i]);\n cszValue += cszTemp;\n }\n }\n break;\n\n case typeInt32:\n {\n CString cszTemp;\n std::vector<int> vecData = GetArray<int>();\n for (size_t i=0, iMax = vecData.size(); i<iMax; i++)\n {\n cszTemp.Format(_T(\"%s%i\"), i == 0 ? _T(\"\") : _T(\" \"), vecData[i]);\n cszValue += cszTemp;\n }\n }\n break;\n default:\n ATLASSERT(false);\n cszValue = _T(\"??? (array)\");\n break;\n }\n }\n else\n switch (m_enType)\n {\n case typeBool:\n cszValue = Get<bool>() ? _T(\"yes\") : _T(\"no\");\n break;\n\n case typeString:\n cszValue = Get<CString>();\n break;\n\n case typeInt8:\n cszValue.Format(_T(\"%i\"), Get<char>());\n break;\n\n case typeUInt8:\n cszValue.Format(_T(\"%02x\"), Get<unsigned char>());\n break;\n\n case typeInt16:\n cszValue.Format(_T(\"%i\"), Get<short>());\n break;\n\n case typeUInt16:\n cszValue.Format(_T(\"%04x\"), Get<unsigned short>());\n break;\n\n case typeInt32:\n cszValue.Format(_T(\"%i\"), Get<int>());\n break;\n\n case typeUInt32:\n cszValue.Format(_T(\"%08x\"), Get<unsigned int>());\n break;\n\n case typeDouble:\n cszValue.Format(_T(\"%f\"), Get<double>());\n break;\n\n case typeInvalid:\n cszValue = _T(\"invalid type\");\n break;\n\n case typeInt64:\n case typeUInt64:\n case typeFloat:\n case typeByteBlock:\n case typeRational:\n case typePoint:\n case typeRect:\n case typeTime:\n \/\/ not implement\n\n default:\n ATLASSERT(false);\n cszValue = _T(\"???\");\n break;\n }\n return cszValue;\n}\n\nLPCTSTR Variant::TypeAsString(VariantType vt) throw()\n{\n switch(vt)\n {\n case typeBool: return _T(\"Bool\");\n case typeString: return _T(\"String\");\n case typeInt8: return _T(\"Int8\");\n case typeUInt8: return _T(\"UInt8\");\n case typeInt16: return _T(\"Int16\");\n case typeUInt16: return _T(\"UInt16\");\n case typeInt32: return _T(\"Int32\");\n case typeUInt32: return _T(\"UInt32\");\n case typeInt64: return _T(\"Int64\");\n case typeUInt64: return _T(\"UInt64\");\n case typeFloat: return _T(\"Float\");\n case typeDouble: return _T(\"Double\");\n case typeByteBlock: return _T(\"ByteBlock\");\n case typeRational: return _T(\"Rational\");\n case typePoint: return _T(\"Point\");\n case typeRect: return _T(\"Rect\");\n case typeTime: return _T(\"Time\");\n case typeInvalid: return _T(\"Invalid\");\n default:\n ATLASSERT(false);\n return _T(\"???\");\n }\n}\n<commit_msg>added formatting float types in Variant<commit_after>\/\/\n\/\/ RemotePhotoTool - remote camera control software\n\/\/ Copyright (C) 2008-2014 Michael Fink\n\/\/\n\/\/\/ \\file Variant.cpp Canon control - Variant data\n\/\/\n\n\/\/ includes\n#include \"StdAfx.h\"\n#include \"Variant.hpp\"\n\nVariant::Variant() throw()\n:m_enType(typeInvalid),\n m_bIsArray(false)\n{\n}\n\nCString Variant::ToString() const\n{\n CString cszValue;\n\n if (m_bIsArray)\n {\n switch (m_enType)\n {\n case typeUInt8:\n {\n CString cszTemp;\n std::vector<unsigned char> vecData = GetArray<unsigned char>();\n for (size_t i=0, iMax = vecData.size(); i<iMax; i++)\n {\n cszTemp.Format(_T(\"%s%02x\"), i == 0 ? _T(\"\") : _T(\" \"), vecData[i]);\n cszValue += cszTemp;\n }\n }\n break;\n\n case typeUInt16:\n {\n CString cszTemp;\n std::vector<unsigned short> vecData = GetArray<unsigned short>();\n for (size_t i = 0, iMax = vecData.size(); i<iMax; i++)\n {\n cszTemp.Format(_T(\"%s%04x\"), i == 0 ? _T(\"\") : _T(\" \"), vecData[i]);\n cszValue += cszTemp;\n }\n }\n break;\n\n case typeUInt32:\n {\n CString cszTemp;\n std::vector<unsigned int> vecData = GetArray<unsigned int>();\n for (size_t i=0, iMax = vecData.size(); i<iMax; i++)\n {\n cszTemp.Format(_T(\"%s%08x\"), i == 0 ? _T(\"\") : _T(\" \"), vecData[i]);\n cszValue += cszTemp;\n }\n }\n break;\n\n case typeInt32:\n {\n CString cszTemp;\n std::vector<int> vecData = GetArray<int>();\n for (size_t i=0, iMax = vecData.size(); i<iMax; i++)\n {\n cszTemp.Format(_T(\"%s%i\"), i == 0 ? _T(\"\") : _T(\" \"), vecData[i]);\n cszValue += cszTemp;\n }\n }\n break;\n default:\n ATLASSERT(false);\n cszValue = _T(\"??? (array)\");\n break;\n }\n }\n else\n switch (m_enType)\n {\n case typeBool:\n cszValue = Get<bool>() ? _T(\"yes\") : _T(\"no\");\n break;\n\n case typeString:\n cszValue = Get<CString>();\n break;\n\n case typeInt8:\n cszValue.Format(_T(\"%i\"), Get<char>());\n break;\n\n case typeUInt8:\n cszValue.Format(_T(\"%02x\"), Get<unsigned char>());\n break;\n\n case typeInt16:\n cszValue.Format(_T(\"%i\"), Get<short>());\n break;\n\n case typeUInt16:\n cszValue.Format(_T(\"%04x\"), Get<unsigned short>());\n break;\n\n case typeInt32:\n cszValue.Format(_T(\"%i\"), Get<int>());\n break;\n\n case typeUInt32:\n cszValue.Format(_T(\"%08x\"), Get<unsigned int>());\n break;\n\n case typeDouble:\n cszValue.Format(_T(\"%f\"), Get<double>());\n break;\n\n case typeFloat: \/\/ used in gPhoto2\n cszValue.Format(_T(\"%f\"), Get<float>());\n break;\n\n case typeInvalid:\n cszValue = _T(\"invalid type\");\n break;\n\n case typeInt64:\n case typeUInt64:\n case typeByteBlock:\n case typeRational:\n case typePoint:\n case typeRect:\n case typeTime:\n \/\/ not implement\n\n default:\n ATLASSERT(false);\n cszValue = _T(\"???\");\n break;\n }\n return cszValue;\n}\n\nLPCTSTR Variant::TypeAsString(VariantType vt) throw()\n{\n switch(vt)\n {\n case typeBool: return _T(\"Bool\");\n case typeString: return _T(\"String\");\n case typeInt8: return _T(\"Int8\");\n case typeUInt8: return _T(\"UInt8\");\n case typeInt16: return _T(\"Int16\");\n case typeUInt16: return _T(\"UInt16\");\n case typeInt32: return _T(\"Int32\");\n case typeUInt32: return _T(\"UInt32\");\n case typeInt64: return _T(\"Int64\");\n case typeUInt64: return _T(\"UInt64\");\n case typeFloat: return _T(\"Float\");\n case typeDouble: return _T(\"Double\");\n case typeByteBlock: return _T(\"ByteBlock\");\n case typeRational: return _T(\"Rational\");\n case typePoint: return _T(\"Point\");\n case typeRect: return _T(\"Rect\");\n case typeTime: return _T(\"Time\");\n case typeInvalid: return _T(\"Invalid\");\n default:\n ATLASSERT(false);\n return _T(\"???\");\n }\n}\n<|endoftext|>"} {"text":"<commit_before>#ifndef DOMStringImpl_HEADER_GUARD_\n#define DOMStringImpl_HEADER_GUARD_\n\n\/*\n * The Apache Software License, Version 1.1\n * \n * Copyright (c) 1999 The Apache Software Foundation. All rights \n * reserved.\n * \n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n * \n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer. \n * \n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in\n * the documentation and\/or other materials provided with the\n * distribution.\n * \n * 3. The end-user documentation included with the redistribution,\n * if any, must include the following acknowledgment: \n * \"This product includes software developed by the\n * Apache Software Foundation (http:\/\/www.apache.org\/).\"\n * Alternately, this acknowledgment may appear in the software itself,\n * if and wherever such third-party acknowledgments normally appear.\n * \n * 4. The names \"Xerces\" and \"Apache Software Foundation\" must\n * not be used to endorse or promote products derived from this\n * software without prior written permission. For written \n * permission, please contact apache\\@apache.org.\n * \n * 5. Products derived from this software may not be called \"Apache\",\n * nor may \"Apache\" appear in their name, without prior written\n * permission of the Apache Software Foundation.\n * \n * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED\n * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR\n * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF\n * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT\n * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n * ====================================================================\n * \n * This software consists of voluntary contributions made by many\n * individuals on behalf of the Apache Software Foundation, and was\n * originally based on software copyright (c) 1999, International\n * Business Machines, Inc., http:\/\/www.ibm.com . For more information\n * on the Apache Software Foundation, please see\n * <http:\/\/www.apache.org\/>.\n *\/\n\n\/**\n * $Log$\n * Revision 1.1 2000\/01\/05 22:16:26 robweir\n * Move DOMString implementation class declarations into a new\n * file: DOMStringImpl.hpp. Include this header in DOMString.hpp\n * for XML_DEBUG builds so the underlying character array will be\n * visible in the debugger. <robert_weir@lotus.com>\n *\n *\n *\/\n\n\n\/\/\n\/\/ This file is part of the internal implementation of the C++ XML DOM.\n\/\/ It should NOT be included or used directly by application programs.\n\/\/\n\n\n#include <util\/XML4CDefs.hpp>\n\n\nclass DOMStringData\n{\npublic:\n int fBufferLength;\n int fRefCount;\n XMLCh fData[1];\n \n static DOMStringData *allocateBuffer(int length);\n inline void addRef();\n inline void removeRef();\n};\n\nclass DOMStringHandle\n{\npublic:\n int fLength;\n int fRefCount;\n DOMStringData *fDSData;\n\n void *operator new( size_t sizeToAlloc);\n void operator delete( void *pvMem );\nprivate:\n static void *freeListPtr;\npublic:\n static DOMStringHandle *createNewStringHandle(int bufLength);\n DOMStringHandle *cloneStringHandle();\n inline void addRef();\n inline void removeRef();\n ~DOMStringHandle() {};\nprivate:\n inline DOMStringHandle() {};\n};\n\n\n#endif\n \n<commit_msg>Included header for size_t<commit_after>#ifndef DOMStringImpl_HEADER_GUARD_\n#define DOMStringImpl_HEADER_GUARD_\n\n\/*\n * The Apache Software License, Version 1.1\n * \n * Copyright (c) 1999 The Apache Software Foundation. All rights \n * reserved.\n * \n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n * \n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer. \n * \n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in\n * the documentation and\/or other materials provided with the\n * distribution.\n * \n * 3. The end-user documentation included with the redistribution,\n * if any, must include the following acknowledgment: \n * \"This product includes software developed by the\n * Apache Software Foundation (http:\/\/www.apache.org\/).\"\n * Alternately, this acknowledgment may appear in the software itself,\n * if and wherever such third-party acknowledgments normally appear.\n * \n * 4. The names \"Xerces\" and \"Apache Software Foundation\" must\n * not be used to endorse or promote products derived from this\n * software without prior written permission. For written \n * permission, please contact apache\\@apache.org.\n * \n * 5. Products derived from this software may not be called \"Apache\",\n * nor may \"Apache\" appear in their name, without prior written\n * permission of the Apache Software Foundation.\n * \n * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED\n * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR\n * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF\n * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT\n * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n * ====================================================================\n * \n * This software consists of voluntary contributions made by many\n * individuals on behalf of the Apache Software Foundation, and was\n * originally based on software copyright (c) 1999, International\n * Business Machines, Inc., http:\/\/www.ibm.com . For more information\n * on the Apache Software Foundation, please see\n * <http:\/\/www.apache.org\/>.\n *\/\n\n\/**\n * $Log$\n * Revision 1.2 2000\/01\/12 19:55:14 aruna1\n * Included header for size_t\n *\n * Revision 1.1 2000\/01\/05 22:16:26 robweir\n * Move DOMString implementation class declarations into a new\n * file: DOMStringImpl.hpp. Include this header in DOMString.hpp\n * for XML_DEBUG builds so the underlying character array will be\n * visible in the debugger. <robert_weir@lotus.com>\n *\n *\n *\/\n\n\n\/\/\n\/\/ This file is part of the internal implementation of the C++ XML DOM.\n\/\/ It should NOT be included or used directly by application programs.\n\/\/\n\n\n#include <util\/XML4CDefs.hpp>\n#include <stdio.h>\n\n\nclass DOMStringData\n{\npublic:\n int fBufferLength;\n int fRefCount;\n XMLCh fData[1];\n \n static DOMStringData *allocateBuffer(int length);\n inline void addRef();\n inline void removeRef();\n};\n\nclass DOMStringHandle\n{\npublic:\n int fLength;\n int fRefCount;\n DOMStringData *fDSData;\n\n void *operator new( size_t sizeToAlloc);\n void operator delete( void *pvMem );\nprivate:\n static void *freeListPtr;\npublic:\n static DOMStringHandle *createNewStringHandle(int bufLength);\n DOMStringHandle *cloneStringHandle();\n inline void addRef();\n inline void removeRef();\n ~DOMStringHandle() {};\nprivate:\n inline DOMStringHandle() {};\n};\n\n\n#endif\n \n<|endoftext|>"} {"text":"<commit_before>#include \"stdafx.h\"\n#include \"aabb2.h\"\n#include \"mathutil.h\"\n#include \"matrix2.h\"\n\nnamespace dukat\n{\n\tbool AABB2::overlaps(const AABB2& another) const\n\t{\n\t\tif (max.x < another.min.x) return false; \/\/ a is left of b\n\t\tif (min.x > another.max.x) return false; \/\/ a is right of b\n\t\tif (max.y < another.min.y) return false; \/\/ a is above b\n\t\tif (min.y > another.max.y) return false; \/\/ a is below b\n\t\treturn true; \/\/ boxes overlap\n\t}\n\n\tbool AABB2::intersect(const AABB2& another, Collision& collision) const\n\t{\n\t\tauto this_c = center();\n\t\tauto that_c = another.center();\n\t\tauto d = this_c - that_c;\n\t\tauto p = ((max - min) + (another.max - another.min)) * 0.5f - d.abs();\n\t\tif (p.x <= 0.0f || p.y <= 0.0f)\n\t\t\treturn false;\n\n\t\tif (p.x < p.y)\n\t\t{\n\t\t\tauto sx = sgn(d.x);\n\t\t\tcollision.delta.x = p.x * sx;\n\t\t\tcollision.normal.x = static_cast<float>(sx);\n\t\t\tcollision.pos.x = sx < 0 ? min.x : max.x;\n\t\t\tcollision.pos.y = that_c.y;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tauto sy = sgn(d.y);\n\t\t\tcollision.delta.y = p.y * sy;\n\t\t\tcollision.normal.y = static_cast<float>(sy);\n\t\t\tcollision.pos.x = that_c.x;\t\t\t\n\t\t\tcollision.pos.y = sy < 0 ? min.y : max.y;\n\t\t}\n\t\treturn true;\n\t}\n\n\tbool AABB2::contains(const Vector2& p) const\n\t{\n\t\t\/\/ check for overlap on each axis\n\t\treturn\n\t\t\t(p.x >= min.x) && (p.x <= max.x) &&\n\t\t\t(p.y >= min.y) && (p.y <= max.y);\n\t}\n\n\tbool AABB2::intersect_circle(const Vector2& p, float radius) const\n\t{\n\t\tconst auto center = this->center();\n\t\tauto v = center - p;\n\t\tconst auto dist2_centers = v.mag2();\n\n\t\t\/\/ compute inner & outer radius of bounding box\n\t\tauto outer_rad = (center - min).mag2();\n\t\tauto inner_rad = (max - center).mag2();\n\t\tif (outer_rad < inner_rad)\n\t\t\tstd::swap(outer_rad, inner_rad);\n\n\t\t\/\/ Case #1 - bb definitely outside of bb\n\t\tif (dist2_centers > outer_rad + radius)\n\t\t\treturn false;\n\t\t\/\/ Case #2 - bb definitely inside of bb\n\t\tif (dist2_centers < inner_rad + radius)\n\t\t\treturn true;\n\t\t\/\/ Case #3 - test point on circle on vector between centers\n\t\tv.normalize();\n\t\treturn contains(center + v * radius);\n\t}\n\n\tvoid AABB2::clear()\n\t{\n\t\tmin.x = min.y = big_number;\n\t\tmax.x = max.y = -big_number;\n\t}\n\n\tvoid AABB2::add(const Vector2& p)\n\t{\n\t\tif (p.x < min.x)\n\t\t{\n\t\t\tmin.x = p.x;\n\t\t}\n\t\tif (p.y < min.y)\n\t\t{\n\t\t\tmin.y = p.y;\n\t\t}\n\t\tif (p.x > max.x)\n\t\t{\n\t\t\tmax.x = p.x;\n\t\t}\n\t\tif (p.y > max.y)\n\t\t{\n\t\t\tmax.y = p.y;\n\t\t}\n\t}\n\n\tvoid AABB2::add(const AABB2& box)\n\t{\n\t\tadd(box.min);\n\t\tadd(box.max);\n\t}\n\n\tbool AABB2::empty(void) const\n\t{\n\t\t\/\/ check if we're inverted on any axis\n\t\treturn (min.x > max.x) || (min.y > max.y);\n\t}\n\n\tvoid AABB2::set_to_transformed_box(const AABB2& box, const Transform2& t)\n\t{\n\t\tclear();\n\t\tadd(t.pos + box.min.rotate(t.rot));\n\t\tadd(t.pos + box.max.rotate(t.rot));\n\t}\n\n\tfloat AABB2::intersect_ray(const Ray2& ray, float near, float far) const \n\t{\n\t\tauto tmin = (min.x - ray.origin.x) \/ ray.dir.x;\n\t\tauto tmax = (max.x - ray.origin.x) \/ ray.dir.x;\n\t\tif (tmin > tmax) \n\t\t\tstd::swap(tmin, tmax);\n\t\tauto tymin = (min.y - ray.origin.y) \/ ray.dir.y;\n\t\tauto tymax = (max.y - ray.origin.y) \/ ray.dir.y;\n\t\tif (tymin > tymax) \n\t\t\tstd::swap(tymin, tymax);\n\t\tif ((tmin > tymax) || (tymin > tmax))\n\t\t\treturn no_intersection;\n\t\tif (tymin > tmin)\n\t\t\ttmin = tymin;\n\t\tif (tymax < tmax)\n\t\t\ttmax = tymax;\n\t\tif ((tmin > far) || (tmax < near)) \n\t\t\treturn no_intersection;\n\t\treturn tmin;\n\t}\n\n\tint AABB2::classify_ray(const Ray2& ray) const\n\t{\n\t\t\/\/ compute ray normal by rotating the direction by 90 degrees CW\n\t\t\/\/ this means that the \"right\" side of the ray is considered its \n\t\t\/\/ front side \n\t\tVector2 n(-ray.dir.y, ray.dir.x);\n\t\tauto d = ray.origin * n;\n\t\t\n\t\t\/\/ Inspect the normal and compute the minimum and \n\t\t\/\/ maximum D values\n\t\tfloat mind, maxd;\n\n\t\tif (n.x > 0.0f)\n\t\t{\n\t\t\tmind = n.x * min.x;\n\t\t\tmaxd = n.x * max.x;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tmind = n.x * max.x;\n\t\t\tmaxd = n.x * min.x;\n\t\t}\n\n\t\tif (n.y > 0.0f)\n\t\t{\n\t\t\tmind += n.y * min.y;\n\t\t\tmaxd += n.y * max.y;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tmind += n.y * max.y;\n\t\t\tmaxd += n.y * min.y;\n\t\t}\n\n\t\t\/\/ check if completely on the front side of the plane\n\t\tif (mind >= d)\n\t\t{\n\t\t\treturn 1;\n\t\t}\n\t\t\/\/ check if completely on the back side of plane\n\t\telse if (maxd <= d)\n\t\t{\n\t\t\treturn -1;\n\t\t}\n\t\telse\n\t\t{\n\t\t\treturn 0;\n\t\t}\n\t}\n}<commit_msg>Fixing said method<commit_after>#include \"stdafx.h\"\n#include \"aabb2.h\"\n#include \"mathutil.h\"\n#include \"matrix2.h\"\n\nnamespace dukat\n{\n\tbool AABB2::overlaps(const AABB2& another) const\n\t{\n\t\tif (max.x < another.min.x) return false; \/\/ a is left of b\n\t\tif (min.x > another.max.x) return false; \/\/ a is right of b\n\t\tif (max.y < another.min.y) return false; \/\/ a is above b\n\t\tif (min.y > another.max.y) return false; \/\/ a is below b\n\t\treturn true; \/\/ boxes overlap\n\t}\n\n\tbool AABB2::intersect(const AABB2& another, Collision& collision) const\n\t{\n\t\tauto this_c = center();\n\t\tauto that_c = another.center();\n\t\tauto d = this_c - that_c;\n\t\tauto p = ((max - min) + (another.max - another.min)) * 0.5f - d.abs();\n\t\tif (p.x <= 0.0f || p.y <= 0.0f)\n\t\t\treturn false;\n\n\t\tif (p.x < p.y)\n\t\t{\n\t\t\tauto sx = sgn(d.x);\n\t\t\tcollision.delta.x = p.x * sx;\n\t\t\tcollision.normal.x = static_cast<float>(sx);\n\t\t\tcollision.pos.x = sx < 0 ? min.x : max.x;\n\t\t\tcollision.pos.y = that_c.y;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tauto sy = sgn(d.y);\n\t\t\tcollision.delta.y = p.y * sy;\n\t\t\tcollision.normal.y = static_cast<float>(sy);\n\t\t\tcollision.pos.x = that_c.x;\t\t\t\n\t\t\tcollision.pos.y = sy < 0 ? min.y : max.y;\n\t\t}\n\t\treturn true;\n\t}\n\n\tbool AABB2::contains(const Vector2& p) const\n\t{\n\t\t\/\/ check for overlap on each axis\n\t\treturn\n\t\t\t(p.x >= min.x) && (p.x <= max.x) &&\n\t\t\t(p.y >= min.y) && (p.y <= max.y);\n\t}\n\n\tbool AABB2::intersect_circle(const Vector2& p, float radius) const\n\t{\n\t\tconst auto center = this->center();\n\t\tauto v = center - p;\n\t\tconst auto dist2_centers = v.mag2();\n\n\t\t\/\/ compute inner & outer radius of bounding box\n\t\tauto outer_rad = (center - min).mag2();\n\t\tauto inner_rad = (max - center).mag2();\n\t\tif (outer_rad < inner_rad)\n\t\t\tstd::swap(outer_rad, inner_rad);\n\n\t\t\/\/ Case #1 - bb definitely outside of bb\n\t\tif (dist2_centers > outer_rad + radius * radius)\n\t\t\treturn false;\n\t\t\/\/ Case #2 - bb definitely inside of bb\n\t\tif (dist2_centers < inner_rad + radius * radius)\n\t\t\treturn true;\n\t\t\/\/ Case #3 - test point on circle on vector between centers\n\t\tv.normalize();\n\t\treturn contains(center + v * radius);\n\t}\n\n\tvoid AABB2::clear()\n\t{\n\t\tmin.x = min.y = big_number;\n\t\tmax.x = max.y = -big_number;\n\t}\n\n\tvoid AABB2::add(const Vector2& p)\n\t{\n\t\tif (p.x < min.x)\n\t\t{\n\t\t\tmin.x = p.x;\n\t\t}\n\t\tif (p.y < min.y)\n\t\t{\n\t\t\tmin.y = p.y;\n\t\t}\n\t\tif (p.x > max.x)\n\t\t{\n\t\t\tmax.x = p.x;\n\t\t}\n\t\tif (p.y > max.y)\n\t\t{\n\t\t\tmax.y = p.y;\n\t\t}\n\t}\n\n\tvoid AABB2::add(const AABB2& box)\n\t{\n\t\tadd(box.min);\n\t\tadd(box.max);\n\t}\n\n\tbool AABB2::empty(void) const\n\t{\n\t\t\/\/ check if we're inverted on any axis\n\t\treturn (min.x > max.x) || (min.y > max.y);\n\t}\n\n\tvoid AABB2::set_to_transformed_box(const AABB2& box, const Transform2& t)\n\t{\n\t\tclear();\n\t\tadd(t.pos + box.min.rotate(t.rot));\n\t\tadd(t.pos + box.max.rotate(t.rot));\n\t}\n\n\tfloat AABB2::intersect_ray(const Ray2& ray, float near, float far) const \n\t{\n\t\tauto tmin = (min.x - ray.origin.x) \/ ray.dir.x;\n\t\tauto tmax = (max.x - ray.origin.x) \/ ray.dir.x;\n\t\tif (tmin > tmax) \n\t\t\tstd::swap(tmin, tmax);\n\t\tauto tymin = (min.y - ray.origin.y) \/ ray.dir.y;\n\t\tauto tymax = (max.y - ray.origin.y) \/ ray.dir.y;\n\t\tif (tymin > tymax) \n\t\t\tstd::swap(tymin, tymax);\n\t\tif ((tmin > tymax) || (tymin > tmax))\n\t\t\treturn no_intersection;\n\t\tif (tymin > tmin)\n\t\t\ttmin = tymin;\n\t\tif (tymax < tmax)\n\t\t\ttmax = tymax;\n\t\tif ((tmin > far) || (tmax < near)) \n\t\t\treturn no_intersection;\n\t\treturn tmin;\n\t}\n\n\tint AABB2::classify_ray(const Ray2& ray) const\n\t{\n\t\t\/\/ compute ray normal by rotating the direction by 90 degrees CW\n\t\t\/\/ this means that the \"right\" side of the ray is considered its \n\t\t\/\/ front side \n\t\tVector2 n(-ray.dir.y, ray.dir.x);\n\t\tauto d = ray.origin * n;\n\t\t\n\t\t\/\/ Inspect the normal and compute the minimum and \n\t\t\/\/ maximum D values\n\t\tfloat mind, maxd;\n\n\t\tif (n.x > 0.0f)\n\t\t{\n\t\t\tmind = n.x * min.x;\n\t\t\tmaxd = n.x * max.x;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tmind = n.x * max.x;\n\t\t\tmaxd = n.x * min.x;\n\t\t}\n\n\t\tif (n.y > 0.0f)\n\t\t{\n\t\t\tmind += n.y * min.y;\n\t\t\tmaxd += n.y * max.y;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tmind += n.y * max.y;\n\t\t\tmaxd += n.y * min.y;\n\t\t}\n\n\t\t\/\/ check if completely on the front side of the plane\n\t\tif (mind >= d)\n\t\t{\n\t\t\treturn 1;\n\t\t}\n\t\t\/\/ check if completely on the back side of plane\n\t\telse if (maxd <= d)\n\t\t{\n\t\t\treturn -1;\n\t\t}\n\t\telse\n\t\t{\n\t\t\treturn 0;\n\t\t}\n\t}\n}<|endoftext|>"} {"text":"<commit_before>#include \"GolfBall.hpp\"\n#include \"..\/Resources.hpp\"\n#include \"Default3D.vert.hpp\"\n#include \"Default3D.geom.hpp\"\n#include \"Default3D.frag.hpp\"\n#include \"glm\/gtc\/constants.hpp\"\n#include \"..\/Util\/Log.hpp\"\n#include <glm\/gtc\/matrix_transform.hpp>\n#include <glm\/gtx\/quaternion.hpp>\n\nGolfBall::GolfBall(BallType ballType, TerrainObject* terrain) : ModelObject(modelGeometry = Resources().CreateOBJModel(\"Resources\/Models\/GolfBall\/GolfBall.obj\"),\n \"Resources\/Models\/GolfBall\/Diffuse.png\",\n \"Resources\/Models\/GolfBall\/Normal.png\",\n \"Resources\/Models\/GolfBall\/Specular.png\") {\n active = false;\n \n restitution = ballType == TWOPIECE ? 0.78f : 0.68f;\n this->terrain = terrain;\n groundLevel = this->terrain->Position().y;\n origin = glm::vec3(1.f, 0.f, 1.f);\n \n \/\/\/ @todo Mass based on explosive material.\n mass = 0.0459f;\n this->ballType = ballType;\n \n sphere.position = Position();\n SetRadius(0.0214f);\n}\n\nGolfBall::~GolfBall() {\n Resources().FreeOBJModel(modelGeometry);\n}\n\nvoid GolfBall::Reset(){\n active = false;\n velocity = glm::vec3(0.f, 0.f, 0.f);\n angularVelocity = glm::vec3(0.f, 0.f, 0.f);\n SetPosition(origin);\n sphere.position = Position();\n orientation = glm::quat();\n}\n\nvoid GolfBall::Update(double time, const glm::vec3& wind, std::vector<PlayerObject>& players) {\n if (active) {\n Move(static_cast<float>(time) * velocity);\n sphere.position = Position();\n \n if (glm::length(angularVelocity) > 0.0001f) {\n glm::quat deltaQuat = glm::angleAxis(static_cast<float>(time) * glm::length(angularVelocity), glm::normalize(angularVelocity));\n orientation = deltaQuat * orientation;\n }\n \n\t\t\/\/check for collision\n\t\tif ((sphere.position.y - sphere.radius) < groundLevel){\n\t\t\tfloat vCritical = 0.2f;\n\t\t\tfloat e = 0.55f;\n\t\t\tfloat mu = 0.91f;\n\t\t\tfloat muRolling = 0.011f;\n\t\t\tSetPosition(Position().x, groundLevel + sphere.radius, Position().z);\n\t\t\tsphere.position = Position();\n\t\t\tglm::vec3 surfaceNormal = glm::normalize(glm::vec3(0.f, 1.f, 0.f));\n\t\t\tglm::vec3 eRoh = glm::normalize(surfaceNormal);\n\t\t\t\/\/@TODO: Find better approximative value for vCrit.\n\t\t\tglm::vec3 tangentialVelocity = velocity - (glm::dot(velocity, surfaceNormal))*surfaceNormal;\n\t\t\t\/\/If the velocity projected along the surface normal isn't enough to lift the ball off the surface, then the ball is either rolling or sliding across the surface.\n\t\t\t\/\/@TODO: Move ball along surfacenormal instead of along y-axis. Need to know distance between balls current position and triangle.\n\t\t\t\/\/glm::vec3 originAtTriangle\n\t\t\t\/\/glm::vec3 displacementAlongNormal = surfaceNormal*sphere.radius;\n\t\t\t\/\/modelObject->SetPosition(displacementAlongNormal + originAtTriangle);\n\t\t\tglm::vec3 eFriction = glm::normalize((sphere.radius*glm::cross(eRoh, angularVelocity) + tangentialVelocity));\n\t\t\tglm::vec3 vRoh = velocity*eRoh;\n\t\t\tglm::vec3 eR = -eRoh;\n\t\t\tfloat deltaU = glm::length(-(e + 1.f)*vRoh);\n\t\t\t\/\/Log() << glm::length(glm::dot(velocity, eRoh));\n\t\t\tglm::vec3 angularDirection = glm::cross(glm::normalize(tangentialVelocity), eR);\n\t\t\tif (glm::length(glm::dot(velocity, eRoh)) < vCritical){\n\t\t\t\tif (glm::dot(angularDirection, angularVelocity) < 0.f)\n\t\t\t\t{\n\t\t\t\t\tLog() << \"Slajding.\\n\";\n\t\t\t\t\t\/\/slajding\n\t\t\t\t\tvelocity = tangentialVelocity - static_cast<float>(time)*(eFriction*mu)*glm::vec3(0.f, 9.82f, 0.f);\n\t\t\t\t\tangularVelocity += (5.f \/ 2.f)*(mu*9.82f \/ sphere.radius)*static_cast<float>(time)*angularDirection;\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\tLog() << \"Rolling.\\n\";\n\t\t\t\t\t\/\/rolling\n\t\t\t\t\tvelocity += angularVelocity*sphere.radius;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tglm::vec3 vRoh = velocity*eRoh;\n\t\t\t\tfloat deltaU = glm::length(-(e + 1.f)*vRoh);\n\t\t\t\tvelocity += (deltaU)*(eRoh + mu*eFriction);\n\t\t\t\tangularVelocity += ((mu*glm::length(deltaU)) \/ (sphere.radius))*(glm::cross(eR, eFriction));\n\t\t\t}\n\t\t}\n Log() << angularVelocity << \"\\n\";\n \/\/Log() << glm::dot(velocity, glm::vec3(0.f,1.f,0.f)) << \"\\n\";\n \n \/\/ Calculate magnus force.\n float v = glm::length(velocity);\n float u = glm::length(velocity - wind);\n float w = glm::length(angularVelocity);\n glm::vec3 eU = (velocity - wind) \/ u;\n glm::vec3 magnusForce = glm::vec3(0.f, 0.f, 0.f);\n if (v > 0.f && w > 0.f) {\n float Cm = (sqrt(1.f + 0.31f * (w \/ v)) - 1.f) \/ 20.f;\n float Fm = 0.5f * Cm * 1.23f * area * u * u;\n magnusForce = Fm * glm::cross(eU, glm::normalize(angularVelocity));\n }\n \n \/\/ Calculate drag force.\n float cD;\n if (ballType == TWOPIECE)\n cD = v < 65.f ? -0.0051f * v + 0.53f : 0.21f;\n else\n cD = v < 60.f ? -0.0084f * v + 0.73f : 0.22f;\n \n glm::vec3 dragForce = -0.5f * 1.23f * area * cD * u * u * eU;\n \n \/\/ Calculate gravitational force.\n glm::vec3 gravitationForce = glm::vec3(0.f, mass * -9.82f, 0.f);\n \n \/\/ Get acceleration from total force.\n glm::vec3 acceleration = (dragForce + magnusForce + gravitationForce) \/ mass;\n velocity += acceleration * static_cast<float>(time);\n }\n}\n\nvoid GolfBall::Render(Camera* camera, const glm::vec2& screenSize, const glm::vec4& clippingPlane) const{\n ModelObject::Render(camera, screenSize, clippingPlane);\n}\n\nvoid GolfBall::Explode(std::vector<PlayerObject>& players, int playerIndex){\n \/\/@TODO: Set mass equivalent depending on material used.\n float equivalenceFactor = 1.0f;\n float massEquivalent = mass*equivalenceFactor;\n for (auto &player : players){\n glm::vec3 distanceV = (Position() - player.Position());\n float distance = glm::length(distanceV);\n \/\/pow(meq, 1.f\/3.f) => cube root of meq\n float z = distance \/ (pow(massEquivalent, 1.f \/ 3.f));\n float alpha = 1 + pow((z \/ 4.5f), 2.f);\n float beta = 1 + pow((z \/ 0.048f), 2.f);\n float gamma = 1 + pow((z \/ 1.35f), 2.f);\n float delta = 1 + pow((z \/ 0.32f), 2.f);\n float Pf = 8.08f*pow(10.f, 7.f)*alpha;\n Pf = Pf \/ sqrt(beta*gamma*delta);\n player.TakeDamage(Pf);\n }\n origin = players[playerIndex].Position();\n Reset();\n}\n\nvoid GolfBall::Strike(ClubType club, const glm::vec3& clubVelocity) {\n active = true;\n \n \/\/ Club velocity in strike plane.\n float v = glm::length(clubVelocity);\n float sinLoft = sin(club.loft);\n float cosLoft = cos(club.loft);\n \n \/\/ Ball velocity.\n float massCoefficient = club.mass \/ (club.mass + mass);\n float Up = (1.f + restitution) * massCoefficient * v * cosLoft;\n float Un = (2.f \/ 7.f) * massCoefficient * v * sinLoft;\n \n \/\/ Go back from strike plane to 3D.\n glm::vec3 forward = clubVelocity \/ v;\n glm::vec3 up = glm::cross(forward, glm::cross(glm::vec3(0.f, 1.f, 0.f), forward));\n glm::vec3 ep = glm::normalize(cosLoft * forward + sinLoft * up);\n glm::vec3 en = glm::normalize(sinLoft * forward - cosLoft * up);\n \n \/\/ Total velocity.\n velocity = Up * ep + Un * en;\n angularVelocity = -Un \/ sphere.radius * glm::cross(ep, en);\n}\n\nvoid GolfBall::SetRadius(float radius) {\n sphere.radius = radius;\n SetScale(glm::vec3(radius, radius, radius));\n area = glm::pi<float>() * radius * radius;\n}\n\nglm::mat4 GolfBall::Orientation() const {\n\treturn glm::toMat4(orientation);\n}\n<commit_msg>More work on sliding<commit_after>#include \"GolfBall.hpp\"\n#include \"..\/Resources.hpp\"\n#include \"Default3D.vert.hpp\"\n#include \"Default3D.geom.hpp\"\n#include \"Default3D.frag.hpp\"\n#include \"glm\/gtc\/constants.hpp\"\n#include \"..\/Util\/Log.hpp\"\n#include <glm\/gtc\/matrix_transform.hpp>\n#include <glm\/gtx\/quaternion.hpp>\n\nGolfBall::GolfBall(BallType ballType, TerrainObject* terrain) : ModelObject(modelGeometry = Resources().CreateOBJModel(\"Resources\/Models\/GolfBall\/GolfBall.obj\"),\n \"Resources\/Models\/GolfBall\/Diffuse.png\",\n \"Resources\/Models\/GolfBall\/Normal.png\",\n \"Resources\/Models\/GolfBall\/Specular.png\") {\n active = false;\n \n restitution = ballType == TWOPIECE ? 0.78f : 0.68f;\n this->terrain = terrain;\n groundLevel = this->terrain->Position().y;\n origin = glm::vec3(1.f, 0.f, 1.f);\n \n \/\/\/ @todo Mass based on explosive material.\n mass = 0.0459f;\n this->ballType = ballType;\n \n sphere.position = Position();\n SetRadius(0.0214f);\n}\n\nGolfBall::~GolfBall() {\n Resources().FreeOBJModel(modelGeometry);\n}\n\nvoid GolfBall::Reset(){\n active = false;\n velocity = glm::vec3(0.f, 0.f, 0.f);\n angularVelocity = glm::vec3(0.f, 0.f, 0.f);\n SetPosition(origin);\n sphere.position = Position();\n orientation = glm::quat();\n}\n\nvoid GolfBall::Update(double time, const glm::vec3& wind, std::vector<PlayerObject>& players) {\n if (active) {\n Move(static_cast<float>(time) * velocity);\n sphere.position = Position();\n \n if (glm::length(angularVelocity) > 0.0001f) {\n glm::quat deltaQuat = glm::angleAxis(static_cast<float>(time) * glm::length(angularVelocity), glm::normalize(angularVelocity));\n orientation = deltaQuat * orientation;\n }\n \n\t\t\/\/check for collision\n\t\tif ((sphere.position.y - sphere.radius) < groundLevel){\n\t\t\tfloat vCritical = 0.2f;\n\t\t\tfloat e = 0.55f;\n\t\t\tfloat mu = 0.91f;\n\t\t\tfloat muRolling = 0.011f;\n\t\t\tSetPosition(Position().x, groundLevel + sphere.radius, Position().z);\n\t\t\tsphere.position = Position();\n\t\t\tglm::vec3 surfaceNormal = glm::normalize(glm::vec3(0.f, 1.f, 0.f));\n\t\t\tglm::vec3 eRoh = glm::normalize(surfaceNormal);\n\t\t\t\/\/@TODO: Find better approximative value for vCrit.\n\t\t\tglm::vec3 tangentialVelocity = velocity - (glm::dot(velocity, surfaceNormal))*surfaceNormal;\n\t\t\t\/\/If the velocity projected along the surface normal isn't enough to lift the ball off the surface, then the ball is either rolling or sliding across the surface.\n\t\t\t\/\/@TODO: Move ball along surfacenormal instead of along y-axis. Need to know distance between balls current position and triangle.\n\t\t\t\/\/glm::vec3 originAtTriangle\n\t\t\t\/\/glm::vec3 displacementAlongNormal = surfaceNormal*sphere.radius;\n\t\t\t\/\/modelObject->SetPosition(displacementAlongNormal + originAtTriangle);\n\t\t\tglm::vec3 eFriction = glm::normalize((sphere.radius*glm::cross(eRoh, angularVelocity) + tangentialVelocity));\n\t\t\tglm::vec3 vRoh = velocity*eRoh;\n\t\t\tglm::vec3 eR = -eRoh;\n\t\t\tfloat deltaU = glm::length(-(e + 1.f)*vRoh);\n\t\t\t\/\/Log() << glm::length(glm::dot(velocity, eRoh));\n\t\t\tglm::vec3 angularDirection = glm::cross(glm::normalize(tangentialVelocity), eR);\n\t\t\tfloat w = glm::dot(angularVelocity, angularDirection);\n\t\t\tif (glm::length(glm::dot(velocity, eRoh)) < vCritical){\n\t\t\t\tif (w*sphere.radius > glm::length(tangentialVelocity))\n\t\t\t\t{\n\t\t\t\t\tLog() << \"Slajding.\\n\";\n\t\t\t\t\t\/\/slajding\n\t\t\t\t\tvelocity = tangentialVelocity - static_cast<float>(time)*(eFriction*mu)*glm::vec3(0.f, 9.82f, 0.f);\n\t\t\t\t\tangularVelocity += (5.f \/ 2.f)*(mu*9.82f \/ sphere.radius)*static_cast<float>(time)*angularDirection;\n\t\t\t\t} else {\n\t\t\t\t\tLog() << \"Rolling.\\n\";\n\t\t\t\t\tvelocity = tangentialVelocity - static_cast<float>(time)*(eFriction*muRolling)*glm::vec3(0.f, 9.82f, 0.f);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tglm::vec3 vRoh = velocity*eRoh;\n\t\t\t\tfloat deltaU = glm::length(-(e + 1.f)*vRoh);\n\t\t\t\tvelocity += (deltaU)*(eRoh + mu*eFriction);\n\t\t\t\tangularVelocity += ((mu*glm::length(deltaU)) \/ (sphere.radius))*(glm::cross(eR, eFriction));\n\t\t\t}\n\t\t}\n Log() << angularVelocity << \"\\n\";\n \/\/Log() << glm::dot(velocity, glm::vec3(0.f,1.f,0.f)) << \"\\n\";\n \n \/\/ Calculate magnus force.\n float v = glm::length(velocity);\n float u = glm::length(velocity - wind);\n float w = glm::length(angularVelocity);\n glm::vec3 eU = (velocity - wind) \/ u;\n glm::vec3 magnusForce = glm::vec3(0.f, 0.f, 0.f);\n if (v > 0.f && w > 0.f) {\n float Cm = (sqrt(1.f + 0.31f * (w \/ v)) - 1.f) \/ 20.f;\n float Fm = 0.5f * Cm * 1.23f * area * u * u;\n magnusForce = Fm * glm::cross(eU, glm::normalize(angularVelocity));\n }\n \n \/\/ Calculate drag force.\n float cD;\n if (ballType == TWOPIECE)\n cD = v < 65.f ? -0.0051f * v + 0.53f : 0.21f;\n else\n cD = v < 60.f ? -0.0084f * v + 0.73f : 0.22f;\n \n glm::vec3 dragForce = -0.5f * 1.23f * area * cD * u * u * eU;\n \n \/\/ Calculate gravitational force.\n glm::vec3 gravitationForce = glm::vec3(0.f, mass * -9.82f, 0.f);\n \n \/\/ Get acceleration from total force.\n glm::vec3 acceleration = (dragForce + magnusForce + gravitationForce) \/ mass;\n velocity += acceleration * static_cast<float>(time);\n }\n}\n\nvoid GolfBall::Render(Camera* camera, const glm::vec2& screenSize, const glm::vec4& clippingPlane) const{\n ModelObject::Render(camera, screenSize, clippingPlane);\n}\n\nvoid GolfBall::Explode(std::vector<PlayerObject>& players, int playerIndex){\n \/\/@TODO: Set mass equivalent depending on material used.\n float equivalenceFactor = 1.0f;\n float massEquivalent = mass*equivalenceFactor;\n for (auto &player : players){\n glm::vec3 distanceV = (Position() - player.Position());\n float distance = glm::length(distanceV);\n \/\/pow(meq, 1.f\/3.f) => cube root of meq\n float z = distance \/ (pow(massEquivalent, 1.f \/ 3.f));\n float alpha = 1 + pow((z \/ 4.5f), 2.f);\n float beta = 1 + pow((z \/ 0.048f), 2.f);\n float gamma = 1 + pow((z \/ 1.35f), 2.f);\n float delta = 1 + pow((z \/ 0.32f), 2.f);\n float Pf = 8.08f*pow(10.f, 7.f)*alpha;\n Pf = Pf \/ sqrt(beta*gamma*delta);\n player.TakeDamage(Pf);\n }\n origin = players[playerIndex].Position();\n Reset();\n}\n\nvoid GolfBall::Strike(ClubType club, const glm::vec3& clubVelocity) {\n active = true;\n \n \/\/ Club velocity in strike plane.\n float v = glm::length(clubVelocity);\n float sinLoft = sin(club.loft);\n float cosLoft = cos(club.loft);\n \n \/\/ Ball velocity.\n float massCoefficient = club.mass \/ (club.mass + mass);\n float Up = (1.f + restitution) * massCoefficient * v * cosLoft;\n float Un = (2.f \/ 7.f) * massCoefficient * v * sinLoft;\n \n \/\/ Go back from strike plane to 3D.\n glm::vec3 forward = clubVelocity \/ v;\n glm::vec3 up = glm::cross(forward, glm::cross(glm::vec3(0.f, 1.f, 0.f), forward));\n glm::vec3 ep = glm::normalize(cosLoft * forward + sinLoft * up);\n glm::vec3 en = glm::normalize(sinLoft * forward - cosLoft * up);\n \n \/\/ Total velocity.\n velocity = Up * ep + Un * en;\n angularVelocity = -Un \/ sphere.radius * glm::cross(ep, en);\n}\n\nvoid GolfBall::SetRadius(float radius) {\n sphere.radius = radius;\n SetScale(glm::vec3(radius, radius, radius));\n area = glm::pi<float>() * radius * radius;\n}\n\nglm::mat4 GolfBall::Orientation() const {\n\treturn glm::toMat4(orientation);\n}\n<|endoftext|>"} {"text":"<commit_before>#include <cstdint>\n#include <memory>\n\n#include <boost\/assert.hpp>\n\nnamespace blackhole {\n\ntemplate<typename T>\nclass monadic;\n\nclass config_t {\npublic:\n virtual auto operator[](const std::size_t& idx) const -> monadic<config_t> = 0;\n virtual auto operator[](const std::string& key) const -> monadic<config_t> = 0;\n\n virtual auto to_i64() const -> std::int64_t = 0;\n virtual auto to_u64() const -> std::uint64_t = 0;\n virtual auto to_string() const -> std::string = 0;\n};\n\n\/\/ TODO: Can be hidden for the sake of encapsulation.\ntemplate<>\nclass monadic<config_t> {\n std::unique_ptr<config_t> inner;\n\npublic:\n explicit monadic(std::unique_ptr<config_t> inner) :\n inner(std::move(inner))\n {\n BOOST_ASSERT(this->inner);\n }\n\n auto operator[](const std::size_t& idx) const -> monadic<config_t> {\n return inner->operator[](idx);\n }\n\n auto operator[](const std::string& key) const -> monadic<config_t> {\n return inner->operator[](key);\n }\n\n auto operator->() -> config_t* {\n return inner.get();\n }\n};\n\ntemplate<typename T, typename... Args>\nauto make_monadic(Args&&... args) -> monadic<config_t> {\n return monadic<config_t>(std::unique_ptr<T>(new T(std::forward<Args>(args)...)));\n}\n\n} \/\/ namespace blackhole\n\n#include <gtest\/gtest.h>\n\n#include <boost\/algorithm\/string.hpp>\n\n#include <rapidjson\/document.h>\n\nnamespace blackhole {\nnamespace testing {\n\n\/\/ builder(xml) - читает и генерирует свое дерево и реализации config_t.\n\/\/ .sevmap(...) - просто запоминает\n\/\/ .build() - ищет ключ \"formatter\/type\" config[\"formatter\"][\"type\"]\n\/\/ по type делегирует config[\"formatter\"] в нужную фабрику\n\n\/\/\/ None value. Throws an exception on any get access, but maps to none on subscription.\nclass none_t : public config_t {\n auto operator[](const std::size_t& idx) const -> monadic<config_t> {\n return make_monadic<none_t>();\n }\n\n auto operator[](const std::string& key) const -> monadic<config_t> {\n return make_monadic<none_t>();\n }\n\n auto to_i64() const -> std::int64_t {\n throw std::out_of_range(\"none\");\n }\n\n auto to_u64() const -> std::uint64_t {\n throw std::out_of_range(\"none\");\n }\n\n auto to_string() const -> std::string {\n throw std::out_of_range(\"none\");\n }\n};\n\nclass json_t : public config_t {\n const rapidjson::Value& value;\n\npublic:\n explicit json_t(const rapidjson::Value& value) :\n value(value)\n {}\n\n auto operator[](const std::size_t& idx) const -> monadic<config_t> {\n if (value.IsArray() && idx < value.Size()) {\n return make_monadic<json_t>(value[idx]);\n }\n\n return make_monadic<none_t>();\n }\n\n auto operator[](const std::string& key) const -> monadic<config_t> {\n if (value.IsObject() && value.HasMember(key.c_str())) {\n return make_monadic<json_t>(value[key.c_str()]);\n }\n\n return make_monadic<none_t>();\n }\n\n auto to_i64() const -> std::int64_t {\n if (value.IsInt64()) {\n return value.GetInt64();\n }\n\n throw std::invalid_argument(\"\"); \/\/ TODO: Bad cast.\n }\n\n auto to_u64() const -> std::uint64_t {\n if (value.IsUint64()) {\n return value.GetUint64();\n }\n\n throw std::invalid_argument(\"\"); \/\/ TODO: Bad cast.\n }\n\n auto to_string() const -> std::string {\n if (value.IsString()) {\n return value.GetString();\n }\n\n throw std::invalid_argument(\"\"); \/\/ TODO: Bad cast.\n }\n};\n\nclass json_factory_t {\n rapidjson::Document doc;\n\npublic:\n explicit json_factory_t(const std::string& value) {\n doc.Parse<0>(value.c_str());\n if (doc.HasParseError()) {\n throw std::runtime_error(\"parse error\");\n }\n }\n\n auto build() -> void {\n auto config = json_t(doc);\n const auto type = config[\"formatter\"][\"type\"]->to_string();\n }\n};\n\nTEST(config_t, json) {\n static const std::string JSON = R\"({\n 'formatter': {\n 'type': 'string',\n 'pattern': '[%(level)s]: %(message)s'\n },\n 'sinks': [\n {\n 'type': 'files',\n 'path': 'test.log',\n 'rotation': {\n 'pattern': 'test.log.%N',\n 'backups': 5,\n 'size': 1000000\n }\n }\n ]\n })\";\n\n const std::string valid(boost::algorithm::replace_all_copy(JSON, \"'\", \"\\\"\"));\n rapidjson::Document doc;\n doc.Parse<0>(valid.c_str());\n ASSERT_FALSE(doc.HasParseError());\n\n json_t config(doc);\n\n EXPECT_EQ(\"string\", config[\"formatter\"][\"type\"]->to_string());\n EXPECT_EQ(\"[%(level)s]: %(message)s\", config[\"formatter\"][\"pattern\"]->to_string());\n\n EXPECT_EQ(\"files\", config[\"sinks\"][0][\"type\"]->to_string());\n EXPECT_EQ(\"test.log\", config[\"sinks\"][0][\"path\"]->to_string());\n EXPECT_EQ(\"test.log.%N\", config[\"sinks\"][0][\"rotation\"][\"pattern\"]->to_string());\n EXPECT_EQ(5, config[\"sinks\"][0][\"rotation\"][\"backups\"]->to_i64());\n EXPECT_EQ(1000000, config[\"sinks\"][0][\"rotation\"][\"size\"]->to_u64());\n}\n\n} \/\/ namespace testing\n} \/\/ namespace blackhole\n<commit_msg>feat(builder): add each and each_map methods<commit_after>#include <cstdint>\n#include <functional>\n#include <memory>\n#include <stdexcept>\n#include <string>\n#include <vector>\n\n#include <boost\/assert.hpp>\n\nnamespace blackhole {\n\ntemplate<typename T>\nclass monadic;\n\nclass config_t {\npublic:\n typedef std::function<auto(const config_t&) -> void> each_function;\n typedef std::function<auto(const std::string&, const config_t&) -> void> member_function;\n\n virtual auto operator[](const std::size_t& idx) const -> monadic<config_t> = 0;\n virtual auto operator[](const std::string& key) const -> monadic<config_t> = 0;\n\n virtual auto to_i64() const -> std::int64_t = 0;\n virtual auto to_u64() const -> std::uint64_t = 0;\n virtual auto to_string() const -> std::string = 0;\n\n virtual auto each(const each_function& fn) -> void = 0;\n virtual auto each_map(const member_function& fn) -> void = 0;\n};\n\n\/\/\/ None value. Throws an exception on any get access, but maps to none on subscription.\nclass none_t : public config_t {\n auto operator[](const std::size_t& idx) const -> monadic<config_t>;\n auto operator[](const std::string& key) const -> monadic<config_t>;\n auto to_i64() const -> std::int64_t;\n auto to_u64() const -> std::uint64_t;\n auto to_string() const -> std::string;\n\n auto each(const each_function& fn) -> void;\n auto each_map(const member_function& fn) -> void;\n};\n\n\/\/ TODO: Can be hidden for the sake of encapsulation.\ntemplate<>\nclass monadic<config_t> {\n std::unique_ptr<config_t> inner;\n\npublic:\n monadic() :\n inner(new none_t)\n {}\n\n explicit monadic(std::unique_ptr<config_t> inner) :\n inner(std::move(inner))\n {\n BOOST_ASSERT(this->inner);\n }\n\n auto operator[](const std::size_t& idx) const -> monadic<config_t> {\n return inner->operator[](idx);\n }\n\n auto operator[](const std::string& key) const -> monadic<config_t> {\n return inner->operator[](key);\n }\n\n auto operator->() -> config_t* {\n return inner.get();\n }\n\n auto operator*() const -> const config_t& {\n return *inner;\n }\n};\n\nauto\nnone_t::operator[](const std::size_t& idx) const -> monadic<config_t> {\n return {};\n}\n\nauto\nnone_t::operator[](const std::string& key) const -> monadic<config_t> {\n return {};\n}\n\nauto\nnone_t::to_i64() const -> std::int64_t {\n throw std::out_of_range(\"none\");\n}\n\nauto\nnone_t::to_u64() const -> std::uint64_t {\n throw std::out_of_range(\"none\");\n}\n\nauto\nnone_t::to_string() const -> std::string {\n throw std::out_of_range(\"none\");\n}\n\nauto\nnone_t::each(const each_function& fn) -> void {\n throw std::out_of_range(\"none\");\n}\n\nauto\nnone_t::each_map(const member_function& fn) -> void {\n throw std::out_of_range(\"none\");\n}\n\ntemplate<typename T, typename... Args>\nauto make_monadic(Args&&... args) -> monadic<config_t> {\n return monadic<config_t>(std::unique_ptr<T>(new T(std::forward<Args>(args)...)));\n}\n\n} \/\/ namespace blackhole\n\n#include <gtest\/gtest.h>\n\n#include <boost\/algorithm\/string.hpp>\n\n#include <rapidjson\/document.h>\n\nnamespace blackhole {\nnamespace testing {\n\n\/\/ builder(xml) - читает и генерирует свое дерево и реализации config_t.\n\/\/ .sevmap(...) - просто запоминает\n\/\/ .build() - ищет ключ \"formatter\/type\" config[\"formatter\"][\"type\"]\n\/\/ по type делегирует config[\"formatter\"] в нужную фабрику\n\nclass json_t : public config_t {\n const rapidjson::Value& value;\n\npublic:\n explicit json_t(const rapidjson::Value& value) :\n value(value)\n {}\n\n auto operator[](const std::size_t& idx) const -> monadic<config_t> {\n if (value.IsArray() && idx < value.Size()) {\n return make_monadic<json_t>(value[idx]);\n }\n\n return {};\n }\n\n auto operator[](const std::string& key) const -> monadic<config_t> {\n if (value.IsObject() && value.HasMember(key.c_str())) {\n return make_monadic<json_t>(value[key.c_str()]);\n }\n\n return {};\n }\n\n auto to_i64() const -> std::int64_t {\n if (value.IsInt64()) {\n return value.GetInt64();\n }\n\n throw std::invalid_argument(\"\"); \/\/ TODO: Bad cast.\n }\n\n auto to_u64() const -> std::uint64_t {\n if (value.IsUint64()) {\n return value.GetUint64();\n }\n\n throw std::invalid_argument(\"\"); \/\/ TODO: Bad cast.\n }\n\n auto to_string() const -> std::string {\n if (value.IsString()) {\n return value.GetString();\n }\n\n throw std::invalid_argument(\"\"); \/\/ TODO: Bad cast.\n }\n\n auto each(const each_function& fn) -> void {\n for (auto it = value.Begin(); it != value.End(); ++it) {\n fn(*make_monadic<json_t>(*it));\n }\n }\n\n auto each_map(const member_function& fn) -> void {\n for (auto it = value.MemberBegin(); it != value.MemberEnd(); ++it) {\n fn(it->name.GetString(), *make_monadic<json_t>(it->value));\n }\n }\n};\n\nTEST(config_t, json) {\n static const std::string JSON = R\"({\n 'formatter': {\n 'type': 'string',\n 'pattern': '[%(level)s]: %(message)s'\n },\n 'sinks': [\n {\n 'type': 'files',\n 'path': 'test.log',\n 'rotation': {\n 'pattern': 'test.log.%N',\n 'backups': 5,\n 'size': 1000000\n }\n }\n ]\n })\";\n\n const std::string valid(boost::algorithm::replace_all_copy(JSON, \"'\", \"\\\"\"));\n rapidjson::Document doc;\n doc.Parse<0>(valid.c_str());\n ASSERT_FALSE(doc.HasParseError());\n\n json_t config(doc);\n\n EXPECT_EQ(\"string\", config[\"formatter\"][\"type\"]->to_string());\n EXPECT_EQ(\"[%(level)s]: %(message)s\", config[\"formatter\"][\"pattern\"]->to_string());\n\n EXPECT_EQ(\"files\", config[\"sinks\"][0][\"type\"]->to_string());\n EXPECT_EQ(\"test.log\", config[\"sinks\"][0][\"path\"]->to_string());\n EXPECT_EQ(\"test.log.%N\", config[\"sinks\"][0][\"rotation\"][\"pattern\"]->to_string());\n EXPECT_EQ(5, config[\"sinks\"][0][\"rotation\"][\"backups\"]->to_i64());\n EXPECT_EQ(1000000, config[\"sinks\"][0][\"rotation\"][\"size\"]->to_u64());\n\n \/\/ NOTE: There is only one sink, so it's okay to compare strongly.\n auto counter = 0;\n config[\"sinks\"]->each([&](const config_t& sink) {\n EXPECT_EQ(\"files\", sink[\"type\"]->to_string());\n EXPECT_EQ(\"test.log\", sink[\"path\"]->to_string());\n EXPECT_EQ(\"test.log.%N\", sink[\"rotation\"][\"pattern\"]->to_string());\n EXPECT_EQ(5, sink[\"rotation\"][\"backups\"]->to_i64());\n EXPECT_EQ(1000000, sink[\"rotation\"][\"size\"]->to_u64());\n ++counter;\n });\n\n EXPECT_EQ(1, counter);\n\n std::vector<std::string> keys;\n config.each_map([&](const std::string& key, const config_t& sink) {\n keys.push_back(key);\n });\n\n EXPECT_EQ((std::vector<std::string>{\"formatter\", \"sinks\"}), keys);\n}\n\n} \/\/ namespace testing\n} \/\/ namespace blackhole\n<|endoftext|>"} {"text":"<commit_before>#include <nds.h>\n#include <stdlib.h>\n#include <stdio.h>\n#include \"gameboy.h\"\n#include \"gbcpu.h\"\n#include \"gbgfx.h\"\n#include \"gbsnd.h\"\n#include \"mmu.h\"\n#include \"timer.h\"\n#include \"main.h\"\n#include \"inputhelper.h\"\n#include \"nifi.h\"\n#include \"console.h\"\n\nint mode2Cycles, mode3Cycles;\nint scanlineCounter;\nint doubleSpeed;\n\nint turbo;\nint turboFrameSkip;\nint frameskip;\nint frameskipCounter;\nbool fpsOutput=true;\nbool timeOutput=true;\nbool fastForwardMode = false; \/\/ controlled by the menu\nbool fastForwardKey = false; \/\/ only while its hotkey is pressed\n\n\/\/ ...what is phase? I think I made that up. Used for timing when the gameboy \n\/\/ screen is off.\nint phaseCounter;\nint dividerCounter;\nint serialCounter;\n\nint timerCounter;\nint timerPeriod;\nlong periods[4];\n\nbool screenOn = true;\n\nint cyclesToEvent;\nint maxWaitCycles;\n\ninline void setEventCycles(int cycles) {\n if (cycles < cyclesToEvent) {\n cyclesToEvent = cycles;\n \/*\n if (cyclesToEvent <= 0) {\n cyclesToEvent = 1;\n }\n *\/\n }\n}\n\nint updateInput() {\n readKeys();\n int retval = handleEvents();\t\t\/\/ Input mostly\n if (!consoleDebugOutput && getTimerTicks() >= 1000)\n {\n consoleClear();\n int line=0;\n if (fpsOutput) {\n consoleClear();\n printf(\"FPS: %d\\n\", fps);\n line++;\n }\n fps = 0;\n startTimer();\n if (timeOutput) {\n for (; line<23-1; line++)\n printf(\"\\n\");\n time_t rawTime = time(NULL);\n char *timeString = ctime(&rawTime);\n for (int i=0;; i++) {\n if (timeString[i] == ':') {\n timeString += i-2;\n break;\n }\n }\n char s[50];\n strncpy(s, timeString, 50);\n s[5] = '\\0';\n int spaces = 31-strlen(s);\n for (int i=0; i<spaces; i++)\n printf(\" \");\n printf(\"%s\\n\", s);\n }\n }\n return retval;\n}\n\nint extraCycles;\nvoid runEmul()\n{\n for (;;)\n {\nemuLoopStart:\n cyclesToEvent -= extraCycles;\n int cycles;\n if (halt)\n cycles = cyclesToEvent;\n else\n cycles = runOpcode(cyclesToEvent);\n cycles += extraCycles;\n\n cyclesToEvent = maxWaitCycles;\n extraCycles=0;\n\n if (serialCounter > 0) {\n serialCounter -= cycles;\n if (serialCounter <= 0) {\n serialCounter = 0;\n packetData = 0xff;\n transferReady = true;\n }\n else\n setEventCycles(serialCounter);\n }\n if (transferReady) {\n if (!(ioRam[0x02] & 1)) {\n sendPacketByte(56, sendData);\n }\n timerStop(2);\n ioRam[0x01] = packetData;\n requestInterrupt(SERIAL);\n ioRam[0x02] &= ~0x80;\n packetData = -1;\n transferReady = false;\n }\n updateTimers(cycles);\n updateSound(cycles);\n\n if (updateLCD(cycles))\n \/\/ Emulation is being reset or something\n goto emuLoopStart;\n\n int interruptTriggered = ioRam[0x0F] & ioRam[0xFF];\n \/\/ Run another opcode before triggering an interrupt.\n \/\/ Robocop 2 needs this.\n if (interruptTriggered) {\n if (!halt)\n extraCycles += runOpcode(4);\n handleInterrupts(interruptTriggered);\n }\n }\n}\n\nvoid initLCD()\n{\n \/\/ Pokemon Yellow hack: I need to intentionally SLOW DOWN emulation for \n \/\/ Pikachu's pitch to sound right...\n \/\/ The exact value of this will vary, so I'm going to leave it commented for \n \/\/ now.\n \/*\n if (strcmp(getRomTitle(), \"POKEMON YELLOW\") == 0)\n maxWaitCycles = 100;\n else\n *\/\n maxWaitCycles = 800;\n\n setDoubleSpeed(0);\n\n scanlineCounter = 456*(doubleSpeed?2:1);\n phaseCounter = 456*153;\n timerCounter = 0;\n dividerCounter = 256;\n serialCounter = 0;\n turboFrameSkip = 4;\n turbo=0;\n\n \/\/ Timer stuff\n periods[0] = clockSpeed\/4096;\n periods[1] = clockSpeed\/262144;\n periods[2] = clockSpeed\/65536;\n periods[3] = clockSpeed\/16384;\n timerPeriod = periods[0];\n\n timerStop(2);\n}\n\ninline int updateLCD(int cycles)\n{\n if (!(ioRam[0x40] & 0x80))\t\t\/\/ If LCD is off\n {\n scanlineCounter = 456*(doubleSpeed?2:1);;\n ioRam[0x44] = 0;\n ioRam[0x41] &= 0xF8;\n \/\/ Normally timing is synchronized with gameboy's vblank. If the screen \n \/\/ is off, this code kicks in. The \"phaseCounter\" is a counter until the \n \/\/ ds should check for input and whatnot.\n phaseCounter -= cycles;\n if (phaseCounter <= 0) {\n if (!(fastForwardMode || fastForwardKey))\n swiIntrWait(interruptWaitMode, 1);\n fps++;\n phaseCounter += 456*153*(doubleSpeed?2:1);\n if (screenOn) {\n disableScreen();\n screenOn = false;\n }\n if (updateInput())\n return 1;\n }\n return 0;\n }\n\n scanlineCounter -= cycles;\n\n switch(ioRam[0x41]&3)\n {\n case 2:\n {\n if (scanlineCounter <= mode2Cycles) {\n ioRam[0x41]++;\n setEventCycles(scanlineCounter-mode3Cycles);\n }\n else\n setEventCycles(scanlineCounter-mode2Cycles);\n }\n break;\n case 3:\n {\n if (scanlineCounter <= mode3Cycles) {\n ioRam[0x41] &= ~3;\n\n if (ioRam[0x41]&0x8)\n {\n requestInterrupt(LCD);\n }\n\n drawScanline(ioRam[0x44]);\n if (updateHblankDMA()) {\n extraCycles += 50;\n }\n\n setEventCycles(scanlineCounter);\n }\n else\n setEventCycles(scanlineCounter-mode3Cycles);\n }\n break;\n case 0:\n {\n \/\/ fall through to next case\n }\n case 1:\n if (scanlineCounter <= 0)\n {\n scanlineCounter += 456*(doubleSpeed?2:1);\n ioRam[0x44]++;\n\n if (ioRam[0x44] < 144 || ioRam[0x44] >= 153) {\n setEventCycles(scanlineCounter-mode2Cycles);\n ioRam[0x41] &= ~3;\n ioRam[0x41] |= 2;\n if (ioRam[0x41]&0x20)\n {\n requestInterrupt(LCD);\n }\n\n if (ioRam[0x44] >= 153)\n {\n ioRam[0x44] = 0;\n }\n }\n else if (ioRam[0x44] == 144)\n {\n ioRam[0x41] &= ~3;\n ioRam[0x41] |= 1;\n\n requestInterrupt(VBLANK);\n if (ioRam[0x41]&0x10)\n {\n requestInterrupt(LCD);\n }\n\n fps++;\n drawScreen();\n if (!screenOn) {\n enableScreen();\n screenOn = true;\n }\n if (updateInput())\n return 1;\n }\n if (ioRam[0x44] >= 144) {\n setEventCycles(scanlineCounter);\n }\n\n \/\/ LYC check\n if (ioRam[0x44] == ioRam[0x45])\n {\n ioRam[0x41] |= 4;\n if (ioRam[0x41]&0x40)\n requestInterrupt(LCD);\n }\n else\n ioRam[0x41] &= ~4;\n\n }\n else {\n setEventCycles(scanlineCounter);\n }\n break;\n }\n\n return 0;\n}\n\ninline void updateTimers(int cycles)\n{\n if (ioRam[0x07] & 0x4)\n {\n timerCounter -= cycles;\n while (timerCounter <= 0)\n {\n timerCounter = timerPeriod + timerCounter;\n if ((++ioRam[0x05]) == 0)\n {\n requestInterrupt(TIMER);\n ioRam[0x05] = ioRam[0x06];\n }\n }\n setEventCycles(timerCounter+timerPeriod*(255-ioRam[0x05]));\n }\n dividerCounter -= cycles;\n if (dividerCounter <= 0)\n {\n dividerCounter = 256+dividerCounter;\n ioRam[0x04]++;\n }\n \/\/setEventCycles(dividerCounter);\n}\n\n\nvoid requestInterrupt(int id)\n{\n ioRam[0x0F] |= id;\n if (ioRam[0x0F] & ioRam[0xFF])\n cyclesToExecute = 0;\n}\n\nvoid setDoubleSpeed(int val) {\n if (val == 0) {\n mode2Cycles = 456 - 80;\n mode3Cycles = 456 - 172 - 80;\n doubleSpeed = 0;\n ioRam[0x4D] &= ~0x80;\n }\n else {\n mode2Cycles = (456 - 80)*2;\n mode3Cycles = (456 - 172 - 80)*2;\n doubleSpeed = 1;\n ioRam[0x4D] |= 0x80;\n }\n}\n<commit_msg>Sound is updated less often to increase speed<commit_after>#include <nds.h>\n#include <stdlib.h>\n#include <stdio.h>\n#include \"gameboy.h\"\n#include \"gbcpu.h\"\n#include \"gbgfx.h\"\n#include \"gbsnd.h\"\n#include \"mmu.h\"\n#include \"timer.h\"\n#include \"main.h\"\n#include \"inputhelper.h\"\n#include \"nifi.h\"\n#include \"console.h\"\n\nint mode2Cycles, mode3Cycles;\nint scanlineCounter;\nint doubleSpeed;\n\nint turbo;\nint turboFrameSkip;\nint frameskip;\nint frameskipCounter;\nbool fpsOutput=true;\nbool timeOutput=true;\nbool fastForwardMode = false; \/\/ controlled by the menu\nbool fastForwardKey = false; \/\/ only while its hotkey is pressed\n\n\/\/ ...what is phase? I think I made that up. Used for timing when the gameboy \n\/\/ screen is off.\nint phaseCounter;\nint dividerCounter;\nint serialCounter;\n\nint timerCounter;\nint timerPeriod;\nlong periods[4];\n\nbool screenOn = true;\n\nint cyclesToEvent;\nint maxWaitCycles;\n\ninline void setEventCycles(int cycles) {\n if (cycles < cyclesToEvent) {\n cyclesToEvent = cycles;\n \/*\n if (cyclesToEvent <= 0) {\n cyclesToEvent = 1;\n }\n *\/\n }\n}\n\nint updateInput() {\n readKeys();\n int retval = handleEvents();\t\t\/\/ Input mostly\n if (!consoleDebugOutput && getTimerTicks() >= 1000)\n {\n consoleClear();\n int line=0;\n if (fpsOutput) {\n consoleClear();\n printf(\"FPS: %d\\n\", fps);\n line++;\n }\n fps = 0;\n startTimer();\n if (timeOutput) {\n for (; line<23-1; line++)\n printf(\"\\n\");\n time_t rawTime = time(NULL);\n char *timeString = ctime(&rawTime);\n for (int i=0;; i++) {\n if (timeString[i] == ':') {\n timeString += i-2;\n break;\n }\n }\n char s[50];\n strncpy(s, timeString, 50);\n s[5] = '\\0';\n int spaces = 31-strlen(s);\n for (int i=0; i<spaces; i++)\n printf(\" \");\n printf(\"%s\\n\", s);\n }\n }\n return retval;\n}\n\nint soundCycles=0;\nint extraCycles;\nvoid runEmul()\n{\n for (;;)\n {\nemuLoopStart:\n cyclesToEvent -= extraCycles;\n int cycles;\n if (halt)\n cycles = cyclesToEvent;\n else\n cycles = runOpcode(cyclesToEvent);\n cycles += extraCycles;\n\n cyclesToEvent = maxWaitCycles;\n extraCycles=0;\n\n if (serialCounter > 0) {\n serialCounter -= cycles;\n if (serialCounter <= 0) {\n serialCounter = 0;\n packetData = 0xff;\n transferReady = true;\n }\n else\n setEventCycles(serialCounter);\n }\n if (transferReady) {\n if (!(ioRam[0x02] & 1)) {\n sendPacketByte(56, sendData);\n }\n timerStop(2);\n ioRam[0x01] = packetData;\n requestInterrupt(SERIAL);\n ioRam[0x02] &= ~0x80;\n packetData = -1;\n transferReady = false;\n }\n updateTimers(cycles);\n soundCycles += cycles;\n if (soundCycles >= 66666) {\n updateSound(soundCycles);\n soundCycles = 0;\n }\n\n if (updateLCD(cycles))\n \/\/ Emulation is being reset or something\n goto emuLoopStart;\n\n int interruptTriggered = ioRam[0x0F] & ioRam[0xFF];\n \/\/ Run another opcode before triggering an interrupt.\n \/\/ Robocop 2 needs this.\n if (interruptTriggered) {\n if (!halt)\n extraCycles += runOpcode(4);\n handleInterrupts(interruptTriggered);\n }\n }\n}\n\nvoid initLCD()\n{\n \/\/ Pokemon Yellow hack: I need to intentionally SLOW DOWN emulation for \n \/\/ Pikachu's pitch to sound right...\n \/\/ The exact value of this will vary, so I'm going to leave it commented for \n \/\/ now.\n \/*\n if (strcmp(getRomTitle(), \"POKEMON YELLOW\") == 0)\n maxWaitCycles = 100;\n else\n *\/\n maxWaitCycles = 800;\n\n setDoubleSpeed(0);\n\n scanlineCounter = 456*(doubleSpeed?2:1);\n phaseCounter = 456*153;\n timerCounter = 0;\n dividerCounter = 256;\n serialCounter = 0;\n turboFrameSkip = 4;\n turbo=0;\n\n \/\/ Timer stuff\n periods[0] = clockSpeed\/4096;\n periods[1] = clockSpeed\/262144;\n periods[2] = clockSpeed\/65536;\n periods[3] = clockSpeed\/16384;\n timerPeriod = periods[0];\n\n timerStop(2);\n}\n\ninline int updateLCD(int cycles)\n{\n if (!(ioRam[0x40] & 0x80))\t\t\/\/ If LCD is off\n {\n scanlineCounter = 456*(doubleSpeed?2:1);;\n ioRam[0x44] = 0;\n ioRam[0x41] &= 0xF8;\n \/\/ Normally timing is synchronized with gameboy's vblank. If the screen \n \/\/ is off, this code kicks in. The \"phaseCounter\" is a counter until the \n \/\/ ds should check for input and whatnot.\n phaseCounter -= cycles;\n if (phaseCounter <= 0) {\n if (!(fastForwardMode || fastForwardKey))\n swiIntrWait(interruptWaitMode, 1);\n fps++;\n phaseCounter += 456*153*(doubleSpeed?2:1);\n if (screenOn) {\n disableScreen();\n screenOn = false;\n }\n if (updateInput())\n return 1;\n }\n return 0;\n }\n\n scanlineCounter -= cycles;\n\n switch(ioRam[0x41]&3)\n {\n case 2:\n {\n if (scanlineCounter <= mode2Cycles) {\n ioRam[0x41]++;\n setEventCycles(scanlineCounter-mode3Cycles);\n }\n else\n setEventCycles(scanlineCounter-mode2Cycles);\n }\n break;\n case 3:\n {\n if (scanlineCounter <= mode3Cycles) {\n ioRam[0x41] &= ~3;\n\n if (ioRam[0x41]&0x8)\n {\n requestInterrupt(LCD);\n }\n\n drawScanline(ioRam[0x44]);\n if (updateHblankDMA()) {\n extraCycles += 50;\n }\n\n setEventCycles(scanlineCounter);\n }\n else\n setEventCycles(scanlineCounter-mode3Cycles);\n }\n break;\n case 0:\n {\n \/\/ fall through to next case\n }\n case 1:\n if (scanlineCounter <= 0)\n {\n scanlineCounter += 456*(doubleSpeed?2:1);\n ioRam[0x44]++;\n\n if (ioRam[0x44] < 144 || ioRam[0x44] >= 153) {\n setEventCycles(scanlineCounter-mode2Cycles);\n ioRam[0x41] &= ~3;\n ioRam[0x41] |= 2;\n if (ioRam[0x41]&0x20)\n {\n requestInterrupt(LCD);\n }\n\n if (ioRam[0x44] >= 153)\n {\n ioRam[0x44] = 0;\n }\n }\n else if (ioRam[0x44] == 144)\n {\n ioRam[0x41] &= ~3;\n ioRam[0x41] |= 1;\n\n requestInterrupt(VBLANK);\n if (ioRam[0x41]&0x10)\n {\n requestInterrupt(LCD);\n }\n\n fps++;\n drawScreen();\n if (!screenOn) {\n enableScreen();\n screenOn = true;\n }\n if (updateInput())\n return 1;\n }\n if (ioRam[0x44] >= 144) {\n setEventCycles(scanlineCounter);\n }\n\n \/\/ LYC check\n if (ioRam[0x44] == ioRam[0x45])\n {\n ioRam[0x41] |= 4;\n if (ioRam[0x41]&0x40)\n requestInterrupt(LCD);\n }\n else\n ioRam[0x41] &= ~4;\n\n }\n else {\n setEventCycles(scanlineCounter);\n }\n break;\n }\n\n return 0;\n}\n\ninline void updateTimers(int cycles)\n{\n if (ioRam[0x07] & 0x4)\n {\n timerCounter -= cycles;\n while (timerCounter <= 0)\n {\n timerCounter = timerPeriod + timerCounter;\n if ((++ioRam[0x05]) == 0)\n {\n requestInterrupt(TIMER);\n ioRam[0x05] = ioRam[0x06];\n }\n }\n setEventCycles(timerCounter+timerPeriod*(255-ioRam[0x05]));\n }\n dividerCounter -= cycles;\n if (dividerCounter <= 0)\n {\n dividerCounter = 256+dividerCounter;\n ioRam[0x04]++;\n }\n \/\/setEventCycles(dividerCounter);\n}\n\n\nvoid requestInterrupt(int id)\n{\n ioRam[0x0F] |= id;\n if (ioRam[0x0F] & ioRam[0xFF])\n cyclesToExecute = 0;\n}\n\nvoid setDoubleSpeed(int val) {\n if (val == 0) {\n mode2Cycles = 456 - 80;\n mode3Cycles = 456 - 172 - 80;\n doubleSpeed = 0;\n ioRam[0x4D] &= ~0x80;\n }\n else {\n mode2Cycles = (456 - 80)*2;\n mode3Cycles = (456 - 172 - 80)*2;\n doubleSpeed = 1;\n ioRam[0x4D] |= 0x80;\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ $Id: constants.C,v 1.1 2000\/05\/04 18:30:55 oliver Exp $\n\n#include <BALL\/COMMON\/constants.h>\n\nnamespace BALL\n{\n\tnamespace Constants\n\t{\n\t\tdouble EPSILON = 1e-6;\n\t}\n}\n<commit_msg>changed: constants are now extern const (problems with g++\/Linux-alpha)<commit_after>\/\/ $Id: constants.C,v 1.2 2000\/05\/15 19:10:51 oliver Exp $\n\n#include <BALL\/COMMON\/constants.h>\n\nnamespace BALL\n{\n\tnamespace Constants\n\t{\n\t\t\/\/ EPSILON (used fr comparisons)\n\t\tdouble EPSILON = 1e-6;\n\n\t\t\/\/ PI\n\t\tconst double PI = 3.14159265358979323846L;\n\n\t\t\/\/ Euler's number - base of the natural logarithm\n\t\tconst double E = 2.718281828459045235L;\n\t\t\n\t\t\/\/\tElementary charge.\n\t\tconst double\tELEMENTARY_CHARGE = 1.60217738E-19L; \t \/\/ C \n\t\n\t\t\/\/\/ Elementary charge (alias)\n\t\tconst double\te0\t\t\t\t\t\t\t\t=\tELEMENTARY_CHARGE;\n\n\t\t\/\/ Electron mass.\n\t\tconst double\tELECTRON_MASS \t= 9.1093897E-31L; \t \/\/ kg\n\n\t\t\/\/ Proton mass.\n\t\tconst double\tPROTON_MASS \t= 1.6726230E-27L; \t \/\/ kg\n\n\t\t\/\/ Neutron mass.\n\t\tconst double\tNEUTRON_MASS \t= 1.6749286E-27L; \t \/\/ kg\n\n\t\t\/\/ Avogadro constant.\n\t\tconst double\tAVOGADRO \t= 6.0221367E+23L; \t \/\/ 1 \/ mol\n\n\t\t\/\/ Avogadro constant (alias)\n\t\tconst double\tNA\t\t\t\t\t\t\t\t= AVOGADRO;\n\n\t\t\/\/ Avogadro constant (alias)\n\t\tconst double\tMOL \t= AVOGADRO;\n\n\t\t\/\/ Boltzmann constant.\n\t\tconst double\tBOLTZMANN \t= 1.380657E-23L; \t \/\/ J \/ K\n\n\t\t\/\/ Boltzmann constant (alias)\n\t\tconst double\tk\t \t\t\t\t= BOLTZMANN;\n\t\t\n\t\t\/\/ Planck constant.\n\t\tconst double\tPLANCK \t \t= 6.6260754E-34L; \/\/ J * sec\n\n\t\t\/\/ Planck constant (alias)\n\t\tconst double\th \t \t\t\t= PLANCK;\n\n\t\t\/\/ Gas constant (= NA * k)\t\n\t\tconst double\tGAS_CONSTANT \t \t= NA * k;\n\n\t\t\/\/ Gas constant (alias)\n\t\tconst double R \t\t\t\t\t\t\t\t= GAS_CONSTANT;\n\n\t\t\/\/ Faraday constant (= NA * e0)\n\t\tconst double\tFARADAY \t= NA * e0;\n\n\t\t\/\/ Faraday constant (alias)\n\t\tconst double\tF \t\t\t\t\t\t\t= FARADAY;\n\n\t\t\/\/ Bohr radius.\n\t\tconst double\tBOHR_RADIUS \t= 5.29177249E-11L; \/\/ m\n\n\t\t\/\/ Bohr radius (alias)\n\t\tconst double\ta0 \t\t\t\t\t\t= BOHR_RADIUS;\n\n\t\t\/\/ the following values from: \n\t\t\/\/ P.W.Atkins: Physical Chemistry, 5th ed., Oxford University Press, 1995\n\n\t\t\/\/ Vacuum permittivity.\n\t\tconst double\tVACUUM_PERMITTIVITY \t= 8.85419E-12L; \/\/ C^2 \/ (J * m)\n\n\t\t\/\/ Vacuum permeability.\n\t\tconst double\tVACUUM_PERMEABILITY = (4 * PI * 1E-7L);\t\/\/ J s^2 \/ (C^2 * m)\n\n\t\t\/\/ Speed of light.\n\t\tconst double\tSPEED_OF_LIGHT = 2.99792458E+8L;\t \/\/ m \/ s\n\n\t\t\/\/ Speed of Light (alias)\n\t\tconst double\tc\t\t\t\t\t\t\t\t\t\t\t\t= SPEED_OF_LIGHT;\n\n\t\t\/\/ Gravitational constant.\n\t\tconst double\tGRAVITATIONAL_CONSTANT = 6.67259E-11L; \t\/\/ N m^2 \/ kg^2\n\n\t\t\/\/ Fine structure constant.\n\t\tconst double\tFINE_STRUCTURE_CONSTANT = 7.29735E-3L; \t\t\/\/ 1 \n\t\t\t\n\t\t\/\/ Degree per rad.\n\t\tconst double\tDEG_PER_RAD\t\t\t\t= 57.2957795130823209L;\n\n\t\t\/\/ Rad per degree.\n\t\tconst double\tRAD_PER_DEG\t\t\t \t= 0.0174532925199432957L;\n\n\t\t\/\/ mm per inch.\n\t\tconst double\tMM_PER_INCH \t\t\t= 25.4L;\n\n\t\t\/\/ m per foot.\n\t\tconst double\tM_PER_FOOT \t\t\t= 3.048L;\n\n\t\t\/\/ Joule per calorie\n\t\tconst double\tJOULE_PER_CAL = 4.184;\n\n\t\t\/\/ Calories per Joule.\n\t\tconst double\tCAL_PER_JOULE = (1 \/ 4.184);\n\n\t}\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Flexisip, a flexible SIP proxy server with media capabilities.\n * Copyright (C) 2018 Belledonne Communications SARL, All rights reserved.\n *\n * This program is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License as\n * published by the Free Software Foundation, either version 3 of the\n * License, or (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Affero General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public License\n * along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n\n#include <algorithm>\n#include <cstring>\n#include <sstream>\n#include <stdexcept>\n\n#include \"log\/logmanager.hh\"\n\n#include \"external-auth-module.hh\"\n\nusing namespace std;\n\nExternalAuthModule::ExternalAuthModule(su_root_t *root, const std::string &domain, const std::string &algo) : FlexisipAuthModuleBase(root, domain, algo) {\n\tmEngine = nth_engine_create(root, TAG_END());\n}\n\nExternalAuthModule::ExternalAuthModule(su_root_t *root, const std::string &domain, const std::string &algo, int nonceExpire) : FlexisipAuthModuleBase(root, domain, algo, nonceExpire) {\n\tmEngine = nth_engine_create(root, TAG_END());\n}\n\nExternalAuthModule::~ExternalAuthModule() {\n\tnth_engine_destroy(mEngine);\n}\n\nvoid ExternalAuthModule::checkAuthHeader(FlexisipAuthStatus &as, msg_auth_t *credentials, auth_challenger_t const *ach) {\n\ttry {\n\t\tauto &externalAs = dynamic_cast<ExternalAuthModule::Status &>(as);\n\t\tmap<string, string> params = extractParameters(externalAs, *credentials);\n\n\t\tstring uri;\n\t\ttry {\n\t\t\turi = mUriFormater.format(params);\n\t\t} catch (const invalid_argument &e) {\n\t\t\tostringstream os;\n\t\t\tos << \"cannot format HTTP URI: \" << e.what();\n\t\t\tthrow runtime_error(os.str());\n\t\t}\n\n\t\tauto *ctx = new HttpRequestCtx({*this, as});\n\n\t\tnth_client_t *request = nth_client_tcreate(mEngine,\n\t\t\tonHttpResponseCb,\n\t\t\treinterpret_cast<nth_client_magic_t *>(ctx),\n\t\t\thttp_method_get,\n\t\t\t\"GET\",\n\t\t\tURL_STRING_MAKE(uri.c_str()),\n\t\t\tTAG_END()\n\t\t);\n\t\tif (request == nullptr) {\n\t\t\tostringstream os;\n\t\t\tos << \"HTTP request for '\" << uri << \"' has failed\";\n\t\t\tdelete ctx;\n\t\t\tthrow runtime_error(os.str());\n\t\t}\n\t\tSLOGD << \"HTTP request [\" << request << \"] to '\" << uri << \"' successfully sent\";\n\t\tas.status(100);\n\t} catch (const runtime_error &e) {\n\t\tSLOGE << e.what();\n\t\tonError(as);\n\t}\n}\n\nvoid ExternalAuthModule::loadPassword(const FlexisipAuthStatus &as) {\n}\n\nstd::map<std::string, std::string> ExternalAuthModule::extractParameters(const Status &as, const msg_auth_t &credentials) const {\n\tmap<string, string> params;\n\n\tfor (int i = 0; credentials.au_params[i] != nullptr; i++) {\n\t\tconst char *param = credentials.au_params[i];\n\t\tconst char *equal = strchr(const_cast<char *>(param), '=');\n\t\tstring key(param, equal-param);\n\t\tstring value = equal+1;\n\t\tparams[move(key)] = move(value);\n\t}\n\n\tparams[\"scheme\"] = credentials.au_scheme;\n\tparams[\"method\"] = as.method();\n\tparams[\"from\"] = as.fromHeader();\n\tparams[\"sip-instance\"] = as.sipInstance();\n\tparams[\"domain\"] = as.domain();\n\treturn params;\n}\n\nvoid ExternalAuthModule::onHttpResponse(FlexisipAuthStatus &as, nth_client_t *request, const http_t *http) {\n\tshared_ptr<RequestSipEvent> ev;\n\ttry {\n\t\tint sipCode = 0;\n\t\tstring phrase;\n\t\tstring reasonHeaderValue;\n\t\tstring pAssertedIdentity;\n\t\tostringstream os;\n\n\t\tif (http == nullptr) {\n\t\t\tos << \"HTTP server responds with code \" << nth_client_status(request);\n\t\t\tthrow runtime_error(os.str());\n\t\t}\n\n\t\tint status = http->http_status->st_status;\n\t\tSLOGD << \"HTTP response received [\" << status << \"]: \" << endl << http->http_payload;\n\t\tif (status != 200) {\n\t\t\tos << \"unhandled HTTP status code [\" << status << \"]\";\n\t\t\tthrow runtime_error(os.str());\n\t\t}\n\n\t\tstring httpBody = toString(http->http_payload);\n\t\tif (httpBody.empty()) {\n\t\t\tos << \"HTTP server answered with an empty body\";\n\t\t\tthrow runtime_error(os.str());\n\t\t}\n\n\t\ttry {\n\t\t\tmap<string, string> kv = parseHttpBody(httpBody);\n\t\t\tsipCode = stoi(kv[\"Status\"]);\n\t\t\tphrase = move(kv[\"Phrase\"]);\n\t\t\treasonHeaderValue = move(kv[\"Reason\"]);\n\t\t\tpAssertedIdentity = move(kv[\"P-Asserted-Identity\"]);\n\t\t} catch (const logic_error &e) {\n\t\t\tos << \"error while parsing HTTP body: \" << e.what();\n\t\t\tthrow runtime_error(os.str());\n\t\t}\n\n\t\tif (!validSipCode(sipCode) || reasonHeaderValue.empty()) {\n\t\t\tos << \"invalid SIP code or reason\";\n\t\t\tthrow runtime_error(os.str());\n\t\t}\n\n\t\tauto &httpAuthStatus = dynamic_cast<ExternalAuthModule::Status &>(as);\n\t\thttpAuthStatus.status(sipCode == 200 ? 0 : sipCode);\n\t\thttpAuthStatus.phrase(su_strdup(as.home(), phrase.c_str()));\n\t\thttpAuthStatus.reason(reasonHeaderValue);\n\t\thttpAuthStatus.pAssertedIdentity(pAssertedIdentity);\n\t\tfinish(as);\n\t} catch (const runtime_error &e) {\n\t\tSLOGE << \"HTTP request [\" << request << \"]: \" << e.what();\n\t\tonError(as);\n\t} catch (...) {\n\t\tif (request) nth_client_destroy(request);\n\t\tthrow;\n\t}\n\tif (request) nth_client_destroy(request);\n}\n\nstd::map<std::string, std::string> ExternalAuthModule::parseHttpBody(const std::string &body) const {\n\tistringstream is(body);\n\tostringstream os;\n\tmap<string, string> result;\n\tstring line;\n\n\tdo {\n\t\tgetline(is, line);\n\t\tif (line.empty()) continue;\n\n\t\tauto column = find(line.cbegin(), line.cend(), ':');\n\t\tif (column == line.cend()) {\n\t\t\tos << \"invalid line '\" << line << \"': missing column symbol\";\n\t\t\tthrow invalid_argument(os.str());\n\t\t}\n\n\t\tstring &value = result[string(line.cbegin(), column)];\n\t\tauto valueStart = find_if_not(column+1, line.cend(), [](const char &c){return isspace(c) != 0;});\n\t\tif (valueStart == line.cend()) {\n\t\t\tos << \"invalid line '\" << line << \"': missing value\";\n\t\t\tthrow invalid_argument(os.str());\n\t\t}\n\n\t\tvalue.assign(valueStart, line.cend());\n\t} while (!is.eof());\n\treturn result;\n}\n\nint ExternalAuthModule::onHttpResponseCb(nth_client_magic_t *magic, nth_client_t *request, const http_t *http) noexcept {\n\tauto *ctx = reinterpret_cast<HttpRequestCtx *>(magic);\n\tctx->am.onHttpResponse(ctx->as, request, http);\n\tdelete ctx;\n\treturn 0;\n}\n\nstd::string ExternalAuthModule::toString(const http_payload_t *httpPayload) {\n\tif (httpPayload == nullptr || httpPayload->pl_data == nullptr || httpPayload->pl_len == 0) {\n\t\treturn string();\n\t}\n\treturn string(httpPayload->pl_data, httpPayload->pl_len);\n}\n\nbool ExternalAuthModule::validSipCode(int sipCode) {\n\tconst auto it = find(sValidSipCodes.cbegin(), sValidSipCodes.cend(), sipCode);\n\treturn (it != sValidSipCodes.cend());\n}\n\nstd::array<int, 4> ExternalAuthModule::sValidSipCodes{{200, 401, 407, 403}};\n<commit_msg>ExternalAuth: Make Reason header to be optional in the HTTP server response<commit_after>\/*\n * Flexisip, a flexible SIP proxy server with media capabilities.\n * Copyright (C) 2018 Belledonne Communications SARL, All rights reserved.\n *\n * This program is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License as\n * published by the Free Software Foundation, either version 3 of the\n * License, or (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Affero General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public License\n * along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n\n#include <algorithm>\n#include <cstring>\n#include <sstream>\n#include <stdexcept>\n\n#include \"log\/logmanager.hh\"\n\n#include \"external-auth-module.hh\"\n\nusing namespace std;\n\nExternalAuthModule::ExternalAuthModule(su_root_t *root, const std::string &domain, const std::string &algo) : FlexisipAuthModuleBase(root, domain, algo) {\n\tmEngine = nth_engine_create(root, TAG_END());\n}\n\nExternalAuthModule::ExternalAuthModule(su_root_t *root, const std::string &domain, const std::string &algo, int nonceExpire) : FlexisipAuthModuleBase(root, domain, algo, nonceExpire) {\n\tmEngine = nth_engine_create(root, TAG_END());\n}\n\nExternalAuthModule::~ExternalAuthModule() {\n\tnth_engine_destroy(mEngine);\n}\n\nvoid ExternalAuthModule::checkAuthHeader(FlexisipAuthStatus &as, msg_auth_t *credentials, auth_challenger_t const *ach) {\n\ttry {\n\t\tauto &externalAs = dynamic_cast<ExternalAuthModule::Status &>(as);\n\t\tmap<string, string> params = extractParameters(externalAs, *credentials);\n\n\t\tstring uri;\n\t\ttry {\n\t\t\turi = mUriFormater.format(params);\n\t\t} catch (const invalid_argument &e) {\n\t\t\tostringstream os;\n\t\t\tos << \"cannot format HTTP URI: \" << e.what();\n\t\t\tthrow runtime_error(os.str());\n\t\t}\n\n\t\tauto *ctx = new HttpRequestCtx({*this, as});\n\n\t\tnth_client_t *request = nth_client_tcreate(mEngine,\n\t\t\tonHttpResponseCb,\n\t\t\treinterpret_cast<nth_client_magic_t *>(ctx),\n\t\t\thttp_method_get,\n\t\t\t\"GET\",\n\t\t\tURL_STRING_MAKE(uri.c_str()),\n\t\t\tTAG_END()\n\t\t);\n\t\tif (request == nullptr) {\n\t\t\tostringstream os;\n\t\t\tos << \"HTTP request for '\" << uri << \"' has failed\";\n\t\t\tdelete ctx;\n\t\t\tthrow runtime_error(os.str());\n\t\t}\n\t\tSLOGD << \"HTTP request [\" << request << \"] to '\" << uri << \"' successfully sent\";\n\t\tas.status(100);\n\t} catch (const runtime_error &e) {\n\t\tSLOGE << e.what();\n\t\tonError(as);\n\t}\n}\n\nvoid ExternalAuthModule::loadPassword(const FlexisipAuthStatus &as) {\n}\n\nstd::map<std::string, std::string> ExternalAuthModule::extractParameters(const Status &as, const msg_auth_t &credentials) const {\n\tmap<string, string> params;\n\n\tfor (int i = 0; credentials.au_params[i] != nullptr; i++) {\n\t\tconst char *param = credentials.au_params[i];\n\t\tconst char *equal = strchr(const_cast<char *>(param), '=');\n\t\tstring key(param, equal-param);\n\t\tstring value = equal+1;\n\t\tparams[move(key)] = move(value);\n\t}\n\n\tparams[\"scheme\"] = credentials.au_scheme;\n\tparams[\"method\"] = as.method();\n\tparams[\"from\"] = as.fromHeader();\n\tparams[\"sip-instance\"] = as.sipInstance();\n\tparams[\"domain\"] = as.domain();\n\treturn params;\n}\n\nvoid ExternalAuthModule::onHttpResponse(FlexisipAuthStatus &as, nth_client_t *request, const http_t *http) {\n\tshared_ptr<RequestSipEvent> ev;\n\ttry {\n\t\tint sipCode = 0;\n\t\tstring phrase;\n\t\tstring reasonHeaderValue;\n\t\tstring pAssertedIdentity;\n\t\tostringstream os;\n\n\t\tif (http == nullptr) {\n\t\t\tos << \"HTTP server responds with code \" << nth_client_status(request);\n\t\t\tthrow runtime_error(os.str());\n\t\t}\n\n\t\tint status = http->http_status->st_status;\n\t\tSLOGD << \"HTTP response received [\" << status << \"]: \" << endl << http->http_payload;\n\t\tif (status != 200) {\n\t\t\tos << \"unhandled HTTP status code [\" << status << \"]\";\n\t\t\tthrow runtime_error(os.str());\n\t\t}\n\n\t\tstring httpBody = toString(http->http_payload);\n\t\tif (httpBody.empty()) {\n\t\t\tos << \"HTTP server answered with an empty body\";\n\t\t\tthrow runtime_error(os.str());\n\t\t}\n\n\t\ttry {\n\t\t\tmap<string, string> kv = parseHttpBody(httpBody);\n\t\t\tsipCode = stoi(kv[\"Status\"]);\n\t\t\tphrase = move(kv[\"Phrase\"]);\n\t\t\treasonHeaderValue = move(kv[\"Reason\"]);\n\t\t\tpAssertedIdentity = move(kv[\"P-Asserted-Identity\"]);\n\t\t} catch (const logic_error &e) {\n\t\t\tos << \"error while parsing HTTP body: \" << e.what();\n\t\t\tthrow runtime_error(os.str());\n\t\t}\n\n\t\tif (!validSipCode(sipCode)) {\n\t\t\tos << \"invalid SIP code\";\n\t\t\tthrow runtime_error(os.str());\n\t\t}\n\n\t\tauto &httpAuthStatus = dynamic_cast<ExternalAuthModule::Status &>(as);\n\t\thttpAuthStatus.status(sipCode == 200 ? 0 : sipCode);\n\t\thttpAuthStatus.phrase(su_strdup(as.home(), phrase.c_str()));\n\t\thttpAuthStatus.reason(reasonHeaderValue);\n\t\thttpAuthStatus.pAssertedIdentity(pAssertedIdentity);\n\t\tfinish(as);\n\t} catch (const runtime_error &e) {\n\t\tSLOGE << \"HTTP request [\" << request << \"]: \" << e.what();\n\t\tonError(as);\n\t} catch (...) {\n\t\tif (request) nth_client_destroy(request);\n\t\tthrow;\n\t}\n\tif (request) nth_client_destroy(request);\n}\n\nstd::map<std::string, std::string> ExternalAuthModule::parseHttpBody(const std::string &body) const {\n\tistringstream is(body);\n\tostringstream os;\n\tmap<string, string> result;\n\tstring line;\n\n\tdo {\n\t\tgetline(is, line);\n\t\tif (line.empty()) continue;\n\n\t\tauto column = find(line.cbegin(), line.cend(), ':');\n\t\tif (column == line.cend()) {\n\t\t\tos << \"invalid line '\" << line << \"': missing column symbol\";\n\t\t\tthrow invalid_argument(os.str());\n\t\t}\n\n\t\tstring &value = result[string(line.cbegin(), column)];\n\t\tauto valueStart = find_if_not(column+1, line.cend(), [](const char &c){return isspace(c) != 0;});\n\t\tif (valueStart == line.cend()) {\n\t\t\tos << \"invalid line '\" << line << \"': missing value\";\n\t\t\tthrow invalid_argument(os.str());\n\t\t}\n\n\t\tvalue.assign(valueStart, line.cend());\n\t} while (!is.eof());\n\treturn result;\n}\n\nint ExternalAuthModule::onHttpResponseCb(nth_client_magic_t *magic, nth_client_t *request, const http_t *http) noexcept {\n\tauto *ctx = reinterpret_cast<HttpRequestCtx *>(magic);\n\tctx->am.onHttpResponse(ctx->as, request, http);\n\tdelete ctx;\n\treturn 0;\n}\n\nstd::string ExternalAuthModule::toString(const http_payload_t *httpPayload) {\n\tif (httpPayload == nullptr || httpPayload->pl_data == nullptr || httpPayload->pl_len == 0) {\n\t\treturn string();\n\t}\n\treturn string(httpPayload->pl_data, httpPayload->pl_len);\n}\n\nbool ExternalAuthModule::validSipCode(int sipCode) {\n\tconst auto it = find(sValidSipCodes.cbegin(), sValidSipCodes.cend(), sipCode);\n\treturn (it != sValidSipCodes.cend());\n}\n\nstd::array<int, 4> ExternalAuthModule::sValidSipCodes{{200, 401, 407, 403}};\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ This file is part of the Marble Desktop Globe.\n\/\/\n\/\/ This program is free software licensed under the GNU LGPL. You can\n\/\/ find a copy of this license in LICENSE.txt in the top directory of\n\/\/ the source code.\n\/\/\n\/\/ Copyright 2010 Niko Sams <niko.sams@gmail.com>\n\/\/\n\n\n#include \"AltitudeProfile.h\"\n#include <GeoPainter.h>\n#include <GeoSceneLayer.h>\n#include <ViewportParams.h>\n#include <routing\/RoutingManager.h>\n#include <routing\/AlternativeRoutesModel.h>\n#include <GeoDataDocument.h>\n#include <MarbleDebug.h>\n#include <KPlotWidget>\n#include <KPlotObject>\n#include <KPlotAxis>\n#include <AltitudeModel.h>\n#include <MarbleModel.h>\n#include <GeoDataParser.h>\n#include <QFile>\n\n#include \"MarbleGraphicsGridLayout.h\"\n#include \"WidgetGraphicsItem.h\"\n#include <QLabel>\n#include <QLayout>\n\nusing namespace Marble;\n\nAltitudeProfile::AltitudeProfile(const QPointF& point, const QSizeF& size)\n : AbstractFloatItem(point, size), m_isInitialized(false)\n{\n\n}\n\nQStringList AltitudeProfile::backendTypes() const\n{\n return QStringList( \"altitudeProfile\" );\n}\n\nbool AltitudeProfile::isInitialized() const\n{\n return m_isInitialized;\n}\n\nvoid AltitudeProfile::initialize()\n{\n m_isInitialized = true;\n\n connect( marbleModel()->routingManager()->alternativeRoutesModel(), SIGNAL( currentRouteChanged( GeoDataDocument* ) ), SLOT( currentRouteChanged( GeoDataDocument* ) ) );\n connect( marbleModel()->routingManager()->alternativeRoutesModel(), SIGNAL( currentRouteChanged( GeoDataDocument* ) ), SLOT( currentRouteChanged( GeoDataDocument* ) ) );\n\n m_graph = new KPlotWidget();\n m_graph->setAntialiasing( true );\n m_graph->axis( KPlotWidget::TopAxis )->setVisible( false );\n m_graph->axis( KPlotWidget::RightAxis )->setVisible( false );\n m_graph->resetPlot();\n \/\/m_graph->axis( KPlotWidget::LeftAxis )->setLabel( QString() );\n \/\/m_graph->axis( KPlotWidget::LeftAxis )->setLabel(tr(\"Altitude\"));\n m_graph->axis( KPlotWidget::BottomAxis )->setTickLabelsShown(false);\n\n m_plot = new KPlotObject(Qt::red, KPlotObject::Lines, 3);\n m_graph->addPlotObject(m_plot);\n m_graph->setMaximumSize( QSize( 300, 100 ) );\n m_graph->setMinimumSize( QSize( 300, 100 ) );\n\n m_stats = new QLabel(\"Stats\");\n\/\/ setContentSize( QSize( 400, 100 ) );\n QWidget *w = new QWidget();\n w->setMaximumSize( QSize( 400, 100 ) );\n w->setMinimumSize( QSize( 400, 100 ) );\n QHBoxLayout* l = new QHBoxLayout;\n w->setLayout( l );\n l->addWidget( m_graph, 3 );\n l->addWidget( m_stats, 1 );\n\n m_widgetItem = new WidgetGraphicsItem( this );\n m_widgetItem->setWidget( w );\n\n MarbleGraphicsGridLayout *layout = new MarbleGraphicsGridLayout( 1, 1 );\n layout->addItem( m_widgetItem, 0, 0 );\n\n setLayout( layout );\n\n#if 0\n GeoDataParser parser( GeoData_UNKNOWN );\n\n QFile file( \"\/home\/niko\/tracks\/2011-06-12-mattighofen.gpx\" );\n file.open( QIODevice::ReadOnly );\n Q_ASSERT( parser.read( &file ) );\n GeoDataDocument* document = static_cast<GeoDataDocument*>( parser.releaseDocument() );\n Q_ASSERT( document );\n file.close();\n GeoDataPlacemark* routePlacemark = document->placemarkList().first();\n qDebug() << routePlacemark->geometry()->geometryId();\n Q_ASSERT(routePlacemark->geometry()->geometryId() == GeoDataMultiGeometryId);\n GeoDataMultiGeometry* routeWaypoints = static_cast<GeoDataMultiGeometry*>(routePlacemark->geometry());\n qDebug() << \"size\" << routeWaypoints->size(); \/\/ << \"length\" << routeWaypoints->length( EARTH_RADIUS );\n for(int i=0; i < routeWaypoints->size(); ++i) {\n GeoDataGeometry* route2 = routeWaypoints->child(i);\n qDebug() << \"route2.geometryId\" << route2->geometryId();\n Q_ASSERT(route2->geometryId() == GeoDataLineStringId);\n GeoDataLineString* routeWaypoints2 = static_cast<GeoDataLineString*>(route2);\n qDebug() << \"size\" << routeWaypoints2->size() << \"length\" << routeWaypoints2->length(EARTH_RADIUS);\n qreal previousAlt = 0;\n qreal totalIncrease = 0;\n for(int j=0; j< routeWaypoints2->size(); ++j) {\n GeoDataCoordinates coordinate = routeWaypoints2->at( j );\n qDebug() << coordinate.latitude(Marble::GeoDataCoordinates::Degree) << coordinate.longitude(Marble::GeoDataCoordinates::Degree) << coordinate.altitude();\n if (previousAlt && coordinate.altitude() > previousAlt) {\n totalIncrease += coordinate.altitude() - previousAlt;\n }\n previousAlt = coordinate.altitude();\n }\n qDebug() << \"totalIncrease\" << totalIncrease << \"vs. 254m von garmin gemessen\";\n }\n#endif\n}\nvoid AltitudeProfile::currentRouteChanged( GeoDataDocument* route )\n{\n m_plot->clearPoints();\n\n qint32 minY = INT_MAX;\n qint32 maxY = 0;\n quint32 numDataPoints = 0;\n qDebug() << \"*************************\";\n\n GeoDataPlacemark* routePlacemark = route->placemarkList().first();\n Q_ASSERT(routePlacemark->geometry()->geometryId() == GeoDataLineStringId);\n GeoDataLineString* routeWaypoints = static_cast<GeoDataLineString*>(routePlacemark->geometry());\n qDebug() << routeWaypoints->length( EARTH_RADIUS );\n qreal totalIncrease = 0;\n qreal totalIncreaseAvg = 0;\n qreal totalDecreaseAvg = 0;\n qreal lastAltitude = -100000;\n qreal lastAvgAltitude = -100000;\n QList<qreal> allAltitudes;\n for(int i=1; i < routeWaypoints->size(); ++i) {\n GeoDataCoordinates coordinate = routeWaypoints->at( i );\n GeoDataCoordinates coordinatePrev = routeWaypoints->at( i - 1 );\n \/\/qreal altitude = marbleModel()->altitudeModel()->height(coordinate.latitude(Marble::GeoDataCoordinates::Degree), coordinate.longitude(Marble::GeoDataCoordinates::Degree));\n QList<qreal> altitudes = marbleModel()->altitudeModel()->heightProfile(\n coordinatePrev.latitude(Marble::GeoDataCoordinates::Degree),\n coordinatePrev.longitude(Marble::GeoDataCoordinates::Degree),\n coordinate.latitude(Marble::GeoDataCoordinates::Degree),\n coordinate.longitude(Marble::GeoDataCoordinates::Degree)\n );\n foreach(const qreal altitude, altitudes) {\n qDebug() << \"POINT\" << numDataPoints << coordinate.longitude(Marble::GeoDataCoordinates::Degree) << coordinate.latitude(Marble::GeoDataCoordinates::Degree)\n << \"height\" << altitude;\n allAltitudes << altitude;\n if ( allAltitudes.count() >= 10 ) {\n qreal avgAltitude = 0;\n for(int j=0; j<10; ++j) {\n avgAltitude += allAltitudes.at(allAltitudes.count()-j-1);\n }\n avgAltitude = avgAltitude \/ 10;\n if (lastAvgAltitude != -100000 && avgAltitude > lastAvgAltitude) {\n totalIncreaseAvg += avgAltitude-lastAvgAltitude;\n }\n if (lastAvgAltitude != -100000 && avgAltitude < lastAvgAltitude) {\n totalDecreaseAvg -= avgAltitude-lastAvgAltitude;\n }\n lastAvgAltitude = avgAltitude;\n }\n if ( lastAltitude != -100000 && altitude > lastAltitude ) {\n totalIncrease += altitude - lastAltitude;\n qDebug() << \"INCREASE +=\" << altitude - lastAltitude << \"totalIncrease is now\" << totalIncrease;\n }\n\n double value = altitude;\n \/\/qDebug() << \"value\" << value;\n m_plot->addPoint(numDataPoints++, value);\n if (value > maxY) maxY = value;\n if (value < minY) minY = value;\n lastAltitude = altitude;\n }\n }\n qDebug() << \"TOTAL INCREASE\" << totalIncrease;\n qDebug() << \"TOTAL INCREASE AVG\" << totalIncreaseAvg;\n\n m_graph->setLimits( 0, numDataPoints, minY - minY \/ 5, maxY + maxY \/ 5 );\n\n m_stats->setText( tr( \"Gain:<br>%0m<br>Loss:<br>%1m\" ).arg( totalIncreaseAvg ).arg( totalDecreaseAvg ) );\n}\n\n\nQIcon AltitudeProfile::icon() const\n{\n return QIcon();\n}\n\nQString AltitudeProfile::description() const\n{\n return tr( \"This is a float item that displays the altitude profile of a track.\" );\n}\n\nQString AltitudeProfile::nameId() const\n{\n return QString( \"altitudeProfile\" );\n}\n\nQString AltitudeProfile::guiString() const\n{\n return tr( \"&Altitude Profile\" );\n}\n\nQString AltitudeProfile::name() const\n{\n return QString( \"Altitude Profile\" );\n}\n\nQ_EXPORT_PLUGIN2( AltitudeProfile, Marble::AltitudeProfile )\n\n#include \"AltitudeProfile.moc\"\n\n<commit_msg>check for GeoDataFolder, sometimes a route is in one<commit_after>\/\/\n\/\/ This file is part of the Marble Desktop Globe.\n\/\/\n\/\/ This program is free software licensed under the GNU LGPL. You can\n\/\/ find a copy of this license in LICENSE.txt in the top directory of\n\/\/ the source code.\n\/\/\n\/\/ Copyright 2010 Niko Sams <niko.sams@gmail.com>\n\/\/\n\n\n#include \"AltitudeProfile.h\"\n#include <GeoPainter.h>\n#include <GeoSceneLayer.h>\n#include <ViewportParams.h>\n#include <routing\/RoutingManager.h>\n#include <routing\/AlternativeRoutesModel.h>\n#include <GeoDataDocument.h>\n#include <MarbleDebug.h>\n#include <KPlotWidget>\n#include <KPlotObject>\n#include <KPlotAxis>\n#include <AltitudeModel.h>\n#include <MarbleModel.h>\n#include <GeoDataParser.h>\n#include <QFile>\n\n#include \"MarbleGraphicsGridLayout.h\"\n#include \"WidgetGraphicsItem.h\"\n#include <QLabel>\n#include <QLayout>\n#include <GeoDataFolder.h>\n\nusing namespace Marble;\n\nAltitudeProfile::AltitudeProfile(const QPointF& point, const QSizeF& size)\n : AbstractFloatItem(point, size), m_isInitialized(false)\n{\n\n}\n\nQStringList AltitudeProfile::backendTypes() const\n{\n return QStringList( \"altitudeProfile\" );\n}\n\nbool AltitudeProfile::isInitialized() const\n{\n return m_isInitialized;\n}\n\nvoid AltitudeProfile::initialize()\n{\n m_isInitialized = true;\n\n connect( marbleModel()->routingManager()->alternativeRoutesModel(), SIGNAL( currentRouteChanged( GeoDataDocument* ) ), SLOT( currentRouteChanged( GeoDataDocument* ) ) );\n connect( marbleModel()->routingManager()->alternativeRoutesModel(), SIGNAL( currentRouteChanged( GeoDataDocument* ) ), SLOT( currentRouteChanged( GeoDataDocument* ) ) );\n\n m_graph = new KPlotWidget();\n m_graph->setAntialiasing( true );\n m_graph->axis( KPlotWidget::TopAxis )->setVisible( false );\n m_graph->axis( KPlotWidget::RightAxis )->setVisible( false );\n m_graph->resetPlot();\n \/\/m_graph->axis( KPlotWidget::LeftAxis )->setLabel( QString() );\n \/\/m_graph->axis( KPlotWidget::LeftAxis )->setLabel(tr(\"Altitude\"));\n m_graph->axis( KPlotWidget::BottomAxis )->setTickLabelsShown(false);\n\n m_plot = new KPlotObject(Qt::red, KPlotObject::Lines, 3);\n m_graph->addPlotObject(m_plot);\n m_graph->setMaximumSize( QSize( 300, 100 ) );\n m_graph->setMinimumSize( QSize( 300, 100 ) );\n\n m_stats = new QLabel(\"Stats\");\n\/\/ setContentSize( QSize( 400, 100 ) );\n QWidget *w = new QWidget();\n w->setMaximumSize( QSize( 400, 100 ) );\n w->setMinimumSize( QSize( 400, 100 ) );\n QHBoxLayout* l = new QHBoxLayout;\n w->setLayout( l );\n l->addWidget( m_graph, 3 );\n l->addWidget( m_stats, 1 );\n\n m_widgetItem = new WidgetGraphicsItem( this );\n m_widgetItem->setWidget( w );\n\n MarbleGraphicsGridLayout *layout = new MarbleGraphicsGridLayout( 1, 1 );\n layout->addItem( m_widgetItem, 0, 0 );\n\n setLayout( layout );\n\n#if 0\n GeoDataParser parser( GeoData_UNKNOWN );\n\n QFile file( \"\/home\/niko\/tracks\/2011-06-12-mattighofen.gpx\" );\n file.open( QIODevice::ReadOnly );\n Q_ASSERT( parser.read( &file ) );\n GeoDataDocument* document = static_cast<GeoDataDocument*>( parser.releaseDocument() );\n Q_ASSERT( document );\n file.close();\n GeoDataPlacemark* routePlacemark = document->placemarkList().first();\n qDebug() << routePlacemark->geometry()->geometryId();\n Q_ASSERT(routePlacemark->geometry()->geometryId() == GeoDataMultiGeometryId);\n GeoDataMultiGeometry* routeWaypoints = static_cast<GeoDataMultiGeometry*>(routePlacemark->geometry());\n qDebug() << \"size\" << routeWaypoints->size(); \/\/ << \"length\" << routeWaypoints->length( EARTH_RADIUS );\n for(int i=0; i < routeWaypoints->size(); ++i) {\n GeoDataGeometry* route2 = routeWaypoints->child(i);\n qDebug() << \"route2.geometryId\" << route2->geometryId();\n Q_ASSERT(route2->geometryId() == GeoDataLineStringId);\n GeoDataLineString* routeWaypoints2 = static_cast<GeoDataLineString*>(route2);\n qDebug() << \"size\" << routeWaypoints2->size() << \"length\" << routeWaypoints2->length(EARTH_RADIUS);\n qreal previousAlt = 0;\n qreal totalIncrease = 0;\n for(int j=0; j< routeWaypoints2->size(); ++j) {\n GeoDataCoordinates coordinate = routeWaypoints2->at( j );\n qDebug() << coordinate.latitude(Marble::GeoDataCoordinates::Degree) << coordinate.longitude(Marble::GeoDataCoordinates::Degree) << coordinate.altitude();\n if (previousAlt && coordinate.altitude() > previousAlt) {\n totalIncrease += coordinate.altitude() - previousAlt;\n }\n previousAlt = coordinate.altitude();\n }\n qDebug() << \"totalIncrease\" << totalIncrease << \"vs. 254m von garmin gemessen\";\n }\n#endif\n}\nvoid AltitudeProfile::currentRouteChanged( GeoDataDocument* route )\n{\n m_plot->clearPoints();\n\n qint32 minY = INT_MAX;\n qint32 maxY = 0;\n quint32 numDataPoints = 0;\n qDebug() << \"*************************\";\n\n GeoDataPlacemark* routePlacemark = 0;\n Q_ASSERT(route->size());\n if ( !route->placemarkList().count() ) {\n qDebug() << \"no placemarks found?!\";\n for(int i=0; i<route->size(); ++i) {\n qDebug() << \"nodeType\" << i << route->child( i )->nodeType();\n if ( dynamic_cast<GeoDataFolder*>( route->child( i ) ) ) {\n Q_ASSERT( static_cast<GeoDataFolder*>( route->child( i ) )->placemarkList().size() );\n routePlacemark = static_cast<GeoDataFolder*>( route->child( i ) )->placemarkList().first();\n }\n }\n } else {\n routePlacemark = route->placemarkList().first();\n }\n Q_ASSERT(routePlacemark);\n Q_ASSERT(routePlacemark->geometry()->geometryId() == GeoDataLineStringId);\n GeoDataLineString* routeWaypoints = static_cast<GeoDataLineString*>(routePlacemark->geometry());\n qDebug() << routeWaypoints->length( EARTH_RADIUS );\n qreal totalIncrease = 0;\n qreal totalIncreaseAvg = 0;\n qreal totalDecreaseAvg = 0;\n qreal lastAltitude = -100000;\n qreal lastAvgAltitude = -100000;\n QList<qreal> allAltitudes;\n for(int i=1; i < routeWaypoints->size(); ++i) {\n GeoDataCoordinates coordinate = routeWaypoints->at( i );\n GeoDataCoordinates coordinatePrev = routeWaypoints->at( i - 1 );\n \/\/qreal altitude = marbleModel()->altitudeModel()->height(coordinate.latitude(Marble::GeoDataCoordinates::Degree), coordinate.longitude(Marble::GeoDataCoordinates::Degree));\n QList<qreal> altitudes = marbleModel()->altitudeModel()->heightProfile(\n coordinatePrev.latitude(Marble::GeoDataCoordinates::Degree),\n coordinatePrev.longitude(Marble::GeoDataCoordinates::Degree),\n coordinate.latitude(Marble::GeoDataCoordinates::Degree),\n coordinate.longitude(Marble::GeoDataCoordinates::Degree)\n );\n foreach(const qreal altitude, altitudes) {\n qDebug() << \"POINT\" << numDataPoints << coordinate.longitude(Marble::GeoDataCoordinates::Degree) << coordinate.latitude(Marble::GeoDataCoordinates::Degree)\n << \"height\" << altitude;\n allAltitudes << altitude;\n if ( allAltitudes.count() >= 10 ) {\n qreal avgAltitude = 0;\n for(int j=0; j<10; ++j) {\n avgAltitude += allAltitudes.at(allAltitudes.count()-j-1);\n }\n avgAltitude = avgAltitude \/ 10;\n if (lastAvgAltitude != -100000 && avgAltitude > lastAvgAltitude) {\n totalIncreaseAvg += avgAltitude-lastAvgAltitude;\n }\n if (lastAvgAltitude != -100000 && avgAltitude < lastAvgAltitude) {\n totalDecreaseAvg -= avgAltitude-lastAvgAltitude;\n }\n lastAvgAltitude = avgAltitude;\n }\n if ( lastAltitude != -100000 && altitude > lastAltitude ) {\n totalIncrease += altitude - lastAltitude;\n qDebug() << \"INCREASE +=\" << altitude - lastAltitude << \"totalIncrease is now\" << totalIncrease;\n }\n\n double value = altitude;\n \/\/qDebug() << \"value\" << value;\n m_plot->addPoint(numDataPoints++, value);\n if (value > maxY) maxY = value;\n if (value < minY) minY = value;\n lastAltitude = altitude;\n }\n }\n qDebug() << \"TOTAL INCREASE\" << totalIncrease;\n qDebug() << \"TOTAL INCREASE AVG\" << totalIncreaseAvg;\n\n m_graph->setLimits( 0, numDataPoints, minY - minY \/ 5, maxY + maxY \/ 5 );\n\n m_stats->setText( tr( \"Gain:<br>%0m<br>Loss:<br>%1m\" ).arg( totalIncreaseAvg ).arg( totalDecreaseAvg ) );\n}\n\n\nQIcon AltitudeProfile::icon() const\n{\n return QIcon();\n}\n\nQString AltitudeProfile::description() const\n{\n return tr( \"This is a float item that displays the altitude profile of a track.\" );\n}\n\nQString AltitudeProfile::nameId() const\n{\n return QString( \"altitudeProfile\" );\n}\n\nQString AltitudeProfile::guiString() const\n{\n return tr( \"&Altitude Profile\" );\n}\n\nQString AltitudeProfile::name() const\n{\n return QString( \"Altitude Profile\" );\n}\n\nQ_EXPORT_PLUGIN2( AltitudeProfile, Marble::AltitudeProfile )\n\n#include \"AltitudeProfile.moc\"\n\n<|endoftext|>"} {"text":"<commit_before>#pragma once\n#include \"support\/cpp14.hpp\"\n#include <string>\n#include <algorithm>\n#include <cctype>\n\n#if defined(_MSC_VER) && _MSC_VER <= 1800 \/\/ a bit of a hack...\n#define snprintf _snprintf\n#endif\n\nnamespace fmt {\n\ninline void print(const std::string& str, bool flush = false) {\n printf(\"%s\", str.c_str());\n if (flush)\n fflush(stdout);\n}\n\ninline void println(const std::string& str, bool flush = false) {\n print(str);\n printf(\"\\n\");\n if (flush)\n fflush(stdout);\n}\n\n\/\/ specialize for desired class\ninline std::string str(const std::string& s) { return s; }\n\nnamespace detail {\n inline const char* norm_arg(const std::string& x) { return x.c_str(); }\n\n template<class T> cpp14::enable_if_t<std::is_integral<T>::value, long> norm_arg(T x) { return x; }\n template<class T> cpp14::enable_if_t<std::is_floating_point<T>::value, double> norm_arg(T x) { return x; }\n template<class T> cpp14::enable_if_t<std::is_pointer<T>::value, T> norm_arg(T x) { return x; }\n\n template<class T> cpp14::enable_if_t<\n !std::is_integral<T>::value &&\n !std::is_floating_point<T>::value &&\n !std::is_pointer<T>::value,\n const T*\n >\n inline norm_arg(const T& x) { return &x; }\n\n template<class R, class P>\n inline auto norm_arg(const std::chrono::duration<R, P>& x) -> decltype(norm_arg(x.count())) {\n return norm_arg(x.count());\n }\n\n template<class T>\n inline std::string conversion_specifier(const T* t) { return \".0s\" + str(*t); }\n inline constexpr char conversion_specifier(long) { return 'd'; }\n inline constexpr char conversion_specifier(double) { return 'f'; }\n inline constexpr char conversion_specifier(const char*) { return 's'; }\n\n template<class T> inline bool check_specifier(char) { return false; }\n template<> inline bool check_specifier<long>(char type) { return type == 'd' || type == 'i'; }\n template<> inline bool check_specifier<double>(char type) { return type == 'f' || type == 'g' || type == 'e'; }\n template<> inline bool check_specifier<const char*>(char type) { return type == 's'; }\n\n struct convert_and_check_format {\n template <class... Ts>\n convert_and_check_format(const std::string& fmt, const Ts&... ts)\n : _begin{fmt.begin()}, _end{fmt.end()}\n {\n format.reserve(fmt.size());\n convert(ts...);\n }\n\n const char* c_str() const { return format.c_str(); }\n\n private:\n using iter_t = std::string::const_iterator;\n\n iter_t append(iter_t from, const iter_t to) {\n for (; from != to; ++from) {\n if (*from == '}' && (from + 1) != to && *(from + 1) == '}')\n continue; \/\/ only print one close brace \"}}\"\n\n format.push_back(*from);\n if (*from == '%') \/\/ escape % by doubling it\n format.push_back('%');\n }\n return to;\n }\n\n void convert() {\n \/\/ no arguments left, we don't want to find any more format specifiers\n it = std::find(_begin, _end, '{');\n if (it != _end && it + 1 != _end) {\n ++it;\n if (*it == '{') { \/\/ skip double brace \"{{\"\n append(_begin, it);\n _begin = it + 1;\n }\n else {\n throw std::logic_error{\"Too many format specifiers.\"};\n }\n }\n\n append(_begin, _end); \/\/ copy everything that's left\n }\n\n template <class T, class... Ts>\n void convert(const T& t, const Ts&... ts) {\n \/\/ look for a *single* open brace\n do {\n it = std::find(_begin, _end, '{');\n if (it == _end || it + 1 == _end)\n throw std::logic_error{\"Too few format specifiers.\"};\n\n ++it;\n if (*it == '{') { \/\/ skip double brace \"{{\"\n append(_begin, it);\n _begin = it + 1;\n }\n } while (*it == '{');\n\n \/\/ copy everything before the open brace\n _begin = append(_begin, it - 1);\n\n \/\/ replace '{' with '%'\n format.push_back('%');\n\n \/\/ look for close brace\n it = std::find(_begin, _end, '}');\n if (it == _end)\n throw std::logic_error{\"Unclosed brace fromat specifier.\"};\n\n _begin = std::find(_begin, it, ':');\n if (_begin == it || _begin + 1 == it) { \/\/ automatically deduce type\n format += detail::conversion_specifier(t);\n }\n else { \/\/ check type\n if (!detail::check_specifier<T>(*(it - 1)))\n throw std::logic_error{\"Invalid format specifier: \" + std::string(it - 1, it)};\n\n format.append(_begin + 1, it);\n }\n\n _begin = it + 1;\n convert(ts...); \/\/ this is not recursion (calling different function template)\n }\n\n private:\n iter_t it, _begin;\n const iter_t _end;\n std::string format;\n };\n}\n\ntemplate<class... Ts>\nstd::string format(std::string fmt, Ts&&... ts) {\n const auto new_fmt = detail::convert_and_check_format(fmt, detail::norm_arg(ts)...);\n\n auto size = 2 * fmt.size();\n do {\n fmt.resize(size + 1);\n auto ret = snprintf(&fmt[0], fmt.size(), new_fmt.c_str(), detail::norm_arg(ts)...);\n if (ret >= 0)\n size = ret;\n else\n throw std::runtime_error{\"Error while using snprintf() in fmt::format().\"};\n } while (size > fmt.size());\n\n fmt.resize(size);\n return fmt;\n}\n\ninline std::string with_suffix(int number) {\n \/\/ number to string with SI suffix, e.g.: 14226 -> 14.2k, 5395984 -> 5.4M\n if (number >= 1000000)\n return format(\"{:.1f}M\", number \/ 1000000.0);\n else if (number > 1000)\n return format(\"{:.1f}k\", number \/ 1000.0);\n else\n return std::to_string(number);\n}\n\n} \/\/ namespace fmt\n<commit_msg>Fixed format() on VS2013<commit_after>#pragma once\n#include \"support\/cpp14.hpp\"\n#include <string>\n#include <algorithm>\n#include <cctype>\n\n#if defined(_MSC_VER) && _MSC_VER <= 1800 \/\/ VS2013 does not have a C99 compliant snprintf\n# include <cstdarg>\n# define snprintf c99_snprintf\n\ninline int c99_snprintf(char* str, size_t size, const char* format, ...) {\n int count = -1;\n va_list ap;\n\n va_start(ap, format);\n if (size != 0)\n count = _vsnprintf_s(str, size, _TRUNCATE, format, ap);\n if (count == -1)\n count = _vscprintf(format, ap);\n va_end(ap);\n\n return count;\n}\n#endif\n\nnamespace fmt {\n\ninline void print(const std::string& str, bool flush = false) {\n printf(\"%s\", str.c_str());\n if (flush)\n fflush(stdout);\n}\n\ninline void println(const std::string& str, bool flush = false) {\n print(str);\n printf(\"\\n\");\n if (flush)\n fflush(stdout);\n}\n\n\/\/ specialize for desired class\ninline std::string str(const std::string& s) { return s; }\n\nnamespace detail {\n inline const char* norm_arg(const std::string& x) { return x.c_str(); }\n\n template<class T> cpp14::enable_if_t<std::is_integral<T>::value, long> norm_arg(T x) { return x; }\n template<class T> cpp14::enable_if_t<std::is_floating_point<T>::value, double> norm_arg(T x) { return x; }\n template<class T> cpp14::enable_if_t<std::is_pointer<T>::value, T> norm_arg(T x) { return x; }\n\n template<class T> cpp14::enable_if_t<\n !std::is_integral<T>::value &&\n !std::is_floating_point<T>::value &&\n !std::is_pointer<T>::value,\n const T*\n >\n inline norm_arg(const T& x) { return &x; }\n\n template<class R, class P>\n inline auto norm_arg(const std::chrono::duration<R, P>& x) -> decltype(norm_arg(x.count())) {\n return norm_arg(x.count());\n }\n\n template<class T>\n inline std::string conversion_specifier(const T* t) { return \".0s\" + str(*t); }\n inline constexpr char conversion_specifier(long) { return 'd'; }\n inline constexpr char conversion_specifier(double) { return 'f'; }\n inline constexpr char conversion_specifier(const char*) { return 's'; }\n\n template<class T> inline bool check_specifier(char) { return false; }\n template<> inline bool check_specifier<long>(char type) { return type == 'd' || type == 'i'; }\n template<> inline bool check_specifier<double>(char type) { return type == 'f' || type == 'g' || type == 'e'; }\n template<> inline bool check_specifier<const char*>(char type) { return type == 's'; }\n\n struct convert_and_check_format {\n template <class... Ts>\n convert_and_check_format(const std::string& fmt, const Ts&... ts)\n : _begin{fmt.begin()}, _end{fmt.end()}\n {\n format.reserve(fmt.size());\n convert(ts...);\n }\n\n const char* c_str() const { return format.c_str(); }\n\n private:\n using iter_t = std::string::const_iterator;\n\n iter_t append(iter_t from, const iter_t to) {\n for (; from != to; ++from) {\n if (*from == '}' && (from + 1) != to && *(from + 1) == '}')\n continue; \/\/ only print one close brace \"}}\"\n\n format.push_back(*from);\n if (*from == '%') \/\/ escape % by doubling it\n format.push_back('%');\n }\n return to;\n }\n\n void convert() {\n \/\/ no arguments left, we don't want to find any more format specifiers\n it = std::find(_begin, _end, '{');\n if (it != _end && it + 1 != _end) {\n ++it;\n if (*it == '{') { \/\/ skip double brace \"{{\"\n append(_begin, it);\n _begin = it + 1;\n }\n else {\n throw std::logic_error{\"Too many format specifiers.\"};\n }\n }\n\n append(_begin, _end); \/\/ copy everything that's left\n }\n\n template <class T, class... Ts>\n void convert(const T& t, const Ts&... ts) {\n \/\/ look for a *single* open brace\n do {\n it = std::find(_begin, _end, '{');\n if (it == _end || it + 1 == _end)\n throw std::logic_error{\"Too few format specifiers.\"};\n\n ++it;\n if (*it == '{') { \/\/ skip double brace \"{{\"\n append(_begin, it);\n _begin = it + 1;\n }\n } while (*it == '{');\n\n \/\/ copy everything before the open brace\n _begin = append(_begin, it - 1);\n\n \/\/ replace '{' with '%'\n format.push_back('%');\n\n \/\/ look for close brace\n it = std::find(_begin, _end, '}');\n if (it == _end)\n throw std::logic_error{\"Unclosed brace fromat specifier.\"};\n\n _begin = std::find(_begin, it, ':');\n if (_begin == it || _begin + 1 == it) { \/\/ automatically deduce type\n format += detail::conversion_specifier(t);\n }\n else { \/\/ check type\n if (!detail::check_specifier<T>(*(it - 1)))\n throw std::logic_error{\"Invalid format specifier: \" + std::string(it - 1, it)};\n\n format.append(_begin + 1, it);\n }\n\n _begin = it + 1;\n convert(ts...); \/\/ this is not recursion (calling different function template)\n }\n\n private:\n iter_t it, _begin;\n const iter_t _end;\n std::string format;\n };\n}\n\ntemplate<class... Ts>\nstd::string format(std::string fmt, Ts&&... ts) {\n const auto new_fmt = detail::convert_and_check_format(fmt, detail::norm_arg(ts)...);\n\n auto size = 2 * fmt.size();\n do {\n fmt.resize(size + 1);\n auto ret = snprintf(&fmt[0], fmt.size(), new_fmt.c_str(), detail::norm_arg(ts)...);\n if (ret >= 0)\n size = ret;\n else\n throw std::runtime_error{\"Error while using snprintf() in fmt::format().\"};\n } while (size > fmt.size());\n\n fmt.resize(size);\n return fmt;\n}\n\ninline std::string with_suffix(int number) {\n \/\/ number to string with SI suffix, e.g.: 14226 -> 14.2k, 5395984 -> 5.4M\n if (number >= 1000000)\n return format(\"{:.1f}M\", number \/ 1000000.0);\n else if (number > 1000)\n return format(\"{:.1f}k\", number \/ 1000.0);\n else\n return std::to_string(number);\n}\n\n} \/\/ namespace fmt\n<|endoftext|>"} {"text":"<commit_before>#ifndef LIBTEN_SHARED_POOL_HH\n#define LIBTEN_SHARED_POOL_HH\n\n#include \"task\/rendez.hh\"\n#include \"ten\/logging.hh\"\n\n#include <boost\/call_traits.hpp>\n#include <set>\n#include <deque>\n#include <memory>\n#include <atomic>\n\nnamespace ten {\n\nnamespace detail {\n template <typename T> class scoped_resource;\n}\n\n\/\/! thread and task safe pool of shared resources\n\/\/\n\/\/! useful for connection pools and other types of shared resources\ntemplate <typename ResourceT, typename ScopeT = detail::scoped_resource<ResourceT> >\nclass shared_pool {\npublic:\n \/\/ use this scoped_resource type to RAII resources from the pool\n typedef ScopeT scoped_resource;\n typedef std::deque<std::shared_ptr<ResourceT> > queue_type;\n typedef std::set<std::shared_ptr<ResourceT> > set_type;\n typedef std::function<std::shared_ptr<ResourceT> ()> alloc_func;\nprotected:\n template <typename TT> friend class detail::scoped_resource;\n\n struct pool_impl {\n qutex mut;\n rendez not_empty;\n queue_type q;\n set_type set;\n std::string name;\n alloc_func new_resource;\n ssize_t max;\n };\n\n std::mutex _mutex;\n std::shared_ptr<pool_impl> _m;\n\n std::shared_ptr<pool_impl> get_safe() {\n#if 0\n return std::atomic_load(&_m);\n#else\n std::lock_guard<std::mutex> lock(_mutex);\n return _m;\n#endif\n }\n\n void set_safe(std::shared_ptr<pool_impl> &other) {\n#if 0\n std::atomic_store(&_m, other);\n#else\n\n std::lock_guard<std::mutex> lock(_mutex);\n _m = other;\n#endif\n }\n\npublic:\n shared_pool(const std::string &name_,\n const alloc_func &alloc_,\n ssize_t max_ = -1)\n {\n std::shared_ptr<pool_impl> m = std::make_shared<pool_impl>();\n m->name = name_;\n m->new_resource = alloc_;\n m->max = max_;\n set_safe(m);\n }\n\n shared_pool(const shared_pool &) = delete;\n shared_pool &operator =(const shared_pool &) = delete;\n\n size_t size() {\n std::shared_ptr<pool_impl> m(get_safe());\n std::lock_guard<qutex> lk(m->mut);\n return m->set.size();\n }\n\n void clear() {\n std::shared_ptr<pool_impl> m(get_safe());\n std::lock_guard<qutex> lk(m->ut);\n m->q.clear();\n m->set.clear();\n }\n\n const std::string &name() {\n std::shared_ptr<pool_impl> m(get_safe());\n return m->name;\n }\n\nprotected:\n bool is_not_empty() {\n std::shared_ptr<pool_impl> m(get_safe());\n return !m->q.empty();\n }\n\n static std::shared_ptr<ResourceT> acquire(std::shared_ptr<pool_impl> &m) {\n std::unique_lock<qutex> lk(m->mut);\n return create_or_acquire_with_lock(m, lk);\n }\n\n \/\/ internal, does not lock mutex\n static std::shared_ptr<ResourceT> create_or_acquire_with_lock(std::shared_ptr<pool_impl> &m, std::unique_lock<qutex> &lk) {\n while (m->q.empty()) {\n if (m->max < 0 || m->set.size() < (size_t)m->max) {\n \/\/ need to create a new resource\n return add_new_resource(m, lk);\n break;\n } else {\n \/\/ can't create anymore we're at max, try waiting\n \/\/ we don't use a predicate here because\n \/\/ we might be woken up from destroy()\n \/\/ in which case we might not be at max anymore\n m->not_empty.sleep(lk);\n }\n }\n\n CHECK(!m->q.empty());\n \/\/ pop resource from front of queue\n std::shared_ptr<ResourceT> c = m->q.front();\n m->q.pop_front();\n CHECK(c) << \"acquire shared resource failed in pool: \" << m->name;\n return c;\n }\n\n static void release(std::shared_ptr<pool_impl> &m, std::shared_ptr<ResourceT> &c) {\n safe_lock<qutex> lk(m->mut);\n \/\/ don't add resource to queue if it was removed from _set\n if (m->set.count(c)) {\n m->q.push_front(c);\n m->not_empty.wakeup();\n }\n }\n\n static void destroy(std::shared_ptr<pool_impl> &m, std::shared_ptr<ResourceT> &c) {\n safe_lock<qutex> lk(m->mut);\n \/\/ remove bad resource\n DVLOG(4) << \"shared_pool(\" << m->name\n << \") destroy in set? \" << m->set.count(c)\n << \" : \" << c << \" rc: \" << c.use_count();\n size_t count = m->set.erase(c);\n if (count) {\n LOG(WARNING) << \"destroying shared resource from pool \" << m->name;\n }\n typename queue_type::iterator i = std::find(m->q.begin(), m->q.end(), c);\n if (i!=m->q.end()) { m->q.erase(i); }\n\n c.reset();\n\n \/\/ give waiting threads a chance to allocate a new resource\n m->not_empty.wakeup();\n }\n\n static std::shared_ptr<ResourceT> add_new_resource(std::shared_ptr<pool_impl> &m, std::unique_lock<qutex> &lk) {\n std::shared_ptr<ResourceT> c;\n lk.unlock(); \/\/ unlock while newing resource\n try {\n c = m->new_resource();\n CHECK(c) << \"new_resource failed for pool: \" << m->name;\n DVLOG(4) << \"inserting to shared_pool(\" << m->name << \"): \" << c;\n } catch (std::exception &e) {\n LOG(ERROR) << \"exception creating new resource for pool: \" << m->name << \" \" << e.what();\n lk.lock();\n throw;\n }\n lk.lock(); \/\/ re-lock before inserting to set\n m->set.insert(c);\n return c;\n }\n\n};\n\nnamespace detail {\n\n\/\/ do not use this class directly, instead use your shared_pool<>::scoped_resource\ntemplate <typename T> class scoped_resource {\npublic:\n \/\/typedef typename std::add_reference<shared_pool<T>>::type poolref;\n typedef typename boost::call_traits<shared_pool<T>>::reference poolref;\n typedef typename shared_pool<T>::pool_impl pool_impl;\nprotected:\n std::shared_ptr<pool_impl> _pool;\n std::shared_ptr<T> _c;\n bool _success;\npublic:\n explicit scoped_resource(poolref p)\n : _pool(p.get_safe()),\n _success(false)\n {\n _c = shared_pool<T>::acquire(_pool);\n }\n\n \/\/! must call done() to return the resource to the pool\n \/\/! otherwise we destroy it because a timeout or other exception\n \/\/! could have occured causing the resource state to be in transition\n ~scoped_resource() {\n if (_success) {\n shared_pool<T>::release(_pool, _c);\n } else {\n shared_pool<T>::destroy(_pool, _c);\n }\n }\n\n void done() {\n DCHECK(!_success);\n _success = true;\n }\n\n T *operator->() {\n if (!_c) throw std::runtime_error(\"null pointer\");\n return _c.get();\n }\n\n};\n\n} \/\/ end detail namespace\n\n} \/\/ end namespace ten\n\n#endif \/\/ LIBTEN_SHARED_POOL_HH\n<commit_msg>fix weird name parsing conflict<commit_after>#ifndef LIBTEN_SHARED_POOL_HH\n#define LIBTEN_SHARED_POOL_HH\n\n#include \"task\/rendez.hh\"\n#include \"ten\/logging.hh\"\n\n#include <boost\/call_traits.hpp>\n#include <set>\n#include <deque>\n#include <memory>\n#include <atomic>\n\nnamespace ten {\n\nnamespace detail {\n template <typename T> class scoped_resource;\n}\n\n\/\/! thread and task safe pool of shared resources\n\/\/\n\/\/! useful for connection pools and other types of shared resources\ntemplate <typename ResourceT, typename ScopeT = detail::scoped_resource<ResourceT> >\nclass shared_pool {\npublic:\n \/\/ use this scoped_resource type to RAII resources from the pool\n typedef ScopeT scoped_resource;\n typedef std::deque<std::shared_ptr<ResourceT> > queue_type;\n typedef std::set<std::shared_ptr<ResourceT> > set_type;\n typedef std::function<std::shared_ptr<ResourceT> ()> alloc_func;\nprotected:\n template <typename TT> friend class detail::scoped_resource;\n\n struct pool_impl {\n qutex mut;\n rendez not_empty;\n queue_type q;\n set_type set;\n std::string name;\n alloc_func new_resource;\n ssize_t max_resources;\n };\n\n std::mutex _mutex;\n std::shared_ptr<pool_impl> _m;\n\n std::shared_ptr<pool_impl> get_safe() {\n#if 0\n return std::atomic_load(&_m);\n#else\n std::lock_guard<std::mutex> lock(_mutex);\n return _m;\n#endif\n }\n\n void set_safe(std::shared_ptr<pool_impl> &other) {\n#if 0\n std::atomic_store(&_m, other);\n#else\n\n std::lock_guard<std::mutex> lock(_mutex);\n _m = other;\n#endif\n }\n\npublic:\n shared_pool(const std::string &name_,\n const alloc_func &alloc_,\n ssize_t max_ = -1)\n {\n std::shared_ptr<pool_impl> m = std::make_shared<pool_impl>();\n m->name = name_;\n m->new_resource = alloc_;\n m->max_resources = max_;\n set_safe(m);\n }\n\n shared_pool(const shared_pool &) = delete;\n shared_pool &operator =(const shared_pool &) = delete;\n\n size_t size() {\n std::shared_ptr<pool_impl> m(get_safe());\n std::lock_guard<qutex> lk(m->mut);\n return m->set.size();\n }\n\n void clear() {\n std::shared_ptr<pool_impl> m(get_safe());\n std::lock_guard<qutex> lk(m->ut);\n m->q.clear();\n m->set.clear();\n }\n\n const std::string &name() {\n std::shared_ptr<pool_impl> m(get_safe());\n return m->name;\n }\n\nprotected:\n bool is_not_empty() {\n std::shared_ptr<pool_impl> m(get_safe());\n return !m->q.empty();\n }\n\n static std::shared_ptr<ResourceT> acquire(std::shared_ptr<pool_impl> &m) {\n std::unique_lock<qutex> lk(m->mut);\n return create_or_acquire_with_lock(m, lk);\n }\n\n \/\/ internal, does not lock mutex\n static std::shared_ptr<ResourceT> create_or_acquire_with_lock(std::shared_ptr<pool_impl> &m, std::unique_lock<qutex> &lk) {\n while (m->q.empty()) {\n if (m->max_resources < 0 || m->set.size() < (size_t)m->max_resources) {\n \/\/ need to create a new resource\n return add_new_resource(m, lk);\n break;\n } else {\n \/\/ can't create anymore we're at max, try waiting\n \/\/ we don't use a predicate here because\n \/\/ we might be woken up from destroy()\n \/\/ in which case we might not be at max anymore\n m->not_empty.sleep(lk);\n }\n }\n\n CHECK(!m->q.empty());\n \/\/ pop resource from front of queue\n std::shared_ptr<ResourceT> c = m->q.front();\n m->q.pop_front();\n CHECK(c) << \"acquire shared resource failed in pool: \" << m->name;\n return c;\n }\n\n static void release(std::shared_ptr<pool_impl> &m, std::shared_ptr<ResourceT> &c) {\n safe_lock<qutex> lk(m->mut);\n \/\/ don't add resource to queue if it was removed from _set\n if (m->set.count(c)) {\n m->q.push_front(c);\n m->not_empty.wakeup();\n }\n }\n\n static void destroy(std::shared_ptr<pool_impl> &m, std::shared_ptr<ResourceT> &c) {\n safe_lock<qutex> lk(m->mut);\n \/\/ remove bad resource\n DVLOG(4) << \"shared_pool(\" << m->name\n << \") destroy in set? \" << m->set.count(c)\n << \" : \" << c << \" rc: \" << c.use_count();\n size_t count = m->set.erase(c);\n if (count) {\n LOG(WARNING) << \"destroying shared resource from pool \" << m->name;\n }\n typename queue_type::iterator i = std::find(m->q.begin(), m->q.end(), c);\n if (i!=m->q.end()) { m->q.erase(i); }\n\n c.reset();\n\n \/\/ give waiting threads a chance to allocate a new resource\n m->not_empty.wakeup();\n }\n\n static std::shared_ptr<ResourceT> add_new_resource(std::shared_ptr<pool_impl> &m, std::unique_lock<qutex> &lk) {\n std::shared_ptr<ResourceT> c;\n lk.unlock(); \/\/ unlock while newing resource\n try {\n c = m->new_resource();\n CHECK(c) << \"new_resource failed for pool: \" << m->name;\n DVLOG(4) << \"inserting to shared_pool(\" << m->name << \"): \" << c;\n } catch (std::exception &e) {\n LOG(ERROR) << \"exception creating new resource for pool: \" << m->name << \" \" << e.what();\n lk.lock();\n throw;\n }\n lk.lock(); \/\/ re-lock before inserting to set\n m->set.insert(c);\n return c;\n }\n\n};\n\nnamespace detail {\n\n\/\/ do not use this class directly, instead use your shared_pool<>::scoped_resource\ntemplate <typename T> class scoped_resource {\npublic:\n \/\/typedef typename std::add_reference<shared_pool<T>>::type poolref;\n typedef typename boost::call_traits<shared_pool<T>>::reference poolref;\n typedef typename shared_pool<T>::pool_impl pool_impl;\nprotected:\n std::shared_ptr<pool_impl> _pool;\n std::shared_ptr<T> _c;\n bool _success;\npublic:\n explicit scoped_resource(poolref p)\n : _pool(p.get_safe()),\n _success(false)\n {\n _c = shared_pool<T>::acquire(_pool);\n }\n\n \/\/! must call done() to return the resource to the pool\n \/\/! otherwise we destroy it because a timeout or other exception\n \/\/! could have occured causing the resource state to be in transition\n ~scoped_resource() {\n if (_success) {\n shared_pool<T>::release(_pool, _c);\n } else {\n shared_pool<T>::destroy(_pool, _c);\n }\n }\n\n void done() {\n DCHECK(!_success);\n _success = true;\n }\n\n T *operator->() {\n if (!_c) throw std::runtime_error(\"null pointer\");\n return _c.get();\n }\n\n};\n\n} \/\/ end detail namespace\n\n} \/\/ end namespace ten\n\n#endif \/\/ LIBTEN_SHARED_POOL_HH\n<|endoftext|>"} {"text":"<commit_before>\/\/----------------------------------------------------------------------------\n\/\/\/ \\file stream_io.hpp\n\/\/\/ \\author Serge Aleynikov\n\/\/----------------------------------------------------------------------------\n\/\/\/ Defines functions for stream input\/output\n\/\/----------------------------------------------------------------------------\n\/\/ Copyright (C) 2016 Serge Aleynikov <saleyn@gmail.com>\n\/\/ Created: 2016-02-26\n\/\/----------------------------------------------------------------------------\n\/*\n***** BEGIN LICENSE BLOCK *****\n\nThis file is a part of utxx open-source project.\n\nCopyright (C) 2016 Serge Aleynikov <saleyn@gmail.com>\n\nThis library is free software; you can redistribute it and\/or\nmodify it under the terms of the GNU Lesser General Public\nLicense as published by the Free Software Foundation; either\nversion 2.1 of the License, or (at your option) any later version.\n\nThis library is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\nLesser General Public License for more details.\n\nYou should have received a copy of the GNU Lesser General Public\nLicense along with this library; if not, write to the Free Software\nFoundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n\n***** END LICENSE BLOCK *****\n*\/\n#pragma once\n\n#include <iosfwd>\n#include <utxx\/convert.hpp>\n#include <utxx\/container\/stack_container.hpp>\n\nnamespace utxx {\n\n\/\/------------------------------------------------------------------------------\n\/\/\/ Read \\a a_cnt values from the input stream.\n\/\/\/ @param in input stream.\n\/\/\/ @param a_output array of \\a a_cnt double values.\n\/\/\/ @param a_fields array of \\a a_cnt field positions (ascending order). If this\n\/\/\/ value is NULL, the values are read from the input stream\n\/\/\/ in consequitive order disregarding field positions.\n\/\/\/ @param a_cnt count of values to read (must be > 0).\n\/\/\/ @param a_convert lambda used to convert a string value to type \\a T:\n\/\/\/ <code>const char* (const char* begin, const char* end, T& outout);<\/code>\n\/\/\/ The function must return NULL if conversion is unsuccessful, or a pointer\n\/\/\/ past last successfully parsed character otherwise.\n\/\/\/ @return true if successfully read \\a a_cnt values.\n\/\/------------------------------------------------------------------------------\ntemplate <typename T = double, int StrSize = 256, class Convert>\nbool read_values(std::istream& in, T* a_output, int* a_fields, int a_cnt,\n const Convert& a_convert)\n{\n assert(a_cnt);\n\n basic_stack_string<StrSize> str;\n\n auto& line = str.container();\n\n if (a_fields == nullptr) {\n for (int i=0; i < a_cnt; ++i) {\n if (in.eof()) return false;\n in >> *a_output++;\n }\n }\n else if (!std::getline(in, line))\n return false;\n else {\n const char* p = &*line.begin();\n const char* e = &*line.end();\n\n int fld = 0;\n\n auto ws = [](char c) { return c == ' ' || c == '\\t'; };\n auto skip_ws = [&p, e, &ws]() { while (ws(*p) && p != e) p++; };\n\n for (int i=0; i < a_cnt; ++i, ++a_fields, ++a_output) {\n while (p != e) {\n skip_ws();\n if (++fld == *a_fields)\n break;\n while (!ws(*p) && p != e) p++;\n }\n\n if (fld != *a_fields)\n return false;\n\n p = a_convert(p, e, *a_output);\n\n if (!p)\n return false;\n }\n }\n\n return true;\n}\n\n} \/\/ namespace utxx<commit_msg>Fix issue of reading bad input<commit_after>\/\/----------------------------------------------------------------------------\n\/\/\/ \\file stream_io.hpp\n\/\/\/ \\author Serge Aleynikov\n\/\/----------------------------------------------------------------------------\n\/\/\/ Defines functions for stream input\/output\n\/\/----------------------------------------------------------------------------\n\/\/ Copyright (C) 2016 Serge Aleynikov <saleyn@gmail.com>\n\/\/ Created: 2016-02-26\n\/\/----------------------------------------------------------------------------\n\/*\n***** BEGIN LICENSE BLOCK *****\n\nThis file is a part of utxx open-source project.\n\nCopyright (C) 2016 Serge Aleynikov <saleyn@gmail.com>\n\nThis library is free software; you can redistribute it and\/or\nmodify it under the terms of the GNU Lesser General Public\nLicense as published by the Free Software Foundation; either\nversion 2.1 of the License, or (at your option) any later version.\n\nThis library is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\nLesser General Public License for more details.\n\nYou should have received a copy of the GNU Lesser General Public\nLicense along with this library; if not, write to the Free Software\nFoundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n\n***** END LICENSE BLOCK *****\n*\/\n#pragma once\n\n#include <iosfwd>\n#include <utxx\/convert.hpp>\n#include <utxx\/container\/stack_container.hpp>\n\nnamespace utxx {\n\n\/\/------------------------------------------------------------------------------\n\/\/\/ Read \\a a_cnt values from the input stream.\n\/\/\/ @param in input stream.\n\/\/\/ @param a_output array of \\a a_cnt double values.\n\/\/\/ @param a_fields array of \\a a_cnt field positions (ascending order). If this\n\/\/\/ value is NULL, the values are read from the input stream\n\/\/\/ in consequitive order disregarding field positions.\n\/\/\/ @param a_cnt count of values to read (must be > 0).\n\/\/\/ @param a_convert lambda used to convert a string value to type \\a T:\n\/\/\/ <code>const char* (const char* begin, const char* end, T& outout);<\/code>\n\/\/\/ The function must return NULL if conversion is unsuccessful, or a pointer\n\/\/\/ past last successfully parsed character otherwise.\n\/\/\/ @return true if successfully read \\a a_cnt values.\n\/\/------------------------------------------------------------------------------\ntemplate <typename T = double, int StrSize = 256, class Convert>\nbool read_values(std::istream& in, T* a_output, int* a_fields, int a_cnt,\n const Convert& a_convert)\n{\n assert(a_cnt);\n\n basic_stack_string<StrSize> str;\n\n auto& line = str.container();\n\n if (a_fields == nullptr) {\n for (int i=0; i < a_cnt; ++i) {\n if (in.eof()) return false;\n in >> *a_output++;\n if (in.fail()) {\n in.clear();\n std::getline(in, line);\n return false;\n }\n }\n }\n else if (!std::getline(in, line))\n return false;\n else {\n const char* p = &*line.begin();\n const char* e = &*line.end();\n\n int fld = 0;\n\n auto ws = [](char c) { return c == ' ' || c == '\\t'; };\n auto skip_ws = [&p, e, &ws]() { while (ws(*p) && p != e) p++; };\n\n for (int i=0; i < a_cnt; ++i, ++a_fields, ++a_output) {\n while (p != e) {\n skip_ws();\n if (++fld == *a_fields)\n break;\n while (!ws(*p) && p != e) p++;\n }\n\n if (fld != *a_fields)\n return false;\n\n p = a_convert(p, e, *a_output);\n\n if (!p)\n return false;\n }\n }\n\n return true;\n}\n\n} \/\/ namespace utxx<|endoftext|>"} {"text":"<commit_before>#ifndef VSMC_RNG_AESNI_HPP\n#define VSMC_RNG_AESNI_HPP\n\n#include <vsmc\/rng\/m128i.hpp>\n\n#define VSMC_STATIC_ASSERT_RNG_AESNI_RESULT_TYPE(ResultType) \\\n VSMC_STATIC_ASSERT( \\\n (cxx11::is_same<ResultType, uint32_t>::value || \\\n cxx11::is_same<ResultType, uint64_t>::value), \\\n USE_AESNIEngine_WITH_INTEGER_TYPE_OTHER_THAN_uint32_t_OR_uint64_t)\n\n#define VSMC_STATIC_ASSERT_RNG_AESNI \\\n VSMC_STATIC_ASSERT_RNG_AESNI_RESULT_TYPE(ResultType);\n\n#define VSMC_DEFINE_RNG_AESNI_ROUND_CONSTANT(N, val) \\\n template <> struct AESNIRoundConstant< N > : \\\n public cxx11::integral_constant<int, val > {};\n\nnamespace vsmc {\n\nnamespace internal {\n\ntemplate <std::size_t N> struct AESNIRoundConstant;\n\nVSMC_DEFINE_RNG_AESNI_ROUND_CONSTANT(0, 0x01)\nVSMC_DEFINE_RNG_AESNI_ROUND_CONSTANT(1, 0x02)\nVSMC_DEFINE_RNG_AESNI_ROUND_CONSTANT(2, 0x04)\nVSMC_DEFINE_RNG_AESNI_ROUND_CONSTANT(3, 0x08)\nVSMC_DEFINE_RNG_AESNI_ROUND_CONSTANT(4, 0x10)\nVSMC_DEFINE_RNG_AESNI_ROUND_CONSTANT(5, 0x20)\nVSMC_DEFINE_RNG_AESNI_ROUND_CONSTANT(6, 0x40)\nVSMC_DEFINE_RNG_AESNI_ROUND_CONSTANT(7, 0x80)\nVSMC_DEFINE_RNG_AESNI_ROUND_CONSTANT(8, 0x1B)\nVSMC_DEFINE_RNG_AESNI_ROUND_CONSTANT(9, 0x36)\n\n} \/\/ namespace vsmc::internal\n\n\/\/\/ \\brief AESNI RNG engine reimplemented\n\/\/\/ \\ingroup R123RNG\n\/\/\/\n\/\/\/ \\details\n\/\/\/ This is a reimplementation of the algorithm AES as described in [Parallel\n\/\/\/ Random Numbers: As Easy as 1, 2, 3][r123paper] and implemented in\n\/\/\/ [Random123][r123lib].\n\/\/\/\n\/\/\/ The implementation is almost identical to the original. Compared to\n\/\/\/ `r123:Engine<r123::AESNI4x32>`, when using the default constructor or the\n\/\/\/ one with a single seed, the output shall be exactly the same for the first\n\/\/\/ \\f$2^32\\f$ iterations. Further iterations may produce different results, as\n\/\/\/ vSMC increment the counter slightly differently, but it still cover the\n\/\/\/ same range and has the same period as the original. In addition, this\n\/\/\/ engine allows output of 64-bits integers.\ntemplate <typename ResultType>\nclass AESNIEngine\n{\n static VSMC_CONSTEXPR const std::size_t R_ = 10;\n static VSMC_CONSTEXPR const std::size_t K_ =\n sizeof(__m128i) \/ sizeof(ResultType);\n\n public :\n\n typedef ResultType result_type;\n typedef StaticVector<ResultType, K_> ctr_type;\n typedef StaticVector<__m128i, R_ + 1> key_type;\n typedef StaticVector<ResultType, K_> ukey_type;\n\n explicit AESNIEngine (result_type s = 0) :\n pac_(_mm_setzero_si128()),\n tmp0_(pac_), tmp1_(pac_), tmp2_(pac_), remain_(0)\n {\n VSMC_STATIC_ASSERT_RNG_AESNI;\n seed(s);\n }\n\n template <typename SeedSeq>\n explicit AESNIEngine (SeedSeq &seq, typename cxx11::enable_if<\n !internal::is_seed_sequence<SeedSeq, ResultType>::value>::type * =\n VSMC_NULLPTR) :\n pac_(_mm_setzero_si128()),\n tmp0_(pac_), tmp1_(pac_), tmp2_(pac_), remain_(0)\n {\n VSMC_STATIC_ASSERT_RNG_AESNI;\n seed(seq);\n }\n\n void seed (result_type s)\n {\n ctr_.fill(0);\n ukey_type uk;\n uk.fill(0);\n uk.front() = s;\n ukey(uk);\n remain_ = 0;\n }\n\n template <typename SeedSeq>\n void seed (SeedSeq &seq, typename cxx11::enable_if<\n !internal::is_seed_sequence<SeedSeq, ResultType>::value>::type * =\n VSMC_NULLPTR)\n {\n ctr_.fill(0);\n ukey_type uk;\n seq.generate(uk.begin(), uk.end());\n ukey(uk);\n remain_ = 0;\n }\n\n const ctr_type &ctr () const {return ctr_;}\n\n const key_type &key () const {return key_;}\n\n void ctr (const ctr_type &c)\n {\n ctr_ = c;\n remain_ = 0;\n }\n\n void key (const key_type &k)\n {\n key_ = k;\n remain_ = 0;\n }\n\n void ukey (const ukey_type &uk)\n {\n internal::pack(uk, pac_);\n init_key(pac_);\n remain_ = 0;\n }\n\n \/\/\/ \\brief Same as operator() but return the __m128i type\n __m128i generate ()\n {\n internal::RngCounter<ResultType, K_>::increment(ctr_);\n pack();\n generate<0>(cxx11::true_type());\n remain_ = 0;\n\n return pac_;\n }\n\n result_type operator() ()\n {\n if (remain_ == 0) {\n generate();\n internal::unpack(pac_, res_);\n remain_ = K_;\n }\n\n return res_[--remain_];\n }\n\n void discard (std::size_t nskip)\n {\n if (nskip == 0)\n return;\n\n --nskip;\n internal::RngCounter<ResultType, K_>::increment(ctr_, nskip);\n remain_ = 0;\n operator()();\n nskip = nskip % K_;\n if (remain_ >= nskip) {\n remain_ -= nskip;\n return;\n }\n\n nskip -= remain_;\n remain_ = K_ - nskip;\n }\n\n static VSMC_CONSTEXPR const result_type _Min = 0;\n static VSMC_CONSTEXPR const result_type _Max = static_cast<result_type>(\n ~(static_cast<result_type>(0)));\n\n static VSMC_CONSTEXPR result_type min VSMC_MNE () {return _Min;}\n static VSMC_CONSTEXPR result_type max VSMC_MNE () {return _Max;}\n\n friend inline bool operator== (\n const AESNIEngine<ResultType> &eng1,\n const AESNIEngine<ResultType> &eng2)\n {\n if (eng1.ctr_ != eng2.ctr_)\n return false;\n\n if (eng1.res_ != eng2.res_)\n return false;\n\n for (std::size_t i = 0; i != key_type::size(); ++i)\n if (!internal::is_equal(eng1.key_[i], eng2.key_[i]))\n return false;\n\n return eng1.remain_ == eng2.remain_;\n }\n\n friend inline bool operator!= (\n const AESNIEngine<ResultType> &eng1,\n const AESNIEngine<ResultType> &eng2)\n {return !(eng1 == eng2);}\n\n template <typename CharT, typename Traits>\n friend inline std::basic_ostream<CharT, Traits> &operator<< (\n std::basic_ostream<CharT, Traits> &os,\n const AESNIEngine<ResultType> &eng)\n {\n if (os) os << eng.ctr_ << ' ';\n if (os) os << eng.res_ << ' ';\n for (std::size_t i = 0; i != key_type::size(); ++i) {\n internal::output_m128i(os, eng.key_[i]);\n if (os) os << ' ';\n }\n internal::output_m128i(os, eng.pac_); if (os) os << ' ';\n internal::output_m128i(os, eng.tmp0_); if (os) os << ' ';\n internal::output_m128i(os, eng.tmp1_); if (os) os << ' ';\n internal::output_m128i(os, eng.tmp2_); if (os) os << ' ';\n if (os) os << eng.remain_;\n\n return os;\n }\n\n template <typename CharT, typename Traits>\n friend inline std::basic_istream<CharT, Traits> &operator>> (\n std::basic_istream<CharT, Traits> &is,\n AESNIEngine<ResultType> &eng)\n {\n AESNIEngine eng_tmp;\n if (is) is >> std::ws >> eng_tmp.ctr_;\n if (is) is >> std::ws >> eng_tmp.res_;\n for (std::size_t i = 0; i != key_type::size(); ++i)\n internal::input_m128i(is, eng_tmp.key_[i]);\n internal::input_m128i(is, eng_tmp.pac_);\n internal::input_m128i(is, eng_tmp.tmp0_);\n internal::input_m128i(is, eng_tmp.tmp1_);\n internal::input_m128i(is, eng_tmp.tmp2_);\n if (is) is >> std::ws >> eng_tmp.remain_;\n if (is) eng = eng_tmp;\n\n return is;\n }\n\n private :\n\n ctr_type ctr_;\n ctr_type res_;\n key_type key_;\n __m128i pac_;\n __m128i tmp0_;\n __m128i tmp1_;\n __m128i tmp2_;\n std::size_t remain_;\n\n void pack ()\n {\n internal::pack(ctr_, pac_);\n pac_ = _mm_xor_si128(pac_, key_.front());\n }\n\n template <std::size_t>\n void generate (cxx11::false_type)\n {pac_ = _mm_aesenclast_si128(pac_, key_.back());}\n\n template <std::size_t N>\n void generate (cxx11::true_type)\n {\n pac_ = _mm_aesenc_si128(pac_, key_[Position<N + 1>()]);\n generate<N + 1>(cxx11::integral_constant<bool, N + 2 < R_>());\n }\n\n void init_key(__m128i k)\n {\n tmp0_ = k;\n init_key<0>(cxx11::true_type());\n }\n\n template <std::size_t>\n void init_key (cxx11::false_type) {key_.back() = tmp0_;}\n\n template <std::size_t N>\n void init_key (cxx11::true_type)\n {\n key_[Position<N>()] = tmp0_;\n tmp1_ = _mm_aeskeygenassist_si128(tmp0_,\n internal::AESNIRoundConstant<N>::value);\n init_key_assit();\n init_key<N + 1>(cxx11::integral_constant<bool, N + 1 < R_>());\n }\n\n void init_key_assit ()\n {\n tmp1_ = _mm_shuffle_epi32 (tmp1_ ,0xFF);\n tmp2_ = _mm_slli_si128 (tmp0_, 0x04);\n tmp0_ = _mm_xor_si128 (tmp0_, tmp2_);\n tmp2_ = _mm_slli_si128 (tmp2_, 0x04);\n tmp0_ = _mm_xor_si128 (tmp0_, tmp2_);\n tmp2_ = _mm_slli_si128 (tmp2_, 0x04);\n tmp0_ = _mm_xor_si128 (tmp0_, tmp2_);\n tmp0_ = _mm_xor_si128 (tmp0_, tmp1_);\n }\n}; \/\/ class AESNIEngine\n\n\/\/\/ \\brief AESNI RNG engine returning 32-bits integers\n\/\/\/ \\ingroup R123RNG\ntypedef AESNIEngine<uint32_t> AESNI4x32;\n\n\/\/\/ \\brief AESNI RNG engine returning 64-bits integers\n\/\/\/ \\ingroup R123RNG\ntypedef AESNIEngine<uint64_t> AESNI2x64;\n\n\/\/\/ \\brief AESNI RNG engine returning 128-bits integers\n\/\/\/ \\ingroup R123RNG\ntypedef AESNIEngine<__m128i> AESNI1x128;\n\n} \/\/ namespace vsmc\n\n#endif \/\/ VSMC_RNG_AESNI_HPP\n<commit_msg>AESNIEngine now can use multiple blocks<commit_after>#ifndef VSMC_RNG_AESNI_HPP\n#define VSMC_RNG_AESNI_HPP\n\n#include <vsmc\/rng\/m128i.hpp>\n\n#define VSMC_STATIC_ASSERT_RNG_AESNI_RESULT_TYPE(ResultType) \\\n VSMC_STATIC_ASSERT( \\\n (cxx11::is_same<ResultType, uint32_t>::value || \\\n cxx11::is_same<ResultType, uint64_t>::value), \\\n USE_AESNIEngine_WITH_INTEGER_TYPE_OTHER_THAN_uint32_t_OR_uint64_t)\n\n#define VSMC_STATIC_ASSERT_RNG_AESNI_BLOCKS(Blocks) \\\n VSMC_STATIC_ASSERT((Blocks > 0), USE_AESNIEngine_WITH_ZERO_BLOCKS)\n\n#define VSMC_STATIC_ASSERT_RNG_AESNI \\\n VSMC_STATIC_ASSERT_RNG_AESNI_RESULT_TYPE(ResultType); \\\n VSMC_STATIC_ASSERT_RNG_AESNI_BLOCKS(Blocks);\n\n#define VSMC_DEFINE_RNG_AESNI_ROUND_CONSTANT(N, val) \\\n template <> struct AESNIRoundConstant< N > : \\\n public cxx11::integral_constant<int, val > {};\n\nnamespace vsmc {\n\nnamespace internal {\n\ntemplate <std::size_t N> struct AESNIRoundConstant;\n\nVSMC_DEFINE_RNG_AESNI_ROUND_CONSTANT(0, 0x01)\nVSMC_DEFINE_RNG_AESNI_ROUND_CONSTANT(1, 0x02)\nVSMC_DEFINE_RNG_AESNI_ROUND_CONSTANT(2, 0x04)\nVSMC_DEFINE_RNG_AESNI_ROUND_CONSTANT(3, 0x08)\nVSMC_DEFINE_RNG_AESNI_ROUND_CONSTANT(4, 0x10)\nVSMC_DEFINE_RNG_AESNI_ROUND_CONSTANT(5, 0x20)\nVSMC_DEFINE_RNG_AESNI_ROUND_CONSTANT(6, 0x40)\nVSMC_DEFINE_RNG_AESNI_ROUND_CONSTANT(7, 0x80)\nVSMC_DEFINE_RNG_AESNI_ROUND_CONSTANT(8, 0x1B)\nVSMC_DEFINE_RNG_AESNI_ROUND_CONSTANT(9, 0x36)\n\n} \/\/ namespace vsmc::internal\n\n\/\/\/ \\brief AESNI RNG engine reimplemented\n\/\/\/ \\ingroup R123RNG\n\/\/\/\n\/\/\/ \\details\n\/\/\/ This is a reimplementation of the algorithm AES as described in [Parallel\n\/\/\/ Random Numbers: As Easy as 1, 2, 3][r123paper] and implemented in\n\/\/\/ [Random123][r123lib].\n\/\/\/\n\/\/\/ The implementation is almost identical to the original. Compared to\n\/\/\/ `r123:Engine<r123::AESNI4x32>`, when using the default constructor or the\n\/\/\/ one with a single seed, the output shall be exactly the same for the first\n\/\/\/ \\f$2^32\\f$ iterations. Further iterations may produce different results, as\n\/\/\/ vSMC increment the counter slightly differently, but it still cover the\n\/\/\/ same range and has the same period as the original. In addition, this\n\/\/\/ engine allows output of 64-bits integers.\ntemplate <typename ResultType, std::size_t Blocks = 1>\nclass AESNIEngine\n{\n static VSMC_CONSTEXPR const std::size_t R_ = 10;\n static VSMC_CONSTEXPR const std::size_t K_ =\n sizeof(__m128i) \/ sizeof(ResultType);\n\n public :\n\n typedef ResultType result_type;\n typedef StaticVector<ResultType, K_> ctr_type;\n typedef StaticVector<__m128i, R_ + 1> key_type;\n typedef StaticVector<ResultType, K_> ukey_type;\n\n explicit AESNIEngine (result_type s = 0) :\n tmp0_(), tmp1_(), tmp2_(), remain_(0)\n {\n VSMC_STATIC_ASSERT_RNG_AESNI;\n seed(s);\n }\n\n template <typename SeedSeq>\n explicit AESNIEngine (SeedSeq &seq, typename cxx11::enable_if<\n !internal::is_seed_sequence<SeedSeq, ResultType>::value>::type * =\n VSMC_NULLPTR) : tmp0_(), tmp1_(), tmp2_(), remain_(0)\n {\n VSMC_STATIC_ASSERT_RNG_AESNI;\n seed(seq);\n }\n\n void seed (result_type s)\n {\n ctr_type c;\n c.fill(0);\n ctr_.fill(c);\n ukey_type uk;\n uk.fill(0);\n uk.front() = s;\n ukey(uk);\n remain_ = 0;\n }\n\n template <typename SeedSeq>\n void seed (SeedSeq &seq, typename cxx11::enable_if<\n !internal::is_seed_sequence<SeedSeq, ResultType>::value>::type * =\n VSMC_NULLPTR)\n {\n ctr_type c;\n c.fill(0);\n ctr_.fill(c);\n ukey_type uk;\n seq.generate(uk.begin(), uk.end());\n ukey(uk);\n remain_ = 0;\n }\n\n const ctr_type &ctr () const {return ctr_;}\n\n const key_type &key () const {return key_;}\n\n void ctr (const ctr_type &c)\n {\n ctr_.back() = c;\n remain_ = 0;\n }\n\n void key (const key_type &k)\n {\n key_ = k;\n remain_ = 0;\n }\n\n void ukey (const ukey_type &uk)\n {\n internal::pack(uk, pac_.front());\n init_key(pac_.front());\n remain_ = 0;\n }\n\n result_type operator() ()\n {\n if (remain_ == 0)\n generate();\n --remain_;\n\n return result<Blocks - 1>(\n cxx11::integral_constant<bool, 1 < Blocks>());\n }\n\n void discard (std::size_t nskip)\n {\n if (nskip == 0)\n return;\n\n --nskip;\n internal::RngCounter<ResultType, K_>::increment(ctr_, nskip);\n remain_ = 0;\n operator()();\n nskip = nskip % K_;\n if (remain_ >= nskip) {\n remain_ -= nskip;\n return;\n }\n\n nskip -= remain_;\n remain_ = K_ - nskip;\n }\n\n static VSMC_CONSTEXPR const result_type _Min = 0;\n static VSMC_CONSTEXPR const result_type _Max = static_cast<result_type>(\n ~(static_cast<result_type>(0)));\n\n static VSMC_CONSTEXPR result_type min VSMC_MNE () {return _Min;}\n static VSMC_CONSTEXPR result_type max VSMC_MNE () {return _Max;}\n\n friend inline bool operator== (\n const AESNIEngine<ResultType> &eng1,\n const AESNIEngine<ResultType> &eng2)\n {\n if (eng1.ctr_ != eng2.ctr_)\n return false;\n\n if (eng1.res_ != eng2.res_)\n return false;\n\n for (std::size_t i = 0; i != key_type::size(); ++i)\n if (!internal::is_equal(eng1.key_[i], eng2.key_[i]))\n return false;\n\n return eng1.remain_ == eng2.remain_;\n }\n\n friend inline bool operator!= (\n const AESNIEngine<ResultType> &eng1,\n const AESNIEngine<ResultType> &eng2)\n {return !(eng1 == eng2);}\n\n template <typename CharT, typename Traits>\n friend inline std::basic_ostream<CharT, Traits> &operator<< (\n std::basic_ostream<CharT, Traits> &os,\n const AESNIEngine<ResultType> &eng)\n {\n if (os) os << eng.ctr_ << ' ';\n if (os) os << eng.res_ << ' ';\n for (std::size_t i = 0; i != key_type::size(); ++i) {\n internal::output_m128i(os, eng.key_[i]);\n if (os) os << ' ';\n }\n internal::output_m128i(os, eng.pac_); if (os) os << ' ';\n internal::output_m128i(os, eng.tmp0_); if (os) os << ' ';\n internal::output_m128i(os, eng.tmp1_); if (os) os << ' ';\n internal::output_m128i(os, eng.tmp2_); if (os) os << ' ';\n if (os) os << eng.remain_;\n\n return os;\n }\n\n template <typename CharT, typename Traits>\n friend inline std::basic_istream<CharT, Traits> &operator>> (\n std::basic_istream<CharT, Traits> &is,\n AESNIEngine<ResultType> &eng)\n {\n AESNIEngine eng_tmp;\n if (is) is >> std::ws >> eng_tmp.ctr_;\n if (is) is >> std::ws >> eng_tmp.res_;\n for (std::size_t i = 0; i != key_type::size(); ++i)\n internal::input_m128i(is, eng_tmp.key_[i]);\n internal::input_m128i(is, eng_tmp.pac_);\n internal::input_m128i(is, eng_tmp.tmp0_);\n internal::input_m128i(is, eng_tmp.tmp1_);\n internal::input_m128i(is, eng_tmp.tmp2_);\n if (is) is >> std::ws >> eng_tmp.remain_;\n if (is) eng = eng_tmp;\n\n return is;\n }\n\n private :\n\n StaticVector<ctr_type, Blocks> ctr_;\n StaticVector<ctr_type, Blocks> res_;\n key_type key_;\n StaticVector<__m128i, Blocks> pac_;\n __m128i tmp0_;\n __m128i tmp1_;\n __m128i tmp2_;\n std::size_t remain_;\n\n void increment ()\n {\n ctr_.front() = ctr_.back();\n internal::RngCounter<ResultType, K_>::increment(ctr_.front());\n increment<1>(cxx11::integral_constant<bool, 1 < Blocks>());\n }\n\n template <std::size_t> void increment (cxx11::false_type) {}\n\n template <std::size_t B>\n void increment (cxx11::true_type)\n {\n ctr_[Position<B>()] = ctr_[Position<B - 1>()];\n internal::RngCounter<ResultType, K_>::increment(ctr_[Position<B>()]);\n increment<B + 1>(cxx11::integral_constant<bool, B + 1 < Blocks>());\n }\n\n void pack ()\n {\n internal::pack(ctr_.front(), pac_.front());\n pack<1>(cxx11::integral_constant<bool, 1 < Blocks>());\n pac_.front() = _mm_xor_si128(pac_.front(), key_.front());\n pac_xor<1>(cxx11::integral_constant<bool, 1 < Blocks>());\n }\n\n template <std::size_t> void pack (cxx11::false_type) {}\n\n template <std::size_t B>\n void pack (cxx11::true_type)\n {\n internal::pack(ctr_[Position<B>()], pac_[Position<B>()]);\n pack<B + 1>(cxx11::integral_constant<bool, B + 1 < Blocks>());\n }\n\n template <std::size_t> void pac_xor (cxx11::false_type) {}\n\n template <std::size_t B>\n void pac_xor (cxx11::true_type)\n {\n pac_[Position<B>()] = _mm_xor_si128(pac_[Position<B>()], key_.front());\n pac_xor<B + 1>(cxx11::integral_constant<bool, B + 1 < Blocks>());\n }\n\n template <std::size_t> void unpack (cxx11::false_type) {}\n\n void unpack ()\n {\n internal::unpack(pac_.front(), res_.front());\n unpack<1>(cxx11::integral_constant<bool, 1 < Blocks>());\n }\n\n template <std::size_t B>\n void unpack (cxx11::true_type)\n {\n internal::unpack(pac_[Position<B>()], res_[Position<B>()]);\n unpack<B + 1>(cxx11::integral_constant<bool, B + 1 < Blocks>());\n }\n\n void generate ()\n {\n increment();\n pack();\n generate<0>(cxx11::true_type());\n unpack();\n remain_ = K_ * Blocks;\n }\n\n template <std::size_t>\n void generate (cxx11::false_type)\n {\n pac_.front() = _mm_aesenclast_si128(pac_.front(), key_.back());\n generate_last<1>(cxx11::integral_constant<bool, 1 < Blocks>());\n }\n\n template <std::size_t> void generate_last (cxx11::false_type) {}\n\n template <std::size_t B>\n void generate_last (cxx11::true_type)\n {\n pac_[Position<B>()] =\n _mm_aesenclast_si128(pac_[Position<B>()], key_.back());\n generate_last<B + 1>(cxx11::integral_constant<bool, B + 1 < Blocks>());\n }\n\n template <std::size_t N>\n void generate (cxx11::true_type)\n {\n pac_.front() = _mm_aesenc_si128(pac_.front(), key_[Position<N + 1>()]);\n generate_step<1, N>(cxx11::integral_constant<bool, 1 < Blocks>());\n generate<N + 1>(cxx11::integral_constant<bool, N + 2 < R_>());\n }\n\n template <std::size_t, std::size_t>\n void generate_step (cxx11::false_type) {}\n\n template <std::size_t B, std::size_t N>\n void generate_step (cxx11::true_type)\n {\n pac_[Position<B>()] =\n _mm_aesenc_si128(pac_[Position<B>()], key_[Position<N + 1>()]);\n generate_step<B + 1, N>(\n cxx11::integral_constant<bool, B + 1 < Blocks>());\n }\n\n template <std::size_t>\n result_type result (cxx11::false_type)\n {return res_.front()[remain_];}\n\n template <std::size_t R>\n result_type result (cxx11::true_type)\n {\n if (remain_ > R * K_)\n return res_[Position<R>()][remain_ - R * K_];\n return result<R - 1>(cxx11::integral_constant<bool, 0 < R>());\n }\n\n void init_key(__m128i k)\n {\n tmp0_ = k;\n init_key<0>(cxx11::true_type());\n }\n\n template <std::size_t>\n void init_key (cxx11::false_type) {key_.back() = tmp0_;}\n\n template <std::size_t N>\n void init_key (cxx11::true_type)\n {\n key_[Position<N>()] = tmp0_;\n tmp1_ = _mm_aeskeygenassist_si128(tmp0_,\n internal::AESNIRoundConstant<N>::value);\n init_key_assit();\n init_key<N + 1>(cxx11::integral_constant<bool, N + 1 < R_>());\n }\n\n void init_key_assit ()\n {\n tmp1_ = _mm_shuffle_epi32 (tmp1_ ,0xFF);\n tmp2_ = _mm_slli_si128 (tmp0_, 0x04);\n tmp0_ = _mm_xor_si128 (tmp0_, tmp2_);\n tmp2_ = _mm_slli_si128 (tmp2_, 0x04);\n tmp0_ = _mm_xor_si128 (tmp0_, tmp2_);\n tmp2_ = _mm_slli_si128 (tmp2_, 0x04);\n tmp0_ = _mm_xor_si128 (tmp0_, tmp2_);\n tmp0_ = _mm_xor_si128 (tmp0_, tmp1_);\n }\n}; \/\/ class AESNIEngine\n\n\/\/\/ \\brief AESNI RNG engine returning 32-bits integers with default blocks\n\/\/\/ \\ingroup R123RNG\ntypedef AESNIEngine<uint32_t> AESNI4x32;\n\n\/\/\/ \\brief AESNI RNG engine returning 64-bits integers with default blocks\n\/\/\/ \\ingroup R123RNG\ntypedef AESNIEngine<uint64_t> AESNI2x64;\n\n\/\/\/ \\brief AESNI RNG engine returning 128-bits integers with default blocks\n\/\/\/ \\ingroup R123RNG\ntypedef AESNIEngine<__m128i> AESNI1x128;\n\n\/\/\/ \\brief AESNI RNG engine returning 32-bits integers with 1 block\n\/\/\/ \\ingroup R123RNG\ntypedef AESNIEngine<uint32_t, 1> AESNI4x32_1;\n\n\/\/\/ \\brief AESNI RNG engine returning 64-bits integers with 1 block\n\/\/\/ \\ingroup R123RNG\ntypedef AESNIEngine<uint64_t, 1> AESNI2x64_1;\n\n\/\/\/ \\brief AESNI RNG engine returning 128-bits integers with 1 block\n\/\/\/ \\ingroup R123RNG\ntypedef AESNIEngine<__m128i, 1> AESNI1x128_1;\n\n\/\/\/ \\brief AESNI RNG engine returning 32-bits integers with 2 block\n\/\/\/ \\ingroup R123RNG\ntypedef AESNIEngine<uint32_t, 2> AESNI4x32_2;\n\n\/\/\/ \\brief AESNI RNG engine returning 64-bits integers with 2 block\n\/\/\/ \\ingroup R123RNG\ntypedef AESNIEngine<uint64_t, 2> AESNI2x64_2;\n\n\/\/\/ \\brief AESNI RNG engine returning 128-bits integers with 2 block\n\/\/\/ \\ingroup R123RNG\ntypedef AESNIEngine<__m128i, 2> AESNI1x128_2;\n\n\/\/\/ \\brief AESNI RNG engine returning 32-bits integers with 4 block\n\/\/\/ \\ingroup R123RNG\ntypedef AESNIEngine<uint32_t, 4> AESNI4x32_4;\n\n\/\/\/ \\brief AESNI RNG engine returning 64-bits integers with 4 block\n\/\/\/ \\ingroup R123RNG\ntypedef AESNIEngine<uint64_t, 4> AESNI2x64_4;\n\n\/\/\/ \\brief AESNI RNG engine returning 128-bits integers with 4 block\n\/\/\/ \\ingroup R123RNG\ntypedef AESNIEngine<__m128i, 4> AESNI1x128_4;\n\n} \/\/ namespace vsmc\n\n#endif \/\/ VSMC_RNG_AESNI_HPP\n<|endoftext|>"} {"text":"<commit_before>#pragma once\n#ifndef WTL_FILESYSTEM_HPP_\n#define WTL_FILESYSTEM_HPP_\n\n#ifdef _WIN32\n #include <direct.h>\n #include <io.h>\n #define mkdir(path, mode) _mkdir(path)\n #define chdir _chdir\n #define getcwd _getcwd\n #define access _access\n #define F_OK 0\n #include <algorithm> \/\/ replace()\n#else\n #include <sys\/stat.h>\n #include <unistd.h>\n#endif\n#include <cerrno>\n#include <stdexcept>\n#include <string>\n#include <ostream>\n\nnamespace wtl {\n\/\/\/\/\/\/\/\/\/1\/\/\/\/\/\/\/\/\/2\/\/\/\/\/\/\/\/\/3\/\/\/\/\/\/\/\/\/4\/\/\/\/\/\/\/\/\/5\/\/\/\/\/\/\/\/\/6\/\/\/\/\/\/\/\/\/7\/\/\/\/\/\/\/\/\/\nnamespace filesystem {\n\nclass path {\n public:\n using value_type = char;\n#ifdef _WIN32\n static constexpr value_type preferred_separator = '\\\\';\n#else\n static constexpr value_type preferred_separator = '\/';\n#endif\n using string_type = std::basic_string<value_type>;\n\n path() = default;\n path(const path&) = default;\n path(path&&) = default;\n ~path() = default;\n\n template <class T>\n path(const T& x): native_(x) {to_native(native_);}\n path(string_type&& x): native_(std::move(x)) {to_native(native_);}\n\n path parent_path() const {\n auto pos = native_.find_last_of(preferred_separator);\n if (pos == string_type::npos) return path();\n if (pos == 0u) return path(\"\/\");\n return path(native_.substr(0u, pos));\n }\n path filename() const {\n auto pos = native_.find_last_of(preferred_separator);\n return path(native_.substr(++pos));\n }\n path stem() const {\n auto name = filename().native();\n auto pos = name.find_last_of('.');\n if (pos == string_type::npos || pos == 0u) return path(name);\n if (pos == name.size() - 1u && name == \"..\") return path(name);\n return path(name.substr(0u, pos));\n }\n path extension() const {\n auto name = filename().native();\n auto pos = name.find_last_of('.');\n if (pos == string_type::npos || pos == 0u) return path();\n if (pos == name.size() - 1u && name == \"..\") return path();\n return path(name.substr(pos));\n }\n path& append(const path& p) {\n if (p.is_absolute()) {\n native_ = p.native_;\n } else {\n if (native_.back() != preferred_separator) {\n native_ += preferred_separator;\n }\n native_ += p.native();\n }\n return *this;\n }\n path& operator\/=(const path& p) {\n return append(p);\n }\n path& concat(const path& p) {\n native_ += p.native();\n return *this;\n }\n path& operator+=(const path& p) {\n return concat(p);\n }\n bool is_absolute() const {return native_.front() == preferred_separator;}\n bool is_relative() const {return !is_absolute();}\n const string_type& native() const noexcept {return native_;}\n const value_type* c_str() const noexcept {return native_.c_str();}\n operator string_type() const noexcept {return native_;}\n std::string string() const noexcept {return native_;}\n std::string generic_string() const noexcept {\n std::string copy(native_);\n to_generic(copy);\n return copy;\n }\n private:\n#ifdef _WIN32\n void to_native(string_type& data) const {\n std::replace(data.begin(), data.end(), '\/', preferred_separator);\n }\n void to_generic(string_type& data) const {\n std::replace(data.begin(), data.end(), preferred_separator, '\/');\n }\n#else\n void to_native(string_type&) const noexcept {}\n void to_generic(string_type&) const noexcept {}\n#endif\n string_type native_;\n};\n\ninline path operator\/(const path& lhs, const path& rhs) {\n return path(lhs) \/= rhs;\n}\ninline bool operator==(const path& lhs, const path& rhs) noexcept {\n return lhs.native() == rhs.native();\n}\ninline bool operator!=(const path& lhs, const path& rhs) noexcept {\n return lhs.native() != rhs.native();\n}\ninline std::ostream& operator<<(std::ostream& ost, const path& p) {\n return ost << '\"' << p.string() << '\"';\n}\n\ninline bool create_directory(const path& p) {\n const int status = ::mkdir(p.c_str(), 0755);\n if (status && errno != EEXIST) {\n throw std::runtime_error(p.native());\n }\n return status == 0;\n}\n\ninline void current_path(const path& p) {\n if (::chdir(p.c_str())) {\n throw std::runtime_error(p.native());\n }\n}\n\ninline path current_path() {\n char buffer[1024];\n if (!::getcwd(buffer, sizeof(buffer))) {\n throw std::runtime_error(buffer);\n }\n return path(buffer);\n}\n\ninline bool exists(const path& p) {\n return !::access(p.c_str(), F_OK);\n}\n\n} \/\/ namespace filesystem\n\/\/\/\/\/\/\/\/\/1\/\/\/\/\/\/\/\/\/2\/\/\/\/\/\/\/\/\/3\/\/\/\/\/\/\/\/\/4\/\/\/\/\/\/\/\/\/5\/\/\/\/\/\/\/\/\/6\/\/\/\/\/\/\/\/\/7\/\/\/\/\/\/\/\/\/\n\n\/\/ RAII\nclass ChDir {\n public:\n ChDir(const std::string& dst, bool mkdir=false) {\n if (dst.empty() || dst == \".\") return;\n if (mkdir) {\n filesystem::create_directory(dst);\n }\n filesystem::current_path(dst);\n }\n ~ChDir() {\n filesystem::current_path(origin_);\n }\n private:\n const filesystem::path origin_ = filesystem::current_path();\n};\n\n} \/\/ namespace wtl\n\n#endif \/* WTL_FILESYSTEM_HPP_ *\/\n<commit_msg>:sparkles: Add operator= and empty() to fs::path<commit_after>#pragma once\n#ifndef WTL_FILESYSTEM_HPP_\n#define WTL_FILESYSTEM_HPP_\n\n#ifdef _WIN32\n #include <direct.h>\n #include <io.h>\n #define mkdir(path, mode) _mkdir(path)\n #define chdir _chdir\n #define getcwd _getcwd\n #define access _access\n #define F_OK 0\n #include <algorithm> \/\/ replace()\n#else\n #include <sys\/stat.h>\n #include <unistd.h>\n#endif\n#include <cerrno>\n#include <stdexcept>\n#include <string>\n#include <ostream>\n\nnamespace wtl {\n\/\/\/\/\/\/\/\/\/1\/\/\/\/\/\/\/\/\/2\/\/\/\/\/\/\/\/\/3\/\/\/\/\/\/\/\/\/4\/\/\/\/\/\/\/\/\/5\/\/\/\/\/\/\/\/\/6\/\/\/\/\/\/\/\/\/7\/\/\/\/\/\/\/\/\/\nnamespace filesystem {\n\nclass path {\n public:\n using value_type = char;\n#ifdef _WIN32\n static constexpr value_type preferred_separator = '\\\\';\n#else\n static constexpr value_type preferred_separator = '\/';\n#endif\n using string_type = std::basic_string<value_type>;\n\n path() = default;\n path(const path&) = default;\n path(path&&) = default;\n path(string_type&& x): native_(std::move(x)) {to_native(native_);}\n template <class T>\n path(const T& x): native_(x) {to_native(native_);}\n\n ~path() = default;\n\n path& operator=(const path&) = default;\n path& operator=(path&&) = default;\n path& operator=(string_type&& s) {return *this = path(std::move(s));}\n template <class T>\n path& operator=(const T& s) {return *this = path(s);}\n\n path& append(const path& p) {\n if (p.is_absolute()) {\n native_ = p.native_;\n } else {\n if (native_.back() != preferred_separator) {\n native_ += preferred_separator;\n }\n native_ += p.native();\n }\n return *this;\n }\n path& operator\/=(const path& p) {\n return append(p);\n }\n path& concat(const path& p) {\n native_ += p.native();\n return *this;\n }\n path& operator+=(const path& p) {\n return concat(p);\n }\n\n path parent_path() const {\n auto pos = native_.find_last_of(preferred_separator);\n if (pos == string_type::npos) return path();\n if (pos == 0u) return path(\"\/\");\n return path(native_.substr(0u, pos));\n }\n path filename() const {\n auto pos = native_.find_last_of(preferred_separator);\n return path(native_.substr(++pos));\n }\n path stem() const {\n auto name = filename().native();\n auto pos = name.find_last_of('.');\n if (pos == string_type::npos || pos == 0u) return path(name);\n if (pos == name.size() - 1u && name == \"..\") return path(name);\n return path(name.substr(0u, pos));\n }\n path extension() const {\n auto name = filename().native();\n auto pos = name.find_last_of('.');\n if (pos == string_type::npos || pos == 0u) return path();\n if (pos == name.size() - 1u && name == \"..\") return path();\n return path(name.substr(pos));\n }\n\n bool empty() const noexcept {return native_.empty();}\n bool is_absolute() const {return native_.front() == preferred_separator;}\n bool is_relative() const {return !is_absolute();}\n\n const string_type& native() const noexcept {return native_;}\n const value_type* c_str() const noexcept {return native_.c_str();}\n operator string_type() const noexcept {return native_;}\n std::string string() const noexcept {return native_;}\n std::string generic_string() const noexcept {\n std::string copy(native_);\n to_generic(copy);\n return copy;\n }\n\n private:\n#ifdef _WIN32\n void to_native(string_type& data) const {\n std::replace(data.begin(), data.end(), '\/', preferred_separator);\n }\n void to_generic(string_type& data) const {\n std::replace(data.begin(), data.end(), preferred_separator, '\/');\n }\n#else\n void to_native(string_type&) const noexcept {}\n void to_generic(string_type&) const noexcept {}\n#endif\n string_type native_;\n};\n\ninline path operator\/(const path& lhs, const path& rhs) {\n return path(lhs) \/= rhs;\n}\ninline bool operator==(const path& lhs, const path& rhs) noexcept {\n return lhs.native() == rhs.native();\n}\ninline bool operator!=(const path& lhs, const path& rhs) noexcept {\n return lhs.native() != rhs.native();\n}\ninline std::ostream& operator<<(std::ostream& ost, const path& p) {\n return ost << '\"' << p.string() << '\"';\n}\n\ninline bool create_directory(const path& p) {\n const int status = ::mkdir(p.c_str(), 0755);\n if (status && errno != EEXIST) {\n throw std::runtime_error(p.native());\n }\n return status == 0;\n}\n\ninline void current_path(const path& p) {\n if (::chdir(p.c_str())) {\n throw std::runtime_error(p.native());\n }\n}\n\ninline path current_path() {\n char buffer[1024];\n if (!::getcwd(buffer, sizeof(buffer))) {\n throw std::runtime_error(buffer);\n }\n return path(buffer);\n}\n\ninline bool exists(const path& p) {\n return !::access(p.c_str(), F_OK);\n}\n\n} \/\/ namespace filesystem\n\/\/\/\/\/\/\/\/\/1\/\/\/\/\/\/\/\/\/2\/\/\/\/\/\/\/\/\/3\/\/\/\/\/\/\/\/\/4\/\/\/\/\/\/\/\/\/5\/\/\/\/\/\/\/\/\/6\/\/\/\/\/\/\/\/\/7\/\/\/\/\/\/\/\/\/\n\n\/\/ RAII\nclass ChDir {\n public:\n ChDir(const std::string& dst, bool mkdir=false) {\n if (dst.empty() || dst == \".\") return;\n if (mkdir) {\n filesystem::create_directory(dst);\n }\n filesystem::current_path(dst);\n }\n ~ChDir() {\n filesystem::current_path(origin_);\n }\n private:\n const filesystem::path origin_ = filesystem::current_path();\n};\n\n} \/\/ namespace wtl\n\n#endif \/* WTL_FILESYSTEM_HPP_ *\/\n<|endoftext|>"} {"text":"<commit_before>\/* This source file is part of the Tomviz project, https:\/\/tomviz.org\/.\n It is released under the 3-Clause BSD License, see \"LICENSE\". *\/\n\n#include \"GenericHDF5Format.h\"\n\n#include <DataExchangeFormat.h>\n#include <DataSource.h>\n#include <Hdf5SubsampleWidget.h>\n#include <Utilities.h>\n\n#include <h5cpp\/h5readwrite.h>\n#include <h5cpp\/h5vtktypemaps.h>\n\n#include <QDialog>\n#include <QDialogButtonBox>\n#include <QInputDialog>\n#include <QStringList>\n#include <QVBoxLayout>\n\n#include <vtkDataArray.h>\n#include <vtkImageData.h>\n#include <vtkPointData.h>\n\n#include <string>\n#include <vector>\n\n#include <iostream>\n\nusing std::cerr;\nusing std::cout;\nusing std::endl;\n\nnamespace tomviz {\n\ntemplate <typename T>\nvoid ReorderArrayC(T* in, T* out, int dim[3])\n{\n for (int i = 0; i < dim[0]; ++i) {\n for (int j = 0; j < dim[1]; ++j) {\n for (int k = 0; k < dim[2]; ++k) {\n out[static_cast<size_t>(i * dim[1] + j) * dim[2] + k] =\n in[static_cast<size_t>(k * dim[1] + j) * dim[0] + i];\n }\n }\n }\n}\n\ntemplate <typename T>\nvoid ReorderArrayF(T* in, T* out, int dim[3])\n{\n for (int i = 0; i < dim[0]; ++i) {\n for (int j = 0; j < dim[1]; ++j) {\n for (int k = 0; k < dim[2]; ++k) {\n out[static_cast<size_t>(k * dim[1] + j) * dim[0] + i] =\n in[static_cast<size_t>(i * dim[1] + j) * dim[2] + k];\n }\n }\n }\n}\n\nbool GenericHDF5Format::addScalarArray(h5::H5ReadWrite& reader,\n const std::string& path,\n vtkImageData* image,\n const std::string& name)\n{\n \/\/ Get the type of the data\n h5::H5ReadWrite::DataType type = reader.dataType(path);\n int vtkDataType = h5::H5VtkTypeMaps::dataTypeToVtk(type);\n\n \/\/ Get the dimensions\n std::vector<int> dims = reader.getDimensions(path);\n\n \/\/ Set up the strides and counts\n int strides[3] = { 1, 1, 1 };\n size_t start[3], counts[3];\n if (DataSource::wasSubsampled(image)) {\n \/\/ If the main image was subsampled, we need to use the same\n \/\/ subsampling for the scalars\n DataSource::subsampleStrides(image, strides);\n int bs[6];\n DataSource::subsampleVolumeBounds(image, bs);\n\n for (int i = 0; i < 3; ++i) {\n start[i] = static_cast<size_t>(bs[i * 2]);\n counts[i] = (bs[i * 2 + 1] - start[i]) \/ strides[i];\n }\n } else {\n for (int i = 0; i < 3; ++i) {\n start[i] = 0;\n counts[i] = dims[i];\n }\n }\n\n \/\/ vtk requires the counts to be an int array\n int vtkCounts[3];\n for (int i = 0; i < 3; ++i)\n vtkCounts[i] = counts[i];\n\n vtkNew<vtkImageData> tmp;\n tmp->SetDimensions(&vtkCounts[0]);\n tmp->AllocateScalars(vtkDataType, 1);\n\n if (!reader.readData(path, type, tmp->GetScalarPointer(), strides, start,\n counts)) {\n std::cerr << \"Failed to read the data\\n\";\n return false;\n }\n\n auto* array = vtkAbstractArray::CreateArray(vtkDataType);\n array->SetNumberOfTuples(counts[0] * counts[1] * counts[2]);\n array->SetName(name.c_str());\n image->GetPointData()->AddArray(array);\n\n \/\/ HDF5 typically stores data as row major order.\n \/\/ VTK expects column major order.\n auto inPtr = tmp->GetPointData()->GetScalars()->GetVoidPointer(0);\n auto outPtr = array->GetVoidPointer(0);\n switch (vtkDataType) {\n vtkTemplateMacro(tomviz::ReorderArrayF(reinterpret_cast<VTK_TT*>(inPtr),\n reinterpret_cast<VTK_TT*>(outPtr),\n &vtkCounts[0]));\n default:\n cout << \"Generic HDF5 Format: Unknown data type\" << endl;\n }\n image->Modified();\n\n return true;\n}\n\nbool GenericHDF5Format::isDataExchange(const std::string& fileName)\n{\n using h5::H5ReadWrite;\n H5ReadWrite::OpenMode mode = H5ReadWrite::OpenMode::ReadOnly;\n H5ReadWrite reader(fileName.c_str(), mode);\n\n \/\/ If \/exchange\/data is a dataset, assume this is a DataExchangeFormat\n return reader.isDataSet(\"\/exchange\/data\");\n}\n\nbool GenericHDF5Format::isFxi(const std::string& fileName)\n{\n using h5::H5ReadWrite;\n H5ReadWrite::OpenMode mode = H5ReadWrite::OpenMode::ReadOnly;\n H5ReadWrite reader(fileName.c_str(), mode);\n\n \/\/ Look for a few keys, loosely defined BNL FXI data format.\n return reader.isDataSet(\"\/img_tomo\") && reader.isDataSet(\"\/img_bkg\");\n}\n\nbool GenericHDF5Format::readVolume(h5::H5ReadWrite& reader,\n const std::string& path, vtkImageData* image,\n const QVariantMap& options)\n{\n \/\/ Get the type of the data\n h5::H5ReadWrite::DataType type = reader.dataType(path);\n int vtkDataType = h5::H5VtkTypeMaps::dataTypeToVtk(type);\n\n \/\/ This is the easiest way I could find to get the size of the type\n int size = vtkDataArray::GetDataTypeSize(vtkDataType);\n\n \/\/ Get the dimensions\n std::vector<int> dims = reader.getDimensions(path);\n\n int bs[6] = { -1, -1, -1, -1, -1, -1 };\n int strides[3] = { 1, 1, 1 };\n if (options.contains(\"subsampleVolumeBounds\")) {\n \/\/ Get the subsample volume bounds if the caller specified them\n QVariantList list = options[\"subsampleVolumeBounds\"].toList();\n for (int i = 0; i < list.size() && i < 6; ++i)\n bs[i] = list[i].toInt();\n DataSource::setWasSubsampled(image, true);\n DataSource::setSubsampleVolumeBounds(image, bs);\n } else {\n \/\/ Set it to the defaults\n for (int i = 0; i < 3; ++i) {\n bs[i * 2] = 0;\n bs[i * 2 + 1] = dims[i];\n }\n }\n\n if (options.contains(\"subsampleStrides\")) {\n \/\/ Get the strides if the caller specified them\n QVariantList list = options[\"subsampleStrides\"].toList();\n for (int i = 0; i < list.size() && i < 3; ++i) {\n strides[i] = list[i].toInt();\n if (strides[i] < 1)\n strides[i] = 1;\n }\n\n DataSource::setWasSubsampled(image, true);\n DataSource::setSubsampleStrides(image, strides);\n }\n\n bool askForSubsample = false;\n if (options.contains(\"askForSubsample\")) {\n \/\/ If the options specify whether to ask for a subsample, use that\n askForSubsample = options[\"askForSubsample\"].toBool();\n } else {\n \/\/ Otherwise, only ask for a subsample if the data looks large\n int subsampleDimOverride = 1200;\n if (options.contains(\"subsampleDimOverride\"))\n subsampleDimOverride = options[\"subsampleDimOverride\"].toInt();\n\n askForSubsample =\n std::any_of(dims.cbegin(), dims.cend(), [subsampleDimOverride](int i) {\n return i >= subsampleDimOverride;\n });\n }\n\n if (askForSubsample) {\n int dimensions[3] = { dims[0], dims[1], dims[2] };\n QDialog dialog;\n dialog.setWindowTitle(\"Pick Subsample\");\n QVBoxLayout layout;\n dialog.setLayout(&layout);\n\n Hdf5SubsampleWidget widget(dimensions, size);\n layout.addWidget(&widget);\n\n if (DataSource::wasSubsampled(image)) {\n \/\/ If it was previously subsampled, start with the previous values\n DataSource::subsampleStrides(image, strides);\n widget.setStrides(strides);\n\n DataSource::subsampleVolumeBounds(image, bs);\n widget.setBounds(bs);\n }\n\n QDialogButtonBox buttons(QDialogButtonBox::Ok | QDialogButtonBox::Cancel |\n QDialogButtonBox::Help);\n layout.addWidget(&buttons);\n QObject::connect(&buttons, &QDialogButtonBox::accepted, &dialog,\n &QDialog::accept);\n QObject::connect(&buttons, &QDialogButtonBox::rejected, &dialog,\n &QDialog::reject);\n QObject::connect(&buttons, &QDialogButtonBox::helpRequested,\n []() { openHelpUrl(\"data\/#hdf5-subsampling\"); });\n\n \/\/ Check if the user cancels\n if (!dialog.exec())\n return false;\n\n widget.bounds(bs);\n widget.strides(strides);\n\n DataSource::setWasSubsampled(image, true);\n DataSource::setSubsampleStrides(image, strides);\n DataSource::setSubsampleVolumeBounds(image, bs);\n }\n\n \/\/ Do one final check to make sure none of the bounds are less than 0\n if (std::any_of(std::begin(bs), std::end(bs), [](int i) { return i < 0; })) {\n \/\/ Set them to their defaults so we don't seg fault\n for (int i = 0; i < 3; ++i) {\n bs[i * 2] = 0;\n bs[i * 2 + 1] = dims[i];\n }\n }\n\n \/\/ Set up the strides and counts\n size_t start[3] = { static_cast<size_t>(bs[0]), static_cast<size_t>(bs[2]),\n static_cast<size_t>(bs[4]) };\n size_t counts[3];\n for (size_t i = 0; i < 3; ++i)\n counts[i] = (bs[i * 2 + 1] - start[i]) \/ strides[i];\n\n \/\/ vtk requires the counts to be an int array\n int vtkCounts[3];\n for (int i = 0; i < 3; ++i)\n vtkCounts[i] = counts[i];\n\n vtkNew<vtkImageData> tmp;\n tmp->SetDimensions(&vtkCounts[0]);\n tmp->AllocateScalars(vtkDataType, 1);\n image->SetDimensions(&vtkCounts[0]);\n image->AllocateScalars(vtkDataType, 1);\n\n if (!reader.readData(path, type, tmp->GetScalarPointer(), strides, start,\n counts)) {\n std::cerr << \"Failed to read the data\\n\";\n return false;\n }\n\n \/\/ HDF5 typically stores data as row major order.\n \/\/ VTK expects column major order.\n auto inPtr = tmp->GetPointData()->GetScalars()->GetVoidPointer(0);\n auto outPtr = image->GetPointData()->GetScalars()->GetVoidPointer(0);\n switch (image->GetPointData()->GetScalars()->GetDataType()) {\n vtkTemplateMacro(tomviz::ReorderArrayF(reinterpret_cast<VTK_TT*>(inPtr),\n reinterpret_cast<VTK_TT*>(outPtr),\n &vtkCounts[0]));\n default:\n cout << \"Generic HDF5 Format: Unknown data type\" << endl;\n }\n image->Modified();\n\n return true;\n}\n\nbool GenericHDF5Format::read(const std::string& fileName, vtkImageData* image,\n const QVariantMap& options)\n{\n Q_UNUSED(options)\n\n using h5::H5ReadWrite;\n H5ReadWrite::OpenMode mode = H5ReadWrite::OpenMode::ReadOnly;\n H5ReadWrite reader(fileName.c_str(), mode);\n\n \/\/ Find all 3D datasets. If there is more than one, have the user choose.\n std::vector<std::string> datasets = reader.allDataSets();\n for (auto it = datasets.begin(); it != datasets.end();) {\n \/\/ Remove all non-3D datasets\n std::vector<int> dims = reader.getDimensions(*it);\n if (dims.size() != 3)\n datasets.erase(it);\n else\n ++it;\n }\n\n if (datasets.empty()) {\n std::cerr << \"No 3D datasets found in \" << fileName.c_str() << \"\\n\";\n return false;\n }\n\n std::string dataNode = datasets[0];\n\n if (datasets.size() != 1) {\n \/\/ If there is more than one dataset, have the user choose one\n QStringList items;\n for (auto& d : datasets)\n items.append(QString::fromStdString(d));\n\n bool ok;\n QString res = QInputDialog::getItem(\n nullptr, \"Choose volume\", \"Choose volume to load:\", items, 0, false, &ok);\n\n \/\/ Check if user canceled\n if (!ok)\n return false;\n\n dataNode = datasets[items.indexOf(res)];\n }\n\n return readVolume(reader, dataNode, image);\n}\n\nbool GenericHDF5Format::writeVolume(h5::H5ReadWrite& writer,\n const std::string& path,\n const std::string& name,\n vtkImageData* image)\n{\n int dim[3];\n image->GetDimensions(dim);\n std::vector<int> dims({ dim[0], dim[1], dim[2] });\n\n \/\/ We must allocate a new array, and copy the reordered array into it.\n auto arrayPtr = image->GetPointData()->GetScalars();\n auto dataPtr = arrayPtr->GetVoidPointer(0);\n vtkNew<vtkImageData> reorderedImageData;\n reorderedImageData->SetDimensions(dim);\n reorderedImageData->AllocateScalars(arrayPtr->GetDataType(), 1);\n auto outPtr =\n reorderedImageData->GetPointData()->GetScalars()->GetVoidPointer(0);\n\n switch (arrayPtr->GetDataType()) {\n vtkTemplateMacro(tomviz::ReorderArrayC(reinterpret_cast<VTK_TT*>(dataPtr),\n reinterpret_cast<VTK_TT*>(outPtr),\n dim));\n default:\n cout << \"Generic HDF5 Format: Unknown data type\" << endl;\n }\n\n h5::H5ReadWrite::DataType type =\n h5::H5VtkTypeMaps::VtkToDataType(arrayPtr->GetDataType());\n\n return writer.writeData(path, name, dims, type, outPtr);\n}\n\n} \/\/ namespace tomviz\n<commit_msg>Add ability to load multiple volumes from HDF5<commit_after>\/* This source file is part of the Tomviz project, https:\/\/tomviz.org\/.\n It is released under the 3-Clause BSD License, see \"LICENSE\". *\/\n\n#include \"GenericHDF5Format.h\"\n\n#include <DataExchangeFormat.h>\n#include <DataSource.h>\n#include <Hdf5SubsampleWidget.h>\n#include <Utilities.h>\n\n#include <h5cpp\/h5readwrite.h>\n#include <h5cpp\/h5vtktypemaps.h>\n\n#include <QCheckBox>\n#include <QDialog>\n#include <QDialogButtonBox>\n#include <QMessageBox>\n#include <QScrollArea>\n#include <QStringList>\n#include <QVBoxLayout>\n\n#include <vtkDataArray.h>\n#include <vtkImageData.h>\n#include <vtkPointData.h>\n\n#include <string>\n#include <vector>\n\n#include <iostream>\n#include <sstream>\n\nusing std::cerr;\nusing std::cout;\nusing std::endl;\n\nnamespace tomviz {\n\ntemplate <typename T>\nvoid ReorderArrayC(T* in, T* out, int dim[3])\n{\n for (int i = 0; i < dim[0]; ++i) {\n for (int j = 0; j < dim[1]; ++j) {\n for (int k = 0; k < dim[2]; ++k) {\n out[static_cast<size_t>(i * dim[1] + j) * dim[2] + k] =\n in[static_cast<size_t>(k * dim[1] + j) * dim[0] + i];\n }\n }\n }\n}\n\ntemplate <typename T>\nvoid ReorderArrayF(T* in, T* out, int dim[3])\n{\n for (int i = 0; i < dim[0]; ++i) {\n for (int j = 0; j < dim[1]; ++j) {\n for (int k = 0; k < dim[2]; ++k) {\n out[static_cast<size_t>(k * dim[1] + j) * dim[0] + i] =\n in[static_cast<size_t>(i * dim[1] + j) * dim[2] + k];\n }\n }\n }\n}\n\nbool GenericHDF5Format::addScalarArray(h5::H5ReadWrite& reader,\n const std::string& path,\n vtkImageData* image,\n const std::string& name)\n{\n \/\/ Get the type of the data\n h5::H5ReadWrite::DataType type = reader.dataType(path);\n int vtkDataType = h5::H5VtkTypeMaps::dataTypeToVtk(type);\n\n \/\/ Get the dimensions\n std::vector<int> dims = reader.getDimensions(path);\n\n \/\/ Set up the strides and counts\n int strides[3] = { 1, 1, 1 };\n size_t start[3], counts[3];\n if (DataSource::wasSubsampled(image)) {\n \/\/ If the main image was subsampled, we need to use the same\n \/\/ subsampling for the scalars\n DataSource::subsampleStrides(image, strides);\n int bs[6];\n DataSource::subsampleVolumeBounds(image, bs);\n\n for (int i = 0; i < 3; ++i) {\n start[i] = static_cast<size_t>(bs[i * 2]);\n counts[i] = (bs[i * 2 + 1] - start[i]) \/ strides[i];\n }\n } else {\n for (int i = 0; i < 3; ++i) {\n start[i] = 0;\n counts[i] = dims[i];\n }\n }\n\n \/\/ vtk requires the counts to be an int array\n int vtkCounts[3];\n for (int i = 0; i < 3; ++i)\n vtkCounts[i] = counts[i];\n\n \/\/ Make sure the dimensions match those of the image, or else\n \/\/ we will probably experience a crash later...\n int imageDims[3];\n image->GetDimensions(imageDims);\n for (int i = 0; i < 3; ++i) {\n if (vtkCounts[i] != imageDims[i]) {\n std::stringstream ss;\n if (DataSource::wasSubsampled(image)) {\n ss << \"Subsampled dimensions of \";\n } else {\n ss << \"Dimensions of \";\n }\n ss << path << \" (\" << vtkCounts[0] << \", \" << vtkCounts[1] << \", \"\n << vtkCounts[2] << \") do not match the dimensions of the image (\"\n << imageDims[0] << \", \" << imageDims[1] << \", \" << imageDims[2]\n << \")\\nThe array cannot be added.\";\n\n std::cerr << \"Error in GenericHDF5Format::addScalarArray():\\n\"\n << ss.str() << std::endl;\n QMessageBox::critical(nullptr, \"Dimensions do not match\",\n ss.str().c_str());\n return false;\n }\n }\n\n vtkNew<vtkImageData> tmp;\n tmp->SetDimensions(&vtkCounts[0]);\n tmp->AllocateScalars(vtkDataType, 1);\n\n if (!reader.readData(path, type, tmp->GetScalarPointer(), strides, start,\n counts)) {\n std::cerr << \"Failed to read the data\\n\";\n return false;\n }\n\n auto* array = vtkAbstractArray::CreateArray(vtkDataType);\n array->SetNumberOfTuples(counts[0] * counts[1] * counts[2]);\n array->SetName(name.c_str());\n image->GetPointData()->AddArray(array);\n\n \/\/ HDF5 typically stores data as row major order.\n \/\/ VTK expects column major order.\n auto inPtr = tmp->GetPointData()->GetScalars()->GetVoidPointer(0);\n auto outPtr = array->GetVoidPointer(0);\n switch (vtkDataType) {\n vtkTemplateMacro(tomviz::ReorderArrayF(reinterpret_cast<VTK_TT*>(inPtr),\n reinterpret_cast<VTK_TT*>(outPtr),\n &vtkCounts[0]));\n default:\n cout << \"Generic HDF5 Format: Unknown data type\" << endl;\n }\n image->Modified();\n\n return true;\n}\n\nbool GenericHDF5Format::isDataExchange(const std::string& fileName)\n{\n using h5::H5ReadWrite;\n H5ReadWrite::OpenMode mode = H5ReadWrite::OpenMode::ReadOnly;\n H5ReadWrite reader(fileName.c_str(), mode);\n\n \/\/ If \/exchange\/data is a dataset, assume this is a DataExchangeFormat\n return reader.isDataSet(\"\/exchange\/data\");\n}\n\nbool GenericHDF5Format::isFxi(const std::string& fileName)\n{\n using h5::H5ReadWrite;\n H5ReadWrite::OpenMode mode = H5ReadWrite::OpenMode::ReadOnly;\n H5ReadWrite reader(fileName.c_str(), mode);\n\n \/\/ Look for a few keys, loosely defined BNL FXI data format.\n return reader.isDataSet(\"\/img_tomo\") && reader.isDataSet(\"\/img_bkg\");\n}\n\nbool GenericHDF5Format::readVolume(h5::H5ReadWrite& reader,\n const std::string& path, vtkImageData* image,\n const QVariantMap& options)\n{\n \/\/ Get the type of the data\n h5::H5ReadWrite::DataType type = reader.dataType(path);\n int vtkDataType = h5::H5VtkTypeMaps::dataTypeToVtk(type);\n\n \/\/ This is the easiest way I could find to get the size of the type\n int size = vtkDataArray::GetDataTypeSize(vtkDataType);\n\n \/\/ Get the dimensions\n std::vector<int> dims = reader.getDimensions(path);\n\n int bs[6] = { -1, -1, -1, -1, -1, -1 };\n int strides[3] = { 1, 1, 1 };\n if (options.contains(\"subsampleVolumeBounds\")) {\n \/\/ Get the subsample volume bounds if the caller specified them\n QVariantList list = options[\"subsampleVolumeBounds\"].toList();\n for (int i = 0; i < list.size() && i < 6; ++i)\n bs[i] = list[i].toInt();\n DataSource::setWasSubsampled(image, true);\n DataSource::setSubsampleVolumeBounds(image, bs);\n } else {\n \/\/ Set it to the defaults\n for (int i = 0; i < 3; ++i) {\n bs[i * 2] = 0;\n bs[i * 2 + 1] = dims[i];\n }\n }\n\n if (options.contains(\"subsampleStrides\")) {\n \/\/ Get the strides if the caller specified them\n QVariantList list = options[\"subsampleStrides\"].toList();\n for (int i = 0; i < list.size() && i < 3; ++i) {\n strides[i] = list[i].toInt();\n if (strides[i] < 1)\n strides[i] = 1;\n }\n\n DataSource::setWasSubsampled(image, true);\n DataSource::setSubsampleStrides(image, strides);\n }\n\n bool askForSubsample = false;\n if (options.contains(\"askForSubsample\")) {\n \/\/ If the options specify whether to ask for a subsample, use that\n askForSubsample = options[\"askForSubsample\"].toBool();\n } else {\n \/\/ Otherwise, only ask for a subsample if the data looks large\n int subsampleDimOverride = 1200;\n if (options.contains(\"subsampleDimOverride\"))\n subsampleDimOverride = options[\"subsampleDimOverride\"].toInt();\n\n askForSubsample =\n std::any_of(dims.cbegin(), dims.cend(), [subsampleDimOverride](int i) {\n return i >= subsampleDimOverride;\n });\n }\n\n if (askForSubsample) {\n int dimensions[3] = { dims[0], dims[1], dims[2] };\n QDialog dialog;\n dialog.setWindowTitle(\"Pick Subsample\");\n QVBoxLayout layout;\n dialog.setLayout(&layout);\n\n Hdf5SubsampleWidget widget(dimensions, size);\n layout.addWidget(&widget);\n\n if (DataSource::wasSubsampled(image)) {\n \/\/ If it was previously subsampled, start with the previous values\n DataSource::subsampleStrides(image, strides);\n widget.setStrides(strides);\n\n DataSource::subsampleVolumeBounds(image, bs);\n widget.setBounds(bs);\n }\n\n QDialogButtonBox buttons(QDialogButtonBox::Ok | QDialogButtonBox::Cancel |\n QDialogButtonBox::Help);\n layout.addWidget(&buttons);\n QObject::connect(&buttons, &QDialogButtonBox::accepted, &dialog,\n &QDialog::accept);\n QObject::connect(&buttons, &QDialogButtonBox::rejected, &dialog,\n &QDialog::reject);\n QObject::connect(&buttons, &QDialogButtonBox::helpRequested,\n []() { openHelpUrl(\"data\/#hdf5-subsampling\"); });\n\n \/\/ Check if the user cancels\n if (!dialog.exec())\n return false;\n\n widget.bounds(bs);\n widget.strides(strides);\n\n DataSource::setWasSubsampled(image, true);\n DataSource::setSubsampleStrides(image, strides);\n DataSource::setSubsampleVolumeBounds(image, bs);\n }\n\n \/\/ Do one final check to make sure none of the bounds are less than 0\n if (std::any_of(std::begin(bs), std::end(bs), [](int i) { return i < 0; })) {\n \/\/ Set them to their defaults so we don't seg fault\n for (int i = 0; i < 3; ++i) {\n bs[i * 2] = 0;\n bs[i * 2 + 1] = dims[i];\n }\n }\n\n \/\/ Set up the strides and counts\n size_t start[3] = { static_cast<size_t>(bs[0]), static_cast<size_t>(bs[2]),\n static_cast<size_t>(bs[4]) };\n size_t counts[3];\n for (size_t i = 0; i < 3; ++i)\n counts[i] = (bs[i * 2 + 1] - start[i]) \/ strides[i];\n\n \/\/ vtk requires the counts to be an int array\n int vtkCounts[3];\n for (int i = 0; i < 3; ++i)\n vtkCounts[i] = counts[i];\n\n vtkNew<vtkImageData> tmp;\n tmp->SetDimensions(&vtkCounts[0]);\n tmp->AllocateScalars(vtkDataType, 1);\n image->SetDimensions(&vtkCounts[0]);\n image->AllocateScalars(vtkDataType, 1);\n\n if (!reader.readData(path, type, tmp->GetScalarPointer(), strides, start,\n counts)) {\n std::cerr << \"Failed to read the data\\n\";\n return false;\n }\n\n \/\/ HDF5 typically stores data as row major order.\n \/\/ VTK expects column major order.\n auto inPtr = tmp->GetPointData()->GetScalars()->GetVoidPointer(0);\n auto outPtr = image->GetPointData()->GetScalars()->GetVoidPointer(0);\n switch (image->GetPointData()->GetScalars()->GetDataType()) {\n vtkTemplateMacro(tomviz::ReorderArrayF(reinterpret_cast<VTK_TT*>(inPtr),\n reinterpret_cast<VTK_TT*>(outPtr),\n &vtkCounts[0]));\n default:\n cout << \"Generic HDF5 Format: Unknown data type\" << endl;\n }\n image->Modified();\n\n return true;\n}\n\nbool GenericHDF5Format::read(const std::string& fileName, vtkImageData* image,\n const QVariantMap& options)\n{\n Q_UNUSED(options)\n\n using h5::H5ReadWrite;\n H5ReadWrite::OpenMode mode = H5ReadWrite::OpenMode::ReadOnly;\n H5ReadWrite reader(fileName.c_str(), mode);\n\n \/\/ Find all 3D datasets. If there is more than one, have the user choose.\n std::vector<std::string> datasets = reader.allDataSets();\n for (auto it = datasets.begin(); it != datasets.end();) {\n \/\/ Remove all non-3D datasets\n std::vector<int> dims = reader.getDimensions(*it);\n if (dims.size() != 3)\n datasets.erase(it);\n else\n ++it;\n }\n\n if (datasets.empty()) {\n std::cerr << \"No 3D datasets found in \" << fileName.c_str() << \"\\n\";\n return false;\n }\n\n std::string dataNode = datasets[0];\n\n if (datasets.size() == 1) {\n \/\/ Only one volume. Load and return.\n return readVolume(reader, dataNode, image);\n }\n\n \/\/ If there is more than one volume, have the user choose.\n QStringList items;\n for (auto& d : datasets)\n items.append(QString::fromStdString(d));\n\n \/\/ Choose the volumes to load\n QDialog dialog;\n dialog.setWindowTitle(\"Choose volumes\");\n QVBoxLayout layout;\n dialog.setLayout(&layout);\n\n \/\/ Use a scroll area in case there are a lot of options\n QScrollArea scrollArea;\n scrollArea.setWidgetResizable(true); \/\/ Necessary for some reason\n layout.addWidget(&scrollArea);\n\n QWidget scrollAreaWidget;\n QVBoxLayout scrollAreaLayout;\n scrollAreaWidget.setLayout(&scrollAreaLayout);\n scrollArea.setWidget(&scrollAreaWidget);\n\n \/\/ Add the checkboxes\n QList<QCheckBox*> checkboxes;\n for (const auto& item : items) {\n checkboxes.append(new QCheckBox(item, &scrollAreaWidget));\n scrollAreaLayout.addWidget(checkboxes.back());\n }\n\n \/\/ Setup Ok and Cancel buttons\n QDialogButtonBox buttons(QDialogButtonBox::Ok | QDialogButtonBox::Cancel);\n layout.addWidget(&buttons);\n QObject::connect(&buttons, &QDialogButtonBox::accepted, &dialog,\n &QDialog::accept);\n QObject::connect(&buttons, &QDialogButtonBox::rejected, &dialog,\n &QDialog::reject);\n\n if (!dialog.exec()) {\n \/\/ User canceled, just return\n return false;\n }\n\n \/\/ Find the checked checkboxes\n std::vector<std::string> selectedDatasets;\n for (const auto& cb : checkboxes) {\n if (cb->isChecked()) {\n \/\/ Take advantage of the fact that the text is the name exactly\n selectedDatasets.push_back(cb->text().toStdString());\n }\n }\n\n if (selectedDatasets.empty()) {\n QString msg = \"At least one volume must be selected\";\n std::cerr << msg.toStdString() << std::endl;\n QMessageBox::critical(nullptr, \"Invalid Selection\", msg);\n return false;\n }\n\n \/\/ Read the first dataset with readVolume(). This might ask for\n \/\/ subsampling options, which will be applied to the rest of the\n \/\/ datasets.\n if (!readVolume(reader, selectedDatasets[0], image)) {\n auto msg =\n QString(\"Failed to read the data at: \") + selectedDatasets[0].c_str();\n std::cerr << msg.toStdString() << std::endl;\n QMessageBox::critical(nullptr, \"Read Failed\", msg);\n return false;\n }\n\n \/\/ Set the name of the first array\n image->GetPointData()->GetScalars()->SetName(selectedDatasets[0].c_str());\n\n \/\/ Add any more datasets with addScalarArray()\n for (size_t i = 1; i < selectedDatasets.size(); ++i) {\n const auto& path = selectedDatasets[i];\n if (!addScalarArray(reader, path, image, path)) {\n auto msg = QString(\"Failed to read or add the data of: \") + path.c_str();\n std::cerr << msg.toStdString() << std::endl;\n QMessageBox::critical(nullptr, \"Failure\", msg);\n return false;\n }\n }\n\n \/\/ Made it to the end...\n return true;\n}\n\nbool GenericHDF5Format::writeVolume(h5::H5ReadWrite& writer,\n const std::string& path,\n const std::string& name,\n vtkImageData* image)\n{\n int dim[3];\n image->GetDimensions(dim);\n std::vector<int> dims({ dim[0], dim[1], dim[2] });\n\n \/\/ We must allocate a new array, and copy the reordered array into it.\n auto arrayPtr = image->GetPointData()->GetScalars();\n auto dataPtr = arrayPtr->GetVoidPointer(0);\n vtkNew<vtkImageData> reorderedImageData;\n reorderedImageData->SetDimensions(dim);\n reorderedImageData->AllocateScalars(arrayPtr->GetDataType(), 1);\n auto outPtr =\n reorderedImageData->GetPointData()->GetScalars()->GetVoidPointer(0);\n\n switch (arrayPtr->GetDataType()) {\n vtkTemplateMacro(tomviz::ReorderArrayC(reinterpret_cast<VTK_TT*>(dataPtr),\n reinterpret_cast<VTK_TT*>(outPtr),\n dim));\n default:\n cout << \"Generic HDF5 Format: Unknown data type\" << endl;\n }\n\n h5::H5ReadWrite::DataType type =\n h5::H5VtkTypeMaps::VtkToDataType(arrayPtr->GetDataType());\n\n return writer.writeData(path, name, dims, type, outPtr);\n}\n\n} \/\/ namespace tomviz\n<|endoftext|>"} {"text":"<commit_before>\/* Copyright 2015 The TensorFlow Authors. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*\/\n\n#include \"tensorflow\/core\/util\/device_name_utils.h\"\n\n#include \"tensorflow\/core\/lib\/core\/errors.h\"\n#include \"tensorflow\/core\/lib\/strings\/str_util.h\"\n#include \"tensorflow\/core\/lib\/strings\/strcat.h\"\n#include \"tensorflow\/core\/platform\/logging.h\"\n\nnamespace tensorflow {\n\nstatic bool IsAlpha(char c) {\n return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z');\n}\n\nstatic bool IsAlphaNum(char c) { return IsAlpha(c) || (c >= '0' && c <= '9'); }\n\n\/\/ Returns true iff \"in\" is a valid job name.\nstatic bool IsJobName(StringPiece in) {\n if (in.empty()) return false;\n if (!IsAlpha(in[0])) return false;\n for (size_t i = 1; i < in.size(); ++i) {\n if (!(IsAlphaNum(in[i]) || in[i] == '_')) return false;\n }\n return true;\n}\n\n\/\/ Returns true and fills in \"*job\" iff \"*in\" starts with a job name.\nstatic bool ConsumeJobName(StringPiece* in, string* job) {\n if (in->empty()) return false;\n if (!IsAlpha((*in)[0])) return false;\n size_t i = 1;\n for (; i < in->size(); ++i) {\n const char c = (*in)[i];\n if (c == '\/') break;\n if (!(IsAlphaNum(c) || c == '_')) {\n return false;\n }\n }\n job->assign(in->data(), i);\n in->remove_prefix(i);\n return true;\n}\n\n\/\/ Returns true and fills in \"*device_type\" iff \"*in\" starts with a device type\n\/\/ name.\nstatic bool ConsumeDeviceType(StringPiece* in, string* device_type) {\n if (in->empty()) return false;\n if (!IsAlpha((*in)[0])) return false;\n size_t i = 1;\n for (; i < in->size(); ++i) {\n const char c = (*in)[i];\n if (c == '\/' || c == ':') break;\n if (!(IsAlphaNum(c) || c == '_')) {\n return false;\n }\n }\n device_type->assign(in->data(), i);\n in->remove_prefix(i);\n return true;\n}\n\n\/\/ Returns true and fills in \"*val\" iff \"*in\" starts with a decimal\n\/\/ number.\nstatic bool ConsumeNumber(StringPiece* in, int* val) {\n uint64 tmp;\n if (str_util::ConsumeLeadingDigits(in, &tmp)) {\n *val = tmp;\n return true;\n } else {\n return false;\n }\n}\n\n\/* static *\/\nstring DeviceNameUtils::FullName(const string& job, int replica, int task,\n const string& type, int id) {\n CHECK(IsJobName(job)) << job;\n CHECK_LE(0, replica);\n CHECK_LE(0, task);\n CHECK(!type.empty());\n CHECK_LE(0, id);\n return strings::StrCat(\"\/job:\", job, \"\/replica:\", replica, \"\/task:\", task,\n \"\/device:\", type, \":\", id);\n}\n\n\/* static *\/\nstring DeviceNameUtils::LegacyName(const string& job, int replica, int task,\n const string& type, int id) {\n CHECK(IsJobName(job)) << job;\n CHECK_LE(0, replica);\n CHECK_LE(0, task);\n CHECK(!type.empty());\n CHECK_LE(0, id);\n return strings::StrCat(\"\/job:\", job, \"\/replica:\", replica, \"\/task:\", task,\n \"\/\", str_util::Lowercase(type), \":\", id);\n}\n\nbool DeviceNameUtils::ParseFullName(StringPiece fullname, ParsedName* p) {\n p->Clear();\n if (fullname == \"\/\") {\n return true;\n }\n StringPiece tmp;\n while (!fullname.empty()) {\n bool progress = false;\n if (str_util::ConsumePrefix(&fullname, \"\/job:\")) {\n p->has_job = !str_util::ConsumePrefix(&fullname, \"*\");\n if (p->has_job && !ConsumeJobName(&fullname, &p->job)) {\n return false;\n }\n progress = true;\n }\n if (str_util::ConsumePrefix(&fullname, \"\/replica:\")) {\n p->has_replica = !str_util::ConsumePrefix(&fullname, \"*\");\n if (p->has_replica && !ConsumeNumber(&fullname, &p->replica)) {\n return false;\n }\n progress = true;\n }\n if (str_util::ConsumePrefix(&fullname, \"\/task:\")) {\n p->has_task = !str_util::ConsumePrefix(&fullname, \"*\");\n if (p->has_task && !ConsumeNumber(&fullname, &p->task)) {\n return false;\n }\n progress = true;\n }\n if (str_util::ConsumePrefix(&fullname, \"\/device:\")) {\n p->has_type = !str_util::ConsumePrefix(&fullname, \"*\");\n if (p->has_type && !ConsumeDeviceType(&fullname, &p->type)) {\n return false;\n }\n if (!str_util::ConsumePrefix(&fullname, \":\")) {\n p->has_id = false;\n } else {\n p->has_id = !str_util::ConsumePrefix(&fullname, \"*\");\n if (p->has_id && !ConsumeNumber(&fullname, &p->id)) {\n return false;\n }\n }\n progress = true;\n }\n\n \/\/ Handle legacy naming convention for cpu and gpu.\n if (str_util::ConsumePrefix(&fullname, \"\/cpu:\") ||\n str_util::ConsumePrefix(&fullname, \"\/CPU:\")) {\n p->has_type = true;\n p->type = \"CPU\"; \/\/ Treat '\/cpu:..' as uppercase '\/device:CPU:...'\n p->has_id = !str_util::ConsumePrefix(&fullname, \"*\");\n if (p->has_id && !ConsumeNumber(&fullname, &p->id)) {\n return false;\n }\n progress = true;\n }\n if (str_util::ConsumePrefix(&fullname, \"\/gpu:\") ||\n str_util::ConsumePrefix(&fullname, \"\/GPU:\")) {\n p->has_type = true;\n p->type = \"GPU\"; \/\/ Treat '\/gpu:..' as uppercase '\/device:GPU:...'\n p->has_id = !str_util::ConsumePrefix(&fullname, \"*\");\n if (p->has_id && !ConsumeNumber(&fullname, &p->id)) {\n return false;\n }\n progress = true;\n }\n\n if (!progress) {\n return false;\n }\n }\n return true;\n}\n\n\/* static *\/\nstring DeviceNameUtils::ParsedNameToString(const ParsedName& pn) {\n string buf;\n if (pn.has_job) strings::StrAppend(&buf, \"\/job:\", pn.job);\n if (pn.has_replica) strings::StrAppend(&buf, \"\/replica:\", pn.replica);\n if (pn.has_task) strings::StrAppend(&buf, \"\/task:\", pn.task);\n if (pn.has_type) {\n strings::StrAppend(&buf, \"\/device:\", pn.type, \":\");\n if (pn.has_id) {\n strings::StrAppend(&buf, pn.id);\n } else {\n strings::StrAppend(&buf, \"*\");\n }\n }\n return buf;\n}\n\n\/* static *\/\nbool DeviceNameUtils::IsSpecification(const ParsedName& less_specific,\n const ParsedName& more_specific) {\n if (less_specific.has_job &&\n (!more_specific.has_job || (less_specific.job != more_specific.job))) {\n return false;\n }\n if (less_specific.has_replica &&\n (!more_specific.has_replica ||\n (less_specific.replica != more_specific.replica))) {\n return false;\n }\n if (less_specific.has_task &&\n (!more_specific.has_task || (less_specific.task != more_specific.task))) {\n return false;\n }\n if (less_specific.has_type &&\n (!more_specific.has_type || (less_specific.type != more_specific.type))) {\n return false;\n }\n if (less_specific.has_id &&\n (!more_specific.has_id || (less_specific.id != more_specific.id))) {\n return false;\n }\n return true;\n}\n\n\/* static *\/\nbool DeviceNameUtils::IsCompleteSpecification(const ParsedName& pattern,\n const ParsedName& name) {\n CHECK(name.has_job && name.has_replica && name.has_task && name.has_type &&\n name.has_id);\n\n if (pattern.has_job && (pattern.job != name.job)) return false;\n if (pattern.has_replica && (pattern.replica != name.replica)) return false;\n if (pattern.has_task && (pattern.task != name.task)) return false;\n if (pattern.has_type && (pattern.type != name.type)) return false;\n if (pattern.has_id && (pattern.id != name.id)) return false;\n return true;\n}\n\n\/* static *\/\nStatus DeviceNameUtils::MergeDevNames(ParsedName* target,\n const ParsedName& other,\n bool allow_soft_placement) {\n if (other.has_job) {\n if (target->has_job && target->job != other.job) {\n return errors::InvalidArgument(\n \"Cannot merge devices with incompatible jobs: '\",\n ParsedNameToString(*target), \"' and '\", ParsedNameToString(other),\n \"'\");\n } else {\n target->has_job = other.has_job;\n target->job = other.job;\n }\n }\n\n if (other.has_replica) {\n if (target->has_replica && target->replica != other.replica) {\n return errors::InvalidArgument(\n \"Cannot merge devices with incompatible replicas: '\",\n ParsedNameToString(*target), \"' and '\", ParsedNameToString(other),\n \"'\");\n } else {\n target->has_replica = other.has_replica;\n target->replica = other.replica;\n }\n }\n\n if (other.has_task) {\n if (target->has_task && target->task != other.task) {\n return errors::InvalidArgument(\n \"Cannot merge devices with incompatible tasks: '\",\n ParsedNameToString(*target), \"' and '\", ParsedNameToString(other),\n \"'\");\n } else {\n target->has_task = other.has_task;\n target->task = other.task;\n }\n }\n\n if (other.has_type) {\n if (target->has_type && target->type != other.type) {\n if (!allow_soft_placement) {\n return errors::InvalidArgument(\n \"Cannot merge devices with incompatible types: '\",\n ParsedNameToString(*target), \"' and '\", ParsedNameToString(other),\n \"'\");\n } else {\n target->has_id = false;\n target->has_type = false;\n return Status::OK();\n }\n } else {\n target->has_type = other.has_type;\n target->type = other.type;\n }\n }\n\n if (other.has_id) {\n if (target->has_id && target->id != other.id) {\n if (!allow_soft_placement) {\n return errors::InvalidArgument(\n \"Cannot merge devices with incompatible ids: '\",\n ParsedNameToString(*target), \"' and '\", ParsedNameToString(other),\n \"'\");\n } else {\n target->has_id = false;\n return Status::OK();\n }\n } else {\n target->has_id = other.has_id;\n target->id = other.id;\n }\n }\n\n return Status::OK();\n}\n\n\/* static *\/\nbool DeviceNameUtils::IsSameAddressSpace(const ParsedName& a,\n const ParsedName& b) {\n return (a.has_job && b.has_job && (a.job == b.job)) &&\n (a.has_replica && b.has_replica && (a.replica == b.replica)) &&\n (a.has_task && b.has_task && (a.task == b.task));\n}\n\n\/* static *\/\nbool DeviceNameUtils::IsSameAddressSpace(StringPiece src, StringPiece dst) {\n ParsedName x;\n ParsedName y;\n return ParseFullName(src, &x) && ParseFullName(dst, &y) &&\n IsSameAddressSpace(x, y);\n}\n\n\/* static *\/\nstring DeviceNameUtils::LocalName(StringPiece type, int id) {\n return strings::StrCat(type, \":\", id);\n}\n\n\/* static *\/\nstring DeviceNameUtils::LocalName(StringPiece fullname) {\n ParsedName x;\n CHECK(ParseFullName(fullname, &x)) << fullname;\n return LocalName(x.type, x.id);\n}\n\n\/* static *\/\nbool DeviceNameUtils::ParseLocalName(StringPiece name, ParsedName* p) {\n if (!ConsumeDeviceType(&name, &p->type)) {\n return false;\n }\n if (!str_util::ConsumePrefix(&name, \":\")) {\n return false;\n }\n if (!ConsumeNumber(&name, &p->id)) {\n return false;\n }\n return name.empty();\n}\n\n\/* static *\/\nbool DeviceNameUtils::SplitDeviceName(StringPiece name, string* task,\n string* device) {\n ParsedName pn;\n if (ParseFullName(name, &pn) && pn.has_type && pn.has_id) {\n task->clear();\n task->reserve(\n (pn.has_job ? (5 + pn.job.size()) : 0) +\n (pn.has_replica ? (9 + 4 \/*estimated UB for # replica digits*\/) : 0) +\n (pn.has_task ? (6 + 4 \/*estimated UB for # task digits*\/) : 0));\n if (pn.has_job) {\n strings::StrAppend(task, \"\/job:\", pn.job);\n }\n if (pn.has_replica) {\n strings::StrAppend(task, \"\/replica:\", pn.replica);\n }\n if (pn.has_task) {\n strings::StrAppend(task, \"\/task:\", pn.task);\n }\n device->clear();\n strings::StrAppend(device, pn.type, \":\", pn.id);\n return true;\n }\n return false;\n}\n\n} \/\/ namespace tensorflow\n<commit_msg>Refactoring device name utils (#11797)<commit_after>\/* Copyright 2015 The TensorFlow Authors. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*\/\n\n#include \"tensorflow\/core\/util\/device_name_utils.h\"\n\n#include \"tensorflow\/core\/lib\/core\/errors.h\"\n#include \"tensorflow\/core\/lib\/strings\/str_util.h\"\n#include \"tensorflow\/core\/lib\/strings\/strcat.h\"\n#include \"tensorflow\/core\/platform\/logging.h\"\n\nnamespace tensorflow {\n\nstatic bool IsAlpha(char c) {\n return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z');\n}\n\nstatic bool IsAlphaNum(char c) { return IsAlpha(c) || (c >= '0' && c <= '9'); }\n\n\/\/ Returns true iff \"in\" is a valid job name.\nstatic bool IsJobName(StringPiece in) {\n if (in.empty()) return false;\n if (!IsAlpha(in[0])) return false;\n for (size_t i = 1; i < in.size(); ++i) {\n if (!(IsAlphaNum(in[i]) || in[i] == '_')) return false;\n }\n return true;\n}\n\n\/\/ Returns true and fills in \"*job\" iff \"*in\" starts with a job name.\nstatic bool ConsumeJobName(StringPiece* in, string* job) {\n if (in->empty()) return false;\n if (!IsAlpha((*in)[0])) return false;\n size_t i = 1;\n for (; i < in->size(); ++i) {\n const char c = (*in)[i];\n if (c == '\/') break;\n if (!(IsAlphaNum(c) || c == '_')) {\n return false;\n }\n }\n job->assign(in->data(), i);\n in->remove_prefix(i);\n return true;\n}\n\n\/\/ Returns true and fills in \"*device_type\" iff \"*in\" starts with a device type\n\/\/ name.\nstatic bool ConsumeDeviceType(StringPiece* in, string* device_type) {\n if (in->empty()) return false;\n if (!IsAlpha((*in)[0])) return false;\n size_t i = 1;\n for (; i < in->size(); ++i) {\n const char c = (*in)[i];\n if (c == '\/' || c == ':') break;\n if (!(IsAlphaNum(c) || c == '_')) {\n return false;\n }\n }\n device_type->assign(in->data(), i);\n in->remove_prefix(i);\n return true;\n}\n\n\/\/ Returns true and fills in \"*val\" iff \"*in\" starts with a decimal\n\/\/ number.\nstatic bool ConsumeNumber(StringPiece* in, int* val) {\n uint64 tmp;\n if (str_util::ConsumeLeadingDigits(in, &tmp)) {\n *val = tmp;\n return true;\n } else {\n return false;\n }\n}\n\n\/\/ Returns a fully qualified device name given the parameters.\nstatic string DeviceName(const string& job, int replica, int task,\n const string& device_prefix, const string& device_type,\n int id) {\n CHECK(IsJobName(job)) << job;\n CHECK_LE(0, replica);\n CHECK_LE(0, task);\n CHECK(!device_type.empty());\n CHECK_LE(0, id);\n return strings::StrCat(\"\/job:\", job, \"\/replica:\", replica, \"\/task:\", task,\n device_prefix, device_type, \":\", id);\n}\n\n\/* static *\/\nstring DeviceNameUtils::FullName(const string& job, int replica, int task,\n const string& type, int id) {\n return DeviceName(job, replica, task, \"\/device:\", type, id);\n}\n\n\/* static *\/\nstring DeviceNameUtils::LegacyName(const string& job, int replica, int task,\n const string& type, int id) {\n return DeviceName(job, replica, task, \"\/\", str_util::Lowercase(type), id);\n}\n\nbool DeviceNameUtils::ParseFullName(StringPiece fullname, ParsedName* p) {\n p->Clear();\n if (fullname == \"\/\") {\n return true;\n }\n StringPiece tmp;\n while (!fullname.empty()) {\n bool progress = false;\n if (str_util::ConsumePrefix(&fullname, \"\/job:\")) {\n p->has_job = !str_util::ConsumePrefix(&fullname, \"*\");\n if (p->has_job && !ConsumeJobName(&fullname, &p->job)) {\n return false;\n }\n progress = true;\n }\n if (str_util::ConsumePrefix(&fullname, \"\/replica:\")) {\n p->has_replica = !str_util::ConsumePrefix(&fullname, \"*\");\n if (p->has_replica && !ConsumeNumber(&fullname, &p->replica)) {\n return false;\n }\n progress = true;\n }\n if (str_util::ConsumePrefix(&fullname, \"\/task:\")) {\n p->has_task = !str_util::ConsumePrefix(&fullname, \"*\");\n if (p->has_task && !ConsumeNumber(&fullname, &p->task)) {\n return false;\n }\n progress = true;\n }\n if (str_util::ConsumePrefix(&fullname, \"\/device:\")) {\n p->has_type = !str_util::ConsumePrefix(&fullname, \"*\");\n if (p->has_type && !ConsumeDeviceType(&fullname, &p->type)) {\n return false;\n }\n if (!str_util::ConsumePrefix(&fullname, \":\")) {\n p->has_id = false;\n } else {\n p->has_id = !str_util::ConsumePrefix(&fullname, \"*\");\n if (p->has_id && !ConsumeNumber(&fullname, &p->id)) {\n return false;\n }\n }\n progress = true;\n }\n\n \/\/ Handle legacy naming convention for cpu and gpu.\n if (str_util::ConsumePrefix(&fullname, \"\/cpu:\") ||\n str_util::ConsumePrefix(&fullname, \"\/CPU:\")) {\n p->has_type = true;\n p->type = \"CPU\"; \/\/ Treat '\/cpu:..' as uppercase '\/device:CPU:...'\n p->has_id = !str_util::ConsumePrefix(&fullname, \"*\");\n if (p->has_id && !ConsumeNumber(&fullname, &p->id)) {\n return false;\n }\n progress = true;\n }\n if (str_util::ConsumePrefix(&fullname, \"\/gpu:\") ||\n str_util::ConsumePrefix(&fullname, \"\/GPU:\")) {\n p->has_type = true;\n p->type = \"GPU\"; \/\/ Treat '\/gpu:..' as uppercase '\/device:GPU:...'\n p->has_id = !str_util::ConsumePrefix(&fullname, \"*\");\n if (p->has_id && !ConsumeNumber(&fullname, &p->id)) {\n return false;\n }\n progress = true;\n }\n\n if (!progress) {\n return false;\n }\n }\n return true;\n}\n\n\/* static *\/\nstring DeviceNameUtils::ParsedNameToString(const ParsedName& pn) {\n string buf;\n if (pn.has_job) strings::StrAppend(&buf, \"\/job:\", pn.job);\n if (pn.has_replica) strings::StrAppend(&buf, \"\/replica:\", pn.replica);\n if (pn.has_task) strings::StrAppend(&buf, \"\/task:\", pn.task);\n if (pn.has_type) {\n strings::StrAppend(&buf, \"\/device:\", pn.type, \":\");\n if (pn.has_id) {\n strings::StrAppend(&buf, pn.id);\n } else {\n strings::StrAppend(&buf, \"*\");\n }\n }\n return buf;\n}\n\n\/* static *\/\nbool DeviceNameUtils::IsSpecification(const ParsedName& less_specific,\n const ParsedName& more_specific) {\n if (less_specific.has_job &&\n (!more_specific.has_job || (less_specific.job != more_specific.job))) {\n return false;\n }\n if (less_specific.has_replica &&\n (!more_specific.has_replica ||\n (less_specific.replica != more_specific.replica))) {\n return false;\n }\n if (less_specific.has_task &&\n (!more_specific.has_task || (less_specific.task != more_specific.task))) {\n return false;\n }\n if (less_specific.has_type &&\n (!more_specific.has_type || (less_specific.type != more_specific.type))) {\n return false;\n }\n if (less_specific.has_id &&\n (!more_specific.has_id || (less_specific.id != more_specific.id))) {\n return false;\n }\n return true;\n}\n\n\/* static *\/\nbool DeviceNameUtils::IsCompleteSpecification(const ParsedName& pattern,\n const ParsedName& name) {\n CHECK(name.has_job && name.has_replica && name.has_task && name.has_type &&\n name.has_id);\n\n if (pattern.has_job && (pattern.job != name.job)) return false;\n if (pattern.has_replica && (pattern.replica != name.replica)) return false;\n if (pattern.has_task && (pattern.task != name.task)) return false;\n if (pattern.has_type && (pattern.type != name.type)) return false;\n if (pattern.has_id && (pattern.id != name.id)) return false;\n return true;\n}\n\n\/* static *\/\nStatus DeviceNameUtils::MergeDevNames(ParsedName* target,\n const ParsedName& other,\n bool allow_soft_placement) {\n if (other.has_job) {\n if (target->has_job && target->job != other.job) {\n return errors::InvalidArgument(\n \"Cannot merge devices with incompatible jobs: '\",\n ParsedNameToString(*target), \"' and '\", ParsedNameToString(other),\n \"'\");\n } else {\n target->has_job = other.has_job;\n target->job = other.job;\n }\n }\n\n if (other.has_replica) {\n if (target->has_replica && target->replica != other.replica) {\n return errors::InvalidArgument(\n \"Cannot merge devices with incompatible replicas: '\",\n ParsedNameToString(*target), \"' and '\", ParsedNameToString(other),\n \"'\");\n } else {\n target->has_replica = other.has_replica;\n target->replica = other.replica;\n }\n }\n\n if (other.has_task) {\n if (target->has_task && target->task != other.task) {\n return errors::InvalidArgument(\n \"Cannot merge devices with incompatible tasks: '\",\n ParsedNameToString(*target), \"' and '\", ParsedNameToString(other),\n \"'\");\n } else {\n target->has_task = other.has_task;\n target->task = other.task;\n }\n }\n\n if (other.has_type) {\n if (target->has_type && target->type != other.type) {\n if (!allow_soft_placement) {\n return errors::InvalidArgument(\n \"Cannot merge devices with incompatible types: '\",\n ParsedNameToString(*target), \"' and '\", ParsedNameToString(other),\n \"'\");\n } else {\n target->has_id = false;\n target->has_type = false;\n return Status::OK();\n }\n } else {\n target->has_type = other.has_type;\n target->type = other.type;\n }\n }\n\n if (other.has_id) {\n if (target->has_id && target->id != other.id) {\n if (!allow_soft_placement) {\n return errors::InvalidArgument(\n \"Cannot merge devices with incompatible ids: '\",\n ParsedNameToString(*target), \"' and '\", ParsedNameToString(other),\n \"'\");\n } else {\n target->has_id = false;\n return Status::OK();\n }\n } else {\n target->has_id = other.has_id;\n target->id = other.id;\n }\n }\n\n return Status::OK();\n}\n\n\/* static *\/\nbool DeviceNameUtils::IsSameAddressSpace(const ParsedName& a,\n const ParsedName& b) {\n return (a.has_job && b.has_job && (a.job == b.job)) &&\n (a.has_replica && b.has_replica && (a.replica == b.replica)) &&\n (a.has_task && b.has_task && (a.task == b.task));\n}\n\n\/* static *\/\nbool DeviceNameUtils::IsSameAddressSpace(StringPiece src, StringPiece dst) {\n ParsedName x;\n ParsedName y;\n return ParseFullName(src, &x) && ParseFullName(dst, &y) &&\n IsSameAddressSpace(x, y);\n}\n\n\/* static *\/\nstring DeviceNameUtils::LocalName(StringPiece type, int id) {\n return strings::StrCat(type, \":\", id);\n}\n\n\/* static *\/\nstring DeviceNameUtils::LocalName(StringPiece fullname) {\n ParsedName x;\n CHECK(ParseFullName(fullname, &x)) << fullname;\n return LocalName(x.type, x.id);\n}\n\n\/* static *\/\nbool DeviceNameUtils::ParseLocalName(StringPiece name, ParsedName* p) {\n if (!ConsumeDeviceType(&name, &p->type)) {\n return false;\n }\n if (!str_util::ConsumePrefix(&name, \":\")) {\n return false;\n }\n if (!ConsumeNumber(&name, &p->id)) {\n return false;\n }\n return name.empty();\n}\n\n\/* static *\/\nbool DeviceNameUtils::SplitDeviceName(StringPiece name, string* task,\n string* device) {\n ParsedName pn;\n if (ParseFullName(name, &pn) && pn.has_type && pn.has_id) {\n task->clear();\n task->reserve(\n (pn.has_job ? (5 + pn.job.size()) : 0) +\n (pn.has_replica ? (9 + 4 \/*estimated UB for # replica digits*\/) : 0) +\n (pn.has_task ? (6 + 4 \/*estimated UB for # task digits*\/) : 0));\n if (pn.has_job) {\n strings::StrAppend(task, \"\/job:\", pn.job);\n }\n if (pn.has_replica) {\n strings::StrAppend(task, \"\/replica:\", pn.replica);\n }\n if (pn.has_task) {\n strings::StrAppend(task, \"\/task:\", pn.task);\n }\n device->clear();\n strings::StrAppend(device, pn.type, \":\", pn.id);\n return true;\n }\n return false;\n}\n\n} \/\/ namespace tensorflow\n<|endoftext|>"} {"text":"<commit_before>#include \"..\/common\/indep-test-dep.hpp\"\n\nusing namespace wrd::indep;\n\nTEST(BuildFeature, dateGetter) {\n\tBuildFeature::Date date;\n ASSERT_GT(date.getYear(), 0);\n ASSERT_GT(date.getMonth(), 0);\n ASSERT_GT(date.getDay(), 0);\n ASSERT_STRNE(date.get().c_str(), \"\");\n}\n\nTEST(BuildFeature, timeGetter) {\n ASSERT_GT(BuildFeature::Time::getHour(), 0);\n ASSERT_GT(BuildFeature::Time::getMin(), 0);\n ASSERT_GT(BuildFeature::Time::getSec(), 0);\n ASSERT_STRNE(BuildFeature::Time::get().c_str(), \"\");\n}\n\nTEST(BuildFeature, versionGetter) {\n ASSERT_GE(BuildFeature::Version::getMajor(), 0);\n ASSERT_GE(BuildFeature::Version::getMinor(), 0);\n ASSERT_GE(BuildFeature::Version::getFix(), 0);\n ASSERT_STRNE(BuildFeature::Version::get().c_str(), \"\");\n ASSERT_STRNE(BuildFeature::Version::getValue().c_str(), \"\");\n ASSERT_STRNE(BuildFeature::Version::getName().c_str(), \"\");\n}\n\nTEST(BuildFeature, platformGetter) {\n BuildFeature::PlatformType type = BuildFeature::Platform::get();\n ASSERT_GT(type, BuildFeature::PLATFORM_TYPE_START);\n ASSERT_LE(type, BuildFeature::PLATFORM_TYPE_END);\n ASSERT_STRNE(BuildFeature::Platform::getVersion().c_str(), \"\");\n ASSERT_STRNE(BuildFeature::Platform::getName().c_str(), \"\");\n}\n<commit_msg>- [indep] fix wrong tc: build time can be 0.<commit_after>#include \"..\/common\/indep-test-dep.hpp\"\n\nusing namespace wrd::indep;\n\nTEST(BuildFeature, dateGetter) {\n\tBuildFeature::Date date;\n ASSERT_GT(date.getYear(), 0);\n ASSERT_GT(date.getMonth(), 0);\n ASSERT_GT(date.getDay(), 0);\n ASSERT_STRNE(date.get().c_str(), \"\");\n}\n\nTEST(BuildFeature, timeGetter) {\n ASSERT_GT(BuildFeature::Time::getHour(), 0);\n ASSERT_GE(BuildFeature::Time::getMin(), 0);\n ASSERT_GE(BuildFeature::Time::getSec(), 0);\n ASSERT_STRNE(BuildFeature::Time::get().c_str(), \"\");\n}\n\nTEST(BuildFeature, versionGetter) {\n ASSERT_GE(BuildFeature::Version::getMajor(), 0);\n ASSERT_GE(BuildFeature::Version::getMinor(), 0);\n ASSERT_GE(BuildFeature::Version::getFix(), 0);\n ASSERT_STRNE(BuildFeature::Version::get().c_str(), \"\");\n ASSERT_STRNE(BuildFeature::Version::getValue().c_str(), \"\");\n ASSERT_STRNE(BuildFeature::Version::getName().c_str(), \"\");\n}\n\nTEST(BuildFeature, platformGetter) {\n BuildFeature::PlatformType type = BuildFeature::Platform::get();\n ASSERT_GT(type, BuildFeature::PLATFORM_TYPE_START);\n ASSERT_LE(type, BuildFeature::PLATFORM_TYPE_END);\n ASSERT_STRNE(BuildFeature::Platform::getVersion().c_str(), \"\");\n ASSERT_STRNE(BuildFeature::Platform::getName().c_str(), \"\");\n}\n<|endoftext|>"} {"text":"<commit_before>\/**\n * @file LawOfCosines.hpp\n * @brief LawOfCosines class prototype.\n * @author zer0\n * @date 2019-05-02\n *\n * @see <https:\/\/en.wikipedia.org\/wiki\/Law_of_cosines>\n * @see <https:\/\/ko.wikipedia.org\/wiki\/%EC%BD%94%EC%82%AC%EC%9D%B8_%EB%B2%95%EC%B9%99>\n *\n * @translate{ko, 코사인 법칙은 삼각형의 두 변과 그 사잇각을 알 때 남은 한 변을 구하거나, 세 변을 알 때 세 각을 구하는 데 사용될 수 있다.}\n *\n * @remarks\n * @code\n * C\n * *\n * \/|\n * b \/ |\n * \/ | a\n * \/ |\n * A *----* B\n * c\n * @endcode\n * - <code>A<\/code> is internal angle of between <code>b<\/code> and <code>c<\/code>.\n * - <code>B<\/code> is internal angle of between <code>a<\/code> and <code>c<\/code>.\n * - <code>C<\/code> is internal angle of between <code>a<\/code> and <code>b<\/code>.\n * - <code>a<\/code> is the distance between <code>B<\/code> and <code>C<\/code>.\n * - <code>b<\/code> is the distance between <code>A<\/code> and <code>C<\/code>.\n * - <code>c<\/code> is the distance between <code>A<\/code> and <code>B<\/code>.\n * The law of cosines states:\n * \\f[\n * c^{2} = a^{2} + b^{2} - 2ab\\cos{C}\n * \\f]\n *\/\n\n#ifndef __INCLUDE_LIBTBAG__LIBTBAG_MATH_LAWOFCOSINES_HPP__\n#define __INCLUDE_LIBTBAG__LIBTBAG_MATH_LAWOFCOSINES_HPP__\n\n\/\/ MS compatible compilers support #pragma once\n#if defined(_MSC_VER) && (_MSC_VER >= 1020)\n#pragma once\n#endif\n\n#include <libtbag\/config.h>\n#include <libtbag\/predef.hpp>\n\n\/\/ -------------------\nNAMESPACE_LIBTBAG_OPEN\n\/\/ -------------------\n\nnamespace math {\n\n} \/\/ namespace math\n\n\/\/ --------------------\nNAMESPACE_LIBTBAG_CLOSE\n\/\/ --------------------\n\n#endif \/\/ __INCLUDE_LIBTBAG__LIBTBAG_MATH_LAWOFCOSINES_HPP__\n\n<commit_msg>Fixed unknown command warning in doxygen.<commit_after>\/**\n * @file LawOfCosines.hpp\n * @brief LawOfCosines class prototype.\n * @author zer0\n * @date 2019-05-02\n *\n * @translate{ko, 코사인 법칙은 삼각형의 두 변과 그 사잇각을 알 때 남은 한 변을 구하거나 세 변을 알 때 세 각을 구하는 데 사용될 수 있다.}\n *\n * @see <https:\/\/en.wikipedia.org\/wiki\/Law_of_cosines>\n * @see <https:\/\/ko.wikipedia.org\/wiki\/%EC%BD%94%EC%82%AC%EC%9D%B8_%EB%B2%95%EC%B9%99>\n *\n * @remarks\n * @code\n * C\n * *\n * \/|\n * b \/ |\n * \/ | a\n * \/ |\n * A *----* B\n * c\n * @endcode\n * - <code>A<\/code> is internal angle of between <code>b<\/code> and <code>c<\/code>.\n * - <code>B<\/code> is internal angle of between <code>a<\/code> and <code>c<\/code>.\n * - <code>C<\/code> is internal angle of between <code>a<\/code> and <code>b<\/code>.\n * - <code>a<\/code> is the distance between <code>B<\/code> and <code>C<\/code>.\n * - <code>b<\/code> is the distance between <code>A<\/code> and <code>C<\/code>.\n * - <code>c<\/code> is the distance between <code>A<\/code> and <code>B<\/code>.\n * The law of cosines states:\n * \\f[\n * c^{2} = a^{2} + b^{2} - 2ab\\cos{C}\n * \\f]\n *\/\n\n#ifndef __INCLUDE_LIBTBAG__LIBTBAG_MATH_LAWOFCOSINES_HPP__\n#define __INCLUDE_LIBTBAG__LIBTBAG_MATH_LAWOFCOSINES_HPP__\n\n\/\/ MS compatible compilers support #pragma once\n#if defined(_MSC_VER) && (_MSC_VER >= 1020)\n#pragma once\n#endif\n\n#include <libtbag\/config.h>\n#include <libtbag\/predef.hpp>\n\n\/\/ -------------------\nNAMESPACE_LIBTBAG_OPEN\n\/\/ -------------------\n\nnamespace math {\n\n} \/\/ namespace math\n\n\/\/ --------------------\nNAMESPACE_LIBTBAG_CLOSE\n\/\/ --------------------\n\n#endif \/\/ __INCLUDE_LIBTBAG__LIBTBAG_MATH_LAWOFCOSINES_HPP__\n\n<|endoftext|>"} {"text":"<commit_before>\/******************************************************************************\n * _ _____ __________ *\n * | | \/ \/ _ | \/ __\/_ __\/ Visibility *\n * | |\/ \/ __ |_\\ \\ \/ \/ Across *\n * |___\/_\/ |_\/___\/ \/_\/ Space and Time *\n * *\n * This file is part of VAST. It is subject to the license terms in the *\n * LICENSE file found in the top-level directory of this distribution and at *\n * http:\/\/vast.io\/license. No part of VAST, including this file, may be *\n * copied, modified, propagated, or distributed except according to the terms *\n * contained in the LICENSE file. *\n ******************************************************************************\/\n\n#include \"vast\/system\/index.hpp\"\n\n#define SUITE index\n#include \"test.hpp\"\n\n#include \"vast\/concept\/parseable\/to.hpp\"\n#include \"vast\/concept\/parseable\/vast\/expression.hpp\"\n#include \"vast\/concept\/printable\/std\/chrono.hpp\"\n#include \"vast\/concept\/printable\/vast\/event.hpp\"\n#include \"vast\/concept\/printable\/to_string.hpp\"\n#include \"vast\/detail\/spawn_container_source.hpp\"\n#include \"vast\/detail\/spawn_generator_source.hpp\"\n#include \"vast\/event.hpp\"\n#include \"vast\/ids.hpp\"\n#include \"vast\/query_options.hpp\"\n\n#include \"fixtures\/actor_system_and_events.hpp\"\n\nusing caf::after;\nusing std::chrono_literals::operator\"\"s;\n\nusing namespace vast;\nusing namespace std::chrono;\n\nnamespace {\n\nstatic constexpr size_t partition_size = 100;\n\nstatic constexpr size_t in_mem_partitions = 8;\n\nstatic constexpr size_t taste_count = 4;\n\nstatic constexpr size_t num_collectors = 1;\n\nconst timestamp epoch;\n\nusing interval = system::meta_index::interval;\n\nauto int_generator(int mod = std::numeric_limits<int>::max()) {\n int i = 0;\n return [i, mod]() mutable {\n auto result = event::make(i % mod, integer_type{}, i);\n result.timestamp(epoch + std::chrono::seconds(i));\n ++i;\n return result;\n };\n}\n\nstruct fixture : fixtures::deterministic_actor_system_and_events {\n fixture() {\n directory \/= \"index\";\n index = self->spawn(system::index, directory \/ \"index\", partition_size,\n in_mem_partitions, taste_count, num_collectors);\n }\n\n ~fixture() {\n anon_send_exit(index, caf::exit_reason::user_shutdown);\n }\n\n \/\/ Returns the state of the `index`.\n system::index_state& state() {\n return deref<caf::stateful_actor<system::index_state>>(index).state;\n }\n\n auto partition_intervals() {\n std::vector<interval> result;\n for (auto& kvp : state().part_index.partitions())\n result.emplace_back(kvp.second.range);\n std::sort(result.begin(), result.end(),\n [](auto& x, auto& y) { return x.from < y.from; });\n return result;\n }\n\n auto query(std::string_view expr) {\n self->send(index, unbox(to<expression>(expr)));\n run_exhaustively();\n std::tuple<uuid, size_t, size_t> result;\n self->receive(\n [&](uuid& query_id, size_t hits, size_t scheduled) {\n result = std::tie(query_id, hits, scheduled);\n },\n after(0s) >> [&] { FAIL(\"INDEX did not respond to query\"); });\n return result;\n }\n\n ids receive_result(const uuid& query_id, size_t hits, size_t scheduled) {\n if (hits == scheduled)\n CHECK_EQUAL(query_id, uuid::nil());\n else\n CHECK_NOT_EQUAL(query_id, uuid::nil());\n ids result;\n size_t collected = 0;\n auto fetch = [&](size_t chunk) {\n for (size_t i = 0; i < chunk; ++i)\n self->receive(\n [&](ids& sub_result) {\n ++collected;\n result |= sub_result;\n },\n after(0s) >> [&] {\n FAIL(\"missing sub result #\" << (i + 1) << \" in partition #\"\n << (collected + 1));\n }\n );\n };\n fetch(scheduled);\n while (collected < hits) {\n auto chunk = std::min(hits - collected, taste_count);\n self->send(index, query_id, chunk);\n run_exhaustively();\n fetch(chunk);\n }\n return result;\n }\n\n \/\/ Handle to the INDEX actor.\n caf::actor index;\n};\n\n} \/\/ namespace <anonymous>\n\nFIXTURE_SCOPE(index_tests, fixture)\n\nTEST(ingestion) {\n MESSAGE(\"ingest 1000 integers\");\n auto src = detail::spawn_generator_source(sys, 1000, int_generator(), index);\n run_exhaustively();\n MESSAGE(\"verify partition index\");\n REQUIRE_EQUAL(state().part_index.size(), 10u);\n auto intervals = partition_intervals();\n CHECK_EQUAL(intervals[0], interval(epoch, epoch + 99s));\n CHECK_EQUAL(intervals[1], interval(epoch + 100s, epoch + 199s));\n CHECK_EQUAL(intervals[2], interval(epoch + 200s, epoch + 299s));\n CHECK_EQUAL(intervals[3], interval(epoch + 300s, epoch + 399s));\n CHECK_EQUAL(intervals[4], interval(epoch + 400s, epoch + 499s));\n CHECK_EQUAL(intervals[5], interval(epoch + 500s, epoch + 599s));\n CHECK_EQUAL(intervals[6], interval(epoch + 600s, epoch + 699s));\n CHECK_EQUAL(intervals[7], interval(epoch + 700s, epoch + 799s));\n CHECK_EQUAL(intervals[8], interval(epoch + 800s, epoch + 899s));\n CHECK_EQUAL(intervals[9], interval(epoch + 900s, epoch + 999s));\n}\n\nTEST(one-shot integer query result) {\n MESSAGE(\"fill first \" << taste_count << \" partitions\");\n auto src = detail::spawn_generator_source(sys,\n partition_size * taste_count,\n int_generator(2), index);\n run_exhaustively();\n MESSAGE(\"query half of the values\");\n auto [query_id, hits, scheduled] = query(\":int == 1\");\n CHECK_EQUAL(query_id, uuid::nil());\n CHECK_EQUAL(hits, taste_count);\n CHECK_EQUAL(scheduled, taste_count);\n ids expected_result;\n for (size_t i = 0; i < (partition_size * taste_count) \/ 2; ++i) {\n expected_result.append_bit(false);\n expected_result.append_bit(true);\n }\n auto result = receive_result(query_id, hits, scheduled);\n CHECK_EQUAL(result, expected_result);\n}\n\nTEST(iterable integer query result) {\n MESSAGE(\"fill first \" << (taste_count * 3) << \" partitions\");\n auto src = detail::spawn_generator_source(sys,\n partition_size * taste_count * 3,\n int_generator(2), index);\n run_exhaustively();\n MESSAGE(\"query half of the values\");\n auto [query_id, hits, scheduled] = query(\":int == 1\");\n CHECK_NOT_EQUAL(query_id, uuid::nil());\n CHECK_EQUAL(hits, taste_count * 3);\n CHECK_EQUAL(scheduled, taste_count);\n ids expected_result;\n for (size_t i = 0; i < (partition_size * taste_count * 3) \/ 2; ++i) {\n expected_result.append_bit(false);\n expected_result.append_bit(true);\n }\n MESSAGE(\"collect results\");\n auto result = receive_result(query_id, hits, scheduled);\n CHECK_EQUAL(result, expected_result);\n}\n\nTEST(iterable bro conn log query result) {\n REQUIRE_EQUAL(bro_conn_log.size(), 8462u);\n MESSAGE(\"ingest conn.log\");\n detail::spawn_container_source(sys, bro_conn_log, index);\n run_exhaustively();\n MESSAGE(\"issue field type query\");\n {\n auto expected_result = make_ids({680, 682, 719, 720}, bro_conn_log.size());\n auto [query_id, hits, scheduled] = query(\":addr == 169.254.225.22\");\n auto result = receive_result(query_id, hits, scheduled);\n CHECK_EQUAL(rank(result), rank(expected_result));\n CHECK_EQUAL(result, expected_result);\n }\n MESSAGE(\"issue field name query\");\n {\n auto expected_result = make_ids({680, 682, 719, 720}, bro_conn_log.size());\n auto [query_id, hits, scheduled] = query(\"id.orig_h == 169.254.225.22\");\n auto result = receive_result(query_id, hits, scheduled);\n CHECK_EQUAL(rank(result), rank(expected_result));\n CHECK_EQUAL(result, expected_result);\n }\n MESSAGE(\"issue historical point query with conjunction\");\n {\n auto expected_result\n = make_ids({105, 150, 246, 257, 322, 419, 440, 480, 579, 595,\n 642, 766, 1224, 1251, 1751, 1762, 2670, 3661, 3682, 3820,\n 6345, 6777, 7677, 7843, 8002, 8286, 8325, 8354},\n bro_conn_log.size());\n auto [query_id, hits, scheduled] = query(\"service == \\\"http\\\" \"\n \"&& :addr == 212.227.96.110\");\n auto result = receive_result(query_id, hits, scheduled);\n CHECK_EQUAL(rank(expected_result), 28u);\n CHECK_EQUAL(rank(result), 28u);\n CHECK_EQUAL(result, expected_result);\n }\n}\n\nFIXTURE_SCOPE_END()\n<commit_msg>Add another (simpler) failing unit test<commit_after>\/******************************************************************************\n * _ _____ __________ *\n * | | \/ \/ _ | \/ __\/_ __\/ Visibility *\n * | |\/ \/ __ |_\\ \\ \/ \/ Across *\n * |___\/_\/ |_\/___\/ \/_\/ Space and Time *\n * *\n * This file is part of VAST. It is subject to the license terms in the *\n * LICENSE file found in the top-level directory of this distribution and at *\n * http:\/\/vast.io\/license. No part of VAST, including this file, may be *\n * copied, modified, propagated, or distributed except according to the terms *\n * contained in the LICENSE file. *\n ******************************************************************************\/\n\n#include \"vast\/system\/index.hpp\"\n\n#define SUITE index\n#include \"test.hpp\"\n\n#include \"vast\/concept\/parseable\/to.hpp\"\n#include \"vast\/concept\/parseable\/vast\/expression.hpp\"\n#include \"vast\/concept\/printable\/std\/chrono.hpp\"\n#include \"vast\/concept\/printable\/vast\/event.hpp\"\n#include \"vast\/concept\/printable\/to_string.hpp\"\n#include \"vast\/detail\/spawn_container_source.hpp\"\n#include \"vast\/detail\/spawn_generator_source.hpp\"\n#include \"vast\/event.hpp\"\n#include \"vast\/ids.hpp\"\n#include \"vast\/query_options.hpp\"\n\n#include \"fixtures\/actor_system_and_events.hpp\"\n\nusing caf::after;\nusing std::chrono_literals::operator\"\"s;\n\nusing namespace vast;\nusing namespace std::chrono;\n\nnamespace {\n\nstatic constexpr size_t partition_size = 100;\n\nstatic constexpr size_t in_mem_partitions = 8;\n\nstatic constexpr size_t taste_count = 4;\n\nstatic constexpr size_t num_collectors = 1;\n\nconst timestamp epoch;\n\nusing interval = system::meta_index::interval;\n\nauto int_generator(int mod = std::numeric_limits<int>::max()) {\n int i = 0;\n return [i, mod]() mutable {\n auto result = event::make(i % mod, integer_type{}, i);\n result.timestamp(epoch + std::chrono::seconds(i));\n ++i;\n return result;\n };\n}\n\nstruct fixture : fixtures::deterministic_actor_system_and_events {\n fixture() {\n directory \/= \"index\";\n index = self->spawn(system::index, directory \/ \"index\", partition_size,\n in_mem_partitions, taste_count, num_collectors);\n }\n\n ~fixture() {\n anon_send_exit(index, caf::exit_reason::user_shutdown);\n }\n\n \/\/ Returns the state of the `index`.\n system::index_state& state() {\n return deref<caf::stateful_actor<system::index_state>>(index).state;\n }\n\n auto partition_intervals() {\n std::vector<interval> result;\n for (auto& kvp : state().part_index.partitions())\n result.emplace_back(kvp.second.range);\n std::sort(result.begin(), result.end(),\n [](auto& x, auto& y) { return x.from < y.from; });\n return result;\n }\n\n auto query(std::string_view expr) {\n self->send(index, unbox(to<expression>(expr)));\n run_exhaustively();\n std::tuple<uuid, size_t, size_t> result;\n self->receive(\n [&](uuid& query_id, size_t hits, size_t scheduled) {\n result = std::tie(query_id, hits, scheduled);\n },\n after(0s) >> [&] { FAIL(\"INDEX did not respond to query\"); });\n return result;\n }\n\n ids receive_result(const uuid& query_id, size_t hits, size_t scheduled) {\n if (hits == scheduled)\n CHECK_EQUAL(query_id, uuid::nil());\n else\n CHECK_NOT_EQUAL(query_id, uuid::nil());\n ids result;\n size_t collected = 0;\n auto fetch = [&](size_t chunk) {\n for (size_t i = 0; i < chunk; ++i)\n self->receive(\n [&](ids& sub_result) {\n ++collected;\n result |= sub_result;\n },\n after(0s) >> [&] {\n FAIL(\"missing sub result #\" << (i + 1) << \" in partition #\"\n << (collected + 1));\n }\n );\n };\n fetch(scheduled);\n while (collected < hits) {\n auto chunk = std::min(hits - collected, taste_count);\n self->send(index, query_id, chunk);\n run_exhaustively();\n fetch(chunk);\n }\n return result;\n }\n\n \/\/ Handle to the INDEX actor.\n caf::actor index;\n};\n\n} \/\/ namespace <anonymous>\n\nFIXTURE_SCOPE(index_tests, fixture)\n\nTEST(ingestion) {\n MESSAGE(\"ingest 1000 integers\");\n auto src = detail::spawn_generator_source(sys, 1000, int_generator(), index);\n run_exhaustively();\n MESSAGE(\"verify partition index\");\n REQUIRE_EQUAL(state().part_index.size(), 10u);\n auto intervals = partition_intervals();\n CHECK_EQUAL(intervals[0], interval(epoch, epoch + 99s));\n CHECK_EQUAL(intervals[1], interval(epoch + 100s, epoch + 199s));\n CHECK_EQUAL(intervals[2], interval(epoch + 200s, epoch + 299s));\n CHECK_EQUAL(intervals[3], interval(epoch + 300s, epoch + 399s));\n CHECK_EQUAL(intervals[4], interval(epoch + 400s, epoch + 499s));\n CHECK_EQUAL(intervals[5], interval(epoch + 500s, epoch + 599s));\n CHECK_EQUAL(intervals[6], interval(epoch + 600s, epoch + 699s));\n CHECK_EQUAL(intervals[7], interval(epoch + 700s, epoch + 799s));\n CHECK_EQUAL(intervals[8], interval(epoch + 800s, epoch + 899s));\n CHECK_EQUAL(intervals[9], interval(epoch + 900s, epoch + 999s));\n}\n\nTEST(one-shot integer query result) {\n MESSAGE(\"fill first \" << taste_count << \" partitions\");\n auto src = detail::spawn_generator_source(sys,\n partition_size * taste_count,\n int_generator(2), index);\n run_exhaustively();\n MESSAGE(\"query half of the values\");\n auto [query_id, hits, scheduled] = query(\":int == 1\");\n CHECK_EQUAL(query_id, uuid::nil());\n CHECK_EQUAL(hits, taste_count);\n CHECK_EQUAL(scheduled, taste_count);\n ids expected_result;\n for (size_t i = 0; i < (partition_size * taste_count) \/ 2; ++i) {\n expected_result.append_bit(false);\n expected_result.append_bit(true);\n }\n auto result = receive_result(query_id, hits, scheduled);\n CHECK_EQUAL(result, expected_result);\n}\n\nTEST(iterable integer query result) {\n MESSAGE(\"fill first \" << (taste_count * 3) << \" partitions\");\n auto src = detail::spawn_generator_source(sys,\n partition_size * taste_count * 3,\n int_generator(2), index);\n run_exhaustively();\n MESSAGE(\"query half of the values\");\n auto [query_id, hits, scheduled] = query(\":int == 1\");\n CHECK_NOT_EQUAL(query_id, uuid::nil());\n CHECK_EQUAL(hits, taste_count * 3);\n CHECK_EQUAL(scheduled, taste_count);\n ids expected_result;\n for (size_t i = 0; i < (partition_size * taste_count * 3) \/ 2; ++i) {\n expected_result.append_bit(false);\n expected_result.append_bit(true);\n }\n MESSAGE(\"collect results\");\n auto result = receive_result(query_id, hits, scheduled);\n CHECK_EQUAL(result, expected_result);\n}\n\nTEST(iterable bro conn log query result) {\n REQUIRE_EQUAL(bro_conn_log.size(), 8462u);\n MESSAGE(\"ingest conn.log\");\n detail::spawn_container_source(sys, bro_conn_log, index);\n run_exhaustively();\n MESSAGE(\"issue field type query\");\n {\n auto expected_result = make_ids({680, 682, 719, 720}, bro_conn_log.size());\n auto [query_id, hits, scheduled] = query(\":addr == 169.254.225.22\");\n auto result = receive_result(query_id, hits, scheduled);\n CHECK_EQUAL(rank(result), rank(expected_result));\n CHECK_EQUAL(result, expected_result);\n }\n MESSAGE(\"issue field name queries\");\n {\n auto expected_result = make_ids({680, 682, 719, 720}, bro_conn_log.size());\n auto [query_id, hits, scheduled] = query(\"id.orig_h == 169.254.225.22\");\n auto result = receive_result(query_id, hits, scheduled);\n CHECK_EQUAL(rank(result), rank(expected_result));\n CHECK_EQUAL(result, expected_result);\n }\n {\n auto [query_id, hits, scheduled] = query(\"service == \\\"http\\\"\");\n auto result = receive_result(query_id, hits, scheduled);\n CHECK_EQUAL(rank(result), 2386u);\n }\n MESSAGE(\"issue historical point query with conjunction\");\n {\n auto expected_result\n = make_ids({105, 150, 246, 257, 322, 419, 440, 480, 579, 595,\n 642, 766, 1224, 1251, 1751, 1762, 2670, 3661, 3682, 3820,\n 6345, 6777, 7677, 7843, 8002, 8286, 8325, 8354},\n bro_conn_log.size());\n auto [query_id, hits, scheduled] = query(\"service == \\\"http\\\" \"\n \"&& :addr == 212.227.96.110\");\n auto result = receive_result(query_id, hits, scheduled);\n CHECK_EQUAL(rank(expected_result), 28u);\n CHECK_EQUAL(rank(result), 28u);\n CHECK_EQUAL(result, expected_result);\n }\n}\n\nFIXTURE_SCOPE_END()\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: thesdsp.hxx,v $\n *\n * $Revision: 1.4 $\n *\n * last change: $Author: vg $ $Date: 2007-05-25 12:25:59 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef _LINGUISTIC_THESDSP_HXX_\n#define _LINGUISTIC_THESDSP_HXX_\n\n#ifndef _COM_SUN_STAR_UNO_REFERENCE_H_\n#include <com\/sun\/star\/uno\/Reference.h>\n#endif\n#ifndef _COM_SUN_STAR_UNO_SEQUENCE_H_\n#include <com\/sun\/star\/uno\/Sequence.h>\n#endif\n#ifndef _COM_SUN_STAR_BEANS_XPROPERTYACCESS_HPP_\n#include <com\/sun\/star\/beans\/XPropertyAccess.hpp>\n#endif\n#ifndef _COM_SUN_STAR_BEANS_XPROPERTYCHANGELISTENER_HPP_\n#include <com\/sun\/star\/beans\/XPropertyChangeListener.hpp>\n#endif\n#ifndef _COM_SUN_STAR_LANG_XCOMPONENT_HPP_\n#include <com\/sun\/star\/lang\/XComponent.hpp>\n#endif\n#ifndef _COM_SUN_STAR_LANG_XINITIALIZATION_HPP_\n#include <com\/sun\/star\/lang\/XInitialization.hpp>\n#endif\n#ifndef _COM_SUN_STAR_LANG_XSERVICEDISPLAYNAME_HPP_\n#include <com\/sun\/star\/lang\/XServiceDisplayName.hpp>\n#endif\n\n#include <com\/sun\/star\/lang\/XServiceInfo.hpp>\n#include <com\/sun\/star\/linguistic2\/XThesaurus.hpp>\n\n#include <uno\/lbnames.h> \/\/ CPPU_CURRENT_LANGUAGE_BINDING_NAME macro, which specify the environment type\n#include <cppuhelper\/implbase1.hxx> \/\/ helper for implementations\n#include <cppuhelper\/implbase5.hxx> \/\/ helper for implementations\n\n#ifndef _CPPUHELPER_INTERFACECONTAINER_H_\n#include <cppuhelper\/interfacecontainer.h>\n#endif\n\n#include <vos\/mutex.hxx>\n\n#ifndef _TOOLS_TABLE_HXX\n#include <tools\/table.hxx>\n#endif\n\n#include \"lngopt.hxx\"\n\n\nclass LinguOptions;\n\nnamespace com { namespace sun { namespace star { namespace beans {\n class XPropertySet;\n}}}}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nclass SeqLangSvcEntry_Thes\n{\n friend class ThesaurusDispatcher;\n\n ::com::sun::star::uno::Sequence< ::rtl::OUString > aSvcImplNames;\n ::com::sun::star::uno::Sequence<\n ::com::sun::star::uno::Reference<\n ::com::sun::star::linguistic2::XThesaurus > > aSvcRefs;\n\/\/ INT16 nLang; \/\/used as key in the table\n SvcFlags aFlags;\n\npublic:\n SeqLangSvcEntry_Thes() {}\n SeqLangSvcEntry_Thes( const ::com::sun::star::uno::Sequence<\n ::rtl::OUString > &rSvcImplNames );\n ~SeqLangSvcEntry_Thes();\n\n BOOL IsAlreadyWarned() const { return aFlags.bAlreadyWarned != 0; }\n void SetAlreadyWarned(BOOL bVal) { aFlags.bAlreadyWarned = 0 != bVal; }\n BOOL IsDoWarnAgain() const { return aFlags.bDoWarnAgain != 0; }\n void SetDoWarnAgain(BOOL bVal) { aFlags.bDoWarnAgain = 0 != bVal; }\n};\n\n\n\nDECLARE_TABLE( ThesSvcList, SeqLangSvcEntry_Thes * )\n\nclass ThesaurusDispatcher :\n public cppu::WeakImplHelper1\n <\n ::com::sun::star::linguistic2::XThesaurus\n >,\n public LinguDispatcher\n{\n ThesSvcList aSvcList;\n\n ::com::sun::star::uno::Reference<\n ::com::sun::star::beans::XPropertySet > xPropSet;\n\n \/\/ disallow copy-constructor and assignment-operator for now\n ThesaurusDispatcher(const ThesaurusDispatcher &);\n ThesaurusDispatcher & operator = (const ThesaurusDispatcher &);\n\n inline ::com::sun::star::uno::Reference<\n ::com::sun::star::beans::XPropertySet >\n GetPropSet();\n\n void ClearSvcList();\n\npublic:\n ThesaurusDispatcher();\n virtual ~ThesaurusDispatcher();\n\n \/\/ XSupportedLocales\n virtual ::com::sun::star::uno::Sequence<\n ::com::sun::star::lang::Locale > SAL_CALL\n getLocales()\n throw(::com::sun::star::uno::RuntimeException);\n virtual sal_Bool SAL_CALL\n hasLocale( const ::com::sun::star::lang::Locale& aLocale )\n throw(::com::sun::star::uno::RuntimeException);\n\n \/\/ XThesaurus\n virtual ::com::sun::star::uno::Sequence<\n ::com::sun::star::uno::Reference<\n ::com::sun::star::linguistic2::XMeaning > > SAL_CALL\n queryMeanings( const ::rtl::OUString& aTerm,\n const ::com::sun::star::lang::Locale& aLocale,\n const ::com::sun::star::beans::PropertyValues& aProperties )\n throw(::com::sun::star::lang::IllegalArgumentException,\n ::com::sun::star::uno::RuntimeException);\n\n \/\/ LinguDispatcher\n virtual void\n SetServiceList( const ::com::sun::star::lang::Locale &rLocale,\n const ::com::sun::star::uno::Sequence<\n rtl::OUString > &rSvcImplNames );\n virtual ::com::sun::star::uno::Sequence< rtl::OUString >\n GetServiceList( const ::com::sun::star::lang::Locale &rLocale ) const;\n virtual DspType\n GetDspType() const;\n};\n\n\ninline ::com::sun::star::uno::Reference<\n ::com::sun::star::beans::XPropertySet >\n ThesaurusDispatcher::GetPropSet()\n{\n return xPropSet.is() ?\n xPropSet : xPropSet = linguistic::GetLinguProperties();\n}\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#endif\n\n<commit_msg>INTEGRATION: CWS changefileheader (1.4.40); FILE MERGED 2008\/04\/01 15:21:28 thb 1.4.40.3: #i85898# Stripping all external header guards 2008\/04\/01 12:31:46 thb 1.4.40.2: #i85898# Stripping all external header guards 2008\/03\/31 16:25:38 rt 1.4.40.1: #i87441# Change license header to LPGL v3.<commit_after>\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2008 by Sun Microsystems, Inc.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: thesdsp.hxx,v $\n * $Revision: 1.5 $\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * <http:\/\/www.openoffice.org\/license.html>\n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n#ifndef _LINGUISTIC_THESDSP_HXX_\n#define _LINGUISTIC_THESDSP_HXX_\n\n#include <com\/sun\/star\/uno\/Reference.h>\n#include <com\/sun\/star\/uno\/Sequence.h>\n#include <com\/sun\/star\/beans\/XPropertyAccess.hpp>\n#include <com\/sun\/star\/beans\/XPropertyChangeListener.hpp>\n#include <com\/sun\/star\/lang\/XComponent.hpp>\n#include <com\/sun\/star\/lang\/XInitialization.hpp>\n#include <com\/sun\/star\/lang\/XServiceDisplayName.hpp>\n\n#include <com\/sun\/star\/lang\/XServiceInfo.hpp>\n#include <com\/sun\/star\/linguistic2\/XThesaurus.hpp>\n\n#include <uno\/lbnames.h> \/\/ CPPU_CURRENT_LANGUAGE_BINDING_NAME macro, which specify the environment type\n#include <cppuhelper\/implbase1.hxx> \/\/ helper for implementations\n#include <cppuhelper\/implbase5.hxx> \/\/ helper for implementations\n#include <cppuhelper\/interfacecontainer.h>\n\n#include <vos\/mutex.hxx>\n#include <tools\/table.hxx>\n\n#include \"lngopt.hxx\"\n\n\nclass LinguOptions;\n\nnamespace com { namespace sun { namespace star { namespace beans {\n class XPropertySet;\n}}}}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nclass SeqLangSvcEntry_Thes\n{\n friend class ThesaurusDispatcher;\n\n ::com::sun::star::uno::Sequence< ::rtl::OUString > aSvcImplNames;\n ::com::sun::star::uno::Sequence<\n ::com::sun::star::uno::Reference<\n ::com::sun::star::linguistic2::XThesaurus > > aSvcRefs;\n\/\/ INT16 nLang; \/\/used as key in the table\n SvcFlags aFlags;\n\npublic:\n SeqLangSvcEntry_Thes() {}\n SeqLangSvcEntry_Thes( const ::com::sun::star::uno::Sequence<\n ::rtl::OUString > &rSvcImplNames );\n ~SeqLangSvcEntry_Thes();\n\n BOOL IsAlreadyWarned() const { return aFlags.bAlreadyWarned != 0; }\n void SetAlreadyWarned(BOOL bVal) { aFlags.bAlreadyWarned = 0 != bVal; }\n BOOL IsDoWarnAgain() const { return aFlags.bDoWarnAgain != 0; }\n void SetDoWarnAgain(BOOL bVal) { aFlags.bDoWarnAgain = 0 != bVal; }\n};\n\n\n\nDECLARE_TABLE( ThesSvcList, SeqLangSvcEntry_Thes * )\n\nclass ThesaurusDispatcher :\n public cppu::WeakImplHelper1\n <\n ::com::sun::star::linguistic2::XThesaurus\n >,\n public LinguDispatcher\n{\n ThesSvcList aSvcList;\n\n ::com::sun::star::uno::Reference<\n ::com::sun::star::beans::XPropertySet > xPropSet;\n\n \/\/ disallow copy-constructor and assignment-operator for now\n ThesaurusDispatcher(const ThesaurusDispatcher &);\n ThesaurusDispatcher & operator = (const ThesaurusDispatcher &);\n\n inline ::com::sun::star::uno::Reference<\n ::com::sun::star::beans::XPropertySet >\n GetPropSet();\n\n void ClearSvcList();\n\npublic:\n ThesaurusDispatcher();\n virtual ~ThesaurusDispatcher();\n\n \/\/ XSupportedLocales\n virtual ::com::sun::star::uno::Sequence<\n ::com::sun::star::lang::Locale > SAL_CALL\n getLocales()\n throw(::com::sun::star::uno::RuntimeException);\n virtual sal_Bool SAL_CALL\n hasLocale( const ::com::sun::star::lang::Locale& aLocale )\n throw(::com::sun::star::uno::RuntimeException);\n\n \/\/ XThesaurus\n virtual ::com::sun::star::uno::Sequence<\n ::com::sun::star::uno::Reference<\n ::com::sun::star::linguistic2::XMeaning > > SAL_CALL\n queryMeanings( const ::rtl::OUString& aTerm,\n const ::com::sun::star::lang::Locale& aLocale,\n const ::com::sun::star::beans::PropertyValues& aProperties )\n throw(::com::sun::star::lang::IllegalArgumentException,\n ::com::sun::star::uno::RuntimeException);\n\n \/\/ LinguDispatcher\n virtual void\n SetServiceList( const ::com::sun::star::lang::Locale &rLocale,\n const ::com::sun::star::uno::Sequence<\n rtl::OUString > &rSvcImplNames );\n virtual ::com::sun::star::uno::Sequence< rtl::OUString >\n GetServiceList( const ::com::sun::star::lang::Locale &rLocale ) const;\n virtual DspType\n GetDspType() const;\n};\n\n\ninline ::com::sun::star::uno::Reference<\n ::com::sun::star::beans::XPropertySet >\n ThesaurusDispatcher::GetPropSet()\n{\n return xPropSet.is() ?\n xPropSet : xPropSet = linguistic::GetLinguProperties();\n}\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#endif\n\n<|endoftext|>"} {"text":"<commit_before>\/* vim: set sw=4 sts=4 et foldmethod=syntax : *\/\n\n#include <max_clique\/dbmcsa_max_clique.hh>\n#include <max_clique\/colourise.hh>\n#include <max_clique\/print_incumbent.hh>\n#include <graph\/degree_sort.hh>\n#include <graph\/min_width_sort.hh>\n\n#include <algorithm>\n\nusing namespace parasols;\n\nnamespace\n{\n template <unsigned size_>\n struct Defer\n {\n std::array<unsigned, size_ * bits_per_word> p_order;\n std::array<unsigned, size_ * bits_per_word> colours;\n FixedBitSet<size_> c;\n FixedBitSet<size_> p;\n std::vector<int> positions;\n };\n\n template <unsigned size_>\n auto expand(\n const FixedBitGraph<size_> & graph,\n const std::vector<int> & o, \/\/ vertex ordering\n const std::array<unsigned, size_ * bits_per_word> & p_order,\n const std::array<unsigned, size_ * bits_per_word> & colours,\n FixedBitSet<size_> & c, \/\/ current candidate clique\n FixedBitSet<size_> & p, \/\/ potential additions\n MaxCliqueResult & result,\n const MaxCliqueParams & params,\n std::vector<int> & positions,\n bool already_split\n ) -> void\n {\n auto c_popcount = c.popcount();\n int n = p.popcount() - 1;\n\n \/\/ bound, timeout or early exit?\n if (c_popcount + colours[n] <= result.size || result.size >= params.stop_after_finding || params.abort.load())\n return;\n\n auto v = p_order[n];\n ++positions.back();\n\n \/\/ consider taking v\n c.set(v);\n ++c_popcount;\n\n \/\/ filter p to contain vertices adjacent to v\n FixedBitSet<size_> new_p = p;\n graph.intersect_with_row(v, new_p);\n\n if (new_p.empty()) {\n \/\/ potential new best\n if (c_popcount > result.size) {\n result.size = c_popcount;\n result.members.clear();\n for (int i = 0 ; i < graph.size() ; ++i)\n if (c.test(i))\n result.members.insert(o[i]);\n\n print_incumbent(params, c_popcount, positions);\n }\n }\n else {\n \/\/ get our coloured vertices\n ++result.nodes;\n std::array<unsigned, size_ * bits_per_word> new_p_order, new_colours;\n colourise<size_>(graph, new_p, new_p_order, new_colours);\n positions.push_back(0);\n expand<size_>(graph, o, new_p_order, new_colours, c, new_p, result, params, positions, false);\n positions.pop_back();\n }\n\n if (! already_split) {\n \/\/ now consider not taking v\n c.unset(v);\n p.unset(v);\n --c_popcount;\n\n if (n > 0) {\n expand<size_>(graph, o, p_order, colours, c, p, result, params, positions, false);\n }\n }\n }\n\n template <MaxCliqueOrder order_, unsigned size_>\n auto dbmcsa(const Graph & graph, const MaxCliqueParams & params) -> MaxCliqueResult\n {\n MaxCliqueResult result;\n result.size = params.initial_bound;\n\n std::vector<int> o(graph.size()); \/\/ vertex ordering\n\n FixedBitSet<size_> c; \/\/ current candidate clique\n c.resize(graph.size());\n\n FixedBitSet<size_> p; \/\/ potential additions\n p.resize(graph.size());\n p.set_all();\n\n \/\/ populate our order with every vertex initially\n std::iota(o.begin(), o.end(), 0);\n\n switch (order_) {\n case MaxCliqueOrder::Degree:\n degree_sort(graph, o, false);\n break;\n case MaxCliqueOrder::MinWidth:\n min_width_sort(graph, o, false);\n break;\n case MaxCliqueOrder::ExDegree:\n exdegree_sort(graph, o, false);\n break;\n case MaxCliqueOrder::DynExDegree:\n dynexdegree_sort(graph, o, false);\n break;\n }\n\n \/\/ re-encode graph as a bit graph\n FixedBitGraph<size_> bit_graph;\n bit_graph.resize(graph.size());\n\n for (int i = 0 ; i < graph.size() ; ++i)\n for (int j = 0 ; j < graph.size() ; ++j)\n if (graph.adjacent(o[i], o[j]))\n bit_graph.add_edge(i, j);\n\n std::vector<int> positions;\n positions.reserve(graph.size());\n positions.push_back(0);\n\n \/\/ initial ordering\n ++result.nodes;\n std::array<unsigned, size_ * bits_per_word> new_p_order, new_colours;\n colourise<size_>(bit_graph, p, new_p_order, new_colours);\n\n \/\/ first job\n Defer<size_> next_job{ new_p_order, new_colours, c, p, positions };\n\n \/\/ go!\n while (! next_job.p.empty()) {\n \/\/ split\n Defer<size_> job = next_job;\n\n ++next_job.positions.back();\n auto v = next_job.p_order[next_job.p.popcount() - 1];\n next_job.c.unset(v);\n next_job.p.unset(v);\n\n expand<size_>(bit_graph, o, job.p_order, job.colours, job.c, job.p, result, params, job.positions, true);\n }\n\n return result;\n }\n}\n\ntemplate <MaxCliqueOrder order_>\nauto parasols::dbmcsa_max_clique(const Graph & graph, const MaxCliqueParams & params) -> MaxCliqueResult\n{\n \/* This is pretty horrible: in order to avoid dynamic allocation, select\n * the appropriate specialisation for our graph's size. *\/\n static_assert(max_graph_words == 1024, \"Need to update here if max_graph_size is changed.\");\n if (graph.size() < bits_per_word)\n return dbmcsa<order_, 1>(graph, params);\n else if (graph.size() < 2 * bits_per_word)\n return dbmcsa<order_, 2>(graph, params);\n else if (graph.size() < 4 * bits_per_word)\n return dbmcsa<order_, 4>(graph, params);\n else if (graph.size() < 8 * bits_per_word)\n return dbmcsa<order_, 8>(graph, params);\n else if (graph.size() < 16 * bits_per_word)\n return dbmcsa<order_, 16>(graph, params);\n else if (graph.size() < 32 * bits_per_word)\n return dbmcsa<order_, 32>(graph, params);\n else if (graph.size() < 64 * bits_per_word)\n return dbmcsa<order_, 64>(graph, params);\n else if (graph.size() < 128 * bits_per_word)\n return dbmcsa<order_, 128>(graph, params);\n else if (graph.size() < 256 * bits_per_word)\n return dbmcsa<order_, 256>(graph, params);\n else if (graph.size() < 512 * bits_per_word)\n return dbmcsa<order_, 512>(graph, params);\n else if (graph.size() < 1024 * bits_per_word)\n return dbmcsa<order_, 1024>(graph, params);\n else\n throw GraphTooBig();\n}\n\ntemplate auto parasols::dbmcsa_max_clique<MaxCliqueOrder::Degree>(const Graph &, const MaxCliqueParams &) -> MaxCliqueResult;\ntemplate auto parasols::dbmcsa_max_clique<MaxCliqueOrder::MinWidth>(const Graph &, const MaxCliqueParams &) -> MaxCliqueResult;\ntemplate auto parasols::dbmcsa_max_clique<MaxCliqueOrder::ExDegree>(const Graph &, const MaxCliqueParams &) -> MaxCliqueResult;\ntemplate auto parasols::dbmcsa_max_clique<MaxCliqueOrder::DynExDegree>(const Graph &, const MaxCliqueParams &) -> MaxCliqueResult;\n\n<commit_msg>Threaded goodness<commit_after>\/* vim: set sw=4 sts=4 et foldmethod=syntax : *\/\n\n#include <max_clique\/dbmcsa_max_clique.hh>\n#include <max_clique\/colourise.hh>\n#include <max_clique\/print_incumbent.hh>\n#include <graph\/degree_sort.hh>\n#include <graph\/min_width_sort.hh>\n#include <threads\/atomic_incumbent.hh>\n\n#include <algorithm>\n#include <thread>\n#include <mutex>\n\nusing namespace parasols;\n\nnamespace\n{\n template <unsigned size_>\n struct Defer\n {\n std::array<unsigned, size_ * bits_per_word> p_order;\n std::array<unsigned, size_ * bits_per_word> colours;\n FixedBitSet<size_> c;\n FixedBitSet<size_> p;\n std::vector<int> positions;\n };\n\n template <unsigned size_>\n auto found_possible_new_best(\n const FixedBitGraph<size_> & graph,\n const std::vector<int> & o,\n const FixedBitSet<size_> & c,\n int c_popcount,\n const MaxCliqueParams & params,\n MaxCliqueResult & result,\n AtomicIncumbent & best_anywhere,\n const std::vector<int> & position) -> void\n {\n if (best_anywhere.update(c_popcount)) {\n result.size = c_popcount;\n result.members.clear();\n for (int i = 0 ; i < graph.size() ; ++i)\n if (c.test(i))\n result.members.insert(o[i]);\n print_incumbent(params, result.size, position);\n }\n }\n\n auto bound(unsigned c_popcount, unsigned cn, const MaxCliqueParams & params, AtomicIncumbent & best_anywhere) -> bool\n {\n unsigned best_anywhere_value = best_anywhere.get();\n return (c_popcount + cn <= best_anywhere_value || best_anywhere_value >= params.stop_after_finding);\n }\n\n template <unsigned size_>\n auto expand(\n const FixedBitGraph<size_> & graph,\n const std::vector<int> & o, \/\/ vertex ordering\n const std::array<unsigned, size_ * bits_per_word> & p_order,\n const std::array<unsigned, size_ * bits_per_word> & colours,\n FixedBitSet<size_> & c, \/\/ current candidate clique\n FixedBitSet<size_> & p, \/\/ potential additions\n MaxCliqueResult & result,\n AtomicIncumbent & best_anywhere,\n const MaxCliqueParams & params,\n std::vector<int> & positions,\n bool already_split\n ) -> void\n {\n auto c_popcount = c.popcount();\n int n = p.popcount() - 1;\n\n \/\/ bound, timeout or early exit?\n if (bound(c_popcount, colours[n], params, best_anywhere) || params.abort.load())\n return;\n\n auto v = p_order[n];\n ++positions.back();\n\n \/\/ consider taking v\n c.set(v);\n ++c_popcount;\n\n \/\/ filter p to contain vertices adjacent to v\n FixedBitSet<size_> new_p = p;\n graph.intersect_with_row(v, new_p);\n\n if (new_p.empty()) {\n found_possible_new_best(graph, o, c, c_popcount, params, result, best_anywhere, positions);\n }\n else {\n \/\/ get our coloured vertices\n ++result.nodes;\n std::array<unsigned, size_ * bits_per_word> new_p_order, new_colours;\n colourise<size_>(graph, new_p, new_p_order, new_colours);\n positions.push_back(0);\n expand<size_>(graph, o, new_p_order, new_colours, c, new_p, result, best_anywhere, params, positions, false);\n positions.pop_back();\n }\n\n if (! already_split) {\n \/\/ now consider not taking v\n c.unset(v);\n p.unset(v);\n --c_popcount;\n\n if (n > 0) {\n expand<size_>(graph, o, p_order, colours, c, p, result, best_anywhere, params, positions, false);\n }\n }\n }\n\n template <MaxCliqueOrder order_, unsigned size_>\n auto dbmcsa(const Graph & graph, const MaxCliqueParams & params) -> MaxCliqueResult\n {\n MaxCliqueResult result;\n std::mutex result_mutex;\n result.size = params.initial_bound;\n\n AtomicIncumbent best_anywhere; \/\/ global incumbent\n best_anywhere.update(params.initial_bound);\n\n std::vector<int> o(graph.size()); \/\/ vertex ordering\n\n FixedBitSet<size_> c; \/\/ current candidate clique\n c.resize(graph.size());\n\n FixedBitSet<size_> p; \/\/ potential additions\n p.resize(graph.size());\n p.set_all();\n\n \/\/ populate our order with every vertex initially\n std::iota(o.begin(), o.end(), 0);\n\n switch (order_) {\n case MaxCliqueOrder::Degree:\n degree_sort(graph, o, false);\n break;\n case MaxCliqueOrder::MinWidth:\n min_width_sort(graph, o, false);\n break;\n case MaxCliqueOrder::ExDegree:\n exdegree_sort(graph, o, false);\n break;\n case MaxCliqueOrder::DynExDegree:\n dynexdegree_sort(graph, o, false);\n break;\n }\n\n \/\/ re-encode graph as a bit graph\n FixedBitGraph<size_> bit_graph;\n bit_graph.resize(graph.size());\n\n for (int i = 0 ; i < graph.size() ; ++i)\n for (int j = 0 ; j < graph.size() ; ++j)\n if (graph.adjacent(o[i], o[j]))\n bit_graph.add_edge(i, j);\n\n std::vector<int> positions;\n positions.reserve(graph.size());\n positions.push_back(0);\n\n \/\/ initial ordering\n ++result.nodes;\n std::array<unsigned, size_ * bits_per_word> new_p_order, new_colours;\n colourise<size_>(bit_graph, p, new_p_order, new_colours);\n\n \/\/ first job\n std::mutex next_job_mutex;\n Defer<size_> next_job{ new_p_order, new_colours, c, p, positions };\n\n std::list<std::thread> threads; \/\/ workers\n for (unsigned i = 0 ; i < params.n_threads ; ++i) {\n threads.push_back(std::thread([&, i] {\n\n auto start_time = std::chrono::steady_clock::now(); \/\/ local start time\n MaxCliqueResult tr; \/\/ local result\n\n while (true) {\n Defer<size_> job;\n {\n std::unique_lock<std::mutex> guard(next_job_mutex);\n if (next_job.p.empty())\n break;\n\n \/\/ split\n job = next_job;\n\n ++next_job.positions.back();\n auto v = next_job.p_order[next_job.p.popcount() - 1];\n next_job.c.unset(v);\n next_job.p.unset(v);\n }\n\n expand<size_>(bit_graph, o, job.p_order, job.colours, job.c, job.p, tr, best_anywhere, params, job.positions, true);\n }\n\n auto overall_time = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now() - start_time);\n\n \/\/ merge results\n {\n std::unique_lock<std::mutex> guard(result_mutex);\n result.merge(tr);\n result.times.push_back(overall_time);\n }\n }));\n }\n\n for (auto & t : threads)\n t.join();\n\n return result;\n }\n}\n\ntemplate <MaxCliqueOrder order_>\nauto parasols::dbmcsa_max_clique(const Graph & graph, const MaxCliqueParams & params) -> MaxCliqueResult\n{\n \/* This is pretty horrible: in order to avoid dynamic allocation, select\n * the appropriate specialisation for our graph's size. *\/\n static_assert(max_graph_words == 1024, \"Need to update here if max_graph_size is changed.\");\n if (graph.size() < bits_per_word)\n return dbmcsa<order_, 1>(graph, params);\n else if (graph.size() < 2 * bits_per_word)\n return dbmcsa<order_, 2>(graph, params);\n else if (graph.size() < 4 * bits_per_word)\n return dbmcsa<order_, 4>(graph, params);\n else if (graph.size() < 8 * bits_per_word)\n return dbmcsa<order_, 8>(graph, params);\n else if (graph.size() < 16 * bits_per_word)\n return dbmcsa<order_, 16>(graph, params);\n else if (graph.size() < 32 * bits_per_word)\n return dbmcsa<order_, 32>(graph, params);\n else if (graph.size() < 64 * bits_per_word)\n return dbmcsa<order_, 64>(graph, params);\n else if (graph.size() < 128 * bits_per_word)\n return dbmcsa<order_, 128>(graph, params);\n else if (graph.size() < 256 * bits_per_word)\n return dbmcsa<order_, 256>(graph, params);\n else if (graph.size() < 512 * bits_per_word)\n return dbmcsa<order_, 512>(graph, params);\n else if (graph.size() < 1024 * bits_per_word)\n return dbmcsa<order_, 1024>(graph, params);\n else\n throw GraphTooBig();\n}\n\ntemplate auto parasols::dbmcsa_max_clique<MaxCliqueOrder::Degree>(const Graph &, const MaxCliqueParams &) -> MaxCliqueResult;\ntemplate auto parasols::dbmcsa_max_clique<MaxCliqueOrder::MinWidth>(const Graph &, const MaxCliqueParams &) -> MaxCliqueResult;\ntemplate auto parasols::dbmcsa_max_clique<MaxCliqueOrder::ExDegree>(const Graph &, const MaxCliqueParams &) -> MaxCliqueResult;\ntemplate auto parasols::dbmcsa_max_clique<MaxCliqueOrder::DynExDegree>(const Graph &, const MaxCliqueParams &) -> MaxCliqueResult;\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2010-2013 RethinkDB, all rights reserved.\n#include \"rdb_protocol\/datum.hpp\"\n#include \"rdb_protocol\/error.hpp\"\n#include \"rdb_protocol\/validate.hpp\"\n#include \"utils.hpp\"\n\n\n#define check_has(pb, has_field, field) do { \\\n auto const &check_has_tmp = (pb); \\\n rcheck_toplevel( \\\n check_has_tmp.has_field(), \\\n ql::base_exc_t::GENERIC, \\\n strprintf(\"MALFORMED PROTOBUF (missing field `%s`):\\n%s\", \\\n (field), check_has_tmp.DebugString().c_str())); \\\n } while (0)\n\n#define check_not_has(pb, has_field, field) do { \\\n auto const &check_not_has_tmp = (pb); \\\n rcheck_toplevel( \\\n !check_not_has_tmp.has_field(), \\\n ql::base_exc_t::GENERIC, \\\n strprintf(\"MALFORMED PROTOBUF (spurious field `%s`):\\n%s\", \\\n (field), \\\n check_not_has_tmp.DebugString().c_str())); \\\n } while (0)\n\n#define check_size(expected_size, pb, field_size, field) do { \\\n auto const &check_size_tmp = (pb); \\\n const int check_size_expected = (expected_size); \\\n rcheck_toplevel( \\\n check_size_tmp.field_size() == check_size_expected, \\\n ql::base_exc_t::GENERIC, \\\n strprintf(\"MALFORMED PROTOBUF (expected field `%s` \" \\\n \"to have size %d):\\n%s\", \\\n (field), check_size_expected, \\\n check_size_tmp.DebugString().c_str())); \\\n } while(0)\n\n#define check_empty(pb, field_size, field) check_size(0, pb, field_size, field)\n\n#define check_type(pbname, pb) do { \\\n check_has(pb, has_type, \"type\"); \\\n rcheck_toplevel( \\\n pbname##_##pbname##Type_IsValid(pb.type()), \\\n ql::base_exc_t::GENERIC, \\\n strprintf(\"MALFORMED PROTOBUF (Illegal \" #pbname \" type %d).\", \\\n pb.type())); \\\n } while (0)\n\nvoid validate_pb(const Query &q) {\n check_type(Query, q);\n if (q.type() == Query::START) {\n check_has(q, has_query, \"query\");\n validate_pb(q.query());\n } else {\n check_not_has(q, has_query, \"query\");\n }\n check_has(q, has_token, \"token\");\n for (int i = 0; i < q.global_optargs_size(); ++i) {\n validate_pb(q.global_optargs(i).val());\n }\n}\n\nvoid validate_pb(const Query::AssocPair &ap) {\n check_has(ap, has_key, \"key\");\n check_has(ap, has_val, \"val\");\n validate_pb(ap.val());\n}\n\nvoid validate_pb(const Frame &f) {\n check_type(Frame, f);\n if (f.type() == Frame::POS) {\n check_has(f, has_pos, \"pos\");\n } else {\n check_has(f, has_opt, \"opt\");\n }\n}\n\nvoid validate_pb(const Backtrace &bt) {\n for (int i = 0; i < bt.frames_size(); ++i) {\n validate_pb(bt.frames(i));\n }\n}\n\nvoid validate_pb(const Response &r) {\n check_type(Response, r);\n if (r.type() == Response::SUCCESS_ATOM\n || r.type() == Response::SUCCESS_SEQUENCE\n || r.type() == Response::SUCCESS_PARTIAL) {\n check_not_has(r, has_backtrace, \"backtrace\");\n } else {\n check_has(r, has_backtrace, \"backtrace\");\n }\n check_has(r, has_token, \"token\");\n for (int i = 0; i < r.response_size(); ++i) {\n validate_pb(r.response(i));\n }\n}\n\nvoid validate_pb(const Datum &d) {\n check_type(Datum, d);\n if (d.type() == Datum::R_BOOL) {\n check_has(d, has_r_bool, \"r_bool\");\n } else {\n check_not_has(d, has_r_bool, \"r_bool\");\n }\n if (d.type() == Datum::R_NUM) {\n check_has(d, has_r_num, \"r_num\");\n } else {\n check_not_has(d, has_r_num, \"r_num\");\n }\n if (d.type() == Datum::R_STR || d.type() == Datum::R_JSON) {\n check_has(d, has_r_str, \"r_str\");\n } else {\n check_not_has(d, has_r_str, \"r_str\");\n }\n if (d.type() == Datum::R_ARRAY) {\n for (int i = 0; i < d.r_array_size(); ++i) {\n validate_pb(d.r_array(i));\n }\n } else {\n check_empty(d, r_array_size, \"r_array\");\n }\n if (d.type() == Datum::R_OBJECT) {\n for (int i = 0; i < d.r_object_size(); ++i) {\n validate_pb(d.r_object(i));\n }\n } else {\n check_empty(d, r_object_size, \"r_object\");\n }\n}\n\nvoid validate_pb(const Datum::AssocPair &ap) {\n check_has(ap, has_key, \"key\");\n check_has(ap, has_val, \"val\");\n validate_pb(ap.val());\n}\n\nvoid validate_var_term(const Term &t) {\n check_empty(t, optargs_size, \"optargs\");\n check_size(1, t, args_size, \"args\");\n const Term &arg0 = t.args(0);\n rcheck_toplevel(arg0.type() == Term::DATUM && arg0.has_datum() &&\n arg0.datum().type() == Datum::R_NUM &&\n arg0.datum().has_r_num(),\n ql::base_exc_t::GENERIC,\n strprintf(\"MALFORMED PROTOBUF (expected VAR term \"\n \"to have DATUM of type R_NUM):\\n%s\",\n t.DebugString().c_str()));\n double number = arg0.datum().r_num();\n int64_t i;\n if (!ql::number_as_integer(number, &i) || i < 0) {\n rfail_toplevel(ql::base_exc_t::GENERIC,\n \"MALFORMED PROTOBUF (VAR term should have \"\n \"a positive integer value):\\n%s\",\n t.DebugString().c_str());\n }\n}\n\nvoid validate_pb(const Term &t) {\n check_type(Term, t);\n if (t.type() == Term::DATUM) {\n check_has(t, has_datum, \"datum\");\n } else {\n check_not_has(t, has_datum, \"datum\");\n if (t.type() == Term::VAR) {\n validate_var_term(t);\n return;\n }\n }\n for (int i = 0; i < t.args_size(); ++i) {\n validate_pb(t.args(i));\n }\n for (int i = 0; i < t.optargs_size(); ++i) {\n validate_pb(t.optargs(i));\n }\n}\n\nvoid validate_pb(const Term::AssocPair &ap) {\n check_has(ap, has_key, \"key\");\n check_has(ap, has_val, \"val\");\n validate_pb(ap.val());\n}\n\nstatic std::set<std::string> acceptable_keys = {\n \"use_outdated\",\n \"noreply\",\n \"time_format\",\n \"profile\",\n \"durability\",\n \"group_format\",\n \"binary_format\",\n \"array_limit\",\n \"identifier_format\",\n \"min_batch_rows\",\n \"max_batch_rows\",\n \"max_batch_bytes\",\n \"max_batch_seconds\",\n \"first_batch_scaledown_factor\",\n};\n\nvoid validate_optargs(const Query &q) {\n for (int i = 0; i < q.global_optargs_size(); ++i) {\n rcheck_toplevel(\n acceptable_keys.find(q.global_optargs(i).key()) != acceptable_keys.end(),\n ql::base_exc_t::GENERIC,\n strprintf(\"MALFORMED QUERY (global optarg `%s` is not recognized)\",\n q.global_optargs(i).key().c_str()));\n }\n}\n<commit_msg>Add `right_bound` to the list.<commit_after>\/\/ Copyright 2010-2013 RethinkDB, all rights reserved.\n#include \"rdb_protocol\/datum.hpp\"\n#include \"rdb_protocol\/error.hpp\"\n#include \"rdb_protocol\/validate.hpp\"\n#include \"utils.hpp\"\n\n\n#define check_has(pb, has_field, field) do { \\\n auto const &check_has_tmp = (pb); \\\n rcheck_toplevel( \\\n check_has_tmp.has_field(), \\\n ql::base_exc_t::GENERIC, \\\n strprintf(\"MALFORMED PROTOBUF (missing field `%s`):\\n%s\", \\\n (field), check_has_tmp.DebugString().c_str())); \\\n } while (0)\n\n#define check_not_has(pb, has_field, field) do { \\\n auto const &check_not_has_tmp = (pb); \\\n rcheck_toplevel( \\\n !check_not_has_tmp.has_field(), \\\n ql::base_exc_t::GENERIC, \\\n strprintf(\"MALFORMED PROTOBUF (spurious field `%s`):\\n%s\", \\\n (field), \\\n check_not_has_tmp.DebugString().c_str())); \\\n } while (0)\n\n#define check_size(expected_size, pb, field_size, field) do { \\\n auto const &check_size_tmp = (pb); \\\n const int check_size_expected = (expected_size); \\\n rcheck_toplevel( \\\n check_size_tmp.field_size() == check_size_expected, \\\n ql::base_exc_t::GENERIC, \\\n strprintf(\"MALFORMED PROTOBUF (expected field `%s` \" \\\n \"to have size %d):\\n%s\", \\\n (field), check_size_expected, \\\n check_size_tmp.DebugString().c_str())); \\\n } while(0)\n\n#define check_empty(pb, field_size, field) check_size(0, pb, field_size, field)\n\n#define check_type(pbname, pb) do { \\\n check_has(pb, has_type, \"type\"); \\\n rcheck_toplevel( \\\n pbname##_##pbname##Type_IsValid(pb.type()), \\\n ql::base_exc_t::GENERIC, \\\n strprintf(\"MALFORMED PROTOBUF (Illegal \" #pbname \" type %d).\", \\\n pb.type())); \\\n } while (0)\n\nvoid validate_pb(const Query &q) {\n check_type(Query, q);\n if (q.type() == Query::START) {\n check_has(q, has_query, \"query\");\n validate_pb(q.query());\n } else {\n check_not_has(q, has_query, \"query\");\n }\n check_has(q, has_token, \"token\");\n for (int i = 0; i < q.global_optargs_size(); ++i) {\n validate_pb(q.global_optargs(i).val());\n }\n}\n\nvoid validate_pb(const Query::AssocPair &ap) {\n check_has(ap, has_key, \"key\");\n check_has(ap, has_val, \"val\");\n validate_pb(ap.val());\n}\n\nvoid validate_pb(const Frame &f) {\n check_type(Frame, f);\n if (f.type() == Frame::POS) {\n check_has(f, has_pos, \"pos\");\n } else {\n check_has(f, has_opt, \"opt\");\n }\n}\n\nvoid validate_pb(const Backtrace &bt) {\n for (int i = 0; i < bt.frames_size(); ++i) {\n validate_pb(bt.frames(i));\n }\n}\n\nvoid validate_pb(const Response &r) {\n check_type(Response, r);\n if (r.type() == Response::SUCCESS_ATOM\n || r.type() == Response::SUCCESS_SEQUENCE\n || r.type() == Response::SUCCESS_PARTIAL) {\n check_not_has(r, has_backtrace, \"backtrace\");\n } else {\n check_has(r, has_backtrace, \"backtrace\");\n }\n check_has(r, has_token, \"token\");\n for (int i = 0; i < r.response_size(); ++i) {\n validate_pb(r.response(i));\n }\n}\n\nvoid validate_pb(const Datum &d) {\n check_type(Datum, d);\n if (d.type() == Datum::R_BOOL) {\n check_has(d, has_r_bool, \"r_bool\");\n } else {\n check_not_has(d, has_r_bool, \"r_bool\");\n }\n if (d.type() == Datum::R_NUM) {\n check_has(d, has_r_num, \"r_num\");\n } else {\n check_not_has(d, has_r_num, \"r_num\");\n }\n if (d.type() == Datum::R_STR || d.type() == Datum::R_JSON) {\n check_has(d, has_r_str, \"r_str\");\n } else {\n check_not_has(d, has_r_str, \"r_str\");\n }\n if (d.type() == Datum::R_ARRAY) {\n for (int i = 0; i < d.r_array_size(); ++i) {\n validate_pb(d.r_array(i));\n }\n } else {\n check_empty(d, r_array_size, \"r_array\");\n }\n if (d.type() == Datum::R_OBJECT) {\n for (int i = 0; i < d.r_object_size(); ++i) {\n validate_pb(d.r_object(i));\n }\n } else {\n check_empty(d, r_object_size, \"r_object\");\n }\n}\n\nvoid validate_pb(const Datum::AssocPair &ap) {\n check_has(ap, has_key, \"key\");\n check_has(ap, has_val, \"val\");\n validate_pb(ap.val());\n}\n\nvoid validate_var_term(const Term &t) {\n check_empty(t, optargs_size, \"optargs\");\n check_size(1, t, args_size, \"args\");\n const Term &arg0 = t.args(0);\n rcheck_toplevel(arg0.type() == Term::DATUM && arg0.has_datum() &&\n arg0.datum().type() == Datum::R_NUM &&\n arg0.datum().has_r_num(),\n ql::base_exc_t::GENERIC,\n strprintf(\"MALFORMED PROTOBUF (expected VAR term \"\n \"to have DATUM of type R_NUM):\\n%s\",\n t.DebugString().c_str()));\n double number = arg0.datum().r_num();\n int64_t i;\n if (!ql::number_as_integer(number, &i) || i < 0) {\n rfail_toplevel(ql::base_exc_t::GENERIC,\n \"MALFORMED PROTOBUF (VAR term should have \"\n \"a positive integer value):\\n%s\",\n t.DebugString().c_str());\n }\n}\n\nvoid validate_pb(const Term &t) {\n check_type(Term, t);\n if (t.type() == Term::DATUM) {\n check_has(t, has_datum, \"datum\");\n } else {\n check_not_has(t, has_datum, \"datum\");\n if (t.type() == Term::VAR) {\n validate_var_term(t);\n return;\n }\n }\n for (int i = 0; i < t.args_size(); ++i) {\n validate_pb(t.args(i));\n }\n for (int i = 0; i < t.optargs_size(); ++i) {\n validate_pb(t.optargs(i));\n }\n}\n\nvoid validate_pb(const Term::AssocPair &ap) {\n check_has(ap, has_key, \"key\");\n check_has(ap, has_val, \"val\");\n validate_pb(ap.val());\n}\n\nstatic std::set<std::string> acceptable_keys = {\n \"use_outdated\",\n \"noreply\",\n \"time_format\",\n \"profile\",\n \"durability\",\n \"group_format\",\n \"binary_format\",\n \"array_limit\",\n \"identifier_format\",\n \"right_bound\",\n\n \"min_batch_rows\",\n \"max_batch_rows\",\n \"max_batch_bytes\",\n \"max_batch_seconds\",\n \"first_batch_scaledown_factor\",\n};\n\nvoid validate_optargs(const Query &q) {\n for (int i = 0; i < q.global_optargs_size(); ++i) {\n rcheck_toplevel(\n acceptable_keys.find(q.global_optargs(i).key()) != acceptable_keys.end(),\n ql::base_exc_t::GENERIC,\n strprintf(\"MALFORMED QUERY (global optarg `%s` is not recognized)\",\n q.global_optargs(i).key().c_str()));\n }\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"gtest\/gtest.h\"\n#include \"dsb\/util.hpp\"\n#include <vector>\n\nusing namespace dsb::util;\n\nTEST(dsb_util, EncodeUint16) {\n char b[2] = { '\\xFF', '\\xFF' };\n\n EncodeUint16(0, b);\n EXPECT_EQ('\\x00', b[0]);\n EXPECT_EQ('\\x00', b[1]);\n\n EncodeUint16(65535, b);\n EXPECT_EQ('\\xFF', b[0]);\n EXPECT_EQ('\\xFF', b[1]);\n\n EncodeUint16(4608, b);\n EXPECT_EQ('\\x00', b[0]);\n EXPECT_EQ('\\x12', b[1]);\n\n EncodeUint16(63, b);\n EXPECT_EQ('\\x3F', b[0]);\n EXPECT_EQ('\\x00', b[1]);\n\n EncodeUint16(15238, b);\n EXPECT_EQ('\\x86', b[0]);\n EXPECT_EQ('\\x3B', b[1]);\n}\n\nTEST(dsb_util, DecodeUint16) {\n EXPECT_EQ( 0, DecodeUint16(\"\\x00\\x00\"));\n EXPECT_EQ(65535, DecodeUint16(\"\\xFF\\xFF\"));\n EXPECT_EQ( 4608, DecodeUint16(\"\\x00\\x12\"));\n EXPECT_EQ( 63, DecodeUint16(\"\\x3F\\x00\"));\n EXPECT_EQ(15238, DecodeUint16(\"\\x86\\x3B\"));\n}\n\nTEST(dsb_util, RandomUUID)\n{\n const auto u = RandomUUID();\n EXPECT_EQ(36U, u.size());\n EXPECT_NE(u, RandomUUID());\n}\n\nTEST(dsb_util, SwapOut_value)\n{\n int a = 123;\n int b = SwapOut(a, 456);\n EXPECT_EQ(456, a);\n EXPECT_EQ(123, b);\n int c = SwapOut(b);\n EXPECT_EQ(0, b);\n EXPECT_EQ(123, c);\n}\n\nTEST(dsb_util, SwapOut_class)\n{\n std::vector<int> a;\n a.push_back(123);\n const auto dataPtr = a.data();\n std::vector<int> r;\n r.push_back(456);\n r.push_back(789);\n\n std::vector<int> b = SwapOut(a, r);\n ASSERT_EQ(2U, a.size());\n EXPECT_EQ(456, a[0]);\n EXPECT_EQ(789, a[1]);\n\n \/\/ The following test is (most likely) not specified C++ behaviour, but\n \/\/ it would be a strange vector implementation that didn't implement a move\n \/\/ as a pointer move...\n EXPECT_EQ(1U, b.size());\n EXPECT_EQ(dataPtr, b.data());\n\n std::vector<int> c = SwapOut(b);\n EXPECT_TRUE(b.empty());\n EXPECT_EQ(1U, c.size());\n EXPECT_EQ(dataPtr, c.data());\n}\n\nTEST(dsb_util, OnScopeExit)\n{\n int i = 0;\n {\n auto setToOne = OnScopeExit([&i]() { i = 1; });\n EXPECT_EQ(0, i);\n }\n EXPECT_EQ(1, i);\n try {\n auto setToTwo = OnScopeExit([&i]() { i = 2; });\n EXPECT_EQ(1, i);\n throw 0;\n } catch (...) {\n EXPECT_EQ(2, i);\n i = 3;\n }\n EXPECT_EQ(3, i);\n}\n<commit_msg>Added some missing dsb::util tests<commit_after>#include \"gtest\/gtest.h\"\n#include \"dsb\/util.hpp\"\n#include <vector>\n#include \"boost\/filesystem.hpp\"\n\n\nusing namespace dsb::util;\n\nTEST(dsb_util, EncodeUint16) {\n char b[2] = { '\\xFF', '\\xFF' };\n\n EncodeUint16(0, b);\n EXPECT_EQ('\\x00', b[0]);\n EXPECT_EQ('\\x00', b[1]);\n\n EncodeUint16(65535, b);\n EXPECT_EQ('\\xFF', b[0]);\n EXPECT_EQ('\\xFF', b[1]);\n\n EncodeUint16(4608, b);\n EXPECT_EQ('\\x00', b[0]);\n EXPECT_EQ('\\x12', b[1]);\n\n EncodeUint16(63, b);\n EXPECT_EQ('\\x3F', b[0]);\n EXPECT_EQ('\\x00', b[1]);\n\n EncodeUint16(15238, b);\n EXPECT_EQ('\\x86', b[0]);\n EXPECT_EQ('\\x3B', b[1]);\n}\n\nTEST(dsb_util, DecodeUint16) {\n EXPECT_EQ( 0, DecodeUint16(\"\\x00\\x00\"));\n EXPECT_EQ(65535, DecodeUint16(\"\\xFF\\xFF\"));\n EXPECT_EQ( 4608, DecodeUint16(\"\\x00\\x12\"));\n EXPECT_EQ( 63, DecodeUint16(\"\\x3F\\x00\"));\n EXPECT_EQ(15238, DecodeUint16(\"\\x86\\x3B\"));\n}\n\nTEST(dsb_util, RandomUUID)\n{\n const auto u = RandomUUID();\n EXPECT_EQ(36U, u.size());\n EXPECT_NE(u, RandomUUID());\n}\n\nTEST(dsb_util, SwapOut_value)\n{\n int a = 123;\n int b = SwapOut(a, 456);\n EXPECT_EQ(456, a);\n EXPECT_EQ(123, b);\n int c = SwapOut(b);\n EXPECT_EQ(0, b);\n EXPECT_EQ(123, c);\n}\n\nTEST(dsb_util, SwapOut_class)\n{\n std::vector<int> a;\n a.push_back(123);\n const auto dataPtr = a.data();\n std::vector<int> r;\n r.push_back(456);\n r.push_back(789);\n\n std::vector<int> b = SwapOut(a, r);\n ASSERT_EQ(2U, a.size());\n EXPECT_EQ(456, a[0]);\n EXPECT_EQ(789, a[1]);\n\n \/\/ The following test is (most likely) not specified C++ behaviour, but\n \/\/ it would be a strange vector implementation that didn't implement a move\n \/\/ as a pointer move...\n EXPECT_EQ(1U, b.size());\n EXPECT_EQ(dataPtr, b.data());\n\n std::vector<int> c = SwapOut(b);\n EXPECT_TRUE(b.empty());\n EXPECT_EQ(1U, c.size());\n EXPECT_EQ(dataPtr, c.data());\n}\n\nTEST(dsb_util, OnScopeExit)\n{\n int i = 0;\n {\n auto setToOne = OnScopeExit([&i]() { i = 1; });\n EXPECT_EQ(0, i);\n }\n EXPECT_EQ(1, i);\n try {\n auto setToTwo = OnScopeExit([&i]() { i = 2; });\n EXPECT_EQ(1, i);\n throw 0;\n } catch (...) {\n EXPECT_EQ(2, i);\n i = 3;\n }\n EXPECT_EQ(3, i);\n}\n\nTEST(dsb_util, TempDir)\n{\n boost::filesystem::path d;\n {\n auto tmp = TempDir();\n d = tmp.Path();\n ASSERT_FALSE(d.empty());\n EXPECT_TRUE(boost::filesystem::is_directory(d));\n EXPECT_TRUE(boost::filesystem::is_empty(d));\n }\n EXPECT_FALSE(boost::filesystem::exists(d));\n}\n\nTEST(dsb_util, ThisExePath)\n{\n#ifdef _WIN32\n const auto expected = \"dsb_test.exe\";\n#else\n const auto expected = \"dsb_test\";\n#endif\n EXPECT_EQ(expected, ThisExePath().filename().string());\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Copyright (c) 2014, John Haddon. All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are\n\/\/ met:\n\/\/\n\/\/ * Redistributions of source code must retain the above\n\/\/ copyright notice, this list of conditions and the following\n\/\/ disclaimer.\n\/\/\n\/\/ * Redistributions in binary form must reproduce the above\n\/\/ copyright notice, this list of conditions and the following\n\/\/ disclaimer in the documentation and\/or other materials provided with\n\/\/ the distribution.\n\/\/\n\/\/ * Neither the name of John Haddon nor the names of\n\/\/ any other contributors to this software may be used to endorse or\n\/\/ promote products derived from this software without specific prior\n\/\/ written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS\n\/\/ IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,\n\/\/ THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n\/\/ PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR\n\/\/ CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n\/\/ EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n\/\/ PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n\/\/ PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n\/\/ LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n\/\/ NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n\/\/ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"GafferScene\/Duplicate.h\"\n\n#include \"GafferScene\/SceneAlgo.h\"\n\n#include \"Gaffer\/StringPlug.h\"\n\n#include \"IECore\/StringAlgo.h\"\n\nusing namespace std;\nusing namespace IECore;\nusing namespace Gaffer;\nusing namespace GafferScene;\n\nIE_CORE_DEFINERUNTIMETYPED( Duplicate );\n\nsize_t Duplicate::g_firstPlugIndex = 0;\n\nDuplicate::Duplicate( const std::string &name )\n\t:\tBranchCreator( name )\n{\n\n\tstoreIndexOfNextChild( g_firstPlugIndex );\n\n\taddChild( new StringPlug( \"target\" ) );\n\taddChild( new IntPlug( \"copies\", Plug::In, 1, 0 ) );\n\taddChild( new StringPlug( \"name\" ) );\n\taddChild( new TransformPlug( \"transform\" ) );\n\taddChild( new StringPlug( \"__outParent\", Plug::Out ) );\n\taddChild( new InternedStringVectorDataPlug( \"__outChildNames\", Plug::Out, inPlug()->childNamesPlug()->defaultValue() ) );\n\n\tparentPlug()->setInput( outParentPlug() );\n\tparentPlug()->setFlags( Plug::Serialisable, false );\n\n\t\/\/ Since we don't introduce any new sets, but just duplicate parts\n\t\/\/ of existing ones, we can save the BranchCreator base class some\n\t\/\/ trouble by making the setNamesPlug into a pass-through.\n\toutPlug()->setNamesPlug()->setInput( inPlug()->setNamesPlug() );\n}\n\nDuplicate::~Duplicate()\n{\n}\n\nGaffer::StringPlug *Duplicate::targetPlug()\n{\n\treturn getChild<StringPlug>( g_firstPlugIndex );\n}\n\nconst Gaffer::StringPlug *Duplicate::targetPlug() const\n{\n\treturn getChild<StringPlug>( g_firstPlugIndex );\n}\n\nGaffer::IntPlug *Duplicate::copiesPlug()\n{\n\treturn getChild<IntPlug>( g_firstPlugIndex + 1 );\n}\n\nconst Gaffer::IntPlug *Duplicate::copiesPlug() const\n{\n\treturn getChild<IntPlug>( g_firstPlugIndex + 1 );\n}\n\nGaffer::StringPlug *Duplicate::namePlug()\n{\n\treturn getChild<StringPlug>( g_firstPlugIndex + 2 );\n}\n\nconst Gaffer::StringPlug *Duplicate::namePlug() const\n{\n\treturn getChild<StringPlug>( g_firstPlugIndex + 2 );\n}\n\nGaffer::TransformPlug *Duplicate::transformPlug()\n{\n\treturn getChild<TransformPlug>( g_firstPlugIndex + 3 );\n}\n\nconst Gaffer::TransformPlug *Duplicate::transformPlug() const\n{\n\treturn getChild<TransformPlug>( g_firstPlugIndex + 3 );\n}\n\nGaffer::StringPlug *Duplicate::outParentPlug()\n{\n\treturn getChild<StringPlug>( g_firstPlugIndex + 4 );\n}\n\nconst Gaffer::StringPlug *Duplicate::outParentPlug() const\n{\n\treturn getChild<StringPlug>( g_firstPlugIndex + 4 );\n}\n\nGaffer::InternedStringVectorDataPlug *Duplicate::childNamesPlug()\n{\n\treturn getChild<InternedStringVectorDataPlug>( g_firstPlugIndex + 5 );\n}\n\nconst Gaffer::InternedStringVectorDataPlug *Duplicate::childNamesPlug() const\n{\n\treturn getChild<InternedStringVectorDataPlug>( g_firstPlugIndex + 5 );\n}\n\nvoid Duplicate::affects( const Gaffer::Plug *input, AffectedPlugsContainer &outputs ) const\n{\n\tBranchCreator::affects( input, outputs );\n\n\tif( input == targetPlug() )\n\t{\n\t\toutputs.push_back( outParentPlug() );\n\t\toutputs.push_back( childNamesPlug() );\n\t}\n\telse if( input == copiesPlug() )\n\t{\n\t\toutputs.push_back( childNamesPlug() );\n\t}\n\telse if( input == namePlug() )\n\t{\n\t\toutputs.push_back( childNamesPlug() );\n\t}\n\telse if( input == childNamesPlug() )\n\t{\n\t\toutputs.push_back( outPlug()->childNamesPlug() );\n\t}\n\telse if( transformPlug()->isAncestorOf( input ) )\n\t{\n\t\toutputs.push_back( outPlug()->transformPlug() );\n\t}\n}\n\nvoid Duplicate::hash( const ValuePlug *output, const Context *context, IECore::MurmurHash &h ) const\n{\n\tBranchCreator::hash( output, context, h );\n\n\tif( output == outParentPlug() )\n\t{\n\t\ttargetPlug()->hash( h );\n\t}\n\telse if( output == childNamesPlug() )\n\t{\n\t\tScenePath target;\n\t\tScenePlug::stringToPath( targetPlug()->getValue(), target );\n\t\tif( !SceneAlgo::exists( inPlug(), target ) )\n\t\t{\n\t\t\th = childNamesPlug()->defaultValue()->Object::hash();\n\t\t\treturn;\n\t\t}\n\t\th.append( target.data(), target.size() );\n\t\tcopiesPlug()->hash( h );\n\t\tnamePlug()->hash( h );\n\t}\n}\n\nvoid Duplicate::compute( ValuePlug *output, const Context *context ) const\n{\n\tif( output == outParentPlug() )\n\t{\n\t\tScenePath target;\n\t\tScenePlug::stringToPath( targetPlug()->getValue(), target );\n\t\tstring parent;\n\t\tfor( size_t i = 0; i < target.size(); ++i )\n\t\t{\n\t\t\tparent += \"\/\";\n\t\t\tif( i < target.size() - 1 )\n\t\t\t{\n\t\t\t\tparent += target[i];\n\t\t\t}\n\t\t}\n\t\tstatic_cast<StringPlug *>( output )->setValue( parent );\n\t\treturn;\n\t}\n\telse if( output == childNamesPlug() )\n\t{\n\t\t\/\/ Get the path to our target, and check it exists.\n\t\tScenePath target;\n\t\tScenePlug::stringToPath( targetPlug()->getValue(), target );\n\t\tif( !SceneAlgo::exists( inPlug(), target ) )\n\t\t{\n\t\t\toutput->setToDefault();\n\t\t\treturn;\n\t\t}\n\n\t\t\/\/ go ahead and generate our childnames.\n\t\t\/\/ these are composed of a stem and possibly\n\t\t\/\/ a numeric suffix. we default to deriving\n\t\t\/\/ these from the name of the target.\n\n\t\tstd::string stem;\n\t\tint suffix = StringAlgo::numericSuffix( target.back(), 0, &stem );\n\t\tsuffix++;\n\n\t\tconst int copies = copiesPlug()->getValue();\n\t\tconst std::string name = namePlug()->getValue();\n\n\t\t\/\/ if a name is provided explicitly, then\n\t\t\/\/ it overrides the name and suffix derived\n\t\t\/\/ from the target.\n\t\tif( name.size() )\n\t\t{\n\t\t\tstd::string nameStem;\n\t\t\tconst int nameSuffix = StringAlgo::numericSuffix( name, &nameStem );\n\t\t\tstem = nameStem;\n\t\t\tsuffix = copies == 1 ? nameSuffix : max( nameSuffix, 1 );\n\t\t}\n\n\t\tInternedStringVectorDataPtr childNamesData = new InternedStringVectorData;\n\t\tstd::vector<InternedString> &childNames = childNamesData->writable();\n\t\tchildNames.reserve( copies );\n\n\t\tif( suffix == -1 )\n\t\t{\n\t\t\tassert( copies == 1 );\n\t\t\tchildNames.push_back( stem );\n\t\t}\n\t\telse\n\t\t{\n\t\t\tboost::format formatter( \"%s%d\" );\n\t\t\tfor( int i = 0; i < copies; ++i )\n\t\t\t{\n\t\t\t\tchildNames.push_back( boost::str( formatter % stem % suffix++ ) );\n\t\t\t}\n\t\t}\n\n\t\tstatic_cast<InternedStringVectorDataPlug *>( output )->setValue( childNamesData );\n\t\treturn;\n\t}\n\n\tBranchCreator::compute( output, context );\n}\n\nvoid Duplicate::hashBranchBound( const ScenePath &parentPath, const ScenePath &branchPath, const Gaffer::Context *context, IECore::MurmurHash &h ) const\n{\n\tScenePath source;\n\tsourcePath( branchPath, source );\n\th = inPlug()->boundHash( source );\n}\n\nImath::Box3f Duplicate::computeBranchBound( const ScenePath &parentPath, const ScenePath &branchPath, const Gaffer::Context *context ) const\n{\n\tScenePath source;\n\tsourcePath( branchPath, source );\n\treturn inPlug()->bound( source );\n}\n\nvoid Duplicate::hashBranchTransform( const ScenePath &parentPath, const ScenePath &branchPath, const Gaffer::Context *context, IECore::MurmurHash &h ) const\n{\n\tScenePath source;\n\tsourcePath( branchPath, source );\n\tif( branchPath.size() == 1 )\n\t{\n\t\tBranchCreator::hashBranchTransform( parentPath, branchPath, context, h );\n\t\th.append( inPlug()->transformHash( source ) );\n\t\ttransformPlug()->hash( h );\n\t\tchildNamesPlug()->hash( h );\n\t\th.append( branchPath[0] );\n\t}\n\telse\n\t{\n\t\th = inPlug()->transformHash( source );\n\t}\n}\n\nImath::M44f Duplicate::computeBranchTransform( const ScenePath &parentPath, const ScenePath &branchPath, const Gaffer::Context *context ) const\n{\n\tScenePath source;\n\tsourcePath( branchPath, source );\n\tImath::M44f result = inPlug()->transform( source );\n\tif( branchPath.size() == 1 )\n\t{\n\t\tconst Imath::M44f matrix = transformPlug()->matrix();\n\t\tConstInternedStringVectorDataPtr childNamesData = childNamesPlug()->getValue();\n\t\tconst vector<InternedString> &childNames = childNamesData->readable();\n\n\t\tsize_t i = 0;\n\t\tdo\n\t\t{\n\t\t\tresult = result * matrix;\n\t\t} while( i < childNames.size() && branchPath[0] != childNames[i++] );\n\t}\n\treturn result;\n}\n\nvoid Duplicate::hashBranchAttributes( const ScenePath &parentPath, const ScenePath &branchPath, const Gaffer::Context *context, IECore::MurmurHash &h ) const\n{\n\tScenePath source;\n\tsourcePath( branchPath, source );\n\th = inPlug()->attributesHash( source );\n}\n\nIECore::ConstCompoundObjectPtr Duplicate::computeBranchAttributes( const ScenePath &parentPath, const ScenePath &branchPath, const Gaffer::Context *context ) const\n{\n\tScenePath source;\n\tsourcePath( branchPath, source );\n\treturn inPlug()->attributes( source );\n}\n\nvoid Duplicate::hashBranchObject( const ScenePath &parentPath, const ScenePath &branchPath, const Gaffer::Context *context, IECore::MurmurHash &h ) const\n{\n\tScenePath source;\n\tsourcePath( branchPath, source );\n\th = inPlug()->objectHash( source );\n}\n\nIECore::ConstObjectPtr Duplicate::computeBranchObject( const ScenePath &parentPath, const ScenePath &branchPath, const Gaffer::Context *context ) const\n{\n\tScenePath source;\n\tsourcePath( branchPath, source );\n\treturn inPlug()->object( source );\n}\n\nvoid Duplicate::hashBranchChildNames( const ScenePath &parentPath, const ScenePath &branchPath, const Gaffer::Context *context, IECore::MurmurHash &h ) const\n{\n\tif( branchPath.size() == 0 )\n\t{\n\t\th = childNamesPlug()->hash();\n\t}\n\telse\n\t{\n\t\tScenePath source;\n\t\tsourcePath( branchPath, source );\n\t\th = inPlug()->childNamesHash( source );\n\t}\n}\n\nIECore::ConstInternedStringVectorDataPtr Duplicate::computeBranchChildNames( const ScenePath &parentPath, const ScenePath &branchPath, const Gaffer::Context *context ) const\n{\n\tif( branchPath.size() == 0 )\n\t{\n\t\treturn childNamesPlug()->getValue();\n\t}\n\telse\n\t{\n\t\tScenePath source;\n\t\tsourcePath( branchPath, source );\n\t\treturn inPlug()->childNames( source );\n\t}\n}\n\nvoid Duplicate::hashBranchSet( const ScenePath &parentPath, const IECore::InternedString &setName, const Gaffer::Context *context, IECore::MurmurHash &h ) const\n{\n\th.append( inPlug()->setHash( setName ) );\n\ttargetPlug()->hash( h );\n\tchildNamesPlug()->hash( h );\n}\n\nIECore::ConstPathMatcherDataPtr Duplicate::computeBranchSet( const ScenePath &parentPath, const IECore::InternedString &setName, const Gaffer::Context *context ) const\n{\n\tConstPathMatcherDataPtr inputSetData = inPlug()->set( setName );\n\tconst PathMatcher &inputSet = inputSetData->readable();\n\tif( inputSet.isEmpty() )\n\t{\n\t\treturn outPlug()->setPlug()->defaultValue();\n\t}\n\n\tPathMatcher subTree = inputSet.subTree( targetPlug()->getValue() );\n\tif( subTree.isEmpty() )\n\t{\n\t\treturn outPlug()->setPlug()->defaultValue();\n\t}\n\n\tConstInternedStringVectorDataPtr childNamesData = childNamesPlug()->getValue();\n\tconst vector<InternedString> &childNames = childNamesData->readable();\n\n\tPathMatcherDataPtr resultData = new PathMatcherData;\n\tPathMatcher &result = resultData->writable();\n\tScenePath prefix( 1 );\n\tfor( vector<InternedString>::const_iterator it = childNames.begin(), eIt = childNames.end(); it != eIt; ++it )\n\t{\n\t\tprefix.back() = *it;\n\t\tresult.addPaths( subTree, prefix );\n\t}\n\n\treturn resultData;\n}\n\nvoid Duplicate::sourcePath( const ScenePath &branchPath, ScenePath &source ) const\n{\n\tassert( branchPath.size() );\n\tScenePlug::stringToPath( targetPlug()->getValue(), source );\n\tcopy( ++branchPath.begin(), branchPath.end(), back_inserter( source ) );\n}\n<commit_msg>Duplicate : Hide filter plug<commit_after>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Copyright (c) 2014, John Haddon. All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are\n\/\/ met:\n\/\/\n\/\/ * Redistributions of source code must retain the above\n\/\/ copyright notice, this list of conditions and the following\n\/\/ disclaimer.\n\/\/\n\/\/ * Redistributions in binary form must reproduce the above\n\/\/ copyright notice, this list of conditions and the following\n\/\/ disclaimer in the documentation and\/or other materials provided with\n\/\/ the distribution.\n\/\/\n\/\/ * Neither the name of John Haddon nor the names of\n\/\/ any other contributors to this software may be used to endorse or\n\/\/ promote products derived from this software without specific prior\n\/\/ written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS\n\/\/ IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,\n\/\/ THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n\/\/ PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR\n\/\/ CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n\/\/ EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n\/\/ PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n\/\/ PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n\/\/ LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n\/\/ NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n\/\/ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"GafferScene\/Duplicate.h\"\n\n#include \"GafferScene\/SceneAlgo.h\"\n\n#include \"Gaffer\/StringPlug.h\"\n\n#include \"IECore\/StringAlgo.h\"\n\nusing namespace std;\nusing namespace IECore;\nusing namespace Gaffer;\nusing namespace GafferScene;\n\nIE_CORE_DEFINERUNTIMETYPED( Duplicate );\n\nsize_t Duplicate::g_firstPlugIndex = 0;\n\nDuplicate::Duplicate( const std::string &name )\n\t:\tBranchCreator( name )\n{\n\n\tstoreIndexOfNextChild( g_firstPlugIndex );\n\n\taddChild( new StringPlug( \"target\" ) );\n\taddChild( new IntPlug( \"copies\", Plug::In, 1, 0 ) );\n\taddChild( new StringPlug( \"name\" ) );\n\taddChild( new TransformPlug( \"transform\" ) );\n\taddChild( new StringPlug( \"__outParent\", Plug::Out ) );\n\taddChild( new InternedStringVectorDataPlug( \"__outChildNames\", Plug::Out, inPlug()->childNamesPlug()->defaultValue() ) );\n\n\tparentPlug()->setInput( outParentPlug() );\n\tparentPlug()->setFlags( Plug::Serialisable, false );\n\n\t\/\/ Make the filter plug private. We do want to support this one\n\t\/\/ day, but the filter should be specifying the objects to duplicate,\n\t\/\/ not the parent locations to duplicate them under. Until we implement\n\t\/\/ that, its best not to allow folks to become dependent upon behaviour\n\t\/\/ that will change.\n\tfilterPlug()->setName( \"__filter\" );\n\n\t\/\/ Since we don't introduce any new sets, but just duplicate parts\n\t\/\/ of existing ones, we can save the BranchCreator base class some\n\t\/\/ trouble by making the setNamesPlug into a pass-through.\n\toutPlug()->setNamesPlug()->setInput( inPlug()->setNamesPlug() );\n}\n\nDuplicate::~Duplicate()\n{\n}\n\nGaffer::StringPlug *Duplicate::targetPlug()\n{\n\treturn getChild<StringPlug>( g_firstPlugIndex );\n}\n\nconst Gaffer::StringPlug *Duplicate::targetPlug() const\n{\n\treturn getChild<StringPlug>( g_firstPlugIndex );\n}\n\nGaffer::IntPlug *Duplicate::copiesPlug()\n{\n\treturn getChild<IntPlug>( g_firstPlugIndex + 1 );\n}\n\nconst Gaffer::IntPlug *Duplicate::copiesPlug() const\n{\n\treturn getChild<IntPlug>( g_firstPlugIndex + 1 );\n}\n\nGaffer::StringPlug *Duplicate::namePlug()\n{\n\treturn getChild<StringPlug>( g_firstPlugIndex + 2 );\n}\n\nconst Gaffer::StringPlug *Duplicate::namePlug() const\n{\n\treturn getChild<StringPlug>( g_firstPlugIndex + 2 );\n}\n\nGaffer::TransformPlug *Duplicate::transformPlug()\n{\n\treturn getChild<TransformPlug>( g_firstPlugIndex + 3 );\n}\n\nconst Gaffer::TransformPlug *Duplicate::transformPlug() const\n{\n\treturn getChild<TransformPlug>( g_firstPlugIndex + 3 );\n}\n\nGaffer::StringPlug *Duplicate::outParentPlug()\n{\n\treturn getChild<StringPlug>( g_firstPlugIndex + 4 );\n}\n\nconst Gaffer::StringPlug *Duplicate::outParentPlug() const\n{\n\treturn getChild<StringPlug>( g_firstPlugIndex + 4 );\n}\n\nGaffer::InternedStringVectorDataPlug *Duplicate::childNamesPlug()\n{\n\treturn getChild<InternedStringVectorDataPlug>( g_firstPlugIndex + 5 );\n}\n\nconst Gaffer::InternedStringVectorDataPlug *Duplicate::childNamesPlug() const\n{\n\treturn getChild<InternedStringVectorDataPlug>( g_firstPlugIndex + 5 );\n}\n\nvoid Duplicate::affects( const Gaffer::Plug *input, AffectedPlugsContainer &outputs ) const\n{\n\tBranchCreator::affects( input, outputs );\n\n\tif( input == targetPlug() )\n\t{\n\t\toutputs.push_back( outParentPlug() );\n\t\toutputs.push_back( childNamesPlug() );\n\t}\n\telse if( input == copiesPlug() )\n\t{\n\t\toutputs.push_back( childNamesPlug() );\n\t}\n\telse if( input == namePlug() )\n\t{\n\t\toutputs.push_back( childNamesPlug() );\n\t}\n\telse if( input == childNamesPlug() )\n\t{\n\t\toutputs.push_back( outPlug()->childNamesPlug() );\n\t}\n\telse if( transformPlug()->isAncestorOf( input ) )\n\t{\n\t\toutputs.push_back( outPlug()->transformPlug() );\n\t}\n}\n\nvoid Duplicate::hash( const ValuePlug *output, const Context *context, IECore::MurmurHash &h ) const\n{\n\tBranchCreator::hash( output, context, h );\n\n\tif( output == outParentPlug() )\n\t{\n\t\ttargetPlug()->hash( h );\n\t}\n\telse if( output == childNamesPlug() )\n\t{\n\t\tScenePath target;\n\t\tScenePlug::stringToPath( targetPlug()->getValue(), target );\n\t\tif( !SceneAlgo::exists( inPlug(), target ) )\n\t\t{\n\t\t\th = childNamesPlug()->defaultValue()->Object::hash();\n\t\t\treturn;\n\t\t}\n\t\th.append( target.data(), target.size() );\n\t\tcopiesPlug()->hash( h );\n\t\tnamePlug()->hash( h );\n\t}\n}\n\nvoid Duplicate::compute( ValuePlug *output, const Context *context ) const\n{\n\tif( output == outParentPlug() )\n\t{\n\t\tScenePath target;\n\t\tScenePlug::stringToPath( targetPlug()->getValue(), target );\n\t\tstring parent;\n\t\tfor( size_t i = 0; i < target.size(); ++i )\n\t\t{\n\t\t\tparent += \"\/\";\n\t\t\tif( i < target.size() - 1 )\n\t\t\t{\n\t\t\t\tparent += target[i];\n\t\t\t}\n\t\t}\n\t\tstatic_cast<StringPlug *>( output )->setValue( parent );\n\t\treturn;\n\t}\n\telse if( output == childNamesPlug() )\n\t{\n\t\t\/\/ Get the path to our target, and check it exists.\n\t\tScenePath target;\n\t\tScenePlug::stringToPath( targetPlug()->getValue(), target );\n\t\tif( !SceneAlgo::exists( inPlug(), target ) )\n\t\t{\n\t\t\toutput->setToDefault();\n\t\t\treturn;\n\t\t}\n\n\t\t\/\/ go ahead and generate our childnames.\n\t\t\/\/ these are composed of a stem and possibly\n\t\t\/\/ a numeric suffix. we default to deriving\n\t\t\/\/ these from the name of the target.\n\n\t\tstd::string stem;\n\t\tint suffix = StringAlgo::numericSuffix( target.back(), 0, &stem );\n\t\tsuffix++;\n\n\t\tconst int copies = copiesPlug()->getValue();\n\t\tconst std::string name = namePlug()->getValue();\n\n\t\t\/\/ if a name is provided explicitly, then\n\t\t\/\/ it overrides the name and suffix derived\n\t\t\/\/ from the target.\n\t\tif( name.size() )\n\t\t{\n\t\t\tstd::string nameStem;\n\t\t\tconst int nameSuffix = StringAlgo::numericSuffix( name, &nameStem );\n\t\t\tstem = nameStem;\n\t\t\tsuffix = copies == 1 ? nameSuffix : max( nameSuffix, 1 );\n\t\t}\n\n\t\tInternedStringVectorDataPtr childNamesData = new InternedStringVectorData;\n\t\tstd::vector<InternedString> &childNames = childNamesData->writable();\n\t\tchildNames.reserve( copies );\n\n\t\tif( suffix == -1 )\n\t\t{\n\t\t\tassert( copies == 1 );\n\t\t\tchildNames.push_back( stem );\n\t\t}\n\t\telse\n\t\t{\n\t\t\tboost::format formatter( \"%s%d\" );\n\t\t\tfor( int i = 0; i < copies; ++i )\n\t\t\t{\n\t\t\t\tchildNames.push_back( boost::str( formatter % stem % suffix++ ) );\n\t\t\t}\n\t\t}\n\n\t\tstatic_cast<InternedStringVectorDataPlug *>( output )->setValue( childNamesData );\n\t\treturn;\n\t}\n\n\tBranchCreator::compute( output, context );\n}\n\nvoid Duplicate::hashBranchBound( const ScenePath &parentPath, const ScenePath &branchPath, const Gaffer::Context *context, IECore::MurmurHash &h ) const\n{\n\tScenePath source;\n\tsourcePath( branchPath, source );\n\th = inPlug()->boundHash( source );\n}\n\nImath::Box3f Duplicate::computeBranchBound( const ScenePath &parentPath, const ScenePath &branchPath, const Gaffer::Context *context ) const\n{\n\tScenePath source;\n\tsourcePath( branchPath, source );\n\treturn inPlug()->bound( source );\n}\n\nvoid Duplicate::hashBranchTransform( const ScenePath &parentPath, const ScenePath &branchPath, const Gaffer::Context *context, IECore::MurmurHash &h ) const\n{\n\tScenePath source;\n\tsourcePath( branchPath, source );\n\tif( branchPath.size() == 1 )\n\t{\n\t\tBranchCreator::hashBranchTransform( parentPath, branchPath, context, h );\n\t\th.append( inPlug()->transformHash( source ) );\n\t\ttransformPlug()->hash( h );\n\t\tchildNamesPlug()->hash( h );\n\t\th.append( branchPath[0] );\n\t}\n\telse\n\t{\n\t\th = inPlug()->transformHash( source );\n\t}\n}\n\nImath::M44f Duplicate::computeBranchTransform( const ScenePath &parentPath, const ScenePath &branchPath, const Gaffer::Context *context ) const\n{\n\tScenePath source;\n\tsourcePath( branchPath, source );\n\tImath::M44f result = inPlug()->transform( source );\n\tif( branchPath.size() == 1 )\n\t{\n\t\tconst Imath::M44f matrix = transformPlug()->matrix();\n\t\tConstInternedStringVectorDataPtr childNamesData = childNamesPlug()->getValue();\n\t\tconst vector<InternedString> &childNames = childNamesData->readable();\n\n\t\tsize_t i = 0;\n\t\tdo\n\t\t{\n\t\t\tresult = result * matrix;\n\t\t} while( i < childNames.size() && branchPath[0] != childNames[i++] );\n\t}\n\treturn result;\n}\n\nvoid Duplicate::hashBranchAttributes( const ScenePath &parentPath, const ScenePath &branchPath, const Gaffer::Context *context, IECore::MurmurHash &h ) const\n{\n\tScenePath source;\n\tsourcePath( branchPath, source );\n\th = inPlug()->attributesHash( source );\n}\n\nIECore::ConstCompoundObjectPtr Duplicate::computeBranchAttributes( const ScenePath &parentPath, const ScenePath &branchPath, const Gaffer::Context *context ) const\n{\n\tScenePath source;\n\tsourcePath( branchPath, source );\n\treturn inPlug()->attributes( source );\n}\n\nvoid Duplicate::hashBranchObject( const ScenePath &parentPath, const ScenePath &branchPath, const Gaffer::Context *context, IECore::MurmurHash &h ) const\n{\n\tScenePath source;\n\tsourcePath( branchPath, source );\n\th = inPlug()->objectHash( source );\n}\n\nIECore::ConstObjectPtr Duplicate::computeBranchObject( const ScenePath &parentPath, const ScenePath &branchPath, const Gaffer::Context *context ) const\n{\n\tScenePath source;\n\tsourcePath( branchPath, source );\n\treturn inPlug()->object( source );\n}\n\nvoid Duplicate::hashBranchChildNames( const ScenePath &parentPath, const ScenePath &branchPath, const Gaffer::Context *context, IECore::MurmurHash &h ) const\n{\n\tif( branchPath.size() == 0 )\n\t{\n\t\th = childNamesPlug()->hash();\n\t}\n\telse\n\t{\n\t\tScenePath source;\n\t\tsourcePath( branchPath, source );\n\t\th = inPlug()->childNamesHash( source );\n\t}\n}\n\nIECore::ConstInternedStringVectorDataPtr Duplicate::computeBranchChildNames( const ScenePath &parentPath, const ScenePath &branchPath, const Gaffer::Context *context ) const\n{\n\tif( branchPath.size() == 0 )\n\t{\n\t\treturn childNamesPlug()->getValue();\n\t}\n\telse\n\t{\n\t\tScenePath source;\n\t\tsourcePath( branchPath, source );\n\t\treturn inPlug()->childNames( source );\n\t}\n}\n\nvoid Duplicate::hashBranchSet( const ScenePath &parentPath, const IECore::InternedString &setName, const Gaffer::Context *context, IECore::MurmurHash &h ) const\n{\n\th.append( inPlug()->setHash( setName ) );\n\ttargetPlug()->hash( h );\n\tchildNamesPlug()->hash( h );\n}\n\nIECore::ConstPathMatcherDataPtr Duplicate::computeBranchSet( const ScenePath &parentPath, const IECore::InternedString &setName, const Gaffer::Context *context ) const\n{\n\tConstPathMatcherDataPtr inputSetData = inPlug()->set( setName );\n\tconst PathMatcher &inputSet = inputSetData->readable();\n\tif( inputSet.isEmpty() )\n\t{\n\t\treturn outPlug()->setPlug()->defaultValue();\n\t}\n\n\tPathMatcher subTree = inputSet.subTree( targetPlug()->getValue() );\n\tif( subTree.isEmpty() )\n\t{\n\t\treturn outPlug()->setPlug()->defaultValue();\n\t}\n\n\tConstInternedStringVectorDataPtr childNamesData = childNamesPlug()->getValue();\n\tconst vector<InternedString> &childNames = childNamesData->readable();\n\n\tPathMatcherDataPtr resultData = new PathMatcherData;\n\tPathMatcher &result = resultData->writable();\n\tScenePath prefix( 1 );\n\tfor( vector<InternedString>::const_iterator it = childNames.begin(), eIt = childNames.end(); it != eIt; ++it )\n\t{\n\t\tprefix.back() = *it;\n\t\tresult.addPaths( subTree, prefix );\n\t}\n\n\treturn resultData;\n}\n\nvoid Duplicate::sourcePath( const ScenePath &branchPath, ScenePath &source ) const\n{\n\tassert( branchPath.size() );\n\tScenePlug::stringToPath( targetPlug()->getValue(), source );\n\tcopy( ++branchPath.begin(), branchPath.end(), back_inserter( source ) );\n}\n<|endoftext|>"} {"text":"<commit_before>\/***************************************************************************\r\n * Copyright (c) 2015 FreeCAD Developers *\r\n * Author: Przemo Firszt <przemo@firszt.eu> *\r\n * Based on DlgToolbars.cpp file *\r\n * *\r\n * This file is part of the FreeCAD CAx development system. *\r\n * *\r\n * This library is free software; you can redistribute it and\/or *\r\n * modify it under the terms of the GNU Library General Public *\r\n * License as published by the Free Software Foundation; either *\r\n * version 2 of the License, or (at your option) any later version. *\r\n * *\r\n * This library is distributed in the hope that it will be useful, *\r\n * but WITHOUT ANY WARRANTY; without even the implied warranty of *\r\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *\r\n * GNU Library General Public License for more details. *\r\n * *\r\n * You should have received a copy of the GNU Library General Public *\r\n * License along with this library; see the file COPYING.LIB. If not, *\r\n * write to the Free Software Foundation, Inc., 59 Temple Place, *\r\n * Suite 330, Boston, MA 02111-1307, USA *\r\n * *\r\n ***************************************************************************\/\r\n\r\n\r\n#include \"PreCompiled.h\"\r\n#ifndef _PreComp_\r\n# include <QInputDialog>\r\n#endif\r\n\r\n#include \"DlgWorkbenchesImp.h\"\r\n#include \"Application.h\"\r\n#include \"BitmapFactory.h\"\r\n#include \"Command.h\"\r\n#include \"MainWindow.h\"\r\n#include \"Widgets.h\"\r\n#include \"Workbench.h\"\r\n#include \"WorkbenchManager.h\"\r\n#include \"QListWidgetCustom.h\"\r\n\r\nusing namespace Gui::Dialog;\r\n\r\nconst QString DlgWorkbenchesImp::all_workbenches = QString::fromAscii(\"ALL\");\r\n\r\n\/* TRANSLATOR Gui::Dialog::DlgWorkbenches *\/\r\n\r\nDlgWorkbenchesImp::DlgWorkbenchesImp(QWidget* parent)\r\n : CustomizeActionPage(parent)\r\n{\r\n this->setupUi(this);\r\n set_lw_properties(lw_enabled_workbenches);\r\n set_lw_properties(lw_disabled_workbenches);\r\n const QString lw_disabled_name = QString::fromAscii(\"disabled workbenches\");\r\n lw_disabled_workbenches->setAccessibleName(lw_disabled_name);\r\n lw_disabled_workbenches->setSortingEnabled(true);\r\n\r\n QStringList enabled_wbs_list = load_enabled_workbenches();\r\n QStringList workbenches = Application::Instance->workbenches();\r\n\r\n for (QStringList::Iterator it = enabled_wbs_list.begin(); it != enabled_wbs_list.end(); ++it) {\r\n if (workbenches.contains(*it)){\r\n QString wb = *it;\r\n add_workbench(lw_enabled_workbenches, wb);\r\n } else {\r\n qDebug(\"Ignoring unknown \" + it->toLatin1() + \" workbench found in user preferences.\");\r\n }\r\n }\r\n for (QStringList::Iterator it = workbenches.begin(); it != workbenches.end(); ++it) {\r\n if (!enabled_wbs_list.contains(*it)){\r\n QString wb = *it;\r\n add_workbench(lw_disabled_workbenches, wb);\r\n }\r\n }\r\n lw_enabled_workbenches->setCurrentRow(0);\r\n lw_disabled_workbenches->setCurrentRow(0);\r\n}\r\n\r\n\/** Destroys the object and frees any allocated resources *\/\r\nDlgWorkbenchesImp::~DlgWorkbenchesImp()\r\n{\r\n}\r\n\r\nvoid DlgWorkbenchesImp::set_lw_properties(QListWidgetCustom *lw)\r\n{\r\n lw->setDragDropMode(QAbstractItemView::DragDrop);\r\n lw->setSelectionMode(QAbstractItemView::SingleSelection);\r\n lw->viewport()->setAcceptDrops(true);\r\n lw->setDropIndicatorShown(true);\r\n lw->setDragEnabled(true);\r\n lw->setDefaultDropAction(Qt::MoveAction);\r\n}\r\n\r\nvoid DlgWorkbenchesImp::add_workbench(QListWidgetCustom *lw, QString it)\r\n{\r\n QPixmap px = Application::Instance->workbenchIcon(it);\r\n QString mt = Application::Instance->workbenchMenuText(it);\r\n QListWidgetItem *wi = (new QListWidgetItem(QIcon(px), mt));\r\n wi->setData(Qt::UserRole, QVariant(it));\r\n lw->addItem(wi);\r\n}\r\n\r\nvoid DlgWorkbenchesImp::changeEvent(QEvent *e)\r\n{\r\n if (e->type() == QEvent::LanguageChange) {\r\n retranslateUi(this);\r\n }\r\n else {\r\n QWidget::changeEvent(e);\r\n }\r\n}\r\n\r\nvoid DlgWorkbenchesImp::hideEvent(QHideEvent * event)\r\n{\r\n save_enabled_workbenches();\r\n}\r\n\r\nvoid DlgWorkbenchesImp::onAddMacroAction(const QByteArray& macro)\r\n{\r\n}\r\n\r\nvoid DlgWorkbenchesImp::onRemoveMacroAction(const QByteArray& macro)\r\n{\r\n}\r\n\r\nvoid DlgWorkbenchesImp::onModifyMacroAction(const QByteArray& macro)\r\n{\r\n}\r\n\r\nvoid DlgWorkbenchesImp::move_workbench(QListWidgetCustom *lwc_dest,\r\n QListWidgetItem *wi)\r\n{\r\n QListWidgetItem* item = wi->clone();\r\n lwc_dest->addItem(item);\r\n lwc_dest->setCurrentItem(item);\r\n delete wi;\r\n}\r\n\r\nvoid DlgWorkbenchesImp::on_add_to_enabled_workbenches_btn_clicked()\r\n{\r\n QListWidgetItem* ci = lw_disabled_workbenches->currentItem();\r\n if (ci) {\r\n\tmove_workbench(lw_enabled_workbenches, ci);\r\n }\r\n}\r\n\r\nvoid DlgWorkbenchesImp::on_remove_from_enabled_workbenches_btn_clicked()\r\n{\r\n QListWidgetItem* ci = lw_enabled_workbenches->currentItem();\r\n if (ci) {\r\n\tmove_workbench(lw_disabled_workbenches, ci);\r\n }\r\n}\r\n\r\nvoid DlgWorkbenchesImp::shift_workbench(bool up)\r\n{\r\n int direction;\r\n if (up){\r\n direction = -1;\r\n } else {\r\n direction = 1;\r\n }\r\n if (lw_enabled_workbenches->currentItem()) {\r\n int index = lw_enabled_workbenches->currentRow();\r\n QListWidgetItem *item = lw_enabled_workbenches->takeItem(index);\r\n lw_enabled_workbenches->insertItem(index + direction, item);\r\n lw_enabled_workbenches->setCurrentRow(index + direction);\r\n }\r\n}\r\n\r\nvoid DlgWorkbenchesImp::on_shift_workbench_up_btn_clicked()\r\n{\r\n shift_workbench(true);\r\n}\r\n\r\nvoid DlgWorkbenchesImp::on_shift_workbench_down_btn_clicked()\r\n{\r\n shift_workbench(false);\r\n}\r\n\r\nvoid DlgWorkbenchesImp::on_sort_enabled_workbenches_btn_clicked()\r\n{\r\n lw_enabled_workbenches->sortItems();\r\n}\r\n\r\nvoid DlgWorkbenchesImp::on_add_all_to_enabled_workbenches_btn_clicked()\r\n{\r\n while (lw_disabled_workbenches->count() > 0) {\r\n QListWidgetItem* item = lw_disabled_workbenches->item(0);\r\n move_workbench(lw_enabled_workbenches, item);\r\n }\r\n}\r\n\r\nQStringList DlgWorkbenchesImp::load_enabled_workbenches()\r\n{\r\n QString enabled_wbs;\r\n QStringList enabled_wbs_list;\r\n ParameterGrp::handle hGrp;\r\n\r\n hGrp = App::GetApplication().GetParameterGroupByPath(\"User parameter:BaseApp\/Workbenches\");\r\n enabled_wbs = QString::fromStdString(hGrp->GetASCII(\"Enabled\", all_workbenches.toStdString().c_str()).c_str());\r\n enabled_wbs_list = enabled_wbs.split(QLatin1String(\",\"), QString::SkipEmptyParts);\r\n\r\n if (enabled_wbs_list.at(0) == all_workbenches) {\r\n enabled_wbs_list.removeFirst();\r\n QStringList workbenches = Application::Instance->workbenches();\r\n for (QStringList::Iterator it = workbenches.begin(); it != workbenches.end(); ++it) {\r\n enabled_wbs_list.append(*it);\r\n }\r\n enabled_wbs_list.sort();\r\n }\r\n return enabled_wbs_list;\r\n}\r\n\r\nvoid DlgWorkbenchesImp::save_enabled_workbenches()\r\n{\r\n QString enabled_wbs;\r\n ParameterGrp::handle hGrp;\r\n\r\n hGrp = App::GetApplication().GetParameterGroupByPath(\"User parameter:BaseApp\/Workbenches\");\r\n hGrp->Clear();\r\n\r\n if (lw_enabled_workbenches->count() == 0) {\r\n enabled_wbs.append(QString::fromAscii(\"NoneWorkbench\"));\r\n } else {\r\n for (int i = 0; i < lw_enabled_workbenches->count(); i++) {\r\n QVariant item_data = lw_enabled_workbenches->item(i)->data(Qt::UserRole);\r\n QString name = item_data.toString();\r\n enabled_wbs.append(name + QString::fromAscii(\",\"));\r\n }\r\n }\r\n hGrp->SetASCII(\"Enabled\", enabled_wbs.toAscii());\r\n}\r\n\r\n#include \"moc_DlgWorkbenchesImp.cpp\"\r\n<commit_msg>+ fix minor bug in string concatenation<commit_after>\/***************************************************************************\r\n * Copyright (c) 2015 FreeCAD Developers *\r\n * Author: Przemo Firszt <przemo@firszt.eu> *\r\n * Based on DlgToolbars.cpp file *\r\n * *\r\n * This file is part of the FreeCAD CAx development system. *\r\n * *\r\n * This library is free software; you can redistribute it and\/or *\r\n * modify it under the terms of the GNU Library General Public *\r\n * License as published by the Free Software Foundation; either *\r\n * version 2 of the License, or (at your option) any later version. *\r\n * *\r\n * This library is distributed in the hope that it will be useful, *\r\n * but WITHOUT ANY WARRANTY; without even the implied warranty of *\r\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *\r\n * GNU Library General Public License for more details. *\r\n * *\r\n * You should have received a copy of the GNU Library General Public *\r\n * License along with this library; see the file COPYING.LIB. If not, *\r\n * write to the Free Software Foundation, Inc., 59 Temple Place, *\r\n * Suite 330, Boston, MA 02111-1307, USA *\r\n * *\r\n ***************************************************************************\/\r\n\r\n\r\n#include \"PreCompiled.h\"\r\n#ifndef _PreComp_\r\n# include <QInputDialog>\r\n#endif\r\n\r\n#include \"DlgWorkbenchesImp.h\"\r\n#include \"Application.h\"\r\n#include \"BitmapFactory.h\"\r\n#include \"Command.h\"\r\n#include \"MainWindow.h\"\r\n#include \"Widgets.h\"\r\n#include \"Workbench.h\"\r\n#include \"WorkbenchManager.h\"\r\n#include \"QListWidgetCustom.h\"\r\n\r\nusing namespace Gui::Dialog;\r\n\r\nconst QString DlgWorkbenchesImp::all_workbenches = QString::fromAscii(\"ALL\");\r\n\r\n\/* TRANSLATOR Gui::Dialog::DlgWorkbenches *\/\r\n\r\nDlgWorkbenchesImp::DlgWorkbenchesImp(QWidget* parent)\r\n : CustomizeActionPage(parent)\r\n{\r\n this->setupUi(this);\r\n set_lw_properties(lw_enabled_workbenches);\r\n set_lw_properties(lw_disabled_workbenches);\r\n const QString lw_disabled_name = QString::fromAscii(\"disabled workbenches\");\r\n lw_disabled_workbenches->setAccessibleName(lw_disabled_name);\r\n lw_disabled_workbenches->setSortingEnabled(true);\r\n\r\n QStringList enabled_wbs_list = load_enabled_workbenches();\r\n QStringList workbenches = Application::Instance->workbenches();\r\n\r\n for (QStringList::Iterator it = enabled_wbs_list.begin(); it != enabled_wbs_list.end(); ++it) {\r\n if (workbenches.contains(*it)) {\r\n QString wb = *it;\r\n add_workbench(lw_enabled_workbenches, wb);\r\n } else {\r\n qDebug() << \"Ignoring unknown \" << it->toLatin1() << \" workbench found in user preferences.\";\r\n }\r\n }\r\n for (QStringList::Iterator it = workbenches.begin(); it != workbenches.end(); ++it) {\r\n if (!enabled_wbs_list.contains(*it)){\r\n QString wb = *it;\r\n add_workbench(lw_disabled_workbenches, wb);\r\n }\r\n }\r\n lw_enabled_workbenches->setCurrentRow(0);\r\n lw_disabled_workbenches->setCurrentRow(0);\r\n}\r\n\r\n\/** Destroys the object and frees any allocated resources *\/\r\nDlgWorkbenchesImp::~DlgWorkbenchesImp()\r\n{\r\n}\r\n\r\nvoid DlgWorkbenchesImp::set_lw_properties(QListWidgetCustom *lw)\r\n{\r\n lw->setDragDropMode(QAbstractItemView::DragDrop);\r\n lw->setSelectionMode(QAbstractItemView::SingleSelection);\r\n lw->viewport()->setAcceptDrops(true);\r\n lw->setDropIndicatorShown(true);\r\n lw->setDragEnabled(true);\r\n lw->setDefaultDropAction(Qt::MoveAction);\r\n}\r\n\r\nvoid DlgWorkbenchesImp::add_workbench(QListWidgetCustom *lw, QString it)\r\n{\r\n QPixmap px = Application::Instance->workbenchIcon(it);\r\n QString mt = Application::Instance->workbenchMenuText(it);\r\n QListWidgetItem *wi = (new QListWidgetItem(QIcon(px), mt));\r\n wi->setData(Qt::UserRole, QVariant(it));\r\n lw->addItem(wi);\r\n}\r\n\r\nvoid DlgWorkbenchesImp::changeEvent(QEvent *e)\r\n{\r\n if (e->type() == QEvent::LanguageChange) {\r\n retranslateUi(this);\r\n }\r\n else {\r\n QWidget::changeEvent(e);\r\n }\r\n}\r\n\r\nvoid DlgWorkbenchesImp::hideEvent(QHideEvent * event)\r\n{\r\n save_enabled_workbenches();\r\n}\r\n\r\nvoid DlgWorkbenchesImp::onAddMacroAction(const QByteArray& macro)\r\n{\r\n}\r\n\r\nvoid DlgWorkbenchesImp::onRemoveMacroAction(const QByteArray& macro)\r\n{\r\n}\r\n\r\nvoid DlgWorkbenchesImp::onModifyMacroAction(const QByteArray& macro)\r\n{\r\n}\r\n\r\nvoid DlgWorkbenchesImp::move_workbench(QListWidgetCustom *lwc_dest,\r\n QListWidgetItem *wi)\r\n{\r\n QListWidgetItem* item = wi->clone();\r\n lwc_dest->addItem(item);\r\n lwc_dest->setCurrentItem(item);\r\n delete wi;\r\n}\r\n\r\nvoid DlgWorkbenchesImp::on_add_to_enabled_workbenches_btn_clicked()\r\n{\r\n QListWidgetItem* ci = lw_disabled_workbenches->currentItem();\r\n if (ci) {\r\n\tmove_workbench(lw_enabled_workbenches, ci);\r\n }\r\n}\r\n\r\nvoid DlgWorkbenchesImp::on_remove_from_enabled_workbenches_btn_clicked()\r\n{\r\n QListWidgetItem* ci = lw_enabled_workbenches->currentItem();\r\n if (ci) {\r\n\tmove_workbench(lw_disabled_workbenches, ci);\r\n }\r\n}\r\n\r\nvoid DlgWorkbenchesImp::shift_workbench(bool up)\r\n{\r\n int direction;\r\n if (up){\r\n direction = -1;\r\n } else {\r\n direction = 1;\r\n }\r\n if (lw_enabled_workbenches->currentItem()) {\r\n int index = lw_enabled_workbenches->currentRow();\r\n QListWidgetItem *item = lw_enabled_workbenches->takeItem(index);\r\n lw_enabled_workbenches->insertItem(index + direction, item);\r\n lw_enabled_workbenches->setCurrentRow(index + direction);\r\n }\r\n}\r\n\r\nvoid DlgWorkbenchesImp::on_shift_workbench_up_btn_clicked()\r\n{\r\n shift_workbench(true);\r\n}\r\n\r\nvoid DlgWorkbenchesImp::on_shift_workbench_down_btn_clicked()\r\n{\r\n shift_workbench(false);\r\n}\r\n\r\nvoid DlgWorkbenchesImp::on_sort_enabled_workbenches_btn_clicked()\r\n{\r\n lw_enabled_workbenches->sortItems();\r\n}\r\n\r\nvoid DlgWorkbenchesImp::on_add_all_to_enabled_workbenches_btn_clicked()\r\n{\r\n while (lw_disabled_workbenches->count() > 0) {\r\n QListWidgetItem* item = lw_disabled_workbenches->item(0);\r\n move_workbench(lw_enabled_workbenches, item);\r\n }\r\n}\r\n\r\nQStringList DlgWorkbenchesImp::load_enabled_workbenches()\r\n{\r\n QString enabled_wbs;\r\n QStringList enabled_wbs_list;\r\n ParameterGrp::handle hGrp;\r\n\r\n hGrp = App::GetApplication().GetParameterGroupByPath(\"User parameter:BaseApp\/Workbenches\");\r\n enabled_wbs = QString::fromStdString(hGrp->GetASCII(\"Enabled\", all_workbenches.toStdString().c_str()).c_str());\r\n enabled_wbs_list = enabled_wbs.split(QLatin1String(\",\"), QString::SkipEmptyParts);\r\n\r\n if (enabled_wbs_list.at(0) == all_workbenches) {\r\n enabled_wbs_list.removeFirst();\r\n QStringList workbenches = Application::Instance->workbenches();\r\n for (QStringList::Iterator it = workbenches.begin(); it != workbenches.end(); ++it) {\r\n enabled_wbs_list.append(*it);\r\n }\r\n enabled_wbs_list.sort();\r\n }\r\n return enabled_wbs_list;\r\n}\r\n\r\nvoid DlgWorkbenchesImp::save_enabled_workbenches()\r\n{\r\n QString enabled_wbs;\r\n ParameterGrp::handle hGrp;\r\n\r\n hGrp = App::GetApplication().GetParameterGroupByPath(\"User parameter:BaseApp\/Workbenches\");\r\n hGrp->Clear();\r\n\r\n if (lw_enabled_workbenches->count() == 0) {\r\n enabled_wbs.append(QString::fromAscii(\"NoneWorkbench\"));\r\n } else {\r\n for (int i = 0; i < lw_enabled_workbenches->count(); i++) {\r\n QVariant item_data = lw_enabled_workbenches->item(i)->data(Qt::UserRole);\r\n QString name = item_data.toString();\r\n enabled_wbs.append(name + QString::fromAscii(\",\"));\r\n }\r\n }\r\n hGrp->SetASCII(\"Enabled\", enabled_wbs.toAscii());\r\n}\r\n\r\n#include \"moc_DlgWorkbenchesImp.cpp\"\r\n\r\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright Daniel Wallin 2006. Use, modification and distribution is\n\/\/ subject to the Boost Software License, Version 1.0. (See accompanying\n\/\/ file LICENSE_1_0.txt or copy at http:\/\/www.boost.org\/LICENSE_1_0.txt)\n\n#include <libtorrent\/torrent_handle.hpp>\n#include <boost\/python.hpp>\n#include <boost\/lexical_cast.hpp>\n#include \"gil.hpp\"\n\nusing namespace boost::python;\nusing namespace libtorrent;\n\nnamespace\n{\n\n list url_seeds(torrent_handle& handle)\n {\n list ret;\n std::set<std::string> urls;\n {\n allow_threading_guard guard;\n urls = handle.url_seeds();\n }\n\n for (std::set<std::string>::iterator i(urls.begin())\n , end(urls.end()); i != end; ++i)\n ret.append(*i);\n return ret;\n }\n\n list piece_availability(torrent_handle& handle)\n {\n list ret;\n std::vector<int> avail;\n {\n allow_threading_guard guard;\n handle.piece_availability(avail);\n }\n\n for (std::vector<int>::iterator i(avail.begin())\n , end(avail.end()); i != end; ++i)\n ret.append(*i);\n return ret;\n }\n\n list piece_priorities(torrent_handle& handle)\n {\n list ret;\n std::vector<int> prio;\n {\n allow_threading_guard guard;\n prio = handle.piece_priorities();\n }\n\n for (std::vector<int>::iterator i(prio.begin())\n , end(prio.end()); i != end; ++i)\n ret.append(*i);\n return ret;\n }\n\n std::vector<announce_entry>::const_iterator begin_trackers(torrent_handle& i)\n {\n allow_threading_guard guard;\n return i.trackers().begin();\n }\n\n std::vector<announce_entry>::const_iterator end_trackers(torrent_handle& i)\n {\n allow_threading_guard guard;\n return i.trackers().end();\n }\n\n} \/\/ namespace unnamed\n\nlist file_progress(torrent_handle& handle)\n{\n std::vector<float> p;\n\n {\n allow_threading_guard guard;\n p.reserve(handle.get_torrent_info().num_files());\n handle.file_progress(p);\n }\n\n list result;\n\n for (std::vector<float>::iterator i(p.begin()), e(p.end()); i != e; ++i)\n result.append(*i);\n\n return result;\n}\n\nlist get_peer_info(torrent_handle const& handle)\n{\n std::vector<peer_info> pi;\n\n {\n allow_threading_guard guard;\n handle.get_peer_info(pi);\n }\n\n list result;\n\n for (std::vector<peer_info>::iterator i = pi.begin(); i != pi.end(); ++i)\n result.append(*i);\n\n return result;\n}\n\nvoid prioritize_pieces(torrent_handle& info, object o)\n{\n std::vector<int> result;\n try\n {\n object iter_obj = object( handle<>( PyObject_GetIter( o.ptr() ) ));\n while( 1 )\n {\n object obj = extract<object>( iter_obj.attr( \"next\" )() );\n result.push_back(extract<int const>( obj ));\n }\n }\n catch( error_already_set )\n {\n PyErr_Clear();\n info.prioritize_pieces(result);\n return;\n }\n}\n\nvoid prioritize_files(torrent_handle& info, object o)\n{\n std::vector<int> result;\n try\n {\n object iter_obj = object( handle<>( PyObject_GetIter( o.ptr() ) ));\n while( 1 )\n {\n object obj = extract<object>( iter_obj.attr( \"next\" )() );\n result.push_back(extract<int const>( obj ));\n }\n }\n catch( error_already_set )\n {\n PyErr_Clear();\n info.prioritize_files(result);\n return;\n }\n}\n\n\nvoid replace_trackers(torrent_handle& info, object trackers)\n{\n object iter(trackers.attr(\"__iter__\")());\n\n std::vector<announce_entry> result;\n\n for (;;)\n {\n handle<> entry(allow_null(PyIter_Next(iter.ptr())));\n\n if (entry == handle<>())\n break;\n\n result.push_back(extract<announce_entry const&>(object(entry)));\n }\n\n allow_threading_guard guard;\n info.replace_trackers(result);\n}\n\nlist get_download_queue(torrent_handle& handle)\n{\n list ret;\n\n std::vector<partial_piece_info> downloading;\n\n {\n allow_threading_guard guard;\n handle.get_download_queue(downloading);\n }\n\n for (std::vector<partial_piece_info>::iterator i = downloading.begin()\n , end(downloading.end()); i != end; ++i)\n {\n dict partial_piece;\n partial_piece[\"piece_index\"] = i->piece_index;\n partial_piece[\"blocks_in_piece\"] = i->blocks_in_piece;\n list block_list;\n for (int k = 0; k < i->blocks_in_piece; ++k)\n {\n dict block_info;\n block_info[\"state\"] = i->blocks[k].state;\n block_info[\"num_peers\"] = i->blocks[k].num_peers;\n block_info[\"bytes_progress\"] = i->blocks[k].bytes_progress;\n block_info[\"block_size\"] = i->blocks[k].block_size;\n block_info[\"peer\"] = std::make_pair(\n boost::lexical_cast<std::string>(i->blocks[k].peer.address()), i->blocks[k].peer.port());\n block_list.append(block_info);\n }\n partial_piece[\"blocks\"] = block_list;\n\n ret.append(partial_piece);\n }\n\n return ret;\n}\n\nnamespace\n{\n tcp::endpoint tuple_to_endpoint(tuple const& t)\n {\n return tcp::endpoint(address::from_string(extract<std::string>(t[0])), extract<int>(t[1]));\n }\n}\n\nvoid force_reannounce(torrent_handle& th, int s)\n{\n th.force_reannounce(boost::posix_time::seconds(s));\n}\n\nvoid connect_peer(torrent_handle& th, tuple ip, int source)\n{\n th.connect_peer(tuple_to_endpoint(ip), source);\n}\n\nvoid set_peer_upload_limit(torrent_handle& th, tuple const& ip, int limit)\n{\n th.set_peer_upload_limit(tuple_to_endpoint(ip), limit);\n}\n\nvoid set_peer_download_limit(torrent_handle& th, tuple const& ip, int limit)\n{\n th.set_peer_download_limit(tuple_to_endpoint(ip), limit);\n}\n\nvoid bind_torrent_handle()\n{\n void (torrent_handle::*force_reannounce0)() const = &torrent_handle::force_reannounce;\n\n int (torrent_handle::*piece_priority0)(int) const = &torrent_handle::piece_priority;\n void (torrent_handle::*piece_priority1)(int, int) const = &torrent_handle::piece_priority;\n\n#ifndef TORRENT_DISABLE_RESOLVE_COUNTRIES\t\n bool (torrent_handle::*resolve_countries0)() const = &torrent_handle::resolve_countries;\n void (torrent_handle::*resolve_countries1)(bool) = &torrent_handle::resolve_countries;\n#endif\n\n return_value_policy<copy_const_reference> copy;\n\n#define _ allow_threads\n\n class_<torrent_handle>(\"torrent_handle\")\n .def(\"get_peer_info\", get_peer_info)\n .def(\"status\", _(&torrent_handle::status))\n .def(\"get_download_queue\", get_download_queue)\n .def(\"file_progress\", file_progress)\n .def(\"trackers\", range(begin_trackers, end_trackers))\n .def(\"replace_trackers\", replace_trackers)\n .def(\"add_url_seed\", _(&torrent_handle::add_url_seed))\n .def(\"remove_url_seed\", _(&torrent_handle::remove_url_seed))\n .def(\"url_seeds\", url_seeds)\n .def(\"has_metadata\", _(&torrent_handle::has_metadata))\n .def(\"get_torrent_info\", _(&torrent_handle::get_torrent_info), return_internal_reference<>())\n .def(\"is_valid\", _(&torrent_handle::is_valid))\n .def(\"is_seed\", _(&torrent_handle::is_seed))\n .def(\"is_finished\", _(&torrent_handle::is_finished))\n .def(\"is_paused\", _(&torrent_handle::is_paused))\n .def(\"pause\", _(&torrent_handle::pause))\n .def(\"resume\", _(&torrent_handle::resume))\n \n .def_readonly(\"is_auto_managed\", _(&torrent_handle::is_auto_managed))\n .def(\"auto_managed\", _(&torrent_handle::auto_managed))\n .def_readonly(\"queue_position\", _(&torrent_handle::queue_position))\n .def(\"queue_position_up\", _(&torrent_handle::queue_position_up))\n .def(\"queue_position_down\", _(&torrent_handle::queue_position_down))\n .def(\"queue_position_top\", _(&torrent_handle::queue_position_top))\n .def(\"queue_position_bottom\", _(&torrent_handle::queue_position_bottom))\n \n#ifndef TORRENT_DISABLE_RESOLVE_COUNTRIES\t\n .def(\"resolve_countries\", _(resolve_countries0))\n .def(\"resolve_countries\", _(resolve_countries1))\n#endif\n \/\/ deprecated\n .def(\"filter_piece\", _(&torrent_handle::filter_piece))\n .def(\"is_piece_filtered\", _(&torrent_handle::is_piece_filtered))\n\n .def(\"piece_availability\", piece_availability)\n .def(\"piece_priority\", _(piece_priority0))\n .def(\"piece_priority\", _(piece_priority1))\n .def(\"prioritize_pieces\", prioritize_pieces)\n .def(\"piece_prioritize\", piece_priorities)\n .def(\"prioritize_files\", prioritize_files)\n .def(\"use_interface\", &torrent_handle::use_interface)\n .def(\"write_resume_data\", _(&torrent_handle::write_resume_data))\n .def(\"save_resume_data\", _(&torrent_handle::save_resume_data))\n .def(\"force_reannounce\", _(force_reannounce0))\n .def(\"force_reannounce\", force_reannounce)\n .def(\"scrape_tracker\", _(&torrent_handle::scrape_tracker))\n .def(\"name\", _(&torrent_handle::name))\n .def(\"set_upload_limit\", _(&torrent_handle::set_upload_limit))\n .def(\"upload_limit\", _(&torrent_handle::upload_limit))\n .def(\"set_download_limit\", _(&torrent_handle::set_download_limit))\n .def(\"download_limit\", _(&torrent_handle::download_limit))\n .def(\"set_sequential_download\", _(&torrent_handle::set_sequential_download))\n .def(\"set_peer_upload_limit\", set_peer_upload_limit)\n .def(\"set_peer_download_limit\", set_peer_download_limit)\n .def(\"connect_peer\", connect_peer)\n .def(\"set_ratio\", _(&torrent_handle::set_ratio))\n .def(\"save_path\", _(&torrent_handle::save_path))\n .def(\"set_max_uploads\", _(&torrent_handle::set_max_uploads))\n .def(\"set_max_connections\", _(&torrent_handle::set_max_connections))\n .def(\"set_tracker_login\", _(&torrent_handle::set_tracker_login))\n .def(\"move_storage\", _(&torrent_handle::move_storage))\n .def(\"info_hash\", _(&torrent_handle::info_hash))\n ;\n}\n\n<commit_msg>Fix issue with is_auto_managed and queue_position<commit_after>\/\/ Copyright Daniel Wallin 2006. Use, modification and distribution is\n\/\/ subject to the Boost Software License, Version 1.0. (See accompanying\n\/\/ file LICENSE_1_0.txt or copy at http:\/\/www.boost.org\/LICENSE_1_0.txt)\n\n#include <libtorrent\/torrent_handle.hpp>\n#include <boost\/python.hpp>\n#include <boost\/lexical_cast.hpp>\n#include \"gil.hpp\"\n\nusing namespace boost::python;\nusing namespace libtorrent;\n\nnamespace\n{\n\n list url_seeds(torrent_handle& handle)\n {\n list ret;\n std::set<std::string> urls;\n {\n allow_threading_guard guard;\n urls = handle.url_seeds();\n }\n\n for (std::set<std::string>::iterator i(urls.begin())\n , end(urls.end()); i != end; ++i)\n ret.append(*i);\n return ret;\n }\n\n list piece_availability(torrent_handle& handle)\n {\n list ret;\n std::vector<int> avail;\n {\n allow_threading_guard guard;\n handle.piece_availability(avail);\n }\n\n for (std::vector<int>::iterator i(avail.begin())\n , end(avail.end()); i != end; ++i)\n ret.append(*i);\n return ret;\n }\n\n list piece_priorities(torrent_handle& handle)\n {\n list ret;\n std::vector<int> prio;\n {\n allow_threading_guard guard;\n prio = handle.piece_priorities();\n }\n\n for (std::vector<int>::iterator i(prio.begin())\n , end(prio.end()); i != end; ++i)\n ret.append(*i);\n return ret;\n }\n\n std::vector<announce_entry>::const_iterator begin_trackers(torrent_handle& i)\n {\n allow_threading_guard guard;\n return i.trackers().begin();\n }\n\n std::vector<announce_entry>::const_iterator end_trackers(torrent_handle& i)\n {\n allow_threading_guard guard;\n return i.trackers().end();\n }\n\n} \/\/ namespace unnamed\n\nlist file_progress(torrent_handle& handle)\n{\n std::vector<float> p;\n\n {\n allow_threading_guard guard;\n p.reserve(handle.get_torrent_info().num_files());\n handle.file_progress(p);\n }\n\n list result;\n\n for (std::vector<float>::iterator i(p.begin()), e(p.end()); i != e; ++i)\n result.append(*i);\n\n return result;\n}\n\nlist get_peer_info(torrent_handle const& handle)\n{\n std::vector<peer_info> pi;\n\n {\n allow_threading_guard guard;\n handle.get_peer_info(pi);\n }\n\n list result;\n\n for (std::vector<peer_info>::iterator i = pi.begin(); i != pi.end(); ++i)\n result.append(*i);\n\n return result;\n}\n\nvoid prioritize_pieces(torrent_handle& info, object o)\n{\n std::vector<int> result;\n try\n {\n object iter_obj = object( handle<>( PyObject_GetIter( o.ptr() ) ));\n while( 1 )\n {\n object obj = extract<object>( iter_obj.attr( \"next\" )() );\n result.push_back(extract<int const>( obj ));\n }\n }\n catch( error_already_set )\n {\n PyErr_Clear();\n info.prioritize_pieces(result);\n return;\n }\n}\n\nvoid prioritize_files(torrent_handle& info, object o)\n{\n std::vector<int> result;\n try\n {\n object iter_obj = object( handle<>( PyObject_GetIter( o.ptr() ) ));\n while( 1 )\n {\n object obj = extract<object>( iter_obj.attr( \"next\" )() );\n result.push_back(extract<int const>( obj ));\n }\n }\n catch( error_already_set )\n {\n PyErr_Clear();\n info.prioritize_files(result);\n return;\n }\n}\n\n\nvoid replace_trackers(torrent_handle& info, object trackers)\n{\n object iter(trackers.attr(\"__iter__\")());\n\n std::vector<announce_entry> result;\n\n for (;;)\n {\n handle<> entry(allow_null(PyIter_Next(iter.ptr())));\n\n if (entry == handle<>())\n break;\n\n result.push_back(extract<announce_entry const&>(object(entry)));\n }\n\n allow_threading_guard guard;\n info.replace_trackers(result);\n}\n\nlist get_download_queue(torrent_handle& handle)\n{\n list ret;\n\n std::vector<partial_piece_info> downloading;\n\n {\n allow_threading_guard guard;\n handle.get_download_queue(downloading);\n }\n\n for (std::vector<partial_piece_info>::iterator i = downloading.begin()\n , end(downloading.end()); i != end; ++i)\n {\n dict partial_piece;\n partial_piece[\"piece_index\"] = i->piece_index;\n partial_piece[\"blocks_in_piece\"] = i->blocks_in_piece;\n list block_list;\n for (int k = 0; k < i->blocks_in_piece; ++k)\n {\n dict block_info;\n block_info[\"state\"] = i->blocks[k].state;\n block_info[\"num_peers\"] = i->blocks[k].num_peers;\n block_info[\"bytes_progress\"] = i->blocks[k].bytes_progress;\n block_info[\"block_size\"] = i->blocks[k].block_size;\n block_info[\"peer\"] = std::make_pair(\n boost::lexical_cast<std::string>(i->blocks[k].peer.address()), i->blocks[k].peer.port());\n block_list.append(block_info);\n }\n partial_piece[\"blocks\"] = block_list;\n\n ret.append(partial_piece);\n }\n\n return ret;\n}\n\nnamespace\n{\n tcp::endpoint tuple_to_endpoint(tuple const& t)\n {\n return tcp::endpoint(address::from_string(extract<std::string>(t[0])), extract<int>(t[1]));\n }\n}\n\nvoid force_reannounce(torrent_handle& th, int s)\n{\n th.force_reannounce(boost::posix_time::seconds(s));\n}\n\nvoid connect_peer(torrent_handle& th, tuple ip, int source)\n{\n th.connect_peer(tuple_to_endpoint(ip), source);\n}\n\nvoid set_peer_upload_limit(torrent_handle& th, tuple const& ip, int limit)\n{\n th.set_peer_upload_limit(tuple_to_endpoint(ip), limit);\n}\n\nvoid set_peer_download_limit(torrent_handle& th, tuple const& ip, int limit)\n{\n th.set_peer_download_limit(tuple_to_endpoint(ip), limit);\n}\n\nvoid bind_torrent_handle()\n{\n void (torrent_handle::*force_reannounce0)() const = &torrent_handle::force_reannounce;\n\n int (torrent_handle::*piece_priority0)(int) const = &torrent_handle::piece_priority;\n void (torrent_handle::*piece_priority1)(int, int) const = &torrent_handle::piece_priority;\n\n#ifndef TORRENT_DISABLE_RESOLVE_COUNTRIES\t\n bool (torrent_handle::*resolve_countries0)() const = &torrent_handle::resolve_countries;\n void (torrent_handle::*resolve_countries1)(bool) = &torrent_handle::resolve_countries;\n#endif\n\n return_value_policy<copy_const_reference> copy;\n\n#define _ allow_threads\n\n class_<torrent_handle>(\"torrent_handle\")\n .def(\"get_peer_info\", get_peer_info)\n .def(\"status\", _(&torrent_handle::status))\n .def(\"get_download_queue\", get_download_queue)\n .def(\"file_progress\", file_progress)\n .def(\"trackers\", range(begin_trackers, end_trackers))\n .def(\"replace_trackers\", replace_trackers)\n .def(\"add_url_seed\", _(&torrent_handle::add_url_seed))\n .def(\"remove_url_seed\", _(&torrent_handle::remove_url_seed))\n .def(\"url_seeds\", url_seeds)\n .def(\"has_metadata\", _(&torrent_handle::has_metadata))\n .def(\"get_torrent_info\", _(&torrent_handle::get_torrent_info), return_internal_reference<>())\n .def(\"is_valid\", _(&torrent_handle::is_valid))\n .def(\"is_seed\", _(&torrent_handle::is_seed))\n .def(\"is_finished\", _(&torrent_handle::is_finished))\n .def(\"is_paused\", _(&torrent_handle::is_paused))\n .def(\"pause\", _(&torrent_handle::pause))\n .def(\"resume\", _(&torrent_handle::resume))\n \n .def(\"is_auto_managed\", _(&torrent_handle::is_auto_managed))\n .def(\"auto_managed\", _(&torrent_handle::auto_managed))\n .def(\"queue_position\", _(&torrent_handle::queue_position))\n .def(\"queue_position_up\", _(&torrent_handle::queue_position_up))\n .def(\"queue_position_down\", _(&torrent_handle::queue_position_down))\n .def(\"queue_position_top\", _(&torrent_handle::queue_position_top))\n .def(\"queue_position_bottom\", _(&torrent_handle::queue_position_bottom))\n \n#ifndef TORRENT_DISABLE_RESOLVE_COUNTRIES\t\n .def(\"resolve_countries\", _(resolve_countries0))\n .def(\"resolve_countries\", _(resolve_countries1))\n#endif\n \/\/ deprecated\n .def(\"filter_piece\", _(&torrent_handle::filter_piece))\n .def(\"is_piece_filtered\", _(&torrent_handle::is_piece_filtered))\n\n .def(\"piece_availability\", piece_availability)\n .def(\"piece_priority\", _(piece_priority0))\n .def(\"piece_priority\", _(piece_priority1))\n .def(\"prioritize_pieces\", prioritize_pieces)\n .def(\"piece_prioritize\", piece_priorities)\n .def(\"prioritize_files\", prioritize_files)\n .def(\"use_interface\", &torrent_handle::use_interface)\n .def(\"write_resume_data\", _(&torrent_handle::write_resume_data))\n .def(\"save_resume_data\", _(&torrent_handle::save_resume_data))\n .def(\"force_reannounce\", _(force_reannounce0))\n .def(\"force_reannounce\", force_reannounce)\n .def(\"scrape_tracker\", _(&torrent_handle::scrape_tracker))\n .def(\"name\", _(&torrent_handle::name))\n .def(\"set_upload_limit\", _(&torrent_handle::set_upload_limit))\n .def(\"upload_limit\", _(&torrent_handle::upload_limit))\n .def(\"set_download_limit\", _(&torrent_handle::set_download_limit))\n .def(\"download_limit\", _(&torrent_handle::download_limit))\n .def(\"set_sequential_download\", _(&torrent_handle::set_sequential_download))\n .def(\"set_peer_upload_limit\", set_peer_upload_limit)\n .def(\"set_peer_download_limit\", set_peer_download_limit)\n .def(\"connect_peer\", connect_peer)\n .def(\"set_ratio\", _(&torrent_handle::set_ratio))\n .def(\"save_path\", _(&torrent_handle::save_path))\n .def(\"set_max_uploads\", _(&torrent_handle::set_max_uploads))\n .def(\"set_max_connections\", _(&torrent_handle::set_max_connections))\n .def(\"set_tracker_login\", _(&torrent_handle::set_tracker_login))\n .def(\"move_storage\", _(&torrent_handle::move_storage))\n .def(\"info_hash\", _(&torrent_handle::info_hash))\n ;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright Daniel Wallin 2006. Use, modification and distribution is\n\/\/ subject to the Boost Software License, Version 1.0. (See accompanying\n\/\/ file LICENSE_1_0.txt or copy at http:\/\/www.boost.org\/LICENSE_1_0.txt)\n\n#include <libtorrent\/torrent_handle.hpp>\n#include <boost\/python.hpp>\n#include <boost\/lexical_cast.hpp>\n#include \"gil.hpp\"\n\nusing namespace boost::python;\nusing namespace libtorrent;\n\nnamespace\n{\n\n list url_seeds(torrent_handle& handle)\n {\n list ret;\n std::set<std::string> urls;\n {\n allow_threading_guard guard;\n urls = handle.url_seeds();\n }\n\n for (std::set<std::string>::iterator i(urls.begin())\n , end(urls.end()); i != end; ++i)\n ret.append(*i);\n return ret;\n }\n\n list piece_availability(torrent_handle& handle)\n {\n list ret;\n std::vector<int> avail;\n {\n allow_threading_guard guard;\n handle.piece_availability(avail);\n }\n\n for (std::vector<int>::iterator i(avail.begin())\n , end(avail.end()); i != end; ++i)\n ret.append(*i);\n return ret;\n }\n\n list piece_priorities(torrent_handle& handle)\n {\n list ret;\n std::vector<int> prio;\n {\n allow_threading_guard guard;\n prio = handle.piece_priorities();\n }\n\n for (std::vector<int>::iterator i(prio.begin())\n , end(prio.end()); i != end; ++i)\n ret.append(*i);\n return ret;\n }\n\n std::vector<announce_entry>::const_iterator begin_trackers(torrent_handle& i)\n {\n allow_threading_guard guard;\n return i.trackers().begin();\n }\n\n std::vector<announce_entry>::const_iterator end_trackers(torrent_handle& i)\n {\n allow_threading_guard guard;\n return i.trackers().end();\n }\n\n} \/\/ namespace unnamed\n\nlist file_progress(torrent_handle& handle)\n{\n std::vector<float> p;\n\n {\n allow_threading_guard guard;\n p.reserve(handle.get_torrent_info().num_files());\n handle.file_progress(p);\n }\n\n list result;\n\n for (std::vector<float>::iterator i(p.begin()), e(p.end()); i != e; ++i)\n result.append(*i);\n\n return result;\n}\n\nlist get_peer_info(torrent_handle const& handle)\n{\n std::vector<peer_info> pi;\n\n {\n allow_threading_guard guard;\n handle.get_peer_info(pi);\n }\n\n list result;\n\n for (std::vector<peer_info>::iterator i = pi.begin(); i != pi.end(); ++i)\n result.append(*i);\n\n return result;\n}\n\nvoid prioritize_pieces(torrent_handle& info, object o)\n{\n std::vector<int> result;\n try\n {\n object iter_obj = object( handle<>( PyObject_GetIter( o.ptr() ) ));\n while( 1 )\n {\n object obj = extract<object>( iter_obj.attr( \"next\" )() );\n result.push_back(extract<int const>( obj ));\n }\n }\n catch( error_already_set )\n {\n PyErr_Clear();\n info.prioritize_pieces(result);\n return;\n }\n}\n\nvoid prioritize_files(torrent_handle& info, object o)\n{\n std::vector<int> result;\n try\n {\n object iter_obj = object( handle<>( PyObject_GetIter( o.ptr() ) ));\n while( 1 )\n {\n object obj = extract<object>( iter_obj.attr( \"next\" )() );\n result.push_back(extract<int const>( obj ));\n }\n }\n catch( error_already_set )\n {\n PyErr_Clear();\n info.prioritize_files(result);\n return;\n }\n}\n\n\nvoid replace_trackers(torrent_handle& info, object trackers)\n{\n object iter(trackers.attr(\"__iter__\")());\n\n std::vector<announce_entry> result;\n\n for (;;)\n {\n handle<> entry(allow_null(PyIter_Next(iter.ptr())));\n\n if (entry == handle<>())\n break;\n\n result.push_back(extract<announce_entry const&>(object(entry)));\n }\n\n allow_threading_guard guard;\n info.replace_trackers(result);\n}\n\nlist get_download_queue(torrent_handle& handle)\n{\n list ret;\n\n std::vector<partial_piece_info> downloading;\n\n {\n allow_threading_guard guard;\n handle.get_download_queue(downloading);\n }\n\n for (std::vector<partial_piece_info>::iterator i = downloading.begin()\n , end(downloading.end()); i != end; ++i)\n {\n dict partial_piece;\n partial_piece[\"piece_index\"] = i->piece_index;\n partial_piece[\"blocks_in_piece\"] = i->blocks_in_piece;\n list block_list;\n for (int k = 0; k < i->blocks_in_piece; ++k)\n {\n dict block_info;\n block_info[\"state\"] = i->blocks[k].state;\n block_info[\"num_peers\"] = i->blocks[k].num_peers;\n block_info[\"bytes_progress\"] = i->blocks[k].bytes_progress;\n block_info[\"block_size\"] = i->blocks[k].block_size;\n block_info[\"peer\"] = std::make_pair(\n boost::lexical_cast<std::string>(i->blocks[k].peer.address()), i->blocks[k].peer.port());\n block_list.append(block_info);\n }\n partial_piece[\"blocks\"] = block_list;\n\n ret.append(partial_piece);\n }\n\n return ret;\n}\n\nnamespace\n{\n tcp::endpoint tuple_to_endpoint(tuple const& t)\n {\n return tcp::endpoint(address::from_string(extract<std::string>(t[0])), extract<int>(t[1]));\n }\n}\n\nvoid force_reannounce(torrent_handle& th, int s)\n{\n th.force_reannounce(boost::posix_time::seconds(s));\n}\n\nvoid connect_peer(torrent_handle& th, tuple ip, int source)\n{\n th.connect_peer(tuple_to_endpoint(ip), source);\n}\n\nvoid set_peer_upload_limit(torrent_handle& th, tuple const& ip, int limit)\n{\n th.set_peer_upload_limit(tuple_to_endpoint(ip), limit);\n}\n\nvoid set_peer_download_limit(torrent_handle& th, tuple const& ip, int limit)\n{\n th.set_peer_download_limit(tuple_to_endpoint(ip), limit);\n}\n\nvoid bind_torrent_handle()\n{\n void (torrent_handle::*force_reannounce0)() const = &torrent_handle::force_reannounce;\n\n int (torrent_handle::*piece_priority0)(int) const = &torrent_handle::piece_priority;\n void (torrent_handle::*piece_priority1)(int, int) const = &torrent_handle::piece_priority;\n\n#ifndef TORRENT_DISABLE_RESOLVE_COUNTRIES\t\n bool (torrent_handle::*resolve_countries0)() const = &torrent_handle::resolve_countries;\n void (torrent_handle::*resolve_countries1)(bool) = &torrent_handle::resolve_countries;\n#endif\n\n return_value_policy<copy_const_reference> copy;\n\n#define _ allow_threads\n\n class_<torrent_handle>(\"torrent_handle\")\n .def(\"get_peer_info\", get_peer_info)\n .def(\"status\", _(&torrent_handle::status))\n .def(\"get_download_queue\", get_download_queue)\n .def(\"file_progress\", file_progress)\n .def(\"trackers\", range(begin_trackers, end_trackers))\n .def(\"replace_trackers\", replace_trackers)\n .def(\"add_url_seed\", _(&torrent_handle::add_url_seed))\n .def(\"remove_url_seed\", _(&torrent_handle::remove_url_seed))\n .def(\"url_seeds\", url_seeds)\n .def(\"has_metadata\", _(&torrent_handle::has_metadata))\n .def(\"get_torrent_info\", _(&torrent_handle::get_torrent_info), return_internal_reference<>())\n .def(\"is_valid\", _(&torrent_handle::is_valid))\n .def(\"is_seed\", _(&torrent_handle::is_seed))\n .def(\"is_finished\", _(&torrent_handle::is_finished))\n .def(\"is_paused\", _(&torrent_handle::is_paused))\n .def(\"pause\", _(&torrent_handle::pause))\n .def(\"resume\", _(&torrent_handle::resume))\n \n .def_readonly(\"is_auto_managed\", _(&torrent_handle::is_auto_managed))\n .def(\"auto_managed\", _(&torrent_handle::auto_managed))\n .def_readonly(\"queue_position\", _(&torrent_handle::queue_position))\n .def(\"queue_position_up\", _(&torrent_handle::queue_position_up))\n .def(\"queue_position_down\", _(&torrent_handle::queue_position_down))\n .def(\"queue_position_top\", _(&torrent_handle::queue_position_top))\n .def(\"queue_position_bottom\", _(&torrent_handle::queue_position_bottom))\n \n#ifndef TORRENT_DISABLE_RESOLVE_COUNTRIES\t\n .def(\"resolve_countries\", _(resolve_countries0))\n .def(\"resolve_countries\", _(resolve_countries1))\n#endif\n \/\/ deprecated\n .def(\"filter_piece\", _(&torrent_handle::filter_piece))\n .def(\"is_piece_filtered\", _(&torrent_handle::is_piece_filtered))\n\n .def(\"piece_availability\", piece_availability)\n .def(\"piece_priority\", _(piece_priority0))\n .def(\"piece_priority\", _(piece_priority1))\n .def(\"prioritize_pieces\", prioritize_pieces)\n .def(\"piece_prioritize\", piece_priorities)\n .def(\"prioritize_files\", prioritize_files)\n .def(\"use_interface\", &torrent_handle::use_interface)\n .def(\"write_resume_data\", _(&torrent_handle::write_resume_data))\n .def(\"save_resume_data\", _(&torrent_handle::save_resume_data))\n .def(\"force_reannounce\", _(force_reannounce0))\n .def(\"force_reannounce\", force_reannounce)\n .def(\"scrape_tracker\", _(&torrent_handle::scrape_tracker))\n .def(\"name\", _(&torrent_handle::name))\n .def(\"set_upload_limit\", _(&torrent_handle::set_upload_limit))\n .def(\"upload_limit\", _(&torrent_handle::upload_limit))\n .def(\"set_download_limit\", _(&torrent_handle::set_download_limit))\n .def(\"download_limit\", _(&torrent_handle::download_limit))\n .def(\"set_sequential_download\", _(&torrent_handle::set_sequential_download))\n .def(\"set_peer_upload_limit\", set_peer_upload_limit)\n .def(\"set_peer_download_limit\", set_peer_download_limit)\n .def(\"connect_peer\", connect_peer)\n .def(\"set_ratio\", _(&torrent_handle::set_ratio))\n .def(\"save_path\", _(&torrent_handle::save_path))\n .def(\"set_max_uploads\", _(&torrent_handle::set_max_uploads))\n .def(\"set_max_connections\", _(&torrent_handle::set_max_connections))\n .def(\"set_tracker_login\", _(&torrent_handle::set_tracker_login))\n .def(\"move_storage\", _(&torrent_handle::move_storage))\n .def(\"info_hash\", _(&torrent_handle::info_hash))\n ;\n}\n\n<commit_msg>Fix issue with is_auto_managed and queue_position<commit_after>\/\/ Copyright Daniel Wallin 2006. Use, modification and distribution is\n\/\/ subject to the Boost Software License, Version 1.0. (See accompanying\n\/\/ file LICENSE_1_0.txt or copy at http:\/\/www.boost.org\/LICENSE_1_0.txt)\n\n#include <libtorrent\/torrent_handle.hpp>\n#include <boost\/python.hpp>\n#include <boost\/lexical_cast.hpp>\n#include \"gil.hpp\"\n\nusing namespace boost::python;\nusing namespace libtorrent;\n\nnamespace\n{\n\n list url_seeds(torrent_handle& handle)\n {\n list ret;\n std::set<std::string> urls;\n {\n allow_threading_guard guard;\n urls = handle.url_seeds();\n }\n\n for (std::set<std::string>::iterator i(urls.begin())\n , end(urls.end()); i != end; ++i)\n ret.append(*i);\n return ret;\n }\n\n list piece_availability(torrent_handle& handle)\n {\n list ret;\n std::vector<int> avail;\n {\n allow_threading_guard guard;\n handle.piece_availability(avail);\n }\n\n for (std::vector<int>::iterator i(avail.begin())\n , end(avail.end()); i != end; ++i)\n ret.append(*i);\n return ret;\n }\n\n list piece_priorities(torrent_handle& handle)\n {\n list ret;\n std::vector<int> prio;\n {\n allow_threading_guard guard;\n prio = handle.piece_priorities();\n }\n\n for (std::vector<int>::iterator i(prio.begin())\n , end(prio.end()); i != end; ++i)\n ret.append(*i);\n return ret;\n }\n\n std::vector<announce_entry>::const_iterator begin_trackers(torrent_handle& i)\n {\n allow_threading_guard guard;\n return i.trackers().begin();\n }\n\n std::vector<announce_entry>::const_iterator end_trackers(torrent_handle& i)\n {\n allow_threading_guard guard;\n return i.trackers().end();\n }\n\n} \/\/ namespace unnamed\n\nlist file_progress(torrent_handle& handle)\n{\n std::vector<float> p;\n\n {\n allow_threading_guard guard;\n p.reserve(handle.get_torrent_info().num_files());\n handle.file_progress(p);\n }\n\n list result;\n\n for (std::vector<float>::iterator i(p.begin()), e(p.end()); i != e; ++i)\n result.append(*i);\n\n return result;\n}\n\nlist get_peer_info(torrent_handle const& handle)\n{\n std::vector<peer_info> pi;\n\n {\n allow_threading_guard guard;\n handle.get_peer_info(pi);\n }\n\n list result;\n\n for (std::vector<peer_info>::iterator i = pi.begin(); i != pi.end(); ++i)\n result.append(*i);\n\n return result;\n}\n\nvoid prioritize_pieces(torrent_handle& info, object o)\n{\n std::vector<int> result;\n try\n {\n object iter_obj = object( handle<>( PyObject_GetIter( o.ptr() ) ));\n while( 1 )\n {\n object obj = extract<object>( iter_obj.attr( \"next\" )() );\n result.push_back(extract<int const>( obj ));\n }\n }\n catch( error_already_set )\n {\n PyErr_Clear();\n info.prioritize_pieces(result);\n return;\n }\n}\n\nvoid prioritize_files(torrent_handle& info, object o)\n{\n std::vector<int> result;\n try\n {\n object iter_obj = object( handle<>( PyObject_GetIter( o.ptr() ) ));\n while( 1 )\n {\n object obj = extract<object>( iter_obj.attr( \"next\" )() );\n result.push_back(extract<int const>( obj ));\n }\n }\n catch( error_already_set )\n {\n PyErr_Clear();\n info.prioritize_files(result);\n return;\n }\n}\n\n\nvoid replace_trackers(torrent_handle& info, object trackers)\n{\n object iter(trackers.attr(\"__iter__\")());\n\n std::vector<announce_entry> result;\n\n for (;;)\n {\n handle<> entry(allow_null(PyIter_Next(iter.ptr())));\n\n if (entry == handle<>())\n break;\n\n result.push_back(extract<announce_entry const&>(object(entry)));\n }\n\n allow_threading_guard guard;\n info.replace_trackers(result);\n}\n\nlist get_download_queue(torrent_handle& handle)\n{\n list ret;\n\n std::vector<partial_piece_info> downloading;\n\n {\n allow_threading_guard guard;\n handle.get_download_queue(downloading);\n }\n\n for (std::vector<partial_piece_info>::iterator i = downloading.begin()\n , end(downloading.end()); i != end; ++i)\n {\n dict partial_piece;\n partial_piece[\"piece_index\"] = i->piece_index;\n partial_piece[\"blocks_in_piece\"] = i->blocks_in_piece;\n list block_list;\n for (int k = 0; k < i->blocks_in_piece; ++k)\n {\n dict block_info;\n block_info[\"state\"] = i->blocks[k].state;\n block_info[\"num_peers\"] = i->blocks[k].num_peers;\n block_info[\"bytes_progress\"] = i->blocks[k].bytes_progress;\n block_info[\"block_size\"] = i->blocks[k].block_size;\n block_info[\"peer\"] = std::make_pair(\n boost::lexical_cast<std::string>(i->blocks[k].peer.address()), i->blocks[k].peer.port());\n block_list.append(block_info);\n }\n partial_piece[\"blocks\"] = block_list;\n\n ret.append(partial_piece);\n }\n\n return ret;\n}\n\nnamespace\n{\n tcp::endpoint tuple_to_endpoint(tuple const& t)\n {\n return tcp::endpoint(address::from_string(extract<std::string>(t[0])), extract<int>(t[1]));\n }\n}\n\nvoid force_reannounce(torrent_handle& th, int s)\n{\n th.force_reannounce(boost::posix_time::seconds(s));\n}\n\nvoid connect_peer(torrent_handle& th, tuple ip, int source)\n{\n th.connect_peer(tuple_to_endpoint(ip), source);\n}\n\nvoid set_peer_upload_limit(torrent_handle& th, tuple const& ip, int limit)\n{\n th.set_peer_upload_limit(tuple_to_endpoint(ip), limit);\n}\n\nvoid set_peer_download_limit(torrent_handle& th, tuple const& ip, int limit)\n{\n th.set_peer_download_limit(tuple_to_endpoint(ip), limit);\n}\n\nvoid bind_torrent_handle()\n{\n void (torrent_handle::*force_reannounce0)() const = &torrent_handle::force_reannounce;\n\n int (torrent_handle::*piece_priority0)(int) const = &torrent_handle::piece_priority;\n void (torrent_handle::*piece_priority1)(int, int) const = &torrent_handle::piece_priority;\n\n#ifndef TORRENT_DISABLE_RESOLVE_COUNTRIES\t\n bool (torrent_handle::*resolve_countries0)() const = &torrent_handle::resolve_countries;\n void (torrent_handle::*resolve_countries1)(bool) = &torrent_handle::resolve_countries;\n#endif\n\n return_value_policy<copy_const_reference> copy;\n\n#define _ allow_threads\n\n class_<torrent_handle>(\"torrent_handle\")\n .def(\"get_peer_info\", get_peer_info)\n .def(\"status\", _(&torrent_handle::status))\n .def(\"get_download_queue\", get_download_queue)\n .def(\"file_progress\", file_progress)\n .def(\"trackers\", range(begin_trackers, end_trackers))\n .def(\"replace_trackers\", replace_trackers)\n .def(\"add_url_seed\", _(&torrent_handle::add_url_seed))\n .def(\"remove_url_seed\", _(&torrent_handle::remove_url_seed))\n .def(\"url_seeds\", url_seeds)\n .def(\"has_metadata\", _(&torrent_handle::has_metadata))\n .def(\"get_torrent_info\", _(&torrent_handle::get_torrent_info), return_internal_reference<>())\n .def(\"is_valid\", _(&torrent_handle::is_valid))\n .def(\"is_seed\", _(&torrent_handle::is_seed))\n .def(\"is_finished\", _(&torrent_handle::is_finished))\n .def(\"is_paused\", _(&torrent_handle::is_paused))\n .def(\"pause\", _(&torrent_handle::pause))\n .def(\"resume\", _(&torrent_handle::resume))\n \n .def(\"is_auto_managed\", _(&torrent_handle::is_auto_managed))\n .def(\"auto_managed\", _(&torrent_handle::auto_managed))\n .def(\"queue_position\", _(&torrent_handle::queue_position))\n .def(\"queue_position_up\", _(&torrent_handle::queue_position_up))\n .def(\"queue_position_down\", _(&torrent_handle::queue_position_down))\n .def(\"queue_position_top\", _(&torrent_handle::queue_position_top))\n .def(\"queue_position_bottom\", _(&torrent_handle::queue_position_bottom))\n \n#ifndef TORRENT_DISABLE_RESOLVE_COUNTRIES\t\n .def(\"resolve_countries\", _(resolve_countries0))\n .def(\"resolve_countries\", _(resolve_countries1))\n#endif\n \/\/ deprecated\n .def(\"filter_piece\", _(&torrent_handle::filter_piece))\n .def(\"is_piece_filtered\", _(&torrent_handle::is_piece_filtered))\n\n .def(\"piece_availability\", piece_availability)\n .def(\"piece_priority\", _(piece_priority0))\n .def(\"piece_priority\", _(piece_priority1))\n .def(\"prioritize_pieces\", prioritize_pieces)\n .def(\"piece_prioritize\", piece_priorities)\n .def(\"prioritize_files\", prioritize_files)\n .def(\"use_interface\", &torrent_handle::use_interface)\n .def(\"write_resume_data\", _(&torrent_handle::write_resume_data))\n .def(\"save_resume_data\", _(&torrent_handle::save_resume_data))\n .def(\"force_reannounce\", _(force_reannounce0))\n .def(\"force_reannounce\", force_reannounce)\n .def(\"scrape_tracker\", _(&torrent_handle::scrape_tracker))\n .def(\"name\", _(&torrent_handle::name))\n .def(\"set_upload_limit\", _(&torrent_handle::set_upload_limit))\n .def(\"upload_limit\", _(&torrent_handle::upload_limit))\n .def(\"set_download_limit\", _(&torrent_handle::set_download_limit))\n .def(\"download_limit\", _(&torrent_handle::download_limit))\n .def(\"set_sequential_download\", _(&torrent_handle::set_sequential_download))\n .def(\"set_peer_upload_limit\", set_peer_upload_limit)\n .def(\"set_peer_download_limit\", set_peer_download_limit)\n .def(\"connect_peer\", connect_peer)\n .def(\"set_ratio\", _(&torrent_handle::set_ratio))\n .def(\"save_path\", _(&torrent_handle::save_path))\n .def(\"set_max_uploads\", _(&torrent_handle::set_max_uploads))\n .def(\"set_max_connections\", _(&torrent_handle::set_max_connections))\n .def(\"set_tracker_login\", _(&torrent_handle::set_tracker_login))\n .def(\"move_storage\", _(&torrent_handle::move_storage))\n .def(\"info_hash\", _(&torrent_handle::info_hash))\n ;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/******************************************************************************\n * ____ _ _____ *\n * \/ ___| \/ \\ | ___| C++ *\n * | | \/ _ \\ | |_ Actor *\n * | |___ \/ ___ \\| _| Framework *\n * \\____\/_\/ \\_|_| *\n * *\n * Copyright (C) 2011 - 2014 *\n * Dominik Charousset <dominik.charousset (at) haw-hamburg.de> *\n * *\n * Distributed under the terms and conditions of the BSD 3-Clause License or *\n * (at your option) under the terms and conditions of the Boost Software *\n * License 1.0. See accompanying files LICENSE and LICENCE_ALTERNATIVE. *\n * *\n * If you did not receive a copy of the license files, see *\n * http:\/\/opensource.org\/licenses\/BSD-3-Clause and *\n * http:\/\/www.boost.org\/LICENSE_1_0.txt. *\n ******************************************************************************\/\n\n#ifndef CAF_NO_SCHEDULING_HPP\n#define CAF_NO_SCHEDULING_HPP\n\n#include <mutex>\n#include <thread>\n#include <chrono>\n#include <condition_variable>\n\n#include \"caf\/duration.hpp\"\n#include \"caf\/exit_reason.hpp\"\n\n#include \"caf\/policy\/scheduling_policy.hpp\"\n\n#include \"caf\/detail\/logging.hpp\"\n#include \"caf\/detail\/singletons.hpp\"\n#include \"caf\/detail\/scope_guard.hpp\"\n#include \"caf\/detail\/actor_registry.hpp\"\n#include \"caf\/detail\/sync_request_bouncer.hpp\"\n#include \"caf\/detail\/single_reader_queue.hpp\"\n\n\n#include \"caf\/actor_ostream.hpp\"\n\n\n\nnamespace caf {\nnamespace policy {\n\nclass no_scheduling {\n using lock_type = std::unique_lock<std::mutex>;\n public:\n using timeout_type = std::chrono::high_resolution_clock::time_point;\n\n template <class Actor>\n void enqueue(Actor* self, const actor_addr& sender, message_id mid,\n message& msg, execution_unit*) {\n auto ptr = self->new_mailbox_element(sender, mid, std::move(msg));\n \/\/ returns false if mailbox has been closed\n if (!self->mailbox().synchronized_enqueue(m_mtx, m_cv, ptr)) {\n if (mid.is_request()) {\n detail::sync_request_bouncer srb{self->exit_reason()};\n srb(sender, mid);\n }\n }\n }\n\n template <class Actor>\n void launch(Actor* self, execution_unit*) {\n CAF_REQUIRE(self != nullptr);\n CAF_PUSH_AID(self->id());\n CAF_LOG_TRACE(CAF_ARG(self));\n intrusive_ptr<Actor> mself{self};\n self->attach_to_scheduler();\n std::thread([=] {\n CAF_PUSH_AID(mself->id());\n CAF_LOG_TRACE(\"\");\n for (;;) {\n if (mself->resume(nullptr, 0) == resumable::done) {\n return;\n }\n \/\/ await new data before resuming actor\n await_data(mself.get());\n CAF_REQUIRE(self->mailbox().blocked() == false);\n }\n self->detach_from_scheduler();\n }).detach();\n }\n\n \/\/ await_data is being called from no_resume (only)\n template <class Actor>\n void await_data(Actor* self) {\n if (self->has_next_message()) return;\n self->mailbox().synchronized_await(m_mtx, m_cv);\n }\n\n \/\/ this additional member function is needed to implement\n \/\/ timer_actor (see scheduler.cpp)\n template <class Actor, class TimePoint>\n bool await_data(Actor* self, const TimePoint& tp) {\n if (self->has_next_message()) return true;\n return self->mailbox().synchronized_await(m_mtx, m_cv, tp);\n }\n\n private:\n std::mutex m_mtx;\n std::condition_variable m_cv;\n};\n\n} \/\/ namespace policy\n} \/\/ namespace caf\n\n#endif \/\/ CAF_NO_SCHEDULING_HPP\n<commit_msg>Fix reference count for detachted actors<commit_after>\/******************************************************************************\n * ____ _ _____ *\n * \/ ___| \/ \\ | ___| C++ *\n * | | \/ _ \\ | |_ Actor *\n * | |___ \/ ___ \\| _| Framework *\n * \\____\/_\/ \\_|_| *\n * *\n * Copyright (C) 2011 - 2014 *\n * Dominik Charousset <dominik.charousset (at) haw-hamburg.de> *\n * *\n * Distributed under the terms and conditions of the BSD 3-Clause License or *\n * (at your option) under the terms and conditions of the Boost Software *\n * License 1.0. See accompanying files LICENSE and LICENCE_ALTERNATIVE. *\n * *\n * If you did not receive a copy of the license files, see *\n * http:\/\/opensource.org\/licenses\/BSD-3-Clause and *\n * http:\/\/www.boost.org\/LICENSE_1_0.txt. *\n ******************************************************************************\/\n\n#ifndef CAF_NO_SCHEDULING_HPP\n#define CAF_NO_SCHEDULING_HPP\n\n#include <mutex>\n#include <thread>\n#include <chrono>\n#include <condition_variable>\n\n#include \"caf\/duration.hpp\"\n#include \"caf\/exit_reason.hpp\"\n\n#include \"caf\/policy\/scheduling_policy.hpp\"\n\n#include \"caf\/detail\/logging.hpp\"\n#include \"caf\/detail\/singletons.hpp\"\n#include \"caf\/detail\/scope_guard.hpp\"\n#include \"caf\/detail\/actor_registry.hpp\"\n#include \"caf\/detail\/sync_request_bouncer.hpp\"\n#include \"caf\/detail\/single_reader_queue.hpp\"\n\n\n#include \"caf\/actor_ostream.hpp\"\n\n\n\nnamespace caf {\nnamespace policy {\n\nclass no_scheduling {\n using lock_type = std::unique_lock<std::mutex>;\n public:\n using timeout_type = std::chrono::high_resolution_clock::time_point;\n\n template <class Actor>\n void enqueue(Actor* self, const actor_addr& sender, message_id mid,\n message& msg, execution_unit*) {\n auto ptr = self->new_mailbox_element(sender, mid, std::move(msg));\n \/\/ returns false if mailbox has been closed\n if (!self->mailbox().synchronized_enqueue(m_mtx, m_cv, ptr)) {\n if (mid.is_request()) {\n detail::sync_request_bouncer srb{self->exit_reason()};\n srb(sender, mid);\n }\n }\n }\n\n template <class Actor>\n void launch(Actor* self, execution_unit*) {\n CAF_REQUIRE(self != nullptr);\n CAF_PUSH_AID(self->id());\n CAF_LOG_TRACE(CAF_ARG(self));\n intrusive_ptr<Actor> mself{self};\n self->attach_to_scheduler();\n std::thread([=] {\n CAF_PUSH_AID(mself->id());\n CAF_LOG_TRACE(\"\");\n while (mself->resume(nullptr, 0) != resumable::done) {\n \/\/ await new data before resuming actor\n await_data(mself.get());\n CAF_REQUIRE(self->mailbox().blocked() == false);\n }\n self->detach_from_scheduler();\n }).detach();\n }\n\n \/\/ await_data is being called from no_resume (only)\n template <class Actor>\n void await_data(Actor* self) {\n if (self->has_next_message()) return;\n self->mailbox().synchronized_await(m_mtx, m_cv);\n }\n\n \/\/ this additional member function is needed to implement\n \/\/ timer_actor (see scheduler.cpp)\n template <class Actor, class TimePoint>\n bool await_data(Actor* self, const TimePoint& tp) {\n if (self->has_next_message()) return true;\n return self->mailbox().synchronized_await(m_mtx, m_cv, tp);\n }\n\n private:\n std::mutex m_mtx;\n std::condition_variable m_cv;\n};\n\n} \/\/ namespace policy\n} \/\/ namespace caf\n\n#endif \/\/ CAF_NO_SCHEDULING_HPP\n<|endoftext|>"} {"text":"<commit_before>#include \"HearthstoneLogTracker.h\"\n\n#include <QRegExp>\n#include <QStringList>\n\n\/\/ Hero Power Card Ids: Auto generated\nconst int NUM_HERO_POWER_CARDS = 43;\nconst char HERO_POWER_CARD_IDS[NUM_HERO_POWER_CARDS][32] = {\n\"CS1h_001\" \/* Lesser Heal *\/, \"CS2_017\" \/* Shapeshift *\/, \"CS2_034\" \/* Fireblast *\/, \"CS2_049\" \/* Totemic Call *\/, \"CS2_056\" \/* Life Tap *\/, \"CS2_083b\" \/* Dagger Mastery *\/, \"CS2_101\" \/* Reinforce *\/, \"CS2_102\" \/* Armor Up! *\/, \"DS1h_292\" \/* Steady Shot *\/, \"EX1_625t\" \/* Mind Spike *\/, \"EX1_625t2\" \/* Mind Shatter *\/, \"EX1_tk33\" \/* INFERNO! *\/, \"NAX10_03\" \/* Hateful Strike *\/, \"NAX10_03H\" \/* Hateful Strike *\/, \"NAX11_02\" \/* Poison Cloud *\/, \"NAX11_02H\" \/* Poison Cloud *\/, \"NAX12_02\" \/* Decimate *\/, \"NAX12_02H\" \/* Decimate *\/, \"NAX13_02\" \/* Polarity Shift *\/, \"NAX14_02\" \/* Frost Breath *\/, \"NAX15_02\" \/* Frost Blast *\/, \"NAX15_02H\" \/* Frost Blast *\/, \"NAX15_04\" \/* Chains *\/, \"NAX15_04H\" \/* Chains *\/, \"NAX1_04\" \/* Skitter *\/, \"NAX1h_04\" \/* Skitter *\/, \"NAX2_03\" \/* Rain of Fire *\/, \"NAX2_03H\" \/* Rain of Fire *\/, \"NAX3_02\" \/* Web Wrap *\/, \"NAX3_02H\" \/* Web Wrap *\/, \"NAX4_04\" \/* Raise Dead *\/, \"NAX4_04H\" \/* Raise Dead *\/, \"NAX5_02\" \/* Eruption *\/, \"NAX5_02H\" \/* Eruption *\/, \"NAX6_02\" \/* Necrotic Aura *\/, \"NAX6_02H\" \/* Necrotic Aura *\/, \"NAX7_03\" \/* Unbalancing Strike *\/, \"NAX7_03H\" \/* Unbalancing Strike *\/, \"NAX8_02\" \/* Harvest *\/, \"NAX8_02H\" \/* Harvest *\/, \"NAX9_06\" \/* Unholy Shadow *\/, \"TU4d_003\" \/* Shotgun Blast *\/, \"TU4e_002\" \/* Flames of Azzinoth *\/\n};\n\n\/\/ Hero Ids: Must match Class enum\nconst int NUM_HEROES = 9;\nconst char HERO_IDS[NUM_HEROES][32] = {\n \"HERO_09\", \/\/ CLASS_PRIEST = 0,\n \"HERO_03\", \/\/ CLASS_ROGUE,\n \"HERO_08\", \/\/ CLASS_MAGE,\n \"HERO_04\", \/\/ CLASS_PALADIN,\n \"HERO_01\", \/\/ CLASS_WARRIOR,\n \"HERO_07\", \/\/ CLASS_WARLOCK,\n \"HERO_05\", \/\/ CLASS_HUNTER,\n \"HERO_02\", \/\/ CLASS_SHAMAN,\n \"HERO_06\" \/\/ CLASS_DRUID,\n};\n\nQ_DECLARE_METATYPE( ::CardHistoryList );\n\nHearthstoneLogTracker::HearthstoneLogTracker()\n : mTurnCounter( 0 ), mHeroPowerUsed( false ), mHeroPlayerId( 0 ), mLegendTracked( false )\n{\n qRegisterMetaType< ::CardHistoryList >( \"CardHistoryList\" );\n\n connect( &mLogWatcher, SIGNAL( LineAdded(QString) ), this, SLOT( HandleLogLine(QString) ) );\n Reset();\n}\n\nvoid HearthstoneLogTracker::Reset() {\n mTurnCounter = 0;\n mHeroPowerUsed = false;\n mCardHistoryList.clear();\n mLegendTracked = false;\n mSpectating = false;\n mIsMyOwnTurnOdd = false;\n}\n\nvoid HearthstoneLogTracker::HandleLogLine( const QString& line ) {\n if( line.trimmed().isEmpty() || line.startsWith( \"(Filename:\" ) ) {\n return;\n }\n\n \/\/ CardPlayed \/ CardReturned \/ PlayerDied\n QRegExp regex( \"ProcessChanges.*\\\\[.*id=(\\\\d+).*cardId=(\\\\w+|).*\\\\].*zone from (.*) -> (.*)\" );\n if( regex.indexIn(line) != -1 ) {\n QStringList captures = regex.capturedTexts();\n int id = captures[1].toInt();\n QString cardId = captures[2];\n QString from = captures[3];\n QString to = captures[4];\n\n bool draw = from.contains( \"DECK\" ) && to.contains( \"HAND\" );\n bool mulligan = from.contains( \"HAND\" ) && to.contains( \"DECK\" );\n\n \/\/ Discarded cards by playing Soulfire, Doomguard etc.\n bool discard = from.contains( \"HAND\" ) && to.contains( \"GRAVEYARD\" );\n\n if( !draw && !mulligan && !discard ) {\n if( from.contains( \"FRIENDLY HAND\" ) ) {\n CardPlayed( PLAYER_SELF, cardId.toStdString(), id );\n } else if( from.contains( \"OPPOSING HAND\" ) ) {\n CardPlayed( PLAYER_OPPONENT, cardId.toStdString(), id );\n } else if( from.contains( \"OPPOSING SECRET\" ) && to.contains( \"OPPOSING GRAVEYARD\" ) ) {\n SecretResolved( PLAYER_OPPONENT, cardId.toStdString(), id );\n }\n }\n\n if( from.contains( \"FRIENDLY PLAY\" ) && to.contains( \"FRIENDLY HAND\" ) ) {\n CardReturned( PLAYER_SELF, cardId.toStdString() );\n }\n\n DBG( \"Card %s from %s -> %s. (draw: %d, mulligan %d, discard %d) [%d]\", cardId.toStdString().c_str(), from.toStdString().c_str(), to.toStdString().c_str(), draw, mulligan, discard, id );\n }\n\n \/\/ Outcome\n QRegExp regexOutcome( \"\\\\[Asset\\\\].*name=(victory|defeat)_screen_start\" );\n if( regexOutcome.indexIn(line) != -1 ) {\n QStringList captures = regexOutcome.capturedTexts();\n QString outcome = captures[1];\n\n if( outcome == \"victory\" ) {\n emit HandleOutcome( OUTCOME_VICTORY );\n } else if( outcome == \"defeat\" ) {\n emit HandleOutcome( OUTCOME_DEFEAT );\n }\n emit HandleMatchEnd( mCardHistoryList, mSpectating );\n Reset();\n }\n\n \/\/ Coin\n QRegExp regexCoin( \"ProcessChanges.*zonePos=5.*zone from -> (.*)\" ); \/\/ unique because from is nothing -> \" \"\n if( regexCoin.indexIn(line) != -1 ) {\n QStringList captures = regexCoin.capturedTexts();\n QString to = captures[1];\n\n if( to.contains( \"FRIENDLY HAND\" ) ) {\n \/\/ I go second because I get the coin\n mIsMyOwnTurnOdd = false;\n emit HandleOrder( ORDER_SECOND );\n } else if( to.contains( \"OPPOSING HAND\" ) ) {\n \/\/ Opponent got coin, so I go first\n mIsMyOwnTurnOdd = true;\n emit HandleOrder( ORDER_FIRST );\n }\n }\n\n \/\/ Turn Info\n QRegExp regexTurn( \"change=powerTask.*tag=NEXT_STEP value=MAIN_ACTION\" );\n if( regexTurn.indexIn(line) != -1 ) {\n mTurnCounter++;\n bool myTurn = ( mTurnCounter % 2 != 0 && mIsMyOwnTurnOdd ) ? true : false;\n emit HandleTurn( CurrentTurn(), myTurn );\n\n \/\/ reset hero power usage on turn change\n mHeroPowerUsed = false;\n }\n\n \/\/ Hero Power\n QRegExp regexHeroPowerEquip( \"\\\\[Zone\\\\].*player=(\\\\d+).*-> FRIENDLY PLAY \\\\(Hero Power\\\\)\" );\n if( regexHeroPowerEquip.indexIn(line) != -1 ) {\n QStringList captures = regexHeroPowerEquip.capturedTexts();\n QString playerId = captures[1];\n\n mHeroPlayerId = playerId.toInt();\n DBG( \"Hero Power Equip -> My Player Id: %d\", mHeroPlayerId );\n }\n\n QRegExp regexHeroPower( \"\\\\[Power\\\\] PowerProcessor\\\\.DoTaskListForCard.*cardId=(\\\\w+).*player=(\\\\d+)\" );\n if( regexHeroPower.indexIn(line) != -1 ) {\n QStringList captures = regexHeroPower.capturedTexts();\n QString cardId = captures[1];\n int playerId = captures[2].toInt();\n Player player = ( playerId == mHeroPlayerId ) ? PLAYER_SELF : PLAYER_OPPONENT;\n\n bool isHeroPower = false;\n for( int i = 0; i < NUM_HERO_POWER_CARDS; i++ ) {\n if( cardId == HERO_POWER_CARD_IDS[ i ] ) {\n isHeroPower = true;\n break;\n }\n }\n\n \/\/ Power log line is emitted multiple times\n \/\/ Make sure we only account for first occurrence\n \/\/ Plus line is emitted when match starts, so ignore turn 0\n if( isHeroPower && !mHeroPowerUsed && CurrentTurn() > 0 ) {\n CardPlayed( player, cardId.toStdString() );\n mHeroPowerUsed = true;\n }\n }\n\n \/\/ Hero Equip\n QRegExp regexHeroEquip( \"\\\\[Zone\\\\].*cardId=(\\\\w+).*-> (\\\\w+) PLAY \\\\(Hero\\\\)\" );\n if( regexHeroEquip.indexIn(line) != -1 ) {\n QStringList captures = regexHeroEquip.capturedTexts();\n QString cardId = captures[1];\n QString type = captures[2];\n\n \/\/ This log line can be emitted when hero swaps (Lord Jaraxxus)\n \/\/ So make sure we only account for the \"initial\" playable heroes\n Class hero = CLASS_UNKNOWN;\n for( int i = 0; i < NUM_HEROES; i++ ) {\n \/\/ startsWith instead of exact match to support\n \/\/ the new reasonably priced hero skins\n \/\/ (e.g. HERO_01a instead of HERO_01)\n if( cardId.startsWith( HERO_IDS[ i ] ) ) {\n hero = ( Class )i;\n }\n }\n\n \/\/ Set solo mode when encountering naxxramas\/blackrock mountain heroes\n if( hero == CLASS_UNKNOWN ) {\n if( cardId.startsWith(\"NAX\") || cardId.startsWith(\"BRM\") ) {\n HandleGameMode( MODE_SOLO_ADVENTURES );\n }\n }\n\n if( hero != CLASS_UNKNOWN ) {\n if( type == \"FRIENDLY\" ) {\n emit HandleMatchStart();\n emit HandleOwnClass( hero );\n } else {\n emit HandleOpponentClass( hero );\n }\n }\n }\n\n \/\/ Game Mode\n \/\/ Practice, Casual\/Ranked, SreenForge\n QRegExp regexMode( \"\\\\[Bob\\\\] ---(\\\\w+)---\" );\n if( regexMode.indexIn(line) != -1 ) {\n QStringList captures = regexMode.capturedTexts();\n QString screen = captures[1];\n\n if( screen == \"RegisterScreenPractice\" ) {\n HandleGameMode( MODE_SOLO_ADVENTURES );\n } else if( screen == \"RegisterScreenTourneys\") {\n HandleGameMode( MODE_CASUAL ); \/\/ or ranked resp.\n } else if( screen == \"RegisterScreenForge\" ) {\n HandleGameMode( MODE_ARENA );\n } else if( screen == \"RegisterScreenFriendly\" ) {\n HandleGameMode( MODE_FRIENDLY );\n }\n }\n\n \/\/ Tavern Brawl\n QRegExp regexTavernBrawl( \"SAVE --> NetCacheTavernBrawlRecord\" );\n if( regexTavernBrawl.indexIn(line) != -1 ) {\n HandleGameMode( MODE_TAVERN_BRAWL );\n }\n\n \/\/ Rank\n \/\/ Rank events via log are unreliable\n\n \/\/ Legend\n \/\/ Emitted at the end of the game twice, make sure we capture only the first time\n QRegExp regexLegend( \"legend rank (\\\\d+)\" );\n if( !mLegendTracked && regexLegend.indexIn(line) != -1 ) {\n QStringList captures = regexLegend.capturedTexts();\n int legend = captures[1].toInt();\n if( legend > 0 ) {\n mLegendTracked = true;\n HandleLegend( legend );\n }\n }\n\n \/\/ Casual\/Ranked distinction\n QRegExp regexRanked( \"name=rank_window\" );\n if( regexRanked.indexIn(line) != -1 ) {\n HandleGameMode( MODE_RANKED );\n }\n\n \/\/ flag current GAME as spectated\n QRegExp regexBeginSpectating( \"\\\\[Power\\\\].*Start Spectator Game\" );\n if( regexBeginSpectating.indexIn(line) != -1 ) {\n DBG( \"Begin spectator game\" );\n mSpectating = true;\n }\n\n \/\/ disable spectating flag if we leave the spectator MODE\n QRegExp regexEndSpectating( \"\\\\[Power\\\\].*End Spectator Mode\" );\n if( regexEndSpectating.indexIn(line) != -1 ) {\n DBG( \"End spectator mode\" );\n mSpectating = false;\n }\n}\n\nvoid HearthstoneLogTracker::CardPlayed( Player player, const string& cardId, int internalId ) {\n DBG( \"%s played card %s on turn %d\", PLAYER_NAMES[ player ], cardId.c_str(), CurrentTurn() );\n mCardHistoryList.push_back( CardHistoryItem( CurrentTurn(), player, cardId, internalId ) );\n}\n\nvoid HearthstoneLogTracker::CardReturned( Player player, const string& cardId ) {\n DBG( \"Card returned %s on turn %d: %s\", PLAYER_NAMES[ player ], CurrentTurn(), cardId.c_str() );\n \/\/ Make sure we remove the \"Choose One\"-cards from the history\n \/\/ if we decide to withdraw them after a second of thought\n if( !mCardHistoryList.empty() &&\n mCardHistoryList.back().turn == CurrentTurn() &&\n mCardHistoryList.back().player == player &&\n mCardHistoryList.back().cardId == cardId )\n {\n mCardHistoryList.pop_back();\n }\n}\n\nvoid HearthstoneLogTracker::SecretResolved( Player player, const string& cardId, int internalId ) {\n DBG( \"Secret resolved by %s: %s\", PLAYER_NAMES[ player ], cardId.c_str() );\n for( CardHistoryItem& item : mCardHistoryList ) {\n if( item.player == player && item.internalId == internalId ) {\n item.cardId = cardId;\n }\n }\n}\n\nint HearthstoneLogTracker::CurrentTurn() const {\n return ( mTurnCounter + 1 ) \/ 2;\n}\n<commit_msg>Instruments rocks! Create regexp objects only once -> perf boost<commit_after>#include \"HearthstoneLogTracker.h\"\n\n#include <QRegExp>\n#include <QStringList>\n\n\/\/ Hero Power Card Ids: Auto generated\nconst int NUM_HERO_POWER_CARDS = 43;\nconst char HERO_POWER_CARD_IDS[NUM_HERO_POWER_CARDS][32] = {\n\"CS1h_001\" \/* Lesser Heal *\/, \"CS2_017\" \/* Shapeshift *\/, \"CS2_034\" \/* Fireblast *\/, \"CS2_049\" \/* Totemic Call *\/, \"CS2_056\" \/* Life Tap *\/, \"CS2_083b\" \/* Dagger Mastery *\/, \"CS2_101\" \/* Reinforce *\/, \"CS2_102\" \/* Armor Up! *\/, \"DS1h_292\" \/* Steady Shot *\/, \"EX1_625t\" \/* Mind Spike *\/, \"EX1_625t2\" \/* Mind Shatter *\/, \"EX1_tk33\" \/* INFERNO! *\/, \"NAX10_03\" \/* Hateful Strike *\/, \"NAX10_03H\" \/* Hateful Strike *\/, \"NAX11_02\" \/* Poison Cloud *\/, \"NAX11_02H\" \/* Poison Cloud *\/, \"NAX12_02\" \/* Decimate *\/, \"NAX12_02H\" \/* Decimate *\/, \"NAX13_02\" \/* Polarity Shift *\/, \"NAX14_02\" \/* Frost Breath *\/, \"NAX15_02\" \/* Frost Blast *\/, \"NAX15_02H\" \/* Frost Blast *\/, \"NAX15_04\" \/* Chains *\/, \"NAX15_04H\" \/* Chains *\/, \"NAX1_04\" \/* Skitter *\/, \"NAX1h_04\" \/* Skitter *\/, \"NAX2_03\" \/* Rain of Fire *\/, \"NAX2_03H\" \/* Rain of Fire *\/, \"NAX3_02\" \/* Web Wrap *\/, \"NAX3_02H\" \/* Web Wrap *\/, \"NAX4_04\" \/* Raise Dead *\/, \"NAX4_04H\" \/* Raise Dead *\/, \"NAX5_02\" \/* Eruption *\/, \"NAX5_02H\" \/* Eruption *\/, \"NAX6_02\" \/* Necrotic Aura *\/, \"NAX6_02H\" \/* Necrotic Aura *\/, \"NAX7_03\" \/* Unbalancing Strike *\/, \"NAX7_03H\" \/* Unbalancing Strike *\/, \"NAX8_02\" \/* Harvest *\/, \"NAX8_02H\" \/* Harvest *\/, \"NAX9_06\" \/* Unholy Shadow *\/, \"TU4d_003\" \/* Shotgun Blast *\/, \"TU4e_002\" \/* Flames of Azzinoth *\/\n};\n\n\/\/ Hero Ids: Must match Class enum\nconst int NUM_HEROES = 9;\nconst char HERO_IDS[NUM_HEROES][32] = {\n \"HERO_09\", \/\/ CLASS_PRIEST = 0,\n \"HERO_03\", \/\/ CLASS_ROGUE,\n \"HERO_08\", \/\/ CLASS_MAGE,\n \"HERO_04\", \/\/ CLASS_PALADIN,\n \"HERO_01\", \/\/ CLASS_WARRIOR,\n \"HERO_07\", \/\/ CLASS_WARLOCK,\n \"HERO_05\", \/\/ CLASS_HUNTER,\n \"HERO_02\", \/\/ CLASS_SHAMAN,\n \"HERO_06\" \/\/ CLASS_DRUID,\n};\n\nQ_DECLARE_METATYPE( ::CardHistoryList );\n\nHearthstoneLogTracker::HearthstoneLogTracker()\n : mTurnCounter( 0 ), mHeroPowerUsed( false ), mHeroPlayerId( 0 ), mLegendTracked( false )\n{\n qRegisterMetaType< ::CardHistoryList >( \"CardHistoryList\" );\n\n connect( &mLogWatcher, SIGNAL( LineAdded(QString) ), this, SLOT( HandleLogLine(QString) ) );\n Reset();\n}\n\nvoid HearthstoneLogTracker::Reset() {\n mTurnCounter = 0;\n mHeroPowerUsed = false;\n mCardHistoryList.clear();\n mLegendTracked = false;\n mSpectating = false;\n mIsMyOwnTurnOdd = false;\n}\n\nvoid HearthstoneLogTracker::HandleLogLine( const QString& line ) {\n if( line.trimmed().isEmpty() || line.startsWith( \"(Filename:\" ) ) {\n return;\n }\n\n \/\/ CardPlayed \/ CardReturned \/ PlayerDied\n static QRegExp regex( \"ProcessChanges.*\\\\[.*id=(\\\\d+).*cardId=(\\\\w+|).*\\\\].*zone from (.*) -> (.*)\" );\n if( regex.indexIn(line) != -1 ) {\n QStringList captures = regex.capturedTexts();\n int id = captures[1].toInt();\n QString cardId = captures[2];\n QString from = captures[3];\n QString to = captures[4];\n\n bool draw = from.contains( \"DECK\" ) && to.contains( \"HAND\" );\n bool mulligan = from.contains( \"HAND\" ) && to.contains( \"DECK\" );\n\n \/\/ Discarded cards by playing Soulfire, Doomguard etc.\n bool discard = from.contains( \"HAND\" ) && to.contains( \"GRAVEYARD\" );\n\n if( !draw && !mulligan && !discard ) {\n if( from.contains( \"FRIENDLY HAND\" ) ) {\n CardPlayed( PLAYER_SELF, cardId.toStdString(), id );\n } else if( from.contains( \"OPPOSING HAND\" ) ) {\n CardPlayed( PLAYER_OPPONENT, cardId.toStdString(), id );\n } else if( from.contains( \"OPPOSING SECRET\" ) && to.contains( \"OPPOSING GRAVEYARD\" ) ) {\n SecretResolved( PLAYER_OPPONENT, cardId.toStdString(), id );\n }\n }\n\n if( from.contains( \"FRIENDLY PLAY\" ) && to.contains( \"FRIENDLY HAND\" ) ) {\n CardReturned( PLAYER_SELF, cardId.toStdString() );\n }\n\n DBG( \"Card %s from %s -> %s. (draw: %d, mulligan %d, discard %d) [%d]\", cardId.toStdString().c_str(), from.toStdString().c_str(), to.toStdString().c_str(), draw, mulligan, discard, id );\n }\n\n \/\/ Outcome\n static QRegExp regexOutcome( \"\\\\[Asset\\\\].*name=(victory|defeat)_screen_start\" );\n if( regexOutcome.indexIn(line) != -1 ) {\n QStringList captures = regexOutcome.capturedTexts();\n QString outcome = captures[1];\n\n if( outcome == \"victory\" ) {\n emit HandleOutcome( OUTCOME_VICTORY );\n } else if( outcome == \"defeat\" ) {\n emit HandleOutcome( OUTCOME_DEFEAT );\n }\n emit HandleMatchEnd( mCardHistoryList, mSpectating );\n Reset();\n }\n\n \/\/ Coin\n static QRegExp regexCoin( \"ProcessChanges.*zonePos=5.*zone from -> (.*)\" ); \/\/ unique because from is nothing -> \" \"\n if( regexCoin.indexIn(line) != -1 ) {\n QStringList captures = regexCoin.capturedTexts();\n QString to = captures[1];\n\n if( to.contains( \"FRIENDLY HAND\" ) ) {\n \/\/ I go second because I get the coin\n mIsMyOwnTurnOdd = false;\n emit HandleOrder( ORDER_SECOND );\n } else if( to.contains( \"OPPOSING HAND\" ) ) {\n \/\/ Opponent got coin, so I go first\n mIsMyOwnTurnOdd = true;\n emit HandleOrder( ORDER_FIRST );\n }\n }\n\n \/\/ Turn Info\n static QRegExp regexTurn( \"change=powerTask.*tag=NEXT_STEP value=MAIN_ACTION\" );\n if( regexTurn.indexIn(line) != -1 ) {\n mTurnCounter++;\n bool myTurn = ( mTurnCounter % 2 != 0 && mIsMyOwnTurnOdd ) ? true : false;\n emit HandleTurn( CurrentTurn(), myTurn );\n\n \/\/ reset hero power usage on turn change\n mHeroPowerUsed = false;\n }\n\n \/\/ Hero Power\n static QRegExp regexHeroPowerEquip( \"\\\\[Zone\\\\].*player=(\\\\d+).*-> FRIENDLY PLAY \\\\(Hero Power\\\\)\" );\n if( regexHeroPowerEquip.indexIn(line) != -1 ) {\n QStringList captures = regexHeroPowerEquip.capturedTexts();\n QString playerId = captures[1];\n\n mHeroPlayerId = playerId.toInt();\n DBG( \"Hero Power Equip -> My Player Id: %d\", mHeroPlayerId );\n }\n\n static QRegExp regexHeroPower( \"\\\\[Power\\\\] PowerProcessor\\\\.DoTaskListForCard.*cardId=(\\\\w+).*player=(\\\\d+)\" );\n if( regexHeroPower.indexIn(line) != -1 ) {\n QStringList captures = regexHeroPower.capturedTexts();\n QString cardId = captures[1];\n int playerId = captures[2].toInt();\n Player player = ( playerId == mHeroPlayerId ) ? PLAYER_SELF : PLAYER_OPPONENT;\n\n bool isHeroPower = false;\n for( int i = 0; i < NUM_HERO_POWER_CARDS; i++ ) {\n if( cardId == HERO_POWER_CARD_IDS[ i ] ) {\n isHeroPower = true;\n break;\n }\n }\n\n \/\/ Power log line is emitted multiple times\n \/\/ Make sure we only account for first occurrence\n \/\/ Plus line is emitted when match starts, so ignore turn 0\n if( isHeroPower && !mHeroPowerUsed && CurrentTurn() > 0 ) {\n CardPlayed( player, cardId.toStdString() );\n mHeroPowerUsed = true;\n }\n }\n\n \/\/ Hero Equip\n static QRegExp regexHeroEquip( \"\\\\[Zone\\\\].*cardId=(\\\\w+).*-> (\\\\w+) PLAY \\\\(Hero\\\\)\" );\n if( regexHeroEquip.indexIn(line) != -1 ) {\n QStringList captures = regexHeroEquip.capturedTexts();\n QString cardId = captures[1];\n QString type = captures[2];\n\n \/\/ This log line can be emitted when hero swaps (Lord Jaraxxus)\n \/\/ So make sure we only account for the \"initial\" playable heroes\n Class hero = CLASS_UNKNOWN;\n for( int i = 0; i < NUM_HEROES; i++ ) {\n \/\/ startsWith instead of exact match to support\n \/\/ the new reasonably priced hero skins\n \/\/ (e.g. HERO_01a instead of HERO_01)\n if( cardId.startsWith( HERO_IDS[ i ] ) ) {\n hero = ( Class )i;\n }\n }\n\n \/\/ Set solo mode when encountering naxxramas\/blackrock mountain heroes\n if( hero == CLASS_UNKNOWN ) {\n if( cardId.startsWith(\"NAX\") || cardId.startsWith(\"BRM\") ) {\n HandleGameMode( MODE_SOLO_ADVENTURES );\n }\n }\n\n if( hero != CLASS_UNKNOWN ) {\n if( type == \"FRIENDLY\" ) {\n emit HandleMatchStart();\n emit HandleOwnClass( hero );\n } else {\n emit HandleOpponentClass( hero );\n }\n }\n }\n\n \/\/ Game Mode\n \/\/ Practice, Casual\/Ranked, SreenForge\n static QRegExp regexMode( \"\\\\[Bob\\\\] ---(\\\\w+)---\" );\n if( regexMode.indexIn(line) != -1 ) {\n QStringList captures = regexMode.capturedTexts();\n QString screen = captures[1];\n\n if( screen == \"RegisterScreenPractice\" ) {\n HandleGameMode( MODE_SOLO_ADVENTURES );\n } else if( screen == \"RegisterScreenTourneys\") {\n HandleGameMode( MODE_CASUAL ); \/\/ or ranked resp.\n } else if( screen == \"RegisterScreenForge\" ) {\n HandleGameMode( MODE_ARENA );\n } else if( screen == \"RegisterScreenFriendly\" ) {\n HandleGameMode( MODE_FRIENDLY );\n }\n }\n\n \/\/ Tavern Brawl\n static QRegExp regexTavernBrawl( \"SAVE --> NetCacheTavernBrawlRecord\" );\n if( regexTavernBrawl.indexIn(line) != -1 ) {\n HandleGameMode( MODE_TAVERN_BRAWL );\n }\n\n \/\/ Rank\n \/\/ Rank events via log are unreliable\n\n \/\/ Legend\n \/\/ Emitted at the end of the game twice, make sure we capture only the first time\n static QRegExp regexLegend( \"legend rank (\\\\d+)\" );\n if( !mLegendTracked && regexLegend.indexIn(line) != -1 ) {\n QStringList captures = regexLegend.capturedTexts();\n int legend = captures[1].toInt();\n if( legend > 0 ) {\n mLegendTracked = true;\n HandleLegend( legend );\n }\n }\n\n \/\/ Casual\/Ranked distinction\n static QRegExp regexRanked( \"name=rank_window\" );\n if( regexRanked.indexIn(line) != -1 ) {\n HandleGameMode( MODE_RANKED );\n }\n\n \/\/ flag current GAME as spectated\n static QRegExp regexBeginSpectating( \"\\\\[Power\\\\].*Start Spectator Game\" );\n if( regexBeginSpectating.indexIn(line) != -1 ) {\n DBG( \"Begin spectator game\" );\n mSpectating = true;\n }\n\n \/\/ disable spectating flag if we leave the spectator MODE\n static QRegExp regexEndSpectating( \"\\\\[Power\\\\].*End Spectator Mode\" );\n if( regexEndSpectating.indexIn(line) != -1 ) {\n DBG( \"End spectator mode\" );\n mSpectating = false;\n }\n}\n\nvoid HearthstoneLogTracker::CardPlayed( Player player, const string& cardId, int internalId ) {\n DBG( \"%s played card %s on turn %d\", PLAYER_NAMES[ player ], cardId.c_str(), CurrentTurn() );\n mCardHistoryList.push_back( CardHistoryItem( CurrentTurn(), player, cardId, internalId ) );\n}\n\nvoid HearthstoneLogTracker::CardReturned( Player player, const string& cardId ) {\n DBG( \"Card returned %s on turn %d: %s\", PLAYER_NAMES[ player ], CurrentTurn(), cardId.c_str() );\n \/\/ Make sure we remove the \"Choose One\"-cards from the history\n \/\/ if we decide to withdraw them after a second of thought\n if( !mCardHistoryList.empty() &&\n mCardHistoryList.back().turn == CurrentTurn() &&\n mCardHistoryList.back().player == player &&\n mCardHistoryList.back().cardId == cardId )\n {\n mCardHistoryList.pop_back();\n }\n}\n\nvoid HearthstoneLogTracker::SecretResolved( Player player, const string& cardId, int internalId ) {\n DBG( \"Secret resolved by %s: %s\", PLAYER_NAMES[ player ], cardId.c_str() );\n for( CardHistoryItem& item : mCardHistoryList ) {\n if( item.player == player && item.internalId == internalId ) {\n item.cardId = cardId;\n }\n }\n}\n\nint HearthstoneLogTracker::CurrentTurn() const {\n return ( mTurnCounter + 1 ) \/ 2;\n}\n<|endoftext|>"} {"text":"<commit_before><commit_msg>media: Fix DCHECK in DeocderStream::Decode().<commit_after><|endoftext|>"} {"text":"<commit_before><commit_msg>Enable support for additional media formats by using the duration from AVFormatContext, if present.<commit_after><|endoftext|>"} {"text":"<commit_before>#include \"LocalSearchPathFinder.hpp\"\n#include \"GreedyPathFinder.hpp\"\n#include <queue>\n#include <iostream>\n#include <limits>\n#include \"Types.hpp\"\n\nusing namespace FireflyAssembler;\nusing namespace std;\n\nPathPointer LocalSearchPathFinder::findPath(IGraphConstPointer graph,\n FitnessFunctionPointer ff)\n{\n if (graph->sequenceCount() == 1)\n {\n vector<int> path(1);\n path.push_back(0);\n PathPointer returned(new Path(graph, path));\n return returned;\n }\n else\n {\n PathFinderPointer greedy(new GreedyPathFinder());\n PathPointer initial = greedy->findPath(graph,ff);\n vector<int> triedPath;\n for (int i = 0; i < graph->sequenceCount(); i++)\n {\n triedPath.push_back((*initial)[i]);\n }\n\n double currentScore = ff->rate(Path(graph, triedPath));\n double bestScore = -numeric_limits<double>::infinity();\n while (currentScore > bestScore)\n {\n bestScore = currentScore;\n bool found = false;\n for (int i = 0; i < graph->sequenceCount(); i++)\n {\n for (int j = i + 1; j < graph->sequenceCount(); j++)\n {\n int tmp = triedPath[i];\n triedPath[i] = triedPath[j];\n triedPath[j] = tmp;\n double score = ff->rate(Path(graph,triedPath));\n if (score > currentScore)\n {\n found = true;\n currentScore = score;\n break;\n }\n triedPath[j] = triedPath[i];\n triedPath[i] = tmp;\n }\n if (found)\n {\n break;\n }\n }\n }\n return PathPointer(new Path(graph, triedPath));\n }\n}\n\n<commit_msg>Try to fix local search<commit_after>#include \"LocalSearchPathFinder.hpp\"\n#include \"GreedyPathFinder.hpp\"\n#include <queue>\n#include <iostream>\n#include <limits>\n#include <random>\n#include \"Types.hpp\"\n\nusing namespace FireflyAssembler;\nusing namespace std;\n\nPathPointer LocalSearchPathFinder::findPath(IGraphConstPointer graph,\n FitnessFunctionPointer ff)\n{\n if (graph->sequenceCount() == 1)\n {\n vector<int> path(1);\n path.push_back(0);\n PathPointer returned(new Path(graph, path));\n return returned;\n }\n else\n {\n vector<int> path;\n HashSet<int> visited;\n default_random_engine generator;\n uniform_int_distribution<int> distribution(0,graph->sequenceCount()-1);\n auto random = bind(distribution, generator);\n while (visited.size() < graph->sequenceCount())\n {\n int node = random();\n if (visited.find(node) == visited.end())\n {\n visited.insert(node);\n path.push_back(node);\n }\n }\n PathPointer initial(new Path(graph, path));\n\n \/\/PathFinderPointer greedy(new GreedyPathFinder());\n \/\/PathPointer initial = greedy->findPath(graph,ff);\n \/\/for (int i = 0; i < graph->sequenceCount(); i++)\n \/\/{\n \/\/ path.push_back((*initial)[i]);\n \/\/}\n\n double currentScore = ff->rate(*initial);\n double bestScore = -numeric_limits<double>::infinity();\n vector<int> currentPath = path;\n while (currentScore > bestScore)\n {\n bestScore = currentScore;\n for (int i = 1; i < graph->sequenceCount()-1; i++)\n {\n vector<int> triedPath(currentPath.begin()+i,currentPath.end());\n triedPath.insert(triedPath.end(),currentPath.begin(),\n currentPath.begin()+i);\n double score = ff->rate(Path(graph,triedPath));\n if (score > bestScore)\n {\n cout << \"Improved!\" << endl;\n currentScore = score;\n currentPath = triedPath;\n break;\n }\n }\n }\n return PathPointer(new Path(graph, currentPath));\n }\n}\n\n<|endoftext|>"} {"text":"<commit_before>#include \"MOLPUpdateComputation.hpp\"\n\nMOLPUpdateComputation::MOLPUpdateComputation(MOLP a, MOLP b) : molpA(a), molpB(b), endA(molpA.end()), endB(molpB.end()), iterA(molpA.begin()), iterB(molpB.begin()) {\n}\n\nbool MOLPUpdateComputation::noDominance() {\n return (molpA.empty() ||\n molpB.empty() ||\n molpA.isInA1AreaOf(molpB) ||\n molpB.isInA1AreaOf(molpA));\n}\n\nvoid MOLPUpdateComputation::prepareIterators() {\n while (iterA->isInA1AreaOf(*iterB) && iterA != endA)\n ++iterA;\n while (iterB->isInA1AreaOf(*iterA) && iterB != endB)\n ++iterB;\n}\n\nDominanceStatus MOLPUpdateComputation::computeUpdate() {\n if (noDominance())\n return DominanceStatus::NO_DOM;\n prepareIterators();\n}\n<commit_msg>MUC: Better check iterators validity when preparing them<commit_after>#include \"MOLPUpdateComputation.hpp\"\n\nMOLPUpdateComputation::MOLPUpdateComputation(MOLP a, MOLP b) : molpA(a), molpB(b), endA(molpA.end()), endB(molpB.end()), iterA(molpA.begin()), iterB(molpB.begin()) {\n}\n\nbool MOLPUpdateComputation::noDominance() {\n return (molpA.empty() ||\n molpB.empty() ||\n molpA.isInA1AreaOf(molpB) ||\n molpB.isInA1AreaOf(molpA));\n}\n\nvoid MOLPUpdateComputation::prepareIterators() {\n while (iterA != endA && iterB != endB && iterA->isInA1AreaOf(*iterB))\n ++iterA;\n while (iterA != endA && iterB != endB && iterB->isInA1AreaOf(*iterA))\n ++iterB;\n}\n\nDominanceStatus MOLPUpdateComputation::computeUpdate() {\n if (noDominance())\n return DominanceStatus::NO_DOM;\n prepareIterators();\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.\n *\n * Use of this source code is governed by a BSD-style license\n * that can be found in the LICENSE file in the root of the source\n * tree. An additional intellectual property rights grant can be found\n * in the file PATENTS. All contributing project authors may\n * be found in the AUTHORS file in the root of the source tree.\n *\/\n\n#include \"webrtc\/modules\/audio_processing\/residual_echo_detector.h\"\n\n#include <algorithm>\n#include <numeric>\n\n#include \"webrtc\/modules\/audio_processing\/audio_buffer.h\"\n\nnamespace {\n\nfloat Power(rtc::ArrayView<const float> input) {\n return std::inner_product(input.begin(), input.end(), input.begin(), 0.f);\n}\n\nconstexpr size_t kLookbackFrames = 650;\n\/\/ TODO(ivoc): Verify the size of this buffer.\nconstexpr size_t kRenderBufferSize = 30;\n\n} \/\/ namespace\n\nnamespace webrtc {\n\nResidualEchoDetector::ResidualEchoDetector()\n : render_buffer_(kRenderBufferSize),\n render_power_(kLookbackFrames),\n render_power_mean_(kLookbackFrames),\n render_power_std_dev_(kLookbackFrames),\n covariances_(kLookbackFrames){};\n\nResidualEchoDetector::~ResidualEchoDetector() = default;\n\nvoid ResidualEchoDetector::AnalyzeRenderAudio(\n rtc::ArrayView<const float> render_audio) {\n if (render_buffer_.Size() == 0) {\n frames_since_zero_buffer_size_ = 0;\n } else if (frames_since_zero_buffer_size_ >= kRenderBufferSize) {\n \/\/ This can happen in a few cases: at the start of a call, due to a glitch\n \/\/ or due to clock drift. The excess capture value will be ignored.\n \/\/ TODO(ivoc): Include how often this happens in APM stats.\n render_buffer_.Pop();\n frames_since_zero_buffer_size_ = 0;\n }\n ++frames_since_zero_buffer_size_;\n float power = Power(render_audio);\n render_buffer_.Push(power);\n}\n\nvoid ResidualEchoDetector::AnalyzeCaptureAudio(\n rtc::ArrayView<const float> capture_audio) {\n if (first_process_call_) {\n \/\/ On the first process call (so the start of a call), we must flush the\n \/\/ render buffer, otherwise the render data will be delayed.\n render_buffer_.Clear();\n first_process_call_ = false;\n }\n\n \/\/ Get the next render value.\n const rtc::Optional<float> buffered_render_power = render_buffer_.Pop();\n if (!buffered_render_power) {\n \/\/ This can happen in a few cases: at the start of a call, due to a glitch\n \/\/ or due to clock drift. The excess capture value will be ignored.\n \/\/ TODO(ivoc): Include how often this happens in APM stats.\n return;\n }\n \/\/ Update the render statistics, and store the statistics in circular buffers.\n render_statistics_.Update(*buffered_render_power);\n RTC_DCHECK_LT(next_insertion_index_, kLookbackFrames);\n render_power_[next_insertion_index_] = *buffered_render_power;\n render_power_mean_[next_insertion_index_] = render_statistics_.mean();\n render_power_std_dev_[next_insertion_index_] =\n render_statistics_.std_deviation();\n\n \/\/ Get the next capture value, update capture statistics and add the relevant\n \/\/ values to the buffers.\n const float capture_power = Power(capture_audio);\n capture_statistics_.Update(capture_power);\n const float capture_mean = capture_statistics_.mean();\n const float capture_std_deviation = capture_statistics_.std_deviation();\n\n \/\/ Update the covariance values and determine the new echo likelihood.\n echo_likelihood_ = 0.f;\n for (size_t delay = 0; delay < covariances_.size(); ++delay) {\n const size_t read_index =\n (kLookbackFrames + next_insertion_index_ - delay) % kLookbackFrames;\n RTC_DCHECK_LT(read_index, render_power_.size());\n covariances_[delay].Update(capture_power, capture_mean,\n capture_std_deviation, render_power_[read_index],\n render_power_mean_[read_index],\n render_power_std_dev_[read_index]);\n echo_likelihood_ = std::max(\n echo_likelihood_, covariances_[delay].normalized_cross_correlation());\n }\n\n \/\/ Update the next insertion index.\n ++next_insertion_index_;\n next_insertion_index_ %= kLookbackFrames;\n}\n\nvoid ResidualEchoDetector::Initialize() {\n render_buffer_.Clear();\n std::fill(render_power_.begin(), render_power_.end(), 0.f);\n std::fill(render_power_mean_.begin(), render_power_mean_.end(), 0.f);\n std::fill(render_power_std_dev_.begin(), render_power_std_dev_.end(), 0.f);\n render_statistics_.Clear();\n capture_statistics_.Clear();\n for (auto& cov : covariances_) {\n cov.Clear();\n }\n echo_likelihood_ = 0.f;\n next_insertion_index_ = 0;\n}\n\nvoid ResidualEchoDetector::PackRenderAudioBuffer(\n AudioBuffer* audio,\n std::vector<float>* packed_buffer) {\n RTC_DCHECK_GE(160u, audio->num_frames_per_band());\n\n packed_buffer->clear();\n packed_buffer->insert(packed_buffer->end(),\n audio->split_bands_const_f(0)[kBand0To8kHz],\n (audio->split_bands_const_f(0)[kBand0To8kHz] +\n audio->num_frames_per_band()));\n}\n\n} \/\/ namespace webrtc\n<commit_msg>Add UMA histogram for Echo likelihood.<commit_after>\/*\n * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.\n *\n * Use of this source code is governed by a BSD-style license\n * that can be found in the LICENSE file in the root of the source\n * tree. An additional intellectual property rights grant can be found\n * in the file PATENTS. All contributing project authors may\n * be found in the AUTHORS file in the root of the source tree.\n *\/\n\n#include \"webrtc\/modules\/audio_processing\/residual_echo_detector.h\"\n\n#include <algorithm>\n#include <numeric>\n\n#include \"webrtc\/modules\/audio_processing\/audio_buffer.h\"\n#include \"webrtc\/system_wrappers\/include\/metrics.h\"\n\nnamespace {\n\nfloat Power(rtc::ArrayView<const float> input) {\n return std::inner_product(input.begin(), input.end(), input.begin(), 0.f);\n}\n\nconstexpr size_t kLookbackFrames = 650;\n\/\/ TODO(ivoc): Verify the size of this buffer.\nconstexpr size_t kRenderBufferSize = 30;\n\n} \/\/ namespace\n\nnamespace webrtc {\n\nResidualEchoDetector::ResidualEchoDetector()\n : render_buffer_(kRenderBufferSize),\n render_power_(kLookbackFrames),\n render_power_mean_(kLookbackFrames),\n render_power_std_dev_(kLookbackFrames),\n covariances_(kLookbackFrames){};\n\nResidualEchoDetector::~ResidualEchoDetector() = default;\n\nvoid ResidualEchoDetector::AnalyzeRenderAudio(\n rtc::ArrayView<const float> render_audio) {\n if (render_buffer_.Size() == 0) {\n frames_since_zero_buffer_size_ = 0;\n } else if (frames_since_zero_buffer_size_ >= kRenderBufferSize) {\n \/\/ This can happen in a few cases: at the start of a call, due to a glitch\n \/\/ or due to clock drift. The excess capture value will be ignored.\n \/\/ TODO(ivoc): Include how often this happens in APM stats.\n render_buffer_.Pop();\n frames_since_zero_buffer_size_ = 0;\n }\n ++frames_since_zero_buffer_size_;\n float power = Power(render_audio);\n render_buffer_.Push(power);\n}\n\nvoid ResidualEchoDetector::AnalyzeCaptureAudio(\n rtc::ArrayView<const float> capture_audio) {\n if (first_process_call_) {\n \/\/ On the first process call (so the start of a call), we must flush the\n \/\/ render buffer, otherwise the render data will be delayed.\n render_buffer_.Clear();\n first_process_call_ = false;\n }\n\n \/\/ Get the next render value.\n const rtc::Optional<float> buffered_render_power = render_buffer_.Pop();\n if (!buffered_render_power) {\n \/\/ This can happen in a few cases: at the start of a call, due to a glitch\n \/\/ or due to clock drift. The excess capture value will be ignored.\n \/\/ TODO(ivoc): Include how often this happens in APM stats.\n return;\n }\n \/\/ Update the render statistics, and store the statistics in circular buffers.\n render_statistics_.Update(*buffered_render_power);\n RTC_DCHECK_LT(next_insertion_index_, kLookbackFrames);\n render_power_[next_insertion_index_] = *buffered_render_power;\n render_power_mean_[next_insertion_index_] = render_statistics_.mean();\n render_power_std_dev_[next_insertion_index_] =\n render_statistics_.std_deviation();\n\n \/\/ Get the next capture value, update capture statistics and add the relevant\n \/\/ values to the buffers.\n const float capture_power = Power(capture_audio);\n capture_statistics_.Update(capture_power);\n const float capture_mean = capture_statistics_.mean();\n const float capture_std_deviation = capture_statistics_.std_deviation();\n\n \/\/ Update the covariance values and determine the new echo likelihood.\n echo_likelihood_ = 0.f;\n for (size_t delay = 0; delay < covariances_.size(); ++delay) {\n const size_t read_index =\n (kLookbackFrames + next_insertion_index_ - delay) % kLookbackFrames;\n RTC_DCHECK_LT(read_index, render_power_.size());\n covariances_[delay].Update(capture_power, capture_mean,\n capture_std_deviation, render_power_[read_index],\n render_power_mean_[read_index],\n render_power_std_dev_[read_index]);\n echo_likelihood_ = std::max(\n echo_likelihood_, covariances_[delay].normalized_cross_correlation());\n }\n int echo_percentage = static_cast<int>(echo_likelihood_ * 100);\n RTC_HISTOGRAM_COUNTS(\"WebRTC.Audio.ResidualEchoDetector.EchoLikelihood\",\n echo_percentage, 0, 100, 100 \/* number of bins *\/);\n\n \/\/ Update the next insertion index.\n ++next_insertion_index_;\n next_insertion_index_ %= kLookbackFrames;\n}\n\nvoid ResidualEchoDetector::Initialize() {\n render_buffer_.Clear();\n std::fill(render_power_.begin(), render_power_.end(), 0.f);\n std::fill(render_power_mean_.begin(), render_power_mean_.end(), 0.f);\n std::fill(render_power_std_dev_.begin(), render_power_std_dev_.end(), 0.f);\n render_statistics_.Clear();\n capture_statistics_.Clear();\n for (auto& cov : covariances_) {\n cov.Clear();\n }\n echo_likelihood_ = 0.f;\n next_insertion_index_ = 0;\n}\n\nvoid ResidualEchoDetector::PackRenderAudioBuffer(\n AudioBuffer* audio,\n std::vector<float>* packed_buffer) {\n RTC_DCHECK_GE(160u, audio->num_frames_per_band());\n\n packed_buffer->clear();\n packed_buffer->insert(packed_buffer->end(),\n audio->split_bands_const_f(0)[kBand0To8kHz],\n (audio->split_bands_const_f(0)[kBand0To8kHz] +\n audio->num_frames_per_band()));\n}\n\n} \/\/ namespace webrtc\n<|endoftext|>"} {"text":"<commit_before>#include <string.h>\n#include <thread> \n#include <iostream>\n\n#include \"PokeyMAX7219Manager.h\"\n\nusing namespace std::chrono_literals;\n\nPokeyMAX7219Manager::PokeyMAX7219Manager(sPoKeysDevice *pokey, uint8_t chipSelect)\n{\n _chipSelect = chipSelect;\n _pokey = pokey;\n _driver = std::make_shared<MAX7219>();\n _stateMatrix = {{0, 0, 0, 0, 0, 0, 0, 0},\n {0, 0, 0, 0, 0, 0, 0, 0},\n {0, 0, 0, 0, 0, 0, 0, 0},\n {0, 0, 0, 0, 0, 0, 0, 0},\n {0, 0, 0, 0, 0, 0, 0, 0},\n {0, 0, 0, 0, 0, 0, 0, 0},\n {0, 0, 0, 0, 0, 0, 0, 0},\n {0, 0, 0, 0, 0, 0, 0, 0}};\n \n PK_SPIConfigure(_pokey, MAX7219_PRESCALER, MAX7219_FRAMEFORMAT);\n\n uint16_t packet = 0;\n packet = driver()->encodeOutputPacket(REG_DECODE_MODE, MODE_DECODE_B_OFF);\n deliverDisplayPacket(packet);\n packet = driver()->encodeOutputPacket(REG_SCAN_LIMIT, MODE_SCAN_LIMIT_ALL);\n deliverDisplayPacket(packet);\n packet = driver()->encodeOutputPacket(REG_SHUTDOWN, MODE_SHUTDOWN_OFF);\n deliverDisplayPacket(packet);\n packet = driver()->encodeOutputPacket(REG_DISPLAY_TEST, MODE_DISPLAY_TEST_OFF);\n deliverDisplayPacket(packet);\n packet = driver()->encodeOutputPacket(REG_INTENSITY, MODE_INTENSITY_HIGH);\n deliverDisplayPacket(packet);\n}\n\n PokeyMAX7219Manager::~PokeyMAX7219Manager(void) {}\n\nstd::shared_ptr<MAX7219> PokeyMAX7219Manager::driver(void)\n{\n return _driver;\n}\n\nvoid PokeyMAX7219Manager::setAllPinStates(bool enabled)\n{\n for (uint8_t col = 1; col < 9; col++) {\n for (uint8_t row = 1; row < 9; row++) {\n setPinState(col, row, enabled);\n }\n }\n}\n\n#define BYTE_TO_BINARY_PATTERN \"%c%c%c%c%c%c%c%c\\n\"\n#define BYTE_TO_BINARY(byte) \\\n (byte & 0x80 ? '1' : '0'), \\\n (byte & 0x40 ? '1' : '0'), \\\n (byte & 0x20 ? '1' : '0'), \\\n (byte & 0x10 ? '1' : '0'), \\\n (byte & 0x08 ? '1' : '0'), \\\n (byte & 0x04 ? '1' : '0'), \\\n (byte & 0x02 ? '1' : '0'), \\\n (byte & 0x01 ? '1' : '0') \n\nvoid PokeyMAX7219Manager::setPinState(uint8_t col, uint8_t row, bool enabled)\n{\n assert(col >= 1 && col <= 8 && row >=1 && row <= 8);\n\n \/\/ this function allows for eight states per column,\n \/\/ so get the row mask value with a shift by row\n \/\/ (see MODE_ROW_1 -> MODE_ROW_8)\n\n _stateMatrix[col - 1][row - 1] = enabled;\n\n \/\/ explicitly set the entire row of values to match stored state\n\n uint8_t rowMask = 0;\n uint8_t colRegister = REG_COL_1 + col - 1;\n uint16_t packet = driver()->encodeOutputPacket(colRegister, rowMask);\n\n \/\/ build up the mask for the entire col to which the row belongs\n\n for (uint8_t idx = 0; idx < 8; idx++) {\n if (_stateMatrix[col - 1][idx]) {\n\t rowMask |= (1 << idx);\n }\n }\n\n \/\/ PRINTF(\"---> COL REG BITS: \" BYTE_TO_BINARY_PATTERN, BYTE_TO_BINARY((&packet)[0]));\n \/\/ printf(\"---> COL ROW MASK BITS: \" BYTE_TO_BINARY_PATTERN, BYTE_TO_BINARY(((uint8_t*)&packet)[1]));\n\n if (deliverDisplayPacket(packet) != PK_OK) {\n throw std::runtime_error(\"failed to set MAX7219 pin state\");\n }\n}\n\n\/**\n * send MAX7219 packet to device via SPI interface\n *\/\nuint32_t PokeyMAX7219Manager::deliverDisplayPacket(uint16_t packet)\n{\n assert(_pokey);\n return PK_SPIWrite(_pokey, (uint8_t *)&packet, sizeof(packet), _chipSelect);\n}\n\nbool PokeyMAX7219Manager::RunTests(sPoKeysDevice *pokey, uint8_t chipSelect)\n{\n bool retVal = true;\n\n try {\n std::shared_ptr<PokeyMAX7219Manager> matrixManager = std::make_shared<PokeyMAX7219Manager>(pokey, chipSelect);\n \/\/matrixManager->setAllPinStates(true);\n std::this_thread::sleep_for(500ms);\n matrixManager->setAllPinStates(false);\n std::this_thread::sleep_for(500ms);\n\n for (uint8_t col = 1; col < 9; col++) {\n for (uint8_t row = 1; row < 9; row++) {\n matrixManager->setPinState(col, row, true);\n std::this_thread::sleep_for(250ms);\n }\n }\n \n matrixManager->setAllPinStates(false);\n }\n catch (std::runtime_error &err) {\n std::cout << \"ERROR: \" << err.what() << std::endl;\n retVal = false;\n }\n\n \/*\n std::shared_ptr<MAX7219> output = matrixManager->driver();\n\n uint16_t packet = 0;\n packet = output->encodeOutputPacket(REG_DECODE_MODE, MODE_DECODE_B_OFF);\n matrixManager->deliverDisplayPacket(packet);\n packet = output->encodeOutputPacket(REG_SCAN_LIMIT, MODE_SCAN_LIMIT_ALL);\n matrixManager->deliverDisplayPacket(packet);\n packet = output->encodeOutputPacket(REG_SHUTDOWN, MODE_SHUTDOWN_OFF);\n matrixManager->deliverDisplayPacket(packet);\n packet = output->encodeOutputPacket(REG_DISPLAY_TEST, MODE_DISPLAY_TEST_OFF);\n matrixManager->deliverDisplayPacket(packet);\n packet = 0;\n matrixManager->deliverDisplayPacket(packet);\n packet = output->encodeOutputPacket(REG_INTENSITY, MODE_INTENSITY_LOW);\n matrixManager->deliverDisplayPacket(packet);\n\n \/\/ more for show than for go, so to speak...\n\n for (uint8_t col = REG_COL_1; col <= REG_COL_8; col++) {\n packet = output->encodeOutputPacket(col, 0);\n matrixManager->deliverDisplayPacket(packet);\n std::this_thread::sleep_for(200ms);\n }\n\n for (uint8_t col = REG_COL_1; col <= REG_COL_8; col++) {\n for (uint8_t row = MODE_ROW_1; row <= MODE_ROW_8; row++) {\n packet = output->encodeOutputPacket(col, row);\n matrixManager->deliverDisplayPacket(packet);\n std::this_thread::sleep_for(10ms);\n }\n }\n *\/\n\n return retVal;\n}\n<commit_msg>Fix breakage in previous commit<commit_after>#include <string.h>\n#include <thread> \n#include <iostream>\n\n#include \"PokeyMAX7219Manager.h\"\n\nusing namespace std::chrono_literals;\n\nPokeyMAX7219Manager::PokeyMAX7219Manager(sPoKeysDevice *pokey, uint8_t chipSelect)\n{\n _chipSelect = chipSelect;\n _pokey = pokey;\n _driver = std::make_shared<MAX7219>();\n _stateMatrix = {{0, 0, 0, 0, 0, 0, 0, 0},\n {0, 0, 0, 0, 0, 0, 0, 0},\n {0, 0, 0, 0, 0, 0, 0, 0},\n {0, 0, 0, 0, 0, 0, 0, 0},\n {0, 0, 0, 0, 0, 0, 0, 0},\n {0, 0, 0, 0, 0, 0, 0, 0},\n {0, 0, 0, 0, 0, 0, 0, 0},\n {0, 0, 0, 0, 0, 0, 0, 0}};\n \n PK_SPIConfigure(_pokey, MAX7219_PRESCALER, MAX7219_FRAMEFORMAT);\n\n uint16_t packet = 0;\n packet = driver()->encodeOutputPacket(REG_DECODE_MODE, MODE_DECODE_B_OFF);\n deliverDisplayPacket(packet);\n packet = driver()->encodeOutputPacket(REG_SCAN_LIMIT, MODE_SCAN_LIMIT_ALL);\n deliverDisplayPacket(packet);\n packet = driver()->encodeOutputPacket(REG_SHUTDOWN, MODE_SHUTDOWN_OFF);\n deliverDisplayPacket(packet);\n packet = driver()->encodeOutputPacket(REG_DISPLAY_TEST, MODE_DISPLAY_TEST_OFF);\n deliverDisplayPacket(packet);\n packet = driver()->encodeOutputPacket(REG_INTENSITY, MODE_INTENSITY_HIGH);\n deliverDisplayPacket(packet);\n}\n\n PokeyMAX7219Manager::~PokeyMAX7219Manager(void) {}\n\nstd::shared_ptr<MAX7219> PokeyMAX7219Manager::driver(void)\n{\n return _driver;\n}\n\nvoid PokeyMAX7219Manager::setAllPinStates(bool enabled)\n{\n for (uint8_t col = 1; col < 9; col++) {\n for (uint8_t row = 1; row < 9; row++) {\n setPinState(col, row, enabled);\n }\n }\n}\n\n#define BYTE_TO_BINARY_PATTERN \"%c%c%c%c%c%c%c%c\\n\"\n#define BYTE_TO_BINARY(byte) \\\n (byte & 0x80 ? '1' : '0'), \\\n (byte & 0x40 ? '1' : '0'), \\\n (byte & 0x20 ? '1' : '0'), \\\n (byte & 0x10 ? '1' : '0'), \\\n (byte & 0x08 ? '1' : '0'), \\\n (byte & 0x04 ? '1' : '0'), \\\n (byte & 0x02 ? '1' : '0'), \\\n (byte & 0x01 ? '1' : '0') \n\nvoid PokeyMAX7219Manager::setPinState(uint8_t col, uint8_t row, bool enabled)\n{\n assert(col >= 1 && col <= 8 && row >=1 && row <= 8);\n\n \/\/ this function allows for eight states per column,\n \/\/ so get the row mask value with a shift by row\n \/\/ (see MODE_ROW_1 -> MODE_ROW_8)\n\n _stateMatrix[col - 1][row - 1] = enabled;\n\n \/\/ explicitly set the entire row of values to match stored state\n\n uint8_t rowMask = 0;\n uint8_t colRegister = REG_COL_1 + col - 1;\n\n \/\/ build up the mask for the entire col to which the row belongs\n\n for (uint8_t idx = 0; idx < 8; idx++) {\n if (_stateMatrix[col - 1][idx]) {\n\t rowMask |= (1 << idx);\n }\n }\n \n uint16_t packet = driver()->encodeOutputPacket(colRegister, rowMask);\n \n \/\/ PRINTF(\"---> COL REG BITS: \" BYTE_TO_BINARY_PATTERN, BYTE_TO_BINARY((&packet)[0]));\n \/\/ printf(\"---> COL ROW MASK BITS: \" BYTE_TO_BINARY_PATTERN, BYTE_TO_BINARY(((uint8_t*)&packet)[1]));\n\n if (deliverDisplayPacket(packet) != PK_OK) {\n throw std::runtime_error(\"failed to set MAX7219 pin state\");\n }\n}\n\n\/**\n * send MAX7219 packet to device via SPI interface\n *\/\nuint32_t PokeyMAX7219Manager::deliverDisplayPacket(uint16_t packet)\n{\n assert(_pokey);\n return PK_SPIWrite(_pokey, (uint8_t *)&packet, sizeof(packet), _chipSelect);\n}\n\nbool PokeyMAX7219Manager::RunTests(sPoKeysDevice *pokey, uint8_t chipSelect)\n{\n bool retVal = true;\n\n try {\n std::shared_ptr<PokeyMAX7219Manager> matrixManager = std::make_shared<PokeyMAX7219Manager>(pokey, chipSelect);\n matrixManager->setAllPinStates(true);\n std::this_thread::sleep_for(500ms);\n matrixManager->setAllPinStates(false);\n std::this_thread::sleep_for(500ms);\n\n for (uint8_t col = 1; col < 9; col++) {\n for (uint8_t row = 1; row < 9; row++) {\n matrixManager->setPinState(col, row, true);\n std::this_thread::sleep_for(250ms);\n }\n }\n \n matrixManager->setAllPinStates(false);\n }\n catch (std::runtime_error &err) {\n std::cout << \"ERROR: \" << err.what() << std::endl;\n retVal = false;\n }\n\n \/*\n std::shared_ptr<MAX7219> output = matrixManager->driver();\n\n uint16_t packet = 0;\n packet = output->encodeOutputPacket(REG_DECODE_MODE, MODE_DECODE_B_OFF);\n matrixManager->deliverDisplayPacket(packet);\n packet = output->encodeOutputPacket(REG_SCAN_LIMIT, MODE_SCAN_LIMIT_ALL);\n matrixManager->deliverDisplayPacket(packet);\n packet = output->encodeOutputPacket(REG_SHUTDOWN, MODE_SHUTDOWN_OFF);\n matrixManager->deliverDisplayPacket(packet);\n packet = output->encodeOutputPacket(REG_DISPLAY_TEST, MODE_DISPLAY_TEST_OFF);\n matrixManager->deliverDisplayPacket(packet);\n packet = 0;\n matrixManager->deliverDisplayPacket(packet);\n packet = output->encodeOutputPacket(REG_INTENSITY, MODE_INTENSITY_LOW);\n matrixManager->deliverDisplayPacket(packet);\n\n \/\/ more for show than for go, so to speak...\n\n for (uint8_t col = REG_COL_1; col <= REG_COL_8; col++) {\n packet = output->encodeOutputPacket(col, 0);\n matrixManager->deliverDisplayPacket(packet);\n std::this_thread::sleep_for(200ms);\n }\n\n for (uint8_t col = REG_COL_1; col <= REG_COL_8; col++) {\n for (uint8_t row = MODE_ROW_1; row <= MODE_ROW_8; row++) {\n packet = output->encodeOutputPacket(col, row);\n matrixManager->deliverDisplayPacket(packet);\n std::this_thread::sleep_for(10ms);\n }\n }\n *\/\n\n return retVal;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"sass.hpp\"\n#include \"ast.hpp\"\n#include \"environment.hpp\"\n\nnamespace Sass {\n\n template <typename T>\n Environment<T>::Environment(bool is_shadow)\n : local_frame_(std::map<std::string, T>()),\n parent_(0), is_shadow_(false)\n { }\n template <typename T>\n Environment<T>::Environment(Environment<T>* env, bool is_shadow)\n : local_frame_(std::map<std::string, T>()),\n parent_(env), is_shadow_(is_shadow)\n { }\n template <typename T>\n Environment<T>::Environment(Environment<T>& env, bool is_shadow)\n : local_frame_(std::map<std::string, T>()),\n parent_(&env), is_shadow_(is_shadow)\n { }\n\n \/\/ link parent to create a stack\n template <typename T>\n void Environment<T>::link(Environment& env) { parent_ = &env; }\n template <typename T>\n void Environment<T>::link(Environment* env) { parent_ = env; }\n\n \/\/ this is used to find the global frame\n \/\/ which is the second last on the stack\n template <typename T>\n bool Environment<T>::is_lexical() const\n {\n return !! parent_ && parent_->parent_;\n }\n\n \/\/ only match the real root scope\n \/\/ there is still a parent around\n \/\/ not sure what it is actually use for\n \/\/ I guess we store functions etc. there\n template <typename T>\n bool Environment<T>::is_global() const\n {\n return parent_ && ! parent_->parent_;\n }\n\n template <typename T>\n std::map<std::string, T>& Environment<T>::local_frame() {\n return local_frame_;\n }\n\n template <typename T>\n bool Environment<T>::has_local(const std::string& key) const\n { return local_frame_.find(key) != local_frame_.end(); }\n\n template <typename T>\n T& Environment<T>::get_local(const std::string& key)\n { return local_frame_[key]; }\n\n template <typename T>\n void Environment<T>::set_local(const std::string& key, T val)\n {\n local_frame_[key] = val;\n }\n\n template <typename T>\n void Environment<T>::del_local(const std::string& key)\n { local_frame_.erase(key); }\n\n template <typename T>\n Environment<T>* Environment<T>::global_env()\n {\n Environment* cur = this;\n while (cur->is_lexical()) {\n cur = cur->parent_;\n }\n return cur;\n }\n\n template <typename T>\n bool Environment<T>::has_global(const std::string& key)\n { return global_env()->has(key); }\n\n template <typename T>\n T& Environment<T>::get_global(const std::string& key)\n { return (*global_env())[key]; }\n\n template <typename T>\n void Environment<T>::set_global(const std::string& key, T val)\n {\n global_env()->local_frame_[key] = val;\n }\n\n template <typename T>\n void Environment<T>::del_global(const std::string& key)\n { global_env()->local_frame_.erase(key); }\n\n template <typename T>\n Environment<T>* Environment<T>::lexical_env(const std::string& key)\n {\n Environment* cur = this;\n while (cur) {\n if (cur->has_local(key)) {\n return cur;\n }\n cur = cur->parent_;\n }\n return this;\n }\n\n \/\/ see if we have a lexical variable\n \/\/ move down the stack but stop before we\n \/\/ reach the global frame (is not included)\n template <typename T>\n bool Environment<T>::has_lexical(const std::string& key) const\n {\n auto cur = this;\n while (cur->is_lexical()) {\n if (cur->has_local(key)) return true;\n cur = cur->parent_;\n }\n return false;\n }\n\n \/\/ see if we have a lexical we could update\n \/\/ either update already existing lexical value\n \/\/ or if flag is set, we create one if no lexical found\n template <typename T>\n void Environment<T>::set_lexical(const std::string& key, T val)\n {\n auto cur = this; bool shadow = false;\n while (cur->is_lexical() || shadow) {\n if (cur->has_local(key)) {\n cur->set_local(key, val);\n return;\n }\n shadow = cur->is_shadow();\n cur = cur->parent_;\n }\n set_local(key, val);\n }\n\n \/\/ look on the full stack for key\n \/\/ include all scopes available\n template <typename T>\n bool Environment<T>::has(const std::string& key) const\n {\n auto cur = this;\n while (cur) {\n if (cur->has_local(key)) {\n return true;\n }\n cur = cur->parent_;\n }\n return false;\n }\n\n \/\/ use array access for getter and setter functions\n template <typename T>\n T& Environment<T>::operator[](const std::string& key)\n {\n auto cur = this;\n while (cur) {\n if (cur->has_local(key)) {\n return cur->get_local(key);\n }\n cur = cur->parent_;\n }\n return get_local(key);\n }\n\n #ifdef DEBUG\n template <typename T>\n size_t Environment<T>::print(std::string prefix)\n {\n size_t indent = 0;\n if (parent_) indent = parent_->print(prefix) + 1;\n std::cerr << prefix << std::string(indent, ' ') << \"== \" << this << std::endl;\n for (typename std::map<std::string, T>::iterator i = local_frame_.begin(); i != local_frame_.end(); ++i) {\n if (!ends_with(i->first, \"[f]\") && !ends_with(i->first, \"[f]4\") && !ends_with(i->first, \"[f]2\")) {\n std::cerr << prefix << std::string(indent, ' ') << i->first << \" \" << i->second;\n if (Value* val = dynamic_cast<Value*>(i->second))\n { std::cerr << \" : \" << val->to_string(true, 5); }\n std::cerr << std::endl;\n }\n }\n return indent ;\n }\n #endif\n\n \/\/ compile implementation for AST_Node\n template class Environment<AST_Node*>;\n\n}\n\n<commit_msg>Fix DEBUG print template<commit_after>#include \"sass.hpp\"\n#include \"ast.hpp\"\n#include \"environment.hpp\"\n\nnamespace Sass {\n\n template <typename T>\n Environment<T>::Environment(bool is_shadow)\n : local_frame_(std::map<std::string, T>()),\n parent_(0), is_shadow_(false)\n { }\n template <typename T>\n Environment<T>::Environment(Environment<T>* env, bool is_shadow)\n : local_frame_(std::map<std::string, T>()),\n parent_(env), is_shadow_(is_shadow)\n { }\n template <typename T>\n Environment<T>::Environment(Environment<T>& env, bool is_shadow)\n : local_frame_(std::map<std::string, T>()),\n parent_(&env), is_shadow_(is_shadow)\n { }\n\n \/\/ link parent to create a stack\n template <typename T>\n void Environment<T>::link(Environment& env) { parent_ = &env; }\n template <typename T>\n void Environment<T>::link(Environment* env) { parent_ = env; }\n\n \/\/ this is used to find the global frame\n \/\/ which is the second last on the stack\n template <typename T>\n bool Environment<T>::is_lexical() const\n {\n return !! parent_ && parent_->parent_;\n }\n\n \/\/ only match the real root scope\n \/\/ there is still a parent around\n \/\/ not sure what it is actually use for\n \/\/ I guess we store functions etc. there\n template <typename T>\n bool Environment<T>::is_global() const\n {\n return parent_ && ! parent_->parent_;\n }\n\n template <typename T>\n std::map<std::string, T>& Environment<T>::local_frame() {\n return local_frame_;\n }\n\n template <typename T>\n bool Environment<T>::has_local(const std::string& key) const\n { return local_frame_.find(key) != local_frame_.end(); }\n\n template <typename T>\n T& Environment<T>::get_local(const std::string& key)\n { return local_frame_[key]; }\n\n template <typename T>\n void Environment<T>::set_local(const std::string& key, T val)\n {\n local_frame_[key] = val;\n }\n\n template <typename T>\n void Environment<T>::del_local(const std::string& key)\n { local_frame_.erase(key); }\n\n template <typename T>\n Environment<T>* Environment<T>::global_env()\n {\n Environment* cur = this;\n while (cur->is_lexical()) {\n cur = cur->parent_;\n }\n return cur;\n }\n\n template <typename T>\n bool Environment<T>::has_global(const std::string& key)\n { return global_env()->has(key); }\n\n template <typename T>\n T& Environment<T>::get_global(const std::string& key)\n { return (*global_env())[key]; }\n\n template <typename T>\n void Environment<T>::set_global(const std::string& key, T val)\n {\n global_env()->local_frame_[key] = val;\n }\n\n template <typename T>\n void Environment<T>::del_global(const std::string& key)\n { global_env()->local_frame_.erase(key); }\n\n template <typename T>\n Environment<T>* Environment<T>::lexical_env(const std::string& key)\n {\n Environment* cur = this;\n while (cur) {\n if (cur->has_local(key)) {\n return cur;\n }\n cur = cur->parent_;\n }\n return this;\n }\n\n \/\/ see if we have a lexical variable\n \/\/ move down the stack but stop before we\n \/\/ reach the global frame (is not included)\n template <typename T>\n bool Environment<T>::has_lexical(const std::string& key) const\n {\n auto cur = this;\n while (cur->is_lexical()) {\n if (cur->has_local(key)) return true;\n cur = cur->parent_;\n }\n return false;\n }\n\n \/\/ see if we have a lexical we could update\n \/\/ either update already existing lexical value\n \/\/ or if flag is set, we create one if no lexical found\n template <typename T>\n void Environment<T>::set_lexical(const std::string& key, T val)\n {\n auto cur = this; bool shadow = false;\n while (cur->is_lexical() || shadow) {\n if (cur->has_local(key)) {\n cur->set_local(key, val);\n return;\n }\n shadow = cur->is_shadow();\n cur = cur->parent_;\n }\n set_local(key, val);\n }\n\n \/\/ look on the full stack for key\n \/\/ include all scopes available\n template <typename T>\n bool Environment<T>::has(const std::string& key) const\n {\n auto cur = this;\n while (cur) {\n if (cur->has_local(key)) {\n return true;\n }\n cur = cur->parent_;\n }\n return false;\n }\n\n \/\/ use array access for getter and setter functions\n template <typename T>\n T& Environment<T>::operator[](const std::string& key)\n {\n auto cur = this;\n while (cur) {\n if (cur->has_local(key)) {\n return cur->get_local(key);\n }\n cur = cur->parent_;\n }\n return get_local(key);\n }\n\n #ifdef DEBUG\n template <typename T>\n size_t Environment<T>::print(std::string prefix)\n {\n size_t indent = 0;\n if (parent_) indent = parent_->print(prefix) + 1;\n std::cerr << prefix << std::string(indent, ' ') << \"== \" << this << std::endl;\n for (typename std::map<std::string, T>::iterator i = local_frame_.begin(); i != local_frame_.end(); ++i) {\n if (!ends_with(i->first, \"[f]\") && !ends_with(i->first, \"[f]4\") && !ends_with(i->first, \"[f]2\")) {\n std::cerr << prefix << std::string(indent, ' ') << i->first << \" \" << i->second;\n if (Value* val = dynamic_cast<Value*>(i->second))\n { std::cerr << \" : \" << val->to_string(); }\n std::cerr << std::endl;\n }\n }\n return indent ;\n }\n #endif\n\n \/\/ compile implementation for AST_Node\n template class Environment<AST_Node*>;\n\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/*\r\n Copyright (C) 2006 by Marten Svanfeldt\r\n\r\n This library is free software; you can redistribute it and\/or\r\n modify it under the terms of the GNU Lesser General Public\r\n License as published by the Free Software Foundation; either\r\n version 2 of the License, or (at your option) any later version.\r\n\r\n This library is distributed in the hope that it will be useful,\r\n but WITHOUT ANY WARRANTY; without even the implied warranty of\r\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\r\n Library General Public License for more details.\r\n\r\n You should have received a copy of the GNU Library General Public\r\n License along with this library; if not, write to the Free\r\n Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\r\n*\/\r\n\r\n#include \"cssysdef.h\"\r\n\r\n#include \"csutil\/threading\/thread.h\"\r\n#include \"csutil\/threading\/pthread_thread.h\"\r\n#include \"csutil\/threading\/barrier.h\"\r\n#include \"csutil\/threading\/condition.h\"\r\n\r\n\r\nnamespace CS\r\n{\r\nnamespace Threading\r\n{\r\nnamespace Implementation\r\n{\r\n\r\n namespace\r\n {\r\n\r\n class ThreadStartParams : public CS::Memory::CustomAllocated\r\n {\r\n public:\r\n ThreadStartParams (ThreadBase* thread, Runnable* runner, int32* isRunningPtr, \r\n Barrier* startupBarrier)\r\n : thread (thread), runnable (runner), isRunningPtr (isRunningPtr), \r\n startupBarrier (startupBarrier)\r\n {\r\n }\r\n\r\n ThreadBase* thread;\r\n Runnable* runnable;\r\n int32* isRunningPtr;\r\n Barrier* startupBarrier;\r\n };\r\n\r\n void* proxyFunc (void* param)\r\n {\r\n \/\/ Extract the parameters\r\n ThreadStartParams* tp = static_cast<ThreadStartParams*> (param);\r\n csRef<ThreadBase> thread (tp->thread);\r\n int32* isRunningPtr = tp->isRunningPtr;\r\n Runnable* runnable = tp->runnable;\r\n Barrier* startupBarrier = tp->startupBarrier;\r\n\r\n \/\/ Set as running and wait for main thread to catch up\r\n AtomicOperations::Set (isRunningPtr, 1);\r\n startupBarrier->Wait ();\r\n\r\n #ifdef CS_HAVE_PTHREAD_SETNAME_NP\r\n {\r\n\t\/\/ Set the name, for debugging\r\n\tconst char* threadName = runnable->GetName ();\r\n\tif (threadName)\r\n\t pthread_setname_np (thread->threadHandle, threadName);\r\n }\r\n #endif\r\n \r\n \/\/ Run \r\n runnable->Run ();\r\n\r\n \/\/ Set as non-running\r\n AtomicOperations::Set (isRunningPtr, 0);\r\n \r\n return 0;\r\n }\r\n\r\n }\r\n\r\n\r\n ThreadBase::ThreadBase (Runnable* runnable)\r\n : runnable (runnable), isRunning (0), priority (THREAD_PRIO_NORMAL),\r\n startupBarrier (2)\r\n {\r\n }\r\n\r\n void ThreadBase::Start ()\r\n {\r\n if (!IsRunning ())\r\n { \r\n ThreadStartParams param (this, runnable, &isRunning, &startupBarrier);\r\n\r\n pthread_attr_t attr;\r\n pthread_attr_init(&attr);\r\n pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);\r\n pthread_create(&threadHandle, &attr, proxyFunc, ¶m); \r\n \r\n startupBarrier.Wait ();\r\n\r\n \/\/ Set priority to make sure its updated if we set it before starting\r\n SetPriority (priority);\r\n }\r\n }\r\n\r\n void ThreadBase::Stop ()\r\n {\r\n if (IsRunning ())\r\n {\r\n int res = pthread_cancel (threadHandle);\r\n if (res == 0)\r\n {\r\n AtomicOperations::Set (&isRunning, 0);\r\n }\r\n }\r\n }\r\n\r\n bool ThreadBase::IsRunning () const\r\n {\r\n return (AtomicOperations::Read ((int32*)&isRunning) != 0);\r\n }\r\n\r\n bool ThreadBase::SetPriority (ThreadPriority prio)\r\n {\r\n int res = 1;\r\n \r\n if (IsRunning ())\r\n { \r\n struct sched_param SchedulerProperties;\r\n\r\n \/\/ Clear the properties initially\r\n memset(&SchedulerProperties, 0, sizeof (struct sched_param));\r\n\r\n \/\/ Map the CS thread priority identifier to an appropriate platform specific identifier\r\n \/\/ or fail if this mapping is not possible.\r\n switch(prio)\r\n {\r\n case THREAD_PRIO_LOW:\r\n \/\/ Posix Pthreads does not guarantee support for any compatible priority,\r\n \/\/ so we'll default to NORMAL\r\n case THREAD_PRIO_NORMAL:\r\n SchedulerProperties.sched_priority = sched_get_priority_max (SCHED_OTHER);\r\n res = pthread_setschedparam (threadHandle, SCHED_OTHER, &SchedulerProperties);\r\n break;\r\n\r\n case THREAD_PRIO_HIGH:\r\n SchedulerProperties.sched_priority = sched_get_priority_max (SCHED_RR) - 1;\r\n res = pthread_setschedparam (threadHandle, SCHED_RR, &SchedulerProperties);\r\n break;\r\n }\r\n }\r\n\r\n if (res != 0)\r\n {\r\n priority = prio;\r\n }\r\n\r\n return res != 0;\r\n }\r\n\r\n void ThreadBase::Wait () const\r\n {\r\n if (IsRunning ())\r\n {\r\n pthread_join (threadHandle,0);\r\n }\r\n }\r\n\r\n void ThreadBase::Yield () \r\n {\r\n sched_yield ();\r\n }\r\n\r\n ThreadID ThreadBase::GetThreadID ()\r\n {\r\n return (ThreadID)pthread_self();\r\n }\r\n}\r\n}\r\n}\r\n<commit_msg>Compile fix<commit_after>\/*\r\n Copyright (C) 2006 by Marten Svanfeldt\r\n\r\n This library is free software; you can redistribute it and\/or\r\n modify it under the terms of the GNU Lesser General Public\r\n License as published by the Free Software Foundation; either\r\n version 2 of the License, or (at your option) any later version.\r\n\r\n This library is distributed in the hope that it will be useful,\r\n but WITHOUT ANY WARRANTY; without even the implied warranty of\r\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\r\n Library General Public License for more details.\r\n\r\n You should have received a copy of the GNU Library General Public\r\n License along with this library; if not, write to the Free\r\n Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\r\n*\/\r\n\r\n#include \"cssysdef.h\"\r\n\r\n#include \"csutil\/threading\/thread.h\"\r\n#include \"csutil\/threading\/pthread_thread.h\"\r\n#include \"csutil\/threading\/barrier.h\"\r\n#include \"csutil\/threading\/condition.h\"\r\n\r\n\r\nnamespace CS\r\n{\r\nnamespace Threading\r\n{\r\nnamespace Implementation\r\n{\r\n\r\n namespace\r\n {\r\n\r\n class ThreadStartParams : public CS::Memory::CustomAllocated\r\n {\r\n public:\r\n ThreadStartParams (ThreadBase* thread, Runnable* runner, int32* isRunningPtr, \r\n Barrier* startupBarrier)\r\n : thread (thread), runnable (runner), isRunningPtr (isRunningPtr), \r\n startupBarrier (startupBarrier)\r\n {\r\n }\r\n\r\n ThreadBase* thread;\r\n Runnable* runnable;\r\n int32* isRunningPtr;\r\n Barrier* startupBarrier;\r\n };\r\n\r\n void* proxyFunc (void* param)\r\n {\r\n \/\/ Extract the parameters\r\n ThreadStartParams* tp = static_cast<ThreadStartParams*> (param);\r\n csRef<ThreadBase> thread (tp->thread);\r\n int32* isRunningPtr = tp->isRunningPtr;\r\n Runnable* runnable = tp->runnable;\r\n Barrier* startupBarrier = tp->startupBarrier;\r\n\r\n \/\/ Set as running and wait for main thread to catch up\r\n AtomicOperations::Set (isRunningPtr, 1);\r\n startupBarrier->Wait ();\r\n\r\n #ifdef CS_HAVE_PTHREAD_SETNAME_NP\r\n {\r\n\t\/\/ Set the name, for debugging\r\n\tconst char* threadName = runnable->GetName ();\r\n\tif (threadName)\r\n\t pthread_setname_np (pthread_self(), threadName);\r\n }\r\n #endif\r\n \r\n \/\/ Run \r\n runnable->Run ();\r\n\r\n \/\/ Set as non-running\r\n AtomicOperations::Set (isRunningPtr, 0);\r\n \r\n return 0;\r\n }\r\n\r\n }\r\n\r\n\r\n ThreadBase::ThreadBase (Runnable* runnable)\r\n : runnable (runnable), isRunning (0), priority (THREAD_PRIO_NORMAL),\r\n startupBarrier (2)\r\n {\r\n }\r\n\r\n void ThreadBase::Start ()\r\n {\r\n if (!IsRunning ())\r\n { \r\n ThreadStartParams param (this, runnable, &isRunning, &startupBarrier);\r\n\r\n pthread_attr_t attr;\r\n pthread_attr_init(&attr);\r\n pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);\r\n pthread_create(&threadHandle, &attr, proxyFunc, ¶m); \r\n \r\n startupBarrier.Wait ();\r\n\r\n \/\/ Set priority to make sure its updated if we set it before starting\r\n SetPriority (priority);\r\n }\r\n }\r\n\r\n void ThreadBase::Stop ()\r\n {\r\n if (IsRunning ())\r\n {\r\n int res = pthread_cancel (threadHandle);\r\n if (res == 0)\r\n {\r\n AtomicOperations::Set (&isRunning, 0);\r\n }\r\n }\r\n }\r\n\r\n bool ThreadBase::IsRunning () const\r\n {\r\n return (AtomicOperations::Read ((int32*)&isRunning) != 0);\r\n }\r\n\r\n bool ThreadBase::SetPriority (ThreadPriority prio)\r\n {\r\n int res = 1;\r\n \r\n if (IsRunning ())\r\n { \r\n struct sched_param SchedulerProperties;\r\n\r\n \/\/ Clear the properties initially\r\n memset(&SchedulerProperties, 0, sizeof (struct sched_param));\r\n\r\n \/\/ Map the CS thread priority identifier to an appropriate platform specific identifier\r\n \/\/ or fail if this mapping is not possible.\r\n switch(prio)\r\n {\r\n case THREAD_PRIO_LOW:\r\n \/\/ Posix Pthreads does not guarantee support for any compatible priority,\r\n \/\/ so we'll default to NORMAL\r\n case THREAD_PRIO_NORMAL:\r\n SchedulerProperties.sched_priority = sched_get_priority_max (SCHED_OTHER);\r\n res = pthread_setschedparam (threadHandle, SCHED_OTHER, &SchedulerProperties);\r\n break;\r\n\r\n case THREAD_PRIO_HIGH:\r\n SchedulerProperties.sched_priority = sched_get_priority_max (SCHED_RR) - 1;\r\n res = pthread_setschedparam (threadHandle, SCHED_RR, &SchedulerProperties);\r\n break;\r\n }\r\n }\r\n\r\n if (res != 0)\r\n {\r\n priority = prio;\r\n }\r\n\r\n return res != 0;\r\n }\r\n\r\n void ThreadBase::Wait () const\r\n {\r\n if (IsRunning ())\r\n {\r\n pthread_join (threadHandle,0);\r\n }\r\n }\r\n\r\n void ThreadBase::Yield () \r\n {\r\n sched_yield ();\r\n }\r\n\r\n ThreadID ThreadBase::GetThreadID ()\r\n {\r\n return (ThreadID)pthread_self();\r\n }\r\n}\r\n}\r\n}\r\n<|endoftext|>"} {"text":"<commit_before>\n\/*\n * Copyright (C) 2010, Victor Semionov\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND\n * CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES,\n * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\n * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS\n * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,\n * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE\n * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH\n * DAMAGE.\n *\/\n\n#include <climits>\n\n#include <string>\n#include <vector>\n#include <set>\n#include <ostream>\n#include <iostream>\n\n#include \"Poco\/Util\/ServerApplication.h\"\n#include \"Poco\/URI.h\"\n#include \"Poco\/File.h\"\n#include \"Poco\/DirectoryIterator.h\"\n#include \"Poco\/NumberFormatter.h\"\n\n#include \"IndigoRequestHandler.h\"\n#include \"IndigoConfiguration.h\"\n\nusing namespace std;\n\nusing namespace Poco;\nusing namespace Poco::Util;\nusing namespace Poco::Net;\n\nPOCO_DECLARE_EXCEPTION(, ShareNotFoundException, ApplicationException)\nPOCO_IMPLEMENT_EXCEPTION(ShareNotFoundException, ApplicationException, \"ShareNotFoundException\")\n\nIndigoRequestHandler::IndigoRequestHandler()\n{\n}\n\nvoid IndigoRequestHandler::handleRequest(HTTPServerRequest &request, HTTPServerResponse &response)\n{\n\tlogRequest(request);\n\n\tconst string &method = request.getMethod();\n\n\tif (method != HTTPRequest::HTTP_GET)\n\t{\n\t\tsendMethodNotAllowed(response);\n\t\treturn;\n\t}\n\n\tURI uri;\n\ttry\n\t{\n\t\turi = request.getURI();\n\t}\n\tcatch (SyntaxException &se)\n\t{\n\t\tsendBadRequest(response);\n\t\treturn;\n\t}\n\n\tconst string processedURI = uri.getPath();\n\tconst Path uriPath(processedURI, Path::PATH_UNIX);\n\n\tif (!uriPath.isAbsolute())\n\t{\n\t\tsendBadRequest(response);\n\t\treturn;\n\t}\n\n\tconst IndigoConfiguration &configuration = IndigoConfiguration::get();\n\n\ttry\n\t{\n\t\tif (uriPath.isDirectory() && uriPath.depth() == 0)\n\t\t{\n\t\t\tif (configuration.virtualRoot())\n\t\t\t{\n\t\t\t\tsendVirtualIndex(response);\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\n\t\tconst Path fsPath = resolveFSPath(uriPath);\n\t\tconst string target = fsPath.toString();\n\n\t\tFile f(target);\n\n\t\tif (uriPath.isDirectory())\n\t\t{\n\t\t\tif (f.isDirectory())\n\t\t\t{\n\t\t\t\tsendDirectoryIndex(response, target, processedURI);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tsendNotFound(response);\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif (f.isDirectory())\n\t\t\t{\n\t\t\t\tPath uriDirPath = uriPath;\n\t\t\t\turiDirPath.makeDirectory();\n\t\t\t\tredirectToDirectory(response, uriDirPath.toString(Path::PATH_UNIX), false);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tsendFile(response, fsPath);\n\t\t\t}\n\t\t}\n\t}\n\tcatch (ShareNotFoundException &snfe)\n\t{\n\t\tsendNotFound(response);\n\t}\n\tcatch (FileNotFoundException &fnfe)\n\t{\n\t\tsendNotFound(response);\n\t}\n\tcatch (FileAccessDeniedException &fade)\n\t{\n\t\tsendForbidden(response);\n\t}\n\tcatch (FileException &fe)\n\t{\n\t\tsendInternalServerError(response);\n\t}\n\tcatch (PathSyntaxException &pse)\n\t{\n\t\tsendNotImplemented(response);\n\t}\n\tcatch (...)\n\t{\n\t\tsendInternalServerError(response);\n\t}\n}\n\nPath IndigoRequestHandler::resolveFSPath(const Path &uriPath)\n{\n\tconst IndigoConfiguration &configuration = IndigoConfiguration::get();\n\n\tconst string &shareName = uriPath[0];\n\tstring base = configuration.getSharePath(shareName);\n\tbool share = true;\n\n\tif (base.empty())\n\t{\n\t\tbase = configuration.getRoot();\n\t\tif (base.empty())\n\t\t\tthrow ShareNotFoundException();\n\n\t\tshare = false;\n\t}\n\n\tPath fsPath(base);\n\n\tif (share)\n\t{\n\t\tfsPath.makeDirectory();\n\n\t\tint d = uriPath.depth();\n\t\tfor (int i = 1; i <= d; i++)\n\t\t\tfsPath.pushDirectory(uriPath[i]);\n\t}\n\telse\n\t{\n\t\tfsPath.append(uriPath);\n\t}\n\n\tfsPath.makeFile();\n\treturn fsPath;\n}\n\nvoid IndigoRequestHandler::sendFile(HTTPServerResponse &response, const Path &path)\n{\n\tstring ext = path.getExtension();\n\tconst string &mediaType = IndigoConfiguration::get().getMimeType(ext);\n\tresponse.sendFile(path.toString(), mediaType);\n}\n\nvoid IndigoRequestHandler::sendFile(HTTPServerResponse &response, const string &path)\n{\n\tstring ext = Path(path).getExtension();\n\tconst string &mediaType = IndigoConfiguration::get().getMimeType(ext);\n\tresponse.sendFile(path, mediaType);\n}\n\nvoid IndigoRequestHandler::sendDirectoryListing(HTTPServerResponse &response, const string &uri, const vector<string> &entries)\n{\n\tbool root = (uri == \"\/\");\n\n\tresponse.setContentType(\"text\/html\");\n\tresponse.setContentLength(HTTPResponse::UNKNOWN_CONTENT_LENGTH);\n\tresponse.setChunkedTransferEncoding(true);\n\n\tostream &out = response.send();\n\n\tout << \"<html>\" << endl;\n\tout << \"<head>\" << endl;\n\tout << \"<title>\";\n\tout << \"Index of \" << uri;\n\tout << \"<\/title>\" << endl;\n\tout << \"<\/head>\" << endl;\n\tout << \"<body>\" << endl;\n\tout << \"<h1>\";\n\tout << \"Index of \" << uri;\n\tout << \"<\/h1>\" << endl;\n\n\tif (!root)\n\t{\n\t\tout << \"<a href=\\\"..\/\\\"><Parent Directory><\/a><br>\" << endl;\n\t}\n\n\tint l = entries.size();\n\tfor (int i = 0; i < l; i++)\n\t{\n\t\tout << \"<a href=\\\"\" << entries[i] << \"\\\">\" << entries[i] << \"<\/a>\" << \"<br>\" << endl;\n\t}\n\n\tout << \"<\/body>\" << endl;\n\tout << \"<\/html>\" << endl;\n}\n\nPath IndigoRequestHandler::findVirtualIndex()\n{\n\tconst IndigoConfiguration &configuration = IndigoConfiguration::get();\n\n\tconst set<string> &indexes = configuration.getIndexes();\n\n\tset<string>::const_iterator it;\n\tset<string>::const_iterator end = indexes.end();\n\tfor (it = indexes.begin(); it != end; ++it)\n\t{\n\t\ttry\n\t\t{\n\t\t\tPath indexURI = Path('\/' + *it, Path::PATH_UNIX);\n\t\t\tPath index = resolveFSPath(indexURI);\n\n\t\t\tFile f(index);\n\t\t\tif (f.isFile())\n\t\t\t\treturn index;\n\t\t}\n\t\tcatch (ShareNotFoundException &snfe)\n\t\t{\n\t\t}\n\t\tcatch (FileException &fe)\n\t\t{\n\t\t}\n\t\tcatch (PathSyntaxException &pse)\n\t\t{\n\t\t}\n\t}\n\n\treturn Path(false);\n}\n\nvoid IndigoRequestHandler::sendVirtualIndex(HTTPServerResponse &response)\n{\n\tconst IndigoConfiguration &configuration = IndigoConfiguration::get();\n\n\tPath index = findVirtualIndex();\n\tif (index.isAbsolute())\n\t{\n\t\tsendFile(response, index);\n\t\treturn;\n\t}\n\n\tif (!configuration.getAutoIndex())\n\t\tthrow ShareNotFoundException();\n\n\tconst set<string> &shares = configuration.getShares();\n\tvector<string> entries;\n\n\tset<string>::const_iterator it;\n\tset<string>::const_iterator end = shares.end();\n\tfor (it = shares.begin(); it != end; ++it)\n\t{\n\t\tconst string &shareName = *it;\n\t\ttry\n\t\t{\n\t\t\tPath shareURI = Path('\/' + shareName, Path::PATH_UNIX);\n\t\t\tPath fsPath = resolveFSPath(shareURI);\n\t\t\tFile f(fsPath);\n\n\t\t\tif (!f.isHidden())\n\t\t\t{\n\t\t\t\tstring entry = shareName;\n\t\t\t\tif (f.isDirectory())\n\t\t\t\t\tentry += '\/';\n\n\t\t\t\tentries.push_back(entry);\n\t\t\t}\n\t\t}\n\t\tcatch (ShareNotFoundException &snfe)\n\t\t{\n\t\t}\n\t\tcatch (FileException &fe)\n\t\t{\n\t\t}\n\t\tcatch (PathSyntaxException &pse)\n\t\t{\n\t\t}\n\t}\n\n\tsendDirectoryListing(response, \"\/\", entries);\n}\n\nstring IndigoRequestHandler::findDirectoryIndex(const string &base)\n{\n\tconst IndigoConfiguration &configuration = IndigoConfiguration::get();\n\n\tconst set<string> &indexes = configuration.getIndexes(true);\n\n\tset<string>::const_iterator it;\n\tset<string>::const_iterator end = indexes.end();\n\tfor (it = indexes.begin(); it != end; ++it)\n\t{\n\t\ttry\n\t\t{\n\t\t\tstring index = base;\n\t\t\tif (index[index.length() - 1] != Path::separator())\n\t\t\t\tindex += Path::separator();\n\t\t\tindex += *it;\n\n\t\t\tFile f(index);\n\t\t\tif (f.isFile())\n\t\t\t\treturn index;\n\t\t}\n\t\tcatch (FileException &fe)\n\t\t{\n\t\t}\n\t\tcatch (PathSyntaxException &pse)\n\t\t{\n\t\t}\n\t}\n\n\treturn \"\";\n}\n\nvoid IndigoRequestHandler::sendDirectoryIndex(HTTPServerResponse &response, const string &path, const string &uri)\n{\n\tconst IndigoConfiguration &configuration = IndigoConfiguration::get();\n\n\tstring index = findDirectoryIndex(path);\n\tif (!index.empty())\n\t{\n\t\tsendFile(response, index);\n\t\treturn;\n\t}\n\n\tif (!configuration.getAutoIndex())\n\t\tthrow FileNotFoundException();\n\n\tvector<string> entries;\n\n\tDirectoryIterator it(path);\n\tDirectoryIterator end;\n\twhile (it != end)\n\t{\n\t\ttry\n\t\t{\n\t\t\tif (!it->isHidden())\n\t\t\t{\n\t\t\t\tstring entry = it.name();\n\t\t\t\tif (it->isDirectory())\n\t\t\t\t\tentry += '\/';\n\n\t\t\t\tentries.push_back(entry);\n\t\t\t}\n\t\t}\n\t\tcatch (FileException &fe)\n\t\t{\n\t\t}\n\t\tcatch (PathSyntaxException &pse)\n\t\t{\n\t\t}\n\n\t\t++it;\n\t}\n\n\tsendDirectoryListing(response, uri, entries);\n}\n\nvoid IndigoRequestHandler::redirectToDirectory(HTTPServerResponse &response, const string &uri, bool permanent)\n{\n\tif (!permanent)\n\t{\n\t\tresponse.redirect(uri);\n\t}\n\telse\n\t{\n\t\tresponse.setStatusAndReason(HTTPResponse::HTTP_MOVED_PERMANENTLY);\n\t\tresponse.setContentLength(0);\n\t\tresponse.setChunkedTransferEncoding(false);\n\t\tresponse.set(\"Location\", uri);\n\t\tresponse.send();\n\t}\n}\n\nvoid IndigoRequestHandler::logRequest(const HTTPServerRequest &request)\n{\n\tconst ServerApplication &app = dynamic_cast<ServerApplication &>(Application::instance());\n\tif (app.isInteractive())\n\t{\n\t\tconst string &method = request.getMethod();\n\t\tconst string &uri = request.getURI();\n\t\tstring host = request.clientAddress().host().toString();\n\n\t\tstring logString = host + \" - \" + method + \" \" + uri;\n\n\t\tapp.logger().information(logString);\n\t}\n}\n\nvoid IndigoRequestHandler::sendError(HTTPServerResponse &response, int code)\n{\n\tif (response.sent())\n\t\treturn;\n\n\tresponse.setStatusAndReason(HTTPResponse::HTTPStatus(code));\n\tresponse.setChunkedTransferEncoding(true);\n\tresponse.setContentType(\"text\/html\");\n\n\tconst string &reason = response.getReason();\n\n\tostream &out = response.send();\n\tout << \"<html>\";\n\tout << \"<head><title>\" + NumberFormatter::format(code) + \" \" + reason + \"<\/title><\/head>\";\n\tout << \"<body><h1>\" + reason + \"<\/h1><\/body>\";\n\tout << \"<\/html>\";\n}\n\nvoid IndigoRequestHandler::sendMethodNotAllowed(HTTPServerResponse &response)\n{\n\tsendError(response, HTTPResponse::HTTP_METHOD_NOT_ALLOWED);\n}\n\nvoid IndigoRequestHandler::sendRequestURITooLong(HTTPServerResponse &response)\n{\n\tsendError(response, HTTPResponse::HTTP_REQUESTURITOOLONG);\n}\n\nvoid IndigoRequestHandler::sendBadRequest(HTTPServerResponse &response)\n{\n\tsendError(response, HTTPResponse::HTTP_BAD_REQUEST);\n}\n\nvoid IndigoRequestHandler::sendNotImplemented(HTTPServerResponse &response)\n{\n\tsendError(response, HTTPResponse::HTTP_NOT_IMPLEMENTED);\n}\n\nvoid IndigoRequestHandler::sendNotFound(HTTPServerResponse &response)\n{\n\tsendError(response, HTTPResponse::HTTP_NOT_FOUND);\n}\n\nvoid IndigoRequestHandler::sendForbidden(HTTPServerResponse &response)\n{\n\tsendError(response, HTTPResponse::HTTP_FORBIDDEN);\n}\n\nvoid IndigoRequestHandler::sendInternalServerError(HTTPServerResponse &response)\n{\n\tsendError(response, HTTPResponse::HTTP_INTERNAL_SERVER_ERROR);\n}\n<commit_msg>Close the connection after sending an error.<commit_after>\n\/*\n * Copyright (C) 2010, Victor Semionov\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND\n * CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES,\n * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\n * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS\n * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,\n * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE\n * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH\n * DAMAGE.\n *\/\n\n#include <climits>\n\n#include <string>\n#include <vector>\n#include <set>\n#include <ostream>\n#include <iostream>\n\n#include \"Poco\/Util\/ServerApplication.h\"\n#include \"Poco\/URI.h\"\n#include \"Poco\/File.h\"\n#include \"Poco\/DirectoryIterator.h\"\n#include \"Poco\/NumberFormatter.h\"\n\n#include \"IndigoRequestHandler.h\"\n#include \"IndigoConfiguration.h\"\n\nusing namespace std;\n\nusing namespace Poco;\nusing namespace Poco::Util;\nusing namespace Poco::Net;\n\nPOCO_DECLARE_EXCEPTION(, ShareNotFoundException, ApplicationException)\nPOCO_IMPLEMENT_EXCEPTION(ShareNotFoundException, ApplicationException, \"ShareNotFoundException\")\n\nIndigoRequestHandler::IndigoRequestHandler()\n{\n}\n\nvoid IndigoRequestHandler::handleRequest(HTTPServerRequest &request, HTTPServerResponse &response)\n{\n\tlogRequest(request);\n\n\tconst string &method = request.getMethod();\n\n\tif (method != HTTPRequest::HTTP_GET)\n\t{\n\t\tsendMethodNotAllowed(response);\n\t\treturn;\n\t}\n\n\tURI uri;\n\ttry\n\t{\n\t\turi = request.getURI();\n\t}\n\tcatch (SyntaxException &se)\n\t{\n\t\tsendBadRequest(response);\n\t\treturn;\n\t}\n\n\tconst string processedURI = uri.getPath();\n\tconst Path uriPath(processedURI, Path::PATH_UNIX);\n\n\tif (!uriPath.isAbsolute())\n\t{\n\t\tsendBadRequest(response);\n\t\treturn;\n\t}\n\n\tconst IndigoConfiguration &configuration = IndigoConfiguration::get();\n\n\ttry\n\t{\n\t\tif (uriPath.isDirectory() && uriPath.depth() == 0)\n\t\t{\n\t\t\tif (configuration.virtualRoot())\n\t\t\t{\n\t\t\t\tsendVirtualIndex(response);\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\n\t\tconst Path fsPath = resolveFSPath(uriPath);\n\t\tconst string target = fsPath.toString();\n\n\t\tFile f(target);\n\n\t\tif (uriPath.isDirectory())\n\t\t{\n\t\t\tif (f.isDirectory())\n\t\t\t{\n\t\t\t\tsendDirectoryIndex(response, target, processedURI);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tsendNotFound(response);\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif (f.isDirectory())\n\t\t\t{\n\t\t\t\tPath uriDirPath = uriPath;\n\t\t\t\turiDirPath.makeDirectory();\n\t\t\t\tredirectToDirectory(response, uriDirPath.toString(Path::PATH_UNIX), false);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tsendFile(response, fsPath);\n\t\t\t}\n\t\t}\n\t}\n\tcatch (ShareNotFoundException &snfe)\n\t{\n\t\tsendNotFound(response);\n\t}\n\tcatch (FileNotFoundException &fnfe)\n\t{\n\t\tsendNotFound(response);\n\t}\n\tcatch (FileAccessDeniedException &fade)\n\t{\n\t\tsendForbidden(response);\n\t}\n\tcatch (FileException &fe)\n\t{\n\t\tsendInternalServerError(response);\n\t}\n\tcatch (PathSyntaxException &pse)\n\t{\n\t\tsendNotImplemented(response);\n\t}\n\tcatch (...)\n\t{\n\t\tsendInternalServerError(response);\n\t}\n}\n\nPath IndigoRequestHandler::resolveFSPath(const Path &uriPath)\n{\n\tconst IndigoConfiguration &configuration = IndigoConfiguration::get();\n\n\tconst string &shareName = uriPath[0];\n\tstring base = configuration.getSharePath(shareName);\n\tbool share = true;\n\n\tif (base.empty())\n\t{\n\t\tbase = configuration.getRoot();\n\t\tif (base.empty())\n\t\t\tthrow ShareNotFoundException();\n\n\t\tshare = false;\n\t}\n\n\tPath fsPath(base);\n\n\tif (share)\n\t{\n\t\tfsPath.makeDirectory();\n\n\t\tint d = uriPath.depth();\n\t\tfor (int i = 1; i <= d; i++)\n\t\t\tfsPath.pushDirectory(uriPath[i]);\n\t}\n\telse\n\t{\n\t\tfsPath.append(uriPath);\n\t}\n\n\tfsPath.makeFile();\n\treturn fsPath;\n}\n\nvoid IndigoRequestHandler::sendFile(HTTPServerResponse &response, const Path &path)\n{\n\tstring ext = path.getExtension();\n\tconst string &mediaType = IndigoConfiguration::get().getMimeType(ext);\n\tresponse.sendFile(path.toString(), mediaType);\n}\n\nvoid IndigoRequestHandler::sendFile(HTTPServerResponse &response, const string &path)\n{\n\tstring ext = Path(path).getExtension();\n\tconst string &mediaType = IndigoConfiguration::get().getMimeType(ext);\n\tresponse.sendFile(path, mediaType);\n}\n\nvoid IndigoRequestHandler::sendDirectoryListing(HTTPServerResponse &response, const string &uri, const vector<string> &entries)\n{\n\tbool root = (uri == \"\/\");\n\n\tresponse.setContentType(\"text\/html\");\n\tresponse.setContentLength(HTTPResponse::UNKNOWN_CONTENT_LENGTH);\n\tresponse.setChunkedTransferEncoding(true);\n\n\tostream &out = response.send();\n\n\tout << \"<html>\" << endl;\n\tout << \"<head>\" << endl;\n\tout << \"<title>\";\n\tout << \"Index of \" << uri;\n\tout << \"<\/title>\" << endl;\n\tout << \"<\/head>\" << endl;\n\tout << \"<body>\" << endl;\n\tout << \"<h1>\";\n\tout << \"Index of \" << uri;\n\tout << \"<\/h1>\" << endl;\n\n\tif (!root)\n\t{\n\t\tout << \"<a href=\\\"..\/\\\"><Parent Directory><\/a><br>\" << endl;\n\t}\n\n\tint l = entries.size();\n\tfor (int i = 0; i < l; i++)\n\t{\n\t\tout << \"<a href=\\\"\" << entries[i] << \"\\\">\" << entries[i] << \"<\/a>\" << \"<br>\" << endl;\n\t}\n\n\tout << \"<\/body>\" << endl;\n\tout << \"<\/html>\" << endl;\n}\n\nPath IndigoRequestHandler::findVirtualIndex()\n{\n\tconst IndigoConfiguration &configuration = IndigoConfiguration::get();\n\n\tconst set<string> &indexes = configuration.getIndexes();\n\n\tset<string>::const_iterator it;\n\tset<string>::const_iterator end = indexes.end();\n\tfor (it = indexes.begin(); it != end; ++it)\n\t{\n\t\ttry\n\t\t{\n\t\t\tPath indexURI = Path('\/' + *it, Path::PATH_UNIX);\n\t\t\tPath index = resolveFSPath(indexURI);\n\n\t\t\tFile f(index);\n\t\t\tif (f.isFile())\n\t\t\t\treturn index;\n\t\t}\n\t\tcatch (ShareNotFoundException &snfe)\n\t\t{\n\t\t}\n\t\tcatch (FileException &fe)\n\t\t{\n\t\t}\n\t\tcatch (PathSyntaxException &pse)\n\t\t{\n\t\t}\n\t}\n\n\treturn Path(false);\n}\n\nvoid IndigoRequestHandler::sendVirtualIndex(HTTPServerResponse &response)\n{\n\tconst IndigoConfiguration &configuration = IndigoConfiguration::get();\n\n\tPath index = findVirtualIndex();\n\tif (index.isAbsolute())\n\t{\n\t\tsendFile(response, index);\n\t\treturn;\n\t}\n\n\tif (!configuration.getAutoIndex())\n\t\tthrow ShareNotFoundException();\n\n\tconst set<string> &shares = configuration.getShares();\n\tvector<string> entries;\n\n\tset<string>::const_iterator it;\n\tset<string>::const_iterator end = shares.end();\n\tfor (it = shares.begin(); it != end; ++it)\n\t{\n\t\tconst string &shareName = *it;\n\t\ttry\n\t\t{\n\t\t\tPath shareURI = Path('\/' + shareName, Path::PATH_UNIX);\n\t\t\tPath fsPath = resolveFSPath(shareURI);\n\t\t\tFile f(fsPath);\n\n\t\t\tif (!f.isHidden())\n\t\t\t{\n\t\t\t\tstring entry = shareName;\n\t\t\t\tif (f.isDirectory())\n\t\t\t\t\tentry += '\/';\n\n\t\t\t\tentries.push_back(entry);\n\t\t\t}\n\t\t}\n\t\tcatch (ShareNotFoundException &snfe)\n\t\t{\n\t\t}\n\t\tcatch (FileException &fe)\n\t\t{\n\t\t}\n\t\tcatch (PathSyntaxException &pse)\n\t\t{\n\t\t}\n\t}\n\n\tsendDirectoryListing(response, \"\/\", entries);\n}\n\nstring IndigoRequestHandler::findDirectoryIndex(const string &base)\n{\n\tconst IndigoConfiguration &configuration = IndigoConfiguration::get();\n\n\tconst set<string> &indexes = configuration.getIndexes(true);\n\n\tset<string>::const_iterator it;\n\tset<string>::const_iterator end = indexes.end();\n\tfor (it = indexes.begin(); it != end; ++it)\n\t{\n\t\ttry\n\t\t{\n\t\t\tstring index = base;\n\t\t\tif (index[index.length() - 1] != Path::separator())\n\t\t\t\tindex += Path::separator();\n\t\t\tindex += *it;\n\n\t\t\tFile f(index);\n\t\t\tif (f.isFile())\n\t\t\t\treturn index;\n\t\t}\n\t\tcatch (FileException &fe)\n\t\t{\n\t\t}\n\t\tcatch (PathSyntaxException &pse)\n\t\t{\n\t\t}\n\t}\n\n\treturn \"\";\n}\n\nvoid IndigoRequestHandler::sendDirectoryIndex(HTTPServerResponse &response, const string &path, const string &uri)\n{\n\tconst IndigoConfiguration &configuration = IndigoConfiguration::get();\n\n\tstring index = findDirectoryIndex(path);\n\tif (!index.empty())\n\t{\n\t\tsendFile(response, index);\n\t\treturn;\n\t}\n\n\tif (!configuration.getAutoIndex())\n\t\tthrow FileNotFoundException();\n\n\tvector<string> entries;\n\n\tDirectoryIterator it(path);\n\tDirectoryIterator end;\n\twhile (it != end)\n\t{\n\t\ttry\n\t\t{\n\t\t\tif (!it->isHidden())\n\t\t\t{\n\t\t\t\tstring entry = it.name();\n\t\t\t\tif (it->isDirectory())\n\t\t\t\t\tentry += '\/';\n\n\t\t\t\tentries.push_back(entry);\n\t\t\t}\n\t\t}\n\t\tcatch (FileException &fe)\n\t\t{\n\t\t}\n\t\tcatch (PathSyntaxException &pse)\n\t\t{\n\t\t}\n\n\t\t++it;\n\t}\n\n\tsendDirectoryListing(response, uri, entries);\n}\n\nvoid IndigoRequestHandler::redirectToDirectory(HTTPServerResponse &response, const string &uri, bool permanent)\n{\n\tif (!permanent)\n\t{\n\t\tresponse.redirect(uri);\n\t}\n\telse\n\t{\n\t\tresponse.setStatusAndReason(HTTPResponse::HTTP_MOVED_PERMANENTLY);\n\t\tresponse.setContentLength(0);\n\t\tresponse.setChunkedTransferEncoding(false);\n\t\tresponse.set(\"Location\", uri);\n\t\tresponse.send();\n\t}\n}\n\nvoid IndigoRequestHandler::logRequest(const HTTPServerRequest &request)\n{\n\tconst ServerApplication &app = dynamic_cast<ServerApplication &>(Application::instance());\n\tif (app.isInteractive())\n\t{\n\t\tconst string &method = request.getMethod();\n\t\tconst string &uri = request.getURI();\n\t\tstring host = request.clientAddress().host().toString();\n\n\t\tstring logString = host + \" - \" + method + \" \" + uri;\n\n\t\tapp.logger().information(logString);\n\t}\n}\n\nvoid IndigoRequestHandler::sendError(HTTPServerResponse &response, int code)\n{\n\tif (response.sent())\n\t\treturn;\n\n\tresponse.setStatusAndReason(HTTPResponse::HTTPStatus(code));\n\tresponse.setChunkedTransferEncoding(false);\n\tresponse.setContentLength(HTTPResponse::UNKNOWN_CONTENT_LENGTH);\n\tresponse.setContentType(\"text\/html\");\n\tresponse.setKeepAlive(false);\n\n\tconst string &reason = response.getReason();\n\n\tostream &out = response.send();\n\tout << \"<html>\";\n\tout << \"<head><title>\" + NumberFormatter::format(code) + \" \" + reason + \"<\/title><\/head>\";\n\tout << \"<body><h1>\" + reason + \"<\/h1><\/body>\";\n\tout << \"<\/html>\";\n}\n\nvoid IndigoRequestHandler::sendMethodNotAllowed(HTTPServerResponse &response)\n{\n\tsendError(response, HTTPResponse::HTTP_METHOD_NOT_ALLOWED);\n}\n\nvoid IndigoRequestHandler::sendRequestURITooLong(HTTPServerResponse &response)\n{\n\tsendError(response, HTTPResponse::HTTP_REQUESTURITOOLONG);\n}\n\nvoid IndigoRequestHandler::sendBadRequest(HTTPServerResponse &response)\n{\n\tsendError(response, HTTPResponse::HTTP_BAD_REQUEST);\n}\n\nvoid IndigoRequestHandler::sendNotImplemented(HTTPServerResponse &response)\n{\n\tsendError(response, HTTPResponse::HTTP_NOT_IMPLEMENTED);\n}\n\nvoid IndigoRequestHandler::sendNotFound(HTTPServerResponse &response)\n{\n\tsendError(response, HTTPResponse::HTTP_NOT_FOUND);\n}\n\nvoid IndigoRequestHandler::sendForbidden(HTTPServerResponse &response)\n{\n\tsendError(response, HTTPResponse::HTTP_FORBIDDEN);\n}\n\nvoid IndigoRequestHandler::sendInternalServerError(HTTPServerResponse &response)\n{\n\tsendError(response, HTTPResponse::HTTP_INTERNAL_SERVER_ERROR);\n}\n<|endoftext|>"} {"text":"<commit_before>\n#include \"nui.h\"\n#include \"nuiDrawerView.h\"\n\nstatic const float SPRING_TOLERANCE = 0.0000000005f;\nstatic const float STIFFNESS = .3f;\nstatic const float PULL_COEF = 4;\nstatic const float MOVE_TOLERANCE = 8;\n\n\nnuiDrawerView::nuiDrawerView() :\nmpLeft(nullptr), mpMain(nullptr), mpRight(nullptr), mOffset(0), mTouched(false), mMoving(false), mOriginalOffset(0), mTargetOffset(0), mEventSink(this), mInteractive(true)\n{\n if (SetObjectClass(\"nuiDrawerView\"))\n {\n \/\/ Init attributes:\n AddAttribute(new nuiAttribute<bool>\n (nglString(_T(\"Interactive\")), nuiUnitBoolean,\n nuiMakeDelegate(this, &nuiDrawerView::GetInteractive),\n nuiMakeDelegate(this, &nuiDrawerView::SetInteractive)));\n\n AddAttribute(new nuiAttribute<float>\n (nglString(_T(\"AnimRatio\")), nuiUnitBoolean,\n nuiMakeDelegate(this, &nuiDrawerView::GetAnimRatio),\n nuiMakeDelegate(this, &nuiDrawerView::SetAnimRatio)));\n }\n\n NUI_ADD_EVENT(LeftOpened);\n NUI_ADD_EVENT(RightOpened);\n NUI_ADD_EVENT(Opened);\n NUI_ADD_EVENT(Closed);\n\n nuiAnimation::AcquireTimer();\n}\n\nnuiDrawerView::~nuiDrawerView()\n{\n nuiAnimation::ReleaseTimer();\n}\n\nvoid nuiDrawerView::OpenLeft()\n{\n if (!mpLeft)\n return;\n\n mMoving = false;\n mTouched = false;\n\n float width = mpLeft->GetIdealRect().GetWidth();\n mTargetOffset = width;\n\n if (mOffset != mTargetOffset)\n {\n mEventSink.Connect(nuiAnimation::GetTimer()->Tick, &nuiDrawerView::OnAnimateDrawer);\n }\n\n UpdateLayout();\n}\n\nvoid nuiDrawerView::OpenRight()\n{\n if (!mpRight)\n return;\n\n mMoving = false;\n mTouched = false;\n\n float width = mpRight->GetIdealRect().GetWidth();\n mTargetOffset = -width;\n\n if (mOffset != mTargetOffset)\n {\n mEventSink.Connect(nuiAnimation::GetTimer()->Tick, &nuiDrawerView::OnAnimateDrawer);\n }\n\n UpdateLayout();\n}\n\nvoid nuiDrawerView::Close()\n{\n mMoving = false;\n mTouched = false;\n\n mTargetOffset = 0;\n\n if (mOffset != mTargetOffset)\n {\n mEventSink.Connect(nuiAnimation::GetTimer()->Tick, &nuiDrawerView::OnAnimateDrawer);\n }\n\n UpdateLayout();\n}\n\nbool nuiDrawerView::IsOpen() const\n{\n return mTargetOffset != 0;\n}\n\nbool nuiDrawerView::IsLeftOpen() const\n{\n return mTargetOffset > 0;\n}\n\nbool nuiDrawerView::IsRightOpen() const\n{\n return mTargetOffset < 0;\n}\n\nvoid nuiDrawerView::ToggleLeft()\n{\n if (!IsLeftOpen())\n OpenLeft();\n else\n Close();\n}\n\nvoid nuiDrawerView::ToggleRight()\n{\n if (!IsRightOpen())\n OpenRight();\n else\n Close();\n}\n\n\nbool nuiDrawerView::SetRect(const nuiRect& rRect)\n{\n nuiWidget::SetRect(rRect);\n \/\/NGL_OUT(\"Set Rect with mOffset %f\\n\", mOffset);\n if (mpLeft)\n {\n nuiRect r(MIN(mpLeft->GetIdealRect().GetWidth(), rRect.GetWidth()), rRect.GetHeight());\n r.Move(MIN(0, mOffset - r.GetWidth()), 0);\n mpLeft->SetLayout(r);\n }\n\n if (mpMain)\n {\n nuiRect r(rRect.Size());\n r.Move(mOffset, 0);\n mpMain->SetLayout(r);\n }\n\n if (mpRight)\n {\n nuiRect r(MIN(mpRight->GetIdealRect().GetWidth(), rRect.GetWidth()), rRect.GetHeight());\n r.Move(MAX(mOffset + rRect.GetWidth(), rRect.GetWidth() - r.GetWidth()), 0);\n mpRight->SetLayout(r);\n }\n\n return true;\n}\n\nnuiRect nuiDrawerView::CalcIdealSize()\n{\n return mpMain ? mpMain->GetIdealRect() : nuiRect();\n}\n\n\nbool nuiDrawerView::AddChild(nuiWidgetPtr pWidget)\n{\n if (pWidget->GetProperty(\"Drawer\").Compare(\"left\", false) == 0)\n {\n if (mpLeft)\n DelChild(mpLeft);\n mpLeft = pWidget;\n }\n else if (pWidget->GetProperty(\"Drawer\").Compare(\"right\", false) == 0)\n {\n if (mpRight)\n DelChild(mpRight);\n mpRight = pWidget;\n }\n else\n {\n if (mpMain)\n DelChild(mpMain);\n mpMain = pWidget;\n }\n return nuiSimpleContainer::AddChild(pWidget);\n}\n\nbool nuiDrawerView::DelChild(nuiWidgetPtr pWidget)\n{\n if (pWidget == mpLeft)\n mpLeft = NULL;\n if (pWidget == mpRight)\n mpRight = NULL;\n if (pWidget == mpMain)\n mpMain = NULL;\n return nuiSimpleContainer::DelChild(pWidget);\n}\n\nvoid nuiDrawerView::SetLeft(nuiWidgetPtr pWidget)\n{\n if (mpLeft)\n DelChild(mpLeft);\n if (pWidget)\n AddChild(pWidget);\n mpLeft = pWidget;\n}\n\nvoid nuiDrawerView::SetMain(nuiWidgetPtr pWidget)\n{\n if (mpMain)\n DelChild(mpMain);\n if (pWidget)\n AddChild(pWidget);\n mpMain = pWidget;\n}\n\nvoid nuiDrawerView::SetRight(nuiWidgetPtr pWidget)\n{\n if (mpRight)\n DelChild(mpRight);\n if (pWidget)\n AddChild(pWidget);\n mpRight = pWidget;\n}\n\n\nnuiWidgetPtr nuiDrawerView::GetLeft()\n{\n return mpLeft;\n}\n\nnuiWidgetPtr nuiDrawerView::GetMain()\n{\n return mpMain;\n}\n\nnuiWidgetPtr nuiDrawerView::GetRight()\n{\n return mpRight;\n}\n\nbool nuiDrawerView::PreMouseClicked(const nglMouseInfo& rInfo)\n{\n if (!mInteractive)\n return false;\n\n if (rInfo.Buttons & nglMouseInfo::ButtonLeft)\n {\n mTouch = rInfo;\n mTouched = true;\n mOriginalOffset = mOffset;\n \/\/NGL_OUT(\"PreMouseClicked mOriginalOffset = %f\\n\", mOriginalOffset);\n }\n return false;\n}\n\nbool nuiDrawerView::PreMouseUnclicked(const nglMouseInfo& rInfo)\n{\n if (!mInteractive)\n return false;\n\n if (mStealRefused)\n {\n mTouched = false;\n mMoving = false;\n mStealRefused = false;\n return false;\n }\n\n if (rInfo.Buttons & nglMouseInfo::ButtonLeft)\n {\n if (mTouched && !mMoving && mOffset != 0)\n {\n if ((mOffset < 0 && rInfo.X < mRect.GetWidth() + mOffset) || (mOffset > 0 && rInfo.X > mOffset))\n {\n if (mpMain)\n {\n mpMain->DispatchMouseCanceled(this, rInfo);\n }\n mTouched = false;\n\n mTargetOffset = 0;\n mEventSink.Connect(nuiAnimation::GetTimer()->Tick, &nuiDrawerView::OnAnimateDrawer);\n\n return true;\n }\n }\n mTouched = false;\n }\n return false;\n}\n\nbool nuiDrawerView::PreMouseMoved(const nglMouseInfo& rInfo)\n{\n if (!mInteractive)\n return false;\n\n if (mTouched && !mMoving)\n {\n float x = 0;\n x = mTouch.X - rInfo.X;\n float dist = fabs(x);\n\n if (dist > MOVE_TOLERANCE)\n {\n \/\/NGL_OUT(\"nuiDrawerView Preempting mouse from existing grabber!\\n\");\n NGL_ASSERT(GetTopLevel());\n\n if (StealMouseEvent(rInfo))\n {\n mTouched = false;\n mMoving = true;\n mStealRefused = false;\n return true;\n }\n else\n {\n NGL_LOG(\"nuiDrawer\", NGL_LOG_DEBUG, \"PreMouseMoved: StealMouseEvent refused\\n\");\n mStealRefused = true;\n }\n }\n }\n return false;\n}\n\nbool nuiDrawerView::MouseClicked(const nglMouseInfo& rInfo)\n{\n if (rInfo.Buttons & nglMouseInfo::ButtonLeft)\n {\n mMoving = false;\n mTouched = false;\n\n mTouch = rInfo;\n mOriginalOffset = mOffset;\n\n SetSelected(true);\n \/\/ Stop events, just in case...\n mEventSink.DisconnectAll();\n }\n return false;\n}\n\nvoid nuiDrawerView::ReleaseTouch()\n{\n mMoving = false;\n mTouched = false;\n\n if (mOffset < 0)\n {\n \/\/ We should we go?\n float width = mpRight->GetIdealRect().GetWidth();\n if (-mOffset < width * 0.5)\n {\n \/\/ We're less than half way though, so we go back to our original position:\n mTargetOffset = 0;\n }\n else\n {\n mTargetOffset = -width;\n }\n }\n else if (mOffset > 0)\n {\n \/\/ We should we go?\n float width = mpLeft->GetIdealRect().GetWidth();\n if (mOffset < width * 0.5)\n {\n \/\/ We're less than half way though, so we go back to our original position:\n mTargetOffset = 0;\n }\n else\n {\n mTargetOffset = width;\n }\n }\n else\n {\n mTargetOffset = 0;\n }\n\n if (mOffset != mTargetOffset)\n {\n mEventSink.Connect(nuiAnimation::GetTimer()->Tick, &nuiDrawerView::OnAnimateDrawer);\n }\n\n UpdateLayout();\n}\n\nbool nuiDrawerView::MouseUnclicked(const nglMouseInfo& rInfo)\n{\n if (rInfo.Buttons & nglMouseInfo::ButtonLeft)\n {\n ReleaseTouch();\n SetSelected(false);\n }\n return false;\n}\n\nbool nuiDrawerView::MouseMoved(const nglMouseInfo& rInfo)\n{\n if (mMoving)\n {\n float dx = mTouch.X - rInfo.X;\n mOffset = mOriginalOffset -dx;\n if (mOffset < 0)\n {\n if (!mpRight)\n {\n mOffset = 0;\n }\n else\n {\n float width = mpRight->GetIdealRect().GetWidth();\n if (mOffset < -width)\n {\n \/\/ Compute the position with the\n float diff = -mOffset - width ;\n mOffset = -width - PULL_COEF * sqrt(diff);\n \/\/NGL_OUT(\"Diff : %f\\n\", diff);\n }\n }\n }\n else\n {\n if (!mpLeft)\n {\n mOffset = 0;\n }\n else\n {\n float width = mpLeft->GetIdealRect().GetWidth();\n if (mOffset > width)\n {\n \/\/ Compute the position with the\n float diff = mOffset - width ;\n mOffset = width + PULL_COEF * sqrt(diff);\n \/\/NGL_OUT(\"Diff : %f\\n\", diff);\n }\n }\n }\n\n \/\/NGL_OUT(\"Mouse moved, new offset = %f\\n\", mOffset);\n UpdateLayout();\n return true;\n }\n\n if (mTouched)\n {\n float x = 0;\n x = mTouch.X - rInfo.X;\n float dist = fabs(x);\n\n if (dist > MOVE_TOLERANCE)\n {\n \/\/NGL_OUT(\"nuiDrawerView Preempting mouse from existing grabber!\\n\");\n NGL_ASSERT(GetTopLevel());\n\n mTouched = false;\n mMoving = true;\n }\n }\n return false;\n}\n\nbool nuiDrawerView::MouseCanceled(const nglMouseInfo& rInfo)\n{\n if (mMoving)\n {\n ReleaseTouch();\n }\n SetSelected(false);\n mTouched = false;\n mMoving = false;\n return false;\n}\n\nvoid nuiDrawerView::OnAnimateDrawer(const nuiEvent &rEvent)\n{\n float diff = mTargetOffset - mOffset;\n mOffset += diff * mAnimRatio;\n\n \/\/NGL_OUT(\".\");\n diff = mTargetOffset - mOffset;\n if (fabs(diff) < 1.0)\n {\n \/\/NGL_OUT(\"nuiDrawerView Offset Realease Done\\n\");\n mOffset = mTargetOffset;\n \/\/NGL_OUT(\"!!!!!!!! Anim end mOffset = %f\\n\", mOffset);\n mEventSink.DisconnectAll();\n\n\n if (IsOpen())\n {\n Opened();\n if (IsLeftOpen())\n {\n LeftOpened();\n }\n else\n {\n RightOpened();\n }\n }\n else\n {\n Closed();\n }\n }\n\n mOriginalOffset = mOffset;\n UpdateLayout();\n}\n<commit_msg>better close\/toogle\/open interactions<commit_after>\n#include \"nui.h\"\n#include \"nuiDrawerView.h\"\n\nstatic const float SPRING_TOLERANCE = 0.0000000005f;\nstatic const float STIFFNESS = .3f;\nstatic const float PULL_COEF = 4;\nstatic const float MOVE_TOLERANCE = 8;\n\n\nnuiDrawerView::nuiDrawerView() :\nmpLeft(nullptr), mpMain(nullptr), mpRight(nullptr), mOffset(0), mTouched(false), mMoving(false), mOriginalOffset(0), mTargetOffset(0), mEventSink(this), mInteractive(true)\n{\n if (SetObjectClass(\"nuiDrawerView\"))\n {\n \/\/ Init attributes:\n AddAttribute(new nuiAttribute<bool>\n (\"Interactive\", nuiUnitBoolean,\n nuiMakeDelegate(this, &nuiDrawerView::GetInteractive),\n nuiMakeDelegate(this, &nuiDrawerView::SetInteractive)));\n\n AddAttribute(new nuiAttribute<float>\n (\"AnimRatio\", nuiUnitBoolean,\n nuiMakeDelegate(this, &nuiDrawerView::GetAnimRatio),\n nuiMakeDelegate(this, &nuiDrawerView::SetAnimRatio)));\n }\n\n NUI_ADD_EVENT(LeftOpened);\n NUI_ADD_EVENT(RightOpened);\n NUI_ADD_EVENT(Opened);\n NUI_ADD_EVENT(Closed);\n\n nuiAnimation::AcquireTimer();\n}\n\nnuiDrawerView::~nuiDrawerView()\n{\n nuiAnimation::ReleaseTimer();\n}\n\nvoid nuiDrawerView::OpenLeft()\n{\n if (!mpLeft)\n return;\n\n mMoving = false;\n mTouched = false;\n mStealRefused = false;\n\n float width = mpLeft->GetIdealRect().GetWidth();\n mTargetOffset = width;\n\n if (mOffset != mTargetOffset)\n {\n mEventSink.Connect(nuiAnimation::GetTimer()->Tick, &nuiDrawerView::OnAnimateDrawer);\n }\n\n UpdateLayout();\n}\n\nvoid nuiDrawerView::OpenRight()\n{\n if (!mpRight)\n return;\n\n mMoving = false;\n mTouched = false;\n mStealRefused = false;\n\n float width = mpRight->GetIdealRect().GetWidth();\n mTargetOffset = -width;\n\n if (mOffset != mTargetOffset)\n {\n mEventSink.Connect(nuiAnimation::GetTimer()->Tick, &nuiDrawerView::OnAnimateDrawer);\n }\n\n UpdateLayout();\n}\n\nvoid nuiDrawerView::Close()\n{\n mMoving = false;\n mTouched = false;\n mStealRefused = false;\n\n mTargetOffset = 0;\n\n if (mOffset != mTargetOffset)\n {\n mEventSink.Connect(nuiAnimation::GetTimer()->Tick, &nuiDrawerView::OnAnimateDrawer);\n }\n\n UpdateLayout();\n}\n\nbool nuiDrawerView::IsOpen() const\n{\n return mTargetOffset != 0;\n}\n\nbool nuiDrawerView::IsLeftOpen() const\n{\n return mTargetOffset > 0;\n}\n\nbool nuiDrawerView::IsRightOpen() const\n{\n return mTargetOffset < 0;\n}\n\nvoid nuiDrawerView::ToggleLeft()\n{\n if (!IsLeftOpen())\n OpenLeft();\n else\n Close();\n}\n\nvoid nuiDrawerView::ToggleRight()\n{\n if (!IsRightOpen())\n OpenRight();\n else\n Close();\n}\n\n\nbool nuiDrawerView::SetRect(const nuiRect& rRect)\n{\n nuiWidget::SetRect(rRect);\n \/\/NGL_OUT(\"Set Rect with mOffset %f\\n\", mOffset);\n if (mpLeft)\n {\n nuiRect r(MIN(mpLeft->GetIdealRect().GetWidth(), rRect.GetWidth()), rRect.GetHeight());\n r.Move(MIN(0, mOffset - r.GetWidth()), 0);\n mpLeft->SetLayout(r);\n }\n\n if (mpMain)\n {\n nuiRect r(rRect.Size());\n r.Move(mOffset, 0);\n mpMain->SetLayout(r);\n }\n\n if (mpRight)\n {\n nuiRect r(MIN(mpRight->GetIdealRect().GetWidth(), rRect.GetWidth()), rRect.GetHeight());\n r.Move(MAX(mOffset + rRect.GetWidth(), rRect.GetWidth() - r.GetWidth()), 0);\n mpRight->SetLayout(r);\n }\n\n return true;\n}\n\nnuiRect nuiDrawerView::CalcIdealSize()\n{\n return mpMain ? mpMain->GetIdealRect() : nuiRect();\n}\n\n\nbool nuiDrawerView::AddChild(nuiWidgetPtr pWidget)\n{\n if (pWidget->GetProperty(\"Drawer\").Compare(\"left\", false) == 0)\n {\n if (mpLeft)\n DelChild(mpLeft);\n mpLeft = pWidget;\n }\n else if (pWidget->GetProperty(\"Drawer\").Compare(\"right\", false) == 0)\n {\n if (mpRight)\n DelChild(mpRight);\n mpRight = pWidget;\n }\n else\n {\n if (mpMain)\n DelChild(mpMain);\n mpMain = pWidget;\n }\n return nuiSimpleContainer::AddChild(pWidget);\n}\n\nbool nuiDrawerView::DelChild(nuiWidgetPtr pWidget)\n{\n if (pWidget == mpLeft)\n mpLeft = NULL;\n if (pWidget == mpRight)\n mpRight = NULL;\n if (pWidget == mpMain)\n mpMain = NULL;\n return nuiSimpleContainer::DelChild(pWidget);\n}\n\nvoid nuiDrawerView::SetLeft(nuiWidgetPtr pWidget)\n{\n if (mpLeft)\n DelChild(mpLeft);\n if (pWidget)\n AddChild(pWidget);\n mpLeft = pWidget;\n}\n\nvoid nuiDrawerView::SetMain(nuiWidgetPtr pWidget)\n{\n if (mpMain)\n DelChild(mpMain);\n if (pWidget)\n AddChild(pWidget);\n mpMain = pWidget;\n}\n\nvoid nuiDrawerView::SetRight(nuiWidgetPtr pWidget)\n{\n if (mpRight)\n DelChild(mpRight);\n if (pWidget)\n AddChild(pWidget);\n mpRight = pWidget;\n}\n\n\nnuiWidgetPtr nuiDrawerView::GetLeft()\n{\n return mpLeft;\n}\n\nnuiWidgetPtr nuiDrawerView::GetMain()\n{\n return mpMain;\n}\n\nnuiWidgetPtr nuiDrawerView::GetRight()\n{\n return mpRight;\n}\n\nbool nuiDrawerView::PreMouseClicked(const nglMouseInfo& rInfo)\n{\n if (!mInteractive)\n return false;\n\n if (rInfo.Buttons & nglMouseInfo::ButtonLeft)\n {\n mTouch = rInfo;\n mTouched = true;\n mOriginalOffset = mOffset;\n \/\/NGL_OUT(\"PreMouseClicked mOriginalOffset = %f\\n\", mOriginalOffset);\n }\n return false;\n}\n\nbool nuiDrawerView::PreMouseUnclicked(const nglMouseInfo& rInfo)\n{\n if (!mInteractive)\n return false;\n\n if (mStealRefused)\n {\n mTouched = false;\n mMoving = false;\n mStealRefused = false;\n return false;\n }\n\n if (rInfo.Buttons & nglMouseInfo::ButtonLeft)\n {\n if (mTouched && !mMoving && mOffset != 0)\n {\n if ((mOffset < 0 && rInfo.X < mRect.GetWidth() + mOffset) || (mOffset > 0 && rInfo.X > mOffset))\n {\n if (mpMain)\n {\n mpMain->DispatchMouseCanceled(this, rInfo);\n }\n mTouched = false;\n\n Close();\n\n return true;\n }\n }\n mTouched = false;\n }\n return false;\n}\n\nbool nuiDrawerView::PreMouseMoved(const nglMouseInfo& rInfo)\n{\n if (!mInteractive)\n return false;\n\n if (mTouched && !mMoving)\n {\n float x = 0;\n x = mTouch.X - rInfo.X;\n float dist = fabs(x);\n\n if (dist > MOVE_TOLERANCE)\n {\n \/\/NGL_OUT(\"nuiDrawerView Preempting mouse from existing grabber!\\n\");\n NGL_ASSERT(GetTopLevel());\n\n if (StealMouseEvent(rInfo))\n {\n mTouched = false;\n mMoving = true;\n mStealRefused = false;\n return true;\n }\n else\n {\n NGL_LOG(\"nuiDrawer\", NGL_LOG_DEBUG, \"PreMouseMoved: StealMouseEvent refused\\n\");\n mStealRefused = true;\n }\n }\n }\n return false;\n}\n\nbool nuiDrawerView::MouseClicked(const nglMouseInfo& rInfo)\n{\n if (rInfo.Buttons & nglMouseInfo::ButtonLeft)\n {\n mMoving = false;\n mTouched = false;\n\n mTouch = rInfo;\n mOriginalOffset = mOffset;\n\n SetSelected(true);\n \/\/ Stop events, just in case...\n mEventSink.DisconnectAll();\n }\n return false;\n}\n\nvoid nuiDrawerView::ReleaseTouch()\n{\n mMoving = false;\n mTouched = false;\n\n if (mOffset < 0)\n {\n \/\/ We should we go?\n float width = mpRight->GetIdealRect().GetWidth();\n if (-mOffset < width * 0.5)\n {\n \/\/ We're less than half way though, so we go back to our original position:\n Close();\n return;\n }\n else\n {\n mTargetOffset = -width;\n }\n }\n else if (mOffset > 0)\n {\n \/\/ We should we go?\n float width = mpLeft->GetIdealRect().GetWidth();\n if (mOffset < width * 0.5)\n {\n \/\/ We're less than half way though, so we go back to our original position:\n Close();\n return;\n }\n else\n {\n mTargetOffset = width;\n }\n }\n else\n {\n mTargetOffset = 0;\n }\n\n if (mOffset != mTargetOffset)\n {\n mEventSink.Connect(nuiAnimation::GetTimer()->Tick, &nuiDrawerView::OnAnimateDrawer);\n }\n\n UpdateLayout();\n}\n\nbool nuiDrawerView::MouseUnclicked(const nglMouseInfo& rInfo)\n{\n if (rInfo.Buttons & nglMouseInfo::ButtonLeft)\n {\n ReleaseTouch();\n SetSelected(false);\n }\n return false;\n}\n\nbool nuiDrawerView::MouseMoved(const nglMouseInfo& rInfo)\n{\n if (mMoving)\n {\n float dx = mTouch.X - rInfo.X;\n mOffset = mOriginalOffset -dx;\n if (mOffset < 0)\n {\n if (!mpRight)\n {\n mOffset = 0;\n }\n else\n {\n float width = mpRight->GetIdealRect().GetWidth();\n if (mOffset < -width)\n {\n \/\/ Compute the position with the\n float diff = -mOffset - width ;\n mOffset = -width - PULL_COEF * sqrt(diff);\n \/\/NGL_OUT(\"Diff : %f\\n\", diff);\n }\n }\n }\n else\n {\n if (!mpLeft)\n {\n mOffset = 0;\n }\n else\n {\n float width = mpLeft->GetIdealRect().GetWidth();\n if (mOffset > width)\n {\n \/\/ Compute the position with the\n float diff = mOffset - width ;\n mOffset = width + PULL_COEF * sqrt(diff);\n \/\/NGL_OUT(\"Diff : %f\\n\", diff);\n }\n }\n }\n\n \/\/NGL_OUT(\"Mouse moved, new offset = %f\\n\", mOffset);\n UpdateLayout();\n return true;\n }\n\n if (mTouched)\n {\n float x = 0;\n x = mTouch.X - rInfo.X;\n float dist = fabs(x);\n\n if (dist > MOVE_TOLERANCE)\n {\n \/\/NGL_OUT(\"nuiDrawerView Preempting mouse from existing grabber!\\n\");\n NGL_ASSERT(GetTopLevel());\n\n mTouched = false;\n mMoving = true;\n }\n }\n return false;\n}\n\nbool nuiDrawerView::MouseCanceled(const nglMouseInfo& rInfo)\n{\n if (mMoving)\n {\n ReleaseTouch();\n }\n SetSelected(false);\n mTouched = false;\n mMoving = false;\n return false;\n}\n\nvoid nuiDrawerView::OnAnimateDrawer(const nuiEvent &rEvent)\n{\n float diff = mTargetOffset - mOffset;\n mOffset += diff * mAnimRatio;\n\n \/\/NGL_OUT(\".\");\n diff = mTargetOffset - mOffset;\n if (fabs(diff) < 1.0)\n {\n \/\/NGL_OUT(\"nuiDrawerView Offset Realease Done\\n\");\n mOffset = mTargetOffset;\n \/\/NGL_OUT(\"!!!!!!!! Anim end mOffset = %f\\n\", mOffset);\n mEventSink.DisconnectAll();\n\n\n if (IsOpen())\n {\n Opened();\n if (IsLeftOpen())\n {\n LeftOpened();\n }\n else\n {\n RightOpened();\n }\n }\n else\n {\n Closed();\n }\n }\n\n mOriginalOffset = mOffset;\n UpdateLayout();\n}\n<|endoftext|>"} {"text":"<commit_before>\/******************************************************************************\n * Copyright 2017 The Apollo Authors. All Rights Reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *****************************************************************************\/\n\n\/**\n * @file\n *\/\n\n#include \"modules\/third_party_perception\/fusion.h\"\n\n#include <vector>\n\n#include \"modules\/common\/math\/polygon2d.h\"\n#include \"modules\/common\/math\/vec2d.h\"\n#include \"modules\/third_party_perception\/common\/third_party_perception_gflags.h\"\n#include \"modules\/third_party_perception\/common\/third_party_perception_util.h\"\n\n\/**\n * @namespace apollo::third_party_perception::fusion\n * @brief apollo::third_party_perception\n *\/\nnamespace apollo {\nnamespace third_party_perception {\nnamespace fusion {\n\nusing apollo::common::math::Vec2d;\nusing apollo::perception::PerceptionObstacles;\nusing apollo::perception::PerceptionObstacle;\n\nstd::vector<Vec2d> PerceptionObstacleToVectorVec2d(\n const PerceptionObstacle& obstacle) {\n std::vector<Vec2d> result;\n for (const auto& vertex : obstacle.polygon_point()) {\n result.emplace_back(vertex.x(), vertex.y());\n }\n return result;\n}\n\nbool HasOverlap(const PerceptionObstacle& obstacle_1,\n const PerceptionObstacle& obstacle_2) {\n common::math::Polygon2d polygon_1(\n PerceptionObstacleToVectorVec2d(obstacle_1));\n common::math::Polygon2d polygon_2(\n PerceptionObstacleToVectorVec2d(obstacle_2));\n return polygon_1.HasOverlap(polygon_2);\n}\n\nbool HasOverlap(const PerceptionObstacle& obstacle,\n const PerceptionObstacles& obstacles) {\n for (const auto& current_obstacle : obstacles.perception_obstacle()) {\n if (HasOverlap(obstacle, current_obstacle)) {\n return true;\n }\n }\n return false;\n}\n\nPerceptionObstacles MobileyeRadarFusion(\n const PerceptionObstacles& mobileye_obstacles,\n const PerceptionObstacles& radar_obstacles) {\n PerceptionObstacles mobileye_obstacles_fusion = mobileye_obstacles;\n PerceptionObstacles radar_obstacles_fusion = radar_obstacles;\n\n for (auto& mobileye_obstacle :\n *(mobileye_obstacles_fusion.mutable_perception_obstacle())) {\n for (auto& radar_obstacle :\n *(radar_obstacles_fusion.mutable_perception_obstacle())) {\n if (HasOverlap(mobileye_obstacle, radar_obstacle)) {\n mobileye_obstacle.set_confidence(0.99);\n radar_obstacle.set_confidence(0.99);\n }\n }\n }\n\n mobileye_obstacles_fusion.MergeFrom(radar_obstacles_fusion);\n return mobileye_obstacles_fusion;\n}\n\n} \/\/ namespace fusion\n} \/\/ namespace third_party_perception\n} \/\/ namespace apollo\n<commit_msg>ThirdParty : Change simple fusion strategy<commit_after>\/******************************************************************************\n * Copyright 2017 The Apollo Authors. All Rights Reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *****************************************************************************\/\n\n\/**\n * @file\n *\/\n\n#include \"modules\/third_party_perception\/fusion.h\"\n\n#include <vector>\n\n#include \"modules\/common\/math\/polygon2d.h\"\n#include \"modules\/common\/math\/vec2d.h\"\n#include \"modules\/third_party_perception\/common\/third_party_perception_gflags.h\"\n#include \"modules\/third_party_perception\/common\/third_party_perception_util.h\"\n\n\/**\n * @namespace apollo::third_party_perception::fusion\n * @brief apollo::third_party_perception\n *\/\nnamespace apollo {\nnamespace third_party_perception {\nnamespace fusion {\n\nusing apollo::common::math::Vec2d;\nusing apollo::perception::PerceptionObstacle;\nusing apollo::perception::PerceptionObstacles;\n\nstd::vector<Vec2d> PerceptionObstacleToVectorVec2d(\n const PerceptionObstacle& obstacle) {\n std::vector<Vec2d> result;\n for (const auto& vertex : obstacle.polygon_point()) {\n result.emplace_back(vertex.x(), vertex.y());\n }\n return result;\n}\n\nbool HasOverlap(const PerceptionObstacle& obstacle_1,\n const PerceptionObstacle& obstacle_2) {\n common::math::Polygon2d polygon_1(\n PerceptionObstacleToVectorVec2d(obstacle_1));\n common::math::Polygon2d polygon_2(\n PerceptionObstacleToVectorVec2d(obstacle_2));\n return polygon_1.HasOverlap(polygon_2);\n}\n\nbool HasOverlap(const PerceptionObstacle& obstacle,\n const PerceptionObstacles& obstacles) {\n for (const auto& current_obstacle : obstacles.perception_obstacle()) {\n if (HasOverlap(obstacle, current_obstacle)) {\n return true;\n }\n }\n return false;\n}\n\nPerceptionObstacles MobileyeRadarFusion(\n const PerceptionObstacles& mobileye_obstacles,\n const PerceptionObstacles& radar_obstacles) {\n PerceptionObstacles mobileye_obstacles_fusion = mobileye_obstacles;\n PerceptionObstacles radar_obstacles_fusion = radar_obstacles;\n\n for (auto& mobileye_obstacle :\n *(mobileye_obstacles_fusion.mutable_perception_obstacle())) {\n for (auto& radar_obstacle :\n *(radar_obstacles_fusion.mutable_perception_obstacle())) {\n if (HasOverlap(mobileye_obstacle, radar_obstacle)) {\n mobileye_obstacle.set_confidence(0.99);\n mobileye_obstacle.mutable_velocity()->CopyFrom(\n radar_obstacle.velocity());\n }\n }\n }\n\n \/\/ mobileye_obstacles_fusion.MergeFrom(radar_obstacles_fusion);\n return mobileye_obstacles_fusion;\n}\n\n} \/\/ namespace fusion\n} \/\/ namespace third_party_perception\n} \/\/ namespace apollo\n<|endoftext|>"} {"text":"<commit_before>#include \"MeshCuboidParameters.h\"\n\n\/\/ -- Parameters -- \/\/\n\/\/\nDEFINE_bool(param_optimize_with_non_linear_constraints, true, \"\");\nDEFINE_bool(param_optimize_training_cuboids, true, \"\");\n\nDEFINE_int32(param_num_sample_point_neighbors, 8, \"\");\nDEFINE_int32(param_min_num_cuboid_sample_points, 10, \"\");\nDEFINE_int32(param_min_num_symmetric_point_pairs, 50, \"\");\nDEFINE_int32(param_num_cuboid_surface_points, 1000, \"\");\nDEFINE_int32(param_intra_cuboid_symmetry_axis, 0, \"\");\nDEFINE_int32(param_eval_num_neighbor_range_samples, 1001, \"\");\nDEFINE_int32(param_opt_max_iterations, 5, \"\");\n\nDEFINE_double(param_min_sample_point_confidence, 0.7, \"\");\nDEFINE_double(param_min_num_confidence_tol_sample_points, 0.5, \"\");\nDEFINE_double(param_min_cuboid_bbox_size, 0.1, \"\");\nDEFINE_double(param_min_cuboid_bbox_diag_length, 0.3, \"\");\nDEFINE_double(param_sparse_neighbor_distance, 0.05, \"\");\nDEFINE_double(param_cuboid_split_neighbor_distance, 0.2, \"\");\nDEFINE_double(param_occlusion_test_neighbor_distance, 0.01, \"\");\nDEFINE_double(param_eval_max_neighbor_distance, 0.005, \"\");\nDEFINE_double(param_min_cuboid_overall_visibility, 0.8, \"\");\nDEFINE_double(param_max_potential, 1.0E8, \"\");\nDEFINE_double(param_dummy_potential, 1.0E4, \"\");\nDEFINE_double(param_opt_single_energy_term_weight, 1.0E4, \"\");\nDEFINE_double(param_opt_symmetry_energy_term_weight, 1.0E6, \"\");\nDEFINE_double(param_part_assembly_window_size, 0.1, \"\");\nDEFINE_double(param_part_assembly_voxel_size, 0.01, \"\");\nDEFINE_double(param_part_assembly_voxel_variance, 0.01, \"\");\n\n\/\/DEFINE_double(param_sim_abs_attr_tol, 0.2, \"\");\n\/\/DEFINE_double(param_zero_tol, 1.0E-6, \"\");\n\/\/\n\/\/ ---- \/\/\n\n\n\/\/ -- Experiments -- \/\/\n\/\/\nDEFINE_bool(run_training, false, \"\");\nDEFINE_bool(run_prediction, false, \"\");\nDEFINE_bool(run_part_assembly, false, \"\");\nDEFINE_string(mesh_filename, \"\", \"\");\n\nDEFINE_string(data_root_path, \"D:\/Data\/shape2pose\/\", \"\");\nDEFINE_string(label_info_path, \"data\/0_body\/assembly_chairs\/\", \"\");\nDEFINE_string(mesh_path, \"data\/1_input\/assembly_chairs\/off\/\", \"\");\nDEFINE_string(sample_path, \"data\/2_analysis\/assembly_chairs\/points\/even1000\/\", \"\");\nDEFINE_string(dense_sample_path, \"data\/2_analysis\/assembly_chairs\/points\/random100000\/\", \"\");\nDEFINE_string(mesh_label_path, \"data\/1_input\/assembly_chairs\/gt\/\", \"\");\nDEFINE_string(sample_label_path, \"data\/4_experiments\/exp1_assembly_chairs\/1_prediction\/\", \"\");\nDEFINE_string(output_dir, \"output\", \"\");\nDEFINE_string(training_dir, \"training\", \"\");\nDEFINE_string(part_assembly_dir, \"part_assembly\", \"\");\n\nDEFINE_string(label_info_filename, \"regions.txt\", \"\");\nDEFINE_string(label_symmetry_info_filename, \"regions_symmetry.txt\", \"\");\nDEFINE_string(symmetry_group_info_filename, \"symmetry_groups.txt\", \"\");\nDEFINE_string(pose_filename, \"pose.txt\", \"\");\nDEFINE_string(occlusion_pose_filename, \"\", \"\");\n\/\/DEFINE_string(occlusion_pose_filename, \"occlusion_pose.txt\", \"\");\n\nDEFINE_string(single_feature_filename_prefix, \"single_feature_\", \"\");\nDEFINE_string(pair_feature_filename_prefix, \"pair_feature_\", \"\");\nDEFINE_string(single_stats_filename_prefix, \"single_stats_\", \"\");\nDEFINE_string(pair_stats_filename_prefix, \"pair_stats_\", \"\");\nDEFINE_string(feature_filename_prefix, \"feature_\", \"\");\nDEFINE_string(transformation_filename_prefix, \"transformation_\", \"\");\nDEFINE_string(joint_normal_relation_filename_prefix, \"joint_normal_\", \"\");\nDEFINE_string(cond_normal_relation_filename_prefix, \"conditional_normal_\", \"\");\nDEFINE_string(object_list_filename, \"object_list.txt\", \"\");\n\nDEFINE_double(occlusion_test_radius, 0.01, \"\");\nDEFINE_int32(random_view_seed, 20150416, \"\");\n\n\/\/ To be removed.\n\/\/DEFINE_bool(use_symmetric_group_cuboids, false, \"\");\n\/\/\n\/\/ ---- \/\/<commit_msg>Minor updates.<commit_after>#include \"MeshCuboidParameters.h\"\n\n\/\/ -- Parameters -- \/\/\n\/\/\nDEFINE_bool(param_optimize_with_non_linear_constraints, true, \"\");\nDEFINE_bool(param_optimize_training_cuboids, true, \"\");\n\nDEFINE_int32(param_num_sample_point_neighbors, 8, \"\");\nDEFINE_int32(param_min_num_cuboid_sample_points, 10, \"\");\nDEFINE_int32(param_min_num_symmetric_point_pairs, 50, \"\");\nDEFINE_int32(param_num_cuboid_surface_points, 1000, \"\");\nDEFINE_int32(param_intra_cuboid_symmetry_axis, 0, \"\");\nDEFINE_int32(param_eval_num_neighbor_range_samples, 1001, \"\");\nDEFINE_int32(param_opt_max_iterations, 5, \"\");\n\nDEFINE_double(param_min_sample_point_confidence, 0.7, \"\");\nDEFINE_double(param_min_num_confidence_tol_sample_points, 0.5, \"\");\nDEFINE_double(param_min_cuboid_bbox_size, 0.1, \"\");\nDEFINE_double(param_min_cuboid_bbox_diag_length, 0.3, \"\");\nDEFINE_double(param_sparse_neighbor_distance, 0.05, \"\");\nDEFINE_double(param_cuboid_split_neighbor_distance, 0.2, \"\");\nDEFINE_double(param_occlusion_test_neighbor_distance, 0.01, \"\");\nDEFINE_double(param_eval_max_neighbor_distance, 0.1, \"\");\nDEFINE_double(param_min_cuboid_overall_visibility, 0.8, \"\");\nDEFINE_double(param_max_potential, 1.0E8, \"\");\nDEFINE_double(param_dummy_potential, 1.0E4, \"\");\nDEFINE_double(param_opt_single_energy_term_weight, 1.0E4, \"\");\nDEFINE_double(param_opt_symmetry_energy_term_weight, 1.0E6, \"\");\nDEFINE_double(param_part_assembly_window_size, 0.1, \"\");\nDEFINE_double(param_part_assembly_voxel_size, 0.01, \"\");\nDEFINE_double(param_part_assembly_voxel_variance, 0.01, \"\");\n\n\/\/DEFINE_double(param_sim_abs_attr_tol, 0.2, \"\");\n\/\/DEFINE_double(param_zero_tol, 1.0E-6, \"\");\n\/\/\n\/\/ ---- \/\/\n\n\n\/\/ -- Experiments -- \/\/\n\/\/\nDEFINE_bool(run_training, false, \"\");\nDEFINE_bool(run_prediction, false, \"\");\nDEFINE_bool(run_part_assembly, false, \"\");\nDEFINE_string(mesh_filename, \"\", \"\");\n\nDEFINE_string(data_root_path, \"D:\/Data\/shape2pose\/\", \"\");\nDEFINE_string(label_info_path, \"data\/0_body\/assembly_chairs\/\", \"\");\nDEFINE_string(mesh_path, \"data\/1_input\/assembly_chairs\/off\/\", \"\");\nDEFINE_string(sample_path, \"data\/2_analysis\/assembly_chairs\/points\/even1000\/\", \"\");\nDEFINE_string(dense_sample_path, \"data\/2_analysis\/assembly_chairs\/points\/random100000\/\", \"\");\nDEFINE_string(mesh_label_path, \"data\/1_input\/assembly_chairs\/gt\/\", \"\");\nDEFINE_string(sample_label_path, \"data\/4_experiments\/exp1_assembly_chairs\/1_prediction\/\", \"\");\nDEFINE_string(output_dir, \"output\", \"\");\nDEFINE_string(training_dir, \"training\", \"\");\nDEFINE_string(part_assembly_dir, \"part_assembly\", \"\");\n\nDEFINE_string(label_info_filename, \"regions.txt\", \"\");\nDEFINE_string(label_symmetry_info_filename, \"regions_symmetry.txt\", \"\");\nDEFINE_string(symmetry_group_info_filename, \"symmetry_groups.txt\", \"\");\nDEFINE_string(pose_filename, \"pose.txt\", \"\");\nDEFINE_string(occlusion_pose_filename, \"\", \"\");\n\/\/DEFINE_string(occlusion_pose_filename, \"occlusion_pose.txt\", \"\");\n\nDEFINE_string(single_feature_filename_prefix, \"single_feature_\", \"\");\nDEFINE_string(pair_feature_filename_prefix, \"pair_feature_\", \"\");\nDEFINE_string(single_stats_filename_prefix, \"single_stats_\", \"\");\nDEFINE_string(pair_stats_filename_prefix, \"pair_stats_\", \"\");\nDEFINE_string(feature_filename_prefix, \"feature_\", \"\");\nDEFINE_string(transformation_filename_prefix, \"transformation_\", \"\");\nDEFINE_string(joint_normal_relation_filename_prefix, \"joint_normal_\", \"\");\nDEFINE_string(cond_normal_relation_filename_prefix, \"conditional_normal_\", \"\");\nDEFINE_string(object_list_filename, \"object_list.txt\", \"\");\n\nDEFINE_double(occlusion_test_radius, 0.01, \"\");\nDEFINE_int32(random_view_seed, 20150416, \"\");\n\n\/\/ To be removed.\n\/\/DEFINE_bool(use_symmetric_group_cuboids, false, \"\");\n\/\/\n\/\/ ---- \/\/<|endoftext|>"} {"text":"<commit_before>#include <algorithm>\n#include <cstdio>\n#include <limits>\n\n#include \"graphics.h\"\n#include \"nesterovBase.h\"\n#include \"placerBase.h\"\n\nnamespace replace {\n\nGraphics::Graphics(std::shared_ptr<PlacerBase> pb,\n std::shared_ptr<NesterovBase> nb,\n bool draw_bins)\n : pb_(pb), nb_(nb), selected_(nullptr), draw_bins_(draw_bins)\n{\n gui::Gui::get()->register_renderer(this);\n}\n\nvoid Graphics::drawObjects(gui::Painter& painter)\n{\n \/\/ draw core bounds\n auto& die = pb_->die();\n painter.setPen(gui::Painter::yellow, \/* cosmetic *\/ true);\n painter.drawLine(die.coreLx(), die.coreLy(), die.coreUx(), die.coreLy());\n painter.drawLine(die.coreUx(), die.coreLy(), die.coreUx(), die.coreUy());\n painter.drawLine(die.coreUx(), die.coreUy(), die.coreLx(), die.coreUy());\n painter.drawLine(die.coreLx(), die.coreUy(), die.coreLx(), die.coreLy());\n\n if (draw_bins_) {\n \/\/ Draw the bins\n painter.setPen(gui::Painter::white, \/* cosmetic *\/ true);\n for (auto& bin : nb_->bins()) {\n int color = bin->density() * 50 + 20;\n\n color = (color > 255) ? 255 : (color < 20) ? 20 : color;\n color = 255 - color;\n\n painter.setBrush({color, color, color, 180});\n painter.drawRect({bin->lx(), bin->ly(), bin->ux(), bin->uy()});\n }\n }\n\n \/\/ Draw the placeable objects\n painter.setPen(gui::Painter::white);\n for (auto* gCell : nb_->gCells()) {\n const int gcx = gCell->dCx();\n const int gcy = gCell->dCy();\n\n int xl = gcx - gCell->dx() \/ 2;\n int yl = gcy - gCell->dy() \/ 2;\n int xh = gcx + gCell->dx() \/ 2;\n int yh = gcy + gCell->dy() \/ 2;\n\n gui::Painter::Color color;\n if (gCell->isInstance()) {\n color = gui::Painter::dark_blue;\n } else if (gCell->isFiller()) {\n color = gui::Painter::dark_magenta;\n }\n if (gCell == selected_) {\n color = gui::Painter::yellow;\n }\n\n color.a = 180;\n painter.setBrush(color);\n painter.drawRect({xl, yl, xh, yh});\n }\n\n \/\/ Draw lines to neighbors\n if (selected_) {\n painter.setPen(gui::Painter::yellow, true);\n for (GPin* pin : selected_->gPins()) {\n GNet* net = pin->gNet();\n if (!net) {\n continue;\n }\n for (GPin* other_pin : net->gPins()) {\n GCell* neighbor = other_pin->gCell();\n if (neighbor == selected_) {\n continue;\n }\n painter.drawLine(\n pin->cx(), pin->cy(), other_pin->cx(), other_pin->cy());\n }\n }\n }\n\n \/\/ Draw force direction lines\n if (draw_bins_) {\n float efMax = 0;\n int max_len = std::numeric_limits<int>::max();\n for (auto& bin : nb_->bins()) {\n efMax\n = std::max(efMax, hypot(bin->electroForceX(), bin->electroForceY()));\n max_len = std::min({max_len, bin->dx(), bin->dy()});\n }\n\n for (auto& bin : nb_->bins()) {\n float fx = bin->electroForceX();\n float fy = bin->electroForceY();\n float angle = atan(fy \/ fx);\n float ratio = hypot(fx, fy) \/ efMax;\n float dx = cos(angle) * max_len * ratio;\n float dy = sin(angle) * max_len * ratio;\n\n int cx = bin->cx();\n int cy = bin->cy();\n\n painter.setPen(gui::Painter::red, true);\n painter.drawLine(cx, cy, cx + dx, cy + dy);\n }\n }\n}\n\nvoid Graphics::cellPlot(bool pause)\n{\n gui::Gui::get()->redraw();\n if (pause) {\n gui::Gui::get()->pause();\n }\n}\n\ngui::Selected Graphics::select(odb::dbTechLayer* layer, const odb::Point& point)\n{\n selected_ = nullptr;\n\n if (layer) {\n return gui::Selected();\n }\n\n for (GCell* cell : nb_->gCells()) {\n const int gcx = cell->dCx();\n const int gcy = cell->dCy();\n\n int xl = gcx - cell->dx() \/ 2;\n int yl = gcy - cell->dy() \/ 2;\n int xh = gcx + cell->dx() \/ 2;\n int yh = gcy + cell->dy() \/ 2;\n\n if (point.x() < xl || point.y() < yl || point.x() > xh || point.y() > yh) {\n continue;\n }\n\n selected_ = cell;\n if (cell->isInstance()) {\n return gui::Selected(cell->instance()->dbInst());\n }\n }\n return gui::Selected();\n}\n\nvoid Graphics::status(const std::string& message)\n{\n gui::Gui::get()->status(message);\n}\n\n\/* static *\/\nbool Graphics::guiActive()\n{\n return gui::Gui::get() != nullptr;\n}\n\n} \/\/ namespace replace\n<commit_msg>replace: fix force line<commit_after>#include <algorithm>\n#include <cstdio>\n#include <limits>\n\n#include \"graphics.h\"\n#include \"nesterovBase.h\"\n#include \"placerBase.h\"\n\nnamespace replace {\n\nGraphics::Graphics(std::shared_ptr<PlacerBase> pb,\n std::shared_ptr<NesterovBase> nb,\n bool draw_bins)\n : pb_(pb), nb_(nb), selected_(nullptr), draw_bins_(draw_bins)\n{\n gui::Gui::get()->register_renderer(this);\n}\n\nvoid Graphics::drawObjects(gui::Painter& painter)\n{\n \/\/ draw core bounds\n auto& die = pb_->die();\n painter.setPen(gui::Painter::yellow, \/* cosmetic *\/ true);\n painter.drawLine(die.coreLx(), die.coreLy(), die.coreUx(), die.coreLy());\n painter.drawLine(die.coreUx(), die.coreLy(), die.coreUx(), die.coreUy());\n painter.drawLine(die.coreUx(), die.coreUy(), die.coreLx(), die.coreUy());\n painter.drawLine(die.coreLx(), die.coreUy(), die.coreLx(), die.coreLy());\n\n if (draw_bins_) {\n \/\/ Draw the bins\n painter.setPen(gui::Painter::white, \/* cosmetic *\/ true);\n for (auto& bin : nb_->bins()) {\n int color = bin->density() * 50 + 20;\n\n color = (color > 255) ? 255 : (color < 20) ? 20 : color;\n color = 255 - color;\n\n painter.setBrush({color, color, color, 180});\n painter.drawRect({bin->lx(), bin->ly(), bin->ux(), bin->uy()});\n }\n }\n\n \/\/ Draw the placeable objects\n painter.setPen(gui::Painter::white);\n for (auto* gCell : nb_->gCells()) {\n const int gcx = gCell->dCx();\n const int gcy = gCell->dCy();\n\n int xl = gcx - gCell->dx() \/ 2;\n int yl = gcy - gCell->dy() \/ 2;\n int xh = gcx + gCell->dx() \/ 2;\n int yh = gcy + gCell->dy() \/ 2;\n\n gui::Painter::Color color;\n if (gCell->isInstance()) {\n color = gui::Painter::dark_blue;\n } else if (gCell->isFiller()) {\n color = gui::Painter::dark_magenta;\n }\n if (gCell == selected_) {\n color = gui::Painter::yellow;\n }\n\n color.a = 180;\n painter.setBrush(color);\n painter.drawRect({xl, yl, xh, yh});\n }\n\n \/\/ Draw lines to neighbors\n if (selected_) {\n painter.setPen(gui::Painter::yellow, true);\n for (GPin* pin : selected_->gPins()) {\n GNet* net = pin->gNet();\n if (!net) {\n continue;\n }\n for (GPin* other_pin : net->gPins()) {\n GCell* neighbor = other_pin->gCell();\n if (neighbor == selected_) {\n continue;\n }\n painter.drawLine(\n pin->cx(), pin->cy(), other_pin->cx(), other_pin->cy());\n }\n }\n }\n\n \/\/ Draw force direction lines\n if (draw_bins_) {\n float efMax = 0;\n int max_len = std::numeric_limits<int>::max();\n for (auto& bin : nb_->bins()) {\n efMax\n = std::max(efMax, hypot(bin->electroForceX(), bin->electroForceY()));\n max_len = std::min({max_len, bin->dx(), bin->dy()});\n }\n\n for (auto& bin : nb_->bins()) {\n float fx = bin->electroForceX();\n float fy = bin->electroForceY();\n float f = hypot(fx, fy);\n float ratio = f \/ efMax;\n float dx = fx \/ f * max_len * ratio;\n float dy = fy \/ f * max_len * ratio;\n\n int cx = bin->cx();\n int cy = bin->cy();\n\n painter.setPen(gui::Painter::red, true);\n painter.drawLine(cx, cy, cx + dx, cy + dy);\n }\n }\n}\n\nvoid Graphics::cellPlot(bool pause)\n{\n gui::Gui::get()->redraw();\n if (pause) {\n gui::Gui::get()->pause();\n }\n}\n\ngui::Selected Graphics::select(odb::dbTechLayer* layer, const odb::Point& point)\n{\n selected_ = nullptr;\n\n if (layer) {\n return gui::Selected();\n }\n\n for (GCell* cell : nb_->gCells()) {\n const int gcx = cell->dCx();\n const int gcy = cell->dCy();\n\n int xl = gcx - cell->dx() \/ 2;\n int yl = gcy - cell->dy() \/ 2;\n int xh = gcx + cell->dx() \/ 2;\n int yh = gcy + cell->dy() \/ 2;\n\n if (point.x() < xl || point.y() < yl || point.x() > xh || point.y() > yh) {\n continue;\n }\n\n selected_ = cell;\n if (cell->isInstance()) {\n return gui::Selected(cell->instance()->dbInst());\n }\n }\n return gui::Selected();\n}\n\nvoid Graphics::status(const std::string& message)\n{\n gui::Gui::get()->status(message);\n}\n\n\/* static *\/\nbool Graphics::guiActive()\n{\n return gui::Gui::get() != nullptr;\n}\n\n} \/\/ namespace replace\n<|endoftext|>"} {"text":"<commit_before>#include \"TextureFont.hpp\"\n\nusing namespace rffalcon;\n\n#define POINT_RES 64\n#define DPI 72\n\nTextureFont::TextureFont(std::shared_ptr<TextureAtlas> atlas, const float pointSize, const std::string &filename)\n\t: _atlas(atlas), _pointSize(pointSize), _filename(filename)\n{\n\t_initialize();\n}\n\nTextureFont::~TextureFont()\n{\n}\n\nfloat TextureFont::getHeight() const\n{\n\treturn _height;\n}\n\nvoid TextureFont::loadGlyphs(const std::string &text)\n{\n\tint width = _atlas->getWidth();\n\tint height = _atlas->getHeight();\n\tint depth = _atlas->getDepth();\n\n\tFT_Library library;\n\tFT_Face face;\n\t_loadFace(&library, &face);\n\tint length = text.length();\n\t\/\/ Load the glyph for each character in the string\n\tfor (int i = 0; i < length; ++i)\n\t{\n\t\t\/\/ Skip glyphs that have already been loaded\n\t\tfor (int j = 0; j < _glyphs.size(); ++j)\n\t\t{\n\t\t\tTextureGlyph glyph = _glyphs[j];\n\t\t\tif (glyph.charCode == text[i])\n\t\t\t{\n\n\t\t\t}\n\t\t}\n\t}\n}\n\nvoid TextureFont::_initialize()\n{\n\tFT_Library library;\n\tFT_Face face;\n\tFT_Size_Metrics metrics;\n\n\tFT_Error error = FT_Init_FreeType(&library);\n\tif (error != FT_Err_Ok)\n\t{\n\t\tthrow new std::exception();\n\t}\n\n\t_loadFace(&library, &face, _pointSize * 100.0f);\n\tmetrics = face->size->metrics;\n\t_ascender = (metrics.ascender >> 6) \/ 100.0f;\n\t_descender = (metrics.descender >> 6) \/ 100.0f;\n\t_height = (metrics.height >> 6) \/ 100.0f;\n\t_linegap = _height - _ascender + _descender;\n\n\tFT_Done_Face(face);\n\tFT_Done_FreeType(library);\n}\n\nvoid TextureFont::_loadFace(FT_Library *library, FT_Face *face, float pointSize)\n{\n\tFT_Error error = FT_New_Face(*library, _filename.c_str(), 0, face);\n\tif (error != FT_Err_Ok)\n\t{\n\t\tthrow new std::exception();\n\t}\n\n\terror = FT_Select_Charmap(*face, FT_ENCODING_UNICODE);\n\tif (error)\n\t{\n\t\tthrow new std::exception();\n\t}\n\n\terror = FT_Set_Char_Size(*face, (int)(pointSize * POINT_RES), 0, DPI * POINT_RES, DPI);\n\tif (error)\n\t{\n\t\tthrow new std::exception();\n\t}\n\t\n\tFT_Matrix matrix = {\n\t\t(int)((1.0 \/ POINT_RES) * 0x10000L),\n\t\t0,\n\t\t0,\n\t\t0x10000L\n\t};\n\n\tFT_Set_Transform(*face, &matrix, nullptr);\n}\n\nvoid TextureFont::_loadFace(FT_Library *library, FT_Face *face)\n{\n\t_loadFace(library, face, _pointSize);\n}<commit_msg>static_cast of size of glyphs to answer warning<commit_after>#include \"TextureFont.hpp\"\n\nusing namespace rffalcon;\n\n#define POINT_RES 64\n#define DPI 72\n\nTextureFont::TextureFont(std::shared_ptr<TextureAtlas> atlas, const float pointSize, const std::string &filename)\n\t: _atlas(atlas), _pointSize(pointSize), _filename(filename)\n{\n\t_initialize();\n}\n\nTextureFont::~TextureFont()\n{\n}\n\nfloat TextureFont::getHeight() const\n{\n\treturn _height;\n}\n\nvoid TextureFont::loadGlyphs(const std::string &text)\n{\n\tint width = _atlas->getWidth();\n\tint height = _atlas->getHeight();\n\tint depth = _atlas->getDepth();\n\n\tFT_Library library;\n\tFT_Face face;\n\t_loadFace(&library, &face);\n\tint length = text.length();\n\tint sizeGlyphs = static_cast<int>(_glyphs.size());\n\t\/\/ Load the glyph for each character in the string\n\tfor (int i = 0; i < length; ++i)\n\t{\n\t\t\/\/ Skip glyphs that have already been loaded\n\t\tfor (int j = 0; j < sizeGlyphs; ++j)\n\t\t{\n\t\t\tTextureGlyph glyph = _glyphs[j];\n\t\t\tif (glyph.charCode == text[i])\n\t\t\t{\n\n\t\t\t}\n\t\t}\n\t}\n}\n\nvoid TextureFont::_initialize()\n{\n\tFT_Library library;\n\tFT_Face face;\n\tFT_Size_Metrics metrics;\n\n\tFT_Error error = FT_Init_FreeType(&library);\n\tif (error != FT_Err_Ok)\n\t{\n\t\tthrow new std::exception();\n\t}\n\n\t_loadFace(&library, &face, _pointSize * 100.0f);\n\tmetrics = face->size->metrics;\n\t_ascender = (metrics.ascender >> 6) \/ 100.0f;\n\t_descender = (metrics.descender >> 6) \/ 100.0f;\n\t_height = (metrics.height >> 6) \/ 100.0f;\n\t_linegap = _height - _ascender + _descender;\n\n\tFT_Done_Face(face);\n\tFT_Done_FreeType(library);\n}\n\nvoid TextureFont::_loadFace(FT_Library *library, FT_Face *face, float pointSize)\n{\n\tFT_Error error = FT_New_Face(*library, _filename.c_str(), 0, face);\n\tif (error != FT_Err_Ok)\n\t{\n\t\tthrow new std::exception();\n\t}\n\n\terror = FT_Select_Charmap(*face, FT_ENCODING_UNICODE);\n\tif (error)\n\t{\n\t\tthrow new std::exception();\n\t}\n\n\terror = FT_Set_Char_Size(*face, (int)(pointSize * POINT_RES), 0, DPI * POINT_RES, DPI);\n\tif (error)\n\t{\n\t\tthrow new std::exception();\n\t}\n\t\n\tFT_Matrix matrix = {\n\t\t(int)((1.0 \/ POINT_RES) * 0x10000L),\n\t\t0,\n\t\t0,\n\t\t0x10000L\n\t};\n\n\tFT_Set_Transform(*face, &matrix, nullptr);\n}\n\nvoid TextureFont::_loadFace(FT_Library *library, FT_Face *face)\n{\n\t_loadFace(library, face, _pointSize);\n}<|endoftext|>"} {"text":"<commit_before><commit_msg>typo - fixed reloading<commit_after><|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (C) 2017 Jérôme Leclercq\n\/\/ This file is part of the \"Nazara Engine - Utility module\"\n\/\/ For conditions of distribution and use, see copyright notice in Config.hpp\n\n#include <Nazara\/Utility\/Buffer.hpp>\n#include <Nazara\/Core\/CallOnExit.hpp>\n#include <Nazara\/Core\/Error.hpp>\n#include <Nazara\/Core\/ErrorFlags.hpp>\n#include <Nazara\/Utility\/BufferMapper.hpp>\n#include <Nazara\/Utility\/Config.hpp>\n#include <Nazara\/Utility\/SoftwareBuffer.hpp>\n#include <memory>\n#include <Nazara\/Utility\/Debug.hpp>\n\nnamespace Nz\n{\n\tBuffer::Buffer(BufferType type) :\n\tm_type(type),\n\tm_usage(0),\n\tm_size(0)\n\t{\n\t}\n\n\tBuffer::Buffer(BufferType type, UInt32 size, DataStorage storage, BufferUsageFlags usage) :\n\tBuffer(type)\n\t{\n\t\tErrorFlags flags(ErrorFlag_ThrowException, true);\n\n\t\tCreate(size, storage, usage);\n\t}\n\n\tBuffer::~Buffer()\n\t{\n\t\tOnBufferRelease(this);\n\n\t\tDestroy();\n\t}\n\n\tbool Buffer::CopyContent(const BufferRef& buffer)\n\t{\n\t\tNazaraAssert(m_impl, \"Invalid buffer\");\n\t\tNazaraAssert(!buffer && !buffer->IsValid(), \"Invalid source buffer\");\n\n\t\tBufferMapper<Buffer> mapper(*buffer, BufferAccess_ReadOnly);\n\t\treturn Fill(mapper.GetPointer(), 0, buffer->GetSize());\n\t}\n\n\tbool Buffer::Create(UInt32 size, DataStorage storage, BufferUsageFlags usage)\n\t{\n\t\tDestroy();\n\n\t\t\/\/ Notre buffer est-il supporté ?\n\t\tif (!IsStorageSupported(storage))\n\t\t{\n\t\t\tNazaraError(\"Buffer storage not supported\");\n\t\t\treturn false;\n\t\t}\n\n\t\tstd::unique_ptr<AbstractBuffer> impl(s_bufferFactories[storage](this, m_type));\n\t\tif (!impl->Initialize(size, usage))\n\t\t{\n\t\t\tNazaraError(\"Failed to create buffer\");\n\t\t\treturn false;\n\t\t}\n\n\t\tm_impl = std::move(impl);\n\t\tm_size = size;\n\t\tm_usage = usage;\n\n\t\treturn true; \/\/ Si on arrive ici c'est que tout s'est bien passé.\n\t}\n\n\tvoid Buffer::Destroy()\n\t{\n\t\tif (!m_impl)\n\t\t{\n\t\t\tOnBufferDestroy(this);\n\n\t\t\tm_impl.reset();\n\t\t}\n\t}\n\n\tbool Buffer::Fill(const void* data, UInt32 offset, UInt32 size)\n\t{\n\t\tNazaraAssert(m_impl, \"Invalid buffer\");\n\t\tNazaraAssert(offset + size <= m_size, \"Exceeding buffer size\");\n\n\t\treturn m_impl->Fill(data, offset, (size == 0) ? m_size - offset : size);\n\t}\n\n\tvoid* Buffer::Map(BufferAccess access, UInt32 offset, UInt32 size)\n\t{\n\t\tNazaraAssert(m_impl, \"Invalid buffer\");\n\t\tNazaraAssert(offset + size <= m_size, \"Exceeding buffer size\");\n\n\t\treturn m_impl->Map(access, offset, (size == 0) ? m_size - offset : size);\n\t}\n\n\tvoid* Buffer::Map(BufferAccess access, UInt32 offset, UInt32 size) const\n\t{\n\t\tNazaraAssert(m_impl, \"Invalid buffer\");\n\t\tNazaraAssert(access == BufferAccess_ReadOnly, \"Buffer access must be read-only when used const\");\n\t\tNazaraAssert(offset + size <= m_size, \"Exceeding buffer size\");\n\n\t\treturn m_impl->Map(access, offset, (size == 0) ? m_size - offset : size);\n\t}\n\n\tbool Buffer::SetStorage(DataStorage storage)\n\t{\n\t\tNazaraAssert(m_impl, \"Invalid buffer\");\n\n\t\tif (HasStorage(storage))\n\t\t\treturn true;\n\n\t\tif (!IsStorageSupported(storage))\n\t\t{\n\t\t\tNazaraError(\"Storage not supported\");\n\t\t\treturn false;\n\t\t}\n\n\t\tvoid* ptr = m_impl->Map(BufferAccess_ReadOnly, 0, m_size);\n\t\tif (!ptr)\n\t\t{\n\t\t\tNazaraError(\"Failed to map buffer\");\n\t\t\treturn false;\n\t\t}\n\n\t\tCallOnExit unmapMyImpl([this]()\n\t\t{\n\t\t\tm_impl->Unmap();\n\t\t});\n\n\t\tstd::unique_ptr<AbstractBuffer> impl(s_bufferFactories[storage](this, m_type));\n\t\tif (!impl->Initialize(m_size, m_usage))\n\t\t{\n\t\t\tNazaraError(\"Failed to create buffer\");\n\t\t\treturn false;\n\t\t}\n\n\t\tif (!impl->Fill(ptr, 0, m_size))\n\t\t{\n\t\t\tNazaraError(\"Failed to fill buffer\");\n\t\t\treturn false;\n\t\t}\n\n\t\tunmapMyImpl.CallAndReset();\n\n\t\tm_impl = std::move(impl);\n\n\t\treturn true;\n\t}\n\n\tvoid Buffer::Unmap() const\n\t{\n\t\tNazaraAssert(m_impl, \"Invalid buffer\");\n\n\t\tif (!m_impl->Unmap())\n\t\t\tNazaraWarning(\"Failed to unmap buffer (it's content may be undefined)\"); \/\/\/TODO: Unexpected ?\n\t}\n\n\tbool Buffer::IsStorageSupported(DataStorage storage)\n\t{\n\t\treturn s_bufferFactories[storage] != nullptr;\n\t}\n\n\tvoid Buffer::SetBufferFactory(DataStorage storage, BufferFactory func)\n\t{\n\t\ts_bufferFactories[storage] = func;\n\t}\n\n\tbool Buffer::Initialize()\n\t{\n\t\tSetBufferFactory(DataStorage_Software, [](Buffer* parent, BufferType type) -> AbstractBuffer*\n\t\t{\n\t\t\treturn new SoftwareBuffer(parent, type);\n\t\t});\n\n\t\treturn true;\n\t}\n\n\tvoid Buffer::Uninitialize()\n\t{\n\t\tstd::fill(s_bufferFactories.begin(), s_bufferFactories.end(), nullptr);\n\t}\n\n\tstd::array<Buffer::BufferFactory, DataStorage_Max + 1> Buffer::s_bufferFactories;\n}\n<commit_msg>Utility\/Buffer: Fix Destroy() not really destroying buffer<commit_after>\/\/ Copyright (C) 2017 Jérôme Leclercq\n\/\/ This file is part of the \"Nazara Engine - Utility module\"\n\/\/ For conditions of distribution and use, see copyright notice in Config.hpp\n\n#include <Nazara\/Utility\/Buffer.hpp>\n#include <Nazara\/Core\/CallOnExit.hpp>\n#include <Nazara\/Core\/Error.hpp>\n#include <Nazara\/Core\/ErrorFlags.hpp>\n#include <Nazara\/Utility\/BufferMapper.hpp>\n#include <Nazara\/Utility\/Config.hpp>\n#include <Nazara\/Utility\/SoftwareBuffer.hpp>\n#include <memory>\n#include <Nazara\/Utility\/Debug.hpp>\n\nnamespace Nz\n{\n\tBuffer::Buffer(BufferType type) :\n\tm_type(type),\n\tm_usage(0),\n\tm_size(0)\n\t{\n\t}\n\n\tBuffer::Buffer(BufferType type, UInt32 size, DataStorage storage, BufferUsageFlags usage) :\n\tBuffer(type)\n\t{\n\t\tErrorFlags flags(ErrorFlag_ThrowException, true);\n\n\t\tCreate(size, storage, usage);\n\t}\n\n\tBuffer::~Buffer()\n\t{\n\t\tOnBufferRelease(this);\n\n\t\tDestroy();\n\t}\n\n\tbool Buffer::CopyContent(const BufferRef& buffer)\n\t{\n\t\tNazaraAssert(m_impl, \"Invalid buffer\");\n\t\tNazaraAssert(!buffer && !buffer->IsValid(), \"Invalid source buffer\");\n\n\t\tBufferMapper<Buffer> mapper(*buffer, BufferAccess_ReadOnly);\n\t\treturn Fill(mapper.GetPointer(), 0, buffer->GetSize());\n\t}\n\n\tbool Buffer::Create(UInt32 size, DataStorage storage, BufferUsageFlags usage)\n\t{\n\t\tDestroy();\n\n\t\t\/\/ Notre buffer est-il supporté ?\n\t\tif (!IsStorageSupported(storage))\n\t\t{\n\t\t\tNazaraError(\"Buffer storage not supported\");\n\t\t\treturn false;\n\t\t}\n\n\t\tstd::unique_ptr<AbstractBuffer> impl(s_bufferFactories[storage](this, m_type));\n\t\tif (!impl->Initialize(size, usage))\n\t\t{\n\t\t\tNazaraError(\"Failed to create buffer\");\n\t\t\treturn false;\n\t\t}\n\n\t\tm_impl = std::move(impl);\n\t\tm_size = size;\n\t\tm_usage = usage;\n\n\t\treturn true; \/\/ Si on arrive ici c'est que tout s'est bien passé.\n\t}\n\n\tvoid Buffer::Destroy()\n\t{\n\t\tif (m_impl)\n\t\t{\n\t\t\tOnBufferDestroy(this);\n\n\t\t\tm_impl.reset();\n\t\t}\n\t}\n\n\tbool Buffer::Fill(const void* data, UInt32 offset, UInt32 size)\n\t{\n\t\tNazaraAssert(m_impl, \"Invalid buffer\");\n\t\tNazaraAssert(offset + size <= m_size, \"Exceeding buffer size\");\n\n\t\treturn m_impl->Fill(data, offset, (size == 0) ? m_size - offset : size);\n\t}\n\n\tvoid* Buffer::Map(BufferAccess access, UInt32 offset, UInt32 size)\n\t{\n\t\tNazaraAssert(m_impl, \"Invalid buffer\");\n\t\tNazaraAssert(offset + size <= m_size, \"Exceeding buffer size\");\n\n\t\treturn m_impl->Map(access, offset, (size == 0) ? m_size - offset : size);\n\t}\n\n\tvoid* Buffer::Map(BufferAccess access, UInt32 offset, UInt32 size) const\n\t{\n\t\tNazaraAssert(m_impl, \"Invalid buffer\");\n\t\tNazaraAssert(access == BufferAccess_ReadOnly, \"Buffer access must be read-only when used const\");\n\t\tNazaraAssert(offset + size <= m_size, \"Exceeding buffer size\");\n\n\t\treturn m_impl->Map(access, offset, (size == 0) ? m_size - offset : size);\n\t}\n\n\tbool Buffer::SetStorage(DataStorage storage)\n\t{\n\t\tNazaraAssert(m_impl, \"Invalid buffer\");\n\n\t\tif (HasStorage(storage))\n\t\t\treturn true;\n\n\t\tif (!IsStorageSupported(storage))\n\t\t{\n\t\t\tNazaraError(\"Storage not supported\");\n\t\t\treturn false;\n\t\t}\n\n\t\tvoid* ptr = m_impl->Map(BufferAccess_ReadOnly, 0, m_size);\n\t\tif (!ptr)\n\t\t{\n\t\t\tNazaraError(\"Failed to map buffer\");\n\t\t\treturn false;\n\t\t}\n\n\t\tCallOnExit unmapMyImpl([this]()\n\t\t{\n\t\t\tm_impl->Unmap();\n\t\t});\n\n\t\tstd::unique_ptr<AbstractBuffer> impl(s_bufferFactories[storage](this, m_type));\n\t\tif (!impl->Initialize(m_size, m_usage))\n\t\t{\n\t\t\tNazaraError(\"Failed to create buffer\");\n\t\t\treturn false;\n\t\t}\n\n\t\tif (!impl->Fill(ptr, 0, m_size))\n\t\t{\n\t\t\tNazaraError(\"Failed to fill buffer\");\n\t\t\treturn false;\n\t\t}\n\n\t\tunmapMyImpl.CallAndReset();\n\n\t\tm_impl = std::move(impl);\n\n\t\treturn true;\n\t}\n\n\tvoid Buffer::Unmap() const\n\t{\n\t\tNazaraAssert(m_impl, \"Invalid buffer\");\n\n\t\tif (!m_impl->Unmap())\n\t\t\tNazaraWarning(\"Failed to unmap buffer (it's content may be undefined)\"); \/\/\/TODO: Unexpected ?\n\t}\n\n\tbool Buffer::IsStorageSupported(DataStorage storage)\n\t{\n\t\treturn s_bufferFactories[storage] != nullptr;\n\t}\n\n\tvoid Buffer::SetBufferFactory(DataStorage storage, BufferFactory func)\n\t{\n\t\ts_bufferFactories[storage] = func;\n\t}\n\n\tbool Buffer::Initialize()\n\t{\n\t\tSetBufferFactory(DataStorage_Software, [](Buffer* parent, BufferType type) -> AbstractBuffer*\n\t\t{\n\t\t\treturn new SoftwareBuffer(parent, type);\n\t\t});\n\n\t\treturn true;\n\t}\n\n\tvoid Buffer::Uninitialize()\n\t{\n\t\tstd::fill(s_bufferFactories.begin(), s_bufferFactories.end(), nullptr);\n\t}\n\n\tstd::array<Buffer::BufferFactory, DataStorage_Max + 1> Buffer::s_bufferFactories;\n}\n<|endoftext|>"} {"text":"<commit_before>#include <gtest\/gtest.h>\n#include <zmq.hpp>\n\n#if defined(ZMQ_CPP11) && defined(ZMQ_BUILD_DRAFT_API)\n\n#include <array>\n#include <memory>\n\nTEST(poller, create_destroy)\n{\n zmq::poller_t poller;\n ASSERT_EQ(0u, poller.size ());\n}\n\nstatic_assert(!std::is_copy_constructible<zmq::poller_t>::value, \"poller_t should not be copy-constructible\");\nstatic_assert(!std::is_copy_assignable<zmq::poller_t>::value, \"poller_t should not be copy-assignable\");\n\nTEST(poller, move_construct_empty)\n{\n std::unique_ptr<zmq::poller_t> a{new zmq::poller_t};\n zmq::poller_t b = std::move(*a);\n\n ASSERT_EQ(0u, a->size ());\n a.reset ();\n ASSERT_EQ(0u, b.size ());\n}\n\nTEST(poller, move_assign_empty)\n{\n std::unique_ptr<zmq::poller_t> a{new zmq::poller_t};\n zmq::poller_t b;\n\n b = std::move(*a);\n\n ASSERT_EQ(0u, a->size ());\n a.reset ();\n ASSERT_EQ(0u, b.size ());\n}\n\nTEST(poller, move_construct_non_empty)\n{\n zmq::context_t context;\n zmq::socket_t socket{context, zmq::socket_type::router};\n\n std::unique_ptr<zmq::poller_t> a{new zmq::poller_t};\n a->add(socket, ZMQ_POLLIN, [](short) {});\n zmq::poller_t b = std::move(*a);\n\n ASSERT_EQ(0u, a->size ());\n a.reset ();\n ASSERT_EQ(1u, b.size ());\n}\n\nTEST(poller, move_assign_non_empty)\n{\n zmq::context_t context;\n zmq::socket_t socket{context, zmq::socket_type::router};\n\n std::unique_ptr<zmq::poller_t> a{new zmq::poller_t};\n a->add(socket, ZMQ_POLLIN, [](short) {});\n zmq::poller_t b;\n\n b = std::move(*a);\n\n ASSERT_EQ(0u, a->size ());\n a.reset ();\n ASSERT_EQ(1u, b.size ());\n}\n\nTEST(poller, add_handler)\n{\n zmq::context_t context;\n zmq::socket_t socket{context, zmq::socket_type::router};\n zmq::poller_t poller;\n zmq::poller_t::handler_t handler;\n ASSERT_NO_THROW(poller.add(socket, ZMQ_POLLIN, handler));\n}\n\nTEST(poller, add_handler_invalid_events_type)\n{\n zmq::context_t context;\n zmq::socket_t socket{context, zmq::socket_type::router};\n zmq::poller_t poller;\n zmq::poller_t::handler_t handler;\n short invalid_events_type = 2 << 10;\n ASSERT_NO_THROW(poller.add(socket, invalid_events_type, handler));\n}\n\nTEST(poller, add_handler_twice_throws)\n{\n zmq::context_t context;\n zmq::socket_t socket{context, zmq::socket_type::router};\n zmq::poller_t poller;\n zmq::poller_t::handler_t handler;\n poller.add(socket, ZMQ_POLLIN, handler);\n \/\/\/ \\todo the actual error code should be checked\n ASSERT_THROW(poller.add(socket, ZMQ_POLLIN, handler), zmq::error_t);\n}\n\nTEST(poller, wait_with_no_handlers_throws)\n{\n zmq::poller_t poller;\n \/\/\/ \\todo the actual error code should be checked\n ASSERT_THROW(poller.wait(std::chrono::milliseconds{10}), zmq::error_t);\n}\n\nTEST(poller, remove_unregistered_throws)\n{\n zmq::context_t context;\n zmq::socket_t socket{context, zmq::socket_type::router};\n zmq::poller_t poller;\n \/\/\/ \\todo the actual error code should be checked\n ASSERT_THROW(poller.remove(socket), zmq::error_t);\n}\n\nTEST(poller, remove_registered_empty)\n{\n zmq::context_t context;\n zmq::socket_t socket{context, zmq::socket_type::router};\n zmq::poller_t poller;\n poller.add(socket, ZMQ_POLLIN, zmq::poller_t::handler_t{});\n ASSERT_NO_THROW(poller.remove(socket));\n}\n\nTEST(poller, remove_registered_non_empty)\n{\n zmq::context_t context;\n zmq::socket_t socket{context, zmq::socket_type::router};\n zmq::poller_t poller;\n poller.add(socket, ZMQ_POLLIN, [](short) {});\n ASSERT_NO_THROW(poller.remove(socket));\n}\n\nnamespace {\n\nclass loopback_ip4_binder\n{\npublic:\n loopback_ip4_binder(zmq::socket_t &socket) { bind(socket); }\n std::string endpoint() { return endpoint_; }\nprivate:\n \/\/ Helper function used in constructor\n \/\/ as Gtest allows ASSERT_* only in void returning functions\n \/\/ and constructor\/destructor are not.\n void bind(zmq::socket_t &socket)\n {\n ASSERT_NO_THROW(socket.bind(\"tcp:\/\/127.0.0.1:*\"));\n std::array<char, 100> endpoint{};\n size_t endpoint_size = endpoint.size();\n ASSERT_NO_THROW(socket.getsockopt(ZMQ_LAST_ENDPOINT, endpoint.data(),\n &endpoint_size));\n ASSERT_TRUE(endpoint_size < endpoint.size());\n endpoint_ = std::string{endpoint.data()};\n }\n std::string endpoint_;\n};\n\nstruct server_client_setup\n{\n server_client_setup ()\n {\n init ();\n }\n\n void init()\n {\n endpoint = loopback_ip4_binder {server}.endpoint ();\n ASSERT_NO_THROW (client.connect (endpoint));\n }\n\n zmq::poller_t::handler_t handler = [&](short e) {\n events = e;\n };\n\n zmq::context_t context;\n zmq::socket_t server {context, zmq::socket_type::router};\n zmq::socket_t client {context, zmq::socket_type::dealer};\n std::string endpoint;\n short events = 0;\n};\n\n} \/\/namespace\n\nTEST(poller, poll_basic)\n{\n server_client_setup s;\n\n ASSERT_NO_THROW(s.client.send(\"Hi\"));\n\n zmq::poller_t poller;\n bool message_received = false;\n zmq::poller_t::handler_t handler = [&message_received](short events) {\n ASSERT_TRUE(0 != (events & ZMQ_POLLIN));\n message_received = true;\n };\n ASSERT_NO_THROW(poller.add(s.server, ZMQ_POLLIN, handler));\n ASSERT_NO_THROW(poller.wait(std::chrono::milliseconds{-1}));\n ASSERT_TRUE(message_received);\n}\n\n\/\/\/ \\todo this contains multiple test cases that should be split up\nTEST(poller, client_server)\n{\n const std::string send_msg = \"Hi\";\n\n \/\/ Setup server and client\n server_client_setup s;\n\n \/\/ Setup poller\n zmq::poller_t poller;\n short events;\n zmq::poller_t::handler_t handler = [&](short e) {\n if (0 != (e & ZMQ_POLLIN)) {\n zmq::message_t zmq_msg;\n ASSERT_NO_THROW(s.server.recv(&zmq_msg)); \/\/ skip msg id\n ASSERT_NO_THROW(s.server.recv(&zmq_msg)); \/\/ get message\n std::string recv_msg(zmq_msg.data<char>(),\n zmq_msg.size());\n ASSERT_EQ(send_msg, recv_msg);\n } else if (0 != (e & ~ZMQ_POLLOUT)) {\n ASSERT_TRUE(false) << \"Unexpected event type \" << events;\n }\n events = e;\n };\n\n ASSERT_NO_THROW(poller.add(s.server, ZMQ_POLLIN, handler));\n\n \/\/ client sends message\n ASSERT_NO_THROW(s.client.send(send_msg));\n\n ASSERT_NO_THROW(poller.wait(std::chrono::milliseconds{-1}));\n ASSERT_EQ(events, ZMQ_POLLIN);\n\n \/\/ Re-add server socket with pollout flag\n ASSERT_NO_THROW(poller.remove(s.server));\n ASSERT_NO_THROW(poller.add(s.server, ZMQ_POLLIN | ZMQ_POLLOUT, handler));\n ASSERT_NO_THROW(poller.wait(std::chrono::milliseconds{-1}));\n ASSERT_EQ(events, ZMQ_POLLOUT);\n}\n\nTEST(poller, poller_add_invalid_socket_throws)\n{\n zmq::context_t context;\n zmq::poller_t poller;\n zmq::socket_t a {context, zmq::socket_type::router};\n zmq::socket_t b {std::move (a)};\n ASSERT_THROW (poller.add (a, ZMQ_POLLIN, zmq::poller_t::handler_t {}),\n zmq::error_t);\n ASSERT_EQ (0u, poller.size ());\n}\n\nTEST(poller, poller_remove_invalid_socket_throws)\n{\n zmq::context_t context;\n zmq::socket_t socket {context, zmq::socket_type::router};\n zmq::poller_t poller;\n ASSERT_NO_THROW (poller.add (socket, ZMQ_POLLIN, zmq::poller_t::handler_t {}));\n ASSERT_EQ (1u, poller.size ());\n std::vector<zmq::socket_t> sockets;\n sockets.emplace_back (std::move (socket));\n ASSERT_THROW (poller.remove (socket), zmq::error_t);\n ASSERT_EQ (1u, poller.size ());\n}\n\nTEST(poller, wait_on_added_empty_handler)\n{\n server_client_setup s;\n ASSERT_NO_THROW(s.client.send(\"Hi\"));\n zmq::poller_t poller;\n std::function<void(void)> handler;\n ASSERT_NO_THROW(poller.add(s.server, ZMQ_POLLIN, handler));\n ASSERT_NO_THROW(poller.wait(std::chrono::milliseconds{-1}));\n}\n\nTEST(poller, modify_empty_throws)\n{\n zmq::context_t context;\n zmq::socket_t socket {context, zmq::socket_type::push};\n zmq::poller_t poller;\n ASSERT_THROW (poller.modify (socket, ZMQ_POLLIN), zmq::error_t);\n}\n\nTEST(poller, modify_invalid_socket_throws)\n{\n zmq::context_t context;\n zmq::socket_t a {context, zmq::socket_type::push};\n zmq::socket_t b {std::move (a)};\n zmq::poller_t poller;\n ASSERT_THROW (poller.modify (a, ZMQ_POLLIN), zmq::error_t);\n}\n\nTEST(poller, modified_not_added_throws)\n{\n zmq::context_t context;\n zmq::socket_t a {context, zmq::socket_type::push};\n zmq::socket_t b {context, zmq::socket_type::push};\n zmq::poller_t poller;\n ASSERT_NO_THROW (poller.add (a, ZMQ_POLLIN, zmq::poller_t::handler_t {}));\n ASSERT_THROW (poller.modify (b, ZMQ_POLLIN), zmq::error_t);\n}\n\nTEST(poller, poll_client_server)\n{\n \/\/ Setup server and client\n server_client_setup s;\n\n \/\/ Setup poller\n zmq::poller_t poller;\n ASSERT_NO_THROW(poller.add(s.server, ZMQ_POLLIN, s.handler));\n\n \/\/ client sends message\n ASSERT_NO_THROW(s.client.send(\"Hi\"));\n\n \/\/ wait for message and verify events\n ASSERT_NO_THROW(poller.wait(std::chrono::milliseconds{500}));\n ASSERT_TRUE(s.events == ZMQ_POLLIN);\n ASSERT_EQ(s.events, ZMQ_POLLIN);\n\n \/\/ Modify server socket with pollout flag\n ASSERT_NO_THROW(poller.modify(s.server, ZMQ_POLLIN | ZMQ_POLLOUT));\n ASSERT_NO_THROW(poller.wait(std::chrono::milliseconds{500}));\n ASSERT_EQ(s.events, ZMQ_POLLIN | ZMQ_POLLOUT);\n}\n\n#endif\n<commit_msg>Problem: poller_t simple modify test case missing<commit_after>#include <gtest\/gtest.h>\n#include <zmq.hpp>\n\n#if defined(ZMQ_CPP11) && defined(ZMQ_BUILD_DRAFT_API)\n\n#include <array>\n#include <memory>\n\nTEST(poller, create_destroy)\n{\n zmq::poller_t poller;\n ASSERT_EQ(0u, poller.size ());\n}\n\nstatic_assert(!std::is_copy_constructible<zmq::poller_t>::value, \"poller_t should not be copy-constructible\");\nstatic_assert(!std::is_copy_assignable<zmq::poller_t>::value, \"poller_t should not be copy-assignable\");\n\nTEST(poller, move_construct_empty)\n{\n std::unique_ptr<zmq::poller_t> a{new zmq::poller_t};\n zmq::poller_t b = std::move(*a);\n\n ASSERT_EQ(0u, a->size ());\n a.reset ();\n ASSERT_EQ(0u, b.size ());\n}\n\nTEST(poller, move_assign_empty)\n{\n std::unique_ptr<zmq::poller_t> a{new zmq::poller_t};\n zmq::poller_t b;\n\n b = std::move(*a);\n\n ASSERT_EQ(0u, a->size ());\n a.reset ();\n ASSERT_EQ(0u, b.size ());\n}\n\nTEST(poller, move_construct_non_empty)\n{\n zmq::context_t context;\n zmq::socket_t socket{context, zmq::socket_type::router};\n\n std::unique_ptr<zmq::poller_t> a{new zmq::poller_t};\n a->add(socket, ZMQ_POLLIN, [](short) {});\n zmq::poller_t b = std::move(*a);\n\n ASSERT_EQ(0u, a->size ());\n a.reset ();\n ASSERT_EQ(1u, b.size ());\n}\n\nTEST(poller, move_assign_non_empty)\n{\n zmq::context_t context;\n zmq::socket_t socket{context, zmq::socket_type::router};\n\n std::unique_ptr<zmq::poller_t> a{new zmq::poller_t};\n a->add(socket, ZMQ_POLLIN, [](short) {});\n zmq::poller_t b;\n\n b = std::move(*a);\n\n ASSERT_EQ(0u, a->size ());\n a.reset ();\n ASSERT_EQ(1u, b.size ());\n}\n\nTEST(poller, add_handler)\n{\n zmq::context_t context;\n zmq::socket_t socket{context, zmq::socket_type::router};\n zmq::poller_t poller;\n zmq::poller_t::handler_t handler;\n ASSERT_NO_THROW(poller.add(socket, ZMQ_POLLIN, handler));\n}\n\nTEST(poller, add_handler_invalid_events_type)\n{\n zmq::context_t context;\n zmq::socket_t socket{context, zmq::socket_type::router};\n zmq::poller_t poller;\n zmq::poller_t::handler_t handler;\n short invalid_events_type = 2 << 10;\n ASSERT_NO_THROW(poller.add(socket, invalid_events_type, handler));\n}\n\nTEST(poller, add_handler_twice_throws)\n{\n zmq::context_t context;\n zmq::socket_t socket{context, zmq::socket_type::router};\n zmq::poller_t poller;\n zmq::poller_t::handler_t handler;\n poller.add(socket, ZMQ_POLLIN, handler);\n \/\/\/ \\todo the actual error code should be checked\n ASSERT_THROW(poller.add(socket, ZMQ_POLLIN, handler), zmq::error_t);\n}\n\nTEST(poller, wait_with_no_handlers_throws)\n{\n zmq::poller_t poller;\n \/\/\/ \\todo the actual error code should be checked\n ASSERT_THROW(poller.wait(std::chrono::milliseconds{10}), zmq::error_t);\n}\n\nTEST(poller, remove_unregistered_throws)\n{\n zmq::context_t context;\n zmq::socket_t socket{context, zmq::socket_type::router};\n zmq::poller_t poller;\n \/\/\/ \\todo the actual error code should be checked\n ASSERT_THROW(poller.remove(socket), zmq::error_t);\n}\n\nTEST(poller, remove_registered_empty)\n{\n zmq::context_t context;\n zmq::socket_t socket{context, zmq::socket_type::router};\n zmq::poller_t poller;\n poller.add(socket, ZMQ_POLLIN, zmq::poller_t::handler_t{});\n ASSERT_NO_THROW(poller.remove(socket));\n}\n\nTEST(poller, remove_registered_non_empty)\n{\n zmq::context_t context;\n zmq::socket_t socket{context, zmq::socket_type::router};\n zmq::poller_t poller;\n poller.add(socket, ZMQ_POLLIN, [](short) {});\n ASSERT_NO_THROW(poller.remove(socket));\n}\n\nnamespace {\n\nclass loopback_ip4_binder\n{\npublic:\n loopback_ip4_binder(zmq::socket_t &socket) { bind(socket); }\n std::string endpoint() { return endpoint_; }\nprivate:\n \/\/ Helper function used in constructor\n \/\/ as Gtest allows ASSERT_* only in void returning functions\n \/\/ and constructor\/destructor are not.\n void bind(zmq::socket_t &socket)\n {\n ASSERT_NO_THROW(socket.bind(\"tcp:\/\/127.0.0.1:*\"));\n std::array<char, 100> endpoint{};\n size_t endpoint_size = endpoint.size();\n ASSERT_NO_THROW(socket.getsockopt(ZMQ_LAST_ENDPOINT, endpoint.data(),\n &endpoint_size));\n ASSERT_TRUE(endpoint_size < endpoint.size());\n endpoint_ = std::string{endpoint.data()};\n }\n std::string endpoint_;\n};\n\nstruct server_client_setup\n{\n server_client_setup ()\n {\n init ();\n }\n\n void init()\n {\n endpoint = loopback_ip4_binder {server}.endpoint ();\n ASSERT_NO_THROW (client.connect (endpoint));\n }\n\n zmq::poller_t::handler_t handler = [&](short e) {\n events = e;\n };\n\n zmq::context_t context;\n zmq::socket_t server {context, zmq::socket_type::router};\n zmq::socket_t client {context, zmq::socket_type::dealer};\n std::string endpoint;\n short events = 0;\n};\n\n} \/\/namespace\n\nTEST(poller, poll_basic)\n{\n server_client_setup s;\n\n ASSERT_NO_THROW(s.client.send(\"Hi\"));\n\n zmq::poller_t poller;\n bool message_received = false;\n zmq::poller_t::handler_t handler = [&message_received](short events) {\n ASSERT_TRUE(0 != (events & ZMQ_POLLIN));\n message_received = true;\n };\n ASSERT_NO_THROW(poller.add(s.server, ZMQ_POLLIN, handler));\n ASSERT_NO_THROW(poller.wait(std::chrono::milliseconds{-1}));\n ASSERT_TRUE(message_received);\n}\n\n\/\/\/ \\todo this contains multiple test cases that should be split up\nTEST(poller, client_server)\n{\n const std::string send_msg = \"Hi\";\n\n \/\/ Setup server and client\n server_client_setup s;\n\n \/\/ Setup poller\n zmq::poller_t poller;\n short events;\n zmq::poller_t::handler_t handler = [&](short e) {\n if (0 != (e & ZMQ_POLLIN)) {\n zmq::message_t zmq_msg;\n ASSERT_NO_THROW(s.server.recv(&zmq_msg)); \/\/ skip msg id\n ASSERT_NO_THROW(s.server.recv(&zmq_msg)); \/\/ get message\n std::string recv_msg(zmq_msg.data<char>(),\n zmq_msg.size());\n ASSERT_EQ(send_msg, recv_msg);\n } else if (0 != (e & ~ZMQ_POLLOUT)) {\n ASSERT_TRUE(false) << \"Unexpected event type \" << events;\n }\n events = e;\n };\n\n ASSERT_NO_THROW(poller.add(s.server, ZMQ_POLLIN, handler));\n\n \/\/ client sends message\n ASSERT_NO_THROW(s.client.send(send_msg));\n\n ASSERT_NO_THROW(poller.wait(std::chrono::milliseconds{-1}));\n ASSERT_EQ(events, ZMQ_POLLIN);\n\n \/\/ Re-add server socket with pollout flag\n ASSERT_NO_THROW(poller.remove(s.server));\n ASSERT_NO_THROW(poller.add(s.server, ZMQ_POLLIN | ZMQ_POLLOUT, handler));\n ASSERT_NO_THROW(poller.wait(std::chrono::milliseconds{-1}));\n ASSERT_EQ(events, ZMQ_POLLOUT);\n}\n\nTEST(poller, poller_add_invalid_socket_throws)\n{\n zmq::context_t context;\n zmq::poller_t poller;\n zmq::socket_t a {context, zmq::socket_type::router};\n zmq::socket_t b {std::move (a)};\n ASSERT_THROW (poller.add (a, ZMQ_POLLIN, zmq::poller_t::handler_t {}),\n zmq::error_t);\n ASSERT_EQ (0u, poller.size ());\n}\n\nTEST(poller, poller_remove_invalid_socket_throws)\n{\n zmq::context_t context;\n zmq::socket_t socket {context, zmq::socket_type::router};\n zmq::poller_t poller;\n ASSERT_NO_THROW (poller.add (socket, ZMQ_POLLIN, zmq::poller_t::handler_t {}));\n ASSERT_EQ (1u, poller.size ());\n std::vector<zmq::socket_t> sockets;\n sockets.emplace_back (std::move (socket));\n ASSERT_THROW (poller.remove (socket), zmq::error_t);\n ASSERT_EQ (1u, poller.size ());\n}\n\nTEST(poller, wait_on_added_empty_handler)\n{\n server_client_setup s;\n ASSERT_NO_THROW(s.client.send(\"Hi\"));\n zmq::poller_t poller;\n std::function<void(void)> handler;\n ASSERT_NO_THROW(poller.add(s.server, ZMQ_POLLIN, handler));\n ASSERT_NO_THROW(poller.wait(std::chrono::milliseconds{-1}));\n}\n\nTEST(poller, modify_empty_throws)\n{\n zmq::context_t context;\n zmq::socket_t socket {context, zmq::socket_type::push};\n zmq::poller_t poller;\n ASSERT_THROW (poller.modify (socket, ZMQ_POLLIN), zmq::error_t);\n}\n\nTEST(poller, modify_invalid_socket_throws)\n{\n zmq::context_t context;\n zmq::socket_t a {context, zmq::socket_type::push};\n zmq::socket_t b {std::move (a)};\n zmq::poller_t poller;\n ASSERT_THROW (poller.modify (a, ZMQ_POLLIN), zmq::error_t);\n}\n\nTEST(poller, modify_not_added_throws)\n{\n zmq::context_t context;\n zmq::socket_t a {context, zmq::socket_type::push};\n zmq::socket_t b {context, zmq::socket_type::push};\n zmq::poller_t poller;\n ASSERT_NO_THROW (poller.add (a, ZMQ_POLLIN, zmq::poller_t::handler_t {}));\n ASSERT_THROW (poller.modify (b, ZMQ_POLLIN), zmq::error_t);\n}\n\nTEST(poller, modify_simple)\n{\n zmq::context_t context;\n zmq::socket_t a {context, zmq::socket_type::push};\n zmq::poller_t poller;\n ASSERT_NO_THROW (poller.add (a, ZMQ_POLLIN, zmq::poller_t::handler_t {}));\n ASSERT_NO_THROW (poller.modify (a, ZMQ_POLLIN|ZMQ_POLLOUT));\n}\n\nTEST(poller, poll_client_server)\n{\n \/\/ Setup server and client\n server_client_setup s;\n\n \/\/ Setup poller\n zmq::poller_t poller;\n ASSERT_NO_THROW(poller.add(s.server, ZMQ_POLLIN, s.handler));\n\n \/\/ client sends message\n ASSERT_NO_THROW(s.client.send(\"Hi\"));\n\n \/\/ wait for message and verify events\n ASSERT_NO_THROW(poller.wait(std::chrono::milliseconds{500}));\n ASSERT_TRUE(s.events == ZMQ_POLLIN);\n ASSERT_EQ(s.events, ZMQ_POLLIN);\n\n \/\/ Modify server socket with pollout flag\n ASSERT_NO_THROW(poller.modify(s.server, ZMQ_POLLIN | ZMQ_POLLOUT));\n ASSERT_NO_THROW(poller.wait(std::chrono::milliseconds{500}));\n ASSERT_EQ(s.events, ZMQ_POLLIN | ZMQ_POLLOUT);\n}\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/\/ The MIT License (MIT)\n\n\/\/ Copyright (c) 2016, Microsoft\n\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n\/\/ THE SOFTWARE.\n\n#include \"BitFunnel\/Allocators\/IAllocator.h\"\n#include \"BitFunnel\/IDiagnosticStream.h\"\n#include \"BitFunnel\/Index\/IIngestor.h\"\n#include \"BitFunnel\/Index\/ISimpleIndex.h\"\n#include \"BitFunnel\/Index\/IShard.h\"\n#include \"BitFunnel\/Index\/Token.h\"\n#include \"BitFunnel\/Plan\/Factories.h\"\n#include \"BitFunnel\/Plan\/QueryInstrumentation.h\"\n#include \"BitFunnel\/Plan\/TermMatchNode.h\"\n#include \"BitFunnel\/Utilities\/Factories.h\"\n#include \"BitFunnel\/Utilities\/IObjectFormatter.h\"\n#include \"ByteCodeInterpreter.h\"\n#include \"CompileNode.h\"\n#include \"IPlanRows.h\"\n#include \"MatchTreeCompiler.h\"\n#include \"MatchTreeRewriter.h\"\n#include \"QueryPlanner.h\"\n#include \"QueryResources.h\"\n#include \"RankDownCompiler.h\"\n#include \"RegisterAllocator.h\"\n#include \"RowSet.h\"\n#include \"TermPlan.h\"\n#include \"TermPlanConverter.h\"\n\n\nnamespace BitFunnel\n{\n \/\/ TODO: remove. This is a quick shortcut to try to connect QueryPlanner the\n \/\/ way SimplePlanner is connected.\n void Factories::RunQueryPlanner(TermMatchNode const & tree,\n ISimpleIndex const & index,\n QueryResources & resources,\n IDiagnosticStream & diagnosticStream,\n QueryInstrumentation & instrumentation,\n ResultsBuffer & resultsBuffer,\n bool useNativeCode)\n {\n const int c_arbitraryRowCount = 500;\n QueryPlanner planner(tree,\n c_arbitraryRowCount,\n index,\n resources,\n diagnosticStream,\n instrumentation,\n resultsBuffer,\n useNativeCode);\n }\n\n\n unsigned const c_targetCrossProductTermCount = 180;\n\n \/\/ TODO: this should take a TermPlan instead of a TermMatchNode when we have\n \/\/ scoring and query preferences.\n QueryPlanner::QueryPlanner(TermMatchNode const & tree,\n unsigned targetRowCount,\n ISimpleIndex const & index,\n QueryResources & resources,\n IDiagnosticStream & diagnosticStream,\n QueryInstrumentation & instrumentation,\n ResultsBuffer & resultsBuffer,\n bool useNativeCode)\n : m_resultsBuffer(resultsBuffer)\n {\n if (diagnosticStream.IsEnabled(\"planning\/term\"))\n {\n std::ostream& out = diagnosticStream.GetStream();\n std::unique_ptr<IObjectFormatter>\n formatter(Factories::CreateObjectFormatter(diagnosticStream.GetStream()));\n\n out << \"--------------------\" << std::endl;\n out << \"Term Plan:\" << std::endl;\n tree.Format(*formatter);\n out << std::endl;\n }\n\n RowPlan const & rowPlan =\n TermPlanConverter::BuildRowPlan(tree,\n index,\n \/\/ generateNonBodyPlan,\n resources.GetMatchTreeAllocator());\n\n if (diagnosticStream.IsEnabled(\"planning\/row\"))\n {\n std::ostream& out = diagnosticStream.GetStream();\n std::unique_ptr<IObjectFormatter>\n formatter(Factories::CreateObjectFormatter(diagnosticStream.GetStream()));\n\n out << \"--------------------\" << std::endl;\n out << \"Row Plan:\" << std::endl;\n rowPlan.Format(*formatter);\n out << std::endl;\n }\n\n m_planRows = &rowPlan.GetPlanRows();\n\n if (diagnosticStream.IsEnabled(\"planning\/planrows\"))\n {\n std::ostream& out = diagnosticStream.GetStream();\n std::unique_ptr<IObjectFormatter>\n formatter(Factories::CreateObjectFormatter(diagnosticStream.GetStream()));\n\n out << \"--------------------\" << std::endl;\n out << \"IPlanRows:\" << std::endl;\n out << \" ShardCount: \" << m_planRows->GetShardCount() << std::endl;\n for (ShardId shard = 0 ; shard < m_planRows->GetShardCount(); ++shard)\n {\n for (unsigned id = 0 ; id < m_planRows->GetRowCount(); ++id)\n {\n RowId row = m_planRows->PhysicalRow(shard, id);\n\n out\n << \" (\" << shard << \", \" << id << \"): \"\n << \"RowId(\" << \", \" << row.GetRank()\n << \", \" << row.GetIndex() << \")\" << std::endl;\n }\n }\n }\n\n \/\/ Rewrite match tree to optimal form for the RankDownCompiler.\n RowMatchNode const & rewritten =\n MatchTreeRewriter::Rewrite(rowPlan.GetMatchTree(),\n targetRowCount,\n c_targetCrossProductTermCount,\n resources.GetMatchTreeAllocator());\n\n\n if (diagnosticStream.IsEnabled(\"planning\/rewrite\"))\n {\n std::ostream& out = diagnosticStream.GetStream();\n std::unique_ptr<IObjectFormatter>\n formatter(Factories::CreateObjectFormatter(diagnosticStream.GetStream()));\n\n out << \"--------------------\" << std::endl;\n out << \"Rewritten Plan:\" << std::endl;\n rewritten.Format(*formatter);\n out << std::endl;\n }\n\n \/\/ Compile the match tree into CompileNodes.\n RankDownCompiler compiler(resources.GetMatchTreeAllocator());\n compiler.Compile(rewritten);\n const Rank initialRank = compiler.GetMaximumRank();\n CompileNode const & compileTree = compiler.CreateTree(initialRank);\n\n if (diagnosticStream.IsEnabled(\"planning\/compile\"))\n {\n std::ostream& out = diagnosticStream.GetStream();\n std::unique_ptr<IObjectFormatter>\n formatter(Factories::CreateObjectFormatter(diagnosticStream.GetStream()));\n\n out << \"--------------------\" << std::endl;\n out << \"Compile Nodes:\" << std::endl;\n compileTree.Format(*formatter);\n out << std::endl;\n }\n\n RowSet rowSet(index, *m_planRows, resources.GetMatchTreeAllocator());\n rowSet.LoadRows();\n\n if (diagnosticStream.IsEnabled(\"planning\/rowset\"))\n {\n std::ostream& out = diagnosticStream.GetStream();\n out << \"--------------------\" << std::endl;\n out << \"Row Set:\" << std::endl;\n out << \" ShardCount: \" << rowSet.GetShardCount() << std::endl;\n out << \" Row Count: \" << rowSet.GetRowCount() << std::endl;\n\n }\n\n instrumentation.SetRowCount(rowSet.GetRowCount());\n\n if (useNativeCode)\n {\n RunNativeCode(index,\n resources,\n instrumentation,\n compileTree,\n initialRank,\n rowSet);\n }\n else\n {\n RunByteCodeInterpreter(index,\n resources,\n instrumentation,\n compileTree,\n initialRank,\n rowSet);\n }\n }\n\n\n void QueryPlanner::RunByteCodeInterpreter(ISimpleIndex const & index,\n QueryResources & resources,\n QueryInstrumentation & instrumentation,\n CompileNode const & compileTree,\n Rank initialRank,\n RowSet const & rowSet)\n {\n \/\/ TODO: Clear results buffer here?\n compileTree.Compile(m_code);\n m_code.Seal();\n\n instrumentation.FinishPlanning();\n\n \/\/ Get token before we GetSliceBuffers.\n {\n auto token = index.GetIngestor().GetTokenManager().RequestToken();\n\n for (ShardId shardId = 0; shardId < index.GetIngestor().GetShardCount(); ++shardId)\n {\n auto & shard = index.GetIngestor().GetShard(shardId);\n auto & sliceBuffers = shard.GetSliceBuffers();\n\n \/\/ Iterations per slice calculation.\n auto iterationsPerSlice = shard.GetSliceCapacity() >> 6 >> initialRank;\n\n m_resultsBuffer.Reset();\n\n ByteCodeInterpreter intepreter(m_code,\n m_resultsBuffer,\n sliceBuffers.size(),\n sliceBuffers.data(),\n iterationsPerSlice,\n initialRank,\n rowSet.GetRowOffsets(shardId),\n nullptr,\n instrumentation,\n resources.GetCacheLineRecorder());\n\n intepreter.Run();\n }\n\n instrumentation.FinishMatching();\n instrumentation.SetMatchCount(m_resultsBuffer.size());\n } \/\/ End of token lifetime.\n }\n\n\n void QueryPlanner::RunNativeCode(ISimpleIndex const & index,\n QueryResources & resources,\n QueryInstrumentation & instrumentation,\n CompileNode const & compileTree,\n Rank initialRank,\n RowSet const & rowSet)\n {\n \/\/ Perform register allocation on the compile tree.\n RegisterAllocator const registers(compileTree,\n rowSet.GetRowCount(),\n c_registerBase,\n c_registerCount,\n resources.GetMatchTreeAllocator());\n\n MatchTreeCompiler compiler(resources,\n compileTree,\n registers,\n initialRank);\n\n\n \/\/ TODO: Clear results buffer here?\n compileTree.Compile(m_code);\n m_code.Seal();\n\n instrumentation.FinishPlanning();\n\n \/\/ Get token before we GetSliceBuffers.\n {\n auto token = index.GetIngestor().GetTokenManager().RequestToken();\n\n for (ShardId shardId = 0; shardId < index.GetIngestor().GetShardCount(); ++shardId)\n {\n auto & shard = index.GetIngestor().GetShard(shardId);\n auto & sliceBuffers = shard.GetSliceBuffers();\n\n \/\/ Iterations per slice calculation.\n auto iterationsPerSlice = shard.GetSliceCapacity() >> 6 >> initialRank;\n\n\n m_resultsBuffer.Reset();\n\n size_t quadwordCount = compiler.Run(sliceBuffers.size(),\n sliceBuffers.data(),\n iterationsPerSlice,\n rowSet.GetRowOffsets(shardId),\n m_resultsBuffer);\n\n instrumentation.IncrementQuadwordCount(quadwordCount);\n }\n\n instrumentation.FinishMatching();\n instrumentation.SetMatchCount(m_resultsBuffer.size());\n } \/\/ End of token lifetime.\n }\n\n\n IPlanRows const & QueryPlanner::GetPlanRows() const\n {\n return *m_planRows;\n }\n}\n<commit_msg>Avoid throwing away all but last shard's results. Fixes #380.<commit_after>\/\/ The MIT License (MIT)\n\n\/\/ Copyright (c) 2016, Microsoft\n\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n\/\/ THE SOFTWARE.\n\n#include \"BitFunnel\/Allocators\/IAllocator.h\"\n#include \"BitFunnel\/IDiagnosticStream.h\"\n#include \"BitFunnel\/Index\/IIngestor.h\"\n#include \"BitFunnel\/Index\/ISimpleIndex.h\"\n#include \"BitFunnel\/Index\/IShard.h\"\n#include \"BitFunnel\/Index\/Token.h\"\n#include \"BitFunnel\/Plan\/Factories.h\"\n#include \"BitFunnel\/Plan\/QueryInstrumentation.h\"\n#include \"BitFunnel\/Plan\/TermMatchNode.h\"\n#include \"BitFunnel\/Utilities\/Factories.h\"\n#include \"BitFunnel\/Utilities\/IObjectFormatter.h\"\n#include \"ByteCodeInterpreter.h\"\n#include \"CompileNode.h\"\n#include \"IPlanRows.h\"\n#include \"MatchTreeCompiler.h\"\n#include \"MatchTreeRewriter.h\"\n#include \"QueryPlanner.h\"\n#include \"QueryResources.h\"\n#include \"RankDownCompiler.h\"\n#include \"RegisterAllocator.h\"\n#include \"RowSet.h\"\n#include \"TermPlan.h\"\n#include \"TermPlanConverter.h\"\n\n\nnamespace BitFunnel\n{\n \/\/ TODO: remove. This is a quick shortcut to try to connect QueryPlanner the\n \/\/ way SimplePlanner is connected.\n void Factories::RunQueryPlanner(TermMatchNode const & tree,\n ISimpleIndex const & index,\n QueryResources & resources,\n IDiagnosticStream & diagnosticStream,\n QueryInstrumentation & instrumentation,\n ResultsBuffer & resultsBuffer,\n bool useNativeCode)\n {\n const int c_arbitraryRowCount = 500;\n QueryPlanner planner(tree,\n c_arbitraryRowCount,\n index,\n resources,\n diagnosticStream,\n instrumentation,\n resultsBuffer,\n useNativeCode);\n }\n\n\n unsigned const c_targetCrossProductTermCount = 180;\n\n \/\/ TODO: this should take a TermPlan instead of a TermMatchNode when we have\n \/\/ scoring and query preferences.\n QueryPlanner::QueryPlanner(TermMatchNode const & tree,\n unsigned targetRowCount,\n ISimpleIndex const & index,\n QueryResources & resources,\n IDiagnosticStream & diagnosticStream,\n QueryInstrumentation & instrumentation,\n ResultsBuffer & resultsBuffer,\n bool useNativeCode)\n : m_resultsBuffer(resultsBuffer)\n {\n if (diagnosticStream.IsEnabled(\"planning\/term\"))\n {\n std::ostream& out = diagnosticStream.GetStream();\n std::unique_ptr<IObjectFormatter>\n formatter(Factories::CreateObjectFormatter(diagnosticStream.GetStream()));\n\n out << \"--------------------\" << std::endl;\n out << \"Term Plan:\" << std::endl;\n tree.Format(*formatter);\n out << std::endl;\n }\n\n RowPlan const & rowPlan =\n TermPlanConverter::BuildRowPlan(tree,\n index,\n \/\/ generateNonBodyPlan,\n resources.GetMatchTreeAllocator());\n\n if (diagnosticStream.IsEnabled(\"planning\/row\"))\n {\n std::ostream& out = diagnosticStream.GetStream();\n std::unique_ptr<IObjectFormatter>\n formatter(Factories::CreateObjectFormatter(diagnosticStream.GetStream()));\n\n out << \"--------------------\" << std::endl;\n out << \"Row Plan:\" << std::endl;\n rowPlan.Format(*formatter);\n out << std::endl;\n }\n\n m_planRows = &rowPlan.GetPlanRows();\n\n if (diagnosticStream.IsEnabled(\"planning\/planrows\"))\n {\n std::ostream& out = diagnosticStream.GetStream();\n std::unique_ptr<IObjectFormatter>\n formatter(Factories::CreateObjectFormatter(diagnosticStream.GetStream()));\n\n out << \"--------------------\" << std::endl;\n out << \"IPlanRows:\" << std::endl;\n out << \" ShardCount: \" << m_planRows->GetShardCount() << std::endl;\n for (ShardId shard = 0 ; shard < m_planRows->GetShardCount(); ++shard)\n {\n for (unsigned id = 0 ; id < m_planRows->GetRowCount(); ++id)\n {\n RowId row = m_planRows->PhysicalRow(shard, id);\n\n out\n << \" (\" << shard << \", \" << id << \"): \"\n << \"RowId(\" << \", \" << row.GetRank()\n << \", \" << row.GetIndex() << \")\" << std::endl;\n }\n }\n }\n\n \/\/ Rewrite match tree to optimal form for the RankDownCompiler.\n RowMatchNode const & rewritten =\n MatchTreeRewriter::Rewrite(rowPlan.GetMatchTree(),\n targetRowCount,\n c_targetCrossProductTermCount,\n resources.GetMatchTreeAllocator());\n\n\n if (diagnosticStream.IsEnabled(\"planning\/rewrite\"))\n {\n std::ostream& out = diagnosticStream.GetStream();\n std::unique_ptr<IObjectFormatter>\n formatter(Factories::CreateObjectFormatter(diagnosticStream.GetStream()));\n\n out << \"--------------------\" << std::endl;\n out << \"Rewritten Plan:\" << std::endl;\n rewritten.Format(*formatter);\n out << std::endl;\n }\n\n \/\/ Compile the match tree into CompileNodes.\n RankDownCompiler compiler(resources.GetMatchTreeAllocator());\n compiler.Compile(rewritten);\n const Rank initialRank = compiler.GetMaximumRank();\n CompileNode const & compileTree = compiler.CreateTree(initialRank);\n\n if (diagnosticStream.IsEnabled(\"planning\/compile\"))\n {\n std::ostream& out = diagnosticStream.GetStream();\n std::unique_ptr<IObjectFormatter>\n formatter(Factories::CreateObjectFormatter(diagnosticStream.GetStream()));\n\n out << \"--------------------\" << std::endl;\n out << \"Compile Nodes:\" << std::endl;\n compileTree.Format(*formatter);\n out << std::endl;\n }\n\n RowSet rowSet(index, *m_planRows, resources.GetMatchTreeAllocator());\n rowSet.LoadRows();\n\n if (diagnosticStream.IsEnabled(\"planning\/rowset\"))\n {\n std::ostream& out = diagnosticStream.GetStream();\n out << \"--------------------\" << std::endl;\n out << \"Row Set:\" << std::endl;\n out << \" ShardCount: \" << rowSet.GetShardCount() << std::endl;\n out << \" Row Count: \" << rowSet.GetRowCount() << std::endl;\n\n }\n\n instrumentation.SetRowCount(rowSet.GetRowCount());\n\n if (useNativeCode)\n {\n RunNativeCode(index,\n resources,\n instrumentation,\n compileTree,\n initialRank,\n rowSet);\n }\n else\n {\n RunByteCodeInterpreter(index,\n resources,\n instrumentation,\n compileTree,\n initialRank,\n rowSet);\n }\n }\n\n\n void QueryPlanner::RunByteCodeInterpreter(ISimpleIndex const & index,\n QueryResources & resources,\n QueryInstrumentation & instrumentation,\n CompileNode const & compileTree,\n Rank initialRank,\n RowSet const & rowSet)\n {\n \/\/ TODO: Clear results buffer here?\n compileTree.Compile(m_code);\n m_code.Seal();\n\n instrumentation.FinishPlanning();\n m_resultsBuffer.Reset();\n\n \/\/ Get token before we GetSliceBuffers.\n {\n auto token = index.GetIngestor().GetTokenManager().RequestToken();\n\n for (ShardId shardId = 0; shardId < index.GetIngestor().GetShardCount(); ++shardId)\n {\n auto & shard = index.GetIngestor().GetShard(shardId);\n auto & sliceBuffers = shard.GetSliceBuffers();\n\n \/\/ Iterations per slice calculation.\n auto iterationsPerSlice = shard.GetSliceCapacity() >> 6 >> initialRank;\n\n ByteCodeInterpreter intepreter(m_code,\n m_resultsBuffer,\n sliceBuffers.size(),\n sliceBuffers.data(),\n iterationsPerSlice,\n initialRank,\n rowSet.GetRowOffsets(shardId),\n nullptr,\n instrumentation,\n resources.GetCacheLineRecorder());\n\n intepreter.Run();\n }\n\n instrumentation.FinishMatching();\n instrumentation.SetMatchCount(m_resultsBuffer.size());\n } \/\/ End of token lifetime.\n }\n\n\n void QueryPlanner::RunNativeCode(ISimpleIndex const & index,\n QueryResources & resources,\n QueryInstrumentation & instrumentation,\n CompileNode const & compileTree,\n Rank initialRank,\n RowSet const & rowSet)\n {\n \/\/ Perform register allocation on the compile tree.\n RegisterAllocator const registers(compileTree,\n rowSet.GetRowCount(),\n c_registerBase,\n c_registerCount,\n resources.GetMatchTreeAllocator());\n\n MatchTreeCompiler compiler(resources,\n compileTree,\n registers,\n initialRank);\n\n\n \/\/ TODO: Clear results buffer here?\n compileTree.Compile(m_code);\n m_code.Seal();\n\n instrumentation.FinishPlanning();\n\n m_resultsBuffer.Reset();\n\n \/\/ Get token before we GetSliceBuffers.\n {\n auto token = index.GetIngestor().GetTokenManager().RequestToken();\n\n for (ShardId shardId = 0; shardId < index.GetIngestor().GetShardCount(); ++shardId)\n {\n auto & shard = index.GetIngestor().GetShard(shardId);\n auto & sliceBuffers = shard.GetSliceBuffers();\n\n \/\/ Iterations per slice calculation.\n auto iterationsPerSlice = shard.GetSliceCapacity() >> 6 >> initialRank;\n\n\n size_t quadwordCount = compiler.Run(sliceBuffers.size(),\n sliceBuffers.data(),\n iterationsPerSlice,\n rowSet.GetRowOffsets(shardId),\n m_resultsBuffer);\n\n instrumentation.IncrementQuadwordCount(quadwordCount);\n }\n\n instrumentation.FinishMatching();\n instrumentation.SetMatchCount(m_resultsBuffer.size());\n } \/\/ End of token lifetime.\n }\n\n\n IPlanRows const & QueryPlanner::GetPlanRows() const\n {\n return *m_planRows;\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2013 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"base\/command_line.h\"\n#include \"base\/strings\/stringprintf.h\"\n#include \"chrome\/browser\/media\/webrtc_browsertest_base.h\"\n#include \"chrome\/browser\/media\/webrtc_browsertest_common.h\"\n#include \"chrome\/browser\/ui\/browser.h\"\n#include \"chrome\/browser\/ui\/browser_tabstrip.h\"\n#include \"chrome\/browser\/ui\/tabs\/tab_strip_model.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/test\/base\/in_process_browser_test.h\"\n#include \"chrome\/test\/base\/ui_test_utils.h\"\n#include \"content\/public\/test\/browser_test_utils.h\"\n#include \"media\/base\/media_switches.h\"\n#include \"net\/test\/embedded_test_server\/embedded_test_server.h\"\n\nstatic const char kMainWebrtcTestHtmlPage[] =\n \"\/webrtc\/webrtc_jsep01_test.html\";\n\n\/\/ Top-level integration test for WebRTC. It always uses fake devices; see\n\/\/ WebRtcWebcamBrowserTest for a test that acquires any real webcam on the\n\/\/ system.\nclass WebRtcBrowserTest : public WebRtcTestBase {\n public:\n void SetUpInProcessBrowserTestFixture() override {\n DetectErrorsInJavaScript(); \/\/ Look for errors in our rather complex js.\n }\n\n void SetUpCommandLine(base::CommandLine* command_line) override {\n \/\/ Ensure the infobar is enabled, since we expect that in this test.\n EXPECT_FALSE(command_line->HasSwitch(switches::kUseFakeUIForMediaStream));\n\n \/\/ Always use fake devices.\n command_line->AppendSwitch(switches::kUseFakeDeviceForMediaStream);\n\n \/\/ Flag used by TestWebAudioMediaStream to force garbage collection.\n command_line->AppendSwitchASCII(switches::kJavaScriptFlags, \"--expose-gc\");\n }\n};\n\n\/\/ Flaky on ChromeOS (?), Windows: http:\/\/crbug.com\/443542.\n#if defined(OS_CHROMEOS) || defined(OS_WIN)\n#define MAYBE_RunsAudioVideoWebRTCCallInTwoTabs \\\n DISABLED_RunsAudioVideoWebRTCCallInTwoTabs\n#else\n#define MAYBE_RunsAudioVideoWebRTCCallInTwoTabs \\\n RunsAudioVideoWebRTCCallInTwoTabs\n#endif\nIN_PROC_BROWSER_TEST_F(WebRtcBrowserTest,\n MAYBE_RunsAudioVideoWebRTCCallInTwoTabs) {\n if (OnWinXp()) return;\n\n ASSERT_TRUE(embedded_test_server()->InitializeAndWaitUntilReady());\n\n content::WebContents* left_tab =\n OpenTestPageAndGetUserMediaInNewTab(kMainWebrtcTestHtmlPage);\n content::WebContents* right_tab =\n OpenTestPageAndGetUserMediaInNewTab(kMainWebrtcTestHtmlPage);\n\n SetupPeerconnectionWithLocalStream(left_tab);\n SetupPeerconnectionWithLocalStream(right_tab);\n\n NegotiateCall(left_tab, right_tab);\n\n StartDetectingVideo(left_tab, \"remote-view\");\n StartDetectingVideo(right_tab, \"remote-view\");\n\n#if !defined(OS_MACOSX)\n \/\/ Video is choppy on Mac OS X. http:\/\/crbug.com\/443542.\n WaitForVideoToPlay(left_tab);\n WaitForVideoToPlay(right_tab);\n#endif\n\n HangUp(left_tab);\n HangUp(right_tab);\n}\n\nIN_PROC_BROWSER_TEST_F(WebRtcBrowserTest, TestWebAudioMediaStream) {\n \/\/ This tests against crash regressions for the WebAudio-MediaStream\n \/\/ integration.\n if (OnWinXp()) return;\n\n ASSERT_TRUE(embedded_test_server()->InitializeAndWaitUntilReady());\n GURL url(embedded_test_server()->GetURL(\"\/webrtc\/webaudio_crash.html\"));\n ui_test_utils::NavigateToURL(browser(), url);\n content::WebContents* tab =\n browser()->tab_strip_model()->GetActiveWebContents();\n\n \/\/ A sleep is necessary to be able to detect the crash.\n test::SleepInJavascript(tab, 1000);\n\n ASSERT_FALSE(tab->IsCrashed());\n}\n<commit_msg>Trying to re-enable WebRTC browser test on win and CrOS.<commit_after>\/\/ Copyright 2013 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"base\/command_line.h\"\n#include \"base\/strings\/stringprintf.h\"\n#include \"chrome\/browser\/media\/webrtc_browsertest_base.h\"\n#include \"chrome\/browser\/media\/webrtc_browsertest_common.h\"\n#include \"chrome\/browser\/ui\/browser.h\"\n#include \"chrome\/browser\/ui\/browser_tabstrip.h\"\n#include \"chrome\/browser\/ui\/tabs\/tab_strip_model.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/test\/base\/in_process_browser_test.h\"\n#include \"chrome\/test\/base\/ui_test_utils.h\"\n#include \"content\/public\/test\/browser_test_utils.h\"\n#include \"media\/base\/media_switches.h\"\n#include \"net\/test\/embedded_test_server\/embedded_test_server.h\"\n\nstatic const char kMainWebrtcTestHtmlPage[] =\n \"\/webrtc\/webrtc_jsep01_test.html\";\n\n\/\/ Top-level integration test for WebRTC. It always uses fake devices; see\n\/\/ WebRtcWebcamBrowserTest for a test that acquires any real webcam on the\n\/\/ system.\nclass WebRtcBrowserTest : public WebRtcTestBase {\n public:\n void SetUpInProcessBrowserTestFixture() override {\n DetectErrorsInJavaScript(); \/\/ Look for errors in our rather complex js.\n }\n\n void SetUpCommandLine(base::CommandLine* command_line) override {\n \/\/ Ensure the infobar is enabled, since we expect that in this test.\n EXPECT_FALSE(command_line->HasSwitch(switches::kUseFakeUIForMediaStream));\n\n \/\/ Always use fake devices.\n command_line->AppendSwitch(switches::kUseFakeDeviceForMediaStream);\n\n \/\/ Flag used by TestWebAudioMediaStream to force garbage collection.\n command_line->AppendSwitchASCII(switches::kJavaScriptFlags, \"--expose-gc\");\n }\n};\n\nIN_PROC_BROWSER_TEST_F(WebRtcBrowserTest,\n RunsAudioVideoWebRTCCallInTwoTabs) {\n if (OnWinXp()) return;\n\n ASSERT_TRUE(embedded_test_server()->InitializeAndWaitUntilReady());\n\n content::WebContents* left_tab =\n OpenTestPageAndGetUserMediaInNewTab(kMainWebrtcTestHtmlPage);\n content::WebContents* right_tab =\n OpenTestPageAndGetUserMediaInNewTab(kMainWebrtcTestHtmlPage);\n\n SetupPeerconnectionWithLocalStream(left_tab);\n SetupPeerconnectionWithLocalStream(right_tab);\n\n NegotiateCall(left_tab, right_tab);\n\n StartDetectingVideo(left_tab, \"remote-view\");\n StartDetectingVideo(right_tab, \"remote-view\");\n\n#if !defined(OS_MACOSX)\n \/\/ Video is choppy on Mac OS X. http:\/\/crbug.com\/443542.\n WaitForVideoToPlay(left_tab);\n WaitForVideoToPlay(right_tab);\n#endif\n\n HangUp(left_tab);\n HangUp(right_tab);\n}\n\nIN_PROC_BROWSER_TEST_F(WebRtcBrowserTest, TestWebAudioMediaStream) {\n \/\/ This tests against crash regressions for the WebAudio-MediaStream\n \/\/ integration.\n if (OnWinXp()) return;\n\n ASSERT_TRUE(embedded_test_server()->InitializeAndWaitUntilReady());\n GURL url(embedded_test_server()->GetURL(\"\/webrtc\/webaudio_crash.html\"));\n ui_test_utils::NavigateToURL(browser(), url);\n content::WebContents* tab =\n browser()->tab_strip_model()->GetActiveWebContents();\n\n \/\/ A sleep is necessary to be able to detect the crash.\n test::SleepInJavascript(tab, 1000);\n\n ASSERT_FALSE(tab->IsCrashed());\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"FoundationModel.h\"\n#include <iomanip> \/\/ Included this to create tables - debugging\n\nnamespace voom {\n\n \/\/ Constructor\n FoundationModel::FoundationModel(Mesh* aMesh, const uint NodeDoF, const string SpNodes, Real SpringK):\n Model(aMesh, NodeDoF), _springK(SpringK)\n {\n _field.resize( (_myMesh->getNumberOfNodes() )*_nodeDoF );\n this->initializeField();\n this->initSpringBC(SpNodes);\n }\n\n \/\/ Compute Function - Compute Energy, Force, Stiffness\n void FoundationModel::compute(Result * R)\n {\n const vector<GeomElement* > elements = _myMesh->getElements();\n const int AvgNodePerEl = ((elements[0])->getNodesID()).size();\n const int NumEl = elements.size();\n const int dim = _myMesh->getDimension();\n vector<Triplet<Real > > KtripletList;\n\n int PbDoF = R->getPbDoF();\n\n \/\/ Reset values in result struct\n \/\/ Todo: Once we have the wrapper, we won't want to do this\n if ( R->getRequest() & ENERGY ) {\n R->setEnergy(0.0);\n }\n if ( R->getRequest() & FORCE) {\n R->resetResidualToZero();\n }\n if ( R->getRequest() & STIFFNESS ) {\n \/\/ R->resetStiffnessToZero();\n KtripletList.reserve(dim*dim*NumEl*AvgNodePerEl*AvgNodePerEl);\n }\n\n \/\/ Loop through nodes\n MechanicsMaterial::FKresults FKres;\n FKres.request = R->getRequest();\n\n \/\/** Insert stuff from the spring here **\/\/\n vector <Triplet<Real > > KtripletList_FromSpring;\n\n \/\/ Loop through _spNodes\n for(int n = 0; n < _spNodes.size(); n++)\n {\n int NodeID = _spNodes[n];\n Vector3d xa_prev, xa_curr;\n xa_prev << _prevField[NodeID*3], _prevField[NodeID*3+1], _prevField[NodeID*3+2];\n xa_curr << _field[NodeID*3], _field[NodeID*3+1], _field[NodeID*3+2];\n\n \/\/ Compute energy\n if (R->getRequest() & ENERGY) {\n R->addEnergy( 0.5* _springK*pow( (xa_curr - xa_prev).dot(_spNormals[n]), 2.0) );\n }\n\n \/\/ Compute Residual\n if ((R->getRequest() & FORCE)) {\n for(uint i = 0; i < 3; i++) {\n R->addResidual(NodeID*3+i, _springK*_spNormals[n](i)*(xa_curr - xa_prev).dot(_spNormals[n]) );\n } \/\/ i loop\n } \/\/ Internal force loop\n\n \/\/ Compute stiffness matrix\n if ( R->getRequest() & STIFFNESS ) {\n for(uint i = 0; i < 3; i++) {\n for(uint j = 0; j < 3; j++) {\n KtripletList_FromSpring.push_back(Triplet<Real >( NodeID*3+i, NodeID*3+j, _springK*_spNormals[n](i)*_spNormals[n](j) ));\n } \/\/ j loop\n } \/\/ i loop\n KtripletList.insert( KtripletList.end(), KtripletList_FromSpring.begin(), KtripletList_FromSpring.end() );\n R->setStiffnessFromTriplets(KtripletList);\n R->FinalizeGlobalStiffnessAssembly();\n } \/\/ Stiffness loop\n } \/\/ Spring nodes loop\n } \/\/ Compute Mechanics Model\n\n\n void FoundationModel::computeNormals() {\n\n \/\/ First compute normal of any element in _myMesh\n const vector<GeomElement* > elements = _myMesh->getElements();\n\n vector<Vector3d > ElNormals(elements.size(), Vector3d::Zero());\n\n \/\/ Loop over elements\n for(int e = 0; e < elements.size(); e++)\n {\n GeomElement* geomEl = elements[e];\n const vector<int >& NodesID = geomEl->getNodesID();\n const int numQP = geomEl->getNumberOfQuadPoints();\n const int numNodes = NodesID.size();\n\n \/\/ Loop over quadrature points\n for(int q = 0; q < numQP; q++) {\n\n \/\/ Compute normal based on _prevField\n Vector3d a1 = Vector3d::Zero(), a2 = Vector3d::Zero(), a3 = Vector3d::Zero();\n for (int a = 0; a < NodesID.size(); a++) {\n int nodeID = NodesID[a];\n Vector3d xa_prev;\n xa_prev << _prevField[nodeID*3], _prevField[nodeID*3+1], _prevField[nodeID*3+2];\n a1 += xa_prev*geomEl->getDN(q, a, 0);\n a2 += xa_prev*geomEl->getDN(q, a, 1);\n }\n ElNormals[e] += a1.cross(a2); \/\/ Not normalized with respect to area (elements with larger area count more)\n } \/\/ loop over QP\n\n } \/\/ loop over elements\n\n \/\/ loop over _spNodes\n for (int n = 0; n < _spNodes.size(); n++) {\n \/\/ Reset normal to zero\n _spNormals[n] = Vector3d::Zero();\n \/\/ Loop over all elements sharing that node\n for (int m = 0; m < _spNodesToEle[n].size(); m++) {\n _spNormals[n] += ElNormals[_spNodesToEle[n][m]];\n }\n Real normFactor = 1.0\/_spNormals[n].norm();\n _spNormals[n] *= normFactor;\n }\n\n } \/\/ compute Normals\n\n\n\n void FoundationModel::initSpringBC(const string SpNodes) {\n \/\/ Store node number on the outer surface\n ifstream inp(SpNodes.c_str());\n int nodeNum = 0;\n while (inp >> nodeNum)\n _spNodes.push_back(nodeNum);\n\n \/\/ Collect elements that share a node in _spNodes\n const vector<GeomElement* > elements = _myMesh->getElements();\n\n for (int n = 0; n < _spNodes.size(); n++) {\n vector<int > connected;\n for(int e = 0; e < elements.size(); e++) {\n const vector<int >& NodesID = elements[e]->getNodesID();\n for (int m = 0; m < NodesID.size(); m++) {\n if (NodesID[m] == _spNodes[n]) {\n connected.push_back(e);\n break;\n } \/\/ check if node belong to element\n } \/\/ loop over nodes of the element\n } \/\/ loop over elements\n _spNodesToEle.push_back(connected);\n\n } \/\/ loop over _spNodes\n\n _spNormals.resize(_spNodes.size(), Vector3d::Zero());\n \/\/ Compute initial node normals\n this->computeNormals();\n\n } \/\/ InitSpringBC\n\n\n \/\/ Writing output\n void FoundationModel::writeOutputVTK(const string OutputFile, int step) {\n\n cout << \"Step \" << step << \" Output:\" << endl;\n cout << left << setw(8) << setfill(' ') << \"Node\";\n cout << left << setw(8) << setfill(' ') << \"Pos X\";\n cout << left << setw(8) << setfill(' ') << \"Pos Y\";\n cout << left << setw(8) << setfill(' ') << \"Pos Z\" << endl;\n\n for (int i = 0; i < _myMesh->getNumberOfNodes(); i++) {\n cout << left << setw(8) << setfill(' ') << i;\n cout << left << setw(8) << setfill(' ') << _myMesh->getX(i)(0);\n cout << left << setw(8) << setfill(' ') << _myMesh->getX(i)(1);\n cout << left << setw(8) << setfill(' ') << _myMesh->getX(i)(2) << endl;\n }\n\n } \/\/ writeOutput\n\n} \/\/ namespace voom\n<commit_msg>Changes to FoundationModel.cc Output<commit_after>#include \"FoundationModel.h\"\n#include <iomanip> \/\/ Included this to create tables - debugging\n\nnamespace voom {\n\n \/\/ Constructor\n FoundationModel::FoundationModel(Mesh* aMesh, const uint NodeDoF, const string SpNodes, Real SpringK):\n Model(aMesh, NodeDoF), _springK(SpringK)\n {\n _field.resize( (_myMesh->getNumberOfNodes() )*_nodeDoF );\n this->initializeField();\n this->initSpringBC(SpNodes);\n }\n\n \/\/ Compute Function - Compute Energy, Force, Stiffness\n void FoundationModel::compute(Result * R)\n {\n const vector<GeomElement* > elements = _myMesh->getElements();\n const int AvgNodePerEl = ((elements[0])->getNodesID()).size();\n const int NumEl = elements.size();\n const int dim = _myMesh->getDimension();\n vector<Triplet<Real > > KtripletList;\n\n int PbDoF = R->getPbDoF();\n\n \/\/ Reset values in result struct\n \/\/ Todo: Once we have the wrapper, we won't want to do this\n if ( R->getRequest() & ENERGY ) {\n R->setEnergy(0.0);\n }\n if ( R->getRequest() & FORCE) {\n R->resetResidualToZero();\n }\n if ( R->getRequest() & STIFFNESS ) {\n \/\/ R->resetStiffnessToZero();\n KtripletList.reserve(dim*dim*NumEl*AvgNodePerEl*AvgNodePerEl);\n }\n\n \/\/ Loop through nodes\n MechanicsMaterial::FKresults FKres;\n FKres.request = R->getRequest();\n\n \/\/** Insert stuff from the spring here **\/\/\n vector <Triplet<Real > > KtripletList_FromSpring;\n\n \/\/ Loop through _spNodes\n for(int n = 0; n < _spNodes.size(); n++)\n {\n int NodeID = _spNodes[n];\n Vector3d xa_prev, xa_curr;\n xa_prev << _prevField[NodeID*3], _prevField[NodeID*3+1], _prevField[NodeID*3+2];\n xa_curr << _field[NodeID*3], _field[NodeID*3+1], _field[NodeID*3+2];\n\n \/\/ Compute energy\n if (R->getRequest() & ENERGY) {\n R->addEnergy( 0.5* _springK*pow( (xa_curr - xa_prev).dot(_spNormals[n]), 2.0) );\n }\n\n \/\/ Compute Residual\n if ((R->getRequest() & FORCE)) {\n for(uint i = 0; i < 3; i++) {\n R->addResidual(NodeID*3+i, _springK*_spNormals[n](i)*(xa_curr - xa_prev).dot(_spNormals[n]) );\n } \/\/ i loop\n } \/\/ Internal force loop\n\n \/\/ Compute stiffness matrix\n if ( R->getRequest() & STIFFNESS ) {\n for(uint i = 0; i < 3; i++) {\n for(uint j = 0; j < 3; j++) {\n KtripletList_FromSpring.push_back(Triplet<Real >( NodeID*3+i, NodeID*3+j, _springK*_spNormals[n](i)*_spNormals[n](j) ));\n } \/\/ j loop\n } \/\/ i loop\n KtripletList.insert( KtripletList.end(), KtripletList_FromSpring.begin(), KtripletList_FromSpring.end() );\n R->setStiffnessFromTriplets(KtripletList);\n R->FinalizeGlobalStiffnessAssembly();\n } \/\/ Stiffness loop\n } \/\/ Spring nodes loop\n } \/\/ Compute Mechanics Model\n\n\n void FoundationModel::computeNormals() {\n\n \/\/ First compute normal of any element in _myMesh\n const vector<GeomElement* > elements = _myMesh->getElements();\n\n vector<Vector3d > ElNormals(elements.size(), Vector3d::Zero());\n\n \/\/ Loop over elements\n for(int e = 0; e < elements.size(); e++)\n {\n GeomElement* geomEl = elements[e];\n const vector<int >& NodesID = geomEl->getNodesID();\n const int numQP = geomEl->getNumberOfQuadPoints();\n const int numNodes = NodesID.size();\n\n \/\/ Loop over quadrature points\n for(int q = 0; q < numQP; q++) {\n\n \/\/ Compute normal based on _prevField\n Vector3d a1 = Vector3d::Zero(), a2 = Vector3d::Zero(), a3 = Vector3d::Zero();\n for (int a = 0; a < NodesID.size(); a++) {\n int nodeID = NodesID[a];\n Vector3d xa_prev;\n xa_prev << _prevField[nodeID*3], _prevField[nodeID*3+1], _prevField[nodeID*3+2];\n a1 += xa_prev*geomEl->getDN(q, a, 0);\n a2 += xa_prev*geomEl->getDN(q, a, 1);\n }\n ElNormals[e] += a1.cross(a2); \/\/ Not normalized with respect to area (elements with larger area count more)\n } \/\/ loop over QP\n\n } \/\/ loop over elements\n\n \/\/ loop over _spNodes\n for (int n = 0; n < _spNodes.size(); n++) {\n \/\/ Reset normal to zero\n _spNormals[n] = Vector3d::Zero();\n \/\/ Loop over all elements sharing that node\n for (int m = 0; m < _spNodesToEle[n].size(); m++) {\n _spNormals[n] += ElNormals[_spNodesToEle[n][m]];\n }\n Real normFactor = 1.0\/_spNormals[n].norm();\n _spNormals[n] *= normFactor;\n }\n\n } \/\/ compute Normals\n\n\n\n void FoundationModel::initSpringBC(const string SpNodes) {\n \/\/ Store node number on the outer surface\n ifstream inp(SpNodes.c_str());\n int nodeNum = 0;\n while (inp >> nodeNum)\n _spNodes.push_back(nodeNum);\n\n \/\/ Collect elements that share a node in _spNodes\n const vector<GeomElement* > elements = _myMesh->getElements();\n\n for (int n = 0; n < _spNodes.size(); n++) {\n vector<int > connected;\n for(int e = 0; e < elements.size(); e++) {\n const vector<int >& NodesID = elements[e]->getNodesID();\n for (int m = 0; m < NodesID.size(); m++) {\n if (NodesID[m] == _spNodes[n]) {\n connected.push_back(e);\n break;\n } \/\/ check if node belong to element\n } \/\/ loop over nodes of the element\n } \/\/ loop over elements\n _spNodesToEle.push_back(connected);\n\n } \/\/ loop over _spNodes\n\n _spNormals.resize(_spNodes.size(), Vector3d::Zero());\n \/\/ Compute initial node normals\n this->computeNormals();\n\n } \/\/ InitSpringBC\n\n\n \/\/ Writing output\n void FoundationModel::writeOutputVTK(const string OutputFile, int step) {\n\n cout << \"Step \" << step << \" Output:\" << endl;\n cout << left << setw(8) << setfill(' ') << \"Node\";\n cout << left << setw(8) << setfill(' ') << \"Pos X\";\n cout << left << setw(8) << setfill(' ') << \"Pos Y\";\n if (_nodeDoF > 2)\n cout << left << setw(8) << setfill(' ') << \"Pos Z\" << endl;\n else\n cout << endl;\n\n for (int i = 0; i < _myMesh->getNumberOfNodes(); i++) {\n cout << left << setw(8) << setfill(' ') << i;\n cout << left << setw(8) << setfill(' ') << _myMesh->getX(i)(0);\n cout << left << setw(8) << setfill(' ') << _myMesh->getX(i)(1);\n if (_nodeDoF > 2)\n cout << left << setw(8) << setfill(' ') << _myMesh->getX(i)(2) << endl;\n else\n cout << endl;\n }\n\n } \/\/ writeOutput\n\n} \/\/ namespace voom\n<|endoftext|>"} {"text":"<commit_before>\/\/functor_overload header\n\/\/Copyright (c) 2014 mmYYmmdd\n\n#include \"functor_overload.hpp\"\n\ntemplate <typename T>\n struct is_Numeric {\n static const bool value = std::is_integral<typename std::remove_reference<T>::type>::value ||\n std::is_floating_point<typename std::remove_reference<T>::type>::value;\n};\n\ntemplate <typename T>\n struct is_Pointer {\n static const bool value = std::is_pointer<typename std::remove_reference<T>::type>::value;\n};\n\nstruct Plus {\n template <typename T>\n auto operator()(T a, T b) const\n { return a + b; }\n template <typename T>\n auto operator()(T* a, T* b) const\n { return *a + *b; }\n};\n\nstruct Minus {\n template <typename T>\n auto operator()(T a, T b) const\n { return a - b; }\n template <typename T>\n auto operator()(T* a, T* b) const\n { return *a - *b; }\n};\n\n#include <iostream>\n\nint main()\n{\n using namespace mymd;\n std::cout << \"\/\/数値/ポインタに対する計算をオーバーロードする人工的な例\" << std::endl;\n std::cout << \"\/\/ふたつのファンクタのシグネチャは同一。それを意識的に選択する。\" << std::endl;\n auto mm = gen<cond<is_Numeric>, cond<is_Numeric>>(Plus{} ) + \n gen<cond<is_Pointer>, cond<is_Pointer>>(Minus{}) ;\n int i = 4, j = 5;\n double a = 3.676, b = 8.3212;\n std::cout << mm(i, j) << std::endl;\n std::cout << mm(a, b+0.0) << std::endl;\n std::cout << mm(&i, &j) << std::endl;\n std::cout << mm(&a, &b) << std::endl;\n} \n<commit_msg>sample for functor overload(gen) のサンプル<commit_after>\/\/functor_overload header\n\/\/Copyright (c) 2014 mmYYmmdd\n\n#include \"functor_overload.hpp\"\n\ntemplate <typename T>\n struct is_Numeric {\n static const bool value = std::is_integral<typename std::remove_reference<T>::type>::value ||\n std::is_floating_point<typename std::remove_reference<T>::type>::value;\n};\n\ntemplate <typename T>\n struct is_Pointer {\n static const bool value = std::is_pointer<typename std::remove_reference<T>::type>::value;\n};\n\nstruct Plus {\n template <typename T>\n auto operator()(T a, T b) const\n { return a + b; }\n template <typename T>\n auto operator()(T* a, T* b) const\n { return *a + *b; }\n};\n\nstruct Minus {\n template <typename T>\n auto operator()(T a, T b) const\n { return a - b; }\n template <typename T>\n auto operator()(T* a, T* b) const\n { return *a - *b; }\n};\n\n#include <iostream>\n\nint main()\n{\n using namespace mymd;\n std::cout << \"\/\/ sample for overload the calculation of numerics and of pointers\" << std::endl;\n std::cout << \"\/\/ sets of signatures of two functors are same, \" << std::endl;\n std::cout << \"\/\/ and choice the members to use from them \" << std::endl;\n std::cout << \"\/\/数値/ポインタに対する計算をオーバーロードする人工的な例\" << std::endl;\n std::cout << \"\/\/ふたつのファンクタのシグネチャは同一。それを意識的に選択する。\" << std::endl;\n auto mm = gen<cond<is_Numeric>, cond<is_Numeric>>(Plus{} ) + \n gen<cond<is_Pointer>, cond<is_Pointer>>(Minus{}) ;\n int i = 4, j = 5;\n double a = 3.676, b = 8.3212;\n std::cout << mm(i, j) << std::endl;\n std::cout << mm(a, b+0.0) << std::endl;\n std::cout << mm(&i, &j) << std::endl;\n std::cout << mm(&a, &b) << std::endl;\n} \n<|endoftext|>"} {"text":"<commit_before>\/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- *\/\n\/*\n * This file is part of the LibreOffice project.\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\n * This file incorporates work covered by the following license notice:\n *\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed\n * with this work for additional information regarding copyright\n * ownership. The ASF licenses this file to you under the Apache\n * License, Version 2.0 (the \"License\"); you may not use this file\n * except in compliance with the License. You may obtain a copy of\n * the License at http:\/\/www.apache.org\/licenses\/LICENSE-2.0 .\n *\/\n\n#include <rtl\/ref.hxx>\n#include <cppuhelper\/implbase2.hxx>\n#include <cppuhelper\/factory.hxx>\n#include <cppuhelper\/implementationentry.hxx>\n#include <cppuhelper\/supportsservice.hxx>\n\n#include <com\/sun\/star\/lang\/XServiceInfo.hpp>\n#include <com\/sun\/star\/accessibility\/XMSAAService.hpp>\n#include <com\/sun\/star\/accessibility\/AccessibleRole.hpp>\n\n#include <com\/sun\/star\/awt\/XExtendedToolkit.hpp>\n#include <vcl\/svapp.hxx>\n#include <vcl\/window.hxx>\n\n#include <prewin.h>\n#include <postwin.h>\n\nusing namespace ::com::sun::star; \/\/ for odk interfaces\nusing namespace ::com::sun::star::uno; \/\/ for basic types\nusing namespace ::com::sun::star::accessibility;\n\nusing namespace ::com::sun::star::awt;\n\n#include \"AccTopWindowListener.hxx\"\n\nnamespace my_sc_impl\n{\n\nstatic Sequence< OUString > getSupportedServiceNames_MSAAServiceImpl()\n{\n Sequence< OUString > seqNames(1);\n seqNames.getArray()[0] = \"com.sun.star.accessibility.MSAAService\";\n return seqNames;\n}\n\nstatic OUString getImplementationName_MSAAServiceImpl()\n{\n return OUString( \"com.sun.star.accessibility.my_sc_implementation.MSAAService\" );\n}\n\nclass MSAAServiceImpl : public ::cppu::WeakImplHelper2<\n XMSAAService, lang::XServiceInfo >\n{\nprivate:\n rtl::Reference<AccTopWindowListener> m_pTopWindowListener;\n\npublic:\n MSAAServiceImpl ();\n virtual ~MSAAServiceImpl();\n\n \/\/ XComponent - as used by VCL to lifecycle manage this bridge.\n virtual void SAL_CALL dispose();\n virtual void SAL_CALL addEventListener( const css::uno::Reference< css::lang::XEventListener >& ) { \/* dummy *\/ }\n virtual void SAL_CALL removeEventListener( const css::uno::Reference< css::lang::XEventListener >& ) { \/* dummy *\/ }\n\n \/\/ XMSAAService\n virtual sal_Int64 SAL_CALL getAccObjectPtr(\n sal_Int64 hWnd, sal_Int64 lParam, sal_Int64 wParam);\n virtual void SAL_CALL handleWindowOpened(sal_Int64);\n\n \/\/ XServiceInfo\n virtual OUString SAL_CALL getImplementationName();\n virtual sal_Bool SAL_CALL supportsService( OUString const & serviceName );\n virtual Sequence< OUString > SAL_CALL getSupportedServiceNames();\n};\n\n\/**\n * Implemention of getAccObjectPtr.\n * @param\n * @return Com interface.\n *\/\nsal_Int64 MSAAServiceImpl::getAccObjectPtr(\n sal_Int64 hWnd, sal_Int64 lParam, sal_Int64 wParam)\nthrow (RuntimeException)\n{\n SolarMutexGuard g;\n\n if (!m_pTopWindowListener.is())\n {\n return 0;\n }\n return m_pTopWindowListener->GetMSComPtr(hWnd, lParam, wParam);\n}\n\n\/**\n * Implemention of handleWindowOpened, the method will be invoked when a\n * top window is opened and AT starts up.\n * @param\n * @return\n *\/\nvoid MSAAServiceImpl::handleWindowOpened(sal_Int64 nAcc)\n{\n SolarMutexGuard g;\n\n SAL_INFO( \"iacc2\", \"Window opened \" << nAcc );\n\n if (m_pTopWindowListener.is() && nAcc)\n {\n m_pTopWindowListener->HandleWindowOpened(\n static_cast<com::sun::star::accessibility::XAccessible*>(\n reinterpret_cast<void*>(nAcc)));\n }\n}\n\nOUString MSAAServiceImpl::getImplementationName() throw (RuntimeException)\n{\n return OUString( \"com.sun.star.accessibility.my_sc_impl.MSAAService\" );\n}\n\n\/**\n * Implemention of XServiceInfo,return support service name.\n * @param Service name.\n * @return If the service name is supported.\n *\/\nsal_Bool MSAAServiceImpl::supportsService( OUString const & serviceName ) throw (RuntimeException)\n{\n return cppu::supportsService(this, serviceName);\n}\n\n\/**\n * Implemention of XServiceInfo,return all service names.\n * @param.\n * @return service name sequence.\n *\/\nSequence< OUString > MSAAServiceImpl::getSupportedServiceNames() throw (RuntimeException)\n{\n return getSupportedServiceNames_MSAAServiceImpl();\n}\n\nstatic void AccessBridgeHandleExistingWindow(const Reference< XMSAAService > &xAccMgr,\n vcl::Window *pWindow, bool bShow)\n{\n if ( pWindow )\n {\n css::uno::Reference< css::accessibility::XAccessible > xAccessible;\n\n SAL_INFO( \"iacc2\", \"Decide whether to register existing window with IAccessible2\" );\n\n \/\/ Test for combo box - drop down floating windows first\n vcl::Window * pParentWindow = pWindow->GetParent();\n\n if ( pParentWindow )\n {\n try\n {\n \/\/ The parent window of a combo box floating window should have the role COMBO_BOX\n css::uno::Reference< css::accessibility::XAccessible > xParentAccessible(pParentWindow->GetAccessible());\n if ( xParentAccessible.is() )\n {\n css::uno::Reference< css::accessibility::XAccessibleContext > xParentAC( xParentAccessible->getAccessibleContext() );\n if ( xParentAC.is() && (css::accessibility::AccessibleRole::COMBO_BOX == xParentAC->getAccessibleRole()) )\n {\n \/\/ O.k. - this is a combo box floating window corresponding to the child of role LIST of the parent.\n \/\/ Let's not rely on a specific child order, just search for the child with the role LIST\n sal_Int32 nCount = xParentAC->getAccessibleChildCount();\n for ( sal_Int32 n = 0; (n < nCount) && !xAccessible.is(); n++)\n {\n css::uno::Reference< css::accessibility::XAccessible > xChild = xParentAC->getAccessibleChild(n);\n if ( xChild.is() )\n {\n css::uno::Reference< css::accessibility::XAccessibleContext > xChildAC = xChild->getAccessibleContext();\n if ( xChildAC.is() && (css::accessibility::AccessibleRole::LIST == xChildAC->getAccessibleRole()) )\n {\n xAccessible = xChild;\n }\n }\n }\n }\n }\n }\n catch (::com::sun::star::uno::RuntimeException const&)\n {\n \/\/ Ignore show events that throw DisposedExceptions in getAccessibleContext(),\n \/\/ but keep revoking these windows in hide(s).\n if (bShow)\n return;\n }\n }\n\n \/\/ We have to rely on the fact that Window::GetAccessible()->getAccessibleContext() returns a valid XAccessibleContext\n \/\/ also for other menus than menubar or toplevel popup window. Otherwise we had to traverse the hierarchy to find the\n \/\/ context object to this menu floater. This makes the call to Window->IsMenuFloatingWindow() obsolete.\n if ( ! xAccessible.is() )\n xAccessible = pWindow->GetAccessible();\n\n assert( xAccMgr.is() );\n if ( xAccessible.is() )\n {\n xAccMgr->handleWindowOpened(\n reinterpret_cast<sal_Int64>(xAccessible.get()));\n SAL_INFO( \"iacc2\", \"Decide whether to register existing window with IAccessible2\" );\n }\n }\n}\n\n\/*\n * Setup and notify the OS of Accessible peers for all existing windows.\n *\/\nstatic void AccessBridgeUpdateOldTopWindows( const Reference< XMSAAService > &xAccMgr )\n{\n sal_uInt16 nTopWindowCount = (sal_uInt16)Application::GetTopWindowCount();\n\n for ( sal_uInt16 i = 0; i < nTopWindowCount; i++ )\n {\n vcl::Window* pTopWindow = Application::GetTopWindow( i );\n css::uno::Reference< css::accessibility::XAccessible > xAccessible = pTopWindow->GetAccessible();\n if ( xAccessible.is() )\n {\n css::uno::Reference< css::accessibility::XAccessibleContext > xAC( xAccessible->getAccessibleContext() );\n if ( xAC.is())\n {\n if ( !xAC->getAccessibleName().isEmpty() )\n AccessBridgeHandleExistingWindow( xAccMgr, pTopWindow, true );\n }\n }\n }\n}\n\n\/**\n * Static method that can create an entity of our MSAA Service\n * @param xContext No use here.\n * @return The object interface.\n *\/\nReference< XInterface > SAL_CALL create_MSAAServiceImpl( Reference< XComponentContext > const & \/*xContext*\/ )\n{\n Reference< XMSAAService > xAccMgr( new MSAAServiceImpl() );\n\n AccessBridgeUpdateOldTopWindows( xAccMgr );\n\n SAL_INFO(\"iacc2\", \"Created new IAccessible2 service impl.\");\n\n return xAccMgr;\n}\n\nMSAAServiceImpl::MSAAServiceImpl()\n{\n Reference< XExtendedToolkit > xToolkit =\n Reference< XExtendedToolkit >(Application::GetVCLToolkit(), UNO_QUERY);\n\n if( xToolkit.is() )\n {\n m_pTopWindowListener.set(new AccTopWindowListener());\n Reference<XTopWindowListener> const xRef(m_pTopWindowListener.get());\n xToolkit->addTopWindowListener( xRef );\n SAL_INFO( \"iacc2\", \"successfully connected to the toolkit event hose\" );\n }\n else\n SAL_WARN( \"iacc2\", \"No VCL toolkit interface to listen to for events\");\n}\n\nMSAAServiceImpl::~MSAAServiceImpl()\n{\n}\n\nvoid MSAAServiceImpl::dispose()\n{\n SolarMutexGuard g;\n\n \/\/ As all folders and streams contain references to their parents,\n \/\/ we must remove these references so that they will be deleted when\n \/\/ the hash_map of the root folder is cleared, releasing all subfolders\n \/\/ and substreams which in turn release theirs, etc. When xRootFolder is\n \/\/ released when this destructor completes, the folder tree should be\n \/\/ deleted fully (and automagically).\n m_pTopWindowListener.clear();\n}\n\n}\n\n\/* shared lib exports implemented without helpers in service_impl1.cxx *\/\nnamespace my_sc_impl\n{\nstatic struct ::cppu::ImplementationEntry s_component_entries [] =\n {\n {\n create_MSAAServiceImpl, getImplementationName_MSAAServiceImpl,\n getSupportedServiceNames_MSAAServiceImpl,\n ::cppu::createSingleComponentFactory,\n 0, 0\n },\n { 0, 0, 0, 0, 0, 0 }\n };\n}\n\nextern \"C\"\n{\n SAL_DLLPUBLIC_EXPORT void * SAL_CALL iacc2_component_getFactory(\n sal_Char const * implName, lang::XMultiServiceFactory * xMgr,\n registry::XRegistryKey * xRegistry )\n {\n return ::cppu::component_getFactoryHelper(\n implName, xMgr, xRegistry, ::my_sc_impl::s_component_entries );\n }\n}\n\n\/* vim:set shiftwidth=4 softtabstop=4 expandtab: *\/\n<commit_msg>presumably this will fix the mismatch of the service names<commit_after>\/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- *\/\n\/*\n * This file is part of the LibreOffice project.\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\n * This file incorporates work covered by the following license notice:\n *\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed\n * with this work for additional information regarding copyright\n * ownership. The ASF licenses this file to you under the Apache\n * License, Version 2.0 (the \"License\"); you may not use this file\n * except in compliance with the License. You may obtain a copy of\n * the License at http:\/\/www.apache.org\/licenses\/LICENSE-2.0 .\n *\/\n\n#include <rtl\/ref.hxx>\n#include <cppuhelper\/implbase2.hxx>\n#include <cppuhelper\/factory.hxx>\n#include <cppuhelper\/implementationentry.hxx>\n#include <cppuhelper\/supportsservice.hxx>\n\n#include <com\/sun\/star\/lang\/XServiceInfo.hpp>\n#include <com\/sun\/star\/accessibility\/XMSAAService.hpp>\n#include <com\/sun\/star\/accessibility\/AccessibleRole.hpp>\n\n#include <com\/sun\/star\/awt\/XExtendedToolkit.hpp>\n#include <vcl\/svapp.hxx>\n#include <vcl\/window.hxx>\n\n#include <prewin.h>\n#include <postwin.h>\n\nusing namespace ::com::sun::star; \/\/ for odk interfaces\nusing namespace ::com::sun::star::uno; \/\/ for basic types\nusing namespace ::com::sun::star::accessibility;\n\nusing namespace ::com::sun::star::awt;\n\n#include \"AccTopWindowListener.hxx\"\n\nnamespace my_sc_impl\n{\n\nstatic Sequence< OUString > getSupportedServiceNames_MSAAServiceImpl()\n{\n Sequence< OUString > seqNames(1);\n seqNames.getArray()[0] = \"com.sun.star.accessibility.MSAAService\";\n return seqNames;\n}\n\nstatic OUString getImplementationName_MSAAServiceImpl()\n{\n return OUString( \"com.sun.star.accessibility.my_sc_implementation.MSAAService\" );\n}\n\nclass MSAAServiceImpl : public ::cppu::WeakImplHelper2<\n XMSAAService, lang::XServiceInfo >\n{\nprivate:\n rtl::Reference<AccTopWindowListener> m_pTopWindowListener;\n\npublic:\n MSAAServiceImpl ();\n virtual ~MSAAServiceImpl();\n\n \/\/ XComponent - as used by VCL to lifecycle manage this bridge.\n virtual void SAL_CALL dispose();\n virtual void SAL_CALL addEventListener( const css::uno::Reference< css::lang::XEventListener >& ) { \/* dummy *\/ }\n virtual void SAL_CALL removeEventListener( const css::uno::Reference< css::lang::XEventListener >& ) { \/* dummy *\/ }\n\n \/\/ XMSAAService\n virtual sal_Int64 SAL_CALL getAccObjectPtr(\n sal_Int64 hWnd, sal_Int64 lParam, sal_Int64 wParam);\n virtual void SAL_CALL handleWindowOpened(sal_Int64);\n\n \/\/ XServiceInfo\n virtual OUString SAL_CALL getImplementationName();\n virtual sal_Bool SAL_CALL supportsService( OUString const & serviceName );\n virtual Sequence< OUString > SAL_CALL getSupportedServiceNames();\n};\n\n\/**\n * Implemention of getAccObjectPtr.\n * @param\n * @return Com interface.\n *\/\nsal_Int64 MSAAServiceImpl::getAccObjectPtr(\n sal_Int64 hWnd, sal_Int64 lParam, sal_Int64 wParam)\nthrow (RuntimeException)\n{\n SolarMutexGuard g;\n\n if (!m_pTopWindowListener.is())\n {\n return 0;\n }\n return m_pTopWindowListener->GetMSComPtr(hWnd, lParam, wParam);\n}\n\n\/**\n * Implemention of handleWindowOpened, the method will be invoked when a\n * top window is opened and AT starts up.\n * @param\n * @return\n *\/\nvoid MSAAServiceImpl::handleWindowOpened(sal_Int64 nAcc)\n{\n SolarMutexGuard g;\n\n SAL_INFO( \"iacc2\", \"Window opened \" << nAcc );\n\n if (m_pTopWindowListener.is() && nAcc)\n {\n m_pTopWindowListener->HandleWindowOpened(\n static_cast<com::sun::star::accessibility::XAccessible*>(\n reinterpret_cast<void*>(nAcc)));\n }\n}\n\nOUString MSAAServiceImpl::getImplementationName() throw (RuntimeException)\n{\n return getImplementationName_MSAAServiceImpl();\n}\n\n\/**\n * Implemention of XServiceInfo,return support service name.\n * @param Service name.\n * @return If the service name is supported.\n *\/\nsal_Bool MSAAServiceImpl::supportsService( OUString const & serviceName ) throw (RuntimeException)\n{\n return cppu::supportsService(this, serviceName);\n}\n\n\/**\n * Implemention of XServiceInfo,return all service names.\n * @param.\n * @return service name sequence.\n *\/\nSequence< OUString > MSAAServiceImpl::getSupportedServiceNames() throw (RuntimeException)\n{\n return getSupportedServiceNames_MSAAServiceImpl();\n}\n\nstatic void AccessBridgeHandleExistingWindow(const Reference< XMSAAService > &xAccMgr,\n vcl::Window *pWindow, bool bShow)\n{\n if ( pWindow )\n {\n css::uno::Reference< css::accessibility::XAccessible > xAccessible;\n\n SAL_INFO( \"iacc2\", \"Decide whether to register existing window with IAccessible2\" );\n\n \/\/ Test for combo box - drop down floating windows first\n vcl::Window * pParentWindow = pWindow->GetParent();\n\n if ( pParentWindow )\n {\n try\n {\n \/\/ The parent window of a combo box floating window should have the role COMBO_BOX\n css::uno::Reference< css::accessibility::XAccessible > xParentAccessible(pParentWindow->GetAccessible());\n if ( xParentAccessible.is() )\n {\n css::uno::Reference< css::accessibility::XAccessibleContext > xParentAC( xParentAccessible->getAccessibleContext() );\n if ( xParentAC.is() && (css::accessibility::AccessibleRole::COMBO_BOX == xParentAC->getAccessibleRole()) )\n {\n \/\/ O.k. - this is a combo box floating window corresponding to the child of role LIST of the parent.\n \/\/ Let's not rely on a specific child order, just search for the child with the role LIST\n sal_Int32 nCount = xParentAC->getAccessibleChildCount();\n for ( sal_Int32 n = 0; (n < nCount) && !xAccessible.is(); n++)\n {\n css::uno::Reference< css::accessibility::XAccessible > xChild = xParentAC->getAccessibleChild(n);\n if ( xChild.is() )\n {\n css::uno::Reference< css::accessibility::XAccessibleContext > xChildAC = xChild->getAccessibleContext();\n if ( xChildAC.is() && (css::accessibility::AccessibleRole::LIST == xChildAC->getAccessibleRole()) )\n {\n xAccessible = xChild;\n }\n }\n }\n }\n }\n }\n catch (::com::sun::star::uno::RuntimeException const&)\n {\n \/\/ Ignore show events that throw DisposedExceptions in getAccessibleContext(),\n \/\/ but keep revoking these windows in hide(s).\n if (bShow)\n return;\n }\n }\n\n \/\/ We have to rely on the fact that Window::GetAccessible()->getAccessibleContext() returns a valid XAccessibleContext\n \/\/ also for other menus than menubar or toplevel popup window. Otherwise we had to traverse the hierarchy to find the\n \/\/ context object to this menu floater. This makes the call to Window->IsMenuFloatingWindow() obsolete.\n if ( ! xAccessible.is() )\n xAccessible = pWindow->GetAccessible();\n\n assert( xAccMgr.is() );\n if ( xAccessible.is() )\n {\n xAccMgr->handleWindowOpened(\n reinterpret_cast<sal_Int64>(xAccessible.get()));\n SAL_INFO( \"iacc2\", \"Decide whether to register existing window with IAccessible2\" );\n }\n }\n}\n\n\/*\n * Setup and notify the OS of Accessible peers for all existing windows.\n *\/\nstatic void AccessBridgeUpdateOldTopWindows( const Reference< XMSAAService > &xAccMgr )\n{\n sal_uInt16 nTopWindowCount = (sal_uInt16)Application::GetTopWindowCount();\n\n for ( sal_uInt16 i = 0; i < nTopWindowCount; i++ )\n {\n vcl::Window* pTopWindow = Application::GetTopWindow( i );\n css::uno::Reference< css::accessibility::XAccessible > xAccessible = pTopWindow->GetAccessible();\n if ( xAccessible.is() )\n {\n css::uno::Reference< css::accessibility::XAccessibleContext > xAC( xAccessible->getAccessibleContext() );\n if ( xAC.is())\n {\n if ( !xAC->getAccessibleName().isEmpty() )\n AccessBridgeHandleExistingWindow( xAccMgr, pTopWindow, true );\n }\n }\n }\n}\n\n\/**\n * Static method that can create an entity of our MSAA Service\n * @param xContext No use here.\n * @return The object interface.\n *\/\nReference< XInterface > SAL_CALL create_MSAAServiceImpl( Reference< XComponentContext > const & \/*xContext*\/ )\n{\n Reference< XMSAAService > xAccMgr( new MSAAServiceImpl() );\n\n AccessBridgeUpdateOldTopWindows( xAccMgr );\n\n SAL_INFO(\"iacc2\", \"Created new IAccessible2 service impl.\");\n\n return xAccMgr;\n}\n\nMSAAServiceImpl::MSAAServiceImpl()\n{\n Reference< XExtendedToolkit > xToolkit =\n Reference< XExtendedToolkit >(Application::GetVCLToolkit(), UNO_QUERY);\n\n if( xToolkit.is() )\n {\n m_pTopWindowListener.set(new AccTopWindowListener());\n Reference<XTopWindowListener> const xRef(m_pTopWindowListener.get());\n xToolkit->addTopWindowListener( xRef );\n SAL_INFO( \"iacc2\", \"successfully connected to the toolkit event hose\" );\n }\n else\n SAL_WARN( \"iacc2\", \"No VCL toolkit interface to listen to for events\");\n}\n\nMSAAServiceImpl::~MSAAServiceImpl()\n{\n}\n\nvoid MSAAServiceImpl::dispose()\n{\n SolarMutexGuard g;\n\n \/\/ As all folders and streams contain references to their parents,\n \/\/ we must remove these references so that they will be deleted when\n \/\/ the hash_map of the root folder is cleared, releasing all subfolders\n \/\/ and substreams which in turn release theirs, etc. When xRootFolder is\n \/\/ released when this destructor completes, the folder tree should be\n \/\/ deleted fully (and automagically).\n m_pTopWindowListener.clear();\n}\n\n}\n\n\/* shared lib exports implemented without helpers in service_impl1.cxx *\/\nnamespace my_sc_impl\n{\nstatic struct ::cppu::ImplementationEntry s_component_entries [] =\n {\n {\n create_MSAAServiceImpl, getImplementationName_MSAAServiceImpl,\n getSupportedServiceNames_MSAAServiceImpl,\n ::cppu::createSingleComponentFactory,\n 0, 0\n },\n { 0, 0, 0, 0, 0, 0 }\n };\n}\n\nextern \"C\"\n{\n SAL_DLLPUBLIC_EXPORT void * SAL_CALL iacc2_component_getFactory(\n sal_Char const * implName, lang::XMultiServiceFactory * xMgr,\n registry::XRegistryKey * xRegistry )\n {\n return ::cppu::component_getFactoryHelper(\n implName, xMgr, xRegistry, ::my_sc_impl::s_component_entries );\n }\n}\n\n\/* vim:set shiftwidth=4 softtabstop=4 expandtab: *\/\n<|endoftext|>"} {"text":"<commit_before>\/*! \\file unitTestRandomNumberGenerator.cpp\n * Source file that defines a unit test that tests the random number\n * generator included in Tudat.\n *\n * Path : \/Mathematics\/\n * Version : 3\n * Check status : Checked\n *\n * Author : K. Kumar\n * Affiliation : Delft University of Technology\n * E-mail address : K.Kumar@tudelft.nl\n *\n * Checker : D. Dirkx\n * Affiliation : Delft University of Technology\n * E-mail address : D.Dirkx@student.tudelft.nl\n *\n * Date created : 7 January, 2011\n * Last modified : 7 July, 2011\n *\n * References\n * Walpole, R.E., et al. Probabilty and Statistics for Engineers &\n * Scientists, Seventh Edition, Prentice Hall, NJ, 2002.\n * Texas A&M University. Chi Square Calculator,\n * http:\/\/www.stat.tamu.edu\/~west\/applets\/chisqdemo.html, last\n * accessed: 7 July, 2011.\n * Faculty of Mathematics and Informatics, University of Sofia.\n * http:\/\/www.fmi.uni-sofia.bg\/vesta\/virtual_labs\/interval\/interval6.html,\n * last accessed: 7 July, 2011.\n *\n * Notes\n * Test runs code and verifies result against expected value.\n * If the tested code is erroneous, the test function returns a boolean\n * true; if the code is correct, the function returns a boolean false.\n *\n * The code tests for the quality of the uniform distribution by testing\n * the sample mean and variance against the true mean and variance using\n * standard error estimates. These estimates are stated with a\n * confidence of 99.96%. If the unit test fails due to Test 5, it is\n * recommended that the unit test is run again to rule out statistical\n * anomalies.\n *\n * Copyright (c) 2010 Delft University of Technology.\n *\n * This software is protected by national and international copyright.\n * Any unauthorized use, reproduction or modification is unlawful and\n * will be prosecuted. Commercial and non-private application of the\n * software in any form is strictly prohibited unless otherwise granted\n * by the authors.\n *\n * The code is provided without any warranty; without even the implied\n * warranty of merchantibility or fitness for a particular purpose.\n *\n * Changelog\n * YYMMDD Author Comment\n * 110107 K. Kumar First creation of code.\n * 110207 K. Kumar Updated code to conform to protocol; added\n * cerr statements.\n * 110209 K. Kumar Updated tests and added test for mean and\n * variance of uniform distribution; added\n * note and reference.\n * 110707 K. Kumar Corrected variance calculation errors;\n * updated references.\n *\/\n\n\/\/ Include statements.\n#include \"randomNumberGenerator.h\"\n\n\/\/ Using declarations.\nusing mathematics::computeAbsoluteValue;\nusing mathematics::raiseToIntegerPower;\nusing mathematics::MACHINE_PRECISION_DOUBLES;\nusing std::cerr;\nusing std::endl;\n\n\/\/! Namespace for all unit tests.\nnamespace unit_tests\n{\n\n\/\/! Test of implementation of random number generator class.\nbool testRandomNumberGenerator( )\n{\n \/\/ Four tests.\n \/\/ Test 1: Get a random integer ( 64-bit ).\n \/\/ Test 2: Get a random integer ( 32-bit ).\n \/\/ Test 3: Get a normalized random double in the interval [ 0, 1 ].\n \/\/ Test 4: Get a random plus\/minus sign.\n \/\/ Test 5: Compute sample mean and standard distrubution of distribution\n \/\/ and compare to analytical results.\n\n \/\/ Test result initialised to false.\n bool isRandomNumberGeneratorErroneous = false;\n\n \/\/ Create random number generator object.\n RandomNumberGenerator randomNumbers( time( NULL ) );\n\n \/\/ Results computed using implementation of random number generator class.\n \/\/ Test 1: Get a random integer ( 64-bit ).\n int computedResultForTest1 = randomNumbers\n .getUniformlyDistributedRandom64BitInteger( );\n\n \/\/ Compute differences between computed and expected results and generate\n \/\/ cerr statement if test fails.\n if ( fmod( computedResultForTest1, floor( computedResultForTest1 ) )\n > MACHINE_PRECISION_DOUBLES )\n {\n isRandomNumberGeneratorErroneous = true;\n\n cerr << \"The computed value ( \" << computedResultForTest1\n << \" ) using the 64-bit random integer generator \"\n << \"is not an integer\" << endl;\n }\n\n \/\/ Test 2: Get a random integer ( 32-bit ).\n int computedResultForTest2 = randomNumbers\n .getUniformlyDistributedRandom32BitInteger( );\n\n \/\/ Compute differences between computed and expected results and generate\n \/\/ cerr statement if test fails.\n if ( fmod( computedResultForTest2, floor( computedResultForTest2 ) )\n > MACHINE_PRECISION_DOUBLES )\n {\n isRandomNumberGeneratorErroneous = true;\n\n cerr << \"The computed value ( \" << computedResultForTest2\n << \" ) using the 32-bit random integer generator \"\n << \"is not an integer\" << endl;\n }\n\n \/\/ Test 3: Get a normalized random double in the interval [ 0, 1 ].\n double computedResultForTest3\n = randomNumbers.getUniformlyDistributedNormalizedRandomDouble( );\n\n \/\/ Compute differences between computed and expected results and generate\n \/\/ cerr statement if test fails.\n if ( computedResultForTest3 < 0.0 && computedResultForTest3 > 1.0 )\n {\n isRandomNumberGeneratorErroneous = true;\n\n cerr << \"The computed value ( \" << computedResultForTest3\n << \" ) using the normalized random number generator \"\n << \"is not within the prescribed bounds [ 0, 1 ]\" << endl;\n }\n\n \/\/ Test 4: Get a random plus\/minus sign.\n double computedResultForTest4 = randomNumbers.getRandomPlusMinusSign( );\n\n \/\/ Compute differences between computed and expected results and generate\n \/\/ cerr statement if test fails.\n if ( computeAbsoluteValue( computedResultForTest4 ) - 1.0\n > MACHINE_PRECISION_DOUBLES )\n {\n isRandomNumberGeneratorErroneous = true;\n\n cerr << \"The computed value ( \" << computedResultForTest4\n << \" ) using the plus\/minus sign random generator \"\n << \"is not equal to either +1 or -1\" << endl;\n }\n\n \/\/ Test 5: Compute sample mean and variance of distribution and compare to\n \/\/ analytical results.\n \/\/ Declare and initialize number of samples.\n unsigned int numberOfSamples = 100000;\n\n \/\/ Declare and set size of vector of sample random values.\n VectorXd sampleOfRandomValues = VectorXd( numberOfSamples );\n\n \/\/ Fill vector of sample random values.\n for ( unsigned int i = 0; i < numberOfSamples; i++ )\n {\n sampleOfRandomValues( i )\n = randomNumbers\n .getUniformlyDistributedNormalizedRandomDouble( );\n }\n\n \/\/ Estimate sample mean of the distribution.\n double sampleMean = sampleOfRandomValues.sum( )\n \/ numberOfSamples;\n\n \/\/ Estimate sample variance.\n double sumOfResidualsSquared = 0.0;\n for ( unsigned int i = 0; i < numberOfSamples; i++ )\n {\n sumOfResidualsSquared +=\n raiseToIntegerPower( sampleOfRandomValues( i )\n - sampleMean, 2 );\n }\n double sampleVariance\n = 1.0 \/ ( numberOfSamples - 1.0 ) * sumOfResidualsSquared;\n\n \/\/ Compute differences between computed and expected results.\n \/\/ Test sample mean versus true mean with a confidence of 99.96%.\n \/\/ This means that the test below guarentees that this unit test will\n \/\/ fail on average every 2500 times it is run.\n \/\/ Also test sample variance versus true variance with a confidence of\n \/\/ 99.96%. The true mean and true variance of a uniform distribution\n \/\/ from 0 to 1 are 1\/2 and 1\/12 respectively.\n \/\/ The tolerances were computed using confidence intervals for the sample\n \/\/ mean and variance and table lookup.\n if ( computeAbsoluteValue( sampleMean - 0.5 )\n > 3.49 * 1.0 \/ sqrt( 12.0 )\n * 1.0 \/ static_cast< double >( sqrt( numberOfSamples ) )\n )\n {\n isRandomNumberGeneratorErroneous = true;\n\n cerr << \"The computed sample mean ( \" << sampleMean\n << \" ) using a sample size of \" << numberOfSamples\n << \" is not within the standard error of the true sample mean\"\n << \" ( 1\/2 ) \" << endl;\n cerr << \"The distribution is not uniform to a confidence of 99.96%. \"\n << \"Run the unit test again to ensure error is not due to \"\n << \"statistical anomaly. \" << endl;\n }\n\n if ( ( 1.0 \/ 12.0 ) \/ sampleVariance\n < static_cast< double >( numberOfSamples - 1 ) \/ 101291\n || ( 1.0 \/ 12.0 ) \/ sampleVariance\n > static_cast< double>( numberOfSamples - 1 ) \/ 98717 )\n {\n isRandomNumberGeneratorErroneous = true;\n\n cerr << \"The computed sample variance ( \" << sampleVariance\n << \" ) using a sample size of \" << numberOfSamples\n << \" is not within the standard error of the true sample variance\"\n << \"( 1\/12 ) \" << endl;\n cerr << \"The distribution is not uniform to a confidence of 99.96%. \"\n << \"Run the unit test again to ensure error is not due to \"\n << \"statistical anomaly.\" << endl;\n }\n\n \/\/ Return test result.\n \/\/ If test is successful return false; if test fails, return true.\n return isRandomNumberGeneratorErroneous;\n}\n\n}\n\n\/\/ End of file.\n<commit_msg>Commit of correction to random number generator unit test.<commit_after>\/*! \\file unitTestRandomNumberGenerator.cpp\n * Source file that defines a unit test that tests the random number\n * generator included in Tudat.\n *\n * Path : \/Mathematics\/\n * Version : 3\n * Check status : Checked\n *\n * Author : K. Kumar\n * Affiliation : Delft University of Technology\n * E-mail address : K.Kumar@tudelft.nl\n *\n * Checker : D. Dirkx\n * Affiliation : Delft University of Technology\n * E-mail address : D.Dirkx@student.tudelft.nl\n *\n * Date created : 7 January, 2011\n * Last modified : 7 July, 2011\n *\n * References\n * Walpole, R.E., et al. Probabilty and Statistics for Engineers &\n * Scientists, Seventh Edition, Prentice Hall, NJ, 2002.\n * Texas A&M University. Chi Square Calculator,\n * http:\/\/www.stat.tamu.edu\/~west\/applets\/chisqdemo.html, last\n * accessed: 7 July, 2011.\n * Faculty of Mathematics and Informatics, University of Sofia.\n * http:\/\/www.fmi.uni-sofia.bg\/vesta\/virtual_labs\/interval\/interval6.html,\n * last accessed: 7 July, 2011.\n *\n * Notes\n * Test runs code and verifies result against expected value.\n * If the tested code is erroneous, the test function returns a boolean\n * true; if the code is correct, the function returns a boolean false.\n *\n * The code tests for the quality of the uniform distribution by testing\n * the sample mean and variance against the true mean and variance using\n * standard error estimates. These estimates are stated with a\n * confidence of 99.96%. If the unit test fails due to Test 5, it is\n * recommended that the unit test is run again to rule out statistical\n * anomalies.\n *\n * Copyright (c) 2010 Delft University of Technology.\n *\n * This software is protected by national and international copyright.\n * Any unauthorized use, reproduction or modification is unlawful and\n * will be prosecuted. Commercial and non-private application of the\n * software in any form is strictly prohibited unless otherwise granted\n * by the authors.\n *\n * The code is provided without any warranty; without even the implied\n * warranty of merchantibility or fitness for a particular purpose.\n *\n * Changelog\n * YYMMDD Author Comment\n * 110107 K. Kumar First creation of code.\n * 110207 K. Kumar Updated code to conform to protocol; added\n * cerr statements.\n * 110209 K. Kumar Updated tests and added test for mean and\n * variance of uniform distribution; added\n * note and reference.\n * 110707 K. Kumar Corrected variance calculation errors;\n * updated references.\n *\/\n\n\/\/ Include statements.\n#include \"randomNumberGenerator.h\"\n\n\/\/ Using declarations.\nusing mathematics::computeAbsoluteValue;\nusing mathematics::raiseToIntegerPower;\nusing mathematics::MACHINE_PRECISION_DOUBLES;\nusing std::cerr;\nusing std::endl;\n\n\/\/! Namespace for all unit tests.\nnamespace unit_tests\n{\n\n\/\/! Test of implementation of random number generator class.\nbool testRandomNumberGenerator( )\n{\n \/\/ Four tests.\n \/\/ Test 1: Get a random integer ( 64-bit ).\n \/\/ Test 2: Get a random integer ( 32-bit ).\n \/\/ Test 3: Get a normalized random double in the interval [ 0, 1 ].\n \/\/ Test 4: Get a random plus\/minus sign.\n \/\/ Test 5: Compute sample mean and standard distrubution of distribution\n \/\/ and compare to analytical results.\n\n \/\/ Test result initialised to false.\n bool isRandomNumberGeneratorErroneous = false;\n\n \/\/ Create random number generator object.\n RandomNumberGenerator randomNumbers( time( NULL ) );\n\n \/\/ Results computed using implementation of random number generator class.\n \/\/ Test 1: Get a random integer ( 64-bit ).\n int computedResultForTest1 = randomNumbers\n .getUniformlyDistributedRandom64BitInteger( );\n\n \/\/ Compute differences between computed and expected results and generate\n \/\/ cerr statement if test fails.\n if ( fmod( computedResultForTest1, floor( computedResultForTest1 ) )\n > MACHINE_PRECISION_DOUBLES )\n {\n isRandomNumberGeneratorErroneous = true;\n\n cerr << \"The computed value ( \" << computedResultForTest1\n << \" ) using the 64-bit random integer generator \"\n << \"is not an integer\" << endl;\n }\n\n \/\/ Test 2: Get a random integer ( 32-bit ).\n int computedResultForTest2 = randomNumbers\n .getUniformlyDistributedRandom32BitInteger( );\n\n \/\/ Compute differences between computed and expected results and generate\n \/\/ cerr statement if test fails.\n if ( fmod( computedResultForTest2, floor( computedResultForTest2 ) )\n > MACHINE_PRECISION_DOUBLES )\n {\n isRandomNumberGeneratorErroneous = true;\n\n cerr << \"The computed value ( \" << computedResultForTest2\n << \" ) using the 32-bit random integer generator \"\n << \"is not an integer\" << endl;\n }\n\n \/\/ Test 3: Get a normalized random double in the interval [ 0, 1 ].\n double computedResultForTest3\n = randomNumbers.getUniformlyDistributedNormalizedRandomDouble( );\n\n \/\/ Compute differences between computed and expected results and generate\n \/\/ cerr statement if test fails.\n if ( computedResultForTest3 < 0.0 && computedResultForTest3 > 1.0 )\n {\n isRandomNumberGeneratorErroneous = true;\n\n cerr << \"The computed value ( \" << computedResultForTest3\n << \" ) using the normalized random number generator \"\n << \"is not within the prescribed bounds [ 0, 1 ]\" << endl;\n }\n\n \/\/ Test 4: Get a random plus\/minus sign.\n double computedResultForTest4 = randomNumbers.getRandomPlusMinusSign( );\n\n \/\/ Compute differences between computed and expected results and generate\n \/\/ cerr statement if test fails.\n if ( computeAbsoluteValue( computedResultForTest4 ) - 1.0\n > MACHINE_PRECISION_DOUBLES )\n {\n isRandomNumberGeneratorErroneous = true;\n\n cerr << \"The computed value ( \" << computedResultForTest4\n << \" ) using the plus\/minus sign random generator \"\n << \"is not equal to either +1 or -1\" << endl;\n }\n\n \/\/ Test 5: Compute sample mean and variance of distribution and compare to\n \/\/ analytical results.\n \/\/ Declare and initialize number of samples.\n unsigned int numberOfSamples = 100000;\n\n \/\/ Declare and set size of vector of sample random values.\n VectorXd sampleOfRandomValues = VectorXd( numberOfSamples );\n\n \/\/ Fill vector of sample random values.\n for ( unsigned int i = 0; i < numberOfSamples; i++ )\n {\n sampleOfRandomValues( i )\n = randomNumbers\n .getUniformlyDistributedNormalizedRandomDouble( );\n }\n\n \/\/ Estimate sample mean of the distribution.\n double sampleMean = sampleOfRandomValues.sum( )\n \/ numberOfSamples;\n\n \/\/ Estimate sample variance.\n double sumOfResidualsSquared = 0.0;\n for ( unsigned int i = 0; i < numberOfSamples; i++ )\n {\n sumOfResidualsSquared +=\n raiseToIntegerPower( sampleOfRandomValues( i )\n - sampleMean, 2 );\n }\n double sampleVariance\n = 1.0 \/ ( numberOfSamples - 1.0 ) * sumOfResidualsSquared;\n\n \/\/ Compute differences between computed and expected results.\n \/\/ Test sample mean versus true mean with a confidence of 99.96%.\n \/\/ This means that the test below guarentees that this unit test will\n \/\/ fail on average every 2500 times it is run.\n \/\/ Also test sample variance versus true variance with a confidence of\n \/\/ 99.96%. The true mean and true variance of a uniform distribution\n \/\/ from 0 to 1 are 1\/2 and 1\/12 respectively.\n \/\/ The tolerances were computed using confidence intervals for the sample\n \/\/ mean and variance and table lookup.\n if ( computeAbsoluteValue( sampleMean - 0.5 )\n > 3.49 * 1.0 \/ sqrt( 12.0 )\n * 1.0 \/ static_cast< double >( sqrt( numberOfSamples ) )\n )\n {\n isRandomNumberGeneratorErroneous = true;\n\n cerr << \"The computed sample mean ( \" << sampleMean\n << \" ) using a sample size of \" << numberOfSamples\n << \" is not within the standard error of the true sample mean\"\n << \" ( 1\/2 ) \" << endl;\n cerr << \"The distribution is not uniform to a confidence of 99.96%. \"\n << \"Run the unit test again to ensure error is not due to \"\n << \"statistical anomaly. \" << endl;\n }\n\n if ( ( 1.0 \/ 12.0 ) \/ sampleVariance\n < static_cast< double >( numberOfSamples - 1 ) \/ 101590\n || ( 1.0 \/ 12.0 ) \/ sampleVariance\n > static_cast< double>( numberOfSamples - 1 ) \/ 98424 )\n {\n isRandomNumberGeneratorErroneous = true;\n\n cerr << \"The computed sample variance ( \" << sampleVariance\n << \" ) using a sample size of \" << numberOfSamples\n << \" is not within the standard error of the true sample variance\"\n << \"( 1\/12 ) \" << endl;\n cerr << \"The distribution is not uniform to a confidence of 99.96%. \"\n << \"Run the unit test again to ensure error is not due to \"\n << \"statistical anomaly.\" << endl;\n }\n\n \/\/ Return test result.\n \/\/ If test is successful return false; if test fails, return true.\n return isRandomNumberGeneratorErroneous;\n}\n\n}\n\n\/\/ End of file.\n<|endoftext|>"} {"text":"<commit_before>#ifdef __AVR__\n#include <avr\/pgmspace.h>\n#elif defined(ESP8266) || defined(ESP32)\n#include <pgmspace.h>\n#else\n\/*\n * Not all non-AVR boards installs define macros\n * for compatibility with existing PROGMEM-reading AVR code.\n *\/\n#ifndef PROGMEM\n#define PROGMEM\n#endif\n#ifndef PGM_P\n#define PGM_P const char *\n#endif\n#ifndef SIZE_IRRELEVANT\n#define SIZE_IRRELEVANT 0x7fffffff\n#endif\n#ifndef pgm_read_byte\n#define pgm_read_byte(addr) (*(const unsigned char *)(addr))\n#endif\n#ifndef strcpy_P\nchar* strncpy_P(char* dest, PGM_P src, size_t size) {\n bool size_known = (size != SIZE_IRRELEVANT);\n const char* read = src;\n char* write = dest;\n char ch = '.';\n while (size > 0 && ch != '\\0')\n {\n ch = pgm_read_byte(read++);\n *write++ = ch;\n size--;\n }\n if (size_known)\n {\n while (size > 0)\n {\n *write++ = 0;\n size--;\n }\n }\n\n return dest;\n}\n#define strcpy_P(dest, src) strncpy_P((dest), (src), SIZE_IRRELEVANT)\n#endif\n#endif \/\/ PROGMEM\n\n\/*\n * TetheringInternet class\n *\/\nconst char XOD_PREFIX[] PROGMEM = \"+XOD:\";\n\nconst char OK[] PROGMEM = \"OK\";\nconst char FAIL[] PROGMEM = \"FAIL\";\nconst char ERROR[] PROGMEM = \"ERROR\";\nconst char IPD[] PROGMEM = \"IPD,\";\nconst char CLOSED[] PROGMEM = \"CLOSED\";\nconst char CIFSR[] PROGMEM = \"AT+CIFSR\";\nconst char STAIP[] PROGMEM = \"STAIP,\\\"\";\n\nconst char AT[] PROGMEM = \"AT\";\nconst char CIPSEND[] PROGMEM = \"AT+CIPSEND=\";\nconst char CIPSTART[] PROGMEM = \"AT+CIPSTART=\\\"\";\nconst char CIPCLOSE[] PROGMEM = \"AT+CIPCLOSE\";\nconst char TCP[] PROGMEM = \"TCP\";\n\nconst char SEND_OK[] PROGMEM = \"SEND OK\";\nconst char LINK_IS_NOT[] PROGMEM = \"link is not\";\nconst char PROMPT[] PROGMEM = \">\";\n\nconst char COMMA[] PROGMEM = \",\";\nconst char COMMA_1[] PROGMEM = \"\\\",\";\nconst char COMMA_2[] PROGMEM = \"\\\",\\\"\";\nconst char COLON[] PROGMEM = \":\";\n\nconst char EOL[] PROGMEM = \"\\r\\n\";\n\n\nclass TetheringInternet {\nprivate:\n#ifdef XOD_WASM_SERIAL_H\n WasmSerial_* _serial = &XOD_DEBUG_SERIAL;\n#else\n Stream* _serial = &XOD_DEBUG_SERIAL;\n#endif\n uint16_t _nodeId;\n bool _connected = false;\n static volatile uint16_t _pkgSize;\n void printPrefix() {\n writeCmd(XOD_PREFIX);\n _serial->print(transactionTime());\n writeCmd(COLON);\n _serial->print(_nodeId);\n writeCmd(COLON);\n }\n uint8_t readCmd(const char* text1, const char* text2 = nullptr, uint32_t timeout = 5000) {\n \/\/ setup buffers on stack & copy data from PROGMEM pointers\n char buf1[16] = { '\\0' };\n char buf2[16] = { '\\0' };\n if (text1 != nullptr)\n strcpy_P(buf1, text1);\n if (text2 != nullptr)\n strcpy_P(buf2, text2);\n uint8_t len1 = strlen(buf1);\n uint8_t len2 = strlen(buf2);\n uint8_t pos1 = 0;\n uint8_t pos2 = 0;\n \/\/ read chars until first match or timeout\n uint32_t stop = millis() + timeout;\n do {\n while (_serial->available()) {\n char c = _serial->read();\n pos1 = (c == buf1[pos1]) ? pos1 + 1 : 0;\n pos2 = (c == buf2[pos2]) ? pos2 + 1 : 0;\n if (len1 > 0 && pos1 == len1) {\n return 1;\n }\n if (len2 > 0 && pos2 == len2) {\n return 2;\n }\n }\n } while (millis() < stop);\n return 0;\n }\n bool cmdOK(const char* okResponse, const char* failResponse = nullptr, uint32_t timeout = 1000) {\n uint8_t res = readCmd(okResponse, failResponse, timeout);\n return res == 1;\n }\n void writeCmd(const char* text1 = nullptr, const char* text2 = nullptr) {\n char buf[16] = { '\\0' };\n strcpy_P(buf, text1);\n _serial->print(buf);\n if (text2 == EOL) {\n _serial->println();\n } else if (text2 != nullptr) {\n strcpy_P(buf, text2);\n _serial->print(buf);\n }\n }\npublic:\n TetheringInternet(uint16_t nodeId) {\n _nodeId = nodeId;\n }\n\n static bool isReceiving() {\n return _pkgSize > 0;\n }\n static void beginReceiving(uint16_t pkgSize) {\n _pkgSize = pkgSize;\n }\n\n bool kick() {\n printPrefix();\n writeCmd(AT, EOL);\n _serial->flush();\n uint8_t res = readCmd(OK, ERROR);\n return res == 1;\n }\n bool openTcp(XString host, uint32_t port, uint16_t keepAlive = 0) {\n printPrefix();\n \/\/ Command + connection type\n writeCmd(CIPSTART);\n writeCmd(TCP);\n writeCmd(COMMA_2);\n \/\/ Host\n for (auto it = host.iterate(); it; ++it)\n _serial->print((char)*it);\n \/\/ Port\n writeCmd(COMMA_1);\n char _port[32];\n xod::formatNumber(port, 0, _port);\n _serial->print(port);\n \/\/ Delimiter\n writeCmd(COMMA);\n \/\/ Keep alive\n char _keepAlive[1];\n xod::formatNumber(keepAlive, 0, _keepAlive);\n _serial->println(keepAlive);\n _serial->flush();\n\n _connected = readCmd(OK, ERROR) == 1;\n return _connected;\n }\n bool send(XString req) {\n printPrefix();\n\n size_t len = length(req);\n char reqLen[len];\n xod::formatNumber(len, 0, reqLen);\n\n writeCmd(CIPSEND);\n _serial->println(reqLen);\n _serial->flush();\n\n bool prompt = cmdOK(PROMPT, LINK_IS_NOT);\n if (!prompt)\n return false;\n\n \/\/ Send message in a special way to wrap each line with a XOD prefix\n bool nextLine = true;\n bool cr = false;\n for (auto it = req.iterate(); it; ++it) {\n if (nextLine) {\n printPrefix();\n nextLine = false;\n }\n if (*it == '\\r') {\n cr = true;\n _serial->print(\"\\\\r\");\n } else if (*it == '\\n') {\n nextLine = true;\n _serial->print(\"\\\\n\");\n if (cr) _serial->print('\\r');\n _serial->print('\\n');\n } else {\n _serial->print((char)*it);\n }\n }\n\n _serial->flush();\n\n return cmdOK(SEND_OK, nullptr, 5000);\n }\n bool isConnected() {\n return _connected;\n }\n bool isAvailable() {\n return _serial->available();\n }\n bool receiveByte(char* outBuff, uint32_t timeout = 5000) {\n uint32_t stop = millis() + timeout;\n uint32_t a = 0;\n do {\n if (isAvailable() && isReceiving()) {\n *outBuff = _serial->read();\n _pkgSize--;\n \/\/ Response with ACK character to request next chunks\n if (_pkgSize == 0) {\n printPrefix();\n _serial->println('\\6');\n }\n if (*outBuff == '\\4') {\n \/\/ end of transmittion symbol == connection closed\n _connected = false;\n _pkgSize = 0;\n }\n return true;\n }\n } while (a < stop);\n return false;\n }\n uint32_t getIP() {\n printPrefix();\n writeCmd(CIFSR, EOL);\n uint8_t code = readCmd(STAIP, ERROR);\n if (code == 1) {\n \/\/ found ip\n uint32_t ip[4];\n ip[0] = _serial->parseInt();\n _serial->read(); \/\/ .\n ip[1] = _serial->parseInt();\n _serial->read(); \/\/ .\n ip[2] = _serial->parseInt();\n _serial->read(); \/\/ .\n ip[3] = _serial->parseInt();\n\n if ((ip[0] | ip[1] | ip[2] | ip[3]) >= 0x100)\n return 0;\n\n return ip[0] + ip[1] * 0x100 + ip[2] * 0x10000ul + ip[3] * 0x1000000ul;\n }\n return 0;\n }\n bool close(uint8_t linkId) {\n \/\/ TODO: MUX\n printPrefix();\n writeCmd(CIPCLOSE, EOL);\n return readCmd(OK, ERROR) == 1;\n }\n};\n\nvolatile uint16_t TetheringInternet::_pkgSize = 0;\n\nstruct State {\n uint8_t mem[sizeof(TetheringInternet)];\n TetheringInternet* inet;\n};\n\nusing Type = TetheringInternet*;\n\n{{ GENERATED_CODE }}\n\nvoid evaluate(Context ctx) {\n auto state = getState(ctx);\n state->inet = new (state->mem) TetheringInternet(getNodeId(ctx));\n emitValue<output_INET>(ctx, state->inet);\n}\n<commit_msg>fix(stdlib): fix sending of the last row of a request in tethering-inet<commit_after>#ifdef __AVR__\n#include <avr\/pgmspace.h>\n#elif defined(ESP8266) || defined(ESP32)\n#include <pgmspace.h>\n#else\n\/*\n * Not all non-AVR boards installs define macros\n * for compatibility with existing PROGMEM-reading AVR code.\n *\/\n#ifndef PROGMEM\n#define PROGMEM\n#endif\n#ifndef PGM_P\n#define PGM_P const char *\n#endif\n#ifndef SIZE_IRRELEVANT\n#define SIZE_IRRELEVANT 0x7fffffff\n#endif\n#ifndef pgm_read_byte\n#define pgm_read_byte(addr) (*(const unsigned char *)(addr))\n#endif\n#ifndef strcpy_P\nchar* strncpy_P(char* dest, PGM_P src, size_t size) {\n bool size_known = (size != SIZE_IRRELEVANT);\n const char* read = src;\n char* write = dest;\n char ch = '.';\n while (size > 0 && ch != '\\0')\n {\n ch = pgm_read_byte(read++);\n *write++ = ch;\n size--;\n }\n if (size_known)\n {\n while (size > 0)\n {\n *write++ = 0;\n size--;\n }\n }\n\n return dest;\n}\n#define strcpy_P(dest, src) strncpy_P((dest), (src), SIZE_IRRELEVANT)\n#endif\n#endif \/\/ PROGMEM\n\n\/*\n * TetheringInternet class\n *\/\nconst char XOD_PREFIX[] PROGMEM = \"+XOD:\";\n\nconst char OK[] PROGMEM = \"OK\";\nconst char FAIL[] PROGMEM = \"FAIL\";\nconst char ERROR[] PROGMEM = \"ERROR\";\nconst char IPD[] PROGMEM = \"IPD,\";\nconst char CLOSED[] PROGMEM = \"CLOSED\";\nconst char CIFSR[] PROGMEM = \"AT+CIFSR\";\nconst char STAIP[] PROGMEM = \"STAIP,\\\"\";\n\nconst char AT[] PROGMEM = \"AT\";\nconst char CIPSEND[] PROGMEM = \"AT+CIPSEND=\";\nconst char CIPSTART[] PROGMEM = \"AT+CIPSTART=\\\"\";\nconst char CIPCLOSE[] PROGMEM = \"AT+CIPCLOSE\";\nconst char TCP[] PROGMEM = \"TCP\";\n\nconst char SEND_OK[] PROGMEM = \"SEND OK\";\nconst char LINK_IS_NOT[] PROGMEM = \"link is not\";\nconst char PROMPT[] PROGMEM = \">\";\n\nconst char COMMA[] PROGMEM = \",\";\nconst char COMMA_1[] PROGMEM = \"\\\",\";\nconst char COMMA_2[] PROGMEM = \"\\\",\\\"\";\nconst char COLON[] PROGMEM = \":\";\n\nconst char EOL[] PROGMEM = \"\\r\\n\";\n\n\nclass TetheringInternet {\nprivate:\n#ifdef XOD_WASM_SERIAL_H\n WasmSerial_* _serial = &XOD_DEBUG_SERIAL;\n#else\n Stream* _serial = &XOD_DEBUG_SERIAL;\n#endif\n uint16_t _nodeId;\n bool _connected = false;\n static volatile uint16_t _pkgSize;\n void printPrefix() {\n writeCmd(XOD_PREFIX);\n _serial->print(transactionTime());\n writeCmd(COLON);\n _serial->print(_nodeId);\n writeCmd(COLON);\n }\n uint8_t readCmd(const char* text1, const char* text2 = nullptr, uint32_t timeout = 5000) {\n \/\/ setup buffers on stack & copy data from PROGMEM pointers\n char buf1[16] = { '\\0' };\n char buf2[16] = { '\\0' };\n if (text1 != nullptr)\n strcpy_P(buf1, text1);\n if (text2 != nullptr)\n strcpy_P(buf2, text2);\n uint8_t len1 = strlen(buf1);\n uint8_t len2 = strlen(buf2);\n uint8_t pos1 = 0;\n uint8_t pos2 = 0;\n \/\/ read chars until first match or timeout\n uint32_t stop = millis() + timeout;\n do {\n while (_serial->available()) {\n char c = _serial->read();\n pos1 = (c == buf1[pos1]) ? pos1 + 1 : 0;\n pos2 = (c == buf2[pos2]) ? pos2 + 1 : 0;\n if (len1 > 0 && pos1 == len1) {\n return 1;\n }\n if (len2 > 0 && pos2 == len2) {\n return 2;\n }\n }\n } while (millis() < stop);\n return 0;\n }\n bool cmdOK(const char* okResponse, const char* failResponse = nullptr, uint32_t timeout = 1000) {\n uint8_t res = readCmd(okResponse, failResponse, timeout);\n return res == 1;\n }\n void writeCmd(const char* text1 = nullptr, const char* text2 = nullptr) {\n char buf[16] = { '\\0' };\n strcpy_P(buf, text1);\n _serial->print(buf);\n if (text2 == EOL) {\n _serial->println();\n } else if (text2 != nullptr) {\n strcpy_P(buf, text2);\n _serial->print(buf);\n }\n }\npublic:\n TetheringInternet(uint16_t nodeId) {\n _nodeId = nodeId;\n }\n\n static bool isReceiving() {\n return _pkgSize > 0;\n }\n static void beginReceiving(uint16_t pkgSize) {\n _pkgSize = pkgSize;\n }\n\n bool kick() {\n printPrefix();\n writeCmd(AT, EOL);\n _serial->flush();\n uint8_t res = readCmd(OK, ERROR);\n return res == 1;\n }\n bool openTcp(XString host, uint32_t port, uint16_t keepAlive = 0) {\n printPrefix();\n \/\/ Command + connection type\n writeCmd(CIPSTART);\n writeCmd(TCP);\n writeCmd(COMMA_2);\n \/\/ Host\n for (auto it = host.iterate(); it; ++it)\n _serial->print((char)*it);\n \/\/ Port\n writeCmd(COMMA_1);\n char _port[32];\n xod::formatNumber(port, 0, _port);\n _serial->print(port);\n \/\/ Delimiter\n writeCmd(COMMA);\n \/\/ Keep alive\n char _keepAlive[1];\n xod::formatNumber(keepAlive, 0, _keepAlive);\n _serial->println(keepAlive);\n _serial->flush();\n\n _connected = readCmd(OK, ERROR) == 1;\n return _connected;\n }\n bool send(XString req) {\n printPrefix();\n\n size_t len = length(req);\n char reqLen[len];\n xod::formatNumber(len, 0, reqLen);\n\n writeCmd(CIPSEND);\n _serial->println(reqLen);\n _serial->flush();\n\n bool prompt = cmdOK(PROMPT, LINK_IS_NOT);\n if (!prompt)\n return false;\n\n \/\/ Send message in a special way to wrap each line with a XOD prefix\n bool nextLine = true;\n bool cr = false;\n for (auto it = req.iterate(); it; ++it) {\n if (nextLine) {\n printPrefix();\n nextLine = false;\n }\n if (*it == '\\r') {\n cr = true;\n _serial->print(\"\\\\r\");\n } else if (*it == '\\n') {\n nextLine = true;\n _serial->print(\"\\\\n\");\n if (cr) _serial->print('\\r');\n _serial->print('\\n');\n } else {\n _serial->print((char)*it);\n }\n }\n \/\/ Ensure the latest line of request sent\n if (!nextLine) {\n _serial->println();\n }\n\n _serial->flush();\n\n return cmdOK(SEND_OK, nullptr, 5000);\n }\n bool isConnected() {\n return _connected;\n }\n bool isAvailable() {\n return _serial->available();\n }\n bool receiveByte(char* outBuff, uint32_t timeout = 5000) {\n uint32_t stop = millis() + timeout;\n uint32_t a = 0;\n do {\n if (isAvailable() && isReceiving()) {\n *outBuff = _serial->read();\n _pkgSize--;\n \/\/ Response with ACK character to request next chunks\n if (_pkgSize == 0) {\n printPrefix();\n _serial->println('\\6');\n }\n if (*outBuff == '\\4') {\n \/\/ end of transmittion symbol == connection closed\n _connected = false;\n _pkgSize = 0;\n }\n return true;\n }\n } while (a < stop);\n return false;\n }\n uint32_t getIP() {\n printPrefix();\n writeCmd(CIFSR, EOL);\n uint8_t code = readCmd(STAIP, ERROR);\n if (code == 1) {\n \/\/ found ip\n uint32_t ip[4];\n ip[0] = _serial->parseInt();\n _serial->read(); \/\/ .\n ip[1] = _serial->parseInt();\n _serial->read(); \/\/ .\n ip[2] = _serial->parseInt();\n _serial->read(); \/\/ .\n ip[3] = _serial->parseInt();\n\n if ((ip[0] | ip[1] | ip[2] | ip[3]) >= 0x100)\n return 0;\n\n return ip[0] + ip[1] * 0x100 + ip[2] * 0x10000ul + ip[3] * 0x1000000ul;\n }\n return 0;\n }\n bool close(uint8_t linkId) {\n \/\/ TODO: MUX\n printPrefix();\n writeCmd(CIPCLOSE, EOL);\n return readCmd(OK, ERROR) == 1;\n }\n};\n\nvolatile uint16_t TetheringInternet::_pkgSize = 0;\n\nstruct State {\n uint8_t mem[sizeof(TetheringInternet)];\n TetheringInternet* inet;\n};\n\nusing Type = TetheringInternet*;\n\n{{ GENERATED_CODE }}\n\nvoid evaluate(Context ctx) {\n auto state = getState(ctx);\n state->inet = new (state->mem) TetheringInternet(getNodeId(ctx));\n emitValue<output_INET>(ctx, state->inet);\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\nCopyright (c) 2007, Regents of the University of Alaska\n\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:\n\n * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and\/or other materials provided with the distribution.\n * Neither the name of the Geographic Information Network of Alaska nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\nLIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\nA PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR\nCONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\nEXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\nPROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\nPROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\nLIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\nNEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\nSOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*\/\n\n\n\n#include \"common.h\"\n#include \"polygon.h\"\n#include \"debugplot.h\"\n\n#ifdef MIN\n#undef MIN\n#endif\n#define MIN(a,b) ((a)<(b)?(a):(b))\n\n#ifndef bool\n#define uint8_t bool\n#endif\n#ifndef false\n#define false 0\n#endif\n#ifndef true\n#define true (!false)\n#endif\n\n\/*\nstatic inline double sqlen(vertex_t v0, vertex_t v1) {\n\tdouble dx = v1.x - v0.x;\n\tdouble dy = v1.y - v0.y;\n\treturn dx*dx + dy*dy;\n}\n\nstatic int is_seg_good(ring_t *ring, int v0_idx) {\n\tdouble radius = 10.0; \/\/ FIXME\n\tdouble rad2 = radius*radius;\n\n\tvertex_t *pts = ring->pts;\n\tint npts = ring->npts;\n\n\tint vl_idx = v0_idx;\n\tint vr_idx = (v0_idx+1) % npts;\n\tvertex_t v0 = pts[vl_idx];\n\tvertex_t v1 = pts[vr_idx];\n\tvertex_t center;\n\tcenter.x = (v0.x + v1.x) \/ 2.0;\n\tcenter.y = (v0.y + v1.y) \/ 2.0;\n\n\tfor(;;) {\n\t\tif(sqlen(center, pts[vr_idx]) > rad2) break;\n\t\tvr_idx = (vr_idx+1) % npts;\n\t\tif(vr_idx == vl_idx) return 0; \/\/ FIXME\n\t}\n\tfor(;;) {\n\t\tif(sqlen(center, pts[vl_idx]) > rad2) break;\n\t\tvl_idx = (vl_idx+npts-1) % npts;\n\t\tif(vr_idx == vl_idx) return 0; \/\/ FIXME\n\t}\n\n\tdouble up=0, dn=0, lf=0, rt=0;\n\tfor(int i=vl_idx; i!=vr_idx; i=(i+1)%npts) {\n\t\tvertex_t v0 = pts[i];\n\t\tvertex_t v1 = pts[(i+1)%npts];\n\t\tdouble dx = v1.x - v0.x;\n\t\tdouble dy = v1.y - v0.y;\n\t\tif(dx<0) lf += -dx;\n\t\tif(dx>0) rt += dx;\n\t\tif(dy<0) dn += -dy;\n\t\tif(dy>0) up += dy;\n\t}\n\tdouble loopback = MIN(up,dn) + MIN(lf,rt);\n\n\treturn loopback == 0;\n}\n\nring_t pinch_excursions(ring_t *ring, report_image_t *dbuf) {\n\tfor(int i=0; i<ring->npts; i++) {\n\t\tvertex_t v0 = ring->pts[i];\n\t\tvertex_t v1 = ring->pts[(i+1)%ring->npts];\n\t\tint good = is_seg_good(ring, i);\n\t\tif(good) plot_line(dbuf, v0, v1, 255, 0, 0);\n\t}\n\treturn *ring;\n}\n*\/\n\nstatic inline double seg_ang(vertex_t v0, vertex_t v1) {\n\tdouble dx = v1.x - v0.x;\n\tdouble dy = v1.y - v0.y;\n\treturn atan2(dy, dx);\n}\n\nstatic int find_bottom_pt(ring_t *ring) {\n\tdouble min = 0;\n\tint min_idx = -1;\n\tfor(int i=0; i<ring->npts; i++) {\n\t\tdouble y = ring->pts[i].y;\n\t\tif(i==0 || y<min) {\n\t\t\tmin = y;\n\t\t\tmin_idx = i;\n\t\t}\n\t}\n\treturn min_idx;\n}\n\nstatic int find_next_convex(ring_t *ring, int start_idx, int limit_idx, double start_ang, double *ang_out) {\n\tint npts = ring->npts;\n\tvertex_t *pts = ring->pts;\n\tvertex_t v0 = pts[start_idx];\n\tdouble min_angdiff = 2.0 * M_PI;\n\tint best_vert = -1;\n\tdouble best_segang = 0;\n\tfor(int i=(start_idx+1)%npts; i!=limit_idx; i=(i+1)%npts) {\n\t\tvertex_t v1 = pts[i];\n\t\tdouble segang = seg_ang(v0, v1);\n\t\tdouble angdiff = segang - start_ang;\n\t\twhile(angdiff < 0) angdiff += 2.0 * M_PI;\n\t\twhile(angdiff >= 2.0 * M_PI) angdiff -= 2.0 * M_PI;\n\t\tif(angdiff < min_angdiff) {\n\t\t\tmin_angdiff = angdiff;\n\t\t\tbest_vert = i;\n\t\t\tbest_segang = segang;\n\t\t}\n\t}\n\tif(ang_out) *ang_out = best_segang;\n\treturn best_vert;\n}\n\nstatic bool *find_chull(ring_t *ring) {\n\tbool *keep = (bool *)malloc_or_die(sizeof(bool) * ring->npts);\n\tfor(int i=0; i<ring->npts; i++) keep[i] = false;\n\n\tint start_idx = find_bottom_pt(ring);\n\tkeep[start_idx] = true;\n\tdouble ang = -M_PI;\n\tint idx = start_idx;\n\tfor(;;) {\n\t\tidx = find_next_convex(ring, idx, start_idx, ang, &ang);\n\t\tif(idx < 0) break;\n\t\tkeep[idx] = true;\n\t}\n\n\treturn keep;\n}\n\nstatic double subring_area(ring_t *ring, int from, int to) {\n\tint npts = ring->npts;\n\tvertex_t *pts = ring->pts;\n\n\tdouble accum = 0;\n\tint i;\n\tfor(i=from; ; i=(i+1)%npts) {\n\t\tint i2 = i==to ? from : (i+1)%npts;\n\t\tdouble x0 = pts[i].x;\n\t\tdouble y0 = pts[i].y;\n\t\tdouble x1 = pts[i2].x;\n\t\tdouble y1 = pts[i2].y;\n\t\taccum += x0*y1 - x1*y0;\n\t\tif(i == to) break;\n\t}\n\treturn accum \/ 2.0;\n}\n\nstatic void refine(ring_t *ring, bool *keep) {\n\tint npts = ring->npts;\n\tvertex_t *pts = ring->pts;\n\tfor(int i=0; i<npts; i++) {\n\t\tif(!keep[i]) continue;\n\t\tfor(;;) {\n\t\t\tint j;\n\t\t\tfor(j=(i+1)%npts; j!=i; j=(j+1)%npts) {\n\t\t\t\tif(keep[j]) break;\n\t\t\t}\n\t\t\tdouble area = subring_area(ring, i, j);\n\t\t\tarea = fabs(area); \/\/ FIXME\n\t\t\tprintf(\"area = %g\\n\", area);\n\t\t\tif(area > 1000) {\n\t\t\t\tif(j>i) keep[(i+j)\/2] = true;\n\t\t\t\telse keep[((i+j+npts)\/2)%npts] = true;\n\t\t\t} else {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n}\n\nring_t pinch_excursions(ring_t *ring, report_image_t *dbuf) {\n\tint npts = ring->npts;\n\tvertex_t *pts = ring->pts;\n\n\tif(!ring_is_ccw(ring)) {\n\t\t\/\/ reverse ring to make it CCW\n\t\tfor(int i=0; i<npts\/2; i++) {\n\t\t\tvertex_t tmp = pts[i];\n\t\t\tpts[i] = pts[npts-1-i];\n\t\t\tpts[npts-1-i] = tmp;\n\t\t}\n\t}\n\n\tbool *keep = find_chull(ring);\n\n\trefine(ring, keep);\n\n\tint nkeep = 0;\n\tfor(int i=0; i<npts; i++) {\n\t\tif(keep[i]) nkeep++;\n\t}\n\n\tring_t outring = *ring;\n\toutring.npts = nkeep;\n\toutring.pts = (vertex_t *)malloc_or_die(sizeof(vertex_t) * outring.npts);\n\tint oidx=0;\n\tfor(int i=0; i<npts; i++) {\n\t\tif(keep[i]) outring.pts[oidx++] = pts[i];\n\t}\n\n\tfor(int i=0; i<outring.npts; i++) {\n\t\tvertex_t v0 = outring.pts[i];\n\t\tvertex_t v1 = outring.pts[(i+1)%outring.npts];\n\t\tplot_line(dbuf, v0, v1, 255, 0, 0);\n\t}\n\n\treturn outring;\n}\n<commit_msg>more pincher<commit_after>\/*\nCopyright (c) 2007, Regents of the University of Alaska\n\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:\n\n * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and\/or other materials provided with the distribution.\n * Neither the name of the Geographic Information Network of Alaska nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\nLIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\nA PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR\nCONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\nEXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\nPROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\nPROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\nLIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\nNEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\nSOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*\/\n\n\n\n#include \"common.h\"\n#include \"polygon.h\"\n#include \"debugplot.h\"\n\n#ifdef MIN\n#undef MIN\n#endif\n#define MIN(a,b) ((a)<(b)?(a):(b))\n\n#ifndef bool\n#define uint8_t bool\n#endif\n#ifndef false\n#define false 0\n#endif\n#ifndef true\n#define true (!false)\n#endif\n\n\/*\nstatic inline double sqlen(vertex_t v0, vertex_t v1) {\n\tdouble dx = v1.x - v0.x;\n\tdouble dy = v1.y - v0.y;\n\treturn dx*dx + dy*dy;\n}\n\nstatic int is_seg_good(ring_t *ring, int v0_idx) {\n\tdouble radius = 10.0; \/\/ FIXME\n\tdouble rad2 = radius*radius;\n\n\tvertex_t *pts = ring->pts;\n\tint npts = ring->npts;\n\n\tint vl_idx = v0_idx;\n\tint vr_idx = (v0_idx+1) % npts;\n\tvertex_t v0 = pts[vl_idx];\n\tvertex_t v1 = pts[vr_idx];\n\tvertex_t center;\n\tcenter.x = (v0.x + v1.x) \/ 2.0;\n\tcenter.y = (v0.y + v1.y) \/ 2.0;\n\n\tfor(;;) {\n\t\tif(sqlen(center, pts[vr_idx]) > rad2) break;\n\t\tvr_idx = (vr_idx+1) % npts;\n\t\tif(vr_idx == vl_idx) return 0; \/\/ FIXME\n\t}\n\tfor(;;) {\n\t\tif(sqlen(center, pts[vl_idx]) > rad2) break;\n\t\tvl_idx = (vl_idx+npts-1) % npts;\n\t\tif(vr_idx == vl_idx) return 0; \/\/ FIXME\n\t}\n\n\tdouble up=0, dn=0, lf=0, rt=0;\n\tfor(int i=vl_idx; i!=vr_idx; i=(i+1)%npts) {\n\t\tvertex_t v0 = pts[i];\n\t\tvertex_t v1 = pts[(i+1)%npts];\n\t\tdouble dx = v1.x - v0.x;\n\t\tdouble dy = v1.y - v0.y;\n\t\tif(dx<0) lf += -dx;\n\t\tif(dx>0) rt += dx;\n\t\tif(dy<0) dn += -dy;\n\t\tif(dy>0) up += dy;\n\t}\n\tdouble loopback = MIN(up,dn) + MIN(lf,rt);\n\n\treturn loopback == 0;\n}\n\nring_t pinch_excursions(ring_t *ring, report_image_t *dbuf) {\n\tfor(int i=0; i<ring->npts; i++) {\n\t\tvertex_t v0 = ring->pts[i];\n\t\tvertex_t v1 = ring->pts[(i+1)%ring->npts];\n\t\tint good = is_seg_good(ring, i);\n\t\tif(good) plot_line(dbuf, v0, v1, 255, 0, 0);\n\t}\n\treturn *ring;\n}\n*\/\n\nstatic inline double seg_ang(vertex_t v0, vertex_t v1) {\n\tdouble dx = v1.x - v0.x;\n\tdouble dy = v1.y - v0.y;\n\treturn atan2(dy, dx);\n}\n\nstatic int find_bottom_pt(ring_t *ring) {\n\tdouble min = 0;\n\tint min_idx = -1;\n\tfor(int i=0; i<ring->npts; i++) {\n\t\tdouble y = ring->pts[i].y;\n\t\tif(i==0 || y<min) {\n\t\t\tmin = y;\n\t\t\tmin_idx = i;\n\t\t}\n\t}\n\treturn min_idx;\n}\n\nstatic int find_next_convex(ring_t *ring, int start_idx, int limit_idx, double start_ang, double *ang_out) {\n\tint npts = ring->npts;\n\tvertex_t *pts = ring->pts;\n\tvertex_t v0 = pts[start_idx];\n\tdouble min_angdiff = 2.0 * M_PI;\n\tint best_vert = -1;\n\tdouble best_segang = 0;\n\tfor(int i=(start_idx+1)%npts; i!=limit_idx; i=(i+1)%npts) {\n\t\tvertex_t v1 = pts[i];\n\t\tdouble segang = seg_ang(v0, v1);\n\/\/printf(\"start_ang=%g*PI, seg_ang=%g*PI\\n\", start_ang\/M_PI, segang\/M_PI);\n\t\tdouble angdiff = segang - start_ang;\n\t\twhile(angdiff < 0) angdiff += 2.0 * M_PI;\n\t\twhile(angdiff >= 2.0 * M_PI) angdiff -= 2.0 * M_PI;\n\t\tif(angdiff < min_angdiff) {\n\t\t\tmin_angdiff = angdiff;\n\t\t\tbest_vert = i;\n\t\t\tbest_segang = segang;\n\t\t}\n\t}\n\tif(best_vert < 0) {\n\t\treturn limit_idx;\n\t} else if(min_angdiff >= M_PI) {\n\t\t\/\/fatal_error(\"point on wrong side of half-plane (ang=%g*PI)\", min_angdiff\/M_PI);\n\t\treturn -1;\n\t} else {\n\t\tif(ang_out) *ang_out = best_segang;\n\t\treturn best_vert;\n\t}\n}\n\nstatic bool *find_chull(ring_t *ring) {\n\tbool *keep = (bool *)malloc_or_die(sizeof(bool) * ring->npts);\n\tfor(int i=0; i<ring->npts; i++) keep[i] = false;\n\n\tint start_idx = find_bottom_pt(ring);\n\tkeep[start_idx] = true;\n\tdouble ang = 0;\n\tint idx = start_idx;\n\tfor(;;) {\n\t\tidx = find_next_convex(ring, idx, start_idx, ang, &ang);\n\t\tif(idx < 0) fatal_error(\"could not get convex hull\");\n\t\tif(idx == start_idx) break;\n\t\tkeep[idx] = true;\n\t}\n\n\treturn keep;\n}\n\nstatic double subring_area(ring_t *ring, int from, int to) {\n\tint npts = ring->npts;\n\tvertex_t *pts = ring->pts;\n\n\tdouble accum = 0;\n\tint i;\n\tfor(i=from; ; i=(i+1)%npts) {\n\t\tint i2 = i==to ? from : (i+1)%npts;\n\t\tdouble x0 = pts[i].x;\n\t\tdouble y0 = pts[i].y;\n\t\tdouble x1 = pts[i2].x;\n\t\tdouble y1 = pts[i2].y;\n\t\taccum -= x0*y1 - x1*y0;\n\t\tif(i == to) break;\n\t}\n\tif(accum < 0) {\n\t\t\/\/ FIXME\n\t\tprintf(\"subring_area was negative\\n\");\n\t\t\/\/fatal_error(\"subring_area was negative\");\n\t}\n\treturn accum \/ 2.0;\n}\n\nstatic int next_keep(int npts, bool *keep, int i) {\n\tfor(int j=(i+1)%npts; j!=i; j=(j+1)%npts) {\n\t\tif(keep[j]) return j;\n\t}\n\treturn i;\n}\n\nstatic int prev_keep(int npts, bool *keep, int i) {\n\tfor(int j=(i+npts-1)%npts; j!=i; j=(j+npts-1)%npts) {\n\t\tif(keep[j]) return j;\n\t}\n\treturn i;\n}\n\nstatic int reach_point(ring_t *ring, bool *keep, int from, int to, double ang) {\n\tint npts = ring->npts;\n\tvertex_t *pts = ring->pts;\n\n\tint idx = from;\n\tfor(;;) {\n\t\tidx = find_next_convex(ring, idx, to, ang, &ang);\n\t\tif(idx < 0) return 1;\n\t\tkeep[idx] = true;\n\t\tif(idx == to) break;\n\t}\n\tfor(int pk=from;;) {\n\t\tint nk = next_keep(npts, keep, pk);\n\t\tif(nk == to) return 0;\n\n\t\tfor(int i=0; i<npts; i++) {\n\t\t\tint i2 = (i+1)%npts;\n\t\t\tif(i==pk || i==nk || i2==pk || i2==nk) continue;\n\t\t\tif(line_intersects_line(pts[pk], pts[nk], pts[i], pts[i2], 0)) return 1;\n\t\t}\n\n\t\tpk = nk;\n\t}\n}\n\n\/*\nstatic int chord_crosses_arc(ring_t *ring, int c0, int c1, int from, int to) {\n\tint npts = ring->npts;\n\tvertex_t *pts = ring->pts;\n\n\tfor(int i=from; i!=to; i=(i+1)%npts) {\n\t\tint i2 = (i+1)%npts;\n\t\tif(i==c0 || i==c1 || i2==c0 || i2==c1) continue;\n\t\tif(line_intersects_line(pts[c0], pts[c1], pts[i], pts[i2], 0)) return 1;\n\t}\n\treturn 0;\n}\n*\/\n\nstatic int refine_seg(ring_t *ring, bool *keep_orig, int from, int to) {\n\tint npts = ring->npts;\n\tvertex_t *pts = ring->pts;\n\tbool *keep_new = (bool *)malloc_or_die(sizeof(bool) * npts);\n\n\tint mid; \/\/ FIXME\n\tif(to>from) mid = (from+to)\/2;\n\telse mid = ((from+to+npts)\/2)%npts;\n\n\tdouble best_area = 0;\n\n\tfor(int i=(from+1)%npts; i!=to; i=(i+1)%npts) {\n\t\t\/\/if(i != mid) continue; \/\/ FIXME\n\t\tmemcpy(keep_new, keep_orig, sizeof(bool) * npts);\n\t\tkeep_new[i] = true;\n\n\t\tdouble ang = seg_ang(pts[from], pts[to]);\n\t\tint error = reach_point(ring, keep_new, from, i, ang);\n\t\tif(error) {\n\t\t\tcontinue; \/\/ FIXME\n\t\t\tfatal_error(\"could not reach middle point\");\n\t\t}\n\n\t\tint pk = prev_keep(npts, keep_new, i);\n\t\tif(pk == i) fatal_error(\"pk == i\");\n\t\tang = seg_ang(pts[i], pts[pk]);\n\t\terror = reach_point(ring, keep_new, i, to, ang);\n\t\tif(error) continue;\n\n\t\tdouble area = 0;\n\t\tfor(int pk=from;;) {\n\t\t\tint nk = next_keep(npts, keep_new, pk);\n\t\t\tif(nk == to) break;\n\t\t\tarea += subring_area(ring, pk, nk);\n\t\t\tpk = nk;\n\t\t}\n\t\t\/\/printf(\"a2 = %g\\n\", area);\n\n\t\tif(area > best_area) {\n\t\t\tbest_area = area;\n\t\t\tmemcpy(keep_orig, keep_new, sizeof(bool) * npts);\n\t\t}\n\t}\n\treturn best_area == 0;\n}\n\n\nstatic void refine_ring(ring_t *ring, bool *keep) {\n\tint npts = ring->npts;\n\tint nref=0; \/\/ FIXME\n\tfor(int i=0; i<npts; i++) {\n\t\tif(!keep[i]) continue;\n\t\tfor(;;) {\n\t\t\tint j = next_keep(npts, keep, i);\n\t\t\tdouble area = subring_area(ring, i, j);\n\t\t\t\/\/printf(\"area = %g\\n\", area);\n\t\t\tif(area > 1000) { \/\/ FIXME\n\t\t\t\tint error = refine_seg(ring, keep, i, j);\n\t\t\t\tif(error) break;\n\t\t\t\tnref++;\n\t\t\t\tprintf(\"nref=%d\\n\", nref);\n\t\t\t\t\/\/if(nref > 0) return; \/\/ FIXME\n\t\t\t} else {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n}\n\nring_t pinch_excursions(ring_t *ring, report_image_t *dbuf) {\n\tint npts = ring->npts;\n\tvertex_t *pts = ring->pts;\n\n\tif(!ring_is_ccw(ring)) {\n\t\t\/\/ reverse ring to make it CCW\n\t\tfor(int i=0; i<npts\/2; i++) {\n\t\t\tvertex_t tmp = pts[i];\n\t\t\tpts[i] = pts[npts-1-i];\n\t\t\tpts[npts-1-i] = tmp;\n\t\t}\n\t}\n\n\tbool *keep = find_chull(ring);\n\n\trefine_ring(ring, keep);\n\n\tint nkeep = 0;\n\tfor(int i=0; i<npts; i++) {\n\t\tif(keep[i]) nkeep++;\n\t}\n\n\tring_t outring = *ring;\n\toutring.npts = nkeep;\n\toutring.pts = (vertex_t *)malloc_or_die(sizeof(vertex_t) * outring.npts);\n\tint oidx=0;\n\tfor(int i=0; i<npts; i++) {\n\t\tif(keep[i]) outring.pts[oidx++] = pts[i];\n\t}\n\n\tfor(int i=0; i<outring.npts; i++) {\n\t\tvertex_t v0 = outring.pts[i];\n\t\tvertex_t v1 = outring.pts[(i+1)%outring.npts];\n\t\tplot_line(dbuf, v0, v1, 255, 0, 0);\n\t}\n\n\treturn outring;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2011 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/ui\/views\/dropdown_bar_host.h\"\n\n#include \"base\/logging.h\"\n\nNativeWebKeyboardEvent DropdownBarHost::GetKeyboardEvent(\n const TabContents* contents,\n const views::KeyEvent& key_event) {\n \/\/ TODO(beng):\n NOTIMPLEMENTED();\n return NativeWebKeyboardEvent();\n}\n\nvoid DropdownBarHost::SetWidgetPositionNative(const gfx::Rect& new_pos,\n bool no_redraw) {\n \/\/ TODO(beng):\n NOTIMPLEMENTED();\n}\n<commit_msg>Gets the findbar to at least show up.<commit_after>\/\/ Copyright (c) 2011 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/ui\/views\/dropdown_bar_host.h\"\n\n#include \"base\/logging.h\"\n#include \"ui\/aura\/window.h\"\n#include \"views\/widget\/widget.h\"\n\nNativeWebKeyboardEvent DropdownBarHost::GetKeyboardEvent(\n const TabContents* contents,\n const views::KeyEvent& key_event) {\n return NativeWebKeyboardEvent(key_event.native_event());\n}\n\nvoid DropdownBarHost::SetWidgetPositionNative(const gfx::Rect& new_pos,\n bool no_redraw) {\n if (!host_->IsVisible())\n host_->GetNativeView()->Show();\n host_->GetNativeView()->SetBounds(new_pos);\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n Copyright © 2010, 2011, 2012 Vladimír Vondruš <mosra@centrum.cz>\n\n This file is part of Magnum.\n\n Magnum is free software: you can redistribute it and\/or modify\n it under the terms of the GNU Lesser General Public License version 3\n only, as published by the Free Software Foundation.\n\n Magnum is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU Lesser General Public License version 3 for more details.\n*\/\n\n#include <Utility\/Debug.h>\n\n#include \"Context.h\"\n#include \"Platform\/WindowlessGlxApplication.h\"\n\nnamespace Magnum {\n\nclass MagnumInfo: public Platform::WindowlessGlxApplication {\n public:\n MagnumInfo(int& argc, char** argv);\n\n inline int exec() override { return 0; }\n};\n\nMagnumInfo::MagnumInfo(int& argc, char** argv): WindowlessGlxApplication(argc, argv) {\n Context* c = Context::current();\n\n Debug() << \"\";\n Debug() << \" +---------------------------------------------------------+\";\n Debug() << \" | Information about Magnum engine and OpenGL capabilities |\";\n Debug() << \" +---------------------------------------------------------+\";\n Debug() << \"\";\n\n Debug() << \"Used application: Platform::WindowlessGlxApplication\";\n {\n Debug d;\n d << \"Compilation flags:\";\n #ifdef MAGNUM_TARGET_GLES\n d << \"MAGNUM_TARGET_GLES\";\n #endif\n #ifdef MAGNUM_TARGET_GLES2\n d << \"MAGNUM_TARGET_GLES2\";\n #endif\n #ifdef MAGNUM_TARGET_NACL\n d << \"MAGNUM_TARGET_NACL\";\n #endif\n #ifdef CORRADE_GCC46_COMPATIBILITY\n d << \"CORRADE_GCC46_COMPATIBILITY\";\n #endif\n }\n Debug() << \"\";\n\n Debug() << \"Vendor:\" << c->vendorString();\n Debug() << \"Renderer:\" << c->rendererString();\n Debug() << \"OpenGL version:\" << c->version() << '(' + c->versionString() + ')';\n Debug() << \"GLSL version:\" << c->version() << '(' + c->shadingLanguageVersionString() + ')';\n Debug() << \"\";\n\n \/* Get first future (not supported) version *\/\n std::vector<Version> versions{\n #ifndef MAGNUM_TARGET_GLES\n Version::GL300,\n Version::GL310,\n Version::GL320,\n Version::GL330,\n Version::GL400,\n Version::GL410,\n Version::GL420,\n Version::GL430,\n #else\n Version::GLES200,\n Version::GLES300,\n #endif\n Version::None\n };\n std::size_t future = 0;\n while(versions[future] != Version::None && c->isVersionSupported(versions[future]))\n ++future;\n\n \/* Display supported OpenGL extensions from unsupported versions *\/\n for(std::size_t i = future; i != versions.size(); ++i) {\n if(versions[i] != Version::None)\n Debug() << versions[i] << \"extension support:\";\n else Debug() << \"Vendor extension support:\";\n\n for(const auto& extension: Extension::extensions(versions[i])) {\n std::string extensionName = extension.string();\n Debug d;\n d << \" \" << extensionName << std::string(60-extensionName.size(), ' ');\n if(c->isExtensionSupported(extension))\n d << \"SUPPORTED\";\n else if(c->isVersionSupported(extension.requiredVersion()))\n d << \" - \";\n else\n d << \" --- \";\n }\n\n Debug() << \"\";\n }\n}\n\n}\n\nMAGNUM_WINDOWLESSGLXAPPLICATION_MAIN(Magnum::MagnumInfo)\n<commit_msg>No trailing whitespace in magnum-info utility.<commit_after>\/*\n Copyright © 2010, 2011, 2012 Vladimír Vondruš <mosra@centrum.cz>\n\n This file is part of Magnum.\n\n Magnum is free software: you can redistribute it and\/or modify\n it under the terms of the GNU Lesser General Public License version 3\n only, as published by the Free Software Foundation.\n\n Magnum is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU Lesser General Public License version 3 for more details.\n*\/\n\n#include <Utility\/Debug.h>\n\n#include \"Context.h\"\n#include \"Platform\/WindowlessGlxApplication.h\"\n\nnamespace Magnum {\n\nclass MagnumInfo: public Platform::WindowlessGlxApplication {\n public:\n MagnumInfo(int& argc, char** argv);\n\n inline int exec() override { return 0; }\n};\n\nMagnumInfo::MagnumInfo(int& argc, char** argv): WindowlessGlxApplication(argc, argv) {\n Context* c = Context::current();\n\n Debug() << \"\";\n Debug() << \" +---------------------------------------------------------+\";\n Debug() << \" | Information about Magnum engine and OpenGL capabilities |\";\n Debug() << \" +---------------------------------------------------------+\";\n Debug() << \"\";\n\n Debug() << \"Used application: Platform::WindowlessGlxApplication\";\n {\n Debug d;\n d << \"Compilation flags:\";\n #ifdef MAGNUM_TARGET_GLES\n d << \"MAGNUM_TARGET_GLES\";\n #endif\n #ifdef MAGNUM_TARGET_GLES2\n d << \"MAGNUM_TARGET_GLES2\";\n #endif\n #ifdef MAGNUM_TARGET_NACL\n d << \"MAGNUM_TARGET_NACL\";\n #endif\n #ifdef CORRADE_GCC46_COMPATIBILITY\n d << \"CORRADE_GCC46_COMPATIBILITY\";\n #endif\n }\n Debug() << \"\";\n\n Debug() << \"Vendor:\" << c->vendorString();\n Debug() << \"Renderer:\" << c->rendererString();\n Debug() << \"OpenGL version:\" << c->version() << '(' + c->versionString() + ')';\n Debug() << \"GLSL version:\" << c->version() << '(' + c->shadingLanguageVersionString() + ')';\n Debug() << \"\";\n\n \/* Get first future (not supported) version *\/\n std::vector<Version> versions{\n #ifndef MAGNUM_TARGET_GLES\n Version::GL300,\n Version::GL310,\n Version::GL320,\n Version::GL330,\n Version::GL400,\n Version::GL410,\n Version::GL420,\n Version::GL430,\n #else\n Version::GLES200,\n Version::GLES300,\n #endif\n Version::None\n };\n std::size_t future = 0;\n while(versions[future] != Version::None && c->isVersionSupported(versions[future]))\n ++future;\n\n \/* Display supported OpenGL extensions from unsupported versions *\/\n for(std::size_t i = future; i != versions.size(); ++i) {\n if(versions[i] != Version::None)\n Debug() << versions[i] << \"extension support:\";\n else Debug() << \"Vendor extension support:\";\n\n for(const auto& extension: Extension::extensions(versions[i])) {\n std::string extensionName = extension.string();\n Debug d;\n d << \" \" << extensionName << std::string(60-extensionName.size(), ' ');\n if(c->isExtensionSupported(extension))\n d << \"SUPPORTED\";\n else if(c->isVersionSupported(extension.requiredVersion()))\n d << \" -\";\n else\n d << \" ---\";\n }\n\n Debug() << \"\";\n }\n}\n\n}\n\nMAGNUM_WINDOWLESSGLXAPPLICATION_MAIN(Magnum::MagnumInfo)\n<|endoftext|>"} {"text":"<commit_before>#include \"stickynote.h\"\n\n#include <QHostAddress>\n#include <QTcpServer>\n\n#include \"stickynoteconnection.h\"\n\nK_EXPORT_PLASMA_APPLET(stickynote, StickyNote)\n\nStickyNote::StickyNote(QObject *_parent, const QVariantList &_args)\n: Plasma::Applet(_parent, _args), m_server(0)\n{\n\tsetAspectRatioMode(Plasma::IgnoreAspectRatio);\n\tsetBackgroundHints(Plasma::Applet::NoBackground);\n\n\tresize(0, 0);\n}\n \nStickyNote::~StickyNote(void)\n{\n\tdelete m_server;\n}\n\nvoid\nStickyNote::init(void)\n{\n\tm_server = new QTcpServer(this);\n\t\n\tconnect(m_server, SIGNAL(newConnection()),\n\t this, SLOT(on_server_newConnection()));\n\n\t\/\/ TODO: make address and port customizable\n\tif (!m_server->listen(QHostAddress::LocalHost, 12345))\n\t\tsetFailedToLaunch(true,\n\t\t \"Failed, You might already have a StickyNotes plasmoid running.\");\n}\n \nvoid\nStickyNote::paintInterface(QPainter *_painter,\n const QStyleOptionGraphicsItem *_option, const QRect &_rect)\n{\n\tQ_UNUSED(_option);\n\tQ_UNUSED(_painter);\n\tQ_UNUSED(_rect);\n}\n\nvoid\nStickyNote::on_server_newConnection(void)\n{\n\tQTcpSocket *client;\n\n\tif ((client = m_server->nextPendingConnection()))\n\t\tnew StickyNoteConnection(*this, *client);\n}\n\n<commit_msg>Add missing i18n<commit_after>#include \"stickynote.h\"\n\n#include <QHostAddress>\n#include <QTcpServer>\n\n#include \"stickynoteconnection.h\"\n\nK_EXPORT_PLASMA_APPLET(stickynote, StickyNote)\n\nStickyNote::StickyNote(QObject *_parent, const QVariantList &_args)\n: Plasma::Applet(_parent, _args), m_server(0)\n{\n\tsetAspectRatioMode(Plasma::IgnoreAspectRatio);\n\tsetBackgroundHints(Plasma::Applet::NoBackground);\n\n\tresize(0, 0);\n}\n \nStickyNote::~StickyNote(void)\n{\n\tdelete m_server;\n}\n\nvoid\nStickyNote::init(void)\n{\n\tm_server = new QTcpServer(this);\n\t\n\tconnect(m_server, SIGNAL(newConnection()),\n\t this, SLOT(on_server_newConnection()));\n\n\t\/\/ TODO: make address and port customizable\n\tif (!m_server->listen(QHostAddress::LocalHost, 12345))\n\t\tsetFailedToLaunch(true,\n\t\t i18n(\"Failed, You might already have a StickyNotes plasmoid running.\"));\n}\n \nvoid\nStickyNote::paintInterface(QPainter *_painter,\n const QStyleOptionGraphicsItem *_option, const QRect &_rect)\n{\n\tQ_UNUSED(_option);\n\tQ_UNUSED(_painter);\n\tQ_UNUSED(_rect);\n}\n\nvoid\nStickyNote::on_server_newConnection(void)\n{\n\tQTcpSocket *client;\n\n\tif ((client = m_server->nextPendingConnection()))\n\t\tnew StickyNoteConnection(*this, *client);\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/**\n * Copyright © 2016 IBM Corporation\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n#include <iostream>\n#include <memory>\n#include <cstring>\n#include <cstdlib>\n#include <chrono>\n#include \"sensorset.hpp\"\n#include \"sensorcache.hpp\"\n#include \"hwmon.hpp\"\n#include \"sysfs.hpp\"\n#include \"mainloop.hpp\"\n\nusing namespace std::literals::chrono_literals;\n\nMainLoop::MainLoop(\n sdbusplus::bus::bus&& bus,\n const std::string& path,\n const char* prefix,\n const char* root)\n : _bus(std::move(bus)),\n _manager(sdbusplus::server::manager::manager(_bus, root)),\n _shutdown(false),\n _path(path),\n _prefix(prefix),\n _root(root),\n state()\n{\n if (_path.back() == '\/')\n {\n _path.pop_back();\n }\n}\n\nvoid MainLoop::shutdown() noexcept\n{\n _shutdown = true;\n}\n\nvoid MainLoop::run()\n{\n \/\/ Check sysfs for available sensors.\n auto sensors = std::make_unique<SensorSet>(_path);\n auto sensor_cache = std::make_unique<SensorCache>();\n\n for (auto& i : *sensors)\n {\n \/\/ Ignore inputs without a label.\n std::string envKey = \"LABEL_\" + i.first.first + i.first.second;\n std::string label;\n\n auto env = getenv(envKey.c_str());\n\n if (env)\n {\n label.assign(env);\n }\n\n if (label.empty())\n {\n continue;\n }\n\n \/\/ Get the initial value for the value interface.\n auto sysfsPath = make_sysfs_path(\n _path,\n i.first.first,\n i.first.second,\n hwmon::entry::input);\n int val = 0;\n read_sysfs(sysfsPath, val);\n\n Object o;\n std::string objectPath{_root};\n\n objectPath.append(\"\/\");\n objectPath.append(i.first.first);\n objectPath.append(\"\/\");\n objectPath.append(label);\n\n auto iface = std::make_shared<ValueObject>(_bus, objectPath.c_str());\n iface->value(val);\n o.emplace(InterfaceType::VALUE, iface);\n\n auto value = std::make_tuple(\n std::move(i.second),\n std::move(label),\n std::move(o));\n\n state[std::move(i.first)] = std::move(value);\n }\n\n {\n struct Free\n {\n void operator()(char* ptr) const\n {\n free(ptr);\n }\n };\n\n auto copy = std::unique_ptr<char, Free>(strdup(_path.c_str()));\n auto busname = std::string(_prefix) + '.' + basename(copy.get());\n _bus.request_name(busname.c_str());\n }\n\n \/\/ TODO: Issue#3 - Need to make calls to the dbus sensor cache here to\n \/\/ ensure the objects all exist?\n\n \/\/ Polling loop.\n while (!_shutdown)\n {\n \/\/ Iterate through all the sensors.\n for (auto& i : state)\n {\n auto& attrs = std::get<0>(i.second);\n if (attrs.find(hwmon::entry::input) != attrs.end())\n {\n \/\/ Read value from sensor.\n int value = 0;\n read_sysfs(make_sysfs_path(_path,\n i.first.first, i.first.second,\n hwmon::entry::input),\n value);\n\n \/\/ Update sensor cache.\n if (sensor_cache->update(i.first, value))\n {\n \/\/ TODO: Issue#4 - dbus event here.\n std::cout << i.first.first << i.first.second << \" = \"\n << value << std::endl;\n }\n }\n }\n\n \/\/ Respond to DBus\n _bus.process_discard();\n\n \/\/ Sleep until next interval.\n \/\/ TODO: Issue#5 - Make this configurable.\n \/\/ TODO: Issue#6 - Optionally look at polling interval sysfs entry.\n _bus.wait((1000000us).count());\n\n \/\/ TODO: Issue#7 - Should probably periodically check the SensorSet\n \/\/ for new entries.\n }\n}\n\n\/\/ vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4\n<commit_msg>Set Sensors.Value unit and scale properties<commit_after>\/**\n * Copyright © 2016 IBM Corporation\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n#include <iostream>\n#include <memory>\n#include <cstring>\n#include <cstdlib>\n#include <chrono>\n#include <algorithm>\n#include \"sensorset.hpp\"\n#include \"sensorcache.hpp\"\n#include \"hwmon.hpp\"\n#include \"sysfs.hpp\"\n#include \"mainloop.hpp\"\n\nusing namespace std::literals::chrono_literals;\n\nstatic constexpr auto typeAttrMap =\n{\n \/\/ 1 - hwmon class\n \/\/ 2 - unit\n \/\/ 3 - sysfs scaling factor\n std::make_tuple(\n hwmon::type::ctemp,\n ValueInterface::Unit::DegreesC,\n -3),\n std::make_tuple(\n hwmon::type::cfan,\n ValueInterface::Unit::RPMS,\n 0),\n std::make_tuple(\n hwmon::type::cvolt,\n ValueInterface::Unit::Volts,\n -3),\n};\n\nauto getHwmonType(decltype(typeAttrMap)::const_reference attrs)\n{\n return std::get<0>(attrs);\n}\n\nauto getUnit(decltype(typeAttrMap)::const_reference attrs)\n{\n return std::get<1>(attrs);\n}\n\nauto getScale(decltype(typeAttrMap)::const_reference attrs)\n{\n return std::get<2>(attrs);\n}\n\nMainLoop::MainLoop(\n sdbusplus::bus::bus&& bus,\n const std::string& path,\n const char* prefix,\n const char* root)\n : _bus(std::move(bus)),\n _manager(sdbusplus::server::manager::manager(_bus, root)),\n _shutdown(false),\n _path(path),\n _prefix(prefix),\n _root(root),\n state()\n{\n if (_path.back() == '\/')\n {\n _path.pop_back();\n }\n}\n\nvoid MainLoop::shutdown() noexcept\n{\n _shutdown = true;\n}\n\nvoid MainLoop::run()\n{\n \/\/ Check sysfs for available sensors.\n auto sensors = std::make_unique<SensorSet>(_path);\n auto sensor_cache = std::make_unique<SensorCache>();\n\n for (auto& i : *sensors)\n {\n \/\/ Ignore inputs without a label.\n std::string envKey = \"LABEL_\" + i.first.first + i.first.second;\n std::string label;\n\n auto env = getenv(envKey.c_str());\n\n if (env)\n {\n label.assign(env);\n }\n\n if (label.empty())\n {\n continue;\n }\n\n \/\/ Get the initial value for the value interface.\n auto sysfsPath = make_sysfs_path(\n _path,\n i.first.first,\n i.first.second,\n hwmon::entry::input);\n int val = 0;\n read_sysfs(sysfsPath, val);\n\n Object o;\n std::string objectPath{_root};\n\n objectPath.append(\"\/\");\n objectPath.append(i.first.first);\n objectPath.append(\"\/\");\n objectPath.append(label);\n\n auto iface = std::make_shared<ValueObject>(_bus, objectPath.c_str());\n iface->value(val);\n\n const auto& attrs = std::find_if(\n typeAttrMap.begin(),\n typeAttrMap.end(),\n [&](const auto & e)\n {\n return i.first.first == getHwmonType(e);\n });\n if (attrs != typeAttrMap.end())\n {\n iface->unit(getUnit(*attrs));\n iface->scale(getScale(*attrs));\n }\n\n o.emplace(InterfaceType::VALUE, iface);\n\n auto value = std::make_tuple(\n std::move(i.second),\n std::move(label),\n std::move(o));\n\n state[std::move(i.first)] = std::move(value);\n }\n\n {\n struct Free\n {\n void operator()(char* ptr) const\n {\n free(ptr);\n }\n };\n\n auto copy = std::unique_ptr<char, Free>(strdup(_path.c_str()));\n auto busname = std::string(_prefix) + '.' + basename(copy.get());\n _bus.request_name(busname.c_str());\n }\n\n \/\/ TODO: Issue#3 - Need to make calls to the dbus sensor cache here to\n \/\/ ensure the objects all exist?\n\n \/\/ Polling loop.\n while (!_shutdown)\n {\n \/\/ Iterate through all the sensors.\n for (auto& i : state)\n {\n auto& attrs = std::get<0>(i.second);\n if (attrs.find(hwmon::entry::input) != attrs.end())\n {\n \/\/ Read value from sensor.\n int value = 0;\n read_sysfs(make_sysfs_path(_path,\n i.first.first, i.first.second,\n hwmon::entry::input),\n value);\n\n \/\/ Update sensor cache.\n if (sensor_cache->update(i.first, value))\n {\n \/\/ TODO: Issue#4 - dbus event here.\n std::cout << i.first.first << i.first.second << \" = \"\n << value << std::endl;\n }\n }\n }\n\n \/\/ Respond to DBus\n _bus.process_discard();\n\n \/\/ Sleep until next interval.\n \/\/ TODO: Issue#5 - Make this configurable.\n \/\/ TODO: Issue#6 - Optionally look at polling interval sysfs entry.\n _bus.wait((1000000us).count());\n\n \/\/ TODO: Issue#7 - Should probably periodically check the SensorSet\n \/\/ for new entries.\n }\n}\n\n\/\/ vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4\n<|endoftext|>"} {"text":"<commit_before>\/\/ The libMesh Finite Element Library.\n\/\/ Copyright (C) 2002-2012 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner\n\n\/\/ This library is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU Lesser General Public\n\/\/ License as published by the Free Software Foundation; either\n\/\/ version 2.1 of the License, or (at your option) any later version.\n\n\/\/ This library is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ Lesser General Public License for more details.\n\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License along with this library; if not, write to the Free Software\n\/\/ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n\n\n\n\/\/ Local includes\n#include \"elem.h\"\n#include \"fe.h\"\n#include \"fe_interface.h\"\n\nnamespace libMesh\n{\n\n \/\/ ------------------------------------------------------------\n \/\/ Hierarchic-specific implementations\n\n \/\/ Anonymous namespace for local helper functions\n namespace {\n\n void l2_hierarchic_nodal_soln(const Elem* elem,\n\t\t\t\t const Order order,\n\t\t\t\t const std::vector<Number>& elem_soln,\n\t\t\t\t std::vector<Number>& nodal_soln,\n\t\t\t\t unsigned Dim)\n {\n const unsigned int n_nodes = elem->n_nodes();\n\n const ElemType elem_type = elem->type();\n\n nodal_soln.resize(n_nodes);\n\n const Order totalorder = static_cast<Order>(order + elem->p_level());\n\n \/\/ FEType object to be passed to various FEInterface functions below.\n FEType fe_type(totalorder, L2_HIERARCHIC);\n\n switch (totalorder)\n\t{\n\t \/\/ Constant shape functions\n\tcase CONSTANT:\n\t {\n\t libmesh_assert (elem_soln.size() == 1);\n\n\t const Number val = elem_soln[0];\n\n\t for (unsigned int n=0; n<n_nodes; n++)\n\t nodal_soln[n] = val;\n\n\t return;\n\t }\n\n\n\t \/\/ For other orders do interpolation at the nodes\n\t \/\/ explicitly.\n\tdefault:\n\t {\n\n\t const unsigned int n_sf =\n\t \/\/ FE<Dim,T>::n_shape_functions(elem_type, totalorder);\n\t FEInterface::n_shape_functions(Dim, fe_type, elem_type);\n\n\t std::vector<Point> refspace_nodes;\n\t FEBase::get_refspace_nodes(elem_type,refspace_nodes);\n\t libmesh_assert (refspace_nodes.size() == n_nodes);\n\n\t for (unsigned int n=0; n<n_nodes; n++)\n\t {\n\t\tlibmesh_assert (elem_soln.size() == n_sf);\n\n\t\t\/\/ Zero before summation\n\t\tnodal_soln[n] = 0;\n\n\t\t\/\/ u_i = Sum (alpha_i phi_i)\n\t\tfor (unsigned int i=0; i<n_sf; i++)\n\t\t nodal_soln[n] += elem_soln[i] *\n\t\t \/\/ FE<Dim,T>::shape(elem, order, i, mapped_point);\n\t\t FEInterface::shape(Dim, fe_type, elem, i, refspace_nodes[n]);\n\t }\n\n\t return;\n\t }\n\t}\n } \/\/ l2_hierarchic_nodal_soln()\n\n\n\n\n unsigned int l2_hierarchic_n_dofs(const ElemType t, const Order o)\n {\n libmesh_assert (o > 0);\n switch (t)\n\t{\n\tcase NODEELEM:\n\t return 1;\n\tcase EDGE2:\n\tcase EDGE3:\n\t return (o+1);\n\tcase QUAD4:\n\tcase QUAD8:\n\tcase QUAD9:\n\t return ((o+1)*(o+1));\n\tcase HEX8:\n\tcase HEX20:\n\tcase HEX27:\n\t return ((o+1)*(o+1)*(o+1));\n\tcase TRI6:\n\t return ((o+1)*(o+2)\/2);\n\tdefault:\n\t libmesh_error();\n\t}\n\n libmesh_error();\n return 0;\n } \/\/ l2_hierarchic_n_dofs()\n\n\n } \/\/ anonymous namespace\n\n\n\n\n \/\/ Do full-specialization of nodal_soln() function for every\n \/\/ dimension, instead of explicit instantiation at the end of this\n \/\/ file.\n \/\/ This could be macro-ified so that it fits on one line...\n template <>\n void FE<0,L2_HIERARCHIC>::nodal_soln(const Elem* elem,\n\t\t\t\t const Order order,\n\t\t\t\t const std::vector<Number>& elem_soln,\n\t\t\t\t std::vector<Number>& nodal_soln)\n { l2_hierarchic_nodal_soln(elem, order, elem_soln, nodal_soln, \/*Dim=*\/0); }\n\n template <>\n void FE<1,L2_HIERARCHIC>::nodal_soln(const Elem* elem,\n\t\t\t\t const Order order,\n\t\t\t\t const std::vector<Number>& elem_soln,\n\t\t\t\t std::vector<Number>& nodal_soln)\n { l2_hierarchic_nodal_soln(elem, order, elem_soln, nodal_soln, \/*Dim=*\/1); }\n\n template <>\n void FE<2,L2_HIERARCHIC>::nodal_soln(const Elem* elem,\n\t\t\t\t const Order order,\n\t\t\t\t const std::vector<Number>& elem_soln,\n\t\t\t\t std::vector<Number>& nodal_soln)\n { l2_hierarchic_nodal_soln(elem, order, elem_soln, nodal_soln, \/*Dim=*\/2); }\n\n template <>\n void FE<3,L2_HIERARCHIC>::nodal_soln(const Elem* elem,\n\t\t\t\t const Order order,\n\t\t\t\t const std::vector<Number>& elem_soln,\n\t\t\t\t std::vector<Number>& nodal_soln)\n { l2_hierarchic_nodal_soln(elem, order, elem_soln, nodal_soln, \/*Dim=*\/3); }\n\n \/\/ Full specialization of n_dofs() function for every dimension\n template <> unsigned int FE<0,L2_HIERARCHIC>::n_dofs(const ElemType t, const Order o) { return l2_hierarchic_n_dofs(t, o); }\n template <> unsigned int FE<1,L2_HIERARCHIC>::n_dofs(const ElemType t, const Order o) { return l2_hierarchic_n_dofs(t, o); }\n template <> unsigned int FE<2,L2_HIERARCHIC>::n_dofs(const ElemType t, const Order o) { return l2_hierarchic_n_dofs(t, o); }\n template <> unsigned int FE<3,L2_HIERARCHIC>::n_dofs(const ElemType t, const Order o) { return l2_hierarchic_n_dofs(t, o); }\n\n \/\/ Full specialization of n_dofs_at_node() function for every dimension.\n \/\/ Discontinuous L2 elements only have interior nodes\n template <> unsigned int FE<0,L2_HIERARCHIC>::n_dofs_at_node(const ElemType, const Order, const unsigned int) { return 0; }\n template <> unsigned int FE<1,L2_HIERARCHIC>::n_dofs_at_node(const ElemType, const Order, const unsigned int) { return 0; }\n template <> unsigned int FE<2,L2_HIERARCHIC>::n_dofs_at_node(const ElemType, const Order, const unsigned int) { return 0; }\n template <> unsigned int FE<3,L2_HIERARCHIC>::n_dofs_at_node(const ElemType, const Order, const unsigned int) { return 0; }\n\n \/\/ Full specialization of n_dofs_per_elem() function for every dimension.\n template <> unsigned int FE<0,L2_HIERARCHIC>::n_dofs_per_elem(const ElemType t, const Order o) { return l2_hierarchic_n_dofs(t, o); }\n template <> unsigned int FE<1,L2_HIERARCHIC>::n_dofs_per_elem(const ElemType t, const Order o) { return l2_hierarchic_n_dofs(t, o); }\n template <> unsigned int FE<2,L2_HIERARCHIC>::n_dofs_per_elem(const ElemType t, const Order o) { return l2_hierarchic_n_dofs(t, o); }\n template <> unsigned int FE<3,L2_HIERARCHIC>::n_dofs_per_elem(const ElemType t, const Order o) { return l2_hierarchic_n_dofs(t, o); }\n\n \/\/ L2 Hierarchic FEMs are C^0 continuous\n template <> FEContinuity FE<0,L2_HIERARCHIC>::get_continuity() const { return C_ZERO; }\n template <> FEContinuity FE<1,L2_HIERARCHIC>::get_continuity() const { return C_ZERO; }\n template <> FEContinuity FE<2,L2_HIERARCHIC>::get_continuity() const { return C_ZERO; }\n template <> FEContinuity FE<3,L2_HIERARCHIC>::get_continuity() const { return C_ZERO; }\n\n \/\/ L2 Hierarchic FEMs are hierarchic (duh!)\n template <> bool FE<0,L2_HIERARCHIC>::is_hierarchic() const { return true; }\n template <> bool FE<1,L2_HIERARCHIC>::is_hierarchic() const { return true; }\n template <> bool FE<2,L2_HIERARCHIC>::is_hierarchic() const { return true; }\n template <> bool FE<3,L2_HIERARCHIC>::is_hierarchic() const { return true; }\n\n#ifdef LIBMESH_ENABLE_AMR\n \/\/ compute_constraints() specializations are only needed for 2 and 3D\n template <>\n void FE<2,L2_HIERARCHIC>::compute_constraints (DofConstraints &constraints,\n\t\t\t\t\t\t DofMap &dof_map,\n\t\t\t\t\t\t const unsigned int variable_number,\n\t\t\t\t\t\t const Elem* elem)\n { compute_proj_constraints(constraints, dof_map, variable_number, elem); }\n\n template <>\n void FE<3,L2_HIERARCHIC>::compute_constraints (DofConstraints &constraints,\n\t\t\t\t\t\t DofMap &dof_map,\n\t\t\t\t\t\t const unsigned int variable_number,\n\t\t\t\t\t\t const Elem* elem)\n { compute_proj_constraints(constraints, dof_map, variable_number, elem); }\n#endif \/\/ #ifdef LIBMESH_ENABLE_AMR\n\n \/\/ L2-Hierarchic FEM shapes need reinit\n template <> bool FE<0,L2_HIERARCHIC>::shapes_need_reinit() const { return true; }\n template <> bool FE<1,L2_HIERARCHIC>::shapes_need_reinit() const { return true; }\n template <> bool FE<2,L2_HIERARCHIC>::shapes_need_reinit() const { return true; }\n template <> bool FE<3,L2_HIERARCHIC>::shapes_need_reinit() const { return true; }\n\n} \/\/ namespace libMesh\n<commit_msg>Fixed get_continuity in fe_l2_hierarchic.C, it should return DISCONTINUOUS. Also, change compute_constraints to a NOOP.<commit_after>\/\/ The libMesh Finite Element Library.\n\/\/ Copyright (C) 2002-2012 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner\n\n\/\/ This library is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU Lesser General Public\n\/\/ License as published by the Free Software Foundation; either\n\/\/ version 2.1 of the License, or (at your option) any later version.\n\n\/\/ This library is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ Lesser General Public License for more details.\n\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License along with this library; if not, write to the Free Software\n\/\/ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n\n\n\n\/\/ Local includes\n#include \"elem.h\"\n#include \"fe.h\"\n#include \"fe_interface.h\"\n\nnamespace libMesh\n{\n\n \/\/ ------------------------------------------------------------\n \/\/ Hierarchic-specific implementations\n\n \/\/ Anonymous namespace for local helper functions\n namespace {\n\n void l2_hierarchic_nodal_soln(const Elem* elem,\n\t\t\t\t const Order order,\n\t\t\t\t const std::vector<Number>& elem_soln,\n\t\t\t\t std::vector<Number>& nodal_soln,\n\t\t\t\t unsigned Dim)\n {\n const unsigned int n_nodes = elem->n_nodes();\n\n const ElemType elem_type = elem->type();\n\n nodal_soln.resize(n_nodes);\n\n const Order totalorder = static_cast<Order>(order + elem->p_level());\n\n \/\/ FEType object to be passed to various FEInterface functions below.\n FEType fe_type(totalorder, L2_HIERARCHIC);\n\n switch (totalorder)\n\t{\n\t \/\/ Constant shape functions\n\tcase CONSTANT:\n\t {\n\t libmesh_assert (elem_soln.size() == 1);\n\n\t const Number val = elem_soln[0];\n\n\t for (unsigned int n=0; n<n_nodes; n++)\n\t nodal_soln[n] = val;\n\n\t return;\n\t }\n\n\n\t \/\/ For other orders do interpolation at the nodes\n\t \/\/ explicitly.\n\tdefault:\n\t {\n\n\t const unsigned int n_sf =\n\t \/\/ FE<Dim,T>::n_shape_functions(elem_type, totalorder);\n\t FEInterface::n_shape_functions(Dim, fe_type, elem_type);\n\n\t std::vector<Point> refspace_nodes;\n\t FEBase::get_refspace_nodes(elem_type,refspace_nodes);\n\t libmesh_assert (refspace_nodes.size() == n_nodes);\n\n\t for (unsigned int n=0; n<n_nodes; n++)\n\t {\n\t\tlibmesh_assert (elem_soln.size() == n_sf);\n\n\t\t\/\/ Zero before summation\n\t\tnodal_soln[n] = 0;\n\n\t\t\/\/ u_i = Sum (alpha_i phi_i)\n\t\tfor (unsigned int i=0; i<n_sf; i++)\n\t\t nodal_soln[n] += elem_soln[i] *\n\t\t \/\/ FE<Dim,T>::shape(elem, order, i, mapped_point);\n\t\t FEInterface::shape(Dim, fe_type, elem, i, refspace_nodes[n]);\n\t }\n\n\t return;\n\t }\n\t}\n } \/\/ l2_hierarchic_nodal_soln()\n\n\n\n\n unsigned int l2_hierarchic_n_dofs(const ElemType t, const Order o)\n {\n libmesh_assert (o > 0);\n switch (t)\n\t{\n\tcase NODEELEM:\n\t return 1;\n\tcase EDGE2:\n\tcase EDGE3:\n\t return (o+1);\n\tcase QUAD4:\n\tcase QUAD8:\n\tcase QUAD9:\n\t return ((o+1)*(o+1));\n\tcase HEX8:\n\tcase HEX20:\n\tcase HEX27:\n\t return ((o+1)*(o+1)*(o+1));\n\tcase TRI6:\n\t return ((o+1)*(o+2)\/2);\n\tdefault:\n\t libmesh_error();\n\t}\n\n libmesh_error();\n return 0;\n } \/\/ l2_hierarchic_n_dofs()\n\n\n } \/\/ anonymous namespace\n\n\n\n\n \/\/ Do full-specialization of nodal_soln() function for every\n \/\/ dimension, instead of explicit instantiation at the end of this\n \/\/ file.\n \/\/ This could be macro-ified so that it fits on one line...\n template <>\n void FE<0,L2_HIERARCHIC>::nodal_soln(const Elem* elem,\n\t\t\t\t const Order order,\n\t\t\t\t const std::vector<Number>& elem_soln,\n\t\t\t\t std::vector<Number>& nodal_soln)\n { l2_hierarchic_nodal_soln(elem, order, elem_soln, nodal_soln, \/*Dim=*\/0); }\n\n template <>\n void FE<1,L2_HIERARCHIC>::nodal_soln(const Elem* elem,\n\t\t\t\t const Order order,\n\t\t\t\t const std::vector<Number>& elem_soln,\n\t\t\t\t std::vector<Number>& nodal_soln)\n { l2_hierarchic_nodal_soln(elem, order, elem_soln, nodal_soln, \/*Dim=*\/1); }\n\n template <>\n void FE<2,L2_HIERARCHIC>::nodal_soln(const Elem* elem,\n\t\t\t\t const Order order,\n\t\t\t\t const std::vector<Number>& elem_soln,\n\t\t\t\t std::vector<Number>& nodal_soln)\n { l2_hierarchic_nodal_soln(elem, order, elem_soln, nodal_soln, \/*Dim=*\/2); }\n\n template <>\n void FE<3,L2_HIERARCHIC>::nodal_soln(const Elem* elem,\n\t\t\t\t const Order order,\n\t\t\t\t const std::vector<Number>& elem_soln,\n\t\t\t\t std::vector<Number>& nodal_soln)\n { l2_hierarchic_nodal_soln(elem, order, elem_soln, nodal_soln, \/*Dim=*\/3); }\n\n \/\/ Full specialization of n_dofs() function for every dimension\n template <> unsigned int FE<0,L2_HIERARCHIC>::n_dofs(const ElemType t, const Order o) { return l2_hierarchic_n_dofs(t, o); }\n template <> unsigned int FE<1,L2_HIERARCHIC>::n_dofs(const ElemType t, const Order o) { return l2_hierarchic_n_dofs(t, o); }\n template <> unsigned int FE<2,L2_HIERARCHIC>::n_dofs(const ElemType t, const Order o) { return l2_hierarchic_n_dofs(t, o); }\n template <> unsigned int FE<3,L2_HIERARCHIC>::n_dofs(const ElemType t, const Order o) { return l2_hierarchic_n_dofs(t, o); }\n\n \/\/ Full specialization of n_dofs_at_node() function for every dimension.\n \/\/ Discontinuous L2 elements only have interior nodes\n template <> unsigned int FE<0,L2_HIERARCHIC>::n_dofs_at_node(const ElemType, const Order, const unsigned int) { return 0; }\n template <> unsigned int FE<1,L2_HIERARCHIC>::n_dofs_at_node(const ElemType, const Order, const unsigned int) { return 0; }\n template <> unsigned int FE<2,L2_HIERARCHIC>::n_dofs_at_node(const ElemType, const Order, const unsigned int) { return 0; }\n template <> unsigned int FE<3,L2_HIERARCHIC>::n_dofs_at_node(const ElemType, const Order, const unsigned int) { return 0; }\n\n \/\/ Full specialization of n_dofs_per_elem() function for every dimension.\n template <> unsigned int FE<0,L2_HIERARCHIC>::n_dofs_per_elem(const ElemType t, const Order o) { return l2_hierarchic_n_dofs(t, o); }\n template <> unsigned int FE<1,L2_HIERARCHIC>::n_dofs_per_elem(const ElemType t, const Order o) { return l2_hierarchic_n_dofs(t, o); }\n template <> unsigned int FE<2,L2_HIERARCHIC>::n_dofs_per_elem(const ElemType t, const Order o) { return l2_hierarchic_n_dofs(t, o); }\n template <> unsigned int FE<3,L2_HIERARCHIC>::n_dofs_per_elem(const ElemType t, const Order o) { return l2_hierarchic_n_dofs(t, o); }\n\n \/\/ L2 Hierarchic FEMs are C^0 continuous\n template <> FEContinuity FE<0,L2_HIERARCHIC>::get_continuity() const { return DISCONTINUOUS; }\n template <> FEContinuity FE<1,L2_HIERARCHIC>::get_continuity() const { return DISCONTINUOUS; }\n template <> FEContinuity FE<2,L2_HIERARCHIC>::get_continuity() const { return DISCONTINUOUS; }\n template <> FEContinuity FE<3,L2_HIERARCHIC>::get_continuity() const { return DISCONTINUOUS; }\n\n \/\/ L2 Hierarchic FEMs are hierarchic (duh!)\n template <> bool FE<0,L2_HIERARCHIC>::is_hierarchic() const { return true; }\n template <> bool FE<1,L2_HIERARCHIC>::is_hierarchic() const { return true; }\n template <> bool FE<2,L2_HIERARCHIC>::is_hierarchic() const { return true; }\n template <> bool FE<3,L2_HIERARCHIC>::is_hierarchic() const { return true; }\n\n#ifdef LIBMESH_ENABLE_AMR\n \/\/ compute_constraints() is a NOOP for DISCONTINOUS FE's\n template <>\n void FE<2,L2_HIERARCHIC>::compute_constraints (DofConstraints &,\n\t\t\t\t\t\t DofMap &,\n\t\t\t\t\t\t const unsigned int,\n\t\t\t\t\t\t const Elem*)\n { }\n\n template <>\n void FE<3,L2_HIERARCHIC>::compute_constraints (DofConstraints &,\n\t\t\t\t\t\t DofMap &,\n\t\t\t\t\t\t const unsigned int,\n\t\t\t\t\t\t const Elem*)\n { }\n#endif \/\/ #ifdef LIBMESH_ENABLE_AMR\n\n \/\/ L2-Hierarchic FEM shapes need reinit\n template <> bool FE<0,L2_HIERARCHIC>::shapes_need_reinit() const { return true; }\n template <> bool FE<1,L2_HIERARCHIC>::shapes_need_reinit() const { return true; }\n template <> bool FE<2,L2_HIERARCHIC>::shapes_need_reinit() const { return true; }\n template <> bool FE<3,L2_HIERARCHIC>::shapes_need_reinit() const { return true; }\n\n} \/\/ namespace libMesh\n<|endoftext|>"} {"text":"<commit_before>#ifndef IMAP__H__\n#define IMAP__H__\n\n#include \"zip.hpp\"\n\n#include <utility>\n#include <type_traits>\n\nnamespace iter {\n\n namespace detail {\n\n template <std::size_t Index, typename Functor, typename Tup>\n struct Expander {\n template <typename... Ts>\n static auto call(Functor&& f, Tup&& tup, Ts&&... args)\n -> decltype(Expander<Index-1, Functor, Tup>::call(\n std::forward<Functor>(f),\n std::forward<Tup>(tup),\n std::get<Index-1>(tup),\n std::forward<Ts>(args)...))\n {\n \/\/ recurse\n return Expander<Index-1, Functor, Tup>::call(\n std::forward<Functor>(f),\n std::forward<Tup>(tup),\n std::get<Index-1>(tup), \/\/ pull out one element\n std::forward<Ts>(args)...); \/\/ everything already expanded\n }\n };\n\n template <typename Functor, typename Tup>\n struct Expander<0, Functor, Tup> {\n template <typename... Ts>\n static auto call(Functor&& f, Tup&&, Ts&&... args)\n -> decltype(f(std::forward<Ts>(args)...))\n {\n static_assert(\n std::tuple_size<\n typename std::remove_reference<Tup>::type>::value\n == sizeof...(Ts),\n \"tuple has not been fully expanded\");\n return f(std::forward<Ts>(args)...); \/\/ the actual call\n }\n };\n\n template <typename Functor, typename Tup>\n auto call_with_tuple(Functor&& f, Tup&& tup)\n -> decltype(Expander<std::tuple_size<\n typename std::remove_reference<Tup>::type>::value,\n Functor, Tup>::call(\n std::forward<Functor>(f),\n std::forward<Tup>(tup)))\n {\n return Expander<std::tuple_size<\n typename std::remove_reference<Tup>::type>::value,\n Functor, Tup>::call(\n std::forward<Functor>(f),\n std::forward<Tup>(tup));\n }\n\n } \/\/ end detail\n\n \/\/Forward declarations of IMap and imap\n template <typename MapFunc, typename... Containers>\n class IMap;\n\n template <typename MapFunc, typename... Containers>\n IMap<MapFunc, Containers...> imap(MapFunc, Containers&&...);\n\n template <typename MapFunc, typename... Containers>\n class IMap {\n \/\/ The imap function is the only thing allowed to create a IMap\n friend IMap imap<MapFunc, Containers...>(MapFunc, Containers&& ...);\n\n using ZippedType = decltype(zip(std::declval<Containers>()...));\n using ZippedIterType = iterator_type<ZippedType>;\n private:\n MapFunc map_func;\n ZippedType zipped;\n \n \/\/ Value constructor for use only in the imap function\n IMap(MapFunc map_func, Containers&& ... containers) :\n map_func(map_func),\n zipped(zip(std::forward<Containers>(containers)...))\n { }\n IMap() = delete;\n IMap& operator=(const IMap&) = delete;\n\n public:\n IMap(const IMap&) = default;\n IMap(IMap&&) = default;\n\n class Iterator {\n private:\n MapFunc map_func;\n mutable ZippedIterType zipiter;\n\n public:\n Iterator(MapFunc map_func, ZippedIterType zipiter) :\n map_func(map_func),\n zipiter(zipiter)\n { } \n\n auto operator*() -> \n decltype(detail::call_with_tuple(\n this->map_func, *(this->zipiter)))\n {\n return detail::call_with_tuple(\n this->map_func, *(this->zipiter));\n }\n\n Iterator& operator++() { \n ++this->zipiter;\n return *this;\n }\n\n bool operator!=(const Iterator& other) const {\n return this->zipiter != other.zipiter;\n }\n };\n\n Iterator begin() {\n return {this->map_func, this->zipped.begin()};\n }\n\n Iterator end() {\n return {this->map_func, this->zipped.end()};\n }\n\n };\n\n \/\/ Helper function to instantiate a IMap\n template <typename MapFunc, typename... Containers>\n IMap<MapFunc, Containers...> imap(\n MapFunc map_func, Containers&& ... containers) {\n return {map_func, std::forward<Containers>(containers)...};\n }\n\n}\n\n#endif \/\/ifndef IMAP__H__\n<commit_msg>removes mutable (idk why it was ever there)<commit_after>#ifndef IMAP__H__\n#define IMAP__H__\n\n#include \"zip.hpp\"\n\n#include <utility>\n#include <type_traits>\n\nnamespace iter {\n\n namespace detail {\n\n template <std::size_t Index, typename Functor, typename Tup>\n struct Expander {\n template <typename... Ts>\n static auto call(Functor&& f, Tup&& tup, Ts&&... args)\n -> decltype(Expander<Index-1, Functor, Tup>::call(\n std::forward<Functor>(f),\n std::forward<Tup>(tup),\n std::get<Index-1>(tup),\n std::forward<Ts>(args)...))\n {\n \/\/ recurse\n return Expander<Index-1, Functor, Tup>::call(\n std::forward<Functor>(f),\n std::forward<Tup>(tup),\n std::get<Index-1>(tup), \/\/ pull out one element\n std::forward<Ts>(args)...); \/\/ everything already expanded\n }\n };\n\n template <typename Functor, typename Tup>\n struct Expander<0, Functor, Tup> {\n template <typename... Ts>\n static auto call(Functor&& f, Tup&&, Ts&&... args)\n -> decltype(f(std::forward<Ts>(args)...))\n {\n static_assert(\n std::tuple_size<\n typename std::remove_reference<Tup>::type>::value\n == sizeof...(Ts),\n \"tuple has not been fully expanded\");\n return f(std::forward<Ts>(args)...); \/\/ the actual call\n }\n };\n\n template <typename Functor, typename Tup>\n auto call_with_tuple(Functor&& f, Tup&& tup)\n -> decltype(Expander<std::tuple_size<\n typename std::remove_reference<Tup>::type>::value,\n Functor, Tup>::call(\n std::forward<Functor>(f),\n std::forward<Tup>(tup)))\n {\n return Expander<std::tuple_size<\n typename std::remove_reference<Tup>::type>::value,\n Functor, Tup>::call(\n std::forward<Functor>(f),\n std::forward<Tup>(tup));\n }\n\n } \/\/ end detail\n\n \/\/Forward declarations of IMap and imap\n template <typename MapFunc, typename... Containers>\n class IMap;\n\n template <typename MapFunc, typename... Containers>\n IMap<MapFunc, Containers...> imap(MapFunc, Containers&&...);\n\n template <typename MapFunc, typename... Containers>\n class IMap {\n \/\/ The imap function is the only thing allowed to create a IMap\n friend IMap imap<MapFunc, Containers...>(MapFunc, Containers&& ...);\n\n using ZippedType = decltype(zip(std::declval<Containers>()...));\n using ZippedIterType = iterator_type<ZippedType>;\n private:\n MapFunc map_func;\n ZippedType zipped;\n \n \/\/ Value constructor for use only in the imap function\n IMap(MapFunc map_func, Containers&& ... containers) :\n map_func(map_func),\n zipped(zip(std::forward<Containers>(containers)...))\n { }\n IMap() = delete;\n IMap& operator=(const IMap&) = delete;\n\n public:\n IMap(const IMap&) = default;\n IMap(IMap&&) = default;\n\n class Iterator {\n private:\n MapFunc map_func;\n ZippedIterType zipiter;\n\n public:\n Iterator(MapFunc map_func, ZippedIterType zipiter) :\n map_func(map_func),\n zipiter(zipiter)\n { } \n\n auto operator*() -> \n decltype(detail::call_with_tuple(\n this->map_func, *(this->zipiter)))\n {\n return detail::call_with_tuple(\n this->map_func, *(this->zipiter));\n }\n\n Iterator& operator++() { \n ++this->zipiter;\n return *this;\n }\n\n bool operator!=(const Iterator& other) const {\n return this->zipiter != other.zipiter;\n }\n };\n\n Iterator begin() {\n return {this->map_func, this->zipped.begin()};\n }\n\n Iterator end() {\n return {this->map_func, this->zipped.end()};\n }\n\n };\n\n \/\/ Helper function to instantiate a IMap\n template <typename MapFunc, typename... Containers>\n IMap<MapFunc, Containers...> imap(\n MapFunc map_func, Containers&& ... containers) {\n return {map_func, std::forward<Containers>(containers)...};\n }\n\n}\n\n#endif \/\/ifndef IMAP__H__\n<|endoftext|>"} {"text":"<commit_before>\/**\n * @file\n * @brief Executable running the framework\n *\/\n\n#include <atomic>\n#include <csignal>\n#include <cstdlib>\n#include <fstream>\n#include <memory>\n#include <string>\n#include <utility>\n\n#include \"core\/Allpix.hpp\"\n#include \"core\/config\/ConfigManager.hpp\"\n#include \"core\/geometry\/GeometryManager.hpp\"\n#include \"core\/utils\/exceptions.h\"\n\n#include \"core\/utils\/log.h\"\n\nusing namespace allpix;\n\nvoid clean();\nvoid abort_handler(int);\nvoid interrupt_handler(int);\n\nstd::unique_ptr<Allpix> apx;\nstd::atomic<bool> apx_ready{false};\n\n\/**\n * @brief Handle user abort (CTRL+\\) which should stop the framework immediately\n * @note This handler is actually not fully reliable (but otherwise crashing is okay...)\n *\/\nvoid abort_handler(int) {\n \/\/ Output interrupt message and clean\n LOG(FATAL) << \"Aborting!\";\n clean();\n\n \/\/ Ignore any segmentation fault that may arise after this\n std::signal(SIGSEGV, SIG_IGN); \/\/ NOLINT\n std::abort();\n}\n\n\/**\n * @brief Handle termination request (CTRL+C) as soon as possible while keeping the program flow\n *\/\nvoid interrupt_handler(int) {\n \/\/ Stop the framework if it is loaded\n if(apx_ready) {\n LOG(STATUS) << \"Interrupted! Finishing up current event...\";\n apx->terminate();\n }\n}\n\n\/**\n * @brief Clean the environment when closing application\n *\/\nvoid clean() {\n Log::finish();\n if(apx_ready) {\n apx.reset();\n }\n}\n\n\/**\n * @brief Main function running the application\n *\/\nint main(int argc, const char* argv[]) {\n \/\/ Add cout as the default logging stream\n Log::addStream(std::cout);\n\n \/\/ Install abort handler (CTRL+\\)\n std::signal(SIGQUIT, abort_handler);\n\n \/\/ Install interrupt handler (CTRL+C)\n std::signal(SIGINT, interrupt_handler);\n\n \/\/ If no arguments are provided, print the help:\n bool print_help = false;\n int return_code = 0;\n if(argc == 1) {\n print_help = true;\n return_code = 1;\n }\n\n \/\/ Parse arguments\n std::string config_file_name;\n std::string log_file_name;\n std::vector<std::string> module_options;\n std::vector<std::string> detector_options;\n for(int i = 1; i < argc; i++) {\n if(strcmp(argv[i], \"-h\") == 0) {\n print_help = true;\n } else if(strcmp(argv[i], \"--version\") == 0) {\n std::cout << \"Allpix Squared version \" << ALLPIX_PROJECT_VERSION << std::endl;\n std::cout << \" built on \" << ALLPIX_BUILD_TIME << std::endl;\n std::cout << std::endl;\n std::cout << \"Copyright (c) 2017-2018 CERN and the Allpix Squared authors.\" << std::endl << std::endl;\n std::cout << \"This software is distributed under the terms of the MIT License.\" << std::endl;\n std::cout << \"In applying this license, CERN does not waive the privileges and immunities\" << std::endl;\n std::cout << \"granted to it by virtue of its status as an Intergovernmental Organization\" << std::endl;\n std::cout << \"or submit itself to any jurisdiction.\" << std::endl;\n clean();\n return 0;\n } else if(strcmp(argv[i], \"-v\") == 0 && (i + 1 < argc)) {\n try {\n LogLevel log_level = Log::getLevelFromString(std::string(argv[++i]));\n Log::setReportingLevel(log_level);\n } catch(std::invalid_argument& e) {\n LOG(ERROR) << \"Invalid verbosity level \\\"\" << std::string(argv[i]) << \"\\\", ignoring overwrite\";\n }\n } else if(strcmp(argv[i], \"-c\") == 0 && (i + 1 < argc)) {\n config_file_name = std::string(argv[++i]);\n } else if(strcmp(argv[i], \"-l\") == 0 && (i + 1 < argc)) {\n log_file_name = std::string(argv[++i]);\n } else if(strcmp(argv[i], \"-o\") == 0 && (i + 1 < argc)) {\n module_options.emplace_back(std::string(argv[++i]));\n } else if(strcmp(argv[i], \"-g\") == 0 && (i + 1 < argc)) {\n detector_options.emplace_back(std::string(argv[++i]));\n } else {\n LOG(ERROR) << \"Unrecognized command line argument \\\"\" << argv[i] << \"\\\"\";\n print_help = true;\n return_code = 1;\n }\n }\n\n \/\/ Print help if requested or no arguments given\n if(print_help) {\n std::cout << \"Allpix Squared\" << std::endl;\n std::cout << \"Generic Pixel Detector Simulation Framework\" << std::endl;\n std::cout << std::endl;\n std::cout << \"Usage: allpix -c <file> [OPTIONS]\" << std::endl;\n std::cout << std::endl;\n std::cout << \"Options:\" << std::endl;\n std::cout << \" -c <file> configuration file to be used\" << std::endl;\n std::cout << \" -l <file> file to log to besides standard output\" << std::endl;\n std::cout << \" -o <option> extra module configuration option(s) to pass\" << std::endl;\n std::cout << \" -g <option> extra detector configuration options(s) to pass\" << std::endl;\n std::cout << \" -v <level> verbosity level, overwriting the global level\" << std::endl;\n std::cout << \" --version print version information and quit\" << std::endl;\n std::cout << std::endl;\n std::cout << \"For more help, please see <https:\/\/cern.ch\/allpix-squared>\" << std::endl;\n clean();\n return return_code;\n }\n\n \/\/ Check if we have a configuration file\n if(config_file_name.empty()) {\n LOG(FATAL) << \"No configuration file provided! See usage info with \\\"allpix -h\\\"\";\n clean();\n return 1;\n }\n\n \/\/ Add an extra file to log too if possible\n \/\/ NOTE: this stream should be available for the duration of the logging\n std::ofstream log_file;\n if(!log_file_name.empty()) {\n log_file.open(log_file_name, std::ios_base::out | std::ios_base::trunc);\n if(!log_file.good()) {\n LOG(FATAL) << \"Cannot write to provided log file! Check if permissions are sufficient.\";\n clean();\n return 1;\n }\n\n Log::addStream(log_file);\n }\n\n try {\n \/\/ Construct main Allpix object\n apx = std::make_unique<Allpix>(config_file_name, module_options, detector_options);\n apx_ready = true;\n\n \/\/ Load modules\n apx->load();\n\n \/\/ Initialize modules (pre-run)\n apx->init();\n\n \/\/ Run modules and event-loop\n apx->run();\n\n \/\/ Finalize modules (post-run)\n apx->finalize();\n } catch(ConfigurationError& e) {\n LOG(FATAL) << \"Error in the configuration:\" << std::endl\n << e.what() << std::endl\n << \"The configuration needs to be updated. Cannot continue.\";\n return_code = 1;\n } catch(RuntimeError& e) {\n LOG(FATAL) << \"Error during execution of run:\" << std::endl\n << e.what() << std::endl\n << \"Please check your configuration and modules. Cannot continue.\";\n return_code = 1;\n } catch(LogicError& e) {\n LOG(FATAL) << \"Error in the logic of module:\" << std::endl\n << e.what() << std::endl\n << \"Module has to be properly defined. Cannot continue.\";\n return_code = 1;\n } catch(std::exception& e) {\n LOG(FATAL) << \"Fatal internal error\" << std::endl << e.what() << std::endl << \"Cannot continue.\";\n return_code = 127;\n }\n\n \/\/ Finish the logging\n clean();\n\n return return_code;\n}\n<commit_msg>Executable: terminate gracefully at SIGTERM<commit_after>\/**\n * @file\n * @brief Executable running the framework\n *\/\n\n#include <atomic>\n#include <csignal>\n#include <cstdlib>\n#include <fstream>\n#include <memory>\n#include <string>\n#include <utility>\n\n#include \"core\/Allpix.hpp\"\n#include \"core\/config\/ConfigManager.hpp\"\n#include \"core\/geometry\/GeometryManager.hpp\"\n#include \"core\/utils\/exceptions.h\"\n\n#include \"core\/utils\/log.h\"\n\nusing namespace allpix;\n\nvoid clean();\nvoid abort_handler(int);\nvoid interrupt_handler(int);\n\nstd::unique_ptr<Allpix> apx;\nstd::atomic<bool> apx_ready{false};\n\n\/**\n * @brief Handle user abort (CTRL+\\) which should stop the framework immediately\n * @note This handler is actually not fully reliable (but otherwise crashing is okay...)\n *\/\nvoid abort_handler(int) {\n \/\/ Output interrupt message and clean\n LOG(FATAL) << \"Aborting!\";\n clean();\n\n \/\/ Ignore any segmentation fault that may arise after this\n std::signal(SIGSEGV, SIG_IGN); \/\/ NOLINT\n std::abort();\n}\n\n\/**\n * @brief Handle termination request (CTRL+C) as soon as possible while keeping the program flow\n *\/\nvoid interrupt_handler(int) {\n \/\/ Stop the framework if it is loaded\n if(apx_ready) {\n LOG(STATUS) << \"Interrupted! Finishing up current event...\";\n apx->terminate();\n }\n}\n\n\/**\n * @brief Clean the environment when closing application\n *\/\nvoid clean() {\n Log::finish();\n if(apx_ready) {\n apx.reset();\n }\n}\n\n\/**\n * @brief Main function running the application\n *\/\nint main(int argc, const char* argv[]) {\n \/\/ Add cout as the default logging stream\n Log::addStream(std::cout);\n\n \/\/ Install abort handler (CTRL+\\)\n std::signal(SIGQUIT, abort_handler);\n\n \/\/ Install interrupt handler (CTRL+C)\n std::signal(SIGINT, interrupt_handler);\n\n \/\/ Install termination handler (e.g. from \"kill\"). Gracefully exit, finish last event and quit\n std::signal(SIGTERM, interrupt_handler);\n\n \/\/ If no arguments are provided, print the help:\n bool print_help = false;\n int return_code = 0;\n if(argc == 1) {\n print_help = true;\n return_code = 1;\n }\n\n \/\/ Parse arguments\n std::string config_file_name;\n std::string log_file_name;\n std::vector<std::string> module_options;\n std::vector<std::string> detector_options;\n for(int i = 1; i < argc; i++) {\n if(strcmp(argv[i], \"-h\") == 0) {\n print_help = true;\n } else if(strcmp(argv[i], \"--version\") == 0) {\n std::cout << \"Allpix Squared version \" << ALLPIX_PROJECT_VERSION << std::endl;\n std::cout << \" built on \" << ALLPIX_BUILD_TIME << std::endl;\n std::cout << std::endl;\n std::cout << \"Copyright (c) 2017-2018 CERN and the Allpix Squared authors.\" << std::endl << std::endl;\n std::cout << \"This software is distributed under the terms of the MIT License.\" << std::endl;\n std::cout << \"In applying this license, CERN does not waive the privileges and immunities\" << std::endl;\n std::cout << \"granted to it by virtue of its status as an Intergovernmental Organization\" << std::endl;\n std::cout << \"or submit itself to any jurisdiction.\" << std::endl;\n clean();\n return 0;\n } else if(strcmp(argv[i], \"-v\") == 0 && (i + 1 < argc)) {\n try {\n LogLevel log_level = Log::getLevelFromString(std::string(argv[++i]));\n Log::setReportingLevel(log_level);\n } catch(std::invalid_argument& e) {\n LOG(ERROR) << \"Invalid verbosity level \\\"\" << std::string(argv[i]) << \"\\\", ignoring overwrite\";\n }\n } else if(strcmp(argv[i], \"-c\") == 0 && (i + 1 < argc)) {\n config_file_name = std::string(argv[++i]);\n } else if(strcmp(argv[i], \"-l\") == 0 && (i + 1 < argc)) {\n log_file_name = std::string(argv[++i]);\n } else if(strcmp(argv[i], \"-o\") == 0 && (i + 1 < argc)) {\n module_options.emplace_back(std::string(argv[++i]));\n } else if(strcmp(argv[i], \"-g\") == 0 && (i + 1 < argc)) {\n detector_options.emplace_back(std::string(argv[++i]));\n } else {\n LOG(ERROR) << \"Unrecognized command line argument \\\"\" << argv[i] << \"\\\"\";\n print_help = true;\n return_code = 1;\n }\n }\n\n \/\/ Print help if requested or no arguments given\n if(print_help) {\n std::cout << \"Allpix Squared\" << std::endl;\n std::cout << \"Generic Pixel Detector Simulation Framework\" << std::endl;\n std::cout << std::endl;\n std::cout << \"Usage: allpix -c <file> [OPTIONS]\" << std::endl;\n std::cout << std::endl;\n std::cout << \"Options:\" << std::endl;\n std::cout << \" -c <file> configuration file to be used\" << std::endl;\n std::cout << \" -l <file> file to log to besides standard output\" << std::endl;\n std::cout << \" -o <option> extra module configuration option(s) to pass\" << std::endl;\n std::cout << \" -g <option> extra detector configuration options(s) to pass\" << std::endl;\n std::cout << \" -v <level> verbosity level, overwriting the global level\" << std::endl;\n std::cout << \" --version print version information and quit\" << std::endl;\n std::cout << std::endl;\n std::cout << \"For more help, please see <https:\/\/cern.ch\/allpix-squared>\" << std::endl;\n clean();\n return return_code;\n }\n\n \/\/ Check if we have a configuration file\n if(config_file_name.empty()) {\n LOG(FATAL) << \"No configuration file provided! See usage info with \\\"allpix -h\\\"\";\n clean();\n return 1;\n }\n\n \/\/ Add an extra file to log too if possible\n \/\/ NOTE: this stream should be available for the duration of the logging\n std::ofstream log_file;\n if(!log_file_name.empty()) {\n log_file.open(log_file_name, std::ios_base::out | std::ios_base::trunc);\n if(!log_file.good()) {\n LOG(FATAL) << \"Cannot write to provided log file! Check if permissions are sufficient.\";\n clean();\n return 1;\n }\n\n Log::addStream(log_file);\n }\n\n try {\n \/\/ Construct main Allpix object\n apx = std::make_unique<Allpix>(config_file_name, module_options, detector_options);\n apx_ready = true;\n\n \/\/ Load modules\n apx->load();\n\n \/\/ Initialize modules (pre-run)\n apx->init();\n\n \/\/ Run modules and event-loop\n apx->run();\n\n \/\/ Finalize modules (post-run)\n apx->finalize();\n } catch(ConfigurationError& e) {\n LOG(FATAL) << \"Error in the configuration:\" << std::endl\n << e.what() << std::endl\n << \"The configuration needs to be updated. Cannot continue.\";\n return_code = 1;\n } catch(RuntimeError& e) {\n LOG(FATAL) << \"Error during execution of run:\" << std::endl\n << e.what() << std::endl\n << \"Please check your configuration and modules. Cannot continue.\";\n return_code = 1;\n } catch(LogicError& e) {\n LOG(FATAL) << \"Error in the logic of module:\" << std::endl\n << e.what() << std::endl\n << \"Module has to be properly defined. Cannot continue.\";\n return_code = 1;\n } catch(std::exception& e) {\n LOG(FATAL) << \"Fatal internal error\" << std::endl << e.what() << std::endl << \"Cannot continue.\";\n return_code = 127;\n }\n\n \/\/ Finish the logging\n clean();\n\n return return_code;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"wx\/dc.h\"\n#include \"wx\/dcclient.h\"\n\n#include \"RoboStruct_GUI_style.hpp\"\n#include \"MainFrame.hpp\"\n\nwxAuiToolBarArt* wxAuiSolidToolBarArt::Clone()\n{\n return new wxAuiSolidToolBarArt{};\n}\n\nvoid wxAuiSolidToolBarArt::DrawBackground(wxDC& dc, wxWindow* wnd, const wxRect& rect)\n{\n wxUnusedVar(wnd);\n dc.GradientFillLinear(rect, wxColour{238, 238, 242}, wxColour{238, 238, 242});\n}\n\n\n\nwxAuiSolidTabArt::wxAuiSolidTabArt()\n : wxAuiGenericTabArt()\n{\n m_normalFont = wxSystemSettings::GetFont(wxSYS_DEFAULT_GUI_FONT);\n m_selectedFont = wxSystemSettings::GetFont(wxSYS_DEFAULT_GUI_FONT);\n m_selectedFont.SetWeight(wxNORMAL);\n m_measuringFont = m_selectedFont;\n}\n\nwxAuiSolidTabArt* wxAuiSolidTabArt::Clone()\n{\n return new wxAuiSolidTabArt{};\n}\n\nvoid wxAuiSolidTabArt::DrawBackground(wxDC& dc, wxWindow* wnd, const wxRect& rect)\n{\n wxUnusedVar(wnd);\n dc.GradientFillLinear(rect, wxColour{238, 238, 242}, wxColour{238, 238, 242});\n}\n\nvoid wxAuiSolidTabArt::DrawTab(wxDC& dc, wxWindow* wnd, const wxAuiNotebookPage& page, const wxRect& in_rect,\n int close_button_state, wxRect* out_tab_rect, wxRect* out_button_rect, int* x_extent)\n{\n wxCoord normal_textx, normal_texty;\n\n \/\/ If the caption is empty, measure some temporary text\n wxString caption{page.caption};\n if (caption.empty()) caption = \"Xj\";\n\n dc.SetFont(m_normalFont);\n dc.GetTextExtent(caption, &normal_textx, &normal_texty);\n\n \/\/ Figure out the size of the tab\n wxSize tab_size = GetTabSize(dc, wnd, page.caption, page.bitmap, page.active, close_button_state, x_extent);\n wxCoord tab_height = m_tabCtrlHeight;\n wxCoord tab_width = tab_size.x;\n wxCoord tab_x = in_rect.x;\n wxCoord tab_y = in_rect.y + in_rect.height - tab_height;\n\n caption = page.caption;\n\n dc.SetFont(m_normalFont);\n\n int drawn_tab_height = tab_height - 2;\n\n if (page.active)\n {\n \/\/ draw base background color\n wxRect r{tab_x, tab_y, tab_width, tab_height};\n dc.GradientFillLinear(r, wxColour{51, 153, 255}, wxColour{51, 153, 255});\n } else\n {\n wxRect r{tab_x, tab_y, tab_width, tab_height};\n dc.GradientFillLinear(r, wxColour{204, 206, 219}, wxColour{204, 206, 219});\n }\n\n int text_offset = tab_x + 8;\n\n \/\/ Draw tab text\n wxString draw_text = wxAuiChopText(dc, caption, tab_width - (text_offset-tab_x));\n if (page.active)\n {\n dc.SetTextForeground(wxColour{255, 255, 255});\n dc.DrawText(draw_text, text_offset, tab_y + 2 + (drawn_tab_height) \/ 2 - (normal_texty \/ 2) - 1);\n } else\n {\n dc.SetTextForeground(wxColour{0, 0, 0});\n dc.DrawText(draw_text, text_offset, tab_y + 2 + (drawn_tab_height) \/ 2 - (normal_texty \/ 2) - 1);\n }\n\n *out_tab_rect = wxRect{tab_x, tab_y, tab_width, tab_height};\n}\n\nint wxAuiSolidTabArt::GetBestTabCtrlSize(wxWindow* wnd, const wxAuiNotebookPageArray& pages, const wxSize& requiredBmp_size)\n{\n return 22;\n}\n\n\n\nwxAuiMyNotebook::wxAuiMyNotebook(wxWindow* parent, wxWindowID id, const wxPoint& pos, const wxSize& size, long style)\n : wxAuiNotebook(parent, id, pos, size, style)\n{\n SetArtProvider(new wxAuiSolidTabArt{});\n \n m_mgr.GetArtProvider()->SetMetric(wxAUI_DOCKART_PANE_BORDER_SIZE,0);\n m_mgr.GetArtProvider()->SetColor(wxAUI_DOCKART_BORDER_COLOUR, wxColour{238, 238, 242});\n m_mgr.GetArtProvider()->SetColor(wxAUI_DOCKART_SASH_COLOUR, wxColour{238, 238, 242});\n m_mgr.GetArtProvider()->SetColor(wxAUI_DOCKART_BACKGROUND_COLOUR, wxColour{238, 238, 242});\n}\n\n\n\nvoid MainFrame::InitializeGuiStyle()\n{\n m_toolbar->SetArtProvider(new wxAuiSolidToolBarArt{});\n m_toolbar_log->SetArtProvider(new wxAuiSolidToolBarArt{});\n m_toolbar_options->SetArtProvider(new wxAuiSolidToolBarArt{});\n\n m_mgr.GetArtProvider()->SetColor(wxAUI_DOCKART_BORDER_COLOUR, light_theme_main_color);\n m_mgr.GetArtProvider()->SetColor(wxAUI_DOCKART_SASH_COLOUR, light_theme_main_color);\n m_mgr.GetArtProvider()->SetColor(wxAUI_DOCKART_BACKGROUND_COLOUR, light_theme_main_color);\n m_mgr.GetArtProvider()->SetMetric(wxAUI_DOCKART_PANE_BORDER_SIZE, 0);\n\n m_mgr.GetArtProvider()->SetFont(wxAUI_DOCKART_CAPTION_FONT, wxSystemSettings::GetFont(wxSYS_DEFAULT_GUI_FONT));\n m_mgr.GetArtProvider()->SetMetric(wxAUI_DOCKART_CAPTION_SIZE, 19);\n m_mgr.GetArtProvider()->SetColor(wxAUI_DOCKART_ACTIVE_CAPTION_COLOUR, wxColour{0, 122, 204});\n m_mgr.GetArtProvider()->SetColor(wxAUI_DOCKART_ACTIVE_CAPTION_GRADIENT_COLOUR, wxColour{0, 122, 204});\n m_mgr.GetArtProvider()->SetColor(wxAUI_DOCKART_ACTIVE_CAPTION_TEXT_COLOUR, wxColour{255, 255, 255});\n m_mgr.GetArtProvider()->SetColor(wxAUI_DOCKART_INACTIVE_CAPTION_COLOUR, light_theme_main_color);\n m_mgr.GetArtProvider()->SetColor(wxAUI_DOCKART_INACTIVE_CAPTION_GRADIENT_COLOUR, light_theme_main_color);\n m_mgr.GetArtProvider()->SetColor(wxAUI_DOCKART_INACTIVE_CAPTION_TEXT_COLOUR, wxColour{20, 20, 20});\n m_mgr.Update();\n}\n<commit_msg>removed call to wxAuiManager::Update()<commit_after>#include \"wx\/dc.h\"\n#include \"wx\/dcclient.h\"\n\n#include \"RoboStruct_GUI_style.hpp\"\n#include \"MainFrame.hpp\"\n\nwxAuiToolBarArt* wxAuiSolidToolBarArt::Clone()\n{\n return new wxAuiSolidToolBarArt{};\n}\n\nvoid wxAuiSolidToolBarArt::DrawBackground(wxDC& dc, wxWindow* wnd, const wxRect& rect)\n{\n wxUnusedVar(wnd);\n dc.GradientFillLinear(rect, wxColour{238, 238, 242}, wxColour{238, 238, 242});\n}\n\n\n\nwxAuiSolidTabArt::wxAuiSolidTabArt()\n : wxAuiGenericTabArt()\n{\n m_normalFont = wxSystemSettings::GetFont(wxSYS_DEFAULT_GUI_FONT);\n m_selectedFont = wxSystemSettings::GetFont(wxSYS_DEFAULT_GUI_FONT);\n m_selectedFont.SetWeight(wxNORMAL);\n m_measuringFont = m_selectedFont;\n}\n\nwxAuiSolidTabArt* wxAuiSolidTabArt::Clone()\n{\n return new wxAuiSolidTabArt{};\n}\n\nvoid wxAuiSolidTabArt::DrawBackground(wxDC& dc, wxWindow* wnd, const wxRect& rect)\n{\n wxUnusedVar(wnd);\n dc.GradientFillLinear(rect, wxColour{238, 238, 242}, wxColour{238, 238, 242});\n}\n\nvoid wxAuiSolidTabArt::DrawTab(wxDC& dc, wxWindow* wnd, const wxAuiNotebookPage& page, const wxRect& in_rect,\n int close_button_state, wxRect* out_tab_rect, wxRect* out_button_rect, int* x_extent)\n{\n wxCoord normal_textx, normal_texty;\n\n \/\/ If the caption is empty, measure some temporary text\n wxString caption{page.caption};\n if (caption.empty()) caption = \"Xj\";\n\n dc.SetFont(m_normalFont);\n dc.GetTextExtent(caption, &normal_textx, &normal_texty);\n\n \/\/ Figure out the size of the tab\n wxSize tab_size = GetTabSize(dc, wnd, page.caption, page.bitmap, page.active, close_button_state, x_extent);\n wxCoord tab_height = m_tabCtrlHeight;\n wxCoord tab_width = tab_size.x;\n wxCoord tab_x = in_rect.x;\n wxCoord tab_y = in_rect.y + in_rect.height - tab_height;\n\n caption = page.caption;\n\n dc.SetFont(m_normalFont);\n\n int drawn_tab_height = tab_height - 2;\n\n if (page.active)\n {\n \/\/ draw base background color\n wxRect r{tab_x, tab_y, tab_width, tab_height};\n dc.GradientFillLinear(r, wxColour{51, 153, 255}, wxColour{51, 153, 255});\n } else\n {\n wxRect r{tab_x, tab_y, tab_width, tab_height};\n dc.GradientFillLinear(r, wxColour{204, 206, 219}, wxColour{204, 206, 219});\n }\n\n int text_offset = tab_x + 8;\n\n \/\/ Draw tab text\n wxString draw_text = wxAuiChopText(dc, caption, tab_width - (text_offset-tab_x));\n if (page.active)\n {\n dc.SetTextForeground(wxColour{255, 255, 255});\n dc.DrawText(draw_text, text_offset, tab_y + 2 + (drawn_tab_height) \/ 2 - (normal_texty \/ 2) - 1);\n } else\n {\n dc.SetTextForeground(wxColour{0, 0, 0});\n dc.DrawText(draw_text, text_offset, tab_y + 2 + (drawn_tab_height) \/ 2 - (normal_texty \/ 2) - 1);\n }\n\n *out_tab_rect = wxRect{tab_x, tab_y, tab_width, tab_height};\n}\n\nint wxAuiSolidTabArt::GetBestTabCtrlSize(wxWindow* wnd, const wxAuiNotebookPageArray& pages, const wxSize& requiredBmp_size)\n{\n return 22;\n}\n\n\n\nwxAuiMyNotebook::wxAuiMyNotebook(wxWindow* parent, wxWindowID id, const wxPoint& pos, const wxSize& size, long style)\n : wxAuiNotebook(parent, id, pos, size, style)\n{\n SetArtProvider(new wxAuiSolidTabArt{});\n \n m_mgr.GetArtProvider()->SetMetric(wxAUI_DOCKART_PANE_BORDER_SIZE,0);\n m_mgr.GetArtProvider()->SetColor(wxAUI_DOCKART_BORDER_COLOUR, light_theme_main_color);\n m_mgr.GetArtProvider()->SetColor(wxAUI_DOCKART_SASH_COLOUR, light_theme_main_color);\n m_mgr.GetArtProvider()->SetColor(wxAUI_DOCKART_BACKGROUND_COLOUR, light_theme_main_color);\n}\n\n\n\nvoid MainFrame::InitializeGuiStyle()\n{\n m_toolbar->SetArtProvider(new wxAuiSolidToolBarArt{});\n m_toolbar_log->SetArtProvider(new wxAuiSolidToolBarArt{});\n m_toolbar_options->SetArtProvider(new wxAuiSolidToolBarArt{});\n\n m_mgr.GetArtProvider()->SetColor(wxAUI_DOCKART_BORDER_COLOUR, light_theme_main_color);\n m_mgr.GetArtProvider()->SetColor(wxAUI_DOCKART_SASH_COLOUR, light_theme_main_color);\n m_mgr.GetArtProvider()->SetColor(wxAUI_DOCKART_BACKGROUND_COLOUR, light_theme_main_color);\n m_mgr.GetArtProvider()->SetMetric(wxAUI_DOCKART_PANE_BORDER_SIZE, 0);\n\n m_mgr.GetArtProvider()->SetFont(wxAUI_DOCKART_CAPTION_FONT, wxSystemSettings::GetFont(wxSYS_DEFAULT_GUI_FONT));\n m_mgr.GetArtProvider()->SetMetric(wxAUI_DOCKART_CAPTION_SIZE, 19);\n m_mgr.GetArtProvider()->SetColor(wxAUI_DOCKART_ACTIVE_CAPTION_COLOUR, wxColour{0, 122, 204});\n m_mgr.GetArtProvider()->SetColor(wxAUI_DOCKART_ACTIVE_CAPTION_GRADIENT_COLOUR, wxColour{0, 122, 204});\n m_mgr.GetArtProvider()->SetColor(wxAUI_DOCKART_ACTIVE_CAPTION_TEXT_COLOUR, wxColour{255, 255, 255});\n m_mgr.GetArtProvider()->SetColor(wxAUI_DOCKART_INACTIVE_CAPTION_COLOUR, light_theme_main_color);\n m_mgr.GetArtProvider()->SetColor(wxAUI_DOCKART_INACTIVE_CAPTION_GRADIENT_COLOUR, light_theme_main_color);\n m_mgr.GetArtProvider()->SetColor(wxAUI_DOCKART_INACTIVE_CAPTION_TEXT_COLOUR, wxColour{20, 20, 20});\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (C) 2007-2013 CEA\/DEN, EDF R&D, OPEN CASCADE\n\/\/\n\/\/ Copyright (C) 2003-2007 OPEN CASCADE, EADS\/CCR, LIP6, CEA\/DEN,\n\/\/ CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS\n\/\/\n\/\/ This library is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU Lesser General Public\n\/\/ License as published by the Free Software Foundation; either\n\/\/ version 2.1 of the License.\n\/\/\n\/\/ This library is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ Lesser General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License along with this library; if not, write to the Free Software\n\/\/ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n\/\/\n\/\/ See http:\/\/www.salome-platform.org\/ or email : webmaster.salome@opencascade.com\n\/\/\n\n\/\/ SMESH SMDS : implementaion of Salome mesh data structure\n\/\/ File : SMDS_MeshElement.hxx\n\/\/ Module : SMESH\n\/\/\n#ifndef _SMDS_MeshElement_HeaderFile\n#define _SMDS_MeshElement_HeaderFile\n\n#include \"SMESH_SMDS.hxx\"\n \n#include \"SMDSAbs_ElementType.hxx\"\n#include \"SMDS_MeshObject.hxx\"\n#include \"SMDS_ElemIterator.hxx\"\n#include \"SMDS_MeshElementIDFactory.hxx\"\n#include \"SMDS_StdIterator.hxx\"\n\n#include <vector>\n#include <iostream>\n\n#include <vtkType.h>\n#include <vtkCellType.h>\n\n\/\/typedef unsigned short UShortType;\ntypedef short ShortType;\ntypedef int LongType;\n\nclass SMDS_MeshNode;\nclass SMDS_MeshEdge;\nclass SMDS_MeshFace;\nclass SMDS_Mesh;\n\n\/\/ ============================================================\n\/*!\n * \\brief Base class for elements\n *\/\n\/\/ ============================================================\n\n\nclass SMDS_EXPORT SMDS_MeshElement:public SMDS_MeshObject\n{\npublic:\n\n SMDS_ElemIteratorPtr nodesIterator() const;\n SMDS_ElemIteratorPtr edgesIterator() const;\n SMDS_ElemIteratorPtr facesIterator() const;\n virtual SMDS_ElemIteratorPtr elementsIterator(SMDSAbs_ElementType type) const;\n virtual SMDS_ElemIteratorPtr nodesIteratorToUNV() const;\n virtual SMDS_ElemIteratorPtr interlacedNodesElemIterator() const;\n\n \/\/ std-like iteration on nodes\n typedef SMDS_StdIterator< const SMDS_MeshNode*, SMDS_ElemIteratorPtr > iterator;\n iterator begin_nodes() const { return iterator( nodesIterator() ); }\n iterator end_nodes() const { return iterator(); }\n\n virtual int NbNodes() const;\n virtual int NbEdges() const;\n virtual int NbFaces() const;\n inline int GetID() const { return myID; };\n\n \/\/\/Return the type of the current element\n virtual SMDSAbs_ElementType GetType() const = 0;\n virtual SMDSAbs_EntityType GetEntityType() const = 0;\n virtual SMDSAbs_GeometryType GetGeomType() const = 0;\n virtual vtkIdType GetVtkType() const = 0;\n virtual bool IsPoly() const { return false; }\n virtual bool IsQuadratic() const;\n\n virtual bool IsMediumNode(const SMDS_MeshNode* node) const;\n virtual int NbCornerNodes() const;\n\n friend SMDS_EXPORT std::ostream & operator <<(std::ostream & OS, const SMDS_MeshElement *);\n friend SMDS_EXPORT bool SMDS_MeshElementIDFactory::BindID(int ID,SMDS_MeshElement* elem);\n friend class SMDS_Mesh;\n friend class SMESHDS_Mesh;\n friend class SMESHDS_SubMesh;\n friend class SMDS_MeshElementIDFactory;\n\n \/\/ ===========================\n \/\/ Access to nodes by index\n \/\/ ===========================\n \/*!\n * \\brief Return node by its index\n * \\param ind - node index\n * \\retval const SMDS_MeshNode* - the node\n *\/\n virtual const SMDS_MeshNode* GetNode(const int ind) const;\n\n \/*!\n * \\brief Return node by its index\n * \\param ind - node index\n * \\retval const SMDS_MeshNode* - the node\n * \n * Index is wrapped if it is out of a valid range\n *\/\n const SMDS_MeshNode* GetNodeWrap(const int ind) const { return GetNode( WrappedIndex( ind )); }\n\n \/*!\n * \\brief Return true if index of node is valid (0 <= ind < NbNodes())\n * \\param ind - node index\n * \\retval bool - index check result\n *\/\n virtual bool IsValidIndex(const int ind) const;\n\n \/*!\n * \\brief Return a valid node index, fixing the given one if necessary\n * \\param ind - node index\n * \\retval int - valid node index\n *\/\n int WrappedIndex(const int ind) const {\n if ( ind < 0 ) return NbNodes() + ind % NbNodes();\n if ( ind >= NbNodes() ) return ind % NbNodes();\n return ind;\n }\n\n \/*!\n * \\brief Check if a node belongs to the element\n * \\param node - the node to check\n * \\retval int - node index within the element, -1 if not found\n *\/\n int GetNodeIndex( const SMDS_MeshNode* node ) const;\n\n inline ShortType getMeshId() const { return myMeshId; }\n inline LongType getshapeId() const { return myShapeId; }\n inline int getIdInShape() const { return myIdInShape; }\n inline int getVtkId() const { return myVtkID; }\n\n \/*!\n * \\brief Filters of elements, to be used with SMDS_SetIterator\n *\/\n struct TypeFilter\n {\n SMDSAbs_ElementType _type;\n TypeFilter( SMDSAbs_ElementType t = SMDSAbs_NbElementTypes ):_type(t) {}\n bool operator()(const SMDS_MeshElement* e) const { return e && e->GetType() == _type; }\n };\n struct EntityFilter\n {\n SMDSAbs_EntityType _type;\n EntityFilter( SMDSAbs_EntityType t = SMDSEntity_Last ):_type(t) {}\n bool operator()(const SMDS_MeshElement* e) const { return e && e->GetEntityType() == _type; }\n };\n struct GeomFilter\n {\n SMDSAbs_GeometryType _type;\n GeomFilter( SMDSAbs_GeometryType t = SMDSGeom_NONE ):_type(t) {}\n bool operator()(const SMDS_MeshElement* e) const { return e && e->GetGeomType() == _type; }\n };\n\nprotected:\n inline void setId(int id) {myID = id; }\n inline void setShapeId(LongType shapeId) {myShapeId = shapeId; }\n inline void setIdInShape(int id) { myIdInShape = id; }\n inline void setVtkId(int vtkId) { myVtkID = vtkId; }\n SMDS_MeshElement(int ID=-1);\n SMDS_MeshElement(int id, ShortType meshId, LongType shapeId = 0);\n virtual void init(int id = -1, ShortType meshId = -1, LongType shapeId = 0);\n virtual void Print(std::ostream & OS) const;\n\n \/\/! Element index in vector SMDS_Mesh::myNodes or SMDS_Mesh::myCells\n int myID;\n \/\/! index in vtkUnstructuredGrid\n int myVtkID;\n \/\/! SMDS_Mesh identification in SMESH\n ShortType myMeshId;\n \/\/! SubShape and SubMesh identification in SMESHDS\n LongType myShapeId;\n \/\/! Element index in SMESHDS_SubMesh vector\n int myIdInShape;\n};\n\n\n\/\/ ============================================================\n\/*!\n * \\brief Comparator of elements by ID for usage in std containers\n *\/\n\/\/ ============================================================\n\nstruct TIDCompare {\n bool operator () (const SMDS_MeshElement* e1, const SMDS_MeshElement* e2) const\n { return e1->GetID() < e2->GetID(); }\n};\n\n#endif\n<commit_msg>Regression of XSMESH_TEST\/SMESHCOMMON\/SMESH_TEST\/Grids\/smesh\/bugs12\/M6<commit_after>\/\/ Copyright (C) 2007-2013 CEA\/DEN, EDF R&D, OPEN CASCADE\n\/\/\n\/\/ Copyright (C) 2003-2007 OPEN CASCADE, EADS\/CCR, LIP6, CEA\/DEN,\n\/\/ CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS\n\/\/\n\/\/ This library is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU Lesser General Public\n\/\/ License as published by the Free Software Foundation; either\n\/\/ version 2.1 of the License.\n\/\/\n\/\/ This library is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ Lesser General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License along with this library; if not, write to the Free Software\n\/\/ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n\/\/\n\/\/ See http:\/\/www.salome-platform.org\/ or email : webmaster.salome@opencascade.com\n\/\/\n\n\/\/ SMESH SMDS : implementaion of Salome mesh data structure\n\/\/ File : SMDS_MeshElement.hxx\n\/\/ Module : SMESH\n\/\/\n#ifndef _SMDS_MeshElement_HeaderFile\n#define _SMDS_MeshElement_HeaderFile\n\n#include \"SMESH_SMDS.hxx\"\n \n#include \"SMDSAbs_ElementType.hxx\"\n#include \"SMDS_MeshObject.hxx\"\n#include \"SMDS_ElemIterator.hxx\"\n#include \"SMDS_MeshElementIDFactory.hxx\"\n#include \"SMDS_StdIterator.hxx\"\n\n#include <vector>\n#include <iostream>\n\n#include <vtkType.h>\n#include <vtkCellType.h>\n\n\/\/typedef unsigned short UShortType;\ntypedef short ShortType;\ntypedef int LongType;\n\nclass SMDS_MeshNode;\nclass SMDS_MeshEdge;\nclass SMDS_MeshFace;\nclass SMDS_Mesh;\n\n\/\/ ============================================================\n\/*!\n * \\brief Base class for elements\n *\/\n\/\/ ============================================================\n\n\nclass SMDS_EXPORT SMDS_MeshElement:public SMDS_MeshObject\n{\npublic:\n\n SMDS_ElemIteratorPtr nodesIterator() const;\n SMDS_ElemIteratorPtr edgesIterator() const;\n SMDS_ElemIteratorPtr facesIterator() const;\n virtual SMDS_ElemIteratorPtr elementsIterator(SMDSAbs_ElementType type) const;\n virtual SMDS_ElemIteratorPtr nodesIteratorToUNV() const;\n virtual SMDS_ElemIteratorPtr interlacedNodesElemIterator() const;\n\n \/\/ std-like iteration on nodes\n typedef SMDS_StdIterator< const SMDS_MeshNode*, SMDS_ElemIteratorPtr > iterator;\n iterator begin_nodes() const { return iterator( nodesIterator() ); }\n iterator end_nodes() const { return iterator(); }\n\n virtual int NbNodes() const;\n virtual int NbEdges() const;\n virtual int NbFaces() const;\n inline int GetID() const { return myID; };\n\n \/\/\/Return the type of the current element\n virtual SMDSAbs_ElementType GetType() const = 0;\n virtual SMDSAbs_EntityType GetEntityType() const = 0;\n virtual SMDSAbs_GeometryType GetGeomType() const = 0;\n virtual vtkIdType GetVtkType() const = 0;\n virtual bool IsPoly() const { return false; }\n virtual bool IsQuadratic() const;\n\n virtual bool IsMediumNode(const SMDS_MeshNode* node) const;\n virtual int NbCornerNodes() const;\n\n friend SMDS_EXPORT std::ostream & operator <<(std::ostream & OS, const SMDS_MeshElement *);\n friend SMDS_EXPORT bool SMDS_MeshElementIDFactory::BindID(int ID,SMDS_MeshElement* elem);\n friend class SMDS_Mesh;\n friend class SMESHDS_Mesh;\n friend class SMESHDS_SubMesh;\n friend class SMDS_MeshElementIDFactory;\n\n \/\/ ===========================\n \/\/ Access to nodes by index\n \/\/ ===========================\n \/*!\n * \\brief Return node by its index\n * \\param ind - node index\n * \\retval const SMDS_MeshNode* - the node\n *\/\n virtual const SMDS_MeshNode* GetNode(const int ind) const;\n\n \/*!\n * \\brief Return node by its index\n * \\param ind - node index\n * \\retval const SMDS_MeshNode* - the node\n * \n * Index is wrapped if it is out of a valid range\n *\/\n const SMDS_MeshNode* GetNodeWrap(const int ind) const { return GetNode( WrappedIndex( ind )); }\n\n \/*!\n * \\brief Return true if index of node is valid (0 <= ind < NbNodes())\n * \\param ind - node index\n * \\retval bool - index check result\n *\/\n virtual bool IsValidIndex(const int ind) const;\n\n \/*!\n * \\brief Return a valid node index, fixing the given one if necessary\n * \\param ind - node index\n * \\retval int - valid node index\n *\/\n int WrappedIndex(const int ind) const {\n if ( ind < 0 ) return NbNodes() + ind % NbNodes();\n if ( ind >= NbNodes() ) return ind % NbNodes();\n return ind;\n }\n\n \/*!\n * \\brief Check if a node belongs to the element\n * \\param node - the node to check\n * \\retval int - node index within the element, -1 if not found\n *\/\n int GetNodeIndex( const SMDS_MeshNode* node ) const;\n\n inline ShortType getMeshId() const { return myMeshId; }\n inline LongType getshapeId() const { return myShapeId; }\n inline int getIdInShape() const { return myIdInShape; }\n inline int getVtkId() const { return myVtkID; }\n\n \/*!\n * \\brief Filters of elements, to be used with SMDS_SetIterator\n *\/\n struct TypeFilter\n {\n SMDSAbs_ElementType _type;\n TypeFilter( SMDSAbs_ElementType t = SMDSAbs_NbElementTypes ):_type(t) {}\n bool operator()(const SMDS_MeshElement* e) const { return e && e->GetType() == _type; }\n };\n struct EntityFilter\n {\n SMDSAbs_EntityType _type;\n EntityFilter( SMDSAbs_EntityType t = SMDSEntity_Last ):_type(t) {}\n bool operator()(const SMDS_MeshElement* e) const { return e && e->GetEntityType() == _type; }\n };\n struct GeomFilter\n {\n SMDSAbs_GeometryType _type;\n GeomFilter( SMDSAbs_GeometryType t = SMDSGeom_NONE ):_type(t) {}\n bool operator()(const SMDS_MeshElement* e) const { return e && e->GetGeomType() == _type; }\n };\n\nprotected:\n inline void setId(int id) {myID = id; }\n inline void setShapeId(LongType shapeId) {myShapeId = shapeId; }\n inline void setIdInShape(int id) { myIdInShape = id; }\n inline void setVtkId(int vtkId) { myVtkID = vtkId; }\n SMDS_MeshElement(int ID=-1);\n SMDS_MeshElement(int id, ShortType meshId, LongType shapeId = 0);\n virtual void init(int id = -1, ShortType meshId = -1, LongType shapeId = 0);\n virtual void Print(std::ostream & OS) const;\n\n \/\/! Element index in vector SMDS_Mesh::myNodes or SMDS_Mesh::myCells\n int myID;\n \/\/! index in vtkUnstructuredGrid\n int myVtkID;\n \/\/! SMDS_Mesh identification in SMESH\n ShortType myMeshId;\n \/\/! SubShape and SubMesh identification in SMESHDS\n LongType myShapeId;\n \/\/! Element index in SMESHDS_SubMesh vector\n int myIdInShape;\n};\n\n\n\/\/ ============================================================\n\/*!\n * \\brief Comparator of elements by ID for usage in std containers\n *\/\n\/\/ ============================================================\n\nstruct TIDCompare {\n bool operator () (const SMDS_MeshElement* e1, const SMDS_MeshElement* e2) const\n { return e1->GetType() == e2->GetType() ? e1->GetID() < e2->GetID() : e1->GetType() < e2->GetType(); }\n};\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/* Copyright 2018 Carnegie Mellon University\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"scanner\/api\/source.h\"\n#include \"scanner\/api\/enumerator.h\"\n#include \"stdlib\/stdlib.pb.h\"\n\n#include \"scanner\/util\/tinyformat.h\"\n#include \"scanner\/util\/serialize.h\"\n#include \"scanner\/util\/json.hpp\"\n#include \"stdlib\/misc\/sql.h\"\n\n#include <glog\/logging.h>\n#include <vector>\n#include <pqxx\/pqxx>\n\nusing nlohmann::json;\n\nnamespace scanner {\n\n\/\/ NOTE: SQLSource\/Enumerator currently only supports Postgres.\n\nclass SQLEnumerator : public Enumerator {\n public:\n SQLEnumerator(const EnumeratorConfig& config) : Enumerator(config) {\n bool parsed = args_.ParseFromArray(config.args.data(), config.args.size());\n if (!parsed) {\n RESULT_ERROR(&valid_, \"Could not parse SQLEnumeratorArgs\");\n return;\n }\n }\n\n i64 total_elements() override {\n try {\n std::unique_ptr<pqxx::connection> conn = sql_connect(args_.config());\n pqxx::work txn{*conn};\n \/\/ Count the number the number of groups\n auto query = args_.query();\n pqxx::row r = txn.exec1(tfm::format(\n \"SELECT COUNT(DISTINCT(%s)) FROM %s WHERE %s\", query.group(),\n query.table(), args_.filter()));\n return r[0].as<i32>();\n } catch (pqxx::pqxx_exception& e) {\n LOG(FATAL) << e.base().what();\n }\n }\n\n ElementArgs element_args_at(i64 element_idx) override {\n proto::SQLElementArgs args;\n args.set_filter(args_.filter());\n size_t size = args.ByteSizeLong();\n\n ElementArgs element_args;\n element_args.args.resize(size);\n args.SerializeToArray(element_args.args.data(), size);\n element_args.row_id = element_idx;\n\n return element_args;\n }\n\n private:\n Result valid_;\n scanner::proto::SQLEnumeratorArgs args_;\n\n};\n\nclass SQLSource : public Source {\n public:\n SQLSource(const SourceConfig& config) : Source(config) {\n bool parsed = args_.ParseFromArray(config.args.data(), config.args.size());\n if (!parsed) {\n RESULT_ERROR(&valid_, \"Could not parse SQLSourceArgs\");\n return;\n }\n\n \/\/ Query database for mapping from type IDs to type names\n std::unique_ptr<pqxx::connection> conn = sql_connect(args_.config());\n pqxx::work txn{*conn};\n pqxx::result types = txn.exec(\"SELECT oid, typname FROM pg_type\");\n for (auto row : types) {\n pq_types_[row[\"oid\"].as<pqxx::oid>()] = row[\"typname\"].as<std::string>();\n }\n }\n\n void read(const std::vector<ElementArgs>& element_args,\n std::vector<Elements>& output_columns) override {\n LOG_IF(FATAL, element_args.size() == 0) << \"Asked to read zero elements\";\n\n \/\/ Deserialize all ElementArgs\n std::string filter;\n std::vector<i64> row_ids;\n for (size_t i = 0; i < element_args.size(); ++i) {\n proto::SQLElementArgs a;\n bool parsed = a.ParseFromArray(element_args[i].args.data(),\n element_args[i].args.size());\n LOG_IF(FATAL, !parsed) << \"Could not parse element args in SQL\";\n\n row_ids.push_back(element_args[i].row_id);\n filter = a.filter();\n }\n\n auto query = args_.query();\n\n \/\/ If we received elements from a new job, then flush our cached results and run a new query\n if (last_filter_ != filter) {\n last_filter_ = filter;\n\n \/\/ Execute SELECT to fetch all the rows\n std::unique_ptr<pqxx::connection> conn = sql_connect(args_.config());\n pqxx::work txn{*conn};\n std::string query_str = tfm::format(\n \"SELECT %s, %s AS _scanner_id, %s AS _scanner_number FROM %s \"\n \"WHERE %s ORDER BY _scanner_number, _scanner_id\",\n query.fields(), query.id(), query.group(), query.table(),\n filter);\n\n pqxx::result result = txn.exec(query_str);\n LOG_IF(FATAL, result.size() == 0) << \"Query returned zero rows. Executed query was:\\n\" << query_str;\n\n \/\/ Group the rows based on the provided key\n cached_rows_.clear();\n std::vector<pqxx::row> cur_group;\n i32 last_group = result[0][\"_scanner_number\"].as<i32>();\n for (auto row : result) {\n i32 num = row[\"_scanner_number\"].as<i32>();\n if (num != last_group) {\n last_group = num;\n cached_rows_.push_back(cur_group);\n cur_group = std::vector<pqxx::row>();\n }\n cur_group.push_back(row);\n }\n\n cached_rows_.push_back(cur_group);\n }\n\n size_t total_size = 0;\n std::vector<size_t> sizes;\n\n \/\/ Collect requested outputs and serialize to JSON\n std::vector<std::string> rows_serialized;\n for (auto row_id : row_ids) {\n json jrows = json::array();\n auto& row_group = cached_rows_[row_id];\n for (auto row : row_group) {\n jrows.push_back(row_to_json(row));\n }\n std::string serialized = jrows.dump();\n rows_serialized.push_back(serialized);\n sizes.push_back(serialized.size());\n total_size += serialized.size();\n }\n\n \/\/ Pack serialized results into a single block buffer;\n u8* block_buffer = new_block_buffer(CPU_DEVICE, total_size, sizes.size());\n u8* cursor = block_buffer;\n for (i32 i = 0; i < sizes.size(); ++i) {\n memcpy_buffer(cursor, CPU_DEVICE, (u8*) rows_serialized[i].c_str(), CPU_DEVICE, sizes[i]);\n insert_element(output_columns[0], cursor, sizes[i]);\n cursor += sizes[i];\n }\n }\n\n private:\n json row_to_json(pqxx::row row) {\n json jrow;\n\n for (pqxx::field field : row) {\n std::string name(field.name());\n if (name == \"_scanner_id\" || name == \"_scanner_number\") {\n continue;\n }\n\n pqxx::oid type = field.type();\n std::string& typname = pq_types_[type];\n bool assigned = false;\n\n #define ASSIGN_IF(NAME, TYPE) \\\n if (typname == NAME) { jrow[name] = field.as<TYPE>(); assigned = true; }\n\n \/\/ Left argument is the Postgres type name, right argument is the corresponding C++ type\n ASSIGN_IF(\"int4\", i32);\n ASSIGN_IF(\"float8\", f32);\n ASSIGN_IF(\"bool\", bool);\n ASSIGN_IF(\"text\", std::string);\n ASSIGN_IF(\"varchar\", std::string);\n\n LOG_IF(FATAL, !assigned)\n << \"Requested row has field \" << name\n << \" with a type we can't serialize yet: \" << typname;\n }\n\n return std::move(jrow);\n }\n\n Result valid_;\n scanner::proto::SQLSourceArgs args_;\n std::string last_filter_;\n std::vector<std::vector<pqxx::row>> cached_rows_;\n std::map<pqxx::oid, std::string> pq_types_;\n};\n\nREGISTER_ENUMERATOR(SQL, SQLEnumerator)\n .protobuf_name(\"SQLEnumeratorArgs\");\n\nREGISTER_SOURCE(SQL, SQLSource)\n .output(\"output\")\n .protobuf_name(\"SQLSourceArgs\");\n\n} \/\/ namespace scanner\n<commit_msg>Cache total_elements in SQL source<commit_after>\/* Copyright 2018 Carnegie Mellon University\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"scanner\/api\/source.h\"\n#include \"scanner\/api\/enumerator.h\"\n#include \"stdlib\/stdlib.pb.h\"\n\n#include \"scanner\/util\/tinyformat.h\"\n#include \"scanner\/util\/serialize.h\"\n#include \"scanner\/util\/json.hpp\"\n#include \"stdlib\/misc\/sql.h\"\n\n#include <glog\/logging.h>\n#include <vector>\n#include <pqxx\/pqxx>\n\nusing nlohmann::json;\n\nnamespace scanner {\n\n\/\/ NOTE: SQLSource\/Enumerator currently only supports Postgres.\n\nclass SQLEnumerator : public Enumerator {\n public:\n SQLEnumerator(const EnumeratorConfig& config) : Enumerator(config) {\n bool parsed = args_.ParseFromArray(config.args.data(), config.args.size());\n if (!parsed) {\n RESULT_ERROR(&valid_, \"Could not parse SQLEnumeratorArgs\");\n return;\n }\n }\n\n i64 total_elements() override {\n if (total_elements_cached_ == -1) {\n try {\n std::unique_ptr<pqxx::connection> conn = sql_connect(args_.config());\n pqxx::work txn{*conn};\n \/\/ Count the number the number of groups\n auto query = args_.query();\n pqxx::row r = txn.exec1(tfm::format(\n \"SELECT COUNT(DISTINCT(%s)) FROM %s WHERE %s\", query.group(),\n query.table(), args_.filter()));\n total_elements_cached_ = r[0].as<i32>();\n } catch (pqxx::pqxx_exception& e) {\n LOG(FATAL) << e.base().what();\n }\n }\n\n return total_elements_cached_;\n }\n\n ElementArgs element_args_at(i64 element_idx) override {\n proto::SQLElementArgs args;\n args.set_filter(args_.filter());\n size_t size = args.ByteSizeLong();\n\n ElementArgs element_args;\n element_args.args.resize(size);\n args.SerializeToArray(element_args.args.data(), size);\n element_args.row_id = element_idx;\n\n return element_args;\n }\n\n private:\n Result valid_;\n scanner::proto::SQLEnumeratorArgs args_;\n i64 total_elements_cached_ = -1;\n};\n\nclass SQLSource : public Source {\n public:\n SQLSource(const SourceConfig& config) : Source(config) {\n bool parsed = args_.ParseFromArray(config.args.data(), config.args.size());\n if (!parsed) {\n RESULT_ERROR(&valid_, \"Could not parse SQLSourceArgs\");\n return;\n }\n\n \/\/ Query database for mapping from type IDs to type names\n std::unique_ptr<pqxx::connection> conn = sql_connect(args_.config());\n pqxx::work txn{*conn};\n pqxx::result types = txn.exec(\"SELECT oid, typname FROM pg_type\");\n for (auto row : types) {\n pq_types_[row[\"oid\"].as<pqxx::oid>()] = row[\"typname\"].as<std::string>();\n }\n }\n\n void read(const std::vector<ElementArgs>& element_args,\n std::vector<Elements>& output_columns) override {\n LOG_IF(FATAL, element_args.size() == 0) << \"Asked to read zero elements\";\n\n \/\/ Deserialize all ElementArgs\n std::string filter;\n std::vector<i64> row_ids;\n for (size_t i = 0; i < element_args.size(); ++i) {\n proto::SQLElementArgs a;\n bool parsed = a.ParseFromArray(element_args[i].args.data(),\n element_args[i].args.size());\n LOG_IF(FATAL, !parsed) << \"Could not parse element args in SQL\";\n\n row_ids.push_back(element_args[i].row_id);\n filter = a.filter();\n }\n\n auto query = args_.query();\n\n \/\/ If we received elements from a new job, then flush our cached results and run a new query\n if (last_filter_ != filter) {\n last_filter_ = filter;\n\n \/\/ Execute SELECT to fetch all the rows\n std::unique_ptr<pqxx::connection> conn = sql_connect(args_.config());\n pqxx::work txn{*conn};\n std::string query_str = tfm::format(\n \"SELECT %s, %s AS _scanner_id, %s AS _scanner_number FROM %s \"\n \"WHERE %s ORDER BY _scanner_number, _scanner_id\",\n query.fields(), query.id(), query.group(), query.table(),\n filter);\n\n pqxx::result result = txn.exec(query_str);\n LOG_IF(FATAL, result.size() == 0) << \"Query returned zero rows. Executed query was:\\n\" << query_str;\n\n \/\/ Group the rows based on the provided key\n cached_rows_.clear();\n std::vector<pqxx::row> cur_group;\n i32 last_group = result[0][\"_scanner_number\"].as<i32>();\n for (auto row : result) {\n i32 num = row[\"_scanner_number\"].as<i32>();\n if (num != last_group) {\n last_group = num;\n cached_rows_.push_back(cur_group);\n cur_group = std::vector<pqxx::row>();\n }\n cur_group.push_back(row);\n }\n\n cached_rows_.push_back(cur_group);\n }\n\n size_t total_size = 0;\n std::vector<size_t> sizes;\n\n \/\/ Collect requested outputs and serialize to JSON\n std::vector<std::string> rows_serialized;\n for (auto row_id : row_ids) {\n json jrows = json::array();\n auto& row_group = cached_rows_[row_id];\n for (auto row : row_group) {\n jrows.push_back(row_to_json(row));\n }\n std::string serialized = jrows.dump();\n rows_serialized.push_back(serialized);\n sizes.push_back(serialized.size());\n total_size += serialized.size();\n }\n\n \/\/ Pack serialized results into a single block buffer;\n u8* block_buffer = new_block_buffer(CPU_DEVICE, total_size, sizes.size());\n u8* cursor = block_buffer;\n for (i32 i = 0; i < sizes.size(); ++i) {\n memcpy_buffer(cursor, CPU_DEVICE, (u8*) rows_serialized[i].c_str(), CPU_DEVICE, sizes[i]);\n insert_element(output_columns[0], cursor, sizes[i]);\n cursor += sizes[i];\n }\n }\n\n private:\n json row_to_json(pqxx::row row) {\n json jrow;\n\n for (pqxx::field field : row) {\n std::string name(field.name());\n if (name == \"_scanner_id\" || name == \"_scanner_number\") {\n continue;\n }\n\n pqxx::oid type = field.type();\n std::string& typname = pq_types_[type];\n bool assigned = false;\n\n #define ASSIGN_IF(NAME, TYPE) \\\n if (typname == NAME) { jrow[name] = field.as<TYPE>(); assigned = true; }\n\n \/\/ Left argument is the Postgres type name, right argument is the corresponding C++ type\n ASSIGN_IF(\"int4\", i32);\n ASSIGN_IF(\"float8\", f32);\n ASSIGN_IF(\"bool\", bool);\n ASSIGN_IF(\"text\", std::string);\n ASSIGN_IF(\"varchar\", std::string);\n\n LOG_IF(FATAL, !assigned)\n << \"Requested row has field \" << name\n << \" with a type we can't serialize yet: \" << typname;\n }\n\n return std::move(jrow);\n }\n\n Result valid_;\n scanner::proto::SQLSourceArgs args_;\n std::string last_filter_;\n std::vector<std::vector<pqxx::row>> cached_rows_;\n std::map<pqxx::oid, std::string> pq_types_;\n};\n\nREGISTER_ENUMERATOR(SQL, SQLEnumerator)\n .protobuf_name(\"SQLEnumeratorArgs\");\n\nREGISTER_SOURCE(SQL, SQLSource)\n .output(\"output\")\n .protobuf_name(\"SQLSourceArgs\");\n\n} \/\/ namespace scanner\n<|endoftext|>"} {"text":"<commit_before>#include \"fabo-ble113.h\"\n#include <SoftwareSerial.h>\n\nBeaconParam beaconParam;\n\nSoftwareSerial bleShield(12, 13);\nbool DEBUG = false;\n\nvoid ble113::setDebug(){\n DEBUG = true;\n}\n\nvoid ble113::initBLE113()\n{\n \/\/ BLEとの通信用\n bleShield.begin(9600);\n\n if(DEBUG){\n Serial.begin(9600);\n }\n}\n\nvoid ble113::setBeaconUuid(byte uuid[]){\n \n memcpy(beaconParam.uuid, uuid, 16);\n}\n\nvoid ble113::setBeaconMajor(byte major[]){\n\n memcpy(beaconParam.major, major, 2);\n}\n\nvoid ble113::setBeaconMinor(byte minor[]){\n\n memcpy(beaconParam.minor, minor, 2);\n}\n\nbool ble113::sendBeacon(){\n\n byte command[6] = {0x00, \/\/ message type ->0x00:command\n 0x20, \/\/ Minimum payload length\n 0x06, \/\/ Message class -> 0x06:Generic Access Profile\n 0x09, \/\/ Message ID\n 0x00, \/\/ Advertisement data type -> 0x00: sets advertisement data e\n 0x1e}; \/\/ Advertisement data to send\n \n byte beaconHeader[9] = {0x02,\n 0x01,\n 0x06,\n 0x1A,\n 0xFF,\n 0x4C,\n 0x00,\n 0x02,\n 0x15};\n byte txPower = 0xC9;\n \n for(int i = 0; i < 6; i++){ \n bleShield.write((byte)command[i]);\n }\n for(int i = 0; i < 9; i++){ \n bleShield.write((byte)beaconHeader[i]);\n }\n for(int i = 0; i < 16; i++){ \n bleShield.write((byte)beaconParam.uuid[i]);\n }\n for(int i = 0; i < 2; i++){ \n bleShield.write((byte)beaconParam.major[i]);\n }\n for(int i = 0; i < 2; i++){ \n bleShield.write((byte)beaconParam.minor[i]);\n }\n\n bleShield.write((byte)0xC9);\n\n delay(1000);\n \n byte buffer[10];\n int i = 0;\n while (bleShield.available()) {\n buffer[i] = bleShield.read();\n i++;\n }\n \n if(buffer[0] == 0x00 && buffer[1] == 0x02 && buffer[2] == 0x06 && buffer[3] == 0x09){\n if(buffer[4] == 0x00 && buffer[5] == 0x00){\n return true;\n }\n else {\n if(DEBUG){\n Serial.println(\"(sendBeacon)Error Code\");\n Serial.println(buffer[5],HEX);\n Serial.println(buffer[4],HEX);\n }\n return false;\n }\n } else {\n if(DEBUG){\n Serial.println(\"(sendBeacon)Unknow Error\");\n Serial.println(buffer[0],HEX);\n Serial.println(buffer[1],HEX);\n Serial.println(buffer[2],HEX);\n Serial.println(buffer[3],HEX);\n Serial.println(buffer[4],HEX);\n Serial.println(buffer[5],HEX);\n }\n return false;\n }\n}\n\nbool ble113::setMode()\n{\n\n byte command[6] = {0x00, \/\/ message type ->0x00:command\n 0x02, \/\/ Minimum payload length\n 0x06, \/\/ Message class -> 0x06:Generic Access Profile\n 0x01, \/\/ Message ID\n 0x04, \/\/ GAP Discoverable Mode\n 0x00}; \/\/ GAP Connectable Mode\n\n for(int i = 0; i < 6; i++){ \n bleShield.write((byte)command[i]);\n }\n delay(1000);\n\n byte buffer[10];\n int i = 0;\n while (bleShield.available()) {\n buffer[i] = bleShield.read();\n i++;\n }\n\n if(buffer[0] == 0x00 && buffer[1] == 0x02 && buffer[2] == 0x06 && buffer[3] == 0x01){\n if(buffer[4] == 0x00 && buffer[5] == 0x00){\n return true;\n }\n else {\n if(DEBUG){\n Serial.println(\"Error Code\");\n Serial.println(buffer[5],HEX);\n Serial.println(buffer[4],HEX);\n }\n return false;\n }\n } else {\n if(DEBUG){\n Serial.println(\"Unknow Error\");\n Serial.println(buffer[0],HEX);\n Serial.println(buffer[1],HEX);\n Serial.println(buffer[2],HEX);\n Serial.println(buffer[3],HEX);\n Serial.println(buffer[4],HEX);\n Serial.println(buffer[5],HEX);\n }\n return false;\n }\n}\n\n\nbool ble113::setAdvParams()\n{\n byte command[9] = {0x00, \n 0x05,\n 0x06,\n 0x08,\n 0x00,\n 0x02,\n 0x00,\n 0x02,\n 0x07};\n\n for(int i = 0; i < 9; i++){ \n bleShield.write((byte)command[i]);\n }\n delay(1000);\n\n byte buffer[10];\n int i = 0;\n while (bleShield.available()) {\n buffer[i] = bleShield.read();\n i++;\n }\n\n if(buffer[0] == 0x00 && buffer[1] == 0x02 && buffer[2] == 0x06 && buffer[3] == 0x08){\n if(buffer[4] == 0x00 && buffer[5] == 0x00){\n return true;\n }\n else {\n if(DEBUG){\n Serial.println(\"Error Code\");\n Serial.println(buffer[5],HEX);\n Serial.println(buffer[4],HEX);\n }\n return false;\n }\n } else {\n if(DEBUG){\n Serial.println(\"Unknow Error\");\n Serial.println(buffer[0],HEX);\n Serial.println(buffer[1],HEX);\n Serial.println(buffer[2],HEX);\n Serial.println(buffer[3],HEX);\n Serial.println(buffer[4],HEX);\n Serial.println(buffer[5],HEX);\n }\n return false;\n }\n\nble113 faboBLE;\n\n\n<commit_msg>fixture addend{<commit_after>#include \"fabo-ble113.h\"\n#include <SoftwareSerial.h>\n\nBeaconParam beaconParam;\n\nSoftwareSerial bleShield(12, 13);\nbool DEBUG = false;\n\nvoid ble113::setDebug(){\n DEBUG = true;\n}\n\nvoid ble113::initBLE113()\n{\n \/\/ BLEとの通信用\n bleShield.begin(9600);\n \n if(DEBUG){\n Serial.begin(9600);\n }\n}\n\nvoid ble113::setBeaconUuid(byte uuid[]){\n \n memcpy(beaconParam.uuid, uuid, 16);\n}\n\nvoid ble113::setBeaconMajor(byte major[]){\n \n memcpy(beaconParam.major, major, 2);\n}\n\nvoid ble113::setBeaconMinor(byte minor[]){\n \n memcpy(beaconParam.minor, minor, 2);\n}\n\nbool ble113::sendBeacon(){\n \n byte command[6] = {0x00, \/\/ message type ->0x00:command\n 0x20, \/\/ Minimum payload length\n 0x06, \/\/ Message class -> 0x06:Generic Access Profile\n 0x09, \/\/ Message ID\n 0x00, \/\/ Advertisement data type -> 0x00: sets advertisement data e\n 0x1e}; \/\/ Advertisement data to send\n \n byte beaconHeader[9] = {0x02,\n 0x01,\n 0x06,\n 0x1A,\n 0xFF,\n 0x4C,\n 0x00,\n 0x02,\n 0x15};\n byte txPower = 0xC9;\n \n for(int i = 0; i < 6; i++){\n bleShield.write((byte)command[i]);\n }\n for(int i = 0; i < 9; i++){\n bleShield.write((byte)beaconHeader[i]);\n }\n for(int i = 0; i < 16; i++){\n bleShield.write((byte)beaconParam.uuid[i]);\n }\n for(int i = 0; i < 2; i++){\n bleShield.write((byte)beaconParam.major[i]);\n }\n for(int i = 0; i < 2; i++){\n bleShield.write((byte)beaconParam.minor[i]);\n }\n \n bleShield.write((byte)0xC9);\n \n delay(1000);\n \n byte buffer[10];\n int i = 0;\n while (bleShield.available()) {\n buffer[i] = bleShield.read();\n i++;\n }\n \n if(buffer[0] == 0x00 && buffer[1] == 0x02 && buffer[2] == 0x06 && buffer[3] == 0x09){\n if(buffer[4] == 0x00 && buffer[5] == 0x00){\n return true;\n }\n else {\n if(DEBUG){\n Serial.println(\"(sendBeacon)Error Code\");\n Serial.println(buffer[5],HEX);\n Serial.println(buffer[4],HEX);\n }\n return false;\n }\n } else {\n if(DEBUG){\n Serial.println(\"(sendBeacon)Unknow Error\");\n Serial.println(buffer[0],HEX);\n Serial.println(buffer[1],HEX);\n Serial.println(buffer[2],HEX);\n Serial.println(buffer[3],HEX);\n Serial.println(buffer[4],HEX);\n Serial.println(buffer[5],HEX);\n }\n return false;\n }\n}\n\nbool ble113::setMode()\n{\n \n byte command[6] = {0x00, \/\/ message type ->0x00:command\n 0x02, \/\/ Minimum payload length\n 0x06, \/\/ Message class -> 0x06:Generic Access Profile\n 0x01, \/\/ Message ID\n 0x04, \/\/ GAP Discoverable Mode\n 0x00}; \/\/ GAP Connectable Mode\n \n for(int i = 0; i < 6; i++){\n bleShield.write((byte)command[i]);\n }\n delay(1000);\n \n byte buffer[10];\n int i = 0;\n while (bleShield.available()) {\n buffer[i] = bleShield.read();\n i++;\n }\n \n if(buffer[0] == 0x00 && buffer[1] == 0x02 && buffer[2] == 0x06 && buffer[3] == 0x01){\n if(buffer[4] == 0x00 && buffer[5] == 0x00){\n return true;\n }\n else {\n if(DEBUG){\n Serial.println(\"Error Code\");\n Serial.println(buffer[5],HEX);\n Serial.println(buffer[4],HEX);\n }\n return false;\n }\n } else {\n if(DEBUG){\n Serial.println(\"Unknow Error\");\n Serial.println(buffer[0],HEX);\n Serial.println(buffer[1],HEX);\n Serial.println(buffer[2],HEX);\n Serial.println(buffer[3],HEX);\n Serial.println(buffer[4],HEX);\n Serial.println(buffer[5],HEX);\n }\n return false;\n }\n}\n\n\nbool ble113::setAdvParams()\n{\n byte command[9] = {0x00,\n 0x05,\n 0x06,\n 0x08,\n 0x00,\n 0x02,\n 0x00,\n 0x02,\n 0x07};\n \n for(int i = 0; i < 9; i++){\n bleShield.write((byte)command[i]);\n }\n delay(1000);\n \n byte buffer[10];\n int i = 0;\n while (bleShield.available()) {\n buffer[i] = bleShield.read();\n i++;\n }\n \n if(buffer[0] == 0x00 && buffer[1] == 0x02 && buffer[2] == 0x06 && buffer[3] == 0x08){\n if(buffer[4] == 0x00 && buffer[5] == 0x00){\n return true;\n }\n else {\n if(DEBUG){\n Serial.println(\"Error Code\");\n Serial.println(buffer[5],HEX);\n Serial.println(buffer[4],HEX);\n }\n return false;\n }\n } else {\n if(DEBUG){\n Serial.println(\"Unknow Error\");\n Serial.println(buffer[0],HEX);\n Serial.println(buffer[1],HEX);\n Serial.println(buffer[2],HEX);\n Serial.println(buffer[3],HEX);\n Serial.println(buffer[4],HEX);\n Serial.println(buffer[5],HEX);\n }\n return false;\n }\n}\n ble113 faboBLE;<|endoftext|>"} {"text":"<commit_before>\/*===================================================================\n\nThe Medical Imaging Interaction Toolkit (MITK)\n\nCopyright (c) German Cancer Research Center,\nDivision of Medical and Biological Informatics.\nAll rights reserved.\n\nThis software is distributed WITHOUT ANY WARRANTY; without\neven the implied warranty of MERCHANTABILITY or FITNESS FOR\nA PARTICULAR PURPOSE.\n\nSee LICENSE.txt or http:\/\/www.mitk.org for details.\n\n===================================================================*\/\n\n#include \"QmitkToolGUI.h\"\n\n#include <iostream>\n\nQmitkToolGUI::~QmitkToolGUI()\n{\n m_ReferenceCountLock.Lock();\n m_ReferenceCount = 0; \/\/ otherwise ITK will complain in LightObject's destructor\n m_ReferenceCountLock.Unlock();\n}\n\nvoid QmitkToolGUI::Register() const\n{\n \/\/ empty on purpose, just don't let ITK handle calls to Register()\n}\n\nvoid QmitkToolGUI::UnRegister() const\n{\n \/\/ empty on purpose, just don't let ITK handle calls to UnRegister()\n}\n\nvoid QmitkToolGUI::SetReferenceCount(int)\n{\n \/\/ empty on purpose, just don't let ITK handle calls to SetReferenceCount()\n}\n\nvoid QmitkToolGUI::SetTool( mitk::Tool* tool )\n{\n m_Tool = tool;\n\n emit( NewToolAssociated(tool) );\n}\n\n<commit_msg>Add missing keyword to UnRegister definition<commit_after>\/*===================================================================\n\nThe Medical Imaging Interaction Toolkit (MITK)\n\nCopyright (c) German Cancer Research Center,\nDivision of Medical and Biological Informatics.\nAll rights reserved.\n\nThis software is distributed WITHOUT ANY WARRANTY; without\neven the implied warranty of MERCHANTABILITY or FITNESS FOR\nA PARTICULAR PURPOSE.\n\nSee LICENSE.txt or http:\/\/www.mitk.org for details.\n\n===================================================================*\/\n\n#include \"QmitkToolGUI.h\"\n\n#include <iostream>\n\nQmitkToolGUI::~QmitkToolGUI()\n{\n m_ReferenceCountLock.Lock();\n m_ReferenceCount = 0; \/\/ otherwise ITK will complain in LightObject's destructor\n m_ReferenceCountLock.Unlock();\n}\n\nvoid QmitkToolGUI::Register() const\n{\n \/\/ empty on purpose, just don't let ITK handle calls to Register()\n}\n\nvoid QmitkToolGUI::UnRegister() const ITK_NOEXCEPT\n{\n \/\/ empty on purpose, just don't let ITK handle calls to UnRegister()\n}\n\nvoid QmitkToolGUI::SetReferenceCount(int)\n{\n \/\/ empty on purpose, just don't let ITK handle calls to SetReferenceCount()\n}\n\nvoid QmitkToolGUI::SetTool( mitk::Tool* tool )\n{\n m_Tool = tool;\n\n emit( NewToolAssociated(tool) );\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ Created by mpolovyi on 22\/01\/16.\n\/\/\n\n#include <iostream>\n#include <stdlib.h>\n\n#include <cereal\/archives\/json.hpp>\n#include <cereal\/types\/polymorphic.hpp>\n\n#include <SCOLSS\/SimulationController\/MonteCarloSimCtrl\/CMonteCarloSimParams.h>\n#include <SCOLSS\/SimulationController\/MonteCarloSimCtrl\/CMonteCarloSimCtrl.h>\n#include <SCOLSS\/SimulationController\/LangevinSimCtrl\/CLangevinSimParams.h>\n#include <SCOLSS\/SimulationController\/LangevinSimCtrl\/CLangevinSimCtrl.h>\n\n#include <SCOLSS\/ParticlePhysics\/CYukawaDipolePt.h>\n\nvoid InitializeSimulations(int argc, char **argv);\nvoid RunSimulations(std::shared_ptr<CBaseSimCtrl> sim,\n std::string &fullSaveFileName,\n std::string &miniSaveFileName,\n std::string &savePictureFile,\n std::string& fullSaveTarName,\n std::string& miniSaveTarName,\n std::string& pictSaveTarName);\n\nvoid SaveToFile(std::shared_ptr<CBaseSimCtrl> &contr, std::string &fullSaveFileName, std::string &miniSaveFileName, uint64_t cycle,\n std::string& fullSaveTarName,\n std::string& miniSaveTarName);\n\nint main(int argc, char **argv) {\n InitializeSimulations(argc, argv);\n}\n\nvoid InitializeSimulations(int argc, char **argv) {\n std::string simType = argv[2];\n ESimulationType simT;\n if(simType == \"MC\"){\n simT = ESimulationType::MonteCarlo;\n } else if (simType == \"LD\"){\n simT = ESimulationType::LangevinDynamics;\n } else {\n std::cout << \"Unknown simulation type. Exiting.\" << std::endl;\n return;\n }\n\n std::string simDataFileName = argv[1];\n std::string fullSaveTarName = \"FullData_\" + simDataFileName + \"_\" + \".tar\";\n std::string miniSaveTarName = \"MiniData_\" + simDataFileName + \"_\" + \".tar\";\n std::string pictSaveTarName = \"PictData_\" + simDataFileName + \"_\" + \".tar\";\n\n std::string createFullTarCommand = \"tar -cf \" + fullSaveTarName + \" -T \/dev\/null\";\n std::string createMiniTarCommand = \"tar -cf \" + miniSaveTarName + \" -T \/dev\/null\";\n std::string createPictTarCommand = \"tar -cf \" + pictSaveTarName + \" -T \/dev\/null\";\n\n system(createFullTarCommand.c_str());\n system(createMiniTarCommand.c_str());\n system(createPictTarCommand.c_str());\n\n std::string samples = argv[3];\n for(int i = 1; i <= std::stoi(samples); i++) {\n std::ifstream simDataFileStream(simDataFileName);\n\n cereal::JSONInputArchive simDataArchieve(simDataFileStream);\n\n std::shared_ptr<CBaseSimCtrl> sim;\n\n switch (simT){\n case MonteCarlo: {\n CMonteCarloSimParams data;\n data.load(simDataArchieve);\n sim = std::make_shared<CMonteCarloSimCtrl>(CMonteCarloSimCtrl(data));\n break;\n };\n case LangevinDynamics: {\n CLangevinSimParams data;\n data.load(simDataArchieve);\n sim = std::make_shared<CLangevinSimCtrl>(CLangevinSimCtrl(data));\n break;\n };\n }\n\n std::string fullSaveFileName = \"FullData_\" + std::to_string(i) + \"_\" + simDataFileName;\n std::string miniSaveFileName = \"MiniData_\" + std::to_string(i) + \"_\" + simDataFileName;\n std::string pictSaveFileName = \"PictData_\" + std::to_string(i) + \"_\" + simDataFileName;\n\n SaveToFile(sim, fullSaveFileName, miniSaveFileName, 0,\n fullSaveTarName, miniSaveTarName);\n\n RunSimulations(sim, fullSaveFileName, miniSaveFileName, pictSaveFileName,\n fullSaveTarName,\n miniSaveTarName,\n pictSaveTarName);\n\n std::cout << i << std::endl;\n }\n}\n\nvoid RunSimulations(std::shared_ptr<CBaseSimCtrl> sim, std::string &fullSaveFileName, std::string &miniSaveFileName, std::string &pictSaveFileName,\n std::string& fullSaveTarName,\n std::string& miniSaveTarName,\n std::string& pictSaveTarName) {\n {\n\n EPSPlot savePictureFile(pictSaveFileName.c_str(),\n 0,\n 0,\n sim->SimulationParameters.GetEpsDimensionX(),\n sim->SimulationParameters.GetEpsDimensionY());\n\n savePictureFile.initParticleSavings(sim->SimulationParameters.ParticleDiameter);\n\n sim->SaveIntoEps(savePictureFile);\n\n std::chrono::time_point<std::chrono::system_clock> start_time, step_time;\n start_time = std::chrono::system_clock::now();\n uint64_t prev_measure = 0;\n\n uint64_t totalCycles = sim->SimulationParameters.CyclesBetweenSaves * sim->SimulationParameters.NumberOfSavePoints;\n sim->SimulationParameters.NumberOfImageLines = std::min(totalCycles, sim->SimulationParameters.NumberOfImageLines);\n\n for (uint64_t cycle = 1; cycle <= totalCycles; ++cycle) {\n sim->DoCycle();\n\n if (0 == cycle % (sim->SimulationParameters.CyclesBetweenSaves)) {\n SaveToFile(sim, fullSaveFileName, miniSaveFileName, cycle,\n fullSaveTarName, miniSaveTarName);\n }\n\n if (sim->SimulationParameters.SaveEpsPicture && 0 == cycle % (totalCycles \/ sim->SimulationParameters.NumberOfImageLines)) {\n sim->SaveIntoEps(savePictureFile);\n }\n\n auto doFinish = sim->PrintTimeExtrapolation(start_time, prev_measure, totalCycles, cycle);\n if (doFinish) {\n SaveToFile(sim, fullSaveFileName, miniSaveFileName, cycle,\n fullSaveTarName, miniSaveTarName);\n\n sim->SaveIntoEps(savePictureFile);\n break;\n }\n }\n\n }\n if(sim->SimulationParameters.SaveEpsPicture) {\n std::string pictSaveAppendCommand = \"tar -rpf\" + pictSaveTarName + \" \" + pictSaveFileName + \" && rm \" + pictSaveFileName;\n system(pictSaveAppendCommand.c_str());\n }\n}\n\nvoid SaveToFile(std::shared_ptr<CBaseSimCtrl> &contr, std::string &fullSaveFileName, std::string &miniSaveFileName, uint64_t cycle,\n std::string& fullSaveTarName,\n std::string& miniSaveTarName) {\n {\n std::fstream mainFileStream((fullSaveFileName + std::to_string(cycle)).c_str(), std::ios_base::out);\n cereal::JSONOutputArchive mainFileArchieve(mainFileStream);\n\n std::fstream minimalFileStream((miniSaveFileName + std::to_string(cycle)).c_str(), std::ios_base::out);\n cereal::JSONOutputArchive minimalFileArchieve(minimalFileStream);\n\n switch (contr->SimulationParameters.SaveParticlesInfo) {\n case true:\n contr->save(mainFileArchieve);\n contr->SaveMinimal(minimalFileArchieve);\n break;\n\n case false:\n contr->save(minimalFileArchieve);\n break;\n }\n }\n\n std::string fullSaveAppendCommand =\n \"tar -rpf\" + fullSaveTarName + \" \" + fullSaveFileName + std::to_string(cycle) + \" && rm \" + fullSaveFileName + std::to_string(cycle);\n std::string miniSaveAppendCommand =\n \"tar -rpf\" + miniSaveTarName + \" \" + miniSaveFileName + std::to_string(cycle) + \" && rm \" + miniSaveFileName + std::to_string(cycle);\n\n switch (contr->SimulationParameters.SaveParticlesInfo) {\n case true:\n system(fullSaveAppendCommand.c_str());\n system(miniSaveAppendCommand.c_str());\n break;\n\n case false:\n system(miniSaveAppendCommand.c_str());\n break;\n }\n}\n<commit_msg>typo in tar file names<commit_after>\/\/\n\/\/ Created by mpolovyi on 22\/01\/16.\n\/\/\n\n#include <iostream>\n#include <stdlib.h>\n\n#include <cereal\/archives\/json.hpp>\n#include <cereal\/types\/polymorphic.hpp>\n\n#include <SCOLSS\/SimulationController\/MonteCarloSimCtrl\/CMonteCarloSimParams.h>\n#include <SCOLSS\/SimulationController\/MonteCarloSimCtrl\/CMonteCarloSimCtrl.h>\n#include <SCOLSS\/SimulationController\/LangevinSimCtrl\/CLangevinSimParams.h>\n#include <SCOLSS\/SimulationController\/LangevinSimCtrl\/CLangevinSimCtrl.h>\n\n#include <SCOLSS\/ParticlePhysics\/CYukawaDipolePt.h>\n\nvoid InitializeSimulations(int argc, char **argv);\nvoid RunSimulations(std::shared_ptr<CBaseSimCtrl> sim,\n std::string &fullSaveFileName,\n std::string &miniSaveFileName,\n std::string &savePictureFile,\n std::string& fullSaveTarName,\n std::string& miniSaveTarName,\n std::string& pictSaveTarName);\n\nvoid SaveToFile(std::shared_ptr<CBaseSimCtrl> &contr, std::string &fullSaveFileName, std::string &miniSaveFileName, uint64_t cycle,\n std::string& fullSaveTarName,\n std::string& miniSaveTarName);\n\nint main(int argc, char **argv) {\n InitializeSimulations(argc, argv);\n}\n\nvoid InitializeSimulations(int argc, char **argv) {\n std::string simType = argv[2];\n ESimulationType simT;\n if(simType == \"MC\"){\n simT = ESimulationType::MonteCarlo;\n } else if (simType == \"LD\"){\n simT = ESimulationType::LangevinDynamics;\n } else {\n std::cout << \"Unknown simulation type. Exiting.\" << std::endl;\n return;\n }\n\n std::string simDataFileName = argv[1];\n std::string fullSaveTarName = \"FullData_\" + simDataFileName + \".tar\";\n std::string miniSaveTarName = \"MiniData_\" + simDataFileName + \".tar\";\n std::string pictSaveTarName = \"PictData_\" + simDataFileName + \".tar\";\n\n std::string createFullTarCommand = \"tar -cf \" + fullSaveTarName + \" -T \/dev\/null\";\n std::string createMiniTarCommand = \"tar -cf \" + miniSaveTarName + \" -T \/dev\/null\";\n std::string createPictTarCommand = \"tar -cf \" + pictSaveTarName + \" -T \/dev\/null\";\n\n system(createFullTarCommand.c_str());\n system(createMiniTarCommand.c_str());\n system(createPictTarCommand.c_str());\n\n std::string samples = argv[3];\n for(int i = 1; i <= std::stoi(samples); i++) {\n std::ifstream simDataFileStream(simDataFileName);\n\n cereal::JSONInputArchive simDataArchieve(simDataFileStream);\n\n std::shared_ptr<CBaseSimCtrl> sim;\n\n switch (simT){\n case MonteCarlo: {\n CMonteCarloSimParams data;\n data.load(simDataArchieve);\n sim = std::make_shared<CMonteCarloSimCtrl>(CMonteCarloSimCtrl(data));\n break;\n };\n case LangevinDynamics: {\n CLangevinSimParams data;\n data.load(simDataArchieve);\n sim = std::make_shared<CLangevinSimCtrl>(CLangevinSimCtrl(data));\n break;\n };\n }\n\n std::string fullSaveFileName = \"FullData_\" + std::to_string(i) + \"_\" + simDataFileName;\n std::string miniSaveFileName = \"MiniData_\" + std::to_string(i) + \"_\" + simDataFileName;\n std::string pictSaveFileName = \"PictData_\" + std::to_string(i) + \"_\" + simDataFileName;\n\n SaveToFile(sim, fullSaveFileName, miniSaveFileName, 0,\n fullSaveTarName, miniSaveTarName);\n\n RunSimulations(sim, fullSaveFileName, miniSaveFileName, pictSaveFileName,\n fullSaveTarName,\n miniSaveTarName,\n pictSaveTarName);\n\n std::cout << i << std::endl;\n }\n}\n\nvoid RunSimulations(std::shared_ptr<CBaseSimCtrl> sim, std::string &fullSaveFileName, std::string &miniSaveFileName, std::string &pictSaveFileName,\n std::string& fullSaveTarName,\n std::string& miniSaveTarName,\n std::string& pictSaveTarName) {\n {\n\n EPSPlot savePictureFile(pictSaveFileName.c_str(),\n 0,\n 0,\n sim->SimulationParameters.GetEpsDimensionX(),\n sim->SimulationParameters.GetEpsDimensionY());\n\n savePictureFile.initParticleSavings(sim->SimulationParameters.ParticleDiameter);\n\n sim->SaveIntoEps(savePictureFile);\n\n std::chrono::time_point<std::chrono::system_clock> start_time, step_time;\n start_time = std::chrono::system_clock::now();\n uint64_t prev_measure = 0;\n\n uint64_t totalCycles = sim->SimulationParameters.CyclesBetweenSaves * sim->SimulationParameters.NumberOfSavePoints;\n sim->SimulationParameters.NumberOfImageLines = std::min(totalCycles, sim->SimulationParameters.NumberOfImageLines);\n\n for (uint64_t cycle = 1; cycle <= totalCycles; ++cycle) {\n sim->DoCycle();\n\n if (0 == cycle % (sim->SimulationParameters.CyclesBetweenSaves)) {\n SaveToFile(sim, fullSaveFileName, miniSaveFileName, cycle,\n fullSaveTarName, miniSaveTarName);\n }\n\n if (sim->SimulationParameters.SaveEpsPicture && 0 == cycle % (totalCycles \/ sim->SimulationParameters.NumberOfImageLines)) {\n sim->SaveIntoEps(savePictureFile);\n }\n\n auto doFinish = sim->PrintTimeExtrapolation(start_time, prev_measure, totalCycles, cycle);\n if (doFinish) {\n SaveToFile(sim, fullSaveFileName, miniSaveFileName, cycle,\n fullSaveTarName, miniSaveTarName);\n\n sim->SaveIntoEps(savePictureFile);\n break;\n }\n }\n\n }\n if(sim->SimulationParameters.SaveEpsPicture) {\n std::string pictSaveAppendCommand = \"tar -rpf\" + pictSaveTarName + \" \" + pictSaveFileName + \" && rm \" + pictSaveFileName;\n system(pictSaveAppendCommand.c_str());\n }\n}\n\nvoid SaveToFile(std::shared_ptr<CBaseSimCtrl> &contr, std::string &fullSaveFileName, std::string &miniSaveFileName, uint64_t cycle,\n std::string& fullSaveTarName,\n std::string& miniSaveTarName) {\n {\n std::fstream mainFileStream((fullSaveFileName + std::to_string(cycle)).c_str(), std::ios_base::out);\n cereal::JSONOutputArchive mainFileArchieve(mainFileStream);\n\n std::fstream minimalFileStream((miniSaveFileName + std::to_string(cycle)).c_str(), std::ios_base::out);\n cereal::JSONOutputArchive minimalFileArchieve(minimalFileStream);\n\n switch (contr->SimulationParameters.SaveParticlesInfo) {\n case true:\n contr->save(mainFileArchieve);\n contr->SaveMinimal(minimalFileArchieve);\n break;\n\n case false:\n contr->save(minimalFileArchieve);\n break;\n }\n }\n\n std::string fullSaveAppendCommand =\n \"tar -rpf\" + fullSaveTarName + \" \" + fullSaveFileName + std::to_string(cycle) + \" && rm \" + fullSaveFileName + std::to_string(cycle);\n std::string miniSaveAppendCommand =\n \"tar -rpf\" + miniSaveTarName + \" \" + miniSaveFileName + std::to_string(cycle) + \" && rm \" + miniSaveFileName + std::to_string(cycle);\n\n switch (contr->SimulationParameters.SaveParticlesInfo) {\n case true:\n system(fullSaveAppendCommand.c_str());\n system(miniSaveAppendCommand.c_str());\n break;\n\n case false:\n system(miniSaveAppendCommand.c_str());\n break;\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\n#include \"fastareader.h\"\n#include \"util.h\"\n#include <sstream>\n\nFastaReader::FastaReader(string faFile, bool forceUpperCase)\n{\n \/\/ Set locale and disable stdio synchronization to improve iostream performance\n \/\/ http:\/\/www.drdobbs.com\/the-standard-librarian-iostreams-and-std\/184401305\n \/\/ http:\/\/stackoverflow.com\/questions\/5166263\/how-to-get-iostream-to-perform-better\n setlocale(LC_ALL,\"C\");\n ios_base::sync_with_stdio(false);\n\n mFastaFile = faFile;\n mForceUpperCase = forceUpperCase;\n if (is_directory(mFastaFile)) {\n string error_msg = \"There is a problem with the provided fasta file: \\'\";\n error_msg.append(mFastaFile);\n error_msg.append(\"\\' is a directory NOT a file...\\n\");\n throw invalid_argument(error_msg);\n }\n mFastaFileStream.open( mFastaFile.c_str(),ios::in);\n \/\/ verify that the file can be read\n if (!mFastaFileStream.is_open()) {\n string msg = \"There is a problem with the provided fasta file: could NOT read \";\n msg.append(mFastaFile.c_str());\n msg.append(\"...\\n\");\n throw invalid_argument(msg);\n }\n\n char c;\n \/\/ seek to first contig\n while (mFastaFileStream.get(c) && c != '>') {\n if (mFastaFileStream.eof()) {\n break;\n }\n }\n}\n\nFastaReader::~FastaReader()\n{\n if (mFastaFileStream.is_open()) {\n mFastaFileStream.close();\n }\n}\n\nvoid FastaReader::readNext()\n{\n mCurrentID = \"\";\n mCurrentDescription = \"\";\n mCurrentSequence = \"\";\n bool foundHeader = false;\n \n char c;\n stringstream ssSeq;\n stringstream ssHeader;\n while(true){\n mFastaFileStream.get(c);\n if(c == '>' || mFastaFileStream.eof())\n break;\n else {\n if (foundHeader)\n ssSeq << c;\n else\n ssHeader << c;\n }\n\n string line = \"\";\n getline(mFastaFileStream,line,'\\n');\n\n\n if(foundHeader == false) {\n ssHeader << line;\n foundHeader = true;\n }\n else {\n str_keep_valid_sequence(line, mForceUpperCase);\n ssSeq << line;\n }\n }\n mCurrentSequence = ssSeq.str();\n string header = ssHeader.str();\n\n int space = header.find(\" \");\n mCurrentID = header.substr(0, space);\n}\n\nbool FastaReader::hasNext() {\n return !mFastaFileStream.eof();\n}\n\nvoid FastaReader::readAll() {\n while(!mFastaFileStream.eof()){\n readNext();\n mAllContigs[mCurrentID] = mCurrentSequence;\n }\n}\n\nbool FastaReader::test(){\n FastaReader reader(\"testdata\/tinyref.fa\");\n reader.readAll();\n\n string contig1 = \"GATCACAGGTCTATCACCCTATTAATTGGTATTTTCGTCTGGGGGGTGTGGAGCCGGAGCACCCTATGTCGCAGT\";\n string contig2 = \"GTCTGCACAGCCGCTTTCCACACAGAACCCCCCCCTCCCCCCGCTTCTGGCAAACCCCAAAAACAAAGAACCCTA\";\n\n if(reader.mAllContigs.count(\"contig1\") == 0 || reader.mAllContigs.count(\"contig2\") == 0 )\n return false;\n\n if(reader.mAllContigs[\"contig1\"] != contig1 || reader.mAllContigs[\"contig2\"] != contig2 )\n return false;\n\n return true;\n\n}\n\n\n\n<commit_msg>fix FastaReader lower case bug<commit_after>\n#include \"fastareader.h\"\n#include \"util.h\"\n#include <sstream>\n\nFastaReader::FastaReader(string faFile, bool forceUpperCase)\n{\n \/\/ Set locale and disable stdio synchronization to improve iostream performance\n \/\/ http:\/\/www.drdobbs.com\/the-standard-librarian-iostreams-and-std\/184401305\n \/\/ http:\/\/stackoverflow.com\/questions\/5166263\/how-to-get-iostream-to-perform-better\n setlocale(LC_ALL,\"C\");\n ios_base::sync_with_stdio(false);\n\n mFastaFile = faFile;\n mForceUpperCase = forceUpperCase;\n if (is_directory(mFastaFile)) {\n string error_msg = \"There is a problem with the provided fasta file: \\'\";\n error_msg.append(mFastaFile);\n error_msg.append(\"\\' is a directory NOT a file...\\n\");\n throw invalid_argument(error_msg);\n }\n mFastaFileStream.open( mFastaFile.c_str(),ios::in);\n \/\/ verify that the file can be read\n if (!mFastaFileStream.is_open()) {\n string msg = \"There is a problem with the provided fasta file: could NOT read \";\n msg.append(mFastaFile.c_str());\n msg.append(\"...\\n\");\n throw invalid_argument(msg);\n }\n\n char c;\n \/\/ seek to first contig\n while (mFastaFileStream.get(c) && c != '>') {\n if (mFastaFileStream.eof()) {\n break;\n }\n }\n}\n\nFastaReader::~FastaReader()\n{\n if (mFastaFileStream.is_open()) {\n mFastaFileStream.close();\n }\n}\n\nvoid FastaReader::readNext()\n{\n mCurrentID = \"\";\n mCurrentDescription = \"\";\n mCurrentSequence = \"\";\n bool foundHeader = false;\n \n char c;\n stringstream ssSeq;\n stringstream ssHeader;\n while(true){\n mFastaFileStream.get(c);\n if(c == '>' || mFastaFileStream.eof())\n break;\n else {\n if (foundHeader){\n if(mForceUpperCase && c>='a' && c<='z') {\n c -= ('a' - 'A');\n }\n ssSeq << c;\n }\n else\n ssHeader << c;\n }\n\n string line = \"\";\n getline(mFastaFileStream,line,'\\n');\n\n\n if(foundHeader == false) {\n ssHeader << line;\n foundHeader = true;\n }\n else {\n str_keep_valid_sequence(line, mForceUpperCase);\n ssSeq << line;\n }\n }\n mCurrentSequence = ssSeq.str();\n string header = ssHeader.str();\n\n int space = header.find(\" \");\n mCurrentID = header.substr(0, space);\n}\n\nbool FastaReader::hasNext() {\n return !mFastaFileStream.eof();\n}\n\nvoid FastaReader::readAll() {\n while(!mFastaFileStream.eof()){\n readNext();\n mAllContigs[mCurrentID] = mCurrentSequence;\n }\n}\n\nbool FastaReader::test(){\n FastaReader reader(\"testdata\/tinyref.fa\");\n reader.readAll();\n\n string contig1 = \"GATCACAGGTCTATCACCCTATTAATTGGTATTTTCGTCTGGGGGGTGTGGAGCCGGAGCACCCTATGTCGCAGT\";\n string contig2 = \"GTCTGCACAGCCGCTTTCCACACAGAACCCCCCCCTCCCCCCGCTTCTGGCAAACCCCAAAAACAAAGAACCCTA\";\n\n if(reader.mAllContigs.count(\"contig1\") == 0 || reader.mAllContigs.count(\"contig2\") == 0 )\n return false;\n\n if(reader.mAllContigs[\"contig1\"] != contig1 || reader.mAllContigs[\"contig2\"] != contig2 )\n return false;\n\n return true;\n\n}\n\n\n\n<|endoftext|>"} {"text":"<commit_before>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ webcam.cpp --a part of libdecodeqr\n\/\/\n\/\/ Copyright (c) 2006 NISHI Takao <zophos@koka-in.org>\n\/\/\n\/\/ This is free software with ABSOLUTELY NO WARRANTY.\n\/\/ You can redistribute and\/or modify it under the terms of GPLv2.\n\/\/\n\/\/ $Id$\n\/\/\n#include <stdio.h>\n#include <highgui.h>\n#include \"..\/..\/libdecodeqr\/decodeqr.h\"\n\nint main(int argc,char *argv[])\n{\n \/\/\n \/\/ start camera\n \/\/\n CvCapture *capture=cvCaptureFromCAM(0);\n if(!capture)\n return(-1);\n\n \/\/\n \/\/ initialize qr decoder\n \/\/\n QrDecoderHandle decoder=qr_decoder_open();\n printf(\"libdecodeqr version %s\\n\",qr_decoder_version());\n\n \n cvNamedWindow(\"src\",1);\n cvNamedWindow(\"bin\",1);\n\n puts(\"Hit [SPACE] key to grab, or any key to end.\");\n puts(\"\");\n\n \/\/\n \/\/ 1 shot grabing\n \/\/\n \/\/\n \/\/ allocate grabed buffer to decoder\n \/\/\n int key=-1;\n\n IplImage *src=cvQueryFrame(capture);\n if(src)\n qr_decoder_set_image_buffer(decoder,src);\n else\n key=1;\n\n unsigned char *text=NULL;\n int text_size=0;\n\n while(key<=0){\n cvShowImage(\"src\",src);\n key=cvWaitKey(150);\n\n \/\/\n \/\/ when [SPACE] key pressed, do decode.\n \/\/\n if(key==0x20){\n key=-1;\n\n \/\/\n \/\/ if left-bottom origin (MS-Windows style) format,\n \/\/ it must be converted to left-top origin.\n \/\/\n if(src->origin)\n cvConvertImage(src,src,CV_CVTIMG_FLIP);\n\n \/\/\n \/\/ While decoding is a failure, decrease the\n \/\/ adaptive_th_size parameter.\n \/\/ Note that the adaptive_th_size must be odd.\n \/\/\n for(short sz=25,stat=0;\n (sz>=3)&&((stat&QR_IMAGEREADER_DECODED)==0);\n sz-=2)\n stat=qr_decoder_decode(decoder,sz);\n\n \/\/\n \/\/ for debug, show binarized image.\n \/\/\n cvShowImage(\"bin\",\n qr_decoder_get_binarized_image_buffer(decoder));\n printf(\"adaptive_th_size=%d, status=%04x\\n\",sz,stat);\n\n \/\/\n \/\/ on suceed decoding, print decoded text.\n \/\/\n if(stat&=QR_IMAGEREADER_DECODED){\n QrCodeHeader header;\n qr_decoder_get_header(decoder,&header);\n if(text_sz<header.byte_size+1){\n if(text)\n delete text;\n \n text_sz=header.byte_size+1;\n text=new unsigned char[text_sz];\n }\n qr_decoder_get_body(decoder,text,text_sz);\n printf(\"%s\\n\\n\",text);\n\n key=cvWaitKey(1000);\n }\n }\n\n src=cvQueryFrame(capture);\n if(!src)\n break;\n }\n \n if(text)\n delete text;\n\n qr_decoder_close(decoder);\n cvReleaseCapture(&capture);\n\n return(0);\n}\n<commit_msg> * fixed for gcc<commit_after>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ webcam.cpp --a part of libdecodeqr\n\/\/\n\/\/ Copyright (c) 2006 NISHI Takao <zophos@koka-in.org>\n\/\/\n\/\/ This is free software with ABSOLUTELY NO WARRANTY.\n\/\/ You can redistribute and\/or modify it under the terms of GPLv2.\n\/\/\n\/\/ $Id$\n\/\/\n#include <stdio.h>\n#include <highgui.h>\n#include \"..\/..\/libdecodeqr\/decodeqr.h\"\n\nint main(int argc,char *argv[])\n{\n \/\/\n \/\/ start camera\n \/\/\n CvCapture *capture=cvCaptureFromCAM(0);\n if(!capture)\n return(-1);\n\n \/\/\n \/\/ initialize qr decoder\n \/\/\n QrDecoderHandle decoder=qr_decoder_open();\n printf(\"libdecodeqr version %s\\n\",qr_decoder_version());\n\n \n cvNamedWindow(\"src\",1);\n cvNamedWindow(\"bin\",1);\n\n puts(\"Hit [SPACE] key to grab, or any key to end.\");\n puts(\"\");\n\n \/\/\n \/\/ 1 shot grabing\n \/\/\n \/\/\n \/\/ allocate grabed buffer to decoder\n \/\/\n int key=-1;\n\n IplImage *src=cvQueryFrame(capture);\n if(src)\n qr_decoder_set_image_buffer(decoder,src);\n else\n key=1;\n\n unsigned char *text=NULL;\n int text_size=0;\n\n while(key<=0){\n cvShowImage(\"src\",src);\n key=cvWaitKey(150);\n\n \/\/\n \/\/ when [SPACE] key pressed, do decode.\n \/\/\n if(key==0x20){\n key=-1;\n\n \/\/\n \/\/ if left-bottom origin (MS-Windows style) format,\n \/\/ it must be converted to left-top origin.\n \/\/\n if(src->origin)\n cvConvertImage(src,src,CV_CVTIMG_FLIP);\n\n \/\/\n \/\/ While decoding is a failure, decrease the\n \/\/ adaptive_th_size parameter.\n \/\/ Note that the adaptive_th_size must be odd.\n \/\/\n short sz,stat;\n for(sz=25,stat=0;\n (sz>=3)&&((stat&QR_IMAGEREADER_DECODED)==0);\n sz-=2)\n stat=qr_decoder_decode(decoder,sz);\n\n \/\/\n \/\/ for debug, show binarized image.\n \/\/\n cvShowImage(\"bin\",\n qr_decoder_get_binarized_image_buffer(decoder));\n printf(\"adaptive_th_size=%d, status=%04x\\n\",sz,stat);\n\n \/\/\n \/\/ on suceed decoding, print decoded text.\n \/\/\n if(stat&=QR_IMAGEREADER_DECODED){\n QrCodeHeader header;\n qr_decoder_get_header(decoder,&header);\n if(text_sz<header.byte_size+1){\n if(text)\n delete text;\n \n text_sz=header.byte_size+1;\n text=new unsigned char[text_sz];\n }\n qr_decoder_get_body(decoder,text,text_sz);\n printf(\"%s\\n\\n\",text);\n\n key=cvWaitKey(1000);\n }\n }\n\n src=cvQueryFrame(capture);\n if(!src)\n break;\n }\n \n if(text)\n delete text;\n\n qr_decoder_close(decoder);\n cvReleaseCapture(&capture);\n\n return(0);\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"..\/kontsevich_graph_series.hpp\"\n#include <ginac\/ginac.h>\n#include <iostream>\n#include <vector>\n#include <fstream>\n#include <limits>\n#include <sstream>\nusing namespace std;\nusing namespace GiNaC;\n\nint main(int argc, char* argv[])\n{\n if (argc != 2)\n {\n cout << \"Usage: \" << argv[0] << \" <graph-series-filename>\\n\";\n return 1;\n }\n \n \/\/ Reading in graph series:\n string graph_series_filename(argv[1]);\n ifstream graph_series_file(graph_series_filename);\n parser coefficient_reader;\n KontsevichGraphSeries<ex> graph_series = KontsevichGraphSeries<ex>::from_istream(graph_series_file, [&coefficient_reader](std::string s) -> ex { return coefficient_reader(s); });\n graph_series.reduce();\n\n for (size_t n = 0; n <= graph_series.precision(); ++n)\n {\n cout << \"h^\" << n << \":\\n\";\n for (auto& term : graph_series[n])\n {\n cout << term.second.encoding() << \" \" << term.first << \"\\n\";\n }\n }\n}\n<commit_msg>Add option --print-differential-orders to reduce<commit_after>#include \"..\/kontsevich_graph_series.hpp\"\n#include <ginac\/ginac.h>\n#include <iostream>\n#include <vector>\n#include <fstream>\n#include <limits>\n#include <sstream>\nusing namespace std;\nusing namespace GiNaC;\n\nint main(int argc, char* argv[])\n{\n if (argc != 2 && argc != 3)\n {\n cout << \"Usage: \" << argv[0] << \" <graph-series-filename> [--print-differential-orders]\\n\";\n return 1;\n }\n\n bool print_differential_orders = false;\n if (argc == 3 && string(argv[2]) == \"--print-differential-orders\")\n print_differential_orders = true;\n \n \/\/ Reading in graph series:\n string graph_series_filename(argv[1]);\n ifstream graph_series_file(graph_series_filename);\n parser coefficient_reader;\n KontsevichGraphSeries<ex> graph_series = KontsevichGraphSeries<ex>::from_istream(graph_series_file, [&coefficient_reader](std::string s) -> ex { return coefficient_reader(s); });\n graph_series.reduce();\n\n for (size_t n = 0; n <= graph_series.precision(); ++n)\n {\n if (graph_series[n] != 0 || n == graph_series.precision())\n cout << \"h^\" << n << \":\\n\";\n for (auto& indegree : graph_series[n].in_degrees(true))\n {\n if (print_differential_orders)\n {\n cout << \"# \";\n for (size_t in : indegree)\n cout << in << \" \";\n cout << \"\\n\";\n }\n for (auto& term : graph_series[n][indegree])\n {\n cout << term.second.encoding() << \" \" << term.first << \"\\n\";\n }\n }\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ ChContactContainerGPU.cpp\n\/\/\n\/\/ ------------------------------------------------\n\/\/ Copyright:Alessandro Tasora \/ DeltaKnowledge\n\/\/ www.deltaknowledge.com\n\/\/ ------------------------------------------------\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"chrono_parallel\/collision\/ChContactContainerParallel.h\"\n\n#include \"physics\/ChSystem.h\"\n#include \"physics\/ChBody.h\"\n#include \"physics\/ChParticlesClones.h\"\n#include \"lcp\/ChLcpConstraintTwoContactN.h\"\n#include \"collision\/ChCModelBulletBody.h\"\n#include \"collision\/ChCModelBulletParticle.h\"\n\n#include \"core\/ChMemory.h\" \/\/ must be last include (memory leak debugger). In .cpp only.\n\nnamespace chrono {\n\nusing namespace collision;\nusing namespace geometry;\n\n\/\/ Register into the object factory, to enable run-time\n\/\/ dynamic creation and persistence\nChClassRegister<ChContactContainerParallel> a_registration_ChContactContainerGPU;\n\nChContactContainerParallel::ChContactContainerParallel(ChParallelDataManager* dc)\n: data_container(dc)\n{\n n_added = 0;\n}\n\nChContactContainerParallel::~ChContactContainerParallel() {\n n_added = 0;\n}\n\n} \/\/ END_OF_NAMESPACE____\n\n<commit_msg>Remove unnecessary code.<commit_after>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ ChContactContainerGPU.cpp\n\/\/\n\/\/ ------------------------------------------------\n\/\/ Copyright:Alessandro Tasora \/ DeltaKnowledge\n\/\/ www.deltaknowledge.com\n\/\/ ------------------------------------------------\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"chrono_parallel\/collision\/ChContactContainerParallel.h\"\n\n#include \"physics\/ChSystem.h\"\n#include \"physics\/ChBody.h\"\n#include \"physics\/ChParticlesClones.h\"\n#include \"lcp\/ChLcpConstraintTwoContactN.h\"\n#include \"collision\/ChCModelBulletBody.h\"\n#include \"collision\/ChCModelBulletParticle.h\"\n\n#include \"core\/ChMemory.h\" \/\/ must be last include (memory leak debugger). In .cpp only.\n\nnamespace chrono {\n\nusing namespace collision;\nusing namespace geometry;\n\nChContactContainerParallel::ChContactContainerParallel(ChParallelDataManager* dc)\n: data_container(dc)\n{\n n_added = 0;\n}\n\nChContactContainerParallel::~ChContactContainerParallel() {\n n_added = 0;\n}\n\n} \/\/ END_OF_NAMESPACE____\n\n<|endoftext|>"} {"text":"<commit_before>#include \"core_prop\/Solver_prop.h\"\n#include \"MinisatCore_prop.h\"\n#include \"utils\/System.h\"\n\nnamespace BEEV\n{\n\n template <class T>\n MinisatCore_prop<T>::MinisatCore_prop(volatile bool& timeout)\n {\n s = new T(timeout);\n };\n\n template <class T>\n MinisatCore_prop<T>::~MinisatCore_prop()\n {\n delete s;\n }\n\n template <class T>\n bool\n MinisatCore_prop<T>::addArray(int array_id, const SATSolver::vec_literals& i, const SATSolver::vec_literals& v, const Minisat::vec<Minisat::lbool> & ki, const Minisat::vec<Minisat::lbool> & kv )\n {\n\t s->addArray(array_id, i,v, ki,kv);\n return true;\n }\n\n\n template <class T>\n bool\n MinisatCore_prop<T>::addClause(const SATSolver::vec_literals& ps) \/\/ Add a clause to the solver.\n {\n s->addClause(ps);\n }\n\n template <class T>\n bool\n MinisatCore_prop<T>::okay() const \/\/ FALSE means solver is in a conflicting state\n {\n return s->okay();\n }\n\n template <class T>\n bool\n MinisatCore_prop<T>::solve() \/\/ Search without assumptions.\n {\n if (!s->simplify())\n return false;\n\n return s->solve();\n\n }\n\n template <class T>\n uint8_t\n MinisatCore_prop<T>::modelValue(Var x) const\n {\n return Minisat::toInt(s->modelValue(x));\n }\n\n template <class T>\n Minisat::Var\n MinisatCore_prop<T>::newVar()\n {\n return s->newVar();\n }\n\n template <class T>\n void MinisatCore_prop<T>::setVerbosity(int v)\n {\n s->verbosity = v;\n }\n\n template <class T>\n int MinisatCore_prop<T>::nVars()\n {return s->nVars();}\n\n template <class T>\n void MinisatCore_prop<T>::printStats()\n {\n s->printStats();\n }\n\n template <class T>\n void MinisatCore_prop<T>::setSeed(int i)\n {\n s->random_seed = i;\n }\n\n template class MinisatCore_prop<Minisat::Solver_prop>;\n};\n<commit_msg>Forgot to pass on return value, fixing<commit_after>#include \"core_prop\/Solver_prop.h\"\n#include \"MinisatCore_prop.h\"\n#include \"utils\/System.h\"\n\nnamespace BEEV\n{\n\n template <class T>\n MinisatCore_prop<T>::MinisatCore_prop(volatile bool& timeout)\n {\n s = new T(timeout);\n };\n\n template <class T>\n MinisatCore_prop<T>::~MinisatCore_prop()\n {\n delete s;\n }\n\n template <class T>\n bool\n MinisatCore_prop<T>::addArray(int array_id, const SATSolver::vec_literals& i, const SATSolver::vec_literals& v, const Minisat::vec<Minisat::lbool> & ki, const Minisat::vec<Minisat::lbool> & kv )\n {\n\t s->addArray(array_id, i,v, ki,kv);\n return true;\n }\n\n\n template <class T>\n bool\n MinisatCore_prop<T>::addClause(const SATSolver::vec_literals& ps) \/\/ Add a clause to the solver.\n {\n return s->addClause(ps);\n }\n\n template <class T>\n bool\n MinisatCore_prop<T>::okay() const \/\/ FALSE means solver is in a conflicting state\n {\n return s->okay();\n }\n\n template <class T>\n bool\n MinisatCore_prop<T>::solve() \/\/ Search without assumptions.\n {\n if (!s->simplify())\n return false;\n\n return s->solve();\n\n }\n\n template <class T>\n uint8_t\n MinisatCore_prop<T>::modelValue(Var x) const\n {\n return Minisat::toInt(s->modelValue(x));\n }\n\n template <class T>\n Minisat::Var\n MinisatCore_prop<T>::newVar()\n {\n return s->newVar();\n }\n\n template <class T>\n void MinisatCore_prop<T>::setVerbosity(int v)\n {\n s->verbosity = v;\n }\n\n template <class T>\n int MinisatCore_prop<T>::nVars()\n {return s->nVars();}\n\n template <class T>\n void MinisatCore_prop<T>::printStats()\n {\n s->printStats();\n }\n\n template <class T>\n void MinisatCore_prop<T>::setSeed(int i)\n {\n s->random_seed = i;\n }\n\n template class MinisatCore_prop<Minisat::Solver_prop>;\n};\n<|endoftext|>"} {"text":"<commit_before>\/\/ run as\n\/\/ root -l -b -q lydia2_print_params_observs.C > lydia2_params_observs.txt\n\nusing namespace RooFit ;\n\n\nvoid lydia2_print_params_observs()\n{\n\n TFile *_file0 = TFile::Open(\"\/user\/pbos\/lydia\/lydia2.root\");\n \/\/ TFile *_file0 = TFile::Open(\"\/home\/patrick\/projects\/apcocsm\/lydia\/lydia2.root\");\n RooWorkspace* w = static_cast<RooWorkspace*>(gDirectory->Get(\"combined\"));\n RooStats::ModelConfig* mc = static_cast<RooStats::ModelConfig*>(w->genobj(\"ModelConfig\"));\n RooAbsPdf* pdf = w->pdf(mc->GetPdf()->GetName()) ;\n\n RooAbsData * data = w->data(\"combData\");\n\n RooArgSet* params = pdf->getParameters(data);\n RooAbsCollection* const_params = params->selectByAttrib(\"Constant\",kTRUE);\n RooAbsCollection* var_params = params->selectByAttrib(\"Constant\",kFALSE);\n RooArgSet* observs = pdf->getObservables(data);\n\n \/\/ params->Print()\n \/\/ params->Print(\"v\")\n const_params->Print();\n var_params->Print();\n observs->Print();\n\n \/\/ const_params->writeToFile(\"lydia2_const_params.txt\")\n \/\/ var_params->writeToFile(\"lydia2_var_params.txt\")\n \/\/ observs->writeToFile(\"lydia2_observs.txt\")\n}<commit_msg>Modified paths for new laptop<commit_after>\/\/ run as\n\/\/ root -l -b -q lydia2_print_params_observs.C > lydia2_params_observs.txt\n\nusing namespace RooFit ;\n\n\nvoid lydia2_print_params_observs()\n{\n\n \/\/ TFile *_file0 = TFile::Open(\"\/user\/pbos\/lydia\/lydia2.root\");\n TFile *_file0 = TFile::Open(\"\/Users\/pbos\/projects\/apcocsm\/lydia\/lydia2.root\");\n RooWorkspace* w = static_cast<RooWorkspace*>(gDirectory->Get(\"combined\"));\n RooStats::ModelConfig* mc = static_cast<RooStats::ModelConfig*>(w->genobj(\"ModelConfig\"));\n RooAbsPdf* pdf = w->pdf(mc->GetPdf()->GetName()) ;\n\n RooAbsData * data = w->data(\"combData\");\n\n RooArgSet* params = pdf->getParameters(data);\n RooAbsCollection* const_params = params->selectByAttrib(\"Constant\",kTRUE);\n RooAbsCollection* var_params = params->selectByAttrib(\"Constant\",kFALSE);\n RooArgSet* observs = pdf->getObservables(data);\n\n \/\/ params->Print()\n \/\/ params->Print(\"v\")\n const_params->Print();\n var_params->Print();\n observs->Print();\n\n \/\/ const_params->writeToFile(\"lydia2_const_params.txt\")\n \/\/ var_params->writeToFile(\"lydia2_var_params.txt\")\n \/\/ observs->writeToFile(\"lydia2_observs.txt\")\n}\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n\nusing namespace std;\n\nclass NumDays {\n\n\tconst double HOURS_PER_DAY = 8;\n\nprivate:\n\tdouble hours;\n\tdouble days;\n\n\npublic:\n\tNumDays() {\n\n\t}\n\tNumDays(double hours) {\n\t\tthis->setHours(hours);\n\t}\n\n\tdouble getHours() {\n\t\treturn this->hours;\n\t}\n\n\tdouble getDays() {\n\t\treturn this->days;\n\t}\n\n\tvoid setHours(double hours) {\n\t\tthis->hours = hours;\n\t\tthis->days = hours \/ HOURS_PER_DAY;\n\t}\n\n\tNumDays & operator + (const NumDays & x) {\n\t\treturn NumDays(this->hours + x.hours);\n\t}\n\n\tNumDays & operator - (const NumDays & x) {\n\t\treturn NumDays(this->hours - x.hours);\n\t}\n\n\tNumDays & operator ++ () {\n\t\treturn NumDays(this->hours++);\n\t}\n\n\tNumDays & operator -- () {\n\t\treturn NumDays(this->hours--);\n\t}\n};\n\nint main() {\n\n\tdouble hours1 = 8;\n\tdouble hours2 = 12;\n\n\tNumDays days1(hours1);\n\tNumDays days2(hours2);\n\n\tcout << days1.getDays() << endl;\n\tcout << days2.getDays() << endl;\n\n\tcout << endl;\n\n\tdays1++;\n\n\tcout << days1.getDays() << endl;\n\n}\n<commit_msg>Update Homework-8.cpp<commit_after>#include <iostream>\n#include <stdio.h>\n\nusing namespace std;\n\n\/**\n* Class Definition of NumDays\n*\/\nclass NumDays {\n\n\tconst double HOURS_PER_DAY = 8.0;\n\nprivate:\n\tint hours = 0;\n\tdouble days = 0.0;\n\n\npublic:\n\t\/**\n\t* Default Constructor\n\t*\/\n\tNumDays();\n\t\n\t\/**\n\t* Hours initilizing Constructor.\n\t*\n\t* @param int hours;\n\t*\/\n\tNumDays(int hours);\n\n\t\/**\n\t* Getter for hours\n\t* \n\t* @return int\n\t*\/\n\tint getHours();\n\n\t\/**\n\t* Getter for days\n\t* \n\t* @return double\n\t*\/\n\tdouble getDays();\n\n\t\/**\n\t* Setter for setting hours and recalculating days.\n\t* \n\t* @param int hours\n\t* @return void\n\t*\/\n\tvoid setHours(int hours);\n\n\t\/**\n\t* Addition Operator Overload\n\t* \n\t* @param NumDays& x\n\t* @return NumDays\n\t*\/\n\tNumDays operator+(NumDays& x);\n\n\t\/**\n\t* Subtraction Operator Overload\n\t* \n\t* @param NumDays& x\n\t* @return NumDays\n\t*\/\n\tNumDays operator-(NumDays& x);\n\n\t\/**\n\t* Storing Operator Overload\n\t*\n\t* @param const NumDays&\n\t* @return void\n\t*\/\n\tvoid operator=(const NumDays&);\n\n\t\/**\n\t* Prefix increment operator overload.\n\t*\n\t* @return NumDays\n\t*\/\n\tNumDays& operator++();\n\n\t\/**\n\t* Postfix increment operator overload.\n\t*\n\t* @return NumDays\n\t*\/\n\tNumDays operator++(int);\n\n\t\/**\n\t* Prefix decrement operator overload.\n\t*\n\t* @return NumDays\n\t*\/\n\tNumDays& operator--();\n\n\t\/**\n\t* Postfix decrement operator overload.\n\t*\n\t* @return NumDays\n\t*\/\n\tNumDays operator--(int);\n\n\t\/**\n\t* Prints the hours and days. \"1 days == 8 hours\"\n\t*\n\t* @return void\n\t*\/\n\tvoid printObject() {\n\t\tcout << endl << this->getDays() << \" days == \" << this->getHours() << \" hours\" << endl << endl;\n\t}\n\n};\n\nNumDays::NumDays() {}\n\nNumDays::NumDays(int hours) {\n\tthis->setHours(hours);\n}\n\nint NumDays::getHours() {\n\treturn this->hours;\n}\n\ndouble NumDays::getDays() {\n\treturn this->days;\n}\n\nvoid NumDays::setHours(int hours) {\n\tthis->hours = hours;\n\tthis->days = hours \/ NumDays::HOURS_PER_DAY;\n}\n\nNumDays NumDays::operator+(NumDays& x) {\n\treturn NumDays(this->hours + x.hours);\n}\n\nNumDays NumDays::operator-(NumDays& x) {\n\treturn NumDays(this->hours - x.hours);\n}\n\nvoid NumDays::operator=(const NumDays& x) {\n\tthis->setHours(x.hours);\n}\n\nNumDays& NumDays::operator++() {\n\tthis->hours++;\n\tthis->setHours(this->hours);\n\treturn *this;\n}\n\nNumDays NumDays::operator++(int) {\n\tthis->setHours(++this->hours);\n\treturn *this;\n}\n\nNumDays& NumDays::operator--() {\n\tthis->hours--;\n\tthis->setHours(this->hours);\n\treturn *this;\n}\n\nNumDays NumDays::operator--(int) {\n\tthis->setHours(--this->hours);\n\treturn *this;\n}\n\nint main() {\n\n\twhile (true) {\n\t\tint hours;\n\n\t\tcout << \"Set hours: \";\n\t\tcin >> hours;\n\n\t\tNumDays days1(hours);\n\n\t\tdays1.printObject();\n\n\t\twhile (true) {\n\t\t\tint selection;\n\n\t\t\tcout << \"Select One: \" << endl;\n\t\t\tcout << \"1. Prefix Increment Object.\" << endl;\n\t\t\tcout << \"2. Postfix increment Object.\" << endl;\n\t\t\tcout << \"3. Prefix Decrement Object.\" << endl;\n\t\t\tcout << \"4. Postfix Decrement Object.\" << endl;\n\t\t\tcout << \"5. Add another object to this one.\" << endl;\n\t\t\tcout << \"6. Subtract another object from this one\" << endl;\n\t\t\tcout << \"7. Stop\" << endl;\n\t\t\tcout << \"Select -> \";\n\t\t\tcin >> selection;\n\n\t\t\tint newHours;\n\t\t\tNumDays newObject;\n\n\t\t\tswitch (selection) {\n\t\t\tcase 1:\n\t\t\t\t++days1;\n\t\t\t\tbreak;\n\t\t\tcase 2:\n\t\t\t\tdays1++;\n\t\t\t\tbreak;\n\t\t\tcase 3:\n\t\t\t\t--days1;\n\t\t\t\tbreak;\n\t\t\tcase 4:\n\t\t\t\tdays1--;\n\t\t\t\tbreak;\n\t\t\tcase 5:\n\t\t\t\tcout << \"Set new object's hours: \";\n\t\t\t\tcin >> newHours;\n\t\t\t\tnewObject.setHours(newHours);\n\t\t\t\tdays1 = days1 + newObject;\n\t\t\t\tbreak;\n\t\t\tcase 6:\n\t\t\t\tcout << \"Set new object's hours: \";\n\t\t\t\tcin >> newHours;\n\t\t\t\tnewObject.setHours(newHours);\n\t\t\t\tdays1 = days1 - newObject;\n\t\t\t\tbreak;\n\t\t\tcase 7:\n\t\t\t\tgoto end;\n\t\t\t}\n\t\t\tdays1.printObject();\n\t\t\tcontinue;\n\n\t\tend:\n\t\t\tbreak;\n\t\t}\n\n\t\tint choice;\n\n\t\tcout << \"Would you like to go again?\" << endl;\n\t\tcout << \"1. Yes\" << endl;\n\t\tcout << \"2. No\" << endl;\n\t\tcin >> choice;\n\n\t\tif (choice == 2) {\n\t\t\tbreak;\n\t\t}\n\t\telse if (choice == 1) {\n\t\t\tcontinue;\n\t\t}\n\t}\n\n}\n<|endoftext|>"} {"text":"<commit_before>#include <bureaucracy\/timer.hpp>\n\n#include <algorithm>\n#include <cassert>\n\nusing bureaucracy::Timer;\n\nTimer::Timer()\n : my_nextFuture{my_futureEvents.end()}\n , my_nextId{0}\n , my_isAccepting{true}\n , my_isRunning{true}\n , my_isFiring{false}\n{\n my_timerThread = std::thread{[this]() {\n std::unique_lock<std::mutex> lock{my_mutex};\n\n while(my_isAccepting)\n {\n if(my_futureEvents.empty())\n {\n my_wakeup.wait(lock);\n }\n else\n {\n auto const now = std::chrono::steady_clock::now();\n auto begin = std::begin(my_futureEvents);\n auto const end = std::end(my_futureEvents);\n auto last = std::find_if(begin, end, [now](auto const & event) {\n return now < event.due;\n });\n if(begin != last)\n {\n my_isFiring = true;\n my_nextFuture = last;\n lock.unlock();\n std::for_each(begin, last, [this](auto & futureEvent) {\n auto it = my_events.find(futureEvent.event);\n assert(it != my_events.end());\n it->second();\n });\n lock.lock();\n my_isFiring = false;\n my_futureEvents.erase(begin, last);\n my_nextFuture = my_futureEvents.begin();\n std::for_each(\n std::begin(my_pendingEvents),\n std::end(my_pendingEvents), [this](auto & event) {\n auto it = std::find_if(\n std::begin(my_futureEvents),\n std::end(my_futureEvents),\n [&event](auto const & futureEvent) {\n return event.due < futureEvent.due;\n });\n my_futureEvents.emplace(\n it, FutureEvent{event.event, event.due});\n my_events.emplace(event.event, std::move(event.fn));\n });\n my_pendingEvents.erase(std::begin(my_pendingEvents),\n std::end(my_pendingEvents));\n }\n else\n {\n auto alarm = (*begin).due;\n my_wakeup.wait_until(lock, alarm);\n }\n }\n }\n }};\n}\n\n\/\/\/ \\cond false\nTimer::~Timer() noexcept\n{\n stop();\n}\n\/\/\/ \\endcond\n\nTimer::Item Timer::add(Event event, Time due)\n{\n std::lock_guard<std::mutex> lock{my_mutex};\n\n if(my_isAccepting)\n {\n auto id = [this]() {\n auto ret = my_nextId;\n auto it = my_events.find(ret);\n while(it != my_events.end())\n {\n ++ret;\n it = my_events.find(ret);\n }\n my_nextId = ret + 1;\n return ret;\n }();\n\n if(my_isFiring)\n {\n my_pendingEvents.emplace_back(\n PendingEvent{id, due, std::move(event)});\n }\n else\n {\n auto it = std::find_if(std::begin(my_futureEvents),\n std::end(my_futureEvents),\n [due](auto const & currentEvent) {\n return due < currentEvent.due;\n });\n my_futureEvents.emplace(it, FutureEvent{id, due});\n my_events.emplace(id, std::move(event));\n my_nextFuture = std::begin(my_futureEvents);\n my_wakeup.notify_one();\n }\n return Item{this, id};\n }\n else\n {\n throw std::runtime_error{\"Not accepting\"};\n }\n}\n\nvoid Timer::stop()\n{\n std::unique_lock<std::mutex> lock{my_mutex};\n\n if(my_isAccepting)\n {\n my_isAccepting = false;\n my_wakeup.notify_one();\n lock.unlock();\n my_timerThread.join();\n lock.lock();\n my_isRunning = false;\n }\n}\n\nbool Timer::isAccepting() const noexcept\n{\n std::lock_guard<std::mutex> lock{my_mutex};\n return my_isAccepting;\n}\n\nbool Timer::isRunning() const noexcept\n{\n std::lock_guard<std::mutex> lock{my_mutex};\n return my_isRunning;\n}\n\nTimer::Item::CancelStatus Timer::cancel(Timer::Item item)\n{\n std::lock_guard<std::mutex> lock{my_mutex};\n\n \/\/ If we're firing, check the pending events since they haven't been merged\n \/\/ in yet.\n if(my_isFiring)\n {\n auto const pendingEnd = std::end(my_pendingEvents);\n auto const pendingIt = std::find_if(\n std::begin(my_pendingEvents),\n pendingEnd, [id = item.my_id](auto const & pendingEvent) {\n return pendingEvent.event == id;\n });\n if(pendingIt != pendingEnd)\n {\n my_pendingEvents.erase(pendingIt);\n return Timer::Item::CancelStatus::cancelled;\n }\n }\n\n \/\/ We need to the check the future events whether we're firing or not.\n auto const end = std::end(my_futureEvents);\n auto futureIt = std::find_if(\n my_nextFuture, end, [id = item.my_id](auto const & futureEvent) {\n return futureEvent.event == id;\n });\n if(futureIt != end)\n {\n my_futureEvents.erase(futureIt);\n my_events.erase(item.my_id);\n return Timer::Item::CancelStatus::cancelled;\n }\n\n \/\/ At this point, we didn't find the item in either queue. It's either an\n \/\/ invalid id or queued to fire.\n return Timer::Item::CancelStatus::failed;\n}\n\nTimer::Timer::Item::Item(Timer * const timer, Id id)\n : my_timer{timer}\n , my_id{id}\n{\n}\n<commit_msg>Fix issue raised by clang-tidy<commit_after>#include <bureaucracy\/timer.hpp>\n\n#include <algorithm>\n#include <cassert>\n\nusing bureaucracy::Timer;\n\nTimer::Timer()\n : my_nextFuture{my_futureEvents.end()}\n , my_nextId{0}\n , my_isAccepting{true}\n , my_isRunning{true}\n , my_isFiring{false}\n{\n my_timerThread = std::thread{[this]() {\n std::unique_lock<std::mutex> lock{my_mutex};\n\n while(my_isAccepting)\n {\n if(my_futureEvents.empty())\n {\n my_wakeup.wait(lock);\n }\n else\n {\n auto const now = std::chrono::steady_clock::now();\n auto begin = std::begin(my_futureEvents);\n auto const end = std::end(my_futureEvents);\n auto last = std::find_if(begin, end, [now](auto const & event) {\n return now < event.due;\n });\n if(begin != last)\n {\n my_isFiring = true;\n my_nextFuture = last;\n lock.unlock();\n std::for_each(begin, last, [this](auto & futureEvent) {\n auto it = my_events.find(futureEvent.event);\n assert(it != my_events.end());\n it->second();\n });\n lock.lock();\n my_isFiring = false;\n my_futureEvents.erase(begin, last);\n my_nextFuture = my_futureEvents.begin();\n std::for_each(\n std::begin(my_pendingEvents),\n std::end(my_pendingEvents), [this](auto & event) {\n auto it = std::find_if(\n std::begin(my_futureEvents),\n std::end(my_futureEvents),\n [&event](auto const & futureEvent) {\n return event.due < futureEvent.due;\n });\n my_futureEvents.emplace(\n it, FutureEvent{event.event, event.due});\n my_events.emplace(event.event, std::move(event.fn));\n });\n my_pendingEvents.erase(std::begin(my_pendingEvents),\n std::end(my_pendingEvents));\n }\n else\n {\n auto alarm = (*begin).due;\n my_wakeup.wait_until(lock, alarm);\n }\n }\n }\n }};\n}\n\n\/\/\/ \\cond false\nTimer::~Timer() noexcept\n{\n stop();\n}\n\/\/\/ \\endcond\n\nTimer::Item Timer::add(Event event, Time due)\n{\n std::lock_guard<std::mutex> lock{my_mutex};\n\n if(my_isAccepting)\n {\n auto id = [this]() {\n auto ret = my_nextId;\n auto it = my_events.find(ret);\n while(it != my_events.end())\n {\n ++ret;\n it = my_events.find(ret);\n }\n my_nextId = ret + 1;\n return ret;\n }();\n\n if(my_isFiring)\n {\n my_pendingEvents.emplace_back(\n PendingEvent{id, due, std::move(event)});\n }\n else\n {\n auto it = std::find_if(std::begin(my_futureEvents),\n std::end(my_futureEvents),\n [due](auto const & currentEvent) {\n return due < currentEvent.due;\n });\n my_futureEvents.emplace(it, FutureEvent{id, due});\n my_events.emplace(id, std::move(event));\n my_nextFuture = std::begin(my_futureEvents);\n my_wakeup.notify_one();\n }\n return Item{this, id};\n }\n throw std::runtime_error{\"Not accepting\"};\n}\n\nvoid Timer::stop()\n{\n std::unique_lock<std::mutex> lock{my_mutex};\n\n if(my_isAccepting)\n {\n my_isAccepting = false;\n my_wakeup.notify_one();\n lock.unlock();\n my_timerThread.join();\n lock.lock();\n my_isRunning = false;\n }\n}\n\nbool Timer::isAccepting() const noexcept\n{\n std::lock_guard<std::mutex> lock{my_mutex};\n return my_isAccepting;\n}\n\nbool Timer::isRunning() const noexcept\n{\n std::lock_guard<std::mutex> lock{my_mutex};\n return my_isRunning;\n}\n\nTimer::Item::CancelStatus Timer::cancel(Timer::Item item)\n{\n std::lock_guard<std::mutex> lock{my_mutex};\n\n \/\/ If we're firing, check the pending events since they haven't been merged\n \/\/ in yet.\n if(my_isFiring)\n {\n auto const pendingEnd = std::end(my_pendingEvents);\n auto const pendingIt = std::find_if(\n std::begin(my_pendingEvents),\n pendingEnd, [id = item.my_id](auto const & pendingEvent) {\n return pendingEvent.event == id;\n });\n if(pendingIt != pendingEnd)\n {\n my_pendingEvents.erase(pendingIt);\n return Timer::Item::CancelStatus::cancelled;\n }\n }\n\n \/\/ We need to the check the future events whether we're firing or not.\n auto const end = std::end(my_futureEvents);\n auto futureIt = std::find_if(\n my_nextFuture, end, [id = item.my_id](auto const & futureEvent) {\n return futureEvent.event == id;\n });\n if(futureIt != end)\n {\n my_futureEvents.erase(futureIt);\n my_events.erase(item.my_id);\n return Timer::Item::CancelStatus::cancelled;\n }\n\n \/\/ At this point, we didn't find the item in either queue. It's either an\n \/\/ invalid id or queued to fire.\n return Timer::Item::CancelStatus::failed;\n}\n\nTimer::Timer::Item::Item(Timer * const timer, Id id)\n : my_timer{timer}\n , my_id{id}\n{\n}\n<|endoftext|>"} {"text":"<commit_before>\n\/*\n * Copyright 2011 Google Inc.\n *\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n *\/\n#include \"gm.h\"\n#include \"SkGradientShader.h\"\n\nnamespace skiagm {\n\nstruct GradData {\n int fCount;\n const SkColor* fColors;\n const SkScalar* fPos;\n};\n\nstatic const SkColor gColors[] = {\n SK_ColorRED, SK_ColorGREEN, SK_ColorBLUE, SK_ColorWHITE, SK_ColorBLACK\n};\nstatic const SkScalar gPos0[] = { 0, SK_Scalar1 };\nstatic const SkScalar gPos1[] = { SK_Scalar1\/4, SK_Scalar1*3\/4 };\nstatic const SkScalar gPos2[] = {\n 0, SK_Scalar1\/8, SK_Scalar1\/2, SK_Scalar1*7\/8, SK_Scalar1\n};\n\nstatic const GradData gGradData[] = {\n { 2, gColors, NULL },\n { 2, gColors, gPos0 },\n { 2, gColors, gPos1 },\n { 5, gColors, NULL },\n { 5, gColors, gPos2 }\n};\n\nstatic SkShader* MakeLinear(const SkPoint pts[2], const GradData& data,\n SkShader::TileMode tm, SkUnitMapper* mapper) {\n return SkGradientShader::CreateLinear(pts, data.fColors, data.fPos,\n data.fCount, tm, mapper);\n}\n\nstatic SkShader* MakeRadial(const SkPoint pts[2], const GradData& data,\n SkShader::TileMode tm, SkUnitMapper* mapper) {\n SkPoint center;\n center.set(SkScalarAve(pts[0].fX, pts[1].fX),\n SkScalarAve(pts[0].fY, pts[1].fY));\n return SkGradientShader::CreateRadial(center, center.fX, data.fColors,\n data.fPos, data.fCount, tm, mapper);\n}\n\nstatic SkShader* MakeSweep(const SkPoint pts[2], const GradData& data,\n SkShader::TileMode tm, SkUnitMapper* mapper) {\n SkPoint center;\n center.set(SkScalarAve(pts[0].fX, pts[1].fX),\n SkScalarAve(pts[0].fY, pts[1].fY));\n return SkGradientShader::CreateSweep(center.fX, center.fY, data.fColors,\n data.fPos, data.fCount, mapper);\n}\n\nstatic SkShader* Make2Radial(const SkPoint pts[2], const GradData& data,\n SkShader::TileMode tm, SkUnitMapper* mapper) {\n SkPoint center0, center1;\n center0.set(SkScalarAve(pts[0].fX, pts[1].fX),\n SkScalarAve(pts[0].fY, pts[1].fY));\n center1.set(SkScalarInterp(pts[0].fX, pts[1].fX, SkIntToScalar(3)\/5),\n SkScalarInterp(pts[0].fY, pts[1].fY, SkIntToScalar(1)\/4));\n return SkGradientShader::CreateTwoPointRadial(\n center1, (pts[1].fX - pts[0].fX) \/ 7,\n center0, (pts[1].fX - pts[0].fX) \/ 2,\n data.fColors, data.fPos, data.fCount, tm, mapper);\n}\n\ntypedef SkShader* (*GradMaker)(const SkPoint pts[2], const GradData& data,\n SkShader::TileMode tm, SkUnitMapper* mapper);\nstatic const GradMaker gGradMakers[] = {\n MakeLinear, MakeRadial, MakeSweep, Make2Radial\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nclass GradientsGM : public GM {\npublic:\n\tGradientsGM() {\n this->setBGColor(0xFFDDDDDD);\n }\n \nprotected:\n SkString onShortName() {\n return SkString(\"gradients\");\n }\n \n virtual SkISize onISize() { return make_isize(640, 510); }\n \n virtual void onDraw(SkCanvas* canvas) {\n \n SkPoint pts[2] = {\n { 0, 0 },\n { SkIntToScalar(100), SkIntToScalar(100) }\n };\n SkShader::TileMode tm = SkShader::kClamp_TileMode;\n SkRect r = { 0, 0, SkIntToScalar(100), SkIntToScalar(100) };\n SkPaint paint;\n paint.setAntiAlias(true);\n \n canvas->translate(SkIntToScalar(20), SkIntToScalar(20));\n for (size_t i = 0; i < SK_ARRAY_COUNT(gGradData); i++) {\n canvas->save();\n for (size_t j = 0; j < SK_ARRAY_COUNT(gGradMakers); j++) {\n SkShader* shader = gGradMakers[j](pts, gGradData[i], tm, NULL);\n paint.setShader(shader);\n canvas->drawRect(r, paint);\n shader->unref();\n canvas->translate(0, SkIntToScalar(120));\n }\n canvas->restore();\n canvas->translate(SkIntToScalar(120), 0);\n }\n }\n \nprivate:\n typedef GM INHERITED;\n};\n\n\/*\n Inspired by this <canvas> javascript, where we need to detect that we are not\n solving a quadratic equation, but must instead solve a linear (since our X^2\n coefficient is 0)\n\n ctx.fillStyle = '#f00';\n ctx.fillRect(0, 0, 100, 50);\n \n var g = ctx.createRadialGradient(-80, 25, 70, 0, 25, 150);\n g.addColorStop(0, '#f00');\n g.addColorStop(0.01, '#0f0');\n g.addColorStop(0.99, '#0f0');\n g.addColorStop(1, '#f00');\n ctx.fillStyle = g;\n ctx.fillRect(0, 0, 100, 50);\n *\/\nclass GradientsDegenrate2PointGM : public GM {\npublic:\n GradientsDegenrate2PointGM() {}\n \nprotected:\n SkString onShortName() {\n return SkString(\"gradients_degenerate_2pt\");\n }\n \n\tvirtual SkISize onISize() { return make_isize(320, 320); }\n \n void drawBG(SkCanvas* canvas) {\n canvas->drawColor(SK_ColorBLUE);\n }\n \n virtual void onDraw(SkCanvas* canvas) {\n this->drawBG(canvas);\n \n SkColor colors[] = { SK_ColorRED, SK_ColorGREEN, SK_ColorGREEN, SK_ColorRED };\n SkScalar pos[] = { 0, SkFloatToScalar(0.01f), SkFloatToScalar(0.99f), SK_Scalar1 };\n SkPoint c0;\n c0.iset(-80, 25);\n SkScalar r0 = SkIntToScalar(70);\n SkPoint c1;\n c1.iset(0, 25);\n SkScalar r1 = SkIntToScalar(150);\n SkShader* s = SkGradientShader::CreateTwoPointRadial(c0, r0, c1, r1, colors,\n pos, SK_ARRAY_COUNT(pos),\n SkShader::kClamp_TileMode);\n SkPaint paint;\n paint.setShader(s)->unref();\n canvas->drawPaint(paint);\n }\n \nprivate:\n typedef GM INHERITED;\n};\n\n\/\/\/ Tests correctness of *optimized* codepaths in gradients.\n\nclass ClampedGradientsGM : public GM {\npublic:\n ClampedGradientsGM() {}\n\nprotected:\n SkString onShortName() { return SkString(\"clamped_gradients\"); }\n\n virtual SkISize onISize() { return make_isize(640, 510); }\n\n void drawBG(SkCanvas* canvas) {\n canvas->drawColor(0xFFDDDDDD);\n }\n\n virtual void onDraw(SkCanvas* canvas) {\n this->drawBG(canvas);\n\n SkRect r = { 0, 0, SkIntToScalar(100), SkIntToScalar(300) };\n SkPaint paint;\n paint.setAntiAlias(true);\n\n SkPoint center;\n center.iset(0, 300);\n canvas->translate(SkIntToScalar(20), SkIntToScalar(20));\n SkShader* shader = SkGradientShader::CreateRadial(\n SkPoint(center),\n SkIntToScalar(200), gColors, NULL, 5,\n SkShader::kClamp_TileMode, NULL);\n paint.setShader(shader);\n canvas->drawRect(r, paint);\n shader->unref();\n }\n\nprivate:\n typedef GM INHERITED;\n};\n\n\/\/\/ Checks quality of large radial gradients, which may display\n\/\/\/ some banding.\n\nclass RadialGradientGM : public GM {\npublic:\n RadialGradientGM() {}\n\nprotected:\n SkString onShortName() { return SkString(\"radial_gradient\"); }\n virtual SkISize onISize() { return make_isize(1280, 1024); }\n void drawBG(SkCanvas* canvas) {\n canvas->drawColor(0xFF000000);\n }\n virtual void onDraw(SkCanvas* canvas) {\n this->drawBG(canvas);\n \n SkPaint paint;\n paint.setDither(true);\n SkPoint center;\n center.set(SkIntToScalar(640), SkIntToScalar(512));\n SkScalar radius = SkIntToScalar(640);\n SkColor colors [3] = { 0x7f7f7f7f, 0x7f7f7f7f, 0xb2000000 };\n SkScalar pos [3] = { SkFloatToScalar(0.0),\n SkFloatToScalar(0.35),\n SkFloatToScalar(1.0) };\n SkShader* shader =\n SkGradientShader::CreateRadial(center, radius, colors,\n pos, 3, SkShader::kClamp_TileMode);\n paint.setShader(shader)->unref();\n SkRect r = { 0, 0, SkIntToScalar(1280), SkIntToScalar(1024) };\n canvas->drawRect(r, paint);\n }\nprivate:\n typedef GM INHERITED;\n};\n\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstatic GM* MyFactory(void*) { return new GradientsGM; }\nstatic GMRegistry reg(MyFactory);\n\nstatic GM* MyFactory2(void*) { return new GradientsDegenrate2PointGM; }\nstatic GMRegistry reg2(MyFactory2);\n\nstatic GM* MyFactory3(void*) { return new ClampedGradientsGM; }\nstatic GMRegistry reg3(MyFactory3);\n\nstatic GM* MyFactory4(void*) { return new RadialGradientGM; }\nstatic GMRegistry reg4(MyFactory4);\n}\n\n<commit_msg>increase height to include entire circle for large radial<commit_after>\n\/*\n * Copyright 2011 Google Inc.\n *\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n *\/\n#include \"gm.h\"\n#include \"SkGradientShader.h\"\n\nnamespace skiagm {\n\nstruct GradData {\n int fCount;\n const SkColor* fColors;\n const SkScalar* fPos;\n};\n\nstatic const SkColor gColors[] = {\n SK_ColorRED, SK_ColorGREEN, SK_ColorBLUE, SK_ColorWHITE, SK_ColorBLACK\n};\nstatic const SkScalar gPos0[] = { 0, SK_Scalar1 };\nstatic const SkScalar gPos1[] = { SK_Scalar1\/4, SK_Scalar1*3\/4 };\nstatic const SkScalar gPos2[] = {\n 0, SK_Scalar1\/8, SK_Scalar1\/2, SK_Scalar1*7\/8, SK_Scalar1\n};\n\nstatic const GradData gGradData[] = {\n { 2, gColors, NULL },\n { 2, gColors, gPos0 },\n { 2, gColors, gPos1 },\n { 5, gColors, NULL },\n { 5, gColors, gPos2 }\n};\n\nstatic SkShader* MakeLinear(const SkPoint pts[2], const GradData& data,\n SkShader::TileMode tm, SkUnitMapper* mapper) {\n return SkGradientShader::CreateLinear(pts, data.fColors, data.fPos,\n data.fCount, tm, mapper);\n}\n\nstatic SkShader* MakeRadial(const SkPoint pts[2], const GradData& data,\n SkShader::TileMode tm, SkUnitMapper* mapper) {\n SkPoint center;\n center.set(SkScalarAve(pts[0].fX, pts[1].fX),\n SkScalarAve(pts[0].fY, pts[1].fY));\n return SkGradientShader::CreateRadial(center, center.fX, data.fColors,\n data.fPos, data.fCount, tm, mapper);\n}\n\nstatic SkShader* MakeSweep(const SkPoint pts[2], const GradData& data,\n SkShader::TileMode tm, SkUnitMapper* mapper) {\n SkPoint center;\n center.set(SkScalarAve(pts[0].fX, pts[1].fX),\n SkScalarAve(pts[0].fY, pts[1].fY));\n return SkGradientShader::CreateSweep(center.fX, center.fY, data.fColors,\n data.fPos, data.fCount, mapper);\n}\n\nstatic SkShader* Make2Radial(const SkPoint pts[2], const GradData& data,\n SkShader::TileMode tm, SkUnitMapper* mapper) {\n SkPoint center0, center1;\n center0.set(SkScalarAve(pts[0].fX, pts[1].fX),\n SkScalarAve(pts[0].fY, pts[1].fY));\n center1.set(SkScalarInterp(pts[0].fX, pts[1].fX, SkIntToScalar(3)\/5),\n SkScalarInterp(pts[0].fY, pts[1].fY, SkIntToScalar(1)\/4));\n return SkGradientShader::CreateTwoPointRadial(\n center1, (pts[1].fX - pts[0].fX) \/ 7,\n center0, (pts[1].fX - pts[0].fX) \/ 2,\n data.fColors, data.fPos, data.fCount, tm, mapper);\n}\n\ntypedef SkShader* (*GradMaker)(const SkPoint pts[2], const GradData& data,\n SkShader::TileMode tm, SkUnitMapper* mapper);\nstatic const GradMaker gGradMakers[] = {\n MakeLinear, MakeRadial, MakeSweep, Make2Radial\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nclass GradientsGM : public GM {\npublic:\n\tGradientsGM() {\n this->setBGColor(0xFFDDDDDD);\n }\n \nprotected:\n SkString onShortName() {\n return SkString(\"gradients\");\n }\n \n virtual SkISize onISize() { return make_isize(640, 510); }\n \n virtual void onDraw(SkCanvas* canvas) {\n \n SkPoint pts[2] = {\n { 0, 0 },\n { SkIntToScalar(100), SkIntToScalar(100) }\n };\n SkShader::TileMode tm = SkShader::kClamp_TileMode;\n SkRect r = { 0, 0, SkIntToScalar(100), SkIntToScalar(100) };\n SkPaint paint;\n paint.setAntiAlias(true);\n \n canvas->translate(SkIntToScalar(20), SkIntToScalar(20));\n for (size_t i = 0; i < SK_ARRAY_COUNT(gGradData); i++) {\n canvas->save();\n for (size_t j = 0; j < SK_ARRAY_COUNT(gGradMakers); j++) {\n SkShader* shader = gGradMakers[j](pts, gGradData[i], tm, NULL);\n paint.setShader(shader);\n canvas->drawRect(r, paint);\n shader->unref();\n canvas->translate(0, SkIntToScalar(120));\n }\n canvas->restore();\n canvas->translate(SkIntToScalar(120), 0);\n }\n }\n \nprivate:\n typedef GM INHERITED;\n};\n\n\/*\n Inspired by this <canvas> javascript, where we need to detect that we are not\n solving a quadratic equation, but must instead solve a linear (since our X^2\n coefficient is 0)\n\n ctx.fillStyle = '#f00';\n ctx.fillRect(0, 0, 100, 50);\n \n var g = ctx.createRadialGradient(-80, 25, 70, 0, 25, 150);\n g.addColorStop(0, '#f00');\n g.addColorStop(0.01, '#0f0');\n g.addColorStop(0.99, '#0f0');\n g.addColorStop(1, '#f00');\n ctx.fillStyle = g;\n ctx.fillRect(0, 0, 100, 50);\n *\/\nclass GradientsDegenrate2PointGM : public GM {\npublic:\n GradientsDegenrate2PointGM() {}\n \nprotected:\n SkString onShortName() {\n return SkString(\"gradients_degenerate_2pt\");\n }\n \n\tvirtual SkISize onISize() { return make_isize(320, 320); }\n \n void drawBG(SkCanvas* canvas) {\n canvas->drawColor(SK_ColorBLUE);\n }\n \n virtual void onDraw(SkCanvas* canvas) {\n this->drawBG(canvas);\n \n SkColor colors[] = { SK_ColorRED, SK_ColorGREEN, SK_ColorGREEN, SK_ColorRED };\n SkScalar pos[] = { 0, SkFloatToScalar(0.01f), SkFloatToScalar(0.99f), SK_Scalar1 };\n SkPoint c0;\n c0.iset(-80, 25);\n SkScalar r0 = SkIntToScalar(70);\n SkPoint c1;\n c1.iset(0, 25);\n SkScalar r1 = SkIntToScalar(150);\n SkShader* s = SkGradientShader::CreateTwoPointRadial(c0, r0, c1, r1, colors,\n pos, SK_ARRAY_COUNT(pos),\n SkShader::kClamp_TileMode);\n SkPaint paint;\n paint.setShader(s)->unref();\n canvas->drawPaint(paint);\n }\n \nprivate:\n typedef GM INHERITED;\n};\n\n\/\/\/ Tests correctness of *optimized* codepaths in gradients.\n\nclass ClampedGradientsGM : public GM {\npublic:\n ClampedGradientsGM() {}\n\nprotected:\n SkString onShortName() { return SkString(\"clamped_gradients\"); }\n\n virtual SkISize onISize() { return make_isize(640, 510); }\n\n void drawBG(SkCanvas* canvas) {\n canvas->drawColor(0xFFDDDDDD);\n }\n\n virtual void onDraw(SkCanvas* canvas) {\n this->drawBG(canvas);\n\n SkRect r = { 0, 0, SkIntToScalar(100), SkIntToScalar(300) };\n SkPaint paint;\n paint.setAntiAlias(true);\n\n SkPoint center;\n center.iset(0, 300);\n canvas->translate(SkIntToScalar(20), SkIntToScalar(20));\n SkShader* shader = SkGradientShader::CreateRadial(\n SkPoint(center),\n SkIntToScalar(200), gColors, NULL, 5,\n SkShader::kClamp_TileMode, NULL);\n paint.setShader(shader);\n canvas->drawRect(r, paint);\n shader->unref();\n }\n\nprivate:\n typedef GM INHERITED;\n};\n\n\/\/\/ Checks quality of large radial gradients, which may display\n\/\/\/ some banding.\n\nclass RadialGradientGM : public GM {\npublic:\n RadialGradientGM() {}\n\nprotected:\n SkString onShortName() { return SkString(\"radial_gradient\"); }\n virtual SkISize onISize() { return make_isize(1280, 1280); }\n void drawBG(SkCanvas* canvas) {\n canvas->drawColor(0xFF000000);\n }\n virtual void onDraw(SkCanvas* canvas) {\n const SkISize dim = this->getISize();\n\n this->drawBG(canvas);\n \n SkPaint paint;\n paint.setDither(true);\n SkPoint center;\n center.set(SkIntToScalar(dim.width())\/2, SkIntToScalar(dim.height())\/2);\n SkScalar radius = SkIntToScalar(dim.width())\/2;\n const SkColor colors[] = { 0x7f7f7f7f, 0x7f7f7f7f, 0xb2000000 };\n const SkScalar pos[] = { SkFloatToScalar(0.0),\n SkFloatToScalar(0.35),\n SkFloatToScalar(1.0) };\n SkShader* shader =\n SkGradientShader::CreateRadial(center, radius, colors,\n pos, SK_ARRAY_COUNT(pos),\n SkShader::kClamp_TileMode);\n paint.setShader(shader)->unref();\n SkRect r = {\n 0, 0, SkIntToScalar(dim.width()), SkIntToScalar(dim.height())\n };\n canvas->drawRect(r, paint);\n }\nprivate:\n typedef GM INHERITED;\n};\n\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstatic GM* MyFactory(void*) { return new GradientsGM; }\nstatic GMRegistry reg(MyFactory);\n\nstatic GM* MyFactory2(void*) { return new GradientsDegenrate2PointGM; }\nstatic GMRegistry reg2(MyFactory2);\n\nstatic GM* MyFactory3(void*) { return new ClampedGradientsGM; }\nstatic GMRegistry reg3(MyFactory3);\n\nstatic GM* MyFactory4(void*) { return new RadialGradientGM; }\nstatic GMRegistry reg4(MyFactory4);\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Copyright (c) 2005, Industrial Light & Magic, a division of Lucas\n\/\/ Digital Ltd. LLC\n\/\/ \n\/\/ All rights reserved.\n\/\/ \n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are\n\/\/ met:\n\/\/ * Redistributions of source code must retain the above copyright\n\/\/ notice, this list of conditions and the following disclaimer.\n\/\/ * Redistributions in binary form must reproduce the above\n\/\/ copyright notice, this list of conditions and the following disclaimer\n\/\/ in the documentation and\/or other materials provided with the\n\/\/ distribution.\n\/\/ * Neither the name of Industrial Light & Magic nor the names of\n\/\/ its contributors may be used to endorse or promote products derived\n\/\/ from this software without specific prior written permission. \n\/\/ \n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\/\/ \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n\/\/ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n\/\/ A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n\/\/ OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n\/\/ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n\/\/ LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n\/\/ DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n\/\/ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n\/\/ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n\/\/ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/-----------------------------------------------------------------------------\n\/\/\n\/\/\tclass Semaphore -- implementation for Windows\n\/\/\n\/\/-----------------------------------------------------------------------------\n\n#include \"IlmThreadSemaphore.h\"\n#include \"Iex.h\"\n#include <string>\n#include <assert.h>\n#include <iostream>\n\nnamespace IlmThread {\n\nusing namespace Iex;\n\nnamespace {\n\nstd::string\nerrorString ()\n{\n LPSTR messageBuffer;\n DWORD bufferLength;\n std::string message;\n\n \/\/\n \/\/ Call FormatMessage() to allow for message \n \/\/ text to be acquired from the system.\n \/\/\n\n if (bufferLength = FormatMessageA (FORMAT_MESSAGE_ALLOCATE_BUFFER |\n\t\t\t\t FORMAT_MESSAGE_IGNORE_INSERTS |\n\t\t\t\t FORMAT_MESSAGE_FROM_SYSTEM,\n\t\t\t\t 0,\n\t\t\t\t GetLastError (),\n\t\t\t\t MAKELANGID (LANG_NEUTRAL,\n\t\t\t\t\t\t SUBLANG_DEFAULT),\n\t\t\t\t (LPSTR) &messageBuffer,\n\t\t\t\t 0,\n\t\t\t\t NULL))\n {\n\tmessage = messageBuffer;\n LocalFree (messageBuffer);\n }\n\n return message;\n}\n\n} \/\/ namespace\n\n\nSemaphore::Semaphore (unsigned int value)\n{\n if ((_semaphore = ::CreateSemaphore (0, value, 0x7fffffff, 0)) == 0)\n {\n\tTHROW (LogicExc, \"Could not create semaphore \"\n\t\t\t \"(\" << errorString() << \").\");\n }\n}\n\n\nSemaphore::~Semaphore()\n{\n bool ok = ::CloseHandle (_semaphore);\n assert (ok);\n}\n\n\nvoid\nSemaphore::wait()\n{\n if (::WaitForSingleObject (_semaphore, INFINITE) != WAIT_OBJECT_0)\n {\n\tTHROW (LogicExc, \"Could not wait on semaphore \"\n\t\t\t \"(\" << errorString() << \").\");\n }\n}\n\n\nvoid\nSemaphore::tryWait()\n{\n return ::WaitForSingleObject (_semaphore, 0) == WAIT_OBJECT_0;\n}\n\n\nvoid\nSemaphore::post()\n{\n if (!::ReleaseSemaphore (_semaphore, 1, 0))\n {\n\tTHROW (LogicExc, \"Could not post on semaphore \"\n\t\t\t \"(\" << errorString() << \").\");\n }\n}\n\n\nint\nSemaphore::value() const\n{\n LONG v = -1;\n\n if (!::ReleaseSemaphore (_semaphore, 0, &v) || v < 0)\n {\n\tTHROW (LogicExc, \"Could not get value of semaphore \"\n\t\t\t \"(\" << errorString () << \").\");\n }\n\n return v;\n}\n\n} \/\/ namespace IlmThread\n<commit_msg>Wrong return type for method tryWait().<commit_after>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Copyright (c) 2005, Industrial Light & Magic, a division of Lucas\n\/\/ Digital Ltd. LLC\n\/\/ \n\/\/ All rights reserved.\n\/\/ \n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are\n\/\/ met:\n\/\/ * Redistributions of source code must retain the above copyright\n\/\/ notice, this list of conditions and the following disclaimer.\n\/\/ * Redistributions in binary form must reproduce the above\n\/\/ copyright notice, this list of conditions and the following disclaimer\n\/\/ in the documentation and\/or other materials provided with the\n\/\/ distribution.\n\/\/ * Neither the name of Industrial Light & Magic nor the names of\n\/\/ its contributors may be used to endorse or promote products derived\n\/\/ from this software without specific prior written permission. \n\/\/ \n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\/\/ \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n\/\/ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n\/\/ A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n\/\/ OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n\/\/ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n\/\/ LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n\/\/ DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n\/\/ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n\/\/ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n\/\/ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/-----------------------------------------------------------------------------\n\/\/\n\/\/\tclass Semaphore -- implementation for Windows\n\/\/\n\/\/-----------------------------------------------------------------------------\n\n#include \"IlmThreadSemaphore.h\"\n#include \"Iex.h\"\n#include <string>\n#include <assert.h>\n#include <iostream>\n\nnamespace IlmThread {\n\nusing namespace Iex;\n\nnamespace {\n\nstd::string\nerrorString ()\n{\n LPSTR messageBuffer;\n DWORD bufferLength;\n std::string message;\n\n \/\/\n \/\/ Call FormatMessage() to allow for message \n \/\/ text to be acquired from the system.\n \/\/\n\n if (bufferLength = FormatMessageA (FORMAT_MESSAGE_ALLOCATE_BUFFER |\n\t\t\t\t FORMAT_MESSAGE_IGNORE_INSERTS |\n\t\t\t\t FORMAT_MESSAGE_FROM_SYSTEM,\n\t\t\t\t 0,\n\t\t\t\t GetLastError (),\n\t\t\t\t MAKELANGID (LANG_NEUTRAL,\n\t\t\t\t\t\t SUBLANG_DEFAULT),\n\t\t\t\t (LPSTR) &messageBuffer,\n\t\t\t\t 0,\n\t\t\t\t NULL))\n {\n\tmessage = messageBuffer;\n LocalFree (messageBuffer);\n }\n\n return message;\n}\n\n} \/\/ namespace\n\n\nSemaphore::Semaphore (unsigned int value)\n{\n if ((_semaphore = ::CreateSemaphore (0, value, 0x7fffffff, 0)) == 0)\n {\n\tTHROW (LogicExc, \"Could not create semaphore \"\n\t\t\t \"(\" << errorString() << \").\");\n }\n}\n\n\nSemaphore::~Semaphore()\n{\n bool ok = ::CloseHandle (_semaphore);\n assert (ok);\n}\n\n\nvoid\nSemaphore::wait()\n{\n if (::WaitForSingleObject (_semaphore, INFINITE) != WAIT_OBJECT_0)\n {\n\tTHROW (LogicExc, \"Could not wait on semaphore \"\n\t\t\t \"(\" << errorString() << \").\");\n }\n}\n\n\nbool\nSemaphore::tryWait()\n{\n return ::WaitForSingleObject (_semaphore, 0) == WAIT_OBJECT_0;\n}\n\n\nvoid\nSemaphore::post()\n{\n if (!::ReleaseSemaphore (_semaphore, 1, 0))\n {\n\tTHROW (LogicExc, \"Could not post on semaphore \"\n\t\t\t \"(\" << errorString() << \").\");\n }\n}\n\n\nint\nSemaphore::value() const\n{\n LONG v = -1;\n\n if (!::ReleaseSemaphore (_semaphore, 0, &v) || v < 0)\n {\n\tTHROW (LogicExc, \"Could not get value of semaphore \"\n\t\t\t \"(\" << errorString () << \").\");\n }\n\n return v;\n}\n\n} \/\/ namespace IlmThread\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.\n *\n * Use of this source code is governed by a BSD-style license\n * that can be found in the LICENSE file in the root of the source\n * tree. An additional intellectual property rights grant can be found\n * in the file PATENTS. All contributing project authors may\n * be found in the AUTHORS file in the root of the source tree.\n *\/\n\n#include \"webrtc\/modules\/audio_processing\/high_pass_filter_impl.h\"\n\n#include <assert.h>\n\n#include \"webrtc\/common_audio\/signal_processing\/include\/signal_processing_library.h\"\n#include \"webrtc\/modules\/audio_processing\/audio_buffer.h\"\n#include \"webrtc\/system_wrappers\/interface\/critical_section_wrapper.h\"\n#include \"webrtc\/typedefs.h\"\n\n\nnamespace webrtc {\nnamespace {\nconst int16_t kFilterCoefficients8kHz[5] =\n {3798, -7596, 3798, 7807, -3733};\n\nconst int16_t kFilterCoefficients[5] =\n {4012, -8024, 4012, 8002, -3913};\n\nstruct FilterState {\n int16_t y[4];\n int16_t x[2];\n const int16_t* ba;\n};\n\nint InitializeFilter(FilterState* hpf, int sample_rate_hz) {\n assert(hpf != NULL);\n\n if (sample_rate_hz == AudioProcessing::kSampleRate8kHz) {\n hpf->ba = kFilterCoefficients8kHz;\n } else {\n hpf->ba = kFilterCoefficients;\n }\n\n WebRtcSpl_MemSetW16(hpf->x, 0, 2);\n WebRtcSpl_MemSetW16(hpf->y, 0, 4);\n\n return AudioProcessing::kNoError;\n}\n\nint Filter(FilterState* hpf, int16_t* data, int length) {\n assert(hpf != NULL);\n\n int32_t tmp_int32 = 0;\n int16_t* y = hpf->y;\n int16_t* x = hpf->x;\n const int16_t* ba = hpf->ba;\n\n for (int i = 0; i < length; i++) {\n \/\/ y[i] = b[0] * x[i] + b[1] * x[i-1] + b[2] * x[i-2]\n \/\/ + -a[1] * y[i-1] + -a[2] * y[i-2];\n\n tmp_int32 =\n WEBRTC_SPL_MUL_16_16(y[1], ba[3]); \/\/ -a[1] * y[i-1] (low part)\n tmp_int32 +=\n WEBRTC_SPL_MUL_16_16(y[3], ba[4]); \/\/ -a[2] * y[i-2] (low part)\n tmp_int32 = (tmp_int32 >> 15);\n tmp_int32 +=\n WEBRTC_SPL_MUL_16_16(y[0], ba[3]); \/\/ -a[1] * y[i-1] (high part)\n tmp_int32 +=\n WEBRTC_SPL_MUL_16_16(y[2], ba[4]); \/\/ -a[2] * y[i-2] (high part)\n tmp_int32 = (tmp_int32 << 1);\n\n tmp_int32 += WEBRTC_SPL_MUL_16_16(data[i], ba[0]); \/\/ b[0]*x[0]\n tmp_int32 += WEBRTC_SPL_MUL_16_16(x[0], ba[1]); \/\/ b[1]*x[i-1]\n tmp_int32 += WEBRTC_SPL_MUL_16_16(x[1], ba[2]); \/\/ b[2]*x[i-2]\n\n \/\/ Update state (input part)\n x[1] = x[0];\n x[0] = data[i];\n\n \/\/ Update state (filtered part)\n y[2] = y[0];\n y[3] = y[1];\n y[0] = static_cast<int16_t>(tmp_int32 >> 13);\n y[1] = static_cast<int16_t>(\n (tmp_int32 - (static_cast<int32_t>(y[0]) << 13)) << 2);\n\n \/\/ Rounding in Q12, i.e. add 2^11\n tmp_int32 += 2048;\n\n \/\/ Saturate (to 2^27) so that the HP filtered signal does not overflow\n tmp_int32 = WEBRTC_SPL_SAT(static_cast<int32_t>(134217727),\n tmp_int32,\n static_cast<int32_t>(-134217728));\n\n \/\/ Convert back to Q0 and use rounding.\n data[i] = (int16_t)(tmp_int32 >> 12);\n }\n\n return AudioProcessing::kNoError;\n}\n} \/\/ namespace\n\ntypedef FilterState Handle;\n\nHighPassFilterImpl::HighPassFilterImpl(const AudioProcessing* apm,\n CriticalSectionWrapper* crit)\n : ProcessingComponent(),\n apm_(apm),\n crit_(crit) {}\n\nHighPassFilterImpl::~HighPassFilterImpl() {}\n\nint HighPassFilterImpl::ProcessCaptureAudio(AudioBuffer* audio) {\n int err = apm_->kNoError;\n\n if (!is_component_enabled()) {\n return apm_->kNoError;\n }\n\n assert(audio->samples_per_split_channel() <= 160);\n\n for (int i = 0; i < num_handles(); i++) {\n Handle* my_handle = static_cast<Handle*>(handle(i));\n err = Filter(my_handle,\n audio->split_bands(i)[kBand0To8kHz],\n audio->samples_per_split_channel());\n\n if (err != apm_->kNoError) {\n return GetHandleError(my_handle);\n }\n }\n\n return apm_->kNoError;\n}\n\nint HighPassFilterImpl::Enable(bool enable) {\n CriticalSectionScoped crit_scoped(crit_);\n return EnableComponent(enable);\n}\n\nbool HighPassFilterImpl::is_enabled() const {\n return is_component_enabled();\n}\n\nvoid* HighPassFilterImpl::CreateHandle() const {\n return new FilterState;\n}\n\nvoid HighPassFilterImpl::DestroyHandle(void* handle) const {\n delete static_cast<Handle*>(handle);\n}\n\nint HighPassFilterImpl::InitializeHandle(void* handle) const {\n return InitializeFilter(static_cast<Handle*>(handle),\n apm_->proc_sample_rate_hz());\n}\n\nint HighPassFilterImpl::ConfigureHandle(void* \/*handle*\/) const {\n return apm_->kNoError; \/\/ Not configurable.\n}\n\nint HighPassFilterImpl::num_handles_required() const {\n return apm_->num_output_channels();\n}\n\nint HighPassFilterImpl::GetHandleError(void* handle) const {\n \/\/ The component has no detailed errors.\n assert(handle != NULL);\n return apm_->kUnspecifiedError;\n}\n} \/\/ namespace webrtc\n<commit_msg>audio_processing: Replaced macro WEBRTC_SPL_MUL_16_16 with * in high_pass_filter<commit_after>\/*\n * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.\n *\n * Use of this source code is governed by a BSD-style license\n * that can be found in the LICENSE file in the root of the source\n * tree. An additional intellectual property rights grant can be found\n * in the file PATENTS. All contributing project authors may\n * be found in the AUTHORS file in the root of the source tree.\n *\/\n\n#include \"webrtc\/modules\/audio_processing\/high_pass_filter_impl.h\"\n\n#include <assert.h>\n\n#include \"webrtc\/common_audio\/signal_processing\/include\/signal_processing_library.h\"\n#include \"webrtc\/modules\/audio_processing\/audio_buffer.h\"\n#include \"webrtc\/system_wrappers\/interface\/critical_section_wrapper.h\"\n#include \"webrtc\/typedefs.h\"\n\n\nnamespace webrtc {\nnamespace {\nconst int16_t kFilterCoefficients8kHz[5] =\n {3798, -7596, 3798, 7807, -3733};\n\nconst int16_t kFilterCoefficients[5] =\n {4012, -8024, 4012, 8002, -3913};\n\nstruct FilterState {\n int16_t y[4];\n int16_t x[2];\n const int16_t* ba;\n};\n\nint InitializeFilter(FilterState* hpf, int sample_rate_hz) {\n assert(hpf != NULL);\n\n if (sample_rate_hz == AudioProcessing::kSampleRate8kHz) {\n hpf->ba = kFilterCoefficients8kHz;\n } else {\n hpf->ba = kFilterCoefficients;\n }\n\n WebRtcSpl_MemSetW16(hpf->x, 0, 2);\n WebRtcSpl_MemSetW16(hpf->y, 0, 4);\n\n return AudioProcessing::kNoError;\n}\n\nint Filter(FilterState* hpf, int16_t* data, int length) {\n assert(hpf != NULL);\n\n int32_t tmp_int32 = 0;\n int16_t* y = hpf->y;\n int16_t* x = hpf->x;\n const int16_t* ba = hpf->ba;\n\n for (int i = 0; i < length; i++) {\n \/\/ y[i] = b[0] * x[i] + b[1] * x[i-1] + b[2] * x[i-2]\n \/\/ + -a[1] * y[i-1] + -a[2] * y[i-2];\n\n tmp_int32 = y[1] * ba[3]; \/\/ -a[1] * y[i-1] (low part)\n tmp_int32 += y[3] * ba[4]; \/\/ -a[2] * y[i-2] (low part)\n tmp_int32 = (tmp_int32 >> 15);\n tmp_int32 += y[0] * ba[3]; \/\/ -a[1] * y[i-1] (high part)\n tmp_int32 += y[2] * ba[4]; \/\/ -a[2] * y[i-2] (high part)\n tmp_int32 = (tmp_int32 << 1);\n\n tmp_int32 += data[i] * ba[0]; \/\/ b[0]*x[0]\n tmp_int32 += x[0] * ba[1]; \/\/ b[1]*x[i-1]\n tmp_int32 += x[1] * ba[2]; \/\/ b[2]*x[i-2]\n\n \/\/ Update state (input part)\n x[1] = x[0];\n x[0] = data[i];\n\n \/\/ Update state (filtered part)\n y[2] = y[0];\n y[3] = y[1];\n y[0] = static_cast<int16_t>(tmp_int32 >> 13);\n y[1] = static_cast<int16_t>(\n (tmp_int32 - (static_cast<int32_t>(y[0]) << 13)) << 2);\n\n \/\/ Rounding in Q12, i.e. add 2^11\n tmp_int32 += 2048;\n\n \/\/ Saturate (to 2^27) so that the HP filtered signal does not overflow\n tmp_int32 = WEBRTC_SPL_SAT(static_cast<int32_t>(134217727),\n tmp_int32,\n static_cast<int32_t>(-134217728));\n\n \/\/ Convert back to Q0 and use rounding.\n data[i] = (int16_t)(tmp_int32 >> 12);\n }\n\n return AudioProcessing::kNoError;\n}\n} \/\/ namespace\n\ntypedef FilterState Handle;\n\nHighPassFilterImpl::HighPassFilterImpl(const AudioProcessing* apm,\n CriticalSectionWrapper* crit)\n : ProcessingComponent(),\n apm_(apm),\n crit_(crit) {}\n\nHighPassFilterImpl::~HighPassFilterImpl() {}\n\nint HighPassFilterImpl::ProcessCaptureAudio(AudioBuffer* audio) {\n int err = apm_->kNoError;\n\n if (!is_component_enabled()) {\n return apm_->kNoError;\n }\n\n assert(audio->samples_per_split_channel() <= 160);\n\n for (int i = 0; i < num_handles(); i++) {\n Handle* my_handle = static_cast<Handle*>(handle(i));\n err = Filter(my_handle,\n audio->split_bands(i)[kBand0To8kHz],\n audio->samples_per_split_channel());\n\n if (err != apm_->kNoError) {\n return GetHandleError(my_handle);\n }\n }\n\n return apm_->kNoError;\n}\n\nint HighPassFilterImpl::Enable(bool enable) {\n CriticalSectionScoped crit_scoped(crit_);\n return EnableComponent(enable);\n}\n\nbool HighPassFilterImpl::is_enabled() const {\n return is_component_enabled();\n}\n\nvoid* HighPassFilterImpl::CreateHandle() const {\n return new FilterState;\n}\n\nvoid HighPassFilterImpl::DestroyHandle(void* handle) const {\n delete static_cast<Handle*>(handle);\n}\n\nint HighPassFilterImpl::InitializeHandle(void* handle) const {\n return InitializeFilter(static_cast<Handle*>(handle),\n apm_->proc_sample_rate_hz());\n}\n\nint HighPassFilterImpl::ConfigureHandle(void* \/*handle*\/) const {\n return apm_->kNoError; \/\/ Not configurable.\n}\n\nint HighPassFilterImpl::num_handles_required() const {\n return apm_->num_output_channels();\n}\n\nint HighPassFilterImpl::GetHandleError(void* handle) const {\n \/\/ The component has no detailed errors.\n assert(handle != NULL);\n return apm_->kUnspecifiedError;\n}\n} \/\/ namespace webrtc\n<|endoftext|>"} {"text":"<commit_before>\/* -------------------------------------------------------------------------- *\n * OpenSim: testIterators.cpp *\n * -------------------------------------------------------------------------- *\n * The OpenSim API is a toolkit for musculoskeletal modeling and simulation. *\n * See http:\/\/opensim.stanford.edu and the NOTICE file for more information. *\n * OpenSim is developed at Stanford University and supported by the US *\n * National Institutes of Health (U54 GM072970, R24 HD065690) and by DARPA *\n * through the Warrior Web program. *\n * *\n * Copyright (c) 2014-2014 Stanford University and the Authors *\n * Author(s): Ayman Habib *\n * Contributer(s) : *\n * *\n * Licensed under the Apache License, Version 2.0 (the \"License\"); you may *\n * not use this file except in compliance with the License. You may obtain a *\n * copy of the License at http:\/\/www.apache.org\/licenses\/LICENSE-2.0. *\n * *\n * Unless required by applicable law or agreed to in writing, software *\n * distributed under the License is distributed on an \"AS IS\" BASIS, *\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. *\n * See the License for the specific language governing permissions and *\n * limitations under the License. *\n * -------------------------------------------------------------------------- *\/\n#include <iostream>\n#include <OpenSim\/Simulation\/Model\/Model.h>\n#include <OpenSim\/Common\/LoadOpenSimLibrary.h>\n#include <OpenSim\/Auxiliary\/auxiliaryTestFunctions.h>\n\nusing namespace OpenSim;\nusing namespace std;\n\n\/\/ Example filter that allows for iterating only through Components that have\n\/\/ state variables, used for demonstration purposes.\nclass ComponentWithStateVariables : public ComponentFilter {\npublic:\n ComponentWithStateVariables() {\n \/\/std::cout << \"ComponentWithStateVariables constructed\" << std::endl;\n };\n bool isMatch(const Component& comp) const override {\n return (comp.getNumStateVariables()>0);\n };\n ~ComponentWithStateVariables() {\n \/\/std::cout << \"ComponentWithStateVariables destructed\" << std::endl;\n }\n ComponentWithStateVariables* clone() const {\n return new ComponentWithStateVariables(*this);\n }\n};\nint main()\n{\n try {\n LoadOpenSimLibrary(\"osimActuators\");\n\n std::string filename = \"arm26.osim\";\n\n Model model(filename);\n model.initSystem();\n ComponentList<Component> componentsList = model.getComponentList();\n std::cout << \"list begin: \" << componentsList.begin()->getName() << std::endl;\n int numComponents = 0;\n for (ComponentList<Component>::const_iterator it = componentsList.begin();\n it != componentsList.end();\n ++it) {\n std::cout << \"Iterator is at: \" << it->getConcreteClassName() << \" \" << it->getName() << std::endl;\n numComponents++;\n }\n \n ComponentList<OpenSim::Body> bodiesList = model.getComponentList<OpenSim::Body>();\n int numBodies = 0;\n std::cout << \"Bodies list begin: \" << bodiesList.begin()->getName() << std::endl;\n for (ComponentList<OpenSim::Body>::const_iterator it = bodiesList.begin();\n it != bodiesList.end();\n ++it) {\n std::cout << \"Iterator is at Body: \" << it->getName() << std::endl;\n numBodies++;\n }\n\n std::cout << \"Bodies list begin: \" << bodiesList.begin()->getName() << std::endl;\n int numBodiesPost = 0;\n for (ComponentList<OpenSim::Body>::const_iterator itPost = bodiesList.begin();\n itPost != bodiesList.end();\n itPost++) {\n std::cout << \"Iterator is at Body: \" << itPost->getName() << std::endl;\n numBodiesPost++;\n }\n\n int numMuscles = 0;\n std::cout << \"Using range-for loop over Muscles: \" << std::endl;\n ComponentList<Muscle> musclesList = model.getComponentList<Muscle>();\n for (const Muscle& muscle : musclesList) {\n std::cout << \"Iterator is at muscle: \" << muscle.getName() << std::endl;\n numMuscles++;\n }\n \n int numGeomPaths = 0;\n ComponentList<GeometryPath> geomPathList = model.getComponentList<GeometryPath>();\n for (const GeometryPath& gpath : geomPathList) {\n numGeomPaths++;\n }\n const OpenSim::Joint& shoulderJnt = model.getJointSet().get(0);\n \/\/ cycle thru components under shoulderJnt should return the Joint itself and the Coordinate\n int numJntComponents = 0;\n ComponentList<Component> jComponentsList = shoulderJnt.getComponentList();\n std::cout << \"Components\/subComponents under Shoulder Joint:\" << std::endl;\n for (ComponentList<Component>::const_iterator it = jComponentsList.begin();\n it != jComponentsList.end();\n ++it) {\n std::cout << \"Iterator is at: \" << it->getConcreteClassName() << \" \" << it->getName() << std::endl;\n numJntComponents++;\n }\n cout << \"Num all components = \" << numComponents << std::endl;\n cout << \"Num bodies = \" << numBodies << std::endl;\n cout << \"Num Muscles = \" << numMuscles << std::endl;\n cout << \"Num GeometryPath components = \" << numGeomPaths << std::endl;\n \/\/ Components = Model+3Body+3Marker+2(Joint+Coordinate)+6(Muscle+GeometryPath)\n \/\/ Should test against 1+#Bodies+#Markers+#Joints+#Constraints+#Coordinates+#Forces+#ForcesWithPath+..\n \/\/ Would that account for internal (split-bodies etc.?)\n int numComponentsWithStateVariables = 0;\n ComponentList<ModelComponent> compWithStates = model.getComponentList<ModelComponent>();\n ComponentWithStateVariables* myFilter = new ComponentWithStateVariables();\n compWithStates.setFilter(myFilter); \/\/ Filter is cloned and can be deleted safely\n delete myFilter;\n for (const ModelComponent& comp : compWithStates) {\n cout << comp.getConcreteClassName() << \":\" << comp.getName() << endl;\n numComponentsWithStateVariables++;\n }\n \/\/Now test a std::iterator method\n ComponentList<ModelComponent> comps = model.getComponentList<ModelComponent>();\n ComponentList<ModelComponent>::const_iterator skipIter = comps.begin();\n int countSkipComponent = 0;\n while (skipIter != comps.end()){\n cout << skipIter->getConcreteClassName() << \":\" << skipIter->getName() << endl;\n std::advance(skipIter, 2);\n countSkipComponent++;\n }\n\n ASSERT(numComponents == 23); \n ASSERT(numBodies == model.getNumBodies());\n ASSERT(numBodiesPost == numBodies);\n ASSERT(numMuscles == model.getMuscles().getSize());\n ASSERT(numComponentsWithStateVariables == 11);\n ASSERT(numJntComponents == 2);\n ASSERT(countSkipComponent == 12);\n }\n catch (Exception &ex) {\n ex.print(std::cout);\n return 1;\n }\n cout << \"Done\" << endl;\n return 0;\n}\n<commit_msg>Clarifying text in test case.<commit_after>\/* -------------------------------------------------------------------------- *\n * OpenSim: testIterators.cpp *\n * -------------------------------------------------------------------------- *\n * The OpenSim API is a toolkit for musculoskeletal modeling and simulation. *\n * See http:\/\/opensim.stanford.edu and the NOTICE file for more information. *\n * OpenSim is developed at Stanford University and supported by the US *\n * National Institutes of Health (U54 GM072970, R24 HD065690) and by DARPA *\n * through the Warrior Web program. *\n * *\n * Copyright (c) 2014-2014 Stanford University and the Authors *\n * Author(s): Ayman Habib *\n * Contributer(s) : *\n * *\n * Licensed under the Apache License, Version 2.0 (the \"License\"); you may *\n * not use this file except in compliance with the License. You may obtain a *\n * copy of the License at http:\/\/www.apache.org\/licenses\/LICENSE-2.0. *\n * *\n * Unless required by applicable law or agreed to in writing, software *\n * distributed under the License is distributed on an \"AS IS\" BASIS, *\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. *\n * See the License for the specific language governing permissions and *\n * limitations under the License. *\n * -------------------------------------------------------------------------- *\/\n#include <iostream>\n#include <OpenSim\/Simulation\/Model\/Model.h>\n#include <OpenSim\/Common\/LoadOpenSimLibrary.h>\n#include <OpenSim\/Auxiliary\/auxiliaryTestFunctions.h>\n\nusing namespace OpenSim;\nusing namespace std;\n\n\/\/ Example filter that allows for iterating only through Components that have\n\/\/ state variables, used for demonstration purposes.\nclass ComponentWithStateVariables : public ComponentFilter {\npublic:\n ComponentWithStateVariables() {\n \/\/std::cout << \"ComponentWithStateVariables constructed\" << std::endl;\n };\n bool isMatch(const Component& comp) const override {\n return (comp.getNumStateVariables()>0);\n };\n ~ComponentWithStateVariables() {\n \/\/std::cout << \"ComponentWithStateVariables destructed\" << std::endl;\n }\n ComponentWithStateVariables* clone() const {\n return new ComponentWithStateVariables(*this);\n }\n};\nint main()\n{\n try {\n LoadOpenSimLibrary(\"osimActuators\");\n\n std::string filename = \"arm26.osim\";\n\n Model model(filename);\n model.initSystem();\n ComponentList<Component> componentsList = model.getComponentList();\n std::cout << \"list begin: \" << componentsList.begin()->getName() << std::endl;\n int numComponents = 0;\n for (ComponentList<Component>::const_iterator it = componentsList.begin();\n it != componentsList.end();\n ++it) {\n std::cout << \"Iterator is at: \" << it->getConcreteClassName() << \" \" << it->getName() << std::endl;\n numComponents++;\n }\n \n ComponentList<OpenSim::Body> bodiesList = model.getComponentList<OpenSim::Body>();\n int numBodies = 0;\n std::cout << \"Bodies list begin: \" << bodiesList.begin()->getName() << std::endl;\n for (ComponentList<OpenSim::Body>::const_iterator it = bodiesList.begin();\n it != bodiesList.end();\n ++it) {\n std::cout << \"Iterator is at Body: \" << it->getName() << std::endl;\n numBodies++;\n }\n \/\/ Now we try the post increment variant of the iterator\n std::cout << \"Bodies list begin, using post increment: \" << bodiesList.begin()->getName() << std::endl;\n int numBodiesPost = 0;\n for (ComponentList<OpenSim::Body>::const_iterator itPost = bodiesList.begin();\n itPost != bodiesList.end();\n itPost++) {\n std::cout << \"Iterator is at Body: \" << itPost->getName() << std::endl;\n numBodiesPost++;\n }\n\n int numMuscles = 0;\n std::cout << \"Using range-for loop over Muscles: \" << std::endl;\n ComponentList<Muscle> musclesList = model.getComponentList<Muscle>();\n for (const Muscle& muscle : musclesList) {\n std::cout << \"Iterator is at muscle: \" << muscle.getName() << std::endl;\n numMuscles++;\n }\n \n int numGeomPaths = 0;\n ComponentList<GeometryPath> geomPathList = model.getComponentList<GeometryPath>();\n for (const GeometryPath& gpath : geomPathList) {\n numGeomPaths++;\n }\n const OpenSim::Joint& shoulderJnt = model.getJointSet().get(0);\n \/\/ cycle thru components under shoulderJnt should return the Joint itself and the Coordinate\n int numJntComponents = 0;\n ComponentList<Component> jComponentsList = shoulderJnt.getComponentList();\n std::cout << \"Components\/subComponents under Shoulder Joint:\" << std::endl;\n for (ComponentList<Component>::const_iterator it = jComponentsList.begin();\n it != jComponentsList.end();\n ++it) {\n std::cout << \"Iterator is at: \" << it->getConcreteClassName() << \" \" << it->getName() << std::endl;\n numJntComponents++;\n }\n cout << \"Num all components = \" << numComponents << std::endl;\n cout << \"Num bodies = \" << numBodies << std::endl;\n cout << \"Num Muscles = \" << numMuscles << std::endl;\n cout << \"Num GeometryPath components = \" << numGeomPaths << std::endl;\n \/\/ Components = Model+3Body+3Marker+2(Joint+Coordinate)+6(Muscle+GeometryPath)\n \/\/ Should test against 1+#Bodies+#Markers+#Joints+#Constraints+#Coordinates+#Forces+#ForcesWithPath+..\n \/\/ Would that account for internal (split-bodies etc.?)\n int numComponentsWithStateVariables = 0;\n ComponentList<ModelComponent> compWithStates = model.getComponentList<ModelComponent>();\n ComponentWithStateVariables* myFilter = new ComponentWithStateVariables();\n compWithStates.setFilter(myFilter); \/\/ Filter is cloned and can be deleted safely\n delete myFilter;\n for (const ModelComponent& comp : compWithStates) {\n cout << comp.getConcreteClassName() << \":\" << comp.getName() << endl;\n numComponentsWithStateVariables++;\n }\n \/\/Now test a std::iterator method\n ComponentList<ModelComponent> comps = model.getComponentList<ModelComponent>();\n ComponentList<ModelComponent>::const_iterator skipIter = comps.begin();\n int countSkipComponent = 0;\n while (skipIter != comps.end()){\n cout << skipIter->getConcreteClassName() << \":\" << skipIter->getName() << endl;\n std::advance(skipIter, 2);\n countSkipComponent++;\n }\n\n ASSERT(numComponents == 23); \n ASSERT(numBodies == model.getNumBodies());\n ASSERT(numBodiesPost == numBodies);\n ASSERT(numMuscles == model.getMuscles().getSize());\n ASSERT(numComponentsWithStateVariables == 11);\n ASSERT(numJntComponents == 2);\n ASSERT(countSkipComponent == 12);\n }\n catch (Exception &ex) {\n ex.print(std::cout);\n return 1;\n }\n cout << \"Done\" << endl;\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright © 2010 Intel Corporation\n *\n * Permission is hereby granted, free of charge, to any person obtaining a\n * copy of this software and associated documentation files (the \"Software\"),\n * to deal in the Software without restriction, including without limitation\n * the rights to use, copy, modify, merge, publish, distribute, sublicense,\n * and\/or sell copies of the Software, and to permit persons to whom the\n * Software is furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice (including the next\n * paragraph) shall be included in all copies or substantial portions of the\n * Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n * DEALINGS IN THE SOFTWARE.\n *\/\n\n\/**\n * \\file lower_vector.cpp\n * IR lowering pass to remove some types of ir_quadop_vector\n *\n * \\author Ian Romanick <ian.d.romanick@intel.com>\n *\/\n\n#include \"ir.h\"\n#include \"ir_rvalue_visitor.h\"\n\nclass lower_vector_visitor : public ir_rvalue_visitor {\npublic:\n lower_vector_visitor() : progress(false)\n {\n \/* empty *\/\n }\n\n void handle_rvalue(ir_rvalue **rvalue);\n\n \/**\n * Should SWZ-like expressions be lowered?\n *\/\n bool dont_lower_swz;\n\n bool progress;\n};\n\n\/**\n * Determine if an IR expression tree looks like an extended swizzle\n *\n * Extended swizzles consist of access of a single vector source (with possible\n * per component negation) and the constants -1, 0, or 1.\n *\/\nbool\nis_extended_swizzle(ir_expression *ir)\n{\n \/* Track any variables that are accessed by this expression.\n *\/\n ir_variable *var = NULL;\n\n assert(ir->operation == ir_quadop_vector);\n\n for (unsigned i = 0; i < ir->type->vector_elements; i++) {\n ir_rvalue *op = ir->operands[i];\n\n while (op != NULL) {\n\t switch (op->ir_type) {\n\t case ir_type_constant: {\n\t const ir_constant *const c = op->as_constant();\n\n\t if (!c->is_one() && !c->is_zero() && !c->is_negative_one())\n\t return false;\n\n\t op = NULL;\n\t break;\n\t }\n\n\t case ir_type_dereference_variable: {\n\t ir_dereference_variable *const d = (ir_dereference_variable *) op;\n\n\t if ((var != NULL) && (var != d->var))\n\t return false;\n\n\t var = d->var;\n\t op = NULL;\n\t break;\n\t }\n\n\t case ir_type_expression: {\n\t ir_expression *const ex = (ir_expression *) op;\n\n\t if (ex->operation != ir_unop_neg)\n\t return false;\n\n\t op = ex->operands[0];\n\t break;\n\t }\n\n\t case ir_type_swizzle:\n\t op = ((ir_swizzle *) op)->val;\n\t break;\n\n\t default:\n\t return false;\n\t }\n }\n }\n\n return true;\n}\n\nvoid\nlower_vector_visitor::handle_rvalue(ir_rvalue **rvalue)\n{\n if (!*rvalue)\n return;\n\n ir_expression *expr = (*rvalue)->as_expression();\n if ((expr == NULL) || (expr->operation != ir_quadop_vector))\n return;\n\n if (this->dont_lower_swz && is_extended_swizzle(expr))\n return;\n\n \/* FINISHME: Is this the right thing to use for the talloc context?\n *\/\n void *const mem_ctx = expr;\n\n assert(expr->type->vector_elements == expr->get_num_operands());\n\n \/* Generate a temporary with the same type as the ir_quadop_operation.\n *\/\n ir_variable *const temp =\n new(mem_ctx) ir_variable(expr->type, \"vecop_tmp\", ir_var_temporary);\n\n this->base_ir->insert_before(temp);\n\n \/* Counter of the number of components collected so far.\n *\/\n unsigned assigned;\n\n \/* Write-mask in the destination that receives counted by 'assigned'.\n *\/\n unsigned write_mask;\n\n\n \/* Generate upto four assignments to that variable. Try to group component\n * assignments together:\n *\n * - All constant components can be assigned at once.\n * - All assigments of components from a single variable with the same\n * unary operator can be assigned at once.\n *\/\n ir_constant_data d = { { 0 } };\n\n assigned = 0;\n write_mask = 0;\n for (unsigned i = 0; i < expr->type->vector_elements; i++) {\n const ir_constant *const c = expr->operands[i]->as_constant();\n\n if (c == NULL)\n\t continue;\n\n switch (expr->type->base_type) {\n case GLSL_TYPE_UINT: d.u[assigned] = c->value.u[0]; break;\n case GLSL_TYPE_INT: d.i[assigned] = c->value.i[0]; break;\n case GLSL_TYPE_FLOAT: d.f[assigned] = c->value.f[0]; break;\n case GLSL_TYPE_BOOL: d.b[assigned] = c->value.b[0]; break;\n defatul: assert(!\"Should not get here.\"); break;\n }\n\n write_mask |= (1U << i);\n assigned++;\n }\n\n assert((write_mask == 0) == (assigned == 0));\n\n \/* If there were constant values, generate an assignment.\n *\/\n if (assigned > 0) {\n ir_constant *const c =\n\t new(mem_ctx) ir_constant(glsl_type::get_instance(expr->type->base_type,\n\t\t\t\t\t\t\t assigned, 0),\n\t\t\t\t &d);\n ir_dereference *const lhs = new(mem_ctx) ir_dereference_variable(temp);\n ir_assignment *const assign =\n\t new(mem_ctx) ir_assignment(lhs, c, NULL, write_mask);\n\n this->base_ir->insert_before(assign);\n }\n\n \/* FINISHME: This should try to coalesce assignments.\n *\/\n for (unsigned i = 0; i < expr->type->vector_elements; i++) {\n if (expr->operands[i]->ir_type == ir_type_constant)\n\t continue;\n\n ir_dereference *const lhs = new(mem_ctx) ir_dereference_variable(temp);\n ir_assignment *const assign =\n\t new(mem_ctx) ir_assignment(lhs, expr->operands[i], NULL, (1U << i));\n\n this->base_ir->insert_before(assign);\n assigned++;\n }\n\n assert(assigned == expr->type->vector_elements);\n\n *rvalue = new(mem_ctx) ir_dereference_variable(temp);\n this->progress = true;\n}\n\nbool\nlower_quadop_vector(exec_list *instructions, bool dont_lower_swz)\n{\n lower_vector_visitor v;\n\n v.dont_lower_swz = dont_lower_swz;\n visit_list_elements(&v, instructions);\n\n return v.progress;\n}\n<commit_msg>glsl: Fix type of label 'default' in switch statement.<commit_after>\/*\n * Copyright © 2010 Intel Corporation\n *\n * Permission is hereby granted, free of charge, to any person obtaining a\n * copy of this software and associated documentation files (the \"Software\"),\n * to deal in the Software without restriction, including without limitation\n * the rights to use, copy, modify, merge, publish, distribute, sublicense,\n * and\/or sell copies of the Software, and to permit persons to whom the\n * Software is furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice (including the next\n * paragraph) shall be included in all copies or substantial portions of the\n * Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n * DEALINGS IN THE SOFTWARE.\n *\/\n\n\/**\n * \\file lower_vector.cpp\n * IR lowering pass to remove some types of ir_quadop_vector\n *\n * \\author Ian Romanick <ian.d.romanick@intel.com>\n *\/\n\n#include \"ir.h\"\n#include \"ir_rvalue_visitor.h\"\n\nclass lower_vector_visitor : public ir_rvalue_visitor {\npublic:\n lower_vector_visitor() : progress(false)\n {\n \/* empty *\/\n }\n\n void handle_rvalue(ir_rvalue **rvalue);\n\n \/**\n * Should SWZ-like expressions be lowered?\n *\/\n bool dont_lower_swz;\n\n bool progress;\n};\n\n\/**\n * Determine if an IR expression tree looks like an extended swizzle\n *\n * Extended swizzles consist of access of a single vector source (with possible\n * per component negation) and the constants -1, 0, or 1.\n *\/\nbool\nis_extended_swizzle(ir_expression *ir)\n{\n \/* Track any variables that are accessed by this expression.\n *\/\n ir_variable *var = NULL;\n\n assert(ir->operation == ir_quadop_vector);\n\n for (unsigned i = 0; i < ir->type->vector_elements; i++) {\n ir_rvalue *op = ir->operands[i];\n\n while (op != NULL) {\n\t switch (op->ir_type) {\n\t case ir_type_constant: {\n\t const ir_constant *const c = op->as_constant();\n\n\t if (!c->is_one() && !c->is_zero() && !c->is_negative_one())\n\t return false;\n\n\t op = NULL;\n\t break;\n\t }\n\n\t case ir_type_dereference_variable: {\n\t ir_dereference_variable *const d = (ir_dereference_variable *) op;\n\n\t if ((var != NULL) && (var != d->var))\n\t return false;\n\n\t var = d->var;\n\t op = NULL;\n\t break;\n\t }\n\n\t case ir_type_expression: {\n\t ir_expression *const ex = (ir_expression *) op;\n\n\t if (ex->operation != ir_unop_neg)\n\t return false;\n\n\t op = ex->operands[0];\n\t break;\n\t }\n\n\t case ir_type_swizzle:\n\t op = ((ir_swizzle *) op)->val;\n\t break;\n\n\t default:\n\t return false;\n\t }\n }\n }\n\n return true;\n}\n\nvoid\nlower_vector_visitor::handle_rvalue(ir_rvalue **rvalue)\n{\n if (!*rvalue)\n return;\n\n ir_expression *expr = (*rvalue)->as_expression();\n if ((expr == NULL) || (expr->operation != ir_quadop_vector))\n return;\n\n if (this->dont_lower_swz && is_extended_swizzle(expr))\n return;\n\n \/* FINISHME: Is this the right thing to use for the talloc context?\n *\/\n void *const mem_ctx = expr;\n\n assert(expr->type->vector_elements == expr->get_num_operands());\n\n \/* Generate a temporary with the same type as the ir_quadop_operation.\n *\/\n ir_variable *const temp =\n new(mem_ctx) ir_variable(expr->type, \"vecop_tmp\", ir_var_temporary);\n\n this->base_ir->insert_before(temp);\n\n \/* Counter of the number of components collected so far.\n *\/\n unsigned assigned;\n\n \/* Write-mask in the destination that receives counted by 'assigned'.\n *\/\n unsigned write_mask;\n\n\n \/* Generate upto four assignments to that variable. Try to group component\n * assignments together:\n *\n * - All constant components can be assigned at once.\n * - All assigments of components from a single variable with the same\n * unary operator can be assigned at once.\n *\/\n ir_constant_data d = { { 0 } };\n\n assigned = 0;\n write_mask = 0;\n for (unsigned i = 0; i < expr->type->vector_elements; i++) {\n const ir_constant *const c = expr->operands[i]->as_constant();\n\n if (c == NULL)\n\t continue;\n\n switch (expr->type->base_type) {\n case GLSL_TYPE_UINT: d.u[assigned] = c->value.u[0]; break;\n case GLSL_TYPE_INT: d.i[assigned] = c->value.i[0]; break;\n case GLSL_TYPE_FLOAT: d.f[assigned] = c->value.f[0]; break;\n case GLSL_TYPE_BOOL: d.b[assigned] = c->value.b[0]; break;\n default: assert(!\"Should not get here.\"); break;\n }\n\n write_mask |= (1U << i);\n assigned++;\n }\n\n assert((write_mask == 0) == (assigned == 0));\n\n \/* If there were constant values, generate an assignment.\n *\/\n if (assigned > 0) {\n ir_constant *const c =\n\t new(mem_ctx) ir_constant(glsl_type::get_instance(expr->type->base_type,\n\t\t\t\t\t\t\t assigned, 0),\n\t\t\t\t &d);\n ir_dereference *const lhs = new(mem_ctx) ir_dereference_variable(temp);\n ir_assignment *const assign =\n\t new(mem_ctx) ir_assignment(lhs, c, NULL, write_mask);\n\n this->base_ir->insert_before(assign);\n }\n\n \/* FINISHME: This should try to coalesce assignments.\n *\/\n for (unsigned i = 0; i < expr->type->vector_elements; i++) {\n if (expr->operands[i]->ir_type == ir_type_constant)\n\t continue;\n\n ir_dereference *const lhs = new(mem_ctx) ir_dereference_variable(temp);\n ir_assignment *const assign =\n\t new(mem_ctx) ir_assignment(lhs, expr->operands[i], NULL, (1U << i));\n\n this->base_ir->insert_before(assign);\n assigned++;\n }\n\n assert(assigned == expr->type->vector_elements);\n\n *rvalue = new(mem_ctx) ir_dereference_variable(temp);\n this->progress = true;\n}\n\nbool\nlower_quadop_vector(exec_list *instructions, bool dont_lower_swz)\n{\n lower_vector_visitor v;\n\n v.dont_lower_swz = dont_lower_swz;\n visit_list_elements(&v, instructions);\n\n return v.progress;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright 2012 Google Inc.\n *\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n *\/\n\n#include \"gm.h\"\n#include \"SkCanvas.h\"\n#include \"SkPaint.h\"\n#include \"SkDashPathEffect.h\"\n\nstatic void drawline(SkCanvas* canvas, int on, int off, const SkPaint& paint,\n SkScalar finalX = SkIntToScalar(600)) {\n SkPaint p(paint);\n\n const SkScalar intervals[] = {\n SkIntToScalar(on),\n SkIntToScalar(off),\n };\n\n p.setPathEffect(new SkDashPathEffect(intervals, 2, 0))->unref();\n canvas->drawLine(0, 0, finalX, 0, p);\n}\n\n\/\/ earlier bug stopped us from drawing very long single-segment dashes, because\n\/\/ SkPathMeasure was skipping very small delta-T values (nearlyzero). This is\n\/\/ now fixes, so this giant dash should appear.\nstatic void show_giant_dash(SkCanvas* canvas) {\n SkPaint paint;\n\n drawline(canvas, 1, 1, paint, SkIntToScalar(20 * 1000));\n}\n\nclass DashingGM : public skiagm::GM {\npublic:\n DashingGM() {}\n\nprotected:\n SkString onShortName() {\n return SkString(\"dashing\");\n }\n\n SkISize onISize() { return skiagm::make_isize(640, 300); }\n\n virtual void onDraw(SkCanvas* canvas) {\n static const struct {\n int fOnInterval;\n int fOffInterval;\n } gData[] = {\n { 1, 1 },\n { 4, 1 },\n };\n\n SkPaint paint;\n paint.setStyle(SkPaint::kStroke_Style);\n\n canvas->translate(SkIntToScalar(20), SkIntToScalar(20));\n canvas->translate(0, SK_ScalarHalf);\n\n for (int width = 0; width <= 2; ++width) {\n for (size_t data = 0; data < SK_ARRAY_COUNT(gData); ++data) {\n for (int aa = 0; aa <= 1; ++aa) {\n int w = width * width * width;\n paint.setAntiAlias(SkToBool(aa));\n paint.setStrokeWidth(SkIntToScalar(w));\n\n int scale = w ? w : 1;\n\n drawline(canvas, gData[data].fOnInterval * scale,\n gData[data].fOffInterval * scale,\n paint);\n canvas->translate(0, SkIntToScalar(20));\n }\n }\n }\n\n show_giant_dash(canvas);\n }\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstatic void make_unit_star(SkPath* path, int n) {\n SkScalar rad = -SK_ScalarPI \/ 2;\n const SkScalar drad = (n >> 1) * SK_ScalarPI * 2 \/ n;\n\n path->moveTo(0, -SK_Scalar1);\n for (int i = 1; i < n; i++) {\n rad += drad;\n SkScalar cosV, sinV = SkScalarSinCos(rad, &cosV);\n path->lineTo(cosV, sinV);\n }\n path->close();\n}\n\nstatic void make_path_line(SkPath* path, const SkRect& bounds) {\n path->moveTo(bounds.left(), bounds.top());\n path->lineTo(bounds.right(), bounds.bottom());\n}\n\nstatic void make_path_rect(SkPath* path, const SkRect& bounds) {\n path->addRect(bounds);\n}\n\nstatic void make_path_oval(SkPath* path, const SkRect& bounds) {\n path->addOval(bounds);\n}\n\nstatic void make_path_star(SkPath* path, const SkRect& bounds) {\n make_unit_star(path, 5);\n SkMatrix matrix;\n matrix.setRectToRect(path->getBounds(), bounds, SkMatrix::kCenter_ScaleToFit);\n path->transform(matrix);\n}\n\nclass Dashing2GM : public skiagm::GM {\npublic:\n Dashing2GM() {}\n\nprotected:\n SkString onShortName() {\n return SkString(\"dashing2\");\n }\n\n SkISize onISize() { return skiagm::make_isize(640, 480); }\n\n virtual void onDraw(SkCanvas* canvas) {\n static const int gIntervals[] = {\n 3, \/\/ 3 dashes: each count [0] followed by intervals [1..count]\n 2, 10, 10,\n 4, 20, 5, 5, 5,\n 2, 2, 2\n };\n\n void (*gProc[])(SkPath*, const SkRect&) = {\n make_path_line, make_path_rect, make_path_oval, make_path_star,\n };\n\n SkPaint paint;\n paint.setAntiAlias(true);\n paint.setStyle(SkPaint::kStroke_Style);\n paint.setStrokeWidth(SkIntToScalar(6));\n\n SkRect bounds = SkRect::MakeWH(SkIntToScalar(120), SkIntToScalar(120));\n bounds.offset(SkIntToScalar(20), SkIntToScalar(20));\n SkScalar dx = bounds.width() * 4 \/ 3;\n SkScalar dy = bounds.height() * 4 \/ 3;\n\n const int* intervals = &gIntervals[1];\n for (int y = 0; y < gIntervals[0]; ++y) {\n SkScalar vals[SK_ARRAY_COUNT(gIntervals)]; \/\/ more than enough\n int count = *intervals++;\n for (int i = 0; i < count; ++i) {\n vals[i] = SkIntToScalar(*intervals++);\n }\n SkScalar phase = vals[0] \/ 2;\n paint.setPathEffect(new SkDashPathEffect(vals, count, phase))->unref();\n\n for (size_t x = 0; x < SK_ARRAY_COUNT(gProc); ++x) {\n SkPath path;\n SkRect r = bounds;\n r.offset(x * dx, y * dy);\n gProc[x](&path, r);\n\n canvas->drawPath(path, paint);\n }\n }\n }\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/ Test out the on\/off line dashing Chrome if fond of\nclass Dashing3GM : public skiagm::GM {\npublic:\n Dashing3GM() {}\n\nprotected:\n SkString onShortName() {\n return SkString(\"dashing3\");\n }\n\n SkISize onISize() { return skiagm::make_isize(640, 480); }\n\n \/\/ Draw a 100x100 block of dashed lines. The horizontal ones are BW\n \/\/ while the vertical ones are AA.\n void drawDashedLines(SkCanvas* canvas, SkScalar length, SkScalar phase) {\n SkPaint p;\n p.setColor(SK_ColorBLACK);\n p.setStyle(SkPaint::kStroke_Style);\n p.setStrokeWidth(SK_Scalar1);\n\n SkScalar intervals[2] = { SK_Scalar1, SK_Scalar1 };\n\n p.setPathEffect(new SkDashPathEffect(intervals, 2, phase, false));\n\n SkPoint pts[2];\n\n for (int y = 0; y < 100; y += 5) {\n pts[0].set(0, SkIntToScalar(y));\n pts[1].set(length, SkIntToScalar(y));\n\n canvas->drawPoints(SkCanvas::kLines_PointMode, 2, pts, p);\n }\n\n p.setAntiAlias(true);\n\n for (int x = 0; x < 100; x += 7) {\n pts[0].set(SkIntToScalar(x), 0);\n pts[1].set(SkIntToScalar(x), length);\n\n canvas->drawPoints(SkCanvas::kLines_PointMode, 2, pts, p);\n }\n }\n\n virtual void onDraw(SkCanvas* canvas) {\n \/\/ fast path should work on this run\n canvas->save();\n this->drawDashedLines(canvas, 100, SK_Scalar1);\n canvas->restore();\n\n \/\/ non-1 phase should break the fast path\n canvas->save();\n canvas->translate(110, 0);\n this->drawDashedLines(canvas, 100, SK_ScalarHalf);\n canvas->restore();\n\n \/\/ non-integer length should break the fast path\n canvas->save();\n canvas->translate(220, 0);\n this->drawDashedLines(canvas, 99.5, SK_ScalarHalf);\n canvas->restore();\n\n \/\/ rotation should break the fast path\n canvas->save();\n canvas->translate(110+SK_ScalarRoot2Over2*100, 110+SK_ScalarRoot2Over2*100);\n canvas->rotate(45);\n canvas->translate(-50, -50);\n\n this->drawDashedLines(canvas, 100, SK_Scalar1);\n canvas->restore();\n\n }\n\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstatic skiagm::GM* F0(void*) { return new DashingGM; }\nstatic skiagm::GM* F1(void*) { return new Dashing2GM; }\nstatic skiagm::GM* F2(void*) { return new Dashing3GM; }\n\nstatic skiagm::GMRegistry gR0(F0);\nstatic skiagm::GMRegistry gR1(F1);\nstatic skiagm::GMRegistry gR2(F2);\n\n<commit_msg>Expand dashing3 GM to include additional dashing cases<commit_after>\/*\n * Copyright 2012 Google Inc.\n *\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n *\/\n\n#include \"gm.h\"\n#include \"SkCanvas.h\"\n#include \"SkPaint.h\"\n#include \"SkDashPathEffect.h\"\n\nstatic void drawline(SkCanvas* canvas, int on, int off, const SkPaint& paint,\n SkScalar finalX = SkIntToScalar(600)) {\n SkPaint p(paint);\n\n const SkScalar intervals[] = {\n SkIntToScalar(on),\n SkIntToScalar(off),\n };\n\n p.setPathEffect(new SkDashPathEffect(intervals, 2, 0))->unref();\n canvas->drawLine(0, 0, finalX, 0, p);\n}\n\n\/\/ earlier bug stopped us from drawing very long single-segment dashes, because\n\/\/ SkPathMeasure was skipping very small delta-T values (nearlyzero). This is\n\/\/ now fixes, so this giant dash should appear.\nstatic void show_giant_dash(SkCanvas* canvas) {\n SkPaint paint;\n\n drawline(canvas, 1, 1, paint, SkIntToScalar(20 * 1000));\n}\n\nclass DashingGM : public skiagm::GM {\npublic:\n DashingGM() {}\n\nprotected:\n SkString onShortName() {\n return SkString(\"dashing\");\n }\n\n SkISize onISize() { return skiagm::make_isize(640, 300); }\n\n virtual void onDraw(SkCanvas* canvas) {\n static const struct {\n int fOnInterval;\n int fOffInterval;\n } gData[] = {\n { 1, 1 },\n { 4, 1 },\n };\n\n SkPaint paint;\n paint.setStyle(SkPaint::kStroke_Style);\n\n canvas->translate(SkIntToScalar(20), SkIntToScalar(20));\n canvas->translate(0, SK_ScalarHalf);\n\n for (int width = 0; width <= 2; ++width) {\n for (size_t data = 0; data < SK_ARRAY_COUNT(gData); ++data) {\n for (int aa = 0; aa <= 1; ++aa) {\n int w = width * width * width;\n paint.setAntiAlias(SkToBool(aa));\n paint.setStrokeWidth(SkIntToScalar(w));\n\n int scale = w ? w : 1;\n\n drawline(canvas, gData[data].fOnInterval * scale,\n gData[data].fOffInterval * scale,\n paint);\n canvas->translate(0, SkIntToScalar(20));\n }\n }\n }\n\n show_giant_dash(canvas);\n }\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstatic void make_unit_star(SkPath* path, int n) {\n SkScalar rad = -SK_ScalarPI \/ 2;\n const SkScalar drad = (n >> 1) * SK_ScalarPI * 2 \/ n;\n\n path->moveTo(0, -SK_Scalar1);\n for (int i = 1; i < n; i++) {\n rad += drad;\n SkScalar cosV, sinV = SkScalarSinCos(rad, &cosV);\n path->lineTo(cosV, sinV);\n }\n path->close();\n}\n\nstatic void make_path_line(SkPath* path, const SkRect& bounds) {\n path->moveTo(bounds.left(), bounds.top());\n path->lineTo(bounds.right(), bounds.bottom());\n}\n\nstatic void make_path_rect(SkPath* path, const SkRect& bounds) {\n path->addRect(bounds);\n}\n\nstatic void make_path_oval(SkPath* path, const SkRect& bounds) {\n path->addOval(bounds);\n}\n\nstatic void make_path_star(SkPath* path, const SkRect& bounds) {\n make_unit_star(path, 5);\n SkMatrix matrix;\n matrix.setRectToRect(path->getBounds(), bounds, SkMatrix::kCenter_ScaleToFit);\n path->transform(matrix);\n}\n\nclass Dashing2GM : public skiagm::GM {\npublic:\n Dashing2GM() {}\n\nprotected:\n SkString onShortName() {\n return SkString(\"dashing2\");\n }\n\n SkISize onISize() { return skiagm::make_isize(640, 480); }\n\n virtual void onDraw(SkCanvas* canvas) {\n static const int gIntervals[] = {\n 3, \/\/ 3 dashes: each count [0] followed by intervals [1..count]\n 2, 10, 10,\n 4, 20, 5, 5, 5,\n 2, 2, 2\n };\n\n void (*gProc[])(SkPath*, const SkRect&) = {\n make_path_line, make_path_rect, make_path_oval, make_path_star,\n };\n\n SkPaint paint;\n paint.setAntiAlias(true);\n paint.setStyle(SkPaint::kStroke_Style);\n paint.setStrokeWidth(SkIntToScalar(6));\n\n SkRect bounds = SkRect::MakeWH(SkIntToScalar(120), SkIntToScalar(120));\n bounds.offset(SkIntToScalar(20), SkIntToScalar(20));\n SkScalar dx = bounds.width() * 4 \/ 3;\n SkScalar dy = bounds.height() * 4 \/ 3;\n\n const int* intervals = &gIntervals[1];\n for (int y = 0; y < gIntervals[0]; ++y) {\n SkScalar vals[SK_ARRAY_COUNT(gIntervals)]; \/\/ more than enough\n int count = *intervals++;\n for (int i = 0; i < count; ++i) {\n vals[i] = SkIntToScalar(*intervals++);\n }\n SkScalar phase = vals[0] \/ 2;\n paint.setPathEffect(new SkDashPathEffect(vals, count, phase))->unref();\n\n for (size_t x = 0; x < SK_ARRAY_COUNT(gProc); ++x) {\n SkPath path;\n SkRect r = bounds;\n r.offset(x * dx, y * dy);\n gProc[x](&path, r);\n\n canvas->drawPath(path, paint);\n }\n }\n }\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/ Test out the on\/off line dashing Chrome if fond of\nclass Dashing3GM : public skiagm::GM {\npublic:\n Dashing3GM() {}\n\nprotected:\n SkString onShortName() {\n return SkString(\"dashing3\");\n }\n\n SkISize onISize() { return skiagm::make_isize(640, 480); }\n\n \/\/ Draw a 100x100 block of dashed lines. The horizontal ones are BW\n \/\/ while the vertical ones are AA.\n void drawDashedLines(SkCanvas* canvas, \n SkScalar lineLength, \n SkScalar phase,\n SkScalar dashLength,\n int strokeWidth,\n bool circles) {\n SkPaint p;\n p.setColor(SK_ColorBLACK);\n p.setStyle(SkPaint::kStroke_Style);\n p.setStrokeWidth(SkIntToScalar(strokeWidth));\n\n if (circles) {\n p.setStrokeCap(SkPaint::kRound_Cap);\n }\n\n SkScalar intervals[2] = { dashLength, dashLength };\n\n p.setPathEffect(new SkDashPathEffect(intervals, 2, phase, false));\n\n SkPoint pts[2];\n\n for (int y = 0; y < 100; y += 10*strokeWidth) {\n pts[0].set(0, SkIntToScalar(y));\n pts[1].set(lineLength, SkIntToScalar(y));\n\n canvas->drawPoints(SkCanvas::kLines_PointMode, 2, pts, p);\n }\n\n p.setAntiAlias(true);\n\n for (int x = 0; x < 100; x += 14*strokeWidth) {\n pts[0].set(SkIntToScalar(x), 0);\n pts[1].set(SkIntToScalar(x), lineLength);\n\n canvas->drawPoints(SkCanvas::kLines_PointMode, 2, pts, p);\n }\n }\n\n virtual void onDraw(SkCanvas* canvas) {\n \/\/ 1on\/1off 1x1 squares with phase of 0 - points fastpath\n canvas->save();\n canvas->translate(2, 0);\n this->drawDashedLines(canvas, 100, 0, SK_Scalar1, 1, false);\n canvas->restore();\n\n \/\/ 1on\/1off 1x1 squares with phase of .5 - rects fastpath (due to partial squares)\n canvas->save();\n canvas->translate(112, 0);\n this->drawDashedLines(canvas, 100, SK_ScalarHalf, SK_Scalar1, 1, false);\n canvas->restore();\n\n \/\/ 1on\/1off 1x1 squares with phase of 1 - points fastpath\n canvas->save();\n canvas->translate(222, 0);\n this->drawDashedLines(canvas, 100, SK_Scalar1, SK_Scalar1, 1, false);\n canvas->restore();\n\n \/\/ 1on\/1off 1x1 squares with phase of 1 and non-integer length - rects fastpath\n canvas->save();\n canvas->translate(332, 0);\n this->drawDashedLines(canvas, 99.5, SK_ScalarHalf, SK_Scalar1, 1, false);\n canvas->restore();\n\n \/\/ 1on\/1off 3x3 squares with phase of 0 - points fast path\n canvas->save();\n canvas->translate(2, 110);\n this->drawDashedLines(canvas, 100, 0, SkIntToScalar(3), 3, false);\n canvas->restore();\n\n \/\/ 1on\/1off 3x3 squares with phase of 1.5 - rects fast path\n canvas->save();\n canvas->translate(112, 110);\n this->drawDashedLines(canvas, 100, SkFloatToScalar(1.5f), SkIntToScalar(3), 3, false);\n canvas->restore();\n\n \/\/ 1on\/1off 1x1 circles with phase of 1 - no fast path yet\n canvas->save();\n canvas->translate(2, 220);\n this->drawDashedLines(canvas, 100, SK_Scalar1, SK_Scalar1, 1, true);\n canvas->restore();\n\n \/\/ 1on\/1off 3x3 circles with phase of 1 - no fast path yet\n canvas->save();\n canvas->translate(112, 220);\n this->drawDashedLines(canvas, 100, 0, SkIntToScalar(3), 3, true);\n canvas->restore();\n\n \/\/ 1on\/1off 1x1 squares with rotation - should break fast path\n canvas->save();\n canvas->translate(332+SK_ScalarRoot2Over2*100, 110+SK_ScalarRoot2Over2*100);\n canvas->rotate(45);\n canvas->translate(-50, -50);\n\n this->drawDashedLines(canvas, 100, SK_Scalar1, SK_Scalar1, 1, false);\n canvas->restore();\n\n \/\/ 3on\/3off 3x1 rects - should use rect fast path regardless of phase\n for (int phase = 0; phase <= 3; ++phase) {\n canvas->save();\n canvas->translate(SkIntToScalar(phase*110+2), \n SkIntToScalar(330));\n this->drawDashedLines(canvas, 100, SkIntToScalar(phase), SkIntToScalar(3), 1, false);\n canvas->restore();\n }\n }\n\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstatic skiagm::GM* F0(void*) { return new DashingGM; }\nstatic skiagm::GM* F1(void*) { return new Dashing2GM; }\nstatic skiagm::GM* F2(void*) { return new Dashing3GM; }\n\nstatic skiagm::GMRegistry gR0(F0);\nstatic skiagm::GMRegistry gR1(F1);\nstatic skiagm::GMRegistry gR2(F2);\n\n<|endoftext|>"} {"text":"<commit_before>#include \"gtest\/gtest.h\"\n\n#include \"amf.hpp\"\n#include \"types\/amfvector.hpp\"\n\ntemplate<typename T>\nstatic void isEqual(const std::vector<u8>& expected, AmfVector<T> vector) {\n\tASSERT_EQ(expected, vector.serialize());\n}\n\nTEST(VectorSerializationTest, EmptyVectorInt) {\n\tAmfVector<int> vec({}, false);\n\tv8 expected { 0x0d, 0x01, 0x00 };\n\tASSERT_EQ(expected, vec.serialize());\n\n\tvec = {{}, true};\n\texpected = { 0x0d, 0x01, 0x01 };\n\tASSERT_EQ(expected, vec.serialize());\n}\n\nTEST(VectorSerializationTest, VectorInt) {\n\tAmfVector<int> vec({ 1, 2, 3 }, false);\n\tv8 expected {\n\t\t0x0d, 0x07, 0x00,\n\t\t0x00, 0x00, 0x00, 0x01,\n\t\t0x00, 0x00, 0x00, 0x02,\n\t\t0x00, 0x00, 0x00, 0x03\n\t};\n\tASSERT_EQ(expected, vec.serialize());\n\n\tvec = {{ 0xff, 0x100, 0xfffe, 0xffff, 0x123456, 0xfffffff }, true};\n\texpected = {\n\t\t0x0d, 0x0d, 0x01,\n\t\t0x00, 0x00, 0x00, 0xff,\n\t\t0x00, 0x00, 0x01, 0x00,\n\t\t0x00, 0x00, 0xff, 0xfe,\n\t\t0x00, 0x00, 0xff, 0xff,\n\t\t0x00, 0x12, 0x34, 0x56,\n\t\t0x0f, 0xff, 0xff, 0xff\n\t};\n\tASSERT_EQ(expected, vec.serialize());\n}\n\nTEST(VectorSerializationTest, VectorInt32) {\n\tAmfVector<int> vec({\n\t\t0x20000000,\n\t\t0x40000000,\n\t\t0x7fffffff\n\t}, true);\n\tv8 expected {\n\t\t0x0d, 0x07, 0x01,\n\t\t0x20, 0x00, 0x00, 0x00,\n\t\t0x40, 0x00, 0x00, 0x00,\n\t\t0x7f, 0xff, 0xff, 0xff\n\t};\n\tASSERT_EQ(expected, vec.serialize());\n}\n\nTEST(VectorSerializationTest, VectorIntNegative) {\n\tAmfVector<int> vec({ -1, -2, -0xffff }, false);\n\tv8 expected {\n\t\t0x0d, 0x07, 0x00,\n\t\t0xff, 0xff, 0xff, 0xff,\n\t\t0xff, 0xff, 0xff, 0xfe,\n\t\t0xff, 0xff, 0x00, 0x01\n\t};\n\tASSERT_EQ(expected, vec.serialize());\n}\n\nTEST(VectorSerializationTest, VectorInt32Negative) {\n\tAmfVector<int> vec({\n\t\t-0x20000000,\n\t\t-0x40000000,\n\t\t-0x7fffffff,\n\t\t-0x80000000\n\t}, true);\n\tv8 expected {\n\t\t0x0d, 0x09, 0x01,\n\t\t0xe0, 0x00, 0x00, 0x00,\n\t\t0xc0, 0x00, 0x00, 0x00,\n\t\t0x80, 0x00, 0x00, 0x01,\n\t\t0x80, 0x00, 0x00, 0x00\n\t};\n\tASSERT_EQ(expected, vec.serialize());\n}\n\nTEST(VectorSerializationTest, VectorIntFixedDefault) {\n\tAmfVector<int> vec({1, 3, 5});\n\tv8 expected {\n\t\t0x0d, 0x07, 0x00,\n\t\t0x00, 0x00, 0x00, 0x01,\n\t\t0x00, 0x00, 0x00, 0x03,\n\t\t0x00, 0x00, 0x00, 0x05\n\t};\n\tASSERT_EQ(expected, vec.serialize());\n}\n<commit_msg>Fix int literal in test<commit_after>#include \"gtest\/gtest.h\"\n\n#include \"amf.hpp\"\n#include \"types\/amfvector.hpp\"\n\ntemplate<typename T>\nstatic void isEqual(const std::vector<u8>& expected, AmfVector<T> vector) {\n\tASSERT_EQ(expected, vector.serialize());\n}\n\nTEST(VectorSerializationTest, EmptyVectorInt) {\n\tAmfVector<int> vec({}, false);\n\tv8 expected { 0x0d, 0x01, 0x00 };\n\tASSERT_EQ(expected, vec.serialize());\n\n\tvec = {{}, true};\n\texpected = { 0x0d, 0x01, 0x01 };\n\tASSERT_EQ(expected, vec.serialize());\n}\n\nTEST(VectorSerializationTest, VectorInt) {\n\tAmfVector<int> vec({ 1, 2, 3 }, false);\n\tv8 expected {\n\t\t0x0d, 0x07, 0x00,\n\t\t0x00, 0x00, 0x00, 0x01,\n\t\t0x00, 0x00, 0x00, 0x02,\n\t\t0x00, 0x00, 0x00, 0x03\n\t};\n\tASSERT_EQ(expected, vec.serialize());\n\n\tvec = {{ 0xff, 0x100, 0xfffe, 0xffff, 0x123456, 0xfffffff }, true};\n\texpected = {\n\t\t0x0d, 0x0d, 0x01,\n\t\t0x00, 0x00, 0x00, 0xff,\n\t\t0x00, 0x00, 0x01, 0x00,\n\t\t0x00, 0x00, 0xff, 0xfe,\n\t\t0x00, 0x00, 0xff, 0xff,\n\t\t0x00, 0x12, 0x34, 0x56,\n\t\t0x0f, 0xff, 0xff, 0xff\n\t};\n\tASSERT_EQ(expected, vec.serialize());\n}\n\nTEST(VectorSerializationTest, VectorInt32) {\n\tAmfVector<int> vec({\n\t\t0x20000000,\n\t\t0x40000000,\n\t\t0x7fffffff\n\t}, true);\n\tv8 expected {\n\t\t0x0d, 0x07, 0x01,\n\t\t0x20, 0x00, 0x00, 0x00,\n\t\t0x40, 0x00, 0x00, 0x00,\n\t\t0x7f, 0xff, 0xff, 0xff\n\t};\n\tASSERT_EQ(expected, vec.serialize());\n}\n\nTEST(VectorSerializationTest, VectorIntNegative) {\n\tAmfVector<int> vec({ -1, -2, -0xffff }, false);\n\tv8 expected {\n\t\t0x0d, 0x07, 0x00,\n\t\t0xff, 0xff, 0xff, 0xff,\n\t\t0xff, 0xff, 0xff, 0xfe,\n\t\t0xff, 0xff, 0x00, 0x01\n\t};\n\tASSERT_EQ(expected, vec.serialize());\n}\n\nTEST(VectorSerializationTest, VectorInt32Negative) {\n\tAmfVector<int> vec({\n\t\t-0x20000000,\n\t\t-0x40000000,\n\t\t-0x7fffffff,\n\t\t-2147483648\n\t}, true);\n\tv8 expected {\n\t\t0x0d, 0x09, 0x01,\n\t\t0xe0, 0x00, 0x00, 0x00,\n\t\t0xc0, 0x00, 0x00, 0x00,\n\t\t0x80, 0x00, 0x00, 0x01,\n\t\t0x80, 0x00, 0x00, 0x00\n\t};\n\tASSERT_EQ(expected, vec.serialize());\n}\n\nTEST(VectorSerializationTest, VectorIntFixedDefault) {\n\tAmfVector<int> vec({1, 3, 5});\n\tv8 expected {\n\t\t0x0d, 0x07, 0x00,\n\t\t0x00, 0x00, 0x00, 0x01,\n\t\t0x00, 0x00, 0x00, 0x03,\n\t\t0x00, 0x00, 0x00, 0x05\n\t};\n\tASSERT_EQ(expected, vec.serialize());\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"base\/basictypes.h\"\n#include \"base\/gfx\/png_encoder.h\"\n#include \"base\/logging.h\"\n#include \"base\/scoped_ptr.h\"\n#include \"third_party\/skia\/include\/core\/SkBitmap.h\"\n\nextern \"C\" {\n#include \"third_party\/libpng\/png.h\"\n}\n\nnamespace {\n\n\/\/ Converts BGRA->RGBA and RGBA->BGRA.\nvoid ConvertBetweenBGRAandRGBA(const unsigned char* input, int pixel_width,\n unsigned char* output) {\n for (int x = 0; x < pixel_width; x++) {\n const unsigned char* pixel_in = &input[x * 4];\n unsigned char* pixel_out = &output[x * 4];\n pixel_out[0] = pixel_in[2];\n pixel_out[1] = pixel_in[1];\n pixel_out[2] = pixel_in[0];\n pixel_out[3] = pixel_in[3];\n }\n}\n\nvoid ConvertRGBAtoRGB(const unsigned char* rgba, int pixel_width,\n unsigned char* rgb) {\n for (int x = 0; x < pixel_width; x++) {\n const unsigned char* pixel_in = &rgba[x * 4];\n unsigned char* pixel_out = &rgb[x * 3];\n pixel_out[0] = pixel_in[0];\n pixel_out[1] = pixel_in[1];\n pixel_out[2] = pixel_in[2];\n }\n}\n\n} \/\/ namespace\n\n\/\/ Encoder --------------------------------------------------------------------\n\/\/\n\/\/ This section of the code is based on nsPNGEncoder.cpp in Mozilla\n\/\/ (Copyright 2005 Google Inc.)\n\nnamespace {\n\n\/\/ Passed around as the io_ptr in the png structs so our callbacks know where\n\/\/ to write data.\nstruct PngEncoderState {\n PngEncoderState(std::vector<unsigned char>* o) : out(o) {}\n std::vector<unsigned char>* out;\n};\n\n\/\/ Called by libpng to flush its internal buffer to ours.\nvoid EncoderWriteCallback(png_structp png, png_bytep data, png_size_t size) {\n PngEncoderState* state = static_cast<PngEncoderState*>(png_get_io_ptr(png));\n DCHECK(state->out);\n\n size_t old_size = state->out->size();\n state->out->resize(old_size + size);\n memcpy(&(*state->out)[old_size], data, size);\n}\n\nvoid ConvertBGRAtoRGB(const unsigned char* bgra, int pixel_width,\n unsigned char* rgb) {\n for (int x = 0; x < pixel_width; x++) {\n const unsigned char* pixel_in = &bgra[x * 4];\n unsigned char* pixel_out = &rgb[x * 3];\n pixel_out[0] = pixel_in[2];\n pixel_out[1] = pixel_in[1];\n pixel_out[2] = pixel_in[0];\n }\n}\n\n\/\/ Automatically destroys the given write structs on destruction to make\n\/\/ cleanup and error handling code cleaner.\nclass PngWriteStructDestroyer {\n public:\n PngWriteStructDestroyer(png_struct** ps, png_info** pi) : ps_(ps), pi_(pi) {\n }\n ~PngWriteStructDestroyer() {\n png_destroy_write_struct(ps_, pi_);\n }\n private:\n png_struct** ps_;\n png_info** pi_;\n\n DISALLOW_EVIL_CONSTRUCTORS(PngWriteStructDestroyer);\n};\n\n} \/\/ namespace\n\n\/\/ static\nbool PNGEncoder::Encode(const unsigned char* input, ColorFormat format,\n int w, int h, int row_byte_width,\n bool discard_transparency,\n std::vector<unsigned char>* output) {\n \/\/ Run to convert an input row into the output row format, NULL means no\n \/\/ conversion is necessary.\n void (*converter)(const unsigned char* in, int w, unsigned char* out) = NULL;\n\n int input_color_components, output_color_components;\n int png_output_color_type;\n switch (format) {\n case FORMAT_RGB:\n input_color_components = 3;\n output_color_components = 3;\n png_output_color_type = PNG_COLOR_TYPE_RGB;\n discard_transparency = false;\n break;\n\n case FORMAT_RGBA:\n input_color_components = 4;\n if (discard_transparency) {\n output_color_components = 3;\n png_output_color_type = PNG_COLOR_TYPE_RGB;\n converter = ConvertRGBAtoRGB;\n } else {\n output_color_components = 4;\n png_output_color_type = PNG_COLOR_TYPE_RGB_ALPHA;\n converter = NULL;\n }\n break;\n\n case FORMAT_BGRA:\n input_color_components = 4;\n if (discard_transparency) {\n output_color_components = 3;\n png_output_color_type = PNG_COLOR_TYPE_RGB;\n converter = ConvertBGRAtoRGB;\n } else {\n output_color_components = 4;\n png_output_color_type = PNG_COLOR_TYPE_RGB_ALPHA;\n converter = ConvertBetweenBGRAandRGBA;\n }\n break;\n\n default:\n NOTREACHED() << \"Unknown pixel format\";\n return false;\n }\n\n \/\/ Row stride should be at least as long as the length of the data.\n DCHECK(input_color_components * w <= row_byte_width);\n\n png_struct* png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING,\n png_voidp_NULL,\n png_error_ptr_NULL,\n png_error_ptr_NULL);\n if (!png_ptr)\n return false;\n png_info* info_ptr = png_create_info_struct(png_ptr);\n if (!info_ptr) {\n png_destroy_write_struct(&png_ptr, NULL);\n return false;\n }\n PngWriteStructDestroyer destroyer(&png_ptr, &info_ptr);\n\n if (setjmp(png_jmpbuf(png_ptr))) {\n \/\/ The destroyer will ensure that the structures are cleaned up in this\n \/\/ case, even though we may get here as a jump from random parts of the\n \/\/ PNG library called below.\n return false;\n }\n\n \/\/ Set our callback for libpng to give us the data.\n PngEncoderState state(output);\n png_set_write_fn(png_ptr, &state, EncoderWriteCallback, NULL);\n\n png_set_IHDR(png_ptr, info_ptr, w, h, 8, png_output_color_type,\n PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_DEFAULT,\n PNG_FILTER_TYPE_DEFAULT);\n png_write_info(png_ptr, info_ptr);\n\n if (!converter) {\n \/\/ No conversion needed, give the data directly to libpng.\n for (int y = 0; y < h; y ++)\n png_write_row(png_ptr,\n const_cast<unsigned char*>(&input[y * row_byte_width]));\n } else {\n \/\/ Needs conversion using a separate buffer.\n unsigned char* row = new unsigned char[w * output_color_components];\n for (int y = 0; y < h; y ++) {\n converter(&input[y * row_byte_width], w, row);\n png_write_row(png_ptr, row);\n }\n delete[] row;\n }\n\n png_write_end(png_ptr, info_ptr);\n return true;\n}\n\n\/\/ static\nbool PNGEncoder::EncodeBGRASkBitmap(const SkBitmap& input,\n bool discard_transparency,\n std::vector<unsigned char>* output) {\n \/\/ This only works with images with four bytes per pixel.\n static const int bbp = 4;\n\n DCHECK(input.empty() || input.bytesPerPixel() == bbp);\n\n \/\/ SkBitmaps are premultiplied, we need to unpremultiply them.\n scoped_array<unsigned char> divided(\n new unsigned char[input.width() * input.height() * bbp]);\n\n SkAutoLockPixels lock_input(input);\n int i = 0;\n for (int y = 0; y < input.height(); y++) {\n uint32* src_row = input.getAddr32(0, y);\n for (int x = 0; x < input.width(); x++) {\n int alpha = SkColorGetA(src_row[x]);\n if (alpha != 0 && alpha != 255) {\n divided[i + 0] = (SkColorGetR(src_row[x]) << 8) \/ alpha;\n divided[i + 1] = (SkColorGetG(src_row[x]) << 8) \/ alpha;\n divided[i + 2] = (SkColorGetB(src_row[x]) << 8) \/ alpha;\n divided[i + 3] = alpha;\n } else {\n divided[i + 0] = SkColorGetR(src_row[x]);\n divided[i + 1] = SkColorGetG(src_row[x]);\n divided[i + 2] = SkColorGetB(src_row[x]);\n divided[i + 3] = SkColorGetA(src_row[x]);\n }\n i += bbp;\n }\n }\n\n return Encode(divided.release(),\n PNGEncoder::FORMAT_RGBA, input.width(), input.height(),\n input.rowBytes(), discard_transparency, output);\n}\n<commit_msg>Attempt to fix memory leak again.<commit_after>\/\/ Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"base\/basictypes.h\"\n#include \"base\/gfx\/png_encoder.h\"\n#include \"base\/logging.h\"\n#include \"base\/scoped_ptr.h\"\n#include \"third_party\/skia\/include\/core\/SkBitmap.h\"\n\nextern \"C\" {\n#include \"third_party\/libpng\/png.h\"\n}\n\nnamespace {\n\n\/\/ Converts BGRA->RGBA and RGBA->BGRA.\nvoid ConvertBetweenBGRAandRGBA(const unsigned char* input, int pixel_width,\n unsigned char* output) {\n for (int x = 0; x < pixel_width; x++) {\n const unsigned char* pixel_in = &input[x * 4];\n unsigned char* pixel_out = &output[x * 4];\n pixel_out[0] = pixel_in[2];\n pixel_out[1] = pixel_in[1];\n pixel_out[2] = pixel_in[0];\n pixel_out[3] = pixel_in[3];\n }\n}\n\nvoid ConvertRGBAtoRGB(const unsigned char* rgba, int pixel_width,\n unsigned char* rgb) {\n for (int x = 0; x < pixel_width; x++) {\n const unsigned char* pixel_in = &rgba[x * 4];\n unsigned char* pixel_out = &rgb[x * 3];\n pixel_out[0] = pixel_in[0];\n pixel_out[1] = pixel_in[1];\n pixel_out[2] = pixel_in[2];\n }\n}\n\n} \/\/ namespace\n\n\/\/ Encoder --------------------------------------------------------------------\n\/\/\n\/\/ This section of the code is based on nsPNGEncoder.cpp in Mozilla\n\/\/ (Copyright 2005 Google Inc.)\n\nnamespace {\n\n\/\/ Passed around as the io_ptr in the png structs so our callbacks know where\n\/\/ to write data.\nstruct PngEncoderState {\n PngEncoderState(std::vector<unsigned char>* o) : out(o) {}\n std::vector<unsigned char>* out;\n};\n\n\/\/ Called by libpng to flush its internal buffer to ours.\nvoid EncoderWriteCallback(png_structp png, png_bytep data, png_size_t size) {\n PngEncoderState* state = static_cast<PngEncoderState*>(png_get_io_ptr(png));\n DCHECK(state->out);\n\n size_t old_size = state->out->size();\n state->out->resize(old_size + size);\n memcpy(&(*state->out)[old_size], data, size);\n}\n\nvoid ConvertBGRAtoRGB(const unsigned char* bgra, int pixel_width,\n unsigned char* rgb) {\n for (int x = 0; x < pixel_width; x++) {\n const unsigned char* pixel_in = &bgra[x * 4];\n unsigned char* pixel_out = &rgb[x * 3];\n pixel_out[0] = pixel_in[2];\n pixel_out[1] = pixel_in[1];\n pixel_out[2] = pixel_in[0];\n }\n}\n\n\/\/ Automatically destroys the given write structs on destruction to make\n\/\/ cleanup and error handling code cleaner.\nclass PngWriteStructDestroyer {\n public:\n PngWriteStructDestroyer(png_struct** ps, png_info** pi) : ps_(ps), pi_(pi) {\n }\n ~PngWriteStructDestroyer() {\n png_destroy_write_struct(ps_, pi_);\n }\n private:\n png_struct** ps_;\n png_info** pi_;\n\n DISALLOW_EVIL_CONSTRUCTORS(PngWriteStructDestroyer);\n};\n\n} \/\/ namespace\n\n\/\/ static\nbool PNGEncoder::Encode(const unsigned char* input, ColorFormat format,\n int w, int h, int row_byte_width,\n bool discard_transparency,\n std::vector<unsigned char>* output) {\n \/\/ Run to convert an input row into the output row format, NULL means no\n \/\/ conversion is necessary.\n void (*converter)(const unsigned char* in, int w, unsigned char* out) = NULL;\n\n int input_color_components, output_color_components;\n int png_output_color_type;\n switch (format) {\n case FORMAT_RGB:\n input_color_components = 3;\n output_color_components = 3;\n png_output_color_type = PNG_COLOR_TYPE_RGB;\n discard_transparency = false;\n break;\n\n case FORMAT_RGBA:\n input_color_components = 4;\n if (discard_transparency) {\n output_color_components = 3;\n png_output_color_type = PNG_COLOR_TYPE_RGB;\n converter = ConvertRGBAtoRGB;\n } else {\n output_color_components = 4;\n png_output_color_type = PNG_COLOR_TYPE_RGB_ALPHA;\n converter = NULL;\n }\n break;\n\n case FORMAT_BGRA:\n input_color_components = 4;\n if (discard_transparency) {\n output_color_components = 3;\n png_output_color_type = PNG_COLOR_TYPE_RGB;\n converter = ConvertBGRAtoRGB;\n } else {\n output_color_components = 4;\n png_output_color_type = PNG_COLOR_TYPE_RGB_ALPHA;\n converter = ConvertBetweenBGRAandRGBA;\n }\n break;\n\n default:\n NOTREACHED() << \"Unknown pixel format\";\n return false;\n }\n\n \/\/ Row stride should be at least as long as the length of the data.\n DCHECK(input_color_components * w <= row_byte_width);\n\n png_struct* png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING,\n png_voidp_NULL,\n png_error_ptr_NULL,\n png_error_ptr_NULL);\n if (!png_ptr)\n return false;\n png_info* info_ptr = png_create_info_struct(png_ptr);\n if (!info_ptr) {\n png_destroy_write_struct(&png_ptr, NULL);\n return false;\n }\n PngWriteStructDestroyer destroyer(&png_ptr, &info_ptr);\n\n if (setjmp(png_jmpbuf(png_ptr))) {\n \/\/ The destroyer will ensure that the structures are cleaned up in this\n \/\/ case, even though we may get here as a jump from random parts of the\n \/\/ PNG library called below.\n return false;\n }\n\n \/\/ Set our callback for libpng to give us the data.\n PngEncoderState state(output);\n png_set_write_fn(png_ptr, &state, EncoderWriteCallback, NULL);\n\n png_set_IHDR(png_ptr, info_ptr, w, h, 8, png_output_color_type,\n PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_DEFAULT,\n PNG_FILTER_TYPE_DEFAULT);\n png_write_info(png_ptr, info_ptr);\n\n if (!converter) {\n \/\/ No conversion needed, give the data directly to libpng.\n for (int y = 0; y < h; y ++)\n png_write_row(png_ptr,\n const_cast<unsigned char*>(&input[y * row_byte_width]));\n } else {\n \/\/ Needs conversion using a separate buffer.\n unsigned char* row = new unsigned char[w * output_color_components];\n for (int y = 0; y < h; y ++) {\n converter(&input[y * row_byte_width], w, row);\n png_write_row(png_ptr, row);\n }\n delete[] row;\n }\n\n png_write_end(png_ptr, info_ptr);\n return true;\n}\n\n\/\/ static\nbool PNGEncoder::EncodeBGRASkBitmap(const SkBitmap& input,\n bool discard_transparency,\n std::vector<unsigned char>* output) {\n \/\/ This only works with images with four bytes per pixel.\n static const int bbp = 4;\n\n DCHECK(input.empty() || input.bytesPerPixel() == bbp);\n\n \/\/ SkBitmaps are premultiplied, we need to unpremultiply them.\n scoped_array<unsigned char> divided(\n new unsigned char[input.width() * input.height() * bbp]);\n\n SkAutoLockPixels lock_input(input);\n int i = 0;\n for (int y = 0; y < input.height(); y++) {\n uint32* src_row = input.getAddr32(0, y);\n for (int x = 0; x < input.width(); x++) {\n int alpha = SkColorGetA(src_row[x]);\n if (alpha != 0 && alpha != 255) {\n divided[i + 0] = (SkColorGetR(src_row[x]) << 8) \/ alpha;\n divided[i + 1] = (SkColorGetG(src_row[x]) << 8) \/ alpha;\n divided[i + 2] = (SkColorGetB(src_row[x]) << 8) \/ alpha;\n divided[i + 3] = alpha;\n } else {\n divided[i + 0] = SkColorGetR(src_row[x]);\n divided[i + 1] = SkColorGetG(src_row[x]);\n divided[i + 2] = SkColorGetB(src_row[x]);\n divided[i + 3] = SkColorGetA(src_row[x]);\n }\n i += bbp;\n }\n }\n\n return Encode(divided.get(),\n PNGEncoder::FORMAT_RGBA, input.width(), input.height(),\n input.rowBytes(), discard_transparency, output);\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"gm.h\"\n#include \"SkPicture.h\"\n#include \"SkRectShape.h\"\n#include \"SkBlurDrawLooper.h\"\n\nnamespace skiagm {\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nclass ShadowsGM : public GM {\n\npublic:\n SkPath fCirclePath;\n SkPaint fPaint;\n SkRectShape fRectShape;\n ShadowsGM() {\n fCirclePath.addCircle(SkIntToScalar(20), SkIntToScalar(20), SkIntToScalar(10) );\n fPaint.setStrokeWidth(SkIntToScalar(4));\n fPaint.setAntiAlias(true);\n fPaint.setColor(0xFF00FF00);\n fPaint.setStyle(SkPaint::kStroke_Style); \n SkRect rect;\n rect.set(SkIntToScalar(10), SkIntToScalar(10),\n SkIntToScalar(30), SkIntToScalar(30));\n fRectShape.setRect(rect);\n fRectShape.paint().setColor(SK_ColorRED);\n }\n\n virtual ~ShadowsGM() {\n }\n\nprotected:\n virtual SkString onShortName() {\n return SkString(\"shadows\");\n }\n\n virtual SkISize onISize() {\n return make_isize(200, 80);\n }\n\n void drawBG(SkCanvas* canvas) {\n canvas->drawColor(0xFFDDDDDD);\n }\n\n virtual void onDraw(SkCanvas* canvas) {\n this->drawBG(canvas);\n\n SkBlurDrawLooper* shadowLoopers[5];\n shadowLoopers[0] =\n new SkBlurDrawLooper (SkIntToScalar(10), SkIntToScalar(5),\n SkIntToScalar(10), 0xFF0000FF,\n SkBlurDrawLooper::kIgnoreTransform_BlurFlag |\n SkBlurDrawLooper::kOverrideColor_BlurFlag |\n SkBlurDrawLooper::kHighQuality_BlurFlag );\n SkAutoUnref aurL0(shadowLoopers[0]);\n shadowLoopers[1] =\n new SkBlurDrawLooper (SkIntToScalar(10), SkIntToScalar(5),\n SkIntToScalar(10), 0xFF0000FF,\n SkBlurDrawLooper::kIgnoreTransform_BlurFlag |\n SkBlurDrawLooper::kOverrideColor_BlurFlag );\n SkAutoUnref aurL1(shadowLoopers[1]);\n shadowLoopers[2] =\n new SkBlurDrawLooper (SkIntToScalar(5), SkIntToScalar(5),\n SkIntToScalar(10), 0xFF000000,\n SkBlurDrawLooper::kIgnoreTransform_BlurFlag |\n SkBlurDrawLooper::kHighQuality_BlurFlag );\n SkAutoUnref aurL2(shadowLoopers[2]);\n shadowLoopers[3] =\n new SkBlurDrawLooper (SkIntToScalar(5), SkIntToScalar(-5),\n SkIntToScalar(-10), 0x7FFF0000,\n SkBlurDrawLooper::kIgnoreTransform_BlurFlag |\n SkBlurDrawLooper::kOverrideColor_BlurFlag |\n SkBlurDrawLooper::kHighQuality_BlurFlag );\n SkAutoUnref aurL3(shadowLoopers[3]);\n shadowLoopers[4] =\n new SkBlurDrawLooper (SkIntToScalar(0), SkIntToScalar(5),\n SkIntToScalar(5), 0xFF000000,\n SkBlurDrawLooper::kIgnoreTransform_BlurFlag |\n SkBlurDrawLooper::kOverrideColor_BlurFlag |\n SkBlurDrawLooper::kHighQuality_BlurFlag );\n SkAutoUnref aurL4(shadowLoopers[4]);\n\n for (int looper = 0; looper < 5; looper ++)\n {\n fRectShape.paint().setLooper(shadowLoopers[looper]);\n canvas->resetMatrix();\n canvas->translate(SkIntToScalar(looper*40), SkIntToScalar(0));\n canvas->drawShape(&fRectShape);\n fPaint.setLooper(shadowLoopers[looper]); \n canvas->translate(SkIntToScalar(0), SkIntToScalar(40));\n canvas->drawPath(fCirclePath, fPaint);\n }\n}\n\nprivate:\n typedef GM INHERITED;\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstatic GM* MyFactory(void*) { return new ShadowsGM; }\nstatic GMRegistry reg(MyFactory);\n\n}\n<commit_msg>retool without shapes, which are broken\/experimental<commit_after>#include \"gm.h\"\n#include \"SkBlurDrawLooper.h\"\n\nnamespace skiagm {\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstatic void setup(SkPaint* paint, SkColor c, SkScalar strokeWidth) {\n paint->setColor(c);\n if (strokeWidth < 0) {\n paint->setStyle(SkPaint::kFill_Style);\n } else {\n paint->setStyle(SkPaint::kStroke_Style);\n paint->setStrokeWidth(strokeWidth);\n }\n}\n\nclass ShadowsGM : public GM {\npublic:\n SkPath fCirclePath;\n SkRect fRect;\n\n ShadowsGM() {\n fCirclePath.addCircle(SkIntToScalar(20), SkIntToScalar(20), SkIntToScalar(10) );\n fRect.set(SkIntToScalar(10), SkIntToScalar(10),\n SkIntToScalar(30), SkIntToScalar(30));\n }\n\nprotected:\n virtual SkString onShortName() {\n return SkString(\"shadows\");\n }\n\n virtual SkISize onISize() {\n return make_isize(200, 80);\n }\n\n void drawBG(SkCanvas* canvas) {\n canvas->drawColor(0xFFDDDDDD);\n }\n\n virtual void onDraw(SkCanvas* canvas) {\n this->drawBG(canvas);\n\n SkBlurDrawLooper* shadowLoopers[5];\n shadowLoopers[0] =\n new SkBlurDrawLooper (SkIntToScalar(10), SkIntToScalar(5),\n SkIntToScalar(10), 0xFF0000FF,\n SkBlurDrawLooper::kIgnoreTransform_BlurFlag |\n SkBlurDrawLooper::kOverrideColor_BlurFlag |\n SkBlurDrawLooper::kHighQuality_BlurFlag );\n SkAutoUnref aurL0(shadowLoopers[0]);\n shadowLoopers[1] =\n new SkBlurDrawLooper (SkIntToScalar(10), SkIntToScalar(5),\n SkIntToScalar(10), 0xFF0000FF,\n SkBlurDrawLooper::kIgnoreTransform_BlurFlag |\n SkBlurDrawLooper::kOverrideColor_BlurFlag );\n SkAutoUnref aurL1(shadowLoopers[1]);\n shadowLoopers[2] =\n new SkBlurDrawLooper (SkIntToScalar(5), SkIntToScalar(5),\n SkIntToScalar(10), 0xFF000000,\n SkBlurDrawLooper::kIgnoreTransform_BlurFlag |\n SkBlurDrawLooper::kHighQuality_BlurFlag );\n SkAutoUnref aurL2(shadowLoopers[2]);\n shadowLoopers[3] =\n new SkBlurDrawLooper (SkIntToScalar(5), SkIntToScalar(-5),\n SkIntToScalar(-10), 0x7FFF0000,\n SkBlurDrawLooper::kIgnoreTransform_BlurFlag |\n SkBlurDrawLooper::kOverrideColor_BlurFlag |\n SkBlurDrawLooper::kHighQuality_BlurFlag );\n SkAutoUnref aurL3(shadowLoopers[3]);\n shadowLoopers[4] =\n new SkBlurDrawLooper (SkIntToScalar(0), SkIntToScalar(5),\n SkIntToScalar(5), 0xFF000000,\n SkBlurDrawLooper::kIgnoreTransform_BlurFlag |\n SkBlurDrawLooper::kOverrideColor_BlurFlag |\n SkBlurDrawLooper::kHighQuality_BlurFlag );\n SkAutoUnref aurL4(shadowLoopers[4]);\n\n static const struct {\n SkColor fColor;\n SkScalar fStrokeWidth;\n } gRec[] = {\n { SK_ColorRED, -SK_Scalar1 },\n { SK_ColorGREEN, SkIntToScalar(4) },\n };\n\n SkPaint paint;\n paint.setAntiAlias(true);\n for (size_t i = 0; i < SK_ARRAY_COUNT(shadowLoopers); ++i) {\n SkAutoCanvasRestore acr(canvas, true);\n\n paint.setLooper(shadowLoopers[i]);\n\n canvas->translate(SkIntToScalar(i*40), SkIntToScalar(0));\n setup(&paint, gRec[0].fColor, gRec[0].fStrokeWidth);\n canvas->drawRect(fRect, paint);\n\n canvas->translate(SkIntToScalar(0), SkIntToScalar(40));\n setup(&paint, gRec[1].fColor, gRec[1].fStrokeWidth);\n canvas->drawPath(fCirclePath, paint);\n }\n}\n\nprivate:\n typedef GM INHERITED;\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstatic GM* MyFactory(void*) { return new ShadowsGM; }\nstatic GMRegistry reg(MyFactory);\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ @(#)root\/cont:$Name: $:$Id: TObjectRef.cxx,v 1.1 2001\/10\/01 10:29:08 brun Exp $\n\/\/ Author: Rene Brun 28\/09\/2001\n\n\/*************************************************************************\n * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *\n * All rights reserved. *\n * *\n * For the licensing terms see $ROOTSYS\/LICENSE. *\n * For the list of contributors see $ROOTSYS\/README\/CREDITS. *\n *************************************************************************\/\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ \/\/\n\/\/ TObjectRef \/\/\n\/\/ \/\/\n\/\/ Persistent Reference link to a TObject \/\/\n\/\/ \/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"TObjectRef.h\"\n#include \"TROOT.h\"\n#include \"TProcessID.h\"\n#include \"TFile.h\"\n#include \"TObjArray.h\"\n#include \"TSystem.h\"\n\nClassImp(TObjectRef)\n\n\/\/ A TObjectRef is a lightweight object pointing to any TObject.\n\/\/ This object can be used instead of normal C++ pointers in case\n\/\/ - the referenced object R and the pointer P are not written to the same file\n\/\/ - P is read before R\n\/\/ - R and P are written to different Tree branches\n\/\/\n\/\/ When a top level object (eg Event *event) is a tree\/graph of many objects,\n\/\/ the normal ROOT Streaming mechanism ensures that only one copy of each object\n\/\/ in the tree\/graph is written to the output buffer to avoid circular\n\/\/ dependencies.\n\/\/ However if the object event is split into several files or into several\n\/\/ branches of one or more Trees, normal C++ pointers cannot be used because\n\/\/ each I\/O operation will write the referenced objects.\n\/\/ When a TObjectRef is used to point to a TObject *robj. \n\/\/For example in a class with\n\/\/ TObjectRef fRef;\n\/\/ one can do:\n\/\/ fRef = robj; \/\/to set the pointer\n\/\/ this TObjectRef and robj can be written with two different I\/O calls\n\/\/ in the same or different files, in the same or different branches of a Tree.\n\/\/ If the TObjectRef is read and the referenced object has not yet been read,\n\/\/ the TObjectRef will return a null pointer. As soon as the referenced object\n\/\/ will be read, the TObjectRef will point to it.\n\/\/\n\/\/ TObjectRef also supports the complex situation where a TFile is updated\n\/\/ multiple times on the same machine or a different machine.\n\/\/\n\/\/ How does it work\n\/\/ ----------------\n\/\/ A TObjectRef is itself a TObject with an additional transient pointer fPID.\n\/\/ When the statement fRef = robj is executed, the fRef::fUniqueID is set\n\/\/ to the value \"obj-gSystem\". This uid is in general a small integer, even\n\/\/ on a 64 bit system.\n\/\/ After having set fRef, one can immediatly return the value of robj\n\/\/ with \"gSystem + uid\" using fRef.GetObject() or the dereferencing operator ->.\n\/\/\n\/\/ When the TObjectRef is written, the process id number pidf (see TProcessID)\n\/\/ is written as well as the uid.\n\/\/ When the TObjectRef is read, its pointer fPID is set to the value\n\/\/ stored in the TObjArray of TFile::fProcessIDs (fProcessIDs[pidf]).\n\/\/\n\/\/ When a referenced object robj is written, TObject::Streamer writes\n\/\/ in addition to the standard (fBits,fUniqueID) the pair uid,pidf.\n\/\/ When this robj is read by TObject::Streamer, the pair uid,pidf is read.\n\/\/ At this point, robj is entered into the TExmap of the TProcessID\n\/\/ corresponding to pidf. \n\/\/\n\/\/ Once the referenced object robj is in memory, TObjectRef::GetObject will \n\/\/ store the object pointer robj-gSystem into the fUniqueID such that\n\/\/ the next access to the pointer will be fast (no need to search in\n\/\/ the TExMap of the TProcessID anymore).\n\/\/\n\/\/ Implicit use of TObjectRef in ROOT collections\n\/\/ ----------------------------------------------\n\/\/ The TSeqCollection (TList, TObjArray, etc) have been modified with\n\/\/ additional member functions AddRef, AddRefAt, etc to create automatically\n\/\/ a TObjectRef when doing, eg:\n\/\/ myArray->AddRef(robj);\n\/\/\n\/\/ Example:\n\/\/ Suppose a TObjArray *mytracks containing a list of Track objects\n\/\/ Suppose a TObjArray *pions containing pointers to the pion tracks in mytracks.\n\/\/ This list is created with statements like: pions->AddRef(track);\n\/\/ Suppose a TObjArray *muons containing pointers to the muon tracks in mytracks.\n\/\/ The 3 arrays mytracks,pions and muons may be written separately.\n\/\/\n\n\/\/______________________________________________________________________________\nTObjectRef::TObjectRef(TObject *obj)\n{\n \/\/ TObjectRef copy ctor.\n\n *this = obj;\n fPID = 0;\n}\n\n\/\/______________________________________________________________________________\nTObjectRef::TObjectRef(const TObjectRef &ref)\n{\n}\n\n\/\/______________________________________________________________________________\nvoid TObjectRef::operator=(TObject *obj)\n{\n \/\/ TObjectRef assignment operator.\n\n UInt_t uid;\n if (obj) {\n obj->SetBit(kIsReferenced);\n uid = (char*)obj - (char*)gSystem;\n } else {\n uid = 0;\n }\n SetUniqueID(uid);\n}\n\n\/\/______________________________________________________________________________\nTObject *TObjectRef::GetObject() \n{\n \/\/ Return a pointer to the referenced object.\n\n TObject *obj = 0;\n Long_t uid = (Long_t)GetUniqueID();\n if (uid == 0) return obj;\n if (!TestBit(1)) return (TObject*)(uid + (char*)gSystem);\n if (!fPID) return 0;\n obj = fPID->GetObjectWithID(uid);\n if (obj) {\n ResetBit(1);\n uid = (char*)obj - (char*)gSystem;\n SetUniqueID((UInt_t)uid);\n }\n return obj;\n}\n\n\/\/______________________________________________________________________________\nvoid TObjectRef::ReadRef(TObject *obj, TBuffer &R__b, TFile *file)\n{\n\/\/ static function\n\n Long_t uid;\n Int_t pidf = 0;\n R__b >> uid; \n R__b >> pidf;\n \n TProcessID *pid = TProcessID::ReadProcessID(pidf,file);\n \n if (pid) pid->PutObjectWithID(uid,obj);\n}\n\n\/\/______________________________________________________________________________\nvoid TObjectRef::SaveRef(TObject *obj, TBuffer &R__b, TFile *file)\n{\n\/\/ static function\n\n Long_t uid = (char*)obj - (char*)gSystem;\n Int_t pidf = 0;\n if (file) {\n pidf = file->GetProcessCount();\n }\n R__b << uid;\n R__b << pidf;\n}\n\n\/\/______________________________________________________________________________\nvoid TObjectRef::Streamer(TBuffer &R__b)\n{\n \/\/ Stream an object of class TObjectRef.\n\n Long_t uid;\n Int_t pidf;\n if (R__b.IsReading()) {\n R__b >> pidf;\n R__b >> uid;\n SetBit(1,1);\n SetUniqueID((UInt_t)uid);\n fPID = TProcessID::ReadProcessID(pidf,gFile);\n } else {\n uid = (Long_t)GetUniqueID();\n if (gFile) pidf = gFile->GetProcessCount();\n else pidf = 0;\n R__b << pidf;\n R__b << uid;\n }\n}\n<commit_msg>When a referenced object is written, the TFile bit kHasReferences is set.<commit_after>\/\/ @(#)root\/cont:$Name: $:$Id: TObjectRef.cxx,v 1.2 2001\/10\/02 08:16:23 brun Exp $\n\/\/ Author: Rene Brun 28\/09\/2001\n\n\/*************************************************************************\n * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *\n * All rights reserved. *\n * *\n * For the licensing terms see $ROOTSYS\/LICENSE. *\n * For the list of contributors see $ROOTSYS\/README\/CREDITS. *\n *************************************************************************\/\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ \/\/\n\/\/ TObjectRef \/\/\n\/\/ \/\/\n\/\/ Persistent Reference link to a TObject \/\/\n\/\/ \/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"TObjectRef.h\"\n#include \"TROOT.h\"\n#include \"TProcessID.h\"\n#include \"TFile.h\"\n#include \"TObjArray.h\"\n#include \"TSystem.h\"\n\nClassImp(TObjectRef)\n\n\/\/ A TObjectRef is a lightweight object pointing to any TObject.\n\/\/ This object can be used instead of normal C++ pointers in case\n\/\/ - the referenced object R and the pointer P are not written to the same file\n\/\/ - P is read before R\n\/\/ - R and P are written to different Tree branches\n\/\/\n\/\/ When a top level object (eg Event *event) is a tree\/graph of many objects,\n\/\/ the normal ROOT Streaming mechanism ensures that only one copy of each object\n\/\/ in the tree\/graph is written to the output buffer to avoid circular\n\/\/ dependencies.\n\/\/ However if the object event is split into several files or into several\n\/\/ branches of one or more Trees, normal C++ pointers cannot be used because\n\/\/ each I\/O operation will write the referenced objects.\n\/\/ When a TObjectRef is used to point to a TObject *robj. \n\/\/For example in a class with\n\/\/ TObjectRef fRef;\n\/\/ one can do:\n\/\/ fRef = robj; \/\/to set the pointer\n\/\/ this TObjectRef and robj can be written with two different I\/O calls\n\/\/ in the same or different files, in the same or different branches of a Tree.\n\/\/ If the TObjectRef is read and the referenced object has not yet been read,\n\/\/ the TObjectRef will return a null pointer. As soon as the referenced object\n\/\/ will be read, the TObjectRef will point to it.\n\/\/\n\/\/ TObjectRef also supports the complex situation where a TFile is updated\n\/\/ multiple times on the same machine or a different machine.\n\/\/\n\/\/ How does it work\n\/\/ ----------------\n\/\/ A TObjectRef is itself a TObject with an additional transient pointer fPID.\n\/\/ When the statement fRef = robj is executed, the fRef::fUniqueID is set\n\/\/ to the value \"obj-gSystem\". This uid is in general a small integer, even\n\/\/ on a 64 bit system.\n\/\/ After having set fRef, one can immediatly return the value of robj\n\/\/ with \"gSystem + uid\" using fRef.GetObject() or the dereferencing operator ->.\n\/\/\n\/\/ When the TObjectRef is written, the process id number pidf (see TProcessID)\n\/\/ is written as well as the uid.\n\/\/ When the TObjectRef is read, its pointer fPID is set to the value\n\/\/ stored in the TObjArray of TFile::fProcessIDs (fProcessIDs[pidf]).\n\/\/\n\/\/ When a referenced object robj is written, TObject::Streamer writes\n\/\/ in addition to the standard (fBits,fUniqueID) the pair uid,pidf.\n\/\/ When this robj is read by TObject::Streamer, the pair uid,pidf is read.\n\/\/ At this point, robj is entered into the TExmap of the TProcessID\n\/\/ corresponding to pidf. \n\/\/\n\/\/ Once the referenced object robj is in memory, TObjectRef::GetObject will \n\/\/ store the object pointer robj-gSystem into the fUniqueID such that\n\/\/ the next access to the pointer will be fast (no need to search in\n\/\/ the TExMap of the TProcessID anymore).\n\/\/\n\/\/ WARNING: If MyClass is the class of the referenced object, The TObject\n\/\/ part of MyClass must be Streamed. One should not\n\/\/ call MyClass::Class()->IgnoreTObjectStreamer()\n\/\/\n\/\/ Implicit use of TObjectRef in ROOT collections\n\/\/ ----------------------------------------------\n\/\/ The TSeqCollection (TList, TObjArray, etc) have been modified with\n\/\/ additional member functions AddRef, AddRefAt, etc to create automatically\n\/\/ a TObjectRef when doing, eg:\n\/\/ myArray->AddRef(robj);\n\/\/\n\/\/ Example:\n\/\/ Suppose a TObjArray *mytracks containing a list of Track objects\n\/\/ Suppose a TObjArray *pions containing pointers to the pion tracks in mytracks.\n\/\/ This list is created with statements like: pions->AddRef(track);\n\/\/ Suppose a TObjArray *muons containing pointers to the muon tracks in mytracks.\n\/\/ The 3 arrays mytracks,pions and muons may be written separately.\n\/\/\n\n\/\/______________________________________________________________________________\nTObjectRef::TObjectRef(TObject *obj)\n{\n \/\/ TObjectRef copy ctor.\n\n *this = obj;\n fPID = 0;\n}\n\n\/\/______________________________________________________________________________\nTObjectRef::TObjectRef(const TObjectRef &ref)\n{\n}\n\n\/\/______________________________________________________________________________\nvoid TObjectRef::operator=(TObject *obj)\n{\n \/\/ TObjectRef assignment operator.\n\n UInt_t uid;\n if (obj) {\n if (obj->IsA()->CanIgnoreTObjectStreamer()) {\n Error(\"operator= \",\"Class: %s IgnoreTObjectStreamer. Cannot reference object\",obj->ClassName());\n return;\n }\n obj->SetBit(kIsReferenced);\n uid = (char*)obj - (char*)gSystem;\n } else {\n uid = 0;\n }\n SetUniqueID(uid);\n}\n\n\/\/______________________________________________________________________________\nTObject *TObjectRef::GetObject() \n{\n \/\/ Return a pointer to the referenced object.\n\n TObject *obj = 0;\n Long_t uid = (Long_t)GetUniqueID();\n if (uid == 0) return obj;\n if (!TestBit(1)) return (TObject*)(uid + (char*)gSystem);\n if (!fPID) return 0;\n obj = fPID->GetObjectWithID(uid);\n if (obj) {\n ResetBit(1);\n uid = (char*)obj - (char*)gSystem;\n SetUniqueID((UInt_t)uid);\n }\n return obj;\n}\n\n\/\/______________________________________________________________________________\nvoid TObjectRef::ReadRef(TObject *obj, TBuffer &R__b, TFile *file)\n{\n\/\/ static function\n\n Long_t uid;\n Int_t pidf = 0;\n R__b >> uid; \n R__b >> pidf;\n \n TProcessID *pid = TProcessID::ReadProcessID(pidf,file);\n \n if (pid) pid->PutObjectWithID(uid,obj);\n}\n\n\/\/______________________________________________________________________________\nvoid TObjectRef::SaveRef(TObject *obj, TBuffer &R__b, TFile *file)\n{\n\/\/ static function\n\n Long_t uid = (char*)obj - (char*)gSystem;\n Int_t pidf = 0;\n if (file) {\n pidf = file->GetProcessCount();\n file->SetBit(TFile::kHasReferences);\n }\n R__b << uid;\n R__b << pidf;\n}\n\n\/\/______________________________________________________________________________\nvoid TObjectRef::Streamer(TBuffer &R__b)\n{\n \/\/ Stream an object of class TObjectRef.\n\n Long_t uid;\n Int_t pidf;\n if (R__b.IsReading()) {\n R__b >> pidf;\n R__b >> uid;\n SetBit(1,1);\n SetUniqueID((UInt_t)uid);\n fPID = TProcessID::ReadProcessID(pidf,gFile);\n } else {\n pidf = 0;\n uid = (Long_t)GetUniqueID();\n if (gFile) {\n pidf = gFile->GetProcessCount();\n gFile->SetBit(TFile::kHasReferences);\n }\n R__b << pidf;\n R__b << uid;\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n-----------------------------------------------------------------------------\nThis source file is part of OGRE\n(Object-oriented Graphics Rendering Engine)\nFor the latest info, see http:\/\/www.ogre3d.org\/\n\nCopyright (c) 2000-2009 Torus Knot Software Ltd\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n-----------------------------------------------------------------------------\n*\/\n\n#include \"OgreCgPlugin.h\"\n#include \"OgreRoot.h\"\n#include \"OgreHighLevelGpuProgramManager.h\"\n#include \"OgreCgFxScriptLoader.h\"\n\nnamespace Ogre \n{\n\tconst String sPluginName = \"Cg Program Manager\";\n\t\/\/---------------------------------------------------------------------\n\tCgPlugin::CgPlugin()\n\t\t:mCgProgramFactory(0)\n\t{\n\n\t}\n\t\/\/---------------------------------------------------------------------\n\tconst String& CgPlugin::getName() const\n\t{\n\t\treturn sPluginName;\n\t}\n\t\/\/---------------------------------------------------------------------\n\tvoid CgPlugin::install()\n\t{\n\t\t\/\/ Create new factory\n\t\tmCgProgramFactory = OGRE_NEW CgProgramFactory();\n\t\t\/\/ Register\n\t\tHighLevelGpuProgramManager::getSingleton().addFactory(mCgProgramFactory);\n\n\t\tOGRE_NEW CgFxScriptLoader();\n\t}\n\t\/\/---------------------------------------------------------------------\n\tvoid CgPlugin::initialise()\n\t{\n\t\t\/\/ nothing to do\n\t}\n\t\/\/---------------------------------------------------------------------\n\tvoid CgPlugin::shutdown()\n\t{\n\t\t\/\/ nothing to do\n\t}\n\t\/\/---------------------------------------------------------------------\n\tvoid CgPlugin::uninstall()\n\t{\n if (mCgProgramFactory)\n {\n\t\t\tOGRE_DELETE CgFxScriptLoader::getSingletonPtr(); \n\n \/\/ Remove from manager safely\n if (HighLevelGpuProgramManager::getSingletonPtr())\n HighLevelGpuProgramManager::getSingleton().removeFactory(mCgProgramFactory);\n\t\t OGRE_DELETE mCgProgramFactory;\n\t\t mCgProgramFactory = 0;\n }\n\t}\n\n\n}\n<commit_msg>Fixed so the CG plugin will not register a factory when the GLES2 render system is the active render system.<commit_after>\/*\n-----------------------------------------------------------------------------\nThis source file is part of OGRE\n(Object-oriented Graphics Rendering Engine)\nFor the latest info, see http:\/\/www.ogre3d.org\/\n\nCopyright (c) 2000-2009 Torus Knot Software Ltd\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n-----------------------------------------------------------------------------\n*\/\n\n#include \"OgreCgPlugin.h\"\n#include \"OgreRoot.h\"\n#include \"OgreHighLevelGpuProgramManager.h\"\n#include \"OgreCgFxScriptLoader.h\"\n\nnamespace Ogre \n{\n\tconst String sPluginName = \"Cg Program Manager\";\n\t\/\/---------------------------------------------------------------------\n\tCgPlugin::CgPlugin()\n\t\t:mCgProgramFactory(0)\n\t{\n\n\t}\n\t\/\/---------------------------------------------------------------------\n\tconst String& CgPlugin::getName() const\n\t{\n\t\treturn sPluginName;\n\t}\n\t\/\/---------------------------------------------------------------------\n\tvoid CgPlugin::install()\n\t{\n\t}\n\t\/\/---------------------------------------------------------------------\n\tvoid CgPlugin::initialise()\n\t{\n \/\/ check for gles2 by the glsles factory (this plugin is not supported on embedded systems for now)\n if (HighLevelGpuProgramManager::getSingleton().isLanguageSupported(\"glsles\") == false)\n {\n \/\/ Create new factory\n mCgProgramFactory = OGRE_NEW CgProgramFactory();\n\n \/\/ Register\n HighLevelGpuProgramManager::getSingleton().addFactory(mCgProgramFactory);\n\n OGRE_NEW CgFxScriptLoader();\n }\n\t}\n\t\/\/---------------------------------------------------------------------\n\tvoid CgPlugin::shutdown()\n\t{\n\t\t\/\/ nothing to do\n\t}\n\t\/\/---------------------------------------------------------------------\n\tvoid CgPlugin::uninstall()\n\t{\n if (mCgProgramFactory)\n {\n\t\t\tOGRE_DELETE CgFxScriptLoader::getSingletonPtr(); \n\n \/\/ Remove from manager safely\n if (HighLevelGpuProgramManager::getSingletonPtr())\n HighLevelGpuProgramManager::getSingleton().removeFactory(mCgProgramFactory);\n\t\t OGRE_DELETE mCgProgramFactory;\n\t\t mCgProgramFactory = 0;\n }\n\t}\n}\n<|endoftext|>"} {"text":"<commit_before>#ifndef GAME_CONFIG_HPP\n#define GAME_CONFIG_HPP\n\n\/*\n * Global config values for easy tweaking and changing\n *\/\n\n\/\/ Maximum orbs spawned on screen\nstatic const int MAX_ORBS = 2;\n\n\/\/ variables for borders that restricts movement\nstatic const float RING_INNER = 100.f;\nstatic const float RING_OUTER = 300.f;\n\n\/\/Logic variables for world height and width\nstatic const int WORLD_WIDTH = 1600;\nstatic const int WORLD_HEIGHT = 1200;\n\n\/\/screen width and height\nstatic const int WIDTH = 800;\nstatic const int HEIGHT = 600;\n\nstatic const float MAX_SPEED = 200.f;\n\nstatic const bool DEBUG = true;\nstatic const int DEBUG_START_LEVEL = 1; \/\/ index of first level\n\n#endif\n<commit_msg>Start at level 0<commit_after>#ifndef GAME_CONFIG_HPP\n#define GAME_CONFIG_HPP\n\n\/*\n * Global config values for easy tweaking and changing\n *\/\n\n\/\/ Maximum orbs spawned on screen\nstatic const int MAX_ORBS = 2;\n\n\/\/ variables for borders that restricts movement\nstatic const float RING_INNER = 100.f;\nstatic const float RING_OUTER = 300.f;\n\n\/\/Logic variables for world height and width\nstatic const int WORLD_WIDTH = 1600;\nstatic const int WORLD_HEIGHT = 1200;\n\n\/\/screen width and height\nstatic const int WIDTH = 800;\nstatic const int HEIGHT = 600;\n\nstatic const float MAX_SPEED = 200.f;\n\nstatic const bool DEBUG = true;\nstatic const int DEBUG_START_LEVEL = 0; \/\/ index of first level\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>#pragma once\n\nstruct ScreenMessage {\n\tenum Action {Push, Pop, Clear}\n\n\tstatic ScreenMessage Push(int id) {\n\t\taction = Push;\n\t\tscreen = id;\n\t}\n\n\tstatic ScreenMessage Pop() {\n\t\taction = Pop;\n\t\tscreen = -1;\n\t}\n\n\tstatic ScreenMessage Clear() {\n\t\taction = Clear;\n\t\tscreen = -1;\n\t}\n\n\tint screen;\n\tAction action;\n};\n<commit_msg>Fix syntax.<commit_after>#pragma once\n\nstruct ScreenMessage {\n\tenum Action {Push, Pop, Clear};\n\n\tstatic ScreenMessage Push(int id) {\n\t\taction = Push;\n\t\tscreen = id;\n\t}\n\n\tstatic ScreenMessage Pop() {\n\t\taction = Pop;\n\t\tscreen = -1;\n\t}\n\n\tstatic ScreenMessage Clear() {\n\t\taction = Clear;\n\t\tscreen = -1;\n\t}\n\n\tint screen;\n\tAction action;\n};\n<|endoftext|>"} {"text":"<commit_before>#include \"coroutines\/io_events.h\"\n#include \"coroutines\/io_channel.h\"\n\nextern void dbg(const char *fmt, ...);\n\/\/#define dbg(...)\n\n#ifdef _WIN32\n\n#pragma comment(lib, \"Ws2_32.lib\")\n#define sys_socket(x,y,z,port)\t::socket( x, y, z )\n#define sys_connect(id,addr,sz) ::connect( id, (const sockaddr*) addr, sz )\n#define sys_send ::send\n#define sys_recv ::recv\n#define sys_errno ::WSAGetLastError()\n#define sys_close ::closesocket\n#define sys_bind(id,addr,sz) ::bind(id, (const sockaddr *) addr, sz )\n#define sys_accept(id,addr,sz) ::accept( id, (sockaddr*) addr, sz )\n#define sys_listen ::listen\n\n#define SYS_ERR_WOULD_BLOCK WSAEWOULDBLOCK\n#define SYS_ERR_CONN_IN_PROGRESS WSAEWOULDBLOCK\n\n#else\n\n#include <sys\/types.h>\n#include <sys\/uio.h>\n#include <unistd.h>\n#include <fcntl.h>\n#include <errno.h>\n#include <arpa\/inet.h>\n\n#define sys_socket(x,y,z,port) ::socket( x, y, z )\n#define sys_connect(id,addr,sz) ::connect( id, (const sockaddr*) addr, sz )\n#define sys_send ::send\n#define sys_recv ::recv\n#define sys_errno errno\n#define sys_close ::close\n#define sys_bind(id,addr,sz) ::bind(id, (const sockaddr *) addr, sz )\n#define sys_accept(id,addr,sz) ::accept( id, (sockaddr*) addr, (socklen_t*)sz )\n#define sys_listen ::listen\n\n#define SYS_ERR_WOULD_BLOCK EWOULDBLOCK\n#define SYS_ERR_CONN_IN_PROGRESS EINPROGRESS\n\n#endif\n\n\nnamespace Coroutines {\n\n bool CIOChannel::setNonBlocking() {\n \/\/ set non-blocking\n#if defined(O_NONBLOCK)\n int flags = fcntl(fd, F_GETFL, 0);\n if (flags == -1)\n flags = 0;\n auto rc = fcntl(fd, F_SETFL, flags | O_NONBLOCK);\n#else\n u_long iMode = 1;\n auto rc = ioctlsocket(fd, FIONBIO, &iMode);\n#endif\n if (rc != 0)\n dbg(\"Failed to set socket %d as non-blocking\\n\", fd);\n return rc == 0;\n }\n\n \/\/ ---------------------------------------------------------------------------\n int CIOChannel::getSocketError() {\n \/\/ Confirm we are really connected by checking the socket error\n int sock_err = 0;\n socklen_t sock_err_sz = sizeof(sock_err);\n int rc = getsockopt(fd, SOL_SOCKET, SO_ERROR, (char*)&sock_err, &sock_err_sz);\n return sock_err;\n }\n\n\n \/\/ ---------------------------------------------------------------------------\n bool CIOChannel::listen(const TNetAddress& serving_addr) {\n if (isValid())\n return false;\n\n auto new_fd = sys_socket(AF_INET, SOCK_STREAM, 0, 0);\n if (new_fd < 0)\n return false;\n fd = new_fd;\n\n if (sys_bind(fd, &serving_addr, sizeof(serving_addr)) < 0)\n return false;\n\n if (sys_listen(fd, 5) < 0)\n return false;\n\n setNonBlocking();\n\n return true;\n }\n\n \/\/ ---------------------------------------------------------------------------\n CIOChannel CIOChannel::accept() {\n dbg(\"FD %d is accepting connections\\n\", fd);\n\n while (isValid()) {\n TNetAddress remote_client_addr;\n int remote_addr_sz = sizeof(remote_client_addr);\n int rc = sys_accept(fd, &remote_client_addr.addr, &remote_addr_sz);\n if (rc < 0) {\n int sys_err = sys_errno;\n if (sys_err == SYS_ERR_WOULD_BLOCK) {\n dbg(\"FD %d goes to sleep waiting for a connection\\n\", fd);\n TWatchedEvent we(fd, EVT_SOCKET_IO_CAN_READ);\n wait(&we, 1);\n continue;\n }\n dbg(\"FD %d accept failed (%08x vs %08x)\\n\", fd, sys_err, SYS_ERR_WOULD_BLOCK);\n \/\/ Other types of errors\n return CIOChannel();\n }\n dbg(\"FD %d has accepted new client %d\\n\", fd, rc);\n CIOChannel new_client;\n new_client.fd = rc;\n new_client.setNonBlocking();\n return new_client;\n }\n return CIOChannel();\n }\n\n \/\/ ---------------------------------------------------------------------------\n bool CIOChannel::connect(const TNetAddress &remote_server, int timeout_sec) {\n\n auto new_fd = sys_socket(AF_INET, SOCK_STREAM, 0, 0);\n if (new_fd < 0)\n return false;\n fd = new_fd;\n\n setNonBlocking();\n\n if (0) {\n dbg(\"SYS_ERR_WOULD_BLOCK = %08x\\n\", SYS_ERR_WOULD_BLOCK);\n dbg(\"SYS_ERR_CONN_IN_PROGRESS = %08x\\n\", SYS_ERR_CONN_IN_PROGRESS);\n dbg(\"SYS_ERR_CONN_REFUSED = %08x\\n\", ECONNREFUSED);\n }\n\n dbg(\"FD %d starting to connect\\n\", fd);\n\n while (isValid()) {\n int rc = sys_connect(fd, &remote_server.addr, sizeof(remote_server));\n if (rc < 0) {\n int sys_err = sys_errno;\n if (sys_err == SYS_ERR_CONN_IN_PROGRESS) {\n TWatchedEvent we(fd, EVT_SOCKET_IO_CAN_WRITE);\n int n = wait(&we, 1);\n if (n == 0) {\n\n \/\/ Confirm we are really connected by checking the socket error\n int sock_err = getSocketError();\n \n \/\/ All ok, no errors\n if (sock_err == 0) \n break;\n\n \/\/ The expected error in this case is Conn Refused when there is no server\n \/\/ in the remote address. Other erros, I prefer to report them\n if (sock_err != ECONNREFUSED) \n dbg(\"connect.failed getsockopt( %d ) (err=%08x)\\n\", fd, sock_err);\n }\n }\n dbg(\"FD %d connect rc = %d (%08x vs %08x)\\n\", fd, rc, sys_err, SYS_ERR_CONN_IN_PROGRESS);\n }\n else {\n \/\/ Connected without waiting\n break;\n }\n }\n\n \/\/ If we are not valid, the socket we created should be destroyed.\n if (!isValid())\n close();\n else \n dbg(\"FD %d connected\\n\", fd);\n return isValid();\n }\n\n \/\/ ---------------------------------------------------------------------------\n void CIOChannel::close() {\n if (isValid()) {\n dbg(\"FD %d closed\\n\", fd);\n sys_close(fd);\n fd = invalid_socket_id;\n\n \/\/ Remove from entries...\n }\n }\n\n \/\/ ---------------------------------------------------------------------------\n bool CIOChannel::recv(void* dest_buffer, size_t bytes_to_read) const {\n assert(bytes_to_read > 0);\n size_t total_bytes_read = 0;\n while (isValid()) {\n assert(bytes_to_read > total_bytes_read);\n auto new_bytes_read = sys_recv(fd, (char*)dest_buffer, (int)(bytes_to_read - total_bytes_read), 0);\n if (new_bytes_read == -1) {\n int err = sys_errno;\n if (err == SYS_ERR_WOULD_BLOCK) {\n TWatchedEvent we(fd, EVT_SOCKET_IO_CAN_READ);\n wait(&we, 1);\n }\n else\n break;\n }\n else if (new_bytes_read == 0) {\n break;\n }\n else {\n total_bytes_read += new_bytes_read;\n if (total_bytes_read == bytes_to_read)\n return true;\n }\n }\n return false;\n }\n\n \/\/ ---------------------------------------------------------------------------\n int CIOChannel::recvUpTo(void* dest_buffer, size_t bytes_to_read) const {\n while (isValid()) {\n auto new_bytes_read = sys_recv(fd, (char*)dest_buffer, (int)(bytes_to_read), 0);\n if (new_bytes_read == -1) {\n int err = sys_errno;\n if (err == SYS_ERR_WOULD_BLOCK) {\n TWatchedEvent we(fd, EVT_SOCKET_IO_CAN_READ);\n wait(&we, 1);\n }\n else\n break;\n }\n else {\n return new_bytes_read;\n }\n }\n return -1;\n }\n\n \/\/ ---------------------------------------------------------------------------\n bool CIOChannel::send(const void* src_buffer, size_t bytes_to_send) const {\n assert(bytes_to_send > 0);\n size_t total_bytes_sent = 0;\n while (isValid()) {\n assert(bytes_to_send > total_bytes_sent);\n auto bytes_sent = sys_send(fd, ((const char*)src_buffer) + total_bytes_sent, (int)(bytes_to_send - total_bytes_sent), 0);\n if (bytes_sent == -1) {\n if (errno == SYS_ERR_WOULD_BLOCK) {\n TWatchedEvent we(fd, EVT_SOCKET_IO_CAN_WRITE);\n wait(&we, 1);\n }\n else\n break;\n }\n else {\n \/\/dbg(\"FD %d sent %ld bytes\\n\", fd, bytes_sent);\n total_bytes_sent += bytes_sent;\n if (total_bytes_sent == bytes_to_send)\n return true;\n }\n }\n return false;\n }\n}\n\n\/\/ -----------------------------------------------\n\/\/ port and vport are in host format\nvoid TNetAddress::from(int port, unsigned ip4_in_host_format) {\n assert(port > 0 && port < 65535);\n memset(&addr, 0, sizeof(addr));\n addr.sin_family = AF_INET;\n addr.sin_addr.s_addr = htonl(ip4_in_host_format);\n addr.sin_port = htons(port);\n}\n\nvoid TNetAddress::setPort(unsigned short new_app_port) {\n addr.sin_port = htons(new_app_port);\n}\n\nvoid TNetAddress::fromAnyAddress(int port) {\n from(port, INADDR_ANY);\n}\n\nbool TNetAddress::fromStr(const char *addr_str, int port) {\n fromAnyAddress(port);\n return inet_pton(AF_INET, addr_str, &addr.sin_addr) == 1;\n}\n\n\n<commit_msg>Added strerror<commit_after>#include \"coroutines\/io_events.h\"\n#include \"coroutines\/io_channel.h\"\n\nextern void dbg(const char *fmt, ...);\n\/\/#define dbg(...)\n\n#ifdef _WIN32\n\n#pragma comment(lib, \"Ws2_32.lib\")\n#define sys_socket(x,y,z,port)\t::socket( x, y, z )\n#define sys_connect(id,addr,sz) ::connect( id, (const sockaddr*) addr, sz )\n#define sys_send ::send\n#define sys_recv ::recv\n#define sys_errno ::WSAGetLastError()\n#define sys_close ::closesocket\n#define sys_bind(id,addr,sz) ::bind(id, (const sockaddr *) addr, sz )\n#define sys_accept(id,addr,sz) ::accept( id, (sockaddr*) addr, sz )\n#define sys_listen ::listen\n\n#define SYS_ERR_WOULD_BLOCK WSAEWOULDBLOCK\n#define SYS_ERR_CONN_IN_PROGRESS WSAEWOULDBLOCK\n\n#else\n\n#include <sys\/types.h>\n#include <sys\/uio.h>\n#include <unistd.h>\n#include <fcntl.h>\n#include <errno.h>\n#include <arpa\/inet.h>\n\n#define sys_socket(x,y,z,port) ::socket( x, y, z )\n#define sys_connect(id,addr,sz) ::connect( id, (const sockaddr*) addr, sz )\n#define sys_send ::send\n#define sys_recv ::recv\n#define sys_errno errno\n#define sys_close ::close\n#define sys_bind(id,addr,sz) ::bind(id, (const sockaddr *) addr, sz )\n#define sys_accept(id,addr,sz) ::accept( id, (sockaddr*) addr, (socklen_t*)sz )\n#define sys_listen ::listen\n\n#define SYS_ERR_WOULD_BLOCK EWOULDBLOCK\n#define SYS_ERR_CONN_IN_PROGRESS EINPROGRESS\n\n#endif\n\nnamespace Coroutines {\n\n bool CIOChannel::setNonBlocking() {\n \/\/ set non-blocking\n#if defined(O_NONBLOCK)\n int flags = fcntl(fd, F_GETFL, 0);\n if (flags == -1)\n flags = 0;\n auto rc = fcntl(fd, F_SETFL, flags | O_NONBLOCK);\n#else\n u_long iMode = 1;\n auto rc = ioctlsocket(fd, FIONBIO, &iMode);\n#endif\n if (rc != 0)\n dbg(\"Failed to set socket %d as non-blocking\\n\", fd);\n return rc == 0;\n }\n\n \/\/ ---------------------------------------------------------------------------\n int CIOChannel::getSocketError() {\n \/\/ Confirm we are really connected by checking the socket error\n int sock_err = 0;\n socklen_t sock_err_sz = sizeof(sock_err);\n int rc = getsockopt(fd, SOL_SOCKET, SO_ERROR, (char*)&sock_err, &sock_err_sz);\n return sock_err;\n }\n\n\n \/\/ ---------------------------------------------------------------------------\n bool CIOChannel::listen(const TNetAddress& serving_addr) {\n if (isValid())\n return false;\n\n auto new_fd = sys_socket(AF_INET, SOCK_STREAM, 0, 0);\n if (new_fd < 0)\n return false;\n fd = new_fd;\n\n if (sys_bind(fd, &serving_addr, sizeof(serving_addr)) < 0)\n return false;\n\n if (sys_listen(fd, 5) < 0)\n return false;\n\n setNonBlocking();\n\n return true;\n }\n\n \/\/ ---------------------------------------------------------------------------\n CIOChannel CIOChannel::accept() {\n dbg(\"FD %d is accepting connections\\n\", fd);\n\n while (isValid()) {\n TNetAddress remote_client_addr;\n int remote_addr_sz = sizeof(remote_client_addr);\n int rc = sys_accept(fd, &remote_client_addr.addr, &remote_addr_sz);\n if (rc < 0) {\n int sys_err = sys_errno;\n if (sys_err == SYS_ERR_WOULD_BLOCK) {\n dbg(\"FD %d goes to sleep waiting for a connection\\n\", fd);\n TWatchedEvent we(fd, EVT_SOCKET_IO_CAN_READ);\n wait(&we, 1);\n continue;\n }\n dbg(\"FD %d accept failed (%08x %s)\\n\", fd, sys_err, strerror(sys_err) );\n \/\/ Other types of errors\n return CIOChannel();\n }\n dbg(\"FD %d has accepted new client %d\\n\", fd, rc);\n CIOChannel new_client;\n new_client.fd = rc;\n new_client.setNonBlocking();\n return new_client;\n }\n return CIOChannel();\n }\n\n \/\/ ---------------------------------------------------------------------------\n bool CIOChannel::connect(const TNetAddress &remote_server, int timeout_sec) {\n\n auto new_fd = sys_socket(AF_INET, SOCK_STREAM, 0, 0);\n if (new_fd < 0)\n return false;\n fd = new_fd;\n\n setNonBlocking();\n\n dbg(\"FD %d starting to connect\\n\", fd);\n\n while (isValid()) {\n int rc = sys_connect(fd, &remote_server.addr, sizeof(remote_server));\n if (rc < 0) {\n int sys_err = sys_errno;\n if (sys_err == SYS_ERR_CONN_IN_PROGRESS) {\n TWatchedEvent we(fd, EVT_SOCKET_IO_CAN_WRITE);\n int n = wait(&we, 1);\n if (n == 0) {\n\n \/\/ Confirm we are really connected by checking the socket error\n int sock_err = getSocketError();\n \n \/\/ All ok, no errors\n if (sock_err == 0) \n break;\n\n \/\/ The expected error in this case is Conn Refused when there is no server\n \/\/ in the remote address. Other erros, I prefer to report them\n if (sock_err != ECONNREFUSED) \n dbg(\"connect.failed getsockopt( %d ) (err=%08x)\\n\", fd, sock_err);\n }\n continue;\n }\n dbg(\"FD %d connect rc = %d (%08x %s)\\n\", fd, rc, sys_err, strerror( sys_err ));\n }\n else {\n \/\/ Connected without waiting\n break;\n }\n }\n\n \/\/ If we are not valid, the socket we created should be destroyed.\n if (!isValid())\n close();\n else \n dbg(\"FD %d connected\\n\", fd);\n return isValid();\n }\n\n \/\/ ---------------------------------------------------------------------------\n void CIOChannel::close() {\n if (isValid()) {\n dbg(\"FD %d closed\\n\", fd);\n sys_close(fd);\n fd = invalid_socket_id;\n\n \/\/ Remove from entries...\n }\n }\n\n \/\/ ---------------------------------------------------------------------------\n bool CIOChannel::recv(void* dest_buffer, size_t bytes_to_read) const {\n assert(bytes_to_read > 0);\n size_t total_bytes_read = 0;\n while (isValid()) {\n assert(bytes_to_read > total_bytes_read);\n auto new_bytes_read = sys_recv(fd, (char*)dest_buffer, (int)(bytes_to_read - total_bytes_read), 0);\n if (new_bytes_read == -1) {\n int err = sys_errno;\n if (err == SYS_ERR_WOULD_BLOCK) {\n TWatchedEvent we(fd, EVT_SOCKET_IO_CAN_READ);\n wait(&we, 1);\n }\n else\n break;\n }\n else if (new_bytes_read == 0) {\n break;\n }\n else {\n total_bytes_read += new_bytes_read;\n if (total_bytes_read == bytes_to_read)\n return true;\n }\n }\n return false;\n }\n\n \/\/ ---------------------------------------------------------------------------\n int CIOChannel::recvUpTo(void* dest_buffer, size_t bytes_to_read) const {\n while (isValid()) {\n auto new_bytes_read = sys_recv(fd, (char*)dest_buffer, (int)(bytes_to_read), 0);\n if (new_bytes_read == -1) {\n int err = sys_errno;\n if (err == SYS_ERR_WOULD_BLOCK) {\n TWatchedEvent we(fd, EVT_SOCKET_IO_CAN_READ);\n wait(&we, 1);\n }\n else\n break;\n }\n else {\n return new_bytes_read;\n }\n }\n return -1;\n }\n\n \/\/ ---------------------------------------------------------------------------\n bool CIOChannel::send(const void* src_buffer, size_t bytes_to_send) const {\n assert(bytes_to_send > 0);\n size_t total_bytes_sent = 0;\n while (isValid()) {\n assert(bytes_to_send > total_bytes_sent);\n auto bytes_sent = sys_send(fd, ((const char*)src_buffer) + total_bytes_sent, (int)(bytes_to_send - total_bytes_sent), 0);\n if (bytes_sent == -1) {\n if (errno == SYS_ERR_WOULD_BLOCK) {\n TWatchedEvent we(fd, EVT_SOCKET_IO_CAN_WRITE);\n wait(&we, 1);\n }\n else\n break;\n }\n else {\n \/\/dbg(\"FD %d sent %ld bytes\\n\", fd, bytes_sent);\n total_bytes_sent += bytes_sent;\n if (total_bytes_sent == bytes_to_send)\n return true;\n }\n }\n return false;\n }\n}\n\n\/\/ -----------------------------------------------\n\/\/ port and vport are in host format\nvoid TNetAddress::from(int port, unsigned ip4_in_host_format) {\n assert(port > 0 && port < 65535);\n memset(&addr, 0, sizeof(addr));\n addr.sin_family = AF_INET;\n addr.sin_addr.s_addr = htonl(ip4_in_host_format);\n addr.sin_port = htons(port);\n}\n\nvoid TNetAddress::setPort(unsigned short new_app_port) {\n addr.sin_port = htons(new_app_port);\n}\n\nvoid TNetAddress::fromAnyAddress(int port) {\n from(port, INADDR_ANY);\n}\n\nbool TNetAddress::fromStr(const char *addr_str, int port) {\n fromAnyAddress(port);\n return inet_pton(AF_INET, addr_str, &addr.sin_addr) == 1;\n}\n\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2012 Plenluno All rights reserved.\n\n#include <assert.h>\n#include <http_parser.h>\n#include <uv.h>\n\n#include \"libnode\/http\/server.h\"\n#include \".\/server_request_impl.h\"\n#include \".\/server_response_impl.h\"\n#include \"..\/net\/server_impl.h\"\n#include \"..\/net\/socket_impl.h\"\n\nnamespace libj {\nnamespace node {\nnamespace http {\n\nclass ServerImpl;\n\nclass ServerContext {\n public:\n ServerContext(\n ServerImpl* srv,\n net::SocketImpl::Ptr sock)\n : server(srv)\n , request(ServerRequestImpl::create(sock))\n , response(ServerResponseImpl::create(sock)) {\n parser.data = this;\n }\n\n ServerImpl* server;\n ServerRequestImpl::Ptr request;\n ServerResponseImpl::Ptr response;\n http_parser parser;\n};\n\nclass ServerImpl : public Server {\n public:\n static Ptr create() {\n Ptr p(new ServerImpl());\n return p;\n }\n\n Boolean listen(Int port, String::CPtr hostName, Int backlog) {\n server_->on(\n net::Server::EVENT_CLOSE,\n OnServerClose::create(this));\n server_->on(\n net::Server::EVENT_LISTENING,\n OnServerListening::create());\n server_->on(\n net::Server::EVENT_CONNECTION,\n OnServerConnection::create(this));\n return server_->listen(port, hostName, backlog);\n }\n\n void close() {\n server_->close();\n }\n\n private:\n static http_parser_settings settings;\n\n class OnServerClose : LIBJ_JS_FUNCTION(OnServerClose)\n public:\n static Ptr create(ServerImpl* srv) {\n Ptr p(new OnServerClose(srv));\n return p;\n }\n\n Value operator()(JsArray::Ptr args) {\n server_->emit(EVENT_CLOSE, JsArray::create());\n return libj::Status::OK;\n }\n\n private:\n ServerImpl* server_;\n\n OnServerClose(ServerImpl* srv) : server_(srv) {}\n };\n\n class OnServerListening : LIBJ_JS_FUNCTION(OnServerListening)\n public:\n static Ptr create() {\n Ptr p(new OnServerListening());\n return p;\n }\n\n Value operator()(JsArray::Ptr args) {\n settings.on_url = ServerImpl::onUrl;\n settings.on_header_field = ServerImpl::onHeaderField;\n settings.on_header_value = ServerImpl::onHeaderValue;\n settings.on_headers_complete = ServerImpl::onHeadersComplete;\n settings.on_message_begin = ServerImpl::onMessageBegin;\n settings.on_body = ServerImpl::onBody;\n settings.on_message_complete = ServerImpl::onMessageComplete;\n return libj::Status::OK;\n }\n };\n\n class OnServerConnection : LIBJ_JS_FUNCTION(OnServerConnection)\n public:\n static Ptr create(ServerImpl* srv) {\n Ptr p(new OnServerConnection(srv));\n return p;\n }\n\n Value operator()(JsArray::Ptr args) {\n net::SocketImpl::Ptr socket = toPtr<net::SocketImpl>(args->get(0));\n assert(socket);\n ServerContext* context = new ServerContext(server_, socket);\n http_parser_init(&context->parser, HTTP_REQUEST);\n socket->on(\n net::Socket::EVENT_DATA,\n OnSocketData::create(context));\n socket->on(\n net::Socket::EVENT_CLOSE,\n OnSocketClose::create(context));\n server_->emit(EVENT_CONNECTION, args);\n return libj::Status::OK;\n }\n\n private:\n ServerImpl* server_;\n\n OnServerConnection(ServerImpl* srv) : server_(srv) {}\n };\n\n class OnSocketData : LIBJ_JS_FUNCTION(OnSocketData)\n public:\n static Ptr create(ServerContext* ctxt) {\n assert(ctxt);\n Ptr p(new OnSocketData(ctxt));\n return p;\n }\n\n Value operator()(JsArray::Ptr args) {\n http_parser* httpParser = &context_->parser;\n Buffer::Ptr buf = toPtr<Buffer>(args->get(0));\n assert(buf);\n size_t numRead = buf->length();\n size_t numParsed = http_parser_execute(\n httpParser,\n &settings,\n static_cast<const char*>(buf->data()),\n numRead);\n ServerRequestImpl::Ptr request = context_->request;\n net::SocketImpl::Ptr socket =\n LIBJ_STATIC_PTR_CAST(net::SocketImpl)(request->connection());\n if (httpParser->upgrade) {\n socket->removeAllListeners();\n JsArray::Ptr args = JsArray::create();\n args->add(request);\n args->add(socket);\n args->add(buf->slice(numParsed));\n context_->server->emit(EVENT_UPGRADE, args);\n delete context_;\n } else if (numParsed < numRead) { \/\/ parse error\n socket->destroy(\n libj::Error::create(libj::Error::ILLEGAL_REQUEST));\n }\n return libj::Status::OK;\n }\n\n private:\n ServerContext* context_;\n\n OnSocketData(ServerContext* ctxt) : context_(ctxt) {}\n };\n\n class OnSocketClose : LIBJ_JS_FUNCTION(OnSocketClose)\n public:\n static Ptr create(ServerContext* ctxt) {\n assert(ctxt);\n Ptr p(new OnSocketClose(ctxt));\n return p;\n }\n\n Value operator()(JsArray::Ptr args) {\n if (context_) {\n JsArray::Ptr noArgs = JsArray::create();\n context_->request->emit(ServerRequest::EVENT_CLOSE, noArgs);\n context_->response->emit(ServerResponse::EVENT_CLOSE, noArgs);\n delete context_;\n context_ = NULL;\n }\n return libj::Status::OK;\n }\n\n private:\n ServerContext* context_;\n\n OnSocketClose(ServerContext* ctxt) : context_(ctxt) {}\n };\n\n static int onUrl(http_parser* parser, const char* at, size_t length) {\n ServerContext* context = static_cast<ServerContext*>(parser->data);\n String::CPtr url = String::create(at, String::UTF8, length);\n context->request->setUrl(url);\n return 0;\n }\n\n static String::CPtr headerName;\n\n static int onHeaderField(\n http_parser* parser, const char* at, size_t length) {\n headerName = String::create(at, String::UTF8, length);\n return 0;\n }\n\n static int onHeaderValue(\n http_parser* parser, const char* at, size_t length) {\n ServerContext* context = static_cast<ServerContext*>(parser->data);\n context->request->setHeader(\n headerName,\n String::create(at, String::UTF8, length));\n return 0;\n }\n\n static int onHeadersComplete(http_parser* parser) {\n static const String::CPtr methodDelete = String::create(\"DELETE\");\n static const String::CPtr methodGet = String::create(\"GET\");\n static const String::CPtr methodHead = String::create(\"HEAD\");\n static const String::CPtr methodPost = String::create(\"POST\");\n static const String::CPtr methodPut = String::create(\"PUT\");\n static const String::CPtr methodConnect = String::create(\"CONNECT\");\n static const String::CPtr methodOptions = String::create(\"OPTIONS\");\n static const String::CPtr methodTrace = String::create(\"TRACE\");\n static const String::CPtr dot = String::create(\".\");\n\n ServerContext* context = static_cast<ServerContext*>(parser->data);\n assert(context);\n switch (parser->method) {\n case HTTP_DELETE:\n context->request->setMethod(methodDelete);\n break;\n case HTTP_GET:\n context->request->setMethod(methodGet);\n break;\n case HTTP_HEAD:\n context->request->setMethod(methodHead);\n break;\n case HTTP_POST:\n context->request->setMethod(methodPost);\n break;\n case HTTP_PUT:\n context->request->setMethod(methodPut);\n break;\n case HTTP_CONNECT:\n context->request->setMethod(methodConnect);\n break;\n case HTTP_OPTIONS:\n context->request->setMethod(methodOptions);\n break;\n case HTTP_TRACE:\n context->request->setMethod(methodTrace);\n break;\n default:\n context->request->setMethod(String::create());\n }\n\n Int majorVer = static_cast<Int>(parser->http_major);\n Int minorVer = static_cast<Int>(parser->http_minor);\n String::CPtr httpVer = String::valueOf(majorVer);\n httpVer = httpVer->concat(dot);\n httpVer = httpVer->concat(String::valueOf(minorVer));\n context->request->setHttpVersion(httpVer);\n\n JsArray::Ptr args = JsArray::create();\n ServerRequest::Ptr req(context->request);\n ServerResponse::Ptr res(context->response);\n args->add(req);\n args->add(res);\n assert(context->server);\n context->server->emit(Server::EVENT_REQUEST, args);\n return 0;\n }\n\n static int onMessageBegin(http_parser* parser) {\n return 0;\n }\n\n static int onBody(http_parser* parser, const char* at, size_t length) {\n ServerContext* context = static_cast<ServerContext*>(parser->data);\n ServerRequestImpl::Ptr request = context->request;\n if (request) {\n Buffer::Ptr chunk = Buffer::create(at, length);\n JsArray::Ptr args = JsArray::create();\n if (request->hasEncoding()) {\n Buffer::Encoding enc = request->getEncoding();\n args->add(chunk->toString(enc));\n } else {\n args->add(chunk);\n }\n context->request->emit(ServerRequest::EVENT_DATA, args);\n }\n return 0;\n }\n\n static int onMessageComplete(http_parser* parser) {\n ServerContext* context = static_cast<ServerContext*>(parser->data);\n if (context->request) {\n JsArray::Ptr args = JsArray::create();\n context->request->emit(ServerRequest::EVENT_END, args);\n }\n return 0;\n }\n\n private:\n EventEmitter::Ptr ee_;\n net::ServerImpl::Ptr server_;\n\n ServerImpl()\n : ee_(EventEmitter::create())\n , server_(net::Server::create()) {}\n\n LIBNODE_EVENT_EMITTER_IMPL(ee_);\n};\n\nhttp_parser_settings ServerImpl::settings = {};\nString::CPtr ServerImpl::headerName = String::null();\n\nconst String::CPtr Server::IN_ADDR_ANY = String::create(\"0.0.0.0\");\nconst String::CPtr Server::EVENT_REQUEST = String::create(\"request\");\nconst String::CPtr Server::EVENT_CONNECTION = String::create(\"connection\");\nconst String::CPtr Server::EVENT_CLOSE = String::create(\"close\");\nconst String::CPtr Server::EVENT_UPGRADE = String::create(\"upgrade\");\n\nServer::Ptr Server::create() {\n return ServerImpl::create();\n}\n\n} \/\/ namespace http\n} \/\/ namespace node\n} \/\/ namespace libj\n<commit_msg>refactor ServerImpl<commit_after>\/\/ Copyright (c) 2012 Plenluno All rights reserved.\n\n#include <assert.h>\n#include <http_parser.h>\n#include <uv.h>\n\n#include \"libnode\/http\/server.h\"\n#include \".\/server_request_impl.h\"\n#include \".\/server_response_impl.h\"\n#include \"..\/net\/server_impl.h\"\n#include \"..\/net\/socket_impl.h\"\n\nnamespace libj {\nnamespace node {\nnamespace http {\n\nclass ServerImpl;\n\nclass ServerContext {\n public:\n ServerContext(\n ServerImpl* srv,\n net::SocketImpl::Ptr sock)\n : server(srv)\n , request(ServerRequestImpl::create(sock))\n , response(ServerResponseImpl::create(sock)) {\n parser.data = this;\n }\n\n ServerImpl* server;\n ServerRequestImpl::Ptr request;\n ServerResponseImpl::Ptr response;\n http_parser parser;\n};\n\nclass ServerImpl : public Server {\n public:\n static Ptr create() {\n Ptr p(new ServerImpl());\n return p;\n }\n\n Boolean listen(Int port, String::CPtr hostName, Int backlog) {\n server_->on(\n net::Server::EVENT_CLOSE,\n OnServerClose::create(this));\n server_->on(\n net::Server::EVENT_LISTENING,\n OnServerListening::create());\n server_->on(\n net::Server::EVENT_CONNECTION,\n OnServerConnection::create(this));\n return server_->listen(port, hostName, backlog);\n }\n\n void close() {\n server_->close();\n }\n\n private:\n static http_parser_settings settings;\n\n class OnServerClose : LIBJ_JS_FUNCTION(OnServerClose)\n public:\n static Ptr create(ServerImpl* srv) {\n Ptr p(new OnServerClose(srv));\n return p;\n }\n\n Value operator()(JsArray::Ptr args) {\n server_->emit(EVENT_CLOSE, JsArray::create());\n return libj::Status::OK;\n }\n\n private:\n ServerImpl* server_;\n\n OnServerClose(ServerImpl* srv) : server_(srv) {}\n };\n\n class OnServerListening : LIBJ_JS_FUNCTION(OnServerListening)\n public:\n static Ptr create() {\n Ptr p(new OnServerListening());\n return p;\n }\n\n Value operator()(JsArray::Ptr args) {\n settings.on_url = ServerImpl::onUrl;\n settings.on_header_field = ServerImpl::onHeaderField;\n settings.on_header_value = ServerImpl::onHeaderValue;\n settings.on_headers_complete = ServerImpl::onHeadersComplete;\n settings.on_message_begin = ServerImpl::onMessageBegin;\n settings.on_body = ServerImpl::onBody;\n settings.on_message_complete = ServerImpl::onMessageComplete;\n return libj::Status::OK;\n }\n };\n\n class OnServerConnection : LIBJ_JS_FUNCTION(OnServerConnection)\n public:\n static Ptr create(ServerImpl* srv) {\n Ptr p(new OnServerConnection(srv));\n return p;\n }\n\n Value operator()(JsArray::Ptr args) {\n net::SocketImpl::Ptr socket = toPtr<net::SocketImpl>(args->get(0));\n assert(socket);\n ServerContext* context = new ServerContext(server_, socket);\n http_parser_init(&context->parser, HTTP_REQUEST);\n socket->on(\n net::Socket::EVENT_DATA,\n OnSocketData::create(context));\n socket->on(\n net::Socket::EVENT_CLOSE,\n OnSocketClose::create(context));\n server_->emit(EVENT_CONNECTION, args);\n return libj::Status::OK;\n }\n\n private:\n ServerImpl* server_;\n\n OnServerConnection(ServerImpl* srv) : server_(srv) {}\n };\n\n class OnSocketData : LIBJ_JS_FUNCTION(OnSocketData)\n public:\n static Ptr create(ServerContext* ctxt) {\n assert(ctxt);\n Ptr p(new OnSocketData(ctxt));\n return p;\n }\n\n Value operator()(JsArray::Ptr args) {\n http_parser* httpParser = &context_->parser;\n Buffer::Ptr buf = toPtr<Buffer>(args->get(0));\n assert(buf);\n size_t numRead = buf->length();\n size_t numParsed = http_parser_execute(\n httpParser,\n &settings,\n static_cast<const char*>(buf->data()),\n numRead);\n ServerRequestImpl::Ptr request = context_->request;\n net::SocketImpl::Ptr socket =\n LIBJ_STATIC_PTR_CAST(net::SocketImpl)(request->connection());\n if (httpParser->upgrade) {\n socket->removeAllListeners();\n JsArray::Ptr args = JsArray::create();\n args->add(request);\n args->add(socket);\n args->add(buf->slice(numParsed));\n context_->server->emit(EVENT_UPGRADE, args);\n delete context_;\n } else if (numParsed < numRead) { \/\/ parse error\n socket->destroy(\n libj::Error::create(libj::Error::ILLEGAL_REQUEST));\n }\n return libj::Status::OK;\n }\n\n private:\n ServerContext* context_;\n\n OnSocketData(ServerContext* ctxt) : context_(ctxt) {}\n };\n\n class OnSocketClose : LIBJ_JS_FUNCTION(OnSocketClose)\n public:\n static Ptr create(ServerContext* ctxt) {\n assert(ctxt);\n Ptr p(new OnSocketClose(ctxt));\n return p;\n }\n\n Value operator()(JsArray::Ptr args) {\n if (context_) {\n JsArray::Ptr noArgs = JsArray::create();\n context_->request->emit(ServerRequest::EVENT_CLOSE, noArgs);\n context_->response->emit(ServerResponse::EVENT_CLOSE, noArgs);\n delete context_;\n context_ = NULL;\n }\n return libj::Status::OK;\n }\n\n private:\n ServerContext* context_;\n\n OnSocketClose(ServerContext* ctxt) : context_(ctxt) {}\n };\n\n static int onUrl(http_parser* parser, const char* at, size_t length) {\n ServerContext* context = static_cast<ServerContext*>(parser->data);\n String::CPtr url = String::create(at, String::UTF8, length);\n context->request->setUrl(url);\n return 0;\n }\n\n static String::CPtr headerName;\n\n static int onHeaderField(\n http_parser* parser, const char* at, size_t length) {\n headerName = String::create(at, String::UTF8, length);\n return 0;\n }\n\n static int onHeaderValue(\n http_parser* parser, const char* at, size_t length) {\n ServerContext* context = static_cast<ServerContext*>(parser->data);\n context->request->setHeader(\n headerName,\n String::create(at, String::UTF8, length));\n return 0;\n }\n\n static int onHeadersComplete(http_parser* parser) {\n static const String::CPtr methodDelete = String::create(\"DELETE\");\n static const String::CPtr methodGet = String::create(\"GET\");\n static const String::CPtr methodHead = String::create(\"HEAD\");\n static const String::CPtr methodPost = String::create(\"POST\");\n static const String::CPtr methodPut = String::create(\"PUT\");\n static const String::CPtr methodConnect = String::create(\"CONNECT\");\n static const String::CPtr methodOptions = String::create(\"OPTIONS\");\n static const String::CPtr methodTrace = String::create(\"TRACE\");\n static const String::CPtr dot = String::create(\".\");\n\n ServerContext* context = static_cast<ServerContext*>(parser->data);\n assert(context);\n switch (parser->method) {\n case HTTP_DELETE:\n context->request->setMethod(methodDelete);\n break;\n case HTTP_GET:\n context->request->setMethod(methodGet);\n break;\n case HTTP_HEAD:\n context->request->setMethod(methodHead);\n break;\n case HTTP_POST:\n context->request->setMethod(methodPost);\n break;\n case HTTP_PUT:\n context->request->setMethod(methodPut);\n break;\n case HTTP_CONNECT:\n context->request->setMethod(methodConnect);\n break;\n case HTTP_OPTIONS:\n context->request->setMethod(methodOptions);\n break;\n case HTTP_TRACE:\n context->request->setMethod(methodTrace);\n break;\n default:\n context->request->setMethod(String::create());\n }\n\n Int majorVer = static_cast<Int>(parser->http_major);\n Int minorVer = static_cast<Int>(parser->http_minor);\n String::CPtr httpVer = String::valueOf(majorVer);\n httpVer = httpVer->concat(dot);\n httpVer = httpVer->concat(String::valueOf(minorVer));\n context->request->setHttpVersion(httpVer);\n\n JsArray::Ptr args = JsArray::create();\n ServerRequest::Ptr req(context->request);\n ServerResponse::Ptr res(context->response);\n args->add(req);\n args->add(res);\n assert(context->server);\n context->server->emit(Server::EVENT_REQUEST, args);\n return 0;\n }\n\n static int onMessageBegin(http_parser* parser) {\n return 0;\n }\n\n static int onBody(http_parser* parser, const char* at, size_t length) {\n ServerContext* context = static_cast<ServerContext*>(parser->data);\n ServerRequestImpl::Ptr request = context->request;\n if (request) {\n Buffer::Ptr chunk = Buffer::create(at, length);\n JsArray::Ptr args = JsArray::create();\n if (request->hasEncoding()) {\n Buffer::Encoding enc = request->getEncoding();\n args->add(chunk->toString(enc));\n } else {\n args->add(chunk);\n }\n request->emit(ServerRequest::EVENT_DATA, args);\n }\n return 0;\n }\n\n static int onMessageComplete(http_parser* parser) {\n ServerContext* context = static_cast<ServerContext*>(parser->data);\n ServerRequestImpl::Ptr request = context->request;\n if (request) {\n JsArray::Ptr args = JsArray::create();\n request->emit(ServerRequest::EVENT_END, args);\n }\n return 0;\n }\n\n private:\n EventEmitter::Ptr ee_;\n net::ServerImpl::Ptr server_;\n\n ServerImpl()\n : ee_(EventEmitter::create())\n , server_(net::Server::create()) {}\n\n LIBNODE_EVENT_EMITTER_IMPL(ee_);\n};\n\nhttp_parser_settings ServerImpl::settings = {};\nString::CPtr ServerImpl::headerName = String::null();\n\nconst String::CPtr Server::IN_ADDR_ANY = String::create(\"0.0.0.0\");\nconst String::CPtr Server::EVENT_REQUEST = String::create(\"request\");\nconst String::CPtr Server::EVENT_CONNECTION = String::create(\"connection\");\nconst String::CPtr Server::EVENT_CLOSE = String::create(\"close\");\nconst String::CPtr Server::EVENT_UPGRADE = String::create(\"upgrade\");\n\nServer::Ptr Server::create() {\n return ServerImpl::create();\n}\n\n} \/\/ namespace http\n} \/\/ namespace node\n} \/\/ namespace libj\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright © 2014 Intel Corporation\n *\n * Permission is hereby granted, free of charge, to any person obtaining a\n * copy of this software and associated documentation files (the \"Software\"),\n * to deal in the Software without restriction, including without limitation\n * the rights to use, copy, modify, merge, publish, distribute, sublicense,\n * and\/or sell copies of the Software, and to permit persons to whom the\n * Software is furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice (including the next\n * paragraph) shall be included in all copies or substantial portions of the\n * Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n * IN THE SOFTWARE.\n *\/\n\n\/** @file brw_fs_combine_constants.cpp\n *\n * This file contains the opt_combine_constants() pass that runs after the\n * regular optimization loop. It passes over the instruction list and\n * selectively promotes immediate values to registers by emitting a mov(1)\n * instruction.\n *\n * This is useful on Gen 7 particularly, because a few instructions can be\n * coissued (i.e., issued in the same cycle as another thread on the same EU\n * issues an instruction) under some circumstances, one of which is that they\n * cannot use immediate values.\n *\/\n\n#include \"brw_fs.h\"\n#include \"brw_cfg.h\"\n\nusing namespace brw;\n\n\/* Returns whether an instruction could co-issue if its immediate source were\n * replaced with a GRF source.\n *\/\nstatic bool\ncould_coissue(const struct brw_device_info *devinfo, const fs_inst *inst)\n{\n if (devinfo->gen != 7)\n return false;\n\n switch (inst->opcode) {\n case BRW_OPCODE_MOV:\n case BRW_OPCODE_CMP:\n case BRW_OPCODE_ADD:\n case BRW_OPCODE_MUL:\n return true;\n default:\n return false;\n }\n}\n\n\/**\n * Returns true for instructions that don't support immediate sources.\n *\/\nstatic bool\nmust_promote_imm(const struct brw_device_info *devinfo, const fs_inst *inst)\n{\n switch (inst->opcode) {\n case SHADER_OPCODE_POW:\n return devinfo->gen < 8;\n case BRW_OPCODE_MAD:\n case BRW_OPCODE_LRP:\n return true;\n default:\n return false;\n }\n}\n\n\/** A box for putting fs_regs in a linked list. *\/\nstruct reg_link {\n DECLARE_RALLOC_CXX_OPERATORS(reg_link)\n\n reg_link(fs_reg *reg) : reg(reg) {}\n\n struct exec_node link;\n fs_reg *reg;\n};\n\nstatic struct exec_node *\nlink(void *mem_ctx, fs_reg *reg)\n{\n reg_link *l = new(mem_ctx) reg_link(reg);\n return &l->link;\n}\n\n\/**\n * Information about an immediate value.\n *\/\nstruct imm {\n \/** The common ancestor of all blocks using this immediate value. *\/\n bblock_t *block;\n\n \/**\n * The instruction generating the immediate value, if all uses are contained\n * within a single basic block. Otherwise, NULL.\n *\/\n fs_inst *inst;\n\n \/**\n * A list of fs_regs that refer to this immediate. If we promote it, we'll\n * have to patch these up to refer to the new GRF.\n *\/\n exec_list *uses;\n\n \/** The immediate value. We currently only handle floats. *\/\n float val;\n\n \/**\n * The GRF register and subregister number where we've decided to store the\n * constant value.\n *\/\n uint8_t subreg_offset;\n uint16_t nr;\n\n \/** The number of coissuable instructions using this immediate. *\/\n uint16_t uses_by_coissue;\n\n \/**\n * Whether this constant is used by an instruction that can't handle an\n * immediate source (and already has to be promoted to a GRF).\n *\/\n bool must_promote;\n\n uint16_t first_use_ip;\n uint16_t last_use_ip;\n};\n\n\/** The working set of information about immediates. *\/\nstruct table {\n struct imm *imm;\n int size;\n int len;\n};\n\nstatic struct imm *\nfind_imm(struct table *table, float val)\n{\n assert(signbit(val) == 0);\n\n for (int i = 0; i < table->len; i++) {\n if (table->imm[i].val == val) {\n return &table->imm[i];\n }\n }\n return NULL;\n}\n\nstatic struct imm *\nnew_imm(struct table *table, void *mem_ctx)\n{\n if (table->len == table->size) {\n table->size *= 2;\n table->imm = reralloc(mem_ctx, table->imm, struct imm, table->size);\n }\n return &table->imm[table->len++];\n}\n\n\/**\n * Comparator used for sorting an array of imm structures.\n *\n * We sort by basic block number, then last use IP, then first use IP (least\n * to greatest). This sorting causes immediates live in the same area to be\n * allocated to the same register in the hopes that all values will be dead\n * about the same time and the register can be reused.\n *\/\nstatic int\ncompare(const void *_a, const void *_b)\n{\n const struct imm *a = (const struct imm *)_a,\n *b = (const struct imm *)_b;\n\n int block_diff = a->block->num - b->block->num;\n if (block_diff)\n return block_diff;\n\n int end_diff = a->last_use_ip - b->last_use_ip;\n if (end_diff)\n return end_diff;\n\n return a->first_use_ip - b->first_use_ip;\n}\n\nbool\nfs_visitor::opt_combine_constants()\n{\n void *const_ctx = ralloc_context(NULL);\n\n struct table table;\n table.size = 8;\n table.len = 0;\n table.imm = ralloc_array(const_ctx, struct imm, table.size);\n\n cfg->calculate_idom();\n unsigned ip = -1;\n\n \/* Make a pass through all instructions and count the number of times each\n * constant is used by coissueable instructions or instructions that cannot\n * take immediate arguments.\n *\/\n foreach_block_and_inst(block, fs_inst, inst, cfg) {\n ip++;\n\n if (!could_coissue(devinfo, inst) && !must_promote_imm(devinfo, inst))\n continue;\n\n for (int i = 0; i < inst->sources; i++) {\n if (inst->src[i].file != IMM ||\n inst->src[i].type != BRW_REGISTER_TYPE_F)\n continue;\n\n float val = fabsf(inst->src[i].f);\n struct imm *imm = find_imm(&table, val);\n\n if (imm) {\n bblock_t *intersection = cfg_t::intersect(block, imm->block);\n if (intersection != imm->block)\n imm->inst = NULL;\n imm->block = intersection;\n imm->uses->push_tail(link(const_ctx, &inst->src[i]));\n imm->uses_by_coissue += could_coissue(devinfo, inst);\n imm->must_promote = imm->must_promote || must_promote_imm(devinfo, inst);\n imm->last_use_ip = ip;\n } else {\n imm = new_imm(&table, const_ctx);\n imm->block = block;\n imm->inst = inst;\n imm->uses = new(const_ctx) exec_list();\n imm->uses->push_tail(link(const_ctx, &inst->src[i]));\n imm->val = val;\n imm->uses_by_coissue = could_coissue(devinfo, inst);\n imm->must_promote = must_promote_imm(devinfo, inst);\n imm->first_use_ip = ip;\n imm->last_use_ip = ip;\n }\n }\n }\n\n \/* Remove constants from the table that don't have enough uses to make them\n * profitable to store in a register.\n *\/\n for (int i = 0; i < table.len;) {\n struct imm *imm = &table.imm[i];\n\n if (!imm->must_promote && imm->uses_by_coissue < 4) {\n table.imm[i] = table.imm[table.len - 1];\n table.len--;\n continue;\n }\n i++;\n }\n if (table.len == 0) {\n ralloc_free(const_ctx);\n return false;\n }\n if (cfg->num_blocks != 1)\n qsort(table.imm, table.len, sizeof(struct imm), compare);\n\n\n \/* Insert MOVs to load the constant values into GRFs. *\/\n fs_reg reg(VGRF, alloc.allocate(dispatch_width \/ 8));\n reg.stride = 0;\n for (int i = 0; i < table.len; i++) {\n struct imm *imm = &table.imm[i];\n \/* Insert it either before the instruction that generated the immediate\n * or after the last non-control flow instruction of the common ancestor.\n *\/\n exec_node *n = (imm->inst ? imm->inst :\n imm->block->last_non_control_flow_inst()->next);\n const fs_builder ibld = bld.at(imm->block, n).exec_all().group(1, 0);\n\n ibld.MOV(reg, brw_imm_f(imm->val));\n imm->nr = reg.nr;\n imm->subreg_offset = reg.subreg_offset;\n\n reg.subreg_offset += sizeof(float);\n if ((unsigned)reg.subreg_offset == dispatch_width * sizeof(float)) {\n reg.nr = alloc.allocate(dispatch_width \/ 8);\n reg.subreg_offset = 0;\n }\n }\n promoted_constants = table.len;\n\n \/* Rewrite the immediate sources to refer to the new GRFs. *\/\n for (int i = 0; i < table.len; i++) {\n foreach_list_typed(reg_link, link, link, table.imm[i].uses) {\n fs_reg *reg = link->reg;\n reg->file = VGRF;\n reg->nr = table.imm[i].nr;\n reg->subreg_offset = table.imm[i].subreg_offset;\n reg->stride = 0;\n reg->negate = signbit(reg->f) != signbit(table.imm[i].val);\n assert(fabsf(reg->f) == table.imm[i].val);\n }\n }\n\n ralloc_free(const_ctx);\n invalidate_live_intervals();\n\n return true;\n}\n<commit_msg>i965\/fs: Add debugging to constant combining pass.<commit_after>\/*\n * Copyright © 2014 Intel Corporation\n *\n * Permission is hereby granted, free of charge, to any person obtaining a\n * copy of this software and associated documentation files (the \"Software\"),\n * to deal in the Software without restriction, including without limitation\n * the rights to use, copy, modify, merge, publish, distribute, sublicense,\n * and\/or sell copies of the Software, and to permit persons to whom the\n * Software is furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice (including the next\n * paragraph) shall be included in all copies or substantial portions of the\n * Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n * IN THE SOFTWARE.\n *\/\n\n\/** @file brw_fs_combine_constants.cpp\n *\n * This file contains the opt_combine_constants() pass that runs after the\n * regular optimization loop. It passes over the instruction list and\n * selectively promotes immediate values to registers by emitting a mov(1)\n * instruction.\n *\n * This is useful on Gen 7 particularly, because a few instructions can be\n * coissued (i.e., issued in the same cycle as another thread on the same EU\n * issues an instruction) under some circumstances, one of which is that they\n * cannot use immediate values.\n *\/\n\n#include \"brw_fs.h\"\n#include \"brw_cfg.h\"\n\nusing namespace brw;\n\nstatic const bool debug = false;\n\n\/* Returns whether an instruction could co-issue if its immediate source were\n * replaced with a GRF source.\n *\/\nstatic bool\ncould_coissue(const struct brw_device_info *devinfo, const fs_inst *inst)\n{\n if (devinfo->gen != 7)\n return false;\n\n switch (inst->opcode) {\n case BRW_OPCODE_MOV:\n case BRW_OPCODE_CMP:\n case BRW_OPCODE_ADD:\n case BRW_OPCODE_MUL:\n return true;\n default:\n return false;\n }\n}\n\n\/**\n * Returns true for instructions that don't support immediate sources.\n *\/\nstatic bool\nmust_promote_imm(const struct brw_device_info *devinfo, const fs_inst *inst)\n{\n switch (inst->opcode) {\n case SHADER_OPCODE_POW:\n return devinfo->gen < 8;\n case BRW_OPCODE_MAD:\n case BRW_OPCODE_LRP:\n return true;\n default:\n return false;\n }\n}\n\n\/** A box for putting fs_regs in a linked list. *\/\nstruct reg_link {\n DECLARE_RALLOC_CXX_OPERATORS(reg_link)\n\n reg_link(fs_reg *reg) : reg(reg) {}\n\n struct exec_node link;\n fs_reg *reg;\n};\n\nstatic struct exec_node *\nlink(void *mem_ctx, fs_reg *reg)\n{\n reg_link *l = new(mem_ctx) reg_link(reg);\n return &l->link;\n}\n\n\/**\n * Information about an immediate value.\n *\/\nstruct imm {\n \/** The common ancestor of all blocks using this immediate value. *\/\n bblock_t *block;\n\n \/**\n * The instruction generating the immediate value, if all uses are contained\n * within a single basic block. Otherwise, NULL.\n *\/\n fs_inst *inst;\n\n \/**\n * A list of fs_regs that refer to this immediate. If we promote it, we'll\n * have to patch these up to refer to the new GRF.\n *\/\n exec_list *uses;\n\n \/** The immediate value. We currently only handle floats. *\/\n float val;\n\n \/**\n * The GRF register and subregister number where we've decided to store the\n * constant value.\n *\/\n uint8_t subreg_offset;\n uint16_t nr;\n\n \/** The number of coissuable instructions using this immediate. *\/\n uint16_t uses_by_coissue;\n\n \/**\n * Whether this constant is used by an instruction that can't handle an\n * immediate source (and already has to be promoted to a GRF).\n *\/\n bool must_promote;\n\n uint16_t first_use_ip;\n uint16_t last_use_ip;\n};\n\n\/** The working set of information about immediates. *\/\nstruct table {\n struct imm *imm;\n int size;\n int len;\n};\n\nstatic struct imm *\nfind_imm(struct table *table, float val)\n{\n assert(signbit(val) == 0);\n\n for (int i = 0; i < table->len; i++) {\n if (table->imm[i].val == val) {\n return &table->imm[i];\n }\n }\n return NULL;\n}\n\nstatic struct imm *\nnew_imm(struct table *table, void *mem_ctx)\n{\n if (table->len == table->size) {\n table->size *= 2;\n table->imm = reralloc(mem_ctx, table->imm, struct imm, table->size);\n }\n return &table->imm[table->len++];\n}\n\n\/**\n * Comparator used for sorting an array of imm structures.\n *\n * We sort by basic block number, then last use IP, then first use IP (least\n * to greatest). This sorting causes immediates live in the same area to be\n * allocated to the same register in the hopes that all values will be dead\n * about the same time and the register can be reused.\n *\/\nstatic int\ncompare(const void *_a, const void *_b)\n{\n const struct imm *a = (const struct imm *)_a,\n *b = (const struct imm *)_b;\n\n int block_diff = a->block->num - b->block->num;\n if (block_diff)\n return block_diff;\n\n int end_diff = a->last_use_ip - b->last_use_ip;\n if (end_diff)\n return end_diff;\n\n return a->first_use_ip - b->first_use_ip;\n}\n\nbool\nfs_visitor::opt_combine_constants()\n{\n void *const_ctx = ralloc_context(NULL);\n\n struct table table;\n table.size = 8;\n table.len = 0;\n table.imm = ralloc_array(const_ctx, struct imm, table.size);\n\n cfg->calculate_idom();\n unsigned ip = -1;\n\n \/* Make a pass through all instructions and count the number of times each\n * constant is used by coissueable instructions or instructions that cannot\n * take immediate arguments.\n *\/\n foreach_block_and_inst(block, fs_inst, inst, cfg) {\n ip++;\n\n if (!could_coissue(devinfo, inst) && !must_promote_imm(devinfo, inst))\n continue;\n\n for (int i = 0; i < inst->sources; i++) {\n if (inst->src[i].file != IMM ||\n inst->src[i].type != BRW_REGISTER_TYPE_F)\n continue;\n\n float val = fabsf(inst->src[i].f);\n struct imm *imm = find_imm(&table, val);\n\n if (imm) {\n bblock_t *intersection = cfg_t::intersect(block, imm->block);\n if (intersection != imm->block)\n imm->inst = NULL;\n imm->block = intersection;\n imm->uses->push_tail(link(const_ctx, &inst->src[i]));\n imm->uses_by_coissue += could_coissue(devinfo, inst);\n imm->must_promote = imm->must_promote || must_promote_imm(devinfo, inst);\n imm->last_use_ip = ip;\n } else {\n imm = new_imm(&table, const_ctx);\n imm->block = block;\n imm->inst = inst;\n imm->uses = new(const_ctx) exec_list();\n imm->uses->push_tail(link(const_ctx, &inst->src[i]));\n imm->val = val;\n imm->uses_by_coissue = could_coissue(devinfo, inst);\n imm->must_promote = must_promote_imm(devinfo, inst);\n imm->first_use_ip = ip;\n imm->last_use_ip = ip;\n }\n }\n }\n\n \/* Remove constants from the table that don't have enough uses to make them\n * profitable to store in a register.\n *\/\n for (int i = 0; i < table.len;) {\n struct imm *imm = &table.imm[i];\n\n if (!imm->must_promote && imm->uses_by_coissue < 4) {\n table.imm[i] = table.imm[table.len - 1];\n table.len--;\n continue;\n }\n i++;\n }\n if (table.len == 0) {\n ralloc_free(const_ctx);\n return false;\n }\n if (cfg->num_blocks != 1)\n qsort(table.imm, table.len, sizeof(struct imm), compare);\n\n \/* Insert MOVs to load the constant values into GRFs. *\/\n fs_reg reg(VGRF, alloc.allocate(dispatch_width \/ 8));\n reg.stride = 0;\n for (int i = 0; i < table.len; i++) {\n struct imm *imm = &table.imm[i];\n \/* Insert it either before the instruction that generated the immediate\n * or after the last non-control flow instruction of the common ancestor.\n *\/\n exec_node *n = (imm->inst ? imm->inst :\n imm->block->last_non_control_flow_inst()->next);\n const fs_builder ibld = bld.at(imm->block, n).exec_all().group(1, 0);\n\n ibld.MOV(reg, brw_imm_f(imm->val));\n imm->nr = reg.nr;\n imm->subreg_offset = reg.subreg_offset;\n\n reg.subreg_offset += sizeof(float);\n if ((unsigned)reg.subreg_offset == dispatch_width * sizeof(float)) {\n reg.nr = alloc.allocate(dispatch_width \/ 8);\n reg.subreg_offset = 0;\n }\n }\n promoted_constants = table.len;\n\n \/* Rewrite the immediate sources to refer to the new GRFs. *\/\n for (int i = 0; i < table.len; i++) {\n foreach_list_typed(reg_link, link, link, table.imm[i].uses) {\n fs_reg *reg = link->reg;\n reg->file = VGRF;\n reg->nr = table.imm[i].nr;\n reg->subreg_offset = table.imm[i].subreg_offset;\n reg->stride = 0;\n reg->negate = signbit(reg->f) != signbit(table.imm[i].val);\n assert(fabsf(reg->f) == table.imm[i].val);\n }\n }\n\n if (debug) {\n for (int i = 0; i < table.len; i++) {\n struct imm *imm = &table.imm[i];\n\n printf(\"%.3fF - block %3d, reg %3d sub %2d, Uses: (%2d, %2d), \"\n \"IP: %4d to %4d, length %4d\\n\",\n imm->val,\n imm->block->num,\n imm->nr,\n imm->subreg_offset,\n imm->must_promote,\n imm->uses_by_coissue,\n imm->first_use_ip,\n imm->last_use_ip,\n imm->last_use_ip - imm->first_use_ip);\n }\n }\n\n ralloc_free(const_ctx);\n invalidate_live_intervals();\n\n return true;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2014 Toggl Desktop developers.\n\n#include \".\/https_client.h\"\n\n#include <string>\n#include <sstream>\n\n#include \"Poco\/Exception.h\"\n#include \"Poco\/InflatingStream.h\"\n#include \"Poco\/DeflatingStream.h\"\n#include \"Poco\/Logger.h\"\n#include \"Poco\/URI.h\"\n#include \"Poco\/NumberParser.h\"\n#include \"Poco\/Net\/Context.h\"\n#include \"Poco\/Net\/NameValueCollection.h\"\n#include \"Poco\/Net\/HTTPMessage.h\"\n#include \"Poco\/Net\/HTTPBasicCredentials.h\"\n#include \"Poco\/Net\/InvalidCertificateHandler.h\"\n#include \"Poco\/Net\/AcceptCertificateHandler.h\"\n#include \"Poco\/Net\/SSLManager.h\"\n#include \"Poco\/Net\/PrivateKeyPassphraseHandler.h\"\n#include \"Poco\/Net\/SecureStreamSocket.h\"\n\n#include \".\/libjson.h\"\n#include \".\/const.h\"\n\nnamespace kopsik {\n\nstd::string HTTPSClient::AppName = std::string(\"\");\nstd::string HTTPSClient::AppVersion = std::string(\"\");\nstd::string HTTPSClient::APIURL = std::string(kAPIURL);\nbool HTTPSClient::UseProxy = false;\nbool HTTPSClient::IgnoreCert = false;\nkopsik::Proxy HTTPSClient::ProxySettings = Proxy();\n\nerror HTTPSClient::PostJSON(\n const std::string relative_url,\n const std::string json,\n const std::string basic_auth_username,\n const std::string basic_auth_password,\n std::string *response_body) {\n return requestJSON(Poco::Net::HTTPRequest::HTTP_POST,\n relative_url,\n json,\n basic_auth_username,\n basic_auth_password,\n response_body);\n}\n\nerror HTTPSClient::GetJSON(\n const std::string relative_url,\n const std::string basic_auth_username,\n const std::string basic_auth_password,\n std::string *response_body) {\n return requestJSON(Poco::Net::HTTPRequest::HTTP_GET,\n relative_url,\n \"\",\n basic_auth_username,\n basic_auth_password,\n response_body);\n}\n\nerror HTTPSClient::requestJSON(\n const std::string method,\n const std::string relative_url,\n const std::string json,\n const std::string basic_auth_username,\n const std::string basic_auth_password,\n std::string *response_body) {\n return request(\n method,\n relative_url,\n json,\n basic_auth_username,\n basic_auth_password,\n response_body);\n}\n\nerror HTTPSClient::request(\n const std::string method,\n const std::string relative_url,\n const std::string payload,\n const std::string basic_auth_username,\n const std::string basic_auth_password,\n std::string *response_body) {\n\n poco_assert(!method.empty());\n poco_assert(!relative_url.empty());\n\n poco_check_ptr(response_body);\n\n *response_body = \"\";\n\n try {\n Poco::URI uri(APIURL);\n\n Poco::SharedPtr<Poco::Net::InvalidCertificateHandler>\n acceptCertHandler =\n new Poco::Net::AcceptCertificateHandler(true);\n\n Poco::Net::Context::VerificationMode verification_mode =\n Poco::Net::Context::VERIFY_RELAXED;\n if (IgnoreCert) {\n verification_mode = Poco::Net::Context::VERIFY_NONE;\n }\n Poco::Net::Context::Ptr context = new Poco::Net::Context(\n Poco::Net::Context::CLIENT_USE, \"\",\n verification_mode, 9, true, \"ALL\");\n\n Poco::Net::SSLManager::instance().initializeClient(\n 0, acceptCertHandler, context);\n\n Poco::Net::HTTPSClientSession session(uri.getHost(), uri.getPort(),\n context);\n if (ProxySettings.IsConfigured()) {\n session.setProxy(ProxySettings.host, ProxySettings.port);\n if (ProxySettings.HasCredentials()) {\n session.setProxyCredentials(ProxySettings.username,\n ProxySettings.password);\n }\n }\n session.setKeepAlive(false);\n session.setTimeout(Poco::Timespan(10 * Poco::Timespan::SECONDS));\n\n Poco::Logger &logger = Poco::Logger::get(\"https_client\");\n {\n std::stringstream ss;\n ss << \"Sending request to \" << relative_url << \" ..\";\n logger.debug(ss.str());\n }\n\n Poco::Net::HTTPRequest req(method,\n relative_url,\n Poco::Net::HTTPMessage::HTTP_1_1);\n req.setKeepAlive(false);\n req.setContentType(\"application\/json\");\n req.set(\"User-Agent\", UserAgent());\n req.setChunkedTransferEncoding(true);\n\n Poco::Net::HTTPBasicCredentials cred(\n basic_auth_username, basic_auth_password);\n if (!basic_auth_username.empty() && !basic_auth_password.empty()) {\n cred.authenticate(req);\n }\n\n std::istringstream requestStream(payload);\n Poco::DeflatingInputStream gzipRequest(\n requestStream,\n Poco::DeflatingStreamBuf::STREAM_GZIP);\n Poco::DeflatingStreamBuf *pBuff = gzipRequest.rdbuf();\n\n Poco::Int64 size = pBuff->pubseekoff(0, std::ios::end, std::ios::in);\n pBuff->pubseekpos(0, std::ios::in);\n\n req.setContentLength(size);\n req.set(\"Content-Encoding\", \"gzip\");\n req.set(\"Accept-Encoding\", \"gzip\");\n\n session.sendRequest(req) << pBuff << std::flush;\n\n \/\/ Log out request contents\n std::stringstream request_string;\n req.write(request_string);\n logger.debug(request_string.str());\n\n logger.debug(\"Request sent. Receiving response..\");\n\n \/\/ Receive response\n Poco::Net::HTTPResponse response;\n std::istream& is = session.receiveResponse(response);\n\n {\n std::stringstream ss;\n ss << \"Response content length \" << response.getContentLength()\n << \", content type \" << response.getContentType();\n if (response.has(\"Content-Encoding\")) {\n ss << \", content encoding \" << response.get(\"Content-Encoding\");\n } else {\n ss << \", unknown content encoding\";\n }\n logger.debug(ss.str());\n }\n\n \/\/ Inflate, if gzip was sent\n if (response.has(\"Content-Encoding\") &&\n \"gzip\" == response.get(\"Content-Encoding\")) {\n Poco::InflatingInputStream inflater(\n is,\n Poco::InflatingStreamBuf::STREAM_GZIP);\n {\n std::stringstream ss;\n ss << inflater.rdbuf();\n *response_body = ss.str();\n }\n } else {\n std::istreambuf_iterator<char> eos;\n *response_body =\n std::string(std::istreambuf_iterator<char>(is), eos);\n }\n\n logger.trace(*response_body);\n\n if (response.getStatus() < 200 || response.getStatus() >= 300) {\n if (response_body->empty()) {\n std::stringstream description;\n description << \"Request to server failed with status code: \"\n << response.getStatus();\n return description.str();\n }\n return \"Data push failed with error: \" + *response_body;\n }\n } catch(const Poco::Exception& exc) {\n return exc.displayText();\n } catch(const std::exception& ex) {\n return ex.what();\n } catch(const std::string& ex) {\n return ex;\n }\n return noError;\n}\n\n} \/\/ namespace kopsik\n<commit_msg>Better wording for failing requests<commit_after>\/\/ Copyright 2014 Toggl Desktop developers.\n\n#include \".\/https_client.h\"\n\n#include <string>\n#include <sstream>\n\n#include \"Poco\/Exception.h\"\n#include \"Poco\/InflatingStream.h\"\n#include \"Poco\/DeflatingStream.h\"\n#include \"Poco\/Logger.h\"\n#include \"Poco\/URI.h\"\n#include \"Poco\/NumberParser.h\"\n#include \"Poco\/Net\/Context.h\"\n#include \"Poco\/Net\/NameValueCollection.h\"\n#include \"Poco\/Net\/HTTPMessage.h\"\n#include \"Poco\/Net\/HTTPBasicCredentials.h\"\n#include \"Poco\/Net\/InvalidCertificateHandler.h\"\n#include \"Poco\/Net\/AcceptCertificateHandler.h\"\n#include \"Poco\/Net\/SSLManager.h\"\n#include \"Poco\/Net\/PrivateKeyPassphraseHandler.h\"\n#include \"Poco\/Net\/SecureStreamSocket.h\"\n\n#include \".\/libjson.h\"\n#include \".\/const.h\"\n\nnamespace kopsik {\n\nstd::string HTTPSClient::AppName = std::string(\"\");\nstd::string HTTPSClient::AppVersion = std::string(\"\");\nstd::string HTTPSClient::APIURL = std::string(kAPIURL);\nbool HTTPSClient::UseProxy = false;\nbool HTTPSClient::IgnoreCert = false;\nkopsik::Proxy HTTPSClient::ProxySettings = Proxy();\n\nerror HTTPSClient::PostJSON(\n const std::string relative_url,\n const std::string json,\n const std::string basic_auth_username,\n const std::string basic_auth_password,\n std::string *response_body) {\n return requestJSON(Poco::Net::HTTPRequest::HTTP_POST,\n relative_url,\n json,\n basic_auth_username,\n basic_auth_password,\n response_body);\n}\n\nerror HTTPSClient::GetJSON(\n const std::string relative_url,\n const std::string basic_auth_username,\n const std::string basic_auth_password,\n std::string *response_body) {\n return requestJSON(Poco::Net::HTTPRequest::HTTP_GET,\n relative_url,\n \"\",\n basic_auth_username,\n basic_auth_password,\n response_body);\n}\n\nerror HTTPSClient::requestJSON(\n const std::string method,\n const std::string relative_url,\n const std::string json,\n const std::string basic_auth_username,\n const std::string basic_auth_password,\n std::string *response_body) {\n return request(\n method,\n relative_url,\n json,\n basic_auth_username,\n basic_auth_password,\n response_body);\n}\n\nerror HTTPSClient::request(\n const std::string method,\n const std::string relative_url,\n const std::string payload,\n const std::string basic_auth_username,\n const std::string basic_auth_password,\n std::string *response_body) {\n\n poco_assert(!method.empty());\n poco_assert(!relative_url.empty());\n\n poco_check_ptr(response_body);\n\n *response_body = \"\";\n\n try {\n Poco::URI uri(APIURL);\n\n Poco::SharedPtr<Poco::Net::InvalidCertificateHandler>\n acceptCertHandler =\n new Poco::Net::AcceptCertificateHandler(true);\n\n Poco::Net::Context::VerificationMode verification_mode =\n Poco::Net::Context::VERIFY_RELAXED;\n if (IgnoreCert) {\n verification_mode = Poco::Net::Context::VERIFY_NONE;\n }\n Poco::Net::Context::Ptr context = new Poco::Net::Context(\n Poco::Net::Context::CLIENT_USE, \"\",\n verification_mode, 9, true, \"ALL\");\n\n Poco::Net::SSLManager::instance().initializeClient(\n 0, acceptCertHandler, context);\n\n Poco::Net::HTTPSClientSession session(uri.getHost(), uri.getPort(),\n context);\n if (ProxySettings.IsConfigured()) {\n session.setProxy(ProxySettings.host, ProxySettings.port);\n if (ProxySettings.HasCredentials()) {\n session.setProxyCredentials(ProxySettings.username,\n ProxySettings.password);\n }\n }\n session.setKeepAlive(false);\n session.setTimeout(Poco::Timespan(10 * Poco::Timespan::SECONDS));\n\n Poco::Logger &logger = Poco::Logger::get(\"https_client\");\n {\n std::stringstream ss;\n ss << \"Sending request to \" << relative_url << \" ..\";\n logger.debug(ss.str());\n }\n\n Poco::Net::HTTPRequest req(method,\n relative_url,\n Poco::Net::HTTPMessage::HTTP_1_1);\n req.setKeepAlive(false);\n req.setContentType(\"application\/json\");\n req.set(\"User-Agent\", UserAgent());\n req.setChunkedTransferEncoding(true);\n\n Poco::Net::HTTPBasicCredentials cred(\n basic_auth_username, basic_auth_password);\n if (!basic_auth_username.empty() && !basic_auth_password.empty()) {\n cred.authenticate(req);\n }\n\n std::istringstream requestStream(payload);\n Poco::DeflatingInputStream gzipRequest(\n requestStream,\n Poco::DeflatingStreamBuf::STREAM_GZIP);\n Poco::DeflatingStreamBuf *pBuff = gzipRequest.rdbuf();\n\n Poco::Int64 size = pBuff->pubseekoff(0, std::ios::end, std::ios::in);\n pBuff->pubseekpos(0, std::ios::in);\n\n req.setContentLength(size);\n req.set(\"Content-Encoding\", \"gzip\");\n req.set(\"Accept-Encoding\", \"gzip\");\n\n session.sendRequest(req) << pBuff << std::flush;\n\n \/\/ Log out request contents\n std::stringstream request_string;\n req.write(request_string);\n logger.debug(request_string.str());\n\n logger.debug(\"Request sent. Receiving response..\");\n\n \/\/ Receive response\n Poco::Net::HTTPResponse response;\n std::istream& is = session.receiveResponse(response);\n\n {\n std::stringstream ss;\n ss << \"Response status code \" << response.getStatus()\n << \", content length \" << response.getContentLength()\n << \", content type \" << response.getContentType();\n if (response.has(\"Content-Encoding\")) {\n ss << \", content encoding \" << response.get(\"Content-Encoding\");\n } else {\n ss << \", unknown content encoding\";\n }\n logger.debug(ss.str());\n }\n\n \/\/ Inflate, if gzip was sent\n if (response.has(\"Content-Encoding\") &&\n \"gzip\" == response.get(\"Content-Encoding\")) {\n Poco::InflatingInputStream inflater(\n is,\n Poco::InflatingStreamBuf::STREAM_GZIP);\n {\n std::stringstream ss;\n ss << inflater.rdbuf();\n *response_body = ss.str();\n }\n } else {\n std::istreambuf_iterator<char> eos;\n *response_body =\n std::string(std::istreambuf_iterator<char>(is), eos);\n }\n\n logger.trace(*response_body);\n\n if (response.getStatus() < 200 || response.getStatus() >= 300) {\n if (response_body->empty()) {\n std::stringstream description;\n description << \"Request to server failed with status code: \"\n << response.getStatus();\n return description.str();\n }\n return \"Request failed with error: \" + *response_body;\n }\n } catch(const Poco::Exception& exc) {\n return exc.displayText();\n } catch(const std::exception& ex) {\n return ex.what();\n } catch(const std::string& ex) {\n return ex;\n }\n return noError;\n}\n\n} \/\/ namespace kopsik\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright © 2012 Intel Corporation\n *\n * Permission is hereby granted, free of charge, to any person obtaining a\n * copy of this software and associated documentation files (the \"Software\"),\n * to deal in the Software without restriction, including without limitation\n * the rights to use, copy, modify, merge, publish, distribute, sublicense,\n * and\/or sell copies of the Software, and to permit persons to whom the\n * Software is furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice (including the next\n * paragraph) shall be included in all copies or substantial portions of the\n * Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n * IN THE SOFTWARE.\n *\/\n\n\/** @file brw_fs_register_coalesce.cpp\n *\n * Implements register coalescing: Checks if the two registers involved in a\n * raw move don't interfere, in which case they can both be stored in the same\n * place and the MOV removed.\n *\n * To do this, all uses of the source of the MOV in the shader are replaced\n * with the destination of the MOV. For example:\n *\n * add vgrf3:F, vgrf1:F, vgrf2:F\n * mov vgrf4:F, vgrf3:F\n * mul vgrf5:F, vgrf5:F, vgrf4:F\n *\n * becomes\n *\n * add vgrf4:F, vgrf1:F, vgrf2:F\n * mul vgrf5:F, vgrf5:F, vgrf4:F\n *\/\n\n#include \"brw_fs.h\"\n#include \"brw_fs_live_variables.h\"\n\nstatic bool\nis_nop_mov(const fs_inst *inst)\n{\n if (inst->opcode == BRW_OPCODE_MOV) {\n return inst->dst.equals(inst->src[0]);\n }\n\n return false;\n}\n\nstatic bool\nis_coalesce_candidate(const fs_inst *inst, const int *virtual_grf_sizes)\n{\n if (inst->opcode != BRW_OPCODE_MOV ||\n inst->is_partial_write() ||\n inst->saturate ||\n inst->src[0].file != GRF ||\n inst->src[0].negate ||\n inst->src[0].abs ||\n !inst->src[0].is_contiguous() ||\n inst->dst.file != GRF ||\n inst->dst.type != inst->src[0].type) {\n return false;\n }\n\n if (virtual_grf_sizes[inst->src[0].reg] >\n virtual_grf_sizes[inst->dst.reg])\n return false;\n\n return true;\n}\n\nstatic bool\ncan_coalesce_vars(brw::fs_live_variables *live_intervals,\n const exec_list *instructions, const fs_inst *inst,\n int var_to, int var_from)\n{\n if (!live_intervals->vars_interfere(var_from, var_to))\n return true;\n\n \/* We know that the live ranges of A (var_from) and B (var_to)\n * interfere because of the ->vars_interfere() call above. If the end\n * of B's live range is after the end of A's range, then we know two\n * things:\n * - the start of B's live range must be in A's live range (since we\n * already know the two ranges interfere, this is the only remaining\n * possibility)\n * - the interference isn't of the form we're looking for (where B is\n * entirely inside A)\n *\/\n if (live_intervals->end[var_to] > live_intervals->end[var_from])\n return false;\n\n int scan_ip = -1;\n\n foreach_list(n, instructions) {\n fs_inst *scan_inst = (fs_inst *)n;\n scan_ip++;\n\n if (scan_inst->is_control_flow())\n return false;\n\n if (scan_ip <= live_intervals->start[var_to])\n continue;\n\n if (scan_ip > live_intervals->end[var_to])\n break;\n\n if (scan_inst->dst.equals(inst->dst) ||\n scan_inst->dst.equals(inst->src[0]))\n return false;\n }\n\n return true;\n}\n\nbool\nfs_visitor::register_coalesce()\n{\n bool progress = false;\n\n calculate_live_intervals();\n\n int src_size = 0;\n int channels_remaining = 0;\n int reg_from = -1, reg_to = -1;\n int reg_to_offset[MAX_SAMPLER_MESSAGE_SIZE];\n fs_inst *mov[MAX_SAMPLER_MESSAGE_SIZE];\n int var_to[MAX_SAMPLER_MESSAGE_SIZE];\n int var_from[MAX_SAMPLER_MESSAGE_SIZE];\n\n foreach_list(node, &this->instructions) {\n fs_inst *inst = (fs_inst *)node;\n\n if (!is_coalesce_candidate(inst, virtual_grf_sizes))\n continue;\n\n if (is_nop_mov(inst)) {\n inst->opcode = BRW_OPCODE_NOP;\n progress = true;\n continue;\n }\n\n if (reg_from != inst->src[0].reg) {\n reg_from = inst->src[0].reg;\n\n src_size = virtual_grf_sizes[inst->src[0].reg];\n assert(src_size <= MAX_SAMPLER_MESSAGE_SIZE);\n\n channels_remaining = src_size;\n memset(mov, 0, sizeof(mov));\n\n reg_to = inst->dst.reg;\n }\n\n if (reg_to != inst->dst.reg)\n continue;\n\n const int offset = inst->src[0].reg_offset;\n reg_to_offset[offset] = inst->dst.reg_offset;\n mov[offset] = inst;\n channels_remaining--;\n\n if (channels_remaining)\n continue;\n\n bool can_coalesce = true;\n for (int i = 0; i < src_size; i++) {\n var_to[i] = live_intervals->var_from_vgrf[reg_to] + reg_to_offset[i];\n var_from[i] = live_intervals->var_from_vgrf[reg_from] + i;\n\n if (!can_coalesce_vars(live_intervals, &instructions, inst,\n var_to[i], var_from[i])) {\n can_coalesce = false;\n reg_from = -1;\n break;\n }\n }\n\n if (!can_coalesce)\n continue;\n\n progress = true;\n\n for (int i = 0; i < src_size; i++) {\n if (mov[i]) {\n mov[i]->opcode = BRW_OPCODE_NOP;\n mov[i]->conditional_mod = BRW_CONDITIONAL_NONE;\n mov[i]->dst = reg_undef;\n mov[i]->src[0] = reg_undef;\n mov[i]->src[1] = reg_undef;\n mov[i]->src[2] = reg_undef;\n }\n }\n\n foreach_list(node, &this->instructions) {\n fs_inst *scan_inst = (fs_inst *)node;\n\n for (int i = 0; i < src_size; i++) {\n if (mov[i]) {\n if (scan_inst->dst.file == GRF &&\n scan_inst->dst.reg == reg_from &&\n scan_inst->dst.reg_offset == i) {\n scan_inst->dst.reg = reg_to;\n scan_inst->dst.reg_offset = reg_to_offset[i];\n }\n for (int j = 0; j < 3; j++) {\n if (scan_inst->src[j].file == GRF &&\n scan_inst->src[j].reg == reg_from &&\n scan_inst->src[j].reg_offset == i) {\n scan_inst->src[j].reg = reg_to;\n scan_inst->src[j].reg_offset = reg_to_offset[i];\n }\n }\n }\n }\n }\n\n for (int i = 0; i < src_size; i++) {\n live_intervals->start[var_to[i]] =\n MIN2(live_intervals->start[var_to[i]],\n live_intervals->start[var_from[i]]);\n live_intervals->end[var_to[i]] =\n MAX2(live_intervals->end[var_to[i]],\n live_intervals->end[var_from[i]]);\n }\n reg_from = -1;\n }\n\n if (progress) {\n foreach_list_safe(node, &this->instructions) {\n fs_inst *inst = (fs_inst *)node;\n\n if (inst->opcode == BRW_OPCODE_NOP) {\n inst->remove();\n }\n }\n\n invalidate_live_intervals();\n }\n\n return progress;\n}\n<commit_msg>i965\/fs: Simplify interference scan in register coalescing.<commit_after>\/*\n * Copyright © 2012 Intel Corporation\n *\n * Permission is hereby granted, free of charge, to any person obtaining a\n * copy of this software and associated documentation files (the \"Software\"),\n * to deal in the Software without restriction, including without limitation\n * the rights to use, copy, modify, merge, publish, distribute, sublicense,\n * and\/or sell copies of the Software, and to permit persons to whom the\n * Software is furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice (including the next\n * paragraph) shall be included in all copies or substantial portions of the\n * Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n * IN THE SOFTWARE.\n *\/\n\n\/** @file brw_fs_register_coalesce.cpp\n *\n * Implements register coalescing: Checks if the two registers involved in a\n * raw move don't interfere, in which case they can both be stored in the same\n * place and the MOV removed.\n *\n * To do this, all uses of the source of the MOV in the shader are replaced\n * with the destination of the MOV. For example:\n *\n * add vgrf3:F, vgrf1:F, vgrf2:F\n * mov vgrf4:F, vgrf3:F\n * mul vgrf5:F, vgrf5:F, vgrf4:F\n *\n * becomes\n *\n * add vgrf4:F, vgrf1:F, vgrf2:F\n * mul vgrf5:F, vgrf5:F, vgrf4:F\n *\/\n\n#include \"brw_fs.h\"\n#include \"brw_fs_live_variables.h\"\n\nstatic bool\nis_nop_mov(const fs_inst *inst)\n{\n if (inst->opcode == BRW_OPCODE_MOV) {\n return inst->dst.equals(inst->src[0]);\n }\n\n return false;\n}\n\nstatic bool\nis_coalesce_candidate(const fs_inst *inst, const int *virtual_grf_sizes)\n{\n if (inst->opcode != BRW_OPCODE_MOV ||\n inst->is_partial_write() ||\n inst->saturate ||\n inst->src[0].file != GRF ||\n inst->src[0].negate ||\n inst->src[0].abs ||\n !inst->src[0].is_contiguous() ||\n inst->dst.file != GRF ||\n inst->dst.type != inst->src[0].type) {\n return false;\n }\n\n if (virtual_grf_sizes[inst->src[0].reg] >\n virtual_grf_sizes[inst->dst.reg])\n return false;\n\n return true;\n}\n\nstatic bool\ncan_coalesce_vars(brw::fs_live_variables *live_intervals,\n const exec_list *instructions, const fs_inst *inst, int ip,\n int var_to, int var_from)\n{\n if (!live_intervals->vars_interfere(var_from, var_to))\n return true;\n\n \/* We know that the live ranges of A (var_from) and B (var_to)\n * interfere because of the ->vars_interfere() call above. If the end\n * of B's live range is after the end of A's range, then we know two\n * things:\n * - the start of B's live range must be in A's live range (since we\n * already know the two ranges interfere, this is the only remaining\n * possibility)\n * - the interference isn't of the form we're looking for (where B is\n * entirely inside A)\n *\/\n if (live_intervals->end[var_to] > live_intervals->end[var_from])\n return false;\n\n assert(ip >= live_intervals->start[var_to]);\n\n fs_inst *scan_inst;\n for (scan_inst = (fs_inst *)inst->next;\n !scan_inst->is_tail_sentinel() && ip <= live_intervals->end[var_to];\n scan_inst = (fs_inst *)scan_inst->next, ip++) {\n if (scan_inst->is_control_flow())\n return false;\n\n if (scan_inst->dst.equals(inst->dst) ||\n scan_inst->dst.equals(inst->src[0]))\n return false;\n }\n\n return true;\n}\n\nbool\nfs_visitor::register_coalesce()\n{\n bool progress = false;\n\n calculate_live_intervals();\n\n int src_size = 0;\n int channels_remaining = 0;\n int reg_from = -1, reg_to = -1;\n int reg_to_offset[MAX_SAMPLER_MESSAGE_SIZE];\n fs_inst *mov[MAX_SAMPLER_MESSAGE_SIZE];\n int var_to[MAX_SAMPLER_MESSAGE_SIZE];\n int var_from[MAX_SAMPLER_MESSAGE_SIZE];\n int ip = -1;\n\n foreach_list(node, &this->instructions) {\n fs_inst *inst = (fs_inst *)node;\n ip++;\n\n if (!is_coalesce_candidate(inst, virtual_grf_sizes))\n continue;\n\n if (is_nop_mov(inst)) {\n inst->opcode = BRW_OPCODE_NOP;\n progress = true;\n continue;\n }\n\n if (reg_from != inst->src[0].reg) {\n reg_from = inst->src[0].reg;\n\n src_size = virtual_grf_sizes[inst->src[0].reg];\n assert(src_size <= MAX_SAMPLER_MESSAGE_SIZE);\n\n channels_remaining = src_size;\n memset(mov, 0, sizeof(mov));\n\n reg_to = inst->dst.reg;\n }\n\n if (reg_to != inst->dst.reg)\n continue;\n\n const int offset = inst->src[0].reg_offset;\n reg_to_offset[offset] = inst->dst.reg_offset;\n mov[offset] = inst;\n channels_remaining--;\n\n if (channels_remaining)\n continue;\n\n bool can_coalesce = true;\n for (int i = 0; i < src_size; i++) {\n var_to[i] = live_intervals->var_from_vgrf[reg_to] + reg_to_offset[i];\n var_from[i] = live_intervals->var_from_vgrf[reg_from] + i;\n\n if (!can_coalesce_vars(live_intervals, &instructions, inst, ip,\n var_to[i], var_from[i])) {\n can_coalesce = false;\n reg_from = -1;\n break;\n }\n }\n\n if (!can_coalesce)\n continue;\n\n progress = true;\n\n for (int i = 0; i < src_size; i++) {\n if (mov[i]) {\n mov[i]->opcode = BRW_OPCODE_NOP;\n mov[i]->conditional_mod = BRW_CONDITIONAL_NONE;\n mov[i]->dst = reg_undef;\n mov[i]->src[0] = reg_undef;\n mov[i]->src[1] = reg_undef;\n mov[i]->src[2] = reg_undef;\n }\n }\n\n foreach_list(node, &this->instructions) {\n fs_inst *scan_inst = (fs_inst *)node;\n\n for (int i = 0; i < src_size; i++) {\n if (mov[i]) {\n if (scan_inst->dst.file == GRF &&\n scan_inst->dst.reg == reg_from &&\n scan_inst->dst.reg_offset == i) {\n scan_inst->dst.reg = reg_to;\n scan_inst->dst.reg_offset = reg_to_offset[i];\n }\n for (int j = 0; j < 3; j++) {\n if (scan_inst->src[j].file == GRF &&\n scan_inst->src[j].reg == reg_from &&\n scan_inst->src[j].reg_offset == i) {\n scan_inst->src[j].reg = reg_to;\n scan_inst->src[j].reg_offset = reg_to_offset[i];\n }\n }\n }\n }\n }\n\n for (int i = 0; i < src_size; i++) {\n live_intervals->start[var_to[i]] =\n MIN2(live_intervals->start[var_to[i]],\n live_intervals->start[var_from[i]]);\n live_intervals->end[var_to[i]] =\n MAX2(live_intervals->end[var_to[i]],\n live_intervals->end[var_from[i]]);\n }\n reg_from = -1;\n }\n\n if (progress) {\n foreach_list_safe(node, &this->instructions) {\n fs_inst *inst = (fs_inst *)node;\n\n if (inst->opcode == BRW_OPCODE_NOP) {\n inst->remove();\n }\n }\n\n invalidate_live_intervals();\n }\n\n return progress;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/===-- tsan_suppressions.cc ------------------------------------*- C++ -*-===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This file is a part of ThreadSanitizer (TSan), a race detector.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"tsan_suppressions.h\"\n#include \"tsan_rtl.h\"\n#include \"tsan_flags.h\"\n#include \"tsan_mman.h\"\n#include \"tsan_platform.h\"\n\nnamespace __tsan {\n\nstatic Suppression *g_suppressions;\n\nstatic char *ReadFile(const char *filename) {\n if (filename == 0 || filename[0] == 0)\n return 0;\n InternalScopedBuf<char> tmp(4*1024);\n if (filename[0] == '\/')\n Snprintf(tmp, tmp.Size(), \"%s\", filename);\n else\n Snprintf(tmp, tmp.Size(), \"%s\/%s\", internal_getpwd(), filename);\n fd_t fd = internal_open(tmp, false);\n if (fd == kInvalidFd) {\n Printf(\"ThreadSanitizer: failed to open suppressions file '%s'\\n\",\n tmp.Ptr());\n Die();\n }\n const uptr fsize = internal_filesize(fd);\n if (fsize == (uptr)-1) {\n Printf(\"ThreadSanitizer: failed to stat suppressions file '%s'\\n\",\n tmp.Ptr());\n Die();\n }\n char *buf = (char*)internal_alloc(MBlockSuppression, fsize + 1);\n if (fsize != internal_read(fd, buf, fsize)) {\n Printf(\"ThreadSanitizer: failed to read suppressions file '%s'\\n\",\n tmp.Ptr());\n Die();\n }\n internal_close(fd);\n buf[fsize] = 0;\n return buf;\n}\n\nbool SuppressionMatch(char *templ, const char *str) {\n if (str == 0 || str[0] == 0)\n return false;\n char *tpos;\n const char *spos;\n while (templ && templ[0]) {\n if (templ[0] == '*') {\n templ++;\n continue;\n }\n if (str[0] == 0)\n return false;\n tpos = (char*)internal_strchr(templ, '*');\n if (tpos != 0)\n tpos[0] = 0;\n spos = internal_strstr(str, templ);\n str = spos + internal_strlen(templ);\n templ = tpos;\n if (tpos)\n tpos[0] = '*';\n if (spos == 0)\n return false;\n }\n return true;\n}\n\nSuppression *SuppressionParse(const char* supp) {\n Suppression *head = 0;\n const char *line = supp;\n while (line) {\n while (line[0] == ' ' || line[0] == '\\t')\n line++;\n const char *end = internal_strchr(line, '\\n');\n if (end == 0)\n end = line + internal_strlen(line);\n if (line != end && line[0] != '#') {\n const char *end2 = end;\n while (line != end2 && (end2[-1] == ' ' || end2[-1] == '\\t'))\n end2--;\n SuppressionType stype;\n if (0 == internal_strncmp(line, \"race:\", sizeof(\"race:\") - 1)) {\n stype = SuppressionRace;\n line += sizeof(\"race:\") - 1;\n } else if (0 == internal_strncmp(line, \"thread:\",\n sizeof(\"thread:\") - 1)) {\n stype = SuppressionThread;\n line += sizeof(\"thread:\") - 1;\n } else if (0 == internal_strncmp(line, \"mutex:\",\n sizeof(\"mutex:\") - 1)) {\n stype = SuppressionMutex;\n line += sizeof(\"mutex:\") - 1;\n } else if (0 == internal_strncmp(line, \"signal:\",\n sizeof(\"signal:\") - 1)) {\n stype = SuppressionSignal;\n line += sizeof(\"signal:\") - 1;\n } else {\n Printf(\"ThreadSanitizer: failed to parse suppressions file\\n\");\n Die();\n }\n Suppression *s = (Suppression*)internal_alloc(MBlockSuppression,\n sizeof(Suppression));\n s->next = head;\n head = s;\n s->type = stype;\n s->templ = (char*)internal_alloc(MBlockSuppression, end2 - line + 1);\n internal_memcpy(s->templ, line, end2 - line);\n s->templ[end2 - line] = 0;\n }\n if (end[0] == 0)\n break;\n line = end + 1;\n }\n return head;\n}\n\nvoid InitializeSuppressions() {\n char *supp = ReadFile(flags()->suppressions);\n g_suppressions = SuppressionParse(supp);\n}\n\nbool IsSuppressed(ReportType typ, const ReportStack *stack) {\n if (g_suppressions == 0 || stack == 0)\n return false;\n SuppressionType stype;\n if (typ == ReportTypeRace)\n stype = SuppressionRace;\n else if (typ == ReportTypeThreadLeak)\n stype = SuppressionThread;\n else if (typ == ReportTypeMutexDestroyLocked)\n stype = SuppressionMutex;\n else if (typ == ReportTypeSignalUnsafe)\n stype = SuppressionSignal;\n else\n return false;\n for (const ReportStack *frame = stack; frame; frame = frame->next) {\n for (Suppression *supp = g_suppressions; supp; supp = supp->next) {\n if (stype == supp->type ||\n SuppressionMatch(supp->templ, frame->func) ||\n SuppressionMatch(supp->templ, frame->file)) {\n DPrintf(\"ThreadSanitizer: matched suppression '%s'\\n\", supp->templ);\n return true;\n }\n }\n }\n return false;\n}\n} \/\/ namespace __tsan\n<commit_msg>tsan: fix a typo<commit_after>\/\/===-- tsan_suppressions.cc ------------------------------------*- C++ -*-===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This file is a part of ThreadSanitizer (TSan), a race detector.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"tsan_suppressions.h\"\n#include \"tsan_rtl.h\"\n#include \"tsan_flags.h\"\n#include \"tsan_mman.h\"\n#include \"tsan_platform.h\"\n\nnamespace __tsan {\n\nstatic Suppression *g_suppressions;\n\nstatic char *ReadFile(const char *filename) {\n if (filename == 0 || filename[0] == 0)\n return 0;\n InternalScopedBuf<char> tmp(4*1024);\n if (filename[0] == '\/')\n Snprintf(tmp, tmp.Size(), \"%s\", filename);\n else\n Snprintf(tmp, tmp.Size(), \"%s\/%s\", internal_getpwd(), filename);\n fd_t fd = internal_open(tmp, false);\n if (fd == kInvalidFd) {\n Printf(\"ThreadSanitizer: failed to open suppressions file '%s'\\n\",\n tmp.Ptr());\n Die();\n }\n const uptr fsize = internal_filesize(fd);\n if (fsize == (uptr)-1) {\n Printf(\"ThreadSanitizer: failed to stat suppressions file '%s'\\n\",\n tmp.Ptr());\n Die();\n }\n char *buf = (char*)internal_alloc(MBlockSuppression, fsize + 1);\n if (fsize != internal_read(fd, buf, fsize)) {\n Printf(\"ThreadSanitizer: failed to read suppressions file '%s'\\n\",\n tmp.Ptr());\n Die();\n }\n internal_close(fd);\n buf[fsize] = 0;\n return buf;\n}\n\nbool SuppressionMatch(char *templ, const char *str) {\n if (str == 0 || str[0] == 0)\n return false;\n char *tpos;\n const char *spos;\n while (templ && templ[0]) {\n if (templ[0] == '*') {\n templ++;\n continue;\n }\n if (str[0] == 0)\n return false;\n tpos = (char*)internal_strchr(templ, '*');\n if (tpos != 0)\n tpos[0] = 0;\n spos = internal_strstr(str, templ);\n str = spos + internal_strlen(templ);\n templ = tpos;\n if (tpos)\n tpos[0] = '*';\n if (spos == 0)\n return false;\n }\n return true;\n}\n\nSuppression *SuppressionParse(const char* supp) {\n Suppression *head = 0;\n const char *line = supp;\n while (line) {\n while (line[0] == ' ' || line[0] == '\\t')\n line++;\n const char *end = internal_strchr(line, '\\n');\n if (end == 0)\n end = line + internal_strlen(line);\n if (line != end && line[0] != '#') {\n const char *end2 = end;\n while (line != end2 && (end2[-1] == ' ' || end2[-1] == '\\t'))\n end2--;\n SuppressionType stype;\n if (0 == internal_strncmp(line, \"race:\", sizeof(\"race:\") - 1)) {\n stype = SuppressionRace;\n line += sizeof(\"race:\") - 1;\n } else if (0 == internal_strncmp(line, \"thread:\",\n sizeof(\"thread:\") - 1)) {\n stype = SuppressionThread;\n line += sizeof(\"thread:\") - 1;\n } else if (0 == internal_strncmp(line, \"mutex:\",\n sizeof(\"mutex:\") - 1)) {\n stype = SuppressionMutex;\n line += sizeof(\"mutex:\") - 1;\n } else if (0 == internal_strncmp(line, \"signal:\",\n sizeof(\"signal:\") - 1)) {\n stype = SuppressionSignal;\n line += sizeof(\"signal:\") - 1;\n } else {\n Printf(\"ThreadSanitizer: failed to parse suppressions file\\n\");\n Die();\n }\n Suppression *s = (Suppression*)internal_alloc(MBlockSuppression,\n sizeof(Suppression));\n s->next = head;\n head = s;\n s->type = stype;\n s->templ = (char*)internal_alloc(MBlockSuppression, end2 - line + 1);\n internal_memcpy(s->templ, line, end2 - line);\n s->templ[end2 - line] = 0;\n }\n if (end[0] == 0)\n break;\n line = end + 1;\n }\n return head;\n}\n\nvoid InitializeSuppressions() {\n char *supp = ReadFile(flags()->suppressions);\n g_suppressions = SuppressionParse(supp);\n}\n\nbool IsSuppressed(ReportType typ, const ReportStack *stack) {\n if (g_suppressions == 0 || stack == 0)\n return false;\n SuppressionType stype;\n if (typ == ReportTypeRace)\n stype = SuppressionRace;\n else if (typ == ReportTypeThreadLeak)\n stype = SuppressionThread;\n else if (typ == ReportTypeMutexDestroyLocked)\n stype = SuppressionMutex;\n else if (typ == ReportTypeSignalUnsafe)\n stype = SuppressionSignal;\n else\n return false;\n for (const ReportStack *frame = stack; frame; frame = frame->next) {\n for (Suppression *supp = g_suppressions; supp; supp = supp->next) {\n if (stype == supp->type &&\n (SuppressionMatch(supp->templ, frame->func) ||\n SuppressionMatch(supp->templ, frame->file))) {\n DPrintf(\"ThreadSanitizer: matched suppression '%s'\\n\", supp->templ);\n return true;\n }\n }\n }\n return false;\n}\n} \/\/ namespace __tsan\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2013 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"base\/basictypes.h\"\n#include \"base\/command_line.h\"\n#include \"base\/string16.h\"\n#include \"base\/string_util.h\"\n#include \"base\/stringprintf.h\"\n#include \"base\/utf_string_conversions.h\"\n#include \"content\/public\/common\/content_switches.h\"\n#include \"content\/public\/test\/browser_test_utils.h\"\n#include \"content\/shell\/shell.h\"\n#include \"content\/test\/content_browser_test_utils.h\"\n#include \"content\/test\/layout_browsertest.h\"\n#include \"googleurl\/src\/gurl.h\"\n\n\/\/ Common media types.\nstatic const char kWebMAudioOnly[] = \"audio\/webm; codecs=\\\"vorbis\\\"\";\nstatic const char kWebMVideoOnly[] = \"video\/webm; codecs=\\\"vp8\\\"\";\nstatic const char kWebMAudioVideo[] = \"video\/webm; codecs=\\\"vorbis, vp8\\\"\";\n\n\/\/ Common test expectations.\nconst string16 kEnded = ASCIIToUTF16(\"ENDED\");\nconst string16 kError = ASCIIToUTF16(\"ERROR\");\nconst string16 kFailed = ASCIIToUTF16(\"FAILED\");\n\nnamespace content {\n\nclass MediaSourceTest : public ContentBrowserTest {\n public:\n void TestSimplePlayback(const char* media_file, const char* media_type,\n const string16 expectation) {\n ASSERT_NO_FATAL_FAILURE(\n RunTest(\"media_source_player.html\", media_file, media_type,\n expectation));\n }\n\n void RunTest(const char* html_page, const char* media_file,\n const char* media_type, const string16 expectation) {\n ASSERT_TRUE(test_server()->Start());\n GURL player_gurl = test_server()->GetURL(base::StringPrintf(\n \"files\/media\/%s?mediafile=%s&mediatype=%s\", html_page, media_file,\n media_type));\n TitleWatcher title_watcher(shell()->web_contents(), expectation);\n title_watcher.AlsoWaitForTitle(kError);\n title_watcher.AlsoWaitForTitle(kFailed);\n\n NavigateToURL(shell(), player_gurl);\n string16 final_title = title_watcher.WaitAndGetTitle();\n EXPECT_EQ(expectation, final_title);\n\n if (final_title == kFailed) {\n std::string fail_message;\n EXPECT_TRUE(ExecuteScriptAndExtractString(\n shell()->web_contents(),\n \"window.domAutomationController.send(failMessage);\",\n &fail_message));\n LOG(INFO) << \"Test failed: \" << fail_message;\n }\n }\n};\n\nIN_PROC_BROWSER_TEST_F(MediaSourceTest, Playback_VideoAudio_WebM) {\n TestSimplePlayback(\"bear-320x240.webm\", kWebMAudioVideo, kEnded);\n}\n\nIN_PROC_BROWSER_TEST_F(MediaSourceTest, Playback_VideoOnly_WebM) {\n TestSimplePlayback(\"bear-320x240-video-only.webm\", kWebMVideoOnly, kEnded);\n}\n\nIN_PROC_BROWSER_TEST_F(MediaSourceTest, Playback_AudioOnly_WebM) {\n TestSimplePlayback(\"bear-320x240-audio-only.webm\", kWebMAudioOnly, kEnded);\n}\n\nIN_PROC_BROWSER_TEST_F(MediaSourceTest, Playback_Type_Error) {\n TestSimplePlayback(\"bear-320x240-video-only.webm\", kWebMAudioOnly, kError);\n}\n\nIN_PROC_BROWSER_TEST_F(MediaSourceTest, ConfigChangeVideo) {\n ASSERT_NO_FATAL_FAILURE(\n RunTest(\"mse_config_change.html\", NULL, NULL, kEnded));\n}\n\n} \/\/ namespace content<commit_msg>Disable ConfigChangeVideo test.<commit_after>\/\/ Copyright (c) 2013 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"base\/basictypes.h\"\n#include \"base\/command_line.h\"\n#include \"base\/string16.h\"\n#include \"base\/string_util.h\"\n#include \"base\/stringprintf.h\"\n#include \"base\/utf_string_conversions.h\"\n#include \"content\/public\/common\/content_switches.h\"\n#include \"content\/public\/test\/browser_test_utils.h\"\n#include \"content\/shell\/shell.h\"\n#include \"content\/test\/content_browser_test_utils.h\"\n#include \"content\/test\/layout_browsertest.h\"\n#include \"googleurl\/src\/gurl.h\"\n\n\/\/ Common media types.\nstatic const char kWebMAudioOnly[] = \"audio\/webm; codecs=\\\"vorbis\\\"\";\nstatic const char kWebMVideoOnly[] = \"video\/webm; codecs=\\\"vp8\\\"\";\nstatic const char kWebMAudioVideo[] = \"video\/webm; codecs=\\\"vorbis, vp8\\\"\";\n\n\/\/ Common test expectations.\nconst string16 kEnded = ASCIIToUTF16(\"ENDED\");\nconst string16 kError = ASCIIToUTF16(\"ERROR\");\nconst string16 kFailed = ASCIIToUTF16(\"FAILED\");\n\nnamespace content {\n\nclass MediaSourceTest : public ContentBrowserTest {\n public:\n void TestSimplePlayback(const char* media_file, const char* media_type,\n const string16 expectation) {\n ASSERT_NO_FATAL_FAILURE(\n RunTest(\"media_source_player.html\", media_file, media_type,\n expectation));\n }\n\n void RunTest(const char* html_page, const char* media_file,\n const char* media_type, const string16 expectation) {\n ASSERT_TRUE(test_server()->Start());\n GURL player_gurl = test_server()->GetURL(base::StringPrintf(\n \"files\/media\/%s?mediafile=%s&mediatype=%s\", html_page, media_file,\n media_type));\n TitleWatcher title_watcher(shell()->web_contents(), expectation);\n title_watcher.AlsoWaitForTitle(kError);\n title_watcher.AlsoWaitForTitle(kFailed);\n\n NavigateToURL(shell(), player_gurl);\n string16 final_title = title_watcher.WaitAndGetTitle();\n EXPECT_EQ(expectation, final_title);\n\n if (final_title == kFailed) {\n std::string fail_message;\n EXPECT_TRUE(ExecuteScriptAndExtractString(\n shell()->web_contents(),\n \"window.domAutomationController.send(failMessage);\",\n &fail_message));\n LOG(INFO) << \"Test failed: \" << fail_message;\n }\n }\n};\n\nIN_PROC_BROWSER_TEST_F(MediaSourceTest, Playback_VideoAudio_WebM) {\n TestSimplePlayback(\"bear-320x240.webm\", kWebMAudioVideo, kEnded);\n}\n\nIN_PROC_BROWSER_TEST_F(MediaSourceTest, Playback_VideoOnly_WebM) {\n TestSimplePlayback(\"bear-320x240-video-only.webm\", kWebMVideoOnly, kEnded);\n}\n\nIN_PROC_BROWSER_TEST_F(MediaSourceTest, Playback_AudioOnly_WebM) {\n TestSimplePlayback(\"bear-320x240-audio-only.webm\", kWebMAudioOnly, kEnded);\n}\n\nIN_PROC_BROWSER_TEST_F(MediaSourceTest, Playback_Type_Error) {\n TestSimplePlayback(\"bear-320x240-video-only.webm\", kWebMAudioOnly, kError);\n}\n\nIN_PROC_BROWSER_TEST_F(MediaSourceTest, DISABLED_ConfigChangeVideo) {\n ASSERT_NO_FATAL_FAILURE(\n RunTest(\"mse_config_change.html\", NULL, NULL, kEnded));\n}\n\n} \/\/ namespace content<|endoftext|>"} {"text":"<commit_before><commit_msg>fixed bug when trackers are removed from torrent<commit_after><|endoftext|>"} {"text":"<commit_before>\/*\n FILNAMN: \t\tNetClient.cc\n PROGRAMMERARE:\thanel742, eriek984, jened502, tobgr602, niker917, davha227\n SKAPAD DATUM:\t2013-11-19\n BESKRIVNING:\n *\/\n\n#include \"NetClient.h\"\n#include \"..\/gui\/gui.h\"\n\nusing namespace std;\n\nNetClient::NetClient(QString username, QString inAddress, Gui* myGui, QObject *parent) : QObject(parent){\n \n guiPointer = myGui;\n name=username;\n address=inAddress;\n compare += 0x1F;\n breaker +=0x1E;\n}\n\n\/\/ ---------------------------------------------\n\nvoid NetClient::start(){\n TcpSocket = new QTcpSocket(this);\n \n connect(TcpSocket,SIGNAL(connected()),this,SLOT(connected()));\n connect(TcpSocket,SIGNAL(disconnected()),this,SLOT(disconnected()));\n connect(TcpSocket,SIGNAL(readyRead()),this,SLOT(readyRead()));\n \n QHostInfo info = QHostInfo::fromName(address);\n \n if (info.addresses().size() == 0){\n guiPointer->noConnection();\n }\n else{\n TcpSocket->connectToHost(info.addresses().at(0),quint16(40001));\n if(!TcpSocket->waitForConnected(1000)){\n guiPointer->noConnection();\n }\n }\n}\n\n\n\/\/------Slots---------\n\nvoid NetClient::connected(){\n QByteArray array = \"\/initiate\";\n array += 0x1F; \/\/unit separator\n array += name;\n array += breaker;\n \n TcpSocket->write(array);\n TcpSocket->waitForBytesWritten(1000);\n}\n\nvoid NetClient::disconnected(){\n guiPointer->disconnectedFromServer();\n \n}\n\n\/\/ --------readyRead------------------\n\nvoid NetClient::readyRead(){\n \n QString inData = \"\";\n \n if( not(incompleteCommand.isEmpty())){\n inData = incompleteCommand;\n cout << \"old command exists\" << endl;\n incompleteCommand = \"\";\n }\n QByteArray Data = TcpSocket->readAll();\n \n QString commandName = \"\";\n inData += Data;\n QString rest = \"\";\n int n = inData.indexOf(breaker);\n int i;\n int p = 0;\n \n \n if(inData.indexOf(breaker) == -1 ){\n cout << \"breaker missing \" << endl;\n incompleteCommand = inData;\n return;\n }\n \n do {\n \n rest = inData.mid(n+1);\n inData = inData.left(n);\n i = inData.indexOf(compare);\n cout << p << endl;\n commandName = inData.left(i);\n \n p = p + 1;\n inData = inData.mid(i+1);\n \n QString temp = inData;\n string stdInData = temp.toStdString();\n \n \/\/ Check which command that's supposed to run\n if (commandName == \"\/reinitiate\") {\n guiPointer->userNameTaken();\n break;\n }\n \n else if ( commandName == \"\/userAccepted\") {\n guiPointer->connected();\n }\n \n else if (commandName == \"\/history\") {\n handleHistory(inData);\n }\n \n else if (commandName == \"\/oldHistory\") {\n handleOldHistory(inData);\n }\n \n else if (commandName == \"\/message\") {\n handleMessage(inData);\n }\n \n else if ( commandName == \"\/requestStruct\") {\n handleRequestStruct();\n }\n \n else if ( commandName == \"\/structure\" ) {\n handleStructure(inData);\n }\n \n else {\n \n throw logic_error(\"Unknown command: \" + commandName.toStdString());\n }\n \n inData = rest;\n n = inData.indexOf(breaker);\n commandName = \"\";\n \n }while (n != -1 );\n}\n\n\/\/ ---------------------------------------------\n\nvoid NetClient::sendMessage(QString from, QString to, QString message){\n QByteArray array = \"\/message\";\n array += 0x1F; \/\/unit separator\n array += from;\n array += 0x1F;\n array += to;\n array += 0x1F;\n array += message;\n array += breaker;\n \n TcpSocket->write(array);\n TcpSocket->waitForBytesWritten(1000);\n}\n\nvoid NetClient::setName(QString inName) {\n name=inName;\n}\n\nvoid NetClient::getStruct(){\n QByteArray array = \"\/structure\";\n array += 0x1E;\n \n TcpSocket->write(array);\n TcpSocket->waitForBytesWritten(1000);\n}\n\n\/\/--------------------------------------------\n\/\/Helpfunctions\n\nvoid NetClient::handleRequestStruct(){\n QByteArray array = \"\/structure\";\n array += compare;\n array += breaker;\n \n TcpSocket->write(array);\n TcpSocket->waitForBytesWritten(1000);\n}\n\n\/\/ ---------------------------------------------\n\nvoid NetClient::handleMessage(QString inData){\n \n int i;\n \/\/ Get from\n i = inData.indexOf(compare);\n QString from = inData.left(i);\n inData = inData.mid(i+1);\n \n \/\/ Get to\n i = inData.indexOf(compare);\n QString to = inData.left(i);\n inData = inData.mid(i+1);\n \n \/\/ Get message\n i = inData.indexOf(compare);\n QString contents = inData.left(i);\n inData = inData.mid(i+1);\n \n \/\/ Get time\n QString dateTime = inData;\n \n \/\/Send message to Gui\n guiPointer->receiveMessage(from, to, contents, dateTime);\n \n}\n\n\/\/ ---------------------------------------------\n\nvoid NetClient::handleHistory(QString inData){\n QVector<QString> history;\n int i = inData.indexOf(compare);\n while(i != -1 ){\n \n \/\/ Get from\n i = inData.indexOf(compare);\n QString from = inData.left(i);\n inData = inData.mid(i+1);\n history.push_back(from);\n \n \/\/ Get to\n i = inData.indexOf(compare);\n QString to = inData.left(i);\n inData = inData.mid(i+1);\n history.push_back(to);\n \n \/\/ Get message\n i = inData.indexOf(compare);\n QString contents = inData.left(i);\n inData = inData.mid(i+1);\n history.push_back(contents);\n \n \n \/\/Get time\n i = inData.indexOf(compare);\n QString time = inData.left(i);\n inData = inData.mid(i+1);\n history.push_back(time);\n }\n guiPointer->receiveHistory(history);\n}\n\n\/\/ ---------------------------------------------\n\nvoid NetClient::handleOldHistory(QString inData){\n QVector<QString> history;\n int i = inData.indexOf(compare);\n while(i != -1 ){\n \n \/\/ Get from\n i = inData.indexOf(compare);\n QString from = inData.left(i);\n inData = inData.mid(i+1);\n history.push_back(from);\n \n \/\/ Get to\n i = inData.indexOf(compare);\n QString to = inData.left(i);\n inData = inData.mid(i+1);\n history.push_back(to);\n \n \/\/ Get message\n i = inData.indexOf(compare);\n QString contents = inData.left(i);\n inData = inData.mid(i+1);\n history.push_back(contents);\n \n \n \/\/Get time\n i = inData.indexOf(compare);\n QString time = inData.left(i);\n inData = inData.mid(i+1);\n history.push_back(time);\n }\n guiPointer->receiveOldHistory(history);\n}\n\n\/\/ ---------------------------------------------\n\nvoid NetClient::handleStructure(QString inData){\n QVector<QString> output;\n int i = inData.indexOf(compare);\n \n while(i != -1){\n \/\/Create vector output, containing room content structure\n QString data = inData.left(i);\n inData = inData.mid(i+1);\n output.push_back(data);\n \n i = inData.indexOf(compare);\n }\n \n output.push_back(inData);\n \n guiPointer->updateStruct(output);\n \n}\n\n\/\/ ---------------------------------------------\n\nvoid NetClient::getHistory(unsigned int daysBack) {\n QString temp;\n string daysBackString = to_string(daysBack);\n \n temp = QString::fromStdString(daysBackString);\n \n QByteArray array = \"\/oldHistory\";\n array += compare; \/\/unit separator\n array += temp;\n array += breaker;\n \n TcpSocket->write(array);\n TcpSocket->waitForBytesWritten(1000);\n}\n\n\n<commit_msg>NetClient non-crash on unknown commands for release version<commit_after>\/*\n FILNAMN: \t\tNetClient.cc\n PROGRAMMERARE:\thanel742, eriek984, jened502, tobgr602, niker917, davha227\n SKAPAD DATUM:\t2013-11-19\n BESKRIVNING:\n *\/\n\n#include \"NetClient.h\"\n#include \"..\/gui\/gui.h\"\n\nusing namespace std;\n\nNetClient::NetClient(QString username, QString inAddress, Gui* myGui, QObject *parent) : QObject(parent){\n \n guiPointer = myGui;\n name=username;\n address=inAddress;\n compare += 0x1F;\n breaker +=0x1E;\n}\n\n\/\/ ---------------------------------------------\n\nvoid NetClient::start(){\n TcpSocket = new QTcpSocket(this);\n \n connect(TcpSocket,SIGNAL(connected()),this,SLOT(connected()));\n connect(TcpSocket,SIGNAL(disconnected()),this,SLOT(disconnected()));\n connect(TcpSocket,SIGNAL(readyRead()),this,SLOT(readyRead()));\n \n QHostInfo info = QHostInfo::fromName(address);\n \n if (info.addresses().size() == 0){\n guiPointer->noConnection();\n }\n else{\n TcpSocket->connectToHost(info.addresses().at(0),quint16(40001));\n if(!TcpSocket->waitForConnected(1000)){\n guiPointer->noConnection();\n }\n }\n}\n\n\n\/\/------Slots---------\n\nvoid NetClient::connected(){\n QByteArray array = \"\/initiate\";\n array += 0x1F; \/\/unit separator\n array += name;\n array += breaker;\n \n TcpSocket->write(array);\n TcpSocket->waitForBytesWritten(1000);\n}\n\nvoid NetClient::disconnected(){\n guiPointer->disconnectedFromServer();\n \n}\n\n\/\/ --------readyRead------------------\n\nvoid NetClient::readyRead(){\n \n QString inData = \"\";\n \n if( not(incompleteCommand.isEmpty())){\n inData = incompleteCommand;\n cout << \"old command exists\" << endl;\n incompleteCommand = \"\";\n }\n QByteArray Data = TcpSocket->readAll();\n \n QString commandName = \"\";\n inData += Data;\n QString rest = \"\";\n int n = inData.indexOf(breaker);\n int i;\n int p = 0;\n \n \n if(inData.indexOf(breaker) == -1 ){\n cout << \"breaker missing \" << endl;\n incompleteCommand = inData;\n return;\n }\n \n do {\n \n rest = inData.mid(n+1);\n inData = inData.left(n);\n i = inData.indexOf(compare);\n cout << p << endl;\n commandName = inData.left(i);\n \n p = p + 1;\n inData = inData.mid(i+1);\n \n QString temp = inData;\n string stdInData = temp.toStdString();\n \n \/\/ Check which command that's supposed to run\n if (commandName == \"\/reinitiate\") {\n guiPointer->userNameTaken();\n break;\n }\n \n else if ( commandName == \"\/userAccepted\") {\n guiPointer->connected();\n }\n \n else if (commandName == \"\/history\") {\n handleHistory(inData);\n }\n \n else if (commandName == \"\/oldHistory\") {\n handleOldHistory(inData);\n }\n \n else if (commandName == \"\/message\") {\n handleMessage(inData);\n }\n \n else if ( commandName == \"\/requestStruct\") {\n handleRequestStruct();\n }\n \n else if ( commandName == \"\/structure\" ) {\n handleStructure(inData);\n }\n \n else {\n \n \/\/throw logic_error(\"Unknown command: \" + commandName.toStdString());\n \/\/release version\n cout << \"Unknown command: \" << endl;\n inData = \"\";\n commandName = \"\";\n incompleteCommand = \"\";\n return;\n }\n \n inData = rest;\n n = inData.indexOf(breaker);\n commandName = \"\";\n \n }while (n != -1 );\n}\n\n\/\/ ---------------------------------------------\n\nvoid NetClient::sendMessage(QString from, QString to, QString message){\n QByteArray array = \"\/message\";\n array += 0x1F; \/\/unit separator\n array += from;\n array += 0x1F;\n array += to;\n array += 0x1F;\n array += message;\n array += breaker;\n \n TcpSocket->write(array);\n TcpSocket->waitForBytesWritten(1000);\n}\n\nvoid NetClient::setName(QString inName) {\n name=inName;\n}\n\nvoid NetClient::getStruct(){\n QByteArray array = \"\/structure\";\n array += 0x1E;\n \n TcpSocket->write(array);\n TcpSocket->waitForBytesWritten(1000);\n}\n\n\/\/--------------------------------------------\n\/\/Helpfunctions\n\nvoid NetClient::handleRequestStruct(){\n QByteArray array = \"\/structure\";\n array += compare;\n array += breaker;\n \n TcpSocket->write(array);\n TcpSocket->waitForBytesWritten(1000);\n}\n\n\/\/ ---------------------------------------------\n\nvoid NetClient::handleMessage(QString inData){\n \n int i;\n \/\/ Get from\n i = inData.indexOf(compare);\n QString from = inData.left(i);\n inData = inData.mid(i+1);\n \n \/\/ Get to\n i = inData.indexOf(compare);\n QString to = inData.left(i);\n inData = inData.mid(i+1);\n \n \/\/ Get message\n i = inData.indexOf(compare);\n QString contents = inData.left(i);\n inData = inData.mid(i+1);\n \n \/\/ Get time\n QString dateTime = inData;\n \n \/\/Send message to Gui\n guiPointer->receiveMessage(from, to, contents, dateTime);\n \n}\n\n\/\/ ---------------------------------------------\n\nvoid NetClient::handleHistory(QString inData){\n QVector<QString> history;\n int i = inData.indexOf(compare);\n while(i != -1 ){\n \n \/\/ Get from\n i = inData.indexOf(compare);\n QString from = inData.left(i);\n inData = inData.mid(i+1);\n history.push_back(from);\n \n \/\/ Get to\n i = inData.indexOf(compare);\n QString to = inData.left(i);\n inData = inData.mid(i+1);\n history.push_back(to);\n \n \/\/ Get message\n i = inData.indexOf(compare);\n QString contents = inData.left(i);\n inData = inData.mid(i+1);\n history.push_back(contents);\n \n \n \/\/Get time\n i = inData.indexOf(compare);\n QString time = inData.left(i);\n inData = inData.mid(i+1);\n history.push_back(time);\n }\n guiPointer->receiveHistory(history);\n}\n\n\/\/ ---------------------------------------------\n\nvoid NetClient::handleOldHistory(QString inData){\n QVector<QString> history;\n int i = inData.indexOf(compare);\n while(i != -1 ){\n \n \/\/ Get from\n i = inData.indexOf(compare);\n QString from = inData.left(i);\n inData = inData.mid(i+1);\n history.push_back(from);\n \n \/\/ Get to\n i = inData.indexOf(compare);\n QString to = inData.left(i);\n inData = inData.mid(i+1);\n history.push_back(to);\n \n \/\/ Get message\n i = inData.indexOf(compare);\n QString contents = inData.left(i);\n inData = inData.mid(i+1);\n history.push_back(contents);\n \n \n \/\/Get time\n i = inData.indexOf(compare);\n QString time = inData.left(i);\n inData = inData.mid(i+1);\n history.push_back(time);\n }\n guiPointer->receiveOldHistory(history);\n}\n\n\/\/ ---------------------------------------------\n\nvoid NetClient::handleStructure(QString inData){\n QVector<QString> output;\n int i = inData.indexOf(compare);\n \n while(i != -1){\n \/\/Create vector output, containing room content structure\n QString data = inData.left(i);\n inData = inData.mid(i+1);\n output.push_back(data);\n \n i = inData.indexOf(compare);\n }\n \n output.push_back(inData);\n \n guiPointer->updateStruct(output);\n \n}\n\n\/\/ ---------------------------------------------\n\nvoid NetClient::getHistory(unsigned int daysBack) {\n QString temp;\n string daysBackString = to_string(daysBack);\n \n temp = QString::fromStdString(daysBackString);\n \n QByteArray array = \"\/oldHistory\";\n array += compare; \/\/unit separator\n array += temp;\n array += breaker;\n \n TcpSocket->write(array);\n TcpSocket->waitForBytesWritten(1000);\n}\n\n\n<|endoftext|>"} {"text":"<commit_before>#include \"shell_manager.hh\"\n\n#include \"buffer_utils.hh\"\n#include \"clock.hh\"\n#include \"context.hh\"\n#include \"display_buffer.hh\"\n#include \"event_manager.hh\"\n#include \"face_registry.hh\"\n#include \"file.hh\"\n#include \"regex.hh\"\n\n#include <cstring>\n#include <sys\/types.h>\n#include <sys\/wait.h>\n#include <unistd.h>\n#include <stdlib.h>\n\nextern char **environ;\n\nnamespace Kakoune\n{\n\nShellManager::ShellManager()\n{\n \/\/ Get a guaranteed to be POSIX shell binary\n {\n auto size = confstr(_CS_PATH, 0, 0);\n String path; path.resize(size, 0);\n confstr(_CS_PATH, path.data(), size);\n for (auto dir : StringView{path} | split<StringView>(':'))\n {\n String candidate = format(\"{}\/sh\", dir);\n struct stat st;\n if (stat(candidate.c_str(), &st))\n continue;\n\n bool executable = (st.st_mode & S_IXUSR)\n | (st.st_mode & S_IXGRP)\n | (st.st_mode & S_IXOTH);\n if (S_ISREG(st.st_mode) and executable)\n {\n m_shell = std::move(candidate);\n break;\n }\n }\n if (m_shell.empty())\n throw runtime_error{format(\"unable to find a posix shell in {}\", path)};\n }\n\n \/\/ Add Kakoune binary location to the path to guarantee that %sh{ ... }\n \/\/ have access to the kak command regardless of if the user installed it\n {\n const char* path = getenv(\"PATH\");\n auto new_path = format(\"{}:{}\", path, split_path(get_kak_binary_path()).first);\n setenv(\"PATH\", new_path.c_str(), 1);\n }\n}\n\nnamespace\n{\n\nstruct Pipe\n{\n Pipe(bool create = true)\n : m_fd{-1, -1}\n {\n if (create and ::pipe(m_fd) < 0)\n throw runtime_error(format(\"unable to create pipe (fds: {}\/{}; errno: {})\", m_fd[0], m_fd[1], ::strerror(errno)));\n }\n ~Pipe() { close_read_fd(); close_write_fd(); }\n\n int read_fd() const { return m_fd[0]; }\n int write_fd() const { return m_fd[1]; }\n\n void close_read_fd() { close_fd(m_fd[0]); }\n void close_write_fd() { close_fd(m_fd[1]); }\n\nprivate:\n void close_fd(int& fd) { if (fd != -1) { close(fd); fd = -1; } }\n int m_fd[2];\n};\n\ntemplate<typename Func>\npid_t spawn_shell(const char* shell, StringView cmdline,\n ConstArrayView<String> params,\n ConstArrayView<String> kak_env,\n Func setup_child)\n{\n Vector<const char*> envptrs;\n for (char** envp = environ; *envp; ++envp)\n envptrs.push_back(*envp);\n for (auto& env : kak_env)\n envptrs.push_back(env.c_str());\n envptrs.push_back(nullptr);\n\n auto cmdlinezstr = cmdline.zstr();\n Vector<const char*> execparams = { shell, \"-c\", cmdlinezstr };\n if (not params.empty())\n execparams.push_back(shell);\n for (auto& param : params)\n execparams.push_back(param.c_str());\n execparams.push_back(nullptr);\n\n if (pid_t pid = fork())\n return pid;\n\n setup_child();\n\n execve(shell, (char* const*)execparams.data(), (char* const*)envptrs.data());\n exit(-1);\n return -1;\n}\n\nVector<String> generate_env(StringView cmdline, const Context& context, const ShellContext& shell_context)\n{\n static const Regex re(R\"(\\bkak_(\\w+)\\b)\");\n\n Vector<String> kak_env;\n for (RegexIterator<const char*> it{cmdline.begin(), cmdline.end(), re}, end;\n it != end; ++it)\n {\n StringView name{(*it)[1].first, (*it)[1].second};\n\n auto match_name = [&](const String& s) {\n return s.length() > name.length() and\n prefix_match(s, name) and s[name.length()] == '=';\n };\n if (contains_that(kak_env, match_name))\n continue;\n\n auto var_it = shell_context.env_vars.find(name);\n try\n {\n const String& value = var_it != shell_context.env_vars.end() ?\n var_it->value : ShellManager::instance().get_val(name, context);\n\n kak_env.push_back(format(\"kak_{}={}\", name, value));\n } catch (runtime_error&) {}\n }\n\n return kak_env;\n}\n\n}\n\nstd::pair<String, int> ShellManager::eval(\n StringView cmdline, const Context& context, StringView input,\n Flags flags, const ShellContext& shell_context)\n{\n const DebugFlags debug_flags = context.options()[\"debug\"].get<DebugFlags>();\n const bool profile = debug_flags & DebugFlags::Profile;\n if (debug_flags & DebugFlags::Shell)\n write_to_debug_buffer(format(\"shell:\\n{}\\n----\\n\", cmdline));\n\n auto start_time = profile ? Clock::now() : Clock::time_point{};\n\n auto kak_env = generate_env(cmdline, context, shell_context);\n\n auto spawn_time = profile ? Clock::now() : Clock::time_point{};\n\n Pipe child_stdin{not input.empty()}, child_stdout, child_stderr;\n pid_t pid = spawn_shell(m_shell.c_str(), cmdline, shell_context.params, kak_env,\n [&child_stdin, &child_stdout, &child_stderr] {\n auto move = [](int oldfd, int newfd) { dup2(oldfd, newfd); close(oldfd); };\n\n if (child_stdin.read_fd() != -1)\n {\n close(child_stdin.write_fd());\n move(child_stdin.read_fd(), 0);\n }\n\n close(child_stdout.read_fd());\n move(child_stdout.write_fd(), 1);\n\n close(child_stderr.read_fd());\n move(child_stderr.write_fd(), 2);\n });\n\n child_stdin.close_read_fd();\n child_stdout.close_write_fd();\n child_stderr.close_write_fd();\n\n write(child_stdin.write_fd(), input);\n child_stdin.close_write_fd();\n\n auto wait_time = Clock::now();\n\n struct PipeReader : FDWatcher\n {\n PipeReader(Pipe& pipe, String& contents)\n : FDWatcher(pipe.read_fd(), FdEvents::Read,\n [&contents, &pipe](FDWatcher& watcher, FdEvents, EventMode) {\n char buffer[1024];\n while (fd_readable(pipe.read_fd()))\n {\n size_t size = ::read(pipe.read_fd(), buffer, 1024);\n if (size <= 0)\n {\n pipe.close_read_fd();\n watcher.disable();\n return;\n }\n contents += StringView{buffer, buffer+size};\n }\n })\n {}\n };\n\n String stdout_contents, stderr_contents;\n PipeReader stdout_reader{child_stdout, stdout_contents};\n PipeReader stderr_reader{child_stderr, stderr_contents};\n\n \/\/ block SIGCHLD to make sure we wont receive it before\n \/\/ our call to pselect, that will end up blocking indefinitly.\n sigset_t mask, orig_mask;\n sigemptyset(&mask);\n sigaddset(&mask, SIGCHLD);\n sigprocmask(SIG_BLOCK, &mask, &orig_mask);\n auto restore_mask = on_scope_end([&] { sigprocmask(SIG_SETMASK, &orig_mask, nullptr); });\n\n int status = 0;\n \/\/ check for termination now that SIGCHLD is blocked\n bool terminated = waitpid(pid, &status, WNOHANG);\n\n using namespace std::chrono;\n static constexpr seconds wait_timeout{1};\n bool wait_notified = false;\n Timer wait_timer{wait_time + wait_timeout, [&](Timer& timer)\n {\n auto wait_duration = Clock::now() - wait_time;\n context.print_status({ format(\"waiting for shell command to finish ({}s)\",\n duration_cast<seconds>(wait_duration).count()),\n get_face(\"Information\") }, true);\n timer.set_next_date(Clock::now() + wait_timeout);\n wait_notified = true;\n }, EventMode::Urgent};\n\n while (not terminated or\n ((flags & Flags::WaitForStdout) and\n (child_stdout.read_fd() != -1 or child_stderr.read_fd() != -1)))\n {\n EventManager::instance().handle_next_events(EventMode::Urgent, &orig_mask);\n if (not terminated)\n terminated = waitpid(pid, &status, WNOHANG);\n }\n\n if (not stderr_contents.empty())\n write_to_debug_buffer(format(\"shell stderr: <<<\\n{}>>>\", stderr_contents));\n\n if (profile)\n {\n auto end_time = Clock::now();\n auto full = duration_cast<milliseconds>(end_time - start_time);\n auto spawn = duration_cast<milliseconds>(wait_time - spawn_time);\n auto wait = duration_cast<milliseconds>(end_time - wait_time);\n write_to_debug_buffer(format(\"shell execution took {} ms (spawn: {}, wait: {})\",\n (size_t)full.count(), (size_t)spawn.count(), (size_t)wait.count()));\n }\n\n if (wait_notified) \/\/ clear the status line\n context.print_status({ \"\", get_face(\"Information\") }, true);\n\n return { std::move(stdout_contents), WIFEXITED(status) ? WEXITSTATUS(status) : -1 };\n}\n\nvoid ShellManager::register_env_var(StringView str, bool prefix,\n EnvVarRetriever retriever)\n{\n m_env_vars.push_back({ str.str(), prefix, std::move(retriever) });\n}\n\nString ShellManager::get_val(StringView name, const Context& context) const\n{\n auto env_var = std::find_if(\n m_env_vars.begin(), m_env_vars.end(),\n [name](const EnvVarDesc& desc) {\n return desc.prefix ? prefix_match(name, desc.str) : name == desc.str;\n });\n\n if (env_var == m_env_vars.end())\n throw runtime_error(\"no such env var: \" + name);\n\n return env_var->func(name, context);\n}\n\nCandidateList ShellManager::complete_env_var(StringView prefix,\n ByteCount cursor_pos) const\n{\n return complete(prefix, cursor_pos,\n m_env_vars | transform(std::mem_fn(&EnvVarDesc::str)));\n}\n\n}\n<commit_msg>Fix getting path confstr, the returned size includes the zero terminator<commit_after>#include \"shell_manager.hh\"\n\n#include \"buffer_utils.hh\"\n#include \"clock.hh\"\n#include \"context.hh\"\n#include \"display_buffer.hh\"\n#include \"event_manager.hh\"\n#include \"face_registry.hh\"\n#include \"file.hh\"\n#include \"regex.hh\"\n\n#include <cstring>\n#include <sys\/types.h>\n#include <sys\/wait.h>\n#include <unistd.h>\n#include <stdlib.h>\n\nextern char **environ;\n\nnamespace Kakoune\n{\n\nShellManager::ShellManager()\n{\n \/\/ Get a guaranteed to be POSIX shell binary\n {\n auto size = confstr(_CS_PATH, 0, 0);\n String path; path.resize(size-1, 0);\n confstr(_CS_PATH, path.data(), size);\n for (auto dir : StringView{path} | split<StringView>(':'))\n {\n String candidate = format(\"{}\/sh\", dir);\n struct stat st;\n if (stat(candidate.c_str(), &st))\n continue;\n\n bool executable = (st.st_mode & S_IXUSR)\n | (st.st_mode & S_IXGRP)\n | (st.st_mode & S_IXOTH);\n if (S_ISREG(st.st_mode) and executable)\n {\n m_shell = std::move(candidate);\n break;\n }\n }\n if (m_shell.empty())\n throw runtime_error{format(\"unable to find a posix shell in {}\", path)};\n }\n\n \/\/ Add Kakoune binary location to the path to guarantee that %sh{ ... }\n \/\/ have access to the kak command regardless of if the user installed it\n {\n const char* path = getenv(\"PATH\");\n auto new_path = format(\"{}:{}\", path, split_path(get_kak_binary_path()).first);\n setenv(\"PATH\", new_path.c_str(), 1);\n }\n}\n\nnamespace\n{\n\nstruct Pipe\n{\n Pipe(bool create = true)\n : m_fd{-1, -1}\n {\n if (create and ::pipe(m_fd) < 0)\n throw runtime_error(format(\"unable to create pipe (fds: {}\/{}; errno: {})\", m_fd[0], m_fd[1], ::strerror(errno)));\n }\n ~Pipe() { close_read_fd(); close_write_fd(); }\n\n int read_fd() const { return m_fd[0]; }\n int write_fd() const { return m_fd[1]; }\n\n void close_read_fd() { close_fd(m_fd[0]); }\n void close_write_fd() { close_fd(m_fd[1]); }\n\nprivate:\n void close_fd(int& fd) { if (fd != -1) { close(fd); fd = -1; } }\n int m_fd[2];\n};\n\ntemplate<typename Func>\npid_t spawn_shell(const char* shell, StringView cmdline,\n ConstArrayView<String> params,\n ConstArrayView<String> kak_env,\n Func setup_child)\n{\n Vector<const char*> envptrs;\n for (char** envp = environ; *envp; ++envp)\n envptrs.push_back(*envp);\n for (auto& env : kak_env)\n envptrs.push_back(env.c_str());\n envptrs.push_back(nullptr);\n\n auto cmdlinezstr = cmdline.zstr();\n Vector<const char*> execparams = { shell, \"-c\", cmdlinezstr };\n if (not params.empty())\n execparams.push_back(shell);\n for (auto& param : params)\n execparams.push_back(param.c_str());\n execparams.push_back(nullptr);\n\n if (pid_t pid = fork())\n return pid;\n\n setup_child();\n\n execve(shell, (char* const*)execparams.data(), (char* const*)envptrs.data());\n exit(-1);\n return -1;\n}\n\nVector<String> generate_env(StringView cmdline, const Context& context, const ShellContext& shell_context)\n{\n static const Regex re(R\"(\\bkak_(\\w+)\\b)\");\n\n Vector<String> kak_env;\n for (RegexIterator<const char*> it{cmdline.begin(), cmdline.end(), re}, end;\n it != end; ++it)\n {\n StringView name{(*it)[1].first, (*it)[1].second};\n\n auto match_name = [&](const String& s) {\n return s.length() > name.length() and\n prefix_match(s, name) and s[name.length()] == '=';\n };\n if (contains_that(kak_env, match_name))\n continue;\n\n auto var_it = shell_context.env_vars.find(name);\n try\n {\n const String& value = var_it != shell_context.env_vars.end() ?\n var_it->value : ShellManager::instance().get_val(name, context);\n\n kak_env.push_back(format(\"kak_{}={}\", name, value));\n } catch (runtime_error&) {}\n }\n\n return kak_env;\n}\n\n}\n\nstd::pair<String, int> ShellManager::eval(\n StringView cmdline, const Context& context, StringView input,\n Flags flags, const ShellContext& shell_context)\n{\n const DebugFlags debug_flags = context.options()[\"debug\"].get<DebugFlags>();\n const bool profile = debug_flags & DebugFlags::Profile;\n if (debug_flags & DebugFlags::Shell)\n write_to_debug_buffer(format(\"shell:\\n{}\\n----\\n\", cmdline));\n\n auto start_time = profile ? Clock::now() : Clock::time_point{};\n\n auto kak_env = generate_env(cmdline, context, shell_context);\n\n auto spawn_time = profile ? Clock::now() : Clock::time_point{};\n\n Pipe child_stdin{not input.empty()}, child_stdout, child_stderr;\n pid_t pid = spawn_shell(m_shell.c_str(), cmdline, shell_context.params, kak_env,\n [&child_stdin, &child_stdout, &child_stderr] {\n auto move = [](int oldfd, int newfd) { dup2(oldfd, newfd); close(oldfd); };\n\n if (child_stdin.read_fd() != -1)\n {\n close(child_stdin.write_fd());\n move(child_stdin.read_fd(), 0);\n }\n\n close(child_stdout.read_fd());\n move(child_stdout.write_fd(), 1);\n\n close(child_stderr.read_fd());\n move(child_stderr.write_fd(), 2);\n });\n\n child_stdin.close_read_fd();\n child_stdout.close_write_fd();\n child_stderr.close_write_fd();\n\n write(child_stdin.write_fd(), input);\n child_stdin.close_write_fd();\n\n auto wait_time = Clock::now();\n\n struct PipeReader : FDWatcher\n {\n PipeReader(Pipe& pipe, String& contents)\n : FDWatcher(pipe.read_fd(), FdEvents::Read,\n [&contents, &pipe](FDWatcher& watcher, FdEvents, EventMode) {\n char buffer[1024];\n while (fd_readable(pipe.read_fd()))\n {\n size_t size = ::read(pipe.read_fd(), buffer, 1024);\n if (size <= 0)\n {\n pipe.close_read_fd();\n watcher.disable();\n return;\n }\n contents += StringView{buffer, buffer+size};\n }\n })\n {}\n };\n\n String stdout_contents, stderr_contents;\n PipeReader stdout_reader{child_stdout, stdout_contents};\n PipeReader stderr_reader{child_stderr, stderr_contents};\n\n \/\/ block SIGCHLD to make sure we wont receive it before\n \/\/ our call to pselect, that will end up blocking indefinitly.\n sigset_t mask, orig_mask;\n sigemptyset(&mask);\n sigaddset(&mask, SIGCHLD);\n sigprocmask(SIG_BLOCK, &mask, &orig_mask);\n auto restore_mask = on_scope_end([&] { sigprocmask(SIG_SETMASK, &orig_mask, nullptr); });\n\n int status = 0;\n \/\/ check for termination now that SIGCHLD is blocked\n bool terminated = waitpid(pid, &status, WNOHANG);\n\n using namespace std::chrono;\n static constexpr seconds wait_timeout{1};\n bool wait_notified = false;\n Timer wait_timer{wait_time + wait_timeout, [&](Timer& timer)\n {\n auto wait_duration = Clock::now() - wait_time;\n context.print_status({ format(\"waiting for shell command to finish ({}s)\",\n duration_cast<seconds>(wait_duration).count()),\n get_face(\"Information\") }, true);\n timer.set_next_date(Clock::now() + wait_timeout);\n wait_notified = true;\n }, EventMode::Urgent};\n\n while (not terminated or\n ((flags & Flags::WaitForStdout) and\n (child_stdout.read_fd() != -1 or child_stderr.read_fd() != -1)))\n {\n EventManager::instance().handle_next_events(EventMode::Urgent, &orig_mask);\n if (not terminated)\n terminated = waitpid(pid, &status, WNOHANG);\n }\n\n if (not stderr_contents.empty())\n write_to_debug_buffer(format(\"shell stderr: <<<\\n{}>>>\", stderr_contents));\n\n if (profile)\n {\n auto end_time = Clock::now();\n auto full = duration_cast<milliseconds>(end_time - start_time);\n auto spawn = duration_cast<milliseconds>(wait_time - spawn_time);\n auto wait = duration_cast<milliseconds>(end_time - wait_time);\n write_to_debug_buffer(format(\"shell execution took {} ms (spawn: {}, wait: {})\",\n (size_t)full.count(), (size_t)spawn.count(), (size_t)wait.count()));\n }\n\n if (wait_notified) \/\/ clear the status line\n context.print_status({ \"\", get_face(\"Information\") }, true);\n\n return { std::move(stdout_contents), WIFEXITED(status) ? WEXITSTATUS(status) : -1 };\n}\n\nvoid ShellManager::register_env_var(StringView str, bool prefix,\n EnvVarRetriever retriever)\n{\n m_env_vars.push_back({ str.str(), prefix, std::move(retriever) });\n}\n\nString ShellManager::get_val(StringView name, const Context& context) const\n{\n auto env_var = std::find_if(\n m_env_vars.begin(), m_env_vars.end(),\n [name](const EnvVarDesc& desc) {\n return desc.prefix ? prefix_match(name, desc.str) : name == desc.str;\n });\n\n if (env_var == m_env_vars.end())\n throw runtime_error(\"no such env var: \" + name);\n\n return env_var->func(name, context);\n}\n\nCandidateList ShellManager::complete_env_var(StringView prefix,\n ByteCount cursor_pos) const\n{\n return complete(prefix, cursor_pos,\n m_env_vars | transform(std::mem_fn(&EnvVarDesc::str)));\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ inpal_prime.cpp\n\/\/ Inverse Palindrome Library\n\/\/\n\/\/ Created by Bryan Triana on 7\/21\/16.\n\/\/ Copyright © 2016 Inverse Palindrome. All rights reserved.\n\/\/\n\n\n#include \"inpal_prime.hpp\"\n#include \"inpal_algorithm.hpp\"\n\n\nstd::vector<std::size_t> inpal::prime::prime_list(std::size_t range)\n{\n const auto primes = prime_sieve(range);\n std::vector<std::size_t> p_list;\n \n for(std::size_t i=2; i<=range; i++) if(primes[i]) p_list.push_back(i);\n \n return p_list;\n}\n\n\nstd::vector<bool> inpal::prime::prime_sieve(std::size_t range)\n{\n std::vector<bool> p_test(range+1, false);\n \n \/\/defines square root of range for future usage\n const std::size_t root = ceil(sqrt(range));\n \n \/\/sieve axioms\n for(std::size_t x=1; x<=root; x++)\n for(std::size_t y=1; y<=root; y++)\n {\n std::size_t i = (4*x*x)+(y*y);\n if(i<=range && (i%12==1 || i%12==5)) p_test[i].flip();\n \n i = (3*x*x)+(y*y);\n if(i<=range && i%12==7) p_test[i].flip();\n \n i = (3*x*x)-(y*y);\n if(x>y && i<=range && i%12==11) p_test[i].flip();\n }\n \n \/\/marks 2,3,5 and 7 as prime numbers to deal with input smaller than 7\n p_test[2]=p_test[3]=p_test[5]=true;\n \n \/\/marks all multiples of primes as non primes\n for(std::size_t r=5; r<=root; r++)\n {\n if(p_test[r])\n {\n for(std::size_t j=r*r; j<=range; j+=r*r) p_test[j]=false;\n }\n }\n \n return p_test;\n}\n\n\nstd::vector<std::size_t> inpal::prime::factor_list(std::size_t num)\n{\n std::vector<std::size_t> factors;\n std::vector<std::size_t> primes;\n \n std::size_t factor = algorithm::pollard_rho(num);\n factors.push_back(num\/factor);\n factors.push_back(factor);\n \n do\n {\n std::size_t m = factors.back();\n factors.pop_back();\n \n if(m==1) continue;\n if(prime_test(m))\n {\n primes.push_back(m);\n \n \/\/decomposes the factors into primes\n for(std::size_t i=0; i<factors.size(); i++)\n {\n std::size_t k = factors[i];\n if(k%m==0)\n {\n do k\/=m;\n while(k%m==0);\n \n factors[i]=k;\n }\n }\n }\n else\n {\n factor=algorithm::pollard_rho(m);\n factors.push_back(m\/factor);\n factors.push_back(factor);\n }\n }\n while(factors.size());\n \n \/\/prime factors found by pollard rho arent always ordered\n std::sort(primes.begin(), primes.end());\n \n return primes;\n}\n\n\nstd::size_t inpal::prime::prime_locate(std::size_t pos)\n{\n \/\/index starts at 1 instead of 0, eg 1st prime is 2\n pos = pos-1;\n \n \/\/return values for input less or equal to 10\n const auto small_primes = prime_list(29);\n if(pos<10) return small_primes[pos];\n \n \/\/denotes the limit of the sieve\n std::size_t limit = pos*log(pos)+pos*log(log(pos));\n const auto primes = prime_list(limit);\n \n return primes[pos];\n}\n\n\nstd::size_t inpal::prime::max_prime(std::size_t range)\n{\n for(std::size_t i=range; i>0; i--) if(prime_test(i)) return i;\n\n return 2;\n}\n\n\nstd::size_t inpal::prime::prime_count(std::size_t range)\n{\n const auto primes = prime_sieve(range);\n \n return std::count(primes.begin(), primes.end(), true);\n}\n\n\ndouble inpal::prime::prime_density(double range)\n{\n return prime_count(range)\/range;\n}\n\n\nbool inpal::prime::prime_test(std::size_t num)\n{\n if(num!=2 && num%2==0) return false;\n \n \/\/iterations will occur 20 times to ensure that the margin of error is less than 4^-20\n const std::size_t cycle = 20;\n std::size_t s = num-1;\n while(s%2==0) s\/=2;\n \n for(std::size_t i=0; i<cycle; i++)\n {\n std::size_t a = rand()%(num-1)+1;\n std::size_t b = s;\n std::size_t mod = algorithm::modulo(a,b,num);\n \n while(b!=num-1 && mod!=1 && mod!=num-1)\n {\n mod=algorithm::mulmod(mod,mod,num);\n b*=2;\n }\n if(mod!=num-1 && b%2==0) return false;\n }\n \n return true;\n}\n\n\nbool inpal::prime::twin_test(std::size_t num)\n{\n return prime_test(num) && (prime_test(num-2) || prime_test(num+2));\n}\n\n\nbool inpal::prime::cousin_test(std::size_t num)\n{\n return prime_test(num) && (prime_test(num-4) || prime_test(num+4));\n}\n\n\nbool inpal::prime::sexy_test(std::size_t num)\n{\n return num!=3 && prime_test(num) && (prime_test(num-6) || prime_test(num+6));\n}\n\n\nstd::size_t inpal::prime::max_palprime(std::size_t range)\n{\n for(std::size_t i=range; i>2; --i) if(algorithm::pal_test(i) && prime_test(i)) return i;\n \n return 2;\n}\n\n\nstd::size_t inpal::prime::max_factor(std::size_t num)\n{\n return factor_list(num).back();\n}\n\n\nstd::size_t inpal::prime::factor_count(std::size_t num)\n{\n return factor_list(num).size();\n}\n\n\n<commit_msg>Update inpal_prime.cpp<commit_after>\/\/\n\/\/ inpal_prime.cpp\n\/\/ Inverse Palindrome Library\n\/\/\n\/\/ Created by Bryan Triana on 7\/21\/16.\n\/\/ Copyright © 2016 Inverse Palindrome. All rights reserved.\n\/\/\n\n\n#include \"inpal_prime.hpp\"\n#include \"inpal_algorithm.hpp\"\n\n\nstd::vector<std::size_t> inpal::prime::prime_list(std::size_t range)\n{\n const auto primes = prime_sieve(range);\n std::vector<std::size_t> p_list;\n \n for(std::size_t i=2; i<=range; i++) if(primes[i]) p_list.push_back(i);\n \n return p_list;\n}\n\n\nstd::vector<bool> inpal::prime::prime_sieve(std::size_t range)\n{\n std::vector<bool> p_test(range+1, false);\n \n \/\/defines square root of range for future usage\n const std::size_t root = ceil(sqrt(range));\n \n \/\/sieve axioms\n for(std::size_t x=1; x<=root; x++)\n for(std::size_t y=1; y<=root; y++)\n {\n std::size_t i = (4*x*x)+(y*y);\n if(i<=range && (i%12==1 || i%12==5)) p_test[i].flip();\n \n i = (3*x*x)+(y*y);\n if(i<=range && i%12==7) p_test[i].flip();\n \n i = (3*x*x)-(y*y);\n if(x>y && i<=range && i%12==11) p_test[i].flip();\n }\n \n \/\/marks 2, 3 and 5 as prime numbers to ignore these numbers in the next process\n p_test[2]=p_test[3]=p_test[5]=true;\n \n \/\/marks all multiples of primes as non primes\n for(std::size_t r=5; r<=root; r++)\n {\n if(p_test[r])\n {\n for(std::size_t j=r*r; j<=range; j+=r*r) p_test[j]=false;\n }\n }\n \n return p_test;\n}\n\n\nstd::vector<std::size_t> inpal::prime::factor_list(std::size_t num)\n{\n std::vector<std::size_t> factors;\n std::vector<std::size_t> primes;\n \n std::size_t factor = algorithm::pollard_rho(num);\n factors.push_back(num\/factor);\n factors.push_back(factor);\n \n do\n {\n std::size_t m = factors.back();\n factors.pop_back();\n \n if(m==1) continue;\n if(prime_test(m))\n {\n primes.push_back(m);\n \n \/\/decomposes the factors into primes\n for(std::size_t i=0; i<factors.size(); i++)\n {\n std::size_t k = factors[i];\n if(k%m==0)\n {\n do k\/=m;\n while(k%m==0);\n \n factors[i]=k;\n }\n }\n }\n else\n {\n factor=algorithm::pollard_rho(m);\n factors.push_back(m\/factor);\n factors.push_back(factor);\n }\n }\n while(factors.size());\n \n \/\/prime factors found by pollard rho arent always ordered\n std::sort(primes.begin(), primes.end());\n \n return primes;\n}\n\n\nstd::size_t inpal::prime::prime_locate(std::size_t pos)\n{\n \/\/index starts at 1 instead of 0, eg 1st prime is 2\n pos = pos-1;\n \n \/\/return values for input less or equal to 10\n const auto small_primes = prime_list(29);\n if(pos<10) return small_primes[pos];\n \n \/\/denotes the limit of the sieve\n std::size_t limit = pos*log(pos)+pos*log(log(pos));\n const auto primes = prime_list(limit);\n \n return primes[pos];\n}\n\n\nstd::size_t inpal::prime::max_prime(std::size_t range)\n{\n for(std::size_t i=range; i>0; i--) if(prime_test(i)) return i;\n\n return 2;\n}\n\n\nstd::size_t inpal::prime::prime_count(std::size_t range)\n{\n const auto primes = prime_sieve(range);\n \n return std::count(primes.begin(), primes.end(), true);\n}\n\n\ndouble inpal::prime::prime_density(double range)\n{\n return prime_count(range)\/range;\n}\n\n\nbool inpal::prime::prime_test(std::size_t num)\n{\n if(num!=2 && num%2==0) return false;\n \n \/\/iterations will occur 20 times to ensure that the margin of error is less than 4^-20\n const std::size_t cycle = 20;\n std::size_t s = num-1;\n while(s%2==0) s\/=2;\n \n for(std::size_t i=0; i<cycle; i++)\n {\n std::size_t a = rand()%(num-1)+1;\n std::size_t b = s;\n std::size_t mod = algorithm::modulo(a,b,num);\n \n while(b!=num-1 && mod!=1 && mod!=num-1)\n {\n mod=algorithm::mulmod(mod,mod,num);\n b*=2;\n }\n if(mod!=num-1 && b%2==0) return false;\n }\n \n return true;\n}\n\n\nbool inpal::prime::twin_test(std::size_t num)\n{\n return prime_test(num) && (prime_test(num-2) || prime_test(num+2));\n}\n\n\nbool inpal::prime::cousin_test(std::size_t num)\n{\n return prime_test(num) && (prime_test(num-4) || prime_test(num+4));\n}\n\n\nbool inpal::prime::sexy_test(std::size_t num)\n{\n return num!=3 && prime_test(num) && (prime_test(num-6) || prime_test(num+6));\n}\n\n\nstd::size_t inpal::prime::max_palprime(std::size_t range)\n{\n for(std::size_t i=range; i>2; --i) if(algorithm::pal_test(i) && prime_test(i)) return i;\n \n return 2;\n}\n\n\nstd::size_t inpal::prime::max_factor(std::size_t num)\n{\n return factor_list(num).back();\n}\n\n\nstd::size_t inpal::prime::factor_count(std::size_t num)\n{\n return factor_list(num).size();\n}\n\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 2002-2005 The Regents of The University of Michigan\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met: redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer;\n * redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution;\n * neither the name of the copyright holders nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n * Authors: Nathan Binkert\n * Erik Hallnor\n * Steve Reinhardt\n *\/\n\n#include <sys\/time.h>\n#include <sys\/types.h>\n#include <sys\/stat.h>\n#include <errno.h>\n\n#include <fstream>\n#include <list>\n#include <string>\n#include <vector>\n\n#include \"base\/inifile.hh\"\n#include \"base\/misc.hh\"\n#include \"base\/output.hh\"\n#include \"base\/str.hh\"\n#include \"base\/trace.hh\"\n#include \"sim\/eventq.hh\"\n#include \"sim\/serialize.hh\"\n#include \"sim\/sim_events.hh\"\n#include \"sim\/sim_exit.hh\"\n#include \"sim\/sim_object.hh\"\n\n\/\/ For stat reset hack\n#include \"sim\/stat_control.hh\"\n\nusing namespace std;\n\nextern SimObject *resolveSimObject(const string &);\n\n\/\/\n\/\/ The base implementations use to_number for parsing and '<<' for\n\/\/ displaying, suitable for integer types.\n\/\/\ntemplate <class T>\nbool\nparseParam(const string &s, T &value)\n{\n return to_number(s, value);\n}\n\ntemplate <class T>\nvoid\nshowParam(ostream &os, const T &value)\n{\n os << value;\n}\n\n\/\/\n\/\/ Template specializations:\n\/\/ - char (8-bit integer)\n\/\/ - floating-point types\n\/\/ - bool\n\/\/ - string\n\/\/\n\n\/\/ Treat 8-bit ints (chars) as ints on output, not as chars\ntemplate <>\nvoid\nshowParam(ostream &os, const char &value)\n{\n os << (int)value;\n}\n\n\ntemplate <>\nvoid\nshowParam(ostream &os, const signed char &value)\n{\n os << (int)value;\n}\n\n\ntemplate <>\nvoid\nshowParam(ostream &os, const unsigned char &value)\n{\n os << (unsigned int)value;\n}\n\n\n\/\/ Use sscanf() for FP types as to_number() only handles integers\ntemplate <>\nbool\nparseParam(const string &s, float &value)\n{\n return (sscanf(s.c_str(), \"%f\", &value) == 1);\n}\n\ntemplate <>\nbool\nparseParam(const string &s, double &value)\n{\n return (sscanf(s.c_str(), \"%lf\", &value) == 1);\n}\n\ntemplate <>\nbool\nparseParam(const string &s, bool &value)\n{\n const string &ls = to_lower(s);\n\n if (ls == \"true\") {\n value = true;\n return true;\n }\n\n if (ls == \"false\") {\n value = false;\n return true;\n }\n\n return false;\n}\n\n\/\/ Display bools as strings\ntemplate <>\nvoid\nshowParam(ostream &os, const bool &value)\n{\n os << (value ? \"true\" : \"false\");\n}\n\n\n\/\/ String requires no processing to speak of\ntemplate <>\nbool\nparseParam(const string &s, string &value)\n{\n value = s;\n return true;\n}\n\nint Serializable::ckptMaxCount = 0;\nint Serializable::ckptCount = 0;\nint Serializable::ckptPrevCount = -1;\n\nvoid\nSerializable::nameOut(ostream &os)\n{\n os << \"\\n[\" << name() << \"]\\n\";\n}\n\nvoid\nSerializable::nameOut(ostream &os, const string &_name)\n{\n os << \"\\n[\" << _name << \"]\\n\";\n}\n\ntemplate <class T>\nvoid\nparamOut(ostream &os, const string &name, const T ¶m)\n{\n os << name << \"=\";\n showParam(os, param);\n os << \"\\n\";\n}\n\ntemplate <class T>\nvoid\narrayParamOut(ostream &os, const string &name, const vector<T> ¶m)\n{\n typename vector<T>::size_type size = param.size();\n os << name << \"=\";\n if (size > 0)\n showParam(os, param[0]);\n for (typename vector<T>::size_type i = 1; i < size; ++i) {\n os << \" \";\n showParam(os, param[i]);\n }\n os << \"\\n\";\n}\n\n\ntemplate <class T>\nvoid\nparamIn(Checkpoint *cp, const string §ion, const string &name, T ¶m)\n{\n string str;\n if (!cp->find(section, name, str) || !parseParam(str, param)) {\n fatal(\"Can't unserialize '%s:%s'\\n\", section, name);\n }\n}\n\ntemplate <class T>\nbool\noptParamIn(Checkpoint *cp, const string §ion, const string &name, T ¶m)\n{\n string str;\n if (!cp->find(section, name, str) || !parseParam(str, param)) {\n warn(\"optional parameter %s:%s not present\\n\", section, name);\n return false;\n } else {\n return true;\n }\n}\n\ntemplate <class T>\nvoid\narrayParamOut(ostream &os, const string &name, const T *param, unsigned size)\n{\n os << name << \"=\";\n if (size > 0)\n showParam(os, param[0]);\n for (unsigned i = 1; i < size; ++i) {\n os << \" \";\n showParam(os, param[i]);\n }\n os << \"\\n\";\n}\n\n\ntemplate <class T>\nvoid\narrayParamIn(Checkpoint *cp, const string §ion, const string &name,\n T *param, unsigned size)\n{\n string str;\n if (!cp->find(section, name, str)) {\n fatal(\"Can't unserialize '%s:%s'\\n\", section, name);\n }\n\n \/\/ code below stolen from VectorParam<T>::parse().\n \/\/ it would be nice to unify these somehow...\n\n vector<string> tokens;\n\n tokenize(tokens, str, ' ');\n\n \/\/ Need this if we were doing a vector\n \/\/ value.resize(tokens.size());\n\n if (tokens.size() != size) {\n fatal(\"Array size mismatch on %s:%s'\\n\", section, name);\n }\n\n for (vector<string>::size_type i = 0; i < tokens.size(); i++) {\n \/\/ need to parse into local variable to handle vector<bool>,\n \/\/ for which operator[] returns a special reference class\n \/\/ that's not the same as 'bool&', (since it's a packed\n \/\/ vector)\n T scalar_value = 0;\n if (!parseParam(tokens[i], scalar_value)) {\n string err(\"could not parse \\\"\");\n\n err += str;\n err += \"\\\"\";\n\n fatal(err);\n }\n\n \/\/ assign parsed value to vector\n param[i] = scalar_value;\n }\n}\n\ntemplate <class T>\nvoid\narrayParamIn(Checkpoint *cp, const string §ion,\n const string &name, vector<T> ¶m)\n{\n string str;\n if (!cp->find(section, name, str)) {\n fatal(\"Can't unserialize '%s:%s'\\n\", section, name);\n }\n\n \/\/ code below stolen from VectorParam<T>::parse().\n \/\/ it would be nice to unify these somehow...\n\n vector<string> tokens;\n\n tokenize(tokens, str, ' ');\n\n \/\/ Need this if we were doing a vector\n \/\/ value.resize(tokens.size());\n\n param.resize(tokens.size());\n\n for (vector<string>::size_type i = 0; i < tokens.size(); i++) {\n \/\/ need to parse into local variable to handle vector<bool>,\n \/\/ for which operator[] returns a special reference class\n \/\/ that's not the same as 'bool&', (since it's a packed\n \/\/ vector)\n T scalar_value = 0;\n if (!parseParam(tokens[i], scalar_value)) {\n string err(\"could not parse \\\"\");\n\n err += str;\n err += \"\\\"\";\n\n fatal(err);\n }\n\n \/\/ assign parsed value to vector\n param[i] = scalar_value;\n }\n}\n\nvoid\nobjParamIn(Checkpoint *cp, const string §ion,\n const string &name, SimObject * ¶m)\n{\n if (!cp->findObj(section, name, param)) {\n fatal(\"Can't unserialize '%s:%s'\\n\", section, name);\n }\n}\n\n\n#define INSTANTIATE_PARAM_TEMPLATES(type) \\\ntemplate void \\\nparamOut(ostream &os, const string &name, type const ¶m); \\\ntemplate void \\\nparamIn(Checkpoint *cp, const string §ion, \\\n const string &name, type & param); \\\ntemplate bool \\\noptParamIn(Checkpoint *cp, const string §ion, \\\n const string &name, type & param); \\\ntemplate void \\\narrayParamOut(ostream &os, const string &name, \\\n type const *param, unsigned size); \\\ntemplate void \\\narrayParamIn(Checkpoint *cp, const string §ion, \\\n const string &name, type *param, unsigned size); \\\ntemplate void \\\narrayParamOut(ostream &os, const string &name, \\\n const vector<type> ¶m); \\\ntemplate void \\\narrayParamIn(Checkpoint *cp, const string §ion, \\\n const string &name, vector<type> ¶m);\n\nINSTANTIATE_PARAM_TEMPLATES(char)\nINSTANTIATE_PARAM_TEMPLATES(signed char)\nINSTANTIATE_PARAM_TEMPLATES(unsigned char)\nINSTANTIATE_PARAM_TEMPLATES(signed short)\nINSTANTIATE_PARAM_TEMPLATES(unsigned short)\nINSTANTIATE_PARAM_TEMPLATES(signed int)\nINSTANTIATE_PARAM_TEMPLATES(unsigned int)\nINSTANTIATE_PARAM_TEMPLATES(signed long)\nINSTANTIATE_PARAM_TEMPLATES(unsigned long)\nINSTANTIATE_PARAM_TEMPLATES(signed long long)\nINSTANTIATE_PARAM_TEMPLATES(unsigned long long)\nINSTANTIATE_PARAM_TEMPLATES(bool)\nINSTANTIATE_PARAM_TEMPLATES(float)\nINSTANTIATE_PARAM_TEMPLATES(double)\nINSTANTIATE_PARAM_TEMPLATES(string)\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/\/ Container for serializing global variables (not associated with\n\/\/\/ any serialized object).\nclass Globals : public Serializable\n{\n public:\n const string name() const;\n void serialize(ostream &os);\n void unserialize(Checkpoint *cp);\n};\n\n\/\/\/ The one and only instance of the Globals class.\nGlobals globals;\n\nconst string\nGlobals::name() const\n{\n return \"Globals\";\n}\n\nvoid\nGlobals::serialize(ostream &os)\n{\n nameOut(os);\n SERIALIZE_SCALAR(curTick());\n\n nameOut(os, \"MainEventQueue\");\n mainEventQueue.serialize(os);\n}\n\nvoid\nGlobals::unserialize(Checkpoint *cp)\n{\n const string §ion = name();\n Tick tick;\n paramIn(cp, section, \"curTick\", tick);\n curTick(tick);\n\n mainEventQueue.unserialize(cp, \"MainEventQueue\");\n}\n\nSerializable::Serializable()\n{\n}\n\nSerializable::~Serializable()\n{\n}\n\nvoid\nSerializable::serialize(ostream &os)\n{\n}\n\nvoid\nSerializable::unserialize(Checkpoint *cp, const string §ion)\n{\n}\n\nvoid\nSerializable::serializeAll(const string &cpt_dir)\n{\n string dir = Checkpoint::setDir(cpt_dir);\n if (mkdir(dir.c_str(), 0775) == -1 && errno != EEXIST)\n fatal(\"couldn't mkdir %s\\n\", dir);\n\n string cpt_file = dir + Checkpoint::baseFilename;\n ofstream outstream(cpt_file.c_str());\n time_t t = time(NULL);\n if (!outstream.is_open())\n fatal(\"Unable to open file %s for writing\\n\", cpt_file.c_str());\n outstream << \"## checkpoint generated: \" << ctime(&t);\n\n globals.serialize(outstream);\n SimObject::serializeAll(outstream);\n}\n\nvoid\nSerializable::unserializeGlobals(Checkpoint *cp)\n{\n globals.unserialize(cp);\n}\n\nvoid\ndebug_serialize(const string &cpt_dir)\n{\n Serializable::serializeAll(cpt_dir);\n}\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ SerializableClass member definitions\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/ Map of class names to SerializableBuilder creation functions.\n\/\/ Need to make this a pointer so we can force initialization on the\n\/\/ first reference; otherwise, some SerializableClass constructors\n\/\/ may be invoked before the classMap constructor.\nmap<string, SerializableClass::CreateFunc> *SerializableClass::classMap = 0;\n\n\/\/ SerializableClass constructor: add mapping to classMap\nSerializableClass::SerializableClass(const string &className,\n CreateFunc createFunc)\n{\n if (classMap == NULL)\n classMap = new map<string, SerializableClass::CreateFunc>();\n\n if ((*classMap)[className])\n fatal(\"Error: simulation object class %s redefined\\n\", className);\n\n \/\/ add className --> createFunc to class map\n (*classMap)[className] = createFunc;\n}\n\n\/\/\n\/\/\nSerializable *\nSerializableClass::createObject(Checkpoint *cp, const string §ion)\n{\n string className;\n\n if (!cp->find(section, \"type\", className)) {\n fatal(\"Serializable::create: no 'type' entry in section '%s'.\\n\",\n section);\n }\n\n CreateFunc createFunc = (*classMap)[className];\n\n if (createFunc == NULL) {\n fatal(\"Serializable::create: no create function for class '%s'.\\n\",\n className);\n }\n\n Serializable *object = createFunc(cp, section);\n\n assert(object != NULL);\n\n return object;\n}\n\n\nSerializable *\nSerializable::create(Checkpoint *cp, const string §ion)\n{\n Serializable *object = SerializableClass::createObject(cp, section);\n object->unserialize(cp, section);\n return object;\n}\n\n\nconst char *Checkpoint::baseFilename = \"m5.cpt\";\n\nstring Checkpoint::currentDirectory;\n\nstring\nCheckpoint::setDir(const string &name)\n{\n \/\/ use csprintf to insert curTick() into directory name if it\n \/\/ appears to have a format placeholder in it.\n currentDirectory = (name.find(\"%\") != string::npos) ?\n csprintf(name, curTick()) : name;\n if (currentDirectory[currentDirectory.size() - 1] != '\/')\n currentDirectory += \"\/\";\n return currentDirectory;\n}\n\nstring\nCheckpoint::dir()\n{\n return currentDirectory;\n}\n\n\nCheckpoint::Checkpoint(const string &cpt_dir)\n : db(new IniFile), cptDir(setDir(cpt_dir))\n{\n string filename = cptDir + \"\/\" + Checkpoint::baseFilename;\n if (!db->load(filename)) {\n fatal(\"Can't load checkpoint file '%s'\\n\", filename);\n }\n}\n\n\nbool\nCheckpoint::find(const string §ion, const string &entry, string &value)\n{\n return db->find(section, entry, value);\n}\n\n\nbool\nCheckpoint::findObj(const string §ion, const string &entry,\n SimObject *&value)\n{\n string path;\n\n if (!db->find(section, entry, path))\n return false;\n\n value = resolveSimObject(path);\n return true;\n}\n\n\nbool\nCheckpoint::sectionExists(const string §ion)\n{\n return db->sectionExists(section);\n}\n<commit_msg>checkpointing: fix bug from curTick accessor conversion.<commit_after>\/*\n * Copyright (c) 2002-2005 The Regents of The University of Michigan\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met: redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer;\n * redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution;\n * neither the name of the copyright holders nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n * Authors: Nathan Binkert\n * Erik Hallnor\n * Steve Reinhardt\n *\/\n\n#include <sys\/time.h>\n#include <sys\/types.h>\n#include <sys\/stat.h>\n#include <errno.h>\n\n#include <fstream>\n#include <list>\n#include <string>\n#include <vector>\n\n#include \"base\/inifile.hh\"\n#include \"base\/misc.hh\"\n#include \"base\/output.hh\"\n#include \"base\/str.hh\"\n#include \"base\/trace.hh\"\n#include \"sim\/eventq.hh\"\n#include \"sim\/serialize.hh\"\n#include \"sim\/sim_events.hh\"\n#include \"sim\/sim_exit.hh\"\n#include \"sim\/sim_object.hh\"\n\n\/\/ For stat reset hack\n#include \"sim\/stat_control.hh\"\n\nusing namespace std;\n\nextern SimObject *resolveSimObject(const string &);\n\n\/\/\n\/\/ The base implementations use to_number for parsing and '<<' for\n\/\/ displaying, suitable for integer types.\n\/\/\ntemplate <class T>\nbool\nparseParam(const string &s, T &value)\n{\n return to_number(s, value);\n}\n\ntemplate <class T>\nvoid\nshowParam(ostream &os, const T &value)\n{\n os << value;\n}\n\n\/\/\n\/\/ Template specializations:\n\/\/ - char (8-bit integer)\n\/\/ - floating-point types\n\/\/ - bool\n\/\/ - string\n\/\/\n\n\/\/ Treat 8-bit ints (chars) as ints on output, not as chars\ntemplate <>\nvoid\nshowParam(ostream &os, const char &value)\n{\n os << (int)value;\n}\n\n\ntemplate <>\nvoid\nshowParam(ostream &os, const signed char &value)\n{\n os << (int)value;\n}\n\n\ntemplate <>\nvoid\nshowParam(ostream &os, const unsigned char &value)\n{\n os << (unsigned int)value;\n}\n\n\n\/\/ Use sscanf() for FP types as to_number() only handles integers\ntemplate <>\nbool\nparseParam(const string &s, float &value)\n{\n return (sscanf(s.c_str(), \"%f\", &value) == 1);\n}\n\ntemplate <>\nbool\nparseParam(const string &s, double &value)\n{\n return (sscanf(s.c_str(), \"%lf\", &value) == 1);\n}\n\ntemplate <>\nbool\nparseParam(const string &s, bool &value)\n{\n const string &ls = to_lower(s);\n\n if (ls == \"true\") {\n value = true;\n return true;\n }\n\n if (ls == \"false\") {\n value = false;\n return true;\n }\n\n return false;\n}\n\n\/\/ Display bools as strings\ntemplate <>\nvoid\nshowParam(ostream &os, const bool &value)\n{\n os << (value ? \"true\" : \"false\");\n}\n\n\n\/\/ String requires no processing to speak of\ntemplate <>\nbool\nparseParam(const string &s, string &value)\n{\n value = s;\n return true;\n}\n\nint Serializable::ckptMaxCount = 0;\nint Serializable::ckptCount = 0;\nint Serializable::ckptPrevCount = -1;\n\nvoid\nSerializable::nameOut(ostream &os)\n{\n os << \"\\n[\" << name() << \"]\\n\";\n}\n\nvoid\nSerializable::nameOut(ostream &os, const string &_name)\n{\n os << \"\\n[\" << _name << \"]\\n\";\n}\n\ntemplate <class T>\nvoid\nparamOut(ostream &os, const string &name, const T ¶m)\n{\n os << name << \"=\";\n showParam(os, param);\n os << \"\\n\";\n}\n\ntemplate <class T>\nvoid\narrayParamOut(ostream &os, const string &name, const vector<T> ¶m)\n{\n typename vector<T>::size_type size = param.size();\n os << name << \"=\";\n if (size > 0)\n showParam(os, param[0]);\n for (typename vector<T>::size_type i = 1; i < size; ++i) {\n os << \" \";\n showParam(os, param[i]);\n }\n os << \"\\n\";\n}\n\n\ntemplate <class T>\nvoid\nparamIn(Checkpoint *cp, const string §ion, const string &name, T ¶m)\n{\n string str;\n if (!cp->find(section, name, str) || !parseParam(str, param)) {\n fatal(\"Can't unserialize '%s:%s'\\n\", section, name);\n }\n}\n\ntemplate <class T>\nbool\noptParamIn(Checkpoint *cp, const string §ion, const string &name, T ¶m)\n{\n string str;\n if (!cp->find(section, name, str) || !parseParam(str, param)) {\n warn(\"optional parameter %s:%s not present\\n\", section, name);\n return false;\n } else {\n return true;\n }\n}\n\ntemplate <class T>\nvoid\narrayParamOut(ostream &os, const string &name, const T *param, unsigned size)\n{\n os << name << \"=\";\n if (size > 0)\n showParam(os, param[0]);\n for (unsigned i = 1; i < size; ++i) {\n os << \" \";\n showParam(os, param[i]);\n }\n os << \"\\n\";\n}\n\n\ntemplate <class T>\nvoid\narrayParamIn(Checkpoint *cp, const string §ion, const string &name,\n T *param, unsigned size)\n{\n string str;\n if (!cp->find(section, name, str)) {\n fatal(\"Can't unserialize '%s:%s'\\n\", section, name);\n }\n\n \/\/ code below stolen from VectorParam<T>::parse().\n \/\/ it would be nice to unify these somehow...\n\n vector<string> tokens;\n\n tokenize(tokens, str, ' ');\n\n \/\/ Need this if we were doing a vector\n \/\/ value.resize(tokens.size());\n\n if (tokens.size() != size) {\n fatal(\"Array size mismatch on %s:%s'\\n\", section, name);\n }\n\n for (vector<string>::size_type i = 0; i < tokens.size(); i++) {\n \/\/ need to parse into local variable to handle vector<bool>,\n \/\/ for which operator[] returns a special reference class\n \/\/ that's not the same as 'bool&', (since it's a packed\n \/\/ vector)\n T scalar_value = 0;\n if (!parseParam(tokens[i], scalar_value)) {\n string err(\"could not parse \\\"\");\n\n err += str;\n err += \"\\\"\";\n\n fatal(err);\n }\n\n \/\/ assign parsed value to vector\n param[i] = scalar_value;\n }\n}\n\ntemplate <class T>\nvoid\narrayParamIn(Checkpoint *cp, const string §ion,\n const string &name, vector<T> ¶m)\n{\n string str;\n if (!cp->find(section, name, str)) {\n fatal(\"Can't unserialize '%s:%s'\\n\", section, name);\n }\n\n \/\/ code below stolen from VectorParam<T>::parse().\n \/\/ it would be nice to unify these somehow...\n\n vector<string> tokens;\n\n tokenize(tokens, str, ' ');\n\n \/\/ Need this if we were doing a vector\n \/\/ value.resize(tokens.size());\n\n param.resize(tokens.size());\n\n for (vector<string>::size_type i = 0; i < tokens.size(); i++) {\n \/\/ need to parse into local variable to handle vector<bool>,\n \/\/ for which operator[] returns a special reference class\n \/\/ that's not the same as 'bool&', (since it's a packed\n \/\/ vector)\n T scalar_value = 0;\n if (!parseParam(tokens[i], scalar_value)) {\n string err(\"could not parse \\\"\");\n\n err += str;\n err += \"\\\"\";\n\n fatal(err);\n }\n\n \/\/ assign parsed value to vector\n param[i] = scalar_value;\n }\n}\n\nvoid\nobjParamIn(Checkpoint *cp, const string §ion,\n const string &name, SimObject * ¶m)\n{\n if (!cp->findObj(section, name, param)) {\n fatal(\"Can't unserialize '%s:%s'\\n\", section, name);\n }\n}\n\n\n#define INSTANTIATE_PARAM_TEMPLATES(type) \\\ntemplate void \\\nparamOut(ostream &os, const string &name, type const ¶m); \\\ntemplate void \\\nparamIn(Checkpoint *cp, const string §ion, \\\n const string &name, type & param); \\\ntemplate bool \\\noptParamIn(Checkpoint *cp, const string §ion, \\\n const string &name, type & param); \\\ntemplate void \\\narrayParamOut(ostream &os, const string &name, \\\n type const *param, unsigned size); \\\ntemplate void \\\narrayParamIn(Checkpoint *cp, const string §ion, \\\n const string &name, type *param, unsigned size); \\\ntemplate void \\\narrayParamOut(ostream &os, const string &name, \\\n const vector<type> ¶m); \\\ntemplate void \\\narrayParamIn(Checkpoint *cp, const string §ion, \\\n const string &name, vector<type> ¶m);\n\nINSTANTIATE_PARAM_TEMPLATES(char)\nINSTANTIATE_PARAM_TEMPLATES(signed char)\nINSTANTIATE_PARAM_TEMPLATES(unsigned char)\nINSTANTIATE_PARAM_TEMPLATES(signed short)\nINSTANTIATE_PARAM_TEMPLATES(unsigned short)\nINSTANTIATE_PARAM_TEMPLATES(signed int)\nINSTANTIATE_PARAM_TEMPLATES(unsigned int)\nINSTANTIATE_PARAM_TEMPLATES(signed long)\nINSTANTIATE_PARAM_TEMPLATES(unsigned long)\nINSTANTIATE_PARAM_TEMPLATES(signed long long)\nINSTANTIATE_PARAM_TEMPLATES(unsigned long long)\nINSTANTIATE_PARAM_TEMPLATES(bool)\nINSTANTIATE_PARAM_TEMPLATES(float)\nINSTANTIATE_PARAM_TEMPLATES(double)\nINSTANTIATE_PARAM_TEMPLATES(string)\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/\/ Container for serializing global variables (not associated with\n\/\/\/ any serialized object).\nclass Globals : public Serializable\n{\n public:\n const string name() const;\n void serialize(ostream &os);\n void unserialize(Checkpoint *cp);\n};\n\n\/\/\/ The one and only instance of the Globals class.\nGlobals globals;\n\nconst string\nGlobals::name() const\n{\n return \"Globals\";\n}\n\nvoid\nGlobals::serialize(ostream &os)\n{\n nameOut(os);\n paramOut(os, \"curTick\", curTick());\n\n nameOut(os, \"MainEventQueue\");\n mainEventQueue.serialize(os);\n}\n\nvoid\nGlobals::unserialize(Checkpoint *cp)\n{\n const string §ion = name();\n Tick tick;\n paramIn(cp, section, \"curTick\", tick);\n curTick(tick);\n\n mainEventQueue.unserialize(cp, \"MainEventQueue\");\n}\n\nSerializable::Serializable()\n{\n}\n\nSerializable::~Serializable()\n{\n}\n\nvoid\nSerializable::serialize(ostream &os)\n{\n}\n\nvoid\nSerializable::unserialize(Checkpoint *cp, const string §ion)\n{\n}\n\nvoid\nSerializable::serializeAll(const string &cpt_dir)\n{\n string dir = Checkpoint::setDir(cpt_dir);\n if (mkdir(dir.c_str(), 0775) == -1 && errno != EEXIST)\n fatal(\"couldn't mkdir %s\\n\", dir);\n\n string cpt_file = dir + Checkpoint::baseFilename;\n ofstream outstream(cpt_file.c_str());\n time_t t = time(NULL);\n if (!outstream.is_open())\n fatal(\"Unable to open file %s for writing\\n\", cpt_file.c_str());\n outstream << \"## checkpoint generated: \" << ctime(&t);\n\n globals.serialize(outstream);\n SimObject::serializeAll(outstream);\n}\n\nvoid\nSerializable::unserializeGlobals(Checkpoint *cp)\n{\n globals.unserialize(cp);\n}\n\nvoid\ndebug_serialize(const string &cpt_dir)\n{\n Serializable::serializeAll(cpt_dir);\n}\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ SerializableClass member definitions\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/ Map of class names to SerializableBuilder creation functions.\n\/\/ Need to make this a pointer so we can force initialization on the\n\/\/ first reference; otherwise, some SerializableClass constructors\n\/\/ may be invoked before the classMap constructor.\nmap<string, SerializableClass::CreateFunc> *SerializableClass::classMap = 0;\n\n\/\/ SerializableClass constructor: add mapping to classMap\nSerializableClass::SerializableClass(const string &className,\n CreateFunc createFunc)\n{\n if (classMap == NULL)\n classMap = new map<string, SerializableClass::CreateFunc>();\n\n if ((*classMap)[className])\n fatal(\"Error: simulation object class %s redefined\\n\", className);\n\n \/\/ add className --> createFunc to class map\n (*classMap)[className] = createFunc;\n}\n\n\/\/\n\/\/\nSerializable *\nSerializableClass::createObject(Checkpoint *cp, const string §ion)\n{\n string className;\n\n if (!cp->find(section, \"type\", className)) {\n fatal(\"Serializable::create: no 'type' entry in section '%s'.\\n\",\n section);\n }\n\n CreateFunc createFunc = (*classMap)[className];\n\n if (createFunc == NULL) {\n fatal(\"Serializable::create: no create function for class '%s'.\\n\",\n className);\n }\n\n Serializable *object = createFunc(cp, section);\n\n assert(object != NULL);\n\n return object;\n}\n\n\nSerializable *\nSerializable::create(Checkpoint *cp, const string §ion)\n{\n Serializable *object = SerializableClass::createObject(cp, section);\n object->unserialize(cp, section);\n return object;\n}\n\n\nconst char *Checkpoint::baseFilename = \"m5.cpt\";\n\nstring Checkpoint::currentDirectory;\n\nstring\nCheckpoint::setDir(const string &name)\n{\n \/\/ use csprintf to insert curTick() into directory name if it\n \/\/ appears to have a format placeholder in it.\n currentDirectory = (name.find(\"%\") != string::npos) ?\n csprintf(name, curTick()) : name;\n if (currentDirectory[currentDirectory.size() - 1] != '\/')\n currentDirectory += \"\/\";\n return currentDirectory;\n}\n\nstring\nCheckpoint::dir()\n{\n return currentDirectory;\n}\n\n\nCheckpoint::Checkpoint(const string &cpt_dir)\n : db(new IniFile), cptDir(setDir(cpt_dir))\n{\n string filename = cptDir + \"\/\" + Checkpoint::baseFilename;\n if (!db->load(filename)) {\n fatal(\"Can't load checkpoint file '%s'\\n\", filename);\n }\n}\n\n\nbool\nCheckpoint::find(const string §ion, const string &entry, string &value)\n{\n return db->find(section, entry, value);\n}\n\n\nbool\nCheckpoint::findObj(const string §ion, const string &entry,\n SimObject *&value)\n{\n string path;\n\n if (!db->find(section, entry, path))\n return false;\n\n value = resolveSimObject(path);\n return true;\n}\n\n\nbool\nCheckpoint::sectionExists(const string §ion)\n{\n return db->sectionExists(section);\n}\n<|endoftext|>"} {"text":"<commit_before>\/* JDELAY - regenerating delay instrument, adapted from DELAY\n\n Compared with DELAY, JDELAY adds:\n - a simple low-pass filter\n - control over wet\/dry mix\n - a DC blocking filter\n - switchable pre\/post-fader delay\n \n Parameters:\n p0 = output start time\n p1 = input start time\n p2 = input duration\n p3 = amplitude multiplier\n p4 = delay time\n p5 = delay feedback (i.e., regeneration multiplier) [-1 to 1]\n p6 = ring-down duration\n p7 = cutoff freq for low-pass filter (in cps) (0 to disable filter)\n p8 = wet\/dry mix (0: dry -> 1: wet)\n p9 = input channel number [optional, default is 0]\n p10 = pan (in percent-to-left form: 0-1) [optional, default is .5] \n p11 = pre-fader send (0: No, 1: Yes) [optional, default is No]\n p12 = apply DC blocking filter (0: No, 1: Yes) [optional, default is Yes]\n (DC bias can affect sounds made with high feedback setting.)\n \n p3 (amplitude), p4 (delay time), p5 (feedback), p7 (cutoff), p8 (wet\/dry)\n and p8 (pan) can receive dynamic updates from a table or real-time control\n source.\n\n If an old-style gen table 1 is present, its values will be multiplied\n by the p3 amplitude multiplier, even if the latter is dynamic.\n\n The point of the ring-down duration parameter is to let you control\n how long the delay will sound after the input has stopped. Too short\n a time, and the sound may be cut off prematurely.\n\n If pre-fader send is set to 1, sends input signal to delay line with\n no attenuation. Then p3 (amp multiplier) and setline controls entire\n note, including delay ring-down.\n \n John Gibson (jgg9c@virginia.edu), 6\/23\/99; rev for v4, 7\/21\/04\n*\/\n#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n#include <ugens.h>\n#include <Instrument.h>\n#include \"JDELAY.h\"\n#include <rt.h>\n#include <rtdefs.h>\n\n#define MAXDELTIME 30.0 \/\/ seconds (176400 bytes per second at SR=44100)\n\n\/\/ local functions\nstatic void toneset(double, int, double []);\nstatic double tone(double, double []);\n\n\nJDELAY::JDELAY() : Instrument()\n{\n in = NULL;\n delay = NULL;\n branch = 0;\n usefilt = false;\n warn_deltime = true;\n}\n\n\nJDELAY::~JDELAY()\n{\n delete [] in;\n delete delay;\n}\n\n\nint JDELAY::init(double p[], int n_args)\n{\n nargs = n_args;\n float outskip = p[0];\n float inskip = p[1];\n float dur = p[2];\n amp = p[3];\n float deltime = p[4];\n regen = p[5];\n float ringdur = p[6];\n cutoff = p[7];\n percent_wet = p[8];\n inchan = n_args > 9 ? (int) p[9] : 0;\n prefadersend = n_args > 11 ? (bool) p[11] : false; \/\/ default is \"no\"\n dcblock = n_args > 12 ? (bool) p[12] : true; \/\/ default is \"yes\"\n\n if (rtsetinput(inskip, this) != 0)\n return DONT_SCHEDULE;\n nsamps = rtsetoutput(outskip, dur + ringdur, this);\n insamps = (int) (dur * SR + 0.5);\n\n if (inchan >= inputChannels())\n return die(\"JDELAY\", \"You asked for channel %d of a %d-channel file.\",\n inchan, inputChannels());\n\n if (regen < -1.0 || regen > 1.0)\n return die(\"JDELAY\", \"Regeneration multiplier must be between -1 and 1.\");\n\n if (cutoff < 0.0)\n return die(\"JDELAY\",\n \"Cutoff freq. should be positive (or zero to disable filter).\");\n else if (cutoff == 0.0)\n advise(\"JDELAY\", \"Low-pass filter disabled.\");\n else {\n usefilt = true;\n toneset(cutoff, 1, tonedata);\n }\n\n if (percent_wet < 0.0 || percent_wet > 1.0)\n return die(\"JDELAY\", \"Wet\/dry mix must be between 0 and 1 inclusive.\");\n\n if (deltime > MAXDELTIME)\n return die(\"JDELAY\", \"Maximum delay time (%g seconds) exceeded.\",\n MAXDELTIME);\n\n long maxdelsamps = (long) (MAXDELTIME * SR + 0.5);\n delay = new Ozdelay(maxdelsamps);\n if (delay == NULL)\n return die(\"JDELAY\", \"Can't allocate delay line memory.\");\n\n amptable = floc(1);\n if (amptable) {\n int amplen = fsize(1);\n if (prefadersend)\n tableset(dur + ringdur, amplen, amptabs);\n else\n tableset(dur, amplen, amptabs);\n }\n\n skip = (int) (SR \/ (float) resetval);\n\n prev_in = prev_out = 0.0; \/\/ for DC-blocker\n\n return nsamps;\n}\n\n\nvoid JDELAY::doupdate(double p[])\n{\n amp = p[3];\n if (amptable)\n amp *= tablei(currentFrame(), amptable, amptabs);\n\n float deltime = p[4];\n if (deltime > MAXDELTIME) {\n if (warn_deltime) {\n warn(\"JDELAY\", \"Maximum delay time (%g seconds) exceeded!\",\n MAXDELTIME);\n warn_deltime = false;\n }\n delsamps = MAXDELTIME * SR;\n }\n else\n delsamps = deltime * SR;\n\n regen = p[5];\n if (regen < -1.0)\n regen = -1.0;\n else if (regen > 1.0)\n regen = 1.0;\n\n if (usefilt && p[7] != cutoff) {\n cutoff = p[7];\n if (cutoff <= 0.0)\n cutoff = 0.1;\n toneset(cutoff, 0, tonedata);\n }\n\n percent_wet = p[8];\n if (percent_wet < 0.0)\n percent_wet = 0.0;\n else if (percent_wet > 1.0)\n percent_wet = 1.0;\n\n pctleft = nargs > 10 ? p[10] : 0.5; \/\/ default is center\n}\n\n\nint JDELAY::configure()\n{\n in = new float [RTBUFSAMPS * inputChannels()];\n return in ? 0 : -1;\n}\n\n\nint JDELAY::run()\n{\n int samps = framesToRun() * inputChannels();\n\n if (currentFrame() < insamps)\n rtgetin(in, this, samps);\n\n for (int i = 0; i < samps; i += inputChannels()) {\n if (--branch <= 0) {\n double p[11];\n update(p, 11,\n kAmp | kDelTime | kDelRegen | kCutoff | kWetPercent | kPan);\n doupdate(p);\n branch = skip;\n }\n\n float delsig = delay->getsamp(delsamps) * regen;\n\n float insig;\n if (currentFrame() < insamps) \/\/ still taking input from file\n insig = in[i + inchan];\n else\n insig = 0.0;\n\n float out[2];\n if (prefadersend) {\n delay->putsamp(insig + delsig);\n out[0] = insig * (1.0 - percent_wet) + delsig * percent_wet;\n out[0] *= amp;\n }\n else {\n insig *= amp;\n delay->putsamp(insig + delsig);\n out[0] = insig * (1.0 - percent_wet) + delsig * percent_wet;\n }\n\n \/* NOTE: We filter the sig *after* putting it in the delay line.\n Otherwise, pitch for short delays drops with low cutoff freqs.\n *\/\n if (usefilt)\n out[0] = tone(out[0], tonedata);\n\n \/* The DC-blocking code is from Perry Cook's STK (STK98v2\/DCBlock.cpp).\n It works pretty well (and quickly) for all but extreme cases. But I've\n gotten JDELAY to generate files with a fair amount of DC even *with*\n this simple filter. The Remove DC function in mxv works better. It's\n the standard cmix elliptical filter with 60db atten., stopband at 5 hz,\n and passband at 20 hz. But that's overkill for here.\n *\/\n if (dcblock) {\n float tmp_in = out[0];\n out[0] = tmp_in - prev_in + (0.99 * prev_out);\n prev_in = tmp_in;\n prev_out = out[0];\n }\n\n if (outputChannels() == 2) {\n out[1] = out[0] * (1.0 - pctleft);\n out[0] *= pctleft;\n }\n rtaddout(out);\n increment();\n }\n\n return framesToRun();\n}\n\n\n\/* -------------------------------------------------------------------------- *\/\n\/* This filter nabbed from Doug Scott's place program *\/\n\n\/* toneset calculates the coefficients for tone.\n <cutoff> is -3db point in cps\n <flag> will reset history if set to 1\n <data> is an array of 3 doubles, used for bookeeping\n NOTE: JDELAY doesn't try to use the inverse function cited below.\n*\/\nstatic void\ntoneset(double cutoff, int flag, double data[])\n{\n double x;\n\n x = 2.0 - cos(cutoff * PI2 \/ SR); \/* feedback coeff. *\/\n data[1] = x - sqrt(x * x - 1.0); \n data[0] = 1.0 - data[1]; \/* gain coeff. *\/\n if (cutoff < 0.0)\n data[1] *= -1.0; \/* inverse function *\/\n if (flag)\n data[2] = 0.0;\n}\n\n\n\/* tone is a simple 1st order recursive lowpass filter\n <data> is an array of 3 doubles, used for bookeeping\n*\/\nstatic double\ntone(double sig, double data[])\n{\n data[2] = data[0] * sig + data[1] * data[2];\n return data[2];\n}\n\n\nInstrument *makeJDELAY()\n{\n JDELAY *inst;\n\n inst = new JDELAY();\n inst->set_bus_config(\"JDELAY\");\n\n return inst;\n}\n\nvoid rtprofile()\n{\n RT_INTRO(\"JDELAY\", makeJDELAY);\n}\n\n<commit_msg>Use nSamps() for init return.<commit_after>\/* JDELAY - regenerating delay instrument, adapted from DELAY\n\n Compared with DELAY, JDELAY adds:\n - a simple low-pass filter\n - control over wet\/dry mix\n - a DC blocking filter\n - switchable pre\/post-fader delay\n \n Parameters:\n p0 = output start time\n p1 = input start time\n p2 = input duration\n p3 = amplitude multiplier\n p4 = delay time\n p5 = delay feedback (i.e., regeneration multiplier) [-1 to 1]\n p6 = ring-down duration\n p7 = cutoff freq for low-pass filter (in cps) (0 to disable filter)\n p8 = wet\/dry mix (0: dry -> 1: wet)\n p9 = input channel number [optional, default is 0]\n p10 = pan (in percent-to-left form: 0-1) [optional, default is .5] \n p11 = pre-fader send (0: No, 1: Yes) [optional, default is No]\n p12 = apply DC blocking filter (0: No, 1: Yes) [optional, default is Yes]\n (DC bias can affect sounds made with high feedback setting.)\n \n p3 (amplitude), p4 (delay time), p5 (feedback), p7 (cutoff), p8 (wet\/dry)\n and p8 (pan) can receive dynamic updates from a table or real-time control\n source.\n\n If an old-style gen table 1 is present, its values will be multiplied\n by the p3 amplitude multiplier, even if the latter is dynamic.\n\n The point of the ring-down duration parameter is to let you control\n how long the delay will sound after the input has stopped. Too short\n a time, and the sound may be cut off prematurely.\n\n If pre-fader send is set to 1, sends input signal to delay line with\n no attenuation. Then p3 (amp multiplier) and setline controls entire\n note, including delay ring-down.\n \n John Gibson (jgg9c@virginia.edu), 6\/23\/99; rev for v4, 7\/21\/04\n*\/\n#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n#include <ugens.h>\n#include <Instrument.h>\n#include \"JDELAY.h\"\n#include <rt.h>\n#include <rtdefs.h>\n\n#define MAXDELTIME 30.0 \/\/ seconds (176400 bytes per second at SR=44100)\n\n\/\/ local functions\nstatic void toneset(double, int, double []);\nstatic double tone(double, double []);\n\n\nJDELAY::JDELAY() : Instrument()\n{\n in = NULL;\n delay = NULL;\n branch = 0;\n usefilt = false;\n warn_deltime = true;\n}\n\n\nJDELAY::~JDELAY()\n{\n delete [] in;\n delete delay;\n}\n\n\nint JDELAY::init(double p[], int n_args)\n{\n nargs = n_args;\n float outskip = p[0];\n float inskip = p[1];\n float dur = p[2];\n amp = p[3];\n float deltime = p[4];\n regen = p[5];\n float ringdur = p[6];\n cutoff = p[7];\n percent_wet = p[8];\n inchan = n_args > 9 ? (int) p[9] : 0;\n prefadersend = n_args > 11 ? (bool) p[11] : false; \/\/ default is \"no\"\n dcblock = n_args > 12 ? (bool) p[12] : true; \/\/ default is \"yes\"\n\n if (rtsetinput(inskip, this) != 0)\n return DONT_SCHEDULE;\n nsamps = rtsetoutput(outskip, dur + ringdur, this);\n insamps = (int) (dur * SR + 0.5);\n\n if (inchan >= inputChannels())\n return die(\"JDELAY\", \"You asked for channel %d of a %d-channel file.\",\n inchan, inputChannels());\n\n if (regen < -1.0 || regen > 1.0)\n return die(\"JDELAY\", \"Regeneration multiplier must be between -1 and 1.\");\n\n if (cutoff < 0.0)\n return die(\"JDELAY\",\n \"Cutoff freq. should be positive (or zero to disable filter).\");\n else if (cutoff == 0.0)\n advise(\"JDELAY\", \"Low-pass filter disabled.\");\n else {\n usefilt = true;\n toneset(cutoff, 1, tonedata);\n }\n\n if (percent_wet < 0.0 || percent_wet > 1.0)\n return die(\"JDELAY\", \"Wet\/dry mix must be between 0 and 1 inclusive.\");\n\n if (deltime > MAXDELTIME)\n return die(\"JDELAY\", \"Maximum delay time (%g seconds) exceeded.\",\n MAXDELTIME);\n\n long maxdelsamps = (long) (MAXDELTIME * SR + 0.5);\n delay = new Ozdelay(maxdelsamps);\n if (delay == NULL)\n return die(\"JDELAY\", \"Can't allocate delay line memory.\");\n\n amptable = floc(1);\n if (amptable) {\n int amplen = fsize(1);\n if (prefadersend)\n tableset(dur + ringdur, amplen, amptabs);\n else\n tableset(dur, amplen, amptabs);\n }\n\n skip = (int) (SR \/ (float) resetval);\n\n prev_in = prev_out = 0.0; \/\/ for DC-blocker\n\n return nSamps();\n}\n\n\nvoid JDELAY::doupdate(double p[])\n{\n amp = p[3];\n if (amptable)\n amp *= tablei(currentFrame(), amptable, amptabs);\n\n float deltime = p[4];\n if (deltime > MAXDELTIME) {\n if (warn_deltime) {\n warn(\"JDELAY\", \"Maximum delay time (%g seconds) exceeded!\",\n MAXDELTIME);\n warn_deltime = false;\n }\n delsamps = MAXDELTIME * SR;\n }\n else\n delsamps = deltime * SR;\n\n regen = p[5];\n if (regen < -1.0)\n regen = -1.0;\n else if (regen > 1.0)\n regen = 1.0;\n\n if (usefilt && p[7] != cutoff) {\n cutoff = p[7];\n if (cutoff <= 0.0)\n cutoff = 0.1;\n toneset(cutoff, 0, tonedata);\n }\n\n percent_wet = p[8];\n if (percent_wet < 0.0)\n percent_wet = 0.0;\n else if (percent_wet > 1.0)\n percent_wet = 1.0;\n\n pctleft = nargs > 10 ? p[10] : 0.5; \/\/ default is center\n}\n\n\nint JDELAY::configure()\n{\n in = new float [RTBUFSAMPS * inputChannels()];\n return in ? 0 : -1;\n}\n\n\nint JDELAY::run()\n{\n int samps = framesToRun() * inputChannels();\n\n if (currentFrame() < insamps)\n rtgetin(in, this, samps);\n\n for (int i = 0; i < samps; i += inputChannels()) {\n if (--branch <= 0) {\n double p[11];\n update(p, 11,\n kAmp | kDelTime | kDelRegen | kCutoff | kWetPercent | kPan);\n doupdate(p);\n branch = skip;\n }\n\n float delsig = delay->getsamp(delsamps) * regen;\n\n float insig;\n if (currentFrame() < insamps) \/\/ still taking input from file\n insig = in[i + inchan];\n else\n insig = 0.0;\n\n float out[2];\n if (prefadersend) {\n delay->putsamp(insig + delsig);\n out[0] = insig * (1.0 - percent_wet) + delsig * percent_wet;\n out[0] *= amp;\n }\n else {\n insig *= amp;\n delay->putsamp(insig + delsig);\n out[0] = insig * (1.0 - percent_wet) + delsig * percent_wet;\n }\n\n \/* NOTE: We filter the sig *after* putting it in the delay line.\n Otherwise, pitch for short delays drops with low cutoff freqs.\n *\/\n if (usefilt)\n out[0] = tone(out[0], tonedata);\n\n \/* The DC-blocking code is from Perry Cook's STK (STK98v2\/DCBlock.cpp).\n It works pretty well (and quickly) for all but extreme cases. But I've\n gotten JDELAY to generate files with a fair amount of DC even *with*\n this simple filter. The Remove DC function in mxv works better. It's\n the standard cmix elliptical filter with 60db atten., stopband at 5 hz,\n and passband at 20 hz. But that's overkill for here.\n *\/\n if (dcblock) {\n float tmp_in = out[0];\n out[0] = tmp_in - prev_in + (0.99 * prev_out);\n prev_in = tmp_in;\n prev_out = out[0];\n }\n\n if (outputChannels() == 2) {\n out[1] = out[0] * (1.0 - pctleft);\n out[0] *= pctleft;\n }\n rtaddout(out);\n increment();\n }\n\n return framesToRun();\n}\n\n\n\/* -------------------------------------------------------------------------- *\/\n\/* This filter nabbed from Doug Scott's place program *\/\n\n\/* toneset calculates the coefficients for tone.\n <cutoff> is -3db point in cps\n <flag> will reset history if set to 1\n <data> is an array of 3 doubles, used for bookeeping\n NOTE: JDELAY doesn't try to use the inverse function cited below.\n*\/\nstatic void\ntoneset(double cutoff, int flag, double data[])\n{\n double x;\n\n x = 2.0 - cos(cutoff * PI2 \/ SR); \/* feedback coeff. *\/\n data[1] = x - sqrt(x * x - 1.0); \n data[0] = 1.0 - data[1]; \/* gain coeff. *\/\n if (cutoff < 0.0)\n data[1] *= -1.0; \/* inverse function *\/\n if (flag)\n data[2] = 0.0;\n}\n\n\n\/* tone is a simple 1st order recursive lowpass filter\n <data> is an array of 3 doubles, used for bookeeping\n*\/\nstatic double\ntone(double sig, double data[])\n{\n data[2] = data[0] * sig + data[1] * data[2];\n return data[2];\n}\n\n\nInstrument *makeJDELAY()\n{\n JDELAY *inst;\n\n inst = new JDELAY();\n inst->set_bus_config(\"JDELAY\");\n\n return inst;\n}\n\nvoid rtprofile()\n{\n RT_INTRO(\"JDELAY\", makeJDELAY);\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/****************************************************************************\n**\n** Copyright (c) 2008-2009 Nokia Corporation and\/or its subsidiary(-ies).\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n** This file is part of the Qt Mobility Components.\n**\n** $QT_BEGIN_LICENSE:LGPL$\n** No Commercial Usage\n** This file contains pre-release code and may not be distributed.\n** You may use this file in accordance with the terms and conditions\n** contained in the Technology Preview License Agreement accompanying\n** this package.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Nokia gives you certain\n** additional rights. These rights are described in the Nokia Qt LGPL\n** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this\n** package.\n**\n** If you have questions regarding the use of this file, please\n** contact Nokia at http:\/\/qt.nokia.com\/contact.\n** $QT_END_LICENSE$\n**\n****************************************************************************\/\n#include \"qmessagestore.h\"\n#include \"qmfhelpers_p.h\"\n\n#include <qmailstore.h>\n\n#include <QCoreApplication>\n#include <QEvent>\n\nusing namespace QmfHelpers;\n\nclass QMessageStorePrivate\n{\npublic:\n QMessageStorePrivate() : _store(QMailStore::instance()), _error(QMessageStore::NoError) {}\n\n QMailStore *_store;\n QMessageStore::ErrorCode _error;\n\n static QMailStore *convert(QMessageStore *store);\n\n Q_SCOPED_STATIC_DECLARE(QMessageStore,storeInstance);\n\n static void registerMessageStatus(QMailStore *store, const QString &field);\n static void createNonexistentFolder(QMailStore *store, const QString &path, quint64 status);\n};\n\nQ_SCOPED_STATIC_DEFINE(QMessageStore,QMessageStorePrivate,storeInstance);\n\nQMailStore *QMessageStorePrivate::convert(QMessageStore *store)\n{\n return store->d_ptr->_store;\n}\n\nvoid QMessageStorePrivate::registerMessageStatus(QMailStore *store, const QString &field)\n{\n store->registerMessageStatusFlag(field);\n}\n\nvoid QMessageStorePrivate::createNonexistentFolder(QMailStore *store, const QString &path, quint64 status)\n{\n QMailFolderKey pathKey(QMailFolderKey::path(path));\n QMailFolderKey accountKey(QMailFolderKey::parentAccountId(QMailAccountId()));\n\n if (store->countFolders(pathKey & accountKey) == 0) {\n QMailFolder folder;\n folder.setPath(path);\n folder.setStatus(status);\n\n if (!store->addFolder(&folder)) {\n qWarning() << \"Unable to add folder for:\" << path;\n }\n }\n}\n\nnamespace QmfHelpers {\n\nQMailStore *convert(QMessageStore *store)\n{\n return QMessageStorePrivate::convert(store);\n}\n\n}\n\nQMessageStore::QMessageStore(QObject *parent)\n : QObject(parent),\n d_ptr(new QMessageStorePrivate)\n{\n Q_ASSERT(instance() != 0);\n}\n\nQMessageStore::~QMessageStore()\n{\n delete d_ptr;\n}\n\nQMessageStore::ErrorCode QMessageStore::lastError() const\n{\n if (d_ptr->_error != QMessageStore::NoError) {\n return d_ptr->_error;\n }\n\n return convert(d_ptr->_store->lastError());\n}\n\nQMessageIdList QMessageStore::queryMessages(const QMessageFilterKey &key, const QMessageSortKey &sortKey, uint limit, uint offset) const\n{\n if (key.options() != 0) {\n d_ptr->_error = QMessageStore::NotYetImplemented;\n return QMessageIdList();\n }\n \n d_ptr->_error = QMessageStore::NoError;\n return convert(d_ptr->_store->queryMessages(convert(key), convert(sortKey), limit, offset));\n}\n\nQMessageIdList QMessageStore::queryMessages(const QString &body, const QMessageFilterKey &key, const QMessageSortKey &sortKey, QMessageDataComparator::Options options, uint limit, uint offset) const\n{\n Q_UNUSED(key)\n Q_UNUSED(sortKey)\n Q_UNUSED(body)\n Q_UNUSED(options)\n Q_UNUSED(limit)\n Q_UNUSED(offset)\n return QMessageIdList(); \/\/ stub\n}\n\n#ifdef QMESSAGING_OPTIONAL_FOLDER\nQMessageFolderIdList QMessageStore::queryFolders(const QMessageFolderFilterKey &key, const QMessageFolderSortKey &sortKey, uint limit, uint offset) const\n{\n if (key.options() != 0) {\n d_ptr->_error = QMessageStore::NotYetImplemented;\n return QMessageFolderIdList();\n }\n \n d_ptr->_error = QMessageStore::NoError;\n return convert(d_ptr->_store->queryFolders(convert(key), convert(sortKey), limit, offset));\n}\n#endif\n\nQMessageAccountIdList QMessageStore::queryAccounts(const QMessageAccountFilterKey &key, const QMessageAccountSortKey &sortKey, uint limit, uint offset) const\n{\n if (key.options() != 0) {\n d_ptr->_error = QMessageStore::NotYetImplemented;\n return QMessageAccountIdList();\n }\n \n d_ptr->_error = QMessageStore::NoError;\n return convert(d_ptr->_store->queryAccounts(convert(key), convert(sortKey), limit, offset));\n}\n\nint QMessageStore::countMessages(const QMessageFilterKey& key) const\n{\n if (key.options() != 0) {\n d_ptr->_error = QMessageStore::NotYetImplemented;\n return 0;\n }\n \n d_ptr->_error = QMessageStore::NoError;\n return d_ptr->_store->countMessages(convert(key));\n}\n\n#ifdef QMESSAGING_OPTIONAL_FOLDER\nint QMessageStore::countFolders(const QMessageFolderFilterKey& key) const\n{\n if (key.options() != 0) {\n d_ptr->_error = QMessageStore::NotYetImplemented;\n return 0;\n }\n \n d_ptr->_error = QMessageStore::NoError;\n return d_ptr->_store->countFolders(convert(key));\n}\n#endif\n\nint QMessageStore::countAccounts(const QMessageAccountFilterKey& key) const\n{\n if (key.options() != 0) {\n d_ptr->_error = QMessageStore::NotYetImplemented;\n return 0;\n }\n \n d_ptr->_error = QMessageStore::NoError;\n return d_ptr->_store->countAccounts(convert(key));\n}\n\nbool QMessageStore::removeMessage(const QMessageId& id, QMessageStore::RemovalOption option)\n{\n d_ptr->_error = QMessageStore::NoError;\n return d_ptr->_store->removeMessage(convert(id), convert(option));\n}\n\nbool QMessageStore::removeMessages(const QMessageFilterKey& key, QMessageStore::RemovalOption option)\n{\n d_ptr->_error = QMessageStore::NoError;\n return d_ptr->_store->removeMessages(convert(key), convert(option));\n}\n\nbool QMessageStore::addMessage(QMessage *m)\n{\n QMailMessage msg(convert(*m));\n\n d_ptr->_error = QMessageStore::NoError;\n return d_ptr->_store->addMessage(&msg);\n}\n\nbool QMessageStore::updateMessage(QMessage *m)\n{\n QMailMessage msg(convert(*m));\n\n d_ptr->_error = QMessageStore::NoError;\n return d_ptr->_store->updateMessage(&msg);\n}\n\nQMessage QMessageStore::message(const QMessageId& id) const\n{\n d_ptr->_error = QMessageStore::NoError;\n return convert(d_ptr->_store->message(convert(id)));\n}\n\n#ifdef QMESSAGING_OPTIONAL_FOLDER\nQMessageFolder QMessageStore::folder(const QMessageFolderId& id) const\n{\n d_ptr->_error = QMessageStore::NoError;\n return convert(d_ptr->_store->folder(convert(id)));\n}\n#endif\n\nQMessageAccount QMessageStore::account(const QMessageAccountId& id) const\n{\n d_ptr->_error = QMessageStore::NoError;\n return convert(d_ptr->_store->account(convert(id)));\n}\n\nQMessageStore* QMessageStore::instance()\n{\n static bool initialised(false);\n\n QMessageStore* store(QMessageStorePrivate::storeInstance());\n\n if (!initialised) {\n initialised = true;\n\n QMailStore *mailStore(convert(store));\n\n \/\/ Perform any initialisation tasks\n QMessageStorePrivate::registerMessageStatus(mailStore, \"QMessage::HighPriority\");\n QMessageStorePrivate::registerMessageStatus(mailStore, \"QMessage::LowPriority\");\n\n \/\/ Create the standard folders if they do not exist\n typedef QPair<const char*, quint64> FolderAttributes;\n foreach (const FolderAttributes &folder, QList<FolderAttributes>() << FolderAttributes(\"Inbox\", QMailFolder::Incoming)\n << FolderAttributes(\"Outbox\", QMailFolder::Outgoing)\n << FolderAttributes(\"Drafts\", QMailFolder::Outgoing | QMailFolder::Trash)\n << FolderAttributes(\"Sent\", QMailFolder::Outgoing | QMailFolder::Sent)\n << FolderAttributes(\"Trash\", QMailFolder::Trash)) {\n QMessageStorePrivate::createNonexistentFolder(mailStore, folder.first, folder.second);\n }\n }\n\n return store;\n}\n \nvoid QMessageStore::startNotifications(const QMessageFilterKey &key)\n{\n if (key.options() != 0) {\n d_ptr->_error = QMessageStore::NotYetImplemented;\n return;\n }\n \n \/\/ TODO: implement notifications\n Q_UNUSED(key) \n}\n\nvoid QMessageStore::stopNotifications()\n{\n \/\/ TODO: implement notifications\n}\n\n<commit_msg>Remove assertion causing infinite recursion.<commit_after>\/****************************************************************************\n**\n** Copyright (c) 2008-2009 Nokia Corporation and\/or its subsidiary(-ies).\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n** This file is part of the Qt Mobility Components.\n**\n** $QT_BEGIN_LICENSE:LGPL$\n** No Commercial Usage\n** This file contains pre-release code and may not be distributed.\n** You may use this file in accordance with the terms and conditions\n** contained in the Technology Preview License Agreement accompanying\n** this package.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Nokia gives you certain\n** additional rights. These rights are described in the Nokia Qt LGPL\n** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this\n** package.\n**\n** If you have questions regarding the use of this file, please\n** contact Nokia at http:\/\/qt.nokia.com\/contact.\n** $QT_END_LICENSE$\n**\n****************************************************************************\/\n#include \"qmessagestore.h\"\n#include \"qmfhelpers_p.h\"\n\n#include <qmailstore.h>\n\n#include <QCoreApplication>\n#include <QEvent>\n\nusing namespace QmfHelpers;\n\nclass QMessageStorePrivate\n{\npublic:\n QMessageStorePrivate() : _store(QMailStore::instance()), _error(QMessageStore::NoError) {}\n\n QMailStore *_store;\n QMessageStore::ErrorCode _error;\n\n static QMailStore *convert(QMessageStore *store);\n\n Q_SCOPED_STATIC_DECLARE(QMessageStore,storeInstance);\n\n static void registerMessageStatus(QMailStore *store, const QString &field);\n static void createNonexistentFolder(QMailStore *store, const QString &path, quint64 status);\n};\n\nQ_SCOPED_STATIC_DEFINE(QMessageStore,QMessageStorePrivate,storeInstance);\n\nQMailStore *QMessageStorePrivate::convert(QMessageStore *store)\n{\n return store->d_ptr->_store;\n}\n\nvoid QMessageStorePrivate::registerMessageStatus(QMailStore *store, const QString &field)\n{\n store->registerMessageStatusFlag(field);\n}\n\nvoid QMessageStorePrivate::createNonexistentFolder(QMailStore *store, const QString &path, quint64 status)\n{\n QMailFolderKey pathKey(QMailFolderKey::path(path));\n QMailFolderKey accountKey(QMailFolderKey::parentAccountId(QMailAccountId()));\n\n if (store->countFolders(pathKey & accountKey) == 0) {\n QMailFolder folder;\n folder.setPath(path);\n folder.setStatus(status);\n\n if (!store->addFolder(&folder)) {\n qWarning() << \"Unable to add folder for:\" << path;\n }\n }\n}\n\nnamespace QmfHelpers {\n\nQMailStore *convert(QMessageStore *store)\n{\n return QMessageStorePrivate::convert(store);\n}\n\n}\n\nQMessageStore::QMessageStore(QObject *parent)\n : QObject(parent),\n d_ptr(new QMessageStorePrivate)\n{\n}\n\nQMessageStore::~QMessageStore()\n{\n delete d_ptr;\n}\n\nQMessageStore::ErrorCode QMessageStore::lastError() const\n{\n if (d_ptr->_error != QMessageStore::NoError) {\n return d_ptr->_error;\n }\n\n return convert(d_ptr->_store->lastError());\n}\n\nQMessageIdList QMessageStore::queryMessages(const QMessageFilterKey &key, const QMessageSortKey &sortKey, uint limit, uint offset) const\n{\n if (key.options() != 0) {\n d_ptr->_error = QMessageStore::NotYetImplemented;\n return QMessageIdList();\n }\n \n d_ptr->_error = QMessageStore::NoError;\n return convert(d_ptr->_store->queryMessages(convert(key), convert(sortKey), limit, offset));\n}\n\nQMessageIdList QMessageStore::queryMessages(const QString &body, const QMessageFilterKey &key, const QMessageSortKey &sortKey, QMessageDataComparator::Options options, uint limit, uint offset) const\n{\n Q_UNUSED(key)\n Q_UNUSED(sortKey)\n Q_UNUSED(body)\n Q_UNUSED(options)\n Q_UNUSED(limit)\n Q_UNUSED(offset)\n return QMessageIdList(); \/\/ stub\n}\n\n#ifdef QMESSAGING_OPTIONAL_FOLDER\nQMessageFolderIdList QMessageStore::queryFolders(const QMessageFolderFilterKey &key, const QMessageFolderSortKey &sortKey, uint limit, uint offset) const\n{\n if (key.options() != 0) {\n d_ptr->_error = QMessageStore::NotYetImplemented;\n return QMessageFolderIdList();\n }\n \n d_ptr->_error = QMessageStore::NoError;\n return convert(d_ptr->_store->queryFolders(convert(key), convert(sortKey), limit, offset));\n}\n#endif\n\nQMessageAccountIdList QMessageStore::queryAccounts(const QMessageAccountFilterKey &key, const QMessageAccountSortKey &sortKey, uint limit, uint offset) const\n{\n if (key.options() != 0) {\n d_ptr->_error = QMessageStore::NotYetImplemented;\n return QMessageAccountIdList();\n }\n \n d_ptr->_error = QMessageStore::NoError;\n return convert(d_ptr->_store->queryAccounts(convert(key), convert(sortKey), limit, offset));\n}\n\nint QMessageStore::countMessages(const QMessageFilterKey& key) const\n{\n if (key.options() != 0) {\n d_ptr->_error = QMessageStore::NotYetImplemented;\n return 0;\n }\n \n d_ptr->_error = QMessageStore::NoError;\n return d_ptr->_store->countMessages(convert(key));\n}\n\n#ifdef QMESSAGING_OPTIONAL_FOLDER\nint QMessageStore::countFolders(const QMessageFolderFilterKey& key) const\n{\n if (key.options() != 0) {\n d_ptr->_error = QMessageStore::NotYetImplemented;\n return 0;\n }\n \n d_ptr->_error = QMessageStore::NoError;\n return d_ptr->_store->countFolders(convert(key));\n}\n#endif\n\nint QMessageStore::countAccounts(const QMessageAccountFilterKey& key) const\n{\n if (key.options() != 0) {\n d_ptr->_error = QMessageStore::NotYetImplemented;\n return 0;\n }\n \n d_ptr->_error = QMessageStore::NoError;\n return d_ptr->_store->countAccounts(convert(key));\n}\n\nbool QMessageStore::removeMessage(const QMessageId& id, QMessageStore::RemovalOption option)\n{\n d_ptr->_error = QMessageStore::NoError;\n return d_ptr->_store->removeMessage(convert(id), convert(option));\n}\n\nbool QMessageStore::removeMessages(const QMessageFilterKey& key, QMessageStore::RemovalOption option)\n{\n d_ptr->_error = QMessageStore::NoError;\n return d_ptr->_store->removeMessages(convert(key), convert(option));\n}\n\nbool QMessageStore::addMessage(QMessage *m)\n{\n QMailMessage msg(convert(*m));\n\n d_ptr->_error = QMessageStore::NoError;\n return d_ptr->_store->addMessage(&msg);\n}\n\nbool QMessageStore::updateMessage(QMessage *m)\n{\n QMailMessage msg(convert(*m));\n\n d_ptr->_error = QMessageStore::NoError;\n return d_ptr->_store->updateMessage(&msg);\n}\n\nQMessage QMessageStore::message(const QMessageId& id) const\n{\n d_ptr->_error = QMessageStore::NoError;\n return convert(d_ptr->_store->message(convert(id)));\n}\n\n#ifdef QMESSAGING_OPTIONAL_FOLDER\nQMessageFolder QMessageStore::folder(const QMessageFolderId& id) const\n{\n d_ptr->_error = QMessageStore::NoError;\n return convert(d_ptr->_store->folder(convert(id)));\n}\n#endif\n\nQMessageAccount QMessageStore::account(const QMessageAccountId& id) const\n{\n d_ptr->_error = QMessageStore::NoError;\n return convert(d_ptr->_store->account(convert(id)));\n}\n\nQMessageStore* QMessageStore::instance()\n{\n static bool initialised(false);\n\n QMessageStore* store(QMessageStorePrivate::storeInstance());\n\n if (!initialised) {\n initialised = true;\n\n QMailStore *mailStore(convert(store));\n\n \/\/ Perform any initialisation tasks\n QMessageStorePrivate::registerMessageStatus(mailStore, \"QMessage::HighPriority\");\n QMessageStorePrivate::registerMessageStatus(mailStore, \"QMessage::LowPriority\");\n\n \/\/ Create the standard folders if they do not exist\n typedef QPair<const char*, quint64> FolderAttributes;\n foreach (const FolderAttributes &folder, QList<FolderAttributes>() << FolderAttributes(\"Inbox\", QMailFolder::Incoming)\n << FolderAttributes(\"Outbox\", QMailFolder::Outgoing)\n << FolderAttributes(\"Drafts\", QMailFolder::Outgoing | QMailFolder::Trash)\n << FolderAttributes(\"Sent\", QMailFolder::Outgoing | QMailFolder::Sent)\n << FolderAttributes(\"Trash\", QMailFolder::Trash)) {\n QMessageStorePrivate::createNonexistentFolder(mailStore, folder.first, folder.second);\n }\n }\n\n return store;\n}\n \nvoid QMessageStore::startNotifications(const QMessageFilterKey &key)\n{\n if (key.options() != 0) {\n d_ptr->_error = QMessageStore::NotYetImplemented;\n return;\n }\n \n \/\/ TODO: implement notifications\n Q_UNUSED(key) \n}\n\nvoid QMessageStore::stopNotifications()\n{\n \/\/ TODO: implement notifications\n}\n\n<|endoftext|>"} {"text":"<commit_before>#include \"VulkanTexture.hpp\"\n\nVulkanTexture::VulkanTexture(const char* data, unsigned int length) {\n \n}\n\nVulkanTexture::~VulkanTexture() {\n \n}\n<commit_msg>Load texture from memory<commit_after>#include \"VulkanTexture.hpp\"\n\n#define STB_IMAGE_IMPLEMENTATION\n#include <stb_image.h>\n#include <iostream>\n\nVulkanTexture::VulkanTexture(const char* data, unsigned int length) {\n \/\/ Load texture from memory.\n int width, height, channels;\n stbi_uc* pixels = stbi_load_from_memory(reinterpret_cast<const unsigned char*>(data), length, &width, &height, &channels, 0);\n if (pixels == nullptr) {\n std::cerr << \"Failed to load image from memory.\" << std::endl;\n exit(-1);\n }\n \n \/\/ Clean up.\n stbi_image_free(pixels);\n}\n\nVulkanTexture::~VulkanTexture() {\n \n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Module: Log4CPLUS\n\/\/ File: socket-win32.cxx\n\/\/ Created: 4\/2003\n\/\/ Author: Tad E. Smith\n\/\/\n\/\/\n\/\/ Copyright 2003-2010 Tad E. Smith\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include <log4cplus\/config.hxx>\n#if defined (LOG4CPLUS_USE_WINSOCK)\n\n#include <cassert>\n#include <cerrno>\n#include <vector>\n#include <cstring>\n#include <log4cplus\/internal\/socket.h>\n#include <log4cplus\/helpers\/loglog.h>\n#include <log4cplus\/thread\/threads.h>\n#include <log4cplus\/helpers\/stringhelper.h>\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ file LOCAL Classes\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nnamespace\n{\n\nenum WSInitStates\n{\n WS_UNINITIALIZED,\n WS_INITIALIZING,\n WS_INITIALIZED\n};\n\n\nstatic WSADATA wsa;\nstatic LONG volatile winsock_state = WS_UNINITIALIZED;\n\n\nstatic\nvoid\ninit_winsock_worker ()\n{\n log4cplus::helpers::LogLog * loglog\n = log4cplus::helpers::LogLog::getLogLog ();\n\n \/\/ Try to change the state to WS_INITIALIZING.\n LONG val = ::InterlockedCompareExchange (\n const_cast<LPLONG>(&winsock_state), WS_INITIALIZING, WS_UNINITIALIZED);\n switch (val)\n {\n case WS_UNINITIALIZED:\n {\n int ret = WSAStartup (MAKEWORD (2, 2), &wsa);\n if (ret != 0)\n {\n \/\/ Revert the state back to WS_UNINITIALIZED to unblock other\n \/\/ threads and let them throw exception.\n val = ::InterlockedCompareExchange (\n const_cast<LPLONG>(&winsock_state), WS_UNINITIALIZED,\n WS_INITIALIZING);\n assert (val == WS_INITIALIZING);\n loglog->error (LOG4CPLUS_TEXT (\"Could not initialize WinSock.\"),\n true);\n }\n\n \/\/ WinSock is initialized, change the state to WS_INITIALIZED.\n val = ::InterlockedCompareExchange (\n const_cast<LPLONG>(&winsock_state), WS_INITIALIZED,\n WS_INITIALIZING);\n assert (val == WS_INITIALIZING);\n return;\n }\n\n case WS_INITIALIZING:\n \/\/ Wait for state change.\n while (true)\n {\n switch (winsock_state)\n {\n case WS_INITIALIZED:\n return;\n\n case WS_INITIALIZING:\n log4cplus::thread::yield ();\n continue;\n \n default:\n assert (0);\n loglog->error (LOG4CPLUS_TEXT (\"Unknown WinSock state.\"), true);\n }\n }\n\n case WS_INITIALIZED:\n \/\/ WinSock is already initialized.\n return;\n\n default:\n assert (0);\n loglog->error (LOG4CPLUS_TEXT (\"Unknown WinSock state.\"), true);\n }\n}\n\n\nstatic\nvoid\ninit_winsock ()\n{\n \/\/ Quick check first to avoid the expensive interlocked compare\n \/\/ and exchange.\n if (winsock_state == WS_INITIALIZED)\n return;\n else\n init_winsock_worker ();\n}\n\n\nstruct WinSockInitializer\n{\n ~WinSockInitializer ()\n {\n if (winsock_state == WS_INITIALIZED)\n WSACleanup ();\n }\n\n static WinSockInitializer winSockInitializer;\n};\n\n\nWinSockInitializer WinSockInitializer::winSockInitializer;\n\n\n} \/\/ namespace\n\n\nnamespace log4cplus { namespace helpers {\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Global Methods\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nSOCKET_TYPE\nopenSocket(unsigned short port, SocketState& state)\n{\n struct sockaddr_in server;\n\n init_winsock ();\n\n SOCKET sock = WSASocket (AF_INET, SOCK_STREAM, AF_UNSPEC, 0, 0\n#if defined (WSA_FLAG_NO_HANDLE_INHERIT)\n , WSA_FLAG_NO_HANDLE_INHERIT\n#else\n , 0\n#endif\n );\n\n if (sock == INVALID_OS_SOCKET_VALUE)\n goto error;\n\n server.sin_family = AF_INET;\n server.sin_addr.s_addr = htonl(INADDR_ANY);\n server.sin_port = htons(port);\n\n if (bind(sock, reinterpret_cast<struct sockaddr*>(&server), sizeof(server))\n != 0)\n goto error;\n\n if (::listen(sock, 10) != 0)\n goto error;\n\n state = ok;\n return to_log4cplus_socket (sock);\n\nerror:\n int eno = WSAGetLastError ();\n\n if (sock != INVALID_OS_SOCKET_VALUE)\n ::closesocket (sock);\n\n set_last_socket_error (eno);\n return INVALID_SOCKET_VALUE;\n}\n\n\nSOCKET_TYPE\nconnectSocket(const tstring& hostn, unsigned short port, bool udp, SocketState& state)\n{\n struct hostent * hp;\n struct sockaddr_in insock;\n int retval;\n\n init_winsock ();\n\n SOCKET sock = WSASocket (AF_INET, (udp ? SOCK_DGRAM : SOCK_STREAM),\n AF_UNSPEC, 0, 0\n#if defined (WSA_FLAG_NO_HANDLE_INHERIT)\n , WSA_FLAG_NO_HANDLE_INHERIT\n#else\n , 0\n#endif\n );\n if (sock == INVALID_OS_SOCKET_VALUE)\n goto error;\n\n hp = ::gethostbyname( LOG4CPLUS_TSTRING_TO_STRING(hostn).c_str() );\n if (hp == 0 || hp->h_addrtype != AF_INET)\n {\n insock.sin_family = AF_INET;\n INT insock_size = sizeof (insock);\n INT ret = WSAStringToAddress (const_cast<LPTSTR>(hostn.c_str ()),\n AF_INET, 0, reinterpret_cast<struct sockaddr *>(&insock),\n &insock_size);\n if (ret == SOCKET_ERROR || insock_size != sizeof (insock)) \n {\n state = bad_address;\n goto error;\n }\n }\n else\n std::memcpy (&insock.sin_addr, hp->h_addr_list[0],\n sizeof (insock.sin_addr));\n\n insock.sin_port = htons(port);\n insock.sin_family = AF_INET;\n\n while( (retval = ::connect(sock, (struct sockaddr*)&insock, sizeof(insock))) == -1\n && (WSAGetLastError() == WSAEINTR))\n ;\n if (retval == SOCKET_ERROR)\n goto error;\n\n state = ok;\n return to_log4cplus_socket (sock);\n\nerror:\n int eno = WSAGetLastError ();\n\n if (sock != INVALID_OS_SOCKET_VALUE)\n ::closesocket (sock);\n\n set_last_socket_error (eno);\n return INVALID_SOCKET_VALUE;\n}\n\n\nSOCKET_TYPE\nacceptSocket(SOCKET_TYPE sock, SocketState & state)\n{\n init_winsock ();\n\n SOCKET osSocket = to_os_socket (sock);\n\n \/\/ Prepare event objects.\n \n WSAEVENT close_ev = WSACreateEvent ();\n if (close_ev == WSA_INVALID_EVENT)\n goto error;\n\n WSAEVENT accept_ev = WSACreateEvent ();\n if (accept_ev == WSA_INVALID_EVENT)\n goto error;\n\n \/\/ Prime the socket to report FD_CLOSE.\n\n int ret = WSAEventSelect (osSocket, close_ev, FD_CLOSE);\n if (ret != SOCKET_ERROR)\n goto error;\n\n \/\/ Prime the socket to report FD_ACCEPT.\n\n ret = WSAEventSelect (osSocket, accept_ev, FD_ACCEPT);\n if (ret != SOCKET_ERROR)\n goto error;\n\n WSAEVENT events[2] = { close_ev, accept_ev };\n\n while (1)\n {\n DWORD wfme = WSAWaitForMultipleEvents (2, events, FALSE, WSA_INFINITE,\n TRUE);\n switch (wfme)\n {\n case WSA_WAIT_TIMEOUT:\n \/\/ This should not happen for WSA_INFINITE timeout.\n \/\/ Fall through.\n\n case WSA_WAIT_IO_COMPLETION:\n continue;\n\n case WSA_WAIT_EVENT_0:\n WSASetLastError (ERROR_NO_DATA);\n goto error;\n\n case WSA_WAIT_EVENT_0 + 1:\n {\n WSACloseEvent (close_ev);\n WSACloseEvent (accept_ev);\n\n SOCKET connected_socket = ::accept (osSocket, NULL, NULL);\n\n if (connected_socket != INVALID_OS_SOCKET_VALUE)\n state = ok;\n\n return to_log4cplus_socket (connected_socket);\n }\n\n default:\n helpers::getLogLog ().error (\n LOG4CPLUS_TEXT (\"unexpected WSAWaitForMultipleEvents return value: \")\n + helpers::convertIntegerToString (wfme));\n\n goto error;\n }\n }\n\nerror:\n DWORD const eno = WSAGetLastError ();\n\n if (close_ev != WSA_INVALID_EVENT)\n WSACloseEvent (close_ev);\n\n if (accept_ev != WSA_INVALID_EVENT)\n WSACloseEvent (accept_ev);\n\n set_last_socket_error (eno);\n\n return to_log4cplus_socket (INVALID_SOCKET);\n}\n\n\n\nint\ncloseSocket(SOCKET_TYPE sock)\n{\n return ::closesocket (to_os_socket (sock));\n}\n\n\n\nlong\nread(SOCKET_TYPE sock, SocketBuffer& buffer)\n{\n long res, read = 0;\n \n do\n { \n res = ::recv(to_os_socket (sock), \n buffer.getBuffer() + read, \n static_cast<int>(buffer.getMaxSize() - read),\n 0);\n if (res == SOCKET_ERROR)\n {\n set_last_socket_error (WSAGetLastError ());\n return res;\n }\n read += res;\n }\n while (read < static_cast<long>(buffer.getMaxSize()));\n \n return read;\n}\n\n\n\nlong\nwrite(SOCKET_TYPE sock, const SocketBuffer& buffer)\n{\n long ret = ::send (to_os_socket (sock), buffer.getBuffer(),\n static_cast<int>(buffer.getSize()), 0);\n if (ret == SOCKET_ERROR)\n set_last_socket_error (WSAGetLastError ());\n return ret;\n}\n\n\nlong\nwrite(SOCKET_TYPE sock, const std::string & buffer)\n{\n long ret = ::send (to_os_socket (sock), buffer.c_str (),\n static_cast<int>(buffer.size ()), 0);\n if (ret == SOCKET_ERROR)\n set_last_socket_error (WSAGetLastError ());\n return ret;\n}\n\n\ntstring\ngetHostname (bool fqdn)\n{\n char const * hostname = \"unknown\";\n int ret;\n std::vector<char> hn (1024, 0);\n\n while (true)\n {\n ret = ::gethostname (&hn[0], static_cast<int>(hn.size ()) - 1);\n if (ret == 0)\n {\n hostname = &hn[0];\n break;\n }\n else if (ret != 0 && WSAGetLastError () == WSAEFAULT)\n \/\/ Out buffer was too short. Retry with buffer twice the size.\n hn.resize (hn.size () * 2, 0);\n else\n break;\n }\n\n if (ret != 0 || (ret == 0 && ! fqdn))\n return LOG4CPLUS_STRING_TO_TSTRING (hostname);\n\n struct ::hostent * hp = ::gethostbyname (hostname);\n if (hp)\n hostname = hp->h_name;\n\n return LOG4CPLUS_STRING_TO_TSTRING (hostname);\n}\n\n\nint\nsetTCPNoDelay (SOCKET_TYPE sock, bool val)\n{\n int result;\n int enabled = static_cast<int>(val);\n if ((result = setsockopt(sock, IPPROTO_TCP, TCP_NODELAY,\n reinterpret_cast<char*>(&enabled),sizeof(enabled))) != 0)\n {\n int eno = WSAGetLastError ();\n set_last_socket_error (eno);\n }\n\n return result;\n}\n\n\n} } \/\/ namespace log4cplus { namespace helpers {\n\n#endif \/\/ LOG4CPLUS_USE_WINSOCK\n<commit_msg>socket-win32.cxx: Fix reversed conditional logic.<commit_after>\/\/ Module: Log4CPLUS\n\/\/ File: socket-win32.cxx\n\/\/ Created: 4\/2003\n\/\/ Author: Tad E. Smith\n\/\/\n\/\/\n\/\/ Copyright 2003-2010 Tad E. Smith\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include <log4cplus\/config.hxx>\n#if defined (LOG4CPLUS_USE_WINSOCK)\n\n#include <cassert>\n#include <cerrno>\n#include <vector>\n#include <cstring>\n#include <log4cplus\/internal\/socket.h>\n#include <log4cplus\/helpers\/loglog.h>\n#include <log4cplus\/thread\/threads.h>\n#include <log4cplus\/helpers\/stringhelper.h>\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ file LOCAL Classes\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nnamespace\n{\n\nenum WSInitStates\n{\n WS_UNINITIALIZED,\n WS_INITIALIZING,\n WS_INITIALIZED\n};\n\n\nstatic WSADATA wsa;\nstatic LONG volatile winsock_state = WS_UNINITIALIZED;\n\n\nstatic\nvoid\ninit_winsock_worker ()\n{\n log4cplus::helpers::LogLog * loglog\n = log4cplus::helpers::LogLog::getLogLog ();\n\n \/\/ Try to change the state to WS_INITIALIZING.\n LONG val = ::InterlockedCompareExchange (\n const_cast<LPLONG>(&winsock_state), WS_INITIALIZING, WS_UNINITIALIZED);\n switch (val)\n {\n case WS_UNINITIALIZED:\n {\n int ret = WSAStartup (MAKEWORD (2, 2), &wsa);\n if (ret != 0)\n {\n \/\/ Revert the state back to WS_UNINITIALIZED to unblock other\n \/\/ threads and let them throw exception.\n val = ::InterlockedCompareExchange (\n const_cast<LPLONG>(&winsock_state), WS_UNINITIALIZED,\n WS_INITIALIZING);\n assert (val == WS_INITIALIZING);\n loglog->error (LOG4CPLUS_TEXT (\"Could not initialize WinSock.\"),\n true);\n }\n\n \/\/ WinSock is initialized, change the state to WS_INITIALIZED.\n val = ::InterlockedCompareExchange (\n const_cast<LPLONG>(&winsock_state), WS_INITIALIZED,\n WS_INITIALIZING);\n assert (val == WS_INITIALIZING);\n return;\n }\n\n case WS_INITIALIZING:\n \/\/ Wait for state change.\n while (true)\n {\n switch (winsock_state)\n {\n case WS_INITIALIZED:\n return;\n\n case WS_INITIALIZING:\n log4cplus::thread::yield ();\n continue;\n \n default:\n assert (0);\n loglog->error (LOG4CPLUS_TEXT (\"Unknown WinSock state.\"), true);\n }\n }\n\n case WS_INITIALIZED:\n \/\/ WinSock is already initialized.\n return;\n\n default:\n assert (0);\n loglog->error (LOG4CPLUS_TEXT (\"Unknown WinSock state.\"), true);\n }\n}\n\n\nstatic\nvoid\ninit_winsock ()\n{\n \/\/ Quick check first to avoid the expensive interlocked compare\n \/\/ and exchange.\n if (winsock_state == WS_INITIALIZED)\n return;\n else\n init_winsock_worker ();\n}\n\n\nstruct WinSockInitializer\n{\n ~WinSockInitializer ()\n {\n if (winsock_state == WS_INITIALIZED)\n WSACleanup ();\n }\n\n static WinSockInitializer winSockInitializer;\n};\n\n\nWinSockInitializer WinSockInitializer::winSockInitializer;\n\n\n} \/\/ namespace\n\n\nnamespace log4cplus { namespace helpers {\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Global Methods\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nSOCKET_TYPE\nopenSocket(unsigned short port, SocketState& state)\n{\n struct sockaddr_in server;\n\n init_winsock ();\n\n SOCKET sock = WSASocket (AF_INET, SOCK_STREAM, AF_UNSPEC, 0, 0\n#if defined (WSA_FLAG_NO_HANDLE_INHERIT)\n , WSA_FLAG_NO_HANDLE_INHERIT\n#else\n , 0\n#endif\n );\n\n if (sock == INVALID_OS_SOCKET_VALUE)\n goto error;\n\n server.sin_family = AF_INET;\n server.sin_addr.s_addr = htonl(INADDR_ANY);\n server.sin_port = htons(port);\n\n if (bind(sock, reinterpret_cast<struct sockaddr*>(&server), sizeof(server))\n != 0)\n goto error;\n\n if (::listen(sock, 10) != 0)\n goto error;\n\n state = ok;\n return to_log4cplus_socket (sock);\n\nerror:\n int eno = WSAGetLastError ();\n\n if (sock != INVALID_OS_SOCKET_VALUE)\n ::closesocket (sock);\n\n set_last_socket_error (eno);\n return INVALID_SOCKET_VALUE;\n}\n\n\nSOCKET_TYPE\nconnectSocket(const tstring& hostn, unsigned short port, bool udp, SocketState& state)\n{\n struct hostent * hp;\n struct sockaddr_in insock;\n int retval;\n\n init_winsock ();\n\n SOCKET sock = WSASocket (AF_INET, (udp ? SOCK_DGRAM : SOCK_STREAM),\n AF_UNSPEC, 0, 0\n#if defined (WSA_FLAG_NO_HANDLE_INHERIT)\n , WSA_FLAG_NO_HANDLE_INHERIT\n#else\n , 0\n#endif\n );\n if (sock == INVALID_OS_SOCKET_VALUE)\n goto error;\n\n hp = ::gethostbyname( LOG4CPLUS_TSTRING_TO_STRING(hostn).c_str() );\n if (hp == 0 || hp->h_addrtype != AF_INET)\n {\n insock.sin_family = AF_INET;\n INT insock_size = sizeof (insock);\n INT ret = WSAStringToAddress (const_cast<LPTSTR>(hostn.c_str ()),\n AF_INET, 0, reinterpret_cast<struct sockaddr *>(&insock),\n &insock_size);\n if (ret == SOCKET_ERROR || insock_size != sizeof (insock)) \n {\n state = bad_address;\n goto error;\n }\n }\n else\n std::memcpy (&insock.sin_addr, hp->h_addr_list[0],\n sizeof (insock.sin_addr));\n\n insock.sin_port = htons(port);\n insock.sin_family = AF_INET;\n\n while( (retval = ::connect(sock, (struct sockaddr*)&insock, sizeof(insock))) == -1\n && (WSAGetLastError() == WSAEINTR))\n ;\n if (retval == SOCKET_ERROR)\n goto error;\n\n state = ok;\n return to_log4cplus_socket (sock);\n\nerror:\n int eno = WSAGetLastError ();\n\n if (sock != INVALID_OS_SOCKET_VALUE)\n ::closesocket (sock);\n\n set_last_socket_error (eno);\n return INVALID_SOCKET_VALUE;\n}\n\n\nSOCKET_TYPE\nacceptSocket(SOCKET_TYPE sock, SocketState & state)\n{\n init_winsock ();\n\n SOCKET osSocket = to_os_socket (sock);\n\n \/\/ Prepare event objects.\n \n WSAEVENT close_ev = WSACreateEvent ();\n if (close_ev == WSA_INVALID_EVENT)\n goto error;\n\n WSAEVENT accept_ev = WSACreateEvent ();\n if (accept_ev == WSA_INVALID_EVENT)\n goto error;\n\n \/\/ Prime the socket to report FD_CLOSE.\n\n int ret = WSAEventSelect (osSocket, close_ev, FD_CLOSE);\n if (ret == SOCKET_ERROR)\n goto error;\n\n \/\/ Prime the socket to report FD_ACCEPT.\n\n ret = WSAEventSelect (osSocket, accept_ev, FD_ACCEPT);\n if (ret == SOCKET_ERROR)\n goto error;\n\n WSAEVENT events[2] = { close_ev, accept_ev };\n\n while (1)\n {\n DWORD wfme = WSAWaitForMultipleEvents (2, events, FALSE, WSA_INFINITE,\n TRUE);\n switch (wfme)\n {\n case WSA_WAIT_TIMEOUT:\n \/\/ This should not happen for WSA_INFINITE timeout.\n \/\/ Fall through.\n\n case WSA_WAIT_IO_COMPLETION:\n continue;\n\n case WSA_WAIT_EVENT_0:\n WSASetLastError (ERROR_NO_DATA);\n goto error;\n\n case WSA_WAIT_EVENT_0 + 1:\n {\n WSACloseEvent (close_ev);\n WSACloseEvent (accept_ev);\n\n SOCKET connected_socket = ::accept (osSocket, NULL, NULL);\n\n if (connected_socket != INVALID_OS_SOCKET_VALUE)\n state = ok;\n\n return to_log4cplus_socket (connected_socket);\n }\n\n default:\n helpers::getLogLog ().error (\n LOG4CPLUS_TEXT (\"unexpected WSAWaitForMultipleEvents return value: \")\n + helpers::convertIntegerToString (wfme));\n\n goto error;\n }\n }\n\nerror:\n DWORD const eno = WSAGetLastError ();\n\n if (close_ev != WSA_INVALID_EVENT)\n WSACloseEvent (close_ev);\n\n if (accept_ev != WSA_INVALID_EVENT)\n WSACloseEvent (accept_ev);\n\n set_last_socket_error (eno);\n\n return to_log4cplus_socket (INVALID_SOCKET);\n}\n\n\n\nint\ncloseSocket(SOCKET_TYPE sock)\n{\n return ::closesocket (to_os_socket (sock));\n}\n\n\n\nlong\nread(SOCKET_TYPE sock, SocketBuffer& buffer)\n{\n long res, read = 0;\n \n do\n { \n res = ::recv(to_os_socket (sock), \n buffer.getBuffer() + read, \n static_cast<int>(buffer.getMaxSize() - read),\n 0);\n if (res == SOCKET_ERROR)\n {\n set_last_socket_error (WSAGetLastError ());\n return res;\n }\n read += res;\n }\n while (read < static_cast<long>(buffer.getMaxSize()));\n \n return read;\n}\n\n\n\nlong\nwrite(SOCKET_TYPE sock, const SocketBuffer& buffer)\n{\n long ret = ::send (to_os_socket (sock), buffer.getBuffer(),\n static_cast<int>(buffer.getSize()), 0);\n if (ret == SOCKET_ERROR)\n set_last_socket_error (WSAGetLastError ());\n return ret;\n}\n\n\nlong\nwrite(SOCKET_TYPE sock, const std::string & buffer)\n{\n long ret = ::send (to_os_socket (sock), buffer.c_str (),\n static_cast<int>(buffer.size ()), 0);\n if (ret == SOCKET_ERROR)\n set_last_socket_error (WSAGetLastError ());\n return ret;\n}\n\n\ntstring\ngetHostname (bool fqdn)\n{\n char const * hostname = \"unknown\";\n int ret;\n std::vector<char> hn (1024, 0);\n\n while (true)\n {\n ret = ::gethostname (&hn[0], static_cast<int>(hn.size ()) - 1);\n if (ret == 0)\n {\n hostname = &hn[0];\n break;\n }\n else if (ret != 0 && WSAGetLastError () == WSAEFAULT)\n \/\/ Out buffer was too short. Retry with buffer twice the size.\n hn.resize (hn.size () * 2, 0);\n else\n break;\n }\n\n if (ret != 0 || (ret == 0 && ! fqdn))\n return LOG4CPLUS_STRING_TO_TSTRING (hostname);\n\n struct ::hostent * hp = ::gethostbyname (hostname);\n if (hp)\n hostname = hp->h_name;\n\n return LOG4CPLUS_STRING_TO_TSTRING (hostname);\n}\n\n\nint\nsetTCPNoDelay (SOCKET_TYPE sock, bool val)\n{\n int result;\n int enabled = static_cast<int>(val);\n if ((result = setsockopt(sock, IPPROTO_TCP, TCP_NODELAY,\n reinterpret_cast<char*>(&enabled),sizeof(enabled))) != 0)\n {\n int eno = WSAGetLastError ();\n set_last_socket_error (eno);\n }\n\n return result;\n}\n\n\n} } \/\/ namespace log4cplus { namespace helpers {\n\n#endif \/\/ LOG4CPLUS_USE_WINSOCK\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright 2011, Blender Foundation.\n *\n * This program is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU General Public License\n * as published by the Free Software Foundation; either version 2\n * of the License, or (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software Foundation,\n * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n *\/\n\n#include \"device.h\"\n#include \"particles.h\"\n#include \"scene.h\"\n\n#include \"util_foreach.h\"\n#include \"util_map.h\"\n#include \"util_progress.h\"\n#include \"util_vector.h\"\n\nCCL_NAMESPACE_BEGIN\n\n\/* Particle System *\/\n\nParticleSystem::ParticleSystem()\n{\n}\n\nParticleSystem::~ParticleSystem()\n{\n}\n\nvoid ParticleSystem::tag_update(Scene *scene)\n{\n\tscene->particle_system_manager->need_update = true;\n}\n\n\/* Particle System Manager *\/\n\nParticleSystemManager::ParticleSystemManager()\n{\n\tneed_update = true;\n}\n\nParticleSystemManager::~ParticleSystemManager()\n{\n}\n\nvoid ParticleSystemManager::device_update_particles(Device *device, DeviceScene *dscene, Scene *scene, Progress& progress)\n{\n\t\/* count particles.\n\t * adds one dummy particle at the beginning to avoid invalid lookups,\n\t * in case a shader uses particle info without actual particle data.\n\t *\/\n\tint num_particles = 1;\n\tforeach(ParticleSystem *psys, scene->particle_systems)\n\t\tnum_particles += psys->particles.size();\n\t\n\tfloat4 *particles = dscene->particles.resize(PARTICLE_SIZE*num_particles);\n\t\n\t\/* dummy particle *\/\n\tparticles[0] = make_float4(0.0f, 0.0f, 0.0f, 0.0f);\n\t\n\tint i = 1;\n\tforeach(ParticleSystem *psys, scene->particle_systems) {\n\t\tforeach(Particle &pa, psys->particles) {\n\t\t\t\/* pack in texture *\/\n\t\t\tint offset = i*PARTICLE_SIZE;\n\t\t\t\n\t\t\tparticles[offset] = make_float4(pa.index, pa.age, pa.lifetime, pa.size);\n\t\t\tparticles[offset+1] = pa.rotation;\n\t\t\tparticles[offset+2] = make_float4(pa.location.x, pa.location.y, pa.location.z, pa.velocity.x);\n\t\t\tparticles[offset+3] = make_float4(pa.velocity.y, pa.velocity.z, pa.angular_velocity.x, pa.angular_velocity.y);\n\t\t\tparticles[offset+4] = make_float4(pa.angular_velocity.z, 0.0f, 0.0f, 0.0f);\n\t\t\t\n\t\t\ti++;\n\t\t\t\n\t\t\tif(progress.get_cancel()) return;\n\t\t}\n\t}\n\t\n\tdevice->tex_alloc(\"__particles\", dscene->particles);\n}\n\nvoid ParticleSystemManager::device_update(Device *device, DeviceScene *dscene, Scene *scene, Progress& progress)\n{\n\tif(!need_update)\n\t\treturn;\n\t\n\tdevice_free(device, dscene);\n\n\tif(scene->particle_systems.size() == 0)\n\t\treturn;\n\n\tprogress.set_status(\"Updating Particle Systems\", \"Copying Particles to device\");\n\tdevice_update_particles(device, dscene, scene, progress);\n\t\n\tif(progress.get_cancel()) return;\n\t\n\tneed_update = false;\n}\n\nvoid ParticleSystemManager::device_free(Device *device, DeviceScene *dscene)\n{\n\tdevice->tex_free(dscene->particles);\n\tdscene->particles.clear();\n}\n\nvoid ParticleSystemManager::tag_update(Scene *scene)\n{\n\tneed_update = true;\n}\n\nCCL_NAMESPACE_END\n\n<commit_msg>Cycles: Fully initialize the dummy particle at index 0.<commit_after>\/*\n * Copyright 2011, Blender Foundation.\n *\n * This program is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU General Public License\n * as published by the Free Software Foundation; either version 2\n * of the License, or (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software Foundation,\n * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n *\/\n\n#include \"device.h\"\n#include \"particles.h\"\n#include \"scene.h\"\n\n#include \"util_foreach.h\"\n#include \"util_map.h\"\n#include \"util_progress.h\"\n#include \"util_vector.h\"\n\nCCL_NAMESPACE_BEGIN\n\n\/* Particle System *\/\n\nParticleSystem::ParticleSystem()\n{\n}\n\nParticleSystem::~ParticleSystem()\n{\n}\n\nvoid ParticleSystem::tag_update(Scene *scene)\n{\n\tscene->particle_system_manager->need_update = true;\n}\n\n\/* Particle System Manager *\/\n\nParticleSystemManager::ParticleSystemManager()\n{\n\tneed_update = true;\n}\n\nParticleSystemManager::~ParticleSystemManager()\n{\n}\n\nvoid ParticleSystemManager::device_update_particles(Device *device, DeviceScene *dscene, Scene *scene, Progress& progress)\n{\n\t\/* count particles.\n\t * adds one dummy particle at the beginning to avoid invalid lookups,\n\t * in case a shader uses particle info without actual particle data.\n\t *\/\n\tint num_particles = 1;\n\tforeach(ParticleSystem *psys, scene->particle_systems)\n\t\tnum_particles += psys->particles.size();\n\t\n\tfloat4 *particles = dscene->particles.resize(PARTICLE_SIZE*num_particles);\n\t\n\t\/* dummy particle *\/\n\tparticles[0] = make_float4(0.0f, 0.0f, 0.0f, 0.0f);\n\tparticles[1] = make_float4(0.0f, 0.0f, 0.0f, 0.0f);\n\tparticles[2] = make_float4(0.0f, 0.0f, 0.0f, 0.0f);\n\tparticles[3] = make_float4(0.0f, 0.0f, 0.0f, 0.0f);\n\tparticles[4] = make_float4(0.0f, 0.0f, 0.0f, 0.0f);\n\t\n\tint i = 1;\n\tforeach(ParticleSystem *psys, scene->particle_systems) {\n\t\tforeach(Particle &pa, psys->particles) {\n\t\t\t\/* pack in texture *\/\n\t\t\tint offset = i*PARTICLE_SIZE;\n\t\t\t\n\t\t\tparticles[offset] = make_float4(pa.index, pa.age, pa.lifetime, pa.size);\n\t\t\tparticles[offset+1] = pa.rotation;\n\t\t\tparticles[offset+2] = make_float4(pa.location.x, pa.location.y, pa.location.z, pa.velocity.x);\n\t\t\tparticles[offset+3] = make_float4(pa.velocity.y, pa.velocity.z, pa.angular_velocity.x, pa.angular_velocity.y);\n\t\t\tparticles[offset+4] = make_float4(pa.angular_velocity.z, 0.0f, 0.0f, 0.0f);\n\t\t\t\n\t\t\ti++;\n\t\t\t\n\t\t\tif(progress.get_cancel()) return;\n\t\t}\n\t}\n\t\n\tdevice->tex_alloc(\"__particles\", dscene->particles);\n}\n\nvoid ParticleSystemManager::device_update(Device *device, DeviceScene *dscene, Scene *scene, Progress& progress)\n{\n\tif(!need_update)\n\t\treturn;\n\t\n\tdevice_free(device, dscene);\n\n\tif(scene->particle_systems.size() == 0)\n\t\treturn;\n\n\tprogress.set_status(\"Updating Particle Systems\", \"Copying Particles to device\");\n\tdevice_update_particles(device, dscene, scene, progress);\n\t\n\tif(progress.get_cancel()) return;\n\t\n\tneed_update = false;\n}\n\nvoid ParticleSystemManager::device_free(Device *device, DeviceScene *dscene)\n{\n\tdevice->tex_free(dscene->particles);\n\tdscene->particles.clear();\n}\n\nvoid ParticleSystemManager::tag_update(Scene *scene)\n{\n\tneed_update = true;\n}\n\nCCL_NAMESPACE_END\n\n<|endoftext|>"} {"text":"<commit_before>\/* Begin CVS Header\n $Source: \/Volumes\/Home\/Users\/shoops\/cvs\/copasi_dev\/copasi\/optimization\/COptMethodSteepestDescent.cpp,v $\n $Revision: 1.13 $\n $Name: $\n $Author: shoops $ \n $Date: 2005\/10\/22 13:36:25 $\n End CVS Header *\/\n\n#include \"copasi.h\"\n\n#include \"COptMethod.h\"\n#include \"COptProblem.h\"\n#include \"COptItem.h\"\n#include \"COptTask.h\"\n\n#include \"FminBrent.h\"\n\n#include \"report\/CCopasiObjectReference.h\"\n\nCOptMethodSteepestDescent::COptMethodSteepestDescent(const CCopasiContainer * pParent):\n COptMethod(CCopasiTask::optimization, CCopasiMethod::SteepestDescent, pParent),\n mpDescent(new FDescentTemplate<COptMethodSteepestDescent>(this, &COptMethodSteepestDescent::descentLine))\n{\n addParameter(\"Iteration Limit\", CCopasiParameter::UINT, (unsigned C_INT32) 100);\n addParameter(\"Tolerance\", CCopasiParameter::DOUBLE, (C_FLOAT64) 1e-6);\n}\n\nCOptMethodSteepestDescent::COptMethodSteepestDescent(const COptMethodSteepestDescent & src,\n const CCopasiContainer * pParent): COptMethod(src, pParent),\n mpDescent(new FDescentTemplate<COptMethodSteepestDescent>(this, &COptMethodSteepestDescent::descentLine))\n{}\n\nCOptMethodSteepestDescent::~COptMethodSteepestDescent()\n{\n pdelete(mpDescent);\n\n cleanup();\n}\n\nbool COptMethodSteepestDescent::optimise()\n{\n if (!initialize()) return false;\n\n unsigned C_INT32 i, k;\n C_FLOAT64 tmp, x0, alpha, mn, mx, fmn, fmx;\n bool calc_grad;\n\n \/\/ initial point is first guess but we have to make sure that we\n \/\/ are within the parameter domain\n for (i = 0; i < mVariableSize; i++)\n {\n const COptItem & OptItem = *(*mpOptItem)[i];\n\n switch (OptItem.checkConstraint())\n {\n case - 1:\n mIndividual[i] = *OptItem.getLowerBoundValue();\n (*(*mpSetCalculateVariable)[i])(mIndividual[i]);\n break;\n\n case 1:\n mIndividual[i] = *OptItem.getUpperBoundValue();\n (*(*mpSetCalculateVariable)[i])(mIndividual[i]);\n break;\n\n case 0:\n mIndividual[i] = *OptItem.getObjectValue();\n break;\n }\n }\n\n fmx = mBestValue = evaluate();\n\n mpOptProblem->setSolutionVariables(mIndividual);\n mContinue = mpOptProblem->setSolutionValue(mBestValue);\n\n \/\/ We found a new best value lets report it.\n \/\/if (mpReport) mpReport->printBody();\n mpParentTask->doOutput();\n\n bool SolutionFound = false;\n\n for (mCurrentIteration = 0; mCurrentIteration < mIterations && mContinue && !SolutionFound; mCurrentIteration++)\n {\n \/\/ calculate the direction of steepest descent\n \/\/ by central finite differences\n gradient();\n \/\/ minimise the function in this direction\n \/\/ find brackets for the minimisation\n \/\/ mn = 0.0; md = 1.0;\n \/\/ mnbrak(&mn, &md, &mx, &fmn, &fmd, &fmx, descent_line);\n \/\/ make sure that no parameter will exceed its bounds\n x0 = DBL_MAX;\n\n for (i = 0; i < mVariableSize; i++)\n {\n if (fabs(mGradient[i]) > DBL_EPSILON)\n {\n if (mGradient[i] > 0)\n {\n tmp = *(*mpOptItem)[i]->getUpperBoundValue();\n }\n\n else\n {\n tmp = *(*mpOptItem)[i]->getLowerBoundValue();\n }\n\n \/\/ calculate the size of the largest jump\n tmp = (tmp - mIndividual[i]) \/ mGradient[i];\n \/\/ keep it if it is the smallest\n if (tmp < x0) x0 = tmp;\n }\n else mGradient[i] = 0.0;\n }\n\n if (x0 < mTolerance) x0 = mTolerance;\n\n \/\/ we will move at a rate of 1\/10 this size\n mn = mx = alpha = 0.0;\n\n for (k = 0, calc_grad = false; (k < 9) && !calc_grad && !SolutionFound; k++)\n {\n \/\/ set the minimum to the last successful step\n mn = mx;\n fmn = fmx;\n \/\/ increment alpha\n alpha += 0.1 * x0;\n \/\/ set the maximum to it\n mx = alpha;\n\n \/\/ take one step in that direction\n fmx = descentLine(alpha);\n\n fmx = evaluate();\n\n \/\/ if this was an upward step find the minimum\n if (fmx > fmn)\n {\n \/\/md = mn + (mx-mn)\/2;\n \/\/Brent(mn, md, mx, descent_line, &alpha, &tmp, 1e-6, 50);\n\n FminBrent(mn, mx, mpDescent, &alpha, &tmp, mTolerance, 5);\n\n \/\/ take one step in that direction\n fmx = descentLine(alpha);\n\n \/\/ time to evaluate the new steepest descent direction\n calc_grad = true;\n }\n\n if (fabs(fmx - mBestValue) < mTolerance)\n SolutionFound = true;\n }\n\n for (i = 0; i < mVariableSize; i++)\n mIndividual[i] = *(*mpOptItem)[i]->getObjectValue();\n\n if (fmx < mBestValue)\n {\n mBestValue = fmx;\n\n mpOptProblem->setSolutionVariables(mIndividual);\n mContinue = mpOptProblem->setSolutionValue(mBestValue);\n\n \/\/ We found a new best value lets report it.\n \/\/if (mpReport) mpReport->printBody();\n mpParentTask->doOutput();\n }\n }\n\n return SolutionFound;\n}\n\nbool COptMethodSteepestDescent::cleanup()\n{\n \/\/ pdelete all used variables\n return true;\n}\n\nbool COptMethodSteepestDescent::initialize()\n{\n cleanup();\n\n if (!COptMethod::initialize()) return false;\n\n mIterations = * getValue(\"Iteration Limit\").pUINT;\n mTolerance = * getValue(\"Tolerance\").pDOUBLE;\n\n mContinue = true;\n mVariableSize = mpOptItem->size();\n mIndividual.resize(mVariableSize);\n mGradient.resize(mVariableSize);\n\n mBestValue = DBL_MAX;\n\n return true;\n}\n\nvoid COptMethodSteepestDescent::gradient()\n{\n unsigned C_INT32 i;\n\n C_FLOAT64 y;\n C_FLOAT64 x;\n\n y = evaluate();\n\n for (i = 0; i < mVariableSize && mContinue; i++)\n {\n if ((x = *(*mpOptItem)[i]->getObjectValue()) != 0.0)\n {\n (*(*mpSetCalculateVariable)[i])(x * 1.001);\n mGradient[i] = (y - evaluate()) \/ (x * 0.001);\n }\n\n else\n {\n (*(*mpSetCalculateVariable)[i])(1e-7);\n mGradient[i] = (y - evaluate()) \/ 1e-7;\n }\n\n (*(*mpSetCalculateVariable)[i])(x);\n }\n}\n\nconst C_FLOAT64 COptMethodSteepestDescent::descentLine(const C_FLOAT64 & x)\n{\n for (unsigned C_INT32 i = 0; i < mVariableSize; i++)\n (*(*mpSetCalculateVariable)[i])(mIndividual[i] + x * mGradient[i]);\n\n return evaluate();\n}\n\n\/\/ evaluate the fitness of one individual\nconst C_FLOAT64 & COptMethodSteepestDescent::evaluate()\n{\n \/\/ evaluate the fitness\n mContinue = mpOptProblem->calculate();\n\n mValue = mpOptProblem->getCalculateValue();\n\n \/\/ when we leave the either the parameter or functional domain\n \/\/ we penalize the objective value by forcing it to be larger\n \/\/ than the best value recorded so far.\n if (mValue < mBestValue &&\n (!mpOptProblem->checkParametricConstraints() ||\n !mpOptProblem->checkFunctionalConstraints()))\n mValue = mBestValue + fabs(mBestValue - mValue);\n\n return mValue;\n}\n\nvoid COptMethodSteepestDescent::initObjects()\n{\n addObjectReference(\"Current Iteration\", mCurrentIteration, CCopasiObject::ValueInt);\n}\n<commit_msg>Fixed to work with fitting.<commit_after>\/* Begin CVS Header\n $Source: \/Volumes\/Home\/Users\/shoops\/cvs\/copasi_dev\/copasi\/optimization\/COptMethodSteepestDescent.cpp,v $\n $Revision: 1.14 $\n $Name: $\n $Author: shoops $ \n $Date: 2005\/11\/06 22:17:03 $\n End CVS Header *\/\n\n#include \"copasi.h\"\n\n#include \"COptMethod.h\"\n#include \"COptProblem.h\"\n#include \"COptItem.h\"\n#include \"COptTask.h\"\n\n#include \"FminBrent.h\"\n\n#include \"report\/CCopasiObjectReference.h\"\n\nCOptMethodSteepestDescent::COptMethodSteepestDescent(const CCopasiContainer * pParent):\n COptMethod(CCopasiTask::optimization, CCopasiMethod::SteepestDescent, pParent),\n mpDescent(new FDescentTemplate<COptMethodSteepestDescent>(this, &COptMethodSteepestDescent::descentLine))\n{\n addParameter(\"Iteration Limit\", CCopasiParameter::UINT, (unsigned C_INT32) 100);\n addParameter(\"Tolerance\", CCopasiParameter::DOUBLE, (C_FLOAT64) 1e-6);\n}\n\nCOptMethodSteepestDescent::COptMethodSteepestDescent(const COptMethodSteepestDescent & src,\n const CCopasiContainer * pParent): COptMethod(src, pParent),\n mpDescent(new FDescentTemplate<COptMethodSteepestDescent>(this, &COptMethodSteepestDescent::descentLine))\n{}\n\nCOptMethodSteepestDescent::~COptMethodSteepestDescent()\n{\n pdelete(mpDescent);\n\n cleanup();\n}\n\nbool COptMethodSteepestDescent::optimise()\n{\n if (!initialize()) return false;\n\n unsigned C_INT32 i, k;\n C_FLOAT64 tmp, x0, alpha, mn, mx, fmn, fmx;\n bool calc_grad;\n\n \/\/ initial point is first guess but we have to make sure that we\n \/\/ are within the parameter domain\n for (i = 0; i < mVariableSize; i++)\n {\n const COptItem & OptItem = *(*mpOptItem)[i];\n\n switch (OptItem.checkConstraint())\n {\n case - 1:\n mIndividual[i] = *OptItem.getLowerBoundValue();\n break;\n\n case 1:\n mIndividual[i] = *OptItem.getUpperBoundValue();\n break;\n\n case 0:\n mIndividual[i] = *OptItem.getObjectValue();\n break;\n }\n\n (*(*mpSetCalculateVariable)[i])(mIndividual[i]);\n }\n\n fmx = mBestValue = evaluate();\n\n mpOptProblem->setSolutionVariables(mIndividual);\n mContinue = mpOptProblem->setSolutionValue(mBestValue);\n\n \/\/ We found a new best value lets report it.\n \/\/if (mpReport) mpReport->printBody();\n mpParentTask->doOutput();\n\n bool SolutionFound = false;\n\n for (mCurrentIteration = 0; mCurrentIteration < mIterations && mContinue && !SolutionFound; mCurrentIteration++)\n {\n \/\/ calculate the direction of steepest descent\n \/\/ by central finite differences\n gradient();\n \/\/ minimise the function in this direction\n \/\/ find brackets for the minimisation\n \/\/ mn = 0.0; md = 1.0;\n \/\/ mnbrak(&mn, &md, &mx, &fmn, &fmd, &fmx, descent_line);\n \/\/ make sure that no parameter will exceed its bounds\n x0 = DBL_MAX;\n\n for (i = 0; i < mVariableSize; i++)\n {\n if (fabs(mGradient[i]) > DBL_EPSILON)\n {\n if (mGradient[i] > 0)\n {\n tmp = *(*mpOptItem)[i]->getUpperBoundValue();\n }\n\n else\n {\n tmp = *(*mpOptItem)[i]->getLowerBoundValue();\n }\n\n \/\/ calculate the size of the largest jump\n tmp = (tmp - mIndividual[i]) \/ mGradient[i];\n \/\/ keep it if it is the smallest\n if (tmp < x0) x0 = tmp;\n }\n else mGradient[i] = 0.0;\n }\n\n if (x0 < mTolerance) x0 = mTolerance;\n\n \/\/ we will move at a rate of 1\/10 this size\n mn = mx = alpha = 0.0;\n\n for (k = 0, calc_grad = false; (k < 9) && !calc_grad && !SolutionFound; k++)\n {\n \/\/ set the minimum to the last successful step\n mn = mx;\n fmn = fmx;\n \/\/ increment alpha\n alpha += 0.1 * x0;\n \/\/ set the maximum to it\n mx = alpha;\n\n \/\/ take one step in that direction\n fmx = descentLine(alpha);\n\n fmx = evaluate();\n\n \/\/ if this was an upward step find the minimum\n if (fmx > fmn)\n {\n \/\/md = mn + (mx-mn)\/2;\n \/\/Brent(mn, md, mx, descent_line, &alpha, &tmp, 1e-6, 50);\n\n FminBrent(mn, mx, mpDescent, &alpha, &tmp, mTolerance, 5);\n\n \/\/ take one step in that direction\n fmx = descentLine(alpha);\n\n \/\/ time to evaluate the new steepest descent direction\n calc_grad = true;\n }\n\n if (fabs(fmx - mBestValue) < mTolerance)\n SolutionFound = true;\n }\n\n for (i = 0; i < mVariableSize; i++)\n mIndividual[i] = *(*mpOptItem)[i]->getObjectValue();\n\n if (fmx < mBestValue)\n {\n mBestValue = fmx;\n\n mpOptProblem->setSolutionVariables(mIndividual);\n mContinue = mpOptProblem->setSolutionValue(mBestValue);\n\n \/\/ We found a new best value lets report it.\n \/\/if (mpReport) mpReport->printBody();\n mpParentTask->doOutput();\n }\n }\n\n return SolutionFound;\n}\n\nbool COptMethodSteepestDescent::cleanup()\n{\n \/\/ pdelete all used variables\n return true;\n}\n\nbool COptMethodSteepestDescent::initialize()\n{\n cleanup();\n\n if (!COptMethod::initialize()) return false;\n\n mIterations = * getValue(\"Iteration Limit\").pUINT;\n mTolerance = * getValue(\"Tolerance\").pDOUBLE;\n\n mContinue = true;\n mVariableSize = mpOptItem->size();\n mIndividual.resize(mVariableSize);\n mGradient.resize(mVariableSize);\n\n mBestValue = DBL_MAX;\n\n return true;\n}\n\nvoid COptMethodSteepestDescent::gradient()\n{\n unsigned C_INT32 i;\n\n C_FLOAT64 y;\n C_FLOAT64 x;\n\n y = evaluate();\n\n for (i = 0; i < mVariableSize && mContinue; i++)\n {\n if ((x = *(*mpOptItem)[i]->getObjectValue()) != 0.0)\n {\n (*(*mpSetCalculateVariable)[i])(x * 1.001);\n mGradient[i] = (y - evaluate()) \/ (x * 0.001);\n }\n\n else\n {\n (*(*mpSetCalculateVariable)[i])(1e-7);\n mGradient[i] = (y - evaluate()) \/ 1e-7;\n }\n\n (*(*mpSetCalculateVariable)[i])(x);\n }\n}\n\nconst C_FLOAT64 COptMethodSteepestDescent::descentLine(const C_FLOAT64 & x)\n{\n for (unsigned C_INT32 i = 0; i < mVariableSize; i++)\n (*(*mpSetCalculateVariable)[i])(mIndividual[i] + x * mGradient[i]);\n\n return evaluate();\n}\n\n\/\/ evaluate the fitness of one individual\nconst C_FLOAT64 & COptMethodSteepestDescent::evaluate()\n{\n \/\/ evaluate the fitness\n mContinue = mpOptProblem->calculate();\n\n mValue = mpOptProblem->getCalculateValue();\n\n \/\/ when we leave the either the parameter or functional domain\n \/\/ we penalize the objective value by forcing it to be larger\n \/\/ than the best value recorded so far.\n if (mValue < mBestValue &&\n (!mpOptProblem->checkParametricConstraints() ||\n !mpOptProblem->checkFunctionalConstraints()))\n mValue = mBestValue + fabs(mBestValue - mValue);\n\n return mValue;\n}\n\nvoid COptMethodSteepestDescent::initObjects()\n{\n addObjectReference(\"Current Iteration\", mCurrentIteration, CCopasiObject::ValueInt);\n}\n<|endoftext|>"} {"text":"<commit_before>\/**\n * SFCGAL\n *\n * Copyright (C) 2012-2013 Oslandia <infos@oslandia.com>\n * Copyright (C) 2012-2013 IGN (http:\/\/www.ign.fr)\n *\n * This program is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\n *\/\n#include <boost\/test\/unit_test.hpp>\n\n#include <SFCGAL\/Kernel.h>\n#include <SFCGAL\/all.h>\n#include <SFCGAL\/io\/wkt.h>\n#include <SFCGAL\/algorithm\/length.h>\n\n\nusing namespace boost::unit_test ;\nusing namespace SFCGAL ;\n\nBOOST_AUTO_TEST_SUITE( SFCGAL_algorithm_LengthTest )\n\nBOOST_AUTO_TEST_CASE( testZeroLength )\n{\n\tBOOST_CHECK_EQUAL( algorithm::length( *io::readWkt(\"POINT(0.0 0.0)\" ) ), 0.0 );\n\tBOOST_CHECK_EQUAL( algorithm::length( *io::readWkt(\"LINESTRING EMPTY\" ) ), 0.0 );\n\tBOOST_CHECK_EQUAL( algorithm::length( *io::readWkt(\"POLYGON((0 0,0 1,1 1,1 0,0 0))\" ) ), 0.0 );\n}\n\nBOOST_AUTO_TEST_CASE( testZeroLengthVertical )\n{\n\tBOOST_CHECK_EQUAL( algorithm::length( *io::readWkt(\"LINESTRING(0.0 0.0 0.0,0.0 0.0 1.0)\" ) ), 0.0 );\n}\n\nBOOST_AUTO_TEST_CASE( testLengthLineString )\n{\n\tBOOST_CHECK_EQUAL( algorithm::length( *io::readWkt(\"LINESTRING(0.0 0.0,3.0 4.0)\" ) ), 5.0 );\n\tBOOST_CHECK_EQUAL( algorithm::length( *io::readWkt(\"LINESTRING(0.0 0.0,0.0 1.0,1.0 1.0)\" ) ), 2.0 );\n}\n\n\/\/-- 3D\n\n\nBOOST_AUTO_TEST_CASE( test3DZeroLength )\n{\n\tBOOST_CHECK_EQUAL( algorithm::length3D( *io::readWkt(\"POINT(0.0 0.0)\" ) ), 0.0 );\n\tBOOST_CHECK_EQUAL( algorithm::length3D( *io::readWkt(\"LINESTRING EMPTY\" ) ), 0.0 );\n\tBOOST_CHECK_EQUAL( algorithm::length3D( *io::readWkt(\"POLYGON((0 0,0 1,1 1,1 0,0 0))\" ) ), 0.0 );\n}\nBOOST_AUTO_TEST_CASE( test3DLengthVertical )\n{\n\tBOOST_CHECK_EQUAL( algorithm::length3D( *io::readWkt(\"LINESTRING(0.0 0.0 0.0,0.0 0.0 1.0)\" ) ), 1.0 );\n}\nBOOST_AUTO_TEST_CASE( test3DLengthLineString )\n{\n\tBOOST_CHECK_EQUAL( algorithm::length3D( *io::readWkt(\"LINESTRING(0.0 0.0 0.0,0.0 1.0 0.0,0.0 1.0 1.0)\" ) ), 2.0 );\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n\n<commit_msg>[algorithm::distance]add some tests<commit_after>\/**\n * SFCGAL\n *\n * Copyright (C) 2012-2013 Oslandia <infos@oslandia.com>\n * Copyright (C) 2012-2013 IGN (http:\/\/www.ign.fr)\n *\n * This program is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\n *\/\n#include <boost\/test\/unit_test.hpp>\n\n#include <SFCGAL\/Kernel.h>\n#include <SFCGAL\/all.h>\n#include <SFCGAL\/io\/wkt.h>\n#include <SFCGAL\/algorithm\/length.h>\n\n\nusing namespace boost::unit_test ;\nusing namespace SFCGAL ;\n\nBOOST_AUTO_TEST_SUITE( SFCGAL_algorithm_LengthTest )\n\nBOOST_AUTO_TEST_CASE( testZeroLength )\n{\n\tBOOST_CHECK_EQUAL( algorithm::length( *io::readWkt(\"POINT(0.0 0.0)\" ) ), 0.0 );\n\tBOOST_CHECK_EQUAL( algorithm::length( *io::readWkt(\"LINESTRING EMPTY\" ) ), 0.0 );\n\tBOOST_CHECK_EQUAL( algorithm::length( *io::readWkt(\"POLYGON((0 0,0 1,1 1,1 0,0 0))\" ) ), 0.0 );\n}\n\nBOOST_AUTO_TEST_CASE( testZeroLengthVertical )\n{\n\tBOOST_CHECK_EQUAL( algorithm::length( *io::readWkt(\"LINESTRING(0.0 0.0 0.0,0.0 0.0 1.0)\" ) ), 0.0 );\n}\n\nBOOST_AUTO_TEST_CASE( testLengthLineString )\n{\n\tBOOST_CHECK_EQUAL( algorithm::length( *io::readWkt(\"LINESTRING(0.0 0.0,3.0 4.0)\" ) ), 5.0 );\n\tBOOST_CHECK_EQUAL( algorithm::length( *io::readWkt(\"LINESTRING(0.0 0.0,0.0 1.0,1.0 1.0)\" ) ), 2.0 );\n}\n\n\/\/-- 3D\n\n\nBOOST_AUTO_TEST_CASE( test3DZeroLength )\n{\n\tBOOST_CHECK_EQUAL( algorithm::length3D( *io::readWkt(\"POINT(0.0 0.0)\" ) ), 0.0 );\n\tBOOST_CHECK_EQUAL( algorithm::length3D( *io::readWkt(\"LINESTRING EMPTY\" ) ), 0.0 );\n\tBOOST_CHECK_EQUAL( algorithm::length3D( *io::readWkt(\"POLYGON((0 0,0 1,1 1,1 0,0 0))\" ) ), 0.0 );\n}\nBOOST_AUTO_TEST_CASE( test3DLengthVertical )\n{\n\tBOOST_CHECK_EQUAL( algorithm::length3D( *io::readWkt(\"LINESTRING(0.0 0.0 0.0,0.0 0.0 1.0)\" ) ), 1.0 );\n}\nBOOST_AUTO_TEST_CASE( test3DLengthLineString )\n{\n\tBOOST_CHECK_EQUAL( algorithm::length3D( *io::readWkt(\"LINESTRING(0.0 0.0 0.0,0.0 1.0 0.0,0.0 1.0 1.0)\" ) ), 2.0 );\n}\n\n\n\/\/-- invalid type 2D\n\nBOOST_AUTO_TEST_CASE( testLength_invalidType )\n{\n\tstd::vector< std::string > wkts ;\n\twkts.push_back( \"POINT(3.0 4.0)\" );\n\twkts.push_back( \"TRIANGLE((0.0 0.0,1.0 0.0,1.0 1.0,0.0 0.0))\" );\n\twkts.push_back( \"POLYGON((0.0 0.0,1.0 0.0,1.0 1.0,0.0 0.0))\" );\n\n\tfor ( size_t i = 0; i < wkts.size(); i++ ){\n\t\tBOOST_TEST_MESSAGE( wkts[i] );\n\t\tBOOST_CHECK_EQUAL( algorithm::length( *io::readWkt( wkts[i] ) ), 0.0 );\n\t\tBOOST_CHECK_EQUAL( algorithm::length3D( *io::readWkt( wkts[i] ) ), 0.0 );\n\t}\n\n}\n\/\/-- invalid type 3D\n\n\n\n\nBOOST_AUTO_TEST_SUITE_END()\n\n<|endoftext|>"} {"text":"<commit_before>\/******************************************************************************\n * ____ _ _____ *\n * \/ ___| \/ \\ | ___| C++ *\n * | | \/ _ \\ | |_ Actor *\n * | |___ \/ ___ \\| _| Framework *\n * \\____\/_\/ \\_|_| *\n * *\n * Copyright 2011-2018 Dominik Charousset *\n * *\n * Distributed under the terms and conditions of the BSD 3-Clause License or *\n * (at your option) under the terms and conditions of the Boost Software *\n * License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. *\n * *\n * If you did not receive a copy of the license files, see *\n * http:\/\/opensource.org\/licenses\/BSD-3-Clause and *\n * http:\/\/www.boost.org\/LICENSE_1_0.txt. *\n ******************************************************************************\/\n\n#pragma once\n\n#include \"caf\/config.hpp\"\n#include \"caf\/error.hpp\"\n\n#include \"caf\/detail\/type_traits.hpp\"\n\n\/\/ The class `callback` intentionally has no virtual destructor, because\n\/\/ the lifetime of callback objects is never managed via base pointers.\nCAF_PUSH_NON_VIRTUAL_DTOR_WARNING\n\nnamespace caf {\n\n\/\/\/ Describes a simple callback, usually implemented via lambda expression.\n\/\/\/ Callbacks are used as \"type-safe function objects\" wherever an interface\n\/\/\/ requires dynamic dispatching. The alternative would be to store the lambda\n\/\/\/ in a `std::function`, which adds another layer of indirection and\n\/\/\/ requires a heap allocation. With the callback implementation of CAF,\n\/\/\/ the object remains on the stack and does not cause more overhead\n\/\/\/ than necessary.\ntemplate <class Signature>\nclass callback;\n\ntemplate <class Result, class... Ts>\nclass callback<Result(Ts...)> {\npublic:\n virtual Result operator()(Ts...) = 0;\n};\n\n\/\/\/ Utility class for wrapping a function object of type `F`.\ntemplate <class F, class Signature>\nclass callback_impl;\n\ntemplate <class F, class Result, class... Ts>\nclass callback_impl<F, Result(Ts...)> : public callback<Result(Ts...)> {\npublic:\n callback_impl(F&& f) : f_(std::move(f)) {\n \/\/ nop\n }\n\n callback_impl(callback_impl&&) = default;\n\n callback_impl& operator=(callback_impl&&) = default;\n\n Result operator()(Ts... xs) override {\n return f_(std::forward<Ts>(xs)...);\n }\n\nprivate:\n F f_;\n};\n\n\/\/\/ Creates a ::callback from the function object `fun`.\n\/\/\/ @relates callback\ntemplate <class F>\nauto make_callback(F fun) {\n using signature = typename detail::get_callable_trait<F>::fun_sig;\n return callback_impl<F, signature>{std::move(fun)};\n}\n\n} \/\/ namespace caf\n\nCAF_POP_WARNINGS\n<commit_msg>Add support for heap-allocated callbacks<commit_after>\/******************************************************************************\n * ____ _ _____ *\n * \/ ___| \/ \\ | ___| C++ *\n * | | \/ _ \\ | |_ Actor *\n * | |___ \/ ___ \\| _| Framework *\n * \\____\/_\/ \\_|_| *\n * *\n * Copyright 2011-2018 Dominik Charousset *\n * *\n * Distributed under the terms and conditions of the BSD 3-Clause License or *\n * (at your option) under the terms and conditions of the Boost Software *\n * License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. *\n * *\n * If you did not receive a copy of the license files, see *\n * http:\/\/opensource.org\/licenses\/BSD-3-Clause and *\n * http:\/\/www.boost.org\/LICENSE_1_0.txt. *\n ******************************************************************************\/\n\n#pragma once\n\n#include \"caf\/config.hpp\"\n#include \"caf\/detail\/type_traits.hpp\"\n#include \"caf\/error.hpp\"\n\n#include <memory>\n\nnamespace caf {\n\n\/\/\/ Describes a simple callback, usually implemented via lambda expression.\n\/\/\/ Callbacks are used as \"type-safe function objects\" wherever an interface\n\/\/\/ requires dynamic dispatching. The alternative would be to store the lambda\n\/\/\/ in a `std::function`, which adds another layer of indirection and always\n\/\/\/ requires a heap allocation. With the callback implementation of CAF, the\n\/\/\/ object may remains on the stack and do not cause more overhead than\n\/\/\/ necessary.\ntemplate <class Signature>\nclass callback;\n\ntemplate <class Result, class... Ts>\nclass callback<Result(Ts...)> {\npublic:\n virtual ~callback() {\n \/\/ nop\n }\n\n virtual Result operator()(Ts...) = 0;\n};\n\n\/\/\/ Smart pointer type for heap-allocated callbacks with unique ownership.\ntemplate <class Signature>\nusing unique_callback_ptr = std::unique_ptr<callback<Signature>>;\n\n\/\/\/ Smart pointer type for heap-allocated callbacks with shared ownership.\ntemplate <class Signature>\nusing shared_callback_ptr = std::shared_ptr<callback<Signature>>;\n\n\/\/\/ Utility class for wrapping a function object of type `F`.\ntemplate <class F, class Signature>\nclass callback_impl;\n\ntemplate <class F, class Result, class... Ts>\nclass callback_impl<F, Result(Ts...)> final : public callback<Result(Ts...)> {\npublic:\n callback_impl(F&& f) : f_(std::move(f)) {\n \/\/ nop\n }\n\n callback_impl(callback_impl&&) = default;\n\n callback_impl& operator=(callback_impl&&) = default;\n\n Result operator()(Ts... xs) override {\n return f_(std::forward<Ts>(xs)...);\n }\n\nprivate:\n F f_;\n};\n\n\/\/\/ Wraps `fun` into a @ref callback function object.\n\/\/\/ @relates callback\ntemplate <class F>\nauto make_callback(F fun) {\n using signature = typename detail::get_callable_trait<F>::fun_sig;\n return callback_impl<F, signature>{std::move(fun)};\n}\n\n\/\/\/ Creates a heap-allocated, type-erased @ref callback from the function object\n\/\/\/ `fun`.\n\/\/\/ @relates callback\ntemplate <class F>\nauto make_type_erased_callback(F fun) {\n using signature = typename detail::get_callable_trait<F>::fun_sig;\n using result_t = unique_callback_ptr<signature>;\n return result_t{new callback_impl<F, signature>{std::move(fun)}};\n}\n\n\/\/\/ Creates a heap-allocated, type-erased @ref callback from the function object\n\/\/\/ `fun` with shared ownership.\n\/\/\/ @relates callback\ntemplate <class F>\nauto make_shared_type_erased_callback(F fun) {\n using signature = typename detail::get_callable_trait<F>::fun_sig;\n auto res = std::make_shared<callback_impl<F, signature>>(std::move(fun));\n return shared_callback_ptr<signature>{std::move(res)};\n}\n\n} \/\/ namespace caf\n<|endoftext|>"} {"text":"<commit_before>#include \"NL_DeviceCore.h\"\n\n#include \"NL_Clock.h\"\n#include \"NL_System.h\"\n#include \"NL_SysManager.h\"\n#include \"NL_Scheduler.h\"\n#include \"NL_StateManager.h\"\n#include \"NL_IEngine.h\"\n\n#include <cassert>\n\nnamespace NLE \n{\n\tnamespace Core \n\t{\n\t\tDeviceCore *DeviceCore::_deviceCore = nullptr;\n\n\t\tDeviceCore::DeviceCore() :\n\t\t\t_initialized(false)\n\t\t{ \n\t\t\t_clock = std::make_unique<Clock>();\n\t\t\t_sysManager = std::make_unique<SysManager>();\n\t\t\t_scheduler = std::make_unique<Scheduler>();\n\t\t\t_stateManager = std::make_unique<StateManager>();\n\t\t\t_iEngine = std::make_unique<IEngine>(_scheduler, _sysManager, _stateManager);\n\t\t}\n\n\t\tDeviceCore::~DeviceCore()\n\t\t{\n\t\t\trelease();\n\t\t}\n\n\t\tbool DeviceCore::initialize()\n\t\t{\n\t\t\tassert(!_initialized);\n\n\t\t\tstd::unique_ptr<Scheduler>& scheduler = _scheduler;\n\t\t\tstd::unique_ptr<SysManager>& sysMngr = _sysManager;\n\t\t\tstd::unique_ptr<StateManager>& stateMngr = _stateManager;\n\n\t\t\tif (!_clock->initialize([&scheduler, &sysMngr, &stateMngr](){\n\t\t\t\tprintf(\"Tick...\\n\");\n\t\t\t\tscheduler->manageExecution(sysMngr, stateMngr);\n\t\t\t}))\n\t\t\t\treturn false;\n\t\t\t\t\n\t\t\tif (!_scheduler->initialize())\n\t\t\t\treturn false;\n\t\t\tif (!_sysManager->initialize(_scheduler, _iEngine))\n\t\t\t\treturn false;\n\t\t\tif (!_stateManager->initialize())\n\t\t\t\treturn false;\n\t\t\t\n\t\t\t_initialized = true;\n\t\t\treturn true;\n\t\t}\n\n\t\tvoid DeviceCore::release()\n\t\t{\t\t\n\t\t\tif (_sysManager)\n\t\t\t\t_sysManager->release();\n\t\t\tif (_stateManager)\n\t\t\t\t_stateManager->release();\n\t\t\tif (_scheduler)\n\t\t\t\t_scheduler->release();\n\t\t\tif (_clock)\n\t\t\t\t_clock->release();\n\n\t\t\t_initialized = false;\n\t\t}\n\n\t\tvoid DeviceCore::attachSystem(uint_fast32_t sysId, ExecutionDesc executionDesc, std::unique_ptr<System> system)\n\t\t{\n\t\t\t_sysManager->attachSystem(sysId, executionDesc, std::move(system));\n\t\t}\n\n\t\tvoid DeviceCore::setClockPeriodNs(unsigned long long periodNs)\n\t\t{\n\t\t\t_clock->setPeriodNs(periodNs);\n\t\t}\n\n\t\tvoid DeviceCore::setNumThreads(uint_fast32_t numThreads)\n\t\t{\n\t\t\t_scheduler->setNumThreads(numThreads);\n\t\t}\n\n\t\tuint_fast32_t DeviceCore::getNumHardwareThreads()\n\t\t{\n\t\t\treturn _scheduler->getNumHardwareThreads();\n\t\t}\n\n\t\tvoid DeviceCore::run()\n\t\t{\n\t\t\t_clock->run();\n\t\t}\n\n\t\tvoid DeviceCore::stop()\n\t\t{\n\t\t\t_clock->stop();\n\t\t}\n\t}\n}<commit_msg>core can only be ran when initialized<commit_after>#include \"NL_DeviceCore.h\"\n\n#include \"NL_Clock.h\"\n#include \"NL_System.h\"\n#include \"NL_SysManager.h\"\n#include \"NL_Scheduler.h\"\n#include \"NL_StateManager.h\"\n#include \"NL_IEngine.h\"\n\n#include <cassert>\n\nnamespace NLE \n{\n\tnamespace Core \n\t{\n\t\tDeviceCore *DeviceCore::_deviceCore = nullptr;\n\n\t\tDeviceCore::DeviceCore() :\n\t\t\t_initialized(false)\n\t\t{ \n\t\t\t_clock = std::make_unique<Clock>();\n\t\t\t_sysManager = std::make_unique<SysManager>();\n\t\t\t_scheduler = std::make_unique<Scheduler>();\n\t\t\t_stateManager = std::make_unique<StateManager>();\n\t\t\t_iEngine = std::make_unique<IEngine>(_scheduler, _sysManager, _stateManager);\n\t\t}\n\n\t\tDeviceCore::~DeviceCore()\n\t\t{\n\t\t\trelease();\n\t\t}\n\n\t\tbool DeviceCore::initialize()\n\t\t{\n\t\t\tassert(!_initialized);\n\n\t\t\tstd::unique_ptr<Scheduler>& scheduler = _scheduler;\n\t\t\tstd::unique_ptr<SysManager>& sysMngr = _sysManager;\n\t\t\tstd::unique_ptr<StateManager>& stateMngr = _stateManager;\n\n\t\t\tif (!_clock->initialize([&scheduler, &sysMngr, &stateMngr](){\n\t\t\t\tprintf(\"Tick...\\n\");\n\t\t\t\tscheduler->manageExecution(sysMngr, stateMngr);\n\t\t\t}))\n\t\t\t\treturn false;\n\t\t\t\t\n\t\t\tif (!_scheduler->initialize())\n\t\t\t\treturn false;\n\t\t\tif (!_sysManager->initialize(_scheduler, _iEngine))\n\t\t\t\treturn false;\n\t\t\tif (!_stateManager->initialize())\n\t\t\t\treturn false;\n\t\t\t\n\t\t\t_initialized = true;\n\t\t\treturn true;\n\t\t}\n\n\t\tvoid DeviceCore::release()\n\t\t{\t\t\n\t\t\tif (_sysManager)\n\t\t\t\t_sysManager->release();\n\t\t\tif (_stateManager)\n\t\t\t\t_stateManager->release();\n\t\t\tif (_scheduler)\n\t\t\t\t_scheduler->release();\n\t\t\tif (_clock)\n\t\t\t\t_clock->release();\n\n\t\t\t_initialized = false;\n\t\t}\n\n\t\tvoid DeviceCore::attachSystem(uint_fast32_t sysId, ExecutionDesc executionDesc, std::unique_ptr<System> system)\n\t\t{\n\t\t\t_sysManager->attachSystem(sysId, executionDesc, std::move(system));\n\t\t}\n\n\t\tvoid DeviceCore::setClockPeriodNs(unsigned long long periodNs)\n\t\t{\n\t\t\t_clock->setPeriodNs(periodNs);\n\t\t}\n\n\t\tvoid DeviceCore::setNumThreads(uint_fast32_t numThreads)\n\t\t{\n\t\t\t_scheduler->setNumThreads(numThreads);\n\t\t}\n\n\t\tuint_fast32_t DeviceCore::getNumHardwareThreads()\n\t\t{\n\t\t\treturn _scheduler->getNumHardwareThreads();\n\t\t}\n\n\t\tvoid DeviceCore::run()\n\t\t{\n\t\t\tassert(_initialized);\n\t\t\t_clock->run();\n\t\t}\n\n\t\tvoid DeviceCore::stop()\n\t\t{\n\t\t\t_clock->stop();\n\t\t}\n\t}\n}<|endoftext|>"} {"text":"<commit_before>#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <iostream>\n#include <fstream>\n#include <string>\n\nusing namespace std;\n\n\/\/ Quicksort\nvoid quickSort(int a[], int p, int r);\nint partition(int a[], int p, int r);\n\/\/ BubbleSort\nvoid bubbleSort(int array[]);\n\nmain(int argc, char** argv)\n{\n if (argc != 2)\n\t{\n printf(\"Nope! Like this: .\/bubbles n\\n\");\n return 0;\n }\n\n int userNum = atoi(&argv[1][0]);\n\tcout << \"userNum: \" << userNum << endl;\n\tint array[userNum + 1]; \/\/ creates array to hold names\n\tint n = 0; \n\tifstream myfile (\"..\/..\/size1000\/list998\"); \/\/opening the file.\n \n\tif(myfile.is_open()) \/\/if the file is open\n\t{\n\t\twhile (!myfile.eof() && (n < userNum)) \/\/while the end of file is NOT reached\n\t\t{\n\t\t\tmyfile >> array[n];\n \t\tn++;\n \t}\n\t\tarray[n] = '\\0';\n\t\tmyfile.close(); \/\/closing the file\n\n\t}\n\telse cout << \"Unable to open file\"; \/\/if the file is not open output\n\n\tn = 0;\n cout << \"unsorted list:\\n{\";\n while (array[n] != '\\0')\n {\n cout << array[n] << \", \";\n ++n;\n }\t\n cout << \"}\\n\";\n\n\tint t1 = clock();\n \/\/bubbleSort(array);\n\tint t2 = clock();\n\tquickSort(array, 0, 1000);\n\tint t3 = clock();\n n = 0;\n cout << \"sorted list:\\n{\";\n while (array[n] != '\\0')\n {\n cout << array[n] << \", \";\n ++n;\n }\n cout << \"}\\n\";\n\tcout << \"t1: \" << t1 << \", t2: \" << t2 << endl;\n\tcout << \"BubbleSort execution time on n = \"<< userNum << \": \" << t2-t1 << endl;\n\treturn 0;\n}\n\nvoid bubbleSort(int array[])\n{\n int swap;\n do{\n swap = 0;\n int n = 1;\n while (array[n] != '\\0')\n {\n if (array[n-1] > array[n])\n {\n swap = 1;\n int temp = array[n-1];\n array[n-1] = array[n];\n array[n] = temp;\n }\n ++n;\n }\n }while(swap == 1);\n}\t\nint partition(int a[], int p, int r) {\n int x = a[r];\n int j = p - 1;\n for (int i = p; i < r; i++) {\n\n if (x <= a[i]) {\n j = j + 1;\n int temp = a[j];\n a[j] = a[i];\n a[i] = temp;\n }\n }\n a[r] = a[j + 1];\n a[j + 1] = x;\n\n return (j + 1);\n}\nvoid quickSort(int a[], int p, int r) {\n if (p < r) {\n int q = partition(a, p, r);\n quickSort(a, p, q - 1);\n quickSort(a, q + 1, r);\n }\n}\n<commit_msg>added insertion. now have bbl, ins, quick<commit_after>#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <iostream>\n#include <fstream>\n#include <string>\n#include <time.h>\n#include <sys\/time.h>\nusing namespace std;\n\n\/\/ Quicksort\nvoid quickSort(int a[], int p, int r);\nint partition(int a[], int p, int r);\n\n\/\/ BubbleSort\nvoid bubbleSort(int array[]);\n\n\/\/ InsertionSort\nvoid insertionSort(int arr[], int length);\n\n\/\/ Get unsorted lists of integers\nvoid getList(int array[], int userNum);\n\n\/\/ Print array contents\nvoid printList(int array[]);\n\nmain(int argc, char** argv)\n{\n if (argc != 2)\n {\n printf(\"Nope! Like this: .\/allSort n\\n\");\n return 0;\n }\n\n int userNum = atoi(&argv[1][0]);\n int array[userNum + 1]; \/\/ creates array to hold names\n getList(array, userNum);\n\n \/*\n cout << \"unsorted list:\\n{\";\n printList(array);\n cout << \"}\\n\";\n *\/\n\n timeval t1;\n timeval t2;\n\n \/\/ Bubble Sort\t\n gettimeofday(&t1, NULL);\n bubbleSort(array);\n gettimeofday(&t2, NULL);\n\n \/*\n cout << \"bubbleSorted list:\\n{\";\n printList(array);\n cout << \"}\\n\";\n\n *\/\n \/\/cout << \"t1: \" << t1.tv_usec << \", t2: \" << t2.tv_usec << endl;\n cout << \"bubbleSort execution time on n = \"<< userNum << \": \" << t2.tv_usec - t1.tv_usec << endl;\n\n getList(array, userNum);\n\n \/*\n cout << \"unsorted list:\\n{\";\n printList(array);\n cout << \"}\\n\";\n *\/\n\n \/\/ Quick Sort\t\n gettimeofday(&t1, NULL);\n quickSort(array, 0, 1000);\n gettimeofday(&t2, NULL);\n\n \/*\n cout << \"quickSorted list:\\n{\";\n printList(array);\n cout << \"}\\n\";\n\n cout << \"t1: \" << t1 << \", t2: \" << t2 << endl;\n *\/\n cout << \"quickSort execution time on n = \"<< userNum << \": \" << t2.tv_usec - t1.tv_usec << endl;\n\n getList(array, userNum);\n\n\t\/*\n\tcout << \"unSorted list:\\n{\";\n \tprintList(array);\n \tcout << \"}\\n\";\n\t*\/\n\n gettimeofday(&t1, NULL);\n insertionSort(array, userNum);\n gettimeofday(&t2, NULL);\n\n\t\/*\n cout << \"insertionSorted list:\\n{\";\n printList(array);\n cout << \"}\\n\";\n\t*\/\n\n cout << \"insertionSort execution time on n = \"<< userNum << \": \" << t2.tv_usec - t1.tv_usec << endl;\n\n return 0;\n}\n\nvoid bubbleSort(int array[])\n{\n int swap;\n do{\n swap = 0;\n int n = 1;\n while (array[n] != '\\0')\n {\n if (array[n-1] > array[n])\n {\n swap = 1;\n int temp = array[n-1];\n array[n-1] = array[n];\n array[n] = temp;\n }\n ++n;\n }\n }while(swap == 1);\n}\t\n\nint partition(int a[], int p, int r) {\n int x = a[r];\n int j = p - 1;\n for (int i = p; i < r; i++) {\n\n if (x <= a[i]) {\n j = j + 1;\n int temp = a[j];\n a[j] = a[i];\n a[i] = temp;\n }\n }\n a[r] = a[j + 1];\n a[j + 1] = x;\n\n return (j + 1);\n}\n\nvoid quickSort(int a[], int p, int r) {\n if (p < r) {\n int q = partition(a, p, r);\n quickSort(a, p, q - 1);\n quickSort(a, q + 1, r);\n }\n}\n\nvoid getList(int array[], int userNum)\n{\n int n = 0;\n\n ifstream myfile (\"..\/..\/size1000\/list998\"); \/\/opening the file.\n if(myfile.is_open()) \/\/if the file is open\n { \n while (!myfile.eof() && (n < userNum)) \/\/while the end of file is NOT reached\n { \n myfile >> array[n];\n n++;\n } \n array[n] = '\\0';\n myfile.close(); \/\/closing the file\n\n } \n else cout << \"Unable to open file\"; \/\/if the file is not open output\n}\n\nvoid printList(int array[])\n{\n int n = 0;\n while (array[n] != '\\0')\n { \n cout << array[n] << \", \";\n ++n;\n } \n}\n\nvoid insertionSort(int arr[], int length) \n{\n\n int i, j, tmp;\n for (i = 1; i < length; i++) \n {\n j = i;\n while (j > 0 && arr[j - 1] > arr[j]) \n {\n tmp = arr[j];\n arr[j] = arr[j - 1]; \n arr[j - 1] = tmp;\n j--;\n\n } \n\n } \n\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (C) 2017 - 2018 by Pedro Mendes, Virginia Tech Intellectual\n\/\/ Properties, Inc., University of Heidelberg, and University of\n\/\/ of Connecticut School of Medicine.\n\/\/ All rights reserved.\n\n\/\/ Copyright (C) 2010 - 2016 by Pedro Mendes, Virginia Tech Intellectual\n\/\/ Properties, Inc., University of Heidelberg, and The University\n\/\/ of Manchester.\n\/\/ All rights reserved.\n\n\/\/ Copyright (C) 2008 - 2009 by Pedro Mendes, Virginia Tech Intellectual\n\/\/ Properties, Inc., EML Research, gGmbH, University of Heidelberg,\n\/\/ and The University of Manchester.\n\/\/ All rights reserved.\n\n\/\/ Copyright (C) 2007 by Pedro Mendes, Virginia Tech Intellectual\n\/\/ Properties, Inc. and EML Research, gGmbH.\n\/\/ All rights reserved.\n\n#include \"copasi.h\"\n\n#include \"COptMethodTruncatedNewton.h\"\n#include \"COptProblem.h\"\n#include \"COptItem.h\"\n#include \"COptTask.h\"\n\n#include \"parameterFitting\/CFitProblem.h\"\n#include \"copasi\/core\/CDataObjectReference.h\"\n\nCOptMethodTruncatedNewton::COptMethodTruncatedNewton(const CDataContainer * pParent,\n const CTaskEnum::Method & methodType,\n const CTaskEnum::Task & taskType):\n COptMethod(pParent, methodType, taskType),\n mpTruncatedNewton(new FTruncatedNewtonTemplate<COptMethodTruncatedNewton>(this, &COptMethodTruncatedNewton::sFun)),\n mpCTruncatedNewton(new CTruncatedNewton())\n{\n initObjects();\n}\n\nCOptMethodTruncatedNewton::COptMethodTruncatedNewton(const COptMethodTruncatedNewton & src,\n const CDataContainer * pParent):\n COptMethod(src, pParent),\n mpTruncatedNewton(new FTruncatedNewtonTemplate<COptMethodTruncatedNewton>(this, &COptMethodTruncatedNewton::sFun)),\n mpCTruncatedNewton(new CTruncatedNewton())\n{initObjects();}\n\nCOptMethodTruncatedNewton::~COptMethodTruncatedNewton()\n{\n pdelete(mpTruncatedNewton);\n pdelete(mpCTruncatedNewton);\n cleanup();\n}\n\nvoid COptMethodTruncatedNewton::initObjects()\n{\n addObjectReference(\"Current Iteration\", mIteration, CDataObject::ValueInt);\n}\n\nbool COptMethodTruncatedNewton::optimise()\n{\n if (!initialize()) return false;\n\n if (mLogVerbosity > 0)\n mMethodLog.enterLogEntry(\n COptLogEntry(\n \"Algorithm started\",\n \"For more information about this method see: http:\/\/copasi.org\/Support\/User_Manual\/Methods\/Optimization_Methods\/Truncated_Newton\/\"\n )\n );\n\n C_FLOAT64 fest;\n C_INT lw, ierror = 0;\n lw = 14 * mVariableSize;\n\n CVector< C_FLOAT64 > up(mVariableSize);\n CVector< C_FLOAT64 > low(mVariableSize);\n CVector< C_INT > iPivot(mVariableSize);\n CVector< C_FLOAT64 > dwork(lw);\n\n up = std::numeric_limits< C_FLOAT64 >::max();\n low = - std::numeric_limits< C_FLOAT64 >::max();\n\n \/\/ initial point is the first guess but we have to make sure that\n \/\/ we are within the parameter domain\n C_INT i, repeat;\n bool pointInParameterDomain = true;\n\n for (i = 0; i < mVariableSize; i++)\n {\n const COptItem & OptItem = *(*mpOptItem)[i];\n\n \/\/ :TODO: In COPASI the bounds are not necessarry fixed.\n \/\/ Since evaluate checks for boundaries and constraints this is not\n \/\/ needed. The question remaining is how does tnbc_ handle unconstraint problems?\n \/\/ low[i] = *OptItem.getLowerBoundValue();\n \/\/ up[i] = *OptItem.getUpperBoundValue();\n\n mCurrent[i] = OptItem.getStartValue();\n\n switch (OptItem.checkConstraint(mCurrent[i]))\n {\n case - 1:\n mCurrent[i] = *OptItem.getLowerBoundValue();\n pointInParameterDomain = false;\n break;\n\n case 1:\n mCurrent[i] = *OptItem.getUpperBoundValue();\n pointInParameterDomain = false;\n break;\n\n case 0:\n break;\n }\n\n \/\/ set the value\n *mContainerVariables[i] = (mCurrent[i]);\n }\n\n if (!pointInParameterDomain && (mLogVerbosity > 0))\n mMethodLog.enterLogEntry(COptLogEntry(\"Initial point outside parameter domain.\"));\n\n \/\/ Report the first value as the current best\n mBestValue = evaluate();\n mBest = mCurrent;\n mContinue = mpOptProblem->setSolution(mBestValue, mBest);\n\n repeat = 0;\n\n while (repeat < 10 && mContinue)\n {\n repeat++;\n\n \/\/ estimate minimum is 1\/10 initial function value\n fest = (1 - pow(0.9, (C_FLOAT64) repeat)) * mEvaluationValue;\n ierror = 0;\n\n \/\/ minimise\n try\n {\n mpCTruncatedNewton->tnbc_(&ierror, &mVariableSize, mCurrent.array(), &fest, mGradient.array(), dwork.array(), &lw, mpTruncatedNewton, low.array(), up.array(), iPivot.array());\n\n mEvaluationValue = fest;\n }\n\n \/\/ This signals that the user opted to interrupt\n catch (bool)\n {\n break;\n }\n\n if (ierror < 0)\n fatalError(); \/\/ Invalid parameter values.\n\n \/\/ The way the method is currently implemented may lead to parameters just outside the boundaries.\n \/\/ We need to check whether the current value is within the boundaries or whether the corrected\n \/\/ leads to an improved solution.\n\n bool withinBounds = true;\n\n for (i = 0; i < mVariableSize; i++)\n {\n const COptItem & OptItem = *(*mpOptItem)[i];\n\n \/\/force it to be within the bounds\n switch (OptItem.checkConstraint(mCurrent[i]))\n {\n case - 1:\n withinBounds = false;\n mCurrent[i] = *OptItem.getLowerBoundValue();\n break;\n\n case 1:\n withinBounds = false;\n mCurrent[i] = *OptItem.getUpperBoundValue();\n break;\n\n case 0:\n break;\n }\n\n *mContainerVariables[i] = (mCurrent[i]);\n }\n\n evaluate();\n\n \/\/ Is the corrected value better than solution?\n if (mEvaluationValue < mBestValue)\n {\n \/\/ We found a new best value lets report it.\n \/\/ and store that value\n mBest = mCurrent;\n mBestValue = mEvaluationValue;\n\n mContinue = mpOptProblem->setSolution(mBestValue, mBest);\n\n \/\/ We found a new best value lets report it.\n mpParentTask->output(COutputInterface::DURING);\n }\n\n \/\/ We found a solution\n if (withinBounds)\n break;\n\n \/\/ Choosing another starting point will be left to the user\n#ifdef XXXX\n\n \/\/ Try another starting point\n for (i = 0; i < mVariableSize; i++)\n {\n mCurrent[i] *= 1.2;\n const COptItem & OptItem = *(*mpOptItem)[i];\n\n \/\/force it to be within the bounds\n switch (OptItem.checkConstraint(mCurrent[i]))\n {\n case - 1:\n mCurrent[i] = *OptItem.getLowerBoundValue();\n break;\n\n case 1:\n mCurrent[i] = *OptItem.getUpperBoundValue();\n break;\n\n case 0:\n break;\n }\n\n *mContainerVariables[i] = (mCurrent[i]);\n }\n\n evaluate();\n\n \/\/ Check whether we improved\n if (mEvaluationValue < mBestValue)\n {\n \/\/ We found a new best value lets report it.\n \/\/ and store that value\n mBest = mCurrent;\n mBestValue = mEvaluationValue;\n\n mContinue = mpOptProblem->setSolution(mBestValue, mBest);\n\n \/\/ We found a new best value lets report it.\n mpParentTask->output(COutputInterface::DURING);\n }\n\n#endif \/\/ XXXX\n\n if (mLogVerbosity > 0)\n mMethodLog.enterLogEntry(\n COptLogEntry(\n \"Solution parameters outside of the boundaries. Repeating calculations from current border position (\"\n + std::to_string(repeat) + \")\")\n );\n }\n\n if (mLogVerbosity > 0)\n mMethodLog.enterLogEntry(COptLogEntry(\"Algorithm finished.\"));\n\n return true;\n}\n\nbool COptMethodTruncatedNewton::initialize()\n{\n cleanup();\n\n if (!COptMethod::initialize()) return false;\n\n mVariableSize = (C_INT) mpOptItem->size();\n mCurrent.resize(mVariableSize);\n mBest.resize(mVariableSize);\n\n mContinue = true;\n mBestValue = std::numeric_limits<C_FLOAT64>::infinity();\n mGradient.resize(mVariableSize);\n\n return true;\n}\n\nbool COptMethodTruncatedNewton::cleanup()\n{\n return true;\n}\n\n\/\/ callback function, evaluate the value of the objective function and its gradient\n\/\/(by finite differences), translated by f2c, edited by Pedro and then modified for COPASI by Joseph\nC_INT COptMethodTruncatedNewton::sFun(C_INT *n, C_FLOAT64 *x, C_FLOAT64 *f, C_FLOAT64 *g)\n{\n C_INT i;\n\n \/\/ set the parameter values\n for (i = 0; i < *n; i++)\n *mContainerVariables[i] = (x[i]);\n\n \/\/carry out the function evaluation\n *f = evaluate();\n\n \/\/ Check whether we improved\n if (mEvaluationValue < mBestValue)\n {\n \/\/ We found a new best value lets report it.\n \/\/ and store that value\n for (i = 0; i < *n; i++)\n mBest[i] = x[i];\n\n mBestValue = mEvaluationValue;\n mContinue = mpOptProblem->setSolution(mBestValue, mBest);\n\n \/\/ We found a new best value lets report it.\n mpParentTask->output(COutputInterface::DURING);\n }\n\n \/\/ Calculate the gradient\n for (i = 0; i < *n && mContinue; i++)\n {\n if (x[i] != 0.0)\n {\n *mContainerVariables[i] = (x[i] * 1.001);\n g[i] = (evaluate() - *f) \/ (x[i] * 0.001);\n }\n\n else\n {\n *mContainerVariables[i] = (1e-7);\n g[i] = (evaluate() - *f) \/ 1e-7;\n }\n\n *mContainerVariables[i] = (x[i]);\n }\n\n if (!mContinue)\n throw bool(mContinue);\n\n return 0;\n}\n\nconst C_FLOAT64 & COptMethodTruncatedNewton::evaluate()\n{\n \/\/ We do not need to check whether the parametric constraints are fulfilled\n \/\/ since the parameters are created within the bounds.\n mContinue = mpOptProblem->calculate();\n mEvaluationValue = mpOptProblem->getCalculateValue();\n\n \/\/ when we leave the either the parameter or functional domain\n \/\/ we penalize the objective value by forcing it to be larger\n \/\/ than the best value recorded so far.\n if (mEvaluationValue < mBestValue &&\n (!mpOptProblem->checkParametricConstraints() ||\n !mpOptProblem->checkFunctionalConstraints()))\n mEvaluationValue = mBestValue + mBestValue - mEvaluationValue;\n\n return mEvaluationValue;\n}\n\nunsigned C_INT32 COptMethodTruncatedNewton::getMaxLogVerbosity() const\n{\n return 1;\n}\n<commit_msg>pass pointer to log to deeper functions for debug output<commit_after>\/\/ Copyright (C) 2017 - 2018 by Pedro Mendes, Virginia Tech Intellectual\n\/\/ Properties, Inc., University of Heidelberg, and University of\n\/\/ of Connecticut School of Medicine.\n\/\/ All rights reserved.\n\n\/\/ Copyright (C) 2010 - 2016 by Pedro Mendes, Virginia Tech Intellectual\n\/\/ Properties, Inc., University of Heidelberg, and The University\n\/\/ of Manchester.\n\/\/ All rights reserved.\n\n\/\/ Copyright (C) 2008 - 2009 by Pedro Mendes, Virginia Tech Intellectual\n\/\/ Properties, Inc., EML Research, gGmbH, University of Heidelberg,\n\/\/ and The University of Manchester.\n\/\/ All rights reserved.\n\n\/\/ Copyright (C) 2007 by Pedro Mendes, Virginia Tech Intellectual\n\/\/ Properties, Inc. and EML Research, gGmbH.\n\/\/ All rights reserved.\n\n#include \"copasi.h\"\n\n#include \"COptMethodTruncatedNewton.h\"\n#include \"COptProblem.h\"\n#include \"COptItem.h\"\n#include \"COptTask.h\"\n\n#include \"parameterFitting\/CFitProblem.h\"\n#include \"copasi\/core\/CDataObjectReference.h\"\n\nCOptMethodTruncatedNewton::COptMethodTruncatedNewton(const CDataContainer * pParent,\n const CTaskEnum::Method & methodType,\n const CTaskEnum::Task & taskType):\n COptMethod(pParent, methodType, taskType),\n mpTruncatedNewton(new FTruncatedNewtonTemplate<COptMethodTruncatedNewton>(this, &COptMethodTruncatedNewton::sFun)),\n mpCTruncatedNewton(new CTruncatedNewton())\n{\n initObjects();\n}\n\nCOptMethodTruncatedNewton::COptMethodTruncatedNewton(const COptMethodTruncatedNewton & src,\n const CDataContainer * pParent):\n COptMethod(src, pParent),\n mpTruncatedNewton(new FTruncatedNewtonTemplate<COptMethodTruncatedNewton>(this, &COptMethodTruncatedNewton::sFun)),\n mpCTruncatedNewton(new CTruncatedNewton())\n{initObjects();}\n\nCOptMethodTruncatedNewton::~COptMethodTruncatedNewton()\n{\n pdelete(mpTruncatedNewton);\n pdelete(mpCTruncatedNewton);\n cleanup();\n}\n\nvoid COptMethodTruncatedNewton::initObjects()\n{\n addObjectReference(\"Current Iteration\", mIteration, CDataObject::ValueInt);\n}\n\nbool COptMethodTruncatedNewton::optimise()\n{\n if (!initialize()) return false;\n\n if (mLogVerbosity > 0)\n mMethodLog.enterLogEntry(\n COptLogEntry(\n \"Truncated Newton algorithm started\",\n \"For more information about this method see: http:\/\/copasi.org\/Support\/User_Manual\/Methods\/Optimization_Methods\/Truncated_Newton\/\"\n )\n );\n\n C_FLOAT64 fest;\n C_INT lw, ierror = 0;\n lw = 14 * mVariableSize;\n\n CVector< C_FLOAT64 > up(mVariableSize);\n CVector< C_FLOAT64 > low(mVariableSize);\n CVector< C_INT > iPivot(mVariableSize);\n CVector< C_FLOAT64 > dwork(lw);\n\n up = std::numeric_limits< C_FLOAT64 >::max();\n low = - std::numeric_limits< C_FLOAT64 >::max();\n\n \/\/ initial point is the first guess but we have to make sure that\n \/\/ we are within the parameter domain\n C_INT i, repeat;\n bool pointInParameterDomain = true;\n\n for (i = 0; i < mVariableSize; i++)\n {\n const COptItem & OptItem = *(*mpOptItem)[i];\n\n \/\/ :TODO: In COPASI the bounds are not necessarry fixed.\n \/\/ Since evaluate checks for boundaries and constraints this is not\n \/\/ needed. The question remaining is how does tnbc_ handle unconstraint problems?\n \/\/ low[i] = *OptItem.getLowerBoundValue();\n \/\/ up[i] = *OptItem.getUpperBoundValue();\n\n mCurrent[i] = OptItem.getStartValue();\n\n switch (OptItem.checkConstraint(mCurrent[i]))\n {\n case - 1:\n mCurrent[i] = *OptItem.getLowerBoundValue();\n pointInParameterDomain = false;\n break;\n\n case 1:\n mCurrent[i] = *OptItem.getUpperBoundValue();\n pointInParameterDomain = false;\n break;\n\n case 0:\n break;\n }\n\n \/\/ set the value\n *mContainerVariables[i] = (mCurrent[i]);\n }\n\n if (!pointInParameterDomain && (mLogVerbosity > 0))\n mMethodLog.enterLogEntry(COptLogEntry(\"Initial point outside parameter domain.\"));\n\n \/\/ Report the first value as the current best\n mBestValue = evaluate();\n mBest = mCurrent;\n mContinue = mpOptProblem->setSolution(mBestValue, mBest);\n\n repeat = 0;\n\n \/\/tnbc_ wants a signed int for loglevel...\n C_INT msglvl;\n msglvl = (int) mLogVerbosity;\n\n while (repeat < 10 && mContinue)\n {\n repeat++;\n\n \/\/ estimate minimum is 1\/10 initial function value\n fest = (1 - pow(0.9, (C_FLOAT64) repeat)) * mEvaluationValue;\n ierror = 0;\n\n \/\/ minimise\n try\n {\n mpCTruncatedNewton->tnbc_(&ierror,\n &mVariableSize,\n mCurrent.array(),\n &fest,\n mGradient.array(),\n dwork.array(),\n &lw,\n mpTruncatedNewton,\n low.array(),\n up.array(),\n iPivot.array(),\n &msglvl,\n &mMethodLog);\n\n mEvaluationValue = fest;\n }\n\n \/\/ This signals that the user opted to interrupt\n catch (bool)\n {\n break;\n }\n\n if (ierror < 0)\n fatalError(); \/\/ Invalid parameter values.\n\n \/\/ The way the method is currently implemented may lead to parameters just outside the boundaries.\n \/\/ We need to check whether the current value is within the boundaries or whether the corrected\n \/\/ leads to an improved solution.\n\n bool withinBounds = true;\n\n for (i = 0; i < mVariableSize; i++)\n {\n const COptItem & OptItem = *(*mpOptItem)[i];\n\n \/\/force it to be within the bounds\n switch (OptItem.checkConstraint(mCurrent[i]))\n {\n case - 1:\n withinBounds = false;\n mCurrent[i] = *OptItem.getLowerBoundValue();\n break;\n\n case 1:\n withinBounds = false;\n mCurrent[i] = *OptItem.getUpperBoundValue();\n break;\n\n case 0:\n break;\n }\n\n *mContainerVariables[i] = (mCurrent[i]);\n }\n\n evaluate();\n\n \/\/ Is the corrected value better than solution?\n if (mEvaluationValue < mBestValue)\n {\n \/\/ We found a new best value lets report it.\n \/\/ and store that value\n mBest = mCurrent;\n mBestValue = mEvaluationValue;\n\n mContinue = mpOptProblem->setSolution(mBestValue, mBest);\n\n \/\/ We found a new best value lets report it.\n mpParentTask->output(COutputInterface::DURING);\n }\n\n \/\/ We found a solution\n if (withinBounds)\n break;\n\n \/\/ Choosing another starting point will be left to the user\n#ifdef XXXX\n\n \/\/ Try another starting point\n for (i = 0; i < mVariableSize; i++)\n {\n mCurrent[i] *= 1.2;\n const COptItem & OptItem = *(*mpOptItem)[i];\n\n \/\/force it to be within the bounds\n switch (OptItem.checkConstraint(mCurrent[i]))\n {\n case - 1:\n mCurrent[i] = *OptItem.getLowerBoundValue();\n break;\n\n case 1:\n mCurrent[i] = *OptItem.getUpperBoundValue();\n break;\n\n case 0:\n break;\n }\n\n *mContainerVariables[i] = (mCurrent[i]);\n }\n\n evaluate();\n\n \/\/ Check whether we improved\n if (mEvaluationValue < mBestValue)\n {\n \/\/ We found a new best value lets report it.\n \/\/ and store that value\n mBest = mCurrent;\n mBestValue = mEvaluationValue;\n\n mContinue = mpOptProblem->setSolution(mBestValue, mBest);\n\n \/\/ We found a new best value lets report it.\n mpParentTask->output(COutputInterface::DURING);\n }\n\n#endif \/\/ XXXX\n\n if (mLogVerbosity > 0)\n mMethodLog.enterLogEntry(\n COptLogEntry(\n \"Solution parameters outside of the boundaries. Repeating calculations from current border position (\"\n + std::to_string(repeat) + \")\")\n );\n }\n\n if (mLogVerbosity > 0)\n mMethodLog.enterLogEntry(COptLogEntry(\"Algorithm finished.\"));\n\n return true;\n}\n\nbool COptMethodTruncatedNewton::initialize()\n{\n cleanup();\n\n if (!COptMethod::initialize()) return false;\n\n mVariableSize = (C_INT) mpOptItem->size();\n mCurrent.resize(mVariableSize);\n mBest.resize(mVariableSize);\n\n mContinue = true;\n mBestValue = std::numeric_limits<C_FLOAT64>::infinity();\n mGradient.resize(mVariableSize);\n\n return true;\n}\n\nbool COptMethodTruncatedNewton::cleanup()\n{\n return true;\n}\n\n\/\/ callback function, evaluate the value of the objective function and its gradient\n\/\/(by finite differences), translated by f2c, edited by Pedro and then modified for COPASI by Joseph\nC_INT COptMethodTruncatedNewton::sFun(C_INT *n, C_FLOAT64 *x, C_FLOAT64 *f, C_FLOAT64 *g)\n{\n C_INT i;\n\n \/\/ set the parameter values\n for (i = 0; i < *n; i++)\n *mContainerVariables[i] = (x[i]);\n\n \/\/carry out the function evaluation\n *f = evaluate();\n\n \/\/ Check whether we improved\n if (mEvaluationValue < mBestValue)\n {\n \/\/ We found a new best value lets report it.\n \/\/ and store that value\n for (i = 0; i < *n; i++)\n mBest[i] = x[i];\n\n mBestValue = mEvaluationValue;\n mContinue = mpOptProblem->setSolution(mBestValue, mBest);\n\n \/\/ We found a new best value lets report it.\n mpParentTask->output(COutputInterface::DURING);\n }\n\n \/\/ Calculate the gradient\n for (i = 0; i < *n && mContinue; i++)\n {\n if (x[i] != 0.0)\n {\n *mContainerVariables[i] = (x[i] * 1.001);\n g[i] = (evaluate() - *f) \/ (x[i] * 0.001);\n }\n\n else\n {\n *mContainerVariables[i] = (1e-7);\n g[i] = (evaluate() - *f) \/ 1e-7;\n }\n\n *mContainerVariables[i] = (x[i]);\n }\n\n if (!mContinue)\n throw bool(mContinue);\n\n return 0;\n}\n\nconst C_FLOAT64 & COptMethodTruncatedNewton::evaluate()\n{\n \/\/ We do not need to check whether the parametric constraints are fulfilled\n \/\/ since the parameters are created within the bounds.\n mContinue = mpOptProblem->calculate();\n mEvaluationValue = mpOptProblem->getCalculateValue();\n\n \/\/ when we leave the either the parameter or functional domain\n \/\/ we penalize the objective value by forcing it to be larger\n \/\/ than the best value recorded so far.\n if (mEvaluationValue < mBestValue &&\n (!mpOptProblem->checkParametricConstraints() ||\n !mpOptProblem->checkFunctionalConstraints()))\n mEvaluationValue = mBestValue + mBestValue - mEvaluationValue;\n\n return mEvaluationValue;\n}\n\nunsigned C_INT32 COptMethodTruncatedNewton::getMaxLogVerbosity() const\n{\n return 1;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: zoom.hxx,v $\n *\n * $Revision: 1.5 $\n *\n * last change: $Author: kz $ $Date: 2008-03-07 15:17:12 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n#ifndef _SVX_ZOOM_HXX\n#define _SVX_ZOOM_HXX\n\n\/\/ include ---------------------------------------------------------------\n\n#include <layout\/layout.hxx>\n#ifndef _BASEDLGS_HXX \/\/autogen wg. SfxModalDialog\n#include <sfx2\/basedlgs.hxx>\n#endif\n#ifndef _SV_BUTTON_HXX \/\/autogen wg. Radio-\/OK-\/Cancel-\/HelpButton\n#include <vcl\/button.hxx>\n#endif\n#ifndef _SV_FIELD_HXX \/\/autogen wg. MetricField\n#include <vcl\/field.hxx>\n#endif\n#ifndef _SV_FIXED_HXX\n#include <vcl\/fixed.hxx>\n#endif\n\n\/\/ define ----------------------------------------------------------------\n\/* CHINA001\n#define ZOOMBTN_OPTIMAL ((USHORT)0x0001)\n#define ZOOMBTN_PAGEWIDTH ((USHORT)0x0002)\n#define ZOOMBTN_WHOLEPAGE ((USHORT)0x0004)\n*\/\n#ifndef _SVX_ZOOM_HXX\n#include \"zoom_def.hxx\"\n#endif\n\/\/ class SvxZoomDialog ---------------------------------------------------\n\/*\n {k:\\svx\\prototyp\\dialog\\zoom.bmp}\n\n [Beschreibung]\n Mit diesem Dialog wird ein Zoom-Faktor eingestellt.\n\n [Items]\n SvxZoomItem <SID_ATTR_ZOOM>\n*\/\n\n#include <layout\/layout-pre.hxx>\n\nclass SvxZoomDialog : public SfxModalDialog\n{\nprivate:\n FixedLine aZoomFl;\n RadioButton aOptimalBtn;\n RadioButton aWholePageBtn;\n RadioButton aPageWidthBtn;\n RadioButton a100Btn;\n RadioButton aUserBtn;\n MetricField aUserEdit;\n\n FixedLine aViewLayoutFl;\n RadioButton aAutomaticBtn;\n RadioButton aSingleBtn;\n RadioButton aColumnsBtn;\n MetricField aColumnsEdit;\n CheckBox aBookModeChk;\n\n FixedLine aBottomFl;\n OKButton aOKBtn;\n CancelButton aCancelBtn;\n HelpButton aHelpBtn;\n\n const SfxItemSet& rSet;\n SfxItemSet* pOutSet;\n BOOL bModified;\n\n#ifdef _SVX_ZOOM_CXX\n DECL_LINK( UserHdl, RadioButton* );\n DECL_LINK( SpinHdl, MetricField* );\n DECL_LINK( ViewLayoutUserHdl, RadioButton* );\n DECL_LINK( ViewLayoutSpinHdl, MetricField* );\n DECL_LINK( ViewLayoutCheckHdl, CheckBox* );\n DECL_LINK( OKHdl, Button* );\n#endif\n\npublic:\n SvxZoomDialog( Window* pParent, const SfxItemSet& rCoreSet );\n ~SvxZoomDialog();\n\n static USHORT* GetRanges();\n const SfxItemSet* GetOutputItemSet() const { return pOutSet; }\n\n USHORT GetFactor() const;\n void SetFactor( USHORT nNewFactor, USHORT nBtnId = 0 );\n\n void SetButtonText( USHORT nBtnId, const String& aNewTxt );\n void HideButton( USHORT nBtnId );\n void SetLimits( USHORT nMin, USHORT nMax );\n void SetSpinSize( USHORT nNewSpin );\n};\n\n#include <layout\/layout-post.hxx>\n\n#endif\n\n<commit_msg>INTEGRATION: CWS changefileheader (1.5.50); FILE MERGED 2008\/04\/01 15:50:36 thb 1.5.50.2: #i85898# Stripping all external header guards 2008\/03\/31 14:20:10 rt 1.5.50.1: #i87441# Change license header to LPGL v3.<commit_after>\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2008 by Sun Microsystems, Inc.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: zoom.hxx,v $\n * $Revision: 1.6 $\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * <http:\/\/www.openoffice.org\/license.html>\n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n#ifndef _SVX_ZOOM_HXX\n#define _SVX_ZOOM_HXX\n\n\/\/ include ---------------------------------------------------------------\n\n#include <layout\/layout.hxx>\n#include <sfx2\/basedlgs.hxx>\n#ifndef _SV_BUTTON_HXX \/\/autogen wg. Radio-\/OK-\/Cancel-\/HelpButton\n#include <vcl\/button.hxx>\n#endif\n#include <vcl\/field.hxx>\n#include <vcl\/fixed.hxx>\n\n\/\/ define ----------------------------------------------------------------\n\/* CHINA001\n#define ZOOMBTN_OPTIMAL ((USHORT)0x0001)\n#define ZOOMBTN_PAGEWIDTH ((USHORT)0x0002)\n#define ZOOMBTN_WHOLEPAGE ((USHORT)0x0004)\n*\/\n#ifndef _SVX_ZOOM_HXX\n#include \"zoom_def.hxx\"\n#endif\n\/\/ class SvxZoomDialog ---------------------------------------------------\n\/*\n {k:\\svx\\prototyp\\dialog\\zoom.bmp}\n\n [Beschreibung]\n Mit diesem Dialog wird ein Zoom-Faktor eingestellt.\n\n [Items]\n SvxZoomItem <SID_ATTR_ZOOM>\n*\/\n\n#include <layout\/layout-pre.hxx>\n\nclass SvxZoomDialog : public SfxModalDialog\n{\nprivate:\n FixedLine aZoomFl;\n RadioButton aOptimalBtn;\n RadioButton aWholePageBtn;\n RadioButton aPageWidthBtn;\n RadioButton a100Btn;\n RadioButton aUserBtn;\n MetricField aUserEdit;\n\n FixedLine aViewLayoutFl;\n RadioButton aAutomaticBtn;\n RadioButton aSingleBtn;\n RadioButton aColumnsBtn;\n MetricField aColumnsEdit;\n CheckBox aBookModeChk;\n\n FixedLine aBottomFl;\n OKButton aOKBtn;\n CancelButton aCancelBtn;\n HelpButton aHelpBtn;\n\n const SfxItemSet& rSet;\n SfxItemSet* pOutSet;\n BOOL bModified;\n\n#ifdef _SVX_ZOOM_CXX\n DECL_LINK( UserHdl, RadioButton* );\n DECL_LINK( SpinHdl, MetricField* );\n DECL_LINK( ViewLayoutUserHdl, RadioButton* );\n DECL_LINK( ViewLayoutSpinHdl, MetricField* );\n DECL_LINK( ViewLayoutCheckHdl, CheckBox* );\n DECL_LINK( OKHdl, Button* );\n#endif\n\npublic:\n SvxZoomDialog( Window* pParent, const SfxItemSet& rCoreSet );\n ~SvxZoomDialog();\n\n static USHORT* GetRanges();\n const SfxItemSet* GetOutputItemSet() const { return pOutSet; }\n\n USHORT GetFactor() const;\n void SetFactor( USHORT nNewFactor, USHORT nBtnId = 0 );\n\n void SetButtonText( USHORT nBtnId, const String& aNewTxt );\n void HideButton( USHORT nBtnId );\n void SetLimits( USHORT nMin, USHORT nMax );\n void SetSpinSize( USHORT nNewSpin );\n};\n\n#include <layout\/layout-post.hxx>\n\n#endif\n\n<|endoftext|>"} {"text":"<commit_before>#include <platforms\/posix\/stacktrace.h>\n\n#if defined(COFFEE_UNIXPLAT)\n\n#include <peripherals\/base.h>\n#include <peripherals\/libc\/output_ops.h>\n#include <peripherals\/semantic\/chunk.h>\n#include <peripherals\/semantic\/ptr_wrap.h>\n#include <peripherals\/stl\/regex.h>\n#include <peripherals\/stl\/string_ops.h>\n\n#include <cxxabi.h> \/\/Demangling function names\n\n#if defined(COFFEE_USE_UNWIND)\n#define UNW_LOCAL_ONLY\n#include <libunwind.h> \/\/For retrieving the callstack\n#endif\n\n#if defined(COFFEE_GLIBC_STACKTRACE)\n#include <execinfo.h>\n#endif\n\nnamespace platform {\nnamespace env {\nnamespace posix {\n\nusing namespace ::stl_types;\nusing namespace ::semantic;\n\nCString Stacktracer::DemangleSymbol(const char* sym)\n{\n#ifndef COFFEE_LOWFAT\n i32 stat = 0;\n\n Ptr<char, ptr_opts::managed_ptr> symbol =\n abi::__cxa_demangle(sym, nullptr, nullptr, &stat);\n\n if(stat == 0)\n {\n CString outSymbol = symbol.ptr;\n return outSymbol;\n } else\n#endif\n return sym;\n}\n\nStacktracerDef::Stacktrace Stacktracer::GetRawStackframes(\n C_UNUSED(u32 start), C_UNUSED(i32 length))\n{\n Stacktrace t;\n#ifndef COFFEE_LOWFAT\n#if defined(COFFEE_USE_UNWIND)\n if(!unwind_context)\n {\n unwind_context = new unw_context_t;\n unw_getcontext(unwind_context);\n }\n\n unw_cursor_t cursor;\n unw_init_local(&cursor, unwind_context);\n\n for(uint32 i = 0; i < start; i++)\n unw_step(&cursor);\n\n CString temp_buf;\n temp_buf.resize(256);\n\n int32 depth = 0;\n\n while(unw_step(&cursor) > 0)\n {\n unw_word_t offset, pc;\n unw_get_reg(&cursor, UNW_REG_IP, &pc);\n if(pc == 0)\n break;\n if(unw_get_proc_name(\n &cursor,\n &temp_buf[0],\n temp_buf.size() * sizeof(char),\n &offset) == 0)\n {\n CString fname = DemangleSymbol(temp_buf);\n t.push_back(fname);\n }\n\n depth++;\n if(length != (-1) && depth == length)\n break;\n }\n#endif\n#endif\n return t;\n}\n\nCString Stacktracer::GetStackframeName(u32 depth)\n{\n#ifndef COFFEE_LOWFAT\n Stacktrace trace = GetRawStackframes(depth, 2);\n if(!trace.size())\n return \"???\";\n return CString(trace[0]);\n#else\n return {};\n#endif\n}\n\nCString Stacktracer::GetStackFuncName(u32 depth)\n{\n#ifndef COFFEE_LOWFAT\n static bool rgx_compiled;\n static regex::Pattern rgx;\n\n CString frame = GetStackframeName(depth + 1);\n\n if(!rgx_compiled)\n {\n rgx = regex::compile_pattern(\"^(.*)\\\\(.*$\");\n }\n\n Vector<CString> result;\n\n if(!regex::match(rgx, frame, result))\n return frame;\n\n return result[1];\n#else\n return {};\n#endif\n}\n\n} \/\/ namespace posix\n\n#if defined(COFFEE_GLIBC_STACKTRACE)\nnamespace glibc {\n\nSTATICINLINE CString DemangleBacktrace(char* sym)\n{\n CString sym_ = sym;\n#if defined(COFFEE_LINUX) || defined(COFFEE_APPLE)\n \/* glibc's format *\/\n auto sym_end = sym_.rfind('+');\n\n#if defined(COFFEE_APPLE)\n \/* macOS format looks like this:\n * 0 GLeamBaseTest_RHI 0x000000010030c86a SIGNATURE + 0\n * What we want ~~~~~~~~~^\n * We fix this by adjusting the beginning index\n *\/\n auto sym_begin = sym_.rfind(' ', sym_end);\n sym_begin = sym_.rfind(' ', sym_begin - 1);\n\n sym_end -= 1;\n#else\n auto sym_begin = sym_.rfind('(', sym_end);\n#endif\n\n if(sym_end != CString::npos && sym_begin != CString::npos)\n {\n auto sym_length = sym_end - sym_begin - 1;\n auto sym_target = sym_.substr(sym_begin + 1, sym_length);\n\n sym_ = str::replace::str(\n sym_, sym_target, Stacktracer::DemangleSymbol(sym_target));\n }\n#endif\n\n#if defined(COFFEE_APPLE)\n auto const is_space = [](CString::value_type v) {\n return !std::isspace(v);\n };\n\n auto crop = sym_.find(' ');\n\n auto crop_it = std::find_if(sym_.begin() + crop, sym_.end(), is_space);\n\n auto cursor_start = crop_it - sym_.begin();\n auto cursor_end = sym_.find(' ', cursor_start);\n\n auto module = sym_.substr(cursor_start, cursor_end - cursor_start);\n\n crop_it = std::find_if(sym_.begin() + cursor_end, sym_.end(), is_space);\n cursor_start = crop_it - sym_.begin();\n cursor_end = sym_.find(' ', cursor_start);\n\n auto address = sym_.substr(cursor_start, cursor_end - cursor_start);\n\n crop_it = std::find_if(sym_.begin() + cursor_end, sym_.end(), is_space);\n cursor_start = crop_it - sym_.begin();\n cursor_end = sym_.find(' ', cursor_start);\n\n auto func = sym_.substr(cursor_start, CString::npos);\n\n return module + \"(\" + func + \") [\" + address + \"]\";\n#else\n return sym_;\n#endif\n}\n\nstatic void DefaultedPrint(\n typing::logging::LogInterfaceBasic logger, CString const& line)\n{\n using semantic::debug::Severity;\n using namespace libc::io;\n\n logger(io_handles::err, line, Severity::Critical, 1, 0);\n}\n\nvoid Stacktracer::Backtrace(typing::logging::LogInterfaceBasic log)\n{\n static constexpr szptr MAX_CONTEXT = 21;\n static void* tracestore[MAX_CONTEXT];\n\n for(szptr i=0; i<MAX_CONTEXT; i++)\n tracestore[i] = nullptr;\n\n auto num = backtrace(tracestore, MAX_CONTEXT);\n\n if(!log)\n {\n backtrace_symbols(tracestore, num);\n return;\n }\n\n auto syms = backtrace_symbols(tracestore, num);\n if(syms && num)\n {\n DefaultedPrint(log, \"dumping stacktrace:\");\n for(auto i : Range<>(C_FCAST<szptr>(num)))\n {\n if(syms[i])\n {\n DefaultedPrint(log, \" >> \" + DemangleBacktrace(syms[i]));\n } else\n DefaultedPrint(\n log, \" >> \" + Stacktracer::DemangleSymbol(syms[i]));\n }\n }\n}\n\nvoid Stacktracer::ExceptionStacktrace(\n const ExceptionPtr& exc_ptr, typing::logging::LogInterfaceBasic log)\n{\n try\n {\n if(exc_ptr)\n std::rethrow_exception(exc_ptr);\n } catch(std::exception& e)\n {\n if(libc::io::terminal::interactive())\n DefaultedPrint(\n log,\n str::transform::multiply(\n '-', libc::io::terminal::size().first));\n DefaultedPrint(log, \"exception encountered:\");\n DefaultedPrint(\n log,\n \" >> \" + Stacktracer::DemangleSymbol(typeid(e).name()) + \": \" +\n e.what());\n Backtrace(log);\n }\n}\n\nCString Stacktracer::GetFuncName_Internal(void* funcPtr)\n{\n auto funcName = backtrace_symbols(&funcPtr, 1);\n\n if(!funcName)\n return {};\n\n CString out = DemangleBacktrace(funcName[0]);\n free(funcName);\n\n return out;\n}\n\n} \/\/ namespace glibc\n#endif\n\n} \/\/ namespace env\n} \/\/ namespace platform\n\n#endif\n<commit_msg> - Free backtrace memory on exit<commit_after>#include <platforms\/posix\/stacktrace.h>\n\n#if defined(COFFEE_UNIXPLAT)\n\n#include <peripherals\/base.h>\n#include <peripherals\/libc\/output_ops.h>\n#include <peripherals\/semantic\/chunk.h>\n#include <peripherals\/semantic\/ptr_wrap.h>\n#include <peripherals\/stl\/regex.h>\n#include <peripherals\/stl\/string_ops.h>\n\n#include <cxxabi.h> \/\/Demangling function names\n\n#if defined(COFFEE_USE_UNWIND)\n#define UNW_LOCAL_ONLY\n#include <libunwind.h> \/\/For retrieving the callstack\n#endif\n\n#if defined(COFFEE_GLIBC_STACKTRACE)\n#include <execinfo.h>\n#include <peripherals\/libc\/signals.h>\n#endif\n\nnamespace platform {\nnamespace env {\nnamespace posix {\n\nusing namespace ::stl_types;\nusing namespace ::semantic;\n\nCString Stacktracer::DemangleSymbol(const char* sym)\n{\n#ifndef COFFEE_LOWFAT\n i32 stat = 0;\n\n Ptr<char, ptr_opts::managed_ptr> symbol =\n abi::__cxa_demangle(sym, nullptr, nullptr, &stat);\n\n if(stat == 0)\n {\n CString outSymbol = symbol.ptr;\n return outSymbol;\n } else\n#endif\n return sym;\n}\n\nStacktracerDef::Stacktrace Stacktracer::GetRawStackframes(\n C_UNUSED(u32 start), C_UNUSED(i32 length))\n{\n Stacktrace t;\n#ifndef COFFEE_LOWFAT\n#if defined(COFFEE_USE_UNWIND)\n if(!unwind_context)\n {\n unwind_context = new unw_context_t;\n unw_getcontext(unwind_context);\n }\n\n unw_cursor_t cursor;\n unw_init_local(&cursor, unwind_context);\n\n for(uint32 i = 0; i < start; i++)\n unw_step(&cursor);\n\n CString temp_buf;\n temp_buf.resize(256);\n\n int32 depth = 0;\n\n while(unw_step(&cursor) > 0)\n {\n unw_word_t offset, pc;\n unw_get_reg(&cursor, UNW_REG_IP, &pc);\n if(pc == 0)\n break;\n if(unw_get_proc_name(\n &cursor,\n &temp_buf[0],\n temp_buf.size() * sizeof(char),\n &offset) == 0)\n {\n CString fname = DemangleSymbol(temp_buf);\n t.push_back(fname);\n }\n\n depth++;\n if(length != (-1) && depth == length)\n break;\n }\n#endif\n#endif\n return t;\n}\n\nCString Stacktracer::GetStackframeName(u32 depth)\n{\n#ifndef COFFEE_LOWFAT\n Stacktrace trace = GetRawStackframes(depth, 2);\n if(!trace.size())\n return \"???\";\n return CString(trace[0]);\n#else\n return {};\n#endif\n}\n\nCString Stacktracer::GetStackFuncName(u32 depth)\n{\n#ifndef COFFEE_LOWFAT\n static bool rgx_compiled;\n static regex::Pattern rgx;\n\n CString frame = GetStackframeName(depth + 1);\n\n if(!rgx_compiled)\n {\n rgx = regex::compile_pattern(\"^(.*)\\\\(.*$\");\n }\n\n Vector<CString> result;\n\n if(!regex::match(rgx, frame, result))\n return frame;\n\n return result[1];\n#else\n return {};\n#endif\n}\n\n} \/\/ namespace posix\n\n#if defined(COFFEE_GLIBC_STACKTRACE)\nnamespace glibc {\n\nSTATICINLINE CString DemangleBacktrace(char* sym)\n{\n CString sym_ = sym;\n#if defined(COFFEE_LINUX) || defined(COFFEE_APPLE)\n \/* glibc's format *\/\n auto sym_end = sym_.rfind('+');\n\n#if defined(COFFEE_APPLE)\n \/* macOS format looks like this:\n * 0 GLeamBaseTest_RHI 0x000000010030c86a SIGNATURE + 0\n * What we want ~~~~~~~~~^\n * We fix this by adjusting the beginning index\n *\/\n auto sym_begin = sym_.rfind(' ', sym_end);\n sym_begin = sym_.rfind(' ', sym_begin - 1);\n\n sym_end -= 1;\n#else\n auto sym_begin = sym_.rfind('(', sym_end);\n#endif\n\n if(sym_end != CString::npos && sym_begin != CString::npos)\n {\n auto sym_length = sym_end - sym_begin - 1;\n auto sym_target = sym_.substr(sym_begin + 1, sym_length);\n\n sym_ = str::replace::str(\n sym_, sym_target, Stacktracer::DemangleSymbol(sym_target));\n }\n#endif\n\n#if defined(COFFEE_APPLE)\n auto const is_space = [](CString::value_type v) {\n return !std::isspace(v);\n };\n\n auto crop = sym_.find(' ');\n\n auto crop_it = std::find_if(sym_.begin() + crop, sym_.end(), is_space);\n\n auto cursor_start = crop_it - sym_.begin();\n auto cursor_end = sym_.find(' ', cursor_start);\n\n auto module = sym_.substr(cursor_start, cursor_end - cursor_start);\n\n crop_it = std::find_if(sym_.begin() + cursor_end, sym_.end(), is_space);\n cursor_start = crop_it - sym_.begin();\n cursor_end = sym_.find(' ', cursor_start);\n\n auto address = sym_.substr(cursor_start, cursor_end - cursor_start);\n\n crop_it = std::find_if(sym_.begin() + cursor_end, sym_.end(), is_space);\n cursor_start = crop_it - sym_.begin();\n cursor_end = sym_.find(' ', cursor_start);\n\n auto func = sym_.substr(cursor_start, CString::npos);\n\n return module + \"(\" + func + \") [\" + address + \"]\";\n#else\n return sym_;\n#endif\n}\n\nstatic void DefaultedPrint(\n typing::logging::LogInterfaceBasic logger, CString const& line)\n{\n using semantic::debug::Severity;\n using namespace libc::io;\n\n logger(io_handles::err, line, Severity::Critical, 1, 0);\n}\n\nCOFFEE_DISABLE_ASAN void Stacktracer::Backtrace(typing::logging::LogInterfaceBasic log)\n{\n static constexpr szptr MAX_CONTEXT = 21;\n static void* tracestore[MAX_CONTEXT];\n\n for(szptr i=0; i<MAX_CONTEXT; i++)\n tracestore[i] = nullptr;\n\n auto num = backtrace(tracestore, MAX_CONTEXT);\n\n if(!log)\n {\n backtrace_symbols(tracestore, num);\n libc::signal::register_atexit([]()\n {\n ::free(backtrace_symbols(tracestore, MAX_CONTEXT));\n });\n return;\n }\n\n auto syms = backtrace_symbols(tracestore, num);\n if(syms && num)\n {\n DefaultedPrint(log, \"dumping stacktrace:\");\n for(auto i : Range<>(C_FCAST<szptr>(num)))\n {\n if(syms[i])\n {\n DefaultedPrint(log, \" >> \" + DemangleBacktrace(syms[i]));\n } else\n DefaultedPrint(\n log, \" >> \" + Stacktracer::DemangleSymbol(syms[i]));\n }\n }\n}\n\nvoid Stacktracer::ExceptionStacktrace(\n const ExceptionPtr& exc_ptr, typing::logging::LogInterfaceBasic log)\n{\n try\n {\n if(exc_ptr)\n std::rethrow_exception(exc_ptr);\n } catch(std::exception& e)\n {\n if(libc::io::terminal::interactive())\n DefaultedPrint(\n log,\n str::transform::multiply(\n '-', libc::io::terminal::size().first));\n DefaultedPrint(log, \"exception encountered:\");\n DefaultedPrint(\n log,\n \" >> \" + Stacktracer::DemangleSymbol(typeid(e).name()) + \": \" +\n e.what());\n Backtrace(log);\n }\n}\n\nCString Stacktracer::GetFuncName_Internal(void* funcPtr)\n{\n auto funcName = backtrace_symbols(&funcPtr, 1);\n\n if(!funcName)\n return {};\n\n CString out = DemangleBacktrace(funcName[0]);\n free(funcName);\n\n return out;\n}\n\n} \/\/ namespace glibc\n#endif\n\n} \/\/ namespace env\n} \/\/ namespace platform\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>#include <gtest\/gtest.h>\n#include <stan\/math\/prim.hpp>\n#include <vector>\n\nTEST(MathPrimScalFun, grad2F1_negative_z) {\n double a1 = 3.70975;\n double a2 = 1;\n double b1 = 2.70975;\n double z = -0.2;\n\n double grad_a1;\n double grad_a2;\n double grad_b1;\n stan::math::grad_2F1(grad_a1, grad_a2, grad_b1, a1, a2, b1, z);\n EXPECT_NEAR(-0.0488658806159776, grad_a1, 1e-9);\n EXPECT_NEAR(-0.193844936204681, grad_a2, 1e-9);\n EXPECT_NEAR(0.0677809985598383, grad_b1, 1e-9);\n}\n\nTEST(MathPrimScalFun, grad2F1_zero_z) {\n double a1 = 3.70975;\n double a2 = 1;\n double b1 = 2.70975;\n double z = 0;\n\n double grad_a1;\n double grad_a2;\n double grad_b1;\n stan::math::grad_2F1(grad_a1, grad_a2, grad_b1, a1, a2, b1, z);\n EXPECT_FLOAT_EQ(0, grad_a1);\n EXPECT_FLOAT_EQ(0, grad_a2);\n EXPECT_FLOAT_EQ(0, grad_b1);\n}\n\nTEST(MathPrimScalFun, grad2F1_1) {\n double a1 = 1;\n double a2 = 1;\n double b1 = 1;\n double z = 0.6;\n\n double grad_a1;\n double grad_a2;\n double grad_b1;\n stan::math::grad_2F1(grad_a1, grad_a2, grad_b1, a1, a2, b1, z);\n EXPECT_NEAR(2.290726829685388, grad_a1, 1e-9);\n EXPECT_NEAR(2.290726829685388, grad_a2, 1e-9);\n EXPECT_NEAR(-2.290726829685388, grad_b1, 1e-9);\n}\n\nTEST(MathPrimScalFun, grad2F1_2) {\n double a1 = 1;\n double a2 = 31;\n double b1 = 41;\n double z = 1;\n\n double grad_a1;\n double grad_a2;\n double grad_b1;\n stan::math::grad_2F1(grad_a1, grad_a2, grad_b1, a1, a2, b1, z, 1e-11);\n EXPECT_NEAR(6.825270649241036, grad_a1, 1e-8);\n EXPECT_NEAR(0.4938271604938271, grad_a2, 1e-8);\n EXPECT_NEAR(-0.382716049382716, grad_b1, 1e-8);\n}\n\nTEST(MathPrimScalFun, grad2F1_3) {\n double a1 = 1;\n double a2 = -2.1;\n double b1 = 41;\n double z = 1;\n\n double grad_a1;\n double grad_a2;\n double grad_b1;\n stan::math::grad_2F1(grad_a1, grad_a2, grad_b1, a1, a2, b1, z);\n EXPECT_NEAR(-0.04921317604093563, grad_a1, 1e-8);\n EXPECT_NEAR(0.02256814168279349, grad_a2, 1e-8);\n EXPECT_NEAR(0.00118482743834665, grad_b1, 1e-8);\n}\n\nTEST(MathPrimScalFun, grad2F1_4) {\n double a1 = 1;\n double a2 = 12;\n double b1 = 10;\n double z = 1;\n\n double grad_a1;\n double grad_a2;\n double grad_b1;\n EXPECT_THROW(stan::math::grad_2F1(grad_a1, grad_a2, grad_b1, a1, a2, b1, z),\n std::domain_error);\n}\n\nTEST(MathPrimScalFun, grad2F1_5) {\n double a1 = 1;\n double a2 = 12;\n double b1 = 20;\n double z = 1.2;\n\n double grad_a1;\n double grad_a2;\n double grad_b1;\n EXPECT_THROW(stan::math::grad_2F1(grad_a1, grad_a2, grad_b1, a1, a2, b1, z),\n std::domain_error);\n}\n\nTEST(MathPrimScalFun, grad2F1_6) {\n double a1 = 1;\n double a2 = -0.5;\n double b1 = 10.6;\n double z = 0.3;\n\n double grad_a1;\n double grad_a2;\n double grad_b1;\n stan::math::grad_2F1(grad_a1, grad_a2, grad_b1, a1, a2, b1, z);\n EXPECT_NEAR(-0.01443822031245647, grad_a1, 1e-8);\n EXPECT_NEAR(0.02829710651967078, grad_a2, 1e-8);\n EXPECT_NEAR(0.00136986255602642, grad_b1, 1e-8);\n}\n\nTEST(MathPrimScalFun, grad2F1_7) {\n double a1 = 1;\n double a2 = -0.5;\n double b1 = 10;\n double z = 0.3;\n\n double grad_a1;\n double grad_a2;\n double grad_b1;\n stan::math::grad_2F1(grad_a1, grad_a2, grad_b1, a1, a2, b1, z);\n EXPECT_NEAR(-0.0153218866216130, grad_a1, 1e-8);\n EXPECT_NEAR(0.02999436412836072, grad_a2, 1e-8);\n EXPECT_NEAR(0.0015413242328729, grad_b1, 1e-8);\n}\n\nTEST(MathPrimScalFun, grad2F1_8) {\n double a1 = -.5;\n double a2 = -4.5;\n double b1 = 11;\n double z = 0.3;\n\n double grad_a1;\n double grad_a2;\n double grad_b1;\n stan::math::grad_2F1(grad_a1, grad_a2, grad_b1, a1, a2, b1, z);\n EXPECT_NEAR(-0.1227022810085707, grad_a1, 1e-8);\n EXPECT_NEAR(-0.01298849638043795, grad_a2, 1e-8);\n EXPECT_NEAR(-0.0053540982315572, grad_b1, 1e-8);\n}\n\nTEST(MathPrimScalFun, grad2F1_9) {\n double a1 = -.5;\n double a2 = -4.5;\n double b1 = -3.2;\n double z = 0.9;\n\n double grad_a1;\n double grad_a2;\n double grad_b1;\n stan::math::grad_2F1(grad_a1, grad_a2, grad_b1, a1, a2, b1, z);\n EXPECT_NEAR(0.85880025358111, grad_a1, 1e-8);\n EXPECT_NEAR(0.4677704416159314, grad_a2, 1e-8);\n EXPECT_NEAR(-4.19010422485256, grad_b1, 1e-8);\n}\n\nTEST(MathPrimScalFun, grad2F1_10) {\n double a1 = 2;\n double a2 = 1;\n double b1 = 2;\n double z = 0.4;\n\n double grad_a1;\n double grad_a2;\n double grad_b1;\n stan::math::grad_2F1(grad_a1, grad_a2, grad_b1, a1, a2, b1, z);\n EXPECT_NEAR(0.4617734323582945, grad_a1, 1e-8);\n EXPECT_NEAR(0.851376039609984, grad_a2, 1e-8);\n EXPECT_NEAR(-0.4617734323582945, grad_b1, 1e-8);\n}\n\nTEST(MathPrimScalFun, grad2F1_11) {\n double a1 = 3.70975;\n double a2 = 1;\n double b1 = 2.70975;\n double z = 0.999696;\n\n double grad_a1;\n double grad_a2;\n double grad_b1;\n stan::math::grad_2F1(grad_a1, grad_a2, grad_b1, a1, a2, b1, z);\n\n EXPECT_NEAR(29369830.002773938200417693317785, grad_a1,\n 1e-1); \/\/ reference: discrete diff in mathematica\n EXPECT_NEAR(36347869.41885337, grad_a2, 1e-1);\n EXPECT_NEAR(-30843032.10697079073015067426929807, grad_b1,\n 1e-1); \/\/ reference: discrete diff in mathematica\n}\n<commit_msg>Update prim tests<commit_after>#include <gtest\/gtest.h>\n#include <stan\/math\/prim.hpp>\n#include <vector>\n\nTEST(MathPrimScalFun, grad2F1_negative_z) {\n double a1 = 3.70975;\n double a2 = 1;\n double b1 = 2.70975;\n double z = -0.2;\n\n double grad_a1;\n double grad_a2;\n double grad_b1;\n double grad_z;\n stan::math::grad_2F1(grad_a1, grad_a2, grad_b1, grad_z, a1, a2, b1, z);\n EXPECT_NEAR(-0.0488658806159776, grad_a1, 1e-9);\n EXPECT_NEAR(-0.193844936204681, grad_a2, 1e-9);\n EXPECT_NEAR(0.0677809985598383, grad_b1, 1e-9);\n}\n\nTEST(MathPrimScalFun, grad2F1_zero_z) {\n double a1 = 3.70975;\n double a2 = 1;\n double b1 = 2.70975;\n double z = 0;\n\n double grad_a1;\n double grad_a2;\n double grad_b1;\n double grad_z;\n stan::math::grad_2F1(grad_a1, grad_a2, grad_b1, grad_z, a1, a2, b1, z);\n EXPECT_FLOAT_EQ(0, grad_a1);\n EXPECT_FLOAT_EQ(0, grad_a2);\n EXPECT_FLOAT_EQ(0, grad_b1);\n}\n\nTEST(MathPrimScalFun, grad2F1_1) {\n double a1 = 1;\n double a2 = 1;\n double b1 = 1;\n double z = 0.6;\n\n double grad_a1;\n double grad_a2;\n double grad_b1;\n double grad_z;\n stan::math::grad_2F1(grad_a1, grad_a2, grad_b1, grad_z, a1, a2, b1, z);\n EXPECT_NEAR(2.290726829685388, grad_a1, 1e-9);\n EXPECT_NEAR(2.290726829685388, grad_a2, 1e-9);\n EXPECT_NEAR(-2.290726829685388, grad_b1, 1e-9);\n}\n\nTEST(MathPrimScalFun, grad2F1_2) {\n double a1 = 1;\n double a2 = 31;\n double b1 = 41;\n double z = 1;\n\n double grad_a1;\n double grad_a2;\n double grad_b1;\n double grad_z;\n stan::math::grad_2F1(grad_a1, grad_a2, grad_b1, grad_z, a1, a2, b1, z);\n EXPECT_NEAR(6.825270649241036, grad_a1, 1e-8);\n EXPECT_NEAR(0.4938271604938271, grad_a2, 1e-8);\n EXPECT_NEAR(-0.382716049382716, grad_b1, 1e-8);\n}\n\nTEST(MathPrimScalFun, grad2F1_3) {\n double a1 = 1;\n double a2 = -2.1;\n double b1 = 41;\n double z = 1;\n\n double grad_a1;\n double grad_a2;\n double grad_b1;\n double grad_z;\n stan::math::grad_2F1(grad_a1, grad_a2, grad_b1, grad_z, a1, a2, b1, z);\n EXPECT_NEAR(-0.04921317604093563, grad_a1, 1e-8);\n EXPECT_NEAR(0.02256814168279349, grad_a2, 1e-8);\n EXPECT_NEAR(0.00118482743834665, grad_b1, 1e-8);\n}\n\nTEST(MathPrimScalFun, grad2F1_4) {\n double a1 = 1;\n double a2 = 12;\n double b1 = 10;\n double z = 1;\n\n double grad_a1;\n double grad_a2;\n double grad_b1;\n double grad_z;\n EXPECT_THROW(\n stan::math::grad_2F1(grad_a1, grad_a2, grad_b1, grad_z, a1, a2, b1, z),\n std::domain_error);\n}\n\nTEST(MathPrimScalFun, grad2F1_5) {\n double a1 = 1;\n double a2 = 12;\n double b1 = 20;\n double z = 1.2;\n\n double grad_a1;\n double grad_a2;\n double grad_b1;\n double grad_z;\n EXPECT_THROW(\n stan::math::grad_2F1(grad_a1, grad_a2, grad_b1, grad_z, a1, a2, b1, z),\n std::domain_error);\n}\n\nTEST(MathPrimScalFun, grad2F1_6) {\n double a1 = 1;\n double a2 = -0.5;\n double b1 = 10.6;\n double z = 0.3;\n\n double grad_a1;\n double grad_a2;\n double grad_b1;\n double grad_z;\n stan::math::grad_2F1(grad_a1, grad_a2, grad_b1, grad_z, a1, a2, b1, z);\n EXPECT_NEAR(-0.01443822031245647, grad_a1, 1e-8);\n EXPECT_NEAR(0.02829710651967078, grad_a2, 1e-8);\n EXPECT_NEAR(0.00136986255602642, grad_b1, 1e-8);\n}\n\nTEST(MathPrimScalFun, grad2F1_7) {\n double a1 = 1;\n double a2 = -0.5;\n double b1 = 10;\n double z = 0.3;\n\n double grad_a1;\n double grad_a2;\n double grad_b1;\n double grad_z;\n stan::math::grad_2F1(grad_a1, grad_a2, grad_b1, grad_z, a1, a2, b1, z);\n EXPECT_NEAR(-0.0153218866216130, grad_a1, 1e-8);\n EXPECT_NEAR(0.02999436412836072, grad_a2, 1e-8);\n EXPECT_NEAR(0.0015413242328729, grad_b1, 1e-8);\n}\n\nTEST(MathPrimScalFun, grad2F1_8) {\n double a1 = -.5;\n double a2 = -4.5;\n double b1 = 11;\n double z = 0.3;\n\n double grad_a1;\n double grad_a2;\n double grad_b1;\n double grad_z;\n stan::math::grad_2F1(grad_a1, grad_a2, grad_b1, grad_z, a1, a2, b1, z);\n EXPECT_NEAR(-0.1227022810085707, grad_a1, 1e-8);\n EXPECT_NEAR(-0.01298849638043795, grad_a2, 1e-8);\n EXPECT_NEAR(-0.0053540982315572, grad_b1, 1e-8);\n}\n\nTEST(MathPrimScalFun, grad2F1_9) {\n double a1 = -.5;\n double a2 = -4.5;\n double b1 = -3.2;\n double z = 0.9;\n\n double grad_a1;\n double grad_a2;\n double grad_b1;\n double grad_z;\n stan::math::grad_2F1(grad_a1, grad_a2, grad_b1, grad_z, a1, a2, b1, z);\n EXPECT_NEAR(0.85880025358111, grad_a1, 1e-8);\n EXPECT_NEAR(0.4677704416159314, grad_a2, 1e-8);\n EXPECT_NEAR(-4.19010422485256, grad_b1, 1e-8);\n}\n\nTEST(MathPrimScalFun, grad2F1_10) {\n double a1 = 2;\n double a2 = 1;\n double b1 = 2;\n double z = 0.4;\n\n double grad_a1;\n double grad_a2;\n double grad_b1;\n double grad_z;\n stan::math::grad_2F1(grad_a1, grad_a2, grad_b1, grad_z, a1, a2, b1, z);\n EXPECT_NEAR(0.4617734323582945, grad_a1, 1e-8);\n EXPECT_NEAR(0.851376039609984, grad_a2, 1e-8);\n EXPECT_NEAR(-0.4617734323582945, grad_b1, 1e-8);\n}\n\nTEST(MathPrimScalFun, grad2F1_11) {\n double a1 = 3.70975;\n double a2 = 1;\n double b1 = 2.70975;\n double z = 0.999696;\n\n double grad_a1;\n double grad_a2;\n double grad_b1;\n double grad_z;\n stan::math::grad_2F1(grad_a1, grad_a2, grad_b1, grad_z, a1, a2, b1, z);\n\n EXPECT_NEAR(29369830.002773938200417693317785, grad_a1,\n 1e-1); \/\/ reference: discrete diff in mathematica\n EXPECT_NEAR(36347869.41885337, grad_a2, 1e-1);\n EXPECT_NEAR(-30843032.10697079073015067426929807, grad_b1,\n 1e-1); \/\/ reference: discrete diff in mathematica\n}\n<|endoftext|>"} {"text":"<commit_before>#include <requests\/Context.hpp>\n#include <requests\/Utils.hpp>\n#include <requests\/Exception.hpp>\n\nusing namespace requests;\n\nContext::Context(IOService &service, const Url &url, Method method, const StringMap &data)\n : Context(service, url, method, data, UserCallback())\n{ \n} \n \nContext::Context(IOService &service, const Url &url, Method method, const StringMap &data, const UserCallback &callback)\n : sock_(service),\n url_(url),\n callback_(callback),\n method_(method)\n {\n std::ostream reqStream(&requestBuff_);\n\n if (method_ == Method::Get) \n {\n url_.addQueries(data);\n \n reqStream << \"GET \" << url_.pathAndQueries() << \" HTTP\/1.1\\r\\n\";\n reqStream << \"Host: \" << url_.host() << \"\\r\\n\";\n reqStream << \"Accept: *\/*\\r\\n\";\n reqStream << \"Connection: close\\r\\n\\r\\n\"; \n }\n else if (method_ == Method::Post)\n {\n auto requestBody = urlEncode(data);\n auto length = std::to_string(requestBody.size());\n \n reqStream << \"POST \" << url_.path() << \" HTTP\/1.1\\r\\n\";\n reqStream << \"Host: \" << url_.host() << \"\\r\\n\";\n reqStream << \"Accept: *\/*\\r\\n\";\n reqStream << \"Content-Type: application\/x-www-form-urlencoded\\r\\n\";\n reqStream << \"Content-Length: \" << length << \"\\r\\n\";\n reqStream << \"Connection: close\\r\\n\\r\\n\";\n\n reqStream << requestBody;\n }\n }\n<commit_msg>adjust style<commit_after>#include <requests\/Context.hpp>\n#include <requests\/Utils.hpp>\n#include <requests\/Exception.hpp>\n\nusing namespace requests;\n\nContext::Context(IOService &service, const Url &url, Method method, const StringMap &data)\n : Context(service, url, method, data, UserCallback())\n{ \n} \n \nContext::Context(IOService &service, const Url &url, Method method, const StringMap &data, const UserCallback &callback)\n : sock_(service),\n url_(url),\n callback_(callback),\n method_(method)\n{\n std::ostream reqStream(&requestBuff_);\n \n if (method_ == Method::Get) \n {\n url_.addQueries(data);\n \n reqStream << \"GET \" << url_.pathAndQueries() << \" HTTP\/1.1\\r\\n\";\n reqStream << \"Host: \" << url_.host() << \"\\r\\n\";\n reqStream << \"Accept: *\/*\\r\\n\";\n reqStream << \"Connection: close\\r\\n\\r\\n\"; \n }\n else if (method_ == Method::Post)\n {\n auto requestBody = urlEncode(data);\n auto length = std::to_string(requestBody.size());\n \n reqStream << \"POST \" << url_.path() << \" HTTP\/1.1\\r\\n\";\n reqStream << \"Host: \" << url_.host() << \"\\r\\n\";\n reqStream << \"Accept: *\/*\\r\\n\";\n reqStream << \"Content-Type: application\/x-www-form-urlencoded\\r\\n\";\n reqStream << \"Content-Length: \" << length << \"\\r\\n\";\n reqStream << \"Connection: close\\r\\n\\r\\n\";\n \n reqStream << requestBody;\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/* Copyright 2016 The TensorFlow Authors. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*\/\n\n#include \"tensorflow\/core\/common_runtime\/optimization_registry.h\"\n#include \"tensorflow\/core\/util\/dump_graph.h\"\n\nnamespace tensorflow {\n\n\/\/ static\nOptimizationPassRegistry* OptimizationPassRegistry::Global() {\n static OptimizationPassRegistry* global_optimization_registry =\n new OptimizationPassRegistry;\n return global_optimization_registry;\n}\n\nvoid OptimizationPassRegistry::Register(\n Grouping grouping, int phase, std::unique_ptr<GraphOptimizationPass> pass) {\n groups_[grouping][phase].push_back(std::move(pass));\n}\n\nStatus OptimizationPassRegistry::RunGrouping(\n Grouping grouping, const GraphOptimizationPassOptions& options) {\n auto group = groups_.find(grouping);\n if (group != groups_.end()) {\n for (auto& phase : group->second) {\n VLOG(1) << \"Running optimization phase \" << phase.first;\n for (auto& pass : phase.second) {\n VLOG(1) << \"Running optimization pass: \" << pass->name();\n Status s = pass->Run(options);\n if (!s.ok()) return s;\n if (VLOG_IS_ON(1)) {\n if (options.graph) {\n DumpGraphToFile(\n strings::StrCat(\n \"after_phase_\", phase.first, \"_\", pass->name(), \"_\",\n reinterpret_cast<uintptr_t>((*options.graph).get())),\n **options.graph, options.flib_def);\n }\n if (options.partition_graphs) {\n for (auto& part : *options.partition_graphs) {\n DumpGraphToFile(\n strings::StrCat(\n \"after_phase_\", phase.first, \"_\", pass->name(),\n \"_partition_\", part.first, \"_\",\n reinterpret_cast<uintptr_t>(part.second.get())),\n *part.second, options.flib_def);\n }\n }\n }\n }\n }\n }\n return Status::OK();\n}\n\nvoid OptimizationPassRegistry::LogGrouping(Grouping grouping, int vlog_level) {\n auto group = groups_.find(grouping);\n if (group != groups_.end()) {\n for (auto& phase : group->second) {\n for (auto& pass : phase.second) {\n VLOG(vlog_level) << \"Registered optimization pass grouping \" << grouping\n << \" phase \" << phase.first << \": \" << pass->name();\n }\n }\n }\n}\n\nvoid OptimizationPassRegistry::LogAllGroupings(int vlog_level) {\n for (auto group = groups_.begin(); group != groups_.end(); ++group) {\n LogGrouping(group->first, vlog_level);\n }\n}\n\n} \/\/ namespace tensorflow\n<commit_msg>[TF] Include group number in name of optimization_registry_dumps.<commit_after>\/* Copyright 2016 The TensorFlow Authors. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*\/\n\n#include \"tensorflow\/core\/common_runtime\/optimization_registry.h\"\n#include \"tensorflow\/core\/util\/dump_graph.h\"\n\nnamespace tensorflow {\n\n\/\/ static\nOptimizationPassRegistry* OptimizationPassRegistry::Global() {\n static OptimizationPassRegistry* global_optimization_registry =\n new OptimizationPassRegistry;\n return global_optimization_registry;\n}\n\nvoid OptimizationPassRegistry::Register(\n Grouping grouping, int phase, std::unique_ptr<GraphOptimizationPass> pass) {\n groups_[grouping][phase].push_back(std::move(pass));\n}\n\nStatus OptimizationPassRegistry::RunGrouping(\n Grouping grouping, const GraphOptimizationPassOptions& options) {\n auto group = groups_.find(grouping);\n if (group != groups_.end()) {\n for (auto& phase : group->second) {\n VLOG(1) << \"Running optimization phase \" << phase.first;\n for (auto& pass : phase.second) {\n VLOG(1) << \"Running optimization pass: \" << pass->name();\n Status s = pass->Run(options);\n if (!s.ok()) return s;\n if (VLOG_IS_ON(1)) {\n if (options.graph) {\n DumpGraphToFile(strings::StrCat(\"after_group_\", grouping, \"_phase_\",\n phase.first, \"_\", pass->name(), \"_\",\n reinterpret_cast<uintptr_t>(\n (*options.graph).get())),\n **options.graph, options.flib_def);\n }\n if (options.partition_graphs) {\n for (auto& part : *options.partition_graphs) {\n DumpGraphToFile(\n strings::StrCat(\n \"after_group_\", grouping, \"_phase_\", phase.first, \"_\",\n pass->name(), \"_partition_\", part.first, \"_\",\n reinterpret_cast<uintptr_t>(part.second.get())),\n *part.second, options.flib_def);\n }\n }\n }\n }\n }\n }\n return Status::OK();\n}\n\nvoid OptimizationPassRegistry::LogGrouping(Grouping grouping, int vlog_level) {\n auto group = groups_.find(grouping);\n if (group != groups_.end()) {\n for (auto& phase : group->second) {\n for (auto& pass : phase.second) {\n VLOG(vlog_level) << \"Registered optimization pass grouping \" << grouping\n << \" phase \" << phase.first << \": \" << pass->name();\n }\n }\n }\n}\n\nvoid OptimizationPassRegistry::LogAllGroupings(int vlog_level) {\n for (auto group = groups_.begin(); group != groups_.end(); ++group) {\n LogGrouping(group->first, vlog_level);\n }\n}\n\n} \/\/ namespace tensorflow\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2014 Open Source Robotics Foundation, Inc.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#ifndef RCLCPP__FUNCTION_TRAITS_HPP_\n#define RCLCPP__FUNCTION_TRAITS_HPP_\n\n#include <memory>\n#include <tuple>\n\nnamespace rclcpp\n{\n\nnamespace function_traits\n\n{\n\n\/* NOTE(esteve):\n * We support service callbacks that can optionally take the request id,\n * which should be possible with two overloaded create_service methods,\n * but unfortunately std::function's constructor on VS2015 is too greedy,\n * so we need a mechanism for checking the arity and the type of each argument\n * in a callback function.\n * See http:\/\/blogs.msdn.com\/b\/vcblog\/archive\/2015\/06\/19\/c-11-14-17-features-in-vs-2015-rtm.aspx\n *\/\n\n\/\/ Remove the first item in a tuple\ntemplate<typename T>\nstruct tuple_tail;\n\ntemplate<typename Head, typename ... Tail>\nstruct tuple_tail<std::tuple<Head, Tail ...>>\n{\n using type = std::tuple<Tail ...>;\n};\n\n\/\/ std::function\ntemplate<typename FunctionT>\nstruct function_traits\n{\n using arguments = typename tuple_tail<\n typename function_traits<decltype( & FunctionT::operator())>::arguments>::type;\n\n static constexpr std::size_t arity = std::tuple_size<arguments>::value;\n\n template<std::size_t N>\n using argument_type = typename std::tuple_element<N, arguments>::type;\n};\n\n\/\/ Free functions\ntemplate<typename ReturnTypeT, typename ... Args>\nstruct function_traits<ReturnTypeT(Args ...)>\n{\n using arguments = std::tuple<Args ...>;\n\n static constexpr std::size_t arity = std::tuple_size<arguments>::value;\n\n template<std::size_t N>\n using argument_type = typename std::tuple_element<N, arguments>::type;\n};\n\n\/\/ Function pointers\ntemplate<typename ReturnTypeT, typename ... Args>\nstruct function_traits<ReturnTypeT (*)(Args ...)>: function_traits<ReturnTypeT(Args ...)>\n{};\n\n\/\/ Lambdas\ntemplate<typename ClassT, typename ReturnTypeT, typename ... Args>\nstruct function_traits<ReturnTypeT (ClassT::*)(Args ...) const>\n : function_traits<ReturnTypeT(ClassT &, Args ...)>\n{};\n\ntemplate<typename FunctionT>\nstruct function_traits<FunctionT &>: function_traits<FunctionT>\n{};\n\ntemplate<typename FunctionT>\nstruct function_traits<FunctionT &&>: function_traits<FunctionT>\n{};\n\n\/* NOTE(esteve):\n * VS2015 does not support expression SFINAE, so we're using this template to evaluate\n * the arity of a function.\n *\/\ntemplate<std::size_t Arity, typename FunctorT>\nstruct arity_comparator : std::integral_constant<\n bool, (Arity == function_traits<FunctorT>::arity)>{};\n\ntemplate<typename FunctorT, typename ... Args>\nstruct check_arguments : std::is_same<\n typename function_traits<FunctorT>::arguments,\n std::tuple<Args ...>\n >\n{};\n\ntemplate<typename FunctorAT, typename FunctorBT>\nstruct same_arguments : std::is_same<\n typename function_traits<FunctorAT>::arguments,\n typename function_traits<FunctorBT>::arguments\n >\n{};\n\n} \/\/ namespace function_traits\n\n} \/\/ namespace rclcpp\n\n#endif \/\/ RCLCPP__FUNCTION_TRAITS_HPP_\n<commit_msg>Fix uncrustify warning<commit_after>\/\/ Copyright 2014 Open Source Robotics Foundation, Inc.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#ifndef RCLCPP__FUNCTION_TRAITS_HPP_\n#define RCLCPP__FUNCTION_TRAITS_HPP_\n\n#include <memory>\n#include <tuple>\n\nnamespace rclcpp\n{\n\nnamespace function_traits\n{\n\n\/* NOTE(esteve):\n * We support service callbacks that can optionally take the request id,\n * which should be possible with two overloaded create_service methods,\n * but unfortunately std::function's constructor on VS2015 is too greedy,\n * so we need a mechanism for checking the arity and the type of each argument\n * in a callback function.\n * See http:\/\/blogs.msdn.com\/b\/vcblog\/archive\/2015\/06\/19\/c-11-14-17-features-in-vs-2015-rtm.aspx\n *\/\n\n\/\/ Remove the first item in a tuple\ntemplate<typename T>\nstruct tuple_tail;\n\ntemplate<typename Head, typename ... Tail>\nstruct tuple_tail<std::tuple<Head, Tail ...>>\n{\n using type = std::tuple<Tail ...>;\n};\n\n\/\/ std::function\ntemplate<typename FunctionT>\nstruct function_traits\n{\n using arguments = typename tuple_tail<\n typename function_traits<decltype( & FunctionT::operator())>::arguments>::type;\n\n static constexpr std::size_t arity = std::tuple_size<arguments>::value;\n\n template<std::size_t N>\n using argument_type = typename std::tuple_element<N, arguments>::type;\n};\n\n\/\/ Free functions\ntemplate<typename ReturnTypeT, typename ... Args>\nstruct function_traits<ReturnTypeT(Args ...)>\n{\n using arguments = std::tuple<Args ...>;\n\n static constexpr std::size_t arity = std::tuple_size<arguments>::value;\n\n template<std::size_t N>\n using argument_type = typename std::tuple_element<N, arguments>::type;\n};\n\n\/\/ Function pointers\ntemplate<typename ReturnTypeT, typename ... Args>\nstruct function_traits<ReturnTypeT (*)(Args ...)>: function_traits<ReturnTypeT(Args ...)>\n{};\n\n\/\/ Lambdas\ntemplate<typename ClassT, typename ReturnTypeT, typename ... Args>\nstruct function_traits<ReturnTypeT (ClassT::*)(Args ...) const>\n : function_traits<ReturnTypeT(ClassT &, Args ...)>\n{};\n\ntemplate<typename FunctionT>\nstruct function_traits<FunctionT &>: function_traits<FunctionT>\n{};\n\ntemplate<typename FunctionT>\nstruct function_traits<FunctionT &&>: function_traits<FunctionT>\n{};\n\n\/* NOTE(esteve):\n * VS2015 does not support expression SFINAE, so we're using this template to evaluate\n * the arity of a function.\n *\/\ntemplate<std::size_t Arity, typename FunctorT>\nstruct arity_comparator : std::integral_constant<\n bool, (Arity == function_traits<FunctorT>::arity)>{};\n\ntemplate<typename FunctorT, typename ... Args>\nstruct check_arguments : std::is_same<\n typename function_traits<FunctorT>::arguments,\n std::tuple<Args ...>\n >\n{};\n\ntemplate<typename FunctorAT, typename FunctorBT>\nstruct same_arguments : std::is_same<\n typename function_traits<FunctorAT>::arguments,\n typename function_traits<FunctorBT>::arguments\n >\n{};\n\n} \/\/ namespace function_traits\n\n} \/\/ namespace rclcpp\n\n#endif \/\/ RCLCPP__FUNCTION_TRAITS_HPP_\n<|endoftext|>"} {"text":"<commit_before>#include <stan\/math\/rev.hpp>\n#include <test\/unit\/util.hpp>\n\n#include <gtest\/gtest.h>\n\nTEST(MathFunRev, to_vector_var_value) {\n constexpr Eigen::Index n = 100;\n Eigen::MatrixXd a_val = Eigen::MatrixXd::Random(n, n);\n stan::math::var_value<Eigen::MatrixXd> a(a_val);\n const auto& tmp = stan::math::to_vector(a);\n EXPECT_TRUE((stan::is_col_vector<decltype(tmp.val())>::value));\n EXPECT_MATRIX_EQ(tmp.val(), Eigen::Map<Eigen::VectorXd>(a_val.data(), a.rows() * a.cols()));\n}\n<commit_msg>adds check that adj is referenced w\/o a copy<commit_after>#include <stan\/math\/rev.hpp>\n#include <test\/unit\/util.hpp>\n\n#include <gtest\/gtest.h>\n\nTEST(MathFunRev, to_vector_var_value) {\n constexpr Eigen::Index n = 100;\n Eigen::MatrixXd a_val = Eigen::MatrixXd::Random(n, n);\n stan::math::var_value<Eigen::MatrixXd> a(a_val);\n auto&& tmp = stan::math::to_vector(a);\n EXPECT_TRUE((stan::is_col_vector<decltype(tmp.val())>::value));\n EXPECT_MATRIX_EQ(tmp.val(), Eigen::Map<Eigen::VectorXd>(a_val.data(), a.rows() * a.cols()));\n tmp.adj().array() += 1.0;\n EXPECT_MATRIX_EQ(tmp.adj(), Eigen::Map<Eigen::VectorXd>(a.vi_->adj_.data(), a.rows() * a.cols()));\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\nCopyright (C) 2016 iNuron NV\n\nThis file is part of Open vStorage Open Source Edition (OSE), as available from\n\n\n http:\/\/www.openvstorage.org and\n http:\/\/www.openvstorage.com.\n\nThis file is free software; you can redistribute it and\/or modify it\nunder the terms of the GNU Affero General Public License v3 (GNU AGPLv3)\nas published by the Free Software Foundation, in version 3 as it comes\nin the <LICENSE.txt> file of the Open vStorage OSE distribution.\n\nOpen vStorage is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY of any kind.\n*\/\n\n#include \"llio.h\"\n#include \"proxy_protocol.h\"\n#include \"snappy.h\"\n#include \"stuff.h\"\n#include <boost\/optional\/optional_io.hpp>\n\nnamespace alba {\nnamespace llio {\n\nusing namespace proxy_protocol;\ntemplate <> void from(message &m, EncodingScheme &es) {\n uint8_t version;\n from(m, version);\n if (version != 1) {\n throw deserialisation_exception(\"unexpected EncodingScheme version\");\n }\n\n from(m, es.k);\n from(m, es.m);\n from(m, es.w);\n}\n\nvoid from(message &m, std::unique_ptr<Compression> &p) {\n uint8_t type;\n from(m, type);\n Compression *r;\n switch (type) {\n case 1: {\n r = new NoCompression();\n }; break;\n case 2: {\n r = new SnappyCompression();\n }; break;\n case 3: {\n r = new BZip2Compression();\n }; break;\n case 4: {\n r = new TestCompression();\n }; break;\n default: {\n ALBA_LOG(WARNING, \"unknown compression type \" << (int)type);\n throw deserialisation_exception(\"unknown compression type\"); };\n }\n p.reset(r);\n}\n\nvoid from(message &m, chaining_mode_t &mode) {\n uint8_t type;\n from(m, type);\n switch (type) {\n case 1: {\n mode = chaining_mode_t::CBC;\n }; break;\n case 2: {\n mode = chaining_mode_t::CTR;\n }; break;\n default: { throw deserialisation_exception(\"unknown chaining_mode\"); };\n }\n}\n\nvoid from(message &m, key_length_t &kl) {\n uint8_t type;\n from(m, type);\n switch (type) {\n case 1: {\n kl = key_length_t::L256;\n } break;\n default: { throw deserialisation_exception(\"unknown key_length\"); };\n }\n}\n\nvoid from(message &m, proxy_protocol::algo_t &algo) {\n uint8_t type;\n from(m, type);\n switch (type) {\n case 1: {\n algo = proxy_protocol::algo_t::AES;\n }; break;\n default: { throw deserialisation_exception(\"unknown algo\"); };\n }\n}\nvoid from(message &m, AlgoWithKey &awk) {\n\n \/\/ ALBA_LOG(DEBUG, \"pos = \" << m.get_pos());\n \/\/ alba::stuff::dump_buffer(std::cout, m.current(16), 16);\n\n \/\/ AES CTR KEY_LENGTH x length of key key bytes\n \/\/ 01 02 01 01 20 00 00 00 fa c8\n from(m, awk.algo);\n from(m, awk.mode);\n from(m, awk.key_length);\n uint8_t x;\n from (m,x);\n from(m, awk.key);\n if (awk.key.size() != 32){\n throw deserialisation_exception(\"key length != 32\");\n }\n}\n\nvoid from(message &m, std::unique_ptr<EncryptInfo> &p) {\n uint8_t type;\n from(m, type);\n EncryptInfo *r;\n switch (type) {\n case 1: {\n r = new NoEncryption();\n }; break;\n case 2: {\n AlgoWithKey *awk = new AlgoWithKey();\n from(m, *awk);\n r = awk;\n }; break;\n default: {\n ALBA_LOG(WARNING, \"unknown encryption scheme: type=\" << type);\n throw deserialisation_exception(\"unknown encryption scheme)\"); };\n }\n p.reset(r);\n}\n\ntemplate <> void from(message &m, Manifest &mf) {\n uint8_t version;\n from(m, version);\n if (version != 1) {\n throw deserialisation_exception(\"unexpecteded Manifest version\");\n }\n\n std::string compressed;\n from(m, compressed);\n\n std::string real;\n snappy::Uncompress(compressed.data(), compressed.size(), &real);\n std::vector<char> buffer(real.begin(), real.end());\n message m2(buffer);\n from(m2, mf.name);\n from(m2, mf.object_id);\n\n std::vector<uint32_t> chunk_sizes;\n from(m2, mf.chunk_sizes);\n\n uint8_t version2;\n from(m2, version2);\n if (version2 != 1) {\n throw deserialisation_exception(\"unexpected version2\");\n }\n\n from(m2, mf.encoding_scheme);\n\n from(m2, mf.compression);\n\n from(m2, mf.encrypt_info);\n from(m2, mf.checksum);\n from(m2, mf.size);\n uint8_t layout_tag;\n from(m2, layout_tag);\n if (layout_tag != 1) {\n throw deserialisation_exception(\"unexpected layout tag\");\n }\n from(m2, mf.fragment_locations);\n\n uint8_t layout_tag2;\n from(m2, layout_tag2);\n if (layout_tag2 != 1) {\n throw deserialisation_exception(\"unexpected layout tag 2\");\n }\n\n \/\/ from(m2, mf.fragment_checksums); \/\/ TODO: how to this via the layout based\n \/\/ template ?\n \/\/ iso this:\n\n uint32_t n_chunks;\n from(m2, n_chunks);\n\n for (uint32_t i = 0; i < n_chunks; i++) {\n uint32_t n_fragments;\n from(m2, n_fragments);\n std::vector<std::shared_ptr<alba::Checksum>> chunk(n_fragments);\n for (int32_t f = n_fragments - 1; f >= 0; --f) {\n alba::Checksum *p;\n from(m2, p);\n std::shared_ptr<alba::Checksum> sp(p);\n chunk[f] = sp;\n };\n mf.fragment_checksums.push_back(chunk);\n }\n\n uint8_t layout_tag3;\n from(m2, layout_tag3);\n if (layout_tag3 != 1) {\n throw deserialisation_exception(\"unexpected layout tag 3\");\n }\n\n from(m2, mf.fragment_packed_sizes);\n\n from(m2, mf.version_id);\n from(m2, mf.max_disks_per_node);\n from(m2, mf.timestamp);\n}\n\ntemplate <>\nvoid from(message &m, ManifestWithNamespaceId &mfid) {\n from(m, (Manifest &)mfid);\n from(m, mfid.namespace_id);\n}\n}\n\nnamespace proxy_protocol {\n\nstd::ostream &operator<<(std::ostream &os, const EncodingScheme &scheme) {\n os << \"EncodingScheme{k=\" << scheme.k << \", m=\" << scheme.m\n << \", w=\" << (int)scheme.w << \"}\";\n\n return os;\n}\n\nstd::ostream &operator<<(std::ostream &os, const compressor_t &compressor) {\n switch (compressor) {\n case compressor_t::NO_COMPRESSION:\n os << \"NO_COMPRESSION\";\n break;\n case compressor_t::SNAPPY:\n os << \"SNAPPY\";\n break;\n case compressor_t::BZIP2:\n os << \"BZIP2\"; break;\n case compressor_t::TEST:\n os << \"TEST\"; break;\n };\n return os;\n}\n\nstd::ostream &operator <<(std::ostream &os, const algo_t &algo){\n switch(algo){\n case algo_t::AES:{\n os <<\"AES\";\n }\n };\n return os;\n}\n\nstd::ostream &operator <<(std::ostream &os, const chaining_mode_t &mode){\n switch(mode){\n case chaining_mode_t::CBC:{\n os <<\"CBC\";\n };break;\n case chaining_mode_t::CTR:{\n os << \"CTR\";\n };break;\n };\n return os;\n}\n\nstd::ostream &operator<<(std::ostream &os, const Compression &c) {\n c.print(os);\n return os;\n}\n\nstd::ostream &operator<<(std::ostream &os, const encryption_t &encryption) {\n switch (encryption) {\n case encryption_t::NO_ENCRYPTION:\n os << \"NO_ENCRYPTION\";\n break;\n case encryption_t::ALGO_WITH_KEY:\n os << \"ALGO_WITH_KEY\";\n default:\n os << \"?encryption?\";\n };\n return os;\n}\n\nstd::ostream &operator<<(std::ostream &os, const EncryptInfo &info) {\n info.print(os);\n return os;\n}\n\nstd::ostream &operator<<(std::ostream &os, const fragment_location_t &f) {\n os << \"(\" << f.first \/\/ boost knows how\n << \", \" << f.second << \")\";\n return os;\n}\n\nvoid dump_string(std::ostream &os, const std::string &s) {\n const char *bytes = s.data();\n const int size = s.size();\n stuff::dump_buffer(os, bytes, size);\n}\nstd::ostream &operator<<(std::ostream &os, const Manifest &mf) {\n using alba::stuff::operator<<;\n os << \"{\"\n << \"name = `\";\n dump_string(os, mf.name);\n os << \"`, \" << std::endl;\n os << \" object_id = `\";\n dump_string(os, mf.object_id);\n os << \"`, \" << std::endl\n\n << \" encoding_scheme = \" << mf.encoding_scheme << \",\" << std::endl\n << \" compression = \" << *mf.compression << \",\" << std::endl\n << \" encryptinfo = \" << *mf.encrypt_info << \",\" \/\/ dangerous\n << \" chunk_sizes = \" << mf.chunk_sizes << \",\" << std::endl\n << \" size = \" << mf.size << std::endl\n << std::endl\n << \" checksum= \" << *mf.checksum << \",\" << std::endl\n << \" fragment_locations = \" << mf.fragment_locations << \",\" << std::endl\n << \" fragment_checksums = \" << mf.fragment_checksums << \",\" << std::endl\n << \" fragment_packed_sizes = [\" << std::endl;\n\n for (const std::vector<uint32_t> &c : mf.fragment_packed_sizes) {\n os << c << \",\" << std::endl;\n }\n os << \" ], \";\n os << std::endl\n << \" version_id = \" << mf.version_id << \",\" << std::endl\n << \" timestamp = \" << mf.timestamp \/\/ TODO: decent formatting?\n << \"}\";\n return os;\n}\n\nstd::ostream &operator<<(std::ostream &os,\n const ManifestWithNamespaceId &mfid) {\n os << \"{\" << (Manifest &)mfid << \", namespace_id = \" << mfid.namespace_id\n << \"} \";\n return os;\n}\n}\n}\n<commit_msg>temporarily disabling AlgoWithKey<commit_after>\/*\nCopyright (C) 2016 iNuron NV\n\nThis file is part of Open vStorage Open Source Edition (OSE), as available from\n\n\n http:\/\/www.openvstorage.org and\n http:\/\/www.openvstorage.com.\n\nThis file is free software; you can redistribute it and\/or modify it\nunder the terms of the GNU Affero General Public License v3 (GNU AGPLv3)\nas published by the Free Software Foundation, in version 3 as it comes\nin the <LICENSE.txt> file of the Open vStorage OSE distribution.\n\nOpen vStorage is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY of any kind.\n*\/\n\n#include \"llio.h\"\n#include \"proxy_protocol.h\"\n#include \"snappy.h\"\n#include \"stuff.h\"\n#include <boost\/optional\/optional_io.hpp>\n\nnamespace alba {\nnamespace llio {\n\nusing namespace proxy_protocol;\ntemplate <> void from(message &m, EncodingScheme &es) {\n uint8_t version;\n from(m, version);\n if (version != 1) {\n throw deserialisation_exception(\"unexpected EncodingScheme version\");\n }\n\n from(m, es.k);\n from(m, es.m);\n from(m, es.w);\n}\n\nvoid from(message &m, std::unique_ptr<Compression> &p) {\n uint8_t type;\n from(m, type);\n Compression *r;\n switch (type) {\n case 1: {\n r = new NoCompression();\n }; break;\n case 2: {\n r = new SnappyCompression();\n }; break;\n case 3: {\n r = new BZip2Compression();\n }; break;\n case 4: {\n r = new TestCompression();\n }; break;\n default: {\n ALBA_LOG(WARNING, \"unknown compression type \" << (int)type);\n throw deserialisation_exception(\"unknown compression type\"); };\n }\n p.reset(r);\n}\n\nvoid from(message &m, chaining_mode_t &mode) {\n uint8_t type;\n from(m, type);\n switch (type) {\n case 1: {\n mode = chaining_mode_t::CBC;\n }; break;\n case 2: {\n mode = chaining_mode_t::CTR;\n }; break;\n default: { throw deserialisation_exception(\"unknown chaining_mode\"); };\n }\n}\n\nvoid from(message &m, key_length_t &kl) {\n uint8_t type;\n from(m, type);\n switch (type) {\n case 1: {\n kl = key_length_t::L256;\n } break;\n default: { throw deserialisation_exception(\"unknown key_length\"); };\n }\n}\n\nvoid from(message &m, proxy_protocol::algo_t &algo) {\n uint8_t type;\n from(m, type);\n switch (type) {\n case 1: {\n algo = proxy_protocol::algo_t::AES;\n }; break;\n default: { throw deserialisation_exception(\"unknown algo\"); };\n }\n}\nvoid from(message &m, AlgoWithKey &awk) {\n\n \/\/ ALBA_LOG(DEBUG, \"pos = \" << m.get_pos());\n \/\/ alba::stuff::dump_buffer(std::cout, m.current(16), 16);\n\n \/\/ AES CTR KEY_LENGTH x length of key key bytes\n \/\/ 01 02 01 01 20 00 00 00 fa c8\n from(m, awk.algo);\n from(m, awk.mode);\n from(m, awk.key_length);\n uint8_t x;\n from (m,x);\n from(m, awk.key);\n if (awk.key.size() != 32){\n throw deserialisation_exception(\"key length != 32\");\n }\n}\n\nvoid from(message &m, std::unique_ptr<EncryptInfo> &p) {\n uint8_t type;\n from(m, type);\n EncryptInfo *r;\n switch (type) {\n case 1: {\n r = new NoEncryption();\n }; break;\n case 2: {\n \/\/ comment for now until the serialisation has been cleared out\n\n \/* AlgoWithKey *awk = new AlgoWithKey();\n from(m, *awk);\n r = awk; *\/\n\n throw deserialisation_exception(\"AlgoWithKey not yet supported\");\n\n }; break;\n default: {\n ALBA_LOG(WARNING, \"unknown encryption scheme: type=\" << type);\n throw deserialisation_exception(\"unknown encryption scheme)\"); };\n }\n p.reset(r);\n}\n\ntemplate <> void from(message &m, Manifest &mf) {\n uint8_t version;\n from(m, version);\n if (version != 1) {\n throw deserialisation_exception(\"unexpecteded Manifest version\");\n }\n\n std::string compressed;\n from(m, compressed);\n\n std::string real;\n snappy::Uncompress(compressed.data(), compressed.size(), &real);\n std::vector<char> buffer(real.begin(), real.end());\n message m2(buffer);\n from(m2, mf.name);\n from(m2, mf.object_id);\n\n std::vector<uint32_t> chunk_sizes;\n from(m2, mf.chunk_sizes);\n\n uint8_t version2;\n from(m2, version2);\n if (version2 != 1) {\n throw deserialisation_exception(\"unexpected version2\");\n }\n\n from(m2, mf.encoding_scheme);\n\n from(m2, mf.compression);\n\n from(m2, mf.encrypt_info);\n from(m2, mf.checksum);\n from(m2, mf.size);\n uint8_t layout_tag;\n from(m2, layout_tag);\n if (layout_tag != 1) {\n throw deserialisation_exception(\"unexpected layout tag\");\n }\n from(m2, mf.fragment_locations);\n\n uint8_t layout_tag2;\n from(m2, layout_tag2);\n if (layout_tag2 != 1) {\n throw deserialisation_exception(\"unexpected layout tag 2\");\n }\n\n \/\/ from(m2, mf.fragment_checksums); \/\/ TODO: how to this via the layout based\n \/\/ template ?\n \/\/ iso this:\n\n uint32_t n_chunks;\n from(m2, n_chunks);\n\n for (uint32_t i = 0; i < n_chunks; i++) {\n uint32_t n_fragments;\n from(m2, n_fragments);\n std::vector<std::shared_ptr<alba::Checksum>> chunk(n_fragments);\n for (int32_t f = n_fragments - 1; f >= 0; --f) {\n alba::Checksum *p;\n from(m2, p);\n std::shared_ptr<alba::Checksum> sp(p);\n chunk[f] = sp;\n };\n mf.fragment_checksums.push_back(chunk);\n }\n\n uint8_t layout_tag3;\n from(m2, layout_tag3);\n if (layout_tag3 != 1) {\n throw deserialisation_exception(\"unexpected layout tag 3\");\n }\n\n from(m2, mf.fragment_packed_sizes);\n\n from(m2, mf.version_id);\n from(m2, mf.max_disks_per_node);\n from(m2, mf.timestamp);\n}\n\ntemplate <>\nvoid from(message &m, ManifestWithNamespaceId &mfid) {\n from(m, (Manifest &)mfid);\n from(m, mfid.namespace_id);\n}\n}\n\nnamespace proxy_protocol {\n\nstd::ostream &operator<<(std::ostream &os, const EncodingScheme &scheme) {\n os << \"EncodingScheme{k=\" << scheme.k << \", m=\" << scheme.m\n << \", w=\" << (int)scheme.w << \"}\";\n\n return os;\n}\n\nstd::ostream &operator<<(std::ostream &os, const compressor_t &compressor) {\n switch (compressor) {\n case compressor_t::NO_COMPRESSION:\n os << \"NO_COMPRESSION\";\n break;\n case compressor_t::SNAPPY:\n os << \"SNAPPY\";\n break;\n case compressor_t::BZIP2:\n os << \"BZIP2\"; break;\n case compressor_t::TEST:\n os << \"TEST\"; break;\n };\n return os;\n}\n\nstd::ostream &operator <<(std::ostream &os, const algo_t &algo){\n switch(algo){\n case algo_t::AES:{\n os <<\"AES\";\n }\n };\n return os;\n}\n\nstd::ostream &operator <<(std::ostream &os, const chaining_mode_t &mode){\n switch(mode){\n case chaining_mode_t::CBC:{\n os <<\"CBC\";\n };break;\n case chaining_mode_t::CTR:{\n os << \"CTR\";\n };break;\n };\n return os;\n}\n\nstd::ostream &operator<<(std::ostream &os, const Compression &c) {\n c.print(os);\n return os;\n}\n\nstd::ostream &operator<<(std::ostream &os, const encryption_t &encryption) {\n switch (encryption) {\n case encryption_t::NO_ENCRYPTION:\n os << \"NO_ENCRYPTION\";\n break;\n case encryption_t::ALGO_WITH_KEY:\n os << \"ALGO_WITH_KEY\";\n default:\n os << \"?encryption?\";\n };\n return os;\n}\n\nstd::ostream &operator<<(std::ostream &os, const EncryptInfo &info) {\n info.print(os);\n return os;\n}\n\nstd::ostream &operator<<(std::ostream &os, const fragment_location_t &f) {\n os << \"(\" << f.first \/\/ boost knows how\n << \", \" << f.second << \")\";\n return os;\n}\n\nvoid dump_string(std::ostream &os, const std::string &s) {\n const char *bytes = s.data();\n const int size = s.size();\n stuff::dump_buffer(os, bytes, size);\n}\nstd::ostream &operator<<(std::ostream &os, const Manifest &mf) {\n using alba::stuff::operator<<;\n os << \"{\"\n << \"name = `\";\n dump_string(os, mf.name);\n os << \"`, \" << std::endl;\n os << \" object_id = `\";\n dump_string(os, mf.object_id);\n os << \"`, \" << std::endl\n\n << \" encoding_scheme = \" << mf.encoding_scheme << \",\" << std::endl\n << \" compression = \" << *mf.compression << \",\" << std::endl\n << \" encryptinfo = \" << *mf.encrypt_info << \",\" \/\/ dangerous\n << \" chunk_sizes = \" << mf.chunk_sizes << \",\" << std::endl\n << \" size = \" << mf.size << std::endl\n << std::endl\n << \" checksum= \" << *mf.checksum << \",\" << std::endl\n << \" fragment_locations = \" << mf.fragment_locations << \",\" << std::endl\n << \" fragment_checksums = \" << mf.fragment_checksums << \",\" << std::endl\n << \" fragment_packed_sizes = [\" << std::endl;\n\n for (const std::vector<uint32_t> &c : mf.fragment_packed_sizes) {\n os << c << \",\" << std::endl;\n }\n os << \" ], \";\n os << std::endl\n << \" version_id = \" << mf.version_id << \",\" << std::endl\n << \" timestamp = \" << mf.timestamp \/\/ TODO: decent formatting?\n << \"}\";\n return os;\n}\n\nstd::ostream &operator<<(std::ostream &os,\n const ManifestWithNamespaceId &mfid) {\n os << \"{\" << (Manifest &)mfid << \", namespace_id = \" << mfid.namespace_id\n << \"} \";\n return os;\n}\n}\n}\n<|endoftext|>"} {"text":"<commit_before>\/* Sirikata\n * SpaceNodeConnection.cpp\n *\n * Copyright (c) 2009, Ewen Cheslack-Postava\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in\n * the documentation and\/or other materials provided with the\n * distribution.\n * * Neither the name of Sirikata nor the names of its contributors may\n * be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS\n * IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED\n * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A\n * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER\n * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include <sirikata\/oh\/SpaceNodeConnection.hpp>\n#include <sirikata\/core\/trace\/Trace.hpp>\n#include <sirikata\/core\/network\/StreamFactory.hpp>\n#include <sirikata\/core\/network\/Stream.hpp>\n#include <sirikata\/core\/util\/PluginManager.hpp>\n#include <sirikata\/core\/options\/CommonOptions.hpp>\n#include <sirikata\/core\/network\/IOStrandImpl.hpp>\n\nusing namespace Sirikata;\nusing namespace Sirikata::Network;\n\nnamespace Sirikata {\n\nSpaceNodeConnection::SpaceNodeConnection(ObjectHostContext* ctx, Network::IOStrand* ioStrand, TimeProfiler::Stage* handle_read_stage, OptionSet *streamOptions, const SpaceID& spaceid, ServerID sid, const Network::Address& addr, ConnectionEventCallback ccb, ReceiveCallback rcb)\n : mContext(ctx),\n mHandleReadStage(handle_read_stage),\n mSpace(spaceid),\n mServer(sid),\n socket(Sirikata::Network::StreamFactory::getSingleton().getConstructor(GetOptionValue<String>(\"ohstreamlib\"))(&ioStrand->service(),streamOptions)),\n mAddr(addr),\n mConnecting(false),\n receive_queue(GetOptionValue<int32>(\"object-host-receive-buffer\"), std::tr1::bind(&ObjectMessage::size, std::tr1::placeholders::_1)),\n mConnectCB(ccb),\n mReceiveCB(rcb)\n{\n static Sirikata::PluginManager sPluginManager;\n static int tcpSstLoaded=(sPluginManager.load(GetOptionValue<String>(\"ohstreamlib\")),0);\n}\n\nSpaceNodeConnection::~SpaceNodeConnection() {\n delete socket;\n}\n\nbool SpaceNodeConnection::push(const ObjectMessage& msg) {\n TIMESTAMP_START(tstamp, (&msg));\n\n std::string data;\n msg.serialize(&data);\n\n \/\/ Try to push to the network\n bool success = socket->send(\n \/\/Sirikata::MemoryReference(&(data[0]), data.size()),\n Sirikata::MemoryReference(data),\n Sirikata::Network::ReliableOrdered\n );\n if (success) {\n TIMESTAMP_END(tstamp, Trace::OH_HIT_NETWORK);\n }\n else {\n TIMESTAMP_END(tstamp, Trace::OH_DROPPED_AT_SEND);\n TRACE_DROP(OH_DROPPED_AT_SEND);\n }\n\n return success;\n}\n\nObjectMessage* SpaceNodeConnection::pull() {\n return receive_queue.pull();\n}\n\nbool SpaceNodeConnection::empty() {\n return receive_queue.empty();\n}\n\nvoid SpaceNodeConnection::handleRead(Chunk& chunk, const Sirikata::Network::Stream::PauseReceiveCallback& pause) {\n mHandleReadStage->started();\n\n \/\/ Parse\n ObjectMessage* msg = new ObjectMessage();\n bool parse_success = msg->ParseFromArray(&(*chunk.begin()), chunk.size());\n assert(parse_success == true);\n\n TIMESTAMP_START(tstamp, msg);\n\n \/\/ Mark as received\n TIMESTAMP_END(tstamp, Trace::OH_NET_RECEIVED);\n\n \/\/ NOTE: We can't record drops here or we incur a lot of overhead in parsing...\n bool pushed = receive_queue.push(msg);\n\n if (pushed) {\n \/\/ handleConnectionRead() could be called from any thread\/strand. Everything that is not\n \/\/ thread safe that could result from a new message needs to happen in the main strand,\n \/\/ so just post the whole handler there.\n if (receive_queue.wentNonEmpty())\n mReceiveCB(this);\n }\n else {\n TIMESTAMP_END(tstamp, Trace::OH_DROPPED_AT_RECEIVE_QUEUE);\n TRACE_DROP(OH_DROPPED_AT_RECEIVE_QUEUE);\n }\n\n mHandleReadStage->finished();\n\n \/\/ No matter what, we've \"handled\" the data, either for real or by dropping.\n}\n\nvoid SpaceNodeConnection::connect() {\n using std::tr1::placeholders::_1;\n using std::tr1::placeholders::_2;\n\n mConnecting = true;\n\n socket->connect(mAddr,\n &Sirikata::Network::Stream::ignoreSubstreamCallback,\n mContext->mainStrand->wrap( std::tr1::bind(&SpaceNodeConnection::handleConnectionEvent, this, _1, _2) ),\n std::tr1::bind(&SpaceNodeConnection::handleRead, this, _1, _2),\n &Sirikata::Network::Stream::ignoreReadySendCallback\n );\n}\n\nvoid SpaceNodeConnection::handleConnectionEvent(\n const Network::Stream::ConnectionStatus status,\n const std::string&reason)\n{\n mConnecting = false;\n\n invokeAndClearCallbacks( status == Network::Stream::Connected );\n mConnectCB(status, reason);\n}\n\nvoid SpaceNodeConnection::invokeAndClearCallbacks(bool connected) {\n SpaceNodeConnection* param = (connected ? this : NULL);\n for(ConnectionCallbackList::iterator it = mConnectCallbacks.begin(); it != mConnectCallbacks.end(); it++)\n (*it)(param);\n mConnectCallbacks.clear();\n}\n\nvoid SpaceNodeConnection::shutdown() {\n socket->close();\n}\n\n}\n<commit_msg>Fix leak of message when it is dropped.<commit_after>\/* Sirikata\n * SpaceNodeConnection.cpp\n *\n * Copyright (c) 2009, Ewen Cheslack-Postava\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in\n * the documentation and\/or other materials provided with the\n * distribution.\n * * Neither the name of Sirikata nor the names of its contributors may\n * be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS\n * IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED\n * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A\n * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER\n * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include <sirikata\/oh\/SpaceNodeConnection.hpp>\n#include <sirikata\/core\/trace\/Trace.hpp>\n#include <sirikata\/core\/network\/StreamFactory.hpp>\n#include <sirikata\/core\/network\/Stream.hpp>\n#include <sirikata\/core\/util\/PluginManager.hpp>\n#include <sirikata\/core\/options\/CommonOptions.hpp>\n#include <sirikata\/core\/network\/IOStrandImpl.hpp>\n\nusing namespace Sirikata;\nusing namespace Sirikata::Network;\n\nnamespace Sirikata {\n\nSpaceNodeConnection::SpaceNodeConnection(ObjectHostContext* ctx, Network::IOStrand* ioStrand, TimeProfiler::Stage* handle_read_stage, OptionSet *streamOptions, const SpaceID& spaceid, ServerID sid, const Network::Address& addr, ConnectionEventCallback ccb, ReceiveCallback rcb)\n : mContext(ctx),\n mHandleReadStage(handle_read_stage),\n mSpace(spaceid),\n mServer(sid),\n socket(Sirikata::Network::StreamFactory::getSingleton().getConstructor(GetOptionValue<String>(\"ohstreamlib\"))(&ioStrand->service(),streamOptions)),\n mAddr(addr),\n mConnecting(false),\n receive_queue(GetOptionValue<int32>(\"object-host-receive-buffer\"), std::tr1::bind(&ObjectMessage::size, std::tr1::placeholders::_1)),\n mConnectCB(ccb),\n mReceiveCB(rcb)\n{\n static Sirikata::PluginManager sPluginManager;\n static int tcpSstLoaded=(sPluginManager.load(GetOptionValue<String>(\"ohstreamlib\")),0);\n}\n\nSpaceNodeConnection::~SpaceNodeConnection() {\n delete socket;\n}\n\nbool SpaceNodeConnection::push(const ObjectMessage& msg) {\n TIMESTAMP_START(tstamp, (&msg));\n\n std::string data;\n msg.serialize(&data);\n\n \/\/ Try to push to the network\n bool success = socket->send(\n \/\/Sirikata::MemoryReference(&(data[0]), data.size()),\n Sirikata::MemoryReference(data),\n Sirikata::Network::ReliableOrdered\n );\n if (success) {\n TIMESTAMP_END(tstamp, Trace::OH_HIT_NETWORK);\n }\n else {\n TIMESTAMP_END(tstamp, Trace::OH_DROPPED_AT_SEND);\n TRACE_DROP(OH_DROPPED_AT_SEND);\n }\n\n return success;\n}\n\nObjectMessage* SpaceNodeConnection::pull() {\n return receive_queue.pull();\n}\n\nbool SpaceNodeConnection::empty() {\n return receive_queue.empty();\n}\n\nvoid SpaceNodeConnection::handleRead(Chunk& chunk, const Sirikata::Network::Stream::PauseReceiveCallback& pause) {\n mHandleReadStage->started();\n\n \/\/ Parse\n ObjectMessage* msg = new ObjectMessage();\n bool parse_success = msg->ParseFromArray(&(*chunk.begin()), chunk.size());\n assert(parse_success == true);\n\n TIMESTAMP_START(tstamp, msg);\n\n \/\/ Mark as received\n TIMESTAMP_END(tstamp, Trace::OH_NET_RECEIVED);\n\n \/\/ NOTE: We can't record drops here or we incur a lot of overhead in parsing...\n bool pushed = receive_queue.push(msg);\n\n if (pushed) {\n \/\/ handleConnectionRead() could be called from any thread\/strand. Everything that is not\n \/\/ thread safe that could result from a new message needs to happen in the main strand,\n \/\/ so just post the whole handler there.\n if (receive_queue.wentNonEmpty())\n mReceiveCB(this);\n }\n else {\n TIMESTAMP_END(tstamp, Trace::OH_DROPPED_AT_RECEIVE_QUEUE);\n TRACE_DROP(OH_DROPPED_AT_RECEIVE_QUEUE);\n delete msg;\n }\n\n mHandleReadStage->finished();\n\n \/\/ No matter what, we've \"handled\" the data, either for real or by dropping.\n}\n\nvoid SpaceNodeConnection::connect() {\n using std::tr1::placeholders::_1;\n using std::tr1::placeholders::_2;\n\n mConnecting = true;\n\n socket->connect(mAddr,\n &Sirikata::Network::Stream::ignoreSubstreamCallback,\n mContext->mainStrand->wrap( std::tr1::bind(&SpaceNodeConnection::handleConnectionEvent, this, _1, _2) ),\n std::tr1::bind(&SpaceNodeConnection::handleRead, this, _1, _2),\n &Sirikata::Network::Stream::ignoreReadySendCallback\n );\n}\n\nvoid SpaceNodeConnection::handleConnectionEvent(\n const Network::Stream::ConnectionStatus status,\n const std::string&reason)\n{\n mConnecting = false;\n\n invokeAndClearCallbacks( status == Network::Stream::Connected );\n mConnectCB(status, reason);\n}\n\nvoid SpaceNodeConnection::invokeAndClearCallbacks(bool connected) {\n SpaceNodeConnection* param = (connected ? this : NULL);\n for(ConnectionCallbackList::iterator it = mConnectCallbacks.begin(); it != mConnectCallbacks.end(); it++)\n (*it)(param);\n mConnectCallbacks.clear();\n}\n\nvoid SpaceNodeConnection::shutdown() {\n socket->close();\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ video-coder.cpp\n\/\/ ndnrtc\n\/\/\n\/\/ Copyright 2013 Regents of the University of California\n\/\/ For licensing details see the LICENSE file.\n\/\/\n\/\/ Author: Peter Gusev\n\/\/ Created: 8\/21\/13\n\/\/\n\n\/\/ #define USE_VP9\n\n#include <boost\/thread.hpp>\n#include <webrtc\/modules\/video_coding\/codecs\/vp8\/include\/vp8.h>\n#include <webrtc\/modules\/video_coding\/codecs\/vp9\/include\/vp9.h>\n#include <webrtc\/modules\/video_coding\/include\/video_coding.h>\n#include <webrtc\/modules\/video_coding\/include\/video_codec_interface.h>\n#include <webrtc\/modules\/video_coding\/codec_database.h>\n\n#include \"video-coder.hpp\"\n#include \"threading-capability.hpp\"\n\nusing namespace std;\nusing namespace ndnlog;\nusing namespace ndnrtc;\nusing namespace webrtc;\n\n\/\/ this class is needed in order to synchronously dispatch all\n\/\/ frame scaling (see - FrameScaler) calls on the same thread.\n\/\/ this is WebRTC requirement - all frame scaling calls must be\n\/\/ executed on the same thread throughout lifecycle\nclass ScalerThread : public ThreadingCapability\n{\npublic:\n static ScalerThread *getSharedInstance()\n {\n static ScalerThread scalerThread;\n return &scalerThread;\n }\n \n void perform(boost::function<void(void)> block)\n {\n performOnMyThread(block);\n }\n \nprivate:\n ScalerThread() { startMyThread(); }\n ~ScalerThread() { stopMyThread(); }\n};\n\n\/\/********************************************************************************\nchar* plotCodec(webrtc::VideoCodec codec)\n{\n static char msg[256];\n \n sprintf(msg, \"\\t\\tMax Framerate:\\t%d\\n \\\n \\tStart Bitrate:\\t%d\\n \\\n \\tMin Bitrate:\\t%d\\n \\\n \\tMax Bitrate:\\t%d\\n \\\n \\tTarget Bitrate:\\t%d\\n \\\n \\tWidth:\\t%d\\n \\\n \\tHeight:\\t%d\",\n codec.maxFramerate,\n codec.startBitrate,\n codec.minBitrate,\n codec.maxBitrate,\n codec.targetBitrate,\n codec.width,\n codec.height);\n \n return msg;\n}\n\n\/\/******************************************************************************\n#pragma mark - static\nwebrtc::VideoCodec VideoCoder::codecFromSettings(const VideoCoderParams &settings)\n{\n webrtc::VideoCodec codec;\n\n \/\/ setup default params first\n#ifdef USE_VP9\n webrtc::VCMCodecDataBase::Codec(webrtc::kVideoCodecVP9, &codec);\n#else\n webrtc::VCMCodecDataBase::Codec(webrtc::kVideoCodecVP8, &codec);\n#endif\n\n \/\/ dropping frames\n#ifdef USE_VP9\n codec.VP9()->resilience = 1;\n codec.VP9()->frameDroppingOn = settings.dropFramesOn_;\n codec.VP9()->keyFrameInterval = settings.gop_;\n#else\n codec.VP8()->resilience = kResilientStream;\n codec.VP8()->frameDroppingOn = settings.dropFramesOn_;\n codec.VP8()->keyFrameInterval = settings.gop_;\n#endif\n \n \/\/ customize parameteres if possible\n codec.maxFramerate = (int)settings.codecFrameRate_;\n codec.startBitrate = settings.startBitrate_;\n codec.minBitrate = 100;\n codec.maxBitrate = settings.maxBitrate_;\n codec.targetBitrate = settings.startBitrate_;\n codec.width = settings.encodeWidth_;\n codec.height = settings.encodeHeight_;\n \n return codec;\n}\n\n\/\/******************************************************************************\nFrameScaler::FrameScaler(unsigned int dstWidth, unsigned int dstHeight):\nsrcWidth_(0), srcHeight_(0), \ndstWidth_(dstWidth), dstHeight_(dstHeight)\n{\n initScaledFrame();\n}\n\nconst WebRtcVideoFrame&\nFrameScaler::operator()(const WebRtcVideoFrame& frame)\n{\n \/\/ if (srcWidth_ != frame.width() || srcHeight_ != frame.height())\n \/\/ {\n \/\/ srcWidth_ = frame.width(); srcHeight_ = frame.height();\n \/\/ scaler_.Set(srcWidth_, srcHeight_, dstWidth_, dstHeight_,\n \/\/ webrtc::kI420, webrtc::kI420, webrtc::kScaleBilinear);\n \/\/ }\n\n \/\/ try do scaling on this thread. if throws, do it old-fashioned way\n \/\/ ScalerThread::getSharedInstance()->perform([&res, &frame, this](){\n \/\/ scaledFrameBuffer_->ScaleFrom(frame);\n \/\/ });\n\n scaledFrameBuffer_->ScaleFrom(*(frame.video_frame_buffer()));\n \n return WebRtcVideoFrame(scaledFrameBuffer_, frame.rotation(), frame.timestamp_us());\n}\n\nvoid FrameScaler::initScaledFrame()\n{\n int stride_y = dstWidth_;\n int stride_uv = (dstWidth_ + 1) \/ 2;\n int target_width = dstWidth_;\n int target_height = dstHeight_;\n \n scaledFrameBuffer_ = I420Buffer::Create(target_width,\n abs(target_height),\n stride_y,\n stride_uv, stride_uv);\n \n if (!scaledFrameBuffer_) throw std::runtime_error(\"failed to allocate scaled frame\");\n}\n\n\/\/********************************************************************************\n#pragma mark - construction\/destruction\nVideoCoder::VideoCoder(const VideoCoderParams& coderParams, IEncoderDelegate* delegate,\n KeyEnforcement keyEnforcement) :\nNdnRtcComponent(),\ncoderParams_(coderParams),\ndelegate_(delegate),\ngopCounter_(0),\ncodec_(VideoCoder::codecFromSettings(coderParams_)),\ncodecSpecificInfo_(nullptr),\nkeyEnforcement_(keyEnforcement),\n#ifdef USE_VP9\n encoder_(VP9Encoder::Create())\n#else\n encoder_(VP8Encoder::Create())\n#endif\n{\n assert(delegate_);\n description_ = \"coder\";\n keyFrameType_.push_back(webrtc::kVideoFrameKey);\n\n if (!encoder_.get())\n throw std::runtime_error(\"Error creating encoder\");\n\n encoder_->RegisterEncodeCompleteCallback(this);\n int maxPayload = 1440;\n\n if (encoder_->InitEncode(&codec_, boost::thread::hardware_concurrency(), maxPayload) != WEBRTC_VIDEO_CODEC_OK)\n throw std::runtime_error(\"Can't initialize encoder\");\n\n LogInfoC\n << \"initialized. max payload \" << maxPayload\n << \" parameters: \" << plotCodec(codec_) << endl;\n}\n\n\/\/********************************************************************************\n#pragma mark - public\nvoid VideoCoder::onRawFrame(const WebRtcVideoFrame &frame)\n{\n LogTraceC << \"⤹ encoding ○\" << endl;\n\n if (frame.width() != coderParams_.encodeWidth_ || \n frame.height() != coderParams_.encodeHeight_)\n {\n std::stringstream ss;\n ss << \"Frame size (\" << frame.width() << \"x\" << frame.height()\n << \") does not equal encoding resolution (\" \n << coderParams_.encodeWidth_ << \"x\" << coderParams_.encodeHeight_ \n << \")\" << std::endl;\n throw std::runtime_error(ss.str());\n }\n\n encodeComplete_ = false;\n delegate_->onEncodingStarted();\n \n int err;\n if (gopCounter_%coderParams_.gop_ == 0)\n {\n err = encoder_->Encode(frame, codecSpecificInfo_, &keyFrameType_);\n if (keyEnforcement_ == KeyEnforcement::EncoderDefined) gopCounter_ = 1;\n }\n else\n err = encoder_->Encode(frame, codecSpecificInfo_, NULL);\n \n if (keyEnforcement_ == KeyEnforcement::Timed) gopCounter_++;\n\n if (!encodeComplete_)\n {\n LogTraceC << \" dropped ✕\" << endl;\n delegate_->onDroppedFrame();\n }\n \n if (err != WEBRTC_VIDEO_CODEC_OK)\n LogErrorC <<\"can't encode frame due to error \" << err << std::endl;\n}\n\n\/\/********************************************************************************\n#pragma mark - interfaces realization - EncodedImageCallback\nwebrtc::EncodedImageCallback::Result\nVideoCoder::OnEncodedImage(const EncodedImage& encodedImage,\n const CodecSpecificInfo* codecSpecificInfo,\n const RTPFragmentationHeader* fragmentation)\n{\n encodeComplete_ = true;\n if (keyEnforcement_ == KeyEnforcement::Gop) gopCounter_++;\n \n LogTraceC << \"⤷ encoded ●\" << std::endl;\n \n \/*\n LogInfoC << \"encoded\"\n << \" type \" << ((encodedImage._frameType == webrtc::kKeyFrame) ? \"KEY\":((encodedImage._frameType == webrtc::kSkipFrame)?\"SKIP\":\"DELTA\"))\n << \" complete \" << encodedImage._completeFrame << \"\\n\"\n << \" has Received SLI \" << codecSpecificInfo->codecSpecific.VP8.hasReceivedSLI\n << \" picture Id SLI \" << (int)codecSpecificInfo->codecSpecific.VP8.pictureIdSLI\n << \" has Received RPSI \" << codecSpecificInfo->codecSpecific.VP8.hasReceivedRPSI\n << \" picture Id RPSI \" << codecSpecificInfo->codecSpecific.VP8.pictureIdRPSI\n << \" picture Id \" << codecSpecificInfo->codecSpecific.VP8.pictureId\n << \" non Reference \" << codecSpecificInfo->codecSpecific.VP8.nonReference\n << \" temporalIdx \" << (int)codecSpecificInfo->codecSpecific.VP8.temporalIdx\n << \" layerSync \" << codecSpecificInfo->codecSpecific.VP8.layerSync\n << \" tl0PicIdx \" << codecSpecificInfo->codecSpecific.VP8.tl0PicIdx\n << \" keyIdx \" << (int)codecSpecificInfo->codecSpecific.VP8.keyIdx\n << std::endl; \n *\/\n delegate_->onEncodedFrame(encodedImage);\n return Result(Result::OK);\n}\n<commit_msg>removed commented code<commit_after>\/\/\n\/\/ video-coder.cpp\n\/\/ ndnrtc\n\/\/\n\/\/ Copyright 2013 Regents of the University of California\n\/\/ For licensing details see the LICENSE file.\n\/\/\n\/\/ Author: Peter Gusev\n\/\/ Created: 8\/21\/13\n\/\/\n\n\/\/ #define USE_VP9\n\n#include <boost\/thread.hpp>\n#include <webrtc\/modules\/video_coding\/codecs\/vp8\/include\/vp8.h>\n#include <webrtc\/modules\/video_coding\/codecs\/vp9\/include\/vp9.h>\n#include <webrtc\/modules\/video_coding\/include\/video_coding.h>\n#include <webrtc\/modules\/video_coding\/include\/video_codec_interface.h>\n#include <webrtc\/modules\/video_coding\/codec_database.h>\n\n#include \"video-coder.hpp\"\n#include \"threading-capability.hpp\"\n\nusing namespace std;\nusing namespace ndnlog;\nusing namespace ndnrtc;\nusing namespace webrtc;\n\n\/\/ this class is needed to synchronously dispatch all\n\/\/ frame scaling (see - FrameScaler) calls on the same thread.\n\/\/ this is WebRTC requirement - all frame scaling calls must be\n\/\/ executed on the same thread throughout lifecycle\nclass ScalerThread : public ThreadingCapability\n{\npublic:\n static ScalerThread *getSharedInstance()\n {\n static ScalerThread scalerThread;\n return &scalerThread;\n }\n \n void perform(boost::function<void(void)> block)\n {\n performOnMyThread(block);\n }\n \nprivate:\n ScalerThread() { startMyThread(); }\n ~ScalerThread() { stopMyThread(); }\n};\n\n\/\/********************************************************************************\nchar* plotCodec(webrtc::VideoCodec codec)\n{\n static char msg[256];\n \n sprintf(msg, \"\\t\\tMax Framerate:\\t%d\\n \\\n \\tStart Bitrate:\\t%d\\n \\\n \\tMin Bitrate:\\t%d\\n \\\n \\tMax Bitrate:\\t%d\\n \\\n \\tTarget Bitrate:\\t%d\\n \\\n \\tWidth:\\t%d\\n \\\n \\tHeight:\\t%d\",\n codec.maxFramerate,\n codec.startBitrate,\n codec.minBitrate,\n codec.maxBitrate,\n codec.targetBitrate,\n codec.width,\n codec.height);\n \n return msg;\n}\n\n\/\/******************************************************************************\n#pragma mark - static\nwebrtc::VideoCodec VideoCoder::codecFromSettings(const VideoCoderParams &settings)\n{\n webrtc::VideoCodec codec;\n\n \/\/ setup default params first\n#ifdef USE_VP9\n webrtc::VCMCodecDataBase::Codec(webrtc::kVideoCodecVP9, &codec);\n#else\n webrtc::VCMCodecDataBase::Codec(webrtc::kVideoCodecVP8, &codec);\n#endif\n\n \/\/ dropping frames\n#ifdef USE_VP9\n codec.VP9()->resilience = 1;\n codec.VP9()->frameDroppingOn = settings.dropFramesOn_;\n codec.VP9()->keyFrameInterval = settings.gop_;\n#else\n codec.VP8()->resilience = kResilientStream;\n codec.VP8()->frameDroppingOn = settings.dropFramesOn_;\n codec.VP8()->keyFrameInterval = settings.gop_;\n#endif\n \n \/\/ customize parameteres if possible\n codec.maxFramerate = (int)settings.codecFrameRate_;\n codec.startBitrate = settings.startBitrate_;\n codec.minBitrate = 100;\n codec.maxBitrate = settings.maxBitrate_;\n codec.targetBitrate = settings.startBitrate_;\n codec.width = settings.encodeWidth_;\n codec.height = settings.encodeHeight_;\n \n return codec;\n}\n\n\/\/******************************************************************************\nFrameScaler::FrameScaler(unsigned int dstWidth, unsigned int dstHeight):\nsrcWidth_(0), srcHeight_(0), \ndstWidth_(dstWidth), dstHeight_(dstHeight)\n{\n initScaledFrame();\n}\n\nconst WebRtcVideoFrame&\nFrameScaler::operator()(const WebRtcVideoFrame& frame)\n{\n \/\/ try do scaling on this thread. if throws, do it old-fashioned way\n \/\/ ScalerThread::getSharedInstance()->perform([&res, &frame, this](){\n \/\/ scaledFrameBuffer_->ScaleFrom(frame);\n \/\/ });\n\n scaledFrameBuffer_->ScaleFrom(*(frame.video_frame_buffer()));\n \n return WebRtcVideoFrame(scaledFrameBuffer_, frame.rotation(), frame.timestamp_us());\n}\n\nvoid FrameScaler::initScaledFrame()\n{\n int stride_y = dstWidth_;\n int stride_uv = (dstWidth_ + 1) \/ 2;\n int target_width = dstWidth_;\n int target_height = dstHeight_;\n \n scaledFrameBuffer_ = I420Buffer::Create(target_width,\n abs(target_height),\n stride_y,\n stride_uv, stride_uv);\n \n if (!scaledFrameBuffer_) throw std::runtime_error(\"failed to allocate scaled frame\");\n}\n\n\/\/********************************************************************************\n#pragma mark - construction\/destruction\nVideoCoder::VideoCoder(const VideoCoderParams& coderParams, IEncoderDelegate* delegate,\n KeyEnforcement keyEnforcement) :\nNdnRtcComponent(),\ncoderParams_(coderParams),\ndelegate_(delegate),\ngopCounter_(0),\ncodec_(VideoCoder::codecFromSettings(coderParams_)),\ncodecSpecificInfo_(nullptr),\nkeyEnforcement_(keyEnforcement),\n#ifdef USE_VP9\n encoder_(VP9Encoder::Create())\n#else\n encoder_(VP8Encoder::Create())\n#endif\n{\n assert(delegate_);\n description_ = \"coder\";\n keyFrameType_.push_back(webrtc::kVideoFrameKey);\n\n if (!encoder_.get())\n throw std::runtime_error(\"Error creating encoder\");\n\n encoder_->RegisterEncodeCompleteCallback(this);\n int maxPayload = 1440;\n\n if (encoder_->InitEncode(&codec_, boost::thread::hardware_concurrency(), maxPayload) != WEBRTC_VIDEO_CODEC_OK)\n throw std::runtime_error(\"Can't initialize encoder\");\n\n LogInfoC\n << \"initialized. max payload \" << maxPayload\n << \" parameters: \" << plotCodec(codec_) << endl;\n}\n\n\/\/********************************************************************************\n#pragma mark - public\nvoid VideoCoder::onRawFrame(const WebRtcVideoFrame &frame)\n{\n LogTraceC << \"⤹ encoding ○\" << endl;\n\n if (frame.width() != coderParams_.encodeWidth_ || \n frame.height() != coderParams_.encodeHeight_)\n {\n std::stringstream ss;\n ss << \"Frame size (\" << frame.width() << \"x\" << frame.height()\n << \") does not equal encoding resolution (\" \n << coderParams_.encodeWidth_ << \"x\" << coderParams_.encodeHeight_ \n << \")\" << std::endl;\n throw std::runtime_error(ss.str());\n }\n\n encodeComplete_ = false;\n delegate_->onEncodingStarted();\n \n int err;\n if (gopCounter_%coderParams_.gop_ == 0)\n {\n err = encoder_->Encode(frame, codecSpecificInfo_, &keyFrameType_);\n if (keyEnforcement_ == KeyEnforcement::EncoderDefined) gopCounter_ = 1;\n }\n else\n err = encoder_->Encode(frame, codecSpecificInfo_, NULL);\n \n if (keyEnforcement_ == KeyEnforcement::Timed) gopCounter_++;\n\n if (!encodeComplete_)\n {\n LogTraceC << \" dropped ✕\" << endl;\n delegate_->onDroppedFrame();\n }\n \n if (err != WEBRTC_VIDEO_CODEC_OK)\n LogErrorC <<\"can't encode frame due to error \" << err << std::endl;\n}\n\n\/\/********************************************************************************\n#pragma mark - interfaces realization - EncodedImageCallback\nwebrtc::EncodedImageCallback::Result\nVideoCoder::OnEncodedImage(const EncodedImage& encodedImage,\n const CodecSpecificInfo* codecSpecificInfo,\n const RTPFragmentationHeader* fragmentation)\n{\n encodeComplete_ = true;\n if (keyEnforcement_ == KeyEnforcement::Gop) gopCounter_++;\n \n LogTraceC << \"⤷ encoded ●\" << std::endl;\n \n \/*\n LogInfoC << \"encoded\"\n << \" type \" << ((encodedImage._frameType == webrtc::kKeyFrame) ? \"KEY\":((encodedImage._frameType == webrtc::kSkipFrame)?\"SKIP\":\"DELTA\"))\n << \" complete \" << encodedImage._completeFrame << \"\\n\"\n << \" has Received SLI \" << codecSpecificInfo->codecSpecific.VP8.hasReceivedSLI\n << \" picture Id SLI \" << (int)codecSpecificInfo->codecSpecific.VP8.pictureIdSLI\n << \" has Received RPSI \" << codecSpecificInfo->codecSpecific.VP8.hasReceivedRPSI\n << \" picture Id RPSI \" << codecSpecificInfo->codecSpecific.VP8.pictureIdRPSI\n << \" picture Id \" << codecSpecificInfo->codecSpecific.VP8.pictureId\n << \" non Reference \" << codecSpecificInfo->codecSpecific.VP8.nonReference\n << \" temporalIdx \" << (int)codecSpecificInfo->codecSpecific.VP8.temporalIdx\n << \" layerSync \" << codecSpecificInfo->codecSpecific.VP8.layerSync\n << \" tl0PicIdx \" << codecSpecificInfo->codecSpecific.VP8.tl0PicIdx\n << \" keyIdx \" << (int)codecSpecificInfo->codecSpecific.VP8.keyIdx\n << std::endl; \n *\/\n delegate_->onEncodedFrame(encodedImage);\n return Result(Result::OK);\n}\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: tabsh.hxx,v $\n *\n * $Revision: 1.2 $\n *\n * last change: $Author: rt $ $Date: 2004-08-23 09:02:44 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n#ifndef _SWTABSH_HXX\n#define _SWTABSH_HXX\n\n#ifndef _SWBASESH_HXX\n#include \"basesh.hxx\"\n#endif\n\n#ifndef INCLUDED_SWDLLAPI_H\n#include \"swdllapi.h\"\n#endif\n\nclass SfxItemSet;\nclass SwWrtShell;\n\nSW_DLLPUBLIC void ItemSetToTableParam( const SfxItemSet& rSet, SwWrtShell &rSh );\n\nextern const USHORT __FAR_DATA aUITableAttrRange[];\nSW_DLLPUBLIC const USHORT* SwuiGetUITableAttrRange();\n\nclass SwTableShell: public SwBaseShell\n{\npublic:\n SFX_DECL_INTERFACE(SW_TABSHELL);\n TYPEINFO();\n\n void Execute(SfxRequest &);\n void GetState(SfxItemSet &);\n void GetFrmBorderState(SfxItemSet &rSet);\n void GetLineStyleState(SfxItemSet &rSet);\n void ExecTableStyle(SfxRequest& rReq);\n\n void ExecNumberFormat(SfxRequest& rReq);\n\n SwTableShell(SwView &rView);\n};\n\n#endif\n<commit_msg>INTEGRATION: CWS ooo19126 (1.2.596); FILE MERGED 2005\/09\/05 13:45:44 rt 1.2.596.1: #i54170# Change license header: remove SISSL<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: tabsh.hxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: rt $ $Date: 2005-09-09 10:08:00 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n#ifndef _SWTABSH_HXX\n#define _SWTABSH_HXX\n\n#ifndef _SWBASESH_HXX\n#include \"basesh.hxx\"\n#endif\n\n#ifndef INCLUDED_SWDLLAPI_H\n#include \"swdllapi.h\"\n#endif\n\nclass SfxItemSet;\nclass SwWrtShell;\n\nSW_DLLPUBLIC void ItemSetToTableParam( const SfxItemSet& rSet, SwWrtShell &rSh );\n\nextern const USHORT __FAR_DATA aUITableAttrRange[];\nSW_DLLPUBLIC const USHORT* SwuiGetUITableAttrRange();\n\nclass SwTableShell: public SwBaseShell\n{\npublic:\n SFX_DECL_INTERFACE(SW_TABSHELL);\n TYPEINFO();\n\n void Execute(SfxRequest &);\n void GetState(SfxItemSet &);\n void GetFrmBorderState(SfxItemSet &rSet);\n void GetLineStyleState(SfxItemSet &rSet);\n void ExecTableStyle(SfxRequest& rReq);\n\n void ExecNumberFormat(SfxRequest& rReq);\n\n SwTableShell(SwView &rView);\n};\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>#pragma once\r\n#include <algorithm>\r\n#include <initializer_list>\r\n#include <stdexcept>\r\n#include <utility>\r\n#include <vector>\r\n\r\n#include \"base\/helpers.hpp\"\r\n#include \"is_equal_to_zero.hpp\"\r\n#include \"maths.hpp\"\r\n#include \"random.hpp\"\r\n\r\nstruct maximal_element_search_tag {};\r\nstruct prime_modulo_calculations_tag {};\r\n\r\ntemplate<typename T>\r\nclass Matrix {\r\npublic:\r\n\tusing value_type = T;\r\n\tusing size_type = std::size_t;\r\n\r\n\tusing vector_container_type = std::vector<value_type>;\r\n\tusing matrix_container_type = std::vector<vector_container_type>;\r\n\r\n\tMatrix(const size_type rows_cnt, const size_type cols_cnt, const value_type mod = 1000000007) :\r\n\t\t\trows_cnt_(rows_cnt),\r\n\t\t\tcols_cnt_(cols_cnt),\r\n\t\t\tdata_(rows_cnt, vector_container_type(cols_cnt, 0)),\r\n\t\t\tmod_(mod)\r\n\t{}\r\n\r\n\texplicit Matrix(const std::initializer_list<std::initializer_list<value_type>>& initializer_list, const value_type mod = 1000000007) :\r\n\t\t\trows_cnt_(initializer_list.size()),\r\n\t\t\tcols_cnt_(0),\r\n\t\t\tmod_(mod)\r\n\t{\r\n\t\tdata_.reserve(initializer_list.size());\r\n\t\tfor (const auto& row : initializer_list) {\r\n\t\t\tif (data_.empty()) {\r\n\t\t\t\tcols_cnt_ = row.size();\r\n\t\t\t} else {\r\n\t\t\t\tif (cols_cnt_ != row.size()) {\r\n\t\t\t\t\tthrow std::out_of_range(\"Matrix<T> initializer list must have rows of the same size\");\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tdata_.emplace_back(row);\r\n\t\t}\r\n\t}\r\n\r\n\ttemplate<typename U>\r\n\tMatrix(const Matrix<U>& matrix) :\r\n\t\t\trows_cnt_(matrix.rows_cnt()),\r\n\t\t\tcols_cnt_(matrix.cols_cnt()),\r\n\t\t\tdata_(matrix.rows_cnt(), vector_container_type(matrix.cols_cnt()))\r\n\t{\r\n\t\tfor (size_type i = 0; i < rows_cnt_; ++i) {\r\n\t\t\tfor (size_type j = 0; j < cols_cnt_; ++j) {\r\n\t\t\t\tdata_[i][j] = static_cast<value_type>(matrix[i][j]);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\tsize_type get_matrix_rank() const;\r\n\tsize_type get_matrix_rank(maximal_element_search_tag) const;\r\n\tsize_type get_matrix_rank(prime_modulo_calculations_tag, const value_type& mod) const;\r\n\r\n\tvoid swap_rows(const size_type i, const size_type j) {\r\n\t\tdata_[i].swap(data_[j]);\r\n\t}\r\n\r\n\tvoid swap_cols(const size_type i, const size_type j) {\r\n\t\tfor (auto& row : data_) {\r\n\t\t\tstd::swap(row[i], row[j]);\r\n\t\t}\r\n\t}\r\n\r\n\tvoid shuffle() {\r\n\t\tshuffle_rows();\r\n\t\tshuffle_cols();\r\n\t}\r\n\r\n\tvoid shuffle_cols() {\r\n\t\tmatrix_container_type tmp(rows_cnt_, cols_cnt_);\r\n\t\tstd::vector<size_type> indices(cols_cnt_);\r\n\t\tfor (size_type i = 0; i < cols_cnt_; ++i) {\r\n\t\t\tindices[i] = i;\r\n\t\t}\r\n\t\tstd::shuffle(indices.begin(), indices.end(), Random::random_engine());\r\n\t\tfor (size_type j = 0; j < cols_cnt_; ++j) {\r\n\t\t\tsize_type index = indices[j];\r\n\t\t\tfor (size_type row = 0; row < rows_cnt_; ++row) {\r\n\t\t\t\ttmp[row][j] = data_[row][index];\r\n\t\t\t}\r\n\t\t}\r\n\t\tdata_.swap(tmp);\r\n\t}\r\n\r\n\tvoid shuffle_rows() {\r\n\t\tmatrix_container_type tmp;\r\n\t\ttmp.reserve(rows_cnt_);\r\n\t\tstd::vector<size_type> indices(rows_cnt_);\r\n\t\tfor (size_type i = 0; i < rows_cnt_; ++i) {\r\n\t\t\tindices[i] = i;\r\n\t\t}\r\n\t\tstd::shuffle(indices.begin(), indices.end(), Random::random_engine());\r\n\t\tfor (const auto& index : indices) {\r\n\t\t\ttmp.emplace_back(data_[index]);\r\n\t\t}\r\n\t\tdata_.swap(tmp);\r\n\t}\r\n\r\n\ttypename matrix_container_type::iterator begin() {\r\n\t\treturn data_.begin();\r\n\t}\r\n\r\n\ttypename matrix_container_type::const_iterator begin() const {\r\n\t\treturn data_.begin();\r\n\t}\r\n\r\n\ttypename matrix_container_type::iterator end() {\r\n\t\treturn data_.end();\r\n\t}\r\n\r\n\ttypename matrix_container_type::const_iterator end() const {\r\n\t\treturn data_.end();\r\n\t}\r\n\r\n\tvector_container_type get_column(const size_type index) const {\r\n\t\tvector_container_type column;\r\n\t\tcolumn.reserve(rows_cnt_);\r\n\t\tfor (const auto& row : data_) {\r\n\t\t\tcolumn.emplace_back(row[index]);\r\n\t\t}\r\n\t\treturn column;\r\n\t}\r\n\r\n\tvector_container_type& operator [](const size_type index) {\r\n\t\treturn data_[index];\r\n\t}\r\n\r\n\tconst vector_container_type& operator [](const size_type index) const {\r\n\t\treturn data_[index];\r\n\t}\r\n\r\n\tconstexpr size_type rows_cnt() const {\r\n\t\treturn rows_cnt_;\r\n\t}\r\n\r\n\tconstexpr size_type cols_cnt() const {\r\n\t\treturn cols_cnt_;\r\n\t}\r\n\r\n\tMatrix operator *(const Matrix& rhs) const {\r\n\t\tMatrix result(rows_cnt_, rhs.cols_cnt_);\r\n\t\tfor (size_type i = 0; i < rows_cnt_; i++) {\r\n\t\t\tfor (size_type k = 0; k < rhs.cols_cnt_; k++) {\r\n\t\t\t\tfor (size_type j = 0; j < rhs.rows_cnt_; j++) {\r\n\t\t\t\t\tresult[i][k] += data_[i][j] * rhs[j][k];\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn result;\r\n\t}\r\n\r\n\tMatrix& operator *=(const Matrix& rhs) {\r\n\t\tMatrix result = operator *(rhs);\r\n\t\tswap(result);\r\n\t\treturn *this;\r\n\t}\r\n\r\n\ttemplate<typename U>\r\n\tMatrix binpow(U b) const {\r\n\t\tstatic_assert(std::is_integral<U>::value, \"Degree must be integral. For real degree use pow.\");\r\n\t\tMatrix ret = identity_matrix(rows_cnt_, cols_cnt_);\r\n\t\tMatrix a = *this;\r\n\t\twhile (b != 0) {\r\n\t\t\tif ((b & 1) != 0) {\r\n\t\t\t\tret *= a;\r\n\t\t\t}\r\n\t\t\ta *= a;\r\n\t\t\tb >>= 1;\r\n\t\t}\r\n\t\treturn ret;\r\n\t}\r\n\r\n\tvoid swap(Matrix& rhs) {\r\n\t\tdata_.swap(rhs.data_);\r\n\t\tstd::swap(mod_, rhs.mod_);\r\n\t\tstd::swap(rows_cnt_, rhs.rows_cnt_);\r\n\t\tstd::swap(cols_cnt_, rhs.cols_cnt_);\r\n\t}\r\n\r\n\tstatic Matrix identity_matrix(const size_type rows_cnt, const size_type cols_cnt) {\r\n\t\tMatrix result(rows_cnt, cols_cnt);\r\n\t\tfor (size_type i = 0; i < std::min(rows_cnt, cols_cnt); ++i) {\r\n\t\t\tresult[i][i] = 1;\r\n\t\t}\r\n\t\treturn result;\r\n\t}\r\n\r\nprivate:\r\n\tsize_type rows_cnt_;\r\n\tsize_type cols_cnt_;\r\n\tvalue_type mod_;\r\n\r\n\tmatrix_container_type data_;\r\n};\r\n\r\ntemplate <typename T>\r\ntypename Matrix<T>::size_type Matrix<T>::get_matrix_rank() const {\r\n\tMatrix<long double> tmp(*this);\r\n\tstd::vector<bool> used(rows_cnt_, false);\r\n\tsize_type rank = cols_cnt_;\r\n\tfor (size_type col = 0; col < cols_cnt_; ++col) {\r\n\t\tsize_type best_row = std::numeric_limits<size_type>::max();\r\n\t\tfor (size_type row = 0; row < rows_cnt_; ++row) {\r\n\t\t\tif (!used[row] && !is_equal_to_zero(tmp[row][col])) {\r\n\t\t\t\tbest_row = row;\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t}\r\n\t\tif (best_row == std::numeric_limits<size_type>::max()) {\r\n\t\t\t--rank;\r\n\t\t\tcontinue;\r\n\t\t}\r\n\t\tused[best_row] = true;\r\n\t\tfor (size_type j = col + 1; j < cols_cnt_; ++j) {\r\n\t\t\ttmp[best_row][j] \/= tmp[best_row][col];\r\n\t\t}\r\n\t\tfor (size_type row = 0; row < rows_cnt_; ++row) {\r\n\t\t\tif (used[row] || is_equal_to_zero(tmp[row][col])) {\r\n\t\t\t\tcontinue;\r\n\t\t\t}\r\n\t\t\tfor (size_type j = col + 1; j < cols_cnt_; ++j) {\r\n\t\t\t\ttmp[row][j] -= tmp[best_row][j] * tmp[row][col];\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\treturn rank;\r\n}\r\n\r\ntemplate <typename T>\r\ntypename Matrix<T>::size_type Matrix<T>::get_matrix_rank(maximal_element_search_tag) const {\r\n\tMatrix<long double> tmp(*this);\r\n\tstd::vector<bool> used(rows_cnt_, false);\r\n\tsize_type rank = 0;\r\n\tfor (size_type col = 0; col < cols_cnt_; ++col) {\r\n\t\tvalue_type max_value = EPS;\r\n\t\tsize_type best_row = std::numeric_limits<size_type>::max();\r\n\t\tfor (size_type row = 0; row < rows_cnt_; ++row) {\r\n\t\t\tif (!used[row] && umax(max_value, abs(tmp[row][col]))) {\r\n\t\t\t\tbest_row = row;\r\n\t\t\t}\r\n\t\t}\r\n\t\tif (best_row == std::numeric_limits<size_type>::max()) {\r\n\t\t\tcontinue;\r\n\t\t}\r\n\t\t++rank;\r\n\t\tused[best_row] = true;\r\n\t\tfor (size_type j = col + 1; j < cols_cnt_; ++j) {\r\n\t\t\ttmp[best_row][j] \/= tmp[best_row][col];\r\n\t\t}\r\n\t\tfor (size_type row = 0; row < rows_cnt_; ++row) {\r\n\t\t\tif (used[row] || is_equal_to_zero(tmp[row][col])) {\r\n\t\t\t\tcontinue;\r\n\t\t\t}\r\n\t\t\tfor (size_type j = col + 1; j < cols_cnt_; ++j) {\r\n\t\t\t\ttmp[row][j] -= tmp[best_row][j] * tmp[row][col];\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\treturn rank;\r\n}\r\n\r\ntemplate <typename T>\r\ntypename Matrix<T>::size_type Matrix<T>::get_matrix_rank(prime_modulo_calculations_tag, const value_type& mod) const {\r\n\tstatic_assert(std::is_integral<value_type>::value, \"Integral type required to process calculations by prime modulo\");\r\n\tMatrix<long long> tmp(*this);\r\n\tfor (auto& row : tmp) {\r\n\t\tfor (auto& col : row) {\r\n\t\t\tif (col < 0) {\r\n\t\t\t\tcol += mod;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tstd::vector<bool> used(rows_cnt_, false);\r\n\tsize_type rank = cols_cnt_;\r\n\tfor (size_type col = 0; col < cols_cnt_; ++col) {\r\n\t\tsize_type best_row = std::numeric_limits<size_type>::max();\r\n\t\tfor (size_type row = 0; row < rows_cnt_; ++row) {\r\n\t\t\tif (!used[row] && !is_equal_to_zero(tmp[row][col])) {\r\n\t\t\t\tbest_row = row;\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t}\r\n\t\tif (best_row == std::numeric_limits<size_type>::max()) {\r\n\t\t\t--rank;\r\n\t\t\tcontinue;\r\n\t\t}\r\n\t\tused[best_row] = true; \r\n\t\tfor (size_type j = col + 1; j < cols_cnt_; ++j) {\r\n\t\t\tmul_mod(tmp[best_row][j], inverseElement(tmp[best_row][col], mod), mod);\r\n\t\t}\r\n\t\tfor (size_type row = 0; row < rows_cnt_; ++row) {\r\n\t\t\tif (used[row] || is_equal_to_zero(tmp[row][col])) {\r\n\t\t\t\tcontinue;\r\n\t\t\t}\r\n\t\t\tfor (size_type j = col + 1; j < cols_cnt_; ++j) {\r\n\t\t\t\tlong long x = tmp[best_row][j];\r\n\t\t\t\tmul_mod(x, tmp[row][col], mod);\r\n\t\t\t\tsub_mod(tmp[row][j], x, mod);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\treturn rank;\r\n}\r\n<commit_msg>Fix -Wreorder warning in Matrix<>.<commit_after>#pragma once\r\n#include <algorithm>\r\n#include <initializer_list>\r\n#include <stdexcept>\r\n#include <utility>\r\n#include <vector>\r\n\r\n#include \"base\/helpers.hpp\"\r\n#include \"is_equal_to_zero.hpp\"\r\n#include \"maths.hpp\"\r\n#include \"random.hpp\"\r\n\r\nstruct maximal_element_search_tag {};\r\nstruct prime_modulo_calculations_tag {};\r\n\r\ntemplate<typename T>\r\nclass Matrix {\r\npublic:\r\n\tusing value_type = T;\r\n\tusing size_type = std::size_t;\r\n\r\n\tusing vector_container_type = std::vector<value_type>;\r\n\tusing matrix_container_type = std::vector<vector_container_type>;\r\n\r\n\tMatrix(const size_type rows_cnt, const size_type cols_cnt, const value_type mod = 1000000007) :\r\n\t\t\trows_cnt_(rows_cnt),\r\n\t\t\tcols_cnt_(cols_cnt),\r\n\t\t\tdata_(rows_cnt, vector_container_type(cols_cnt, 0)),\r\n\t\t\tmod_(mod)\r\n\t{}\r\n\r\n\texplicit Matrix(const std::initializer_list<std::initializer_list<value_type>>& initializer_list, const value_type mod = 1000000007) :\r\n\t\t\trows_cnt_(initializer_list.size()),\r\n\t\t\tcols_cnt_(0),\r\n\t\t\tmod_(mod)\r\n\t{\r\n\t\tdata_.reserve(initializer_list.size());\r\n\t\tfor (const auto& row : initializer_list) {\r\n\t\t\tif (data_.empty()) {\r\n\t\t\t\tcols_cnt_ = row.size();\r\n\t\t\t} else {\r\n\t\t\t\tif (cols_cnt_ != row.size()) {\r\n\t\t\t\t\tthrow std::out_of_range(\"Matrix<T> initializer list must have rows of the same size\");\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tdata_.emplace_back(row);\r\n\t\t}\r\n\t}\r\n\r\n\ttemplate<typename U>\r\n\tMatrix(const Matrix<U>& matrix) :\r\n\t\t\trows_cnt_(matrix.rows_cnt()),\r\n\t\t\tcols_cnt_(matrix.cols_cnt()),\r\n\t\t\tdata_(matrix.rows_cnt(), vector_container_type(matrix.cols_cnt()))\r\n\t{\r\n\t\tfor (size_type i = 0; i < rows_cnt_; ++i) {\r\n\t\t\tfor (size_type j = 0; j < cols_cnt_; ++j) {\r\n\t\t\t\tdata_[i][j] = static_cast<value_type>(matrix[i][j]);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\tsize_type get_matrix_rank() const;\r\n\tsize_type get_matrix_rank(maximal_element_search_tag) const;\r\n\tsize_type get_matrix_rank(prime_modulo_calculations_tag, const value_type& mod) const;\r\n\r\n\tvoid swap_rows(const size_type i, const size_type j) {\r\n\t\tdata_[i].swap(data_[j]);\r\n\t}\r\n\r\n\tvoid swap_cols(const size_type i, const size_type j) {\r\n\t\tfor (auto& row : data_) {\r\n\t\t\tstd::swap(row[i], row[j]);\r\n\t\t}\r\n\t}\r\n\r\n\tvoid shuffle() {\r\n\t\tshuffle_rows();\r\n\t\tshuffle_cols();\r\n\t}\r\n\r\n\tvoid shuffle_cols() {\r\n\t\tmatrix_container_type tmp(rows_cnt_, cols_cnt_);\r\n\t\tstd::vector<size_type> indices(cols_cnt_);\r\n\t\tfor (size_type i = 0; i < cols_cnt_; ++i) {\r\n\t\t\tindices[i] = i;\r\n\t\t}\r\n\t\tstd::shuffle(indices.begin(), indices.end(), Random::random_engine());\r\n\t\tfor (size_type j = 0; j < cols_cnt_; ++j) {\r\n\t\t\tsize_type index = indices[j];\r\n\t\t\tfor (size_type row = 0; row < rows_cnt_; ++row) {\r\n\t\t\t\ttmp[row][j] = data_[row][index];\r\n\t\t\t}\r\n\t\t}\r\n\t\tdata_.swap(tmp);\r\n\t}\r\n\r\n\tvoid shuffle_rows() {\r\n\t\tmatrix_container_type tmp;\r\n\t\ttmp.reserve(rows_cnt_);\r\n\t\tstd::vector<size_type> indices(rows_cnt_);\r\n\t\tfor (size_type i = 0; i < rows_cnt_; ++i) {\r\n\t\t\tindices[i] = i;\r\n\t\t}\r\n\t\tstd::shuffle(indices.begin(), indices.end(), Random::random_engine());\r\n\t\tfor (const auto& index : indices) {\r\n\t\t\ttmp.emplace_back(data_[index]);\r\n\t\t}\r\n\t\tdata_.swap(tmp);\r\n\t}\r\n\r\n\ttypename matrix_container_type::iterator begin() {\r\n\t\treturn data_.begin();\r\n\t}\r\n\r\n\ttypename matrix_container_type::const_iterator begin() const {\r\n\t\treturn data_.begin();\r\n\t}\r\n\r\n\ttypename matrix_container_type::iterator end() {\r\n\t\treturn data_.end();\r\n\t}\r\n\r\n\ttypename matrix_container_type::const_iterator end() const {\r\n\t\treturn data_.end();\r\n\t}\r\n\r\n\tvector_container_type get_column(const size_type index) const {\r\n\t\tvector_container_type column;\r\n\t\tcolumn.reserve(rows_cnt_);\r\n\t\tfor (const auto& row : data_) {\r\n\t\t\tcolumn.emplace_back(row[index]);\r\n\t\t}\r\n\t\treturn column;\r\n\t}\r\n\r\n\tvector_container_type& operator [](const size_type index) {\r\n\t\treturn data_[index];\r\n\t}\r\n\r\n\tconst vector_container_type& operator [](const size_type index) const {\r\n\t\treturn data_[index];\r\n\t}\r\n\r\n\tconstexpr size_type rows_cnt() const {\r\n\t\treturn rows_cnt_;\r\n\t}\r\n\r\n\tconstexpr size_type cols_cnt() const {\r\n\t\treturn cols_cnt_;\r\n\t}\r\n\r\n\tMatrix operator *(const Matrix& rhs) const {\r\n\t\tMatrix result(rows_cnt_, rhs.cols_cnt_);\r\n\t\tfor (size_type i = 0; i < rows_cnt_; i++) {\r\n\t\t\tfor (size_type k = 0; k < rhs.cols_cnt_; k++) {\r\n\t\t\t\tfor (size_type j = 0; j < rhs.rows_cnt_; j++) {\r\n\t\t\t\t\tresult[i][k] += data_[i][j] * rhs[j][k];\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn result;\r\n\t}\r\n\r\n\tMatrix& operator *=(const Matrix& rhs) {\r\n\t\tMatrix result = operator *(rhs);\r\n\t\tswap(result);\r\n\t\treturn *this;\r\n\t}\r\n\r\n\ttemplate<typename U>\r\n\tMatrix binpow(U b) const {\r\n\t\tstatic_assert(std::is_integral<U>::value, \"Degree must be integral. For real degree use pow.\");\r\n\t\tMatrix ret = identity_matrix(rows_cnt_, cols_cnt_);\r\n\t\tMatrix a = *this;\r\n\t\twhile (b != 0) {\r\n\t\t\tif ((b & 1) != 0) {\r\n\t\t\t\tret *= a;\r\n\t\t\t}\r\n\t\t\ta *= a;\r\n\t\t\tb >>= 1;\r\n\t\t}\r\n\t\treturn ret;\r\n\t}\r\n\r\n\tvoid swap(Matrix& rhs) {\r\n\t\tdata_.swap(rhs.data_);\r\n\t\tstd::swap(mod_, rhs.mod_);\r\n\t\tstd::swap(rows_cnt_, rhs.rows_cnt_);\r\n\t\tstd::swap(cols_cnt_, rhs.cols_cnt_);\r\n\t}\r\n\r\n\tstatic Matrix identity_matrix(const size_type rows_cnt, const size_type cols_cnt) {\r\n\t\tMatrix result(rows_cnt, cols_cnt);\r\n\t\tfor (size_type i = 0; i < std::min(rows_cnt, cols_cnt); ++i) {\r\n\t\t\tresult[i][i] = 1;\r\n\t\t}\r\n\t\treturn result;\r\n\t}\r\n\r\nprivate:\r\n\tsize_type rows_cnt_;\r\n\tsize_type cols_cnt_;\r\n\tmatrix_container_type data_;\r\n\r\n\tvalue_type mod_;\r\n};\r\n\r\ntemplate <typename T>\r\ntypename Matrix<T>::size_type Matrix<T>::get_matrix_rank() const {\r\n\tMatrix<long double> tmp(*this);\r\n\tstd::vector<bool> used(rows_cnt_, false);\r\n\tsize_type rank = cols_cnt_;\r\n\tfor (size_type col = 0; col < cols_cnt_; ++col) {\r\n\t\tsize_type best_row = std::numeric_limits<size_type>::max();\r\n\t\tfor (size_type row = 0; row < rows_cnt_; ++row) {\r\n\t\t\tif (!used[row] && !is_equal_to_zero(tmp[row][col])) {\r\n\t\t\t\tbest_row = row;\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t}\r\n\t\tif (best_row == std::numeric_limits<size_type>::max()) {\r\n\t\t\t--rank;\r\n\t\t\tcontinue;\r\n\t\t}\r\n\t\tused[best_row] = true;\r\n\t\tfor (size_type j = col + 1; j < cols_cnt_; ++j) {\r\n\t\t\ttmp[best_row][j] \/= tmp[best_row][col];\r\n\t\t}\r\n\t\tfor (size_type row = 0; row < rows_cnt_; ++row) {\r\n\t\t\tif (used[row] || is_equal_to_zero(tmp[row][col])) {\r\n\t\t\t\tcontinue;\r\n\t\t\t}\r\n\t\t\tfor (size_type j = col + 1; j < cols_cnt_; ++j) {\r\n\t\t\t\ttmp[row][j] -= tmp[best_row][j] * tmp[row][col];\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\treturn rank;\r\n}\r\n\r\ntemplate <typename T>\r\ntypename Matrix<T>::size_type Matrix<T>::get_matrix_rank(maximal_element_search_tag) const {\r\n\tMatrix<long double> tmp(*this);\r\n\tstd::vector<bool> used(rows_cnt_, false);\r\n\tsize_type rank = 0;\r\n\tfor (size_type col = 0; col < cols_cnt_; ++col) {\r\n\t\tvalue_type max_value = EPS;\r\n\t\tsize_type best_row = std::numeric_limits<size_type>::max();\r\n\t\tfor (size_type row = 0; row < rows_cnt_; ++row) {\r\n\t\t\tif (!used[row] && umax(max_value, abs(tmp[row][col]))) {\r\n\t\t\t\tbest_row = row;\r\n\t\t\t}\r\n\t\t}\r\n\t\tif (best_row == std::numeric_limits<size_type>::max()) {\r\n\t\t\tcontinue;\r\n\t\t}\r\n\t\t++rank;\r\n\t\tused[best_row] = true;\r\n\t\tfor (size_type j = col + 1; j < cols_cnt_; ++j) {\r\n\t\t\ttmp[best_row][j] \/= tmp[best_row][col];\r\n\t\t}\r\n\t\tfor (size_type row = 0; row < rows_cnt_; ++row) {\r\n\t\t\tif (used[row] || is_equal_to_zero(tmp[row][col])) {\r\n\t\t\t\tcontinue;\r\n\t\t\t}\r\n\t\t\tfor (size_type j = col + 1; j < cols_cnt_; ++j) {\r\n\t\t\t\ttmp[row][j] -= tmp[best_row][j] * tmp[row][col];\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\treturn rank;\r\n}\r\n\r\ntemplate <typename T>\r\ntypename Matrix<T>::size_type Matrix<T>::get_matrix_rank(prime_modulo_calculations_tag, const value_type& mod) const {\r\n\tstatic_assert(std::is_integral<value_type>::value, \"Integral type required to process calculations by prime modulo\");\r\n\tMatrix<long long> tmp(*this);\r\n\tfor (auto& row : tmp) {\r\n\t\tfor (auto& col : row) {\r\n\t\t\tif (col < 0) {\r\n\t\t\t\tcol += mod;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tstd::vector<bool> used(rows_cnt_, false);\r\n\tsize_type rank = cols_cnt_;\r\n\tfor (size_type col = 0; col < cols_cnt_; ++col) {\r\n\t\tsize_type best_row = std::numeric_limits<size_type>::max();\r\n\t\tfor (size_type row = 0; row < rows_cnt_; ++row) {\r\n\t\t\tif (!used[row] && !is_equal_to_zero(tmp[row][col])) {\r\n\t\t\t\tbest_row = row;\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t}\r\n\t\tif (best_row == std::numeric_limits<size_type>::max()) {\r\n\t\t\t--rank;\r\n\t\t\tcontinue;\r\n\t\t}\r\n\t\tused[best_row] = true; \r\n\t\tfor (size_type j = col + 1; j < cols_cnt_; ++j) {\r\n\t\t\tmul_mod(tmp[best_row][j], inverseElement(tmp[best_row][col], mod), mod);\r\n\t\t}\r\n\t\tfor (size_type row = 0; row < rows_cnt_; ++row) {\r\n\t\t\tif (used[row] || is_equal_to_zero(tmp[row][col])) {\r\n\t\t\t\tcontinue;\r\n\t\t\t}\r\n\t\t\tfor (size_type j = col + 1; j < cols_cnt_; ++j) {\r\n\t\t\t\tlong long x = tmp[best_row][j];\r\n\t\t\t\tmul_mod(x, tmp[row][col], mod);\r\n\t\t\t\tsub_mod(tmp[row][j], x, mod);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\treturn rank;\r\n}\r\n<|endoftext|>"} {"text":"<commit_before>#include \"geometry\/triangular_mesh.h\"\n#include \"const.h\"\n#include <cassert>\n\nnamespace hd {\n TriangularMesh::TriangularMesh() {\n _vertices.clear();\n _edges.clear();\n _faces.clear();\n _isPopulated = false;\n _vertexNormalMode = TriangularMesh::VertexNormalMode::AVERAGED;\n _faceNormalMode = TriangularMesh::FaceNormalMode::FLAT;\n }\n\n TriangularMesh::TriangularMesh(const TriangularMesh& mesh) {\n _vertices.insert(_vertices.end(), mesh._vertices.begin(), mesh._vertices.end());\n _edges.insert(_edges.end(), mesh._edges.begin(), mesh._edges.end());\n _faces.insert(_faces.end(), mesh._faces.begin(), mesh._faces.end());\n _isPopulated = mesh._isPopulated;\n _boundingBox = mesh._boundingBox;\n _vertexNormalMode = mesh._vertexNormalMode;\n _faceNormalMode = mesh._faceNormalMode;\n }\n\n TriangularMesh::~TriangularMesh() {\n _vertices.clear();\n _edges.clear();\n _faces.clear();\n }\n\n TriangularMesh::Builder TriangularMesh::newBuilder(\n TriangularMesh::VertexNormalMode vertexNormalMode,\n TriangularMesh::FaceNormalMode faceNormalMode) {\n return TriangularMesh::Builder(vertexNormalMode, faceNormalMode);\n }\n\n TriangularMesh::Vertex TriangularMesh::v(unsigned int index) const {\n assert(index < vertexNum());\n return _vertices[index];\n }\n\n TriangularMesh::Face TriangularMesh::f(unsigned int index) const {\n assert(index < faceNum());\n return _faces[index];\n }\n\n TriangularMesh::Edge TriangularMesh::e(unsigned int index) const {\n assert(index < edgeNum());\n return _edges[index];\n }\n\n unsigned int TriangularMesh::vertexNum() const {\n return _vertices.size();\n }\n\n unsigned int TriangularMesh::edgeNum() const {\n return _edges.size();\n }\n\n unsigned int TriangularMesh::faceNum() const {\n return _faces.size();\n }\n\n Triangle3 TriangularMesh::triangle(unsigned int index) const {\n assert(isPopulated());\n assert(index < faceNum());\n auto f = _faces[index];\n auto faceVertices = std::array<Vector3, 3>();\n for (int vInd = 0; vInd < 3; ++vInd) {\n faceVertices[vInd] = v(f.vertices[vInd]).pos;\n }\n return Triangle3(faceVertices);\n }\n\n Vector3 TriangularMesh::normal(const TriangularMesh::MeshPoint& p) const {\n assert(isPopulated());\n assert(p.faceId < faceNum());\n if (_faceNormalMode != TriangularMesh::FaceNormalMode::PHONG) {\n return f(p.faceId).normal;\n }\n Vector3 avgNormal = Vector3::zero();\n for (unsigned int i = 0; i < 3; ++i) {\n avgNormal += p.params[i] * v(f(p.faceId).vertices[i]).pos;\n }\n return avgNormal.normalize();\n }\n\n\n BoundingBox3 TriangularMesh::boundingBox3() const {\n assert(isPopulated());\n return _boundingBox; \n }\n\n void TriangularMesh::populate() {\n assert(!isPopulated());\n _populateEdges();\n _populateNormals();\n _populateBoundingBox();\n _isPopulated = true;\n }\n\n void TriangularMesh::_populateEdges() {\n \/\/ Generate all edges. Update edge lists of vertices and faces.\n _edges.resize(_faces.size() * 3);\n for (unsigned int fid = 0; fid < _faces.size(); ++fid) {\n auto face = _faces[fid];\n for (unsigned int eid = 0; eid < 3; ++eid) {\n unsigned int edgeId = fid * 3 + eid;\n TriangularMesh::Edge edge = TriangularMesh::Edge();\n edge.startVertex = face.vertices[eid];\n edge.endVertex = face.vertices[(eid + 1) % 3];\n edge.face = fid;\n edge.nextEdge = fid * 3 + (eid + 1) % 3;\n \/\/ prev edge should be (eid - 1) % 3. To avoid overflow when eid is 0, we instead\n \/\/ use (eid + 2) % 3.\n edge.prevEdge = fid * 3 + (eid + 2) % 3;\n _edges[edgeId] = edge;\n _faces[fid].edges[eid] = edgeId;\n _vertices[edge.startVertex].edges.push_back(edgeId);\n }\n }\n \/\/ Rescan all edges, and populate twin edges.\n for (unsigned int eid = 0; eid < _edges.size(); ++eid) {\n unsigned int startVertex = _edges[eid].startVertex;\n unsigned int endVertex = _edges[eid].endVertex;\n for (unsigned int revEdgeId : _vertices[endVertex].edges) {\n if (_edges[revEdgeId].endVertex == startVertex) {\n _edges[eid].twinEdge = revEdgeId;\n break;\n }\n _edges[eid].twinEdge = HD_INVALID_ID;\n }\n }\n }\n\n void TriangularMesh::_populateNormals() {\n if (_faceNormalMode != TriangularMesh::FaceNormalMode::USER_SPECIFIED) {\n \/\/ Calculate natual normals if face normal mdoe is not user-specified. Although this will\n \/\/ not be used for Phong interpolation mode, it is still reqired as an intermeidate step\n \/\/ to calculate averaged vertex normals.\n for (unsigned int fid = 0; fid < faceNum(); ++fid) {\n auto f = _faces[fid];\n Vector3 e0 = v(f.vertices[1]).pos - v(f.vertices[0]).pos;\n Vector3 e1 = v(f.vertices[2]).pos - v(f.vertices[1]).pos;\n Vector3 n = e0 ^ e1;\n assert(n.len2() > HD_EPSILON_TINY);\n _faces[fid].normal = n.normalize();\n }\n }\n if (_vertexNormalMode != TriangularMesh::VertexNormalMode::USER_SPECIFIED) {\n for (unsigned int vid = 0; vid < vertexNum(); ++vid) {\n Vector3 sumOfFaceNormals = Vector3::zero();\n \/\/ Vertex does not directly store all of its adjacent faces. Instead, we go through\n \/\/ every edge starts from it, whose belonging faces must be adjacent to this vertex.\n for (unsigned int eid : v(vid).edges) {\n sumOfFaceNormals += f(e(eid).face).normal;\n }\n \/\/ We don't need to devide sum vector by number of edges: normalization will just include\n \/\/ this procedure.\n _vertices[vid].normal = sumOfFaceNormals.normalize();\n }\n }\n }\n\n void TriangularMesh::_populateBoundingBox() {\n Vector3 minBound = Vector3::identity(HD_INFINITY);\n Vector3 maxBound = Vector3::identity(-HD_INFINITY);\n for (auto v : _vertices) {\n for (unsigned int i = 0; i < 3; ++i) {\n if (v.pos[i] < minBound[i]) {\n minBound[i] = v.pos[i];\n }\n if (v.pos[i] > maxBound[i]) {\n maxBound[i] = v.pos[i];\n }\n }\n }\n _boundingBox = BoundingBox3(minBound, maxBound);\n }\n\n bool TriangularMesh::isPopulated() const {\n return _isPopulated;\n }\n\n TriangularMesh::VertexNormalMode TriangularMesh::vertexNormalMode() const {\n return _vertexNormalMode;\n }\n\n TriangularMesh::FaceNormalMode TriangularMesh::faceNormalMode() const {\n return _faceNormalMode;\n }\n\n TriangularMesh::Builder::Builder(\n TriangularMesh::VertexNormalMode vertexNormalMode,\n TriangularMesh::FaceNormalMode faceNormalMode) {\n _instance = std::unique_ptr<TriangularMesh>(new TriangularMesh());\n _instance->_vertexNormalMode = vertexNormalMode;\n _instance->_faceNormalMode = faceNormalMode;\n }\n\n TriangularMesh::Builder& TriangularMesh::Builder::addVertex(const Vector3& v) {\n assert(_instance->vertexNormalMode() != TriangularMesh::VertexNormalMode::USER_SPECIFIED);\n assert(!_instance->isPopulated());\n _instance->_vertices.push_back(TriangularMesh::Vertex(v));\n return *this;\n }\n\n TriangularMesh::Builder& TriangularMesh::Builder::addVertex(\n const Vector3& v, const Vector3& vn) {\n assert(_instance->vertexNormalMode() == TriangularMesh::VertexNormalMode::USER_SPECIFIED);\n assert(!_instance->isPopulated());\n _instance->_vertices.push_back(TriangularMesh::Vertex(v, vn));\n return *this;\n }\n\n TriangularMesh::Builder& TriangularMesh::Builder::addFace(\n const std::array<unsigned int, 3>& face) {\n assert(_instance->faceNormalMode() != TriangularMesh::FaceNormalMode::USER_SPECIFIED);\n assert(!_instance->isPopulated());\n _instance->_faces.push_back(TriangularMesh::Face(face));\n return *this;\n }\n\n TriangularMesh::Builder& TriangularMesh::Builder::addFace(\n const std::array<unsigned int, 3>& face, const Vector3& fn) {\n assert(_instance->faceNormalMode() == TriangularMesh::FaceNormalMode::USER_SPECIFIED);\n assert(!_instance->isPopulated());\n _instance->_faces.push_back(TriangularMesh::Face(face, fn));\n return *this;\n }\n\n std::unique_ptr<TriangularMesh> TriangularMesh::Builder::build(bool populate) {\n if (populate && !_instance->isPopulated()) {\n _instance->populate();\n }\n auto ptr = std::unique_ptr<TriangularMesh>(_instance.release());\n return ptr;\n }\n}\n<commit_msg>Fix one more bug calculating bounding box of TriangularMesh.<commit_after>#include \"geometry\/triangular_mesh.h\"\n#include \"const.h\"\n#include <cassert>\n\nnamespace hd {\n TriangularMesh::TriangularMesh() {\n _vertices.clear();\n _edges.clear();\n _faces.clear();\n _isPopulated = false;\n _vertexNormalMode = TriangularMesh::VertexNormalMode::AVERAGED;\n _faceNormalMode = TriangularMesh::FaceNormalMode::FLAT;\n }\n\n TriangularMesh::TriangularMesh(const TriangularMesh& mesh) {\n _vertices.insert(_vertices.end(), mesh._vertices.begin(), mesh._vertices.end());\n _edges.insert(_edges.end(), mesh._edges.begin(), mesh._edges.end());\n _faces.insert(_faces.end(), mesh._faces.begin(), mesh._faces.end());\n _isPopulated = mesh._isPopulated;\n _boundingBox = mesh._boundingBox;\n _vertexNormalMode = mesh._vertexNormalMode;\n _faceNormalMode = mesh._faceNormalMode;\n }\n\n TriangularMesh::~TriangularMesh() {\n _vertices.clear();\n _edges.clear();\n _faces.clear();\n }\n\n TriangularMesh::Builder TriangularMesh::newBuilder(\n TriangularMesh::VertexNormalMode vertexNormalMode,\n TriangularMesh::FaceNormalMode faceNormalMode) {\n return TriangularMesh::Builder(vertexNormalMode, faceNormalMode);\n }\n\n TriangularMesh::Vertex TriangularMesh::v(unsigned int index) const {\n assert(index < vertexNum());\n return _vertices[index];\n }\n\n TriangularMesh::Face TriangularMesh::f(unsigned int index) const {\n assert(index < faceNum());\n return _faces[index];\n }\n\n TriangularMesh::Edge TriangularMesh::e(unsigned int index) const {\n assert(index < edgeNum());\n return _edges[index];\n }\n\n unsigned int TriangularMesh::vertexNum() const {\n return _vertices.size();\n }\n\n unsigned int TriangularMesh::edgeNum() const {\n return _edges.size();\n }\n\n unsigned int TriangularMesh::faceNum() const {\n return _faces.size();\n }\n\n Triangle3 TriangularMesh::triangle(unsigned int index) const {\n assert(isPopulated());\n assert(index < faceNum());\n auto f = _faces[index];\n auto faceVertices = std::array<Vector3, 3>();\n for (int vInd = 0; vInd < 3; ++vInd) {\n faceVertices[vInd] = v(f.vertices[vInd]).pos;\n }\n return Triangle3(faceVertices);\n }\n\n Vector3 TriangularMesh::normal(const TriangularMesh::MeshPoint& p) const {\n assert(isPopulated());\n assert(p.faceId < faceNum());\n if (_faceNormalMode != TriangularMesh::FaceNormalMode::PHONG) {\n return f(p.faceId).normal;\n }\n Vector3 avgNormal = Vector3::zero();\n for (unsigned int i = 0; i < 3; ++i) {\n avgNormal += p.params[i] * v(f(p.faceId).vertices[i]).pos;\n }\n return avgNormal.normalize();\n }\n\n\n BoundingBox3 TriangularMesh::boundingBox3() const {\n assert(isPopulated());\n return _boundingBox; \n }\n\n void TriangularMesh::populate() {\n assert(!isPopulated());\n _populateEdges();\n _populateNormals();\n _populateBoundingBox();\n _isPopulated = true;\n }\n\n void TriangularMesh::_populateEdges() {\n \/\/ Generate all edges. Update edge lists of vertices and faces.\n _edges.resize(_faces.size() * 3);\n for (unsigned int fid = 0; fid < _faces.size(); ++fid) {\n auto face = _faces[fid];\n for (unsigned int eid = 0; eid < 3; ++eid) {\n unsigned int edgeId = fid * 3 + eid;\n TriangularMesh::Edge edge = TriangularMesh::Edge();\n edge.startVertex = face.vertices[eid];\n edge.endVertex = face.vertices[(eid + 1) % 3];\n edge.face = fid;\n edge.nextEdge = fid * 3 + (eid + 1) % 3;\n \/\/ prev edge should be (eid - 1) % 3. To avoid overflow when eid is 0, we instead\n \/\/ use (eid + 2) % 3.\n edge.prevEdge = fid * 3 + (eid + 2) % 3;\n _edges[edgeId] = edge;\n _faces[fid].edges[eid] = edgeId;\n _vertices[edge.startVertex].edges.push_back(edgeId);\n }\n }\n \/\/ Rescan all edges, and populate twin edges.\n for (unsigned int eid = 0; eid < _edges.size(); ++eid) {\n unsigned int startVertex = _edges[eid].startVertex;\n unsigned int endVertex = _edges[eid].endVertex;\n for (unsigned int revEdgeId : _vertices[endVertex].edges) {\n if (_edges[revEdgeId].endVertex == startVertex) {\n _edges[eid].twinEdge = revEdgeId;\n break;\n }\n _edges[eid].twinEdge = HD_INVALID_ID;\n }\n }\n }\n\n void TriangularMesh::_populateNormals() {\n if (_faceNormalMode != TriangularMesh::FaceNormalMode::USER_SPECIFIED) {\n \/\/ Calculate natual normals if face normal mdoe is not user-specified. Although this will\n \/\/ not be used for Phong interpolation mode, it is still reqired as an intermeidate step\n \/\/ to calculate averaged vertex normals.\n for (unsigned int fid = 0; fid < faceNum(); ++fid) {\n auto f = _faces[fid];\n Vector3 e0 = v(f.vertices[1]).pos - v(f.vertices[0]).pos;\n Vector3 e1 = v(f.vertices[2]).pos - v(f.vertices[1]).pos;\n Vector3 n = e0 ^ e1;\n assert(n.len2() > HD_EPSILON_TINY);\n _faces[fid].normal = n.normalize();\n }\n }\n if (_vertexNormalMode != TriangularMesh::VertexNormalMode::USER_SPECIFIED) {\n for (unsigned int vid = 0; vid < vertexNum(); ++vid) {\n Vector3 sumOfFaceNormals = Vector3::zero();\n \/\/ Vertex does not directly store all of its adjacent faces. Instead, we go through\n \/\/ every edge starts from it, whose belonging faces must be adjacent to this vertex.\n for (unsigned int eid : v(vid).edges) {\n sumOfFaceNormals += f(e(eid).face).normal;\n }\n \/\/ We don't need to devide sum vector by number of edges: normalization will just include\n \/\/ this procedure.\n _vertices[vid].normal = sumOfFaceNormals.normalize();\n }\n }\n }\n\n void TriangularMesh::_populateBoundingBox() {\n if (_vertices.empty()) {\n _boundingBox = BoundingBox3();\n return;\n }\n Vector3 minBound = Vector3::identity(HD_INFINITY);\n Vector3 maxBound = Vector3::identity(-HD_INFINITY);\n for (auto v : _vertices) {\n for (unsigned int i = 0; i < 3; ++i) {\n if (v.pos[i] < minBound[i]) {\n minBound[i] = v.pos[i];\n }\n if (v.pos[i] > maxBound[i]) {\n maxBound[i] = v.pos[i];\n }\n }\n }\n _boundingBox = BoundingBox3(minBound, maxBound);\n }\n\n bool TriangularMesh::isPopulated() const {\n return _isPopulated;\n }\n\n TriangularMesh::VertexNormalMode TriangularMesh::vertexNormalMode() const {\n return _vertexNormalMode;\n }\n\n TriangularMesh::FaceNormalMode TriangularMesh::faceNormalMode() const {\n return _faceNormalMode;\n }\n\n TriangularMesh::Builder::Builder(\n TriangularMesh::VertexNormalMode vertexNormalMode,\n TriangularMesh::FaceNormalMode faceNormalMode) {\n _instance = std::unique_ptr<TriangularMesh>(new TriangularMesh());\n _instance->_vertexNormalMode = vertexNormalMode;\n _instance->_faceNormalMode = faceNormalMode;\n }\n\n TriangularMesh::Builder& TriangularMesh::Builder::addVertex(const Vector3& v) {\n assert(_instance->vertexNormalMode() != TriangularMesh::VertexNormalMode::USER_SPECIFIED);\n assert(!_instance->isPopulated());\n _instance->_vertices.push_back(TriangularMesh::Vertex(v));\n return *this;\n }\n\n TriangularMesh::Builder& TriangularMesh::Builder::addVertex(\n const Vector3& v, const Vector3& vn) {\n assert(_instance->vertexNormalMode() == TriangularMesh::VertexNormalMode::USER_SPECIFIED);\n assert(!_instance->isPopulated());\n _instance->_vertices.push_back(TriangularMesh::Vertex(v, vn));\n return *this;\n }\n\n TriangularMesh::Builder& TriangularMesh::Builder::addFace(\n const std::array<unsigned int, 3>& face) {\n assert(_instance->faceNormalMode() != TriangularMesh::FaceNormalMode::USER_SPECIFIED);\n assert(!_instance->isPopulated());\n _instance->_faces.push_back(TriangularMesh::Face(face));\n return *this;\n }\n\n TriangularMesh::Builder& TriangularMesh::Builder::addFace(\n const std::array<unsigned int, 3>& face, const Vector3& fn) {\n assert(_instance->faceNormalMode() == TriangularMesh::FaceNormalMode::USER_SPECIFIED);\n assert(!_instance->isPopulated());\n _instance->_faces.push_back(TriangularMesh::Face(face, fn));\n return *this;\n }\n\n std::unique_ptr<TriangularMesh> TriangularMesh::Builder::build(bool populate) {\n if (populate && !_instance->isPopulated()) {\n _instance->populate();\n }\n auto ptr = std::unique_ptr<TriangularMesh>(_instance.release());\n return ptr;\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/**************************************************************************\n**\n** This file is part of Qt Creator\n**\n** Copyright (c) 2010 Nokia Corporation and\/or its subsidiary(-ies).\n**\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n** Commercial Usage\n**\n** Licensees holding valid Qt Commercial licenses may use this file in\n** accordance with the Qt Commercial License Agreement provided with the\n** Software or, alternatively, in accordance with the terms contained in\n** a written agreement between you and Nokia.\n**\n** GNU Lesser General Public License Usage\n**\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** If you are unsure which license is appropriate for your use, please\n** contact the sales department at http:\/\/qt.nokia.com\/contact.\n**\n**************************************************************************\/\n\n#include \"gccetoolchain.h\"\n#include \"qt4project.h\"\n\n#include <utils\/qtcassert.h>\n\n#include <QtCore\/QDir>\n#include <QtCore\/QProcess>\n#include <QtCore\/QtDebug>\n\nenum { debug = 0 };\n\nusing namespace ProjectExplorer;\nusing namespace Qt4ProjectManager::Internal;\n\n\/\/ Locate the compiler via path.\nstatic QString gcceCommand(const QString &dir)\n{\n ProjectExplorer::Environment env = ProjectExplorer::Environment::systemEnvironment();\n if (!dir.isEmpty()) {\n env.prependOrSetPath(dir + QLatin1String(\"\/bin\"));\n env.prependOrSetPath(dir);\n }\n QString gcce = QLatin1String(\"arm-none-symbianelf-gcc\");\n#ifdef Q_OS_WIN\n gcce += QLatin1String(\".exe\");\n#endif\n const QString rc = env.searchInPath(gcce);\n if (debug && rc.isEmpty()) {\n const QString msg = QString::fromLatin1(\"GCCEToolChain: Unable to locate '%1' in '%2' (GCCE root: '%3')\")\n .arg(gcce, env.value(QLatin1String(\"PATH\")), dir);\n qWarning(\"%s\", qPrintable(msg));\n return gcce;\n }\n return rc;\n}\n\n\/\/ The GccToolChain base class constructor wants to know the gcc command\nGCCEToolChain *GCCEToolChain::create(const S60Devices::Device &device,\n const QString &gcceRoot,\n ProjectExplorer::ToolChain::ToolChainType type)\n{\n const QString gccCommand = gcceCommand(gcceRoot);\n const QFileInfo gccCommandFi(gccCommand);\n const QString binPath = gccCommandFi.isRelative() ? QString() : gccCommandFi.absolutePath();\n return new GCCEToolChain(device, binPath, gccCommand, type);\n}\n\nGCCEToolChain::GCCEToolChain(const S60Devices::Device &device,\n const QString &gcceBinPath,\n const QString &gcceCommand,\n ProjectExplorer::ToolChain::ToolChainType type) :\n GccToolChain(gcceCommand),\n m_mixin(device),\n m_type(type),\n m_gcceBinPath(gcceBinPath)\n{\n QTC_ASSERT(m_type == ProjectExplorer::ToolChain::GCCE || m_type == ProjectExplorer::ToolChain::GCCE_GNUPOC, return)\n if (debug)\n qDebug() << \"GCCEToolChain on\" << m_type << gcceCommand << gcceBinPath << m_mixin.device();\n}\n\nToolChain::ToolChainType GCCEToolChain::type() const\n{\n return m_type;\n}\n\nQByteArray GCCEToolChain::predefinedMacros()\n{\n if (m_predefinedMacros.isEmpty()) {\n ProjectExplorer::GccToolChain::predefinedMacros();\n m_predefinedMacros += \"\\n\"\n \"#define __GCCE__\\n\"\n \"#define __SYMBIAN32__\\n\";\n }\n return m_predefinedMacros;\n}\n\nQList<HeaderPath> GCCEToolChain::systemHeaderPaths()\n{\n if (m_systemHeaderPaths.isEmpty()) {\n GccToolChain::systemHeaderPaths();\n switch (m_type) {\n case ProjectExplorer::ToolChain::GCCE:\n m_systemHeaderPaths += m_mixin.epocHeaderPaths();\n break;\n case ProjectExplorer::ToolChain::GCCE_GNUPOC:\n m_systemHeaderPaths += m_mixin.gnuPocHeaderPaths();\n break;\n default:\n break;\n }\n }\n return m_systemHeaderPaths;\n}\n\nvoid GCCEToolChain::addToEnvironment(ProjectExplorer::Environment &env)\n{\n if (debug)\n qDebug() << \"GCCEToolChain::addToEnvironment\" << m_type << gcc() << m_gcceBinPath<< m_mixin.device();\n\n if (!m_gcceBinPath.isEmpty())\n env.prependOrSetPath(m_gcceBinPath);\n switch (m_type) {\n case ProjectExplorer::ToolChain::GCCE:\n m_mixin.addEpocToEnvironment(&env);\n break;\n case ProjectExplorer::ToolChain::GCCE_GNUPOC:\n m_mixin.addGnuPocToEnvironment(&env);\n break;\n default:\n break;\n }\n QString version = gcceVersion();\n version = version.remove(QLatin1Char('.'));\n env.set(QString::fromLatin1(\"SBS_GCCE\") + version + QLatin1String(\"BIN\"), QDir::toNativeSeparators(m_gcceBinPath));\n}\n\nQString GCCEToolChain::makeCommand() const\n{\n return QLatin1String(\"make\");\n}\n\nbool GCCEToolChain::equals(ToolChain *otherIn) const\n{\n if (otherIn->type() != type())\n return false;\n const GCCEToolChain *other = static_cast<const GCCEToolChain *>(otherIn);\n return m_mixin == other->m_mixin\n && m_gcceBinPath == other->m_gcceBinPath\n && gcc() == other->gcc();\n}\n\nQString GCCEToolChain::gcceVersion() const\n{\n if (m_gcceVersion.isEmpty()) {\n QString command = gcceCommand(m_gcceBinPath);\n if (command.isEmpty())\n return QString();\n QProcess gxx;\n QStringList arguments;\n arguments << QLatin1String(\"--version\");\n ProjectExplorer::Environment env = ProjectExplorer::Environment::systemEnvironment();\n env.set(QLatin1String(\"LC_ALL\"), QLatin1String(\"C\")); \/\/override current locale settings\n gxx.setEnvironment(env.toStringList());\n gxx.setReadChannelMode(QProcess::MergedChannels);\n gxx.start(command, arguments);\n gxx.closeWriteChannel();\n gxx.waitForFinished();\n\n QString line;\n if (gxx.canReadLine()) {\n line = gxx.readLine();\n qDebug() << \"GCCVersion:\" << line;\n QRegExp version(\"\\\\s((\\\\d+)\\\\.(\\\\d+)\\\\.(\\\\d+))\\\\s\");\n if (line.indexOf(version) >= -1) {\n qDebug() << \" MATCHED!\";\n m_gcceVersion = version.cap(1);\n }\n }\n }\n return m_gcceVersion;\n}\n<commit_msg>Quiten debug messages<commit_after>\/**************************************************************************\n**\n** This file is part of Qt Creator\n**\n** Copyright (c) 2010 Nokia Corporation and\/or its subsidiary(-ies).\n**\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n** Commercial Usage\n**\n** Licensees holding valid Qt Commercial licenses may use this file in\n** accordance with the Qt Commercial License Agreement provided with the\n** Software or, alternatively, in accordance with the terms contained in\n** a written agreement between you and Nokia.\n**\n** GNU Lesser General Public License Usage\n**\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** If you are unsure which license is appropriate for your use, please\n** contact the sales department at http:\/\/qt.nokia.com\/contact.\n**\n**************************************************************************\/\n\n#include \"gccetoolchain.h\"\n#include \"qt4project.h\"\n\n#include <utils\/qtcassert.h>\n\n#include <QtCore\/QDir>\n#include <QtCore\/QProcess>\n#include <QtCore\/QtDebug>\n\nenum { debug = 0 };\n\nusing namespace ProjectExplorer;\nusing namespace Qt4ProjectManager::Internal;\n\n\/\/ Locate the compiler via path.\nstatic QString gcceCommand(const QString &dir)\n{\n ProjectExplorer::Environment env = ProjectExplorer::Environment::systemEnvironment();\n if (!dir.isEmpty()) {\n env.prependOrSetPath(dir + QLatin1String(\"\/bin\"));\n env.prependOrSetPath(dir);\n }\n QString gcce = QLatin1String(\"arm-none-symbianelf-gcc\");\n#ifdef Q_OS_WIN\n gcce += QLatin1String(\".exe\");\n#endif\n const QString rc = env.searchInPath(gcce);\n if (debug && rc.isEmpty()) {\n const QString msg = QString::fromLatin1(\"GCCEToolChain: Unable to locate '%1' in '%2' (GCCE root: '%3')\")\n .arg(gcce, env.value(QLatin1String(\"PATH\")), dir);\n qWarning(\"%s\", qPrintable(msg));\n return gcce;\n }\n return rc;\n}\n\n\/\/ The GccToolChain base class constructor wants to know the gcc command\nGCCEToolChain *GCCEToolChain::create(const S60Devices::Device &device,\n const QString &gcceRoot,\n ProjectExplorer::ToolChain::ToolChainType type)\n{\n const QString gccCommand = gcceCommand(gcceRoot);\n const QFileInfo gccCommandFi(gccCommand);\n const QString binPath = gccCommandFi.isRelative() ? QString() : gccCommandFi.absolutePath();\n return new GCCEToolChain(device, binPath, gccCommand, type);\n}\n\nGCCEToolChain::GCCEToolChain(const S60Devices::Device &device,\n const QString &gcceBinPath,\n const QString &gcceCommand,\n ProjectExplorer::ToolChain::ToolChainType type) :\n GccToolChain(gcceCommand),\n m_mixin(device),\n m_type(type),\n m_gcceBinPath(gcceBinPath)\n{\n QTC_ASSERT(m_type == ProjectExplorer::ToolChain::GCCE || m_type == ProjectExplorer::ToolChain::GCCE_GNUPOC, return)\n if (debug)\n qDebug() << \"GCCEToolChain on\" << m_type << gcceCommand << gcceBinPath << m_mixin.device();\n}\n\nToolChain::ToolChainType GCCEToolChain::type() const\n{\n return m_type;\n}\n\nQByteArray GCCEToolChain::predefinedMacros()\n{\n if (m_predefinedMacros.isEmpty()) {\n ProjectExplorer::GccToolChain::predefinedMacros();\n m_predefinedMacros += \"\\n\"\n \"#define __GCCE__\\n\"\n \"#define __SYMBIAN32__\\n\";\n }\n return m_predefinedMacros;\n}\n\nQList<HeaderPath> GCCEToolChain::systemHeaderPaths()\n{\n if (m_systemHeaderPaths.isEmpty()) {\n GccToolChain::systemHeaderPaths();\n switch (m_type) {\n case ProjectExplorer::ToolChain::GCCE:\n m_systemHeaderPaths += m_mixin.epocHeaderPaths();\n break;\n case ProjectExplorer::ToolChain::GCCE_GNUPOC:\n m_systemHeaderPaths += m_mixin.gnuPocHeaderPaths();\n break;\n default:\n break;\n }\n }\n return m_systemHeaderPaths;\n}\n\nvoid GCCEToolChain::addToEnvironment(ProjectExplorer::Environment &env)\n{\n if (debug)\n qDebug() << \"GCCEToolChain::addToEnvironment\" << m_type << gcc() << m_gcceBinPath<< m_mixin.device();\n\n if (!m_gcceBinPath.isEmpty())\n env.prependOrSetPath(m_gcceBinPath);\n switch (m_type) {\n case ProjectExplorer::ToolChain::GCCE:\n m_mixin.addEpocToEnvironment(&env);\n break;\n case ProjectExplorer::ToolChain::GCCE_GNUPOC:\n m_mixin.addGnuPocToEnvironment(&env);\n break;\n default:\n break;\n }\n QString version = gcceVersion();\n version = version.remove(QLatin1Char('.'));\n env.set(QString::fromLatin1(\"SBS_GCCE\") + version + QLatin1String(\"BIN\"), QDir::toNativeSeparators(m_gcceBinPath));\n}\n\nQString GCCEToolChain::makeCommand() const\n{\n return QLatin1String(\"make\");\n}\n\nbool GCCEToolChain::equals(ToolChain *otherIn) const\n{\n if (otherIn->type() != type())\n return false;\n const GCCEToolChain *other = static_cast<const GCCEToolChain *>(otherIn);\n return m_mixin == other->m_mixin\n && m_gcceBinPath == other->m_gcceBinPath\n && gcc() == other->gcc();\n}\n\nQString GCCEToolChain::gcceVersion() const\n{\n if (m_gcceVersion.isEmpty()) {\n QString command = gcceCommand(m_gcceBinPath);\n if (command.isEmpty())\n return QString();\n QProcess gxx;\n QStringList arguments;\n arguments << QLatin1String(\"-dumpversion\");\n ProjectExplorer::Environment env = ProjectExplorer::Environment::systemEnvironment();\n env.set(QLatin1String(\"LC_ALL\"), QLatin1String(\"C\")); \/\/override current locale settings\n gxx.setEnvironment(env.toStringList());\n gxx.setReadChannelMode(QProcess::MergedChannels);\n gxx.start(command, arguments);\n gxx.closeWriteChannel();\n gxx.waitForFinished();\n\n QString line;\n if (gxx.canReadLine()) {\n line = gxx.readLine();\n m_gcceVersion = line.trimmed();\n }\n }\n return m_gcceVersion;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2017 Advanced Micro Devices, Inc. All rights reserved.\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n\/\/ THE SOFTWARE.\n\n#ifndef ROCRAND_RNG_MRG32K3A_H_\n#define ROCRAND_RNG_MRG32K3A_H_\n\n#include <algorithm>\n#include <hip\/hip_runtime.h>\n\n#include <rocrand.h>\n\n#include \"generator_type.hpp\"\n#include \"device_engines.hpp\"\n#include \"distributions.hpp\"\n\nnamespace rocrand_host {\nnamespace detail {\n\n typedef ::rocrand_device::mrg32k3a_engine mrg32k3a_device_engine;\n\n __global__\n void init_engines_kernel(mrg32k3a_device_engine * engines,\n unsigned long long seed,\n unsigned long long offset)\n {\n const unsigned int engine_id = hipBlockIdx_x * hipBlockDim_x + hipThreadIdx_x;\n engines[engine_id] = mrg32k3a_device_engine(seed, engine_id, offset);\n }\n\n template<class Type, class Distribution>\n __global__\n void generate_kernel(mrg32k3a_device_engine * engines,\n Type * data, const size_t n,\n const Distribution distribution)\n {\n const unsigned int engine_id = hipBlockIdx_x * hipBlockDim_x + hipThreadIdx_x;\n unsigned int index = engine_id;\n unsigned int stride = hipGridDim_x * hipBlockDim_x;\n\n \/\/ Load device engine\n mrg32k3a_device_engine engine = engines[engine_id];\n\n while(index < n)\n {\n data[index] = distribution(engine());\n \/\/ Next position\n index += stride;\n }\n\n \/\/ Save engine with its state\n engines[engine_id] = engine;\n }\n\n template<class RealType, class Distribution>\n __global__\n void generate_normal_kernel(mrg32k3a_device_engine * engines,\n RealType * data, const size_t n,\n Distribution distribution)\n {\n typedef decltype(distribution(engines->next(), engines->next())) RealType2;\n\n const unsigned int engine_id = hipBlockIdx_x * hipBlockDim_x + hipThreadIdx_x;\n unsigned int index = engine_id;\n unsigned int stride = hipGridDim_x * hipBlockDim_x;\n\n \/\/ Load device engine\n mrg32k3a_device_engine engine = engines[engine_id];\n\n RealType2 * data2 = (RealType2 *)data;\n while(index < (n \/ 2))\n {\n data2[index] = distribution(engine(), engine());\n \/\/ Next position\n index += stride;\n }\n\n \/\/ First work-item saves the tail when n is not a multiple of 2\n if(engine_id == 0 && (n & 1) > 0)\n {\n RealType2 result = distribution(engine(), engine());\n \/\/ Save the tail\n data[n - 1] = result.x;\n }\n\n \/\/ Save engine with its state\n engines[engine_id] = engine;\n }\n\n} \/\/ end namespace detail\n} \/\/ end namespace rocrand_host\n\nclass rocrand_mrg32k3a : public rocrand_generator_type<ROCRAND_RNG_PSEUDO_MRG32K3A>\n{\npublic:\n using base_type = rocrand_generator_type<ROCRAND_RNG_PSEUDO_MRG32K3A>;\n using engine_type = ::rocrand_host::detail::mrg32k3a_device_engine;\n\n rocrand_mrg32k3a(unsigned long long seed = 12345,\n unsigned long long offset = 0,\n hipStream_t stream = 0)\n : base_type(seed, offset, stream),\n m_engines_initialized(false), m_engines(NULL), m_engines_size(1024 * 256)\n {\n \/\/ Allocate device random number engines\n auto error = hipMalloc(&m_engines, sizeof(engine_type) * m_engines_size);\n if(error != hipSuccess)\n {\n throw ROCRAND_STATUS_ALLOCATION_FAILED;\n }\n if(m_seed == 0)\n {\n m_seed = ROCRAND_MRG32K3A_DEFAULT_SEED;\n }\n }\n\n ~rocrand_mrg32k3a()\n {\n hipFree(m_engines);\n }\n\n void reset()\n {\n m_engines_initialized = false;\n }\n\n \/\/\/ Changes seed to \\p seed and resets generator state.\n \/\/\/\n \/\/\/ New seed value should not be zero. If \\p seed_value is equal\n \/\/\/ zero, value \\p ROCRAND_MRG32K3A_DEFAULT_SEED is used instead.\n void set_seed(unsigned long long seed)\n {\n if(seed == 0)\n {\n seed = ROCRAND_MRG32K3A_DEFAULT_SEED;\n }\n m_seed = seed;\n m_engines_initialized = false;\n }\n\n void set_offset(unsigned long long offset)\n {\n m_offset = offset;\n m_engines_initialized = false;\n }\n\n rocrand_status init()\n {\n if (m_engines_initialized)\n return ROCRAND_STATUS_SUCCESS;\n\n #ifdef __HIP_PLATFORM_NVCC__\n const uint32_t threads = 128;\n const uint32_t max_blocks = 128;\n #else\n const uint32_t threads = 256;\n const uint32_t max_blocks = 1024;\n #endif\n const uint32_t blocks = max_blocks;\n\n hipLaunchKernelGGL(\n HIP_KERNEL_NAME(rocrand_host::detail::init_engines_kernel),\n dim3(blocks), dim3(threads), 0, m_stream,\n m_engines, m_seed, m_offset\n );\n \/\/ Check kernel status\n if(hipPeekAtLastError() != hipSuccess)\n return ROCRAND_STATUS_LAUNCH_FAILURE;\n\n m_engines_initialized = true;\n\n return ROCRAND_STATUS_SUCCESS;\n }\n\n template<class T, class Distribution = mrg_uniform_distribution<T> >\n rocrand_status generate(T * data, size_t data_size,\n const Distribution& distribution = Distribution())\n {\n rocrand_status status = init();\n if (status != ROCRAND_STATUS_SUCCESS)\n return status;\n\n #ifdef __HIP_PLATFORM_NVCC__\n const uint32_t threads = 128;\n const uint32_t max_blocks = 128; \/\/ 512\n #else\n const uint32_t threads = 256;\n const uint32_t max_blocks = 1024;\n #endif\n const uint32_t blocks = max_blocks;\n\n hipLaunchKernelGGL(\n HIP_KERNEL_NAME(rocrand_host::detail::generate_kernel),\n dim3(blocks), dim3(threads), 0, m_stream,\n m_engines, data, data_size, distribution\n );\n \/\/ Check kernel status\n if(hipPeekAtLastError() != hipSuccess)\n return ROCRAND_STATUS_LAUNCH_FAILURE;\n\n return ROCRAND_STATUS_SUCCESS;\n }\n\n template<class T>\n rocrand_status generate_uniform(T * data, size_t data_size)\n {\n mrg_uniform_distribution<T> udistribution;\n return generate(data, data_size, udistribution);\n }\n\n template<class T>\n rocrand_status generate_normal(T * data, size_t data_size, T stddev, T mean)\n {\n rocrand_status status = init();\n if (status != ROCRAND_STATUS_SUCCESS)\n return status;\n\n #ifdef __HIP_PLATFORM_NVCC__\n const uint32_t threads = 128;\n const uint32_t max_blocks = 128; \/\/ 512\n #else\n const uint32_t threads = 256;\n const uint32_t max_blocks = 1024;\n #endif\n const uint32_t blocks = max_blocks;\n\n mrg_normal_distribution<T> distribution(mean, stddev);\n\n hipLaunchKernelGGL(\n HIP_KERNEL_NAME(rocrand_host::detail::generate_normal_kernel),\n dim3(blocks), dim3(threads), 0, m_stream,\n m_engines, data, data_size, distribution\n );\n \/\/ Check kernel status\n if(hipPeekAtLastError() != hipSuccess)\n return ROCRAND_STATUS_LAUNCH_FAILURE;\n\n return ROCRAND_STATUS_SUCCESS;\n }\n\n template<class T>\n rocrand_status generate_log_normal(T * data, size_t data_size, T stddev, T mean)\n {\n rocrand_status status = init();\n if (status != ROCRAND_STATUS_SUCCESS)\n return status;\n\n #ifdef __HIP_PLATFORM_NVCC__\n const uint32_t threads = 128;\n const uint32_t max_blocks = 128; \/\/ 512\n #else\n const uint32_t threads = 256;\n const uint32_t max_blocks = 1024;\n #endif\n const uint32_t blocks = max_blocks;\n\n mrg_log_normal_distribution<T> distribution(mean, stddev);\n\n hipLaunchKernelGGL(\n HIP_KERNEL_NAME(rocrand_host::detail::generate_normal_kernel),\n dim3(blocks), dim3(threads), 0, m_stream,\n m_engines, data, data_size, distribution\n );\n \/\/ Check kernel status\n if(hipPeekAtLastError() != hipSuccess)\n return ROCRAND_STATUS_LAUNCH_FAILURE;\n\n return ROCRAND_STATUS_SUCCESS;\n }\n\n rocrand_status generate_poisson(unsigned int * data, size_t data_size, double lambda)\n {\n try\n {\n poisson.set_lambda(lambda);\n }\n catch(rocrand_status status)\n {\n return status;\n }\n return generate(data, data_size, poisson.dis);\n }\n\nprivate:\n bool m_engines_initialized;\n engine_type * m_engines;\n size_t m_engines_size;\n\n \/\/ For caching of Poisson for consecutive generations with the same lambda\n poisson_distribution_manager<> poisson;\n\n \/\/ m_seed from base_type\n \/\/ m_offset from base_type\n};\n\n#endif \/\/ ROCRAND_RNG_MRG32K3A_H_\n<commit_msg>Reduced internal memory usage by MRG32K3A<commit_after>\/\/ Copyright (c) 2017 Advanced Micro Devices, Inc. All rights reserved.\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n\/\/ THE SOFTWARE.\n\n#ifndef ROCRAND_RNG_MRG32K3A_H_\n#define ROCRAND_RNG_MRG32K3A_H_\n\n#include <algorithm>\n#include <hip\/hip_runtime.h>\n\n#include <rocrand.h>\n\n#include \"generator_type.hpp\"\n#include \"device_engines.hpp\"\n#include \"distributions.hpp\"\n\nnamespace rocrand_host {\nnamespace detail {\n\n typedef ::rocrand_device::mrg32k3a_engine mrg32k3a_device_engine;\n\n __global__\n void init_engines_kernel(mrg32k3a_device_engine * engines,\n unsigned long long seed,\n unsigned long long offset)\n {\n const unsigned int engine_id = hipBlockIdx_x * hipBlockDim_x + hipThreadIdx_x;\n engines[engine_id] = mrg32k3a_device_engine(seed, engine_id, offset);\n }\n\n template<class Type, class Distribution>\n __global__\n void generate_kernel(mrg32k3a_device_engine * engines,\n Type * data, const size_t n,\n const Distribution distribution)\n {\n const unsigned int engine_id = hipBlockIdx_x * hipBlockDim_x + hipThreadIdx_x;\n unsigned int index = engine_id;\n unsigned int stride = hipGridDim_x * hipBlockDim_x;\n\n \/\/ Load device engine\n mrg32k3a_device_engine engine = engines[engine_id];\n\n while(index < n)\n {\n data[index] = distribution(engine());\n \/\/ Next position\n index += stride;\n }\n\n \/\/ Save engine with its state\n engines[engine_id] = engine;\n }\n\n template<class RealType, class Distribution>\n __global__\n void generate_normal_kernel(mrg32k3a_device_engine * engines,\n RealType * data, const size_t n,\n Distribution distribution)\n {\n typedef decltype(distribution(engines->next(), engines->next())) RealType2;\n\n const unsigned int engine_id = hipBlockIdx_x * hipBlockDim_x + hipThreadIdx_x;\n unsigned int index = engine_id;\n unsigned int stride = hipGridDim_x * hipBlockDim_x;\n\n \/\/ Load device engine\n mrg32k3a_device_engine engine = engines[engine_id];\n\n RealType2 * data2 = (RealType2 *)data;\n while(index < (n \/ 2))\n {\n data2[index] = distribution(engine(), engine());\n \/\/ Next position\n index += stride;\n }\n\n \/\/ First work-item saves the tail when n is not a multiple of 2\n if(engine_id == 0 && (n & 1) > 0)\n {\n RealType2 result = distribution(engine(), engine());\n \/\/ Save the tail\n data[n - 1] = result.x;\n }\n\n \/\/ Save engine with its state\n engines[engine_id] = engine;\n }\n\n} \/\/ end namespace detail\n} \/\/ end namespace rocrand_host\n\nclass rocrand_mrg32k3a : public rocrand_generator_type<ROCRAND_RNG_PSEUDO_MRG32K3A>\n{\npublic:\n using base_type = rocrand_generator_type<ROCRAND_RNG_PSEUDO_MRG32K3A>;\n using engine_type = ::rocrand_host::detail::mrg32k3a_device_engine;\n\n rocrand_mrg32k3a(unsigned long long seed = 12345,\n unsigned long long offset = 0,\n hipStream_t stream = 0)\n : base_type(seed, offset, stream),\n m_engines_initialized(false), m_engines(NULL), m_engines_size(256 * 256)\n {\n \/\/ Allocate device random number engines\n auto error = hipMalloc(&m_engines, sizeof(engine_type) * m_engines_size);\n if(error != hipSuccess)\n {\n throw ROCRAND_STATUS_ALLOCATION_FAILED;\n }\n if(m_seed == 0)\n {\n m_seed = ROCRAND_MRG32K3A_DEFAULT_SEED;\n }\n }\n\n ~rocrand_mrg32k3a()\n {\n hipFree(m_engines);\n }\n\n void reset()\n {\n m_engines_initialized = false;\n }\n\n \/\/\/ Changes seed to \\p seed and resets generator state.\n \/\/\/\n \/\/\/ New seed value should not be zero. If \\p seed_value is equal\n \/\/\/ zero, value \\p ROCRAND_MRG32K3A_DEFAULT_SEED is used instead.\n void set_seed(unsigned long long seed)\n {\n if(seed == 0)\n {\n seed = ROCRAND_MRG32K3A_DEFAULT_SEED;\n }\n m_seed = seed;\n m_engines_initialized = false;\n }\n\n void set_offset(unsigned long long offset)\n {\n m_offset = offset;\n m_engines_initialized = false;\n }\n\n rocrand_status init()\n {\n if (m_engines_initialized)\n return ROCRAND_STATUS_SUCCESS;\n\n #ifdef __HIP_PLATFORM_NVCC__\n const uint32_t threads = 128;\n const uint32_t max_blocks = 128;\n #else\n const uint32_t threads = 256;\n const uint32_t max_blocks = 256;\n #endif\n const uint32_t blocks = max_blocks;\n\n hipLaunchKernelGGL(\n HIP_KERNEL_NAME(rocrand_host::detail::init_engines_kernel),\n dim3(blocks), dim3(threads), 0, m_stream,\n m_engines, m_seed, m_offset\n );\n \/\/ Check kernel status\n if(hipPeekAtLastError() != hipSuccess)\n return ROCRAND_STATUS_LAUNCH_FAILURE;\n\n m_engines_initialized = true;\n\n return ROCRAND_STATUS_SUCCESS;\n }\n\n template<class T, class Distribution = mrg_uniform_distribution<T> >\n rocrand_status generate(T * data, size_t data_size,\n const Distribution& distribution = Distribution())\n {\n rocrand_status status = init();\n if (status != ROCRAND_STATUS_SUCCESS)\n return status;\n\n #ifdef __HIP_PLATFORM_NVCC__\n const uint32_t threads = 128;\n const uint32_t max_blocks = 128; \/\/ 512\n #else\n const uint32_t threads = 256;\n const uint32_t max_blocks = 256;\n #endif\n const uint32_t blocks = max_blocks;\n\n hipLaunchKernelGGL(\n HIP_KERNEL_NAME(rocrand_host::detail::generate_kernel),\n dim3(blocks), dim3(threads), 0, m_stream,\n m_engines, data, data_size, distribution\n );\n \/\/ Check kernel status\n if(hipPeekAtLastError() != hipSuccess)\n return ROCRAND_STATUS_LAUNCH_FAILURE;\n\n return ROCRAND_STATUS_SUCCESS;\n }\n\n template<class T>\n rocrand_status generate_uniform(T * data, size_t data_size)\n {\n mrg_uniform_distribution<T> udistribution;\n return generate(data, data_size, udistribution);\n }\n\n template<class T>\n rocrand_status generate_normal(T * data, size_t data_size, T stddev, T mean)\n {\n rocrand_status status = init();\n if (status != ROCRAND_STATUS_SUCCESS)\n return status;\n\n #ifdef __HIP_PLATFORM_NVCC__\n const uint32_t threads = 128;\n const uint32_t max_blocks = 128; \/\/ 512\n #else\n const uint32_t threads = 256;\n const uint32_t max_blocks = 256;\n #endif\n const uint32_t blocks = max_blocks;\n\n mrg_normal_distribution<T> distribution(mean, stddev);\n\n hipLaunchKernelGGL(\n HIP_KERNEL_NAME(rocrand_host::detail::generate_normal_kernel),\n dim3(blocks), dim3(threads), 0, m_stream,\n m_engines, data, data_size, distribution\n );\n \/\/ Check kernel status\n if(hipPeekAtLastError() != hipSuccess)\n return ROCRAND_STATUS_LAUNCH_FAILURE;\n\n return ROCRAND_STATUS_SUCCESS;\n }\n\n template<class T>\n rocrand_status generate_log_normal(T * data, size_t data_size, T stddev, T mean)\n {\n rocrand_status status = init();\n if (status != ROCRAND_STATUS_SUCCESS)\n return status;\n\n #ifdef __HIP_PLATFORM_NVCC__\n const uint32_t threads = 128;\n const uint32_t max_blocks = 128; \/\/ 512\n #else\n const uint32_t threads = 256;\n const uint32_t max_blocks = 256;\n #endif\n const uint32_t blocks = max_blocks;\n\n mrg_log_normal_distribution<T> distribution(mean, stddev);\n\n hipLaunchKernelGGL(\n HIP_KERNEL_NAME(rocrand_host::detail::generate_normal_kernel),\n dim3(blocks), dim3(threads), 0, m_stream,\n m_engines, data, data_size, distribution\n );\n \/\/ Check kernel status\n if(hipPeekAtLastError() != hipSuccess)\n return ROCRAND_STATUS_LAUNCH_FAILURE;\n\n return ROCRAND_STATUS_SUCCESS;\n }\n\n rocrand_status generate_poisson(unsigned int * data, size_t data_size, double lambda)\n {\n try\n {\n poisson.set_lambda(lambda);\n }\n catch(rocrand_status status)\n {\n return status;\n }\n return generate(data, data_size, poisson.dis);\n }\n\nprivate:\n bool m_engines_initialized;\n engine_type * m_engines;\n size_t m_engines_size;\n\n \/\/ For caching of Poisson for consecutive generations with the same lambda\n poisson_distribution_manager<> poisson;\n\n \/\/ m_seed from base_type\n \/\/ m_offset from base_type\n};\n\n#endif \/\/ ROCRAND_RNG_MRG32K3A_H_\n<|endoftext|>"} {"text":"<commit_before>\/*\n * The Apache Software License, Version 1.1\n *\n *\n * Copyright (c) 1999 The Apache Software Foundation. All rights \n * reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer. \n *\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in\n * the documentation and\/or other materials provided with the\n * distribution.\n *\n * 3. The end-user documentation included with the redistribution,\n * if any, must include the following acknowledgment: \n * \"This product includes software developed by the\n * Apache Software Foundation (http:\/\/www.apache.org\/).\"\n * Alternately, this acknowledgment may appear in the software itself,\n * if and wherever such third-party acknowledgments normally appear.\n *\n * 4. The names \"Xalan\" and \"Apache Software Foundation\" must\n * not be used to endorse or promote products derived from this\n * software without prior written permission. For written \n * permission, please contact apache@apache.org.\n *\n * 5. Products derived from this software may not be called \"Apache\",\n * nor may \"Apache\" appear in their name, without prior written\n * permission of the Apache Software Foundation.\n *\n * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED\n * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR\n * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF\n * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT\n * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n * ====================================================================\n *\n * This software consists of voluntary contributions made by many\n * individuals on behalf of the Apache Software Foundation and was\n * originally based on software copyright (c) 1999, International\n * Business Machines, Inc., http:\/\/www.ibm.com. For more\n * information on the Apache Software Foundation, please see\n * <http:\/\/www.apache.org\/>.\n *\/\n\/\/ Class header file.\n#include \"XResultTreeFrag.hpp\"\n\n\n\n#include <XalanDOM\/XalanNodeList.hpp>\n#include <XalanDOM\/XalanText.hpp>\n\n\n\n#include <PlatformSupport\/DOMStringHelper.hpp>\n#include <PlatformSupport\/DoubleSupport.hpp>\n\n\n\n#include <DOMSupport\/DOMServices.hpp>\n\n\n\n#include \"NodeRefListBase.hpp\"\n#include \"ResultTreeFragBase.hpp\"\n#include \"XObjectTypeCallback.hpp\"\n\n\n\nXResultTreeFrag::XResultTreeFrag(BorrowReturnResultTreeFrag&\tval) :\n\tXObject(eTypeResultTreeFrag),\n\tm_value(val),\n\tm_cachedStringValue(),\n\tm_cachedNumberValue(0.0)\n#if XALAN_RTREEFRAG_TO_NODESET_CONVERSION\n\t, m_nodeRefListBaseProxy(*this)\n#endif\n{\n}\n\n\n\nXResultTreeFrag::XResultTreeFrag(\n\t\t\tconst XResultTreeFrag&\tsource,\n\t\t\tbool\t\t\t\t\tdeepClone) :\n\tXObject(source),\t\n\tm_value(source.m_value.clone(deepClone)),\n\tm_cachedStringValue(source.m_cachedStringValue),\n\tm_cachedNumberValue(source.m_cachedNumberValue)\n#if XALAN_RTREEFRAG_TO_NODESET_CONVERSION\n\t, m_nodeRefListBaseProxy(*this)\n#endif\n{\n}\n\n\n\nXResultTreeFrag::~XResultTreeFrag()\n{\n}\n\n\n\n#if defined(XALAN_NO_COVARIANT_RETURN_TYPE)\nXObject*\n#else\nXResultTreeFrag*\n#endif\nXResultTreeFrag::clone(void*\ttheAddress) const\n{\n\treturn theAddress == 0 ? new XResultTreeFrag(*this) : new (theAddress) XResultTreeFrag(*this);\n};\n\n\n\nXalanDOMString\nXResultTreeFrag::getTypeString() const\n{\n\treturn XALAN_STATIC_UCODE_STRING(\"#RESULT_TREE_FRAG\");\n}\n\n\n\ndouble\nXResultTreeFrag::num() const\n{\n\tif (m_cachedNumberValue == 0.0)\n\t{\n#if defined(XALAN_NO_MUTABLE)\n\t\t((XResultTreeFrag*)this)->m_cachedNumberValue = DoubleSupport::toDouble(str());\n#else\n\t\tm_cachedNumberValue = DoubleSupport::toDouble(str());\n#endif\n\t}\n\n\treturn m_cachedNumberValue;\n}\n\n\n\nbool\nXResultTreeFrag::boolean() const\n{\n\t\/\/ Result tree fragments always evaluate to true.\n\treturn true;\n}\n\n\n\nconst XalanDOMString&\nXResultTreeFrag::str() const\n{\n\tif (isEmpty(m_cachedStringValue) == true)\n\t{\n#if defined(XALAN_NO_MUTABLE)\n\t\tDOMServices::getNodeData(*m_value, ((XResultTreeFrag*)this)->m_cachedStringValue);\n#else\n\t\tDOMServices::getNodeData(*m_value, m_cachedStringValue);\n#endif\n\t}\n\n\treturn m_cachedStringValue;\n}\n\n\n\nvoid\nXResultTreeFrag::str(\n\t\t\tFormatterListener&\tformatterListener,\n\t\t\tMemberFunctionPtr\tfunction) const\n{\n\tif (isEmpty(m_cachedStringValue) == false)\n\t{\n\t\t(formatterListener.*function)(c_wstr(m_cachedStringValue), length(m_cachedStringValue));\n\t}\n\telse\n\t{\n\t\tDOMServices::getNodeData(*m_value, formatterListener, function);\n\t}\n}\n\n\n\nvoid\nXResultTreeFrag::str(XalanDOMString&\ttheBuffer) const\n{\n\tif (isEmpty(m_cachedStringValue) == false)\n\t{\n\t\tappend(theBuffer, m_cachedStringValue);\n\t}\n\telse\n\t{\n\t\tDOMServices::getNodeData(*m_value, theBuffer);\n\t}\n}\n\n\n\nconst ResultTreeFragBase&\nXResultTreeFrag::rtree(XPathExecutionContext&\t\/* executionContext *\/) const\n{\n\treturn *m_value.get();\n}\n\n\n\nconst ResultTreeFragBase&\nXResultTreeFrag::rtree() const\n{\n\treturn *m_value.get();\n}\n\n\n\nconst NodeRefListBase&\nXResultTreeFrag::nodeset() const\n{\n#if XALAN_RTREEFRAG_TO_NODESET_CONVERSION\n\treturn m_nodeRefListBaseProxy;\n#else\n\treturn ParentType::nodeset();\n#endif\n}\n\n\n\nvoid\nXResultTreeFrag::ProcessXObjectTypeCallback(XObjectTypeCallback&\ttheCallbackObject)\n{\n\ttheCallbackObject.ResultTreeFragment(*this,\n\t\t\t\t\t\t\t\t\t\t rtree());\n}\n\n\n\nvoid\nXResultTreeFrag::ProcessXObjectTypeCallback(XObjectTypeCallback&\ttheCallbackObject) const\n{\n\ttheCallbackObject.ResultTreeFragment(*this,\n\t\t\t\t\t\t\t\t\t\t rtree());\n}\n\n\n\nXalanNode*\nXResultTreeFrag::item(unsigned int\tindex) const\n{\n\tassert(m_value.get() != 0);\n\n\tXalanNode*\ttheCurrentChild = m_value->getFirstChild();\n\n\tfor(unsigned int i = 0; i < index && theCurrentChild != 0; ++i)\n\t{\n\t\ttheCurrentChild = theCurrentChild->getNextSibling();\n\t}\n\n\treturn theCurrentChild;\n}\n\n\n\nunsigned int\nXResultTreeFrag::getLength() const\n{\n\treturn 1;\n\tassert(m_value.get() != 0);\n\n\tunsigned int\ttheLength = 0;\n\n\tXalanNode*\ttheCurrentChild = m_value->getFirstChild();\n\n\twhile(theCurrentChild != 0)\n\t{\n\t\t++theLength;\n\n\t\ttheCurrentChild = theCurrentChild->getNextSibling();\n\t}\n\n\treturn theLength;\n}\n\n\n\nunsigned int\nXResultTreeFrag::indexOf(const XalanNode*\ttheNode) const\n{\n\tunsigned\ttheIndex = 0;\n\tbool\t\tfFound = false;\n\n\tXalanNode*\ttheCurrentChild = m_value->getFirstChild();\n\n\twhile(theCurrentChild != 0 && fFound == false)\n\t{\n\t\tif (theCurrentChild == theNode)\n\t\t{\n\t\t\tfFound = true;\n\t\t}\n\t\telse\n\t\t{\n\t\t\t++theIndex;\n\n\t\t\ttheCurrentChild = theCurrentChild->getNextSibling();\n\t\t}\n\t}\n\n\treturn fFound == true ? theIndex : NodeRefListBase::npos;\n}\n\n\n\nXResultTreeFrag::NodeRefListBaseProxy::NodeRefListBaseProxy(const XResultTreeFrag&\ttheXResultTreeFrag) :\n\tNodeRefListBase(),\n\tm_xresultTreeFrag(theXResultTreeFrag)\n{\n}\n\n\n\nXResultTreeFrag::NodeRefListBaseProxy::~NodeRefListBaseProxy()\n{\n}\n\n\n\nXalanNode*\nXResultTreeFrag::NodeRefListBaseProxy::item(unsigned int\tindex) const\n{\n\tif (index == 0)\n\t{\n\t\treturn m_xresultTreeFrag.m_value.get();\n\t}\n\telse\n\t{\n\t\treturn 0;\n\t}\n}\n\n\n\nunsigned int\nXResultTreeFrag::NodeRefListBaseProxy::getLength() const\n{\n\treturn 1;\n}\n\n\n\nunsigned int\nXResultTreeFrag::NodeRefListBaseProxy::indexOf(const XalanNode*\ttheNode) const\n{\n\tif (theNode == m_xresultTreeFrag.m_value.get())\n\t{\n\t\treturn 0;\n\t}\n\telse\n\t{\n\t\treturn NodeRefListBase::npos;\n\t}\n}\n\n\n\nvoid\nXResultTreeFrag::release()\n{\n\tm_value.release();\n\n\tclear(m_cachedStringValue);\n\n\tm_cachedNumberValue = 0.0;\n}\n\n\n\nvoid\nXResultTreeFrag::set(BorrowReturnResultTreeFrag&\ttheValue)\n{\n\trelease();\n\n\tm_value = theValue;\n}\n<commit_msg>Fixed bugs with interpreting ResultTreeFrags as node-sets.<commit_after>\/*\n * The Apache Software License, Version 1.1\n *\n *\n * Copyright (c) 1999 The Apache Software Foundation. All rights \n * reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer. \n *\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in\n * the documentation and\/or other materials provided with the\n * distribution.\n *\n * 3. The end-user documentation included with the redistribution,\n * if any, must include the following acknowledgment: \n * \"This product includes software developed by the\n * Apache Software Foundation (http:\/\/www.apache.org\/).\"\n * Alternately, this acknowledgment may appear in the software itself,\n * if and wherever such third-party acknowledgments normally appear.\n *\n * 4. The names \"Xalan\" and \"Apache Software Foundation\" must\n * not be used to endorse or promote products derived from this\n * software without prior written permission. For written \n * permission, please contact apache@apache.org.\n *\n * 5. Products derived from this software may not be called \"Apache\",\n * nor may \"Apache\" appear in their name, without prior written\n * permission of the Apache Software Foundation.\n *\n * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED\n * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR\n * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF\n * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT\n * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n * ====================================================================\n *\n * This software consists of voluntary contributions made by many\n * individuals on behalf of the Apache Software Foundation and was\n * originally based on software copyright (c) 1999, International\n * Business Machines, Inc., http:\/\/www.ibm.com. For more\n * information on the Apache Software Foundation, please see\n * <http:\/\/www.apache.org\/>.\n *\/\n\/\/ Class header file.\n#include \"XResultTreeFrag.hpp\"\n\n\n\n#include <XalanDOM\/XalanNodeList.hpp>\n#include <XalanDOM\/XalanText.hpp>\n\n\n\n#include <PlatformSupport\/DOMStringHelper.hpp>\n#include <PlatformSupport\/DoubleSupport.hpp>\n\n\n\n#include <DOMSupport\/DOMServices.hpp>\n\n\n\n#include \"NodeRefListBase.hpp\"\n#include \"ResultTreeFragBase.hpp\"\n#include \"XObjectTypeCallback.hpp\"\n\n\n\nXResultTreeFrag::XResultTreeFrag(BorrowReturnResultTreeFrag&\tval) :\n\tXObject(eTypeResultTreeFrag),\n\tm_value(val),\n\tm_cachedStringValue(),\n\tm_cachedNumberValue(0.0)\n#if XALAN_RTREEFRAG_TO_NODESET_CONVERSION\n\t, m_nodeRefListBaseProxy(*this)\n#endif\n{\n}\n\n\n\nXResultTreeFrag::XResultTreeFrag(\n\t\t\tconst XResultTreeFrag&\tsource,\n\t\t\tbool\t\t\t\t\tdeepClone) :\n\tXObject(source),\t\n\tm_value(source.m_value.clone(deepClone)),\n\tm_cachedStringValue(source.m_cachedStringValue),\n\tm_cachedNumberValue(source.m_cachedNumberValue)\n#if XALAN_RTREEFRAG_TO_NODESET_CONVERSION\n\t, m_nodeRefListBaseProxy(*this)\n#endif\n{\n}\n\n\n\nXResultTreeFrag::~XResultTreeFrag()\n{\n}\n\n\n\n#if defined(XALAN_NO_COVARIANT_RETURN_TYPE)\nXObject*\n#else\nXResultTreeFrag*\n#endif\nXResultTreeFrag::clone(void*\ttheAddress) const\n{\n\treturn theAddress == 0 ? new XResultTreeFrag(*this) : new (theAddress) XResultTreeFrag(*this);\n};\n\n\n\nXalanDOMString\nXResultTreeFrag::getTypeString() const\n{\n\treturn XALAN_STATIC_UCODE_STRING(\"#RESULT_TREE_FRAG\");\n}\n\n\n\ndouble\nXResultTreeFrag::num() const\n{\n\tif (m_cachedNumberValue == 0.0)\n\t{\n#if defined(XALAN_NO_MUTABLE)\n\t\t((XResultTreeFrag*)this)->m_cachedNumberValue = DoubleSupport::toDouble(str());\n#else\n\t\tm_cachedNumberValue = DoubleSupport::toDouble(str());\n#endif\n\t}\n\n\treturn m_cachedNumberValue;\n}\n\n\n\nbool\nXResultTreeFrag::boolean() const\n{\n\t\/\/ Result tree fragments always evaluate to true.\n\treturn true;\n}\n\n\n\nconst XalanDOMString&\nXResultTreeFrag::str() const\n{\n\tif (isEmpty(m_cachedStringValue) == true)\n\t{\n#if defined(XALAN_NO_MUTABLE)\n\t\tDOMServices::getNodeData(*m_value, ((XResultTreeFrag*)this)->m_cachedStringValue);\n#else\n\t\tDOMServices::getNodeData(*m_value, m_cachedStringValue);\n#endif\n\t}\n\n\treturn m_cachedStringValue;\n}\n\n\n\nvoid\nXResultTreeFrag::str(\n\t\t\tFormatterListener&\tformatterListener,\n\t\t\tMemberFunctionPtr\tfunction) const\n{\n\tif (isEmpty(m_cachedStringValue) == false)\n\t{\n\t\t(formatterListener.*function)(c_wstr(m_cachedStringValue), length(m_cachedStringValue));\n\t}\n\telse\n\t{\n\t\tDOMServices::getNodeData(*m_value, formatterListener, function);\n\t}\n}\n\n\n\nvoid\nXResultTreeFrag::str(XalanDOMString&\ttheBuffer) const\n{\n\tif (isEmpty(m_cachedStringValue) == false)\n\t{\n\t\tappend(theBuffer, m_cachedStringValue);\n\t}\n\telse\n\t{\n\t\tDOMServices::getNodeData(*m_value, theBuffer);\n\t}\n}\n\n\n\nconst ResultTreeFragBase&\nXResultTreeFrag::rtree(XPathExecutionContext&\t\/* executionContext *\/) const\n{\n\treturn *m_value.get();\n}\n\n\n\nconst ResultTreeFragBase&\nXResultTreeFrag::rtree() const\n{\n\treturn *m_value.get();\n}\n\n\n\nconst NodeRefListBase&\nXResultTreeFrag::nodeset() const\n{\n#if XALAN_RTREEFRAG_TO_NODESET_CONVERSION\n\treturn m_nodeRefListBaseProxy;\n#else\n\treturn ParentType::nodeset();\n#endif\n}\n\n\n\nvoid\nXResultTreeFrag::ProcessXObjectTypeCallback(XObjectTypeCallback&\ttheCallbackObject)\n{\n\ttheCallbackObject.ResultTreeFragment(*this,\n\t\t\t\t\t\t\t\t\t\t rtree());\n}\n\n\n\nvoid\nXResultTreeFrag::ProcessXObjectTypeCallback(XObjectTypeCallback&\ttheCallbackObject) const\n{\n\ttheCallbackObject.ResultTreeFragment(*this,\n\t\t\t\t\t\t\t\t\t\t rtree());\n}\n\n\n\nXalanNode*\nXResultTreeFrag::item(unsigned int\tindex) const\n{\n\treturn index == 0 ? m_value.get() : 0;\n}\n\n\n\nunsigned int\nXResultTreeFrag::getLength() const\n{\n\treturn 1;\n}\n\n\n\nunsigned int\nXResultTreeFrag::indexOf(const XalanNode*\ttheNode) const\n{\n\treturn theNode == m_value.get() ? 0 : NodeRefListBase::npos;\n}\n\n\n\nXResultTreeFrag::NodeRefListBaseProxy::NodeRefListBaseProxy(const XResultTreeFrag&\ttheXResultTreeFrag) :\n\tNodeRefListBase(),\n\tm_xresultTreeFrag(theXResultTreeFrag)\n{\n}\n\n\n\nXResultTreeFrag::NodeRefListBaseProxy::~NodeRefListBaseProxy()\n{\n}\n\n\n\nXalanNode*\nXResultTreeFrag::NodeRefListBaseProxy::item(unsigned int\tindex) const\n{\n\treturn m_xresultTreeFrag.item(index);\n}\n\n\n\nunsigned int\nXResultTreeFrag::NodeRefListBaseProxy::getLength() const\n{\n\treturn m_xresultTreeFrag.getLength();\n}\n\n\n\nunsigned int\nXResultTreeFrag::NodeRefListBaseProxy::indexOf(const XalanNode*\ttheNode) const\n{\n\treturn m_xresultTreeFrag.indexOf(theNode);\n}\n\n\n\nvoid\nXResultTreeFrag::release()\n{\n\tm_value.release();\n\n\tclear(m_cachedStringValue);\n\n\tm_cachedNumberValue = 0.0;\n}\n\n\n\nvoid\nXResultTreeFrag::set(BorrowReturnResultTreeFrag&\ttheValue)\n{\n\trelease();\n\n\tm_value = theValue;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * The Apache Software License, Version 1.1\n *\n *\n * Copyright (c) 1999-2002 The Apache Software Foundation. All rights \n * reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer. \n *\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in\n * the documentation and\/or other materials provided with the\n * distribution.\n *\n * 3. The end-user documentation included with the redistribution,\n * if any, must include the following acknowledgment: \n * \"This product includes software developed by the\n * Apache Software Foundation (http:\/\/www.apache.org\/).\"\n * Alternately, this acknowledgment may appear in the software itself,\n * if and wherever such third-party acknowledgments normally appear.\n *\n * 4. The names \"Xalan\" and \"Apache Software Foundation\" must\n * not be used to endorse or promote products derived from this\n * software without prior written permission. For written \n * permission, please contact apache@apache.org.\n *\n * 5. Products derived from this software may not be called \"Apache\",\n * nor may \"Apache\" appear in their name, without prior written\n * permission of the Apache Software Foundation.\n *\n * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED\n * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR\n * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF\n * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT\n * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n * ====================================================================\n *\n * This software consists of voluntary contributions made by many\n * individuals on behalf of the Apache Software Foundation and was\n * originally based on software copyright (c) 1999, International\n * Business Machines, Inc., http:\/\/www.ibm.com. For more\n * information on the Apache Software Foundation, please see\n * <http:\/\/www.apache.org\/>.\n *\n * $ Id: $\n \n *\/\n\n#if !defined(XALAN_XSLTRESULTTARGET_HEADER_GUARD)\n#define XALAN_XSLTRESULTTARGET_HEADER_GUARD\n\n\/\/ Base include file. Must be first.\n#include \"XSLTDefinitions.hpp\"\n\n\n\n#if defined(XALAN_CLASSIC_IOSTREAMS)\nclass ostream;\n#else\n#include <iosfwd>\n#endif\n\n\n\n#include <XalanDOM\/XalanDOMString.hpp>\n\n\n\nXALAN_CPP_NAMESPACE_BEGIN\n\n\n\nclass FormatterListener;\nclass XalanDocument;\nclass XalanDocumentFragment;\nclass XalanElement;\nclass Writer;\n\n\n\nclass XALAN_XSLT_EXPORT XSLTResultTarget\n{\npublic:\n\n#if defined(XALAN_NO_STD_NAMESPACE)\n\ttypedef ostream\t\t\tStreamType;\n#else\n\ttypedef std::ostream\tStreamType;\n#endif\n\n\texplicit\n\tXSLTResultTarget();\n\n\t\/**\n\t * Create a new output target with a file name.\n\t *\n\t * @param fileName valid system file name\n\t *\/\n\tXSLTResultTarget(const XalanDOMString&\tfileName);\n\n\t\/**\n\t * Create a new output target with a file name.\n\t *\n\t * @param fileName valid system file name\n\t *\/\n\tXSLTResultTarget(const XalanDOMChar*\tfileName);\n\n\t\/**\n\t * Create a new output target with a file name.\n\t *\n\t * @param fileName valid system file name\n\t *\/\n\tXSLTResultTarget(const char*\tfileName);\n\n\t\/**\n\t * Create a new output target with a stream.\n\t *\n\t * @param byteStream a pointer to a std ostream for the output\n\t *\/\n\tXSLTResultTarget(StreamType*\ttheStream);\n\n\t\/**\n\t * Create a new output target with a stream.\n\t *\n\t * @param byteStream a reference to a std ostream for the output\n\t *\/\n\tXSLTResultTarget(StreamType&\ttheStream);\n\n\t\/**\n\t * Create a new output target with a character stream.\n\t *\n\t * @param characterStream pointer to character stream where the results\n\t * will be written\n\t *\/ \n\tXSLTResultTarget(Writer*\tcharacterStream);\n\n\t\/**\n\t * Create a new output target with a DOM document.\n\t *\n\t * @param n root of DOM node tree that holds results\n\t *\/\n\tXSLTResultTarget(XalanDocument*\t\tdocument);\n\n\t\/**\n\t * Create a new output target with a DOM document fragment.\n\t *\n\t * @param n root of DOM node tree that holds results\n\t *\/\n\tXSLTResultTarget(XalanDocumentFragment*\t\tdocumentFragment);\n\n\t\/**\n\t * Create a new output target with a DOM element.\n\t *\n\t * @param n root of DOM node tree that holds results\n\t *\/\n\tXSLTResultTarget(XalanElement*\telement);\n\n\t\/**\n\t * Create a new output target with a FormatterListener.\n\t *\n\t * @param flistener A FormatterListener instance for result tree events.\n\t *\/\n\tXSLTResultTarget(FormatterListener&\t\tflistener);\n\n\t~XSLTResultTarget();\n\n\t\/**\n\t * Set the file name where the results will be written.\n\t *\n\t * @param fileName system identifier as a string\n\t *\/\n\tvoid\n\tsetFileName(const XalanDOMString&\tfileName)\n\t{\n\t\tm_fileName = fileName;\n\t}\n\n\t\/**\n\t * Get the file name where the results will be written to.\n\t * \n\t * @return file name string\n\t *\/\n\tconst XalanDOMString&\n\tgetFileName() const\n\t{\n\t\treturn m_fileName;\n\t}\n\n\t\/**\n\t * Set the byte stream for this output target.\n\t *\n\t * @param byteStream pointer to byte stream that will contain the result\n\t * document\n\t *\/\n\tvoid\n\tsetByteStream(StreamType*\t\t\tbyteStream)\n\t{\n\t\tm_byteStream = byteStream;\n\t}\n\n\t\/**\n\t * Get the byte stream for this output target.\n\t *\n\t * @return pointer to byte stream, or null if none was supplied.\n\t *\/\n\tStreamType*\n\tgetByteStream() const\n\t{\n\t\treturn m_byteStream;\n\t}\n\n\t\/** \n\t * Set the character encoding, if known.\n\t *\n\t * @param encoding new encoding string\n\t *\/\n\tvoid\n\tsetEncoding(const XalanDOMString&\tencoding)\n\t{\n\t\tm_encoding = encoding;\n\t}\n\n\t\/**\n\t * Get the character encoding in use.\n\t *\n\t * @return encoding string, or empty string if none was supplied.\n\t *\/\n\tconst XalanDOMString&\n\tgetEncoding() const\n\t{\n\t\treturn m_encoding;\n\t}\n\n\t\/**\n\t * Set the character stream for this output target.\n\t *\n\t * @param characterStream pointer to character stream that will contain \n\t * the result document\n\t *\/\n\tvoid\n\tsetCharacterStream(Writer*\tcharacterStream)\n\t{\n\t\tm_characterStream = characterStream;\n\t}\n\n\t\/**\n\t * Get the character stream for this output target.\n\t *\n\t * @return pointer to character stream, or null if none was supplied.\n\t *\/\n\tWriter*\n\tgetCharacterStream() const\n\t{\n\t\treturn m_characterStream;\n\t}\n\n\tbool\n\thasDOMTarget() const\n\t{\n\t\treturn m_document != 0 || m_documentFragment != 0 || m_element != 0;\n\t}\n\n\t\/**\n\t * Set the document node that will contain the result nodes.\n\t *\n\t * @param node DOM node to contain results\n\t *\/\n\tvoid\n\tsetDocument(XalanDocument*\t\tdocument)\n\t{\n\t\tm_document = document;\n\n\t\tm_documentFragment = 0;\n\t\tm_element = 0;\n\t}\n\n\t\/**\n\t * Get the document node that will contain the result nodes.\n\t *\n\t * @return a pointer to the document node\n\t *\/\n\tXalanDocument*\n\tgetDocument() const\n\t{\n\t\treturn m_document;\n\t}\n\n\t\/**\n\t * Set the document fragment node that will contain the result nodes.\n\t *\n\t * @param node DOM node to contain results\n\t *\/\n\tvoid\n\tsetDocumentFragment(XalanDocumentFragment*\tdocumentFragment)\n\t{\n\t\tm_documentFragment = documentFragment;\n\n\t\tm_document = 0;\n\t\tm_element = 0;\n\t}\n\n\t\/**\n\t * Get the document node that will contain the result nodes.\n\t *\n\t * @return a pointer to the document node\n\t *\/\n\tXalanDocumentFragment*\n\tgetDocumentFragment() const\n\t{\n\t\treturn m_documentFragment;\n\t}\n\n\t\/**\n\t * Set the element node that will contain the result nodes.\n\t *\n\t * @param node DOM node to contain results\n\t *\/\n\tvoid\n\tsetElement(XalanElement*\telement)\n\t{\n\t\tm_element = element;\n\n\t\tm_documentFragment = 0;\n\t\tm_document = 0;\n\t}\n\n\t\/**\n\t * Get the document node that will contain the result nodes.\n\t *\n\t * @return a pointer to the document node\n\t *\/\n\tXalanElement*\n\tgetElement() const\n\t{\n\t\treturn m_element;\n\t}\n\n\t\/**\n\t * Set a SAX DocumentHandler to process the result tree events.\n\t *\n\t * @param handler pointer to new handler\n\t *\/\n\tvoid\n\tsetDocumentHandler(FormatterListener*\thandler)\n\t{\n\t\tm_formatterListener = handler;\n\t}\n\n\t\/**\n\t * Get the SAX DocumentHandler that will process the result tree events.\n\t *\n\t * @return pointer to current handler\n\t *\/\n\tFormatterListener*\n\tgetDocumentHandler() const\n\t{\n\t\treturn m_formatterListener;\n\t}\n\n\t\/**\n\t * Set a FormatterListener to process the result tree events.\n\t *\n\t * @param handler pointer to new listener\n\t *\/\n\tvoid\n\tsetFormatterListener(FormatterListener*\t\thandler)\n\t{\n\t\tm_formatterListener = handler;\n\t}\n\n\t\/**\n\t * Get the FormatterListener that will process the result tree events.\n\t *\n\t * @return pointer to new listener\n\t *\/\n\tFormatterListener*\n\tgetFormatterListener() const\n\t{\n\t\treturn m_formatterListener;\n\t}\n\nprivate:\n\n\tXalanDOMString\t\t\tm_fileName;\n\n\tStreamType*\t\t\t\tm_byteStream;\n\n\tXalanDOMString\t\t\tm_encoding;\n\n\tWriter*\t\t\t\t\tm_characterStream;\n\n\tXalanDocument*\t\t\tm_document;\n\n\tXalanDocumentFragment*\tm_documentFragment;\n\n\tXalanElement*\t\t\tm_element;\n\n\tFormatterListener*\t\tm_formatterListener;\n};\n\n\n\nXALAN_CPP_NAMESPACE_END\n\n\n\n#endif\t\/\/ XALAN_XSLTRESULTTARGET_HEADER_GUARD\n<commit_msg>Added set accessor for const char*.<commit_after>\/*\n * The Apache Software License, Version 1.1\n *\n *\n * Copyright (c) 1999-2002 The Apache Software Foundation. All rights \n * reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer. \n *\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in\n * the documentation and\/or other materials provided with the\n * distribution.\n *\n * 3. The end-user documentation included with the redistribution,\n * if any, must include the following acknowledgment: \n * \"This product includes software developed by the\n * Apache Software Foundation (http:\/\/www.apache.org\/).\"\n * Alternately, this acknowledgment may appear in the software itself,\n * if and wherever such third-party acknowledgments normally appear.\n *\n * 4. The names \"Xalan\" and \"Apache Software Foundation\" must\n * not be used to endorse or promote products derived from this\n * software without prior written permission. For written \n * permission, please contact apache@apache.org.\n *\n * 5. Products derived from this software may not be called \"Apache\",\n * nor may \"Apache\" appear in their name, without prior written\n * permission of the Apache Software Foundation.\n *\n * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED\n * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR\n * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF\n * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT\n * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n * ====================================================================\n *\n * This software consists of voluntary contributions made by many\n * individuals on behalf of the Apache Software Foundation and was\n * originally based on software copyright (c) 1999, International\n * Business Machines, Inc., http:\/\/www.ibm.com. For more\n * information on the Apache Software Foundation, please see\n * <http:\/\/www.apache.org\/>.\n *\n * $ Id: $\n \n *\/\n\n#if !defined(XALAN_XSLTRESULTTARGET_HEADER_GUARD)\n#define XALAN_XSLTRESULTTARGET_HEADER_GUARD\n\n\/\/ Base include file. Must be first.\n#include \"XSLTDefinitions.hpp\"\n\n\n\n#if defined(XALAN_CLASSIC_IOSTREAMS)\nclass ostream;\n#else\n#include <iosfwd>\n#endif\n\n\n\n#include <XalanDOM\/XalanDOMString.hpp>\n\n\n\nXALAN_CPP_NAMESPACE_BEGIN\n\n\n\nclass FormatterListener;\nclass XalanDocument;\nclass XalanDocumentFragment;\nclass XalanElement;\nclass Writer;\n\n\n\nclass XALAN_XSLT_EXPORT XSLTResultTarget\n{\npublic:\n\n#if defined(XALAN_NO_STD_NAMESPACE)\n\ttypedef ostream\t\t\tStreamType;\n#else\n\ttypedef std::ostream\tStreamType;\n#endif\n\n\texplicit\n\tXSLTResultTarget();\n\n\t\/**\n\t * Create a new output target with a file name.\n\t *\n\t * @param fileName valid system file name\n\t *\/\n\tXSLTResultTarget(const XalanDOMString&\tfileName);\n\n\t\/**\n\t * Create a new output target with a file name.\n\t *\n\t * @param fileName valid system file name\n\t *\/\n\tXSLTResultTarget(const XalanDOMChar*\tfileName);\n\n\t\/**\n\t * Create a new output target with a file name.\n\t *\n\t * @param fileName valid system file name\n\t *\/\n\tXSLTResultTarget(const char*\tfileName);\n\n\t\/**\n\t * Create a new output target with a stream.\n\t *\n\t * @param byteStream a pointer to a std ostream for the output\n\t *\/\n\tXSLTResultTarget(StreamType*\ttheStream);\n\n\t\/**\n\t * Create a new output target with a stream.\n\t *\n\t * @param byteStream a reference to a std ostream for the output\n\t *\/\n\tXSLTResultTarget(StreamType&\ttheStream);\n\n\t\/**\n\t * Create a new output target with a character stream.\n\t *\n\t * @param characterStream pointer to character stream where the results\n\t * will be written\n\t *\/ \n\tXSLTResultTarget(Writer*\tcharacterStream);\n\n\t\/**\n\t * Create a new output target with a DOM document.\n\t *\n\t * @param n root of DOM node tree that holds results\n\t *\/\n\tXSLTResultTarget(XalanDocument*\t\tdocument);\n\n\t\/**\n\t * Create a new output target with a DOM document fragment.\n\t *\n\t * @param n root of DOM node tree that holds results\n\t *\/\n\tXSLTResultTarget(XalanDocumentFragment*\t\tdocumentFragment);\n\n\t\/**\n\t * Create a new output target with a DOM element.\n\t *\n\t * @param n root of DOM node tree that holds results\n\t *\/\n\tXSLTResultTarget(XalanElement*\telement);\n\n\t\/**\n\t * Create a new output target with a FormatterListener.\n\t *\n\t * @param flistener A FormatterListener instance for result tree events.\n\t *\/\n\tXSLTResultTarget(FormatterListener&\t\tflistener);\n\n\t~XSLTResultTarget();\n\n\t\/**\n\t * Set the file name where the results will be written.\n\t *\n\t * @param fileName system identifier as a string\n\t *\/\n\tvoid\n\tsetFileName(const char*\t\tfileName)\n\t{\n\t\tif (fileName == 0)\n\t\t{\n\t\t\tm_fileName.clear();\n\t\t}\n\t\telse\n\t\t{\n\t\t\tm_fileName = fileName;\n\t\t}\n\t}\n\n\t\/**\n\t * Set the file name where the results will be written.\n\t *\n\t * @param fileName system identifier as a string\n\t *\/\n\tvoid\n\tsetFileName(const XalanDOMString&\tfileName)\n\t{\n\t\tm_fileName = fileName;\n\t}\n\n\t\/**\n\t * Get the file name where the results will be written to.\n\t * \n\t * @return file name string\n\t *\/\n\tconst XalanDOMString&\n\tgetFileName() const\n\t{\n\t\treturn m_fileName;\n\t}\n\n\t\/**\n\t * Set the byte stream for this output target.\n\t *\n\t * @param byteStream pointer to byte stream that will contain the result\n\t * document\n\t *\/\n\tvoid\n\tsetByteStream(StreamType*\t\t\tbyteStream)\n\t{\n\t\tm_byteStream = byteStream;\n\t}\n\n\t\/**\n\t * Get the byte stream for this output target.\n\t *\n\t * @return pointer to byte stream, or null if none was supplied.\n\t *\/\n\tStreamType*\n\tgetByteStream() const\n\t{\n\t\treturn m_byteStream;\n\t}\n\n\t\/** \n\t * Set the character encoding, if known.\n\t *\n\t * @param encoding new encoding string\n\t *\/\n\tvoid\n\tsetEncoding(const XalanDOMString&\tencoding)\n\t{\n\t\tm_encoding = encoding;\n\t}\n\n\t\/**\n\t * Get the character encoding in use.\n\t *\n\t * @return encoding string, or empty string if none was supplied.\n\t *\/\n\tconst XalanDOMString&\n\tgetEncoding() const\n\t{\n\t\treturn m_encoding;\n\t}\n\n\t\/**\n\t * Set the character stream for this output target.\n\t *\n\t * @param characterStream pointer to character stream that will contain \n\t * the result document\n\t *\/\n\tvoid\n\tsetCharacterStream(Writer*\tcharacterStream)\n\t{\n\t\tm_characterStream = characterStream;\n\t}\n\n\t\/**\n\t * Get the character stream for this output target.\n\t *\n\t * @return pointer to character stream, or null if none was supplied.\n\t *\/\n\tWriter*\n\tgetCharacterStream() const\n\t{\n\t\treturn m_characterStream;\n\t}\n\n\tbool\n\thasDOMTarget() const\n\t{\n\t\treturn m_document != 0 || m_documentFragment != 0 || m_element != 0;\n\t}\n\n\t\/**\n\t * Set the document node that will contain the result nodes.\n\t *\n\t * @param node DOM node to contain results\n\t *\/\n\tvoid\n\tsetDocument(XalanDocument*\t\tdocument)\n\t{\n\t\tm_document = document;\n\n\t\tm_documentFragment = 0;\n\t\tm_element = 0;\n\t}\n\n\t\/**\n\t * Get the document node that will contain the result nodes.\n\t *\n\t * @return a pointer to the document node\n\t *\/\n\tXalanDocument*\n\tgetDocument() const\n\t{\n\t\treturn m_document;\n\t}\n\n\t\/**\n\t * Set the document fragment node that will contain the result nodes.\n\t *\n\t * @param node DOM node to contain results\n\t *\/\n\tvoid\n\tsetDocumentFragment(XalanDocumentFragment*\tdocumentFragment)\n\t{\n\t\tm_documentFragment = documentFragment;\n\n\t\tm_document = 0;\n\t\tm_element = 0;\n\t}\n\n\t\/**\n\t * Get the document node that will contain the result nodes.\n\t *\n\t * @return a pointer to the document node\n\t *\/\n\tXalanDocumentFragment*\n\tgetDocumentFragment() const\n\t{\n\t\treturn m_documentFragment;\n\t}\n\n\t\/**\n\t * Set the element node that will contain the result nodes.\n\t *\n\t * @param node DOM node to contain results\n\t *\/\n\tvoid\n\tsetElement(XalanElement*\telement)\n\t{\n\t\tm_element = element;\n\n\t\tm_documentFragment = 0;\n\t\tm_document = 0;\n\t}\n\n\t\/**\n\t * Get the document node that will contain the result nodes.\n\t *\n\t * @return a pointer to the document node\n\t *\/\n\tXalanElement*\n\tgetElement() const\n\t{\n\t\treturn m_element;\n\t}\n\n\t\/**\n\t * Set a SAX DocumentHandler to process the result tree events.\n\t *\n\t * @param handler pointer to new handler\n\t *\/\n\tvoid\n\tsetDocumentHandler(FormatterListener*\thandler)\n\t{\n\t\tm_formatterListener = handler;\n\t}\n\n\t\/**\n\t * Get the SAX DocumentHandler that will process the result tree events.\n\t *\n\t * @return pointer to current handler\n\t *\/\n\tFormatterListener*\n\tgetDocumentHandler() const\n\t{\n\t\treturn m_formatterListener;\n\t}\n\n\t\/**\n\t * Set a FormatterListener to process the result tree events.\n\t *\n\t * @param handler pointer to new listener\n\t *\/\n\tvoid\n\tsetFormatterListener(FormatterListener*\t\thandler)\n\t{\n\t\tm_formatterListener = handler;\n\t}\n\n\t\/**\n\t * Get the FormatterListener that will process the result tree events.\n\t *\n\t * @return pointer to new listener\n\t *\/\n\tFormatterListener*\n\tgetFormatterListener() const\n\t{\n\t\treturn m_formatterListener;\n\t}\n\nprivate:\n\n\tXalanDOMString\t\t\tm_fileName;\n\n\tStreamType*\t\t\t\tm_byteStream;\n\n\tXalanDOMString\t\t\tm_encoding;\n\n\tWriter*\t\t\t\t\tm_characterStream;\n\n\tXalanDocument*\t\t\tm_document;\n\n\tXalanDocumentFragment*\tm_documentFragment;\n\n\tXalanElement*\t\t\tm_element;\n\n\tFormatterListener*\t\tm_formatterListener;\n};\n\n\n\nXALAN_CPP_NAMESPACE_END\n\n\n\n#endif\t\/\/ XALAN_XSLTRESULTTARGET_HEADER_GUARD\n<|endoftext|>"} {"text":"<commit_before>\/**\n * @file test_hsv_aux.cpp\n * @brief Test for HSV color histogram auxiliary functions\n * @author Paolo D'Apice\n *\/\n\n#define BOOST_TEST_MODULE hsv_aux\n#include <boost\/test\/unit_test.hpp>\n\n#include \"fixtures.hpp\"\n#include \"hsv_aux.hpp\"\n#include \"utils\/matrix.hpp\"\n#include \"utils\/print.hpp\"\n#include <opencv2\/highgui\/highgui.hpp>\n\n#define argc boost::unit_test::framework::master_test_suite().argc\n#define argv boost::unit_test::framework::master_test_suite().argv\n\n#define display(TITLE, IMAGE) \\\n do { \\\n cv::namedWindow((TITLE), CV_WINDOW_NORMAL | CV_WINDOW_KEEPRATIO | CV_GUI_EXPANDED); \\\n cv::imshow((TITLE),(IMAGE)); \\\n } while(0)\n\n\nBOOST_AUTO_TEST_CASE(test_ind2sub) {\n const arma::ivec3 size = {3,2,2};\n\n std::vector<std::pair<arma::ivec3,int>> values = {\n std::make_pair(arma::ivec3{0,0,0}, 0),\n std::make_pair(arma::ivec3{2,0,0}, 2),\n std::make_pair(arma::ivec3{1,1,0}, 4),\n std::make_pair(arma::ivec3{2,0,1}, 8),\n std::make_pair(arma::ivec3{2,1,1}, 11),\n };\n\n for (auto p: values) {\n BOOST_CHECK(test::equals(p.first, vis::ind2sub(size, p.second)));\n }\n}\n\ncv::Mat swapChannels(const cv::Mat& in) {\n cv::Mat out(in.size(), in.type());\n const static int fromto[] = { 0,2, 1,1, 2,0 };\n cv::mixChannels(&in, 1, &out, 1, fromto, 3);\n return out;\n}\n\nBOOST_FIXTURE_TEST_CASE(test_functions, test::Peppers) {\n cv::Mat hsv = vis::toHsv(image);\n\n BOOST_CHECK_EQUAL(hsv.size(), image.size());\n BOOST_CHECK_EQUAL(hsv.type(), image.type());\n BOOST_CHECK(test::hasMinMax(hsv, 0., 1.));\n\n arma::ivec3 levels = { 3, 2+1, 2+1 };\n cv::Mat quantized = vis::quantize(hsv, levels);\n BOOST_CHECK_EQUAL(quantized.size(), image.size());\n BOOST_CHECK_EQUAL(quantized.type(), image.type());\n\n std::vector<cv::Mat> planes;\n cv::split(quantized, planes);\n BOOST_CHECK(test::hasMinMax(planes[0], 1, levels[0]));\n BOOST_CHECK(test::hasMinMax(planes[1], 1, levels[1]));\n BOOST_CHECK(test::hasMinMax(planes[2], 1, levels[2]));\n\n if (argc > 1) {\n display(\"image\", image);\n display(\"hsv\", swapChannels(hsv)); \/\/ HSV channels are interpreted as BGR\n\n planes[0] \/= levels[0];\n planes[1] \/= levels[1];\n planes[2] \/= levels[2];\n cv::merge(planes, quantized);\n display(\"quantized\", swapChannels(quantized)); \/\/ idem\n\n cv::Mat bgr = vis::toBgr(quantized);\n display(\"rgb\", bgr);\n\n println(\"Press a key to continue\");\n cv::waitKey(0);\n }\n}\n\nBOOST_AUTO_TEST_CASE(test_imquantize) {\n cv::Mat data = (cv::Mat_<float>(5,5) << 17, 23, 4, 10, 11,\n 24, 5, 6, 12, 18,\n 1, 7, 13, 19, 25,\n 8, 14, 20, 21, 2,\n 15, 16, 22, 3, 9);\n\n arma::fvec thresholds = { 1, 6, 11, 16, 21 };\n\n cv::Mat expected = (cv::Mat_<float>(5,5) << 5, 6, 1, 3, 4,\n 6, 2, 3, 4, 4,\n 2, 2, 4, 5, 6,\n 3, 4, 5, 5, 2,\n 3, 5, 6, 2, 3);\n\n cv::Mat actual = vis::imquantize(data.t(), thresholds); \/\/ NOTE transposed wrt Matlab\n\n printmat(expected);\n printmat(actual);\n\n BOOST_CHECK(test::equals(expected, actual));\n}\n\nBOOST_AUTO_TEST_CASE(test_medfilt2) {\n cv::Mat data = (cv::Mat_<float>(5,5) << 17, 23, 4, 10, 11,\n 24, 5, 6, 12, 18,\n 1, 7, 13, 19, 25,\n 8, 14, 20, 21, 2,\n 15, 16, 22, 3, 9);\n\n cv::Mat expected = (cv::Mat_<float>(5,5) << 17, 17, 8, 8, 15,\n 17, 7, 8, 14, 16,\n 10, 10, 13, 16, 16,\n 10, 12, 18, 19, 9,\n 11, 18, 18, 9, 9);\n\n cv::Mat actual = vis::medfilt2(data.t()); \/\/ NOTE transposed wrt Matlab\n\n printmat(data);\n printmat(expected);\n printmat(actual);\n\n BOOST_CHECK(test::equals(expected, actual));\n}\n\nBOOST_AUTO_TEST_CASE(test_linspace) {\n {\n arma::fvec expected = {1,2,3,4,5,6,7,8,9,10};\n arma::fvec actual = arma::linspace<arma::fvec>(1., 10., 10);\n BOOST_CHECK(test::equals(expected, actual));\n }\n {\n arma::vec expected = { 1.0, 1.642857143, 2.285714286, 2.928571429, 3.571428571,\n 4.214285714, 4.857142857, 5.5, 6.142857143, 6.785714286,\n 7.428571429, 8.071428571, 8.714285714, 9.357142857, 10.0 };\n arma::vec actual = arma::linspace<arma::vec>(1, 10, 15);\n BOOST_REQUIRE_EQUAL(expected.size(), actual.size());\n for(int i = 0; i < 15; ++i) BOOST_CHECK_CLOSE(expected(i), actual(i), 0.000001);\n }\n}\n\ntemplate <typename T>\nvoid doReshapeTest(const arma::Mat<T>& expected, const arma::Mat<T>& actual) {\n printmat(expected);\n printmat(actual);\n\n BOOST_CHECK_EQUAL(actual.size(), expected.size());\n BOOST_CHECK_EQUAL(actual.n_rows, expected.n_rows);\n BOOST_CHECK_EQUAL(actual.n_cols, expected.n_cols);\n BOOST_CHECK(test::equals(expected, actual));\n}\n\nBOOST_AUTO_TEST_CASE(test_reshape) {\n arma::imat data = { 8, 1, 6, 2,\n 3, 5, 7, 9,\n 4, 9, 2, 1 };\n data = arma::reshape(data,4,3).t(); \/\/ NOTE column-major vs row-major\n printmat(data);\n\n {\n arma::imat expected = { 8, 4, 5, 6, 2, 9,\n 3, 1, 9, 7, 2, 1 };\n expected = arma::reshape(expected,6,2).t();\n\n arma::imat actual(data);\n actual.reshape(2,6);\n doReshapeTest(expected, actual);\n }\n {\n arma::imat expected = { 8, 6,\n 3, 7,\n 4, 2,\n 1, 2,\n 5, 9,\n 9, 1 };\n expected = arma::reshape(expected,2,6).t();\n\n arma::imat actual(data);\n actual.reshape(6,2);\n doReshapeTest(expected, actual);\n }\n}\n\n<commit_msg>Deleted tests for removed functions<commit_after>\/**\n * @file test_hsv_aux.cpp\n * @brief Test for HSV color histogram auxiliary functions\n * @author Paolo D'Apice\n *\/\n\n#define BOOST_TEST_MODULE hsv_aux\n#include <boost\/test\/unit_test.hpp>\n\n#include \"fixtures.hpp\"\n#include \"hsv_aux.hpp\"\n#include \"utils\/matrix.hpp\"\n#include \"utils\/print.hpp\"\n#include <opencv2\/highgui\/highgui.hpp>\n\n#define argc boost::unit_test::framework::master_test_suite().argc\n#define argv boost::unit_test::framework::master_test_suite().argv\n\n#define display(TITLE, IMAGE) \\\n do { \\\n cv::namedWindow((TITLE), CV_WINDOW_NORMAL | CV_WINDOW_KEEPRATIO | CV_GUI_EXPANDED); \\\n cv::imshow((TITLE),(IMAGE)); \\\n } while(0)\n\n\nBOOST_AUTO_TEST_CASE(test_ind2sub) {\n const arma::ivec3 size = {3,2,2};\n\n std::vector<std::pair<arma::ivec3,int>> values = {\n std::make_pair(arma::ivec3{0,0,0}, 0),\n std::make_pair(arma::ivec3{2,0,0}, 2),\n std::make_pair(arma::ivec3{1,1,0}, 4),\n std::make_pair(arma::ivec3{2,0,1}, 8),\n std::make_pair(arma::ivec3{2,1,1}, 11),\n };\n\n for (auto p: values) {\n BOOST_CHECK(test::equals(p.first, vis::ind2sub(size, p.second)));\n }\n}\n\ncv::Mat swapChannels(const cv::Mat& in) {\n cv::Mat out(in.size(), in.type());\n const static int fromto[] = { 0,2, 1,1, 2,0 };\n cv::mixChannels(&in, 1, &out, 1, fromto, 3);\n return out;\n}\n\nBOOST_FIXTURE_TEST_CASE(test_functions, test::Peppers) {\n cv::Mat hsv = vis::toHsv(image);\n\n BOOST_CHECK_EQUAL(hsv.size(), image.size());\n BOOST_CHECK_EQUAL(hsv.type(), image.type());\n BOOST_CHECK(test::hasMinMax(hsv, 0., 1.));\n\n arma::ivec3 levels = { 3, 2+1, 2+1 };\n cv::Mat quantized = vis::quantize(hsv, levels);\n BOOST_CHECK_EQUAL(quantized.size(), image.size());\n BOOST_CHECK_EQUAL(quantized.type(), image.type());\n\n std::vector<cv::Mat> planes;\n cv::split(quantized, planes);\n BOOST_CHECK(test::hasMinMax(planes[0], 1, levels[0]));\n BOOST_CHECK(test::hasMinMax(planes[1], 1, levels[1]));\n BOOST_CHECK(test::hasMinMax(planes[2], 1, levels[2]));\n\n if (argc > 1) {\n display(\"image\", image);\n display(\"hsv\", swapChannels(hsv)); \/\/ HSV channels are interpreted as BGR\n\n planes[0] \/= levels[0];\n planes[1] \/= levels[1];\n planes[2] \/= levels[2];\n cv::merge(planes, quantized);\n display(\"quantized\", swapChannels(quantized)); \/\/ idem\n\n cv::Mat bgr = vis::toBgr(quantized);\n display(\"rgb\", bgr);\n\n println(\"Press a key to continue\");\n cv::waitKey(0);\n }\n}\n\nBOOST_AUTO_TEST_CASE(test_imquantize) {\n cv::Mat data = (cv::Mat_<float>(5,5) << 17, 23, 4, 10, 11,\n 24, 5, 6, 12, 18,\n 1, 7, 13, 19, 25,\n 8, 14, 20, 21, 2,\n 15, 16, 22, 3, 9);\n\n arma::fvec thresholds = { 1, 6, 11, 16, 21 };\n\n cv::Mat expected = (cv::Mat_<float>(5,5) << 5, 6, 1, 3, 4,\n 6, 2, 3, 4, 4,\n 2, 2, 4, 5, 6,\n 3, 4, 5, 5, 2,\n 3, 5, 6, 2, 3);\n\n cv::Mat actual = vis::imquantize(data.t(), thresholds); \/\/ NOTE transposed wrt Matlab\n\n printmat(expected);\n printmat(actual);\n\n BOOST_CHECK(test::equals(expected, actual));\n}\n\nBOOST_AUTO_TEST_CASE(test_medfilt2) {\n cv::Mat data = (cv::Mat_<float>(5,5) << 17, 23, 4, 10, 11,\n 24, 5, 6, 12, 18,\n 1, 7, 13, 19, 25,\n 8, 14, 20, 21, 2,\n 15, 16, 22, 3, 9);\n\n cv::Mat expected = (cv::Mat_<float>(5,5) << 17, 17, 8, 8, 15,\n 17, 7, 8, 14, 16,\n 10, 10, 13, 16, 16,\n 10, 12, 18, 19, 9,\n 11, 18, 18, 9, 9);\n\n cv::Mat actual = vis::medfilt2(data.t()); \/\/ NOTE transposed wrt Matlab\n\n printmat(data);\n printmat(expected);\n printmat(actual);\n\n BOOST_CHECK(test::equals(expected, actual));\n}\n\n<|endoftext|>"} {"text":"<commit_before>#ifndef ALEPH_TOPOLOGY_MESH_HH__\n#define ALEPH_TOPOLOGY_MESH_HH__\n\n#include <cassert>\n\n#include <algorithm>\n#include <iterator>\n#include <memory>\n#include <stdexcept>\n#include <unordered_map>\n#include <unordered_set>\n#include <vector>\n\nnamespace aleph\n{\n\nnamespace topology\n{\n\n\/**\n @class Mesh\n @brief Half-edge mesh data structure\n\n This data structure is capable of representing two-dimensional piecewise\n linear manifolds. In order to speed up standard queries, this class uses\n a standard half-edge data structure.\n*\/\n\ntemplate <class Position = float, class Data = float> class Mesh\n{\npublic:\n struct Face;\n struct HalfEdge;\n struct Vertex;\n\n using Index = std::size_t;\n\n using FacePointer = std::shared_ptr<Face>;\n using HalfEdgePointer = std::shared_ptr<HalfEdge>;\n using VertexPointer = std::shared_ptr<Vertex>;\n\n struct HalfEdge\n {\n FacePointer face;\n VertexPointer vertex;\n\n HalfEdgePointer next; \/\/ Next half-edge (counter-clockwise)\n HalfEdgePointer prev; \/\/ Previous half-edge\n HalfEdgePointer pair; \/\/ Opposite half-edge\n\n VertexPointer source() const noexcept\n {\n return pair->vertex;\n }\n\n VertexPointer target() const noexcept\n {\n return vertex;\n }\n };\n\n struct Face\n {\n HalfEdgePointer edge;\n\n \/**\n Collects all vertices of the given face. Vertex IDs will be\n returned in the order in which they are traversed along the\n face.\n *\/\n\n std::vector<Index> vertices() const\n {\n std::vector<Index> v;\n\n auto e = edge;\n\n do\n {\n v.push_back( e->target->id );\n e = e->next;\n }\n while( e != edge );\n\n return v;\n }\n };\n\n struct Vertex\n {\n Index id = Index();\n Position x = Position();\n Position y = Position();\n Position z = Position();\n Data data = Data();\n\n HalfEdgePointer edge;\n };\n\n \/\/ Mesh attributes ---------------------------------------------------\n\n std::size_t vertices() const noexcept\n {\n return _vertices.size();\n }\n\n std::size_t faces() const noexcept\n {\n std::unordered_set<FacePointer> faces;\n\n for( auto&& pair : _vertices )\n {\n auto&& vertex = pair.second;\n auto&& edge = vertex->edge;\n auto&& face = edge->face;\n\n if( face )\n faces.insert( face );\n }\n\n return faces.size();\n }\n\n \/\/ Mesh modification -------------------------------------------------\n\n \/** Adds a new vertex to the mesh *\/\n void addVertex( Position x, Position y, Position z, Data data = Data(), Index id = Index() )\n {\n Vertex v;\n\n v.id = id == Index() ? std::max( _vertices.size(), _largestVertexID ) : id;\n v.x = x;\n v.y = y;\n v.z = z;\n v.data = data;\n\n auto pair = _vertices.insert( std::make_pair( v.id,\n std::make_shared<Vertex>( v ) ) );\n\n if( !pair.second )\n throw std::runtime_error( \"Vertex ID must be unique\" );\n\n _largestVertexID = std::max( _largestVertexID, v.id );\n }\n\n \/**\n Adds a new face to the mesh. This function expects a range of vertex IDs\n that make up the face. The vertices of the face need to sorted correctly\n in order for the orientation to be consistent.\n *\/\n\n template <class InputIterator> void addFace( InputIterator begin, InputIterator end )\n {\n FacePointer face = std::make_shared<Face>();\n\n \/\/ Stores all half-edges created (or found) by this function in the\n \/\/ order in which they belong to the face.\n std::vector<HalfEdgePointer> edges;\n edges.reserve( static_cast<std::size_t>( std::distance( begin, end ) ) );\n\n for( InputIterator it = begin; it != end; ++it )\n {\n auto curr = it;\n auto next = std::next( it );\n\n if( next == end )\n next = begin;\n\n auto source = _vertices.at( *curr ); \/\/ Edge source vertex\n auto target = _vertices.at( *next ); \/\/ Edge target vertex\n auto edge = getEdge( *curr, *next ); \/\/ Edge\n\n \/\/ Case 1: A new edge. Create a new edge and a new pair. Set edges\n \/\/ of source and target vertex correctly. Moreover, initialize the\n \/\/ paired edge with sensible default values.\n if( !edge )\n {\n edge = std::make_shared<HalfEdge>();\n auto pair = std::make_shared<HalfEdge>();\n\n pair->vertex = source; \/\/ This is flipped by design: We point to the\n \/\/ target vertex of the flipped edge. This is\n \/\/ just the source vertex again.\n\n pair->pair = edge;\n edge->pair = pair;\n\n if( !source->edge )\n source->edge = edge;\n\n if( !target->edge )\n target->edge = pair;\n }\n\n assert( !edge->face );\n assert( edge->pair );\n\n edge->face = face;\n edge->vertex = target;\n\n edges.push_back( edge );\n }\n\n \/\/ Set 'next' and 'prev' pointers correctly ------------------------\n \/\/\n \/\/ We first traverse all edges that bound the current face. Here, it\n \/\/ should be possible to traverse the face directly, so we require a\n \/\/ proper pointer in both directions.\n\n for( auto itEdge = edges.begin(); itEdge != edges.end(); ++itEdge )\n {\n auto curr = itEdge;\n auto prev = std::prev( curr );\n auto next = std::next( curr );\n\n if( curr == edges.begin() )\n prev = std::prev( edges.end() );\n\n if( next == edges.end() )\n next = edges.begin();\n\n auto&& edge = *itEdge;\n\n edge->next = *next;\n edge->prev = *prev;\n }\n\n \/\/ Extend boundary -------------------------------------------------\n \/\/\n \/\/ Traverse all vertices whose paired edges have an empty face. Any\n \/\/ of these edges is part of the boundary face.\n\n for( auto&& pair : _vertices )\n {\n auto&& vertex = pair.second;\n\n if( !vertex->edge || vertex->edge->pair->face )\n continue;\n\n auto curr = vertex->edge->target();\n auto edge = vertex->edge->pair;\n\n do\n {\n assert( !edge->face );\n auto edges = this->getEdges( *curr );\n\n for( auto&& e : edges )\n {\n if( !e->pair->face )\n {\n e->pair->next = edge;\n\n edge = e->pair;\n curr = e->pair->pair->target();\n\n break;\n }\n }\n }\n while( curr != vertex );\n\n \/\/ Close the loop around the boundary face by adding a pointer to\n \/\/ the identified edge.\n vertex->edge->pair->next = edge;\n }\n }\n\n \/\/ Mesh queries ------------------------------------------------------\n\n \/**\n The closed star of a vertex is defined as the smallest simplicial\n subcomplex containing the given vertex and all simplices of which\n the vertex is a face.\n *\/\n\n Mesh closedStar( const Vertex& v ) const noexcept\n {\n Mesh M;\n auto faces = this->getFaces( v );\n\n {\n std::unordered_set<VertexPointer> vertices;\n\n for( auto&& f : faces )\n {\n auto&& v = f->vertices();\n vertices.insert( vertices.end(), v.begin(), v.end() );\n }\n\n for( auto&& v : vertices )\n M.addVertex( v.x, v.y, v.z, v.d, v.id );\n }\n\n for( auto&& f : faces )\n {\n auto&& vertices = f->vertices();\n M.addFace( vertices.begin(), vertices.end() );\n }\n\n return M;\n }\n\n \/**\n The link of a vertex is defined as all simplices in the closed star\n that are disjoint from the vertex. For 2-manifolds, this will yield\n a cycle of edges and vertices.\n\n This function will represent the cycle by returning all vertex IDs,\n in an order that is consistent with the orientation of the mesh.\n *\/\n\n std::vector<Index> link( const Vertex& v ) const noexcept\n {\n auto neighbours = this->getNeighbours( v );\n\n std::vector<Index> result;\n result.reserve( neighbours.size() );\n\n for( auto&& neighbour : neighbours )\n result.push_back( neighbour->id );\n\n return result;\n }\n\n std::vector<VertexPointer> getLowerNeighbours( const Vertex& v ) const noexcept\n {\n auto neighbours = this->getNeighbours( v );\n auto data = v.data;\n\n neighbours.erase( std::remove_if( neighbours.begin(), neighbours.end(),\n [&data] ( const VertexPointer& neighbour )\n {\n return neighbour->data >= data;\n } ),\n neighbours.end() );\n\n return neighbours;\n }\n\n std::vector<VertexPointer> getHigherNeighbours( const Vertex& v ) const noexcept\n {\n auto neighbours = this->getNeighbours( v );\n auto data = v.data;\n\n neighbours.erase( std::remove_if( neighbours.begin(), neighbours.end(),\n [&data] ( const VertexPointer& neighbour )\n {\n return neighbour->data <= data;\n } ),\n neighbours.end() );\n\n return neighbours;\n }\n\n VertexPointer vertex( Index id ) const\n {\n return _vertices.at( id );\n }\n\n \/**\n Checks whether an edge between two vertices that are identified by\n their index exists.\n *\/\n\n bool hasEdge( Index u, Index v ) const\n {\n auto&& source = this->vertex(u);\n auto&& target = this->vertex(v);\n\n auto neighbours = this->getNeighbours( *source );\n\n return std::find( neighbours.begin(), neighbours.end(), target ) != neighbours.end();\n }\n\nprivate:\n\n \/** Gets all vertices that are adjacent to a given vertex *\/\n std::vector<VertexPointer> getNeighbours( const Vertex& v ) const noexcept\n {\n std::vector<VertexPointer> neighbours;\n\n auto edge = v.edge;\n do\n {\n if( edge )\n neighbours.push_back( edge->target() );\n else\n break;\n\n edge = edge->pair->next;\n }\n while( edge != v.edge );\n\n return neighbours;\n }\n\n \/** Gets all edges that are incident on a given vertex. *\/\n std::vector<HalfEdgePointer> getEdges( const Vertex& v ) const noexcept\n {\n std::vector<HalfEdgePointer> edges;\n\n auto edge = v.edge;\n do\n {\n if( edge )\n edges.push_back( edge );\n else\n break;\n\n edge = edge->pair->next;\n }\n while( edge != v.edge );\n\n return edges;\n }\n\n \/** Gets all faces that are incident on a given vertex *\/\n std::vector<FacePointer> getFaces( const Vertex& v ) const noexcept\n {\n std::vector<FacePointer> faces;\n\n auto edge = v.edge;\n do\n {\n if( edge && edge->face )\n faces.push_back( edge->face );\n else\n break;\n\n edge = edge->pair->next;\n }\n while( edge != v.edge );\n\n return faces;\n }\n\n \/**\n Check whether a given (directed) edge already exists. If so,\n a pointer to the edge is being returned.\n *\/\n\n HalfEdgePointer getEdge( Index u, Index v ) const noexcept\n {\n auto source = _vertices.at(u); \/\/ Edge source vertex\n auto target = _vertices.at(v); \/\/ Edge target vertex\n auto edges = this->getEdges( *source ); \/\/ Incident edges\n\n auto itEdge = std::find_if( edges.begin(), edges.end(),\n [&source, &target] ( const HalfEdgePointer& edge )\n {\n return edge->source() == source && edge->target() == target;\n } );\n\n if( itEdge != edges.end() )\n return *itEdge;\n else\n return nullptr;\n }\n\n \/**\n Stores largest vertex ID. This is required in order to ensure\n that vertex IDs are not assigned multiple times when the user\n adds vertices one after the other.\n *\/\n\n Index _largestVertexID = Index();\n\n \/**\n Stores all vertex pointers. This is sufficient to store the\n complete mesh.\n *\/\n\n std::unordered_map<Index, VertexPointer> _vertices;\n};\n\n} \/\/ namespace topology\n\n} \/\/ namespace aleph\n\n#endif\n<commit_msg>Started refactoring vertex query interface<commit_after>#ifndef ALEPH_TOPOLOGY_MESH_HH__\n#define ALEPH_TOPOLOGY_MESH_HH__\n\n#include <cassert>\n\n#include <algorithm>\n#include <iterator>\n#include <memory>\n#include <stdexcept>\n#include <unordered_map>\n#include <unordered_set>\n#include <vector>\n\nnamespace aleph\n{\n\nnamespace topology\n{\n\n\/**\n @class Mesh\n @brief Half-edge mesh data structure\n\n This data structure is capable of representing two-dimensional piecewise\n linear manifolds. In order to speed up standard queries, this class uses\n a standard half-edge data structure.\n*\/\n\ntemplate <class Position = float, class Data = float> class Mesh\n{\npublic:\n struct Face;\n struct HalfEdge;\n struct Vertex;\n\n using Index = std::size_t;\n\n using FacePointer = std::shared_ptr<Face>;\n using HalfEdgePointer = std::shared_ptr<HalfEdge>;\n using VertexPointer = std::shared_ptr<Vertex>;\n\n struct HalfEdge\n {\n FacePointer face;\n VertexPointer vertex;\n\n HalfEdgePointer next; \/\/ Next half-edge (counter-clockwise)\n HalfEdgePointer prev; \/\/ Previous half-edge\n HalfEdgePointer pair; \/\/ Opposite half-edge\n\n VertexPointer source() const noexcept\n {\n return pair->vertex;\n }\n\n VertexPointer target() const noexcept\n {\n return vertex;\n }\n };\n\n struct Face\n {\n HalfEdgePointer edge;\n\n \/**\n Collects all vertices of the given face. Vertex IDs will be\n returned in the order in which they are traversed along the\n face.\n *\/\n\n std::vector<Index> vertices() const\n {\n std::vector<Index> v;\n\n auto e = edge;\n\n do\n {\n v.push_back( e->target->id );\n e = e->next;\n }\n while( e != edge );\n\n return v;\n }\n };\n\n struct Vertex\n {\n Index id = Index();\n Position x = Position();\n Position y = Position();\n Position z = Position();\n Data data = Data();\n\n HalfEdgePointer edge;\n };\n\n \/\/ Mesh attributes ---------------------------------------------------\n\n std::size_t vertices() const noexcept\n {\n return _vertices.size();\n }\n\n std::size_t faces() const noexcept\n {\n std::unordered_set<FacePointer> faces;\n\n for( auto&& pair : _vertices )\n {\n auto&& vertex = pair.second;\n auto&& edge = vertex->edge;\n auto&& face = edge->face;\n\n if( face )\n faces.insert( face );\n }\n\n return faces.size();\n }\n\n \/\/ Mesh modification -------------------------------------------------\n\n \/** Adds a new vertex to the mesh *\/\n void addVertex( Position x, Position y, Position z, Data data = Data(), Index id = Index() )\n {\n Vertex v;\n\n v.id = id == Index() ? std::max( _vertices.size(), _largestVertexID ) : id;\n v.x = x;\n v.y = y;\n v.z = z;\n v.data = data;\n\n auto pair = _vertices.insert( std::make_pair( v.id,\n std::make_shared<Vertex>( v ) ) );\n\n if( !pair.second )\n throw std::runtime_error( \"Vertex ID must be unique\" );\n\n _largestVertexID = std::max( _largestVertexID, v.id );\n }\n\n \/**\n Adds a new face to the mesh. This function expects a range of vertex IDs\n that make up the face. The vertices of the face need to sorted correctly\n in order for the orientation to be consistent.\n *\/\n\n template <class InputIterator> void addFace( InputIterator begin, InputIterator end )\n {\n FacePointer face = std::make_shared<Face>();\n\n \/\/ Stores all half-edges created (or found) by this function in the\n \/\/ order in which they belong to the face.\n std::vector<HalfEdgePointer> edges;\n edges.reserve( static_cast<std::size_t>( std::distance( begin, end ) ) );\n\n for( InputIterator it = begin; it != end; ++it )\n {\n auto curr = it;\n auto next = std::next( it );\n\n if( next == end )\n next = begin;\n\n auto source = _vertices.at( *curr ); \/\/ Edge source vertex\n auto target = _vertices.at( *next ); \/\/ Edge target vertex\n auto edge = getEdge( *curr, *next ); \/\/ Edge\n\n \/\/ Case 1: A new edge. Create a new edge and a new pair. Set edges\n \/\/ of source and target vertex correctly. Moreover, initialize the\n \/\/ paired edge with sensible default values.\n if( !edge )\n {\n edge = std::make_shared<HalfEdge>();\n auto pair = std::make_shared<HalfEdge>();\n\n pair->vertex = source; \/\/ This is flipped by design: We point to the\n \/\/ target vertex of the flipped edge. This is\n \/\/ just the source vertex again.\n\n pair->pair = edge;\n edge->pair = pair;\n\n if( !source->edge )\n source->edge = edge;\n\n if( !target->edge )\n target->edge = pair;\n }\n\n assert( !edge->face );\n assert( edge->pair );\n\n edge->face = face;\n edge->vertex = target;\n\n edges.push_back( edge );\n }\n\n \/\/ Set 'next' and 'prev' pointers correctly ------------------------\n \/\/\n \/\/ We first traverse all edges that bound the current face. Here, it\n \/\/ should be possible to traverse the face directly, so we require a\n \/\/ proper pointer in both directions.\n\n for( auto itEdge = edges.begin(); itEdge != edges.end(); ++itEdge )\n {\n auto curr = itEdge;\n auto prev = std::prev( curr );\n auto next = std::next( curr );\n\n if( curr == edges.begin() )\n prev = std::prev( edges.end() );\n\n if( next == edges.end() )\n next = edges.begin();\n\n auto&& edge = *itEdge;\n\n edge->next = *next;\n edge->prev = *prev;\n }\n\n \/\/ Extend boundary -------------------------------------------------\n \/\/\n \/\/ Traverse all vertices whose paired edges have an empty face. Any\n \/\/ of these edges is part of the boundary face.\n\n for( auto&& pair : _vertices )\n {\n auto&& vertex = pair.second;\n\n if( !vertex->edge || vertex->edge->pair->face )\n continue;\n\n auto curr = vertex->edge->target();\n auto edge = vertex->edge->pair;\n\n do\n {\n assert( !edge->face );\n auto edges = this->getEdges( *curr );\n\n for( auto&& e : edges )\n {\n if( !e->pair->face )\n {\n e->pair->next = edge;\n\n edge = e->pair;\n curr = e->pair->pair->target();\n\n break;\n }\n }\n }\n while( curr != vertex );\n\n \/\/ Close the loop around the boundary face by adding a pointer to\n \/\/ the identified edge.\n vertex->edge->pair->next = edge;\n }\n }\n\n \/\/ Mesh queries ------------------------------------------------------\n\n \/**\n The closed star of a vertex is defined as the smallest simplicial\n subcomplex containing the given vertex and all simplices of which\n the vertex is a face.\n *\/\n\n Mesh closedStar( const Vertex& v ) const noexcept\n {\n Mesh M;\n auto faces = this->getFaces( v );\n\n {\n std::unordered_set<VertexPointer> vertices;\n\n for( auto&& f : faces )\n {\n auto&& v = f->vertices();\n vertices.insert( vertices.end(), v.begin(), v.end() );\n }\n\n for( auto&& v : vertices )\n M.addVertex( v.x, v.y, v.z, v.d, v.id );\n }\n\n for( auto&& f : faces )\n {\n auto&& vertices = f->vertices();\n M.addFace( vertices.begin(), vertices.end() );\n }\n\n return M;\n }\n\n \/**\n The link of a vertex is defined as all simplices in the closed star\n that are disjoint from the vertex. For 2-manifolds, this will yield\n a cycle of edges and vertices.\n\n This function will represent the cycle by returning all vertex IDs,\n in an order that is consistent with the orientation of the mesh.\n *\/\n\n std::vector<Index> link( const Vertex& v ) const noexcept\n {\n auto neighbours = this->getNeighbours( v );\n\n std::vector<Index> result;\n result.reserve( neighbours.size() );\n\n for( auto&& neighbour : neighbours )\n result.push_back( neighbour->id );\n\n return result;\n }\n\n std::vector<VertexPointer> getLowerNeighbours( const Vertex& v ) const noexcept\n {\n auto neighbours = this->getNeighbours( v );\n auto data = v.data;\n\n neighbours.erase( std::remove_if( neighbours.begin(), neighbours.end(),\n [&data] ( const VertexPointer& neighbour )\n {\n return neighbour->data >= data;\n } ),\n neighbours.end() );\n\n return neighbours;\n }\n\n std::vector<VertexPointer> getHigherNeighbours( const Vertex& v ) const noexcept\n {\n auto neighbours = this->getNeighbours( v );\n auto data = v.data;\n\n neighbours.erase( std::remove_if( neighbours.begin(), neighbours.end(),\n [&data] ( const VertexPointer& neighbour )\n {\n return neighbour->data <= data;\n } ),\n neighbours.end() );\n\n return neighbours;\n }\n\n \/**\n Checks whether an edge between two vertices that are identified by\n their index exists.\n *\/\n\n bool hasEdge( Index u, Index v ) const\n {\n auto&& source = this->getVertex(u);\n auto&& target = this->getVertex(v);\n\n auto neighbours = this->getNeighbours( *source );\n\n return std::find( neighbours.begin(), neighbours.end(), target ) != neighbours.end();\n }\n\nprivate:\n\n \/** Gets all vertices that are adjacent to a given vertex *\/\n std::vector<VertexPointer> getNeighbours( const Vertex& v ) const noexcept\n {\n std::vector<VertexPointer> neighbours;\n\n auto edge = v.edge;\n do\n {\n if( edge )\n neighbours.push_back( edge->target() );\n else\n break;\n\n edge = edge->pair->next;\n }\n while( edge != v.edge );\n\n return neighbours;\n }\n\n \/** Gets all edges that are incident on a given vertex. *\/\n std::vector<HalfEdgePointer> getEdges( const Vertex& v ) const noexcept\n {\n std::vector<HalfEdgePointer> edges;\n\n auto edge = v.edge;\n do\n {\n if( edge )\n edges.push_back( edge );\n else\n break;\n\n edge = edge->pair->next;\n }\n while( edge != v.edge );\n\n return edges;\n }\n\n \/** Gets all faces that are incident on a given vertex *\/\n std::vector<FacePointer> getFaces( const Vertex& v ) const noexcept\n {\n std::vector<FacePointer> faces;\n\n auto edge = v.edge;\n do\n {\n if( edge && edge->face )\n faces.push_back( edge->face );\n else\n break;\n\n edge = edge->pair->next;\n }\n while( edge != v.edge );\n\n return faces;\n }\n\n \/**\n Check whether a given (directed) edge already exists. If so,\n a pointer to the edge is being returned.\n *\/\n\n HalfEdgePointer getEdge( Index u, Index v ) const noexcept\n {\n auto source = _vertices.at(u); \/\/ Edge source vertex\n auto target = _vertices.at(v); \/\/ Edge target vertex\n auto edges = this->getEdges( *source ); \/\/ Incident edges\n\n auto itEdge = std::find_if( edges.begin(), edges.end(),\n [&source, &target] ( const HalfEdgePointer& edge )\n {\n return edge->source() == source && edge->target() == target;\n } );\n\n if( itEdge != edges.end() )\n return *itEdge;\n else\n return nullptr;\n }\n\n \/**\n Returns vertex with the given ID. This is an internal function\n that is used to obtain all information about a vertex.\n *\/\n\n VertexPointer getVertex( Index id ) const\n {\n return _vertices.at( id );\n }\n\n \/**\n Stores largest vertex ID. This is required in order to ensure\n that vertex IDs are not assigned multiple times when the user\n adds vertices one after the other.\n *\/\n\n Index _largestVertexID = Index();\n\n \/**\n Stores all vertex pointers. This is sufficient to store the\n complete mesh.\n *\/\n\n std::unordered_map<Index, VertexPointer> _vertices;\n};\n\n} \/\/ namespace topology\n\n} \/\/ namespace aleph\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/\/ (C) 2014 Arek Olek\n\n#pragma once\n\n#include <algorithm>\n#include <stack>\n#include <vector>\n\n#include <boost\/graph\/adjacency_list.hpp>\n\n#include \"range.hpp\"\n\nnamespace detail {\n\n unsigned typedef node;\n std::pair<node, node> typedef edge;\n\n template <class Graph>\n void visit(Graph& G, Graph& T, node v, std::vector<bool>& visited,\n std::vector<unsigned>& deg, std::stack<edge>& edges) {\n\n visited[v] = true;\n\n node w = -1, x, y;\n unsigned min_deg = UINT_MAX;\n\n for(auto u : range(adjacent_vertices(v, G))) {\n --deg[u];\n\n if(!visited[u] && deg[u] < min_deg) {\n w = u;\n min_deg = deg[u];\n }\n }\n\n if(min_deg == UINT_MAX) {\n while(!edges.empty() && !visited[edges.top().second])\n edges.pop();\n if(edges.empty())\n return;\n std::tie(x, y) = edges.top();\n } else std::tie(x, y) = edge(v, w);\n\n add_edge(x, y, T);\n\n for(auto u : range(adjacent_vertices(x, G)))\n if(u != y && !visited[u])\n edges.emplace(x, u);\n\n visit(G, T, y, visited, deg, edges);\n }\n\n}\n\ntemplate <class Graph>\nGraph rdfs_tree(Graph& G) {\n unsigned n = num_vertices(G);\n Graph T(n);\n std::vector<bool> visited(n, 0);\n std::vector<unsigned> deg(n, 0);\n std::stack<detail::edge> edges;\n\n for(auto v : range(vertices(G)))\n deg[v] = degree(v, G);\n\n detail::visit(G, T, 0, visited, deg, edges);\n\n return T;\n}\n\ntemplate <class Graph>\nGraph rdfs_sort_tree(Graph const & G) {\n typedef std::pair<int, int> edge;\n std::vector<unsigned> deg(num_vertices(G));\n std::vector<bool> V(num_vertices(G));\n std::stack<edge> Q;\n Graph T(num_vertices(G));\n int parent, v = 0;\n Q.emplace(-1, v);\n for(auto v : range(vertices(G))) deg[v] = degree(v, G);\n while(!Q.empty()) {\n std::tie(parent, v) = Q.top();\n Q.pop();\n if(!V[v]) {\n V[v] = true;\n if(parent >= 0) add_edge(parent, v, T);\n std::vector<unsigned> neighbors;\n for(auto w : range(adjacent_vertices(v, G))) if(!V[w]) {\n --deg[w];\n neighbors.push_back(w);\n }\n std::sort(neighbors.begin(), neighbors.end(), [°](unsigned a, unsigned b) {\n return deg[a] > deg[b];\n });\n for(auto w : neighbors) Q.emplace(v, w);\n }\n }\n return T;\n}\n\ntemplate <class IntType = int, class Generator = std::default_random_engine>\nclass Random {\npublic:\n IntType operator()(IntType a = 0, IntType b = std::numeric_limits<IntType>::max()) {\n return std::uniform_int_distribution<IntType>{a, b}(generator);\n }\nprivate:\n Generator generator;\n};\n\ntemplate <class Graph>\nGraph rdfs_rand_tree(Graph const & G) {\n const int NONE = -1, ADDED = -2;\n std::vector<int> status(num_vertices(G), NONE);\n std::vector<int> degree(num_vertices(G), 0);\n for(auto v : range(vertices(G))) degree[v] = boost::degree(v, G);\n Graph T(num_vertices(G));\n int v = 0;\n status[v] = ADDED;\n Random<unsigned> random;\n for(int i = 1; i < num_vertices(G); ++i) {\n int min_degree = INT_MAX, min_vertex = -1;\n for(auto w : range(adjacent_vertices(v, G))) if(status[w] != ADDED) {\n \/\/ choose random branching as parent\n if(random(degree[w], boost::degree(w, G)) == boost::degree(w, G)) status[w] = v;\n assert(status[w] != NONE || status[w] == v);\n \/\/ neighbors have one option less\n --degree[w];\n \/\/ select neighbor minimizing degree\n if(degree[w] < min_degree) {\n min_degree = degree[w];\n min_vertex = w;\n }\n }\n if(min_vertex == -1) {\n \/\/ dead-end, backtrack to a vertex with minimum degree\n for(unsigned i = 0; i < status.size(); ++i)\n if(status[i] != NONE && status[i] != ADDED && degree[i] < min_degree) {\n min_degree = degree[i];\n min_vertex = i;\n }\n assert(min_vertex != -1);\n } else {\n status[min_vertex] = v;\n }\n v = min_vertex;\n add_edge(status[v], v, T);\n status[v] = ADDED;\n }\n \/\/show(\"tree-test.dot\", G, T);\n return T;\n}\n<commit_msg>simpler rdfs visit<commit_after>\/\/ (C) 2014 Arek Olek\n\n#pragma once\n\n#include <algorithm>\n#include <stack>\n#include <vector>\n\n#include <boost\/graph\/adjacency_list.hpp>\n\n#include \"range.hpp\"\n\nnamespace detail {\n\n unsigned typedef node;\n std::pair<node, node> typedef edge;\n\n template <class Graph>\n void visit(Graph& G, Graph& T, node v, std::vector<bool>& visited,\n std::vector<unsigned>& deg, std::stack<edge>& edges) {\n\n visited[v] = true;\n\n node w = -1, x, y;\n unsigned min_deg = UINT_MAX;\n\n for(auto u : range(adjacent_vertices(v, G))) {\n --deg[u];\n\n if(!visited[u] && deg[u] < min_deg) {\n w = u;\n min_deg = deg[u];\n }\n }\n\n if(min_deg == UINT_MAX) {\n while(!edges.empty() && visited[edges.top().second])\n edges.pop();\n if(edges.empty())\n return;\n std::tie(x, y) = edges.top();\n } else std::tie(x, y) = edge(v, w);\n\n add_edge(x, y, T);\n\n for(auto u : range(adjacent_vertices(x, G)))\n if(u != y && !visited[u])\n edges.emplace(x, u);\n\n visit(G, T, y, visited, deg, edges);\n }\n\n}\n\ntemplate <class Graph>\nGraph rdfs_tree(Graph& G) {\n unsigned n = num_vertices(G);\n Graph T(n);\n std::vector<bool> visited(n, false);\n std::vector<unsigned> deg(n, 0);\n std::stack<detail::edge> edges;\n\n for(auto v : range(vertices(G)))\n deg[v] = degree(v, G);\n\n detail::visit(G, T, 0, visited, deg, edges);\n\n return T;\n}\n\ntemplate <class Graph>\nvoid visit_node(unsigned v, Graph& G,\n std::vector<bool>& visited, std::vector<int>& degree,\n Graph& T) {\n visited[v] = true;\n for(auto u : range(adjacent_vertices(v, G)))\n --degree[u];\n while(degree[v]) {\n int w = -1, min_deg = INT_MAX;\n for(auto u : range(adjacent_vertices(v, G)))\n if(!visited[u] && degree[u] < min_deg) {\n w = u;\n min_deg = degree[u];\n }\n if(w != -1) {\n boost::add_edge(v, w, T);\n visit_node(w, G, visited, degree, T);\n }\n }\n}\n\ntemplate <class Graph>\nGraph rdfs_tree2(Graph& G) {\n unsigned n = num_vertices(G);\n Graph T(n);\n std::vector<bool> visited(n, false);\n std::vector<int> deg(n, 0);\n std::stack<detail::edge> edges;\n\n for(auto v : range(vertices(G)))\n deg[v] = degree(v, G);\n\n visit_node(0, G, visited, deg, T);\n\n return T;\n}\n\ntemplate <class Graph>\nGraph rdfs_sort_tree(Graph const & G) {\n typedef std::pair<int, int> edge;\n std::vector<unsigned> deg(num_vertices(G));\n std::vector<bool> V(num_vertices(G));\n std::stack<edge> Q;\n Graph T(num_vertices(G));\n int parent, v = 0;\n Q.emplace(-1, v);\n for(auto v : range(vertices(G))) deg[v] = degree(v, G);\n while(!Q.empty()) {\n std::tie(parent, v) = Q.top();\n Q.pop();\n if(!V[v]) {\n V[v] = true;\n if(parent >= 0) add_edge(parent, v, T);\n std::vector<unsigned> neighbors;\n for(auto w : range(adjacent_vertices(v, G))) if(!V[w]) {\n --deg[w];\n neighbors.push_back(w);\n }\n std::sort(neighbors.begin(), neighbors.end(), [°](unsigned a, unsigned b) {\n return deg[a] > deg[b];\n });\n for(auto w : neighbors) Q.emplace(v, w);\n }\n }\n return T;\n}\n\ntemplate <class IntType = int, class Generator = std::default_random_engine>\nclass Random {\npublic:\n IntType operator()(IntType a = 0, IntType b = std::numeric_limits<IntType>::max()) {\n return std::uniform_int_distribution<IntType>{a, b}(generator);\n }\nprivate:\n Generator generator;\n};\n\ntemplate <class Graph>\nGraph rdfs_rand_tree(Graph const & G) {\n const int NONE = -1, ADDED = -2;\n std::vector<int> status(num_vertices(G), NONE);\n std::vector<int> degree(num_vertices(G), 0);\n for(auto v : range(vertices(G))) degree[v] = boost::degree(v, G);\n Graph T(num_vertices(G));\n int v = 0;\n status[v] = ADDED;\n Random<unsigned> random;\n for(int i = 1; i < num_vertices(G); ++i) {\n int min_degree = INT_MAX, min_vertex = -1;\n for(auto w : range(adjacent_vertices(v, G))) if(status[w] != ADDED) {\n \/\/ choose random branching as parent\n if(random(degree[w], boost::degree(w, G)) == boost::degree(w, G)) status[w] = v;\n assert(status[w] != NONE || status[w] == v);\n \/\/ neighbors have one option less\n --degree[w];\n \/\/ select neighbor minimizing degree\n if(degree[w] < min_degree) {\n min_degree = degree[w];\n min_vertex = w;\n }\n }\n if(min_vertex == -1) {\n \/\/ dead-end, backtrack to a vertex with minimum degree\n for(unsigned i = 0; i < status.size(); ++i)\n if(status[i] != NONE && status[i] != ADDED && degree[i] < min_degree) {\n min_degree = degree[i];\n min_vertex = i;\n }\n assert(min_vertex != -1);\n } else {\n status[min_vertex] = v;\n }\n v = min_vertex;\n add_edge(status[v], v, T);\n status[v] = ADDED;\n }\n \/\/show(\"tree-test.dot\", G, T);\n return T;\n}\n<|endoftext|>"} {"text":"<commit_before>\/******************************************************************************\\\n * ___ __ *\n * \/\\_ \\ __\/\\ \\ *\n * \\\/\/\\ \\ \/\\_\\ \\ \\____ ___ _____ _____ __ *\n * \\ \\ \\ \\\/\\ \\ \\ '__`\\ \/'___\\\/\\ '__`\\\/\\ '__`\\ \/'__`\\ *\n * \\_\\ \\_\\ \\ \\ \\ \\L\\ \\\/\\ \\__\/\\ \\ \\L\\ \\ \\ \\L\\ \\\/\\ \\L\\.\\_ *\n * \/\\____\\\\ \\_\\ \\_,__\/\\ \\____\\\\ \\ ,__\/\\ \\ ,__\/\\ \\__\/.\\_\\ *\n * \\\/____\/ \\\/_\/\\\/___\/ \\\/____\/ \\ \\ \\\/ \\ \\ \\\/ \\\/__\/\\\/_\/ *\n * \\ \\_\\ \\ \\_\\ *\n * \\\/_\/ \\\/_\/ *\n * *\n * Copyright (C) 2011, 2012 *\n * Dominik Charousset <dominik.charousset@haw-hamburg.de> *\n * *\n * This file is part of libcppa. *\n * libcppa is free software: you can redistribute it and\/or modify it under *\n * the terms of the GNU Lesser General Public License as published by the *\n * Free Software Foundation, either version 3 of the License *\n * or (at your option) any later version. *\n * *\n * libcppa is distributed in the hope that it will be useful, *\n * but WITHOUT ANY WARRANTY; without even the implied warranty of *\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *\n * See the GNU Lesser General Public License for more details. *\n * *\n * You should have received a copy of the GNU Lesser General Public License *\n * along with libcppa. If not, see <http:\/\/www.gnu.org\/licenses\/>. *\n\\******************************************************************************\/\n\n\n#ifndef INVOKABLE_HPP\n#define INVOKABLE_HPP\n\n#include <vector>\n#include <cstddef>\n#include <cstdint>\n\n#include \"cppa\/match.hpp\"\n#include \"cppa\/any_tuple.hpp\"\n#include \"cppa\/tuple_cast.hpp\"\n#include \"cppa\/util\/duration.hpp\"\n#include \"cppa\/util\/apply_tuple.hpp\"\n#include \"cppa\/util\/fixed_vector.hpp\"\n#include \"cppa\/util\/callable_trait.hpp\"\n\n#include \"cppa\/detail\/intermediate.hpp\"\n\n\/\/ forward declaration\nnamespace cppa { class any_tuple; }\n\nnamespace cppa { namespace detail {\n\nclass invokable_base\n{\n\n invokable_base(invokable_base const&) = delete;\n invokable_base& operator=(invokable_base const&) = delete;\n\n public:\n\n invokable_base() = default;\n virtual ~invokable_base();\n virtual bool invoke(any_tuple const&) const = 0;\n\n};\n\nclass timed_invokable : public invokable_base\n{\n\n util::duration m_timeout;\n\n protected:\n\n timed_invokable(util::duration const&);\n\n public:\n\n inline util::duration const& timeout() const\n {\n return m_timeout;\n }\n\n};\n\ntemplate<class TargetFun>\nclass timed_invokable_impl : public timed_invokable\n{\n\n typedef timed_invokable super;\n\n TargetFun m_target;\n\n public:\n\n template<typename F>\n timed_invokable_impl(util::duration const& d, F&& fun)\n : super(d), m_target(std::forward<F>(fun))\n {\n }\n\n bool invoke(any_tuple const&) const\n {\n m_target();\n return true;\n }\n\n};\n\nclass invokable : public invokable_base\n{\n\n public:\n\n virtual intermediate* get_intermediate(any_tuple const&) = 0;\n\n};\n\ntemplate<size_t NumArgs, typename Fun, class Tuple, class Pattern>\nclass invokable_impl : public invokable\n{\n\n struct iimpl : intermediate\n {\n Fun m_fun;\n Tuple m_args;\n template<typename F> iimpl(F&& fun) : m_fun(std::forward<F>(fun)) { }\n void invoke() { util::apply_tuple(m_fun, m_args); }\n }\n m_iimpl;\n std::unique_ptr<Pattern> m_pattern;\n\n template<typename T>\n bool invoke_impl(T const& data) const\n {\n auto tuple_option = tuple_cast(data, *m_pattern);\n if (tuple_option.valid())\n {\n util::apply_tuple(m_iimpl.m_fun, *tuple_option);\n return true;\n }\n return false;\n }\n\n public:\n\n template<typename F>\n invokable_impl(F&& fun, std::unique_ptr<Pattern>&& pptr)\n : m_iimpl(std::forward<F>(fun)), m_pattern(std::move(pptr))\n {\n }\n\n bool invoke(any_tuple const& data) const\n {\n return invoke_impl(data);\n }\n\n intermediate* get_intermediate(any_tuple const& data)\n {\n auto tuple_option = tuple_cast(data, *m_pattern);\n if (tuple_option.valid())\n {\n m_iimpl.m_args = std::move(*tuple_option);\n return &m_iimpl;\n }\n return nullptr;\n }\n\n};\n\ntemplate<typename Fun, class Tuple, class Pattern>\nclass invokable_impl<0, Fun, Tuple, Pattern> : public invokable\n{\n\n struct iimpl : intermediate\n {\n Fun m_fun;\n template<typename F> iimpl(F&& fun) : m_fun(std::forward<F>(fun)) { }\n void invoke() { m_fun(); }\n }\n m_iimpl;\n std::unique_ptr<Pattern> m_pattern;\n\n template<typename T>\n bool invoke_impl(T const& data) const\n {\n if (match(data, *m_pattern))\n {\n m_iimpl.m_fun();\n return true;\n }\n return false;\n }\n\n public:\n\n template<typename F>\n invokable_impl(F&& fun, std::unique_ptr<Pattern>&& pptr)\n : m_iimpl(std::forward<F>(fun)), m_pattern(std::move(pptr))\n {\n }\n\n bool invoke(any_tuple const& data) const\n {\n return invoke_impl(data);\n }\n\n intermediate* get_intermediate(any_tuple const& data)\n {\n return match(data, *m_pattern) ? &m_iimpl : nullptr;\n }\n\n};\n\ntemplate<typename Fun, class Pattern>\nstruct select_invokable_impl\n{\n typedef typename util::get_arg_types<Fun>::types arg_types;\n typedef typename Pattern::filtered_types filtered_types;\n typedef typename tuple_from_type_list<filtered_types>::type tuple_type;\n typedef invokable_impl<arg_types::size, Fun, tuple_type, Pattern> type;\n};\n\ntemplate<typename Fun, class Pattern>\nstd::unique_ptr<invokable> get_invokable_impl(Fun&& fun,\n std::unique_ptr<Pattern>&& pptr)\n{\n typedef typename select_invokable_impl<Fun, Pattern>::type result;\n return std::unique_ptr<invokable>(new result(std::forward<Fun>(fun),\n std::move(pptr)));\n}\n\n} } \/\/ namespace cppa::detail\n\n#endif \/\/ INVOKABLE_HPP\n<commit_msg>added member function to suppress type checking<commit_after>\/******************************************************************************\\\n * ___ __ *\n * \/\\_ \\ __\/\\ \\ *\n * \\\/\/\\ \\ \/\\_\\ \\ \\____ ___ _____ _____ __ *\n * \\ \\ \\ \\\/\\ \\ \\ '__`\\ \/'___\\\/\\ '__`\\\/\\ '__`\\ \/'__`\\ *\n * \\_\\ \\_\\ \\ \\ \\ \\L\\ \\\/\\ \\__\/\\ \\ \\L\\ \\ \\ \\L\\ \\\/\\ \\L\\.\\_ *\n * \/\\____\\\\ \\_\\ \\_,__\/\\ \\____\\\\ \\ ,__\/\\ \\ ,__\/\\ \\__\/.\\_\\ *\n * \\\/____\/ \\\/_\/\\\/___\/ \\\/____\/ \\ \\ \\\/ \\ \\ \\\/ \\\/__\/\\\/_\/ *\n * \\ \\_\\ \\ \\_\\ *\n * \\\/_\/ \\\/_\/ *\n * *\n * Copyright (C) 2011, 2012 *\n * Dominik Charousset <dominik.charousset@haw-hamburg.de> *\n * *\n * This file is part of libcppa. *\n * libcppa is free software: you can redistribute it and\/or modify it under *\n * the terms of the GNU Lesser General Public License as published by the *\n * Free Software Foundation, either version 3 of the License *\n * or (at your option) any later version. *\n * *\n * libcppa is distributed in the hope that it will be useful, *\n * but WITHOUT ANY WARRANTY; without even the implied warranty of *\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *\n * See the GNU Lesser General Public License for more details. *\n * *\n * You should have received a copy of the GNU Lesser General Public License *\n * along with libcppa. If not, see <http:\/\/www.gnu.org\/licenses\/>. *\n\\******************************************************************************\/\n\n\n#ifndef INVOKABLE_HPP\n#define INVOKABLE_HPP\n\n#include <vector>\n#include <cstddef>\n#include <cstdint>\n\n#include \"cppa\/match.hpp\"\n#include \"cppa\/pattern.hpp\"\n#include \"cppa\/any_tuple.hpp\"\n#include \"cppa\/tuple_cast.hpp\"\n#include \"cppa\/util\/duration.hpp\"\n#include \"cppa\/util\/apply_tuple.hpp\"\n#include \"cppa\/util\/fixed_vector.hpp\"\n#include \"cppa\/util\/callable_trait.hpp\"\n\n#include \"cppa\/detail\/intermediate.hpp\"\n\n\/\/ forward declaration\nnamespace cppa { class any_tuple; }\n\nnamespace cppa { namespace detail {\n\nclass invokable_base\n{\n\n invokable_base(invokable_base const&) = delete;\n invokable_base& operator=(invokable_base const&) = delete;\n\n public:\n\n invokable_base() = default;\n virtual ~invokable_base();\n virtual bool invoke(any_tuple const&) const = 0;\n\n};\n\nclass timed_invokable : public invokable_base\n{\n\n util::duration m_timeout;\n\n protected:\n\n timed_invokable(util::duration const&);\n\n public:\n\n inline util::duration const& timeout() const\n {\n return m_timeout;\n }\n\n};\n\ntemplate<class TargetFun>\nclass timed_invokable_impl : public timed_invokable\n{\n\n typedef timed_invokable super;\n\n TargetFun m_target;\n\n public:\n\n template<typename F>\n timed_invokable_impl(util::duration const& d, F&& fun)\n : super(d), m_target(std::forward<F>(fun))\n {\n }\n\n bool invoke(any_tuple const&) const\n {\n m_target();\n return true;\n }\n\n};\n\nclass invokable : public invokable_base\n{\n\n public:\n\n virtual bool matches_values() const = 0;\n \/\/ Checks whether the types of @p value match the pattern.\n virtual bool types_match(any_tuple const& value) const = 0;\n \/\/ Checks whether this invokable could be invoked with @p value.\n virtual bool could_invoke(any_tuple const& value) const = 0;\n \/\/ Prepare this invokable.\n virtual intermediate* get_intermediate(any_tuple const& value) = 0;\n \/\/ Prepare this invokable and suppress type checking.\n virtual intermediate* get_unsafe_intermediate(any_tuple const& value) = 0;\n \/\/ Suppress type checking.\n virtual bool unsafe_invoke(any_tuple const& value) const = 0;\n\n};\n\ntemplate<size_t NumArgs, typename Fun, class Tuple, class Pattern>\nclass invokable_impl : public invokable\n{\n\n struct iimpl : intermediate\n {\n Fun m_fun;\n Tuple m_args;\n template<typename F> iimpl(F&& fun) : m_fun(std::forward<F>(fun)) { }\n void invoke() { util::apply_tuple(m_fun, m_args); }\n }\n m_iimpl;\n std::unique_ptr<Pattern> m_pattern;\n\n public:\n\n template<typename F>\n invokable_impl(F&& fun, std::unique_ptr<Pattern>&& pptr)\n : m_iimpl(std::forward<F>(fun)), m_pattern(std::move(pptr))\n {\n }\n\n bool invoke(any_tuple const& value) const\n {\n auto tuple_option = tuple_cast(value, *m_pattern);\n if (tuple_option)\n {\n util::apply_tuple(m_iimpl.m_fun, *tuple_option);\n return true;\n }\n return false;\n }\n\n bool unsafe_invoke(any_tuple const& value) const\n {\n auto tuple_option = unsafe_tuple_cast(value, *m_pattern);\n if (tuple_option)\n {\n util::apply_tuple(m_iimpl.m_fun, *tuple_option);\n return true;\n }\n return false;\n }\n\n\n bool matches_values() const\n {\n return m_pattern->has_values();\n }\n\n bool types_match(any_tuple const& value) const\n {\n return match_types(value, *m_pattern);\n }\n\n bool could_invoke(any_tuple const& value) const\n {\n return match(value, *m_pattern);\n }\n\n intermediate* get_intermediate(any_tuple const& value)\n {\n auto tuple_option = tuple_cast(value, *m_pattern);\n if (tuple_option)\n {\n m_iimpl.m_args = std::move(*tuple_option);\n return &m_iimpl;\n }\n return nullptr;\n }\n\n intermediate* get_unsafe_intermediate(any_tuple const& value)\n {\n auto x = unsafe_tuple_cast(value, *m_pattern);\n if (x)\n {\n m_iimpl.m_args = std::move(*x);\n return &m_iimpl;\n }\n return nullptr;\n }\n\n};\n\ntemplate<typename Fun, class Tuple, class Pattern>\nclass invokable_impl<0, Fun, Tuple, Pattern> : public invokable\n{\n\n struct iimpl : intermediate\n {\n Fun m_fun;\n template<typename F> iimpl(F&& fun) : m_fun(std::forward<F>(fun)) { }\n void invoke() { m_fun(); }\n }\n m_iimpl;\n std::unique_ptr<Pattern> m_pattern;\n\n template<typename... P>\n bool unsafe_vmatch(any_tuple const& t, pattern<P...> const& p) const\n {\n return matcher<Pattern::wildcard_pos, P...>::vmatch(t, p);\n }\n\n public:\n\n template<typename F>\n invokable_impl(F&& fun, std::unique_ptr<Pattern>&& pptr)\n : m_iimpl(std::forward<F>(fun)), m_pattern(std::move(pptr))\n {\n }\n\n bool invoke(any_tuple const& data) const\n {\n if (match(data, *m_pattern))\n {\n m_iimpl.m_fun();\n return true;\n }\n return false;\n }\n\n bool unsafe_invoke(any_tuple const& value) const\n {\n if (unsafe_vmatch(value, *m_pattern))\n {\n m_iimpl.m_fun();\n return true;\n }\n return false;\n }\n\n bool matches_values() const\n {\n return m_pattern->has_values();\n }\n\n bool types_match(any_tuple const& value) const\n {\n return match_types(value, *m_pattern);\n }\n\n bool could_invoke(any_tuple const& value) const\n {\n return match(value, *m_pattern);\n }\n\n intermediate* get_intermediate(any_tuple const& value)\n {\n return match(value, *m_pattern) ? &m_iimpl : nullptr;\n }\n\n intermediate* get_unsafe_intermediate(any_tuple const& value)\n {\n return unsafe_vmatch(value, *m_pattern) ? &m_iimpl : nullptr;\n }\n\n};\n\ntemplate<typename Fun, class Pattern>\nstruct select_invokable_impl\n{\n typedef typename util::get_arg_types<Fun>::types arg_types;\n typedef typename Pattern::filtered_types filtered_types;\n typedef typename tuple_from_type_list<filtered_types>::type tuple_type;\n typedef invokable_impl<arg_types::size, Fun, tuple_type, Pattern> type;\n};\n\ntemplate<typename Fun, class Pattern>\nstd::unique_ptr<invokable> get_invokable_impl(Fun&& fun,\n std::unique_ptr<Pattern>&& pptr)\n{\n typedef typename select_invokable_impl<Fun, Pattern>::type result;\n return std::unique_ptr<invokable>(new result(std::forward<Fun>(fun),\n std::move(pptr)));\n}\n\n} } \/\/ namespace cppa::detail\n\n#endif \/\/ INVOKABLE_HPP\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2015 Esri.\n\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include <QGuiApplication>\n#include <QQuickView>\n#include <QUrl>\n#include <QCoreApplication>\n#include <QDir>\n#include <QQmlEngine>\n\nint main(int argc, char *argv[])\n{\n QGuiApplication app(argc, argv);\n \n#ifdef Q_OS_WIN\n \/\/ Force usage of OpenGL ES through ANGLE on Windows\n QCoreApplication::setAttribute(Qt::AA_UseOpenGLES);\n#endif\n\n \/\/ Intialize application view\n QQuickView view;\n view.setResizeMode(QQuickView::SizeRootObjectToView);\n\n \/\/ Add the import Path\n view.engine()->addImportPath(QDir(QCoreApplication::applicationDirPath()).filePath(\"qml\"));\n\n \/\/ Set the source\n QQuickView view;\n view.setResizeMode(QQuickView::SizeRootObjectToView);\n\n \/\/ Add the import Path\n view.engine()->addImportPath(QDir(QCoreApplication::applicationDirPath()).filePath(\"qml\"));\n\n \/\/ Set the source\n view.setSource(QUrl(\"qrc:\/Samples\/Maps\/ChangeBasemap\/ChangeBasemap.qml\"));\n\n view.show();\n\n return app.exec();\n}\n<commit_msg>fixed code<commit_after>\/\/ Copyright 2015 Esri.\n\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include <QGuiApplication>\n#include <QQuickView>\n#include <QUrl>\n#include <QCoreApplication>\n#include <QDir>\n#include <QQmlEngine>\n\nint main(int argc, char *argv[])\n{\n QGuiApplication app(argc, argv);\n \n#ifdef Q_OS_WIN\n \/\/ Force usage of OpenGL ES through ANGLE on Windows\n QCoreApplication::setAttribute(Qt::AA_UseOpenGLES);\n#endif\n\n \/\/ Set the source\n QQuickView view;\n view.setResizeMode(QQuickView::SizeRootObjectToView);\n\n \/\/ Add the import Path\n view.engine()->addImportPath(QDir(QCoreApplication::applicationDirPath()).filePath(\"qml\"));\n\n \/\/ Set the source\n view.setSource(QUrl(\"qrc:\/Samples\/Maps\/ChangeBasemap\/ChangeBasemap.qml\"));\n\n view.show();\n\n return app.exec();\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements. See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership. The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n\/*\n * Copyright (C) 2015 ScyllaDB\n *\n * Modified by ScyllaDB\n *\/\n\n\/*\n * This file is part of Scylla.\n *\n * Scylla is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * Scylla is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with Scylla. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n\n#pragma once\n\n#include \"gc_clock.hh\"\n#include \"timestamp.hh\"\n#include \"schema_fwd.hh\"\n#include \"atomic_cell.hh\"\n#include \"tombstone.hh\"\n#include \"exceptions\/exceptions.hh\"\n#include \"cql3\/query_options.hh\"\n#include \"query-request.hh\"\n#include \"query-result.hh\"\n\nnamespace cql3 {\n\n\/**\n * A simple container that simplify passing parameters for collections methods.\n *\/\nclass update_parameters final {\npublic:\n \/\/ Option set for partition_slice to be used when fetching prefetch_data\n static constexpr query::partition_slice::option_set options = query::partition_slice::option_set::of<\n query::partition_slice::option::send_partition_key,\n query::partition_slice::option::send_clustering_key,\n query::partition_slice::option::collections_as_maps>();\n\n \/\/ Holder for data for\n \/\/ 1) CQL list updates which depend on current state of the list\n \/\/ 2) cells needed to check conditions of a CAS statement,\n \/\/ 3) rows of CAS result set.\n struct prefetch_data {\n using key = std::pair<partition_key, clustering_key>;\n using key_view = std::pair<const partition_key&, const clustering_key&>;\n struct key_less {\n partition_key::tri_compare pk_cmp;\n clustering_key::tri_compare ck_cmp;\n\n key_less(const schema& s)\n : pk_cmp(s)\n , ck_cmp(s)\n { }\n std::strong_ordering tri_compare(const partition_key& pk1, const clustering_key& ck1,\n const partition_key& pk2, const clustering_key& ck2) const {\n\n std::strong_ordering rc = pk_cmp(pk1, pk2);\n return rc != 0 ? rc : ck_cmp(ck1, ck2) <=> 0;\n }\n \/\/ Allow mixing std::pair<partition_key, clustering_key> and\n \/\/ std::pair<const partition_key&, const clustering_key&> during lookup\n template <typename Pair1, typename Pair2>\n bool operator()(const Pair1& k1, const Pair2& k2) const {\n return tri_compare(k1.first, k1.second, k2.first, k2.second) < 0;\n }\n };\n public:\n struct row {\n \/\/ Order CAS columns by ordinal column id.\n std::map<ordinal_column_id, data_value> cells;\n \/\/ Return true if this row has at least one static column set.\n bool has_static_columns(const schema& schema) const {\n if (!schema.has_static_columns()) {\n return false;\n }\n \/\/ Static columns use a continuous range of ids so to efficiently check\n \/\/ if a row has a static cell, we can look up the first cell with id >=\n \/\/ first static column id and check if it's static.\n auto it = cells.lower_bound(schema.static_begin()->ordinal_id);\n if (it == cells.end() || !schema.column_at(it->first).is_static()) {\n return false;\n }\n return true;\n }\n };\n \/\/ Use an ordered map since CAS result set must be naturally ordered\n \/\/ when returned to the client.\n std::map<key, row, key_less> rows;\n schema_ptr schema;\n public:\n prefetch_data(schema_ptr schema);\n \/\/ Find a row object for either static or regular subset of cells, depending\n \/\/ on whether clustering key is empty or not.\n \/\/ A particular cell within the row can then be found using a column id.\n const row* find_row(const partition_key& pkey, const clustering_key& ckey) const;\n };\n \/\/ Note: value (mutation) only required to contain the rows we are interested in\nprivate:\n const gc_clock::duration _ttl;\n \/\/ For operations that require a read-before-write, stores prefetched cell values.\n \/\/ For CAS statements, stores values of conditioned columns.\n \/\/ Is a reference to an outside prefetch_data container since a CAS BATCH statement\n \/\/ prefetches all rows at once, for all its nested modification statements.\n const prefetch_data& _prefetched;\npublic:\n const api::timestamp_type _timestamp;\n const gc_clock::time_point _local_deletion_time;\n const schema_ptr _schema;\n const query_options& _options;\n\n update_parameters(const schema_ptr schema_, const query_options& options,\n api::timestamp_type timestamp, gc_clock::duration ttl, const prefetch_data& prefetched)\n : _ttl(ttl)\n , _prefetched(prefetched)\n , _timestamp(timestamp)\n , _local_deletion_time(gc_clock::now())\n , _schema(std::move(schema_))\n , _options(options)\n {\n \/\/ We use MIN_VALUE internally to mean the absence of of timestamp (in Selection, in sstable stats, ...), so exclude\n \/\/ it to avoid potential confusion.\n if (timestamp < api::min_timestamp || timestamp > api::max_timestamp) {\n throw exceptions::invalid_request_exception(format(\"Out of bound timestamp, must be in [{:d}, {:d}]\",\n api::min_timestamp, api::max_timestamp));\n }\n }\n\n atomic_cell make_dead_cell() const {\n return atomic_cell::make_dead(_timestamp, _local_deletion_time);\n }\n\n atomic_cell make_cell(const abstract_type& type, const raw_value_view& value, atomic_cell::collection_member cm = atomic_cell::collection_member::no) const {\n auto ttl = _ttl;\n\n if (ttl.count() <= 0) {\n ttl = _schema->default_time_to_live();\n }\n\n return value.with_value([&] (const FragmentedView auto& v) {\n if (ttl.count() > 0) {\n return atomic_cell::make_live(type, _timestamp, v, _local_deletion_time + ttl, ttl, cm);\n } else {\n return atomic_cell::make_live(type, _timestamp, v, cm);\n }\n });\n };\n\n atomic_cell make_cell(const abstract_type& type, const managed_bytes_view& value, atomic_cell::collection_member cm = atomic_cell::collection_member::no) const {\n auto ttl = _ttl;\n\n if (ttl.count() <= 0) {\n ttl = _schema->default_time_to_live();\n }\n\n if (ttl.count() > 0) {\n return atomic_cell::make_live(type, _timestamp, value, _local_deletion_time + ttl, ttl, cm);\n } else {\n return atomic_cell::make_live(type, _timestamp, value, cm);\n }\n };\n\n atomic_cell make_cell(const abstract_type& type, const bytes_view& value, atomic_cell::collection_member cm = atomic_cell::collection_member::no) const {\n auto ttl = _ttl;\n\n if (ttl.count() <= 0) {\n ttl = _schema->default_time_to_live();\n }\n\n if (ttl.count() > 0) {\n return atomic_cell::make_live(type, _timestamp, value, _local_deletion_time + ttl, ttl, cm);\n } else {\n return atomic_cell::make_live(type, _timestamp, value, cm);\n }\n };\n\n atomic_cell make_counter_update_cell(int64_t delta) const {\n return atomic_cell::make_live_counter_update(_timestamp, delta);\n }\n\n tombstone make_tombstone() const {\n return {_timestamp, _local_deletion_time};\n }\n\n tombstone make_tombstone_just_before() const {\n return {_timestamp - 1, _local_deletion_time};\n }\n\n gc_clock::duration ttl() const {\n return _ttl.count() > 0 ? _ttl : _schema->default_time_to_live();\n }\n\n gc_clock::time_point expiry() const {\n return ttl() + _local_deletion_time;\n }\n\n api::timestamp_type timestamp() const {\n return _timestamp;\n }\n\n const std::vector<std::pair<data_value, data_value>>*\n get_prefetched_list(const partition_key& pkey, const clustering_key& ckey, const column_definition& column) const;\n\n static prefetch_data build_prefetch_data(schema_ptr schema, const query::result& query_result,\n const query::partition_slice& slice);\n};\n\n}\n<commit_msg>cql3: update_parameters: remove unused version of make_cell for bytes_view<commit_after>\/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements. See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership. The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n\/*\n * Copyright (C) 2015 ScyllaDB\n *\n * Modified by ScyllaDB\n *\/\n\n\/*\n * This file is part of Scylla.\n *\n * Scylla is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * Scylla is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with Scylla. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n\n#pragma once\n\n#include \"gc_clock.hh\"\n#include \"timestamp.hh\"\n#include \"schema_fwd.hh\"\n#include \"atomic_cell.hh\"\n#include \"tombstone.hh\"\n#include \"exceptions\/exceptions.hh\"\n#include \"cql3\/query_options.hh\"\n#include \"query-request.hh\"\n#include \"query-result.hh\"\n\nnamespace cql3 {\n\n\/**\n * A simple container that simplify passing parameters for collections methods.\n *\/\nclass update_parameters final {\npublic:\n \/\/ Option set for partition_slice to be used when fetching prefetch_data\n static constexpr query::partition_slice::option_set options = query::partition_slice::option_set::of<\n query::partition_slice::option::send_partition_key,\n query::partition_slice::option::send_clustering_key,\n query::partition_slice::option::collections_as_maps>();\n\n \/\/ Holder for data for\n \/\/ 1) CQL list updates which depend on current state of the list\n \/\/ 2) cells needed to check conditions of a CAS statement,\n \/\/ 3) rows of CAS result set.\n struct prefetch_data {\n using key = std::pair<partition_key, clustering_key>;\n using key_view = std::pair<const partition_key&, const clustering_key&>;\n struct key_less {\n partition_key::tri_compare pk_cmp;\n clustering_key::tri_compare ck_cmp;\n\n key_less(const schema& s)\n : pk_cmp(s)\n , ck_cmp(s)\n { }\n std::strong_ordering tri_compare(const partition_key& pk1, const clustering_key& ck1,\n const partition_key& pk2, const clustering_key& ck2) const {\n\n std::strong_ordering rc = pk_cmp(pk1, pk2);\n return rc != 0 ? rc : ck_cmp(ck1, ck2) <=> 0;\n }\n \/\/ Allow mixing std::pair<partition_key, clustering_key> and\n \/\/ std::pair<const partition_key&, const clustering_key&> during lookup\n template <typename Pair1, typename Pair2>\n bool operator()(const Pair1& k1, const Pair2& k2) const {\n return tri_compare(k1.first, k1.second, k2.first, k2.second) < 0;\n }\n };\n public:\n struct row {\n \/\/ Order CAS columns by ordinal column id.\n std::map<ordinal_column_id, data_value> cells;\n \/\/ Return true if this row has at least one static column set.\n bool has_static_columns(const schema& schema) const {\n if (!schema.has_static_columns()) {\n return false;\n }\n \/\/ Static columns use a continuous range of ids so to efficiently check\n \/\/ if a row has a static cell, we can look up the first cell with id >=\n \/\/ first static column id and check if it's static.\n auto it = cells.lower_bound(schema.static_begin()->ordinal_id);\n if (it == cells.end() || !schema.column_at(it->first).is_static()) {\n return false;\n }\n return true;\n }\n };\n \/\/ Use an ordered map since CAS result set must be naturally ordered\n \/\/ when returned to the client.\n std::map<key, row, key_less> rows;\n schema_ptr schema;\n public:\n prefetch_data(schema_ptr schema);\n \/\/ Find a row object for either static or regular subset of cells, depending\n \/\/ on whether clustering key is empty or not.\n \/\/ A particular cell within the row can then be found using a column id.\n const row* find_row(const partition_key& pkey, const clustering_key& ckey) const;\n };\n \/\/ Note: value (mutation) only required to contain the rows we are interested in\nprivate:\n const gc_clock::duration _ttl;\n \/\/ For operations that require a read-before-write, stores prefetched cell values.\n \/\/ For CAS statements, stores values of conditioned columns.\n \/\/ Is a reference to an outside prefetch_data container since a CAS BATCH statement\n \/\/ prefetches all rows at once, for all its nested modification statements.\n const prefetch_data& _prefetched;\npublic:\n const api::timestamp_type _timestamp;\n const gc_clock::time_point _local_deletion_time;\n const schema_ptr _schema;\n const query_options& _options;\n\n update_parameters(const schema_ptr schema_, const query_options& options,\n api::timestamp_type timestamp, gc_clock::duration ttl, const prefetch_data& prefetched)\n : _ttl(ttl)\n , _prefetched(prefetched)\n , _timestamp(timestamp)\n , _local_deletion_time(gc_clock::now())\n , _schema(std::move(schema_))\n , _options(options)\n {\n \/\/ We use MIN_VALUE internally to mean the absence of of timestamp (in Selection, in sstable stats, ...), so exclude\n \/\/ it to avoid potential confusion.\n if (timestamp < api::min_timestamp || timestamp > api::max_timestamp) {\n throw exceptions::invalid_request_exception(format(\"Out of bound timestamp, must be in [{:d}, {:d}]\",\n api::min_timestamp, api::max_timestamp));\n }\n }\n\n atomic_cell make_dead_cell() const {\n return atomic_cell::make_dead(_timestamp, _local_deletion_time);\n }\n\n atomic_cell make_cell(const abstract_type& type, const raw_value_view& value, atomic_cell::collection_member cm = atomic_cell::collection_member::no) const {\n auto ttl = _ttl;\n\n if (ttl.count() <= 0) {\n ttl = _schema->default_time_to_live();\n }\n\n return value.with_value([&] (const FragmentedView auto& v) {\n if (ttl.count() > 0) {\n return atomic_cell::make_live(type, _timestamp, v, _local_deletion_time + ttl, ttl, cm);\n } else {\n return atomic_cell::make_live(type, _timestamp, v, cm);\n }\n });\n };\n\n atomic_cell make_cell(const abstract_type& type, const managed_bytes_view& value, atomic_cell::collection_member cm = atomic_cell::collection_member::no) const {\n auto ttl = _ttl;\n\n if (ttl.count() <= 0) {\n ttl = _schema->default_time_to_live();\n }\n\n if (ttl.count() > 0) {\n return atomic_cell::make_live(type, _timestamp, value, _local_deletion_time + ttl, ttl, cm);\n } else {\n return atomic_cell::make_live(type, _timestamp, value, cm);\n }\n };\n\n atomic_cell make_counter_update_cell(int64_t delta) const {\n return atomic_cell::make_live_counter_update(_timestamp, delta);\n }\n\n tombstone make_tombstone() const {\n return {_timestamp, _local_deletion_time};\n }\n\n tombstone make_tombstone_just_before() const {\n return {_timestamp - 1, _local_deletion_time};\n }\n\n gc_clock::duration ttl() const {\n return _ttl.count() > 0 ? _ttl : _schema->default_time_to_live();\n }\n\n gc_clock::time_point expiry() const {\n return ttl() + _local_deletion_time;\n }\n\n api::timestamp_type timestamp() const {\n return _timestamp;\n }\n\n const std::vector<std::pair<data_value, data_value>>*\n get_prefetched_list(const partition_key& pkey, const clustering_key& ckey, const column_definition& column) const;\n\n static prefetch_data build_prefetch_data(schema_ptr schema, const query::result& query_result,\n const query::partition_slice& slice);\n};\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/******************************************************************************\n * This file is part of the Gluon Development Platform\n * Copyright (c) 2010 Arjen Hiemstra <ahiemstra@heimr.nl>\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n *\/\n\n#include \"messagedock.h\"\n\n#include <core\/gluon_global.h>\n#include <engine\/game.h>\n\n#include <KDE\/KLocalizedString>\n#include <KDE\/KToolBar>\n#include <KDE\/KAction>\n\n\/\/ Yup, this should be a view... but for now...\n#include <QtGui\/QListWidget>\n#include <QtGui\/QVBoxLayout>\n#include <QtGui\/QApplication>\n#include <QtGui\/QClipboard>\n\nusing namespace GluonCreator;\n\nclass MessageDock::MessageDockPrivate\n{\n public:\n MessageDockPrivate()\n {\n view = 0;\n }\n QListWidget* view;\n};\n\nMessageDock::MessageDock( const QString& title, QWidget* parent, Qt::WindowFlags flags )\n : QDockWidget( title, parent, flags ),\n d( new MessageDockPrivate )\n{\n setObjectName( \"MessageDock\" );\n\n d->view = new QListWidget( this );\n d->view->addItem( new QListWidgetItem( i18n( \"Welcome to Gluon Creator %1\" ).arg( GluonCore::Global::versionString() ), d->view ) );\n\n connect( GluonEngine::Game::instance(), SIGNAL( showDebug( const QString& ) ), SLOT( showDebug( const QString& ) ) );\n\n QWidget* widget = new QWidget( this );\n QVBoxLayout* layout = new QVBoxLayout();\n layout->setContentsMargins( 0, 0, 0, 0 );\n layout->setSpacing( 0 );\n widget->setLayout( layout );\n\n KToolBar* toolBar = new KToolBar(this);\n toolBar->setIconDimensions(16);\n\n QAction* selectAll = toolBar->addAction(KIcon(\"edit-select-all\"), i18n(\"Select All\"), this, SLOT( selectAll() ) );\n d->view->addAction( selectAll );\n\n QAction* copy = toolBar->addAction(KIcon(\"edit-copy\"), i18n(\"Copy\"), this, SLOT( copy() ) );\n d->view->addAction( copy );\n\n KAction* separator = new KAction( d->view );\n separator->setSeparator( true );\n d->view->addAction( separator );\n\n QAction* clearSelection = toolBar->addAction(KIcon(\"edit-clear-list\"), i18n(\"Clear Selection\"), this, SLOT( clearSelection() ) );\n d->view->addAction( clearSelection );\n\n layout->addWidget(toolBar);\n layout->addWidget(d->view);\n setWidget(widget);\n}\n\nvoid MessageDock::showDebug( const QString& debugText )\n{\n QListWidgetItem* item = new QListWidgetItem( debugText, d->view );\n d->view->addItem( item );\n d->view->scrollToItem( item );\n}\n\nMessageDock::~MessageDock()\n{\n delete d;\n}\n\nvoid MessageDock::copy()\n{\n int itemsCount = d->view->count();\n QStringList messages;\n for (int i = 0; i < itemsCount; ++i)\n messages << d->view->item(i)->text();\n\n QApplication::clipboard()->setText(messages.join(\"\\n\"));\n}\n\nvoid MessageDock::selectAll()\n{\n int itemsCount = d->view->count();\n for (int i = 0; i < itemsCount; ++i)\n d->view->item(i)->setSelected(true);\n}\n\nvoid MessageDock::clearSelection()\n{\n int itemsCount = d->view->count();\n for (int i = 0; i < itemsCount; ++i)\n d->view->item(i)->setSelected(false);\n}\n<commit_msg>Creator: Make a better and faster implementation for the copy action<commit_after>\/******************************************************************************\n * This file is part of the Gluon Development Platform\n * Copyright (c) 2010 Arjen Hiemstra <ahiemstra@heimr.nl>\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n *\/\n\n#include \"messagedock.h\"\n\n#include <core\/gluon_global.h>\n#include <engine\/game.h>\n\n#include <KDE\/KLocalizedString>\n#include <KDE\/KToolBar>\n#include <KDE\/KAction>\n\n\/\/ Yup, this should be a view... but for now...\n#include <QtGui\/QListWidget>\n#include <QtGui\/QVBoxLayout>\n#include <QtGui\/QApplication>\n#include <QtGui\/QClipboard>\n\nusing namespace GluonCreator;\n\nclass MessageDock::MessageDockPrivate\n{\n public:\n MessageDockPrivate()\n {\n view = 0;\n }\n QListWidget* view;\n};\n\nMessageDock::MessageDock( const QString& title, QWidget* parent, Qt::WindowFlags flags )\n : QDockWidget( title, parent, flags ),\n d( new MessageDockPrivate )\n{\n setObjectName( \"MessageDock\" );\n\n d->view = new QListWidget( this );\n d->view->addItem( new QListWidgetItem( i18n( \"Welcome to Gluon Creator %1\" ).arg( GluonCore::Global::versionString() ), d->view ) );\n\n connect( GluonEngine::Game::instance(), SIGNAL( showDebug( const QString& ) ), SLOT( showDebug( const QString& ) ) );\n\n QWidget* widget = new QWidget( this );\n QVBoxLayout* layout = new QVBoxLayout();\n layout->setContentsMargins( 0, 0, 0, 0 );\n layout->setSpacing( 0 );\n widget->setLayout( layout );\n\n KToolBar* toolBar = new KToolBar(this);\n toolBar->setIconDimensions(16);\n\n QAction* selectAll = toolBar->addAction(KIcon(\"edit-select-all\"), i18n(\"Select All\"), this, SLOT( selectAll() ) );\n d->view->addAction( selectAll );\n\n QAction* copy = toolBar->addAction(KIcon(\"edit-copy\"), i18n(\"Copy\"), this, SLOT( copy() ) );\n d->view->addAction( copy );\n\n KAction* separator = new KAction( d->view );\n separator->setSeparator( true );\n d->view->addAction( separator );\n\n QAction* clearSelection = toolBar->addAction(KIcon(\"edit-clear-list\"), i18n(\"Clear Selection\"), this, SLOT( clearSelection() ) );\n d->view->addAction( clearSelection );\n\n layout->addWidget(toolBar);\n layout->addWidget(d->view);\n setWidget(widget);\n}\n\nvoid MessageDock::showDebug( const QString& debugText )\n{\n QListWidgetItem* item = new QListWidgetItem( debugText, d->view );\n d->view->addItem( item );\n d->view->scrollToItem( item );\n}\n\nMessageDock::~MessageDock()\n{\n delete d;\n}\n\nvoid MessageDock::copy()\n{\n QStringList messages;\n foreach( QListWidgetItem* item, d->view->selectedItems())\n messages << item->text();\n\n QApplication::clipboard()->setText(messages.join(\"\\n\"));\n}\n\nvoid MessageDock::selectAll()\n{\n int itemsCount = d->view->count();\n for (int i = 0; i < itemsCount; ++i)\n d->view->item(i)->setSelected(true);\n}\n\nvoid MessageDock::clearSelection()\n{\n int itemsCount = d->view->count();\n for (int i = 0; i < itemsCount; ++i)\n d->view->item(i)->setSelected(false);\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (C) 2010, 2011 and 2012 Marcin Arkadiusz Skrobiranda.\n\/\/ All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions\n\/\/ are met:\n\/\/ 1. Redistributions of source code must retain the above copyright\n\/\/ notice, this list of conditions and the following disclaimer.\n\/\/ 2. Redistributions in binary form must reproduce the above copyright\n\/\/ notice, this list of conditions and the following disclaimer in the\n\/\/ documentation and\/or other materials provided with the distribution.\n\/\/ 3. Neither the name of the project nor the names of its contributors\n\/\/ may be used to endorse or promote products derived from this software\n\/\/ without specific prior written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS \"AS IS\" AND\n\/\/ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\/\/ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\/\/ ARE DISCLAIMED. IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE\n\/\/ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n\/\/ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n\/\/ OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n\/\/ HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n\/\/ LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n\/\/ OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n\/\/ SUCH DAMAGE.\n\n#include <Game\/GameServer\/Common\/Constants.hpp>\n#include <Game\/GameServer\/Land\/Executors\/ExecutorDeleteLand.hpp>\n#include <Language\/Interface\/ReplyBuilder.hpp>\n#include <boost\/make_shared.hpp>\n#include <log4cpp\/Category.hh>\n\nusing namespace GameServer::Persistence;\nusing namespace boost;\nusing namespace log4cpp;\nusing namespace std;\n\nnamespace Game\n{\n\nExecutorDeleteLand::ExecutorDeleteLand(\n Server::IContextShrPtr const a_context\n)\n : Executor(a_context)\n{\n}\n\nvoid ExecutorDeleteLand::logExecutorStart() const\n{\n\/\/ TODO: Replace with Poco::Logger. Category::getInstance(\"Category\").infoStream() << \"Starting the ExecutorDeleteLand.\";\n}\n\nbool ExecutorDeleteLand::getParameters(\n Language::ICommand::Handle a_request\n)\n{\n m_login = a_request->getLogin();\n m_password = a_request->getPassword();\n m_land_name = a_request->getParam(\"land_name\");\n\n return true;\n}\n\nbool ExecutorDeleteLand::processParameters()\n{\n return true;\n}\n\nbool ExecutorDeleteLand::authorize(\n IPersistenceShrPtr a_persistence\n) const\n{\n GameServer::Authorization::IAuthorizeUserToLandOperatorShrPtr authorize_operator =\n m_operator_abstract_factory->createAuthorizeUserToLandOperator();\n\n \/\/ The transaction lifetime.\n {\n IConnectionShrPtr connection = a_persistence->getConnection();\n ITransactionShrPtr transaction = a_persistence->getTransaction(connection);\n\n GameServer::Authorization::AuthorizeUserToLandOperatorExitCode const exit_code =\n authorize_operator->authorizeUserToLand(transaction, m_user->getLogin(), m_land_name);\n\n if (exit_code.ok())\n {\n transaction->commit();\n }\n\n return exit_code.m_authorized;\n }\n}\n\nbool ExecutorDeleteLand::epochIsActive(\n IPersistenceShrPtr a_persistence\n) const\n{\n GameServer::Epoch::IGetEpochByLandNameOperatorShrPtr epoch_operator =\n m_operator_abstract_factory->createGetEpochByLandNameOperator();\n\n \/\/ The transaction lifetime.\n {\n IConnectionShrPtr connection = a_persistence->getConnection();\n ITransactionShrPtr transaction = a_persistence->getTransaction(connection);\n\n GameServer::Epoch::GetEpochByLandNameOperatorExitCode const exit_code =\n epoch_operator->getEpochByLandName(transaction, m_land_name);\n\n if (exit_code.ok())\n {\n transaction->commit();\n }\n\n return exit_code.m_epoch ? exit_code.m_epoch->getActive() : false;\n }\n}\n\nbool ExecutorDeleteLand::verifyWorldConfiguration(\n IPersistenceShrPtr a_persistence\n) const\n{\n return true;\n}\n\nLanguage::ICommand::Handle ExecutorDeleteLand::perform(\n IPersistenceShrPtr a_persistence\n) const\n{\n GameServer::Land::IDeleteLandOperatorShrPtr land_operator = m_operator_abstract_factory->createDeleteLandOperator();\n\n \/\/ The transaction lifetime.\n {\n IConnectionShrPtr connection = a_persistence->getConnection();\n ITransactionShrPtr transaction = a_persistence->getTransaction(connection);\n\n GameServer::Land::DeleteLandOperatorExitCode const exit_code =\n land_operator->deleteLand(transaction, m_land_name);\n\n if (exit_code.ok())\n {\n transaction->commit();\n }\n\n return produceReply(exit_code);\n }\n}\n\nLanguage::ICommand::Handle ExecutorDeleteLand::getBasicReply(\n unsigned int const a_status\n) const\n{\n \/\/ FIXME: Remove this method!\n BOOST_ASSERT_MSG(false, \"Should never be called!\");\n}\n\nLanguage::ICommand::Handle ExecutorDeleteLand::produceReply(\n GameServer::Land::DeleteLandOperatorExitCode const & a_exit_code\n) const\n{\n Language::ReplyBuilder reply_builder;\n\n switch (a_exit_code.m_exit_code)\n {\n case GameServer::Land::DELETE_LAND_OPERATOR_EXIT_CODE_LAND_DOES_NOT_EXIST:\n return reply_builder.buildDeleteLandReply(REPLY_STATUS_OK, DELETE_LAND_LAND_DOES_NOT_EXIST);\n\n case GameServer::Land::DELETE_LAND_OPERATOR_EXIT_CODE_LAND_HAS_BEEN_DELETED:\n return reply_builder.buildDeleteLandReply(REPLY_STATUS_OK, DELETE_LAND_LAND_HAS_BEEN_DELETED);\n\n case GameServer::Land::DELETE_LAND_OPERATOR_EXIT_CODE_LAND_HAS_NOT_BEEN_DELETED:\n return reply_builder.buildDeleteLandReply(REPLY_STATUS_OK, DELETE_LAND_LAND_HAS_NOT_BEEN_DELETED);\n\n case GameServer::Land::DELETE_LAND_OPERATOR_EXIT_CODE_UNEXPECTED_ERROR:\n return reply_builder.buildDeleteLandReply(REPLY_STATUS_OK, DELETE_LAND_UNEXPECTED_ERROR);\n\n default:\n return reply_builder.buildDeleteLandReply(REPLY_STATUS_OK,\n METAMESSAGE_EVEN_MORE_UNEXPECTED_ERROR_UNKNOWN_EXIT_CODE);\n }\n}\n\n} \/\/ namespace Game\n<commit_msg>The getBasicReply() method added.<commit_after>\/\/ Copyright (C) 2010, 2011 and 2012 Marcin Arkadiusz Skrobiranda.\n\/\/ All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions\n\/\/ are met:\n\/\/ 1. Redistributions of source code must retain the above copyright\n\/\/ notice, this list of conditions and the following disclaimer.\n\/\/ 2. Redistributions in binary form must reproduce the above copyright\n\/\/ notice, this list of conditions and the following disclaimer in the\n\/\/ documentation and\/or other materials provided with the distribution.\n\/\/ 3. Neither the name of the project nor the names of its contributors\n\/\/ may be used to endorse or promote products derived from this software\n\/\/ without specific prior written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS \"AS IS\" AND\n\/\/ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\/\/ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\/\/ ARE DISCLAIMED. IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE\n\/\/ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n\/\/ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n\/\/ OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n\/\/ HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n\/\/ LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n\/\/ OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n\/\/ SUCH DAMAGE.\n\n#include <Game\/GameServer\/Common\/Constants.hpp>\n#include <Game\/GameServer\/Land\/Executors\/ExecutorDeleteLand.hpp>\n#include <Language\/Interface\/ReplyBuilder.hpp>\n#include <boost\/make_shared.hpp>\n#include <log4cpp\/Category.hh>\n\nusing namespace GameServer::Persistence;\nusing namespace boost;\nusing namespace log4cpp;\nusing namespace std;\n\nnamespace Game\n{\n\nExecutorDeleteLand::ExecutorDeleteLand(\n Server::IContextShrPtr const a_context\n)\n : Executor(a_context)\n{\n}\n\nvoid ExecutorDeleteLand::logExecutorStart() const\n{\n\/\/ TODO: Replace with Poco::Logger. Category::getInstance(\"Category\").infoStream() << \"Starting the ExecutorDeleteLand.\";\n}\n\nbool ExecutorDeleteLand::getParameters(\n Language::ICommand::Handle a_request\n)\n{\n m_login = a_request->getLogin();\n m_password = a_request->getPassword();\n m_land_name = a_request->getParam(\"land_name\");\n\n return true;\n}\n\nbool ExecutorDeleteLand::processParameters()\n{\n return true;\n}\n\nbool ExecutorDeleteLand::authorize(\n IPersistenceShrPtr a_persistence\n) const\n{\n GameServer::Authorization::IAuthorizeUserToLandOperatorShrPtr authorize_operator =\n m_operator_abstract_factory->createAuthorizeUserToLandOperator();\n\n \/\/ The transaction lifetime.\n {\n IConnectionShrPtr connection = a_persistence->getConnection();\n ITransactionShrPtr transaction = a_persistence->getTransaction(connection);\n\n GameServer::Authorization::AuthorizeUserToLandOperatorExitCode const exit_code =\n authorize_operator->authorizeUserToLand(transaction, m_user->getLogin(), m_land_name);\n\n if (exit_code.ok())\n {\n transaction->commit();\n }\n\n return exit_code.m_authorized;\n }\n}\n\nbool ExecutorDeleteLand::epochIsActive(\n IPersistenceShrPtr a_persistence\n) const\n{\n GameServer::Epoch::IGetEpochByLandNameOperatorShrPtr epoch_operator =\n m_operator_abstract_factory->createGetEpochByLandNameOperator();\n\n \/\/ The transaction lifetime.\n {\n IConnectionShrPtr connection = a_persistence->getConnection();\n ITransactionShrPtr transaction = a_persistence->getTransaction(connection);\n\n GameServer::Epoch::GetEpochByLandNameOperatorExitCode const exit_code =\n epoch_operator->getEpochByLandName(transaction, m_land_name);\n\n if (exit_code.ok())\n {\n transaction->commit();\n }\n\n return exit_code.m_epoch ? exit_code.m_epoch->getActive() : false;\n }\n}\n\nbool ExecutorDeleteLand::verifyWorldConfiguration(\n IPersistenceShrPtr a_persistence\n) const\n{\n return true;\n}\n\nLanguage::ICommand::Handle ExecutorDeleteLand::perform(\n IPersistenceShrPtr a_persistence\n) const\n{\n GameServer::Land::IDeleteLandOperatorShrPtr land_operator = m_operator_abstract_factory->createDeleteLandOperator();\n\n \/\/ The transaction lifetime.\n {\n IConnectionShrPtr connection = a_persistence->getConnection();\n ITransactionShrPtr transaction = a_persistence->getTransaction(connection);\n\n GameServer::Land::DeleteLandOperatorExitCode const exit_code =\n land_operator->deleteLand(transaction, m_land_name);\n\n if (exit_code.ok())\n {\n transaction->commit();\n }\n\n return produceReply(exit_code);\n }\n}\n\nLanguage::ICommand::Handle ExecutorDeleteLand::getBasicReply(\n unsigned int const a_status\n) const\n{\n Language::ReplyBuilder reply_builder;\n\n return reply_builder.buildDeleteLandReply(a_status);\n}\n\nLanguage::ICommand::Handle ExecutorDeleteLand::produceReply(\n GameServer::Land::DeleteLandOperatorExitCode const & a_exit_code\n) const\n{\n Language::ReplyBuilder reply_builder;\n\n switch (a_exit_code.m_exit_code)\n {\n case GameServer::Land::DELETE_LAND_OPERATOR_EXIT_CODE_LAND_DOES_NOT_EXIST:\n return reply_builder.buildDeleteLandReply(REPLY_STATUS_OK, DELETE_LAND_LAND_DOES_NOT_EXIST);\n\n case GameServer::Land::DELETE_LAND_OPERATOR_EXIT_CODE_LAND_HAS_BEEN_DELETED:\n return reply_builder.buildDeleteLandReply(REPLY_STATUS_OK, DELETE_LAND_LAND_HAS_BEEN_DELETED);\n\n case GameServer::Land::DELETE_LAND_OPERATOR_EXIT_CODE_LAND_HAS_NOT_BEEN_DELETED:\n return reply_builder.buildDeleteLandReply(REPLY_STATUS_OK, DELETE_LAND_LAND_HAS_NOT_BEEN_DELETED);\n\n case GameServer::Land::DELETE_LAND_OPERATOR_EXIT_CODE_UNEXPECTED_ERROR:\n return reply_builder.buildDeleteLandReply(REPLY_STATUS_OK, DELETE_LAND_UNEXPECTED_ERROR);\n\n default:\n return reply_builder.buildDeleteLandReply(REPLY_STATUS_OK,\n METAMESSAGE_EVEN_MORE_UNEXPECTED_ERROR_UNKNOWN_EXIT_CODE);\n }\n}\n\n} \/\/ namespace Game\n<|endoftext|>"} {"text":"<commit_before>#include <Components\/SpotLight.hh>\n#include <Core\/AScene.hh>\n#include <Utils\/MathematicTools.hh>\n#include <Threads\/PrepareRenderThread.hpp>\n#include <Threads\/ThreadManager.hpp>\n#include <glm\/glm.hpp>\n#include <AssetManagement\/AssetManager.hh>\n\n#ifdef EDITOR_ENABLED\n#\tinclude <imgui\\imgui.h>\n#\tinclude <glm\/gtc\/type_ptr.hpp>\n#endif\n\nnamespace AGE\n{\n\tSpotLightData::SpotLightData(glm::vec3 const &color, glm::vec3 const &range, float exponent, float cutOff, std::shared_ptr<ITexture> const &map)\n\t\t: color(color),\n\t\trange(range),\n\t\texponent(exponent),\n\t\tcutOff(cutOff),\n\t\tmap(map)\n\t{\n\n\t}\n\n\tSpotLightComponent::SpotLightComponent(SpotLightComponent const &o)\n\t\t: _key(o._key)\n\t\t, _data(o._data)\n\t{\n\t\tpostUnserialization();\n\t}\n\n\tvoid SpotLightComponent::_copyFrom(const ComponentBase *model)\n\t{\n\t\tauto o = static_cast<const SpotLightComponent*>(model);\n\t\t_data = o->_data;\n\t\tpostUnserialization();\n\t}\n\n\tvoid SpotLightComponent::reset()\n\t{\n\t\tif (!_key.invalid())\n\t\t{\n\t\t\tentity.getLink().unregisterOctreeObject(_key);\n\t\t}\n\t\t_key = AGE::PrepareKey();\n\t\t_data = SpotLightData();\n\t}\n\n\tvoid SpotLightComponent::init()\n\t{\n\t\t_key = AGE::GetPrepareThread()->addSpotLight();\n\t\tentity.getLink().registerOctreeObject(_key);\n\t\t_data.map = entity.getScene()->getInstance<AssetsManager>()->getSpotLightTexture();\n\t\tassert(!_key.invalid());\n\t\tset(_data);\n\t}\n\n\tSpotLightComponent &SpotLightComponent::set(SpotLightData const &data)\n\t{\n\t\t_data = data;\n\t\tAGE::GetPrepareThread()->setSpotLight(_data, _key);\n\t\treturn (*this);\n\t}\n\n\tvoid SpotLightComponent::postUnserialization()\n\t{\n\t\tinit();\n\t\tset(_data);\n\t}\n\n#ifdef EDITOR_ENABLED\n\tvoid SpotLightComponent::editorCreate()\n\t{}\n\n\tvoid SpotLightComponent::editorDelete()\n\t{\n\t}\n\n\tbool SpotLightComponent::editorUpdate()\n\t{\n\t\tbool modified = false;\n\t\tif (ImGui::ColorEdit3(\"Color\", glm::value_ptr(_data.color)))\n\t\t{\n\t\t\tset(_data);\n\t\t\tmodified = true;\n\t\t}\n\t\tif (ImGui::SliderFloat3(\"Range\", glm::value_ptr(_data.range), 0.0f, 1.0f))\n\t\t{\n\t\t\tset(_data);\n\t\t\tmodified = true;\n\t\t}\n\t\tif (ImGui::InputFloat(\"Exponent\", &_data.exponent))\n\t\t{\n\t\t\tset(_data);\n\t\t\tmodified = true;\n\t\t}\n\t\tif (ImGui::InputFloat(\"cut off\", &_data.cutOff))\n\t\t{\n\t\t\tset(_data);\n\t\t\tmodified = true;\n\t\t}\n\t\treturn modified;\n\t}\n#endif\n}<commit_msg>Forgot file<commit_after>#include <Components\/SpotLight.hh>\n#include <Core\/AScene.hh>\n#include <Utils\/MathematicTools.hh>\n#include <Threads\/PrepareRenderThread.hpp>\n#include <Threads\/ThreadManager.hpp>\n#include <glm\/glm.hpp>\n#include <AssetManagement\/AssetManager.hh>\n\n#ifdef EDITOR_ENABLED\n#\tinclude <imgui\\imgui.h>\n#\tinclude <glm\/gtc\/type_ptr.hpp>\n#endif\n\nnamespace AGE\n{\n\tSpotLightData::SpotLightData(glm::vec3 const &color, glm::vec3 const &range, float exponent, float cutOff, std::shared_ptr<ITexture> const &map)\n\t\t: color(color),\n\t\trange(range),\n\t\texponent(exponent),\n\t\tcutOff(cutOff),\n\t\tmap(map)\n\t{\n\n\t}\n\n\tSpotLightComponent::SpotLightComponent(SpotLightComponent const &o)\n\t\t: _key(o._key)\n\t\t, _data(o._data)\n\t{\n\t\tpostUnserialization();\n\t}\n\n\tvoid SpotLightComponent::_copyFrom(const ComponentBase *model)\n\t{\n\t\tauto o = static_cast<const SpotLightComponent*>(model);\n\t\t_data = o->_data;\n\t\tpostUnserialization();\n\t}\n\n\tvoid SpotLightComponent::reset()\n\t{\n\t\tif (!_key.invalid())\n\t\t{\n\t\t\tentity.getLink().unregisterOctreeObject(_key);\n\t\t}\n\t\t_key = AGE::PrepareKey();\n\t\t_data = SpotLightData();\n\t}\n\n\tvoid SpotLightComponent::init()\n\t{\n\t\t_key = AGE::GetPrepareThread()->addSpotLight();\n\t\tentity.getLink().registerOctreeObject(_key);\n\t\t_data.map = entity.getScene()->getInstance<AssetsManager>()->getSpotLightTexture();\n\t\tassert(!_key.invalid());\n\t\tset(_data);\n\t}\n\n\tvoid SpotLightComponent::set(SpotLightData const &data)\n\t{\n\t\t_data = data;\n\t\tAGE::GetPrepareThread()->setSpotLight(_data, _key);\n\t}\n\n\tvoid SpotLightComponent::postUnserialization()\n\t{\n\t\tinit();\n\t}\n\n#ifdef EDITOR_ENABLED\n\tvoid SpotLightComponent::editorCreate()\n\t{}\n\n\tvoid SpotLightComponent::editorDelete()\n\t{\n\t}\n\n\tbool SpotLightComponent::editorUpdate()\n\t{\n\t\tbool modified = false;\n\t\tif (ImGui::ColorEdit3(\"Color\", glm::value_ptr(_data.color)))\n\t\t{\n\t\t\tset(_data);\n\t\t\tmodified = true;\n\t\t}\n\t\tif (ImGui::SliderFloat3(\"Range\", glm::value_ptr(_data.range), 0.0f, 1.0f))\n\t\t{\n\t\t\tset(_data);\n\t\t\tmodified = true;\n\t\t}\n\t\tif (ImGui::InputFloat(\"Exponent\", &_data.exponent))\n\t\t{\n\t\t\tset(_data);\n\t\t\tmodified = true;\n\t\t}\n\t\tif (ImGui::InputFloat(\"cut off\", &_data.cutOff))\n\t\t{\n\t\t\tset(_data);\n\t\t\tmodified = true;\n\t\t}\n\t\treturn modified;\n\t}\n#endif\n}<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: countermain.cxx,v $\n *\n * $Revision: 1.8 $\n *\n * last change: $Author: kz $ $Date: 2006-11-06 15:07:28 $\n *\n * The Contents of this file are made available subject to the terms of\n * the BSD license.\n *\n * Copyright (c) 2003 by Sun Microsystems, Inc.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution.\n * 3. Neither the name of Sun Microsystems, Inc. nor the names of its\n * contributors may be used to endorse or promote products derived\n * from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS\n * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR\n * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE\n * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n *************************************************************************\/\n\n\/*************************************************************************\n *************************************************************************\n *\n * simple client application registering and using the counter component.\n *\n *************************************************************************\n *************************************************************************\/\n\n#include <stdio.h>\n\n#include <rtl\/ustring.hxx>\n\n#include <osl\/diagnose.h>\n\n#include <cppuhelper\/bootstrap.hxx>\n\n\/\/ generated c++ interfaces\n#include <com\/sun\/star\/lang\/XComponent.hpp>\n#include <com\/sun\/star\/registry\/XImplementationRegistration.hpp>\n#include <foo\/XCountable.hpp>\n\n\nusing namespace foo;\nusing namespace cppu;\nusing namespace com::sun::star::uno;\nusing namespace com::sun::star::lang;\nusing namespace com::sun::star::registry;\n\nusing namespace ::rtl;\n\n\n\/\/=======================================================================\nint SAL_CALL main(int argc, char **argv)\n{\n Reference< XSimpleRegistry > xReg = createSimpleRegistry();\n OSL_ENSURE( xReg.is(), \"### cannot get service instance of \\\"com.sun.star.regiystry.SimpleRegistry\\\"!\" );\n\n xReg->open(OUString::createFromAscii(\"counter.uno.rdb\"), sal_False, sal_False);\n OSL_ENSURE( xReg->isValid(), \"### cannot open test registry \\\"counter.uno.rdb\\\"!\" );\n\n Reference< XComponentContext > xContext = bootstrap_InitialComponentContext(xReg);\n OSL_ENSURE( xContext.is(), \"### cannot creage intial component context!\" );\n\n Reference< XMultiComponentFactory > xMgr = xContext->getServiceManager();\n OSL_ENSURE( xMgr.is(), \"### cannot get initial service manager!\" );\n\n \/\/ register my counter component\n Reference< XImplementationRegistration > xImplReg(\n xMgr->createInstanceWithContext(OUString::createFromAscii(\"com.sun.star.registry.ImplementationRegistration\"), xContext), UNO_QUERY);\n OSL_ENSURE( xImplReg.is(), \"### cannot get service instance of \\\"com.sun.star.registry.ImplementationRegistration\\\"!\" );\n\n if (xImplReg.is())\n {\n xImplReg->registerImplementation(\n OUString::createFromAscii(\"com.sun.star.loader.SharedLibrary\"), \/\/ loader for component\n#ifdef UNX\n#ifdef MACOSX\n OUString::createFromAscii(\"counter.uno.dylib\"), \/\/ component location\n#else\n OUString::createFromAscii(\"counter.uno.so\"), \/\/ component location\n#endif\n#else\n OUString::createFromAscii(\"counter.uno.dll\"), \/\/ component location\n#endif\n Reference< XSimpleRegistry >() \/\/ registry omitted,\n \/\/ defaulting to service manager registry used\n );\n\n \/\/ get a counter instance\n Reference< XInterface > xx ;\n xx = xMgr->createInstanceWithContext(OUString::createFromAscii(\"foo.Counter\"), xContext);\n Reference< XCountable > xCount( xx, UNO_QUERY );\n OSL_ENSURE( xCount.is(), \"### cannot get service instance of \\\"foo.Counter\\\"!\" );\n\n if (xCount.is())\n {\n xCount->setCount( 42 );\n fprintf( stdout , \"%d,\" , xCount->getCount() );\n fprintf( stdout , \"%d,\" , xCount->increment() );\n fprintf( stdout , \"%d\\n\" , xCount->decrement() );\n }\n }\n\n Reference< XComponent >::query( xContext )->dispose();\n return 0;\n}\n<commit_msg>INTEGRATION: CWS jsc20 (1.8.84); FILE MERGED 2008\/01\/03 15:23:32 jsc 1.8.84.1: #i84966# add missing include<commit_after>\/*************************************************************************\n *\n * $RCSfile: countermain.cxx,v $\n *\n * $Revision: 1.9 $\n *\n * last change: $Author: vg $ $Date: 2008-01-28 16:30:31 $\n *\n * The Contents of this file are made available subject to the terms of\n * the BSD license.\n *\n * Copyright (c) 2003 by Sun Microsystems, Inc.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution.\n * 3. Neither the name of Sun Microsystems, Inc. nor the names of its\n * contributors may be used to endorse or promote products derived\n * from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS\n * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR\n * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE\n * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n *************************************************************************\/\n\n\/*************************************************************************\n *************************************************************************\n *\n * simple client application registering and using the counter component.\n *\n *************************************************************************\n *************************************************************************\/\n\n#include <stdio.h>\n\n#include <rtl\/ustring.hxx>\n\n#include <osl\/diagnose.h>\n\n#include <cppuhelper\/bootstrap.hxx>\n\n\/\/ generated c++ interfaces\n#include <com\/sun\/star\/lang\/XComponent.hpp>\n#include <com\/sun\/star\/lang\/XMultiComponentFactory.hpp>\n#include <com\/sun\/star\/registry\/XImplementationRegistration.hpp>\n#include <foo\/XCountable.hpp>\n\n\nusing namespace foo;\nusing namespace cppu;\nusing namespace com::sun::star::uno;\nusing namespace com::sun::star::lang;\nusing namespace com::sun::star::registry;\n\nusing namespace ::rtl;\n\n\n\/\/=======================================================================\nint SAL_CALL main(int argc, char **argv)\n{\n Reference< XSimpleRegistry > xReg = createSimpleRegistry();\n OSL_ENSURE( xReg.is(), \"### cannot get service instance of \\\"com.sun.star.regiystry.SimpleRegistry\\\"!\" );\n\n xReg->open(OUString::createFromAscii(\"counter.uno.rdb\"), sal_False, sal_False);\n OSL_ENSURE( xReg->isValid(), \"### cannot open test registry \\\"counter.uno.rdb\\\"!\" );\n\n Reference< XComponentContext > xContext = bootstrap_InitialComponentContext(xReg);\n OSL_ENSURE( xContext.is(), \"### cannot creage intial component context!\" );\n\n Reference< XMultiComponentFactory > xMgr = xContext->getServiceManager();\n OSL_ENSURE( xMgr.is(), \"### cannot get initial service manager!\" );\n\n \/\/ register my counter component\n Reference< XImplementationRegistration > xImplReg(\n xMgr->createInstanceWithContext(OUString::createFromAscii(\"com.sun.star.registry.ImplementationRegistration\"), xContext), UNO_QUERY);\n OSL_ENSURE( xImplReg.is(), \"### cannot get service instance of \\\"com.sun.star.registry.ImplementationRegistration\\\"!\" );\n\n if (xImplReg.is())\n {\n xImplReg->registerImplementation(\n OUString::createFromAscii(\"com.sun.star.loader.SharedLibrary\"), \/\/ loader for component\n#ifdef UNX\n#ifdef MACOSX\n OUString::createFromAscii(\"counter.uno.dylib\"), \/\/ component location\n#else\n OUString::createFromAscii(\"counter.uno.so\"), \/\/ component location\n#endif\n#else\n OUString::createFromAscii(\"counter.uno.dll\"), \/\/ component location\n#endif\n Reference< XSimpleRegistry >() \/\/ registry omitted,\n \/\/ defaulting to service manager registry used\n );\n\n \/\/ get a counter instance\n Reference< XInterface > xx ;\n xx = xMgr->createInstanceWithContext(OUString::createFromAscii(\"foo.Counter\"), xContext);\n Reference< XCountable > xCount( xx, UNO_QUERY );\n OSL_ENSURE( xCount.is(), \"### cannot get service instance of \\\"foo.Counter\\\"!\" );\n\n if (xCount.is())\n {\n xCount->setCount( 42 );\n fprintf( stdout , \"%d,\" , xCount->getCount() );\n fprintf( stdout , \"%d,\" , xCount->increment() );\n fprintf( stdout , \"%d\\n\" , xCount->decrement() );\n }\n }\n\n Reference< XComponent >::query( xContext )->dispose();\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"MemoryAllocator.h\"\n\n#include <iostream>\n\nconst int SIZE_BLOCK = 22;\n\nvoid roundUp(size_t&);\n\nMemoryAllocator::MemoryAllocator() {\n\tthis->pBlock = new (std::nothrow) value_type[SIZE_BLOCK];\n\n\t*pBlock = SIZE_BLOCK * 8 - 8 - 8; \/\/ header\n\t*(pBlock + SIZE_BLOCK - 1) = SIZE_BLOCK * 8 - 8 - 8; \/\/ footer\n\n\tpStartBlock = pBlock;\n\tpEndBlock = (pBlock + SIZE_BLOCK - 1);\n\n\t\/\/for (int i = 0; i < 50; i++) {\n\t\/\/\tstd::cout << \"pBlock[\" << i << \"] = \" << pBlock[i] << std::endl;\n\t\/\/}\n}\n\nMemoryAllocator::~MemoryAllocator() {\n\tfor (int i = 0; i < SIZE_BLOCK; i++) {\n\t\tstd::cout << \"pBlock[\" << i << \"] = \" << pBlock[i] << std::endl;\n\t}\n\n\tdelete this->pBlock;\n}\n\nvalue_type* MemoryAllocator::MyMalloc(size_t bytes) {\n\tvalue_type* startPointerBlock = this->pBlock;\n\n\troundUp(bytes);\n\t\n\tif (bytes > SIZE_BLOCK * 8 - 8 - 8) {\n\t\tstd::cerr << \"ERROR! There is not enough memory.\" << std::endl;\n\t\treturn NULL;\n\t}\n\n\n\tif (*startPointerBlock % 8 == 0) {\n\t\tvalue_type* pUserBlock = startPointerBlock + 1;\n\t\t\n\t\tsize_t newHeaderBytes = bytes;\n\t\tnewHeaderBytes |= 1; \/\/ set the bit to 1\n\t\tsize_t oldHeaderBytes = *startPointerBlock;\n\t\t*startPointerBlock = newHeaderBytes;\n\t\tstartPointerBlock += bytes \/ 8 + 1;\n\t\t*startPointerBlock = bytes;\n\t\tstartPointerBlock += 1;\n\t\t*startPointerBlock = oldHeaderBytes - bytes - 8 - 8;\n\t\tstartPointerBlock += *startPointerBlock \/ 8 + 1;\n\t\t*startPointerBlock = oldHeaderBytes - bytes - 8 - 8;\n\t\t\n\t\treturn pUserBlock;\n\t}\n\telse {\n\t\twhile (*startPointerBlock % 8 != 0 && startPointerBlock >= pStartBlock && startPointerBlock <= pEndBlock) {\n\t\t\tstartPointerBlock += *startPointerBlock \/ 8 + 2;\n\t\t}\n\t\tbool isLastAvailableBlock = false;\n\t\tif (*startPointerBlock \/ 8 + 2) {\n\t\t\tisLastAvailableBlock = true;\n\t\t}\n\n\t\tif ((bytes + 8 + 8 > *startPointerBlock && ! isLastAvailableBlock) || *startPointerBlock % 8 != 0 || *startPointerBlock == 0) {\n\t\t\tstd::cerr << \"ERROR! There is not enough memory.\" << std::endl;\n\t\t\treturn NULL;\n\t\t}\n\n\t\tvalue_type* pUserBlock = startPointerBlock + 1;\n\t\t\t\n\t\tif (isLastAvailableBlock && bytes == *startPointerBlock) {\n\t\t\tsize_t newHeaderBytes = bytes;\n\t\t\tnewHeaderBytes |= 1; \/\/ set the bit to 1\n\t\t\tsize_t oldHeaderBytes = *startPointerBlock;\n\t\t\t*startPointerBlock = newHeaderBytes;\n\t\t\tstartPointerBlock += bytes \/ 8 + 1;\n\t\t\t*startPointerBlock = bytes;\n\t\t}\n\t\telse {\n\t\t\tif (isLastAvailableBlock && bytes + 8 + 8 > *startPointerBlock) {\n\t\t\t\tstd::cerr << \"ERROR! There is not enough memory.\" << std::endl;\n\t\t\t\treturn NULL;\n\t\t\t}\n\t\t\tsize_t newHeaderBytes = bytes;\n\t\t\tnewHeaderBytes |= 1; \/\/ set the bit to 1\n\t\t\tsize_t oldHeaderBytes = *startPointerBlock;\n\t\t\t*startPointerBlock = newHeaderBytes;\n\t\t\tstartPointerBlock += bytes \/ 8 + 1;\n\t\t\t*startPointerBlock = bytes;\n\t\t\tstartPointerBlock += 1;\n\t\t\t*startPointerBlock = oldHeaderBytes - bytes - 8 - 8;\n\t\t\tstartPointerBlock += *startPointerBlock \/ 8 + 1;\n\t\t\t*startPointerBlock = oldHeaderBytes - bytes - 8 - 8;\n\t\t}\n\t\t\n\n\t\treturn pUserBlock;\n\n\t}\n\n\treturn NULL;\n}\n\nvoid MemoryAllocator::MyFree(value_type* pBlock) {\n\tif (pBlock == NULL) {\n\t\tstd::cerr << \"ERROR! Wrong address.\" << std::endl;\n\t\treturn;\n\t}\n\n\tvalue_type* currentHeader = pBlock - 1; \n\t\/\/std::cout << \"currentHeader: \" << *currentHeader << std::endl;\n\t\n\tvalue_type* leftHeader = currentHeader - (*(currentHeader - 1) \/ 8) - 2; \n\t\/\/std::cout << \"leftHeader: \" << *leftHeader << std::endl;\n\t\n\tvalue_type* rightHeader = currentHeader + *currentHeader \/ 8 + 2; \n\t\/\/std::cout << \"rightHeader: \" << *rightHeader << std::endl;\n\n\tif (currentHeader < pStartBlock || currentHeader > pEndBlock) {\n\t\tstd::cerr << \"ERROR! Wrong address.\" << std::endl;\n\t\treturn;\n\t}\n\n\tif (*leftHeader % 8 != 0 && *rightHeader % 8 != 0 && leftHeader >= pStartBlock && rightHeader <= pEndBlock) {\n\t\tstd::cout << \"-----first case\" << std::endl;\n\t\t*currentHeader &= ~1;\n\t}\n\telse if (*leftHeader % 8 == 0 && *rightHeader % 8 == 0 && leftHeader >= pStartBlock && rightHeader <= pEndBlock) {\n\t\tstd::cout << \"-----fourth case\" << std::endl;\n\t\t*currentHeader &= ~1;\n\t\tsize_t newHeaderBytes = *currentHeader + *leftHeader + 8 + 8 + *rightHeader + 8 + 8;\n\t\tcurrentHeader -= 1;\n\t\tcurrentHeader -= (*currentHeader \/ 8 + 1);\n\t\t*currentHeader = newHeaderBytes;\n\t\tcurrentHeader += *currentHeader \/ 8 + 1;\n\t\t*currentHeader = newHeaderBytes;\n\t}\n\telse if (*rightHeader % 8 == 0 && rightHeader <= pEndBlock) {\n\t\tstd::cout << \"-----second case\" << std::endl;\n\t\t*currentHeader &= ~1;\n\t\tsize_t newHeaderBytes = *currentHeader + *rightHeader + 8 + 8;\n\t\t*currentHeader = newHeaderBytes;\n\t\tcurrentHeader += *currentHeader \/ 8 + 1;\n\t\t*currentHeader = newHeaderBytes;\n\n\t}\n\telse if (*leftHeader % 8 == 0 && leftHeader >= pStartBlock) {\n\t\tstd::cout << \"-----third case\" << std::endl;\n\t\t*currentHeader &= ~1;\n\t\tsize_t newHeaderBytes = *currentHeader + *leftHeader + 8 + 8;\n\t\tcurrentHeader -= 1;\n\t\tcurrentHeader -= (*currentHeader \/ 8 + 1);\n\t\t*currentHeader = newHeaderBytes;\n\t\tcurrentHeader += *currentHeader \/ 8 + 1;\n\t\t*currentHeader = newHeaderBytes;\n\t\t\n\t}\n\telse {\n\t\tstd::cout << \"fifth case\" << std::endl;\n\n\t\tif (leftHeader < pStartBlock && *rightHeader % 8 != 0) {\n\t\t\t*currentHeader &= ~1;\n\t\t}\n\t\t\n\t\tif (rightHeader > pEndBlock && *leftHeader % 8 != 0) {\n\t\t\t*currentHeader &= ~1;\n\t\t}\n\t}\n\n}\n\nvoid roundUp(size_t& bytes) {\n\tif (bytes % 8 != 0) {\n\t\tbytes = bytes - (bytes % 8) + 8;\n\t}\n}<commit_msg>Add BLOCK_ALIGNMENT constant.<commit_after>#include \"MemoryAllocator.h\"\n\n#include <iostream>\n\nconst int SIZE_BLOCK = 22;\nconst int BLOCK_ALIGNMENT = 8;\n\nvoid roundUp(size_t&);\n\nMemoryAllocator::MemoryAllocator() {\n\tthis->pBlock = new (std::nothrow) value_type[SIZE_BLOCK];\n\n\t*pBlock = SIZE_BLOCK * BLOCK_ALIGNMENT - BLOCK_ALIGNMENT - BLOCK_ALIGNMENT; \/\/ header\n\t*(pBlock + SIZE_BLOCK - 1) = SIZE_BLOCK * BLOCK_ALIGNMENT - BLOCK_ALIGNMENT - BLOCK_ALIGNMENT; \/\/ footer\n\n\tpStartBlock = pBlock;\n\tpEndBlock = (pBlock + SIZE_BLOCK - 1);\n\n\t\/\/for (int i = 0; i < 50; i++) {\n\t\/\/\tstd::cout << \"pBlock[\" << i << \"] = \" << pBlock[i] << std::endl;\n\t\/\/}\n}\n\nMemoryAllocator::~MemoryAllocator() {\n\tfor (int i = 0; i < SIZE_BLOCK; i++) {\n\t\tstd::cout << \"pBlock[\" << i << \"] = \" << pBlock[i] << std::endl;\n\t}\n\n\tdelete this->pBlock;\n}\n\nvalue_type* MemoryAllocator::MyMalloc(size_t bytes) {\n\tvalue_type* startPointerBlock = this->pBlock;\n\n\troundUp(bytes);\n\t\n\tif (bytes > SIZE_BLOCK * BLOCK_ALIGNMENT - BLOCK_ALIGNMENT - BLOCK_ALIGNMENT) {\n\t\tstd::cerr << \"ERROR! There is not enough memory.\" << std::endl;\n\t\treturn NULL;\n\t}\n\n\n\tif (*startPointerBlock % BLOCK_ALIGNMENT == 0) {\n\t\tvalue_type* pUserBlock = startPointerBlock + 1;\n\t\t\n\t\tsize_t newHeaderBytes = bytes;\n\t\tnewHeaderBytes |= 1; \/\/ set the bit to 1\n\t\tsize_t oldHeaderBytes = *startPointerBlock;\n\t\t*startPointerBlock = newHeaderBytes;\n\t\tstartPointerBlock += bytes \/ BLOCK_ALIGNMENT + 1;\n\t\t*startPointerBlock = bytes;\n\t\tstartPointerBlock += 1;\n\t\t*startPointerBlock = oldHeaderBytes - bytes - BLOCK_ALIGNMENT - BLOCK_ALIGNMENT;\n\t\tstartPointerBlock += *startPointerBlock \/ BLOCK_ALIGNMENT + 1;\n\t\t*startPointerBlock = oldHeaderBytes - bytes - BLOCK_ALIGNMENT - BLOCK_ALIGNMENT;\n\t\t\n\t\treturn pUserBlock;\n\t}\n\telse {\n\t\twhile (*startPointerBlock % BLOCK_ALIGNMENT != 0 && startPointerBlock >= pStartBlock && startPointerBlock <= pEndBlock) {\n\t\t\tstartPointerBlock += *startPointerBlock \/ BLOCK_ALIGNMENT + 2;\n\t\t}\n\t\tbool isLastAvailableBlock = false;\n\t\tif (*startPointerBlock \/ BLOCK_ALIGNMENT + 2) {\n\t\t\tisLastAvailableBlock = true;\n\t\t}\n\n\t\tif ((bytes + BLOCK_ALIGNMENT + BLOCK_ALIGNMENT > *startPointerBlock && !isLastAvailableBlock) || *startPointerBlock % BLOCK_ALIGNMENT != 0 || *startPointerBlock == 0) {\n\t\t\tstd::cerr << \"ERROR! There is not enough memory.\" << std::endl;\n\t\t\treturn NULL;\n\t\t}\n\n\t\tvalue_type* pUserBlock = startPointerBlock + 1;\n\t\t\t\n\t\tif (isLastAvailableBlock && bytes == *startPointerBlock) {\n\t\t\tsize_t newHeaderBytes = bytes;\n\t\t\tnewHeaderBytes |= 1; \/\/ set the bit to 1\n\t\t\tsize_t oldHeaderBytes = *startPointerBlock;\n\t\t\t*startPointerBlock = newHeaderBytes;\n\t\t\tstartPointerBlock += bytes \/ BLOCK_ALIGNMENT + 1;\n\t\t\t*startPointerBlock = bytes;\n\t\t}\n\t\telse {\n\t\t\tif (isLastAvailableBlock && bytes + BLOCK_ALIGNMENT + BLOCK_ALIGNMENT > *startPointerBlock) {\n\t\t\t\tstd::cerr << \"ERROR! There is not enough memory.\" << std::endl;\n\t\t\t\treturn NULL;\n\t\t\t}\n\t\t\tsize_t newHeaderBytes = bytes;\n\t\t\tnewHeaderBytes |= 1; \/\/ set the bit to 1\n\t\t\tsize_t oldHeaderBytes = *startPointerBlock;\n\t\t\t*startPointerBlock = newHeaderBytes;\n\t\t\tstartPointerBlock += bytes \/ BLOCK_ALIGNMENT + 1;\n\t\t\t*startPointerBlock = bytes;\n\t\t\tstartPointerBlock += 1;\n\t\t\t*startPointerBlock = oldHeaderBytes - bytes - BLOCK_ALIGNMENT - BLOCK_ALIGNMENT;\n\t\t\tstartPointerBlock += *startPointerBlock \/ BLOCK_ALIGNMENT + 1;\n\t\t\t*startPointerBlock = oldHeaderBytes - bytes - BLOCK_ALIGNMENT - BLOCK_ALIGNMENT;\n\t\t}\n\t\t\n\n\t\treturn pUserBlock;\n\n\t}\n\n\treturn NULL;\n}\n\nvoid MemoryAllocator::MyFree(value_type* pBlock) {\n\tif (pBlock == NULL) {\n\t\tstd::cerr << \"ERROR! Wrong address.\" << std::endl;\n\t\treturn;\n\t}\n\n\tvalue_type* currentHeader = pBlock - 1; \n\t\/\/std::cout << \"currentHeader: \" << *currentHeader << std::endl;\n\t\n\tvalue_type* leftHeader = currentHeader - (*(currentHeader - 1) \/ BLOCK_ALIGNMENT) - 2;\n\t\/\/std::cout << \"leftHeader: \" << *leftHeader << std::endl;\n\t\n\tvalue_type* rightHeader = currentHeader + *currentHeader \/ BLOCK_ALIGNMENT + 2;\n\t\/\/std::cout << \"rightHeader: \" << *rightHeader << std::endl;\n\n\tif (currentHeader < pStartBlock || currentHeader > pEndBlock) {\n\t\tstd::cerr << \"ERROR! Wrong address.\" << std::endl;\n\t\treturn;\n\t}\n\n\tif (*leftHeader % BLOCK_ALIGNMENT != 0 && *rightHeader % BLOCK_ALIGNMENT != 0 && leftHeader >= pStartBlock && rightHeader <= pEndBlock) {\n\t\tstd::cout << \"-----first case\" << std::endl;\n\t\t*currentHeader &= ~1;\n\t}\n\telse if (*leftHeader % BLOCK_ALIGNMENT == 0 && *rightHeader % BLOCK_ALIGNMENT == 0 && leftHeader >= pStartBlock && rightHeader <= pEndBlock) {\n\t\tstd::cout << \"-----fourth case\" << std::endl;\n\t\t*currentHeader &= ~1;\n\t\tsize_t newHeaderBytes = *currentHeader + *leftHeader + BLOCK_ALIGNMENT + BLOCK_ALIGNMENT + *rightHeader + BLOCK_ALIGNMENT + BLOCK_ALIGNMENT;\n\t\tcurrentHeader -= 1;\n\t\tcurrentHeader -= (*currentHeader \/ BLOCK_ALIGNMENT + 1);\n\t\t*currentHeader = newHeaderBytes;\n\t\tcurrentHeader += *currentHeader \/ BLOCK_ALIGNMENT + 1;\n\t\t*currentHeader = newHeaderBytes;\n\t}\n\telse if (*rightHeader % BLOCK_ALIGNMENT == 0 && rightHeader <= pEndBlock) {\n\t\tstd::cout << \"-----second case\" << std::endl;\n\t\t*currentHeader &= ~1;\n\t\tsize_t newHeaderBytes = *currentHeader + *rightHeader + BLOCK_ALIGNMENT + BLOCK_ALIGNMENT;\n\t\t*currentHeader = newHeaderBytes;\n\t\tcurrentHeader += *currentHeader \/ BLOCK_ALIGNMENT + 1;\n\t\t*currentHeader = newHeaderBytes;\n\n\t}\n\telse if (*leftHeader % BLOCK_ALIGNMENT == 0 && leftHeader >= pStartBlock) {\n\t\tstd::cout << \"-----third case\" << std::endl;\n\t\t*currentHeader &= ~1;\n\t\tsize_t newHeaderBytes = *currentHeader + *leftHeader + BLOCK_ALIGNMENT + BLOCK_ALIGNMENT;\n\t\tcurrentHeader -= 1;\n\t\tcurrentHeader -= (*currentHeader \/ BLOCK_ALIGNMENT + 1);\n\t\t*currentHeader = newHeaderBytes;\n\t\tcurrentHeader += *currentHeader \/ BLOCK_ALIGNMENT + 1;\n\t\t*currentHeader = newHeaderBytes;\n\t\t\n\t}\n\telse {\n\t\tstd::cout << \"fifth case\" << std::endl;\n\n\t\tif (leftHeader < pStartBlock && *rightHeader % BLOCK_ALIGNMENT != 0) {\n\t\t\t*currentHeader &= ~1;\n\t\t}\n\t\t\n\t\tif (rightHeader > pEndBlock && *leftHeader % BLOCK_ALIGNMENT != 0) {\n\t\t\t*currentHeader &= ~1;\n\t\t}\n\t}\n\n}\n\nvoid roundUp(size_t& bytes) {\n\tif (bytes % BLOCK_ALIGNMENT != 0) {\n\t\tbytes = bytes - (bytes % BLOCK_ALIGNMENT) + BLOCK_ALIGNMENT;\n\t}\n}<|endoftext|>"} {"text":"<commit_before>#include <stdlib.h>\n#include \"license-generator.h\"\n\nint main(int argc, const char *argv[]) {\n\t \/\/license::LicenseGenerator lic;\n\t return license::LicenseGenerator::generateLicense(argc, argv);\n\n}\n\n<commit_msg>cleanup<commit_after>#include <stdlib.h>\n#include \"license-generator.h\"\n\nint main(int argc, const char *argv[]) {\n\t return license::LicenseGenerator::generateLicense(argc, argv);\n\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 2015 Samsung Electronics Co., Ltd.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *\/\n\n#include <dali-toolkit\/dali-toolkit.h>\n\nusing namespace Dali;\nusing Dali::Toolkit::Model3dView;\n\nnamespace\n{\nconst int MODEL_NUMBER(3);\n\nconst char * const MODEL_FILE[] = {\n DEMO_MODEL_DIR \"Dino.obj\",\n DEMO_MODEL_DIR \"ToyRobot-Metal.obj\",\n DEMO_MODEL_DIR \"Toyrobot-Plastic.obj\"\n};\n\nconst char * const MATERIAL_FILE[] = {\n DEMO_MODEL_DIR \"Dino.mtl\",\n DEMO_MODEL_DIR \"ToyRobot-Metal.mtl\",\n DEMO_MODEL_DIR \"Toyrobot-Plastic.mtl\"\n};\n\nconst char * const IMAGE_PATH( DEMO_IMAGE_DIR \"\" );\n\nconst char * BACKGROUND_IMAGE( DEMO_IMAGE_DIR \"background-1.jpg\");\n\n}\n\n\/*\n * This example shows how to create and display a model3d-view control.\n * The application can cycle between 3 different models, and 3 different shaders.\n * There are two animations running, one is a rotation for the model, one is a light that\n * goes from one side of the model to the other.\n * There are dedicated buttons for changing the models, the shaders and pausing the animations.\n * The animations can also be paused, resumed with the space key\n * A double tap in the model3d-view will make zoom-in\/out of the zone clicked\n *\/\n\nclass Model3dViewController : public ConnectionTracker\n{\npublic:\n\n Model3dViewController( Application& application )\n : mApplication( application )\n {\n \/\/ Connect to the Application's Init signal\n mApplication.InitSignal().Connect( this, &Model3dViewController::Create );\n }\n\n ~Model3dViewController()\n {\n \/\/ Nothing to do here;\n }\n\n \/\/ The Init signal is received once (only) during the Application lifetime\n void Create( Application& application )\n {\n \/\/ Get a handle to the stage\n Stage stage = Stage::GetCurrent();\n Vector2 screenSize = stage.GetSize();\n\n \/\/Add background\n Toolkit::ImageView backView = Toolkit::ImageView::New(BACKGROUND_IMAGE);\n backView.SetAnchorPoint( AnchorPoint::TOP_LEFT );\n stage.Add(backView);\n\n \/\/Add 3D model control\n m3DLayer = Layer::New();\n stage.GetRootLayer().Add(m3DLayer);\n\n \/\/3D models require 3D based rendering method, so it can use depth buffer, etc.\n m3DLayer.SetBehavior(Layer::LAYER_3D);\n m3DLayer.SetParentOrigin( ParentOrigin::CENTER );\n m3DLayer.SetAnchorPoint( AnchorPoint::CENTER );\n\n mModelCounter = 0;\n\n mModel3dView = Model3dView::New( MODEL_FILE[0], MATERIAL_FILE[0], IMAGE_PATH );\n mModel3dView.SetParentOrigin( ParentOrigin::CENTER );\n mModel3dView.SetAnchorPoint( AnchorPoint::CENTER );\n mModel3dView.SetName( \"model3dViewControl\" );\n mModel3dView.SetResizePolicy(ResizePolicy::FIXED, Dimension::ALL_DIMENSIONS);\n mModel3dView.SetSize(screenSize);\n\n mModel3dView.SetProperty(Model3dView::Property::LIGHT_POSITION, Vector3(5,10.,0));\n\n m3DLayer.Add( mModel3dView );\n\n mIlluminationShader = Model3dView::IlluminationType(mModel3dView.GetProperty<int>(Model3dView::Property::ILLUMINATION_TYPE));\n\n mButtonLayer = Layer::New();\n mButtonLayer.SetResizePolicy( ResizePolicy::FILL_TO_PARENT, Dimension::ALL_DIMENSIONS );\n mButtonLayer.SetParentOrigin( ParentOrigin::CENTER );\n mButtonLayer.SetAnchorPoint( AnchorPoint::CENTER );\n stage.GetRootLayer().Add(mButtonLayer);\n\n \/\/ Create button for model changing\n Toolkit::PushButton editButton = Toolkit::PushButton::New();\n editButton.SetResizePolicy( ResizePolicy::USE_NATURAL_SIZE, Dimension::ALL_DIMENSIONS );\n editButton.ClickedSignal().Connect( this, &Model3dViewController::OnChangeModelClicked);\n editButton.SetParentOrigin( ParentOrigin::TOP_LEFT );\n editButton.SetAnchorPoint( AnchorPoint::TOP_LEFT );\n editButton.SetLabelText( \"Change Model\" );\n mButtonLayer.Add( editButton );\n\n \/\/ Create button for shader changing\n editButton = Toolkit::PushButton::New();\n editButton.SetResizePolicy( ResizePolicy::USE_NATURAL_SIZE, Dimension::ALL_DIMENSIONS );\n editButton.ClickedSignal().Connect( this, &Model3dViewController::OnChangeLightingClicked);\n editButton.SetParentOrigin( ParentOrigin::TOP_RIGHT );\n editButton.SetAnchorPoint( AnchorPoint::TOP_RIGHT );\n editButton.SetLabelText( \"Change Shader\" );\n mButtonLayer.Add( editButton );\n\n \/\/ Create button for pause\/resume animation\n editButton = Toolkit::PushButton::New();\n editButton.SetResizePolicy( ResizePolicy::USE_NATURAL_SIZE, Dimension::ALL_DIMENSIONS );\n editButton.ClickedSignal().Connect( this, &Model3dViewController::OnPauseAnimationsClicked);\n editButton.SetParentOrigin( ParentOrigin::BOTTOM_CENTER );\n editButton.SetAnchorPoint( AnchorPoint::BOTTOM_CENTER );\n editButton.SetLabelText( \"Pause Animations\" );\n mButtonLayer.Add( editButton );\n\n \/\/Create animations\n mLightAnimation = Animation::New(6.f);\n mLightAnimation.AnimateTo(Property(mModel3dView, Model3dView::Property::LIGHT_POSITION), Vector3(-5,10.0,0), TimePeriod( 0.0f, 3.0f ));\n mLightAnimation.AnimateTo(Property(mModel3dView, Model3dView::Property::LIGHT_POSITION), Vector3(5,10.0,0), TimePeriod( 3.0f, 3.0f ));\n mLightAnimation.SetLooping(true);\n mLightAnimation.Play();\n\n mRotationAnimation = Animation::New(15.f);\n mRotationAnimation.AnimateBy(Property(mModel3dView, Actor::Property::ORIENTATION), Quaternion(Degree(0.f), Degree(360.f), Degree(0.f)) );\n mRotationAnimation.SetLooping(true);\n mRotationAnimation.Play();\n\n mPlaying = true;\n mScaled = false;\n\n \/\/ Respond to a click anywhere on the stage\n stage.KeyEventSignal().Connect(this, &Model3dViewController::OnKeyEvent);\n\n \/\/Create a tap gesture detector for zoom\n mTapDetector = TapGestureDetector::New( 2 );\n mTapDetector.DetectedSignal().Connect(this, &Model3dViewController::OnTap);\n\n mTapDetector.Attach( backView );\n }\n\n \/**\n * Main Tap event handler\n *\/\n void OnTap( Actor actor, const TapGesture& tap )\n {\n if (mScaled)\n {\n mModel3dView.SetScale(1.0);\n mModel3dView.SetPosition(0,0,0);\n mScaled = false;\n }\n else\n {\n Stage stage = Stage::GetCurrent();\n Vector2 screenSize = stage.GetSize();\n\n Vector2 position;\n position.x = tap.screenPoint.x - screenSize.x * 0.5;\n position.y = tap.screenPoint.y - screenSize.y * 0.5;\n\n float size = 2.5;\n\n mModel3dView.SetScale(size);\n mModel3dView.SetPosition(-position.x * size,-position.y * size, 0);\n mScaled = true;\n }\n }\n\n \/**\n * Change models button signal function\n *\/\n bool OnChangeModelClicked(Toolkit::Button button)\n {\n mModelCounter = (mModelCounter + 1) % MODEL_NUMBER;\n mModel3dView.SetProperty(Model3dView::Property::GEOMETRY_URL, MODEL_FILE[mModelCounter]);\n mModel3dView.SetProperty(Model3dView::Property::MATERIAL_URL, MATERIAL_FILE[mModelCounter]);\n mModel3dView.SetProperty(Model3dView::Property::IMAGES_URL, IMAGE_PATH);\n\n return true;\n }\n\n \/**\n * Change shader button signal function\n *\/\n bool OnChangeLightingClicked(Toolkit::Button button)\n {\n if( mIlluminationShader == Model3dView::DIFFUSE_WITH_NORMAL_MAP )\n {\n mModel3dView.SetProperty(Model3dView::Property::ILLUMINATION_TYPE, Model3dView::DIFFUSE_WITH_TEXTURE);\n mIlluminationShader = Model3dView::IlluminationType(mModel3dView.GetProperty<int>(Model3dView::Property::ILLUMINATION_TYPE));\n }\n else if( mIlluminationShader == Model3dView::DIFFUSE_WITH_TEXTURE )\n {\n mModel3dView.SetProperty(Model3dView::Property::ILLUMINATION_TYPE, Model3dView::DIFFUSE);\n mIlluminationShader = Model3dView::IlluminationType(mModel3dView.GetProperty<int>(Model3dView::Property::ILLUMINATION_TYPE));\n }\n else if( mIlluminationShader == Model3dView::DIFFUSE )\n {\n mModel3dView.SetProperty(Model3dView::Property::ILLUMINATION_TYPE, Model3dView::DIFFUSE_WITH_NORMAL_MAP);\n mIlluminationShader = Model3dView::IlluminationType(mModel3dView.GetProperty<int>(Model3dView::Property::ILLUMINATION_TYPE));\n }\n\n return true;\n }\n\n \/**\n * Function to pause resume all animations\n *\/\n void PauseAnimations()\n {\n if( mPlaying )\n {\n mRotationAnimation.Pause();\n mLightAnimation.Pause();\n\n mPlaying = false;\n }\n else\n {\n mRotationAnimation.Play();\n mLightAnimation.Play();\n\n mPlaying = true;\n }\n }\n\n \/**\n * Pause button signal function\n *\/\n bool OnPauseAnimationsClicked(Toolkit::Button button)\n {\n PauseAnimations();\n\n return true;\n }\n\n \/**\n * Main key event handler\n *\/\n void OnKeyEvent(const KeyEvent& event)\n {\n if(event.state == KeyEvent::Down)\n {\n if( IsKey( event, Dali::DALI_KEY_ESCAPE) || IsKey( event, Dali::DALI_KEY_BACK) )\n {\n mApplication.Quit();\n }\n else\n {\n PauseAnimations();\n }\n }\n }\n\n\nprivate:\n Application& mApplication;\n\n int mModelCounter;\n Model3dView mModel3dView;\n\n Layer m3DLayer;\n Layer mButtonLayer;\n TapGestureDetector mTapDetector;\n\n Model3dView::IlluminationType mIlluminationShader;\n\n Animation mRotationAnimation;\n Animation mLightAnimation;\n bool mPlaying;\n\n bool mScaled;\n};\n\nvoid RunTest( Application& application )\n{\n Model3dViewController test( application );\n\n application.MainLoop();\n}\n\n\/\/ Entry point for Linux & Tizen applications\n\/\/\nint DALI_EXPORT_API main( int argc, char **argv )\n{\n Application application = Application::New( &argc, &argv );\n\n RunTest( application );\n\n return 0;\n}\n<commit_msg>Model3DView does not need to set IMAGES_URL when changing model<commit_after>\/*\n * Copyright (c) 2015 Samsung Electronics Co., Ltd.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *\/\n\n#include <dali-toolkit\/dali-toolkit.h>\n\nusing namespace Dali;\nusing Dali::Toolkit::Model3dView;\n\nnamespace\n{\nconst int MODEL_NUMBER(3);\n\nconst char * const MODEL_FILE[] = {\n DEMO_MODEL_DIR \"Dino.obj\",\n DEMO_MODEL_DIR \"ToyRobot-Metal.obj\",\n DEMO_MODEL_DIR \"Toyrobot-Plastic.obj\"\n};\n\nconst char * const MATERIAL_FILE[] = {\n DEMO_MODEL_DIR \"Dino.mtl\",\n DEMO_MODEL_DIR \"ToyRobot-Metal.mtl\",\n DEMO_MODEL_DIR \"Toyrobot-Plastic.mtl\"\n};\n\nconst char * const IMAGE_PATH( DEMO_IMAGE_DIR \"\" );\n\nconst char * BACKGROUND_IMAGE( DEMO_IMAGE_DIR \"background-1.jpg\");\n\n}\n\n\/*\n * This example shows how to create and display a model3d-view control.\n * The application can cycle between 3 different models, and 3 different shaders.\n * There are two animations running, one is a rotation for the model, one is a light that\n * goes from one side of the model to the other.\n * There are dedicated buttons for changing the models, the shaders and pausing the animations.\n * The animations can also be paused, resumed with the space key\n * A double tap in the model3d-view will make zoom-in\/out of the zone clicked\n *\/\n\nclass Model3dViewController : public ConnectionTracker\n{\npublic:\n\n Model3dViewController( Application& application )\n : mApplication( application )\n {\n \/\/ Connect to the Application's Init signal\n mApplication.InitSignal().Connect( this, &Model3dViewController::Create );\n }\n\n ~Model3dViewController()\n {\n \/\/ Nothing to do here;\n }\n\n \/\/ The Init signal is received once (only) during the Application lifetime\n void Create( Application& application )\n {\n \/\/ Get a handle to the stage\n Stage stage = Stage::GetCurrent();\n Vector2 screenSize = stage.GetSize();\n\n \/\/Add background\n Toolkit::ImageView backView = Toolkit::ImageView::New(BACKGROUND_IMAGE);\n backView.SetAnchorPoint( AnchorPoint::TOP_LEFT );\n stage.Add(backView);\n\n \/\/Add 3D model control\n m3DLayer = Layer::New();\n stage.GetRootLayer().Add(m3DLayer);\n\n \/\/3D models require 3D based rendering method, so it can use depth buffer, etc.\n m3DLayer.SetBehavior(Layer::LAYER_3D);\n m3DLayer.SetParentOrigin( ParentOrigin::CENTER );\n m3DLayer.SetAnchorPoint( AnchorPoint::CENTER );\n\n mModelCounter = 0;\n\n mModel3dView = Model3dView::New( MODEL_FILE[0], MATERIAL_FILE[0], IMAGE_PATH );\n mModel3dView.SetParentOrigin( ParentOrigin::CENTER );\n mModel3dView.SetAnchorPoint( AnchorPoint::CENTER );\n mModel3dView.SetName( \"model3dViewControl\" );\n mModel3dView.SetResizePolicy(ResizePolicy::FIXED, Dimension::ALL_DIMENSIONS);\n mModel3dView.SetSize(screenSize);\n\n mModel3dView.SetProperty(Model3dView::Property::LIGHT_POSITION, Vector3(5,10.,0));\n\n m3DLayer.Add( mModel3dView );\n\n mIlluminationShader = Model3dView::IlluminationType(mModel3dView.GetProperty<int>(Model3dView::Property::ILLUMINATION_TYPE));\n\n mButtonLayer = Layer::New();\n mButtonLayer.SetResizePolicy( ResizePolicy::FILL_TO_PARENT, Dimension::ALL_DIMENSIONS );\n mButtonLayer.SetParentOrigin( ParentOrigin::CENTER );\n mButtonLayer.SetAnchorPoint( AnchorPoint::CENTER );\n stage.GetRootLayer().Add(mButtonLayer);\n\n \/\/ Create button for model changing\n Toolkit::PushButton editButton = Toolkit::PushButton::New();\n editButton.SetResizePolicy( ResizePolicy::USE_NATURAL_SIZE, Dimension::ALL_DIMENSIONS );\n editButton.ClickedSignal().Connect( this, &Model3dViewController::OnChangeModelClicked);\n editButton.SetParentOrigin( ParentOrigin::TOP_LEFT );\n editButton.SetAnchorPoint( AnchorPoint::TOP_LEFT );\n editButton.SetLabelText( \"Change Model\" );\n mButtonLayer.Add( editButton );\n\n \/\/ Create button for shader changing\n editButton = Toolkit::PushButton::New();\n editButton.SetResizePolicy( ResizePolicy::USE_NATURAL_SIZE, Dimension::ALL_DIMENSIONS );\n editButton.ClickedSignal().Connect( this, &Model3dViewController::OnChangeLightingClicked);\n editButton.SetParentOrigin( ParentOrigin::TOP_RIGHT );\n editButton.SetAnchorPoint( AnchorPoint::TOP_RIGHT );\n editButton.SetLabelText( \"Change Shader\" );\n mButtonLayer.Add( editButton );\n\n \/\/ Create button for pause\/resume animation\n editButton = Toolkit::PushButton::New();\n editButton.SetResizePolicy( ResizePolicy::USE_NATURAL_SIZE, Dimension::ALL_DIMENSIONS );\n editButton.ClickedSignal().Connect( this, &Model3dViewController::OnPauseAnimationsClicked);\n editButton.SetParentOrigin( ParentOrigin::BOTTOM_CENTER );\n editButton.SetAnchorPoint( AnchorPoint::BOTTOM_CENTER );\n editButton.SetLabelText( \"Pause Animations\" );\n mButtonLayer.Add( editButton );\n\n \/\/Create animations\n mLightAnimation = Animation::New(6.f);\n mLightAnimation.AnimateTo(Property(mModel3dView, Model3dView::Property::LIGHT_POSITION), Vector3(-5,10.0,0), TimePeriod( 0.0f, 3.0f ));\n mLightAnimation.AnimateTo(Property(mModel3dView, Model3dView::Property::LIGHT_POSITION), Vector3(5,10.0,0), TimePeriod( 3.0f, 3.0f ));\n mLightAnimation.SetLooping(true);\n mLightAnimation.Play();\n\n mRotationAnimation = Animation::New(15.f);\n mRotationAnimation.AnimateBy(Property(mModel3dView, Actor::Property::ORIENTATION), Quaternion(Degree(0.f), Degree(360.f), Degree(0.f)) );\n mRotationAnimation.SetLooping(true);\n mRotationAnimation.Play();\n\n mPlaying = true;\n mScaled = false;\n\n \/\/ Respond to a click anywhere on the stage\n stage.KeyEventSignal().Connect(this, &Model3dViewController::OnKeyEvent);\n\n \/\/Create a tap gesture detector for zoom\n mTapDetector = TapGestureDetector::New( 2 );\n mTapDetector.DetectedSignal().Connect(this, &Model3dViewController::OnTap);\n\n mTapDetector.Attach( backView );\n }\n\n \/**\n * Main Tap event handler\n *\/\n void OnTap( Actor actor, const TapGesture& tap )\n {\n if (mScaled)\n {\n mModel3dView.SetScale(1.0);\n mModel3dView.SetPosition(0,0,0);\n mScaled = false;\n }\n else\n {\n Stage stage = Stage::GetCurrent();\n Vector2 screenSize = stage.GetSize();\n\n Vector2 position;\n position.x = tap.screenPoint.x - screenSize.x * 0.5;\n position.y = tap.screenPoint.y - screenSize.y * 0.5;\n\n float size = 2.5;\n\n mModel3dView.SetScale(size);\n mModel3dView.SetPosition(-position.x * size,-position.y * size, 0);\n mScaled = true;\n }\n }\n\n \/**\n * Change models button signal function\n *\/\n bool OnChangeModelClicked(Toolkit::Button button)\n {\n mModelCounter = (mModelCounter + 1) % MODEL_NUMBER;\n mModel3dView.SetProperty(Model3dView::Property::GEOMETRY_URL, MODEL_FILE[mModelCounter]);\n mModel3dView.SetProperty(Model3dView::Property::MATERIAL_URL, MATERIAL_FILE[mModelCounter]);\n return true;\n }\n\n \/**\n * Change shader button signal function\n *\/\n bool OnChangeLightingClicked(Toolkit::Button button)\n {\n if( mIlluminationShader == Model3dView::DIFFUSE_WITH_NORMAL_MAP )\n {\n mModel3dView.SetProperty(Model3dView::Property::ILLUMINATION_TYPE, Model3dView::DIFFUSE_WITH_TEXTURE);\n mIlluminationShader = Model3dView::IlluminationType(mModel3dView.GetProperty<int>(Model3dView::Property::ILLUMINATION_TYPE));\n }\n else if( mIlluminationShader == Model3dView::DIFFUSE_WITH_TEXTURE )\n {\n mModel3dView.SetProperty(Model3dView::Property::ILLUMINATION_TYPE, Model3dView::DIFFUSE);\n mIlluminationShader = Model3dView::IlluminationType(mModel3dView.GetProperty<int>(Model3dView::Property::ILLUMINATION_TYPE));\n }\n else if( mIlluminationShader == Model3dView::DIFFUSE )\n {\n mModel3dView.SetProperty(Model3dView::Property::ILLUMINATION_TYPE, Model3dView::DIFFUSE_WITH_NORMAL_MAP);\n mIlluminationShader = Model3dView::IlluminationType(mModel3dView.GetProperty<int>(Model3dView::Property::ILLUMINATION_TYPE));\n }\n\n return true;\n }\n\n \/**\n * Function to pause resume all animations\n *\/\n void PauseAnimations()\n {\n if( mPlaying )\n {\n mRotationAnimation.Pause();\n mLightAnimation.Pause();\n\n mPlaying = false;\n }\n else\n {\n mRotationAnimation.Play();\n mLightAnimation.Play();\n\n mPlaying = true;\n }\n }\n\n \/**\n * Pause button signal function\n *\/\n bool OnPauseAnimationsClicked(Toolkit::Button button)\n {\n PauseAnimations();\n\n return true;\n }\n\n \/**\n * Main key event handler\n *\/\n void OnKeyEvent(const KeyEvent& event)\n {\n if(event.state == KeyEvent::Down)\n {\n if( IsKey( event, Dali::DALI_KEY_ESCAPE) || IsKey( event, Dali::DALI_KEY_BACK) )\n {\n mApplication.Quit();\n }\n else\n {\n PauseAnimations();\n }\n }\n }\n\n\nprivate:\n Application& mApplication;\n\n int mModelCounter;\n Model3dView mModel3dView;\n\n Layer m3DLayer;\n Layer mButtonLayer;\n TapGestureDetector mTapDetector;\n\n Model3dView::IlluminationType mIlluminationShader;\n\n Animation mRotationAnimation;\n Animation mLightAnimation;\n bool mPlaying;\n\n bool mScaled;\n};\n\nvoid RunTest( Application& application )\n{\n Model3dViewController test( application );\n\n application.MainLoop();\n}\n\n\/\/ Entry point for Linux & Tizen applications\n\/\/\nint DALI_EXPORT_API main( int argc, char **argv )\n{\n Application application = Application::New( &argc, &argv );\n\n RunTest( application );\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/-----------------------------------------------\n\/\/\n\/\/\tThis file is part of the Siv3D Engine.\n\/\/\n\/\/\tCopyright (c) 2008-2021 Ryo Suzuki\n\/\/\tCopyright (c) 2016-2021 OpenSiv3D Project\n\/\/\n\/\/\tLicensed under the MIT License.\n\/\/\n\/\/-----------------------------------------------\n\n# include <Siv3D\/Script.hpp>\n# include <Siv3D\/Polygon.hpp>\n# include \"ScriptBind.hpp\"\n# include \"..\/angelScript\/scriptarray.h\"\n\nnamespace s3d\n{\n\tusing namespace AngelScript;\n\n\tusing ShapeType = Polygon;\n\n\tstatic void DefaultConstruct(ShapeType* self)\n\t{\n\t\tnew(self) ShapeType();\n\t}\n\n\tstatic void CopyConstruct(const Polygon& other, ShapeType* self)\n\t{\n\t\tnew(self) ShapeType(other);\n\t}\n\n\tstatic void ConstructS(const Shape2D& shape2D, ShapeType* self)\n\t{\n\t\tnew(self) ShapeType(shape2D);\n\t}\n\n\tstatic void Destruct(ShapeType* self)\n\t{\n\t\tself->~Polygon();\n\t}\n\n\tstatic void ListConstruct(const void* list, ShapeType* self)\n\t{\n\t\tconst size_t length = *static_cast<const asUINT*>(list);\n\t\tconst Vec2* data = static_cast<const Vec2*>(static_cast<const void*>(static_cast<const uint8*>(list) + 4));\n\t\tnew(self) ShapeType(data, length);\n\t}\n\n\tstatic CScriptArray* Outer(const Polygon& self)\n\t{\n\t\tasITypeInfo* typeID = asGetActiveContext()->GetEngine()->GetTypeInfoByDecl(\"Array<Vec2>\");\n\n\t\tif (void* mem = std::malloc(self.outer().size_bytes() + sizeof(asUINT)))\n\t\t{\n\t\t\t*(asUINT*)mem = static_cast<asUINT>(self.outer().size());\n\t\t\tstd::memcpy(((asUINT*)mem) + 1, self.outer().data(), self.outer().size_bytes());\n\n\t\t\tconst auto p = CScriptArray::Create(typeID, mem);\n\t\t\tstd::free(mem);\n\n\t\t\treturn p;\n\t\t}\n\t\telse\n\t\t{\n\t\t\treturn nullptr;\n\t\t}\n\t}\n\n\tstatic bool ConvToBool(const Polygon& polygon)\n\t{\n\t\treturn !polygon.isEmpty();\n\t}\n\n\tvoid RegisterPolygon(asIScriptEngine* engine)\n\t{\n\t\tconstexpr char TypeName[] = \"Polygon\";\n\n\t\tint32 r = 0;\n\t\tr = engine->RegisterObjectBehaviour(TypeName, asBEHAVE_CONSTRUCT, \"void f()\", asFUNCTION(DefaultConstruct), asCALL_CDECL_OBJLAST); assert(r >= 0);\n\t\tr = engine->RegisterObjectBehaviour(TypeName, asBEHAVE_CONSTRUCT, \"void f(const Polygon& in)\", asFUNCTION(CopyConstruct), asCALL_CDECL_OBJLAST); assert(r >= 0);\n\t\tr = engine->RegisterObjectBehaviour(TypeName, asBEHAVE_DESTRUCT, \"void f()\", asFUNCTION(Destruct), asCALL_CDECL_OBJLAST); assert(r >= 0);\n\t\t\/\/r = engine->RegisterObjectBehaviour(TypeName, asBEHAVE_CONSTRUCT, \"void f(const Shape2D& in)\", asFUNCTION(ConstructS), asCALL_CDECL_OBJLAST); assert(r >= 0);\n\t\tr = engine->RegisterObjectBehaviour(TypeName, asBEHAVE_LIST_CONSTRUCT, \"void f(const Vec2& in) {repeat Vec2}\", asFUNCTION(ListConstruct), asCALL_CDECL_OBJLAST); assert(r >= 0);\n\n\t}\n}\n<commit_msg>[Linux] fix<commit_after>\/\/-----------------------------------------------\n\/\/\n\/\/\tThis file is part of the Siv3D Engine.\n\/\/\n\/\/\tCopyright (c) 2008-2021 Ryo Suzuki\n\/\/\tCopyright (c) 2016-2021 OpenSiv3D Project\n\/\/\n\/\/\tLicensed under the MIT License.\n\/\/\n\/\/-----------------------------------------------\n\n# include <Siv3D\/Script.hpp>\n# include <Siv3D\/Polygon.hpp>\n# include \"ScriptBind.hpp\"\n# include \"..\/angelscript\/scriptarray.h\"\n\nnamespace s3d\n{\n\tusing namespace AngelScript;\n\n\tusing ShapeType = Polygon;\n\n\tstatic void DefaultConstruct(ShapeType* self)\n\t{\n\t\tnew(self) ShapeType();\n\t}\n\n\tstatic void CopyConstruct(const Polygon& other, ShapeType* self)\n\t{\n\t\tnew(self) ShapeType(other);\n\t}\n\n\tstatic void ConstructS(const Shape2D& shape2D, ShapeType* self)\n\t{\n\t\tnew(self) ShapeType(shape2D);\n\t}\n\n\tstatic void Destruct(ShapeType* self)\n\t{\n\t\tself->~Polygon();\n\t}\n\n\tstatic void ListConstruct(const void* list, ShapeType* self)\n\t{\n\t\tconst size_t length = *static_cast<const asUINT*>(list);\n\t\tconst Vec2* data = static_cast<const Vec2*>(static_cast<const void*>(static_cast<const uint8*>(list) + 4));\n\t\tnew(self) ShapeType(data, length);\n\t}\n\n\tstatic CScriptArray* Outer(const Polygon& self)\n\t{\n\t\tasITypeInfo* typeID = asGetActiveContext()->GetEngine()->GetTypeInfoByDecl(\"Array<Vec2>\");\n\n\t\tif (void* mem = std::malloc(self.outer().size_bytes() + sizeof(asUINT)))\n\t\t{\n\t\t\t*(asUINT*)mem = static_cast<asUINT>(self.outer().size());\n\t\t\tstd::memcpy(((asUINT*)mem) + 1, self.outer().data(), self.outer().size_bytes());\n\n\t\t\tconst auto p = CScriptArray::Create(typeID, mem);\n\t\t\tstd::free(mem);\n\n\t\t\treturn p;\n\t\t}\n\t\telse\n\t\t{\n\t\t\treturn nullptr;\n\t\t}\n\t}\n\n\tstatic bool ConvToBool(const Polygon& polygon)\n\t{\n\t\treturn !polygon.isEmpty();\n\t}\n\n\tvoid RegisterPolygon(asIScriptEngine* engine)\n\t{\n\t\tconstexpr char TypeName[] = \"Polygon\";\n\n\t\tint32 r = 0;\n\t\tr = engine->RegisterObjectBehaviour(TypeName, asBEHAVE_CONSTRUCT, \"void f()\", asFUNCTION(DefaultConstruct), asCALL_CDECL_OBJLAST); assert(r >= 0);\n\t\tr = engine->RegisterObjectBehaviour(TypeName, asBEHAVE_CONSTRUCT, \"void f(const Polygon& in)\", asFUNCTION(CopyConstruct), asCALL_CDECL_OBJLAST); assert(r >= 0);\n\t\tr = engine->RegisterObjectBehaviour(TypeName, asBEHAVE_DESTRUCT, \"void f()\", asFUNCTION(Destruct), asCALL_CDECL_OBJLAST); assert(r >= 0);\n\t\t\/\/r = engine->RegisterObjectBehaviour(TypeName, asBEHAVE_CONSTRUCT, \"void f(const Shape2D& in)\", asFUNCTION(ConstructS), asCALL_CDECL_OBJLAST); assert(r >= 0);\n\t\tr = engine->RegisterObjectBehaviour(TypeName, asBEHAVE_LIST_CONSTRUCT, \"void f(const Vec2& in) {repeat Vec2}\", asFUNCTION(ListConstruct), asCALL_CDECL_OBJLAST); assert(r >= 0);\n\n\t}\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"cropeditor.hpp\"\n\n#include \"cropscene.hpp\"\n#include \"cropview.hpp\"\n#include <QApplication>\n#include <QGraphicsPixmapItem>\n#include <QGraphicsView>\n#include <QScreen>\n#include <QTimer>\n#include <settings.hpp>\n\nCropEditor::CropEditor(QPixmap *image, QObject *parent) : QObject(parent) {\n scene = new CropScene(parent, image);\n view = new CropView(scene);\n qreal ratio = QApplication::primaryScreen()->devicePixelRatio();\n pixmapItem = new QGraphicsPixmapItem(*image);\n pixmapItem->setZValue(-1);\n pixmapItem->setScale(1 \/ ratio);\n scene->addItem(pixmapItem);\n scene->setSceneRect(image->rect());\n view->resize(image->width(), image->height());\n view->setMinimumSize(image->size());\n view->move(0, 0);\n view->show();\n\n connect(scene, &CropScene::closedWithRect, this, &CropEditor::crop);\n}\n\nCropEditor::~CropEditor() {\n delete scene;\n delete view;\n}\n\nvoid CropEditor::crop(QRect rect) {\n QPixmap map = view->grab(rect);\n QPixmap *cropp = new QPixmap;\n map.swap(*cropp);\n delete view;\n emit cropped(cropp);\n}\n<commit_msg>Crop editor finally has a title<commit_after>#include \"cropeditor.hpp\"\n\n#include \"cropscene.hpp\"\n#include \"cropview.hpp\"\n#include <QApplication>\n#include <QGraphicsPixmapItem>\n#include <QGraphicsView>\n#include <QScreen>\n#include <QTimer>\n#include <settings.hpp>\n\nCropEditor::CropEditor(QPixmap *image, QObject *parent) : QObject(parent) {\n scene = new CropScene(parent, image);\n view = new CropView(scene);\n qreal ratio = QApplication::primaryScreen()->devicePixelRatio();\n pixmapItem = new QGraphicsPixmapItem(*image);\n pixmapItem->setZValue(-1);\n pixmapItem->setScale(1 \/ ratio);\n scene->addItem(pixmapItem);\n scene->setSceneRect(image->rect());\n view->resize(image->width(), image->height());\n view->setMinimumSize(image->size());\n view->move(0, 0);\n view->setWindowTitle(\"KShare Crop Editor\");\n view->show();\n\n connect(scene, &CropScene::closedWithRect, this, &CropEditor::crop);\n}\n\nCropEditor::~CropEditor() {\n delete scene;\n delete view;\n}\n\nvoid CropEditor::crop(QRect rect) {\n QPixmap map = view->grab(rect);\n QPixmap *cropp = new QPixmap;\n map.swap(*cropp);\n delete view;\n emit cropped(cropp);\n}\n<|endoftext|>"} {"text":"<commit_before>#include <Maple\/Gameplay\/MapleGameLogic.h>\n#include <Bibim\/Math.h>\n#include <Bibim\/Assert.h>\nusing namespace Bibim;\n\nnamespace Maple\n{\n MapleGameLogic::MapleGameLogic()\n : restLife(DefaultLife)\n {\n\n }\n\n MapleGameLogic::MapleGameLogic(int size)\n : puzzleSize(size),\n restLife(DefaultLife)\n {\n\n }\n\n MapleGameLogic::MapleGameLogic(int size, const GamePanel& ansPattern)\n {\n Initialize(size, ansPattern);\n }\n\n void MapleGameLogic::Initialize(int size, const GamePanel& ansPattern)\n {\n puzzleSize = size;\n restLife = DefaultLife;\n\n this->ansPattern = ansPattern;\n }\n\n void MapleGameLogic::Restart()\n {\n for(int i = 0; i < puzzleSize; i++)\n {\n for(int j = 0; j < puzzleSize; j++)\n {\n solvePattern.arr[i][j] = TableState::Uncolored;\n }\n }\n\n restLife = DefaultLife;\n }\n\n void MapleGameLogic::Update(float \/*dt*\/, int \/*timestamp*\/)\n {\n \/\/ Use this code when need to use time measure\n }\n\n const MapleGameLogic::GamePanel& MapleGameLogic::GetSolvePanel() const\n {\n return solvePattern;\n }\n\n int MapleGameLogic::GetPuzzleSize() const\n {\n return puzzleSize;\n }\n\n int MapleGameLogic::GetRestLife() const\n {\n return restLife;\n }\n\n MapleGameLogic::TryFillColorResult::T MapleGameLogic::TryFillColor()\n {\n BBAssert(cursor.X == cursorTail.X || cursor.Y == cursorTail.Y);\n\n \/\/ 'dic' is direction from 'cursorTail' to 'cursor'\n Point2 dic = cursor - cursorTail;\n\n TryFillColorResult::T result = TryFillColorResult::NonChanged;\n\n if(dic == Point2::Zero)\n {\n \/\/ Clicked 'O' button when Single cell selected,\n \/\/ remove 'X' marker at selected cell.\n\n if(solvePattern.arr[cursor.X][cursor.Y] == TableState::Uncolored)\n {\n if(ansPattern.arr[cursor.X][cursor.Y] == TableState::Uncolored)\n {\n \/\/ If not correct, check wrong anser\n\n solvePattern.arr[cursor.X][cursor.Y] = TableState::ForceErased;\n\n Incorrect();\n result = TryFillColorResult::Incorrect;\n }\n else\n {\n \/\/ Only fill colored when correct\n\n solvePattern.arr[cursor.X][cursor.Y] = TableState::Colored;\n result = TryFillColorResult::Correct;\n }\n }\n else if(solvePattern.arr[cursor.X][cursor.Y] == TableState::Erased)\n {\n \/\/ remove 'X' marker when it filled 'X'\n\n solvePattern.arr[cursor.X][cursor.Y] = TableState::Uncolored;\n\n result = TryFillColorResult::NonChanged;\n }\n }\n else\n {\n if(dic.X != 0)\n dic.X \/= Math::Abs(dic.X);\n else if(dic.Y != 0)\n dic.Y \/= Math::Abs(dic.Y);\n\n result = TryFillColorResult::Correct;\n\n for(Point2 currentPoint = cursorTail; currentPoint != (cursor + dic); currentPoint += dic)\n {\n if(solvePattern.arr[currentPoint.X][currentPoint.Y] == TableState::Uncolored)\n {\n \/\/ Only works when 'Uncolored'\n\n if(ansPattern.arr[currentPoint.X][currentPoint.Y] == TableState::Uncolored)\n {\n \/\/ If not correct, check wrong anser and stop filling\n\n solvePattern.arr[currentPoint.X][currentPoint.Y] = TableState::ForceErased;\n\n Incorrect();\n result = TryFillColorResult::Incorrect;\n break;\n }\n else\n {\n \/\/ Only fill colored when correct.\n\n solvePattern.arr[currentPoint.X][currentPoint.Y] = TableState::Colored;\n }\n }\n }\n\n cursorTail = cursor;\n }\n\n if(GetRestLife() < 0)\n {\n result = TryFillColorResult::GameOver;\n }\n else if(WinCheck())\n {\n result = TryFillColorResult::Clear;\n }\n \n return result;\n }\n\n void MapleGameLogic::TryFillErased()\n {\n BBAssert(cursor.X == cursorTail.X || cursor.Y == cursorTail.Y);\n\n \/\/ dic cursorTail cursor ϴ \n Point2 dic = cursor - cursorTail;\n\n if(dic.X != 0)\n dic.X \/= Math::Abs(dic.X);\n else if(dic.Y != 0)\n dic.Y \/= Math::Abs(dic.Y);\n else\n dic.Y = 1;\n\n bool eraseMode = true;\n\n if(solvePattern.arr[cursorTail.X][cursorTail.Y] == TableState::Erased || solvePattern.arr[cursorTail.X][cursorTail.Y] == TableState::ForceErased)\n {\n \/\/ X , X մϴ.\n\n eraseMode = false;\n }\n\n for(Point2 currentPoint = cursorTail; currentPoint != (cursor + dic); currentPoint += dic)\n {\n if(eraseMode && solvePattern.arr[currentPoint.X][currentPoint.Y] == TableState::Uncolored)\n {\n \/\/ X ƴϰ, ƹ ͵ ĭ , X ǥ մϴ.\n solvePattern.arr[currentPoint.X][currentPoint.Y] = TableState::Erased;\n }\n else if(!eraseMode && solvePattern.arr[currentPoint.X][currentPoint.Y] == TableState::Erased)\n {\n \/\/ X̰, X ĥ ִ ĭ̸, X ϴ.\n solvePattern.arr[currentPoint.X][currentPoint.Y] = TableState::Uncolored;\n }\n }\n\n cursorTail = cursor;\n }\n\n std::vector<std::vector<int> > MapleGameLogic::GetHorizontalNumberCount() const\n {\n std::vector<std::vector<int> > pattern;\n\n \/\/ <TODO> Draw() Լ ð ٿ Ѵٸ, pattern ѹ ϵ ؾ մϴ.\n\n for(int i = 0; i < puzzleSize; i++)\n {\n std::vector<int> current;\n\n int j = puzzleSize - 1;\n int counter = 0;\n\n while(j >= 0)\n {\n if(ansPattern.arr[i][j] == TableState::Colored)\n counter++;\n else\n {\n if(counter > 0)\n {\n current.push_back(counter);\n counter = 0;\n }\n }\n\n j--;\n }\n\n if(counter > 0)\n current.push_back(counter);\n\n if(current.size() == 0)\n current.push_back(0);\n\n pattern.push_back(current);\n }\n\n return pattern;\n }\n\n std::vector<std::vector<int> > MapleGameLogic::GetVerticalNumberCount() const\n {\n std::vector<std::vector<int> > pattern;\n\n \/\/ <TODO> Draw() Լ ð ٿ Ѵٸ, pattern ѹ ϵ ؾ մϴ.\n\n for(int i = 0; i < puzzleSize; i++)\n {\n std::vector<int> current;\n\n int j = 0;\n int counter = 0;\n \n while(j < puzzleSize)\n {\n if(ansPattern.arr[j][i] == TableState::Colored)\n counter++;\n else\n {\n if(counter > 0)\n {\n current.push_back(counter);\n counter = 0;\n }\n }\n\n j++;\n }\n\n if(counter > 0)\n current.push_back(counter);\n\n if(current.size() == 0)\n current.push_back(0);\n\n pattern.push_back(current);\n }\n\n return pattern;\n }\n\n Point2 MapleGameLogic::GetCursor() const\n {\n return cursor;\n }\n\n void MapleGameLogic::SetCursor(const Bibim::Point2& value)\n {\n cursor.X = Math::Clamp(value.X, 0, puzzleSize - 1);\n cursor.Y = Math::Clamp(value.Y, 0, puzzleSize - 1);\n }\n\n Point2 MapleGameLogic::GetCursorTail() const\n {\n return cursorTail;\n }\n\n void MapleGameLogic::SetCursorTail(const Bibim::Point2& end)\n {\n Point2 clamped;\n clamped.X = Math::Clamp(end.X, 0, puzzleSize - 1);\n clamped.Y = Math::Clamp(end.Y, 0, puzzleSize - 1);\n\n cursorTail = clamped;\n cursor = clamped;\n }\n\n void MapleGameLogic::CursorMove(const Bibim::Point2& dPoint)\n {\n if(Math::Abs(dPoint.X) + Math::Abs(dPoint.Y) != 1)\n return;\n\n SetCursorTail(cursor + dPoint);\n }\n\n bool MapleGameLogic::WinCheck()\n {\n \/\/ ̰ üũϴ Դϴ.\n \/\/ üũ ĭ ġϸ Դϴ.\n\n bool result = true;\n\n for(int i = 0; i < puzzleSize; i++)\n {\n for(int j = 0; j < puzzleSize; j++)\n {\n if(ansPattern.arr[i][j] == TableState::Colored && solvePattern.arr[i][j] != TableState::Colored)\n {\n result = false;\n break;\n }\n }\n\n if(!result)\n break;\n }\n\n return result;\n }\n\n void MapleGameLogic::Incorrect()\n {\n \/\/ ϴ.\n\n \/\/ UIGameLogic ʿ մϴ.\n\n restLife--;\n }\n}\n<commit_msg>Translate Korean comment to English<commit_after>#include <Maple\/Gameplay\/MapleGameLogic.h>\n#include <Bibim\/Math.h>\n#include <Bibim\/Assert.h>\nusing namespace Bibim;\n\nnamespace Maple\n{\n MapleGameLogic::MapleGameLogic()\n : restLife(DefaultLife)\n {\n\n }\n\n MapleGameLogic::MapleGameLogic(int size)\n : puzzleSize(size),\n restLife(DefaultLife)\n {\n\n }\n\n MapleGameLogic::MapleGameLogic(int size, const GamePanel& ansPattern)\n {\n Initialize(size, ansPattern);\n }\n\n void MapleGameLogic::Initialize(int size, const GamePanel& ansPattern)\n {\n puzzleSize = size;\n restLife = DefaultLife;\n\n this->ansPattern = ansPattern;\n }\n\n void MapleGameLogic::Restart()\n {\n for(int i = 0; i < puzzleSize; i++)\n {\n for(int j = 0; j < puzzleSize; j++)\n {\n solvePattern.arr[i][j] = TableState::Uncolored;\n }\n }\n\n restLife = DefaultLife;\n }\n\n void MapleGameLogic::Update(float \/*dt*\/, int \/*timestamp*\/)\n {\n \/\/ Use this code when need to use time measure\n }\n\n const MapleGameLogic::GamePanel& MapleGameLogic::GetSolvePanel() const\n {\n return solvePattern;\n }\n\n int MapleGameLogic::GetPuzzleSize() const\n {\n return puzzleSize;\n }\n\n int MapleGameLogic::GetRestLife() const\n {\n return restLife;\n }\n\n MapleGameLogic::TryFillColorResult::T MapleGameLogic::TryFillColor()\n {\n BBAssert(cursor.X == cursorTail.X || cursor.Y == cursorTail.Y);\n\n \/\/ 'dic' is direction from 'cursorTail' to 'cursor'\n Point2 dic = cursor - cursorTail;\n\n TryFillColorResult::T result = TryFillColorResult::NonChanged;\n\n if(dic == Point2::Zero)\n {\n \/\/ Clicked 'O' button when Single cell selected,\n \/\/ remove 'X' marker at selected cell.\n\n if(solvePattern.arr[cursor.X][cursor.Y] == TableState::Uncolored)\n {\n if(ansPattern.arr[cursor.X][cursor.Y] == TableState::Uncolored)\n {\n \/\/ If not correct, check wrong anser\n\n solvePattern.arr[cursor.X][cursor.Y] = TableState::ForceErased;\n\n Incorrect();\n result = TryFillColorResult::Incorrect;\n }\n else\n {\n \/\/ Only fill colored when correct\n\n solvePattern.arr[cursor.X][cursor.Y] = TableState::Colored;\n result = TryFillColorResult::Correct;\n }\n }\n else if(solvePattern.arr[cursor.X][cursor.Y] == TableState::Erased)\n {\n \/\/ remove 'X' marker when it filled 'X'\n\n solvePattern.arr[cursor.X][cursor.Y] = TableState::Uncolored;\n\n result = TryFillColorResult::NonChanged;\n }\n }\n else\n {\n if(dic.X != 0)\n dic.X \/= Math::Abs(dic.X);\n else if(dic.Y != 0)\n dic.Y \/= Math::Abs(dic.Y);\n\n result = TryFillColorResult::Correct;\n\n for(Point2 currentPoint = cursorTail; currentPoint != (cursor + dic); currentPoint += dic)\n {\n if(solvePattern.arr[currentPoint.X][currentPoint.Y] == TableState::Uncolored)\n {\n \/\/ Only works when 'Uncolored'\n\n if(ansPattern.arr[currentPoint.X][currentPoint.Y] == TableState::Uncolored)\n {\n \/\/ If not correct, check wrong anser and stop filling\n\n solvePattern.arr[currentPoint.X][currentPoint.Y] = TableState::ForceErased;\n\n Incorrect();\n result = TryFillColorResult::Incorrect;\n break;\n }\n else\n {\n \/\/ Only fill colored when correct.\n\n solvePattern.arr[currentPoint.X][currentPoint.Y] = TableState::Colored;\n }\n }\n }\n\n cursorTail = cursor;\n }\n\n if(GetRestLife() < 0)\n {\n result = TryFillColorResult::GameOver;\n }\n else if(WinCheck())\n {\n result = TryFillColorResult::Clear;\n }\n \n return result;\n }\n\n void MapleGameLogic::TryFillErased()\n {\n BBAssert(cursor.X == cursorTail.X || cursor.Y == cursorTail.Y);\n\n \/\/ 'dic' is direction from 'cursorTail' to 'cursor'\n Point2 dic = cursor - cursorTail;\n\n if(dic.X != 0)\n dic.X \/= Math::Abs(dic.X);\n else if(dic.Y != 0)\n dic.Y \/= Math::Abs(dic.Y);\n else\n dic.Y = 1;\n\n bool eraseMode = true;\n\n if(solvePattern.arr[cursorTail.X][cursorTail.Y] == TableState::Erased || solvePattern.arr[cursorTail.X][cursorTail.Y] == TableState::ForceErased)\n {\n \/\/ If start point is marked 'X', operation will remove 'X'\n\n eraseMode = false;\n }\n\n for(Point2 currentPoint = cursorTail; currentPoint != (cursor + dic); currentPoint += dic)\n {\n if(eraseMode && solvePattern.arr[currentPoint.X][currentPoint.Y] == TableState::Uncolored)\n {\n \/\/ If start point is not 'X', and this is null block, then fill 'X'\n solvePattern.arr[currentPoint.X][currentPoint.Y] = TableState::Erased;\n }\n else if(!eraseMode && solvePattern.arr[currentPoint.X][currentPoint.Y] == TableState::Erased)\n {\n \/\/ If start point is 'X', and this is 'X' block, then remove 'X'\n solvePattern.arr[currentPoint.X][currentPoint.Y] = TableState::Uncolored;\n }\n }\n\n cursorTail = cursor;\n }\n\n std::vector<std::vector<int> > MapleGameLogic::GetHorizontalNumberCount() const\n {\n std::vector<std::vector<int> > pattern;\n\n \/\/ <TODO> If need to reduce 'Draw()' call speed, reduce calculate 'pattern' only first time.\n\n for(int i = 0; i < puzzleSize; i++)\n {\n std::vector<int> current;\n\n int j = puzzleSize - 1;\n int counter = 0;\n\n while(j >= 0)\n {\n if(ansPattern.arr[i][j] == TableState::Colored)\n counter++;\n else\n {\n if(counter > 0)\n {\n current.push_back(counter);\n counter = 0;\n }\n }\n\n j--;\n }\n\n if(counter > 0)\n current.push_back(counter);\n\n if(current.size() == 0)\n current.push_back(0);\n\n pattern.push_back(current);\n }\n\n return pattern;\n }\n\n std::vector<std::vector<int> > MapleGameLogic::GetVerticalNumberCount() const\n {\n std::vector<std::vector<int> > pattern;\n\n \/\/ <TODO> If need to reduce 'Draw()' call speed, reduce calculate 'pattern' only first time.\n\n for(int i = 0; i < puzzleSize; i++)\n {\n std::vector<int> current;\n\n int j = 0;\n int counter = 0;\n \n while(j < puzzleSize)\n {\n if(ansPattern.arr[j][i] == TableState::Colored)\n counter++;\n else\n {\n if(counter > 0)\n {\n current.push_back(counter);\n counter = 0;\n }\n }\n\n j++;\n }\n\n if(counter > 0)\n current.push_back(counter);\n\n if(current.size() == 0)\n current.push_back(0);\n\n pattern.push_back(current);\n }\n\n return pattern;\n }\n\n Point2 MapleGameLogic::GetCursor() const\n {\n return cursor;\n }\n\n void MapleGameLogic::SetCursor(const Bibim::Point2& value)\n {\n cursor.X = Math::Clamp(value.X, 0, puzzleSize - 1);\n cursor.Y = Math::Clamp(value.Y, 0, puzzleSize - 1);\n }\n\n Point2 MapleGameLogic::GetCursorTail() const\n {\n return cursorTail;\n }\n\n void MapleGameLogic::SetCursorTail(const Bibim::Point2& end)\n {\n Point2 clamped;\n clamped.X = Math::Clamp(end.X, 0, puzzleSize - 1);\n clamped.Y = Math::Clamp(end.Y, 0, puzzleSize - 1);\n\n cursorTail = clamped;\n cursor = clamped;\n }\n\n void MapleGameLogic::CursorMove(const Bibim::Point2& dPoint)\n {\n if(Math::Abs(dPoint.X) + Math::Abs(dPoint.Y) != 1)\n return;\n\n SetCursorTail(cursor + dPoint);\n }\n\n bool MapleGameLogic::WinCheck()\n {\n \/\/ Check for Win Game.\n\n bool result = true;\n\n for(int i = 0; i < puzzleSize; i++)\n {\n for(int j = 0; j < puzzleSize; j++)\n {\n if(ansPattern.arr[i][j] == TableState::Colored && solvePattern.arr[i][j] != TableState::Colored)\n {\n result = false;\n break;\n }\n }\n\n if(!result)\n break;\n }\n\n return result;\n }\n\n void MapleGameLogic::Incorrect()\n {\n \/\/ Just reduce life.\n\n restLife--;\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: PropertyHelper.cxx,v $\n *\n * $Revision: 1.4 $\n *\n * last change: $Author: vg $ $Date: 2007-05-22 19:03:24 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_chart2.hxx\"\n#include \"PropertyHelper.hxx\"\n#include \"ContainerHelper.hxx\"\n#include \"macros.hxx\"\n\n#ifndef _COM_SUN_STAR_BEANS_PROPERTYATTRIBUTE_HPP_\n#include <com\/sun\/star\/beans\/PropertyAttribute.hpp>\n#endif\n#ifndef _COM_SUN_STAR_CONTAINER_XNAMECONTAINER_HPP_\n#include <com\/sun\/star\/container\/XNameContainer.hpp>\n#endif\n\n#include <vector>\n#include <algorithm>\n#include <functional>\n\nusing namespace ::com::sun::star;\nusing namespace ::com::sun::star::beans;\nusing ::rtl::OUString;\nusing ::com::sun::star::uno::Any;\nusing ::com::sun::star::uno::Reference;\nusing ::com::sun::star::uno::Sequence;\n\nnamespace\n{\nstruct lcl_EqualsElement : public ::std::unary_function< OUString, bool >\n{\n explicit lcl_EqualsElement( const Any & rValue, const Reference< container::XNameAccess > & xAccess )\n : m_aValue( rValue ), m_xAccess( xAccess )\n {\n OSL_ASSERT( m_xAccess.is());\n }\n\n bool operator() ( const OUString & rName )\n {\n try\n {\n return (m_xAccess->getByName( rName ) == m_aValue);\n }\n catch( const uno::Exception & ex )\n {\n ASSERT_EXCEPTION( ex );\n }\n return false;\n }\n\nprivate:\n Any m_aValue;\n Reference< container::XNameAccess > m_xAccess;\n};\n\nstruct lcl_StringMatches : public ::std::unary_function< OUString ,bool >\n{\n lcl_StringMatches( const OUString & rCmpStr ) :\n m_aCmpStr( rCmpStr )\n {}\n\n bool operator() ( const OUString & rStr )\n {\n return rStr.match( m_aCmpStr );\n }\n\nprivate:\n OUString m_aCmpStr;\n};\n\nstruct lcl_OUStringRestToInt32 : public ::std::unary_function< OUString, sal_Int32 >\n{\n lcl_OUStringRestToInt32( sal_Int32 nPrefixLength ) :\n m_nPrefixLength( nPrefixLength )\n {}\n sal_Int32 operator() ( const OUString & rStr )\n {\n if( m_nPrefixLength > rStr.getLength() )\n return 0;\n return rStr.copy( m_nPrefixLength ).toInt32( 10 \/* radix *\/ );\n }\nprivate:\n sal_Int32 m_nPrefixLength;\n};\n\n\/** adds a fill gradient, fill hatch, fill bitmap, fill transparency gradient,\n line dash or line marker to the corresponding name container with a unique\n name.\n\n @param rPrefix\n The prefix used for automated name generation.\n\n @param rPreferredName\n If this string is not empty it is used as name if it is unique in the\n table. Otherwise a new name is generated using pPrefix.\n\n @return the new name under which the property was stored in the table\n*\/\nOUString lcl_addNamedPropertyUniqueNameToTable(\n const Any & rValue,\n const Reference< container::XNameContainer > & xNameContainer,\n const OUString & rPrefix,\n const OUString & rPreferredName )\n{\n if( ! xNameContainer.is() ||\n ! rValue.hasValue() ||\n ( rValue.getValueType() != xNameContainer->getElementType()))\n return rPreferredName;\n\n try\n {\n Reference< container::XNameAccess > xNameAccess( xNameContainer, uno::UNO_QUERY_THROW );\n ::std::vector< OUString > aNames( ::chart::ContainerHelper::SequenceToVector( xNameAccess->getElementNames()));\n ::std::vector< OUString >::const_iterator aIt(\n ::std::find_if( aNames.begin(), aNames.end(), lcl_EqualsElement( rValue, xNameAccess )));\n\n \/\/ element not found in container\n if( aIt == aNames.end())\n {\n OUString aUniqueName;\n\n \/\/ check if preferred name is already used\n if( rPreferredName.getLength())\n {\n aIt = ::std::find( aNames.begin(), aNames.end(), rPreferredName );\n if( aIt == aNames.end())\n aUniqueName = rPreferredName;\n }\n\n if( ! aUniqueName.getLength())\n {\n \/\/ create a unique id using the prefix plus a number\n ::std::vector< sal_Int32 > aNumbers;\n ::std::vector< OUString >::iterator aNonConstIt(\n ::std::partition( aNames.begin(), aNames.end(), lcl_StringMatches( rPrefix )));\n ::std::transform( aNames.begin(), aNonConstIt,\n back_inserter( aNumbers ),\n lcl_OUStringRestToInt32( rPrefix.getLength() ));\n ::std::vector< sal_Int32 >::const_iterator aMaxIt(\n ::std::max_element( aNumbers.begin(), aNumbers.end()));\n\n sal_Int32 nIndex = 1;\n if( aMaxIt != aNumbers.end())\n nIndex = (*aMaxIt) + 1;\n\n aUniqueName = rPrefix + OUString::valueOf( nIndex );\n }\n\n OSL_ASSERT( aUniqueName.getLength());\n xNameContainer->insertByName( aUniqueName, rValue );\n return aUniqueName;\n }\n else\n \/\/ element found => return name\n return *aIt;\n }\n catch( const uno::Exception & ex )\n {\n ASSERT_EXCEPTION( ex );\n }\n\n return rPreferredName;\n}\n\n} \/\/ anonymous namespace\n\nnamespace chart\n{\n\n\/\/ static\nvoid PropertyHelper::copyProperties(\n const Reference< XPropertySet > & xSource,\n const Reference< XPropertySet > & xDestination )\n{\n if( ! (xSource.is() && xDestination.is()))\n return;\n\n try\n {\n Reference< XPropertySetInfo > xSrcInfo( xSource->getPropertySetInfo(), uno::UNO_QUERY_THROW );\n Reference< XPropertySetInfo > xDestInfo( xDestination->getPropertySetInfo(), uno::UNO_QUERY_THROW );\n Sequence< Property > aProperties( xSrcInfo->getProperties());\n const sal_Int32 nLength = aProperties.getLength();\n for( sal_Int32 i = 0; i < nLength; ++i )\n {\n OUString aName( aProperties[i].Name);\n if( xDestInfo->hasPropertyByName( aName ))\n {\n Property aProp( xDestInfo->getPropertyByName( aName ));\n if( (aProp.Attributes & PropertyAttribute::READONLY) == 0 )\n xDestination->setPropertyValue(\n aName, xSource->getPropertyValue( aName ));\n }\n }\n }\n catch( const uno::Exception & ex )\n {\n ASSERT_EXCEPTION( ex );\n }\n}\n\n\/\/ static\nOUString PropertyHelper::addLineDashUniqueNameToTable(\n const Any & rValue,\n const Reference< lang::XMultiServiceFactory > & xFact,\n const OUString & rPreferredName )\n{\n if( xFact.is())\n {\n Reference< container::XNameContainer > xNameCnt(\n xFact->createInstance( C2U( \"com.sun.star.drawing.DashTable\" )),\n uno::UNO_QUERY );\n if( xNameCnt.is())\n return lcl_addNamedPropertyUniqueNameToTable(\n rValue, xNameCnt, C2U( \"ChartDash \" ), rPreferredName );\n }\n return OUString();\n}\n\n\/\/ static\nOUString PropertyHelper::addGradientUniqueNameToTable(\n const Any & rValue,\n const Reference< lang::XMultiServiceFactory > & xFact,\n const OUString & rPreferredName )\n{\n if( xFact.is())\n {\n Reference< container::XNameContainer > xNameCnt(\n xFact->createInstance( C2U( \"com.sun.star.drawing.GradientTable\" )),\n uno::UNO_QUERY );\n if( xNameCnt.is())\n return lcl_addNamedPropertyUniqueNameToTable(\n rValue, xNameCnt, C2U( \"ChartGradient \" ), rPreferredName );\n }\n return OUString();\n}\n\n\n\/\/ static\nOUString PropertyHelper::addTransparencyGradientUniqueNameToTable(\n const Any & rValue,\n const Reference< lang::XMultiServiceFactory > & xFact,\n const OUString & rPreferredName )\n{\n if( xFact.is())\n {\n Reference< container::XNameContainer > xNameCnt(\n xFact->createInstance( C2U( \"com.sun.star.drawing.TransparencyGradientTable\" )),\n uno::UNO_QUERY );\n if( xNameCnt.is())\n return lcl_addNamedPropertyUniqueNameToTable(\n rValue, xNameCnt, C2U( \"ChartTransparencyGradient \" ), rPreferredName );\n }\n return OUString();\n}\n\n\/\/ static\nOUString PropertyHelper::addHatchUniqueNameToTable(\n const Any & rValue,\n const Reference< lang::XMultiServiceFactory > & xFact,\n const OUString & rPreferredName )\n{\n if( xFact.is())\n {\n Reference< container::XNameContainer > xNameCnt(\n xFact->createInstance( C2U( \"com.sun.star.drawing.HatchTable\" )),\n uno::UNO_QUERY );\n if( xNameCnt.is())\n return lcl_addNamedPropertyUniqueNameToTable(\n rValue, xNameCnt, C2U( \"ChartHatch \" ), rPreferredName );\n }\n return OUString();\n}\n\n\/\/ static\nOUString PropertyHelper::addBitmapUniqueNameToTable(\n const Any & rValue,\n const Reference< lang::XMultiServiceFactory > & xFact,\n const OUString & rPreferredName )\n{\n if( xFact.is())\n {\n Reference< container::XNameContainer > xNameCnt(\n xFact->createInstance( C2U( \"com.sun.star.drawing.BitmapTable\" )),\n uno::UNO_QUERY );\n if( xNameCnt.is())\n return lcl_addNamedPropertyUniqueNameToTable(\n rValue, xNameCnt, C2U( \"ChartBitmap \" ), rPreferredName );\n }\n return OUString();\n}\n\n} \/\/ namespace chart\n<commit_msg>INTEGRATION: CWS chart11 (1.4.38); FILE MERGED 2007\/08\/24 08:27:25 bm 1.4.38.4: #i80084# define template specialization in cxx 2007\/08\/24 07:18:15 bm 1.4.38.3: #i80084# template spezialization needed 2007\/08\/03 12:57:35 bm 1.4.38.2: #i80084# using template specialization instead of a different function name 2007\/07\/31 12:56:46 bm 1.4.38.1: #i80084# avoid usage of map operator[] with enums as keys, simplify initialization of default property values<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: PropertyHelper.cxx,v $\n *\n * $Revision: 1.5 $\n *\n * last change: $Author: vg $ $Date: 2007-09-18 15:09:42 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_chart2.hxx\"\n#include \"PropertyHelper.hxx\"\n#include \"ContainerHelper.hxx\"\n#include \"macros.hxx\"\n\n#ifndef _COM_SUN_STAR_BEANS_PROPERTYATTRIBUTE_HPP_\n#include <com\/sun\/star\/beans\/PropertyAttribute.hpp>\n#endif\n#ifndef _COM_SUN_STAR_CONTAINER_XNAMECONTAINER_HPP_\n#include <com\/sun\/star\/container\/XNameContainer.hpp>\n#endif\n\n#include <vector>\n#include <algorithm>\n#include <functional>\n\nusing namespace ::com::sun::star;\nusing namespace ::com::sun::star::beans;\nusing ::rtl::OUString;\nusing ::com::sun::star::uno::Any;\nusing ::com::sun::star::uno::Reference;\nusing ::com::sun::star::uno::Sequence;\n\nnamespace\n{\nstruct lcl_EqualsElement : public ::std::unary_function< OUString, bool >\n{\n explicit lcl_EqualsElement( const Any & rValue, const Reference< container::XNameAccess > & xAccess )\n : m_aValue( rValue ), m_xAccess( xAccess )\n {\n OSL_ASSERT( m_xAccess.is());\n }\n\n bool operator() ( const OUString & rName )\n {\n try\n {\n return (m_xAccess->getByName( rName ) == m_aValue);\n }\n catch( const uno::Exception & ex )\n {\n ASSERT_EXCEPTION( ex );\n }\n return false;\n }\n\nprivate:\n Any m_aValue;\n Reference< container::XNameAccess > m_xAccess;\n};\n\nstruct lcl_StringMatches : public ::std::unary_function< OUString ,bool >\n{\n lcl_StringMatches( const OUString & rCmpStr ) :\n m_aCmpStr( rCmpStr )\n {}\n\n bool operator() ( const OUString & rStr )\n {\n return rStr.match( m_aCmpStr );\n }\n\nprivate:\n OUString m_aCmpStr;\n};\n\nstruct lcl_OUStringRestToInt32 : public ::std::unary_function< OUString, sal_Int32 >\n{\n lcl_OUStringRestToInt32( sal_Int32 nPrefixLength ) :\n m_nPrefixLength( nPrefixLength )\n {}\n sal_Int32 operator() ( const OUString & rStr )\n {\n if( m_nPrefixLength > rStr.getLength() )\n return 0;\n return rStr.copy( m_nPrefixLength ).toInt32( 10 \/* radix *\/ );\n }\nprivate:\n sal_Int32 m_nPrefixLength;\n};\n\n\/** adds a fill gradient, fill hatch, fill bitmap, fill transparency gradient,\n line dash or line marker to the corresponding name container with a unique\n name.\n\n @param rPrefix\n The prefix used for automated name generation.\n\n @param rPreferredName\n If this string is not empty it is used as name if it is unique in the\n table. Otherwise a new name is generated using pPrefix.\n\n @return the new name under which the property was stored in the table\n*\/\nOUString lcl_addNamedPropertyUniqueNameToTable(\n const Any & rValue,\n const Reference< container::XNameContainer > & xNameContainer,\n const OUString & rPrefix,\n const OUString & rPreferredName )\n{\n if( ! xNameContainer.is() ||\n ! rValue.hasValue() ||\n ( rValue.getValueType() != xNameContainer->getElementType()))\n return rPreferredName;\n\n try\n {\n Reference< container::XNameAccess > xNameAccess( xNameContainer, uno::UNO_QUERY_THROW );\n ::std::vector< OUString > aNames( ::chart::ContainerHelper::SequenceToVector( xNameAccess->getElementNames()));\n ::std::vector< OUString >::const_iterator aIt(\n ::std::find_if( aNames.begin(), aNames.end(), lcl_EqualsElement( rValue, xNameAccess )));\n\n \/\/ element not found in container\n if( aIt == aNames.end())\n {\n OUString aUniqueName;\n\n \/\/ check if preferred name is already used\n if( rPreferredName.getLength())\n {\n aIt = ::std::find( aNames.begin(), aNames.end(), rPreferredName );\n if( aIt == aNames.end())\n aUniqueName = rPreferredName;\n }\n\n if( ! aUniqueName.getLength())\n {\n \/\/ create a unique id using the prefix plus a number\n ::std::vector< sal_Int32 > aNumbers;\n ::std::vector< OUString >::iterator aNonConstIt(\n ::std::partition( aNames.begin(), aNames.end(), lcl_StringMatches( rPrefix )));\n ::std::transform( aNames.begin(), aNonConstIt,\n back_inserter( aNumbers ),\n lcl_OUStringRestToInt32( rPrefix.getLength() ));\n ::std::vector< sal_Int32 >::const_iterator aMaxIt(\n ::std::max_element( aNumbers.begin(), aNumbers.end()));\n\n sal_Int32 nIndex = 1;\n if( aMaxIt != aNumbers.end())\n nIndex = (*aMaxIt) + 1;\n\n aUniqueName = rPrefix + OUString::valueOf( nIndex );\n }\n\n OSL_ASSERT( aUniqueName.getLength());\n xNameContainer->insertByName( aUniqueName, rValue );\n return aUniqueName;\n }\n else\n \/\/ element found => return name\n return *aIt;\n }\n catch( const uno::Exception & ex )\n {\n ASSERT_EXCEPTION( ex );\n }\n\n return rPreferredName;\n}\n\n} \/\/ anonymous namespace\n\nnamespace chart\n{\nnamespace PropertyHelper\n{\n\nvoid copyProperties(\n const Reference< XPropertySet > & xSource,\n const Reference< XPropertySet > & xDestination )\n{\n if( ! (xSource.is() && xDestination.is()))\n return;\n\n try\n {\n Reference< XPropertySetInfo > xSrcInfo( xSource->getPropertySetInfo(), uno::UNO_QUERY_THROW );\n Reference< XPropertySetInfo > xDestInfo( xDestination->getPropertySetInfo(), uno::UNO_QUERY_THROW );\n Sequence< Property > aProperties( xSrcInfo->getProperties());\n const sal_Int32 nLength = aProperties.getLength();\n for( sal_Int32 i = 0; i < nLength; ++i )\n {\n OUString aName( aProperties[i].Name);\n if( xDestInfo->hasPropertyByName( aName ))\n {\n Property aProp( xDestInfo->getPropertyByName( aName ));\n if( (aProp.Attributes & PropertyAttribute::READONLY) == 0 )\n xDestination->setPropertyValue(\n aName, xSource->getPropertyValue( aName ));\n }\n }\n }\n catch( const uno::Exception & ex )\n {\n ASSERT_EXCEPTION( ex );\n }\n}\n\nOUString addLineDashUniqueNameToTable(\n const Any & rValue,\n const Reference< lang::XMultiServiceFactory > & xFact,\n const OUString & rPreferredName )\n{\n if( xFact.is())\n {\n Reference< container::XNameContainer > xNameCnt(\n xFact->createInstance( C2U( \"com.sun.star.drawing.DashTable\" )),\n uno::UNO_QUERY );\n if( xNameCnt.is())\n return lcl_addNamedPropertyUniqueNameToTable(\n rValue, xNameCnt, C2U( \"ChartDash \" ), rPreferredName );\n }\n return OUString();\n}\n\nOUString addGradientUniqueNameToTable(\n const Any & rValue,\n const Reference< lang::XMultiServiceFactory > & xFact,\n const OUString & rPreferredName )\n{\n if( xFact.is())\n {\n Reference< container::XNameContainer > xNameCnt(\n xFact->createInstance( C2U( \"com.sun.star.drawing.GradientTable\" )),\n uno::UNO_QUERY );\n if( xNameCnt.is())\n return lcl_addNamedPropertyUniqueNameToTable(\n rValue, xNameCnt, C2U( \"ChartGradient \" ), rPreferredName );\n }\n return OUString();\n}\n\n\nOUString addTransparencyGradientUniqueNameToTable(\n const Any & rValue,\n const Reference< lang::XMultiServiceFactory > & xFact,\n const OUString & rPreferredName )\n{\n if( xFact.is())\n {\n Reference< container::XNameContainer > xNameCnt(\n xFact->createInstance( C2U( \"com.sun.star.drawing.TransparencyGradientTable\" )),\n uno::UNO_QUERY );\n if( xNameCnt.is())\n return lcl_addNamedPropertyUniqueNameToTable(\n rValue, xNameCnt, C2U( \"ChartTransparencyGradient \" ), rPreferredName );\n }\n return OUString();\n}\n\nOUString addHatchUniqueNameToTable(\n const Any & rValue,\n const Reference< lang::XMultiServiceFactory > & xFact,\n const OUString & rPreferredName )\n{\n if( xFact.is())\n {\n Reference< container::XNameContainer > xNameCnt(\n xFact->createInstance( C2U( \"com.sun.star.drawing.HatchTable\" )),\n uno::UNO_QUERY );\n if( xNameCnt.is())\n return lcl_addNamedPropertyUniqueNameToTable(\n rValue, xNameCnt, C2U( \"ChartHatch \" ), rPreferredName );\n }\n return OUString();\n}\n\nOUString addBitmapUniqueNameToTable(\n const Any & rValue,\n const Reference< lang::XMultiServiceFactory > & xFact,\n const OUString & rPreferredName )\n{\n if( xFact.is())\n {\n Reference< container::XNameContainer > xNameCnt(\n xFact->createInstance( C2U( \"com.sun.star.drawing.BitmapTable\" )),\n uno::UNO_QUERY );\n if( xNameCnt.is())\n return lcl_addNamedPropertyUniqueNameToTable(\n rValue, xNameCnt, C2U( \"ChartBitmap \" ), rPreferredName );\n }\n return OUString();\n}\n\n\/\/ ----------------------------------------\n\nvoid setPropertyValueAny( tPropertyValueMap & rOutMap, tPropertyValueMapKey key, const uno::Any & rAny )\n{\n tPropertyValueMap::iterator aIt( rOutMap.find( key ));\n if( aIt == rOutMap.end())\n rOutMap.insert( tPropertyValueMap::value_type( key, rAny ));\n else\n (*aIt).second = rAny;\n}\n\ntemplate<>\n void setPropertyValue< ::com::sun::star::uno::Any >( tPropertyValueMap & rOutMap, tPropertyValueMapKey key, const ::com::sun::star::uno::Any & rAny )\n{\n setPropertyValueAny( rOutMap, key, rAny );\n}\n\nvoid setPropertyValueDefaultAny( tPropertyValueMap & rOutMap, tPropertyValueMapKey key, const uno::Any & rAny )\n{\n OSL_ENSURE( rOutMap.end() == rOutMap.find( key ), \"Default already exists for property\" );\n setPropertyValue( rOutMap, key, rAny );\n}\n\ntemplate<>\n void setPropertyValueDefault< ::com::sun::star::uno::Any >( tPropertyValueMap & rOutMap, tPropertyValueMapKey key, const ::com::sun::star::uno::Any & rAny )\n{\n setPropertyValueDefaultAny( rOutMap, key, rAny );\n}\n\n\nvoid setEmptyPropertyValueDefault( tPropertyValueMap & rOutMap, tPropertyValueMapKey key )\n{\n setPropertyValueDefault( rOutMap, key, uno::Any());\n}\n\n} \/\/ namespace PropertyHelper\n\n} \/\/ namespace chart\n<|endoftext|>"} {"text":"<commit_before>\/*\n * This program is free software; you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or\n * (at your option) any later version.\n *\n * Written (W) 2013 Soumyajit De\n *\/\n\n#include <shogun\/lib\/common.h>\n#include <shogun\/lib\/SGVector.h>\n#include <shogun\/lib\/SGMatrix.h>\n#include <shogun\/mathematics\/Statistics.h>\n#include <shogun\/mathematics\/eigen3.h>\n#include <shogun\/mathematics\/linalg\/ratapprox\/tracesampler\/NormalSampler.h>\n#include <gtest\/gtest.h>\n\nusing namespace shogun;\nusing namespace Eigen;\n\n#ifdef HAVE_LAPACK\nTEST(NormalSampler, sample)\n{\n\tconst index_t dimension=2;\n\tconst index_t num_samples=5000;\n\tSGMatrix<float64_t> samples(num_samples, dimension);\n\n\tCNormalSampler sampler(dimension);\n\tsampler.precompute();\n\tfor (index_t i=0; i<num_samples; ++i)\n\t{\n\t\tSGVector<float64_t> s=sampler.sample(0);\n\t\tfor (index_t j=0; j<dimension; ++j)\n\t\t\tsamples(i,j)=s[j];\n\t}\n\n\tSGVector<float64_t> mean=CStatistics::matrix_mean(samples);\n\tMap<VectorXd> map_mean(mean.vector, mean.vlen);\n\tEXPECT_NEAR((map_mean-VectorXd::Zero(dimension)).norm(), 0.0, 0.1);\n\n\tSGMatrix<float64_t> cov=CStatistics::covariance_matrix(samples);\n\tMap<MatrixXd> map_cov(cov.matrix, cov.num_rows, cov.num_cols);\n\tEXPECT_NEAR((map_cov-MatrixXd::Identity(dimension, dimension)).norm(),\n\t\t0.0, 0.1);\n}\n#endif \/\/ HAVE_LAPACK\n\n\n<commit_msg>fix another covariance matrix unit test<commit_after>\/*\n * This program is free software; you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or\n * (at your option) any later version.\n *\n * Written (W) 2013 Soumyajit De\n *\/\n\n#include <shogun\/lib\/common.h>\n#include <shogun\/lib\/SGVector.h>\n#include <shogun\/lib\/SGMatrix.h>\n#include <shogun\/mathematics\/Statistics.h>\n#include <shogun\/mathematics\/eigen3.h>\n#include <shogun\/mathematics\/linalg\/ratapprox\/tracesampler\/NormalSampler.h>\n#include <gtest\/gtest.h>\n\nusing namespace shogun;\nusing namespace Eigen;\n\nTEST(NormalSampler, sample)\n{\n\tconst index_t dimension=2;\n\tconst index_t num_samples=5000;\n\tSGMatrix<float64_t> samples(num_samples, dimension);\n\n\tCNormalSampler sampler(dimension);\n\tsampler.precompute();\n\tfor (index_t i=0; i<num_samples; ++i)\n\t{\n\t\tSGVector<float64_t> s=sampler.sample(0);\n\t\tfor (index_t j=0; j<dimension; ++j)\n\t\t\tsamples(i,j)=s[j];\n\t}\n\n\tSGVector<float64_t> mean=CStatistics::matrix_mean(samples);\n\tMap<VectorXd> map_mean(mean.vector, mean.vlen);\n\tEXPECT_NEAR((map_mean-VectorXd::Zero(dimension)).norm(), 0.0, 0.1);\n\tSGMatrix<float64_t>::transpose_matrix(samples.matrix, samples.num_rows, samples.num_cols); \/\/ TODO: refactor sample_from_gaussian to return column vectors!\n\tSGMatrix<float64_t> cov=CStatistics::covariance_matrix(samples);\n\tMap<MatrixXd> map_cov(cov.matrix, cov.num_rows, cov.num_cols);\n\tEXPECT_NEAR((map_cov-MatrixXd::Identity(dimension, dimension)).norm(),\n\t\t0.0, 0.1);\n}\n\n\n<|endoftext|>"} {"text":"<commit_before>\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ PelotonDB\n\/\/\n\/\/ materialization_test.cpp\n\/\/\n\/\/ Identification: tests\/executor\/materialization_test.cpp\n\/\/\n\/\/ Copyright (c) 2015, Carnegie Mellon University Database Group\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include <memory>\n#include <string>\n#include <unordered_map>\n#include <vector>\n#include <chrono>\n#include <iostream>\n#include <ctime>\n\n#include \"gmock\/gmock.h\"\n#include \"gtest\/gtest.h\"\n\n#include \"backend\/planner\/abstract_plan.h\"\n#include \"backend\/planner\/materialization_plan.h\"\n#include \"backend\/planner\/seq_scan_plan.h\"\n\n#include \"backend\/catalog\/manager.h\"\n#include \"backend\/catalog\/schema.h\"\n#include \"backend\/common\/types.h\"\n#include \"backend\/common\/value.h\"\n#include \"backend\/common\/value_factory.h\"\n#include \"backend\/executor\/logical_tile.h\"\n#include \"backend\/executor\/logical_tile_factory.h\"\n#include \"backend\/executor\/materialization_executor.h\"\n#include \"backend\/storage\/backend_vm.h\"\n#include \"backend\/storage\/tile.h\"\n#include \"backend\/storage\/tile_group.h\"\n#include \"backend\/storage\/data_table.h\"\n#include \"backend\/concurrency\/transaction.h\"\n#include \"backend\/executor\/abstract_executor.h\"\n#include \"backend\/executor\/seq_scan_executor.h\"\n#include \"backend\/expression\/abstract_expression.h\"\n#include \"backend\/expression\/expression_util.h\"\n#include \"backend\/storage\/table_factory.h\"\n#include \"backend\/index\/index_factory.h\"\n\n#include \"executor\/executor_tests_util.h\"\n#include \"executor\/mock_executor.h\"\n\nusing ::testing::NotNull;\n\nnamespace peloton {\nnamespace test {\n\n\/\/===--------------------------------------------------------------------===\/\/\n\/\/ Tile Group Layout Tests\n\/\/===--------------------------------------------------------------------===\/\/\n\nvoid RunTest() {\n std::chrono::time_point<std::chrono::system_clock> start, end;\n\n const int tuples_per_tilegroup_count = 10;\n const int tile_group_count = 5;\n const int tuple_count = tuples_per_tilegroup_count * tile_group_count;\n const oid_t col_count = 250;\n const bool is_inlined = true;\n const bool indexes = false;\n\n std::vector<catalog::Column> columns;\n\n for(oid_t col_itr = 0 ; col_itr <= col_count; col_itr++) {\n auto column =\n catalog::Column(VALUE_TYPE_INTEGER, GetTypeSize(VALUE_TYPE_INTEGER),\n \"FIELD\" + std::to_string(col_itr), is_inlined);\n\n columns.push_back(column);\n }\n\n\n catalog::Schema *table_schema = new catalog::Schema(columns);\n std::string table_name(\"TEST_TABLE\");\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ Create table.\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n bool own_schema = true;\n bool adapt_table = true;\n std::unique_ptr<storage::DataTable> table(storage::TableFactory::GetDataTable(\n INVALID_OID, INVALID_OID, table_schema, table_name,\n tuples_per_tilegroup_count,\n own_schema, adapt_table));\n\n \/\/ PRIMARY INDEX\n if (indexes == true) {\n std::vector<oid_t> key_attrs;\n\n auto tuple_schema = table->GetSchema();\n catalog::Schema *key_schema;\n index::IndexMetadata *index_metadata;\n bool unique;\n\n key_attrs = {0};\n key_schema = catalog::Schema::CopySchema(tuple_schema, key_attrs);\n key_schema->SetIndexedColumns(key_attrs);\n\n unique = true;\n\n index_metadata = new index::IndexMetadata(\n \"primary_index\", 123, INDEX_TYPE_BTREE,\n INDEX_CONSTRAINT_TYPE_PRIMARY_KEY, tuple_schema, key_schema, unique);\n\n index::Index *pkey_index = index::IndexFactory::GetInstance(index_metadata);\n table->AddIndex(pkey_index);\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ Load in the data\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n \/\/ Insert tuples into tile_group.\n auto &txn_manager = concurrency::TransactionManager::GetInstance();\n const bool allocate = true;\n auto txn = txn_manager.BeginTransaction();\n\n for (int rowid = 0; rowid < tuple_count; rowid++) {\n int populate_value = rowid;\n\n storage::Tuple tuple(table_schema, allocate);\n\n for(oid_t col_itr = 0 ; col_itr <= col_count; col_itr++) {\n auto value = ValueFactory::GetIntegerValue(populate_value + col_itr);\n tuple.SetValue(col_itr, value);\n }\n\n ItemPointer tuple_slot_id = table->InsertTuple(txn, &tuple);\n EXPECT_TRUE(tuple_slot_id.block != INVALID_OID);\n EXPECT_TRUE(tuple_slot_id.offset != INVALID_OID);\n txn->RecordInsert(tuple_slot_id);\n }\n\n txn_manager.CommitTransaction(txn);\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ Do a seq scan with predicate on top of the table\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n start = std::chrono::system_clock::now();\n\n txn = txn_manager.BeginTransaction();\n std::unique_ptr<executor::ExecutorContext> context(\n new executor::ExecutorContext(txn));\n\n \/\/ Column ids to be added to logical tile after scan.\n \/\/std::vector<oid_t> column_ids;\n \/\/for(oid_t col_itr = 0 ; col_itr <= 200; col_itr++) {\n \/\/ column_ids.push_back(col_itr);\n \/\/}\n std::vector<oid_t> column_ids({198, 206});\n\n \/\/ Create and set up seq scan executor\n planner::SeqScanPlan seq_scan_node(table.get(), nullptr, column_ids);\n int expected_num_tiles = tile_group_count;\n\n executor::SeqScanExecutor seq_scan_executor(&seq_scan_node, context.get());\n\n \/\/ Create and set up materialization executor\n std::vector<catalog::Column> output_columns;\n std::unordered_map<oid_t, oid_t> old_to_new_cols;\n oid_t col_itr = 0;\n for(auto column_id : column_ids) {\n auto column =\n catalog::Column(VALUE_TYPE_INTEGER, GetTypeSize(VALUE_TYPE_INTEGER),\n \"FIELD\" + std::to_string(column_id), is_inlined);\n output_columns.push_back(column);\n\n old_to_new_cols[col_itr] = col_itr;\n col_itr++;\n }\n\n std::unique_ptr<catalog::Schema> output_schema(\n new catalog::Schema(output_columns));\n bool physify_flag = true; \/\/ is going to create a physical tile\n planner::MaterializationPlan mat_node(old_to_new_cols, output_schema.release(),\n physify_flag);\n\n executor::MaterializationExecutor mat_executor(&mat_node, nullptr);\n mat_executor.AddChild(&seq_scan_executor);\n\n EXPECT_TRUE(mat_executor.Init());\n\n std::vector<std::unique_ptr<executor::LogicalTile>> result_tiles;\n for (int i = 0; i < expected_num_tiles; i++) {\n EXPECT_TRUE(mat_executor.Execute());\n std::unique_ptr<executor::LogicalTile> result_tile(mat_executor.GetOutput());\n EXPECT_THAT(result_tile, NotNull());\n result_tiles.emplace_back(result_tile.release());\n }\n\n EXPECT_FALSE(mat_executor.Execute());\n\n txn_manager.CommitTransaction(txn);\n\n end = std::chrono::system_clock::now();\n std::chrono::duration<double> elapsed_seconds = end-start;\n\n std::cout << \"duration :: \" << elapsed_seconds.count() << \"s\\n\";\n}\n\nTEST(TileGroupLayoutTest, RowLayout) {\n peloton_layout = LAYOUT_ROW;\n RunTest();\n}\n\nTEST(TileGroupLayoutTest, ColumnLayout) {\n peloton_layout = LAYOUT_COLUMN;\n RunTest();\n}\n\nTEST(TileGroupLayoutTest, HybridLayout) {\n peloton_layout = LAYOUT_HYBRID;\n RunTest();\n}\n\n} \/\/ namespace test\n} \/\/ namespace peloton\n<commit_msg>Fix tile group layout test<commit_after>\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ PelotonDB\n\/\/\n\/\/ materialization_test.cpp\n\/\/\n\/\/ Identification: tests\/executor\/materialization_test.cpp\n\/\/\n\/\/ Copyright (c) 2015, Carnegie Mellon University Database Group\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include <memory>\n#include <string>\n#include <unordered_map>\n#include <vector>\n#include <chrono>\n#include <iostream>\n#include <ctime>\n\n#include \"gmock\/gmock.h\"\n#include \"gtest\/gtest.h\"\n\n#include \"backend\/planner\/abstract_plan.h\"\n#include \"backend\/planner\/materialization_plan.h\"\n#include \"backend\/planner\/seq_scan_plan.h\"\n\n#include \"backend\/catalog\/manager.h\"\n#include \"backend\/catalog\/schema.h\"\n#include \"backend\/common\/types.h\"\n#include \"backend\/common\/value.h\"\n#include \"backend\/common\/value_factory.h\"\n#include \"backend\/executor\/logical_tile.h\"\n#include \"backend\/executor\/logical_tile_factory.h\"\n#include \"backend\/executor\/materialization_executor.h\"\n#include \"backend\/storage\/backend_vm.h\"\n#include \"backend\/storage\/tile.h\"\n#include \"backend\/storage\/tile_group.h\"\n#include \"backend\/storage\/data_table.h\"\n#include \"backend\/concurrency\/transaction.h\"\n#include \"backend\/executor\/abstract_executor.h\"\n#include \"backend\/executor\/seq_scan_executor.h\"\n#include \"backend\/expression\/abstract_expression.h\"\n#include \"backend\/expression\/expression_util.h\"\n#include \"backend\/storage\/table_factory.h\"\n#include \"backend\/index\/index_factory.h\"\n\n#include \"executor\/executor_tests_util.h\"\n#include \"executor\/mock_executor.h\"\n\nusing ::testing::NotNull;\n\nnamespace peloton {\nnamespace test {\n\n\/\/===--------------------------------------------------------------------===\/\/\n\/\/ Tile Group Layout Tests\n\/\/===--------------------------------------------------------------------===\/\/\n\nvoid RunTest() {\n std::chrono::time_point<std::chrono::system_clock> start, end;\n\n const int tuples_per_tilegroup_count = 10;\n const int tile_group_count = 5;\n const int tuple_count = tuples_per_tilegroup_count * tile_group_count;\n const oid_t col_count = 250;\n const bool is_inlined = true;\n const bool indexes = false;\n\n std::vector<catalog::Column> columns;\n\n for(oid_t col_itr = 0 ; col_itr <= col_count; col_itr++) {\n auto column =\n catalog::Column(VALUE_TYPE_INTEGER, GetTypeSize(VALUE_TYPE_INTEGER),\n \"FIELD\" + std::to_string(col_itr), is_inlined);\n\n columns.push_back(column);\n }\n\n\n catalog::Schema *table_schema = new catalog::Schema(columns);\n std::string table_name(\"TEST_TABLE\");\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ Create table.\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n bool own_schema = true;\n bool adapt_table = true;\n std::unique_ptr<storage::DataTable> table(storage::TableFactory::GetDataTable(\n INVALID_OID, INVALID_OID, table_schema, table_name,\n tuples_per_tilegroup_count,\n own_schema, adapt_table));\n\n \/\/ PRIMARY INDEX\n if (indexes == true) {\n std::vector<oid_t> key_attrs;\n\n auto tuple_schema = table->GetSchema();\n catalog::Schema *key_schema;\n index::IndexMetadata *index_metadata;\n bool unique;\n\n key_attrs = {0};\n key_schema = catalog::Schema::CopySchema(tuple_schema, key_attrs);\n key_schema->SetIndexedColumns(key_attrs);\n\n unique = true;\n\n index_metadata = new index::IndexMetadata(\n \"primary_index\", 123, INDEX_TYPE_BTREE,\n INDEX_CONSTRAINT_TYPE_PRIMARY_KEY, tuple_schema, key_schema, unique);\n\n index::Index *pkey_index = index::IndexFactory::GetInstance(index_metadata);\n table->AddIndex(pkey_index);\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ Load in the data\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n \/\/ Insert tuples into tile_group.\n auto &txn_manager = concurrency::TransactionManager::GetInstance();\n const bool allocate = true;\n auto txn = txn_manager.BeginTransaction();\n\n for (int rowid = 0; rowid < tuple_count; rowid++) {\n int populate_value = rowid;\n\n storage::Tuple tuple(table_schema, allocate);\n\n for(oid_t col_itr = 0 ; col_itr <= col_count; col_itr++) {\n auto value = ValueFactory::GetIntegerValue(populate_value + col_itr);\n tuple.SetValue(col_itr, value);\n }\n\n ItemPointer tuple_slot_id = table->InsertTuple(txn, &tuple);\n EXPECT_TRUE(tuple_slot_id.block != INVALID_OID);\n EXPECT_TRUE(tuple_slot_id.offset != INVALID_OID);\n txn->RecordInsert(tuple_slot_id);\n }\n\n txn_manager.CommitTransaction(txn);\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ Do a seq scan with predicate on top of the table\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n start = std::chrono::system_clock::now();\n\n txn = txn_manager.BeginTransaction();\n std::unique_ptr<executor::ExecutorContext> context(\n new executor::ExecutorContext(txn));\n\n \/\/ Column ids to be added to logical tile after scan.\n \/\/std::vector<oid_t> column_ids;\n \/\/for(oid_t col_itr = 0 ; col_itr <= 200; col_itr++) {\n \/\/ column_ids.push_back(col_itr);\n \/\/}\n std::vector<oid_t> column_ids({198, 206});\n\n \/\/ Create and set up seq scan executor\n planner::SeqScanPlan seq_scan_node(table.get(), nullptr, column_ids);\n int expected_num_tiles = tile_group_count;\n\n executor::SeqScanExecutor seq_scan_executor(&seq_scan_node, context.get());\n\n \/\/ Create and set up materialization executor\n std::vector<catalog::Column> output_columns;\n std::unordered_map<oid_t, oid_t> old_to_new_cols;\n oid_t col_itr = 0;\n for(auto column_id : column_ids) {\n auto column =\n catalog::Column(VALUE_TYPE_INTEGER, GetTypeSize(VALUE_TYPE_INTEGER),\n \"FIELD\" + std::to_string(column_id), is_inlined);\n output_columns.push_back(column);\n\n old_to_new_cols[col_itr] = col_itr;\n col_itr++;\n }\n\n std::unique_ptr<catalog::Schema> output_schema(\n new catalog::Schema(output_columns));\n bool physify_flag = true; \/\/ is going to create a physical tile\n planner::MaterializationPlan mat_node(old_to_new_cols, output_schema.release(),\n physify_flag);\n\n executor::MaterializationExecutor mat_executor(&mat_node, nullptr);\n mat_executor.AddChild(&seq_scan_executor);\n\n EXPECT_TRUE(mat_executor.Init());\n\n std::vector<std::unique_ptr<executor::LogicalTile>> result_tiles;\n for (int i = 0; i < expected_num_tiles; i++) {\n EXPECT_TRUE(mat_executor.Execute());\n std::unique_ptr<executor::LogicalTile> result_tile(mat_executor.GetOutput());\n EXPECT_THAT(result_tile, NotNull());\n result_tiles.emplace_back(result_tile.release());\n }\n\n EXPECT_FALSE(mat_executor.Execute());\n\n txn_manager.CommitTransaction(txn);\n\n end = std::chrono::system_clock::now();\n std::chrono::duration<double> elapsed_seconds = end-start;\n\n std::cout << \"duration :: \" << elapsed_seconds.count() << \"s\\n\";\n}\n\nTEST(TileGroupLayoutTest, RowLayout) {\n peloton_layout = LAYOUT_ROW;\n RunTest();\n}\n\nTEST(TileGroupLayoutTest, ColumnLayout) {\n peloton_layout = LAYOUT_COLUMN;\n RunTest();\n}\n\n} \/\/ namespace test\n} \/\/ namespace peloton\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ Copyright (c) 2012 The ANGLE Project Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\/\/\n\n#include \"PreprocessorTest.h\"\n#include \"Token.h\"\n\nclass VersionTest : public PreprocessorTest\n{\n protected:\n void lex()\n {\n pp::Token token;\n mPreprocessor.lex(&token);\n EXPECT_EQ(pp::Token::LAST, token.type);\n EXPECT_EQ(\"\", token.value);\n }\n};\n\nTEST_F(VersionTest, Valid)\n{\n const char* str = \"#version 200\\n\";\n ASSERT_TRUE(mPreprocessor.init(1, &str, NULL));\n\n using testing::_;\n EXPECT_CALL(mDirectiveHandler,\n handleVersion(pp::SourceLocation(0, 1), 200));\n \/\/ No error or warning.\n EXPECT_CALL(mDiagnostics, print(_, _, _)).Times(0);\n\n lex();\n}\n\nTEST_F(VersionTest, CommentsIgnored)\n{\n const char* str = \"\/*foo*\/\"\n \"#\"\n \"\/*foo*\/\"\n \"version\"\n \"\/*foo*\/\"\n \"200\"\n \"\/*foo*\/\"\n \"\/\/foo\"\n \"\\n\";\n ASSERT_TRUE(mPreprocessor.init(1, &str, NULL));\n\n using testing::_;\n EXPECT_CALL(mDirectiveHandler,\n handleVersion(pp::SourceLocation(0, 1), 200));\n \/\/ No error or warning.\n EXPECT_CALL(mDiagnostics, print(_, _, _)).Times(0);\n\n lex();\n}\n\nTEST_F(VersionTest, MissingNewline)\n{\n const char* str = \"#version 200\";\n ASSERT_TRUE(mPreprocessor.init(1, &str, NULL));\n\n using testing::_;\n \/\/ Directive successfully parsed.\n EXPECT_CALL(mDirectiveHandler,\n handleVersion(pp::SourceLocation(0, 1), 200));\n \/\/ Error reported about EOF.\n EXPECT_CALL(mDiagnostics, print(pp::Diagnostics::EOF_IN_DIRECTIVE, _, _));\n\n lex();\n}\n\nstruct VersionTestParam\n{\n const char* str;\n pp::Diagnostics::ID id;\n};\n\nclass InvalidVersionTest : public VersionTest,\n public testing::WithParamInterface<VersionTestParam>\n{\n};\n\nTEST_P(InvalidVersionTest, Identified)\n{\n VersionTestParam param = GetParam();\n ASSERT_TRUE(mPreprocessor.init(1, ¶m.str, NULL));\n\n using testing::_;\n \/\/ No handleVersion call.\n EXPECT_CALL(mDirectiveHandler, handleVersion(_, _)).Times(0);\n \/\/ Invalid version directive call.\n EXPECT_CALL(mDiagnostics, print(param.id, pp::SourceLocation(0, 1), _));\n\n lex();\n}\n\nstatic const VersionTestParam kParams[] = {\n {\"#version\\n\", pp::Diagnostics::INVALID_VERSION_DIRECTIVE},\n {\"#version foo\\n\", pp::Diagnostics::INVALID_VERSION_NUMBER},\n {\"#version 100 foo\\n\", pp::Diagnostics::UNEXPECTED_TOKEN}\n};\n\nINSTANTIATE_TEST_CASE_P(All, InvalidVersionTest, testing::ValuesIn(kParams));\n<commit_msg>Updated VersionTest to use the same pattern as other tests.<commit_after>\/\/\n\/\/ Copyright (c) 2012 The ANGLE Project Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\/\/\n\n#include \"PreprocessorTest.h\"\n#include \"Token.h\"\n\nclass VersionTest : public PreprocessorTest\n{\n protected:\n void preprocess(const char* str)\n {\n ASSERT_TRUE(mPreprocessor.init(1, &str, NULL));\n\n pp::Token token;\n mPreprocessor.lex(&token);\n EXPECT_EQ(pp::Token::LAST, token.type);\n EXPECT_EQ(\"\", token.value);\n }\n};\n\nTEST_F(VersionTest, Valid)\n{\n const char* str = \"#version 200\\n\";\n\n using testing::_;\n EXPECT_CALL(mDirectiveHandler,\n handleVersion(pp::SourceLocation(0, 1), 200));\n \/\/ No error or warning.\n EXPECT_CALL(mDiagnostics, print(_, _, _)).Times(0);\n\n preprocess(str);\n}\n\nTEST_F(VersionTest, CommentsIgnored)\n{\n const char* str = \"\/*foo*\/\"\n \"#\"\n \"\/*foo*\/\"\n \"version\"\n \"\/*foo*\/\"\n \"200\"\n \"\/*foo*\/\"\n \"\/\/foo\"\n \"\\n\";\n\n using testing::_;\n EXPECT_CALL(mDirectiveHandler,\n handleVersion(pp::SourceLocation(0, 1), 200));\n \/\/ No error or warning.\n EXPECT_CALL(mDiagnostics, print(_, _, _)).Times(0);\n\n preprocess(str);\n}\n\nTEST_F(VersionTest, MissingNewline)\n{\n const char* str = \"#version 200\";\n\n using testing::_;\n \/\/ Directive successfully parsed.\n EXPECT_CALL(mDirectiveHandler,\n handleVersion(pp::SourceLocation(0, 1), 200));\n \/\/ Error reported about EOF.\n EXPECT_CALL(mDiagnostics, print(pp::Diagnostics::EOF_IN_DIRECTIVE, _, _));\n\n preprocess(str);\n}\n\nstruct VersionTestParam\n{\n const char* str;\n pp::Diagnostics::ID id;\n};\n\nclass InvalidVersionTest : public VersionTest,\n public testing::WithParamInterface<VersionTestParam>\n{\n};\n\nTEST_P(InvalidVersionTest, Identified)\n{\n VersionTestParam param = GetParam();\n\n using testing::_;\n \/\/ No handleVersion call.\n EXPECT_CALL(mDirectiveHandler, handleVersion(_, _)).Times(0);\n \/\/ Invalid version directive call.\n EXPECT_CALL(mDiagnostics, print(param.id, pp::SourceLocation(0, 1), _));\n\n preprocess(param.str);\n}\n\nstatic const VersionTestParam kParams[] = {\n {\"#version\\n\", pp::Diagnostics::INVALID_VERSION_DIRECTIVE},\n {\"#version foo\\n\", pp::Diagnostics::INVALID_VERSION_NUMBER},\n {\"#version 100 foo\\n\", pp::Diagnostics::UNEXPECTED_TOKEN}\n};\n\nINSTANTIATE_TEST_CASE_P(All, InvalidVersionTest, testing::ValuesIn(kParams));\n<|endoftext|>"} {"text":"<commit_before>\/\/ example of macro to add two histogram files containing the same histograms\n\/\/ (in a directory structure) or ntuples\/trees.\n\/\/ Histograms are added in memory as well as profile histograms.\n\/\/ ntuples and trees are merged.\n\/\/ The resulting histograms are saved into a new file.\n\/\/ original implementation : Rene Brun\n\/\/ extensions by Dirk Geppert to support files with sub-directories\n\n\/\/______________________________________________________________________\n\/\/ give the list of files below. Last file must be a NULL string\nconst char *cfiles[] = {\n \"file1.root\",\n \"file2.root\",\n \"\"};\nconst char *outfile=\"file.root\";\n\/\/______________________________________________________________________\n\nTFile *fnew;\nTList *flist;\nTFile *afile, *file1;\n\nTH1 *h1, *h2;\nTTree *t1, *t2;\nTObject *obj;\nTKey *key;\n\nvoid AddRecursive(TDirectory *root,TDirectory* node);\n\/\/______________________________________________________________________\n\/\/\n\/\/\n\/\/\n\/\/______________________________________________________________________\nvoid hadd() {\n\n \/\/ create the result file\n fnew = new TFile(outfile,\"RECREATE\");\n\n \/\/create a support list for the input files\n flist = new TList();\n\n \/\/open all input files and insert them in the list of files\n Int_t nfiles = 0;\n while (strlen(cfiles[nfiles])) {\n afile = new TFile(cfiles[nfiles]);\n flist->Add(afile);\n nfiles++;\n }\n\n \/\/Get a pointer to the first file\n afile = file1 = (TFile*)flist->First();\n\n AddRecursive(fnew,file1);\n\n \/\/fnew->ls();\n fnew->Write();\n fnew->Close();\n delete fnew;\n flist->Delete();\n delete flist;\n}\n\n\/\/______________________________________________________________________\n\/\/\n\/\/\n\/\/\n\/\/______________________________________________________________________\nvoid AddRecursive(TDirectory *root,TDirectory* node) {\n\n static TDirectory *dact;\n\n TDirectory *dirsav;\n\n \/\/We create an iterator to loop on all objects(keys) of first file\n TIter nextkey(node->GetListOfKeys());\n while (key = (TKey*)nextkey()) {\n node->cd();\n obj = key->ReadObj();\n if (obj->IsA()->InheritsFrom(\"TTree\")) { \/\/case of a TTree or TNtuple\n t1 = (TTree*)obj;\n \/\/ this part still to be implemented\n \/\/ use TChain::Merge instead\n } elseif(obj->IsA()->InheritsFrom(\"TH1\")) { \/\/case of TH1 or TProfile\n h1 = (TH1*)obj;\n afile = (TFile*)flist->After(file1);\n while (afile) { \/\/loop on all files starting at second file\n char* base=strstr(root->GetPath(),\":\"); base+=2;\n \/\/printf(\"base=%s\\n\",base);\n\n dirsav=gDirectory;\n afile->cd(base);\n h2 = (TH1*)gDirectory->Get(h1->GetName());\n dirsav->cd();\n if (h2) { \/\/ here we should check that we can add\n \/\/printf(\"adding histo %s to %s\\n\",h2->GetName(),h1->GetName());\n h1->Add(h2);\n delete h2;\n }\n afile = (TFile*)flist->After(afile);\n }\n } elseif(obj->IsA()->InheritsFrom(\"TDirectory\")) { \/\/case of TDirectory\n \/\/ recursion\n \/\/ printf(\"Found TDirectory name=%s title=%s\\n\",\n \/\/ obj->GetName(),obj->GetTitle());\n root->cd();\n dact=root->mkdir(obj->GetName(),obj->GetTitle());\n dact->cd();\n AddRecursive(dact,(TDirectory*)obj);\n } else { \/\/another object\n printf(\"anotherobjname=%s, title=%s\\n\",obj->GetName(),obj->GetTitle());\n }\n\n \/\/ write node object, modified or not into fnew\n if (obj) {\n root->cd();\n obj->Write(key->GetName());\n delete obj;\n obj=NULL;\n }\n }\n root->cd();\n}\n\n\n\n<commit_msg>Add the relevant statements to support the case of files with multiple sub directories. The global pointers obj and key must be saved and restored when creating a new subdirectory. Thanks to Erik Brubaker <brubaker@uclink.berkeley.edu> for reporting this problem<commit_after>\/\/ example of macro to add two histogram files containing the same histograms\n\/\/ (in a directory structure) or ntuples\/trees.\n\/\/ Histograms are added in memory as well as profile histograms.\n\/\/ ntuples and trees are merged.\n\/\/ The resulting histograms are saved into a new file.\n\/\/ original implementation : Rene Brun\n\/\/ extensions by Dirk Geppert to support files with sub-directories\n\n\/\/______________________________________________________________________\n\/\/ give the list of files below. Last file must be a NULL string\nconst char *cfiles[] = {\n \"file1.root\",\n \"file2.root\",\n \"\"};\nconst char *outfile=\"file.root\";\n\/\/______________________________________________________________________\n\nTFile *fnew;\nTList *flist;\nTFile *afile, *file1;\n\nTH1 *h1, *h2;\nTTree *t1, *t2;\nTObject *obj;\nTKey *key;\n\nvoid AddRecursive(TDirectory *root,TDirectory* node);\n\/\/______________________________________________________________________\n\/\/\n\/\/\n\/\/\n\/\/______________________________________________________________________\nvoid hadd() {\n\n \/\/ create the result file\n fnew = new TFile(outfile,\"RECREATE\");\n\n \/\/create a support list for the input files\n flist = new TList();\n\n \/\/open all input files and insert them in the list of files\n Int_t nfiles = 0;\n while (strlen(cfiles[nfiles])) {\n afile = new TFile(cfiles[nfiles]);\n flist->Add(afile);\n nfiles++;\n }\n\n \/\/Get a pointer to the first file\n afile = file1 = (TFile*)flist->First();\n\n AddRecursive(fnew,file1);\n\n \/\/fnew->ls();\n fnew->Write();\n fnew->Close();\n delete fnew;\n flist->Delete();\n delete flist;\n}\n\n\/\/______________________________________________________________________\n\/\/\n\/\/\n\/\/\n\/\/______________________________________________________________________\nvoid AddRecursive(TDirectory *root,TDirectory* node) {\n\n static TDirectory *dact;\n\n TDirectory *dirsav;\n\n \/\/We create an iterator to loop on all objects(keys) of first file\n TIter nextkey(node->GetListOfKeys());\n while (key = (TKey*)nextkey()) {\n node->cd();\n obj = key->ReadObj();\n if (obj->IsA()->InheritsFrom(\"TTree\")) { \/\/case of a TTree or TNtuple\n t1 = (TTree*)obj;\n \/\/ this part still to be implemented\n \/\/ use TChain::Merge instead\n } elseif(obj->IsA()->InheritsFrom(\"TH1\")) { \/\/case of TH1 or TProfile\n h1 = (TH1*)obj;\n afile = (TFile*)flist->After(file1);\n while (afile) { \/\/loop on all files starting at second file\n char* base=strstr(root->GetPath(),\":\"); base+=2;\n \/\/printf(\"base=%s\\n\",base);\n\n dirsav=gDirectory;\n afile->cd(base);\n h2 = (TH1*)gDirectory->Get(h1->GetName());\n dirsav->cd();\n if (h2) { \/\/ here we should check that we can add\n \/\/printf(\"adding histo %s to %s\\n\",h2->GetName(),h1->GetName());\n h1->Add(h2);\n delete h2;\n }\n afile = (TFile*)flist->After(afile);\n }\n } elseif(obj->IsA()->InheritsFrom(\"TDirectory\")) { \/\/case of TDirectory\n \/\/ recursion\n \/\/ printf(\"Found TDirectory name=%s title=%s\\n\",\n \/\/ obj->GetName(),obj->GetTitle());\n root->cd();\n dact=root->mkdir(obj->GetName(),obj->GetTitle());\n dact->cd();\n TObject *objsave = obj;\n TKey *keysave = key; \n AddRecursive(dact,(TDirectory*)obj);\n obj = objsave;\n key = keysave;\n } else { \/\/another object\n printf(\"anotherobjname=%s, title=%s\\n\",obj->GetName(),obj->GetTitle());\n }\n\n \/\/ write node object, modified or not into fnew\n if (obj) {\n root->cd();\n obj->Write(key->GetName());\n delete obj;\n obj=NULL;\n }\n }\n root->cd();\n}\n\n\n\n<|endoftext|>"} {"text":"<commit_before>#include \"mainWindow.h\"\n\n\nmainWindow::mainWindow(QWidget *parent)\n : QMainWindow(parent)\n{\n \/\/ Setup GUI\n ui.setupUi(this);\n ui.actionQuit->setShortcut(QKeySequence::Quit);\n\n ui.equation->setText(\"4*((a*(1+sqrt(5))\/2)^2*x^2-1*y^2)*((a*(1+sqrt(5))\/2)^2*y^2-1*z^2)*((a*(1+sqrt(5))\/2)^2*z^2-1*x^2)-1*(1+2*(a*(1+sqrt(5))\/2))*(x^2+y^2+z^2-1*1)^2\");\n connect(ui.equation, SIGNAL(editingFinished()), this, SLOT(equationChanged()));\n\n connect( ui.actionSurface_1, SIGNAL(triggered(bool)), this, SLOT(setSampleSurface1()) );\n connect( ui.actionSurface_2, SIGNAL(triggered(bool)), this, SLOT(setSampleSurface2()) );\n connect( ui.actionSurface_3, SIGNAL(triggered(bool)), this, SLOT(setSampleSurface3()) );\n connect( ui.actionSurface_4, SIGNAL(triggered(bool)), this, SLOT(setSampleSurface4()) );\n connect( ui.actionSurface_5, SIGNAL(triggered(bool)), this, SLOT(setSampleSurface5()) );\n connect( ui.actionSurface_6, SIGNAL(triggered(bool)), this, SLOT(setSampleSurface6()) );\n connect( ui.actionSurface_7, SIGNAL(triggered(bool)), this, SLOT(setSampleSurface7()) );\n connect( ui.actionSurface_8, SIGNAL(triggered(bool)), this, SLOT(setSampleSurface8()) );\n\n connect( ui.aSlider, SIGNAL(valueChanged(int)), this, SLOT(sliderMoved(int)) );\n sliderMoved( ui.aSlider->value() );\n\n scene.surface.setEquation(ui.equation->text());\n ui.sceneWidget->setScene(&scene);\n}\n\n\nmainWindow::~mainWindow()\n{\n}\n\n\nvoid mainWindow::setSampleSurface1()\n{\n ui.equation->setText(\"(2*x^2 + y^2 + z^2 - 1)^3 - x^2*z^3\/10 - y^2*z^3\");\n ui.equation->setCursorPosition(0);\n equationChanged();\n}\n\n\nvoid mainWindow::setSampleSurface2()\n{\n ui.equation->setText(\"x^2 + 4 * y^2 + z^2 - 8\");\n ui.equation->setCursorPosition(0);\n equationChanged();\n}\n\n\nvoid mainWindow::setSampleSurface3()\n{\n ui.equation->setText(\"(x^2 + y^2 + z^2 + 2)^2 - 12*(x^2 + y^2)\");\n ui.equation->setCursorPosition(0);\n equationChanged();\n}\n\n\nvoid mainWindow::setSampleSurface4()\n{\n ui.equation->setText(\"x*y*z\");\n ui.equation->setCursorPosition(0);\n equationChanged();\n}\n\n\nvoid mainWindow::setSampleSurface5()\n{\n ui.equation->setText(\"x^2 + y^2 + z - 1\");\n ui.equation->setCursorPosition(0);\n equationChanged();\n}\n\n\nvoid mainWindow::setSampleSurface6()\n{\n ui.equation->setText(\"x^2 + y^2 - 1\");\n ui.equation->setCursorPosition(0);\n equationChanged();\n}\n\n\nvoid mainWindow::setSampleSurface7()\n{\n ui.equation->setText(\"x^2 + y^2 - z^2\");\n ui.equation->setCursorPosition(0);\n equationChanged();\n}\n\n\nvoid mainWindow::setSampleSurface8()\n{\n ui.equation->setText(\"4*((a*(1+sqrt(5))\/2)^2*x^2-1*y^2)*((a*(1+sqrt(5))\/2)^2*y^2-1*z^2)*((a*(1+sqrt(5))\/2)^2*z^2-1*x^2)-1*(1+2*(a*(1+sqrt(5))\/2))*(x^2+y^2+z^2-1*1)^2\");\n ui.equation->setCursorPosition(0);\n equationChanged();\n}\n\n\nvoid mainWindow::equationChanged()\n{\n scene.surface.setEquation(ui.equation->text());\n\n if (scene.surface.hasError()) {\n statusBar()->showMessage(scene.surface.errorString(), 2000);\n ui.equation->setCursorPosition(scene.surface.errorIndex());\n }\n}\n\n\nvoid mainWindow::sliderMoved(int val)\n{\n qreal a = val\/100.0;\n ui.aLabel->setText( QString(\"a = %1\").arg(a));\n scene.surface.setA(a);\n}\n<commit_msg>Triviale Änderung. Am besten ignorieren.<commit_after>#include \"mainWindow.h\"\n\n\nmainWindow::mainWindow(QWidget *parent)\n : QMainWindow(parent)\n{\n \/\/ Setup GUI\n ui.setupUi(this);\n ui.actionQuit->setShortcut(QKeySequence::Quit);\n\n connect(ui.equation, SIGNAL(editingFinished()), this, SLOT(equationChanged()));\n\n connect(ui.aSlider, SIGNAL(valueChanged(int)), this, SLOT(sliderMoved(int)) );\n sliderMoved( ui.aSlider->value() );\n\n connect( ui.actionSurface_1, SIGNAL(triggered(bool)), this, SLOT(setSampleSurface1()) );\n connect( ui.actionSurface_2, SIGNAL(triggered(bool)), this, SLOT(setSampleSurface2()) );\n connect( ui.actionSurface_3, SIGNAL(triggered(bool)), this, SLOT(setSampleSurface3()) );\n connect( ui.actionSurface_4, SIGNAL(triggered(bool)), this, SLOT(setSampleSurface4()) );\n connect( ui.actionSurface_5, SIGNAL(triggered(bool)), this, SLOT(setSampleSurface5()) );\n connect( ui.actionSurface_6, SIGNAL(triggered(bool)), this, SLOT(setSampleSurface6()) );\n connect( ui.actionSurface_7, SIGNAL(triggered(bool)), this, SLOT(setSampleSurface7()) );\n connect( ui.actionSurface_8, SIGNAL(triggered(bool)), this, SLOT(setSampleSurface8()) );\n\n\n scene.surface.setEquation(ui.equation->text());\n ui.sceneWidget->setScene(&scene);\n\n setSampleSurface8();\n}\n\n\nmainWindow::~mainWindow()\n{\n}\n\n\nvoid mainWindow::setSampleSurface1()\n{\n ui.equation->setText(\"(2*x^2 + y^2 + z^2 - 1)^3 - x^2*z^3\/10 - y^2*z^3\");\n ui.equation->setCursorPosition(0);\n equationChanged();\n}\n\n\nvoid mainWindow::setSampleSurface2()\n{\n ui.equation->setText(\"x^2 + 4 * y^2 + z^2 - 8\");\n ui.equation->setCursorPosition(0);\n equationChanged();\n}\n\n\nvoid mainWindow::setSampleSurface3()\n{\n ui.equation->setText(\"(x^2 + y^2 + z^2 + 2)^2 - 12*(x^2 + y^2)\");\n ui.equation->setCursorPosition(0);\n equationChanged();\n}\n\n\nvoid mainWindow::setSampleSurface4()\n{\n ui.equation->setText(\"x*y*z\");\n ui.equation->setCursorPosition(0);\n equationChanged();\n}\n\n\nvoid mainWindow::setSampleSurface5()\n{\n ui.equation->setText(\"x^2 + y^2 + z - 1\");\n ui.equation->setCursorPosition(0);\n equationChanged();\n}\n\n\nvoid mainWindow::setSampleSurface6()\n{\n ui.equation->setText(\"x^2 + y^2 - 1\");\n ui.equation->setCursorPosition(0);\n equationChanged();\n}\n\n\nvoid mainWindow::setSampleSurface7()\n{\n ui.equation->setText(\"x^2 + y^2 - z^2\");\n ui.equation->setCursorPosition(0);\n equationChanged();\n}\n\n\nvoid mainWindow::setSampleSurface8()\n{\n ui.equation->setText(\"4*((a*(1+sqrt(5))\/2)^2*x^2-1*y^2)*((a*(1+sqrt(5))\/2)^2*y^2-1*z^2)*((a*(1+sqrt(5))\/2)^2*z^2-1*x^2)-1*(1+2*(a*(1+sqrt(5))\/2))*(x^2+y^2+z^2-1*1)^2\");\n ui.equation->setCursorPosition(0);\n equationChanged();\n}\n\n\nvoid mainWindow::equationChanged()\n{\n scene.surface.setEquation(ui.equation->text());\n\n if (scene.surface.hasError()) {\n statusBar()->showMessage(scene.surface.errorString(), 2000);\n ui.equation->setCursorPosition(scene.surface.errorIndex());\n }\n}\n\n\nvoid mainWindow::sliderMoved(int val)\n{\n qreal a = val\/100.0;\n ui.aLabel->setText( QString(\"a = %1\").arg(a));\n scene.surface.setA(a);\n}\n<|endoftext|>"} {"text":"<commit_before>\/**\n * Copyright (c) 2015 Eugene Lazin <4lazin@gmail.com>\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"queryprocessor.h\"\n#include \"util.h\"\n\n#include <random>\n#include <algorithm>\n\n#include <boost\/lexical_cast.hpp>\n\nnamespace Akumuli {\n\nBoltException::BoltException(Bolt::BoltType type, const char* msg)\n : std::runtime_error(msg)\n , type_(type)\n{\n}\n\nBolt::BoltType BoltException::get_type() const {\n return type_;\n}\n\nstruct RandomSamplingBolt : std::enable_shared_from_this<RandomSamplingBolt>, Bolt {\n const uint32_t buffer_size_;\n std::vector<std::shared_ptr<Bolt>> outputs_;\n std::vector<std::weak_ptr<Bolt>> inputs_;\n std::vector<aku_Timestamp> timestamps_;\n std::vector<aku_ParamId> paramids_;\n std::vector<double> values_;\n Rand random_;\n\n RandomSamplingBolt(uint32_t buffer_size)\n : buffer_size_(buffer_size)\n {\n }\n\n \/\/ Bolt interface\n virtual void add_output(std::shared_ptr<Bolt> next) {\n outputs_.push_back(next);\n }\n\n virtual void add_input(std::weak_ptr<Bolt> input) {\n inputs_.push_back(input);\n }\n\n virtual BoltType get_bolt_type() const {\n return Bolt::RandomSampler;\n }\n\n virtual std::vector<std::shared_ptr<Bolt>> get_bolt_outputs() const {\n return outputs_;\n }\n\n virtual std::vector<std::shared_ptr<Bolt>> get_bolt_inputs() const {\n std::vector<std::shared_ptr<Bolt>> result;\n for(auto wref: inputs_) {\n result.push_back(wref.lock());\n }\n return result;\n }\n\n virtual void complete(std::shared_ptr<Bolt> caller) {\n\n \/\/ Reset caller in inputs list\n for(auto& wref: inputs_) { \/\/ TODO: this logic should be\n auto sref = wref.lock(); \/\/ moved to separate mixin class\n if (sref && sref == caller) { \/\/ tested and inherited by all\n wref.reset(); \/\/ blots.\n break;\n }\n }\n\n \/\/ Check precondition (all inputs was gone)\n for(auto& wref: inputs_) {\n if (wref.expired() == false) {\n return;\n }\n }\n if (outputs_.empty()) {\n BoltException except(Bolt::RandomSampler, \"no output bolt\");\n BOOST_THROW_EXCEPTION(except);\n }\n\n \/\/ Do the actual job\n auto& tsarray = timestamps_;\n auto predicate = [&tsarray](uint32_t lhs, uint32_t rhs) {\n return tsarray.at(lhs) < tsarray.at(rhs);\n };\n\n std::vector<uint32_t> indexes;\n uint32_t gencnt = 0u;\n std::generate_n(std::back_inserter(indexes), timestamps_.size(), [&gencnt]() { return gencnt++; });\n std::stable_sort(indexes.begin(), indexes.end(), predicate);\n\n for(auto ix: indexes) {\n for(auto& bolt: outputs_) {\n bolt->put(timestamps_.at(ix),\n paramids_.at(ix),\n values_.at(ix));\n }\n }\n\n for(auto& bolt: outputs_) {\n bolt->complete(shared_from_this());\n }\n }\n\n virtual void put(aku_Timestamp ts, aku_ParamId id, double value) {\n if (outputs_.empty()) {\n BoltException except(Bolt::RandomSampler, \"no output bolt\");\n BOOST_THROW_EXCEPTION(except);\n }\n if (timestamps_.size() < buffer_size_) {\n \/\/ Just append new values\n timestamps_.push_back(ts);\n paramids_.push_back(id);\n values_.push_back(value);\n } else {\n \/\/ Flip a coin\n uint32_t ix = random_() % timestamps_.size();\n if (ix < buffer_size_) {\n timestamps_.at(ix) = ts;\n paramids_.at(ix) = id;\n values_.at(ix) = value;\n }\n }\n }\n};\n\nstd::shared_ptr<Bolt> BoltsBuilder::make_random_sampler(std::string type,\n size_t buffer_size,\n aku_logger_cb_t logger)\n{\n {\n std::stringstream logfmt;\n logfmt << \"Creating random sampler of type \" << type << \" with buffer size \" << buffer_size;\n (*logger)(AKU_LOG_TRACE, logfmt.str().c_str());\n }\n \/\/ only reservoir sampling is supported\n if (type != \"reservoir\") {\n BoltException except(Bolt::RandomSampler, \"unsupported sampler type\");\n BOOST_THROW_EXCEPTION(except);\n }\n \/\/ Build object\n return std::make_shared<RandomSamplingBolt>(buffer_size);\n}\n\nQueryProcessor::QueryProcessor(std::shared_ptr<Bolt> root,\n std::vector<std::string> metrics,\n aku_Timestamp begin,\n aku_Timestamp end)\n : lowerbound(std::min(begin, end))\n , upperbound(std::max(begin, end))\n , direction(begin > end ? AKU_CURSOR_DIR_FORWARD : AKU_CURSOR_DIR_BACKWARD)\n , metrics(metrics)\n , namesofinterest(StringTools::create_table(0x1000))\n , root_bolt(root)\n{\n}\n\nint QueryProcessor::match(uint64_t param_id) {\n return -1;\n}\n\n}\n\n<commit_msg>WIP: query processor<commit_after>\/**\n * Copyright (c) 2015 Eugene Lazin <4lazin@gmail.com>\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"queryprocessor.h\"\n#include \"util.h\"\n\n#include <random>\n#include <algorithm>\n\n#include <boost\/lexical_cast.hpp>\n\nnamespace Akumuli {\n\nBoltException::BoltException(Bolt::BoltType type, const char* msg)\n : std::runtime_error(msg)\n , type_(type)\n{\n}\n\nBolt::BoltType BoltException::get_type() const {\n return type_;\n}\n\n\n\/** Abstract graph node. Handles inputs and outputs.\n * Implements part of the Bolt interface.\n *\/\nstruct AcyclicGraphNode : Bolt\n{\n std::vector<std::shared_ptr<Bolt>> outputs_;\n std::vector<std::weak_ptr<Bolt>> inputs_;\n\n virtual void add_output(std::shared_ptr<Bolt> next) {\n outputs_.push_back(next);\n }\n\n virtual void add_input(std::weak_ptr<Bolt> input) {\n inputs_.push_back(input);\n }\n\n virtual std::vector<std::shared_ptr<Bolt>> get_bolt_outputs() const {\n return outputs_;\n }\n\n virtual std::vector<std::shared_ptr<Bolt>> get_bolt_inputs() const {\n std::vector<std::shared_ptr<Bolt>> result;\n for(auto wref: inputs_) {\n result.push_back(wref.lock());\n }\n return result;\n }\n\n \/** Remove input from inputs list.\n * @return true if all inputs was gone and false otherwise\n * @param caller is a pointer to input node that needs to be removed\n *\/\n bool remove_input(std::shared_ptr<Bolt> caller) {\n \/\/ Reset caller in inputs list\n for(auto& wref: inputs_) {\n auto sref = wref.lock();\n if (sref && sref == caller) {\n wref.reset();\n break;\n }\n }\n\n \/\/ Check precondition (all inputs was gone)\n for(auto& wref: inputs_) {\n if (wref.expired() == false) {\n return false;\n }\n }\n return true;\n }\n\n void distribute(aku_Timestamp ts, aku_ParamId pid, double value) {\n for(auto& bolt: outputs_) {\n bolt->put(ts, pid, value);\n }\n }\n\n \/** Throw exception if there is no output node\n * @throw BoltException\n *\/\n void throw_if_no_output() {\n if (outputs_.empty()) {\n BoltException except(Bolt::RandomSampler, \"no output bolt\");\n BOOST_THROW_EXCEPTION(except);\n }\n }\n\n template<class Derived>\n void complete_children(std::shared_ptr<Derived> caller) {\n for(auto& bolt: outputs_) {\n bolt->complete(caller);\n }\n }\n};\n\n\nstruct RandomSamplingBolt : std::enable_shared_from_this<RandomSamplingBolt>, AcyclicGraphNode {\n const uint32_t buffer_size_;\n std::vector<aku_Timestamp> timestamps_;\n std::vector<aku_ParamId> paramids_;\n std::vector<double> values_;\n Rand random_;\n\n RandomSamplingBolt(uint32_t buffer_size)\n : buffer_size_(buffer_size)\n {\n }\n\n \/\/ Bolt interface\n virtual BoltType get_bolt_type() const {\n return Bolt::RandomSampler;\n }\n\n virtual void complete(std::shared_ptr<Bolt> caller) {\n if (remove_input(caller)) {\n throw_if_no_output();\n\n \/\/ Do the actual job\n auto& tsarray = timestamps_;\n auto predicate = [&tsarray](uint32_t lhs, uint32_t rhs) {\n return tsarray.at(lhs) < tsarray.at(rhs);\n };\n\n std::vector<uint32_t> indexes;\n uint32_t gencnt = 0u;\n std::generate_n(std::back_inserter(indexes), timestamps_.size(), [&gencnt]() { return gencnt++; });\n std::stable_sort(indexes.begin(), indexes.end(), predicate);\n\n for(auto ix: indexes) {\n distribute(timestamps_.at(ix),\n paramids_.at(ix),\n values_.at(ix));\n }\n\n complete_children(shared_from_this());\n }\n }\n\n virtual void put(aku_Timestamp ts, aku_ParamId id, double value) {\n throw_if_no_output();\n if (timestamps_.size() < buffer_size_) {\n \/\/ Just append new values\n timestamps_.push_back(ts);\n paramids_.push_back(id);\n values_.push_back(value);\n } else {\n \/\/ Flip a coin\n uint32_t ix = random_() % timestamps_.size();\n if (ix < buffer_size_) {\n timestamps_.at(ix) = ts;\n paramids_.at(ix) = id;\n values_.at(ix) = value;\n }\n }\n }\n};\n\n\/*\nstruct RandomSamplingBolt : AcyclicGraphNode<RandomSamplingBolt> {\n\n \/\/ Bolt interface\n virtual void complete(std::shared_ptr<Bolt> caller);\n virtual void put(aku_Timestamp ts, aku_ParamId id, double value);\n virtual void add_output(std::shared_ptr<Bolt> next);\n virtual void add_input(std::weak_ptr<Bolt> input);\n virtual BoltType get_bolt_type() const;\n virtual std::vector<std::shared_ptr<Bolt> > get_bolt_inputs() const;\n virtual std::vector<std::shared_ptr<Bolt> > get_bolt_outputs() const;\n};\n*\/\n\n\/\/ \/\/\n\/\/ Factory methods \/\/\n\/\/ \/\/\n\nstd::shared_ptr<Bolt> BoltsBuilder::make_random_sampler(std::string type,\n size_t buffer_size,\n aku_logger_cb_t logger)\n{\n {\n std::stringstream logfmt;\n logfmt << \"Creating random sampler of type \" << type << \" with buffer size \" << buffer_size;\n (*logger)(AKU_LOG_TRACE, logfmt.str().c_str());\n }\n \/\/ only reservoir sampling is supported\n if (type != \"reservoir\") {\n BoltException except(Bolt::RandomSampler, \"unsupported sampler type\");\n BOOST_THROW_EXCEPTION(except);\n }\n \/\/ Build object\n return std::make_shared<RandomSamplingBolt>(buffer_size);\n}\n\nQueryProcessor::QueryProcessor(std::shared_ptr<Bolt> root,\n std::vector<std::string> metrics,\n aku_Timestamp begin,\n aku_Timestamp end)\n : lowerbound(std::min(begin, end))\n , upperbound(std::max(begin, end))\n , direction(begin > end ? AKU_CURSOR_DIR_FORWARD : AKU_CURSOR_DIR_BACKWARD)\n , metrics(metrics)\n , namesofinterest(StringTools::create_table(0x1000))\n , root_bolt(root)\n{\n}\n\nint QueryProcessor::match(uint64_t param_id) {\n return -1;\n}\n\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/**\n * \\file\n * \\brief SoftwareTimerOperationsTestCase class implementation\n *\n * \\author Copyright (C) 2014-2016 Kamil Szczygiel http:\/\/www.distortec.com http:\/\/www.freddiechopin.info\n *\n * \\par License\n * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not\n * distributed with this file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\/\n\n#include \"SoftwareTimerOperationsTestCase.hpp\"\n\n#include \"waitForNextTick.hpp\"\n\n#include \"distortos\/StaticSoftwareTimer.hpp\"\n#include \"distortos\/ThisThread.hpp\"\n\nnamespace distortos\n{\n\nnamespace test\n{\n\n\/*---------------------------------------------------------------------------------------------------------------------+\n| private functions\n+---------------------------------------------------------------------------------------------------------------------*\/\n\nbool SoftwareTimerOperationsTestCase::run_() const\n{\n\tvolatile uint32_t value {};\n\tauto softwareTimer = makeStaticSoftwareTimer(\n\t\t\t[&value]()\n\t\t\t{\n\t\t\t\t++value;\n\t\t\t});\n\n\t{\n\t\tconstexpr auto duration = TickClock::duration{11};\n\n\t\tif (softwareTimer.isRunning() != false || value != 0)\t\/\/ initially must be stopped and must not execute\n\t\t\treturn false;\n\n\t\twaitForNextTick();\n\t\tif (softwareTimer.start(duration) != 0)\n\t\t\treturn false;\n\t\tif (softwareTimer.isRunning() != true || value != 0)\t\/\/ must be started, but may not execute yet\n\t\t\treturn false;\n\n\t\tif (softwareTimer.stop() != 0)\n\t\t\treturn false;\n\t\tif (softwareTimer.isRunning() != false || value != 0)\t\/\/ must be stopped, must not execute\n\t\t\treturn false;\n\n\t\tThisThread::sleepFor(duration * 2);\n\t\tif (softwareTimer.isRunning() != false || value != 0)\t\/\/ make sure it did not execute\n\t\t\treturn false;\n\t}\n\t{\n\t\tconstexpr auto duration = TickClock::duration{9};\n\n\t\twaitForNextTick();\n\t\tif (softwareTimer.start(duration) != 0)\n\t\t\treturn false;\n\t\tif (softwareTimer.isRunning() != true || value != 0)\t\/\/ must be started, but may not execute yet\n\t\t\treturn false;\n\n\t\tconst auto start = TickClock::now();\n\t\twhile (softwareTimer.isRunning() == true);\n\n\t\t\/\/ must be stopped, function must be executed, real duration must equal what is expected\n\t\tif (softwareTimer.isRunning() != false || value != 1 ||\n\t\t\t\tTickClock::now() - start != duration + decltype(duration){1})\n\t\t\treturn false;\n\t}\n\t{\n\t\twaitForNextTick();\n\t\tconst auto wakeUpTimePoint = TickClock::now() + TickClock::duration{13};\n\t\tif (softwareTimer.start(wakeUpTimePoint) != 0)\n\t\t\treturn false;\n\t\tif (softwareTimer.isRunning() != true || value != 1)\t\/\/ must be started, but may not execute yet\n\t\t\treturn false;\n\n\t\twhile (softwareTimer.isRunning() == true);\n\n\t\t\/\/ must be stopped, function must be executed, wake up time point must equal what is expected\n\t\tif (softwareTimer.isRunning() != false || value != 2 || TickClock::now() != wakeUpTimePoint)\n\t\t\treturn false;\n\t}\n\t{\n\t\tconstexpr auto period = TickClock::duration{6};\n\n\t\twaitForNextTick();\n\t\tconst auto wakeUpTimePoint = TickClock::now() + TickClock::duration{17};\n\t\tif (softwareTimer.start(wakeUpTimePoint, period) != 0)\n\t\t\treturn false;\n\t\tif (softwareTimer.isRunning() != true || value != 2)\t\/\/ must be started, but may not execute yet\n\t\t\treturn false;\n\n\t\tfor (size_t iteration {}; iteration < 4; ++iteration)\n\t\t{\n\t\t\twhile (softwareTimer.isRunning() == true && value == 2 + iteration);\n\n\t\t\t\/\/ must be still running, function must be executed, wake up time point must equal what is expected\n\t\t\tif (softwareTimer.isRunning() != true || value != 3 + iteration ||\n\t\t\t\t\tTickClock::now() != wakeUpTimePoint + period * iteration)\n\t\t\t\treturn false;\n\t\t}\n\n\t\tif (softwareTimer.stop() != 0)\n\t\t\treturn false;\n\t\tif (softwareTimer.isRunning() != false || value != 6)\t\/\/ must be stopped\n\t\t\treturn false;\n\n\t\tThisThread::sleepFor(period * 2);\n\t\tif (softwareTimer.isRunning() != false || value != 6)\t\/\/ make sure it did not execute again\n\t\t\treturn false;\n\t}\n\t{\n\t\t\/\/ restart one-shot into one-shot\n\t\tfor (size_t iteration {}; iteration < 4; ++iteration)\n\t\t{\n\t\t\tconstexpr auto duration = TickClock::duration{15};\n\t\t\tconst auto wakeUpTimePoint = TickClock::now() + duration;\n\t\t\tif (softwareTimer.start(wakeUpTimePoint) != 0)\n\t\t\t\treturn false;\n\t\t\tif (softwareTimer.isRunning() != true || value != 6)\t\/\/ must be started, but may not execute yet\n\t\t\t\treturn false;\n\n\t\t\tThisThread::sleepUntil(wakeUpTimePoint - duration \/ 2);\n\n\t\t\tif (softwareTimer.isRunning() != true || value != 6)\t\/\/ must be started, but may not execute yet\n\t\t\t\treturn false;\n\t\t}\n\n\t\t\/\/ restart one-shot into periodic, then periodic into periodic\n\t\tfor (size_t iteration {}; iteration < 4; ++iteration)\n\t\t{\n\t\t\tconstexpr auto delay = TickClock::duration{12};\n\n\t\t\tconst auto wakeUpTimePoint = TickClock::now() + delay;\n\t\t\tif (softwareTimer.start(wakeUpTimePoint, TickClock::duration{10}) != 0)\n\t\t\t\treturn false;\n\t\t\tif (softwareTimer.isRunning() != true || value != 6)\t\/\/ must be started, but may not execute yet\n\t\t\t\treturn false;\n\n\t\t\tThisThread::sleepUntil(wakeUpTimePoint - delay \/ 2);\n\n\t\t\tif (softwareTimer.isRunning() != true || value != 6)\t\/\/ must be started, but may not execute yet\n\t\t\t\treturn false;\n\t\t}\n\n\t\t\/\/ restart periodic into periodic\n\t\t{\n\t\t\tconstexpr auto period = TickClock::duration{19};\n\n\t\t\twaitForNextTick();\n\t\t\tconst auto wakeUpTimePoint = TickClock::now() + TickClock::duration{14};\n\t\t\tif (softwareTimer.start(wakeUpTimePoint, period) != 0)\n\t\t\t\treturn false;\n\t\t\tif (softwareTimer.isRunning() != true || value != 6)\t\/\/ must be started, but may not execute yet\n\t\t\t\treturn false;\n\n\t\t\tfor (size_t iteration {}; iteration < 4; ++iteration)\n\t\t\t{\n\t\t\t\twhile (softwareTimer.isRunning() == true && value == 6 + iteration);\n\n\t\t\t\t\/\/ must be still running, function must be executed, wake up time point must equal what is expected\n\t\t\t\tif (softwareTimer.isRunning() != true || value != 7 + iteration ||\n\t\t\t\t\t\tTickClock::now() != wakeUpTimePoint + period * iteration)\n\t\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\n\t\t\/\/ restart periodic into periodic with different settings\n\t\t{\n\t\t\tconstexpr auto period = TickClock::duration{7};\n\n\t\t\twaitForNextTick();\n\t\t\tconst auto wakeUpTimePoint = TickClock::now() + TickClock::duration{5};\n\t\t\tif (softwareTimer.start(wakeUpTimePoint, period) != 0)\n\t\t\t\treturn false;\n\t\t\tif (softwareTimer.isRunning() != true || value != 10)\t\/\/ must be started, but may not execute yet\n\t\t\t\treturn false;\n\n\t\t\tfor (size_t iteration {}; iteration < 4; ++iteration)\n\t\t\t{\n\t\t\t\twhile (softwareTimer.isRunning() == true && value == 10 + iteration);\n\n\t\t\t\t\/\/ must be still running, function must be executed, wake up time point must equal what is expected\n\t\t\t\tif (softwareTimer.isRunning() != true || value != 11 + iteration ||\n\t\t\t\t\t\tTickClock::now() != wakeUpTimePoint + period * iteration)\n\t\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\n\t\t\/\/ restart periodic into one-shot\n\t\twaitForNextTick();\n\t\tconst auto wakeUpTimePoint = TickClock::now() + TickClock::duration{16};\n\t\tif (softwareTimer.start(wakeUpTimePoint) != 0)\n\t\t\treturn false;\n\t\tif (softwareTimer.isRunning() != true || value != 14)\t\/\/ must be started, but may not execute yet\n\t\t\treturn false;\n\n\t\twhile (softwareTimer.isRunning() == true);\n\n\t\t\/\/ must be stopped, function must be executed, wake up time point must equal what is expected\n\t\tif (softwareTimer.isRunning() != false || value != 15 || TickClock::now() != wakeUpTimePoint)\n\t\t\treturn false;\n\t}\n\n\treturn true;\n}\n\n}\t\/\/ namespace test\n\n}\t\/\/ namespace distortos\n<commit_msg>Use wrapper class instead of lambda in SoftwareTimerOperationsTestCase<commit_after>\/**\n * \\file\n * \\brief SoftwareTimerOperationsTestCase class implementation\n *\n * \\author Copyright (C) 2014-2016 Kamil Szczygiel http:\/\/www.distortec.com http:\/\/www.freddiechopin.info\n *\n * \\par License\n * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not\n * distributed with this file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\/\n\n#include \"SoftwareTimerOperationsTestCase.hpp\"\n\n#include \"waitForNextTick.hpp\"\n\n#include \"distortos\/StaticSoftwareTimer.hpp\"\n#include \"distortos\/ThisThread.hpp\"\n\nnamespace distortos\n{\n\nnamespace test\n{\n\nnamespace\n{\n\n\/*---------------------------------------------------------------------------------------------------------------------+\n| local types\n+---------------------------------------------------------------------------------------------------------------------*\/\n\n\/\/\/ wrapper for software timer\nstruct SoftwareTimerWrapper\n{\npublic:\n\n\t\/**\n\t * \\brief SoftwareTimerWrapper's constructor\n\t *\n\t * \\param [in,out] value is a reference to volatile uint32_t variable which will be incremented when timer's\n\t * function is executed\n\t *\/\n\n\texplicit SoftwareTimerWrapper(volatile uint32_t& value) :\n\t\t\tsoftwareTimer_{&SoftwareTimerWrapper::function, *this},\n\t\t\tvalue_{value}\n\t{\n\n\t}\n\n\t\/**\n\t * \\return reference to internal software timer\n\t *\/\n\n\tSoftwareTimer& get()\n\t{\n\t\treturn softwareTimer_;\n\t}\n\nprivate:\n\n\t\/**\n\t * \\brief Function used by software timer\n\t *\/\n\n\tvoid function()\n\t{\n\t\t++value_;\n\t}\n\n\t\/\/\/ type of internal software timer\n\tusing SoftwareTimerType = decltype(makeStaticSoftwareTimer(&SoftwareTimerWrapper::function,\n\t\t\tstd::ref(std::declval<SoftwareTimerWrapper&>())));\n\n\t\/\/\/ internal software timer\n\tSoftwareTimerType softwareTimer_;\n\n\t\/\/\/ reference to volatile uint32_t variable which will be incremented when timer's function is executed\n\tvolatile uint32_t& value_;\n};\n\n}\t\/\/ namespace\n\n\/*---------------------------------------------------------------------------------------------------------------------+\n| private functions\n+---------------------------------------------------------------------------------------------------------------------*\/\n\nbool SoftwareTimerOperationsTestCase::run_() const\n{\n\tvolatile uint32_t value {};\n\tSoftwareTimerWrapper softwareTimerWrapper {value};\n\tauto& softwareTimer = softwareTimerWrapper.get();\n\n\t{\n\t\tconstexpr auto duration = TickClock::duration{11};\n\n\t\tif (softwareTimer.isRunning() != false || value != 0)\t\/\/ initially must be stopped and must not execute\n\t\t\treturn false;\n\n\t\twaitForNextTick();\n\t\tif (softwareTimer.start(duration) != 0)\n\t\t\treturn false;\n\t\tif (softwareTimer.isRunning() != true || value != 0)\t\/\/ must be started, but may not execute yet\n\t\t\treturn false;\n\n\t\tif (softwareTimer.stop() != 0)\n\t\t\treturn false;\n\t\tif (softwareTimer.isRunning() != false || value != 0)\t\/\/ must be stopped, must not execute\n\t\t\treturn false;\n\n\t\tThisThread::sleepFor(duration * 2);\n\t\tif (softwareTimer.isRunning() != false || value != 0)\t\/\/ make sure it did not execute\n\t\t\treturn false;\n\t}\n\t{\n\t\tconstexpr auto duration = TickClock::duration{9};\n\n\t\twaitForNextTick();\n\t\tif (softwareTimer.start(duration) != 0)\n\t\t\treturn false;\n\t\tif (softwareTimer.isRunning() != true || value != 0)\t\/\/ must be started, but may not execute yet\n\t\t\treturn false;\n\n\t\tconst auto start = TickClock::now();\n\t\twhile (softwareTimer.isRunning() == true);\n\n\t\t\/\/ must be stopped, function must be executed, real duration must equal what is expected\n\t\tif (softwareTimer.isRunning() != false || value != 1 ||\n\t\t\t\tTickClock::now() - start != duration + decltype(duration){1})\n\t\t\treturn false;\n\t}\n\t{\n\t\twaitForNextTick();\n\t\tconst auto wakeUpTimePoint = TickClock::now() + TickClock::duration{13};\n\t\tif (softwareTimer.start(wakeUpTimePoint) != 0)\n\t\t\treturn false;\n\t\tif (softwareTimer.isRunning() != true || value != 1)\t\/\/ must be started, but may not execute yet\n\t\t\treturn false;\n\n\t\twhile (softwareTimer.isRunning() == true);\n\n\t\t\/\/ must be stopped, function must be executed, wake up time point must equal what is expected\n\t\tif (softwareTimer.isRunning() != false || value != 2 || TickClock::now() != wakeUpTimePoint)\n\t\t\treturn false;\n\t}\n\t{\n\t\tconstexpr auto period = TickClock::duration{6};\n\n\t\twaitForNextTick();\n\t\tconst auto wakeUpTimePoint = TickClock::now() + TickClock::duration{17};\n\t\tif (softwareTimer.start(wakeUpTimePoint, period) != 0)\n\t\t\treturn false;\n\t\tif (softwareTimer.isRunning() != true || value != 2)\t\/\/ must be started, but may not execute yet\n\t\t\treturn false;\n\n\t\tfor (size_t iteration {}; iteration < 4; ++iteration)\n\t\t{\n\t\t\twhile (softwareTimer.isRunning() == true && value == 2 + iteration);\n\n\t\t\t\/\/ must be still running, function must be executed, wake up time point must equal what is expected\n\t\t\tif (softwareTimer.isRunning() != true || value != 3 + iteration ||\n\t\t\t\t\tTickClock::now() != wakeUpTimePoint + period * iteration)\n\t\t\t\treturn false;\n\t\t}\n\n\t\tif (softwareTimer.stop() != 0)\n\t\t\treturn false;\n\t\tif (softwareTimer.isRunning() != false || value != 6)\t\/\/ must be stopped\n\t\t\treturn false;\n\n\t\tThisThread::sleepFor(period * 2);\n\t\tif (softwareTimer.isRunning() != false || value != 6)\t\/\/ make sure it did not execute again\n\t\t\treturn false;\n\t}\n\t{\n\t\t\/\/ restart one-shot into one-shot\n\t\tfor (size_t iteration {}; iteration < 4; ++iteration)\n\t\t{\n\t\t\tconstexpr auto duration = TickClock::duration{15};\n\t\t\tconst auto wakeUpTimePoint = TickClock::now() + duration;\n\t\t\tif (softwareTimer.start(wakeUpTimePoint) != 0)\n\t\t\t\treturn false;\n\t\t\tif (softwareTimer.isRunning() != true || value != 6)\t\/\/ must be started, but may not execute yet\n\t\t\t\treturn false;\n\n\t\t\tThisThread::sleepUntil(wakeUpTimePoint - duration \/ 2);\n\n\t\t\tif (softwareTimer.isRunning() != true || value != 6)\t\/\/ must be started, but may not execute yet\n\t\t\t\treturn false;\n\t\t}\n\n\t\t\/\/ restart one-shot into periodic, then periodic into periodic\n\t\tfor (size_t iteration {}; iteration < 4; ++iteration)\n\t\t{\n\t\t\tconstexpr auto delay = TickClock::duration{12};\n\n\t\t\tconst auto wakeUpTimePoint = TickClock::now() + delay;\n\t\t\tif (softwareTimer.start(wakeUpTimePoint, TickClock::duration{10}) != 0)\n\t\t\t\treturn false;\n\t\t\tif (softwareTimer.isRunning() != true || value != 6)\t\/\/ must be started, but may not execute yet\n\t\t\t\treturn false;\n\n\t\t\tThisThread::sleepUntil(wakeUpTimePoint - delay \/ 2);\n\n\t\t\tif (softwareTimer.isRunning() != true || value != 6)\t\/\/ must be started, but may not execute yet\n\t\t\t\treturn false;\n\t\t}\n\n\t\t\/\/ restart periodic into periodic\n\t\t{\n\t\t\tconstexpr auto period = TickClock::duration{19};\n\n\t\t\twaitForNextTick();\n\t\t\tconst auto wakeUpTimePoint = TickClock::now() + TickClock::duration{14};\n\t\t\tif (softwareTimer.start(wakeUpTimePoint, period) != 0)\n\t\t\t\treturn false;\n\t\t\tif (softwareTimer.isRunning() != true || value != 6)\t\/\/ must be started, but may not execute yet\n\t\t\t\treturn false;\n\n\t\t\tfor (size_t iteration {}; iteration < 4; ++iteration)\n\t\t\t{\n\t\t\t\twhile (softwareTimer.isRunning() == true && value == 6 + iteration);\n\n\t\t\t\t\/\/ must be still running, function must be executed, wake up time point must equal what is expected\n\t\t\t\tif (softwareTimer.isRunning() != true || value != 7 + iteration ||\n\t\t\t\t\t\tTickClock::now() != wakeUpTimePoint + period * iteration)\n\t\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\n\t\t\/\/ restart periodic into periodic with different settings\n\t\t{\n\t\t\tconstexpr auto period = TickClock::duration{7};\n\n\t\t\twaitForNextTick();\n\t\t\tconst auto wakeUpTimePoint = TickClock::now() + TickClock::duration{5};\n\t\t\tif (softwareTimer.start(wakeUpTimePoint, period) != 0)\n\t\t\t\treturn false;\n\t\t\tif (softwareTimer.isRunning() != true || value != 10)\t\/\/ must be started, but may not execute yet\n\t\t\t\treturn false;\n\n\t\t\tfor (size_t iteration {}; iteration < 4; ++iteration)\n\t\t\t{\n\t\t\t\twhile (softwareTimer.isRunning() == true && value == 10 + iteration);\n\n\t\t\t\t\/\/ must be still running, function must be executed, wake up time point must equal what is expected\n\t\t\t\tif (softwareTimer.isRunning() != true || value != 11 + iteration ||\n\t\t\t\t\t\tTickClock::now() != wakeUpTimePoint + period * iteration)\n\t\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\n\t\t\/\/ restart periodic into one-shot\n\t\twaitForNextTick();\n\t\tconst auto wakeUpTimePoint = TickClock::now() + TickClock::duration{16};\n\t\tif (softwareTimer.start(wakeUpTimePoint) != 0)\n\t\t\treturn false;\n\t\tif (softwareTimer.isRunning() != true || value != 14)\t\/\/ must be started, but may not execute yet\n\t\t\treturn false;\n\n\t\twhile (softwareTimer.isRunning() == true);\n\n\t\t\/\/ must be stopped, function must be executed, wake up time point must equal what is expected\n\t\tif (softwareTimer.isRunning() != false || value != 15 || TickClock::now() != wakeUpTimePoint)\n\t\t\treturn false;\n\t}\n\n\treturn true;\n}\n\n}\t\/\/ namespace test\n\n}\t\/\/ namespace distortos\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (C) 2015-present ScyllaDB\n *\/\n\n\/*\n * This file is part of Scylla.\n *\n * Scylla is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * Scylla is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with Scylla. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n\n\n#include <boost\/test\/unit_test.hpp>\n#include <seastar\/testing\/test_case.hh>\n#include <seastar\/testing\/thread_test_case.hh>\n#include \"test\/boost\/sstable_test.hh\"\n#include <seastar\/core\/thread.hh>\n#include \"sstables\/sstables.hh\"\n#include \"test\/lib\/mutation_source_test.hh\"\n#include \"test\/lib\/sstable_utils.hh\"\n#include \"row_cache.hh\"\n#include \"test\/lib\/simple_schema.hh\"\n#include \"partition_slice_builder.hh\"\n#include \"test\/lib\/flat_mutation_reader_assertions.hh\"\n#include \"test\/lib\/random_utils.hh\"\n#include \"test\/lib\/random_schema.hh\"\n\nusing namespace sstables;\nusing namespace std::chrono_literals;\n\nstatic\nmutation_source make_sstable_mutation_source(sstables::test_env& env, schema_ptr s, sstring dir, std::vector<mutation> mutations,\n sstable_writer_config cfg, sstables::sstable::version_types version, gc_clock::time_point query_time = gc_clock::now()) {\n return as_mutation_source(make_sstable(env, s, dir, std::move(mutations), cfg, version, query_time));\n}\n\nstatic void consume_all(flat_mutation_reader& rd) {\n while (auto mfopt = rd().get0()) {}\n}\n\n\/\/ It is assumed that src won't change.\nstatic snapshot_source snapshot_source_from_snapshot(mutation_source src) {\n return snapshot_source([src = std::move(src)] {\n return src;\n });\n}\n\nstatic\nvoid test_cache_population_with_range_tombstone_adjacent_to_population_range(populate_fn_ex populate) {\n simple_schema s;\n tests::reader_concurrency_semaphore_wrapper semaphore;\n auto cache_mt = make_lw_shared<memtable>(s.schema());\n\n auto pkey = s.make_pkey();\n\n \/\/ underlying should not be empty, otherwise cache will make the whole range continuous\n mutation m1(s.schema(), pkey);\n s.add_row(m1, s.make_ckey(0), \"v1\");\n s.add_row(m1, s.make_ckey(1), \"v2\");\n s.add_row(m1, s.make_ckey(2), \"v3\");\n s.delete_range(m1, s.make_ckey_range(2, 100));\n cache_mt->apply(m1);\n\n cache_tracker tracker;\n auto ms = populate(s.schema(), std::vector<mutation>({m1}), gc_clock::now());\n row_cache cache(s.schema(), snapshot_source_from_snapshot(std::move(ms)), tracker);\n\n auto pr = dht::partition_range::make_singular(pkey);\n\n auto populate_range = [&] (int start) {\n auto slice = partition_slice_builder(*s.schema())\n .with_range(query::clustering_range::make_singular(s.make_ckey(start)))\n .build();\n auto rd = cache.make_reader(s.schema(), semaphore.make_permit(), pr, slice);\n auto close_rd = deferred_close(rd);\n consume_all(rd);\n };\n\n populate_range(2);\n\n \/\/ The cache now has only row with ckey 2 populated and the rest is discontinuous.\n \/\/ Populating reader which stops populating at entry with ckey 2 should not forget\n \/\/ to emit range_tombstone which starts at before(2).\n\n assert_that(cache.make_reader(s.schema(), semaphore.make_permit()))\n .produces(m1)\n .produces_end_of_stream();\n}\n\nstatic future<> test_sstable_conforms_to_mutation_source(sstable_version_types version, int index_block_size) {\n return sstables::test_env::do_with_async([version, index_block_size] (sstables::test_env& env) {\n sstable_writer_config cfg = env.manager().configure_writer();\n cfg.promoted_index_block_size = index_block_size;\n\n std::vector<tmpdir> dirs;\n auto populate = [&env, &dirs, &cfg, version] (schema_ptr s, const std::vector<mutation>& partitions,\n gc_clock::time_point query_time) -> mutation_source {\n dirs.emplace_back();\n return make_sstable_mutation_source(env, s, dirs.back().path().string(), partitions, cfg, version, query_time);\n };\n\n run_mutation_source_tests(populate);\n\n if (index_block_size == 1) {\n \/\/ The tests below are not sensitive to index bock size so run once.\n test_cache_population_with_range_tombstone_adjacent_to_population_range(populate);\n }\n });\n}\n\nstatic constexpr std::array<int, 3> block_sizes = { 1, 128, 64 * 1024 };\n\n\/\/ Split for better parallelizm\n\nSEASTAR_TEST_CASE(test_sstable_conforms_to_mutation_source_mc_tiny) {\n return test_sstable_conforms_to_mutation_source(writable_sstable_versions[0], block_sizes[0]);\n}\n\nSEASTAR_TEST_CASE(test_sstable_conforms_to_mutation_source_mc_medium) {\n return test_sstable_conforms_to_mutation_source(writable_sstable_versions[0], block_sizes[1]);\n}\n\nSEASTAR_TEST_CASE(test_sstable_conforms_to_mutation_source_mc_large) {\n return test_sstable_conforms_to_mutation_source(writable_sstable_versions[0], block_sizes[2]);\n}\n\nSEASTAR_TEST_CASE(test_sstable_conforms_to_mutation_source_md_tiny) {\n return test_sstable_conforms_to_mutation_source(writable_sstable_versions[1], block_sizes[0]);\n}\n\nSEASTAR_TEST_CASE(test_sstable_conforms_to_mutation_source_md_medium) {\n return test_sstable_conforms_to_mutation_source(writable_sstable_versions[1], block_sizes[1]);\n}\n\nSEASTAR_TEST_CASE(test_sstable_conforms_to_mutation_source_md_large) {\n return test_sstable_conforms_to_mutation_source(writable_sstable_versions[1], block_sizes[2]);\n}\n\n\/\/ This assert makes sure we don't miss writable vertions\nstatic_assert(writable_sstable_versions.size() == 2);\n\n\/\/ TODO: could probably be placed in random_utils\/random_schema after some tuning\nstatic std::vector<query::clustering_range> random_ranges(const std::vector<clustering_key> keys, const schema& s, std::mt19937& engine) {\n std::vector<clustering_key_prefix> ckp_sample;\n for (auto& k: keys) {\n auto exploded = k.explode(s);\n auto key_size = tests::random::get_int<size_t>(1, exploded.size(), engine);\n ckp_sample.push_back(clustering_key_prefix::from_exploded(s,\n std::vector<bytes>{exploded.begin(), exploded.begin() + key_size}));\n }\n\n auto subset_size = tests::random::get_int<size_t>(0, ckp_sample.size(), engine);\n ckp_sample = tests::random::random_subset<clustering_key_prefix>(std::move(ckp_sample), subset_size, engine);\n std::sort(ckp_sample.begin(), ckp_sample.end(), clustering_key_prefix::less_compare(s));\n\n std::vector<query::clustering_range> ranges;\n\n \/\/ (-inf, ...\n if (!ckp_sample.empty() && tests::random::get_bool(engine)) {\n ranges.emplace_back(\n std::nullopt,\n query::clustering_range::bound{ckp_sample.front(), tests::random::get_bool(engine)});\n std::swap(ckp_sample.front(), ckp_sample.back());\n ckp_sample.pop_back();\n }\n\n \/\/ ..., +inf)\n std::optional<query::clustering_range> last_range;\n if (!ckp_sample.empty() && tests::random::get_bool(engine)) {\n last_range.emplace(\n query::clustering_range::bound{ckp_sample.back(), tests::random::get_bool(engine)},\n std::nullopt);\n ckp_sample.pop_back();\n }\n\n for (unsigned i = 0; i + 1 < ckp_sample.size(); i += 2) {\n ranges.emplace_back(\n query::clustering_range::bound{ckp_sample[i], tests::random::get_bool(engine)},\n query::clustering_range::bound{ckp_sample[i+1], tests::random::get_bool(engine)});\n }\n\n if (last_range) {\n ranges.push_back(std::move(*last_range));\n }\n\n if (ranges.empty()) {\n \/\/ no keys sampled, return (-inf, +inf)\n ranges.push_back(query::clustering_range::make_open_ended_both_sides());\n }\n\n return ranges;\n}\n\nSEASTAR_THREAD_TEST_CASE(test_sstable_reversing_reader_random_schema) {\n \/\/ Create two sources: one by creating an sstable from a set of mutations,\n \/\/ and one by creating an sstable from the same set of mutations but reversed.\n \/\/ We query the first source in forward mode and the second in reversed mode.\n \/\/ The two queries should return the same result.\n\n auto random_spec = tests::make_random_schema_specification(get_name());\n auto random_schema = tests::random_schema{tests::random::get_int<uint32_t>(), *random_spec};\n testlog.debug(\"Random schema:\\n{}\", random_schema.cql());\n\n auto muts = tests::generate_random_mutations(random_schema).get();\n\n \/\/ FIXME: workaround for #9352. The index pages for reversed source would sometimes be different\n \/\/ from the forward source, causing one source to hit the bug from #9352 but not the other.\n muts.erase(std::remove_if(muts.begin(), muts.end(), [] (auto& m) { return m.decorated_key().token() == dht::token::from_int64(0); }));\n\n std::vector<mutation> reversed_muts;\n for (auto& m : muts) {\n reversed_muts.push_back(reverse(m));\n }\n\n sstables::test_env::do_with([\n s = random_schema.schema(), muts = std::move(muts), reversed_muts = std::move(reversed_muts),\n version = writable_sstable_versions[1]] (sstables::test_env& env) {\n\n std::vector<tmpdir> dirs;\n sstable_writer_config cfg = env.manager().configure_writer();\n\n for (auto index_block_size: block_sizes) {\n cfg.promoted_index_block_size = index_block_size;\n\n dirs.emplace_back();\n auto source = make_sstable_mutation_source(env, s, dirs.back().path().string(), muts, cfg, version);\n\n dirs.emplace_back();\n auto rev_source = make_sstable_mutation_source(env, s->make_reversed(), dirs.back().path().string(), reversed_muts, cfg, version);\n\n tests::reader_concurrency_semaphore_wrapper semaphore;\n\n std::mt19937 engine{tests::random::get_int<uint32_t>()};\n\n std::vector<clustering_key> keys;\n for (const auto& m: muts) {\n for (auto& r: m.partition().clustered_rows()) {\n keys.push_back(r.key());\n }\n }\n\n auto slice = partition_slice_builder(*s)\n .with_ranges(random_ranges(keys, *s, engine))\n .build();\n\n testlog.trace(\"Slice: {}\", slice);\n\n for (const auto& m: muts) {\n auto prange = dht::partition_range::make_singular(m.decorated_key());\n\n auto r1 = source.make_reader(s, semaphore.make_permit(), prange,\n slice, default_priority_class(), nullptr,\n streamed_mutation::forwarding::no, mutation_reader::forwarding::no);\n auto close_r1 = deferred_action([&r1] { r1.close().get(); });\n\n auto rev_slice = native_reverse_slice_to_legacy_reverse_slice(*s, slice);\n rev_slice.options.set(query::partition_slice::option::reversed);\n auto r2 = rev_source.make_reader(s, semaphore.make_permit(), prange,\n rev_slice, default_priority_class(), nullptr,\n streamed_mutation::forwarding::no, mutation_reader::forwarding::no);\n close_r1.cancel();\n\n compare_readers(*s, std::move(r1), std::move(r2));\n }\n }\n }).get();\n}\n<commit_msg>test: sstable_conforms_to_mutation_source_test: fix `vector::erase` call<commit_after>\/*\n * Copyright (C) 2015-present ScyllaDB\n *\/\n\n\/*\n * This file is part of Scylla.\n *\n * Scylla is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * Scylla is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with Scylla. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n\n\n#include <boost\/test\/unit_test.hpp>\n#include <seastar\/testing\/test_case.hh>\n#include <seastar\/testing\/thread_test_case.hh>\n#include \"test\/boost\/sstable_test.hh\"\n#include <seastar\/core\/thread.hh>\n#include \"sstables\/sstables.hh\"\n#include \"test\/lib\/mutation_source_test.hh\"\n#include \"test\/lib\/sstable_utils.hh\"\n#include \"row_cache.hh\"\n#include \"test\/lib\/simple_schema.hh\"\n#include \"partition_slice_builder.hh\"\n#include \"test\/lib\/flat_mutation_reader_assertions.hh\"\n#include \"test\/lib\/random_utils.hh\"\n#include \"test\/lib\/random_schema.hh\"\n\nusing namespace sstables;\nusing namespace std::chrono_literals;\n\nstatic\nmutation_source make_sstable_mutation_source(sstables::test_env& env, schema_ptr s, sstring dir, std::vector<mutation> mutations,\n sstable_writer_config cfg, sstables::sstable::version_types version, gc_clock::time_point query_time = gc_clock::now()) {\n return as_mutation_source(make_sstable(env, s, dir, std::move(mutations), cfg, version, query_time));\n}\n\nstatic void consume_all(flat_mutation_reader& rd) {\n while (auto mfopt = rd().get0()) {}\n}\n\n\/\/ It is assumed that src won't change.\nstatic snapshot_source snapshot_source_from_snapshot(mutation_source src) {\n return snapshot_source([src = std::move(src)] {\n return src;\n });\n}\n\nstatic\nvoid test_cache_population_with_range_tombstone_adjacent_to_population_range(populate_fn_ex populate) {\n simple_schema s;\n tests::reader_concurrency_semaphore_wrapper semaphore;\n auto cache_mt = make_lw_shared<memtable>(s.schema());\n\n auto pkey = s.make_pkey();\n\n \/\/ underlying should not be empty, otherwise cache will make the whole range continuous\n mutation m1(s.schema(), pkey);\n s.add_row(m1, s.make_ckey(0), \"v1\");\n s.add_row(m1, s.make_ckey(1), \"v2\");\n s.add_row(m1, s.make_ckey(2), \"v3\");\n s.delete_range(m1, s.make_ckey_range(2, 100));\n cache_mt->apply(m1);\n\n cache_tracker tracker;\n auto ms = populate(s.schema(), std::vector<mutation>({m1}), gc_clock::now());\n row_cache cache(s.schema(), snapshot_source_from_snapshot(std::move(ms)), tracker);\n\n auto pr = dht::partition_range::make_singular(pkey);\n\n auto populate_range = [&] (int start) {\n auto slice = partition_slice_builder(*s.schema())\n .with_range(query::clustering_range::make_singular(s.make_ckey(start)))\n .build();\n auto rd = cache.make_reader(s.schema(), semaphore.make_permit(), pr, slice);\n auto close_rd = deferred_close(rd);\n consume_all(rd);\n };\n\n populate_range(2);\n\n \/\/ The cache now has only row with ckey 2 populated and the rest is discontinuous.\n \/\/ Populating reader which stops populating at entry with ckey 2 should not forget\n \/\/ to emit range_tombstone which starts at before(2).\n\n assert_that(cache.make_reader(s.schema(), semaphore.make_permit()))\n .produces(m1)\n .produces_end_of_stream();\n}\n\nstatic future<> test_sstable_conforms_to_mutation_source(sstable_version_types version, int index_block_size) {\n return sstables::test_env::do_with_async([version, index_block_size] (sstables::test_env& env) {\n sstable_writer_config cfg = env.manager().configure_writer();\n cfg.promoted_index_block_size = index_block_size;\n\n std::vector<tmpdir> dirs;\n auto populate = [&env, &dirs, &cfg, version] (schema_ptr s, const std::vector<mutation>& partitions,\n gc_clock::time_point query_time) -> mutation_source {\n dirs.emplace_back();\n return make_sstable_mutation_source(env, s, dirs.back().path().string(), partitions, cfg, version, query_time);\n };\n\n run_mutation_source_tests(populate);\n\n if (index_block_size == 1) {\n \/\/ The tests below are not sensitive to index bock size so run once.\n test_cache_population_with_range_tombstone_adjacent_to_population_range(populate);\n }\n });\n}\n\nstatic constexpr std::array<int, 3> block_sizes = { 1, 128, 64 * 1024 };\n\n\/\/ Split for better parallelizm\n\nSEASTAR_TEST_CASE(test_sstable_conforms_to_mutation_source_mc_tiny) {\n return test_sstable_conforms_to_mutation_source(writable_sstable_versions[0], block_sizes[0]);\n}\n\nSEASTAR_TEST_CASE(test_sstable_conforms_to_mutation_source_mc_medium) {\n return test_sstable_conforms_to_mutation_source(writable_sstable_versions[0], block_sizes[1]);\n}\n\nSEASTAR_TEST_CASE(test_sstable_conforms_to_mutation_source_mc_large) {\n return test_sstable_conforms_to_mutation_source(writable_sstable_versions[0], block_sizes[2]);\n}\n\nSEASTAR_TEST_CASE(test_sstable_conforms_to_mutation_source_md_tiny) {\n return test_sstable_conforms_to_mutation_source(writable_sstable_versions[1], block_sizes[0]);\n}\n\nSEASTAR_TEST_CASE(test_sstable_conforms_to_mutation_source_md_medium) {\n return test_sstable_conforms_to_mutation_source(writable_sstable_versions[1], block_sizes[1]);\n}\n\nSEASTAR_TEST_CASE(test_sstable_conforms_to_mutation_source_md_large) {\n return test_sstable_conforms_to_mutation_source(writable_sstable_versions[1], block_sizes[2]);\n}\n\n\/\/ This assert makes sure we don't miss writable vertions\nstatic_assert(writable_sstable_versions.size() == 2);\n\n\/\/ TODO: could probably be placed in random_utils\/random_schema after some tuning\nstatic std::vector<query::clustering_range> random_ranges(const std::vector<clustering_key> keys, const schema& s, std::mt19937& engine) {\n std::vector<clustering_key_prefix> ckp_sample;\n for (auto& k: keys) {\n auto exploded = k.explode(s);\n auto key_size = tests::random::get_int<size_t>(1, exploded.size(), engine);\n ckp_sample.push_back(clustering_key_prefix::from_exploded(s,\n std::vector<bytes>{exploded.begin(), exploded.begin() + key_size}));\n }\n\n auto subset_size = tests::random::get_int<size_t>(0, ckp_sample.size(), engine);\n ckp_sample = tests::random::random_subset<clustering_key_prefix>(std::move(ckp_sample), subset_size, engine);\n std::sort(ckp_sample.begin(), ckp_sample.end(), clustering_key_prefix::less_compare(s));\n\n std::vector<query::clustering_range> ranges;\n\n \/\/ (-inf, ...\n if (!ckp_sample.empty() && tests::random::get_bool(engine)) {\n ranges.emplace_back(\n std::nullopt,\n query::clustering_range::bound{ckp_sample.front(), tests::random::get_bool(engine)});\n std::swap(ckp_sample.front(), ckp_sample.back());\n ckp_sample.pop_back();\n }\n\n \/\/ ..., +inf)\n std::optional<query::clustering_range> last_range;\n if (!ckp_sample.empty() && tests::random::get_bool(engine)) {\n last_range.emplace(\n query::clustering_range::bound{ckp_sample.back(), tests::random::get_bool(engine)},\n std::nullopt);\n ckp_sample.pop_back();\n }\n\n for (unsigned i = 0; i + 1 < ckp_sample.size(); i += 2) {\n ranges.emplace_back(\n query::clustering_range::bound{ckp_sample[i], tests::random::get_bool(engine)},\n query::clustering_range::bound{ckp_sample[i+1], tests::random::get_bool(engine)});\n }\n\n if (last_range) {\n ranges.push_back(std::move(*last_range));\n }\n\n if (ranges.empty()) {\n \/\/ no keys sampled, return (-inf, +inf)\n ranges.push_back(query::clustering_range::make_open_ended_both_sides());\n }\n\n return ranges;\n}\n\nSEASTAR_THREAD_TEST_CASE(test_sstable_reversing_reader_random_schema) {\n \/\/ Create two sources: one by creating an sstable from a set of mutations,\n \/\/ and one by creating an sstable from the same set of mutations but reversed.\n \/\/ We query the first source in forward mode and the second in reversed mode.\n \/\/ The two queries should return the same result.\n\n auto random_spec = tests::make_random_schema_specification(get_name());\n auto random_schema = tests::random_schema{tests::random::get_int<uint32_t>(), *random_spec};\n testlog.debug(\"Random schema:\\n{}\", random_schema.cql());\n\n auto muts = tests::generate_random_mutations(random_schema).get();\n\n \/\/ FIXME: workaround for #9352. The index pages for reversed source would sometimes be different\n \/\/ from the forward source, causing one source to hit the bug from #9352 but not the other.\n muts.erase(std::remove_if(muts.begin(), muts.end(), [] (auto& m) { return m.decorated_key().token() == dht::token::from_int64(0); }), muts.end());\n\n std::vector<mutation> reversed_muts;\n for (auto& m : muts) {\n reversed_muts.push_back(reverse(m));\n }\n\n sstables::test_env::do_with([\n s = random_schema.schema(), muts = std::move(muts), reversed_muts = std::move(reversed_muts),\n version = writable_sstable_versions[1]] (sstables::test_env& env) {\n\n std::vector<tmpdir> dirs;\n sstable_writer_config cfg = env.manager().configure_writer();\n\n for (auto index_block_size: block_sizes) {\n cfg.promoted_index_block_size = index_block_size;\n\n dirs.emplace_back();\n auto source = make_sstable_mutation_source(env, s, dirs.back().path().string(), muts, cfg, version);\n\n dirs.emplace_back();\n auto rev_source = make_sstable_mutation_source(env, s->make_reversed(), dirs.back().path().string(), reversed_muts, cfg, version);\n\n tests::reader_concurrency_semaphore_wrapper semaphore;\n\n std::mt19937 engine{tests::random::get_int<uint32_t>()};\n\n std::vector<clustering_key> keys;\n for (const auto& m: muts) {\n for (auto& r: m.partition().clustered_rows()) {\n keys.push_back(r.key());\n }\n }\n\n auto slice = partition_slice_builder(*s)\n .with_ranges(random_ranges(keys, *s, engine))\n .build();\n\n testlog.trace(\"Slice: {}\", slice);\n\n for (const auto& m: muts) {\n auto prange = dht::partition_range::make_singular(m.decorated_key());\n\n auto r1 = source.make_reader(s, semaphore.make_permit(), prange,\n slice, default_priority_class(), nullptr,\n streamed_mutation::forwarding::no, mutation_reader::forwarding::no);\n auto close_r1 = deferred_action([&r1] { r1.close().get(); });\n\n auto rev_slice = native_reverse_slice_to_legacy_reverse_slice(*s, slice);\n rev_slice.options.set(query::partition_slice::option::reversed);\n auto r2 = rev_source.make_reader(s, semaphore.make_permit(), prange,\n rev_slice, default_priority_class(), nullptr,\n streamed_mutation::forwarding::no, mutation_reader::forwarding::no);\n close_r1.cancel();\n\n compare_readers(*s, std::move(r1), std::move(r2));\n }\n }\n }).get();\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Monitor which expects a string on a TCP connection.\n *\n * author: Max Kellermann <mk@cm4all.com>\n *\/\n\n#include \"lb_expect_monitor.hxx\"\n#include \"lb_monitor.hxx\"\n#include \"lb_config.hxx\"\n#include \"pool.hxx\"\n#include \"async.hxx\"\n#include \"gerrno.h\"\n#include \"net\/ConnectSocket.hxx\"\n#include \"net\/SocketDescriptor.hxx\"\n#include \"net\/SocketAddress.hxx\"\n#include \"event\/Event.hxx\"\n#include \"event\/Callback.hxx\"\n\n#include <unistd.h>\n#include <sys\/socket.h>\n#include <string.h>\n#include <errno.h>\n\nstruct ExpectMonitor final : ConnectSocketHandler {\n struct pool &pool;\n const LbMonitorConfig &config;\n\n int fd;\n\n Event event;\n\n LbMonitorHandler &handler;\n\n struct async_operation_ref &async_ref;\n struct async_operation operation;\n\n ExpectMonitor(struct pool &_pool, const LbMonitorConfig &_config,\n LbMonitorHandler &_handler,\n async_operation_ref &_async_ref)\n :pool(_pool), config(_config),\n handler(_handler),\n async_ref(_async_ref) {}\n\n ExpectMonitor(const ExpectMonitor &other) = delete;\n\n void EventCallback(evutil_socket_t _fd, short events);\n\n void Abort();\n\n \/* virtual methods from class ConnectSocketHandler *\/\n void OnSocketConnectSuccess(SocketDescriptor &&fd) override;\n\n void OnSocketConnectTimeout() override {\n handler.Timeout();\n delete this;\n }\n\n void OnSocketConnectError(GError *error) override {\n handler.Error(error);\n delete this;\n }\n};\n\nstatic bool\ncheck_expectation(char *received, size_t received_length,\n const char *expect)\n{\n return g_strrstr_len(received, received_length, expect) != NULL;\n}\n\n\/*\n * async operation\n *\n *\/\n\ninline void\nExpectMonitor::Abort()\n{\n event.Delete();\n close(fd);\n pool_unref(&pool);\n delete this;\n}\n\n\/*\n * libevent callback\n *\n *\/\n\ninline void\nExpectMonitor::EventCallback(evutil_socket_t _fd, short events)\n{\n operation.Finished();\n\n if (events & EV_TIMEOUT) {\n close(fd);\n handler.Timeout();\n } else {\n char buffer[1024];\n\n ssize_t nbytes = recv(_fd, buffer, sizeof(buffer),\n MSG_DONTWAIT);\n if (nbytes < 0) {\n GError *error = new_error_errno();\n close(fd);\n handler.Error(error);\n } else if (!config.fade_expect.empty() &&\n check_expectation(buffer, nbytes,\n config.fade_expect.c_str())) {\n close(fd);\n handler.Fade();\n } else if (config.expect.empty() ||\n check_expectation(buffer, nbytes,\n config.expect.c_str())) {\n close(fd);\n handler.Success();\n } else {\n close(fd);\n GError *error = g_error_new_literal(g_file_error_quark(), 0,\n \"Expectation failed\");\n handler.Error(error);\n }\n }\n\n pool_unref(&pool);\n delete this;\n pool_commit();\n}\n\n\/*\n * client_socket handler\n *\n *\/\n\nvoid\nExpectMonitor::OnSocketConnectSuccess(SocketDescriptor &&new_fd)\n{\n if (!config.send.empty()) {\n ssize_t nbytes = send(new_fd.Get(), config.send.data(),\n config.send.length(),\n MSG_DONTWAIT);\n if (nbytes < 0) {\n GError *error = new_error_errno();\n handler.Error(error);\n return;\n }\n }\n\n struct timeval expect_timeout = {\n time_t(config.timeout > 0 ? config.timeout : 10),\n 0,\n };\n\n fd = new_fd.Steal();\n event.Set(fd, EV_READ|EV_TIMEOUT,\n MakeEventCallback(ExpectMonitor, EventCallback), this);\n event.Add(expect_timeout);\n\n operation.Init2<ExpectMonitor>();\n async_ref.Set(operation);\n\n pool_ref(&pool);\n}\n\n\/*\n * lb_monitor_class\n *\n *\/\n\nstatic void\nexpect_monitor_run(gcc_unused EventLoop &event_loop, struct pool &pool,\n const LbMonitorConfig &config,\n SocketAddress address,\n LbMonitorHandler &handler,\n struct async_operation_ref &async_ref)\n{\n ExpectMonitor *expect = new ExpectMonitor(pool, config,\n handler,\n async_ref);\n\n const unsigned connect_timeout = config.connect_timeout > 0\n ? config.connect_timeout\n : (config.timeout > 0\n ? config.timeout\n : 30);\n\n client_socket_new(pool, address.GetFamily(), SOCK_STREAM, 0,\n false,\n SocketAddress::Null(),\n address,\n connect_timeout,\n *expect, async_ref);\n}\n\nconst LbMonitorClass expect_monitor_class = {\n .run = expect_monitor_run,\n};\n<commit_msg>lb_expect_monitor: use class SocketEvent<commit_after>\/*\n * Monitor which expects a string on a TCP connection.\n *\n * author: Max Kellermann <mk@cm4all.com>\n *\/\n\n#include \"lb_expect_monitor.hxx\"\n#include \"lb_monitor.hxx\"\n#include \"lb_config.hxx\"\n#include \"pool.hxx\"\n#include \"async.hxx\"\n#include \"gerrno.h\"\n#include \"net\/ConnectSocket.hxx\"\n#include \"net\/SocketDescriptor.hxx\"\n#include \"net\/SocketAddress.hxx\"\n#include \"event\/SocketEvent.hxx\"\n\n#include <unistd.h>\n#include <sys\/socket.h>\n#include <string.h>\n#include <errno.h>\n\nstruct ExpectMonitor final : ConnectSocketHandler {\n struct pool &pool;\n const LbMonitorConfig &config;\n\n int fd;\n\n SocketEvent event;\n\n LbMonitorHandler &handler;\n\n struct async_operation_ref &async_ref;\n struct async_operation operation;\n\n ExpectMonitor(EventLoop &event_loop,\n struct pool &_pool, const LbMonitorConfig &_config,\n LbMonitorHandler &_handler,\n async_operation_ref &_async_ref)\n :pool(_pool), config(_config),\n event(event_loop, BIND_THIS_METHOD(EventCallback)),\n handler(_handler),\n async_ref(_async_ref) {}\n\n ExpectMonitor(const ExpectMonitor &other) = delete;\n\n void Abort();\n\n \/* virtual methods from class ConnectSocketHandler *\/\n void OnSocketConnectSuccess(SocketDescriptor &&fd) override;\n\n void OnSocketConnectTimeout() override {\n handler.Timeout();\n delete this;\n }\n\n void OnSocketConnectError(GError *error) override {\n handler.Error(error);\n delete this;\n }\n\nprivate:\n void EventCallback(short events);\n};\n\nstatic bool\ncheck_expectation(char *received, size_t received_length,\n const char *expect)\n{\n return g_strrstr_len(received, received_length, expect) != NULL;\n}\n\n\/*\n * async operation\n *\n *\/\n\ninline void\nExpectMonitor::Abort()\n{\n event.Delete();\n close(fd);\n pool_unref(&pool);\n delete this;\n}\n\n\/*\n * libevent callback\n *\n *\/\n\ninline void\nExpectMonitor::EventCallback(short events)\n{\n operation.Finished();\n\n if (events & EV_TIMEOUT) {\n close(fd);\n handler.Timeout();\n } else {\n char buffer[1024];\n\n ssize_t nbytes = recv(fd, buffer, sizeof(buffer),\n MSG_DONTWAIT);\n if (nbytes < 0) {\n GError *error = new_error_errno();\n close(fd);\n handler.Error(error);\n } else if (!config.fade_expect.empty() &&\n check_expectation(buffer, nbytes,\n config.fade_expect.c_str())) {\n close(fd);\n handler.Fade();\n } else if (config.expect.empty() ||\n check_expectation(buffer, nbytes,\n config.expect.c_str())) {\n close(fd);\n handler.Success();\n } else {\n close(fd);\n GError *error = g_error_new_literal(g_file_error_quark(), 0,\n \"Expectation failed\");\n handler.Error(error);\n }\n }\n\n pool_unref(&pool);\n delete this;\n pool_commit();\n}\n\n\/*\n * client_socket handler\n *\n *\/\n\nvoid\nExpectMonitor::OnSocketConnectSuccess(SocketDescriptor &&new_fd)\n{\n if (!config.send.empty()) {\n ssize_t nbytes = send(new_fd.Get(), config.send.data(),\n config.send.length(),\n MSG_DONTWAIT);\n if (nbytes < 0) {\n GError *error = new_error_errno();\n handler.Error(error);\n return;\n }\n }\n\n struct timeval expect_timeout = {\n time_t(config.timeout > 0 ? config.timeout : 10),\n 0,\n };\n\n fd = new_fd.Steal();\n event.Set(fd, EV_READ|EV_TIMEOUT);\n event.Add(expect_timeout);\n\n operation.Init2<ExpectMonitor>();\n async_ref.Set(operation);\n\n pool_ref(&pool);\n}\n\n\/*\n * lb_monitor_class\n *\n *\/\n\nstatic void\nexpect_monitor_run(EventLoop &event_loop, struct pool &pool,\n const LbMonitorConfig &config,\n SocketAddress address,\n LbMonitorHandler &handler,\n struct async_operation_ref &async_ref)\n{\n ExpectMonitor *expect = new ExpectMonitor(event_loop, pool, config,\n handler,\n async_ref);\n\n const unsigned connect_timeout = config.connect_timeout > 0\n ? config.connect_timeout\n : (config.timeout > 0\n ? config.timeout\n : 30);\n\n client_socket_new(pool, address.GetFamily(), SOCK_STREAM, 0,\n false,\n SocketAddress::Null(),\n address,\n connect_timeout,\n *expect, async_ref);\n}\n\nconst LbMonitorClass expect_monitor_class = {\n .run = expect_monitor_run,\n};\n<|endoftext|>"} {"text":"<commit_before>#pragma once\n\n#include <gmock\/gmock.h>\n\n#if defined(__MINGW32__) || defined(__CYGWIN__)\n\t#define _GLAPI extern\n#else\n\t#define _GLAPI __declspec(dllexport)\n#endif\n#define GLAPI _GLAPI\n#include <GL\/glew.h>\n#define GLAPI _GLAPI\n\n#include <memory>\n\nclass GLMock {\npublic:\n\tstatic std::shared_ptr<GLMock> getSingleton();\n\tstatic std::shared_ptr<GLMock> _singleton;\n\n\tGLMock();\n\t~GLMock();\n\tMOCK_METHOD2(glBindTextureMock, void(GLenum target, GLuint texture));\n\tMOCK_METHOD1(glEnableVertexAttribArrayMock, void(GLuint arg0));\n\tMOCK_METHOD2(glGetAttribLocationMock, int(GLuint program, const GLchar* name));\n\tMOCK_METHOD2(glGetIntegervMock, void(GLenum pname, GLint* params));\n\tMOCK_METHOD2(glGenTexturesMock, void(GLsizei n, GLuint* textures));\n\tMOCK_METHOD6(glVertexAttribPointerMock, void(GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, const GLvoid* pointer));\n\tMOCK_METHOD9(glTexImage2DMock, void(GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, const GLvoid* pixels));\n\tMOCK_METHOD3(glTexParameteriMock, void(GLenum target, GLenum pname, GLint param));\n};\n<commit_msg>Fix non-Windows builds<commit_after>#pragma once\n\n#include <gmock\/gmock.h>\n\n#if defined(_WIN32)\n #if defined(__MINGW32__) || defined(__CYGWIN__)\n #define _GLAPI extern\n #else\n #define _GLAPI __declspec(dllexport)\n #endif\n#else\n #define _GLAPI extern\n#endif\n#define GLAPI _GLAPI\n#include <GL\/glew.h>\n#define GLAPI _GLAPI\n\n#include <memory>\n\nclass GLMock {\npublic:\n\tstatic std::shared_ptr<GLMock> getSingleton();\n\tstatic std::shared_ptr<GLMock> _singleton;\n\n\tGLMock();\n\t~GLMock();\n\tMOCK_METHOD2(glBindTextureMock, void(GLenum target, GLuint texture));\n\tMOCK_METHOD1(glEnableVertexAttribArrayMock, void(GLuint arg0));\n\tMOCK_METHOD2(glGetAttribLocationMock, int(GLuint program, const GLchar* name));\n\tMOCK_METHOD2(glGetIntegervMock, void(GLenum pname, GLint* params));\n\tMOCK_METHOD2(glGenTexturesMock, void(GLsizei n, GLuint* textures));\n\tMOCK_METHOD6(glVertexAttribPointerMock, void(GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, const GLvoid* pointer));\n\tMOCK_METHOD9(glTexImage2DMock, void(GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, const GLvoid* pixels));\n\tMOCK_METHOD3(glTexParameteriMock, void(GLenum target, GLenum pname, GLint param));\n};\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ libavg - Media Playback Engine. \n\/\/ Copyright (C) 2003-2012 Ulrich von Zadow\n\/\/\n\/\/ This library is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU Lesser General Public\n\/\/ License as published by the Free Software Foundation; either\n\/\/ version 2 of the License, or (at your option) any later version.\n\/\/\n\/\/ This library is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ Lesser General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License along with this library; if not, write to the Free Software\n\/\/ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n\/\/\n\/\/ Current versions can be found at www.libavg.de\n\n#include \"StandardLogSink.h\"\n#include \"Logger.h\"\n\n#include <iostream>\n#include <iomanip>\n\nusing namespace std;\n\nnamespace avg\n{\n\nStandardLogSink::StandardLogSink()\n{\n\n}\n\nStandardLogSink::~StandardLogSink()\n{\n\n}\n\nvoid StandardLogSink::logMessage(const tm* pTime, unsigned millis,\n const category_t& category, severity_t severity, const UTF8String& sMsg)\n{\n char timeString[256];\n strftime(timeString, sizeof(timeString), \"%y-%m-%d %H:%M:%S\", pTime);\n cerr << \"[\" << timeString << \".\" << \n setw(3) << setfill('0') << millis << setw(0) << \"][\";\n cerr << setw(8) << setfill('.') << Logger::severityToString(severity) << \"][\";\n cerr << setw(13) << setfill('.') << category << \"] : \" << sMsg << endl;\n cerr.flush();\n}\n\n}\n<commit_msg>Shorter log messages.<commit_after>\/\/\n\/\/ libavg - Media Playback Engine. \n\/\/ Copyright (C) 2003-2012 Ulrich von Zadow\n\/\/\n\/\/ This library is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU Lesser General Public\n\/\/ License as published by the Free Software Foundation; either\n\/\/ version 2 of the License, or (at your option) any later version.\n\/\/\n\/\/ This library is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ Lesser General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License along with this library; if not, write to the Free Software\n\/\/ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n\/\/\n\/\/ Current versions can be found at www.libavg.de\n\n#include \"StandardLogSink.h\"\n#include \"Logger.h\"\n\n#include <iostream>\n#include <iomanip>\n\nusing namespace std;\n\nnamespace avg\n{\n\nStandardLogSink::StandardLogSink()\n{\n\n}\n\nStandardLogSink::~StandardLogSink()\n{\n\n}\n\nvoid StandardLogSink::logMessage(const tm* pTime, unsigned millis,\n const category_t& category, severity_t severity, const UTF8String& sMsg)\n{\n char timeString[256];\n strftime(timeString, sizeof(timeString), \"%y-%m-%d %H:%M:%S\", pTime);\n cerr << \"[\" << timeString << \".\" << \n setw(3) << setfill('0') << millis << setw(0) << \"][\";\n cerr << setw(4) << setfill('.') << Logger::severityToString(severity) << \"][\";\n cerr << setw(9) << setfill('.') << category << \"] : \" << sMsg << endl;\n cerr.flush();\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n#include <unordered_set>\n#include <sstream>\n#include <fstream>\n\n#include <getopt.h>\n\n#include \"simhash.h\"\n\nvoid usage(int argc, char** argv)\n{\n std::cout << \"usage: \" << argv[0]\n << \" --blocks BLOCKS\"\n << \" --distance DISTANCE\"\n << \" --input INPUT\"\n << \" --output OUTPUT\\n\\n\"\n << \"Read simhashes from input, find all pairs within distance bits of \\n\"\n << \"each other, writing them to output. The endianness of the output is \\n\"\n << \"the same as that of the input.\\n\\n\"\n << \" --blocks BLOCKS Number of bit blocks to use\\n\"\n << \" --distance DISTANCE Maximum bit distances of matches\\n\"\n << \" --input INPUT Path to input ('-' for stdin)\\n\"\n << \" --output OUTPUT Path to output ('-' for stdout)\\n\";\n}\n\nstd::unordered_set<Simhash::hash_t> read_hashes(std::istream& stream)\n{\n std::unordered_set<Simhash::hash_t> hashes;\n Simhash::hash_t hash(0);\n while (!stream.eof())\n {\n stream.read(reinterpret_cast<char*>(&hash), sizeof(hash));\n if (!stream.fail())\n {\n hashes.insert(hash);\n }\n else\n {\n break;\n }\n }\n return hashes;\n}\n\nvoid write_matches(std::ostream& stream, const Simhash::matches_t& matches)\n{\n for (auto it = matches.begin(); it != matches.end() && !std::cout.fail(); ++it)\n {\n stream.write(\n reinterpret_cast<const char*>(&(it->first)), sizeof(Simhash::hash_t));\n stream.write(\n reinterpret_cast<const char*>(&(it->second)), sizeof(Simhash::hash_t));\n }\n stream.flush();\n}\n\nint main(int argc, char **argv) {\n\n std::string input, output;\n size_t blocks(0), distance(0);\n\n int getopt_return_value(0);\n while (getopt_return_value != -1)\n {\n int option_index = 0;\n static struct option long_options[] = {\n {\"input\", required_argument, 0, 0 },\n {\"output\", required_argument, 0, 0 },\n {\"blocks\", required_argument, 0, 0 },\n {\"distance\", required_argument, 0, 0 },\n {\"help\", no_argument, 0, 0 },\n {0, 0, 0, 0 }\n };\n\n getopt_return_value = getopt_long(\n argc, argv, \"i:o:b:d:h\", long_options, &option_index);\n\n switch(getopt_return_value)\n {\n case 0:\n switch(option_index)\n {\n case 0:\n input = optarg;\n break;\n case 1:\n output = optarg;\n break;\n case 2:\n std::stringstream(std::string(optarg)) >> blocks;\n break;\n case 3:\n std::stringstream(std::string(optarg)) >> distance;\n break;\n case 4:\n usage(argc, argv);\n return 0;\n }\n break;\n case 'i':\n input = optarg;\n break;\n case 'o':\n output = optarg;\n break;\n case 'b':\n std::stringstream(std::string(optarg)) >> blocks;\n break;\n case 'd':\n std::stringstream(std::string(optarg)) >> distance;\n break;\n case 'h':\n usage(argc, argv);\n return 0;\n case '?':\n return 1;\n }\n\n }\n\n if (blocks == 0)\n {\n std::cerr << \"Blocks must be provided and > 0\" << std::endl;\n return 2;\n }\n\n if (distance == 0)\n {\n std::cerr << \"Distance must be provided and > 0\" << std::endl;\n return 3;\n }\n\n if (input.empty())\n {\n std::cerr << \"Input must be provided and non-empty.\" << std::endl;\n return 4;\n }\n\n if (output.empty())\n {\n std::cerr << \"Output must be provided and non-empty.\" << std::endl;\n return 5;\n }\n\n if (blocks <= distance)\n {\n std::cerr << \"Blocks (\" << blocks << \") must be >= distance (\" << distance << \")\"\n << std::endl;\n return 6;\n }\n\n \/\/ Read input\n std::unordered_set<Simhash::hash_t> hashes;\n if (input.compare(\"-\") == 0)\n {\n std::cerr << \"Reading hashes from stdin.\" << std::endl;\n hashes = read_hashes(std::cin);\n }\n else\n {\n std::cerr << \"Reading hashes from \" << input << std::endl;\n {\n std::ifstream fin(input, std::ifstream::in | std::ifstream::binary);\n if (!fin.good())\n {\n std::cerr << \"Error reading \" << input << std::endl;\n return 7;\n }\n hashes = read_hashes(fin);\n }\n }\n\n \/\/ Find matches\n std::cerr << \"Computing matches...\" << std::endl;\n Simhash::matches_t results = Simhash::find_all(hashes, blocks, distance);\n\n \/\/ Write output\n if (output.compare(\"-\") == 0)\n {\n std::cerr << \"Writing results to stdout.\" << std::endl;\n write_matches(std::cout, results);\n }\n else\n {\n std::cerr << \"Writing matches to \" << output << std::endl;\n {\n std::ofstream fout(output, std::ofstream::binary);\n if (!fout.good())\n {\n std::cerr << \"Error writing \" << output << std::endl;\n return 8;\n }\n write_matches(fout, results);\n }\n }\n\n return 0;\n}\n<commit_msg>Changed interface to simhash-find-all to be JSON in and out.<commit_after>#include <iostream>\n#include <unordered_set>\n#include <sstream>\n#include <fstream>\n\n#include <getopt.h>\n\n#include \"simhash.h\"\n\nvoid usage(int argc, char** argv)\n{\n std::cout << \"usage: \" << argv[0]\n << \" --blocks BLOCKS\"\n << \" --distance DISTANCE\"\n << \" --input INPUT\"\n << \" --output OUTPUT\\n\\n\"\n << \"Read simhashes from input, find all pairs within distance bits of \\n\"\n << \"each other, writing them to output. The endianness of the output is \\n\"\n << \"the same as that of the input.\\n\\n\"\n << \" --blocks BLOCKS Number of bit blocks to use\\n\"\n << \" --distance DISTANCE Maximum bit distances of matches\\n\"\n << \" --input INPUT Path to input ('-' for stdin)\\n\"\n << \" --output OUTPUT Path to output ('-' for stdout)\\n\";\n}\n\nstd::unordered_set<Simhash::hash_t> read_hashes(std::istream& stream)\n{\n std::unordered_set<Simhash::hash_t> hashes;\n for (std::string line; std::getline(stream, line); )\n {\n hashes.insert(std::stoull(line));\n }\n return hashes;\n}\n\nvoid write_matches(std::ostream& stream, const Simhash::matches_t& matches)\n{\n for (auto it = matches.begin(); it != matches.end() && !std::cout.fail(); ++it)\n {\n stream << \"[\" << it->first << \", \" << it->second << \"]\\n\";\n }\n stream.flush();\n}\n\nint main(int argc, char **argv) {\n\n std::string input, output;\n size_t blocks(0), distance(0);\n\n int getopt_return_value(0);\n while (getopt_return_value != -1)\n {\n int option_index = 0;\n static struct option long_options[] = {\n {\"input\", required_argument, 0, 0 },\n {\"output\", required_argument, 0, 0 },\n {\"blocks\", required_argument, 0, 0 },\n {\"distance\", required_argument, 0, 0 },\n {\"help\", no_argument, 0, 0 },\n {0, 0, 0, 0 }\n };\n\n getopt_return_value = getopt_long(\n argc, argv, \"i:o:b:d:h\", long_options, &option_index);\n\n switch(getopt_return_value)\n {\n case 0:\n switch(option_index)\n {\n case 0:\n input = optarg;\n break;\n case 1:\n output = optarg;\n break;\n case 2:\n std::stringstream(std::string(optarg)) >> blocks;\n break;\n case 3:\n std::stringstream(std::string(optarg)) >> distance;\n break;\n case 4:\n usage(argc, argv);\n return 0;\n }\n break;\n case 'i':\n input = optarg;\n break;\n case 'o':\n output = optarg;\n break;\n case 'b':\n std::stringstream(std::string(optarg)) >> blocks;\n break;\n case 'd':\n std::stringstream(std::string(optarg)) >> distance;\n break;\n case 'h':\n usage(argc, argv);\n return 0;\n case '?':\n return 1;\n }\n\n }\n\n if (blocks == 0)\n {\n std::cerr << \"Blocks must be provided and > 0\" << std::endl;\n return 2;\n }\n\n if (distance == 0)\n {\n std::cerr << \"Distance must be provided and > 0\" << std::endl;\n return 3;\n }\n\n if (input.empty())\n {\n std::cerr << \"Input must be provided and non-empty.\" << std::endl;\n return 4;\n }\n\n if (output.empty())\n {\n std::cerr << \"Output must be provided and non-empty.\" << std::endl;\n return 5;\n }\n\n if (blocks <= distance)\n {\n std::cerr << \"Blocks (\" << blocks << \") must be >= distance (\" << distance << \")\"\n << std::endl;\n return 6;\n }\n\n \/\/ Read input\n std::unordered_set<Simhash::hash_t> hashes;\n if (input.compare(\"-\") == 0)\n {\n std::cerr << \"Reading hashes from stdin.\" << std::endl;\n hashes = read_hashes(std::cin);\n }\n else\n {\n std::cerr << \"Reading hashes from \" << input << std::endl;\n {\n std::ifstream fin(input, std::ifstream::in | std::ifstream::binary);\n if (!fin.good())\n {\n std::cerr << \"Error reading \" << input << std::endl;\n return 7;\n }\n hashes = read_hashes(fin);\n }\n }\n\n \/\/ Find matches\n std::cerr << \"Computing matches...\" << std::endl;\n Simhash::matches_t results = Simhash::find_all(hashes, blocks, distance);\n\n \/\/ Write output\n if (output.compare(\"-\") == 0)\n {\n std::cerr << \"Writing results to stdout.\" << std::endl;\n write_matches(std::cout, results);\n }\n else\n {\n std::cerr << \"Writing matches to \" << output << std::endl;\n {\n std::ofstream fout(output, std::ofstream::binary);\n if (!fout.good())\n {\n std::cerr << \"Error writing \" << output << std::endl;\n return 8;\n }\n write_matches(fout, results);\n }\n }\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/****************************************************************************\n**\n** Copyright (c) 2011 libmv authors.\n**\n** Permission is hereby granted, free of charge, to any person obtaining a copy\n** of this software and associated documentation files (the \"Software\"), to\n** deal in the Software without restriction, including without limitation the\n** rights to use, copy, modify, merge, publish, distribute, sublicense, and\/or\n** sell copies of the Software, and to permit persons to whom the Software is\n** furnished to do so, subject to the following conditions:\n**\n** The above copyright notice and this permission notice shall be included in\n** all copies or substantial portions of the Software.\n**\n** THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n** IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n** FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n** AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n** LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n** FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n** IN THE SOFTWARE.\n**\n****************************************************************************\/\n\n#include \"libmv\/tracking\/sad.h\"\n#include <stdlib.h>\n#include <math.h>\n\nnamespace libmv {\n\nvoid LaplaceFilter(ubyte* src, ubyte* dst, int width, int height, int strength) {\n for(int y=1; y<height-1; y++) for(int x=1; x<width-1; x++) {\n const ubyte* s = &src[y*width+x];\n int l = 128 +\n s[-width-1] + s[-width] + s[-width+1] +\n s[1] - 8*s[0] + s[1] +\n s[ width-1] + s[ width] + s[ width+1] ;\n int d = ((256-strength)*s[0] + strength*l) \/ 256;\n if(d < 0) d=0;\n if(d > 255) d=255;\n dst[y*width+x] = d;\n }\n}\n\nstruct vec2 {\n float x,y;\n inline vec2(float x, float y):x(x),y(y){}\n};\ninline vec2 operator*(mat32 m, vec2 v) {\n return vec2(v.x*m(0,0)+v.y*m(0,1)+m(0,2),v.x*m(1,0)+v.y*m(1,1)+m(1,2));\n}\n\n\/\/! fixed point bilinear sample with precision k\ntemplate <int k> inline int sample(const ubyte* image,int stride, int x, int y, int u, int v) {\n const ubyte* s = &image[y*stride+x];\n return ((s[ 0] * (k-u) + s[ 1] * u) * (k-v)\n + (s[stride] * (k-u) + s[stride+1] * u) * ( v) ) \/ (k*k);\n}\n\n#ifdef __SSE__\n#include <xmmintrin.h>\nint lround(float x) { return _mm_cvtss_si32(_mm_set_ss(x)); }\n#elif defined(_MSC_VER)\nint lround(float x) { return x+0.5; }\n#endif\n\n\/\/TODO(MatthiasF): SSE optimization\nvoid SamplePattern(ubyte* image, int stride, mat32 warp, ubyte* pattern, int size) {\n const int k = 256;\n for (int i = 0; i < size; i++) for (int j = 0; j < size; j++) {\n vec2 p = warp*vec2(j-size\/2,i-size\/2);\n int fx = lround(p.x*k), fy = lround(p.y*k);\n int ix = fx\/k, iy = fy\/k;\n int u = fx%k, v = fy%k;\n pattern[i*size+j] = sample<k>(image,stride,ix,iy,u,v);\n }\n}\n\n#ifdef __SSE2__\n#include <emmintrin.h>\nstatic uint SAD(const ubyte* pattern, const ubyte* image, int stride, int size) {\n __m128i a = _mm_setzero_si128();\n for(int i = 0; i < size; i++) {\n for(int j = 0; j < size\/16; j++) {\n a = _mm_adds_epu16(a, _mm_sad_epu8( _mm_loadu_si128((__m128i*)(pattern+i*size+j*16)),\n _mm_loadu_si128((__m128i*)(image+i*stride+j*16))));\n }\n }\n return _mm_extract_epi16(a,0) + _mm_extract_epi16(a,4);\n}\n#else\nstatic uint SAD(const ubyte* pattern, const ubyte* image, int stride, int size) {\n uint sad=0;\n for(int i = 0; i < size; i++) {\n for(int j = 0; j < size; j++) {\n sad += abs((int)pattern[i*size+j] - image[i*stride+j]);\n }\n }\n return sad;\n}\n#endif\n\nfloat sq(float x) { return x*x; }\nfloat Track(ubyte* reference, ubyte* warped, int size, ubyte* image, int stride, int w, int h, mat32* warp, float areaPenalty, float conditionPenalty) {\n mat32 m=*warp;\n uint min=-1;\n\n \/\/ exhaustive search integer pixel translation\n int ix = m(0,2), iy = m(1,2);\n for(int y = size\/2; y < h-size\/2; y++) {\n for(int x = size\/2; x < w-size\/2; x++) {\n m(0,2) = x, m(1,2) = y;\n uint sad = SAD(warped,&image[(y-size\/2)*stride+(x-size\/2)],stride,size);\n \/\/ TODO: using chroma could help disambiguate some cases\n if(sad < min) {\n min = sad;\n ix = x, iy = y;\n }\n }\n }\n m(0,2) = ix, m(1,2) = iy;\n min=-1; \/\/reset score since direct warped search match too well (but the wrong pattern).\n\n \/\/ 6D coordinate descent to find affine transform\n ubyte match = new ubyte[size*size];\n float step = 0.5;\n for(int p = 0; p < 8; p++) { \/\/foreach precision level\n for(int i = 0; i < 2; i++) { \/\/ iterate twice per precision level\n \/\/TODO: other sweep pattern might converge better\n for(int d=0; d < 6; d++) { \/\/ iterate dimension sequentially (cyclic descent)\n for(float x = -step; x <= step; x+=step) { \/\/solve subproblem (evaluate only along one coordinate)\n mat32 t = m;\n t.data[d] += x;\n \/\/TODO: better performance would also allow a more exhaustive search\n SamplePattern(image,stride,t,match,size);\n uint sad = SAD(reference,match,size,size);\n \/\/ regularization: keep constant area and good condition\n float area = t(0,0)*t(1,1)-t(0,1)*t(1,0);\n float x = sq(t(0,0))+sq(t(0,1)), y = sq(t(1,0))+sq(t(1,1));\n float condition = x>y ? x\/y : y\/x;\n sad += size*size*( areaPenalty*sq(area-1) + conditionPenalty*sq(condition-1) );\n if(sad < min) {\n min = sad;\n m = t;\n }\n }\n }\n }\n step \/= 2;\n }\n *warp = m;\n\n \/\/ Compute Pearson product-moment correlation coefficient\n uint sX=0,sY=0,sXX=0,sYY=0,sXY=0;\n SamplePattern(image,stride,m,match,size);\n SAD(reference,match,size,size);\n for(int i = 0; i < size; i++) {\n for(int j = 0; j < size; j++) {\n int x = reference[i*size+j];\n int y = match[i*size+j];\n sX += x;\n sY += y;\n sXX += x*x;\n sYY += y*y;\n sXY += x*y;\n }\n }\n delete[] match;\n const int N = size*size;\n sX \/= N, sY \/= N, sXX \/= N, sYY \/= N, sXY \/= N;\n return (sXY-sX*sY)\/sqrt(float((sXX-sX*sX)*(sYY-sY*sY)));\n}\n\n} \/\/ namespace libmv\n<commit_msg>sqrt takes double precision.<commit_after>\/****************************************************************************\n**\n** Copyright (c) 2011 libmv authors.\n**\n** Permission is hereby granted, free of charge, to any person obtaining a copy\n** of this software and associated documentation files (the \"Software\"), to\n** deal in the Software without restriction, including without limitation the\n** rights to use, copy, modify, merge, publish, distribute, sublicense, and\/or\n** sell copies of the Software, and to permit persons to whom the Software is\n** furnished to do so, subject to the following conditions:\n**\n** The above copyright notice and this permission notice shall be included in\n** all copies or substantial portions of the Software.\n**\n** THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n** IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n** FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n** AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n** LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n** FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n** IN THE SOFTWARE.\n**\n****************************************************************************\/\n\n#include \"libmv\/tracking\/sad.h\"\n#include <stdlib.h>\n#include <math.h>\n\nnamespace libmv {\n\nvoid LaplaceFilter(ubyte* src, ubyte* dst, int width, int height, int strength) {\n for(int y=1; y<height-1; y++) for(int x=1; x<width-1; x++) {\n const ubyte* s = &src[y*width+x];\n int l = 128 +\n s[-width-1] + s[-width] + s[-width+1] +\n s[1] - 8*s[0] + s[1] +\n s[ width-1] + s[ width] + s[ width+1] ;\n int d = ((256-strength)*s[0] + strength*l) \/ 256;\n if(d < 0) d=0;\n if(d > 255) d=255;\n dst[y*width+x] = d;\n }\n}\n\nstruct vec2 {\n float x,y;\n inline vec2(float x, float y):x(x),y(y){}\n};\ninline vec2 operator*(mat32 m, vec2 v) {\n return vec2(v.x*m(0,0)+v.y*m(0,1)+m(0,2),v.x*m(1,0)+v.y*m(1,1)+m(1,2));\n}\n\n\/\/! fixed point bilinear sample with precision k\ntemplate <int k> inline int sample(const ubyte* image,int stride, int x, int y, int u, int v) {\n const ubyte* s = &image[y*stride+x];\n return ((s[ 0] * (k-u) + s[ 1] * u) * (k-v)\n + (s[stride] * (k-u) + s[stride+1] * u) * ( v) ) \/ (k*k);\n}\n\n#ifdef __SSE__\n#include <xmmintrin.h>\nint lround(float x) { return _mm_cvtss_si32(_mm_set_ss(x)); }\n#elif defined(_MSC_VER)\nint lround(float x) { return x+0.5; }\n#endif\n\n\/\/TODO(MatthiasF): SSE optimization\nvoid SamplePattern(ubyte* image, int stride, mat32 warp, ubyte* pattern, int size) {\n const int k = 256;\n for (int i = 0; i < size; i++) for (int j = 0; j < size; j++) {\n vec2 p = warp*vec2(j-size\/2,i-size\/2);\n int fx = lround(p.x*k), fy = lround(p.y*k);\n int ix = fx\/k, iy = fy\/k;\n int u = fx%k, v = fy%k;\n pattern[i*size+j] = sample<k>(image,stride,ix,iy,u,v);\n }\n}\n\n#ifdef __SSE2__\n#include <emmintrin.h>\nstatic uint SAD(const ubyte* pattern, const ubyte* image, int stride, int size) {\n __m128i a = _mm_setzero_si128();\n for(int i = 0; i < size; i++) {\n for(int j = 0; j < size\/16; j++) {\n a = _mm_adds_epu16(a, _mm_sad_epu8( _mm_loadu_si128((__m128i*)(pattern+i*size+j*16)),\n _mm_loadu_si128((__m128i*)(image+i*stride+j*16))));\n }\n }\n return _mm_extract_epi16(a,0) + _mm_extract_epi16(a,4);\n}\n#else\nstatic uint SAD(const ubyte* pattern, const ubyte* image, int stride, int size) {\n uint sad=0;\n for(int i = 0; i < size; i++) {\n for(int j = 0; j < size; j++) {\n sad += abs((int)pattern[i*size+j] - image[i*stride+j]);\n }\n }\n return sad;\n}\n#endif\n\nfloat sq(float x) { return x*x; }\nfloat Track(ubyte* reference, ubyte* warped, int size, ubyte* image, int stride, int w, int h, mat32* warp, float areaPenalty, float conditionPenalty) {\n mat32 m=*warp;\n uint min=-1;\n\n \/\/ exhaustive search integer pixel translation\n int ix = m(0,2), iy = m(1,2);\n for(int y = size\/2; y < h-size\/2; y++) {\n for(int x = size\/2; x < w-size\/2; x++) {\n m(0,2) = x, m(1,2) = y;\n uint sad = SAD(warped,&image[(y-size\/2)*stride+(x-size\/2)],stride,size);\n \/\/ TODO: using chroma could help disambiguate some cases\n if(sad < min) {\n min = sad;\n ix = x, iy = y;\n }\n }\n }\n m(0,2) = ix, m(1,2) = iy;\n min=-1; \/\/reset score since direct warped search match too well (but the wrong pattern).\n\n \/\/ 6D coordinate descent to find affine transform\n ubyte match = new ubyte[size*size];\n float step = 0.5;\n for(int p = 0; p < 8; p++) { \/\/foreach precision level\n for(int i = 0; i < 2; i++) { \/\/ iterate twice per precision level\n \/\/TODO: other sweep pattern might converge better\n for(int d=0; d < 6; d++) { \/\/ iterate dimension sequentially (cyclic descent)\n for(float x = -step; x <= step; x+=step) { \/\/solve subproblem (evaluate only along one coordinate)\n mat32 t = m;\n t.data[d] += x;\n \/\/TODO: better performance would also allow a more exhaustive search\n SamplePattern(image,stride,t,match,size);\n uint sad = SAD(reference,match,size,size);\n \/\/ regularization: keep constant area and good condition\n float area = t(0,0)*t(1,1)-t(0,1)*t(1,0);\n float x = sq(t(0,0))+sq(t(0,1)), y = sq(t(1,0))+sq(t(1,1));\n float condition = x>y ? x\/y : y\/x;\n sad += size*size*( areaPenalty*sq(area-1) + conditionPenalty*sq(condition-1) );\n if(sad < min) {\n min = sad;\n m = t;\n }\n }\n }\n }\n step \/= 2;\n }\n *warp = m;\n\n \/\/ Compute Pearson product-moment correlation coefficient\n uint sX=0,sY=0,sXX=0,sYY=0,sXY=0;\n SamplePattern(image,stride,m,match,size);\n SAD(reference,match,size,size);\n for(int i = 0; i < size; i++) {\n for(int j = 0; j < size; j++) {\n int x = reference[i*size+j];\n int y = match[i*size+j];\n sX += x;\n sY += y;\n sXX += x*x;\n sYY += y*y;\n sXY += x*y;\n }\n }\n delete[] match;\n const int N = size*size;\n sX \/= N, sY \/= N, sXX \/= N, sYY \/= N, sXY \/= N;\n return (sXY-sX*sY)\/sqrt(double((sXX-sX*sX)*(sYY-sY*sY)));\n}\n\n} \/\/ namespace libmv\n<|endoftext|>"} {"text":"<commit_before>#pragma once\n\n#include <functional>\n#include <future>\n#include <mutex>\n#include <queue>\n#include <thread>\n#include <utility>\n#include <vector>\n\n#include \"core\/module\/ThreadPool.hpp\"\n#include \"core\/utils\/log.h\"\n\nclass ThreadPool {\nprivate:\n class ThreadWorker {\n private:\n unsigned int m_id;\n ThreadPool* m_pool;\n\n public:\n ThreadWorker(ThreadPool* pool, const unsigned int id, allpix::LogLevel log_level) : m_id(id), m_pool(pool) {\n \/\/ Set logging level\n allpix::Log::setReportingLevel(log_level);\n }\n void operator()() {\n std::function<void()> func;\n bool dequeued;\n while(!m_pool->m_shutdown) {\n {\n std::unique_lock<std::mutex> lock(m_pool->m_conditional_mutex);\n if(m_pool->m_queue.empty()) {\n m_pool->m_conditional_lock.wait(lock);\n }\n dequeued = m_pool->m_queue.pop(func);\n }\n if(dequeued) {\n func();\n }\n }\n }\n };\n\n bool m_shutdown;\n allpix::ThreadPool::SafeQueue<std::function<void()>> m_queue;\n std::vector<std::thread> m_threads;\n std::mutex m_conditional_mutex;\n std::condition_variable m_conditional_lock;\n\npublic:\n ThreadPool(const unsigned int n_threads, allpix::LogLevel log_level)\n : m_shutdown(false), m_threads(std::vector<std::thread>(n_threads)) {\n for(unsigned int i = 0; i < m_threads.size(); ++i) {\n m_threads[i] = std::thread(ThreadWorker(this, i, log_level));\n }\n }\n\n ThreadPool(const ThreadPool&) = delete;\n ThreadPool(ThreadPool&&) = delete;\n\n ThreadPool& operator=(const ThreadPool&) = delete;\n ThreadPool& operator=(ThreadPool&&) = delete;\n\n \/\/ Waits until threads finish their current task and shutdowns the pool\n void shutdown() {\n m_shutdown = true;\n m_conditional_lock.notify_all();\n m_queue.invalidate();\n\n for(auto& thrd : m_threads) {\n if(thrd.joinable()) {\n thrd.join();\n }\n }\n }\n\n \/\/ Submit a function to be executed asynchronously by the pool\n template <typename F, typename... Args> auto submit(F&& f, Args&&... args) -> std::future<decltype(f(args...))> {\n \/\/ Create a function with bounded parameters ready to execute\n std::function<decltype(f(args...))()> func = std::bind(std::forward<F>(f), std::forward<Args>(args)...);\n \/\/ Encapsulate it into a shared ptr in order to be able to copy construct \/ assign\n auto task_ptr = std::make_shared<std::packaged_task<decltype(f(args...))()>>(func);\n\n \/\/ Wrap packaged task into void function\n std::function<void()> wrapper_func = [task_ptr]() { (*task_ptr)(); };\n\n \/\/ Enqueue generic wrapper function\n m_queue.push(wrapper_func);\n\n \/\/ Wake up one thread if its waiting\n m_conditional_lock.notify_one();\n\n \/\/ Return future from promise\n return task_ptr->get_future();\n }\n};\n<commit_msg>fix unused variable in thread pool<commit_after>#ifndef DFISE_THREADPOOL_H\n#define DFISE_THREADPOOL_H\n\n\/\/ NOTE: class is added here temporarily as the allpix ThreadPool cannot be used and threading will be redesigned\n\n#include <functional>\n#include <future>\n#include <mutex>\n#include <queue>\n#include <thread>\n#include <utility>\n#include <vector>\n\n#include \"core\/module\/ThreadPool.hpp\"\n#include \"core\/utils\/log.h\"\n\nclass ThreadPool {\nprivate:\n class ThreadWorker {\n private:\n ThreadPool* m_pool;\n\n public:\n ThreadWorker(ThreadPool* pool, allpix::LogLevel log_level) : m_pool(pool) {\n \/\/ Set logging level\n allpix::Log::setReportingLevel(log_level);\n }\n void operator()() {\n std::function<void()> func;\n bool dequeued;\n while(!m_pool->m_shutdown) {\n {\n std::unique_lock<std::mutex> lock(m_pool->m_conditional_mutex);\n if(m_pool->m_queue.empty()) {\n m_pool->m_conditional_lock.wait(lock);\n }\n dequeued = m_pool->m_queue.pop(func);\n }\n if(dequeued) {\n func();\n }\n }\n }\n };\n\n bool m_shutdown;\n allpix::ThreadPool::SafeQueue<std::function<void()>> m_queue;\n std::vector<std::thread> m_threads;\n std::mutex m_conditional_mutex;\n std::condition_variable m_conditional_lock;\n\npublic:\n ThreadPool(const unsigned int n_threads, allpix::LogLevel log_level)\n : m_shutdown(false), m_threads(std::vector<std::thread>(n_threads)) {\n for(unsigned int i = 0; i < m_threads.size(); ++i) {\n m_threads[i] = std::thread(ThreadWorker(this, log_level));\n }\n }\n\n ThreadPool(const ThreadPool&) = delete;\n ThreadPool(ThreadPool&&) = delete;\n\n ThreadPool& operator=(const ThreadPool&) = delete;\n ThreadPool& operator=(ThreadPool&&) = delete;\n\n \/\/ Waits until threads finish their current task and shutdowns the pool\n void shutdown() {\n m_shutdown = true;\n m_conditional_lock.notify_all();\n m_queue.invalidate();\n\n for(auto& thrd : m_threads) {\n if(thrd.joinable()) {\n thrd.join();\n }\n }\n }\n\n \/\/ Submit a function to be executed asynchronously by the pool\n template <typename F, typename... Args> auto submit(F&& f, Args&&... args) -> std::future<decltype(f(args...))> {\n \/\/ Create a function with bounded parameters ready to execute\n std::function<decltype(f(args...))()> func = std::bind(std::forward<F>(f), std::forward<Args>(args)...);\n \/\/ Encapsulate it into a shared ptr in order to be able to copy construct \/ assign\n auto task_ptr = std::make_shared<std::packaged_task<decltype(f(args...))()>>(func);\n\n \/\/ Wrap packaged task into void function\n std::function<void()> wrapper_func = [task_ptr]() { (*task_ptr)(); };\n\n \/\/ Enqueue generic wrapper function\n m_queue.push(wrapper_func);\n\n \/\/ Wake up one thread if its waiting\n m_conditional_lock.notify_one();\n\n \/\/ Return future from promise\n return task_ptr->get_future();\n }\n};\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright 2009-2017 The VOTCA Development Team\n * (http:\/\/www.votca.org)\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\")\n *\n * You may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *\/\n\n\/\/ Overload of uBLAS prod function with MKL\/GSL implementations\n#include <votca\/tools\/linalg.h>\n#include <votca\/xtp\/aomatrix.h>\n#include <votca\/xtp\/dftcoupling.h>\n\n#include <boost\/numeric\/ublas\/operation.hpp>\n#include <boost\/numeric\/ublas\/banded.hpp>\n#include <boost\/numeric\/ublas\/matrix_proxy.hpp>\n#include <boost\/numeric\/ublas\/vector_proxy.hpp>\n#include <boost\/numeric\/ublas\/symmetric.hpp>\n#include <votca\/tools\/constants.h>\n#include <boost\/format.hpp>\n#include <boost\/progress.hpp>\n\n\nnamespace votca {\n namespace xtp {\n\n namespace ub = boost::numeric::ublas;\n\n\n using boost::format;\n\n double DFTcoupling::getCouplingElement(int levelA, int levelB, Orbitals* _orbitalsA,\n Orbitals* _orbitalsB, ub::matrix<double>* _JAB, double _energy_difference) {\n\n\n int _levelsA = _orbitalsA->getNumberOfLevels();\n\n if (_energy_difference != 0) {\n std::vector<int> list_levelsA = *_orbitalsA->getDegeneracy(levelA, _energy_difference);\n std::vector<int> list_levelsB = *_orbitalsA->getDegeneracy(levelB, _energy_difference);\n\n double _JAB_sq = 0;\n double _JAB_one_level;\n\n for (std::vector<int>::iterator iA = list_levelsA.begin()++; iA != list_levelsA.end(); iA++) {\n for (std::vector<int>::iterator iB = list_levelsB.begin()++; iB != list_levelsB.end(); iB++) {\n \/\/cout << *iA << ':' << *iB << endl;\n _JAB_one_level = _JAB->at_element(*iA - 1, *iB - 1 + _levelsA);\n _JAB_sq += _JAB_one_level*_JAB_one_level;\n }\n }\n\n return sqrt(_JAB_sq \/ (list_levelsA.size() * list_levelsB.size())) * tools::conv::hrt2ev;\n\n } else {\n\n return _JAB->at_element(levelA - 1, levelB - 1 + _levelsA) * tools::conv::hrt2ev;\n\n }\n \/\/ the matrix should be symmetric, could also return this element\n \/\/ _JAB.at_element( _levelsA + levelB - 1 , levelA - 1 );\n }\n\n \/**\n * \\brief evaluates electronic couplings \n * \n * This is a fast version with a rather large block matrix AxB\n * \n * @param _orbitalsA molecular orbitals of molecule A\n * @param _orbitalsB molecular orbitals of molecule B\n * @param _orbitalsAB molecular orbitals of the dimer AB\n * @param _JAB matrix with electronic couplings\n * @return false if failed\n *\/\n bool DFTcoupling::CalculateIntegrals(Orbitals* _orbitalsA, Orbitals* _orbitalsB,\n Orbitals* _orbitalsAB, ub::matrix<double>* _JAB) {\n\n CTP_LOG(ctp::logDEBUG, *_pLog) << \"Calculating electronic couplings\" << flush;\n\n const std::vector<QMAtom*> atomsA = _orbitalsA->QMAtoms();\n const std::vector<QMAtom*> atomsB = _orbitalsB->QMAtoms();\n const std::vector<QMAtom*> atomsAll = _orbitalsAB->QMAtoms();\n\n for (unsigned i = 0; i < atomsAll.size(); i++) {\n QMAtom* dimer = atomsAll[i];\n QMAtom* monomer = NULL;\n \n if (i < atomsA.size()) {\n monomer = atomsA[i];\n if(!monomer->getPos().isClose(dimer->getPos(), 0.001) ) {\n CTP_LOG(ctp::logERROR, *_pLog) << \"======WARNING=======\\n Coordinates of monomers and dimer atoms do not agree, do you know what you are doing?\\n \" << flush;\n continue;\n }\n } else if (i < atomsB.size() + atomsA.size()) {\n monomer = atomsB[i - atomsA.size()];\n if(monomer->getPos().isClose(dimer->getPos(), 0.001)){\n CTP_LOG(ctp::logERROR, *_pLog) << \"======WARNING=======\\n Coordinates of monomers and dimer atoms do not agree, do you know what you are doing?\\n \" << flush;\n continue;\n }\n } else {\n \/\/ Linker\n CTP_LOG(ctp::logERROR, *_pLog) << (format(\"Neither Monomer A nor Monomer B contains atom %s on line %u. Hence, this atom is part of a linker. \\n\") %dimer->getType() %(i+1) ).str()<<flush;\n continue;\n }\n \n if (monomer->getType() != dimer->getType()) {\n throw runtime_error(\"\\nERROR: Atom types do not agree in dimer and monomers\\n\");\n }\n if (tools::abs(monomer->getPos() - dimer->getPos()) > 0.001) {\n CTP_LOG(ctp::logERROR, *_pLog) << \"======WARNING=======\\n Coordinates of monomers and dimer atoms do not agree, do you know what you are doing?\\n \" << flush;\n break;\n }\n }\n\n \/\/ constructing the direct product orbA x orbB\n int _basisA = _orbitalsA->getBasisSetSize();\n int _basisB = _orbitalsB->getBasisSetSize();\n\n if ((_basisA == 0) || (_basisB == 0)) {\n CTP_LOG(ctp::logERROR, *_pLog) << \"Basis set size is not stored in monomers\" << flush;\n return false;\n }\n\n int _levelsA = _orbitalsA->getNumberOfLevels();\n int _levelsB = _orbitalsB->getNumberOfLevels();\n\n \/\/boost::timer t; \/\/ start timing\n \/\/double _st = t.elapsed();\n\n CTP_LOG(ctp::logDEBUG, *_pLog) << \"Levels:Basis A[\" << _levelsA << \":\" << _basisA << \"]\"\n << \" B[\" << _levelsB << \":\" << _basisB << \"]\" << flush;\n\n if ((_levelsA == 0) || (_levelsB == 0)) {\n CTP_LOG(ctp::logERROR, *_pLog) << \"No information about number of occupied\/unoccupied levels is stored\" << flush;\n return false;\n }\n\n \/\/ | Orbitals_A 0 | | Overlap_A | \n \/\/ | 0 Orbitals_B | X | Overlap_B | X Transpose( Orbitals_AB )\n \/\/ub::zero_matrix<double> zeroB(_levelsA, _basisB);\n \/\/ub::zero_matrix<double> zeroA(_levelsB, _basisA);\n\n \n \/\/ CHANGE _basisA + _basisB to \"_basisAB\" of the dimer + extra\n ub::matrix<double>_psi_AxB= ub::zero_matrix<double>(_levelsA + _levelsB ,_orbitalsAB->getBasisSetSize());\n \/\/ ADD another zero matrix for \"padding\", OR initialize _psi_AxB as zero_matrix directly!\n \n\n CTP_LOG(ctp::logDEBUG, *_pLog) << \"Constructing direct product AxB [\"\n << _psi_AxB.size1() << \"x\"\n << _psi_AxB.size2() << \"]\" << flush;\n\n\n \/\/ nothing needs to be done here, if _psi_AxB is initialized as zero_matrix\n \/\/ub::project(_psi_AxB, ub::range(0, _levelsA), ub::range(_basisA, _basisA + _basisB)) = zeroB;\n \/\/ub::project(_psi_AxB, ub::range(_levelsA, _levelsA + _levelsB), ub::range(0, _basisA)) = zeroA;\n ub::project(_psi_AxB, ub::range(0, _levelsA), ub::range(0, _basisA)) = _orbitalsA->MOCoefficients();\n ub::project(_psi_AxB, ub::range(_levelsA, _levelsA + _levelsB), ub::range(_basisA, _basisA + _basisB)) = _orbitalsB->MOCoefficients();\n\n \n \n \/\/ psi_AxB * S_AB * psi_AB\n\n \/\/ NO CHANGE NEEDED\n CTP_LOG(ctp::logDEBUG, *_pLog) << \"Projecting dimer onto monomer orbitals\" << flush;\n ub::matrix<double> overlap;\n if (_orbitalsAB->hasAOOverlap()) {\n CTP_LOG(ctp::logDEBUG, *_pLog) << \"Reading overlap matrix from orbitals\" << flush;\n overlap = _orbitalsAB->AOOverlap();\n } else {\n CTP_LOG(ctp::logDEBUG, *_pLog) << \"Calculating overlap matrix for basisset: \" << _orbitalsAB->getDFTbasis() << flush;\n BasisSet _dftbasisset;\n AOBasis _dftbasis;\n _dftbasisset.LoadBasisSet(_orbitalsAB->getDFTbasis());\n\n _dftbasis.AOBasisFill(&_dftbasisset, _orbitalsAB->QMAtoms());\n AOOverlap _dftAOoverlap;\n _dftAOoverlap.Fill(_dftbasis);\n overlap = _dftAOoverlap.Matrix();\n }\n\n ub::matrix<double> _psi_AB = ub::prod(overlap, ub::trans(_orbitalsAB->MOCoefficients()));\n ub::matrix<double> _psi_AxB_dimer_basis = ub::prod(_psi_AxB, _psi_AB);\n _psi_AB.clear();\n\n \/\/check to see if projection quality is sufficient\n for (unsigned i = 0; i < _psi_AxB_dimer_basis.size1(); i++) {\n double mag = 0.0;\n for (unsigned j = 0; j < _psi_AxB_dimer_basis.size2(); j++) {\n mag += _psi_AxB_dimer_basis(i, j) * _psi_AxB_dimer_basis(i, j);\n\n }\n if (mag < 0.95) {\n throw runtime_error(\"\\nERROR: Projection of monomer orbitals on dimer is insufficient, maybe the orbital order is screwed up, otherwise increase dimer basis.\\n\");\n }\n }\n\n \/\/ J = psi_AxB_dimer_basis * HAB * psi_AxB_dimer_basis^T\n CTP_LOG(ctp::logDEBUG, *_pLog) << \"Projecting the Fock matrix onto the dimer basis\" << flush;\n ub::diagonal_matrix<double> _hamiltonian_AB(_orbitalsAB->getNumberOfLevels(), _orbitalsAB->MOEnergies().data());\n ub::matrix<double> _temp = ub::prod(_hamiltonian_AB, ub::trans(_psi_AxB_dimer_basis));\n ub::matrix<double> JAB_dimer = ub::prod(_psi_AxB_dimer_basis, _temp);\n\n \/\/ S = psi_AxB_dimer_basis * psi_AxB_dimer_basis^T\n CTP_LOG(ctp::logDEBUG, *_pLog) << \"Constructing Overlap matrix\" << flush;\n ub::matrix<double> _S_AxB = ub::prod(_psi_AxB_dimer_basis, ub::trans(_psi_AxB_dimer_basis));\n\n CTP_LOG(ctp::logDEBUG, *_pLog) << \"Calculating the effective overlap JAB [\"\n << JAB_dimer.size1() << \"x\"\n << JAB_dimer.size2() << \"]\" << flush;\n double smalleig = linalg_loewdin(JAB_dimer, _S_AxB);\n CTP_LOG(ctp::logDEBUG, *_pLog) << \"Smallest eigenvalue of overlap matrix is \" << smalleig << flush;\n (*_JAB) = JAB_dimer;\n\n\n CTP_LOG(ctp::logDEBUG, *_pLog) << \"Done with electronic couplings\" << flush;\n\n return true;\n\n }\n\n\n\n }\n}\n<commit_msg>Removed comments<commit_after>\/*\n * Copyright 2009-2017 The VOTCA Development Team\n * (http:\/\/www.votca.org)\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\")\n *\n * You may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *\/\n\n\/\/ Overload of uBLAS prod function with MKL\/GSL implementations\n#include <votca\/tools\/linalg.h>\n#include <votca\/xtp\/aomatrix.h>\n#include <votca\/xtp\/dftcoupling.h>\n\n#include <boost\/numeric\/ublas\/operation.hpp>\n#include <boost\/numeric\/ublas\/banded.hpp>\n#include <boost\/numeric\/ublas\/matrix_proxy.hpp>\n#include <boost\/numeric\/ublas\/vector_proxy.hpp>\n#include <boost\/numeric\/ublas\/symmetric.hpp>\n#include <votca\/tools\/constants.h>\n#include <boost\/format.hpp>\n#include <boost\/progress.hpp>\n\n\nnamespace votca {\n namespace xtp {\n\n namespace ub = boost::numeric::ublas;\n\n\n using boost::format;\n\n double DFTcoupling::getCouplingElement(int levelA, int levelB, Orbitals* _orbitalsA,\n Orbitals* _orbitalsB, ub::matrix<double>* _JAB, double _energy_difference) {\n\n\n int _levelsA = _orbitalsA->getNumberOfLevels();\n\n if (_energy_difference != 0) {\n std::vector<int> list_levelsA = *_orbitalsA->getDegeneracy(levelA, _energy_difference);\n std::vector<int> list_levelsB = *_orbitalsA->getDegeneracy(levelB, _energy_difference);\n\n double _JAB_sq = 0;\n double _JAB_one_level;\n\n for (std::vector<int>::iterator iA = list_levelsA.begin()++; iA != list_levelsA.end(); iA++) {\n for (std::vector<int>::iterator iB = list_levelsB.begin()++; iB != list_levelsB.end(); iB++) {\n \/\/cout << *iA << ':' << *iB << endl;\n _JAB_one_level = _JAB->at_element(*iA - 1, *iB - 1 + _levelsA);\n _JAB_sq += _JAB_one_level*_JAB_one_level;\n }\n }\n\n return sqrt(_JAB_sq \/ (list_levelsA.size() * list_levelsB.size())) * tools::conv::hrt2ev;\n\n } else {\n\n return _JAB->at_element(levelA - 1, levelB - 1 + _levelsA) * tools::conv::hrt2ev;\n\n }\n \/\/ the matrix should be symmetric, could also return this element\n \/\/ _JAB.at_element( _levelsA + levelB - 1 , levelA - 1 );\n }\n\n \/**\n * \\brief evaluates electronic couplings \n * \n * This is a fast version with a rather large block matrix AxB\n * \n * @param _orbitalsA molecular orbitals of molecule A\n * @param _orbitalsB molecular orbitals of molecule B\n * @param _orbitalsAB molecular orbitals of the dimer AB\n * @param _JAB matrix with electronic couplings\n * @return false if failed\n *\/\n bool DFTcoupling::CalculateIntegrals(Orbitals* _orbitalsA, Orbitals* _orbitalsB,\n Orbitals* _orbitalsAB, ub::matrix<double>* _JAB) {\n\n CTP_LOG(ctp::logDEBUG, *_pLog) << \"Calculating electronic couplings\" << flush;\n\n const std::vector<QMAtom*> atomsA = _orbitalsA->QMAtoms();\n const std::vector<QMAtom*> atomsB = _orbitalsB->QMAtoms();\n const std::vector<QMAtom*> atomsAll = _orbitalsAB->QMAtoms();\n\n for (unsigned i = 0; i < atomsAll.size(); i++) {\n QMAtom* dimer = atomsAll[i];\n QMAtom* monomer = NULL;\n \n if (i < atomsA.size()) {\n monomer = atomsA[i];\n if(!monomer->getPos().isClose(dimer->getPos(), 0.001) ) {\n CTP_LOG(ctp::logERROR, *_pLog) << \"======WARNING=======\\n Coordinates of monomers and dimer atoms do not agree, do you know what you are doing?\\n \" << flush;\n continue;\n }\n } else if (i < atomsB.size() + atomsA.size()) {\n monomer = atomsB[i - atomsA.size()];\n if(monomer->getPos().isClose(dimer->getPos(), 0.001)){\n CTP_LOG(ctp::logERROR, *_pLog) << \"======WARNING=======\\n Coordinates of monomers and dimer atoms do not agree, do you know what you are doing?\\n \" << flush;\n continue;\n }\n } else {\n \/\/ Linker\n CTP_LOG(ctp::logDEBUG, *_pLog) << (format(\"Neither Monomer A nor Monomer B contains atom %s on line %u. Hence, this atom is part of a linker. \\n\") %dimer->getType() %(i+1) ).str()<<flush;\n continue;\n }\n \n if (monomer->getType() != dimer->getType()) {\n throw runtime_error(\"\\nERROR: Atom types do not agree in dimer and monomers\\n\");\n }\n if (tools::abs(monomer->getPos() - dimer->getPos()) > 0.001) {\n CTP_LOG(ctp::logERROR, *_pLog) << \"======WARNING=======\\n Coordinates of monomers and dimer atoms do not agree, do you know what you are doing?\\n \" << flush;\n break;\n }\n }\n\n \/\/ constructing the direct product orbA x orbB\n int _basisA = _orbitalsA->getBasisSetSize();\n int _basisB = _orbitalsB->getBasisSetSize();\n\n if ((_basisA == 0) || (_basisB == 0)) {\n CTP_LOG(ctp::logERROR, *_pLog) << \"Basis set size is not stored in monomers\" << flush;\n return false;\n }\n\n int _levelsA = _orbitalsA->getNumberOfLevels();\n int _levelsB = _orbitalsB->getNumberOfLevels();\n\n \/\/boost::timer t; \/\/ start timing\n \/\/double _st = t.elapsed();\n\n CTP_LOG(ctp::logDEBUG, *_pLog) << \"Levels:Basis A[\" << _levelsA << \":\" << _basisA << \"]\"\n << \" B[\" << _levelsB << \":\" << _basisB << \"]\" << flush;\n\n if ((_levelsA == 0) || (_levelsB == 0)) {\n CTP_LOG(ctp::logERROR, *_pLog) << \"No information about number of occupied\/unoccupied levels is stored\" << flush;\n return false;\n }\n\n \/\/ | Orbitals_A 0 | | Overlap_A | \n \/\/ | 0 Orbitals_B | X | Overlap_B | X Transpose( Orbitals_AB )\n \n ub::matrix<double>_psi_AxB= ub::zero_matrix<double>(_levelsA + _levelsB ,_orbitalsAB->getBasisSetSize());\n\n CTP_LOG(ctp::logDEBUG, *_pLog) << \"Constructing direct product AxB [\"\n << _psi_AxB.size1() << \"x\"\n << _psi_AxB.size2() << \"]\" << flush;\n\n ub::project(_psi_AxB, ub::range(0, _levelsA), ub::range(0, _basisA)) = _orbitalsA->MOCoefficients();\n ub::project(_psi_AxB, ub::range(_levelsA, _levelsA + _levelsB), ub::range(_basisA, _basisA + _basisB)) = _orbitalsB->MOCoefficients();\n\n \n \n \/\/ psi_AxB * S_AB * psi_AB\n CTP_LOG(ctp::logDEBUG, *_pLog) << \"Projecting dimer onto monomer orbitals\" << flush;\n ub::matrix<double> overlap;\n if (_orbitalsAB->hasAOOverlap()) {\n CTP_LOG(ctp::logDEBUG, *_pLog) << \"Reading overlap matrix from orbitals\" << flush;\n overlap = _orbitalsAB->AOOverlap();\n } else {\n CTP_LOG(ctp::logDEBUG, *_pLog) << \"Calculating overlap matrix for basisset: \" << _orbitalsAB->getDFTbasis() << flush;\n BasisSet _dftbasisset;\n AOBasis _dftbasis;\n _dftbasisset.LoadBasisSet(_orbitalsAB->getDFTbasis());\n\n _dftbasis.AOBasisFill(&_dftbasisset, _orbitalsAB->QMAtoms());\n AOOverlap _dftAOoverlap;\n _dftAOoverlap.Fill(_dftbasis);\n overlap = _dftAOoverlap.Matrix();\n }\n\n ub::matrix<double> _psi_AB = ub::prod(overlap, ub::trans(_orbitalsAB->MOCoefficients()));\n ub::matrix<double> _psi_AxB_dimer_basis = ub::prod(_psi_AxB, _psi_AB);\n _psi_AB.clear();\n\n \/\/check to see if projection quality is sufficient\n for (unsigned i = 0; i < _psi_AxB_dimer_basis.size1(); i++) {\n double mag = 0.0;\n for (unsigned j = 0; j < _psi_AxB_dimer_basis.size2(); j++) {\n mag += _psi_AxB_dimer_basis(i, j) * _psi_AxB_dimer_basis(i, j);\n\n }\n if (mag < 0.95) {\n throw runtime_error(\"\\nERROR: Projection of monomer orbitals on dimer is insufficient, maybe the orbital order is screwed up, otherwise increase dimer basis.\\n\");\n }\n }\n\n \/\/ J = psi_AxB_dimer_basis * HAB * psi_AxB_dimer_basis^T\n CTP_LOG(ctp::logDEBUG, *_pLog) << \"Projecting the Fock matrix onto the dimer basis\" << flush;\n ub::diagonal_matrix<double> _hamiltonian_AB(_orbitalsAB->getNumberOfLevels(), _orbitalsAB->MOEnergies().data());\n ub::matrix<double> _temp = ub::prod(_hamiltonian_AB, ub::trans(_psi_AxB_dimer_basis));\n ub::matrix<double> JAB_dimer = ub::prod(_psi_AxB_dimer_basis, _temp);\n\n \/\/ S = psi_AxB_dimer_basis * psi_AxB_dimer_basis^T\n CTP_LOG(ctp::logDEBUG, *_pLog) << \"Constructing Overlap matrix\" << flush;\n ub::matrix<double> _S_AxB = ub::prod(_psi_AxB_dimer_basis, ub::trans(_psi_AxB_dimer_basis));\n\n CTP_LOG(ctp::logDEBUG, *_pLog) << \"Calculating the effective overlap JAB [\"\n << JAB_dimer.size1() << \"x\"\n << JAB_dimer.size2() << \"]\" << flush;\n double smalleig = linalg_loewdin(JAB_dimer, _S_AxB);\n CTP_LOG(ctp::logDEBUG, *_pLog) << \"Smallest eigenvalue of overlap matrix is \" << smalleig << flush;\n (*_JAB) = JAB_dimer;\n\n\n CTP_LOG(ctp::logDEBUG, *_pLog) << \"Done with electronic couplings\" << flush;\n\n return true;\n\n }\n\n\n\n }\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"locomotion_module\/locomotion_module.h\"\n\nLocomotionModule::LocomotionModule()\n{\n}\n\nLocomotionModule::~LocomotionModule()\n{\n}\n\nvoid LocomotionModule::publishMessage(ros::Publisher *pub_message, int side)\n{\n \/\/std_msgs::float32 msg;\n\n \/\/pub_message->publish(msg);\n}\n\nvoid LocomotionModule::velMessageCallback(const geometry_msgs::Twist::ConstPtr &msg)\n{\n \/\/translate twist into left and right velocities\n velLeft_.data = msg->linear.x + msg->angular.z*r_; \n velRight_.data = msg->linear.x - msg->angular.z*r_;\n \/\/publish to left and right topics\n pub_left.publish(velLeft_);\n pub_right.publish(velRight_);\n}\n\nvoid LocomotionModule::odomMessageCallback(const geometry_msgs::Twist::ConstPtr &msg)\n{\n current_time = ros::Time::now();\n\n dt = (current_time - last_time).toSec();\n delta_th = msg->angular.z*dt;\n delta_x = (msg->linear.x*cos(th) )* dt;\n delta_y = (msg->linear.y*sin(th) )* dt;\n\n x += delta_x;\n y += delta_y;\n th += delta_th;\n\n \/\/since all odometry is 6DOF we'll need a quaternion created from yaw\n geometry_msgs::Quaternion odom_quat = tf::createQuaternionMsgFromYaw(th);\n\n \/\/first, we'll publish the transform over tf\n geometry_msgs::TransformStamped odom_trans;\n odom_trans.header.stamp = current_time;\n odom_trans.header.frame_id = \"odom\";\n odom_trans.child_frame_id = \"base_link\";\n\n odom_trans.transform.translation.x = x;\n odom_trans.transform.translation.y = y;\n odom_trans.transform.translation.z = 0.0;\n odom_trans.transform.rotation = odom_quat;\n\n \/\/send the transform\n odom_broadcaster.sendTransform(odom_trans);\n\n \/\/next, we'll publish the odometry message over ROS\n nav_msgs::Odometry odom;\n odom.header.stamp = current_time;\n odom.header.frame_id = \"odom\";\n\n \/\/set the position\n odom.pose.pose.position.x = x;\n odom.pose.pose.position.y = y;\n odom.pose.pose.position.z = 0.0;\n odom.pose.pose.orientation = odom_quat;\n\n \/\/set the velocity\n odom.child_frame_id = \"base_link\";\n odom.twist.twist.linear.x = vx;\n odom.twist.twist.linear.y = vy;\n odom.twist.twist.angular.z = vth;\n\n \/\/publish the message\n odom_pub.publish(odom);\n\n last_time = current_time;\n \n\n\n}\n\n\n\nvoid LocomotionModule::configCallback(locomotion_module::locomotionModuleConfig &config, uint32_t level)\n{\n r_ = config.r + r_center_;\n ROS_INFO(\"R changed %f\",r_);\n\n}\n<commit_msg>fixing new class<commit_after>#include \"locomotion_module\/locomotion_module.h\"\n\nLocomotionModule::LocomotionModule()\n{\n}\n\nLocomotionModule::~LocomotionModule()\n{\n}\n\nvoid LocomotionModule::publishMessage(ros::Publisher *pub_message, int side)\n{\n \/\/std_msgs::float32 msg;\n\n \/\/pub_message->publish(msg);\n}\n\nvoid LocomotionModule::velMessageCallback(const geometry_msgs::Twist::ConstPtr &msg)\n{\n \/\/translate twist into left and right velocities\n velLeft_.data = msg->linear.x + msg->angular.z*r_; \n velRight_.data = msg->linear.x - msg->angular.z*r_;\n \/\/publish to left and right topics\n pub_left.publish(velLeft_);\n pub_right.publish(velRight_);\n}\n\nvoid LocomotionModule::odomMessageCallback(const geometry_msgs::Twist::ConstPtr &msg)\n{\n current_time = ros::Time::now();\n\n dt = (current_time - last_time).toSec();\n delta_th = msg->angular.z*dt;\n delta_x = (msg->linear.x*cos(th) )* dt;\n delta_y = (msg->linear.y*sin(th) )* dt;\n\n x += delta_x;\n y += delta_y;\n th += delta_th;\n\n \/\/since all odometry is 6DOF we'll need a quaternion created from yaw\n geometry_msgs::Quaternion odom_quat = tf::createQuaternionMsgFromYaw(th);\n\n \/\/first, we'll publish the transform over tf\n geometry_msgs::TransformStamped odom_trans;\n odom_trans.header.stamp = current_time;\n odom_trans.header.frame_id = \"odom\";\n odom_trans.child_frame_id = \"base_link\";\n\n odom_trans.transform.translation.x = x;\n odom_trans.transform.translation.y = y;\n odom_trans.transform.translation.z = 0.0;\n odom_trans.transform.rotation = odom_quat;\n\n \/\/send the transform\n odom_broadcaster.sendTransform(odom_trans);\n\n \/\/next, we'll publish the odometry message over ROS\n nav_msgs::Odometry odom;\n odom.header.stamp = current_time;\n odom.header.frame_id = \"odom\";\n\n \/\/set the position\n odom.pose.pose.position.x = x;\n odom.pose.pose.position.y = y;\n odom.pose.pose.position.z = 0.0;\n odom.pose.pose.orientation = odom_quat;\n\n \/\/set the velocity\n odom.child_frame_id = \"base_link\";\n odom.twist.twist.linear.x = msg->linear.x;\n odom.twist.twist.linear.y = msg->linear.y;\n odom.twist.twist.angular.z = msg->angular.z;\n\n \/\/publish the message\n odom_pub.publish(odom);\n\n last_time = current_time;\n \n\n\n}\n\n\n\nvoid LocomotionModule::configCallback(locomotion_module::locomotionModuleConfig &config, uint32_t level)\n{\n r_ = config.r + r_center_;\n ROS_INFO(\"R changed %f\",r_);\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2016 Tom Barthel-Steer\n\/\/ http:\/\/www.tomsteer.net\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \"universeview.h\"\n#include \"ui_universeview.h\"\n#include \"streamingacn.h\"\n#include \"sacnlistener.h\"\n#include \"preferences.h\"\n#include \"consts.h\"\n#include \"flickerfinderinfoform.h\"\n\n#include <QFileDialog>\n#include <QStandardPaths>\n#include <QMessageBox>\n\nQString onlineToString(bool value)\n{\n if(value)\n return QString(\"Online\");\n return QString(\"Offline\");\n}\n\nQString protocolVerToString(int value)\n{\n switch(value)\n {\n case sACNProtocolDraft:\n return QString(\"Draft\");\n case sACNProtocolRelease:\n return QString(\"Release\");\n }\n\n return QString(\"Unknown\");\n}\n\nUniverseView::UniverseView(QWidget *parent) :\n QWidget(parent),\n ui(new Ui::UniverseView)\n{\n m_selectedAddress = -1;\n m_logger = NULL;\n ui->setupUi(this);\n connect(ui->universeDisplay, SIGNAL(selectedCellChanged(int)), this, SLOT(selectedAddressChanged(int)));\n\n\n ui->btnGo->setEnabled(true);\n ui->btnPause->setEnabled(false);\n ui->sbUniverse->setEnabled(true);\n setUiForLoggingState(NOT_LOGGING);\n}\n\nUniverseView::~UniverseView()\n{\n delete ui;\n}\n\nvoid UniverseView::startListening(int universe)\n{\n ui->twSources->setRowCount(0);\n ui->btnGo->setEnabled(false);\n ui->btnPause->setEnabled(true);\n ui->sbUniverse->setEnabled(false);\n m_listener = sACNManager::getInstance()->getListener(universe);\n ui->universeDisplay->setUniverse(universe);\n\n \/\/ Add the existing sources\n for(int i=0; i<m_listener->sourceCount(); i++)\n {\n sourceOnline(m_listener->source(i));\n }\n\n connect(m_listener.data(), SIGNAL(sourceFound(sACNSource*)), this, SLOT(sourceOnline(sACNSource*)));\n connect(m_listener.data(), SIGNAL(sourceLost(sACNSource*)), this, SLOT(sourceOffline(sACNSource*)));\n connect(m_listener.data(), SIGNAL(sourceChanged(sACNSource*)), this, SLOT(sourceChanged(sACNSource*)));\n connect(m_listener.data(), SIGNAL(levelsChanged()), this, SLOT(levelsChanged()));\n\n if(ui->sbUniverse->value()!=universe)\n ui->sbUniverse->setValue(universe);\n}\n\nvoid UniverseView::on_btnGo_pressed()\n{\n startListening(ui->sbUniverse->value());\n}\n\nvoid UniverseView::sourceChanged(sACNSource *source)\n{\n if(!m_listener) return;\n if(!m_sourceToTableRow.contains(source))\n {\n return;\n }\n\n int row = m_sourceToTableRow[source];\n ui->twSources->item(row,COL_NAME)->setText(source->name);\n ui->twSources->item(row,COL_NAME)->setBackgroundColor(Preferences::getInstance()->colorForCID(source->src_cid));\n ui->twSources->item(row,COL_CID)->setText(source->cid_string());\n ui->twSources->item(row,COL_PRIO)->setText(QString::number(source->priority));\n ui->twSources->item(row,COL_IP)->setText(source->ip.toString());\n ui->twSources->item(row,COL_FPS)->setText(QString::number((source->fps)));\n ui->twSources->item(row,COL_SEQ_ERR)->setText(QString::number(source->seqErr));\n ui->twSources->item(row,COL_JUMPS)->setText(QString::number(source->jumps));\n ui->twSources->item(row,COL_ONLINE)->setText(onlineToString(source->src_valid));\n ui->twSources->item(row,COL_VER)->setText(protocolVerToString(source->protocol_version));\n ui->twSources->item(row,COL_DD)->setText(source->doing_per_channel ? tr(\"Yes\") : tr(\"No\"));\n}\n\nvoid UniverseView::sourceOnline(sACNSource *source)\n{\n if(!m_listener) return;\n int row = ui->twSources->rowCount();\n ui->twSources->setRowCount(row+1);\n m_sourceToTableRow[source] = row;\n\n ui->twSources->setItem(row,COL_NAME, new QTableWidgetItem() );\n ui->twSources->setItem(row,COL_CID, new QTableWidgetItem() );\n ui->twSources->setItem(row,COL_PRIO, new QTableWidgetItem() );\n ui->twSources->setItem(row,COL_IP, new QTableWidgetItem() );\n ui->twSources->setItem(row,COL_FPS, new QTableWidgetItem() );\n ui->twSources->setItem(row,COL_SEQ_ERR, new QTableWidgetItem() );\n ui->twSources->setItem(row,COL_JUMPS, new QTableWidgetItem() );\n ui->twSources->setItem(row,COL_ONLINE, new QTableWidgetItem() );\n ui->twSources->setItem(row,COL_VER, new QTableWidgetItem() );\n ui->twSources->setItem(row,COL_DD, new QTableWidgetItem() );\n\n sourceChanged(source);\n\n}\n\nvoid UniverseView::sourceOffline(sACNSource *source)\n{\n if(!m_listener) return;\n sourceChanged(source);\n}\n\nvoid UniverseView::levelsChanged()\n{\n if(!m_listener) return;\n if(m_selectedAddress>-1)\n selectedAddressChanged(m_selectedAddress);\n}\n\nvoid UniverseView::resizeEvent(QResizeEvent *event)\n{\n QWidget::resizeEvent(event);\n resizeColumns();\n}\n\nvoid UniverseView::showEvent(QShowEvent *event)\n{\n QWidget::showEvent(event);\n\n resizeColumns();\n}\n\nvoid UniverseView::resizeColumns()\n{\n \/\/ Attempt to resize so all columns fit\n int width = ui->twSources->width();\n\n int widthUnit = width\/14;\n\n int used = 0;\n for(int i=COL_NAME; i<COL_END; i++)\n {\n switch(i)\n {\n case COL_NAME:\n break;\n case COL_CID:\n case COL_IP:\n case COL_DD:\n ui->twSources->setColumnWidth(i, 2*widthUnit);\n used += 2*widthUnit;\n break;\n default:\n ui->twSources->setColumnWidth(i, widthUnit);\n used += widthUnit;\n break;\n }\n }\n\n ui->twSources->setColumnWidth(COL_NAME, width-used-5);\n}\n\nvoid UniverseView::setUiForLoggingState(UniverseView::LOG_STATE state)\n{\n switch(state)\n {\n case LOGGING:\n ui->btnLogToFile->setText(tr(\"Stop Log to File\"));\n break;\n\n default:\n case NOT_LOGGING:\n ui->btnLogToFile->setText(tr(\"Start Log to File\"));\n break;\n }\n}\n\nvoid UniverseView::selectedAddressChanged(int address)\n{\n ui->teInfo->clear();\n m_selectedAddress = address;\n ui->teInfo->clear();\n if(address<0) return;\n\n if(!m_listener) return;\n sACNMergedSourceList list = m_listener->mergedLevels();\n\n QString info;\n\n info.append(tr(\"Address : %1\\n\")\n .arg(address+1));\n\n if(list[address].winningSource)\n {\n info.append(tr(\"Winning Source : %1 @ %2\")\n .arg(list[address].winningSource->name)\n .arg(Preferences::getInstance()->GetFormattedValue(list[address].level)));\n if(list[address].otherSources.count()>0)\n {\n foreach(sACNSource *source, list[address].otherSources)\n {\n int prio;\n if(source->doing_per_channel)\n prio = source->priority_array[address];\n else\n prio = source->priority;\n info.append(tr(\"\\nOther Source : %1 @ %2 (Priority %3)\")\n .arg(source->name)\n .arg(Preferences::getInstance()->GetFormattedValue(source->level_array[address]))\n .arg(prio));\n }\n }\n }\n if(!list[address].winningSource)\n {\n info.append(tr(\"No Sources\"));\n }\n\n ui->teInfo->setPlainText(info);\n}\n\nvoid UniverseView::on_btnPause_pressed()\n{\n ui->universeDisplay->pause();\n this->disconnect(m_listener.data());\n ui->btnGo->setEnabled(true);\n ui->btnPause->setEnabled(false);\n ui->sbUniverse->setEnabled(true);\n}\n\nvoid UniverseView::on_btnLogToFile_pressed()\n{\n if(!m_logger)\n {\n \/\/Setup dialog box\n QFileDialog dialog(this);\n dialog.setWindowTitle(APP_NAME);\n dialog.setDirectory(QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation));\n dialog.setNameFilter(\"CSV Files (*.csv)\");\n dialog.setDefaultSuffix(\"csv\");\n dialog.setFileMode(QFileDialog::AnyFile);\n dialog.setViewMode(QFileDialog::Detail);\n dialog.setAcceptMode(QFileDialog::AcceptSave);\n if(dialog.exec()) {\n QString saveName = dialog.selectedFiles().at(0);\n if(saveName.isEmpty()) {\n return;\n }\n m_logger = new MergedUniverseLogger();\n m_logger->start(saveName, m_listener);\n setUiForLoggingState(LOGGING);\n }\n\n }\n else\n {\n m_logger->stop();\n m_logger->deleteLater();\n m_logger = nullptr;\n\n setUiForLoggingState(NOT_LOGGING);\n }\n\n}\n\nvoid UniverseView::on_btnStartFlickerFinder_pressed()\n{\n if(ui->universeDisplay->flickerFinder())\n {\n ui->universeDisplay->setFlickerFinder(false);\n ui->btnStartFlickerFinder->setText(tr(\"Start Flicker Finder\"));\n }\n else\n {\n if(Preferences::getInstance()->getFlickerFinderShowInfo())\n {\n FlickerFinderInfoForm form;\n int result = form.exec();\n if(!result) return;\n }\n ui->universeDisplay->setFlickerFinder(true);\n ui->btnStartFlickerFinder->setText(tr(\"Stop Flicker Finder\"));\n }\n}\n<commit_msg>Show priority of winning source<commit_after>\/\/ Copyright 2016 Tom Barthel-Steer\n\/\/ http:\/\/www.tomsteer.net\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \"universeview.h\"\n#include \"ui_universeview.h\"\n#include \"streamingacn.h\"\n#include \"sacnlistener.h\"\n#include \"preferences.h\"\n#include \"consts.h\"\n#include \"flickerfinderinfoform.h\"\n\n#include <QFileDialog>\n#include <QStandardPaths>\n#include <QMessageBox>\n\nQString onlineToString(bool value)\n{\n if(value)\n return QString(\"Online\");\n return QString(\"Offline\");\n}\n\nQString protocolVerToString(int value)\n{\n switch(value)\n {\n case sACNProtocolDraft:\n return QString(\"Draft\");\n case sACNProtocolRelease:\n return QString(\"Release\");\n }\n\n return QString(\"Unknown\");\n}\n\nUniverseView::UniverseView(QWidget *parent) :\n QWidget(parent),\n ui(new Ui::UniverseView)\n{\n m_selectedAddress = -1;\n m_logger = NULL;\n ui->setupUi(this);\n connect(ui->universeDisplay, SIGNAL(selectedCellChanged(int)), this, SLOT(selectedAddressChanged(int)));\n\n\n ui->btnGo->setEnabled(true);\n ui->btnPause->setEnabled(false);\n ui->sbUniverse->setEnabled(true);\n setUiForLoggingState(NOT_LOGGING);\n}\n\nUniverseView::~UniverseView()\n{\n delete ui;\n}\n\nvoid UniverseView::startListening(int universe)\n{\n ui->twSources->setRowCount(0);\n ui->btnGo->setEnabled(false);\n ui->btnPause->setEnabled(true);\n ui->sbUniverse->setEnabled(false);\n m_listener = sACNManager::getInstance()->getListener(universe);\n ui->universeDisplay->setUniverse(universe);\n\n \/\/ Add the existing sources\n for(int i=0; i<m_listener->sourceCount(); i++)\n {\n sourceOnline(m_listener->source(i));\n }\n\n connect(m_listener.data(), SIGNAL(sourceFound(sACNSource*)), this, SLOT(sourceOnline(sACNSource*)));\n connect(m_listener.data(), SIGNAL(sourceLost(sACNSource*)), this, SLOT(sourceOffline(sACNSource*)));\n connect(m_listener.data(), SIGNAL(sourceChanged(sACNSource*)), this, SLOT(sourceChanged(sACNSource*)));\n connect(m_listener.data(), SIGNAL(levelsChanged()), this, SLOT(levelsChanged()));\n\n if(ui->sbUniverse->value()!=universe)\n ui->sbUniverse->setValue(universe);\n}\n\nvoid UniverseView::on_btnGo_pressed()\n{\n startListening(ui->sbUniverse->value());\n}\n\nvoid UniverseView::sourceChanged(sACNSource *source)\n{\n if(!m_listener) return;\n if(!m_sourceToTableRow.contains(source))\n {\n return;\n }\n\n int row = m_sourceToTableRow[source];\n ui->twSources->item(row,COL_NAME)->setText(source->name);\n ui->twSources->item(row,COL_NAME)->setBackgroundColor(Preferences::getInstance()->colorForCID(source->src_cid));\n ui->twSources->item(row,COL_CID)->setText(source->cid_string());\n ui->twSources->item(row,COL_PRIO)->setText(QString::number(source->priority));\n ui->twSources->item(row,COL_IP)->setText(source->ip.toString());\n ui->twSources->item(row,COL_FPS)->setText(QString::number((source->fps)));\n ui->twSources->item(row,COL_SEQ_ERR)->setText(QString::number(source->seqErr));\n ui->twSources->item(row,COL_JUMPS)->setText(QString::number(source->jumps));\n ui->twSources->item(row,COL_ONLINE)->setText(onlineToString(source->src_valid));\n ui->twSources->item(row,COL_VER)->setText(protocolVerToString(source->protocol_version));\n ui->twSources->item(row,COL_DD)->setText(source->doing_per_channel ? tr(\"Yes\") : tr(\"No\"));\n}\n\nvoid UniverseView::sourceOnline(sACNSource *source)\n{\n if(!m_listener) return;\n int row = ui->twSources->rowCount();\n ui->twSources->setRowCount(row+1);\n m_sourceToTableRow[source] = row;\n\n ui->twSources->setItem(row,COL_NAME, new QTableWidgetItem() );\n ui->twSources->setItem(row,COL_CID, new QTableWidgetItem() );\n ui->twSources->setItem(row,COL_PRIO, new QTableWidgetItem() );\n ui->twSources->setItem(row,COL_IP, new QTableWidgetItem() );\n ui->twSources->setItem(row,COL_FPS, new QTableWidgetItem() );\n ui->twSources->setItem(row,COL_SEQ_ERR, new QTableWidgetItem() );\n ui->twSources->setItem(row,COL_JUMPS, new QTableWidgetItem() );\n ui->twSources->setItem(row,COL_ONLINE, new QTableWidgetItem() );\n ui->twSources->setItem(row,COL_VER, new QTableWidgetItem() );\n ui->twSources->setItem(row,COL_DD, new QTableWidgetItem() );\n\n sourceChanged(source);\n\n}\n\nvoid UniverseView::sourceOffline(sACNSource *source)\n{\n if(!m_listener) return;\n sourceChanged(source);\n}\n\nvoid UniverseView::levelsChanged()\n{\n if(!m_listener) return;\n if(m_selectedAddress>-1)\n selectedAddressChanged(m_selectedAddress);\n}\n\nvoid UniverseView::resizeEvent(QResizeEvent *event)\n{\n QWidget::resizeEvent(event);\n resizeColumns();\n}\n\nvoid UniverseView::showEvent(QShowEvent *event)\n{\n QWidget::showEvent(event);\n\n resizeColumns();\n}\n\nvoid UniverseView::resizeColumns()\n{\n \/\/ Attempt to resize so all columns fit\n int width = ui->twSources->width();\n\n int widthUnit = width\/14;\n\n int used = 0;\n for(int i=COL_NAME; i<COL_END; i++)\n {\n switch(i)\n {\n case COL_NAME:\n break;\n case COL_CID:\n case COL_IP:\n case COL_DD:\n ui->twSources->setColumnWidth(i, 2*widthUnit);\n used += 2*widthUnit;\n break;\n default:\n ui->twSources->setColumnWidth(i, widthUnit);\n used += widthUnit;\n break;\n }\n }\n\n ui->twSources->setColumnWidth(COL_NAME, width-used-5);\n}\n\nvoid UniverseView::setUiForLoggingState(UniverseView::LOG_STATE state)\n{\n switch(state)\n {\n case LOGGING:\n ui->btnLogToFile->setText(tr(\"Stop Log to File\"));\n break;\n\n default:\n case NOT_LOGGING:\n ui->btnLogToFile->setText(tr(\"Start Log to File\"));\n break;\n }\n}\n\nvoid UniverseView::selectedAddressChanged(int address)\n{\n ui->teInfo->clear();\n m_selectedAddress = address;\n ui->teInfo->clear();\n if(address<0) return;\n\n if(!m_listener) return;\n sACNMergedSourceList list = m_listener->mergedLevels();\n\n QString info;\n\n info.append(tr(\"Address : %1\\n\")\n .arg(address+1));\n\n if(list[address].winningSource)\n {\n int prio;\n if(list[address].winningSource->doing_per_channel)\n prio = list[address].winningSource->priority_array[address];\n else\n prio = list[address].winningSource->priority;\n\n info.append(tr(\"Winning Source : %1 @ %2 (Priority %3)\")\n .arg(list[address].winningSource->name)\n .arg(Preferences::getInstance()->GetFormattedValue(list[address].level))\n .arg(prio));\n if(list[address].otherSources.count()>0)\n {\n foreach(sACNSource *source, list[address].otherSources)\n {\n if(source->doing_per_channel)\n prio = source->priority_array[address];\n else\n prio = source->priority;\n info.append(tr(\"\\nOther Source : %1 @ %2 (Priority %3)\")\n .arg(source->name)\n .arg(Preferences::getInstance()->GetFormattedValue(source->level_array[address]))\n .arg(prio));\n }\n }\n }\n if(!list[address].winningSource)\n {\n info.append(tr(\"No Sources\"));\n }\n\n ui->teInfo->setPlainText(info);\n}\n\nvoid UniverseView::on_btnPause_pressed()\n{\n ui->universeDisplay->pause();\n this->disconnect(m_listener.data());\n ui->btnGo->setEnabled(true);\n ui->btnPause->setEnabled(false);\n ui->sbUniverse->setEnabled(true);\n}\n\nvoid UniverseView::on_btnLogToFile_pressed()\n{\n if(!m_logger)\n {\n \/\/Setup dialog box\n QFileDialog dialog(this);\n dialog.setWindowTitle(APP_NAME);\n dialog.setDirectory(QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation));\n dialog.setNameFilter(\"CSV Files (*.csv)\");\n dialog.setDefaultSuffix(\"csv\");\n dialog.setFileMode(QFileDialog::AnyFile);\n dialog.setViewMode(QFileDialog::Detail);\n dialog.setAcceptMode(QFileDialog::AcceptSave);\n if(dialog.exec()) {\n QString saveName = dialog.selectedFiles().at(0);\n if(saveName.isEmpty()) {\n return;\n }\n m_logger = new MergedUniverseLogger();\n m_logger->start(saveName, m_listener);\n setUiForLoggingState(LOGGING);\n }\n\n }\n else\n {\n m_logger->stop();\n m_logger->deleteLater();\n m_logger = nullptr;\n\n setUiForLoggingState(NOT_LOGGING);\n }\n\n}\n\nvoid UniverseView::on_btnStartFlickerFinder_pressed()\n{\n if(ui->universeDisplay->flickerFinder())\n {\n ui->universeDisplay->setFlickerFinder(false);\n ui->btnStartFlickerFinder->setText(tr(\"Start Flicker Finder\"));\n }\n else\n {\n if(Preferences::getInstance()->getFlickerFinderShowInfo())\n {\n FlickerFinderInfoForm form;\n int result = form.exec();\n if(!result) return;\n }\n ui->universeDisplay->setFlickerFinder(true);\n ui->btnStartFlickerFinder->setText(tr(\"Stop Flicker Finder\"));\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * kinetic-cpp-client\n * Copyright (C) 2014 Seagate Technology.\n *\n * This program is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU General Public License\n * as published by the Free Software Foundation; either version 2\n * of the License, or (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n *\n *\/\n\n#include \"kinetic\/reader_writer.h\"\n\n#include <errno.h>\n#include <unistd.h>\n\n#include \"glog\/logging.h\"\n\nconst uint32_t SOCKET_TIMEOUT = 10000; \/\/10 seconds\n\nnamespace kinetic {\n\nReaderWriter::ReaderWriter(int fd) : fd_(fd) {}\n\nbool ReaderWriter::Read(void *buf, size_t n, int* err) {\n size_t bytes_read = 0;\n uint32_t socket_timeout = 0;\n while (bytes_read < n && socket_timeout < SOCKET_TIMEOUT) {\n int status = read(fd_, reinterpret_cast<char *>(buf) + bytes_read, n - bytes_read);\n if (status == -1 && errno == EINTR) {\n continue;\n } else if (status == -1 && (errno == EAGAIN || errno == EWOULDBLOCK )) {\n\t LOG(INFO) << \"Peer is slow to transmit\";\n\t \/\/Wait for 500us;\n\t usleep(500);\n socket_timeout++;\n continue;\n } else if (status < 0) {\n *err = errno;\n PLOG(WARNING) << \"Failed to read from socket\";\n return false;\n }\n if (status == 0) {\n LOG(WARNING) << \"Unexpected EOF. Socket (TX) may be closed by Peer\";\n return false;\n }\n bytes_read += status;\n }\n\n return true;\n}\n\nbool ReaderWriter::Write(const void *buf, size_t n) {\n size_t bytes_written = 0;\n uint32_t socket_timeout = 0;\n while (bytes_written < n && socket_timeout < SOCKET_TIMEOUT) {\n int status = write(fd_, reinterpret_cast<const char *>(buf) + bytes_written,\n n - bytes_written);\n if (status == -1 && errno == EINTR) {\n continue;\n } else if (status == -1 && (errno == EAGAIN || errno == EWOULDBLOCK)) {\n\t LOG(INFO) << \" Peer is slow to receive\";\n\t usleep(500);\n\t socket_timeout++;\n continue;\n } else if (status < 0) {\t\n PLOG(WARNING) << \"Failed to write to socket\";\n return false;\n }\n if (status == 0) {\n LOG(WARNING) << \"Unexpected EOF, Socket(RX) may be closed by Peer\";\n return false;\n }\n bytes_written += status;\n }\n\n return true;\n}\n\n} \/\/ namespace kinetic\n<commit_msg>Change timeout to 20K<commit_after>\/*\n * kinetic-cpp-client\n * Copyright (C) 2014 Seagate Technology.\n *\n * This program is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU General Public License\n * as published by the Free Software Foundation; either version 2\n * of the License, or (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n *\n *\/\n\n#include \"kinetic\/reader_writer.h\"\n\n#include <errno.h>\n#include <unistd.h>\n\n#include \"glog\/logging.h\"\n\nconst uint32_t SOCKET_TIMEOUT = 20000; \/\/10 seconds\n\nnamespace kinetic {\n\nReaderWriter::ReaderWriter(int fd) : fd_(fd) {}\n\nbool ReaderWriter::Read(void *buf, size_t n, int* err) {\n size_t bytes_read = 0;\n uint32_t socket_timeout = 0;\n while (bytes_read < n && socket_timeout < SOCKET_TIMEOUT) {\n int status = read(fd_, reinterpret_cast<char *>(buf) + bytes_read, n - bytes_read);\n if (status == -1 && errno == EINTR) {\n continue;\n } else if (status == -1 && (errno == EAGAIN || errno == EWOULDBLOCK )) {\n\t LOG(INFO) << \"Peer is slow to transmit\";\n\t \/\/Wait for 500us;\n\t usleep(500);\n socket_timeout++;\n continue;\n } else if (status < 0) {\n *err = errno;\n PLOG(WARNING) << \"Failed to read from socket\";\n return false;\n }\n if (status == 0) {\n LOG(WARNING) << \"Unexpected EOF. Socket (TX) may be closed by Peer\";\n return false;\n }\n bytes_read += status;\n }\n\n return true;\n}\n\nbool ReaderWriter::Write(const void *buf, size_t n) {\n size_t bytes_written = 0;\n uint32_t socket_timeout = 0;\n while (bytes_written < n && socket_timeout < SOCKET_TIMEOUT) {\n int status = write(fd_, reinterpret_cast<const char *>(buf) + bytes_written,\n n - bytes_written);\n if (status == -1 && errno == EINTR) {\n continue;\n } else if (status == -1 && (errno == EAGAIN || errno == EWOULDBLOCK)) {\n\t LOG(INFO) << \" Peer is slow to receive\";\n\t usleep(500);\n\t socket_timeout++;\n continue;\n } else if (status < 0) {\t\n PLOG(WARNING) << \"Failed to write to socket\";\n return false;\n }\n if (status == 0) {\n LOG(WARNING) << \"Unexpected EOF, Socket(RX) may be closed by Peer\";\n return false;\n }\n bytes_written += status;\n }\n\n return true;\n}\n\n} \/\/ namespace kinetic\n<|endoftext|>"} {"text":"<commit_before>#include <QtGui>\n#include \"hled.h\"\n\nstruct HLed::Private\n{\npublic:\n Private()\n : darkerFactor(300), color(Qt::green), isOn(true)\n { }\n\n int darkerFactor;\n QColor color;\n bool isOn;\n};\n\nHLed::HLed(QWidget *parent)\n :QWidget(parent), m_d(new Private)\n{\n}\n\nHLed::~HLed()\n{\n delete m_d;\n}\n\nQColor HLed::color() const\n{\n return m_d->color;\n}\n\nvoid HLed::setColor(const QColor &color)\n{\n if (m_d->color == color)\n return;\n update();\n}\n\nQSize HLed::sizeHint() const\n{\n return QSize(20, 20);\n}\n\nQSize HLed::minimumSizeHint() const\n{\n return QSize(16, 16);\n}\n\nvoid HLed::toggle()\n{\n m_d->isOn = !m_d->isOn;\n update();\n}\n\nvoid HLed::turnOn(bool on)\n{\n m_d->isOn = on;\n update();\n}\n\nvoid HLed::turnOff(bool off)\n{\n turnOn(!off);\n}\n\nvoid HLed::paintEvent(QPaintEvent* \/* event*\/)\n{\n int width = ledWidth();\n\n QPainter painter(this);\n painter.setRenderHint(QPainter::Antialiasing);\n\n QColor color = m_d->isOn ? m_d->color\n : m_d->color.darker(m_d->darkerFactor);\n\n QBrush brush;\n brush.setStyle(Qt::SolidPattern);\n brush.setColor(color);\n painter.setBrush(brush);\n \/\/ draw plain\n painter.drawEllipse(1, 1, width-1, width-1);\n\n QPen pen;\n pen.setWidth(2);\n\n int pos = width \/ 5 + 1;\n int lightWidth = width * 2 \/ 3;\n int lightQuote = 130 * 2 \/ (lightWidth ? lightWidth : 1) + 100;\n\n \/\/ draw bright spot\n while (lightWidth) {\n color = color.lighter(lightQuote);\n pen.setColor(color);\n painter.setPen(pen);\n painter.drawEllipse(pos, pos, lightWidth, lightWidth);\n lightWidth--;\n\n if (!lightWidth)\n break;\n\n painter.drawEllipse(pos, pos, lightWidth, lightWidth);\n lightWidth--;\n\n if (!lightWidth)\n break;\n\n painter.drawEllipse(pos, pos, lightWidth, lightWidth);\n pos++;\n lightWidth--;\n }\n\n \/\/draw border\n painter.setBrush(Qt::NoBrush);\n\n int angle = -720;\n color = palette().color(QPalette::Light);\n\n for (int arc=120; arc<2880; arc+=240) {\n pen.setColor(color);\n painter.setPen(pen);\n int w = width - pen.width()\/2;\n painter.drawArc(pen.width()\/2, pen.width()\/2, w, w, angle+arc, 240);\n painter.drawArc(pen.width()\/2, pen.width()\/2, w, w, angle-arc, 240);\n color = color.darker(110);\n }\n}\n\nint HLed::ledWidth() const\n{\n int width = qMin(this->width(), this->height());\n width -= 2;\n return width > 0 ? width : 0;\n}\n\n<commit_msg>HLed setColor forgot to set<commit_after>#include <QtGui>\n#include \"hled.h\"\n\nstruct HLed::Private\n{\npublic:\n Private()\n : darkerFactor(300), color(Qt::green), isOn(true)\n { }\n\n int darkerFactor;\n QColor color;\n bool isOn;\n};\n\nHLed::HLed(QWidget *parent)\n :QWidget(parent), m_d(new Private)\n{\n}\n\nHLed::~HLed()\n{\n delete m_d;\n}\n\nQColor HLed::color() const\n{\n return m_d->color;\n}\n\nvoid HLed::setColor(const QColor &color)\n{\n if (m_d->color == color)\n return;\n m_d->color = color;\n update();\n}\n\nQSize HLed::sizeHint() const\n{\n return QSize(20, 20);\n}\n\nQSize HLed::minimumSizeHint() const\n{\n return QSize(16, 16);\n}\n\nvoid HLed::toggle()\n{\n m_d->isOn = !m_d->isOn;\n update();\n}\n\nvoid HLed::turnOn(bool on)\n{\n m_d->isOn = on;\n update();\n}\n\nvoid HLed::turnOff(bool off)\n{\n turnOn(!off);\n}\n\nvoid HLed::paintEvent(QPaintEvent* \/* event*\/)\n{\n int width = ledWidth();\n\n QPainter painter(this);\n painter.setRenderHint(QPainter::Antialiasing);\n\n QColor color = m_d->isOn ? m_d->color\n : m_d->color.darker(m_d->darkerFactor);\n\n QBrush brush;\n brush.setStyle(Qt::SolidPattern);\n brush.setColor(color);\n painter.setBrush(brush);\n \/\/ draw plain\n painter.drawEllipse(1, 1, width-1, width-1);\n\n QPen pen;\n pen.setWidth(2);\n\n int pos = width \/ 5 + 1;\n int lightWidth = width * 2 \/ 3;\n int lightQuote = 130 * 2 \/ (lightWidth ? lightWidth : 1) + 100;\n\n \/\/ draw bright spot\n while (lightWidth) {\n color = color.lighter(lightQuote);\n pen.setColor(color);\n painter.setPen(pen);\n painter.drawEllipse(pos, pos, lightWidth, lightWidth);\n lightWidth--;\n\n if (!lightWidth)\n break;\n\n painter.drawEllipse(pos, pos, lightWidth, lightWidth);\n lightWidth--;\n\n if (!lightWidth)\n break;\n\n painter.drawEllipse(pos, pos, lightWidth, lightWidth);\n pos++;\n lightWidth--;\n }\n\n \/\/draw border\n painter.setBrush(Qt::NoBrush);\n\n int angle = -720;\n color = palette().color(QPalette::Light);\n\n for (int arc=120; arc<2880; arc+=240) {\n pen.setColor(color);\n painter.setPen(pen);\n int w = width - pen.width()\/2;\n painter.drawArc(pen.width()\/2, pen.width()\/2, w, w, angle+arc, 240);\n painter.drawArc(pen.width()\/2, pen.width()\/2, w, w, angle-arc, 240);\n color = color.darker(110);\n }\n}\n\nint HLed::ledWidth() const\n{\n int width = qMin(this->width(), this->height());\n width -= 2;\n return width > 0 ? width : 0;\n}\n\n<|endoftext|>"} {"text":"<commit_before>#if defined(DEBUGGER_BRIDGE)\n\n#include \"dbg_delayload.h\"\n#include <windows.h>\n#define DELAYIMP_INSECURE_WRITABLE_HOOKS\n#include <DelayImp.h>\n#include \"dbg_luacompatibility.h\"\n\nnamespace delayload\n{\n\tstatic std::wstring luadll_path;\n\tstatic HMODULE luadll_handle = 0;\n\tstatic GetLuaApi get_lua_api = ::GetProcAddress;\n\n\tvoid set_luadll(const std::wstring& path)\n\t{\n\t\tluadll_path = path;\n\t\tget_lua_api = ::GetProcAddress;\n\t}\n\n\tvoid set_luadll(HMODULE handle, GetLuaApi fn)\n\t{\n\t\tluadll_handle = handle;\n\t\tget_lua_api = fn ? fn : ::GetProcAddress;\n\t}\n\n\tstatic FARPROC WINAPI hook(unsigned dliNotify, PDelayLoadInfo pdli)\n\t{\n\t\tswitch (dliNotify) {\n\t\tcase dliStartProcessing:\n\t\t\tbreak;\n\t\tcase dliNotePreLoadLibrary:\n\t\t\tif (strcmp(\"lua53.dll\", pdli->szDll) == 0) {\n\t\t\t\tif (!luadll_path.empty()) {\n\t\t\t\t\tHMODULE m = LoadLibraryW(luadll_path.c_str());\n\t\t\t\t\tlua::check_version(m);\n\t\t\t\t\treturn (FARPROC)m;\n\t\t\t\t}\n\t\t\t\telse if (luadll_handle) {\n\t\t\t\t\tlua::check_version(luadll_handle);\n\t\t\t\t\treturn (FARPROC)luadll_handle;\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak;\n\t\tcase dliNotePreGetProcAddress: {\n\t\t\tFARPROC ret = get_lua_api(pdli->hmodCur, pdli->dlp.szProcName);\n\t\t\tif (ret) {\n\t\t\t\treturn ret;\n\t\t\t}\n\t\t\tif (strcmp(pdli->dlp.szProcName, \"lua_getuservalue\") == 0) {\n\t\t\t\tlua::lua54::lua_getiuservalue = (int(__cdecl*)(lua_State*, int, int))get_lua_api(pdli->hmodCur, \"lua_getiuservalue\");\n\t\t\t\tif (lua::lua54::lua_getiuservalue) {\n\t\t\t\t\treturn (FARPROC)lua::lua54::lua_getuservalue;\n\t\t\t\t}\n\t\t\t}\n\t\t\tchar str[256];\n\t\t\tsprintf(str, \"Can't find lua c function: `%s`.\", pdli->dlp.szProcName);\n\t\t\tMessageBoxA(0, \"Fatal Error.\", str, 0);\n\t\t\treturn NULL;\n\t\t}\n\t\t\tbreak;\n\t\tcase dliFailLoadLib:\n\t\t\tbreak;\n\t\tcase dliFailGetProc:\n\t\t\tbreak;\n\t\tcase dliNoteEndProcessing:\n\t\t\tbreak;\n\t\tdefault:\n\t\t\treturn NULL;\n\t\t}\n\t\treturn NULL;\n\t}\n}\n\nPfnDliHook __pfnDliNotifyHook2 = delayload::hook;\n\n#endif\n<commit_msg>setluadll只能用一次<commit_after>#if defined(DEBUGGER_BRIDGE)\n\n#include \"dbg_delayload.h\"\n#include <windows.h>\n#define DELAYIMP_INSECURE_WRITABLE_HOOKS\n#include <DelayImp.h>\n#include \"dbg_luacompatibility.h\"\n\nnamespace delayload\n{\n\tstatic std::wstring luadll_path;\n\tstatic HMODULE luadll_handle = 0;\n\tstatic GetLuaApi get_lua_api = ::GetProcAddress;\n\n\tbool has_luadll()\n\t{\n\t\treturn !luadll_path.empty() || luadll_handle != 0;\n\t}\n\n\tvoid set_luadll(const std::wstring& path)\n\t{\n\t\tif (has_luadll()) return;\n\t\tluadll_path = path;\n\t\tget_lua_api = ::GetProcAddress;\n\t}\n\n\tvoid set_luadll(HMODULE handle, GetLuaApi fn)\n\t{\n\t\tif (has_luadll()) return;\n\t\tluadll_handle = handle;\n\t\tget_lua_api = fn ? fn : ::GetProcAddress;\n\t}\n\n\tstatic FARPROC WINAPI hook(unsigned dliNotify, PDelayLoadInfo pdli)\n\t{\n\t\tswitch (dliNotify) {\n\t\tcase dliStartProcessing:\n\t\t\tbreak;\n\t\tcase dliNotePreLoadLibrary:\n\t\t\tif (strcmp(\"lua53.dll\", pdli->szDll) == 0) {\n\t\t\t\tif (!luadll_path.empty()) {\n\t\t\t\t\tHMODULE m = LoadLibraryW(luadll_path.c_str());\n\t\t\t\t\tlua::check_version(m);\n\t\t\t\t\treturn (FARPROC)m;\n\t\t\t\t}\n\t\t\t\telse if (luadll_handle) {\n\t\t\t\t\tlua::check_version(luadll_handle);\n\t\t\t\t\treturn (FARPROC)luadll_handle;\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak;\n\t\tcase dliNotePreGetProcAddress: {\n\t\t\tFARPROC ret = get_lua_api(pdli->hmodCur, pdli->dlp.szProcName);\n\t\t\tif (ret) {\n\t\t\t\treturn ret;\n\t\t\t}\n\t\t\tif (strcmp(pdli->dlp.szProcName, \"lua_getuservalue\") == 0) {\n\t\t\t\tlua::lua54::lua_getiuservalue = (int(__cdecl*)(lua_State*, int, int))get_lua_api(pdli->hmodCur, \"lua_getiuservalue\");\n\t\t\t\tif (lua::lua54::lua_getiuservalue) {\n\t\t\t\t\treturn (FARPROC)lua::lua54::lua_getuservalue;\n\t\t\t\t}\n\t\t\t}\n\t\t\tchar str[256];\n\t\t\tsprintf(str, \"Can't find lua c function: `%s`.\", pdli->dlp.szProcName);\n\t\t\tMessageBoxA(0, \"Fatal Error.\", str, 0);\n\t\t\treturn NULL;\n\t\t}\n\t\t\tbreak;\n\t\tcase dliFailLoadLib:\n\t\t\tbreak;\n\t\tcase dliFailGetProc:\n\t\t\tbreak;\n\t\tcase dliNoteEndProcessing:\n\t\t\tbreak;\n\t\tdefault:\n\t\t\treturn NULL;\n\t\t}\n\t\treturn NULL;\n\t}\n}\n\nPfnDliHook __pfnDliNotifyHook2 = delayload::hook;\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/**\n * The MIT License (MIT)\n *\n * Copyright (c) 2015 Nathan Osman\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to\n * deal in the Software without restriction, including without limitation the\n * rights to use, copy, modify, merge, publish, distribute, sublicense, and\/or\n * sell copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n * IN THE SOFTWARE.\n **\/\n\n#include <QStringList>\n\n#include \"version.h\"\n\nVersion::Version(const QString &versionString)\n : mMajor(0),\n mMinor(0),\n mPatch(0)\n{\n \/\/ Split into components and assign them to the correct member\n QStringList components = versionString.split('.');\n\n mMajor = components.at(0).toInt();\n if(components.count() > 1) {\n mMinor = components.at(1).toInt();\n }\n if(components.count() > 2) {\n mPatch = components.at(2).toInt();\n }\n}\n\nVersion::Version(int major, int minor, int patch)\n : mMajor(major),\n mMinor(minor),\n mPatch(patch)\n{\n}\n\nbool Version::operator==(const Version &other) const\n{\n return mMajor == other.mMajor &&\n mMinor == other.mMinor &&\n mPatch == other.mPatch;\n}\n\nbool Version::operator!=(const Version &other) const\n{\n return !(*this == other);\n}\n\nbool Version::operator<(const Version &other) const\n{\n return mMajor < other.mMajor ||\n (mMajor == other.mMajor && mMinor < other.mMinor) ||\n (mMajor == other.mMajor && mMinor == other.mMinor && mPatch < other.mPatch);\n}\n\nbool Version::operator>(const Version &other) const\n{\n return !(*this < other || *this == other);\n}\n\nbool Version::operator>=(const Version &other) const\n{\n return !(*this < other);\n}\n\nbool Version::operator<=(const Version &other) const\n{\n return !(*this > other);\n}\n<commit_msg>Switched to QRegExp for initializing version from string.<commit_after>\/**\n * The MIT License (MIT)\n *\n * Copyright (c) 2015 Nathan Osman\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to\n * deal in the Software without restriction, including without limitation the\n * rights to use, copy, modify, merge, publish, distribute, sublicense, and\/or\n * sell copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n * IN THE SOFTWARE.\n **\/\n\n#include <QRegExp>\n\n#include \"version.h\"\n\n\/\/ Match any version in the format \"xx.yy.zz\"\nconst QRegExp VersionPattern(\"^(\\\\d+).(\\\\d+).(\\\\d+)$\");\n\nVersion::Version(const QString &versionString)\n : mMajor(0),\n mMinor(0),\n mPatch(0)\n{\n if(!VersionPattern.indexIn(versionString)) {\n mMajor = VersionPattern.cap(1).toInt();\n mMinor = VersionPattern.cap(2).toInt();\n mPatch = VersionPattern.cap(3).toInt();\n }\n}\n\nVersion::Version(int major, int minor, int patch)\n : mMajor(major),\n mMinor(minor),\n mPatch(patch)\n{\n}\n\nbool Version::operator==(const Version &other) const\n{\n return mMajor == other.mMajor &&\n mMinor == other.mMinor &&\n mPatch == other.mPatch;\n}\n\nbool Version::operator!=(const Version &other) const\n{\n return !(*this == other);\n}\n\nbool Version::operator<(const Version &other) const\n{\n return mMajor < other.mMajor ||\n (mMajor == other.mMajor && mMinor < other.mMinor) ||\n (mMajor == other.mMajor && mMinor == other.mMinor && mPatch < other.mPatch);\n}\n\nbool Version::operator>(const Version &other) const\n{\n return !(*this < other || *this == other);\n}\n\nbool Version::operator>=(const Version &other) const\n{\n return !(*this < other);\n}\n\nbool Version::operator<=(const Version &other) const\n{\n return !(*this > other);\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"libpstack\/dwarf.h\"\n#include \"libpstack\/flags.h\"\n#include \"libpstack\/global.h\"\n#include \"libpstack\/proc.h\"\n#include \"libpstack\/fs.h\"\n#include \"libpstack\/ps_callback.h\"\n#if defined(WITH_PYTHON2) || defined(WITH_PYTHON3)\n#define WITH_PYTHON\n#include \"libpstack\/python.h\"\n#endif\n\n#include <sys\/types.h>\n#include <sys\/signal.h>\n#include <sys\/wait.h>\n\n#include <sysexits.h>\n#include <unistd.h>\n\n#include <csignal>\n#include <algorithm>\n#include <fstream>\n#include <iostream>\n#include <set>\n\n#define XSTR(a) #a\n#define STR(a) XSTR(a)\nextern std::ostream & operator << (std::ostream &os, const JSON<ThreadStack, Process *> &jt);\n\nnamespace {\nbool doJson = false;\nvolatile bool interrupted = false;\n\nvoid\npstack(Process &proc, const PstackOptions &options, int maxFrames)\n{\n const auto &threadStacks = proc.getStacks(options, maxFrames);\n auto &os = *options.output;\n if (doJson) {\n os << json(threadStacks, &proc);\n } else {\n os << \"process: \" << *proc.io << \"\\n\";\n for (auto &s : threadStacks) {\n proc.dumpStackText(os, s, options);\n os << std::endl;\n }\n }\n}\n\nint\nstartChild(Elf::Object::sptr exe, const std::string &cmd, const PstackOptions &options, Dwarf::ImageCache &ic) {\n std::vector<std::string> args;\n for (size_t off = 0;;) {\n auto pos = cmd.find(' ', off);\n if (pos == std::string::npos) {\n args.push_back(cmd.substr(off));\n break;\n } else {\n args.push_back(cmd.substr(off, pos));\n off = pos + 1;\n }\n }\n\n int rc, status;\n pid_t pid = fork();\n switch (pid) {\n case 0: {\n rc = ptrace(PTRACE_TRACEME, 0, 0, 0);\n assert(rc == 0);\n if (verbose > 2)\n *debug << getpid() << \" traced, waiting for debugger...\" << std::endl;\n raise(SIGSTOP);\n if (verbose > 2)\n *debug << getpid() << \" ... resumed\\n\";\n std::vector<const char *> sysargs;\n std::transform(args.begin(), args.end(), std::back_inserter(sysargs),\n [] (const std::string &arg) { return arg.c_str(); });\n sysargs.push_back(nullptr);\n execvp(sysargs[0], (char **)&sysargs[0]);\n if (verbose > 2)\n *debug << getpid() << \" execvp failed: \" << strerror(errno) << \"\\n\";\n \/\/ child\n break;\n }\n case -1:\n \/\/ error\n return -1;\n default:\n\n std::shared_ptr<Process> p;\n while (true) {\n if (verbose > 2)\n *debug << getpid() << \" waiting...\\n\";\n rc = wait(&status);\n if (rc != pid) {\n if (verbose > 2)\n *debug << getpid() << \"... wait failed: \" << strerror(errno) << \"\\n\";\n break;\n }\n if (verbose > 2)\n *debug << getpid() << \"... done - rc=\" << rc << \", status=\" << WaitStatus(status) << \"\\n\";\n\n if (WIFSTOPPED(status)) {\n int contsig = WSTOPSIG(status);\n switch (contsig) {\n case SIGSTOP:\n contsig = 0;\n break;\n case SIGTRAP:\n contsig = 0;\n break;\n default:\n if (p == nullptr) {\n p = std::make_shared<LiveProcess>(exe, pid, options, ic, true);\n p->load();\n }\n pstack(*p, std::cout, options, 100);\n }\n rc = ptrace(PTRACE_CONT, pid, 0, contsig == SIGTRAP ? 0 : contsig);\n if (rc == -1)\n *debug << getpid() << \" ptrace failed to continue - \" << strerror(errno) << \"\\n\";\n\n assert(rc == 0);\n if (verbose > 2)\n *debug << getpid() << \"..done\\n\";\n } else {\n return 0;\n }\n }\n break;\n }\n return 0;\n}\n\n\n#ifdef WITH_PYTHON\ntemplate<int V> void doPy(Process &proc, const PstackOptions &options, bool showModules, const PyInterpInfo &info) {\n StopProcess here(&proc);\n PythonPrinter<V> printer(proc, *options.output, options, info);\n if (!printer.interpFound())\n throw Exception() << \"no python interpreter found\";\n printer.printInterpreters(showModules);\n}\n\n\/**\n * @brief Given a process, tries to print the Python strack trace of it.\n * If the process wasn't a Python process, returns false.\n * True on successful printing of Python stack trace\n * \n * @param proc The process\n * @param o The stream to which to print the otutput\n * @param options Options\n * @param showModules Whether to show modules\n * @return boolean of whether the process was a Python process or not\n *\/\nbool pystack(Process &proc, const PstackOptions &options, bool showModules) {\n PyInterpInfo info = getPyInterpInfo(proc);\n\n if (info.libpython == nullptr) \/\/ not a python process or python interpreter not found\n return false;\n\n if (info.versionHex < V2HEX(3, 0)) { \/\/ Python 2.x\n#ifdef WITH_PYTHON2\n doPy<2>(proc, options, showModules, info);\n#else\n throw (Exception() << \"no support for discovered python 2 interpreter\");\n#endif\n } else { \/\/ Python 3.x\n#ifdef WITH_PYTHON3\n doPy<3>(proc, options, showModules, info);\n#else\n throw (Exception() << \"no support for discovered python 3 interpreter\");\n#endif\n }\n return true;\n}\n#endif\n\nint\nusage(std::ostream &os, const char *name, const Flags &options)\n{\n os <<\n\"usage: \" << name << \" <[ exe ] <PID | core> >+\\n\"\n\"\\n\"\n\"print a stack trace of PID or core. If specified, assume image was created from\\n\"\n\" execing `exe`, otherwise, the executable is inferred from the process or core\\n\"\n\"\\n\"\n\"available options:\\n\" << options << \"\\n\";\n return EX_USAGE;\n}\n\nint\nemain(int argc, char **argv, Dwarf::ImageCache &imageCache)\n{\n int maxFrames = 1024;\n double sleepTime = 0.0;\n PstackOptions options;\n std::ofstream out;\n\n#if defined(WITH_PYTHON)\n bool doPython = false;\n bool pythonModules = false;\n#endif\n std::vector<std::string> btLogs;\n std::string execName;\n bool printAllStacks = false;\n int exitCode = -1; \/\/ used for options that exit immediately to signal exit.\n std::string subprocessCmd;\n\n Flags flags;\n flags\n .add(\"replace-path\",\n 'F',\n \"from:to\",\n \"replace `from` with `to` in paths when finding shared libraries\",\n [&](const char *arg) {\n auto sep = strchr(arg, ':');\n if (sep == 0)\n usage(std::cerr, argv[0], flags);\n pathReplacements.push_back(std::make_pair(\n std::string(arg, sep - arg), std::string(sep + 1))); })\n\n .add(\"debug-dir\",\n 'g',\n \"directory\",\n \"extra location to find debug files for binaries and shared libraries\",\n [&](const char *arg) { Elf::globalDebugDirectories.push_back(arg); })\n\n .add(\"constant\",\n 'b',\n \"delay\",\n \"repeat pstack, with `delay` seconds between each iteration (can be non-integer)\",\n Flags::set(sleepTime))\n\n .add(\"elf-dump\",\n 'd',\n \"ELF file\",\n \"dump details of an ELF image in JSON and exit\",\n [&](const char *arg) {\n *options.output << json(Elf::Object(imageCache, loadFile(arg)));\n exitCode = 0; })\n\n .add(\"dwarf-dump\",\n 'D',\n \"ELF file\",\n \"dump details of DWARF information in an ELF image in JSON and exit\",\n [&](const char *arg) {\n auto dumpobj = std::make_shared<Elf::Object>(imageCache, loadFile(arg));\n auto di = std::make_shared<Dwarf::Info>(dumpobj, imageCache);\n *options.output << json(*di);\n exitCode = 0; })\n\n .add(\"depth\",\n 'r',\n \"depth\",\n \"max depth when printing python structures\",\n Flags::set(options.maxdepth))\n\n .add(\"max-frames\",\n 'M',\n \"max frames\",\n \"maximum number of stack frames to print for a thread\",\n Flags::set(maxFrames))\n\n .add(\"help\",\n 'h',\n \"generate this help message\",\n [&]() { exitCode = usage(std::cout, argv[0], flags); })\n\n .add(\"args\",\n 'a',\n \"attempt to show the value of arguments to functions\",\n Flags::setf(options.doargs))\n\n .add(\"json\",\n 'j',\n \"use JSON output rather than plaintext\",\n Flags::setf(doJson))\n\n .add(\"no-src\",\n 's',\n \"don't include source info\",\n Flags::setf(options.nosrc))\n\n .add(\"verbose\",\n 'v',\n \"more debugging data. Can be repeated\",\n [&]() { ++verbose; })\n\n .add(\"no-threaddb\",\n 't',\n \"don't use the thread_db functions to enumerate pthreads (just uses LWPs)\",\n Flags::setf(options.nothreaddb))\n\n .add(\"all\",\n 'A',\n \"show both python and DWARF (C\/C++\/go\/rust) stack traces\",\n Flags::setf(printAllStacks))\n\n .add(\"no-ext-debug\",\n 'n',\n \"don't load external debugging information when processing\",\n Flags::setf(Elf::noExtDebug))\n\n .add(\"version\",\n 'V',\n \"dump version and exit\",\n [&]() {\n std::clog << STR(VERSION) << \"\\n\";\n exitCode = 0; })\n\n#ifdef WITH_PYTHON\n .add(\"python-modules\",\n 'm',\n \"print contents of all python modules when tracing\",\n Flags::setf(pythonModules))\n\n .add(\"python\",\n 'p',\n \"print python stack traces\",\n Flags::setf(doPython))\n\n .add(\"locals\",\n 'l',\n \"print local variables (just python for now)\",\n Flags::setf(options.dolocals))\n#endif\n .add(\"from-log\",\n 'L',\n \"log-file\",\n \"print stack trace given log file including instruction pointers\",\n [&](const char *log) {\n btLogs.push_back(log);\n })\n .add(\"executable\",\n 'e',\n \"executable\",\n \"executable to use by default\", [&](const char *opt) { execName = opt; })\n .add(\"command\",\n 'x',\n \"command line\",\n \"execute command line as subprocess\", Flags::set<std::string>(subprocessCmd))\n .add(\"output\",\n 'o',\n \"output file\",\n \"write output to <output file> instead of stdout\", [&options, &out] (const char *opt) {\n out = std::move(std::ofstream(opt, std::ofstream::out|std::ofstream::trunc));\n options.output = &out;\n })\n .parse(argc, argv);\n\n if (exitCode != -1)\n return exitCode;\n\n \/\/ any instance of a non-core ELF image will override default behaviour of\n \/\/ discovering the executable\n Elf::Object::sptr exec;\n if (execName != \"\")\n exec = imageCache.getImageForName(execName);\n\n if (subprocessCmd != \"\") {\n \/\/ create a new process and trace it.\n startChild(exec, subprocessCmd, options, imageCache);\n return 0;\n }\n\n if (optind == argc && btLogs.empty())\n return usage(std::cerr, argv[0], flags);\n\n auto doStack = [=, &options] (Process &proc) {\n proc.load();\n while (!interrupted) {\n#if defined(WITH_PYTHON)\n if (doPython || printAllStacks) {\n bool isPythonProcess = pystack(proc, options, pythonModules);\n \/\/ error if -p but not python process\n if (doPython && !isPythonProcess)\n throw Exception() << \"Couldn't find a Python interpreter\";\n }\n if (!doPython)\n#endif\n {\n pstack(proc, options, maxFrames);\n }\n if (sleepTime != 0.0)\n usleep(sleepTime * 1000000);\n else\n break;\n }\n };\n\n if (!btLogs.empty()) {\n LogProcess lp{exec, btLogs, options, imageCache};\n doStack(lp);\n return 0;\n } else {\n for (int i = optind; i < argc; i++) {\n try {\n auto process = Process::load(exec, argv[i], options, imageCache);\n if (process == nullptr)\n exec = imageCache.getImageForName(argv[i]);\n else\n doStack(*process);\n } catch (const std::exception &e) {\n std::cerr << \"trace of \" << argv[i] << \" failed: \" << e.what() << \"\\n\";\n }\n }\n }\n return 0;\n}\n}\n\nint\nmain(int argc, char **argv)\n{\n try {\n Dwarf::ImageCache imageCache;\n struct sigaction sa;\n memset(&sa, 0, sizeof sa);\n sa.sa_handler = [](int) { interrupted = true; };\n \/\/ Only interrupt cleanly once. Then just terminate, in case we're stuck in a loop\n sa.sa_flags = SA_RESETHAND;\n sigaction(SIGINT, &sa, nullptr);\n emain(argc, argv, imageCache);\n exit(0);\n }\n catch (std::exception &ex) {\n std::clog << \"error: \" << ex.what() << std::endl;\n return EX_SOFTWARE;\n }\n}\n<commit_msg>Fix up startChild to be useful for tests<commit_after>#include \"libpstack\/dwarf.h\"\n#include \"libpstack\/flags.h\"\n#include \"libpstack\/global.h\"\n#include \"libpstack\/proc.h\"\n#include \"libpstack\/fs.h\"\n#include \"libpstack\/ps_callback.h\"\n#if defined(WITH_PYTHON2) || defined(WITH_PYTHON3)\n#define WITH_PYTHON\n#include \"libpstack\/python.h\"\n#endif\n\n#include <sys\/types.h>\n#include <sys\/signal.h>\n#include <sys\/wait.h>\n\n#include <sysexits.h>\n#include <unistd.h>\n\n#include <csignal>\n#include <algorithm>\n#include <fstream>\n#include <iostream>\n#include <set>\n\n#define XSTR(a) #a\n#define STR(a) XSTR(a)\nextern std::ostream & operator << (std::ostream &os, const JSON<ThreadStack, Process *> &jt);\n\nnamespace {\nbool doJson = false;\nvolatile bool interrupted = false;\n\nvoid\npstack(Process &proc, const PstackOptions &options, int maxFrames)\n{\n const auto &threadStacks = proc.getStacks(options, maxFrames);\n auto &os = *options.output;\n if (doJson) {\n os << json(threadStacks, &proc);\n } else {\n os << \"process: \" << *proc.io << \"\\n\";\n for (auto &s : threadStacks) {\n proc.dumpStackText(os, s, options);\n os << std::endl;\n }\n }\n}\n\n\/\/ This is mostly for testing. We start the process, and run pstack when we see\n\/\/ a signal that is likely to terminate the process, then kill it. This allows\n\/\/ us to reliably run pstack on a process that will abort or segfault, and\n\/\/ doesn't require a readable core file.\nint\nstartChild(Elf::Object::sptr exe, const std::string &cmd, const PstackOptions &options, Dwarf::ImageCache &ic) {\n std::vector<std::string> args;\n for (size_t off = 0;;) {\n auto pos = cmd.find(' ', off);\n if (pos == std::string::npos) {\n args.push_back(cmd.substr(off));\n break;\n } else {\n args.push_back(cmd.substr(off, pos));\n off = pos + 1;\n }\n }\n\n int rc, status;\n pid_t pid = fork();\n switch (pid) {\n case 0: {\n rc = ptrace(PTRACE_TRACEME, 0, 0, 0);\n assert(rc == 0);\n std::vector<const char *> sysargs;\n std::transform(args.begin(), args.end(), std::back_inserter(sysargs),\n [] (const std::string &arg) { return arg.c_str(); });\n sysargs.push_back(nullptr);\n execvp(sysargs[0], (char **)&sysargs[0]);\n if (verbose > 2)\n *debug << getpid() << \" execvp failed: \" << strerror(errno) << \"\\n\";\n \/\/ child\n break;\n }\n case -1:\n \/\/ error\n return -1;\n default:\n std::shared_ptr<Process> p;\n char statusBuf[PATH_MAX];\n snprintf(statusBuf, sizeof statusBuf, \"\/proc\/%d\/status\", pid);\n struct closer { void operator()(FILE *f){ fclose(f); }};\n std::unique_ptr<FILE, closer> statusFile { fopen(statusBuf, \"r\") };\n assert(statusFile.get());\n\n for (;;) {\n if (verbose > 2)\n *debug << getpid() << \" waiting...\\n\";\n rc = wait(&status);\n if (rc != pid) {\n if (verbose > 2)\n *debug << getpid() << \"... wait failed: \" << strerror(errno) << \"\\n\";\n break;\n }\n if (verbose > 2)\n *debug << getpid() << \"... done - rc=\" << rc << \", status=\" << WaitStatus(status) << \"\\n\";\n\n if (WIFSTOPPED(status)) {\n \/\/ Read the content of the process's SigIgn and SigCgt info from procfs.\n fflush(statusFile.get());\n fseek(statusFile.get(), 0, SEEK_SET);\n char line[PATH_MAX];\n unsigned long sigblk = -1, sigign = -1, sigcgt = -1;\n while (fgets(line, sizeof line, statusFile.get()) != NULL) {\n if (strncmp(line, \"SigBlk:\\t\", 8) == 0)\n sigblk = strtoul(line + 8, 0, 16);\n else if (strncmp(line, \"SigCgt:\\t\", 8) == 0)\n sigcgt = strtoul(line + 8, 0, 16);\n else if (strncmp(line, \"SigIgn:\\t\", 8) == 0)\n sigign = strtoul(line + 8, 0, 16);\n }\n unsigned long handledSigs = sigblk | sigcgt | sigign;\n handledSigs |= 1 << (SIGTRAP - 1);\n int stopsig = WSTOPSIG(status);\n int contsig = stopsig == SIGSTOP || stopsig == SIGTRAP ? 0 : stopsig;\n if (((1 << (stopsig -1)) & handledSigs) == 0) {\n p = std::make_shared<LiveProcess>(exe, pid, options, ic, true);\n p->load();\n pstack(*p, options, 100);\n rc = ptrace(PTRACE_KILL, pid, 0, contsig);\n } else {\n rc = ptrace(PTRACE_CONT, pid, 0, contsig);\n }\n if (rc == -1)\n *debug << getpid() << \" ptrace failed to kill\/continue - \" << strerror(errno) << \"\\n\";\n assert(rc == 0);\n if (verbose > 2)\n *debug << getpid() << \"..done\\n\";\n }\n else {\n return 0;\n }\n }\n break;\n }\n return 0;\n}\n\n\n#ifdef WITH_PYTHON\ntemplate<int V> void doPy(Process &proc, const PstackOptions &options, bool showModules, const PyInterpInfo &info) {\n StopProcess here(&proc);\n PythonPrinter<V> printer(proc, *options.output, options, info);\n if (!printer.interpFound())\n throw Exception() << \"no python interpreter found\";\n printer.printInterpreters(showModules);\n}\n\n\/**\n * @brief Given a process, tries to print the Python strack trace of it.\n * If the process wasn't a Python process, returns false.\n * True on successful printing of Python stack trace\n * \n * @param proc The process\n * @param o The stream to which to print the otutput\n * @param options Options\n * @param showModules Whether to show modules\n * @return boolean of whether the process was a Python process or not\n *\/\nbool pystack(Process &proc, const PstackOptions &options, bool showModules) {\n PyInterpInfo info = getPyInterpInfo(proc);\n\n if (info.libpython == nullptr) \/\/ not a python process or python interpreter not found\n return false;\n\n if (info.versionHex < V2HEX(3, 0)) { \/\/ Python 2.x\n#ifdef WITH_PYTHON2\n doPy<2>(proc, options, showModules, info);\n#else\n throw (Exception() << \"no support for discovered python 2 interpreter\");\n#endif\n } else { \/\/ Python 3.x\n#ifdef WITH_PYTHON3\n doPy<3>(proc, options, showModules, info);\n#else\n throw (Exception() << \"no support for discovered python 3 interpreter\");\n#endif\n }\n return true;\n}\n#endif\n\nint\nusage(std::ostream &os, const char *name, const Flags &options)\n{\n os <<\n\"usage: \" << name << \" <[ exe ] <PID | core> >+\\n\"\n\"\\n\"\n\"print a stack trace of PID or core. If specified, assume image was created from\\n\"\n\" execing `exe`, otherwise, the executable is inferred from the process or core\\n\"\n\"\\n\"\n\"available options:\\n\" << options << \"\\n\";\n return EX_USAGE;\n}\n\nint\nemain(int argc, char **argv, Dwarf::ImageCache &imageCache)\n{\n int maxFrames = 1024;\n double sleepTime = 0.0;\n PstackOptions options;\n std::ofstream out;\n\n#if defined(WITH_PYTHON)\n bool doPython = false;\n bool pythonModules = false;\n#endif\n std::vector<std::string> btLogs;\n std::string execName;\n bool printAllStacks = false;\n int exitCode = -1; \/\/ used for options that exit immediately to signal exit.\n std::string subprocessCmd;\n\n Flags flags;\n flags\n .add(\"replace-path\",\n 'F',\n \"from:to\",\n \"replace `from` with `to` in paths when finding shared libraries\",\n [&](const char *arg) {\n auto sep = strchr(arg, ':');\n if (sep == 0)\n usage(std::cerr, argv[0], flags);\n pathReplacements.push_back(std::make_pair(\n std::string(arg, sep - arg), std::string(sep + 1))); })\n\n .add(\"debug-dir\",\n 'g',\n \"directory\",\n \"extra location to find debug files for binaries and shared libraries\",\n [&](const char *arg) { Elf::globalDebugDirectories.push_back(arg); })\n\n .add(\"constant\",\n 'b',\n \"delay\",\n \"repeat pstack, with `delay` seconds between each iteration (can be non-integer)\",\n Flags::set(sleepTime))\n\n .add(\"elf-dump\",\n 'd',\n \"ELF file\",\n \"dump details of an ELF image in JSON and exit\",\n [&](const char *arg) {\n *options.output << json(Elf::Object(imageCache, loadFile(arg)));\n exitCode = 0; })\n\n .add(\"dwarf-dump\",\n 'D',\n \"ELF file\",\n \"dump details of DWARF information in an ELF image in JSON and exit\",\n [&](const char *arg) {\n auto dumpobj = std::make_shared<Elf::Object>(imageCache, loadFile(arg));\n auto di = std::make_shared<Dwarf::Info>(dumpobj, imageCache);\n *options.output << json(*di);\n exitCode = 0; })\n\n .add(\"depth\",\n 'r',\n \"depth\",\n \"max depth when printing python structures\",\n Flags::set(options.maxdepth))\n\n .add(\"max-frames\",\n 'M',\n \"max frames\",\n \"maximum number of stack frames to print for a thread\",\n Flags::set(maxFrames))\n\n .add(\"help\",\n 'h',\n \"generate this help message\",\n [&]() { exitCode = usage(std::cout, argv[0], flags); })\n\n .add(\"args\",\n 'a',\n \"attempt to show the value of arguments to functions\",\n Flags::setf(options.doargs))\n\n .add(\"json\",\n 'j',\n \"use JSON output rather than plaintext\",\n Flags::setf(doJson))\n\n .add(\"no-src\",\n 's',\n \"don't include source info\",\n Flags::setf(options.nosrc))\n\n .add(\"verbose\",\n 'v',\n \"more debugging data. Can be repeated\",\n [&]() { ++verbose; })\n\n .add(\"no-threaddb\",\n 't',\n \"don't use the thread_db functions to enumerate pthreads (just uses LWPs)\",\n Flags::setf(options.nothreaddb))\n\n .add(\"all\",\n 'A',\n \"show both python and DWARF (C\/C++\/go\/rust) stack traces\",\n Flags::setf(printAllStacks))\n\n .add(\"no-ext-debug\",\n 'n',\n \"don't load external debugging information when processing\",\n Flags::setf(Elf::noExtDebug))\n\n .add(\"version\",\n 'V',\n \"dump version and exit\",\n [&]() {\n std::clog << STR(VERSION) << \"\\n\";\n exitCode = 0; })\n\n#ifdef WITH_PYTHON\n .add(\"python-modules\",\n 'm',\n \"print contents of all python modules when tracing\",\n Flags::setf(pythonModules))\n\n .add(\"python\",\n 'p',\n \"print python stack traces\",\n Flags::setf(doPython))\n\n .add(\"locals\",\n 'l',\n \"print local variables (just python for now)\",\n Flags::setf(options.dolocals))\n#endif\n .add(\"from-log\",\n 'L',\n \"log-file\",\n \"print stack trace given log file including instruction pointers\",\n [&](const char *log) {\n btLogs.push_back(log);\n })\n .add(\"executable\",\n 'e',\n \"executable\",\n \"executable to use by default\", [&](const char *opt) { execName = opt; })\n .add(\"command\",\n 'x',\n \"command line\",\n \"execute command line as subprocess, trace when it receives a signal\", Flags::set<std::string>(subprocessCmd))\n .add(\"output\",\n 'o',\n \"output file\",\n \"write output to <output file> instead of stdout\", [&options, &out] (const char *opt) {\n out = std::move(std::ofstream(opt, std::ofstream::out|std::ofstream::trunc));\n options.output = &out;\n })\n .parse(argc, argv);\n\n if (exitCode != -1)\n return exitCode;\n\n \/\/ any instance of a non-core ELF image will override default behaviour of\n \/\/ discovering the executable\n Elf::Object::sptr exec;\n if (execName != \"\")\n exec = imageCache.getImageForName(execName);\n\n if (subprocessCmd != \"\") {\n \/\/ create a new process and trace it.\n startChild(exec, subprocessCmd, options, imageCache);\n return 0;\n }\n\n if (optind == argc && btLogs.empty())\n return usage(std::cerr, argv[0], flags);\n\n auto doStack = [=, &options] (Process &proc) {\n proc.load();\n while (!interrupted) {\n#if defined(WITH_PYTHON)\n if (doPython || printAllStacks) {\n bool isPythonProcess = pystack(proc, options, pythonModules);\n \/\/ error if -p but not python process\n if (doPython && !isPythonProcess)\n throw Exception() << \"Couldn't find a Python interpreter\";\n }\n if (!doPython)\n#endif\n {\n pstack(proc, options, maxFrames);\n }\n if (sleepTime != 0.0)\n usleep(sleepTime * 1000000);\n else\n break;\n }\n };\n if (!btLogs.empty()) {\n LogProcess lp{exec, btLogs, options, imageCache};\n doStack(lp);\n } else {\n for (int i = optind; i < argc; i++) {\n try {\n auto process = Process::load(exec, argv[i], options, imageCache);\n if (process == nullptr)\n exec = imageCache.getImageForName(argv[i]);\n else\n doStack(*process);\n } catch (const std::exception &e) {\n std::cerr << \"trace of \" << argv[i] << \" failed: \" << e.what() << \"\\n\";\n }\n }\n }\n return 0;\n}\n}\n\nint\nmain(int argc, char **argv)\n{\n try {\n Dwarf::ImageCache imageCache;\n struct sigaction sa;\n memset(&sa, 0, sizeof sa);\n sa.sa_handler = [](int) { interrupted = true; };\n \/\/ Only interrupt cleanly once. Then just terminate, in case we're stuck in a loop\n sa.sa_flags = SA_RESETHAND;\n sigaction(SIGINT, &sa, nullptr);\n emain(argc, argv, imageCache);\n exit(0);\n }\n catch (std::exception &ex) {\n std::clog << \"error: \" << ex.what() << std::endl;\n return EX_SOFTWARE;\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/* bzflag\n * Copyright (c) 1993 - 2004 Tim Riker\n *\n * This package is free software; you can redistribute it and\/or\n * modify it under the terms of the license found in the file\n * named LICENSE that should have accompanied this file.\n *\n * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR\n * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED\n * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.\n *\/\n\n\/* bzflag special common - 1st one *\/\n#include \"common.h\"\n\n#include <iostream>\n\n#include \"ActionBinding.h\"\n#include \"CommandManager.h\"\n#include \"KeyManager.h\"\n\n\/\/ initialize the singleton\ntemplate <>\nActionBinding* Singleton<ActionBinding>::_instance = (ActionBinding*)0;\n\n\nActionBinding::ActionBinding() {\n wayToBindActions.insert(std::make_pair(std::string(\"quit\"), press));\n wayToBindActions.insert(std::make_pair(std::string(\"fire\"), both));\n wayToBindActions.insert(std::make_pair(std::string(\"drop\"), press));\n wayToBindActions.insert(std::make_pair(std::string(\"identify\"), press));\n wayToBindActions.insert(std::make_pair(std::string(\"jump\"), press));\n wayToBindActions.insert(std::make_pair(std::string(\"send all\"), press));\n wayToBindActions.insert(std::make_pair(std::string(\"send team\"), press));\n wayToBindActions.insert(std::make_pair(std::string(\"send nemesis\"), press));\n wayToBindActions.insert(std::make_pair(std::string(\"send recipient\"), press));\n wayToBindActions.insert(std::make_pair(std::string(\"send admin\"), press));\n wayToBindActions.insert(std::make_pair(std::string(\"toggle displayScore\"), press));\n wayToBindActions.insert(std::make_pair(std::string(\"toggle displayBinoculars\"), press));\n wayToBindActions.insert(std::make_pair(std::string(\"pause\"), press));\n wayToBindActions.insert(std::make_pair(std::string(\"fullscreen\"), press));\n wayToBindActions.insert(std::make_pair(std::string(\"iconify\"), press));\n#ifdef SNAPPING\n wayToBindActions.insert(std::make_pair(std::string(\"screenshot\"), press));\n#endif\n wayToBindActions.insert(std::make_pair(std::string(\"time backward\"), press));\n wayToBindActions.insert(std::make_pair(std::string(\"time forward\"), press));\n wayToBindActions.insert(std::make_pair(std::string(\"toggleFlags radar\"), press));\n wayToBindActions.insert(std::make_pair(std::string(\"toggleFlags main\"), press));\n wayToBindActions.insert(std::make_pair(std::string(\"silence\"), press));\n wayToBindActions.insert(std::make_pair(std::string(\"toggle displayLabels\"), press));\n wayToBindActions.insert(std::make_pair(std::string(\"destruct\"), press));\n\n \/\/ Movement keys\n wayToBindActions.insert(std::make_pair(std::string(\"turn left\"), both));\n wayToBindActions.insert(std::make_pair(std::string(\"turn right\"), both));\n wayToBindActions.insert(std::make_pair(std::string(\"drive forward\"), both));\n wayToBindActions.insert(std::make_pair(std::string(\"drive reverse\"), both));\n \/\/ End movement keys\n\n wayToBindActions.insert(std::make_pair(std::string(\"roam cycle subject backward\"),\n\t\t\t\t\t press));\n wayToBindActions.insert(std::make_pair(std::string(\"roam cycle subject forward\"), press));\n wayToBindActions.insert(std::make_pair(std::string(\"roam cycle type forward\"), press));\n wayToBindActions.insert(std::make_pair(std::string(\"roam zoom in\"), both));\n wayToBindActions.insert(std::make_pair(std::string(\"roam zoom out\"), both));\n wayToBindActions.insert(std::make_pair(std::string(\"roam zoom normal\"), both));\n wayToBindActions.insert(std::make_pair(std::string(\"servercommand\"), press));\n wayToBindActions.insert(std::make_pair(std::string(\"toggle displayFlagHelp\"), press));\n wayToBindActions.insert(std::make_pair(std::string(\"scrollpanel up\"), press));\n wayToBindActions.insert(std::make_pair(std::string(\"scrollpanel down\"), press));\n wayToBindActions.insert(std::make_pair(std::string(\"set displayRadarRange 0.25\"), press));\n wayToBindActions.insert(std::make_pair(std::string(\"set displayRadarRange 0.5\"), press));\n wayToBindActions.insert(std::make_pair(std::string(\"set displayRadarRange 1.0\"), press));\n wayToBindActions.insert(std::make_pair(std::string(\"toggle slowKeyboard\"), press));\n wayToBindActions.insert(std::make_pair(std::string(\"hunt\"), press));\n wayToBindActions.insert(std::make_pair(std::string(\"restart\"), release));\n wayToBindActions.insert(std::make_pair(std::string(\"autopilot\"), press));\n\n defaultBinding.insert(std::make_pair(std::string(\"F12\"), std::string(\"quit\")));\n defaultBinding.insert(std::make_pair(std::string(\"Left Mouse\"), std::string(\"fire\")));\n defaultBinding.insert(std::make_pair(std::string(\"Enter\"), std::string(\"fire\")));\n defaultBinding.insert(std::make_pair(std::string(\"Middle Mouse\"), std::string(\"drop\")));\n defaultBinding.insert(std::make_pair(std::string(\"Space\"), std::string(\"drop\")));\n defaultBinding.insert(std::make_pair(std::string(\"Right Mouse\"), std::string(\"identify\")));\n defaultBinding.insert(std::make_pair(std::string(\"I\"), std::string(\"identify\")));\n defaultBinding.insert(std::make_pair(std::string(\"Tab\"), std::string(\"jump\")));\n defaultBinding.insert(std::make_pair(std::string(\"N\"), std::string(\"send all\")));\n defaultBinding.insert(std::make_pair(std::string(\"M\"), std::string(\"send team\")));\n defaultBinding.insert(std::make_pair(std::string(\",\"), std::string(\"send nemesis\")));\n defaultBinding.insert(std::make_pair(std::string(\".\"), std::string(\"send recipient\")));\n defaultBinding.insert(std::make_pair(std::string(\"Z\"), std::string(\"send admin\")));\n defaultBinding.insert(std::make_pair(std::string(\"S\"), std::string(\"toggle displayScore\")));\n defaultBinding.insert(std::make_pair(std::string(\"B\"), std::string(\"toggle displayBinoculars\")));\n defaultBinding.insert(std::make_pair(std::string(\"Pause\"), std::string(\"pause\")));\n defaultBinding.insert(std::make_pair(std::string(\"P\"), std::string(\"pause\")));\n defaultBinding.insert(std::make_pair(std::string(\"F1\"),\n\t\t\t\t std::string(\"fullscreen\")));\n defaultBinding.insert(std::make_pair(std::string(\"F4\"), std::string(\"iconify\")));\n#ifdef SNAPPING\n defaultBinding.insert(std::make_pair(std::string(\"F5\"), std::string(\"screenshot\")));\n#endif\n defaultBinding.insert(std::make_pair(std::string(\"-\"), std::string(\"time backward\")));\n defaultBinding.insert(std::make_pair(std::string(\"=\"), std::string(\"time forward\")));\n defaultBinding.insert(std::make_pair(std::string(\"H\"), std::string(\"toggleFlags radar\")));\n defaultBinding.insert(std::make_pair(std::string(\"J\"), std::string(\"toggleFlags main\")));\n defaultBinding.insert(std::make_pair(std::string(\"K\"), std::string(\"silence\")));\n defaultBinding.insert(std::make_pair(std::string(\"L\"), std::string(\"toggle displayLabels\")));\n defaultBinding.insert(std::make_pair(std::string(\"Delete\"), std::string(\"destruct\")));\n\n \/\/ Default movement keys\n defaultBinding.insert(std::make_pair(std::string(\"Left Arrow\"),\n\t\t\t\t std::string(\"turn left\")));\n defaultBinding.insert(std::make_pair(std::string(\"Right Arrow\"),\n\t\t\t\t std::string(\"turn right\")));\n defaultBinding.insert(std::make_pair(std::string(\"Up Arrow\"),\n\t\t\t\t std::string(\"drive forward\")));\n defaultBinding.insert(std::make_pair(std::string(\"Down Arrow\"),\n\t\t\t\t std::string(\"drive reverse\")));\n \/\/ End default movement keys\n\n\n defaultBinding.insert(std::make_pair(std::string(\"F6\"), std::string(\"roam cycle subject backward\")));\n defaultBinding.insert(std::make_pair(std::string(\"F7\"), std::string(\"roam cycle subject forward\")));\n defaultBinding.insert(std::make_pair(std::string(\"F8\"), std::string(\"roam cycle type forward\")));\n defaultBinding.insert(std::make_pair(std::string(\"F9\"), std::string(\"roam zoom in\")));\n defaultBinding.insert(std::make_pair(std::string(\"F10\"), std::string(\"roam zoom out\")));\n defaultBinding.insert(std::make_pair(std::string(\"F11\"), std::string(\"roam zoom normal\")));\n defaultBinding.insert(std::make_pair(std::string(\"O\"), std::string(\"servercommand\")));\n defaultBinding.insert(std::make_pair(std::string(\"F\"), std::string(\"toggle displayFlagHelp\")));\n defaultBinding.insert(std::make_pair(std::string(\"Page Up\"), std::string(\"scrollpanel up\")));\n defaultBinding.insert(std::make_pair(std::string(\"Page Down\"), std::string(\"scrollpanel down\")));\n defaultBinding.insert(std::make_pair(std::string(\"1\"), std::string(\"set displayRadarRange 0.25\")));\n defaultBinding.insert(std::make_pair(std::string(\"2\"), std::string(\"set displayRadarRange 0.5\")));\n defaultBinding.insert(std::make_pair(std::string(\"3\"), std::string(\"set displayRadarRange 1.0\")));\n defaultBinding.insert(std::make_pair(std::string(\"A\"), std::string(\"toggle slowKeyboard\")));\n defaultBinding.insert(std::make_pair(std::string(\"U\"), std::string(\"hunt\")));\n defaultBinding.insert(std::make_pair(std::string(\"Right Mouse\"), std::string(\"restart\")));\n defaultBinding.insert(std::make_pair(std::string(\"I\"), std::string(\"restart\")));\n defaultBinding.insert(std::make_pair(std::string(\"9\"), std::string(\"autopilot\")));\n}\n\nvoid ActionBinding::resetBindings() {\n BindingTable::const_iterator index;\n\n for (index = bindingTable.begin();\n index != bindingTable.end();\n ++index)\n unbind(index->second, index->first);\n\n bindingTable = defaultBinding;\n\n for (index = bindingTable.begin();\n index != bindingTable.end();\n ++index)\n bind(index->second, index->first);\n}\n\nvoid ActionBinding::getFromBindings() {\n bindingTable.clear();\n KEYMGR.iterate(&onScanCB, this);\n}\n\nvoid ActionBinding::onScanCB(const std::string& name, bool,\n\t\t\t const std::string& cmd, void*)\n{\n ActionBinding::instance().associate(name, cmd, false);\n}\n\nvoid ActionBinding::associate(std::string key,\n\t\t\t std::string action,\n\t\t\t bool keyBind) {\n BindingTable::iterator index, next;\n if (!wayToBindActions.count(action))\n return;\n PressStatusBind newStatusBind = wayToBindActions[action];\n for (index = bindingTable.lower_bound( key ); index != bindingTable.upper_bound( key ); index = next) {\n next = index;\n ++next;\n if (newStatusBind == both) {\n if (keyBind)\n\tunbind(index->second, key);\n bindingTable.erase(index);\n } else if (newStatusBind == press) {\n if (wayToBindActions[index->second] != release) {\n\tif (keyBind)\n\t unbind(index->second, key);\n\tbindingTable.erase(index);\n }\n } else {\n if (wayToBindActions[index->second] != press) {\n\tif (keyBind)\n\t unbind(index->second, key);\n\tbindingTable.erase(index);\n }\n }\n }\n bindingTable.insert(std::make_pair(key, action));\n if (keyBind)\n bind(action, key);\n};\n\nvoid ActionBinding::deassociate(std::string action) {\n BindingTable::iterator index, next;\n for (index = bindingTable.begin();\n index != bindingTable.end();\n index = next) {\n next = index;\n ++next;\n if (index->second == action) {\n unbind(action, index->first);\n bindingTable.erase(index);\n }\n }\n};\n\nvoid ActionBinding::bind(std::string action, std::string key) {\n PressStatusBind statusBind = wayToBindActions[action];\n std::string command;\n if (statusBind == press || statusBind == both) {\n command = \"bind \\\"\" + key + \"\\\" down \\\"\" + action + \"\\\"\";\n CMDMGR.run(command);\n };\n if (statusBind == release || statusBind == both) {\n command = \"bind \\\"\" + key + \"\\\" up \\\"\" + action + \"\\\"\";\n CMDMGR.run(command);\n };\n}\n\nvoid ActionBinding::unbind(std::string action, std::string key) {\n PressStatusBind statusBind = wayToBindActions[action];\n std::string command;\n if (statusBind == press || statusBind == both) {\n command = \"unbind \\\"\" + key + \"\\\" down\";\n CMDMGR.run(command);\n };\n if (statusBind == release || statusBind == both) {\n command = \"unbind \\\"\" + key + \"\\\" up\";\n CMDMGR.run(command);\n };\n}\n\n\/\/ Local Variables: ***\n\/\/ mode:C++ ***\n\/\/ tab-width: 8 ***\n\/\/ c-basic-offset: 2 ***\n\/\/ indent-tabs-mode: t ***\n\/\/ End: ***\n\/\/ ex: shiftwidth=2 tabstop=8\n<commit_msg>Adding Message Panel Selection to Shift-F1 - F4<commit_after>\/* bzflag\n * Copyright (c) 1993 - 2004 Tim Riker\n *\n * This package is free software; you can redistribute it and\/or\n * modify it under the terms of the license found in the file\n * named LICENSE that should have accompanied this file.\n *\n * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR\n * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED\n * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.\n *\/\n\n\/* bzflag special common - 1st one *\/\n#include \"common.h\"\n\n#include <iostream>\n\n#include \"ActionBinding.h\"\n#include \"CommandManager.h\"\n#include \"KeyManager.h\"\n\n\/\/ initialize the singleton\ntemplate <>\nActionBinding* Singleton<ActionBinding>::_instance = (ActionBinding*)0;\n\n\nActionBinding::ActionBinding() {\n wayToBindActions.insert(std::make_pair(std::string(\"quit\"), press));\n wayToBindActions.insert(std::make_pair(std::string(\"fire\"), both));\n wayToBindActions.insert(std::make_pair(std::string(\"drop\"), press));\n wayToBindActions.insert(std::make_pair(std::string(\"identify\"), press));\n wayToBindActions.insert(std::make_pair(std::string(\"jump\"), press));\n wayToBindActions.insert(std::make_pair(std::string(\"send all\"), press));\n wayToBindActions.insert(std::make_pair(std::string(\"send team\"), press));\n wayToBindActions.insert(std::make_pair(std::string(\"send nemesis\"), press));\n wayToBindActions.insert(std::make_pair(std::string(\"send recipient\"), press));\n wayToBindActions.insert(std::make_pair(std::string(\"send admin\"), press));\n wayToBindActions.insert(std::make_pair(std::string(\"toggle displayScore\"), press));\n wayToBindActions.insert(std::make_pair(std::string(\"toggle displayBinoculars\"), press));\n wayToBindActions.insert(std::make_pair(std::string(\"pause\"), press));\n wayToBindActions.insert(std::make_pair(std::string(\"fullscreen\"), press));\n wayToBindActions.insert(std::make_pair(std::string(\"iconify\"), press));\n#ifdef SNAPPING\n wayToBindActions.insert(std::make_pair(std::string(\"screenshot\"), press));\n#endif\n wayToBindActions.insert(std::make_pair(std::string(\"time backward\"), press));\n wayToBindActions.insert(std::make_pair(std::string(\"time forward\"), press));\n wayToBindActions.insert(std::make_pair(std::string(\"toggleFlags radar\"), press));\n wayToBindActions.insert(std::make_pair(std::string(\"toggleFlags main\"), press));\n wayToBindActions.insert(std::make_pair(std::string(\"silence\"), press));\n wayToBindActions.insert(std::make_pair(std::string(\"toggle displayLabels\"), press));\n wayToBindActions.insert(std::make_pair(std::string(\"destruct\"), press));\n\n \/\/ Movement keys\n wayToBindActions.insert(std::make_pair(std::string(\"turn left\"), both));\n wayToBindActions.insert(std::make_pair(std::string(\"turn right\"), both));\n wayToBindActions.insert(std::make_pair(std::string(\"drive forward\"), both));\n wayToBindActions.insert(std::make_pair(std::string(\"drive reverse\"), both));\n \/\/ End movement keys\n\n wayToBindActions.insert(std::make_pair(std::string(\"roam cycle subject backward\"),\n\t\t\t\t\t press));\n wayToBindActions.insert(std::make_pair(std::string(\"roam cycle subject forward\"), press));\n wayToBindActions.insert(std::make_pair(std::string(\"roam cycle type forward\"), press));\n wayToBindActions.insert(std::make_pair(std::string(\"roam zoom in\"), both));\n wayToBindActions.insert(std::make_pair(std::string(\"roam zoom out\"), both));\n wayToBindActions.insert(std::make_pair(std::string(\"roam zoom normal\"), both));\n wayToBindActions.insert(std::make_pair(std::string(\"servercommand\"), press));\n wayToBindActions.insert(std::make_pair(std::string(\"toggle displayFlagHelp\"), press));\n wayToBindActions.insert(std::make_pair(std::string(\"scrollpanel up\"), press));\n wayToBindActions.insert(std::make_pair(std::string(\"scrollpanel down\"), press));\n wayToBindActions.insert(std::make_pair(std::string(\"set displayRadarRange 0.25\"), press));\n wayToBindActions.insert(std::make_pair(std::string(\"set displayRadarRange 0.5\"), press));\n wayToBindActions.insert(std::make_pair(std::string(\"set displayRadarRange 1.0\"), press));\n wayToBindActions.insert(std::make_pair(std::string(\"toggle slowKeyboard\"), press));\n wayToBindActions.insert(std::make_pair(std::string(\"hunt\"), press));\n wayToBindActions.insert(std::make_pair(std::string(\"restart\"), release));\n wayToBindActions.insert(std::make_pair(std::string(\"autopilot\"), press));\n\n wayToBindActions.insert(std::make_pair(std::string(\"messagepanel all\"),\n\t\t\t\t\t press));\n wayToBindActions.insert(std::make_pair(std::string(\"messagepanel chat\"),\n\t\t\t\t\t press));\n wayToBindActions.insert(std::make_pair(std::string(\"messagepanel server\"),\n\t\t\t\t\t press));\n wayToBindActions.insert(std::make_pair(std::string(\"messagepanel misc\"),\n\t\t\t\t\t press));\n\n defaultBinding.insert(std::make_pair(std::string(\"F12\"), std::string(\"quit\")));\n defaultBinding.insert(std::make_pair(std::string(\"Left Mouse\"), std::string(\"fire\")));\n defaultBinding.insert(std::make_pair(std::string(\"Enter\"), std::string(\"fire\")));\n defaultBinding.insert(std::make_pair(std::string(\"Middle Mouse\"), std::string(\"drop\")));\n defaultBinding.insert(std::make_pair(std::string(\"Space\"), std::string(\"drop\")));\n defaultBinding.insert(std::make_pair(std::string(\"Right Mouse\"), std::string(\"identify\")));\n defaultBinding.insert(std::make_pair(std::string(\"I\"), std::string(\"identify\")));\n defaultBinding.insert(std::make_pair(std::string(\"Tab\"), std::string(\"jump\")));\n defaultBinding.insert(std::make_pair(std::string(\"N\"), std::string(\"send all\")));\n defaultBinding.insert(std::make_pair(std::string(\"M\"), std::string(\"send team\")));\n defaultBinding.insert(std::make_pair(std::string(\",\"), std::string(\"send nemesis\")));\n defaultBinding.insert(std::make_pair(std::string(\".\"), std::string(\"send recipient\")));\n defaultBinding.insert(std::make_pair(std::string(\"Z\"), std::string(\"send admin\")));\n defaultBinding.insert(std::make_pair(std::string(\"S\"), std::string(\"toggle displayScore\")));\n defaultBinding.insert(std::make_pair(std::string(\"B\"), std::string(\"toggle displayBinoculars\")));\n defaultBinding.insert(std::make_pair(std::string(\"Pause\"), std::string(\"pause\")));\n defaultBinding.insert(std::make_pair(std::string(\"P\"), std::string(\"pause\")));\n defaultBinding.insert(std::make_pair(std::string(\"F1\"),\n\t\t\t\t std::string(\"fullscreen\")));\n defaultBinding.insert(std::make_pair(std::string(\"F4\"), std::string(\"iconify\")));\n#ifdef SNAPPING\n defaultBinding.insert(std::make_pair(std::string(\"F5\"), std::string(\"screenshot\")));\n#endif\n defaultBinding.insert(std::make_pair(std::string(\"-\"), std::string(\"time backward\")));\n defaultBinding.insert(std::make_pair(std::string(\"=\"), std::string(\"time forward\")));\n defaultBinding.insert(std::make_pair(std::string(\"H\"), std::string(\"toggleFlags radar\")));\n defaultBinding.insert(std::make_pair(std::string(\"J\"), std::string(\"toggleFlags main\")));\n defaultBinding.insert(std::make_pair(std::string(\"K\"), std::string(\"silence\")));\n defaultBinding.insert(std::make_pair(std::string(\"L\"), std::string(\"toggle displayLabels\")));\n defaultBinding.insert(std::make_pair(std::string(\"Delete\"), std::string(\"destruct\")));\n\n \/\/ Default movement keys\n defaultBinding.insert(std::make_pair(std::string(\"Left Arrow\"),\n\t\t\t\t std::string(\"turn left\")));\n defaultBinding.insert(std::make_pair(std::string(\"Right Arrow\"),\n\t\t\t\t std::string(\"turn right\")));\n defaultBinding.insert(std::make_pair(std::string(\"Up Arrow\"),\n\t\t\t\t std::string(\"drive forward\")));\n defaultBinding.insert(std::make_pair(std::string(\"Down Arrow\"),\n\t\t\t\t std::string(\"drive reverse\")));\n \/\/ End default movement keys\n\n\n defaultBinding.insert(std::make_pair(std::string(\"F6\"), std::string(\"roam cycle subject backward\")));\n defaultBinding.insert(std::make_pair(std::string(\"F7\"), std::string(\"roam cycle subject forward\")));\n defaultBinding.insert(std::make_pair(std::string(\"F8\"), std::string(\"roam cycle type forward\")));\n defaultBinding.insert(std::make_pair(std::string(\"F9\"), std::string(\"roam zoom in\")));\n defaultBinding.insert(std::make_pair(std::string(\"F10\"), std::string(\"roam zoom out\")));\n defaultBinding.insert(std::make_pair(std::string(\"F11\"), std::string(\"roam zoom normal\")));\n defaultBinding.insert(std::make_pair(std::string(\"O\"), std::string(\"servercommand\")));\n defaultBinding.insert(std::make_pair(std::string(\"F\"), std::string(\"toggle displayFlagHelp\")));\n defaultBinding.insert(std::make_pair(std::string(\"Page Up\"), std::string(\"scrollpanel up\")));\n defaultBinding.insert(std::make_pair(std::string(\"Page Down\"), std::string(\"scrollpanel down\")));\n defaultBinding.insert(std::make_pair(std::string(\"1\"), std::string(\"set displayRadarRange 0.25\")));\n defaultBinding.insert(std::make_pair(std::string(\"2\"), std::string(\"set displayRadarRange 0.5\")));\n defaultBinding.insert(std::make_pair(std::string(\"3\"), std::string(\"set displayRadarRange 1.0\")));\n defaultBinding.insert(std::make_pair(std::string(\"A\"), std::string(\"toggle slowKeyboard\")));\n defaultBinding.insert(std::make_pair(std::string(\"U\"), std::string(\"hunt\")));\n defaultBinding.insert(std::make_pair(std::string(\"Right Mouse\"), std::string(\"restart\")));\n defaultBinding.insert(std::make_pair(std::string(\"I\"), std::string(\"restart\")));\n defaultBinding.insert(std::make_pair(std::string(\"9\"), std::string(\"autopilot\")));\n\n defaultBinding.insert(std::make_pair(std::string(\"Shift+F1\"),\n\t\t\t\t std::string(\"messagepanel all\")));\n defaultBinding.insert(std::make_pair(std::string(\"Shift+F2\"),\n\t\t\t\t std::string(\"messagepanel chat\")));\n defaultBinding.insert(std::make_pair(std::string(\"Shift+F3\"),\n\t\t\t\t std::string(\"messagepanel server\")));\n defaultBinding.insert(std::make_pair(std::string(\"Shift+F4\"),\n\t\t\t\t std::string(\"messagepanel misc\")));\n}\n\nvoid ActionBinding::resetBindings() {\n BindingTable::const_iterator index;\n\n for (index = bindingTable.begin();\n index != bindingTable.end();\n ++index)\n unbind(index->second, index->first);\n\n bindingTable = defaultBinding;\n\n for (index = bindingTable.begin();\n index != bindingTable.end();\n ++index)\n bind(index->second, index->first);\n}\n\nvoid ActionBinding::getFromBindings() {\n bindingTable.clear();\n KEYMGR.iterate(&onScanCB, this);\n}\n\nvoid ActionBinding::onScanCB(const std::string& name, bool,\n\t\t\t const std::string& cmd, void*)\n{\n ActionBinding::instance().associate(name, cmd, false);\n}\n\nvoid ActionBinding::associate(std::string key,\n\t\t\t std::string action,\n\t\t\t bool keyBind) {\n BindingTable::iterator index, next;\n if (!wayToBindActions.count(action))\n return;\n PressStatusBind newStatusBind = wayToBindActions[action];\n for (index = bindingTable.lower_bound( key ); index != bindingTable.upper_bound( key ); index = next) {\n next = index;\n ++next;\n if (newStatusBind == both) {\n if (keyBind)\n\tunbind(index->second, key);\n bindingTable.erase(index);\n } else if (newStatusBind == press) {\n if (wayToBindActions[index->second] != release) {\n\tif (keyBind)\n\t unbind(index->second, key);\n\tbindingTable.erase(index);\n }\n } else {\n if (wayToBindActions[index->second] != press) {\n\tif (keyBind)\n\t unbind(index->second, key);\n\tbindingTable.erase(index);\n }\n }\n }\n bindingTable.insert(std::make_pair(key, action));\n if (keyBind)\n bind(action, key);\n};\n\nvoid ActionBinding::deassociate(std::string action) {\n BindingTable::iterator index, next;\n for (index = bindingTable.begin();\n index != bindingTable.end();\n index = next) {\n next = index;\n ++next;\n if (index->second == action) {\n unbind(action, index->first);\n bindingTable.erase(index);\n }\n }\n};\n\nvoid ActionBinding::bind(std::string action, std::string key) {\n PressStatusBind statusBind = wayToBindActions[action];\n std::string command;\n if (statusBind == press || statusBind == both) {\n command = \"bind \\\"\" + key + \"\\\" down \\\"\" + action + \"\\\"\";\n CMDMGR.run(command);\n };\n if (statusBind == release || statusBind == both) {\n command = \"bind \\\"\" + key + \"\\\" up \\\"\" + action + \"\\\"\";\n CMDMGR.run(command);\n };\n}\n\nvoid ActionBinding::unbind(std::string action, std::string key) {\n PressStatusBind statusBind = wayToBindActions[action];\n std::string command;\n if (statusBind == press || statusBind == both) {\n command = \"unbind \\\"\" + key + \"\\\" down\";\n CMDMGR.run(command);\n };\n if (statusBind == release || statusBind == both) {\n command = \"unbind \\\"\" + key + \"\\\" up\";\n CMDMGR.run(command);\n };\n}\n\n\/\/ Local Variables: ***\n\/\/ mode:C++ ***\n\/\/ tab-width: 8 ***\n\/\/ c-basic-offset: 2 ***\n\/\/ indent-tabs-mode: t ***\n\/\/ End: ***\n\/\/ ex: shiftwidth=2 tabstop=8\n<|endoftext|>"} {"text":"<commit_before>#pragma once\n\n\n#include <type_traits>\n#include <functional>\n#include <memory>\n#include <uv.h>\n#include \"loop.hpp\"\n\n\nnamespace uvw {\n\n\ntemplate<typename>\nstruct HandleType { };\n\n\ntemplate<typename>\nclass Resource;\n\n\ntemplate<typename>\nstruct UVCallback;\n\n\ntemplate<typename... Args>\nstruct UVCallback<Args...> {\n template<typename T, T*(*F)(Args...)>\n static auto get(T *res);\n\nprivate:\n template<typename T, T*(*F)(Args...)>\n static void proto(Args... args);\n};\n\n\ntemplate<typename T>\nclass Resource: public std::enable_shared_from_this<T> {\n template<typename>\n friend struct UVCallback;\n\n static Resource<T>* closeCallback(uv_handle_t* h) {\n auto ptr = static_cast<Resource<T>*>(h->data);\n ptr->closeCb(UVWError{});\n return ptr;\n }\n\nprotected:\n template<typename U>\n explicit Resource(HandleType<U>, std::shared_ptr<Loop> r)\n : pLoop{std::move(r)}, handle{std::make_shared<U>()}\n { }\n\n template<typename U>\n U* get() const noexcept { return reinterpret_cast<U*>(handle.get()); }\n\n uv_loop_t* parent() const noexcept { return pLoop->loop.get(); }\n void reset() noexcept { ref = nullptr; }\n\npublic:\n explicit Resource(const Resource &) = delete;\n explicit Resource(Resource &&) = delete;\n\n ~Resource() { static_assert(std::is_base_of<Resource<T>, T>::value, \"!\"); }\n\n void operator=(const Resource &) = delete;\n void operator=(Resource &&) = delete;\n\n std::shared_ptr<Loop> loop() const noexcept { return pLoop; }\n\n bool active() const noexcept { return !(uv_is_active(get<uv_handle_t>()) == 0); }\n bool closing() const noexcept { return !(uv_is_closing(get<uv_handle_t>()) == 0); }\n\n void reference() noexcept { uv_ref(get<uv_handle_t>()); }\n void unreference() noexcept { uv_ref(get<uv_handle_t>()); }\n bool referenced() const noexcept { return !(uv_has_ref(get<uv_handle_t>()) == 0); }\n\n void close(std::function<void(UVWError)> cb) noexcept {\n using UVCB = UVCallback<uv_handle_t*>;\n auto func = UVCB::get<Resource<T>, &closeCallback>(this);\n closeCb = std::move(cb);\n uv_close(get<uv_handle_t>(), func);\n }\n\nprivate:\n std::function<void(UVWError)> closeCb;\n std::shared_ptr<Loop> pLoop;\n std::shared_ptr<void> handle;\n std::shared_ptr<void> ref;\n};\n\n\ntemplate<typename... Args>\ntemplate<typename T, T*(*F)(Args...)>\nvoid UVCallback<Args...>::proto(Args... args) {\n T *res = F(std::forward<Args>(args)...);\n res->ref = nullptr;\n}\n\ntemplate<typename... Args>\ntemplate<typename T, T*(*F)(Args...)>\nauto UVCallback<Args...>::get(T *res) {\n res->template get<uv_handle_t>()->data = res;\n res->ref = res->shared_from_this();\n return &proto<T, F>;\n}\n\n\n}\n<commit_msg>clean up<commit_after>#pragma once\n\n\n#include <type_traits>\n#include <functional>\n#include <memory>\n#include <uv.h>\n#include \"loop.hpp\"\n\n\nnamespace uvw {\n\n\ntemplate<typename>\nstruct HandleType { };\n\n\ntemplate<typename>\nclass Resource;\n\n\ntemplate<typename... Args>\nstruct UVCallback {\n template<typename T, T*(*F)(Args...)>\n static auto get(T *res);\n\nprivate:\n template<typename T, T*(*F)(Args...)>\n static void proto(Args... args);\n};\n\n\ntemplate<typename T>\nclass Resource: public std::enable_shared_from_this<T> {\n template<typename...>\n friend struct UVCallback;\n\n static Resource<T>* closeCallback(uv_handle_t* h) {\n auto ptr = static_cast<Resource<T>*>(h->data);\n ptr->closeCb(UVWError{});\n return ptr;\n }\n\nprotected:\n template<typename U>\n explicit Resource(HandleType<U>, std::shared_ptr<Loop> r)\n : pLoop{std::move(r)}, handle{std::make_shared<U>()}\n { }\n\n template<typename U>\n U* get() const noexcept { return reinterpret_cast<U*>(handle.get()); }\n\n uv_loop_t* parent() const noexcept { return pLoop->loop.get(); }\n void reset() noexcept { ref = nullptr; }\n\npublic:\n explicit Resource(const Resource &) = delete;\n explicit Resource(Resource &&) = delete;\n\n ~Resource() { static_assert(std::is_base_of<Resource<T>, T>::value, \"!\"); }\n\n void operator=(const Resource &) = delete;\n void operator=(Resource &&) = delete;\n\n std::shared_ptr<Loop> loop() const noexcept { return pLoop; }\n\n bool active() const noexcept { return !(uv_is_active(get<uv_handle_t>()) == 0); }\n bool closing() const noexcept { return !(uv_is_closing(get<uv_handle_t>()) == 0); }\n\n void reference() noexcept { uv_ref(get<uv_handle_t>()); }\n void unreference() noexcept { uv_ref(get<uv_handle_t>()); }\n bool referenced() const noexcept { return !(uv_has_ref(get<uv_handle_t>()) == 0); }\n\n void close(std::function<void(UVWError)> cb) noexcept {\n using UVCB = UVCallback<uv_handle_t*>;\n auto func = UVCB::get<Resource<T>, &closeCallback>(this);\n closeCb = std::move(cb);\n uv_close(get<uv_handle_t>(), func);\n }\n\nprivate:\n std::function<void(UVWError)> closeCb;\n std::shared_ptr<Loop> pLoop;\n std::shared_ptr<void> handle;\n std::shared_ptr<void> ref;\n};\n\n\ntemplate<typename... Args>\ntemplate<typename T, T*(*F)(Args...)>\nvoid UVCallback<Args...>::proto(Args... args) {\n T *res = F(std::forward<Args>(args)...);\n res->ref = nullptr;\n}\n\ntemplate<typename... Args>\ntemplate<typename T, T*(*F)(Args...)>\nauto UVCallback<Args...>::get(T *res) {\n res->template get<uv_handle_t>()->data = res;\n res->ref = res->shared_from_this();\n return &proto<T, F>;\n}\n\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n** buffer.cpp\n** Login : <hcuche@hcuche-de>\n**\n** Author(s):\n** - hcuche <hcuche@aldebaran-robotics.com>\n*\/\n\n#include <qimessaging\/buffer.hpp>\n#include <qi\/log.hpp>\n\n#include <cstdio>\n#include <cstring>\n#include <ctype.h>\n\n#include \"src\/buffer_p.hpp\"\n\n#include <iostream>\n\nnamespace qi\n{\n\n BufferPrivate::BufferPrivate()\n : size(0)\n , cursor(0)\n {\n }\n\n Buffer::Buffer()\n : _p(new BufferPrivate) \/\/ TODO: add allocation-on-write.\n {\n }\n\n int Buffer::write(const void *data, size_t size)\n {\n if (sizeof(_p->data) - _p->size < size)\n {\n qiLogVerbose(\"qi.Buffer\") << \"write(\" << size << \") failed, buffer size is \" << _p->size;\n return -1;\n }\n\n memcpy(_p->data + _p->size, data, size);\n _p->size += size;\n\n return size;\n }\n\n int Buffer::read(void *data, size_t size)\n {\n if (_p->size - _p->cursor < size)\n {\n size = _p->size - _p->cursor;\n }\n\n memcpy(data, _p->data + _p->cursor, size);\n _p->cursor += size;\n\n return size;\n }\n\n void *Buffer::read(size_t size)\n {\n void *p = 0;\n if ((p = peek(size)))\n {\n seek(size);\n }\n\n return p;\n }\n\n size_t Buffer::size() const\n {\n return _p->size;\n }\n\n void *Buffer::reserve(size_t size)\n {\n void *p = _p->data + _p->cursor;\n _p->size = size;\n\n return p;\n }\n\n size_t Buffer::seek(long offset)\n {\n if (_p->cursor + offset <= _p->size)\n {\n _p->cursor += offset;\n return _p->cursor;\n }\n else\n {\n return -1;\n }\n }\n\n void *Buffer::peek(size_t QI_UNUSED(size)) const\n {\n return _p->cursor + _p->data;\n }\n\n void *Buffer::data() const\n {\n return _p->data;\n }\n\n void Buffer::dump() const\n {\n unsigned int i = 0;\n\n while (i < _p->size)\n {\n printf(\"%02x \", _p->data[i]);\n i++;\n if (i % 8 == 0) printf(\" \");\n if (i % 16 == 0)\n {\n for (unsigned int j = i - 16; j < i ; j++)\n {\n printf(\"%c\", isgraph(_p->data[j]) ? _p->data[j] : '.');\n }\n printf(\"\\n\");\n }\n }\n\n while (i % 16 != 0)\n {\n printf(\" \");\n if (i % 8 == 0) printf(\" \");\n i++;\n }\n printf(\" \");\n for (unsigned int j = i - 16; j < _p->size; j++)\n {\n printf(\"%c\", isgraph(_p->data[j]) ? _p->data[j] : '.');\n }\n printf(\"\\n\");\n }\n\n} \/\/ !qi\n<commit_msg>Fix read buffer. Return 0 if size needed is too big.<commit_after>\/*\n** buffer.cpp\n** Login : <hcuche@hcuche-de>\n**\n** Author(s):\n** - hcuche <hcuche@aldebaran-robotics.com>\n*\/\n\n#include <qimessaging\/buffer.hpp>\n#include <qi\/log.hpp>\n\n#include <cstdio>\n#include <cstring>\n#include <ctype.h>\n\n#include \"src\/buffer_p.hpp\"\n\n#include <iostream>\n\nnamespace qi\n{\n\n BufferPrivate::BufferPrivate()\n : size(0)\n , cursor(0)\n {\n }\n\n Buffer::Buffer()\n : _p(new BufferPrivate) \/\/ TODO: add allocation-on-write.\n {\n }\n\n int Buffer::write(const void *data, size_t size)\n {\n if (sizeof(_p->data) - _p->size < size)\n {\n qiLogVerbose(\"qi.Buffer\") << \"write(\" << size << \") failed, buffer size is \" << _p->size;\n return -1;\n }\n\n memcpy(_p->data + _p->size, data, size);\n _p->size += size;\n\n return size;\n }\n\n int Buffer::read(void *data, size_t size)\n {\n if (_p->size - _p->cursor < size)\n {\n size = _p->size - _p->cursor;\n }\n\n memcpy(data, _p->data + _p->cursor, size);\n _p->cursor += size;\n\n return size;\n }\n\n void *Buffer::read(size_t size)\n {\n void *p = 0;\n if ((p = peek(size)))\n seek(size);\n else\n return 0;\n\n return p;\n }\n\n size_t Buffer::size() const\n {\n return _p->size;\n }\n\n void *Buffer::reserve(size_t size)\n {\n void *p = _p->data + _p->cursor;\n _p->size = size;\n\n return p;\n }\n\n size_t Buffer::seek(long offset)\n {\n if (_p->cursor + offset <= _p->size)\n {\n _p->cursor += offset;\n return _p->cursor;\n }\n else\n {\n return -1;\n }\n }\n\n void *Buffer::peek(size_t size) const\n {\n if (_p->cursor + size <= _p->size)\n return _p->cursor + _p->data;\n else\n return 0;\n }\n\n void *Buffer::data() const\n {\n return _p->data;\n }\n\n void Buffer::dump() const\n {\n unsigned int i = 0;\n\n while (i < _p->size)\n {\n printf(\"%02x \", _p->data[i]);\n i++;\n if (i % 8 == 0) printf(\" \");\n if (i % 16 == 0)\n {\n for (unsigned int j = i - 16; j < i ; j++)\n {\n printf(\"%c\", isgraph(_p->data[j]) ? _p->data[j] : '.');\n }\n printf(\"\\n\");\n }\n }\n\n while (i % 16 != 0)\n {\n printf(\" \");\n if (i % 8 == 0) printf(\" \");\n i++;\n }\n printf(\" \");\n for (unsigned int j = i - 16; j < _p->size; j++)\n {\n printf(\"%c\", isgraph(_p->data[j]) ? _p->data[j] : '.');\n }\n printf(\"\\n\");\n }\n\n} \/\/ !qi\n<|endoftext|>"} {"text":"<commit_before>#include \"DeviceMathTest.h\"\n#include <cuda\/DeviceMath.h>\n#include <cuda\/DeviceCopy.h>\n#include <common\/EigenBridge.h>\n#include \"utils.h\"\n\nnamespace sq = sqaod;\n\nDeviceMathTest::DeviceMathTest(void) : MinimalTestSuite(\"DeviceMathTest\") {\n}\n\nDeviceMathTest::~DeviceMathTest(void) {\n}\n\nvoid DeviceMathTest::setUp() {\n device_.initialize(0);\n}\n\nvoid DeviceMathTest::tearDown() {\n device_.finalize();\n}\n\nvoid DeviceMathTest::run(std::ostream &ostm) {\n\n sq::Dim dims[] = { {100, 100} , {32, 33}, {33, 32}};\n \/\/ sq::Dim dim(8, 5), sq::Dim dim(5, 8) sq::Dim dim(5, 5);\n for (int idx = 0; idx < 3; ++idx) {\n tests<double>(dims[idx]);\n tests<float>(dims[idx]);\n }\n}\n\ntemplate<class real>\nvoid DeviceMathTest::tests(const sqaod::Dim &dim) {\n\n DeviceMathType<real> devMath(device_);\n DeviceCopy devCopy(device_);\n\n typedef sq::MatrixType<real> HostMatrix;\n typedef sq::VectorType<real> HostVector;\n typedef sq::EigenMatrixType<real> EigenMatrix;\n typedef sq::EigenRowVectorType<real> EigenRowVector;\n typedef sq::EigenColumnVectorType<real> EigenColumnVector;\n typedef DeviceMatrixType<real> DeviceMatrix;\n typedef DeviceVectorType<real> DeviceVector;\n typedef DeviceScalarType<real> DeviceScalar;\n\n\n auto *alloc = device_.objectAllocator();\n \n DeviceMatrix dA, dB, dC, dD;\n DeviceVector dx, dy, dz;\n DeviceScalar da, db, dc;\n\n testcase(\"test zeros\/eye\") {\n sq::Dim dim1(dim.rows, dim.rows);\n alloc->allocate(&dA, dim1);\n devCopy(&dA, (real)0.); \/* create zero matrix *\/\n device_.synchronize();\n TEST_ASSERT(dA == HostMatrix::zeros(dim1));\n\n devMath.setToDiagonals(&dA, real(1.));\n device_.synchronize();\n TEST_ASSERT(dA == HostMatrix::eye(dim.rows));\n }\n\n testcase(\"mat scale\/sum\") {\n HostMatrix hMat = testMatBalanced<real>(dim);\n devCopy(&dA, hMat);\n devMath.scale(&dB, 10., dA);\n device_.synchronize();\n hMat *= (real)10.;\n TEST_ASSERT(dB == hMat);\n\n devMath.sum(&da, real(3.), dB);\n device_.synchronize();\n TEST_ASSERT(da == real(3. * hMat.sum()));\n \/* mulAddAssign *\/\n devMath.sum(&da, real(3.), dB, 1.);\n device_.synchronize();\n TEST_ASSERT(da == real(6. * hMat.sum()));\n }\n\n testcase(\"vec scale\/sum\") {\n HostVector hVec = testVec<real>(dim.cols);\n devCopy(&dx, hVec);\n\n devMath.scale(&dy, 10., dx);\n device_.synchronize();\n hVec *= (real)10.;\n TEST_ASSERT(dy == hVec);\n\n devMath.scale(&dy, 10., dx, 1.);\n device_.synchronize();\n hVec *= (real)2.;\n TEST_ASSERT(dy == hVec);\n\n devMath.sum(&da, real(3.), dy);\n device_.synchronize();\n TEST_ASSERT(da == real(3. * hVec.sum()));\n \/* mulAddAssign *\/\n devMath.sum(&da, real(3.), dy, 2.);\n TEST_ASSERT(da == real((3. + 6.) * hVec.sum()));\n }\n\n testcase(\"scalar scale\") {\n real hsc = 35.;\n devCopy(&da, hsc);\n\n devMath.scale(&db, 10., da);\n device_.synchronize();\n TEST_ASSERT(db == real(hsc * 10.));\n\n devMath.scale(&db, 10., da, 2.);\n device_.synchronize();\n TEST_ASSERT(db == real(hsc * 30.));\n }\n\n testcase(\"vector scale broadcast\") {\n alloc->allocate(&dx, dim.rows);\n alloc->allocate(&dy, dim.cols);\n alloc->allocate(&da);\n\n \/* initialize *\/\n devCopy(&da, (real)0.);\n devMath.scaleBroadcast(&dx, 1., da);\n HostVector x = HostVector::zeros(dim.rows);\n device_.synchronize();\n TEST_ASSERT(dx == x);\n\n devCopy(&da, (real)1.);\n devMath.scaleBroadcast(&dx, 2., da);\n x = HostVector::ones(dim.rows);\n x *= (real)2.;\n TEST_ASSERT(dx == x);\n\n devMath.scaleBroadcast(&dx, 2., da, 1.);\n x *= (real)2.;\n TEST_ASSERT(dx == x);\n }\n\n testcase(\"matrix scale broadcast\") {\n alloc->allocate(&dA, dim);\n alloc->allocate(&dx, dim.cols);\n alloc->allocate(&dy, dim.rows);\n\n HostMatrix hmat(dim);\n HostVector x = testVec<real>(dim.cols);\n HostVector y = testVec<real>(dim.rows);\n devCopy(&dx, x);\n devCopy(&dy, y);\n\n devMath.scaleBroadcast(&dA, 1., dx, opRowwise);\n sq::mapTo(hmat).rowwise() = sq::mapToRowVector(x);\n device_.synchronize();\n TEST_ASSERT(dA == hmat);\n\n devMath.scaleBroadcast(&dA, 2., dx, opRowwise, 2.);\n sq::mapTo(hmat).rowwise() = 4. * sq::mapToRowVector(x);\n device_.synchronize();\n TEST_ASSERT(dA == hmat);\n\n devMath.scaleBroadcast(&dA, 1., dy, opColwise);\n sq::mapTo(hmat).colwise() = sq::mapToColumnVector(y);\n device_.synchronize();\n TEST_ASSERT(dA == hmat);\n\n devMath.scaleBroadcast(&dA, 2., dy, opColwise, 2.);\n sq::mapTo(hmat).colwise() = 4. * sq::mapToColumnVector(y);\n device_.synchronize();\n TEST_ASSERT(dA == hmat);\n }\n\n\n testcase(\"matrix sum\") {\n HostMatrix hmat = testMat<real>(dim);\n alloc->allocate(&dA, dim);\n alloc->allocate(&da);\n\n devCopy(&dA, hmat);\n devMath.sum(&da, 1., dA);\n device_.synchronize();\n TEST_ASSERT(da == hmat.sum());\n\n devMath.sum(&da, 2., dA, 2.);\n device_.synchronize();\n TEST_ASSERT(da == real(4. * hmat.sum()));\n }\n\n testcase(\"vector sum\") {\n HostVector hvec = testVec<real>(dim.rows);\n alloc->allocate(&dx, dim.rows);\n alloc->allocate(&da);\n\n devCopy(&dx, hvec);\n devMath.sum(&da, 1., dx);\n device_.synchronize();\n TEST_ASSERT(da == hvec.sum());\n\n devMath.sum(&da, 2., dx, 2.);\n device_.synchronize();\n TEST_ASSERT(da == real(4. * hvec.sum()));\n }\n\n testcase(\"diagonal sum\") {\n HostMatrix hmat = testMat<real>(dim);\n alloc->allocate(&dA, dim);\n alloc->allocate(&da);\n\n devCopy(&dA, hmat);\n devMath.sumDiagonals(&da, dA);\n device_.synchronize();\n TEST_ASSERT(da == sq::mapTo(hmat).diagonal().sum());\n }\n testcase(\"sum batched\") {\n alloc->allocate(&dA, dim);\n alloc->allocate(&dx, dim.rows); \/* col vector *\/\n alloc->allocate(&dy, dim.cols); \/* row vector *\/\n\n HostMatrix hmat = testMat<real>(dim);\n HostVector x = testVec<real>(dim.rows); \/* col vector *\/\n HostVector y = testVec<real>(dim.cols); \/* row vector *\/\n devCopy(&dA, hmat);\n devCopy(&dx, x);\n devCopy(&dy, y);\n\n devMath.sumBatched(&dx, 2., dA, opRowwise);\n\n HostVector hvec(dim.rows);\n mapToRowVector(hvec) = 2. * sq::mapTo(hmat).rowwise().sum();\n device_.synchronize();\n TEST_ASSERT(dx == hvec);\n\n devMath.sumBatched(&dy, 2., dA, opColwise);\n hvec.resize(dim.cols);\n mapToColumnVector(hvec) = 2. * sq::mapTo(hmat).colwise().sum();\n device_.synchronize();\n TEST_ASSERT(dy == hvec);\n }\n\n testcase(\"dot\") {\n HostVector x = testVec<real>(dim.rows);\n HostVector y = testVec<real>(dim.rows);\n alloc->allocate(&dx, dim.rows);\n alloc->allocate(&dy, dim.rows);\n alloc->allocate(&da);\n\n devCopy(&dx, x);\n devCopy(&dy, y);\n devMath.dot(&da, 2., dx, dy);\n device_.synchronize();\n real product = mapToColumnVector(x).dot(mapToColumnVector(y));\n TEST_ASSERT(da == real(2. * product));\n\n devMath.dot(&da, 2., dx, dy, 1.);\n device_.synchronize();\n TEST_ASSERT(da == real(product * 4.));\n }\n\n testcase(\"dot batched\") {\n alloc->allocate(&dA, dim);\n alloc->allocate(&dB, dim);\n alloc->allocate(&dx, dim.rows); \/* col vector *\/\n alloc->allocate(&dy, dim.cols); \/* row vector *\/\n\n HostMatrix A = testMatBalanced<real>(dim);\n HostMatrix B = testMatBalanced<real>(dim);\n devCopy(&dA, A);\n devCopy(&dB, B);\n devMath.dotBatched(&dx, 2., dA, opNone, dB, opNone);\n\n EigenMatrix eAB = sq::mapTo(A).array() * sq::mapTo(B).array();\n EigenRowVector vec = 2. * eAB.rowwise().sum();\n device_.synchronize();\n\n TEST_ASSERT(dx == sq::mapFrom(vec));\n\n devMath.dotBatched(&dy, 2., dA, opTranspose, dB, opTranspose);\n vec = 2. * eAB.colwise().sum();\n device_.synchronize();\n\n TEST_ASSERT(dy == sq::mapFrom(vec));\n }\n\n testcase(\"transpose\") {\n HostMatrix hMat = testMat<real>(dim);\n devCopy(&dA, hMat);\n devMath.transpose(&dB, dA);\n device_.synchronize();\n HostMatrix hTrans(hMat.dim().transpose());\n sq::mapTo(hTrans) = sq::mapTo(hMat).transpose();\n TEST_ASSERT(dB == hTrans);\n }\n\n testcase(\"mvProduct\") {\n HostMatrix A = testMatBalanced<real>(dim);\n HostVector x = testVecBalanced<real>(dim.cols);\n devCopy(&dA, A);\n devCopy(&dx, x);\n devMath.mvProduct(&dy, 0.5, dA, opNone, dx);\n EigenRowVector y = 0.5 * sq::mapTo(A) * sq::mapToColumnVector(x);\n device_.synchronize();\n TEST_ASSERT(dy == sq::mapFrom(y));\n\n HostMatrix B = testMatBalanced<real>(dim.transpose());\n devCopy(&dB, B);\n devMath.mvProduct(&dy, 0.25, dB, opTranspose, dx);\n y = sq::mapTo(B).transpose() * sq::mapToColumnVector(x);\n y *= 0.25;\n device_.synchronize();\n TEST_ASSERT(dy == sq::mapFrom(y));\n }\n\n testcase(\"mmProduct\") {\n HostMatrix A = testMatBalanced<real>(dim);\n HostMatrix B = testMatBalanced<real>(dim.transpose());\n EigenMatrix C = 0.5 * sq::mapTo(A) * sq::mapTo(B);\n\n devCopy(&dA, A);\n devCopy(&dB, B);\n devMath.mmProduct(&dC, 0.5, dA, opNone, dB, opNone);\n device_.synchronize();\n TEST_ASSERT(dC == sq::mapFrom(C));\n\n HostMatrix At(dim.transpose());\n HostMatrix Bt(dim);\n sq::mapTo(At) = sq::mapTo(A).transpose();\n sq::mapTo(Bt) = sq::mapTo(B).transpose();\n alloc->deallocate(dA);\n alloc->deallocate(dB);\n alloc->deallocate(dC);\n devCopy(&dA, At);\n devCopy(&dB, Bt);\n devMath.mmProduct(&dC, 0.5, dA, opTranspose, dB, opTranspose);\n device_.synchronize();\n TEST_ASSERT(dC == sq::mapFrom(C));\n }\n\n testcase(\"vmvProduct\") {\n HostMatrix A = testMatBalanced<real>(dim);\n HostVector x = testVecBalanced<real>(dim.cols);\n HostVector y = testVecBalanced<real>(dim.rows);\n real product = mapToRowVector(y) * sq::mapTo(A) * mapToColumnVector(x);\n\n devCopy(&dA, A);\n devCopy(&dx, x);\n devCopy(&dy, y);\n devMath.vmvProduct(&da, 2., dy, dA, dx);\n device_.synchronize();\n TEST_ASSERT(da == real(2. * product));\n }\n\n testcase(\"vmvProductBatched\") {\n sqaod::Dim dimSq(dim.cols, dim.cols);\n HostMatrix A = testMatBalanced<real>(dimSq);\n HostMatrix X = testMatBalanced<real>(dim);\n HostMatrix Y = testMatBalanced<real>(dim);\n\n EigenMatrix AX = sq::mapTo(A) * sq::mapTo(X).transpose();\n EigenMatrix AXY = sq::mapTo(Y).array() * AX.transpose().array();\n EigenColumnVector z = 1. * AXY.rowwise().sum();\n\n devCopy(&dA, A);\n devCopy(&dB, X);\n devCopy(&dC, Y);\n devMath.vmvProductBatched(&dx, 2., dC, dA, dB);\n z *= 2.;\n device_.synchronize();\n TEST_ASSERT(dx == sq::mapFrom(z));\n }\n\n testcase(\"min matrix\") {\n HostMatrix A = testMatBalanced<real>(dim);\n real vMin = sq::mapTo(A).minCoeff();\n devCopy(&dA, A);\n devMath.min(&da, dA);\n device_.synchronize();\n TEST_ASSERT(da == vMin);\n }\n\n testcase(\"min\") {\n HostVector x = testVecBalanced<real>(dim.rows);\n real vMin = sq::mapToRowVector(x).minCoeff();\n devCopy(&dx, x);\n devMath.min(&da, dx);\n device_.synchronize();\n TEST_ASSERT(da == vMin);\n }\n\n alloc->deallocate(dA);\n alloc->deallocate(dB);\n alloc->deallocate(dC);\n alloc->deallocate(dD);\n alloc->deallocate(dx);\n alloc->deallocate(dy);\n alloc->deallocate(da);\n}\n<commit_msg>Using managed memory for ease of debug.<commit_after>#include \"DeviceMathTest.h\"\n#include <cuda\/DeviceMath.h>\n#include <cuda\/DeviceCopy.h>\n#include <common\/EigenBridge.h>\n#include \"utils.h\"\n\nnamespace sq = sqaod;\n\nDeviceMathTest::DeviceMathTest(void) : MinimalTestSuite(\"DeviceMathTest\") {\n}\n\nDeviceMathTest::~DeviceMathTest(void) {\n}\n\nvoid DeviceMathTest::setUp() {\n device_.useManagedMemory(true);\n device_.initialize(0);\n}\n\nvoid DeviceMathTest::tearDown() {\n device_.finalize();\n}\n\nvoid DeviceMathTest::run(std::ostream &ostm) {\n\n sq::Dim dims[] = { {100, 100} , {32, 33}, {33, 32}};\n \/\/ sq::Dim dim(8, 5), sq::Dim dim(5, 8) sq::Dim dim(5, 5);\n for (int idx = 0; idx < 3; ++idx) {\n tests<double>(dims[idx]);\n tests<float>(dims[idx]);\n }\n}\n\ntemplate<class real>\nvoid DeviceMathTest::tests(const sqaod::Dim &dim) {\n\n DeviceMathType<real> devMath(device_);\n DeviceCopy devCopy(device_);\n\n typedef sq::MatrixType<real> HostMatrix;\n typedef sq::VectorType<real> HostVector;\n typedef sq::EigenMatrixType<real> EigenMatrix;\n typedef sq::EigenRowVectorType<real> EigenRowVector;\n typedef sq::EigenColumnVectorType<real> EigenColumnVector;\n typedef DeviceMatrixType<real> DeviceMatrix;\n typedef DeviceVectorType<real> DeviceVector;\n typedef DeviceScalarType<real> DeviceScalar;\n\n\n auto *alloc = device_.objectAllocator();\n \n DeviceMatrix dA, dB, dC, dD;\n DeviceVector dx, dy, dz;\n DeviceScalar da, db, dc;\n\n testcase(\"test zeros\/eye\") {\n sq::Dim dim1(dim.rows, dim.rows);\n alloc->allocate(&dA, dim1);\n devCopy(&dA, (real)0.); \/* create zero matrix *\/\n device_.synchronize();\n TEST_ASSERT(dA == HostMatrix::zeros(dim1));\n\n devMath.setToDiagonals(&dA, real(1.));\n device_.synchronize();\n TEST_ASSERT(dA == HostMatrix::eye(dim.rows));\n }\n\n testcase(\"mat scale\/sum\") {\n HostMatrix hMat = testMatBalanced<real>(dim);\n devCopy(&dA, hMat);\n devMath.scale(&dB, 10., dA);\n device_.synchronize();\n hMat *= (real)10.;\n TEST_ASSERT(dB == hMat);\n\n devMath.sum(&da, real(3.), dB);\n device_.synchronize();\n TEST_ASSERT(da == real(3. * hMat.sum()));\n \/* mulAddAssign *\/\n devMath.sum(&da, real(3.), dB, 1.);\n device_.synchronize();\n TEST_ASSERT(da == real(6. * hMat.sum()));\n }\n\n testcase(\"vec scale\/sum\") {\n HostVector hVec = testVec<real>(dim.cols);\n devCopy(&dx, hVec);\n\n devMath.scale(&dy, 10., dx);\n device_.synchronize();\n hVec *= (real)10.;\n TEST_ASSERT(dy == hVec);\n\n devMath.scale(&dy, 10., dx, 1.);\n device_.synchronize();\n hVec *= (real)2.;\n TEST_ASSERT(dy == hVec);\n\n devMath.sum(&da, real(3.), dy);\n device_.synchronize();\n TEST_ASSERT(da == real(3. * hVec.sum()));\n \/* mulAddAssign *\/\n devMath.sum(&da, real(3.), dy, 2.);\n TEST_ASSERT(da == real((3. + 6.) * hVec.sum()));\n }\n\n testcase(\"scalar scale\") {\n real hsc = 35.;\n devCopy(&da, hsc);\n\n devMath.scale(&db, 10., da);\n device_.synchronize();\n TEST_ASSERT(db == real(hsc * 10.));\n\n devMath.scale(&db, 10., da, 2.);\n device_.synchronize();\n TEST_ASSERT(db == real(hsc * 30.));\n }\n\n testcase(\"vector scale broadcast\") {\n alloc->allocate(&dx, dim.rows);\n alloc->allocate(&dy, dim.cols);\n alloc->allocate(&da);\n\n \/* initialize *\/\n devCopy(&da, (real)0.);\n devMath.scaleBroadcast(&dx, 1., da);\n HostVector x = HostVector::zeros(dim.rows);\n device_.synchronize();\n TEST_ASSERT(dx == x);\n\n devCopy(&da, (real)1.);\n devMath.scaleBroadcast(&dx, 2., da);\n x = HostVector::ones(dim.rows);\n x *= (real)2.;\n TEST_ASSERT(dx == x);\n\n devMath.scaleBroadcast(&dx, 2., da, 1.);\n x *= (real)2.;\n TEST_ASSERT(dx == x);\n }\n\n testcase(\"matrix scale broadcast\") {\n alloc->allocate(&dA, dim);\n alloc->allocate(&dx, dim.cols);\n alloc->allocate(&dy, dim.rows);\n\n HostMatrix hmat(dim);\n HostVector x = testVec<real>(dim.cols);\n HostVector y = testVec<real>(dim.rows);\n devCopy(&dx, x);\n devCopy(&dy, y);\n\n devMath.scaleBroadcast(&dA, 1., dx, opRowwise);\n sq::mapTo(hmat).rowwise() = sq::mapToRowVector(x);\n device_.synchronize();\n TEST_ASSERT(dA == hmat);\n\n devMath.scaleBroadcast(&dA, 2., dx, opRowwise, 2.);\n sq::mapTo(hmat).rowwise() = 4. * sq::mapToRowVector(x);\n device_.synchronize();\n TEST_ASSERT(dA == hmat);\n\n devMath.scaleBroadcast(&dA, 1., dy, opColwise);\n sq::mapTo(hmat).colwise() = sq::mapToColumnVector(y);\n device_.synchronize();\n TEST_ASSERT(dA == hmat);\n\n devMath.scaleBroadcast(&dA, 2., dy, opColwise, 2.);\n sq::mapTo(hmat).colwise() = 4. * sq::mapToColumnVector(y);\n device_.synchronize();\n TEST_ASSERT(dA == hmat);\n }\n\n\n testcase(\"matrix sum\") {\n HostMatrix hmat = testMat<real>(dim);\n alloc->allocate(&dA, dim);\n alloc->allocate(&da);\n\n devCopy(&dA, hmat);\n devMath.sum(&da, 1., dA);\n device_.synchronize();\n TEST_ASSERT(da == hmat.sum());\n\n devMath.sum(&da, 2., dA, 2.);\n device_.synchronize();\n TEST_ASSERT(da == real(4. * hmat.sum()));\n }\n\n testcase(\"vector sum\") {\n HostVector hvec = testVec<real>(dim.rows);\n alloc->allocate(&dx, dim.rows);\n alloc->allocate(&da);\n\n devCopy(&dx, hvec);\n devMath.sum(&da, 1., dx);\n device_.synchronize();\n TEST_ASSERT(da == hvec.sum());\n\n devMath.sum(&da, 2., dx, 2.);\n device_.synchronize();\n TEST_ASSERT(da == real(4. * hvec.sum()));\n }\n\n testcase(\"diagonal sum\") {\n HostMatrix hmat = testMat<real>(dim);\n alloc->allocate(&dA, dim);\n alloc->allocate(&da);\n\n devCopy(&dA, hmat);\n devMath.sumDiagonals(&da, dA);\n device_.synchronize();\n TEST_ASSERT(da == sq::mapTo(hmat).diagonal().sum());\n }\n testcase(\"sum batched\") {\n alloc->allocate(&dA, dim);\n alloc->allocate(&dx, dim.rows); \/* col vector *\/\n alloc->allocate(&dy, dim.cols); \/* row vector *\/\n\n HostMatrix hmat = testMat<real>(dim);\n HostVector x = testVec<real>(dim.rows); \/* col vector *\/\n HostVector y = testVec<real>(dim.cols); \/* row vector *\/\n devCopy(&dA, hmat);\n devCopy(&dx, x);\n devCopy(&dy, y);\n\n devMath.sumBatched(&dx, 2., dA, opRowwise);\n\n HostVector hvec(dim.rows);\n mapToRowVector(hvec) = 2. * sq::mapTo(hmat).rowwise().sum();\n device_.synchronize();\n TEST_ASSERT(dx == hvec);\n\n devMath.sumBatched(&dy, 2., dA, opColwise);\n hvec.resize(dim.cols);\n mapToColumnVector(hvec) = 2. * sq::mapTo(hmat).colwise().sum();\n device_.synchronize();\n TEST_ASSERT(dy == hvec);\n }\n\n testcase(\"dot\") {\n HostVector x = testVec<real>(dim.rows);\n HostVector y = testVec<real>(dim.rows);\n alloc->allocate(&dx, dim.rows);\n alloc->allocate(&dy, dim.rows);\n alloc->allocate(&da);\n\n devCopy(&dx, x);\n devCopy(&dy, y);\n devMath.dot(&da, 2., dx, dy);\n device_.synchronize();\n real product = mapToColumnVector(x).dot(mapToColumnVector(y));\n TEST_ASSERT(da == real(2. * product));\n\n devMath.dot(&da, 2., dx, dy, 1.);\n device_.synchronize();\n TEST_ASSERT(da == real(product * 4.));\n }\n\n testcase(\"dot batched\") {\n alloc->allocate(&dA, dim);\n alloc->allocate(&dB, dim);\n alloc->allocate(&dx, dim.rows); \/* col vector *\/\n alloc->allocate(&dy, dim.cols); \/* row vector *\/\n\n HostMatrix A = testMatBalanced<real>(dim);\n HostMatrix B = testMatBalanced<real>(dim);\n devCopy(&dA, A);\n devCopy(&dB, B);\n devMath.dotBatched(&dx, 2., dA, opNone, dB, opNone);\n\n EigenMatrix eAB = sq::mapTo(A).array() * sq::mapTo(B).array();\n EigenRowVector vec = 2. * eAB.rowwise().sum();\n device_.synchronize();\n\n TEST_ASSERT(dx == sq::mapFrom(vec));\n\n devMath.dotBatched(&dy, 2., dA, opTranspose, dB, opTranspose);\n vec = 2. * eAB.colwise().sum();\n device_.synchronize();\n\n TEST_ASSERT(dy == sq::mapFrom(vec));\n }\n\n testcase(\"transpose\") {\n HostMatrix hMat = testMat<real>(dim);\n devCopy(&dA, hMat);\n devMath.transpose(&dB, dA);\n device_.synchronize();\n HostMatrix hTrans(hMat.dim().transpose());\n sq::mapTo(hTrans) = sq::mapTo(hMat).transpose();\n TEST_ASSERT(dB == hTrans);\n }\n\n testcase(\"mvProduct\") {\n HostMatrix A = testMatBalanced<real>(dim);\n HostVector x = testVecBalanced<real>(dim.cols);\n devCopy(&dA, A);\n devCopy(&dx, x);\n devMath.mvProduct(&dy, 0.5, dA, opNone, dx);\n EigenRowVector y = 0.5 * sq::mapTo(A) * sq::mapToColumnVector(x);\n device_.synchronize();\n TEST_ASSERT(dy == sq::mapFrom(y));\n\n HostMatrix B = testMatBalanced<real>(dim.transpose());\n devCopy(&dB, B);\n devMath.mvProduct(&dy, 0.25, dB, opTranspose, dx);\n y = sq::mapTo(B).transpose() * sq::mapToColumnVector(x);\n y *= 0.25;\n device_.synchronize();\n TEST_ASSERT(dy == sq::mapFrom(y));\n }\n\n testcase(\"mmProduct\") {\n HostMatrix A = testMatBalanced<real>(dim);\n HostMatrix B = testMatBalanced<real>(dim.transpose());\n EigenMatrix C = 0.5 * sq::mapTo(A) * sq::mapTo(B);\n\n devCopy(&dA, A);\n devCopy(&dB, B);\n devMath.mmProduct(&dC, 0.5, dA, opNone, dB, opNone);\n device_.synchronize();\n TEST_ASSERT(dC == sq::mapFrom(C));\n\n HostMatrix At(dim.transpose());\n HostMatrix Bt(dim);\n sq::mapTo(At) = sq::mapTo(A).transpose();\n sq::mapTo(Bt) = sq::mapTo(B).transpose();\n alloc->deallocate(dA);\n alloc->deallocate(dB);\n alloc->deallocate(dC);\n devCopy(&dA, At);\n devCopy(&dB, Bt);\n devMath.mmProduct(&dC, 0.5, dA, opTranspose, dB, opTranspose);\n device_.synchronize();\n TEST_ASSERT(dC == sq::mapFrom(C));\n }\n\n testcase(\"vmvProduct\") {\n HostMatrix A = testMatBalanced<real>(dim);\n HostVector x = testVecBalanced<real>(dim.cols);\n HostVector y = testVecBalanced<real>(dim.rows);\n real product = mapToRowVector(y) * sq::mapTo(A) * mapToColumnVector(x);\n\n devCopy(&dA, A);\n devCopy(&dx, x);\n devCopy(&dy, y);\n devMath.vmvProduct(&da, 2., dy, dA, dx);\n device_.synchronize();\n TEST_ASSERT(da == real(2. * product));\n }\n\n testcase(\"vmvProductBatched\") {\n sqaod::Dim dimSq(dim.cols, dim.cols);\n HostMatrix A = testMatBalanced<real>(dimSq);\n HostMatrix X = testMatBalanced<real>(dim);\n HostMatrix Y = testMatBalanced<real>(dim);\n\n EigenMatrix AX = sq::mapTo(A) * sq::mapTo(X).transpose();\n EigenMatrix AXY = sq::mapTo(Y).array() * AX.transpose().array();\n EigenColumnVector z = 1. * AXY.rowwise().sum();\n\n devCopy(&dA, A);\n devCopy(&dB, X);\n devCopy(&dC, Y);\n devMath.vmvProductBatched(&dx, 2., dC, dA, dB);\n z *= 2.;\n device_.synchronize();\n TEST_ASSERT(dx == sq::mapFrom(z));\n }\n\n testcase(\"min matrix\") {\n HostMatrix A = testMatBalanced<real>(dim);\n real vMin = sq::mapTo(A).minCoeff();\n devCopy(&dA, A);\n devMath.min(&da, dA);\n device_.synchronize();\n TEST_ASSERT(da == vMin);\n }\n\n testcase(\"min\") {\n HostVector x = testVecBalanced<real>(dim.rows);\n real vMin = sq::mapToRowVector(x).minCoeff();\n devCopy(&dx, x);\n devMath.min(&da, dx);\n device_.synchronize();\n TEST_ASSERT(da == vMin);\n }\n\n alloc->deallocate(dA);\n alloc->deallocate(dB);\n alloc->deallocate(dC);\n alloc->deallocate(dD);\n alloc->deallocate(dx);\n alloc->deallocate(dy);\n alloc->deallocate(da);\n}\n<|endoftext|>"} {"text":"<commit_before>#include <osg\/AlphaFunc>\n#include <osg\/Billboard>\n#include <osg\/BlendFunc>\n#include <osg\/Depth>\n#include <osg\/Geode>\n#include <osg\/Geometry>\n#include <osg\/GL2Extensions>\n#include <osg\/Material>\n#include <osg\/Math>\n#include <osg\/MatrixTransform>\n#include <osg\/PolygonOffset>\n#include <osg\/Program>\n#include <osg\/Projection>\n#include <osg\/Shader>\n#include <osg\/ShapeDrawable>\n#include <osg\/StateSet>\n#include <osg\/Switch>\n#include <osg\/Texture2D>\n#include <osg\/Uniform>\n\n#include <osgDB\/ReadFile>\n#include <osgDB\/FileUtils>\n\n#include <osgUtil\/IntersectVisitor>\n#include <osgUtil\/SmoothingVisitor>\n\n#include <osgText\/Text>\n\n#include <osgViewer\/Viewer>\n\n#include <iostream>\n\n\/\/ for the grid data..\n#include \"..\/osghangglide\/terrain_coords.h\"\n\nosg::Node* createScene()\n{\n osg::Group* scene = new osg::Group;\n \n unsigned int numColumns = 38;\n unsigned int numRows = 39;\n unsigned int r;\n unsigned int c;\n\n osg::Vec3 origin(0.0f,0.0f,0.0f);\n osg::Vec3 size(1000.0f,1000.0f,250.0f);\n osg::Vec3 scaleDown(1.0f\/size.x(),1.0f\/size.y(),1.0f\/size.z());\n\n \/\/ ---------------------------------------\n \/\/ Set up a StateSet to texture the objects\n \/\/ ---------------------------------------\n osg::StateSet* stateset = new osg::StateSet();\n\n\n osg::Uniform* originUniform = new osg::Uniform(\"terrainOrigin\",origin);\n stateset->addUniform(originUniform);\n\n osg::Uniform* sizeUniform = new osg::Uniform(\"terrainSize\",size);\n stateset->addUniform(sizeUniform);\n\n osg::Uniform* scaleDownUniform = new osg::Uniform(\"terrainScaleDown\",scaleDown);\n stateset->addUniform(scaleDownUniform);\n\n osg::Uniform* terrainTextureSampler = new osg::Uniform(\"terrainTexture\",0);\n stateset->addUniform(terrainTextureSampler);\n\n osg::Uniform* baseTextureSampler = new osg::Uniform(\"baseTexture\",1);\n stateset->addUniform(baseTextureSampler);\n\n osg::Uniform* treeTextureSampler = new osg::Uniform(\"treeTexture\",1);\n stateset->addUniform(treeTextureSampler);\n\n\n \/\/ compute z range of z values of grid data so we can scale it.\n float min_z = FLT_MAX;\n float max_z = -FLT_MAX;\n for(r=0;r<numRows;++r)\n {\n for(c=0;c<numColumns;++c)\n {\n min_z = osg::minimum(min_z,vertex[r+c*numRows][2]);\n max_z = osg::maximum(max_z,vertex[r+c*numRows][2]);\n }\n }\n \n float scale_z = size.z()\/(max_z-min_z);\n\n osg::Image* terrainImage = new osg::Image;\n terrainImage->allocateImage(numColumns,numRows,1,GL_LUMINANCE, GL_FLOAT);\n terrainImage->setInternalTextureFormat(GL_LUMINANCE_FLOAT32_ATI);\n for(r=0;r<numRows;++r)\n {\n for(c=0;c<numColumns;++c)\n {\n *((float*)(terrainImage->data(c,r))) = (vertex[r+c*numRows][2]-min_z)*scale_z;\n }\n }\n \n osg::Texture2D* terrainTexture = new osg::Texture2D;\n terrainTexture->setImage(terrainImage);\n terrainTexture->setFilter(osg::Texture2D::MIN_FILTER, osg::Texture2D::NEAREST);\n terrainTexture->setFilter(osg::Texture2D::MAG_FILTER, osg::Texture2D::NEAREST);\n terrainTexture->setResizeNonPowerOfTwoHint(false);\n stateset->setTextureAttributeAndModes(0,terrainTexture,osg::StateAttribute::ON);\n\n\n osg::Image* image = osgDB::readImageFile(\"Images\/lz.rgb\");\n if (image)\n {\n osg::Texture2D* texture = new osg::Texture2D;\n \n texture->setImage(image);\n stateset->setTextureAttributeAndModes(1,texture,osg::StateAttribute::ON);\n }\n\n { \n std::cout<<\"Creating terrain...\";\n\n osg::Geode* geode = new osg::Geode();\n geode->setStateSet( stateset );\n\n\n {\n osg::Program* program = new osg::Program;\n stateset->setAttribute(program);\n\n#if 1\n \/\/ use inline shaders\n \n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ vertex shader using just Vec4 coefficients\n char vertexShaderSource[] = \n \"uniform float osg_FrameTime;\\n\"\n \"uniform sampler2D terrainTexture;\\n\"\n \"uniform vec3 terrainOrigin;\\n\"\n \"uniform vec3 terrainScaleDown;\\n\"\n \"\\n\"\n \"varying vec2 texcoord;\\n\"\n \"\\n\"\n \"void main(void)\\n\"\n \"{\\n\"\n \" texcoord = gl_Vertex.xy - terrainOrigin.xy;\\n\"\n \" texcoord.x *= terrainScaleDown.x;\\n\"\n \" texcoord.y *= terrainScaleDown.y;\\n\"\n \"\\n\"\n \" vec4 position;\\n\"\n \" position.x = gl_Vertex.x;\\n\"\n \" position.y = gl_Vertex.y;\\n\"\n \" position.z = texture2D(terrainTexture, texcoord).r;\\n\"\n \" position.w = 1.0;\\n\"\n \" \\n\"\n \" gl_Position = gl_ModelViewProjectionMatrix * position;\\n\"\n \" gl_FrontColor = vec4(1.0,1.0,1.0,1.0);\\n\"\n \"}\\n\";\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ fragment shader\n \/\/\n char fragmentShaderSource[] = \n \"uniform sampler2D baseTexture; \\n\"\n \"varying vec2 texcoord;\\n\"\n \"\\n\"\n \"void main(void) \\n\"\n \"{\\n\"\n \" gl_FragColor = texture2D( baseTexture, texcoord); \\n\"\n \"}\\n\";\n\n program->addShader(new osg::Shader(osg::Shader::VERTEX, vertexShaderSource));\n program->addShader(new osg::Shader(osg::Shader::FRAGMENT, fragmentShaderSource));\n \n#else\n\n \/\/ get shaders from source\n program->addShader(osg::Shader::readShaderFile(osg::Shader::VERTEX, osgDB::findDataFile(\"shaders\/terrain.vert\")));\n program->addShader(osg::Shader::readShaderFile(osg::Shader::FRAGMENT, osgDB::findDataFile(\"shaders\/terrain.frag\")));\n\n#endif\n\n \/\/ get shaders from source\n }\n\n\n {\n osg::Geometry* geometry = new osg::Geometry;\n\n osg::Vec3Array& v = *(new osg::Vec3Array(numColumns*numRows));\n osg::Vec4ubArray& color = *(new osg::Vec4ubArray(1));\n\n color[0].set(255,255,255,255);\n\n float rowCoordDelta = size.y()\/(float)(numRows-1);\n float columnCoordDelta = size.x()\/(float)(numColumns-1);\n\n float rowTexDelta = 1.0f\/(float)(numRows-1);\n float columnTexDelta = 1.0f\/(float)(numColumns-1);\n\n osg::Vec3 pos = origin;\n osg::Vec2 tex(0.0f,0.0f);\n int vi=0;\n for(r=0;r<numRows;++r)\n {\n pos.x() = origin.x();\n tex.x() = 0.0f;\n for(c=0;c<numColumns;++c)\n {\n v[vi].set(pos.x(),pos.y(),pos.z());\n pos.x()+=columnCoordDelta;\n tex.x()+=columnTexDelta;\n ++vi;\n }\n pos.y() += rowCoordDelta;\n tex.y() += rowTexDelta;\n }\n\n geometry->setVertexArray(&v);\n geometry->setColorArray(&color);\n geometry->setColorBinding(osg::Geometry::BIND_OVERALL);\n\n for(r=0;r<numRows-1;++r)\n {\n osg::DrawElementsUShort& drawElements = *(new osg::DrawElementsUShort(GL_QUAD_STRIP,2*numColumns));\n geometry->addPrimitiveSet(&drawElements);\n int ei=0;\n for(c=0;c<numColumns;++c)\n {\n drawElements[ei++] = (r+1)*numColumns+c;\n drawElements[ei++] = (r)*numColumns+c;\n }\n }\n \n geometry->setInitialBound(osg::BoundingBox(origin, origin+size));\n\n geode->addDrawable(geometry);\n\n scene->addChild(geode);\n }\n }\n \n std::cout<<\"done.\"<<std::endl;\n \n return scene;\n}\n\n#if 0\nclass TestSupportCallback : public osgProducer::OsgCameraGroup::RealizeCallback\n{\n public:\n TestSupportCallback():_supported(true),_errorMessage() {}\n \n virtual void operator()( osgProducer::OsgCameraGroup&, osgProducer::OsgSceneHandler& sh, const Producer::RenderSurface& )\n {\n {\n OpenThreads::ScopedLock<OpenThreads::Mutex> lock(_mutex);\n\n unsigned int contextID = sh.getSceneView()->getState()->getContextID();\n osg::GL2Extensions* gl2ext = osg::GL2Extensions::Get(contextID,true);\n if( gl2ext )\n {\n if( !gl2ext->isGlslSupported() )\n {\n _supported = false;\n _errorMessage = \"ERROR: GLSL not supported by OpenGL driver.\";\n }\n\n GLint numVertexTexUnits = 0;\n glGetIntegerv( GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS, &numVertexTexUnits );\n if( numVertexTexUnits <= 0 )\n {\n _supported = false;\n _errorMessage = \"ERROR: vertex texturing not supported by OpenGL driver.\";\n }\n }\n }\n \n sh.init();\n }\n \n OpenThreads::Mutex _mutex;\n bool _supported;\n std::string _errorMessage;\n \n};\n#endif\n\nint main(int, char **)\n{\n \/\/ construct the viewer.\n osgViewer::Viewer viewer;\n\n osg::Node* node = createScene();\n\n \/\/ add model to viewer.\n viewer.setSceneData( node );\n\n#if 0\n \/\/ register a test extension callback to be called when app realizes and gets a valid graphics context\n osg::ref_ptr<TestSupportCallback> testSupportCallback = new TestSupportCallback();\n viewer.setRealizeCallback(testSupportCallback.get());\n \/\/ create the windows and run the threads.\n viewer.realize();\n\n \/\/ exit if we don't have the extensions this example needs.\n if (!testSupportCallback->_supported)\n {\n osg::notify(osg::WARN)<<testSupportCallback->_errorMessage<<std::endl;\n\n exit(1);\n }\n#else\n\n osg::notify(osg::NOTICE)<<\"osgshaderterrain OpenGL support test not implemented yet\"<<std::endl;\n \n#endif\n\n\n return viewer.run();\n}\n<commit_msg>Implement a GraphicsOperation to test extension availability<commit_after>#include <osg\/AlphaFunc>\n#include <osg\/Billboard>\n#include <osg\/BlendFunc>\n#include <osg\/Depth>\n#include <osg\/Geode>\n#include <osg\/Geometry>\n#include <osg\/GL2Extensions>\n#include <osg\/Material>\n#include <osg\/Math>\n#include <osg\/MatrixTransform>\n#include <osg\/PolygonOffset>\n#include <osg\/Program>\n#include <osg\/Projection>\n#include <osg\/Shader>\n#include <osg\/ShapeDrawable>\n#include <osg\/StateSet>\n#include <osg\/Switch>\n#include <osg\/Texture2D>\n#include <osg\/Uniform>\n\n#include <osgDB\/ReadFile>\n#include <osgDB\/FileUtils>\n\n#include <osgUtil\/IntersectVisitor>\n#include <osgUtil\/SmoothingVisitor>\n\n#include <osgText\/Text>\n\n#include <osgViewer\/Viewer>\n\n#include <iostream>\n\n\/\/ for the grid data..\n#include \"..\/osghangglide\/terrain_coords.h\"\n\nosg::Node* createScene()\n{\n osg::Group* scene = new osg::Group;\n \n unsigned int numColumns = 38;\n unsigned int numRows = 39;\n unsigned int r;\n unsigned int c;\n\n osg::Vec3 origin(0.0f,0.0f,0.0f);\n osg::Vec3 size(1000.0f,1000.0f,250.0f);\n osg::Vec3 scaleDown(1.0f\/size.x(),1.0f\/size.y(),1.0f\/size.z());\n\n \/\/ ---------------------------------------\n \/\/ Set up a StateSet to texture the objects\n \/\/ ---------------------------------------\n osg::StateSet* stateset = new osg::StateSet();\n\n\n osg::Uniform* originUniform = new osg::Uniform(\"terrainOrigin\",origin);\n stateset->addUniform(originUniform);\n\n osg::Uniform* sizeUniform = new osg::Uniform(\"terrainSize\",size);\n stateset->addUniform(sizeUniform);\n\n osg::Uniform* scaleDownUniform = new osg::Uniform(\"terrainScaleDown\",scaleDown);\n stateset->addUniform(scaleDownUniform);\n\n osg::Uniform* terrainTextureSampler = new osg::Uniform(\"terrainTexture\",0);\n stateset->addUniform(terrainTextureSampler);\n\n osg::Uniform* baseTextureSampler = new osg::Uniform(\"baseTexture\",1);\n stateset->addUniform(baseTextureSampler);\n\n osg::Uniform* treeTextureSampler = new osg::Uniform(\"treeTexture\",1);\n stateset->addUniform(treeTextureSampler);\n\n\n \/\/ compute z range of z values of grid data so we can scale it.\n float min_z = FLT_MAX;\n float max_z = -FLT_MAX;\n for(r=0;r<numRows;++r)\n {\n for(c=0;c<numColumns;++c)\n {\n min_z = osg::minimum(min_z,vertex[r+c*numRows][2]);\n max_z = osg::maximum(max_z,vertex[r+c*numRows][2]);\n }\n }\n \n float scale_z = size.z()\/(max_z-min_z);\n\n osg::Image* terrainImage = new osg::Image;\n terrainImage->allocateImage(numColumns,numRows,1,GL_LUMINANCE, GL_FLOAT);\n terrainImage->setInternalTextureFormat(GL_LUMINANCE_FLOAT32_ATI);\n for(r=0;r<numRows;++r)\n {\n for(c=0;c<numColumns;++c)\n {\n *((float*)(terrainImage->data(c,r))) = (vertex[r+c*numRows][2]-min_z)*scale_z;\n }\n }\n \n osg::Texture2D* terrainTexture = new osg::Texture2D;\n terrainTexture->setImage(terrainImage);\n terrainTexture->setFilter(osg::Texture2D::MIN_FILTER, osg::Texture2D::NEAREST);\n terrainTexture->setFilter(osg::Texture2D::MAG_FILTER, osg::Texture2D::NEAREST);\n terrainTexture->setResizeNonPowerOfTwoHint(false);\n stateset->setTextureAttributeAndModes(0,terrainTexture,osg::StateAttribute::ON);\n\n\n osg::Image* image = osgDB::readImageFile(\"Images\/lz.rgb\");\n if (image)\n {\n osg::Texture2D* texture = new osg::Texture2D;\n \n texture->setImage(image);\n stateset->setTextureAttributeAndModes(1,texture,osg::StateAttribute::ON);\n }\n\n { \n std::cout<<\"Creating terrain...\";\n\n osg::Geode* geode = new osg::Geode();\n geode->setStateSet( stateset );\n\n\n {\n osg::Program* program = new osg::Program;\n stateset->setAttribute(program);\n\n#if 1\n \/\/ use inline shaders\n \n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ vertex shader using just Vec4 coefficients\n char vertexShaderSource[] = \n \"uniform float osg_FrameTime;\\n\"\n \"uniform sampler2D terrainTexture;\\n\"\n \"uniform vec3 terrainOrigin;\\n\"\n \"uniform vec3 terrainScaleDown;\\n\"\n \"\\n\"\n \"varying vec2 texcoord;\\n\"\n \"\\n\"\n \"void main(void)\\n\"\n \"{\\n\"\n \" texcoord = gl_Vertex.xy - terrainOrigin.xy;\\n\"\n \" texcoord.x *= terrainScaleDown.x;\\n\"\n \" texcoord.y *= terrainScaleDown.y;\\n\"\n \"\\n\"\n \" vec4 position;\\n\"\n \" position.x = gl_Vertex.x;\\n\"\n \" position.y = gl_Vertex.y;\\n\"\n \" position.z = texture2D(terrainTexture, texcoord).r;\\n\"\n \" position.w = 1.0;\\n\"\n \" \\n\"\n \" gl_Position = gl_ModelViewProjectionMatrix * position;\\n\"\n \" gl_FrontColor = vec4(1.0,1.0,1.0,1.0);\\n\"\n \"}\\n\";\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ fragment shader\n \/\/\n char fragmentShaderSource[] = \n \"uniform sampler2D baseTexture; \\n\"\n \"varying vec2 texcoord;\\n\"\n \"\\n\"\n \"void main(void) \\n\"\n \"{\\n\"\n \" gl_FragColor = texture2D( baseTexture, texcoord); \\n\"\n \"}\\n\";\n\n program->addShader(new osg::Shader(osg::Shader::VERTEX, vertexShaderSource));\n program->addShader(new osg::Shader(osg::Shader::FRAGMENT, fragmentShaderSource));\n \n#else\n\n \/\/ get shaders from source\n program->addShader(osg::Shader::readShaderFile(osg::Shader::VERTEX, osgDB::findDataFile(\"shaders\/terrain.vert\")));\n program->addShader(osg::Shader::readShaderFile(osg::Shader::FRAGMENT, osgDB::findDataFile(\"shaders\/terrain.frag\")));\n\n#endif\n\n \/\/ get shaders from source\n }\n\n\n {\n osg::Geometry* geometry = new osg::Geometry;\n\n osg::Vec3Array& v = *(new osg::Vec3Array(numColumns*numRows));\n osg::Vec4ubArray& color = *(new osg::Vec4ubArray(1));\n\n color[0].set(255,255,255,255);\n\n float rowCoordDelta = size.y()\/(float)(numRows-1);\n float columnCoordDelta = size.x()\/(float)(numColumns-1);\n\n float rowTexDelta = 1.0f\/(float)(numRows-1);\n float columnTexDelta = 1.0f\/(float)(numColumns-1);\n\n osg::Vec3 pos = origin;\n osg::Vec2 tex(0.0f,0.0f);\n int vi=0;\n for(r=0;r<numRows;++r)\n {\n pos.x() = origin.x();\n tex.x() = 0.0f;\n for(c=0;c<numColumns;++c)\n {\n v[vi].set(pos.x(),pos.y(),pos.z());\n pos.x()+=columnCoordDelta;\n tex.x()+=columnTexDelta;\n ++vi;\n }\n pos.y() += rowCoordDelta;\n tex.y() += rowTexDelta;\n }\n\n geometry->setVertexArray(&v);\n geometry->setColorArray(&color);\n geometry->setColorBinding(osg::Geometry::BIND_OVERALL);\n\n for(r=0;r<numRows-1;++r)\n {\n osg::DrawElementsUShort& drawElements = *(new osg::DrawElementsUShort(GL_QUAD_STRIP,2*numColumns));\n geometry->addPrimitiveSet(&drawElements);\n int ei=0;\n for(c=0;c<numColumns;++c)\n {\n drawElements[ei++] = (r+1)*numColumns+c;\n drawElements[ei++] = (r)*numColumns+c;\n }\n }\n \n geometry->setInitialBound(osg::BoundingBox(origin, origin+size));\n\n geode->addDrawable(geometry);\n\n scene->addChild(geode);\n }\n }\n \n std::cout<<\"done.\"<<std::endl;\n \n return scene;\n}\n\nclass TestSupportOperation: public osg::GraphicsOperation\n{\npublic:\n\n TestSupportOperation():\n osg::GraphicsOperation(\"TestSupportOperation\",false),\n _supported(true),\n _errorMessage() {}\n\n virtual void operator () (osg::GraphicsContext* gc)\n {\n osg::notify(osg::NOTICE)<<\"Not called\"<<std::endl;\n \n OpenThreads::ScopedLock<OpenThreads::Mutex> lock(_mutex);\n\n unsigned int contextID = gc->getState()->getContextID();\n osg::GL2Extensions* gl2ext = osg::GL2Extensions::Get(contextID,true);\n if( gl2ext )\n {\n if( !gl2ext->isGlslSupported() )\n {\n _supported = false;\n _errorMessage = \"ERROR: GLSL not supported by OpenGL driver.\";\n }\n\n GLint numVertexTexUnits = 0;\n glGetIntegerv( GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS, &numVertexTexUnits );\n if( numVertexTexUnits <= 0 )\n {\n _supported = false;\n _errorMessage = \"ERROR: vertex texturing not supported by OpenGL driver.\";\n }\n }\n\n _supported = false;\n _errorMessage = \"ERROR: Pllalalal.\";\n\n }\n \n OpenThreads::Mutex _mutex;\n bool _supported;\n std::string _errorMessage;\n};\n\nint main(int, char **)\n{\n \/\/ construct the viewer.\n osgViewer::Viewer viewer;\n\n osg::Node* node = createScene();\n\n \/\/ add model to viewer.\n viewer.setSceneData( node );\n\n viewer.setUpViewAcrossAllScreens();\n \n osg::ref_ptr<TestSupportOperation> testSupportOperation = new TestSupportOperation;\n\n osgViewer::Viewer::Windows windows;\n viewer.getWindows(windows);\n for(osgViewer::Viewer::Windows::iterator itr = windows.begin();\n itr != windows.end();\n ++itr)\n {\n (*itr)->add(testSupportOperation.get());\n }\n\n \/\/ create the windows and run the threads.\n viewer.realize();\n \n if (!testSupportOperation->_supported)\n {\n osg::notify(osg::WARN)<<testSupportOperation->_errorMessage<<std::endl;\n\n return 1;\n }\n\n return viewer.run();\n}\n<|endoftext|>"} {"text":"<commit_before>#include <algorithm>\n#include <map>\nextern \"C\"\n{\n#include <wlr\/types\/wlr_surface.h>\n#define static\n#include <wlr\/types\/wlr_compositor.h>\n#include <wlr\/render\/wlr_renderer.h>\n#include <wlr\/types\/wlr_matrix.h>\n#include <wlr\/types\/wlr_buffer.h>\n#include <wlr\/util\/region.h>\n#undef static\n}\n\n#include \"surface-impl.hpp\"\n#include \"subsurface.hpp\"\n#include \"opengl.hpp\"\n#include \"..\/core\/core-impl.hpp\"\n#include \"output.hpp\"\n#include \"debug.hpp\"\n#include \"render-manager.hpp\"\n#include \"signal-definitions.hpp\"\n\n\/****************************\n * surface_interface_t functions\n ****************************\/\nwf::surface_interface_t::surface_interface_t(surface_interface_t *parent)\n{\n this->priv = std::make_unique<impl>();\n take_ref();\n this->priv->parent_surface = parent;\n\n if (parent)\n {\n set_output(parent->get_output());\n parent->priv->surface_children.insert(\n parent->priv->surface_children.begin(), this);\n }\n}\n\nwf::surface_interface_t::~surface_interface_t()\n{\n if (priv->parent_surface)\n {\n auto& container = priv->parent_surface->priv->surface_children;\n auto it = std::remove(container.begin(), container.end(), this);\n container.erase(it, container.end());\n }\n\n for (auto c : priv->surface_children)\n c->priv->parent_surface = nullptr;\n}\n\nvoid wf::surface_interface_t::take_ref()\n{\n ++priv->ref_cnt;\n}\n\nvoid wf::surface_interface_t::unref()\n{\n --priv->ref_cnt;\n if (priv->ref_cnt <= 0)\n destruct();\n}\n\nwf::surface_interface_t *wf::surface_interface_t::get_main_surface()\n{\n if (priv->parent_surface)\n return priv->parent_surface->get_main_surface();\n\n return this;\n}\n\nstd::vector<wf::surface_iterator_t> wf::surface_interface_t::enumerate_surfaces(\n wf_point surface_origin)\n{\n std::vector<wf::surface_iterator_t> result;\n for (auto& child : priv->surface_children)\n {\n if (child->is_mapped())\n {\n auto child_surfaces = child->enumerate_surfaces(\n child->get_offset() + surface_origin);\n\n result.insert(result.end(),\n child_surfaces.begin(), child_surfaces.end());\n }\n }\n\n if (is_mapped())\n result.push_back({this, surface_origin});\n\n return result;\n}\n\nwf::output_t *wf::surface_interface_t::get_output()\n{\n return priv->output;\n}\n\nvoid wf::surface_interface_t::set_output(wf::output_t* output)\n{\n priv->output = output;\n for (auto& c : priv->surface_children)\n c->set_output(output);\n}\n\n\/* Static method *\/\nint wf::surface_interface_t::impl::active_shrink_constraint = 0;\n\nvoid wf::surface_interface_t::set_opaque_shrink_constraint(\n std::string constraint_name, int value)\n{\n static std::map<std::string, int> shrink_constraints;\n\n shrink_constraints[constraint_name] = value;\n\n impl::active_shrink_constraint = 0;\n for (auto& constr : shrink_constraints)\n {\n impl::active_shrink_constraint =\n std::max(impl::active_shrink_constraint, constr.second);\n }\n}\n\nint wf::surface_interface_t::get_active_shrink_constraint()\n{\n return impl::active_shrink_constraint;\n}\n\nvoid wf::surface_interface_t::destruct()\n{\n delete this;\n}\n\n\/****************************\n * surface_interface_t functions for surfaces which are\n * backed by a wlr_surface\n ****************************\/\nvoid wf::surface_interface_t::send_frame_done(const timespec& time)\n{\n if (priv->wsurface)\n wlr_surface_send_frame_done(priv->wsurface, &time);\n}\n\nbool wf::surface_interface_t::accepts_input(int32_t sx, int32_t sy)\n{\n if (!priv->wsurface)\n return false;\n\n return wlr_surface_point_accepts_input(priv->wsurface, sx, sy);\n}\n\nvoid wf::surface_interface_t::subtract_opaque(wf_region& region, int x, int y)\n{\n if (!priv->wsurface)\n return;\n\n wf_region opaque{&priv->wsurface->opaque_region};\n opaque += wf_point{x, y};\n opaque *= get_output()->handle->scale;\n\n \/* region scaling uses std::ceil\/std::floor, so the resulting region\n * encompasses the opaque region. However, in the case of opaque region, we\n * don't want any pixels that aren't actually opaque. So in case of\n * different scales, we just shrink by 1 to compensate for the ceil\/floor\n * discrepancy *\/\n int ceil_factor = 0;\n if (get_output()->handle->scale != (float)priv->wsurface->current.scale)\n ceil_factor = 1;\n\n opaque.expand_edges(-get_active_shrink_constraint() - ceil_factor);\n region ^= opaque;\n}\n\nwl_client* wf::surface_interface_t::get_client()\n{\n if (priv->wsurface)\n return wl_resource_get_client(priv->wsurface->resource);\n\n return nullptr;\n}\n\nwf::wlr_surface_base_t::wlr_surface_base_t(surface_interface_t *self)\n{\n _as_si = self;\n handle_new_subsurface = [&] (void* data)\n {\n auto sub = static_cast<wlr_subsurface*> (data);\n if (sub->data)\n {\n log_error(\"Creating the same subsurface twice!\");\n return;\n }\n\n \/\/ parent isn't mapped yet\n if (!sub->parent->data)\n return;\n\n \/\/ will be deleted by destruct()\n new subsurface_implementation_t(sub, _as_si);\n };\n\n on_new_subsurface.set_callback(handle_new_subsurface);\n on_commit.set_callback([&] (void*) { commit(); });\n}\n\nwf::wlr_surface_base_t::~wlr_surface_base_t() {}\n\n\n\nwf_point wf::wlr_surface_base_t::get_window_offset()\n{\n return {0, 0};\n}\n\nbool wf::wlr_surface_base_t::_is_mapped() const\n{\n return surface;\n}\n\nwf_surface_size_t wf::wlr_surface_base_t::_get_size() const\n{\n if (!_is_mapped())\n return {0, 0};\n\n return {\n surface->current.width,\n surface->current.height,\n };\n}\n\nvoid wf::emit_map_state_change(wf::surface_interface_t *surface)\n{\n std::string state = surface->is_mapped() ? \"_surface_mapped\" : \"_surface_unmapped\";\n\n _surface_map_state_changed_signal data;\n data.surface = surface;\n wf::get_core().emit_signal(state, &data);\n}\n\nvoid wf::wlr_surface_base_t::map(wlr_surface *surface)\n{\n assert(!this->surface && surface);\n this->surface = surface;\n\n _as_si->priv->wsurface = surface;\n\n \/* force surface_send_enter(), and also check whether parent surface\n * output hasn't changed while we were unmapped *\/\n wf::output_t *output = _as_si->priv->parent_surface ?\n _as_si->priv->parent_surface->get_output() : _as_si->get_output();\n _as_si->set_output(output);\n\n on_new_subsurface.connect(&surface->events.new_subsurface);\n on_commit.connect(&surface->events.commit);\n\n surface->data = _as_si;\n\n \/* Handle subsurfaces which were created before this surface was mapped *\/\n wlr_subsurface *sub;\n wl_list_for_each(sub, &surface->subsurfaces, parent_link)\n handle_new_subsurface(sub);\n\n emit_map_state_change(_as_si);\n}\n\nvoid wf::wlr_surface_base_t::unmap()\n{\n assert(this->surface);\n apply_surface_damage();\n damage_surface_box({.x = 0, .y = 0,\n .width = _get_size().width, .height = _get_size().height});\n\n this->surface->data = NULL;\n this->surface = nullptr;\n this->_as_si->priv->wsurface = nullptr;\n emit_map_state_change(_as_si);\n\n on_new_subsurface.disconnect();\n on_destroy.disconnect();\n on_commit.disconnect();\n}\n\nwlr_buffer* wf::wlr_surface_base_t::get_buffer()\n{\n if (surface && wlr_surface_has_buffer(surface))\n return surface->buffer;\n\n return nullptr;\n}\n\nvoid wf::wlr_surface_base_t::damage_surface_region(\n const wf_region& dmg)\n{\n for (const auto& rect : dmg)\n damage_surface_box(wlr_box_from_pixman_box(rect));\n}\n\nvoid wf::wlr_surface_base_t::damage_surface_box(const wlr_box& box)\n{\n auto parent =\n dynamic_cast<wlr_surface_base_t*> (_as_si->priv->parent_surface);\n\n \/* wlr_view_t overrides damage_surface_box and applies it to the output *\/\n if (parent && parent->_is_mapped())\n {\n wlr_box parent_box = box;\n parent_box.x += _as_si->get_offset().x;\n parent_box.y += _as_si->get_offset().y;\n parent->damage_surface_box(parent_box);\n }\n}\n\nvoid wf::wlr_surface_base_t::apply_surface_damage()\n{\n if (!_as_si->get_output() || !_is_mapped())\n return;\n\n wf_region dmg;\n wlr_surface_get_effective_damage(surface, dmg.to_pixman());\n\n if (surface->current.scale != 1 ||\n surface->current.scale != _as_si->get_output()->handle->scale)\n dmg.expand_edges(1);\n\n damage_surface_region(dmg);\n}\n\nvoid wf::wlr_surface_base_t::commit()\n{\n apply_surface_damage();\n if (_as_si->get_output())\n {\n \/* we schedule redraw, because the surface might expect\n * a frame callback *\/\n _as_si->get_output()->render->schedule_redraw();\n }\n}\n\nvoid wf::wlr_surface_base_t::update_output(wf::output_t *old_output,\n wf::output_t *new_output)\n{\n \/* We should send send_leave only if the output is different from the last. *\/\n if (old_output && old_output != new_output && surface)\n wlr_surface_send_leave(surface, old_output->handle);\n\n if (new_output && surface)\n wlr_surface_send_enter(surface, new_output->handle);\n}\n\nvoid wf::wlr_surface_base_t::_wlr_render_box(\n const wf_framebuffer& fb, int x, int y, const wlr_box& scissor)\n{\n if (!get_buffer())\n return;\n\n wlr_box geometry {x, y, surface->current.width, surface->current.height};\n geometry = fb.damage_box_from_geometry_box(geometry);\n\n float projection[9];\n wlr_matrix_projection(projection, fb.viewport_width, fb.viewport_height,\n (wl_output_transform)fb.wl_transform);\n\n float matrix[9];\n wlr_matrix_project_box(matrix, &geometry,\n wlr_output_transform_invert(surface->current.transform), 0, projection);\n\n OpenGL::render_begin(fb);\n auto sbox = scissor; wlr_renderer_scissor(wf::get_core().renderer, &sbox);\n wlr_render_texture_with_matrix(wf::get_core().renderer,\n get_buffer()->texture, matrix, 1.0);\n\n#ifdef WAYFIRE_GRAPHICS_DEBUG\n float scissor_proj[9];\n wlr_matrix_projection(scissor_proj, fb.viewport_width, fb.viewport_height,\n WL_OUTPUT_TRANSFORM_NORMAL);\n\n float col[4] = {0, 0.2, 0, 0.5};\n wlr_render_rect(wf::get_core().renderer, &scissor, col, scissor_proj);\n#endif\n\n OpenGL::render_end();\n}\n\nvoid wf::wlr_surface_base_t::_simple_render(const wf_framebuffer& fb,\n int x, int y, const wf_region& damage)\n{\n for (const auto& rect : damage)\n {\n auto box = wlr_box_from_pixman_box(rect);\n _wlr_render_box(fb, x, y, fb.framebuffer_box_from_damage_box(box));\n }\n}\n\nwf::wlr_child_surface_base_t::wlr_child_surface_base_t(\n surface_interface_t *parent, surface_interface_t *self) :\n wf::surface_interface_t(parent),\n wlr_surface_base_t(self)\n{\n}\n\nwf::wlr_child_surface_base_t::~wlr_child_surface_base_t() { }\n<commit_msg>surface: manually map \"mapped\" subsurfaces when they are created<commit_after>#include <algorithm>\n#include <map>\nextern \"C\"\n{\n#include <wlr\/types\/wlr_surface.h>\n#define static\n#include <wlr\/types\/wlr_compositor.h>\n#include <wlr\/render\/wlr_renderer.h>\n#include <wlr\/types\/wlr_matrix.h>\n#include <wlr\/types\/wlr_buffer.h>\n#include <wlr\/util\/region.h>\n#undef static\n}\n\n#include \"surface-impl.hpp\"\n#include \"subsurface.hpp\"\n#include \"opengl.hpp\"\n#include \"..\/core\/core-impl.hpp\"\n#include \"output.hpp\"\n#include \"debug.hpp\"\n#include \"render-manager.hpp\"\n#include \"signal-definitions.hpp\"\n\n\/****************************\n * surface_interface_t functions\n ****************************\/\nwf::surface_interface_t::surface_interface_t(surface_interface_t *parent)\n{\n this->priv = std::make_unique<impl>();\n take_ref();\n this->priv->parent_surface = parent;\n\n if (parent)\n {\n set_output(parent->get_output());\n parent->priv->surface_children.insert(\n parent->priv->surface_children.begin(), this);\n }\n}\n\nwf::surface_interface_t::~surface_interface_t()\n{\n if (priv->parent_surface)\n {\n auto& container = priv->parent_surface->priv->surface_children;\n auto it = std::remove(container.begin(), container.end(), this);\n container.erase(it, container.end());\n }\n\n for (auto c : priv->surface_children)\n c->priv->parent_surface = nullptr;\n}\n\nvoid wf::surface_interface_t::take_ref()\n{\n ++priv->ref_cnt;\n}\n\nvoid wf::surface_interface_t::unref()\n{\n --priv->ref_cnt;\n if (priv->ref_cnt <= 0)\n destruct();\n}\n\nwf::surface_interface_t *wf::surface_interface_t::get_main_surface()\n{\n if (priv->parent_surface)\n return priv->parent_surface->get_main_surface();\n\n return this;\n}\n\nstd::vector<wf::surface_iterator_t> wf::surface_interface_t::enumerate_surfaces(\n wf_point surface_origin)\n{\n std::vector<wf::surface_iterator_t> result;\n for (auto& child : priv->surface_children)\n {\n if (child->is_mapped())\n {\n auto child_surfaces = child->enumerate_surfaces(\n child->get_offset() + surface_origin);\n\n result.insert(result.end(),\n child_surfaces.begin(), child_surfaces.end());\n }\n }\n\n if (is_mapped())\n result.push_back({this, surface_origin});\n\n return result;\n}\n\nwf::output_t *wf::surface_interface_t::get_output()\n{\n return priv->output;\n}\n\nvoid wf::surface_interface_t::set_output(wf::output_t* output)\n{\n priv->output = output;\n for (auto& c : priv->surface_children)\n c->set_output(output);\n}\n\n\/* Static method *\/\nint wf::surface_interface_t::impl::active_shrink_constraint = 0;\n\nvoid wf::surface_interface_t::set_opaque_shrink_constraint(\n std::string constraint_name, int value)\n{\n static std::map<std::string, int> shrink_constraints;\n\n shrink_constraints[constraint_name] = value;\n\n impl::active_shrink_constraint = 0;\n for (auto& constr : shrink_constraints)\n {\n impl::active_shrink_constraint =\n std::max(impl::active_shrink_constraint, constr.second);\n }\n}\n\nint wf::surface_interface_t::get_active_shrink_constraint()\n{\n return impl::active_shrink_constraint;\n}\n\nvoid wf::surface_interface_t::destruct()\n{\n delete this;\n}\n\n\/****************************\n * surface_interface_t functions for surfaces which are\n * backed by a wlr_surface\n ****************************\/\nvoid wf::surface_interface_t::send_frame_done(const timespec& time)\n{\n if (priv->wsurface)\n wlr_surface_send_frame_done(priv->wsurface, &time);\n}\n\nbool wf::surface_interface_t::accepts_input(int32_t sx, int32_t sy)\n{\n if (!priv->wsurface)\n return false;\n\n return wlr_surface_point_accepts_input(priv->wsurface, sx, sy);\n}\n\nvoid wf::surface_interface_t::subtract_opaque(wf_region& region, int x, int y)\n{\n if (!priv->wsurface)\n return;\n\n wf_region opaque{&priv->wsurface->opaque_region};\n opaque += wf_point{x, y};\n opaque *= get_output()->handle->scale;\n\n \/* region scaling uses std::ceil\/std::floor, so the resulting region\n * encompasses the opaque region. However, in the case of opaque region, we\n * don't want any pixels that aren't actually opaque. So in case of\n * different scales, we just shrink by 1 to compensate for the ceil\/floor\n * discrepancy *\/\n int ceil_factor = 0;\n if (get_output()->handle->scale != (float)priv->wsurface->current.scale)\n ceil_factor = 1;\n\n opaque.expand_edges(-get_active_shrink_constraint() - ceil_factor);\n region ^= opaque;\n}\n\nwl_client* wf::surface_interface_t::get_client()\n{\n if (priv->wsurface)\n return wl_resource_get_client(priv->wsurface->resource);\n\n return nullptr;\n}\n\nwf::wlr_surface_base_t::wlr_surface_base_t(surface_interface_t *self)\n{\n _as_si = self;\n handle_new_subsurface = [&] (void* data)\n {\n auto sub = static_cast<wlr_subsurface*> (data);\n if (sub->data)\n {\n log_error(\"Creating the same subsurface twice!\");\n return;\n }\n\n \/\/ parent isn't mapped yet\n if (!sub->parent->data)\n return;\n\n \/\/ will be deleted by destruct()\n auto subsurface = new subsurface_implementation_t(sub, _as_si);\n if (sub->mapped)\n subsurface->map(sub->surface);\n };\n\n on_new_subsurface.set_callback(handle_new_subsurface);\n on_commit.set_callback([&] (void*) { commit(); });\n}\n\nwf::wlr_surface_base_t::~wlr_surface_base_t() {}\n\n\n\nwf_point wf::wlr_surface_base_t::get_window_offset()\n{\n return {0, 0};\n}\n\nbool wf::wlr_surface_base_t::_is_mapped() const\n{\n return surface;\n}\n\nwf_surface_size_t wf::wlr_surface_base_t::_get_size() const\n{\n if (!_is_mapped())\n return {0, 0};\n\n return {\n surface->current.width,\n surface->current.height,\n };\n}\n\nvoid wf::emit_map_state_change(wf::surface_interface_t *surface)\n{\n std::string state = surface->is_mapped() ? \"_surface_mapped\" : \"_surface_unmapped\";\n\n _surface_map_state_changed_signal data;\n data.surface = surface;\n wf::get_core().emit_signal(state, &data);\n}\n\nvoid wf::wlr_surface_base_t::map(wlr_surface *surface)\n{\n assert(!this->surface && surface);\n this->surface = surface;\n\n _as_si->priv->wsurface = surface;\n\n \/* force surface_send_enter(), and also check whether parent surface\n * output hasn't changed while we were unmapped *\/\n wf::output_t *output = _as_si->priv->parent_surface ?\n _as_si->priv->parent_surface->get_output() : _as_si->get_output();\n _as_si->set_output(output);\n\n on_new_subsurface.connect(&surface->events.new_subsurface);\n on_commit.connect(&surface->events.commit);\n\n surface->data = _as_si;\n\n \/* Handle subsurfaces which were created before this surface was mapped *\/\n wlr_subsurface *sub;\n wl_list_for_each(sub, &surface->subsurfaces, parent_link)\n handle_new_subsurface(sub);\n\n emit_map_state_change(_as_si);\n}\n\nvoid wf::wlr_surface_base_t::unmap()\n{\n assert(this->surface);\n apply_surface_damage();\n damage_surface_box({.x = 0, .y = 0,\n .width = _get_size().width, .height = _get_size().height});\n\n this->surface->data = NULL;\n this->surface = nullptr;\n this->_as_si->priv->wsurface = nullptr;\n emit_map_state_change(_as_si);\n\n on_new_subsurface.disconnect();\n on_destroy.disconnect();\n on_commit.disconnect();\n}\n\nwlr_buffer* wf::wlr_surface_base_t::get_buffer()\n{\n if (surface && wlr_surface_has_buffer(surface))\n return surface->buffer;\n\n return nullptr;\n}\n\nvoid wf::wlr_surface_base_t::damage_surface_region(\n const wf_region& dmg)\n{\n for (const auto& rect : dmg)\n damage_surface_box(wlr_box_from_pixman_box(rect));\n}\n\nvoid wf::wlr_surface_base_t::damage_surface_box(const wlr_box& box)\n{\n auto parent =\n dynamic_cast<wlr_surface_base_t*> (_as_si->priv->parent_surface);\n\n \/* wlr_view_t overrides damage_surface_box and applies it to the output *\/\n if (parent && parent->_is_mapped())\n {\n wlr_box parent_box = box;\n parent_box.x += _as_si->get_offset().x;\n parent_box.y += _as_si->get_offset().y;\n parent->damage_surface_box(parent_box);\n }\n}\n\nvoid wf::wlr_surface_base_t::apply_surface_damage()\n{\n if (!_as_si->get_output() || !_is_mapped())\n return;\n\n wf_region dmg;\n wlr_surface_get_effective_damage(surface, dmg.to_pixman());\n\n if (surface->current.scale != 1 ||\n surface->current.scale != _as_si->get_output()->handle->scale)\n dmg.expand_edges(1);\n\n damage_surface_region(dmg);\n}\n\nvoid wf::wlr_surface_base_t::commit()\n{\n apply_surface_damage();\n if (_as_si->get_output())\n {\n \/* we schedule redraw, because the surface might expect\n * a frame callback *\/\n _as_si->get_output()->render->schedule_redraw();\n }\n}\n\nvoid wf::wlr_surface_base_t::update_output(wf::output_t *old_output,\n wf::output_t *new_output)\n{\n \/* We should send send_leave only if the output is different from the last. *\/\n if (old_output && old_output != new_output && surface)\n wlr_surface_send_leave(surface, old_output->handle);\n\n if (new_output && surface)\n wlr_surface_send_enter(surface, new_output->handle);\n}\n\nvoid wf::wlr_surface_base_t::_wlr_render_box(\n const wf_framebuffer& fb, int x, int y, const wlr_box& scissor)\n{\n if (!get_buffer())\n return;\n\n wlr_box geometry {x, y, surface->current.width, surface->current.height};\n geometry = fb.damage_box_from_geometry_box(geometry);\n\n float projection[9];\n wlr_matrix_projection(projection, fb.viewport_width, fb.viewport_height,\n (wl_output_transform)fb.wl_transform);\n\n float matrix[9];\n wlr_matrix_project_box(matrix, &geometry,\n wlr_output_transform_invert(surface->current.transform), 0, projection);\n\n OpenGL::render_begin(fb);\n auto sbox = scissor; wlr_renderer_scissor(wf::get_core().renderer, &sbox);\n wlr_render_texture_with_matrix(wf::get_core().renderer,\n get_buffer()->texture, matrix, 1.0);\n\n#ifdef WAYFIRE_GRAPHICS_DEBUG\n float scissor_proj[9];\n wlr_matrix_projection(scissor_proj, fb.viewport_width, fb.viewport_height,\n WL_OUTPUT_TRANSFORM_NORMAL);\n\n float col[4] = {0, 0.2, 0, 0.5};\n wlr_render_rect(wf::get_core().renderer, &scissor, col, scissor_proj);\n#endif\n\n OpenGL::render_end();\n}\n\nvoid wf::wlr_surface_base_t::_simple_render(const wf_framebuffer& fb,\n int x, int y, const wf_region& damage)\n{\n for (const auto& rect : damage)\n {\n auto box = wlr_box_from_pixman_box(rect);\n _wlr_render_box(fb, x, y, fb.framebuffer_box_from_damage_box(box));\n }\n}\n\nwf::wlr_child_surface_base_t::wlr_child_surface_base_t(\n surface_interface_t *parent, surface_interface_t *self) :\n wf::surface_interface_t(parent),\n wlr_surface_base_t(self)\n{\n}\n\nwf::wlr_child_surface_base_t::~wlr_child_surface_base_t() { }\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ Copyright (c) 2018 Rokas Kupstys\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n\/\/ THE SOFTWARE.\n\/\/\n\n#include <regex>\n#include <Urho3D\/Core\/CoreEvents.h>\n#include <Urho3D\/Core\/WorkQueue.h>\n#include <Urho3D\/Engine\/EngineEvents.h>\n#include <Urho3D\/IO\/FileSystem.h>\n#include <Urho3D\/IO\/Log.h>\n#include <Urho3D\/Resource\/ResourceCache.h>\n#include \"Editor.h\"\n#include \"AssetConverter.h\"\n#include \"ImportAssimp.h\"\n\n\nnamespace Urho3D\n{\n\nAssetConverter::AssetConverter(Context* context)\n : Object(context)\n{\n assetImporters_.Push(SharedPtr<ImportAssimp>(new ImportAssimp(context_)));\n\n SubscribeToEvent(E_ENDFRAME, std::bind(&AssetConverter::DispatchChangedAssets, this));\n SubscribeToEvent(E_CONSOLECOMMAND, std::bind(&AssetConverter::OnConsoleCommand, this, _2));\n}\n\nAssetConverter::~AssetConverter()\n{\n for (auto& watcher : watchers_)\n watcher->StopWatching();\n}\n\nvoid AssetConverter::AddAssetDirectory(const String& path)\n{\n SharedPtr<FileWatcher> watcher(new FileWatcher(context_));\n watcher->StartWatching(path, true);\n watchers_.Push(watcher);\n}\n\nvoid AssetConverter::RemoveAssetDirectory(const String& path)\n{\n String realPath = AddTrailingSlash(path);\n for (auto it = watchers_.Begin(); it != watchers_.End();)\n {\n if ((*it)->GetPath() == realPath)\n {\n (*it)->StopWatching();\n it = watchers_.Erase(it);\n }\n else\n ++it;\n }\n}\n\nvoid AssetConverter::SetCachePath(const String& cachePath)\n{\n GetFileSystem()->CreateDirsRecursive(cachePath);\n cachePath_ = cachePath;\n}\n\nString AssetConverter::GetCachePath() const\n{\n return cachePath_;\n}\n\nvoid AssetConverter::VerifyCacheAsync()\n{\n GetWorkQueue()->AddWorkItem([=]() {\n for (const auto& watcher : watchers_)\n {\n Vector<String> files;\n GetFileSystem()->ScanDir(files, watcher->GetPath(), \"*\", SCAN_FILES, true);\n\n for (const auto& file : files)\n ConvertAsset(file);\n }\n });\n}\n\nvoid AssetConverter::ConvertAssetAsync(const String& resourceName)\n{\n GetWorkQueue()->AddWorkItem(std::bind(&AssetConverter::ConvertAsset, this, resourceName));\n}\n\nbool AssetConverter::ConvertAsset(const String& resourceName)\n{\n if (!IsCacheOutOfDate(resourceName))\n return true;\n\n \/\/ Ensure that no resources are left over from previous version\n GetFileSystem()->RemoveDir(cachePath_ + resourceName, true);\n String resourceFileName = GetCache()->GetResourceFileName(resourceName);\n bool convertedAny = false;\n\n for (auto& importer : assetImporters_)\n {\n if (importer->Accepts(resourceFileName))\n {\n if (importer->Convert(resourceFileName))\n convertedAny = true;\n }\n }\n\n auto convertedAssets = GetCacheAssets(resourceName);\n if (!convertedAssets.Empty())\n {\n unsigned mtime = GetFileSystem()->GetLastModifiedTime(resourceFileName);\n for (const auto& path : GetCacheAssets(resourceName))\n {\n GetFileSystem()->SetLastModifiedTime(path, mtime);\n URHO3D_LOGINFOF(\"Imported %s\", path.CString());\n }\n }\n\n return convertedAny;\n}\n\nvoid AssetConverter::DispatchChangedAssets()\n{\n if (checkTimer_.GetMSec(false) < 3000)\n return;\n checkTimer_.Reset();\n\n for (auto& watcher : watchers_)\n {\n String path;\n while (watcher->GetNextChange(path))\n ConvertAssetAsync(path);\n }\n}\n\nbool AssetConverter::IsCacheOutOfDate(const String& resourceName)\n{\n unsigned mtime = GetFileSystem()->GetLastModifiedTime(GetCache()->GetResourceFileName(resourceName));\n\n auto files = GetCacheAssets(resourceName);\n for (const auto& path : files)\n {\n if (GetFileSystem()->GetLastModifiedTime(path) != mtime)\n return true;\n }\n\n return files.Empty();\n}\n\nVector<String> AssetConverter::GetCacheAssets(const String& resourceName)\n{\n Vector<String> files;\n String assetCacheDirectory = cachePath_ + resourceName;\n if (GetFileSystem()->DirExists(assetCacheDirectory))\n GetFileSystem()->ScanDir(files, assetCacheDirectory, \"\", SCAN_FILES, true);\n for (auto& fileName : files)\n fileName = AddTrailingSlash(assetCacheDirectory) + fileName;\n return files;\n}\n\nvoid AssetConverter::OnConsoleCommand(VariantMap& args)\n{\n using namespace ConsoleCommand;\n if (args[P_COMMAND].GetString() == \"cache.sync\")\n VerifyCacheAsync();\n}\n\n}\n<commit_msg>Editor: Safer variable captures in asset conversion.<commit_after>\/\/\n\/\/ Copyright (c) 2018 Rokas Kupstys\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n\/\/ THE SOFTWARE.\n\/\/\n\n#include <regex>\n#include <Urho3D\/Core\/CoreEvents.h>\n#include <Urho3D\/Core\/WorkQueue.h>\n#include <Urho3D\/Engine\/EngineEvents.h>\n#include <Urho3D\/IO\/FileSystem.h>\n#include <Urho3D\/IO\/Log.h>\n#include <Urho3D\/Resource\/ResourceCache.h>\n#include \"Editor.h\"\n#include \"AssetConverter.h\"\n#include \"ImportAssimp.h\"\n\n\nnamespace Urho3D\n{\n\nAssetConverter::AssetConverter(Context* context)\n : Object(context)\n{\n assetImporters_.Push(SharedPtr<ImportAssimp>(new ImportAssimp(context_)));\n\n SubscribeToEvent(E_ENDFRAME, std::bind(&AssetConverter::DispatchChangedAssets, this));\n SubscribeToEvent(E_CONSOLECOMMAND, std::bind(&AssetConverter::OnConsoleCommand, this, _2));\n}\n\nAssetConverter::~AssetConverter()\n{\n for (auto& watcher : watchers_)\n watcher->StopWatching();\n}\n\nvoid AssetConverter::AddAssetDirectory(const String& path)\n{\n SharedPtr<FileWatcher> watcher(new FileWatcher(context_));\n watcher->StartWatching(path, true);\n watchers_.Push(watcher);\n}\n\nvoid AssetConverter::RemoveAssetDirectory(const String& path)\n{\n String realPath = AddTrailingSlash(path);\n for (auto it = watchers_.Begin(); it != watchers_.End();)\n {\n if ((*it)->GetPath() == realPath)\n {\n (*it)->StopWatching();\n it = watchers_.Erase(it);\n }\n else\n ++it;\n }\n}\n\nvoid AssetConverter::SetCachePath(const String& cachePath)\n{\n GetFileSystem()->CreateDirsRecursive(cachePath);\n cachePath_ = cachePath;\n}\n\nString AssetConverter::GetCachePath() const\n{\n return cachePath_;\n}\n\nvoid AssetConverter::VerifyCacheAsync()\n{\n StringVector paths;\n for (const auto& watcher : watchers_)\n paths.Push(watcher->GetPath());\n\n GetWorkQueue()->AddWorkItem([this, paths]() {\n for (const auto& path : paths)\n {\n Vector<String> files;\n GetFileSystem()->ScanDir(files, path, \"*\", SCAN_FILES, true);\n\n for (const auto& file : files)\n ConvertAsset(file);\n }\n });\n}\n\nvoid AssetConverter::ConvertAssetAsync(const String& resourceName)\n{\n GetWorkQueue()->AddWorkItem([this, resourceName]() { ConvertAsset(resourceName); });\n}\n\nbool AssetConverter::ConvertAsset(const String& resourceName)\n{\n if (!IsCacheOutOfDate(resourceName))\n return true;\n\n \/\/ Ensure that no resources are left over from previous version\n GetFileSystem()->RemoveDir(cachePath_ + resourceName, true);\n String resourceFileName = GetCache()->GetResourceFileName(resourceName);\n bool convertedAny = false;\n\n for (auto& importer : assetImporters_)\n {\n if (importer->Accepts(resourceFileName))\n {\n if (importer->Convert(resourceFileName))\n convertedAny = true;\n }\n }\n\n auto convertedAssets = GetCacheAssets(resourceName);\n if (!convertedAssets.Empty())\n {\n unsigned mtime = GetFileSystem()->GetLastModifiedTime(resourceFileName);\n for (const auto& path : GetCacheAssets(resourceName))\n {\n GetFileSystem()->SetLastModifiedTime(path, mtime);\n URHO3D_LOGINFOF(\"Imported %s\", path.CString());\n }\n }\n\n return convertedAny;\n}\n\nvoid AssetConverter::DispatchChangedAssets()\n{\n if (checkTimer_.GetMSec(false) < 3000)\n return;\n checkTimer_.Reset();\n\n for (auto& watcher : watchers_)\n {\n String path;\n while (watcher->GetNextChange(path))\n ConvertAssetAsync(path);\n }\n}\n\nbool AssetConverter::IsCacheOutOfDate(const String& resourceName)\n{\n unsigned mtime = GetFileSystem()->GetLastModifiedTime(GetCache()->GetResourceFileName(resourceName));\n\n auto files = GetCacheAssets(resourceName);\n for (const auto& path : files)\n {\n if (GetFileSystem()->GetLastModifiedTime(path) != mtime)\n return true;\n }\n\n return files.Empty();\n}\n\nVector<String> AssetConverter::GetCacheAssets(const String& resourceName)\n{\n Vector<String> files;\n String assetCacheDirectory = cachePath_ + resourceName;\n if (GetFileSystem()->DirExists(assetCacheDirectory))\n GetFileSystem()->ScanDir(files, assetCacheDirectory, \"\", SCAN_FILES, true);\n for (auto& fileName : files)\n fileName = AddTrailingSlash(assetCacheDirectory) + fileName;\n return files;\n}\n\nvoid AssetConverter::OnConsoleCommand(VariantMap& args)\n{\n using namespace ConsoleCommand;\n if (args[P_COMMAND].GetString() == \"cache.sync\")\n VerifyCacheAsync();\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/*******************************************************************************\n * c7a\/net\/group.hpp\n *\n * net::Group is a collection of NetConnections providing simple MPI-like\n * collectives and point-to-point communication.\n *\n * Part of Project c7a.\n *\n * Copyright (C) 2015 Timo Bingmann <tb@panthema.net>\n *\n * This file has no license. Only Chuck Norris can compile it.\n ******************************************************************************\/\n\n#pragma once\n#ifndef C7A_NET_GROUP_HEADER\n#define C7A_NET_GROUP_HEADER\n\n#include <c7a\/net\/endpoint.hpp>\n#include <c7a\/net\/connection.hpp>\n#include <c7a\/common\/functional.hpp>\n#include <c7a\/common\/logger.hpp>\n\n#include <algorithm>\n#include <cassert>\n#include <cstring>\n#include <map>\n#include <string>\n#include <thread>\n#include <utility>\n#include <vector>\n\nnamespace c7a {\nnamespace net {\n\n\/\/! \\addtogroup net Network Communication\n\/\/! \\{\n\ntypedef unsigned int ClientId;\n\n\/\/TODO(ej) Cleanup the Group. Make to a sole collection holding a bunch of connections.\n\/\/Move everything else into appropriate channel.\n\n\/*!\n * Collection of NetConnections to workers, allows point-to-point client\n * communication and simple collectives like MPI.\n *\/\nclass Group\n{\n static const bool debug = false;\n\npublic:\n \/\/! \\name Construction and Initialization\n \/\/! \\{\n\n \/\/! Construct a mock Group using a complete graph of local stream sockets\n \/\/! for testing, and starts a thread for each client, which gets passed the\n \/\/! Group object. This is ideal for testing network communication\n \/\/! protocols. See tests\/net\/test-net-group.cpp for examples.\n \/\/! @param num_clients The number of clients to spawn.\n \/\/! @param thread_function The function to execute for each client.\n static void ExecuteLocalMock(\n size_t num_clients,\n const std::function<void(Group*)>& thread_function);\n\n \/\/! Default empty constructor, must be Initialize()d later.\n Group()\n { }\n\n \/\/! Initialize a real Group for construction from the NetManager.\n void Initialize(ClientId my_rank, size_t group_size) {\n assert(my_rank_ == -1u);\n my_rank_ = my_rank;\n connections_.resize(group_size);\n }\n\n \/\/! Initializing constructor, used by tests for creating Groups.\n Group(ClientId my_rank, size_t group_size) {\n Initialize(my_rank, group_size);\n }\n\n \/\/! \\}\n\n \/\/! non-copyable: delete copy-constructor\n Group(const Group&) = delete;\n \/\/! non-copyable: delete assignment operator\n Group& operator = (const Group&) = delete;\n\n \/\/! \\name Status und Access to NetConnections\n \/\/! \\{\n\n \/\/! Return Connection to client id.\n Connection & connection(ClientId id) {\n if (id >= connections_.size())\n throw Exception(\"Group::Connection() requested \"\n \"invalid client id \" + std::to_string(id));\n\n if (id == my_rank_)\n throw Exception(\"Group::Connection() requested \"\n \"connection to self.\");\n\n return connections_[id];\n } \/\/! Return Connection to client id.\n\n \/**\n * @brief Assigns a connection to this net group.\n * @details This method swaps the net connection to memory managed by this group.\n * The reference given to that method will be invalid afterwards.\n *\n * @param connection The connection to assign.\n * @return A ref to the assigned connection, which is always valid, but might be different from the\n * inut connection.\n *\/\n Connection & AssignConnection(Connection& connection) {\n if (connection.peer_id() >= connections_.size())\n throw Exception(\"Group::GetClient() requested \"\n \"invalid client id \"\n + std::to_string(connection.peer_id()));\n\n connections_[connection.peer_id()] = std::move(connection);\n\n return connections_[connection.peer_id()];\n }\n\n \/\/! Return number of connections in this group.\n size_t Size() const {\n return connections_.size();\n }\n\n \/\/! Return my rank in the connection group\n size_t MyRank() const {\n return my_rank_;\n }\n\n \/\/! Closes all client connections\n void Close() {\n if (listener_.IsValid())\n listener_.Close();\n\n for (size_t i = 0; i != connections_.size(); ++i)\n {\n if (i == my_rank_) continue;\n\n if (connections_[i].IsValid())\n connections_[i].Close();\n }\n\n connections_.clear();\n my_rank_ = -1u;\n }\n\n \/\/! Closes all client connections\n ~Group() {\n Close();\n }\n\n \/\/! \\}\n\n \/\/! \\name Richer ReceiveFromAny Functions\n \/\/! \\{\n\n \/*!\n * Receive a fixed-length integral type from any worker into out_value, puts\n * worker id in *src.\n *\n * @param out_src The id of the client the data was received from.\n * @param out_value The received value.\n *\/\n template <typename T>\n void ReceiveFromAny(ClientId* out_src, T* out_value) {\n fd_set fd_set;\n int max_fd = 0;\n\n FD_ZERO(&fd_set);\n\n \/\/ TODO(ej) use NetDispatcher here?\n \/\/ add file descriptor to read set for poll TODO(ts): make this faster\n \/\/ (somewhen)\n\n sLOG0 << \"--- Group::ReceiveFromAny() - select():\";\n\n for (size_t i = 0; i != connections_.size(); ++i)\n {\n if (i == my_rank_) continue;\n\n int fd = connections_[i].GetSocket().fd();\n FD_SET(fd, &fd_set);\n max_fd = std::max(max_fd, fd);\n sLOG0 << \"select from fd=\" << fd;\n }\n\n int retval = select(max_fd + 1, &fd_set, NULL, NULL, NULL);\n\n if (retval < 0) {\n perror(\"select()\");\n abort();\n }\n else if (retval == 0) {\n perror(\"select() TIMEOUT\");\n abort();\n }\n\n for (size_t i = 0; i < connections_.size(); i++)\n {\n if (i == my_rank_) continue;\n\n int fd = connections_[i].GetSocket().fd();\n\n if (FD_ISSET(fd, &fd_set))\n {\n sLOG << \"select() readable fd\" << fd;\n\n *out_src = i;\n return connections_[i].Receive<T>(out_value);\n }\n }\n\n sLOG << \"Select() returned but no fd was readable.\";\n\n return ReceiveFromAny<T>(out_src, out_value);\n }\n\n \/*!\n * Receives a string message from any worker into out_data, which will be\n * resized as needed, puts worker id in *src.\n *\n * @param out_src The id of the worker the string was received from.\n * @param out_data The string received from the worker.\n *\/\n void ReceiveStringFromAny(ClientId* out_src, std::string* out_data) {\n fd_set fd_set;\n int max_fd = 0;\n\n FD_ZERO(&fd_set);\n\n \/\/ add file descriptor to read set for poll TODO(ts): make this faster\n \/\/ (somewhen)\n\n sLOG0 << \"--- Group::ReceiveFromAny() - select():\";\n\n for (size_t i = 0; i != connections_.size(); ++i)\n {\n if (i == my_rank_) continue;\n\n int fd = connections_[i].GetSocket().fd();\n FD_SET(fd, &fd_set);\n max_fd = std::max(max_fd, fd);\n sLOG0 << \"select from fd=\" << fd;\n }\n\n int retval = select(max_fd + 1, &fd_set, NULL, NULL, NULL);\n\n if (retval < 0) {\n perror(\"select()\");\n abort();\n }\n else if (retval == 0) {\n perror(\"select() TIMEOUT\");\n abort();\n }\n\n for (size_t i = 0; i < connections_.size(); i++)\n {\n if (i == my_rank_) continue;\n\n int fd = connections_[i].GetSocket().fd();\n\n if (FD_ISSET(fd, &fd_set))\n {\n sLOG << my_rank_ << \"- select() readable fd\" << fd << \"id\" << i;\n\n *out_src = i;\n return connections_[i].ReceiveString(out_data);\n }\n }\n\n sLOG << my_rank_ << \" - Select() returned but no fd was readable.\";\n\n return ReceiveStringFromAny(out_src, out_data);\n }\n\n \/**\n * @brief Sends a string to a worker.\n * @details Sends a string to a worker.\n *\n * @param dest The worker to send the string to.\n * @param data The string to send.\n *\/\n void SendStringTo(ClientId dest, const std::string& data) {\n this->connection(dest).SendString(data);\n }\n\n \/**\n * @brief Receives a string from the given worker.\n * @details Receives a string from the given worker.\n *\n * @param src The worker to receive the string from.\n * @param data A pointer to the string where the received string should be stored.\n *\/\n void ReceiveStringFrom(ClientId src, std::string* data) {\n this->connection(src).ReceiveString(data);\n }\n\n \/**\n * @brief Sends a fixed lentgh type to the given worker.\n * @details Sends a fixed lentgh type to the given worker.\n *\n * @param dest The worker to send the data to.\n * @param data The data to send.\n *\/\n template <typename T>\n void SendTo(ClientId dest, const T& data) {\n this->connection(dest).Send(data);\n }\n\n \/**\n * @brief Receives a fixed length type from the given worker.\n * @details Receives a fixed length type from the given worker.\n *\n * @param src The worker to receive the fixed length type from.\n * @param data A pointer to the location where the received data should be stored.\n *\/\n template <typename T>\n void ReceiveFrom(ClientId src, T* data) {\n this->connection(src).Receive(data);\n }\n\n \/**\n * @brief Broadcasts a string to all workers.\n * @details Broadcasts a string to all workers.\n *\n * @param data The string to broadcast.\n *\/\n void BroadcastString(const std::string& data) {\n for (size_t i = 0; i < connections_.size(); i++)\n {\n if (i == my_rank_) continue;\n SendStringTo(i, data);\n }\n }\n\n \/**\n * @brief Broadcasts a fixed length type to all workers.\n * @details Broadcasts a fixed length type to all workers.\n *\n * @param data The data to broadcast.\n *\/\n template <typename T>\n void BroadcastString(const T& data) {\n for (size_t i = 0; i < connections_.size(); i++)\n {\n if (i == my_rank_) continue;\n SendStringTo(i, data);\n }\n }\n\n \/\/! \\}\n\n \/\/! \\name Collective Operations\n \/\/! \\{\n\n \/\/TODO(rh) Please migrate into a different class, since Group is an abstract concept that bundles connections.\n\n template <typename T, typename BinarySumOp = common::SumOp<T> >\n void AllReduce(T& value, BinarySumOp sumOp = BinarySumOp());\n\n template <typename T, typename BinarySumOp = common::SumOp<T> >\n void PrefixSum(T& value, BinarySumOp sumOp = BinarySumOp());\n\n template <typename T, typename BinarySumOp = common::SumOp<T> >\n void ReduceToRoot(T& value, BinarySumOp sumOp = BinarySumOp());\n\n template <typename T>\n void Broadcast(T& value);\n\n \/\/! \\}\n\nprivate:\n \/\/! The client id of this object in the Group.\n ClientId my_rank_ = -1;\n\n \/\/! Connections to all other clients in the Group.\n std::vector<Connection> connections_;\n\n \/\/! Socket on which to listen for incoming connections.\n Connection listener_;\n};\n\ntemplate <typename T, typename BinarySumOp>\nvoid Group::PrefixSum(T& value, BinarySumOp sumOp) {\n \/\/ The total sum in the current hypercube. This is stored, because later,\n \/\/ bigger hypercubes need this value.\n T total_sum = value;\n\n for (size_t d = 1; d < Size(); d <<= 1)\n {\n \/\/ Send total sum of this hypercube to worker with id = id XOR d\n if ((MyRank() ^ d) < Size()) {\n Connection(MyRank() ^ d).Send(total_sum);\n sLOG << \"PREFIX_SUM: Worker\" << MyRank() << \": Sending\" << total_sum\n << \"to worker\" << (MyRank() ^ d);\n }\n\n \/\/ Receive total sum of smaller hypercube from worker with id = id XOR d\n T recv_data;\n if ((MyRank() ^ d) < Size()) {\n Connection(MyRank() ^ d).Receive(&recv_data);\n total_sum = sumOp(total_sum, recv_data);\n \/\/ Variable 'value' represents the prefix sum of this worker\n if (MyRank() & d)\n value = sumOp(value, recv_data);\n sLOG << \"PREFIX_SUM: Worker\" << MyRank() << \": Received\" << recv_data\n << \"from worker\" << (MyRank() ^ d)\n << \"value =\" << value;\n }\n }\n\n sLOG << \"PREFIX_SUM: Worker\" << MyRank()\n << \": value after prefix sum =\" << value;\n}\n\n\/\/! Perform a binomial tree reduce to the worker with index 0\ntemplate <typename T, typename BinarySumOp>\nvoid Group::ReduceToRoot(T& value, BinarySumOp sumOp) {\n bool active = true;\n for (size_t d = 1; d < Size(); d <<= 1) {\n if (active) {\n if (MyRank() & d) {\n connection(MyRank() - d).Send(value);\n active = false;\n }\n else if (MyRank() + d < Size()) {\n T recv_data;\n connection(MyRank() + d).Receive(&recv_data);\n value = sumOp(value, recv_data);\n }\n }\n }\n}\n\n\/\/! Binomial-broadcasts the value of the worker with index 0 to all the others\ntemplate <typename T>\nvoid Group::Broadcast(T& value) {\n if (MyRank() > 0) {\n ClientId from;\n ReceiveFromAny(&from, &value);\n }\n for (size_t d = 1, i = 0; ((MyRank() >> i) & 1) == 0 && d < Size(); d <<= 1, ++i) {\n if (MyRank() + d < Size()) {\n connection(MyRank() + d).Send(value);\n }\n }\n}\n\n\/\/! Perform an All-Reduce on the workers by aggregating all values and sending\n\/\/! them backto all workers\ntemplate <typename T, typename BinarySumOp>\nvoid Group::AllReduce(T& value, BinarySumOp sum_op) {\n ReduceToRoot(value, sum_op);\n Broadcast(value);\n}\n\n\/\/! \\}\n\n} \/\/ namespace net\n} \/\/ namespace c7a\n\n#endif \/\/ !C7A_NET_GROUP_HEADER\n\n\/******************************************************************************\/\n<commit_msg>Fixing connection() calls.<commit_after>\/*******************************************************************************\n * c7a\/net\/group.hpp\n *\n * net::Group is a collection of NetConnections providing simple MPI-like\n * collectives and point-to-point communication.\n *\n * Part of Project c7a.\n *\n * Copyright (C) 2015 Timo Bingmann <tb@panthema.net>\n *\n * This file has no license. Only Chuck Norris can compile it.\n ******************************************************************************\/\n\n#pragma once\n#ifndef C7A_NET_GROUP_HEADER\n#define C7A_NET_GROUP_HEADER\n\n#include <c7a\/net\/endpoint.hpp>\n#include <c7a\/net\/connection.hpp>\n#include <c7a\/common\/functional.hpp>\n#include <c7a\/common\/logger.hpp>\n\n#include <algorithm>\n#include <cassert>\n#include <cstring>\n#include <map>\n#include <string>\n#include <thread>\n#include <utility>\n#include <vector>\n\nnamespace c7a {\nnamespace net {\n\n\/\/! \\addtogroup net Network Communication\n\/\/! \\{\n\ntypedef unsigned int ClientId;\n\n\/\/TODO(ej) Cleanup the Group. Make to a sole collection holding a bunch of connections.\n\/\/Move everything else into appropriate channel.\n\n\/*!\n * Collection of NetConnections to workers, allows point-to-point client\n * communication and simple collectives like MPI.\n *\/\nclass Group\n{\n static const bool debug = false;\n\npublic:\n \/\/! \\name Construction and Initialization\n \/\/! \\{\n\n \/\/! Construct a mock Group using a complete graph of local stream sockets\n \/\/! for testing, and starts a thread for each client, which gets passed the\n \/\/! Group object. This is ideal for testing network communication\n \/\/! protocols. See tests\/net\/test-net-group.cpp for examples.\n \/\/! @param num_clients The number of clients to spawn.\n \/\/! @param thread_function The function to execute for each client.\n static void ExecuteLocalMock(\n size_t num_clients,\n const std::function<void(Group*)>& thread_function);\n\n \/\/! Default empty constructor, must be Initialize()d later.\n Group()\n { }\n\n \/\/! Initialize a real Group for construction from the NetManager.\n void Initialize(ClientId my_rank, size_t group_size) {\n assert(my_rank_ == -1u);\n my_rank_ = my_rank;\n connections_.resize(group_size);\n }\n\n \/\/! Initializing constructor, used by tests for creating Groups.\n Group(ClientId my_rank, size_t group_size) {\n Initialize(my_rank, group_size);\n }\n\n \/\/! \\}\n\n \/\/! non-copyable: delete copy-constructor\n Group(const Group&) = delete;\n \/\/! non-copyable: delete assignment operator\n Group& operator = (const Group&) = delete;\n\n \/\/! \\name Status und Access to NetConnections\n \/\/! \\{\n\n \/\/! Return Connection to client id.\n Connection & connection(ClientId id) {\n if (id >= connections_.size())\n throw Exception(\"Group::Connection() requested \"\n \"invalid client id \" + std::to_string(id));\n\n if (id == my_rank_)\n throw Exception(\"Group::Connection() requested \"\n \"connection to self.\");\n\n return connections_[id];\n } \/\/! Return Connection to client id.\n\n \/**\n * @brief Assigns a connection to this net group.\n * @details This method swaps the net connection to memory managed by this group.\n * The reference given to that method will be invalid afterwards.\n *\n * @param connection The connection to assign.\n * @return A ref to the assigned connection, which is always valid, but might be different from the\n * inut connection.\n *\/\n Connection & AssignConnection(Connection& connection) {\n if (connection.peer_id() >= connections_.size())\n throw Exception(\"Group::GetClient() requested \"\n \"invalid client id \"\n + std::to_string(connection.peer_id()));\n\n connections_[connection.peer_id()] = std::move(connection);\n\n return connections_[connection.peer_id()];\n }\n\n \/\/! Return number of connections in this group.\n size_t Size() const {\n return connections_.size();\n }\n\n \/\/! Return my rank in the connection group\n size_t MyRank() const {\n return my_rank_;\n }\n\n \/\/! Closes all client connections\n void Close() {\n if (listener_.IsValid())\n listener_.Close();\n\n for (size_t i = 0; i != connections_.size(); ++i)\n {\n if (i == my_rank_) continue;\n\n if (connections_[i].IsValid())\n connections_[i].Close();\n }\n\n connections_.clear();\n my_rank_ = -1u;\n }\n\n \/\/! Closes all client connections\n ~Group() {\n Close();\n }\n\n \/\/! \\}\n\n \/\/! \\name Richer ReceiveFromAny Functions\n \/\/! \\{\n\n \/*!\n * Receive a fixed-length integral type from any worker into out_value, puts\n * worker id in *src.\n *\n * @param out_src The id of the client the data was received from.\n * @param out_value The received value.\n *\/\n template <typename T>\n void ReceiveFromAny(ClientId* out_src, T* out_value) {\n fd_set fd_set;\n int max_fd = 0;\n\n FD_ZERO(&fd_set);\n\n \/\/ TODO(ej) use NetDispatcher here?\n \/\/ add file descriptor to read set for poll TODO(ts): make this faster\n \/\/ (somewhen)\n\n sLOG0 << \"--- Group::ReceiveFromAny() - select():\";\n\n for (size_t i = 0; i != connections_.size(); ++i)\n {\n if (i == my_rank_) continue;\n\n int fd = connections_[i].GetSocket().fd();\n FD_SET(fd, &fd_set);\n max_fd = std::max(max_fd, fd);\n sLOG0 << \"select from fd=\" << fd;\n }\n\n int retval = select(max_fd + 1, &fd_set, NULL, NULL, NULL);\n\n if (retval < 0) {\n perror(\"select()\");\n abort();\n }\n else if (retval == 0) {\n perror(\"select() TIMEOUT\");\n abort();\n }\n\n for (size_t i = 0; i < connections_.size(); i++)\n {\n if (i == my_rank_) continue;\n\n int fd = connections_[i].GetSocket().fd();\n\n if (FD_ISSET(fd, &fd_set))\n {\n sLOG << \"select() readable fd\" << fd;\n\n *out_src = i;\n return connections_[i].Receive<T>(out_value);\n }\n }\n\n sLOG << \"Select() returned but no fd was readable.\";\n\n return ReceiveFromAny<T>(out_src, out_value);\n }\n\n \/*!\n * Receives a string message from any worker into out_data, which will be\n * resized as needed, puts worker id in *src.\n *\n * @param out_src The id of the worker the string was received from.\n * @param out_data The string received from the worker.\n *\/\n void ReceiveStringFromAny(ClientId* out_src, std::string* out_data) {\n fd_set fd_set;\n int max_fd = 0;\n\n FD_ZERO(&fd_set);\n\n \/\/ add file descriptor to read set for poll TODO(ts): make this faster\n \/\/ (somewhen)\n\n sLOG0 << \"--- Group::ReceiveFromAny() - select():\";\n\n for (size_t i = 0; i != connections_.size(); ++i)\n {\n if (i == my_rank_) continue;\n\n int fd = connections_[i].GetSocket().fd();\n FD_SET(fd, &fd_set);\n max_fd = std::max(max_fd, fd);\n sLOG0 << \"select from fd=\" << fd;\n }\n\n int retval = select(max_fd + 1, &fd_set, NULL, NULL, NULL);\n\n if (retval < 0) {\n perror(\"select()\");\n abort();\n }\n else if (retval == 0) {\n perror(\"select() TIMEOUT\");\n abort();\n }\n\n for (size_t i = 0; i < connections_.size(); i++)\n {\n if (i == my_rank_) continue;\n\n int fd = connections_[i].GetSocket().fd();\n\n if (FD_ISSET(fd, &fd_set))\n {\n sLOG << my_rank_ << \"- select() readable fd\" << fd << \"id\" << i;\n\n *out_src = i;\n return connections_[i].ReceiveString(out_data);\n }\n }\n\n sLOG << my_rank_ << \" - Select() returned but no fd was readable.\";\n\n return ReceiveStringFromAny(out_src, out_data);\n }\n\n \/**\n * @brief Sends a string to a worker.\n * @details Sends a string to a worker.\n *\n * @param dest The worker to send the string to.\n * @param data The string to send.\n *\/\n void SendStringTo(ClientId dest, const std::string& data) {\n this->connection(dest).SendString(data);\n }\n\n \/**\n * @brief Receives a string from the given worker.\n * @details Receives a string from the given worker.\n *\n * @param src The worker to receive the string from.\n * @param data A pointer to the string where the received string should be stored.\n *\/\n void ReceiveStringFrom(ClientId src, std::string* data) {\n this->connection(src).ReceiveString(data);\n }\n\n \/**\n * @brief Sends a fixed lentgh type to the given worker.\n * @details Sends a fixed lentgh type to the given worker.\n *\n * @param dest The worker to send the data to.\n * @param data The data to send.\n *\/\n template <typename T>\n void SendTo(ClientId dest, const T& data) {\n this->connection(dest).Send(data);\n }\n\n \/**\n * @brief Receives a fixed length type from the given worker.\n * @details Receives a fixed length type from the given worker.\n *\n * @param src The worker to receive the fixed length type from.\n * @param data A pointer to the location where the received data should be stored.\n *\/\n template <typename T>\n void ReceiveFrom(ClientId src, T* data) {\n this->connection(src).Receive(data);\n }\n\n \/**\n * @brief Broadcasts a string to all workers.\n * @details Broadcasts a string to all workers.\n *\n * @param data The string to broadcast.\n *\/\n void BroadcastString(const std::string& data) {\n for (size_t i = 0; i < connections_.size(); i++)\n {\n if (i == my_rank_) continue;\n SendStringTo(i, data);\n }\n }\n\n \/**\n * @brief Broadcasts a fixed length type to all workers.\n * @details Broadcasts a fixed length type to all workers.\n *\n * @param data The data to broadcast.\n *\/\n template <typename T>\n void BroadcastString(const T& data) {\n for (size_t i = 0; i < connections_.size(); i++)\n {\n if (i == my_rank_) continue;\n SendStringTo(i, data);\n }\n }\n\n \/\/! \\}\n\n \/\/! \\name Collective Operations\n \/\/! \\{\n\n \/\/TODO(rh) Please migrate into a different class, since Group is an abstract concept that bundles connections.\n\n template <typename T, typename BinarySumOp = common::SumOp<T> >\n void AllReduce(T& value, BinarySumOp sumOp = BinarySumOp());\n\n template <typename T, typename BinarySumOp = common::SumOp<T> >\n void PrefixSum(T& value, BinarySumOp sumOp = BinarySumOp());\n\n template <typename T, typename BinarySumOp = common::SumOp<T> >\n void ReduceToRoot(T& value, BinarySumOp sumOp = BinarySumOp());\n\n template <typename T>\n void Broadcast(T& value);\n\n \/\/! \\}\n\nprivate:\n \/\/! The client id of this object in the Group.\n ClientId my_rank_ = -1;\n\n \/\/! Connections to all other clients in the Group.\n std::vector<Connection> connections_;\n\n \/\/! Socket on which to listen for incoming connections.\n Connection listener_;\n};\n\ntemplate <typename T, typename BinarySumOp>\nvoid Group::PrefixSum(T& value, BinarySumOp sumOp) {\n \/\/ The total sum in the current hypercube. This is stored, because later,\n \/\/ bigger hypercubes need this value.\n T total_sum = value;\n\n for (size_t d = 1; d < Size(); d <<= 1)\n {\n \/\/ Send total sum of this hypercube to worker with id = id XOR d\n if ((MyRank() ^ d) < Size()) {\n connection(MyRank() ^ d).Send(total_sum);\n sLOG << \"PREFIX_SUM: Worker\" << MyRank() << \": Sending\" << total_sum\n << \"to worker\" << (MyRank() ^ d);\n }\n\n \/\/ Receive total sum of smaller hypercube from worker with id = id XOR d\n T recv_data;\n if ((MyRank() ^ d) < Size()) {\n connection(MyRank() ^ d).Receive(&recv_data);\n total_sum = sumOp(total_sum, recv_data);\n \/\/ Variable 'value' represents the prefix sum of this worker\n if (MyRank() & d)\n value = sumOp(value, recv_data);\n sLOG << \"PREFIX_SUM: Worker\" << MyRank() << \": Received\" << recv_data\n << \"from worker\" << (MyRank() ^ d)\n << \"value =\" << value;\n }\n }\n\n sLOG << \"PREFIX_SUM: Worker\" << MyRank()\n << \": value after prefix sum =\" << value;\n}\n\n\/\/! Perform a binomial tree reduce to the worker with index 0\ntemplate <typename T, typename BinarySumOp>\nvoid Group::ReduceToRoot(T& value, BinarySumOp sumOp) {\n bool active = true;\n for (size_t d = 1; d < Size(); d <<= 1) {\n if (active) {\n if (MyRank() & d) {\n connection(MyRank() - d).Send(value);\n active = false;\n }\n else if (MyRank() + d < Size()) {\n T recv_data;\n connection(MyRank() + d).Receive(&recv_data);\n value = sumOp(value, recv_data);\n }\n }\n }\n}\n\n\/\/! Binomial-broadcasts the value of the worker with index 0 to all the others\ntemplate <typename T>\nvoid Group::Broadcast(T& value) {\n if (MyRank() > 0) {\n ClientId from;\n ReceiveFromAny(&from, &value);\n }\n for (size_t d = 1, i = 0; ((MyRank() >> i) & 1) == 0 && d < Size(); d <<= 1, ++i) {\n if (MyRank() + d < Size()) {\n connection(MyRank() + d).Send(value);\n }\n }\n}\n\n\/\/! Perform an All-Reduce on the workers by aggregating all values and sending\n\/\/! them backto all workers\ntemplate <typename T, typename BinarySumOp>\nvoid Group::AllReduce(T& value, BinarySumOp sum_op) {\n ReduceToRoot(value, sum_op);\n Broadcast(value);\n}\n\n\/\/! \\}\n\n} \/\/ namespace net\n} \/\/ namespace c7a\n\n#endif \/\/ !C7A_NET_GROUP_HEADER\n\n\/******************************************************************************\/\n<|endoftext|>"} {"text":"<commit_before>using namespace GeFiCa;\n\/\/ calculate and save fields of an Inverted Coaxial Point-Contact (ICPC) HPGe\nvoid calculateFields(const char *output=\"ICPC.root\")\n{\n SquarePointContact detector;\n detector.Bias[0]=70; \/\/ bias on point contact\n detector.Bias[1]=0; \/\/ ground outer contact\n\n detector.Width=1.8*cm; detector.Height=1.0*cm; detector.Length=1.8*cm;\n\n detector.PointContactW=0.6*mm; detector.PointContactH=0.1*mm;\n detector.PointContactL=0.6*mm;\n\n detector.TaperW=0.3*cm;\n \/\/detector.WrapAroundW=0.3*cm;\n\n detector.BottomImpurity=4e9\/cm3; detector.TopImpurity=4e9\/cm3;\n\n int nx=50; \n int ny=50; \/\/ precision: 0.1 mm\n int nz=50; \/\/ precision: 0.1 mm\n XYZ grid(nx,ny,nz);\n grid.SetupWith(detector);\n grid.RelaxationFactor=1.84;\n grid.SuccessiveOverRelax();\n \n TFile file(output,\"recreate\");\n detector.Write();\n grid.Write();\n file.Close();\n}\n<commit_msg>update<commit_after>using namespace GeFiCa;\n\/\/ calculate and save fields of an Inverted Coaxial Point-Contact (ICPC) HPGe\nvoid calculateFields(const char *output=\"ICPC.root\")\n{\n SquarePointContact detector;\n detector.Bias[0]=0; \/\/ bias on point contact\n detector.Bias[1]=70; \/\/ ground outer contact\n\n detector.Width=1.8*cm; detector.Height=1.0*cm; detector.Length=1.8*cm;\n\n detector.PointContactW=0.6*mm; detector.PointContactH=0.1*mm;\n detector.PointContactL=0.6*mm;\n\n detector.TaperW=0.3*cm;\n \/\/detector.WrapAroundW=0.3*cm;\n\n detector.BottomImpurity=4e9\/cm3; detector.TopImpurity=4e9\/cm3;\n\n int nx=50; \n int ny=50; \/\/ precision: 0.1 mm\n int nz=100; \/\/ precision: 0.1 mm\n XYZ grid(nx,ny,nz);\n grid.SetupWith(detector);\n grid.RelaxationFactor=1.94;\n grid.SuccessiveOverRelax();\n \n TFile file(output,\"recreate\");\n detector.Write();\n grid.Write();\n file.Close();\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (C) 2013 Google Inc. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS \"AS IS\" AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY\n * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF\n * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \"config.h\"\n\n#if ENABLE(WEBGL)\n\n#include \"EXTDrawBuffers.h\"\n\n#include \"Extensions3D.h\"\n\nnamespace WebCore {\n\nEXTDrawBuffers::EXTDrawBuffers(WebGLRenderingContext* context)\n : WebGLExtension(context)\n{\n}\n\nEXTDrawBuffers::~EXTDrawBuffers()\n{\n}\n\nWebGLExtension::ExtensionName EXTDrawBuffers::getName() const\n{\n return WebGLExtension::EXTDrawBuffersName;\n}\n\nPassOwnPtr<EXTDrawBuffers> EXTDrawBuffers::create(WebGLRenderingContext* context)\n{\n return adoptPtr(new EXTDrawBuffers(context));\n}\n\n\/\/ static\nbool EXTDrawBuffers::supported(WebGLRenderingContext* context)\n{\n#if OS(DARWIN)\n \/\/ https:\/\/bugs.webkit.org\/show_bug.cgi?id=112486\n return false;\n#endif\n Extensions3D* extensions = context->graphicsContext3D()->getExtensions();\n return (extensions->supports(\"GL_EXT_draw_buffers\")\n && satisfiesWebGLRequirements(context));\n}\n\nvoid EXTDrawBuffers::drawBuffersEXT(const Vector<GC3Denum>& buffers)\n{\n if (m_context->isContextLost())\n return;\n GC3Dsizei n = buffers.size();\n const GC3Denum* bufs = buffers.data();\n if (!m_context->m_framebufferBinding) {\n if (n != 1) {\n m_context->synthesizeGLError(GraphicsContext3D::INVALID_VALUE, \"drawBuffersEXT\", \"more than one buffer\");\n return;\n }\n if (bufs[0] != GraphicsContext3D::BACK && bufs[0] != GraphicsContext3D::NONE) {\n m_context->synthesizeGLError(GraphicsContext3D::INVALID_OPERATION, \"drawBuffersEXT\", \"BACK or NONE\");\n return;\n }\n \/\/ Because the backbuffer is simulated on all current WebKit ports, we need to change BACK to COLOR_ATTACHMENT0.\n GC3Denum value = (bufs[0] == GraphicsContext3D::BACK) ? GraphicsContext3D::COLOR_ATTACHMENT0 : GraphicsContext3D::NONE;\n m_context->graphicsContext3D()->getExtensions()->drawBuffersEXT(1, &value);\n m_context->setBackDrawBuffer(bufs[0]);\n } else {\n if (n > m_context->getMaxDrawBuffers()) {\n m_context->synthesizeGLError(GraphicsContext3D::INVALID_VALUE, \"drawBuffersEXT\", \"more than max draw buffers\");\n return;\n }\n for (GC3Dsizei i = 0; i < n; ++i) {\n if (bufs[i] != GraphicsContext3D::NONE && bufs[i] != static_cast<GC3Denum>(Extensions3D::COLOR_ATTACHMENT0_EXT + i)) {\n m_context->synthesizeGLError(GraphicsContext3D::INVALID_OPERATION, \"drawBuffersEXT\", \"COLOR_ATTACHMENTi_EXT or NONE\");\n return;\n }\n }\n m_context->m_framebufferBinding->drawBuffers(buffers);\n }\n}\n\n\/\/ static\nbool EXTDrawBuffers::satisfiesWebGLRequirements(WebGLRenderingContext* webglContext)\n{\n GraphicsContext3D* context = webglContext->graphicsContext3D();\n\n \/\/ This is called after we make sure GL_EXT_draw_buffers is supported.\n GC3Dint maxDrawBuffers = 0;\n GC3Dint maxColorAttachments = 0;\n context->getIntegerv(Extensions3D::MAX_DRAW_BUFFERS_EXT, &maxDrawBuffers);\n context->getIntegerv(Extensions3D::MAX_COLOR_ATTACHMENTS_EXT, &maxColorAttachments);\n if (maxDrawBuffers < 4 || maxColorAttachments < 4)\n return false;\n\n Platform3DObject fbo = context->createFramebuffer();\n context->bindFramebuffer(GraphicsContext3D::FRAMEBUFFER, fbo);\n\n#if PLATFORM(CHROMIUM)\n const unsigned char* buffer = 0; \/\/ Chromium doesn't allow init data for depth\/stencil tetxures.\n#else\n const unsigned char buffer[4] = { 0, 0, 0, 0 }; \/\/ textures are required to be initialized for other ports.\n#endif\n bool supportsDepth = (context->getExtensions()->supports(\"GL_CHROMIUM_depth_texture\")\n || context->getExtensions()->supports(\"GL_OES_depth_texture\")\n || context->getExtensions()->supports(\"GL_ARB_depth_texture\"));\n bool supportsDepthStencil = (context->getExtensions()->supports(\"GL_EXT_packed_depth_stencil\")\n || context->getExtensions()->supports(\"GL_OES_packed_depth_stencil\"));\n Platform3DObject depthStencil = 0;\n if (supportsDepthStencil) {\n depthStencil = context->createTexture();\n context->bindTexture(GraphicsContext3D::TEXTURE_2D, depthStencil);\n context->texImage2D(GraphicsContext3D::TEXTURE_2D, 0, GraphicsContext3D::DEPTH_STENCIL, 1, 1, 0, GraphicsContext3D::DEPTH_STENCIL, GraphicsContext3D::UNSIGNED_INT_24_8, buffer);\n }\n Platform3DObject depth = 0;\n if (supportsDepth) {\n depth = context->createTexture();\n context->bindTexture(GraphicsContext3D::TEXTURE_2D, depth);\n context->texImage2D(GraphicsContext3D::TEXTURE_2D, 0, GraphicsContext3D::DEPTH_COMPONENT, 1, 1, 0, GraphicsContext3D::DEPTH_COMPONENT, GraphicsContext3D::UNSIGNED_INT, buffer);\n }\n\n Vector<Platform3DObject> colors;\n bool ok = true;\n GC3Dint maxAllowedBuffers = std::min(maxDrawBuffers, maxColorAttachments);\n for (GC3Dint i = 0; i < maxAllowedBuffers; ++i) {\n Platform3DObject color = context->createTexture();\n colors.append(color);\n context->bindTexture(GraphicsContext3D::TEXTURE_2D, color);\n context->texImage2D(GraphicsContext3D::TEXTURE_2D, 0, GraphicsContext3D::RGBA, 1, 1, 0, GraphicsContext3D::RGBA, GraphicsContext3D::UNSIGNED_BYTE, buffer);\n context->framebufferTexture2D(GraphicsContext3D::FRAMEBUFFER, GraphicsContext3D::COLOR_ATTACHMENT0 + i, GraphicsContext3D::TEXTURE_2D, color, 0);\n if (context->checkFramebufferStatus(GraphicsContext3D::FRAMEBUFFER) != GraphicsContext3D::FRAMEBUFFER_COMPLETE) {\n ok = false;\n break;\n }\n if (supportsDepth) {\n context->framebufferTexture2D(GraphicsContext3D::FRAMEBUFFER, GraphicsContext3D::DEPTH_ATTACHMENT, GraphicsContext3D::TEXTURE_2D, depth, 0);\n if (context->checkFramebufferStatus(GraphicsContext3D::FRAMEBUFFER) != GraphicsContext3D::FRAMEBUFFER_COMPLETE) {\n ok = false;\n break;\n }\n context->framebufferTexture2D(GraphicsContext3D::FRAMEBUFFER, GraphicsContext3D::DEPTH_ATTACHMENT, GraphicsContext3D::TEXTURE_2D, 0, 0);\n }\n if (supportsDepthStencil) {\n context->framebufferTexture2D(GraphicsContext3D::FRAMEBUFFER, GraphicsContext3D::DEPTH_ATTACHMENT, GraphicsContext3D::TEXTURE_2D, depthStencil, 0);\n context->framebufferTexture2D(GraphicsContext3D::FRAMEBUFFER, GraphicsContext3D::STENCIL_ATTACHMENT, GraphicsContext3D::TEXTURE_2D, depthStencil, 0);\n if (context->checkFramebufferStatus(GraphicsContext3D::FRAMEBUFFER) != GraphicsContext3D::FRAMEBUFFER_COMPLETE) {\n ok = false;\n break;\n }\n context->framebufferTexture2D(GraphicsContext3D::FRAMEBUFFER, GraphicsContext3D::DEPTH_ATTACHMENT, GraphicsContext3D::TEXTURE_2D, 0, 0);\n context->framebufferTexture2D(GraphicsContext3D::FRAMEBUFFER, GraphicsContext3D::STENCIL_ATTACHMENT, GraphicsContext3D::TEXTURE_2D, 0, 0);\n }\n }\n\n webglContext->restoreCurrentFramebuffer();\n context->deleteFramebuffer(fbo);\n webglContext->restoreCurrentTexture2D();\n if (supportsDepth)\n context->deleteTexture(depth);\n if (supportsDepthStencil)\n context->deleteTexture(depthStencil);\n for (size_t i = 0; i < colors.size(); ++i)\n context->deleteTexture(colors[i]);\n return ok;\n}\n\n} \/\/ namespace WebCore\n\n#endif \/\/ ENABLE(WEBGL)\n<commit_msg>Enable EXT_draw_buffers on Mac.<commit_after>\/*\n * Copyright (C) 2013 Google Inc. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS \"AS IS\" AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY\n * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF\n * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \"config.h\"\n\n#if ENABLE(WEBGL)\n\n#include \"EXTDrawBuffers.h\"\n\n#include \"Extensions3D.h\"\n\nnamespace WebCore {\n\nEXTDrawBuffers::EXTDrawBuffers(WebGLRenderingContext* context)\n : WebGLExtension(context)\n{\n}\n\nEXTDrawBuffers::~EXTDrawBuffers()\n{\n}\n\nWebGLExtension::ExtensionName EXTDrawBuffers::getName() const\n{\n return WebGLExtension::EXTDrawBuffersName;\n}\n\nPassOwnPtr<EXTDrawBuffers> EXTDrawBuffers::create(WebGLRenderingContext* context)\n{\n return adoptPtr(new EXTDrawBuffers(context));\n}\n\n\/\/ static\nbool EXTDrawBuffers::supported(WebGLRenderingContext* context)\n{\n Extensions3D* extensions = context->graphicsContext3D()->getExtensions();\n return (extensions->supports(\"GL_EXT_draw_buffers\")\n && satisfiesWebGLRequirements(context));\n}\n\nvoid EXTDrawBuffers::drawBuffersEXT(const Vector<GC3Denum>& buffers)\n{\n if (m_context->isContextLost())\n return;\n GC3Dsizei n = buffers.size();\n const GC3Denum* bufs = buffers.data();\n if (!m_context->m_framebufferBinding) {\n if (n != 1) {\n m_context->synthesizeGLError(GraphicsContext3D::INVALID_VALUE, \"drawBuffersEXT\", \"more than one buffer\");\n return;\n }\n if (bufs[0] != GraphicsContext3D::BACK && bufs[0] != GraphicsContext3D::NONE) {\n m_context->synthesizeGLError(GraphicsContext3D::INVALID_OPERATION, \"drawBuffersEXT\", \"BACK or NONE\");\n return;\n }\n \/\/ Because the backbuffer is simulated on all current WebKit ports, we need to change BACK to COLOR_ATTACHMENT0.\n GC3Denum value = (bufs[0] == GraphicsContext3D::BACK) ? GraphicsContext3D::COLOR_ATTACHMENT0 : GraphicsContext3D::NONE;\n m_context->graphicsContext3D()->getExtensions()->drawBuffersEXT(1, &value);\n m_context->setBackDrawBuffer(bufs[0]);\n } else {\n if (n > m_context->getMaxDrawBuffers()) {\n m_context->synthesizeGLError(GraphicsContext3D::INVALID_VALUE, \"drawBuffersEXT\", \"more than max draw buffers\");\n return;\n }\n for (GC3Dsizei i = 0; i < n; ++i) {\n if (bufs[i] != GraphicsContext3D::NONE && bufs[i] != static_cast<GC3Denum>(Extensions3D::COLOR_ATTACHMENT0_EXT + i)) {\n m_context->synthesizeGLError(GraphicsContext3D::INVALID_OPERATION, \"drawBuffersEXT\", \"COLOR_ATTACHMENTi_EXT or NONE\");\n return;\n }\n }\n m_context->m_framebufferBinding->drawBuffers(buffers);\n }\n}\n\n\/\/ static\nbool EXTDrawBuffers::satisfiesWebGLRequirements(WebGLRenderingContext* webglContext)\n{\n GraphicsContext3D* context = webglContext->graphicsContext3D();\n\n \/\/ This is called after we make sure GL_EXT_draw_buffers is supported.\n GC3Dint maxDrawBuffers = 0;\n GC3Dint maxColorAttachments = 0;\n context->getIntegerv(Extensions3D::MAX_DRAW_BUFFERS_EXT, &maxDrawBuffers);\n context->getIntegerv(Extensions3D::MAX_COLOR_ATTACHMENTS_EXT, &maxColorAttachments);\n if (maxDrawBuffers < 4 || maxColorAttachments < 4)\n return false;\n\n Platform3DObject fbo = context->createFramebuffer();\n context->bindFramebuffer(GraphicsContext3D::FRAMEBUFFER, fbo);\n\n#if PLATFORM(CHROMIUM)\n const unsigned char* buffer = 0; \/\/ Chromium doesn't allow init data for depth\/stencil tetxures.\n#else\n const unsigned char buffer[4] = { 0, 0, 0, 0 }; \/\/ textures are required to be initialized for other ports.\n#endif\n bool supportsDepth = (context->getExtensions()->supports(\"GL_CHROMIUM_depth_texture\")\n || context->getExtensions()->supports(\"GL_OES_depth_texture\")\n || context->getExtensions()->supports(\"GL_ARB_depth_texture\"));\n bool supportsDepthStencil = (context->getExtensions()->supports(\"GL_EXT_packed_depth_stencil\")\n || context->getExtensions()->supports(\"GL_OES_packed_depth_stencil\"));\n Platform3DObject depthStencil = 0;\n if (supportsDepthStencil) {\n depthStencil = context->createTexture();\n context->bindTexture(GraphicsContext3D::TEXTURE_2D, depthStencil);\n context->texImage2D(GraphicsContext3D::TEXTURE_2D, 0, GraphicsContext3D::DEPTH_STENCIL, 1, 1, 0, GraphicsContext3D::DEPTH_STENCIL, GraphicsContext3D::UNSIGNED_INT_24_8, buffer);\n }\n Platform3DObject depth = 0;\n if (supportsDepth) {\n depth = context->createTexture();\n context->bindTexture(GraphicsContext3D::TEXTURE_2D, depth);\n context->texImage2D(GraphicsContext3D::TEXTURE_2D, 0, GraphicsContext3D::DEPTH_COMPONENT, 1, 1, 0, GraphicsContext3D::DEPTH_COMPONENT, GraphicsContext3D::UNSIGNED_INT, buffer);\n }\n\n Vector<Platform3DObject> colors;\n bool ok = true;\n GC3Dint maxAllowedBuffers = std::min(maxDrawBuffers, maxColorAttachments);\n for (GC3Dint i = 0; i < maxAllowedBuffers; ++i) {\n Platform3DObject color = context->createTexture();\n colors.append(color);\n context->bindTexture(GraphicsContext3D::TEXTURE_2D, color);\n context->texImage2D(GraphicsContext3D::TEXTURE_2D, 0, GraphicsContext3D::RGBA, 1, 1, 0, GraphicsContext3D::RGBA, GraphicsContext3D::UNSIGNED_BYTE, buffer);\n context->framebufferTexture2D(GraphicsContext3D::FRAMEBUFFER, GraphicsContext3D::COLOR_ATTACHMENT0 + i, GraphicsContext3D::TEXTURE_2D, color, 0);\n if (context->checkFramebufferStatus(GraphicsContext3D::FRAMEBUFFER) != GraphicsContext3D::FRAMEBUFFER_COMPLETE) {\n ok = false;\n break;\n }\n if (supportsDepth) {\n context->framebufferTexture2D(GraphicsContext3D::FRAMEBUFFER, GraphicsContext3D::DEPTH_ATTACHMENT, GraphicsContext3D::TEXTURE_2D, depth, 0);\n if (context->checkFramebufferStatus(GraphicsContext3D::FRAMEBUFFER) != GraphicsContext3D::FRAMEBUFFER_COMPLETE) {\n ok = false;\n break;\n }\n context->framebufferTexture2D(GraphicsContext3D::FRAMEBUFFER, GraphicsContext3D::DEPTH_ATTACHMENT, GraphicsContext3D::TEXTURE_2D, 0, 0);\n }\n if (supportsDepthStencil) {\n context->framebufferTexture2D(GraphicsContext3D::FRAMEBUFFER, GraphicsContext3D::DEPTH_ATTACHMENT, GraphicsContext3D::TEXTURE_2D, depthStencil, 0);\n context->framebufferTexture2D(GraphicsContext3D::FRAMEBUFFER, GraphicsContext3D::STENCIL_ATTACHMENT, GraphicsContext3D::TEXTURE_2D, depthStencil, 0);\n if (context->checkFramebufferStatus(GraphicsContext3D::FRAMEBUFFER) != GraphicsContext3D::FRAMEBUFFER_COMPLETE) {\n ok = false;\n break;\n }\n context->framebufferTexture2D(GraphicsContext3D::FRAMEBUFFER, GraphicsContext3D::DEPTH_ATTACHMENT, GraphicsContext3D::TEXTURE_2D, 0, 0);\n context->framebufferTexture2D(GraphicsContext3D::FRAMEBUFFER, GraphicsContext3D::STENCIL_ATTACHMENT, GraphicsContext3D::TEXTURE_2D, 0, 0);\n }\n }\n\n webglContext->restoreCurrentFramebuffer();\n context->deleteFramebuffer(fbo);\n webglContext->restoreCurrentTexture2D();\n if (supportsDepth)\n context->deleteTexture(depth);\n if (supportsDepthStencil)\n context->deleteTexture(depthStencil);\n for (size_t i = 0; i < colors.size(); ++i)\n context->deleteTexture(colors[i]);\n return ok;\n}\n\n} \/\/ namespace WebCore\n\n#endif \/\/ ENABLE(WEBGL)\n<|endoftext|>"} {"text":"<commit_before>\/***************************************************************\n *\n * Copyright (C) 1990-2007, Condor Team, Computer Sciences Department,\n * University of Wisconsin-Madison, WI.\n * \n * Licensed under the Apache License, Version 2.0 (the \"License\"); you\n * may not use this file except in compliance with the License. You may\n * obtain a copy of the License at\n * \n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n ***************************************************************\/\n\n\n#include \"classad\/common.h\"\n#include \"classad\/source.h\"\n#include \"classad\/matchClassad.h\"\n\nusing namespace std;\n\nstatic char const *ATTR_UNOPTIMIZED_REQUIREMENTS = \"UnoptimizedRequirements\";\n\nnamespace classad {\n\nMatchClassAd::\nMatchClassAd()\n{\n\tlCtx = rCtx = NULL;\n\tlad = rad = NULL;\n\tladParent = radParent = NULL;\n\tsymmetric_match = NULL;\n\tright_matches_left = NULL;\n\tleft_matches_right = NULL;\n\tInitMatchClassAd( NULL, NULL );\n}\n\n\nMatchClassAd::\nMatchClassAd( ClassAd *adl, ClassAd *adr ) : ClassAd()\n{\n\tlad = rad = lCtx = rCtx = NULL;\n\tladParent = radParent = NULL;\n\tInitMatchClassAd( adl, adr );\n}\n\n\nMatchClassAd::\n~MatchClassAd()\n{\n}\n\n\nMatchClassAd* MatchClassAd::\nMakeMatchClassAd( ClassAd *adl, ClassAd *adr )\n{\n\treturn( new MatchClassAd( adl, adr ) );\n}\n\nbool MatchClassAd::\nInitMatchClassAd( ClassAd *adl, ClassAd *adr )\n{\n\tClassAdParser parser;\n\n\t\t\/\/ clear out old info\n\tClear( );\n\tlad = rad = NULL;\n\tlCtx = rCtx = NULL;\n\n\t\t\/\/ convenience expressions\n\tClassAd *upd;\n\tif( !( upd = parser.ParseClassAd( \n\t\t\t\"[symmetricMatch = RIGHT.requirements && LEFT.requirements ;\"\n\t\t\t\"leftMatchesRight = RIGHT.requirements ;\"\n\t\t\t\"rightMatchesLeft = LEFT.requirements ;\"\n\t\t\t\"leftRankValue = LEFT.rank ;\"\n\t\t\t\"rightRankValue = RIGHT.rank]\" ) ) ) {\n\t\tClear( );\n\t\tlCtx = NULL;\n\t\trCtx = NULL;\n\t\treturn( false );\n\t}\n\tUpdate( *upd );\n\tdelete upd;\n\n\t\t\/\/ In the following, global-scope references to LEFT and RIGHT\n\t\t\/\/ are used to make things slightly more efficient. That means\n\t\t\/\/ that this match ad should not be nested inside other ads.\n\t\t\/\/ Also for effiency, the left and right ads are actually\n\t\t\/\/ inserted as .LEFT and .RIGHT (ie at the top level) but\n\t\t\/\/ their parent scope is set to the lCtx and rCtx ads as\n\t\t\/\/ though they were inserted as lCtx.ad and rCtx.ad. This way,\n\t\t\/\/ the most direct way to reference the ads is through the\n\t\t\/\/ top-level global names .LEFT and .RIGHT.\n\n\t\t\/\/ the left context\n\tif( !( lCtx = parser.ParseClassAd( \n\t\t\t\"[other=.RIGHT;target=.RIGHT;my=.LEFT;ad=.LEFT]\" ) ) ) {\n\t\tClear( );\n\t\tlCtx = NULL;\n\t\trCtx = NULL;\n\t\treturn( false );\n\t}\n\n\t\t\/\/ the right context\n\tif( !( rCtx = parser.ParseClassAd( \n\t\t\t\"[other=.LEFT;target=.LEFT;my=.RIGHT;ad=.RIGHT]\" ) ) ) {\n\t\tdelete lCtx;\n\t\tlCtx = rCtx = NULL;\n\t\treturn( false );\n\t}\n\n\t\/\/ Insert the Ad resolver but also lookup before using b\/c\n\t\/\/ there are no gaurentees not to collide.\n\tInsert( \"lCtx\", lCtx, false );\n\tInsert( \"rCtx\", rCtx, false );\n\n\tsymmetric_match = Lookup(\"symmetricMatch\");\n\tright_matches_left = Lookup(\"rightMatchesLeft\");\n\tleft_matches_right = Lookup(\"leftMatchesRight\");\n\n\tif( !adl ) {\n\t\tadl = new ClassAd();\n\t}\n\tif( !adr ) {\n\t\tadr = new ClassAd();\n\t}\n\tReplaceLeftAd( adl );\n\tReplaceRightAd( adr );\n\n\treturn( true );\n}\n\n\nbool MatchClassAd::\nReplaceLeftAd( ClassAd *ad )\n{\n\tlad = ad;\n\tladParent = ad ? ad->GetParentScope( ) : (ClassAd*)NULL;\n\tif( ad ) {\n\t\tif( !Insert( \"LEFT\", ad, false ) ) {\n\t\t\tlad = NULL;\n\t\t\tladParent = NULL;\n\t\t\tDelete( \"LEFT\" );\n\t\t\treturn false;\n\t\t}\n\t\t\n\t\t\/\/ For the ability to efficiently reference the ad via\n\t\t\/\/ .LEFT, it is inserted in the top match ad, but we want\n\t\t\/\/ its parent scope to be the context ad.\n\t\tlCtx->SetParentScope(this);\n\t\tlad->SetParentScope(lCtx);\n\t} else {\n\t\tDelete( \"LEFT\" );\n\t}\n\treturn true;\n}\n\n\nbool MatchClassAd::\nReplaceRightAd( ClassAd *ad )\n{\n\trad = ad;\n\tradParent = ad ? ad->GetParentScope( ) : (ClassAd*)NULL;\n\tif( ad ) {\n\t\tif( !Insert( \"RIGHT\", ad , false ) ) {\n\t\t\trad = NULL;\n\t\t\tradParent = NULL;\n\t\t\tDelete( \"RIGHT\" );\n\t\t\treturn false;\n\t\t}\n\t\t\n\t\n\t\t\/\/ For the ability to efficiently reference the ad via\n\t\t\/\/ .RIGHT, it is inserted in the top match ad, but we want\n\t\t\/\/ its parent scope to be the context ad.\n\t\trCtx->SetParentScope(this);\n\t\trad->SetParentScope(rCtx);\n\t} else {\n\t\tDelete( \"RIGHT\" );\n\t}\n\treturn true;\n}\n\n\nClassAd *MatchClassAd::\nGetLeftAd()\n{\n\treturn( lad );\n}\n\n\nClassAd *MatchClassAd::\nGetRightAd()\n{\n\treturn( rad );\n}\n\n\nClassAd *MatchClassAd::\nGetLeftContext( )\n{\n\treturn( lCtx );\n}\n\n\nClassAd *MatchClassAd::\nGetRightContext( )\n{\n\treturn( rCtx );\n}\n\n\nClassAd *MatchClassAd::\nRemoveLeftAd( )\n{\n\tClassAd *ad = lad;\n\tRemove( \"LEFT\" );\n\tif( lad ) {\n\t\tlad->SetParentScope( ladParent );\n\t}\n\tladParent = NULL;\n\tlad = NULL;\n\treturn( ad );\n}\n\n\nClassAd *MatchClassAd::\nRemoveRightAd( )\n{\n\tClassAd\t*ad = rad;\n\tRemove( \"RIGHT\" );\n\tif( rad ) {\n\t\trad->SetParentScope( radParent );\n\t}\n\tradParent = NULL;\n\trad = NULL;\n\treturn( ad );\n}\n\nbool MatchClassAd::\nOptimizeRightAdForMatchmaking( ClassAd *ad, std::string *error_msg )\n{\n\treturn MatchClassAd::OptimizeAdForMatchmaking( ad, true, error_msg );\n}\n\nbool MatchClassAd::\nOptimizeLeftAdForMatchmaking( ClassAd *ad, std::string *error_msg )\n{\n\treturn MatchClassAd::OptimizeAdForMatchmaking( ad, false, error_msg );\n}\n\nbool MatchClassAd::\nOptimizeAdForMatchmaking( ClassAd *ad, bool is_right, std::string *error_msg )\n{\n\tif( ad->Lookup(\"my\") ||\n\t\tad->Lookup(\"target\") ||\n\t\tad->Lookup(\"other\") ||\n\t\tad->Lookup(ATTR_UNOPTIMIZED_REQUIREMENTS) )\n\t{\n\t\tif( error_msg ) {\n\t\t\t*error_msg = \"Optimization of matchmaking requirements failed, because ad already contains one of my, target, other, or UnoptimizedRequirements.\";\n\t\t}\n\t\treturn false;\n\t}\n\n\tExprTree *requirements = ad->Lookup(ATTR_REQUIREMENTS);\n\tif( !requirements ) {\n\t\tif( error_msg ) {\n\t\t\t*error_msg = \"No requirements found in ad to be optimized.\";\n\t\t}\n\t\treturn false;\n\t}\n\n\t\t\/\/ insert \"my\" into this ad so that references that use it\n\t\t\/\/ can be flattened\n\tif ( !_useOldClassAdSemantics ) {\n\t\tValue me;\n\t\tExprTree * pLit;\n\t\tme.SetClassAdValue( ad );\n\t\tad->Insert(\"my\",(pLit=Literal::MakeLiteral(me)));\n\t}\n\n\t\t\/\/ insert \"target\" and \"other\" into this ad so references can be\n\t\t\/\/ _partially_ flattened to the more efficient .RIGHT or .LEFT\n\tchar const *other = is_right ? \"LEFT\" : \"RIGHT\";\n\tExprTree *target = AttributeReference::MakeAttributeReference(NULL,other,true);\n\tExprTree *t2 = AttributeReference::MakeAttributeReference(NULL,other,true);\n\t\n\tad->Insert(\"target\",target);\n\tad->Insert(\"other\",t2);\n\n\n\tExprTree *flat_requirements = NULL;\n\tValue flat_val;\n\n\tif( ad->FlattenAndInline(requirements,flat_val,flat_requirements) ) {\n\t\tif( !flat_requirements ) {\n\t\t\t\t\/\/ flattened to a value\n\t\t\tflat_requirements = Literal::MakeLiteral(flat_val);\n\t\t}\n\t\tif( flat_requirements ) {\n\t\t\t\t\/\/ save original requirements\n\t\t\tExprTree *orig_requirements = ad->Remove(ATTR_REQUIREMENTS);\n\t\t\tif( orig_requirements ) {\n\t\t\t\tif( !ad->Insert(ATTR_UNOPTIMIZED_REQUIREMENTS,orig_requirements) )\n\t\t\t\t{\n\t\t\t\t\t\t\/\/ Now we have no requirements. Very bad!\n\t\t\t\t\tif( error_msg ) {\n\t\t\t\t\t\t*error_msg = \"Failed to rename original requirements.\";\n\t\t\t\t\t}\n\t\t\t\t\tdelete orig_requirements;\n\t\t\t\t\tdelete flat_requirements;\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t\t\/\/ insert new flattened requirements\n\t\t\tif( !ad->Insert(ATTR_REQUIREMENTS,flat_requirements) ) {\n\t\t\t\tif( error_msg ) {\n\t\t\t\t\t*error_msg = \"Failed to insert optimized requirements.\";\n\t\t\t\t}\n\t\t\t\tdelete flat_requirements;\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t}\n\n\t\t\/\/ After flatenning, no references should remain to MY or TARGET.\n\t\t\/\/ Even if there are, those can be resolved by the context ads, so\n\t\t\/\/ we don't need to leave these attributes in the ad.\n\tif ( !_useOldClassAdSemantics ) {\n\t\tad->Delete(\"my\");\n\t}\n\tad->Delete(\"other\"); \n\tad->Delete(\"target\");\n\n\treturn true;\n}\n\nbool MatchClassAd::\nUnoptimizeAdForMatchmaking( ClassAd *ad )\n{\n\tExprTree *orig_requirements = ad->Remove(ATTR_UNOPTIMIZED_REQUIREMENTS);\n\tif( orig_requirements ) {\n\t\tif( !ad->Insert(ATTR_REQUIREMENTS,orig_requirements) ) {\n\t\t\treturn false;\n\t\t}\n\t}\n\treturn true;\n}\n\nbool MatchClassAd::\nEvalMatchExpr(ExprTree *match_expr)\n{\n\tValue val;\n\tif( !match_expr ) {\n\t\treturn false;\n\t}\n\n\tif( EvaluateExpr( match_expr, val ) ) {\n\t\tbool result = false;\n\t\tif( val.IsBooleanValueEquiv( result ) ) {\n\t\t\treturn result;\n\t\t}\n\t\tlong long int_result = 0;\n\t\tif( val.IsIntegerValue( int_result ) ) {\n\t\t\treturn int_result != 0;\n\t\t}\n\t}\n\treturn false;\n}\n\nbool MatchClassAd::\nsymmetricMatch()\n{\n\treturn EvalMatchExpr( symmetric_match );\n}\n\nbool MatchClassAd::\nrightMatchesLeft()\n{\n\treturn EvalMatchExpr( right_matches_left );\n}\n\nbool MatchClassAd::\nleftMatchesRight()\n{\n\treturn EvalMatchExpr( left_matches_right );\n}\n\n} \/\/ classad\n<commit_msg>Make Target scoping option in MatchClassAd with old semantics. #5550<commit_after>\/***************************************************************\n *\n * Copyright (C) 1990-2007, Condor Team, Computer Sciences Department,\n * University of Wisconsin-Madison, WI.\n * \n * Licensed under the Apache License, Version 2.0 (the \"License\"); you\n * may not use this file except in compliance with the License. You may\n * obtain a copy of the License at\n * \n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n ***************************************************************\/\n\n\n#include \"classad\/common.h\"\n#include \"classad\/source.h\"\n#include \"classad\/matchClassad.h\"\n\nusing namespace std;\n\nstatic char const *ATTR_UNOPTIMIZED_REQUIREMENTS = \"UnoptimizedRequirements\";\n\nnamespace classad {\n\nMatchClassAd::\nMatchClassAd()\n{\n\tlCtx = rCtx = NULL;\n\tlad = rad = NULL;\n\tladParent = radParent = NULL;\n\tsymmetric_match = NULL;\n\tright_matches_left = NULL;\n\tleft_matches_right = NULL;\n\tInitMatchClassAd( NULL, NULL );\n}\n\n\nMatchClassAd::\nMatchClassAd( ClassAd *adl, ClassAd *adr ) : ClassAd()\n{\n\tlad = rad = lCtx = rCtx = NULL;\n\tladParent = radParent = NULL;\n\tInitMatchClassAd( adl, adr );\n}\n\n\nMatchClassAd::\n~MatchClassAd()\n{\n}\n\n\nMatchClassAd* MatchClassAd::\nMakeMatchClassAd( ClassAd *adl, ClassAd *adr )\n{\n\treturn( new MatchClassAd( adl, adr ) );\n}\n\nbool MatchClassAd::\nInitMatchClassAd( ClassAd *adl, ClassAd *adr )\n{\n\tClassAdParser parser;\n\n\t\t\/\/ clear out old info\n\tClear( );\n\tlad = rad = NULL;\n\tlCtx = rCtx = NULL;\n\n\t\t\/\/ convenience expressions\n\tClassAd *upd;\n\tif( !( upd = parser.ParseClassAd( \n\t\t\t\"[symmetricMatch = RIGHT.requirements && LEFT.requirements ;\"\n\t\t\t\"leftMatchesRight = RIGHT.requirements ;\"\n\t\t\t\"rightMatchesLeft = LEFT.requirements ;\"\n\t\t\t\"leftRankValue = LEFT.rank ;\"\n\t\t\t\"rightRankValue = RIGHT.rank]\" ) ) ) {\n\t\tClear( );\n\t\tlCtx = NULL;\n\t\trCtx = NULL;\n\t\treturn( false );\n\t}\n\tUpdate( *upd );\n\tdelete upd;\n\n\t\t\/\/ In the following, global-scope references to LEFT and RIGHT\n\t\t\/\/ are used to make things slightly more efficient. That means\n\t\t\/\/ that this match ad should not be nested inside other ads.\n\t\t\/\/ Also for effiency, the left and right ads are actually\n\t\t\/\/ inserted as .LEFT and .RIGHT (ie at the top level) but\n\t\t\/\/ their parent scope is set to the lCtx and rCtx ads as\n\t\t\/\/ though they were inserted as lCtx.ad and rCtx.ad. This way,\n\t\t\/\/ the most direct way to reference the ads is through the\n\t\t\/\/ top-level global names .LEFT and .RIGHT.\n\n\t\t\/\/ the left context\n\tif( !( lCtx = parser.ParseClassAd( \n\t\t\t\"[other=.RIGHT;target=.RIGHT;my=.LEFT;ad=.LEFT]\" ) ) ) {\n\t\tClear( );\n\t\tlCtx = NULL;\n\t\trCtx = NULL;\n\t\treturn( false );\n\t}\n\n\t\t\/\/ the right context\n\tif( !( rCtx = parser.ParseClassAd( \n\t\t\t\"[other=.LEFT;target=.LEFT;my=.RIGHT;ad=.RIGHT]\" ) ) ) {\n\t\tdelete lCtx;\n\t\tlCtx = rCtx = NULL;\n\t\treturn( false );\n\t}\n\n\t\/\/ Insert the Ad resolver but also lookup before using b\/c\n\t\/\/ there are no gaurentees not to collide.\n\tInsert( \"lCtx\", lCtx, false );\n\tInsert( \"rCtx\", rCtx, false );\n\n\tsymmetric_match = Lookup(\"symmetricMatch\");\n\tright_matches_left = Lookup(\"rightMatchesLeft\");\n\tleft_matches_right = Lookup(\"leftMatchesRight\");\n\n\tif( !adl ) {\n\t\tadl = new ClassAd();\n\t}\n\tif( !adr ) {\n\t\tadr = new ClassAd();\n\t}\n\tReplaceLeftAd( adl );\n\tReplaceRightAd( adr );\n\n\treturn( true );\n}\n\n\nbool MatchClassAd::\nReplaceLeftAd( ClassAd *ad )\n{\n\tlad = ad;\n\tladParent = ad ? ad->GetParentScope( ) : (ClassAd*)NULL;\n\tif( ad ) {\n\t\tif( !Insert( \"LEFT\", ad, false ) ) {\n\t\t\tlad = NULL;\n\t\t\tladParent = NULL;\n\t\t\tDelete( \"LEFT\" );\n\t\t\treturn false;\n\t\t}\n\t\t\n\t\t\/\/ For the ability to efficiently reference the ad via\n\t\t\/\/ .LEFT, it is inserted in the top match ad, but we want\n\t\t\/\/ its parent scope to be the context ad.\n\t\tlCtx->SetParentScope(this);\n\t\tlad->SetParentScope(lCtx);\n\n\t\tif ( _useOldClassAdSemantics ) {\n\t\t\tlad->alternateScope = rad;\n\t\t}\n\t} else {\n\t\tDelete( \"LEFT\" );\n\t}\n\tif ( rad && _useOldClassAdSemantics ) {\n\t\trad->alternateScope = lad;\n\t}\n\treturn true;\n}\n\n\nbool MatchClassAd::\nReplaceRightAd( ClassAd *ad )\n{\n\trad = ad;\n\tradParent = ad ? ad->GetParentScope( ) : (ClassAd*)NULL;\n\tif( ad ) {\n\t\tif( !Insert( \"RIGHT\", ad , false ) ) {\n\t\t\trad = NULL;\n\t\t\tradParent = NULL;\n\t\t\tDelete( \"RIGHT\" );\n\t\t\treturn false;\n\t\t}\n\t\t\n\t\n\t\t\/\/ For the ability to efficiently reference the ad via\n\t\t\/\/ .RIGHT, it is inserted in the top match ad, but we want\n\t\t\/\/ its parent scope to be the context ad.\n\t\trCtx->SetParentScope(this);\n\t\trad->SetParentScope(rCtx);\n\n\t\tif ( _useOldClassAdSemantics ) {\n\t\t\trad->alternateScope = lad;\n\t\t}\n\t} else {\n\t\tDelete( \"RIGHT\" );\n\t}\n\tif ( lad && _useOldClassAdSemantics ) {\n\t\tlad->alternateScope = rad;\n\t}\n\treturn true;\n}\n\n\nClassAd *MatchClassAd::\nGetLeftAd()\n{\n\treturn( lad );\n}\n\n\nClassAd *MatchClassAd::\nGetRightAd()\n{\n\treturn( rad );\n}\n\n\nClassAd *MatchClassAd::\nGetLeftContext( )\n{\n\treturn( lCtx );\n}\n\n\nClassAd *MatchClassAd::\nGetRightContext( )\n{\n\treturn( rCtx );\n}\n\n\nClassAd *MatchClassAd::\nRemoveLeftAd( )\n{\n\tClassAd *ad = lad;\n\tRemove( \"LEFT\" );\n\tif( lad ) {\n\t\tlad->SetParentScope( ladParent );\n\t\tif ( _useOldClassAdSemantics && rad ) {\n\t\t\tlad->alternateScope = NULL;\n\t\t\trad->alternateScope = NULL;\n\t\t}\n\t}\n\tladParent = NULL;\n\tlad = NULL;\n\treturn( ad );\n}\n\n\nClassAd *MatchClassAd::\nRemoveRightAd( )\n{\n\tClassAd\t*ad = rad;\n\tRemove( \"RIGHT\" );\n\tif( rad ) {\n\t\trad->SetParentScope( radParent );\n\t\tif ( _useOldClassAdSemantics && lad ) {\n\t\t\tlad->alternateScope = NULL;\n\t\t\trad->alternateScope = NULL;\n\t\t}\n\t}\n\tradParent = NULL;\n\trad = NULL;\n\treturn( ad );\n}\n\nbool MatchClassAd::\nOptimizeRightAdForMatchmaking( ClassAd *ad, std::string *error_msg )\n{\n\treturn MatchClassAd::OptimizeAdForMatchmaking( ad, true, error_msg );\n}\n\nbool MatchClassAd::\nOptimizeLeftAdForMatchmaking( ClassAd *ad, std::string *error_msg )\n{\n\treturn MatchClassAd::OptimizeAdForMatchmaking( ad, false, error_msg );\n}\n\nbool MatchClassAd::\nOptimizeAdForMatchmaking( ClassAd *ad, bool is_right, std::string *error_msg )\n{\n\tif( ad->Lookup(\"my\") ||\n\t\tad->Lookup(\"target\") ||\n\t\tad->Lookup(\"other\") ||\n\t\tad->Lookup(ATTR_UNOPTIMIZED_REQUIREMENTS) )\n\t{\n\t\tif( error_msg ) {\n\t\t\t*error_msg = \"Optimization of matchmaking requirements failed, because ad already contains one of my, target, other, or UnoptimizedRequirements.\";\n\t\t}\n\t\treturn false;\n\t}\n\n\tExprTree *requirements = ad->Lookup(ATTR_REQUIREMENTS);\n\tif( !requirements ) {\n\t\tif( error_msg ) {\n\t\t\t*error_msg = \"No requirements found in ad to be optimized.\";\n\t\t}\n\t\treturn false;\n\t}\n\n\t\t\/\/ insert \"my\" into this ad so that references that use it\n\t\t\/\/ can be flattened\n\tif ( !_useOldClassAdSemantics ) {\n\t\tValue me;\n\t\tExprTree * pLit;\n\t\tme.SetClassAdValue( ad );\n\t\tad->Insert(\"my\",(pLit=Literal::MakeLiteral(me)));\n\t}\n\n\t\t\/\/ insert \"target\" and \"other\" into this ad so references can be\n\t\t\/\/ _partially_ flattened to the more efficient .RIGHT or .LEFT\n\tchar const *other = is_right ? \"LEFT\" : \"RIGHT\";\n\tExprTree *target = AttributeReference::MakeAttributeReference(NULL,other,true);\n\tExprTree *t2 = AttributeReference::MakeAttributeReference(NULL,other,true);\n\t\n\tad->Insert(\"target\",target);\n\tad->Insert(\"other\",t2);\n\n\n\tExprTree *flat_requirements = NULL;\n\tValue flat_val;\n\n\tif( ad->FlattenAndInline(requirements,flat_val,flat_requirements) ) {\n\t\tif( !flat_requirements ) {\n\t\t\t\t\/\/ flattened to a value\n\t\t\tflat_requirements = Literal::MakeLiteral(flat_val);\n\t\t}\n\t\tif( flat_requirements ) {\n\t\t\t\t\/\/ save original requirements\n\t\t\tExprTree *orig_requirements = ad->Remove(ATTR_REQUIREMENTS);\n\t\t\tif( orig_requirements ) {\n\t\t\t\tif( !ad->Insert(ATTR_UNOPTIMIZED_REQUIREMENTS,orig_requirements) )\n\t\t\t\t{\n\t\t\t\t\t\t\/\/ Now we have no requirements. Very bad!\n\t\t\t\t\tif( error_msg ) {\n\t\t\t\t\t\t*error_msg = \"Failed to rename original requirements.\";\n\t\t\t\t\t}\n\t\t\t\t\tdelete orig_requirements;\n\t\t\t\t\tdelete flat_requirements;\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t\t\/\/ insert new flattened requirements\n\t\t\tif( !ad->Insert(ATTR_REQUIREMENTS,flat_requirements) ) {\n\t\t\t\tif( error_msg ) {\n\t\t\t\t\t*error_msg = \"Failed to insert optimized requirements.\";\n\t\t\t\t}\n\t\t\t\tdelete flat_requirements;\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t}\n\n\t\t\/\/ After flatenning, no references should remain to MY or TARGET.\n\t\t\/\/ Even if there are, those can be resolved by the context ads, so\n\t\t\/\/ we don't need to leave these attributes in the ad.\n\tif ( !_useOldClassAdSemantics ) {\n\t\tad->Delete(\"my\");\n\t}\n\tad->Delete(\"other\"); \n\tad->Delete(\"target\");\n\n\treturn true;\n}\n\nbool MatchClassAd::\nUnoptimizeAdForMatchmaking( ClassAd *ad )\n{\n\tExprTree *orig_requirements = ad->Remove(ATTR_UNOPTIMIZED_REQUIREMENTS);\n\tif( orig_requirements ) {\n\t\tif( !ad->Insert(ATTR_REQUIREMENTS,orig_requirements) ) {\n\t\t\treturn false;\n\t\t}\n\t}\n\treturn true;\n}\n\nbool MatchClassAd::\nEvalMatchExpr(ExprTree *match_expr)\n{\n\tValue val;\n\tif( !match_expr ) {\n\t\treturn false;\n\t}\n\n\tif( EvaluateExpr( match_expr, val ) ) {\n\t\tbool result = false;\n\t\tif( val.IsBooleanValueEquiv( result ) ) {\n\t\t\treturn result;\n\t\t}\n\t\tlong long int_result = 0;\n\t\tif( val.IsIntegerValue( int_result ) ) {\n\t\t\treturn int_result != 0;\n\t\t}\n\t}\n\treturn false;\n}\n\nbool MatchClassAd::\nsymmetricMatch()\n{\n\treturn EvalMatchExpr( symmetric_match );\n}\n\nbool MatchClassAd::\nrightMatchesLeft()\n{\n\treturn EvalMatchExpr( right_matches_left );\n}\n\nbool MatchClassAd::\nleftMatchesRight()\n{\n\treturn EvalMatchExpr( left_matches_right );\n}\n\n} \/\/ classad\n<|endoftext|>"} {"text":"<commit_before>#include \"ship_instance.h\"\n\nShipCarrier::ShipCarrier(int id, std::vector<float> d) : Ship(id, 1000, 400, d, 9.5, 100, .5, .5) {}\nShipScout::ShipScout(int id, std::vector<float> d) : Ship(id, 200, 100, d, .2, 500, 1, 1) {}\nShipFighter::ShipFighter(int id, std::vector<float> d) : Ship(id, 400, 200, d, .4, 200, 5, 5) {}\n<commit_msg>Changed presets<commit_after>#include \"ship_instance.h\"\n\nShipCarrier::ShipCarrier(int id, std::vector<float> d) : Ship(id, 1000, 400, d, 9.5, 100, .5, .5) {}\nShipScout::ShipScout(int id, std::vector<float> d) : Ship(id, 200, 100, d, .2, 500, .5, .5) {}\nShipFighter::ShipFighter(int id, std::vector<float> d) : Ship(id, 400, 200, d, .4, 200, .5, .5) {}\n<|endoftext|>"} {"text":"<commit_before>#ifndef MJOLNIR_READ_OBSERVER_HPP\n#define MJOLNIR_READ_OBSERVER_HPP\n#include <extlib\/toml\/toml.hpp>\n#include <mjolnir\/core\/ObserverContainer.hpp>\n#include <mjolnir\/core\/EnergyObserver.hpp>\n#include <mjolnir\/core\/XYZObserver.hpp>\n#include <mjolnir\/core\/DCDObserver.hpp>\n#include <mjolnir\/util\/logger.hpp>\n#include <mjolnir\/util\/make_unique.hpp>\n\nnamespace mjolnir\n{\n\ntemplate<typename traitsT>\nObserverContainer<traitsT>\nread_observer(const toml::table& root)\n{\n MJOLNIR_GET_DEFAULT_LOGGER();\n MJOLNIR_LOG_FUNCTION();\n\n const auto& files = toml::find<toml::value>(root, \"files\");\n const auto& output = toml::find<toml::value>(files, \"output\");\n\n const auto progress_bar_enabled = toml::expect<bool>(output, \"progress_bar\")\n .unwrap_or(true);\n\n std::string output_path(\".\/\");\n if(toml::get<toml::table>(output).count(\"path\") == 1)\n {\n output_path = toml::find<std::string>(output, \"path\");\n if(output_path.back() != '\/') {output_path += '\/';}\n }\n const auto output_prefix = toml::find<std::string>(output, \"prefix\");\n MJOLNIR_LOG_NOTICE(\"output files are `\", output_path, output_prefix, \".*`\");\n\n const std::string file_prefix = output_path + output_prefix;\n\n ObserverContainer<traitsT> observers(progress_bar_enabled);\n\n \/\/ Energy is always written to \"prefix.ene\".\n observers.push_back(make_unique<EnergyObserver<traitsT>>(file_prefix));\n\n const auto& format = toml::find<std::string>(output, \"format\");\n if(format == \"xyz\")\n {\n using observer_type = XYZObserver<traitsT>;\n MJOLNIR_LOG_NOTICE(\"output format is xyz.\");\n observers.push_back(make_unique<observer_type>(file_prefix));\n return observers;\n }\n if(format == \"dcd\")\n {\n using observer_type = DCDObserver<traitsT>;\n MJOLNIR_LOG_NOTICE(\"output format is dcd.\");\n observers.push_back(make_unique<observer_type>(file_prefix));\n return observers;\n }\n else\n {\n throw_exception<std::runtime_error>(toml::format_error(\"[error] \"\n \"mjolnir::read_observer: output format not supported\",\n toml::find(output, \"format\"), \"here\", {\n \"expected one of the following.\",\n \"- \\\"xyz\\\": the simplest ascii format\",\n \"- \\\"dcd\\\": widely used DCD format\"\n }));\n }\n}\n\n} \/\/ mjolnir\n#endif\/\/ MJOLNIR_READ_OBSERVER_HPP\n<commit_msg>feat: allow array for `files.output.format`<commit_after>#ifndef MJOLNIR_READ_OBSERVER_HPP\n#define MJOLNIR_READ_OBSERVER_HPP\n#include <extlib\/toml\/toml.hpp>\n#include <mjolnir\/core\/ObserverContainer.hpp>\n#include <mjolnir\/core\/EnergyObserver.hpp>\n#include <mjolnir\/core\/XYZObserver.hpp>\n#include <mjolnir\/core\/DCDObserver.hpp>\n#include <mjolnir\/util\/logger.hpp>\n#include <mjolnir\/util\/make_unique.hpp>\n\nnamespace mjolnir\n{\n\ntemplate<typename traitsT>\nvoid add_observer(ObserverContainer<traitsT>& observers,\n const toml::value& format, const std::string& file_prefix)\n{\n MJOLNIR_GET_DEFAULT_LOGGER();\n MJOLNIR_LOG_FUNCTION();\n\n \/\/ To show the informative error message, here it uses toml::value that\n \/\/ contains file location. But this function assumes that the `format`\n \/\/ contains `toml::string`.\n assert(format.is(toml::value_t::String));\n\n if(format == \"xyz\")\n {\n using observer_type = XYZObserver<traitsT>;\n MJOLNIR_LOG_NOTICE(\"output xyz format.\");\n observers.push_back(make_unique<observer_type>(file_prefix));\n return;\n }\n if(format == \"dcd\")\n {\n using observer_type = DCDObserver<traitsT>;\n MJOLNIR_LOG_NOTICE(\"output dcd format.\");\n observers.push_back(make_unique<observer_type>(file_prefix));\n return;\n }\n else\n {\n throw_exception<std::runtime_error>(toml::format_error(\"[error] \"\n \"mjolnir::read_observer: output format not supported\", format,\n \"here\", {\n \"expected one of the following.\",\n \"- \\\"xyz\\\": the simplest ascii format\",\n \"- \\\"dcd\\\": widely used binary format\"\n }));\n }\n return ;\n}\n\n\ntemplate<typename traitsT>\nObserverContainer<traitsT>\nread_observer(const toml::table& root)\n{\n MJOLNIR_GET_DEFAULT_LOGGER();\n MJOLNIR_LOG_FUNCTION();\n\n const auto& files = toml::find<toml::value>(root, \"files\");\n const auto& output = toml::find<toml::value>(files, \"output\");\n\n const auto progress_bar_enabled = toml::expect<bool>(output, \"progress_bar\")\n .unwrap_or(true);\n std::string output_path(\".\/\");\n if(toml::get<toml::table>(output).count(\"path\") == 1)\n {\n output_path = toml::find<std::string>(output, \"path\");\n if(output_path.back() != '\/') {output_path += '\/';}\n }\n const auto output_prefix = toml::find<std::string>(output, \"prefix\");\n MJOLNIR_LOG_NOTICE(\"output file prefix is `\", output_path, output_prefix, '`');\n\n const std::string file_prefix = output_path + output_prefix;\n\n \/\/ ------------------------------------------------------------------------\n\n ObserverContainer<traitsT> observers(progress_bar_enabled);\n\n \/\/ Energy is always written to \"prefix.ene\".\n observers.push_back(make_unique<EnergyObserver<traitsT>>(file_prefix));\n\n const auto& format = toml::find(output, \"format\");\n\n if(format.is(toml::value_t::String))\n {\n add_observer(observers, format, file_prefix);\n }\n else if(format.is(toml::value_t::Array))\n {\n const auto fmts = toml::get<toml::array>(format);\n for(const auto& fmt : fmts)\n {\n add_observer(observers, fmt, file_prefix);\n }\n }\n return observers;\n}\n\n} \/\/ mjolnir\n#endif\/\/ MJOLNIR_READ_OBSERVER_HPP\n<|endoftext|>"} {"text":"<commit_before>\/*\n Copyright (C) 2003 by Frank Richter\n\n This library is free software; you can redistribute it and\/or\n modify it under the terms of the GNU Library General Public\n License as published by the Free Software Foundation; either\n version 2 of the License, or (at your option) any later version.\n\n This library is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n Library General Public License for more details.\n\n You should have received a copy of the GNU Library General Public\n License along with this library; if not, write to the Free\n Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n*\/\n\n#include \"cssysdef.h\"\n#include \"cssys\/sysfunc.h\"\n#include \"cssys\/syspath.h\"\n#include \"csutil\/cstring.h\"\n#include \"csutil\/util.h\"\n#include <string.h>\n\nchar* csGetAppDir (const char* argv0)\n{\n char* appdir = 0;\n char* apppath = csGetAppPath(argv0);\n if (apppath != 0)\n {\n char* slash = strrchr (apppath, PATH_SEPARATOR);\n if (slash != 0)\n *slash = '\\0';\n appdir = csStrNew (apppath);\n delete[] apppath;\n }\n return appdir;\n}\n<commit_msg>Removed '#include \"csutil\/string.h\"', which does not exist from appdir.cpp.<commit_after>\/*\n Copyright (C) 2003 by Frank Richter\n\n This library is free software; you can redistribute it and\/or\n modify it under the terms of the GNU Library General Public\n License as published by the Free Software Foundation; either\n version 2 of the License, or (at your option) any later version.\n\n This library is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n Library General Public License for more details.\n\n You should have received a copy of the GNU Library General Public\n License along with this library; if not, write to the Free\n Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n*\/\n\n#include \"cssysdef.h\"\n#include \"cssys\/sysfunc.h\"\n#include \"cssys\/syspath.h\"\n#include \"csutil\/util.h\"\n#include <string.h>\n\nchar* csGetAppDir (const char* argv0)\n{\n char* appdir = 0;\n char* apppath = csGetAppPath(argv0);\n if (apppath != 0)\n {\n char* slash = strrchr (apppath, PATH_SEPARATOR);\n if (slash != 0)\n *slash = '\\0';\n appdir = csStrNew (apppath);\n delete[] apppath;\n }\n return appdir;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"statistics.h\"\n\nTI_NAMESPACE_BEGIN\n\nStatistics stat;\n\nvoid Statistics::add(std::string key, Statistics::value_type value) {\n counters[key] += value;\n}\n\nvoid Statistics::print(std::string *output) {\n std::vector<std::string> keys;\n for (auto const &item : counters)\n keys.push_back(item.first);\n\n std::sort(keys.begin(), keys.end());\n\n std::stringstream ss;\n for (auto const &k : keys)\n ss << fmt::format(\"{:20}: {:.2f}\\n\", k, counters[k]);\n\n if (output) {\n *output = ss.str();\n } else {\n fmt::print(ss.str());\n }\n}\n\nvoid Statistics::clear() {\n counters.clear();\n}\n\nTI_NAMESPACE_END\n<commit_msg>[misc] Avoid printing empty logs (#848)<commit_after>#include \"statistics.h\"\n\nTI_NAMESPACE_BEGIN\n\nStatistics stat;\n\nvoid Statistics::add(std::string key, Statistics::value_type value) {\n counters[key] += value;\n}\n\nvoid Statistics::print(std::string *output) {\n std::vector<std::string> keys;\n for (auto const &item : counters)\n keys.push_back(item.first);\n\n std::sort(keys.begin(), keys.end());\n\n std::stringstream ss;\n for (auto const &k : keys)\n ss << fmt::format(\"{:20}: {:.2f}\\n\", k, counters[k]);\n\n if (output) {\n *output = ss.str();\n } else {\n fmt::print(ss.str());\n }\n}\n\nvoid Statistics::clear() {\n counters.clear();\n counters[\"codegen_statements\"] = 0;\n counters[\"codegen_offloaded_tasks\"] = 0;\n}\n\nTI_NAMESPACE_END\n<|endoftext|>"} {"text":"<commit_before>#include \"SVM_VirtualMachine.h\"\n#include \"SVM_Opcodes.h\"\n#include \"ShogunVM.h\"\n\n#include <fstream>\n#include <iomanip>\n\nnamespace Shogun\n{\n\tVirtualMachine::VirtualMachine(Memory::MemSize initialMemory)\n\t\t: memory(initialMemory)\n\t{\n\t}\n\n\tVirtualMachine::~VirtualMachine()\n\t{\n\t}\n\n\tMemory& VirtualMachine::getMemory()\n\t{\n\t\treturn this->memory;\n\t}\n\n\tStack& VirtualMachine::getStack()\n\t{\n\t\treturn this->stack;\n\t}\n\n\tVMCallMap& VirtualMachine::getCallMap()\n\t{\n\t\treturn this->callMap;\n\t}\n\n\tvoid VirtualMachine::loadProgram(const Program& program)\n\t{\n\t\tmemory.resize(program.size() + 3);\n\t\tsetRegMmx(program.size() + 2);\n\n\t\tstack.clear();\n\n\t\tUInt32 i = 1;\n\t\tfor (auto it = program.cbegin(); it != program.cend(); ++it)\n\t\t{\n\t\t\tmemory.set(i, *it);\n\t\t\ti++;\n\t\t}\n\n\t\tsetRegPri(1);\n\t}\n\n\tvoid VirtualMachine::importProgram(const Program& program)\n\t{\n\t\tmemory.resize(memory.getSize() + program.size());\n\n\t\tUInt32 i = getRegMmx();\n\t\tsetRegMmx(memory.getSize());\n\n\t\tfor (auto it = program.cbegin(); it != program.cend(); ++it)\n\t\t{\n\t\t\tmemory.set(i, *it);\n\t\t\ti++;\n\t\t}\n\t}\n\n\tvoid VirtualMachine::run()\n\t{\n\t\tthis->running = true;\n\t\twhile (this->running)\n\t\t{\n\t\t\tUInt32 opcode = memory.get(getRegPri())->getAddress();\n\t\t\texecuteOperation(this, (Opcode)opcode);\n\t\t\tthis->setRegPri(this->getRegPri() + 1);\n\t\t}\n\t}\n\n\tvoid VirtualMachine::dump()\n\t{\n\t\tdumpStack(std::cerr);\n\t\t\n\t\tstd::ofstream dump;\n\t\tdump.open(\"shogun.dump\", std::ios::out | std::ios::trunc);\n\t\tif (!dump.is_open()) {\n\t\t\tstd::cerr << \"Unable to open shogun.dump to output dump.\" << std::endl;\n\t\t\treturn;\n\t\t}\n\n\t\tdumpStack(dump);\n\t\tdumpHeap(dump);\n\n\t\tstd::cerr << \"Full dump at shogun.dump\" << std::endl;\n\t}\n\n\tvoid VirtualMachine::dumpStack(std::ostream& stream)\n\t{\n\t\tauto t = std::time(nullptr);\n\t\tauto tm = *std::localtime(&t);\n\n\t\tstream << \"ShogunVM version \" << Shogun::version_string() << \"-\" << Shogun::version() << std::endl;\n\t\tstream << \"dump time - \" << std::put_time(&tm, \"%Y-%m-%d %H-%M-%S\") << std::endl;\n\t\tstream << \"----------\" << std::endl;\n\t\tstream << \"Registers:\" << std::endl;\n\t\tstream << \" PRI = \" << this->getRegPri() << std::endl;\n\t\tstream << \" MMX = \" << this->getRegMmx() << std::endl;\n\t\tstream << \"----------\" << std::endl;\n\t\tstream << \"Stack:\" << std::endl;\n\n\t\tfor (Stack::iterator it = stack.begin(); it != stack.end(); ++it)\n\t\t{\n\t\t\tstream << \"> \" << (*it)->getReadableString() << std::endl;\n\t\t}\n\n\t\tstream << \"----------\" << std::endl;\n\t\tstream << \"- end of stack dump\" << std::endl;\n\t}\n\n\tvoid VirtualMachine::dumpHeap(std::ostream& stream)\n\t{\n\t\tauto t = std::time(nullptr);\n\t\tauto tm = *std::localtime(&t);\n\n\t\tstream << \"ShogunVM version \" << Shogun::version_string() << \"-\" << Shogun::version() << std::endl;\n\t\tstream << \"dump time - \" << std::put_time(&tm, \"%Y-%m-%d %H-%M-%S\") << std::endl;\n\t\tstream << \"----------\" << std::endl;\n\t\tstream << \"Registers:\" << std::endl;\n\t\tstream << \" PRI = \" << this->getRegPri() << std::endl;\n\t\tstream << \" MMX = \" << this->getRegMmx() << std::endl;\n\t\tstream << \"----------\" << std::endl;\n\t\tstream << \"Heap:\" << std::endl;\n\n\t\tfor (Memory::MemSize i = 0; i < memory.getSize(); ++i)\n\t\t{\n\t\t\tstream << \"[\" << i << \"] \" << memory.get(i)->getReadableString() << std::endl;\n\t\t}\n\n\t\tstream << \"- end of heap dump\" << std::endl;\n\t}\n}<commit_msg>show pri and mmx in heap dump<commit_after>#include \"SVM_VirtualMachine.h\"\n#include \"SVM_Opcodes.h\"\n#include \"ShogunVM.h\"\n\n#include <fstream>\n#include <iomanip>\n\nnamespace Shogun\n{\n\tVirtualMachine::VirtualMachine(Memory::MemSize initialMemory)\n\t\t: memory(initialMemory)\n\t{\n\t}\n\n\tVirtualMachine::~VirtualMachine()\n\t{\n\t}\n\n\tMemory& VirtualMachine::getMemory()\n\t{\n\t\treturn this->memory;\n\t}\n\n\tStack& VirtualMachine::getStack()\n\t{\n\t\treturn this->stack;\n\t}\n\n\tVMCallMap& VirtualMachine::getCallMap()\n\t{\n\t\treturn this->callMap;\n\t}\n\n\tvoid VirtualMachine::loadProgram(const Program& program)\n\t{\n\t\tmemory.resize(program.size() + 3);\n\t\tsetRegMmx(program.size() + 2);\n\n\t\tstack.clear();\n\n\t\tUInt32 i = 1;\n\t\tfor (auto it = program.cbegin(); it != program.cend(); ++it)\n\t\t{\n\t\t\tmemory.set(i, *it);\n\t\t\ti++;\n\t\t}\n\n\t\tsetRegPri(1);\n\t}\n\n\tvoid VirtualMachine::importProgram(const Program& program)\n\t{\n\t\tmemory.resize(memory.getSize() + program.size());\n\n\t\tUInt32 i = getRegMmx();\n\t\tsetRegMmx(memory.getSize());\n\n\t\tfor (auto it = program.cbegin(); it != program.cend(); ++it)\n\t\t{\n\t\t\tmemory.set(i, *it);\n\t\t\ti++;\n\t\t}\n\t}\n\n\tvoid VirtualMachine::run()\n\t{\n\t\tthis->running = true;\n\t\twhile (this->running)\n\t\t{\n\t\t\tUInt32 opcode = memory.get(getRegPri())->getAddress();\n\t\t\texecuteOperation(this, (Opcode)opcode);\n\t\t\tthis->setRegPri(this->getRegPri() + 1);\n\t\t}\n\t}\n\n\tvoid VirtualMachine::dump()\n\t{\n\t\tdumpStack(std::cerr);\n\t\t\n\t\tstd::ofstream dump;\n\t\tdump.open(\"shogun.dump\", std::ios::out | std::ios::trunc);\n\t\tif (!dump.is_open()) {\n\t\t\tstd::cerr << \"Unable to open shogun.dump to output dump.\" << std::endl;\n\t\t\treturn;\n\t\t}\n\n\t\tdumpStack(dump);\n\t\tdumpHeap(dump);\n\n\t\tstd::cerr << \"Full dump at shogun.dump\" << std::endl;\n\t}\n\n\tvoid VirtualMachine::dumpStack(std::ostream& stream)\n\t{\n\t\tauto t = std::time(nullptr);\n\t\tauto tm = *std::localtime(&t);\n\n\t\tstream << \"ShogunVM version \" << Shogun::version_string() << \"-\" << Shogun::version() << std::endl;\n\t\tstream << \"dump time - \" << std::put_time(&tm, \"%Y-%m-%d %H-%M-%S\") << std::endl;\n\t\tstream << \"----------\" << std::endl;\n\t\tstream << \"Registers:\" << std::endl;\n\t\tstream << \" PRI = \" << this->getRegPri() << std::endl;\n\t\tstream << \" MMX = \" << this->getRegMmx() << std::endl;\n\t\tstream << \"----------\" << std::endl;\n\t\tstream << \"Stack:\" << std::endl;\n\n\t\tfor (Stack::iterator it = stack.begin(); it != stack.end(); ++it)\n\t\t{\n\t\t\tstream << \"> \" << (*it)->getReadableString() << std::endl;\n\t\t}\n\n\t\tstream << \"----------\" << std::endl;\n\t\tstream << \"- end of stack dump\" << std::endl;\n\t}\n\n\tvoid VirtualMachine::dumpHeap(std::ostream& stream)\n\t{\n\t\tauto t = std::time(nullptr);\n\t\tauto tm = *std::localtime(&t);\n\n\t\tstream << \"ShogunVM version \" << Shogun::version_string() << \"-\" << Shogun::version() << std::endl;\n\t\tstream << \"dump time - \" << std::put_time(&tm, \"%Y-%m-%d %H-%M-%S\") << std::endl;\n\t\tstream << \"----------\" << std::endl;\n\t\tstream << \"Registers:\" << std::endl;\n\t\tstream << \" PRI = \" << this->getRegPri() << std::endl;\n\t\tstream << \" MMX = \" << this->getRegMmx() << std::endl;\n\t\tstream << \"----------\" << std::endl;\n\t\tstream << \"Heap:\" << std::endl;\n\n\t\tfor (Memory::MemSize i = 0; i < memory.getSize(); ++i)\n\t\t{\n\t\t\tstream << \"[\" << i << \"] \" << memory.get(i)->getReadableString();\n\t\t\tif (i == this->getRegPri())\n\t\t\t{\n\t\t\t\tstream << \" !PRI!\";\n\t\t\t}\n\t\t\t\n\t\t\tif (i == this->getRegMmx())\n\t\t\t{\n\t\t\t\tstream << \" !MMX!\";\n\t\t\t}\n\n\t\t\tstream << std::endl;\n\t\t}\n\n\t\tstream << \"- end of heap dump\" << std::endl;\n\t}\n}<|endoftext|>"} {"text":"<commit_before>\/**\n * @file SocketAddress.hpp\n * @brief SocketAddress class prototype.\n * @author zer0\n * @date 2017-06-18\n * @date 2019-01-19 (Move: libtbag\/network -> libtbag\/net)\n *\/\n\n#ifndef __INCLUDE_LIBTBAG__LIBTBAG_NETWORK_SOCKETADDRESS_HPP__\n#define __INCLUDE_LIBTBAG__LIBTBAG_NETWORK_SOCKETADDRESS_HPP__\n\n\/\/ MS compatible compilers support #pragma once\n#if defined(_MSC_VER) && (_MSC_VER >= 1020)\n#pragma once\n#endif\n\n#include <libtbag\/config.h>\n#include <libtbag\/predef.hpp>\n#include <libtbag\/Err.hpp>\n#include <libtbag\/net\/Uri.hpp>\n\n#include <string>\n\n#if defined(TBAG_PLATFORM_WINDOWS)\n# include <winsock2.h>\n# include <WS2tcpip.h> \/\/ sockaddr_in6, addrinfo\n# include <Windows.h>\n#else\n# include <netinet\/in.h>\n# include <netdb.h> \/\/ addrinfo\n#endif\n\n\/\/ -------------------\nNAMESPACE_LIBTBAG_OPEN\n\/\/ -------------------\n\nnamespace net {\n\n\/**\n * SocketAddress class prototype.\n *\n * @author zer0\n * @date 2017-06-18\n * @date 2019-01-19 (Move: libtbag\/network -> libtbag\/net)\n *\/\nclass TBAG_API SocketAddress\n{\nprivate:\n union {\n sockaddr common;\n sockaddr_in ipv4;\n sockaddr_in6 ipv6;\n } _addr;\n\npublic:\n SocketAddress();\n explicit SocketAddress(struct sockaddr const * addr);\n explicit SocketAddress(struct sockaddr_in const * addr);\n explicit SocketAddress(struct sockaddr_in6 const * addr);\n SocketAddress(SocketAddress const & obj);\n SocketAddress(SocketAddress && obj) TBAG_NOEXCEPT;\n virtual ~SocketAddress();\n\npublic:\n SocketAddress & operator =(SocketAddress const & obj);\n SocketAddress & operator =(SocketAddress && obj) TBAG_NOEXCEPT;\n\npublic:\n Err init(struct sockaddr const * addr);\n Err init(struct sockaddr_in const * addr);\n Err init(struct sockaddr_in6 const * addr);\n\npublic:\n Err initIpv4(std::string const & ip, int port = 0);\n Err initIpv6(std::string const & ip, int port = 0);\n Err initName(std::string const & host, std::string const & service = \"\", int port = 0);\n\npublic:\n Err init(std::string const & host, int port);\n Err init(Uri const & uri);\n\npublic:\n inline struct sockaddr const * getCommon() const TBAG_NOEXCEPT { return &_addr.common; }\n inline struct sockaddr_in const * getIpv4 () const TBAG_NOEXCEPT { return &_addr.ipv4; }\n inline struct sockaddr_in6 const * getIpv6 () const TBAG_NOEXCEPT { return &_addr.ipv6; }\n\n inline bool isIpv4() const TBAG_NOEXCEPT { return _addr.ipv4.sin_port == AF_INET; }\n inline bool isIpv6() const TBAG_NOEXCEPT { return _addr.ipv6.sin6_port == AF_INET6; }\n\npublic:\n std::string getIpName() const;\n int getPortNumber() const;\n};\n\n\/\/ -----------------------\n\/\/ Miscellaneous utilities\n\/\/ -----------------------\n\n\/**\n * Find the network interface that the client IP is connected to and return the hostname of that interface.\n *\n * @param[in] client_ip\n * Client IP address.\n * @param[in] client_ip\n * Flag values for getnameinfo(). (e.g. NI_NUMERICHOST)\n * @param[out] result_host\n * Result host name.\n *\n * @return Result error code.\n *\/\nTBAG_API Err requestHostNameByClientIp(std::string const & client_ip, int flags, std::string & result_host);\nTBAG_API std::string requestHostNameByClientIp(std::string const & client_ip, int flags);\n\n\/**\n * Find the network interface that the client IP is connected to and return the hostname of that interface.\n *\n * Flag value is <code>NI_NUMERICHOST<\/code>.\n *\n * @param[in] client_ip\n * Client IP address.\n *\n * @return Result host name.\n *\/\nTBAG_API std::string requestHostNameByClientIp(std::string const & client_ip);\n\n} \/\/ namespace net\n\n\/\/ --------------------\nNAMESPACE_LIBTBAG_CLOSE\n\/\/ --------------------\n\n#endif \/\/ __INCLUDE_LIBTBAG__LIBTBAG_NETWORK_SOCKETADDRESS_HPP__\n\n<commit_msg>Fixed doxygen warnings.<commit_after>\/**\n * @file SocketAddress.hpp\n * @brief SocketAddress class prototype.\n * @author zer0\n * @date 2017-06-18\n * @date 2019-01-19 (Move: libtbag\/network -> libtbag\/net)\n *\/\n\n#ifndef __INCLUDE_LIBTBAG__LIBTBAG_NETWORK_SOCKETADDRESS_HPP__\n#define __INCLUDE_LIBTBAG__LIBTBAG_NETWORK_SOCKETADDRESS_HPP__\n\n\/\/ MS compatible compilers support #pragma once\n#if defined(_MSC_VER) && (_MSC_VER >= 1020)\n#pragma once\n#endif\n\n#include <libtbag\/config.h>\n#include <libtbag\/predef.hpp>\n#include <libtbag\/Err.hpp>\n#include <libtbag\/net\/Uri.hpp>\n\n#include <string>\n\n#if defined(TBAG_PLATFORM_WINDOWS)\n# include <winsock2.h>\n# include <WS2tcpip.h> \/\/ sockaddr_in6, addrinfo\n# include <Windows.h>\n#else\n# include <netinet\/in.h>\n# include <netdb.h> \/\/ addrinfo\n#endif\n\n\/\/ -------------------\nNAMESPACE_LIBTBAG_OPEN\n\/\/ -------------------\n\nnamespace net {\n\n\/**\n * SocketAddress class prototype.\n *\n * @author zer0\n * @date 2017-06-18\n * @date 2019-01-19 (Move: libtbag\/network -> libtbag\/net)\n *\/\nclass TBAG_API SocketAddress\n{\nprivate:\n union {\n sockaddr common;\n sockaddr_in ipv4;\n sockaddr_in6 ipv6;\n } _addr;\n\npublic:\n SocketAddress();\n explicit SocketAddress(struct sockaddr const * addr);\n explicit SocketAddress(struct sockaddr_in const * addr);\n explicit SocketAddress(struct sockaddr_in6 const * addr);\n SocketAddress(SocketAddress const & obj);\n SocketAddress(SocketAddress && obj) TBAG_NOEXCEPT;\n virtual ~SocketAddress();\n\npublic:\n SocketAddress & operator =(SocketAddress const & obj);\n SocketAddress & operator =(SocketAddress && obj) TBAG_NOEXCEPT;\n\npublic:\n Err init(struct sockaddr const * addr);\n Err init(struct sockaddr_in const * addr);\n Err init(struct sockaddr_in6 const * addr);\n\npublic:\n Err initIpv4(std::string const & ip, int port = 0);\n Err initIpv6(std::string const & ip, int port = 0);\n Err initName(std::string const & host, std::string const & service = \"\", int port = 0);\n\npublic:\n Err init(std::string const & host, int port);\n Err init(Uri const & uri);\n\npublic:\n inline struct sockaddr const * getCommon() const TBAG_NOEXCEPT { return &_addr.common; }\n inline struct sockaddr_in const * getIpv4 () const TBAG_NOEXCEPT { return &_addr.ipv4; }\n inline struct sockaddr_in6 const * getIpv6 () const TBAG_NOEXCEPT { return &_addr.ipv6; }\n\n inline bool isIpv4() const TBAG_NOEXCEPT { return _addr.ipv4.sin_port == AF_INET; }\n inline bool isIpv6() const TBAG_NOEXCEPT { return _addr.ipv6.sin6_port == AF_INET6; }\n\npublic:\n std::string getIpName() const;\n int getPortNumber() const;\n};\n\n\/\/ -----------------------\n\/\/ Miscellaneous utilities\n\/\/ -----------------------\n\n\/**\n * Find the network interface that the client IP is connected to and return the hostname of that interface.\n *\n * @param[in] client_ip\n * Client IP address.\n * @param[in] flags\n * Flag values for getnameinfo(). (e.g. NI_NUMERICHOST)\n * @param[out] result_host\n * Result host name.\n *\n * @return Result error code.\n *\/\nTBAG_API Err requestHostNameByClientIp(std::string const & client_ip, int flags, std::string & result_host);\nTBAG_API std::string requestHostNameByClientIp(std::string const & client_ip, int flags);\n\n\/**\n * Find the network interface that the client IP is connected to and return the hostname of that interface.\n *\n * Flag value is <code>NI_NUMERICHOST<\/code>.\n *\n * @param[in] client_ip\n * Client IP address.\n *\n * @return Result host name.\n *\/\nTBAG_API std::string requestHostNameByClientIp(std::string const & client_ip);\n\n} \/\/ namespace net\n\n\/\/ --------------------\nNAMESPACE_LIBTBAG_CLOSE\n\/\/ --------------------\n\n#endif \/\/ __INCLUDE_LIBTBAG__LIBTBAG_NETWORK_SOCKETADDRESS_HPP__\n\n<|endoftext|>"} {"text":"<commit_before>\/******************************************************************************\n * _ _____ __________ *\n * | | \/ \/ _ | \/ __\/_ __\/ Visibility *\n * | |\/ \/ __ |_\\ \\ \/ \/ Across *\n * |___\/_\/ |_\/___\/ \/_\/ Space and Time *\n * *\n * This file is part of VAST. It is subject to the license terms in the *\n * LICENSE file found in the top-level directory of this distribution and at *\n * http:\/\/vast.io\/license. No part of VAST, including this file, may be *\n * copied, modified, propagated, or distributed except according to the terms *\n * contained in the LICENSE file. *\n ******************************************************************************\/\n\n#define SUITE community_id\n\n#include \"vast\/test\/test.hpp\"\n\n#include \"vast\/community_id.hpp\"\n#include \"vast\/concept\/parseable\/to.hpp\"\n#include \"vast\/concept\/parseable\/vast\/address.hpp\"\n\nusing namespace vast;\nusing namespace community_id;\n\nnamespace {\n\n#define FLOW_FACTORY(protocol) \\\n flow make_##protocol##_flow(std::string_view orig_h, uint16_t orig_p, \\\n std::string_view resp_h, uint16_t resp_p) { \\\n constexpr auto proto = port::port_type::protocol; \\\n auto x = make_flow<proto>(orig_h, orig_p, resp_h, resp_p); \\\n REQUIRE(x); \\\n return *x; \\\n }\n\nFLOW_FACTORY(icmp)\nFLOW_FACTORY(tcp)\nFLOW_FACTORY(udp)\nFLOW_FACTORY(icmp6)\n\n#undef FLOW_FACTORY\n\n} \/\/ namespace\n\n\/\/ Ground truth established with Christian Kreibich's Python module, e.g.:\n\/\/\n\/\/ from communityid import *\n\/\/ commid = CommunityID(seed=0, use_base64=False)\n\/\/ commid.calc(flow)\n\/\/ flow = FlowTuple(PROTO_UDP, \"192.168.1.102\", \"192.168.1.1\", 68, 67)\n\nTEST(UDP IPv4) {\n auto x = make_udp_flow(\"192.168.1.102\", 68, \"192.168.1.1\", 67);\n auto hex = compute<policy::ascii>(x);\n auto b64 = compute<policy::base64>(x);\n CHECK_EQUAL(hex, \"1:69665f2c8aae6250b1286b89eb67d01a5805cc02\");\n CHECK_EQUAL(b64, \"1:aWZfLIquYlCxKGuJ62fQGlgFzAI=\");\n}\n\nTEST(UDP IPv6) {\n auto x = make_udp_flow(\"fe80::2c23:b96c:78d:e116\", 58544, \"ff02::c\", 3702);\n auto hex = compute<policy::ascii>(x);\n auto b64 = compute<policy::base64>(x);\n CHECK_EQUAL(hex, \"1:662f40748c18bd99d8bee39b4cf806582052611b\");\n CHECK_EQUAL(b64, \"1:Zi9AdIwYvZnYvuObTPgGWCBSYRs=\");\n}\n\nTEST(TCP IPv4) {\n auto x = make_tcp_flow(\"192.168.1.102\", 1180, \"68.216.79.113\", 37);\n auto hex = compute<policy::ascii>(x);\n auto b64 = compute<policy::base64>(x);\n CHECK_EQUAL(hex, \"1:f4bfed67579b1f395687307fa49c92f405495b2f\");\n CHECK_EQUAL(b64, \"1:9L\/tZ1ebHzlWhzB\/pJyS9AVJWy8=\");\n}\n\nTEST(TCP IPv6) {\n auto x = make_tcp_flow(\"fe80::219:e3ff:fee7:5d23\", 5353, \"ff02::fb\", 53);\n auto hex = compute<policy::ascii>(x);\n auto b64 = compute<policy::base64>(x);\n CHECK_EQUAL(hex, \"1:03aaaffe2842910257a2fdf52f863395cb8a4769\");\n CHECK_EQUAL(b64, \"1:A6qv\/ihCkQJXov31L4YzlcuKR2k=\");\n}\n\nTEST(ICMPv4) {\n auto x = make_icmp_flow(\"1.2.3.4\", 0, \"5.6.7.8\", 8);\n auto hex = compute<policy::ascii>(x);\n auto b64 = compute<policy::base64>(x);\n CHECK_EQUAL(hex, \"1:d6f36bf9c570edbcd9fad1ac8761fbbe807069a6\");\n CHECK_EQUAL(b64, \"1:1vNr+cVw7bzZ+tGsh2H7voBwaaY=\");\n}\n\nTEST(ICMPv4 oneway) {\n auto x = make_icmp_flow(\"192.168.0.89\", 128, \"192.168.0.1\", 129);\n auto hex = compute<policy::ascii>(x);\n auto b64 = compute<policy::base64>(x);\n CHECK_EQUAL(hex, \"1:86459c1ce1ea4c65aaffe7f01c48a6e5efa0d5f1\");\n CHECK_EQUAL(b64, \"1:hkWcHOHqTGWq\/+fwHEim5e+g1fE=\");\n}\n\nTEST(ICMPv6) {\n auto x = make_icmp6_flow(\"fe80::200:86ff:fe05:80da\", 135, \"fe80::260\", 136);\n auto hex = compute<policy::ascii>(x);\n auto b64 = compute<policy::base64>(x);\n CHECK_EQUAL(hex, \"1:ffb2d8321708804a883ac02fe6c76655499b3ff5\");\n CHECK_EQUAL(b64, \"1:\/7LYMhcIgEqIOsAv5sdmVUmbP\/U=\");\n}\n\nTEST(ICMPv6 oneway) {\n auto x = make_icmp6_flow(\"fe80::dead\", 42, \"fe80::beef\", 84);\n auto hex = compute<policy::ascii>(x);\n auto b64 = compute<policy::base64>(x);\n CHECK_EQUAL(hex, \"1:118a3bbf175529a3d55dca55c4364ec47f1c4152\");\n CHECK_EQUAL(b64, \"1:EYo7vxdVKaPVXcpVxDZOxH8cQVI=\");\n}\n<commit_msg>Simplify flow factory<commit_after>\/******************************************************************************\n * _ _____ __________ *\n * | | \/ \/ _ | \/ __\/_ __\/ Visibility *\n * | |\/ \/ __ |_\\ \\ \/ \/ Across *\n * |___\/_\/ |_\/___\/ \/_\/ Space and Time *\n * *\n * This file is part of VAST. It is subject to the license terms in the *\n * LICENSE file found in the top-level directory of this distribution and at *\n * http:\/\/vast.io\/license. No part of VAST, including this file, may be *\n * copied, modified, propagated, or distributed except according to the terms *\n * contained in the LICENSE file. *\n ******************************************************************************\/\n\n#define SUITE community_id\n\n#include \"vast\/test\/test.hpp\"\n\n#include \"vast\/community_id.hpp\"\n#include \"vast\/concept\/parseable\/to.hpp\"\n#include \"vast\/concept\/parseable\/vast\/address.hpp\"\n\nusing namespace vast;\nusing namespace community_id;\n\nnamespace {\n\n#define FLOW_FACTORY(protocol) \\\n flow make_##protocol##_flow(std::string_view orig_h, uint16_t orig_p, \\\n std::string_view resp_h, uint16_t resp_p) { \\\n constexpr auto proto = port::port_type::protocol; \\\n return unbox(make_flow<proto>(orig_h, orig_p, resp_h, resp_p)); \\\n }\n\nFLOW_FACTORY(icmp)\nFLOW_FACTORY(tcp)\nFLOW_FACTORY(udp)\nFLOW_FACTORY(icmp6)\n\n#undef FLOW_FACTORY\n\n} \/\/ namespace\n\n\/\/ Ground truth established with Christian Kreibich's Python module, e.g.:\n\/\/\n\/\/ from communityid import *\n\/\/ commid = CommunityID(seed=0, use_base64=False)\n\/\/ commid.calc(flow)\n\/\/ flow = FlowTuple(PROTO_UDP, \"192.168.1.102\", \"192.168.1.1\", 68, 67)\n\nTEST(UDP IPv4) {\n auto x = make_udp_flow(\"192.168.1.102\", 68, \"192.168.1.1\", 67);\n auto hex = compute<policy::ascii>(x);\n auto b64 = compute<policy::base64>(x);\n CHECK_EQUAL(hex, \"1:69665f2c8aae6250b1286b89eb67d01a5805cc02\");\n CHECK_EQUAL(b64, \"1:aWZfLIquYlCxKGuJ62fQGlgFzAI=\");\n}\n\nTEST(UDP IPv6) {\n auto x = make_udp_flow(\"fe80::2c23:b96c:78d:e116\", 58544, \"ff02::c\", 3702);\n auto hex = compute<policy::ascii>(x);\n auto b64 = compute<policy::base64>(x);\n CHECK_EQUAL(hex, \"1:662f40748c18bd99d8bee39b4cf806582052611b\");\n CHECK_EQUAL(b64, \"1:Zi9AdIwYvZnYvuObTPgGWCBSYRs=\");\n}\n\nTEST(TCP IPv4) {\n auto x = make_tcp_flow(\"192.168.1.102\", 1180, \"68.216.79.113\", 37);\n auto hex = compute<policy::ascii>(x);\n auto b64 = compute<policy::base64>(x);\n CHECK_EQUAL(hex, \"1:f4bfed67579b1f395687307fa49c92f405495b2f\");\n CHECK_EQUAL(b64, \"1:9L\/tZ1ebHzlWhzB\/pJyS9AVJWy8=\");\n}\n\nTEST(TCP IPv6) {\n auto x = make_tcp_flow(\"fe80::219:e3ff:fee7:5d23\", 5353, \"ff02::fb\", 53);\n auto hex = compute<policy::ascii>(x);\n auto b64 = compute<policy::base64>(x);\n CHECK_EQUAL(hex, \"1:03aaaffe2842910257a2fdf52f863395cb8a4769\");\n CHECK_EQUAL(b64, \"1:A6qv\/ihCkQJXov31L4YzlcuKR2k=\");\n}\n\nTEST(ICMPv4) {\n auto x = make_icmp_flow(\"1.2.3.4\", 0, \"5.6.7.8\", 8);\n auto hex = compute<policy::ascii>(x);\n auto b64 = compute<policy::base64>(x);\n CHECK_EQUAL(hex, \"1:d6f36bf9c570edbcd9fad1ac8761fbbe807069a6\");\n CHECK_EQUAL(b64, \"1:1vNr+cVw7bzZ+tGsh2H7voBwaaY=\");\n}\n\nTEST(ICMPv4 oneway) {\n auto x = make_icmp_flow(\"192.168.0.89\", 128, \"192.168.0.1\", 129);\n auto hex = compute<policy::ascii>(x);\n auto b64 = compute<policy::base64>(x);\n CHECK_EQUAL(hex, \"1:86459c1ce1ea4c65aaffe7f01c48a6e5efa0d5f1\");\n CHECK_EQUAL(b64, \"1:hkWcHOHqTGWq\/+fwHEim5e+g1fE=\");\n}\n\nTEST(ICMPv6) {\n auto x = make_icmp6_flow(\"fe80::200:86ff:fe05:80da\", 135, \"fe80::260\", 136);\n auto hex = compute<policy::ascii>(x);\n auto b64 = compute<policy::base64>(x);\n CHECK_EQUAL(hex, \"1:ffb2d8321708804a883ac02fe6c76655499b3ff5\");\n CHECK_EQUAL(b64, \"1:\/7LYMhcIgEqIOsAv5sdmVUmbP\/U=\");\n}\n\nTEST(ICMPv6 oneway) {\n auto x = make_icmp6_flow(\"fe80::dead\", 42, \"fe80::beef\", 84);\n auto hex = compute<policy::ascii>(x);\n auto b64 = compute<policy::base64>(x);\n CHECK_EQUAL(hex, \"1:118a3bbf175529a3d55dca55c4364ec47f1c4152\");\n CHECK_EQUAL(b64, \"1:EYo7vxdVKaPVXcpVxDZOxH8cQVI=\");\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2009 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/chromeos\/preferences.h\"\n\n#include \"base\/string_util.h\"\n#include \"base\/utf_string_conversions.h\"\n#include \"chrome\/browser\/chromeos\/cros\/cros_library.h\"\n#include \"chrome\/browser\/chromeos\/cros\/language_library.h\"\n#include \"chrome\/browser\/chromeos\/cros\/synaptics_library.h\"\n#include \"chrome\/browser\/chromeos\/language_preferences.h\"\n#include \"chrome\/browser\/pref_member.h\"\n#include \"chrome\/browser\/pref_service.h\"\n#include \"chrome\/common\/notification_service.h\"\n#include \"chrome\/common\/pref_names.h\"\n#include \"unicode\/timezone.h\"\n\nnamespace {\n\n\/\/ Section and config names for the IBus configuration daemon.\nconst char kGeneralSectionName[] = \"general\";\nconst char kHotKeySectionName[] = \"general\/hotkey\";\nconst char kHangulSectionName[] = \"engine\/Hangul\";\n\nconst char kUseGlobalEngineConfigName[] = \"use_global_engine\";\nconst char kNextEngineConfigName[] = \"next_engine\";\nconst char kTriggerConfigName[] = \"trigger\";\nconst char kHangulKeyboardConfigName[] = \"HangulKeyboard\";\n\n} \/\/ namespace\n\nnamespace chromeos {\n\n\/\/ static\nvoid Preferences::RegisterUserPrefs(PrefService* prefs) {\n prefs->RegisterStringPref(prefs::kTimeZone, L\"US\/Pacific\");\n prefs->RegisterBooleanPref(prefs::kTapToClickEnabled, false);\n prefs->RegisterBooleanPref(prefs::kVertEdgeScrollEnabled, false);\n prefs->RegisterIntegerPref(prefs::kTouchpadSpeedFactor, 5);\n prefs->RegisterIntegerPref(prefs::kTouchpadSensitivity, 5);\n prefs->RegisterBooleanPref(prefs::kLanguageUseGlobalEngine, true);\n prefs->RegisterStringPref(prefs::kLanguageHotkeyNextEngine,\n kHotkeyNextEngine);\n prefs->RegisterStringPref(prefs::kLanguageHotkeyTrigger, kHotkeyTrigger);\n prefs->RegisterStringPref(prefs::kLanguagePreloadEngines,\n UTF8ToWide(kFallbackInputMethodId)); \/\/ EN layout\n prefs->RegisterStringPref(prefs::kLanguageHangulKeyboard,\n kHangulKeyboardNameIDPairs[0].keyboard_id);\n}\n\nvoid Preferences::Init(PrefService* prefs) {\n timezone_.Init(prefs::kTimeZone, prefs, this);\n tap_to_click_enabled_.Init(prefs::kTapToClickEnabled, prefs, this);\n vert_edge_scroll_enabled_.Init(prefs::kVertEdgeScrollEnabled, prefs, this);\n speed_factor_.Init(prefs::kTouchpadSpeedFactor, prefs, this);\n sensitivity_.Init(prefs::kTouchpadSensitivity, prefs, this);\n language_use_global_engine_.Init(\n prefs::kLanguageUseGlobalEngine, prefs, this);\n language_hotkey_next_engine_.Init(\n prefs::kLanguageHotkeyNextEngine, prefs, this);\n language_hotkey_trigger_.Init(prefs::kLanguageHotkeyTrigger, prefs, this);\n language_preload_engines_.Init(prefs::kLanguagePreloadEngines, prefs, this);\n language_hangul_keyboard_.Init(prefs::kLanguageHangulKeyboard, prefs, this);\n\n \/\/ Initialize touchpad settings to what's saved in user preferences.\n NotifyPrefChanged(NULL);\n}\n\nvoid Preferences::Observe(NotificationType type,\n const NotificationSource& source,\n const NotificationDetails& details) {\n if (type == NotificationType::PREF_CHANGED)\n NotifyPrefChanged(Details<std::wstring>(details).ptr());\n}\n\nvoid Preferences::NotifyPrefChanged(const std::wstring* pref_name) {\n if (!pref_name || *pref_name == prefs::kTimeZone)\n SetTimeZone(timezone_.GetValue());\n if (!pref_name || *pref_name == prefs::kTapToClickEnabled)\n CrosLibrary::Get()->GetSynapticsLibrary()->SetBoolParameter(\n PARAM_BOOL_TAP_TO_CLICK,\n tap_to_click_enabled_.GetValue());\n if (!pref_name || *pref_name == prefs::kVertEdgeScrollEnabled)\n CrosLibrary::Get()->GetSynapticsLibrary()->SetBoolParameter(\n PARAM_BOOL_VERTICAL_EDGE_SCROLLING,\n vert_edge_scroll_enabled_.GetValue());\n if (!pref_name || *pref_name == prefs::kTouchpadSpeedFactor)\n CrosLibrary::Get()->GetSynapticsLibrary()->SetRangeParameter(\n PARAM_RANGE_SPEED_SENSITIVITY,\n speed_factor_.GetValue());\n if (!pref_name || *pref_name == prefs::kTouchpadSensitivity)\n CrosLibrary::Get()->GetSynapticsLibrary()->SetRangeParameter(\n PARAM_RANGE_TOUCH_SENSITIVITY,\n sensitivity_.GetValue());\n if (!pref_name || *pref_name == prefs::kLanguageUseGlobalEngine)\n SetLanguageConfigBoolean(kGeneralSectionName, kUseGlobalEngineConfigName,\n language_use_global_engine_.GetValue());\n if (!pref_name || *pref_name == prefs::kLanguageHotkeyNextEngine)\n SetHotkeys(kNextEngineConfigName, language_hotkey_next_engine_.GetValue());\n if (!pref_name || *pref_name == prefs::kLanguageHotkeyTrigger)\n SetHotkeys(kTriggerConfigName, language_hotkey_trigger_.GetValue());\n if (!pref_name || *pref_name == prefs::kLanguagePreloadEngines)\n SetPreloadEngines(language_preload_engines_.GetValue());\n if (!pref_name || *pref_name == prefs::kLanguageHangulKeyboard)\n SetLanguageConfigString(kHangulSectionName, kHangulKeyboardConfigName,\n language_hangul_keyboard_.GetValue());\n}\n\nvoid Preferences::SetTimeZone(const std::wstring& id) {\n icu::TimeZone* timezone = icu::TimeZone::createTimeZone(\n icu::UnicodeString::fromUTF8(WideToASCII(id)));\n icu::TimeZone::adoptDefault(timezone);\n}\n\nvoid Preferences::SetLanguageConfigBoolean(const char* section,\n const char* name,\n bool value) {\n ImeConfigValue config;\n config.type = ImeConfigValue::kValueTypeBool;\n config.bool_value = value;\n CrosLibrary::Get()->GetLanguageLibrary()->SetImeConfig(section, name, config);\n}\n\nvoid Preferences::SetLanguageConfigString(const char* section,\n const char* name,\n const std::wstring& value) {\n ImeConfigValue config;\n config.type = ImeConfigValue::kValueTypeString;\n config.string_value = WideToUTF8(value);\n CrosLibrary::Get()->GetLanguageLibrary()->SetImeConfig(section, name, config);\n}\n\nvoid Preferences::SetLanguageConfigStringList(\n const char* section,\n const char* name,\n const std::vector<std::wstring>& values) {\n ImeConfigValue config;\n config.type = ImeConfigValue::kValueTypeStringList;\n for (size_t i = 0; i < values.size(); ++i) {\n config.string_list_value.push_back(WideToUTF8(values[i]));\n }\n CrosLibrary::Get()->GetLanguageLibrary()->SetImeConfig(section, name, config);\n}\n\nvoid Preferences::SetHotkeys(const char* name, const std::wstring& value) {\n std::vector<std::wstring> hotkeys;\n if (!value.empty()) {\n SplitString(value, L',', &hotkeys);\n }\n \/\/ We should call the cros API even when |value| is empty, to disable default\n \/\/ hot-keys.\n SetLanguageConfigStringList(kHotKeySectionName, name, hotkeys);\n}\n\nvoid Preferences::SetPreloadEngines(const std::wstring& value) {\n \/\/ TODO(yusukes): might be better to change the cros API signature so it\n \/\/ could accept the comma separated |value| as-is.\n\n LanguageLibrary* library = CrosLibrary::Get()->GetLanguageLibrary();\n std::vector<std::wstring> input_method_ids;\n SplitString(value, L',', &input_method_ids);\n LOG(INFO) << \"Setting preload_engines to '\" << value << \"'\";\n\n \/\/ Activate languages in |value|.\n for (size_t i = 0; i < input_method_ids.size(); ++i) {\n library->SetInputMethodActivated(WideToUTF8(input_method_ids[i]), true);\n }\n\n \/\/ Deactivate languages that are currently active, but are not in |value|.\n const std::set<std::wstring> input_method_id_set(input_method_ids.begin(),\n input_method_ids.end());\n scoped_ptr<InputMethodDescriptors> active_input_methods(\n library->GetActiveInputMethods());\n for (size_t i = 0; i < active_input_methods->size(); ++i) {\n const InputMethodDescriptor& active_input_method\n = active_input_methods->at(i);\n if (input_method_id_set.count(UTF8ToWide(active_input_method.id)) == 0) {\n library->SetInputMethodActivated(active_input_method.id, false);\n }\n }\n}\n\n} \/\/ namespace chromeos\n<commit_msg>Fix build break (browser_test failure on Chromium OS bot). This is partial revert of r44072.<commit_after>\/\/ Copyright (c) 2009 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/chromeos\/preferences.h\"\n\n#include \"base\/string_util.h\"\n#include \"base\/utf_string_conversions.h\"\n#include \"chrome\/browser\/chromeos\/cros\/cros_library.h\"\n#include \"chrome\/browser\/chromeos\/cros\/language_library.h\"\n#include \"chrome\/browser\/chromeos\/cros\/synaptics_library.h\"\n#include \"chrome\/browser\/chromeos\/language_preferences.h\"\n#include \"chrome\/browser\/pref_member.h\"\n#include \"chrome\/browser\/pref_service.h\"\n#include \"chrome\/common\/notification_service.h\"\n#include \"chrome\/common\/pref_names.h\"\n#include \"unicode\/timezone.h\"\n\nnamespace {\n\n\/\/ Section and config names for the IBus configuration daemon.\nconst char kGeneralSectionName[] = \"general\";\nconst char kHotKeySectionName[] = \"general\/hotkey\";\nconst char kHangulSectionName[] = \"engine\/Hangul\";\n\nconst char kUseGlobalEngineConfigName[] = \"use_global_engine\";\nconst char kNextEngineConfigName[] = \"next_engine\";\nconst char kTriggerConfigName[] = \"trigger\";\nconst char kHangulKeyboardConfigName[] = \"HangulKeyboard\";\n\n} \/\/ namespace\n\nnamespace chromeos {\n\n\/\/ static\nvoid Preferences::RegisterUserPrefs(PrefService* prefs) {\n prefs->RegisterStringPref(prefs::kTimeZone, L\"US\/Pacific\");\n prefs->RegisterBooleanPref(prefs::kTapToClickEnabled, false);\n prefs->RegisterBooleanPref(prefs::kVertEdgeScrollEnabled, false);\n prefs->RegisterIntegerPref(prefs::kTouchpadSpeedFactor, 5);\n prefs->RegisterIntegerPref(prefs::kTouchpadSensitivity, 5);\n prefs->RegisterBooleanPref(prefs::kLanguageUseGlobalEngine, true);\n prefs->RegisterStringPref(prefs::kLanguageHotkeyNextEngine,\n kHotkeyNextEngine);\n prefs->RegisterStringPref(prefs::kLanguageHotkeyTrigger, kHotkeyTrigger);\n prefs->RegisterStringPref(prefs::kLanguagePreloadEngines,\n UTF8ToWide(kFallbackInputMethodId)); \/\/ EN layout\n prefs->RegisterStringPref(prefs::kLanguageHangulKeyboard,\n kHangulKeyboardNameIDPairs[0].keyboard_id);\n}\n\nvoid Preferences::Init(PrefService* prefs) {\n timezone_.Init(prefs::kTimeZone, prefs, this);\n tap_to_click_enabled_.Init(prefs::kTapToClickEnabled, prefs, this);\n vert_edge_scroll_enabled_.Init(prefs::kVertEdgeScrollEnabled, prefs, this);\n speed_factor_.Init(prefs::kTouchpadSpeedFactor, prefs, this);\n sensitivity_.Init(prefs::kTouchpadSensitivity, prefs, this);\n language_use_global_engine_.Init(\n prefs::kLanguageUseGlobalEngine, prefs, this);\n language_hotkey_next_engine_.Init(\n prefs::kLanguageHotkeyNextEngine, prefs, this);\n language_hotkey_trigger_.Init(prefs::kLanguageHotkeyTrigger, prefs, this);\n language_preload_engines_.Init(prefs::kLanguagePreloadEngines, prefs, this);\n language_hangul_keyboard_.Init(prefs::kLanguageHangulKeyboard, prefs, this);\n\n \/\/ Initialize touchpad settings to what's saved in user preferences.\n NotifyPrefChanged(NULL);\n}\n\nvoid Preferences::Observe(NotificationType type,\n const NotificationSource& source,\n const NotificationDetails& details) {\n if (type == NotificationType::PREF_CHANGED)\n NotifyPrefChanged(Details<std::wstring>(details).ptr());\n}\n\nvoid Preferences::NotifyPrefChanged(const std::wstring* pref_name) {\n if (!pref_name || *pref_name == prefs::kTimeZone)\n SetTimeZone(timezone_.GetValue());\n if (!pref_name || *pref_name == prefs::kTapToClickEnabled)\n CrosLibrary::Get()->GetSynapticsLibrary()->SetBoolParameter(\n PARAM_BOOL_TAP_TO_CLICK,\n tap_to_click_enabled_.GetValue());\n if (!pref_name || *pref_name == prefs::kVertEdgeScrollEnabled)\n CrosLibrary::Get()->GetSynapticsLibrary()->SetBoolParameter(\n PARAM_BOOL_VERTICAL_EDGE_SCROLLING,\n vert_edge_scroll_enabled_.GetValue());\n if (!pref_name || *pref_name == prefs::kTouchpadSpeedFactor)\n CrosLibrary::Get()->GetSynapticsLibrary()->SetRangeParameter(\n PARAM_RANGE_SPEED_SENSITIVITY,\n speed_factor_.GetValue());\n if (!pref_name || *pref_name == prefs::kTouchpadSensitivity)\n CrosLibrary::Get()->GetSynapticsLibrary()->SetRangeParameter(\n PARAM_RANGE_TOUCH_SENSITIVITY,\n sensitivity_.GetValue());\n if (!pref_name || *pref_name == prefs::kLanguageUseGlobalEngine)\n SetLanguageConfigBoolean(kGeneralSectionName, kUseGlobalEngineConfigName,\n language_use_global_engine_.GetValue());\n if (!pref_name || *pref_name == prefs::kLanguageHotkeyNextEngine)\n SetHotkeys(kNextEngineConfigName, language_hotkey_next_engine_.GetValue());\n if (!pref_name || *pref_name == prefs::kLanguageHotkeyTrigger)\n SetHotkeys(kTriggerConfigName, language_hotkey_trigger_.GetValue());\n if (!pref_name || *pref_name == prefs::kLanguagePreloadEngines)\n SetPreloadEngines(language_preload_engines_.GetValue());\n if (!pref_name || *pref_name == prefs::kLanguageHangulKeyboard)\n SetLanguageConfigString(kHangulSectionName, kHangulKeyboardConfigName,\n language_hangul_keyboard_.GetValue());\n}\n\nvoid Preferences::SetTimeZone(const std::wstring& id) {\n icu::TimeZone* timezone = icu::TimeZone::createTimeZone(\n icu::UnicodeString::fromUTF8(WideToASCII(id)));\n icu::TimeZone::adoptDefault(timezone);\n}\n\nvoid Preferences::SetLanguageConfigBoolean(const char* section,\n const char* name,\n bool value) {\n ImeConfigValue config;\n config.type = ImeConfigValue::kValueTypeBool;\n config.bool_value = value;\n CrosLibrary::Get()->GetLanguageLibrary()->SetImeConfig(section, name, config);\n}\n\nvoid Preferences::SetLanguageConfigString(const char* section,\n const char* name,\n const std::wstring& value) {\n ImeConfigValue config;\n config.type = ImeConfigValue::kValueTypeString;\n config.string_value = WideToUTF8(value);\n CrosLibrary::Get()->GetLanguageLibrary()->SetImeConfig(section, name, config);\n}\n\nvoid Preferences::SetLanguageConfigStringList(\n const char* section,\n const char* name,\n const std::vector<std::wstring>& values) {\n ImeConfigValue config;\n config.type = ImeConfigValue::kValueTypeStringList;\n for (size_t i = 0; i < values.size(); ++i) {\n config.string_list_value.push_back(WideToUTF8(values[i]));\n }\n \/\/ TODO(yusukes): Re-enable this line.\n \/\/ CrosLibrary::Get()->GetLanguageLibrary()->SetImeConfig(\n \/\/ section, name, config);\n}\n\nvoid Preferences::SetHotkeys(const char* name, const std::wstring& value) {\n std::vector<std::wstring> hotkeys;\n if (!value.empty()) {\n SplitString(value, L',', &hotkeys);\n }\n \/\/ We should call the cros API even when |value| is empty, to disable default\n \/\/ hot-keys.\n SetLanguageConfigStringList(kHotKeySectionName, name, hotkeys);\n}\n\nvoid Preferences::SetPreloadEngines(const std::wstring& value) {\n \/\/ TODO(yusukes): might be better to change the cros API signature so it\n \/\/ could accept the comma separated |value| as-is.\n\n LanguageLibrary* library = CrosLibrary::Get()->GetLanguageLibrary();\n std::vector<std::wstring> input_method_ids;\n SplitString(value, L',', &input_method_ids);\n LOG(INFO) << \"Setting preload_engines to '\" << value << \"'\";\n\n \/\/ Activate languages in |value|.\n for (size_t i = 0; i < input_method_ids.size(); ++i) {\n library->SetInputMethodActivated(WideToUTF8(input_method_ids[i]), true);\n }\n\n \/\/ Deactivate languages that are currently active, but are not in |value|.\n const std::set<std::wstring> input_method_id_set(input_method_ids.begin(),\n input_method_ids.end());\n scoped_ptr<InputMethodDescriptors> active_input_methods(\n library->GetActiveInputMethods());\n for (size_t i = 0; i < active_input_methods->size(); ++i) {\n const InputMethodDescriptor& active_input_method\n = active_input_methods->at(i);\n if (input_method_id_set.count(UTF8ToWide(active_input_method.id)) == 0) {\n library->SetInputMethodActivated(active_input_method.id, false);\n }\n }\n}\n\n} \/\/ namespace chromeos\n<|endoftext|>"} {"text":"<commit_before>#ifndef MJOLNIR_CORE_NEIGHBOR_LIST_HPP\n#define MJOLNIR_CORE_NEIGHBOR_LIST_HPP\n#include <mjolnir\/util\/range.hpp>\n#include <mjolnir\/util\/empty.hpp>\n#include <type_traits>\n#include <algorithm>\n#include <iterator>\n#include <utility>\n#include <vector>\n\n\/\/! a container for verlet-list, cell-list, and other spatial indexing methods.\n\/\/! the objectives are\n\/\/! - store indices of possible partners that has interaction.\n\/\/! - store pre-calculated parameters. e.g. epsilon_ij = sqrt(eps_i * eps_j)\n\/\/! for Lennard-Jones takes relatively large computational cost to obtain.\n\/\/! calculate it for all the possible pairs to make force calculation fast.\n\nnamespace mjolnir\n{\n\n\/\/ google with \"empty base optimization(EBO)\".\n\/\/ By using EBO, we can compress the object size when `potT` is a empty class.\n\/\/ without this, empty parameter type consumes 8 byte (on x86_64) because\n\/\/ std::size_t requires 8-byte alignment.\n\nnamespace detail\n{\n\/\/ In order to handle `double` or other non-class object, neighbor_element need\n\/\/ another layer that checks `std::is_empty`. If empty, it inherits it and EBO\n\/\/ removes the overhead. If not empty(like `double`), it keeps storage for the\n\/\/ value. `neighbor_elmenet_impl` stores value if `std::true_type` is passed.\ntemplate<typename potT, bool IsEmpty>\nstruct neighbor_element_impl;\n\ntemplate<typename potT>\nstruct neighbor_element_impl<potT, true> : private potT \/\/ for EBO\n{\n using potential_type = potT;\n\n explicit neighbor_element_impl(const potential_type&) {}\n explicit neighbor_element_impl(potential_type&&) {}\n\n neighbor_element_impl() = default;\n ~neighbor_element_impl() = default;\n neighbor_element_impl(const neighbor_element_impl&) = default;\n neighbor_element_impl(neighbor_element_impl&&) = default;\n neighbor_element_impl& operator=(const neighbor_element_impl&) = default;\n neighbor_element_impl& operator=(neighbor_element_impl&&) = default;\n\n potential_type& potential() noexcept {return *this;}\n potential_type const& potential() const noexcept {return *this;}\n};\n\ntemplate<typename potT>\nstruct neighbor_element_impl<potT, false>\n{\n using potential_type = potT;\n\n explicit neighbor_element_impl(const potential_type& p): pot(p) {}\n explicit neighbor_element_impl(potential_type&& p): pot(std::move(p)) {}\n\n neighbor_element_impl() = default;\n ~neighbor_element_impl() = default;\n neighbor_element_impl(const neighbor_element_impl&) = default;\n neighbor_element_impl(neighbor_element_impl&&) = default;\n neighbor_element_impl& operator=(const neighbor_element_impl&) = default;\n neighbor_element_impl& operator=(neighbor_element_impl&&) = default;\n\n potential_type& potential() noexcept {return this->pot;}\n potential_type const& potential() const noexcept {return this->pot;}\n\n potential_type pot;\n};\n\n} \/\/ detail\n\ntemplate<typename potT>\nstruct neighbor_element\n : private detail::neighbor_element_impl<potT, std::is_empty<potT>::value>\n{\n static constexpr bool potential_is_empty = std::is_empty<potT>::value;\n\n using base_type = detail::neighbor_element_impl<potT, potential_is_empty>;\n using potential_type = typename base_type::potential_type;\n\n neighbor_element(std::size_t idx, const potT& p)\n : base_type(p), index(idx)\n {}\n neighbor_element(std::size_t idx, potT&& p)\n : base_type(std::move(p)), index(idx)\n {}\n\n neighbor_element() = default;\n ~neighbor_element() = default;\n neighbor_element(const neighbor_element&) = default;\n neighbor_element(neighbor_element&&) = default;\n neighbor_element& operator=(const neighbor_element&) = default;\n neighbor_element& operator=(neighbor_element&&) = default;\n\n potential_type& potential() noexcept {return base_type::potential();}\n potential_type const& potential() const noexcept {return base_type::potential();}\n\n \/\/ potential_type pot; \/\/ derived from neighbor_element_impl\n std::size_t index;\n};\ntemplate<typename potT>\nconstexpr bool neighbor_element<potT>::potential_is_empty;\n\n\/\/ Check the EBO works and the size of neighbor_element with empty class\n\/\/ is equal to the size of `std::size_t index;`.\nstatic_assert(sizeof(std::size_t) == sizeof(neighbor_element<empty_t>),\n \"checking neighbor_element reduces size of empty object\");\n\ntemplate<typename potT>\ninline bool operator==(\n const neighbor_element<potT>& lhs, const neighbor_element<potT>& rhs)\n{\n return lhs.index == rhs.index;\n}\ntemplate<typename potT>\ninline bool operator!=(\n const neighbor_element<potT>& lhs, const neighbor_element<potT>& rhs)\n{\n return lhs.index != rhs.index;\n}\ntemplate<typename potT>\ninline bool operator<(\n const neighbor_element<potT>& lhs, const neighbor_element<potT>& rhs)\n{\n return lhs.index < rhs.index;\n}\ntemplate<typename potT>\ninline bool operator>(\n const neighbor_element<potT>& lhs, const neighbor_element<potT>& rhs)\n{\n return lhs.index > rhs.index;\n}\ntemplate<typename potT>\ninline bool operator<=(\n const neighbor_element<potT>& lhs, const neighbor_element<potT>& rhs)\n{\n return lhs.index <= rhs.index;\n}\ntemplate<typename potT>\ninline bool operator>=(\n const neighbor_element<paramT>& lhs, const neighbor_element<paramT>& rhs)\n{\n return lhs.index >= rhs.index;\n}\n\n\/\/ ----------------------------------------------------------------------------\n\/\/ neighbor list\n\ntemplate<typename potentialT>\nclass NeighborList\n{\n public:\n using potential_type = potentialT;\n using neighbor_type = neighbor_element<potential_type>;\n using container_type = std::vector<neighbor_type>;\n using range_type = range<typename container_type::const_iterator>;\n\n \/\/ XXX this contains the list in the following way.\n \/\/\n \/\/ 1. The neighboring list that has interaction partners of each particle\n \/\/ and the parameter for each pairs (e.g. `q_i*q_j` for electrostatics).\n \/\/\n \/\/ __partner of p1__ __partner of p2___________ ____ ... pN__\n \/\/ ' ' ' '\n \/\/ |{p2,q12}|{p3,q13}|{p4,q24}|{p6,q26}|{p7,q27}|{ ... }|\n \/\/ 0th 1st 2nd 3rd 4th 5th ... M-1 th element\n \/\/\n \/\/ 2. The range list that contains from where to where the partners are\n \/\/ contained.\n \/\/ +---- partner of p1 starts from 0th element of the above array\n \/\/ | +-- partner of p2 starts from 2nd element of the above array\n \/\/ v v\n \/\/ |0|2|5|...|M|\n \/\/ ^ ^ ^\n \/\/ +-+-----+-- the last partner of p1 is 2-1 = 1.\n \/\/ +-----+-- the last pertner of p2 is 5-1 = 4.\n \/\/ +-- the last element of pN is M-1.\n \/\/\n \/\/ This list should have N+1 elements because i-th and (i+1)-th elements of\n \/\/ the list is needed to obtain the partner.\n \/\/\n \/\/ By doing this, we can reduce the memory resource to have the list.\n\n public:\n\n NeighborList() = default;\n ~NeighborList() = default;\n NeighborList(const NeighborList&) = default;\n NeighborList(NeighborList&&) = default;\n NeighborList& operator=(const NeighborList&) = default;\n NeighborList& operator=(NeighborList&&) = default;\n\n void clear()\n {\n this->neighbors_.clear();\n this->ranges_ .clear();\n return;\n }\n\n \/\/ assign the partners in range [first, last) as the partner of particle i.\n template<typename Iterator>\n void add_list_for(const std::size_t i, Iterator first, Iterator last)\n {\n static_assert(std::is_same<\n typename std::iterator_traits<Iterator>::value_type, neighbor_type\n >::value, \"The iterator must points neighbor type.\");\n\n if(this->ranges_.size() <= i+1)\n {\n this->ranges_.resize(i+2, 0);\n }\n\n assert(ranges_[i] == 0 || ranges_[i] == this->neighbors_.size());\n\n this->ranges_[i] = this->neighbors_.size();\n this->ranges_[i+1] = this->neighbors_.size() + std::distance(first, last);\n\n \/\/ allcoate if the current size is not enough.\n \/\/ XXX\n \/\/ This invalidates iterators because of the re-allocation.\n \/\/ So the `ranges_` cannot have iterators.\n \/\/ The elements of `ranges_` must be indices.\n this->neighbors_.reserve(neighbors_.size() + std::distance(first, last));\n\n std::copy(first, last, std::back_inserter(this->neighbors_));\n return ;\n }\n\n void reserve(const std::size_t approx_neighbors,\n const std::size_t num_participants,\n const std::size_t num_particles)\n {\n neighbors_.reserve(approx_neighbors * num_participants);\n ranges_.reserve(num_particles);\n }\n\n std::size_t num_neighbors() const noexcept {return neighbors_.size();}\n\n range_type operator[](const std::size_t i) const noexcept\n {\n return range_type{\n this->neighbors_.begin() + this->ranges_[i],\n this->neighbors_.begin() + this->ranges_[i+1]\n };\n }\n range_type at(const std::size_t i) const\n {\n return range_type{\n this->neighbors_.begin() + this->ranges_.at(i),\n this->neighbors_.begin() + this->ranges_.at(i+1)\n };\n }\n\n \/\/ ------------------------------------------------------------------------\n \/\/ Caution: take great care when you use the following functions.\n \/\/ If possible, use `add_list_for` instead.\n\n container_type& neighbors() noexcept {return neighbors_;}\n std::vector<std::size_t>& ranges() noexcept {return ranges_;}\n\n private:\n container_type neighbors_;\n std::vector<std::size_t> ranges_;\n};\n\n} \/\/ mjolnir\n#endif\/\/ MJOLNIR_NEIGHBOR_LIST_HPP\n<commit_msg>fix: fix typo in type<commit_after>#ifndef MJOLNIR_CORE_NEIGHBOR_LIST_HPP\n#define MJOLNIR_CORE_NEIGHBOR_LIST_HPP\n#include <mjolnir\/util\/range.hpp>\n#include <mjolnir\/util\/empty.hpp>\n#include <type_traits>\n#include <algorithm>\n#include <iterator>\n#include <utility>\n#include <vector>\n\n\/\/! a container for verlet-list, cell-list, and other spatial indexing methods.\n\/\/! the objectives are\n\/\/! - store indices of possible partners that has interaction.\n\/\/! - store pre-calculated parameters. e.g. epsilon_ij = sqrt(eps_i * eps_j)\n\/\/! for Lennard-Jones takes relatively large computational cost to obtain.\n\/\/! calculate it for all the possible pairs to make force calculation fast.\n\nnamespace mjolnir\n{\n\n\/\/ google with \"empty base optimization(EBO)\".\n\/\/ By using EBO, we can compress the object size when `potT` is a empty class.\n\/\/ without this, empty parameter type consumes 8 byte (on x86_64) because\n\/\/ std::size_t requires 8-byte alignment.\n\nnamespace detail\n{\n\/\/ In order to handle `double` or other non-class object, neighbor_element need\n\/\/ another layer that checks `std::is_empty`. If empty, it inherits it and EBO\n\/\/ removes the overhead. If not empty(like `double`), it keeps storage for the\n\/\/ value. `neighbor_elmenet_impl` stores value if `std::true_type` is passed.\ntemplate<typename potT, bool IsEmpty>\nstruct neighbor_element_impl;\n\ntemplate<typename potT>\nstruct neighbor_element_impl<potT, true> : private potT \/\/ for EBO\n{\n using potential_type = potT;\n\n explicit neighbor_element_impl(const potential_type&) {}\n explicit neighbor_element_impl(potential_type&&) {}\n\n neighbor_element_impl() = default;\n ~neighbor_element_impl() = default;\n neighbor_element_impl(const neighbor_element_impl&) = default;\n neighbor_element_impl(neighbor_element_impl&&) = default;\n neighbor_element_impl& operator=(const neighbor_element_impl&) = default;\n neighbor_element_impl& operator=(neighbor_element_impl&&) = default;\n\n potential_type& potential() noexcept {return *this;}\n potential_type const& potential() const noexcept {return *this;}\n};\n\ntemplate<typename potT>\nstruct neighbor_element_impl<potT, false>\n{\n using potential_type = potT;\n\n explicit neighbor_element_impl(const potential_type& p): pot(p) {}\n explicit neighbor_element_impl(potential_type&& p): pot(std::move(p)) {}\n\n neighbor_element_impl() = default;\n ~neighbor_element_impl() = default;\n neighbor_element_impl(const neighbor_element_impl&) = default;\n neighbor_element_impl(neighbor_element_impl&&) = default;\n neighbor_element_impl& operator=(const neighbor_element_impl&) = default;\n neighbor_element_impl& operator=(neighbor_element_impl&&) = default;\n\n potential_type& potential() noexcept {return this->pot;}\n potential_type const& potential() const noexcept {return this->pot;}\n\n potential_type pot;\n};\n\n} \/\/ detail\n\ntemplate<typename potT>\nstruct neighbor_element\n : private detail::neighbor_element_impl<potT, std::is_empty<potT>::value>\n{\n static constexpr bool potential_is_empty = std::is_empty<potT>::value;\n\n using base_type = detail::neighbor_element_impl<potT, potential_is_empty>;\n using potential_type = typename base_type::potential_type;\n\n neighbor_element(std::size_t idx, const potT& p)\n : base_type(p), index(idx)\n {}\n neighbor_element(std::size_t idx, potT&& p)\n : base_type(std::move(p)), index(idx)\n {}\n\n neighbor_element() = default;\n ~neighbor_element() = default;\n neighbor_element(const neighbor_element&) = default;\n neighbor_element(neighbor_element&&) = default;\n neighbor_element& operator=(const neighbor_element&) = default;\n neighbor_element& operator=(neighbor_element&&) = default;\n\n potential_type& potential() noexcept {return base_type::potential();}\n potential_type const& potential() const noexcept {return base_type::potential();}\n\n \/\/ potential_type pot; \/\/ derived from neighbor_element_impl\n std::size_t index;\n};\ntemplate<typename potT>\nconstexpr bool neighbor_element<potT>::potential_is_empty;\n\n\/\/ Check the EBO works and the size of neighbor_element with empty class\n\/\/ is equal to the size of `std::size_t index;`.\nstatic_assert(sizeof(std::size_t) == sizeof(neighbor_element<empty_t>),\n \"checking neighbor_element reduces size of empty object\");\n\ntemplate<typename potT>\ninline bool operator==(\n const neighbor_element<potT>& lhs, const neighbor_element<potT>& rhs)\n{\n return lhs.index == rhs.index;\n}\ntemplate<typename potT>\ninline bool operator!=(\n const neighbor_element<potT>& lhs, const neighbor_element<potT>& rhs)\n{\n return lhs.index != rhs.index;\n}\ntemplate<typename potT>\ninline bool operator<(\n const neighbor_element<potT>& lhs, const neighbor_element<potT>& rhs)\n{\n return lhs.index < rhs.index;\n}\ntemplate<typename potT>\ninline bool operator>(\n const neighbor_element<potT>& lhs, const neighbor_element<potT>& rhs)\n{\n return lhs.index > rhs.index;\n}\ntemplate<typename potT>\ninline bool operator<=(\n const neighbor_element<potT>& lhs, const neighbor_element<potT>& rhs)\n{\n return lhs.index <= rhs.index;\n}\ntemplate<typename potT>\ninline bool operator>=(\n const neighbor_element<potT>& lhs, const neighbor_element<potT>& rhs)\n{\n return lhs.index >= rhs.index;\n}\n\n\/\/ ----------------------------------------------------------------------------\n\/\/ neighbor list\n\ntemplate<typename potentialT>\nclass NeighborList\n{\n public:\n using potential_type = potentialT;\n using neighbor_type = neighbor_element<potential_type>;\n using container_type = std::vector<neighbor_type>;\n using range_type = range<typename container_type::const_iterator>;\n\n \/\/ XXX this contains the list in the following way.\n \/\/\n \/\/ 1. The neighboring list that has interaction partners of each particle\n \/\/ and the parameter for each pairs (e.g. `q_i*q_j` for electrostatics).\n \/\/\n \/\/ __partner of p1__ __partner of p2___________ ____ ... pN__\n \/\/ ' ' ' '\n \/\/ |{p2,q12}|{p3,q13}|{p4,q24}|{p6,q26}|{p7,q27}|{ ... }|\n \/\/ 0th 1st 2nd 3rd 4th 5th ... M-1 th element\n \/\/\n \/\/ 2. The range list that contains from where to where the partners are\n \/\/ contained.\n \/\/ +---- partner of p1 starts from 0th element of the above array\n \/\/ | +-- partner of p2 starts from 2nd element of the above array\n \/\/ v v\n \/\/ |0|2|5|...|M|\n \/\/ ^ ^ ^\n \/\/ +-+-----+-- the last partner of p1 is 2-1 = 1.\n \/\/ +-----+-- the last pertner of p2 is 5-1 = 4.\n \/\/ +-- the last element of pN is M-1.\n \/\/\n \/\/ This list should have N+1 elements because i-th and (i+1)-th elements of\n \/\/ the list is needed to obtain the partner.\n \/\/\n \/\/ By doing this, we can reduce the memory resource to have the list.\n\n public:\n\n NeighborList() = default;\n ~NeighborList() = default;\n NeighborList(const NeighborList&) = default;\n NeighborList(NeighborList&&) = default;\n NeighborList& operator=(const NeighborList&) = default;\n NeighborList& operator=(NeighborList&&) = default;\n\n void clear()\n {\n this->neighbors_.clear();\n this->ranges_ .clear();\n return;\n }\n\n \/\/ assign the partners in range [first, last) as the partner of particle i.\n template<typename Iterator>\n void add_list_for(const std::size_t i, Iterator first, Iterator last)\n {\n static_assert(std::is_same<\n typename std::iterator_traits<Iterator>::value_type, neighbor_type\n >::value, \"The iterator must points neighbor type.\");\n\n if(this->ranges_.size() <= i+1)\n {\n this->ranges_.resize(i+2, 0);\n }\n\n assert(ranges_[i] == 0 || ranges_[i] == this->neighbors_.size());\n\n this->ranges_[i] = this->neighbors_.size();\n this->ranges_[i+1] = this->neighbors_.size() + std::distance(first, last);\n\n \/\/ allcoate if the current size is not enough.\n \/\/ XXX\n \/\/ This invalidates iterators because of the re-allocation.\n \/\/ So the `ranges_` cannot have iterators.\n \/\/ The elements of `ranges_` must be indices.\n this->neighbors_.reserve(neighbors_.size() + std::distance(first, last));\n\n std::copy(first, last, std::back_inserter(this->neighbors_));\n return ;\n }\n\n void reserve(const std::size_t approx_neighbors,\n const std::size_t num_participants,\n const std::size_t num_particles)\n {\n neighbors_.reserve(approx_neighbors * num_participants);\n ranges_.reserve(num_particles);\n }\n\n std::size_t num_neighbors() const noexcept {return neighbors_.size();}\n\n range_type operator[](const std::size_t i) const noexcept\n {\n return range_type{\n this->neighbors_.begin() + this->ranges_[i],\n this->neighbors_.begin() + this->ranges_[i+1]\n };\n }\n range_type at(const std::size_t i) const\n {\n return range_type{\n this->neighbors_.begin() + this->ranges_.at(i),\n this->neighbors_.begin() + this->ranges_.at(i+1)\n };\n }\n\n \/\/ ------------------------------------------------------------------------\n \/\/ Caution: take great care when you use the following functions.\n \/\/ If possible, use `add_list_for` instead.\n\n container_type& neighbors() noexcept {return neighbors_;}\n std::vector<std::size_t>& ranges() noexcept {return ranges_;}\n\n private:\n container_type neighbors_;\n std::vector<std::size_t> ranges_;\n};\n\n} \/\/ mjolnir\n#endif\/\/ MJOLNIR_NEIGHBOR_LIST_HPP\n<|endoftext|>"} {"text":"<commit_before>#ifndef MJOLNIR_UTIL_PROGRESS_BAR_HPP\n#define MJOLNIR_UTIL_PROGRESS_BAR_HPP\n#include <array>\n#include <cstring>\n#include <cmath>\n#include <cassert>\n\nnamespace mjolnir\n{\n\ntemplate<std::size_t Width>\nclass progress_bar\n{\n public:\n\n progress_bar() noexcept\n : total_(1), r_total_(1.0)\n {}\n explicit progress_bar(std::size_t tot) noexcept\n : total_(tot), r_total_(1.0 \/ tot)\n {}\n ~progress_bar() = default;\n progress_bar(progress_bar const&) = default;\n progress_bar(progress_bar &&) = default;\n progress_bar& operator=(progress_bar const&) = default;\n progress_bar& operator=(progress_bar &&) = default;\n\n void reset(const std::size_t total_step)\n {\n this->total_ = total_step;\n this->r_total_ = 1.0 \/ static_cast<double>(total_step);\n return;\n }\n\n void format(std::size_t count, std::ostream& os)\n {\n \/\/XXX: requires UTF-8. TODO: consider setting locale\n constexpr auto full = u8\"█\"; \/\/ U+2588 Full block\n constexpr auto l7 = u8\"▉\"; \/\/ U+2589 Left seven eighths block\n constexpr auto l6 = u8\"▊\"; \/\/ U+258A Left three quarters block\n constexpr auto l5 = u8\"▋\"; \/\/ U+258B Left five eighths block\n constexpr auto l4 = u8\"▌\"; \/\/ U+258C Left half block\n constexpr auto l3 = u8\"▍\"; \/\/ U+258D Left three eighths block\n constexpr auto l2 = u8\"▎\"; \/\/ U+258E Left one quarter block\n constexpr auto l1 = u8\"▏\"; \/\/ U+258F Left one eighth block\n\n const double ratio = (count == total_) ? 1.0 :\n std::max(0.0, std::min(1.0, count * this->r_total_));\n\n std::array<char, 8> buf1;\n std::snprintf(buf1.data(), 8, \"%5.1f%%|\", ratio * 100.0);\n os << '\\r' << buf1.data();\n\n const std::size_t filled = std::floor(ratio*Width);\n for(std::size_t i=0; i<filled; ++i)\n {\n os << full;\n }\n if(Width > filled)\n {\n switch(static_cast<std::size_t>(ratio * Width * 8) % 8)\n {\n case 0:{os << ' '; break;}\n case 1:{os << l1; break;}\n case 2:{os << l2; break;}\n case 3:{os << l3; break;}\n case 4:{os << l4; break;}\n case 5:{os << l5; break;}\n case 6:{os << l6; break;}\n case 7:{os << l7; break;}\n }\n for(std::size_t i=1; i<Width - filled; ++i)\n {\n os << ' ';\n }\n }\n os << '|' << std::flush;\n return ;\n }\n\n std::size_t total() const noexcept {return total_;}\n\n private:\n\n std::size_t total_;\n double r_total_;\n};\n\n} \/\/ mjolnir\n#endif\/\/ MJOLNIR_PROGRESS_BAR_HPP\n<commit_msg>feat: output remaining time in progress bar<commit_after>#ifndef MJOLNIR_UTIL_PROGRESS_BAR_HPP\n#define MJOLNIR_UTIL_PROGRESS_BAR_HPP\n#include <array>\n#include <chrono>\n#include <cstring>\n#include <cmath>\n#include <cassert>\n\nnamespace mjolnir\n{\n\ntemplate<std::size_t Width>\nclass progress_bar\n{\n public:\n\n progress_bar() noexcept\n : total_(1), r_total_(1.0), start_(std::chrono::system_clock::now())\n {}\n explicit progress_bar(std::size_t tot) noexcept\n : total_(tot), r_total_(1.0 \/ tot),\n start_(std::chrono::system_clock::now())\n {}\n ~progress_bar() = default;\n progress_bar(progress_bar const&) = default;\n progress_bar(progress_bar &&) = default;\n progress_bar& operator=(progress_bar const&) = default;\n progress_bar& operator=(progress_bar &&) = default;\n\n void reset(const std::size_t total_step)\n {\n this->total_ = total_step;\n this->r_total_ = 1.0 \/ static_cast<double>(total_step);\n this->start_ = std::chrono::system_clock::now();\n return;\n }\n\n void format(std::size_t count, std::ostream& os)\n {\n if(count == 0){start_ = std::chrono::system_clock::now();}\n\n \/\/XXX: requires UTF-8.\n constexpr auto full = u8\"█\"; \/\/ U+2588 Full block\n constexpr auto l7 = u8\"▉\"; \/\/ U+2589 Left seven eighths block\n constexpr auto l6 = u8\"▊\"; \/\/ U+258A Left three quarters block\n constexpr auto l5 = u8\"▋\"; \/\/ U+258B Left five eighths block\n constexpr auto l4 = u8\"▌\"; \/\/ U+258C Left half block\n constexpr auto l3 = u8\"▍\"; \/\/ U+258D Left three eighths block\n constexpr auto l2 = u8\"▎\"; \/\/ U+258E Left one quarter block\n constexpr auto l1 = u8\"▏\"; \/\/ U+258F Left one eighth block\n\n const double ratio = (count == total_) ? 1.0 :\n std::max(0.0, std::min(1.0, count * this->r_total_));\n\n std::array<char, 8> buf;\n std::snprintf(buf.data(), 8, \"%5.1f%%|\", ratio * 100.0);\n os << '\\r' << buf.data();\n\n const std::size_t filled = std::floor(ratio*Width);\n for(std::size_t i=0; i<filled; ++i)\n {\n os << full;\n }\n if(Width > filled)\n {\n switch(static_cast<std::size_t>(ratio * Width * 8) % 8)\n {\n case 0: {os << ' '; break;}\n case 1: {os << l1; break;}\n case 2: {os << l2; break;}\n case 3: {os << l3; break;}\n case 4: {os << l4; break;}\n case 5: {os << l5; break;}\n case 6: {os << l6; break;}\n case 7: {os << l7; break;}\n }\n for(std::size_t i=1; i<Width - filled; ++i)\n {\n os << ' ';\n }\n }\n os << '|';\n\n const auto current = std::chrono::system_clock::now();\n const auto residual = std::chrono::duration_cast<std::chrono::milliseconds>(\n (current - start_) * (1.0 - ratio) \/ ratio).count() * 0.001;\n\n if(residual < 60.0)\n {\n std::snprintf(buf.data(), 6, \"%5.1f\", residual);\n os << buf.data() << \" seconds remaining \";\n }\n else if(residual < 60.0 * 60.0)\n {\n std::snprintf(buf.data(), 6, \"%5.1f\", residual * 0.0167);\n os << buf.data() << \" minutes remaining \";\n }\n else if(residual < 60.0 * 60.0 * 24.0)\n {\n std::snprintf(buf.data(), 6, \"%5.1f\", residual * 0.0167 * 0.0167);\n os << buf.data() << \" hours remaining \";\n }\n else if(residual < 60.0 * 60.0 * 24.0 * 99.0)\n {\n std::snprintf(buf.data(), 6, \"%5.1f\", residual * 0.0167 * 0.0167 * 0.0417);\n os << buf.data() << \" days remaining \";\n }\n else\n {\n os << \" over 100 days remaining\";\n }\n os << std::flush;\n return ;\n }\n\n std::size_t total() const noexcept {return total_;}\n\n private:\n\n std::size_t total_;\n double r_total_;\n std::chrono::system_clock::time_point start_;\n};\n\n} \/\/ mjolnir\n#endif\/\/ MJOLNIR_PROGRESS_BAR_HPP\n<|endoftext|>"} {"text":"<commit_before>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Copyright 2006 - 2014, Paul Beckingham, Federico Hernandez.\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included\n\/\/ in all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n\/\/ OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n\/\/ THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n\/\/ SOFTWARE.\n\/\/\n\/\/ http:\/\/www.opensource.org\/licenses\/mit-license.php\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include <cmake.h>\n#include <iostream>\n#include <Context.h>\n#include <Filter.h>\n#include <text.h>\n#include <util.h>\n#include <i18n.h>\n#include <main.h>\n#include <CmdDenotate.h>\n\nextern Context context;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nCmdDenotate::CmdDenotate ()\n{\n _keyword = \"denotate\";\n _usage = \"task <filter> denotate <pattern>\";\n _description = STRING_CMD_DENO_USAGE;\n _read_only = false;\n _displays_id = false;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nint CmdDenotate::execute (std::string& output)\n{\n int rc = 0;\n int count = 0;\n bool sensitive = context.config.getBoolean (\"search.case.sensitive\");\n\n \/\/ Apply filter.\n Filter filter;\n std::vector <Task> filtered;\n filter.subset (filtered);\n if (filtered.size () == 0)\n {\n context.footnote (STRING_FEEDBACK_NO_TASKS_SP);\n return 1;\n }\n\n \/\/ Apply the command line modifications to the completed task.\n A3 words = context.a3.extract_modifications ();\n if (!words.size ())\n throw std::string (STRING_CMD_DENO_WORDS);\n\n \/\/ Accumulated project change notifications.\n std::map <std::string, std::string> projectChanges;\n\n std::string pattern = words.combine ();\n\n std::vector <Task>::iterator task;\n for (task = filtered.begin (); task != filtered.end (); ++task)\n {\n Task before (*task);\n\n std::map <std::string, std::string> annotations;\n task->getAnnotations (annotations);\n\n if (annotations.size () == 0)\n throw std::string (STRING_CMD_DENO_NONE);\n\n std::map <std::string, std::string>::iterator i;\n std::string anno;\n bool match = false;\n for (i = annotations.begin (); i != annotations.end (); ++i)\n {\n if (i->second == pattern)\n {\n match = true;\n anno = i->second;\n annotations.erase (i);\n task->setAnnotations (annotations);\n break;\n }\n }\n if (!match)\n {\n for (i = annotations.begin (); i != annotations.end (); ++i)\n {\n std::string::size_type loc = find (i->second, pattern, sensitive);\n if (loc != std::string::npos)\n {\n anno = i->second;\n annotations.erase (i);\n task->setAnnotations (annotations);\n break;\n }\n }\n }\n\n if (taskDiff (before, *task))\n {\n std::string question = format (STRING_CMD_DENO_CONFIRM,\n task->id,\n task->get (\"description\"));\n\n if (permission (*task, taskDifferences (before, *task) + question, filtered.size ()))\n {\n ++count;\n context.tdb2.modify (*task);\n feedback_affected (format (STRING_CMD_DENO_FOUND, anno));\n if (context.verbose (\"project\"))\n projectChanges[task->get (\"project\")] = onProjectChange (*task, false);\n }\n else\n {\n std::cout << STRING_CMD_DENO_NO << \"\\n\";\n rc = 1;\n if (_permission_quit)\n break;\n }\n }\n else\n {\n std::cout << format (STRING_CMD_DENO_NOMATCH, pattern) << \"\\n\";\n rc = 1;\n }\n }\n\n \/\/ Now list the project changes.\n std::map <std::string, std::string>::iterator i;\n for (i = projectChanges.begin (); i != projectChanges.end (); ++i)\n if (i->first != \"\")\n context.footnote (i->second);\n\n context.tdb2.commit ();\n feedback_affected (count == 1 ? STRING_CMD_DENO_1 : STRING_CMD_DENO_N, count);\n return rc;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n<commit_msg>CmdDenotate<commit_after>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Copyright 2006 - 2014, Paul Beckingham, Federico Hernandez.\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included\n\/\/ in all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n\/\/ OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n\/\/ THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n\/\/ SOFTWARE.\n\/\/\n\/\/ http:\/\/www.opensource.org\/licenses\/mit-license.php\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include <cmake.h>\n#include <iostream>\n#include <Context.h>\n#include <Filter.h>\n#include <text.h>\n#include <util.h>\n#include <i18n.h>\n#include <main.h>\n#include <CmdDenotate.h>\n\nextern Context context;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nCmdDenotate::CmdDenotate ()\n{\n _keyword = \"denotate\";\n _usage = \"task <filter> denotate <pattern>\";\n _description = STRING_CMD_DENO_USAGE;\n _read_only = false;\n _displays_id = false;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nint CmdDenotate::execute (std::string& output)\n{\n int rc = 0;\n int count = 0;\n bool sensitive = context.config.getBoolean (\"search.case.sensitive\");\n\n \/\/ Apply filter.\n Filter filter;\n std::vector <Task> filtered;\n filter.subset (filtered);\n if (filtered.size () == 0)\n {\n context.footnote (STRING_FEEDBACK_NO_TASKS_SP);\n return 1;\n }\n\n \/\/ Apply the command line modifications to the completed task.\n std::vector <std::string> words = context.parser.getWords ();\n if (!words.size ())\n throw std::string (STRING_CMD_DENO_WORDS);\n\n \/\/ Accumulated project change notifications.\n std::map <std::string, std::string> projectChanges;\n\n \/\/std::string pattern = words.combine ();\n std::string pattern;\n join (pattern, \" \", words);\n\n std::vector <Task>::iterator task;\n for (task = filtered.begin (); task != filtered.end (); ++task)\n {\n Task before (*task);\n\n std::map <std::string, std::string> annotations;\n task->getAnnotations (annotations);\n\n if (annotations.size () == 0)\n throw std::string (STRING_CMD_DENO_NONE);\n\n std::map <std::string, std::string>::iterator i;\n std::string anno;\n bool match = false;\n for (i = annotations.begin (); i != annotations.end (); ++i)\n {\n if (i->second == pattern)\n {\n match = true;\n anno = i->second;\n annotations.erase (i);\n task->setAnnotations (annotations);\n break;\n }\n }\n if (!match)\n {\n for (i = annotations.begin (); i != annotations.end (); ++i)\n {\n std::string::size_type loc = find (i->second, pattern, sensitive);\n if (loc != std::string::npos)\n {\n anno = i->second;\n annotations.erase (i);\n task->setAnnotations (annotations);\n break;\n }\n }\n }\n\n if (taskDiff (before, *task))\n {\n std::string question = format (STRING_CMD_DENO_CONFIRM,\n task->id,\n task->get (\"description\"));\n\n if (permission (*task, taskDifferences (before, *task) + question, filtered.size ()))\n {\n ++count;\n context.tdb2.modify (*task);\n feedback_affected (format (STRING_CMD_DENO_FOUND, anno));\n if (context.verbose (\"project\"))\n projectChanges[task->get (\"project\")] = onProjectChange (*task, false);\n }\n else\n {\n std::cout << STRING_CMD_DENO_NO << \"\\n\";\n rc = 1;\n if (_permission_quit)\n break;\n }\n }\n else\n {\n std::cout << format (STRING_CMD_DENO_NOMATCH, pattern) << \"\\n\";\n rc = 1;\n }\n }\n\n \/\/ Now list the project changes.\n std::map <std::string, std::string>::iterator i;\n for (i = projectChanges.begin (); i != projectChanges.end (); ++i)\n if (i->first != \"\")\n context.footnote (i->second);\n\n context.tdb2.commit ();\n feedback_affected (count == 1 ? STRING_CMD_DENO_1 : STRING_CMD_DENO_N, count);\n return rc;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n<|endoftext|>"} {"text":"<commit_before>\/* CUDA device function execution\n *\n * Copyright (C) 2007 Peter Colberg\n *\n * This program is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n\n#ifndef BOOST_PP_IS_ITERATING\n\n #ifndef CUDA_FUNCTION_HPP\n #define CUDA_FUNCTION_HPP\n\n #include <boost\/preprocessor\/iteration\/iterate.hpp>\n #include <boost\/preprocessor\/repetition\/enum_params.hpp>\n #include <boost\/preprocessor\/repetition\/enum_binary_params.hpp>\n #include <boost\/preprocessor\/repetition\/repeat.hpp>\n #include <cuda\/cuda_runtime.h>\n #ifndef __CUDACC__\n #include <cuda_wrapper\/error.hpp>\n #include <cuda_wrapper\/stream.hpp>\n #endif\n\n\n \/* maximum number of arguments passed to device functions *\/\n #ifndef CUDA_FUNCTION_MAX_ARGS\n #define CUDA_FUNCTION_MAX_ARGS 10\n #endif\n\n namespace cuda\n {\n\n \/*\n * CUDA execution configuration\n *\/\n class config\n {\n public:\n\t\/* grid dimensions *\/\n\tdim3 grid;\n\t\/* block dimensions *\/\n\tdim3 block;\n\t\/* FIXME store useful numbers (no. of threads per grid\/block) *\/\n\n\tconfig()\n\t{\n\t}\n\n\tconfig(dim3 grid, dim3 block) : grid(grid), block(block)\n\t{\n\t \/* FIXME store useful numbers (no. of threads per grid\/block) *\/\n\t}\n\n\tsize_t threads() const\n\t{\n\t return grid.y * grid.x * block.z * block.y * block.x;\n\t}\n\n\tsize_t blocks_per_grid() const\n\t{\n\t return grid.y * grid.x;\n\t}\n\n\tsize_t threads_per_block() const\n\t{\n\t return block.z * block.y * block.x;\n\t}\n };\n\n } \/\/ namespace cuda\n\n\n #define BOOST_PP_FILENAME_1 <cuda_wrapper\/function.hpp>\n #define BOOST_PP_ITERATION_LIMITS (1, CUDA_FUNCTION_MAX_ARGS)\n #include BOOST_PP_ITERATE()\n\n #endif \/* ! CUDA_FUNCTION_HPP *\/\n\n#else \/* ! BOOST_PP_IS_ITERATING *\/\n\n namespace cuda\n {\n\n template <typename T>\n class function;\n\n \/**\n * CUDA kernel execution wrapper for n-ary device function\n *\/\n template <BOOST_PP_ENUM_PARAMS(BOOST_PP_ITERATION(), typename T)>\n class function<void (BOOST_PP_ENUM_PARAMS(BOOST_PP_ITERATION(), T))>\n {\n public:\n\ttypedef void T (BOOST_PP_ENUM_PARAMS(BOOST_PP_ITERATION(), T));\n\n public:\n\tfunction(T *entry) : entry(entry) {}\n\n #ifndef __CUDACC__\n\n\t\/**\n\t * configure execution parameters\n\t *\/\n\tstatic void configure(config const& dim, size_t shared_mem = 0)\n\t{\n\t CUDA_CALL(cudaConfigureCall(dim.grid, dim.block, shared_mem, 0));\n\t}\n\n #ifdef CUDA_WRAPPER_ASYNC_API\n\t\/**\n\t * configure execution parameters\n\t *\/\n\tstatic void configure(config const& dim, stream& stream)\n\t{\n\t CUDA_CALL(cudaConfigureCall(dim.grid, dim.block, 0, stream.data()));\n\t}\n\n\t\/**\n\t * configure execution parameters\n\t *\/\n\tstatic void configure(config const& dim, size_t shared_mem, stream& stream)\n\t{\n\t CUDA_CALL(cudaConfigureCall(dim.grid, dim.block, shared_mem, stream.data()));\n\t}\n #endif \/* CUDA_WRAPPER_ASYNC_API *\/\n\n\t\/**\n\t * execute kernel\n\t *\/\n\tvoid operator()(BOOST_PP_ENUM_BINARY_PARAMS(BOOST_PP_ITERATION(), T, const& x))\n\t{\n\t size_t offset = 0;\n #define SETUP_ARGUMENT(z, n, x) setup_argument(x##n, offset);\n\t BOOST_PP_REPEAT(BOOST_PP_ITERATION(), SETUP_ARGUMENT, x)\n #undef SETUP_ARGUMENT\n\t CUDA_CALL(cudaLaunch(reinterpret_cast<const char *>(entry)));\n\t}\n\n private:\n\t\/**\n\t * push arbitrary argument into argument passing area\n\t *\/\n\ttemplate <typename U>\n\tstatic void setup_argument(U const& arg, size_t& offset)\n\t{\n\t \/* respect alignment requirements of passed argument *\/\n\t if (0 != offset % __alignof(U)) {\n\t\toffset += __alignof(U) - offset % __alignof(U);\n\t }\n\n\t CUDA_CALL(cudaSetupArgument(&arg, sizeof(U), offset));\n\n\t \/* advance argument offset for next call *\/\n\t offset += sizeof(U);\n\t}\n\n #endif \/* ! __CUDACC__ *\/\n\n private:\n\tT *entry;\n };\n\n } \/\/ namespace cuda\n\n#endif \/* ! BOOST_PP_IS_ITERATING *\/\n<commit_msg>Remove CUDA execution preparation from CUDA device function template<commit_after>\/* CUDA device function execution\n *\n * Copyright (C) 2007 Peter Colberg\n *\n * This program is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n\n#ifndef BOOST_PP_IS_ITERATING\n\n #ifndef CUDA_FUNCTION_HPP\n #define CUDA_FUNCTION_HPP\n\n #include <boost\/preprocessor\/iteration\/iterate.hpp>\n #include <boost\/preprocessor\/repetition\/enum_params.hpp>\n #include <boost\/preprocessor\/repetition\/enum_binary_params.hpp>\n #include <boost\/preprocessor\/repetition\/repeat.hpp>\n #include <cuda\/cuda_runtime.h>\n #ifndef __CUDACC__\n #include <cuda_wrapper\/error.hpp>\n #include <cuda_wrapper\/stream.hpp>\n #endif\n\n\n \/* maximum number of arguments passed to device functions *\/\n #ifndef CUDA_FUNCTION_MAX_ARGS\n #define CUDA_FUNCTION_MAX_ARGS 10\n #endif\n\n namespace cuda\n {\n\n \/*\n * CUDA execution configuration\n *\/\n class config\n {\n public:\n\t\/* grid dimensions *\/\n\tdim3 grid;\n\t\/* block dimensions *\/\n\tdim3 block;\n\t\/* FIXME store useful numbers (no. of threads per grid\/block) *\/\n\n\tconfig()\n\t{\n\t}\n\n\tconfig(dim3 grid, dim3 block) : grid(grid), block(block)\n\t{\n\t \/* FIXME store useful numbers (no. of threads per grid\/block) *\/\n\t}\n\n\tsize_t threads() const\n\t{\n\t return grid.y * grid.x * block.z * block.y * block.x;\n\t}\n\n\tsize_t blocks_per_grid() const\n\t{\n\t return grid.y * grid.x;\n\t}\n\n\tsize_t threads_per_block() const\n\t{\n\t return block.z * block.y * block.x;\n\t}\n };\n\n #ifndef __CUDACC__\n\n \/**\n * configure execution parameters\n *\/\n __inline__ void configure(dim3 const& grid, dim3 const& block, size_t shared_mem = 0)\n {\n\tCUDA_CALL(cudaConfigureCall(grid, block, shared_mem, 0));\n }\n\n #ifdef CUDA_WRAPPER_ASYNC_API\n \/**\n * configure execution parameters\n *\/\n __inline__ void configure(dim3 const& grid, dim3 const& block, stream& stream)\n {\n\tCUDA_CALL(cudaConfigureCall(grid, block, 0, stream.data()));\n }\n\n \/**\n * configure execution parameters\n *\/\n __inline__ void configure(dim3 const& grid, dim3 const& block, size_t shared_mem, stream& stream)\n {\n\tCUDA_CALL(cudaConfigureCall(grid, block, shared_mem, stream.data()));\n }\n #endif \/* CUDA_WRAPPER_ASYNC_API *\/\n\n #endif \/* ! __CUDACC__ *\/\n\n } \/\/ namespace cuda\n\n\n #define BOOST_PP_FILENAME_1 <cuda_wrapper\/function.hpp>\n #define BOOST_PP_ITERATION_LIMITS (1, CUDA_FUNCTION_MAX_ARGS)\n #include BOOST_PP_ITERATE()\n\n #endif \/* ! CUDA_FUNCTION_HPP *\/\n\n#else \/* ! BOOST_PP_IS_ITERATING *\/\n\n namespace cuda\n {\n\n template <typename T>\n class function;\n\n \/**\n * CUDA kernel execution wrapper for n-ary device function\n *\/\n template <BOOST_PP_ENUM_PARAMS(BOOST_PP_ITERATION(), typename T)>\n class function<void (BOOST_PP_ENUM_PARAMS(BOOST_PP_ITERATION(), T))>\n {\n public:\n\ttypedef void T (BOOST_PP_ENUM_PARAMS(BOOST_PP_ITERATION(), T));\n\n public:\n\tfunction(T *entry) : entry(entry) {}\n\n #ifndef __CUDACC__\n\n\t\/**\n\t * execute kernel\n\t *\/\n\tvoid operator()(BOOST_PP_ENUM_BINARY_PARAMS(BOOST_PP_ITERATION(), T, const& x))\n\t{\n\t size_t offset = 0;\n #define SETUP_ARGUMENT(z, n, x) setup_argument(x##n, offset);\n\t BOOST_PP_REPEAT(BOOST_PP_ITERATION(), SETUP_ARGUMENT, x)\n #undef SETUP_ARGUMENT\n\t CUDA_CALL(cudaLaunch(reinterpret_cast<const char *>(entry)));\n\t}\n\n private:\n\t\/**\n\t * push arbitrary argument into argument passing area\n\t *\/\n\ttemplate <typename U>\n\tstatic void setup_argument(U const& arg, size_t& offset)\n\t{\n\t \/* respect alignment requirements of passed argument *\/\n\t if (0 != offset % __alignof(U)) {\n\t\toffset += __alignof(U) - offset % __alignof(U);\n\t }\n\n\t CUDA_CALL(cudaSetupArgument(&arg, sizeof(U), offset));\n\n\t \/* advance argument offset for next call *\/\n\t offset += sizeof(U);\n\t}\n\n #endif \/* ! __CUDACC__ *\/\n\n private:\n\tT *entry;\n };\n\n } \/\/ namespace cuda\n\n#endif \/* ! BOOST_PP_IS_ITERATING *\/\n<|endoftext|>"} {"text":"<commit_before>\/\/+ Example of a simple script creating 2 threads each with one canvas.\n\/\/ This script can only be executed via ACliC .x threadsh2.C++.\n\/\/ The canvases are saved in a animated gif file.\n\n#include \"TROOT.h\"\n#include \"TCanvas.h\"\n#include \"TRootCanvas.h\"\n#include \"TFrame.h\"\n#include \"TH1F.h\"\n#include \"TRandom.h\"\n#include \"TThread.h\"\n#include \"TMethodCall.h\"\n\nTCanvas *c1, *c2;\nTH1F *hpx, *total, *hmain, *s1, *s2;\nTThread *thread1, *thread2, *threadj;\nBool_t finished;\n\nvoid *handle1(void *)\n{\n int nfills = 10000;\n int upd = 500;\n\n TThread::Lock();\n hpx = new TH1F(\"hpx\", \"This is the px distribution\", 100, -4, 4);\n hpx->SetFillColor(48);\n TThread::UnLock();\n Float_t px, py, pz;\n gRandom->SetSeed();\n for (Int_t i = 0; i < nfills; i++) {\n gRandom->Rannor(px, py);\n pz = px*px + py*py;\n hpx->Fill(px);\n if (i && (i%upd) == 0) {\n if (i == upd) {\n c1->cd();\n hpx->Draw();\n }\n c1->Modified();\n c1->Update();\n gSystem->Sleep(10);\n TMethodCall c(c1->IsA(), \"Print\", \"\");\n void *arr[4];\n arr[1] = &c;\n arr[2] = (void *)c1;\n arr[3] = (void*)\"\\\"hpxanim.gif+50\\\"\";\n (*gThreadXAR)(\"METH\", 4, arr, NULL);\n }\n }\n c1->Modified();\n c1->Update();\n TMethodCall c(c1->IsA(), \"Print\", \"\");\n void *arr[4];\n arr[1] = &c;\n arr[2] = (void *)c1;\n arr[3] = (void*)\"\\\"hpxanim.gif++\\\"\";\n (*gThreadXAR)(\"METH\", 4, arr, NULL);\n return 0;\n}\n\nvoid *handle2(void *)\n{\n int nfills = 10000;\n int upd = 500;\n\n TThread::Lock();\n total = new TH1F(\"total\",\"This is the total distribution\",100,-4,4);\n hmain = new TH1F(\"hmain\",\"Main contributor\",100,-4,4);\n s1 = new TH1F(\"s1\",\"This is the first signal\",100,-4,4);\n s2 = new TH1F(\"s2\",\"This is the second signal\",100,-4,4);\n total->Sumw2(); \/\/ this makes sure that the sum of squares of weights will be stored\n total->SetMarkerStyle(21);\n total->SetMarkerSize(0.7);\n hmain->SetFillColor(16);\n s1->SetFillColor(42);\n s2->SetFillColor(46);\n TThread::UnLock();\n Float_t xs1, xs2, xmain;\n gRandom->SetSeed();\n for (Int_t i = 0; i < nfills; i++) {\n xmain = gRandom->Gaus(-1,1.5);\n xs1 = gRandom->Gaus(-0.5,0.5);\n xs2 = gRandom->Landau(1,0.15);\n hmain->Fill(xmain);\n s1->Fill(xs1,0.3);\n s2->Fill(xs2,0.2);\n total->Fill(xmain);\n total->Fill(xs1,0.3);\n total->Fill(xs2,0.2);\n if (i && (i%upd) == 0) {\n if (i == upd) {\n c2->cd();\n total->Draw(\"e1p\");\n hmain->Draw(\"same\");\n s1->Draw(\"same\");\n s2->Draw(\"same\");\n }\n c2->Modified();\n c2->Update();\n gSystem->Sleep(10);\n TMethodCall c(c2->IsA(), \"Print\", \"\");\n void *arr[4];\n arr[1] = &c;\n arr[2] = (void *)c2;\n arr[3] = (void*)\"\\\"hsumanim.gif+50\\\"\";\n (*gThreadXAR)(\"METH\", 4, arr, NULL);\n }\n }\n total->Draw(\"sameaxis\"); \/\/ to redraw axis hidden by the fill area\n c2->Modified();\n c2->Update();\n \/\/ make infinite animation by adding \"++\" to the file name\n TMethodCall c(c2->IsA(), \"Print\", \"\");\n void *arr[4];\n arr[1] = &c;\n arr[2] = (void *)c2;\n arr[3] = (void*)\"\\\"hsumanim.gif++\\\"\";\n (*gThreadXAR)(\"METH\", 4, arr, NULL);\n return 0;\n}\n\nvoid *joiner(void *)\n{\n thread1->Join();\n thread2->Join();\n\n finished = kTRUE;\n\n return 0;\n}\n\nvoid tryclosing(Int_t id)\n{\n \/\/ allow to close the canvas only after the threads are done\n if (!finished) return;\n if (id == 1) ((TRootCanvas *)c1->GetCanvasImp())->CloseWindow();\n else if (id == 2) ((TRootCanvas *)c2->GetCanvasImp())->CloseWindow();\n}\n\nvoid threadsh2()\n{\n#ifdef __CINT__\n printf(\"This script can only be executed via ACliC: .x threadsh2.C++\\n\");\n return;\n#endif\n\n c1 = new TCanvas(\"c1\",\"Dynamic Filling Example\", 100, 30, 400, 300);\n c1->SetFillColor(42);\n c1->GetFrame()->SetFillColor(21);\n c1->GetFrame()->SetBorderSize(6);\n c1->GetFrame()->SetBorderMode(-1);\n \/\/ connect to the CloseWindow() signal and prevent to close the canvas \n \/\/ while the thread is running\n ((TRootCanvas *)c1->GetCanvasImp())->Connect(\"CloseWindow()\", 0, 0, \n \"tryclosing(Int_t=1)\");\n ((TRootCanvas *)c1->GetCanvasImp())->DontCallClose();\n\n c2 = new TCanvas(\"c2\",\"Dynamic Filling Example\", 515, 30, 400, 300);\n c2->SetGrid();\n \/\/ connect to the CloseWindow() signal and prevent to close the canvas \n \/\/ while the thread is running\n ((TRootCanvas *)c2->GetCanvasImp())->Connect(\"CloseWindow()\", 0, 0, \n \"tryclosing(Int_t=2)\");\n ((TRootCanvas *)c2->GetCanvasImp())->DontCallClose();\n\n finished = kFALSE;\n \/\/gDebug = 1;\n gSystem->Unlink(\"hpxanim.gif\");\n gSystem->Unlink(\"hsumanim.gif\");\n\n printf(\"Starting Thread 0\\n\");\n thread1 = new TThread(\"t0\", handle1, (void*) 0);\n thread1->Run();\n printf(\"Starting Thread 1\\n\");\n thread2 = new TThread(\"t1\", handle2, (void*) 1);\n thread2->Run();\n printf(\"Starting Joiner Thread \\n\");\n threadj = new TThread(\"t4\", joiner, (void*) 3);\n threadj->Run();\n\n TThread::Ps();\n\n while (!finished) {\n gSystem->Sleep(100);\n gSystem->ProcessEvents();\n }\n\n threadj->Join();\n TThread::Ps();\n\n delete thread1;\n delete thread2;\n delete threadj;\n}\n<commit_msg>threadsh2 must be run in interactive ... nonetheless succeed (do nothing) in batch mode<commit_after>\/\/+ Example of a simple script creating 2 threads each with one canvas.\n\/\/ This script can only be executed via ACliC .x threadsh2.C++.\n\/\/ The canvases are saved in a animated gif file.\n\n#include \"TROOT.h\"\n#include \"TCanvas.h\"\n#include \"TRootCanvas.h\"\n#include \"TFrame.h\"\n#include \"TH1F.h\"\n#include \"TRandom.h\"\n#include \"TThread.h\"\n#include \"TMethodCall.h\"\n\nTCanvas *c1, *c2;\nTH1F *hpx, *total, *hmain, *s1, *s2;\nTThread *thread1, *thread2, *threadj;\nBool_t finished;\n\nvoid *handle1(void *)\n{\n int nfills = 10000;\n int upd = 500;\n\n TThread::Lock();\n hpx = new TH1F(\"hpx\", \"This is the px distribution\", 100, -4, 4);\n hpx->SetFillColor(48);\n TThread::UnLock();\n Float_t px, py, pz;\n gRandom->SetSeed();\n for (Int_t i = 0; i < nfills; i++) {\n gRandom->Rannor(px, py);\n pz = px*px + py*py;\n hpx->Fill(px);\n if (i && (i%upd) == 0) {\n if (i == upd) {\n c1->cd();\n hpx->Draw();\n }\n c1->Modified();\n c1->Update();\n gSystem->Sleep(10);\n TMethodCall c(c1->IsA(), \"Print\", \"\");\n void *arr[4];\n arr[1] = &c;\n arr[2] = (void *)c1;\n arr[3] = (void*)\"\\\"hpxanim.gif+50\\\"\";\n (*gThreadXAR)(\"METH\", 4, arr, NULL);\n }\n }\n c1->Modified();\n c1->Update();\n TMethodCall c(c1->IsA(), \"Print\", \"\");\n void *arr[4];\n arr[1] = &c;\n arr[2] = (void *)c1;\n arr[3] = (void*)\"\\\"hpxanim.gif++\\\"\";\n (*gThreadXAR)(\"METH\", 4, arr, NULL);\n return 0;\n}\n\nvoid *handle2(void *)\n{\n int nfills = 10000;\n int upd = 500;\n\n TThread::Lock();\n total = new TH1F(\"total\",\"This is the total distribution\",100,-4,4);\n hmain = new TH1F(\"hmain\",\"Main contributor\",100,-4,4);\n s1 = new TH1F(\"s1\",\"This is the first signal\",100,-4,4);\n s2 = new TH1F(\"s2\",\"This is the second signal\",100,-4,4);\n total->Sumw2(); \/\/ this makes sure that the sum of squares of weights will be stored\n total->SetMarkerStyle(21);\n total->SetMarkerSize(0.7);\n hmain->SetFillColor(16);\n s1->SetFillColor(42);\n s2->SetFillColor(46);\n TThread::UnLock();\n Float_t xs1, xs2, xmain;\n gRandom->SetSeed();\n for (Int_t i = 0; i < nfills; i++) {\n xmain = gRandom->Gaus(-1,1.5);\n xs1 = gRandom->Gaus(-0.5,0.5);\n xs2 = gRandom->Landau(1,0.15);\n hmain->Fill(xmain);\n s1->Fill(xs1,0.3);\n s2->Fill(xs2,0.2);\n total->Fill(xmain);\n total->Fill(xs1,0.3);\n total->Fill(xs2,0.2);\n if (i && (i%upd) == 0) {\n if (i == upd) {\n c2->cd();\n total->Draw(\"e1p\");\n hmain->Draw(\"same\");\n s1->Draw(\"same\");\n s2->Draw(\"same\");\n }\n c2->Modified();\n c2->Update();\n gSystem->Sleep(10);\n TMethodCall c(c2->IsA(), \"Print\", \"\");\n void *arr[4];\n arr[1] = &c;\n arr[2] = (void *)c2;\n arr[3] = (void*)\"\\\"hsumanim.gif+50\\\"\";\n (*gThreadXAR)(\"METH\", 4, arr, NULL);\n }\n }\n total->Draw(\"sameaxis\"); \/\/ to redraw axis hidden by the fill area\n c2->Modified();\n c2->Update();\n \/\/ make infinite animation by adding \"++\" to the file name\n TMethodCall c(c2->IsA(), \"Print\", \"\");\n void *arr[4];\n arr[1] = &c;\n arr[2] = (void *)c2;\n arr[3] = (void*)\"\\\"hsumanim.gif++\\\"\";\n (*gThreadXAR)(\"METH\", 4, arr, NULL);\n return 0;\n}\n\nvoid *joiner(void *)\n{\n thread1->Join();\n thread2->Join();\n\n finished = kTRUE;\n\n return 0;\n}\n\nvoid tryclosing(Int_t id)\n{\n \/\/ allow to close the canvas only after the threads are done\n if (!finished) return;\n if (id == 1) ((TRootCanvas *)c1->GetCanvasImp())->CloseWindow();\n else if (id == 2) ((TRootCanvas *)c2->GetCanvasImp())->CloseWindow();\n}\n\n#include \"TClass.h\"\n\nvoid threadsh2()\n{\n#ifdef __CINT__\n printf(\"This script can only be executed via ACliC: .x threadsh2.C++\\n\");\n return;\n#endif\n\n if (gROOT->IsBatch()) {\n return;\n }\n c1 = new TCanvas(\"c1\",\"Dynamic Filling Example\", 100, 30, 400, 300);\n c1->SetFillColor(42);\n c1->GetFrame()->SetFillColor(21);\n c1->GetFrame()->SetBorderSize(6);\n c1->GetFrame()->SetBorderMode(-1);\n \/\/ connect to the CloseWindow() signal and prevent to close the canvas \n \/\/ while the thread is running\n TRootCanvas *rc = dynamic_cast<TRootCanvas*>(c1->GetCanvasImp());\n if (!rc) return;\n\n rc->Connect(\"CloseWindow()\", 0, 0,\n \"tryclosing(Int_t=1)\");\n rc->DontCallClose();\n\n c2 = new TCanvas(\"c2\",\"Dynamic Filling Example\", 515, 30, 400, 300);\n c2->SetGrid();\n \/\/ connect to the CloseWindow() signal and prevent to close the canvas \n \/\/ while the thread is running\n rc = dynamic_cast<TRootCanvas*>(c2->GetCanvasImp());\n if (!rc) return;\n rc->Connect(\"CloseWindow()\", 0, 0,\n \"tryclosing(Int_t=2)\");\n rc->DontCallClose();\n\n finished = kFALSE;\n \/\/gDebug = 1;\n gSystem->Unlink(\"hpxanim.gif\");\n gSystem->Unlink(\"hsumanim.gif\");\n\n printf(\"Starting Thread 0\\n\");\n thread1 = new TThread(\"t0\", handle1, (void*) 0);\n thread1->Run();\n printf(\"Starting Thread 1\\n\");\n thread2 = new TThread(\"t1\", handle2, (void*) 1);\n thread2->Run();\n printf(\"Starting Joiner Thread \\n\");\n threadj = new TThread(\"t4\", joiner, (void*) 3);\n threadj->Run();\n\n TThread::Ps();\n\n while (!finished) {\n gSystem->Sleep(100);\n gSystem->ProcessEvents();\n }\n\n threadj->Join();\n TThread::Ps();\n\n delete thread1;\n delete thread2;\n delete threadj;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/test\/in_process_browser_test.h\"\n\n#include \"base\/command_line.h\"\n#include \"base\/file_path.h\"\n#include \"base\/file_util.h\"\n#include \"base\/path_service.h\"\n#include \"base\/scoped_nsautorelease_pool.h\"\n#include \"base\/string_number_conversions.h\"\n#include \"base\/test\/test_file_util.h\"\n#include \"chrome\/browser\/browser.h\"\n#include \"chrome\/browser\/browser_list.h\"\n#include \"chrome\/browser\/browser_process.h\"\n#include \"chrome\/browser\/browser_shutdown.h\"\n#include \"chrome\/browser\/browser_window.h\"\n#include \"chrome\/browser\/chrome_thread.h\"\n#include \"chrome\/browser\/intranet_redirect_detector.h\"\n#include \"chrome\/browser\/io_thread.h\"\n#include \"chrome\/browser\/net\/url_request_mock_util.h\"\n#include \"chrome\/browser\/profile.h\"\n#include \"chrome\/browser\/profile_manager.h\"\n#include \"chrome\/browser\/renderer_host\/render_process_host.h\"\n#include \"chrome\/browser\/tab_contents\/tab_contents.h\"\n#if defined(OS_WIN)\n#include \"chrome\/browser\/views\/frame\/browser_view.h\"\n#endif\n#include \"chrome\/common\/chrome_constants.h\"\n#include \"chrome\/common\/chrome_paths.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/common\/main_function_params.h\"\n#include \"chrome\/common\/notification_registrar.h\"\n#include \"chrome\/common\/notification_type.h\"\n#include \"chrome\/common\/url_constants.h\"\n#include \"chrome\/test\/testing_browser_process.h\"\n#include \"chrome\/test\/ui_test_utils.h\"\n#include \"net\/base\/mock_host_resolver.h\"\n#include \"net\/test\/test_server.h\"\n#include \"sandbox\/src\/dep.h\"\n\n#if defined(OS_LINUX)\n#include \"base\/singleton.h\"\n#include \"chrome\/browser\/renderer_host\/render_sandbox_host_linux.h\"\n#include \"chrome\/browser\/zygote_host_linux.h\"\n\nnamespace {\n\n\/\/ A helper class to do Linux-only initialization only once per process.\nclass LinuxHostInit {\n public:\n LinuxHostInit() {\n RenderSandboxHostLinux* shost = Singleton<RenderSandboxHostLinux>::get();\n shost->Init(\"\");\n ZygoteHost* zhost = Singleton<ZygoteHost>::get();\n zhost->Init(\"\");\n }\n ~LinuxHostInit() {}\n};\n\n} \/\/ namespace\n#endif\n\nextern int BrowserMain(const MainFunctionParams&);\n\nconst wchar_t kUnitTestShowWindows[] = L\"show-windows\";\n\n\/\/ Passed as value of kTestType.\nstatic const char kBrowserTestType[] = \"browser\";\n\n\/\/ Default delay for the time-out at which we stop the\n\/\/ inner-message loop the first time.\nconst int kInitialTimeoutInMS = 30000;\n\n\/\/ Delay for sub-sequent time-outs once the initial time-out happened.\nconst int kSubsequentTimeoutInMS = 5000;\n\nInProcessBrowserTest::InProcessBrowserTest()\n : browser_(NULL),\n test_server_(net::TestServer::TYPE_HTTP,\n FilePath(FILE_PATH_LITERAL(\"chrome\/test\/data\"))),\n show_window_(false),\n dom_automation_enabled_(false),\n tab_closeable_state_watcher_enabled_(false),\n original_single_process_(false),\n initial_timeout_(kInitialTimeoutInMS) {\n}\n\nInProcessBrowserTest::~InProcessBrowserTest() {\n}\n\nvoid InProcessBrowserTest::SetUp() {\n \/\/ Cleanup the user data dir.\n FilePath user_data_dir;\n PathService::Get(chrome::DIR_USER_DATA, &user_data_dir);\n ASSERT_LT(10, static_cast<int>(user_data_dir.value().size())) <<\n \"The user data directory name passed into this test was too \"\n \"short to delete safely. Please check the user-data-dir \"\n \"argument and try again.\";\n ASSERT_TRUE(file_util::DieFileDie(user_data_dir, true));\n\n \/\/ Recreate the user data dir. (PathService::Get guarantees that the directory\n \/\/ exists if it returns true, but it only actually checks on the first call,\n \/\/ the rest are cached. Thus we need to recreate it ourselves to not break\n \/\/ the PathService guarantee.)\n ASSERT_TRUE(file_util::CreateDirectory(user_data_dir));\n\n \/\/ The unit test suite creates a testingbrowser, but we want the real thing.\n \/\/ Delete the current one. We'll install the testing one in TearDown.\n delete g_browser_process;\n g_browser_process = NULL;\n\n SetUpUserDataDirectory();\n\n \/\/ Don't delete the resources when BrowserMain returns. Many ui classes\n \/\/ cache SkBitmaps in a static field so that if we delete the resource\n \/\/ bundle we'll crash.\n browser_shutdown::delete_resources_on_shutdown = false;\n\n \/\/ Remember the command line. Normally this doesn't matter, because the test\n \/\/ harness creates a new process for each test, but when the test harness is\n \/\/ running in single process mode, we can't let one test's command-line\n \/\/ changes (e.g. enabling DOM automation) affect other tests.\n CommandLine* command_line = CommandLine::ForCurrentProcessMutable();\n original_command_line_.reset(new CommandLine(*command_line));\n\n SetUpCommandLine(command_line);\n\n#if defined(OS_WIN)\n \/\/ Hide windows on show.\n if (!command_line->HasSwitch(kUnitTestShowWindows) && !show_window_)\n BrowserView::SetShowState(SW_HIDE);\n#endif\n\n if (dom_automation_enabled_)\n command_line->AppendSwitch(switches::kDomAutomationController);\n\n \/\/ Turn off tip loading for tests; see http:\/\/crbug.com\/17725\n command_line->AppendSwitch(switches::kDisableWebResources);\n\n command_line->AppendSwitchPath(switches::kUserDataDir, user_data_dir);\n\n \/\/ Don't show the first run ui.\n command_line->AppendSwitch(switches::kNoFirstRun);\n\n \/\/ This is a Browser test.\n command_line->AppendSwitchASCII(switches::kTestType, kBrowserTestType);\n\n \/\/ Single-process mode is not set in BrowserMain so it needs to be processed\n \/\/ explicitly.\n original_single_process_ = RenderProcessHost::run_renderer_in_process();\n if (command_line->HasSwitch(switches::kSingleProcess))\n RenderProcessHost::set_run_renderer_in_process(true);\n\n#if defined(OS_WIN)\n \/\/ The Windows sandbox requires that the browser and child processes are the\n \/\/ same binary. So we launch browser_process.exe which loads chrome.dll\n command_line->AppendSwitchPath(switches::kBrowserSubprocessPath,\n command_line->GetProgram());\n#else\n \/\/ Explicitly set the path of the binary used for child processes, otherwise\n \/\/ they'll try to use browser_tests which doesn't contain ChromeMain.\n FilePath subprocess_path;\n PathService::Get(base::FILE_EXE, &subprocess_path);\n subprocess_path = subprocess_path.DirName();\n subprocess_path = subprocess_path.AppendASCII(WideToASCII(\n chrome::kBrowserProcessExecutablePath));\n#if defined(OS_MACOSX)\n \/\/ Recreate the real environment, run the helper within the app bundle.\n subprocess_path = subprocess_path.DirName().DirName();\n DCHECK_EQ(subprocess_path.BaseName().value(), \"Contents\");\n subprocess_path =\n subprocess_path.Append(\"Versions\").Append(chrome::kChromeVersion);\n subprocess_path =\n subprocess_path.Append(chrome::kHelperProcessExecutablePath);\n#endif\n command_line->AppendSwitchPath(switches::kBrowserSubprocessPath,\n subprocess_path);\n#endif\n\n \/\/ Enable warning level logging so that we can see when bad stuff happens.\n command_line->AppendSwitch(switches::kEnableLogging);\n command_line->AppendSwitchASCII(switches::kLoggingLevel, \"1\"); \/\/ warning\n\n \/\/ If ncecessary, disable TabCloseableStateWatcher.\n if (!tab_closeable_state_watcher_enabled_)\n command_line->AppendSwitch(switches::kDisableTabCloseableStateWatcher);\n\n SandboxInitWrapper sandbox_wrapper;\n MainFunctionParams params(*command_line, sandbox_wrapper, NULL);\n params.ui_task =\n NewRunnableMethod(this, &InProcessBrowserTest::RunTestOnMainThreadLoop);\n\n host_resolver_ = new net::RuleBasedHostResolverProc(\n new IntranetRedirectHostResolverProc(NULL));\n\n \/\/ Something inside the browser does this lookup implicitly. Make it fail\n \/\/ to avoid external dependency. It won't break the tests.\n host_resolver_->AddSimulatedFailure(\"*.google.com\");\n\n \/\/ See http:\/\/en.wikipedia.org\/wiki\/Web_Proxy_Autodiscovery_Protocol\n \/\/ We don't want the test code to use it.\n host_resolver_->AddSimulatedFailure(\"wpad\");\n\n net::ScopedDefaultHostResolverProc scoped_host_resolver_proc(\n host_resolver_.get());\n\n SetUpInProcessBrowserTestFixture();\n\n \/\/ Before we run the browser, we have to hack the path to the exe to match\n \/\/ what it would be if Chrome was running, because it is used to fork renderer\n \/\/ processes, on Linux at least (failure to do so will cause a browser_test to\n \/\/ be run instead of a renderer).\n FilePath chrome_path;\n CHECK(PathService::Get(base::FILE_EXE, &chrome_path));\n chrome_path = chrome_path.DirName();\n#if defined(OS_WIN)\n chrome_path = chrome_path.Append(chrome::kBrowserProcessExecutablePath);\n#elif defined(OS_POSIX)\n chrome_path = chrome_path.Append(\n WideToASCII(chrome::kBrowserProcessExecutablePath));\n#endif\n CHECK(PathService::Override(base::FILE_EXE, chrome_path));\n\n#if defined(OS_LINUX)\n \/\/ Initialize the RenderSandbox and Zygote hosts. Apparently they get used\n \/\/ for InProcessBrowserTest, and this is not the normal browser startup path.\n Singleton<LinuxHostInit>::get();\n#endif\n\n BrowserMain(params);\n TearDownInProcessBrowserTestFixture();\n}\n\nvoid InProcessBrowserTest::TearDown() {\n \/\/ Reinstall testing browser process.\n delete g_browser_process;\n g_browser_process = new TestingBrowserProcess();\n\n browser_shutdown::delete_resources_on_shutdown = true;\n\n#if defined(OS_WIN)\n BrowserView::SetShowState(-1);\n#endif\n\n *CommandLine::ForCurrentProcessMutable() = *original_command_line_;\n RenderProcessHost::set_run_renderer_in_process(original_single_process_);\n}\n\n\/\/ Creates a browser with a single tab (about:blank), waits for the tab to\n\/\/ finish loading and shows the browser.\nBrowser* InProcessBrowserTest::CreateBrowser(Profile* profile) {\n Browser* browser = Browser::Create(profile);\n\n browser->AddTabWithURL(GURL(chrome::kAboutBlankURL), GURL(),\n PageTransition::START_PAGE, -1,\n TabStripModel::ADD_SELECTED, NULL, std::string(),\n &browser);\n\n \/\/ Wait for the page to finish loading.\n ui_test_utils::WaitForNavigation(\n &browser->GetSelectedTabContents()->controller());\n\n browser->window()->Show();\n\n return browser;\n}\n\nvoid InProcessBrowserTest::RunTestOnMainThreadLoop() {\n \/\/ On Mac, without the following autorelease pool, code which is directly\n \/\/ executed (as opposed to executed inside a message loop) would autorelease\n \/\/ objects into a higher-level pool. This pool is not recycled in-sync with\n \/\/ the message loops' pools and causes problems with code relying on\n \/\/ deallocation via an autorelease pool (such as browser window closure and\n \/\/ browser shutdown). To avoid this, the following pool is recycled after each\n \/\/ time code is directly executed.\n base::ScopedNSAutoreleasePool pool;\n\n \/\/ Pump startup related events.\n MessageLoopForUI::current()->RunAllPending();\n\n \/\/ In the long term it would be great if we could use a TestingProfile\n \/\/ here and only enable services you want tested, but that requires all\n \/\/ consumers of Profile to handle NULL services.\n Profile* profile = ProfileManager::GetDefaultProfile();\n if (!profile) {\n \/\/ We should only be able to get here if the profile already exists and\n \/\/ has been created.\n NOTREACHED();\n return;\n }\n pool.Recycle();\n\n ChromeThread::PostTask(\n ChromeThread::IO, FROM_HERE,\n NewRunnableFunction(chrome_browser_net::SetUrlRequestMocksEnabled, true));\n\n browser_ = CreateBrowser(profile);\n pool.Recycle();\n\n \/\/ Start the timeout timer to prevent hangs.\n MessageLoopForUI::current()->PostDelayedTask(FROM_HERE,\n NewRunnableMethod(this, &InProcessBrowserTest::TimedOut),\n initial_timeout_);\n\n \/\/ Pump any pending events that were created as a result of creating a\n \/\/ browser.\n MessageLoopForUI::current()->RunAllPending();\n\n RunTestOnMainThread();\n pool.Recycle();\n\n CleanUpOnMainThread();\n pool.Recycle();\n\n QuitBrowsers();\n pool.Recycle();\n}\n\nvoid InProcessBrowserTest::QuitBrowsers() {\n if (BrowserList::size() == 0)\n return;\n\n \/\/ Invoke CloseAllBrowsersAndExit on a running message loop.\n \/\/ CloseAllBrowsersAndExit exits the message loop after everything has been\n \/\/ shut down properly.\n MessageLoopForUI::current()->PostTask(\n FROM_HERE,\n NewRunnableFunction(&BrowserList::CloseAllBrowsersAndExit));\n ui_test_utils::RunMessageLoop();\n}\n\nvoid InProcessBrowserTest::TimedOut() {\n std::string error_message = \"Test timed out. Each test runs for a max of \";\n error_message += base::IntToString(initial_timeout_);\n error_message += \" ms (kInitialTimeoutInMS).\";\n\n MessageLoopForUI::current()->Quit();\n\n \/\/ WARNING: This must be after Quit as it returns.\n FAIL() << error_message;\n}\n\nvoid InProcessBrowserTest::SetInitialTimeoutInMS(int timeout_value) {\n DCHECK_GT(timeout_value, 0);\n initial_timeout_ = timeout_value;\n}\n<commit_msg>The browser tests seem to fail with preconnects; the python server crashes. Preconnect seems to be working properly.<commit_after>\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/test\/in_process_browser_test.h\"\n\n#include \"base\/command_line.h\"\n#include \"base\/file_path.h\"\n#include \"base\/file_util.h\"\n#include \"base\/path_service.h\"\n#include \"base\/scoped_nsautorelease_pool.h\"\n#include \"base\/string_number_conversions.h\"\n#include \"base\/test\/test_file_util.h\"\n#include \"chrome\/browser\/browser.h\"\n#include \"chrome\/browser\/browser_list.h\"\n#include \"chrome\/browser\/browser_process.h\"\n#include \"chrome\/browser\/browser_shutdown.h\"\n#include \"chrome\/browser\/browser_window.h\"\n#include \"chrome\/browser\/chrome_thread.h\"\n#include \"chrome\/browser\/intranet_redirect_detector.h\"\n#include \"chrome\/browser\/io_thread.h\"\n#include \"chrome\/browser\/net\/url_request_mock_util.h\"\n#include \"chrome\/browser\/profile.h\"\n#include \"chrome\/browser\/profile_manager.h\"\n#include \"chrome\/browser\/renderer_host\/render_process_host.h\"\n#include \"chrome\/browser\/tab_contents\/tab_contents.h\"\n#if defined(OS_WIN)\n#include \"chrome\/browser\/views\/frame\/browser_view.h\"\n#endif\n#include \"chrome\/common\/chrome_constants.h\"\n#include \"chrome\/common\/chrome_paths.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/common\/main_function_params.h\"\n#include \"chrome\/common\/notification_registrar.h\"\n#include \"chrome\/common\/notification_type.h\"\n#include \"chrome\/common\/url_constants.h\"\n#include \"chrome\/test\/testing_browser_process.h\"\n#include \"chrome\/test\/ui_test_utils.h\"\n#include \"net\/base\/mock_host_resolver.h\"\n#include \"net\/test\/test_server.h\"\n#include \"sandbox\/src\/dep.h\"\n\n#if defined(OS_LINUX)\n#include \"base\/singleton.h\"\n#include \"chrome\/browser\/renderer_host\/render_sandbox_host_linux.h\"\n#include \"chrome\/browser\/zygote_host_linux.h\"\n\nnamespace {\n\n\/\/ A helper class to do Linux-only initialization only once per process.\nclass LinuxHostInit {\n public:\n LinuxHostInit() {\n RenderSandboxHostLinux* shost = Singleton<RenderSandboxHostLinux>::get();\n shost->Init(\"\");\n ZygoteHost* zhost = Singleton<ZygoteHost>::get();\n zhost->Init(\"\");\n }\n ~LinuxHostInit() {}\n};\n\n} \/\/ namespace\n#endif\n\nextern int BrowserMain(const MainFunctionParams&);\n\nconst wchar_t kUnitTestShowWindows[] = L\"show-windows\";\n\n\/\/ Passed as value of kTestType.\nstatic const char kBrowserTestType[] = \"browser\";\n\n\/\/ Default delay for the time-out at which we stop the\n\/\/ inner-message loop the first time.\nconst int kInitialTimeoutInMS = 30000;\n\n\/\/ Delay for sub-sequent time-outs once the initial time-out happened.\nconst int kSubsequentTimeoutInMS = 5000;\n\nInProcessBrowserTest::InProcessBrowserTest()\n : browser_(NULL),\n test_server_(net::TestServer::TYPE_HTTP,\n FilePath(FILE_PATH_LITERAL(\"chrome\/test\/data\"))),\n show_window_(false),\n dom_automation_enabled_(false),\n tab_closeable_state_watcher_enabled_(false),\n original_single_process_(false),\n initial_timeout_(kInitialTimeoutInMS) {\n}\n\nInProcessBrowserTest::~InProcessBrowserTest() {\n}\n\nvoid InProcessBrowserTest::SetUp() {\n \/\/ Cleanup the user data dir.\n FilePath user_data_dir;\n PathService::Get(chrome::DIR_USER_DATA, &user_data_dir);\n ASSERT_LT(10, static_cast<int>(user_data_dir.value().size())) <<\n \"The user data directory name passed into this test was too \"\n \"short to delete safely. Please check the user-data-dir \"\n \"argument and try again.\";\n ASSERT_TRUE(file_util::DieFileDie(user_data_dir, true));\n\n \/\/ Recreate the user data dir. (PathService::Get guarantees that the directory\n \/\/ exists if it returns true, but it only actually checks on the first call,\n \/\/ the rest are cached. Thus we need to recreate it ourselves to not break\n \/\/ the PathService guarantee.)\n ASSERT_TRUE(file_util::CreateDirectory(user_data_dir));\n\n \/\/ The unit test suite creates a testingbrowser, but we want the real thing.\n \/\/ Delete the current one. We'll install the testing one in TearDown.\n delete g_browser_process;\n g_browser_process = NULL;\n\n SetUpUserDataDirectory();\n\n \/\/ Don't delete the resources when BrowserMain returns. Many ui classes\n \/\/ cache SkBitmaps in a static field so that if we delete the resource\n \/\/ bundle we'll crash.\n browser_shutdown::delete_resources_on_shutdown = false;\n\n \/\/ Remember the command line. Normally this doesn't matter, because the test\n \/\/ harness creates a new process for each test, but when the test harness is\n \/\/ running in single process mode, we can't let one test's command-line\n \/\/ changes (e.g. enabling DOM automation) affect other tests.\n CommandLine* command_line = CommandLine::ForCurrentProcessMutable();\n original_command_line_.reset(new CommandLine(*command_line));\n\n SetUpCommandLine(command_line);\n\n#if defined(OS_WIN)\n \/\/ Hide windows on show.\n if (!command_line->HasSwitch(kUnitTestShowWindows) && !show_window_)\n BrowserView::SetShowState(SW_HIDE);\n#endif\n\n if (dom_automation_enabled_)\n command_line->AppendSwitch(switches::kDomAutomationController);\n\n \/\/ Turn off tip loading for tests; see http:\/\/crbug.com\/17725\n command_line->AppendSwitch(switches::kDisableWebResources);\n\n \/\/ Turn off preconnects because they break the brittle python webserver.\n command_line->AppendSwitch(switches::kDisablePreconnect);\n\n command_line->AppendSwitchPath(switches::kUserDataDir, user_data_dir);\n\n \/\/ Don't show the first run ui.\n command_line->AppendSwitch(switches::kNoFirstRun);\n\n \/\/ This is a Browser test.\n command_line->AppendSwitchASCII(switches::kTestType, kBrowserTestType);\n\n \/\/ Single-process mode is not set in BrowserMain so it needs to be processed\n \/\/ explicitly.\n original_single_process_ = RenderProcessHost::run_renderer_in_process();\n if (command_line->HasSwitch(switches::kSingleProcess))\n RenderProcessHost::set_run_renderer_in_process(true);\n\n#if defined(OS_WIN)\n \/\/ The Windows sandbox requires that the browser and child processes are the\n \/\/ same binary. So we launch browser_process.exe which loads chrome.dll\n command_line->AppendSwitchPath(switches::kBrowserSubprocessPath,\n command_line->GetProgram());\n#else\n \/\/ Explicitly set the path of the binary used for child processes, otherwise\n \/\/ they'll try to use browser_tests which doesn't contain ChromeMain.\n FilePath subprocess_path;\n PathService::Get(base::FILE_EXE, &subprocess_path);\n subprocess_path = subprocess_path.DirName();\n subprocess_path = subprocess_path.AppendASCII(WideToASCII(\n chrome::kBrowserProcessExecutablePath));\n#if defined(OS_MACOSX)\n \/\/ Recreate the real environment, run the helper within the app bundle.\n subprocess_path = subprocess_path.DirName().DirName();\n DCHECK_EQ(subprocess_path.BaseName().value(), \"Contents\");\n subprocess_path =\n subprocess_path.Append(\"Versions\").Append(chrome::kChromeVersion);\n subprocess_path =\n subprocess_path.Append(chrome::kHelperProcessExecutablePath);\n#endif\n command_line->AppendSwitchPath(switches::kBrowserSubprocessPath,\n subprocess_path);\n#endif\n\n \/\/ Enable warning level logging so that we can see when bad stuff happens.\n command_line->AppendSwitch(switches::kEnableLogging);\n command_line->AppendSwitchASCII(switches::kLoggingLevel, \"1\"); \/\/ warning\n\n \/\/ If ncecessary, disable TabCloseableStateWatcher.\n if (!tab_closeable_state_watcher_enabled_)\n command_line->AppendSwitch(switches::kDisableTabCloseableStateWatcher);\n\n SandboxInitWrapper sandbox_wrapper;\n MainFunctionParams params(*command_line, sandbox_wrapper, NULL);\n params.ui_task =\n NewRunnableMethod(this, &InProcessBrowserTest::RunTestOnMainThreadLoop);\n\n host_resolver_ = new net::RuleBasedHostResolverProc(\n new IntranetRedirectHostResolverProc(NULL));\n\n \/\/ Something inside the browser does this lookup implicitly. Make it fail\n \/\/ to avoid external dependency. It won't break the tests.\n host_resolver_->AddSimulatedFailure(\"*.google.com\");\n\n \/\/ See http:\/\/en.wikipedia.org\/wiki\/Web_Proxy_Autodiscovery_Protocol\n \/\/ We don't want the test code to use it.\n host_resolver_->AddSimulatedFailure(\"wpad\");\n\n net::ScopedDefaultHostResolverProc scoped_host_resolver_proc(\n host_resolver_.get());\n\n SetUpInProcessBrowserTestFixture();\n\n \/\/ Before we run the browser, we have to hack the path to the exe to match\n \/\/ what it would be if Chrome was running, because it is used to fork renderer\n \/\/ processes, on Linux at least (failure to do so will cause a browser_test to\n \/\/ be run instead of a renderer).\n FilePath chrome_path;\n CHECK(PathService::Get(base::FILE_EXE, &chrome_path));\n chrome_path = chrome_path.DirName();\n#if defined(OS_WIN)\n chrome_path = chrome_path.Append(chrome::kBrowserProcessExecutablePath);\n#elif defined(OS_POSIX)\n chrome_path = chrome_path.Append(\n WideToASCII(chrome::kBrowserProcessExecutablePath));\n#endif\n CHECK(PathService::Override(base::FILE_EXE, chrome_path));\n\n#if defined(OS_LINUX)\n \/\/ Initialize the RenderSandbox and Zygote hosts. Apparently they get used\n \/\/ for InProcessBrowserTest, and this is not the normal browser startup path.\n Singleton<LinuxHostInit>::get();\n#endif\n\n BrowserMain(params);\n TearDownInProcessBrowserTestFixture();\n}\n\nvoid InProcessBrowserTest::TearDown() {\n \/\/ Reinstall testing browser process.\n delete g_browser_process;\n g_browser_process = new TestingBrowserProcess();\n\n browser_shutdown::delete_resources_on_shutdown = true;\n\n#if defined(OS_WIN)\n BrowserView::SetShowState(-1);\n#endif\n\n *CommandLine::ForCurrentProcessMutable() = *original_command_line_;\n RenderProcessHost::set_run_renderer_in_process(original_single_process_);\n}\n\n\/\/ Creates a browser with a single tab (about:blank), waits for the tab to\n\/\/ finish loading and shows the browser.\nBrowser* InProcessBrowserTest::CreateBrowser(Profile* profile) {\n Browser* browser = Browser::Create(profile);\n\n browser->AddTabWithURL(GURL(chrome::kAboutBlankURL), GURL(),\n PageTransition::START_PAGE, -1,\n TabStripModel::ADD_SELECTED, NULL, std::string(),\n &browser);\n\n \/\/ Wait for the page to finish loading.\n ui_test_utils::WaitForNavigation(\n &browser->GetSelectedTabContents()->controller());\n\n browser->window()->Show();\n\n return browser;\n}\n\nvoid InProcessBrowserTest::RunTestOnMainThreadLoop() {\n \/\/ On Mac, without the following autorelease pool, code which is directly\n \/\/ executed (as opposed to executed inside a message loop) would autorelease\n \/\/ objects into a higher-level pool. This pool is not recycled in-sync with\n \/\/ the message loops' pools and causes problems with code relying on\n \/\/ deallocation via an autorelease pool (such as browser window closure and\n \/\/ browser shutdown). To avoid this, the following pool is recycled after each\n \/\/ time code is directly executed.\n base::ScopedNSAutoreleasePool pool;\n\n \/\/ Pump startup related events.\n MessageLoopForUI::current()->RunAllPending();\n\n \/\/ In the long term it would be great if we could use a TestingProfile\n \/\/ here and only enable services you want tested, but that requires all\n \/\/ consumers of Profile to handle NULL services.\n Profile* profile = ProfileManager::GetDefaultProfile();\n if (!profile) {\n \/\/ We should only be able to get here if the profile already exists and\n \/\/ has been created.\n NOTREACHED();\n return;\n }\n pool.Recycle();\n\n ChromeThread::PostTask(\n ChromeThread::IO, FROM_HERE,\n NewRunnableFunction(chrome_browser_net::SetUrlRequestMocksEnabled, true));\n\n browser_ = CreateBrowser(profile);\n pool.Recycle();\n\n \/\/ Start the timeout timer to prevent hangs.\n MessageLoopForUI::current()->PostDelayedTask(FROM_HERE,\n NewRunnableMethod(this, &InProcessBrowserTest::TimedOut),\n initial_timeout_);\n\n \/\/ Pump any pending events that were created as a result of creating a\n \/\/ browser.\n MessageLoopForUI::current()->RunAllPending();\n\n RunTestOnMainThread();\n pool.Recycle();\n\n CleanUpOnMainThread();\n pool.Recycle();\n\n QuitBrowsers();\n pool.Recycle();\n}\n\nvoid InProcessBrowserTest::QuitBrowsers() {\n if (BrowserList::size() == 0)\n return;\n\n \/\/ Invoke CloseAllBrowsersAndExit on a running message loop.\n \/\/ CloseAllBrowsersAndExit exits the message loop after everything has been\n \/\/ shut down properly.\n MessageLoopForUI::current()->PostTask(\n FROM_HERE,\n NewRunnableFunction(&BrowserList::CloseAllBrowsersAndExit));\n ui_test_utils::RunMessageLoop();\n}\n\nvoid InProcessBrowserTest::TimedOut() {\n std::string error_message = \"Test timed out. Each test runs for a max of \";\n error_message += base::IntToString(initial_timeout_);\n error_message += \" ms (kInitialTimeoutInMS).\";\n\n MessageLoopForUI::current()->Quit();\n\n \/\/ WARNING: This must be after Quit as it returns.\n FAIL() << error_message;\n}\n\nvoid InProcessBrowserTest::SetInitialTimeoutInMS(int timeout_value) {\n DCHECK_GT(timeout_value, 0);\n initial_timeout_ = timeout_value;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/===- OpInterfacesGen.cpp - MLIR op interface utility generator ----------===\/\/\n\/\/\n\/\/ Copyright 2019 The MLIR Authors.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/ =============================================================================\n\/\/\n\/\/ OpInterfacesGen generates definitions for operation interfaces.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"mlir\/Support\/STLExtras.h\"\n#include \"mlir\/TableGen\/GenInfo.h\"\n#include \"llvm\/ADT\/SmallVector.h\"\n#include \"llvm\/ADT\/StringExtras.h\"\n#include \"llvm\/Support\/FormatVariadic.h\"\n#include \"llvm\/Support\/raw_ostream.h\"\n#include \"llvm\/TableGen\/Error.h\"\n#include \"llvm\/TableGen\/Record.h\"\n#include \"llvm\/TableGen\/TableGenBackend.h\"\n\nusing namespace llvm;\nusing namespace mlir;\n\nnamespace {\n\/\/ This struct represents a single method argument.\nstruct MethodArgument {\n StringRef type, name;\n};\n\n\/\/ Wrapper class around a single interface method.\nclass OpInterfaceMethod {\npublic:\n explicit OpInterfaceMethod(const llvm::Record *def) : def(def) {\n llvm::DagInit *args = def->getValueAsDag(\"arguments\");\n for (unsigned i = 0, e = args->getNumArgs(); i != e; ++i) {\n arguments.push_back(\n {llvm::cast<llvm::StringInit>(args->getArg(i))->getValue(),\n args->getArgNameStr(i)});\n }\n }\n\n \/\/ Return the return type of this method.\n StringRef getReturnType() const {\n return def->getValueAsString(\"returnType\");\n }\n\n \/\/ Return the name of this method.\n StringRef getName() const { return def->getValueAsString(\"name\"); }\n\n \/\/ Return if this method is static.\n bool isStatic() const { return def->isSubClassOf(\"StaticInterfaceMethod\"); }\n\n \/\/ Return the body for this method if it has one.\n llvm::Optional<StringRef> getBody() const {\n auto value = def->getValueAsString(\"body\");\n return value.empty() ? llvm::Optional<StringRef>() : value;\n }\n\n \/\/ Arguments.\n ArrayRef<MethodArgument> getArguments() const { return arguments; }\n bool arg_empty() const { return arguments.empty(); }\n\nprotected:\n \/\/ The TableGen definition of this method.\n const llvm::Record *def;\n\n \/\/ The arguments of this method.\n SmallVector<MethodArgument, 2> arguments;\n};\n\n\/\/ Wrapper class with helper methods for accessing OpInterfaces defined in\n\/\/ TableGen.\nclass OpInterface {\npublic:\n explicit OpInterface(const llvm::Record *def) : def(def) {\n auto *listInit = dyn_cast<llvm::ListInit>(def->getValueInit(\"methods\"));\n for (llvm::Init *init : listInit->getValues())\n methods.emplace_back(cast<llvm::DefInit>(init)->getDef());\n }\n\n \/\/ Return the name of this interface.\n StringRef getName() const { return def->getValueAsString(\"cppClassName\"); }\n\n \/\/ Return the methods of this interface.\n ArrayRef<OpInterfaceMethod> getMethods() const { return methods; }\n\nprotected:\n \/\/ The TableGen definition of this interface.\n const llvm::Record *def;\n\n \/\/ The methods of this interface.\n SmallVector<OpInterfaceMethod, 8> methods;\n};\n} \/\/ end anonymous namespace\n\n\/\/ Emit the method name and argument list for the given method. If\n\/\/ 'addOperationArg' is true, then an Operation* argument is added to the\n\/\/ beginning of the argument list.\nstatic void emitMethodNameAndArgs(const OpInterfaceMethod &method,\n raw_ostream &os, bool addOperationArg) {\n os << method.getName() << '(';\n if (addOperationArg)\n os << \"Operation *tablegen_opaque_op\" << (method.arg_empty() ? \"\" : \", \");\n interleaveComma(method.getArguments(), os, [&](const MethodArgument &arg) {\n os << arg.type << \" \" << arg.name;\n });\n os << ')';\n}\n\nstatic void emitInterfaceDef(const Record &interfaceDef, raw_ostream &os) {\n OpInterface interface(&interfaceDef);\n StringRef interfaceName = interface.getName();\n\n \/\/ Insert the method definitions.\n auto *listInit = dyn_cast<ListInit>(interfaceDef.getValueInit(\"methods\"));\n for (Init *init : listInit->getValues()) {\n OpInterfaceMethod method(cast<DefInit>(init)->getDef());\n os << method.getReturnType() << \" \" << interfaceName << \"::\";\n emitMethodNameAndArgs(method, os, \/*addOperationArg=*\/false);\n\n \/\/ Forward to the method on the concrete operation type.\n os << \" {\\n return getImpl()->\" << method.getName() << '(';\n if (!method.isStatic())\n os << \"getOperation()\" << (method.arg_empty() ? \"\" : \", \");\n interleaveComma(method.getArguments(), os,\n [&](const MethodArgument &arg) { os << arg.name; });\n os << \");\\n }\\n\";\n }\n}\n\nstatic bool emitInterfaceDefs(const RecordKeeper &recordKeeper,\n raw_ostream &os) {\n llvm::emitSourceFileHeader(\"Operation Interface Definitions\", os);\n\n auto defs = recordKeeper.getAllDerivedDefinitions(\"OpInterface\");\n for (const auto *def : defs)\n emitInterfaceDef(*def, os);\n return false;\n}\n\nstatic void emitConceptDecl(const Record &interfaceDef, raw_ostream &os) {\n os << \" class Concept {\\n\"\n << \" public:\\n\"\n << \" virtual ~Concept() = default;\\n\";\n\n \/\/ Insert each of the virtual methods.\n auto *listInit = dyn_cast<ListInit>(interfaceDef.getValueInit(\"methods\"));\n for (Init *init : listInit->getValues()) {\n OpInterfaceMethod method(cast<DefInit>(init)->getDef());\n\n \/\/ In the concept, all methods are pure virtual.\n os << \" virtual \" << method.getReturnType() << \" \";\n emitMethodNameAndArgs(method, os, \/*addOperationArg=*\/!method.isStatic());\n os << \" = 0;\\n\";\n }\n os << \" };\\n\";\n}\n\nstatic void emitModelDecl(const Record &interfaceDef, raw_ostream &os) {\n os << \" template<typename ConcreteOp>\\n\";\n os << \" class Model : public Concept {\\npublic:\\n\";\n\n \/\/ Insert each of the virtual method overrides.\n auto *listInit = dyn_cast<ListInit>(interfaceDef.getValueInit(\"methods\"));\n for (Init *init : listInit->getValues()) {\n OpInterfaceMethod method(cast<DefInit>(init)->getDef());\n os << \" \" << method.getReturnType() << \" \";\n emitMethodNameAndArgs(method, os, \/*addOperationArg=*\/!method.isStatic());\n os << \" final {\\n\";\n\n \/\/ Provide a definition of the concrete op if this is non static.\n if (!method.isStatic()) {\n os << \" auto op = llvm::cast<ConcreteOp>(tablegen_opaque_op);\\n\"\n << \" (void)op;\\n\";\n }\n\n \/\/ Check for a provided body to the function.\n if (auto body = method.getBody()) {\n os << body << \"\\n }\\n\";\n continue;\n }\n\n \/\/ Forward to the method on the concrete operation type.\n os << \" return \" << (method.isStatic() ? \"ConcreteOp::\" : \"op.\");\n\n \/\/ Add the arguments to the call.\n os << method.getName() << '(';\n interleaveComma(method.getArguments(), os,\n [&](const MethodArgument &arg) { os << arg.name; });\n os << \");\\n }\\n\";\n }\n os << \" };\\n\";\n}\n\nstatic void emitInterfaceDecl(const Record &interfaceDef, raw_ostream &os) {\n OpInterface interface(&interfaceDef);\n StringRef interfaceName = interface.getName();\n auto interfaceTraitsName = (interfaceName + \"InterfaceTraits\").str();\n\n \/\/ Emit the traits struct containing the concept and model declarations.\n os << \"namespace detail {\\n\"\n << \"struct \" << interfaceTraitsName << \" {\\n\";\n emitConceptDecl(interfaceDef, os);\n emitModelDecl(interfaceDef, os);\n os << \"};\\n} \/\/ end namespace detail\\n\";\n\n \/\/ Emit the main interface class declaration.\n os << llvm::formatv(\"class {0} : public OpInterface<{1}, detail::{2}> {\\n\"\n \"public:\\n\"\n \" using OpInterface<{1}, detail::{2}>::OpInterface;\\n\",\n interfaceName, interfaceName, interfaceTraitsName);\n\n \/\/ Insert the method declarations.\n for (auto &method : interface.getMethods()) {\n os << \" \" << method.getReturnType() << \" \";\n emitMethodNameAndArgs(method, os, \/*addOperationArg=*\/false);\n os << \";\\n\";\n }\n os << \"};\\n\";\n}\n\nstatic bool emitInterfaceDecls(const RecordKeeper &recordKeeper,\n raw_ostream &os) {\n llvm::emitSourceFileHeader(\"Operation Interface Declarations\", os);\n\n auto defs = recordKeeper.getAllDerivedDefinitions(\"OpInterface\");\n for (const auto *def : defs)\n emitInterfaceDecl(*def, os);\n return false;\n}\n\n\/\/ Registers the operation interface generator to mlir-tblgen.\nstatic mlir::GenRegistration\n genInterfaceDecls(\"gen-op-interface-decls\",\n \"Generate op interface declarations\",\n [](const RecordKeeper &records, raw_ostream &os) {\n return emitInterfaceDecls(records, os);\n });\n\n\/\/ Registers the operation interface generator to mlir-tblgen.\nstatic mlir::GenRegistration\n genInterfaceDefs(\"gen-op-interface-defs\",\n \"Generate op interface definitions\",\n [](const RecordKeeper &records, raw_ostream &os) {\n return emitInterfaceDefs(records, os);\n });\n<commit_msg>NFC: Avoid reconstructing the OpInterface methods. PiperOrigin-RevId: 264881293<commit_after>\/\/===- OpInterfacesGen.cpp - MLIR op interface utility generator ----------===\/\/\n\/\/\n\/\/ Copyright 2019 The MLIR Authors.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/ =============================================================================\n\/\/\n\/\/ OpInterfacesGen generates definitions for operation interfaces.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"mlir\/Support\/STLExtras.h\"\n#include \"mlir\/TableGen\/GenInfo.h\"\n#include \"llvm\/ADT\/SmallVector.h\"\n#include \"llvm\/ADT\/StringExtras.h\"\n#include \"llvm\/Support\/FormatVariadic.h\"\n#include \"llvm\/Support\/raw_ostream.h\"\n#include \"llvm\/TableGen\/Error.h\"\n#include \"llvm\/TableGen\/Record.h\"\n#include \"llvm\/TableGen\/TableGenBackend.h\"\n\nusing namespace llvm;\nusing namespace mlir;\n\nnamespace {\n\/\/ This struct represents a single method argument.\nstruct MethodArgument {\n StringRef type, name;\n};\n\n\/\/ Wrapper class around a single interface method.\nclass OpInterfaceMethod {\npublic:\n explicit OpInterfaceMethod(const llvm::Record *def) : def(def) {\n llvm::DagInit *args = def->getValueAsDag(\"arguments\");\n for (unsigned i = 0, e = args->getNumArgs(); i != e; ++i) {\n arguments.push_back(\n {llvm::cast<llvm::StringInit>(args->getArg(i))->getValue(),\n args->getArgNameStr(i)});\n }\n }\n\n \/\/ Return the return type of this method.\n StringRef getReturnType() const {\n return def->getValueAsString(\"returnType\");\n }\n\n \/\/ Return the name of this method.\n StringRef getName() const { return def->getValueAsString(\"name\"); }\n\n \/\/ Return if this method is static.\n bool isStatic() const { return def->isSubClassOf(\"StaticInterfaceMethod\"); }\n\n \/\/ Return the body for this method if it has one.\n llvm::Optional<StringRef> getBody() const {\n auto value = def->getValueAsString(\"body\");\n return value.empty() ? llvm::Optional<StringRef>() : value;\n }\n\n \/\/ Arguments.\n ArrayRef<MethodArgument> getArguments() const { return arguments; }\n bool arg_empty() const { return arguments.empty(); }\n\nprotected:\n \/\/ The TableGen definition of this method.\n const llvm::Record *def;\n\n \/\/ The arguments of this method.\n SmallVector<MethodArgument, 2> arguments;\n};\n\n\/\/ Wrapper class with helper methods for accessing OpInterfaces defined in\n\/\/ TableGen.\nclass OpInterface {\npublic:\n explicit OpInterface(const llvm::Record *def) : def(def) {\n auto *listInit = dyn_cast<llvm::ListInit>(def->getValueInit(\"methods\"));\n for (llvm::Init *init : listInit->getValues())\n methods.emplace_back(cast<llvm::DefInit>(init)->getDef());\n }\n\n \/\/ Return the name of this interface.\n StringRef getName() const { return def->getValueAsString(\"cppClassName\"); }\n\n \/\/ Return the methods of this interface.\n ArrayRef<OpInterfaceMethod> getMethods() const { return methods; }\n\nprotected:\n \/\/ The TableGen definition of this interface.\n const llvm::Record *def;\n\n \/\/ The methods of this interface.\n SmallVector<OpInterfaceMethod, 8> methods;\n};\n} \/\/ end anonymous namespace\n\n\/\/ Emit the method name and argument list for the given method. If\n\/\/ 'addOperationArg' is true, then an Operation* argument is added to the\n\/\/ beginning of the argument list.\nstatic void emitMethodNameAndArgs(const OpInterfaceMethod &method,\n raw_ostream &os, bool addOperationArg) {\n os << method.getName() << '(';\n if (addOperationArg)\n os << \"Operation *tablegen_opaque_op\" << (method.arg_empty() ? \"\" : \", \");\n interleaveComma(method.getArguments(), os, [&](const MethodArgument &arg) {\n os << arg.type << \" \" << arg.name;\n });\n os << ')';\n}\n\nstatic void emitInterfaceDef(const Record &interfaceDef, raw_ostream &os) {\n OpInterface interface(&interfaceDef);\n StringRef interfaceName = interface.getName();\n\n \/\/ Insert the method definitions.\n for (auto &method : interface.getMethods()) {\n os << method.getReturnType() << \" \" << interfaceName << \"::\";\n emitMethodNameAndArgs(method, os, \/*addOperationArg=*\/false);\n\n \/\/ Forward to the method on the concrete operation type.\n os << \" {\\n return getImpl()->\" << method.getName() << '(';\n if (!method.isStatic())\n os << \"getOperation()\" << (method.arg_empty() ? \"\" : \", \");\n interleaveComma(method.getArguments(), os,\n [&](const MethodArgument &arg) { os << arg.name; });\n os << \");\\n }\\n\";\n }\n}\n\nstatic bool emitInterfaceDefs(const RecordKeeper &recordKeeper,\n raw_ostream &os) {\n llvm::emitSourceFileHeader(\"Operation Interface Definitions\", os);\n\n auto defs = recordKeeper.getAllDerivedDefinitions(\"OpInterface\");\n for (const auto *def : defs)\n emitInterfaceDef(*def, os);\n return false;\n}\n\nstatic void emitConceptDecl(OpInterface &interface, raw_ostream &os) {\n os << \" class Concept {\\n\"\n << \" public:\\n\"\n << \" virtual ~Concept() = default;\\n\";\n\n \/\/ Insert each of the pure virtual concept methods.\n for (auto &method : interface.getMethods()) {\n os << \" virtual \" << method.getReturnType() << \" \";\n emitMethodNameAndArgs(method, os, \/*addOperationArg=*\/!method.isStatic());\n os << \" = 0;\\n\";\n }\n os << \" };\\n\";\n}\n\nstatic void emitModelDecl(OpInterface &interface, raw_ostream &os) {\n os << \" template<typename ConcreteOp>\\n\";\n os << \" class Model : public Concept {\\npublic:\\n\";\n\n \/\/ Insert each of the virtual method overrides.\n for (auto &method : interface.getMethods()) {\n os << \" \" << method.getReturnType() << \" \";\n emitMethodNameAndArgs(method, os, \/*addOperationArg=*\/!method.isStatic());\n os << \" final {\\n\";\n\n \/\/ Provide a definition of the concrete op if this is non static.\n if (!method.isStatic()) {\n os << \" auto op = llvm::cast<ConcreteOp>(tablegen_opaque_op);\\n\"\n << \" (void)op;\\n\";\n }\n\n \/\/ Check for a provided body to the function.\n if (auto body = method.getBody()) {\n os << body << \"\\n }\\n\";\n continue;\n }\n\n \/\/ Forward to the method on the concrete operation type.\n os << \" return \" << (method.isStatic() ? \"ConcreteOp::\" : \"op.\");\n\n \/\/ Add the arguments to the call.\n os << method.getName() << '(';\n interleaveComma(method.getArguments(), os,\n [&](const MethodArgument &arg) { os << arg.name; });\n os << \");\\n }\\n\";\n }\n os << \" };\\n\";\n}\n\nstatic void emitInterfaceDecl(const Record &interfaceDef, raw_ostream &os) {\n OpInterface interface(&interfaceDef);\n StringRef interfaceName = interface.getName();\n auto interfaceTraitsName = (interfaceName + \"InterfaceTraits\").str();\n\n \/\/ Emit the traits struct containing the concept and model declarations.\n os << \"namespace detail {\\n\"\n << \"struct \" << interfaceTraitsName << \" {\\n\";\n emitConceptDecl(interface, os);\n emitModelDecl(interface, os);\n os << \"};\\n} \/\/ end namespace detail\\n\";\n\n \/\/ Emit the main interface class declaration.\n os << llvm::formatv(\"class {0} : public OpInterface<{1}, detail::{2}> {\\n\"\n \"public:\\n\"\n \" using OpInterface<{1}, detail::{2}>::OpInterface;\\n\",\n interfaceName, interfaceName, interfaceTraitsName);\n\n \/\/ Insert the method declarations.\n for (auto &method : interface.getMethods()) {\n os << \" \" << method.getReturnType() << \" \";\n emitMethodNameAndArgs(method, os, \/*addOperationArg=*\/false);\n os << \";\\n\";\n }\n os << \"};\\n\";\n}\n\nstatic bool emitInterfaceDecls(const RecordKeeper &recordKeeper,\n raw_ostream &os) {\n llvm::emitSourceFileHeader(\"Operation Interface Declarations\", os);\n\n auto defs = recordKeeper.getAllDerivedDefinitions(\"OpInterface\");\n for (const auto *def : defs)\n emitInterfaceDecl(*def, os);\n return false;\n}\n\n\/\/ Registers the operation interface generator to mlir-tblgen.\nstatic mlir::GenRegistration\n genInterfaceDecls(\"gen-op-interface-decls\",\n \"Generate op interface declarations\",\n [](const RecordKeeper &records, raw_ostream &os) {\n return emitInterfaceDecls(records, os);\n });\n\n\/\/ Registers the operation interface generator to mlir-tblgen.\nstatic mlir::GenRegistration\n genInterfaceDefs(\"gen-op-interface-defs\",\n \"Generate op interface definitions\",\n [](const RecordKeeper &records, raw_ostream &os) {\n return emitInterfaceDefs(records, os);\n });\n<|endoftext|>"} {"text":"<commit_before>\/**\n * Ownership\n * =========\n *\n * Case study of ownership, mainly based on CppCoreGuidelines.\n *\n * Note: Compile with -std=c++14.\n *\/\n\n#include <iostream>\n#include <type_traits>\n\n\/\/ Annotate in the header that the return value of the function is probably\n\/\/ a pointer that will not be deleted on the heap, passing the ownership to the\n\/\/ caller.\ntemplate <class T, class =std::enable_if_t<std::is_pointer<T>::value>>\nusing owner = T;\n\nclass foo {\n\tfoo()\n\t{\n\t\tstd::cout << \"foo ctor\" << std::endl;\n\t}\n\n\tfriend owner<foo*> get_foo();\n};\n\nowner<foo*>\nget_foo()\n{\n\treturn new foo;\n}\n\nint\nmain()\n{\n\tauto p = get_foo();\n\tdelete p;\n\treturn 0;\n}\n<commit_msg>updated ownership: make a singleton<commit_after>\/**\n * Ownership\n * =========\n *\n * Case study of ownership, mainly based on CppCoreGuidelines.\n *\n * Note: Compile with -std=c++14.\n *\/\n\n#include <iostream>\n#include <type_traits>\n#include <cassert>\n\n\/\/ Annotate in the header that the return value of the function is probably\n\/\/ a pointer that will not be deleted on the heap, passing the ownership to the\n\/\/ caller.\ntemplate <class T, class = std::enable_if_t<std::is_pointer<T>::value>>\nusing owner = T;\n\nclass foo {\npublic:\n\tstatic owner<foo*>\n\tget()\n\t{\n\t\tif (!i_) i_ = new foo;\n\t\treturn i_;\n\t}\n\n\tstatic void\n\tdo_something()\n\t{\n\t\tassert(i_ != nullptr && \"singleton is not alive\");\n\t}\nprivate:\n\tfoo() = default;\n\n\tstatic foo* i_;\n};\n\nfoo* foo::i_{};\n\nint\nmain()\n{\n\tauto p = foo::get();\n\tp->do_something();\n\tdelete p;\n\n\treturn 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2004-present Facebook. All Rights Reserved.\n\n#include <stdio.h>\n#include <string.h>\n#include <JavaScriptCore\/JavaScript.h>\n#include <JavaScriptCore\/API\/JSProfilerPrivate.h>\n#include <jsc_legacy_profiler.h>\n#include \"JSCHelpers.h\"\n#include \"JSCLegacyProfiler.h\"\n\nstatic JSValueRef nativeProfilerStart(\n JSContextRef ctx,\n JSObjectRef function,\n JSObjectRef thisObject,\n size_t argumentCount,\n const JSValueRef arguments[],\n JSValueRef* exception) {\n if (argumentCount < 1) {\n \/\/ Could raise an exception here.\n return JSValueMakeUndefined(ctx);\n }\n\n JSStringRef title = JSValueToStringCopy(ctx, arguments[0], NULL);\n JSStartProfiling(ctx, title);\n JSStringRelease(title);\n return JSValueMakeUndefined(ctx);\n}\n\nstatic JSValueRef nativeProfilerEnd(\n JSContextRef ctx,\n JSObjectRef function,\n JSObjectRef thisObject,\n size_t argumentCount,\n const JSValueRef arguments[],\n JSValueRef* exception) {\n if (argumentCount < 1) {\n \/\/ Could raise an exception here.\n return JSValueMakeUndefined(ctx);\n }\n\n JSStringRef title = JSValueToStringCopy(ctx, arguments[0], NULL);\n JSEndProfilingAndRender(ctx, title, \"\/sdcard\/profile.json\");\n JSStringRelease(title);\n return JSValueMakeUndefined(ctx);\n}\n\nnamespace facebook {\nnamespace react {\n\nvoid stopAndOutputProfilingFile(\n JSContextRef ctx,\n JSStringRef title,\n const char *filename) {\n JSEndProfilingAndRender(ctx, title, filename);\n}\n\nvoid addNativeProfilingHooks(JSGlobalContextRef ctx) {\n JSEnableByteCodeProfiling();\n installGlobalFunction(ctx, \"nativeProfilerStart\", nativeProfilerStart);\n installGlobalFunction(ctx, \"nativeProfilerEnd\", nativeProfilerEnd);\n}\n\n} }\n<commit_msg>Allow the output of the JSC profile to be specified in JS<commit_after>\/\/ Copyright 2004-present Facebook. All Rights Reserved.\n\n#include <stdio.h>\n#include <string.h>\n#include <JavaScriptCore\/JavaScript.h>\n#include <JavaScriptCore\/API\/JSProfilerPrivate.h>\n#include <jsc_legacy_profiler.h>\n#include \"JSCHelpers.h\"\n#include \"JSCLegacyProfiler.h\"\n#include \"Value.h\"\n\nstatic JSValueRef nativeProfilerStart(\n JSContextRef ctx,\n JSObjectRef function,\n JSObjectRef thisObject,\n size_t argumentCount,\n const JSValueRef arguments[],\n JSValueRef* exception) {\n if (argumentCount < 1) {\n \/\/ Could raise an exception here.\n return JSValueMakeUndefined(ctx);\n }\n\n JSStringRef title = JSValueToStringCopy(ctx, arguments[0], exception);\n JSStartProfiling(ctx, title);\n JSStringRelease(title);\n return JSValueMakeUndefined(ctx);\n}\n\nstatic JSValueRef nativeProfilerEnd(\n JSContextRef ctx,\n JSObjectRef function,\n JSObjectRef thisObject,\n size_t argumentCount,\n const JSValueRef arguments[],\n JSValueRef* exception) {\n if (argumentCount < 1) {\n \/\/ Could raise an exception here.\n return JSValueMakeUndefined(ctx);\n }\n\n std::string writeLocation(\"\/sdcard\/\");\n if (argumentCount > 1) {\n JSStringRef fileName = JSValueToStringCopy(ctx, arguments[1], exception);\n writeLocation += facebook::react::String::ref(fileName).str();\n JSStringRelease(fileName);\n } else {\n writeLocation += \"profile.json\";\n }\n JSStringRef title = JSValueToStringCopy(ctx, arguments[0], exception);\n JSEndProfilingAndRender(ctx, title, writeLocation.c_str());\n JSStringRelease(title);\n return JSValueMakeUndefined(ctx);\n}\n\nnamespace facebook {\nnamespace react {\n\nvoid stopAndOutputProfilingFile(\n JSContextRef ctx,\n JSStringRef title,\n const char *filename) {\n JSEndProfilingAndRender(ctx, title, filename);\n}\n\nvoid addNativeProfilingHooks(JSGlobalContextRef ctx) {\n JSEnableByteCodeProfiling();\n installGlobalFunction(ctx, \"nativeProfilerStart\", nativeProfilerStart);\n installGlobalFunction(ctx, \"nativeProfilerEnd\", nativeProfilerEnd);\n}\n\n} }\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) Facebook, Inc. and its affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n *\/\n\n#include <algorithm>\n#include <memory>\n\n#include <gtest\/gtest.h>\n\n#include <react\/components\/root\/RootComponentDescriptor.h>\n#include <react\/components\/scrollview\/ScrollViewComponentDescriptor.h>\n#include <react\/components\/view\/ViewComponentDescriptor.h>\n#include <react\/element\/ComponentBuilder.h>\n#include <react\/element\/Element.h>\n#include <react\/element\/testUtils.h>\n#include <react\/uimanager\/ComponentDescriptorProviderRegistry.h>\n\nusing namespace facebook::react;\n\nTEST(ElementTest, testYogaDirtyFlag) {\n auto builder = simpleComponentBuilder();\n\n auto rootShadowNode = std::shared_ptr<RootShadowNode>{};\n auto innerShadowNode = std::shared_ptr<ViewShadowNode>{};\n\n \/\/ clang-format off\n auto element =\n Element<RootShadowNode>()\n .reference(rootShadowNode)\n .tag(1)\n .children({\n Element<ViewShadowNode>()\n .tag(2),\n Element<ViewShadowNode>()\n .tag(3)\n .reference(innerShadowNode)\n .children({\n Element<ViewShadowNode>()\n .tag(4)\n .props([] {\n \/*\n * Some non-default props.\n *\/\n auto mutableViewProps = std::make_shared<ViewProps>();\n auto &props = *mutableViewProps;\n props.nativeId = \"native Id\";\n props.opacity = 0.5;\n props.yogaStyle.alignContent() = YGAlignBaseline;\n props.yogaStyle.flexDirection() = YGFlexDirectionRowReverse;\n return mutableViewProps;\n }),\n Element<ViewShadowNode>()\n .tag(5),\n Element<ViewShadowNode>()\n .tag(6)\n }),\n Element<ScrollViewShadowNode>()\n .tag(9)\n });\n \/\/ clang-format on\n\n builder.build(element);\n\n \/*\n * Yoga nodes are dirty right after creation.\n *\/\n EXPECT_TRUE(rootShadowNode->layoutIfNeeded());\n\n \/*\n * Yoga nodes are clean (not dirty) right after layout pass.\n *\/\n EXPECT_FALSE(rootShadowNode->layoutIfNeeded());\n\n {\n \/*\n * Cloning props without changing them must *not* dirty Yoga nodes.\n *\/\n auto newRootShadowNode =\n std::static_pointer_cast<RootShadowNode>(rootShadowNode->cloneTree(\n innerShadowNode->getFamily(), [](ShadowNode const &oldShadowNode) {\n auto &componentDescriptor =\n oldShadowNode.getComponentDescriptor();\n auto props = componentDescriptor.cloneProps(\n oldShadowNode.getProps(), RawProps());\n return oldShadowNode.clone(ShadowNodeFragment{props});\n }));\n\n EXPECT_FALSE(newRootShadowNode->layoutIfNeeded());\n }\n\n {\n \/*\n * Changing *non-layout* sub-props must *not* dirty Yoga nodes.\n *\/\n auto newRootShadowNode =\n std::static_pointer_cast<RootShadowNode>(rootShadowNode->cloneTree(\n innerShadowNode->getFamily(), [](ShadowNode const &oldShadowNode) {\n auto viewProps = std::make_shared<ViewProps>();\n auto &props = *viewProps;\n\n props.nativeId = \"some new native Id\";\n props.foregroundColor = whiteColor();\n props.backgroundColor = blackColor();\n props.opacity = props.opacity + 0.042;\n props.zIndex = props.zIndex + 42;\n props.shouldRasterize = !props.shouldRasterize;\n props.collapsable = !props.collapsable;\n\n return oldShadowNode.clone(ShadowNodeFragment{viewProps});\n }));\n\n EXPECT_FALSE(newRootShadowNode->layoutIfNeeded());\n }\n\n {\n \/*\n * Changing *layout* sub-props *must* dirty Yoga nodes.\n *\/\n auto newRootShadowNode =\n std::static_pointer_cast<RootShadowNode>(rootShadowNode->cloneTree(\n innerShadowNode->getFamily(), [](ShadowNode const &oldShadowNode) {\n auto viewProps = std::make_shared<ViewProps>();\n auto &props = *viewProps;\n\n props.yogaStyle.alignContent() = YGAlignBaseline;\n props.yogaStyle.display() = YGDisplayNone;\n\n return oldShadowNode.clone(ShadowNodeFragment{viewProps});\n }));\n\n EXPECT_TRUE(newRootShadowNode->layoutIfNeeded());\n }\n\n {\n \/*\n * Removing all children *must* dirty Yoga nodes.\n *\/\n auto newRootShadowNode =\n std::static_pointer_cast<RootShadowNode>(rootShadowNode->cloneTree(\n innerShadowNode->getFamily(), [](ShadowNode const &oldShadowNode) {\n return oldShadowNode.clone(\n {ShadowNodeFragment::propsPlaceholder(),\n ShadowNode::emptySharedShadowNodeSharedList()});\n }));\n\n EXPECT_TRUE(newRootShadowNode->layoutIfNeeded());\n }\n\n {\n \/*\n * Removing the last child *must* dirty Yoga nodes.\n *\/\n auto newRootShadowNode =\n std::static_pointer_cast<RootShadowNode>(rootShadowNode->cloneTree(\n innerShadowNode->getFamily(), [](ShadowNode const &oldShadowNode) {\n auto children = oldShadowNode.getChildren();\n children.pop_back();\n\n std::reverse(children.begin(), children.end());\n\n return oldShadowNode.clone(\n {ShadowNodeFragment::propsPlaceholder(),\n std::make_shared<ShadowNode::ListOfShared const>(children)});\n }));\n\n EXPECT_TRUE(newRootShadowNode->layoutIfNeeded());\n }\n\n {\n \/*\n * Reversing a list of children *must* dirty Yoga nodes.\n *\/\n auto newRootShadowNode =\n std::static_pointer_cast<RootShadowNode>(rootShadowNode->cloneTree(\n innerShadowNode->getFamily(), [](ShadowNode const &oldShadowNode) {\n auto children = oldShadowNode.getChildren();\n\n std::reverse(children.begin(), children.end());\n\n return oldShadowNode.clone(\n {ShadowNodeFragment::propsPlaceholder(),\n std::make_shared<ShadowNode::ListOfShared const>(children)});\n }));\n\n EXPECT_TRUE(newRootShadowNode->layoutIfNeeded());\n }\n}\n<commit_msg>Fabric: Modernizing Yoga Dirty flag test.<commit_after>\/*\n * Copyright (c) Facebook, Inc. and its affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n *\/\n\n#include <algorithm>\n#include <memory>\n\n#include <gtest\/gtest.h>\n\n#include <react\/components\/root\/RootComponentDescriptor.h>\n#include <react\/components\/scrollview\/ScrollViewComponentDescriptor.h>\n#include <react\/components\/view\/ViewComponentDescriptor.h>\n#include <react\/element\/ComponentBuilder.h>\n#include <react\/element\/Element.h>\n#include <react\/element\/testUtils.h>\n#include <react\/uimanager\/ComponentDescriptorProviderRegistry.h>\n\nusing namespace facebook::react;\n\nclass YogaDirtyFlagTest : public ::testing::Test {\n protected:\n ComponentBuilder builder_;\n std::shared_ptr<RootShadowNode> rootShadowNode_;\n std::shared_ptr<ViewShadowNode> innerShadowNode_;\n std::shared_ptr<ScrollViewShadowNode> scrollViewShadowNode_;\n\n YogaDirtyFlagTest() : builder_(simpleComponentBuilder()) {\n \/\/ clang-format off\n auto element =\n Element<RootShadowNode>()\n .reference(rootShadowNode_)\n .tag(1)\n .children({\n Element<ViewShadowNode>()\n .tag(2),\n Element<ViewShadowNode>()\n .tag(3)\n .reference(innerShadowNode_)\n .children({\n Element<ViewShadowNode>()\n .tag(4)\n .props([] {\n \/*\n * Some non-default props.\n *\/\n auto mutableViewProps = std::make_shared<ViewProps>();\n auto &props = *mutableViewProps;\n props.nativeId = \"native Id\";\n props.opacity = 0.5;\n props.yogaStyle.alignContent() = YGAlignBaseline;\n props.yogaStyle.flexDirection() = YGFlexDirectionRowReverse;\n return mutableViewProps;\n }),\n Element<ViewShadowNode>()\n .tag(5),\n Element<ViewShadowNode>()\n .tag(6),\n Element<ScrollViewShadowNode>()\n .reference(scrollViewShadowNode_)\n .tag(7)\n })\n });\n \/\/ clang-format on\n\n builder_.build(element);\n\n \/*\n * Yoga nodes are dirty right after creation.\n *\/\n EXPECT_TRUE(rootShadowNode_->layoutIfNeeded());\n\n \/*\n * Yoga nodes are clean (not dirty) right after layout pass.\n *\/\n EXPECT_FALSE(rootShadowNode_->layoutIfNeeded());\n }\n};\n\nTEST_F(YogaDirtyFlagTest, cloningPropsWithoutChangingThem) {\n \/*\n * Cloning props without changing them must *not* dirty a Yoga node.\n *\/\n auto newRootShadowNode = rootShadowNode_->cloneTree(\n innerShadowNode_->getFamily(), [](ShadowNode const &oldShadowNode) {\n auto &componentDescriptor = oldShadowNode.getComponentDescriptor();\n auto props = componentDescriptor.cloneProps(\n oldShadowNode.getProps(), RawProps());\n return oldShadowNode.clone(ShadowNodeFragment{props});\n });\n\n EXPECT_FALSE(\n static_cast<RootShadowNode &>(*newRootShadowNode).layoutIfNeeded());\n}\n\nTEST_F(YogaDirtyFlagTest, changingNonLayoutSubPropsMustNotDirtyYogaNode) {\n \/*\n * Changing *non-layout* sub-props must *not* dirty a Yoga node.\n *\/\n auto newRootShadowNode = rootShadowNode_->cloneTree(\n innerShadowNode_->getFamily(), [](ShadowNode const &oldShadowNode) {\n auto viewProps = std::make_shared<ViewProps>();\n auto &props = *viewProps;\n\n props.nativeId = \"some new native Id\";\n props.foregroundColor = whiteColor();\n props.backgroundColor = blackColor();\n props.opacity = props.opacity + 0.042;\n props.zIndex = props.zIndex + 42;\n props.shouldRasterize = !props.shouldRasterize;\n props.collapsable = !props.collapsable;\n\n return oldShadowNode.clone(ShadowNodeFragment{viewProps});\n });\n\n EXPECT_FALSE(\n static_cast<RootShadowNode &>(*newRootShadowNode).layoutIfNeeded());\n}\n\nTEST_F(YogaDirtyFlagTest, changingLayoutSubPropsMustDirtyYogaNode) {\n \/*\n * Changing *layout* sub-props *must* dirty a Yoga node.\n *\/\n auto newRootShadowNode = rootShadowNode_->cloneTree(\n innerShadowNode_->getFamily(), [](ShadowNode const &oldShadowNode) {\n auto viewProps = std::make_shared<ViewProps>();\n auto &props = *viewProps;\n\n props.yogaStyle.alignContent() = YGAlignBaseline;\n props.yogaStyle.display() = YGDisplayNone;\n\n return oldShadowNode.clone(ShadowNodeFragment{viewProps});\n });\n\n EXPECT_TRUE(\n static_cast<RootShadowNode &>(*newRootShadowNode).layoutIfNeeded());\n}\n\nTEST_F(YogaDirtyFlagTest, removingAllChildrenMustDirtyYogaNode) {\n \/*\n * Removing all children *must* dirty a Yoga node.\n *\/\n auto newRootShadowNode = rootShadowNode_->cloneTree(\n innerShadowNode_->getFamily(), [](ShadowNode const &oldShadowNode) {\n return oldShadowNode.clone(\n {ShadowNodeFragment::propsPlaceholder(),\n ShadowNode::emptySharedShadowNodeSharedList()});\n });\n\n EXPECT_TRUE(\n static_cast<RootShadowNode &>(*newRootShadowNode).layoutIfNeeded());\n}\n\nTEST_F(YogaDirtyFlagTest, removingLastChildMustDirtyYogaNode) {\n \/*\n * Removing the last child *must* dirty the Yoga node.\n *\/\n auto newRootShadowNode = rootShadowNode_->cloneTree(\n innerShadowNode_->getFamily(), [](ShadowNode const &oldShadowNode) {\n auto children = oldShadowNode.getChildren();\n children.pop_back();\n\n std::reverse(children.begin(), children.end());\n\n return oldShadowNode.clone(\n {ShadowNodeFragment::propsPlaceholder(),\n std::make_shared<ShadowNode::ListOfShared const>(children)});\n });\n\n EXPECT_TRUE(\n static_cast<RootShadowNode &>(*newRootShadowNode).layoutIfNeeded());\n}\n\nTEST_F(YogaDirtyFlagTest, reversingListOfChildrenMustDirtyYogaNode) {\n \/*\n * Reversing a list of children *must* dirty a Yoga node.\n *\/\n auto newRootShadowNode = rootShadowNode_->cloneTree(\n innerShadowNode_->getFamily(), [](ShadowNode const &oldShadowNode) {\n auto children = oldShadowNode.getChildren();\n\n std::reverse(children.begin(), children.end());\n\n return oldShadowNode.clone(\n {ShadowNodeFragment::propsPlaceholder(),\n std::make_shared<ShadowNode::ListOfShared const>(children)});\n });\n\n EXPECT_TRUE(\n static_cast<RootShadowNode &>(*newRootShadowNode).layoutIfNeeded());\n}\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2008 by Sun Microsystems, Inc.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: JoinDesignView.cxx,v $\n * $Revision: 1.22 $\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * <http:\/\/www.openoffice.org\/license.html>\n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_dbaccess.hxx\"\n#ifndef DBAUI_JOINDESIGNVIEW_HXX\n#include \"JoinDesignView.hxx\"\n#endif\n#ifndef DBAUI_JOINTABLEVIEW_HXX\n#include \"JoinTableView.hxx\"\n#endif\n#ifndef DBAUI_JOINCONTROLLER_HXX\n#include \"JoinController.hxx\"\n#endif\n#ifndef _UNDO_HXX\n#include <svtools\/undo.hxx>\n#endif\n#ifndef DBAUI_QYDLGTAB_HXX\n#include \"adtabdlg.hxx\"\n#endif\n#ifndef _SV_SVAPP_HXX\n#include <vcl\/svapp.hxx>\n#endif\n#ifndef _SV_MSGBOX_HXX\n#include <vcl\/msgbox.hxx>\n#endif\n#ifndef DBACCESS_UI_BROWSER_ID_HXX\n#include \"browserids.hxx\"\n#endif\n#ifndef _DBU_QRY_HRC_\n#include \"dbu_qry.hrc\"\n#endif\n#ifndef _COMPHELPER_TYPES_HXX_\n#include <comphelper\/types.hxx>\n#endif\n#ifndef _CONNECTIVITY_DBTOOLS_HXX_\n#include <connectivity\/dbtools.hxx>\n#endif\n#ifndef _COM_SUN_STAR_SDBC_DATATYPE_HPP_\n#include <com\/sun\/star\/sdbc\/DataType.hpp>\n#endif\n#ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_\n#include <com\/sun\/star\/container\/XNameAccess.hpp>\n#endif\n#ifndef DBAUI_TABLECONNECTION_HXX\n#include \"TableConnection.hxx\"\n#endif\n#ifndef DBAUI_CONNECTIONLINE_HXX\n#include \"ConnectionLine.hxx\"\n#endif\n#ifndef DBAUI_CONNECTIONLINEDATA_HXX\n#include \"ConnectionLineData.hxx\"\n#endif\n#ifndef DBAUI_TABLECONNECTIONDATA_HXX\n#include \"TableConnectionData.hxx\"\n#endif\n#ifndef DBACCESS_SHARED_DBUSTRINGS_HRC\n#include \"dbustrings.hrc\"\n#endif\n#ifndef _COMPHELPER_EXTRACT_HXX_\n#include <comphelper\/extract.hxx>\n#endif\n#ifndef DBAUI_TOOLS_HXX\n#include \"UITools.hxx\"\n#endif\n#ifndef DBAUI_JOINTABLEVIEW_HXX\n#include \"JoinTableView.hxx\"\n#endif\n\/\/ #include <com\/sun\/star\/util\/URL.hdl>\n\nusing namespace ::com::sun::star::uno;\nusing namespace ::com::sun::star::lang;\nusing namespace ::com::sun::star::i18n;\nusing namespace ::com::sun::star::sdbc;\nusing namespace ::com::sun::star::beans;\nusing namespace ::com::sun::star::container;\nusing namespace ::com::sun::star::util;\n\nnamespace dbaui\n{\n\n\/\/ =============================================================================\n\/\/ = OJoinDesignView\n\/\/ =============================================================================\n\/\/ -----------------------------------------------------------------------------\nOJoinDesignView::OJoinDesignView(Window* _pParent, OJoinController* _pController,const Reference< XMultiServiceFactory >& _rFactory)\n :ODataView(_pParent,_pController,_rFactory)\n ,m_pTableView(NULL)\n ,m_pController(_pController)\n{\n m_pScrollWindow = new OScrollWindowHelper(this);\n}\n\/\/ -----------------------------------------------------------------------------\nOJoinDesignView::~OJoinDesignView()\n{\n ::std::auto_ptr<Window> aT3(m_pScrollWindow);\n m_pScrollWindow = NULL;\n ::std::auto_ptr<Window> aT2(m_pTableView);\n m_pTableView = NULL;\n}\n\/\/ -------------------------------------------------------------------------\nvoid OJoinDesignView::Construct()\n{\n m_pScrollWindow->setTableView(m_pTableView);\n m_pScrollWindow->Show();\n m_pTableView->Show();\n\n SetBackground( Wallpaper( Application::GetSettings().GetStyleSettings().GetFaceColor()) );\n\n ODataView::Construct();\n}\n\/\/ -----------------------------------------------------------------------------\nvoid OJoinDesignView::initialize()\n{\n \/\/ getAddTableDialog()->Update();\n}\n\/\/ -------------------------------------------------------------------------\nvoid OJoinDesignView::resizeDocumentView(Rectangle& _rPlayground)\n{\n m_pScrollWindow->SetPosSizePixel( _rPlayground.TopLeft(), _rPlayground.GetSize() );\n\n \/\/ just for completeness: there is no space left, we occupied it all ...\n _rPlayground.SetPos( _rPlayground.BottomRight() );\n _rPlayground.SetSize( Size( 0, 0 ) );\n}\n\/\/ -----------------------------------------------------------------------------\nvoid OJoinDesignView::setReadOnly(sal_Bool \/*_bReadOnly*\/)\n{\n}\n\/\/ -----------------------------------------------------------------------------\nvoid OJoinDesignView::SaveTabWinUIConfig(OTableWindow* pWin)\n{\n getController()->SaveTabWinPosSize(pWin, m_pScrollWindow->GetHScrollBar()->GetThumbPos(), m_pScrollWindow->GetVScrollBar()->GetThumbPos());\n}\n\/\/ -----------------------------------------------------------------------------\nvoid OJoinDesignView::KeyInput( const KeyEvent& rEvt )\n{\n if ( m_pTableView && m_pTableView->IsVisible() )\n m_pTableView->KeyInput( rEvt );\n else\n ODataView::KeyInput(rEvt);\n}\n\/\/ -----------------------------------------------------------------------------\n\n} \/\/ namespace dbaui\n\n<commit_msg>INTEGRATION: CWS dba30d (1.22.30); FILE MERGED 2008\/05\/29 11:30:21 fs 1.22.30.1: during #i80943#: refactoring: IController now passed around as reference, not as pointer<commit_after>\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2008 by Sun Microsystems, Inc.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: JoinDesignView.cxx,v $\n * $Revision: 1.23 $\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * <http:\/\/www.openoffice.org\/license.html>\n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_dbaccess.hxx\"\n#ifndef DBAUI_JOINDESIGNVIEW_HXX\n#include \"JoinDesignView.hxx\"\n#endif\n#ifndef DBAUI_JOINTABLEVIEW_HXX\n#include \"JoinTableView.hxx\"\n#endif\n#ifndef DBAUI_JOINCONTROLLER_HXX\n#include \"JoinController.hxx\"\n#endif\n#ifndef _UNDO_HXX\n#include <svtools\/undo.hxx>\n#endif\n#ifndef DBAUI_QYDLGTAB_HXX\n#include \"adtabdlg.hxx\"\n#endif\n#ifndef _SV_SVAPP_HXX\n#include <vcl\/svapp.hxx>\n#endif\n#ifndef _SV_MSGBOX_HXX\n#include <vcl\/msgbox.hxx>\n#endif\n#ifndef DBACCESS_UI_BROWSER_ID_HXX\n#include \"browserids.hxx\"\n#endif\n#ifndef _DBU_QRY_HRC_\n#include \"dbu_qry.hrc\"\n#endif\n#ifndef _COMPHELPER_TYPES_HXX_\n#include <comphelper\/types.hxx>\n#endif\n#ifndef _CONNECTIVITY_DBTOOLS_HXX_\n#include <connectivity\/dbtools.hxx>\n#endif\n#ifndef _COM_SUN_STAR_SDBC_DATATYPE_HPP_\n#include <com\/sun\/star\/sdbc\/DataType.hpp>\n#endif\n#ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_\n#include <com\/sun\/star\/container\/XNameAccess.hpp>\n#endif\n#ifndef DBAUI_TABLECONNECTION_HXX\n#include \"TableConnection.hxx\"\n#endif\n#ifndef DBAUI_CONNECTIONLINE_HXX\n#include \"ConnectionLine.hxx\"\n#endif\n#ifndef DBAUI_CONNECTIONLINEDATA_HXX\n#include \"ConnectionLineData.hxx\"\n#endif\n#ifndef DBAUI_TABLECONNECTIONDATA_HXX\n#include \"TableConnectionData.hxx\"\n#endif\n#ifndef DBACCESS_SHARED_DBUSTRINGS_HRC\n#include \"dbustrings.hrc\"\n#endif\n#ifndef _COMPHELPER_EXTRACT_HXX_\n#include <comphelper\/extract.hxx>\n#endif\n#ifndef DBAUI_TOOLS_HXX\n#include \"UITools.hxx\"\n#endif\n#ifndef DBAUI_JOINTABLEVIEW_HXX\n#include \"JoinTableView.hxx\"\n#endif\n\/\/ #include <com\/sun\/star\/util\/URL.hdl>\n\nusing namespace ::com::sun::star::uno;\nusing namespace ::com::sun::star::lang;\nusing namespace ::com::sun::star::i18n;\nusing namespace ::com::sun::star::sdbc;\nusing namespace ::com::sun::star::beans;\nusing namespace ::com::sun::star::container;\nusing namespace ::com::sun::star::util;\n\nnamespace dbaui\n{\n\n\/\/ =============================================================================\n\/\/ = OJoinDesignView\n\/\/ =============================================================================\n\/\/ -----------------------------------------------------------------------------\nOJoinDesignView::OJoinDesignView(Window* _pParent, OJoinController& _rController,const Reference< XMultiServiceFactory >& _rFactory)\n :ODataView( _pParent, _rController, _rFactory )\n ,m_pTableView(NULL)\n ,m_rController( _rController )\n{\n m_pScrollWindow = new OScrollWindowHelper(this);\n}\n\/\/ -----------------------------------------------------------------------------\nOJoinDesignView::~OJoinDesignView()\n{\n ::std::auto_ptr<Window> aT3(m_pScrollWindow);\n m_pScrollWindow = NULL;\n ::std::auto_ptr<Window> aT2(m_pTableView);\n m_pTableView = NULL;\n}\n\/\/ -------------------------------------------------------------------------\nvoid OJoinDesignView::Construct()\n{\n m_pScrollWindow->setTableView(m_pTableView);\n m_pScrollWindow->Show();\n m_pTableView->Show();\n\n SetBackground( Wallpaper( Application::GetSettings().GetStyleSettings().GetFaceColor()) );\n\n ODataView::Construct();\n}\n\/\/ -----------------------------------------------------------------------------\nvoid OJoinDesignView::initialize()\n{\n \/\/ getAddTableDialog()->Update();\n}\n\/\/ -------------------------------------------------------------------------\nvoid OJoinDesignView::resizeDocumentView(Rectangle& _rPlayground)\n{\n m_pScrollWindow->SetPosSizePixel( _rPlayground.TopLeft(), _rPlayground.GetSize() );\n\n \/\/ just for completeness: there is no space left, we occupied it all ...\n _rPlayground.SetPos( _rPlayground.BottomRight() );\n _rPlayground.SetSize( Size( 0, 0 ) );\n}\n\/\/ -----------------------------------------------------------------------------\nvoid OJoinDesignView::setReadOnly(sal_Bool \/*_bReadOnly*\/)\n{\n}\n\/\/ -----------------------------------------------------------------------------\nvoid OJoinDesignView::SaveTabWinUIConfig(OTableWindow* pWin)\n{\n getController().SaveTabWinPosSize(pWin, m_pScrollWindow->GetHScrollBar()->GetThumbPos(), m_pScrollWindow->GetVScrollBar()->GetThumbPos());\n}\n\/\/ -----------------------------------------------------------------------------\nvoid OJoinDesignView::KeyInput( const KeyEvent& rEvt )\n{\n if ( m_pTableView && m_pTableView->IsVisible() )\n m_pTableView->KeyInput( rEvt );\n else\n ODataView::KeyInput(rEvt);\n}\n\/\/ -----------------------------------------------------------------------------\n\n} \/\/ namespace dbaui\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright(c) Sophist Solutions, Inc. 1990-2017. All rights reserved\n *\/\n#ifndef _Stroika_Foundation_Execution_SpinLock_inl_\n#define _Stroika_Foundation_Execution_SpinLock_inl_ 1\n\n\/*\n ********************************************************************************\n ***************************** Implementation Details ***************************\n ********************************************************************************\n *\/\n\nnamespace Stroika {\n namespace Foundation {\n namespace Execution {\n\n \/*\n ********************************************************************************\n ******************************** Execution::SpinLock ***************************\n ********************************************************************************\n *\/\n inline SpinLock::SpinLock (BarrierFlag barrier)\n : fBarrierFlag_ (barrier)\n#if !qCompilerAndStdLib_atomic_flag_atomic_flag_init_Buggy\n , fLock_ (ATOMIC_FLAG_INIT)\n#endif\n {\n#if qStroika_FeatureSupported_Valgrind\n Stroika_Foundation_Debug_ValgrindDisableCheck_stdatomic (fLock_);\n VALGRIND_HG_MUTEX_INIT_POST (&fLock_, true);\n#endif\n#if qCompilerAndStdLib_atomic_flag_atomic_flag_init_Buggy\n fLock_.clear (std::memory_order_release); \/\/ docs indicate no, but looking at MSFT impl, seems yes (to avoid issue with flag_init not working?\n#endif\n }\n#if qStroika_FeatureSupported_Valgrind\n inline SpinLock::~SpinLock ()\n {\n VALGRIND_HG_MUTEX_DESTROY_PRE (&fLock_);\n VALGRIND_HG_ENABLE_CHECKING (&fLock_, sizeof (fLock_));\n }\n#endif\n inline bool SpinLock::try_lock ()\n {\n\/\/ Atomically set fLock to true and examine the previous value. If it was false, we\n\/\/ successfully gained the lock. If it was already true (someone else holds the lock),\n\/\/ we did NOT gain the lock, but we changed nothing. The fact that we changed nothing in the case where\n\/\/ we didn't gain the lock, is why this is not a race.\n#if qStroika_FeatureSupported_Valgrind\n VALGRIND_HG_MUTEX_LOCK_PRE (&fLock_, true);\n#endif\n bool result = not fLock_.test_and_set (std::memory_order_acquire);\n#if qStroika_FeatureSupported_Valgrind\n if (result) {\n VALGRIND_HG_MUTEX_LOCK_POST (&fLock_);\n }\n#endif\n if (result) {\n \/*\n * https:\/\/stroika.atlassian.net\/browse\/STK-494\n *\n * According to http:\/\/www.boost.org\/doc\/libs\/1_54_0\/doc\/html\/atomic\/usage_examples.html#boost_atomic.usage_examples.example_spinlock\n * it makes sense to use memory_order_acquire, but that doesn't seem right, as the\n * lock could protect reading or writing another memory area.\n *\/\n switch (fBarrierFlag_) {\n case BarrierFlag::eReleaseAcquire:\n std::atomic_thread_fence (std::memory_order_acquire);\n break;\n case BarrierFlag::eMemoryTotalOrder:\n std::atomic_thread_fence (std::memory_order_seq_cst);\n break;\n default:\n break;\n }\n }\n return result;\n }\n inline void SpinLock::lock ()\n {\n \/\/ Acquire lock. If \/ when fails, yield processor to avoid too much busy waiting.\n while (not try_lock ()) {\n std::this_thread::yield (); \/\/ nb: until Stroika v2.0a209, this called Execution::Yield (), making this a cancelation point. That is principally bad because it makes SpinLock not interchangeable with mutex\n }\n }\n inline void SpinLock::unlock ()\n {\n switch (fBarrierFlag_) {\n case BarrierFlag::eReleaseAcquire:\n std::atomic_thread_fence (std::memory_order_release);\n break;\n case BarrierFlag::eMemoryTotalOrder:\n std::atomic_thread_fence (std::memory_order_seq_cst);\n break;\n default:\n break;\n }\n\/\/ release lock\n#if qStroika_FeatureSupported_Valgrind\n VALGRIND_HG_MUTEX_UNLOCK_PRE (&fLock_);\n#endif\n fLock_.clear (std::memory_order_release);\n#if qStroika_FeatureSupported_Valgrind\n VALGRIND_HG_MUTEX_UNLOCK_POST (&fLock_);\n#endif\n }\n }\n }\n}\n#endif \/*_Stroika_Foundation_Execution_SpinLock_inl_*\/\n<commit_msg>missing include<commit_after>\/*\n * Copyright(c) Sophist Solutions, Inc. 1990-2017. All rights reserved\n *\/\n#ifndef _Stroika_Foundation_Execution_SpinLock_inl_\n#define _Stroika_Foundation_Execution_SpinLock_inl_ 1\n\n\/*\n ********************************************************************************\n ***************************** Implementation Details ***************************\n ********************************************************************************\n *\/\n\n#include <thread>\n\nnamespace Stroika {\n namespace Foundation {\n namespace Execution {\n\n \/*\n ********************************************************************************\n ******************************** Execution::SpinLock ***************************\n ********************************************************************************\n *\/\n inline SpinLock::SpinLock (BarrierFlag barrier)\n : fBarrierFlag_ (barrier)\n#if !qCompilerAndStdLib_atomic_flag_atomic_flag_init_Buggy\n , fLock_ (ATOMIC_FLAG_INIT)\n#endif\n {\n#if qStroika_FeatureSupported_Valgrind\n Stroika_Foundation_Debug_ValgrindDisableCheck_stdatomic (fLock_);\n VALGRIND_HG_MUTEX_INIT_POST (&fLock_, true);\n#endif\n#if qCompilerAndStdLib_atomic_flag_atomic_flag_init_Buggy\n fLock_.clear (std::memory_order_release); \/\/ docs indicate no, but looking at MSFT impl, seems yes (to avoid issue with flag_init not working?\n#endif\n }\n#if qStroika_FeatureSupported_Valgrind\n inline SpinLock::~SpinLock ()\n {\n VALGRIND_HG_MUTEX_DESTROY_PRE (&fLock_);\n VALGRIND_HG_ENABLE_CHECKING (&fLock_, sizeof (fLock_));\n }\n#endif\n inline bool SpinLock::try_lock ()\n {\n\/\/ Atomically set fLock to true and examine the previous value. If it was false, we\n\/\/ successfully gained the lock. If it was already true (someone else holds the lock),\n\/\/ we did NOT gain the lock, but we changed nothing. The fact that we changed nothing in the case where\n\/\/ we didn't gain the lock, is why this is not a race.\n#if qStroika_FeatureSupported_Valgrind\n VALGRIND_HG_MUTEX_LOCK_PRE (&fLock_, true);\n#endif\n bool result = not fLock_.test_and_set (std::memory_order_acquire);\n#if qStroika_FeatureSupported_Valgrind\n if (result) {\n VALGRIND_HG_MUTEX_LOCK_POST (&fLock_);\n }\n#endif\n if (result) {\n \/*\n * https:\/\/stroika.atlassian.net\/browse\/STK-494\n *\n * According to http:\/\/www.boost.org\/doc\/libs\/1_54_0\/doc\/html\/atomic\/usage_examples.html#boost_atomic.usage_examples.example_spinlock\n * it makes sense to use memory_order_acquire, but that doesn't seem right, as the\n * lock could protect reading or writing another memory area.\n *\/\n switch (fBarrierFlag_) {\n case BarrierFlag::eReleaseAcquire:\n std::atomic_thread_fence (std::memory_order_acquire);\n break;\n case BarrierFlag::eMemoryTotalOrder:\n std::atomic_thread_fence (std::memory_order_seq_cst);\n break;\n default:\n break;\n }\n }\n return result;\n }\n inline void SpinLock::lock ()\n {\n \/\/ Acquire lock. If \/ when fails, yield processor to avoid too much busy waiting.\n while (not try_lock ()) {\n std::this_thread::yield (); \/\/ nb: until Stroika v2.0a209, this called Execution::Yield (), making this a cancelation point. That is principally bad because it makes SpinLock not interchangeable with mutex\n }\n }\n inline void SpinLock::unlock ()\n {\n switch (fBarrierFlag_) {\n case BarrierFlag::eReleaseAcquire:\n std::atomic_thread_fence (std::memory_order_release);\n break;\n case BarrierFlag::eMemoryTotalOrder:\n std::atomic_thread_fence (std::memory_order_seq_cst);\n break;\n default:\n break;\n }\n\/\/ release lock\n#if qStroika_FeatureSupported_Valgrind\n VALGRIND_HG_MUTEX_UNLOCK_PRE (&fLock_);\n#endif\n fLock_.clear (std::memory_order_release);\n#if qStroika_FeatureSupported_Valgrind\n VALGRIND_HG_MUTEX_UNLOCK_POST (&fLock_);\n#endif\n }\n }\n }\n}\n#endif \/*_Stroika_Foundation_Execution_SpinLock_inl_*\/\n<|endoftext|>"} {"text":"<commit_before>#include \"..\/..\/config.h\"\n#ifndef UNITTEST_NO_EXCEPTIONS\n\n#include \"..\/..\/unittestpp.h\"\n#include \"..\/CurrentTest.h\"\n#include \"RecordingReporter.h\"\n#include \"ScopedCurrentTest.h\"\n\n#include <stdexcept>\n\nusing namespace std;\n\nnamespace {\n\nint ThrowingFunction()\n{\n throw \"Doh\";\n}\n\nint ThrowingStdExceptionFunction()\n{\n throw std::logic_error(\"Doh\");\n}\n\nstruct CheckFixture\n{\n CheckFixture()\n : reporter()\n , testResults(&reporter)\n {\n }\n\n void Throw()\n {\n ScopedCurrentTest scopedResults(testResults);\n CHECK(ThrowingFunction() == 1);\n }\n\n void StdThrow()\n {\n ScopedCurrentTest scopedResults(testResults);\n CHECK(ThrowingStdExceptionFunction() == 1);\n }\n\n RecordingReporter reporter;\n UnitTest::TestResults testResults;\n};\n\nTEST_FIXTURE(CheckFixture, CheckFailsOnException)\n{\n Throw();\n CHECK(testResults.GetFailureCount() > 0);\n}\n\nTEST_FIXTURE(CheckFixture, CheckFailsOnStdException)\n{\n StdThrow();\n CHECK(testResults.GetFailureCount() > 0);\n}\n\nTEST_FIXTURE(CheckFixture, CheckFailureBecauseOfExceptionIncludesCheckContents)\n{\n Throw();\n CHECK(strstr(reporter.lastFailedMessage, \"ThrowingFunction() == 1\"));\n}\n\nTEST_FIXTURE(CheckFixture, CheckFailureBecauseOfStdExceptionIncludesCheckContents)\n{\n StdThrow();\n CHECK(strstr(reporter.lastFailedMessage, \"ThrowingStdExceptionFunction() == 1\"));\n}\n\nTEST_FIXTURE(CheckFixture, CheckFailureBecauseOfStandardExceptionIncludesWhat)\n{\n StdThrow();\n CHECK(strstr(reporter.lastFailedMessage, \"exception (Doh)\"));\n}\n\nTEST(CheckEqualFailsOnException)\n{\n bool failure = false;\n {\n RecordingReporter reporter;\n UnitTest::TestResults testResults(&reporter);\n\t\tScopedCurrentTest scopedResults(testResults);\n CHECK_EQUAL(ThrowingFunction(), 1);\n failure = (testResults.GetFailureCount() > 0);\n }\n\n CHECK(failure);\n}\n\nTEST(CheckEqualFailureBecauseOfExceptionContainsCorrectDetails)\n{\n int line = 0;\n RecordingReporter reporter;\n {\n UnitTest::TestResults testResults(&reporter);\n\t\tUnitTest::TestDetails const testDetails(\"testName\", \"suiteName\", \"filename\", -1);\n\t\tScopedCurrentTest scopedResults(testResults, &testDetails);\n\n\t\tCHECK_EQUAL(ThrowingFunction(), 123); line = __LINE__;\n }\n\n CHECK_EQUAL(\"testName\", reporter.lastFailedTest);\n CHECK_EQUAL(\"suiteName\", reporter.lastFailedSuite);\n CHECK_EQUAL(\"filename\", reporter.lastFailedFile);\n CHECK_EQUAL(line, reporter.lastFailedLine);\n}\n\nTEST(CheckEqualFailureBecauseOfExceptionIncludesCheckContents)\n{\n RecordingReporter reporter;\n {\n UnitTest::TestResults testResults(&reporter);\n\t\tScopedCurrentTest scopedResults(testResults);\n CHECK_EQUAL(ThrowingFunction(), 123);\n }\n\n CHECK(strstr(reporter.lastFailedMessage, \"ThrowingFunction()\"));\n CHECK(strstr(reporter.lastFailedMessage, \"123\"));\n}\n\nTEST(CheckEqualFailureBecauseOfStandardExceptionIncludesWhat)\n{\n RecordingReporter reporter;\n {\n UnitTest::TestResults testResults(&reporter);\n ScopedCurrentTest scopedResults(testResults);\n CHECK_EQUAL(ThrowingStdExceptionFunction(), 123);\n }\n\n CHECK(strstr(reporter.lastFailedMessage, \"exception (Doh)\"));\n}\n\nTEST(CheckCloseFailsOnException)\n{\n bool failure = false;\n {\n RecordingReporter reporter;\n UnitTest::TestResults testResults(&reporter);\n\t\tScopedCurrentTest scopedResults(testResults);\n CHECK_CLOSE((float)ThrowingFunction(), 1.0001f, 0.1f);\n failure = (testResults.GetFailureCount() > 0);\n }\n\n CHECK(failure);\n}\n\nTEST(CheckCloseFailureBecauseOfExceptionContainsCorrectDetails)\n{\n int line = 0;\n RecordingReporter reporter;\n {\n UnitTest::TestResults testResults(&reporter);\n\t\tUnitTest::TestDetails testDetails(\"closeTest\", \"closeSuite\", \"filename\", -1);\n\t\tScopedCurrentTest scopedResults(testResults, &testDetails);\n CHECK_CLOSE((float)ThrowingFunction(), 1.0001f, 0.1f); line = __LINE__;\n }\n\n CHECK_EQUAL(\"closeTest\", reporter.lastFailedTest);\n CHECK_EQUAL(\"closeSuite\", reporter.lastFailedSuite);\n CHECK_EQUAL(\"filename\", reporter.lastFailedFile);\n CHECK_EQUAL(line, reporter.lastFailedLine);\n}\n\nTEST(CheckCloseFailureBecauseOfExceptionIncludesCheckContents)\n{\n RecordingReporter reporter;\n {\n UnitTest::TestResults testResults(&reporter);\n\t\tScopedCurrentTest scopedResults(testResults);\n CHECK_CLOSE((float)ThrowingFunction(), 1.0001f, 0.1f);\n }\n\n CHECK(strstr(reporter.lastFailedMessage, \"(float)ThrowingFunction()\"));\n CHECK(strstr(reporter.lastFailedMessage, \"1.0001f\"));\n}\n\nTEST(CheckCloseFailureBecauseOfStandardExceptionIncludesWhat)\n{\n RecordingReporter reporter;\n {\n UnitTest::TestResults testResults(&reporter);\n ScopedCurrentTest scopedResults(testResults);\n CHECK_CLOSE((float)ThrowingStdExceptionFunction(), 1.0001f, 0.1f);\n }\n\n CHECK(strstr(reporter.lastFailedMessage, \"exception (Doh)\"));\n}\n\nclass ThrowingObject\n{\npublic:\n float operator[](int) const\n {\n throw \"Test throw\";\n }\n};\n\nTEST(CheckArrayCloseFailureBecauseOfExceptionContainsCorrectDetails)\n{\n int line = 0;\n RecordingReporter reporter;\n {\n UnitTest::TestResults testResults(&reporter);\n\t\tUnitTest::TestDetails testDetails(\"arrayCloseTest\", \"arrayCloseSuite\", \"filename\", -1);\n\t\tScopedCurrentTest scopedResults(testResults, &testDetails);\n\n\t\tint const data[4] = { 0, 1, 2, 3 };\n CHECK_ARRAY_CLOSE(data, ThrowingObject(), 4, 0.01f); line = __LINE__;\n }\n\n CHECK_EQUAL(\"arrayCloseTest\", reporter.lastFailedTest);\n CHECK_EQUAL(\"arrayCloseSuite\", reporter.lastFailedSuite);\n CHECK_EQUAL(\"filename\", reporter.lastFailedFile);\n CHECK_EQUAL(line, reporter.lastFailedLine);\n}\n\nTEST(CheckArrayCloseFailsOnException)\n{\n bool failure = false;\n {\n RecordingReporter reporter;\n UnitTest::TestResults testResults(&reporter);\n\t\tScopedCurrentTest scopedResults(testResults);\n\n\t\tconst float data[4] = { 0, 1, 2, 3 };\n ThrowingObject obj;\n CHECK_ARRAY_CLOSE(data, obj, 3, 0.01f);\n\n\t\tfailure = (testResults.GetFailureCount() > 0);\n }\n\n CHECK(failure);\n}\n\nTEST(CheckArrayCloseFailureOnExceptionIncludesCheckContents)\n{\n RecordingReporter reporter;\n {\n UnitTest::TestResults testResults(&reporter);\n\t\tScopedCurrentTest scopedResults(testResults);\n\n\t\tconst float data[4] = { 0, 1, 2, 3 };\n ThrowingObject obj;\n CHECK_ARRAY_CLOSE(data, obj, 3, 0.01f);\n }\n\n CHECK(strstr(reporter.lastFailedMessage, \"data\"));\n CHECK(strstr(reporter.lastFailedMessage, \"obj\"));\n}\n\nTEST(CheckArrayEqualFailsOnException)\n{\n bool failure = false;\n {\n RecordingReporter reporter;\n UnitTest::TestResults testResults(&reporter);\n\t\tScopedCurrentTest scopedResults(testResults);\n\n\t\tconst float data[4] = { 0, 1, 2, 3 };\n ThrowingObject obj;\n CHECK_ARRAY_EQUAL (data, obj, 3);\n\n\t\tfailure = (testResults.GetFailureCount() > 0);\n }\n\n CHECK(failure);\n}\n\nTEST(CheckArrayEqualFailureOnExceptionIncludesCheckContents)\n{\n RecordingReporter reporter;\n {\n UnitTest::TestResults testResults(&reporter);\n\t\tScopedCurrentTest scopedResults(testResults);\n\n\t\tconst float data[4] = { 0, 1, 2, 3 };\n ThrowingObject obj;\n CHECK_ARRAY_EQUAL (data, obj, 3);\n }\n\n CHECK(strstr(reporter.lastFailedMessage, \"data\"));\n CHECK(strstr(reporter.lastFailedMessage, \"obj\"));\n}\n\nclass ThrowingObject2D\n{\npublic:\n float* operator[](int) const\n {\n throw \"Test throw\";\n }\n};\n\nTEST(CheckArray2DCloseFailureBecauseOfExceptionContainsCorrectDetails)\n{\n int line = 0;\n RecordingReporter reporter;\n {\n UnitTest::TestResults testResults(&reporter);\n\t\tUnitTest::TestDetails testDetails(\"array2DCloseTest\", \"array2DCloseSuite\", \"filename\", -1);\n\t\tScopedCurrentTest scopedResults(testResults, &testDetails);\n\n\t\tconst float data[2][2] = { {0, 1}, {2, 3} };\n CHECK_ARRAY2D_CLOSE(data, ThrowingObject2D(), 2, 2, 0.01f); line = __LINE__;\n }\n\n CHECK_EQUAL(\"array2DCloseTest\", reporter.lastFailedTest);\n CHECK_EQUAL(\"array2DCloseSuite\", reporter.lastFailedSuite);\n CHECK_EQUAL(\"filename\", reporter.lastFailedFile);\n CHECK_EQUAL(line, reporter.lastFailedLine);\n}\n\nTEST(CheckArray2DCloseFailsOnException)\n{\n bool failure = false;\n {\n RecordingReporter reporter;\n UnitTest::TestResults testResults(&reporter);\n\t\tScopedCurrentTest scopedResults(testResults);\n\n\t\tconst float data[2][2] = { {0, 1}, {2, 3} };\n ThrowingObject2D obj;\n CHECK_ARRAY2D_CLOSE(data, obj, 2, 2, 0.01f);\n\n\t\tfailure = (testResults.GetFailureCount() > 0);\n }\n\n CHECK(failure);\n}\n\nTEST(CheckArray2DCloseFailureOnExceptionIncludesCheckContents)\n{\n RecordingReporter reporter;\n {\n UnitTest::TestResults testResults(&reporter);\n\t\tScopedCurrentTest scopedResults(testResults);\n\n\t\tconst float data[2][2] = { {0, 1}, {2, 3} };\n ThrowingObject2D obj;\n CHECK_ARRAY2D_CLOSE(data, obj, 2, 2, 0.01f);\n }\n\n CHECK(strstr(reporter.lastFailedMessage, \"data\"));\n CHECK(strstr(reporter.lastFailedMessage, \"obj\"));\n}\n\n}\n\n#endif\n<commit_msg>Improve CheckFixture method names.<commit_after>#include \"..\/..\/config.h\"\n#ifndef UNITTEST_NO_EXCEPTIONS\n\n#include \"..\/..\/unittestpp.h\"\n#include \"..\/CurrentTest.h\"\n#include \"RecordingReporter.h\"\n#include \"ScopedCurrentTest.h\"\n\n#include <stdexcept>\n\nusing namespace std;\n\nnamespace {\n\nint ThrowingFunction()\n{\n throw \"Doh\";\n}\n\nint ThrowingStdExceptionFunction()\n{\n throw std::logic_error(\"Doh\");\n}\n\nstruct CheckFixture\n{\n CheckFixture()\n : reporter()\n , testResults(&reporter)\n {\n }\n\n void PerformCheckWithNonStdThrow()\n {\n ScopedCurrentTest scopedResults(testResults);\n CHECK(ThrowingFunction() == 1);\n }\n\n void PerformCheckWithStdThrow()\n {\n ScopedCurrentTest scopedResults(testResults);\n CHECK(ThrowingStdExceptionFunction() == 1);\n }\n\n RecordingReporter reporter;\n UnitTest::TestResults testResults;\n};\n\nTEST_FIXTURE(CheckFixture, CheckFailsOnException)\n{\n PerformCheckWithNonStdThrow();\n CHECK(testResults.GetFailureCount() > 0);\n}\n\nTEST_FIXTURE(CheckFixture, CheckFailsOnStdException)\n{\n PerformCheckWithStdThrow();\n CHECK(testResults.GetFailureCount() > 0);\n}\n\nTEST_FIXTURE(CheckFixture, CheckFailureBecauseOfExceptionIncludesCheckContents)\n{\n PerformCheckWithNonStdThrow();\n CHECK(strstr(reporter.lastFailedMessage, \"ThrowingFunction() == 1\"));\n}\n\nTEST_FIXTURE(CheckFixture, CheckFailureBecauseOfStdExceptionIncludesCheckContents)\n{\n PerformCheckWithStdThrow();\n CHECK(strstr(reporter.lastFailedMessage, \"ThrowingStdExceptionFunction() == 1\"));\n}\n\nTEST_FIXTURE(CheckFixture, CheckFailureBecauseOfStandardExceptionIncludesWhat)\n{\n PerformCheckWithStdThrow();\n CHECK(strstr(reporter.lastFailedMessage, \"exception (Doh)\"));\n}\n\nTEST(CheckEqualFailsOnException)\n{\n bool failure = false;\n {\n RecordingReporter reporter;\n UnitTest::TestResults testResults(&reporter);\n\t\tScopedCurrentTest scopedResults(testResults);\n CHECK_EQUAL(ThrowingFunction(), 1);\n failure = (testResults.GetFailureCount() > 0);\n }\n\n CHECK(failure);\n}\n\nTEST(CheckEqualFailureBecauseOfExceptionContainsCorrectDetails)\n{\n int line = 0;\n RecordingReporter reporter;\n {\n UnitTest::TestResults testResults(&reporter);\n\t\tUnitTest::TestDetails const testDetails(\"testName\", \"suiteName\", \"filename\", -1);\n\t\tScopedCurrentTest scopedResults(testResults, &testDetails);\n\n\t\tCHECK_EQUAL(ThrowingFunction(), 123); line = __LINE__;\n }\n\n CHECK_EQUAL(\"testName\", reporter.lastFailedTest);\n CHECK_EQUAL(\"suiteName\", reporter.lastFailedSuite);\n CHECK_EQUAL(\"filename\", reporter.lastFailedFile);\n CHECK_EQUAL(line, reporter.lastFailedLine);\n}\n\nTEST(CheckEqualFailureBecauseOfExceptionIncludesCheckContents)\n{\n RecordingReporter reporter;\n {\n UnitTest::TestResults testResults(&reporter);\n\t\tScopedCurrentTest scopedResults(testResults);\n CHECK_EQUAL(ThrowingFunction(), 123);\n }\n\n CHECK(strstr(reporter.lastFailedMessage, \"ThrowingFunction()\"));\n CHECK(strstr(reporter.lastFailedMessage, \"123\"));\n}\n\nTEST(CheckEqualFailureBecauseOfStandardExceptionIncludesWhat)\n{\n RecordingReporter reporter;\n {\n UnitTest::TestResults testResults(&reporter);\n ScopedCurrentTest scopedResults(testResults);\n CHECK_EQUAL(ThrowingStdExceptionFunction(), 123);\n }\n\n CHECK(strstr(reporter.lastFailedMessage, \"exception (Doh)\"));\n}\n\nTEST(CheckCloseFailsOnException)\n{\n bool failure = false;\n {\n RecordingReporter reporter;\n UnitTest::TestResults testResults(&reporter);\n\t\tScopedCurrentTest scopedResults(testResults);\n CHECK_CLOSE((float)ThrowingFunction(), 1.0001f, 0.1f);\n failure = (testResults.GetFailureCount() > 0);\n }\n\n CHECK(failure);\n}\n\nTEST(CheckCloseFailureBecauseOfExceptionContainsCorrectDetails)\n{\n int line = 0;\n RecordingReporter reporter;\n {\n UnitTest::TestResults testResults(&reporter);\n\t\tUnitTest::TestDetails testDetails(\"closeTest\", \"closeSuite\", \"filename\", -1);\n\t\tScopedCurrentTest scopedResults(testResults, &testDetails);\n CHECK_CLOSE((float)ThrowingFunction(), 1.0001f, 0.1f); line = __LINE__;\n }\n\n CHECK_EQUAL(\"closeTest\", reporter.lastFailedTest);\n CHECK_EQUAL(\"closeSuite\", reporter.lastFailedSuite);\n CHECK_EQUAL(\"filename\", reporter.lastFailedFile);\n CHECK_EQUAL(line, reporter.lastFailedLine);\n}\n\nTEST(CheckCloseFailureBecauseOfExceptionIncludesCheckContents)\n{\n RecordingReporter reporter;\n {\n UnitTest::TestResults testResults(&reporter);\n\t\tScopedCurrentTest scopedResults(testResults);\n CHECK_CLOSE((float)ThrowingFunction(), 1.0001f, 0.1f);\n }\n\n CHECK(strstr(reporter.lastFailedMessage, \"(float)ThrowingFunction()\"));\n CHECK(strstr(reporter.lastFailedMessage, \"1.0001f\"));\n}\n\nTEST(CheckCloseFailureBecauseOfStandardExceptionIncludesWhat)\n{\n RecordingReporter reporter;\n {\n UnitTest::TestResults testResults(&reporter);\n ScopedCurrentTest scopedResults(testResults);\n CHECK_CLOSE((float)ThrowingStdExceptionFunction(), 1.0001f, 0.1f);\n }\n\n CHECK(strstr(reporter.lastFailedMessage, \"exception (Doh)\"));\n}\n\nclass ThrowingObject\n{\npublic:\n float operator[](int) const\n {\n throw \"Test throw\";\n }\n};\n\nTEST(CheckArrayCloseFailureBecauseOfExceptionContainsCorrectDetails)\n{\n int line = 0;\n RecordingReporter reporter;\n {\n UnitTest::TestResults testResults(&reporter);\n\t\tUnitTest::TestDetails testDetails(\"arrayCloseTest\", \"arrayCloseSuite\", \"filename\", -1);\n\t\tScopedCurrentTest scopedResults(testResults, &testDetails);\n\n\t\tint const data[4] = { 0, 1, 2, 3 };\n CHECK_ARRAY_CLOSE(data, ThrowingObject(), 4, 0.01f); line = __LINE__;\n }\n\n CHECK_EQUAL(\"arrayCloseTest\", reporter.lastFailedTest);\n CHECK_EQUAL(\"arrayCloseSuite\", reporter.lastFailedSuite);\n CHECK_EQUAL(\"filename\", reporter.lastFailedFile);\n CHECK_EQUAL(line, reporter.lastFailedLine);\n}\n\nTEST(CheckArrayCloseFailsOnException)\n{\n bool failure = false;\n {\n RecordingReporter reporter;\n UnitTest::TestResults testResults(&reporter);\n\t\tScopedCurrentTest scopedResults(testResults);\n\n\t\tconst float data[4] = { 0, 1, 2, 3 };\n ThrowingObject obj;\n CHECK_ARRAY_CLOSE(data, obj, 3, 0.01f);\n\n\t\tfailure = (testResults.GetFailureCount() > 0);\n }\n\n CHECK(failure);\n}\n\nTEST(CheckArrayCloseFailureOnExceptionIncludesCheckContents)\n{\n RecordingReporter reporter;\n {\n UnitTest::TestResults testResults(&reporter);\n\t\tScopedCurrentTest scopedResults(testResults);\n\n\t\tconst float data[4] = { 0, 1, 2, 3 };\n ThrowingObject obj;\n CHECK_ARRAY_CLOSE(data, obj, 3, 0.01f);\n }\n\n CHECK(strstr(reporter.lastFailedMessage, \"data\"));\n CHECK(strstr(reporter.lastFailedMessage, \"obj\"));\n}\n\nTEST(CheckArrayEqualFailsOnException)\n{\n bool failure = false;\n {\n RecordingReporter reporter;\n UnitTest::TestResults testResults(&reporter);\n\t\tScopedCurrentTest scopedResults(testResults);\n\n\t\tconst float data[4] = { 0, 1, 2, 3 };\n ThrowingObject obj;\n CHECK_ARRAY_EQUAL (data, obj, 3);\n\n\t\tfailure = (testResults.GetFailureCount() > 0);\n }\n\n CHECK(failure);\n}\n\nTEST(CheckArrayEqualFailureOnExceptionIncludesCheckContents)\n{\n RecordingReporter reporter;\n {\n UnitTest::TestResults testResults(&reporter);\n\t\tScopedCurrentTest scopedResults(testResults);\n\n\t\tconst float data[4] = { 0, 1, 2, 3 };\n ThrowingObject obj;\n CHECK_ARRAY_EQUAL (data, obj, 3);\n }\n\n CHECK(strstr(reporter.lastFailedMessage, \"data\"));\n CHECK(strstr(reporter.lastFailedMessage, \"obj\"));\n}\n\nclass ThrowingObject2D\n{\npublic:\n float* operator[](int) const\n {\n throw \"Test throw\";\n }\n};\n\nTEST(CheckArray2DCloseFailureBecauseOfExceptionContainsCorrectDetails)\n{\n int line = 0;\n RecordingReporter reporter;\n {\n UnitTest::TestResults testResults(&reporter);\n\t\tUnitTest::TestDetails testDetails(\"array2DCloseTest\", \"array2DCloseSuite\", \"filename\", -1);\n\t\tScopedCurrentTest scopedResults(testResults, &testDetails);\n\n\t\tconst float data[2][2] = { {0, 1}, {2, 3} };\n CHECK_ARRAY2D_CLOSE(data, ThrowingObject2D(), 2, 2, 0.01f); line = __LINE__;\n }\n\n CHECK_EQUAL(\"array2DCloseTest\", reporter.lastFailedTest);\n CHECK_EQUAL(\"array2DCloseSuite\", reporter.lastFailedSuite);\n CHECK_EQUAL(\"filename\", reporter.lastFailedFile);\n CHECK_EQUAL(line, reporter.lastFailedLine);\n}\n\nTEST(CheckArray2DCloseFailsOnException)\n{\n bool failure = false;\n {\n RecordingReporter reporter;\n UnitTest::TestResults testResults(&reporter);\n\t\tScopedCurrentTest scopedResults(testResults);\n\n\t\tconst float data[2][2] = { {0, 1}, {2, 3} };\n ThrowingObject2D obj;\n CHECK_ARRAY2D_CLOSE(data, obj, 2, 2, 0.01f);\n\n\t\tfailure = (testResults.GetFailureCount() > 0);\n }\n\n CHECK(failure);\n}\n\nTEST(CheckArray2DCloseFailureOnExceptionIncludesCheckContents)\n{\n RecordingReporter reporter;\n {\n UnitTest::TestResults testResults(&reporter);\n\t\tScopedCurrentTest scopedResults(testResults);\n\n\t\tconst float data[2][2] = { {0, 1}, {2, 3} };\n ThrowingObject2D obj;\n CHECK_ARRAY2D_CLOSE(data, obj, 2, 2, 0.01f);\n }\n\n CHECK(strstr(reporter.lastFailedMessage, \"data\"));\n CHECK(strstr(reporter.lastFailedMessage, \"obj\"));\n}\n\n}\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/*\n Persons Model\n Copyright (C) 2012 Aleix Pol Gonzalez <aleixpol@blue-systems.com>\n\n This library is free software; you can redistribute it and\/or\n modify it under the terms of the GNU Lesser General Public\n License as published by the Free Software Foundation; either\n version 2.1 of the License, or (at your option) any later version.\n\n This library is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n Lesser General Public License for more details.\n\n You should have received a copy of the GNU Lesser General Public\n License along with this library; if not, write to the Free Software\n Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n*\/\n\n#include \"duplicatestest.h\"\n#include <duplicatesfinder.h>\n#include <persons-model.h>\n\n#include <qtest_kde.h>\n#include <QStandardItemModel>\n\nQTEST_KDEMAIN_CORE( DuplicatesTest )\n\nDuplicatesTest::DuplicatesTest(QObject* parent): QObject(parent)\n{}\n\nvoid DuplicatesTest::testDuplicates()\n{\n PersonsModel m;\n\/\/ m.appendRow();\n \n DuplicatesFinder f(&m);\n f.start();\n QTest::kWaitForSignal(&f, SIGNAL(finished(KJob*)));\n}\n<commit_msg>fix the test...<commit_after>\/*\n Persons Model\n Copyright (C) 2012 Aleix Pol Gonzalez <aleixpol@blue-systems.com>\n\n This library is free software; you can redistribute it and\/or\n modify it under the terms of the GNU Lesser General Public\n License as published by the Free Software Foundation; either\n version 2.1 of the License, or (at your option) any later version.\n\n This library is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n Lesser General Public License for more details.\n\n You should have received a copy of the GNU Lesser General Public\n License along with this library; if not, write to the Free Software\n Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n*\/\n\n#include \"duplicatestest.h\"\n#include <duplicatesfinder.h>\n#include <persons-model.h>\n\n#include <qtest_kde.h>\n#include <QStandardItemModel>\n\nQTEST_KDEMAIN_CORE( DuplicatesTest )\n\nDuplicatesTest::DuplicatesTest(QObject* parent): QObject(parent)\n{}\n\nvoid DuplicatesTest::testDuplicates()\n{\n PersonsModel m;\n\/\/ m.appendRow();\n \n QScopedPointer<DuplicatesFinder> f(new DuplicatesFinder(&m));\n f->start();\n QTest::kWaitForSignal(f.data(), SIGNAL(finished(KJob*)));\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Plot2D.cpp\n * hog2\n *\n * Created by Nathan Sturtevant on 4\/18\/07.\n * Copyright 2007 Nathan Sturtevant, University of Alberta. All rights reserved.\n *\n *\/\n\n#include \"Plot2D.h\"\n#include <math.h>\n#include <cstring>\n\nnamespace Plotting {\n\t\n\tLine::Line(char *label, tPlotType ptype)\n\t:plotType(ptype)\n\t{\n\t\tClearColor();\n\t\tstrncpy(name,label,1024);\n\t\txMin = DBL_MAX;\n\t\txMax = DBL_MIN;\n\t\tyMin = DBL_MAX;\n\t\tyMax = DBL_MIN;\n\t\thidden = false;\n\t\tchangedLine = false;\n\t}\n\n\tvoid Line::AddPoint(double _y)\n\t{\n\t\tchangedLine = true;\n\t\tif (x.size() == 0)\n\t\t\tAddPoint(0, _y);\n\t\telse\n\t\t\tAddPoint(x.back()+1, _y);\n\t}\n\n\tvoid Line::AddPoint(double _x, double _y)\n\t{\n\t\tchangedLine = true;\n\t\tif (_x < xMin)\n\t\t\txMin = _x;\n\t\tif (_x > xMax)\n\t\t\txMax = _x;\n\t\tif (_y < yMin)\n\t\t\tyMin = _y;\n\t\tif (_y > yMax)\n\t\t\tyMax = _y;\n\t\tx.push_back(_x);\n\t\ty.push_back(_y);\n\n\t\t\/\/printf(\"New %s bounds (%1.2f, %1.2f, %1.2f, %1.2f)\\n\", name, xMin, yMax, xMax, yMin);\n\n\t}\n\t\t\n\tdouble Line::DistanceToLine(double xp, double yp)\n\t{\n\t\tdouble bestDist = (y[0]-yp)*(y[0]-yp)+(x[0]-xp)*(x[0]-xp);\n\t\tint bestIndex = 0;\n\t\t\/\/ Linear search? - can be sped up with binary search if needed\n\t\tfor (unsigned int m = 1; m < x.size()-1; m++)\n\t\t{\n\t\t\tif (fless((y[m]-yp)*(y[m]-yp)+(x[m]-xp)*(x[m]-xp), bestDist))\n\t\t\t{\n\t\t\t\tbestDist = (y[m]-yp)*(y[m]-yp)+(x[m]-xp)*(x[m]-xp);\n\t\t\t\tbestIndex = m;\n\t\t\t}\n\t\t}\n\t\treturn sqrt(bestDist);\n\t}\n\n\tdouble Line::VerticalDistanceToLine(double xp, double yp)\n\t{\n\t\tdouble horizDist = fabs(y[0]-yp);\n\t\tint horizIndex = 0;\n\t\t\/\/ Linear search? - can be sped up with binary search if needed\n\t\tfor (unsigned int m = 1; m < x.size()-1; m++)\n\t\t{\n\t\t\tif (fabs(y[m]-yp) < horizDist)\n\t\t\t{\n\t\t\t\thorizDist = fabs(y[m]-yp);\n\t\t\t\thorizIndex = m;\n\t\t\t}\n\t\t}\n\t\treturn fabs(x[horizIndex]-xp);\n\t}\n\n\tvoid Line::Smooth(unsigned int windowSize)\n\t{\n\t\tdouble sum=0;\n\t\t\/\/ setup initial window\n\t\tfor (unsigned int m = 0; (m < x.size()) && (m < windowSize); m++)\n\t\t{\n\t\t\tsum += y[m];\n\t\t\ty[m\/2] = sum\/(double)(m+1);\n\t\t}\n\t\tfor (unsigned int m = windowSize\/2; m < x.size()-windowSize\/2-1; m++)\n\t\t{\n\t\t\ty[m] = sum\/(double)windowSize;\n\t\t\tsum-=y[m-windowSize\/2];\n\t\t\tsum+=y[m+windowSize\/2];\n\t\t}\n\t\tfor (unsigned int m = x.size()-windowSize\/2-1; m < x.size(); m++)\n\t\t{\n\t\t\ty[m] = sum\/(double)(windowSize\/2+x.size()-1-m);\n\t\t\tsum-=y[m-windowSize\/2];\n\t\t}\n\t}\n\n\tvoid Line::ClearColor()\n\t{\n\t\tr = -1;\n\t}\n\n\tvoid Line::SetColor(double _r, double _g, double _b)\n\t{\n\t\tr = _r; g = _g; b = _b;\n\t}\n\n\tvoid Line::OpenGLDraw() const\n\t{\n\t\tif (hidden)\n\t\t\treturn;\n\t\tswitch (plotType)\n\t\t{\n\t\t\tcase kLinePlot:\n\t\t\t{\n\t\t\t\tglBegin(GL_LINE_STRIP);\n\t\t\t\tif (r != -1)\n\t\t\t\t{\n\t\t\t\t\tglColor3f(r, g, b);\n\t\t\t\t}\n\t\t\t\tfor (unsigned int t = 0; t < x.size(); t++)\n\t\t\t\t\tglVertex2d(x[t], y[t]);\n\t\t\t\tglEnd();\n\t\t\t}\n\t\t\tbreak;\n\t\t\tcase kImpulsePlot:\n\t\t\t{\n\t\t\t\tglBegin(GL_LINES);\n\t\t\t\tif (r != -1)\n\t\t\t\t{\n\t\t\t\t\tglColor3f(r, g, b);\n\t\t\t\t}\n\t\t\t\tfor (unsigned int t = 0; t < x.size(); t++)\n\t\t\t\t{\n\t\t\t\t\tglVertex2d(x[t], 0);\n\t\t\t\t\tglVertex2d(x[t], y[t]);\n\t\t\t\t}\n\t\t\t\tglEnd();\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tPlot2D::Plot2D()\n\t{\n\t\tResetAxis();\n\t\tdrawMouse = true;\n\t\tlastSelectedLine = -1;\n\t\trecomputeBorders = true;\n\t}\n\n\tvoid Plot2D::AddLine(Line *l)\n\t{\n\t\tlines.push_back(l);\n\t\t\n\t\tif (l->GetMaxX() > xMax)\n\t\t\txMax = l->GetMaxX();\n\t\tif (l->GetMaxY() > yMax)\n\t\t\tyMax = l->GetMaxY();\n\t\tif (l->GetMinX() < xMin)\n\t\t\txMin = l->GetMinX();\n\t\tif (l->GetMinY() < yMin)\n\t\t\tyMin = l->GetMinY();\n\n\t\tif (!forceAxis)\n\t\t\tResetAxis();\n\t}\n\n\tvoid Plot2D::Zoom(double amt)\n\t{\n\t\tprintf(\"Got amt %1.2f\\n\", amt);\n\t\tdouble cx, cy;\n\t\tamt = 1-0.01*amt;\n\t\tcx = xMin+(xMax-xMin)\/2;\n\t\tcy = yMin+(yMax-yMin)\/2;\n\t\tdouble width = (xMax-xMin)*amt;\n\t\tdouble height = (yMax-yMin)*amt;\n\n\t\txMin = cx - width\/2;\n\t\txMax = cx + width\/2;\n\t\tyMin = cy - height\/2;\n\t\tyMax = cy + height\/2;\n\n\t\tdLeft = xMin;\n\t\tdRight = xMax;\n\t\tdTop = yMax;\n\t\tdBottom = yMin;\n\t}\n\n\tvoid Plot2D::SetAxis(double minx, double miny, double maxx, double maxy)\n\t{\n\t\tforceAxis = true;\n\t\txMax = maxx;\n\t\txMin = minx;\n\t\tyMax = maxy;\n\t\tyMin = miny;\n\t}\n\n\tvoid Plot2D::ResetAxis()\n\t{\n\t\tforceAxis = false;\n\t\trecomputeBorders = false;\n\t\txMin = DBL_MAX;\n\t\txMax = DBL_MIN;\n\t\tyMin = DBL_MAX;\n\t\tyMax = DBL_MIN;\n\n\t\t\/\/ recompute max\/min stuff\n\t\tfor (unsigned int x = 0; x < lines.size(); x++)\n\t\t{\n\t\t\tLine *l = lines[x];\n\n\t\t\tif (l->GetMaxX() > xMax)\n\t\t\t\txMax = l->GetMaxX();\n\t\t\tif (l->GetMaxY() > yMax)\n\t\t\t\tyMax = l->GetMaxY();\n\t\t\tif (l->GetMinX() < xMin)\n\t\t\t\txMin = l->GetMinX();\n\t\t\tif (l->GetMinY() < yMin)\n\t\t\t\tyMin = l->GetMinY();\n\t\t}\n\n\t\tdLeft = xMin;\n\t\tdRight = xMax;\n\t\tdTop = yMax;\n\t\tdBottom = yMin;\n\t}\n\n\tvoid Plot2D::OffsetCurrMouse(double deltaX, double deltaY)\n\t{\n\t\tmouseXLoc += deltaX;\n\t\tmouseYLoc += deltaY;\n\t\t\n\t\tif (lines.size() == 0)\n\t\t\treturn;\n\t\t\n\t\tdouble minDist = lines[0]->DistanceToLine(mouseXLoc, mouseYLoc);\n\t\tint minIndex = 0;\n\t\tfor (unsigned int x = 1; x < lines.size(); x++)\n\t\t{\n\t\t\tif (lines[x]->IsHidden())\n\t\t\t\tcontinue;\n\n\t\t\tif (fless(lines[x]->DistanceToLine(mouseXLoc, mouseYLoc), minDist))\n\t\t\t{\n\t\t\t\tminIndex = x;\n\t\t\t\tminDist = lines[x]->DistanceToLine(mouseXLoc, mouseYLoc);\n\t\t\t}\n\t\t\t\/\/\t\tif (lines[x]->pointOnLine(mouseXLoc, mouseYLoc))\n\t\t\t\/\/\t\t\tprintf(\"Near: %s\\n\", lines[x]->getLabel());\n\t\t}\n\t\tif (minIndex != lastSelectedLine)\n\t\t{\n\t\t\t\/\/ set colors here instead\n\/\/\t\t\tif (lastSelectedLine != -1)\n\/\/\t\t\t\tlines[lastSelectedLine]->unselect();\n\/\/\t\t\tlines[minIndex]->select();\n\t\t\tlastSelectedLine = minIndex;\n\/\/\t\t\tprintf(\"Near: %s\\n\", lines[minIndex]->getLabel());\n\/\/\t\t\tsubmitMessage(lines[minIndex]->getLabel());\n\t\t}\n\t}\n\n\/\/\tvoid Plot2D::SetCurrMouse(double lastX, double lastY, Rect &winRect)\n\/\/\t{\n\/\/\t\tdouble tpW = (dRight-dLeft)*.05;\n\/\/\t\tdouble tpH = (dTop-dBottom)*.05;\n\/\/\t\tmouseXLoc = dLeft-tpW+(dRight+2*tpW - dLeft)*(lastX\/winRect.right);\n\/\/\t\tmouseYLoc = dBottom-tpH+(dTop+2*tpH - dBottom)*(1-(lastY\/winRect.bottom));\n\/\/\n\/\/\t\tif (lines.size() == 0)\n\/\/\t\t\treturn;\n\/\/\t\t\n\/\/\t\tdouble minDist = lines[0]->DistanceToLine(mouseXLoc, mouseYLoc);\n\/\/\t\tint minIndex = 0;\n\/\/\t\tfor (unsigned int x = 1; x < lines.size(); x++)\n\/\/\t\t{\n\/\/\t\t\tif (fless(lines[x]->DistanceToLine(mouseXLoc, mouseYLoc), minDist))\n\/\/\t\t\t{\n\/\/\t\t\t\tminIndex = x;\n\/\/\t\t\t\tminDist = lines[x]->DistanceToLine(mouseXLoc, mouseYLoc);\n\/\/\t\t\t}\n\/\/\t\/\/\t\tif (lines[x]->pointOnLine(mouseXLoc, mouseYLoc))\n\/\/\t\/\/\t\t\tprintf(\"Near: %s\\n\", lines[x]->getLabel());\n\/\/\t\t}\n\/\/\t\tif (minIndex != lastSelectedLine)\n\/\/\t\t{\n\/\/\/\/\t\t\tif (lastSelectedLine != -1)\n\/\/\/\/\t\t\t\tlines[lastSelectedLine]->unselect();\n\/\/\/\/\t\t\tlines[minIndex]->select();\n\/\/\t\t\tlastSelectedLine = minIndex;\n\/\/\t\t\t\/\/printf(\"Near: %s\\n\", lines[minIndex]->getLabel());\n\/\/\t\t\t\/\/submitMessage(lines[minIndex]->getLabel());\n\/\/\t\t}\n\/\/\t}\n\/\/\n\/\/\tvoid Plot2D::Recenter(double lastX, double lastY, Rect &winRect)\n\/\/\t{\n\/\/\t\tdouble tpW = (dRight-dLeft)*.05;\n\/\/\t\tdouble tpH = (dTop-dBottom)*.05;\n\/\/\t\tdouble XLoc = dLeft-tpW+(dRight+2*tpW - dLeft)*(lastX\/winRect.right);\n\/\/\t\tdouble YLoc = dBottom-tpH+(dTop+2*tpH - dBottom)*(1-(lastY\/winRect.bottom));\n\/\/\n\/\/\t\txMin = XLoc - (dRight-dLeft)\/2;\n\/\/\t\txMax = XLoc + (dRight-dLeft)\/2;\n\/\/\t\tyMin = YLoc - (dTop-dBottom)\/2;\n\/\/\t\tyMax = YLoc + (dTop-dBottom)\/2;\n\/\/\t\t\n\/\/\t\tdLeft = xMin;\n\/\/\t\tdRight = xMax;\n\/\/\t\tdTop = yMax;\n\/\/\t\tdBottom = yMin;\n\/\/\t\t\n\/\/\t}\n\n\n\tvoid Plot2D::SmoothLines()\n\t{\n\t\tfor (unsigned int x = 0; x < lines.size(); x++)\n\t\t\tlines[x]->Smooth(50);\n\t\tResetAxis();\n\t}\n\n\tvoid Plot2D::OpenGLDraw() const\n\t{\n\t\tGLint matrixMode;\n\t\t\n\t\tif (recomputeBorders)\n\t\t\tassert(false);\n\/\/\t\t\tResetAxis();\n\t\t\n\t\tglGetIntegerv(GL_MATRIX_MODE, &matrixMode);\n\t\t\n\t\tglEnable(GL_BLEND); \/\/ for text fading\n\t\tglBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); \/\/ ditto\n\t\t\n\t\t\/\/ set orthograhic 1:1 pixel transform in local view coords\n\t\tglDisable(GL_DEPTH_TEST);\n\t\t\n\t\tglMatrixMode(GL_PROJECTION);\n\t\tglPushMatrix();\n\t\tglLoadIdentity();\n\t\tglMatrixMode(GL_MODELVIEW);\n\t\tglPushMatrix();\n\t\tglLoadIdentity();\n\t\tglColor3f(0, 1, 0);\n\t\t\n\t\t\/\/ left, right, bottom, top, near, far\n\t\tdouble tpW = (dRight-dLeft)*.05;\n\t\tdouble tpH = (dTop-dBottom)*.05;\n\t\tglOrtho(dLeft-tpW, dRight+tpW, dBottom-tpH, dTop+tpH, -1, 1);\n\t\t\/\/printf(\"Drawing axis (%1.2f, %1.2f, %1.2f, %1.2f)\\n\", dLeft, dTop, dRight, dBottom);\n\t\t\n\t\tglColor3f(1, 1, 1); \/\/ draw axis\n\t\tglBegin(GL_LINES);\n\t\tglVertex2d(dLeft-tpW, 0); glVertex2d(dRight+tpW, 0);\n\t\tglVertex2d(0, dBottom-tpH); glVertex2d(0, dTop+tpH);\n\t\tglEnd();\n\t\t\n\t\tfor (unsigned int x = 0; x < lines.size(); x++)\n\t\t{\n\t\t\tif (lines[x]->GetChanged())\n\t\t\t\tassert(false);\n\t\t\t\/\/recomputeBorders = true;\n\t\t\tlines[x]->OpenGLDraw();\n\t\t}\n\n\t\tglLineWidth(3.0);\n\t\tif (lastSelectedLine != -1)\n\t\t\tlines[lastSelectedLine]->OpenGLDraw();\n\t\tglLineWidth(1.0);\n\n\t\t\/\/ draw mouse - temporary hack\n\t\tif (drawMouse)\n\t\t{\n\t\t\tglColor4f(0, 1, 0, .5); \/\/ draw axis\n\t\t\tglBegin(GL_LINES);\n\t\t\tglVertex2d(mouseXLoc, dBottom-tpH); glVertex2d(mouseXLoc, dTop+tpH);\n\t\t\tglVertex2d(dLeft-tpW, mouseYLoc); glVertex2d(dRight+tpW, mouseYLoc);\n\t\t\tglEnd();\n\t\t}\n\n\t\tglPopMatrix(); \/\/ GL_MODELVIEW\n\t\tglMatrixMode(GL_PROJECTION);\n\t\tglPopMatrix();\n\t\tglMatrixMode(matrixMode);\n\t\t\n\t\tglEnable(GL_DEPTH_TEST);\n\t}\n}\n<commit_msg>added assert include<commit_after>\/*\n * Plot2D.cpp\n * hog2\n *\n * Created by Nathan Sturtevant on 4\/18\/07.\n * Copyright 2007 Nathan Sturtevant, University of Alberta. All rights reserved.\n *\n *\/\n\n#include \"Plot2D.h\"\n#include <math.h>\n#include <cstring>\n#include <assert.h>\n\nnamespace Plotting {\n\t\n\tLine::Line(char *label, tPlotType ptype)\n\t:plotType(ptype)\n\t{\n\t\tClearColor();\n\t\tstrncpy(name,label,1024);\n\t\txMin = DBL_MAX;\n\t\txMax = DBL_MIN;\n\t\tyMin = DBL_MAX;\n\t\tyMax = DBL_MIN;\n\t\thidden = false;\n\t\tchangedLine = false;\n\t}\n\n\tvoid Line::AddPoint(double _y)\n\t{\n\t\tchangedLine = true;\n\t\tif (x.size() == 0)\n\t\t\tAddPoint(0, _y);\n\t\telse\n\t\t\tAddPoint(x.back()+1, _y);\n\t}\n\n\tvoid Line::AddPoint(double _x, double _y)\n\t{\n\t\tchangedLine = true;\n\t\tif (_x < xMin)\n\t\t\txMin = _x;\n\t\tif (_x > xMax)\n\t\t\txMax = _x;\n\t\tif (_y < yMin)\n\t\t\tyMin = _y;\n\t\tif (_y > yMax)\n\t\t\tyMax = _y;\n\t\tx.push_back(_x);\n\t\ty.push_back(_y);\n\n\t\t\/\/printf(\"New %s bounds (%1.2f, %1.2f, %1.2f, %1.2f)\\n\", name, xMin, yMax, xMax, yMin);\n\n\t}\n\t\t\n\tdouble Line::DistanceToLine(double xp, double yp)\n\t{\n\t\tdouble bestDist = (y[0]-yp)*(y[0]-yp)+(x[0]-xp)*(x[0]-xp);\n\t\tint bestIndex = 0;\n\t\t\/\/ Linear search? - can be sped up with binary search if needed\n\t\tfor (unsigned int m = 1; m < x.size()-1; m++)\n\t\t{\n\t\t\tif (fless((y[m]-yp)*(y[m]-yp)+(x[m]-xp)*(x[m]-xp), bestDist))\n\t\t\t{\n\t\t\t\tbestDist = (y[m]-yp)*(y[m]-yp)+(x[m]-xp)*(x[m]-xp);\n\t\t\t\tbestIndex = m;\n\t\t\t}\n\t\t}\n\t\treturn sqrt(bestDist);\n\t}\n\n\tdouble Line::VerticalDistanceToLine(double xp, double yp)\n\t{\n\t\tdouble horizDist = fabs(y[0]-yp);\n\t\tint horizIndex = 0;\n\t\t\/\/ Linear search? - can be sped up with binary search if needed\n\t\tfor (unsigned int m = 1; m < x.size()-1; m++)\n\t\t{\n\t\t\tif (fabs(y[m]-yp) < horizDist)\n\t\t\t{\n\t\t\t\thorizDist = fabs(y[m]-yp);\n\t\t\t\thorizIndex = m;\n\t\t\t}\n\t\t}\n\t\treturn fabs(x[horizIndex]-xp);\n\t}\n\n\tvoid Line::Smooth(unsigned int windowSize)\n\t{\n\t\tdouble sum=0;\n\t\t\/\/ setup initial window\n\t\tfor (unsigned int m = 0; (m < x.size()) && (m < windowSize); m++)\n\t\t{\n\t\t\tsum += y[m];\n\t\t\ty[m\/2] = sum\/(double)(m+1);\n\t\t}\n\t\tfor (unsigned int m = windowSize\/2; m < x.size()-windowSize\/2-1; m++)\n\t\t{\n\t\t\ty[m] = sum\/(double)windowSize;\n\t\t\tsum-=y[m-windowSize\/2];\n\t\t\tsum+=y[m+windowSize\/2];\n\t\t}\n\t\tfor (unsigned int m = x.size()-windowSize\/2-1; m < x.size(); m++)\n\t\t{\n\t\t\ty[m] = sum\/(double)(windowSize\/2+x.size()-1-m);\n\t\t\tsum-=y[m-windowSize\/2];\n\t\t}\n\t}\n\n\tvoid Line::ClearColor()\n\t{\n\t\tr = -1;\n\t}\n\n\tvoid Line::SetColor(double _r, double _g, double _b)\n\t{\n\t\tr = _r; g = _g; b = _b;\n\t}\n\n\tvoid Line::OpenGLDraw() const\n\t{\n\t\tif (hidden)\n\t\t\treturn;\n\t\tswitch (plotType)\n\t\t{\n\t\t\tcase kLinePlot:\n\t\t\t{\n\t\t\t\tglBegin(GL_LINE_STRIP);\n\t\t\t\tif (r != -1)\n\t\t\t\t{\n\t\t\t\t\tglColor3f(r, g, b);\n\t\t\t\t}\n\t\t\t\tfor (unsigned int t = 0; t < x.size(); t++)\n\t\t\t\t\tglVertex2d(x[t], y[t]);\n\t\t\t\tglEnd();\n\t\t\t}\n\t\t\tbreak;\n\t\t\tcase kImpulsePlot:\n\t\t\t{\n\t\t\t\tglBegin(GL_LINES);\n\t\t\t\tif (r != -1)\n\t\t\t\t{\n\t\t\t\t\tglColor3f(r, g, b);\n\t\t\t\t}\n\t\t\t\tfor (unsigned int t = 0; t < x.size(); t++)\n\t\t\t\t{\n\t\t\t\t\tglVertex2d(x[t], 0);\n\t\t\t\t\tglVertex2d(x[t], y[t]);\n\t\t\t\t}\n\t\t\t\tglEnd();\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tPlot2D::Plot2D()\n\t{\n\t\tResetAxis();\n\t\tdrawMouse = true;\n\t\tlastSelectedLine = -1;\n\t\trecomputeBorders = true;\n\t}\n\n\tvoid Plot2D::AddLine(Line *l)\n\t{\n\t\tlines.push_back(l);\n\t\t\n\t\tif (l->GetMaxX() > xMax)\n\t\t\txMax = l->GetMaxX();\n\t\tif (l->GetMaxY() > yMax)\n\t\t\tyMax = l->GetMaxY();\n\t\tif (l->GetMinX() < xMin)\n\t\t\txMin = l->GetMinX();\n\t\tif (l->GetMinY() < yMin)\n\t\t\tyMin = l->GetMinY();\n\n\t\tif (!forceAxis)\n\t\t\tResetAxis();\n\t}\n\n\tvoid Plot2D::Zoom(double amt)\n\t{\n\t\tprintf(\"Got amt %1.2f\\n\", amt);\n\t\tdouble cx, cy;\n\t\tamt = 1-0.01*amt;\n\t\tcx = xMin+(xMax-xMin)\/2;\n\t\tcy = yMin+(yMax-yMin)\/2;\n\t\tdouble width = (xMax-xMin)*amt;\n\t\tdouble height = (yMax-yMin)*amt;\n\n\t\txMin = cx - width\/2;\n\t\txMax = cx + width\/2;\n\t\tyMin = cy - height\/2;\n\t\tyMax = cy + height\/2;\n\n\t\tdLeft = xMin;\n\t\tdRight = xMax;\n\t\tdTop = yMax;\n\t\tdBottom = yMin;\n\t}\n\n\tvoid Plot2D::SetAxis(double minx, double miny, double maxx, double maxy)\n\t{\n\t\tforceAxis = true;\n\t\txMax = maxx;\n\t\txMin = minx;\n\t\tyMax = maxy;\n\t\tyMin = miny;\n\t}\n\n\tvoid Plot2D::ResetAxis()\n\t{\n\t\tforceAxis = false;\n\t\trecomputeBorders = false;\n\t\txMin = DBL_MAX;\n\t\txMax = DBL_MIN;\n\t\tyMin = DBL_MAX;\n\t\tyMax = DBL_MIN;\n\n\t\t\/\/ recompute max\/min stuff\n\t\tfor (unsigned int x = 0; x < lines.size(); x++)\n\t\t{\n\t\t\tLine *l = lines[x];\n\n\t\t\tif (l->GetMaxX() > xMax)\n\t\t\t\txMax = l->GetMaxX();\n\t\t\tif (l->GetMaxY() > yMax)\n\t\t\t\tyMax = l->GetMaxY();\n\t\t\tif (l->GetMinX() < xMin)\n\t\t\t\txMin = l->GetMinX();\n\t\t\tif (l->GetMinY() < yMin)\n\t\t\t\tyMin = l->GetMinY();\n\t\t}\n\n\t\tdLeft = xMin;\n\t\tdRight = xMax;\n\t\tdTop = yMax;\n\t\tdBottom = yMin;\n\t}\n\n\tvoid Plot2D::OffsetCurrMouse(double deltaX, double deltaY)\n\t{\n\t\tmouseXLoc += deltaX;\n\t\tmouseYLoc += deltaY;\n\t\t\n\t\tif (lines.size() == 0)\n\t\t\treturn;\n\t\t\n\t\tdouble minDist = lines[0]->DistanceToLine(mouseXLoc, mouseYLoc);\n\t\tint minIndex = 0;\n\t\tfor (unsigned int x = 1; x < lines.size(); x++)\n\t\t{\n\t\t\tif (lines[x]->IsHidden())\n\t\t\t\tcontinue;\n\n\t\t\tif (fless(lines[x]->DistanceToLine(mouseXLoc, mouseYLoc), minDist))\n\t\t\t{\n\t\t\t\tminIndex = x;\n\t\t\t\tminDist = lines[x]->DistanceToLine(mouseXLoc, mouseYLoc);\n\t\t\t}\n\t\t\t\/\/\t\tif (lines[x]->pointOnLine(mouseXLoc, mouseYLoc))\n\t\t\t\/\/\t\t\tprintf(\"Near: %s\\n\", lines[x]->getLabel());\n\t\t}\n\t\tif (minIndex != lastSelectedLine)\n\t\t{\n\t\t\t\/\/ set colors here instead\n\/\/\t\t\tif (lastSelectedLine != -1)\n\/\/\t\t\t\tlines[lastSelectedLine]->unselect();\n\/\/\t\t\tlines[minIndex]->select();\n\t\t\tlastSelectedLine = minIndex;\n\/\/\t\t\tprintf(\"Near: %s\\n\", lines[minIndex]->getLabel());\n\/\/\t\t\tsubmitMessage(lines[minIndex]->getLabel());\n\t\t}\n\t}\n\n\/\/\tvoid Plot2D::SetCurrMouse(double lastX, double lastY, Rect &winRect)\n\/\/\t{\n\/\/\t\tdouble tpW = (dRight-dLeft)*.05;\n\/\/\t\tdouble tpH = (dTop-dBottom)*.05;\n\/\/\t\tmouseXLoc = dLeft-tpW+(dRight+2*tpW - dLeft)*(lastX\/winRect.right);\n\/\/\t\tmouseYLoc = dBottom-tpH+(dTop+2*tpH - dBottom)*(1-(lastY\/winRect.bottom));\n\/\/\n\/\/\t\tif (lines.size() == 0)\n\/\/\t\t\treturn;\n\/\/\t\t\n\/\/\t\tdouble minDist = lines[0]->DistanceToLine(mouseXLoc, mouseYLoc);\n\/\/\t\tint minIndex = 0;\n\/\/\t\tfor (unsigned int x = 1; x < lines.size(); x++)\n\/\/\t\t{\n\/\/\t\t\tif (fless(lines[x]->DistanceToLine(mouseXLoc, mouseYLoc), minDist))\n\/\/\t\t\t{\n\/\/\t\t\t\tminIndex = x;\n\/\/\t\t\t\tminDist = lines[x]->DistanceToLine(mouseXLoc, mouseYLoc);\n\/\/\t\t\t}\n\/\/\t\/\/\t\tif (lines[x]->pointOnLine(mouseXLoc, mouseYLoc))\n\/\/\t\/\/\t\t\tprintf(\"Near: %s\\n\", lines[x]->getLabel());\n\/\/\t\t}\n\/\/\t\tif (minIndex != lastSelectedLine)\n\/\/\t\t{\n\/\/\/\/\t\t\tif (lastSelectedLine != -1)\n\/\/\/\/\t\t\t\tlines[lastSelectedLine]->unselect();\n\/\/\/\/\t\t\tlines[minIndex]->select();\n\/\/\t\t\tlastSelectedLine = minIndex;\n\/\/\t\t\t\/\/printf(\"Near: %s\\n\", lines[minIndex]->getLabel());\n\/\/\t\t\t\/\/submitMessage(lines[minIndex]->getLabel());\n\/\/\t\t}\n\/\/\t}\n\/\/\n\/\/\tvoid Plot2D::Recenter(double lastX, double lastY, Rect &winRect)\n\/\/\t{\n\/\/\t\tdouble tpW = (dRight-dLeft)*.05;\n\/\/\t\tdouble tpH = (dTop-dBottom)*.05;\n\/\/\t\tdouble XLoc = dLeft-tpW+(dRight+2*tpW - dLeft)*(lastX\/winRect.right);\n\/\/\t\tdouble YLoc = dBottom-tpH+(dTop+2*tpH - dBottom)*(1-(lastY\/winRect.bottom));\n\/\/\n\/\/\t\txMin = XLoc - (dRight-dLeft)\/2;\n\/\/\t\txMax = XLoc + (dRight-dLeft)\/2;\n\/\/\t\tyMin = YLoc - (dTop-dBottom)\/2;\n\/\/\t\tyMax = YLoc + (dTop-dBottom)\/2;\n\/\/\t\t\n\/\/\t\tdLeft = xMin;\n\/\/\t\tdRight = xMax;\n\/\/\t\tdTop = yMax;\n\/\/\t\tdBottom = yMin;\n\/\/\t\t\n\/\/\t}\n\n\n\tvoid Plot2D::SmoothLines()\n\t{\n\t\tfor (unsigned int x = 0; x < lines.size(); x++)\n\t\t\tlines[x]->Smooth(50);\n\t\tResetAxis();\n\t}\n\n\tvoid Plot2D::OpenGLDraw() const\n\t{\n\t\tGLint matrixMode;\n\t\t\n\t\tif (recomputeBorders)\n\t\t\tassert(false);\n\/\/\t\t\tResetAxis();\n\t\t\n\t\tglGetIntegerv(GL_MATRIX_MODE, &matrixMode);\n\t\t\n\t\tglEnable(GL_BLEND); \/\/ for text fading\n\t\tglBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); \/\/ ditto\n\t\t\n\t\t\/\/ set orthograhic 1:1 pixel transform in local view coords\n\t\tglDisable(GL_DEPTH_TEST);\n\t\t\n\t\tglMatrixMode(GL_PROJECTION);\n\t\tglPushMatrix();\n\t\tglLoadIdentity();\n\t\tglMatrixMode(GL_MODELVIEW);\n\t\tglPushMatrix();\n\t\tglLoadIdentity();\n\t\tglColor3f(0, 1, 0);\n\t\t\n\t\t\/\/ left, right, bottom, top, near, far\n\t\tdouble tpW = (dRight-dLeft)*.05;\n\t\tdouble tpH = (dTop-dBottom)*.05;\n\t\tglOrtho(dLeft-tpW, dRight+tpW, dBottom-tpH, dTop+tpH, -1, 1);\n\t\t\/\/printf(\"Drawing axis (%1.2f, %1.2f, %1.2f, %1.2f)\\n\", dLeft, dTop, dRight, dBottom);\n\t\t\n\t\tglColor3f(1, 1, 1); \/\/ draw axis\n\t\tglBegin(GL_LINES);\n\t\tglVertex2d(dLeft-tpW, 0); glVertex2d(dRight+tpW, 0);\n\t\tglVertex2d(0, dBottom-tpH); glVertex2d(0, dTop+tpH);\n\t\tglEnd();\n\t\t\n\t\tfor (unsigned int x = 0; x < lines.size(); x++)\n\t\t{\n\t\t\tif (lines[x]->GetChanged())\n\t\t\t\tassert(false);\n\t\t\t\/\/recomputeBorders = true;\n\t\t\tlines[x]->OpenGLDraw();\n\t\t}\n\n\t\tglLineWidth(3.0);\n\t\tif (lastSelectedLine != -1)\n\t\t\tlines[lastSelectedLine]->OpenGLDraw();\n\t\tglLineWidth(1.0);\n\n\t\t\/\/ draw mouse - temporary hack\n\t\tif (drawMouse)\n\t\t{\n\t\t\tglColor4f(0, 1, 0, .5); \/\/ draw axis\n\t\t\tglBegin(GL_LINES);\n\t\t\tglVertex2d(mouseXLoc, dBottom-tpH); glVertex2d(mouseXLoc, dTop+tpH);\n\t\t\tglVertex2d(dLeft-tpW, mouseYLoc); glVertex2d(dRight+tpW, mouseYLoc);\n\t\t\tglEnd();\n\t\t}\n\n\t\tglPopMatrix(); \/\/ GL_MODELVIEW\n\t\tglMatrixMode(GL_PROJECTION);\n\t\tglPopMatrix();\n\t\tglMatrixMode(matrixMode);\n\t\t\n\t\tglEnable(GL_DEPTH_TEST);\n\t}\n}\n<|endoftext|>"} {"text":"<commit_before><commit_msg>Care for the entire height of the hbox when intersecting with obstacles, not just the baseline.<commit_after><|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2017 Leander Perera\r\n\/\/\r\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\r\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\r\n\/\/ in the Software without restriction, including without limitation the rights\r\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\r\n\/\/ copies of the Software, and to permit persons to whom the Software is\r\n\/\/ furnished to do so, subject to the following conditions:\r\n\/\/\r\n\/\/ The above copyright notice and this permission notice shall be included in all\r\n\/\/ copies or substantial portions of the Software.\r\n\/\/\r\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\r\n\/\/ SOFTWARE.\r\n\r\n#pragma once\r\n\r\n\/\/\/ The dynarray class manages an automatically re-sizing collection of elements.\r\ntemplate <class T>\r\nclass dynarray\r\n{\r\npublic:\r\n dynarray(unsigned int size = 0);\r\n ~dynarray();\r\n T get_element(unsigned int index);\r\n bool set_element(unsigned int index, T element);\r\n bool insert_element(unsigned int index, T element);\r\n bool delete_element(unsigned int index);\r\n unsigned int array_capacity();\r\n bool is_empty();\r\nprivate:\r\n bool resize_array(int newsize);\r\n T *mp_array;\r\n unsigned int m_capacity;\t \/\/ Size allocated for the array\r\n};\r\n\r\n\/\/\/ Function Swaps the values of the first and second arguments passed\r\n\/\/\/\r\n\/\/\/ @param[in,out] first reference to first item to swap\r\n\/\/\/ @param[in,out] second reference to second item to swap\r\ntemplate <class T>\r\nvoid swap(T &first, T &second)\r\n{\r\n T temp = first;\r\n first = second;\r\n second = temp;\r\n}\r\n\r\n\/\/\/ Function that copies the specified range of elements from the source array to the destination array\r\n\/\/\/\r\n\/\/\/ @param[in,out] dest_array The destination array to which elements will be copied to\r\n\/\/\/ @param[in] src_array The source array to which elements will be copied from\r\n\/\/\/ @param[in] from_index The starting index for the copy\r\n\/\/\/ @param[in] to_index The ending index for the copy\r\ntemplate <class T>\r\nbool copy_array_range(T &dest_array, const T &src_array, unsigned int from_index, unsigned int to_index)\r\n{\r\n return false;\r\n}\r\n\r\n\/\/\/ Resize the array by the specified size.\r\n\/\/\/\r\n\/\/\/ The function creates a new array of the specified size and copies the\r\n\/\/\/ contents from the old array to the new array. The old array is deallocated.\r\n\/\/\/ The function also updates the size of the dynamic array to the new size.\r\n\/\/\/ The newsize needs to be larger than the currently allocated size of the\r\n\/\/\/ array.\r\n\/\/\/\r\n\/\/\/ @param[in] newsize the size of the reallocated array\r\n\/\/\/ @return true if successful, false otherwise\r\ntemplate <class T>\r\nbool dynarray<T>::resize_array(int newsize)\r\n{\r\n bool retval = false;\r\n\r\n \/\/ Only resize if new size is larger than the currently allocated capacity\r\n if (newsize > m_capacity) {\r\n \/\/ Allocate new array of specified capacity\r\n T *p_new_array = new T[newsize]{}; \/\/ Initialize the elements to 0s\r\n if (p_new_array) {\r\n \/\/ Copy over elements from old array to new array\r\n for (unsigned int i = 0; i < m_capacity; ++i) {\r\n p_new_array[i] = mp_array[i];\r\n }\r\n\r\n \/\/ De-allocate the old array and make it point to the new array\r\n delete []mp_array;\r\n mp_array = p_new_array;\r\n\r\n \/\/ Update the new size of the array\r\n m_capacity = newsize;\r\n retval = true;\r\n }\r\n }\r\n\r\n return retval;\r\n}\r\n\r\n\/\/\/ Constructor with initial size for the dynamic array.\r\n\/\/\/\r\n\/\/\/ @param[in] size Amount of space to allocate for the dynamic array.\r\n\/\/\/ By default a 0 size array is created if no arguments\r\n\/\/\/ are specified.\r\ntemplate <class T>\r\ndynarray<T>::dynarray(unsigned int size)\r\n{\r\n \/\/ Initialize array elements to 0s. Ensure that allocation\r\n \/\/ does not throw an exception, but rather returns a NULL on failure.\r\n mp_array = new (std::nothrow) T[size]{};\r\n m_capacity = 0;\r\n\r\n \/\/ Set the size if the allocation was successful\r\n if (mp_array) {\r\n m_capacity = size;\r\n }\r\n}\r\n\r\n\/\/\/ Destructor deallocates memory allocated for the dynamic array\r\ntemplate <class T>\r\ndynarray<T>::~dynarray()\r\n{\r\n delete[] mp_array;\r\n mp_array = NULL;\r\n}\r\n\r\n\/\/\/ Returns the element at the specified index\r\n\/\/\/\r\n\/\/\/ @param[in] index A zero-based index ranging from from 0 to the size\r\n\/\/ of the array - 1.\r\ntemplate <class T>\r\nT dynarray<T>::get_element(unsigned int index)\r\n{\r\n\tT retVal;\r\n\tif (mp_array && index < m_capacity) {\r\n\t\tretVal = mp_array[index];\r\n\t}\r\n\r\n return retVal;\r\n}\r\n\r\n\/\/\/ Sets the element at the specified index.\r\n\/\/\/\r\n\/\/\/ The index needs to be within the capacity of the array. If not the function\r\n\/\/\/ will return a failure code.\r\n\/\/\/\r\n\/\/\/ @param[in] index A zero-based index ranging from from 0 to the size\r\n\/\/\/ of the array - 1.\r\n\/\/\/ @param[in] element The element to be stored at the specified index\r\n\/\/\/ @return true if successful, false otherwise\r\ntemplate <class T>\r\nbool dynarray<T>::set_element(unsigned int index, T element)\r\n{\r\n bool retval = false;\r\n if (mp_array && index < m_capacity) {\r\n \/\/ Store the element at the index\r\n mp_array[index] = element;\r\n retval = true;\r\n }\r\n\r\n return retval;\r\n}\r\n\r\n\/\/\/ Insert the specified element at the specified index.\r\n\/\/\/\r\n\/\/\/ @param[in] index A zero-based index ranging from from 0 to the size\r\n\/\/\/ of the array. If the index is equal to the size of the\r\n\/\/\/ dynamic array, the element is added to the end of the\r\n\/\/\/ dynamic array.\r\n\/\/\/ @param[in] element The item to be inserted into the dynamic array.\r\ntemplate <class T>\r\nbool dynarray<T>::insert_element(unsigned int index, T element)\r\n{\r\n bool retval = false;\r\n\r\n \/\/ The index needs to be between 0 and the capacity (inclusive)\r\n \/\/ If inserting new element at the begining, index is 0.\r\n \/\/ If inserting new element at the end, index = capacity.\r\n if (index <= m_capacity) {\r\n \/\/ Allocate array large enough to hold new element.\r\n \/\/ Initialize each element to 0.\r\n T *new_array = new T[m_capacity + 1]{};\r\n\r\n if (new_array) {\r\n \/\/ Store the new element at the index\r\n new_array[index] = element;\r\n\r\n \/\/ Copy the rest of the items to the new_array\r\n for (int i = 0, j = 0; i < m_capacity; ++i, ++j) {\r\n if (i == index) {\r\n \/\/ Skip the index for the new element that was already stored\r\n ++j;\r\n }\r\n new_array[j] = mp_array[i];\r\n }\r\n\r\n \/\/ Deallocate old array\r\n delete[] mp_array;\r\n\r\n \/\/ Assign new array\r\n mp_array = new_array;\r\n\r\n \/\/ Update the capacity of the array\r\n m_capacity += 1;\r\n retval = true;\r\n }\r\n }\r\n\r\n\treturn retval;\r\n}\r\n\r\n\/\/\/ Delete the element at the specified index.\r\n\/\/\/\r\n\/\/\/ @param[in] index A zero-based index ranging from from 0 to the size\r\n\/\/\/ of the array - 1.\r\ntemplate <class T>\r\nbool dynarray<T>::delete_element(unsigned int index)\r\n{\r\n return false;\r\n}\r\n\r\n\/\/\/ Returns the capacity of the backing array\r\n\/\/\/ @return capacity of backing array\r\ntemplate <class T>\r\nunsigned int dynarray<T>::array_capacity()\r\n{\r\n return m_capacity;\r\n}\r\n\r\n\/\/\/ Returns whether or not the array is empty\r\n\/\/\/ @return TRUE - array is empty, FALSE otherwise\r\ntemplate <class T>\r\nbool dynarray<T>::is_empty()\r\n{\r\n return (m_capacity == 0);\r\n}\r\n<commit_msg>Used size_t instead of unsigned int to take advantage of 64bit systems that can address more memory.<commit_after>\/\/ Copyright (c) 2017 Leander Perera\r\n\/\/\r\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\r\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\r\n\/\/ in the Software without restriction, including without limitation the rights\r\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\r\n\/\/ copies of the Software, and to permit persons to whom the Software is\r\n\/\/ furnished to do so, subject to the following conditions:\r\n\/\/\r\n\/\/ The above copyright notice and this permission notice shall be included in all\r\n\/\/ copies or substantial portions of the Software.\r\n\/\/\r\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\r\n\/\/ SOFTWARE.\r\n\r\n#pragma once\r\n#include <cstdlib>\r\n\r\n\/\/\/ The dynarray class manages an automatically re-sizing collection of elements.\r\ntemplate <class T>\r\nclass dynarray\r\n{\r\npublic:\r\n dynarray(size_t size = 0);\r\n ~dynarray();\r\n T get_element(size_t index);\r\n bool set_element(size_t index, T element);\r\n bool insert_element(size_t index, T element);\r\n bool delete_element(size_t index);\r\n size_t array_capacity();\r\n bool is_empty();\r\nprivate:\r\n bool resize_array(size_t newsize);\r\n T *mp_array;\r\n size_t m_capacity;\t \/\/ Size allocated for the array\r\n};\r\n\r\n\/\/\/ Function Swaps the values of the first and second arguments passed\r\n\/\/\/\r\n\/\/\/ @param[in,out] first reference to first item to swap\r\n\/\/\/ @param[in,out] second reference to second item to swap\r\ntemplate <class T>\r\nvoid swap(T &first, T &second)\r\n{\r\n T temp = first;\r\n first = second;\r\n second = temp;\r\n}\r\n\r\n\/\/\/ Function that copies the specified range of elements from the source array to the destination array\r\n\/\/\/\r\n\/\/\/ @param[in,out] dest_array The destination array to which elements will be copied to\r\n\/\/\/ @param[in] src_array The source array to which elements will be copied from\r\n\/\/\/ @param[in] from_index The starting index for the copy\r\n\/\/\/ @param[in] to_index The ending index for the copy\r\ntemplate <class T>\r\nbool copy_array_range(T &dest_array, const T &src_array, size_t from_index, size_t to_index)\r\n{\r\n return false;\r\n}\r\n\r\n\/\/\/ Resize the array by the specified size.\r\n\/\/\/\r\n\/\/\/ The function creates a new array of the specified size and copies the\r\n\/\/\/ contents from the old array to the new array. The old array is deallocated.\r\n\/\/\/ The function also updates the size of the dynamic array to the new size.\r\n\/\/\/ The newsize needs to be larger than the currently allocated size of the\r\n\/\/\/ array.\r\n\/\/\/\r\n\/\/\/ @param[in] newsize the size of the reallocated array\r\n\/\/\/ @return true if successful, false otherwise\r\ntemplate <class T>\r\nbool dynarray<T>::resize_array(size_t newsize)\r\n{\r\n bool retval = false;\r\n\r\n \/\/ Only resize if new size is larger than the currently allocated capacity\r\n if (newsize > m_capacity) {\r\n \/\/ Allocate new array of specified capacity\r\n T *p_new_array = new T[newsize]{}; \/\/ Initialize the elements to 0s\r\n if (p_new_array) {\r\n \/\/ Copy over elements from old array to new array\r\n for (unsigned int i = 0; i < m_capacity; ++i) {\r\n p_new_array[i] = mp_array[i];\r\n }\r\n\r\n \/\/ De-allocate the old array and make it point to the new array\r\n delete []mp_array;\r\n mp_array = p_new_array;\r\n\r\n \/\/ Update the new size of the array\r\n m_capacity = newsize;\r\n retval = true;\r\n }\r\n }\r\n\r\n return retval;\r\n}\r\n\r\n\/\/\/ Constructor with initial size for the dynamic array.\r\n\/\/\/\r\n\/\/\/ @param[in] size Amount of space to allocate for the dynamic array.\r\n\/\/\/ By default a 0 size array is created if no arguments\r\n\/\/\/ are specified.\r\ntemplate <class T>\r\ndynarray<T>::dynarray(size_t size)\r\n{\r\n \/\/ Initialize array elements to 0s. Ensure that allocation\r\n \/\/ does not throw an exception, but rather returns a NULL on failure.\r\n mp_array = new (std::nothrow) T[size]{};\r\n m_capacity = 0;\r\n\r\n \/\/ Set the size if the allocation was successful\r\n if (mp_array) {\r\n m_capacity = size;\r\n }\r\n}\r\n\r\n\/\/\/ Destructor deallocates memory allocated for the dynamic array\r\ntemplate <class T>\r\ndynarray<T>::~dynarray()\r\n{\r\n delete[] mp_array;\r\n mp_array = NULL;\r\n}\r\n\r\n\/\/\/ Returns the element at the specified index\r\n\/\/\/\r\n\/\/\/ @param[in] index A zero-based index ranging from from 0 to the size\r\n\/\/ of the array - 1.\r\ntemplate <class T>\r\nT dynarray<T>::get_element(size_t index)\r\n{\r\n\tT retVal;\r\n\tif (mp_array && index < m_capacity) {\r\n\t\tretVal = mp_array[index];\r\n\t}\r\n\r\n return retVal;\r\n}\r\n\r\n\/\/\/ Sets the element at the specified index.\r\n\/\/\/\r\n\/\/\/ The index needs to be within the capacity of the array. If not the function\r\n\/\/\/ will return a failure code.\r\n\/\/\/\r\n\/\/\/ @param[in] index A zero-based index ranging from from 0 to the size\r\n\/\/\/ of the array - 1.\r\n\/\/\/ @param[in] element The element to be stored at the specified index\r\n\/\/\/ @return true if successful, false otherwise\r\ntemplate <class T>\r\nbool dynarray<T>::set_element(size_t index, T element)\r\n{\r\n bool retval = false;\r\n if (mp_array && index < m_capacity) {\r\n \/\/ Store the element at the index\r\n mp_array[index] = element;\r\n retval = true;\r\n }\r\n\r\n return retval;\r\n}\r\n\r\n\/\/\/ Insert the specified element at the specified index.\r\n\/\/\/\r\n\/\/\/ @param[in] index A zero-based index ranging from from 0 to the size\r\n\/\/\/ of the array. If the index is equal to the size of the\r\n\/\/\/ dynamic array, the element is added to the end of the\r\n\/\/\/ dynamic array.\r\n\/\/\/ @param[in] element The item to be inserted into the dynamic array.\r\ntemplate <class T>\r\nbool dynarray<T>::insert_element(size_t index, T element)\r\n{\r\n bool retval = false;\r\n\r\n \/\/ The index needs to be between 0 and the capacity (inclusive)\r\n \/\/ If inserting new element at the begining, index is 0.\r\n \/\/ If inserting new element at the end, index = capacity.\r\n if (index <= m_capacity) {\r\n \/\/ Allocate array large enough to hold new element.\r\n \/\/ Initialize each element to 0.\r\n T *new_array = new T[m_capacity + 1]{};\r\n\r\n if (new_array) {\r\n \/\/ Store the new element at the index\r\n new_array[index] = element;\r\n\r\n \/\/ Copy the rest of the items to the new_array\r\n for (int i = 0, j = 0; i < m_capacity; ++i, ++j) {\r\n if (i == index) {\r\n \/\/ Skip the index for the new element that was already stored\r\n ++j;\r\n }\r\n new_array[j] = mp_array[i];\r\n }\r\n\r\n \/\/ Deallocate old array\r\n delete[] mp_array;\r\n\r\n \/\/ Assign new array\r\n mp_array = new_array;\r\n\r\n \/\/ Update the capacity of the array\r\n m_capacity += 1;\r\n retval = true;\r\n }\r\n }\r\n\r\n\treturn retval;\r\n}\r\n\r\n\/\/\/ Delete the element at the specified index.\r\n\/\/\/\r\n\/\/\/ @param[in] index A zero-based index ranging from from 0 to the size\r\n\/\/\/ of the array - 1.\r\ntemplate <class T>\r\nbool dynarray<T>::delete_element(size_t index)\r\n{\r\n return false;\r\n}\r\n\r\n\/\/\/ Returns the capacity of the backing array\r\n\/\/\/ @return capacity of backing array\r\ntemplate <class T>\r\nsize_t dynarray<T>::array_capacity()\r\n{\r\n return m_capacity;\r\n}\r\n\r\n\/\/\/ Returns whether or not the array is empty\r\n\/\/\/ @return TRUE - array is empty, FALSE otherwise\r\ntemplate <class T>\r\nbool dynarray<T>::is_empty()\r\n{\r\n return (m_capacity == 0);\r\n}\r\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: browserlistbox.hxx,v $\n *\n * $Revision: 1.8 $\n *\n * last change: $Author: vg $ $Date: 2006-03-14 11:17:37 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef _EXTENSIONS_PROPCTRLR_BROWSERLISTBOX_HXX_\n#define _EXTENSIONS_PROPCTRLR_BROWSERLISTBOX_HXX_\n\n#ifndef _EXTENSIONS_PROPCTRLR_BROWSERLINE_HXX_\n#include \"browserline.hxx\"\n#endif\n#ifndef _EXTENSIONS_PROPCTRLR_MODULEPRC_HXX_\n#include \"modulepcr.hxx\"\n#endif\n#ifndef _EXTENSIONS_PROPCTRLR_PCRCOMMON_HXX_\n#include \"pcrcommon.hxx\"\n#endif\n\n\/** === begin UNO includes === **\/\n#ifndef _COM_SUN_STAR_INSPECTION_XPROPERTYCONTROL_HPP_\n#include <com\/sun\/star\/inspection\/XPropertyControl.hpp>\n#endif\n#ifndef _COM_SUN_STAR_INSPECTION_XPROPERTYHANDLER_HPP_\n#include <com\/sun\/star\/inspection\/XPropertyHandler.hpp>\n#endif\n\/** === end UNO includes === **\/\n\n#ifndef _SV_SCRBAR_HXX\n#include <vcl\/scrbar.hxx>\n#endif\n#ifndef _SV_LSTBOX_HXX\n#include <vcl\/lstbox.hxx>\n#endif\n#ifndef _SV_BUTTON_HXX\n#include <vcl\/button.hxx>\n#endif\n#ifndef _LINK_HXX\n#include <tools\/link.hxx>\n#endif\n#ifndef _RTL_REF_HXX_\n#include <rtl\/ref.hxx>\n#endif\n\n#include <set>\n#include <vector>\n#include <hash_map>\n#include <boost\/shared_ptr.hpp>\n\n\/\/............................................................................\nnamespace pcr\n{\n\/\/............................................................................\n\n class IPropertyLineListener;\n struct OLineDescriptor;\n class PropertyControlContext_Impl;\n\n \/\/========================================================================\n \/\/= administrative structures for OBrowserListBox\n \/\/========================================================================\n typedef ::boost::shared_ptr< OBrowserLine > BrowserLinePointer;\n struct ListBoxLine\n {\n BrowserLinePointer pLine;\n ::com::sun::star::uno::Reference< ::com::sun::star::inspection::XPropertyHandler >\n xHandler;\n\n ListBoxLine() { }\n ListBoxLine( BrowserLinePointer _pLine, const ::com::sun::star::uno::Reference< ::com::sun::star::inspection::XPropertyHandler >& _rxHandler )\n :pLine( _pLine )\n ,xHandler( _rxHandler )\n {\n }\n };\n typedef ::std::hash_map< ::rtl::OUString, ListBoxLine, ::rtl::OUStringHash > ListBoxLines;\n typedef ::std::vector< ListBoxLines::iterator > OrderedListBoxLines;\n\n \/\/========================================================================\n \/\/= IControlContext\n \/\/========================================================================\n \/** non-UNO version of XPropertyControlContext\n *\/\n class SAL_NO_VTABLE IControlContext\n {\n public:\n virtual void SAL_CALL focusGained( const ::com::sun::star::uno::Reference< ::com::sun::star::inspection::XPropertyControl >& Control ) throw (::com::sun::star::uno::RuntimeException) = 0;\n virtual void SAL_CALL controlValueChanged( const ::com::sun::star::uno::Reference< ::com::sun::star::inspection::XPropertyControl >& Control ) throw (::com::sun::star::uno::RuntimeException) = 0;\n virtual void SAL_CALL activateNextControl( const ::com::sun::star::uno::Reference< ::com::sun::star::inspection::XPropertyControl >& CurrentControl ) throw (::com::sun::star::uno::RuntimeException) = 0;\n };\n\n \/\/========================================================================\n \/\/= OBrowserListBox\n \/\/========================================================================\n class OBrowserListBox :public Control\n ,public IButtonClickListener\n ,public IControlContext\n ,public PcrClient\n {\n protected:\n Window m_aPlayGround;\n ScrollBar m_aVScroll;\n ListBoxLines m_aLines;\n OrderedListBoxLines m_aOrderedLines;\n IPropertyLineListener* m_pLineListener;\n long m_nYOffset;\n ::com::sun::star::uno::Reference< ::com::sun::star::inspection::XPropertyControl >\n m_xActiveControl;\n sal_uInt16 m_nTheNameSize;\n sal_uInt16 m_nRowHeight;\n ::std::set< sal_uInt16 > m_aOutOfDateLines;\n sal_Bool m_bIsActive : 1;\n sal_Bool m_bUpdate : 1;\n ::rtl::Reference< PropertyControlContext_Impl >\n m_pControlContextImpl;\n\n protected:\n void PositionLine( sal_uInt16 _nIndex );\n void UpdatePosNSize();\n void UpdatePlayGround();\n void UpdateVScroll();\n void ShowEntry(sal_uInt16 nPos);\n void MoveThumbTo(long nNewThumbPos);\n void Resize();\n\n public:\n OBrowserListBox( Window* pParent, WinBits nWinStyle = WB_DIALOGCONTROL );\n\n ~OBrowserListBox();\n\n void UpdateAll();\n\n void Activate(sal_Bool _bActive = sal_True);\n\n sal_uInt16 CalcVisibleLines();\n void EnableUpdate();\n void DisableUpdate();\n long Notify( NotifyEvent& _rNEvt );\n\n void setListener(IPropertyLineListener* _pPLL);\n\n void Clear();\n\n sal_uInt16 InsertEntry( const OLineDescriptor&, sal_uInt16 nPos = EDITOR_LIST_APPEND );\n sal_Bool RemoveEntry( const ::rtl::OUString& _rName );\n void ChangeEntry( const OLineDescriptor&, sal_uInt16 nPos );\n\n void SetPropertyValue( const ::rtl::OUString& rEntryName, const ::com::sun::star::uno::Any& rValue );\n ::com::sun::star::uno::Any GetPropertyValue( const ::rtl::OUString& rEntryName ) const;\n sal_uInt16 GetPropertyPos( const ::rtl::OUString& rEntryName ) const;\n ::com::sun::star::uno::Reference< ::com::sun::star::inspection::XPropertyControl >\n GetPropertyControl( const ::rtl::OUString& rEntryName );\n void EnablePropertyControls( const ::rtl::OUString& _rEntryName, sal_Int16 _nControls, bool _bEnable );\n void EnablePropertyLine( const ::rtl::OUString& _rEntryName, bool _bEnable );\n sal_Bool IsPropertyInputEnabled( const ::rtl::OUString& _rEntryName ) const;\n\n \/\/ #95343# --------------------------\n sal_Int32 GetMinimumWidth();\n\n\n sal_Bool IsModified( ) const;\n void CommitModified( );\n\n protected:\n \/\/ IControlContext\n virtual void SAL_CALL focusGained( const ::com::sun::star::uno::Reference< ::com::sun::star::inspection::XPropertyControl >& Control ) throw (::com::sun::star::uno::RuntimeException);\n virtual void SAL_CALL controlValueChanged( const ::com::sun::star::uno::Reference< ::com::sun::star::inspection::XPropertyControl >& Control ) throw (::com::sun::star::uno::RuntimeException);\n virtual void SAL_CALL activateNextControl( const ::com::sun::star::uno::Reference< ::com::sun::star::inspection::XPropertyControl >& CurrentControl ) throw (::com::sun::star::uno::RuntimeException);\n\n \/\/ IButtonClickListener\n void buttonClicked( OBrowserLine* _pLine, sal_Bool _bPrimary );\n\n private:\n DECL_LINK( ScrollHdl, ScrollBar* );\n\n \/** retrieves the index of a given control in our line list\n @param _rxControl\n The control to lookup. Must denote a control of one of the lines in ->m_aLines\n *\/\n sal_uInt16 impl_getControlPos( const ::com::sun::star::uno::Reference< ::com::sun::star::inspection::XPropertyControl >& _rxControl ) const;\n\n \/** retrieves (a reference to) the ->ListBoxLine for a given control\n @param _rxControl\n The control to lookup. Must denote a control of one of the lines in ->m_aLines\n *\/\n inline const ListBoxLine&\n impl_getControlLine( const ::com::sun::star::uno::Reference< ::com::sun::star::inspection::XPropertyControl >& _rxControl ) const\n {\n return m_aOrderedLines[ impl_getControlPos( _rxControl ) ]->second;\n }\n\n \/** sets the given property value at the given control, after converting it as necessary\n @param _rLine\n The line whose at which the value is to be set.\n @param _rPropertyValue\n the property value to set. If it's not compatible with the control value,\n it will be converted, using <member>XPropertyHandler::convertToControlValue<\/member>\n *\/\n void impl_setControlAsPropertyValue( const ListBoxLine& _rLine, const ::com::sun::star::uno::Any& _rPropertyValue );\n\n \/** retrieves the value for the given control, as a property value, after converting it as necessary\n @param _rLine\n The line whose at which the value is to be set.\n *\/\n ::com::sun::star::uno::Any\n impl_getControlAsPropertyValue( const ListBoxLine& _rLine ) const;\n\n \/** retrieves the ->BrowserLinePointer for a given entry name\n @param _rEntryName\n the name whose line is to be looked up\n @param _out_rpLine\n contains, upon return, the found browser line, if any\n @return\n <TRUE\/> if and only if a non-<NULL\/> line for the given entry name could be\n found.\n *\/\n bool impl_getBrowserLineForName( const ::rtl::OUString& _rEntryName, BrowserLinePointer& _out_rpLine ) const;\n };\n\n\/\/............................................................................\n} \/\/ namespace pcr\n\/\/............................................................................\n\n#endif \/\/ _EXTENSIONS_PROPCTRLR_BROWSERLISTBOX_HXX_\n\n\n<commit_msg>INTEGRATION: CWS long2int (1.7.34); FILE MERGED 2006\/03\/17 19:23:25 pjanik 1.7.34.2: RESYNC: (1.7-1.8); FILE MERGED 2005\/10\/26 18:07:11 kendy 1.7.34.1: #i56715# Trivial long\/ULONG -> sal_Int32\/sal_uInt32 patches extracted from ooo64bit02 CWS.<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: browserlistbox.hxx,v $\n *\n * $Revision: 1.9 $\n *\n * last change: $Author: vg $ $Date: 2006-03-31 09:24:18 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef _EXTENSIONS_PROPCTRLR_BROWSERLISTBOX_HXX_\n#define _EXTENSIONS_PROPCTRLR_BROWSERLISTBOX_HXX_\n\n#ifndef _EXTENSIONS_PROPCTRLR_BROWSERLINE_HXX_\n#include \"browserline.hxx\"\n#endif\n#ifndef _EXTENSIONS_PROPCTRLR_MODULEPRC_HXX_\n#include \"modulepcr.hxx\"\n#endif\n#ifndef _EXTENSIONS_PROPCTRLR_PCRCOMMON_HXX_\n#include \"pcrcommon.hxx\"\n#endif\n\n\/** === begin UNO includes === **\/\n#ifndef _COM_SUN_STAR_INSPECTION_XPROPERTYCONTROL_HPP_\n#include <com\/sun\/star\/inspection\/XPropertyControl.hpp>\n#endif\n#ifndef _COM_SUN_STAR_INSPECTION_XPROPERTYHANDLER_HPP_\n#include <com\/sun\/star\/inspection\/XPropertyHandler.hpp>\n#endif\n\/** === end UNO includes === **\/\n\n#ifndef _SV_SCRBAR_HXX\n#include <vcl\/scrbar.hxx>\n#endif\n#ifndef _SV_LSTBOX_HXX\n#include <vcl\/lstbox.hxx>\n#endif\n#ifndef _SV_BUTTON_HXX\n#include <vcl\/button.hxx>\n#endif\n#ifndef _LINK_HXX\n#include <tools\/link.hxx>\n#endif\n#ifndef _RTL_REF_HXX_\n#include <rtl\/ref.hxx>\n#endif\n\n#include <set>\n#include <vector>\n#include <hash_map>\n#include <boost\/shared_ptr.hpp>\n\n\/\/............................................................................\nnamespace pcr\n{\n\/\/............................................................................\n\n class IPropertyLineListener;\n struct OLineDescriptor;\n class PropertyControlContext_Impl;\n\n \/\/========================================================================\n \/\/= administrative structures for OBrowserListBox\n \/\/========================================================================\n typedef ::boost::shared_ptr< OBrowserLine > BrowserLinePointer;\n struct ListBoxLine\n {\n BrowserLinePointer pLine;\n ::com::sun::star::uno::Reference< ::com::sun::star::inspection::XPropertyHandler >\n xHandler;\n\n ListBoxLine() { }\n ListBoxLine( BrowserLinePointer _pLine, const ::com::sun::star::uno::Reference< ::com::sun::star::inspection::XPropertyHandler >& _rxHandler )\n :pLine( _pLine )\n ,xHandler( _rxHandler )\n {\n }\n };\n typedef ::std::hash_map< ::rtl::OUString, ListBoxLine, ::rtl::OUStringHash > ListBoxLines;\n typedef ::std::vector< ListBoxLines::iterator > OrderedListBoxLines;\n\n \/\/========================================================================\n \/\/= IControlContext\n \/\/========================================================================\n \/** non-UNO version of XPropertyControlContext\n *\/\n class SAL_NO_VTABLE IControlContext\n {\n public:\n virtual void SAL_CALL focusGained( const ::com::sun::star::uno::Reference< ::com::sun::star::inspection::XPropertyControl >& Control ) throw (::com::sun::star::uno::RuntimeException) = 0;\n virtual void SAL_CALL controlValueChanged( const ::com::sun::star::uno::Reference< ::com::sun::star::inspection::XPropertyControl >& Control ) throw (::com::sun::star::uno::RuntimeException) = 0;\n virtual void SAL_CALL activateNextControl( const ::com::sun::star::uno::Reference< ::com::sun::star::inspection::XPropertyControl >& CurrentControl ) throw (::com::sun::star::uno::RuntimeException) = 0;\n };\n\n \/\/========================================================================\n \/\/= OBrowserListBox\n \/\/========================================================================\n class OBrowserListBox :public Control\n ,public IButtonClickListener\n ,public IControlContext\n ,public PcrClient\n {\n protected:\n Window m_aPlayGround;\n ScrollBar m_aVScroll;\n ListBoxLines m_aLines;\n OrderedListBoxLines m_aOrderedLines;\n IPropertyLineListener* m_pLineListener;\n long m_nYOffset;\n ::com::sun::star::uno::Reference< ::com::sun::star::inspection::XPropertyControl >\n m_xActiveControl;\n sal_uInt16 m_nTheNameSize;\n sal_uInt16 m_nRowHeight;\n ::std::set< sal_uInt16 > m_aOutOfDateLines;\n sal_Bool m_bIsActive : 1;\n sal_Bool m_bUpdate : 1;\n ::rtl::Reference< PropertyControlContext_Impl >\n m_pControlContextImpl;\n\n protected:\n void PositionLine( sal_uInt16 _nIndex );\n void UpdatePosNSize();\n void UpdatePlayGround();\n void UpdateVScroll();\n void ShowEntry(sal_uInt16 nPos);\n void MoveThumbTo(sal_Int32 nNewThumbPos);\n void Resize();\n\n public:\n OBrowserListBox( Window* pParent, WinBits nWinStyle = WB_DIALOGCONTROL );\n\n ~OBrowserListBox();\n\n void UpdateAll();\n\n void Activate(sal_Bool _bActive = sal_True);\n\n sal_uInt16 CalcVisibleLines();\n void EnableUpdate();\n void DisableUpdate();\n long Notify( NotifyEvent& _rNEvt );\n\n void setListener(IPropertyLineListener* _pPLL);\n\n void Clear();\n\n sal_uInt16 InsertEntry( const OLineDescriptor&, sal_uInt16 nPos = EDITOR_LIST_APPEND );\n sal_Bool RemoveEntry( const ::rtl::OUString& _rName );\n void ChangeEntry( const OLineDescriptor&, sal_uInt16 nPos );\n\n void SetPropertyValue( const ::rtl::OUString& rEntryName, const ::com::sun::star::uno::Any& rValue );\n ::com::sun::star::uno::Any GetPropertyValue( const ::rtl::OUString& rEntryName ) const;\n sal_uInt16 GetPropertyPos( const ::rtl::OUString& rEntryName ) const;\n ::com::sun::star::uno::Reference< ::com::sun::star::inspection::XPropertyControl >\n GetPropertyControl( const ::rtl::OUString& rEntryName );\n void EnablePropertyControls( const ::rtl::OUString& _rEntryName, sal_Int16 _nControls, bool _bEnable );\n void EnablePropertyLine( const ::rtl::OUString& _rEntryName, bool _bEnable );\n sal_Bool IsPropertyInputEnabled( const ::rtl::OUString& _rEntryName ) const;\n\n \/\/ #95343# --------------------------\n sal_Int32 GetMinimumWidth();\n\n\n sal_Bool IsModified( ) const;\n void CommitModified( );\n\n protected:\n \/\/ IControlContext\n virtual void SAL_CALL focusGained( const ::com::sun::star::uno::Reference< ::com::sun::star::inspection::XPropertyControl >& Control ) throw (::com::sun::star::uno::RuntimeException);\n virtual void SAL_CALL controlValueChanged( const ::com::sun::star::uno::Reference< ::com::sun::star::inspection::XPropertyControl >& Control ) throw (::com::sun::star::uno::RuntimeException);\n virtual void SAL_CALL activateNextControl( const ::com::sun::star::uno::Reference< ::com::sun::star::inspection::XPropertyControl >& CurrentControl ) throw (::com::sun::star::uno::RuntimeException);\n\n \/\/ IButtonClickListener\n void buttonClicked( OBrowserLine* _pLine, sal_Bool _bPrimary );\n\n private:\n DECL_LINK( ScrollHdl, ScrollBar* );\n\n \/** retrieves the index of a given control in our line list\n @param _rxControl\n The control to lookup. Must denote a control of one of the lines in ->m_aLines\n *\/\n sal_uInt16 impl_getControlPos( const ::com::sun::star::uno::Reference< ::com::sun::star::inspection::XPropertyControl >& _rxControl ) const;\n\n \/** retrieves (a reference to) the ->ListBoxLine for a given control\n @param _rxControl\n The control to lookup. Must denote a control of one of the lines in ->m_aLines\n *\/\n inline const ListBoxLine&\n impl_getControlLine( const ::com::sun::star::uno::Reference< ::com::sun::star::inspection::XPropertyControl >& _rxControl ) const\n {\n return m_aOrderedLines[ impl_getControlPos( _rxControl ) ]->second;\n }\n\n \/** sets the given property value at the given control, after converting it as necessary\n @param _rLine\n The line whose at which the value is to be set.\n @param _rPropertyValue\n the property value to set. If it's not compatible with the control value,\n it will be converted, using <member>XPropertyHandler::convertToControlValue<\/member>\n *\/\n void impl_setControlAsPropertyValue( const ListBoxLine& _rLine, const ::com::sun::star::uno::Any& _rPropertyValue );\n\n \/** retrieves the value for the given control, as a property value, after converting it as necessary\n @param _rLine\n The line whose at which the value is to be set.\n *\/\n ::com::sun::star::uno::Any\n impl_getControlAsPropertyValue( const ListBoxLine& _rLine ) const;\n\n \/** retrieves the ->BrowserLinePointer for a given entry name\n @param _rEntryName\n the name whose line is to be looked up\n @param _out_rpLine\n contains, upon return, the found browser line, if any\n @return\n <TRUE\/> if and only if a non-<NULL\/> line for the given entry name could be\n found.\n *\/\n bool impl_getBrowserLineForName( const ::rtl::OUString& _rEntryName, BrowserLinePointer& _out_rpLine ) const;\n };\n\n\/\/............................................................................\n} \/\/ namespace pcr\n\/\/............................................................................\n\n#endif \/\/ _EXTENSIONS_PROPCTRLR_BROWSERLISTBOX_HXX_\n\n\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2008 by Sun Microsystems, Inc.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: propertyeditor.hxx,v $\n * $Revision: 1.17 $\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * <http:\/\/www.openoffice.org\/license.html>\n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n#ifndef _EXTENSIONS_PROPCTRLR_PROPERTYEDITOR_HXX_\n#define _EXTENSIONS_PROPCTRLR_PROPERTYEDITOR_HXX_\n\n#include \"pcrcommon.hxx\"\n\n\/** === begin UNO includes === **\/\n#include <com\/sun\/star\/inspection\/XPropertyControl.hpp>\n\/** === end UNO includes === **\/\n#include <vcl\/tabctrl.hxx>\n#include <comphelper\/stl_types.hxx>\n#include <boost\/mem_fn.hpp>\n#include <map>\n\n\/\/............................................................................\nnamespace pcr\n{\n\/\/............................................................................\n\n class IPropertyLineListener;\n class IPropertyControlObserver;\n class OBrowserPage;\n struct OLineDescriptor;\n class OBrowserListBox;\n\n \/\/========================================================================\n \/\/= OPropertyEditor\n \/\/========================================================================\n class OPropertyEditor : public Control\n {\n private:\n typedef ::std::map< ::rtl::OUString, sal_uInt16 > MapStringToPageId;\n struct HiddenPage\n {\n sal_uInt16 nPos;\n TabPage* pPage;\n HiddenPage() : nPos( 0 ), pPage( NULL ) { }\n HiddenPage( sal_uInt16 _nPos, TabPage* _pPage ) : nPos( _nPos ), pPage( _pPage ) { }\n };\n\n private:\n TabControl m_aTabControl;\n IPropertyLineListener* m_pListener;\n IPropertyControlObserver* m_pObserver;\n sal_uInt16 m_nNextId;\n Link m_aPageActivationHandler;\n bool m_bHasHelpSection;\n sal_Int32 m_nMinHelpLines;\n sal_Int32 m_nMaxHelpLines;\n\n MapStringToPageId m_aPropertyPageIds;\n ::std::map< sal_uInt16, HiddenPage > m_aHiddenPages;\n\n protected:\n void Resize();\n void GetFocus();\n\n public:\n OPropertyEditor (Window* pParent, WinBits nWinStyle = WB_DIALOGCONTROL);\n\n ~OPropertyEditor();\n\n sal_uInt16 CalcVisibleLines();\n void EnableUpdate();\n void DisableUpdate();\n\n void SetLineListener( IPropertyLineListener* );\n void SetControlObserver( IPropertyControlObserver* );\n\n void EnableHelpSection( bool _bEnable );\n bool HasHelpSection() const;\n void SetHelpText( const ::rtl::OUString& _rHelpText );\n void SetHelpLineLimites( sal_Int32 _nMinLines, sal_Int32 _nMaxLines );\n\n void SetHelpId( sal_uInt32 nHelpId );\n sal_uInt16 AppendPage( const String& r, const SmartId& _rHelpId );\n void SetPage( sal_uInt16 );\n void RemovePage(sal_uInt16 nID);\n sal_uInt16 GetCurPage();\n void ClearAll();\n\n void SetPropertyValue(const ::rtl::OUString& _rEntryName, const ::com::sun::star::uno::Any& _rValue );\n ::com::sun::star::uno::Any GetPropertyValue(const ::rtl::OUString& rEntryName ) const;\n sal_uInt16 GetPropertyPos(const ::rtl::OUString& rEntryName ) const;\n ::com::sun::star::uno::Reference< ::com::sun::star::inspection::XPropertyControl >\n GetPropertyControl( const ::rtl::OUString& rEntryName );\n void EnablePropertyLine( const ::rtl::OUString& _rEntryName, bool _bEnable );\n void EnablePropertyControls( const ::rtl::OUString& _rEntryName, sal_Int16 _nControls, bool _bEnable );\n sal_Bool IsPropertyInputEnabled( const ::rtl::OUString& _rEntryName ) const;\n\n void ShowPropertyPage( sal_uInt16 _nPageId, bool _bShow );\n\n sal_uInt16 InsertEntry( const OLineDescriptor&, sal_uInt16 _nPageId, sal_uInt16 nPos = EDITOR_LIST_APPEND );\n void RemoveEntry( const ::rtl::OUString& _rName );\n void ChangeEntry( const OLineDescriptor& );\n\n void setPageActivationHandler(const Link& _rHdl) { m_aPageActivationHandler = _rHdl; }\n Link getPageActivationHandler() const { return m_aPageActivationHandler; }\n\n \/\/ #95343# -------------------------------\n sal_Int32 getMinimumWidth();\n sal_Int32 getMinimumHeight();\n\n void CommitModified();\n\n protected:\n using Window::SetHelpText;\n using Window::Update;\n\n private:\n OBrowserPage* getPage( sal_uInt16& _rPageId );\n const OBrowserPage* getPage( sal_uInt16& _rPageId ) const;\n\n OBrowserPage* getPage( const ::rtl::OUString& _rPropertyName );\n const OBrowserPage* getPage( const ::rtl::OUString& _rPropertyName ) const;\n\n void Update(const ::std::mem_fun_t<void,OBrowserListBox>& _aUpdateFunction);\n\n typedef void (OPropertyEditor::*PageOperation)( OBrowserPage&, const void* );\n void forEachPage( PageOperation _pOperation, const void* _pArgument = NULL );\n\n void setPageLineListener( OBrowserPage& _rPage, const void* );\n void setPageControlObserver( OBrowserPage& _rPage, const void* );\n void enableHelpSection( OBrowserPage& _rPage, const void* );\n void setHelpSectionText( OBrowserPage& _rPage, const void* _pPointerToOUString );\n void setHelpLineLimits( OBrowserPage& _rPage, const void* );\n\n protected:\n DECL_LINK(OnPageDeactivate, TabControl*);\n DECL_LINK(OnPageActivate, TabControl*);\n };\n\n\/\/............................................................................\n} \/\/ namespace pcr\n\/\/............................................................................\n\n#endif \/\/ _EXTENSIONS_PROPCTRLR_PROPERTYEDITOR_HXX_\n\n\n<commit_msg>INTEGRATION: CWS mba30patches01 (1.16.4); FILE MERGED 2008\/04\/23 10:49:57 mba 1.16.4.2: RESYNC: (1.16-1.17); FILE MERGED 2008\/03\/18 15:41:00 mba 1.16.4.1: #i86365#: remove unused code<commit_after>\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2008 by Sun Microsystems, Inc.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: propertyeditor.hxx,v $\n * $Revision: 1.18 $\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * <http:\/\/www.openoffice.org\/license.html>\n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n#ifndef _EXTENSIONS_PROPCTRLR_PROPERTYEDITOR_HXX_\n#define _EXTENSIONS_PROPCTRLR_PROPERTYEDITOR_HXX_\n\n#include \"pcrcommon.hxx\"\n\n\/** === begin UNO includes === **\/\n#include <com\/sun\/star\/inspection\/XPropertyControl.hpp>\n\/** === end UNO includes === **\/\n#include <vcl\/tabctrl.hxx>\n#include <comphelper\/stl_types.hxx>\n#include <boost\/mem_fn.hpp>\n#include <map>\n\n\/\/............................................................................\nnamespace pcr\n{\n\/\/............................................................................\n\n class IPropertyLineListener;\n class IPropertyControlObserver;\n class OBrowserPage;\n struct OLineDescriptor;\n class OBrowserListBox;\n\n \/\/========================================================================\n \/\/= OPropertyEditor\n \/\/========================================================================\n class OPropertyEditor : public Control\n {\n private:\n typedef ::std::map< ::rtl::OUString, sal_uInt16 > MapStringToPageId;\n struct HiddenPage\n {\n sal_uInt16 nPos;\n TabPage* pPage;\n HiddenPage() : nPos( 0 ), pPage( NULL ) { }\n HiddenPage( sal_uInt16 _nPos, TabPage* _pPage ) : nPos( _nPos ), pPage( _pPage ) { }\n };\n\n private:\n TabControl m_aTabControl;\n IPropertyLineListener* m_pListener;\n IPropertyControlObserver* m_pObserver;\n sal_uInt16 m_nNextId;\n Link m_aPageActivationHandler;\n bool m_bHasHelpSection;\n sal_Int32 m_nMinHelpLines;\n sal_Int32 m_nMaxHelpLines;\n\n MapStringToPageId m_aPropertyPageIds;\n ::std::map< sal_uInt16, HiddenPage > m_aHiddenPages;\n\n protected:\n void Resize();\n void GetFocus();\n\n public:\n OPropertyEditor (Window* pParent, WinBits nWinStyle = WB_DIALOGCONTROL);\n\n ~OPropertyEditor();\n\n void EnableUpdate();\n void DisableUpdate();\n\n void SetLineListener( IPropertyLineListener* );\n void SetControlObserver( IPropertyControlObserver* );\n\n void EnableHelpSection( bool _bEnable );\n bool HasHelpSection() const;\n void SetHelpText( const ::rtl::OUString& _rHelpText );\n void SetHelpLineLimites( sal_Int32 _nMinLines, sal_Int32 _nMaxLines );\n\n void SetHelpId( sal_uInt32 nHelpId );\n sal_uInt16 AppendPage( const String& r, const SmartId& _rHelpId );\n void SetPage( sal_uInt16 );\n void RemovePage(sal_uInt16 nID);\n sal_uInt16 GetCurPage();\n void ClearAll();\n\n void SetPropertyValue(const ::rtl::OUString& _rEntryName, const ::com::sun::star::uno::Any& _rValue );\n ::com::sun::star::uno::Any GetPropertyValue(const ::rtl::OUString& rEntryName ) const;\n sal_uInt16 GetPropertyPos(const ::rtl::OUString& rEntryName ) const;\n ::com::sun::star::uno::Reference< ::com::sun::star::inspection::XPropertyControl >\n GetPropertyControl( const ::rtl::OUString& rEntryName );\n void EnablePropertyLine( const ::rtl::OUString& _rEntryName, bool _bEnable );\n void EnablePropertyControls( const ::rtl::OUString& _rEntryName, sal_Int16 _nControls, bool _bEnable );\n\n void ShowPropertyPage( sal_uInt16 _nPageId, bool _bShow );\n\n sal_uInt16 InsertEntry( const OLineDescriptor&, sal_uInt16 _nPageId, sal_uInt16 nPos = EDITOR_LIST_APPEND );\n void RemoveEntry( const ::rtl::OUString& _rName );\n void ChangeEntry( const OLineDescriptor& );\n\n void setPageActivationHandler(const Link& _rHdl) { m_aPageActivationHandler = _rHdl; }\n Link getPageActivationHandler() const { return m_aPageActivationHandler; }\n\n \/\/ #95343# -------------------------------\n sal_Int32 getMinimumWidth();\n sal_Int32 getMinimumHeight();\n\n void CommitModified();\n\n protected:\n using Window::SetHelpText;\n using Window::Update;\n\n private:\n OBrowserPage* getPage( sal_uInt16& _rPageId );\n const OBrowserPage* getPage( sal_uInt16& _rPageId ) const;\n\n OBrowserPage* getPage( const ::rtl::OUString& _rPropertyName );\n const OBrowserPage* getPage( const ::rtl::OUString& _rPropertyName ) const;\n\n void Update(const ::std::mem_fun_t<void,OBrowserListBox>& _aUpdateFunction);\n\n typedef void (OPropertyEditor::*PageOperation)( OBrowserPage&, const void* );\n void forEachPage( PageOperation _pOperation, const void* _pArgument = NULL );\n\n void setPageLineListener( OBrowserPage& _rPage, const void* );\n void setPageControlObserver( OBrowserPage& _rPage, const void* );\n void enableHelpSection( OBrowserPage& _rPage, const void* );\n void setHelpSectionText( OBrowserPage& _rPage, const void* _pPointerToOUString );\n void setHelpLineLimits( OBrowserPage& _rPage, const void* );\n\n protected:\n DECL_LINK(OnPageDeactivate, TabControl*);\n DECL_LINK(OnPageActivate, TabControl*);\n };\n\n\/\/............................................................................\n} \/\/ namespace pcr\n\/\/............................................................................\n\n#endif \/\/ _EXTENSIONS_PROPCTRLR_PROPERTYEDITOR_HXX_\n\n\n<|endoftext|>"} {"text":"<commit_before>\/* -------------------------------------------------------------------------- *\n * OpenSim: toyLeg_example.cpp *\n * -------------------------------------------------------------------------- *\n * The OpenSim API is a toolkit for musculoskeletal modeling and simulation. *\n * See http:\/\/opensim.stanford.edu and the NOTICE file for more information. *\n * OpenSim is developed at Stanford University and supported by the US *\n * National Institutes of Health (U54 GM072970, R24 HD065690) and by DARPA *\n * through the Warrior Web program. *\n * *\n * Copyright (c) 2005-2012 Stanford University and the Authors *\n * Author(s): Matt S. DeMers *\n * *\n * Licensed under the Apache License, Version 2.0 (the \"License\"); you may *\n * not use this file except in compliance with the License. You may obtain a *\n * copy of the License at http:\/\/www.apache.org\/licenses\/LICENSE-2.0. *\n * *\n * Unless required by applicable law or agreed to in writing, software *\n * distributed under the License is distributed on an \"AS IS\" BASIS, *\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. *\n * See the License for the specific language governing permissions and *\n * limitations under the License. *\n * -------------------------------------------------------------------------- *\/\n\n\/* \n * Below is an example of an OpenSim application that provides its own \n * main() routine. This application acts as an example for utilizing the \n * ControllabeSpring actuator.\n *\/\n\n\/\/ Author: Matt DeMers\n\n\/\/==============================================================================\n\/\/==============================================================================\n#include \"PistonActuator.h\"\n#include \"ControllableSpring.h\"\n#include <OpenSim\/OpenSim.h>\n#include \"OpenSim\/Common\/STOFileAdapter.h\"\n\nusing namespace OpenSim;\nusing namespace SimTK;\n\n\/\/______________________________________________________________________________\n\/**\n * Run a simulation of block sliding with contact on by two muscles sliding with contact \n *\/\nint main()\n{\n\n try {\n \/\/ Create a new OpenSim model\n Model osimModel;\n osimModel.setName(\"osimModel\");\n osimModel.setAuthors(\"Matt DeMers\");\n\n double Pi = SimTK::Pi;\n \n \/\/ Get the ground body\n Ground& ground = osimModel.updGround();\n ground.attachGeometry(new Mesh(\"checkered_floor.vtp\"));\n\n \/\/ create linkage body\n double linkageMass = 0.001, linkageLength = 0.5, linkageDiameter = 0.06;\n \n Vec3 linkageDimensions(linkageDiameter, linkageLength, linkageDiameter);\n Vec3 linkageMassCenter(0,linkageLength\/2,0);\n Inertia linkageInertia = Inertia::cylinderAlongY(linkageDiameter\/2.0, linkageLength\/2.0);\n\n OpenSim::Body* linkage1 = new OpenSim::Body(\"linkage1\", linkageMass, linkageMassCenter, linkageMass*linkageInertia);\n linkage1->attachGeometry(new Sphere(0.1));\n\n \/\/ Graphical representation\n Cylinder cyl(linkageDiameter\/2, linkageLength);\n Frame* cyl1Frame = new PhysicalOffsetFrame(*linkage1, \n Transform(Vec3(0.0, linkageLength \/ 2.0, 0.0)));\n cyl1Frame->setName(\"Cyl1_frame\");\n cyl1Frame->attachGeometry(cyl.clone());\n osimModel.addFrame(cyl1Frame);\n\n \/\/ Create a second linkage body as a clone of the first\n OpenSim::Body* linkage2 = linkage1->clone();\n linkage2->setName(\"linkage2\");\n Frame* cyl2Frame = new PhysicalOffsetFrame(*linkage2,\n Transform(Vec3(0.0, linkageLength \/ 2.0, 0.0)));\n cyl2Frame->setName(\"Cyl2_frame\");\n osimModel.addFrame(cyl2Frame);\n\n \/\/ Create a block to be the pelvis\n double blockMass = 20.0, blockSideLength = 0.2;\n Vec3 blockMassCenter(0);\n Inertia blockInertia = blockMass*Inertia::brick(blockSideLength, blockSideLength, blockSideLength);\n OpenSim::Body *block = new OpenSim::Body(\"block\", blockMass, blockMassCenter, blockInertia);\n block->attachGeometry(new Brick(SimTK::Vec3(0.05, 0.05, 0.05)));\n\n \/\/ Create 1 degree-of-freedom pin joints between the bodies to create a kinematic chain from ground through the block\n Vec3 orientationInGround(0), locationInGround(0), locationInParent(0.0, linkageLength, 0.0), orientationInChild(0), locationInChild(0);\n\n PinJoint *ankle = new PinJoint(\"ankle\", ground, locationInGround, orientationInGround, *linkage1, \n locationInChild, orientationInChild);\n\n PinJoint *knee = new PinJoint(\"knee\", *linkage1, locationInParent, orientationInChild, *linkage2,\n locationInChild, orientationInChild);\n\n PinJoint *hip = new PinJoint(\"hip\", *linkage2, locationInParent, orientationInChild, *block,\n locationInChild, orientationInChild);\n \n double range[2] = {-SimTK::Pi*2, SimTK::Pi*2};\n CoordinateSet& ankleCoordinateSet = ankle->upd_CoordinateSet();\n ankleCoordinateSet[0].setName(\"q1\");\n ankleCoordinateSet[0].setRange(range);\n\n CoordinateSet& kneeCoordinateSet = knee->upd_CoordinateSet();\n kneeCoordinateSet[0].setName(\"q2\");\n kneeCoordinateSet[0].setRange(range);\n\n CoordinateSet& hipCoordinateSet = hip->upd_CoordinateSet();\n hipCoordinateSet[0].setName(\"q3\");\n hipCoordinateSet[0].setRange(range);\n\n \/\/ Add the bodies to the model\n osimModel.addBody(linkage1);\n osimModel.addBody(linkage2);\n osimModel.addBody(block);\n\n \/\/ Add the joints to the model\n osimModel.addJoint(ankle);\n osimModel.addJoint(knee);\n osimModel.addJoint(hip);\n \/\/ Define constraints on the model\n \/\/ Add a point on line constraint to limit the block to vertical motion\n\n Vec3 lineDirection(0,1,0), pointOnLine(0,0,0), pointOnBlock(0);\n PointOnLineConstraint *lineConstraint = new PointOnLineConstraint(ground, lineDirection, pointOnLine, *block, pointOnBlock);\n osimModel.addConstraint(lineConstraint);\n\n \/\/ Add PistonActuator between the first linkage and the block\n Vec3 pointOnBodies(0);\n PistonActuator *piston = new PistonActuator();\n piston->setName(\"piston\");\n piston->setBodyA(linkage1);\n piston->setBodyB(block);\n piston->setPointA(pointOnBodies);\n piston->setPointB(pointOnBodies);\n piston->setOptimalForce(200.0);\n piston->setPointsAreGlobal(false);\n\n osimModel.addForce(piston);\n \/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n \/\/ Added ControllableSpring between the first linkage and the second block\n \/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n ControllableSpring *spring = new ControllableSpring;\n spring->setName(\"spring\");\n spring->setBodyA(block);\n spring->setBodyB(linkage1);\n spring->setPointA(pointOnBodies);\n spring->setPointB(pointOnBodies);\n spring->setOptimalForce(2000.0);\n spring->setPointsAreGlobal(false);\n spring->setRestLength(0.8);\n\n osimModel.addForce(spring);\n\n \/\/ define the simulation times\n double t0(0.0), tf(15);\n\n \/\/ create a controller to control the piston and spring actuators\n \/\/ the prescribed controller sets the controls as functions of time\n PrescribedController *legController = new PrescribedController();\n \/\/ give the legController control over all (two) model actuators\n legController->setActuators(osimModel.updActuators());\n\n \/\/ specify some control nodes for spring stiffness control\n double t[] = {0.0, 4.0, 7.0, 10.0, 15.0};\n double x[] = {1.0, 1.0, 0.25, 0.25, 5.0};\n\n \/\/ specify the control function for each actuator\n legController->prescribeControlForActuator(\"piston\", new Constant(0.1));\n legController->prescribeControlForActuator(\"spring\", new PiecewiseLinearFunction(5, t, x));\n\n \/\/ add the controller to the model\n osimModel.addController(legController); \n \n \/\/ define the acceleration due to gravity\n osimModel.setGravity(Vec3(0, -9.80665, 0));\n\n \/\/ enable the model visualizer see the model in action, which can be\n \/\/ useful for debugging\n osimModel.setUseVisualizer(false);\n\n \/\/ Initialize system\n SimTK::State& si = osimModel.initSystem();\n \n \/\/ Pin joint initial states\n double q1_i = -Pi\/4;\n double q2_i = - 2*q1_i;\n CoordinateSet &coordinates = osimModel.updCoordinateSet();\n coordinates[0].setValue(si, q1_i, true);\n coordinates[1].setValue(si,q2_i, true);\n\n \/\/ Setup integrator and manager\n SimTK::RungeKuttaMersonIntegrator integrator(osimModel.getMultibodySystem());\n integrator.setAccuracy(1.0e-3);\n\n ForceReporter *forces = new ForceReporter(&osimModel); \n osimModel.updAnalysisSet().adoptAndAppend(forces);\n Manager manager(osimModel, integrator);\n \n \/\/Examine the model\n osimModel.printDetailedInfo(si, std::cout);\n \/\/ Save the model\n osimModel.print(\"toyLeg.osim\");\n \/\/ Print out the initial position and velocity states\n si.getQ().dump(\"Initial q's\");\n si.getU().dump(\"Initial u's\");\n std::cout << \"Initial time: \" << si.getTime() << std::endl;\n\n \/\/ Integrate\n manager.setInitialTime(t0);\n manager.setFinalTime(tf);\n std::cout<<\"\\n\\nIntegrating from \" << t0 << \" to \" << tf << std::endl;\n manager.integrate(si);\n\n \/\/ Save results\n auto controlsTable = osimModel.getControlsTable();\n STOFileAdapter::write(controlsTable, \"SpringActuatedLeg_controls.sto\");\n\n auto statesTable = manager.getStatesTable();\n osimModel.updSimbodyEngine().convertRadiansToDegrees(statesTable);\n STOFileAdapter::write(statesTable, \n \"SpringActuatedLeg_states_degrees.sto\");\n\n auto forcesTable = forces->getForcesTable();\n STOFileAdapter::write(forcesTable, \"actuator_forces.sto\");\n }\n catch (const std::exception& ex)\n {\n std::cout << \"Exception in toyLeg_example: \" << ex.what() << std::endl;\n return 1;\n }\n\n std::cout << \"Done.\" << std::endl;\n return 0;\n}\n<commit_msg>Remove unused linkageDimensions from toyLeg_example.cpp<commit_after>\/* -------------------------------------------------------------------------- *\n * OpenSim: toyLeg_example.cpp *\n * -------------------------------------------------------------------------- *\n * The OpenSim API is a toolkit for musculoskeletal modeling and simulation. *\n * See http:\/\/opensim.stanford.edu and the NOTICE file for more information. *\n * OpenSim is developed at Stanford University and supported by the US *\n * National Institutes of Health (U54 GM072970, R24 HD065690) and by DARPA *\n * through the Warrior Web program. *\n * *\n * Copyright (c) 2005-2012 Stanford University and the Authors *\n * Author(s): Matt S. DeMers *\n * *\n * Licensed under the Apache License, Version 2.0 (the \"License\"); you may *\n * not use this file except in compliance with the License. You may obtain a *\n * copy of the License at http:\/\/www.apache.org\/licenses\/LICENSE-2.0. *\n * *\n * Unless required by applicable law or agreed to in writing, software *\n * distributed under the License is distributed on an \"AS IS\" BASIS, *\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. *\n * See the License for the specific language governing permissions and *\n * limitations under the License. *\n * -------------------------------------------------------------------------- *\/\n\n\/* \n * Below is an example of an OpenSim application that provides its own \n * main() routine. This application acts as an example for utilizing the \n * ControllabeSpring actuator.\n *\/\n\n\/\/ Author: Matt DeMers\n\n\/\/==============================================================================\n\/\/==============================================================================\n#include \"PistonActuator.h\"\n#include \"ControllableSpring.h\"\n#include <OpenSim\/OpenSim.h>\n#include \"OpenSim\/Common\/STOFileAdapter.h\"\n\nusing namespace OpenSim;\nusing namespace SimTK;\n\n\/\/______________________________________________________________________________\n\/**\n * Run a simulation of block sliding with contact on by two muscles sliding with contact \n *\/\nint main()\n{\n try {\n \/\/ Create a new OpenSim model\n Model osimModel;\n osimModel.setName(\"osimModel\");\n osimModel.setAuthors(\"Matt DeMers\");\n\n double Pi = SimTK::Pi;\n \n \/\/ Get the ground body\n Ground& ground = osimModel.updGround();\n ground.attachGeometry(new Mesh(\"checkered_floor.vtp\"));\n\n \/\/ create linkage body\n double linkageMass = 0.001, linkageLength = 0.5, linkageDiameter = 0.06;\n \n Vec3 linkageMassCenter(0,linkageLength\/2,0);\n Inertia linkageInertia = Inertia::cylinderAlongY(linkageDiameter\/2.0, linkageLength\/2.0);\n\n OpenSim::Body* linkage1 = new OpenSim::Body(\"linkage1\", linkageMass, linkageMassCenter, linkageMass*linkageInertia);\n linkage1->attachGeometry(new Sphere(0.1));\n\n \/\/ Graphical representation\n Cylinder cyl(linkageDiameter\/2, linkageLength);\n Frame* cyl1Frame = new PhysicalOffsetFrame(*linkage1, \n Transform(Vec3(0.0, linkageLength \/ 2.0, 0.0)));\n cyl1Frame->setName(\"Cyl1_frame\");\n cyl1Frame->attachGeometry(cyl.clone());\n osimModel.addFrame(cyl1Frame);\n\n \/\/ Create a second linkage body as a clone of the first\n OpenSim::Body* linkage2 = linkage1->clone();\n linkage2->setName(\"linkage2\");\n Frame* cyl2Frame = new PhysicalOffsetFrame(*linkage2,\n Transform(Vec3(0.0, linkageLength \/ 2.0, 0.0)));\n cyl2Frame->setName(\"Cyl2_frame\");\n osimModel.addFrame(cyl2Frame);\n\n \/\/ Create a block to be the pelvis\n double blockMass = 20.0, blockSideLength = 0.2;\n Vec3 blockMassCenter(0);\n Inertia blockInertia = blockMass*Inertia::brick(blockSideLength, blockSideLength, blockSideLength);\n OpenSim::Body *block = new OpenSim::Body(\"block\", blockMass, blockMassCenter, blockInertia);\n block->attachGeometry(new Brick(SimTK::Vec3(0.05, 0.05, 0.05)));\n\n \/\/ Create 1 degree-of-freedom pin joints between the bodies to create a kinematic chain from ground through the block\n Vec3 orientationInGround(0), locationInGround(0), locationInParent(0.0, linkageLength, 0.0), orientationInChild(0), locationInChild(0);\n\n PinJoint *ankle = new PinJoint(\"ankle\", ground, locationInGround, orientationInGround, *linkage1, \n locationInChild, orientationInChild);\n\n PinJoint *knee = new PinJoint(\"knee\", *linkage1, locationInParent, orientationInChild, *linkage2,\n locationInChild, orientationInChild);\n\n PinJoint *hip = new PinJoint(\"hip\", *linkage2, locationInParent, orientationInChild, *block,\n locationInChild, orientationInChild);\n \n double range[2] = {-SimTK::Pi*2, SimTK::Pi*2};\n CoordinateSet& ankleCoordinateSet = ankle->upd_CoordinateSet();\n ankleCoordinateSet[0].setName(\"q1\");\n ankleCoordinateSet[0].setRange(range);\n\n CoordinateSet& kneeCoordinateSet = knee->upd_CoordinateSet();\n kneeCoordinateSet[0].setName(\"q2\");\n kneeCoordinateSet[0].setRange(range);\n\n CoordinateSet& hipCoordinateSet = hip->upd_CoordinateSet();\n hipCoordinateSet[0].setName(\"q3\");\n hipCoordinateSet[0].setRange(range);\n\n \/\/ Add the bodies to the model\n osimModel.addBody(linkage1);\n osimModel.addBody(linkage2);\n osimModel.addBody(block);\n\n \/\/ Add the joints to the model\n osimModel.addJoint(ankle);\n osimModel.addJoint(knee);\n osimModel.addJoint(hip);\n \/\/ Define constraints on the model\n \/\/ Add a point on line constraint to limit the block to vertical motion\n\n Vec3 lineDirection(0,1,0), pointOnLine(0,0,0), pointOnBlock(0);\n PointOnLineConstraint *lineConstraint = new PointOnLineConstraint(ground, lineDirection, pointOnLine, *block, pointOnBlock);\n osimModel.addConstraint(lineConstraint);\n\n \/\/ Add PistonActuator between the first linkage and the block\n Vec3 pointOnBodies(0);\n PistonActuator *piston = new PistonActuator();\n piston->setName(\"piston\");\n piston->setBodyA(linkage1);\n piston->setBodyB(block);\n piston->setPointA(pointOnBodies);\n piston->setPointB(pointOnBodies);\n piston->setOptimalForce(200.0);\n piston->setPointsAreGlobal(false);\n\n osimModel.addForce(piston);\n \/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n \/\/ Added ControllableSpring between the first linkage and the second block\n \/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n ControllableSpring *spring = new ControllableSpring;\n spring->setName(\"spring\");\n spring->setBodyA(block);\n spring->setBodyB(linkage1);\n spring->setPointA(pointOnBodies);\n spring->setPointB(pointOnBodies);\n spring->setOptimalForce(2000.0);\n spring->setPointsAreGlobal(false);\n spring->setRestLength(0.8);\n\n osimModel.addForce(spring);\n\n \/\/ define the simulation times\n double t0(0.0), tf(15);\n\n \/\/ create a controller to control the piston and spring actuators\n \/\/ the prescribed controller sets the controls as functions of time\n PrescribedController *legController = new PrescribedController();\n \/\/ give the legController control over all (two) model actuators\n legController->setActuators(osimModel.updActuators());\n\n \/\/ specify some control nodes for spring stiffness control\n double t[] = {0.0, 4.0, 7.0, 10.0, 15.0};\n double x[] = {1.0, 1.0, 0.25, 0.25, 5.0};\n\n \/\/ specify the control function for each actuator\n legController->prescribeControlForActuator(\"piston\", new Constant(0.1));\n legController->prescribeControlForActuator(\"spring\", new PiecewiseLinearFunction(5, t, x));\n\n \/\/ add the controller to the model\n osimModel.addController(legController); \n \n \/\/ define the acceleration due to gravity\n osimModel.setGravity(Vec3(0, -9.80665, 0));\n\n \/\/ enable the model visualizer see the model in action, which can be\n \/\/ useful for debugging\n osimModel.setUseVisualizer(false);\n\n \/\/ Initialize system\n SimTK::State& si = osimModel.initSystem();\n \n \/\/ Pin joint initial states\n double q1_i = -Pi\/4;\n double q2_i = - 2*q1_i;\n CoordinateSet &coordinates = osimModel.updCoordinateSet();\n coordinates[0].setValue(si, q1_i, true);\n coordinates[1].setValue(si,q2_i, true);\n\n \/\/ Setup integrator and manager\n SimTK::RungeKuttaMersonIntegrator integrator(osimModel.getMultibodySystem());\n integrator.setAccuracy(1.0e-3);\n\n ForceReporter *forces = new ForceReporter(&osimModel); \n osimModel.updAnalysisSet().adoptAndAppend(forces);\n Manager manager(osimModel, integrator);\n \n \/\/Examine the model\n osimModel.printDetailedInfo(si, std::cout);\n \/\/ Save the model\n osimModel.print(\"toyLeg.osim\");\n \/\/ Print out the initial position and velocity states\n si.getQ().dump(\"Initial q's\");\n si.getU().dump(\"Initial u's\");\n std::cout << \"Initial time: \" << si.getTime() << std::endl;\n\n \/\/ Integrate\n manager.setInitialTime(t0);\n manager.setFinalTime(tf);\n std::cout<<\"\\n\\nIntegrating from \" << t0 << \" to \" << tf << std::endl;\n manager.integrate(si);\n\n \/\/ Save results\n auto controlsTable = osimModel.getControlsTable();\n STOFileAdapter::write(controlsTable, \"SpringActuatedLeg_controls.sto\");\n\n auto statesTable = manager.getStatesTable();\n osimModel.updSimbodyEngine().convertRadiansToDegrees(statesTable);\n STOFileAdapter::write(statesTable, \n \"SpringActuatedLeg_states_degrees.sto\");\n\n auto forcesTable = forces->getForcesTable();\n STOFileAdapter::write(forcesTable, \"actuator_forces.sto\");\n }\n catch (const std::exception& ex)\n {\n std::cout << \"Exception in toyLeg_example: \" << ex.what() << std::endl;\n return 1;\n }\n\n std::cout << \"Done.\" << std::endl;\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"multiplayer_proxy.h\"\n#include \"multiplayer_internal.h\"\n\nGameServerProxy::GameServerProxy(sf::IpAddress hostname, int hostPort, string password, int listenPort)\n: password(password)\n{\n mainSocket.connect(hostname, hostPort);\n mainSocket.setBlocking(false);\n listenSocket.listen(listenPort);\n listenSocket.setBlocking(false);\n\n newSocket = std::unique_ptr<TcpSocket>(new TcpSocket());\n newSocket->setBlocking(false);\n\n lastReceiveTime.restart();\n}\n\nGameServerProxy::~GameServerProxy()\n{\n}\n\nvoid GameServerProxy::destroy()\n{\n clientList.clear();\n}\n\nvoid GameServerProxy::update(float delta)\n{\n mainSocket.update();\n sf::Packet packet;\n sf::TcpSocket::Status socketStatus;\n while((socketStatus = mainSocket.receive(packet)) == sf::TcpSocket::Done)\n {\n lastReceiveTime.restart();\n command_t command;\n packet >> command;\n switch(command)\n {\n case CMD_REQUEST_AUTH:\n {\n bool requirePassword;\n packet >> serverVersion >> requirePassword;\n\n sf::Packet reply;\n reply << CMD_CLIENT_SEND_AUTH << int32_t(serverVersion) << string(password);\n mainSocket.send(reply);\n }\n break;\n case CMD_SET_CLIENT_ID:\n packet >> clientId;\n break;\n case CMD_ALIVE:\n {\n sf::Packet reply;\n reply << CMD_ALIVE_RESP;\n mainSocket.send(reply);\n }\n sendAll(packet);\n break;\n case CMD_CREATE:\n case CMD_DELETE:\n case CMD_UPDATE_VALUE:\n case CMD_SET_GAME_SPEED:\n case CMD_SERVER_COMMAND:\n sendAll(packet);\n break;\n case CMD_SET_PROXY_CLIENT_ID:\n {\n int32_t tempId, clientId;\n packet >> tempId >> clientId;\n for(auto& info : clientList)\n {\n if (!info.validClient && info.clientId == tempId)\n {\n info.validClient = true;\n info.clientId = clientId;\n info.receiveState = CRS_Main;\n {\n sf::Packet packet;\n packet << CMD_SET_CLIENT_ID << info.clientId;\n info.socket->send(packet);\n }\n }\n }\n }\n break;\n }\n }\n\n if (socketStatus == sf::TcpSocket::Disconnected || lastReceiveTime.getElapsedTime().asSeconds() > noDataDisconnectTime)\n {\n mainSocket.disconnect();\n }\n\n if (listenSocket.accept(*newSocket))\n {\n ClientInfo info;\n info.socket = std::move(newSocket);\n newSocket = std::unique_ptr<TcpSocket>(new TcpSocket());\n newSocket->setBlocking(false);\n {\n sf::Packet packet;\n packet << CMD_REQUEST_AUTH << int32_t(serverVersion) << bool(password != \"\");\n info.socket->send(packet);\n }\n clientList.emplace_back(std::move(info));\n }\n\n for(unsigned int n=0; n<clientList.size(); n++)\n {\n auto& info = clientList[n];\n info.socket->update();\n while(info.socket && (socketStatus = info.socket->receive(packet)) == sf::TcpSocket::Done)\n {\n command_t command;\n packet >> command;\n switch(info.receiveState)\n {\n case CRS_Auth:\n switch(command)\n {\n case CMD_CLIENT_SEND_AUTH:\n {\n int32_t clientVersion;\n string clientPassword;\n packet >> clientVersion >> clientPassword;\n if (clientVersion == serverVersion && clientPassword == password)\n {\n sf::Packet serverUpdate;\n serverUpdate << CMD_NEW_PROXY_CLIENT << info.clientId;\n mainSocket.send(serverUpdate);\n }\n else\n {\n info.socket->disconnect();\n info.socket = NULL;\n }\n }\n break;\n case CMD_ALIVE_RESP:\n break;\n default:\n LOG(ERROR) << \"Unknown command from client: \" << command;\n break;\n }\n break;\n case CRS_Main:\n switch(command)\n {\n case CMD_CLIENT_COMMAND:\n packet >> info.commandObjectId;\n info.receiveState = CRS_Command;\n break;\n case CMD_ALIVE_RESP:\n break;\n default:\n LOG(ERROR) << \"Unknown command from client: \" << command;\n break;\n }\n break;\n case CRS_Command:\n {\n sf::Packet mainPacket;\n mainPacket << CMD_PROXY_CLIENT_COMMAND << info.commandObjectId << info.clientId;\n mainSocket.send(mainPacket);\n mainSocket.send(packet);\n }\n info.receiveState = CRS_Main;\n break;\n }\n }\n if (socketStatus == sf::TcpSocket::Disconnected || info.socket == NULL)\n {\n if (info.validClient)\n {\n sf::Packet serverUpdate;\n serverUpdate << CMD_DEL_PROXY_CLIENT << info.clientId;\n mainSocket.send(serverUpdate);\n }\n clientList.erase(clientList.begin() + n);\n n--;\n }\n }\n}\n\nvoid GameServerProxy::sendAll(sf::Packet& packet)\n{\n for(auto& info : clientList)\n {\n if (info.validClient && info.socket)\n info.socket->send(packet);\n }\n}\n<commit_msg>Add some basic logging to the proxy, and shutdown if the proxy gets disconnected.<commit_after>#include \"multiplayer_proxy.h\"\n#include \"multiplayer_internal.h\"\n#include \"engine.h\"\n\n\nGameServerProxy::GameServerProxy(sf::IpAddress hostname, int hostPort, string password, int listenPort)\n: password(password)\n{\n LOG(INFO) << \"Starting proxy server\";\n if (mainSocket.connect(hostname, hostPort) != sf::Socket::Status::Done)\n LOG(INFO) << \"Failed to connect to server\";\n else\n LOG(INFO) << \"Connected to server\";\n mainSocket.setBlocking(false);\n listenSocket.listen(listenPort);\n listenSocket.setBlocking(false);\n\n newSocket = std::unique_ptr<TcpSocket>(new TcpSocket());\n newSocket->setBlocking(false);\n\n lastReceiveTime.restart();\n}\n\nGameServerProxy::~GameServerProxy()\n{\n}\n\nvoid GameServerProxy::destroy()\n{\n clientList.clear();\n}\n\nvoid GameServerProxy::update(float delta)\n{\n mainSocket.update();\n sf::Packet packet;\n sf::TcpSocket::Status socketStatus;\n while((socketStatus = mainSocket.receive(packet)) == sf::TcpSocket::Done)\n {\n lastReceiveTime.restart();\n command_t command;\n packet >> command;\n switch(command)\n {\n case CMD_REQUEST_AUTH:\n {\n bool requirePassword;\n packet >> serverVersion >> requirePassword;\n\n sf::Packet reply;\n reply << CMD_CLIENT_SEND_AUTH << int32_t(serverVersion) << string(password);\n mainSocket.send(reply);\n }\n break;\n case CMD_SET_CLIENT_ID:\n packet >> clientId;\n break;\n case CMD_ALIVE:\n {\n sf::Packet reply;\n reply << CMD_ALIVE_RESP;\n mainSocket.send(reply);\n }\n sendAll(packet);\n break;\n case CMD_CREATE:\n case CMD_DELETE:\n case CMD_UPDATE_VALUE:\n case CMD_SET_GAME_SPEED:\n case CMD_SERVER_COMMAND:\n sendAll(packet);\n break;\n case CMD_SET_PROXY_CLIENT_ID:\n {\n int32_t tempId, clientId;\n packet >> tempId >> clientId;\n for(auto& info : clientList)\n {\n if (!info.validClient && info.clientId == tempId)\n {\n info.validClient = true;\n info.clientId = clientId;\n info.receiveState = CRS_Main;\n {\n sf::Packet packet;\n packet << CMD_SET_CLIENT_ID << info.clientId;\n info.socket->send(packet);\n }\n }\n }\n }\n break;\n }\n }\n\n if (socketStatus == sf::TcpSocket::Disconnected || lastReceiveTime.getElapsedTime().asSeconds() > noDataDisconnectTime)\n {\n LOG(INFO) << \"Disconnected proxy\";\n mainSocket.disconnect();\n engine->shutdown();\n }\n\n if (listenSocket.accept(*newSocket))\n {\n ClientInfo info;\n info.socket = std::move(newSocket);\n newSocket = std::unique_ptr<TcpSocket>(new TcpSocket());\n newSocket->setBlocking(false);\n {\n sf::Packet packet;\n packet << CMD_REQUEST_AUTH << int32_t(serverVersion) << bool(password != \"\");\n info.socket->send(packet);\n }\n clientList.emplace_back(std::move(info));\n }\n\n for(unsigned int n=0; n<clientList.size(); n++)\n {\n auto& info = clientList[n];\n info.socket->update();\n while(info.socket && (socketStatus = info.socket->receive(packet)) == sf::TcpSocket::Done)\n {\n command_t command;\n packet >> command;\n switch(info.receiveState)\n {\n case CRS_Auth:\n switch(command)\n {\n case CMD_CLIENT_SEND_AUTH:\n {\n int32_t clientVersion;\n string clientPassword;\n packet >> clientVersion >> clientPassword;\n if (clientVersion == serverVersion && clientPassword == password)\n {\n sf::Packet serverUpdate;\n serverUpdate << CMD_NEW_PROXY_CLIENT << info.clientId;\n mainSocket.send(serverUpdate);\n }\n else\n {\n info.socket->disconnect();\n info.socket = NULL;\n }\n }\n break;\n case CMD_ALIVE_RESP:\n break;\n default:\n LOG(ERROR) << \"Unknown command from client: \" << command;\n break;\n }\n break;\n case CRS_Main:\n switch(command)\n {\n case CMD_CLIENT_COMMAND:\n packet >> info.commandObjectId;\n info.receiveState = CRS_Command;\n break;\n case CMD_ALIVE_RESP:\n break;\n default:\n LOG(ERROR) << \"Unknown command from client: \" << command;\n break;\n }\n break;\n case CRS_Command:\n {\n sf::Packet mainPacket;\n mainPacket << CMD_PROXY_CLIENT_COMMAND << info.commandObjectId << info.clientId;\n mainSocket.send(mainPacket);\n mainSocket.send(packet);\n }\n info.receiveState = CRS_Main;\n break;\n }\n }\n if (socketStatus == sf::TcpSocket::Disconnected || info.socket == NULL)\n {\n if (info.validClient)\n {\n sf::Packet serverUpdate;\n serverUpdate << CMD_DEL_PROXY_CLIENT << info.clientId;\n mainSocket.send(serverUpdate);\n }\n clientList.erase(clientList.begin() + n);\n n--;\n }\n }\n}\n\nvoid GameServerProxy::sendAll(sf::Packet& packet)\n{\n for(auto& info : clientList)\n {\n if (info.validClient && info.socket)\n info.socket->send(packet);\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/***********************************************************************\nMoses - factored phrase-based language decoder\nCopyright (C) 2009 University of Edinburgh\n\nThis library is free software; you can redistribute it and\/or\nmodify it under the terms of the GNU Lesser General Public\nLicense as published by the Free Software Foundation; either\nversion 2.1 of the License, or (at your option) any later version.\n\nThis library is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\nLesser General Public License for more details.\n\nYou should have received a copy of the GNU Lesser General Public\nLicense along with this library; if not, write to the Free Software\nFoundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n***********************************************************************\/\n\n#include \"Decoder.h\"\n#include \"Manager.h\"\n#include \"ChartManager.h\"\n#include \"Sentence.h\"\n#include \"InputType.h\"\n#include \"TranslationSystem.h\"\n#include \"Phrase.h\"\n#include \"TrellisPathList.h\"\n#include \"ChartTrellisPathList.h\"\n#include \"ChartTrellisPath.h\"\n#include \"IOWrapper.h\"\n\nusing namespace std;\nusing namespace Moses;\n\n\nnamespace Mira {\n\n \/**\n * Allocates a char* and copies string into it.\n **\/\n static char* strToChar(const string& s) {\n char* c = new char[s.size()+1];\n strcpy(c,s.c_str());\n return c;\n }\n\n MosesDecoder::MosesDecoder(const string& inifile, int debuglevel, int argc, vector<string> decoder_params)\n\t\t: m_manager(NULL) {\n \tstatic int BASE_ARGC = 4;\n\t Parameter* params = new Parameter();\n\t char ** mosesargv = new char*[BASE_ARGC + argc];\n\t mosesargv[0] = strToChar(\"-f\");\n\t mosesargv[1] = strToChar(inifile);\n\t mosesargv[2] = strToChar(\"-v\");\n\t stringstream dbgin;\n\t dbgin << debuglevel;\n\t mosesargv[3] = strToChar(dbgin.str());\n\n\t for (int i = 0; i < argc; ++i) {\n\t\t char *cstr = &(decoder_params[i])[0];\n\t\t mosesargv[BASE_ARGC + i] = cstr;\n\t }\n\n\t if (!params->LoadParam(BASE_ARGC + argc,mosesargv)) {\n\t\t cerr << \"Loading static data failed, exit.\" << endl;\n\t\t exit(1);\n\t }\n\t StaticData::LoadDataStatic(params);\n\t for (int i = 0; i < BASE_ARGC; ++i) {\n\t\t delete[] mosesargv[i];\n\t }\n\t delete[] mosesargv;\n\n\t const StaticData &staticData = StaticData::Instance();\n m_bleuScoreFeature = staticData.GetBleuScoreFeature();\n }\n \n void MosesDecoder::cleanup(bool chartDecoding) {\n\t delete m_manager;\n\t if (chartDecoding)\n\t \tdelete m_chartManager;\n\t else\n\t \tdelete m_sentence;\n }\n\n vector< vector<const Word*> > MosesDecoder::getNBest(const std::string& source,\n size_t sentenceid,\n size_t nBestSize,\n float bleuObjectiveWeight, \n float bleuScoreWeight,\n vector< ScoreComponentCollection>& featureValues,\n vector< float>& bleuScores,\n vector< float>& modelScores,\n size_t numReturnedTranslations,\n bool distinct,\n bool avgRefLength,\n size_t rank,\n size_t epoch)\n {\n \tStaticData &staticData = StaticData::InstanceNonConst();\n \tinitialize(staticData, source, sentenceid, bleuObjectiveWeight, bleuScoreWeight, avgRefLength);\n const TranslationSystem& system = staticData.GetTranslationSystem(TranslationSystem::DEFAULT);\n\n \/\/ run the decoder\n if (staticData.GetSearchAlgorithm() == ChartDecoding) {\n \treturn runChartDecoder(source, sentenceid, nBestSize, bleuObjectiveWeight, bleuScoreWeight,\n \t\t\tfeatureValues, bleuScores, modelScores, numReturnedTranslations, distinct, rank, epoch,\n \t\t\tsystem);\n }\n else {\n \tSearchAlgorithm search = staticData.GetSearchAlgorithm();\n \treturn runDecoder(source, sentenceid, nBestSize, bleuObjectiveWeight, bleuScoreWeight,\n \t\t\tfeatureValues, bleuScores, modelScores, numReturnedTranslations, distinct, rank, epoch,\n \t\t\tsearch, system);\n }\n }\n\n vector< vector<const Word*> > MosesDecoder::runDecoder(const std::string& source,\n \t\t\t\t\t\t\t\t\t\t\t\t\t\tsize_t sentenceid,\n \t\t\t\t\t\t\t\t\t\t\t\t\t\tsize_t nBestSize,\n \t\t\t\t\t\t\t\t\t\t\t\t\t\tfloat bleuObjectiveWeight,\n \t\t\t\t\t\t\t\t\t\t\t\t\t\tfloat bleuScoreWeight,\n \t\t\t\t\t\t\t\t\t\t\t\t\t\tvector< ScoreComponentCollection>& featureValues,\n \t\t\t\t\t\t\t\t\t\t\t\t\t\tvector< float>& bleuScores,\n \t\t\t\t\t\t\t\t\t\t\t\t\t\tvector< float>& modelScores,\n \t\t\t\t\t\t\t\t\t\t\t\t\t\tsize_t numReturnedTranslations,\n \t\t\t\t\t\t\t\t\t\t\t\t\t\tbool distinct,\n \t\t\t\t\t\t\t\t\t\t\t\t\t\tsize_t rank,\n \t\t\t\t\t\t\t\t\t\t\t\t\t\tsize_t epoch,\n \t\t\t\t\t\t\t\t\t\t\t\t\t\tSearchAlgorithm& search,\n \t\t\t\t\t\t\t\t\t\t\t\t\t\tconst TranslationSystem& system) {\n \t\/\/ run the decoder\n m_manager = new Moses::Manager(*m_sentence, search, &system);\n m_manager->ProcessSentence();\n TrellisPathList nBestList;\n m_manager->CalcNBest(nBestSize, nBestList, distinct);\n\n \/\/ read off the feature values and bleu scores for each sentence in the nbest list\n Moses::TrellisPathList::const_iterator iter;\n for (iter = nBestList.begin() ; iter != nBestList.end() ; ++iter) {\n \tconst Moses::TrellisPath &path = **iter;\n \tfeatureValues.push_back(path.GetScoreBreakdown());\n \tfloat bleuScore = getBleuScore(featureValues.back());\n \tbleuScores.push_back(bleuScore);\n\n \t\/\/std::cout << \"Score breakdown: \" << path.GetScoreBreakdown() << endl;\n \tfloat scoreWithoutBleu = path.GetTotalScore() - (bleuObjectiveWeight * bleuScoreWeight * bleuScore);\n \tmodelScores.push_back(scoreWithoutBleu);\n\n \tPhrase bestPhrase = path.GetTargetPhrase();\n\n \tif (iter != nBestList.begin())\n \t\tcerr << endl;\n \t\tcerr << \"Rank \" << rank << \", epoch \" << epoch << \", \\\"\";\n \t\tPhrase phrase = path.GetTargetPhrase();\n \t\tfor (size_t pos = 0; pos < phrase.GetSize(); ++pos) {\n \t\tconst Word &word = phrase.GetWord(pos);\n \t\tWord *newWord = new Word(word);\n \t\tcerr << *newWord;\n \t}\n\n \tcerr << \"\\\", score: \" << scoreWithoutBleu << \", Bleu: \" << bleuScore << \", total: \" << path.GetTotalScore();\n\n \t\/\/ set bleu score to zero in the feature vector since we do not want to optimise its weight\n \tsetBleuScore(featureValues.back(), 0);\n }\n\n \/\/ prepare translations to return\n vector< vector<const Word*> > translations;\n for (size_t i=0; i < numReturnedTranslations && i < nBestList.GetSize(); ++i) {\n const TrellisPath &path = nBestList.at(i);\n Phrase phrase = path.GetTargetPhrase();\n\n vector<const Word*> translation;\n for (size_t pos = 0; pos < phrase.GetSize(); ++pos) {\n \tconst Word &word = phrase.GetWord(pos);\n \tWord *newWord = new Word(word);\n \ttranslation.push_back(newWord);\n }\n translations.push_back(translation);\n }\n\n\/\/ cerr << \"Rank \" << rank << \", use cache: \" << staticData.GetUseTransOptCache() << \", weights: \" << staticData.GetAllWeights() << endl;\n return translations;\n }\n\n vector< vector<const Word*> > MosesDecoder::runChartDecoder(const std::string& source,\n size_t sentenceid,\n size_t nBestSize,\n float bleuObjectiveWeight,\n float bleuScoreWeight,\n vector< ScoreComponentCollection>& featureValues,\n vector< float>& bleuScores,\n vector< float>& modelScores,\n size_t numReturnedTranslations,\n bool distinct,\n size_t rank,\n size_t epoch,\n const TranslationSystem& system) {\n \t\/\/ run the decoder\n m_chartManager = new ChartManager(*m_sentence, &system);\n m_chartManager->ProcessSentence();\n ChartTrellisPathList nBestList;\n m_chartManager->CalcNBest(nBestSize, nBestList, distinct);\n\n \/\/ read off the feature values and bleu scores for each sentence in the nbest list\n ChartTrellisPathList::const_iterator iter;\n for (iter = nBestList.begin() ; iter != nBestList.end() ; ++iter) {\n \tconst Moses::ChartTrellisPath &path = **iter;\n \tfeatureValues.push_back(path.GetScoreBreakdown());\n \tfloat bleuScore = getBleuScore(featureValues.back());\n \tbleuScores.push_back(bleuScore);\n\n \t\/\/std::cout << \"Score breakdown: \" << path.GetScoreBreakdown() << endl;\n \tfloat scoreWithoutBleu = path.GetTotalScore() - (bleuObjectiveWeight * bleuScoreWeight * bleuScore);\n \tmodelScores.push_back(scoreWithoutBleu);\n\n \tPhrase bestPhrase = path.GetOutputPhrase();\n\n \tif (iter != nBestList.begin())\n \t\tcerr << endl;\n \t\tcerr << \"Rank \" << rank << \", epoch \" << epoch << \", \\\"\";\n \t\tPhrase phrase = path.GetOutputPhrase();\n \t\tfor (size_t pos = 0; pos < phrase.GetSize(); ++pos) {\n \t\tconst Word &word = phrase.GetWord(pos);\n \t\tWord *newWord = new Word(word);\n \t\tcerr << *newWord;\n \t}\n\n \tcerr << \"\\\", score: \" << scoreWithoutBleu << \", Bleu: \" << bleuScore << \", total: \" << path.GetTotalScore();\n\n \t\/\/ set bleu score to zero in the feature vector since we do not want to optimise its weight\n \tsetBleuScore(featureValues.back(), 0);\n }\n\n \/\/ prepare translations to return\n vector< vector<const Word*> > translations;\n for (iter = nBestList.begin() ; iter != nBestList.end() ; ++iter) {\n const ChartTrellisPath &path = **iter;\n Phrase phrase = path.GetOutputPhrase();\n\n vector<const Word*> translation;\n for (size_t pos = 0; pos < phrase.GetSize(); ++pos) {\n \tconst Word &word = phrase.GetWord(pos);\n \tWord *newWord = new Word(word);\n \ttranslation.push_back(newWord);\n }\n translations.push_back(translation);\n }\n\n\/\/ cerr << \"Rank \" << rank << \", use cache: \" << staticData.GetUseTransOptCache() << \", weights: \" << staticData.GetAllWeights() << endl;\n return translations;\n }\n\n void MosesDecoder::outputNBestList(const std::string& source, size_t sentenceid,\n \t\t\t\t\t\t\t\t\t\t\t\t\t\tsize_t nBestSize, float bleuObjectiveWeight, float bleuScoreWeight,\n \t\t\t\t\t\t\t\t\t\t\t\t\t\tbool distinctNbest, bool avgRefLength, string filename, ofstream& streamOut) {\n \tStaticData &staticData = StaticData::InstanceNonConst();\n \tinitialize(staticData, source, sentenceid, bleuObjectiveWeight, bleuScoreWeight, avgRefLength);\n const TranslationSystem& system = staticData.GetTranslationSystem(TranslationSystem::DEFAULT);\n\n if (staticData.GetSearchAlgorithm() == ChartDecoding) {\n m_chartManager = new ChartManager(*m_sentence, &system);\n m_chartManager->ProcessSentence();\n ChartTrellisPathList nBestList;\n m_chartManager->CalcNBest(nBestSize, nBestList, distinctNbest);\n\n cerr << \"generate nbest list \" << filename << endl;\n cerr << \"not implemented..\" << endl;\n exit(1);\n \tif (filename != \"\") {\n \t\tofstream out(filename.c_str());\n \t\tif (!out) {\n \t\t\tostringstream msg;\n \t\t\tmsg << \"Unable to open \" << filename;\n \t\t\tthrow runtime_error(msg.str());\n \t\t}\n \t\t\/\/ TODO: handle sentence id (for now always 0)\n\/\/ \t\tOutputNBestList(const ChartTrellisPathList &nBestList, const ChartHypothesis *bestHypo, const TranslationSystem* system, long translationId)\n\/\/ \t\tOutputNBest(out, nBestList, StaticData::Instance().GetOutputFactorOrder(),m_manager->GetTranslationSystem(), 0);\n \t\tout.close();\n \t}\n \telse {\n\/\/ \t\tOutputNBest(streamOut, nBestList, StaticData::Instance().GetOutputFactorOrder(),m_manager->GetTranslationSystem(), sentenceid);\n \t}\n }\n else {\n \t\/\/ run the decoder\n m_manager = new Moses::Manager(*m_sentence, staticData.GetSearchAlgorithm(), &system);\n m_manager->ProcessSentence();\n TrellisPathList nBestList;\n m_manager->CalcNBest(nBestSize, nBestList, distinctNbest);\n\n if (filename != \"\") {\n \t\tofstream out(filename.c_str());\n \t\tif (!out) {\n \t\t\tostringstream msg;\n \t\t\tmsg << \"Unable to open \" << filename;\n \t\t\tthrow runtime_error(msg.str());\n \t\t}\n \t\t\/\/ TODO: handle sentence id (for now always 0)\n \t\tOutputNBest(out, nBestList, StaticData::Instance().GetOutputFactorOrder(),m_manager->GetTranslationSystem(), 0);\n \t\tout.close();\n }\n else {\n\tOutputNBest(streamOut, nBestList, StaticData::Instance().GetOutputFactorOrder(),m_manager->GetTranslationSystem(), sentenceid);\n\tstreamOut.flush();\n }\n }\n }\n\n void MosesDecoder::initialize(StaticData& staticData, const std::string& source, size_t sentenceid,\n \t\t\t\t\t\t\t\t\t\t\t\t\tfloat bleuObjectiveWeight, float bleuScoreWeight, bool avgRefLength) {\n \tm_sentence = new Sentence();\n stringstream in(source + \"\\n\");\n const std::vector<FactorType> &inputFactorOrder = staticData.GetInputFactorOrder();\n m_sentence->Read(in,inputFactorOrder);\n\n \/\/ set weight of BleuScoreFeature\n staticData.ReLoadBleuScoreFeatureParameter(bleuObjectiveWeight*bleuScoreWeight);\n\n m_bleuScoreFeature->SetCurrSourceLength((*m_sentence).GetSize());\n if (avgRefLength)\n \tm_bleuScoreFeature->SetCurrAvgRefLength(sentenceid);\n else\n \tm_bleuScoreFeature->SetCurrShortestRefLength(sentenceid);\n m_bleuScoreFeature->SetCurrReferenceNgrams(sentenceid);\n }\n\n float MosesDecoder::getBleuScore(const ScoreComponentCollection& scores) {\n return scores.GetScoreForProducer(m_bleuScoreFeature);\n }\n\n void MosesDecoder::setBleuScore(ScoreComponentCollection& scores, float bleu) {\n scores.Assign(m_bleuScoreFeature, bleu);\n }\n\n ScoreComponentCollection MosesDecoder::getWeights() {\n return StaticData::Instance().GetAllWeights();\n }\n\n void MosesDecoder::setWeights(const ScoreComponentCollection& weights) {\n StaticData::InstanceNonConst().SetAllWeights(weights);\n }\n\n void MosesDecoder::updateHistory(const vector<const Word*>& words) {\n m_bleuScoreFeature->UpdateHistory(words);\n }\n\n void MosesDecoder::updateHistory(const vector< vector< const Word*> >& words, vector<size_t>& sourceLengths, vector<size_t>& ref_ids, size_t rank, size_t epoch) {\n\t m_bleuScoreFeature->UpdateHistory(words, sourceLengths, ref_ids, rank, epoch);\n }\n\n void MosesDecoder::printBleuFeatureHistory(std::ostream& out) {\n \tm_bleuScoreFeature->PrintHistory(out);\n }\n\n size_t MosesDecoder::getClosestReferenceLength(size_t ref_id, int hypoLength) {\n \treturn m_bleuScoreFeature->GetClosestRefLength(ref_id, hypoLength);\n }\n\n size_t MosesDecoder::getShortestReferenceIndex(size_t ref_id) {\n \treturn m_bleuScoreFeature->GetShortestRefIndex(ref_id);\n }\n\n void MosesDecoder::setBleuParameters(bool sentenceBleu, bool scaleByInputLength, bool scaleByAvgInputLength,\n\t\t bool scaleByInverseLength, bool scaleByAvgInverseLength,\n\t\t float scaleByX, float historySmoothing, size_t scheme, float relax_BP,\n\t\t bool useSourceLengthHistory) {\n\t m_bleuScoreFeature->SetBleuParameters(sentenceBleu, scaleByInputLength, scaleByAvgInputLength,\n\t\t\t scaleByInverseLength, scaleByAvgInverseLength,\n\t\t\t scaleByX, historySmoothing, scheme, relax_BP,\n\t\t\t useSourceLengthHistory);\n }\n} \n\n<commit_msg>disable caching<commit_after>\/***********************************************************************\nMoses - factored phrase-based language decoder\nCopyright (C) 2009 University of Edinburgh\n\nThis library is free software; you can redistribute it and\/or\nmodify it under the terms of the GNU Lesser General Public\nLicense as published by the Free Software Foundation; either\nversion 2.1 of the License, or (at your option) any later version.\n\nThis library is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\nLesser General Public License for more details.\n\nYou should have received a copy of the GNU Lesser General Public\nLicense along with this library; if not, write to the Free Software\nFoundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n***********************************************************************\/\n\n#include \"Decoder.h\"\n#include \"Manager.h\"\n#include \"ChartManager.h\"\n#include \"Sentence.h\"\n#include \"InputType.h\"\n#include \"TranslationSystem.h\"\n#include \"Phrase.h\"\n#include \"TrellisPathList.h\"\n#include \"ChartTrellisPathList.h\"\n#include \"ChartTrellisPath.h\"\n#include \"IOWrapper.h\"\n\nusing namespace std;\nusing namespace Moses;\n\n\nnamespace Mira {\n\n \/**\n * Allocates a char* and copies string into it.\n **\/\n static char* strToChar(const string& s) {\n char* c = new char[s.size()+1];\n strcpy(c,s.c_str());\n return c;\n }\n\n MosesDecoder::MosesDecoder(const string& inifile, int debuglevel, int argc, vector<string> decoder_params)\n\t\t: m_manager(NULL) {\n \tstatic int BASE_ARGC = 6;\n\t Parameter* params = new Parameter();\n\t char ** mosesargv = new char*[BASE_ARGC + argc];\n\t mosesargv[0] = strToChar(\"-f\");\n\t mosesargv[1] = strToChar(inifile);\n\t mosesargv[2] = strToChar(\"-v\");\n\t stringstream dbgin;\n\t dbgin << debuglevel;\n\t mosesargv[3] = strToChar(dbgin.str());\n\t mosesargv[4] = strToChar(\"-use-persistent-cache\"); \n\t mosesargv[5] = strToChar(\"0\"); \n\n\t for (int i = 0; i < argc; ++i) {\n\t\t char *cstr = &(decoder_params[i])[0];\n\t\t mosesargv[BASE_ARGC + i] = cstr;\n\t }\n\n\t if (!params->LoadParam(BASE_ARGC + argc,mosesargv)) {\n\t\t cerr << \"Loading static data failed, exit.\" << endl;\n\t\t exit(1);\n\t }\n\t StaticData::LoadDataStatic(params);\n\t for (int i = 0; i < BASE_ARGC; ++i) {\n\t\t delete[] mosesargv[i];\n\t }\n\t delete[] mosesargv;\n\n\t const StaticData &staticData = StaticData::Instance();\n m_bleuScoreFeature = staticData.GetBleuScoreFeature();\n }\n \n void MosesDecoder::cleanup(bool chartDecoding) {\n\t delete m_manager;\n\t if (chartDecoding)\n\t \tdelete m_chartManager;\n\t else\n\t \tdelete m_sentence;\n }\n\n vector< vector<const Word*> > MosesDecoder::getNBest(const std::string& source,\n size_t sentenceid,\n size_t nBestSize,\n float bleuObjectiveWeight, \n float bleuScoreWeight,\n vector< ScoreComponentCollection>& featureValues,\n vector< float>& bleuScores,\n vector< float>& modelScores,\n size_t numReturnedTranslations,\n bool distinct,\n bool avgRefLength,\n size_t rank,\n size_t epoch)\n {\n \tStaticData &staticData = StaticData::InstanceNonConst();\n \tinitialize(staticData, source, sentenceid, bleuObjectiveWeight, bleuScoreWeight, avgRefLength);\n const TranslationSystem& system = staticData.GetTranslationSystem(TranslationSystem::DEFAULT);\n\n \/\/ run the decoder\n if (staticData.GetSearchAlgorithm() == ChartDecoding) {\n \treturn runChartDecoder(source, sentenceid, nBestSize, bleuObjectiveWeight, bleuScoreWeight,\n \t\t\tfeatureValues, bleuScores, modelScores, numReturnedTranslations, distinct, rank, epoch,\n \t\t\tsystem);\n }\n else {\n \tSearchAlgorithm search = staticData.GetSearchAlgorithm();\n \treturn runDecoder(source, sentenceid, nBestSize, bleuObjectiveWeight, bleuScoreWeight,\n \t\t\tfeatureValues, bleuScores, modelScores, numReturnedTranslations, distinct, rank, epoch,\n \t\t\tsearch, system);\n }\n }\n\n vector< vector<const Word*> > MosesDecoder::runDecoder(const std::string& source,\n \t\t\t\t\t\t\t\t\t\t\t\t\t\tsize_t sentenceid,\n \t\t\t\t\t\t\t\t\t\t\t\t\t\tsize_t nBestSize,\n \t\t\t\t\t\t\t\t\t\t\t\t\t\tfloat bleuObjectiveWeight,\n \t\t\t\t\t\t\t\t\t\t\t\t\t\tfloat bleuScoreWeight,\n \t\t\t\t\t\t\t\t\t\t\t\t\t\tvector< ScoreComponentCollection>& featureValues,\n \t\t\t\t\t\t\t\t\t\t\t\t\t\tvector< float>& bleuScores,\n \t\t\t\t\t\t\t\t\t\t\t\t\t\tvector< float>& modelScores,\n \t\t\t\t\t\t\t\t\t\t\t\t\t\tsize_t numReturnedTranslations,\n \t\t\t\t\t\t\t\t\t\t\t\t\t\tbool distinct,\n \t\t\t\t\t\t\t\t\t\t\t\t\t\tsize_t rank,\n \t\t\t\t\t\t\t\t\t\t\t\t\t\tsize_t epoch,\n \t\t\t\t\t\t\t\t\t\t\t\t\t\tSearchAlgorithm& search,\n \t\t\t\t\t\t\t\t\t\t\t\t\t\tconst TranslationSystem& system) {\n \t\/\/ run the decoder\n m_manager = new Moses::Manager(*m_sentence, search, &system);\n m_manager->ProcessSentence();\n TrellisPathList nBestList;\n m_manager->CalcNBest(nBestSize, nBestList, distinct);\n\n \/\/ read off the feature values and bleu scores for each sentence in the nbest list\n Moses::TrellisPathList::const_iterator iter;\n for (iter = nBestList.begin() ; iter != nBestList.end() ; ++iter) {\n \tconst Moses::TrellisPath &path = **iter;\n \tfeatureValues.push_back(path.GetScoreBreakdown());\n \tfloat bleuScore = getBleuScore(featureValues.back());\n \tbleuScores.push_back(bleuScore);\n\n \t\/\/std::cout << \"Score breakdown: \" << path.GetScoreBreakdown() << endl;\n \tfloat scoreWithoutBleu = path.GetTotalScore() - (bleuObjectiveWeight * bleuScoreWeight * bleuScore);\n \tmodelScores.push_back(scoreWithoutBleu);\n\n \tPhrase bestPhrase = path.GetTargetPhrase();\n\n \tif (iter != nBestList.begin())\n \t\tcerr << endl;\n \t\tcerr << \"Rank \" << rank << \", epoch \" << epoch << \", \\\"\";\n \t\tPhrase phrase = path.GetTargetPhrase();\n \t\tfor (size_t pos = 0; pos < phrase.GetSize(); ++pos) {\n \t\tconst Word &word = phrase.GetWord(pos);\n \t\tWord *newWord = new Word(word);\n \t\tcerr << *newWord;\n \t}\n\n \tcerr << \"\\\", score: \" << scoreWithoutBleu << \", Bleu: \" << bleuScore << \", total: \" << path.GetTotalScore();\n\n \t\/\/ set bleu score to zero in the feature vector since we do not want to optimise its weight\n \tsetBleuScore(featureValues.back(), 0);\n }\n\n \/\/ prepare translations to return\n vector< vector<const Word*> > translations;\n for (size_t i=0; i < numReturnedTranslations && i < nBestList.GetSize(); ++i) {\n const TrellisPath &path = nBestList.at(i);\n Phrase phrase = path.GetTargetPhrase();\n\n vector<const Word*> translation;\n for (size_t pos = 0; pos < phrase.GetSize(); ++pos) {\n \tconst Word &word = phrase.GetWord(pos);\n \tWord *newWord = new Word(word);\n \ttranslation.push_back(newWord);\n }\n translations.push_back(translation);\n }\n\n\/\/ cerr << \"Rank \" << rank << \", use cache: \" << staticData.GetUseTransOptCache() << \", weights: \" << staticData.GetAllWeights() << endl;\n return translations;\n }\n\n vector< vector<const Word*> > MosesDecoder::runChartDecoder(const std::string& source,\n size_t sentenceid,\n size_t nBestSize,\n float bleuObjectiveWeight,\n float bleuScoreWeight,\n vector< ScoreComponentCollection>& featureValues,\n vector< float>& bleuScores,\n vector< float>& modelScores,\n size_t numReturnedTranslations,\n bool distinct,\n size_t rank,\n size_t epoch,\n const TranslationSystem& system) {\n \t\/\/ run the decoder\n m_chartManager = new ChartManager(*m_sentence, &system);\n m_chartManager->ProcessSentence();\n ChartTrellisPathList nBestList;\n m_chartManager->CalcNBest(nBestSize, nBestList, distinct);\n\n \/\/ read off the feature values and bleu scores for each sentence in the nbest list\n ChartTrellisPathList::const_iterator iter;\n for (iter = nBestList.begin() ; iter != nBestList.end() ; ++iter) {\n \tconst Moses::ChartTrellisPath &path = **iter;\n \tfeatureValues.push_back(path.GetScoreBreakdown());\n \tfloat bleuScore = getBleuScore(featureValues.back());\n \tbleuScores.push_back(bleuScore);\n\n \t\/\/std::cout << \"Score breakdown: \" << path.GetScoreBreakdown() << endl;\n \tfloat scoreWithoutBleu = path.GetTotalScore() - (bleuObjectiveWeight * bleuScoreWeight * bleuScore);\n \tmodelScores.push_back(scoreWithoutBleu);\n\n \tPhrase bestPhrase = path.GetOutputPhrase();\n\n \tif (iter != nBestList.begin())\n \t\tcerr << endl;\n \t\tcerr << \"Rank \" << rank << \", epoch \" << epoch << \", \\\"\";\n \t\tPhrase phrase = path.GetOutputPhrase();\n \t\tfor (size_t pos = 0; pos < phrase.GetSize(); ++pos) {\n \t\tconst Word &word = phrase.GetWord(pos);\n \t\tWord *newWord = new Word(word);\n \t\tcerr << *newWord;\n \t}\n\n \tcerr << \"\\\", score: \" << scoreWithoutBleu << \", Bleu: \" << bleuScore << \", total: \" << path.GetTotalScore();\n\n \t\/\/ set bleu score to zero in the feature vector since we do not want to optimise its weight\n \tsetBleuScore(featureValues.back(), 0);\n }\n\n \/\/ prepare translations to return\n vector< vector<const Word*> > translations;\n for (iter = nBestList.begin() ; iter != nBestList.end() ; ++iter) {\n const ChartTrellisPath &path = **iter;\n Phrase phrase = path.GetOutputPhrase();\n\n vector<const Word*> translation;\n for (size_t pos = 0; pos < phrase.GetSize(); ++pos) {\n \tconst Word &word = phrase.GetWord(pos);\n \tWord *newWord = new Word(word);\n \ttranslation.push_back(newWord);\n }\n translations.push_back(translation);\n }\n\n\/\/ cerr << \"Rank \" << rank << \", use cache: \" << staticData.GetUseTransOptCache() << \", weights: \" << staticData.GetAllWeights() << endl;\n return translations;\n }\n\n void MosesDecoder::outputNBestList(const std::string& source, size_t sentenceid,\n \t\t\t\t\t\t\t\t\t\t\t\t\t\tsize_t nBestSize, float bleuObjectiveWeight, float bleuScoreWeight,\n \t\t\t\t\t\t\t\t\t\t\t\t\t\tbool distinctNbest, bool avgRefLength, string filename, ofstream& streamOut) {\n \tStaticData &staticData = StaticData::InstanceNonConst();\n \tinitialize(staticData, source, sentenceid, bleuObjectiveWeight, bleuScoreWeight, avgRefLength);\n const TranslationSystem& system = staticData.GetTranslationSystem(TranslationSystem::DEFAULT);\n\n if (staticData.GetSearchAlgorithm() == ChartDecoding) {\n m_chartManager = new ChartManager(*m_sentence, &system);\n m_chartManager->ProcessSentence();\n ChartTrellisPathList nBestList;\n m_chartManager->CalcNBest(nBestSize, nBestList, distinctNbest);\n\n cerr << \"generate nbest list \" << filename << endl;\n cerr << \"not implemented..\" << endl;\n exit(1);\n \tif (filename != \"\") {\n \t\tofstream out(filename.c_str());\n \t\tif (!out) {\n \t\t\tostringstream msg;\n \t\t\tmsg << \"Unable to open \" << filename;\n \t\t\tthrow runtime_error(msg.str());\n \t\t}\n \t\t\/\/ TODO: handle sentence id (for now always 0)\n\/\/ \t\tOutputNBestList(const ChartTrellisPathList &nBestList, const ChartHypothesis *bestHypo, const TranslationSystem* system, long translationId)\n\/\/ \t\tOutputNBest(out, nBestList, StaticData::Instance().GetOutputFactorOrder(),m_manager->GetTranslationSystem(), 0);\n \t\tout.close();\n \t}\n \telse {\n\/\/ \t\tOutputNBest(streamOut, nBestList, StaticData::Instance().GetOutputFactorOrder(),m_manager->GetTranslationSystem(), sentenceid);\n \t}\n }\n else {\n \t\/\/ run the decoder\n m_manager = new Moses::Manager(*m_sentence, staticData.GetSearchAlgorithm(), &system);\n m_manager->ProcessSentence();\n TrellisPathList nBestList;\n m_manager->CalcNBest(nBestSize, nBestList, distinctNbest);\n\n if (filename != \"\") {\n \t\tofstream out(filename.c_str());\n \t\tif (!out) {\n \t\t\tostringstream msg;\n \t\t\tmsg << \"Unable to open \" << filename;\n \t\t\tthrow runtime_error(msg.str());\n \t\t}\n \t\t\/\/ TODO: handle sentence id (for now always 0)\n \t\tOutputNBest(out, nBestList, StaticData::Instance().GetOutputFactorOrder(),m_manager->GetTranslationSystem(), 0);\n \t\tout.close();\n }\n else {\n\tOutputNBest(streamOut, nBestList, StaticData::Instance().GetOutputFactorOrder(),m_manager->GetTranslationSystem(), sentenceid);\n\tstreamOut.flush();\n }\n }\n }\n\n void MosesDecoder::initialize(StaticData& staticData, const std::string& source, size_t sentenceid,\n \t\t\t\t\t\t\t\t\t\t\t\t\tfloat bleuObjectiveWeight, float bleuScoreWeight, bool avgRefLength) {\n \tm_sentence = new Sentence();\n stringstream in(source + \"\\n\");\n const std::vector<FactorType> &inputFactorOrder = staticData.GetInputFactorOrder();\n m_sentence->Read(in,inputFactorOrder);\n\n \/\/ set weight of BleuScoreFeature\n staticData.ReLoadBleuScoreFeatureParameter(bleuObjectiveWeight*bleuScoreWeight);\n\n m_bleuScoreFeature->SetCurrSourceLength((*m_sentence).GetSize());\n if (avgRefLength)\n \tm_bleuScoreFeature->SetCurrAvgRefLength(sentenceid);\n else\n \tm_bleuScoreFeature->SetCurrShortestRefLength(sentenceid);\n m_bleuScoreFeature->SetCurrReferenceNgrams(sentenceid);\n }\n\n float MosesDecoder::getBleuScore(const ScoreComponentCollection& scores) {\n return scores.GetScoreForProducer(m_bleuScoreFeature);\n }\n\n void MosesDecoder::setBleuScore(ScoreComponentCollection& scores, float bleu) {\n scores.Assign(m_bleuScoreFeature, bleu);\n }\n\n ScoreComponentCollection MosesDecoder::getWeights() {\n return StaticData::Instance().GetAllWeights();\n }\n\n void MosesDecoder::setWeights(const ScoreComponentCollection& weights) {\n StaticData::InstanceNonConst().SetAllWeights(weights);\n }\n\n void MosesDecoder::updateHistory(const vector<const Word*>& words) {\n m_bleuScoreFeature->UpdateHistory(words);\n }\n\n void MosesDecoder::updateHistory(const vector< vector< const Word*> >& words, vector<size_t>& sourceLengths, vector<size_t>& ref_ids, size_t rank, size_t epoch) {\n\t m_bleuScoreFeature->UpdateHistory(words, sourceLengths, ref_ids, rank, epoch);\n }\n\n void MosesDecoder::printBleuFeatureHistory(std::ostream& out) {\n \tm_bleuScoreFeature->PrintHistory(out);\n }\n\n size_t MosesDecoder::getClosestReferenceLength(size_t ref_id, int hypoLength) {\n \treturn m_bleuScoreFeature->GetClosestRefLength(ref_id, hypoLength);\n }\n\n size_t MosesDecoder::getShortestReferenceIndex(size_t ref_id) {\n \treturn m_bleuScoreFeature->GetShortestRefIndex(ref_id);\n }\n\n void MosesDecoder::setBleuParameters(bool sentenceBleu, bool scaleByInputLength, bool scaleByAvgInputLength,\n\t\t bool scaleByInverseLength, bool scaleByAvgInverseLength,\n\t\t float scaleByX, float historySmoothing, size_t scheme, float relax_BP,\n\t\t bool useSourceLengthHistory) {\n\t m_bleuScoreFeature->SetBleuParameters(sentenceBleu, scaleByInputLength, scaleByAvgInputLength,\n\t\t\t scaleByInverseLength, scaleByAvgInverseLength,\n\t\t\t scaleByX, historySmoothing, scheme, relax_BP,\n\t\t\t useSourceLengthHistory);\n }\n} \n\n<|endoftext|>"} {"text":"<commit_before>\/***************************************************************************\n fbellini@cern.ch - last modified on 28\/11\/2013\n\/\/\n\/\/Lauches KStar analysis with rsn mini package\n\/\/Allows basic configuration of pile-up check and event cuts\n\/\/\n****************************************************************************\/\nenum pairYCutSet { kPairDefault=0,\n\t\t kCentral \/\/=1\n };\n\nenum eventCutSet { kEvtDefault=0,\n\t\t kNoPileUpCut, \/\/=1\n\t\t kDefaultVtx12,\/\/=2\n\t\t kDefaultVtx8, \/\/=3\n\t\t kDefaultVtx5, \/\/=4 \n\t\t kMCEvtDefault, \/\/=5\n\t\t kSpecial1, \/\/=6 \n\t\t kSpecial2, \/\/=7\n\t\t kNoEvtSel, \/\/=8 \n\t\t kSpecial3\/\/=9\n };\n\nenum eventMixConfig { kDisabled = -1,\n\t\t kMixDefault,\/\/=0 \/\/10 events, Dvz = 1cm, DC = 10\n\t\t k5Evts, \/\/=1 \/\/5 events, Dvz = 1cm, DC = 10\n\t\t k5Cent, \/\/=2 \/\/10 events, Dvz = 1cm, DC = 5\n\t\t k5Evts5Cent\n };\n\n\nAliRsnMiniAnalysisTask * AddTaskKStarPP13TeV_PID_sp\n(\n Bool_t useHIST = kTRUE,\n Bool_t Sp = kFALSE,\n Bool_t isMC = kFALSE,\n Bool_t isPP = kTRUE,\n TString outNameSuffix = \"tpc2stof3sveto\",\n Int_t evtCutSetID = 0,\n Int_t pairCutSetID = 0,\n Int_t mixingConfigID = 0,\n Int_t aodFilterBit = 5,\n Int_t customQualityCutsID = -1,\n AliRsnCutSetDaughterParticle::ERsnDaughterCutSet cutPiCandidate = AliRsnCutSetDaughterParticle::kTPCpidTOFveto3s,\n AliRsnCutSetDaughterParticle::ERsnDaughterCutSet cutKaCandidate = AliRsnCutSetDaughterParticle::kTPCpidTOFveto3s,\n Float_t nsigmaPi = 2.0,\n Float_t nsigmaKa = 2.0,\n Bool_t enableMonitor = kTRUE,\n Bool_t IsMcTrueOnly = kFALSE,\n TString monitorOpt = \"NoSIGN\",\n Bool_t useMixLS = 0,\n Bool_t checkReflex = 0,\n AliRsnMiniValue::EType yaxisvar = AliRsnMiniValue::kPt\n)\n{ \n\n \n \/\/-------------------------------------------\n \/\/ event cuts\n \/\/-------------------------------------------\n UInt_t triggerMask = AliVEvent::kINT7;\/\/A Khuntia\n \/\/ if(isMC && (evtCutSetID==eventCutSet::kNoEvtSel || evtCutSetID==eventCutSet::kSpecial3)) triggerMask=AliVEvent::kAny;\n Bool_t rejectPileUp = kTRUE; \/\/\n Double_t vtxZcut = 10.0; \/\/cm, default cut on vtx z\n \n if (evtCutSetID==eventCutSet::kDefaultVtx12){vtxZcut = 12.0;} \/\/cm\n\n if (evtCutSetID==eventCutSet::kDefaultVtx8){vtxZcut = 8.0;} \/\/cm\n \n if (evtCutSetID==eventCutSet::kDefaultVtx5){vtxZcut = 5.0;}\/\/cm\n \n if (evtCutSetID==eventCutSet::kNoPileUpCut){rejectPileUp=kFALSE;}\/\/cm\n \n if(evtCutSetID==eventCutSet::kSpecial2) vtxZcut=1.e6;\/\/off\n\n \/\/-------------------------------------------\n \/\/pair cuts\n \/\/-------------------------------------------\n Double_t minYlab = -0.5;\n Double_t maxYlab = 0.5;\n \n if (pairCutSetID==pairYCutSet::kCentral) { \/\/|y_cm|<0.3\n minYlab = -0.3; maxYlab = 0.3;\n }\n\n \/\/-------------------------------------------\n \/\/mixing settings\n \/\/-------------------------------------------\n Int_t nmix = 0;\n Float_t maxDiffVzMix = 1.0;\n Float_t maxDiffMultMix = 10.0;\n \n if (mixingConfigID == eventMixConfig::kMixDefault) { nmix = 10;}\n\n if (mixingConfigID == eventMixConfig::k5Evts) {nmix = 5;}\n \n if (mixingConfigID == eventMixConfig::k5Cent) {maxDiffMultMix = 5;}\n \n if(mixingConfigID==eventMixConfig::k5Evts5Cent){nmix=5; maxDiffMultMix=5;}\n\n \/\/\n \/\/ -- INITIALIZATION ----------------------------------------------------------------------------\n \/\/ retrieve analysis manager\n \/\/\n AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();\n if (!mgr) {\n ::Error(\"AddAnalysisTaskTOFKStar\", \"No analysis manager to connect to.\");\n return NULL;\n } \n\n \/\/ create the task and configure \n TString taskName = Form(\"TOFKStar%s%s_%i%i\", (isPP? \"pp\" : \"PbPb\"), (isMC ? \"MC\" : \"Data\"), (Int_t)cutPiCandidate,(Int_t)cutKaCandidate );\n AliRsnMiniAnalysisTask *task = new AliRsnMiniAnalysisTask(taskName.Data(), isMC);\n \/\/task->UseESDTriggerMask(triggerMask); \/\/ESD\n \/\/task->SelectCollisionCandidates(triggerMask); \/\/AOD\n if(evtCutSetID!=eventCutSet::kNoEvtSel && evtCutSetID!=eventCutSet::kSpecial3) task->SelectCollisionCandidates(triggerMask); \/\/AOD\n\n \n if (isPP) \n task->UseMultiplicity(\"QUALITY\");\n else\n task->UseCentrality(\"V0M\"); \n \/\/ set event mixing options\n task->UseContinuousMix();\n \/\/task->UseBinnedMix();\n task->SetNMix(nmix);\n task->SetMaxDiffVz(maxDiffVzMix);\n task->SetMaxDiffMult(maxDiffMultMix);\n ::Info(\"AddAnalysisTaskTOFKStar\", Form(\"Event mixing configuration: \\n events to mix = %i \\n max diff. vtxZ = cm %5.3f \\n max diff multi = %5.3f\", nmix, maxDiffVzMix, maxDiffMultMix));\n \n mgr->AddTask(task);\n \n \/\/\n \/\/ cut on primary vertex:\n \/\/ - 2nd argument --> |Vz| range\n \/\/ - 3rd argument --> minimum required number of contributors to vtx\n \/\/ - 4th argument --> tells if TPC stand-alone vertexes must be accepted\n AliRsnCutPrimaryVertex *cutVertex=0;\n if (evtCutSetID!=eventCutSet::kSpecial1 && evtCutSetID!=eventCutSet::kNoEvtSel){\n cutVertex = new AliRsnCutPrimaryVertex(\"cutVertex\", vtxZcut, 0, kFALSE);\n if (evtCutSetID==eventCutSet::kSpecial3) cutVertex->SetCheckGeneratedVertexZ();\n\n }\/\/vertex loop\n\n\n \n if (isPP && (!isMC)&&cutVertex) { \n cutVertex->SetCheckPileUp(rejectPileUp); \/\/ set the check for pileup \n ::Info(\"AddAnalysisTaskTOFKStar\", Form(\":::::::::::::::::: Pile-up rejection mode: %s\", (rejectPileUp)?\"ON\":\"OFF\"));\n \/\/cutVertex->SetCheckZResolutionSPD();\/\/A Khuntia\n \/\/cutVertex->SetCheckDispersionSPD();\/\/A Khuntia\n \/\/cutVertex->SetCheckZDifferenceSPDTrack();\/\/A Khuntia\n }\n \n\n \n \/\/\/\/\/\/\/----------AKhuntia----------\/\/\/\/\/\/\n \/*AliRsnCutEventUtils* cutEventUtils=0;\n cutEventUtils=new AliRsnCutEventUtils(\"cutEventUtils\",kTRUE,rejectPileUp);\n cutEventUtils->SetCheckIncompleteDAQ();\n cutEventUtils->SetCheckSPDClusterVsTrackletBG();*\/\n \/\/------------------------------------\n \/\/ define and fill cut set for event cut\n\n AliRsnCutSet* eventCuts=0;\n if(cutVertex){\n eventCuts = new AliRsnCutSet(\"eventCuts\", AliRsnTarget::kEvent);\n eventCuts->AddCut(cutVertex);\n eventCuts->SetCutScheme(Form(\"%s\", cutVertex->GetName()));\n task->SetEventCuts(eventCuts);\n }\n \/\/\n \/\/ -- EVENT-ONLY COMPUTATIONS -------------------------------------------------------------------\n \/\/ \n \/\/vertex\n Int_t vtxID = task->CreateValue(AliRsnMiniValue::kVz, kFALSE);\n AliRsnMiniOutput *outVtx = task->CreateOutput(\"eventVtx\", \"HIST\", \"EVENT\");\n outVtx->AddAxis(vtxID, 240, -12.0, 12.0);\n \n \/\/multiplicity or centrality\n Int_t multID = task->CreateValue(AliRsnMiniValue::kMult, kFALSE);\n AliRsnMiniOutput *outMult = task->CreateOutput(\"eventMult\", \"HIST\", \"EVENT\");\n if (isPP) \n outMult->AddAxis(multID, 400, 0.0, 400.0);\n else\n outMult->AddAxis(multID, 100, 0.0, 100.0);\n \n TH2F* hvz=new TH2F(\"hVzVsCent\",\"\", 100, 0., 100., 240, -12.0, 12.0);\n task->SetEventQAHist(\"vz\",hvz);\/\/plugs this histogram into the fHAEventVz data member\n\n TH2F* hmc=new TH2F(\"MultiVsCent\",\"\", 100, 0., 100., 400, 0., 400.);\n hmc->GetYaxis()->SetTitle(\"QUALITY\");\n task->SetEventQAHist(\"multicent\",hmc);\/\/plugs this histogram into the fHAEventMultiCent data member\n\n \/\/-------------------------------Arvind Spherocity QA-------------------------------------------\n\n if (Sp) AliRsnMiniAnalysisTask::SetComputeSpherocity(kTRUE);\n TH2F* hsp=new TH2F(\"hSpherocityVsCent\",\"\",110,0.,110., 200,0.,1.5);\n task->SetEventQAHist(\"spherocitycent\",hsp);\/\/plugs this histogram into the fHASpherocityCent data member\n \n \/\/\n \/\/ -- PAIR CUTS (common to all resonances) ------------------------------------------------------\n \/\/\n \n AliRsnCutMiniPair *cutY = new AliRsnCutMiniPair(\"cutRapidity\", AliRsnCutMiniPair::kRapidityRange);\n cutY->SetRangeD(minYlab, maxYlab);\n \n AliRsnCutSet *cutsPair = new AliRsnCutSet(\"pairCuts\", AliRsnTarget::kMother);\n cutsPair->AddCut(cutY);\n cutsPair->SetCutScheme(cutY->GetName());\n \n \/\/\n \/\/ -- CONFIG ANALYSIS --------------------------------------------------------------------------\n \/\/ \n gROOT->LoadMacro(\"$ALICE_PHYSICS\/PWGLF\/RESONANCES\/macros\/mini\/ConfigKStarPP13TeV_PID_sp.C\");\n \/\/gROOT->LoadMacro(\"ConfigKStarPP13TeV_PID_sp.C\");\n if (!ConfigKStarPP8TeV_PID(task,useHIST, isMC, isPP, \"\", cutsPair, aodFilterBit, customQualityCutsID, cutPiCandidate, cutKaCandidate, nsigmaPi, nsigmaKa, enableMonitor, isMC&IsMcTrueOnly, monitorOpt.Data(), useMixLS, isMC&checkReflex, yaxisvar)) return 0x0;\n \n \n \/\/\n \/\/ -- CONTAINERS --------------------------------------------------------------------------------\n \/\/\n TString outputFileName = AliAnalysisManager::GetCommonFileName();\n \/\/ outputFileName += \":Rsn\";\n Printf(\"AddAnalysisTaskTOFKStar - Set OutputFileName : \\n %s\\n\", outputFileName.Data() );\n \n if(!useHIST)\n { AliAnalysisDataContainer *output = mgr->CreateContainer(Form(\"RsnOut_%s\",outNameSuffix.Data()), \n\t\t\t\t\t\t\t TList::Class(), \n\t\t\t\t\t\t\t AliAnalysisManager::kOutputContainer, \n\t\t\t\t\t\t\t outputFileName);\n mgr->ConnectInput(task, 0, mgr->GetCommonInputContainer());\n mgr->ConnectOutput(task, 1, output);\n }\n\n if(useHIST)\n { AliAnalysisDataContainer *output = mgr->CreateContainer(Form(\"RsnOut_hist%s\",outNameSuffix.Data()), \n\t\t\t\t\t\t\t TList::Class(), \n\t\t\t\t\t\t\t AliAnalysisManager::kOutputContainer, \n\t\t\t\t\t\t\t outputFileName);\n mgr->ConnectInput(task, 0, mgr->GetCommonInputContainer());\n mgr->ConnectOutput(task, 1, output);\n }\n \n return task;\n}\n \n<commit_msg>Correction on AddTask macro for KStar analysis in pp at 13 TeV<commit_after>\/***************************************************************************\n fbellini@cern.ch - last modified on 28\/11\/2013\n\/\/\n\/\/Lauches KStar analysis with rsn mini package\n\/\/Allows basic configuration of pile-up check and event cuts\n\/\/\n****************************************************************************\/\nenum pairYCutSet { kPairDefault=0,\n\t\t kCentral \/\/=1\n };\n\nenum eventCutSet { kEvtDefault=0,\n\t\t kNoPileUpCut, \/\/=1\n\t\t kDefaultVtx12,\/\/=2\n\t\t kDefaultVtx8, \/\/=3\n\t\t kDefaultVtx5, \/\/=4 \n\t\t kMCEvtDefault, \/\/=5\n\t\t kSpecial1, \/\/=6 \n\t\t kSpecial2, \/\/=7\n\t\t kNoEvtSel, \/\/=8 \n\t\t kSpecial3\/\/=9\n };\n\nenum eventMixConfig { kDisabled = -1,\n\t\t kMixDefault,\/\/=0 \/\/10 events, Dvz = 1cm, DC = 10\n\t\t k5Evts, \/\/=1 \/\/5 events, Dvz = 1cm, DC = 10\n\t\t k5Cent, \/\/=2 \/\/10 events, Dvz = 1cm, DC = 5\n\t\t k5Evts5Cent\n };\n\n\nAliRsnMiniAnalysisTask * AddTaskKStarPP13TeV_PID_sp\n(\n Bool_t useHIST = kTRUE,\n Bool_t Sp = kFALSE,\n Bool_t isMC = kFALSE,\n Bool_t isPP = kTRUE,\n TString outNameSuffix = \"tpc2stof3sveto\",\n Int_t evtCutSetID = 0,\n Int_t pairCutSetID = 0,\n Int_t mixingConfigID = 0,\n Int_t aodFilterBit = 5,\n Int_t customQualityCutsID = -1,\n AliRsnCutSetDaughterParticle::ERsnDaughterCutSet cutPiCandidate = AliRsnCutSetDaughterParticle::kTPCpidTOFveto3s,\n AliRsnCutSetDaughterParticle::ERsnDaughterCutSet cutKaCandidate = AliRsnCutSetDaughterParticle::kTPCpidTOFveto3s,\n Float_t nsigmaPi = 2.0,\n Float_t nsigmaKa = 2.0,\n Bool_t enableMonitor = kTRUE,\n Bool_t IsMcTrueOnly = kFALSE,\n TString monitorOpt = \"NoSIGN\",\n Bool_t useMixLS = 0,\n Bool_t checkReflex = 0,\n AliRsnMiniValue::EType yaxisvar = AliRsnMiniValue::kPt\n)\n{ \n\n \n \/\/-------------------------------------------\n \/\/ event cuts\n \/\/-------------------------------------------\n UInt_t triggerMask = AliVEvent::kINT7;\/\/A Khuntia\n \/\/ if(isMC && (evtCutSetID==eventCutSet::kNoEvtSel || evtCutSetID==eventCutSet::kSpecial3)) triggerMask=AliVEvent::kAny;\n Bool_t rejectPileUp = kTRUE; \/\/\n Double_t vtxZcut = 10.0; \/\/cm, default cut on vtx z\n \n if (evtCutSetID==eventCutSet::kDefaultVtx12){vtxZcut = 12.0;} \/\/cm\n\n if (evtCutSetID==eventCutSet::kDefaultVtx8){vtxZcut = 8.0;} \/\/cm\n \n if (evtCutSetID==eventCutSet::kDefaultVtx5){vtxZcut = 5.0;}\/\/cm\n \n if (evtCutSetID==eventCutSet::kNoPileUpCut){rejectPileUp=kFALSE;}\/\/cm\n \n if(evtCutSetID==eventCutSet::kSpecial2) vtxZcut=1.e6;\/\/off\n\n \/\/-------------------------------------------\n \/\/pair cuts\n \/\/-------------------------------------------\n Double_t minYlab = -0.5;\n Double_t maxYlab = 0.5;\n \n if (pairCutSetID==pairYCutSet::kCentral) { \/\/|y_cm|<0.3\n minYlab = -0.3; maxYlab = 0.3;\n }\n\n \/\/-------------------------------------------\n \/\/mixing settings\n \/\/-------------------------------------------\n Int_t nmix = 0;\n Float_t maxDiffVzMix = 1.0;\n Float_t maxDiffMultMix = 10.0;\n \n if (mixingConfigID == eventMixConfig::kMixDefault) { nmix = 10;}\n\n if (mixingConfigID == eventMixConfig::k5Evts) {nmix = 5;}\n \n if (mixingConfigID == eventMixConfig::k5Cent) {maxDiffMultMix = 5;}\n \n if(mixingConfigID==eventMixConfig::k5Evts5Cent){nmix=5; maxDiffMultMix=5;}\n\n \/\/\n \/\/ -- INITIALIZATION ----------------------------------------------------------------------------\n \/\/ retrieve analysis manager\n \/\/\n AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();\n if (!mgr) {\n ::Error(\"AddAnalysisTaskTOFKStar\", \"No analysis manager to connect to.\");\n return NULL;\n } \n\n \/\/ create the task and configure \n TString taskName = Form(\"TOFKStar%s%s_%i%i\", (isPP? \"pp\" : \"PbPb\"), (isMC ? \"MC\" : \"Data\"), (Int_t)cutPiCandidate,(Int_t)cutKaCandidate );\n AliRsnMiniAnalysisTask *task = new AliRsnMiniAnalysisTask(taskName.Data(), isMC);\n \/\/task->UseESDTriggerMask(triggerMask); \/\/ESD\n \/\/task->SelectCollisionCandidates(triggerMask); \/\/AOD\n if(evtCutSetID!=eventCutSet::kNoEvtSel && evtCutSetID!=eventCutSet::kSpecial3) task->SelectCollisionCandidates(triggerMask); \/\/AOD\n\n \n if (isPP) \n task->UseMultiplicity(\"QUALITY\");\n else\n task->UseCentrality(\"V0M\"); \n \/\/ set event mixing options\n task->UseContinuousMix();\n \/\/task->UseBinnedMix();\n task->SetNMix(nmix);\n task->SetMaxDiffVz(maxDiffVzMix);\n task->SetMaxDiffMult(maxDiffMultMix);\n ::Info(\"AddAnalysisTaskTOFKStar\", Form(\"Event mixing configuration: \\n events to mix = %i \\n max diff. vtxZ = cm %5.3f \\n max diff multi = %5.3f\", nmix, maxDiffVzMix, maxDiffMultMix));\n \n mgr->AddTask(task);\n \n \/\/\n \/\/ cut on primary vertex:\n \/\/ - 2nd argument --> |Vz| range\n \/\/ - 3rd argument --> minimum required number of contributors to vtx\n \/\/ - 4th argument --> tells if TPC stand-alone vertexes must be accepted\n AliRsnCutPrimaryVertex *cutVertex=0;\n if (evtCutSetID!=eventCutSet::kSpecial1 && evtCutSetID!=eventCutSet::kNoEvtSel){\n cutVertex = new AliRsnCutPrimaryVertex(\"cutVertex\", vtxZcut, 0, kFALSE);\n if (evtCutSetID==eventCutSet::kSpecial3) cutVertex->SetCheckGeneratedVertexZ();\n\n }\/\/vertex loop\n\n\n \n if (isPP && (!isMC)&&cutVertex) { \n cutVertex->SetCheckPileUp(rejectPileUp); \/\/ set the check for pileup \n ::Info(\"AddAnalysisTaskTOFKStar\", Form(\":::::::::::::::::: Pile-up rejection mode: %s\", (rejectPileUp)?\"ON\":\"OFF\"));\n \/\/cutVertex->SetCheckZResolutionSPD();\/\/A Khuntia\n \/\/cutVertex->SetCheckDispersionSPD();\/\/A Khuntia\n \/\/cutVertex->SetCheckZDifferenceSPDTrack();\/\/A Khuntia\n }\n \n\n \n \/\/\/\/\/\/\/----------AKhuntia----------\/\/\/\/\/\/\n \/*AliRsnCutEventUtils* cutEventUtils=0;\n cutEventUtils=new AliRsnCutEventUtils(\"cutEventUtils\",kTRUE,rejectPileUp);\n cutEventUtils->SetCheckIncompleteDAQ();\n cutEventUtils->SetCheckSPDClusterVsTrackletBG();*\/\n \/\/------------------------------------\n \/\/ define and fill cut set for event cut\n\n AliRsnCutSet* eventCuts=0;\n if(cutVertex){\n eventCuts = new AliRsnCutSet(\"eventCuts\", AliRsnTarget::kEvent);\n eventCuts->AddCut(cutVertex);\n eventCuts->SetCutScheme(Form(\"%s\", cutVertex->GetName()));\n task->SetEventCuts(eventCuts);\n }\n \/\/\n \/\/ -- EVENT-ONLY COMPUTATIONS -------------------------------------------------------------------\n \/\/ \n \/\/vertex\n Int_t vtxID = task->CreateValue(AliRsnMiniValue::kVz, kFALSE);\n AliRsnMiniOutput *outVtx = task->CreateOutput(\"eventVtx\", \"HIST\", \"EVENT\");\n outVtx->AddAxis(vtxID, 240, -12.0, 12.0);\n \n \/\/multiplicity or centrality\n Int_t multID = task->CreateValue(AliRsnMiniValue::kMult, kFALSE);\n AliRsnMiniOutput *outMult = task->CreateOutput(\"eventMult\", \"HIST\", \"EVENT\");\n if (isPP) \n outMult->AddAxis(multID, 400, 0.0, 400.0);\n else\n outMult->AddAxis(multID, 100, 0.0, 100.0);\n \n TH2F* hvz=new TH2F(\"hVzVsCent\",\"\", 100, 0., 100., 240, -12.0, 12.0);\n task->SetEventQAHist(\"vz\",hvz);\/\/plugs this histogram into the fHAEventVz data member\n\n TH2F* hmc=new TH2F(\"MultiVsCent\",\"\", 100, 0., 100., 400, 0., 400.);\n hmc->GetYaxis()->SetTitle(\"QUALITY\");\n task->SetEventQAHist(\"multicent\",hmc);\/\/plugs this histogram into the fHAEventMultiCent data member\n\n \/\/-------------------------------Arvind Spherocity QA-------------------------------------------\n\n if (Sp) AliRsnMiniAnalysisTask::SetComputeSpherocity(kTRUE);\n TH2F* hsp=new TH2F(\"hSpherocityVsCent\",\"\",110,0.,110., 200,0.,1.5);\n task->SetEventQAHist(\"spherocitycent\",hsp);\/\/plugs this histogram into the fHASpherocityCent data member\n \n \/\/\n \/\/ -- PAIR CUTS (common to all resonances) ------------------------------------------------------\n \/\/\n \n AliRsnCutMiniPair *cutY = new AliRsnCutMiniPair(\"cutRapidity\", AliRsnCutMiniPair::kRapidityRange);\n cutY->SetRangeD(minYlab, maxYlab);\n \n AliRsnCutSet *cutsPair = new AliRsnCutSet(\"pairCuts\", AliRsnTarget::kMother);\n cutsPair->AddCut(cutY);\n cutsPair->SetCutScheme(cutY->GetName());\n \n \/\/\n \/\/ -- CONFIG ANALYSIS --------------------------------------------------------------------------\n \/\/ \n gROOT->LoadMacro(\"$ALICE_PHYSICS\/PWGLF\/RESONANCES\/macros\/mini\/ConfigKStarPP13TeV_PID_sp.C\");\n \/\/gROOT->LoadMacro(\"ConfigKStarPP13TeV_PID_sp.C\");\n if (!ConfigKStarPP13TeV_PID_sp(task,useHIST, isMC, isPP, \"\", cutsPair, aodFilterBit, customQualityCutsID, cutPiCandidate, cutKaCandidate, nsigmaPi, nsigmaKa, enableMonitor, isMC&IsMcTrueOnly, monitorOpt.Data(), useMixLS, isMC&checkReflex, yaxisvar)) return 0x0;\n \n \n \/\/\n \/\/ -- CONTAINERS --------------------------------------------------------------------------------\n \/\/\n TString outputFileName = AliAnalysisManager::GetCommonFileName();\n \/\/ outputFileName += \":Rsn\";\n Printf(\"AddAnalysisTaskTOFKStar - Set OutputFileName : \\n %s\\n\", outputFileName.Data() );\n \n if(!useHIST)\n { AliAnalysisDataContainer *output = mgr->CreateContainer(Form(\"RsnOut_%s\",outNameSuffix.Data()), \n\t\t\t\t\t\t\t TList::Class(), \n\t\t\t\t\t\t\t AliAnalysisManager::kOutputContainer, \n\t\t\t\t\t\t\t outputFileName);\n mgr->ConnectInput(task, 0, mgr->GetCommonInputContainer());\n mgr->ConnectOutput(task, 1, output);\n }\n\n if(useHIST)\n { AliAnalysisDataContainer *output = mgr->CreateContainer(Form(\"RsnOut_hist%s\",outNameSuffix.Data()), \n\t\t\t\t\t\t\t TList::Class(), \n\t\t\t\t\t\t\t AliAnalysisManager::kOutputContainer, \n\t\t\t\t\t\t\t outputFileName);\n mgr->ConnectInput(task, 0, mgr->GetCommonInputContainer());\n mgr->ConnectOutput(task, 1, output);\n }\n \n return task;\n}\n \n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (C) 2004, 2005, 2006, 2007 Nikolas Zimmermann <zimmermann@kde.org>\n * Copyright (C) 2004, 2005 Rob Buis <buis@kde.org>\n * Copyright (C) 2005 Eric Seidel <eric@webkit.org>\n * Copyright (C) 2009 Dirk Schulze <krit@webkit.org>\n * Copyright (C) Research In Motion Limited 2010. All rights reserved.\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Library General Public\n * License as published by the Free Software Foundation; either\n * version 2 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Library General Public License for more details.\n *\n * You should have received a copy of the GNU Library General Public License\n * along with this library; see the file COPYING.LIB. If not, write to\n * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,\n * Boston, MA 02110-1301, USA.\n *\/\n\n#include \"config.h\"\n#include \"core\/rendering\/svg\/RenderSVGResourceFilter.h\"\n\n#include \"core\/dom\/ElementTraversal.h\"\n#include \"core\/svg\/SVGFilterPrimitiveStandardAttributes.h\"\n#include \"platform\/graphics\/GraphicsContext.h\"\n#include \"platform\/graphics\/filters\/SkiaImageFilterBuilder.h\"\n#include \"platform\/graphics\/filters\/SourceAlpha.h\"\n#include \"platform\/graphics\/filters\/SourceGraphic.h\"\n#include \"third_party\/skia\/include\/core\/SkPicture.h\"\n\nnamespace blink {\n\nvoid FilterData::trace(Visitor* visitor)\n{\n#if ENABLE(OILPAN)\n visitor->trace(filter);\n visitor->trace(builder);\n#endif\n}\n\nRenderSVGResourceFilter::RenderSVGResourceFilter(SVGFilterElement* node)\n : RenderSVGResourceContainer(node)\n{\n}\n\nRenderSVGResourceFilter::~RenderSVGResourceFilter()\n{\n}\n\nvoid RenderSVGResourceFilter::trace(Visitor* visitor)\n{\n#if ENABLE(OILPAN)\n visitor->trace(m_filter);\n#endif\n RenderSVGResourceContainer::trace(visitor);\n}\n\nvoid RenderSVGResourceFilter::destroy()\n{\n m_filter.clear();\n RenderSVGResourceContainer::destroy();\n}\n\nbool RenderSVGResourceFilter::isChildAllowed(RenderObject* child, RenderStyle*) const\n{\n return child->isSVGResourceFilterPrimitive();\n}\n\nvoid RenderSVGResourceFilter::removeAllClientsFromCache(bool markForInvalidation)\n{\n m_filter.clear();\n markAllClientsForInvalidation(markForInvalidation ? LayoutAndBoundariesInvalidation : ParentOnlyInvalidation);\n}\n\nvoid RenderSVGResourceFilter::removeClientFromCache(RenderObject* client, bool markForInvalidation)\n{\n ASSERT(client);\n\n m_filter.remove(client);\n\n markClientForInvalidation(client, markForInvalidation ? BoundariesInvalidation : ParentOnlyInvalidation);\n}\n\nPassRefPtrWillBeRawPtr<SVGFilterBuilder> RenderSVGResourceFilter::buildPrimitives(SVGFilter* filter)\n{\n SVGFilterElement* filterElement = toSVGFilterElement(element());\n FloatRect targetBoundingBox = filter->targetBoundingBox();\n\n \/\/ Add effects to the builder\n RefPtrWillBeRawPtr<SVGFilterBuilder> builder = SVGFilterBuilder::create(SourceGraphic::create(filter), SourceAlpha::create(filter));\n for (SVGElement* element = Traversal<SVGElement>::firstChild(*filterElement); element; element = Traversal<SVGElement>::nextSibling(*element)) {\n if (!element->isFilterEffect() || !element->renderer())\n continue;\n\n SVGFilterPrimitiveStandardAttributes* effectElement = static_cast<SVGFilterPrimitiveStandardAttributes*>(element);\n RefPtrWillBeRawPtr<FilterEffect> effect = effectElement->build(builder.get(), filter);\n if (!effect) {\n builder->clearEffects();\n return nullptr;\n }\n builder->appendEffectToEffectReferences(effect, effectElement->renderer());\n effectElement->setStandardAttributes(effect.get());\n effect->setEffectBoundaries(SVGLengthContext::resolveRectangle<SVGFilterPrimitiveStandardAttributes>(effectElement, filterElement->primitiveUnits()->currentValue()->enumValue(), targetBoundingBox));\n effect->setOperatingColorSpace(\n effectElement->renderer()->style()->svgStyle().colorInterpolationFilters() == CI_LINEARRGB ? ColorSpaceLinearRGB : ColorSpaceDeviceRGB);\n builder->add(AtomicString(effectElement->result()->currentValue()->value()), effect);\n }\n return builder.release();\n}\n\nstatic void beginDeferredFilter(GraphicsContext* context, FilterData* filterData)\n{\n context->beginRecording(filterData->boundaries);\n}\n\nstatic void endDeferredFilter(GraphicsContext* context, FilterData* filterData)\n{\n \/\/ FIXME: maybe filterData should just hold onto SourceGraphic after creation?\n SourceGraphic* sourceGraphic = static_cast<SourceGraphic*>(filterData->builder->getEffectById(SourceGraphic::effectName()));\n ASSERT(sourceGraphic);\n sourceGraphic->setPicture(context->endRecording());\n}\n\nstatic void drawDeferredFilter(GraphicsContext* context, FilterData* filterData, SVGFilterElement* filterElement)\n{\n SkiaImageFilterBuilder builder(context);\n SourceGraphic* sourceGraphic = static_cast<SourceGraphic*>(filterData->builder->getEffectById(SourceGraphic::effectName()));\n ASSERT(sourceGraphic);\n builder.setSourceGraphic(sourceGraphic);\n RefPtr<ImageFilter> imageFilter = builder.build(filterData->builder->lastEffect(), ColorSpaceDeviceRGB);\n FloatRect boundaries = filterData->boundaries;\n context->save();\n\n \/\/ Clip drawing of filtered image to the minimum required paint rect.\n FilterEffect* lastEffect = filterData->builder->lastEffect();\n context->clipRect(lastEffect->determineAbsolutePaintRect(lastEffect->maxEffectRect()));\n if (filterElement->hasAttribute(SVGNames::filterResAttr)) {\n \/\/ Get boundaries in device coords.\n \/\/ FIXME: See crbug.com\/382491. Is the use of getCTM OK here, given it does not include device\n \/\/ zoom or High DPI adjustments?\n FloatSize size = context->getCTM().mapSize(boundaries.size());\n \/\/ Compute the scale amount required so that the resulting offscreen is exactly filterResX by filterResY pixels.\n float filterResScaleX = filterElement->filterResX()->currentValue()->value() \/ size.width();\n float filterResScaleY = filterElement->filterResY()->currentValue()->value() \/ size.height();\n \/\/ Scale the CTM so the primitive is drawn to filterRes.\n context->scale(filterResScaleX, filterResScaleY);\n \/\/ Create a resize filter with the inverse scale.\n AffineTransform resizeMatrix;\n resizeMatrix.scale(1 \/ filterResScaleX, 1 \/ filterResScaleY);\n imageFilter = builder.buildTransform(resizeMatrix, imageFilter.get());\n }\n \/\/ If the CTM contains rotation or shearing, apply the filter to\n \/\/ the unsheared\/unrotated matrix, and do the shearing\/rotation\n \/\/ as a final pass.\n AffineTransform ctm = context->getCTM();\n if (ctm.b() || ctm.c()) {\n AffineTransform scaleAndTranslate;\n scaleAndTranslate.translate(ctm.e(), ctm.f());\n scaleAndTranslate.scale(ctm.xScale(), ctm.yScale());\n ASSERT(scaleAndTranslate.isInvertible());\n AffineTransform shearAndRotate = scaleAndTranslate.inverse();\n shearAndRotate.multiply(ctm);\n context->setCTM(scaleAndTranslate);\n imageFilter = builder.buildTransform(shearAndRotate, imageFilter.get());\n }\n context->beginLayer(1, CompositeSourceOver, &boundaries, ColorFilterNone, imageFilter.get());\n context->endLayer();\n context->restore();\n}\n\nbool RenderSVGResourceFilter::prepareEffect(RenderObject* object, GraphicsContext*& context)\n{\n ASSERT(object);\n ASSERT(context);\n\n clearInvalidationMask();\n\n if (m_filter.contains(object)) {\n FilterData* filterData = m_filter.get(object);\n if (filterData->state == FilterData::PaintingSource)\n filterData->state = FilterData::CycleDetected;\n return false; \/\/ Already built, or we're in a cycle. Regardless, just do nothing more now.\n }\n\n OwnPtrWillBeRawPtr<FilterData> filterData = FilterData::create();\n FloatRect targetBoundingBox = object->objectBoundingBox();\n\n SVGFilterElement* filterElement = toSVGFilterElement(element());\n filterData->boundaries = SVGLengthContext::resolveRectangle<SVGFilterElement>(filterElement, filterElement->filterUnits()->currentValue()->enumValue(), targetBoundingBox);\n if (filterData->boundaries.isEmpty())\n return false;\n\n \/\/ Create the SVGFilter object.\n FloatRect drawingRegion = object->strokeBoundingBox();\n drawingRegion.intersect(filterData->boundaries);\n bool primitiveBoundingBoxMode = filterElement->primitiveUnits()->currentValue()->enumValue() == SVGUnitTypes::SVG_UNIT_TYPE_OBJECTBOUNDINGBOX;\n filterData->filter = SVGFilter::create(enclosingIntRect(drawingRegion), targetBoundingBox, filterData->boundaries, primitiveBoundingBoxMode);\n\n \/\/ Create all relevant filter primitives.\n filterData->builder = buildPrimitives(filterData->filter.get());\n if (!filterData->builder)\n return false;\n\n FilterEffect* lastEffect = filterData->builder->lastEffect();\n if (!lastEffect)\n return false;\n\n lastEffect->determineFilterPrimitiveSubregion(ClipToFilterRegion);\n\n FilterData* data = filterData.get();\n m_filter.set(object, filterData.release());\n beginDeferredFilter(context, data);\n return true;\n}\n\nvoid RenderSVGResourceFilter::finishEffect(RenderObject* object, GraphicsContext*& context)\n{\n ASSERT(object);\n ASSERT(context);\n\n FilterData* filterData = m_filter.get(object);\n if (!filterData)\n return;\n\n switch (filterData->state) {\n case FilterData::CycleDetected:\n \/\/ applyResource detected a cycle. This can occur due to FeImage\n \/\/ referencing a source that makes use of the FEImage itself. This is\n \/\/ the first place we've hit the cycle, so set the state back to\n \/\/ PaintingSource so the return stack will continue correctly.\n filterData->state = FilterData::PaintingSource;\n return;\n\n case FilterData::PaintingSource:\n endDeferredFilter(context, filterData);\n break;\n\n case FilterData::Built: { } \/\/ Empty\n }\n\n drawDeferredFilter(context, filterData, toSVGFilterElement(element()));\n filterData->state = FilterData::Built;\n}\n\nFloatRect RenderSVGResourceFilter::resourceBoundingBox(const RenderObject* object)\n{\n if (SVGFilterElement* element = toSVGFilterElement(this->element()))\n return SVGLengthContext::resolveRectangle<SVGFilterElement>(element, element->filterUnits()->currentValue()->enumValue(), object->objectBoundingBox());\n\n return FloatRect();\n}\n\nvoid RenderSVGResourceFilter::primitiveAttributeChanged(RenderObject* object, const QualifiedName& attribute)\n{\n FilterMap::iterator it = m_filter.begin();\n FilterMap::iterator end = m_filter.end();\n SVGFilterPrimitiveStandardAttributes* primitve = static_cast<SVGFilterPrimitiveStandardAttributes*>(object->node());\n\n for (; it != end; ++it) {\n FilterData* filterData = it->value.get();\n if (filterData->state != FilterData::Built)\n continue;\n\n SVGFilterBuilder* builder = filterData->builder.get();\n FilterEffect* effect = builder->effectByRenderer(object);\n if (!effect)\n continue;\n \/\/ Since all effects shares the same attribute value, all\n \/\/ or none of them will be changed.\n if (!primitve->setFilterEffectAttribute(effect, attribute))\n return;\n builder->clearResultsRecursive(effect);\n\n \/\/ Issue paint invalidations for the image on the screen.\n markClientForInvalidation(it->key, PaintInvalidation);\n }\n markAllClientLayersForInvalidation();\n}\n\n}\n<commit_msg>[S. P.] Disable transform matrix-dependent code for SVG filters.<commit_after>\/*\n * Copyright (C) 2004, 2005, 2006, 2007 Nikolas Zimmermann <zimmermann@kde.org>\n * Copyright (C) 2004, 2005 Rob Buis <buis@kde.org>\n * Copyright (C) 2005 Eric Seidel <eric@webkit.org>\n * Copyright (C) 2009 Dirk Schulze <krit@webkit.org>\n * Copyright (C) Research In Motion Limited 2010. All rights reserved.\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Library General Public\n * License as published by the Free Software Foundation; either\n * version 2 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Library General Public License for more details.\n *\n * You should have received a copy of the GNU Library General Public License\n * along with this library; see the file COPYING.LIB. If not, write to\n * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,\n * Boston, MA 02110-1301, USA.\n *\/\n\n#include \"config.h\"\n#include \"core\/rendering\/svg\/RenderSVGResourceFilter.h\"\n\n#include \"core\/dom\/ElementTraversal.h\"\n#include \"core\/svg\/SVGFilterPrimitiveStandardAttributes.h\"\n#include \"platform\/graphics\/GraphicsContext.h\"\n#include \"platform\/graphics\/filters\/SkiaImageFilterBuilder.h\"\n#include \"platform\/graphics\/filters\/SourceAlpha.h\"\n#include \"platform\/graphics\/filters\/SourceGraphic.h\"\n#include \"third_party\/skia\/include\/core\/SkPicture.h\"\n\nnamespace blink {\n\nvoid FilterData::trace(Visitor* visitor)\n{\n#if ENABLE(OILPAN)\n visitor->trace(filter);\n visitor->trace(builder);\n#endif\n}\n\nRenderSVGResourceFilter::RenderSVGResourceFilter(SVGFilterElement* node)\n : RenderSVGResourceContainer(node)\n{\n}\n\nRenderSVGResourceFilter::~RenderSVGResourceFilter()\n{\n}\n\nvoid RenderSVGResourceFilter::trace(Visitor* visitor)\n{\n#if ENABLE(OILPAN)\n visitor->trace(m_filter);\n#endif\n RenderSVGResourceContainer::trace(visitor);\n}\n\nvoid RenderSVGResourceFilter::destroy()\n{\n m_filter.clear();\n RenderSVGResourceContainer::destroy();\n}\n\nbool RenderSVGResourceFilter::isChildAllowed(RenderObject* child, RenderStyle*) const\n{\n return child->isSVGResourceFilterPrimitive();\n}\n\nvoid RenderSVGResourceFilter::removeAllClientsFromCache(bool markForInvalidation)\n{\n m_filter.clear();\n markAllClientsForInvalidation(markForInvalidation ? LayoutAndBoundariesInvalidation : ParentOnlyInvalidation);\n}\n\nvoid RenderSVGResourceFilter::removeClientFromCache(RenderObject* client, bool markForInvalidation)\n{\n ASSERT(client);\n\n m_filter.remove(client);\n\n markClientForInvalidation(client, markForInvalidation ? BoundariesInvalidation : ParentOnlyInvalidation);\n}\n\nPassRefPtrWillBeRawPtr<SVGFilterBuilder> RenderSVGResourceFilter::buildPrimitives(SVGFilter* filter)\n{\n SVGFilterElement* filterElement = toSVGFilterElement(element());\n FloatRect targetBoundingBox = filter->targetBoundingBox();\n\n \/\/ Add effects to the builder\n RefPtrWillBeRawPtr<SVGFilterBuilder> builder = SVGFilterBuilder::create(SourceGraphic::create(filter), SourceAlpha::create(filter));\n for (SVGElement* element = Traversal<SVGElement>::firstChild(*filterElement); element; element = Traversal<SVGElement>::nextSibling(*element)) {\n if (!element->isFilterEffect() || !element->renderer())\n continue;\n\n SVGFilterPrimitiveStandardAttributes* effectElement = static_cast<SVGFilterPrimitiveStandardAttributes*>(element);\n RefPtrWillBeRawPtr<FilterEffect> effect = effectElement->build(builder.get(), filter);\n if (!effect) {\n builder->clearEffects();\n return nullptr;\n }\n builder->appendEffectToEffectReferences(effect, effectElement->renderer());\n effectElement->setStandardAttributes(effect.get());\n effect->setEffectBoundaries(SVGLengthContext::resolveRectangle<SVGFilterPrimitiveStandardAttributes>(effectElement, filterElement->primitiveUnits()->currentValue()->enumValue(), targetBoundingBox));\n effect->setOperatingColorSpace(\n effectElement->renderer()->style()->svgStyle().colorInterpolationFilters() == CI_LINEARRGB ? ColorSpaceLinearRGB : ColorSpaceDeviceRGB);\n builder->add(AtomicString(effectElement->result()->currentValue()->value()), effect);\n }\n return builder.release();\n}\n\nstatic void beginDeferredFilter(GraphicsContext* context, FilterData* filterData)\n{\n context->beginRecording(filterData->boundaries);\n}\n\nstatic void endDeferredFilter(GraphicsContext* context, FilterData* filterData)\n{\n \/\/ FIXME: maybe filterData should just hold onto SourceGraphic after creation?\n SourceGraphic* sourceGraphic = static_cast<SourceGraphic*>(filterData->builder->getEffectById(SourceGraphic::effectName()));\n ASSERT(sourceGraphic);\n sourceGraphic->setPicture(context->endRecording());\n}\n\nstatic void drawDeferredFilter(GraphicsContext* context, FilterData* filterData, SVGFilterElement* filterElement)\n{\n SkiaImageFilterBuilder builder(context);\n SourceGraphic* sourceGraphic = static_cast<SourceGraphic*>(filterData->builder->getEffectById(SourceGraphic::effectName()));\n ASSERT(sourceGraphic);\n builder.setSourceGraphic(sourceGraphic);\n RefPtr<ImageFilter> imageFilter = builder.build(filterData->builder->lastEffect(), ColorSpaceDeviceRGB);\n FloatRect boundaries = filterData->boundaries;\n context->save();\n\n \/\/ Clip drawing of filtered image to the minimum required paint rect.\n FilterEffect* lastEffect = filterData->builder->lastEffect();\n context->clipRect(lastEffect->determineAbsolutePaintRect(lastEffect->maxEffectRect()));\n if (filterElement->hasAttribute(SVGNames::filterResAttr)) {\n \/\/ Get boundaries in device coords.\n \/\/ FIXME: See crbug.com\/382491. Is the use of getCTM OK here, given it does not include device\n \/\/ zoom or High DPI adjustments?\n FloatSize size = context->getCTM().mapSize(boundaries.size());\n \/\/ Compute the scale amount required so that the resulting offscreen is exactly filterResX by filterResY pixels.\n float filterResScaleX = filterElement->filterResX()->currentValue()->value() \/ size.width();\n float filterResScaleY = filterElement->filterResY()->currentValue()->value() \/ size.height();\n \/\/ Scale the CTM so the primitive is drawn to filterRes.\n context->scale(filterResScaleX, filterResScaleY);\n \/\/ Create a resize filter with the inverse scale.\n AffineTransform resizeMatrix;\n resizeMatrix.scale(1 \/ filterResScaleX, 1 \/ filterResScaleY);\n imageFilter = builder.buildTransform(resizeMatrix, imageFilter.get());\n }\n\n \/\/ See crbug.com\/382491.\n if (!RuntimeEnabledFeatures::slimmingPaintEnabled()) {\n \/\/ If the CTM contains rotation or shearing, apply the filter to\n \/\/ the unsheared\/unrotated matrix, and do the shearing\/rotation\n \/\/ as a final pass.\n AffineTransform ctm = context->getCTM();\n if (ctm.b() || ctm.c()) {\n AffineTransform scaleAndTranslate;\n scaleAndTranslate.translate(ctm.e(), ctm.f());\n scaleAndTranslate.scale(ctm.xScale(), ctm.yScale());\n ASSERT(scaleAndTranslate.isInvertible());\n AffineTransform shearAndRotate = scaleAndTranslate.inverse();\n shearAndRotate.multiply(ctm);\n context->setCTM(scaleAndTranslate);\n imageFilter = builder.buildTransform(shearAndRotate, imageFilter.get());\n }\n }\n context->beginLayer(1, CompositeSourceOver, &boundaries, ColorFilterNone, imageFilter.get());\n context->endLayer();\n context->restore();\n}\n\nbool RenderSVGResourceFilter::prepareEffect(RenderObject* object, GraphicsContext*& context)\n{\n ASSERT(object);\n ASSERT(context);\n\n clearInvalidationMask();\n\n if (m_filter.contains(object)) {\n FilterData* filterData = m_filter.get(object);\n if (filterData->state == FilterData::PaintingSource)\n filterData->state = FilterData::CycleDetected;\n return false; \/\/ Already built, or we're in a cycle. Regardless, just do nothing more now.\n }\n\n OwnPtrWillBeRawPtr<FilterData> filterData = FilterData::create();\n FloatRect targetBoundingBox = object->objectBoundingBox();\n\n SVGFilterElement* filterElement = toSVGFilterElement(element());\n filterData->boundaries = SVGLengthContext::resolveRectangle<SVGFilterElement>(filterElement, filterElement->filterUnits()->currentValue()->enumValue(), targetBoundingBox);\n if (filterData->boundaries.isEmpty())\n return false;\n\n \/\/ Create the SVGFilter object.\n FloatRect drawingRegion = object->strokeBoundingBox();\n drawingRegion.intersect(filterData->boundaries);\n bool primitiveBoundingBoxMode = filterElement->primitiveUnits()->currentValue()->enumValue() == SVGUnitTypes::SVG_UNIT_TYPE_OBJECTBOUNDINGBOX;\n filterData->filter = SVGFilter::create(enclosingIntRect(drawingRegion), targetBoundingBox, filterData->boundaries, primitiveBoundingBoxMode);\n\n \/\/ Create all relevant filter primitives.\n filterData->builder = buildPrimitives(filterData->filter.get());\n if (!filterData->builder)\n return false;\n\n FilterEffect* lastEffect = filterData->builder->lastEffect();\n if (!lastEffect)\n return false;\n\n lastEffect->determineFilterPrimitiveSubregion(ClipToFilterRegion);\n\n FilterData* data = filterData.get();\n m_filter.set(object, filterData.release());\n beginDeferredFilter(context, data);\n return true;\n}\n\nvoid RenderSVGResourceFilter::finishEffect(RenderObject* object, GraphicsContext*& context)\n{\n ASSERT(object);\n ASSERT(context);\n\n FilterData* filterData = m_filter.get(object);\n if (!filterData)\n return;\n\n switch (filterData->state) {\n case FilterData::CycleDetected:\n \/\/ applyResource detected a cycle. This can occur due to FeImage\n \/\/ referencing a source that makes use of the FEImage itself. This is\n \/\/ the first place we've hit the cycle, so set the state back to\n \/\/ PaintingSource so the return stack will continue correctly.\n filterData->state = FilterData::PaintingSource;\n return;\n\n case FilterData::PaintingSource:\n endDeferredFilter(context, filterData);\n break;\n\n case FilterData::Built: { } \/\/ Empty\n }\n\n drawDeferredFilter(context, filterData, toSVGFilterElement(element()));\n filterData->state = FilterData::Built;\n}\n\nFloatRect RenderSVGResourceFilter::resourceBoundingBox(const RenderObject* object)\n{\n if (SVGFilterElement* element = toSVGFilterElement(this->element()))\n return SVGLengthContext::resolveRectangle<SVGFilterElement>(element, element->filterUnits()->currentValue()->enumValue(), object->objectBoundingBox());\n\n return FloatRect();\n}\n\nvoid RenderSVGResourceFilter::primitiveAttributeChanged(RenderObject* object, const QualifiedName& attribute)\n{\n FilterMap::iterator it = m_filter.begin();\n FilterMap::iterator end = m_filter.end();\n SVGFilterPrimitiveStandardAttributes* primitve = static_cast<SVGFilterPrimitiveStandardAttributes*>(object->node());\n\n for (; it != end; ++it) {\n FilterData* filterData = it->value.get();\n if (filterData->state != FilterData::Built)\n continue;\n\n SVGFilterBuilder* builder = filterData->builder.get();\n FilterEffect* effect = builder->effectByRenderer(object);\n if (!effect)\n continue;\n \/\/ Since all effects shares the same attribute value, all\n \/\/ or none of them will be changed.\n if (!primitve->setFilterEffectAttribute(effect, attribute))\n return;\n builder->clearResultsRecursive(effect);\n\n \/\/ Issue paint invalidations for the image on the screen.\n markClientForInvalidation(it->key, PaintInvalidation);\n }\n markAllClientLayersForInvalidation();\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * jcom.snapshot\n * External for Jamoma: capture, recall, transform, and manipulate global snapshots\n * By Timothy Place, Copyright 2009\n *\n * License: This code is licensed under the terms of the GNU LGPL\n * http:\/\/www.gnu.org\/licenses\/lgpl.html\n *\/\n\n#include \"Jamoma.h\"\n\nclass SnapshotParameterValue {\npublic:\n TTFloat64 value;\n ObjectPtr parameter;\n\n SnapshotParameterValue(TTFloat64& f, ObjectPtr o):\n value(f),\n parameter(o)\n {;}\n\n\n};\n\n\/\/ A vector of 64-bit floats used to represent a given snapshot\ntypedef vector<SnapshotParameterValue> Snapshot;\ntypedef Snapshot::iterator SnapshotIter;\ntypedef Snapshot* SnapshotPtr;\n\n\/\/ A vector (or collection) of snapshots\ntypedef vector<SnapshotPtr> SnapshotCollection;\ntypedef SnapshotCollection::iterator SnapshotCollectionIter;\ntypedef SnapshotCollection* SnapshotCollectionPtr;\n\n\/\/ Data Structure for this object\ntypedef struct {\n Object ob;\n TTTreePtr tree;\n SnapshotCollectionPtr snapshots;\n SymbolPtr excludes[128]; \/\/ list of parameter and container names to exclude from snapshots\n TTInt32 excludeSize;\n} TTModSnapshot;\ntypedef TTModSnapshot* TTModSnapshotPtr;\n\n\n\/\/ Prototypes\nTTPtr TTModSnapshotNew (SymbolPtr name, AtomCount argc, AtomPtr argv);\nvoid TTModSnapshotFree (TTModSnapshotPtr self);\nMaxErr TTModSnapshotNotify (TTModSnapshotPtr self, SymbolPtr s, SymbolPtr msg, void *sender, void *data);\nvoid TTModSnapshotAssist (TTModSnapshotPtr self, void *b, long m, long a, char *s);\nvoid TTModSnapshotDump (TTModSnapshotPtr self);\nvoid TTModSnapshotStore (TTModSnapshotPtr self, SymbolPtr s, AtomCount argc, AtomPtr argv);\nvoid TTModSnapshotRecall (TTModSnapshotPtr self, SymbolPtr s, AtomCount argc, AtomPtr argv);\n\n\n\/\/ Shared\nstatic ClassPtr sMaxClass;\n\n\n\/\/ Class Definition\nint JAMOMA_EXPORT_MAXOBJ main(void)\n{\n ClassPtr c = class_new(\"jcom.snapshot\",\n (method)TTModSnapshotNew,\n (method)TTModSnapshotFree,\n sizeof(TTModSnapshot),\n NULL, A_GIMME, 0);\n\n jamoma_init();\n common_symbols_init();\n\n class_addmethod(c, (method)TTModSnapshotNotify, \"notify\", A_CANT, 0);\n class_addmethod(c, (method)TTModSnapshotAssist, \"assist\", A_CANT, 0);\n class_addmethod(c, (method)TTModSnapshotDump, \"dump\", 0);\n class_addmethod(c, (method)TTModSnapshotStore, \"store\", A_GIMME, 0);\n class_addmethod(c, (method)TTModSnapshotRecall, \"recall\", A_GIMME, 0);\n\n CLASS_ATTR_SYM_VARSIZE(c, \"excludes\", 0, TTModSnapshot, excludes, excludeSize, 128);\n\n class_register(_sym_box, c);\n sMaxClass = c;\n return 0;\n}\n\n\n#if 0\n#pragma mark -\n#pragma mark Life Cycle\n#endif 0\n\nTTPtr TTModSnapshotNew(SymbolPtr name, AtomCount argc, AtomPtr argv)\n{\n TTModSnapshotPtr self = (TTModSnapshotPtr)object_alloc(sMaxClass);\n\n if (self) {\n TTUInt32 i=0;\n\n self->snapshots = new SnapshotCollection;\n self->tree = jamoma_tree_init();\n\n self->excludes[i++] = gensym(\"ch\");\n self->excludes[i++] = gensym(\"view\");\n self->excludes[i++] = gensym(\"documentation\");\n self->excludeSize = i;\n\n attr_args_process(self, argc, argv);\n }\n return self;\n}\n\nvoid TTModSnapshotFree(TTModSnapshotPtr self)\n{\n \/\/ TODO: leaking memory! -- free of the actuall snapshots held by the pointers!\n delete self->snapshots;\n}\n\n\n#if 0\n#pragma mark -\n#pragma mark Methods\n#endif 0\n\nMaxErr TTModSnapshotNotify(TTModSnapshotPtr self, SymbolPtr s, SymbolPtr msg, TTPtr sender, TTPtr data)\n{\n object_post(SELF, \"notification : %s\", msg->s_name);\n return MAX_ERR_NONE;\n}\n\n\nvoid TTModSnapshotAssist(TTModSnapshotPtr self, void* b, long msg, long arg, char* dst)\n{\n if (msg == ASSIST_INLET) { \/\/ inlet\n if (arg == 0)\n strcpy(dst, \"inlet\");\n }\n else { \/\/ outlet\n if (arg == 0)\n strcpy(dst, \"outlet\");\n }\n}\n\n\nvoid TTModSnapshotDump(TTModSnapshotPtr self)\n{\n jamoma_tree_dump(); \/\/ dump all the address of the tree in the Max window\n}\n\n\nvoid TTModSnapshotStore(TTModSnapshotPtr self, SymbolPtr s, AtomCount argc, AtomPtr argv)\n{\n TTNodePtr rootNode = self->tree->getRoot();\n TTValue moduleNodes;\n TTUInt32 numModules;\n TTListPtr returnedChildren = NULL;\n TTErr err;\n SnapshotPtr snapshot = NULL;\n TTUInt32 snapshotIndex = 0;\n\n \/\/ snapshot numbers are 1-based for the outside world\n if (argc && argv)\n snapshotIndex = atom_getlong(argv) - 1;\n if (snapshotIndex < 0)\n snapshotIndex = 0;\n\n if (snapshotIndex >= self->snapshots->size()) {\n if (snapshotIndex >= self->snapshots->capacity()) {\n self->snapshots->reserve(snapshotIndex+1);\n }\n self->snapshots->resize(snapshotIndex+1);\n }\n else {\n snapshot = self->snapshots->at(snapshotIndex);\n delete snapshot;\n snapshot = NULL;\n }\n snapshot = new Snapshot;\n\n\n err = rootNode->getChildren(TT(\"*\"), TT(\"*\"), &returnedChildren);\n\n returnedChildren->assignToValue(moduleNodes);\n numModules = moduleNodes.getSize();\n for (TTUInt32 i=0; i<numModules; i++) {\n TTNodePtr module = NULL;\n TTSymbolPtr type;\n\n moduleNodes.get(i, (TTPtr*)(&module));\n if (module) {\n type = module->getType();\n if (type == TT(\"hub\")) {\n TTValue parameterNodes;\n TTUInt32 numParameters;\n\n post(\" Module: %s\", module->getName()->getCString());\n err = module->getChildren(TT(\"*\"), TT(\"*\"), &returnedChildren);\n returnedChildren->assignToValue(parameterNodes);\n numParameters = parameterNodes.getSize();\n for (TTUInt32 i=0; i<numParameters; i++) {\n TTNodePtr parameter = NULL;\n TTSymbolPtr childType;\n\n parameterNodes.get(i, (TTPtr*)(¶meter));\n if (parameter) {\n bool exclude = false;\n \/\/ first check for the name in the excludes list\n for (TTInt32 e=0; e < self->excludeSize; e++) {\n TTSymbolPtr s1 = parameter->getName();\n TTSymbolPtr s2 = TT(self->excludes[e]->s_name);\n\n if (s1 == s2) {\n exclude = true;\n break;\n }\n }\n if (exclude)\n continue;\n\n \/\/ then make sure it is actually a parameter\n childType = parameter->getType();\n if (childType == TT(\"subscribe_parameter\")) { \/\/ FIXME: this name sucks for the type.\n ObjectPtr maxObject = (ObjectPtr)parameter->getObject();\n SymbolPtr maxType = object_attr_getsym(maxObject, SymbolGen(\"type\"));\n\n \/\/ we're ignoring non-int, non-float params for the time being\n if (maxType == SymbolGen(\"decimal\") || maxType == SymbolGen(\"integer\")) {\n TTFloat64 value = object_attr_getfloat(maxObject, SymbolGen(\"value\"));\n SnapshotParameterValue spv(value, maxObject);\n\n snapshot->push_back(spv);\n post(\" parameter: %s -- value: %lf\", parameter->getName()->getCString(), value);\n }\n }\n \/\/ FIXME: the code below sucks big-time -- need to redo as a recursive function\n else if (childType == TT(\"container\")) {\n\t\t\t\t\t\t\tTTValue containerNodes;\n\t\t\t\t\t\t\tTTUInt32 numParameters2;\n\t\t\t\t\t\t\tTTListPtr\tcontainerChildren = NULL;\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tpost(\" Container: %s\", parameter->getName()->getCString());\n\t\t\t\t\t\t\terr = parameter->getChildren(TT(\"*\"), TT(\"*\"), &containerChildren);\n\t\t\t\t\t\t\tcontainerChildren->assignToValue(containerNodes);\n\t\t\t\t\t\t\tnumParameters2 = containerNodes.getSize();\n\t\t\t\t\t\t\tfor (TTUInt32 i=0; i<numParameters2; i++) {\n\t\t\t\t\t\t\t\tTTNodePtr parameter2 = NULL;\n\t\t\t\t\t\t\t\tTTSymbolPtr childType2;\n\n\t\t\t\t\t\t\t\tcontainerNodes.get(i, (TTPtr*)(¶meter2));\n\t\t\t\t\t\t\t\tif (parameter2) {\n\t\t\t\t\t\t\t\t\tbool exclude = false;\n\t\t\t\t\t\t\t\t\t\/\/ first check for the name in the excludes list\n\t\t\t\t\t\t\t\t\tfor (TTInt32 e=0; e < self->excludeSize; e++) {\n\t\t\t\t\t\t\t\t\t\tTTSymbolPtr s1 = parameter2->getName();\n\t\t\t\t\t\t\t\t\t\tTTSymbolPtr s2 = TT(self->excludes[e]->s_name);\n\n\t\t\t\t\t\t\t\t\t\tif (s1 == s2) {\n\t\t\t\t\t\t\t\t\t\t\texclude = true;\n\t\t\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tif (exclude)\n\t\t\t\t\t\t\t\t\t\tcontinue;\n\n\t\t\t\t\t\t\t\t\t\/\/ then make sure it is actually a parameter\n\t\t\t\t\t\t\t\t\tchildType2 = parameter2->getType();\n\t\t\t\t\t\t\t\t\tif (childType2 == TT(\"subscribe_parameter\")) { \/\/ FIXME: this name sucks for the type.\n\t\t\t\t\t\t\t\t\t\tObjectPtr maxObject = (ObjectPtr)parameter2->getObject();\n\t\t\t\t\t\t\t\t\t\tSymbolPtr maxType = object_attr_getsym(maxObject, SymbolGen(\"type\"));\n\n\t\t\t\t\t\t\t\t\t\t\/\/ we're ignoring non-int, non-float params for the time being\n\t\t\t\t\t\t\t\t\t\tif (maxType == SymbolGen(\"decimal\") || maxType == SymbolGen(\"integer\")) {\n\t\t\t\t\t\t\t\t\t\t\tTTFloat64 value = object_attr_getfloat(maxObject, SymbolGen(\"value\"));\n\t\t\t\t\t\t\t\t\t\t\tSnapshotParameterValue spv(value, maxObject);\n\n\t\t\t\t\t\t\t\t\t\t\tsnapshot->push_back(spv);\n\t\t\t\t\t\t\t\t\t\t\tpost(\" parameter: %s -- value: %lf\", parameter2->getName()->getCString(), value);\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n }\n }\n }\n }\n }\n }\n }\n (*self->snapshots)[snapshotIndex] = snapshot;\n}\n\n\nvoid TTModSnapshotRecallOne(const SnapshotParameterValue& spv)\n{\n object_method(spv.parameter, _sym_float, spv.value);\n}\n\n\nvoid TTModSnapshotRecall(TTModSnapshotPtr self, SymbolPtr s, AtomCount argc, AtomPtr argv)\n{\n if (!argc || !argv)\n return;\n\n \/\/ straight recall\n if (argc == 1) {\n SnapshotPtr snapshot;\n TTUInt32 snapshotIndex = atom_getlong(argv) - 1;\n\n if (snapshotIndex < 0)\n snapshotIndex = 0;\n\n if (snapshotIndex >= self->snapshots->size()) {\n object_error(SELF, \"preset recall out of range\");\n return;\n }\n snapshot = (*self->snapshots)[snapshotIndex];\n for_each((*snapshot).begin(), (*snapshot).end(), TTModSnapshotRecallOne);\n }\n\n \/\/ interpolate between any two\n else if (argc == 3) {\n SnapshotPtr snapshotA;\n SnapshotPtr snapshotB;\n TTUInt32 snapshotIndexA = atom_getlong(argv+0) - 1;\n TTUInt32 snapshotIndexB = atom_getlong(argv+1) - 1;\n TTUInt32 snapshotSizeA = atom_getlong(argv+0);\n TTUInt32 snapshotSizeB = atom_getlong(argv+1);\n TTFloat32 position = atom_getfloat(argv+2);\n\n if (snapshotIndexA < 0)\n snapshotIndexA = 0;\n if (snapshotIndexB < 0)\n snapshotIndexB = 0;\n\n if (snapshotIndexA >= self->snapshots->size() ||\n snapshotIndexB >= self->snapshots->size())\n {\n object_error(SELF, \"preset recall out of range\");\n return;\n }\n\n snapshotA = (*self->snapshots)[snapshotIndexA];\n snapshotB = (*self->snapshots)[snapshotIndexB];\n snapshotSizeA = snapshotA->size();\n snapshotSizeB = snapshotB->size();\n\n if (snapshotSizeA != snapshotSizeB) {\n object_error(SELF, \"preset recall -- cannot interpolate between snapshots of unequal size\");\n return;\n }\n\n for (TTUInt32 i=0; i<snapshotSizeA; i++) {\n if ( (*snapshotA)[i].parameter == (*snapshotB)[i].parameter ) {\n TTFloat32 f = ((*snapshotA)[i].value * (1.0 - position)) + ((*snapshotB)[i].value * (position));\n object_method((*snapshotA)[i].parameter, _sym_float, f);\n }\n }\n }\n\n \/\/ wieghted interpolation\n else if (argc > 3) {\n TTUInt32 size;\n TTUInt32 ac = argc;\n bool boundsCheckFailed = false;\n SnapshotPtr snapshot;\n Snapshot interpolatedResult;\n TTFloat32 weight;\n\n \/\/ check bounds\n if (ac > self->snapshots->size()) {\n object_error(SELF, \"recall can not interpolate -- not enough snapshots for provided weights\");\n return;\n }\n\n snapshot = (*self->snapshots)[0];\n if (!snapshot) {\n object_error(SELF, \"recall can not interpolate -- bogus initial snapshot\");\n return;\n }\n\n size = snapshot->size();\n for (int i=1; i<argc; i++) {\n if (!(*self->snapshots)[i] || (*self->snapshots)[i]->size() != size) {\n boundsCheckFailed = true;\n break;\n }\n }\n if (boundsCheckFailed) {\n object_error(SELF, \"recall can not interpolate -- snapshots are of unequal size, or there is a missing snapshot in the sequence\");\n return;\n }\n\n interpolatedResult.reserve(size);\n for (int i=0; i<argc; i++) {\n snapshot = (*self->snapshots)[i];\n weight = atom_getfloat(argv+i);\n if (i==0) {\n interpolatedResult.insert(interpolatedResult.begin(), snapshot->begin(), snapshot->end());\n \/\/ TODO: There must be a better way than this nested loop using some variant for for_each() or something...\n for (TTUInt32 j=0; j<size; j++) {\n interpolatedResult[j].value *= weight;\n }\n }\n else {\n \/\/ TODO: There must be a better way than this nested loop using some variant for for_each() or something...\n for (TTUInt32 j=0; j<size; j++) {\n interpolatedResult[j].value += ((*snapshot)[j].value * weight);\n }\n }\n }\n for_each(interpolatedResult.begin(), interpolatedResult.end(), TTModSnapshotRecallOne);\n }\n}\n\n<commit_msg>jcom.snapshot: fix for crash when a preset is recalled that was never actually stored.<commit_after>\/*\n * jcom.snapshot\n * External for Jamoma: capture, recall, transform, and manipulate global snapshots\n * By Timothy Place, Copyright 2009\n *\n * License: This code is licensed under the terms of the GNU LGPL\n * http:\/\/www.gnu.org\/licenses\/lgpl.html\n *\/\n\n#include \"Jamoma.h\"\n\nclass SnapshotParameterValue {\npublic:\n TTFloat64 value;\n ObjectPtr parameter;\n\n SnapshotParameterValue(TTFloat64& f, ObjectPtr o):\n value(f),\n parameter(o)\n {;}\n\n\n};\n\n\/\/ A vector of 64-bit floats used to represent a given snapshot\ntypedef vector<SnapshotParameterValue> Snapshot;\ntypedef Snapshot::iterator SnapshotIter;\ntypedef Snapshot* SnapshotPtr;\n\n\/\/ A vector (or collection) of snapshots\ntypedef vector<SnapshotPtr> SnapshotCollection;\ntypedef SnapshotCollection::iterator SnapshotCollectionIter;\ntypedef SnapshotCollection* SnapshotCollectionPtr;\n\n\/\/ Data Structure for this object\ntypedef struct {\n Object ob;\n TTTreePtr tree;\n SnapshotCollectionPtr snapshots;\n SymbolPtr excludes[128]; \/\/ list of parameter and container names to exclude from snapshots\n TTInt32 excludeSize;\n} TTModSnapshot;\ntypedef TTModSnapshot* TTModSnapshotPtr;\n\n\n\/\/ Prototypes\nTTPtr TTModSnapshotNew (SymbolPtr name, AtomCount argc, AtomPtr argv);\nvoid TTModSnapshotFree (TTModSnapshotPtr self);\nMaxErr TTModSnapshotNotify (TTModSnapshotPtr self, SymbolPtr s, SymbolPtr msg, void *sender, void *data);\nvoid TTModSnapshotAssist (TTModSnapshotPtr self, void *b, long m, long a, char *s);\nvoid TTModSnapshotDump (TTModSnapshotPtr self);\nvoid TTModSnapshotStore (TTModSnapshotPtr self, SymbolPtr s, AtomCount argc, AtomPtr argv);\nvoid TTModSnapshotRecall (TTModSnapshotPtr self, SymbolPtr s, AtomCount argc, AtomPtr argv);\n\n\n\/\/ Shared\nstatic ClassPtr sMaxClass;\n\n\n\/\/ Class Definition\nint JAMOMA_EXPORT_MAXOBJ main(void)\n{\n ClassPtr c = class_new(\"jcom.snapshot\",\n (method)TTModSnapshotNew,\n (method)TTModSnapshotFree,\n sizeof(TTModSnapshot),\n NULL, A_GIMME, 0);\n\n jamoma_init();\n common_symbols_init();\n\n class_addmethod(c, (method)TTModSnapshotNotify, \"notify\", A_CANT, 0);\n class_addmethod(c, (method)TTModSnapshotAssist, \"assist\", A_CANT, 0);\n class_addmethod(c, (method)TTModSnapshotDump, \"dump\", 0);\n class_addmethod(c, (method)TTModSnapshotStore, \"store\", A_GIMME, 0);\n class_addmethod(c, (method)TTModSnapshotRecall, \"recall\", A_GIMME, 0);\n\n CLASS_ATTR_SYM_VARSIZE(c, \"excludes\", 0, TTModSnapshot, excludes, excludeSize, 128);\n\n class_register(_sym_box, c);\n sMaxClass = c;\n return 0;\n}\n\n\n#if 0\n#pragma mark -\n#pragma mark Life Cycle\n#endif 0\n\nTTPtr TTModSnapshotNew(SymbolPtr name, AtomCount argc, AtomPtr argv)\n{\n TTModSnapshotPtr self = (TTModSnapshotPtr)object_alloc(sMaxClass);\n\n if (self) {\n TTUInt32 i=0;\n\n self->snapshots = new SnapshotCollection;\n self->tree = jamoma_tree_init();\n\n self->excludes[i++] = gensym(\"ch\");\n self->excludes[i++] = gensym(\"view\");\n self->excludes[i++] = gensym(\"documentation\");\n self->excludeSize = i;\n\n attr_args_process(self, argc, argv);\n }\n return self;\n}\n\nvoid TTModSnapshotFree(TTModSnapshotPtr self)\n{\n \/\/ TODO: leaking memory! -- free of the actuall snapshots held by the pointers!\n delete self->snapshots;\n}\n\n\n#if 0\n#pragma mark -\n#pragma mark Methods\n#endif 0\n\nMaxErr TTModSnapshotNotify(TTModSnapshotPtr self, SymbolPtr s, SymbolPtr msg, TTPtr sender, TTPtr data)\n{\n object_post(SELF, \"notification : %s\", msg->s_name);\n return MAX_ERR_NONE;\n}\n\n\nvoid TTModSnapshotAssist(TTModSnapshotPtr self, void* b, long msg, long arg, char* dst)\n{\n if (msg == ASSIST_INLET) { \/\/ inlet\n if (arg == 0)\n strcpy(dst, \"inlet\");\n }\n else { \/\/ outlet\n if (arg == 0)\n strcpy(dst, \"outlet\");\n }\n}\n\n\nvoid TTModSnapshotDump(TTModSnapshotPtr self)\n{\n jamoma_tree_dump(); \/\/ dump all the address of the tree in the Max window\n}\n\n\nvoid TTModSnapshotStore(TTModSnapshotPtr self, SymbolPtr s, AtomCount argc, AtomPtr argv)\n{\n TTNodePtr rootNode = self->tree->getRoot();\n TTValue moduleNodes;\n TTUInt32 numModules;\n TTListPtr returnedChildren = NULL;\n TTErr err;\n SnapshotPtr snapshot = NULL;\n TTUInt32 snapshotIndex = 0;\n\n \/\/ snapshot numbers are 1-based for the outside world\n if (argc && argv)\n snapshotIndex = atom_getlong(argv) - 1;\n if (snapshotIndex < 0)\n snapshotIndex = 0;\n\n if (snapshotIndex >= self->snapshots->size()) {\n if (snapshotIndex >= self->snapshots->capacity()) {\n self->snapshots->reserve(snapshotIndex+1);\n }\n self->snapshots->resize(snapshotIndex+1);\n }\n else {\n snapshot = self->snapshots->at(snapshotIndex);\n delete snapshot;\n snapshot = NULL;\n }\n snapshot = new Snapshot;\n\n\n err = rootNode->getChildren(TT(\"*\"), TT(\"*\"), &returnedChildren);\n\n returnedChildren->assignToValue(moduleNodes);\n numModules = moduleNodes.getSize();\n for (TTUInt32 i=0; i<numModules; i++) {\n TTNodePtr module = NULL;\n TTSymbolPtr type;\n\n moduleNodes.get(i, (TTPtr*)(&module));\n if (module) {\n type = module->getType();\n if (type == TT(\"hub\")) {\n TTValue parameterNodes;\n TTUInt32 numParameters;\n\n post(\" Module: %s\", module->getName()->getCString());\n err = module->getChildren(TT(\"*\"), TT(\"*\"), &returnedChildren);\n returnedChildren->assignToValue(parameterNodes);\n numParameters = parameterNodes.getSize();\n for (TTUInt32 i=0; i<numParameters; i++) {\n TTNodePtr parameter = NULL;\n TTSymbolPtr childType;\n\n parameterNodes.get(i, (TTPtr*)(¶meter));\n if (parameter) {\n bool exclude = false;\n \/\/ first check for the name in the excludes list\n for (TTInt32 e=0; e < self->excludeSize; e++) {\n TTSymbolPtr s1 = parameter->getName();\n TTSymbolPtr s2 = TT(self->excludes[e]->s_name);\n\n if (s1 == s2) {\n exclude = true;\n break;\n }\n }\n if (exclude)\n continue;\n\n \/\/ then make sure it is actually a parameter\n childType = parameter->getType();\n if (childType == TT(\"subscribe_parameter\")) { \/\/ FIXME: this name sucks for the type.\n ObjectPtr maxObject = (ObjectPtr)parameter->getObject();\n SymbolPtr maxType = object_attr_getsym(maxObject, SymbolGen(\"type\"));\n\n \/\/ we're ignoring non-int, non-float params for the time being\n if (maxType == SymbolGen(\"decimal\") || maxType == SymbolGen(\"integer\")) {\n TTFloat64 value = object_attr_getfloat(maxObject, SymbolGen(\"value\"));\n SnapshotParameterValue spv(value, maxObject);\n\n snapshot->push_back(spv);\n post(\" parameter: %s -- value: %lf\", parameter->getName()->getCString(), value);\n }\n }\n \/\/ FIXME: the code below sucks big-time -- need to redo as a recursive function\n else if (childType == TT(\"container\")) {\n\t\t\t\t\t\t\tTTValue containerNodes;\n\t\t\t\t\t\t\tTTUInt32 numParameters2;\n\t\t\t\t\t\t\tTTListPtr\tcontainerChildren = NULL;\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tpost(\" Container: %s\", parameter->getName()->getCString());\n\t\t\t\t\t\t\terr = parameter->getChildren(TT(\"*\"), TT(\"*\"), &containerChildren);\n\t\t\t\t\t\t\tcontainerChildren->assignToValue(containerNodes);\n\t\t\t\t\t\t\tnumParameters2 = containerNodes.getSize();\n\t\t\t\t\t\t\tfor (TTUInt32 i=0; i<numParameters2; i++) {\n\t\t\t\t\t\t\t\tTTNodePtr parameter2 = NULL;\n\t\t\t\t\t\t\t\tTTSymbolPtr childType2;\n\n\t\t\t\t\t\t\t\tcontainerNodes.get(i, (TTPtr*)(¶meter2));\n\t\t\t\t\t\t\t\tif (parameter2) {\n\t\t\t\t\t\t\t\t\tbool exclude = false;\n\t\t\t\t\t\t\t\t\t\/\/ first check for the name in the excludes list\n\t\t\t\t\t\t\t\t\tfor (TTInt32 e=0; e < self->excludeSize; e++) {\n\t\t\t\t\t\t\t\t\t\tTTSymbolPtr s1 = parameter2->getName();\n\t\t\t\t\t\t\t\t\t\tTTSymbolPtr s2 = TT(self->excludes[e]->s_name);\n\n\t\t\t\t\t\t\t\t\t\tif (s1 == s2) {\n\t\t\t\t\t\t\t\t\t\t\texclude = true;\n\t\t\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tif (exclude)\n\t\t\t\t\t\t\t\t\t\tcontinue;\n\n\t\t\t\t\t\t\t\t\t\/\/ then make sure it is actually a parameter\n\t\t\t\t\t\t\t\t\tchildType2 = parameter2->getType();\n\t\t\t\t\t\t\t\t\tif (childType2 == TT(\"subscribe_parameter\")) { \/\/ FIXME: this name sucks for the type.\n\t\t\t\t\t\t\t\t\t\tObjectPtr maxObject = (ObjectPtr)parameter2->getObject();\n\t\t\t\t\t\t\t\t\t\tSymbolPtr maxType = object_attr_getsym(maxObject, SymbolGen(\"type\"));\n\n\t\t\t\t\t\t\t\t\t\t\/\/ we're ignoring non-int, non-float params for the time being\n\t\t\t\t\t\t\t\t\t\tif (maxType == SymbolGen(\"decimal\") || maxType == SymbolGen(\"integer\")) {\n\t\t\t\t\t\t\t\t\t\t\tTTFloat64 value = object_attr_getfloat(maxObject, SymbolGen(\"value\"));\n\t\t\t\t\t\t\t\t\t\t\tSnapshotParameterValue spv(value, maxObject);\n\n\t\t\t\t\t\t\t\t\t\t\tsnapshot->push_back(spv);\n\t\t\t\t\t\t\t\t\t\t\tpost(\" parameter: %s -- value: %lf\", parameter2->getName()->getCString(), value);\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n }\n }\n }\n }\n }\n }\n }\n (*self->snapshots)[snapshotIndex] = snapshot;\n}\n\n\nvoid TTModSnapshotRecallOne(const SnapshotParameterValue& spv)\n{\n object_method(spv.parameter, _sym_float, spv.value);\n}\n\n\nvoid TTModSnapshotRecall(TTModSnapshotPtr self, SymbolPtr s, AtomCount argc, AtomPtr argv)\n{\n if (!argc || !argv)\n return;\n\n \/\/ straight recall\n if (argc == 1) {\n SnapshotPtr snapshot;\n TTUInt32 snapshotIndex = atom_getlong(argv) - 1;\n\n if (snapshotIndex < 0)\n snapshotIndex = 0;\n\n if (snapshotIndex >= self->snapshots->size()) {\n object_error(SELF, \"preset recall out of range\");\n return;\n }\n snapshot = (*self->snapshots)[snapshotIndex];\n\t\tif (snapshot)\n \tfor_each((*snapshot).begin(), (*snapshot).end(), TTModSnapshotRecallOne);\n\t\telse\n\t\t\tobject_error(SELF, \"invalid preset recall requested\");\n }\n\n \/\/ interpolate between any two\n else if (argc == 3) {\n SnapshotPtr snapshotA;\n SnapshotPtr snapshotB;\n TTUInt32 snapshotIndexA = atom_getlong(argv+0) - 1;\n TTUInt32 snapshotIndexB = atom_getlong(argv+1) - 1;\n TTUInt32 snapshotSizeA = atom_getlong(argv+0);\n TTUInt32 snapshotSizeB = atom_getlong(argv+1);\n TTFloat32 position = atom_getfloat(argv+2);\n\n if (snapshotIndexA < 0)\n snapshotIndexA = 0;\n if (snapshotIndexB < 0)\n snapshotIndexB = 0;\n\n if (snapshotIndexA >= self->snapshots->size() ||\n snapshotIndexB >= self->snapshots->size())\n {\n object_error(SELF, \"preset recall out of range\");\n return;\n }\n\n snapshotA = (*self->snapshots)[snapshotIndexA];\n snapshotB = (*self->snapshots)[snapshotIndexB];\n snapshotSizeA = snapshotA->size();\n snapshotSizeB = snapshotB->size();\n\n if (snapshotSizeA != snapshotSizeB) {\n object_error(SELF, \"preset recall -- cannot interpolate between snapshots of unequal size\");\n return;\n }\n\n for (TTUInt32 i=0; i<snapshotSizeA; i++) {\n if ( (*snapshotA)[i].parameter == (*snapshotB)[i].parameter ) {\n TTFloat32 f = ((*snapshotA)[i].value * (1.0 - position)) + ((*snapshotB)[i].value * (position));\n object_method((*snapshotA)[i].parameter, _sym_float, f);\n }\n }\n }\n\n \/\/ wieghted interpolation\n else if (argc > 3) {\n TTUInt32 size;\n TTUInt32 ac = argc;\n bool boundsCheckFailed = false;\n SnapshotPtr snapshot;\n Snapshot interpolatedResult;\n TTFloat32 weight;\n\n \/\/ check bounds\n if (ac > self->snapshots->size()) {\n object_error(SELF, \"recall can not interpolate -- not enough snapshots for provided weights\");\n return;\n }\n\n snapshot = (*self->snapshots)[0];\n if (!snapshot) {\n object_error(SELF, \"recall can not interpolate -- bogus initial snapshot\");\n return;\n }\n\n size = snapshot->size();\n for (int i=1; i<argc; i++) {\n if (!(*self->snapshots)[i] || (*self->snapshots)[i]->size() != size) {\n boundsCheckFailed = true;\n break;\n }\n }\n if (boundsCheckFailed) {\n object_error(SELF, \"recall can not interpolate -- snapshots are of unequal size, or there is a missing snapshot in the sequence\");\n return;\n }\n\n interpolatedResult.reserve(size);\n for (int i=0; i<argc; i++) {\n snapshot = (*self->snapshots)[i];\n weight = atom_getfloat(argv+i);\n if (i==0) {\n interpolatedResult.insert(interpolatedResult.begin(), snapshot->begin(), snapshot->end());\n \/\/ TODO: There must be a better way than this nested loop using some variant for for_each() or something...\n for (TTUInt32 j=0; j<size; j++) {\n interpolatedResult[j].value *= weight;\n }\n }\n else {\n \/\/ TODO: There must be a better way than this nested loop using some variant for for_each() or something...\n for (TTUInt32 j=0; j<size; j++) {\n interpolatedResult[j].value += ((*snapshot)[j].value * weight);\n }\n }\n }\n for_each(interpolatedResult.begin(), interpolatedResult.end(), TTModSnapshotRecallOne);\n }\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n * caosVM_agent.cpp\n * openc2e\n *\n * Created by Alyssa Milburn on Tue Jun 01 2004.\n * Copyright (c) 2004 Alyssa Milburn. All rights reserved.\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n *\/\n\n#include \"caosVM.h\"\n#include \"openc2e.h\"\n#include \"Agent.h\"\n#include \"AgentRef.h\"\n#include \"World.h\"\n#include <iostream>\nusing std::cerr;\n\n\/**\n ELAS (command) elas (integer)\n %status maybe\n\n Sets the elasticity (in other words, bounciness) of the TARG agent.\n*\/\nvoid caosVM::c_ELAS() {\n\tVM_VERIFY_SIZE(1)\n\tVM_PARAM_INTEGER(elas)\n\n\tvalid_agent(targ);\n\ttarg->elas = elas;\n}\n\n\/***\n ELAS (integer)\n %status maybe\n\n Returns the elasticity of the TARG agent.\n*\/\nvoid caosVM::v_ELAS() {\n\tVM_VERIFY_SIZE(0)\n\n\tvalid_agent(targ);\n\tresult.setInt(targ->elas);\n}\n\n\/**\n MVTO (command) x (float) y (float)\n %status maybe\n\n Places the TARG agent at the given x\/y position in the world (using the upper left hand corner of the agent).\n*\/\nvoid caosVM::c_MVTO() {\n\tVM_VERIFY_SIZE(2)\n\tVM_PARAM_FLOAT(y)\n\tVM_PARAM_FLOAT(x)\n\tvalid_agent(targ);\n\ttarg->moveTo(x, y);\n}\n\n\/**\n MVBY (command) x (float) y (float)\n %status maybe\n\n Changes the TARG agent's position by the given relative distances.\n*\/\nvoid caosVM::c_MVBY() {\n\tVM_PARAM_FLOAT(y)\n\tVM_PARAM_FLOAT(x)\n\n\tvalid_agent(targ);\n\ttarg->moveTo(targ->x + x, targ->y + y);\n}\n\n\/**\n VELX (variable)\n %status maybe\n\n Returns the current horizontal velocity, in pixels\/tick, of the TARG agent.\n*\/\nvoid caosVM::v_VELX() {\n\tVM_VERIFY_SIZE(0)\n\tvalid_agent(targ);\n\tvm->valueStack.push_back(&targ->velx);\n}\n\n\/**\n VELY (variable)\n %status maybe\n\n Returns the current vertical velocity, in pixels\/tick, of the TARG agent.\n*\/\nvoid caosVM::v_VELY() {\n\tVM_VERIFY_SIZE(0)\n\n\tvalid_agent(targ);\n\tvm->valueStack.push_back(&targ->vely);\n}\n\n\/**\n OBST (float) direction (integer)\n %status maybe\n\n Returns the distance from the TARG agent to the nearest wall that it might collide with in the given direction.\n (except right now it just gives the direction to the nearest wall at world edge - fuzzie)\n*\/\nvoid caosVM::v_OBST() {\n\tVM_VERIFY_SIZE(1)\n\tVM_PARAM_INTEGER(direction) caos_assert(direction >= 0); caos_assert(direction <= 3);\n\n\t\/*\n\t * TODO: CL's docs say to return \"a very large number\" if distance is greater than rnge - if (!collided)?\n\t * also, this code is untested :) - fuzzie\n\t *\/\n\t\n\tvalid_agent(targ);\n\t\n\tPoint src = targ->boundingBoxPoint(direction);\n\tPoint dest = src;\n\n\tswitch (direction) {\n\t\tcase 0: \/\/ left\n\t\t\tdest.x -= targ->range; break;\n\t\tcase 1: \/\/ right\n\t\t\tdest.x += targ->range; break;\n\t\tcase 2: \/\/ top\n\t\t\tdest.y -= targ->range; break;\n\t\tcase 3: \/\/ bottom\n\t\t\tdest.y += targ->range; break;\n\t}\n\n\tRoom *ourRoom = world.map.roomAt(src.x, src.y);\n\tif (!ourRoom) {\n\t\t\/\/ TODO: is this correct behaviour?\n\t\tresult.setFloat(0.0f);\n\t\treturn;\n\t}\n\n\tunsigned int dummy1; Line dummy2; Point point;\n\tbool collided = world.map.collideLineWithRoomSystem(src, dest, ourRoom, point, dummy2, dummy1, targ->perm);\n\n\tswitch (direction) {\n\t\tcase 0: result.setFloat(src.x - point.x); break;\n\t\tcase 1: result.setFloat(point.x - src.x); break;\n\t\tcase 2: result.setFloat(src.y - point.y); break;\n\t\tcase 3: result.setFloat(point.y - src.y); break;\n\t}\n}\n\n\/**\n TMVT (integer) x (float) y (float)\n %status maybe\n \n Returns 1 if the TARG agent could move to (x, y) and still be in room system, or 0 if otherwise.\n*\/\nvoid caosVM::v_TMVT() {\n\tVM_VERIFY_SIZE(2)\n\tVM_PARAM_FLOAT(y)\n\tVM_PARAM_FLOAT(x)\n\n\tvalid_agent(targ);\n\n\tif (targ->validInRoomSystem(Point(x, y), targ->getWidth(), targ->getHeight(), targ->perm))\n\t\tresult.setInt(1);\n\telse\n\t\tresult.setInt(0);\n}\n\n\/**\n TMVF (integer) x (float) y (float)\n %status stub\n \n Returns 1 if the TARG Creature could move foot to (x, y) and still be in room system, or 0 if otherwise.\n*\/\nvoid caosVM::v_TMVF() {\n\tVM_VERIFY_SIZE(2)\n\tVM_PARAM_FLOAT(y)\n\tVM_PARAM_FLOAT(x)\n\n\tvalid_agent(targ);\n\tresult.setInt(1); \/\/ TODO: don't hardcode\n}\n\n\/**\n ACCG (command) accel (float)\n %status maybe\n\n Sets the TARG agent's free-fall acceleration, in pixels\/tick squared.\n*\/\nvoid caosVM::c_ACCG() {\n\tVM_VERIFY_SIZE(1)\n\tVM_PARAM_FLOAT(accel)\n\n\tvalid_agent(targ);\n\ttarg->accg = accel;\n}\n\n\/**\n ACCG (float)\n %status maybe\n \n Returns the TARG agent's free-fall acceleration, in pixels\/tick squared.\n*\/\nvoid caosVM::v_ACCG() {\n\tVM_VERIFY_SIZE(0)\n\n\tvalid_agent(targ);\n\tresult.setFloat(targ->accg);\n}\n\n\/**\n AERO (command) aero (float)\n %status maybe\n\n Sets the aerodynamics of the TARG agent to the given float value.\n*\/\nvoid caosVM::c_AERO() {\n\tVM_VERIFY_SIZE(1)\n\tVM_PARAM_FLOAT(aero)\n\n\tvalid_agent(targ);\n\ttarg->aero = aero;\n}\n\n\/**\n AERO (float)\n %status maybe\n\n Returns the aerodynamics of the TARG agent.\n*\/\nvoid caosVM::v_AERO() {\n\tVM_VERIFY_SIZE(0)\n\t\n\tvalid_agent(targ);\n\tresult.setFloat(targ->aero);\n}\n\n\/**\n RELX (float) first (agent) second (agent)\n %status maybe\n\n Returns the relative horizontal distance between the centers of the two given agents.\n*\/\nvoid caosVM::v_RELX() {\n\tVM_VERIFY_SIZE(2)\n\tVM_PARAM_VALIDAGENT(second)\n\tVM_PARAM_VALIDAGENT(first)\n\n\tfloat one = first->x + (first->getWidth() \/ 2.0);\n\tfloat two = second->x + (second->getWidth() \/ 2.0);\n\n\tresult.setFloat(two - one);\n}\n\n\/**\n RELY (float) first (agent) second (agent)\n %status maybe\n\n Returns the relative vertical distance between the centers of the two given agents.\n*\/\nvoid caosVM::v_RELY() {\n\tVM_VERIFY_SIZE(2)\n\tVM_PARAM_VALIDAGENT(second)\n\tVM_PARAM_VALIDAGENT(first)\n\n\tfloat one = first->y + (first->getHeight() \/ 2.0);\n\tfloat two = second->y + (second->getHeight() \/ 2.0);\n\n\tresult.setFloat(two - one);\n}\n\n\/**\n VELO (command) xvel (float) yvel (float)\n %status maybe\n\n Sets the horizontal and vertical velocity of the TARG agent, in pixels\/tick.\n*\/\nvoid caosVM::c_VELO() {\n\tVM_VERIFY_SIZE(2)\n\tVM_PARAM_FLOAT(vely)\n\tVM_PARAM_FLOAT(velx)\n\n\tvalid_agent(targ);\n\ttarg->velx.reset();\n\ttarg->velx.setFloat(velx);\n\ttarg->vely.reset();\n\ttarg->vely.setFloat(vely);\n}\n\n\/**\n MVSF (command) x (float) y (float)\n %status maybe\n\n Move the target agent to an area inside the room system at about (x, y).\n This allows 'safe' moves.\n*\/\nvoid caosVM::c_MVSF() {\n\tVM_PARAM_FLOAT(y)\n\tVM_PARAM_FLOAT(x)\n\tvalid_agent(targ);\n\n\t\/\/ TODO: this is a silly hack, to cater for simplest case (where we just need to nudge the agent up a bit)\n\tunsigned int tries = 0;\n\twhile (tries < 150) {\n\t\tif (targ->validInRoomSystem(Point(x, y - tries), targ->getWidth(), targ->getHeight(), targ->perm)) {\n\t\t\ttarg->moveTo(x, y - tries);\n\t\t\treturn;\n\t\t}\n\t\ttries++;\n\t}\n\n\t\/\/ TODO: temp hack to shut scripts up\n\ttarg->kill();\n\tif (owner) owner->kill();\n\tthrow creaturesException(\"MVSF failed to find a safe place\");\n}\n\n\/**\n FRIC (float)\n %status maybe\n\n Returns the TARG agent's coefficient of friction as a percentage.\n*\/\nvoid caosVM::v_FRIC() {\n\tVM_VERIFY_SIZE(0)\n\t\n\tvalid_agent(targ);\n\tresult.setFloat(targ->friction);\n}\n\n\/**\n FRIC (command) friction (integer)\n %status maybe\n \n Sets the TARG agent's coefficient of friction, or the percentage of motion that will be lost as it slides on a \n surface.\n*\/\nvoid caosVM::c_FRIC() {\n\tVM_VERIFY_SIZE(1)\n\tVM_PARAM_INTEGER(friction) caos_assert(friction >= 0); caos_assert(friction <= 100);\n\n\tvalid_agent(targ);\n\ttarg->friction = friction;\n}\n\n\/**\n FALL (integer)\n %status maybe\n\n Returns 1 if the TARG agent is moving due to gravity, or 0 if otherwise.\n*\/\nvoid caosVM::v_FALL() {\n\tVM_VERIFY_SIZE(0)\n\tvalid_agent(targ);\n\n\t\/\/ XXX: this probably isn't quite correct, but it's close enough for now.\n\tif (targ->falling)\n\t\tresult.setInt(1);\n\telse\n\t\tresult.setInt(0);\n}\n\n\/**\n MOVS (integer)\n %status stub\n\n Returns an integer representing the motion status of the TARG agent. 0 is autonomous, 1 is moving by mouse, 2 is \n floating, 3 is inside a vehicle, and 4 is being carried.\n*\/\nvoid caosVM::v_MOVS() {\n\tvalid_agent(targ);\n\n\tresult.setInt(0); \/\/ TODO\n}\n\n\/**\n FLTO (command) x (float) y (float)\n %status maybe\n\n Sets the TARG agent to float its top-left corner (x, y) away from the top-left corner of the FREL agent.\n*\/\nvoid caosVM::c_FLTO() {\n\tVM_PARAM_FLOAT(y)\n\tVM_PARAM_FLOAT(x)\n\n\tvalid_agent(targ)\n\ttarg->floatTo(x, y);\n}\n\n\/**\n FREL (command) agent (agent)\n %status maybe\n\n Sets the agent the TARG agent floats relative to. You must set the 'floatable' attribute for this to work.\n The default is NULL, which means the target agent floats relative to the main camera.\n*\/\nvoid caosVM::c_FREL() {\n\tVM_PARAM_AGENT(agent)\n\n\tvalid_agent(targ)\n\ttarg->floatTo(agent);\n}\n\n\/**\n FLTX (float)\n %status maybe\n\n Returns the x value of the TARG agent's floating vector.\n*\/\nvoid caosVM::v_FLTX() {\n\tvalid_agent(targ);\n\n\tif (targ->floatingagent)\n\t\tresult.setFloat(targ->floatingagent->x - targ->x);\n\telse\n\t\tresult.setFloat(world.camera.getX() - targ->x);\n}\n\n\/**\n FLTY (float)\n %status maybe\n\n Returns the y value of the TARG agent's floating vector.\n*\/\nvoid caosVM::v_FLTY() {\n\tvalid_agent(targ);\n\t\n\tif (targ->floatingagent)\n\t\tresult.setFloat(targ->floatingagent->x - targ->x);\n\telse\n\t\tresult.setFloat(world.camera.getX() - targ->x);\n}\n\n\/* vim: set noet: *\/\n<commit_msg>add more hacky behaviour to MVSF, plus a better exception message<commit_after>\/*\n * caosVM_agent.cpp\n * openc2e\n *\n * Created by Alyssa Milburn on Tue Jun 01 2004.\n * Copyright (c) 2004 Alyssa Milburn. All rights reserved.\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n *\/\n\n#include \"caosVM.h\"\n#include \"openc2e.h\"\n#include \"Agent.h\"\n#include \"AgentRef.h\"\n#include \"World.h\"\n#include <iostream>\n#include <boost\/format.hpp>\nusing std::cerr;\n\n\/**\n ELAS (command) elas (integer)\n %status maybe\n\n Sets the elasticity (in other words, bounciness) of the TARG agent.\n*\/\nvoid caosVM::c_ELAS() {\n\tVM_VERIFY_SIZE(1)\n\tVM_PARAM_INTEGER(elas)\n\n\tvalid_agent(targ);\n\ttarg->elas = elas;\n}\n\n\/***\n ELAS (integer)\n %status maybe\n\n Returns the elasticity of the TARG agent.\n*\/\nvoid caosVM::v_ELAS() {\n\tVM_VERIFY_SIZE(0)\n\n\tvalid_agent(targ);\n\tresult.setInt(targ->elas);\n}\n\n\/**\n MVTO (command) x (float) y (float)\n %status maybe\n\n Places the TARG agent at the given x\/y position in the world (using the upper left hand corner of the agent).\n*\/\nvoid caosVM::c_MVTO() {\n\tVM_VERIFY_SIZE(2)\n\tVM_PARAM_FLOAT(y)\n\tVM_PARAM_FLOAT(x)\n\tvalid_agent(targ);\n\ttarg->moveTo(x, y);\n}\n\n\/**\n MVBY (command) x (float) y (float)\n %status maybe\n\n Changes the TARG agent's position by the given relative distances.\n*\/\nvoid caosVM::c_MVBY() {\n\tVM_PARAM_FLOAT(y)\n\tVM_PARAM_FLOAT(x)\n\n\tvalid_agent(targ);\n\ttarg->moveTo(targ->x + x, targ->y + y);\n}\n\n\/**\n VELX (variable)\n %status maybe\n\n Returns the current horizontal velocity, in pixels\/tick, of the TARG agent.\n*\/\nvoid caosVM::v_VELX() {\n\tVM_VERIFY_SIZE(0)\n\tvalid_agent(targ);\n\tvm->valueStack.push_back(&targ->velx);\n}\n\n\/**\n VELY (variable)\n %status maybe\n\n Returns the current vertical velocity, in pixels\/tick, of the TARG agent.\n*\/\nvoid caosVM::v_VELY() {\n\tVM_VERIFY_SIZE(0)\n\n\tvalid_agent(targ);\n\tvm->valueStack.push_back(&targ->vely);\n}\n\n\/**\n OBST (float) direction (integer)\n %status maybe\n\n Returns the distance from the TARG agent to the nearest wall that it might collide with in the given direction.\n (except right now it just gives the direction to the nearest wall at world edge - fuzzie)\n*\/\nvoid caosVM::v_OBST() {\n\tVM_VERIFY_SIZE(1)\n\tVM_PARAM_INTEGER(direction) caos_assert(direction >= 0); caos_assert(direction <= 3);\n\n\t\/*\n\t * TODO: CL's docs say to return \"a very large number\" if distance is greater than rnge - if (!collided)?\n\t * also, this code is untested :) - fuzzie\n\t *\/\n\t\n\tvalid_agent(targ);\n\t\n\tPoint src = targ->boundingBoxPoint(direction);\n\tPoint dest = src;\n\n\tswitch (direction) {\n\t\tcase 0: \/\/ left\n\t\t\tdest.x -= targ->range; break;\n\t\tcase 1: \/\/ right\n\t\t\tdest.x += targ->range; break;\n\t\tcase 2: \/\/ top\n\t\t\tdest.y -= targ->range; break;\n\t\tcase 3: \/\/ bottom\n\t\t\tdest.y += targ->range; break;\n\t}\n\n\tRoom *ourRoom = world.map.roomAt(src.x, src.y);\n\tif (!ourRoom) {\n\t\t\/\/ TODO: is this correct behaviour?\n\t\tresult.setFloat(0.0f);\n\t\treturn;\n\t}\n\n\tunsigned int dummy1; Line dummy2; Point point;\n\tbool collided = world.map.collideLineWithRoomSystem(src, dest, ourRoom, point, dummy2, dummy1, targ->perm);\n\n\tswitch (direction) {\n\t\tcase 0: result.setFloat(src.x - point.x); break;\n\t\tcase 1: result.setFloat(point.x - src.x); break;\n\t\tcase 2: result.setFloat(src.y - point.y); break;\n\t\tcase 3: result.setFloat(point.y - src.y); break;\n\t}\n}\n\n\/**\n TMVT (integer) x (float) y (float)\n %status maybe\n \n Returns 1 if the TARG agent could move to (x, y) and still be in room system, or 0 if otherwise.\n*\/\nvoid caosVM::v_TMVT() {\n\tVM_VERIFY_SIZE(2)\n\tVM_PARAM_FLOAT(y)\n\tVM_PARAM_FLOAT(x)\n\n\tvalid_agent(targ);\n\n\tif (targ->validInRoomSystem(Point(x, y), targ->getWidth(), targ->getHeight(), targ->perm))\n\t\tresult.setInt(1);\n\telse\n\t\tresult.setInt(0);\n}\n\n\/**\n TMVF (integer) x (float) y (float)\n %status stub\n \n Returns 1 if the TARG Creature could move foot to (x, y) and still be in room system, or 0 if otherwise.\n*\/\nvoid caosVM::v_TMVF() {\n\tVM_VERIFY_SIZE(2)\n\tVM_PARAM_FLOAT(y)\n\tVM_PARAM_FLOAT(x)\n\n\tvalid_agent(targ);\n\tresult.setInt(1); \/\/ TODO: don't hardcode\n}\n\n\/**\n ACCG (command) accel (float)\n %status maybe\n\n Sets the TARG agent's free-fall acceleration, in pixels\/tick squared.\n*\/\nvoid caosVM::c_ACCG() {\n\tVM_VERIFY_SIZE(1)\n\tVM_PARAM_FLOAT(accel)\n\n\tvalid_agent(targ);\n\ttarg->accg = accel;\n}\n\n\/**\n ACCG (float)\n %status maybe\n \n Returns the TARG agent's free-fall acceleration, in pixels\/tick squared.\n*\/\nvoid caosVM::v_ACCG() {\n\tVM_VERIFY_SIZE(0)\n\n\tvalid_agent(targ);\n\tresult.setFloat(targ->accg);\n}\n\n\/**\n AERO (command) aero (float)\n %status maybe\n\n Sets the aerodynamics of the TARG agent to the given float value.\n*\/\nvoid caosVM::c_AERO() {\n\tVM_VERIFY_SIZE(1)\n\tVM_PARAM_FLOAT(aero)\n\n\tvalid_agent(targ);\n\ttarg->aero = aero;\n}\n\n\/**\n AERO (float)\n %status maybe\n\n Returns the aerodynamics of the TARG agent.\n*\/\nvoid caosVM::v_AERO() {\n\tVM_VERIFY_SIZE(0)\n\t\n\tvalid_agent(targ);\n\tresult.setFloat(targ->aero);\n}\n\n\/**\n RELX (float) first (agent) second (agent)\n %status maybe\n\n Returns the relative horizontal distance between the centers of the two given agents.\n*\/\nvoid caosVM::v_RELX() {\n\tVM_VERIFY_SIZE(2)\n\tVM_PARAM_VALIDAGENT(second)\n\tVM_PARAM_VALIDAGENT(first)\n\n\tfloat one = first->x + (first->getWidth() \/ 2.0);\n\tfloat two = second->x + (second->getWidth() \/ 2.0);\n\n\tresult.setFloat(two - one);\n}\n\n\/**\n RELY (float) first (agent) second (agent)\n %status maybe\n\n Returns the relative vertical distance between the centers of the two given agents.\n*\/\nvoid caosVM::v_RELY() {\n\tVM_VERIFY_SIZE(2)\n\tVM_PARAM_VALIDAGENT(second)\n\tVM_PARAM_VALIDAGENT(first)\n\n\tfloat one = first->y + (first->getHeight() \/ 2.0);\n\tfloat two = second->y + (second->getHeight() \/ 2.0);\n\n\tresult.setFloat(two - one);\n}\n\n\/**\n VELO (command) xvel (float) yvel (float)\n %status maybe\n\n Sets the horizontal and vertical velocity of the TARG agent, in pixels\/tick.\n*\/\nvoid caosVM::c_VELO() {\n\tVM_VERIFY_SIZE(2)\n\tVM_PARAM_FLOAT(vely)\n\tVM_PARAM_FLOAT(velx)\n\n\tvalid_agent(targ);\n\ttarg->velx.reset();\n\ttarg->velx.setFloat(velx);\n\ttarg->vely.reset();\n\ttarg->vely.setFloat(vely);\n}\n\n\/**\n MVSF (command) x (float) y (float)\n %status maybe\n\n Move the target agent to an area inside the room system at about (x, y).\n This allows 'safe' moves.\n*\/\nvoid caosVM::c_MVSF() {\n\tVM_PARAM_FLOAT(y)\n\tVM_PARAM_FLOAT(x)\n\tvalid_agent(targ);\n\n\t\/\/ TODO: this is a silly hack, to cater for simplest case (where we just need to nudge the agent up a bit)\n\tunsigned int tries = 0;\n\twhile (tries < 150) {\n\t\tif (targ->validInRoomSystem(Point(x, y - tries), targ->getWidth(), targ->getHeight(), targ->perm)) {\n\t\t\ttarg->moveTo(x, y - tries);\n\t\t\treturn;\n\t\t}\n\t\ttries++;\n\t}\n\n\t\/\/ second hacky attempt, move from side to side (+\/- 50) and up a little\n\tfor (unsigned int xadjust = 0; xadjust < 50; xadjust++) {\n\t\tfor (unsigned int yadjust = 0; yadjust < 50; yadjust++) {\n\t\t\tif (targ->validInRoomSystem(Point(x - xadjust, y - yadjust), targ->getWidth(), targ->getHeight(), targ->perm))\n\t\t\t\ttarg->moveTo(x - xadjust, y - yadjust);\n\t\t\telse if (targ->validInRoomSystem(Point(x + xadjust, y - yadjust), targ->getWidth(), targ->getHeight(), targ->perm))\n\t\t\t\ttarg->moveTo(x + xadjust, y - yadjust);\n\t\t\telse\n\t\t\t\tcontinue;\n\t\t\treturn;\n\t\t}\n\t}\n\n\tthrow creaturesException(boost::str(boost::format(\"MVSF failed to find a safe place around (%d, %d)\") % x % y));\n}\n\n\/**\n FRIC (float)\n %status maybe\n\n Returns the TARG agent's coefficient of friction as a percentage.\n*\/\nvoid caosVM::v_FRIC() {\n\tVM_VERIFY_SIZE(0)\n\t\n\tvalid_agent(targ);\n\tresult.setFloat(targ->friction);\n}\n\n\/**\n FRIC (command) friction (integer)\n %status maybe\n \n Sets the TARG agent's coefficient of friction, or the percentage of motion that will be lost as it slides on a \n surface.\n*\/\nvoid caosVM::c_FRIC() {\n\tVM_VERIFY_SIZE(1)\n\tVM_PARAM_INTEGER(friction) caos_assert(friction >= 0); caos_assert(friction <= 100);\n\n\tvalid_agent(targ);\n\ttarg->friction = friction;\n}\n\n\/**\n FALL (integer)\n %status maybe\n\n Returns 1 if the TARG agent is moving due to gravity, or 0 if otherwise.\n*\/\nvoid caosVM::v_FALL() {\n\tVM_VERIFY_SIZE(0)\n\tvalid_agent(targ);\n\n\t\/\/ XXX: this probably isn't quite correct, but it's close enough for now.\n\tif (targ->falling)\n\t\tresult.setInt(1);\n\telse\n\t\tresult.setInt(0);\n}\n\n\/**\n MOVS (integer)\n %status stub\n\n Returns an integer representing the motion status of the TARG agent. 0 is autonomous, 1 is moving by mouse, 2 is \n floating, 3 is inside a vehicle, and 4 is being carried.\n*\/\nvoid caosVM::v_MOVS() {\n\tvalid_agent(targ);\n\n\tresult.setInt(0); \/\/ TODO\n}\n\n\/**\n FLTO (command) x (float) y (float)\n %status maybe\n\n Sets the TARG agent to float its top-left corner (x, y) away from the top-left corner of the FREL agent.\n*\/\nvoid caosVM::c_FLTO() {\n\tVM_PARAM_FLOAT(y)\n\tVM_PARAM_FLOAT(x)\n\n\tvalid_agent(targ)\n\ttarg->floatTo(x, y);\n}\n\n\/**\n FREL (command) agent (agent)\n %status maybe\n\n Sets the agent the TARG agent floats relative to. You must set the 'floatable' attribute for this to work.\n The default is NULL, which means the target agent floats relative to the main camera.\n*\/\nvoid caosVM::c_FREL() {\n\tVM_PARAM_AGENT(agent)\n\n\tvalid_agent(targ)\n\ttarg->floatTo(agent);\n}\n\n\/**\n FLTX (float)\n %status maybe\n\n Returns the x value of the TARG agent's floating vector.\n*\/\nvoid caosVM::v_FLTX() {\n\tvalid_agent(targ);\n\n\tif (targ->floatingagent)\n\t\tresult.setFloat(targ->floatingagent->x - targ->x);\n\telse\n\t\tresult.setFloat(world.camera.getX() - targ->x);\n}\n\n\/**\n FLTY (float)\n %status maybe\n\n Returns the y value of the TARG agent's floating vector.\n*\/\nvoid caosVM::v_FLTY() {\n\tvalid_agent(targ);\n\t\n\tif (targ->floatingagent)\n\t\tresult.setFloat(targ->floatingagent->x - targ->x);\n\telse\n\t\tresult.setFloat(world.camera.getX() - targ->x);\n}\n\n\/* vim: set noet: *\/\n<|endoftext|>"} {"text":"<commit_before>\/\/ This file is a part of the OpenSurgSim project.\n\/\/ Copyright 2012-2013, SimQuest Solutions Inc.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n\/\/\/ \\file\n\/\/\/ Render Tests for the OsgShader class.\n\n\n#include \"SurgSim\/Framework\/ApplicationData.h\"\n#include \"SurgSim\/Framework\/BasicSceneElement.h\"\n#include \"SurgSim\/Framework\/Runtime.h\"\n#include \"SurgSim\/Framework\/Scene.h\"\n#include \"SurgSim\/Framework\/SceneElement.h\"\n#include \"SurgSim\/Graphics\/OsgAxesRepresentation.h\"\n#include \"SurgSim\/Graphics\/OsgCamera.h\"\n#include \"SurgSim\/Graphics\/OsgLight.h\"\n#include \"SurgSim\/Graphics\/OsgManager.h\"\n#include \"SurgSim\/Graphics\/OsgMaterial.h\"\n#include \"SurgSim\/Graphics\/OsgShader.h\"\n#include \"SurgSim\/Graphics\/OsgSphereRepresentation.h\"\n#include \"SurgSim\/Graphics\/OsgUniform.h\"\n#include \"SurgSim\/Graphics\/OsgViewElement.h\"\n#include \"SurgSim\/Graphics\/RenderTests\/RenderTest.h\"\n#include \"SurgSim\/Math\/Quaternion.h\"\n#include \"SurgSim\/Math\/Vector.h\"\n\n#include <boost\/filesystem.hpp>\n\n#include <gtest\/gtest.h>\n\n#include <random>\n\n\nusing SurgSim::Framework::Runtime;\nusing SurgSim::Framework::Scene;\nusing SurgSim::Framework::SceneElement;\nusing SurgSim::Math::Quaterniond;\nusing SurgSim::Math::RigidTransform3d;\nusing SurgSim::Math::Vector3d;\nusing SurgSim::Math::makeRigidTransform;\n\nnamespace SurgSim\n{\n\nnamespace Graphics\n{\n\nstd::shared_ptr<Shader> loadExampleShader(const SurgSim::Framework::ApplicationData& data)\n{\n\tstd::shared_ptr<Shader> shader = std::make_shared<OsgShader>();\n\n\tstd::string vertexShaderPath = data.findFile(\"OsgShaderRenderTests\/shader.vert\");\n\tstd::string geometryShaderPath = data.findFile(\"OsgShaderRenderTests\/shader.geom\");\n\tstd::string fragmentShaderPath = data.findFile(\"OsgShaderRenderTests\/shader.frag\");\n\n\tEXPECT_NE(\"\", vertexShaderPath) << \"Could not find vertex shader!\";\n\tEXPECT_NE(\"\", geometryShaderPath) << \"Could not find geometry shader!\";\n\tEXPECT_NE(\"\", fragmentShaderPath) << \"Could not find fragment shader!\";\n\n\tshader->loadVertexShaderSource(vertexShaderPath);\n\tshader->loadGeometryShaderSource(geometryShaderPath);\n\tshader->loadFragmentShaderSource(fragmentShaderPath);\n\n\treturn shader;\n}\n\nstd::shared_ptr<Material> loadMaterial(const SurgSim::Framework::ApplicationData& data,\n\t\t\t\t\t\t\t\t\t const std::string& shaderName)\n{\n\tSCOPED_TRACE(\"Load Material\");\n\n\tauto shader = std::make_shared<SurgSim::Graphics::OsgShader>();\n\n\tstd::string filename;\n\tEXPECT_TRUE(data.tryFindFile(shaderName + \".vert\", &filename));\n\tshader->loadVertexShaderSource(filename);\n\n\tEXPECT_TRUE(data.tryFindFile(shaderName + \".frag\", &filename));\n\tshader->loadFragmentShaderSource(filename);\n\n\tauto material = std::make_shared<SurgSim::Graphics::OsgMaterial>();\n\tmaterial->setShader(shader);\n\n\treturn material;\n}\n\nstd::shared_ptr<Material> createShinyMaterial(const SurgSim::Framework::ApplicationData& data)\n{\n\tauto material = loadMaterial(data, \"Shaders\/material\");\n\tstd::shared_ptr<SurgSim::Graphics::UniformBase>\n\tuniform = std::make_shared<OsgUniform<SurgSim::Math::Vector4f>>(\"diffuseColor\");\n\tmaterial->addUniform(uniform);\n\n\tuniform = std::make_shared<OsgUniform<SurgSim::Math::Vector4f>>(\"specularColor\");\n\tmaterial->addUniform(uniform);\n\n\tuniform = std::make_shared<OsgUniform<float>>(\"shininess\");\n\tmaterial->addUniform(uniform);\n\n\treturn material;\n}\n\nstruct OsgShaderRenderTests : public RenderTest\n{\n\n};\n\n\/\/\/ Pops up a window with a sphere colored by its normals and its mirror along the x-axis is also drawn using the\n\/\/\/ geometry shader\nTEST_F(OsgShaderRenderTests, SphereShaderTest)\n{\n\t\/\/\/ Add the sphere representation to the view element, no need to make another scene element\n\tstd::shared_ptr<SphereRepresentation> sphereRepresentation =\n\t\tstd::make_shared<OsgSphereRepresentation>(\"sphere representation\");\n\tsphereRepresentation->setRadius(0.25);\n\tsphereRepresentation->setLocalPose(makeRigidTransform(Quaterniond::Identity(), Vector3d(0.25, 0.0, -1.0)));\n\n\t\/\/\/ Add a shader to the sphere\n\tstd::shared_ptr<OsgMaterial> material = std::make_shared<OsgMaterial>();\n\tstd::shared_ptr<Shader> shader = loadExampleShader(*applicationData);\n\n\tmaterial->setShader(shader);\n\tsphereRepresentation->setMaterial(material);\n\n\tviewElement->addComponent(sphereRepresentation);\n\n\t\/\/\/ Run the thread\n\truntime->start();\n\tboost::this_thread::sleep(boost::posix_time::milliseconds(1000));\n\truntime->stop();\n\n}\n\nTEST_F(OsgShaderRenderTests, ShinyShaderTest)\n{\n\t\/\/\/ Add the sphere representation to the view element, no need to make another scene element\n\tauto sceneElement = std::make_shared<SurgSim::Framework::BasicSceneElement>(\"Sphere\");\n\tstd::shared_ptr<SphereRepresentation> sphereRepresentation =\n\t\tstd::make_shared<OsgSphereRepresentation>(\"sphere representation\");\n\tsphereRepresentation->setRadius(0.25);\n\n\tauto material = createShinyMaterial(*runtime->getApplicationData());\n\tmaterial->setValue(\"diffuseColor\", SurgSim::Math::Vector4f(0.8, 0.8, 0.1, 1.0));\n\tmaterial->setValue(\"specularColor\", SurgSim::Math::Vector4f(1.0, 1.0, 0.4, 1.0));\n\tmaterial->setValue(\"shininess\", 64.0f);\n\tsphereRepresentation->setMaterial(material);\n\tsceneElement->addComponent(sphereRepresentation);\n\tsceneElement->addComponent(std::make_shared<SurgSim::Graphics::OsgAxesRepresentation>(\"axes\"));\n\tscene->addSceneElement(sceneElement);\n\n\n\tsceneElement = std::make_shared<SurgSim::Framework::BasicSceneElement>(\"Light\");\n\tauto light = std::make_shared<SurgSim::Graphics::OsgLight>(\"Light\");\n\tlight->setDiffuseColor(SurgSim::Math::Vector4d(0.8, 0.8, 0.8, 1.0));\n\tlight->setSpecularColor(SurgSim::Math::Vector4d(0.8, 0.8, 0.8, 1.0));\n\tlight->setLightGroupReference(SurgSim::Graphics::Representation::DefaultGroupName);\n\tsceneElement->addComponent(light);\n\tsceneElement->addComponent(std::make_shared<SurgSim::Graphics::OsgAxesRepresentation>(\"axes\"));\n\tsceneElement->setPose(makeRigidTransform(Quaterniond::Identity(), Vector3d(-2.0, -2.0, -4.0)));\n\n\tscene->addSceneElement(sceneElement);\n\n\tviewElement->setPose(\n\t\tmakeRigidTransform(Vector3d(0.0, 0.0, -2.0), Vector3d(0.0, 0.0, 0.0), Vector3d(0.0, 1.0, 0.0)));\n\tviewElement->addComponent(std::make_shared<SurgSim::Graphics::OsgAxesRepresentation>(\"axes\"));\n\n\n\t\/\/\/ Run the thread\n\truntime->start();\n\tboost::this_thread::sleep(boost::posix_time::milliseconds(500));\n\truntime->stop();\n\n}\n\nTEST_F(OsgShaderRenderTests, TexturedShinyShaderTest)\n{\n\t\/\/\/ Add the sphere representation to the view element, no need to make another scene element\n\tauto sceneElement = std::make_shared<SurgSim::Framework::BasicSceneElement>(\"Sphere\");\n\tstd::shared_ptr<SphereRepresentation> sphereRepresentation =\n\t\tstd::make_shared<OsgSphereRepresentation>(\"sphere representation\");\n\tsphereRepresentation->setRadius(0.25);\n\n\tviewElement->getCamera()->setAmbientColor(SurgSim::Math::Vector4d(0.2, 0.2, 0.2, 1.0));\n\n\tauto material = loadMaterial(*runtime->getApplicationData(), \"Shaders\/ds_mapping_material\");\n\tstd::shared_ptr<SurgSim::Graphics::UniformBase>\n\tuniform = std::make_shared<OsgUniform<SurgSim::Math::Vector4f>>(\"diffuseColor\");\n\tmaterial->addUniform(uniform);\n\tmaterial->setValue(\"diffuseColor\", SurgSim::Math::Vector4f(1.0, 1.0, 1.0, 1.0));\n\n\tuniform = std::make_shared<OsgUniform<SurgSim::Math::Vector4f>>(\"specularColor\");\n\tmaterial->addUniform(uniform);\n\tmaterial->setValue(\"specularColor\", SurgSim::Math::Vector4f(1.0, 1.0, 1.0, 1.0));\n\n\tuniform = std::make_shared<OsgUniform<float>>(\"shininess\");\n\tmaterial->addUniform(uniform);\n\tmaterial->setValue(\"shininess\", 32.0f);\n\n\tstd::string filename;\n\tEXPECT_TRUE(runtime->getApplicationData()->tryFindFile(\"Data\/Textures\/CheckerBoard.png\", &filename));\n\tauto texture = std::make_shared<SurgSim::Graphics::OsgTexture2d>();\n\ttexture->loadImage(filename);\n\tauto diffuseMapUniform =\n\t\tstd::make_shared<OsgTextureUniform<OsgTexture2d>>(\"diffuseMap\");\n\tdiffuseMapUniform->set(texture);\n\tmaterial->addUniform(diffuseMapUniform);\n\n\tmaterial->setValue(\"diffuseColor\", SurgSim::Math::Vector4f(0.8, 0.8, 0.1, 1.0));\n\tmaterial->setValue(\"specularColor\", SurgSim::Math::Vector4f(1.0, 1.0, 0.4, 1.0));\n\tmaterial->setValue(\"shininess\", 1.0f);\n\tsphereRepresentation->setMaterial(material);\n\tsceneElement->addComponent(sphereRepresentation);\n\tsceneElement->addComponent(std::make_shared<SurgSim::Graphics::OsgAxesRepresentation>(\"axes\"));\n\tscene->addSceneElement(sceneElement);\n\n\n\tsceneElement = std::make_shared<SurgSim::Framework::BasicSceneElement>(\"Light\");\n\tauto light = std::make_shared<SurgSim::Graphics::OsgLight>(\"Light\");\n\tlight->setDiffuseColor(SurgSim::Math::Vector4d(0.8, 0.8, 0.8, 1.0));\n\tlight->setSpecularColor(SurgSim::Math::Vector4d(0.8, 0.8, 0.8, 1.0));\n\tlight->setLightGroupReference(SurgSim::Graphics::Representation::DefaultGroupName);\n\tsceneElement->addComponent(light);\n\tsceneElement->addComponent(std::make_shared<SurgSim::Graphics::OsgAxesRepresentation>(\"axes\"));\n\tsceneElement->setPose(makeRigidTransform(Quaterniond::Identity(), Vector3d(-2.0, -2.0, -4.0)));\n\n\tsphereRepresentation = std::make_shared<OsgSphereRepresentation>(\"debug\");\n\tsphereRepresentation->setRadius(0.01);\n\tsceneElement->addComponent(sphereRepresentation);\n\n\tscene->addSceneElement(sceneElement);\n\n\t\/\/viewElement->enableManipulator(true);\n\n\tviewElement->setPose(makeRigidTransform(Vector3d(0.0, 0.0, -2.0),\n\t\t\t\t\t\t\t\t\t\t\tVector3d(0.0, 0.0, 0.0),\n\t\t\t\t\t\t\t\t\t\t\tVector3d(0.0, 1.0, 0.0)));\n\tviewElement->addComponent(std::make_shared<SurgSim::Graphics::OsgAxesRepresentation>(\"axes\"));\n\n\n\t\/\/\/ Run the thread\n\t\/\/ \truntime->start();\n\t\/\/ \tboost::this_thread::sleep(boost::posix_time::milliseconds(10000));\n\t\/\/ \truntime->stop();\n\truntime->execute();\n\n}\n\n}; \/\/ namespace Graphics\n\n}; \/\/ namespace SurgSim\n<commit_msg>Use common load material function in ShaderRenderTest<commit_after>\/\/ This file is a part of the OpenSurgSim project.\n\/\/ Copyright 2012-2013, SimQuest Solutions Inc.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n\/\/\/ \\file\n\/\/\/ Render Tests for the OsgShader class.\n\n\n#include \"SurgSim\/Framework\/ApplicationData.h\"\n#include \"SurgSim\/Framework\/BasicSceneElement.h\"\n#include \"SurgSim\/Framework\/Runtime.h\"\n#include \"SurgSim\/Framework\/Scene.h\"\n#include \"SurgSim\/Framework\/SceneElement.h\"\n#include \"SurgSim\/Graphics\/OsgAxesRepresentation.h\"\n#include \"SurgSim\/Graphics\/OsgCamera.h\"\n#include \"SurgSim\/Graphics\/OsgLight.h\"\n#include \"SurgSim\/Graphics\/OsgManager.h\"\n#include \"SurgSim\/Graphics\/OsgMaterial.h\"\n#include \"SurgSim\/Graphics\/OsgShader.h\"\n#include \"SurgSim\/Graphics\/OsgSphereRepresentation.h\"\n#include \"SurgSim\/Graphics\/OsgUniform.h\"\n#include \"SurgSim\/Graphics\/OsgViewElement.h\"\n#include \"SurgSim\/Graphics\/RenderTests\/RenderTest.h\"\n#include \"SurgSim\/Math\/Quaternion.h\"\n#include \"SurgSim\/Math\/Vector.h\"\n\n#include <boost\/filesystem.hpp>\n\n#include <gtest\/gtest.h>\n\n#include <random>\n\n\nusing SurgSim::Framework::Runtime;\nusing SurgSim::Framework::Scene;\nusing SurgSim::Framework::SceneElement;\nusing SurgSim::Math::Quaterniond;\nusing SurgSim::Math::RigidTransform3d;\nusing SurgSim::Math::Vector3d;\nusing SurgSim::Math::makeRigidTransform;\n\nnamespace SurgSim\n{\n\nnamespace Graphics\n{\n\nstd::shared_ptr<Shader> loadExampleShader(const SurgSim::Framework::ApplicationData& data)\n{\n\tstd::shared_ptr<Shader> shader = std::make_shared<OsgShader>();\n\n\tstd::string vertexShaderPath = data.findFile(\"OsgShaderRenderTests\/shader.vert\");\n\tstd::string geometryShaderPath = data.findFile(\"OsgShaderRenderTests\/shader.geom\");\n\tstd::string fragmentShaderPath = data.findFile(\"OsgShaderRenderTests\/shader.frag\");\n\n\tEXPECT_NE(\"\", vertexShaderPath) << \"Could not find vertex shader!\";\n\tEXPECT_NE(\"\", geometryShaderPath) << \"Could not find geometry shader!\";\n\tEXPECT_NE(\"\", fragmentShaderPath) << \"Could not find fragment shader!\";\n\n\tshader->loadVertexShaderSource(vertexShaderPath);\n\tshader->loadGeometryShaderSource(geometryShaderPath);\n\tshader->loadFragmentShaderSource(fragmentShaderPath);\n\n\treturn shader;\n}\n\n\nstd::shared_ptr<Material> createShinyMaterial(const SurgSim::Framework::ApplicationData& data)\n{\n\tauto material = createMaterialWithShaders(data, \"Shaders\/material\");\n\tstd::shared_ptr<SurgSim::Graphics::UniformBase>\n\tuniform = std::make_shared<OsgUniform<SurgSim::Math::Vector4f>>(\"diffuseColor\");\n\tmaterial->addUniform(uniform);\n\n\tuniform = std::make_shared<OsgUniform<SurgSim::Math::Vector4f>>(\"specularColor\");\n\tmaterial->addUniform(uniform);\n\n\tuniform = std::make_shared<OsgUniform<float>>(\"shininess\");\n\tmaterial->addUniform(uniform);\n\n\treturn material;\n}\n\nstruct OsgShaderRenderTests : public RenderTest\n{\n\n};\n\n\/\/\/ Pops up a window with a sphere colored by its normals and its mirror along the x-axis is also drawn using the\n\/\/\/ geometry shader\nTEST_F(OsgShaderRenderTests, SphereShaderTest)\n{\n\t\/\/\/ Add the sphere representation to the view element, no need to make another scene element\n\tstd::shared_ptr<SphereRepresentation> sphereRepresentation =\n\t\tstd::make_shared<OsgSphereRepresentation>(\"sphere representation\");\n\tsphereRepresentation->setRadius(0.25);\n\tsphereRepresentation->setLocalPose(makeRigidTransform(Quaterniond::Identity(), Vector3d(0.25, 0.0, -1.0)));\n\n\t\/\/\/ Add a shader to the sphere\n\tstd::shared_ptr<OsgMaterial> material = std::make_shared<OsgMaterial>();\n\tstd::shared_ptr<Shader> shader = loadExampleShader(*applicationData);\n\n\tmaterial->setShader(shader);\n\tsphereRepresentation->setMaterial(material);\n\n\tviewElement->addComponent(sphereRepresentation);\n\n\t\/\/\/ Run the thread\n\truntime->start();\n\tboost::this_thread::sleep(boost::posix_time::milliseconds(1000));\n\truntime->stop();\n\n}\n\nTEST_F(OsgShaderRenderTests, ShinyShaderTest)\n{\n\t\/\/\/ Add the sphere representation to the view element, no need to make another scene element\n\tauto sceneElement = std::make_shared<SurgSim::Framework::BasicSceneElement>(\"Sphere\");\n\tstd::shared_ptr<SphereRepresentation> sphereRepresentation =\n\t\tstd::make_shared<OsgSphereRepresentation>(\"sphere representation\");\n\tsphereRepresentation->setRadius(0.25);\n\n\tauto material = createShinyMaterial(*runtime->getApplicationData());\n\tmaterial->setValue(\"diffuseColor\", SurgSim::Math::Vector4f(0.8, 0.8, 0.1, 1.0));\n\tmaterial->setValue(\"specularColor\", SurgSim::Math::Vector4f(1.0, 1.0, 0.4, 1.0));\n\tmaterial->setValue(\"shininess\", 64.0f);\n\tsphereRepresentation->setMaterial(material);\n\tsceneElement->addComponent(sphereRepresentation);\n\tsceneElement->addComponent(std::make_shared<SurgSim::Graphics::OsgAxesRepresentation>(\"axes\"));\n\tscene->addSceneElement(sceneElement);\n\n\n\tsceneElement = std::make_shared<SurgSim::Framework::BasicSceneElement>(\"Light\");\n\tauto light = std::make_shared<SurgSim::Graphics::OsgLight>(\"Light\");\n\tlight->setDiffuseColor(SurgSim::Math::Vector4d(0.8, 0.8, 0.8, 1.0));\n\tlight->setSpecularColor(SurgSim::Math::Vector4d(0.8, 0.8, 0.8, 1.0));\n\tlight->setLightGroupReference(SurgSim::Graphics::Representation::DefaultGroupName);\n\tsceneElement->addComponent(light);\n\tsceneElement->addComponent(std::make_shared<SurgSim::Graphics::OsgAxesRepresentation>(\"axes\"));\n\tsceneElement->setPose(makeRigidTransform(Quaterniond::Identity(), Vector3d(-2.0, -2.0, -4.0)));\n\n\tscene->addSceneElement(sceneElement);\n\n\tviewElement->setPose(\n\t\tmakeRigidTransform(Vector3d(0.0, 0.0, -2.0), Vector3d(0.0, 0.0, 0.0), Vector3d(0.0, 1.0, 0.0)));\n\tviewElement->addComponent(std::make_shared<SurgSim::Graphics::OsgAxesRepresentation>(\"axes\"));\n\n\n\t\/\/\/ Run the thread\n\truntime->start();\n\tboost::this_thread::sleep(boost::posix_time::milliseconds(500));\n\truntime->stop();\n\n}\n\nTEST_F(OsgShaderRenderTests, TexturedShinyShaderTest)\n{\n\t\/\/\/ Add the sphere representation to the view element, no need to make another scene element\n\tauto sceneElement = std::make_shared<SurgSim::Framework::BasicSceneElement>(\"Sphere\");\n\tstd::shared_ptr<SphereRepresentation> sphereRepresentation =\n\t\tstd::make_shared<OsgSphereRepresentation>(\"sphere representation\");\n\tsphereRepresentation->setRadius(0.25);\n\n\tviewElement->getCamera()->setAmbientColor(SurgSim::Math::Vector4d(0.2, 0.2, 0.2, 1.0));\n\n\tauto material = createMaterialWithShaders(*runtime->getApplicationData(), \"Shaders\/ds_mapping_material\");\n\tstd::shared_ptr<SurgSim::Graphics::UniformBase>\n\tuniform = std::make_shared<OsgUniform<SurgSim::Math::Vector4f>>(\"diffuseColor\");\n\tmaterial->addUniform(uniform);\n\tmaterial->setValue(\"diffuseColor\", SurgSim::Math::Vector4f(1.0, 1.0, 1.0, 1.0));\n\n\tuniform = std::make_shared<OsgUniform<SurgSim::Math::Vector4f>>(\"specularColor\");\n\tmaterial->addUniform(uniform);\n\tmaterial->setValue(\"specularColor\", SurgSim::Math::Vector4f(1.0, 1.0, 1.0, 1.0));\n\n\tuniform = std::make_shared<OsgUniform<float>>(\"shininess\");\n\tmaterial->addUniform(uniform);\n\tmaterial->setValue(\"shininess\", 32.0f);\n\n\tstd::string filename;\n\tEXPECT_TRUE(runtime->getApplicationData()->tryFindFile(\"Data\/Textures\/CheckerBoard.png\", &filename));\n\tauto texture = std::make_shared<SurgSim::Graphics::OsgTexture2d>();\n\ttexture->loadImage(filename);\n\tauto diffuseMapUniform =\n\t\tstd::make_shared<OsgTextureUniform<OsgTexture2d>>(\"diffuseMap\");\n\tdiffuseMapUniform->set(texture);\n\tmaterial->addUniform(diffuseMapUniform);\n\n\tmaterial->setValue(\"diffuseColor\", SurgSim::Math::Vector4f(0.8, 0.8, 0.1, 1.0));\n\tmaterial->setValue(\"specularColor\", SurgSim::Math::Vector4f(1.0, 1.0, 0.4, 1.0));\n\tmaterial->setValue(\"shininess\", 1.0f);\n\tsphereRepresentation->setMaterial(material);\n\tsceneElement->addComponent(sphereRepresentation);\n\tsceneElement->addComponent(std::make_shared<SurgSim::Graphics::OsgAxesRepresentation>(\"axes\"));\n\tscene->addSceneElement(sceneElement);\n\n\n\tsceneElement = std::make_shared<SurgSim::Framework::BasicSceneElement>(\"Light\");\n\tauto light = std::make_shared<SurgSim::Graphics::OsgLight>(\"Light\");\n\tlight->setDiffuseColor(SurgSim::Math::Vector4d(0.8, 0.8, 0.8, 1.0));\n\tlight->setSpecularColor(SurgSim::Math::Vector4d(0.8, 0.8, 0.8, 1.0));\n\tlight->setLightGroupReference(SurgSim::Graphics::Representation::DefaultGroupName);\n\tsceneElement->addComponent(light);\n\tsceneElement->addComponent(std::make_shared<SurgSim::Graphics::OsgAxesRepresentation>(\"axes\"));\n\tsceneElement->setPose(makeRigidTransform(Quaterniond::Identity(), Vector3d(-2.0, -2.0, -4.0)));\n\n\tsphereRepresentation = std::make_shared<OsgSphereRepresentation>(\"debug\");\n\tsphereRepresentation->setRadius(0.01);\n\tsceneElement->addComponent(sphereRepresentation);\n\n\tscene->addSceneElement(sceneElement);\n\n\t\/\/viewElement->enableManipulator(true);\n\n\tviewElement->setPose(makeRigidTransform(Vector3d(0.0, 0.0, -2.0),\n\t\t\t\t\t\t\t\t\t\t\tVector3d(0.0, 0.0, 0.0),\n\t\t\t\t\t\t\t\t\t\t\tVector3d(0.0, 1.0, 0.0)));\n\tviewElement->addComponent(std::make_shared<SurgSim::Graphics::OsgAxesRepresentation>(\"axes\"));\n\n\n\t\/\/\/ Run the thread\n\t\/\/ \truntime->start();\n\t\/\/ \tboost::this_thread::sleep(boost::posix_time::milliseconds(10000));\n\t\/\/ \truntime->stop();\n\truntime->execute();\n\n}\n\n}; \/\/ namespace Graphics\n\n}; \/\/ namespace SurgSim\n<|endoftext|>"} {"text":"<commit_before>#include \"TeslaCoilModuleControllerSystem.h\"\n#include \"ShipModule.h\"\n#include \"TeslaCoilModule.h\"\n#include \"ShipModulesTrackerSystem.h\"\n#include \"Transform.h\"\n#include \"PhysicsBody.h\"\n#include \"PhysicsSystem.h\"\n#include <PhysicsController.h>\n#include <TcpClient.h>\n#include \"NetworkSynced.h\"\n#include <RandomUtil.h>\n#include \"TeslaHitPacket.h\"\n#include <TcpServer.h>\n#include <algorithm>\n\nTeslaCoilModuleControllerSystem::TeslaCoilModuleControllerSystem(TcpServer* p_server)\n\t: EntitySystem(SystemType::TeslaCoilModuleControllerSystem, 5,\n\tComponentType::TeslaCoilModule, ComponentType::ShipModule, ComponentType::Transform,\n\tComponentType::PhysicsBody, ComponentType::NetworkSynced)\n{\n\tm_server = p_server;\n}\n\nvoid TeslaCoilModuleControllerSystem::processEntities( const vector<Entity*>& p_entities )\n{\n\tfloat dt = m_world->getDelta();\n\tfor(unsigned int i=0; i<p_entities.size(); i++)\n\t{\n\t\tShipModule* module = static_cast<ShipModule*>(p_entities[i]->getComponent(\n\t\t\tComponentType::ShipModule));\n\t\tif(module->isOwned())\n\t\t{\n\t\t\tTeslaCoilModule* teslaCoil = static_cast<TeslaCoilModule*>(\n\t\t\t\tp_entities[i]->getComponent(ComponentType::TeslaCoilModule));\n\t\t\tteslaCoil->cooldown -= dt;\n\t\t\tif(teslaCoil->cooldown <= 0.0f && module->getActive())\n\t\t\t{\n\t\t\t\tteslaCoil->cooldown = teslaCoil->cooldownTime;\n\t\t\t\tTransform* teslaTransform = static_cast<Transform*>(p_entities[i]->\n\t\t\t\t\tgetComponent(ComponentType::Transform));\n\t\t\t\tNetworkSynced* teslaNetsync = static_cast<NetworkSynced*>(p_entities[i]->\n\t\t\t\t\tgetComponent(ComponentType::NetworkSynced));\n\t\t\t\tShipModule* teslaShipModule = static_cast<ShipModule*>(p_entities[i]->\n\t\t\t\t\tgetComponent(ComponentType::ShipModule));\n\t\t\t\tfireTeslaCoil(p_entities[i], teslaCoil, teslaTransform, teslaNetsync,\n\t\t\t\t\tteslaShipModule);\n\t\t\t}\n\t\t}\n\t}\n}\n\nvoid TeslaCoilModuleControllerSystem::fireTeslaCoil(Entity* p_teslaEntity,\n\tTeslaCoilModule* p_teslaModule, Transform* p_teslaTransform,\n\tNetworkSynced* p_teslaNetsync, ShipModule* p_teslaShipModule)\n{\n\tvector<int> entitiesHit;\n\tShipModulesTrackerSystem* moduleTracker = static_cast<\n\t\tShipModulesTrackerSystem*>(m_world->getSystem(\n\t\tSystemType::ShipModulesTrackerSystem));\n\tAglVector3 teslaPosition = p_teslaTransform->getTranslation();\n\tfor(unsigned int otherModuleIndex=0;\n\t\totherModuleIndex<moduleTracker->getActiveEntities().size();\n\t\totherModuleIndex++)\n\t{\n\t\tEntity* otherModule = moduleTracker->getActiveEntities()[otherModuleIndex];\n\t\tAglVector3 otherModulePosition = static_cast<Transform*>(otherModule->getComponent(\n\t\t\tComponentType::Transform))->getTranslation();\n\t\tAglVector3 distanceVector = otherModulePosition - teslaPosition;\n\t\tif(distanceVector.lengthSquared() < p_teslaModule->range * p_teslaModule->range)\n\t\t{\n\t\t\tPhysicsBody* body = static_cast<PhysicsBody*>(\n\t\t\t\totherModule->getComponent(ComponentType::PhysicsBody));\n\t\t\tShipModule* otherShipModule = static_cast<ShipModule*>(\n\t\t\t\totherModule->getComponent(ComponentType::ShipModule));\n\t\t\tfloat distance = distanceVector.length();\n\t\t\tfloat hitChance = calculateHitChance(distance, p_teslaModule->optimalRange,\n\t\t\t\tp_teslaModule->range);\n\t\t\tif(RandomUtil::randomSingle() <= hitChance)\n\t\t\t{\n\t\t\t\tif(otherShipModule->m_parentEntity != p_teslaShipModule->m_parentEntity)\n\t\t\t\t{\n\t\t\t\t\totherShipModule->addDamageThisTick(hitChance * p_teslaModule->damage,\n\t\t\t\t\t\tp_teslaNetsync->getNetworkOwner());\n\t\t\t\t\tentitiesHit.push_back(otherModule->getIndex());\n\t\t\t\t}\n\t\t\t}\n\t\t}\/\/if\n\t}\/\/for: otherModuleIndex\n\tif(!entitiesHit.empty())\n\t{\n\t\t\/\/struct lengthCompare\n\t\t\/\/{\n\t\t\/\/\tEntityWorld* world;\n\t\t\/\/\tAglVector3 sourcePosition;\n\t\t\/\/\tlengthCompare(EntityWorld* p_world, AglVector3 p_sourcePosition)\n\t\t\/\/\t{\n\t\t\/\/\t\tworld = p_world;\n\t\t\/\/\t\tsourcePosition = p_sourcePosition;\n\t\t\/\/\t}\n\t\t\/\/\tbool operator() (int i, int j)\n\t\t\/\/\t{\n\t\t\/\/\t}\n\t\t\/\/} myLengthCompare(m_world, static_cast<Transform*>(p_teslaEntity->getComponent(\n\t\t\/\/\tComponentType::Transform))->getTranslation());\n\t\tunsigned int i=0;\n\t\tTeslaHitPacket hitPacket;\n\t\thitPacket.identitySource = p_teslaEntity->getIndex();\n\t\twhile(i < (unsigned int)hitPacket.NUM_TESLA_HITS_MAX && i < entitiesHit.size())\n\t\t{\n\t\t\thitPacket.identitiesHit[i] = entitiesHit[i];\n\t\t\ti++;\n\t\t}\n\t\thitPacket.numberOfHits = static_cast<unsigned char>(i);\n\t\tm_server->broadcastPacket(hitPacket.pack());\n\t}\n}\n\nfloat TeslaCoilModuleControllerSystem::calculateHitChance(float p_distance,\n\tfloat p_optimalRange, float p_range)\n{\n\tfloat hitChance = 1.0f;\n\tif(p_distance > p_optimalRange)\n\t{\n\t\thitChance = 1.0f - (p_distance - p_optimalRange) \/\n\t\t\t(p_range - p_optimalRange);\n\t}\n\treturn hitChance;\n}<commit_msg>Made so that Tesla coil fires on the 10 closest target modules (if there are 10 or more within range).<commit_after>#include \"TeslaCoilModuleControllerSystem.h\"\n#include \"ShipModule.h\"\n#include \"TeslaCoilModule.h\"\n#include \"ShipModulesTrackerSystem.h\"\n#include \"Transform.h\"\n#include \"PhysicsBody.h\"\n#include \"PhysicsSystem.h\"\n#include <PhysicsController.h>\n#include <TcpClient.h>\n#include \"NetworkSynced.h\"\n#include <RandomUtil.h>\n#include \"TeslaHitPacket.h\"\n#include <TcpServer.h>\n#include <algorithm>\n\nTeslaCoilModuleControllerSystem::TeslaCoilModuleControllerSystem(TcpServer* p_server)\n\t: EntitySystem(SystemType::TeslaCoilModuleControllerSystem, 5,\n\tComponentType::TeslaCoilModule, ComponentType::ShipModule, ComponentType::Transform,\n\tComponentType::PhysicsBody, ComponentType::NetworkSynced)\n{\n\tm_server = p_server;\n}\n\nvoid TeslaCoilModuleControllerSystem::processEntities( const vector<Entity*>& p_entities )\n{\n\tfloat dt = m_world->getDelta();\n\tfor(unsigned int i=0; i<p_entities.size(); i++)\n\t{\n\t\tShipModule* module = static_cast<ShipModule*>(p_entities[i]->getComponent(\n\t\t\tComponentType::ShipModule));\n\t\tif(module->isOwned())\n\t\t{\n\t\t\tTeslaCoilModule* teslaCoil = static_cast<TeslaCoilModule*>(\n\t\t\t\tp_entities[i]->getComponent(ComponentType::TeslaCoilModule));\n\t\t\tteslaCoil->cooldown -= dt;\n\t\t\tif(teslaCoil->cooldown <= 0.0f && module->getActive())\n\t\t\t{\n\t\t\t\tteslaCoil->cooldown = teslaCoil->cooldownTime;\n\t\t\t\tTransform* teslaTransform = static_cast<Transform*>(p_entities[i]->\n\t\t\t\t\tgetComponent(ComponentType::Transform));\n\t\t\t\tNetworkSynced* teslaNetsync = static_cast<NetworkSynced*>(p_entities[i]->\n\t\t\t\t\tgetComponent(ComponentType::NetworkSynced));\n\t\t\t\tShipModule* teslaShipModule = static_cast<ShipModule*>(p_entities[i]->\n\t\t\t\t\tgetComponent(ComponentType::ShipModule));\n\t\t\t\tfireTeslaCoil(p_entities[i], teslaCoil, teslaTransform, teslaNetsync,\n\t\t\t\t\tteslaShipModule);\n\t\t\t}\n\t\t}\n\t}\n}\n\nvoid TeslaCoilModuleControllerSystem::fireTeslaCoil(Entity* p_teslaEntity,\n\tTeslaCoilModule* p_teslaModule, Transform* p_teslaTransform,\n\tNetworkSynced* p_teslaNetsync, ShipModule* p_teslaShipModule)\n{\n\tvector<int> entitiesHit;\n\tShipModulesTrackerSystem* moduleTracker = static_cast<\n\t\tShipModulesTrackerSystem*>(m_world->getSystem(\n\t\tSystemType::ShipModulesTrackerSystem));\n\tAglVector3 teslaPosition = p_teslaTransform->getTranslation();\n\tfor(unsigned int otherModuleIndex=0;\n\t\totherModuleIndex<moduleTracker->getActiveEntities().size();\n\t\totherModuleIndex++)\n\t{\n\t\tEntity* otherModule = moduleTracker->getActiveEntities()[otherModuleIndex];\n\t\tAglVector3 otherModulePosition = static_cast<Transform*>(otherModule->getComponent(\n\t\t\tComponentType::Transform))->getTranslation();\n\t\tAglVector3 distanceVector = otherModulePosition - teslaPosition;\n\t\tif(distanceVector.lengthSquared() < p_teslaModule->range * p_teslaModule->range)\n\t\t{\n\t\t\tPhysicsBody* body = static_cast<PhysicsBody*>(\n\t\t\t\totherModule->getComponent(ComponentType::PhysicsBody));\n\t\t\tShipModule* otherShipModule = static_cast<ShipModule*>(\n\t\t\t\totherModule->getComponent(ComponentType::ShipModule));\n\t\t\tfloat distance = distanceVector.length();\n\t\t\tfloat hitChance = calculateHitChance(distance, p_teslaModule->optimalRange,\n\t\t\t\tp_teslaModule->range);\n\t\t\tif(RandomUtil::randomSingle() <= hitChance)\n\t\t\t{\n\t\t\t\tif(otherShipModule->m_parentEntity != p_teslaShipModule->m_parentEntity)\n\t\t\t\t{\n\t\t\t\t\totherShipModule->addDamageThisTick(hitChance * p_teslaModule->damage,\n\t\t\t\t\t\tp_teslaNetsync->getNetworkOwner());\n\t\t\t\t\tentitiesHit.push_back(otherModule->getIndex());\n\t\t\t\t}\n\t\t\t}\n\t\t}\/\/if\n\t}\/\/for: otherModuleIndex\n\tif(!entitiesHit.empty())\n\t{\n\t\t\/\/ Compare functor\n\t\tstruct LengthCompare\n\t\t{\n\t\t\tEntityWorld* world;\n\t\t\tAglVector3 sourcePosition;\n\t\t\tLengthCompare(EntityWorld* p_world, AglVector3 p_sourcePosition)\n\t\t\t{\n\t\t\t\tworld = p_world;\n\t\t\t\tsourcePosition = p_sourcePosition;\n\t\t\t}\n\t\t\tbool operator() (int p_firstIndex, int p_secondIndex)\n\t\t\t{\n\t\t\t\tAglVector3 firstPosition = static_cast<Transform*>(\n\t\t\t\t\tworld->getComponentManager()->getComponent(p_firstIndex,\n\t\t\t\t\tComponentType::Transform))->getTranslation();\n\t\t\t\tAglVector3 secondPosition = static_cast<Transform*>(\n\t\t\t\t\tworld->getComponentManager()->getComponent(p_secondIndex,\n\t\t\t\t\tComponentType::Transform))->getTranslation();\n\t\t\t\tfloat firstLengthSquared = (firstPosition - sourcePosition).lengthSquared();\n\t\t\t\tfloat secondLengthSquared = (secondPosition - sourcePosition).lengthSquared();\n\t\t\t\treturn firstLengthSquared < secondLengthSquared;\n\t\t\t}\n\t\t} myLengthCompare(m_world, static_cast<Transform*>(p_teslaEntity->getComponent(\n\t\t\tComponentType::Transform))->getTranslation());\n\n\t\tstd::sort(entitiesHit.begin(), entitiesHit.begin() + entitiesHit.size(), myLengthCompare);\n\t\tunsigned int i=0;\n\t\tTeslaHitPacket hitPacket;\n\t\thitPacket.identitySource = p_teslaEntity->getIndex();\n\t\twhile(i < (unsigned int)hitPacket.NUM_TESLA_HITS_MAX && i < entitiesHit.size())\n\t\t{\n\t\t\thitPacket.identitiesHit[i] = entitiesHit[i];\n\t\t\ti++;\n\t\t}\n\t\thitPacket.numberOfHits = static_cast<unsigned char>(i);\n\t\tm_server->broadcastPacket(hitPacket.pack());\n\t}\n}\n\nfloat TeslaCoilModuleControllerSystem::calculateHitChance(float p_distance,\n\tfloat p_optimalRange, float p_range)\n{\n\tfloat hitChance = 1.0f;\n\tif(p_distance > p_optimalRange)\n\t{\n\t\thitChance = 1.0f - (p_distance - p_optimalRange) \/\n\t\t\t(p_range - p_optimalRange);\n\t}\n\treturn hitChance;\n}<|endoftext|>"} {"text":"<commit_before>\/*\n** Author(s):\n** - Cedric GESTES <gestes@aldebaran-robotics.com>\n**\n** Copyright (C) 2010 Aldebaran Robotics\n*\/\n\n#ifndef AL_MESSAGING_SLEEP_HXX_\n# define AL_MESSAGING_SLEEP_HXX_\n\n#ifdef _WIN32\n# define sleep(x) Sleep(x * 1000)\n#else\n# include <unistd.h>\n#endif\n\n#endif \/* !AL_MESSAGING_SLEEP_HXX_ *\/\n<commit_msg>Fixed sleep<commit_after>\/*\n** Author(s):\n** - Cedric GESTES <gestes@aldebaran-robotics.com>\n**\n** Copyright (C) 2010 Aldebaran Robotics\n*\/\n\n#ifndef AL_MESSAGING_SLEEP_HXX_\n# define AL_MESSAGING_SLEEP_HXX_\n\n#ifdef _WIN32\n# include <winsock2.h>\n# define sleep(x) Sleep(x * 1000)\n#else\n# include <unistd.h>\n#endif\n\n#endif \/* !AL_MESSAGING_SLEEP_HXX_ *\/\n<|endoftext|>"} {"text":"<commit_before>\/*=========================================================================\n\n Program: ORFEO Toolbox\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n\n Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.\n See OTBCopyright.txt for details.\n\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notices for more information.\n\n=========================================================================*\/\n#include \"otbImage.h\"\n#include \"otbVectorImage.h\"\n#include \"otbImageFileReader.h\"\n#include \"otbImageFileWriter.h\"\n\n#include \"otbDotProductImageFilter.h\"\n#include \"otbProjectiveProjectionImageFilter.h\"\n#include \"otbMatrixImageFilter.h\"\n#include \"otbVectorImageToMatrixImageFilter.h\"\n#include \"otbStreamingStatisticsImageFilter.h\"\n#include \"otbStreamingStatisticsVectorImageFilter.h\"\n\nconst unsigned int Dimension = 2;\ntypedef double PixelType;\ntypedef double PrecisionType;\n\ntypedef otb::Image<PixelType, Dimension> ImageType;\ntypedef otb::VectorImage<PixelType, Dimension> VectorImageType;\ntypedef otb::ImageFileReader<VectorImageType> ReaderType;\ntypedef otb::ProjectiveProjectionImageFilter<VectorImageType, VectorImageType, PrecisionType> ProjectiveProjectionImageFilterType;\ntypedef otb::DotProductImageFilter<VectorImageType, ImageType> DotProductImageFilterType;\ntypedef otb::MatrixImageFilter<VectorImageType, VectorImageType> MatrixImageFilterType;\ntypedef otb::VectorImageToMatrixImageFilter<VectorImageType> VectorImageToMatrixImageFilterType;\ntypedef otb::ImageFileWriter<VectorImageType> WriterType;\ntypedef otb::StreamingStatisticsVectorImageFilter<VectorImageType> StreamingStatisticsVectorImageFilterType;\ntypedef otb::StreamingStatisticsImageFilter<ImageType> StreamingStatisticsImageFilterType;\n\ntypedef StreamingStatisticsVectorImageFilterType::MatrixType MatrixType;\n\nint otbProjectiveProjectionNew(int argc, char * argv[])\n{\n ProjectiveProjectionImageFilterType::Pointer filter = ProjectiveProjectionImageFilterType::New();\n std::cout << filter << std::endl;\n return EXIT_SUCCESS;\n}\n\nint otbProjectiveProjectionTestHighSNR(int argc, char * argv[])\n{\n const char * inputImage = argv[1];\n const unsigned int nbEndmembers = atoi(argv[2]);\n const char * outputImage = argv[3];\n\n\n ReaderType::Pointer readerImage = ReaderType::New();\n readerImage->SetFileName(inputImage);\n\n std::cout << \"Computing image stats\" << std::endl;\n StreamingStatisticsVectorImageFilterType::Pointer statsInput = \\\n StreamingStatisticsVectorImageFilterType::New();\n\n statsInput->SetInput(readerImage->GetOutput());\n statsInput->Update();\n\n std::cout << \"Computing SVD of correlation matrix\" << std::endl;\n \/\/ Take the correlation matrix\n vnl_matrix<PrecisionType> R = statsInput->GetCorrelation().GetVnlMatrix();\n\n \/\/ Apply SVD\n vnl_svd<PrecisionType> svd(R);\n vnl_matrix<PrecisionType> U = svd.U();\n vnl_matrix<PrecisionType> Ud = U.get_n_columns(0, nbEndmembers).transpose();\n\n std::cout << \"Apply dimensionnality reduction\" << std::endl;\n \/\/ Xd = Ud.'*M;\n MatrixImageFilterType::Pointer mulUd = MatrixImageFilterType::New();\n mulUd->SetInput(readerImage->GetOutput());\n mulUd->SetMatrix(Ud);\n mulUd->UpdateOutputInformation();\n\n VectorImageType::Pointer Xd = mulUd->GetOutput();\n\n \/\/ Compute mean(Xd)\n std::cout << \"Compute mean(Xd)\" << std::endl;\n StreamingStatisticsVectorImageFilterType::Pointer statsXd = \\\n StreamingStatisticsVectorImageFilterType::New();\n statsXd->SetInput(Xd);\n statsXd->Update();\n VectorImageType::PixelType Xdmean = statsXd->GetMean();\n\n \/\/ Compute Xd .\/ repmat( sum( Xd .* repmat(u, [1 N]) ) , [d 1]);\n \/\/ -> divides each pixel component by the dot product <Xd(i, j), mean(Xd)>\n std::cout << \"Compute projective projection\" << std::endl;\n ProjectiveProjectionImageFilterType::Pointer proj = ProjectiveProjectionImageFilterType::New();\n proj->SetInput(Xd);\n proj->SetProjectionDirection(Xdmean);\n\n std::cout << \"Write output\" << std::endl;\n WriterType::Pointer writer = WriterType::New();\n writer->SetFileName(outputImage);\n writer->SetInput(proj->GetOutput());\n writer->Update();\n\n return EXIT_SUCCESS;\n}\n<commit_msg>ENH: fix ProjectiveProjection test<commit_after>\/*=========================================================================\n\n Program: ORFEO Toolbox\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n\n Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.\n See OTBCopyright.txt for details.\n\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notices for more information.\n\n=========================================================================*\/\n#include \"otbImage.h\"\n#include \"otbVectorImage.h\"\n#include \"otbImageFileReader.h\"\n#include \"otbImageFileWriter.h\"\n\n#include \"otbDotProductImageFilter.h\"\n#include \"otbProjectiveProjectionImageFilter.h\"\n#include \"otbMatrixImageFilter.h\"\n#include \"otbVectorImageToMatrixImageFilter.h\"\n#include \"otbStreamingStatisticsImageFilter.h\"\n#include \"otbStreamingStatisticsVectorImageFilter.h\"\n\nconst unsigned int Dimension = 2;\ntypedef double PixelType;\ntypedef double PrecisionType;\n\ntypedef otb::Image<PixelType, Dimension> ImageType;\ntypedef otb::VectorImage<PixelType, Dimension> VectorImageType;\ntypedef otb::ImageFileReader<VectorImageType> ReaderType;\ntypedef otb::ProjectiveProjectionImageFilter<VectorImageType, VectorImageType, PrecisionType> ProjectiveProjectionImageFilterType;\ntypedef otb::DotProductImageFilter<VectorImageType, ImageType> DotProductImageFilterType;\ntypedef otb::MatrixImageFilter<VectorImageType, VectorImageType> MatrixImageFilterType;\ntypedef otb::VectorImageToMatrixImageFilter<VectorImageType> VectorImageToMatrixImageFilterType;\ntypedef otb::ImageFileWriter<VectorImageType> WriterType;\ntypedef otb::StreamingStatisticsVectorImageFilter<VectorImageType> StreamingStatisticsVectorImageFilterType;\ntypedef otb::StreamingStatisticsImageFilter<ImageType> StreamingStatisticsImageFilterType;\n\ntypedef StreamingStatisticsVectorImageFilterType::MatrixType MatrixType;\n\nint otbProjectiveProjectionNew(int argc, char * argv[])\n{\n ProjectiveProjectionImageFilterType::Pointer filter = ProjectiveProjectionImageFilterType::New();\n std::cout << filter << std::endl;\n return EXIT_SUCCESS;\n}\n\nint otbProjectiveProjectionTestHighSNR(int argc, char * argv[])\n{\n const char * inputImage = argv[1];\n const unsigned int nbEndmembers = atoi(argv[2]);\n const char * outputImage = argv[3];\n\n\n ReaderType::Pointer readerImage = ReaderType::New();\n readerImage->SetFileName(inputImage);\n\n std::cout << \"Computing image stats\" << std::endl;\n StreamingStatisticsVectorImageFilterType::Pointer statsInput = \\\n StreamingStatisticsVectorImageFilterType::New();\n\n statsInput->SetInput(readerImage->GetOutput());\n statsInput->Update();\n\n std::cout << \"Computing SVD of correlation matrix\" << std::endl;\n \/\/ Take the correlation matrix\n vnl_matrix<PrecisionType> R = statsInput->GetCorrelation().GetVnlMatrix();\n\n \/\/ Apply SVD\n vnl_svd<PrecisionType> svd(R);\n vnl_matrix<PrecisionType> U = svd.U();\n vnl_matrix<PrecisionType> Ud = U.get_n_columns(0, nbEndmembers).transpose();\n\n std::cout << \"Apply dimensionnality reduction\" << std::endl;\n \/\/ Xd = Ud.'*M;\n MatrixImageFilterType::Pointer mulUd = MatrixImageFilterType::New();\n mulUd->SetInput(readerImage->GetOutput());\n mulUd->SetMatrix(Ud);\n mulUd->MatrixByVectorOn();\n mulUd->UpdateOutputInformation();\n\n VectorImageType::Pointer Xd = mulUd->GetOutput();\n\n \/\/ Compute mean(Xd)\n std::cout << \"Compute mean(Xd)\" << std::endl;\n StreamingStatisticsVectorImageFilterType::Pointer statsXd = \\\n StreamingStatisticsVectorImageFilterType::New();\n statsXd->SetInput(Xd);\n statsXd->Update();\n VectorImageType::PixelType Xdmean = statsXd->GetMean();\n\n \/\/ Compute Xd .\/ repmat( sum( Xd .* repmat(u, [1 N]) ) , [d 1]);\n \/\/ -> divides each pixel component by the dot product <Xd(i, j), mean(Xd)>\n std::cout << \"Compute projective projection\" << std::endl;\n ProjectiveProjectionImageFilterType::Pointer proj = ProjectiveProjectionImageFilterType::New();\n proj->SetInput(Xd);\n proj->SetProjectionDirection(Xdmean);\n\n std::cout << \"Write output\" << std::endl;\n WriterType::Pointer writer = WriterType::New();\n writer->SetFileName(outputImage);\n writer->SetInput(proj->GetOutput());\n writer->Update();\n\n return EXIT_SUCCESS;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\nThe MIT License (MIT)\n\nCopyright (c) 2013-2014 winlin\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of\nthis software and associated documentation files (the \"Software\"), to deal in\nthe Software without restriction, including without limitation the rights to\nuse, copy, modify, merge, publish, distribute, sublicense, and\/or sell copies of\nthe Software, and to permit persons to whom the Software is furnished to do so,\nsubject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS\nFOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\nCOPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\nIN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\nCONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n*\/\n\n#include <htl_stdinc.hpp>\n\n#include <inttypes.h>\n#include <stdlib.h>\n\n#include <string>\n#include <sstream>\nusing namespace std;\n\n#include <htl_core_error.hpp>\n#include <htl_core_log.hpp>\n#include <htl_app_rtmp_play.hpp>\n#include <htl_app_rtmp_publish.hpp>\n\n#include <htl_app_rtmp_load.hpp>\n\nStRtmpTask::StRtmpTask(){\n}\n\nStRtmpTask::~StRtmpTask(){\n}\n\nint StRtmpTask::Initialize(string http_url, double startup, double delay, double error, int count){\n int ret = ERROR_SUCCESS;\n \n if((ret = InitializeBase(http_url, startup, delay, error, count)) != ERROR_SUCCESS){\n return ret;\n }\n \n return ret;\n}\n\nUri* StRtmpTask::GetUri(){\n return &url;\n}\n\nint StRtmpTask::ProcessTask(){\n int ret = ERROR_SUCCESS;\n \n Trace(\"start to process RTMP play task #%d, schema=%s, host=%s, port=%d, tcUrl=%s, stream=%s, startup=%.2f, delay=%.2f, error=%.2f, count=%d\", \n GetId(), url.GetSchema(), url.GetHost(), url.GetPort(), url.GetTcUrl(), url.GetStream(), startup_seconds, delay_seconds, error_seconds, count);\n \n StRtmpPlayClient client;\n \n \/\/ if count is zero, infinity loop.\n for(int i = 0; count == 0 || i < count; i++){\n statistic->OnTaskStart(GetId(), url.GetUrl());\n \n if((ret = client.Dump(&url)) != ERROR_SUCCESS){\n statistic->OnTaskError(GetId(), 0);\n \n Error(\"rtmp client dump url failed. ret=%d\", ret);\n st_usleep((st_utime_t)(error_seconds * 1000 * 1000));\n continue;\n }\n \n int sleep_ms = StUtility::BuildRandomMTime((delay_seconds >= 0)? delay_seconds:0);\n Trace(\"[RTMP] %s dump success, sleep %dms\", url.GetUrl(), sleep_ms);\n st_usleep(sleep_ms * 1000);\n \n statistic->OnTaskEnd(GetId(), 0);\n }\n \n return ret;\n}\n\nStRtmpTaskFast::StRtmpTaskFast(){\n}\n\nStRtmpTaskFast::~StRtmpTaskFast(){\n}\n\nint StRtmpTaskFast::Initialize(string http_url, double startup, double delay, double error, int count){\n int ret = ERROR_SUCCESS;\n \n if((ret = InitializeBase(http_url, startup, delay, error, count)) != ERROR_SUCCESS){\n return ret;\n }\n \n return ret;\n}\n\nUri* StRtmpTaskFast::GetUri(){\n return &url;\n}\n\nint StRtmpTaskFast::ProcessTask(){\n int ret = ERROR_SUCCESS;\n \n Trace(\"start to process RTMP play fast task #%d, schema=%s, host=%s, port=%d, tcUrl=%s, stream=%s, startup=%.2f, delay=%.2f, error=%.2f, count=%d\", \n GetId(), url.GetSchema(), url.GetHost(), url.GetPort(), url.GetTcUrl(), url.GetStream(), startup_seconds, delay_seconds, error_seconds, count);\n \n StRtmpPlayClient client;\n \n \/\/ if count is zero, infinity loop.\n for(int i = 0; count == 0 || i < count; i++){\n statistic->OnTaskStart(GetId(), url.GetUrl());\n \n if((ret = client.Dump(&url)) != ERROR_SUCCESS){\n statistic->OnTaskError(GetId(), 0);\n \n Error(\"rtmp client dump url failed. ret=%d\", ret);\n st_usleep((st_utime_t)(error_seconds * 1000 * 1000));\n continue;\n }\n \n int sleep_ms = StUtility::BuildRandomMTime((delay_seconds >= 0)? delay_seconds:0);\n Trace(\"[RTMP] %s dump success, sleep %dms\", url.GetUrl(), sleep_ms);\n st_usleep(sleep_ms * 1000);\n \n statistic->OnTaskEnd(GetId(), 0);\n }\n \n return ret;\n}\n\nStRtmpPublishTask::StRtmpPublishTask(){\n}\n\nStRtmpPublishTask::~StRtmpPublishTask(){\n}\n\nint StRtmpPublishTask::Initialize(string input, string http_url, double startup, double delay, double error, int count){\n int ret = ERROR_SUCCESS;\n \n input_flv_file = input;\n \n if((ret = InitializeBase(http_url, startup, delay, error, count)) != ERROR_SUCCESS){\n return ret;\n }\n \n return ret;\n}\n\nUri* StRtmpPublishTask::GetUri(){\n return &url;\n}\n\nint StRtmpPublishTask::ProcessTask(){\n int ret = ERROR_SUCCESS;\n \n Trace(\"start to process RTMP publish task #%d, schema=%s, host=%s, port=%d, tcUrl=%s, stream=%s, startup=%.2f, delay=%.2f, error=%.2f, count=%d\", \n GetId(), url.GetSchema(), url.GetHost(), url.GetPort(), url.GetTcUrl(), url.GetStream(), startup_seconds, delay_seconds, error_seconds, count);\n \n StRtmpPublishClient client;\n \n \/\/ if count is zero, infinity loop.\n for(int i = 0; count == 0 || i < count; i++){\n statistic->OnTaskStart(GetId(), url.GetUrl());\n \n if((ret = client.Publish(input_flv_file, &url)) != ERROR_SUCCESS){\n statistic->OnTaskError(GetId(), 0);\n \n Error(\"rtmp client publish url failed. ret=%d\", ret);\n st_usleep((st_utime_t)(error_seconds * 1000 * 1000));\n continue;\n }\n \n int sleep_ms = StUtility::BuildRandomMTime((delay_seconds >= 0)? delay_seconds:0);\n Trace(\"[RTMP] %s publish success, sleep %dms\", url.GetUrl(), sleep_ms);\n st_usleep(sleep_ms * 1000);\n \n statistic->OnTaskEnd(GetId(), 0);\n }\n \n return ret;\n}\n\n<commit_msg>use fast rtmp client.<commit_after>\/*\nThe MIT License (MIT)\n\nCopyright (c) 2013-2014 winlin\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of\nthis software and associated documentation files (the \"Software\"), to deal in\nthe Software without restriction, including without limitation the rights to\nuse, copy, modify, merge, publish, distribute, sublicense, and\/or sell copies of\nthe Software, and to permit persons to whom the Software is furnished to do so,\nsubject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS\nFOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\nCOPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\nIN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\nCONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n*\/\n\n#include <htl_stdinc.hpp>\n\n#include <inttypes.h>\n#include <stdlib.h>\n\n#include <string>\n#include <sstream>\nusing namespace std;\n\n#include <htl_core_error.hpp>\n#include <htl_core_log.hpp>\n#include <htl_app_rtmp_play.hpp>\n#include <htl_app_rtmp_publish.hpp>\n\n#include <htl_app_rtmp_load.hpp>\n\nStRtmpTask::StRtmpTask(){\n}\n\nStRtmpTask::~StRtmpTask(){\n}\n\nint StRtmpTask::Initialize(string http_url, double startup, double delay, double error, int count){\n int ret = ERROR_SUCCESS;\n \n if((ret = InitializeBase(http_url, startup, delay, error, count)) != ERROR_SUCCESS){\n return ret;\n }\n \n return ret;\n}\n\nUri* StRtmpTask::GetUri(){\n return &url;\n}\n\nint StRtmpTask::ProcessTask(){\n int ret = ERROR_SUCCESS;\n \n Trace(\"start to process RTMP play task #%d, schema=%s, host=%s, port=%d, tcUrl=%s, stream=%s, startup=%.2f, delay=%.2f, error=%.2f, count=%d\", \n GetId(), url.GetSchema(), url.GetHost(), url.GetPort(), url.GetTcUrl(), url.GetStream(), startup_seconds, delay_seconds, error_seconds, count);\n \n StRtmpPlayClient client;\n \n \/\/ if count is zero, infinity loop.\n for(int i = 0; count == 0 || i < count; i++){\n statistic->OnTaskStart(GetId(), url.GetUrl());\n \n if((ret = client.Dump(&url)) != ERROR_SUCCESS){\n statistic->OnTaskError(GetId(), 0);\n \n Error(\"rtmp client dump url failed. ret=%d\", ret);\n st_usleep((st_utime_t)(error_seconds * 1000 * 1000));\n continue;\n }\n \n int sleep_ms = StUtility::BuildRandomMTime((delay_seconds >= 0)? delay_seconds:0);\n Trace(\"[RTMP] %s dump success, sleep %dms\", url.GetUrl(), sleep_ms);\n st_usleep(sleep_ms * 1000);\n \n statistic->OnTaskEnd(GetId(), 0);\n }\n \n return ret;\n}\n\nStRtmpTaskFast::StRtmpTaskFast(){\n}\n\nStRtmpTaskFast::~StRtmpTaskFast(){\n}\n\nint StRtmpTaskFast::Initialize(string http_url, double startup, double delay, double error, int count){\n int ret = ERROR_SUCCESS;\n \n if((ret = InitializeBase(http_url, startup, delay, error, count)) != ERROR_SUCCESS){\n return ret;\n }\n \n return ret;\n}\n\nUri* StRtmpTaskFast::GetUri(){\n return &url;\n}\n\nint StRtmpTaskFast::ProcessTask(){\n int ret = ERROR_SUCCESS;\n \n Trace(\"start to process RTMP play fast task #%d, schema=%s, host=%s, port=%d, tcUrl=%s, stream=%s, startup=%.2f, delay=%.2f, error=%.2f, count=%d\", \n GetId(), url.GetSchema(), url.GetHost(), url.GetPort(), url.GetTcUrl(), url.GetStream(), startup_seconds, delay_seconds, error_seconds, count);\n \n StRtmpPlayClientFast client;\n \n \/\/ if count is zero, infinity loop.\n for(int i = 0; count == 0 || i < count; i++){\n statistic->OnTaskStart(GetId(), url.GetUrl());\n \n if((ret = client.Dump(&url)) != ERROR_SUCCESS){\n statistic->OnTaskError(GetId(), 0);\n \n Error(\"rtmp client dump url failed. ret=%d\", ret);\n st_usleep((st_utime_t)(error_seconds * 1000 * 1000));\n continue;\n }\n \n int sleep_ms = StUtility::BuildRandomMTime((delay_seconds >= 0)? delay_seconds:0);\n Trace(\"[RTMP] %s dump success, sleep %dms\", url.GetUrl(), sleep_ms);\n st_usleep(sleep_ms * 1000);\n \n statistic->OnTaskEnd(GetId(), 0);\n }\n \n return ret;\n}\n\nStRtmpPublishTask::StRtmpPublishTask(){\n}\n\nStRtmpPublishTask::~StRtmpPublishTask(){\n}\n\nint StRtmpPublishTask::Initialize(string input, string http_url, double startup, double delay, double error, int count){\n int ret = ERROR_SUCCESS;\n \n input_flv_file = input;\n \n if((ret = InitializeBase(http_url, startup, delay, error, count)) != ERROR_SUCCESS){\n return ret;\n }\n \n return ret;\n}\n\nUri* StRtmpPublishTask::GetUri(){\n return &url;\n}\n\nint StRtmpPublishTask::ProcessTask(){\n int ret = ERROR_SUCCESS;\n \n Trace(\"start to process RTMP publish task #%d, schema=%s, host=%s, port=%d, tcUrl=%s, stream=%s, startup=%.2f, delay=%.2f, error=%.2f, count=%d\", \n GetId(), url.GetSchema(), url.GetHost(), url.GetPort(), url.GetTcUrl(), url.GetStream(), startup_seconds, delay_seconds, error_seconds, count);\n \n StRtmpPublishClient client;\n \n \/\/ if count is zero, infinity loop.\n for(int i = 0; count == 0 || i < count; i++){\n statistic->OnTaskStart(GetId(), url.GetUrl());\n \n if((ret = client.Publish(input_flv_file, &url)) != ERROR_SUCCESS){\n statistic->OnTaskError(GetId(), 0);\n \n Error(\"rtmp client publish url failed. ret=%d\", ret);\n st_usleep((st_utime_t)(error_seconds * 1000 * 1000));\n continue;\n }\n \n int sleep_ms = StUtility::BuildRandomMTime((delay_seconds >= 0)? delay_seconds:0);\n Trace(\"[RTMP] %s publish success, sleep %dms\", url.GetUrl(), sleep_ms);\n st_usleep(sleep_ms * 1000);\n \n statistic->OnTaskEnd(GetId(), 0);\n }\n \n return ret;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"base\/lock_impl.h\"\n\n#include <errno.h>\n\n#include \"base\/logging.h\"\n\nLockImpl::LockImpl() {\n#ifndef NDEBUG\n \/\/ In debug, setup attributes for lock error checking.\n pthread_mutexattr_t mta;\n int rv = pthread_mutexattr_init(&mta);\n DCHECK(rv == 0);\n rv = pthread_mutexattr_settype(&mta, PTHREAD_MUTEX_ERRORCHECK);\n DCHECK(rv == 0);\n rv = pthread_mutex_init(&os_lock_, &mta);\n DCHECK(rv == 0);\n rv = pthread_mutexattr_destroy(&mta);\n DCHECK(rv == 0);\n#else\n \/\/ In release, go with the default lock attributes.\n pthread_mutex_init(&os_lock_, NULL);\n#endif\n}\n\nLockImpl::~LockImpl() {\n int rv = pthread_mutex_destroy(&os_lock_);\n DCHECK(rv == 0);\n}\n\nbool LockImpl::Try() {\n int rv = pthread_mutex_trylock(&os_lock_);\n DCHECK(rv == 0 || rv == EBUSY);\n return rv == 0;\n}\n\nvoid LockImpl::Lock() {\n int rv = pthread_mutex_lock(&os_lock_);\n DCHECK(rv == 0);\n}\n\nvoid LockImpl::Unlock() {\n int rv = pthread_mutex_unlock(&os_lock_);\n DCHECK(rv == 0);\n}\n<commit_msg>Change DCHECK( == 0) to DCHECK_EQ in the posix lock implementation.<commit_after>\/\/ Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"base\/lock_impl.h\"\n\n#include <errno.h>\n\n#include \"base\/logging.h\"\n\nLockImpl::LockImpl() {\n#ifndef NDEBUG\n \/\/ In debug, setup attributes for lock error checking.\n pthread_mutexattr_t mta;\n int rv = pthread_mutexattr_init(&mta);\n DCHECK_EQ(rv, 0);\n rv = pthread_mutexattr_settype(&mta, PTHREAD_MUTEX_ERRORCHECK);\n DCHECK_EQ(rv, 0);\n rv = pthread_mutex_init(&os_lock_, &mta);\n DCHECK_EQ(rv, 0);\n rv = pthread_mutexattr_destroy(&mta);\n DCHECK_EQ(rv, 0);\n#else\n \/\/ In release, go with the default lock attributes.\n pthread_mutex_init(&os_lock_, NULL);\n#endif\n}\n\nLockImpl::~LockImpl() {\n int rv = pthread_mutex_destroy(&os_lock_);\n DCHECK_EQ(rv, 0);\n}\n\nbool LockImpl::Try() {\n int rv = pthread_mutex_trylock(&os_lock_);\n DCHECK(rv == 0 || rv == EBUSY);\n return rv == 0;\n}\n\nvoid LockImpl::Lock() {\n int rv = pthread_mutex_lock(&os_lock_);\n DCHECK_EQ(rv, 0);\n}\n\nvoid LockImpl::Unlock() {\n int rv = pthread_mutex_unlock(&os_lock_);\n DCHECK_EQ(rv, 0);\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"condor_common.h\"\n#include \"condor_classad.h\"\n\nBEGIN_NAMESPACE( classad )\n\nClassAd* getOldClassAd( Sock& sock )\n{\n\tClassAd *ad = new ClassAd( );\n\tif( !ad ) { \n\t\treturn (ClassAd*) 0;\n\t}\n\tif( !getOldClassAd( sock, *ad ) ) {\n\t\tdelete ad;\n\t\treturn NULL;\n\t}\n\treturn ad;\t\n}\n\n\nbool getOldClassAd( Sock& sock, ClassAd& ad )\n{\n\tSource \tsrc;\n\tint \tnumExprs;\n\tchar \t*eq;\n\tExprTree *expr;\n\tstatic char *buffer = new char[ 10240 ];\n\n\tsock.decode( );\n\tif( !sock.code( numExprs ) ) {\n\t\treturn false;\n\t}\n\n\tfor( int i = 0 ; i < numExprs ; i++ ) {\n\t\t\t\/\/ get the expression and find the '=' in the expr\n\t\tif( !sock.code( buffer ) || !( eq = strchr( buffer, '=' ) ) ) {\n\t\t\treturn false;\n\t\t}\n\t\t\t\/\/ split the expression at the '='\n\t\t*eq = '\\0';\n\n\t\t\t\/\/ set the source to the part after the '='\n\t\tsrc.SetSource( eq+1 );\n\n\t\t\t\/\/ parse the expression and insert it into the classad\n\t\tif( !src.ParseExpression( expr ) || !ad.Insert( buffer, expr ) ) {\n\t\t\treturn false;\n\t\t}\n\t}\n\n\treturn true;\n}\n\n\nvoid printClassAdExpr( ExprTree *tree )\n{\n\tstatic Sink\t\t\t\tsink;\n\tstatic FormatOptions\tfo;\n\n\tsink.SetSink( stdout );\n\tfo.SetClassAdIndentation( );\n\tfo.SetListIndentation( );\n\tsink.SetFormatOptions( &fo );\n\ttree->ToSink( sink );\n\tsink.FlushSink( );\n}\n\n\nvoid printClassAdValue( Value &val )\n{\n\tstatic Sink\t\t\t\tsink;\n\tstatic FormatOptions\tfo;\n\n\tsink.SetSink( stdout );\n\tfo.SetClassAdIndentation( );\n\tfo.SetListIndentation( );\n\tsink.SetFormatOptions( &fo );\n\tval.ToSink( sink );\n\tsink.FlushSink( );\n}\n\nEND_NAMESPACE \/\/ classad\n<commit_msg>Added methods to send and receive old classads<commit_after>#include \"condor_common.h\"\n#include \"condor_classad.h\"\n\nBEGIN_NAMESPACE( classad )\n\nClassAd* getOldClassAd( Sock& sock )\n{\n\tClassAd *ad = new ClassAd( );\n\tif( !ad ) { \n\t\treturn (ClassAd*) 0;\n\t}\n\tif( !getOldClassAd( sock, *ad ) ) {\n\t\tdelete ad;\n\t\treturn NULL;\n\t}\n\treturn ad;\t\n}\n\n\nbool getOldClassAd( Sock& sock, ClassAd& ad )\n{\n\tSource \tsrc;\n\tint \tnumExprs;\n\tchar \t*eq;\n\tExprTree *expr;\n\tstatic char *buffer = new char[ 10240 ];\n\n\tsock.decode( );\n\tif( !sock.code( numExprs ) ) {\n\t\treturn false;\n\t}\n\n\tfor( int i = 0 ; i < numExprs ; i++ ) {\n\t\t\t\/\/ get the expression and find the '=' in the expr\n\t\tif( !sock.code( buffer ) || !( eq = strchr( buffer, '=' ) ) ) {\n\t\t\treturn false;\n\t\t}\n\t\t\t\/\/ split the expression at the '='\n\t\t*eq = '\\0';\n\n\t\t\t\/\/ set the source to the part after the '='\n\t\tsrc.SetSource( eq+1 );\n\n\t\t\t\/\/ parse the expression and insert it into the classad\n\t\tif( !src.ParseExpression( expr ) || !ad.Insert( buffer, expr ) ) {\n\t\t\treturn false;\n\t\t}\n\t}\n\n\t\/\/ Get my type and target type\n\tif (!sock.code(buffer) || !ad.Insert(\"MyType\",buffer)) return false;\n\tif (!sock.code(buffer) || !ad.Insert(\"TargetType\",buffer)) return false;\n\n\treturn true;\n}\n\nbool putOldClassAd ( Sock& sock, ClassAd& ad )\n{\n\tchar* attr;\n\tExprTree* expr;\n\n\tchar buffer[10240];\n\tchar tmp[10240];\n\tchar* tmpPtr=tmp;\n\n\tint numExprs=0;\n\tClassAdIterator itor(ad);\n\twhile (itor.NextAttribute(attr, expr)) {\n\t\tif (strcmp(attr,\"MyType\")==0 || strcmp(attr,\"TargetType\")==0) continue;\n\t\tnumExprs++;\n\t}\n\t\n\tsock.encode( );\n\/\/printf(\"Sending: %d\\n\",numExprs);\n\tif( !sock.code( numExprs ) ) {\n\t\treturn false;\n\t}\n\t\t\n\titor.ToBeforeFirst();\n\twhile (itor.NextAttribute(attr, expr)) {\n\t\tif (strcmp(attr,\"MyType\")==0 || strcmp(attr,\"TargetType\")==0) continue;\n\t\tmemset(buffer,0,sizeof(buffer));\n\t\tSink s;\n\t\ts.SetSink(buffer,sizeof(buffer));\n\t\texpr->ToSink(s);\n\t\tsprintf(tmp,\"%s = %s\",attr,buffer);\n\/\/printf(\"Sending: %s\\n\",tmpPtr);\n\t\tif (!sock.code(tmpPtr)) {\n\t\t\treturn false;\n\t\t}\n\t}\n\n\t\/\/ Send the type\n\tchar* type=NULL;\n\tif (!ad.EvaluateAttrString(\"MyType\",type)) type=\"(unknown type)\";\n\/\/printf(\"Sending: %s\\n\",type);\n\tif (!sock.code(type)) {\n\t\treturn false;\n\t}\n\n\tchar* target_type=NULL;\n\tif (!ad.EvaluateAttrString(\"TargetType\",target_type)) target_type=\"(unknown type)\";\n\/\/printf(\"Sending: %s\\n\",target_type);\n\tif (!sock.code(target_type)) {\n\t\treturn false;\n\t}\n\n\treturn true;\n}\n\nvoid printClassAdExpr( ExprTree *tree )\n{\n\tstatic Sink\t\t\t\tsink;\n\tstatic FormatOptions\tfo;\n\n\tsink.SetSink( stdout );\n\tfo.SetClassAdIndentation( );\n\tfo.SetListIndentation( );\n\tsink.SetFormatOptions( &fo );\n\ttree->ToSink( sink );\n\tsink.FlushSink( );\n}\n\n\nvoid printClassAdValue( Value &val )\n{\n\tstatic Sink\t\t\t\tsink;\n\tstatic FormatOptions\tfo;\n\n\tsink.SetSink( stdout );\n\tfo.SetClassAdIndentation( );\n\tfo.SetListIndentation( );\n\tsink.SetFormatOptions( &fo );\n\tval.ToSink( sink );\n\tsink.FlushSink( );\n}\n\nEND_NAMESPACE \/\/ classad\n<|endoftext|>"} {"text":"<commit_before>#pragma once\n\n#include \"node.hpp\"\n#include \"random.hpp\"\n#include \"settings.hpp\"\n#include \"data.hpp\"\n#include \"MeanShift.hpp\"\n\n#include <vector>\n#include <cstdint>\n#include <ctime>\n\n#include <unordered_map>\n\nnamespace ISUE {\n namespace RelocForests {\n class Point3D {\n public:\n Point3D(double x, double y, double z) : x(x), y(y), z(z) {};\n double x, y, z;\n };\n\n struct hashFunc{\n size_t operator()(const Point3D &k) const {\n size_t h1 = std::hash<double>()(k.x);\n size_t h2 = std::hash<double>()(k.y);\n size_t h3 = std::hash<double>()(k.z);\n return (h1 ^ (h2 << 1)) ^ h3;\n }\n };\n\n struct equalsFunc {\n bool operator()(const Point3D &l, const Point3D &r) const{\n return (l.x == r.x) && (l.y == r.y) && (l.z == r.z);\n }\n };\n\n typedef std::unordered_map<Point3D, uint32_t, hashFunc, equalsFunc> Point3DMap;\n\n\n class Tree {\n public:\n Tree()\n {\n root_ = new Node();\n };\n\n ~Tree()\n {\n delete root_;\n };\n\n void Serialize(std::ostream& stream) const\n {\n const int majorVersion = 0, minorVersion = 0;\n \n stream.write(binaryFileHeader_, strlen(binaryFileHeader_));\n stream.write((const char*)(&majorVersion), sizeof(majorVersion));\n stream.write((const char*)(&minorVersion), sizeof(minorVersion));\n\n stream.write((const char*)(&settings_->max_tree_depth_), sizeof(settings_->max_tree_depth_));\n\n stream.write((const char*)(this), sizeof(this));\n }\n\n\n \/\/ learner output\n enum DECISION { LEFT, RIGHT, TRASH };\n\n \/\/ Evaluates weak learner. Decides whether the point should go left or right.\n \/\/ Returns DECISION enum value.\n DECISION eval_learner(Data *data, LabeledPixel pixel, DepthAdaptiveRGB *feature) \n {\n bool valid = true;\n float response = feature->GetResponse(data->GetDepthImage(pixel.frame_), data->GetRGBImage(pixel.frame_), pixel.pos_, valid);\n\n if (!valid) \/\/ no depth or out of bounds\n return DECISION::TRASH;\n\n return (DECISION)(response >= feature->GetThreshold());\n }\n\n \/\/ V(S)\n double variance(std::vector<LabeledPixel> labeled_data)\n {\n if (labeled_data.size() == 0)\n return 0.0;\n double V = (1.0f \/ (double)labeled_data.size());\n double sum = 0.0f;\n\n \/\/ calculate mean of S\n cv::Point3f tmp;\n for (auto p : labeled_data)\n tmp += p.label_;\n uint32_t size = labeled_data.size();\n cv::Point3f mean(tmp.x \/ size, tmp.y \/ size, tmp.z \/ size);\n\n for (auto p : labeled_data) {\n cv::Point3f val = (p.label_ - mean);\n sum += val.x * val.x + val.y * val.y + val.z * val.z;\n }\n\n return V * sum;\n }\n\n\n \/\/ Q(S_n, \\theta)\n double objective_function(std::vector<LabeledPixel> data, std::vector<LabeledPixel> left, std::vector<LabeledPixel> right)\n {\n double var = variance(data);\n double left_val = ((double)left.size() \/ (double)data.size()) * variance(left);\n double right_val = ((double)right.size() \/ (double)data.size()) * variance(right);\n\n return var - (left_val + right_val);\n }\n\n \/\/ Returns height from current node to root node.\n uint32_t traverse_to_root(Node *node) {\n if (node == nullptr)\n return 0;\n return 1 + traverse_to_root(node->parent_);\n }\n\n\n void train_recurse(Node *node, std::vector<LabeledPixel> S) \n {\n uint16_t height = traverse_to_root(node);\n if (S.size() == 1 || height >= settings_->max_tree_depth_) {\n\n std::vector<Eigen::Vector3d> data;\n\n \/\/ calc mode for leaf, sub-sample N_SS = 500\n for (uint16_t i = 0; i < (S.size() < 500 ? S.size() : 500); i++) {\n auto p = S.at(i);\n Eigen::Vector3d point { p.label_.x, p.label_.y, p.label_.z };\n data.push_back(point);\n }\n\n \/\/ cluster\n MeanShift *ms = new MeanShift(nullptr);\n double kernel_bandwidth = 0.01f; \/\/ gaussian\n std::vector<Eigen::Vector3d> cluster = ms->cluster(data, kernel_bandwidth);\n\n \/\/ find mode\n std::vector<Point3D> clustered_points;\n for (auto c : cluster)\n clustered_points.push_back(Point3D(floor(c[0] * 10000) \/ 10000, floor(c[1] * 10000) \/ 10000, floor(c[2] * 10000) \/ 10000));\n\n Point3DMap cluster_map;\n\n for (auto p : clustered_points)\n cluster_map[p]++;\n\n std::vector<cv::Point3d> modes;\n for (auto p : cluster_map)\n modes.push_back(cv::Point3d(p.first.x, p.first.y, p.first.z));\n\n node->modes_ = modes;\n node->is_leaf_ = true;\n return;\n }\n else if (S.size() == 0) {\n delete node;\n node = nullptr;\n return;\n }\n\n node->is_split_ = true;\n node->is_leaf_ = false;\n\n uint32_t num_candidates = 5,\n feature = 0;\n double minimum_objective = DBL_MAX;\n\n std::vector<DepthAdaptiveRGB*> candidate_params;\n std::vector<LabeledPixel> left_final, right_final;\n\n\n for (uint32_t i = 0; i < num_candidates; ++i) {\n\n \/\/ add candidate\n candidate_params.push_back(DepthAdaptiveRGB::CreateRandom(random_));\n\n \/\/ partition data with candidate\n std::vector<LabeledPixel> left_data, right_data;\n\n for (uint32_t j = 0; j < S.size(); ++j) {\n \/\/ todo throw away undefined vals\n\n DECISION val = eval_learner(data_, S.at(j), candidate_params.at(i));\n\n switch (val) {\n case LEFT:\n left_data.push_back(S.at(j));\n break;\n case RIGHT:\n right_data.push_back(S.at(j));\n break;\n case TRASH:\n \/\/ do nothing\n break;\n }\n\n }\n\n \/\/ eval tree training objective function and take best\n \/\/ todo: ensure objective function is correct\n double objective = objective_function(S, left_data, right_data);\n\n if (objective < minimum_objective) {\n feature = i;\n minimum_objective= objective;\n left_final = left_data;\n right_final = right_data;\n }\n }\n\n \/\/ set feature\n node->feature_ = candidate_params.at(feature);\n node->left_ = new Node();\n node->right_ = new Node();\n node->left_->parent_ = node->right_->parent_ = node;\n\n train_recurse(node->left_, left_final);\n train_recurse(node->right_, right_final);\n }\n\n void Train(Data *data, std::vector<LabeledPixel> labeled_data, Random *random, Settings *settings) \n {\n data_ = data;\n random_ = random;\n settings_ = settings;\n train_recurse(root_, labeled_data);\n }\n\n std::vector<cv::Point3d> eval_recursive(Node *node, int row, int col, cv::Mat rgb_image, cv::Mat depth_image)\n {\n\n if (node->is_leaf_) {\n return node->modes_;\n }\n\n bool valid = true;\n\n float response = node->feature_->GetResponse(depth_image, rgb_image, cv::Point2i(col, row), valid);\n\n DECISION val = (DECISION)(response >= node->feature_->GetThreshold());\n\n switch (val) {\n case LEFT:\n eval_recursive(node->left_, row, col, rgb_image, depth_image);\n break;\n case RIGHT:\n eval_recursive(node->right_, row, col, rgb_image, depth_image);\n break;\n case TRASH:\n \/\/ do nothing\n break;\n }\n }\n\n \/\/ Evaluate tree at a pixel\n std::vector<cv::Point3d> Eval(int row, int col, cv::Mat rgb_image, cv::Mat depth_image)\n {\n return eval_recursive(root_, row, col, rgb_image, depth_image);\n }\n\n\n private:\n Node *root_;\n Data *data_;\n Random *random_;\n Settings *settings_;\n const char* binaryFileHeader_ = \"ISUE.RelocForests.Tree\";\n };\n }\n}\n<commit_msg>Use eval_learner for training and testing.<commit_after>#pragma once\n\n#include \"node.hpp\"\n#include \"random.hpp\"\n#include \"settings.hpp\"\n#include \"data.hpp\"\n#include \"MeanShift.hpp\"\n\n#include <vector>\n#include <cstdint>\n#include <ctime>\n\n#include <unordered_map>\n\nnamespace ISUE {\n namespace RelocForests {\n class Point3D {\n public:\n Point3D(double x, double y, double z) : x(x), y(y), z(z) {};\n double x, y, z;\n };\n\n struct hashFunc{\n size_t operator()(const Point3D &k) const {\n size_t h1 = std::hash<double>()(k.x);\n size_t h2 = std::hash<double>()(k.y);\n size_t h3 = std::hash<double>()(k.z);\n return (h1 ^ (h2 << 1)) ^ h3;\n }\n };\n\n struct equalsFunc {\n bool operator()(const Point3D &l, const Point3D &r) const{\n return (l.x == r.x) && (l.y == r.y) && (l.z == r.z);\n }\n };\n\n typedef std::unordered_map<Point3D, uint32_t, hashFunc, equalsFunc> Point3DMap;\n\n\n class Tree {\n public:\n Tree()\n {\n root_ = new Node();\n };\n\n ~Tree()\n {\n delete root_;\n };\n\n void Serialize(std::ostream& stream) const\n {\n const int majorVersion = 0, minorVersion = 0;\n \n stream.write(binaryFileHeader_, strlen(binaryFileHeader_));\n stream.write((const char*)(&majorVersion), sizeof(majorVersion));\n stream.write((const char*)(&minorVersion), sizeof(minorVersion));\n\n stream.write((const char*)(&settings_->max_tree_depth_), sizeof(settings_->max_tree_depth_));\n\n stream.write((const char*)(this), sizeof(this));\n }\n\n\n \/\/ learner output\n enum DECISION { LEFT, RIGHT, TRASH };\n\n \/\/ Evaluates weak learner. Decides whether the point should go left or right.\n \/\/ Returns DECISION enum value.\n \/\/DECISION eval_learner(Data *data, LabeledPixel pixel, DepthAdaptiveRGB *feature) \n DECISION eval_learner(DepthAdaptiveRGB *feature, cv::Mat depth_image, cv::Mat rgb_image, cv::Point2i pos)\n {\n bool valid = true;\n float response = feature->GetResponse(depth_image, rgb_image, pos, valid);\n\n if (!valid) \/\/ no depth or out of bounds\n return DECISION::TRASH;\n\n return (DECISION)(response >= feature->GetThreshold());\n }\n\n \/\/ V(S)\n double variance(std::vector<LabeledPixel> labeled_data)\n {\n if (labeled_data.size() == 0)\n return 0.0;\n double V = (1.0f \/ (double)labeled_data.size());\n double sum = 0.0f;\n\n \/\/ calculate mean of S\n cv::Point3f tmp;\n for (auto p : labeled_data)\n tmp += p.label_;\n uint32_t size = labeled_data.size();\n cv::Point3f mean(tmp.x \/ size, tmp.y \/ size, tmp.z \/ size);\n\n for (auto p : labeled_data) {\n cv::Point3f val = (p.label_ - mean);\n sum += val.x * val.x + val.y * val.y + val.z * val.z;\n }\n\n return V * sum;\n }\n\n\n \/\/ Q(S_n, \\theta)\n double objective_function(std::vector<LabeledPixel> data, std::vector<LabeledPixel> left, std::vector<LabeledPixel> right)\n {\n double var = variance(data);\n double left_val = ((double)left.size() \/ (double)data.size()) * variance(left);\n double right_val = ((double)right.size() \/ (double)data.size()) * variance(right);\n\n return var - (left_val + right_val);\n }\n\n \/\/ Returns height from current node to root node.\n uint32_t traverse_to_root(Node *node) {\n if (node == nullptr)\n return 0;\n return 1 + traverse_to_root(node->parent_);\n }\n\n\n void train_recurse(Node *node, std::vector<LabeledPixel> S) \n {\n uint16_t height = traverse_to_root(node);\n if (S.size() == 1 || height >= settings_->max_tree_depth_) {\n\n std::vector<Eigen::Vector3d> data;\n\n \/\/ calc mode for leaf, sub-sample N_SS = 500\n for (uint16_t i = 0; i < (S.size() < 500 ? S.size() : 500); i++) {\n auto p = S.at(i);\n Eigen::Vector3d point { p.label_.x, p.label_.y, p.label_.z };\n data.push_back(point);\n }\n\n \/\/ cluster\n MeanShift *ms = new MeanShift(nullptr);\n double kernel_bandwidth = 0.01f; \/\/ gaussian\n std::vector<Eigen::Vector3d> cluster = ms->cluster(data, kernel_bandwidth);\n\n \/\/ find mode\n std::vector<Point3D> clustered_points;\n for (auto c : cluster)\n clustered_points.push_back(Point3D(floor(c[0] * 10000) \/ 10000, floor(c[1] * 10000) \/ 10000, floor(c[2] * 10000) \/ 10000));\n\n Point3DMap cluster_map;\n\n for (auto p : clustered_points)\n cluster_map[p]++;\n\n std::vector<cv::Point3d> modes;\n for (auto p : cluster_map)\n modes.push_back(cv::Point3d(p.first.x, p.first.y, p.first.z));\n\n node->modes_ = modes;\n node->is_leaf_ = true;\n return;\n }\n else if (S.size() == 0) {\n delete node;\n node = nullptr;\n return;\n }\n\n node->is_split_ = true;\n node->is_leaf_ = false;\n\n uint32_t num_candidates = 5,\n feature = 0;\n double minimum_objective = DBL_MAX;\n\n std::vector<DepthAdaptiveRGB*> candidate_params;\n std::vector<LabeledPixel> left_final, right_final;\n\n\n for (uint32_t i = 0; i < num_candidates; ++i) {\n\n \/\/ add candidate\n candidate_params.push_back(DepthAdaptiveRGB::CreateRandom(random_));\n\n \/\/ partition data with candidate\n std::vector<LabeledPixel> left_data, right_data;\n\n for (uint32_t j = 0; j < S.size(); ++j) {\n\n \/\/DECISION val = eval_learner(data_, S.at(j), candidate_params.at(i));\n LabeledPixel p = S.at(j);\n DECISION val = eval_learner(candidate_params.at(i), data_->GetDepthImage(p.frame_), data_->GetRGBImage(p.frame_), p.pos_);\n\n switch (val) {\n case LEFT:\n left_data.push_back(S.at(j));\n break;\n case RIGHT:\n right_data.push_back(S.at(j));\n break;\n case TRASH:\n \/\/ do nothing\n break;\n }\n\n }\n\n \/\/ eval tree training objective function and take best\n \/\/ todo: ensure objective function is correct\n double objective = objective_function(S, left_data, right_data);\n\n if (objective < minimum_objective) {\n feature = i;\n minimum_objective= objective;\n left_final = left_data;\n right_final = right_data;\n }\n }\n\n \/\/ set feature\n node->feature_ = candidate_params.at(feature);\n node->left_ = new Node();\n node->right_ = new Node();\n node->left_->parent_ = node->right_->parent_ = node;\n\n train_recurse(node->left_, left_final);\n train_recurse(node->right_, right_final);\n }\n\n void Train(Data *data, std::vector<LabeledPixel> labeled_data, Random *random, Settings *settings) \n {\n data_ = data;\n random_ = random;\n settings_ = settings;\n train_recurse(root_, labeled_data);\n }\n\n std::vector<cv::Point3d> eval_recursive(Node *node, int row, int col, cv::Mat rgb_image, cv::Mat depth_image)\n {\n\n if (node->is_leaf_) {\n return node->modes_;\n }\n\n DECISION val = eval_learner(node->feature_, depth_image, rgb_image, cv::Point2i(col, row));\n\n switch (val) {\n case LEFT:\n eval_recursive(node->left_, row, col, rgb_image, depth_image);\n break;\n case RIGHT:\n eval_recursive(node->right_, row, col, rgb_image, depth_image);\n break;\n case TRASH:\n break;\n }\n }\n\n \/\/ Evaluate tree at a pixel\n std::vector<cv::Point3d> Eval(int row, int col, cv::Mat rgb_image, cv::Mat depth_image)\n {\n return eval_recursive(root_, row, col, rgb_image, depth_image);\n }\n\n\n private:\n Node *root_;\n Data *data_;\n Random *random_;\n Settings *settings_;\n const char* binaryFileHeader_ = \"ISUE.RelocForests.Tree\";\n };\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/*****************************************************************************************\n* *\n* OpenSpace *\n* *\n* Copyright (c) 2014 *\n* *\n* Permission is hereby granted, free of charge, to any person obtaining a copy of this *\n* software and associated documentation files (the \"Software\"), to deal in the Software *\n* without restriction, including without limitation the rights to use, copy, modify, *\n* merge, publish, distribute, sublicense, and\/or sell copies of the Software, and to *\n* permit persons to whom the Software is furnished to do so, subject to the following *\n* conditions: *\n* *\n* The above copyright notice and this permission notice shall be included in all copies *\n* or substantial portions of the Software. *\n* *\n* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, *\n* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A *\n* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT *\n* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF *\n* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE *\n* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *\n****************************************************************************************\/\n\n\/\/ open space includes\n#include <openspace\/util\/ImageSequencer2.h>\n#include <ghoul\/logging\/logmanager.h>\n#include <ghoul\/filesystem\/filesystem.h>\n#include <ghoul\/filesystem\/directory.h>\n#include <openspace\/util\/time.h>\n#include <ghoul\/filesystem\/cachemanager.h>\n\n#include <openspace\/util\/spicemanager.h>\n#include <fstream>\n#include <iterator>\n#include <iomanip>\n#include <limits>\n\nnamespace {\nconst std::string _loggerCat = \"ImageSequencer2\";\n}\n\nnamespace openspace {\n\nImageSequencer2* ImageSequencer2::_instance = nullptr;\n\nImageSequencer2::ImageSequencer2() :\n_hasData(false),\n_defaultCaptureImage(absPath(\"C:\/Users\/michal\/openspace\/openspace-data\/scene\/common\/textures\/placeholder_blank.png\"))\n{}\n\n\nImageSequencer2& ImageSequencer2::ref() {\n\tassert(_instance != nullptr);\n\treturn *_instance;\n}\nvoid ImageSequencer2::initialize() {\n\tassert(_instance == nullptr);\n\t_instance = new ImageSequencer2;\n}\n\nvoid ImageSequencer2::deinitialize() {\n\tdelete _instance;\n\t_instance = nullptr;\n}\n\nbool ImageSequencer2::isReady(){\n\treturn _hasData;\n}\n\nbool ImageSequencer2::imageComparer(const Image &a, const Image &b){\n\treturn a.startTime < b.startTime;\n};\n\nstd::vector<Image>::iterator ImageSequencer2::binary_find(std::vector<Image>::iterator begin,\n\tstd::vector<Image>::iterator end,\n\tconst Image &val,\n\tbool(*compareFunc)(const Image &a, const Image &b)){\n\t\/\/ Finds the lower bound in at most log(last - first) + 1 comparisons\n\tstd::vector<Image>::iterator it = std::lower_bound(begin, end, val, compareFunc);\n\tif (it != begin && it != end){\n\t\treturn it;\n\t}\n\treturn end;\n}\n\nvoid ImageSequencer2::updateSequencer(double time){\n\tif (_currentTime != time){\n\t\t_previousTime = _currentTime;\n\t\t_currentTime = time;\n\t}\n}\n\nstd::pair<double, std::string> ImageSequencer2::getNextTarget(){\n\t\/\/ make into template func\n\tauto compareTime = [](const std::pair<double, std::string> &a,\n\t \t const std::pair<double, std::string> &b)->bool{\n\t\treturn a.first < b.first;\n\t};\n\tstd::pair<double, std::string> findEqualToThis;\n\tfindEqualToThis.first = _currentTime;\n\tauto it = std::lower_bound(_targetTimes.begin(), _targetTimes.end(), findEqualToThis, compareTime);\n\n\tif (it != _targetTimes.end()){\n\t\treturn (*it);\n\t}\n}\n\nstd::pair<double, std::string> ImageSequencer2::getCurrentTarget(){\n\t\/\/ make into template func\n\tauto compareTime = [](const std::pair<double, std::string> &a,\n\t\tconst std::pair<double, std::string> &b)->bool{\n\t\treturn a.first < b.first;\n\t};\n\tstd::pair<double, std::string> findEqualToThis;\n\tfindEqualToThis.first = _currentTime;\n\tauto it = std::lower_bound(_targetTimes.begin(), _targetTimes.end(), findEqualToThis, compareTime);\n\n\tif (it != _targetTimes.end()){\n\t\treturn *std::prev(it);\n\t}\n}\n\nstd::pair<double, std::vector<std::string>> ImageSequencer2::getIncidentTargetList(int range){\n\tstd::pair<double, std::vector<std::string>> incidentTargets;\n\n\tauto compareTime = [](const std::pair<double, std::string> &a,\n\t\tconst std::pair<double, std::string> &b)->bool{\n\t\treturn a.first < b.first;\n\t};\n\tstd::pair<double, std::string> findEqualToThis;\n\tfindEqualToThis.first = _currentTime;\n\tauto it = std::lower_bound(_targetTimes.begin(), _targetTimes.end(), findEqualToThis, compareTime);\n\t\n\tstd::advance(it, -(range+1));\n\n\tfor (int i = 0; i < 2*range+1; i++){\n\t\tincidentTargets.first = it->first;\n\t\tincidentTargets.second.push_back(it->second);\n\t\tit++;\n\t\tif (it == _targetTimes.end()) \n\t\t\tbreak;\n\t}\n\n\treturn incidentTargets;\n}\n\ndouble ImageSequencer2::getIntervalLength(){\n\tdouble upcoming = getNextCaptureTime();\n\tif (_nextCapture != upcoming){\n\t\t_nextCapture = upcoming;\n\t\t_intervalLength = upcoming - _currentTime;\n\t}\n\treturn _intervalLength;\n}\n\ndouble ImageSequencer2::getNextCaptureTime(){\n\tauto compareTime = [](const double &a, const double &b)->bool{\n\t\treturn a < b;\n\t};\n\tdouble nextCaptureTime = 0;\n\tauto it = std::lower_bound(_captureProgression.begin(), _captureProgression.end(), _currentTime, compareTime);\n\tif (it != _captureProgression.end())\n\t\tnextCaptureTime = *it;\n\n\treturn nextCaptureTime;\n}\n\nstd::vector<std::pair<std::string, bool>> ImageSequencer2::getActiveInstruments(){\n\tfor (int i = 0; i < _instrumentOnOff.size(); i++){\n\t\t_instrumentOnOff[i].second = false;\n\t}\n\tfor (auto key : _fileTranslation){\n\t\tfor (auto instrumentID : key.second->getTranslation()){\n\t\t\t\tif (instumentActive(instrumentID)){\n\t\t\t\t\tfor (int i = 0; i < _instrumentOnOff.size(); i++){\n\t\t\t\t\t\tif (instrumentID == _instrumentOnOff[i].first){\n\t\t\t\t\t\t\t_instrumentOnOff[i].second = true;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\treturn _instrumentOnOff;\n}\nbool ImageSequencer2::instumentActive(std::string instrumentID){\n\tfor (auto i : _instrumentTimes){\n\t\t\/\/check if this instrument is in range\n\t\tif (i.second.inRange(_currentTime)){\n\t\t\t\/\/if so, then get the corresponding spiceIDs\n\t\t\tstd::vector < std::string> spiceIDs = _fileTranslation[i.first]->getTranslation();\n\t\t\t\/\/check which specific subinstrument is firing\n\t\t\tfor (auto s : spiceIDs){\n\t\t\t\tif (s == instrumentID){\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn false;\n}\nbool ImageSequencer2::getImagePaths(std::vector<std::pair<double, std::string>>& captures, std::string projectee, std::string instrumentID){\n\tif (!instumentActive(instrumentID) && !Time::ref().timeJumped()) return false;\n\treturn (instrumentID == \"NH_LORRI\") ? getImagePaths(captures, projectee) : false;\n}\n\nbool ImageSequencer2::getImagePaths(std::vector<std::pair<double, std::string>>& captures, \n\t std::string projectee){\n\tif (_subsetMap[projectee]._range.inRange(_currentTime) ||\n\t\t_subsetMap[projectee]._range.inRange(_previousTime)){\n\t\tauto compareTime = [](const Image &a,\n\t\t\tconst Image &b)->bool{\n\t\t\treturn a.startTime < b.startTime;\n\t\t};\n\n\t\tauto begin = _subsetMap[projectee]._subset.begin();\n\t\tauto end = _subsetMap[projectee]._subset.end();\n\n\t\tstd::vector<std::pair<double, std::string>> captureTimes;\n\t\tImage findPrevious;\n\t\tfindPrevious.startTime = _previousTime;\n\t\tImage findCurrent;\n\t\tfindCurrent.startTime = _currentTime;\n\n\t\tauto curr = std::lower_bound(begin, end, findCurrent, compareTime);\n\t\tauto prev = std::lower_bound(begin, end, findPrevious, compareTime);\n\n\t\tif (curr != begin && curr != end && prev != begin && prev != end){\n\t\t\tstd::transform(prev, curr, std::back_inserter(captureTimes),\n\t\t\t\t[](const Image& i) {\n\t\t\t\treturn std::make_pair(i.startTime, i.path);\n\t\t\t});\n\t\t\tstd::reverse(captureTimes.begin(), captureTimes.end());\n\t\t\tcaptures = captureTimes;\n\t\t\treturn true;\n\t\t}\n\t}\n\treturn false;\n}\n\n\nvoid ImageSequencer2::runSequenceParser(SequenceParser* parser){\n\tparser->create();\n\t_fileTranslation = parser->getTranslation(); \/\/ should perhaps be named 'instrumentTranslation'\n\t_subsetMap = parser->getSubsetMap();\n\t_instrumentTimes = parser->getIstrumentTimes();\n\t_targetTimes = parser->getTargetTimes();\n\t_captureProgression = parser->getCaptureProgression();\n\n\t\/\/copy payload from _fileTranslation \n\tfor (auto t : _fileTranslation){\n\t\tstd::vector<std::string> spiceIDs = t.second->getTranslation();\n\t\tfor (auto id : spiceIDs){\n\t\t\t_instrumentOnOff.push_back(std::make_pair(id, false));\n\t\t}\n\t}\n\t_instrumentOnOff.erase(std::unique(_instrumentOnOff.begin(),\n\t\t\t\t\t\t\t\t\t _instrumentOnOff.end()),\n\t\t\t\t\t\t\t\t\t _instrumentOnOff.end());\n\t_hasData = true;\n\n}\n} \/\/ namespace openspace\n<commit_msg>Changed from absolute path into relative using ${OPENSPACE_DATA}<commit_after>\/*****************************************************************************************\n* *\n* OpenSpace *\n* *\n* Copyright (c) 2014 *\n* *\n* Permission is hereby granted, free of charge, to any person obtaining a copy of this *\n* software and associated documentation files (the \"Software\"), to deal in the Software *\n* without restriction, including without limitation the rights to use, copy, modify, *\n* merge, publish, distribute, sublicense, and\/or sell copies of the Software, and to *\n* permit persons to whom the Software is furnished to do so, subject to the following *\n* conditions: *\n* *\n* The above copyright notice and this permission notice shall be included in all copies *\n* or substantial portions of the Software. *\n* *\n* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, *\n* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A *\n* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT *\n* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF *\n* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE *\n* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *\n****************************************************************************************\/\n\n\/\/ open space includes\n#include <openspace\/util\/ImageSequencer2.h>\n#include <ghoul\/logging\/logmanager.h>\n#include <ghoul\/filesystem\/filesystem.h>\n#include <ghoul\/filesystem\/directory.h>\n#include <openspace\/util\/time.h>\n#include <ghoul\/filesystem\/cachemanager.h>\n\n#include <openspace\/util\/spicemanager.h>\n#include <fstream>\n#include <iterator>\n#include <iomanip>\n#include <limits>\n\nnamespace {\nconst std::string _loggerCat = \"ImageSequencer2\";\n}\n\nnamespace openspace {\n\nImageSequencer2* ImageSequencer2::_instance = nullptr;\n\nImageSequencer2::ImageSequencer2() :\n_hasData(false),\n_defaultCaptureImage(absPath(\"${OPENSPACE_DATA}\/scene\/common\/textures\/placeholder_blank.png\"))\n{}\n\n\nImageSequencer2& ImageSequencer2::ref() {\n\tassert(_instance != nullptr);\n\treturn *_instance;\n}\nvoid ImageSequencer2::initialize() {\n\tassert(_instance == nullptr);\n\t_instance = new ImageSequencer2;\n}\n\nvoid ImageSequencer2::deinitialize() {\n\tdelete _instance;\n\t_instance = nullptr;\n}\n\nbool ImageSequencer2::isReady(){\n\treturn _hasData;\n}\n\nbool ImageSequencer2::imageComparer(const Image &a, const Image &b){\n\treturn a.startTime < b.startTime;\n};\n\nstd::vector<Image>::iterator ImageSequencer2::binary_find(std::vector<Image>::iterator begin,\n\tstd::vector<Image>::iterator end,\n\tconst Image &val,\n\tbool(*compareFunc)(const Image &a, const Image &b)){\n\t\/\/ Finds the lower bound in at most log(last - first) + 1 comparisons\n\tstd::vector<Image>::iterator it = std::lower_bound(begin, end, val, compareFunc);\n\tif (it != begin && it != end){\n\t\treturn it;\n\t}\n\treturn end;\n}\n\nvoid ImageSequencer2::updateSequencer(double time){\n\tif (_currentTime != time){\n\t\t_previousTime = _currentTime;\n\t\t_currentTime = time;\n\t}\n}\n\nstd::pair<double, std::string> ImageSequencer2::getNextTarget(){\n\t\/\/ make into template func\n\tauto compareTime = [](const std::pair<double, std::string> &a,\n\t \t const std::pair<double, std::string> &b)->bool{\n\t\treturn a.first < b.first;\n\t};\n\tstd::pair<double, std::string> findEqualToThis;\n\tfindEqualToThis.first = _currentTime;\n\tauto it = std::lower_bound(_targetTimes.begin(), _targetTimes.end(), findEqualToThis, compareTime);\n\n\tif (it != _targetTimes.end()){\n\t\treturn (*it);\n\t}\n}\n\nstd::pair<double, std::string> ImageSequencer2::getCurrentTarget(){\n\t\/\/ make into template func\n\tauto compareTime = [](const std::pair<double, std::string> &a,\n\t\tconst std::pair<double, std::string> &b)->bool{\n\t\treturn a.first < b.first;\n\t};\n\tstd::pair<double, std::string> findEqualToThis;\n\tfindEqualToThis.first = _currentTime;\n\tauto it = std::lower_bound(_targetTimes.begin(), _targetTimes.end(), findEqualToThis, compareTime);\n\n\tif (it != _targetTimes.end()){\n\t\treturn *std::prev(it);\n\t}\n}\n\nstd::pair<double, std::vector<std::string>> ImageSequencer2::getIncidentTargetList(int range){\n\tstd::pair<double, std::vector<std::string>> incidentTargets;\n\n\tauto compareTime = [](const std::pair<double, std::string> &a,\n\t\tconst std::pair<double, std::string> &b)->bool{\n\t\treturn a.first < b.first;\n\t};\n\tstd::pair<double, std::string> findEqualToThis;\n\tfindEqualToThis.first = _currentTime;\n\tauto it = std::lower_bound(_targetTimes.begin(), _targetTimes.end(), findEqualToThis, compareTime);\n\t\n\tstd::advance(it, -(range+1));\n\n\tfor (int i = 0; i < 2*range+1; i++){\n\t\tincidentTargets.first = it->first;\n\t\tincidentTargets.second.push_back(it->second);\n\t\tit++;\n\t\tif (it == _targetTimes.end()) \n\t\t\tbreak;\n\t}\n\n\treturn incidentTargets;\n}\n\ndouble ImageSequencer2::getIntervalLength(){\n\tdouble upcoming = getNextCaptureTime();\n\tif (_nextCapture != upcoming){\n\t\t_nextCapture = upcoming;\n\t\t_intervalLength = upcoming - _currentTime;\n\t}\n\treturn _intervalLength;\n}\n\ndouble ImageSequencer2::getNextCaptureTime(){\n\tauto compareTime = [](const double &a, const double &b)->bool{\n\t\treturn a < b;\n\t};\n\tdouble nextCaptureTime = 0;\n\tauto it = std::lower_bound(_captureProgression.begin(), _captureProgression.end(), _currentTime, compareTime);\n\tif (it != _captureProgression.end())\n\t\tnextCaptureTime = *it;\n\n\treturn nextCaptureTime;\n}\n\nstd::vector<std::pair<std::string, bool>> ImageSequencer2::getActiveInstruments(){\n\tfor (int i = 0; i < _instrumentOnOff.size(); i++){\n\t\t_instrumentOnOff[i].second = false;\n\t}\n\tfor (auto key : _fileTranslation){\n\t\tfor (auto instrumentID : key.second->getTranslation()){\n\t\t\t\tif (instumentActive(instrumentID)){\n\t\t\t\t\tfor (int i = 0; i < _instrumentOnOff.size(); i++){\n\t\t\t\t\t\tif (instrumentID == _instrumentOnOff[i].first){\n\t\t\t\t\t\t\t_instrumentOnOff[i].second = true;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\treturn _instrumentOnOff;\n}\nbool ImageSequencer2::instumentActive(std::string instrumentID){\n\tfor (auto i : _instrumentTimes){\n\t\t\/\/check if this instrument is in range\n\t\tif (i.second.inRange(_currentTime)){\n\t\t\t\/\/if so, then get the corresponding spiceIDs\n\t\t\tstd::vector < std::string> spiceIDs = _fileTranslation[i.first]->getTranslation();\n\t\t\t\/\/check which specific subinstrument is firing\n\t\t\tfor (auto s : spiceIDs){\n\t\t\t\tif (s == instrumentID){\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn false;\n}\nbool ImageSequencer2::getImagePaths(std::vector<std::pair<double, std::string>>& captures, std::string projectee, std::string instrumentID){\n\tif (!instumentActive(instrumentID) && !Time::ref().timeJumped()) return false;\n\treturn (instrumentID == \"NH_LORRI\") ? getImagePaths(captures, projectee) : false;\n}\n\nbool ImageSequencer2::getImagePaths(std::vector<std::pair<double, std::string>>& captures, \n\t std::string projectee){\n\tif (_subsetMap[projectee]._range.inRange(_currentTime) ||\n\t\t_subsetMap[projectee]._range.inRange(_previousTime)){\n\t\tauto compareTime = [](const Image &a,\n\t\t\tconst Image &b)->bool{\n\t\t\treturn a.startTime < b.startTime;\n\t\t};\n\n\t\tauto begin = _subsetMap[projectee]._subset.begin();\n\t\tauto end = _subsetMap[projectee]._subset.end();\n\n\t\tstd::vector<std::pair<double, std::string>> captureTimes;\n\t\tImage findPrevious;\n\t\tfindPrevious.startTime = _previousTime;\n\t\tImage findCurrent;\n\t\tfindCurrent.startTime = _currentTime;\n\n\t\tauto curr = std::lower_bound(begin, end, findCurrent, compareTime);\n\t\tauto prev = std::lower_bound(begin, end, findPrevious, compareTime);\n\n\t\tif (curr != begin && curr != end && prev != begin && prev != end){\n\t\t\tstd::transform(prev, curr, std::back_inserter(captureTimes),\n\t\t\t\t[](const Image& i) {\n\t\t\t\treturn std::make_pair(i.startTime, i.path);\n\t\t\t});\n\t\t\tstd::reverse(captureTimes.begin(), captureTimes.end());\n\t\t\tcaptures = captureTimes;\n\t\t\treturn true;\n\t\t}\n\t}\n\treturn false;\n}\n\n\nvoid ImageSequencer2::runSequenceParser(SequenceParser* parser){\n\tparser->create();\n\t_fileTranslation = parser->getTranslation(); \/\/ should perhaps be named 'instrumentTranslation'\n\t_subsetMap = parser->getSubsetMap();\n\t_instrumentTimes = parser->getIstrumentTimes();\n\t_targetTimes = parser->getTargetTimes();\n\t_captureProgression = parser->getCaptureProgression();\n\n\t\/\/copy payload from _fileTranslation \n\tfor (auto t : _fileTranslation){\n\t\tstd::vector<std::string> spiceIDs = t.second->getTranslation();\n\t\tfor (auto id : spiceIDs){\n\t\t\t_instrumentOnOff.push_back(std::make_pair(id, false));\n\t\t}\n\t}\n\t_instrumentOnOff.erase(std::unique(_instrumentOnOff.begin(),\n\t\t\t\t\t\t\t\t\t _instrumentOnOff.end()),\n\t\t\t\t\t\t\t\t\t _instrumentOnOff.end());\n\t_hasData = true;\n\n}\n} \/\/ namespace openspace\n<|endoftext|>"} {"text":"<commit_before>\/*\n *\n *\/\n#include <stdio.h>\n#include \"sync.h\"\n#include \"topo.h\"\n#include \"mp.h\"\n#include \"measurement_framework.h\"\n#include <pthread.h>\n#include <unistd.h>\n#include <vector>\n\n#include \"model_defs.h\"\n#include \"barrier.h\"\n\n#ifdef PARLIB\n#include \"mcs.h\"\n#endif\n\n\n\/\/#define SEND7\n\n#ifdef BARRELFISH\n#include <barrelfish\/barrelfish.h>\n#include <posixcompat.h>\n#endif\n\n__thread struct sk_measurement m;\n__thread struct sk_measurement m2;\n\nunsigned num_threads;\n#define NUM_RUNS 100000 \/\/50 \/\/ 10000 \/\/ Tested up to 1.000.000\n#define NUM_RESULTS 1000\n\npthread_barrier_t ab_barrier;\n\n#define TOPO_NAME(x,y) sprintf(x, \"%s_%s\", y, topo_get_name());\n\nmcs_barrier_t mcs_b;\nstatic void* mcs_barrier(void* a)\n{\n coreid_t tid = *((int*) a);\n __thread_init(tid, num_threads); \/\/ will bind threads\n\n cycles_t *buf = (cycles_t*) malloc(sizeof(cycles_t)*NUM_RESULTS);\n char outname[1024];\n TOPO_NAME(outname, \"mcs-barrier\");\n sk_m_init(&m, NUM_RESULTS, outname, buf);\n\n sk_m_restart_tsc(&m);\n for (unsigned i=0; i<NUM_RUNS; i++) {\n\n mcs_barrier_wait(&mcs_b, tid);\n }\n\n sk_m_add(&m);\n if (get_thread_id() == get_sequentializer()) {\n sk_m_print(&m);\n }\n\n return NULL;\n}\n\nstatic void* barrier(void* a)\n{\n\n coreid_t tid = *((int*) a);\n __thread_init(tid, num_threads);\n\n cycles_t *buf = (cycles_t*) malloc(sizeof(cycles_t)*NUM_RESULTS);\n char outname[1024];\n TOPO_NAME(outname, \"syc-barrier\");\n sk_m_init(&m, NUM_RESULTS, outname, buf);\n\n sk_m_restart_tsc(&m);\n for (int epoch=0; epoch<NUM_RUNS; epoch++) {\n#ifdef HYB\n shl_hybrid_barrier(NULL);\n#else\n mp_barrier(NULL);\n#endif\n }\n\n sk_m_add(&m);\n if (get_thread_id() == get_sequentializer()) {\n sk_m_print(&m);\n }\n\n __thread_end();\n return NULL;\n}\n\nstatic void* barrier0(void* a)\n{\n\n coreid_t tid = *((int*) a);\n __thread_init(tid, num_threads);\n\n cycles_t *buf = (cycles_t*) malloc(sizeof(cycles_t)*NUM_RESULTS);\n char outname[1024];\n TOPO_NAME(outname, \"syc-barrier0\");\n sk_m_init(&m, NUM_RESULTS, outname, buf);\n\n sk_m_restart_tsc(&m);\n for (int epoch=0; epoch<NUM_RUNS; epoch++) {\n#ifdef HYB\n shl_hybrid_barrier0(NULL);\n#else\n mp_barrier0();\n#endif\n }\n\n sk_m_add(&m);\n if (get_thread_id() == get_sequentializer()) {\n sk_m_print(&m);\n }\n\n __thread_end();\n return NULL;\n}\n\n#define NUM_EXP 3\n\n#define max(a,b) \\\n ({ __typeof__ (a) _a = (a); \\\n __typeof__ (b) _b = (b); \\\n _a > _b ? _a : _b; })\n\nint main(int argc, char **argv)\n{\n unsigned nthreads = sysconf(_SC_NPROCESSORS_CONF);\n\n int topology = -1;\n if (argc>1) {\n topology = atoi(argv[1]);\n\n }\n if (topology>=0) {\n switch_topo_to_idx(topology);\n } else {\n printf(\"No topology given, using default one\\n\");\n }\n\n __sync_init(nthreads, true);\n\n num_threads = get_num_threads();\n\n mcs_barrier_init(&mcs_b, num_threads);\n pthread_barrier_init(&ab_barrier, NULL, num_threads);\n\n typedef void* (worker_func_t)(void*);\n worker_func_t* workers[NUM_EXP] = {\n &mcs_barrier,\n &barrier,\n &barrier0,\n };\n\n const char *labels[NUM_EXP] = {\n \"MCS barrier\",\n \"libsync barrier\",\n \"libsync barrier0\"\n };\n\n pthread_t ptds[num_threads];\n int tids[num_threads];\n\n printf(\"%d models\\n\", max(1U, (topo_num_topos()-1)));\n\n \/\/ Choose how many topologies to evaluate. We evaluate at least\n \/\/ one, even in the case of the auto-generated binary tree. If a\n \/\/ topology is given as argument, we ONLY evaluate that single\n \/\/ one.\n size_t num_topos = max(1U, (topo_num_topos()-1));\n if (topology>=0) {\n num_topos = 1;\n }\n\n for (unsigned e=0; e<num_topos; e++) {\n for (int j=0; j<NUM_EXP; j++) {\n printf(\"----------------------------------------\\n\");\n printf(\"Executing experiment %d - %s\\n\", (j+1), labels[j]);\n printf(\"----------------------------------------\\n\");\n\n \/\/ Yield to reduce the risk of getting de-scheduled later\n sched_yield();\n\n \/\/ Create\n for (unsigned i=1; i<num_threads; i++) {\n tids[i] = i;\n\n pthread_create(ptds+i, NULL, workers[j], (void*) (tids+i));\n }\n\n \/\/ Master thread executes work for node 0\n tids[0] = 0;\n workers[j]((void*) (tids+0));\n\n \/\/ Join\n for (unsigned i=1; i<num_threads; i++) {\n pthread_join(ptds[i], NULL);\n }\n }\n\n if( e<topo_num_topos()-1) switch_topo();\n }\n\n pthread_barrier_destroy(&ab_barrier);\n}\n<commit_msg>adding multiple runs for ab-throuthput<commit_after>\/*\n *\n *\/\n#include <stdio.h>\n#include \"sync.h\"\n#include \"topo.h\"\n#include \"mp.h\"\n#include \"measurement_framework.h\"\n#include <pthread.h>\n#include <unistd.h>\n#include <vector>\n\n#include \"model_defs.h\"\n#include \"barrier.h\"\n\n#ifdef PARLIB\n#include \"mcs.h\"\n#endif\n\n#define HYB 1\n\n\/\/#define SEND7\n\n#ifdef BARRELFISH\n#include <barrelfish\/barrelfish.h>\n#include <posixcompat.h>\n#endif\n\n__thread struct sk_measurement m;\n__thread struct sk_measurement m2;\n\nunsigned num_threads;\n#define NUM_RUNS 100000 \/\/50 \/\/ 10000 \/\/ Tested up to 1.000.000\n#define NUM_REPETITIONS 100\n#define NUM_RESULTS 1000\n\npthread_barrier_t ab_barrier;\n\n#define TOPO_NAME(x,y) sprintf(x, \"%s_%s\", y, topo_get_name());\n\nmcs_barrier_t mcs_b;\nstatic void* mcs_barrier(void* a)\n{\n coreid_t tid = *((int*) a);\n __thread_init(tid, num_threads); \/\/ will bind threads\n\n cycles_t *buf = (cycles_t*) malloc(sizeof(cycles_t)*NUM_RESULTS);\n char outname[1024];\n TOPO_NAME(outname, \"mcs-barrier\");\n sk_m_init(&m, NUM_RESULTS, outname, buf);\nfor (int k = 0; k < NUM_REPETITIONS; ++k) {\n\n sk_m_restart_tsc(&m);\n for (unsigned i=0; i<NUM_RUNS; i++) {\n\n mcs_barrier_wait(&mcs_b, tid);\n }\n\n sk_m_add(&m);\n if (get_thread_id() == get_sequentializer()) {\n sk_m_print(&m);\n }\n}\n return NULL;\n}\n\nstatic void* barrier(void* a)\n{\n\n coreid_t tid = *((int*) a);\n __thread_init(tid, num_threads);\n\n cycles_t *buf = (cycles_t*) malloc(sizeof(cycles_t)*NUM_RESULTS);\n char outname[1024];\n TOPO_NAME(outname, \"syc-barrier\");\n sk_m_init(&m, NUM_RESULTS, outname, buf);\nfor (int k = 0; k < NUM_REPETITIONS; ++k) {\n\n sk_m_restart_tsc(&m);\n for (int epoch=0; epoch<NUM_RUNS; epoch++) {\n#ifdef HYB\n shl_hybrid_barrier(NULL);\n#else\n mp_barrier(NULL);\n#endif\n }\n\n sk_m_add(&m);\n if (get_thread_id() == get_sequentializer()) {\n sk_m_print(&m);\n }\n}\n __thread_end();\n return NULL;\n}\n\nstatic void* barrier0(void* a)\n{\n\n coreid_t tid = *((int*) a);\n __thread_init(tid, num_threads);\n\n cycles_t *buf = (cycles_t*) malloc(sizeof(cycles_t)*NUM_RESULTS);\n char outname[1024];\n TOPO_NAME(outname, \"syc-barrier0\");\n sk_m_init(&m, NUM_RESULTS, outname, buf);\n\n for (int k = 0; k < NUM_REPETITIONS; ++k) {\n\n\n sk_m_restart_tsc(&m);\n for (int epoch=0; epoch<NUM_RUNS; epoch++) {\n#ifdef HYB\n shl_hybrid_barrier0(NULL);\n#else\n mp_barrier0();\n#endif\n }\n\n sk_m_add(&m);\n if (get_thread_id() == get_sequentializer()) {\n sk_m_print(&m);\n }\n }\n __thread_end();\n return NULL;\n}\n\n#define NUM_EXP 3\n\n#define max(a,b) \\\n ({ __typeof__ (a) _a = (a); \\\n __typeof__ (b) _b = (b); \\\n _a > _b ? _a : _b; })\n\n#ifdef BARRELFISH\nstatic void domain_init_done(void *arg, errval_t err)\n{\n debug_printf(\"SPANNED!\\n\");\n}\n#endif\n\n\nint main(int argc, char **argv)\n{\n unsigned nthreads = sysconf(_SC_NPROCESSORS_CONF);\n\n int topology = -1;\n if (argc>1) {\n topology = atoi(argv[1]);\n\n }\n if (topology>=0) {\n switch_topo_to_idx(topology);\n } else {\n printf(\"No topology given, using default one\\n\");\n }\n\n __sync_init(nthreads, true);\n\n num_threads = get_num_threads();\n\n mcs_barrier_init(&mcs_b, num_threads);\n pthread_barrier_init(&ab_barrier, NULL, num_threads);\n\n typedef void* (worker_func_t)(void*);\n worker_func_t* workers[NUM_EXP] = {\n &mcs_barrier,\n &barrier,\n &barrier0,\n };\n\n const char *labels[NUM_EXP] = {\n \"MCS barrier\",\n \"libsync barrier\",\n \"libsync barrier0\"\n };\n\n pthread_t ptds[num_threads];\n int tids[num_threads];\n\n printf(\"%d models\\n\", max(1U, (topo_num_topos()-1)));\n\n\n#ifdef BARRELFISH\n cpu_set_t *cpuset = CPU_ALLOC(num_threads);\n\n for (unsigned i=1; i<num_threads; i++) {\n \/\/for (int i = my_core_id + BOMP_DEFAULT_CORE_STRIDE; i < nos_threads + my_core_id; i++) {\n coreid_t core = i;\n errval_t err = domain_new_dispatcher(core, domain_init_done, NULL);\n if (err_is_fail(err)) {\n DEBUG_ERR(err, \"failed to span domain\");\n printf(\"Failed to span domain to %d\\n\", i);\n assert(err_is_ok(err));\n }\n }\n\n#endif\n\n\n \/\/ Choose how many topologies to evaluate. We evaluate at least\n \/\/ one, even in the case of the auto-generated binary tree. If a\n \/\/ topology is given as argument, we ONLY evaluate that single\n \/\/ one.\n size_t num_topos = max(1U, (topo_num_topos()-1));\n if (topology>=0) {\n num_topos = 1;\n }\n\n for (unsigned e=0; e<num_topos; e++) {\n for (int j=0; j<NUM_EXP; j++) {\n printf(\"----------------------------------------\\n\");\n printf(\"Executing experiment %d - %s\\n\", (j+1), labels[j]);\n printf(\"----------------------------------------\\n\");\n \/\/ Yield to reduce the risk of getting de-scheduled later\n sched_yield();\n\n \/\/ Create\n for (unsigned i=1; i<num_threads; i++) {\n tids[i] = i;\n#ifdef BARRELFISH\n pthread_attr_t attr;\n pthread_attr_init(&attr);\n\n CPU_ZERO(cpuset);\n CPU_SET(i, cpuset);\n pthread_attr_setaffinity_np(&attr, sizeof(cpu_set_t), cpuset);\n\n pthread_create(ptds+i, &attr, workers[j], (void*) (tids+i));\n#else\n\n pthread_create(ptds+i, NULL, workers[j], (void*) (tids+i));\n#endif\n }\n\n \/\/ Master thread executes work for node 0\n tids[0] = 0;\n workers[j]((void*) (tids+0));\n\n \/\/ Join\n for (unsigned i=1; i<num_threads; i++) {\n pthread_join(ptds[i], NULL);\n }\n }\n\n if( e<topo_num_topos()-1) switch_topo();\n }\n\n pthread_barrier_destroy(&ab_barrier);\n}\n<|endoftext|>"} {"text":"<commit_before>\/* Copyright (c) 2010-2017, Delft University of Technology\n * All rigths reserved\n *\n * This file is part of the Tudat. Redistribution and use in source and\n * binary forms, with or without modification, are permitted exclusively\n * under the terms of the Modified BSD license. You should have received\n * a copy of the license with this file. If not, please or visit:\n * http:\/\/tudat.tudelft.nl\/LICENSE.\n *\/\n\n#define BOOST_TEST_MAIN\n\n#include \"Tudat\/JsonInterface\/UnitTests\/unitTestSupport.h\"\n#include \"Tudat\/JsonInterface\/Support\/valueAccess.h\"\n#include \"Tudat\/JsonInterface\/Support\/valueConversions.h\"\n#include \"Tudat\/JsonInterface\/Support\/deserialization.h\"\n\nnamespace tudat\n{\n\nnamespace unit_tests\n{\n\n#define INPUT( filename ) \\\n ( json_interface::inputDirectory( ) \/ boost::filesystem::path( __FILE__ ).stem( ) \/ filename ).string( )\n\nBOOST_AUTO_TEST_SUITE( test_json_deserialization )\n\n\/\/ Test 1: value access\nBOOST_AUTO_TEST_CASE( test_json_valueAccess )\n{\n using namespace json_interface;\n\n const nlohmann::json dog = parseJSONFile( INPUT( \"valueAccess\" ) );\n\n \/\/ Numbers\n BOOST_CHECK_EQUAL( getValue< unsigned int >( dog, \"age\" ), 11 );\n BOOST_CHECK_EQUAL( getValue< int >( dog, \"age\" ), 11 );\n BOOST_CHECK_EQUAL( getValue< double >( dog, \"mass\" ), 19.5 );\n BOOST_CHECK_EQUAL( getValue< float >( dog, \"mass\" ), 19.5 );\n BOOST_CHECK_EQUAL( getValue< long double >( dog, \"mass\" ), 19.5 );\n\n \/\/ Strings\n BOOST_CHECK_EQUAL( getValue< std::string >( dog, \"name\" ), \"Bumper\" );\n\n \/\/ Arrays\n const std::vector< std::string > hobbies = { \"eat\", \"sleep\" };\n const std::string hobbiesKey = \"hobbies\";\n BOOST_CHECK( getValue< std::vector< std::string > >( dog, hobbiesKey ) == hobbies );\n BOOST_CHECK_EQUAL( getValue< std::string >( dog, hobbiesKey \/ 0 ), hobbies.at( 0 ) );\n BOOST_CHECK_EQUAL( getValue< std::string >( dog, hobbiesKey \/ 1 ), hobbies.at( 1 ) );\n\n \/\/ Context: one level\n const nlohmann::json enemy = getValue< std::vector< nlohmann::json > >( dog, \"enemies\" ).front( );\n BOOST_CHECK_EQUAL( getRootObject( enemy ), dog );\n BOOST_CHECK_EQUAL( getValue< double >( enemy, \"mass\" ), 2.6 );\n BOOST_CHECK_EQUAL( getValue< double >( enemy, SpecialKeys::up \/ SpecialKeys::up \/ \"mass\" ), 19.5 );\n BOOST_CHECK_EQUAL( getValue< double >( enemy, SpecialKeys::root \/ \"mass\" ), 19.5 );\n\n \/\/ Context: several levels\n const nlohmann::json valencia =\n getValue< nlohmann::json >( enemy, std::string( \"mother\" ) \/ \"birthplace\" \/ \"city\" );\n BOOST_CHECK_EQUAL( valencia.at( \"name\" ), \"Valencia\" );\n BOOST_CHECK_EQUAL( getValue< double >( valencia, SpecialKeys::root \/ \"mass\" ), 19.5 );\n BOOST_CHECK_EQUAL( getValue< double >( valencia, SpecialKeys::up \/ SpecialKeys::up \/ SpecialKeys::up \/\n SpecialKeys::up \/ SpecialKeys::up \/ \"mass\" ), 19.5 );\n BOOST_CHECK_EQUAL( getValue< double >( valencia, SpecialKeys::up \/ \"continent\" \/ \"temperatureRange\" \/ 0 ), -15 );\n BOOST_CHECK_EQUAL( getValue< double >( valencia, SpecialKeys::up \/ \"continent\" \/ \"temperatureRange\" \/ 1 ), 45 );\n\n \/\/ Eigen\n const Eigen::Matrix3d matrix = getValue< Eigen::Matrix3d >( dog, \"orientation\" );\n const Eigen::Matrix3d matrix2 = ( Eigen::Matrix3d( ) << 1.0, 0.0, 0.0, 0.0, 2.0, 1.0, 0.0, 3.0, -1.0 ).finished( );\n BOOST_CHECK_EQUAL( matrix, matrix2 );\n\n \/\/ Map with non-char keys\n const std::map< double, std::string > food = getValue< std::map< double, std::string > >( dog, \"food\" );\n const std::map< double, std::string > food2 = { { 7, \"feed\" }, { 12, \"meat\" }, { 15, \"feed\" }, { 19, \"feed\" } };\n BOOST_CHECK( food == food2 );\n}\n\n\/\/ Test 2: modular\nBOOST_AUTO_TEST_CASE( test_json_modular )\n{\n using namespace json_interface;\n\n const nlohmann::json modular = getDeserializedJSON( getPathForJSONFile( INPUT( \"modular\" ) ) );\n\n nlohmann::json simulation;\n simulation[ \"bodies\" ] =\n R\"(\n {\n \"Earth\": {\n \"useDefaultSettings\": true\n },\n \"satellite\": {\n \"mass\": 500\n }\n }\n )\"_json;\n\n simulation[ \"propagators\" ] =\n R\"(\n [\n {\n \"centralBodies\": [\n \"Earth\"\n ],\n \"bodiesToPropagate\": [\n \"satellite\"\n ]\n }\n ]\n )\"_json;\n\n simulation[ \"integrator\" ] =\n R\"(\n {\n \"type\": \"rungeKutta4\",\n \"stepSize\": 30\n }\n )\"_json;\n\n simulation[ \"export\" ] =\n R\"(\n [\n {\n \"variables\": [\n {\n \"type\": \"independent\"\n }\n ]\n },\n {\n \"variables\": [\n {\n \"body\": \"satellite\",\n \"dependentVariableType\": \"relativePosition\",\n \"relatieToBody\": \"Earth\"\n },\n {\n \"body\": \"satellite\",\n \"dependentVariableType\": \"relativeVelocity\",\n \"relatieToBody\": \"Earth\"\n }\n ]\n }\n ]\n )\"_json;\n\n simulation[ \"export\" ][ 0 ][ \"file\" ] =\n ( boost::filesystem::path( \"export\" ) \/ \"..\" \/ \"outputs\" \/ \"epochs.txt\" ).string( );\n simulation[ \"export\" ][ 1 ][ \"file\" ] =\n ( boost::filesystem::path( \"export\" ) \/ \"..\" \/ \"states.txt\" ).string( );\n\n BOOST_CHECK_EQUAL( modular, simulation );\n}\n\n\/\/ Test 3: mergeable\nBOOST_AUTO_TEST_CASE( test_json_mergeable )\n{\n using namespace json_interface;\n using namespace boost::filesystem;\n\n const nlohmann::json merged1 = getDeserializedJSON(\n getPathForJSONFile( INPUT( ( path( \"mergeable\" ) \/ \"inputs\" \/ \"merge1\" ).string( ) ) ) );\n\n const nlohmann::json manual1 =\n R\"(\n {\n \"type\": \"rungeKutta4\",\n \"stepSize\": 20\n }\n )\"_json;\n\n BOOST_CHECK_EQUAL( merged1, manual1 );\n\n\n const nlohmann::json merged2 = getDeserializedJSON(\n getPathForJSONFile( INPUT( ( path( \"mergeable\" ) \/ \"inputs\" \/ \"merge2\" ).string( ) ) ) );\n\n const nlohmann::json manual2 =\n R\"(\n {\n \"integrator\": {\n \"type\": \"rungeKutta4\",\n \"stepSize\": 20,\n \"initialTimes\": [\n 0,\n 86400\n ]\n }\n }\n )\"_json;\n\n BOOST_CHECK_EQUAL( merged2, manual2 );\n\n\n const nlohmann::json merged3 = getDeserializedJSON(\n getPathForJSONFile( INPUT( ( path( \"mergeable\" ) \/ \"inputs\" \/ \"merge3\" ).string( ) ) ) );\n\n const nlohmann::json manual3 =\n R\"(\n {\n \"integrator\": {\n \"type\": \"rungeKutta4\",\n \"stepSize\": 20,\n \"initialTimes\": [\n 0,\n 43200,\n 86400\n ]\n },\n \"spice\": {\n \"useStandardKernels\": true,\n \"preloadEpehemeris\": false\n }\n }\n )\"_json;\n\n BOOST_CHECK_EQUAL( merged3, manual3 );\n}\n\nBOOST_AUTO_TEST_SUITE_END( )\n\n} \/\/ namespace unit_tests\n\n} \/\/ namespace tudat\n<commit_msg>Fix path difference in unit test for windows.<commit_after>\/* Copyright (c) 2010-2017, Delft University of Technology\n * All rigths reserved\n *\n * This file is part of the Tudat. Redistribution and use in source and\n * binary forms, with or without modification, are permitted exclusively\n * under the terms of the Modified BSD license. You should have received\n * a copy of the license with this file. If not, please or visit:\n * http:\/\/tudat.tudelft.nl\/LICENSE.\n *\/\n\n#define BOOST_TEST_MAIN\n\n#include \"Tudat\/JsonInterface\/UnitTests\/unitTestSupport.h\"\n#include \"Tudat\/JsonInterface\/Support\/valueAccess.h\"\n#include \"Tudat\/JsonInterface\/Support\/valueConversions.h\"\n#include \"Tudat\/JsonInterface\/Support\/deserialization.h\"\n\nnamespace tudat\n{\n\nnamespace unit_tests\n{\n\n#define INPUT( filename ) \\\n ( json_interface::inputDirectory( ) \/ boost::filesystem::path( __FILE__ ).stem( ) \/ filename ).string( )\n\nBOOST_AUTO_TEST_SUITE( test_json_deserialization )\n\n\/\/ Test 1: value access\nBOOST_AUTO_TEST_CASE( test_json_valueAccess )\n{\n using namespace json_interface;\n\n const nlohmann::json dog = parseJSONFile( INPUT( \"valueAccess\" ) );\n\n \/\/ Numbers\n BOOST_CHECK_EQUAL( getValue< unsigned int >( dog, \"age\" ), 11 );\n BOOST_CHECK_EQUAL( getValue< int >( dog, \"age\" ), 11 );\n BOOST_CHECK_EQUAL( getValue< double >( dog, \"mass\" ), 19.5 );\n BOOST_CHECK_EQUAL( getValue< float >( dog, \"mass\" ), 19.5 );\n BOOST_CHECK_EQUAL( getValue< long double >( dog, \"mass\" ), 19.5 );\n\n \/\/ Strings\n BOOST_CHECK_EQUAL( getValue< std::string >( dog, \"name\" ), \"Bumper\" );\n\n \/\/ Arrays\n const std::vector< std::string > hobbies = { \"eat\", \"sleep\" };\n const std::string hobbiesKey = \"hobbies\";\n BOOST_CHECK( getValue< std::vector< std::string > >( dog, hobbiesKey ) == hobbies );\n BOOST_CHECK_EQUAL( getValue< std::string >( dog, hobbiesKey \/ 0 ), hobbies.at( 0 ) );\n BOOST_CHECK_EQUAL( getValue< std::string >( dog, hobbiesKey \/ 1 ), hobbies.at( 1 ) );\n\n \/\/ Context: one level\n const nlohmann::json enemy = getValue< std::vector< nlohmann::json > >( dog, \"enemies\" ).front( );\n BOOST_CHECK_EQUAL( getRootObject( enemy ), dog );\n BOOST_CHECK_EQUAL( getValue< double >( enemy, \"mass\" ), 2.6 );\n BOOST_CHECK_EQUAL( getValue< double >( enemy, SpecialKeys::up \/ SpecialKeys::up \/ \"mass\" ), 19.5 );\n BOOST_CHECK_EQUAL( getValue< double >( enemy, SpecialKeys::root \/ \"mass\" ), 19.5 );\n\n \/\/ Context: several levels\n const nlohmann::json valencia =\n getValue< nlohmann::json >( enemy, std::string( \"mother\" ) \/ \"birthplace\" \/ \"city\" );\n BOOST_CHECK_EQUAL( valencia.at( \"name\" ), \"Valencia\" );\n BOOST_CHECK_EQUAL( getValue< double >( valencia, SpecialKeys::root \/ \"mass\" ), 19.5 );\n BOOST_CHECK_EQUAL( getValue< double >( valencia, SpecialKeys::up \/ SpecialKeys::up \/ SpecialKeys::up \/\n SpecialKeys::up \/ SpecialKeys::up \/ \"mass\" ), 19.5 );\n BOOST_CHECK_EQUAL( getValue< double >( valencia, SpecialKeys::up \/ \"continent\" \/ \"temperatureRange\" \/ 0 ), -15 );\n BOOST_CHECK_EQUAL( getValue< double >( valencia, SpecialKeys::up \/ \"continent\" \/ \"temperatureRange\" \/ 1 ), 45 );\n\n \/\/ Eigen\n const Eigen::Matrix3d matrix = getValue< Eigen::Matrix3d >( dog, \"orientation\" );\n const Eigen::Matrix3d matrix2 = ( Eigen::Matrix3d( ) << 1.0, 0.0, 0.0, 0.0, 2.0, 1.0, 0.0, 3.0, -1.0 ).finished( );\n BOOST_CHECK_EQUAL( matrix, matrix2 );\n\n \/\/ Map with non-char keys\n const std::map< double, std::string > food = getValue< std::map< double, std::string > >( dog, \"food\" );\n const std::map< double, std::string > food2 = { { 7, \"feed\" }, { 12, \"meat\" }, { 15, \"feed\" }, { 19, \"feed\" } };\n BOOST_CHECK( food == food2 );\n}\n\n\/\/ Test 2: modular\nBOOST_AUTO_TEST_CASE( test_json_modular )\n{\n using namespace json_interface;\n\n const nlohmann::json modular = getDeserializedJSON( getPathForJSONFile( INPUT( \"modular\" ) ) );\n\n nlohmann::json simulation;\n simulation[ \"bodies\" ] =\n R\"(\n {\n \"Earth\": {\n \"useDefaultSettings\": true\n },\n \"satellite\": {\n \"mass\": 500\n }\n }\n )\"_json;\n\n simulation[ \"propagators\" ] =\n R\"(\n [\n {\n \"centralBodies\": [\n \"Earth\"\n ],\n \"bodiesToPropagate\": [\n \"satellite\"\n ]\n }\n ]\n )\"_json;\n\n simulation[ \"integrator\" ] =\n R\"(\n {\n \"type\": \"rungeKutta4\",\n \"stepSize\": 30\n }\n )\"_json;\n\n simulation[ \"export\" ] =\n R\"(\n [\n {\n \"variables\": [\n {\n \"type\": \"independent\"\n }\n ]\n },\n {\n \"variables\": [\n {\n \"body\": \"satellite\",\n \"dependentVariableType\": \"relativePosition\",\n \"relatieToBody\": \"Earth\"\n },\n {\n \"body\": \"satellite\",\n \"dependentVariableType\": \"relativeVelocity\",\n \"relatieToBody\": \"Earth\"\n }\n ]\n }\n ]\n )\"_json;\n\n simulation[ \"export\" ][ 0 ][ \"file\" ] =\n ( boost::filesystem::path( \"export\" ) \/ \"..\/outputs\/epochs.txt\" ).string( );\n simulation[ \"export\" ][ 1 ][ \"file\" ] =\n ( boost::filesystem::path( \"export\" ) \/ \"..\/states.txt\" ).string( );\n\n BOOST_CHECK_EQUAL( modular, simulation );\n}\n\n\/\/ Test 3: mergeable\nBOOST_AUTO_TEST_CASE( test_json_mergeable )\n{\n using namespace json_interface;\n using namespace boost::filesystem;\n\n const nlohmann::json merged1 = getDeserializedJSON(\n getPathForJSONFile( INPUT( ( path( \"mergeable\" ) \/ \"inputs\" \/ \"merge1\" ).string( ) ) ) );\n\n const nlohmann::json manual1 =\n R\"(\n {\n \"type\": \"rungeKutta4\",\n \"stepSize\": 20\n }\n )\"_json;\n\n BOOST_CHECK_EQUAL( merged1, manual1 );\n\n\n const nlohmann::json merged2 = getDeserializedJSON(\n getPathForJSONFile( INPUT( ( path( \"mergeable\" ) \/ \"inputs\" \/ \"merge2\" ).string( ) ) ) );\n\n const nlohmann::json manual2 =\n R\"(\n {\n \"integrator\": {\n \"type\": \"rungeKutta4\",\n \"stepSize\": 20,\n \"initialTimes\": [\n 0,\n 86400\n ]\n }\n }\n )\"_json;\n\n BOOST_CHECK_EQUAL( merged2, manual2 );\n\n\n const nlohmann::json merged3 = getDeserializedJSON(\n getPathForJSONFile( INPUT( ( path( \"mergeable\" ) \/ \"inputs\" \/ \"merge3\" ).string( ) ) ) );\n\n const nlohmann::json manual3 =\n R\"(\n {\n \"integrator\": {\n \"type\": \"rungeKutta4\",\n \"stepSize\": 20,\n \"initialTimes\": [\n 0,\n 43200,\n 86400\n ]\n },\n \"spice\": {\n \"useStandardKernels\": true,\n \"preloadEpehemeris\": false\n }\n }\n )\"_json;\n\n BOOST_CHECK_EQUAL( merged3, manual3 );\n}\n\nBOOST_AUTO_TEST_SUITE_END( )\n\n} \/\/ namespace unit_tests\n\n} \/\/ namespace tudat\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ Created by Vadim N. on 18\/03\/2015.\n\/\/\n\n#ifndef _BENCHMARK_H_\n#define _BENCHMARK_H_\n\n\n#include \"benchutils.h\"\n\n\nint main(int argc, char* argv[]) {\n\n if (argc < 2) {\n std::cout << \"Please re-run the script with the data folder path supplied.\" << std::endl;\n return 1;\n }\n\n std::chrono::system_clock::time_point tp1, tp2;\n\n std::vector< std::pair<std::string, size_t> > timepoints;\n\n std::vector<prob_t> logLvec;\n\n std::string temp_str;\n \n std::string BENCH_DATA_FOLDER = argv[1];\n\n ClonesetNuc cloneset_vj, cloneset_vdj, cloneset_vj_noncoding, cloneset_vdj_noncoding;\n\n\n string input_alpha_file = \"alpha.full.500k.txt\", input_alpha_file_nonc = \"alpha.noncoding.100k.txt\";\n string input_beta_file = \"beta.noncoding.500k.txt\", input_beta_file_nonc = \"beta.noncoding.100k.txt\";\n\n\n auto vdj_aligner_parameters_nuc = VDJAlignerParameters(3,\n VDJAlignmentEventScore(AlignmentEventScore(1, -1, 1),\n AlignmentEventScore(1, -1, 1),\n AlignmentEventScore(1, -1, 1)),\n VDJAlignmentScoreThreshold(2, 3, 2));\n\n ParserNuc parser(new NaiveCDR3NucleotideAligner());\n\n\n \/\/\n \/\/ TCR alpha chain repertoire - VJ recombination\n \/\/\n VDJRecombinationGenes vj_single_genes(\"Vgene\",\n BENCH_DATA_FOLDER + \"trav.txt\",\n \"Jgene\",\n BENCH_DATA_FOLDER + \"traj.txt\");\n\n YMIR_BENCHMARK(\"Parsing VJ\",\n parser.openAndParse(BENCH_DATA_FOLDER + input_alpha_file,\n &cloneset_vj,\n vj_single_genes,\n VJ_RECOMB,\n AlignmentColumnOptions(AlignmentColumnOptions::REALIGN_PROVIDED,\n AlignmentColumnOptions::REALIGN_PROVIDED),\n vdj_aligner_parameters_nuc))\n\n \/\/\n \/\/ TCR beta chain repertoire - VDJ recombination\n \/\/\n VDJRecombinationGenes vdj_single_genes(\"Vgene\",\n BENCH_DATA_FOLDER + \"trbv.txt\",\n \"Jgene\",\n BENCH_DATA_FOLDER + \"trbj.txt\",\n \"Dgene\",\n BENCH_DATA_FOLDER + \"trbd.txt\");\n\n YMIR_BENCHMARK(\"Parsing VDJ\",\n parser.openAndParse(BENCH_DATA_FOLDER + input_beta_file,\n &cloneset_vdj,\n vdj_single_genes,\n VDJ_RECOMB,\n AlignmentColumnOptions(AlignmentColumnOptions::REALIGN_PROVIDED,\n AlignmentColumnOptions::OVERWRITE,\n AlignmentColumnOptions::REALIGN_PROVIDED),\n vdj_aligner_parameters_nuc))\n\n \/\/\n \/\/ VJ MAAG\n \/\/\n vector<prob_t> vec;\n ProbabilisticAssemblingModel vj_single_model(BENCH_DATA_FOLDER + \"..\/..\/models\/hTRA\", EMPTY);\n YMIR_BENCHMARK(\"VJ meta\", vj_single_model.buildGraphs(cloneset_vj, SAVE_METADATA, NO_ERRORS, false))\n YMIR_BENCHMARK(\"VJ prob\", vec = vj_single_model.computeFullProbabilities(cloneset_vj, NO_ERRORS, SUM_PROBABILITY, false))\n std::cout << loglikelihood(vec) << std::endl;\n\n \/\/\n \/\/ VDJ MAAG\n \/\/\n ProbabilisticAssemblingModel vdj_single_model(BENCH_DATA_FOLDER + \"..\/..\/models\/hTRB\", EMPTY);\n YMIR_BENCHMARK(\"VDJ meta\", vdj_single_model.buildGraphs(cloneset_vdj, SAVE_METADATA, NO_ERRORS, false))\n YMIR_BENCHMARK(\"VDJ prob\", vdj_single_model.computeFullProbabilities(cloneset_vdj, NO_ERRORS, SUM_PROBABILITY, false))\n\n \/\/\n \/\/ VJ inference\n \/\/\n parser.openAndParse(BENCH_DATA_FOLDER + input_alpha_file_nonc,\n &cloneset_vj_noncoding,\n vj_single_genes,\n VJ_RECOMB,\n AlignmentColumnOptions(AlignmentColumnOptions::REALIGN_PROVIDED,\n AlignmentColumnOptions::REALIGN_PROVIDED),\n vdj_aligner_parameters_nuc);\n\n YMIR_BENCHMARK(\"VJ EM\",\n logLvec = EMAlgorithm().statisticalInference(cloneset_vj, vj_single_model,\n EMAlgorithm::AlgorithmParameters()\n .set(\"niter\", 30),\n NO_ERRORS))\n\/\/\n\/\/ YMIR_BENCHMARK(\"VJ SG\",\n\/\/ logLvec = SGAlgorithm().statisticalInference(cloneset_vj, vj_single_model,\n\/\/ SGAlgorithm::AlgorithmParameters()\n\/\/ .set(\"niter\", 10)\n\/\/ .set(\"block.size\", 5000)\n\/\/ .set(\"alpha\", .7)\n\/\/ .set(\"beta\", 1.)\n\/\/ .set(\"K\", 2.)\n\/\/ .set(\"prebuild\", false)\n\/\/ .set(\"sample\", 100000),\n\/\/ NO_ERRORS))\n\n\n \/\/\n \/\/ VDJ inference\n \/\/\n parser.openAndParse(BENCH_DATA_FOLDER + input_beta_file_nonc,\n &cloneset_vdj_noncoding,\n vdj_single_genes,\n VDJ_RECOMB,\n AlignmentColumnOptions(AlignmentColumnOptions::REALIGN_PROVIDED,\n AlignmentColumnOptions::OVERWRITE,\n AlignmentColumnOptions::REALIGN_PROVIDED),\n vdj_aligner_parameters_nuc);\n\n YMIR_BENCHMARK(\"VDJ EM\",\n logLvec = EMAlgorithm().statisticalInference(cloneset_vdj, vdj_single_model,\n EMAlgorithm::AlgorithmParameters()\n .set(\"niter\", 30),\n NO_ERRORS))\n\/\/\n\/\/ YMIR_BENCHMARK(\"VDJ SG\",\n\/\/ logLvec = SGAlgorithm().statisticalInference(cloneset_vdj, vdj_single_model,\n\/\/ SGAlgorithm::AlgorithmParameters()\n\/\/ .set(\"niter\", 10)\n\/\/ .set(\"block.size\", 5000)\n\/\/ .set(\"alpha\", .7)\n\/\/ .set(\"beta\", 1.)\n\/\/ .set(\"K\", 2.)\n\/\/ .set(\"prebuild\", false)\n\/\/ .set(\"sample\", 100000),\n\/\/ NO_ERRORS))\n\n \/\/\n \/\/ Results\n \/\/\n cout << \"========================\" << endl << \"Results:\" << endl;\n\n for (size_t i = 0; i < timepoints.size(); ++i) {\n cout << timepoints[i].first << \":\\t\" << timepoints[i].second << endl;\n }\n\n cout << endl << \"========================\" << endl;\n\n\n return 0;\n}\n\n#endif \/\/_BENCHMARK_H_\n<commit_msg>change aligner params<commit_after>\/\/\n\/\/ Created by Vadim N. on 18\/03\/2015.\n\/\/\n\n#ifndef _BENCHMARK_H_\n#define _BENCHMARK_H_\n\n\n#include \"benchutils.h\"\n\n\nint main(int argc, char* argv[]) {\n\n if (argc < 2) {\n std::cout << \"Please re-run the script with the data folder path supplied.\" << std::endl;\n return 1;\n }\n\n std::chrono::system_clock::time_point tp1, tp2;\n\n std::vector< std::pair<std::string, size_t> > timepoints;\n\n std::vector<prob_t> logLvec;\n\n std::string temp_str;\n \n std::string BENCH_DATA_FOLDER = argv[1];\n\n ClonesetNuc cloneset_vj, cloneset_vdj, cloneset_vj_noncoding, cloneset_vdj_noncoding;\n\n\n string input_alpha_file = \"alpha.full.500k.txt\", input_alpha_file_nonc = \"alpha.noncoding.100k.txt\";\n string input_beta_file = \"beta.noncoding.500k.txt\", input_beta_file_nonc = \"beta.noncoding.100k.txt\";\n\n\n auto vdj_aligner_parameters_nuc = VDJAlignerParameters(3,\n VDJAlignmentEventScore(AlignmentEventScore(1, -1, 1),\n AlignmentEventScore(1, -1, 1),\n AlignmentEventScore(1, -1, 1)),\n VDJAlignmentScoreThreshold(6, 3, 5));\n\n ParserNuc parser(new NaiveCDR3NucleotideAligner());\n\n\n \/\/\n \/\/ TCR alpha chain repertoire - VJ recombination\n \/\/\n VDJRecombinationGenes vj_single_genes(\"Vgene\",\n BENCH_DATA_FOLDER + \"trav.txt\",\n \"Jgene\",\n BENCH_DATA_FOLDER + \"traj.txt\");\n\n YMIR_BENCHMARK(\"Parsing VJ\",\n parser.openAndParse(BENCH_DATA_FOLDER + input_alpha_file,\n &cloneset_vj,\n vj_single_genes,\n VJ_RECOMB,\n AlignmentColumnOptions(AlignmentColumnOptions::OVERWRITE,\n AlignmentColumnOptions::OVERWRITE),\n vdj_aligner_parameters_nuc))\n\n \/\/\n \/\/ TCR beta chain repertoire - VDJ recombination\n \/\/\n VDJRecombinationGenes vdj_single_genes(\"Vgene\",\n BENCH_DATA_FOLDER + \"trbv.txt\",\n \"Jgene\",\n BENCH_DATA_FOLDER + \"trbj.txt\",\n \"Dgene\",\n BENCH_DATA_FOLDER + \"trbd.txt\");\n\n YMIR_BENCHMARK(\"Parsing VDJ\",\n parser.openAndParse(BENCH_DATA_FOLDER + input_beta_file,\n &cloneset_vdj,\n vdj_single_genes,\n VDJ_RECOMB,\n AlignmentColumnOptions(AlignmentColumnOptions::OVERWRITE,\n AlignmentColumnOptions::OVERWRITE,\n AlignmentColumnOptions::OVERWRITE),\n vdj_aligner_parameters_nuc))\n\n \/\/\n \/\/ VJ MAAG\n \/\/\n vector<prob_t> vec;\n ProbabilisticAssemblingModel vj_single_model(BENCH_DATA_FOLDER + \"..\/..\/models\/hTRA\", EMPTY);\n YMIR_BENCHMARK(\"VJ meta\", vj_single_model.buildGraphs(cloneset_vj, SAVE_METADATA, NO_ERRORS, false))\n YMIR_BENCHMARK(\"VJ prob\", vec = vj_single_model.computeFullProbabilities(cloneset_vj, NO_ERRORS, SUM_PROBABILITY, false))\n std::cout << loglikelihood(vec) << std::endl;\n\n \/\/\n \/\/ VDJ MAAG\n \/\/\n ProbabilisticAssemblingModel vdj_single_model(BENCH_DATA_FOLDER + \"..\/..\/models\/hTRB\", EMPTY);\n YMIR_BENCHMARK(\"VDJ meta\", vdj_single_model.buildGraphs(cloneset_vdj, SAVE_METADATA, NO_ERRORS, false))\n YMIR_BENCHMARK(\"VDJ prob\", vdj_single_model.computeFullProbabilities(cloneset_vdj, NO_ERRORS, SUM_PROBABILITY, false))\n\n \/\/\n \/\/ VJ inference\n \/\/\n parser.openAndParse(BENCH_DATA_FOLDER + input_alpha_file_nonc,\n &cloneset_vj_noncoding,\n vj_single_genes,\n VJ_RECOMB,\n AlignmentColumnOptions(AlignmentColumnOptions::REALIGN_PROVIDED,\n AlignmentColumnOptions::REALIGN_PROVIDED),\n vdj_aligner_parameters_nuc);\n\n YMIR_BENCHMARK(\"VJ EM\",\n logLvec = EMAlgorithm().statisticalInference(cloneset_vj, vj_single_model,\n EMAlgorithm::AlgorithmParameters()\n .set(\"niter\", 30),\n NO_ERRORS))\n\/\/\n\/\/ YMIR_BENCHMARK(\"VJ SG\",\n\/\/ logLvec = SGAlgorithm().statisticalInference(cloneset_vj, vj_single_model,\n\/\/ SGAlgorithm::AlgorithmParameters()\n\/\/ .set(\"niter\", 10)\n\/\/ .set(\"block.size\", 5000)\n\/\/ .set(\"alpha\", .7)\n\/\/ .set(\"beta\", 1.)\n\/\/ .set(\"K\", 2.)\n\/\/ .set(\"prebuild\", false)\n\/\/ .set(\"sample\", 100000),\n\/\/ NO_ERRORS))\n\n\n \/\/\n \/\/ VDJ inference\n \/\/\n parser.openAndParse(BENCH_DATA_FOLDER + input_beta_file_nonc,\n &cloneset_vdj_noncoding,\n vdj_single_genes,\n VDJ_RECOMB,\n AlignmentColumnOptions(AlignmentColumnOptions::REALIGN_PROVIDED,\n AlignmentColumnOptions::OVERWRITE,\n AlignmentColumnOptions::REALIGN_PROVIDED),\n vdj_aligner_parameters_nuc);\n\n YMIR_BENCHMARK(\"VDJ EM\",\n logLvec = EMAlgorithm().statisticalInference(cloneset_vdj, vdj_single_model,\n EMAlgorithm::AlgorithmParameters()\n .set(\"niter\", 30),\n NO_ERRORS))\n\/\/\n\/\/ YMIR_BENCHMARK(\"VDJ SG\",\n\/\/ logLvec = SGAlgorithm().statisticalInference(cloneset_vdj, vdj_single_model,\n\/\/ SGAlgorithm::AlgorithmParameters()\n\/\/ .set(\"niter\", 10)\n\/\/ .set(\"block.size\", 5000)\n\/\/ .set(\"alpha\", .7)\n\/\/ .set(\"beta\", 1.)\n\/\/ .set(\"K\", 2.)\n\/\/ .set(\"prebuild\", false)\n\/\/ .set(\"sample\", 100000),\n\/\/ NO_ERRORS))\n\n \/\/\n \/\/ Results\n \/\/\n cout << \"========================\" << endl << \"Results:\" << endl;\n\n for (size_t i = 0; i < timepoints.size(); ++i) {\n cout << timepoints[i].first << \":\\t\" << timepoints[i].second << endl;\n }\n\n cout << endl << \"========================\" << endl;\n\n\n return 0;\n}\n\n#endif \/\/_BENCHMARK_H_\n<|endoftext|>"} {"text":"<commit_before>\/\/=============================================================================\n\/\/ Copyright (c) 2017 Ryooooooga\n\/\/ https:\/\/github.com\/Ryooooooga\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"),\n\/\/ to deal in the Software without restriction, including without limitation\n\/\/ the rights to use, copy, modify, merge, publish, distribute, sublicense,\n\/\/ and\/or sell copies of the Software, and to permit persons to whom\n\/\/ the Software is furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n\/\/ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n\/\/ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\n\/\/ IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n\/\/ DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n\/\/ TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE\n\/\/ OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\/\/=============================================================================\n\n#ifndef INCLUDE_NENE_GRAPHICS_WINDOWS_DIRECT3D11_DYNAMICTEXTURE_HPP\n#define INCLUDE_NENE_GRAPHICS_WINDOWS_DIRECT3D11_DYNAMICTEXTURE_HPP\n\n#include \"..\/..\/..\/Platform.hpp\"\n#if defined(NENE_OS_WINDOWS)\n\n#include <memory>\n#include <d3d11.h>\n#include <wrl\/client.h>\n#include \"..\/..\/..\/Uncopyable.hpp\"\n#include \"..\/..\/IDynamicTexture.hpp\"\n\nnamespace Nene::Windows::Direct3D11\n{\n\t\/\/ Forward declarations.\n\tclass Texture;\n\n\t\/**\n\t * @brief Directr3D11 dynamic texture implementation.\n\t *\/\n\tclass DynamicTexture final\n\t\t: public IDynamicTexture\n\t\t, private Uncopyable\n\t{\n\t\tstd::unique_ptr<Texture> texture_;\n\n\t\tMicrosoft::WRL::ComPtr<ID3D11RenderTargetView> renderTarget_;\n\n\tpublic:\n\t\t\/**\n\t\t * @brief Constructor.\n\t\t *\n\t\t * @param[in] texture Direct3D11 texture.\n\t\t *\/\n\t\texplicit DynamicTexture(const Microsoft::WRL::ComPtr<ID3D11Texture2D>& texture);\n\n\t\t\/**\n\t\t * @brief Constructor.\n\t\t *\n\t\t * @param[in] device Direct3D11 device.\n\t\t * @param[in] size The texture size.\n\t\t * @param[in] format The texture pixel format.\n\t\t *\/\n\t\texplicit DynamicTexture(const Microsoft::WRL::ComPtr<ID3D11Device>& device, const Size2Di& size);\n\n\t\t\/**\n\t\t * @brief Destructor.\n\t\t *\/\n\t\t~DynamicTexture();\n\n\t\t\/**\n\t\t * @see `Nene::ITexture::size()`.\n\t\t *\/\n\t\t[[nodiscard]]\n\t\tconst Size2Di& size() const noexcept override;\n\t};\n}\n\n#endif\n\n#endif \/\/ #ifndef INCLUDE_NENE_GRAPHICS_WINDOWS_DIRECT3D11_DYNAMICTEXTURE_HPP\n<commit_msg>:pencil: Fix typo.<commit_after>\/\/=============================================================================\n\/\/ Copyright (c) 2017 Ryooooooga\n\/\/ https:\/\/github.com\/Ryooooooga\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"),\n\/\/ to deal in the Software without restriction, including without limitation\n\/\/ the rights to use, copy, modify, merge, publish, distribute, sublicense,\n\/\/ and\/or sell copies of the Software, and to permit persons to whom\n\/\/ the Software is furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n\/\/ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n\/\/ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\n\/\/ IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n\/\/ DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n\/\/ TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE\n\/\/ OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\/\/=============================================================================\n\n#ifndef INCLUDE_NENE_GRAPHICS_WINDOWS_DIRECT3D11_DYNAMICTEXTURE_HPP\n#define INCLUDE_NENE_GRAPHICS_WINDOWS_DIRECT3D11_DYNAMICTEXTURE_HPP\n\n#include \"..\/..\/..\/Platform.hpp\"\n#if defined(NENE_OS_WINDOWS)\n\n#include <memory>\n#include <d3d11.h>\n#include <wrl\/client.h>\n#include \"..\/..\/..\/Uncopyable.hpp\"\n#include \"..\/..\/IDynamicTexture.hpp\"\n\nnamespace Nene::Windows::Direct3D11\n{\n\t\/\/ Forward declarations.\n\tclass Texture;\n\n\t\/**\n\t * @brief Direct3D11 dynamic texture implementation.\n\t *\/\n\tclass DynamicTexture final\n\t\t: public IDynamicTexture\n\t\t, private Uncopyable\n\t{\n\t\tstd::unique_ptr<Texture> texture_;\n\n\t\tMicrosoft::WRL::ComPtr<ID3D11RenderTargetView> renderTarget_;\n\n\tpublic:\n\t\t\/**\n\t\t * @brief Constructor.\n\t\t *\n\t\t * @param[in] texture Direct3D11 texture.\n\t\t *\/\n\t\texplicit DynamicTexture(const Microsoft::WRL::ComPtr<ID3D11Texture2D>& texture);\n\n\t\t\/**\n\t\t * @brief Constructor.\n\t\t *\n\t\t * @param[in] device Direct3D11 device.\n\t\t * @param[in] size The texture size.\n\t\t * @param[in] format The texture pixel format.\n\t\t *\/\n\t\texplicit DynamicTexture(const Microsoft::WRL::ComPtr<ID3D11Device>& device, const Size2Di& size);\n\n\t\t\/**\n\t\t * @brief Destructor.\n\t\t *\/\n\t\t~DynamicTexture();\n\n\t\t\/**\n\t\t * @see `Nene::ITexture::size()`.\n\t\t *\/\n\t\t[[nodiscard]]\n\t\tconst Size2Di& size() const noexcept override;\n\t};\n}\n\n#endif\n\n#endif \/\/ #ifndef INCLUDE_NENE_GRAPHICS_WINDOWS_DIRECT3D11_DYNAMICTEXTURE_HPP\n<|endoftext|>"} {"text":"<commit_before>#include <cstdio>\n#include <cstdint>\n#include <vector>\n#include <limits>\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Represents the range [low,high]\ntemplate <typename VAL_T>\nclass value_range\n{\n public:\n\ttypedef VAL_T value_type;\n\ttypedef std::size_t size_type;\n\n\tvalue_range() : begin(0) , end(0) { }\n\n\tvalue_range(const value_type & low, const value_type & high)\n\t : begin(low) , end(high) { }\n\n\/*\n\tvalue_range(const value_range & other) = default;\n\tvalue_range(value_range && other) = default;\n\t~value_range() = default;\n*\/\n\n\tvalue_type min() const { return begin; }\n\n\tvalue_type max() const { return end; }\n\n\tsize_type size() const { return (end - begin); }\n\n\tbool intersects(const value_range & other)\n\t{\n\t\treturn ( ( other.begin >= begin && other.begin <= end )\n\t\t || ( other.end >= begin && other.end <= end )\n\t\t || ( begin >= other.begin && begin <= other.end )\n\t\t || ( end >= other.begin && end <= other.end ) );\n\t}\n\n\tbool operator == (const value_range & other)\n\t\t{ return ( (begin == other.begin) && (end == other.end) ); }\n\n private:\n\tvalue_type begin, end;\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvalue_range<uint32_t>\nfind_interval(std::vector<uint32_t> & interval_list, uint32_t val)\n{\n\tvalue_range<uint32_t> retval;\n\tuint32_t last = 0;\n\tfor (auto & x : interval_list)\n\t{\n\t\tif (val <= x)\n\t\t{\n\t\t\tretval = value_range<uint32_t>(last, x);\n\t\t\tbreak;\n\t\t}\n\n\t\tlast = x + 1;\n\t}\n\treturn retval;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvalue_range<uint32_t>\nfind_interval2(std::vector<uint32_t> & interval_list, uint32_t val)\n{\n\tvalue_range<uint32_t> retval;\n\tsize_t index = (interval_list.size() >> 1);\n\tsize_t lbound = 0;\n\tsize_t ubound = interval_list.size() - 1;\n\n\twhile ((ubound - lbound) > 1)\n\t{\n\t\tprintf(\"index = %zu, l = %zu, u = %zu\\n\", index, lbound, ubound);\n\t\tif (val <= interval_list[index])\n\t\t{\n\t\t\tubound = index;\n\t\t} else if (val > interval_list[index])\n\t\t{\n\t\t\tlbound = index;\n\t\t}\n\n\t\tindex = ((ubound + lbound) >> 1);\n\t}\n\n\tprintf(\"index = %zu, l = %zu, u = %zu\\n\", index, lbound, ubound);\n\tprintf(\"----> %u (%u-%u)\\n\", interval_list[index],\n\t interval_list[lbound], interval_list[ubound]);\n\n\treturn retval;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nint main()\n{\n\tstd::vector<value_range<uint32_t>> intervals;\n\tstd::vector<uint32_t> search;\n\n\tintervals.emplace_back(0, 20);\n\tintervals.emplace_back(intervals.back().max() + 1, 23);\n\tintervals.emplace_back(intervals.back().max() + 1, 24);\n\tintervals.emplace_back(intervals.back().max() + 1, 50);\n\tintervals.emplace_back(intervals.back().max() + 1, 60);\n\tintervals.emplace_back(intervals.back().max() + 1, 81);\n\tintervals.emplace_back(intervals.back().max() + 1, 85);\n\tintervals.emplace_back(intervals.back().max() + 1, 90);\n\tintervals.emplace_back(intervals.back().max() + 1, 99);\n\tintervals.emplace_back(intervals.back().max() + 1,\n\t std::numeric_limits<uint32_t>::max());\n\n\tsearch.reserve(intervals.size());\n\tfor (auto & r : intervals)\n\t{\n\t\tsearch.push_back(r.max());\n\t\tprintf(\"%u\\n\", r.max());\n\t}\n\n\tauto r = find_interval(search, 2);\n\tprintf(\"%u -> [%u-%u]\\n\", 2, r.min(), r.max());\n\tr = find_interval2(search, 2);\n\n\tr = find_interval(search, 80);\n\tprintf(\"%u -> [%u-%u]\\n\", 80, r.min(), r.max());\n\tr = find_interval2(search, 80);\n\n\tr = find_interval(search, 24);\n\tprintf(\"%u -> [%u-%u]\\n\", 24, r.min(), r.max());\n\tr = find_interval2(search, 24);\n\n\tr = find_interval2(search, 2000);\n\n\treturn 0;\n}\n<commit_msg>More fun with intervals<commit_after>#include <cstdio>\n#include <cstdint>\n#include <vector>\n#include <limits>\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Represents the range [low,high]\ntemplate <typename VAL_T>\nclass value_range\n{\n public:\n\ttypedef VAL_T value_type;\n\ttypedef std::size_t size_type;\n\n\tvalue_range() : begin(0) , end(0) { }\n\n\tvalue_range(const value_type & low, const value_type & high)\n\t : begin(low) , end(high) { }\n\n\/*\n\tvalue_range(const value_range & other) = default;\n\tvalue_range(value_range && other) = default;\n\t~value_range() = default;\n*\/\n\n\tvalue_type & min() { return begin; }\n\tconst value_type & min() const { return begin; }\n\n\tvalue_type & max() { return end; }\n\tconst value_type & max() const { return end; }\n\n\tsize_type size() const { return (end - begin); }\n\n\tbool intersects(const value_range & other)\n\t{\n\t\treturn ( ( other.begin >= begin && other.begin <= end )\n\t\t || ( other.end >= begin && other.end <= end )\n\t\t || ( begin >= other.begin && begin <= other.end )\n\t\t || ( end >= other.begin && end <= other.end ) );\n\t}\n\n\tbool operator == (const value_range & other)\n\t\t{ return ( (begin == other.begin) && (end == other.end) ); }\n\n private:\n\tvalue_type begin, end;\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate <typename T>\nvalue_range<T> find_interval(const std::vector<T> & interval_list, T val)\n{\n\tint i = 1;\n\tvalue_range<T> retval { std::numeric_limits<T>::min(),\n\t std::numeric_limits<T>::max() };\n\n\/\/\tuint32_t last = std::numeric_limits<uint32_t>::min();\n\n\tfor (auto & x : interval_list)\n\t{\n\t\t++i;\n\t\tif (val <= x)\n\t\t{\n\t\t\tretval.max() = x;\n\t\t\tbreak;\n\t\t}\n\n\t\tretval.min() = x + 1;\n\t}\n\tprintf(\"--> i = %d\\n\", i);\n\treturn retval;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate <typename T>\nvalue_range<T> find_interval2(const std::vector<T> & list, T val)\n{\n\tvalue_range<T> retval { std::numeric_limits<T>::min(),\n\t\t std::numeric_limits<T>::max() };\n\tint i = 1;\n\n\tif (list.empty())\n\t{\n\t\t\/\/ do nothing\n\t} else if (val <= list.front())\n\t{\n\t\tretval.max() = list.front();\n\t} else if (val > list.back())\n\t{\n\t\tretval.min() = list.back() + 1;\n\t\t++i;\n\t} else\n\t{\n\t\t++i;\n\t\t++i;\n\t\tsize_t lower = 0;\n\t\tsize_t upper = (list.size() - 1);\n\t\tsize_t middle;\n\t\twhile (upper - lower > 1)\n\t\t{\n\t\t\tmiddle = ((upper + lower) >> 1);\n\n\t\t\tif (val <= list[middle])\n\t\t\t\tupper = middle;\n\t\t\telse\n\t\t\t\tlower = middle;\n\n\t\t\t++i;\n\t\t}\n\t\tretval = value_range<T>{list[lower] + 1, list[upper]};\n\t}\n\n\tprintf(\"--> i = %d\\n\", i);\n\n\treturn retval;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nint main()\n{\n\tstd::vector<value_range<uint32_t>> intervals;\n\tstd::vector<uint32_t> search;\n\tstd::vector<uint32_t> search2;\n\n\tintervals.emplace_back(0, 9);\n\tintervals.emplace_back(intervals.back().max() + 1, 15);\n\tintervals.emplace_back(intervals.back().max() + 1, 21);\n\tintervals.emplace_back(intervals.back().max() + 1, 23);\n\tintervals.emplace_back(intervals.back().max() + 1, 24);\n\tintervals.emplace_back(intervals.back().max() + 1, 50);\n\tintervals.emplace_back(intervals.back().max() + 1, 60);\n\tintervals.emplace_back(intervals.back().max() + 1, 81);\n\tintervals.emplace_back(intervals.back().max() + 1, 85);\n\tintervals.emplace_back(intervals.back().max() + 1, 90);\n\tintervals.emplace_back(intervals.back().max() + 1, intervals.back().max() + 5);\n\tintervals.emplace_back(intervals.back().max() + 1, intervals.back().max() + 5);\n\tintervals.emplace_back(intervals.back().max() + 1, intervals.back().max() + 5);\n\tintervals.emplace_back(intervals.back().max() + 1, intervals.back().max() + 5);\n\tintervals.emplace_back(intervals.back().max() + 1, intervals.back().max() + 5);\n\tintervals.emplace_back(intervals.back().max() + 1, intervals.back().max() + 5);\n\tintervals.emplace_back(intervals.back().max() + 1, intervals.back().max() + 5);\n\tintervals.emplace_back(intervals.back().max() + 1, intervals.back().max() + 5);\n\tintervals.emplace_back(intervals.back().max() + 1, intervals.back().max() + 5);\n\tintervals.emplace_back(intervals.back().max() + 1, intervals.back().max() + 5);\n\tintervals.emplace_back(intervals.back().max() + 1, intervals.back().max() + 5);\n\tintervals.emplace_back(intervals.back().max() + 1, intervals.back().max() + 5);\n\tintervals.emplace_back(intervals.back().max() + 1, intervals.back().max() + 5);\n\tintervals.emplace_back(intervals.back().max() + 1, intervals.back().max() + 5);\n\tintervals.emplace_back(intervals.back().max() + 1, intervals.back().max() + 5);\n\tintervals.emplace_back(intervals.back().max() + 1, intervals.back().max() + 5);\n\tintervals.emplace_back(intervals.back().max() + 1, intervals.back().max() + 5);\n\tintervals.emplace_back(intervals.back().max() + 1, intervals.back().max() + 5);\n\tintervals.emplace_back(intervals.back().max() + 1, intervals.back().max() + 5);\n\tintervals.emplace_back(intervals.back().max() + 1, intervals.back().max() + 5);\n\tintervals.emplace_back(intervals.back().max() + 1, intervals.back().max() + 5);\n\tintervals.emplace_back(intervals.back().max() + 1, intervals.back().max() + 5);\n\tintervals.emplace_back(intervals.back().max() + 1, intervals.back().max() + 5);\n\tintervals.emplace_back(intervals.back().max() + 1, intervals.back().max() + 5);\n\tintervals.emplace_back(intervals.back().max() + 1, intervals.back().max() + 5);\n\/*\n\tintervals.emplace_back(intervals.back().max() + 1,\n\t std::numeric_limits<uint32_t>::max());\n*\/\n\n\tprintf(\"SIZE = %zu\\n\", intervals.size());\n\tsearch.reserve(intervals.size());\n\tsearch2.reserve(intervals.size() + 1);\n\t\/\/search2.push_back(0);\n\tfor (auto & r : intervals)\n\t{\n\t\tsearch.push_back(r.max());\n\t\tsearch2.push_back(r.max());\n\t\tprintf(\"%u\\n\", r.max());\n\t}\n\n\tauto r = find_interval(search, 2u);\n\tprintf(\"%u -> [%u-%u]\\n\", 2u, r.min(), r.max());\n\tr = find_interval2(search2, 2u);\n\tprintf(\"%u -> [%u-%u]\\n\", 2u, r.min(), r.max());\n\n\tr = find_interval(search, 80u);\n\tprintf(\"%u -> [%u-%u]\\n\", 80u, r.min(), r.max());\n\tr = find_interval2(search2, 80u);\n\tprintf(\"%u -> [%u-%u]\\n\", 80u, r.min(), r.max());\n\n\tr = find_interval(search, 24u);\n\tprintf(\"%u -> [%u-%u]\\n\", 24u, r.min(), r.max());\n\tr = find_interval2(search2, 24u);\n\tprintf(\"%u -> [%u-%u]\\n\", 24u, r.min(), r.max());\n\n\tr = find_interval(search, 2000u);\n\tprintf(\"%u -> [%u-%u]\\n\", 2000u, r.min(), r.max());\n\tr = find_interval2(search2, 2000u);\n\tprintf(\"%u -> [%u-%u]\\n\", 2000u, r.min(), r.max());\n\n\tr = find_interval(search, 125u);\n\tprintf(\"%u -> [%u-%u]\\n\", 125u, r.min(), r.max());\n\tr = find_interval2(search2, 125u);\n\tprintf(\"%u -> [%u-%u]\\n\", 125u, r.min(), r.max());\n\n\tr = find_interval(search, 4294967295u);\n\tprintf(\"%u -> [%u-%u]\\n\", 4294967295u, r.min(), r.max());\n\tr = find_interval2(search2, 4294967295u);\n\tprintf(\"%u -> [%u-%u]\\n\", 4294967295u, r.min(), r.max());\n\n\treturn 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*=========================================================================\n\n Program: Visualization Toolkit\n Module: vtkConnectivityFilter.cc\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n\nCopyright (c) 1993-1995 Ken Martin, Will Schroeder, Bill Lorensen.\n\nThis software is copyrighted by Ken Martin, Will Schroeder and Bill Lorensen.\nThe following terms apply to all files associated with the software unless\nexplicitly disclaimed in individual files. This copyright specifically does\nnot apply to the related textbook \"The Visualization Toolkit\" ISBN\n013199837-4 published by Prentice Hall which is covered by its own copyright.\n\nThe authors hereby grant permission to use, copy, and distribute this\nsoftware and its documentation for any purpose, provided that existing\ncopyright notices are retained in all copies and that this notice is included\nverbatim in any distributions. Additionally, the authors grant permission to\nmodify this software and its documentation for any purpose, provided that\nsuch modifications are not distributed without the explicit consent of the\nauthors and that existing copyright notices are retained in all copies. Some\nof the algorithms implemented by this software are patented, observe all\napplicable patent law.\n\nIN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR\nDIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT\nOF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF,\nEVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\nTHE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING,\nBUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\nPARTICULAR PURPOSE, AND NON-INFRINGEMENT. THIS SOFTWARE IS PROVIDED ON AN\n\"AS IS\" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE\nMAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.\n\n\n=========================================================================*\/\n#include \"vtkConnectivityFilter.hh\"\n\n\/\/ Description:\n\/\/ Construct with default extraction mode to extract largest regions.\nvtkConnectivityFilter::vtkConnectivityFilter()\n{\n this->ExtractionMode = VTK_EXTRACT_LARGEST_REGION;\n this->ColorRegions = 0;\n this->MaxRecursionDepth = 10000;\n}\n\nstatic NumExceededMaxDepth;\nstatic int *Visited, *PointMap;\nstatic vtkFloatScalars *NewScalars;\nstatic int RecursionDepth;\nstatic int RegionNumber, PointNumber; \nstatic int NumCellsInRegion;\nstatic vtkIdList *RecursionSeeds;\n\nvoid vtkConnectivityFilter::Execute()\n{\n int cellId, i, j, pt;\n int numPts, numCells;\n vtkFloatPoints *newPts;\n vtkIdList cellIds(VTK_CELL_SIZE), ptIds(VTK_CELL_SIZE);\n vtkPointData *pd;\n int id;\n int maxCellsInRegion, largestRegionId;\n vtkUnstructuredGrid *output = this->GetOutput();\n vtkPointData *outputPD = output->GetPointData();\n \n vtkDebugMacro(<<\"Executing connectivity filter.\");\n \/\/\n \/\/ Check input\/allocate storage\n \/\/\n if ( (numPts=this->Input->GetNumberOfPoints()) < 1 ||\n (numCells=this->Input->GetNumberOfCells()) < 1 )\n {\n vtkDebugMacro(<<\"No data to connect!\");\n return;\n }\n output->Allocate(numCells,numCells);\n \/\/\n \/\/ Initialize. Keep track of points and cells visited.\n \/\/\n this->RegionSizes.Reset();\n Visited = new int[numCells];\n for ( i=0; i < numCells; i++ ) Visited[i] = -1;\n PointMap = new int[numPts]; \n for ( i=0; i < numPts; i++ ) PointMap[i] = -1;\n\n NewScalars = new vtkFloatScalars(numPts);\n newPts = new vtkFloatPoints(numPts);\n \/\/\n \/\/ Traverse all cells marking those visited. Each new search\n \/\/ starts a new connected region. Note: have to truncate recursion\n \/\/ and keep track of seeds to start up again.\n \/\/\n RecursionSeeds = new vtkIdList(1000,10000);\n\n NumExceededMaxDepth = 0;\n PointNumber = 0;\n RegionNumber = 0;\n maxCellsInRegion = 0;\n\n if ( this->ExtractionMode != VTK_EXTRACT_POINT_SEEDED_REGIONS && \n this->ExtractionMode != VTK_EXTRACT_CELL_SEEDED_REGIONS ) \n { \/\/visit all cells marking with region number\n for (cellId=0; cellId < numCells; cellId++)\n {\n if ( Visited[cellId] < 0 ) \n {\n NumCellsInRegion = 0;\n RecursionDepth = 0;\n this->TraverseAndMark (cellId);\n\n for (i=0; i < RecursionSeeds->GetNumberOfIds(); i++) \n {\n RecursionDepth = 0;\n this->TraverseAndMark (RecursionSeeds->GetId(i));\n }\n\n if ( NumCellsInRegion > maxCellsInRegion )\n {\n maxCellsInRegion = NumCellsInRegion;\n largestRegionId = RegionNumber;\n }\n\n this->RegionSizes.InsertValue(RegionNumber++,NumCellsInRegion);\n RecursionSeeds->Reset();\n }\n }\n }\n else \/\/ regions have been seeded, everything considered in same region\n {\n NumCellsInRegion = 0;\n\n if ( this->ExtractionMode == VTK_EXTRACT_POINT_SEEDED_REGIONS )\n {\n for (i=0; i < this->Seeds.GetNumberOfIds(); i++) \n {\n pt = this->Seeds.GetId(i);\n if ( pt >= 0 ) \n {\n this->Input->GetPointCells(pt,cellIds);\n for (j=0; j < cellIds.GetNumberOfIds(); j++) \n RecursionSeeds->InsertNextId(cellIds.GetId(j));\n }\n }\n }\n else if ( this->ExtractionMode == VTK_EXTRACT_CELL_SEEDED_REGIONS )\n {\n for (i=0; i < this->Seeds.GetNumberOfIds(); i++) \n {\n cellId = this->Seeds.GetId(i);\n if ( cellId >= 0 ) RecursionSeeds->InsertNextId(cellId);\n }\n }\n\n \/\/mark all seeded regions\n for (i=0; i < RecursionSeeds->GetNumberOfIds(); i++) \n {\n RecursionDepth = 0;\n this->TraverseAndMark (RecursionSeeds->GetId(i));\n }\n this->RegionSizes.InsertValue(RegionNumber,NumCellsInRegion);\n }\n\n vtkDebugMacro (<<\"Extracted \" << RegionNumber << \" region(s)\");\n vtkDebugMacro (<<\"Exceeded recursion depth \" << NumExceededMaxDepth \n << \" times\\n\");\n\n RecursionSeeds->Delete();\n\/\/\n\/\/ Now that points and cells have been marked, traverse these lists pulling\n\/\/ everything that has been visited.\n\/\/\n \/\/Pass through point data that has been visited\n pd = this->Input->GetPointData();\n if ( this->ColorRegions ) outputPD->CopyScalarsOff();\n outputPD->CopyAllocate(pd);\n\n for (i=0; i < numPts; i++)\n {\n if ( PointMap[i] > -1 )\n {\n newPts->SetPoint(PointMap[i],this->Input->GetPoint(i));\n outputPD->CopyData(pd,i,PointMap[i]);\n }\n }\n\n \/\/ if coloring regions; send down new scalar data\n if ( this->ColorRegions ) outputPD->SetScalars(NewScalars);\n NewScalars->Delete();\n\n output->SetPoints(newPts);\n newPts->Delete();\n\/\/\n\/\/ Create output cells\n\/\/\n if ( this->ExtractionMode == VTK_EXTRACT_POINT_SEEDED_REGIONS ||\n this->ExtractionMode == VTK_EXTRACT_CELL_SEEDED_REGIONS )\n { \/\/ extract any cell that's been visited\n for (cellId=0; cellId < numCells; cellId++)\n {\n if ( Visited[cellId] >= 0 )\n {\n this->Input->GetCellPoints(cellId, ptIds);\n for (i=0; i < ptIds.GetNumberOfIds(); i++)\n {\n id = PointMap[ptIds.GetId(i)];\n ptIds.InsertId(i,id);\n }\n output->InsertNextCell(this->Input->GetCellType(cellId),ptIds);\n }\n }\n }\n else if ( this->ExtractionMode == VTK_EXTRACT_SPECIFIED_REGIONS )\n {\n for (cellId=0; cellId < numCells; cellId++)\n {\n int inReg, regionId;\n if ( (regionId=Visited[cellId]) >= 0 )\n {\n for (inReg=0,i=0; i<this->SpecifiedRegionIds.GetNumberOfIds(); i++)\n {\n if ( regionId == this->SpecifiedRegionIds.GetId(i) )\n {\n inReg = 1;\n break;\n }\n }\n if ( inReg )\n {\n this->Input->GetCellPoints(cellId, ptIds);\n for (i=0; i < ptIds.GetNumberOfIds(); i++)\n {\n id = PointMap[ptIds.GetId(i)];\n ptIds.InsertId(i,id);\n }\n output->InsertNextCell(this->Input->GetCellType(cellId),ptIds);\n }\n }\n }\n }\n else \/\/extract largest region\n {\n for (cellId=0; cellId < numCells; cellId++)\n {\n if ( Visited[cellId] == largestRegionId )\n {\n this->Input->GetCellPoints(cellId, ptIds);\n for (i=0; i < ptIds.GetNumberOfIds(); i++)\n {\n id = PointMap[ptIds.GetId(i)];\n ptIds.InsertId(i,id);\n }\n output->InsertNextCell(this->Input->GetCellType(cellId),ptIds);\n }\n }\n }\n\n delete [] Visited;\n delete [] PointMap;\n\n vtkDebugMacro (<<\"Extracted \" << output->GetNumberOfCells() << \" cells\");\n\n return;\n}\n\n\/\/\n\/\/ Mark current cell as visited and assign region number. Note:\n\/\/ traversal occurs across shared vertices.\n\/\/\nvoid vtkConnectivityFilter::TraverseAndMark (int cellId)\n{\n int j, k, ptId;\n vtkIdList ptIds, cellIds;\n\n Visited[cellId] = RegionNumber;\n NumCellsInRegion++;\n\n if ( RecursionDepth++ > this->MaxRecursionDepth ) \n {\n RecursionSeeds->InsertNextId(cellId);\n NumExceededMaxDepth++;\n return;\n }\n\n this->Input->GetCellPoints(cellId, ptIds);\n\n for (j=0; j < ptIds.GetNumberOfIds(); j++) \n {\n if ( PointMap[ptId=ptIds.GetId(j)] < 0 )\n {\n PointMap[ptId] = PointNumber++;\n NewScalars->SetScalar(PointMap[ptId], RegionNumber);\n }\n \n this->Input->GetPointCells(ptId,cellIds);\n\n for (k=0; k < cellIds.GetNumberOfIds(); k++)\n if ( Visited[cellIds.GetId(k)] < 0 )\n TraverseAndMark (cellIds.GetId(k));\n\n } \/\/ for all cells of this element\n\n RecursionDepth--;\n return;\n}\n\n\/\/ Description:\n\/\/ Obtain the number of connected regions.\nint vtkConnectivityFilter::GetNumberOfExtractedRegions()\n{\n return this->RegionSizes.GetSize();\n}\n\n\/\/ Description:\n\/\/ Set the extraction mode to extract regions sharing specified point ids.\nvoid vtkConnectivityFilter::ExtractPointSeededRegions()\n{\n if ( this->ExtractionMode != VTK_EXTRACT_POINT_SEEDED_REGIONS )\n {\n this->Modified();\n this->ExtractionMode = VTK_EXTRACT_POINT_SEEDED_REGIONS;\n }\n}\n\n\/\/ Description:\n\/\/ Set the extraction mode to extract regions sharing specified cell ids.\nvoid vtkConnectivityFilter::ExtractCellSeededRegions()\n{\n if ( this->ExtractionMode != VTK_EXTRACT_CELL_SEEDED_REGIONS )\n {\n this->Modified();\n this->ExtractionMode = VTK_EXTRACT_CELL_SEEDED_REGIONS;\n }\n}\n\n\/\/ Description:\n\/\/ Set the extraction mode to extract regions of specified id. You may \n\/\/ have to execute filter first (with debug turned on) to determine region ids.\nvoid vtkConnectivityFilter::ExtractSpecifiedRegions()\n{\n if ( this->ExtractionMode != VTK_EXTRACT_SPECIFIED_REGIONS )\n {\n this->Modified();\n this->ExtractionMode = VTK_EXTRACT_SPECIFIED_REGIONS;\n }\n}\n\n\/\/ Description:\n\/\/ Set the extraction mode to extract the largest region found.\nvoid vtkConnectivityFilter::ExtractLargestRegion()\n{\n if ( this->ExtractionMode != VTK_EXTRACT_LARGEST_REGION )\n {\n this->Modified();\n this->ExtractionMode = VTK_EXTRACT_LARGEST_REGION;\n }\n}\n\n\/\/ Description:\n\/\/ Initialize list of point ids\/cell ids used to seed regions.\nvoid vtkConnectivityFilter::InitializeSeedList()\n{\n this->Modified();\n this->Seeds.Reset();\n}\n\n\/\/ Description:\n\/\/ Add a seed id (point or cell id). Note: ids are 0-offset.\nvoid vtkConnectivityFilter::AddSeed(int id)\n{\n this->Modified();\n this->Seeds.InsertNextId(id);\n}\n\n\/\/ Description:\n\/\/ Delete a seed id (point or cell id). Note: ids are 0-offset.\nvoid vtkConnectivityFilter::DeleteSeed(int id)\n{\n this->Modified();\n this->Seeds.DeleteId(id);\n}\n\n\/\/ Description:\n\/\/ Initialize list of region ids to extract.\nvoid vtkConnectivityFilter::InitializeSpecifiedRegionList()\n{\n this->Modified();\n this->SpecifiedRegionIds.Reset();\n}\n\n\/\/ Description:\n\/\/ Add a region id to extract. Note: ids are 0-offset.\nvoid vtkConnectivityFilter::AddSpecifiedRegion(int id)\n{\n this->Modified();\n this->SpecifiedRegionIds.InsertNextId(id);\n}\n\n\/\/ Description:\n\/\/ Delete a region id to extract. Note: ids are 0-offset.\nvoid vtkConnectivityFilter::DeleteSpecifiedRegion(int id)\n{\n this->Modified();\n this->SpecifiedRegionIds.DeleteId(id);\n}\n\nvoid vtkConnectivityFilter::PrintSelf(ostream& os, vtkIndent indent)\n{\n vtkDataSetToUnstructuredGridFilter::PrintSelf(os,indent);\n\n os << indent << \"Extraction Mode: \";\n switch (this->ExtractionMode)\n {\n case VTK_EXTRACT_POINT_SEEDED_REGIONS:\n os << \"(Extract point seeded regions)\\n\";\n break;\n case VTK_EXTRACT_CELL_SEEDED_REGIONS:\n os << \"(Extract cell seeded regions)\\n\";\n break;\n case VTK_EXTRACT_SPECIFIED_REGIONS:\n os << \"(Extract specified regions)\\n\";\n break;\n case VTK_EXTRACT_LARGEST_REGION:\n os << \"(Extract largest region)\\n\";\n break;\n }\n\n os << indent << \"Color Regions: \" << (this->ColorRegions ? \"On\\n\" : \"Off\\n\");\n os << indent << \"Maximum Recursion Depth: \" << this->MaxRecursionDepth << \"\\n\";\n}\n\n<commit_msg>minor fix<commit_after>\/*=========================================================================\n\n Program: Visualization Toolkit\n Module: vtkConnectivityFilter.cc\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n\nCopyright (c) 1993-1995 Ken Martin, Will Schroeder, Bill Lorensen.\n\nThis software is copyrighted by Ken Martin, Will Schroeder and Bill Lorensen.\nThe following terms apply to all files associated with the software unless\nexplicitly disclaimed in individual files. This copyright specifically does\nnot apply to the related textbook \"The Visualization Toolkit\" ISBN\n013199837-4 published by Prentice Hall which is covered by its own copyright.\n\nThe authors hereby grant permission to use, copy, and distribute this\nsoftware and its documentation for any purpose, provided that existing\ncopyright notices are retained in all copies and that this notice is included\nverbatim in any distributions. Additionally, the authors grant permission to\nmodify this software and its documentation for any purpose, provided that\nsuch modifications are not distributed without the explicit consent of the\nauthors and that existing copyright notices are retained in all copies. Some\nof the algorithms implemented by this software are patented, observe all\napplicable patent law.\n\nIN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR\nDIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT\nOF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF,\nEVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\nTHE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING,\nBUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\nPARTICULAR PURPOSE, AND NON-INFRINGEMENT. THIS SOFTWARE IS PROVIDED ON AN\n\"AS IS\" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE\nMAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.\n\n\n=========================================================================*\/\n#include \"vtkConnectivityFilter.hh\"\n\n\/\/ Description:\n\/\/ Construct with default extraction mode to extract largest regions.\nvtkConnectivityFilter::vtkConnectivityFilter()\n{\n this->ExtractionMode = VTK_EXTRACT_LARGEST_REGION;\n this->ColorRegions = 0;\n this->MaxRecursionDepth = 10000;\n}\n\nstatic int NumExceededMaxDepth;\nstatic int *Visited, *PointMap;\nstatic vtkFloatScalars *NewScalars;\nstatic int RecursionDepth;\nstatic int RegionNumber, PointNumber; \nstatic int NumCellsInRegion;\nstatic vtkIdList *RecursionSeeds;\n\nvoid vtkConnectivityFilter::Execute()\n{\n int cellId, i, j, pt;\n int numPts, numCells;\n vtkFloatPoints *newPts;\n vtkIdList cellIds(VTK_CELL_SIZE), ptIds(VTK_CELL_SIZE);\n vtkPointData *pd;\n int id;\n int maxCellsInRegion, largestRegionId;\n vtkUnstructuredGrid *output = this->GetOutput();\n vtkPointData *outputPD = output->GetPointData();\n \n vtkDebugMacro(<<\"Executing connectivity filter.\");\n \/\/\n \/\/ Check input\/allocate storage\n \/\/\n if ( (numPts=this->Input->GetNumberOfPoints()) < 1 ||\n (numCells=this->Input->GetNumberOfCells()) < 1 )\n {\n vtkDebugMacro(<<\"No data to connect!\");\n return;\n }\n output->Allocate(numCells,numCells);\n \/\/\n \/\/ Initialize. Keep track of points and cells visited.\n \/\/\n this->RegionSizes.Reset();\n Visited = new int[numCells];\n for ( i=0; i < numCells; i++ ) Visited[i] = -1;\n PointMap = new int[numPts]; \n for ( i=0; i < numPts; i++ ) PointMap[i] = -1;\n\n NewScalars = new vtkFloatScalars(numPts);\n newPts = new vtkFloatPoints(numPts);\n \/\/\n \/\/ Traverse all cells marking those visited. Each new search\n \/\/ starts a new connected region. Note: have to truncate recursion\n \/\/ and keep track of seeds to start up again.\n \/\/\n RecursionSeeds = new vtkIdList(1000,10000);\n\n NumExceededMaxDepth = 0;\n PointNumber = 0;\n RegionNumber = 0;\n maxCellsInRegion = 0;\n\n if ( this->ExtractionMode != VTK_EXTRACT_POINT_SEEDED_REGIONS && \n this->ExtractionMode != VTK_EXTRACT_CELL_SEEDED_REGIONS ) \n { \/\/visit all cells marking with region number\n for (cellId=0; cellId < numCells; cellId++)\n {\n if ( Visited[cellId] < 0 ) \n {\n NumCellsInRegion = 0;\n RecursionDepth = 0;\n this->TraverseAndMark (cellId);\n\n for (i=0; i < RecursionSeeds->GetNumberOfIds(); i++) \n {\n RecursionDepth = 0;\n this->TraverseAndMark (RecursionSeeds->GetId(i));\n }\n\n if ( NumCellsInRegion > maxCellsInRegion )\n {\n maxCellsInRegion = NumCellsInRegion;\n largestRegionId = RegionNumber;\n }\n\n this->RegionSizes.InsertValue(RegionNumber++,NumCellsInRegion);\n RecursionSeeds->Reset();\n }\n }\n }\n else \/\/ regions have been seeded, everything considered in same region\n {\n NumCellsInRegion = 0;\n\n if ( this->ExtractionMode == VTK_EXTRACT_POINT_SEEDED_REGIONS )\n {\n for (i=0; i < this->Seeds.GetNumberOfIds(); i++) \n {\n pt = this->Seeds.GetId(i);\n if ( pt >= 0 ) \n {\n this->Input->GetPointCells(pt,cellIds);\n for (j=0; j < cellIds.GetNumberOfIds(); j++) \n RecursionSeeds->InsertNextId(cellIds.GetId(j));\n }\n }\n }\n else if ( this->ExtractionMode == VTK_EXTRACT_CELL_SEEDED_REGIONS )\n {\n for (i=0; i < this->Seeds.GetNumberOfIds(); i++) \n {\n cellId = this->Seeds.GetId(i);\n if ( cellId >= 0 ) RecursionSeeds->InsertNextId(cellId);\n }\n }\n\n \/\/mark all seeded regions\n for (i=0; i < RecursionSeeds->GetNumberOfIds(); i++) \n {\n RecursionDepth = 0;\n this->TraverseAndMark (RecursionSeeds->GetId(i));\n }\n this->RegionSizes.InsertValue(RegionNumber,NumCellsInRegion);\n }\n\n vtkDebugMacro (<<\"Extracted \" << RegionNumber << \" region(s)\");\n vtkDebugMacro (<<\"Exceeded recursion depth \" << NumExceededMaxDepth \n << \" times\\n\");\n\n RecursionSeeds->Delete();\n\/\/\n\/\/ Now that points and cells have been marked, traverse these lists pulling\n\/\/ everything that has been visited.\n\/\/\n \/\/Pass through point data that has been visited\n pd = this->Input->GetPointData();\n if ( this->ColorRegions ) outputPD->CopyScalarsOff();\n outputPD->CopyAllocate(pd);\n\n for (i=0; i < numPts; i++)\n {\n if ( PointMap[i] > -1 )\n {\n newPts->SetPoint(PointMap[i],this->Input->GetPoint(i));\n outputPD->CopyData(pd,i,PointMap[i]);\n }\n }\n\n \/\/ if coloring regions; send down new scalar data\n if ( this->ColorRegions ) outputPD->SetScalars(NewScalars);\n NewScalars->Delete();\n\n output->SetPoints(newPts);\n newPts->Delete();\n\/\/\n\/\/ Create output cells\n\/\/\n if ( this->ExtractionMode == VTK_EXTRACT_POINT_SEEDED_REGIONS ||\n this->ExtractionMode == VTK_EXTRACT_CELL_SEEDED_REGIONS )\n { \/\/ extract any cell that's been visited\n for (cellId=0; cellId < numCells; cellId++)\n {\n if ( Visited[cellId] >= 0 )\n {\n this->Input->GetCellPoints(cellId, ptIds);\n for (i=0; i < ptIds.GetNumberOfIds(); i++)\n {\n id = PointMap[ptIds.GetId(i)];\n ptIds.InsertId(i,id);\n }\n output->InsertNextCell(this->Input->GetCellType(cellId),ptIds);\n }\n }\n }\n else if ( this->ExtractionMode == VTK_EXTRACT_SPECIFIED_REGIONS )\n {\n for (cellId=0; cellId < numCells; cellId++)\n {\n int inReg, regionId;\n if ( (regionId=Visited[cellId]) >= 0 )\n {\n for (inReg=0,i=0; i<this->SpecifiedRegionIds.GetNumberOfIds(); i++)\n {\n if ( regionId == this->SpecifiedRegionIds.GetId(i) )\n {\n inReg = 1;\n break;\n }\n }\n if ( inReg )\n {\n this->Input->GetCellPoints(cellId, ptIds);\n for (i=0; i < ptIds.GetNumberOfIds(); i++)\n {\n id = PointMap[ptIds.GetId(i)];\n ptIds.InsertId(i,id);\n }\n output->InsertNextCell(this->Input->GetCellType(cellId),ptIds);\n }\n }\n }\n }\n else \/\/extract largest region\n {\n for (cellId=0; cellId < numCells; cellId++)\n {\n if ( Visited[cellId] == largestRegionId )\n {\n this->Input->GetCellPoints(cellId, ptIds);\n for (i=0; i < ptIds.GetNumberOfIds(); i++)\n {\n id = PointMap[ptIds.GetId(i)];\n ptIds.InsertId(i,id);\n }\n output->InsertNextCell(this->Input->GetCellType(cellId),ptIds);\n }\n }\n }\n\n delete [] Visited;\n delete [] PointMap;\n\n vtkDebugMacro (<<\"Extracted \" << output->GetNumberOfCells() << \" cells\");\n\n return;\n}\n\n\/\/\n\/\/ Mark current cell as visited and assign region number. Note:\n\/\/ traversal occurs across shared vertices.\n\/\/\nvoid vtkConnectivityFilter::TraverseAndMark (int cellId)\n{\n int j, k, ptId;\n vtkIdList ptIds, cellIds;\n\n Visited[cellId] = RegionNumber;\n NumCellsInRegion++;\n\n if ( RecursionDepth++ > this->MaxRecursionDepth ) \n {\n RecursionSeeds->InsertNextId(cellId);\n NumExceededMaxDepth++;\n return;\n }\n\n this->Input->GetCellPoints(cellId, ptIds);\n\n for (j=0; j < ptIds.GetNumberOfIds(); j++) \n {\n if ( PointMap[ptId=ptIds.GetId(j)] < 0 )\n {\n PointMap[ptId] = PointNumber++;\n NewScalars->SetScalar(PointMap[ptId], RegionNumber);\n }\n \n this->Input->GetPointCells(ptId,cellIds);\n\n for (k=0; k < cellIds.GetNumberOfIds(); k++)\n if ( Visited[cellIds.GetId(k)] < 0 )\n TraverseAndMark (cellIds.GetId(k));\n\n } \/\/ for all cells of this element\n\n RecursionDepth--;\n return;\n}\n\n\/\/ Description:\n\/\/ Obtain the number of connected regions.\nint vtkConnectivityFilter::GetNumberOfExtractedRegions()\n{\n return this->RegionSizes.GetSize();\n}\n\n\/\/ Description:\n\/\/ Set the extraction mode to extract regions sharing specified point ids.\nvoid vtkConnectivityFilter::ExtractPointSeededRegions()\n{\n if ( this->ExtractionMode != VTK_EXTRACT_POINT_SEEDED_REGIONS )\n {\n this->Modified();\n this->ExtractionMode = VTK_EXTRACT_POINT_SEEDED_REGIONS;\n }\n}\n\n\/\/ Description:\n\/\/ Set the extraction mode to extract regions sharing specified cell ids.\nvoid vtkConnectivityFilter::ExtractCellSeededRegions()\n{\n if ( this->ExtractionMode != VTK_EXTRACT_CELL_SEEDED_REGIONS )\n {\n this->Modified();\n this->ExtractionMode = VTK_EXTRACT_CELL_SEEDED_REGIONS;\n }\n}\n\n\/\/ Description:\n\/\/ Set the extraction mode to extract regions of specified id. You may \n\/\/ have to execute filter first (with debug turned on) to determine region ids.\nvoid vtkConnectivityFilter::ExtractSpecifiedRegions()\n{\n if ( this->ExtractionMode != VTK_EXTRACT_SPECIFIED_REGIONS )\n {\n this->Modified();\n this->ExtractionMode = VTK_EXTRACT_SPECIFIED_REGIONS;\n }\n}\n\n\/\/ Description:\n\/\/ Set the extraction mode to extract the largest region found.\nvoid vtkConnectivityFilter::ExtractLargestRegion()\n{\n if ( this->ExtractionMode != VTK_EXTRACT_LARGEST_REGION )\n {\n this->Modified();\n this->ExtractionMode = VTK_EXTRACT_LARGEST_REGION;\n }\n}\n\n\/\/ Description:\n\/\/ Initialize list of point ids\/cell ids used to seed regions.\nvoid vtkConnectivityFilter::InitializeSeedList()\n{\n this->Modified();\n this->Seeds.Reset();\n}\n\n\/\/ Description:\n\/\/ Add a seed id (point or cell id). Note: ids are 0-offset.\nvoid vtkConnectivityFilter::AddSeed(int id)\n{\n this->Modified();\n this->Seeds.InsertNextId(id);\n}\n\n\/\/ Description:\n\/\/ Delete a seed id (point or cell id). Note: ids are 0-offset.\nvoid vtkConnectivityFilter::DeleteSeed(int id)\n{\n this->Modified();\n this->Seeds.DeleteId(id);\n}\n\n\/\/ Description:\n\/\/ Initialize list of region ids to extract.\nvoid vtkConnectivityFilter::InitializeSpecifiedRegionList()\n{\n this->Modified();\n this->SpecifiedRegionIds.Reset();\n}\n\n\/\/ Description:\n\/\/ Add a region id to extract. Note: ids are 0-offset.\nvoid vtkConnectivityFilter::AddSpecifiedRegion(int id)\n{\n this->Modified();\n this->SpecifiedRegionIds.InsertNextId(id);\n}\n\n\/\/ Description:\n\/\/ Delete a region id to extract. Note: ids are 0-offset.\nvoid vtkConnectivityFilter::DeleteSpecifiedRegion(int id)\n{\n this->Modified();\n this->SpecifiedRegionIds.DeleteId(id);\n}\n\nvoid vtkConnectivityFilter::PrintSelf(ostream& os, vtkIndent indent)\n{\n vtkDataSetToUnstructuredGridFilter::PrintSelf(os,indent);\n\n os << indent << \"Extraction Mode: \";\n switch (this->ExtractionMode)\n {\n case VTK_EXTRACT_POINT_SEEDED_REGIONS:\n os << \"(Extract point seeded regions)\\n\";\n break;\n case VTK_EXTRACT_CELL_SEEDED_REGIONS:\n os << \"(Extract cell seeded regions)\\n\";\n break;\n case VTK_EXTRACT_SPECIFIED_REGIONS:\n os << \"(Extract specified regions)\\n\";\n break;\n case VTK_EXTRACT_LARGEST_REGION:\n os << \"(Extract largest region)\\n\";\n break;\n }\n\n os << indent << \"Color Regions: \" << (this->ColorRegions ? \"On\\n\" : \"Off\\n\");\n os << indent << \"Maximum Recursion Depth: \" << this->MaxRecursionDepth << \"\\n\";\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/*******************************************************\n * Copyright (c) 2014, ArrayFire\n * All rights reserved.\n *\n * This file is distributed under 3-clause BSD license.\n * The complete license agreement can be obtained at:\n * http:\/\/arrayfire.com\/licenses\/BSD-3-Clause\n ********************************************************\/\n\n#include <af\/version.h>\n#include <platform.hpp>\n#include <driver.h>\n#include <vector>\n#include <string>\n#include <algorithm>\n#include <sstream>\n#include <stdexcept>\n#include <cstdio>\n#include <cstring>\n#include <err_cuda.hpp>\n\n\/\/Macro for checking cuda errors following a cuda launch or api call\n#define CUDA(call) \\\ndo { \\\n cudaError_t err = call; \\\n if (cudaSuccess != err) { \\\n fprintf (stderr, \"CUDA Error in %s:%d : %s.\", \\\n __FILE__, __LINE__, cudaGetErrorString(err)); \\\n exit(EXIT_FAILURE); \\\n } \\\n} while (0); \\\n\nusing namespace std;\n\nnamespace cuda\n{\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ HELPERS\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ pulled from CUTIL from CUDA SDK\nstatic inline int compute2cores(int major, int minor)\n{\n struct {\n int compute; \/\/ 0xMm (hex), M = major version, m = minor version\n int cores;\n } gpus[] = {\n { 0x10, 8 },\n { 0x11, 8 },\n { 0x12, 8 },\n { 0x13, 8 },\n { 0x20, 32 },\n { 0x21, 48 },\n { 0x30, 192 },\n { 0x35, 192 },\n { 0x50, 128 },\n { -1, -1 },\n };\n\n for (int i = 0; gpus[i].compute != -1; ++i) {\n if (gpus[i].compute == (major << 4) + minor)\n return gpus[i].cores;\n }\n return 0;\n}\n\n\/\/ compare two cards based on (in order):\n\/\/ 1. flops (theoretical)\n\/\/ 2. total memory\n\n#define COMPARE(a,b,f) do { \\\n return ((a)->f >= (b)->f); \\\n } while (0);\n\n\nstatic inline bool card_compare_compute(const cudaDevice_t &l, const cudaDevice_t &r)\n{\n const cudaDevice_t *lc = &l;\n const cudaDevice_t *rc = &r;\n\n COMPARE(lc, rc, prop.major);\n COMPARE(lc, rc, prop.minor);\n COMPARE(lc, rc, flops);\n COMPARE(lc, rc, prop.totalGlobalMem);\n COMPARE(lc, rc, nativeId);\n return 0;\n}\n\nstatic inline bool card_compare_flops(const cudaDevice_t &l, const cudaDevice_t &r)\n{\n const cudaDevice_t *lc = &l;\n const cudaDevice_t *rc = &r;\n\n COMPARE(lc, rc, flops);\n COMPARE(lc, rc, prop.totalGlobalMem);\n COMPARE(lc, rc, prop.major);\n COMPARE(lc, rc, prop.minor);\n COMPARE(lc, rc, nativeId);\n return 0;\n}\n\nstatic inline bool card_compare_mem(const cudaDevice_t &l, const cudaDevice_t &r)\n{\n const cudaDevice_t *lc = &l;\n const cudaDevice_t *rc = &r;\n\n COMPARE(lc, rc, prop.totalGlobalMem);\n COMPARE(lc, rc, flops);\n COMPARE(lc, rc, prop.major);\n COMPARE(lc, rc, prop.minor);\n COMPARE(lc, rc, nativeId);\n return 0;\n}\n\nstatic inline bool card_compare_num(const cudaDevice_t &l, const cudaDevice_t &r)\n{\n const cudaDevice_t *lc = &l;\n const cudaDevice_t *rc = &r;\n\n COMPARE(lc, rc, nativeId);\n return 0;\n}\n\nstatic const char *get_system(void)\n{\n return\n#if defined(ARCH_32)\n \"32-bit \"\n#elif defined(ARCH_64)\n \"64-bit \"\n#endif\n\n#if defined(OS_LNX)\n \"Linux\";\n#elif defined(OS_WIN)\n \"Windows\";\n#elif defined(OS_MAC)\n \"Mac OSX\";\n#endif\n}\n\ntemplate <typename T>\nstatic inline string toString(T val)\n{\n stringstream s;\n s << val;\n return s.str();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Wrapper Functions\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nstring getInfo()\n{\n ostringstream info;\n info << \"ArrayFire v\" << AF_VERSION\n << \" (CUDA, \" << get_system() << \", build \" << AF_REVISION << \")\" << std::endl;\n info << getPlatformInfo();\n for (int i = 0; i < getDeviceCount(); ++i) {\n info << getDeviceInfo(i);\n }\n return info.str();\n}\n\nstring getDeviceInfo(int device)\n{\n cudaDeviceProp dev = getDeviceProp(device);\n\n size_t mem_gpu_total = dev.totalGlobalMem;\n \/\/double cc = double(dev.major) + double(dev.minor) \/ 10;\n\n bool show_braces = getActiveDeviceId() == device;\n\n string id = (show_braces ? string(\"[\") : \"-\") + toString(device) +\n (show_braces ? string(\"]\") : \"-\");\n string name(dev.name);\n string memory = toString((mem_gpu_total \/ (1024 * 1024))\n + !!(mem_gpu_total % (1024 * 1024)))\n + string(\" MB\");\n string compute = string(\"CUDA Compute \") + toString(dev.major) + string(\".\") + toString(dev.minor);\n\n string info = id + string(\" \") +\n name + string(\", \") +\n memory + string(\", \") +\n compute + string(\"\\n\");\n return info;\n}\n\nstring getPlatformInfo()\n{\n string driverVersion = getDriverVersion();\n std::string cudaRuntime = getCUDARuntimeVersion();\n string platform = \"Platform: CUDA Toolkit \" + cudaRuntime;\n if (!driverVersion.empty()) {\n platform.append(\", Driver: \");\n platform.append(driverVersion);\n }\n platform.append(\"\\n\");\n return platform;\n}\n\nbool isDoubleSupported(int device)\n{\n return true;\n}\n\nvoid devprop(char* d_name, char* d_platform, char *d_toolkit, char* d_compute)\n{\n if (getDeviceCount() <= 0) {\n printf(\"No CUDA-capable devices detected.\\n\");\n return;\n }\n\n cudaDeviceProp dev = getDeviceProp(getActiveDeviceId());\n\n \/\/ Name\n snprintf(d_name, 32, \"%s\", dev.name);\n\n \/\/Platform\n std::string cudaRuntime = getCUDARuntimeVersion();\n snprintf(d_platform, 10, \"CUDA\");\n snprintf(d_toolkit, 64, \"v%s\", cudaRuntime.c_str());\n\n \/\/ Compute Version\n snprintf(d_compute, 10, \"%d.%d\", dev.major, dev.minor);\n\n \/\/ Sanitize input\n for (int i = 0; i < 31; i++) {\n if (d_name[i] == ' ') {\n if (d_name[i + 1] == 0 || d_name[i + 1] == ' ') d_name[i] = 0;\n else d_name[i] = '_';\n }\n }\n}\n\nstring getDriverVersion()\n{\n char driverVersion[1024] = {\" \",};\n int x = nvDriverVersion(driverVersion, sizeof(driverVersion));\n if (x != 1) {\n #if !defined(OS_MAC) && !defined(__arm__) \/\/ HACK Mac OSX 10.7 needs new method for fetching driver\n throw runtime_error(\"Invalid driver\");\n #endif\n int driver = 0;\n CUDA(cudaDriverGetVersion(&driver));\n return string(\"CUDA Driver Version: \") + toString(driver);\n } else {\n return string(driverVersion);\n }\n}\n\nstring getCUDARuntimeVersion()\n{\n int runtime = 0;\n CUDA(cudaRuntimeGetVersion(&runtime));\n if(runtime \/ 100.f > 0)\n return toString((runtime \/ 1000) + (runtime % 1000)\/ 100.);\n else\n return toString(runtime \/ 1000) + string(\".0\");\n\n}\n\nint getDeviceCount()\n{\n return DeviceManager::getInstance().nDevices;\n}\n\nint getActiveDeviceId()\n{\n return DeviceManager::getInstance().activeDev;\n}\n\nint getDeviceNativeId(int device)\n{\n if(device < (int)DeviceManager::getInstance().cuDevices.size())\n return DeviceManager::getInstance().cuDevices[device].nativeId;\n return -1;\n}\n\nint setDevice(int device)\n{\n return DeviceManager::getInstance().setActiveDevice(device);\n}\n\ncudaDeviceProp getDeviceProp(int device)\n{\n if(device < (int)DeviceManager::getInstance().cuDevices.size())\n return DeviceManager::getInstance().cuDevices[device].prop;\n return DeviceManager::getInstance().cuDevices[0].prop;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ DeviceManager Class Functions\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nDeviceManager& DeviceManager::getInstance()\n{\n static DeviceManager my_instance;\n return my_instance;\n}\n\nDeviceManager::DeviceManager()\n : cuDevices(0), activeDev(0), nDevices(0)\n{\n CUDA(cudaGetDeviceCount(&nDevices));\n if (nDevices == 0)\n throw runtime_error(\"No CUDA-Capable devices found\");\n\n cuDevices.reserve(nDevices);\n\n for(int i = 0; i < nDevices; i++) {\n cudaDevice_t dev;\n cudaGetDeviceProperties(&dev.prop, i);\n dev.flops = dev.prop.multiProcessorCount * compute2cores(dev.prop.major, dev.prop.minor) * dev.prop.clockRate;\n dev.nativeId = i;\n cuDevices.push_back(dev);\n }\n\n sortDevices();\n\n const char* deviceENV = getenv(\"AF_CUDA_DEFAULT_DEVICE\");\n if(!deviceENV) {\n setActiveDevice(0, cuDevices[0].nativeId);\n } else {\n stringstream s(deviceENV);\n int def_device = -1;\n s >> def_device;\n if(def_device < 0 || def_device >= nDevices) {\n printf(\"WARNING: AF_CUDA_DEFAULT_DEVICE is out of range\\n\");\n printf(\"Setting default device as 0\\n\");\n setActiveDevice(0, cuDevices[0].nativeId);\n } else {\n setActiveDevice(def_device, cuDevices[def_device].nativeId);\n }\n }\n}\n\nvoid DeviceManager::sortDevices(sort_mode mode)\n{\n switch(mode) {\n case memory :\n sort(cuDevices.begin(), cuDevices.end(), card_compare_mem);\n break;\n case flops :\n sort(cuDevices.begin(), cuDevices.end(), card_compare_flops);\n break;\n case compute :\n sort(cuDevices.begin(), cuDevices.end(), card_compare_compute);\n break;\n case none : default :\n sort(cuDevices.begin(), cuDevices.end(), card_compare_num);\n break;\n }\n}\n\nint DeviceManager::setActiveDevice(int device, int nId)\n{\n if(device > (int)cuDevices.size()) {\n return -1;\n } else {\n int old = activeDev;\n if(nId == -1) nId = getDeviceNativeId(device);\n CUDA(cudaSetDevice(nId));\n activeDev = device;\n return old;\n }\n}\n\nvoid sync(int device)\n{\n int currDevice = getActiveDeviceId();\n setDevice(device);\n CUDA_CHECK(cudaDeviceSynchronize());\n setDevice(currDevice);\n}\n\n}\n<commit_msg>Fixing the cuda error check in cuda\/platform.cpp<commit_after>\/*******************************************************\n * Copyright (c) 2014, ArrayFire\n * All rights reserved.\n *\n * This file is distributed under 3-clause BSD license.\n * The complete license agreement can be obtained at:\n * http:\/\/arrayfire.com\/licenses\/BSD-3-Clause\n ********************************************************\/\n\n#include <af\/version.h>\n#include <platform.hpp>\n#include <driver.h>\n#include <vector>\n#include <string>\n#include <algorithm>\n#include <sstream>\n#include <stdexcept>\n#include <cstdio>\n#include <cstring>\n#include <err_cuda.hpp>\n\nusing namespace std;\n\nnamespace cuda\n{\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ HELPERS\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ pulled from CUTIL from CUDA SDK\nstatic inline int compute2cores(int major, int minor)\n{\n struct {\n int compute; \/\/ 0xMm (hex), M = major version, m = minor version\n int cores;\n } gpus[] = {\n { 0x10, 8 },\n { 0x11, 8 },\n { 0x12, 8 },\n { 0x13, 8 },\n { 0x20, 32 },\n { 0x21, 48 },\n { 0x30, 192 },\n { 0x35, 192 },\n { 0x50, 128 },\n { -1, -1 },\n };\n\n for (int i = 0; gpus[i].compute != -1; ++i) {\n if (gpus[i].compute == (major << 4) + minor)\n return gpus[i].cores;\n }\n return 0;\n}\n\n\/\/ compare two cards based on (in order):\n\/\/ 1. flops (theoretical)\n\/\/ 2. total memory\n\n#define COMPARE(a,b,f) do { \\\n return ((a)->f >= (b)->f); \\\n } while (0);\n\n\nstatic inline bool card_compare_compute(const cudaDevice_t &l, const cudaDevice_t &r)\n{\n const cudaDevice_t *lc = &l;\n const cudaDevice_t *rc = &r;\n\n COMPARE(lc, rc, prop.major);\n COMPARE(lc, rc, prop.minor);\n COMPARE(lc, rc, flops);\n COMPARE(lc, rc, prop.totalGlobalMem);\n COMPARE(lc, rc, nativeId);\n return 0;\n}\n\nstatic inline bool card_compare_flops(const cudaDevice_t &l, const cudaDevice_t &r)\n{\n const cudaDevice_t *lc = &l;\n const cudaDevice_t *rc = &r;\n\n COMPARE(lc, rc, flops);\n COMPARE(lc, rc, prop.totalGlobalMem);\n COMPARE(lc, rc, prop.major);\n COMPARE(lc, rc, prop.minor);\n COMPARE(lc, rc, nativeId);\n return 0;\n}\n\nstatic inline bool card_compare_mem(const cudaDevice_t &l, const cudaDevice_t &r)\n{\n const cudaDevice_t *lc = &l;\n const cudaDevice_t *rc = &r;\n\n COMPARE(lc, rc, prop.totalGlobalMem);\n COMPARE(lc, rc, flops);\n COMPARE(lc, rc, prop.major);\n COMPARE(lc, rc, prop.minor);\n COMPARE(lc, rc, nativeId);\n return 0;\n}\n\nstatic inline bool card_compare_num(const cudaDevice_t &l, const cudaDevice_t &r)\n{\n const cudaDevice_t *lc = &l;\n const cudaDevice_t *rc = &r;\n\n COMPARE(lc, rc, nativeId);\n return 0;\n}\n\nstatic const char *get_system(void)\n{\n return\n#if defined(ARCH_32)\n \"32-bit \"\n#elif defined(ARCH_64)\n \"64-bit \"\n#endif\n\n#if defined(OS_LNX)\n \"Linux\";\n#elif defined(OS_WIN)\n \"Windows\";\n#elif defined(OS_MAC)\n \"Mac OSX\";\n#endif\n}\n\ntemplate <typename T>\nstatic inline string toString(T val)\n{\n stringstream s;\n s << val;\n return s.str();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Wrapper Functions\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nstring getInfo()\n{\n ostringstream info;\n info << \"ArrayFire v\" << AF_VERSION\n << \" (CUDA, \" << get_system() << \", build \" << AF_REVISION << \")\" << std::endl;\n info << getPlatformInfo();\n for (int i = 0; i < getDeviceCount(); ++i) {\n info << getDeviceInfo(i);\n }\n return info.str();\n}\n\nstring getDeviceInfo(int device)\n{\n cudaDeviceProp dev = getDeviceProp(device);\n\n size_t mem_gpu_total = dev.totalGlobalMem;\n \/\/double cc = double(dev.major) + double(dev.minor) \/ 10;\n\n bool show_braces = getActiveDeviceId() == device;\n\n string id = (show_braces ? string(\"[\") : \"-\") + toString(device) +\n (show_braces ? string(\"]\") : \"-\");\n string name(dev.name);\n string memory = toString((mem_gpu_total \/ (1024 * 1024))\n + !!(mem_gpu_total % (1024 * 1024)))\n + string(\" MB\");\n string compute = string(\"CUDA Compute \") + toString(dev.major) + string(\".\") + toString(dev.minor);\n\n string info = id + string(\" \") +\n name + string(\", \") +\n memory + string(\", \") +\n compute + string(\"\\n\");\n return info;\n}\n\nstring getPlatformInfo()\n{\n string driverVersion = getDriverVersion();\n std::string cudaRuntime = getCUDARuntimeVersion();\n string platform = \"Platform: CUDA Toolkit \" + cudaRuntime;\n if (!driverVersion.empty()) {\n platform.append(\", Driver: \");\n platform.append(driverVersion);\n }\n platform.append(\"\\n\");\n return platform;\n}\n\nbool isDoubleSupported(int device)\n{\n return true;\n}\n\nvoid devprop(char* d_name, char* d_platform, char *d_toolkit, char* d_compute)\n{\n if (getDeviceCount() <= 0) {\n printf(\"No CUDA-capable devices detected.\\n\");\n return;\n }\n\n cudaDeviceProp dev = getDeviceProp(getActiveDeviceId());\n\n \/\/ Name\n snprintf(d_name, 32, \"%s\", dev.name);\n\n \/\/Platform\n std::string cudaRuntime = getCUDARuntimeVersion();\n snprintf(d_platform, 10, \"CUDA\");\n snprintf(d_toolkit, 64, \"v%s\", cudaRuntime.c_str());\n\n \/\/ Compute Version\n snprintf(d_compute, 10, \"%d.%d\", dev.major, dev.minor);\n\n \/\/ Sanitize input\n for (int i = 0; i < 31; i++) {\n if (d_name[i] == ' ') {\n if (d_name[i + 1] == 0 || d_name[i + 1] == ' ') d_name[i] = 0;\n else d_name[i] = '_';\n }\n }\n}\n\nstring getDriverVersion()\n{\n char driverVersion[1024] = {\" \",};\n int x = nvDriverVersion(driverVersion, sizeof(driverVersion));\n if (x != 1) {\n #if !defined(OS_MAC) && !defined(__arm__) \/\/ HACK Mac OSX 10.7 needs new method for fetching driver\n throw runtime_error(\"Invalid driver\");\n #endif\n int driver = 0;\n CUDA_CHECK(cudaDriverGetVersion(&driver));\n return string(\"CUDA Driver Version: \") + toString(driver);\n } else {\n return string(driverVersion);\n }\n}\n\nstring getCUDARuntimeVersion()\n{\n int runtime = 0;\n CUDA_CHECK(cudaRuntimeGetVersion(&runtime));\n if(runtime \/ 100.f > 0)\n return toString((runtime \/ 1000) + (runtime % 1000)\/ 100.);\n else\n return toString(runtime \/ 1000) + string(\".0\");\n\n}\n\nint getDeviceCount()\n{\n return DeviceManager::getInstance().nDevices;\n}\n\nint getActiveDeviceId()\n{\n return DeviceManager::getInstance().activeDev;\n}\n\nint getDeviceNativeId(int device)\n{\n if(device < (int)DeviceManager::getInstance().cuDevices.size())\n return DeviceManager::getInstance().cuDevices[device].nativeId;\n return -1;\n}\n\nint setDevice(int device)\n{\n return DeviceManager::getInstance().setActiveDevice(device);\n}\n\ncudaDeviceProp getDeviceProp(int device)\n{\n if(device < (int)DeviceManager::getInstance().cuDevices.size())\n return DeviceManager::getInstance().cuDevices[device].prop;\n return DeviceManager::getInstance().cuDevices[0].prop;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ DeviceManager Class Functions\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nDeviceManager& DeviceManager::getInstance()\n{\n static DeviceManager my_instance;\n return my_instance;\n}\n\nDeviceManager::DeviceManager()\n : cuDevices(0), activeDev(0), nDevices(0)\n{\n CUDA_CHECK(cudaGetDeviceCount(&nDevices));\n if (nDevices == 0)\n throw runtime_error(\"No CUDA-Capable devices found\");\n\n cuDevices.reserve(nDevices);\n\n for(int i = 0; i < nDevices; i++) {\n cudaDevice_t dev;\n cudaGetDeviceProperties(&dev.prop, i);\n dev.flops = dev.prop.multiProcessorCount * compute2cores(dev.prop.major, dev.prop.minor) * dev.prop.clockRate;\n dev.nativeId = i;\n cuDevices.push_back(dev);\n }\n\n sortDevices();\n\n const char* deviceENV = getenv(\"AF_CUDA_DEFAULT_DEVICE\");\n if(!deviceENV) {\n setActiveDevice(0, cuDevices[0].nativeId);\n } else {\n stringstream s(deviceENV);\n int def_device = -1;\n s >> def_device;\n if(def_device < 0 || def_device >= nDevices) {\n printf(\"WARNING: AF_CUDA_DEFAULT_DEVICE is out of range\\n\");\n printf(\"Setting default device as 0\\n\");\n setActiveDevice(0, cuDevices[0].nativeId);\n } else {\n setActiveDevice(def_device, cuDevices[def_device].nativeId);\n }\n }\n}\n\nvoid DeviceManager::sortDevices(sort_mode mode)\n{\n switch(mode) {\n case memory :\n sort(cuDevices.begin(), cuDevices.end(), card_compare_mem);\n break;\n case flops :\n sort(cuDevices.begin(), cuDevices.end(), card_compare_flops);\n break;\n case compute :\n sort(cuDevices.begin(), cuDevices.end(), card_compare_compute);\n break;\n case none : default :\n sort(cuDevices.begin(), cuDevices.end(), card_compare_num);\n break;\n }\n}\n\nint DeviceManager::setActiveDevice(int device, int nId)\n{\n if(device > (int)cuDevices.size()) {\n return -1;\n } else {\n int old = activeDev;\n if(nId == -1) nId = getDeviceNativeId(device);\n CUDA_CHECK(cudaSetDevice(nId));\n activeDev = device;\n return old;\n }\n}\n\nvoid sync(int device)\n{\n int currDevice = getActiveDeviceId();\n setDevice(device);\n CUDA_CHECK(cudaDeviceSynchronize());\n setDevice(currDevice);\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/*!\n@file\n\n@copyright Edouard Alligand and Joel Falcou 2015-2017\n(See accompanying file LICENSE.md or copy at http:\/\/boost.org\/LICENSE_1_0.txt)\n*\/\n#ifndef BOOST_BRIGAND_SEQUENCES_RANGE_HPP\n#define BOOST_BRIGAND_SEQUENCES_RANGE_HPP\n\n#include <brigand\/config.hpp>\n#include <brigand\/sequences\/list.hpp>\n#include <brigand\/types\/integral_constant.hpp>\n\nnamespace brigand\n{\nnamespace detail\n{\n template <class T, class, class, T>\n struct range_cat;\n\n#ifdef BRIGAND_COMP_MSVC\n template <class T, T Start, T Int>\n struct int_plus\n {\n using type = brigand::integral_constant<T, Start + Int>;\n };\n#endif\n\n template <class T, class... Ts, T... Ints, T Start>\n struct range_cat<T, list<Ts...>, list<brigand::integral_constant<T, Ints>...>, Start>\n {\n#ifdef BRIGAND_COMP_MSVC\n using type = list<Ts..., typename int_plus<T, Start, Ints>::type...>;\n#else\n using type = list<Ts..., brigand::integral_constant<T, Start + Ints>...>;\n#endif\n };\n\n template <class T, T Start, unsigned int N>\n struct range_impl : range_cat<T, typename range_impl<T, Start, N \/ 2>::type,\n typename range_impl<T, Start, N - N \/ 2>::type, N \/ 2>\n {\n };\n\n template <class T, T Start>\n struct range_impl<T, Start, 1>\n {\n using type = list<brigand::integral_constant<T, Start>>;\n };\n\n template <class T, T Start>\n struct range_impl<T, Start, 0>\n {\n using type = list<>;\n };\n\n template <class T, class, class, T>\n struct reverse_range_cat;\n\n#ifdef BRIGAND_COMP_MSVC\n template <class T, T Start, T Int>\n struct int_minus\n {\n using type = brigand::integral_constant<T, Int - Start>;\n };\n#endif\n\n template <class T, class... Ts, T... Ints, T Start>\n struct reverse_range_cat<T, list<Ts...>, list<brigand::integral_constant<T, Ints>...>, Start>\n {\n#ifdef BRIGAND_COMP_MSVC\n using type = list<Ts..., typename int_minus<T, Start, Ints>::type...>;\n#else\n using type = list<Ts..., brigand::integral_constant<T, Ints - Start>...>;\n#endif\n };\n\n template <class T, T Start, unsigned int N>\n struct reverse_range_impl\n : reverse_range_cat<T, typename reverse_range_impl<T, Start, N \/ 2>::type,\n typename reverse_range_impl<T, Start, N - N \/ 2>::type, N \/ 2>\n {\n };\n\n template <class T, T Start>\n struct reverse_range_impl<T, Start, 1>\n {\n using type = list<brigand::integral_constant<T, Start>>;\n };\n\n template <class T, T Start>\n struct reverse_range_impl<T, Start, 0>\n {\n using type = list<>;\n };\n\n template <class T, T Start, T Stop>\n struct reverse_range_safe\n {\n static_assert(\n Start >= Stop,\n \"Invalid parameters. reverse_range<> syntax is reverse_range<type, from, down_to>\");\n using type = typename reverse_range_impl<T, Start, Start - Stop>::type;\n };\n}\n\ntemplate <class T, T Start, T Stop>\nusing range = typename detail::range_impl<T, Start, Stop - Start>::type;\n\ntemplate <class T, T Start, T Stop>\nusing reverse_range = typename detail::reverse_range_safe<T, Start, Stop>::type;\n}\n#endif\n<commit_msg>Delete range.hpp<commit_after><|endoftext|>"} {"text":"<commit_before>#include \"walrus_joystick_controller\/joystick_controller.h\"\n#include \"geometry_msgs\/Twist.h\"\n#include \"std_msgs\/Float64.h\"\n\nnamespace walrus_joystick_controller {\n\n\nJoystickController::JoystickController(ros::NodeHandle& nh, ros::NodeHandle& pnh)\n{\n pnh.param<int>(\"axis_linear\", axis_linear_, 1);\n pnh.param<double>(\"scale_linear\", scale_linear_, 0.5);\n\n pnh.param<int>(\"axis_angular\", axis_angular_, 0);\n pnh.param<double>(\"scale_angular\", scale_angular_, 1.0);\n\n pnh.param<int>(\"button_pods_up\", button_pods_up_, 0);\n pnh.param<int>(\"button_pods_toes\", button_pods_toes_, 1);\n pnh.param<int>(\"button_pods_flat\", button_pods_flat_, 2);\n\n joy_sub_ = nh.subscribe<sensor_msgs::Joy>(\"joy\", 1, &JoystickController::joyCallback, this);\n enabled_sub_ = nh.subscribe<std_msgs::Bool>(\"enabled\", 1, &JoystickController::enabledCallback, this);\n\n cmd_vel_pub_ = nh.advertise<geometry_msgs::Twist>(\"cmd_vel\", 1);\n\n back_left_pod_pub_ = nh.advertise<std_msgs::Float64>(\"back_left_pod_joint_controller\/command\", 1);\n back_right_pod_pub_ = nh.advertise<std_msgs::Float64>(\"back_right_pod_joint_controller\/command\", 1);\n front_left_pod_pub_ = nh.advertise<std_msgs::Float64>(\"front_left_pod_joint_controller\/command\", 1);\n front_right_pod_pub_ = nh.advertise<std_msgs::Float64>(\"front_right_pod_joint_controller\/command\", 1);\n}\n\nvoid JoystickController::joyCallback(const sensor_msgs::Joy::ConstPtr& joy_msg)\n{\n if(enabled_)\n {\n geometry_msgs::Twist twist_msg;\n\n twist_msg.linear.x = joy_msg->axes[axis_linear_] * scale_linear_;\n twist_msg.angular.z = joy_msg->axes[axis_angular_] * scale_angular_;\n cmd_vel_pub_.publish(twist_msg);\n\n if(joy_msg->buttons[button_pods_up_]) {\n publishPodAngles(0.3);\n }\n else if(joy_msg->buttons[button_pods_toes_]) {\n publishPodAngles(-0.3);\n }\n else if(joy_msg->buttons[button_pods_flat_]) {\n publishPodAngles(0.0);\n }\n }\n}\n\nvoid JoystickController::publishPodAngles(double angle) {\n std_msgs::Float64 angle_msg;\n angle_msg.data = angle;\n std_msgs::Float64 negated_angle_msg;\n negated_angle_msg.data = -angle;\n\n back_left_pod_pub_.publish(angle_msg);\n back_right_pod_pub_.publish(angle_msg);\n\n front_left_pod_pub_.publish(negated_angle_msg);\n front_right_pod_pub_.publish(negated_angle_msg);\n}\n\n\nvoid JoystickController::enabledCallback(const std_msgs::Bool::ConstPtr& bool_msg)\n{\n enabled_ = bool_msg->data;\n\n if(enabled_)\n {\n \/\/ Publish zero twist\n geometry_msgs::Twist twist_msg;\n cmd_vel_pub_.publish(twist_msg);\n }\n}\n\n}\n\n<commit_msg>Move pods more when using joystick<commit_after>#include \"walrus_joystick_controller\/joystick_controller.h\"\n#include \"geometry_msgs\/Twist.h\"\n#include \"std_msgs\/Float64.h\"\n\nnamespace walrus_joystick_controller {\n\n\nJoystickController::JoystickController(ros::NodeHandle& nh, ros::NodeHandle& pnh)\n{\n pnh.param<int>(\"axis_linear\", axis_linear_, 1);\n pnh.param<double>(\"scale_linear\", scale_linear_, 0.5);\n\n pnh.param<int>(\"axis_angular\", axis_angular_, 0);\n pnh.param<double>(\"scale_angular\", scale_angular_, 1.0);\n\n pnh.param<int>(\"button_pods_up\", button_pods_up_, 0);\n pnh.param<int>(\"button_pods_toes\", button_pods_toes_, 1);\n pnh.param<int>(\"button_pods_flat\", button_pods_flat_, 2);\n\n joy_sub_ = nh.subscribe<sensor_msgs::Joy>(\"joy\", 1, &JoystickController::joyCallback, this);\n enabled_sub_ = nh.subscribe<std_msgs::Bool>(\"enabled\", 1, &JoystickController::enabledCallback, this);\n\n cmd_vel_pub_ = nh.advertise<geometry_msgs::Twist>(\"cmd_vel\", 1);\n\n back_left_pod_pub_ = nh.advertise<std_msgs::Float64>(\"back_left_pod_joint_controller\/command\", 1);\n back_right_pod_pub_ = nh.advertise<std_msgs::Float64>(\"back_right_pod_joint_controller\/command\", 1);\n front_left_pod_pub_ = nh.advertise<std_msgs::Float64>(\"front_left_pod_joint_controller\/command\", 1);\n front_right_pod_pub_ = nh.advertise<std_msgs::Float64>(\"front_right_pod_joint_controller\/command\", 1);\n}\n\nvoid JoystickController::joyCallback(const sensor_msgs::Joy::ConstPtr& joy_msg)\n{\n if(enabled_)\n {\n geometry_msgs::Twist twist_msg;\n\n twist_msg.linear.x = joy_msg->axes[axis_linear_] * scale_linear_;\n twist_msg.angular.z = joy_msg->axes[axis_angular_] * scale_angular_;\n cmd_vel_pub_.publish(twist_msg);\n\n if(joy_msg->buttons[button_pods_up_]) {\n publishPodAngles(0.6);\n }\n else if(joy_msg->buttons[button_pods_toes_]) {\n publishPodAngles(-0.6);\n }\n else if(joy_msg->buttons[button_pods_flat_]) {\n publishPodAngles(0.0);\n }\n }\n}\n\nvoid JoystickController::publishPodAngles(double angle) {\n std_msgs::Float64 angle_msg;\n angle_msg.data = angle;\n std_msgs::Float64 negated_angle_msg;\n negated_angle_msg.data = -angle;\n\n back_left_pod_pub_.publish(angle_msg);\n back_right_pod_pub_.publish(angle_msg);\n\n front_left_pod_pub_.publish(negated_angle_msg);\n front_right_pod_pub_.publish(negated_angle_msg);\n}\n\n\nvoid JoystickController::enabledCallback(const std_msgs::Bool::ConstPtr& bool_msg)\n{\n enabled_ = bool_msg->data;\n\n if(enabled_)\n {\n \/\/ Publish zero twist\n geometry_msgs::Twist twist_msg;\n cmd_vel_pub_.publish(twist_msg);\n }\n}\n\n}\n\n<|endoftext|>"} {"text":"<commit_before>#include <vector>\n#include <memory>\n#include <iostream>\n#include <utility>\n#include <string>\n#include <uv.h>\n\n#include \"worker_thread.h\"\n#include \"worker_platform.h\"\n#include \"..\/log.h\"\n#include \"..\/queue.h\"\n#include \"..\/message.h\"\n#include \"..\/result.h\"\n\nusing std::endl;\nusing std::vector;\nusing std::unique_ptr;\nusing std::move;\nusing std::string;\n\nWorkerThread::WorkerThread(uv_async_t *main_callback) :\n Thread(this, &WorkerThread::listen, \"worker thread\", main_callback),\n platform{WorkerPlatform::for_worker(this)}\n{\n \/\/\n}\n\nWorkerThread::~WorkerThread()\n{\n \/\/ Necessary so that unique_ptr can see the full definition of WorkerPlatform\n}\n\nResult<> WorkerThread::wake()\n{\n return platform->wake();\n}\n\nvoid WorkerThread::listen()\n{\n \/\/ Handle any commands that were enqueued while the thread was starting.\n Result<> cr = handle_commands();\n if (cr.is_error()) {\n LOGGER << \"Unable to handle initially enqueued commands: \" << cr << endl;\n }\n\n Result<> lr = platform->listen();\n if (lr.is_error()) {\n LOGGER << \"Unable to listen: \" << lr << endl;\n report_error(string(lr.get_error()));\n } else {\n LOGGER << \"listen unexpectedly returned without reporting an error.\" << endl;\n }\n}\n\nResult<> WorkerThread::handle_commands()\n{\n Result< unique_ptr<vector<Message>> > pr = process_all();\n if (pr.is_error()) {\n return error_result(string(pr.get_error()));\n }\n\n unique_ptr<vector<Message>> &accepted = pr.get_value();\n if (!accepted) {\n \/\/ No command messages to accept.\n return ok_result();\n }\n\n vector<Message> acks;\n acks.reserve(accepted->size());\n\n for (auto it = accepted->begin(); it != accepted->end(); ++it) {\n const CommandPayload *command = it->as_command();\n if (!command) {\n LOGGER << \"Received unexpected message \" << *it << \".\" << endl;\n continue;\n }\n\n bool success = true;\n string message = \"\";\n\n switch (command->get_action()) {\n case COMMAND_ADD:\n {\n Result<> r = platform->handle_add_command(command->get_channel_id(), command->get_root());\n if (r.is_error()) {\n success = false;\n message = r.get_error();\n }\n }\n break;\n\n case COMMAND_REMOVE:\n {\n Result<> r = platform->handle_remove_command(command->get_channel_id());\n if (r.is_error()) {\n success = false;\n message = r.get_error();\n }\n }\n break;\n\n case COMMAND_LOG_FILE:\n Logger::to_file(command->get_root().c_str());\n break;\n\n case COMMAND_LOG_DISABLE:\n LOGGER << \"Disabling logger.\" << endl;\n Logger::disable();\n break;\n\n default:\n LOGGER << \"Received command with unexpected action \" << *it << \".\" << endl;\n break;\n }\n\n AckPayload ack(command->get_id(), command->get_channel_id(), success, move(message));\n Message response(move(ack));\n acks.push_back(move(response));\n }\n\n return emit_all(acks.begin(), acks.end());\n}\n\nvoid WorkerThread::collect_status(Status &status)\n{\n status.worker_thread_ok = get_error();\n status.worker_in_size = get_in_queue_size();\n status.worker_in_ok = get_in_queue_error();\n status.worker_out_size = get_out_queue_size();\n status.worker_out_ok = get_out_queue_error();\n}\n<commit_msg>Log errors in the worker loop before returning them<commit_after>#include <vector>\n#include <memory>\n#include <iostream>\n#include <utility>\n#include <string>\n#include <uv.h>\n\n#include \"worker_thread.h\"\n#include \"worker_platform.h\"\n#include \"..\/log.h\"\n#include \"..\/queue.h\"\n#include \"..\/message.h\"\n#include \"..\/result.h\"\n\nusing std::endl;\nusing std::vector;\nusing std::unique_ptr;\nusing std::move;\nusing std::string;\n\nWorkerThread::WorkerThread(uv_async_t *main_callback) :\n Thread(this, &WorkerThread::listen, \"worker thread\", main_callback),\n platform{WorkerPlatform::for_worker(this)}\n{\n \/\/\n}\n\nWorkerThread::~WorkerThread()\n{\n \/\/ Necessary so that unique_ptr can see the full definition of WorkerPlatform\n}\n\nResult<> WorkerThread::wake()\n{\n return platform->wake();\n}\n\nvoid WorkerThread::listen()\n{\n \/\/ Handle any commands that were enqueued while the thread was starting.\n Result<> cr = handle_commands();\n if (cr.is_error()) {\n LOGGER << \"Unable to handle initially enqueued commands: \" << cr << endl;\n }\n\n Result<> lr = platform->listen();\n if (lr.is_error()) {\n LOGGER << \"Unable to listen: \" << lr << endl;\n report_error(string(lr.get_error()));\n } else {\n LOGGER << \"listen unexpectedly returned without reporting an error.\" << endl;\n }\n}\n\nResult<> WorkerThread::handle_commands()\n{\n Result< unique_ptr<vector<Message>> > pr = process_all();\n if (pr.is_error()) {\n return error_result(string(pr.get_error()));\n }\n\n unique_ptr<vector<Message>> &accepted = pr.get_value();\n if (!accepted) {\n \/\/ No command messages to accept.\n return ok_result();\n }\n\n vector<Message> acks;\n acks.reserve(accepted->size());\n\n for (auto it = accepted->begin(); it != accepted->end(); ++it) {\n const CommandPayload *command = it->as_command();\n if (!command) {\n LOGGER << \"Received unexpected message \" << *it << \".\" << endl;\n continue;\n }\n\n bool success = true;\n string message = \"\";\n\n switch (command->get_action()) {\n case COMMAND_ADD:\n {\n Result<> r = platform->handle_add_command(command->get_channel_id(), command->get_root());\n if (r.is_error()) {\n success = false;\n message = r.get_error();\n }\n }\n break;\n\n case COMMAND_REMOVE:\n {\n Result<> r = platform->handle_remove_command(command->get_channel_id());\n if (r.is_error()) {\n success = false;\n message = r.get_error();\n }\n }\n break;\n\n case COMMAND_LOG_FILE:\n Logger::to_file(command->get_root().c_str());\n break;\n\n case COMMAND_LOG_DISABLE:\n LOGGER << \"Disabling logger.\" << endl;\n Logger::disable();\n break;\n\n default:\n LOGGER << \"Received command with unexpected action \" << *it << \".\" << endl;\n break;\n }\n\n if (!message.empty()) {\n LOGGER << \"Reporting platform error: \" << message << \".\" << endl;\n }\n\n AckPayload ack(command->get_id(), command->get_channel_id(), success, move(message));\n Message response(move(ack));\n acks.push_back(move(response));\n }\n\n return emit_all(acks.begin(), acks.end());\n}\n\nvoid WorkerThread::collect_status(Status &status)\n{\n status.worker_thread_ok = get_error();\n status.worker_in_size = get_in_queue_size();\n status.worker_in_ok = get_in_queue_error();\n status.worker_out_size = get_out_queue_size();\n status.worker_out_ok = get_out_queue_error();\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * AscEmu Framework based on ArcEmu MMORPG Server\n * Copyright (C) 2014-2016 AscEmu Team <http:\/\/www.ascemu.org\/>\n * Copyright (C) 2008-2012 ArcEmu Team <http:\/\/www.ArcEmu.org\/>\n * Copyright (C) 2005-2007 Ascent Team\n *\n * This program is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Affero General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\n *\/\n\n#include \"CObjectFactory.h\"\n#include \"ObjectStorage.h\"\n\nGameObject* CObjectFactory::CreateGameObject(uint32 Id, uint32 LowGUID)\n{\n GameObjectInfo* gameobject_info = GameObjectNameStorage.LookupEntry(Id);\n if (gameobject_info == NULL)\n return NULL;\n\n GameObject* gameobject = nullptr;\n\n uint64 GUID = uint64((uint64(HIGHGUID_TYPE_GAMEOBJECT) << 32) | LowGUID);\n\n switch (gameobject_info->type)\n {\n\n case GAMEOBJECT_TYPE_DOOR:\n gameobject = new GameObject_Door(GUID);\n break;\n\n case GAMEOBJECT_TYPE_BUTTON:\n gameobject = new GameObject_Button(GUID);\n break;\n\n case GAMEOBJECT_TYPE_QUESTGIVER:\n gameobject = new GameObject_QuestGiver(GUID);\n break;\n\n case GAMEOBJECT_TYPE_CHEST:\n gameobject = new GameObject_Chest(GUID);\n break;\n\n case GAMEOBJECT_TYPE_TRAP:\n gameobject = new GameObject_Trap(GUID);\n break;\n\n case GAMEOBJECT_TYPE_SPELL_FOCUS:\n gameobject = new GameObject_SpellFocus(GUID);\n break;\n\n case GAMEOBJECT_TYPE_GOOBER:\n gameobject = new GameObject_Goober(GUID);\n break;\n\n case GAMEOBJECT_TYPE_FISHINGNODE:\n gameobject = new GameObject_FishingNode(GUID);\n break;\n\n case GAMEOBJECT_TYPE_RITUAL:\n gameobject = new GameObject_Ritual(GUID);\n break;\n\n case GAMEOBJECT_TYPE_SPELLCASTER:\n gameobject = new GameObject_SpellCaster(GUID);\n break;\n\n case GAMEOBJECT_TYPE_FISHINGHOLE:\n gameobject = new GameObject_FishingHole(GUID);\n break;\n\n case GAMEOBJECT_TYPE_DESTRUCTIBLE_BUILDING:\n gameobject = new GameObject_Destructible(GUID);\n break;\n\n default:\n gameobject = new GameObject(GUID);\n break;\n }\n\n gameobject->SetInfo(gameobject_info);\n\n return gameobject;\n}\n\nvoid CObjectFactory::DisposeOf(Object* obj)\n{\n delete obj;\n}\n<commit_msg>no message<commit_after>\/*\n * AscEmu Framework based on ArcEmu MMORPG Server\n * Copyright (C) 2014-2016 AscEmu Team <http:\/\/www.ascemu.org\/>\n * Copyright (C) 2008-2012 ArcEmu Team <http:\/\/www.ArcEmu.org\/>\n * Copyright (C) 2005-2007 Ascent Team\n *\n * This program is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Affero General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\n *\/\n\n#include \"CObjectFactory.h\"\n#include \"Object.h\"\n#include \"ObjectStorage.h\"\n\nGameObject* CObjectFactory::CreateGameObject(uint32 Id, uint32 LowGUID)\n{\n GameObjectInfo* gameobject_info = GameObjectNameStorage.LookupEntry(Id);\n if (gameobject_info == NULL)\n return NULL;\n\n GameObject* gameobject = nullptr;\n\n uint64 GUID = uint64((uint64(HIGHGUID_TYPE_GAMEOBJECT) << 32) | LowGUID);\n\n switch (gameobject_info->type)\n {\n\n case GAMEOBJECT_TYPE_DOOR:\n gameobject = new GameObject_Door(GUID);\n break;\n\n case GAMEOBJECT_TYPE_BUTTON:\n gameobject = new GameObject_Button(GUID);\n break;\n\n case GAMEOBJECT_TYPE_QUESTGIVER:\n gameobject = new GameObject_QuestGiver(GUID);\n break;\n\n case GAMEOBJECT_TYPE_CHEST:\n gameobject = new GameObject_Chest(GUID);\n break;\n\n case GAMEOBJECT_TYPE_TRAP:\n gameobject = new GameObject_Trap(GUID);\n break;\n\n case GAMEOBJECT_TYPE_SPELL_FOCUS:\n gameobject = new GameObject_SpellFocus(GUID);\n break;\n\n case GAMEOBJECT_TYPE_GOOBER:\n gameobject = new GameObject_Goober(GUID);\n break;\n\n case GAMEOBJECT_TYPE_FISHINGNODE:\n gameobject = new GameObject_FishingNode(GUID);\n break;\n\n case GAMEOBJECT_TYPE_RITUAL:\n gameobject = new GameObject_Ritual(GUID);\n break;\n\n case GAMEOBJECT_TYPE_SPELLCASTER:\n gameobject = new GameObject_SpellCaster(GUID);\n break;\n\n case GAMEOBJECT_TYPE_FISHINGHOLE:\n gameobject = new GameObject_FishingHole(GUID);\n break;\n\n case GAMEOBJECT_TYPE_DESTRUCTIBLE_BUILDING:\n gameobject = new GameObject_Destructible(GUID);\n break;\n\n default:\n gameobject = new GameObject(GUID);\n break;\n }\n\n gameobject->SetInfo(gameobject_info);\n\n return gameobject;\n}\n\nvoid CObjectFactory::DisposeOf(Object* obj)\n{\n delete obj;\n}\n<|endoftext|>"} {"text":"<commit_before>#include <Wire.h>\n#include <Adafruit_Sensor.h>\n#include <Adafruit_LSM303_U.h>\n#include <Adafruit_L3GD20_U.h>\n#include <Adafruit_9DOF.h>\n\n#include \"Arduino.h\"\n#include \"RadioFunctions.h\"\n\/* Assign a unique ID to the sensors *\/\nvoid initSensors();\nvoid setup(void);\nvoid loop(void);\n\nAdafruit_9DOF dof = Adafruit_9DOF();\nAdafruit_LSM303_Accel_Unified accel = Adafruit_LSM303_Accel_Unified(30301);\nAdafruit_LSM303_Mag_Unified mag = Adafruit_LSM303_Mag_Unified(30302);\nAdafruit_L3GD20_Unified gyr = Adafruit_L3GD20_Unified(30303);\n\n\/* Update this with the correct SLP for accurate altitude measurements *\/\nfloat seaLevelPressure = SENSORS_PRESSURE_SEALEVELHPA;\n\nfloat p_roll;\nfloat p_pitch;\nfloat p_gyro_x;\nfloat p_gyro_y;\nfloat p_gyro_z;\nfloat p_heading;\nchar buf[100];\nchar *char_ptr;\n\n\/**************************************************************************\/\n\/*!\n @brief Initialises all the sensors used by this example\n*\/\n\/**************************************************************************\/\nvoid initSensors()\n{\n if(!accel.begin())\n {\n \/* There was a problem detecting the LSM303 ... check your connections *\/\n Serial.println(F(\"Ooops, no LSM303 detected ... Check your wiring!\"));\n while(1);\n }\n if(!mag.begin())\n {\n \/* There was a problem detecting the LSM303 ... check your connections *\/\n Serial.println(\"Ooops, no LSM303 detected ... Check your wiring!\");\n while(1);\n }\n if(!gyr.begin())\n {\n \/* There was a problem detecting the LSM303 ... check your connections *\/\n Serial.println(\"Ooops, no L3GD20 detected ... Check your wiring!\");\n while(1);\n }\n}\n\n\/**************************************************************************\/\n\/*!\n\n*\/\n\/**************************************************************************\/\nvoid setup(void)\n{\n Serial.begin(115200);\n\n rfBegin(11);\n\n \/* Initialise the sensors *\/\n initSensors();\n}\n\n\/**************************************************************************\/\n\/*!\n @brief Constantly check the roll\/pitch\/heading\/altitude\/temperature\n*\/\n\/**************************************************************************\/\nvoid loop(void)\n {\n\n sensors_event_t accel_event;\n sensors_event_t mag_event;\n sensors_event_t gyr_event;\n sensors_vec_t orientation;\n\n \/* Calculate pitch and roll from the raw accelerometer data *\/\n if(!accel.getEvent(&accel_event)) return;\n if (dof.fusionGetOrientation(&accel_event, &mag_event, &orientation))\n {\n \/* 'orientation' should have valid .roll and .pitch fields *\/\n p_roll = orientation.roll; \/\/roll\n \/\/ if(orientation.roll<=0){\n \/\/ Serial.print(-orientation.roll); \/\/roll\n \/\/ }\n \/\/ else{\n \/\/ Serial.print(360-orientation.roll); \/\/roll\n \/\/ }\n p_pitch = orientation.pitch; \/\/pitch\n \/\/ if(orientation.pitch<0){\n \/\/ Serial.print(-orientation.pitch); \/\/pitch\n \/\/ }\n \/\/ else{\n \/\/ Serial.print(360-orientation.pitch); \/\/pitch\n \/\/ }\n }\n\n \/* Calculate x y z from gyroscope *\/\n if (!gyr.getEvent(&gyr_event)) return;\n else {\n \/* 'orientation' should have valid .roll and .pitch fields *\/\n p_gyro_x = gyr_event.gyro.x; \/\/gyr x\n p_gyro_y = gyr_event.gyro.y; \/\/gyr y\n p_gyro_z = gyr_event.gyro.z; \/\/gyr z\n\n }\n\n \/* Calculate the heading using the magnetometer *\/\n if(!mag.getEvent(&mag_event)) return;\n \/\/ dof.magTiltCompensation(SENSOR_AXIS_Z, &mag_event, &accel_event);\n if (dof.fusionGetOrientation(&accel_event, &mag_event, &orientation)) {\n \/* 'orientation' should have valid .heading data now *\/\n p_heading = orientation.heading;\n }\n\n char_ptr = buf;\n *char_ptr = '\\n';\n char_ptr++;\n\n dtostrf(p_roll, 1, 2, char_ptr);\n char_ptr += strlen(char_ptr);\n *char_ptr = ',';\n char_ptr++;\n\n dtostrf(p_pitch, 1, 2, char_ptr);\n char_ptr += strlen(char_ptr);\n *char_ptr = ',';\n char_ptr++;\n\n dtostrf(p_gyro_x, 1, 2, char_ptr);\n char_ptr += strlen(char_ptr);\n *char_ptr = ',';\n char_ptr++;\n\n dtostrf(p_gyro_y, 1, 2, char_ptr);\n char_ptr += strlen(char_ptr);\n *char_ptr = ',';\n char_ptr++;\n\n dtostrf(p_gyro_z, 1, 2, char_ptr);\n char_ptr += strlen(char_ptr);\n *char_ptr = ',';\n char_ptr++;\n\n dtostrf(p_heading, 1, 2, char_ptr);\n strcat(buf, \"\\n\");\n\n rfPrint(buf);\n \/\/Serial.print(buf);\n\n delay(100);\n}\n<commit_msg>Added button code for PCB<commit_after>#include <Wire.h>\n#include <Adafruit_Sensor.h>\n#include <Adafruit_LSM303_U.h>\n#include <Adafruit_L3GD20_U.h>\n#include <Adafruit_9DOF.h>\n\n#include \"Arduino.h\"\n#include \"RadioFunctions.h\"\n\/* Assign a unique ID to the sensors *\/\nvoid initSensors();\nvoid setup(void);\nvoid loop(void);\n\nAdafruit_9DOF dof = Adafruit_9DOF();\nAdafruit_LSM303_Accel_Unified accel = Adafruit_LSM303_Accel_Unified(30301);\nAdafruit_LSM303_Mag_Unified mag = Adafruit_LSM303_Mag_Unified(30302);\nAdafruit_L3GD20_Unified gyr = Adafruit_L3GD20_Unified(30303);\n\n\/* Update this with the correct SLP for accurate altitude measurements *\/\nfloat seaLevelPressure = SENSORS_PRESSURE_SEALEVELHPA;\n\nfloat p_roll;\nfloat p_pitch;\nfloat p_gyro_x;\nfloat p_gyro_y;\nfloat p_gyro_z;\nfloat p_heading;\nchar buf[100];\nchar *char_ptr;\n\n\/**************************************************************************\/\n\/*!\n @brief Initialises all the sensors used by this example\n*\/\n\/**************************************************************************\/\nvoid initSensors()\n{\n if(!accel.begin())\n {\n \/* There was a problem detecting the LSM303 ... check your connections *\/\n Serial.println(F(\"Ooops, no LSM303 detected ... Check your wiring!\"));\n while(1);\n }\n if(!mag.begin())\n {\n \/* There was a problem detecting the LSM303 ... check your connections *\/\n Serial.println(\"Ooops, no LSM303 detected ... Check your wiring!\");\n while(1);\n }\n if(!gyr.begin())\n {\n \/* There was a problem detecting the LSM303 ... check your connections *\/\n Serial.println(\"Ooops, no L3GD20 detected ... Check your wiring!\");\n while(1);\n }\n}\n\n\/**************************************************************************\/\n\/*!\n\n*\/\n\/**************************************************************************\/\nvoid setup(void)\n{\n Serial.begin(115200);\n\n rfBegin(11);\n\n \/* Initialise the sensors *\/\n initSensors();\n}\n\n\/**************************************************************************\/\n\/*!\n @brief Constantly check the roll\/pitch\/heading\/altitude\/temperature\n*\/\n\/**************************************************************************\/\nvoid loop(void)\n {\n\n sensors_event_t accel_event;\n sensors_event_t mag_event;\n sensors_event_t gyr_event;\n sensors_vec_t orientation;\n\n \/* Calculate pitch and roll from the raw accelerometer data *\/\n if(!accel.getEvent(&accel_event)) return;\n if (dof.fusionGetOrientation(&accel_event, &mag_event, &orientation))\n {\n \/* 'orientation' should have valid .roll and .pitch fields *\/\n p_roll = orientation.roll; \/\/roll\n \/\/ if(orientation.roll<=0){\n \/\/ Serial.print(-orientation.roll); \/\/roll\n \/\/ }\n \/\/ else{\n \/\/ Serial.print(360-orientation.roll); \/\/roll\n \/\/ }\n p_pitch = orientation.pitch; \/\/pitch\n \/\/ if(orientation.pitch<0){\n \/\/ Serial.print(-orientation.pitch); \/\/pitch\n \/\/ }\n \/\/ else{\n \/\/ Serial.print(360-orientation.pitch); \/\/pitch\n \/\/ }\n }\n\n \/* Calculate x y z from gyroscope *\/\n if (!gyr.getEvent(&gyr_event)) return;\n else {\n \/* 'orientation' should have valid .roll and .pitch fields *\/\n p_gyro_x = gyr_event.gyro.x; \/\/gyr x\n p_gyro_y = gyr_event.gyro.y; \/\/gyr y\n p_gyro_z = gyr_event.gyro.z; \/\/gyr z\n\n }\n\n \/* Calculate the heading using the magnetometer *\/\n if(!mag.getEvent(&mag_event)) return;\n \/\/ dof.magTiltCompensation(SENSOR_AXIS_Z, &mag_event, &accel_event);\n if (dof.fusionGetOrientation(&accel_event, &mag_event, &orientation)) {\n \/* 'orientation' should have valid .heading data now *\/\n p_heading = orientation.heading;\n }\n\n char_ptr = buf;\n *char_ptr = '\\n';\n char_ptr++;\n\n dtostrf(p_roll, 1, 2, char_ptr);\n char_ptr += strlen(char_ptr);\n *char_ptr = ',';\n char_ptr++;\n\n dtostrf(p_pitch, 1, 2, char_ptr);\n char_ptr += strlen(char_ptr);\n *char_ptr = ',';\n char_ptr++;\n\n dtostrf(p_gyro_x, 1, 2, char_ptr);\n char_ptr += strlen(char_ptr);\n *char_ptr = ',';\n char_ptr++;\n\n dtostrf(p_gyro_y, 1, 2, char_ptr);\n char_ptr += strlen(char_ptr);\n *char_ptr = ',';\n char_ptr++;\n\n dtostrf(p_gyro_z, 1, 2, char_ptr);\n char_ptr += strlen(char_ptr);\n *char_ptr = ',';\n char_ptr++;\n\n dtostrf(p_heading, 1, 2, char_ptr);\n char_ptr += strlen(char_ptr);\n *char_ptr = ',';\n char_ptr++;\n\n char pt1 = analogRead(2) > 255 ? '1' : '0';\n char pt2 = analogRead(3) > 255 ? '1' : '0';\n char pt3 = analogRead(4) > 255 ? '1' : '0';\n\n char_ptr[0] = pt1;\n char_ptr[1] = ',';\n char_ptr[2] = pt2;\n char_ptr[3] = ',';\n char_ptr[4] = pt3;\n char_ptr[5] = '\\n';\n char_ptr[6] = '\\0';\n\n rfPrint(buf);\n \/\/Serial.print(buf);\n\n delay(100);\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * The Apache Software License, Version 1.1\n *\n * Copyright (c) 2003 The Apache Software Foundation. All rights\n * reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n *\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in\n * the documentation and\/or other materials provided with the\n * distribution.\n *\n * 3. The end-user documentation included with the redistribution,\n * if any, must include the following acknowledgment:\n * \"This product includes software developed by the\n * Apache Software Foundation (http:\/\/www.apache.org\/).\"\n * Alternately, this acknowledgment may appear in the software itself,\n * if and wherever such third-party acknowledgments normally appear.\n *\n * 4. The names \"Xerces\" and \"Apache Software Foundation\" must\n * not be used to endorse or promote products derived from this\n * software without prior written permission. For written\n * permission, please contact apache\\@apache.org.\n *\n * 5. Products derived from this software may not be called \"Apache\",\n * nor may \"Apache\" appear in their name, without prior written\n * permission of the Apache Software Foundation.\n *\n * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED\n * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR\n * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF\n * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT\n * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n * ====================================================================\n *\n * This software consists of voluntary contributions made by many\n * individuals on behalf of the Apache Software Foundation, and was\n * originally based on software copyright (c) 1999, International\n * Business Machines, Inc., http:\/\/www.ibm.com . For more information\n * on the Apache Software Foundation, please see\n * <http:\/\/www.apache.org\/>.\n *\/\n\n\/*\n * $Id$\n *\/\n\n\n#if !defined(XMEMORY_HPP)\n#define XMEMORY_HPP\n\n#include <xercesc\/util\/XercesDefs.hpp>\n#include <stdlib.h>\n\nXERCES_CPP_NAMESPACE_BEGIN\n\nclass MemoryManager;\n\n\/**\n * This class makes it possible to override the C++ memory management by\n * adding new\/delete operators to this base class.\n *\n * This class is used in conjuction with the pluggable memory manager. It\n * allows applications to control Xerces memory management.\n *\/\n\nclass XMLUTIL_EXPORT XMemory\n{\npublic :\n \/\/ -----------------------------------------------------------------------\n \/\/ The C++ memory management\n \/\/ -----------------------------------------------------------------------\n \/** @name The C++ memory management *\/\n \/\/@{\n\n \/**\n * This method overrides operator new\n *\n * @param size The requested memory size\n *\/\n void* operator new(size_t size);\n\n \/**\n * This method overrides placement operator new\n *\n * @param size The requested memory size\n * @param memMgr An application's memory manager\n *\/\n void* operator new(size_t size, MemoryManager* memMgr);\n\n \/**\n * This method overrides operator delete\n *\n * @param p The pointer to the allocated memory\n *\/\n void operator delete(void* p);\n\n \/\/The HP compiler is complaining about duplicate overloading of delete\n#if !defined(XML_HPUX)\n \/**\n * This method provide a matching delete for the placement new\n *\n * @param p The pointer to the allocated memory\n * @param memMgr An appliation's memory manager\n *\/\n void operator delete(void* p, MemoryManager* memMgr);\n#endif\n\n \/\/@}\n\nprotected :\n \/\/ -----------------------------------------------------------------------\n \/\/ Hidden Constructors\n \/\/ -----------------------------------------------------------------------\n \/** @name Constructor *\/\n \/\/@{\n\n \/**\n * Protected default constructor\n *\/\n XMemory()\n {\n }\n \/\/@}\n\nprivate:\n \/\/ -----------------------------------------------------------------------\n \/\/ Unimplemented constructors and operators\n \/\/ -----------------------------------------------------------------------\n XMemory(const XMemory&);\n XMemory& operator=(const XMemory&);\n};\n\nXERCES_CPP_NAMESPACE_END\n\n#endif\n<commit_msg>for build on WinXP.NET and Intel Electron<commit_after>\/*\n * The Apache Software License, Version 1.1\n *\n * Copyright (c) 2003 The Apache Software Foundation. All rights\n * reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n *\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in\n * the documentation and\/or other materials provided with the\n * distribution.\n *\n * 3. The end-user documentation included with the redistribution,\n * if any, must include the following acknowledgment:\n * \"This product includes software developed by the\n * Apache Software Foundation (http:\/\/www.apache.org\/).\"\n * Alternately, this acknowledgment may appear in the software itself,\n * if and wherever such third-party acknowledgments normally appear.\n *\n * 4. The names \"Xerces\" and \"Apache Software Foundation\" must\n * not be used to endorse or promote products derived from this\n * software without prior written permission. For written\n * permission, please contact apache\\@apache.org.\n *\n * 5. Products derived from this software may not be called \"Apache\",\n * nor may \"Apache\" appear in their name, without prior written\n * permission of the Apache Software Foundation.\n *\n * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED\n * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR\n * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF\n * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT\n * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n * ====================================================================\n *\n * This software consists of voluntary contributions made by many\n * individuals on behalf of the Apache Software Foundation, and was\n * originally based on software copyright (c) 1999, International\n * Business Machines, Inc., http:\/\/www.ibm.com . For more information\n * on the Apache Software Foundation, please see\n * <http:\/\/www.apache.org\/>.\n *\/\n\n\/*\n * $Id$\n *\/\n\n\n#if !defined(XMEMORY_HPP)\n#define XMEMORY_HPP\n\n#include <xercesc\/util\/XercesDefs.hpp>\n#include <stdlib.h>\n\nXERCES_CPP_NAMESPACE_BEGIN\n\nclass MemoryManager;\n\n\/**\n * This class makes it possible to override the C++ memory management by\n * adding new\/delete operators to this base class.\n *\n * This class is used in conjuction with the pluggable memory manager. It\n * allows applications to control Xerces memory management.\n *\/\n\nclass XMLUTIL_EXPORT XMemory\n{\npublic :\n \/\/ -----------------------------------------------------------------------\n \/\/ The C++ memory management\n \/\/ -----------------------------------------------------------------------\n \/** @name The C++ memory management *\/\n \/\/@{\n\n \/**\n * This method overrides operator new\n *\n * @param size The requested memory size\n *\/\n void* operator new(size_t size);\n\n \/**\n * This method overrides placement operator new\n *\n * @param size The requested memory size\n * @param memMgr An application's memory manager\n *\/\n void* operator new(size_t size, MemoryManager* memMgr);\n\n \/**\n * This method overrides operator delete\n *\n * @param p The pointer to the allocated memory\n *\/\n void operator delete(void* p);\n\n \/\/The HP compiler is complaining about duplicate overloading of delete\n#if !defined(XML_HPUX)\n \/**\n * This method provide a matching delete for the placement new\n *\n * @param p The pointer to the allocated memory\n * @param memMgr An appliation's memory manager\n *\/\n void operator delete(void* p, MemoryManager* memMgr);\n#endif\n\n \/\/@}\n\nprotected :\n \/\/ -----------------------------------------------------------------------\n \/\/ Hidden Constructors\n \/\/ -----------------------------------------------------------------------\n \/** @name Constructor *\/\n \/\/@{\n\n \/**\n * Protected default constructor and copy constructor\n *\/\n XMemory()\n {\n }\n\n XMemory(const XMemory&)\n {\n }\n \/\/@}\n\nprivate:\n \/\/ -----------------------------------------------------------------------\n \/\/ Unimplemented operators\n \/\/ -----------------------------------------------------------------------\n XMemory& operator=(const XMemory&);\n};\n\nXERCES_CPP_NAMESPACE_END\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/*\n\nCopyright 2015-2021 Igor Petrovic\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\n*\/\n\n#include <cstddef>\n#include <stdio.h>\n#include <stdlib.h>\n#include <avr\/power.h>\n#include <avr\/eeprom.h>\n#include <avr\/wdt.h>\n#include \"board\/Board.h\"\n#include \"board\/Internal.h\"\n#include \"board\/common\/io\/Helpers.h\"\n#include \"core\/src\/general\/ADC.h\"\n#include \"core\/src\/arch\/avr\/Misc.h\"\n#include \"core\/src\/general\/IO.h\"\n#include \"core\/src\/general\/Interrupt.h\"\n#include \"core\/src\/general\/Timing.h\"\n#include \"Pins.h\"\n\nextern \"C\" void __cxa_pure_virtual()\n{\n Board::detail::errorHandler();\n}\n\nvoid* operator new(std::size_t size)\n{\n return malloc(size);\n}\n\nvoid operator delete(void* ptr)\n{\n}\n\nnamespace std\n{\n void __throw_bad_function_call()\n {\n Board::detail::errorHandler();\n }\n\n void __throw_bad_alloc()\n {\n Board::detail::errorHandler();\n }\n} \/\/ namespace std\n\nnamespace Board\n{\n namespace detail\n {\n namespace setup\n {\n void bootloader()\n {\n DISABLE_INTERRUPTS();\n\n \/\/clear reset source\n MCUSR &= ~(1 << EXTRF);\n\n \/\/disable watchdog\n MCUSR &= ~(1 << WDRF);\n wdt_disable();\n\n \/\/disable clock division\n clock_prescale_set(clock_div_1);\n\n detail::setup::io();\n\n \/\/relocate the interrupt vector table to the bootloader section\n MCUCR = (1 << IVCE);\n MCUCR = (1 << IVSEL);\n\n ENABLE_INTERRUPTS();\n\n#if defined(USB_LINK_MCU) || !defined(USB_MIDI_SUPPORTED)\n Board::UART::init(UART_CHANNEL_USB_LINK, UART_BAUDRATE_MIDI_OD);\n#endif\n }\n\n void application()\n {\n DISABLE_INTERRUPTS();\n\n \/\/relocate the interrupt vector table to the application section\n MCUCR = (1 << IVCE);\n MCUCR = (0 << IVSEL);\n\n \/\/clear reset source\n MCUSR &= ~(1 << EXTRF);\n\n \/\/disable watchdog\n MCUSR &= ~(1 << WDRF);\n wdt_disable();\n\n \/\/disable clock division\n clock_prescale_set(clock_div_1);\n\n detail::setup::io();\n detail::setup::adc();\n\n#if defined(USB_LINK_MCU) || !defined(USB_MIDI_SUPPORTED)\n Board::UART::init(UART_CHANNEL_USB_LINK, UART_BAUDRATE_MIDI_OD);\n#endif\n\n detail::setup::usb();\n detail::setup::timers();\n\n ENABLE_INTERRUPTS();\n\n#ifndef USB_LINK_MCU\n \/\/add some delay and remove initial readout of digital inputs\n core::timing::waitMs(10);\n detail::io::flushInputReadings();\n#endif\n }\n\n#ifdef ANALOG_SUPPORTED\n void adc()\n {\n core::adc::conf_t adcConfiguration;\n\n adcConfiguration.prescaler = core::adc::prescaler_t::p128;\n\n#ifdef ADC_EXT_REF\n adcConfiguration.vref = core::adc::vRef_t::aref;\n#else\n adcConfiguration.vref = core::adc::vRef_t::avcc;\n#endif\n\n for (int i = 0; i < MAX_ADC_CHANNELS; i++)\n core::adc::disconnectDigitalIn(Board::detail::map::adcChannel(i));\n\n core::adc::setup(adcConfiguration);\n core::adc::setChannel(Board::detail::map::adcChannel(0));\n\n for (int i = 0; i < 3; i++)\n core::adc::read(); \/\/few dummy reads to init ADC\n\n core::adc::enableInterrupt();\n core::adc::startConversion();\n }\n#endif\n\n void timers()\n {\n \/\/set timer0 to ctc, used for millis\/led matrix\n \/\/clear timer0 conf\n TCCR0A = 0;\n TCCR0B = 0;\n TIMSK0 = 0;\n TCCR0A |= (1 << WGM01); \/\/CTC mode\n TCCR0B |= (1 << CS01) | (1 << CS00); \/\/prescaler 64\n OCR0A = 249; \/\/1ms\n TIMSK0 |= (1 << OCIE0A); \/\/compare match interrupt\n\n \/\/use timer1 for soft pwm\n TCCR1A = 0;\n TCCR1B = 0;\n TCCR1C = 0;\n\n TIMSK1 = 0;\n TCCR1B |= (1 << WGM12); \/\/CTC mode\n TCCR1B |= (1 << CS11) | (1 << CS10); \/\/prescaler 64\n OCR1A = 124; \/\/500us\n TIMSK1 |= (1 << OCIE1A); \/\/compare match interrupt\n }\n\n void io()\n {\n#ifdef NUMBER_OF_IN_SR\n CORE_IO_CONFIG(SR_IN_DATA_PORT, SR_IN_DATA_PIN, core::io::pinMode_t::input);\n CORE_IO_CONFIG(SR_IN_CLK_PORT, SR_IN_CLK_PIN, core::io::pinMode_t::output);\n CORE_IO_CONFIG(SR_IN_LATCH_PORT, SR_IN_LATCH_PIN, core::io::pinMode_t::output);\n\n CORE_IO_SET_LOW(SR_IN_CLK_PORT, SR_IN_CLK_PIN);\n CORE_IO_SET_HIGH(SR_IN_LATCH_PORT, SR_IN_LATCH_PIN);\n#else\n for (int i = 0; i < MAX_NUMBER_OF_BUTTONS; i++)\n {\n core::io::mcuPin_t pin = detail::map::buttonPin(i);\n\n CORE_IO_CONFIG(CORE_IO_MCU_PIN_PORT(pin), CORE_IO_MCU_PIN_INDEX(pin), core::io::pinMode_t::input);\n\n#ifndef BUTTONS_EXT_PULLUPS\n CORE_IO_SET_HIGH(CORE_IO_MCU_PIN_PORT(pin), CORE_IO_MCU_PIN_INDEX(pin));\n#endif\n }\n#endif\n\n#ifdef NUMBER_OF_BUTTON_COLUMNS\n CORE_IO_CONFIG(DEC_BM_PORT_A0, DEC_BM_PIN_A0, core::io::pinMode_t::output);\n CORE_IO_CONFIG(DEC_BM_PORT_A1, DEC_BM_PIN_A1, core::io::pinMode_t::output);\n CORE_IO_CONFIG(DEC_BM_PORT_A2, DEC_BM_PIN_A2, core::io::pinMode_t::output);\n\n CORE_IO_SET_LOW(DEC_BM_PORT_A0, DEC_BM_PIN_A0);\n CORE_IO_SET_LOW(DEC_BM_PORT_A1, DEC_BM_PIN_A1);\n CORE_IO_SET_LOW(DEC_BM_PORT_A2, DEC_BM_PIN_A2);\n#endif\n\n#ifdef NUMBER_OF_OUT_SR\n CORE_IO_CONFIG(SR_OUT_DATA_PORT, SR_OUT_DATA_PIN, core::io::pinMode_t::output);\n CORE_IO_CONFIG(SR_OUT_CLK_PORT, SR_OUT_CLK_PIN, core::io::pinMode_t::output);\n CORE_IO_CONFIG(SR_OUT_LATCH_PORT, SR_OUT_LATCH_PIN, core::io::pinMode_t::output);\n\n#ifdef SR_OUT_OE_PORT\n CORE_IO_CONFIG(SR_OUT_OE_PORT, SR_OUT_OE_PIN, core::io::pinMode_t::output);\n#endif\n\n \/\/init all outputs on shift register\n CORE_IO_SET_LOW(SR_OUT_LATCH_PORT, SR_OUT_LATCH_PIN);\n\n for (int i = 0; i < MAX_NUMBER_OF_LEDS; i++)\n {\n EXT_LED_OFF(SR_OUT_DATA_PORT, SR_OUT_DATA_PIN);\n CORE_IO_SET_HIGH(SR_OUT_CLK_PORT, SR_OUT_CLK_PIN);\n detail::io::sr595wait();\n CORE_IO_SET_LOW(SR_OUT_CLK_PORT, SR_OUT_CLK_PIN);\n }\n\n CORE_IO_SET_HIGH(SR_OUT_LATCH_PORT, SR_OUT_LATCH_PIN);\n#ifdef SR_OUT_OE_PORT\n CORE_IO_SET_LOW(SR_OUT_OE_PORT, SR_OUT_OE_PIN);\n#endif\n#else\n#ifdef NUMBER_OF_LED_ROWS\n CORE_IO_CONFIG(DEC_LM_PORT_A0, DEC_LM_PIN_A0, core::io::pinMode_t::output);\n CORE_IO_CONFIG(DEC_LM_PORT_A1, DEC_LM_PIN_A1, core::io::pinMode_t::output);\n CORE_IO_CONFIG(DEC_LM_PORT_A2, DEC_LM_PIN_A2, core::io::pinMode_t::output);\n\n CORE_IO_SET_LOW(DEC_LM_PORT_A0, DEC_LM_PIN_A0);\n CORE_IO_SET_LOW(DEC_LM_PORT_A1, DEC_LM_PIN_A1);\n CORE_IO_SET_LOW(DEC_LM_PORT_A2, DEC_LM_PIN_A2);\n\n for (int i = 0; i < NUMBER_OF_LED_ROWS; i++)\n#else\n for (int i = 0; i < MAX_NUMBER_OF_LEDS; i++)\n#endif\n {\n core::io::mcuPin_t pin = detail::map::ledPin(i);\n\n CORE_IO_CONFIG(CORE_IO_MCU_PIN_PORT(pin), CORE_IO_MCU_PIN_INDEX(pin), core::io::pinMode_t::output);\n EXT_LED_OFF(CORE_IO_MCU_PIN_PORT(pin), CORE_IO_MCU_PIN_INDEX(pin));\n }\n#endif\n\n#if MAX_ADC_CHANNELS > 0\n for (int i = 0; i < MAX_ADC_CHANNELS; i++)\n {\n core::io::mcuPin_t pin = detail::map::adcPin(i);\n\n CORE_IO_CONFIG(CORE_IO_MCU_PIN_PORT(pin), CORE_IO_MCU_PIN_INDEX(pin), core::io::pinMode_t::input);\n CORE_IO_SET_LOW(CORE_IO_MCU_PIN_PORT(pin), CORE_IO_MCU_PIN_INDEX(pin));\n }\n#endif\n\n#ifdef NUMBER_OF_MUX\n CORE_IO_CONFIG(MUX_PORT_S0, MUX_PIN_S0, core::io::pinMode_t::output);\n CORE_IO_CONFIG(MUX_PORT_S1, MUX_PIN_S1, core::io::pinMode_t::output);\n CORE_IO_CONFIG(MUX_PORT_S2, MUX_PIN_S2, core::io::pinMode_t::output);\n#ifdef MUX_PORT_S3\n CORE_IO_CONFIG(MUX_PORT_S3, MUX_PIN_S3, core::io::pinMode_t::output);\n#endif\n#endif\n\n#ifdef BTLDR_BUTTON_PORT\n CORE_IO_CONFIG(BTLDR_BUTTON_PORT, BTLDR_BUTTON_PIN, core::io::pinMode_t::input);\n CORE_IO_SET_HIGH(BTLDR_BUTTON_PORT, BTLDR_BUTTON_PIN);\n#endif\n\n#ifdef LED_INDICATORS\n CORE_IO_CONFIG(LED_MIDI_IN_DIN_PORT, LED_MIDI_IN_DIN_PIN, core::io::pinMode_t::output);\n CORE_IO_CONFIG(LED_MIDI_OUT_DIN_PORT, LED_MIDI_OUT_DIN_PIN, core::io::pinMode_t::output);\n CORE_IO_CONFIG(LED_MIDI_IN_USB_PORT, LED_MIDI_IN_USB_PIN, core::io::pinMode_t::output);\n CORE_IO_CONFIG(LED_MIDI_OUT_USB_PORT, LED_MIDI_OUT_USB_PIN, core::io::pinMode_t::output);\n\n INT_LED_OFF(LED_MIDI_IN_DIN_PORT, LED_MIDI_IN_DIN_PIN);\n INT_LED_OFF(LED_MIDI_OUT_DIN_PORT, LED_MIDI_OUT_DIN_PIN);\n INT_LED_OFF(LED_MIDI_IN_USB_PORT, LED_MIDI_IN_USB_PIN);\n INT_LED_OFF(LED_MIDI_OUT_USB_PORT, LED_MIDI_OUT_USB_PIN);\n#endif\n\n#ifdef LED_BTLDR_PORT\n CORE_IO_CONFIG(LED_BTLDR_PORT, LED_BTLDR_PIN, core::io::pinMode_t::output);\n CORE_IO_SET_HIGH(LED_BTLDR_PORT, LED_BTLDR_PIN);\n#endif\n\n#ifdef TOTAL_UNUSED_IO\n for (int i = 0; i < TOTAL_UNUSED_IO; i++)\n {\n core::io::mcuPin_t pin = detail::map::unusedPin(i);\n CORE_IO_CONFIG(CORE_IO_MCU_PIN_PORT(pin), CORE_IO_MCU_PIN_INDEX(pin), core::io::pinMode_t::output);\n CORE_IO_SET_STATE(CORE_IO_MCU_PIN_PORT(pin), CORE_IO_MCU_PIN_INDEX(pin), detail::map::unusedPinState(i));\n }\n#endif\n }\n } \/\/ namespace setup\n } \/\/ namespace detail\n} \/\/ namespace Board<commit_msg>board\/avr: enable pwm timer only when needed<commit_after>\/*\n\nCopyright 2015-2021 Igor Petrovic\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\n*\/\n\n#include <cstddef>\n#include <stdio.h>\n#include <stdlib.h>\n#include <avr\/power.h>\n#include <avr\/eeprom.h>\n#include <avr\/wdt.h>\n#include \"board\/Board.h\"\n#include \"board\/Internal.h\"\n#include \"board\/common\/io\/Helpers.h\"\n#include \"core\/src\/general\/ADC.h\"\n#include \"core\/src\/arch\/avr\/Misc.h\"\n#include \"core\/src\/general\/IO.h\"\n#include \"core\/src\/general\/Interrupt.h\"\n#include \"core\/src\/general\/Timing.h\"\n#include \"Pins.h\"\n\nextern \"C\" void __cxa_pure_virtual()\n{\n Board::detail::errorHandler();\n}\n\nvoid* operator new(std::size_t size)\n{\n return malloc(size);\n}\n\nvoid operator delete(void* ptr)\n{\n}\n\nnamespace std\n{\n void __throw_bad_function_call()\n {\n Board::detail::errorHandler();\n }\n\n void __throw_bad_alloc()\n {\n Board::detail::errorHandler();\n }\n} \/\/ namespace std\n\nnamespace Board\n{\n namespace detail\n {\n namespace setup\n {\n void bootloader()\n {\n DISABLE_INTERRUPTS();\n\n \/\/clear reset source\n MCUSR &= ~(1 << EXTRF);\n\n \/\/disable watchdog\n MCUSR &= ~(1 << WDRF);\n wdt_disable();\n\n \/\/disable clock division\n clock_prescale_set(clock_div_1);\n\n detail::setup::io();\n\n \/\/relocate the interrupt vector table to the bootloader section\n MCUCR = (1 << IVCE);\n MCUCR = (1 << IVSEL);\n\n ENABLE_INTERRUPTS();\n\n#if defined(USB_LINK_MCU) || !defined(USB_MIDI_SUPPORTED)\n Board::UART::init(UART_CHANNEL_USB_LINK, UART_BAUDRATE_MIDI_OD);\n#endif\n }\n\n void application()\n {\n DISABLE_INTERRUPTS();\n\n \/\/relocate the interrupt vector table to the application section\n MCUCR = (1 << IVCE);\n MCUCR = (0 << IVSEL);\n\n \/\/clear reset source\n MCUSR &= ~(1 << EXTRF);\n\n \/\/disable watchdog\n MCUSR &= ~(1 << WDRF);\n wdt_disable();\n\n \/\/disable clock division\n clock_prescale_set(clock_div_1);\n\n detail::setup::io();\n detail::setup::adc();\n\n#if defined(USB_LINK_MCU) || !defined(USB_MIDI_SUPPORTED)\n Board::UART::init(UART_CHANNEL_USB_LINK, UART_BAUDRATE_MIDI_OD);\n#endif\n\n detail::setup::usb();\n detail::setup::timers();\n\n ENABLE_INTERRUPTS();\n\n#ifndef USB_LINK_MCU\n \/\/add some delay and remove initial readout of digital inputs\n core::timing::waitMs(10);\n detail::io::flushInputReadings();\n#endif\n }\n\n#ifdef ANALOG_SUPPORTED\n void adc()\n {\n core::adc::conf_t adcConfiguration;\n\n adcConfiguration.prescaler = core::adc::prescaler_t::p128;\n\n#ifdef ADC_EXT_REF\n adcConfiguration.vref = core::adc::vRef_t::aref;\n#else\n adcConfiguration.vref = core::adc::vRef_t::avcc;\n#endif\n\n for (int i = 0; i < MAX_ADC_CHANNELS; i++)\n core::adc::disconnectDigitalIn(Board::detail::map::adcChannel(i));\n\n core::adc::setup(adcConfiguration);\n core::adc::setChannel(Board::detail::map::adcChannel(0));\n\n for (int i = 0; i < 3; i++)\n core::adc::read(); \/\/few dummy reads to init ADC\n\n core::adc::enableInterrupt();\n core::adc::startConversion();\n }\n#endif\n\n void timers()\n {\n \/\/set timer0 to ctc, used for millis\/led matrix\n \/\/clear timer0 conf\n TCCR0A = 0;\n TCCR0B = 0;\n TIMSK0 = 0;\n TCCR0A |= (1 << WGM01); \/\/CTC mode\n TCCR0B |= (1 << CS01) | (1 << CS00); \/\/prescaler 64\n OCR0A = 249; \/\/1ms\n TIMSK0 |= (1 << OCIE0A); \/\/compare match interrupt\n\n#ifdef FW_APP\n#ifndef USB_LINK_MCU\n#if MAX_NUMBER_OF_LEDS > 0\n \/\/use timer1 for soft pwm\n TCCR1A = 0;\n TCCR1B = 0;\n TCCR1C = 0;\n\n TIMSK1 = 0;\n TCCR1B |= (1 << WGM12); \/\/CTC mode\n TCCR1B |= (1 << CS11) | (1 << CS10); \/\/prescaler 64\n OCR1A = 124; \/\/500us\n TIMSK1 |= (1 << OCIE1A); \/\/compare match interrupt\n#endif\n#endif\n#endif\n }\n\n void io()\n {\n#ifdef NUMBER_OF_IN_SR\n CORE_IO_CONFIG(SR_IN_DATA_PORT, SR_IN_DATA_PIN, core::io::pinMode_t::input);\n CORE_IO_CONFIG(SR_IN_CLK_PORT, SR_IN_CLK_PIN, core::io::pinMode_t::output);\n CORE_IO_CONFIG(SR_IN_LATCH_PORT, SR_IN_LATCH_PIN, core::io::pinMode_t::output);\n\n CORE_IO_SET_LOW(SR_IN_CLK_PORT, SR_IN_CLK_PIN);\n CORE_IO_SET_HIGH(SR_IN_LATCH_PORT, SR_IN_LATCH_PIN);\n#else\n for (int i = 0; i < MAX_NUMBER_OF_BUTTONS; i++)\n {\n core::io::mcuPin_t pin = detail::map::buttonPin(i);\n\n CORE_IO_CONFIG(CORE_IO_MCU_PIN_PORT(pin), CORE_IO_MCU_PIN_INDEX(pin), core::io::pinMode_t::input);\n\n#ifndef BUTTONS_EXT_PULLUPS\n CORE_IO_SET_HIGH(CORE_IO_MCU_PIN_PORT(pin), CORE_IO_MCU_PIN_INDEX(pin));\n#endif\n }\n#endif\n\n#ifdef NUMBER_OF_BUTTON_COLUMNS\n CORE_IO_CONFIG(DEC_BM_PORT_A0, DEC_BM_PIN_A0, core::io::pinMode_t::output);\n CORE_IO_CONFIG(DEC_BM_PORT_A1, DEC_BM_PIN_A1, core::io::pinMode_t::output);\n CORE_IO_CONFIG(DEC_BM_PORT_A2, DEC_BM_PIN_A2, core::io::pinMode_t::output);\n\n CORE_IO_SET_LOW(DEC_BM_PORT_A0, DEC_BM_PIN_A0);\n CORE_IO_SET_LOW(DEC_BM_PORT_A1, DEC_BM_PIN_A1);\n CORE_IO_SET_LOW(DEC_BM_PORT_A2, DEC_BM_PIN_A2);\n#endif\n\n#ifdef NUMBER_OF_OUT_SR\n CORE_IO_CONFIG(SR_OUT_DATA_PORT, SR_OUT_DATA_PIN, core::io::pinMode_t::output);\n CORE_IO_CONFIG(SR_OUT_CLK_PORT, SR_OUT_CLK_PIN, core::io::pinMode_t::output);\n CORE_IO_CONFIG(SR_OUT_LATCH_PORT, SR_OUT_LATCH_PIN, core::io::pinMode_t::output);\n\n#ifdef SR_OUT_OE_PORT\n CORE_IO_CONFIG(SR_OUT_OE_PORT, SR_OUT_OE_PIN, core::io::pinMode_t::output);\n#endif\n\n \/\/init all outputs on shift register\n CORE_IO_SET_LOW(SR_OUT_LATCH_PORT, SR_OUT_LATCH_PIN);\n\n for (int i = 0; i < MAX_NUMBER_OF_LEDS; i++)\n {\n EXT_LED_OFF(SR_OUT_DATA_PORT, SR_OUT_DATA_PIN);\n CORE_IO_SET_HIGH(SR_OUT_CLK_PORT, SR_OUT_CLK_PIN);\n detail::io::sr595wait();\n CORE_IO_SET_LOW(SR_OUT_CLK_PORT, SR_OUT_CLK_PIN);\n }\n\n CORE_IO_SET_HIGH(SR_OUT_LATCH_PORT, SR_OUT_LATCH_PIN);\n#ifdef SR_OUT_OE_PORT\n CORE_IO_SET_LOW(SR_OUT_OE_PORT, SR_OUT_OE_PIN);\n#endif\n#else\n#ifdef NUMBER_OF_LED_ROWS\n CORE_IO_CONFIG(DEC_LM_PORT_A0, DEC_LM_PIN_A0, core::io::pinMode_t::output);\n CORE_IO_CONFIG(DEC_LM_PORT_A1, DEC_LM_PIN_A1, core::io::pinMode_t::output);\n CORE_IO_CONFIG(DEC_LM_PORT_A2, DEC_LM_PIN_A2, core::io::pinMode_t::output);\n\n CORE_IO_SET_LOW(DEC_LM_PORT_A0, DEC_LM_PIN_A0);\n CORE_IO_SET_LOW(DEC_LM_PORT_A1, DEC_LM_PIN_A1);\n CORE_IO_SET_LOW(DEC_LM_PORT_A2, DEC_LM_PIN_A2);\n\n for (int i = 0; i < NUMBER_OF_LED_ROWS; i++)\n#else\n for (int i = 0; i < MAX_NUMBER_OF_LEDS; i++)\n#endif\n {\n core::io::mcuPin_t pin = detail::map::ledPin(i);\n\n CORE_IO_CONFIG(CORE_IO_MCU_PIN_PORT(pin), CORE_IO_MCU_PIN_INDEX(pin), core::io::pinMode_t::output);\n EXT_LED_OFF(CORE_IO_MCU_PIN_PORT(pin), CORE_IO_MCU_PIN_INDEX(pin));\n }\n#endif\n\n#if MAX_ADC_CHANNELS > 0\n for (int i = 0; i < MAX_ADC_CHANNELS; i++)\n {\n core::io::mcuPin_t pin = detail::map::adcPin(i);\n\n CORE_IO_CONFIG(CORE_IO_MCU_PIN_PORT(pin), CORE_IO_MCU_PIN_INDEX(pin), core::io::pinMode_t::input);\n CORE_IO_SET_LOW(CORE_IO_MCU_PIN_PORT(pin), CORE_IO_MCU_PIN_INDEX(pin));\n }\n#endif\n\n#ifdef NUMBER_OF_MUX\n CORE_IO_CONFIG(MUX_PORT_S0, MUX_PIN_S0, core::io::pinMode_t::output);\n CORE_IO_CONFIG(MUX_PORT_S1, MUX_PIN_S1, core::io::pinMode_t::output);\n CORE_IO_CONFIG(MUX_PORT_S2, MUX_PIN_S2, core::io::pinMode_t::output);\n#ifdef MUX_PORT_S3\n CORE_IO_CONFIG(MUX_PORT_S3, MUX_PIN_S3, core::io::pinMode_t::output);\n#endif\n#endif\n\n#ifdef BTLDR_BUTTON_PORT\n CORE_IO_CONFIG(BTLDR_BUTTON_PORT, BTLDR_BUTTON_PIN, core::io::pinMode_t::input);\n CORE_IO_SET_HIGH(BTLDR_BUTTON_PORT, BTLDR_BUTTON_PIN);\n#endif\n\n#ifdef LED_INDICATORS\n CORE_IO_CONFIG(LED_MIDI_IN_DIN_PORT, LED_MIDI_IN_DIN_PIN, core::io::pinMode_t::output);\n CORE_IO_CONFIG(LED_MIDI_OUT_DIN_PORT, LED_MIDI_OUT_DIN_PIN, core::io::pinMode_t::output);\n CORE_IO_CONFIG(LED_MIDI_IN_USB_PORT, LED_MIDI_IN_USB_PIN, core::io::pinMode_t::output);\n CORE_IO_CONFIG(LED_MIDI_OUT_USB_PORT, LED_MIDI_OUT_USB_PIN, core::io::pinMode_t::output);\n\n INT_LED_OFF(LED_MIDI_IN_DIN_PORT, LED_MIDI_IN_DIN_PIN);\n INT_LED_OFF(LED_MIDI_OUT_DIN_PORT, LED_MIDI_OUT_DIN_PIN);\n INT_LED_OFF(LED_MIDI_IN_USB_PORT, LED_MIDI_IN_USB_PIN);\n INT_LED_OFF(LED_MIDI_OUT_USB_PORT, LED_MIDI_OUT_USB_PIN);\n#endif\n\n#ifdef LED_BTLDR_PORT\n CORE_IO_CONFIG(LED_BTLDR_PORT, LED_BTLDR_PIN, core::io::pinMode_t::output);\n CORE_IO_SET_HIGH(LED_BTLDR_PORT, LED_BTLDR_PIN);\n#endif\n\n#ifdef TOTAL_UNUSED_IO\n for (int i = 0; i < TOTAL_UNUSED_IO; i++)\n {\n core::io::mcuPin_t pin = detail::map::unusedPin(i);\n CORE_IO_CONFIG(CORE_IO_MCU_PIN_PORT(pin), CORE_IO_MCU_PIN_INDEX(pin), core::io::pinMode_t::output);\n CORE_IO_SET_STATE(CORE_IO_MCU_PIN_PORT(pin), CORE_IO_MCU_PIN_INDEX(pin), detail::map::unusedPinState(i));\n }\n#endif\n }\n } \/\/ namespace setup\n } \/\/ namespace detail\n} \/\/ namespace Board<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2008 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"SkGraphicsContext.h\"\n\n#include \"base\/gfx\/platform_canvas_mac.h\"\n#include \"base\/gfx\/image_operations.h\"\n#include \"base\/gfx\/skia_utils_mac.h\"\n#include \"base\/logging.h\"\n#include \"GraphicsContextPrivate.h\"\n#include \"SkBitmap.h\"\n#include \"NativeImageSkia.h\"\n#include \"SkiaUtils.h\"\n\n\/\/ These need to be moved\n#include \"ThemeData.h\"\n\n#define kSkiaOrientation kHIThemeOrientationNormal\n\nnamespace {\n\n\/\/ Draws the given bitmap to the given canvas. The subset of the source bitmap\n\/\/ identified by src_rect is drawn to the given destination rect. The bitmap\n\/\/ will be resampled to resample_width * resample_height (this is the size of\n\/\/ the whole image, not the subset). See shouldResampleBitmap for more.\n\/\/\n\/\/ This does a lot of computation to resample only the portion of the bitmap\n\/\/ that will only be drawn. This is critical for performance since when we are\n\/\/ scrolling, for example, we are only drawing a small strip of the image.\n\/\/ Resampling the whole image every time is very slow, so this speeds up things\n\/\/ dramatically.\nvoid DrawResampledBitmap(SkCanvas& canvas,\n SkPaint& paint,\n const NativeImageSkia& bitmap,\n const SkIRect& src_irect,\n const SkRect& dest_rect) {\n \/\/ First get the subset we need. This is efficient and does not copy pixels.\n SkBitmap subset;\n bitmap.extractSubset(&subset, src_irect);\n SkRect src_rect;\n src_rect.set(src_irect);\n\n \/\/ Whether we're doing a subset or using the full source image.\n bool src_is_full = src_irect.fLeft == 0 && src_irect.fTop == 0 &&\n src_irect.width() == bitmap.width() &&\n src_irect.height() == bitmap.height();\n\n \/\/ We will always draw in integer sizes, so round the destination rect.\n SkIRect dest_rect_rounded;\n dest_rect.round(&dest_rect_rounded);\n SkIRect resized_image_rect; \/\/ Represents the size of the resized image.\n resized_image_rect.set(0, 0,\n dest_rect_rounded.width(), dest_rect_rounded.height());\n\n if (src_is_full &&\n bitmap.hasResizedBitmap(dest_rect_rounded.width(),\n dest_rect_rounded.height())) {\n \/\/ Yay, this bitmap frame already has a resized version appropriate for us.\n SkBitmap resampled = bitmap.resizedBitmap(dest_rect_rounded.width(),\n dest_rect_rounded.height());\n canvas.drawBitmapRect(resampled, NULL, dest_rect, &paint);\n return;\n }\n\n \/\/ Compute the visible portion of our rect.\n SkRect dest_bitmap_subset_sk;\n ClipRectToCanvas(canvas, dest_rect, &dest_bitmap_subset_sk);\n dest_bitmap_subset_sk.offset(-dest_rect.fLeft, -dest_rect.fTop);\n\n \/\/ The matrix inverting, etc. could have introduced rounding error which\n \/\/ causes the bounds to be outside of the resized bitmap. We round outward so\n \/\/ we always lean toward it being larger rather than smaller than we need,\n \/\/ and then clamp to the bitmap bounds so we don't get any invalid data.\n SkIRect dest_bitmap_subset_sk_i;\n dest_bitmap_subset_sk.roundOut(&dest_bitmap_subset_sk_i);\n if (!dest_bitmap_subset_sk_i.intersect(resized_image_rect))\n return; \/\/ Resized image does not intersect.\n\n if (src_is_full && bitmap.shouldCacheResampling(\n resized_image_rect.width(),\n resized_image_rect.height(),\n dest_bitmap_subset_sk_i.width(),\n dest_bitmap_subset_sk_i.height())) {\n \/\/ We're supposed to resize the entire image and cache it, even though we\n \/\/ don't need all of it.\n SkBitmap resampled = bitmap.resizedBitmap(dest_rect_rounded.width(),\n dest_rect_rounded.height());\n canvas.drawBitmapRect(resampled, NULL, dest_rect, &paint);\n } else {\n \/\/ We should only resize the exposed part of the bitmap to do the minimal\n \/\/ possible work.\n gfx::Rect dest_bitmap_subset(dest_bitmap_subset_sk_i.fLeft,\n dest_bitmap_subset_sk_i.fTop,\n dest_bitmap_subset_sk_i.width(),\n dest_bitmap_subset_sk_i.height());\n\n \/\/ Resample the needed part of the image.\n SkBitmap resampled = gfx::ImageOperations::Resize(subset,\n gfx::ImageOperations::RESIZE_LANCZOS3,\n gfx::Size(dest_rect_rounded.width(), dest_rect_rounded.height()),\n dest_bitmap_subset);\n\n \/\/ Compute where the new bitmap should be drawn. Since our new bitmap may be\n \/\/ smaller than the original, we have to shift it over by the same amount\n \/\/ that we cut off the top and left.\n SkRect offset_dest_rect = {\n dest_bitmap_subset.x() + dest_rect.fLeft,\n dest_bitmap_subset.y() + dest_rect.fTop,\n dest_bitmap_subset.right() + dest_rect.fLeft,\n dest_bitmap_subset.bottom() + dest_rect.fTop };\n\n canvas.drawBitmapRect(resampled, NULL, offset_dest_rect, &paint);\n }\n}\n\n} \/\/ namespace\n\nSkGraphicsContext::SkGraphicsContext(gfx::PlatformCanvas* canvas)\n : canvas_(canvas),\n paint_context_(NULL),\n own_canvas_(false) {\n}\n\nSkGraphicsContext::~SkGraphicsContext() {\n if (own_canvas_)\n delete canvas_;\n}\n\nconst gfx::NativeTheme* SkGraphicsContext::nativeTheme() {\n \/\/ TODO(pinkerton): fix me\n return nil;\n}\n\nvoid SkGraphicsContext::paintIcon(CGImageRef icon, const SkIRect& rect) {\n CGContextRef context = canvas_->beginPlatformPaint();\n CGRect r = gfx::SkIRectToCGRect(rect);\n CGContextDrawImage(context, r, icon);\n canvas_->endPlatformPaint();\n}\n\n\nvoid SkGraphicsContext::paintButton(const SkIRect& widgetRect,\n const ThemeData& themeData) {\n CGContextRef context = canvas_->beginPlatformPaint();\n\n int state = themeData.m_state;\n CGRect rect(gfx::SkIRectToCGRect(widgetRect));\n HIThemeButtonDrawInfo button_draw_info = { 0 };\n button_draw_info.state = state;\n CGRect label_rect;\n\n HIThemeDrawButton(&rect, &button_draw_info, context,\n kSkiaOrientation, &label_rect);\n\n canvas_->endPlatformPaint();\n}\n\nvoid SkGraphicsContext::paintTextField(const SkIRect& widgetRect,\n const ThemeData& themeData,\n SkColor c,\n bool drawEdges) {\n CGContextRef context = canvas_->beginPlatformPaint();\n\n int state = themeData.m_state;\n CGRect rect(gfx::SkIRectToCGRect(widgetRect));\n CGContextSaveGState(context);\n CGColorRef color = gfx::SkColorToCGColorRef(c);\n CGContextSetFillColorWithColor(context, color);\n CGContextFillRect(context, rect);\n CGContextSetRGBStrokeColor(context, 0.0, 0.0, 0.0, 1.0); \/\/ black border for now\n CGContextStrokeRect(context, rect);\n CGContextRestoreGState(context);\n CGColorRelease(color);\n canvas_->endPlatformPaint();\n}\n\nvoid SkGraphicsContext::paintMenuListArrowButton(const SkIRect& widgetRect,\n unsigned state,\n unsigned classic_state) {\n CGContextRef context = canvas_->beginPlatformPaint();\n\n CGRect rect(gfx::SkIRectToCGRect(widgetRect));\n HIThemePopupArrowDrawInfo arrow_draw_info = { 0 };\n arrow_draw_info.state = state;\n CGRect label_rect;\n \n HIThemeDrawPopupArrow(&rect, &arrow_draw_info, context, kSkiaOrientation);\n\n canvas_->endPlatformPaint();\n}\n\nvoid SkGraphicsContext::paintComplexText(UniscribeStateTextRun& state,\n const SkPoint& point,\n int from,\n int to,\n int ascent) {\n SkColor sk_color(paint_context_->fillColor());\n uint8 alpha = SkColorGetA(sk_color);\n \/\/ Skip 100% transparent text; no need to draw anything.\n if (!alpha)\n return;\n\n CGContextRef context = canvas_->beginPlatformPaint();\n CGContextSaveGState(context);\n CGColorRef color = gfx::SkColorToCGColorRef(sk_color);\n CGContextSetFillColorWithColor(context, color);\n\n \/\/TODO: remove use of UniscribeStateTextRun; show placeholder to test other\n \/\/ code for the moment\n CGContextShowTextAtPoint(context, point.fX, point.fY, \"complex\", 7);\n CGContextRestoreGState(context);\n CGColorRelease(color);\n canvas_->endPlatformPaint();\n}\n\nbool SkGraphicsContext::paintText(FontHandle font,\n int number_glyph,\n const uint16* chars,\n const int* advances,\n const SkPoint& origin) {\n SkColor sk_color(paint_context_->fillColor());\n uint8 alpha = SkColorGetA(sk_color);\n \/\/ Skip 100% transparent text; no need to draw anything.\n if (!alpha)\n return true;\n\n bool success = false;\n CGContextRef context = canvas_->beginPlatformPaint();\n CGContextSaveGState(context);\n CGColorRef color = gfx::SkColorToCGColorRef(sk_color);\n CGContextSetFillColorWithColor(context, color);\n CGContextMoveToPoint(context, origin.fX, origin.fY);\n CGFontRef cg_font = CTFontCopyGraphicsFont(font, NULL);\n CGContextSetFont(context, cg_font);\n\n CGSize cg_advances[number_glyph];\n CGGlyph cg_glyphs[number_glyph];\n \n CTFontGetGlyphsForCharacters(font, chars, cg_glyphs, number_glyph);\n CGContextShowGlyphsAtPoint(context, origin.fX, origin.fY,\n cg_glyphs, number_glyph);\n CGContextRestoreGState(context);\n CGColorRelease(color);\n CGFontRelease(cg_font);\n canvas_->endPlatformPaint();\n return success;\n}\n\nvoid SkGraphicsContext::paintSkPaint(const SkRect& rect,\n const SkPaint& paint) {\n canvas_->drawRect(rect, paint);\n}\n\n\/\/ Returns smallest multiple of two of the dest size that is more than a small\n\/\/ multiple larger than src_size.\n\/\/\n\/\/ Used to determine the size that source should be high-quality upsampled to,\n\/\/ after which we use linear interpolation. Making sure that the linear\n\/\/ interpolation is a factor of two reduces artifacts, and doing the lowest\n\/\/ level of resampling \nstatic int GetResamplingThreshold(int src_size, int dest_size) {\n int lower_bound = src_size * 3 \/ 2; \/\/ Minimum size we'll resample to (1.5x).\n int cur = dest_size;\n\n \/\/ Find the largest multiple of two of the destination size less than our\n \/\/ threshold\n while (cur > lower_bound)\n cur \/= 2;\n\n \/\/ We want the next size above that, or just the destination size if it's\n \/\/ smaller.\n cur *= 2;\n if (cur > dest_size)\n return dest_size;\n return cur;\n}\n\n\/\/ static\nSkGraphicsContext::ResamplingMode SkGraphicsContext::computeResamplingMode(\n const NativeImageSkia& bitmap,\n int src_width, int src_height,\n float dest_width, float dest_height) {\n int dest_iwidth = static_cast<int>(dest_width);\n int dest_iheight = static_cast<int>(dest_height);\n\n \/\/ The percent change below which we will not resample. This usually means\n \/\/ an off-by-one error on the web page, and just doing nearest neighbor\n \/\/ sampling is usually good enough.\n const float kFractionalChangeThreshold = 0.025f;\n\n \/\/ Images smaller than this in either direction are considered \"small\" and\n \/\/ are not resampled ever (see below).\n const int kSmallImageSizeThreshold = 8;\n\n \/\/ The amount an image can be stretched in a single direction before we\n \/\/ say that it is being stretched so much that it must be a line or\n \/\/ background that doesn't need resampling.\n const float kLargeStretch = 3.0f;\n\n \/\/ Figure out if we should resample this image. We try to prune out some\n \/\/ common cases where resampling won't give us anything, since it is much\n \/\/ slower than drawing stretched.\n if (src_width == dest_iwidth && src_height == dest_iheight) {\n \/\/ We don't need to resample if the source and destination are the same.\n return RESAMPLE_NONE;\n }\n \n if (src_width <= kSmallImageSizeThreshold ||\n src_height <= kSmallImageSizeThreshold ||\n dest_width <= kSmallImageSizeThreshold ||\n dest_height <= kSmallImageSizeThreshold) {\n \/\/ Never resample small images. These are often used for borders and\n \/\/ rules (think 1x1 images used to make lines).\n return RESAMPLE_NONE;\n }\n \n if (src_height * kLargeStretch <= dest_height ||\n src_width * kLargeStretch <= dest_width) {\n \/\/ Large image detected.\n\n \/\/ Don't resample if it is being stretched a lot in only one direction.\n \/\/ This is trying to catch cases where somebody has created a border\n \/\/ (which might be large) and then is stretching it to fill some part\n \/\/ of the page.\n if (src_width == dest_width || src_height == dest_height)\n return RESAMPLE_NONE;\n\n \/\/ The image is growing a lot and in more than one direction. Resampling\n \/\/ is slow and doesn't give us very much when growing a lot.\n return RESAMPLE_LINEAR;\n }\n \n if ((fabs(dest_width - src_width) \/ src_width <\n kFractionalChangeThreshold) &&\n (fabs(dest_height - src_height) \/ src_height <\n kFractionalChangeThreshold)) {\n \/\/ It is disappointingly common on the web for image sizes to be off by\n \/\/ one or two pixels. We don't bother resampling if the size difference\n \/\/ is a small fraction of the original size.\n return RESAMPLE_NONE;\n }\n\n \/\/ When the image is not yet done loading, use linear. We don't cache the\n \/\/ partially resampled images, and as they come in incrementally, it causes\n \/\/ us to have to resample the whole thing every time.\n if (!bitmap.isDataComplete())\n return RESAMPLE_LINEAR;\n\n \/\/ Everything else gets resampled.\n return RESAMPLE_AWESOME;\n}\n\nvoid SkGraphicsContext::paintSkBitmap(const NativeImageSkia& bitmap,\n const SkIRect& src_rect,\n const SkRect& dest_rect,\n const SkPorterDuff::Mode& comp_op) {\n SkPaint paint;\n paint.setPorterDuffXfermode(comp_op);\n\n ResamplingMode resampling = IsPrinting() ? RESAMPLE_NONE :\n computeResamplingMode(bitmap, src_rect.width(), src_rect.height(),\n SkScalarToFloat(dest_rect.width()),\n SkScalarToFloat(dest_rect.height()));\n if (resampling == RESAMPLE_AWESOME) {\n paint.setFilterBitmap(false);\n DrawResampledBitmap(*canvas_, paint, bitmap, src_rect, dest_rect);\n } else {\n \/\/ No resampling necessary, we can just draw the bitmap.\n \/\/ Note: for serialization, we will want to subset the bitmap first so\n \/\/ we don't send extra pixels.\n paint.setFilterBitmap(resampling == RESAMPLE_LINEAR);\n canvas_->drawBitmapRect(bitmap, &src_rect, dest_rect, &paint);\n }\n}\n\nvoid SkGraphicsContext::setDashPathEffect(SkDashPathEffect *dash) {\n paint_context_->setDashPathEffect(dash);\n}\n\nvoid SkGraphicsContext::setGradient(SkShader *gradient) {\n paint_context_->setGradient(gradient);\n}\n\nvoid SkGraphicsContext::setPattern(SkShader *pattern) {\n paint_context_->setPattern(pattern);\n}\n\nconst SkBitmap* SkGraphicsContext::bitmap() const {\n return &canvas_->getDevice()->accessBitmap(false);\n}\n\ngfx::PlatformCanvas* SkGraphicsContext::canvas() const {\n return canvas_;\n}\n\nbool SkGraphicsContext::IsPrinting() {\n return canvas_->getTopPlatformDevice().IsVectorial();\n}\n<commit_msg>Update include headers for SkGraphicsContextMac.cpp<commit_after>\/\/ Copyright (c) 2008 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"config.h\"\n#include \"SkGraphicsContext.h\"\n\n#include \"base\/gfx\/platform_canvas_mac.h\"\n#include \"base\/gfx\/image_operations.h\"\n#include \"base\/gfx\/skia_utils_mac.h\"\n#include \"base\/logging.h\"\n#include \"GraphicsContextPlatformPrivate.h\"\n#include \"SkBitmap.h\"\n#include \"NativeImageSkia.h\"\n#include \"SkiaUtils.h\"\n\n\/\/ These need to be moved\n#include \"ThemeData.h\"\n\n#define kSkiaOrientation kHIThemeOrientationNormal\n\nnamespace {\n\n\/\/ Draws the given bitmap to the given canvas. The subset of the source bitmap\n\/\/ identified by src_rect is drawn to the given destination rect. The bitmap\n\/\/ will be resampled to resample_width * resample_height (this is the size of\n\/\/ the whole image, not the subset). See shouldResampleBitmap for more.\n\/\/\n\/\/ This does a lot of computation to resample only the portion of the bitmap\n\/\/ that will only be drawn. This is critical for performance since when we are\n\/\/ scrolling, for example, we are only drawing a small strip of the image.\n\/\/ Resampling the whole image every time is very slow, so this speeds up things\n\/\/ dramatically.\nvoid DrawResampledBitmap(SkCanvas& canvas,\n SkPaint& paint,\n const NativeImageSkia& bitmap,\n const SkIRect& src_irect,\n const SkRect& dest_rect) {\n \/\/ First get the subset we need. This is efficient and does not copy pixels.\n SkBitmap subset;\n bitmap.extractSubset(&subset, src_irect);\n SkRect src_rect;\n src_rect.set(src_irect);\n\n \/\/ Whether we're doing a subset or using the full source image.\n bool src_is_full = src_irect.fLeft == 0 && src_irect.fTop == 0 &&\n src_irect.width() == bitmap.width() &&\n src_irect.height() == bitmap.height();\n\n \/\/ We will always draw in integer sizes, so round the destination rect.\n SkIRect dest_rect_rounded;\n dest_rect.round(&dest_rect_rounded);\n SkIRect resized_image_rect; \/\/ Represents the size of the resized image.\n resized_image_rect.set(0, 0,\n dest_rect_rounded.width(), dest_rect_rounded.height());\n\n if (src_is_full &&\n bitmap.hasResizedBitmap(dest_rect_rounded.width(),\n dest_rect_rounded.height())) {\n \/\/ Yay, this bitmap frame already has a resized version appropriate for us.\n SkBitmap resampled = bitmap.resizedBitmap(dest_rect_rounded.width(),\n dest_rect_rounded.height());\n canvas.drawBitmapRect(resampled, NULL, dest_rect, &paint);\n return;\n }\n\n \/\/ Compute the visible portion of our rect.\n SkRect dest_bitmap_subset_sk;\n ClipRectToCanvas(canvas, dest_rect, &dest_bitmap_subset_sk);\n dest_bitmap_subset_sk.offset(-dest_rect.fLeft, -dest_rect.fTop);\n\n \/\/ The matrix inverting, etc. could have introduced rounding error which\n \/\/ causes the bounds to be outside of the resized bitmap. We round outward so\n \/\/ we always lean toward it being larger rather than smaller than we need,\n \/\/ and then clamp to the bitmap bounds so we don't get any invalid data.\n SkIRect dest_bitmap_subset_sk_i;\n dest_bitmap_subset_sk.roundOut(&dest_bitmap_subset_sk_i);\n if (!dest_bitmap_subset_sk_i.intersect(resized_image_rect))\n return; \/\/ Resized image does not intersect.\n\n if (src_is_full && bitmap.shouldCacheResampling(\n resized_image_rect.width(),\n resized_image_rect.height(),\n dest_bitmap_subset_sk_i.width(),\n dest_bitmap_subset_sk_i.height())) {\n \/\/ We're supposed to resize the entire image and cache it, even though we\n \/\/ don't need all of it.\n SkBitmap resampled = bitmap.resizedBitmap(dest_rect_rounded.width(),\n dest_rect_rounded.height());\n canvas.drawBitmapRect(resampled, NULL, dest_rect, &paint);\n } else {\n \/\/ We should only resize the exposed part of the bitmap to do the minimal\n \/\/ possible work.\n gfx::Rect dest_bitmap_subset(dest_bitmap_subset_sk_i.fLeft,\n dest_bitmap_subset_sk_i.fTop,\n dest_bitmap_subset_sk_i.width(),\n dest_bitmap_subset_sk_i.height());\n\n \/\/ Resample the needed part of the image.\n SkBitmap resampled = gfx::ImageOperations::Resize(subset,\n gfx::ImageOperations::RESIZE_LANCZOS3,\n gfx::Size(dest_rect_rounded.width(), dest_rect_rounded.height()),\n dest_bitmap_subset);\n\n \/\/ Compute where the new bitmap should be drawn. Since our new bitmap may be\n \/\/ smaller than the original, we have to shift it over by the same amount\n \/\/ that we cut off the top and left.\n SkRect offset_dest_rect = {\n dest_bitmap_subset.x() + dest_rect.fLeft,\n dest_bitmap_subset.y() + dest_rect.fTop,\n dest_bitmap_subset.right() + dest_rect.fLeft,\n dest_bitmap_subset.bottom() + dest_rect.fTop };\n\n canvas.drawBitmapRect(resampled, NULL, offset_dest_rect, &paint);\n }\n}\n\n} \/\/ namespace\n\nSkGraphicsContext::SkGraphicsContext(gfx::PlatformCanvas* canvas)\n : canvas_(canvas),\n paint_context_(NULL),\n own_canvas_(false) {\n}\n\nSkGraphicsContext::~SkGraphicsContext() {\n if (own_canvas_)\n delete canvas_;\n}\n\nconst gfx::NativeTheme* SkGraphicsContext::nativeTheme() {\n \/\/ TODO(pinkerton): fix me\n return nil;\n}\n\nvoid SkGraphicsContext::paintIcon(CGImageRef icon, const SkIRect& rect) {\n CGContextRef context = canvas_->beginPlatformPaint();\n CGRect r = gfx::SkIRectToCGRect(rect);\n CGContextDrawImage(context, r, icon);\n canvas_->endPlatformPaint();\n}\n\n\nvoid SkGraphicsContext::paintButton(const SkIRect& widgetRect,\n const ThemeData& themeData) {\n CGContextRef context = canvas_->beginPlatformPaint();\n\n int state = themeData.m_state;\n CGRect rect(gfx::SkIRectToCGRect(widgetRect));\n HIThemeButtonDrawInfo button_draw_info = { 0 };\n button_draw_info.state = state;\n CGRect label_rect;\n\n HIThemeDrawButton(&rect, &button_draw_info, context,\n kSkiaOrientation, &label_rect);\n\n canvas_->endPlatformPaint();\n}\n\nvoid SkGraphicsContext::paintTextField(const SkIRect& widgetRect,\n const ThemeData& themeData,\n SkColor c,\n bool drawEdges) {\n CGContextRef context = canvas_->beginPlatformPaint();\n\n int state = themeData.m_state;\n CGRect rect(gfx::SkIRectToCGRect(widgetRect));\n CGContextSaveGState(context);\n CGColorRef color = gfx::SkColorToCGColorRef(c);\n CGContextSetFillColorWithColor(context, color);\n CGContextFillRect(context, rect);\n CGContextSetRGBStrokeColor(context, 0.0, 0.0, 0.0, 1.0); \/\/ black border for now\n CGContextStrokeRect(context, rect);\n CGContextRestoreGState(context);\n CGColorRelease(color);\n canvas_->endPlatformPaint();\n}\n\nvoid SkGraphicsContext::paintMenuListArrowButton(const SkIRect& widgetRect,\n unsigned state,\n unsigned classic_state) {\n CGContextRef context = canvas_->beginPlatformPaint();\n\n CGRect rect(gfx::SkIRectToCGRect(widgetRect));\n HIThemePopupArrowDrawInfo arrow_draw_info = { 0 };\n arrow_draw_info.state = state;\n CGRect label_rect;\n \n HIThemeDrawPopupArrow(&rect, &arrow_draw_info, context, kSkiaOrientation);\n\n canvas_->endPlatformPaint();\n}\n\nvoid SkGraphicsContext::paintComplexText(UniscribeStateTextRun& state,\n const SkPoint& point,\n int from,\n int to,\n int ascent) {\n SkColor sk_color(paint_context_->fillColor());\n uint8 alpha = SkColorGetA(sk_color);\n \/\/ Skip 100% transparent text; no need to draw anything.\n if (!alpha)\n return;\n\n CGContextRef context = canvas_->beginPlatformPaint();\n CGContextSaveGState(context);\n CGColorRef color = gfx::SkColorToCGColorRef(sk_color);\n CGContextSetFillColorWithColor(context, color);\n\n \/\/TODO: remove use of UniscribeStateTextRun; show placeholder to test other\n \/\/ code for the moment\n CGContextShowTextAtPoint(context, point.fX, point.fY, \"complex\", 7);\n CGContextRestoreGState(context);\n CGColorRelease(color);\n canvas_->endPlatformPaint();\n}\n\nbool SkGraphicsContext::paintText(FontHandle font,\n int number_glyph,\n const uint16* chars,\n const int* advances,\n const SkPoint& origin) {\n SkColor sk_color(paint_context_->fillColor());\n uint8 alpha = SkColorGetA(sk_color);\n \/\/ Skip 100% transparent text; no need to draw anything.\n if (!alpha)\n return true;\n\n bool success = false;\n CGContextRef context = canvas_->beginPlatformPaint();\n CGContextSaveGState(context);\n CGColorRef color = gfx::SkColorToCGColorRef(sk_color);\n CGContextSetFillColorWithColor(context, color);\n CGContextMoveToPoint(context, origin.fX, origin.fY);\n CGFontRef cg_font = CTFontCopyGraphicsFont(font, NULL);\n CGContextSetFont(context, cg_font);\n\n CGSize cg_advances[number_glyph];\n CGGlyph cg_glyphs[number_glyph];\n \n CTFontGetGlyphsForCharacters(font, chars, cg_glyphs, number_glyph);\n CGContextShowGlyphsAtPoint(context, origin.fX, origin.fY,\n cg_glyphs, number_glyph);\n CGContextRestoreGState(context);\n CGColorRelease(color);\n CGFontRelease(cg_font);\n canvas_->endPlatformPaint();\n return success;\n}\n\nvoid SkGraphicsContext::paintSkPaint(const SkRect& rect,\n const SkPaint& paint) {\n canvas_->drawRect(rect, paint);\n}\n\n\/\/ Returns smallest multiple of two of the dest size that is more than a small\n\/\/ multiple larger than src_size.\n\/\/\n\/\/ Used to determine the size that source should be high-quality upsampled to,\n\/\/ after which we use linear interpolation. Making sure that the linear\n\/\/ interpolation is a factor of two reduces artifacts, and doing the lowest\n\/\/ level of resampling \nstatic int GetResamplingThreshold(int src_size, int dest_size) {\n int lower_bound = src_size * 3 \/ 2; \/\/ Minimum size we'll resample to (1.5x).\n int cur = dest_size;\n\n \/\/ Find the largest multiple of two of the destination size less than our\n \/\/ threshold\n while (cur > lower_bound)\n cur \/= 2;\n\n \/\/ We want the next size above that, or just the destination size if it's\n \/\/ smaller.\n cur *= 2;\n if (cur > dest_size)\n return dest_size;\n return cur;\n}\n\n\/\/ static\nSkGraphicsContext::ResamplingMode SkGraphicsContext::computeResamplingMode(\n const NativeImageSkia& bitmap,\n int src_width, int src_height,\n float dest_width, float dest_height) {\n int dest_iwidth = static_cast<int>(dest_width);\n int dest_iheight = static_cast<int>(dest_height);\n\n \/\/ The percent change below which we will not resample. This usually means\n \/\/ an off-by-one error on the web page, and just doing nearest neighbor\n \/\/ sampling is usually good enough.\n const float kFractionalChangeThreshold = 0.025f;\n\n \/\/ Images smaller than this in either direction are considered \"small\" and\n \/\/ are not resampled ever (see below).\n const int kSmallImageSizeThreshold = 8;\n\n \/\/ The amount an image can be stretched in a single direction before we\n \/\/ say that it is being stretched so much that it must be a line or\n \/\/ background that doesn't need resampling.\n const float kLargeStretch = 3.0f;\n\n \/\/ Figure out if we should resample this image. We try to prune out some\n \/\/ common cases where resampling won't give us anything, since it is much\n \/\/ slower than drawing stretched.\n if (src_width == dest_iwidth && src_height == dest_iheight) {\n \/\/ We don't need to resample if the source and destination are the same.\n return RESAMPLE_NONE;\n }\n \n if (src_width <= kSmallImageSizeThreshold ||\n src_height <= kSmallImageSizeThreshold ||\n dest_width <= kSmallImageSizeThreshold ||\n dest_height <= kSmallImageSizeThreshold) {\n \/\/ Never resample small images. These are often used for borders and\n \/\/ rules (think 1x1 images used to make lines).\n return RESAMPLE_NONE;\n }\n \n if (src_height * kLargeStretch <= dest_height ||\n src_width * kLargeStretch <= dest_width) {\n \/\/ Large image detected.\n\n \/\/ Don't resample if it is being stretched a lot in only one direction.\n \/\/ This is trying to catch cases where somebody has created a border\n \/\/ (which might be large) and then is stretching it to fill some part\n \/\/ of the page.\n if (src_width == dest_width || src_height == dest_height)\n return RESAMPLE_NONE;\n\n \/\/ The image is growing a lot and in more than one direction. Resampling\n \/\/ is slow and doesn't give us very much when growing a lot.\n return RESAMPLE_LINEAR;\n }\n \n if ((fabs(dest_width - src_width) \/ src_width <\n kFractionalChangeThreshold) &&\n (fabs(dest_height - src_height) \/ src_height <\n kFractionalChangeThreshold)) {\n \/\/ It is disappointingly common on the web for image sizes to be off by\n \/\/ one or two pixels. We don't bother resampling if the size difference\n \/\/ is a small fraction of the original size.\n return RESAMPLE_NONE;\n }\n\n \/\/ When the image is not yet done loading, use linear. We don't cache the\n \/\/ partially resampled images, and as they come in incrementally, it causes\n \/\/ us to have to resample the whole thing every time.\n if (!bitmap.isDataComplete())\n return RESAMPLE_LINEAR;\n\n \/\/ Everything else gets resampled.\n return RESAMPLE_AWESOME;\n}\n\nvoid SkGraphicsContext::paintSkBitmap(const NativeImageSkia& bitmap,\n const SkIRect& src_rect,\n const SkRect& dest_rect,\n const SkPorterDuff::Mode& comp_op) {\n SkPaint paint;\n paint.setPorterDuffXfermode(comp_op);\n\n ResamplingMode resampling = IsPrinting() ? RESAMPLE_NONE :\n computeResamplingMode(bitmap, src_rect.width(), src_rect.height(),\n SkScalarToFloat(dest_rect.width()),\n SkScalarToFloat(dest_rect.height()));\n if (resampling == RESAMPLE_AWESOME) {\n paint.setFilterBitmap(false);\n DrawResampledBitmap(*canvas_, paint, bitmap, src_rect, dest_rect);\n } else {\n \/\/ No resampling necessary, we can just draw the bitmap.\n \/\/ Note: for serialization, we will want to subset the bitmap first so\n \/\/ we don't send extra pixels.\n paint.setFilterBitmap(resampling == RESAMPLE_LINEAR);\n canvas_->drawBitmapRect(bitmap, &src_rect, dest_rect, &paint);\n }\n}\n\nvoid SkGraphicsContext::setDashPathEffect(SkDashPathEffect *dash) {\n paint_context_->setDashPathEffect(dash);\n}\n\nvoid SkGraphicsContext::setGradient(SkShader *gradient) {\n paint_context_->setGradient(gradient);\n}\n\nvoid SkGraphicsContext::setPattern(SkShader *pattern) {\n paint_context_->setPattern(pattern);\n}\n\nconst SkBitmap* SkGraphicsContext::bitmap() const {\n return &canvas_->getDevice()->accessBitmap(false);\n}\n\ngfx::PlatformCanvas* SkGraphicsContext::canvas() const {\n return canvas_;\n}\n\nbool SkGraphicsContext::IsPrinting() {\n return canvas_->getTopPlatformDevice().IsVectorial();\n}\n<|endoftext|>"} {"text":"<commit_before>#include <eeros\/core\/PeriodicCounter.hpp>\n#include <eeros\/logger\/Pretty.hpp>\nusing namespace eeros;\n\nPeriodicCounter::PeriodicCounter(double period, unsigned logger_category) :\n\treset_after(20), log(logger_category)\n{\n\tsetPeriod(period);\n\tstart = clk::now();\n\tfirst = true;\n}\n\nvoid PeriodicCounter::setPeriod(double period) {\n\tcounter_period = period;\n\treset();\n}\n\nvoid PeriodicCounter::setResetTime(double sec) {\n\treset_after = sec;\n}\n\nvoid PeriodicCounter::addDefaultMonitor(double tolerance) {\n\tPeriodicCounter::addDefaultMonitor(monitors, counter_period, tolerance);\n}\n\nvoid PeriodicCounter::tick() {\n\tlast = start;\n\tstart = clk::now();\n}\n\nvoid PeriodicCounter::tock() {\n\tif (first) {\n\t\tfirst = false;\n\t\treturn;\n\t}\n\n\ttime_point stop = clk::now();\n\tdouble new_period = std::chrono::duration<double>(start - last).count();\n\tdouble new_run = std::chrono::duration<double>(stop - start).count();\n\tdouble new_jitter = (new_period - counter_period);\n\t\n\tperiod.add(new_period);\n\trun.add(new_run);\n\tjitter.add(new_jitter);\n\t\n\tfor (auto &func: monitors)\n\t\tfunc(*this, log);\n\n\/*\tif (reset_counter <= 0) {\n\t\t*this >> log.trace();\n\t\treset();\n\t}\n\telse {\n\t\treset_counter--;\n\t}*\/\n}\n\nvoid PeriodicCounter::reset() {\n\tperiod.reset();\n\tjitter.reset();\n\trun.reset();\n\treset_counter = (int)(reset_after \/ counter_period);\n}\n\nvoid PeriodicCounter:: operator >> (eeros::logger::LogEntry &event) {\n\tusing namespace eeros::logger;\n\n\tauto l = [](LogEntry &e, Statistics &x) -> decltype(e) {\n\t\treturn e << pretty(x.mean) << \"\\t\" << pretty(x.variance) << \"\\t\" << pretty(x.min) << \"\\t\" << pretty(x.max);\n\t};\n\n\tevent << \"stats:\\t mean\\t variance\\t min\\t max\" << endl;\n\n\tevent << \"period\\t\";\n\tl(event, period) << endl;\n\n\tevent << \"jitter\\t\";\n\tl(event, jitter) << endl;\n\n\tevent << \"run \\t\";\n\tl(event, run) << endl;\n\n\tevent << \"count = \" << period.count;\n}\n\nvoid PeriodicCounter:: operator >> (eeros::logger::LogEntry &&event) {\n\t*this >> event;\n}\n\n\nvoid PeriodicCounter::addDefaultMonitor(std::vector<MonitorFunc> &monitors, double period, double tolerance){\n\tdouble Tmin = period * (1 - tolerance);\n\tdouble Tmax = period * (1 + tolerance);\n\n\tmonitors.push_back([Tmin, Tmax](PeriodicCounter& counter, Logger& log){\n\t\tdouble T = counter.period.last;\n\t\tif (T < Tmin || T > Tmax) {\n\t\t\tauto e = log.warn();\n\t\t\te << \"last period was \" << T << eeros::logger::endl;\n\t\t\tcounter >> e;\n\t\t}\n\t});\n\n}\n<commit_msg>Change run measurement, is now valid even after first run<commit_after>#include <eeros\/core\/PeriodicCounter.hpp>\n#include <eeros\/logger\/Pretty.hpp>\nusing namespace eeros;\n\nPeriodicCounter::PeriodicCounter(double period, unsigned logger_category) :\n\treset_after(20), log(logger_category) {\n\tsetPeriod(period);\n\tstart = clk::now();\n\tfirst = true;\n}\n\nvoid PeriodicCounter::setPeriod(double period) {\n\tcounter_period = period;\n\treset();\n}\n\nvoid PeriodicCounter::setResetTime(double sec) {\n\treset_after = sec;\n}\n\nvoid PeriodicCounter::addDefaultMonitor(double tolerance) {\n\tPeriodicCounter::addDefaultMonitor(monitors, counter_period, tolerance);\n}\n\nvoid PeriodicCounter::tick() {\n\tlast = start;\n\tstart = clk::now();\n}\n\nvoid PeriodicCounter::tock() {\n\ttime_point stop = clk::now();\n\tdouble new_run = std::chrono::duration<double>(stop - start).count();\n\trun.add(new_run);\n \n\tif (first) {\n\t\tfirst = false;\n\t\treturn;\n\t}\n\n\tdouble new_period = std::chrono::duration<double>(start - last).count();\n\tdouble new_jitter = (new_period - counter_period);\n\t\n\tperiod.add(new_period);\n\tjitter.add(new_jitter);\n\t\n\tfor (auto &func: monitors) func(*this, log);\n}\n\nvoid PeriodicCounter::reset() {\n\tperiod.reset();\n\tjitter.reset();\n\trun.reset();\n\treset_counter = (int)(reset_after \/ counter_period);\n}\n\nvoid PeriodicCounter:: operator >> (eeros::logger::LogEntry &event) {\n\tusing namespace eeros::logger;\n\n\tauto l = [](LogEntry &e, Statistics &x) -> decltype(e) {\n\t\treturn e << pretty(x.mean) << \"\\t\" << pretty(x.variance) << \"\\t\" << pretty(x.min) << \"\\t\" << pretty(x.max);\n\t};\n\n\tevent << \"stats:\\t mean\\t variance\\t min\\t max\" << endl;\n\n\tevent << \"period\\t\";\n\tl(event, period) << endl;\n\n\tevent << \"jitter\\t\";\n\tl(event, jitter) << endl;\n\n\tevent << \"run \\t\";\n\tl(event, run) << endl;\n\n\tevent << \"count = \" << period.count;\n}\n\nvoid PeriodicCounter:: operator >> (eeros::logger::LogEntry &&event) {\n\t*this >> event;\n}\n\n\nvoid PeriodicCounter::addDefaultMonitor(std::vector<MonitorFunc> &monitors, double period, double tolerance){\n\tdouble Tmin = period * (1 - tolerance);\n\tdouble Tmax = period * (1 + tolerance);\n\n\tmonitors.push_back([Tmin, Tmax](PeriodicCounter& counter, Logger& log){\n\t\tdouble T = counter.period.last;\n\t\tif (T < Tmin || T > Tmax) {\n\t\t\tauto e = log.warn();\n\t\t\te << \"last period was \" << T << eeros::logger::endl;\n\t\t\tcounter >> e;\n\t\t}\n\t});\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2014 MongoDB Inc.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#pragma once\n\n#include <bsoncxx\/config\/prelude.hpp>\n\n#include <cstddef>\n#include <cstdint>\n#include <iostream>\n#include <iterator>\n#include <type_traits>\n\n#include <bsoncxx\/document\/element.hpp>\n#include <bsoncxx\/stdx\/string_view.hpp>\n\nnamespace bsoncxx {\nBSONCXX_INLINE_NAMESPACE_BEGIN\nnamespace document {\n\n\/\/\/\n\/\/\/ A read-only, non-owning view of a BSON document.\n\/\/\/\nclass BSONCXX_API view {\n\n public:\n class iterator;\n class const_iterator;\n\n \/\/\/\n \/\/\/ @returns A const_iterator to the first element of the document.\n \/\/\/\n const_iterator cbegin() const;\n\n \/\/\/\n \/\/\/ @returns A const_iterator to the past-the-end element of the document.\n \/\/\/\n const_iterator cend() const;\n\n \/\/\/\n \/\/\/ @returns An iterator to the first element of the document.\n \/\/\/\n iterator begin() const;\n\n \/\/\/\n \/\/\/ @returns An iterator to the past-the-end element of the document.\n \/\/\/\n iterator end() const;\n\n \/\/\/\n \/\/\/ Finds the first element of the document with the provided key. If there is\n \/\/\/ no such element, the past-the-end iterator will be returned. The runtime of\n \/\/\/ find() is linear in the length of the document. This method only searches\n \/\/\/ the top-level document, and will not recurse to any subdocuments.\n \/\/\/\n \/\/\/ @remark In BSON, keys are not required to be unique. If there are multiple\n \/\/\/ elements with a matching key in the document, the first matching element from\n \/\/\/ the start will be returned.\n \/\/\/\n \/\/\/ @param key\n \/\/\/ The key to search for.\n \/\/\/\n \/\/\/ @return An iterator to the matching element, if found, or the past-the-end iterator.\n \/\/\/\n iterator find(stdx::string_view key) const;\n\n \/\/\/\n \/\/\/ Finds the first element of the document with the provided key. If there is no\n \/\/\/ such element, the invalid document::element will be returned. The runtime of operator[]\n \/\/\/ is linear in the length of the document.\n \/\/\/\n \/\/\/ @param key\n \/\/\/ The key to search for.\n \/\/\/\n \/\/\/ @return The matching element, if found, or the invalid element.\n \/\/\/\n element operator[](stdx::string_view key) const;\n\n \/\/\/\n \/\/\/ Default constructs a view. The resulting view will be initialized to point at\n \/\/\/ an empty BSON document.\n \/\/\/\n view();\n\n \/\/\/\n \/\/\/ Constructs a view from a buffer. The caller is responsible for ensuring that\n \/\/\/ the lifetime of the resulting view is a subset of the buffer's.\n \/\/\/\n \/\/\/ @param data\n \/\/\/ A buffer containing a valid BSON document.\n \/\/\/ @param length\n \/\/\/ The size of the buffer, in bytes.\n \/\/\/\n view(const std::uint8_t* data, std::size_t length);\n\n \/\/\/\n \/\/\/ Access the raw bytes of the underlying document.\n \/\/\/\n \/\/\/ @return A (non-owning) pointer to the view's buffer.\n \/\/\/\n const std::uint8_t* data() const;\n\n \/\/\/\n \/\/\/ Gets the length of the underlying buffer.\n \/\/\/\n \/\/\/ @remark This is not the number of elements in the document.\n \/\/\/ To compute the number of elements, use std::distance.\n \/\/\/\n \/\/\/ @return The length of the document, in bytes.\n \/\/\/\n std::size_t length() const;\n\n friend BSONCXX_API bool operator==(view, view);\n friend BSONCXX_API bool operator!=(view, view);\n\n private:\n const std::uint8_t* _data;\n std::size_t _length;\n};\n\nclass view::iterator : public std::iterator<std::forward_iterator_tag, element> {\n public:\n iterator();\n explicit iterator(const element& element);\n\n reference operator*();\n pointer operator->();\n\n iterator& operator++();\n iterator operator++(int);\n\n friend BSONCXX_API bool operator==(const iterator&, const iterator&);\n friend BSONCXX_API bool operator!=(const iterator&, const iterator&);\n\n private:\n element _element;\n};\n\nclass view::const_iterator : public std::iterator<std::forward_iterator_tag, element, std::ptrdiff_t,\n const element*, const element&> {\n public:\n const_iterator();\n explicit const_iterator(const element& element);\n\n reference operator*();\n pointer operator->();\n\n const_iterator& operator++();\n const_iterator operator++(int);\n\n friend BSONCXX_API bool operator==(const const_iterator&, const const_iterator&);\n friend BSONCXX_API bool operator!=(const const_iterator&, const const_iterator&);\n\n private:\n element _element;\n};\n\n} \/\/ namespace document\nBSONCXX_INLINE_NAMESPACE_END\n} \/\/ namespace bsoncxx\n\n#include <bsoncxx\/config\/postlude.hpp>\n<commit_msg>Move bson::document::view() constructor up<commit_after>\/\/ Copyright 2014 MongoDB Inc.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#pragma once\n\n#include <bsoncxx\/config\/prelude.hpp>\n\n#include <cstddef>\n#include <cstdint>\n#include <iostream>\n#include <iterator>\n#include <type_traits>\n\n#include <bsoncxx\/document\/element.hpp>\n#include <bsoncxx\/stdx\/string_view.hpp>\n\nnamespace bsoncxx {\nBSONCXX_INLINE_NAMESPACE_BEGIN\nnamespace document {\n\n\/\/\/\n\/\/\/ A read-only, non-owning view of a BSON document.\n\/\/\/\nclass BSONCXX_API view {\n\n public:\n class iterator;\n class const_iterator;\n\n \/\/\/\n \/\/\/ Default constructs a view. The resulting view will be initialized to point at\n \/\/\/ an empty BSON document.\n \/\/\/\n view();\n\n \/\/\/\n \/\/\/ Constructs a view from a buffer. The caller is responsible for ensuring that\n \/\/\/ the lifetime of the resulting view is a subset of the buffer's.\n \/\/\/\n \/\/\/ @param data\n \/\/\/ A buffer containing a valid BSON document.\n \/\/\/ @param length\n \/\/\/ The size of the buffer, in bytes.\n \/\/\/\n view(const std::uint8_t* data, std::size_t length);\n\n \/\/\/\n \/\/\/ @returns A const_iterator to the first element of the document.\n \/\/\/\n const_iterator cbegin() const;\n\n \/\/\/\n \/\/\/ @returns A const_iterator to the past-the-end element of the document.\n \/\/\/\n const_iterator cend() const;\n\n \/\/\/\n \/\/\/ @returns An iterator to the first element of the document.\n \/\/\/\n iterator begin() const;\n\n \/\/\/\n \/\/\/ @returns An iterator to the past-the-end element of the document.\n \/\/\/\n iterator end() const;\n\n \/\/\/\n \/\/\/ Finds the first element of the document with the provided key. If there is\n \/\/\/ no such element, the past-the-end iterator will be returned. The runtime of\n \/\/\/ find() is linear in the length of the document. This method only searches\n \/\/\/ the top-level document, and will not recurse to any subdocuments.\n \/\/\/\n \/\/\/ @remark In BSON, keys are not required to be unique. If there are multiple\n \/\/\/ elements with a matching key in the document, the first matching element from\n \/\/\/ the start will be returned.\n \/\/\/\n \/\/\/ @param key\n \/\/\/ The key to search for.\n \/\/\/\n \/\/\/ @return An iterator to the matching element, if found, or the past-the-end iterator.\n \/\/\/\n iterator find(stdx::string_view key) const;\n\n \/\/\/\n \/\/\/ Finds the first element of the document with the provided key. If there is no\n \/\/\/ such element, the invalid document::element will be returned. The runtime of operator[]\n \/\/\/ is linear in the length of the document.\n \/\/\/\n \/\/\/ @param key\n \/\/\/ The key to search for.\n \/\/\/\n \/\/\/ @return The matching element, if found, or the invalid element.\n \/\/\/\n element operator[](stdx::string_view key) const;\n\n \/\/\/\n \/\/\/ Access the raw bytes of the underlying document.\n \/\/\/\n \/\/\/ @return A (non-owning) pointer to the view's buffer.\n \/\/\/\n const std::uint8_t* data() const;\n\n \/\/\/\n \/\/\/ Gets the length of the underlying buffer.\n \/\/\/\n \/\/\/ @remark This is not the number of elements in the document.\n \/\/\/ To compute the number of elements, use std::distance.\n \/\/\/\n \/\/\/ @return The length of the document, in bytes.\n \/\/\/\n std::size_t length() const;\n\n friend BSONCXX_API bool operator==(view, view);\n friend BSONCXX_API bool operator!=(view, view);\n\n private:\n const std::uint8_t* _data;\n std::size_t _length;\n};\n\nclass view::iterator : public std::iterator<std::forward_iterator_tag, element> {\n public:\n iterator();\n explicit iterator(const element& element);\n\n reference operator*();\n pointer operator->();\n\n iterator& operator++();\n iterator operator++(int);\n\n friend BSONCXX_API bool operator==(const iterator&, const iterator&);\n friend BSONCXX_API bool operator!=(const iterator&, const iterator&);\n\n private:\n element _element;\n};\n\nclass view::const_iterator : public std::iterator<std::forward_iterator_tag, element, std::ptrdiff_t,\n const element*, const element&> {\n public:\n const_iterator();\n explicit const_iterator(const element& element);\n\n reference operator*();\n pointer operator->();\n\n const_iterator& operator++();\n const_iterator operator++(int);\n\n friend BSONCXX_API bool operator==(const const_iterator&, const const_iterator&);\n friend BSONCXX_API bool operator!=(const const_iterator&, const const_iterator&);\n\n private:\n element _element;\n};\n\n} \/\/ namespace document\nBSONCXX_INLINE_NAMESPACE_END\n} \/\/ namespace bsoncxx\n\n#include <bsoncxx\/config\/postlude.hpp>\n<|endoftext|>"} {"text":"<commit_before>#include \"buffer_cache\/buf_patch.hpp\"\n\n\/* For now, we have to include all buf_patches files here to allow deserialization *\/\n#include \"btree\/buf_patches.hpp\"\n\n#include <string.h>\n#include \"utils.hpp\"\n#include \"logger.hpp\"\n\npatch_deserialization_error_t::patch_deserialization_error_t(const char *file, int line, const char *msg) {\n message = strprintf(\"Patch deserialization error%s%s (in %s:%d)\",\n msg[0] ? \": \" : \"\", msg, file, line);\n}\n\nbuf_patch_t *buf_patch_t::load_patch(const char *source) {\n try {\n uint16_t remaining_length = *reinterpret_cast<const uint16_t *>(source);\n source += sizeof(remaining_length);\n if (remaining_length == 0)\n return NULL;\n remaining_length -= sizeof(remaining_length);\n guarantee_patch_format(remaining_length >= sizeof(block_id_t) + sizeof(patch_counter_t) + sizeof(patch_operation_code_t));\n block_id_t block_id = *reinterpret_cast<const block_id_t *>(source);\n source += sizeof(block_id_t);\n remaining_length -= sizeof(block_id_t);\n patch_counter_t patch_counter = *reinterpret_cast<const patch_counter_t *>(source);\n source += sizeof(patch_counter_t);\n remaining_length -= sizeof(block_id_t);\n block_sequence_id_t applies_to_block_sequence_id = *reinterpret_cast<const block_sequence_id_t *>(source);\n source += sizeof(block_sequence_id_t);\n remaining_length -= sizeof(block_sequence_id_t);\n patch_operation_code_t operation_code = *reinterpret_cast<const patch_operation_code_t *>(source);\n source += sizeof(patch_operation_code_t);\n remaining_length -= sizeof(patch_operation_code_t);\n\n buf_patch_t* result = NULL;\n switch (operation_code) {\n\tcase OPER_MEMCPY:\n\t result = new memcpy_patch_t(block_id, patch_counter, source, remaining_length); break;\n\tcase OPER_MEMMOVE:\n\t result = new memmove_patch_t(block_id, patch_counter, source, remaining_length); break;\n\tcase OPER_LEAF_INSERT:\n\t result = new leaf_insert_patch_t(block_id, patch_counter, source, remaining_length); break;\n\tcase OPER_LEAF_REMOVE:\n\t result = new leaf_remove_patch_t(block_id, patch_counter, source, remaining_length); break;\n\tcase OPER_LEAF_ERASE_PRESENCE:\n\t result = new leaf_erase_presence_patch_t(block_id, patch_counter, source, remaining_length); break;\n\tdefault:\n\t guarantee_patch_format(false, \"Unsupported patch operation code\");\n\t return NULL;\n }\n result->set_block_sequence_id(applies_to_block_sequence_id);\n return result;\n } catch (patch_deserialization_error_t &e) {\n logERR(\"%s\\n\", e.c_str());\n throw e;\n }\n}\n\nvoid buf_patch_t::serialize(char* destination) const {\n uint16_t length = get_serialized_size();\n memcpy(destination, &length, sizeof(length));\n destination += sizeof(length);\n memcpy(destination, &block_id, sizeof(block_id));\n destination += sizeof(block_id);\n memcpy(destination, &patch_counter, sizeof(patch_counter));\n destination += sizeof(patch_counter);\n memcpy(destination, &applies_to_block_sequence_id, sizeof(applies_to_block_sequence_id));\n destination += sizeof(applies_to_block_sequence_id);\n memcpy(destination, &operation_code, sizeof(operation_code));\n destination += sizeof(operation_code);\n serialize_data(destination);\n}\n\nbuf_patch_t::buf_patch_t(const block_id_t _block_id, const patch_counter_t _patch_counter, const patch_operation_code_t _operation_code) :\n block_id(_block_id),\n patch_counter(_patch_counter),\n applies_to_block_sequence_id(NULL_BLOCK_SEQUENCE_ID),\n operation_code(_operation_code) {\n}\n\nbool buf_patch_t::applies_before(const buf_patch_t *p) const {\n rassert(block_id == p->block_id, \"Tried to compare incomparable patches\");\n return applies_to_block_sequence_id < p->applies_to_block_sequence_id\n || (applies_to_block_sequence_id == p->applies_to_block_sequence_id && patch_counter < p->patch_counter);\n}\n\n\n\n\nmemcpy_patch_t::memcpy_patch_t(const block_id_t block_id, const patch_counter_t patch_counter, const uint16_t _dest_offset, const char* src, const uint16_t _n) :\n buf_patch_t(block_id, patch_counter, buf_patch_t::OPER_MEMCPY),\n dest_offset(_dest_offset),\n n(_n) {\n src_buf = new char[n];\n memcpy(src_buf, src, n);\n}\nmemcpy_patch_t::memcpy_patch_t(const block_id_t block_id, const patch_counter_t patch_counter, const char* data, const uint16_t data_length) :\n buf_patch_t(block_id, patch_counter, buf_patch_t::OPER_MEMCPY) {\n guarantee_patch_format(data_length >= sizeof(dest_offset) + sizeof(n));\n dest_offset = *reinterpret_cast<const uint16_t *>(data);\n data += sizeof(dest_offset);\n n = *reinterpret_cast<const uint16_t *>(data);\n data += sizeof(n);\n guarantee_patch_format(data_length == sizeof(dest_offset) + sizeof(n) + n);\n src_buf = new char[n];\n memcpy(src_buf, data, n);\n data += n;\n}\n\nvoid memcpy_patch_t::serialize_data(char* destination) const {\n memcpy(destination, &dest_offset, sizeof(dest_offset));\n destination += sizeof(dest_offset);\n memcpy(destination, &n, sizeof(n));\n destination += sizeof(n);\n memcpy(destination, src_buf, n);\n destination += n;\n}\nuint16_t memcpy_patch_t::get_data_size() const {\n return sizeof(dest_offset) + sizeof(n) + n;\n}\n\nmemcpy_patch_t::~memcpy_patch_t() {\n delete[] src_buf;\n}\n\nvoid memcpy_patch_t::apply_to_buf(char* buf_data, UNUSED block_size_t bs) {\n memcpy(buf_data + dest_offset, src_buf, n);\n}\n\nmemmove_patch_t::memmove_patch_t(const block_id_t block_id, const patch_counter_t patch_counter, const uint16_t _dest_offset, const uint16_t _src_offset, const uint16_t _n) :\n buf_patch_t(block_id, patch_counter, buf_patch_t::OPER_MEMMOVE),\n dest_offset(_dest_offset),\n src_offset(_src_offset),\n n(_n) { }\n\nmemmove_patch_t::memmove_patch_t(const block_id_t block_id, const patch_counter_t patch_counter, const char* data, const uint16_t data_length) :\n buf_patch_t(block_id, patch_counter, buf_patch_t::OPER_MEMMOVE) {\n guarantee_patch_format(data_length == get_data_size());\n dest_offset = *reinterpret_cast<const uint16_t *>(data);\n data += sizeof(dest_offset);\n src_offset = *reinterpret_cast<const uint16_t *>(data);\n data += sizeof(src_offset);\n n = *reinterpret_cast<const uint16_t *>(data);\n data += sizeof(n);\n}\n\nvoid memmove_patch_t::serialize_data(char* destination) const {\n memcpy(destination, &dest_offset, sizeof(dest_offset));\n destination += sizeof(dest_offset);\n memcpy(destination, &src_offset, sizeof(src_offset));\n destination += sizeof(src_offset);\n memcpy(destination, &n, sizeof(n));\n destination += sizeof(n);\n}\nuint16_t memmove_patch_t::get_data_size() const {\n return sizeof(dest_offset) + sizeof(src_offset) + sizeof(n);\n}\n\nvoid memmove_patch_t::apply_to_buf(char* buf_data, UNUSED block_size_t bs) {\n memmove(buf_data + dest_offset, buf_data + src_offset, n);\n}\n\n<commit_msg>Curly braces.<commit_after>#include \"buffer_cache\/buf_patch.hpp\"\n\n\/* For now, we have to include all buf_patches files here to allow deserialization *\/\n#include \"btree\/buf_patches.hpp\"\n\n#include <string.h>\n#include \"utils.hpp\"\n#include \"logger.hpp\"\n\npatch_deserialization_error_t::patch_deserialization_error_t(const char *file, int line, const char *msg) {\n message = strprintf(\"Patch deserialization error%s%s (in %s:%d)\",\n msg[0] ? \": \" : \"\", msg, file, line);\n}\n\nbuf_patch_t *buf_patch_t::load_patch(const char *source) {\n try {\n uint16_t remaining_length = *reinterpret_cast<const uint16_t *>(source);\n source += sizeof(remaining_length);\n if (remaining_length == 0) {\n return NULL;\n }\n remaining_length -= sizeof(remaining_length);\n guarantee_patch_format(remaining_length >= sizeof(block_id_t) + sizeof(patch_counter_t) + sizeof(patch_operation_code_t));\n block_id_t block_id = *reinterpret_cast<const block_id_t *>(source);\n source += sizeof(block_id_t);\n remaining_length -= sizeof(block_id_t);\n patch_counter_t patch_counter = *reinterpret_cast<const patch_counter_t *>(source);\n source += sizeof(patch_counter_t);\n remaining_length -= sizeof(block_id_t);\n block_sequence_id_t applies_to_block_sequence_id = *reinterpret_cast<const block_sequence_id_t *>(source);\n source += sizeof(block_sequence_id_t);\n remaining_length -= sizeof(block_sequence_id_t);\n patch_operation_code_t operation_code = *reinterpret_cast<const patch_operation_code_t *>(source);\n source += sizeof(patch_operation_code_t);\n remaining_length -= sizeof(patch_operation_code_t);\n\n buf_patch_t* result = NULL;\n switch (operation_code) {\n\tcase OPER_MEMCPY:\n\t result = new memcpy_patch_t(block_id, patch_counter, source, remaining_length); break;\n\tcase OPER_MEMMOVE:\n\t result = new memmove_patch_t(block_id, patch_counter, source, remaining_length); break;\n\tcase OPER_LEAF_INSERT:\n\t result = new leaf_insert_patch_t(block_id, patch_counter, source, remaining_length); break;\n\tcase OPER_LEAF_REMOVE:\n\t result = new leaf_remove_patch_t(block_id, patch_counter, source, remaining_length); break;\n\tcase OPER_LEAF_ERASE_PRESENCE:\n\t result = new leaf_erase_presence_patch_t(block_id, patch_counter, source, remaining_length); break;\n\tdefault:\n\t guarantee_patch_format(false, \"Unsupported patch operation code\");\n\t return NULL;\n }\n result->set_block_sequence_id(applies_to_block_sequence_id);\n return result;\n } catch (patch_deserialization_error_t &e) {\n logERR(\"%s\\n\", e.c_str());\n throw e;\n }\n}\n\nvoid buf_patch_t::serialize(char* destination) const {\n uint16_t length = get_serialized_size();\n memcpy(destination, &length, sizeof(length));\n destination += sizeof(length);\n memcpy(destination, &block_id, sizeof(block_id));\n destination += sizeof(block_id);\n memcpy(destination, &patch_counter, sizeof(patch_counter));\n destination += sizeof(patch_counter);\n memcpy(destination, &applies_to_block_sequence_id, sizeof(applies_to_block_sequence_id));\n destination += sizeof(applies_to_block_sequence_id);\n memcpy(destination, &operation_code, sizeof(operation_code));\n destination += sizeof(operation_code);\n serialize_data(destination);\n}\n\nbuf_patch_t::buf_patch_t(const block_id_t _block_id, const patch_counter_t _patch_counter, const patch_operation_code_t _operation_code) :\n block_id(_block_id),\n patch_counter(_patch_counter),\n applies_to_block_sequence_id(NULL_BLOCK_SEQUENCE_ID),\n operation_code(_operation_code) {\n}\n\nbool buf_patch_t::applies_before(const buf_patch_t *p) const {\n rassert(block_id == p->block_id, \"Tried to compare incomparable patches\");\n return applies_to_block_sequence_id < p->applies_to_block_sequence_id\n || (applies_to_block_sequence_id == p->applies_to_block_sequence_id && patch_counter < p->patch_counter);\n}\n\n\n\n\nmemcpy_patch_t::memcpy_patch_t(const block_id_t block_id, const patch_counter_t patch_counter, const uint16_t _dest_offset, const char* src, const uint16_t _n) :\n buf_patch_t(block_id, patch_counter, buf_patch_t::OPER_MEMCPY),\n dest_offset(_dest_offset),\n n(_n) {\n src_buf = new char[n];\n memcpy(src_buf, src, n);\n}\nmemcpy_patch_t::memcpy_patch_t(const block_id_t block_id, const patch_counter_t patch_counter, const char* data, const uint16_t data_length) :\n buf_patch_t(block_id, patch_counter, buf_patch_t::OPER_MEMCPY) {\n guarantee_patch_format(data_length >= sizeof(dest_offset) + sizeof(n));\n dest_offset = *reinterpret_cast<const uint16_t *>(data);\n data += sizeof(dest_offset);\n n = *reinterpret_cast<const uint16_t *>(data);\n data += sizeof(n);\n guarantee_patch_format(data_length == sizeof(dest_offset) + sizeof(n) + n);\n src_buf = new char[n];\n memcpy(src_buf, data, n);\n data += n;\n}\n\nvoid memcpy_patch_t::serialize_data(char* destination) const {\n memcpy(destination, &dest_offset, sizeof(dest_offset));\n destination += sizeof(dest_offset);\n memcpy(destination, &n, sizeof(n));\n destination += sizeof(n);\n memcpy(destination, src_buf, n);\n destination += n;\n}\nuint16_t memcpy_patch_t::get_data_size() const {\n return sizeof(dest_offset) + sizeof(n) + n;\n}\n\nmemcpy_patch_t::~memcpy_patch_t() {\n delete[] src_buf;\n}\n\nvoid memcpy_patch_t::apply_to_buf(char* buf_data, UNUSED block_size_t bs) {\n memcpy(buf_data + dest_offset, src_buf, n);\n}\n\nmemmove_patch_t::memmove_patch_t(const block_id_t block_id, const patch_counter_t patch_counter, const uint16_t _dest_offset, const uint16_t _src_offset, const uint16_t _n) :\n buf_patch_t(block_id, patch_counter, buf_patch_t::OPER_MEMMOVE),\n dest_offset(_dest_offset),\n src_offset(_src_offset),\n n(_n) { }\n\nmemmove_patch_t::memmove_patch_t(const block_id_t block_id, const patch_counter_t patch_counter, const char* data, const uint16_t data_length) :\n buf_patch_t(block_id, patch_counter, buf_patch_t::OPER_MEMMOVE) {\n guarantee_patch_format(data_length == get_data_size());\n dest_offset = *reinterpret_cast<const uint16_t *>(data);\n data += sizeof(dest_offset);\n src_offset = *reinterpret_cast<const uint16_t *>(data);\n data += sizeof(src_offset);\n n = *reinterpret_cast<const uint16_t *>(data);\n data += sizeof(n);\n}\n\nvoid memmove_patch_t::serialize_data(char* destination) const {\n memcpy(destination, &dest_offset, sizeof(dest_offset));\n destination += sizeof(dest_offset);\n memcpy(destination, &src_offset, sizeof(src_offset));\n destination += sizeof(src_offset);\n memcpy(destination, &n, sizeof(n));\n destination += sizeof(n);\n}\nuint16_t memmove_patch_t::get_data_size() const {\n return sizeof(dest_offset) + sizeof(src_offset) + sizeof(n);\n}\n\nvoid memmove_patch_t::apply_to_buf(char* buf_data, UNUSED block_size_t bs) {\n memmove(buf_data + dest_offset, buf_data + src_offset, n);\n}\n\n<|endoftext|>"} {"text":"<commit_before>#pragma once\n\n#include <vector>\n#include <math.h>\n#include <iostream>\n\n#include \"angle.hpp\"\n#include \"global_config.hpp\"\n#include \"error.hpp\"\n\nusing namespace mocc;\n\n\/\/ Hide all of these constants from the rest of the world\nnamespace {\n real_t mu_base[] = {0.577350269189626, 0.350021000000000,\n 0.266636000000000, 0.218218218218218, 0.192450089729876,\n 0.174077655955702, 0.161575000000000, 0.149071198499989};\n\n real_t w_unique[] = {\n 1.0,\n 1.0\/3.0,\n 0.1761262, 0.1572071,\n 0.1209876, 0.0907408, 0.0925925,\n 0.0893043, 0.0725281, 0.0450455, 0.0539274,\n 0.0707734, 0.0558760, 0.0373436, 0.0502654, 0.0258553,\n 0.0580031, 0.0488943, 0.0228095, 0.0393955, 0.0380920, 0.0258382, 0.0082759,\n 0.0489967, 0.0413235, 0.0203158, 0.0265468, 0.0378883, 0.0135404, 0.0326129, 0.0103825\n };\n\n int w_offset[] = {0, 1, 2, 4, 7, 11, 16, 23};\n\n int w_map[] = {\n 1,\n 1, 1, 1,\n 1, 2, 2, 1, 2, 1,\n 1, 2, 2, 2, 3, 2, 1, 2, 2, 1,\n 1, 2, 2, 3, 4, 3, 2, 4, 4, 2, 1, 2, 3, 2, 1,\n 1, 2, 2, 3, 5, 3, 4, 6, 6, 4, 3, 6, 7, 6, 3, 2, 5, 6, 6, 5, 2, 1, 2, 3, 4, 3, 2, 1,\n 1, 2, 2, 3, 5, 3, 4, 6, 6, 4, 4, 7, 8, 7, 4, 3, 6, 8, 8, 6, 3, 2, 5, 6, 7, 6, 5, 2, 1, 2, 3, 4, 4, 3, 2, 1\n };\n\n int w_map_offset[] = { 0, 1, 4, 10, 20, 35, 63 };\n}\n\n\n\n\/\/ Produce a vector of angles matching the level-symmetric quadrature of order\n\/\/ 'order'\nstd::vector<Angle> GenSn( int order ){\n\n if( order%2 != 0 ) {\n throw EXCEPT(\"Sn quadrature order must be even.\");\n }\n if( order > 16 ) {\n throw EXCEPT(\"Max supported Sn quadrature order is 16.\");\n }\n\n \/\/ n is the number of base cosines to use\n const int n = order\/2;\n\n \/\/ set up the list of base cosines\n VecF mu;\n mu.push_back(mu_base[n-1]);\n if( order > 2) {\n const real_t delta_mu = 2.0 * ( 1.0 -\n 3.0*(mu[0]*mu[0]) ) \/ (real_t)(order-2);\n for (int i=1; i<n; i++) {\n mu.push_back( sqrt(mu[0]*mu[0] + i*delta_mu) );\n }\n }\n\n \/\/ Alias the w_unique array to get a slice for the order we are interested\n \/\/ in.\n real_t* weights = &w_unique[w_offset[n-1]];\n \/\/ Alias into the w_map to get our indices\n int* map = &w_map[w_map_offset[n-1]];\n\n \/\/ Apply the permutations of the base cosines to get actual angles. We will\n \/\/ do this once for the first octant, then reflect around.\n std::vector<Angle> angles;\n real_t wsum = 0.0;\n int k=0;\n for( int i=0; i<n; i++ ) {\n for( int j=0; j<=i; j++ ) {\n Angle angle( mu[i-j],\n mu[j],\n mu[n-i-1],\n weights[map[k]-1]);\n\n angles.push_back(angle);\n wsum += angle.weight;\n k++;\n }\n }\n\n \/\/ One of these days, i should calculate the weights algorithmically, rather\n \/\/ than storing in a table. For now, make sure the angular integral comes\n \/\/ out to 4*PI. We defined the angles above for one octant, so make sure\n \/\/ that the weights sum to 1 to machine precision.\n for( auto &a: angles ) {\n a.weight \/= wsum;\n }\n\n return angles;\n\n}\n<commit_msg>added Yamamoto quad set<commit_after>#pragma once\n\n#include <vector>\n#include <math.h>\n#include <iostream>\n\n#include \"angle.hpp\"\n#include \"global_config.hpp\"\n#include \"error.hpp\"\n\nusing namespace mocc;\n\n\/\/ Hide all of these constants from the rest of the world\nnamespace {\n real_t mu_base[] = {0.577350269189626, 0.350021000000000,\n 0.266636000000000, 0.218218218218218, 0.192450089729876,\n 0.174077655955702, 0.161575000000000, 0.149071198499989};\n\n real_t w_unique[] = {\n 1.0,\n 1.0\/3.0,\n 0.1761262, 0.1572071,\n 0.1209876, 0.0907408, 0.0925925,\n 0.0893043, 0.0725281, 0.0450455, 0.0539274,\n 0.0707734, 0.0558760, 0.0373436, 0.0502654, 0.0258553,\n 0.0580031, 0.0488943, 0.0228095, 0.0393955, 0.0380920, 0.0258382, 0.0082759,\n 0.0489967, 0.0413235, 0.0203158, 0.0265468, 0.0378883, 0.0135404, 0.0326129, 0.0103825\n };\n\n int w_offset[] = {0, 1, 2, 4, 7, 11, 16, 23};\n\n int w_map[] = {\n 1,\n 1, 1, 1,\n 1, 2, 2, 1, 2, 1,\n 1, 2, 2, 2, 3, 2, 1, 2, 2, 1,\n 1, 2, 2, 3, 4, 3, 2, 4, 4, 2, 1, 2, 3, 2, 1,\n 1, 2, 2, 3, 5, 3, 4, 6, 6, 4, 3, 6, 7, 6, 3, 2, 5, 6, 6, 5, 2, 1, 2, 3, 4, 3, 2, 1,\n 1, 2, 2, 3, 5, 3, 4, 6, 6, 4, 4, 7, 8, 7, 4, 3, 6, 8, 8, 6, 3, 2, 5, 6, 7, 6, 5, 2, 1, 2, 3, 4, 4, 3, 2, 1\n };\n\n int w_map_offset[] = { 0, 1, 4, 10, 20, 35, 63 };\n}\n\n\n\n\/\/ Produce a vector of angles matching the level-symmetric quadrature of order\n\/\/ 'order'\nstd::vector<Angle> GenSn( int order ){\n\n if( order%2 != 0 ) {\n throw EXCEPT(\"Sn quadrature order must be even.\");\n }\n if( order > 16 ) {\n throw EXCEPT(\"Max supported Sn quadrature order is 16.\");\n }\n\n \/\/ n is the number of base cosines to use\n const int n = order\/2;\n\n \/\/ set up the list of base cosines\n VecF mu;\n mu.push_back(mu_base[n-1]);\n if( order > 2) {\n const real_t delta_mu = 2.0 * ( 1.0 -\n 3.0*(mu[0]*mu[0]) ) \/ (real_t)(order-2);\n for (int i=1; i<n; i++) {\n mu.push_back( sqrt(mu[0]*mu[0] + i*delta_mu) );\n }\n }\n\n \/\/ Alias the w_unique array to get a slice for the order we are interested\n \/\/ in.\n real_t* weights = &w_unique[w_offset[n-1]];\n \/\/ Alias into the w_map to get our indices\n int* map = &w_map[w_map_offset[n-1]];\n\n \/\/ Apply the permutations of the base cosines to get actual angles. We will\n \/\/ do this once for the first octant, then reflect around.\n std::vector<Angle> angles;\n real_t wsum = 0.0;\n int k=0;\n for( int i=0; i<n; i++ ) {\n for( int j=0; j<=i; j++ ) {\n Angle angle( mu[i-j],\n mu[j],\n mu[n-i-1],\n weights[map[k]-1]);\n\n angles.push_back(angle);\n wsum += angle.weight;\n k++;\n }\n }\n\n \/\/ One of these days, i should calculate the weights algorithmically, rather\n \/\/ than storing in a table. For now, make sure the angular integral comes\n \/\/ out to 4*PI. We defined the angles above for one octant, so make sure\n \/\/ that the weights sum to 1 to machine precision.\n for( auto &a: angles ) {\n a.weight \/= wsum;\n }\n\n return angles;\n\n}\n\n\/\/ Produce a vector of pairs for Yamamoto quadrature set of order 'order'.\n\/\/ Currently, only order 3 is supported. The first value in the pair is theta in\n\/\/ range (0, PI\/2) and the second value is the corresponding weight. All weights\n\/\/ sum to 1.\nvector<pair<real_t,real_t>> genYamamoto( int order){\n\n vector<pair<real_t,real_t>> thetaWeightPairVec;\n if ( order != 3 ) {\n throw EXCEPT(\"Only support Yamamoto quadrature of order 3\");\n }\n thetaWeightPairVec.emplace_back(0.167429147795000,4.623300000000000E-002);\n thetaWeightPairVec.emplace_back(0.567715121084000,0.283619000000000);\n thetaWeightPairVec.emplace_back(1.20253314678900,0.670148000000000);\n}\n\n\n\/\/ Produce a vector of angles matching the Chebyshev-Gaussian quadrature of\n\/\/ order 'azi-order' for azimuthal angles and 'polar-order' for polar\n\/\/ angles.\nstd::vector<Angle> GenCG( int azi_order, int polar_order ){\n \n}\n\n\n\/\/ Produce a vector of angles matching the Chebyshev-Yamamoto quadrature of\n\/\/ order 'azimuthal-order' for azimuthal angles and 'polar-order' for polar\n\/\/ angles. \n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 2016, The OpenThread Authors.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution.\n * 3. Neither the name of the copyright holder nor the\n * names of its contributors may be used to endorse or promote products\n * derived from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n\/**\n * @file\n * This file implements IPv6 addresses.\n *\/\n\n#include \"ip6_address.hpp\"\n\n#include <stdio.h>\n\n#include \"common\/code_utils.hpp\"\n#include \"common\/encoding.hpp\"\n#include \"common\/instance.hpp\"\n\nusing ot::Encoding::BigEndian::HostSwap16;\nusing ot::Encoding::BigEndian::HostSwap32;\n\nnamespace ot {\nnamespace Ip6 {\n\nvoid Address::Clear(void)\n{\n memset(mFields.m8, 0, sizeof(mFields));\n}\n\nbool Address::IsUnspecified(void) const\n{\n return (mFields.m32[0] == 0 && mFields.m32[1] == 0 && mFields.m32[2] == 0 && mFields.m32[3] == 0);\n}\n\nbool Address::IsLoopback(void) const\n{\n return (mFields.m32[0] == 0 && mFields.m32[1] == 0 && mFields.m32[2] == 0 && mFields.m32[3] == HostSwap32(1));\n}\n\nbool Address::IsLinkLocal(void) const\n{\n return (mFields.m16[0] & HostSwap16(0xffc0)) == HostSwap16(0xfe80);\n}\n\nbool Address::IsMulticast(void) const\n{\n return mFields.m8[0] == 0xff;\n}\n\nbool Address::IsLinkLocalMulticast(void) const\n{\n return IsMulticast() && (GetScope() == kLinkLocalScope);\n}\n\nbool Address::IsLinkLocalAllNodesMulticast(void) const\n{\n return (mFields.m32[0] == HostSwap32(0xff020000) && mFields.m32[1] == 0 && mFields.m32[2] == 0 &&\n mFields.m32[3] == HostSwap32(0x01));\n}\n\nbool Address::IsLinkLocalAllRoutersMulticast(void) const\n{\n return (mFields.m32[0] == HostSwap32(0xff020000) && mFields.m32[1] == 0 && mFields.m32[2] == 0 &&\n mFields.m32[3] == HostSwap32(0x02));\n}\n\nbool Address::IsRealmLocalMulticast(void) const\n{\n return IsMulticast() && (GetScope() == kRealmLocalScope);\n}\n\nbool Address::IsMulticastLargerThanRealmLocal(void) const\n{\n return IsMulticast() && (GetScope() > kRealmLocalScope);\n}\n\nbool Address::IsRealmLocalAllNodesMulticast(void) const\n{\n return (mFields.m32[0] == HostSwap32(0xff030000) && mFields.m32[1] == 0 && mFields.m32[2] == 0 &&\n mFields.m32[3] == HostSwap32(0x01));\n}\n\nbool Address::IsRealmLocalAllRoutersMulticast(void) const\n{\n return (mFields.m32[0] == HostSwap32(0xff030000) && mFields.m32[1] == 0 && mFields.m32[2] == 0 &&\n mFields.m32[3] == HostSwap32(0x02));\n}\n\nbool Address::IsRealmLocalAllMplForwarders(void) const\n{\n return (mFields.m32[0] == HostSwap32(0xff030000) && mFields.m32[1] == 0 && mFields.m32[2] == 0 &&\n mFields.m32[3] == HostSwap32(0xfc));\n}\n\nbool Address::IsRoutingLocator(void) const\n{\n return (mFields.m32[2] == HostSwap32(0x000000ff) && mFields.m16[6] == HostSwap16(0xfe00) &&\n mFields.m8[14] < kAloc16Mask && (mFields.m8[14] & kRloc16ReservedBitMask) == 0);\n}\n\nbool Address::IsAnycastRoutingLocator(void) const\n{\n return (mFields.m32[2] == HostSwap32(0x000000ff) && mFields.m16[6] == HostSwap16(0xfe00) &&\n mFields.m8[14] == kAloc16Mask);\n}\n\nbool Address::IsAnycastServiceLocator(void) const\n{\n return IsAnycastRoutingLocator() && (mFields.m16[7] >= HostSwap16(Mle::kAloc16ServiceStart)) &&\n (mFields.m16[7] <= HostSwap16(Mle::kAloc16ServiceEnd));\n}\n\nbool Address::IsSubnetRouterAnycast(void) const\n{\n return (mFields.m32[2] == 0 && mFields.m32[3] == 0);\n}\n\nbool Address::IsReservedSubnetAnycast(void) const\n{\n return (mFields.m32[2] == HostSwap32(0xfdffffff) && mFields.m16[6] == 0xffff && mFields.m8[14] == 0xff &&\n mFields.m8[15] >= 0x80);\n}\n\nbool Address::IsIidReserved(void) const\n{\n return IsSubnetRouterAnycast() || IsReservedSubnetAnycast() || IsAnycastRoutingLocator();\n}\n\nconst uint8_t *Address::GetIid(void) const\n{\n return mFields.m8 + kInterfaceIdentifierOffset;\n}\n\nuint8_t *Address::GetIid(void)\n{\n return mFields.m8 + kInterfaceIdentifierOffset;\n}\n\nvoid Address::SetIid(const uint8_t *aIid)\n{\n memcpy(mFields.m8 + kInterfaceIdentifierOffset, aIid, kInterfaceIdentifierSize);\n}\n\nvoid Address::SetIid(const Mac::ExtAddress &aExtAddress)\n{\n Mac::ExtAddress addr;\n\n addr = aExtAddress;\n addr.ToggleLocal();\n addr.CopyTo(mFields.m8 + kInterfaceIdentifierOffset);\n}\n\nvoid Address::ToExtAddress(Mac::ExtAddress &aExtAddress) const\n{\n aExtAddress.Set(mFields.m8 + kInterfaceIdentifierOffset);\n aExtAddress.ToggleLocal();\n}\n\nvoid Address::ToExtAddress(Mac::Address &aMacAddress) const\n{\n aMacAddress.SetExtended(mFields.m8 + kInterfaceIdentifierOffset);\n aMacAddress.GetExtended().ToggleLocal();\n}\n\nuint8_t Address::GetScope(void) const\n{\n uint8_t rval;\n\n if (IsMulticast())\n {\n rval = mFields.m8[1] & 0xf;\n }\n else if (IsLinkLocal())\n {\n rval = kLinkLocalScope;\n }\n else if (IsLoopback())\n {\n rval = kNodeLocalScope;\n }\n else\n {\n rval = kGlobalScope;\n }\n\n return rval;\n}\n\nuint8_t Address::PrefixMatch(const uint8_t *aPrefixA, const uint8_t *aPrefixB, uint8_t aMaxLength)\n{\n uint8_t rval = 0;\n uint8_t diff;\n\n if (aMaxLength > sizeof(Address))\n {\n aMaxLength = sizeof(Address);\n }\n\n for (uint8_t i = 0; i < aMaxLength; i++)\n {\n diff = aPrefixA[i] ^ aPrefixB[i];\n\n if (diff == 0)\n {\n rval += 8;\n }\n else\n {\n while ((diff & 0x80) == 0)\n {\n rval++;\n diff <<= 1;\n }\n\n break;\n }\n }\n\n return rval;\n}\n\nuint8_t Address::PrefixMatch(const otIp6Address &aOther) const\n{\n return PrefixMatch(mFields.m8, aOther.mFields.m8, sizeof(Address));\n}\n\nbool Address::operator==(const Address &aOther) const\n{\n return memcmp(mFields.m8, aOther.mFields.m8, sizeof(mFields.m8)) == 0;\n}\n\notError Address::FromString(const char *aBuf)\n{\n otError error = OT_ERROR_NONE;\n uint8_t * dst = reinterpret_cast<uint8_t *>(mFields.m8);\n uint8_t * endp = reinterpret_cast<uint8_t *>(mFields.m8 + 15);\n uint8_t * colonp = NULL;\n const char *colonc = NULL;\n uint16_t val = 0;\n uint8_t count = 0;\n bool first = true;\n bool hasIp4 = false;\n char ch;\n uint8_t d;\n\n Clear();\n\n dst--;\n\n for (;;)\n {\n ch = *aBuf++;\n d = ch & 0xf;\n\n if (('a' <= ch && ch <= 'f') || ('A' <= ch && ch <= 'F'))\n {\n d += 9;\n }\n else if (ch == ':' || ch == '\\0' || ch == ' ')\n {\n if (count)\n {\n VerifyOrExit(dst + 2 <= endp, error = OT_ERROR_PARSE);\n *(dst + 1) = static_cast<uint8_t>(val >> 8);\n *(dst + 2) = static_cast<uint8_t>(val);\n dst += 2;\n count = 0;\n val = 0;\n }\n else if (ch == ':')\n {\n VerifyOrExit(colonp == NULL || first, error = OT_ERROR_PARSE);\n colonp = dst;\n }\n\n if (ch == '\\0' || ch == ' ')\n {\n break;\n }\n\n colonc = aBuf;\n\n continue;\n }\n else if (ch == '.')\n {\n hasIp4 = true;\n\n \/\/ Do not count bytes of the embedded IPv4 address.\n endp -= kIp4AddressSize;\n\n VerifyOrExit(dst <= endp, error = OT_ERROR_PARSE);\n\n break;\n }\n else\n {\n VerifyOrExit('0' <= ch && ch <= '9', error = OT_ERROR_PARSE);\n }\n\n first = false;\n val = static_cast<uint16_t>((val << 4) | d);\n VerifyOrExit(++count <= 4, error = OT_ERROR_PARSE);\n }\n\n VerifyOrExit(colonp || dst == endp, error = OT_ERROR_PARSE);\n\n while (colonp && dst > colonp)\n {\n *endp-- = *dst--;\n }\n\n while (endp > dst)\n {\n *endp-- = 0;\n }\n\n if (hasIp4)\n {\n val = 0;\n\n \/\/ Reset the start and end pointers.\n dst = reinterpret_cast<uint8_t *>(mFields.m8 + 12);\n endp = reinterpret_cast<uint8_t *>(mFields.m8 + 15);\n\n for (;;)\n {\n ch = *colonc++;\n\n if (ch == '.' || ch == '\\0' || ch == ' ')\n {\n VerifyOrExit(dst <= endp, error = OT_ERROR_PARSE);\n\n *dst++ = static_cast<uint8_t>(val);\n val = 0;\n\n if (ch == '\\0' || ch == ' ')\n {\n \/\/ Check if embedded IPv4 address had exactly four parts.\n VerifyOrExit(dst == endp + 1, error = OT_ERROR_PARSE);\n break;\n }\n }\n else\n {\n VerifyOrExit('0' <= ch && ch <= '9', error = OT_ERROR_PARSE);\n\n val = (10 * val) + (ch & 0xf);\n\n \/\/ Single part of IPv4 address has to fit in one byte.\n VerifyOrExit(val <= 0xff, error = OT_ERROR_PARSE);\n }\n }\n }\n\nexit:\n return error;\n}\n\nAddress::InfoString Address::ToString(void) const\n{\n return InfoString(\"%x:%x:%x:%x:%x:%x:%x:%x\", HostSwap16(mFields.m16[0]), HostSwap16(mFields.m16[1]),\n HostSwap16(mFields.m16[2]), HostSwap16(mFields.m16[3]), HostSwap16(mFields.m16[4]),\n HostSwap16(mFields.m16[5]), HostSwap16(mFields.m16[6]), HostSwap16(mFields.m16[7]));\n}\n\n} \/\/ namespace Ip6\n} \/\/ namespace ot\n<commit_msg>[ip6-address] simplify IsAnycastServiceLocator() (#4519)<commit_after>\/*\n * Copyright (c) 2016, The OpenThread Authors.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution.\n * 3. Neither the name of the copyright holder nor the\n * names of its contributors may be used to endorse or promote products\n * derived from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n\/**\n * @file\n * This file implements IPv6 addresses.\n *\/\n\n#include \"ip6_address.hpp\"\n\n#include <stdio.h>\n\n#include \"common\/code_utils.hpp\"\n#include \"common\/encoding.hpp\"\n#include \"common\/instance.hpp\"\n\nusing ot::Encoding::BigEndian::HostSwap16;\nusing ot::Encoding::BigEndian::HostSwap32;\n\nnamespace ot {\nnamespace Ip6 {\n\nvoid Address::Clear(void)\n{\n memset(mFields.m8, 0, sizeof(mFields));\n}\n\nbool Address::IsUnspecified(void) const\n{\n return (mFields.m32[0] == 0 && mFields.m32[1] == 0 && mFields.m32[2] == 0 && mFields.m32[3] == 0);\n}\n\nbool Address::IsLoopback(void) const\n{\n return (mFields.m32[0] == 0 && mFields.m32[1] == 0 && mFields.m32[2] == 0 && mFields.m32[3] == HostSwap32(1));\n}\n\nbool Address::IsLinkLocal(void) const\n{\n return (mFields.m16[0] & HostSwap16(0xffc0)) == HostSwap16(0xfe80);\n}\n\nbool Address::IsMulticast(void) const\n{\n return mFields.m8[0] == 0xff;\n}\n\nbool Address::IsLinkLocalMulticast(void) const\n{\n return IsMulticast() && (GetScope() == kLinkLocalScope);\n}\n\nbool Address::IsLinkLocalAllNodesMulticast(void) const\n{\n return (mFields.m32[0] == HostSwap32(0xff020000) && mFields.m32[1] == 0 && mFields.m32[2] == 0 &&\n mFields.m32[3] == HostSwap32(0x01));\n}\n\nbool Address::IsLinkLocalAllRoutersMulticast(void) const\n{\n return (mFields.m32[0] == HostSwap32(0xff020000) && mFields.m32[1] == 0 && mFields.m32[2] == 0 &&\n mFields.m32[3] == HostSwap32(0x02));\n}\n\nbool Address::IsRealmLocalMulticast(void) const\n{\n return IsMulticast() && (GetScope() == kRealmLocalScope);\n}\n\nbool Address::IsMulticastLargerThanRealmLocal(void) const\n{\n return IsMulticast() && (GetScope() > kRealmLocalScope);\n}\n\nbool Address::IsRealmLocalAllNodesMulticast(void) const\n{\n return (mFields.m32[0] == HostSwap32(0xff030000) && mFields.m32[1] == 0 && mFields.m32[2] == 0 &&\n mFields.m32[3] == HostSwap32(0x01));\n}\n\nbool Address::IsRealmLocalAllRoutersMulticast(void) const\n{\n return (mFields.m32[0] == HostSwap32(0xff030000) && mFields.m32[1] == 0 && mFields.m32[2] == 0 &&\n mFields.m32[3] == HostSwap32(0x02));\n}\n\nbool Address::IsRealmLocalAllMplForwarders(void) const\n{\n return (mFields.m32[0] == HostSwap32(0xff030000) && mFields.m32[1] == 0 && mFields.m32[2] == 0 &&\n mFields.m32[3] == HostSwap32(0xfc));\n}\n\nbool Address::IsRoutingLocator(void) const\n{\n return (mFields.m32[2] == HostSwap32(0x000000ff) && mFields.m16[6] == HostSwap16(0xfe00) &&\n mFields.m8[14] < kAloc16Mask && (mFields.m8[14] & kRloc16ReservedBitMask) == 0);\n}\n\nbool Address::IsAnycastRoutingLocator(void) const\n{\n return (mFields.m32[2] == HostSwap32(0x000000ff) && mFields.m16[6] == HostSwap16(0xfe00) &&\n mFields.m8[14] == kAloc16Mask);\n}\n\nbool Address::IsAnycastServiceLocator(void) const\n{\n return IsAnycastRoutingLocator() && (mFields.m8[15] >= (Mle::kAloc16ServiceStart & 0xff)) &&\n (mFields.m8[15] <= (Mle::kAloc16ServiceEnd & 0xff));\n}\n\nbool Address::IsSubnetRouterAnycast(void) const\n{\n return (mFields.m32[2] == 0 && mFields.m32[3] == 0);\n}\n\nbool Address::IsReservedSubnetAnycast(void) const\n{\n return (mFields.m32[2] == HostSwap32(0xfdffffff) && mFields.m16[6] == 0xffff && mFields.m8[14] == 0xff &&\n mFields.m8[15] >= 0x80);\n}\n\nbool Address::IsIidReserved(void) const\n{\n return IsSubnetRouterAnycast() || IsReservedSubnetAnycast() || IsAnycastRoutingLocator();\n}\n\nconst uint8_t *Address::GetIid(void) const\n{\n return mFields.m8 + kInterfaceIdentifierOffset;\n}\n\nuint8_t *Address::GetIid(void)\n{\n return mFields.m8 + kInterfaceIdentifierOffset;\n}\n\nvoid Address::SetIid(const uint8_t *aIid)\n{\n memcpy(mFields.m8 + kInterfaceIdentifierOffset, aIid, kInterfaceIdentifierSize);\n}\n\nvoid Address::SetIid(const Mac::ExtAddress &aExtAddress)\n{\n Mac::ExtAddress addr;\n\n addr = aExtAddress;\n addr.ToggleLocal();\n addr.CopyTo(mFields.m8 + kInterfaceIdentifierOffset);\n}\n\nvoid Address::ToExtAddress(Mac::ExtAddress &aExtAddress) const\n{\n aExtAddress.Set(mFields.m8 + kInterfaceIdentifierOffset);\n aExtAddress.ToggleLocal();\n}\n\nvoid Address::ToExtAddress(Mac::Address &aMacAddress) const\n{\n aMacAddress.SetExtended(mFields.m8 + kInterfaceIdentifierOffset);\n aMacAddress.GetExtended().ToggleLocal();\n}\n\nuint8_t Address::GetScope(void) const\n{\n uint8_t rval;\n\n if (IsMulticast())\n {\n rval = mFields.m8[1] & 0xf;\n }\n else if (IsLinkLocal())\n {\n rval = kLinkLocalScope;\n }\n else if (IsLoopback())\n {\n rval = kNodeLocalScope;\n }\n else\n {\n rval = kGlobalScope;\n }\n\n return rval;\n}\n\nuint8_t Address::PrefixMatch(const uint8_t *aPrefixA, const uint8_t *aPrefixB, uint8_t aMaxLength)\n{\n uint8_t rval = 0;\n uint8_t diff;\n\n if (aMaxLength > sizeof(Address))\n {\n aMaxLength = sizeof(Address);\n }\n\n for (uint8_t i = 0; i < aMaxLength; i++)\n {\n diff = aPrefixA[i] ^ aPrefixB[i];\n\n if (diff == 0)\n {\n rval += 8;\n }\n else\n {\n while ((diff & 0x80) == 0)\n {\n rval++;\n diff <<= 1;\n }\n\n break;\n }\n }\n\n return rval;\n}\n\nuint8_t Address::PrefixMatch(const otIp6Address &aOther) const\n{\n return PrefixMatch(mFields.m8, aOther.mFields.m8, sizeof(Address));\n}\n\nbool Address::operator==(const Address &aOther) const\n{\n return memcmp(mFields.m8, aOther.mFields.m8, sizeof(mFields.m8)) == 0;\n}\n\notError Address::FromString(const char *aBuf)\n{\n otError error = OT_ERROR_NONE;\n uint8_t * dst = reinterpret_cast<uint8_t *>(mFields.m8);\n uint8_t * endp = reinterpret_cast<uint8_t *>(mFields.m8 + 15);\n uint8_t * colonp = NULL;\n const char *colonc = NULL;\n uint16_t val = 0;\n uint8_t count = 0;\n bool first = true;\n bool hasIp4 = false;\n char ch;\n uint8_t d;\n\n Clear();\n\n dst--;\n\n for (;;)\n {\n ch = *aBuf++;\n d = ch & 0xf;\n\n if (('a' <= ch && ch <= 'f') || ('A' <= ch && ch <= 'F'))\n {\n d += 9;\n }\n else if (ch == ':' || ch == '\\0' || ch == ' ')\n {\n if (count)\n {\n VerifyOrExit(dst + 2 <= endp, error = OT_ERROR_PARSE);\n *(dst + 1) = static_cast<uint8_t>(val >> 8);\n *(dst + 2) = static_cast<uint8_t>(val);\n dst += 2;\n count = 0;\n val = 0;\n }\n else if (ch == ':')\n {\n VerifyOrExit(colonp == NULL || first, error = OT_ERROR_PARSE);\n colonp = dst;\n }\n\n if (ch == '\\0' || ch == ' ')\n {\n break;\n }\n\n colonc = aBuf;\n\n continue;\n }\n else if (ch == '.')\n {\n hasIp4 = true;\n\n \/\/ Do not count bytes of the embedded IPv4 address.\n endp -= kIp4AddressSize;\n\n VerifyOrExit(dst <= endp, error = OT_ERROR_PARSE);\n\n break;\n }\n else\n {\n VerifyOrExit('0' <= ch && ch <= '9', error = OT_ERROR_PARSE);\n }\n\n first = false;\n val = static_cast<uint16_t>((val << 4) | d);\n VerifyOrExit(++count <= 4, error = OT_ERROR_PARSE);\n }\n\n VerifyOrExit(colonp || dst == endp, error = OT_ERROR_PARSE);\n\n while (colonp && dst > colonp)\n {\n *endp-- = *dst--;\n }\n\n while (endp > dst)\n {\n *endp-- = 0;\n }\n\n if (hasIp4)\n {\n val = 0;\n\n \/\/ Reset the start and end pointers.\n dst = reinterpret_cast<uint8_t *>(mFields.m8 + 12);\n endp = reinterpret_cast<uint8_t *>(mFields.m8 + 15);\n\n for (;;)\n {\n ch = *colonc++;\n\n if (ch == '.' || ch == '\\0' || ch == ' ')\n {\n VerifyOrExit(dst <= endp, error = OT_ERROR_PARSE);\n\n *dst++ = static_cast<uint8_t>(val);\n val = 0;\n\n if (ch == '\\0' || ch == ' ')\n {\n \/\/ Check if embedded IPv4 address had exactly four parts.\n VerifyOrExit(dst == endp + 1, error = OT_ERROR_PARSE);\n break;\n }\n }\n else\n {\n VerifyOrExit('0' <= ch && ch <= '9', error = OT_ERROR_PARSE);\n\n val = (10 * val) + (ch & 0xf);\n\n \/\/ Single part of IPv4 address has to fit in one byte.\n VerifyOrExit(val <= 0xff, error = OT_ERROR_PARSE);\n }\n }\n }\n\nexit:\n return error;\n}\n\nAddress::InfoString Address::ToString(void) const\n{\n return InfoString(\"%x:%x:%x:%x:%x:%x:%x:%x\", HostSwap16(mFields.m16[0]), HostSwap16(mFields.m16[1]),\n HostSwap16(mFields.m16[2]), HostSwap16(mFields.m16[3]), HostSwap16(mFields.m16[4]),\n HostSwap16(mFields.m16[5]), HostSwap16(mFields.m16[6]), HostSwap16(mFields.m16[7]));\n}\n\n} \/\/ namespace Ip6\n} \/\/ namespace ot\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Author: Brendan Le Foll <brendan.le.foll@intel.com>\n * Copyright (c) 2014 Intel Corporation.\n *\n * Permission is hereby granted, free of charge, to any person obtaining\n * a copy of this software and associated documentation files (the\n * \"Software\"), to deal in the Software without restriction, including\n * without limitation the rights to use, copy, modify, merge, publish,\n * distribute, sublicense, and\/or sell copies of the Software, and to\n * permit persons to whom the Software is furnished to do so, subject to\n * the following conditions:\n *\n * The above copyright notice and this permission notice shall be\n * included in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n *\/\n\n#pragma once\n\n#include \"spi.h\"\n#include <stdexcept>\n\nnamespace mraa\n{\n\n\/**\n * MRAA SPI Modes\n *\/\ntypedef enum {\n SPI_MODE0 = 0, \/**< CPOL = 0, CPHA = 0, Clock idle low, data is clocked in on rising edge,\n output data (change) on falling edge *\/\n SPI_MODE1 = 1, \/**< CPOL = 0, CPHA = 1, Clock idle low, data is clocked in on falling edge,\n output data (change) on rising edge *\/\n SPI_MODE2 = 2, \/**< CPOL = 1, CPHA = 0, Clock idle low, data is clocked in on falling edge,\n output data (change) on rising edge *\/\n SPI_MODE3 = 3, \/**< CPOL = 1, CPHA = 1, Clock idle low, data is clocked in on rising, edge\n output data (change) on falling edge *\/\n} Spi_Mode;\n\n\n\/**\n* @brief API to Serial Peripheral Interface\n*\n* This file defines the SPI interface for libmraa\n*\n* @snippet Spi-pot.cpp Interesting\n*\/\nclass Spi\n{\n public:\n \/**\n * Initialise SPI object using the board mapping to set muxes\n *\n * @param bus to use, as listed in the platform definition, normally 0\n *\/\n Spi(int bus)\n {\n m_spi = mraa_spi_init(bus);\n\n if (m_spi == NULL) {\n throw std::invalid_argument(\"Error initialising SPI bus\");\n }\n }\n\n \/**\n * Closes spi bus\n *\/\n ~Spi()\n {\n mraa_spi_stop(m_spi);\n }\n\n \/**\n * Set the SPI device mode. see spidev0-3\n *\n * @param mode the mode. See Linux spidev doc\n * @return Result of operation\n *\/\n mraa_result_t\n mode(Spi_Mode mode)\n {\n return mraa_spi_mode(m_spi, (mraa_spi_mode_t) mode);\n }\n\n \/**\n * Set the SPI device operating clock frequency\n *\n * @param hz the frequency to set in hz\n * @return Result of operation\n *\/\n mraa_result_t\n frequency(int hz)\n {\n return mraa_spi_frequency(m_spi, hz);\n }\n\n \/**\n * Write single byte to the SPI device\n *\n * @param data the byte to send\n * @return data received on the miso line or -1 in case of error\n *\/\n int\n writeByte(uint8_t data)\n {\n return mraa_spi_write(m_spi, (uint8_t) data);\n }\n\n \/**\n * Write single byte to the SPI device\n *\n * @param data the byte to send\n * @return data received on the miso line\n *\/\n uint16_t\n write_word(uint16_t data)\n {\n return mraa_spi_write_word(m_spi, (uint16_t) data);\n }\n\n \/**\n * Write buffer of bytes to SPI device The pointer return has to be\n * free'd by the caller. It will return a NULL pointer in cases of\n * error\n *\n * @param txBuf buffer to send\n * @param length size of buffer to send\n * @return uint8_t* data received on the miso line. Same length as passed in\n *\/\n uint8_t*\n write(uint8_t* txBuf, int length)\n {\n return mraa_spi_write_buf(m_spi, txBuf, length);\n }\n\n#ifndef SWIG\n \/**\n * Write buffer of bytes to SPI device The pointer return has to be\n * free'd by the caller. It will return a NULL pointer in cases of\n * error\n *\n * @param txBuf buffer to send\n * @param length size of buffer (in bytes) to send\n * @return uint8_t* data received on the miso line. Same length as passed in\n *\/\n uint16_t*\n write_word(uint16_t* txBuf, int length)\n {\n return mraa_spi_write_buf_word(m_spi, txBuf, length);\n }\n#endif\n\n#ifndef SWIG\n \/**\n * Transfer data to and from SPI device Receive pointer may be null if\n * return data is not needed.\n *\n * @param data buffer to send\n * @param rxBuf buffer to optionally receive data from spi device\n * @param length size of buffer to send\n * @return Result of operation\n *\/\n mraa_result_t\n transfer(uint8_t* txBuf, uint8_t* rxBuf, int length)\n {\n return mraa_spi_transfer_buf(m_spi, txBuf, rxBuf, length);\n }\n\n \/**\n * Transfer data to and from SPI device Receive pointer may be null if\n * return data is not needed.\n *\n * @param data buffer to send\n * @param rxBuf buffer to optionally receive data from spi device\n * @param length size of buffer to send\n * @return Result of operation\n *\/\n mraa_result_t\n transfer_word(uint16_t* txBuf, uint16_t* rxBuf, int length)\n {\n return mraa_spi_transfer_buf_word(m_spi, txBuf, rxBuf, length);\n }\n#endif\n\n \/**\n * Change the SPI lsb mode\n *\n * @param lsb Use least significant bit transmission - 0 for msbi\n * @return Result of operation\n *\/\n mraa_result_t\n lsbmode(bool lsb)\n {\n return mraa_spi_lsbmode(m_spi, (mraa_boolean_t) lsb);\n }\n\n \/**\n * Set bits per mode on transaction, default is 8\n *\n * @param bits bits per word\n * @return Result of operation\n *\/\n mraa_result_t\n bitPerWord(unsigned int bits)\n {\n return mraa_spi_bit_per_word(m_spi, bits);\n }\n\n private:\n mraa_spi_context m_spi;\n};\n}\n<commit_msg>spi.hpp: fix wrong docstrings data -> txBuf<commit_after>\/*\n * Author: Brendan Le Foll <brendan.le.foll@intel.com>\n * Copyright (c) 2014 Intel Corporation.\n *\n * Permission is hereby granted, free of charge, to any person obtaining\n * a copy of this software and associated documentation files (the\n * \"Software\"), to deal in the Software without restriction, including\n * without limitation the rights to use, copy, modify, merge, publish,\n * distribute, sublicense, and\/or sell copies of the Software, and to\n * permit persons to whom the Software is furnished to do so, subject to\n * the following conditions:\n *\n * The above copyright notice and this permission notice shall be\n * included in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n *\/\n\n#pragma once\n\n#include \"spi.h\"\n#include <stdexcept>\n\nnamespace mraa\n{\n\n\/**\n * MRAA SPI Modes\n *\/\ntypedef enum {\n SPI_MODE0 = 0, \/**< CPOL = 0, CPHA = 0, Clock idle low, data is clocked in on rising edge,\n output data (change) on falling edge *\/\n SPI_MODE1 = 1, \/**< CPOL = 0, CPHA = 1, Clock idle low, data is clocked in on falling edge,\n output data (change) on rising edge *\/\n SPI_MODE2 = 2, \/**< CPOL = 1, CPHA = 0, Clock idle low, data is clocked in on falling edge,\n output data (change) on rising edge *\/\n SPI_MODE3 = 3, \/**< CPOL = 1, CPHA = 1, Clock idle low, data is clocked in on rising, edge\n output data (change) on falling edge *\/\n} Spi_Mode;\n\n\n\/**\n* @brief API to Serial Peripheral Interface\n*\n* This file defines the SPI interface for libmraa\n*\n* @snippet Spi-pot.cpp Interesting\n*\/\nclass Spi\n{\n public:\n \/**\n * Initialise SPI object using the board mapping to set muxes\n *\n * @param bus to use, as listed in the platform definition, normally 0\n *\/\n Spi(int bus)\n {\n m_spi = mraa_spi_init(bus);\n\n if (m_spi == NULL) {\n throw std::invalid_argument(\"Error initialising SPI bus\");\n }\n }\n\n \/**\n * Closes spi bus\n *\/\n ~Spi()\n {\n mraa_spi_stop(m_spi);\n }\n\n \/**\n * Set the SPI device mode. see spidev0-3\n *\n * @param mode the mode. See Linux spidev doc\n * @return Result of operation\n *\/\n mraa_result_t\n mode(Spi_Mode mode)\n {\n return mraa_spi_mode(m_spi, (mraa_spi_mode_t) mode);\n }\n\n \/**\n * Set the SPI device operating clock frequency\n *\n * @param hz the frequency to set in hz\n * @return Result of operation\n *\/\n mraa_result_t\n frequency(int hz)\n {\n return mraa_spi_frequency(m_spi, hz);\n }\n\n \/**\n * Write single byte to the SPI device\n *\n * @param data the byte to send\n * @return data received on the miso line or -1 in case of error\n *\/\n int\n writeByte(uint8_t data)\n {\n return mraa_spi_write(m_spi, (uint8_t) data);\n }\n\n \/**\n * Write single byte to the SPI device\n *\n * @param data the byte to send\n * @return data received on the miso line\n *\/\n uint16_t\n write_word(uint16_t data)\n {\n return mraa_spi_write_word(m_spi, (uint16_t) data);\n }\n\n \/**\n * Write buffer of bytes to SPI device The pointer return has to be\n * free'd by the caller. It will return a NULL pointer in cases of\n * error\n *\n * @param txBuf buffer to send\n * @param length size of buffer to send\n * @return uint8_t* data received on the miso line. Same length as passed in\n *\/\n uint8_t*\n write(uint8_t* txBuf, int length)\n {\n return mraa_spi_write_buf(m_spi, txBuf, length);\n }\n\n#ifndef SWIG\n \/**\n * Write buffer of bytes to SPI device The pointer return has to be\n * free'd by the caller. It will return a NULL pointer in cases of\n * error\n *\n * @param txBuf buffer to send\n * @param length size of buffer (in bytes) to send\n * @return uint8_t* data received on the miso line. Same length as passed in\n *\/\n uint16_t*\n write_word(uint16_t* txBuf, int length)\n {\n return mraa_spi_write_buf_word(m_spi, txBuf, length);\n }\n#endif\n\n#ifndef SWIG\n \/**\n * Transfer data to and from SPI device Receive pointer may be null if\n * return data is not needed.\n *\n * @param txBuf buffer to send\n * @param rxBuf buffer to optionally receive data from spi device\n * @param length size of buffer to send\n * @return Result of operation\n *\/\n mraa_result_t\n transfer(uint8_t* txBuf, uint8_t* rxBuf, int length)\n {\n return mraa_spi_transfer_buf(m_spi, txBuf, rxBuf, length);\n }\n\n \/**\n * Transfer data to and from SPI device Receive pointer may be null if\n * return data is not needed.\n *\n * @param txBuf buffer to send\n * @param rxBuf buffer to optionally receive data from spi device\n * @param length size of buffer to send\n * @return Result of operation\n *\/\n mraa_result_t\n transfer_word(uint16_t* txBuf, uint16_t* rxBuf, int length)\n {\n return mraa_spi_transfer_buf_word(m_spi, txBuf, rxBuf, length);\n }\n#endif\n\n \/**\n * Change the SPI lsb mode\n *\n * @param lsb Use least significant bit transmission - 0 for msbi\n * @return Result of operation\n *\/\n mraa_result_t\n lsbmode(bool lsb)\n {\n return mraa_spi_lsbmode(m_spi, (mraa_boolean_t) lsb);\n }\n\n \/**\n * Set bits per mode on transaction, default is 8\n *\n * @param bits bits per word\n * @return Result of operation\n *\/\n mraa_result_t\n bitPerWord(unsigned int bits)\n {\n return mraa_spi_bit_per_word(m_spi, bits);\n }\n\n private:\n mraa_spi_context m_spi;\n};\n}\n<|endoftext|>"} {"text":"<commit_before>#pragma once\n\n#include <openMVG\/features\/descriptor.hpp>\n#include <openMVG\/features\/image_describer.hpp>\n#include <openMVG\/features\/regions_factory.hpp>\n\nextern \"C\" {\n#include \"nonFree\/sift\/vl\/sift.h\"\n}\n\n#include <cereal\/cereal.hpp>\n\n#include <iostream>\n#include <numeric>\n\nnamespace openMVG {\nnamespace features {\n\nstruct SiftParams\n{\n SiftParams(\n int first_octave = 0,\n int num_octaves = 6,\n int num_scales = 3,\n float edge_threshold = 10.0f,\n float peak_threshold = 0.04f,\n \/\/\n std::size_t gridSize = 4,\n std::size_t maxTotalKeypoints = 1000,\n \/\/\n bool root_sift = true\n ):\n _first_octave(first_octave),\n _num_octaves(num_octaves),\n _num_scales(num_scales),\n _edge_threshold(edge_threshold),\n _peak_threshold(peak_threshold),\n \/\/\n _gridSize(gridSize),\n _maxTotalKeypoints(maxTotalKeypoints),\n \/\/\n _root_sift(root_sift) {}\n\n template<class Archive>\n void serialize( Archive & ar )\n {\n ar(\n cereal::make_nvp(\"first_octave\", _first_octave), \n cereal::make_nvp(\"num_octaves\",_num_octaves),\n cereal::make_nvp(\"num_scales\",_num_scales),\n cereal::make_nvp(\"edge_threshold\",_edge_threshold),\n cereal::make_nvp(\"peak_threshold\",_peak_threshold),\n \/\/\n cereal::make_nvp(\"grid_size\", _gridSize),\n cereal::make_nvp(\"max_total_keypoints\", _maxTotalKeypoints),\n \/\/\n cereal::make_nvp(\"root_sift\",_root_sift));\n }\n\n \/\/ Parameters\n int _first_octave; \/\/ Use original image, or perform an upscale if == -1\n int _num_octaves; \/\/ Max octaves count\n int _num_scales; \/\/ Scales per octave\n float _edge_threshold; \/\/ Max ratio of Hessian eigenvalues\n float _peak_threshold; \/\/ Min contrast\n \/\/\n std::size_t _gridSize;\n std::size_t _maxTotalKeypoints;\n \/\/\n bool _root_sift; \/\/ see [1]\n \n bool setPreset(EDESCRIBER_PRESET preset)\n {\n switch(preset)\n {\n case LOW_PRESET:\n {\n _maxTotalKeypoints = 1000;\n _peak_threshold = 0.04f;\n _first_octave = 2;\n break;\n }\n case MEDIUM_PRESET:\n {\n _maxTotalKeypoints = 5000;\n _peak_threshold = 0.04f;\n _first_octave = 1;\n break;\n }\n case NORMAL_PRESET:\n {\n _maxTotalKeypoints = 10000;\n _peak_threshold = 0.04f;\n break;\n }\n case HIGH_PRESET:\n {\n _maxTotalKeypoints = 20000;\n _peak_threshold = 0.01f;\n break;\n }\n case ULTRA_PRESET:\n {\n _maxTotalKeypoints = 40000;\n _peak_threshold = 0.01f;\n _first_octave = -1;\n break;\n }\n default:\n return false;\n }\n return true;\n }\n \n \n};\n\n\/\/convertSIFT\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate < typename TOut > \ninline void convertSIFT(\n const vl_sift_pix* descr,\n Descriptor<TOut,128> & descriptor,\n bool brootSift = false\n );\n\ntemplate <> \ninline void convertSIFT<float>(\n const vl_sift_pix* descr,\n Descriptor<float,128> &descriptor,\n bool brootSift)\n{\n if(brootSift)\n {\n const float sum = std::accumulate(descr, descr + 128, 0.0f);\n for(int k = 0; k < 128; ++k)\n descriptor[k] = std::floor(512.f*sqrt(descr[k] \/ sum));\n }\n else\n {\n for(int k = 0; k < 128; ++k)\n descriptor[k] = std::floor(512.f*descr[k]);\n }\n}\n\ntemplate <> \ninline void convertSIFT<unsigned char>(\n const vl_sift_pix* descr,\n Descriptor<unsigned char,128> & descriptor,\n bool brootSift)\n{\n if (brootSift)\n {\n \/\/ rootsift = sqrt( sift \/ sum(sift) );\n const float sum = std::accumulate(descr, descr+128, 0.0f);\n for (int k=0;k<128;++k)\n descriptor[k] = static_cast<unsigned char>(512.f*sqrt(descr[k]\/sum));\n }\n else\n {\n for (int k=0;k<128;++k)\n descriptor[k] = static_cast<unsigned char>(512.f*descr[k]);\n }\n}\n\n\/**\n * @brief Extract SIFT regions (in float or unsigned char).\n * \n * @param image\n * @param regions\n * @param params\n * @param bOrientation\n * @param mask\n * @return \n *\/\ntemplate < typename T >\nbool extractSIFT(const image::Image<unsigned char>& image,\n std::unique_ptr<Regions> ®ions,\n const SiftParams& params,\n bool bOrientation,\n const image::Image<unsigned char> * mask)\n{\n const int w = image.Width(), h = image.Height();\n \/\/Convert to float\n const image::Image<float> imageFloat(image.GetMat().cast<float>());\n\n VlSiftFilt *filt = vl_sift_new(w, h, params._num_octaves, params._num_scales, params._first_octave);\n if (params._edge_threshold >= 0)\n vl_sift_set_edge_thresh(filt, params._edge_threshold);\n if (params._peak_threshold >= 0)\n vl_sift_set_peak_thresh(filt, 255.0 * params._peak_threshold\/params._num_scales);\n\n Descriptor<vl_sift_pix, 128> vlFeatDescriptor;\n Descriptor<T, 128> descriptor;\n\n \/\/ Process SIFT computation\n vl_sift_process_first_octave(filt, imageFloat.data());\n\n typedef Scalar_Regions<SIOPointFeature,T,128> SIFT_Region_T;\n regions.reset( new SIFT_Region_T );\n \n \/\/ Build alias to cached data\n SIFT_Region_T * regionsCasted = dynamic_cast<SIFT_Region_T*>(regions.get());\n \/\/ reserve some memory for faster keypoint saving\n const std::size_t reserveSize = (params._gridSize && params._maxTotalKeypoints) ? params._maxTotalKeypoints : 2000;\n regionsCasted->Features().reserve(reserveSize);\n regionsCasted->Descriptors().reserve(reserveSize);\n\n while (true)\n {\n vl_sift_detect(filt);\n\n VlSiftKeypoint const *keys = vl_sift_get_keypoints(filt);\n const int nkeys = vl_sift_get_nkeypoints(filt);\n\n \/\/ Update gradient before launching parallel extraction\n vl_sift_update_gradient(filt);\n\n std::cout << \"TEST octave_width: \" << filt->octave_width << std::endl;\n #ifdef OPENMVG_USE_OPENMP\n #pragma omp parallel for private(vlFeatDescriptor, descriptor)\n #endif\n for (int i = 0; i < nkeys; ++i)\n {\n\n \/\/ Feature masking\n if (mask)\n {\n const image::Image<unsigned char> & maskIma = *mask;\n if (maskIma(keys[i].y, keys[i].x) > 0)\n continue;\n }\n\n double angles [4] = {0.0, 0.0, 0.0, 0.0};\n int nangles = 1; \/\/ by default (1 upright feature)\n if (bOrientation)\n { \/\/ compute from 1 to 4 orientations\n nangles = vl_sift_calc_keypoint_orientations(filt, angles, keys+i);\n }\n\n for (int q=0 ; q < nangles ; ++q)\n {\n vl_sift_calc_keypoint_descriptor(filt, &vlFeatDescriptor[0], keys+i, angles[q]);\n const SIOPointFeature fp(keys[i].x, keys[i].y,\n keys[i].sigma, static_cast<float>(angles[q]));\n\n convertSIFT<T>(&vlFeatDescriptor[0], descriptor, params._root_sift);\n #ifdef OPENMVG_USE_OPENMP\n #pragma omp critical\n #endif\n {\n regionsCasted->Descriptors().push_back(descriptor);\n regionsCasted->Features().push_back(fp);\n }\n \n }\n }\n \n if (vl_sift_process_next_octave(filt))\n break; \/\/ Last octave\n }\n vl_sift_delete(filt);\n\n const auto& features = regionsCasted->Features();\n const auto& descriptors = regionsCasted->Descriptors();\n \n \/\/Sorting the extracted features according to their scale\n {\n std::vector<std::size_t> indexSort(features.size());\n std::iota(indexSort.begin(), indexSort.end(), 0);\n std::sort(indexSort.begin(), indexSort.end(), [&](std::size_t a, std::size_t b){ return features[a].scale() > features[b].scale(); });\n \n std::vector<typename SIFT_Region_T::FeatureT> sortedFeatures(features.size());\n std::vector<typename SIFT_Region_T::DescriptorT> sortedDescriptors(features.size());\n for(std::size_t i: indexSort)\n {\n sortedFeatures[i] = features[indexSort[i]];\n sortedDescriptors[i] = descriptors[indexSort[i]];\n }\n regionsCasted->Features().swap(sortedFeatures);\n regionsCasted->Descriptors().swap(sortedDescriptors);\n }\n \n \/\/ Grid filtering of the keypoints to ensure a global repartition\n if(params._gridSize && params._maxTotalKeypoints)\n {\n \/\/ Only filter features if we have more features than the maxTotalKeypoints\n if(features.size() > params._maxTotalKeypoints)\n {\n std::vector<typename SIFT_Region_T::FeatureT> filtered_keypoints;\n std::vector<typename SIFT_Region_T::FeatureT> rejected_keypoints;\n filtered_keypoints.reserve(std::min(features.size(), params._maxTotalKeypoints));\n rejected_keypoints.reserve(features.size());\n\n const std::size_t sizeMat = params._gridSize * params._gridSize;\n std::vector<std::size_t> countFeatPerCell(sizeMat, 0);\n for (int Indice = 0; Indice < sizeMat; Indice++)\n {\n \t countFeatPerCell[Indice] = 0;\n }\n const std::size_t keypointsPerCell = params._maxTotalKeypoints \/ sizeMat;\n const double regionWidth = w \/ double(params._gridSize);\n const double regionHeight = h \/ double(params._gridSize);\n\n \/\/std::cout << \"Grid filtering -- keypointsPerCell: \" << keypointsPerCell\n \/\/ << \", regionWidth: \" << regionWidth\n \/\/ << \", regionHeight: \" << regionHeight << std::endl;\n\n for(const auto& keypoint: features)\n {\n const std::size_t cellX = std::min(std::size_t(keypoint.x() \/ regionWidth), params._gridSize);\n const std::size_t cellY = std::min(std::size_t(keypoint.y() \/ regionHeight), params._gridSize);\n \/\/std::cout << \"- keypoint.pt.x: \" << keypoint.pt.x << \", keypoint.pt.y: \" << keypoint.pt.y << std::endl;\n \/\/std::cout << \"- cellX: \" << cellX << \", cellY: \" << cellY << std::endl;\n \/\/std::cout << \"- countFeatPerCell: \" << countFeatPerCell << std::endl;\n \/\/std::cout << \"- gridSize: \" << _params.gridSize << std::endl;\n\n std::size_t &count = countFeatPerCell[cellX*params._gridSize + cellY];\n ++count;\n\n if(count < keypointsPerCell)\n filtered_keypoints.push_back(keypoint);\n else\n rejected_keypoints.push_back(keypoint);\n }\n \/\/ If we don't have enough features (less than maxTotalKeypoints) after the grid filtering (empty regions in the grid for example).\n \/\/ We add the best other ones, without repartition constraint.\n if( filtered_keypoints.size() < params._maxTotalKeypoints )\n {\n const std::size_t remainingElements = std::min(rejected_keypoints.size(), params._maxTotalKeypoints - filtered_keypoints.size());\n std::cout << \"Grid filtering -- Copy remaining points: \" << remainingElements << std::endl;\n filtered_keypoints.insert(filtered_keypoints.end(), rejected_keypoints.begin(), rejected_keypoints.begin() + remainingElements);\n }\n\n regionsCasted->Features().swap(filtered_keypoints);\n }\n }\n \n return true;\n}\n\n} \/\/namespace openMVG\n} \/\/namespace features\n\n<commit_msg>[sift] remove cout<commit_after>#pragma once\n\n#include <openMVG\/features\/descriptor.hpp>\n#include <openMVG\/features\/image_describer.hpp>\n#include <openMVG\/features\/regions_factory.hpp>\n\nextern \"C\" {\n#include \"nonFree\/sift\/vl\/sift.h\"\n}\n\n#include <cereal\/cereal.hpp>\n\n#include <iostream>\n#include <numeric>\n\nnamespace openMVG {\nnamespace features {\n\nstruct SiftParams\n{\n SiftParams(\n int first_octave = 0,\n int num_octaves = 6,\n int num_scales = 3,\n float edge_threshold = 10.0f,\n float peak_threshold = 0.04f,\n \/\/\n std::size_t gridSize = 4,\n std::size_t maxTotalKeypoints = 1000,\n \/\/\n bool root_sift = true\n ):\n _first_octave(first_octave),\n _num_octaves(num_octaves),\n _num_scales(num_scales),\n _edge_threshold(edge_threshold),\n _peak_threshold(peak_threshold),\n \/\/\n _gridSize(gridSize),\n _maxTotalKeypoints(maxTotalKeypoints),\n \/\/\n _root_sift(root_sift) {}\n\n template<class Archive>\n void serialize( Archive & ar )\n {\n ar(\n cereal::make_nvp(\"first_octave\", _first_octave), \n cereal::make_nvp(\"num_octaves\",_num_octaves),\n cereal::make_nvp(\"num_scales\",_num_scales),\n cereal::make_nvp(\"edge_threshold\",_edge_threshold),\n cereal::make_nvp(\"peak_threshold\",_peak_threshold),\n \/\/\n cereal::make_nvp(\"grid_size\", _gridSize),\n cereal::make_nvp(\"max_total_keypoints\", _maxTotalKeypoints),\n \/\/\n cereal::make_nvp(\"root_sift\",_root_sift));\n }\n\n \/\/ Parameters\n int _first_octave; \/\/ Use original image, or perform an upscale if == -1\n int _num_octaves; \/\/ Max octaves count\n int _num_scales; \/\/ Scales per octave\n float _edge_threshold; \/\/ Max ratio of Hessian eigenvalues\n float _peak_threshold; \/\/ Min contrast\n \/\/\n std::size_t _gridSize;\n std::size_t _maxTotalKeypoints;\n \/\/\n bool _root_sift; \/\/ see [1]\n \n bool setPreset(EDESCRIBER_PRESET preset)\n {\n switch(preset)\n {\n case LOW_PRESET:\n {\n _maxTotalKeypoints = 1000;\n _peak_threshold = 0.04f;\n _first_octave = 2;\n break;\n }\n case MEDIUM_PRESET:\n {\n _maxTotalKeypoints = 5000;\n _peak_threshold = 0.04f;\n _first_octave = 1;\n break;\n }\n case NORMAL_PRESET:\n {\n _maxTotalKeypoints = 10000;\n _peak_threshold = 0.04f;\n break;\n }\n case HIGH_PRESET:\n {\n _maxTotalKeypoints = 20000;\n _peak_threshold = 0.01f;\n break;\n }\n case ULTRA_PRESET:\n {\n _maxTotalKeypoints = 40000;\n _peak_threshold = 0.01f;\n _first_octave = -1;\n break;\n }\n default:\n return false;\n }\n return true;\n }\n \n \n};\n\n\/\/convertSIFT\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate < typename TOut > \ninline void convertSIFT(\n const vl_sift_pix* descr,\n Descriptor<TOut,128> & descriptor,\n bool brootSift = false\n );\n\ntemplate <> \ninline void convertSIFT<float>(\n const vl_sift_pix* descr,\n Descriptor<float,128> &descriptor,\n bool brootSift)\n{\n if(brootSift)\n {\n const float sum = std::accumulate(descr, descr + 128, 0.0f);\n for(int k = 0; k < 128; ++k)\n descriptor[k] = std::floor(512.f*sqrt(descr[k] \/ sum));\n }\n else\n {\n for(int k = 0; k < 128; ++k)\n descriptor[k] = std::floor(512.f*descr[k]);\n }\n}\n\ntemplate <> \ninline void convertSIFT<unsigned char>(\n const vl_sift_pix* descr,\n Descriptor<unsigned char,128> & descriptor,\n bool brootSift)\n{\n if (brootSift)\n {\n \/\/ rootsift = sqrt( sift \/ sum(sift) );\n const float sum = std::accumulate(descr, descr+128, 0.0f);\n for (int k=0;k<128;++k)\n descriptor[k] = static_cast<unsigned char>(512.f*sqrt(descr[k]\/sum));\n }\n else\n {\n for (int k=0;k<128;++k)\n descriptor[k] = static_cast<unsigned char>(512.f*descr[k]);\n }\n}\n\n\/**\n * @brief Extract SIFT regions (in float or unsigned char).\n * \n * @param image\n * @param regions\n * @param params\n * @param bOrientation\n * @param mask\n * @return \n *\/\ntemplate < typename T >\nbool extractSIFT(const image::Image<unsigned char>& image,\n std::unique_ptr<Regions> ®ions,\n const SiftParams& params,\n bool bOrientation,\n const image::Image<unsigned char> * mask)\n{\n const int w = image.Width(), h = image.Height();\n \/\/Convert to float\n const image::Image<float> imageFloat(image.GetMat().cast<float>());\n\n VlSiftFilt *filt = vl_sift_new(w, h, params._num_octaves, params._num_scales, params._first_octave);\n if (params._edge_threshold >= 0)\n vl_sift_set_edge_thresh(filt, params._edge_threshold);\n if (params._peak_threshold >= 0)\n vl_sift_set_peak_thresh(filt, 255.0 * params._peak_threshold\/params._num_scales);\n\n Descriptor<vl_sift_pix, 128> vlFeatDescriptor;\n Descriptor<T, 128> descriptor;\n\n \/\/ Process SIFT computation\n vl_sift_process_first_octave(filt, imageFloat.data());\n\n typedef Scalar_Regions<SIOPointFeature,T,128> SIFT_Region_T;\n regions.reset( new SIFT_Region_T );\n \n \/\/ Build alias to cached data\n SIFT_Region_T * regionsCasted = dynamic_cast<SIFT_Region_T*>(regions.get());\n \/\/ reserve some memory for faster keypoint saving\n const std::size_t reserveSize = (params._gridSize && params._maxTotalKeypoints) ? params._maxTotalKeypoints : 2000;\n regionsCasted->Features().reserve(reserveSize);\n regionsCasted->Descriptors().reserve(reserveSize);\n\n while (true)\n {\n vl_sift_detect(filt);\n\n VlSiftKeypoint const *keys = vl_sift_get_keypoints(filt);\n const int nkeys = vl_sift_get_nkeypoints(filt);\n\n \/\/ Update gradient before launching parallel extraction\n vl_sift_update_gradient(filt);\n\n #ifdef OPENMVG_USE_OPENMP\n #pragma omp parallel for private(vlFeatDescriptor, descriptor)\n #endif\n for (int i = 0; i < nkeys; ++i)\n {\n\n \/\/ Feature masking\n if (mask)\n {\n const image::Image<unsigned char> & maskIma = *mask;\n if (maskIma(keys[i].y, keys[i].x) > 0)\n continue;\n }\n\n double angles [4] = {0.0, 0.0, 0.0, 0.0};\n int nangles = 1; \/\/ by default (1 upright feature)\n if (bOrientation)\n { \/\/ compute from 1 to 4 orientations\n nangles = vl_sift_calc_keypoint_orientations(filt, angles, keys+i);\n }\n\n for (int q=0 ; q < nangles ; ++q)\n {\n vl_sift_calc_keypoint_descriptor(filt, &vlFeatDescriptor[0], keys+i, angles[q]);\n const SIOPointFeature fp(keys[i].x, keys[i].y,\n keys[i].sigma, static_cast<float>(angles[q]));\n\n convertSIFT<T>(&vlFeatDescriptor[0], descriptor, params._root_sift);\n #ifdef OPENMVG_USE_OPENMP\n #pragma omp critical\n #endif\n {\n regionsCasted->Descriptors().push_back(descriptor);\n regionsCasted->Features().push_back(fp);\n }\n \n }\n }\n \n if (vl_sift_process_next_octave(filt))\n break; \/\/ Last octave\n }\n vl_sift_delete(filt);\n\n const auto& features = regionsCasted->Features();\n const auto& descriptors = regionsCasted->Descriptors();\n \n \/\/Sorting the extracted features according to their scale\n {\n std::vector<std::size_t> indexSort(features.size());\n std::iota(indexSort.begin(), indexSort.end(), 0);\n std::sort(indexSort.begin(), indexSort.end(), [&](std::size_t a, std::size_t b){ return features[a].scale() > features[b].scale(); });\n \n std::vector<typename SIFT_Region_T::FeatureT> sortedFeatures(features.size());\n std::vector<typename SIFT_Region_T::DescriptorT> sortedDescriptors(features.size());\n for(std::size_t i: indexSort)\n {\n sortedFeatures[i] = features[indexSort[i]];\n sortedDescriptors[i] = descriptors[indexSort[i]];\n }\n regionsCasted->Features().swap(sortedFeatures);\n regionsCasted->Descriptors().swap(sortedDescriptors);\n }\n \n \/\/ Grid filtering of the keypoints to ensure a global repartition\n if(params._gridSize && params._maxTotalKeypoints)\n {\n \/\/ Only filter features if we have more features than the maxTotalKeypoints\n if(features.size() > params._maxTotalKeypoints)\n {\n std::vector<typename SIFT_Region_T::FeatureT> filtered_keypoints;\n std::vector<typename SIFT_Region_T::FeatureT> rejected_keypoints;\n filtered_keypoints.reserve(std::min(features.size(), params._maxTotalKeypoints));\n rejected_keypoints.reserve(features.size());\n\n const std::size_t sizeMat = params._gridSize * params._gridSize;\n std::vector<std::size_t> countFeatPerCell(sizeMat, 0);\n for (int Indice = 0; Indice < sizeMat; Indice++)\n {\n \t countFeatPerCell[Indice] = 0;\n }\n const std::size_t keypointsPerCell = params._maxTotalKeypoints \/ sizeMat;\n const double regionWidth = w \/ double(params._gridSize);\n const double regionHeight = h \/ double(params._gridSize);\n\n \/\/std::cout << \"Grid filtering -- keypointsPerCell: \" << keypointsPerCell\n \/\/ << \", regionWidth: \" << regionWidth\n \/\/ << \", regionHeight: \" << regionHeight << std::endl;\n\n for(const auto& keypoint: features)\n {\n const std::size_t cellX = std::min(std::size_t(keypoint.x() \/ regionWidth), params._gridSize);\n const std::size_t cellY = std::min(std::size_t(keypoint.y() \/ regionHeight), params._gridSize);\n \/\/std::cout << \"- keypoint.pt.x: \" << keypoint.pt.x << \", keypoint.pt.y: \" << keypoint.pt.y << std::endl;\n \/\/std::cout << \"- cellX: \" << cellX << \", cellY: \" << cellY << std::endl;\n \/\/std::cout << \"- countFeatPerCell: \" << countFeatPerCell << std::endl;\n \/\/std::cout << \"- gridSize: \" << _params.gridSize << std::endl;\n\n std::size_t &count = countFeatPerCell[cellX*params._gridSize + cellY];\n ++count;\n\n if(count < keypointsPerCell)\n filtered_keypoints.push_back(keypoint);\n else\n rejected_keypoints.push_back(keypoint);\n }\n \/\/ If we don't have enough features (less than maxTotalKeypoints) after the grid filtering (empty regions in the grid for example).\n \/\/ We add the best other ones, without repartition constraint.\n if( filtered_keypoints.size() < params._maxTotalKeypoints )\n {\n const std::size_t remainingElements = std::min(rejected_keypoints.size(), params._maxTotalKeypoints - filtered_keypoints.size());\n std::cout << \"Grid filtering -- Copy remaining points: \" << remainingElements << std::endl;\n filtered_keypoints.insert(filtered_keypoints.end(), rejected_keypoints.begin(), rejected_keypoints.begin() + remainingElements);\n }\n\n regionsCasted->Features().swap(filtered_keypoints);\n }\n }\n \n return true;\n}\n\n} \/\/namespace openMVG\n} \/\/namespace features\n\n<|endoftext|>"} {"text":"<commit_before>#ifndef CXX_OBJECT_HXX\n# define CXX_OBJECT_HXX\n\n# include <boost\/bind.hpp>\n\n# include <object\/atom.hh>\n# include <object\/primitive-class.hh>\n# include <object\/string-class.hh>\n# include <object\/object-class.hh>\n# include <object\/primitives.hh>\n\nnamespace object\n{\n template <typename T>\n bool CxxObject::add(const std::string& name, rObject& tgt)\n {\n std::cerr << \"REGISTER: \" << name << std::endl;\n initializers_get().push_back(new TypeInitializer<T>(name, tgt));\n return true;\n }\n\n template <typename T>\n CxxObject::TypeInitializer<T>::TypeInitializer(const std::string& name,\n rObject& tgt)\n : Initializer(tgt), name_(name)\n {}\n\n namespace\n {\n template <typename T>\n rObject cxx_object_clone(runner::Runner&, objects_type args)\n {\n CHECK_ARG_COUNT(1);\n rObject tgt = args[0];\n rObject res;\n if (tgt->is_a<T>())\n res = new T(tgt->as<T>());\n else\n res = new T();\n return res;\n }\n\n template <typename T>\n rObject cxx_object_id(runner::Runner&, objects_type args)\n {\n CHECK_ARG_COUNT(1);\n return args[0];\n }\n }\n\n template <typename T>\n void\n CxxObject::TypeInitializer<T>::create()\n {\n res_ = new Object();\n }\n\n template <typename T>\n rObject\n CxxObject::TypeInitializer<T>::make_class()\n {\n std::cerr << \"INIT: \" << name_ << std::endl;\n res_->proto_add(object_class);\n res_->slot_set(SYMBOL(protoName), new String(name_));\n res_->slot_set(SYMBOL(clone),\n rPrimitive(new Primitive(boost::bind(cxx_object_clone<T>,\n _1, _2))));\n Binder<T> b(res_);\n T::initialize(b);\n\n libport::Symbol conversion =\n libport::Symbol(std::string(\"as\") + name_.name_get());\n if (!res_->slot_locate(conversion, 0))\n res_->slot_set(conversion,\n rPrimitive(new Primitive(boost::bind(cxx_object_id<T>,\n _1, _2))));\n return res_;\n }\n\n template <typename T>\n libport::Symbol\n CxxObject::TypeInitializer<T>::name()\n {\n return name_;\n }\n\n \/\/ BINDER\n\n template <typename T>\n CxxObject::Binder<T>::Binder(rObject tgt)\n : tgt_(tgt)\n {}\n\n namespace\n {\n\n# define PRINT_true(X) X\n# define PRINT_false(X)\n# define PRINT_truetrue(X) X\n# define PRINT_falsetrue(X)\n# define PRINT_truefalse(X)\n# define PRINT_falsefalse(X)\n# define NPRINT_true(X)\n# define NPRINT_false(X) X\n\n# define WHEN(Cond, X) PRINT_##Cond(X)\n# define WHEN_NOT(Cond, X) NPRINT_##Cond(X)\n\n# define IF(Cond, Then, Else) WHEN(Cond, Then) WHEN_NOT(Cond, Else)\n\n# define COMMA_ ,\n# define COMMA(Cond) PRINT_##Cond(COMMA_)\n\n# define COMMA2(Cond1, Cond2) PRINT_##Cond1##Cond2(COMMA_)\n\n# define MET(Met, Name, Ret, Run, Arg1, Arg2, Arg3) \\\n IF(Ret, libport::shared_ptr<R>, void) \\\n (WHEN(Met, T::)*Name)( \\\n WHEN(Run, runner::Runner&) COMMA2(Run, Arg1) \\\n WHEN(Arg1, libport::shared_ptr<A1>) \\\n COMMA(Arg2) WHEN(Arg2, libport::shared_ptr<A2>) \\\n COMMA(Arg3) WHEN(Arg3, libport::shared_ptr<A3>) \\\n )\n\n#define GET_ARG(Met, N) \\\n type_check<A##N>(args[N WHEN_NOT(Met, - 1)], name.name_get()); \\\n libport::shared_ptr<A##N> a##N = \\\n args[N WHEN_NOT(Met, - 1)].unsafe_cast<A##N>(); \\\n assert(a##N);\n\n#define FETCH_TGT() \\\n type_check<T>(args[0], name.name_get()); \\\n libport::shared_ptr<T> tgt = args[0].unsafe_cast<T>();\n\n#define PRIMITIVE(Met, Ret, ArgsC, Run, Arg1, Arg2, Arg3) \\\n template <typename T \\\n COMMA(Ret) WHEN(Ret, typename R) \\\n COMMA(Arg1) WHEN(Arg1, typename A1) \\\n COMMA(Arg2) WHEN(Arg2, typename A2) \\\n COMMA(Arg3) WHEN(Arg3, typename A3) \\\n > \\\n struct primitive<T, MET(Met, , Ret, Run, Arg1, Arg2, Arg3)> \\\n { \\\n static rObject make( \\\n MET(Met, method, Ret, Run, Arg1, Arg2, Arg3), \\\n const libport::Symbol& IF(Met, name, WHEN(Arg1, name)), \\\n runner::Runner& WHEN(Run, r), \\\n objects_type args) \\\n { \\\n\t (void)args;\t\t\t\t\t\t\t\\\n assert(args.size() == \\\n ArgsC IF(Met, + 1, WHEN_NOT(Arg1, + 1))); \\\n WHEN(Met, FETCH_TGT()); \\\n WHEN(Arg1, GET_ARG(Met, 1)) \\\n WHEN(Arg2, GET_ARG(Met, 2)) \\\n WHEN(Arg3, GET_ARG(Met, 3)) \\\n WHEN(Ret, return) \\\n (WHEN(Met, tgt.get()->*)method)( \\\n WHEN(Run, r) COMMA2(Run, Arg1) \\\n WHEN(Arg1, a1) \\\n COMMA(Arg2) WHEN(Arg2, a2) \\\n COMMA(Arg3) WHEN(Arg3, a3) \\\n ); \\\n return void_class; \\\n } \\\n }\n\n#define LIST_MET(Name, Met, Ret, Run) \\\n IF(Ret, R, void) \\\n (WHEN(Met, T::)*Name)(WHEN(Run, runner::Runner&) COMMA(Run) \\\n objects_type) \\\n\n#define LIST_PRIMITIVE(Met, Ret, Run) \\\n template <typename T \\\n COMMA(Ret) WHEN(Ret, typename R) \\\n > \\\n struct primitive<T, LIST_MET(, Met, Ret, Run)> \\\n { \\\n static rObject make( \\\n LIST_MET(method, Met, Ret, Run), \\\n const libport::Symbol& name, \\\n runner::Runner& WHEN(Run, r), \\\n objects_type args) \\\n { \\\n WHEN(Met, FETCH_TGT()); \\\n WHEN(Met, args.pop_front()); \\\n WHEN(Ret, return) \\\n (WHEN(Met, tgt.get()->*)method)( \\\n WHEN(Run, r) COMMA(Run) \\\n args \\\n ); \\\n return void_class; \\\n } \\\n }\n\n template <typename T, typename M>\n struct primitive\n {\n };\n\n \/* Python for these:\nfor met in ('true', 'false'):\n for ret in ('true', 'false'):\n for run in ('true', 'false'):\n print \" LIST_PRIMITIVE(%s, %s, %s);\" % (met, ret, run)\n *\/\n LIST_PRIMITIVE(true, true, true);\n LIST_PRIMITIVE(true, true, false);\n LIST_PRIMITIVE(true, false, true);\n LIST_PRIMITIVE(true, false, false);\n LIST_PRIMITIVE(false, true, true);\n LIST_PRIMITIVE(false, true, false);\n LIST_PRIMITIVE(false, false, true);\n LIST_PRIMITIVE(false, false, false);\n\n \/* Python for these:\nmax = 3\nfor ret in ('true', 'false'):\n for run in ('true', 'false'):\n for nargs in range(max + 1):\n for macro in ('PRIMITIVE ', 'PRIMITIVEF'):\n print \" %s(%s, %i, %s\" % (macro, ret, nargs, run),\n for i in range(max):\n print \", %s\" % str(i < nargs).lower(),\n print \");\"\n *\/\n PRIMITIVE(true , true, 0, true , false , false , false );\n PRIMITIVE(true , true, 1, true , true , false , false );\n PRIMITIVE(true , true, 2, true , true , true , false );\n PRIMITIVE(true , true, 3, true , true , true , true );\n PRIMITIVE(true , true, 0, false , false , false , false );\n PRIMITIVE(true , true, 1, false , true , false , false );\n PRIMITIVE(true , true, 2, false , true , true , false );\n PRIMITIVE(true , true, 3, false , true , true , true );\n PRIMITIVE(true , false, 0, true , false , false , false );\n PRIMITIVE(true , false, 1, true , true , false , false );\n PRIMITIVE(true , false, 2, true , true , true , false );\n PRIMITIVE(true , false, 3, true , true , true , true );\n PRIMITIVE(true , false, 0, false , false , false , false );\n PRIMITIVE(true , false, 1, false , true , false , false );\n PRIMITIVE(true , false, 2, false , true , true , false );\n PRIMITIVE(true , false, 3, false , true , true , true );\n PRIMITIVE(false, true, 0, true , false , false , false );\n PRIMITIVE(false, true, 1, true , true , false , false );\n PRIMITIVE(false, true, 2, true , true , true , false );\n PRIMITIVE(false, true, 3, true , true , true , true );\n PRIMITIVE(false, true, 0, false , false , false , false );\n PRIMITIVE(false, true, 1, false , true , false , false );\n PRIMITIVE(false, true, 2, false , true , true , false );\n PRIMITIVE(false, true, 3, false , true , true , true );\n PRIMITIVE(false, false, 0, true , false , false , false );\n PRIMITIVE(false, false, 1, true , true , false , false );\n PRIMITIVE(false, false, 2, true , true , true , false );\n PRIMITIVE(false, false, 3, true , true , true , true );\n PRIMITIVE(false, false, 0, false , false , false , false );\n PRIMITIVE(false, false, 1, false , true , false , false );\n PRIMITIVE(false, false, 2, false , true , true , false );\n PRIMITIVE(false, false, 3, false , true , true , true );\n }\n\n template <typename T>\n template <typename M>\n void CxxObject::Binder<T>::operator()(const libport::Symbol& name,\n M method)\n {\n \/\/ If make is unfound here, you passed an unsupported pointer type\n \/\/ to the binder.\n rObject p =\n new Primitive(boost::bind(primitive<T, M>::make,\n method, name, _1, _2));\n tgt_->slot_set(name, p);\n }\n\n\n template <typename T>\n inline void\n type_check(rObject o, const std::string& fun)\n {\n libport::shared_ptr<CxxObject> co = o.unsafe_cast<CxxObject>();\n \/\/ FIXME: I can't fill all the source type for now since some old\n \/\/ atoms don't define type_name for now\n if (!co)\n throw object::WrongArgumentType(T::type_name, \"Object\", fun);\n else if (!o->is_a<T>())\n throw object::WrongArgumentType(T::type_name, co->type_name_get(), fun);\n }\n\n template <>\n inline void\n type_check<Object>(rObject, const std::string&)\n {}\n\n template <>\n inline void\n type_check<List>(rObject, const std::string&)\n {}\n\n}\n\n#endif\n<commit_msg>Remove forgotten debug output.<commit_after>#ifndef CXX_OBJECT_HXX\n# define CXX_OBJECT_HXX\n\n# include <boost\/bind.hpp>\n\n# include <object\/atom.hh>\n# include <object\/primitive-class.hh>\n# include <object\/string-class.hh>\n# include <object\/object-class.hh>\n# include <object\/primitives.hh>\n\nnamespace object\n{\n template <typename T>\n bool CxxObject::add(const std::string& name, rObject& tgt)\n {\n initializers_get().push_back(new TypeInitializer<T>(name, tgt));\n return true;\n }\n\n template <typename T>\n CxxObject::TypeInitializer<T>::TypeInitializer(const std::string& name,\n rObject& tgt)\n : Initializer(tgt), name_(name)\n {}\n\n namespace\n {\n template <typename T>\n rObject cxx_object_clone(runner::Runner&, objects_type args)\n {\n CHECK_ARG_COUNT(1);\n rObject tgt = args[0];\n rObject res;\n if (tgt->is_a<T>())\n res = new T(tgt->as<T>());\n else\n res = new T();\n return res;\n }\n\n template <typename T>\n rObject cxx_object_id(runner::Runner&, objects_type args)\n {\n CHECK_ARG_COUNT(1);\n return args[0];\n }\n }\n\n template <typename T>\n void\n CxxObject::TypeInitializer<T>::create()\n {\n res_ = new Object();\n }\n\n template <typename T>\n rObject\n CxxObject::TypeInitializer<T>::make_class()\n {\n res_->proto_add(object_class);\n res_->slot_set(SYMBOL(protoName), new String(name_));\n res_->slot_set(SYMBOL(clone),\n rPrimitive(new Primitive(boost::bind(cxx_object_clone<T>,\n _1, _2))));\n Binder<T> b(res_);\n T::initialize(b);\n\n libport::Symbol conversion =\n libport::Symbol(std::string(\"as\") + name_.name_get());\n if (!res_->slot_locate(conversion, 0))\n res_->slot_set(conversion,\n rPrimitive(new Primitive(boost::bind(cxx_object_id<T>,\n _1, _2))));\n return res_;\n }\n\n template <typename T>\n libport::Symbol\n CxxObject::TypeInitializer<T>::name()\n {\n return name_;\n }\n\n \/\/ BINDER\n\n template <typename T>\n CxxObject::Binder<T>::Binder(rObject tgt)\n : tgt_(tgt)\n {}\n\n namespace\n {\n\n# define PRINT_true(X) X\n# define PRINT_false(X)\n# define PRINT_truetrue(X) X\n# define PRINT_falsetrue(X)\n# define PRINT_truefalse(X)\n# define PRINT_falsefalse(X)\n# define NPRINT_true(X)\n# define NPRINT_false(X) X\n\n# define WHEN(Cond, X) PRINT_##Cond(X)\n# define WHEN_NOT(Cond, X) NPRINT_##Cond(X)\n\n# define IF(Cond, Then, Else) WHEN(Cond, Then) WHEN_NOT(Cond, Else)\n\n# define COMMA_ ,\n# define COMMA(Cond) PRINT_##Cond(COMMA_)\n\n# define COMMA2(Cond1, Cond2) PRINT_##Cond1##Cond2(COMMA_)\n\n# define MET(Met, Name, Ret, Run, Arg1, Arg2, Arg3) \\\n IF(Ret, libport::shared_ptr<R>, void) \\\n (WHEN(Met, T::)*Name)( \\\n WHEN(Run, runner::Runner&) COMMA2(Run, Arg1) \\\n WHEN(Arg1, libport::shared_ptr<A1>) \\\n COMMA(Arg2) WHEN(Arg2, libport::shared_ptr<A2>) \\\n COMMA(Arg3) WHEN(Arg3, libport::shared_ptr<A3>) \\\n )\n\n#define GET_ARG(Met, N) \\\n type_check<A##N>(args[N WHEN_NOT(Met, - 1)], name.name_get()); \\\n libport::shared_ptr<A##N> a##N = \\\n args[N WHEN_NOT(Met, - 1)].unsafe_cast<A##N>(); \\\n assert(a##N);\n\n#define FETCH_TGT() \\\n type_check<T>(args[0], name.name_get()); \\\n libport::shared_ptr<T> tgt = args[0].unsafe_cast<T>();\n\n#define PRIMITIVE(Met, Ret, ArgsC, Run, Arg1, Arg2, Arg3) \\\n template <typename T \\\n COMMA(Ret) WHEN(Ret, typename R) \\\n COMMA(Arg1) WHEN(Arg1, typename A1) \\\n COMMA(Arg2) WHEN(Arg2, typename A2) \\\n COMMA(Arg3) WHEN(Arg3, typename A3) \\\n > \\\n struct primitive<T, MET(Met, , Ret, Run, Arg1, Arg2, Arg3)> \\\n { \\\n static rObject make( \\\n MET(Met, method, Ret, Run, Arg1, Arg2, Arg3), \\\n const libport::Symbol& IF(Met, name, WHEN(Arg1, name)), \\\n runner::Runner& WHEN(Run, r), \\\n objects_type args) \\\n { \\\n\t (void)args;\t\t\t\t\t\t\t\\\n assert(args.size() == \\\n ArgsC IF(Met, + 1, WHEN_NOT(Arg1, + 1))); \\\n WHEN(Met, FETCH_TGT()); \\\n WHEN(Arg1, GET_ARG(Met, 1)) \\\n WHEN(Arg2, GET_ARG(Met, 2)) \\\n WHEN(Arg3, GET_ARG(Met, 3)) \\\n WHEN(Ret, return) \\\n (WHEN(Met, tgt.get()->*)method)( \\\n WHEN(Run, r) COMMA2(Run, Arg1) \\\n WHEN(Arg1, a1) \\\n COMMA(Arg2) WHEN(Arg2, a2) \\\n COMMA(Arg3) WHEN(Arg3, a3) \\\n ); \\\n return void_class; \\\n } \\\n }\n\n#define LIST_MET(Name, Met, Ret, Run) \\\n IF(Ret, R, void) \\\n (WHEN(Met, T::)*Name)(WHEN(Run, runner::Runner&) COMMA(Run) \\\n objects_type) \\\n\n#define LIST_PRIMITIVE(Met, Ret, Run) \\\n template <typename T \\\n COMMA(Ret) WHEN(Ret, typename R) \\\n > \\\n struct primitive<T, LIST_MET(, Met, Ret, Run)> \\\n { \\\n static rObject make( \\\n LIST_MET(method, Met, Ret, Run), \\\n const libport::Symbol& name, \\\n runner::Runner& WHEN(Run, r), \\\n objects_type args) \\\n { \\\n WHEN(Met, FETCH_TGT()); \\\n WHEN(Met, args.pop_front()); \\\n WHEN(Ret, return) \\\n (WHEN(Met, tgt.get()->*)method)( \\\n WHEN(Run, r) COMMA(Run) \\\n args \\\n ); \\\n return void_class; \\\n } \\\n }\n\n template <typename T, typename M>\n struct primitive\n {\n };\n\n \/* Python for these:\nfor met in ('true', 'false'):\n for ret in ('true', 'false'):\n for run in ('true', 'false'):\n print \" LIST_PRIMITIVE(%s, %s, %s);\" % (met, ret, run)\n *\/\n LIST_PRIMITIVE(true, true, true);\n LIST_PRIMITIVE(true, true, false);\n LIST_PRIMITIVE(true, false, true);\n LIST_PRIMITIVE(true, false, false);\n LIST_PRIMITIVE(false, true, true);\n LIST_PRIMITIVE(false, true, false);\n LIST_PRIMITIVE(false, false, true);\n LIST_PRIMITIVE(false, false, false);\n\n \/* Python for these:\nmax = 3\nfor ret in ('true', 'false'):\n for run in ('true', 'false'):\n for nargs in range(max + 1):\n for macro in ('PRIMITIVE ', 'PRIMITIVEF'):\n print \" %s(%s, %i, %s\" % (macro, ret, nargs, run),\n for i in range(max):\n print \", %s\" % str(i < nargs).lower(),\n print \");\"\n *\/\n PRIMITIVE(true , true, 0, true , false , false , false );\n PRIMITIVE(true , true, 1, true , true , false , false );\n PRIMITIVE(true , true, 2, true , true , true , false );\n PRIMITIVE(true , true, 3, true , true , true , true );\n PRIMITIVE(true , true, 0, false , false , false , false );\n PRIMITIVE(true , true, 1, false , true , false , false );\n PRIMITIVE(true , true, 2, false , true , true , false );\n PRIMITIVE(true , true, 3, false , true , true , true );\n PRIMITIVE(true , false, 0, true , false , false , false );\n PRIMITIVE(true , false, 1, true , true , false , false );\n PRIMITIVE(true , false, 2, true , true , true , false );\n PRIMITIVE(true , false, 3, true , true , true , true );\n PRIMITIVE(true , false, 0, false , false , false , false );\n PRIMITIVE(true , false, 1, false , true , false , false );\n PRIMITIVE(true , false, 2, false , true , true , false );\n PRIMITIVE(true , false, 3, false , true , true , true );\n PRIMITIVE(false, true, 0, true , false , false , false );\n PRIMITIVE(false, true, 1, true , true , false , false );\n PRIMITIVE(false, true, 2, true , true , true , false );\n PRIMITIVE(false, true, 3, true , true , true , true );\n PRIMITIVE(false, true, 0, false , false , false , false );\n PRIMITIVE(false, true, 1, false , true , false , false );\n PRIMITIVE(false, true, 2, false , true , true , false );\n PRIMITIVE(false, true, 3, false , true , true , true );\n PRIMITIVE(false, false, 0, true , false , false , false );\n PRIMITIVE(false, false, 1, true , true , false , false );\n PRIMITIVE(false, false, 2, true , true , true , false );\n PRIMITIVE(false, false, 3, true , true , true , true );\n PRIMITIVE(false, false, 0, false , false , false , false );\n PRIMITIVE(false, false, 1, false , true , false , false );\n PRIMITIVE(false, false, 2, false , true , true , false );\n PRIMITIVE(false, false, 3, false , true , true , true );\n }\n\n template <typename T>\n template <typename M>\n void CxxObject::Binder<T>::operator()(const libport::Symbol& name,\n M method)\n {\n \/\/ If make is unfound here, you passed an unsupported pointer type\n \/\/ to the binder.\n rObject p =\n new Primitive(boost::bind(primitive<T, M>::make,\n method, name, _1, _2));\n tgt_->slot_set(name, p);\n }\n\n\n template <typename T>\n inline void\n type_check(rObject o, const std::string& fun)\n {\n libport::shared_ptr<CxxObject> co = o.unsafe_cast<CxxObject>();\n \/\/ FIXME: I can't fill all the source type for now since some old\n \/\/ atoms don't define type_name for now\n if (!co)\n throw object::WrongArgumentType(T::type_name, \"Object\", fun);\n else if (!o->is_a<T>())\n throw object::WrongArgumentType(T::type_name, co->type_name_get(), fun);\n }\n\n template <>\n inline void\n type_check<Object>(rObject, const std::string&)\n {}\n\n template <>\n inline void\n type_check<List>(rObject, const std::string&)\n {}\n\n}\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/\/ this source meant to test the behaviour of g++ compiler when there are (syntactical) errors in the source code\n\n\/\/ test01 - commenting #include line to pretend it was left out...\n\/\/ test02 - include but intentionally misspell std_lib_facilities.h\n\/\/ test03 - \"forget\" to terminate string on line 9 with a \"\n\/\/ test04 - call main() function using \"integer\" instead on \"int\" (this has to do with the expected result of the function)\n\/\/ test05 - use only one < for directing the \"input\" for cout - one might expect this to make cout want to \"replace\" the console? at least if\n\/\/\t\twriting a file that might be the case (ie. < is replace where << would be append)\n\n#include \"std_lib_facilities.h\"\n\nint main() {\n\tcout < \"Hello, World!\\n\";\n\tkeep_window_open();\n\treturn 0;\n}\n<commit_msg>setup for test06<commit_after>\/\/ this source meant to test the behaviour of g++ compiler when there are (syntactical) errors in the source code\n\n\/\/ test01 - commenting #include line to pretend it was left out...\n\/\/ test02 - include but intentionally misspell std_lib_facilities.h\n\/\/ test03 - \"forget\" to terminate string on line 9 with a \"\n\/\/ test04 - call main() function using \"integer\" instead on \"int\" (this has to do with the expected result of the function)\n\/\/ test05 - use only one < for directing the \"input\" for cout - one might expect this to make cout want to \"replace\" the console? at least if\n\/\/\t\twriting a file that might be the case (ie. < is replace where << would be append)\n\/\/ test06 - using a single quote ' rather than double \" to define the string\n\n#include \"std_lib_facilities.h\"\n\nint main() {\n\tcout << 'Hello, World!\\n';\n\tkeep_window_open();\n\treturn 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/**************************************************************************\n * Copyright(c) 1998-2007, ALICE Experiment at CERN, All rights reserved. *\n * *\n * Author: The ALICE Off-line Project. *\n * Contributors are mentioned in the code where appropriate. *\n * *\n * Permission to use, copy, modify and distribute this software and its *\n * documentation strictly for non-commercial purposes is hereby granted *\n * without fee, provided that the above copyright notice appears in all *\n * copies and that both the copyright notice and this permission notice *\n * appear in the supporting documentation. The authors make no claims *\n * about the suitability of this software for any purpose. It is *\n * provided \"as is\" without express or implied warranty. *\n **************************************************************************\/\n\n\/* $Id$ *\/\n\n\/\/-------------------------------------------------------------------------\n\/\/ Event handler for AOD input \n\/\/ Author: Andreas Morsch, CERN\n\/\/-------------------------------------------------------------------------\n\n#include <TTree.h>\n#include <TList.h>\n#include <TNamed.h>\n\n#include \"AliAODInputHandler.h\"\n#include \"AliAODEvent.h\"\n\nClassImp(AliAODInputHandler)\n\nstatic Option_t *gAODDataType = \"AOD\";\n\n\/\/______________________________________________________________________________\nAliAODInputHandler::AliAODInputHandler() :\n AliInputEventHandler(),\n fEvent(0),\n fFriends(new TList())\n{\n \/\/ Default constructor\n}\n\n\/\/______________________________________________________________________________\nAliAODInputHandler::AliAODInputHandler(const char* name, const char* title):\n AliInputEventHandler(name, title),\n fEvent(0),\n fFriends(new TList())\n{\n \/\/ Constructor\n}\n\n\/\/______________________________________________________________________________\nAliAODInputHandler::~AliAODInputHandler() \n{\n\/\/ Destructor\n fFriends->Delete();\n}\n\n\nBool_t AliAODInputHandler::Init(TTree* tree, Option_t* \/*opt*\/)\n{\n \/\/ Initialisation necessary for each new tree\n fTree = tree;\n TIter next(fFriends);\n TNamed* obj;\n \n if (!fTree) return kFALSE;\n \n while((obj = (TNamed*)next())) {\n\tif (fTree->GetTree()) {\n\t (fTree->GetTree())->AddFriend(\"aodTree\", obj->GetName());\n\t} else {\n\t fTree->AddFriend(\"aodTree\", obj->GetName());\n\t}\n }\n \n\n SwitchOffBranches();\n SwitchOnBranches();\n \n \/\/ Get pointer to AOD event\n if (fEvent) {\n delete fEvent;\n fEvent = 0;\n }\n fEvent = new AliAODEvent();\n\n fEvent->ReadFromTree(fTree);\n return kTRUE;\n}\n\nBool_t AliAODInputHandler::BeginEvent(Long64_t \/*entry*\/)\n{\n \/\/\n \/\/if (fTree) fTree->BranchRef();\n return kTRUE;\n}\n\nvoid AliAODInputHandler::AddFriend(char* filename)\n{\n \/\/ Add a friend tree \n TNamed* obj = new TNamed(filename, filename);\n fFriends->Add(obj);\n}\n\nOption_t *AliAODInputHandler::GetDataType() const\n{\n\/\/ Returns handled data type.\n return gAODDataType;\n}\n<commit_msg>Corrected handling of friens trees in Input (A. Dainese)<commit_after>\/**************************************************************************\n * Copyright(c) 1998-2007, ALICE Experiment at CERN, All rights reserved. *\n * *\n * Author: The ALICE Off-line Project. *\n * Contributors are mentioned in the code where appropriate. *\n * *\n * Permission to use, copy, modify and distribute this software and its *\n * documentation strictly for non-commercial purposes is hereby granted *\n * without fee, provided that the above copyright notice appears in all *\n * copies and that both the copyright notice and this permission notice *\n * appear in the supporting documentation. The authors make no claims *\n * about the suitability of this software for any purpose. It is *\n * provided \"as is\" without express or implied warranty. *\n **************************************************************************\/\n\n\/* $Id$ *\/\n\n\/\/-------------------------------------------------------------------------\n\/\/ Event handler for AOD input \n\/\/ Author: Andreas Morsch, CERN\n\/\/-------------------------------------------------------------------------\n\n#include <TTree.h>\n#include <TList.h>\n#include <TNamed.h>\n#include <TFile.h>\n\n#include \"AliAODInputHandler.h\"\n#include \"AliAODEvent.h\"\n\nClassImp(AliAODInputHandler)\n\nstatic Option_t *gAODDataType = \"AOD\";\n\n\/\/______________________________________________________________________________\nAliAODInputHandler::AliAODInputHandler() :\n AliInputEventHandler(),\n fEvent(0),\n fFriends(new TList())\n{\n \/\/ Default constructor\n}\n\n\/\/______________________________________________________________________________\nAliAODInputHandler::AliAODInputHandler(const char* name, const char* title):\n AliInputEventHandler(name, title),\n fEvent(0),\n fFriends(new TList())\n{\n \/\/ Constructor\n}\n\n\/\/______________________________________________________________________________\nAliAODInputHandler::~AliAODInputHandler() \n{\n\/\/ Destructor\n fFriends->Delete();\n}\n\n\nBool_t AliAODInputHandler::Init(TTree* tree, Option_t* \/*opt*\/)\n{\n \/\/ Initialisation necessary for each new tree\n fTree = tree;\n TIter next(fFriends);\n TNamed* obj;\n \n if (!fTree) return kFALSE;\n \n TString aodTreeFName,aodFriendTreeFName;\n\n while((obj = (TNamed*)next())) {\n\tif (fTree->GetTree()) {\n\t aodTreeFName = (fTree->GetTree()->GetCurrentFile())->GetName();\n\t aodFriendTreeFName = aodTreeFName;\n\t aodFriendTreeFName.ReplaceAll(\"AliAOD.root\",obj->GetName());\n\t aodFriendTreeFName.ReplaceAll(\"AliAODs.root\",obj->GetName());\n\t (fTree->GetTree())->AddFriend(\"aodTree\", aodFriendTreeFName.Data());\n\t} else {\n\t aodTreeFName = (fTree->GetCurrentFile())->GetName();\n\t aodFriendTreeFName = aodTreeFName;\n\t aodFriendTreeFName.ReplaceAll(\"AliAOD.root\",obj->GetName());\n\t aodFriendTreeFName.ReplaceAll(\"AliAODs.root\",obj->GetName());\n\t fTree->AddFriend(\"aodTree\", aodFriendTreeFName.Data());\n\t}\n }\n \n\n SwitchOffBranches();\n SwitchOnBranches();\n \n \/\/ Get pointer to AOD event\n if (fEvent) {\n delete fEvent;\n fEvent = 0;\n }\n fEvent = new AliAODEvent();\n\n fEvent->ReadFromTree(fTree);\n return kTRUE;\n}\n\nBool_t AliAODInputHandler::BeginEvent(Long64_t \/*entry*\/)\n{\n \/\/\n \/\/if (fTree) fTree->BranchRef();\n return kTRUE;\n}\n\nvoid AliAODInputHandler::AddFriend(char* filename)\n{\n \/\/ Add a friend tree \n TNamed* obj = new TNamed(filename, filename);\n fFriends->Add(obj);\n}\n\nOption_t *AliAODInputHandler::GetDataType() const\n{\n\/\/ Returns handled data type.\n return gAODDataType;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ =============================================================================\n\/\/ PROJECT CHRONO - http:\/\/projectchrono.org\n\/\/\n\/\/ Copyright (c) 2014 projectchrono.org\n\/\/ All right reserved.\n\/\/\n\/\/ Use of this source code is governed by a BSD-style license that can be found\n\/\/ in the LICENSE file at the top level of the distribution and at\n\/\/ http:\/\/projectchrono.org\/license-chrono.txt.\n\/\/\n\/\/ =============================================================================\n\/\/ Authors: Alessandro Tasora, Radu Serban\n\/\/ =============================================================================\n\n#include \"chrono\/physics\/ChGlobal.h\"\n#include \"chrono\/physics\/ChLink.h\"\n#include \"chrono\/physics\/ChSystem.h\"\n\nnamespace chrono {\n\n\/\/ Register into the object factory, to enable run-time dynamic creation and persistence\nChClassRegisterABSTRACT<ChLink> a_registration_ChLink;\n\nChLink::ChLink(const ChLink& other) : ChLinkBase(other) {\n Body1 = NULL;\n Body2 = NULL;\n\n react_force = other.react_force;\n react_torque = other.react_torque;\n}\n\nvoid ChLink::UpdateTime(double time) {\n ChTime = time;\n}\n\nvoid ChLink::Update(double time, bool update_assets) {\n \/\/ 1 -\n UpdateTime(time);\n}\n\nvoid ChLink::Update(bool update_assets) {\n Update(ChTime, update_assets); \/\/ use the same time\n}\n\nvoid ChLink::ArchiveOUT(ChArchiveOut& marchive) {\n \/\/ version number\n marchive.VersionWrite(1);\n\n \/\/ serialize parent class\n ChLinkBase::ArchiveOUT(marchive);\n\n \/\/ serialize all member data:\n}\n\nvoid ChLink::ArchiveIN(ChArchiveIn& marchive) {\n \/\/ version number\n int version = marchive.VersionRead();\n\n \/\/ deserialize parent class\n ChLinkBase::ArchiveIN(marchive);\n\n \/\/ deserialize all member data:\n}\n\n} \/\/ end namespace chrono\n<commit_msg>Update assets inserted in ChLink objects too (just like for assets added to ChBody stuff etc.)<commit_after>\/\/ =============================================================================\n\/\/ PROJECT CHRONO - http:\/\/projectchrono.org\n\/\/\n\/\/ Copyright (c) 2014 projectchrono.org\n\/\/ All right reserved.\n\/\/\n\/\/ Use of this source code is governed by a BSD-style license that can be found\n\/\/ in the LICENSE file at the top level of the distribution and at\n\/\/ http:\/\/projectchrono.org\/license-chrono.txt.\n\/\/\n\/\/ =============================================================================\n\/\/ Authors: Alessandro Tasora, Radu Serban\n\/\/ =============================================================================\n\n#include \"chrono\/physics\/ChGlobal.h\"\n#include \"chrono\/physics\/ChLink.h\"\n#include \"chrono\/physics\/ChSystem.h\"\n\nnamespace chrono {\n\n\/\/ Register into the object factory, to enable run-time dynamic creation and persistence\nChClassRegisterABSTRACT<ChLink> a_registration_ChLink;\n\nChLink::ChLink(const ChLink& other) : ChLinkBase(other) {\n Body1 = NULL;\n Body2 = NULL;\n\n react_force = other.react_force;\n react_torque = other.react_torque;\n}\n\nvoid ChLink::UpdateTime(double time) {\n ChTime = time;\n}\n\nvoid ChLink::Update(double time, bool update_assets) {\n \/\/ 1 -\n UpdateTime(time);\n\n \/\/ This will update assets\n ChPhysicsItem::Update(ChTime, update_assets);\n}\n\nvoid ChLink::Update(bool update_assets) {\n Update(ChTime, update_assets); \/\/ use the same time\n}\n\nvoid ChLink::ArchiveOUT(ChArchiveOut& marchive) {\n \/\/ version number\n marchive.VersionWrite(1);\n\n \/\/ serialize parent class\n ChLinkBase::ArchiveOUT(marchive);\n\n \/\/ serialize all member data:\n}\n\nvoid ChLink::ArchiveIN(ChArchiveIn& marchive) {\n \/\/ version number\n int version = marchive.VersionRead();\n\n \/\/ deserialize parent class\n ChLinkBase::ArchiveIN(marchive);\n\n \/\/ deserialize all member data:\n}\n\n} \/\/ end namespace chrono\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright(c) Sophist Solutions, Inc. 1990-2021. All rights reserved\n *\/\n#include \"..\/..\/StroikaPreComp.h\"\n\n#include \"..\/..\/Characters\/StringBuilder.h\"\n#include \"..\/..\/DataExchange\/Variant\/JSON\/Reader.h\"\n#include \"..\/..\/DataExchange\/Variant\/JSON\/Writer.h\"\n\n#include \"Schema.h\"\n\nusing std::byte;\n\nusing namespace Stroika::Foundation;\nusing namespace Stroika::Foundation::Characters;\nusing namespace Stroika::Foundation::Database;\nusing namespace Stroika::Foundation::DataExchange;\n\n\/\/ Comment this in to turn on aggressive noisy DbgTrace in this module\n\/\/#define USE_NOISY_TRACE_IN_THIS_MODULE_ 1\n\n\/*\n ********************************************************************************\n *************************** ORM::Schema::CatchAllField *************************\n ********************************************************************************\n *\/\nORM::Schema::CatchAllField::CatchAllField ()\n{\n fName = L\"_other_fields_\"sv;\n fVariantType = VariantValue::Type::eBLOB; \/\/ can be BLOB or String, but BLOB more compact\/efficient\n}\n\nfunction<VariantValue (const Mapping<String, VariantValue>& fields2Map)> ORM::Schema::CatchAllField::GetEffectiveRawToCombined () const\n{\n if (fMapRawFieldsToCombinedField != nullptr) {\n return fMapRawFieldsToCombinedField;\n }\n Require (fVariantType);\n switch (*fVariantType) {\n case VariantValue::eBLOB:\n return kDefaultMapper_RawToCombined_BLOB;\n case VariantValue::eString:\n return kDefaultMapper_RawToCombined_String;\n default:\n RequireNotReached ();\n return nullptr;\n }\n}\n\nfunction<Mapping<String, VariantValue> (const VariantValue& map2Fields)> ORM::Schema::CatchAllField::GetEffectiveCombinedToRaw () const\n{\n if (fMapCombinedFieldToRawFields != nullptr) {\n return fMapCombinedFieldToRawFields;\n }\n Require (fVariantType);\n switch (*fVariantType) {\n case VariantValue::eBLOB:\n return kDefaultMapper_CombinedToRaw_BLOB;\n case VariantValue::eString:\n return kDefaultMapper_CombinedToRaw_String;\n default:\n RequireNotReached ();\n return nullptr;\n }\n}\n\nVariantValue ORM::Schema::CatchAllField::kDefaultMapper_RawToCombined_BLOB (const Mapping<String, VariantValue>& fields2Map)\n{\n return DataExchange::Variant::JSON::Writer{}.WriteAsBLOB (VariantValue{fields2Map});\n}\n\nVariantValue ORM::Schema::CatchAllField::kDefaultMapper_RawToCombined_String (const Mapping<String, VariantValue>& fields2Map)\n{\n return DataExchange::Variant::JSON::Writer{}.WriteAsString (VariantValue{fields2Map});\n}\n\nMapping<String, VariantValue> ORM::Schema::CatchAllField::kDefaultMapper_CombinedToRaw_BLOB (const VariantValue& fields2Map)\n{\n return DataExchange::Variant::JSON::Reader{}.Read (fields2Map.As<Memory::BLOB> ()).As<Mapping<String, VariantValue>> ();\n}\n\nMapping<String, VariantValue> ORM::Schema::CatchAllField::kDefaultMapper_CombinedToRaw_String (const VariantValue& fields2Map)\n{\n return DataExchange::Variant::JSON::Reader{}.Read (fields2Map.As<String> ()).As<Mapping<String, VariantValue>> ();\n}\n\n\/*\n ********************************************************************************\n ****************************** ORM::Schema::Table ******************************\n ********************************************************************************\n *\/\nMapping<String, VariantValue> ORM::Schema::Table::MapToDB (const Mapping<String, VariantValue>& fields) const\n{\n#if USE_NOISY_TRACE_IN_THIS_MODULE_\n TraceContextBumper ctx{\"ORM::Schema::Table::MapToDB\", Stroika_Foundation_Debug_OptionalizeTraceArgs (L\"fields=%s\", Characters::ToString (fields).c_str ())};\n#endif\n Mapping<String, VariantValue> resultFields;\n Set<String> usedFields; \/\/ must track outside of resultFields.Keys () cuz input key could differ from output\n for (const auto& fi : fNamedFields) {\n String srcKey = fi.GetVariantValueFieldName ();\n if (auto oFieldVal = fields.Lookup (srcKey)) {\n if (fi.fVariantType) {\n resultFields.Add (fi.fName, oFieldVal->ConvertTo (*fi.fVariantType));\n }\n else {\n resultFields.Add (fi.fName, *oFieldVal);\n }\n usedFields += srcKey;\n }\n else if (fi.fRequired) {\n \/\/ throw or assert?\n AssertNotReached ();\n }\n }\n \/\/ now fold remaining fields into special 'extra' field (for structured non-indexed\/non-searchable data)\n Set<String> fields2Accumulate = Set<String>{fields.Keys ()} - usedFields;\n if (fSpecialCatchAll.has_value () and not fields2Accumulate.empty ()) {\n Mapping<String, VariantValue> extraFields;\n for (auto i : fields2Accumulate) {\n extraFields.Add (i, *fields.Lookup (i));\n }\n \/\/ Combine fields into a new variant value (typically json string)\n resultFields.Add (fSpecialCatchAll->fName, fSpecialCatchAll->GetEffectiveRawToCombined () (extraFields));\n }\n else {\n Require (fields2Accumulate.empty () or fSpecialCatchAll.has_value ());\n }\n#if USE_NOISY_TRACE_IN_THIS_MODULE_\n DbgTrace (L\"returning: %s\", Characters::ToString (vv).c_str ());\n#endif\n return resultFields;\n}\n\nMapping<String, VariantValue> ORM::Schema::Table::MapFromDB (const Mapping<String, VariantValue>& fields) const\n{\n#if USE_NOISY_TRACE_IN_THIS_MODULE_\n TraceContextBumper ctx{\"ORM::Schema::Table::MapFromDB\", Stroika_Foundation_Debug_OptionalizeTraceArgs (L\"fields=%s\", Characters::ToString (fields).c_str ())};\n#endif\n Mapping<String, VariantValue> resultFields;\n for (const auto& fi : fNamedFields) {\n if (auto oFieldVal = fields.Lookup (fi.fName)) {\n String toName = fi.GetVariantValueFieldName ();\n if (fi.fVariantType) {\n resultFields.Add (toName, oFieldVal->ConvertTo (*fi.fVariantType));\n }\n else {\n resultFields.Add (toName, *oFieldVal);\n }\n }\n else if (fi.fRequired) {\n \/\/ throw or assert?\n }\n }\n \/\/ now fold remaining fields into special 'extra' field (for structured non-indexed\/non-searchable data)\n if (fSpecialCatchAll.has_value ()) {\n if (auto o = fields.Lookup (fSpecialCatchAll->fName)) {\n \/\/ no need to map names here because that is for DBRep to\/from VariantValue rep name mapping and there is none for these fields\n resultFields.AddAll (fSpecialCatchAll->GetEffectiveCombinedToRaw () (*o));\n }\n }\n else {\n \/\/ @todo maybe check fNamedFields contains all the actual fields??? Maybe OK to not check\n }\n return resultFields;\n}\n\nauto ORM::Schema::Table::GetIDField () const -> optional<Field>\n{\n return fNamedFields.First<Field> ([] (const Field& fi) -> optional<Field> {\n if (fi.fIsKeyField) {\n return fi;\n }\n return nullopt;\n });\n}\n\n\/*\n ********************************************************************************\n ************************* ORM::Schema::StandardSQLStatements *******************\n ********************************************************************************\n *\/\nnamespace {\n String GetSQLiteFldType_ (const ORM::Schema::Field& f)\n {\n if (f.fVariantType) {\n switch (*f.fVariantType) {\n case VariantValue::eBLOB:\n return L\"BLOB\"sv;\n case VariantValue::eDate:\n case VariantValue::eDateTime:\n case VariantValue::eString:\n return L\"TEXT\"sv;\n case VariantValue::eBoolean:\n case VariantValue::eInteger:\n case VariantValue::eUnsignedInteger:\n return L\"INT\"sv;\n case VariantValue::eFloat:\n return L\"REAL\"sv;\n }\n }\n return L\"TEXT\"sv; \/\/ @todo better\n }\n}\n\nString ORM::Schema::StandardSQLStatements::CreateTable () const\n{\n StringBuilder sb;\n\n \/*\n * CREATE TABLE DEVICES(\n * ID BLOB PRIMARY KEY DEFAULT(randomblob(16)),\n * NAME TEXT NOT NULL\n * );\n *\/\n sb += L\"CREATE TABLE \" + fTable.fName + L\" (\";\n bool firstField = true;\n auto addField = [&] (const Field& fi) {\n if (firstField) {\n firstField = false;\n }\n else {\n sb += L\", \";\n }\n sb += fi.fName + L\" \";\n sb += GetSQLiteFldType_ (fi) + L\" \";\n if (fi.fIsKeyField == true) {\n sb += L\" PRIMARY KEY\";\n }\n if (fi.fDefaultExpression) {\n sb += L\" DEFAULT(\" + *fi.fDefaultExpression + L\")\";\n }\n if (fi.fNotNull == true) {\n sb += L\" NOT NULL\";\n }\n };\n for (const Field& i : fTable.fNamedFields) {\n addField (i);\n }\n if (fTable.fSpecialCatchAll) {\n addField (*fTable.fSpecialCatchAll);\n }\n sb += L\");\";\n\n return sb.str ();\n}\n\nString ORM::Schema::StandardSQLStatements::Insert () const\n{\n StringBuilder sb;\n\n \/*\n * INSERT INTO DEVICES (name) values (:NAME);\n *\/\n sb += L\"INSERT INTO \" + fTable.fName + L\" (\";\n bool firstField = true;\n auto addFieldName = [&] (const Field& fi) {\n if (firstField) {\n firstField = false;\n }\n else {\n sb += L\", \";\n }\n sb += fi.fName;\n };\n for (const Field& i : fTable.fNamedFields) {\n addFieldName (i);\n }\n if (fTable.fSpecialCatchAll) {\n addFieldName (*fTable.fSpecialCatchAll);\n }\n sb += L\") VALUES (\";\n firstField = true;\n auto addFieldValueVariableName = [&] (const Field& fi) {\n if (firstField) {\n firstField = false;\n }\n else {\n sb += L\", \";\n }\n sb += L\":\" + fi.fName;\n };\n for (const Field& i : fTable.fNamedFields) {\n addFieldValueVariableName (i);\n }\n if (fTable.fSpecialCatchAll) {\n addFieldValueVariableName (*fTable.fSpecialCatchAll);\n }\n sb += L\");\";\n return sb.str ();\n}\n\nString ORM::Schema::StandardSQLStatements::DeleteByID () const\n{\n StringBuilder sb;\n \/*\n * Delete from DEVICES (ID) where ID=:ID;\n *\/\n Field indexField = Memory::ValueOf (fTable.GetIDField ());\n sb += L\"DELETE FROM \" + fTable.fName + L\" WHERE \" + indexField.fName + L\"=:\" + indexField.fName + L\";\";\n return sb.str ();\n}\n\nString ORM::Schema::StandardSQLStatements::GetByID () const\n{\n StringBuilder sb;\n \/*\n * SELECT * FROM DEVICES where ID=:ID;\n *\/\n Field indexField = Memory::ValueOf (fTable.GetIDField ());\n sb += L\"SELECT * FROM \" + fTable.fName + L\" WHERE \" + indexField.fName + L\"=:\" + indexField.fName + L\";\";\n return sb.str ();\n}\n\nString ORM::Schema::StandardSQLStatements::UpdateByID () const\n{\n StringBuilder sb;\n \/*\n * UPDATE Customers\n * SET ContactName = 'Alfred Schmidt', City= 'Frankfurt'\n * WHERE ID=:ID;\n *\/\n Field indexField = Memory::ValueOf (fTable.GetIDField ());\n sb += L\"UPDATE \" + fTable.fName;\n bool firstField = true;\n auto addSetField = [&] (const Field& fi) {\n if (firstField) {\n firstField = false;\n sb += L\" SET \";\n }\n else {\n sb += L\", \";\n }\n sb += fi.fName + L\"=:\" + fi.fName;\n };\n for (const Field& i : fTable.fNamedFields) {\n if (not i.fIsKeyField) {\n addSetField (i);\n }\n }\n if (fTable.fSpecialCatchAll) {\n addSetField (*fTable.fSpecialCatchAll);\n }\n sb += L\" WHERE \" + indexField.fName + L\"=:\" + indexField.fName + L\";\";\n return sb.str ();\n}\n\nString ORM::Schema::StandardSQLStatements::GetAllElements () const\n{\n StringBuilder sb;\n \/*\n * Select * from DEVICES;\n *\/\n sb += L\"SELECT * FROM \" + fTable.fName + L\";\";\n return sb.str ();\n}\n<commit_msg>cosmetic<commit_after>\/*\n * Copyright(c) Sophist Solutions, Inc. 1990-2021. All rights reserved\n *\/\n#include \"..\/..\/StroikaPreComp.h\"\n\n#include \"..\/..\/Characters\/StringBuilder.h\"\n#include \"..\/..\/DataExchange\/Variant\/JSON\/Reader.h\"\n#include \"..\/..\/DataExchange\/Variant\/JSON\/Writer.h\"\n\n#include \"Schema.h\"\n\nusing std::byte;\n\nusing namespace Stroika::Foundation;\nusing namespace Stroika::Foundation::Characters;\nusing namespace Stroika::Foundation::Database;\nusing namespace Stroika::Foundation::DataExchange;\n\n\/\/ Comment this in to turn on aggressive noisy DbgTrace in this module\n\/\/#define USE_NOISY_TRACE_IN_THIS_MODULE_ 1\n\n\/*\n ********************************************************************************\n *************************** ORM::Schema::CatchAllField *************************\n ********************************************************************************\n *\/\nORM::Schema::CatchAllField::CatchAllField ()\n{\n fName = L\"_other_fields_\"sv;\n fVariantType = VariantValue::Type::eBLOB; \/\/ can be BLOB or String, but BLOB more compact\/efficient\n}\n\nfunction<VariantValue (const Mapping<String, VariantValue>& fields2Map)> ORM::Schema::CatchAllField::GetEffectiveRawToCombined () const\n{\n if (fMapRawFieldsToCombinedField != nullptr) {\n return fMapRawFieldsToCombinedField;\n }\n Require (fVariantType);\n switch (*fVariantType) {\n case VariantValue::eBLOB:\n return kDefaultMapper_RawToCombined_BLOB;\n case VariantValue::eString:\n return kDefaultMapper_RawToCombined_String;\n default:\n RequireNotReached ();\n return nullptr;\n }\n}\n\nfunction<Mapping<String, VariantValue> (const VariantValue& map2Fields)> ORM::Schema::CatchAllField::GetEffectiveCombinedToRaw () const\n{\n if (fMapCombinedFieldToRawFields != nullptr) {\n return fMapCombinedFieldToRawFields;\n }\n Require (fVariantType);\n switch (*fVariantType) {\n case VariantValue::eBLOB:\n return kDefaultMapper_CombinedToRaw_BLOB;\n case VariantValue::eString:\n return kDefaultMapper_CombinedToRaw_String;\n default:\n RequireNotReached ();\n return nullptr;\n }\n}\n\nVariantValue ORM::Schema::CatchAllField::kDefaultMapper_RawToCombined_BLOB (const Mapping<String, VariantValue>& fields2Map)\n{\n return DataExchange::Variant::JSON::Writer{}.WriteAsBLOB (VariantValue{fields2Map});\n}\n\nVariantValue ORM::Schema::CatchAllField::kDefaultMapper_RawToCombined_String (const Mapping<String, VariantValue>& fields2Map)\n{\n return DataExchange::Variant::JSON::Writer{}.WriteAsString (VariantValue{fields2Map});\n}\n\nMapping<String, VariantValue> ORM::Schema::CatchAllField::kDefaultMapper_CombinedToRaw_BLOB (const VariantValue& fields2Map)\n{\n return DataExchange::Variant::JSON::Reader{}.Read (fields2Map.As<Memory::BLOB> ()).As<Mapping<String, VariantValue>> ();\n}\n\nMapping<String, VariantValue> ORM::Schema::CatchAllField::kDefaultMapper_CombinedToRaw_String (const VariantValue& fields2Map)\n{\n return DataExchange::Variant::JSON::Reader{}.Read (fields2Map.As<String> ()).As<Mapping<String, VariantValue>> ();\n}\n\n\/*\n ********************************************************************************\n ****************************** ORM::Schema::Table ******************************\n ********************************************************************************\n *\/\nMapping<String, VariantValue> ORM::Schema::Table::MapToDB (const Mapping<String, VariantValue>& fields) const\n{\n#if USE_NOISY_TRACE_IN_THIS_MODULE_\n TraceContextBumper ctx{\"ORM::Schema::Table::MapToDB\", Stroika_Foundation_Debug_OptionalizeTraceArgs (L\"fields=%s\", Characters::ToString (fields).c_str ())};\n#endif\n Mapping<String, VariantValue> resultFields;\n Set<String> usedFields; \/\/ must track outside of resultFields.Keys () cuz input key could differ from output\n for (const auto& fi : fNamedFields) {\n String srcKey = fi.GetVariantValueFieldName ();\n if (auto oFieldVal = fields.Lookup (srcKey)) {\n if (fi.fVariantType) {\n resultFields.Add (fi.fName, oFieldVal->ConvertTo (*fi.fVariantType));\n }\n else {\n resultFields.Add (fi.fName, *oFieldVal);\n }\n usedFields += srcKey;\n }\n else if (fi.fRequired) {\n \/\/ throw or assert?\n AssertNotReached ();\n }\n }\n \/\/ now fold remaining fields into special 'extra' field (for structured non-indexed\/non-searchable data)\n Set<String> fields2Accumulate = Set<String>{fields.Keys ()} - usedFields;\n if (fSpecialCatchAll.has_value () and not fields2Accumulate.empty ()) {\n Mapping<String, VariantValue> extraFields;\n for (auto i : fields2Accumulate) {\n extraFields.Add (i, *fields.Lookup (i));\n }\n \/\/ Combine fields into a new variant value (typically json string)\n resultFields.Add (fSpecialCatchAll->fName, fSpecialCatchAll->GetEffectiveRawToCombined () (extraFields));\n }\n else {\n Require (fields2Accumulate.empty () or fSpecialCatchAll.has_value ());\n }\n#if USE_NOISY_TRACE_IN_THIS_MODULE_\n DbgTrace (L\"returning: %s\", Characters::ToString (vv).c_str ());\n#endif\n return resultFields;\n}\n\nMapping<String, VariantValue> ORM::Schema::Table::MapFromDB (const Mapping<String, VariantValue>& fields) const\n{\n#if USE_NOISY_TRACE_IN_THIS_MODULE_\n TraceContextBumper ctx{\"ORM::Schema::Table::MapFromDB\", Stroika_Foundation_Debug_OptionalizeTraceArgs (L\"fields=%s\", Characters::ToString (fields).c_str ())};\n#endif\n Mapping<String, VariantValue> resultFields;\n for (const auto& fi : fNamedFields) {\n if (auto oFieldVal = fields.Lookup (fi.fName)) {\n String toName = fi.GetVariantValueFieldName ();\n if (fi.fVariantType) {\n resultFields.Add (toName, oFieldVal->ConvertTo (*fi.fVariantType));\n }\n else {\n resultFields.Add (toName, *oFieldVal);\n }\n }\n else if (fi.fRequired) {\n \/\/ throw or assert?\n }\n }\n \/\/ now fold remaining fields into special 'extra' field (for structured non-indexed\/non-searchable data)\n if (fSpecialCatchAll.has_value ()) {\n if (auto o = fields.Lookup (fSpecialCatchAll->fName)) {\n \/\/ no need to map names here because that is for DBRep to\/from VariantValue rep name mapping and there is none for these fields\n resultFields.AddAll (fSpecialCatchAll->GetEffectiveCombinedToRaw () (*o));\n }\n }\n else {\n \/\/ @todo maybe check fNamedFields contains all the actual fields??? Maybe OK to not check\n }\n return resultFields;\n}\n\nauto ORM::Schema::Table::GetIDField () const -> optional<Field>\n{\n return fNamedFields.First<Field> ([] (const Field& fi) -> optional<Field> {\n if (fi.fIsKeyField) {\n return fi;\n }\n return nullopt;\n });\n}\n\n\/*\n ********************************************************************************\n ************************* ORM::Schema::StandardSQLStatements *******************\n ********************************************************************************\n *\/\nnamespace {\n String GetSQLiteFldType_ (const ORM::Schema::Field& f)\n {\n if (f.fVariantType) {\n switch (*f.fVariantType) {\n case VariantValue::eBLOB:\n return L\"BLOB\"sv;\n case VariantValue::eDate:\n case VariantValue::eDateTime:\n case VariantValue::eString:\n return L\"TEXT\"sv;\n case VariantValue::eBoolean:\n case VariantValue::eInteger:\n case VariantValue::eUnsignedInteger:\n return L\"INT\"sv;\n case VariantValue::eFloat:\n return L\"REAL\"sv;\n }\n }\n return L\"TEXT\"sv; \/\/ @todo better\n }\n}\n\nString ORM::Schema::StandardSQLStatements::CreateTable () const\n{\n StringBuilder sb;\n\n \/*\n * CREATE TABLE DEVICES(\n * ID BLOB PRIMARY KEY DEFAULT(randomblob(16)),\n * NAME TEXT NOT NULL\n * );\n *\/\n sb += L\"CREATE TABLE \" + fTable.fName + L\" (\";\n bool firstField = true;\n auto addField = [&] (const Field& fi) {\n if (firstField) {\n firstField = false;\n }\n else {\n sb += L\", \";\n }\n sb += fi.fName + L\" \";\n sb += GetSQLiteFldType_ (fi) + L\" \";\n if (fi.fIsKeyField == true) {\n sb += L\" PRIMARY KEY\";\n }\n if (fi.fDefaultExpression) {\n sb += L\" DEFAULT(\" + *fi.fDefaultExpression + L\")\";\n }\n if (fi.fNotNull == true) {\n sb += L\" NOT NULL\";\n }\n };\n for (const Field& i : fTable.fNamedFields) {\n addField (i);\n }\n if (fTable.fSpecialCatchAll) {\n addField (*fTable.fSpecialCatchAll);\n }\n sb += L\");\";\n\n return sb.str ();\n}\n\nString ORM::Schema::StandardSQLStatements::Insert () const\n{\n StringBuilder sb;\n\n \/*\n * INSERT INTO DEVICES (name) values (:NAME);\n *\/\n sb += L\"INSERT INTO \" + fTable.fName + L\" (\";\n bool firstField = true;\n auto addFieldName = [&] (const Field& fi) {\n if (firstField) {\n firstField = false;\n }\n else {\n sb += L\", \";\n }\n sb += fi.fName;\n };\n for (const Field& i : fTable.fNamedFields) {\n addFieldName (i);\n }\n if (fTable.fSpecialCatchAll) {\n addFieldName (*fTable.fSpecialCatchAll);\n }\n sb += L\") VALUES (\";\n firstField = true;\n auto addFieldValueVariableName = [&] (const Field& fi) {\n if (firstField) {\n firstField = false;\n }\n else {\n sb += L\", \";\n }\n sb += L\":\" + fi.fName;\n };\n for (const Field& i : fTable.fNamedFields) {\n addFieldValueVariableName (i);\n }\n if (fTable.fSpecialCatchAll) {\n addFieldValueVariableName (*fTable.fSpecialCatchAll);\n }\n sb += L\");\";\n return sb.str ();\n}\n\nString ORM::Schema::StandardSQLStatements::DeleteByID () const\n{\n StringBuilder sb;\n \/*\n * Delete from DEVICES (ID) where ID=:ID;\n *\/\n Field indexField = Memory::ValueOf (fTable.GetIDField ());\n sb += L\"DELETE FROM \" + fTable.fName + L\" WHERE \" + indexField.fName + L\"=:\" + indexField.fName + L\";\";\n return sb.str ();\n}\n\nString ORM::Schema::StandardSQLStatements::GetByID () const\n{\n StringBuilder sb;\n \/*\n * SELECT * FROM DEVICES where ID=:ID;\n *\/\n Field indexField = Memory::ValueOf (fTable.GetIDField ());\n sb += L\"SELECT * FROM \" + fTable.fName + L\" WHERE \" + indexField.fName + L\"=:\" + indexField.fName + L\";\";\n return sb.str ();\n}\n\nString ORM::Schema::StandardSQLStatements::UpdateByID () const\n{\n StringBuilder sb;\n \/*\n * UPDATE Customers\n * SET ContactName = 'Alfred Schmidt', City= 'Frankfurt'\n * WHERE ID=:ID;\n *\/\n Field indexField = Memory::ValueOf (fTable.GetIDField ());\n sb += L\"UPDATE \" + fTable.fName;\n bool firstField = true;\n auto addSetField = [&] (const Field& fi) {\n if (firstField) {\n firstField = false;\n sb += L\" SET \";\n }\n else {\n sb += L\", \";\n }\n sb += fi.fName + L\"=:\" + fi.fName;\n };\n for (const Field& i : fTable.fNamedFields) {\n if (not i.fIsKeyField) {\n addSetField (i);\n }\n }\n if (fTable.fSpecialCatchAll) {\n addSetField (*fTable.fSpecialCatchAll);\n }\n sb += L\" WHERE \" + indexField.fName + L\"=:\" + indexField.fName + L\";\";\n return sb.str ();\n}\n\nString ORM::Schema::StandardSQLStatements::GetAllElements () const\n{\n StringBuilder sb;\n \/*\n * Select * from DEVICES;\n *\/\n sb += L\"SELECT * FROM \" + fTable.fName + L\";\";\n return sb.str ();\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"stdafx.h\"\n#include \"Screenshot.h\"\n\n#include <stdio.h>\n#include <time.h>\n#include <atlimage.h>\n\nScreenshot::Screenshot()\n{\n}\n\n\nScreenshot::~Screenshot()\n{\n\tDeleteDC(hdcSnapshot);\n\tDeleteObject(hbmSnapshot);\n}\n\nvoid Screenshot::StartScreenshot(HWND hWnd)\n{\n\tHDC hdcScreen;\n\n\t\/\/ Create a normal DC and a memory DC for the entire screen. The\n\t\/\/ normal DC provides a \"snapshot\" of the screen contents. The\n\t\/\/ memory DC keeps a copy of this \"snapshot\" in the associated\n\t\/\/ bitmap.\n\thdcScreen = CreateDC(TEXT(\"DISPLAY\"), NULL, NULL, NULL);\n\tif (hdcSnapshot == NULL) {\n\t\thdcSnapshot = CreateCompatibleDC(hdcScreen);\n\t}\n\n\t\/\/ Create a compatible bitmap for hdcScreen.\n\tif (hbmSnapshot == NULL) {\n\t\thbmSnapshot = CreateCompatibleBitmap(hdcScreen,\n\t\t\tGetDeviceCaps(hdcScreen, HORZRES),\n\t\t\tGetDeviceCaps(hdcScreen, VERTRES));\n\t}\n\n\tif (hbmSnapshot == NULL) {\n\t\tMessageBox(hWnd, TEXT(\"Can't create a compatible bitmap.\"), TEXT(\"Error\"), MB_OK);\n\t}\n\n\t\/\/ Select the bitmaps into the compatible DC.\n\tif (!SelectObject(hdcSnapshot, hbmSnapshot)) {\n\t\tMessageBox(hWnd, TEXT(\"SelectObject Failed\"), TEXT(\"Error\"), MB_OK);\n\t}\n\n\t\/\/ Hide the application window.\n\tShowWindow(hWnd, SW_HIDE);\n\tSleep(100);\n\n\t\/\/ Copy color data for the entire display into a\n\t\/\/ bitmap that is selected into a compatible DC.\n\tif (!BitBlt(hdcSnapshot, 0, 0, mResX, mResY, hdcScreen, 0, 0, SRCCOPY)) {\n\t\tMessageBox(hWnd, TEXT(\"BitBlt Failed\"), TEXT(\"Error\"), MB_OK);\n\t}\n\n\t\/\/ Redraw the application window.\n\tShowWindow(hWnd, SW_SHOW);\n\n\t\/\/ Delete\n\tDeleteDC(hdcScreen);\n}\n\nvoid Screenshot::GetScreenResolution()\n{\n\t\/\/ Get screen resolution.\n\tmResX = GetSystemMetrics(SM_CXSCREEN);\n\tmResY = GetSystemMetrics(SM_CYSCREEN);\n}\n\nint Screenshot::GetScreenResolutionX()\n{\n\tif (mResX == -1)\n\t\tGetScreenResolution();\n\treturn mResX;\n}\n\nint Screenshot::GetScreenResolutionY()\n{\n\tif (mResY == -1)\n\t\tGetScreenResolution();\n\treturn mResY;\n}\n\nvoid Screenshot::SaveScreenshot(WCHAR *imageType)\n{\n\t\/\/ Prepare image filename\n\tWCHAR imageDirname[256] = TEXT(\"screenshot\");\n\tWCHAR imageFilename[256];\n\tWCHAR dateString[256];\n\tGetDateString(dateString);\n\twsprintf(imageFilename, TEXT(\"%s\\\\%s%s\"), imageDirname, dateString, imageType);\n\n\t\/\/ Save image\n\tCreateDirectory(imageDirname, NULL);\n\tCImage image;\n\timage.Attach(hbmSnapshot);\n\timage.Save(imageFilename);\n}\n\nvoid Screenshot::GetDateString(WCHAR *buf)\n{\n\tstruct tm t;\n\ttime_t now;\n\n\ttime(&now);\n\tlocaltime_s(&t, &now);\n\n\twsprintf(buf, TEXT(\"%04d-%02d-%02d_%02d-%02d-%02d\"),\n\t\tt.tm_year + 1900, t.tm_mon + 1, t.tm_mday, t.tm_hour, t.tm_min, t.tm_sec);\n}<commit_msg>Copy Bitmap to Clipboard<commit_after>#include \"stdafx.h\"\n#include \"Screenshot.h\"\n\n#include <stdio.h>\n#include <time.h>\n#include <atlimage.h>\n\nScreenshot::Screenshot()\n{\n}\n\n\nScreenshot::~Screenshot()\n{\n\tDeleteDC(hdcSnapshot);\n\tDeleteObject(hbmSnapshot);\n}\n\nvoid Screenshot::StartScreenshot(HWND hWnd)\n{\n\tHDC hdcScreen;\n\n\t\/\/ Create a normal DC and a memory DC for the entire screen. The\n\t\/\/ normal DC provides a \"snapshot\" of the screen contents. The\n\t\/\/ memory DC keeps a copy of this \"snapshot\" in the associated\n\t\/\/ bitmap.\n\thdcScreen = CreateDC(TEXT(\"DISPLAY\"), NULL, NULL, NULL);\n\tif (hdcSnapshot == NULL) {\n\t\thdcSnapshot = CreateCompatibleDC(hdcScreen);\n\t}\n\n\t\/\/ Create a compatible bitmap for hdcScreen.\n\tif (hbmSnapshot == NULL) {\n\t\thbmSnapshot = CreateCompatibleBitmap(hdcScreen,\n\t\t\tGetDeviceCaps(hdcScreen, HORZRES),\n\t\t\tGetDeviceCaps(hdcScreen, VERTRES));\n\t}\n\n\tif (hbmSnapshot == NULL) {\n\t\tMessageBox(hWnd, TEXT(\"Can't create a compatible bitmap.\"), TEXT(\"Error\"), MB_OK);\n\t}\n\n\t\/\/ Select the bitmaps into the compatible DC.\n\tif (!SelectObject(hdcSnapshot, hbmSnapshot)) {\n\t\tMessageBox(hWnd, TEXT(\"SelectObject Failed\"), TEXT(\"Error\"), MB_OK);\n\t}\n\n\t\/\/ Hide the application window.\n\tShowWindow(hWnd, SW_HIDE);\n\tSleep(100);\n\n\t\/\/ Copy color data for the entire display into a\n\t\/\/ bitmap that is selected into a compatible DC.\n\tif (!BitBlt(hdcSnapshot, 0, 0, mResX, mResY, hdcScreen, 0, 0, SRCCOPY)) {\n\t\tMessageBox(hWnd, TEXT(\"BitBlt Failed\"), TEXT(\"Error\"), MB_OK);\n\t}\n\n\t\/\/ Redraw the application window.\n\tShowWindow(hWnd, SW_SHOW);\n\n\t\/\/ Copy Bitmap to Clipboard\n\tOpenClipboard(hWnd);\n\tEmptyClipboard();\n\tSetClipboardData(CF_BITMAP, hbmSnapshot);\n\tCloseClipboard();\n\n\t\/\/ Delete\n\tDeleteDC(hdcScreen);\n}\n\nvoid Screenshot::GetScreenResolution()\n{\n\t\/\/ Get screen resolution.\n\tmResX = GetSystemMetrics(SM_CXSCREEN);\n\tmResY = GetSystemMetrics(SM_CYSCREEN);\n}\n\nint Screenshot::GetScreenResolutionX()\n{\n\tif (mResX == -1)\n\t\tGetScreenResolution();\n\treturn mResX;\n}\n\nint Screenshot::GetScreenResolutionY()\n{\n\tif (mResY == -1)\n\t\tGetScreenResolution();\n\treturn mResY;\n}\n\nvoid Screenshot::SaveScreenshot(WCHAR *imageType)\n{\n\t\/\/ Prepare image filename\n\tWCHAR imageDirname[256] = TEXT(\"screenshot\");\n\tWCHAR imageFilename[256];\n\tWCHAR dateString[256];\n\tGetDateString(dateString);\n\twsprintf(imageFilename, TEXT(\"%s\\\\%s%s\"), imageDirname, dateString, imageType);\n\n\t\/\/ Save image\n\tCreateDirectory(imageDirname, NULL);\n\tCImage image;\n\timage.Attach(hbmSnapshot);\n\timage.Save(imageFilename);\n}\n\nvoid Screenshot::GetDateString(WCHAR *buf)\n{\n\tstruct tm t;\n\ttime_t now;\n\n\ttime(&now);\n\tlocaltime_s(&t, &now);\n\n\twsprintf(buf, TEXT(\"%04d-%02d-%02d_%02d-%02d-%02d\"),\n\t\tt.tm_year + 1900, t.tm_mon + 1, t.tm_mday, t.tm_hour, t.tm_min, t.tm_sec);\n}<|endoftext|>"} {"text":"<commit_before>\/* PCDM Login Manager:\n* Written by Ken Moore (ken@pcbsd.org) 2012\/2013\n* Copyright(c) 2013 by the PC-BSD Project\n* Available under the 3-clause BSD license\n*\/\n\n#include <QApplication>\n#include <QTranslator>\n#include <QLocale>\n#include <QDesktopWidget>\n#include <QFile>\n#include <QSplashScreen>\n#include <QTime>\n#include <QDebug>\n#include <QX11Info>\n#include <QTextCodec>\n\n#include <sys\/types.h>\n#include <sys\/wait.h>\n#include <unistd.h>\n\n\/\/#define TMPLANGFILE QString(\"\/var\/tmp\/.PCDMLang\")\n#define TMPAUTOLOGINFILE QString(\"\/var\/tmp\/.PCDMAutoLogin-%1\")\n#define TMPAUTHFILE QString(\"\/var\/tmp\/.PCDMAuth-%1\")\n#define TMPSTOPFILE QString(\"\/var\/tmp\/.PCDMstop-%1\")\n\n#include \"pcdm-gui.h\"\n#include \"pcdm-backend.h\"\n#include \"pcdm-config.h\"\n#include \"pcdm-xprocess.h\"\n#include \"pcdm-logindelay.h\"\n\n\/\/bool USECLIBS=false;\n\n\n\/\/Global classes\nUserList *USERS = 0;\nQString VT;\n\n\/\/Setup any qDebug\/qWarning\/qError messages to get saved into this log file directly\nQFile* logfile = new QFile();\nvoid MessageOutput(QtMsgType type, const QMessageLogContext &, const QString &msg){\n QString txt;\n switch(type){\n case QtDebugMsg:\n \t txt = QString(\"Debug: %1\").arg(msg);\n \t break;\n case QtWarningMsg:\n \t txt = QString(\"Warning: %1\").arg(msg);\n \t break;\n case QtCriticalMsg:\n \t txt = QString(\"CRITICAL: %1\").arg(msg);\n \t break;\n case QtFatalMsg:\n \t txt = QString(\"FATAL: %1\").arg(msg);\n \t break;\n default:\n txt = msg;\n }\n\n if(logfile != nullptr and logfile->isOpen())\n {\n QTextStream out(logfile);\n out << txt;\n if(!txt.endsWith(\"\\n\")){ out << \"\\n\"; }\n }\n}\nint runSingleSession(int argc, char *argv[]){\n \/\/QTime clock;\n \/\/clock.start();\n Backend::checkLocalDirs(); \/\/ Create and fill \"\/usr\/local\/share\/PCDM\" if needed\n \n if(logfile == nullptr)\n {\n logfile = new QFile();\n }\n \/\/Setup the log file\n logfile->setFileName(\"\/var\/log\/PCDM-\"+VT+\".log\");\n qDebug() << \"PCDM Log File: \" << logfile->fileName(); \/\/This does not go into the log\n if(QFile::exists(logfile->fileName()+\".old\")){ QFile::remove(logfile->fileName()+\".old\"); }\n if(logfile->exists()){ QFile::rename(logfile->fileName(), logfile->fileName()+\".old\"); }\n \/\/Make sure the parent directory exists\n if(!QFile::exists(\"\/var\/log\")){\n QDir dir;\n dir.mkpath(\"\/var\/log\");\n }\n logfile->open(QIODevice::WriteOnly | QIODevice::Append);\n \/\/Backend::openLogFile(\"\/var\/log\/PCDM.log\");\n\n \/\/qDebug() << \"Backend Checks Finished:\" << QString::number(clock.elapsed())+\" ms\";\n Backend::loadDPIpreference();\n \/\/Setup the initial system environment (locale, keyboard)\n QString lang, kmodel, klayout, kvariant;\n Backend::readDefaultSysEnvironment(lang,kmodel,klayout,kvariant);\n lang = lang.section(\".\",0,0).simplified(); \/\/just in case it also had the encoding saved to the file\n if(lang.isEmpty() || lang.toLower()==\"c\"){ lang = \"en_US\"; }\n setenv(\"LANG\", lang.toUtf8(), 0);\n Backend::changeKbMap(kmodel,klayout,kvariant);\n \/\/Check for the flag to try and auto-login\n bool ALtriggered = false;\n if(QFile::exists(TMPAUTOLOGINFILE.arg(VT))){ ALtriggered=true; QFile::remove(TMPAUTOLOGINFILE.arg(VT)); }\n\n \/\/QString changeLang;\n \/\/ Load the configuration file\n QString confFile = \"\/usr\/local\/etc\/pcdm.conf\";\n if(!QFile::exists(confFile)){\n qDebug() << \"PCDM: Configuration file missing:\"<<confFile<<\"\\n - Using default configuration\";\n QFile::copy(\":samples\/pcdm.conf\", confFile);\n }\n\n Config::loadConfigFile(confFile);\n \/\/ Now set the backend functionality of which usernames are allowed\n if(USERS==0){\n USERS = new UserList();\n USERS->allowUnder1K(Config::allowUnder1KUsers());\n USERS->allowRootUser(Config::allowRootUser());\n USERS->excludeUsers(Config::excludedUserList());\n USERS->updateList(); \/\/now start the probe so things are ready on demand\n }\n \/\/Backend::allowUidUnder1K(Config::allowUnder1KUsers(), Config::excludedUserList());\n \/\/qDebug() << \"Config File Loaded:\" << QString::number(clock.elapsed())+\" ms\";\n \/\/ Startup the main application\n QApplication* a = new QApplication(argc,argv);\n \/\/Setup Log File\n qInstallMessageHandler(MessageOutput);\n int retCode = 0; \/\/used for UI\/application return\n \/\/Print out some debugging information about the init routine\n qDebug() << \"Autologin triggered:\" << ALtriggered << VT;\n\n \/\/Initialize the xprocess\n XProcess* desktop = new XProcess();\n\n \/\/ Check what directory our app is in\n QString appDir = \"\/usr\/local\/share\/PCDM\";\n \/\/ Load the translator\n QTranslator translator;\n QString langCode = lang;\n \/\/Check for a language change detected\n \/\/if ( ! changeLang.isEmpty() )\n \/\/langCode = changeLang;\n \/\/Load the proper locale for the translator\n if ( QFile::exists(appDir + \"\/i18n\/PCDM_\" + langCode + \".qm\" ) ) {\n translator.load( QString(\"PCDM_\") + langCode, appDir + \"\/i18n\/\" );\n a->installTranslator(&translator);\n qDebug() <<\"Loaded Translation:\" + appDir + \"\/i18n\/PCDM_\" + langCode + \".qm\";\n } else {\n qDebug() << \"Could not find: \" + appDir + \"\/i18n\/PCDM_\" + langCode + \".qm\";\n langCode = \"en_US\"; \/\/always default to US english\n }\n\n\n QTextCodec::setCodecForLocale( QTextCodec::codecForName(\"UTF-8\") ); \/\/Force Utf-8 compliance\n \/\/qDebug() << \"Translation Finished:\" << QString::number(clock.elapsed())+\" ms\";\n\n QProcess compositor;\n if ( QFile::exists(\"\/usr\/local\/bin\/compton\") ) {\n compositor.start(\"\/usr\/local\/bin\/compton\");\n }\n\n \/\/ Check if VirtualGL is in use, open up the system for GL rendering if so\n if ( Config::enableVGL() ) {\n system(\"xhost +\");\n }\n\n \/\/ *** STARTUP THE PROGRAM ***\n bool goodAL = false; \/\/Flag for whether the autologin was successful\n \/\/ Start the autologin procedure if applicable\n if( ALtriggered && Config::useAutoLogin() ){\n \/\/Setup the Auto Login\n QString user = Backend::getALUsername();\n QString pwd = Backend::getALPassword();\n QString dsk = Backend::getLastDE(user, \"\");\n if( user.isEmpty() || dsk.isEmpty() || QFile::exists(\"\/var\/db\/personacrypt\/\"+user+\".key\") ){\n\t\/\/Invalid inputs (or a PersonaCrypt user)\n\t goodAL=false;\n }else{\n\t\/\/Run the time delay for the autologin attempt\n\tif(Config::autoLoginDelay() >= 0){\n\t ThemeStruct ctheme;\n ctheme.loadThemeFile(Config::themeFile());\n\t loginDelay dlg(Config::autoLoginDelay(), user, ctheme.itemValue(\"background\") );\n\t \/\/splash.close();\n\t dlg.start();\n\t dlg.activateWindow();\n\t dlg.exec();\n\t goodAL = dlg.continueLogin;\n\t}else{\n\t goodAL = true;\n\t}\n\t\/\/now start the autologin if appropriate\n\tif(goodAL){\n \/\/qDebug() << \"Starting AutoLogin:\" << user;\n\t desktop->loginToXSession(user,pwd, dsk,lang,\"\",false);\n\t \/\/splash.close();\n\t if(desktop->isRunning()){\n\t goodAL=true; \/\/flag this as a good login to skip the GUI\n\t }\n }\n }\n }\n \/\/qDebug() << \"AutoLogin Finished:\" << QString::number(clock.elapsed())+\" ms\";\n if(!goodAL){\n \/\/ ------START THE PCDM GUI-------\n retCode = -1;\n while(retCode==-1){\n retCode = 0;\n qDebug() << \"Starting up PCDM interface\";\n PCDMgui w;\n\n QLocale locale(lang); \/\/Always use the \"lang\" saved from last login - even if the \"langCode\" was reset to en_US for loading PCDM translations\n w.setLocale(locale);\n \/\/qDebug() << \"Main GUI Created:\" << QString::number(clock.elapsed())+\" ms\";\n \/\/splash.finish(&w); \/\/close the splash when the GUI starts up\n\n \/\/Setup the signals\/slots to startup the desktop session\n QObject::connect( &w,SIGNAL(xLoginAttempt(QString,QString,QString,QString, QString, bool)), desktop,SLOT(loginToXSession(QString,QString,QString,QString, QString,bool)) ); \n \/\/Setup the signals\/slots for return information for the GUI\n QObject::connect( desktop, SIGNAL(InvalidLogin()), &w, SLOT(slotLoginFailure()) );\n QObject::connect( desktop, SIGNAL(started()), &w, SLOT(slotLoginSuccess()) );\n QObject::connect( desktop, SIGNAL(ValidLogin()), &w, SLOT(slotLoginSuccess()) );\n\n \/\/qDebug() << \"Showing GUI:\" << QString::number(clock.elapsed())+\" ms\";\n w.show();\n \/\/Set the flag which says that X started properly\n if( !QFile::exists(\"\/var\/tmp\/.pcdm-x-started-\"+VT) ){\n QProcess::startDetached(\"touch \/var\/tmp\/.pcdm-x-started-\"+VT);\n }\n \/\/Now start the event loop until the window closes\n retCode = a->exec();\n }\/\/end special retCode==-1 check (restart GUI)\n } \/\/ end of PCDM GUI running\n USERS->stopUpdates();\n \/\/Wait for the desktop session to finish before exiting\n if(compositor.state()==QProcess::Running){ compositor.terminate(); }\n desktop->waitForSessionClosed();\n qDebug() << \"PCDM Session finished\";\n logfile->close();\n if(logfile != nullptr)\n {\n delete logfile;\n logfile = nullptr;\n }\n \/\/splash.show(); \/\/show the splash screen again\n \/\/Now wait a couple seconds for things to settle\n QTime wTime = QTime::currentTime().addSecs(2);\n while( QTime::currentTime() < wTime ){\n QCoreApplication::processEvents(QEventLoop::AllEvents,100);\n }\n \/\/check for shutdown process\n if( QFile::exists(TMPSTOPFILE.arg(VT)) || QFile::exists(\"\/var\/run\/nologin\") || retCode > 0){\n \/\/splash.showMessage(QObject::tr(\"System Shutting Down\"), Qt::AlignHCenter | Qt::AlignBottom, Qt::white);\n QCoreApplication::processEvents();\n \/\/Pause for a few seconds to prevent starting a new session during a shutdown\n wTime = QTime::currentTime().addSecs(30);\n while( QTime::currentTime() < wTime ){\n \/\/Keep processing events during the wait (for splashscreen)\n QCoreApplication::processEvents(QEventLoop::AllEvents, 100);\n }\n }\n\n\n \/\/Clean up Code\n if(desktop != nullptr)\n {\n delete desktop;\n desktop = nullptr;\n }\n if(a != nullptr)\n {\n delete a;\n a = nullptr;\n }\n \/\/delete &splash;\n\n return retCode;\n}\n\nint main(int argc, char *argv[])\n{\n bool neverquit = true;\n bool runonce = true; \/\/Always set this for now until the internal repeater works properly\n setenv(\"MM_CHARSET\", \"UTF-8\", 1); \/\/ensure UTF-8 text formatting\n VT = \"vt9\";\n for(int i=1; i<argc; i++){\n if(QString(argv[i]) == \"-once\"){ runonce = true; }\n else{ VT = QString(argv[i]); }\n }\n while(neverquit){\n if(runonce){ neverquit = false; }\n qDebug() << \" -- PCDM Session Starting...\";\n \/*int sid = -1;\n int pid = fork();\n if(pid < 0){\n qDebug() << \"Error: Could not fork the PCDM session\";\n return -1;\n }else if( pid ==0 ){\n \/\/New Child Process\n sid = setsid(); \/\/start a session\n qDebug() << \"-- Session ID:\" << sid;*\/\n int retCode = runSingleSession(argc,argv);\n qDebug() << \"-- PCDM Session Ended --\";\n\n \/\/ Need to clean up pid file otherwise daemon restart command fails\n \/\/ saying process is already running\n if(QFile::exists(\"\/var\/run\/PCDMd-\" + VT + \".pid\")) \n {\n QFile::remove(\"\/var\/run\/PCDMd-\" + VT+ \".pid\");\n } \n \/\/check for special exit code\n if(retCode == -1){ neverquit=true; } \/\/make sure we go around again at least once\n else if(retCode != 0){ neverquit=false; }\n \/\/Now kill the shild process (whole session)\n \/*qDebug() << \"Exiting child process\";\n exit(3);\n }else{\n \/\/Parent (calling) process\n int status;\n sleep(2);\n waitpid(sid,&status,0); \/\/wait for the child (session) to finish\n \/\/NOTE: the parent will eventually become a login-watcher daemon process that\n \/\/ can spawn multiple child sessions on different TTY displays\n }*\/\n qDebug() << \"-- PCDM Session Ended --\";\n if(QFile::exists(\"\/var\/run\/nologin\") || QFile::exists(TMPSTOPFILE.arg(VT)) ){ neverquit = false; }\n }\n\n if(logfile != nullptr)\n {\n delete logfile;\t \n logfile = nullptr;\n }\n return 0;\n}\n<commit_msg>Update main.cpp<commit_after>\/* PCDM Login Manager:\n* Written by Ken Moore (ken@pcbsd.org) 2012\/2013\n* Copyright(c) 2013 by the PC-BSD Project\n* Available under the 3-clause BSD license\n*\/\n\n#include <QApplication>\n#include <QTranslator>\n#include <QLocale>\n#include <QDesktopWidget>\n#include <QFile>\n#include <QSplashScreen>\n#include <QTime>\n#include <QDebug>\n#include <QX11Info>\n#include <QTextCodec>\n\n#include <sys\/types.h>\n#include <sys\/wait.h>\n#include <unistd.h>\n\n\/\/#define TMPLANGFILE QString(\"\/var\/tmp\/.PCDMLang\")\n#define TMPAUTOLOGINFILE QString(\"\/var\/tmp\/.PCDMAutoLogin-%1\")\n#define TMPAUTHFILE QString(\"\/var\/tmp\/.PCDMAuth-%1\")\n#define TMPSTOPFILE QString(\"\/var\/tmp\/.PCDMstop-%1\")\n\n#include \"pcdm-gui.h\"\n#include \"pcdm-backend.h\"\n#include \"pcdm-config.h\"\n#include \"pcdm-xprocess.h\"\n#include \"pcdm-logindelay.h\"\n\n\/\/bool USECLIBS=false;\n\n\n\/\/Global classes\nUserList *USERS = 0;\nQString VT;\n\n\/\/Setup any qDebug\/qWarning\/qError messages to get saved into this log file directly\nQFile* logfile = new QFile();\nvoid MessageOutput(QtMsgType type, const QMessageLogContext &, const QString &msg){\n QString txt;\n switch(type){\n case QtDebugMsg:\n \t txt = QString(\"Debug: %1\").arg(msg);\n \t break;\n case QtWarningMsg:\n \t txt = QString(\"Warning: %1\").arg(msg);\n \t break;\n case QtCriticalMsg:\n \t txt = QString(\"CRITICAL: %1\").arg(msg);\n \t break;\n case QtFatalMsg:\n \t txt = QString(\"FATAL: %1\").arg(msg);\n \t break;\n default:\n txt = msg;\n }\n\n if(logfile != nullptr and logfile->isOpen())\n {\n QTextStream out(logfile);\n out << txt;\n if(!txt.endsWith(\"\\n\")){ out << \"\\n\"; }\n }\n}\nint runSingleSession(int argc, char *argv[]){\n \/\/QTime clock;\n \/\/clock.start();\n Backend::checkLocalDirs(); \/\/ Create and fill \"\/usr\/local\/share\/PCDM\" if needed\n \n if(logfile == nullptr)\n {\n logfile = new QFile();\n }\n \/\/Setup the log file\n logfile->setFileName(\"\/var\/log\/PCDM-\"+VT+\".log\");\n qDebug() << \"PCDM Log File: \" << logfile->fileName(); \/\/This does not go into the log\n if(QFile::exists(logfile->fileName()+\".old\")){ QFile::remove(logfile->fileName()+\".old\"); }\n if(logfile->exists()){ QFile::rename(logfile->fileName(), logfile->fileName()+\".old\"); }\n \/\/Make sure the parent directory exists\n if(!QFile::exists(\"\/var\/log\")){\n QDir dir;\n dir.mkpath(\"\/var\/log\");\n }\n logfile->open(QIODevice::WriteOnly | QIODevice::Append);\n \/\/Backend::openLogFile(\"\/var\/log\/PCDM.log\");\n\n \/\/qDebug() << \"Backend Checks Finished:\" << QString::number(clock.elapsed())+\" ms\";\n Backend::loadDPIpreference();\n \/\/Setup the initial system environment (locale, keyboard)\n QString lang, kmodel, klayout, kvariant;\n Backend::readDefaultSysEnvironment(lang,kmodel,klayout,kvariant);\n lang = lang.section(\".\",0,0).simplified(); \/\/just in case it also had the encoding saved to the file\n if(lang.isEmpty() || lang.toLower()==\"c\"){ lang = \"en_US\"; }\n setenv(\"LANG\", lang.toUtf8(), 0);\n Backend::changeKbMap(kmodel,klayout,kvariant);\n \/\/Check for the flag to try and auto-login\n bool ALtriggered = false;\n if(QFile::exists(TMPAUTOLOGINFILE.arg(VT))){ ALtriggered=true; QFile::remove(TMPAUTOLOGINFILE.arg(VT)); }\n\n \/\/QString changeLang;\n \/\/ Load the configuration file\n QString confFile = \"\/usr\/local\/etc\/pcdm.conf\";\n if(!QFile::exists(confFile)){\n qDebug() << \"PCDM: Configuration file missing:\"<<confFile<<\"\\n - Using default configuration\";\n QFile::copy(\":samples\/pcdm.conf\", confFile);\n }\n\n Config::loadConfigFile(confFile);\n \/\/ Now set the backend functionality of which usernames are allowed\n if(USERS==0){\n USERS = new UserList();\n USERS->allowUnder1K(Config::allowUnder1KUsers());\n USERS->allowRootUser(Config::allowRootUser());\n USERS->excludeUsers(Config::excludedUserList());\n USERS->updateList(); \/\/now start the probe so things are ready on demand\n }\n \/\/Backend::allowUidUnder1K(Config::allowUnder1KUsers(), Config::excludedUserList());\n \/\/qDebug() << \"Config File Loaded:\" << QString::number(clock.elapsed())+\" ms\";\n \/\/ Startup the main application\n QApplication* a = new QApplication(argc,argv);\n \/\/Setup Log File\n qInstallMessageHandler(MessageOutput);\n int retCode = 0; \/\/used for UI\/application return\n \/\/Print out some debugging information about the init routine\n qDebug() << \"Autologin triggered:\" << ALtriggered << VT;\n\n \/\/Initialize the xprocess\n XProcess* desktop = new XProcess();\n\n \/\/ Check what directory our app is in\n QString appDir = \"\/usr\/local\/share\/PCDM\";\n \/\/ Load the translator\n QTranslator translator;\n QString langCode = lang;\n \/\/Check for a language change detected\n \/\/if ( ! changeLang.isEmpty() )\n \/\/langCode = changeLang;\n \/\/Load the proper locale for the translator\n if ( QFile::exists(appDir + \"\/i18n\/PCDM_\" + langCode + \".qm\" ) ) {\n translator.load( QString(\"PCDM_\") + langCode, appDir + \"\/i18n\/\" );\n a->installTranslator(&translator);\n qDebug() <<\"Loaded Translation:\" + appDir + \"\/i18n\/PCDM_\" + langCode + \".qm\";\n } else {\n qDebug() << \"Could not find: \" + appDir + \"\/i18n\/PCDM_\" + langCode + \".qm\";\n langCode = \"en_US\"; \/\/always default to US english\n }\n\n\n QTextCodec::setCodecForLocale( QTextCodec::codecForName(\"UTF-8\") ); \/\/Force Utf-8 compliance\n \/\/qDebug() << \"Translation Finished:\" << QString::number(clock.elapsed())+\" ms\";\n\n QProcess compositor;\n if ( QFile::exists(\"\/usr\/local\/bin\/compton\") ) {\n compositor.start(\"\/usr\/local\/bin\/compton\");\n }\n\n \/\/ Check if VirtualGL is in use, open up the system for GL rendering if so\n if ( Config::enableVGL() ) {\n system(\"xhost +\");\n }\n\n \/\/ *** STARTUP THE PROGRAM ***\n bool goodAL = false; \/\/Flag for whether the autologin was successful\n \/\/ Start the autologin procedure if applicable\n if( ALtriggered && Config::useAutoLogin() ){\n \/\/Setup the Auto Login\n QString user = Backend::getALUsername();\n QString pwd = Backend::getALPassword();\n QString dsk = Backend::getLastDE(user, \"\");\n if( user.isEmpty() || dsk.isEmpty() || QFile::exists(\"\/var\/db\/personacrypt\/\"+user+\".key\") ){\n\t\/\/Invalid inputs (or a PersonaCrypt user)\n\t goodAL=false;\n }else{\n\t\/\/Run the time delay for the autologin attempt\n\tif(Config::autoLoginDelay() >= 0){\n\t ThemeStruct ctheme;\n ctheme.loadThemeFile(Config::themeFile());\n\t loginDelay dlg(Config::autoLoginDelay(), user, ctheme.itemValue(\"background\") );\n\t \/\/splash.close();\n\t dlg.start();\n\t dlg.activateWindow();\n\t dlg.exec();\n\t goodAL = dlg.continueLogin;\n\t}else{\n\t goodAL = true;\n\t}\n\t\/\/now start the autologin if appropriate\n\tif(goodAL){\n \/\/qDebug() << \"Starting AutoLogin:\" << user;\n\t desktop->loginToXSession(user,pwd, dsk,lang,\"\",false);\n\t \/\/splash.close();\n\t if(desktop->isRunning()){\n\t goodAL=true; \/\/flag this as a good login to skip the GUI\n\t }\n }\n }\n }\n \/\/qDebug() << \"AutoLogin Finished:\" << QString::number(clock.elapsed())+\" ms\";\n if(!goodAL){\n \/\/ ------START THE PCDM GUI-------\n retCode = -1;\n while(retCode==-1){\n retCode = 0;\n qDebug() << \"Starting up PCDM interface\";\n PCDMgui w;\n\n QLocale locale(lang); \/\/Always use the \"lang\" saved from last login - even if the \"langCode\" was reset to en_US for loading PCDM translations\n w.setLocale(locale);\n \/\/qDebug() << \"Main GUI Created:\" << QString::number(clock.elapsed())+\" ms\";\n \/\/splash.finish(&w); \/\/close the splash when the GUI starts up\n\n \/\/Setup the signals\/slots to startup the desktop session\n QObject::connect( &w,SIGNAL(xLoginAttempt(QString,QString,QString,QString, QString, bool)), desktop,SLOT(loginToXSession(QString,QString,QString,QString, QString,bool)) ); \n \/\/Setup the signals\/slots for return information for the GUI\n QObject::connect( desktop, SIGNAL(InvalidLogin()), &w, SLOT(slotLoginFailure()) );\n QObject::connect( desktop, SIGNAL(started()), &w, SLOT(slotLoginSuccess()) );\n QObject::connect( desktop, SIGNAL(ValidLogin()), &w, SLOT(slotLoginSuccess()) );\n\n \/\/qDebug() << \"Showing GUI:\" << QString::number(clock.elapsed())+\" ms\";\n w.show();\n \/\/Set the flag which says that X started properly\n if( !QFile::exists(\"\/var\/tmp\/.pcdm-x-started-\"+VT) ){\n QProcess::startDetached(\"touch \/var\/tmp\/.pcdm-x-started-\"+VT);\n }\n \/\/Now start the event loop until the window closes\n retCode = a->exec();\n }\/\/end special retCode==-1 check (restart GUI)\n } \/\/ end of PCDM GUI running\n USERS->stopUpdates();\n \/\/Wait for the desktop session to finish before exiting\n if(compositor.state()==QProcess::Running){ compositor.terminate(); }\n desktop->waitForSessionClosed();\n qDebug() << \"PCDM Session finished\";\n logfile->close();\n if(logfile != nullptr)\n {\n delete logfile;\n logfile = nullptr;\n }\n \/\/splash.show(); \/\/show the splash screen again\n \/\/Now wait a couple seconds for things to settle\n QTime wTime = QTime::currentTime().addSecs(2);\n while( QTime::currentTime() < wTime ){\n QCoreApplication::processEvents(QEventLoop::AllEvents,100);\n }\n \/\/check for shutdown process\n if( QFile::exists(TMPSTOPFILE.arg(VT)) || QFile::exists(\"\/var\/run\/nologin\") || retCode > 0){\n \/\/splash.showMessage(QObject::tr(\"System Shutting Down\"), Qt::AlignHCenter | Qt::AlignBottom, Qt::white);\n QCoreApplication::processEvents();\n \/\/Pause for a few seconds to prevent starting a new session during a shutdown\n wTime = QTime::currentTime().addSecs(30);\n while( QTime::currentTime() < wTime ){\n \/\/Keep processing events during the wait (for splashscreen)\n QCoreApplication::processEvents(QEventLoop::AllEvents, 100);\n }\n }\n\n\n \/\/Clean up Code\n if(desktop != nullptr)\n {\n delete desktop;\n desktop = nullptr;\n }\n if(a != nullptr)\n {\n delete a;\n a = nullptr;\n }\n \/\/delete &splash;\n\n return retCode;\n}\n\nint main(int argc, char *argv[])\n{\n bool neverquit = true;\n bool runonce = true; \/\/Always set this for now until the internal repeater works properly\n setenv(\"MM_CHARSET\", \"UTF-8\", 1); \/\/ensure UTF-8 text formatting\n VT = \"vt9\";\n for(int i=1; i<argc; i++){\n if(QString(argv[i]) == \"-once\"){ runonce = true; }\n else{ VT = QString(argv[i]); }\n }\n while(neverquit){\n if(runonce){ neverquit = false; }\n qDebug() << \" -- PCDM Session Starting...\";\n \/*int sid = -1;\n int pid = fork();\n if(pid < 0){\n qDebug() << \"Error: Could not fork the PCDM session\";\n return -1;\n }else if( pid ==0 ){\n \/\/New Child Process\n sid = setsid(); \/\/start a session\n qDebug() << \"-- Session ID:\" << sid;*\/\n int retCode = runSingleSession(argc,argv);\n qDebug() << \"-- PCDM Session Ended --\";\n\n\n \/\/check for special exit code\n if(retCode == -1){ neverquit=true; } \/\/make sure we go around again at least once\n else if(retCode != 0){ neverquit=false; }\n \/\/Now kill the shild process (whole session)\n \/*qDebug() << \"Exiting child process\";\n exit(3);\n }else{\n \/\/Parent (calling) process\n int status;\n sleep(2);\n waitpid(sid,&status,0); \/\/wait for the child (session) to finish\n \/\/NOTE: the parent will eventually become a login-watcher daemon process that\n \/\/ can spawn multiple child sessions on different TTY displays\n }*\/\n qDebug() << \"-- PCDM Session Ended --\";\n if(QFile::exists(\"\/var\/run\/nologin\") || QFile::exists(TMPSTOPFILE.arg(VT)) ){ neverquit = false; }\n }\n \/\/ Need to clean up pid file otherwise daemon restart command fails\n \/\/ saying process is already running\n if(QFile::exists(\"\/var\/run\/PCDMd-\" + VT + \".pid\")) \n {\n QFile::remove(\"\/var\/run\/PCDMd-\" + VT+ \".pid\");\n } \n if(logfile != nullptr)\n {\n delete logfile;\t \n logfile = nullptr;\n }\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"Session.hpp\"\n\nnamespace Dissent {\nnamespace Anonymity {\n Session::Session(const Group &group, const Id &local_id, const Id &leader_id,\n const Id &session_id, ConnectionTable &ct, RpcHandler &rpc,\n CreateRound create_round, const QByteArray &default_data) :\n _local_id(local_id),\n _leader_id(leader_id),\n _group(group),\n _ct(ct),\n _rpc(rpc),\n _session_id(session_id),\n _default_data(default_data),\n _current_round(0),\n _previous_round(0),\n _started(false),\n _closed(false),\n _ready(*this, &Session::Ready),\n _create_round(create_round)\n {\n foreach(const Id &id, _group.GetIds()) {\n Connection *con = _ct.GetConnection(id);\n if(con) {\n QObject::connect(con, SIGNAL(Disconnected(Connection *, const QString &)),\n this, SLOT(HandleDisconnect(Connection *, const QString &)));\n }\n }\n }\n\n Session::~Session()\n {\n if(_current_round) {\n QObject::disconnect(_current_round, SIGNAL(Finished(Round *)),\n this, SLOT(HandleRoundFinished(Round *)));\n delete _current_round;\n }\n if(_previous_round) {\n delete _previous_round;\n }\n }\n\n void Session::Start()\n {\n if(_started) {\n qWarning() << \"Called start twice.\";\n return;\n }\n if(_closed) {\n qWarning() << \"Already closed.\";\n return;\n }\n _started = true;\n NextRound();\n }\n\n void Session::Stop()\n {\n if(_closed) {\n qDebug() << \"Already closed.\";\n return;\n }\n\n foreach(const Id &id, _group.GetIds()) {\n Connection *con = _ct.GetConnection(id);\n if(con) {\n QObject::disconnect(con, SIGNAL(Disconnected(Connection *, const QString &)),\n this, SLOT(HandleDisconnect(Connection *, const QString &)));\n }\n }\n\n _closed = true;\n if(_current_round) {\n _current_round->Close(\"Session stopped\");\n }\n emit Closed(this);\n }\n\n void Session::ReceivedReady(RpcRequest &request)\n {\n if(!IsLeader()) {\n qWarning() << \"Received a Ready message when not a leader.\";\n return;\n }\n\n \/\/ Are we actually expecting this message?\n \n Connection *con = dynamic_cast<Connection *>(request.GetFrom());\n if(!con) {\n qWarning() << \"Received a Ready message from a non-connection: \" <<\n request.GetFrom()->ToString();\n return;\n }\n\n if(_id_to_request.contains(con->GetRemoteId())) {\n qWarning() << \"Received a duplicate Ready message from: \" << con->ToString();\n return;\n }\n\n _id_to_request.insert(con->GetRemoteId(), request);\n LeaderReady();\n }\n\n bool Session::LeaderReady()\n {\n if(_id_to_request.count() != _group.Count() - 1) {\n return false;\n }\n\n QVariantMap response;\n foreach(RpcRequest request, _id_to_request) {\n request.Respond(response);\n }\n _id_to_request.clear();\n\n _current_round->Start();\n return true;\n }\n\n void Session::Ready(RpcRequest &)\n {\n _current_round->Start();\n }\n\n void Session::HandleRoundFinished(Round *round)\n {\n if(round != _current_round) {\n qWarning() << \"Received an awry Round Finished notification\";\n return;\n }\n\n emit RoundFinished(this, _current_round);\n\n if(_closed) {\n qDebug() << \"Session closed.\";\n } else \n if( round->Successful()) {\n NextRound();\n } else {\n qWarning() << \"Round ended unsuccessfully ... what to do...\";\n }\n }\n\n void Session::NextRound()\n {\n if(_current_round) {\n QObject::disconnect(_current_round, SIGNAL(Finished(Round *)),\n this, SLOT(HandleRoundFinished(Round *)));\n\n if(_previous_round) {\n delete _previous_round;\n }\n\n _previous_round = _current_round;\n }\n \n _current_round = GetRound((_send_queue.isEmpty()) ?\n _default_data : _send_queue.dequeue());\n\n _current_round->SetSink(this);\n QObject::connect(_current_round, SIGNAL(Finished(Round *)),\n this, SLOT(HandleRoundFinished(Round *)));\n\n if(IsLeader()) {\n LeaderReady();\n } else {\n QVariantMap request;\n request[\"method\"] = \"SM::Ready\";\n request[\"session_id\"] = _session_id.GetByteArray();\n _rpc.SendRequest(request, _ct.GetConnection(_leader_id), &_ready);\n }\n }\n\n void Session::Send(const QByteArray &data)\n {\n if(_closed) {\n qWarning() << \"Session is closed.\";\n return;\n }\n\n _send_queue.append(data);\n }\n\n void Session::IncomingData(RpcRequest ¬ification)\n {\n QByteArray data = notification.GetMessage()[\"data\"].toByteArray();\n _current_round->HandleData(data, notification.GetFrom());\n }\n\n void Session::HandleDisconnect(Connection *con, const QString &)\n {\n if(!_group.Contains(con->GetRemoteId()) || _closed) {\n return;\n }\n qDebug() << \"Closing Session due to disconnect\";\n Stop();\n }\n\n Round *Session::GetRound(const QByteArray &data)\n {\n return _create_round(_group, _local_id, _session_id, _ct, _rpc, data);\n }\n}\n}\n<commit_msg>[Anonymity] Fixed a race condition in Session which resulted in a crash<commit_after>#include \"Session.hpp\"\n\nnamespace Dissent {\nnamespace Anonymity {\n Session::Session(const Group &group, const Id &local_id, const Id &leader_id,\n const Id &session_id, ConnectionTable &ct, RpcHandler &rpc,\n CreateRound create_round, const QByteArray &default_data) :\n _local_id(local_id),\n _leader_id(leader_id),\n _group(group),\n _ct(ct),\n _rpc(rpc),\n _session_id(session_id),\n _default_data(default_data),\n _current_round(0),\n _previous_round(0),\n _started(false),\n _closed(false),\n _ready(*this, &Session::Ready),\n _create_round(create_round)\n {\n foreach(const Id &id, _group.GetIds()) {\n Connection *con = _ct.GetConnection(id);\n if(con) {\n QObject::connect(con, SIGNAL(Disconnected(Connection *, const QString &)),\n this, SLOT(HandleDisconnect(Connection *, const QString &)));\n }\n }\n }\n\n Session::~Session()\n {\n if(_current_round) {\n QObject::disconnect(_current_round, SIGNAL(Finished(Round *)),\n this, SLOT(HandleRoundFinished(Round *)));\n delete _current_round;\n }\n if(_previous_round) {\n delete _previous_round;\n }\n }\n\n void Session::Start()\n {\n qDebug() << \"Session\" << ToString() << \"started\";\n if(_started) {\n qWarning() << \"Called start twice.\";\n return;\n }\n if(_closed) {\n qWarning() << \"Already closed.\";\n return;\n }\n _started = true;\n NextRound();\n }\n\n void Session::Stop()\n {\n if(_closed) {\n qDebug() << \"Already closed.\";\n return;\n }\n\n foreach(const Id &id, _group.GetIds()) {\n Connection *con = _ct.GetConnection(id);\n if(con) {\n QObject::disconnect(con, SIGNAL(Disconnected(Connection *, const QString &)),\n this, SLOT(HandleDisconnect(Connection *, const QString &)));\n }\n }\n\n _closed = true;\n if(_current_round) {\n _current_round->Close(\"Session stopped\");\n }\n emit Closed(this);\n }\n\n void Session::ReceivedReady(RpcRequest &request)\n {\n if(!IsLeader()) {\n qWarning() << \"Received a Ready message when not a leader.\";\n return;\n }\n\n \/\/ Are we actually expecting this message?\n \n Connection *con = dynamic_cast<Connection *>(request.GetFrom());\n if(!con) {\n qWarning() << \"Received a Ready message from a non-connection: \" <<\n request.GetFrom()->ToString();\n return;\n }\n\n if(_id_to_request.contains(con->GetRemoteId())) {\n qWarning() << \"Received a duplicate Ready message from: \" << con->ToString();\n return;\n }\n\n _id_to_request.insert(con->GetRemoteId(), request);\n if(_started) {\n LeaderReady();\n }\n }\n\n bool Session::LeaderReady()\n {\n if(_id_to_request.count() != _group.Count() - 1) {\n return false;\n }\n\n QVariantMap response;\n foreach(RpcRequest request, _id_to_request) {\n request.Respond(response);\n }\n _id_to_request.clear();\n\n _current_round->Start();\n return true;\n }\n\n void Session::Ready(RpcRequest &)\n {\n _current_round->Start();\n }\n\n void Session::HandleRoundFinished(Round *round)\n {\n qDebug() << \"Session\" << ToString() << \"round finished\";\n if(round != _current_round) {\n qWarning() << \"Received an awry Round Finished notification\";\n return;\n }\n\n emit RoundFinished(this, _current_round);\n\n if(_closed) {\n qDebug() << \"Session closed.\";\n } else \n if( round->Successful()) {\n NextRound();\n } else {\n qWarning() << \"Round ended unsuccessfully ... what to do...\";\n }\n }\n\n void Session::NextRound()\n {\n if(_current_round) {\n qDebug() << \"Session\" << ToString() << \"creating a new round\";\n QObject::disconnect(_current_round, SIGNAL(Finished(Round *)),\n this, SLOT(HandleRoundFinished(Round *)));\n\n if(_previous_round) {\n delete _previous_round;\n }\n\n _previous_round = _current_round;\n }\n \n _current_round = GetRound((_send_queue.isEmpty()) ?\n _default_data : _send_queue.dequeue());\n\n _current_round->SetSink(this);\n QObject::connect(_current_round, SIGNAL(Finished(Round *)),\n this, SLOT(HandleRoundFinished(Round *)));\n\n if(IsLeader()) {\n LeaderReady();\n } else {\n QVariantMap request;\n request[\"method\"] = \"SM::Ready\";\n request[\"session_id\"] = _session_id.GetByteArray();\n _rpc.SendRequest(request, _ct.GetConnection(_leader_id), &_ready);\n }\n }\n\n void Session::Send(const QByteArray &data)\n {\n if(_closed) {\n qWarning() << \"Session is closed.\";\n return;\n }\n\n _send_queue.append(data);\n }\n\n void Session::IncomingData(RpcRequest ¬ification)\n {\n QByteArray data = notification.GetMessage()[\"data\"].toByteArray();\n _current_round->HandleData(data, notification.GetFrom());\n }\n\n void Session::HandleDisconnect(Connection *con, const QString &)\n {\n if(!_group.Contains(con->GetRemoteId()) || _closed) {\n return;\n }\n qDebug() << \"Closing Session due to disconnect\";\n Stop();\n }\n\n Round *Session::GetRound(const QByteArray &data)\n {\n return _create_round(_group, _local_id, _session_id, _ct, _rpc, data);\n }\n}\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2015, Matthew Malensek.\n\/\/ Distributed under the BSD 2-Clause License (see LICENSE.txt for details)\n\n#include \"Updater.h\"\n\n#pragma comment(lib, \"Urlmon.lib\")\n#pragma comment(lib, \"Version.lib\")\n#pragma comment(lib, \"wininet.lib\")\n\n#include <Windows.h>\n#include <Shlobj.h> \/\/ Has to be included before WinInet to avoid warning\n#include <WinInet.h>\n#include <sstream>\n\n#include \"..\/..\/3RVX\/Settings.h\"\n#include \"..\/..\/3RVX\/StringUtils.h\"\n#include \"..\/..\/3RVX\/Logger.h\"\n#include \"..\/Controls\/StatusCallback.h\"\n#include \"Version.h\"\n\nconst std::wstring Updater::DOWNLOAD_URL\n = L\"https:\/\/3rvx.com\/releases\/\";\n\n\/* Since this const depends on DOWNLOAD_URL, it needs to be defined after it. *\/\nconst std::wstring Updater::LATEST_URL\n = Updater::DOWNLOAD_URL + L\"latest_version\";\n\nbool Updater::NewerVersionAvailable() {\n Version remote = RemoteVersion();\n Version local = MainAppVersion();\n CLOG(L\"Remote version: %s\\n Local version: %s\",\n remote.ToString().c_str(),\n local.ToString().c_str());\n\n if (remote.ToInt() == 0 || local.ToInt() == 0) {\n \/* One of the version checks failed, so say that there is no new\n * version. No need to bother the user with (hopefully) temporary\n * errors. *\/\n return false;\n }\n\n if (remote.ToInt() > local.ToInt()) {\n return true;\n } else {\n return false;\n }\n}\n\nVersion Updater::MainAppVersion() {\n std::wstring mainExe = Settings::Instance()->MainApp();\n BOOL result;\n\n DWORD size = GetFileVersionInfoSize(mainExe.c_str(), NULL);\n if (size == 0) {\n CLOG(L\"Could not determine version info size\");\n return { 0, 0, 0 };\n }\n\n unsigned char *block = new unsigned char[size];\n result = GetFileVersionInfo(mainExe.c_str(), NULL, size, block);\n if (result == 0) {\n CLOG(L\"Failed to retrieve file version info\");\n delete[] block;\n return { 0, 0, 0 };\n }\n\n unsigned int dataSz;\n VS_FIXEDFILEINFO *vers;\n result = VerQueryValue(block, L\"\\\\\", (void **) &vers, &dataSz);\n if (result == 0) {\n CLOG(L\"Could not query root block for version info\");\n delete[] block;\n return { 0, 0, 0 };\n }\n\n if (vers->dwSignature != 0xFEEF04BD) {\n CLOG(L\"Invalid version signature\");\n delete[] block;\n return { 0, 0, 0 };\n }\n\n unsigned long verms = vers->dwProductVersionMS;\n int hi = (verms >> 16) & 0xFF;\n int lo = verms & 0xFF;\n\n unsigned long verls = vers->dwProductVersionLS;\n int rev = (verls >> 16) & 0xFF;\n\n delete[] block;\n return Version(hi, lo, rev);\n}\n\nstd::wstring Updater::DownloadVersion(Version version, StatusCallback *cb) {\n std::wstring localDir = L\"\";\n\n if (Settings::Portable()) {\n PWSTR dlPath = nullptr;\n SHGetKnownFolderPath(FOLDERID_Downloads, 0, NULL, &dlPath);\n localDir = std::wstring(dlPath);\n CoTaskMemFree(dlPath);\n } else {\n wchar_t tmpPath[MAX_PATH];\n DWORD result = GetTempPath(MAX_PATH, tmpPath);\n if (result == 0) {\n CLOG(L\"Could not get temp download path\");\n return L\"\";\n }\n localDir = std::wstring(tmpPath);\n }\n\n if (localDir == L\"\") {\n CLOG(L\"Could not determine local download directory\");\n return L\"\";\n }\n\n std::wstring fname = DownloadFileName(version);\n std::wstring url = DOWNLOAD_URL + fname;\n std::wstring localFile = localDir + L\"\\\\\" + fname;\n\n CLOG(L\"Downloading %s to %s...\", url.c_str(), localFile.c_str());\n DeleteUrlCacheEntry(url.c_str());\n HRESULT hr = URLDownloadToFile(\n NULL,\n url.c_str(),\n localFile.c_str(),\n 0,\n cb);\n\n if (hr == S_OK) {\n return localFile;\n } else {\n return L\"\";\n }\n}\n\nstd::wstring Updater::DownloadFileName(Version version) {\n std::wstring ext;\n if (Settings::Portable()) {\n ext = L\".zip\";\n } else {\n ext = L\".msi\";\n }\n return std::wstring(L\"3RVX-\" + version.ToString() + ext);\n}\n\nVersion Updater::RemoteVersion() {\n HINTERNET internet = InternetOpen(\n L\"3RVX Updater\",\n INTERNET_OPEN_TYPE_PRECONFIG,\n NULL,\n NULL,\n NULL);\n\n CLOG(L\"Opening URL: %s\", LATEST_URL.c_str());\n HINTERNET connection = InternetOpenUrl(\n internet,\n LATEST_URL.c_str(),\n NULL,\n 0,\n INTERNET_FLAG_NO_CACHE_WRITE | INTERNET_FLAG_PRAGMA_NOCACHE,\n 0);\n\n if (connection == NULL) {\n CLOG(L\"Could not connect to URL!\");\n return { 0, 0, 0 };\n }\n\n std::string str(\"\");\n char buf[32];\n DWORD read;\n while (InternetReadFile(connection, buf, 16, &read) == TRUE && read != 0) {\n str.append(buf);\n }\n\n \/* Only consider the first line *\/\n str.erase(str.find('\\n'), str.size() - 1);\n\n size_t dot = str.find('.');\n size_t dot2 = str.find('.', dot + 1);\n std::string major = str.substr(0, dot);\n std::string minor = str.substr(dot + 1, dot2);\n std::string rev = str.substr(dot2 + 1, str.size());\n return Version(std::stoi(major), std::stoi(minor), std::stoi(rev));\n}<commit_msg>Verify destination file is writeable<commit_after>\/\/ Copyright (c) 2015, Matthew Malensek.\n\/\/ Distributed under the BSD 2-Clause License (see LICENSE.txt for details)\n\n#include \"Updater.h\"\n\n#pragma comment(lib, \"Urlmon.lib\")\n#pragma comment(lib, \"Version.lib\")\n#pragma comment(lib, \"wininet.lib\")\n\n#include <Windows.h>\n#include <Shlobj.h> \/\/ Has to be included before WinInet to avoid warning\n#include <WinInet.h>\n#include <sstream>\n\n#include \"..\/..\/3RVX\/Settings.h\"\n#include \"..\/..\/3RVX\/StringUtils.h\"\n#include \"..\/..\/3RVX\/Logger.h\"\n#include \"..\/Controls\/StatusCallback.h\"\n#include \"Version.h\"\n\nconst std::wstring Updater::DOWNLOAD_URL\n = L\"https:\/\/3rvx.com\/releases\/\";\n\n\/* Since this const depends on DOWNLOAD_URL, it needs to be defined after it. *\/\nconst std::wstring Updater::LATEST_URL\n = Updater::DOWNLOAD_URL + L\"latest_version\";\n\nbool Updater::NewerVersionAvailable() {\n Version remote = RemoteVersion();\n Version local = MainAppVersion();\n CLOG(L\"Remote version: %s\\n Local version: %s\",\n remote.ToString().c_str(),\n local.ToString().c_str());\n\n if (remote.ToInt() == 0 || local.ToInt() == 0) {\n \/* One of the version checks failed, so say that there is no new\n * version. No need to bother the user with (hopefully) temporary\n * errors. *\/\n return false;\n }\n\n if (remote.ToInt() > local.ToInt()) {\n return true;\n } else {\n return false;\n }\n}\n\nVersion Updater::MainAppVersion() {\n std::wstring mainExe = Settings::Instance()->MainApp();\n BOOL result;\n\n DWORD size = GetFileVersionInfoSize(mainExe.c_str(), NULL);\n if (size == 0) {\n CLOG(L\"Could not determine version info size\");\n return { 0, 0, 0 };\n }\n\n unsigned char *block = new unsigned char[size];\n result = GetFileVersionInfo(mainExe.c_str(), NULL, size, block);\n if (result == 0) {\n CLOG(L\"Failed to retrieve file version info\");\n delete[] block;\n return { 0, 0, 0 };\n }\n\n unsigned int dataSz;\n VS_FIXEDFILEINFO *vers;\n result = VerQueryValue(block, L\"\\\\\", (void **) &vers, &dataSz);\n if (result == 0) {\n CLOG(L\"Could not query root block for version info\");\n delete[] block;\n return { 0, 0, 0 };\n }\n\n if (vers->dwSignature != 0xFEEF04BD) {\n CLOG(L\"Invalid version signature\");\n delete[] block;\n return { 0, 0, 0 };\n }\n\n unsigned long verms = vers->dwProductVersionMS;\n int hi = (verms >> 16) & 0xFF;\n int lo = verms & 0xFF;\n\n unsigned long verls = vers->dwProductVersionLS;\n int rev = (verls >> 16) & 0xFF;\n\n delete[] block;\n return Version(hi, lo, rev);\n}\n\nstd::wstring Updater::DownloadVersion(Version version, StatusCallback *cb) {\n std::wstring localDir = L\"\";\n\n if (Settings::Portable()) {\n PWSTR dlPath = nullptr;\n SHGetKnownFolderPath(FOLDERID_Downloads, 0, NULL, &dlPath);\n localDir = std::wstring(dlPath);\n CoTaskMemFree(dlPath);\n } else {\n wchar_t tmpPath[MAX_PATH];\n DWORD result = GetTempPath(MAX_PATH, tmpPath);\n if (result == 0) {\n CLOG(L\"Could not get temp download path\");\n return L\"\";\n }\n localDir = std::wstring(tmpPath);\n }\n\n if (localDir == L\"\") {\n CLOG(L\"Could not determine local download directory\");\n return L\"\";\n }\n\n std::wstring fname = DownloadFileName(version);\n std::wstring url = DOWNLOAD_URL + fname;\n std::wstring localFile = localDir + L\"\\\\\" + fname;\n\n \/* Make sure we can actually write to the file *\/\n HANDLE fileHandle = CreateFile(\n localFile.c_str(),\n GENERIC_READ | GENERIC_WRITE,\n FILE_SHARE_READ | FILE_SHARE_WRITE,\n NULL,\n CREATE_ALWAYS,\n FILE_ATTRIBUTE_NORMAL,\n NULL);\n if (fileHandle == INVALID_HANDLE_VALUE) {\n CLOG(L\"Could not open destination file\");\n Logger::LogLastError();\n }\n CloseHandle(fileHandle);\n\n CLOG(L\"Downloading %s to %s...\", url.c_str(), localFile.c_str());\n DeleteUrlCacheEntry(url.c_str());\n HRESULT hr = URLDownloadToFile(\n NULL,\n url.c_str(),\n localFile.c_str(),\n 0,\n cb);\n\n if (hr == S_OK) {\n return localFile;\n } else {\n return L\"\";\n }\n}\n\nstd::wstring Updater::DownloadFileName(Version version) {\n std::wstring ext;\n if (Settings::Portable()) {\n ext = L\".zip\";\n } else {\n ext = L\".msi\";\n }\n return std::wstring(L\"3RVX-\" + version.ToString() + ext);\n}\n\nVersion Updater::RemoteVersion() {\n HINTERNET internet = InternetOpen(\n L\"3RVX Updater\",\n INTERNET_OPEN_TYPE_PRECONFIG,\n NULL,\n NULL,\n NULL);\n\n CLOG(L\"Opening URL: %s\", LATEST_URL.c_str());\n HINTERNET connection = InternetOpenUrl(\n internet,\n LATEST_URL.c_str(),\n NULL,\n 0,\n INTERNET_FLAG_NO_CACHE_WRITE | INTERNET_FLAG_PRAGMA_NOCACHE,\n 0);\n\n if (connection == NULL) {\n CLOG(L\"Could not connect to URL!\");\n return { 0, 0, 0 };\n }\n\n std::string str(\"\");\n char buf[32];\n DWORD read;\n while (InternetReadFile(connection, buf, 16, &read) == TRUE && read != 0) {\n str.append(buf);\n }\n\n \/* Only consider the first line *\/\n str.erase(str.find('\\n'), str.size() - 1);\n\n size_t dot = str.find('.');\n size_t dot2 = str.find('.', dot + 1);\n std::string major = str.substr(0, dot);\n std::string minor = str.substr(dot + 1, dot2);\n std::string rev = str.substr(dot2 + 1, str.size());\n return Version(std::stoi(major), std::stoi(minor), std::stoi(rev));\n}<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"base\/bind.h\"\n#include \"base\/message_loop.h\"\n#include \"base\/time.h\"\n#include \"base\/utf_string_conversions.h\"\n#include \"chrome\/browser\/ui\/autofill\/autofill_dialog_controller_impl.h\"\n#include \"chrome\/browser\/ui\/autofill\/autofill_dialog_view.h\"\n#include \"chrome\/browser\/ui\/browser.h\"\n#include \"chrome\/browser\/ui\/tabs\/tab_strip_model.h\"\n#include \"chrome\/test\/base\/in_process_browser_test.h\"\n#include \"components\/autofill\/browser\/autofill_metrics.h\"\n#include \"components\/autofill\/common\/form_data.h\"\n#include \"components\/autofill\/common\/form_field_data.h\"\n#include \"content\/public\/test\/test_utils.h\"\n#include \"testing\/gtest\/include\/gtest\/gtest.h\"\n\nnamespace autofill {\n\nnamespace {\n\nvoid MockCallback(const FormStructure*, const std::string&) {}\n\nclass MockAutofillMetrics : public AutofillMetrics {\n public:\n MockAutofillMetrics()\n : dialog_type_(static_cast<DialogType>(-1)),\n dialog_dismissal_action_(\n static_cast<AutofillMetrics::DialogDismissalAction>(-1)),\n autocheckout_status_(\n static_cast<AutofillMetrics::AutocheckoutCompletionStatus>(-1)) {}\n virtual ~MockAutofillMetrics() {}\n\n \/\/ AutofillMetrics:\n virtual void LogAutocheckoutDuration(\n const base::TimeDelta& duration,\n AutocheckoutCompletionStatus status) const OVERRIDE {\n \/\/ Ignore constness for testing.\n MockAutofillMetrics* mutable_this = const_cast<MockAutofillMetrics*>(this);\n mutable_this->autocheckout_status_ = status;\n }\n\n virtual void LogDialogUiDuration(\n const base::TimeDelta& duration,\n DialogType dialog_type,\n DialogDismissalAction dismissal_action) const OVERRIDE {\n \/\/ Ignore constness for testing.\n MockAutofillMetrics* mutable_this = const_cast<MockAutofillMetrics*>(this);\n mutable_this->dialog_type_ = dialog_type;\n mutable_this->dialog_dismissal_action_ = dismissal_action;\n }\n\n DialogType dialog_type() const { return dialog_type_; }\n AutofillMetrics::DialogDismissalAction dialog_dismissal_action() const {\n return dialog_dismissal_action_;\n }\n\n AutofillMetrics::AutocheckoutCompletionStatus autocheckout_status() const {\n return autocheckout_status_;\n }\n\n private:\n DialogType dialog_type_;\n AutofillMetrics::DialogDismissalAction dialog_dismissal_action_;\n AutofillMetrics::AutocheckoutCompletionStatus autocheckout_status_;\n\n DISALLOW_COPY_AND_ASSIGN(MockAutofillMetrics);\n};\n\nclass TestAutofillDialogController : public AutofillDialogControllerImpl {\n public:\n TestAutofillDialogController(content::WebContents* contents,\n const FormData& form_data,\n const AutofillMetrics& metric_logger,\n const DialogType dialog_type)\n : AutofillDialogControllerImpl(contents,\n form_data,\n GURL(),\n dialog_type,\n base::Bind(&MockCallback)),\n metric_logger_(metric_logger) {\n DisableWallet();\n }\n\n virtual ~TestAutofillDialogController() {}\n\n virtual void ViewClosed() OVERRIDE {\n AutofillDialogControllerImpl::ViewClosed();\n MessageLoop::current()->Quit();\n }\n\n virtual bool InputIsValid(AutofillFieldType type,\n const string16& value) const OVERRIDE {\n return true;\n }\n\n virtual std::vector<AutofillFieldType> InputsAreValid(\n const DetailOutputMap& inputs,\n ValidationType validation_type) const OVERRIDE {\n return std::vector<AutofillFieldType>();\n }\n\n \/\/ Increase visibility for testing.\n AutofillDialogView* view() { return AutofillDialogControllerImpl::view(); }\n\n private:\n \/\/ To specify our own metric logger.\n virtual const AutofillMetrics& GetMetricLogger() const OVERRIDE {\n return metric_logger_;\n }\n\n const AutofillMetrics& metric_logger_;\n\n DISALLOW_COPY_AND_ASSIGN(TestAutofillDialogController);\n};\n\n} \/\/ namespace\n\nclass AutofillDialogControllerTest : public InProcessBrowserTest {\n public:\n AutofillDialogControllerTest() {}\n virtual ~AutofillDialogControllerTest() {}\n\n content::WebContents* GetActiveWebContents() {\n return browser()->tab_strip_model()->GetActiveWebContents();\n }\n\n private:\n DISALLOW_COPY_AND_ASSIGN(AutofillDialogControllerTest);\n};\n\n\/\/ TODO(isherman): Enable this test on other platforms once the UI is\n\/\/ implemented on those platforms.\n#if defined(TOOLKIT_VIEWS)\n#define MAYBE_RequestAutocompleteUiDurationMetrics \\\n RequestAutocompleteUiDurationMetrics\n#else\n#define MAYBE_RequestAutocompleteUiDurationMetrics \\\n DISABLED_RequestAutocompleteUiDurationMetrics\n#endif \/\/ defined(TOOLKIT_VIEWS)\nIN_PROC_BROWSER_TEST_F(AutofillDialogControllerTest,\n MAYBE_RequestAutocompleteUiDurationMetrics) {\n FormData form;\n form.name = ASCIIToUTF16(\"TestForm\");\n form.method = ASCIIToUTF16(\"POST\");\n form.origin = GURL(\"http:\/\/example.com\/form.html\");\n form.action = GURL(\"http:\/\/example.com\/submit.html\");\n form.user_submitted = true;\n\n FormFieldData field;\n field.autocomplete_attribute = \"email\";\n form.fields.push_back(field);\n\n \/\/ Submit the form data.\n {\n MockAutofillMetrics metric_logger;\n TestAutofillDialogController* dialog_controller =\n new TestAutofillDialogController(\n GetActiveWebContents(), form, metric_logger,\n DIALOG_TYPE_REQUEST_AUTOCOMPLETE);\n dialog_controller->Show();\n dialog_controller->view()->SubmitForTesting();\n\n content::RunMessageLoop();\n\n EXPECT_EQ(AutofillMetrics::DIALOG_ACCEPTED,\n metric_logger.dialog_dismissal_action());\n EXPECT_EQ(DIALOG_TYPE_REQUEST_AUTOCOMPLETE, metric_logger.dialog_type());\n }\n\n \/\/ Cancel out of the dialog.\n {\n MockAutofillMetrics metric_logger;\n TestAutofillDialogController* dialog_controller =\n new TestAutofillDialogController(\n GetActiveWebContents(), form, metric_logger,\n DIALOG_TYPE_AUTOCHECKOUT);\n dialog_controller->Show();\n dialog_controller->view()->CancelForTesting();\n\n content::RunMessageLoop();\n\n EXPECT_EQ(AutofillMetrics::DIALOG_CANCELED,\n metric_logger.dialog_dismissal_action());\n EXPECT_EQ(DIALOG_TYPE_AUTOCHECKOUT, metric_logger.dialog_type());\n }\n\n \/\/ Take some other action that dismisses the dialog.\n {\n MockAutofillMetrics metric_logger;\n TestAutofillDialogController* dialog_controller =\n new TestAutofillDialogController(\n GetActiveWebContents(), form, metric_logger,\n DIALOG_TYPE_AUTOCHECKOUT);\n dialog_controller->Show();\n dialog_controller->Hide();\n\n content::RunMessageLoop();\n\n EXPECT_EQ(AutofillMetrics::DIALOG_CANCELED,\n metric_logger.dialog_dismissal_action());\n EXPECT_EQ(DIALOG_TYPE_AUTOCHECKOUT, metric_logger.dialog_type());\n }\n\n \/\/ Test Autocheckout success metrics.\n {\n MockAutofillMetrics metric_logger;\n TestAutofillDialogController* dialog_controller =\n new TestAutofillDialogController(\n GetActiveWebContents(), form, metric_logger,\n DIALOG_TYPE_AUTOCHECKOUT);\n dialog_controller->Show();\n dialog_controller->view()->SubmitForTesting();\n\n EXPECT_EQ(AutofillMetrics::DIALOG_ACCEPTED,\n metric_logger.dialog_dismissal_action());\n EXPECT_EQ(DIALOG_TYPE_AUTOCHECKOUT, metric_logger.dialog_type());\n\n dialog_controller->Hide();\n\n content::RunMessageLoop();\n\n EXPECT_EQ(AutofillMetrics::AUTOCHECKOUT_SUCCEEDED,\n metric_logger.autocheckout_status());\n }\n\n \/\/ Test Autocheckout failure metric.\n {\n MockAutofillMetrics metric_logger;\n TestAutofillDialogController* dialog_controller =\n new TestAutofillDialogController(\n GetActiveWebContents(), form, metric_logger,\n DIALOG_TYPE_AUTOCHECKOUT);\n dialog_controller->Show();\n dialog_controller->view()->SubmitForTesting();\n\n EXPECT_EQ(AutofillMetrics::DIALOG_ACCEPTED,\n metric_logger.dialog_dismissal_action());\n EXPECT_EQ(DIALOG_TYPE_AUTOCHECKOUT, metric_logger.dialog_type());\n\n dialog_controller->OnAutocheckoutError();\n dialog_controller->view()->CancelForTesting();\n\n content::RunMessageLoop();\n\n EXPECT_EQ(AutofillMetrics::AUTOCHECKOUT_FAILED,\n metric_logger.autocheckout_status());\n }\n}\n\n} \/\/ namespace autofill\n<commit_msg>[Autofill] Fix MessageLoop in test.<commit_after>\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"base\/bind.h\"\n#include \"base\/memory\/ref_counted.h\"\n#include \"base\/message_loop.h\"\n#include \"base\/time.h\"\n#include \"base\/utf_string_conversions.h\"\n#include \"chrome\/browser\/ui\/autofill\/autofill_dialog_controller_impl.h\"\n#include \"chrome\/browser\/ui\/autofill\/autofill_dialog_view.h\"\n#include \"chrome\/browser\/ui\/browser.h\"\n#include \"chrome\/browser\/ui\/tabs\/tab_strip_model.h\"\n#include \"chrome\/test\/base\/in_process_browser_test.h\"\n#include \"components\/autofill\/browser\/autofill_metrics.h\"\n#include \"components\/autofill\/common\/form_data.h\"\n#include \"components\/autofill\/common\/form_field_data.h\"\n#include \"content\/public\/test\/test_utils.h\"\n#include \"testing\/gtest\/include\/gtest\/gtest.h\"\n\nnamespace autofill {\n\nnamespace {\n\nvoid MockCallback(const FormStructure*, const std::string&) {}\n\nclass MockAutofillMetrics : public AutofillMetrics {\n public:\n MockAutofillMetrics()\n : dialog_type_(static_cast<DialogType>(-1)),\n dialog_dismissal_action_(\n static_cast<AutofillMetrics::DialogDismissalAction>(-1)),\n autocheckout_status_(\n static_cast<AutofillMetrics::AutocheckoutCompletionStatus>(-1)) {}\n virtual ~MockAutofillMetrics() {}\n\n \/\/ AutofillMetrics:\n virtual void LogAutocheckoutDuration(\n const base::TimeDelta& duration,\n AutocheckoutCompletionStatus status) const OVERRIDE {\n \/\/ Ignore constness for testing.\n MockAutofillMetrics* mutable_this = const_cast<MockAutofillMetrics*>(this);\n mutable_this->autocheckout_status_ = status;\n }\n\n virtual void LogDialogUiDuration(\n const base::TimeDelta& duration,\n DialogType dialog_type,\n DialogDismissalAction dismissal_action) const OVERRIDE {\n \/\/ Ignore constness for testing.\n MockAutofillMetrics* mutable_this = const_cast<MockAutofillMetrics*>(this);\n mutable_this->dialog_type_ = dialog_type;\n mutable_this->dialog_dismissal_action_ = dismissal_action;\n }\n\n DialogType dialog_type() const { return dialog_type_; }\n AutofillMetrics::DialogDismissalAction dialog_dismissal_action() const {\n return dialog_dismissal_action_;\n }\n\n AutofillMetrics::AutocheckoutCompletionStatus autocheckout_status() const {\n return autocheckout_status_;\n }\n\n private:\n DialogType dialog_type_;\n AutofillMetrics::DialogDismissalAction dialog_dismissal_action_;\n AutofillMetrics::AutocheckoutCompletionStatus autocheckout_status_;\n\n DISALLOW_COPY_AND_ASSIGN(MockAutofillMetrics);\n};\n\nclass TestAutofillDialogController : public AutofillDialogControllerImpl {\n public:\n TestAutofillDialogController(content::WebContents* contents,\n const FormData& form_data,\n const AutofillMetrics& metric_logger,\n scoped_refptr<content::MessageLoopRunner> runner,\n const DialogType dialog_type)\n : AutofillDialogControllerImpl(contents,\n form_data,\n GURL(),\n dialog_type,\n base::Bind(&MockCallback)),\n metric_logger_(metric_logger),\n message_loop_runner_(runner) {\n DisableWallet();\n }\n\n virtual ~TestAutofillDialogController() {}\n\n virtual void ViewClosed() OVERRIDE {\n message_loop_runner_->Quit();\n AutofillDialogControllerImpl::ViewClosed();\n }\n\n virtual bool InputIsValid(AutofillFieldType type,\n const string16& value) const OVERRIDE {\n return true;\n }\n\n virtual std::vector<AutofillFieldType> InputsAreValid(\n const DetailOutputMap& inputs,\n ValidationType validation_type) const OVERRIDE {\n return std::vector<AutofillFieldType>();\n }\n\n \/\/ Increase visibility for testing.\n AutofillDialogView* view() { return AutofillDialogControllerImpl::view(); }\n\n private:\n \/\/ To specify our own metric logger.\n virtual const AutofillMetrics& GetMetricLogger() const OVERRIDE {\n return metric_logger_;\n }\n\n const AutofillMetrics& metric_logger_;\n scoped_refptr<content::MessageLoopRunner> message_loop_runner_;\n\n DISALLOW_COPY_AND_ASSIGN(TestAutofillDialogController);\n};\n\n} \/\/ namespace\n\nclass AutofillDialogControllerTest : public InProcessBrowserTest {\n public:\n AutofillDialogControllerTest() {}\n virtual ~AutofillDialogControllerTest() {}\n\n content::WebContents* GetActiveWebContents() {\n return browser()->tab_strip_model()->GetActiveWebContents();\n }\n\n TestAutofillDialogController* CreateController(\n const FormData& form,\n const AutofillMetrics& metric_logger,\n const DialogType dialog_type) {\n message_loop_runner_ = new content::MessageLoopRunner;\n return new TestAutofillDialogController(\n GetActiveWebContents(), form, metric_logger, message_loop_runner_,\n dialog_type);\n }\n\n void RunMessageLoop() {\n message_loop_runner_->Run();\n }\n\n private:\n scoped_refptr<content::MessageLoopRunner> message_loop_runner_;\n DISALLOW_COPY_AND_ASSIGN(AutofillDialogControllerTest);\n};\n\n\/\/ TODO(isherman): Enable this test on other platforms once the UI is\n\/\/ implemented on those platforms.\n#if defined(TOOLKIT_VIEWS)\n#define MAYBE_RequestAutocompleteUiDurationMetrics \\\n RequestAutocompleteUiDurationMetrics\n#else\n#define MAYBE_RequestAutocompleteUiDurationMetrics \\\n DISABLED_RequestAutocompleteUiDurationMetrics\n#endif \/\/ defined(TOOLKIT_VIEWS)\nIN_PROC_BROWSER_TEST_F(AutofillDialogControllerTest,\n MAYBE_RequestAutocompleteUiDurationMetrics) {\n FormData form;\n form.name = ASCIIToUTF16(\"TestForm\");\n form.method = ASCIIToUTF16(\"POST\");\n form.origin = GURL(\"http:\/\/example.com\/form.html\");\n form.action = GURL(\"http:\/\/example.com\/submit.html\");\n form.user_submitted = true;\n\n FormFieldData field;\n field.autocomplete_attribute = \"email\";\n form.fields.push_back(field);\n\n \/\/ Submit the form data.\n {\n MockAutofillMetrics metric_logger;\n TestAutofillDialogController* dialog_controller = CreateController(\n form, metric_logger, DIALOG_TYPE_REQUEST_AUTOCOMPLETE);\n dialog_controller->Show();\n dialog_controller->view()->SubmitForTesting();\n\n RunMessageLoop();\n\n EXPECT_EQ(AutofillMetrics::DIALOG_ACCEPTED,\n metric_logger.dialog_dismissal_action());\n EXPECT_EQ(DIALOG_TYPE_REQUEST_AUTOCOMPLETE, metric_logger.dialog_type());\n }\n\n \/\/ Cancel out of the dialog.\n {\n MockAutofillMetrics metric_logger;\n TestAutofillDialogController* dialog_controller = CreateController(\n form, metric_logger, DIALOG_TYPE_AUTOCHECKOUT);\n dialog_controller->Show();\n dialog_controller->view()->CancelForTesting();\n\n RunMessageLoop();\n\n EXPECT_EQ(AutofillMetrics::DIALOG_CANCELED,\n metric_logger.dialog_dismissal_action());\n EXPECT_EQ(DIALOG_TYPE_AUTOCHECKOUT, metric_logger.dialog_type());\n }\n\n \/\/ Take some other action that dismisses the dialog.\n {\n MockAutofillMetrics metric_logger;\n TestAutofillDialogController* dialog_controller = CreateController(\n form, metric_logger, DIALOG_TYPE_AUTOCHECKOUT);\n dialog_controller->Show();\n dialog_controller->Hide();\n\n RunMessageLoop();\n\n EXPECT_EQ(AutofillMetrics::DIALOG_CANCELED,\n metric_logger.dialog_dismissal_action());\n EXPECT_EQ(DIALOG_TYPE_AUTOCHECKOUT, metric_logger.dialog_type());\n }\n\n \/\/ Test Autocheckout success metrics.\n {\n MockAutofillMetrics metric_logger;\n TestAutofillDialogController* dialog_controller = CreateController(\n form, metric_logger, DIALOG_TYPE_AUTOCHECKOUT);\n dialog_controller->Show();\n dialog_controller->view()->SubmitForTesting();\n\n EXPECT_EQ(AutofillMetrics::DIALOG_ACCEPTED,\n metric_logger.dialog_dismissal_action());\n EXPECT_EQ(DIALOG_TYPE_AUTOCHECKOUT, metric_logger.dialog_type());\n\n dialog_controller->Hide();\n\n RunMessageLoop();\n\n EXPECT_EQ(AutofillMetrics::AUTOCHECKOUT_SUCCEEDED,\n metric_logger.autocheckout_status());\n }\n\n \/\/ Test Autocheckout failure metric.\n {\n MockAutofillMetrics metric_logger;\n TestAutofillDialogController* dialog_controller = CreateController(\n form, metric_logger, DIALOG_TYPE_AUTOCHECKOUT);\n dialog_controller->Show();\n dialog_controller->view()->SubmitForTesting();\n\n EXPECT_EQ(AutofillMetrics::DIALOG_ACCEPTED,\n metric_logger.dialog_dismissal_action());\n EXPECT_EQ(DIALOG_TYPE_AUTOCHECKOUT, metric_logger.dialog_type());\n\n dialog_controller->OnAutocheckoutError();\n dialog_controller->view()->CancelForTesting();\n\n RunMessageLoop();\n\n EXPECT_EQ(AutofillMetrics::AUTOCHECKOUT_FAILED,\n metric_logger.autocheckout_status());\n }\n}\n\n} \/\/ namespace autofill\n<|endoftext|>"} {"text":"<commit_before>\/**\n * @file\tpci_device_base.cpp\n * @brief\tPCI デバイス基底クラス実装。\n * @author\tMasakazu Asama <m-asama@ginzado.co.jp>\n *\/\n\n#include \"pci_device_management.h\"\n\n#include \"pci_device_base.h\"\n\npci_device_base::pci_device_base()\n\t: m_bus(-1), m_slot(-1)\n{\n}\n\npci_device_base::~pci_device_base()\n{\n}\n\nbool\npci_device_base::operator==(const pci_device_base &rhs)\n{\n\tif ((m_bus == rhs.m_bus)\n\t && (m_slot == rhs.m_slot)) {\n\t\treturn true;\n\t}\n\treturn false;\n}\n\nbool\npci_device_base::operator>(const pci_device_base &rhs)\n{\n\tif ((m_bus > rhs.m_bus)\n\t || ((m_bus == rhs.m_bus)\n\t && (m_slot > rhs.m_slot))) {\n\t\treturn true;\n\t}\n\treturn false;\n}\n\nvoid\npci_device_base::bus(sint16_t bus)\n{\n\tm_bus = bus;\n}\n\nsint16_t\npci_device_base::bus()\n{\n\treturn m_bus;\n}\n\nvoid\npci_device_base::slot(sint16_t slot)\n{\n\tm_slot = slot;\n}\n\nsint16_t\npci_device_base::slot()\n{\n\treturn m_slot;\n}\n\nutf8str\npci_device_base::pci_dump()\n{\n\tutf8str s;\n\ts += \"Bus: \";\n\ts.append_hex64(m_bus, 2);\n\ts += \" Slot: \";\n\ts.append_hex64(m_slot, 2);\n\ts += \"\\n\";\n\ts += \" Vendor ID: \";\n\ts.append_hex64(pci_config_read_uint16(m_bus, m_slot, 0, 0x00), 4);\n\ts += \" Device ID: \";\n\ts.append_hex64(pci_config_read_uint16(m_bus, m_slot, 0, 0x02), 4);\n\ts += \"\\n\";\n\ts += \" Command: \";\n\ts.append_hex64(pci_config_read_uint16(m_bus, m_slot, 0, 0x04), 4);\n\ts += \" Status: \";\n\ts.append_hex64(pci_config_read_uint16(m_bus, m_slot, 0, 0x06), 4);\n\ts += \"\\n\";\n\ts += \" Revision ID: \";\n\ts.append_hex64(pci_config_read_uint8(m_bus, m_slot, 0, 0x08), 2);\n\ts += \" Class Code: \";\n\ts.append_hex64((pci_config_read_uint32(m_bus, m_slot, 0, 0x08) >> 8), 6);\n\ts += \"\\n\";\n\ts += \" Cacheline Size: \";\n\ts.append_hex64(pci_config_read_uint8(m_bus, m_slot, 0, 0x0c), 2);\n\ts += \" Latency Timer: \";\n\ts.append_hex64(pci_config_read_uint8(m_bus, m_slot, 0, 0x0d), 2);\n\ts += \" Header Type: \";\n\ts.append_hex64(pci_config_read_uint8(m_bus, m_slot, 0, 0x0e), 2);\n\ts += \" BIST: \";\n\ts.append_hex64(pci_config_read_uint8(m_bus, m_slot, 0, 0x0f), 2);\n\ts += \"\\n\";\n\ts += \" Base Address Register 1: \";\n\ts.append_hex64(pci_config_read_uint32(m_bus, m_slot, 0, 0x10), 8);\n\ts += \"\\n\";\n\ts += \" Base Address Register 2: \";\n\ts.append_hex64(pci_config_read_uint32(m_bus, m_slot, 0, 0x14), 8);\n\ts += \"\\n\";\n\ts += \" Base Address Register 3: \";\n\ts.append_hex64(pci_config_read_uint32(m_bus, m_slot, 0, 0x18), 8);\n\ts += \"\\n\";\n\ts += \" Base Address Register 4: \";\n\ts.append_hex64(pci_config_read_uint32(m_bus, m_slot, 0, 0x1c), 8);\n\ts += \"\\n\";\n\ts += \" Base Address Register 5: \";\n\ts.append_hex64(pci_config_read_uint32(m_bus, m_slot, 0, 0x20), 8);\n\ts += \"\\n\";\n\ts += \" Base Address Register 6: \";\n\ts.append_hex64(pci_config_read_uint32(m_bus, m_slot, 0, 0x24), 8);\n\ts += \"\\n\";\n\ts += \" Cardbus CIS Pointer: \";\n\ts.append_hex64(pci_config_read_uint32(m_bus, m_slot, 0, 0x28), 8);\n\ts += \"\\n\";\n\ts += \" Subsystem Vendor ID: \";\n\ts.append_hex64(pci_config_read_uint16(m_bus, m_slot, 0, 0x2c), 4);\n\ts += \" Subsystem ID: \";\n\ts.append_hex64(pci_config_read_uint16(m_bus, m_slot, 0, 0x2e), 4);\n\ts += \"\\n\";\n\ts += \" Expansion ROM Base Address: \";\n\ts.append_hex64(pci_config_read_uint32(m_bus, m_slot, 0, 0x30), 8);\n\ts += \"\\n\";\n\ts += \" Capabilities Pointer: \";\n\ts.append_hex64(pci_config_read_uint8(m_bus, m_slot, 0, 0x34), 2);\n\ts += \" Reserved: \";\n\ts.append_hex64((pci_config_read_uint32(m_bus, m_slot, 0, 0x34) >> 8), 6);\n\ts += \"\\n\";\n\ts += \" Reserved: \";\n\ts.append_hex64(pci_config_read_uint32(m_bus, m_slot, 0, 0x38), 8);\n\ts += \"\\n\";\n\ts += \" Interrupt Line: \";\n\ts.append_hex64(pci_config_read_uint8(m_bus, m_slot, 0, 0x3c), 2);\n\ts += \" Interrupt Pin: \";\n\ts.append_hex64(pci_config_read_uint8(m_bus, m_slot, 0, 0x3d), 2);\n\ts += \" Min_Gnt: \";\n\ts.append_hex64(pci_config_read_uint8(m_bus, m_slot, 0, 0x3e), 2);\n\ts += \" Max_Lat: \";\n\ts.append_hex64(pci_config_read_uint8(m_bus, m_slot, 0, 0x3f), 2);\n\ts += \"\\n\";\n\n\ts += \" Capabilities List:\\n\";\n\tuint8_t capp = pci_config_read_uint8(m_bus, m_slot, 0, 0x34);\n\twhile (capp != 0x00) {\n\t\tuint8_t capid = pci_config_read_uint8(m_bus, m_slot, 0, capp);\n\t\ts += \" Capability ID: \";\n\t\ts.append_hex64(capid, 2);\n\t\tswitch (capid) {\n\t\tcase 0x01: s += \" (PCI Power Management Interface)\\n\"; break;\n\t\tcase 0x02: s += \" (AGP)\\n\"; break;\n\t\tcase 0x03: s += \" (VPD)\\n\"; break;\n\t\tcase 0x04: s += \" (Slot Identification)\\n\"; break;\n\t\tcase 0x05: s += \" (Message Signaled Interrupts)\\n\"; break;\n\t\tcase 0x06: s += \" (CompactPCI Hot Swap)\\n\"; break;\n\t\tcase 0x07: s += \" (PCI-X)\\n\"; break;\n\t\tcase 0x08: s += \" (HyperTransport)\\n\"; break;\n\t\tcase 0x09: s += \" (Vendor Specific)\\n\"; break;\n\t\tcase 0x0a: s += \" (Debug port)\\n\"; break;\n\t\tcase 0x0b: s += \" (CompactPCI central resource control)\\n\"; break;\n\t\tcase 0x0c: s += \" (PCI Hot-Plug)\\n\"; break;\n\t\tcase 0x0d: s += \" (PCI Bridge Subsystem Vendor ID)\\n\"; break;\n\t\tcase 0x0e: s += \" (AGP 8x)\\n\"; break;\n\t\tcase 0x0f: s += \" (Secure Device)\\n\"; break;\n\t\tcase 0x10: s += \" (PCI Express)\\n\"; break;\n\t\tcase 0x11: s += \" (MSI-X)\\n\"; break;\n\t\tdefault:\n\t\t\ts += \" (Unknown Capability)\\n\";\n\t\t}\n\t\tcapp = pci_config_read_uint8(m_bus, m_slot, 0, capp + 1);\n\t}\n\n\treturn s;\n}\n\n<commit_msg>PCI デバイスのデバッグダンプのケイパビリティに MSI-X の情報を追加。<commit_after>\/**\n * @file\tpci_device_base.cpp\n * @brief\tPCI デバイス基底クラス実装。\n * @author\tMasakazu Asama <m-asama@ginzado.co.jp>\n *\/\n\n#include \"pci_device_management.h\"\n\n#include \"pci_device_base.h\"\n\npci_device_base::pci_device_base()\n\t: m_bus(-1), m_slot(-1)\n{\n}\n\npci_device_base::~pci_device_base()\n{\n}\n\nbool\npci_device_base::operator==(const pci_device_base &rhs)\n{\n\tif ((m_bus == rhs.m_bus)\n\t && (m_slot == rhs.m_slot)) {\n\t\treturn true;\n\t}\n\treturn false;\n}\n\nbool\npci_device_base::operator>(const pci_device_base &rhs)\n{\n\tif ((m_bus > rhs.m_bus)\n\t || ((m_bus == rhs.m_bus)\n\t && (m_slot > rhs.m_slot))) {\n\t\treturn true;\n\t}\n\treturn false;\n}\n\nvoid\npci_device_base::bus(sint16_t bus)\n{\n\tm_bus = bus;\n}\n\nsint16_t\npci_device_base::bus()\n{\n\treturn m_bus;\n}\n\nvoid\npci_device_base::slot(sint16_t slot)\n{\n\tm_slot = slot;\n}\n\nsint16_t\npci_device_base::slot()\n{\n\treturn m_slot;\n}\n\nutf8str\npci_device_base::pci_dump()\n{\n\tutf8str s;\n\ts += \"Bus: \";\n\ts.append_hex64(m_bus, 2);\n\ts += \" Slot: \";\n\ts.append_hex64(m_slot, 2);\n\ts += \"\\n\";\n\ts += \" Vendor ID: \";\n\ts.append_hex64(pci_config_read_uint16(m_bus, m_slot, 0, 0x00), 4);\n\ts += \" Device ID: \";\n\ts.append_hex64(pci_config_read_uint16(m_bus, m_slot, 0, 0x02), 4);\n\ts += \"\\n\";\n\ts += \" Command: \";\n\ts.append_hex64(pci_config_read_uint16(m_bus, m_slot, 0, 0x04), 4);\n\ts += \" Status: \";\n\ts.append_hex64(pci_config_read_uint16(m_bus, m_slot, 0, 0x06), 4);\n\ts += \"\\n\";\n\ts += \" Revision ID: \";\n\ts.append_hex64(pci_config_read_uint8(m_bus, m_slot, 0, 0x08), 2);\n\ts += \" Class Code: \";\n\ts.append_hex64((pci_config_read_uint32(m_bus, m_slot, 0, 0x08) >> 8), 6);\n\ts += \"\\n\";\n\ts += \" Cacheline Size: \";\n\ts.append_hex64(pci_config_read_uint8(m_bus, m_slot, 0, 0x0c), 2);\n\ts += \" Latency Timer: \";\n\ts.append_hex64(pci_config_read_uint8(m_bus, m_slot, 0, 0x0d), 2);\n\ts += \" Header Type: \";\n\ts.append_hex64(pci_config_read_uint8(m_bus, m_slot, 0, 0x0e), 2);\n\ts += \" BIST: \";\n\ts.append_hex64(pci_config_read_uint8(m_bus, m_slot, 0, 0x0f), 2);\n\ts += \"\\n\";\n\tif (pci_config_read_uint8(m_bus, m_slot, 0, 0x0e) != 0x00) {\n\t\treturn s;\n\t}\n\ts += \" Base Address Register 1: \";\n\ts.append_hex64(pci_config_read_uint32(m_bus, m_slot, 0, 0x10), 8);\n\ts += \"\\n\";\n\ts += \" Base Address Register 2: \";\n\ts.append_hex64(pci_config_read_uint32(m_bus, m_slot, 0, 0x14), 8);\n\ts += \"\\n\";\n\ts += \" Base Address Register 3: \";\n\ts.append_hex64(pci_config_read_uint32(m_bus, m_slot, 0, 0x18), 8);\n\ts += \"\\n\";\n\ts += \" Base Address Register 4: \";\n\ts.append_hex64(pci_config_read_uint32(m_bus, m_slot, 0, 0x1c), 8);\n\ts += \"\\n\";\n\ts += \" Base Address Register 5: \";\n\ts.append_hex64(pci_config_read_uint32(m_bus, m_slot, 0, 0x20), 8);\n\ts += \"\\n\";\n\ts += \" Base Address Register 6: \";\n\ts.append_hex64(pci_config_read_uint32(m_bus, m_slot, 0, 0x24), 8);\n\ts += \"\\n\";\n\ts += \" Cardbus CIS Pointer: \";\n\ts.append_hex64(pci_config_read_uint32(m_bus, m_slot, 0, 0x28), 8);\n\ts += \"\\n\";\n\ts += \" Subsystem Vendor ID: \";\n\ts.append_hex64(pci_config_read_uint16(m_bus, m_slot, 0, 0x2c), 4);\n\ts += \" Subsystem ID: \";\n\ts.append_hex64(pci_config_read_uint16(m_bus, m_slot, 0, 0x2e), 4);\n\ts += \"\\n\";\n\ts += \" Expansion ROM Base Address: \";\n\ts.append_hex64(pci_config_read_uint32(m_bus, m_slot, 0, 0x30), 8);\n\ts += \"\\n\";\n\ts += \" Capabilities Pointer: \";\n\ts.append_hex64(pci_config_read_uint8(m_bus, m_slot, 0, 0x34), 2);\n\ts += \" Reserved: \";\n\ts.append_hex64((pci_config_read_uint32(m_bus, m_slot, 0, 0x34) >> 8), 6);\n\ts += \"\\n\";\n\ts += \" Reserved: \";\n\ts.append_hex64(pci_config_read_uint32(m_bus, m_slot, 0, 0x38), 8);\n\ts += \"\\n\";\n\ts += \" Interrupt Line: \";\n\ts.append_hex64(pci_config_read_uint8(m_bus, m_slot, 0, 0x3c), 2);\n\ts += \" Interrupt Pin: \";\n\ts.append_hex64(pci_config_read_uint8(m_bus, m_slot, 0, 0x3d), 2);\n\ts += \" Min_Gnt: \";\n\ts.append_hex64(pci_config_read_uint8(m_bus, m_slot, 0, 0x3e), 2);\n\ts += \" Max_Lat: \";\n\ts.append_hex64(pci_config_read_uint8(m_bus, m_slot, 0, 0x3f), 2);\n\ts += \"\\n\";\n\n\ts += \" Capabilities List:\\n\";\n\tuint8_t capp = pci_config_read_uint8(m_bus, m_slot, 0, 0x34) & 0xfc;\n\twhile (capp != 0x00) {\n\t\tuint8_t capid = pci_config_read_uint8(m_bus, m_slot, 0, capp);\n\t\ts += \" Capability ID: \";\n\t\ts.append_hex64(capid, 2);\n\t\tswitch (capid) {\n\t\tcase 0x01: s += \" (PCI Power Management Interface)\\n\"; break;\n\t\tcase 0x02: s += \" (AGP)\\n\"; break;\n\t\tcase 0x03: s += \" (VPD)\\n\"; break;\n\t\tcase 0x04: s += \" (Slot Identification)\\n\"; break;\n\t\tcase 0x05: s += \" (Message Signaled Interrupts)\\n\"; break;\n\t\tcase 0x06: s += \" (CompactPCI Hot Swap)\\n\"; break;\n\t\tcase 0x07: s += \" (PCI-X)\\n\"; break;\n\t\tcase 0x08: s += \" (HyperTransport)\\n\"; break;\n\t\tcase 0x09: s += \" (Vendor Specific)\\n\"; break;\n\t\tcase 0x0a: s += \" (Debug port)\\n\"; break;\n\t\tcase 0x0b: s += \" (CompactPCI central resource control)\\n\"; break;\n\t\tcase 0x0c: s += \" (PCI Hot-Plug)\\n\"; break;\n\t\tcase 0x0d: s += \" (PCI Bridge Subsystem Vendor ID)\\n\"; break;\n\t\tcase 0x0e: s += \" (AGP 8x)\\n\"; break;\n\t\tcase 0x0f: s += \" (Secure Device)\\n\"; break;\n\t\tcase 0x10: s += \" (PCI Express)\\n\"; break;\n\t\tcase 0x11:\n\t\t\ts += \" (MSI-X)\\n\";\n\t\t\ts += \" Message Control: \";\n\t\t\ts.append_hex64(pci_config_read_uint16(m_bus, m_slot, 0, capp + 2), 4);\n\t\t\ts += \"\\n Table Offset: \";\n\t\t\ts.append_hex64(pci_config_read_uint32(m_bus, m_slot, 0, capp + 4), 8);\n\t\t\ts += \"\\n PBA Offset: \";\n\t\t\ts.append_hex64(pci_config_read_uint32(m_bus, m_slot, 0, capp + 8), 8);\n\t\t\ts += \"\\n\";\n\t\t\tbreak;\n\t\tdefault:\n\t\t\ts += \" (Unknown Capability)\\n\";\n\t\t}\n\t\tcapp = pci_config_read_uint8(m_bus, m_slot, 0, capp + 1) & 0xfc;\n\t}\n\n\treturn s;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/\/----------------------------------------------------------------------------\n\/\/\n\/\/ \"Copyright Centre National d'Etudes Spatiales\"\n\/\/ \"Copyright Centre for Remote Imaging, Sensing and Processing\"\n\/\/\n\/\/ License: LGPL\n\/\/\n\/\/ See LICENSE.txt file in the top level directory for more details.\n\/\/\n\/\/----------------------------------------------------------------------------\n\/\/ $Id$\n\n#include <AlosPalsar\/AlosPalsarData.h>\n#include <AlosPalsar\/AlosPalsarRecordHeader.h>\n\n#include <AlosPalsar\/AlosPalsarDataFileDescriptor.h>\n#include <AlosPalsar\/AlosPalsarSignalData.h>\n\n#include <ossim\/base\/ossimTrace.h>\n#include <ossim\/base\/ossimKeywordlist.h>\n#include <ossim\/base\/ossimKeywordNames.h>\n\n\/\/ Static trace for debugging\nstatic ossimTrace traceDebug(\"ossimAlosPalsarData:debug\");\n\nnamespace ossimplugins\n{\n\nconst int AlosPalsarData::AlosPalsarDataFileDescriptorID = 1;\nconst int AlosPalsarData::AlosPalsarSignalDataID = 2;\n\nAlosPalsarData::AlosPalsarData()\n{\n\n}\n\nAlosPalsarData::~AlosPalsarData()\n{\n ClearRecords();\n}\n\nstd::ostream& operator<<(std::ostream& os, const AlosPalsarData& data)\n{\n std::map<int, AlosPalsarRecord*>::const_iterator it = data._records.begin();\n while (it != data._records.end())\n {\n (*it).second->Write(os);\n ++it;\n }\n return os;\n\n}\n\nstd::istream& operator>>(std::istream& is, AlosPalsarData& data)\n{\n\n data.ClearRecords();\n\n AlosPalsarRecordHeader header;\n\n is >> header;\n\n AlosPalsarRecord* record = new AlosPalsarDataFileDescriptor;\n if (record != NULL)\n {\n record->Read(is);\n data._records[header.get_rec_seq()] = record;\n }\n else\n {\n char* buff = new char[header.get_length()-12];\n is.read(buff, header.get_length() - 12);\n delete buff;\n }\n\n std::streampos filePosition;\n\n filePosition = is.tellg();\n is >> header;\n\n record = new AlosPalsarSignalData;\n\n if (record != NULL)\n {\n record->Read(is);\n data._records[header.get_rec_seq()] = record;\n\/\/ std::cout << \"Record sequence number = \" << header.get_rec_seq() << std::endl;\n }\n is.seekg(filePosition); \/\/ Rewind file pointer to start of record\n \/\/ Then, advance pointer to next record\n is.seekg(static_cast<std::streamoff>(header.get_length()), std::ios::cur);\n\n return is;\n}\n\n\nAlosPalsarData::AlosPalsarData(const AlosPalsarData& rhs)\n{\n std::map<int, AlosPalsarRecord*>::const_iterator it = rhs._records.begin();\n while (it != rhs._records.end())\n {\n _records[(*it).first] = (*it).second->Clone();\n ++it;\n }\n}\n\nAlosPalsarData& AlosPalsarData::operator=(const AlosPalsarData& rhs)\n{\n ClearRecords();\n std::map<int, AlosPalsarRecord*>::const_iterator it = rhs._records.begin();\n while (it != rhs._records.end())\n {\n _records[(*it).first] = (*it).second->Clone();\n ++it;\n }\n\n return *this;\n}\n\nvoid AlosPalsarData::ClearRecords()\n{\n std::map<int, AlosPalsarRecord*>::const_iterator it = _records.begin();\n while (it != _records.end())\n {\n delete(*it).second;\n ++it;\n }\n _records.clear();\n}\n\nbool AlosPalsarData::saveState(ossimKeywordlist& kwl,\n const char* prefix) const\n{\n\n static const char MODULE[] = \"AlosPalsarData::saveState\";\n\n if (traceDebug())\n {\n ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << \" entered...\\n\";\n }\n\n bool result = true;\n\n \/*\n * Adding metadata necessary to the sensor model in the keywordlist\n *\/\n const AlosPalsarDataFileDescriptor *datafiledesc = get_AlosPalsarDataFileDescriptor();\n if (datafiledesc != NULL)\n {\n kwl.add(prefix, \"num_lines\", datafiledesc->get_num_lines(), true);\n kwl.add(prefix, \"num_pix_in_line\", datafiledesc->get_num_pix_in_line(), true);\n }\n else\n {\n result = false;\n }\n\n const AlosPalsarSignalData *signalData = get_AlosPalsarSignalData();\n if (datafiledesc != NULL)\n {\n kwl.add(prefix, \"pulse_repetition_frequency\", signalData->get_pulse_repetition_frequency(), true);\n \/\/ slant range to 1st data sample in metres\n kwl.add(prefix, \"slant_range_to_1st_data_sample\", signalData->get_slant_range_to_1st_data_sample(), true);\n }\n else\n {\n result = false;\n }\n\n\n return result;\n}\n\n\nconst AlosPalsarDataFileDescriptor * AlosPalsarData::get_AlosPalsarDataFileDescriptor() const\n{\n return dynamic_cast<const AlosPalsarDataFileDescriptor*>(_records.find(AlosPalsarDataFileDescriptorID)->second);\n}\n\nconst AlosPalsarSignalData * AlosPalsarData::get_AlosPalsarSignalData() const\n{\n \/\/ TODO: Check if _records[AlosPalsarSignalDataID] works\n return dynamic_cast<const AlosPalsarSignalData*>(_records.find(AlosPalsarSignalDataID)->second);\n}\n\n}\n<commit_msg>Fixed delete [] for array allocated pointer<commit_after>\/\/----------------------------------------------------------------------------\n\/\/\n\/\/ \"Copyright Centre National d'Etudes Spatiales\"\n\/\/ \"Copyright Centre for Remote Imaging, Sensing and Processing\"\n\/\/\n\/\/ License: LGPL\n\/\/\n\/\/ See LICENSE.txt file in the top level directory for more details.\n\/\/\n\/\/----------------------------------------------------------------------------\n\/\/ $Id$\n\n#include <AlosPalsar\/AlosPalsarData.h>\n#include <AlosPalsar\/AlosPalsarRecordHeader.h>\n\n#include <AlosPalsar\/AlosPalsarDataFileDescriptor.h>\n#include <AlosPalsar\/AlosPalsarSignalData.h>\n\n#include <ossim\/base\/ossimTrace.h>\n#include <ossim\/base\/ossimKeywordlist.h>\n#include <ossim\/base\/ossimKeywordNames.h>\n\n\/\/ Static trace for debugging\nstatic ossimTrace traceDebug(\"ossimAlosPalsarData:debug\");\n\nnamespace ossimplugins\n{\n\nconst int AlosPalsarData::AlosPalsarDataFileDescriptorID = 1;\nconst int AlosPalsarData::AlosPalsarSignalDataID = 2;\n\nAlosPalsarData::AlosPalsarData()\n{\n\n}\n\nAlosPalsarData::~AlosPalsarData()\n{\n ClearRecords();\n}\n\nstd::ostream& operator<<(std::ostream& os, const AlosPalsarData& data)\n{\n std::map<int, AlosPalsarRecord*>::const_iterator it = data._records.begin();\n while (it != data._records.end())\n {\n (*it).second->Write(os);\n ++it;\n }\n return os;\n\n}\n\nstd::istream& operator>>(std::istream& is, AlosPalsarData& data)\n{\n\n data.ClearRecords();\n\n AlosPalsarRecordHeader header;\n\n is >> header;\n\n AlosPalsarRecord* record = new AlosPalsarDataFileDescriptor;\n if (record != NULL)\n {\n record->Read(is);\n data._records[header.get_rec_seq()] = record;\n }\n else\n {\n char* buff = new char[header.get_length()-12];\n is.read(buff, header.get_length() - 12);\n delete [] buff;\n }\n\n std::streampos filePosition;\n\n filePosition = is.tellg();\n is >> header;\n\n record = new AlosPalsarSignalData;\n\n if (record != NULL)\n {\n record->Read(is);\n data._records[header.get_rec_seq()] = record;\n\/\/ std::cout << \"Record sequence number = \" << header.get_rec_seq() << std::endl;\n }\n is.seekg(filePosition); \/\/ Rewind file pointer to start of record\n \/\/ Then, advance pointer to next record\n is.seekg(static_cast<std::streamoff>(header.get_length()), std::ios::cur);\n\n return is;\n}\n\n\nAlosPalsarData::AlosPalsarData(const AlosPalsarData& rhs)\n{\n std::map<int, AlosPalsarRecord*>::const_iterator it = rhs._records.begin();\n while (it != rhs._records.end())\n {\n _records[(*it).first] = (*it).second->Clone();\n ++it;\n }\n}\n\nAlosPalsarData& AlosPalsarData::operator=(const AlosPalsarData& rhs)\n{\n ClearRecords();\n std::map<int, AlosPalsarRecord*>::const_iterator it = rhs._records.begin();\n while (it != rhs._records.end())\n {\n _records[(*it).first] = (*it).second->Clone();\n ++it;\n }\n\n return *this;\n}\n\nvoid AlosPalsarData::ClearRecords()\n{\n std::map<int, AlosPalsarRecord*>::const_iterator it = _records.begin();\n while (it != _records.end())\n {\n delete(*it).second;\n ++it;\n }\n _records.clear();\n}\n\nbool AlosPalsarData::saveState(ossimKeywordlist& kwl,\n const char* prefix) const\n{\n\n static const char MODULE[] = \"AlosPalsarData::saveState\";\n\n if (traceDebug())\n {\n ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << \" entered...\\n\";\n }\n\n bool result = true;\n\n \/*\n * Adding metadata necessary to the sensor model in the keywordlist\n *\/\n const AlosPalsarDataFileDescriptor *datafiledesc = get_AlosPalsarDataFileDescriptor();\n if (datafiledesc != NULL)\n {\n kwl.add(prefix, \"num_lines\", datafiledesc->get_num_lines(), true);\n kwl.add(prefix, \"num_pix_in_line\", datafiledesc->get_num_pix_in_line(), true);\n }\n else\n {\n result = false;\n }\n\n const AlosPalsarSignalData *signalData = get_AlosPalsarSignalData();\n if (datafiledesc != NULL)\n {\n kwl.add(prefix, \"pulse_repetition_frequency\", signalData->get_pulse_repetition_frequency(), true);\n \/\/ slant range to 1st data sample in metres\n kwl.add(prefix, \"slant_range_to_1st_data_sample\", signalData->get_slant_range_to_1st_data_sample(), true);\n }\n else\n {\n result = false;\n }\n\n\n return result;\n}\n\n\nconst AlosPalsarDataFileDescriptor * AlosPalsarData::get_AlosPalsarDataFileDescriptor() const\n{\n return dynamic_cast<const AlosPalsarDataFileDescriptor*>(_records.find(AlosPalsarDataFileDescriptorID)->second);\n}\n\nconst AlosPalsarSignalData * AlosPalsarData::get_AlosPalsarSignalData() const\n{\n \/\/ TODO: Check if _records[AlosPalsarSignalDataID] works\n return dynamic_cast<const AlosPalsarSignalData*>(_records.find(AlosPalsarSignalDataID)->second);\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/**\n * kmacctcachedimap.cpp\n *\n * Copyright (c) 2002-2004 Bo Thorsen <bo@klaralvdalens-datakonsult.se>\n * Copyright (c) 2002-2003 Steffen Hansen <steffen@klaralvdalens-datakonsult.se>\n *\n * This program is free software; you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; version 2 of the License\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.\n *\n * In addition, as a special exception, the copyright holders give\n * permission to link the code of this program with any edition of\n * the Qt library by Trolltech AS, Norway (or with modified versions\n * of Qt that use the same license as Qt), and distribute linked\n * combinations including the two. You must obey the GNU General\n * Public License in all respects for all of the code used other than\n * Qt. If you modify this file, you may extend this exception to\n * your version of the file, but you are not obligated to do so. If\n * you do not wish to do so, delete this exception statement from\n * your version.\n *\/\n\n#ifdef HAVE_CONFIG_H\n#include <config.h>\n#endif\n\n#include \"kmacctcachedimap.h\"\nusing KMail::SieveConfig;\n\n#include \"kmfoldertree.h\"\n#include \"kmfoldermgr.h\"\n#include \"kmfiltermgr.h\"\n#include \"kmfoldercachedimap.h\"\n#include \"kmmainwin.h\"\n#include \"kmmainwidget.h\"\n#include \"kmkernel.h\"\n#include \"kmacctmgr.h\"\n#include \"progressmanager.h\"\n\n#include <kio\/passdlg.h>\n#include <kio\/scheduler.h>\n#include <kio\/slave.h>\n#include <kmessagebox.h>\n#include <kdebug.h>\n#include <kstandarddirs.h>\n#include <kapplication.h>\n#include <kconfig.h>\n\n\nKMAcctCachedImap::KMAcctCachedImap( KMAcctMgr* aOwner,\n\t\t\t\t const QString& aAccountName, uint id )\n : KMail::ImapAccountBase( aOwner, aAccountName, id ), mFolder( 0 ),\n mProgressDialogEnabled( true )\n{\n \/\/ Never EVER set this for the cached IMAP account\n mAutoExpunge = false;\n}\n\n\n\/\/-----------------------------------------------------------------------------\nKMAcctCachedImap::~KMAcctCachedImap()\n{\n killAllJobs( true );\n}\n\n\n\/\/-----------------------------------------------------------------------------\nQString KMAcctCachedImap::type() const\n{\n return \"cachedimap\";\n}\n\nvoid KMAcctCachedImap::init() {\n ImapAccountBase::init();\n\n setProgressDialogEnabled( true );\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid KMAcctCachedImap::pseudoAssign( const KMAccount * a ) {\n killAllJobs( true );\n if (mFolder)\n {\n mFolder->setContentState(KMFolderCachedImap::imapNoInformation);\n mFolder->setSubfolderState(KMFolderCachedImap::imapNoInformation);\n }\n\n setProgressDialogEnabled(static_cast<const KMAcctCachedImap*>(a)->isProgressDialogEnabled());\n\n ImapAccountBase::pseudoAssign( a );\n}\n\nvoid KMAcctCachedImap::setPrefixHook() {\n if ( mFolder ) mFolder->setImapPath( prefix() );\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid KMAcctCachedImap::setImapFolder(KMFolderCachedImap *aFolder)\n{\n mFolder = aFolder;\n mFolder->setImapPath(mPrefix);\n mFolder->setAccount( this );\n}\n\n\n\/\/-----------------------------------------------------------------------------\nvoid KMAcctCachedImap::setAutoExpunge( bool \/*aAutoExpunge*\/ )\n{\n \/\/ Never EVER set this for the cached IMAP account\n mAutoExpunge = false;\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid KMAcctCachedImap::killAllJobs( bool disconnectSlave )\n{\n \/\/kdDebug(5006) << \"killAllJobs: disconnectSlave=\" << disconnectSlave << \" \" << mapJobData.count() << \" jobs in map.\" << endl;\n \/\/ Make list of folders to reset. This must be done last, since folderComplete\n \/\/ can trigger the next queued mail check already.\n QValueList<KMFolderCachedImap*> folderList;\n QMap<KIO::Job*, jobData>::Iterator it = mapJobData.begin();\n for (; it != mapJobData.end(); ++it) {\n if ((*it).parent)\n folderList << static_cast<KMFolderCachedImap*>((*it).parent->storage());\n \/\/ Kill the job - except if it's the one that already died and is calling us\n if ( !it.key()->error() && mSlave ) {\n it.key()->kill();\n mSlave = 0; \/\/ killing a job, kills the slave\n }\n }\n mapJobData.clear();\n\n \/\/ Clear the joblist. Make SURE to stop the job emitting \"finished\"\n for( QPtrListIterator<CachedImapJob> it( mJobList ); it.current(); ++it )\n it.current()->setPassiveDestructor( true );\n KMAccount::deleteFolderJobs();\n\n if ( disconnectSlave && slave() ) {\n KIO::Scheduler::disconnectSlave( slave() );\n mSlave = 0;\n }\n for( QValueList<KMFolderCachedImap*>::Iterator it = folderList.begin(); it != folderList.end(); ++it ) {\n KMFolderCachedImap *fld = *it;\n fld->resetSyncState();\n fld->setContentState(KMFolderCachedImap::imapNoInformation);\n fld->setSubfolderState(KMFolderCachedImap::imapNoInformation);\n fld->sendFolderComplete(FALSE);\n }\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid KMAcctCachedImap::cancelMailCheck()\n{\n \/\/ Make list of folders to reset, like in killAllJobs\n QValueList<KMFolderCachedImap*> folderList;\n QMap<KIO::Job*, jobData>::Iterator it = mapJobData.begin();\n for (; it != mapJobData.end(); ++it) {\n if ( (*it).cancellable && (*it).parent )\n folderList << static_cast<KMFolderCachedImap*>((*it).parent->storage());\n }\n \/\/ Kill jobs\n ImapAccountBase::cancelMailCheck();\n \/\/ Reset sync states and emit folderComplete, this is important for\n \/\/ KMAccount::checkingMail() to be reset, in case we restart checking mail later.\n for( QValueList<KMFolderCachedImap*>::Iterator it = folderList.begin(); it != folderList.end(); ++it ) {\n KMFolderCachedImap *fld = *it;\n fld->resetSyncState();\n fld->setContentState(KMFolderCachedImap::imapNoInformation);\n fld->setSubfolderState(KMFolderCachedImap::imapNoInformation);\n fld->sendFolderComplete(FALSE);\n }\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid KMAcctCachedImap::killJobsForItem(KMFolderTreeItem * fti)\n{\n QMap<KIO::Job *, jobData>::Iterator it = mapJobData.begin();\n while (it != mapJobData.end())\n {\n if (it.data().parent == fti->folder())\n {\n killAllJobs();\n break;\n }\n else ++it;\n }\n}\n\n\/\/ Reimplemented from ImapAccountBase because we only check one folder at a time\nvoid KMAcctCachedImap::slotCheckQueuedFolders()\n{\n mMailCheckFolders.clear();\n mMailCheckFolders.append( mFoldersQueuedForChecking.front() );\n mFoldersQueuedForChecking.pop_front();\n if ( mFoldersQueuedForChecking.isEmpty() )\n disconnect( this, SIGNAL( finishedCheck( bool, CheckStatus ) ),\n this, SLOT( slotCheckQueuedFolders() ) );\n\n kmkernel->acctMgr()->singleCheckMail(this, true);\n mMailCheckFolders.clear();\n}\n\nvoid KMAcctCachedImap::processNewMail( bool interactive )\n{\n if ( !mFolder ) { \/\/ happens if this is a pseudo-account (from configuredialog)\n checkDone( false, CheckIgnored );\n return;\n }\n if ( mMailCheckFolders.isEmpty() )\n processNewMail( mFolder, interactive, true );\n else {\n KMFolder* f = mMailCheckFolders.front();\n mMailCheckFolders.pop_front();\n processNewMail( static_cast<KMFolderCachedImap *>( f->storage() ), interactive, false );\n }\n}\n\nvoid KMAcctCachedImap::processNewMail( KMFolderCachedImap* folder,\n\t\t\t\t bool interactive,\n bool recurse )\n{\n \/\/ This should never be set for a cached IMAP account\n mAutoExpunge = false;\n mCountLastUnread = 0;\n mUnreadBeforeCheck.clear();\n\n if( interactive && isProgressDialogEnabled() ) {\n \/\/ Show progress dialog in all kmail-mainwidgets.\n QPtrList<KMMainWidget>* lst = KMMainWidget::mainWidgetList();\n if ( lst ) {\n for( QPtrListIterator<KMMainWidget> it( *lst ); *it; ++it ) {\n (*it)->setProgressDialogVisible( true );\n }\n }\n }\n\n Q_ASSERT( !mMailCheckProgressItem );\n mMailCheckProgressItem = KMail::ProgressManager::createProgressItem(\n \"MailCheck\" + QString::number( id() ),\n folder->label(), \/\/ will be changed immediately in serverSync anyway\n QString::null,\n true, \/\/ can be cancelled\n useSSL() || useTLS() );\n connect( mMailCheckProgressItem, SIGNAL( progressItemCanceled( ProgressItem* ) ),\n this, SLOT( slotProgressItemCanceled( ProgressItem* ) ) );\n\n folder->setAccount(this);\n connect(folder, SIGNAL(folderComplete(KMFolderCachedImap*, bool)),\n\t this, SLOT(postProcessNewMail(KMFolderCachedImap*, bool)));\n folder->serverSync( recurse );\n}\n\nvoid KMAcctCachedImap::postProcessNewMail( KMFolderCachedImap* folder, bool )\n{\n disconnect(folder, SIGNAL(folderComplete(KMFolderCachedImap*, bool)),\n this, SLOT(postProcessNewMail(KMFolderCachedImap*, bool)));\n mMailCheckProgressItem->setComplete();\n mMailCheckProgressItem = 0;\n\n \/\/ We remove everything from the deleted folders list after a sync, unconditionally.\n \/\/ Even if it fails (no permission), because on the next sync we want the folder to reappear,\n \/\/ instead of the user being stuck with \"can't delete\" every time.\n \/\/ And we do it for _all_ deleted folders, even those that were deleted on the server in the first place (slotListResult).\n \/\/ Otherwise this might have side effects much later (e.g. when regaining permissions to a folder we could see before)\n mDeletedFolders.clear();\n mPreviouslyDeletedFolders.clear();\n\n KMail::ImapAccountBase::postProcessNewMail();\n}\n\nvoid KMAcctCachedImap::addUnreadMsgCount( const KMFolderCachedImap *folder,\n int countUnread )\n{\n if ( folder->imapPath() != \"\/INBOX\/\" ) {\n \/\/ new mail in INBOX is processed with KMAccount::processNewMsg() and\n \/\/ therefore doesn't need to be counted here\n const QString folderId = folder->folder()->idString();\n int newInFolder = countUnread;\n if ( mUnreadBeforeCheck.find( folderId ) != mUnreadBeforeCheck.end() )\n newInFolder -= mUnreadBeforeCheck[folderId];\n if ( newInFolder > 0 )\n addToNewInFolder( folderId, newInFolder );\n }\n mCountUnread += countUnread;\n}\n\nvoid KMAcctCachedImap::addLastUnreadMsgCount( const KMFolderCachedImap *folder,\n int countLastUnread )\n{\n mUnreadBeforeCheck[folder->folder()->idString()] = countLastUnread;\n mCountLastUnread += countLastUnread;\n}\n\n\/\/\n\/\/\n\/\/ read\/write config\n\/\/\n\/\/\n\nvoid KMAcctCachedImap::readConfig( \/*const*\/ KConfig\/*Base*\/ & config ) {\n ImapAccountBase::readConfig( config );\n setProgressDialogEnabled( config.readBoolEntry( \"progressdialog\", true ) );\n \/\/ Apparently this method is only ever called once (from KMKernel::init) so this is ok\n mPreviouslyDeletedFolders = config.readListEntry( \"deleted-folders\" );\n mDeletedFolders.clear(); \/\/ but just in case...\n}\n\nvoid KMAcctCachedImap::writeConfig( KConfig\/*Base*\/ & config ) \/*const*\/ {\n ImapAccountBase::writeConfig( config );\n config.writeEntry( \"progressdialog\", isProgressDialogEnabled() );\n config.writeEntry( \"deleted-folders\", mDeletedFolders + mPreviouslyDeletedFolders );\n}\n\nvoid KMAcctCachedImap::invalidateIMAPFolders()\n{\n invalidateIMAPFolders( mFolder );\n}\n\nvoid KMAcctCachedImap::invalidateIMAPFolders( KMFolderCachedImap* folder )\n{\n if( !folder || !folder->folder() )\n return;\n\n folder->setAccount(this);\n\n QStringList strList;\n QValueList<QGuardedPtr<KMFolder> > folderList;\n kmkernel->dimapFolderMgr()->createFolderList( &strList, &folderList,\n\t\t\t\t\t\tfolder->folder()->child(), QString::null,\n\t\t\t\t\t\tfalse );\n QValueList<QGuardedPtr<KMFolder> >::Iterator it;\n mCountLastUnread = 0;\n mUnreadBeforeCheck.clear();\n\n for( it = folderList.begin(); it != folderList.end(); ++it ) {\n KMFolder *f = *it;\n if( f && f->folderType() == KMFolderTypeCachedImap ) {\n KMFolderCachedImap *cfolder = static_cast<KMFolderCachedImap*>(f->storage());\n \/\/ This invalidates the folder completely\n cfolder->setUidValidity(\"INVALID\");\n cfolder->writeUidCache();\n processNewMailSingleFolder( f );\n }\n }\n folder->setUidValidity(\"INVALID\");\n folder->writeUidCache();\n\n processNewMailSingleFolder( folder->folder() );\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid KMAcctCachedImap::addDeletedFolder( const QString& subFolderPath )\n{\n mDeletedFolders.append( subFolderPath );\n}\n\nbool KMAcctCachedImap::isDeletedFolder( const QString& subFolderPath ) const\n{\n return mDeletedFolders.find( subFolderPath ) != mDeletedFolders.end();\n}\n\nbool KMAcctCachedImap::isPreviouslyDeletedFolder( const QString& subFolderPath ) const\n{\n return mPreviouslyDeletedFolders.find( subFolderPath ) != mPreviouslyDeletedFolders.end();\n}\n\nvoid KMAcctCachedImap::removeDeletedFolder( const QString& subFolderPath )\n{\n mDeletedFolders.remove( subFolderPath );\n mPreviouslyDeletedFolders.remove( subFolderPath );\n}\n\nvoid KMAcctCachedImap::slotProgressItemCanceled( ProgressItem* )\n{\n killAllJobs( false );\n}\n\nFolderStorage* KMAcctCachedImap::rootFolder()\n{\n return mFolder;\n}\n\n#include \"kmacctcachedimap.moc\"\n<commit_msg>Use mIdleTimer again, to send a noop every minute, so that we don't end up with a \"connection broken\" error message after not syncing mail for a long time. CCMAIL: hansen@kde.org<commit_after>\/**\n * kmacctcachedimap.cpp\n *\n * Copyright (c) 2002-2004 Bo Thorsen <bo@klaralvdalens-datakonsult.se>\n * Copyright (c) 2002-2003 Steffen Hansen <steffen@klaralvdalens-datakonsult.se>\n *\n * This program is free software; you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; version 2 of the License\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.\n *\n * In addition, as a special exception, the copyright holders give\n * permission to link the code of this program with any edition of\n * the Qt library by Trolltech AS, Norway (or with modified versions\n * of Qt that use the same license as Qt), and distribute linked\n * combinations including the two. You must obey the GNU General\n * Public License in all respects for all of the code used other than\n * Qt. If you modify this file, you may extend this exception to\n * your version of the file, but you are not obligated to do so. If\n * you do not wish to do so, delete this exception statement from\n * your version.\n *\/\n\n#ifdef HAVE_CONFIG_H\n#include <config.h>\n#endif\n\n#include \"kmacctcachedimap.h\"\nusing KMail::SieveConfig;\n\n#include \"kmfoldertree.h\"\n#include \"kmfoldermgr.h\"\n#include \"kmfiltermgr.h\"\n#include \"kmfoldercachedimap.h\"\n#include \"kmmainwin.h\"\n#include \"kmmainwidget.h\"\n#include \"kmkernel.h\"\n#include \"kmacctmgr.h\"\n#include \"progressmanager.h\"\n\n#include <kio\/passdlg.h>\n#include <kio\/scheduler.h>\n#include <kio\/slave.h>\n#include <kmessagebox.h>\n#include <kdebug.h>\n#include <kstandarddirs.h>\n#include <kapplication.h>\n#include <kconfig.h>\n\n\nKMAcctCachedImap::KMAcctCachedImap( KMAcctMgr* aOwner,\n\t\t\t\t const QString& aAccountName, uint id )\n : KMail::ImapAccountBase( aOwner, aAccountName, id ), mFolder( 0 ),\n mProgressDialogEnabled( true )\n{\n \/\/ Never EVER set this for the cached IMAP account\n mAutoExpunge = false;\n}\n\n\n\/\/-----------------------------------------------------------------------------\nKMAcctCachedImap::~KMAcctCachedImap()\n{\n killAllJobs( true );\n}\n\n\n\/\/-----------------------------------------------------------------------------\nQString KMAcctCachedImap::type() const\n{\n return \"cachedimap\";\n}\n\nvoid KMAcctCachedImap::init() {\n ImapAccountBase::init();\n\n setProgressDialogEnabled( true );\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid KMAcctCachedImap::pseudoAssign( const KMAccount * a ) {\n killAllJobs( true );\n if (mFolder)\n {\n mFolder->setContentState(KMFolderCachedImap::imapNoInformation);\n mFolder->setSubfolderState(KMFolderCachedImap::imapNoInformation);\n }\n\n setProgressDialogEnabled(static_cast<const KMAcctCachedImap*>(a)->isProgressDialogEnabled());\n\n ImapAccountBase::pseudoAssign( a );\n}\n\nvoid KMAcctCachedImap::setPrefixHook() {\n if ( mFolder ) mFolder->setImapPath( prefix() );\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid KMAcctCachedImap::setImapFolder(KMFolderCachedImap *aFolder)\n{\n mFolder = aFolder;\n mFolder->setImapPath(mPrefix);\n mFolder->setAccount( this );\n}\n\n\n\/\/-----------------------------------------------------------------------------\nvoid KMAcctCachedImap::setAutoExpunge( bool \/*aAutoExpunge*\/ )\n{\n \/\/ Never EVER set this for the cached IMAP account\n mAutoExpunge = false;\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid KMAcctCachedImap::killAllJobs( bool disconnectSlave )\n{\n \/\/kdDebug(5006) << \"killAllJobs: disconnectSlave=\" << disconnectSlave << \" \" << mapJobData.count() << \" jobs in map.\" << endl;\n \/\/ Make list of folders to reset. This must be done last, since folderComplete\n \/\/ can trigger the next queued mail check already.\n QValueList<KMFolderCachedImap*> folderList;\n QMap<KIO::Job*, jobData>::Iterator it = mapJobData.begin();\n for (; it != mapJobData.end(); ++it) {\n if ((*it).parent)\n folderList << static_cast<KMFolderCachedImap*>((*it).parent->storage());\n \/\/ Kill the job - except if it's the one that already died and is calling us\n if ( !it.key()->error() && mSlave ) {\n it.key()->kill();\n mSlave = 0; \/\/ killing a job, kills the slave\n }\n }\n mapJobData.clear();\n\n \/\/ Clear the joblist. Make SURE to stop the job emitting \"finished\"\n for( QPtrListIterator<CachedImapJob> it( mJobList ); it.current(); ++it )\n it.current()->setPassiveDestructor( true );\n KMAccount::deleteFolderJobs();\n\n if ( disconnectSlave && slave() ) {\n KIO::Scheduler::disconnectSlave( slave() );\n mSlave = 0;\n }\n for( QValueList<KMFolderCachedImap*>::Iterator it = folderList.begin(); it != folderList.end(); ++it ) {\n KMFolderCachedImap *fld = *it;\n fld->resetSyncState();\n fld->setContentState(KMFolderCachedImap::imapNoInformation);\n fld->setSubfolderState(KMFolderCachedImap::imapNoInformation);\n fld->sendFolderComplete(FALSE);\n }\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid KMAcctCachedImap::cancelMailCheck()\n{\n \/\/ Make list of folders to reset, like in killAllJobs\n QValueList<KMFolderCachedImap*> folderList;\n QMap<KIO::Job*, jobData>::Iterator it = mapJobData.begin();\n for (; it != mapJobData.end(); ++it) {\n if ( (*it).cancellable && (*it).parent )\n folderList << static_cast<KMFolderCachedImap*>((*it).parent->storage());\n }\n \/\/ Kill jobs\n ImapAccountBase::cancelMailCheck();\n \/\/ Reset sync states and emit folderComplete, this is important for\n \/\/ KMAccount::checkingMail() to be reset, in case we restart checking mail later.\n for( QValueList<KMFolderCachedImap*>::Iterator it = folderList.begin(); it != folderList.end(); ++it ) {\n KMFolderCachedImap *fld = *it;\n fld->resetSyncState();\n fld->setContentState(KMFolderCachedImap::imapNoInformation);\n fld->setSubfolderState(KMFolderCachedImap::imapNoInformation);\n fld->sendFolderComplete(FALSE);\n }\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid KMAcctCachedImap::killJobsForItem(KMFolderTreeItem * fti)\n{\n QMap<KIO::Job *, jobData>::Iterator it = mapJobData.begin();\n while (it != mapJobData.end())\n {\n if (it.data().parent == fti->folder())\n {\n killAllJobs();\n break;\n }\n else ++it;\n }\n}\n\n\/\/ Reimplemented from ImapAccountBase because we only check one folder at a time\nvoid KMAcctCachedImap::slotCheckQueuedFolders()\n{\n mMailCheckFolders.clear();\n mMailCheckFolders.append( mFoldersQueuedForChecking.front() );\n mFoldersQueuedForChecking.pop_front();\n if ( mFoldersQueuedForChecking.isEmpty() )\n disconnect( this, SIGNAL( finishedCheck( bool, CheckStatus ) ),\n this, SLOT( slotCheckQueuedFolders() ) );\n\n kmkernel->acctMgr()->singleCheckMail(this, true);\n mMailCheckFolders.clear();\n}\n\nvoid KMAcctCachedImap::processNewMail( bool interactive )\n{\n if ( !mFolder ) { \/\/ happens if this is a pseudo-account (from configuredialog)\n checkDone( false, CheckIgnored );\n return;\n }\n if ( mMailCheckFolders.isEmpty() )\n processNewMail( mFolder, interactive, true );\n else {\n KMFolder* f = mMailCheckFolders.front();\n mMailCheckFolders.pop_front();\n processNewMail( static_cast<KMFolderCachedImap *>( f->storage() ), interactive, false );\n }\n}\n\nvoid KMAcctCachedImap::processNewMail( KMFolderCachedImap* folder,\n\t\t\t\t bool interactive,\n bool recurse )\n{\n \/\/ This should never be set for a cached IMAP account\n mAutoExpunge = false;\n mCountLastUnread = 0;\n mUnreadBeforeCheck.clear();\n mIdleTimer.stop();\n\n if( interactive && isProgressDialogEnabled() ) {\n \/\/ Show progress dialog in all kmail-mainwidgets.\n QPtrList<KMMainWidget>* lst = KMMainWidget::mainWidgetList();\n if ( lst ) {\n for( QPtrListIterator<KMMainWidget> it( *lst ); *it; ++it ) {\n (*it)->setProgressDialogVisible( true );\n }\n }\n }\n\n Q_ASSERT( !mMailCheckProgressItem );\n mMailCheckProgressItem = KMail::ProgressManager::createProgressItem(\n \"MailCheck\" + QString::number( id() ),\n folder->label(), \/\/ will be changed immediately in serverSync anyway\n QString::null,\n true, \/\/ can be cancelled\n useSSL() || useTLS() );\n connect( mMailCheckProgressItem, SIGNAL( progressItemCanceled( ProgressItem* ) ),\n this, SLOT( slotProgressItemCanceled( ProgressItem* ) ) );\n\n folder->setAccount(this);\n connect(folder, SIGNAL(folderComplete(KMFolderCachedImap*, bool)),\n\t this, SLOT(postProcessNewMail(KMFolderCachedImap*, bool)));\n folder->serverSync( recurse );\n}\n\nvoid KMAcctCachedImap::postProcessNewMail( KMFolderCachedImap* folder, bool )\n{\n mIdleTimer.start( 60000 ); \/\/ send a noop every minute to avoid \"connection broken\" errors\n mIdle = false; \/\/ noop, don't disconnect (to make interval-mail-check faster)\n disconnect(folder, SIGNAL(folderComplete(KMFolderCachedImap*, bool)),\n this, SLOT(postProcessNewMail(KMFolderCachedImap*, bool)));\n mMailCheckProgressItem->setComplete();\n mMailCheckProgressItem = 0;\n\n \/\/ We remove everything from the deleted folders list after a sync, unconditionally.\n \/\/ Even if it fails (no permission), because on the next sync we want the folder to reappear,\n \/\/ instead of the user being stuck with \"can't delete\" every time.\n \/\/ And we do it for _all_ deleted folders, even those that were deleted on the server in the first place (slotListResult).\n \/\/ Otherwise this might have side effects much later (e.g. when regaining permissions to a folder we could see before)\n mDeletedFolders.clear();\n mPreviouslyDeletedFolders.clear();\n\n KMail::ImapAccountBase::postProcessNewMail();\n}\n\nvoid KMAcctCachedImap::addUnreadMsgCount( const KMFolderCachedImap *folder,\n int countUnread )\n{\n if ( folder->imapPath() != \"\/INBOX\/\" ) {\n \/\/ new mail in INBOX is processed with KMAccount::processNewMsg() and\n \/\/ therefore doesn't need to be counted here\n const QString folderId = folder->folder()->idString();\n int newInFolder = countUnread;\n if ( mUnreadBeforeCheck.find( folderId ) != mUnreadBeforeCheck.end() )\n newInFolder -= mUnreadBeforeCheck[folderId];\n if ( newInFolder > 0 )\n addToNewInFolder( folderId, newInFolder );\n }\n mCountUnread += countUnread;\n}\n\nvoid KMAcctCachedImap::addLastUnreadMsgCount( const KMFolderCachedImap *folder,\n int countLastUnread )\n{\n mUnreadBeforeCheck[folder->folder()->idString()] = countLastUnread;\n mCountLastUnread += countLastUnread;\n}\n\n\/\/\n\/\/\n\/\/ read\/write config\n\/\/\n\/\/\n\nvoid KMAcctCachedImap::readConfig( \/*const*\/ KConfig\/*Base*\/ & config ) {\n ImapAccountBase::readConfig( config );\n setProgressDialogEnabled( config.readBoolEntry( \"progressdialog\", true ) );\n \/\/ Apparently this method is only ever called once (from KMKernel::init) so this is ok\n mPreviouslyDeletedFolders = config.readListEntry( \"deleted-folders\" );\n mDeletedFolders.clear(); \/\/ but just in case...\n}\n\nvoid KMAcctCachedImap::writeConfig( KConfig\/*Base*\/ & config ) \/*const*\/ {\n ImapAccountBase::writeConfig( config );\n config.writeEntry( \"progressdialog\", isProgressDialogEnabled() );\n config.writeEntry( \"deleted-folders\", mDeletedFolders + mPreviouslyDeletedFolders );\n}\n\nvoid KMAcctCachedImap::invalidateIMAPFolders()\n{\n invalidateIMAPFolders( mFolder );\n}\n\nvoid KMAcctCachedImap::invalidateIMAPFolders( KMFolderCachedImap* folder )\n{\n if( !folder || !folder->folder() )\n return;\n\n folder->setAccount(this);\n\n QStringList strList;\n QValueList<QGuardedPtr<KMFolder> > folderList;\n kmkernel->dimapFolderMgr()->createFolderList( &strList, &folderList,\n\t\t\t\t\t\tfolder->folder()->child(), QString::null,\n\t\t\t\t\t\tfalse );\n QValueList<QGuardedPtr<KMFolder> >::Iterator it;\n mCountLastUnread = 0;\n mUnreadBeforeCheck.clear();\n\n for( it = folderList.begin(); it != folderList.end(); ++it ) {\n KMFolder *f = *it;\n if( f && f->folderType() == KMFolderTypeCachedImap ) {\n KMFolderCachedImap *cfolder = static_cast<KMFolderCachedImap*>(f->storage());\n \/\/ This invalidates the folder completely\n cfolder->setUidValidity(\"INVALID\");\n cfolder->writeUidCache();\n processNewMailSingleFolder( f );\n }\n }\n folder->setUidValidity(\"INVALID\");\n folder->writeUidCache();\n\n processNewMailSingleFolder( folder->folder() );\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid KMAcctCachedImap::addDeletedFolder( const QString& subFolderPath )\n{\n mDeletedFolders.append( subFolderPath );\n}\n\nbool KMAcctCachedImap::isDeletedFolder( const QString& subFolderPath ) const\n{\n return mDeletedFolders.find( subFolderPath ) != mDeletedFolders.end();\n}\n\nbool KMAcctCachedImap::isPreviouslyDeletedFolder( const QString& subFolderPath ) const\n{\n return mPreviouslyDeletedFolders.find( subFolderPath ) != mPreviouslyDeletedFolders.end();\n}\n\nvoid KMAcctCachedImap::removeDeletedFolder( const QString& subFolderPath )\n{\n mDeletedFolders.remove( subFolderPath );\n mPreviouslyDeletedFolders.remove( subFolderPath );\n}\n\nvoid KMAcctCachedImap::slotProgressItemCanceled( ProgressItem* )\n{\n killAllJobs( false );\n}\n\nFolderStorage* KMAcctCachedImap::rootFolder()\n{\n return mFolder;\n}\n\n#include \"kmacctcachedimap.moc\"\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n#include <vector>\n#include <cmath>\n#include <random>\n#include <map>\n#include <algorithm>\n#include <cassert>\nusing namespace std;\n\nclass Solution3 {\n public:\n double median(int A[], int m, int B[], int n, int k) { \n if (m > n) return median(B, n, A, m, k);\n int ka = min((k+1)\/2, m), kb = k - ka;\n\n if (m == 0) return B[k-1];\n if (k == 1) return min(A[0], B[0]);\n\n int va = A[ka-1], vb = B[kb-1];\n if (A[ka-1] >= B[kb-1]) return median(A, m, B+kb, n-kb, k-kb);\n else return median(A+ka, m-ka, B, n, k-ka);\n }\n\n double findMedianSortedArrays(int A[], int m, int B[], int n) {\n auto mid = (m+n)\/2;\n bool even = (m+n)%2 == 0;\n\n if (even) \n return (median(A, m, B, n, mid) + median(A, m, B, n, mid+1))\/2.0;\n else \n return median(A, m, B, n, mid+1);\n }\n};\n\nclass Solution2 {\n public:\n \/\/ find right most index whose value is equal or less than val, or -1\n int after(int* arr, int len, int val) {\n int l = 0, r = len-1, m = l;\n while (l <= r) {\n m = l + (r-l)\/2;\n if (arr[m] == val) return m;\n else if (arr[m] > val) r = m-1;\n else l = m+1;\n }\n if (arr[m] > val) m--;\n return m;\n }\n\n double single(int* arr, int len, bool even, int mid) {\n double res = arr[mid];\n if (even) {\n res += arr[mid+1];\n res \/= 2.0;\n }\n return res;\n }\n\n double findMedianSortedArrays(int A[], int m, int B[], int n) {\n auto mid = (m+n-1)\/2;\n bool even = (m+n)%2 == 0;\n if (m == 0) return single(B, n, even, mid);\n else if (n == 0) return single(A, m, even, mid);\n\n int *pa = A, *pb = B;\n if (A[0] > B[0]) { pa = B, pb = A; std::swap(m, n); }\n\n double res = 0.0; \n\n \/\/ no intersection\n if (*(pa+m-1) <= *pb) {\n if (mid >= m) {\n mid -= m; \n res = single(pb, n, even, mid);\n } else {\n res = pa[mid];\n if (even) {\n res += (mid == m-1) ? pb[0]: pa[mid+1];\n res \/= 2.0;\n }\n } \n return res;\n }\n\n \/\/ treat pa as buckets, and pb are values split into buckets\n \/\/ first find which bucket mid reside in, then locate it in the bucket\n\n \/\/ find bucket\n int l = 0, r = m-1, gid = -1, k = l;\n while (l <= r) {\n k = l + (r-l)\/2;\n gid = after(pb, n, pa[k]) + k + 1;\n if (mid == gid) {\n res = pa[k];\n if (even) {\n int t = gid - k;\n if (t >= 0 && pb[t] < pa[k+1]) \n res += pb[t];\n else res += pa[k+1];\n res \/= 2.0;\n }\n return res;\n } else if (mid < gid) {\n r = k-1;\n } else l = k+1;\n }\n\n mid -= k+1;\n res = pb[mid];\n if (even) {\n if (mid + 1 == n || (k+1 < m && pa[k+1] < pb[mid+1])) res += pa[k+1];\n else res += pb[mid+1];\n res \/= 2.0;\n }\n\n return res;\n }\n};\n\nclass Solution {\n public:\n double findMedianSortedArrays(int A[], int m, int B[], int n) {\n auto l = m + n, mid = (m+n)\/2;\n double v = 0, w = 0;\n\n for (int i = 0, j = 0, k = 0; k <= l; ) {\n if (k == mid + 1) {\n if (l % 2 == 0) {\n return (w + v)\/2.0;\n } else \n return v;\n }\n\n w = v;\n if (i >= m) v = B[j++]; \n else if (j >= n) v = A[i++];\n else if (A[i] > B[j]) v = B[j++];\n else v = A[i++];\n k++;\n }\n\n return 0;\n }\n};\n\nvoid test(int A[], int m, int B[], int n) \n{\n cout << Solution().findMedianSortedArrays(A, m, B, n) << endl;\n cout << Solution3().findMedianSortedArrays(A, m, B, n) << endl;\n}\n\n#define LEN(a) (sizeof (a) \/sizeof(a[0]))\n\nint main(int argc, char *argv[])\n{\n int a[] = {};\n int b[] = {1};\n test(a, 0, b, 1);\n\n int a1[] = {3, 5};\n int b1[] = {2};\n test(a1, 2, b1, 1);\n\n int a2[] = {3, 5};\n int b2[] = {2, 7};\n test(a2, 2, b2, 2);\n\n int a3[] = {};\n int b3[] = {2, 3};\n test(a3, 0, b3, 2);\n\n {\n int a[] = {2,3,4,5,6,7};\n int b[] = {1};\n test(a, LEN(a), b, LEN(b));\n }\n {\n int a[] = {2};\n int b[] = {1,3,4};\n test(a, LEN(a), b, LEN(b));\n }\n\n {\n int a[] = {1,3,4,8,9};\n int b[] = {2,5,5,6,7,18};\n test(a, LEN(a), b, LEN(b));\n }\n\n {\n int a[] = {1,3,4,8,9,15};\n int b[] = {2,5,5,6,7,18};\n test(a, LEN(a), b, LEN(b));\n }\n\n {\n int a[] = {1,2,4,8,9,15};\n int b[] = {3,4,5,6,7,18};\n test(a, LEN(a), b, LEN(b));\n }\n {\n int a[] = {1, 12, 15, 26, 38};\n int b[] = {2, 13, 17, 30, 45, 50};\n test(a, LEN(a), b, LEN(b));\n }\n return 0;\n}\n<commit_msg>update<commit_after>#include <iostream>\n#include <vector>\n#include <cmath>\n#include <random>\n#include <map>\n#include <algorithm>\n#include <cassert>\nusing namespace std;\n\nclass Solution3 {\n public:\n double median(int A[], int m, int B[], int n, int k) {\n \/\/ cout << \"m \" << m << \", n \" << n << \", k \" << k << endl;\n if (m == 0) return B[k];\n else if (n == 0) return A[k];\n if (k == 0) return min(A[0], B[0]);\n\n int ka = min((k)\/2, m-1), kb = k - ka - 1;\n \/\/ cout << \"ka \" << ka << \", kb \" << kb << endl;\n if (kb < 0) return A[ka];\n else if (kb > n-1) { kb = n-1; ka = k - kb - 1; }\n\n int va = A[ka], vb = B[kb];\n if (A[ka] >= B[kb]) return median(A, m, B+kb+1, n-kb-1, k-kb-1);\n else return median(A+ka+1, m-ka-1, B, n, k-ka-1);\n }\n\n double findMedianSortedArrays(int A[], int m, int B[], int n) {\n auto mid = (m+n-1)\/2;\n bool even = (m+n)%2 == 0;\n\n if (even) \n return (median(A, m, B, n, mid) + median(A, m, B, n, mid+1))\/2.0;\n else \n return median(A, m, B, n, mid);\n }\n};\n\nclass Solution2 {\n public:\n \/\/ find right most index whose value is equal or less than val, or -1\n int after(int* arr, int len, int val) {\n int l = 0, r = len-1, m = l;\n while (l <= r) {\n m = l + (r-l)\/2;\n if (arr[m] == val) return m;\n else if (arr[m] > val) r = m-1;\n else l = m+1;\n }\n if (arr[m] > val) m--;\n return m;\n }\n\n double single(int* arr, int len, bool even, int mid) {\n double res = arr[mid];\n if (even) res = (res + arr[mid+1]) \/ 2.0; \n return res;\n }\n\n double findMedianSortedArrays(int A[], int m, int B[], int n) {\n auto mid = (m+n-1)\/2;\n bool even = (m+n)%2 == 0;\n if (m == 0) return single(B, n, even, mid);\n else if (n == 0) return single(A, m, even, mid);\n\n int *pa = A, *pb = B;\n if (A[0] > B[0]) { pa = B, pb = A; std::swap(m, n); }\n\n double res = 0.0; \n\n \/\/ treat pa as buckets, and pb are values split into buckets\n \/\/ first find which bucket mid reside in, then locate it in the bucket\n\n \/\/ find bucket\n int l = 0, r = m-1, gid = -1, k = l;\n while (l <= r) {\n k = l + (r-l)\/2;\n gid = after(pb, n, pa[k]) + k + 1;\n if (mid == gid) {\n res = pa[k];\n if (even) {\n int t = gid - k;\n if (t >= 0 && pb[t] < pa[k+1]) \n res += pb[t];\n else res += pa[k+1];\n res \/= 2.0;\n }\n return res;\n } else if (mid < gid) {\n r = k-1;\n } else l = k+1;\n }\n\n if (gid >= mid) k--;\n mid -= k+1;\n res = pb[mid];\n if (even) {\n if (mid + 1 == n || (k+1 < m && pa[k+1] < pb[mid+1])) res += pa[k+1];\n else res += pb[mid+1];\n res \/= 2.0;\n }\n\n return res;\n }\n};\n\n\/\/O(m+n)\nclass Solution {\n public:\n double findMedianSortedArrays(int A[], int m, int B[], int n) {\n auto l = m + n, mid = (m+n)\/2;\n double v = 0, w = 0;\n\n for (int i = 0, j = 0, k = 0; k <= l; ) {\n if (k == mid + 1) {\n if (l % 2 == 0) {\n return (w + v)\/2.0;\n } else \n return v;\n }\n\n w = v;\n if (i >= m) v = B[j++]; \n else if (j >= n) v = A[i++];\n else if (A[i] > B[j]) v = B[j++];\n else v = A[i++];\n k++;\n }\n\n return 0;\n }\n};\n\nvoid test(int A[], int m, int B[], int n) \n{\n cout << Solution().findMedianSortedArrays(A, m, B, n) << endl;\n cout << Solution2().findMedianSortedArrays(A, m, B, n) << endl;\n cout << Solution3().findMedianSortedArrays(A, m, B, n) << endl;\n cout << \"--------------\\n\";\n}\n\n#define LEN(a) (sizeof (a) \/sizeof(a[0]))\n\nint main(int argc, char *argv[])\n{\n int a[] = {};\n int b[] = {1};\n test(a, 0, b, 1);\n\n int a1[] = {3, 5};\n int b1[] = {2};\n test(a1, 2, b1, 1);\n\n int a2[] = {3, 5};\n int b2[] = {2, 7};\n test(a2, 2, b2, 2);\n\n int a3[] = {};\n int b3[] = {2, 3};\n test(a3, 0, b3, 2);\n\n {\n int a[] = {2,3,4,5,6,7};\n int b[] = {1};\n test(a, LEN(a), b, LEN(b));\n }\n {\n int a[] = {2};\n int b[] = {1,3,4};\n test(a, LEN(a), b, LEN(b));\n }\n\n {\n int a[] = {1,3,4,8,9};\n int b[] = {2,5,5,6,7,18};\n test(a, LEN(a), b, LEN(b));\n }\n\n {\n int a[] = {1,3,4,8,9,15};\n int b[] = {2,5,5,6,7,18};\n test(a, LEN(a), b, LEN(b));\n }\n\n {\n int a[] = {1,2,4,8,9,15};\n int b[] = {3,4,5,6,7,18};\n test(a, LEN(a), b, LEN(b));\n }\n {\n int a[] = {1, 12, 15, 26, 38};\n int b[] = {2, 13, 17, 30, 45, 50};\n test(a, LEN(a), b, LEN(b));\n }\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>#pragma once\n\n#include \"PhysicallyBasedMaterial.h\"\n#include \"SkyBoxMaterial.h\"\n\n#include \"VectorIndexer.hpp\"\n#include <tuple>\n\nnamespace Rendering\n{\n\tnamespace Manager\n\t{\n\t\ttemplate <class... Materials>\n\t\tclass MaterialPools final\n\t\t{\n\t\tpublic:\n\t\t\tMaterialPools() = default;\n\t\t\tDISALLOW_ASSIGN_COPY(MaterialPools);\n\n\t\t\ttemplate <typename MaterialType>\n\t\t\tvoid Add(const std::string& key, MaterialType& material)\n\t\t\t{\n\t\t\t\tstd::get<MaterialPool<MaterialType>>(_materials).Add(key, material);\n\t\t\t}\n\t\t\ttemplate <typename MaterialType>\n\t\t\tvoid Delete(const std::string& key)\n\t\t\t{\n\t\t\t\tstd::get<MaterialPool<MaterialType>>(_materials).Delete(key);\n\t\t\t}\n\t\t\ttemplate <typename MaterialType>\n\t\t\tauto Find(const std::string& key)\n\t\t\t{\n\t\t\t\treturn std::get<MaterialPool<MaterialType>>(_materials).Find(key);\n\t\t\t}\n\n\t\t\ttemplate <typename MaterialType>\n\t\t\tconst std::vector<MaterialType>& GetMaterials() const\n\t\t\t{\n\t\t\t\treturn std::get<MaterialPool<MaterialType>>(_materials).GetVector();\n\t\t\t}\n\n\t\tprivate:\n\t\t\ttemplate <class MaterialType>\n\t\t\tclass MaterialPool : public Core::VectorHashMap<std::string, MaterialType> {};\n\n\t\t\tstd::tuple<MaterialPool<Materials>...>\t_materials;\n\t\t};\n\n\t\tclass MaterialManager final\n\t\t{\n\t\tpublic:\n\t\t\tMaterialManager() = default;\n\t\t\tDISALLOW_ASSIGN_COPY(MaterialManager);\n\n\t\t\tauto& Get()\n\t\t\t{\n\t\t\t\treturn _materialSystem;\n\t\t\t}\n\n\t\tprivate:\n\t\t\tMaterialPools<PhysicallyBasedMaterial, SkyBoxMaterial> _materialSystem;\n\t\t};\n\t}\n}<commit_msg>MaterialManager - 코드 정리<commit_after>#pragma once\n\n#include \"PhysicallyBasedMaterial.h\"\n#include \"SkyBoxMaterial.h\"\n\n#include \"VectorIndexer.hpp\"\n#include <tuple>\n\nnamespace Rendering\n{\n\tnamespace Manager\n\t{\n\t\tclass MaterialManager final\n\t\t{\n\t\tpublic:\n\t\t\tMaterialManager() = default;\n\t\t\tDISALLOW_ASSIGN_COPY(MaterialManager);\n\n\t\t\ttemplate <typename MaterialType>\n\t\t\tvoid Add(const std::string& key, MaterialType& material)\n\t\t\t{\n\t\t\t\tstd::get<MaterialPool<MaterialType>>(_materials).Add(key, material);\n\t\t\t}\n\t\t\ttemplate <typename MaterialType>\n\t\t\tvoid Delete(const std::string& key)\n\t\t\t{\n\t\t\t\tstd::get<MaterialPool<MaterialType>>(_materials).Delete(key);\n\t\t\t}\n\t\t\ttemplate <typename MaterialType>\n\t\t\tauto Find(const std::string& key)\n\t\t\t{\n\t\t\t\treturn std::get<MaterialPool<MaterialType>>(_materials).Find(key);\n\t\t\t}\n\n\t\t\ttemplate <typename MaterialType>\n\t\t\tconst std::vector<MaterialType>& GetMaterials() const\n\t\t\t{\n\t\t\t\treturn std::get<MaterialPool<MaterialType>>(_materials).GetVector();\n\t\t\t}\n\n\t\tprivate:\n\t\t\ttemplate <class MaterialType>\n\t\t\tusing MaterialPool = Core::VectorHashMap<std::string, MaterialType>;\n\n\t\t\tstd::tuple<\tMaterialPool<PhysicallyBasedMaterial>,\n\t\t\t\t\t\tMaterialPool<SkyBoxMaterial> >\t_materials;\n\t\t};\n\t}\n}<|endoftext|>"} {"text":"<commit_before><commit_msg>Fixe debug cout<commit_after><|endoftext|>"} {"text":"<commit_before>\/\/ Author: Enrico Guiraud, Danilo Piparo CERN 03\/2017\n\n\/*************************************************************************\n * Copyright (C) 1995-2016, Rene Brun and Fons Rademakers. *\n * All rights reserved. *\n * *\n * For the licensing terms see $ROOTSYS\/LICENSE. *\n * For the list of contributors see $ROOTSYS\/README\/CREDITS. *\n *************************************************************************\/\n\n#ifndef ROOT_TRESULTPROXY\n#define ROOT_TRESULTPROXY\n\n#include \"ROOT\/TypeTraits.hxx\"\n#include \"ROOT\/TDFNodes.hxx\"\n#include \"TError.h\" \/\/ Warning\n\n#include <memory>\n#include <functional>\n\nnamespace ROOT {\n\nnamespace Experimental {\nnamespace TDF {\n\/\/ Fwd decl for MakeResultProxy\ntemplate <typename T>\nclass TResultProxy;\n}\n}\n\nnamespace Detail {\nnamespace TDF {\nusing ROOT::Experimental::TDF::TResultProxy;\n\/\/ Fwd decl for TResultProxy\ntemplate <typename T>\nTResultProxy<T> MakeResultProxy(const std::shared_ptr<T> &r, const std::shared_ptr<TLoopManager> &df,\n TDFInternal::TActionBase *actionPtr);\ntemplate <typename T>\nstd::pair<TResultProxy<T>, std::shared_ptr<ROOT::Internal::TDF::TActionBase *>>\nMakeResultProxy(const std::shared_ptr<T> &r, const std::shared_ptr<TLoopManager> &df);\n} \/\/ ns TDF\n} \/\/ ns Detail\n\nnamespace Experimental {\nnamespace TDF {\nnamespace TDFInternal = ROOT::Internal::TDF;\nnamespace TDFDetail = ROOT::Detail::TDF;\nnamespace TTraits = ROOT::TypeTraits;\n\n\/\/\/ Smart pointer for the return type of actions\n\/**\n\\class ROOT::Experimental::TDF::TResultProxy\n\\ingroup dataframe\n\\brief A wrapper around the result of TDataFrame actions able to trigger calculations lazily.\n\\tparam T Type of the action result\n\nA smart pointer which allows to access the result of a TDataFrame action. The\nmethods of the encapsulated object can be accessed via the arrow operator.\nUpon invocation of the arrow operator or dereferencing (`operator*`), the\nloop on the events and calculations of all scheduled actions are executed\nif needed.\nIt is possible to iterate on the result proxy if the proxied object is a collection.\n~~~{.cpp}\nfor (auto& myItem : myResultProxy) { ... };\n~~~\nIf iteration is not supported by the type of the proxied object, a compilation error is thrown.\n\n*\/\ntemplate <typename T>\nclass TResultProxy {\n \/\/\/ \\cond HIDDEN_SYMBOLS\n template <typename V, bool isCont = TTraits::IsContainer<V>::value>\n struct TIterationHelper {\n using Iterator_t = void;\n void GetBegin(const V &) { static_assert(sizeof(V) == 0, \"It does not make sense to ask begin for this class.\"); }\n void GetEnd(const V &) { static_assert(sizeof(V) == 0, \"It does not make sense to ask end for this class.\"); }\n };\n\n template <typename V>\n struct TIterationHelper<V, true> {\n using Iterator_t = decltype(std::begin(std::declval<V>()));\n static Iterator_t GetBegin(const V &v) { return std::begin(v); };\n static Iterator_t GetEnd(const V &v) { return std::end(v); };\n };\n \/\/\/ \\endcond\n using SPT_t = std::shared_ptr<T>;\n using SPTLM_t = std::shared_ptr<TDFDetail::TLoopManager>;\n using WPTLM_t = std::weak_ptr<TDFDetail::TLoopManager>;\n using ShrdPtrBool_t = std::shared_ptr<bool>;\n template <typename W>\n friend TResultProxy<W>\n TDFDetail::MakeResultProxy(const std::shared_ptr<W> &, const SPTLM_t &, TDFInternal::TActionBase *);\n template <typename W>\n friend std::pair<TResultProxy<W>, std::shared_ptr<TDFInternal::TActionBase *>>\n TDFDetail::MakeResultProxy(const std::shared_ptr<W> &, const SPTLM_t &);\n\n const ShrdPtrBool_t fReadiness =\n std::make_shared<bool>(false); \/\/\/< State registered also in the TLoopManager until the event loop is executed\n WPTLM_t fImplWeakPtr; \/\/\/< Points to the TLoopManager at the root of the functional graph\n const SPT_t fObjPtr; \/\/\/< Shared pointer encapsulating the wrapped result\n \/\/\/ Shared_ptr to a _pointer_ to the TDF action that produces this result. It is set at construction time for\n \/\/\/ non-jitted actions, and at jitting time for jitted actions (at the time of writing, this means right\n \/\/\/ before the event-loop).\n \/\/ N.B. what's on the heap is the _pointer_ to TActionBase, we are _not_ taking shared ownership of a TAction.\n \/\/ This cannot be a unique_ptr because that would disallow copy-construction of TResultProxies.\n \/\/ It cannot be just a pointer to TActionBase because we need something to store in the callback callable that will\n \/\/ be passed to TLoopManager _before_ the pointer to TActionBase is set in the case of jitted actions.\n const std::shared_ptr<TDFInternal::TActionBase *> fActionPtrPtr;\n\n \/\/\/ Triggers the event loop in the TLoopManager instance to which it's associated via the fImplWeakPtr\n void TriggerRun();\n\n \/\/\/ Get the pointer to the encapsulated result.\n \/\/\/ Ownership is not transferred to the caller.\n \/\/\/ Triggers event loop and execution of all actions booked in the associated TLoopManager.\n T *Get()\n {\n if (!*fReadiness)\n TriggerRun();\n return fObjPtr.get();\n }\n\n TResultProxy(const SPT_t &objPtr, const ShrdPtrBool_t &readiness, const SPTLM_t &loopManager,\n TDFInternal::TActionBase *actionPtr = nullptr)\n : fReadiness(readiness), fImplWeakPtr(loopManager), fObjPtr(objPtr),\n fActionPtrPtr(new (TDFInternal::TActionBase *)(actionPtr))\n {\n }\n\n std::shared_ptr<TDFInternal::TActionBase *> GetActionPtrPtr() const { return fActionPtrPtr; }\n\n void RegisterCallback(ULong64_t everyNEvents, std::function<void(unsigned int)> &&c) {\n auto lm = fImplWeakPtr.lock();\n if (!lm)\n throw std::runtime_error(\"The main TDataFrame is not reachable: did it go out of scope?\");\n lm->RegisterCallback(everyNEvents, std::move(c));\n }\n\npublic:\n using Value_t = T; \/\/\/< Convenience alias to simplify access to proxied type\n static constexpr ULong64_t kOnce = 0ull; \/\/\/< Convenience definition to express a callback must be executed once\n\n TResultProxy() = delete;\n TResultProxy(const TResultProxy &) = default;\n TResultProxy(TResultProxy &&) = default;\n\n \/\/\/ Get a const reference to the encapsulated object.\n \/\/\/ Triggers event loop and execution of all actions booked in the associated TLoopManager.\n const T &GetValue() { return *Get(); }\n\n \/\/\/ Get a pointer to the encapsulated object.\n \/\/\/ Triggers event loop and execution of all actions booked in the associated TLoopManager.\n T &operator*() { return *Get(); }\n\n \/\/\/ Get a pointer to the encapsulated object.\n \/\/\/ Ownership is not transferred to the caller.\n \/\/\/ Triggers event loop and execution of all actions booked in the associated TLoopManager.\n T *operator->() { return Get(); }\n\n \/\/\/ Return an iterator to the beginning of the contained object if this makes\n \/\/\/ sense, throw a compilation error otherwise\n typename TIterationHelper<T>::Iterator_t begin()\n {\n if (!*fReadiness)\n TriggerRun();\n return TIterationHelper<T>::GetBegin(*fObjPtr);\n }\n\n \/\/\/ Return an iterator to the end of the contained object if this makes\n \/\/\/ sense, throw a compilation error otherwise\n typename TIterationHelper<T>::Iterator_t end()\n {\n if (!*fReadiness)\n TriggerRun();\n return TIterationHelper<T>::GetEnd(*fObjPtr);\n }\n\n \/\/\/ Register a callback that TDataFrame will execute \"everyNEvents\" on a partial result.\n \/\/\/\n \/\/\/ \\param[in] everyNEvents Frequency at which the callback will be called, as a number of events processed\n \/\/\/ \\param[in] callback a callable with signature `void(Value_t&)` where Value_t is the type of the value contained in this TResultProxy\n \/\/\/\n \/\/\/ The callback must be a callable (lambda, function, functor class...) that takes a reference to the result type as\n \/\/\/ argument and returns nothing. TDataFrame will invoke registered callbacks passing partial action results as\n \/\/\/ arguments to them (e.g. a histogram filled with a part of the selected events, a counter incremented only up to a\n \/\/\/ certain point, a mean over a subset of the events and so forth).\n \/\/\/\n \/\/\/ Callbacks can be used e.g. to inspect partial results of the analysis while the event loop is running. For\n \/\/\/ example one can draw an up-to-date version of a result histogram every 100 entries like this:\n \/\/\/ \\code{.cpp}\n \/\/\/ auto h = tdf.Histo1D(\"x\");\n \/\/\/ TCanvas c(\"c\",\"x hist\");\n \/\/\/ h.OnPartialResult(100, [&c](TH1D &h_) { c.cd(); h_.Draw(); c.Update(); });\n \/\/\/ h->Draw(); \/\/ event loop runs here, this `Draw` is executed after the event loop is finished\n \/\/\/ \\endcode\n \/\/\/\n \/\/\/ A value of 0 for everyNEvents indicates the callback must be executed only once, before running the event loop.\n \/\/\/ A conveniece definition `kOnce` is provided to make this fact more expressive in user code (see snippet below).\n \/\/\/ Multiple callbacks can be registered with the same TResultProxy (i.e. results of TDataFrame actions) and will\n \/\/\/ be executed sequentially. Callbacks are executed in the order they were registered.\n \/\/\/ The type of the value contained in a TResultProxy is also available as TResultProxy<T>::Value_t, e.g.\n \/\/\/ \\code{.cpp}\n \/\/\/ auto h = tdf.Histo1D(\"x\");\n \/\/\/ \/\/ h.kOnce is 0\n \/\/\/ \/\/ decltype(h)::Value_t is TH1D\n \/\/\/ \\endcode\n \/\/\/\n \/\/\/ When implicit multi-threading is enabled, the callback:\n \/\/\/ - will never be executed by multiple threads concurrently: it needs not be thread-safe. For example the snippet\n \/\/\/ above that draws the partial histogram on a canvas works seamlessly in multi-thread event loops.\n \/\/\/ - will always be executed \"everyNEvents\": partial results will \"contain\" that number of events more from\n \/\/\/ one call to the next\n \/\/\/ - might be executed by a different worker thread at different times: the value of `std::this_thread::get_id()`\n \/\/\/ might change between calls\n \/\/\/ To register a callback that is called by _each_ worker thread (concurrently) every N events one can use\n \/\/\/ OnPartialResultSlot.\n void OnPartialResult(ULong64_t everyNEvents, std::function<void(T&)> callback)\n {\n auto actionPtrPtr = fActionPtrPtr.get();\n auto c = [actionPtrPtr, callback](unsigned int slot) {\n if (slot != 0)\n return;\n auto partialResult = static_cast<Value_t*>((*actionPtrPtr)->PartialUpdate(slot));\n callback(*partialResult);\n };\n RegisterCallback(everyNEvents, std::move(c));\n }\n\n \/\/\/ Register a callback that TDataFrame will execute in each worker thread concurrently on that thread's partial result.\n \/\/\/\n \/\/\/ \\param[in] everyNEvents Frequency at which the callback will be called by each thread, as a number of events processed\n \/\/\/ \\param[in] a callable with signature `void(unsigned int, Value_t&)` where Value_t is the type of the value contained in this TResultProxy\n \/\/\/\n \/\/\/ See `RegisterCallback` for a generic explanation of the callback mechanism.\n \/\/\/ Compared to `RegisterCallback`, this method has two major differences:\n \/\/\/ - all worker threads invoke the callback once every specified number of events. The event count is per-thread,\n \/\/\/ and callback invocation might happen concurrently (i.e. the callback must be thread-safe)\n \/\/\/ - the callable must take an extra `unsigned int` parameter corresponding to a multi-thread \"processing slot\":\n \/\/\/ this is a \"helper value\" to simplify writing thread-safe callbacks: different worker threads might invoke the\n \/\/\/ callback concurrently but always with different `slot` numbers.\n \/\/\/ - a value of 0 for everyNEvents indicates the callback must be executed once _per slot_.\n \/\/\/\n \/\/\/ For example, the following snippet prints out a thread-safe progress bar of the events processed by TDataFrame\n \/\/\/ \\code\n \/\/\/ auto c = tdf.Count(); \/\/ any action would do, but `Count` is the most lightweight\n \/\/\/ std::string progress;\n \/\/\/ std::mutex bar_mutex;\n \/\/\/ c.OnPartialResultSlot(nEvents \/ 100, [&progress, &bar_mutex](unsigned int, ULong64_t &) {\n \/\/\/ std::lock_guard<std::mutex> lg(bar_mutex);\n \/\/\/ progress.push_back('#');\n \/\/\/ std::cout << \"\\r[\" << std::left << std::setw(100) << progress << ']' << std::flush;\n \/\/\/ });\n \/\/\/ std::cout << \"Analysis running...\" << std::endl;\n \/\/\/ *c; \/\/ trigger the event loop by accessing an action's result\n \/\/\/ std::cout << \"\\nDone!\" << std::endl;\n \/\/\/ \\endcode\n void OnPartialResultSlot(ULong64_t everyNEvents, std::function<void(unsigned int, T&)> callback)\n {\n auto actionPtrPtr = fActionPtrPtr.get();\n auto c = [actionPtrPtr, callback](unsigned int slot) {\n auto partialResult = static_cast<Value_t*>((*actionPtrPtr)->PartialUpdate(slot));\n callback(slot, *partialResult);\n };\n RegisterCallback(everyNEvents, std::move(c));\n }\n};\n\ntemplate <typename T>\nvoid TResultProxy<T>::TriggerRun()\n{\n auto df = fImplWeakPtr.lock();\n if (!df) {\n throw std::runtime_error(\"The main TDataFrame is not reachable: did it go out of scope?\");\n }\n df->Run();\n}\n} \/\/ end NS TDF\n} \/\/ end NS Experimental\n\nnamespace Detail {\nnamespace TDF {\n\/\/\/ Create a TResultProxy and set its pointer to the corresponding TAction\n\/\/\/ This overload is invoked by non-jitted actions, as they have access to TAction before constructing TResultProxy.\ntemplate <typename T>\nTResultProxy<T> MakeResultProxy(const std::shared_ptr<T> &r, const std::shared_ptr<TLoopManager> &df,\n TDFInternal::TActionBase *actionPtr)\n{\n auto readiness = std::make_shared<bool>(false);\n auto resPtr = TResultProxy<T>(r, readiness, df, actionPtr);\n df->Book(readiness);\n return resPtr;\n}\n\n\/\/\/ Create a TResultProxy and return it together with its pointer to TAction\n\/\/\/ This overload is invoked by jitted actions; the pointer to TAction will be set right before the loop by jitted code\ntemplate <typename T>\nstd::pair<TResultProxy<T>, std::shared_ptr<TDFInternal::TActionBase *>>\nMakeResultProxy(const std::shared_ptr<T> &r, const std::shared_ptr<TLoopManager> &df)\n{\n auto readiness = std::make_shared<bool>(false);\n auto resPtr = TResultProxy<T>(r, readiness, df);\n df->Book(readiness);\n return std::make_pair(resPtr, resPtr.GetActionPtrPtr());\n}\n} \/\/ end NS TDF\n} \/\/ end NS Detail\n} \/\/ end NS ROOT\n\n#endif \/\/ ROOT_TRESULTPROXY\n<commit_msg>[TDF] Reorder alias and friend declarations in TResultProxy<commit_after>\/\/ Author: Enrico Guiraud, Danilo Piparo CERN 03\/2017\n\n\/*************************************************************************\n * Copyright (C) 1995-2016, Rene Brun and Fons Rademakers. *\n * All rights reserved. *\n * *\n * For the licensing terms see $ROOTSYS\/LICENSE. *\n * For the list of contributors see $ROOTSYS\/README\/CREDITS. *\n *************************************************************************\/\n\n#ifndef ROOT_TRESULTPROXY\n#define ROOT_TRESULTPROXY\n\n#include \"ROOT\/TypeTraits.hxx\"\n#include \"ROOT\/TDFNodes.hxx\"\n#include \"TError.h\" \/\/ Warning\n\n#include <memory>\n#include <functional>\n\nnamespace ROOT {\n\nnamespace Experimental {\nnamespace TDF {\n\/\/ Fwd decl for MakeResultProxy\ntemplate <typename T>\nclass TResultProxy;\n}\n}\n\nnamespace Detail {\nnamespace TDF {\nusing ROOT::Experimental::TDF::TResultProxy;\n\/\/ Fwd decl for TResultProxy\ntemplate <typename T>\nTResultProxy<T> MakeResultProxy(const std::shared_ptr<T> &r, const std::shared_ptr<TLoopManager> &df,\n TDFInternal::TActionBase *actionPtr);\ntemplate <typename T>\nstd::pair<TResultProxy<T>, std::shared_ptr<ROOT::Internal::TDF::TActionBase *>>\nMakeResultProxy(const std::shared_ptr<T> &r, const std::shared_ptr<TLoopManager> &df);\n} \/\/ ns TDF\n} \/\/ ns Detail\n\nnamespace Experimental {\nnamespace TDF {\nnamespace TDFInternal = ROOT::Internal::TDF;\nnamespace TDFDetail = ROOT::Detail::TDF;\nnamespace TTraits = ROOT::TypeTraits;\n\n\/\/\/ Smart pointer for the return type of actions\n\/**\n\\class ROOT::Experimental::TDF::TResultProxy\n\\ingroup dataframe\n\\brief A wrapper around the result of TDataFrame actions able to trigger calculations lazily.\n\\tparam T Type of the action result\n\nA smart pointer which allows to access the result of a TDataFrame action. The\nmethods of the encapsulated object can be accessed via the arrow operator.\nUpon invocation of the arrow operator or dereferencing (`operator*`), the\nloop on the events and calculations of all scheduled actions are executed\nif needed.\nIt is possible to iterate on the result proxy if the proxied object is a collection.\n~~~{.cpp}\nfor (auto& myItem : myResultProxy) { ... };\n~~~\nIf iteration is not supported by the type of the proxied object, a compilation error is thrown.\n\n*\/\ntemplate <typename T>\nclass TResultProxy {\n \/\/ private using declarations\n using SPT_t = std::shared_ptr<T>;\n using SPTLM_t = std::shared_ptr<TDFDetail::TLoopManager>;\n using WPTLM_t = std::weak_ptr<TDFDetail::TLoopManager>;\n using ShrdPtrBool_t = std::shared_ptr<bool>;\n\n \/\/ friend declarations\n template <typename W>\n friend TResultProxy<W>\n TDFDetail::MakeResultProxy(const std::shared_ptr<W> &, const SPTLM_t &, TDFInternal::TActionBase *);\n template <typename W>\n friend std::pair<TResultProxy<W>, std::shared_ptr<TDFInternal::TActionBase *>>\n TDFDetail::MakeResultProxy(const std::shared_ptr<W> &, const SPTLM_t &);\n\n \/\/\/ \\cond HIDDEN_SYMBOLS\n template <typename V, bool isCont = TTraits::IsContainer<V>::value>\n struct TIterationHelper {\n using Iterator_t = void;\n void GetBegin(const V &) { static_assert(sizeof(V) == 0, \"It does not make sense to ask begin for this class.\"); }\n void GetEnd(const V &) { static_assert(sizeof(V) == 0, \"It does not make sense to ask end for this class.\"); }\n };\n\n template <typename V>\n struct TIterationHelper<V, true> {\n using Iterator_t = decltype(std::begin(std::declval<V>()));\n static Iterator_t GetBegin(const V &v) { return std::begin(v); };\n static Iterator_t GetEnd(const V &v) { return std::end(v); };\n };\n \/\/\/ \\endcond\n\n \/\/\/ State registered also in the TLoopManager until the event loop is executed\n const ShrdPtrBool_t fReadiness = std::make_shared<bool>(false);\n WPTLM_t fImplWeakPtr; \/\/\/< Points to the TLoopManager at the root of the functional graph\n const SPT_t fObjPtr; \/\/\/< Shared pointer encapsulating the wrapped result\n \/\/\/ Shared_ptr to a _pointer_ to the TDF action that produces this result. It is set at construction time for\n \/\/\/ non-jitted actions, and at jitting time for jitted actions (at the time of writing, this means right\n \/\/\/ before the event-loop).\n \/\/ N.B. what's on the heap is the _pointer_ to TActionBase, we are _not_ taking shared ownership of a TAction.\n \/\/ This cannot be a unique_ptr because that would disallow copy-construction of TResultProxies.\n \/\/ It cannot be just a pointer to TActionBase because we need something to store in the callback callable that will\n \/\/ be passed to TLoopManager _before_ the pointer to TActionBase is set in the case of jitted actions.\n const std::shared_ptr<TDFInternal::TActionBase *> fActionPtrPtr;\n\n \/\/\/ Triggers the event loop in the TLoopManager instance to which it's associated via the fImplWeakPtr\n void TriggerRun();\n\n \/\/\/ Get the pointer to the encapsulated result.\n \/\/\/ Ownership is not transferred to the caller.\n \/\/\/ Triggers event loop and execution of all actions booked in the associated TLoopManager.\n T *Get()\n {\n if (!*fReadiness)\n TriggerRun();\n return fObjPtr.get();\n }\n\n TResultProxy(const SPT_t &objPtr, const ShrdPtrBool_t &readiness, const SPTLM_t &loopManager,\n TDFInternal::TActionBase *actionPtr = nullptr)\n : fReadiness(readiness), fImplWeakPtr(loopManager), fObjPtr(objPtr),\n fActionPtrPtr(new (TDFInternal::TActionBase *)(actionPtr))\n {\n }\n\n std::shared_ptr<TDFInternal::TActionBase *> GetActionPtrPtr() const { return fActionPtrPtr; }\n\n void RegisterCallback(ULong64_t everyNEvents, std::function<void(unsigned int)> &&c) {\n auto lm = fImplWeakPtr.lock();\n if (!lm)\n throw std::runtime_error(\"The main TDataFrame is not reachable: did it go out of scope?\");\n lm->RegisterCallback(everyNEvents, std::move(c));\n }\n\npublic:\n using Value_t = T; \/\/\/< Convenience alias to simplify access to proxied type\n static constexpr ULong64_t kOnce = 0ull; \/\/\/< Convenience definition to express a callback must be executed once\n\n TResultProxy() = delete;\n TResultProxy(const TResultProxy &) = default;\n TResultProxy(TResultProxy &&) = default;\n\n \/\/\/ Get a const reference to the encapsulated object.\n \/\/\/ Triggers event loop and execution of all actions booked in the associated TLoopManager.\n const T &GetValue() { return *Get(); }\n\n \/\/\/ Get a pointer to the encapsulated object.\n \/\/\/ Triggers event loop and execution of all actions booked in the associated TLoopManager.\n T &operator*() { return *Get(); }\n\n \/\/\/ Get a pointer to the encapsulated object.\n \/\/\/ Ownership is not transferred to the caller.\n \/\/\/ Triggers event loop and execution of all actions booked in the associated TLoopManager.\n T *operator->() { return Get(); }\n\n \/\/\/ Return an iterator to the beginning of the contained object if this makes\n \/\/\/ sense, throw a compilation error otherwise\n typename TIterationHelper<T>::Iterator_t begin()\n {\n if (!*fReadiness)\n TriggerRun();\n return TIterationHelper<T>::GetBegin(*fObjPtr);\n }\n\n \/\/\/ Return an iterator to the end of the contained object if this makes\n \/\/\/ sense, throw a compilation error otherwise\n typename TIterationHelper<T>::Iterator_t end()\n {\n if (!*fReadiness)\n TriggerRun();\n return TIterationHelper<T>::GetEnd(*fObjPtr);\n }\n\n \/\/\/ Register a callback that TDataFrame will execute \"everyNEvents\" on a partial result.\n \/\/\/\n \/\/\/ \\param[in] everyNEvents Frequency at which the callback will be called, as a number of events processed\n \/\/\/ \\param[in] callback a callable with signature `void(Value_t&)` where Value_t is the type of the value contained in this TResultProxy\n \/\/\/\n \/\/\/ The callback must be a callable (lambda, function, functor class...) that takes a reference to the result type as\n \/\/\/ argument and returns nothing. TDataFrame will invoke registered callbacks passing partial action results as\n \/\/\/ arguments to them (e.g. a histogram filled with a part of the selected events, a counter incremented only up to a\n \/\/\/ certain point, a mean over a subset of the events and so forth).\n \/\/\/\n \/\/\/ Callbacks can be used e.g. to inspect partial results of the analysis while the event loop is running. For\n \/\/\/ example one can draw an up-to-date version of a result histogram every 100 entries like this:\n \/\/\/ \\code{.cpp}\n \/\/\/ auto h = tdf.Histo1D(\"x\");\n \/\/\/ TCanvas c(\"c\",\"x hist\");\n \/\/\/ h.OnPartialResult(100, [&c](TH1D &h_) { c.cd(); h_.Draw(); c.Update(); });\n \/\/\/ h->Draw(); \/\/ event loop runs here, this `Draw` is executed after the event loop is finished\n \/\/\/ \\endcode\n \/\/\/\n \/\/\/ A value of 0 for everyNEvents indicates the callback must be executed only once, before running the event loop.\n \/\/\/ A conveniece definition `kOnce` is provided to make this fact more expressive in user code (see snippet below).\n \/\/\/ Multiple callbacks can be registered with the same TResultProxy (i.e. results of TDataFrame actions) and will\n \/\/\/ be executed sequentially. Callbacks are executed in the order they were registered.\n \/\/\/ The type of the value contained in a TResultProxy is also available as TResultProxy<T>::Value_t, e.g.\n \/\/\/ \\code{.cpp}\n \/\/\/ auto h = tdf.Histo1D(\"x\");\n \/\/\/ \/\/ h.kOnce is 0\n \/\/\/ \/\/ decltype(h)::Value_t is TH1D\n \/\/\/ \\endcode\n \/\/\/\n \/\/\/ When implicit multi-threading is enabled, the callback:\n \/\/\/ - will never be executed by multiple threads concurrently: it needs not be thread-safe. For example the snippet\n \/\/\/ above that draws the partial histogram on a canvas works seamlessly in multi-thread event loops.\n \/\/\/ - will always be executed \"everyNEvents\": partial results will \"contain\" that number of events more from\n \/\/\/ one call to the next\n \/\/\/ - might be executed by a different worker thread at different times: the value of `std::this_thread::get_id()`\n \/\/\/ might change between calls\n \/\/\/ To register a callback that is called by _each_ worker thread (concurrently) every N events one can use\n \/\/\/ OnPartialResultSlot.\n void OnPartialResult(ULong64_t everyNEvents, std::function<void(T&)> callback)\n {\n auto actionPtrPtr = fActionPtrPtr.get();\n auto c = [actionPtrPtr, callback](unsigned int slot) {\n if (slot != 0)\n return;\n auto partialResult = static_cast<Value_t*>((*actionPtrPtr)->PartialUpdate(slot));\n callback(*partialResult);\n };\n RegisterCallback(everyNEvents, std::move(c));\n }\n\n \/\/\/ Register a callback that TDataFrame will execute in each worker thread concurrently on that thread's partial result.\n \/\/\/\n \/\/\/ \\param[in] everyNEvents Frequency at which the callback will be called by each thread, as a number of events processed\n \/\/\/ \\param[in] a callable with signature `void(unsigned int, Value_t&)` where Value_t is the type of the value contained in this TResultProxy\n \/\/\/\n \/\/\/ See `RegisterCallback` for a generic explanation of the callback mechanism.\n \/\/\/ Compared to `RegisterCallback`, this method has two major differences:\n \/\/\/ - all worker threads invoke the callback once every specified number of events. The event count is per-thread,\n \/\/\/ and callback invocation might happen concurrently (i.e. the callback must be thread-safe)\n \/\/\/ - the callable must take an extra `unsigned int` parameter corresponding to a multi-thread \"processing slot\":\n \/\/\/ this is a \"helper value\" to simplify writing thread-safe callbacks: different worker threads might invoke the\n \/\/\/ callback concurrently but always with different `slot` numbers.\n \/\/\/ - a value of 0 for everyNEvents indicates the callback must be executed once _per slot_.\n \/\/\/\n \/\/\/ For example, the following snippet prints out a thread-safe progress bar of the events processed by TDataFrame\n \/\/\/ \\code\n \/\/\/ auto c = tdf.Count(); \/\/ any action would do, but `Count` is the most lightweight\n \/\/\/ std::string progress;\n \/\/\/ std::mutex bar_mutex;\n \/\/\/ c.OnPartialResultSlot(nEvents \/ 100, [&progress, &bar_mutex](unsigned int, ULong64_t &) {\n \/\/\/ std::lock_guard<std::mutex> lg(bar_mutex);\n \/\/\/ progress.push_back('#');\n \/\/\/ std::cout << \"\\r[\" << std::left << std::setw(100) << progress << ']' << std::flush;\n \/\/\/ });\n \/\/\/ std::cout << \"Analysis running...\" << std::endl;\n \/\/\/ *c; \/\/ trigger the event loop by accessing an action's result\n \/\/\/ std::cout << \"\\nDone!\" << std::endl;\n \/\/\/ \\endcode\n void OnPartialResultSlot(ULong64_t everyNEvents, std::function<void(unsigned int, T&)> callback)\n {\n auto actionPtrPtr = fActionPtrPtr.get();\n auto c = [actionPtrPtr, callback](unsigned int slot) {\n auto partialResult = static_cast<Value_t*>((*actionPtrPtr)->PartialUpdate(slot));\n callback(slot, *partialResult);\n };\n RegisterCallback(everyNEvents, std::move(c));\n }\n};\n\ntemplate <typename T>\nvoid TResultProxy<T>::TriggerRun()\n{\n auto df = fImplWeakPtr.lock();\n if (!df) {\n throw std::runtime_error(\"The main TDataFrame is not reachable: did it go out of scope?\");\n }\n df->Run();\n}\n} \/\/ end NS TDF\n} \/\/ end NS Experimental\n\nnamespace Detail {\nnamespace TDF {\n\/\/\/ Create a TResultProxy and set its pointer to the corresponding TAction\n\/\/\/ This overload is invoked by non-jitted actions, as they have access to TAction before constructing TResultProxy.\ntemplate <typename T>\nTResultProxy<T> MakeResultProxy(const std::shared_ptr<T> &r, const std::shared_ptr<TLoopManager> &df,\n TDFInternal::TActionBase *actionPtr)\n{\n auto readiness = std::make_shared<bool>(false);\n auto resPtr = TResultProxy<T>(r, readiness, df, actionPtr);\n df->Book(readiness);\n return resPtr;\n}\n\n\/\/\/ Create a TResultProxy and return it together with its pointer to TAction\n\/\/\/ This overload is invoked by jitted actions; the pointer to TAction will be set right before the loop by jitted code\ntemplate <typename T>\nstd::pair<TResultProxy<T>, std::shared_ptr<TDFInternal::TActionBase *>>\nMakeResultProxy(const std::shared_ptr<T> &r, const std::shared_ptr<TLoopManager> &df)\n{\n auto readiness = std::make_shared<bool>(false);\n auto resPtr = TResultProxy<T>(r, readiness, df);\n df->Book(readiness);\n return std::make_pair(resPtr, resPtr.GetActionPtrPtr());\n}\n} \/\/ end NS TDF\n} \/\/ end NS Detail\n} \/\/ end NS ROOT\n\n#endif \/\/ ROOT_TRESULTPROXY\n<|endoftext|>"} {"text":"<commit_before>\/\/ @(#)root\/ldap:$Id$\n\/\/ Author: Evgenia Smirnova 21\/09\/2001\n\n\/*************************************************************************\n * For the licensing terms see $ROOTSYS\/LICENSE. *\n * For the list of contributors see $ROOTSYS\/README\/CREDITS. *\n *************************************************************************\/\n\n#include \"TLDAPAttribute.h\"\n#include \"TObjString.h\"\n#include \"Riostream.h\"\n\n\nClassImp(TLDAPAttribute)\n\n\/\/______________________________________________________________________________\nTLDAPAttribute::TLDAPAttribute(const char *name) : fNCount(0)\n{\n \/\/constructor\n SetName(name);\n fValues = new TList;\n fValues->SetOwner();\n}\n\n\/\/______________________________________________________________________________\nTLDAPAttribute::TLDAPAttribute(const char *name, const char *value)\n : fNCount(0)\n{\n \/\/ Creates an Attribute with name and value.\n\n SetName(name);\n fValues = new TList;\n fValues->SetOwner();\n AddValue(value);\n}\n\n\/\/______________________________________________________________________________\nTLDAPAttribute::TLDAPAttribute(const TLDAPAttribute &attr)\n : TNamed(attr), fNCount(attr.fNCount)\n{\n \/\/ LDAP attribute copy ctor.\n\n fValues = new TList;\n fValues->SetOwner();\n\n TIter next(attr.fValues);\n while (TObjString *str = (TObjString*) next()) {\n fValues->AddLast(new TObjString(str->GetName()));\n }\n}\n\n\/\/______________________________________________________________________________\nTLDAPAttribute& TLDAPAttribute::operator=(const TLDAPAttribute &attr)\n{\n \/\/ Equal operator\n if(this!=&attr) {\n TNamed::operator=(attr);\n fValues=attr.fValues;\n fNCount=attr.fNCount;\n } return *this;\n}\n\n\/\/______________________________________________________________________________\nTLDAPAttribute::~TLDAPAttribute()\n{\n \/\/destructor\n delete fValues;\n}\n\n\/\/______________________________________________________________________________\nvoid TLDAPAttribute::AddValue(const char *value)\n{\n \/\/ Add a value to the attribute.\n\n fValues->AddLast(new TObjString(value));\n}\n\n\/\/______________________________________________________________________________\nvoid TLDAPAttribute::DeleteValue(const char *value)\n{\n \/\/ Delete value by name.\n\n Int_t n = GetCount();\n for (Int_t i = 0; i < n; i++) {\n TObjString *v = (TObjString*) fValues->At(i);\n if (v->String().CompareTo(value) == 0) {\n delete fValues->Remove(v);\n if (fNCount > i) fNCount--;\n return;\n }\n }\n}\n\n\/\/______________________________________________________________________________\nconst char *TLDAPAttribute::GetValue() const\n{\n \/\/ Get next value of the attribute. Returns zero after the last value,\n \/\/ then returns the first value again.\n\n Int_t n = GetCount();\n if (n > fNCount) {\n return ((TObjString*)fValues->At(fNCount++))->GetName();\n } else {\n fNCount = 0;\n return 0;\n }\n}\n\n\/\/_______________________________________________________________________________\nvoid TLDAPAttribute::Print(Option_t *) const\n{\n \/\/ Print an attribute.\n\n Int_t counter = GetCount();\n if (counter == 0) {\n cout << GetName() << \": \" << endl;\n } else if (counter != 0) {\n for (Int_t i = 0; i < counter; i++) {\n cout << GetName() << \": \" << GetValue() << endl;\n }\n }\n}\n\n\/\/_______________________________________________________________________________\nLDAPMod *TLDAPAttribute::GetMod(Int_t op)\n{\n \/\/ Get \"LDAPMod\" structure for attribute. Returned LDAPMod must be\n \/\/ deleted by the user.\n\n LDAPMod *tmpMod = new LDAPMod;\n Int_t iCount = GetCount();\n char **values = new char* [iCount + 1];\n char *type = new char [strlen(GetName())+1];\n for (int i = 0; i < iCount; i++) {\n values[i] = new char [strlen(((TObjString*)fValues->At(i))->GetName()) + 1];\n strcpy(values[i], ((TObjString*)fValues->At(i))->GetName());\n }\n\n values[iCount] = 0;\n strcpy(type, GetName());\n tmpMod->mod_values = values;\n tmpMod->mod_type = type;\n tmpMod->mod_op = op;\n\n return tmpMod;\n}\n<commit_msg>Fix secure coding. coverity CID 14007<commit_after>\/\/ @(#)root\/ldap:$Id$\n\/\/ Author: Evgenia Smirnova 21\/09\/2001\n\n\/*************************************************************************\n * For the licensing terms see $ROOTSYS\/LICENSE. *\n * For the list of contributors see $ROOTSYS\/README\/CREDITS. *\n *************************************************************************\/\n\n#include \"TLDAPAttribute.h\"\n#include \"TObjString.h\"\n#include \"Riostream.h\"\n\n\nClassImp(TLDAPAttribute)\n\n\/\/______________________________________________________________________________\nTLDAPAttribute::TLDAPAttribute(const char *name) : fNCount(0)\n{\n \/\/constructor\n SetName(name);\n fValues = new TList;\n fValues->SetOwner();\n}\n\n\/\/______________________________________________________________________________\nTLDAPAttribute::TLDAPAttribute(const char *name, const char *value)\n : fNCount(0)\n{\n \/\/ Creates an Attribute with name and value.\n\n SetName(name);\n fValues = new TList;\n fValues->SetOwner();\n AddValue(value);\n}\n\n\/\/______________________________________________________________________________\nTLDAPAttribute::TLDAPAttribute(const TLDAPAttribute &attr)\n : TNamed(attr), fNCount(attr.fNCount)\n{\n \/\/ LDAP attribute copy ctor.\n\n fValues = new TList;\n fValues->SetOwner();\n\n TIter next(attr.fValues);\n while (TObjString *str = (TObjString*) next()) {\n fValues->AddLast(new TObjString(str->GetName()));\n }\n}\n\n\/\/______________________________________________________________________________\nTLDAPAttribute& TLDAPAttribute::operator=(const TLDAPAttribute &attr)\n{\n \/\/ Equal operator\n if(this!=&attr) {\n TNamed::operator=(attr);\n fValues=attr.fValues;\n fNCount=attr.fNCount;\n } return *this;\n}\n\n\/\/______________________________________________________________________________\nTLDAPAttribute::~TLDAPAttribute()\n{\n \/\/destructor\n delete fValues;\n}\n\n\/\/______________________________________________________________________________\nvoid TLDAPAttribute::AddValue(const char *value)\n{\n \/\/ Add a value to the attribute.\n\n fValues->AddLast(new TObjString(value));\n}\n\n\/\/______________________________________________________________________________\nvoid TLDAPAttribute::DeleteValue(const char *value)\n{\n \/\/ Delete value by name.\n\n Int_t n = GetCount();\n for (Int_t i = 0; i < n; i++) {\n TObjString *v = (TObjString*) fValues->At(i);\n if (v->String().CompareTo(value) == 0) {\n delete fValues->Remove(v);\n if (fNCount > i) fNCount--;\n return;\n }\n }\n}\n\n\/\/______________________________________________________________________________\nconst char *TLDAPAttribute::GetValue() const\n{\n \/\/ Get next value of the attribute. Returns zero after the last value,\n \/\/ then returns the first value again.\n\n Int_t n = GetCount();\n if (n > fNCount) {\n return ((TObjString*)fValues->At(fNCount++))->GetName();\n } else {\n fNCount = 0;\n return 0;\n }\n}\n\n\/\/_______________________________________________________________________________\nvoid TLDAPAttribute::Print(Option_t *) const\n{\n \/\/ Print an attribute.\n\n Int_t counter = GetCount();\n if (counter == 0) {\n cout << GetName() << \": \" << endl;\n } else if (counter != 0) {\n for (Int_t i = 0; i < counter; i++) {\n cout << GetName() << \": \" << GetValue() << endl;\n }\n }\n}\n\n\/\/_______________________________________________________________________________\nLDAPMod *TLDAPAttribute::GetMod(Int_t op)\n{\n \/\/ Get \"LDAPMod\" structure for attribute. Returned LDAPMod must be\n \/\/ deleted by the user.\n\n LDAPMod *tmpMod = new LDAPMod;\n Int_t iCount = GetCount();\n char **values = new char* [iCount + 1];\n char *type = new char [strlen(GetName())+1];\n for (int i = 0; i < iCount; i++) {\n int nch = strlen(((TObjString*)fValues->At(i))->GetName()) + 1;\n values[i] = new char [nch];\n strlcpy(values[i], ((TObjString*)fValues->At(i))->GetName(),nch);\n }\n\n values[iCount] = 0;\n strcpy(type, GetName());\n tmpMod->mod_values = values;\n tmpMod->mod_type = type;\n tmpMod->mod_op = op;\n\n return tmpMod;\n}\n<|endoftext|>"} {"text":"<commit_before><commit_msg>vcl: remove dead code from brdwin.cxx<commit_after><|endoftext|>"} {"text":"<commit_before><commit_msg>vcl: Sidebar corner case.<commit_after><|endoftext|>"} {"text":"<commit_before><commit_msg>Once ~SystemWindow calls ~Window, this is no longer a SystemWindow<commit_after><|endoftext|>"} {"text":"<commit_before><commit_msg>coverity#441048 silence Dereference after null check<commit_after><|endoftext|>"} {"text":"<commit_before>\n\/* Interface for debugging- spawns a prompt that will controll the main thread if it hits a specifies break point*\/\n\n\n#include <pthread.h>\n#include <iostream>\n#include <string>\n#include <stdio.h>\n#include <string.h>\n#include <stdlib.h>\n#include <inttypes.h>\n#include \"debug_simHandler.hpp\"\n\nusing namespace std;\n\n\/*function prototypes*\/\nvoid *run_debugger(void * holder);\nvoid parseline(string line);\nint handle_command(string command);\nvoid help();\nvoid messageHandler(uint64_t* msg);\nvoid debugSend(int command, string build);\n\n\/*to store the last input in the debugger*\/\nint lastInstruction = 0;\nstring lastBuild = \"\";\n\n#define DEBUG 16\n#define SIZE (sizeof(uint64_t))\n\nstatic bool isPaused = false;\nstatic void (*sendMessage)(int,int,uint64_t*);\nstatic void (*pauseSimulation)(int);\nstatic void (*unPauseSimulation)(void);\n\n\/*spawn the debbugging prompt as a separate thread to\n controll the main one*\/\nvoid (*initDebugger(void (*sendMsg)(int,int,uint64_t*),\n\t\t void (*pauseSim)(int),\n\t\t void (*unPauseSim)(void)))(uint64_t*){\n \n\n pthread_t tid;\n \n sendMessage = sendMsg;\n pauseSimulation = pauseSim;\n unPauseSimulation = unPauseSim;\n\n isPaused = true;\n pthread_create(&tid,NULL,run_debugger, NULL);\n\n return &messageHandler;\n}\n\nvoid messageHandler(uint64_t* msg){\n\n int sizeMsg;\n int command = (int)msg[2];\n switch(command){\n\n case BREAKFOUND:\n sizeMsg = 3*SIZE;\n uint64_t msgSend[sizeMsg\/SIZE];\n msgSend[0] = sizeMsg;\n msgSend[1] = DEBUG;\n msgSend[2] = PAUSE;\n sendMessage(-1,sizeMsg,(uint64_t*)msgSend);\n pauseSimulation(0);\n cout << (char*)&msg[3];\n isPaused = true;\n break;\n case PRINTCONTENT:\n cout << (char*)&msg[3];\n isPaused = true;\n break;\n\n }\n}\n\n\n\/\/continuously attend command line prompt for debugger\n\/\/when the system is not paused\nvoid *run_debugger(void* holder){\n\n (void)holder;\n string inpt;\n \n while(true){\n if (isPaused){\n cout << \">\";\n isPaused = false;\n getline(cin,inpt);\n \/\/react to the input\n parseline(inpt);\n }\n }\n return NULL;\n}\n\n\n\n\/*parses the command line and run the debugger*\/\nvoid parseline(string line){\n\n string build = \"\";\n int wordCount = 1;\n \n int command = NOTHING;\n\n \/*empty input*\/\n if (line == \"\"){\n \/\/enterlast stored command\n debugSend(lastInstruction,lastBuild);\n return;\n }\n\n \/*loop through input line*\/\n for (unsigned int i = 0; i < line.length(); i++){\n \n\n \/*parse line for words*\/\n if (line[i]!=' '){\n build += line[i];\n\n } else {\n \/\/exract the command\n if (wordCount == 1)\n\tcommand = handle_command(build);\n wordCount++;\n build = \"\";\n }\n }\n \n\n \/*no whitespace at all-single word commands*\/\n if (wordCount == 1){\n command = handle_command(build);\n \n if (command != BREAKPOINT && command!=DUMP){\n debugSend(command,\"\");\n lastInstruction = command;\n lastBuild = build;\n return;\n }\n }\n \n \/*if not enough info - these types must have a specification*\/\n if ((command == BREAKPOINT||command == DUMP)&& wordCount == 1){\n cout << \"Please specify- type help for options\" << endl;\n return;\n }\n\n \/*handle breakpoints and dumps*\/\n if (wordCount == 2){\n\tif (command == BREAKPOINT||command == DUMP)\n\t debugSend(command,build);\n\telse \n\t debugSend(command,\"\");\n lastInstruction = command;\n lastBuild = build;\n }\n}\n\n\nint stringType2Int(string type){\n if (type == \"factDer\"){\n return FACTDER;\n } else if (type == \"factCon\"){\n return FACTCON;\n } else if (type == \"factRet\"){\n return FACTRET;\n } else if (type == \"sense\"){\n return SENSE;\n } else if (type == \"action\"){\n return ACTION;\n } else if (type == \"block\"){\n return BLOCK;\n } else { \n cout << \"unknown type-- enter help for options\" << endl;\n return -1;\n }\n}\n\n\nvoid debugSend(int command, string build){\n \n int node;\n string name;\n int size;\n int type;\n char* nameSpot;\n\n switch(command){\n\n case CONTINUE:\n size = 3*SIZE;\n uint64_t msgCont[size\/SIZE];\n msgCont[0] = size;\n msgCont[1] = DEBUG;\n msgCont[2] = UNPAUSE;\n sendMessage(-1,size,(uint64_t*)msgCont);\n unPauseSimulation();\n break;\n\n case BREAKPOINT:\n if (build[0] == ':'||build[0] == '@'){\n cout << \"Please Specify a Type\" << endl;\n break;\n }\n type = stringType2Int(getType(build));\n if (type == -1)\n break;\n node = atoi(getNode(build).c_str());\n name = getName(build);\n size = 4*SIZE + (name.length() + 1) \n + (SIZE - (name.length() + 1)%SIZE);\n uint64_t msgBreak[size\/SIZE];\n msgBreak[0] = size;\n msgBreak[1] = DEBUG;\n msgBreak[2] = BREAKPOINT;\n msgBreak[3] = type;\n nameSpot = (char*)&msgBreak[4];\n memcpy(nameSpot,name.c_str(),name.length()+1);\n sendMessage(node,size,(uint64_t*)msgBreak);\n break;\n\n case DUMP:\n node = atoi(build.c_str());\n size = 3*SIZE;\n uint64_t msgDump[size\/SIZE];\n msgDump[0] = size;\n msgDump[1] = DEBUG;\n msgDump[2] = DUMP;\n sendMessage(node,size,(uint64_t*)msgDump);\n break;\n\n case NOTHING:\n break;\n }\n}\n\t\t \n\t\t \n\n\t \n\n\n\/*recognizes and sets different modes for the debugger*\/\nint handle_command(string command){\n\n int retVal;\n\n if (command == \"break\"){\n retVal = BREAKPOINT;\n } else if (command == \"help\"||command == \"h\") {\n help();\n retVal = NOTHING;\n } else if (command == \"run\"|| command == \"r\") {\n retVal = CONTINUE;\n } else if (command == \"dump\"||command == \"d\") {\n retVal = DUMP;\n } else if (command == \"continue\"||command == \"c\"){\n retVal = CONTINUE;\n } else if (command == \"quit\"||command == \"q\"){\n exit(0);\n } else {\n cout << \"unknown command: type 'help' for options \" << endl;\n retVal = NOTHING;\n }\n return retVal;\n}\n\n\n\/*prints the help screen*\/\nvoid help(){\n cout << endl;\n cout << \"*******************************************************************\" << endl;\n cout << endl;\n cout << \"DEBUGGER HELP\" << endl;\n cout << \"\\t-break <Specification>- set break point at specified place\" << endl;\n cout << \"\\t\\t-Specification Format:\" << endl;\n cout << \"\\t\\t <type>:<name>@<block> OR\" << endl;\n cout << \"\\t\\t <type>:<name> OR\" << endl;\n cout << \"\\t\\t <type>@<block>\" << endl;\n cout << \"\\t\\t -type - [factRet|factDer|factCon|action|sense|block]\" << endl;\n cout << \"\\t\\t\\t-a type MUST be specified\" << endl;\n cout << \"\\t\\t -name - the name of certain type ex. the name of a fact\" << endl;\n cout << \"\\t\\t -node - the number of the node\" << endl;\n cout << \"\\t-dump or d <nodeID> <all> - dump the state of the system\" << endl;\n cout << \"\\t-continue or c - continue execution\" << endl;\n cout << \"\\t-run or r - start the program\" << endl;\n cout << \"\\t-quit - exit debugger\" << endl;\n cout << endl;\n cout << \"\\t-Press Enter to use last Input\" << endl;\n cout << endl;\n cout << \"*******************************************************************\" << endl;\n}\n \n\n\n\n \n \n\n \n<commit_msg>fixed segfault bug<commit_after>\n\/* Interface for debugging- spawns a prompt that will controll the main thread if it hits a specifies break point*\/\n\n\n#include <pthread.h>\n#include <iostream>\n#include <string>\n#include <stdio.h>\n#include <string.h>\n#include <stdlib.h>\n#include <inttypes.h>\n#include \"debug_simHandler.hpp\"\n\nusing namespace std;\n\n\/*function prototypes*\/\nvoid *run_debugger(void * holder);\nvoid parseline(string line);\nint handle_command(string command);\nvoid help();\nvoid messageHandler(uint64_t* msg);\nvoid debugSend(int command, string build);\n\n\/*to store the last input in the debugger*\/\nint lastInstruction = 0;\nstring lastBuild = \"\";\n\n#define DEBUG 16\n#define SIZE (sizeof(uint64_t))\n\nstatic bool isPaused = false;\nstatic void (*sendMessage)(int,int,uint64_t*);\nstatic void (*pauseSimulation)(int);\nstatic void (*unPauseSimulation)(void);\n\n\/*spawn the debbugging prompt as a separate thread to\n controll the main one*\/\nvoid (*initDebugger(void (*sendMsg)(int,int,uint64_t*),\n\t\t void (*pauseSim)(int),\n\t\t void (*unPauseSim)(void)))(uint64_t*){\n \n\n pthread_t tid;\n \n sendMessage = sendMsg;\n pauseSimulation = pauseSim;\n unPauseSimulation = unPauseSim;\n\n isPaused = true;\n pthread_create(&tid,NULL,run_debugger, NULL);\n\n return messageHandler;\n}\n\nvoid messageHandler(uint64_t* msg){\n\n int sizeMsg;\n int command = (int)msg[2];\n if (command == BREAKPOINT){\n sizeMsg = 3*SIZE;\n uint64_t msgSend[sizeMsg\/SIZE];\n msgSend[0] = sizeMsg;\n msgSend[1] = DEBUG;\n msgSend[2] = PAUSE;\n sendMessage(-1,sizeMsg,(uint64_t*)msgSend);\n pauseSimulation(0);\n cout << (char*)&msg[3];\n isPaused = true;\n } else if (command == PRINTCONTENT){\n cout << (char*)&msg[3];\n isPaused = true;\n }\n}\n\n\n\/\/continuously attend command line prompt for debugger\n\/\/when the system is not paused\nvoid *run_debugger(void* holder){\n\n (void)holder;\n string inpt;\n \n while(true){\n if (isPaused){\n cout << \">\";\n isPaused = false;\n getline(cin,inpt);\n \/\/react to the input\n parseline(inpt);\n }\n }\n return NULL;\n}\n\n\n\n\/*parses the command line and run the debugger*\/\nvoid parseline(string line){\n\n string build = \"\";\n int wordCount = 1;\n \n int command = NOTHING;\n\n \/*empty input*\/\n if (line == \"\"){\n \/\/enterlast stored command\n debugSend(lastInstruction,lastBuild);\n return;\n }\n\n \/*loop through input line*\/\n for (unsigned int i = 0; i < line.length(); i++){\n \n\n \/*parse line for words*\/\n if (line[i]!=' '){\n build += line[i];\n\n } else {\n \/\/exract the command\n if (wordCount == 1)\n\tcommand = handle_command(build);\n wordCount++;\n build = \"\";\n }\n }\n \n\n \/*no whitespace at all-single word commands*\/\n if (wordCount == 1){\n command = handle_command(build);\n \n if (command != BREAKPOINT && command!=DUMP){\n debugSend(command,\"\");\n lastInstruction = command;\n lastBuild = build;\n return;\n }\n }\n \n \/*if not enough info - these types must have a specification*\/\n if ((command == BREAKPOINT||command == DUMP)&& wordCount == 1){\n cout << \"Please specify- type help for options\" << endl;\n isPaused = true;\n return;\n }\n\n \/*handle breakpoints and dumps*\/\n if (wordCount == 2){\n\tif (command == BREAKPOINT||command == DUMP)\n\t debugSend(command,build);\n\telse \n\t debugSend(command,\"\");\n lastInstruction = command;\n lastBuild = build;\n }\n}\n\n\nint stringType2Int(string type){\n if (type == \"factDer\"){\n return FACTDER;\n } else if (type == \"factCon\"){\n return FACTCON;\n } else if (type == \"factRet\"){\n return FACTRET;\n } else if (type == \"sense\"){\n return SENSE;\n } else if (type == \"action\"){\n return ACTION;\n } else if (type == \"block\"){\n return BLOCK;\n } else { \n cout << \"unknown type-- enter help for options\" << endl;\n return -1;\n }\n}\n\n\nvoid debugSend(int command, string build){\n \n int node;\n string name;\n int size;\n int type;\n char* nameSpot;\n\n if(command == CONTINUE){\n size = 3*SIZE;\n uint64_t msgCont[size\/SIZE];\n msgCont[0] = size;\n msgCont[1] = DEBUG;\n msgCont[2] = UNPAUSE;\n sendMessage(-1,size,(uint64_t*)msgCont);\n unPauseSimulation();\n\n } else if (command == BREAKPOINT) {\n if (build[0] == ':'||build[0] == '@'){\n cout << \"Please Specify a Type\" << endl;\n isPaused = true;\n return;\n }\n type = stringType2Int(getType(build));\n if (type == -1){\n isPaused = true;\n return;\n }\n node = atoi(getNode(build).c_str());\n name = getName(build);\n size = 4*SIZE + (name.length() + 1) \n + (SIZE - (name.length() + 1)%SIZE);\n uint64_t msgBreak[size\/SIZE];\n msgBreak[0] = size;\n msgBreak[1] = DEBUG;\n msgBreak[2] = BREAKPOINT;\n msgBreak[3] = type;\n nameSpot = (char*)&msgBreak[4];\n memcpy(nameSpot,name.c_str(),name.length()+1);\n sendMessage(node,size,(uint64_t*)msgBreak);\n\n } else if (command == DUMP){\n node = atoi(build.c_str());\n size = 3*SIZE;\n uint64_t msgDump[size\/SIZE];\n msgDump[0] = size;\n msgDump[1] = DEBUG;\n msgDump[2] = DUMP;\n sendMessage(node,size,(uint64_t*)msgDump);\n\n } else if (command == NOTHING){\n isPaused = true;\n }\n return;\n}\n\t\t \n\t\t \n\n\t \n\n\n\/*recognizes and sets different modes for the debugger*\/\nint handle_command(string command){\n\n int retVal;\n\n if (command == \"break\"){\n retVal = BREAKPOINT;\n } else if (command == \"help\"||command == \"h\") {\n help();\n retVal = NOTHING;\n } else if (command == \"run\"|| command == \"r\") {\n retVal = CONTINUE;\n } else if (command == \"dump\"||command == \"d\") {\n retVal = DUMP;\n } else if (command == \"continue\"||command == \"c\"){\n retVal = CONTINUE;\n } else if (command == \"quit\"||command == \"q\"){\n exit(0);\n } else {\n cout << \"unknown command: type 'help' for options \" << endl;\n retVal = NOTHING;\n }\n return retVal;\n}\n\n\n\/*prints the help screen*\/\nvoid help(){\n cout << endl;\n cout << \"*******************************************************************\" << endl;\n cout << endl;\n cout << \"DEBUGGER HELP\" << endl;\n cout << \"\\t-break <Specification>- set break point at specified place\" << endl;\n cout << \"\\t\\t-Specification Format:\" << endl;\n cout << \"\\t\\t <type>:<name>@<block> OR\" << endl;\n cout << \"\\t\\t <type>:<name> OR\" << endl;\n cout << \"\\t\\t <type>@<block>\" << endl;\n cout << \"\\t\\t -type - [factRet|factDer|factCon|action|sense|block]\" << endl;\n cout << \"\\t\\t\\t-a type MUST be specified\" << endl;\n cout << \"\\t\\t -name - the name of certain type ex. the name of a fact\" << endl;\n cout << \"\\t\\t -node - the number of the node\" << endl;\n cout << \"\\t-dump or d <nodeID> <all> - dump the state of the system\" << endl;\n cout << \"\\t-continue or c - continue execution\" << endl;\n cout << \"\\t-run or r - start the program\" << endl;\n cout << \"\\t-quit - exit debugger\" << endl;\n cout << endl;\n cout << \"\\t-Press Enter to use last Input\" << endl;\n cout << endl;\n cout << \"*******************************************************************\" << endl;\n}\n \n\n\n\n \n \n\n \n<|endoftext|>"} {"text":"<commit_before>\/*\n * The Apache Software License, Version 1.1\n * \n * Copyright (c) 1999-2000 The Apache Software Foundation. All rights\n * reserved.\n * \n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n * \n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer. \n * \n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in\n * the documentation and\/or other materials provided with the\n * distribution.\n * \n * 3. The end-user documentation included with the redistribution,\n * if any, must include the following acknowledgment: \n * \"This product includes software developed by the\n * Apache Software Foundation (http:\/\/www.apache.org\/).\"\n * Alternately, this acknowledgment may appear in the software itself,\n * if and wherever such third-party acknowledgments normally appear.\n * \n * 4. The names \"Xerces\" and \"Apache Software Foundation\" must\n * not be used to endorse or promote products derived from this\n * software without prior written permission. For written \n * permission, please contact apache\\@apache.org.\n * \n * 5. Products derived from this software may not be called \"Apache\",\n * nor may \"Apache\" appear in their name, without prior written\n * permission of the Apache Software Foundation.\n * \n * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED\n * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR\n * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF\n * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT\n * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n * ====================================================================\n * \n * This software consists of voluntary contributions made by many\n * individuals on behalf of the Apache Software Foundation, and was\n * originally based on software copyright (c) 1999, International\n * Business Machines, Inc., http:\/\/www.ibm.com . For more information\n * on the Apache Software Foundation, please see\n * <http:\/\/www.apache.org\/>.\n *\/\n\n\/*\n * $Id$\n *\/\n\n\n\nTHIS_CLASS::THIS_CLASS(DocumentImpl *ownerDoc)\n : PARENT_CLASS(ownerDoc)\n{\n this->ownerDocument = ownerDoc;\n this->firstChild = null;\n}; \n\n\/\/ This only makes a shallow copy, cloneChildren must also be called for a\n\/\/ deep clone\nTHIS_CLASS::THIS_CLASS(const THIS_CLASS &other)\n : PARENT_CLASS(other)\n{\n this->ownerDocument = other.ownerDocument;\n\n \/\/ Need to break the association w\/ original kids\n this->firstChild = null;\n};\n\n\nvoid THIS_CLASS::cloneChildren(const NodeImpl &other) { \n \/\/ for (NodeImpl *mykid = other.getFirstChild(); \n for (NodeImpl *mykid = ((NodeImpl&)other).getFirstChild(); \n mykid != null; \n mykid = mykid->getNextSibling()) {\n this->appendChild(mykid->cloneNode(true));\n }\n}\n\nDocumentImpl * THIS_CLASS::getOwnerDocument() {\n return ownerDocument;\n}\n\n\/\/ unlike getOwnerDocument this is not overriden by DocumentImpl to return null\nDocumentImpl * THIS_CLASS::getDocument() {\n return ownerDocument;\n}\n\nvoid THIS_CLASS::setOwnerDocument(DocumentImpl *doc) {\n ownerDocument = doc;\n for (NodeImpl *child = firstChild;\n child != null; child = child->getNextSibling()) {\n child->setOwnerDocument(doc);\n }\n}\n\n\nNodeListImpl *THIS_CLASS::getChildNodes() {\n return this;\n};\n\n\nNodeImpl * THIS_CLASS::getFirstChild() {\n return firstChild;\n}; \n\n\nNodeImpl * THIS_CLASS::getLastChild()\n{\n return lastChild();\n}; \n\nChildNode * THIS_CLASS::lastChild()\n{\n \/\/ last child is stored as the previous sibling of first child\n return firstChild != null ? firstChild->previousSibling : null;\n}; \n\nvoid THIS_CLASS::lastChild(ChildNode *node) {\n \/\/ store lastChild as previous sibling of first child\n if (firstChild != null) {\n firstChild->previousSibling = node;\n }\n }\n\n\nunsigned int THIS_CLASS::getLength() {\n unsigned int count = 0;\n ChildNode *node = firstChild;\n while(node != null)\n {\n ++count;\n node = node->nextSibling;\n }\n return count;\n};\n\n\nbool THIS_CLASS::hasChildNodes()\n{ \n return firstChild!=null;\n}; \n\n\n\nNodeImpl *THIS_CLASS::insertBefore(NodeImpl *newChild, NodeImpl *refChild) {\n if (isReadOnly())\n throw DOM_DOMException(\n DOM_DOMException::NO_MODIFICATION_ALLOWED_ERR, null);\n \n if (newChild->getOwnerDocument() != ownerDocument)\n throw DOM_DOMException(DOM_DOMException::WRONG_DOCUMENT_ERR, null);\n \n \/\/ Convert to internal type, to avoid repeated casting \n ChildNode * newInternal= (ChildNode *)newChild;\n \n \/\/ Prevent cycles in the tree\n bool treeSafe=true;\n for(NodeImpl *a=this->getParentNode();\n treeSafe && a!=null;\n a=a->getParentNode())\n treeSafe=(newInternal!=a);\n if(!treeSafe)\n throw DOM_DOMException(DOM_DOMException::HIERARCHY_REQUEST_ERR,null);\n \n \/\/ refChild must in fact be a child of this node (or null)\n if (refChild!=null && refChild->getParentNode() != this)\n throw DOM_DOMException(DOM_DOMException::NOT_FOUND_ERR,null);\n \n if (newInternal->isDocumentFragmentImpl())\n {\n \/\/ SLOW BUT SAFE: We could insert the whole subtree without\n \/\/ juggling so many next\/previous pointers. (Wipe out the\n \/\/ parent's child-list, patch the parent pointers, set the\n \/\/ ends of the list.) But we know some subclasses have special-\n \/\/ case behavior they add to insertBefore(), so we don't risk it.\n \/\/ This approch also takes fewer bytecodes.\n \n \/\/ NOTE: If one of the children is not a legal child of this\n \/\/ node, throw HIERARCHY_REQUEST_ERR before _any_ of the children\n \/\/ have been transferred. (Alternative behaviors would be to\n \/\/ reparent up to the first failure point or reparent all those\n \/\/ which are acceptable to the target node, neither of which is\n \/\/ as robust. PR-DOM-0818 isn't entirely clear on which it\n \/\/ recommends?????\n \n \/\/ No need to check kids for right-document; if they weren't,\n \/\/ they wouldn't be kids of that DocFrag.\n for(NodeImpl *kid=newInternal->getFirstChild(); \/\/ Prescan\n kid!=null;\n kid=kid->getNextSibling())\n {\n if (!DocumentImpl::isKidOK(this, kid))\n throw DOM_DOMException(DOM_DOMException::HIERARCHY_REQUEST_ERR,null);\n } \n while(newInternal->hasChildNodes()) \/\/ Move\n insertBefore(newInternal->getFirstChild(),refChild);\n }\n \n else if (!DocumentImpl::isKidOK(this, newInternal))\n throw DOM_DOMException(DOM_DOMException::HIERARCHY_REQUEST_ERR,null);\n \n else\n {\n NodeImpl *oldparent=newInternal->getParentNode();\n if(oldparent!=null) {\n oldparent->removeChild(newInternal);\n }\n\n \/\/ Convert to internal type, to avoid repeated casting\n ChildNode *refInternal = (ChildNode *)refChild;\n\n \/\/ Attach up\n newInternal->ownerNode = this;\n newInternal->isOwned(true);\n \n \/\/ Attach before and after\n \/\/ Note: firstChild.previousSibling == lastChild!!\n if (firstChild == null) {\n \/\/ this our first and only child\n firstChild = newInternal;\n newInternal->isFirstChild(true);\n newInternal->previousSibling = newInternal;\n } else {\n if (refInternal == null) {\n \/\/ this is an append\n ChildNode *lastChild = firstChild->previousSibling;\n lastChild->nextSibling = newInternal;\n newInternal->previousSibling = lastChild;\n firstChild->previousSibling = newInternal;\n } else {\n \/\/ this is an insert\n if (refChild == firstChild) {\n \/\/ at the head of the list\n firstChild->isFirstChild(false);\n newInternal->nextSibling = firstChild;\n newInternal->previousSibling = firstChild->previousSibling;\n firstChild->previousSibling = newInternal;\n firstChild = newInternal;\n newInternal->isFirstChild(true);\n } else {\n \/\/ somewhere in the middle\n ChildNode *prev = refInternal->previousSibling;\n newInternal->nextSibling = refInternal;\n prev->nextSibling = newInternal;\n refInternal->previousSibling = newInternal;\n newInternal->previousSibling = prev;\n }\n }\n }\n }\n\n changed();\n \n if (this->getOwnerDocument() != null) {\n typedef RefVectorOf<RangeImpl> RangeImpls;\n RangeImpls* ranges = this->getOwnerDocument()->getRanges();\n if ( ranges != null) {\n unsigned int sz = ranges->size();\n if (sz != 0) {\n for (unsigned int i =0; i<sz; i++) {\n ranges->elementAt(i)->updateRangeForInsertedNode(newInternal);\n }\n }\n }\n }\n\n return newInternal;\n};\n \n \nNodeImpl *THIS_CLASS::item(unsigned int index) {\n ChildNode *node = firstChild;\n for(unsigned int i=0; i<index && node!=null; ++i)\n node = node->nextSibling;\n return node;\n};\n \n \nNodeImpl *THIS_CLASS::removeChild(NodeImpl *oldChild) \n{\n if (isReadOnly())\n throw DOM_DOMException(\n DOM_DOMException::NO_MODIFICATION_ALLOWED_ERR, null);\n \n if (oldChild != null && oldChild->getParentNode() != this)\n throw DOM_DOMException(DOM_DOMException::NOT_FOUND_ERR, null);\n \n \/\/fix other ranges for change before deleting the node\n if (this->getOwnerDocument() != null ) {\n typedef RefVectorOf<RangeImpl> RangeImpls;\n RangeImpls* ranges = this->getOwnerDocument()->getRanges();\n if (ranges != null) {\n unsigned int sz = ranges->size();\n if (sz != 0) {\n for (unsigned int i =0; i<sz; i++) {\n if (ranges->elementAt(i) != null) \n ranges->elementAt(i)->updateRangeForDeletedNode(oldChild);\n }\n }\n }\n }\n \n ChildNode * oldInternal = (ChildNode *) oldChild;\n \n \/\/ Patch linked list around oldChild\n \/\/ Note: lastChild == firstChild->previousSibling\n if (oldInternal == firstChild) {\n \/\/ removing first child\n oldInternal->isFirstChild(false);\n firstChild = oldInternal->nextSibling;\n if (firstChild != null) {\n firstChild->isFirstChild(true);\n firstChild->previousSibling = oldInternal->previousSibling;\n }\n } else {\n ChildNode *prev = oldInternal->previousSibling;\n ChildNode *next = oldInternal->nextSibling;\n prev->nextSibling = next;\n if (next == null) {\n \/\/ removing last child\n firstChild->previousSibling = prev;\n } else {\n \/\/ removing some other child in the middle\n next->previousSibling = prev;\n }\n }\n\n \/\/ Remove oldInternal's references to tree\n oldInternal->ownerNode = ownerDocument;\n oldInternal->isOwned(false);\n oldInternal->nextSibling = null;\n oldInternal->previousSibling = null;\n\n changed();\n\n return oldInternal;\n};\n\n\nNodeImpl *THIS_CLASS::replaceChild(NodeImpl *newChild, NodeImpl *oldChild)\n{\n insertBefore(newChild, oldChild);\n \/\/ changed() already done.\n return removeChild(oldChild);\n};\n \n\nvoid THIS_CLASS::setReadOnly(bool readOnl, bool deep)\n{\n NodeImpl::setReadOnly(readOnl, deep);\n \n if (deep)\n \/\/ Recursively set kids\n for (ChildNode *mykid = firstChild; \n mykid != null; \n mykid = mykid->nextSibling)\n if(! (mykid->isEntityReference()))\n mykid->setReadOnly(readOnl,true);\n};\n \n \n\/\/Introduced in DOM Level 2\n \nvoid THIS_CLASS::normalize()\n{\n ChildNode *kid, *next;\n for (kid = firstChild; kid != null; kid = next)\n {\n next = kid->nextSibling;\n \n \/\/ If kid and next are both Text nodes (but _not_ CDATASection,\n \/\/ which is a subclass of Text), they can be merged.\n if (next != null && \n kid->isTextImpl() && !(kid->isCDATASectionImpl()) && \n next->isTextImpl() && !(next->isCDATASectionImpl()) )\n {\n ((TextImpl *) kid)->appendData(((TextImpl *) next)->getData());\n removeChild(next);\n if (next->nodeRefCount == 0)\n deleteIf(next);\n next = kid; \/\/ Don't advance; there might be another.\n }\n \n \/\/ Otherwise it might be an Element, which is handled recursively \n else\n if (kid->isElementImpl())\n kid->normalize();\n };\n \n \/\/ changed() will have occurred when the removeChild() was done,\n \/\/ so does not have to be reissued.\n};\n\n<commit_msg>Access violations and stack overflows in insertBefore<commit_after>\/*\n * The Apache Software License, Version 1.1\n * \n * Copyright (c) 1999-2000 The Apache Software Foundation. All rights\n * reserved.\n * \n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n * \n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer. \n * \n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in\n * the documentation and\/or other materials provided with the\n * distribution.\n * \n * 3. The end-user documentation included with the redistribution,\n * if any, must include the following acknowledgment: \n * \"This product includes software developed by the\n * Apache Software Foundation (http:\/\/www.apache.org\/).\"\n * Alternately, this acknowledgment may appear in the software itself,\n * if and wherever such third-party acknowledgments normally appear.\n * \n * 4. The names \"Xerces\" and \"Apache Software Foundation\" must\n * not be used to endorse or promote products derived from this\n * software without prior written permission. For written \n * permission, please contact apache\\@apache.org.\n * \n * 5. Products derived from this software may not be called \"Apache\",\n * nor may \"Apache\" appear in their name, without prior written\n * permission of the Apache Software Foundation.\n * \n * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED\n * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR\n * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF\n * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT\n * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n * ====================================================================\n * \n * This software consists of voluntary contributions made by many\n * individuals on behalf of the Apache Software Foundation, and was\n * originally based on software copyright (c) 1999, International\n * Business Machines, Inc., http:\/\/www.ibm.com . For more information\n * on the Apache Software Foundation, please see\n * <http:\/\/www.apache.org\/>.\n *\/\n\n\/*\n * $Id$\n *\/\n\n\n\nTHIS_CLASS::THIS_CLASS(DocumentImpl *ownerDoc)\n : PARENT_CLASS(ownerDoc)\n{\n this->ownerDocument = ownerDoc;\n this->firstChild = null;\n}; \n\n\/\/ This only makes a shallow copy, cloneChildren must also be called for a\n\/\/ deep clone\nTHIS_CLASS::THIS_CLASS(const THIS_CLASS &other)\n : PARENT_CLASS(other)\n{\n this->ownerDocument = other.ownerDocument;\n\n \/\/ Need to break the association w\/ original kids\n this->firstChild = null;\n};\n\n\nvoid THIS_CLASS::cloneChildren(const NodeImpl &other) { \n \/\/ for (NodeImpl *mykid = other.getFirstChild(); \n for (NodeImpl *mykid = ((NodeImpl&)other).getFirstChild(); \n mykid != null; \n mykid = mykid->getNextSibling()) {\n this->appendChild(mykid->cloneNode(true));\n }\n}\n\nDocumentImpl * THIS_CLASS::getOwnerDocument() {\n return ownerDocument;\n}\n\n\/\/ unlike getOwnerDocument this is not overriden by DocumentImpl to return null\nDocumentImpl * THIS_CLASS::getDocument() {\n return ownerDocument;\n}\n\nvoid THIS_CLASS::setOwnerDocument(DocumentImpl *doc) {\n ownerDocument = doc;\n for (NodeImpl *child = firstChild;\n child != null; child = child->getNextSibling()) {\n child->setOwnerDocument(doc);\n }\n}\n\n\nNodeListImpl *THIS_CLASS::getChildNodes() {\n return this;\n};\n\n\nNodeImpl * THIS_CLASS::getFirstChild() {\n return firstChild;\n}; \n\n\nNodeImpl * THIS_CLASS::getLastChild()\n{\n return lastChild();\n}; \n\nChildNode * THIS_CLASS::lastChild()\n{\n \/\/ last child is stored as the previous sibling of first child\n return firstChild != null ? firstChild->previousSibling : null;\n}; \n\nvoid THIS_CLASS::lastChild(ChildNode *node) {\n \/\/ store lastChild as previous sibling of first child\n if (firstChild != null) {\n firstChild->previousSibling = node;\n }\n }\n\n\nunsigned int THIS_CLASS::getLength() {\n unsigned int count = 0;\n ChildNode *node = firstChild;\n while(node != null)\n {\n ++count;\n node = node->nextSibling;\n }\n return count;\n};\n\n\nbool THIS_CLASS::hasChildNodes()\n{ \n return firstChild!=null;\n}; \n\n\n\nNodeImpl *THIS_CLASS::insertBefore(NodeImpl *newChild, NodeImpl *refChild) {\n if (isReadOnly())\n throw DOM_DOMException(\n DOM_DOMException::NO_MODIFICATION_ALLOWED_ERR, null);\n \n if (newChild->getOwnerDocument() != ownerDocument)\n throw DOM_DOMException(DOM_DOMException::WRONG_DOCUMENT_ERR, null);\n \n \/\/ Convert to internal type, to avoid repeated casting \n ChildNode * newInternal= (ChildNode *)newChild;\n \n \/\/ Prevent cycles in the tree\n \/\/ newChild cannot be ancestor of this Node, and actually cannot be this Node\n bool treeSafe=true;\n for(NodeImpl *a=this;\n treeSafe && a!=null;\n a=a->getParentNode())\n treeSafe=(newInternal!=a);\n if(!treeSafe)\n throw DOM_DOMException(DOM_DOMException::HIERARCHY_REQUEST_ERR,null);\n \n \/\/ refChild must in fact be a child of this node (or null)\n if (refChild!=null && refChild->getParentNode() != this)\n throw DOM_DOMException(DOM_DOMException::NOT_FOUND_ERR,null);\n \n \/\/ refChild cannot be same as newChild\n if(refChild==newInternal)\n throw DOM_DOMException(DOM_DOMException::HIERARCHY_REQUEST_ERR,null);\n\n if (newInternal->isDocumentFragmentImpl())\n {\n \/\/ SLOW BUT SAFE: We could insert the whole subtree without\n \/\/ juggling so many next\/previous pointers. (Wipe out the\n \/\/ parent's child-list, patch the parent pointers, set the\n \/\/ ends of the list.) But we know some subclasses have special-\n \/\/ case behavior they add to insertBefore(), so we don't risk it.\n \/\/ This approch also takes fewer bytecodes.\n \n \/\/ NOTE: If one of the children is not a legal child of this\n \/\/ node, throw HIERARCHY_REQUEST_ERR before _any_ of the children\n \/\/ have been transferred. (Alternative behaviors would be to\n \/\/ reparent up to the first failure point or reparent all those\n \/\/ which are acceptable to the target node, neither of which is\n \/\/ as robust. PR-DOM-0818 isn't entirely clear on which it\n \/\/ recommends?????\n \n \/\/ No need to check kids for right-document; if they weren't,\n \/\/ they wouldn't be kids of that DocFrag.\n for(NodeImpl *kid=newInternal->getFirstChild(); \/\/ Prescan\n kid!=null;\n kid=kid->getNextSibling())\n {\n if (!DocumentImpl::isKidOK(this, kid))\n throw DOM_DOMException(DOM_DOMException::HIERARCHY_REQUEST_ERR,null);\n } \n while(newInternal->hasChildNodes()) \/\/ Move\n insertBefore(newInternal->getFirstChild(),refChild);\n }\n \n else if (!DocumentImpl::isKidOK(this, newInternal))\n throw DOM_DOMException(DOM_DOMException::HIERARCHY_REQUEST_ERR,null);\n \n else\n {\n NodeImpl *oldparent=newInternal->getParentNode();\n if(oldparent!=null) {\n oldparent->removeChild(newInternal);\n }\n\n \/\/ Convert to internal type, to avoid repeated casting\n ChildNode *refInternal = (ChildNode *)refChild;\n\n \/\/ Attach up\n newInternal->ownerNode = this;\n newInternal->isOwned(true);\n \n \/\/ Attach before and after\n \/\/ Note: firstChild.previousSibling == lastChild!!\n if (firstChild == null) {\n \/\/ this our first and only child\n firstChild = newInternal;\n newInternal->isFirstChild(true);\n newInternal->previousSibling = newInternal;\n } else {\n if (refInternal == null) {\n \/\/ this is an append\n ChildNode *lastChild = firstChild->previousSibling;\n lastChild->nextSibling = newInternal;\n newInternal->previousSibling = lastChild;\n firstChild->previousSibling = newInternal;\n } else {\n \/\/ this is an insert\n if (refChild == firstChild) {\n \/\/ at the head of the list\n firstChild->isFirstChild(false);\n newInternal->nextSibling = firstChild;\n newInternal->previousSibling = firstChild->previousSibling;\n firstChild->previousSibling = newInternal;\n firstChild = newInternal;\n newInternal->isFirstChild(true);\n } else {\n \/\/ somewhere in the middle\n ChildNode *prev = refInternal->previousSibling;\n newInternal->nextSibling = refInternal;\n prev->nextSibling = newInternal;\n refInternal->previousSibling = newInternal;\n newInternal->previousSibling = prev;\n }\n }\n }\n }\n\n changed();\n \n if (this->getOwnerDocument() != null) {\n typedef RefVectorOf<RangeImpl> RangeImpls;\n RangeImpls* ranges = this->getOwnerDocument()->getRanges();\n if ( ranges != null) {\n unsigned int sz = ranges->size();\n if (sz != 0) {\n for (unsigned int i =0; i<sz; i++) {\n ranges->elementAt(i)->updateRangeForInsertedNode(newInternal);\n }\n }\n }\n }\n\n return newInternal;\n};\n \n \nNodeImpl *THIS_CLASS::item(unsigned int index) {\n ChildNode *node = firstChild;\n for(unsigned int i=0; i<index && node!=null; ++i)\n node = node->nextSibling;\n return node;\n};\n \n \nNodeImpl *THIS_CLASS::removeChild(NodeImpl *oldChild) \n{\n if (isReadOnly())\n throw DOM_DOMException(\n DOM_DOMException::NO_MODIFICATION_ALLOWED_ERR, null);\n \n if (oldChild != null && oldChild->getParentNode() != this)\n throw DOM_DOMException(DOM_DOMException::NOT_FOUND_ERR, null);\n \n \/\/fix other ranges for change before deleting the node\n if (this->getOwnerDocument() != null ) {\n typedef RefVectorOf<RangeImpl> RangeImpls;\n RangeImpls* ranges = this->getOwnerDocument()->getRanges();\n if (ranges != null) {\n unsigned int sz = ranges->size();\n if (sz != 0) {\n for (unsigned int i =0; i<sz; i++) {\n if (ranges->elementAt(i) != null) \n ranges->elementAt(i)->updateRangeForDeletedNode(oldChild);\n }\n }\n }\n }\n \n ChildNode * oldInternal = (ChildNode *) oldChild;\n \n \/\/ Patch linked list around oldChild\n \/\/ Note: lastChild == firstChild->previousSibling\n if (oldInternal == firstChild) {\n \/\/ removing first child\n oldInternal->isFirstChild(false);\n firstChild = oldInternal->nextSibling;\n if (firstChild != null) {\n firstChild->isFirstChild(true);\n firstChild->previousSibling = oldInternal->previousSibling;\n }\n } else {\n ChildNode *prev = oldInternal->previousSibling;\n ChildNode *next = oldInternal->nextSibling;\n prev->nextSibling = next;\n if (next == null) {\n \/\/ removing last child\n firstChild->previousSibling = prev;\n } else {\n \/\/ removing some other child in the middle\n next->previousSibling = prev;\n }\n }\n\n \/\/ Remove oldInternal's references to tree\n oldInternal->ownerNode = ownerDocument;\n oldInternal->isOwned(false);\n oldInternal->nextSibling = null;\n oldInternal->previousSibling = null;\n\n changed();\n\n return oldInternal;\n};\n\n\nNodeImpl *THIS_CLASS::replaceChild(NodeImpl *newChild, NodeImpl *oldChild)\n{\n insertBefore(newChild, oldChild);\n \/\/ changed() already done.\n return removeChild(oldChild);\n};\n \n\nvoid THIS_CLASS::setReadOnly(bool readOnl, bool deep)\n{\n NodeImpl::setReadOnly(readOnl, deep);\n \n if (deep)\n \/\/ Recursively set kids\n for (ChildNode *mykid = firstChild; \n mykid != null; \n mykid = mykid->nextSibling)\n if(! (mykid->isEntityReference()))\n mykid->setReadOnly(readOnl,true);\n};\n \n \n\/\/Introduced in DOM Level 2\n \nvoid THIS_CLASS::normalize()\n{\n ChildNode *kid, *next;\n for (kid = firstChild; kid != null; kid = next)\n {\n next = kid->nextSibling;\n \n \/\/ If kid and next are both Text nodes (but _not_ CDATASection,\n \/\/ which is a subclass of Text), they can be merged.\n if (next != null && \n kid->isTextImpl() && !(kid->isCDATASectionImpl()) && \n next->isTextImpl() && !(next->isCDATASectionImpl()) )\n {\n ((TextImpl *) kid)->appendData(((TextImpl *) next)->getData());\n removeChild(next);\n if (next->nodeRefCount == 0)\n deleteIf(next);\n next = kid; \/\/ Don't advance; there might be another.\n }\n \n \/\/ Otherwise it might be an Element, which is handled recursively \n else\n if (kid->isElementImpl())\n kid->normalize();\n };\n \n \/\/ changed() will have occurred when the removeChild() was done,\n \/\/ so does not have to be reissued.\n};\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"net\/proxy\/proxy_bypass_rules.h\"\n\n#include \"base\/logging.h\"\n#include \"base\/string_tokenizer.h\"\n#include \"base\/string_util.h\"\n#include \"net\/base\/net_util.h\"\n\nnamespace net {\n\nnamespace {\n\nclass HostnamePatternRule : public ProxyBypassRules::Rule {\n public:\n HostnamePatternRule(const std::string& optional_scheme,\n const std::string& hostname_pattern,\n int optional_port)\n : optional_scheme_(StringToLowerASCII(optional_scheme)),\n hostname_pattern_(StringToLowerASCII(hostname_pattern)),\n optional_port_(optional_port) {\n }\n\n virtual bool Matches(const GURL& url) const {\n if (optional_port_ != -1 && url.EffectiveIntPort() != optional_port_)\n return false; \/\/ Didn't match port expectation.\n\n if (!optional_scheme_.empty() && url.scheme() != optional_scheme_)\n return false; \/\/ Didn't match scheme expectation.\n\n \/\/ Note it is necessary to lower-case the host, since GURL uses capital\n \/\/ letters for percent-escaped characters.\n return MatchPatternASCII(StringToLowerASCII(url.host()),\n hostname_pattern_);\n }\n\n virtual std::string ToString() const {\n std::string str;\n if (!optional_scheme_.empty())\n StringAppendF(&str, \"%s:\/\/\", optional_scheme_.c_str());\n str += hostname_pattern_;\n if (optional_port_ != -1)\n StringAppendF(&str, \":%d\", optional_port_);\n return str;\n }\n\n private:\n const std::string optional_scheme_;\n const std::string hostname_pattern_;\n const int optional_port_;\n};\n\nclass BypassLocalRule : public ProxyBypassRules::Rule {\n public:\n virtual bool Matches(const GURL& url) const {\n const std::string& host = url.host();\n if (host == \"127.0.0.1\" || host == \"[::1]\")\n return true;\n return host.find('.') == std::string::npos;\n }\n\n virtual std::string ToString() const {\n return \"<local>\";\n }\n};\n\n\/\/ Returns true if the given string represents an IP address.\nbool IsIPAddress(const std::string& domain) {\n \/\/ From GURL::HostIsIPAddress()\n url_canon::RawCanonOutputT<char, 128> ignored_output;\n url_canon::CanonHostInfo host_info;\n url_parse::Component domain_comp(0, domain.size());\n url_canon::CanonicalizeIPAddress(domain.c_str(), domain_comp,\n &ignored_output, &host_info);\n return host_info.IsIPAddress();\n}\n\n} \/\/ namespace\n\nProxyBypassRules::~ProxyBypassRules() {\n}\n\nbool ProxyBypassRules::Matches(const GURL& url) const {\n for (RuleList::const_iterator it = rules_.begin(); it != rules_.end(); ++it) {\n if ((*it)->Matches(url))\n return true;\n }\n return false;\n}\n\nbool ProxyBypassRules::Equals(const ProxyBypassRules& other) const {\n if (rules_.size() != other.rules().size())\n return false;\n\n for (size_t i = 0; i < rules_.size(); ++i) {\n if (!rules_[i]->Equals(*other.rules()[i]))\n return false;\n }\n return true;\n}\n\nvoid ProxyBypassRules::ParseFromString(const std::string& raw) {\n ParseFromStringInternal(raw, false);\n}\n\nvoid ProxyBypassRules::ParseFromStringUsingSuffixMatching(\n const std::string& raw) {\n ParseFromStringInternal(raw, true);\n}\n\nbool ProxyBypassRules::AddRuleForHostname(const std::string& optional_scheme,\n const std::string& hostname_pattern,\n int optional_port) {\n if (hostname_pattern.empty())\n return false;\n\n rules_.push_back(new HostnamePatternRule(optional_scheme,\n hostname_pattern,\n optional_port));\n return true;\n}\n\nvoid ProxyBypassRules::AddRuleToBypassLocal() {\n rules_.push_back(new BypassLocalRule);\n}\n\nbool ProxyBypassRules::AddRuleFromString(const std::string& raw) {\n return AddRuleFromStringInternalWithLogging(raw, false);\n}\n\nvoid ProxyBypassRules::Clear() {\n rules_.clear();\n}\n\nvoid ProxyBypassRules::ParseFromStringInternal(\n const std::string& raw,\n bool use_hostname_suffix_matching) {\n Clear();\n\n StringTokenizer entries(raw, \",;\");\n while (entries.GetNext()) {\n AddRuleFromStringInternalWithLogging(entries.token(),\n use_hostname_suffix_matching);\n }\n}\n\nbool ProxyBypassRules::AddRuleFromStringInternal(\n const std::string& raw_untrimmed,\n bool use_hostname_suffix_matching) {\n std::string raw;\n TrimWhitespaceASCII(raw_untrimmed, TRIM_ALL, &raw);\n\n \/\/ This is the special syntax used by WinInet's bypass list -- we allow it\n \/\/ on all platforms and interpret it the same way.\n if (LowerCaseEqualsASCII(raw, \"<local>\")) {\n AddRuleToBypassLocal();\n return true;\n }\n\n \/\/ Extract any scheme-restriction.\n std::string::size_type scheme_pos = raw.find(\":\/\/\");\n std::string scheme;\n if (scheme_pos != std::string::npos) {\n scheme = raw.substr(0, scheme_pos);\n raw = raw.substr(scheme_pos + 3);\n if (scheme.empty())\n return false;\n }\n\n if (raw.empty())\n return false;\n\n \/\/ If there is a forward slash in the input, it is probably a CIDR style\n \/\/ mask.\n if (raw.find('\/') != std::string::npos) {\n LOG(WARNING) << \"TODO: support CIDR-style proxy bypass entries \"\n \"(http:\/\/crbug.com\/9835)\";\n return false;\n }\n\n \/\/ Check if we have an <ip-address>[:port] input. We need to treat this\n \/\/ separately since the IP literal may not be in a canonical form.\n std::string host;\n int port;\n if (ParseHostAndPort(raw, &host, &port)) {\n if (IsIPAddress(host)) {\n \/\/ Canonicalize the IP literal before adding it as a string pattern.\n GURL tmp_url(\"http:\/\/\" + host);\n return AddRuleForHostname(scheme, tmp_url.host(), port);\n }\n }\n\n \/\/ Otherwise assume we have <hostname-pattern>[:port].\n std::string::size_type pos_colon = raw.rfind(':');\n host = raw;\n port = -1;\n if (pos_colon != std::string::npos) {\n if (!StringToInt(raw.substr(pos_colon + 1), &port) ||\n (port < 0 || port > 0xFFFF)) {\n return false; \/\/ Port was invalid.\n }\n raw = raw.substr(0, pos_colon);\n }\n\n \/\/ Special-case hostnames that begin with a period.\n \/\/ For example, we remap \".google.com\" --> \"*.google.com\".\n if (StartsWithASCII(raw, \".\", false))\n raw = \"*\" + raw;\n\n \/\/ If suffix matching was asked for, make sure the pattern starts with a\n \/\/ wildcard.\n if (use_hostname_suffix_matching && !StartsWithASCII(raw, \"*\", false))\n raw = \"*\" + raw;\n\n return AddRuleForHostname(scheme, raw, port);\n}\n\nbool ProxyBypassRules::AddRuleFromStringInternalWithLogging(\n const std::string& raw,\n bool use_hostname_suffix_matching) {\n bool ok = AddRuleFromStringInternal(raw, use_hostname_suffix_matching);\n LOG_IF(WARNING, !ok) << \"Unable to parse proxy bypass rule: \" << raw;\n return ok;\n}\n\n} \/\/ namespace net\n<commit_msg>Remove LOG(WARNING)s for when fails to parse proxy bypass rules. This can pollute the log since it gets hit often (each time poll for checks).<commit_after>\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"net\/proxy\/proxy_bypass_rules.h\"\n\n#include \"base\/logging.h\"\n#include \"base\/string_tokenizer.h\"\n#include \"base\/string_util.h\"\n#include \"net\/base\/net_util.h\"\n\nnamespace net {\n\nnamespace {\n\nclass HostnamePatternRule : public ProxyBypassRules::Rule {\n public:\n HostnamePatternRule(const std::string& optional_scheme,\n const std::string& hostname_pattern,\n int optional_port)\n : optional_scheme_(StringToLowerASCII(optional_scheme)),\n hostname_pattern_(StringToLowerASCII(hostname_pattern)),\n optional_port_(optional_port) {\n }\n\n virtual bool Matches(const GURL& url) const {\n if (optional_port_ != -1 && url.EffectiveIntPort() != optional_port_)\n return false; \/\/ Didn't match port expectation.\n\n if (!optional_scheme_.empty() && url.scheme() != optional_scheme_)\n return false; \/\/ Didn't match scheme expectation.\n\n \/\/ Note it is necessary to lower-case the host, since GURL uses capital\n \/\/ letters for percent-escaped characters.\n return MatchPatternASCII(StringToLowerASCII(url.host()),\n hostname_pattern_);\n }\n\n virtual std::string ToString() const {\n std::string str;\n if (!optional_scheme_.empty())\n StringAppendF(&str, \"%s:\/\/\", optional_scheme_.c_str());\n str += hostname_pattern_;\n if (optional_port_ != -1)\n StringAppendF(&str, \":%d\", optional_port_);\n return str;\n }\n\n private:\n const std::string optional_scheme_;\n const std::string hostname_pattern_;\n const int optional_port_;\n};\n\nclass BypassLocalRule : public ProxyBypassRules::Rule {\n public:\n virtual bool Matches(const GURL& url) const {\n const std::string& host = url.host();\n if (host == \"127.0.0.1\" || host == \"[::1]\")\n return true;\n return host.find('.') == std::string::npos;\n }\n\n virtual std::string ToString() const {\n return \"<local>\";\n }\n};\n\n\/\/ Returns true if the given string represents an IP address.\nbool IsIPAddress(const std::string& domain) {\n \/\/ From GURL::HostIsIPAddress()\n url_canon::RawCanonOutputT<char, 128> ignored_output;\n url_canon::CanonHostInfo host_info;\n url_parse::Component domain_comp(0, domain.size());\n url_canon::CanonicalizeIPAddress(domain.c_str(), domain_comp,\n &ignored_output, &host_info);\n return host_info.IsIPAddress();\n}\n\n} \/\/ namespace\n\nProxyBypassRules::~ProxyBypassRules() {\n}\n\nbool ProxyBypassRules::Matches(const GURL& url) const {\n for (RuleList::const_iterator it = rules_.begin(); it != rules_.end(); ++it) {\n if ((*it)->Matches(url))\n return true;\n }\n return false;\n}\n\nbool ProxyBypassRules::Equals(const ProxyBypassRules& other) const {\n if (rules_.size() != other.rules().size())\n return false;\n\n for (size_t i = 0; i < rules_.size(); ++i) {\n if (!rules_[i]->Equals(*other.rules()[i]))\n return false;\n }\n return true;\n}\n\nvoid ProxyBypassRules::ParseFromString(const std::string& raw) {\n ParseFromStringInternal(raw, false);\n}\n\nvoid ProxyBypassRules::ParseFromStringUsingSuffixMatching(\n const std::string& raw) {\n ParseFromStringInternal(raw, true);\n}\n\nbool ProxyBypassRules::AddRuleForHostname(const std::string& optional_scheme,\n const std::string& hostname_pattern,\n int optional_port) {\n if (hostname_pattern.empty())\n return false;\n\n rules_.push_back(new HostnamePatternRule(optional_scheme,\n hostname_pattern,\n optional_port));\n return true;\n}\n\nvoid ProxyBypassRules::AddRuleToBypassLocal() {\n rules_.push_back(new BypassLocalRule);\n}\n\nbool ProxyBypassRules::AddRuleFromString(const std::string& raw) {\n return AddRuleFromStringInternalWithLogging(raw, false);\n}\n\nvoid ProxyBypassRules::Clear() {\n rules_.clear();\n}\n\nvoid ProxyBypassRules::ParseFromStringInternal(\n const std::string& raw,\n bool use_hostname_suffix_matching) {\n Clear();\n\n StringTokenizer entries(raw, \",;\");\n while (entries.GetNext()) {\n AddRuleFromStringInternalWithLogging(entries.token(),\n use_hostname_suffix_matching);\n }\n}\n\nbool ProxyBypassRules::AddRuleFromStringInternal(\n const std::string& raw_untrimmed,\n bool use_hostname_suffix_matching) {\n std::string raw;\n TrimWhitespaceASCII(raw_untrimmed, TRIM_ALL, &raw);\n\n \/\/ This is the special syntax used by WinInet's bypass list -- we allow it\n \/\/ on all platforms and interpret it the same way.\n if (LowerCaseEqualsASCII(raw, \"<local>\")) {\n AddRuleToBypassLocal();\n return true;\n }\n\n \/\/ Extract any scheme-restriction.\n std::string::size_type scheme_pos = raw.find(\":\/\/\");\n std::string scheme;\n if (scheme_pos != std::string::npos) {\n scheme = raw.substr(0, scheme_pos);\n raw = raw.substr(scheme_pos + 3);\n if (scheme.empty())\n return false;\n }\n\n if (raw.empty())\n return false;\n\n \/\/ If there is a forward slash in the input, it is probably a CIDR style\n \/\/ mask.\n if (raw.find('\/') != std::string::npos) {\n \/\/ TODO(eroman): support CIDR-style proxy bypass entries\n \/\/ (http:\/\/crbug.com\/9835)\n return false;\n }\n\n \/\/ Check if we have an <ip-address>[:port] input. We need to treat this\n \/\/ separately since the IP literal may not be in a canonical form.\n std::string host;\n int port;\n if (ParseHostAndPort(raw, &host, &port)) {\n if (IsIPAddress(host)) {\n \/\/ Canonicalize the IP literal before adding it as a string pattern.\n GURL tmp_url(\"http:\/\/\" + host);\n return AddRuleForHostname(scheme, tmp_url.host(), port);\n }\n }\n\n \/\/ Otherwise assume we have <hostname-pattern>[:port].\n std::string::size_type pos_colon = raw.rfind(':');\n host = raw;\n port = -1;\n if (pos_colon != std::string::npos) {\n if (!StringToInt(raw.substr(pos_colon + 1), &port) ||\n (port < 0 || port > 0xFFFF)) {\n return false; \/\/ Port was invalid.\n }\n raw = raw.substr(0, pos_colon);\n }\n\n \/\/ Special-case hostnames that begin with a period.\n \/\/ For example, we remap \".google.com\" --> \"*.google.com\".\n if (StartsWithASCII(raw, \".\", false))\n raw = \"*\" + raw;\n\n \/\/ If suffix matching was asked for, make sure the pattern starts with a\n \/\/ wildcard.\n if (use_hostname_suffix_matching && !StartsWithASCII(raw, \"*\", false))\n raw = \"*\" + raw;\n\n return AddRuleForHostname(scheme, raw, port);\n}\n\nbool ProxyBypassRules::AddRuleFromStringInternalWithLogging(\n const std::string& raw,\n bool use_hostname_suffix_matching) {\n return AddRuleFromStringInternal(raw, use_hostname_suffix_matching);\n}\n\n} \/\/ namespace net\n<|endoftext|>"} {"text":"<commit_before>#ifndef PARSER_H\n#define PARSER_H\n#include <vector>\n\n\/\/namespace definition\nnamespace CVRP {\n struct Node;\n struct Instance;\n class Parser;\n}\n\n\/\/node definition\nstruct CVRP::Node{\n int demand;\n int x;\n int y;\n};\n\n\/\/instance definition\nstruct CVRP::Instance{\n int number_of_trucks;\n int number_of_nodes;\n int capacity;\n std::vector<Node> nodes;\n std::vector<std::vector<double>> distance_matrix;\n};\n\n\/\/parser definition\nclass CVRP::Parser{\n public:\n Parser();\n ~Parser();\n Instance build_problem();\n double calc_distance(Node node1, Node node2);\n void print_nodes(Instance problem_instance);\n void print_matrix(Instance problem_instance);\n};\n\n#endif\n<commit_msg>Parser | Adicao de atributo de marcacao no nó<commit_after>#ifndef PARSER_H\n#define PARSER_H\n#include <vector>\n\n\/\/namespace definition\nnamespace CVRP {\n class Parser;\n struct Instance;\n struct Node;\n}\n\n\/\/node definition\nstruct CVRP::Node{\n int demand;\n int x;\n int y;\n bool marked = false;\n};\n\n\n\/\/instance definition\nstruct CVRP::Instance{\n int number_of_trucks;\n int number_of_nodes;\n int capacity;\n std::vector<Node> nodes;\n std::vector<std::vector<double>> distance_matrix;\n};\n\n\/\/parser definition\nclass CVRP::Parser{\n public:\n Parser();\n ~Parser();\n Instance build_problem();\n double calc_distance(Node node1, Node node2);\n void print_nodes(Instance problem_instance);\n void print_matrix(Instance problem_instance);\n};\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/* Copyright 2016 Stanford University, NVIDIA Corporation\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"llvmjit_internal.h\"\n\n#include \"realm\/logging.h\"\n\n#include <iostream>\n\n\/\/ xcode's clang isn't defining these?\n#define __STDC_LIMIT_MACROS\n#define __STDC_CONSTANT_MACROS\n\n#include <cstdint>\n\n#include <llvm\/IR\/LLVMContext.h>\n#include <llvm\/IR\/Constants.h>\n#include <llvm\/IR\/Module.h>\n#include <llvm\/IR\/DataLayout.h>\n#include <llvm\/IRReader\/IRReader.h>\n#include <llvm\/Support\/Host.h>\n#include <llvm\/Support\/TargetRegistry.h>\n#include <llvm\/Support\/TargetSelect.h>\n#include <llvm\/Target\/TargetMachine.h>\n#include <llvm\/Support\/SourceMgr.h>\n#include <llvm\/Bitcode\/ReaderWriter.h>\n#include <llvm\/ExecutionEngine\/ExecutionEngine.h>\n#include <llvm\/Support\/MemoryBuffer.h>\n#include <llvm\/ExecutionEngine\/JIT.h>\n#include \"llvm\/Support\/raw_ostream.h\"\n#include \"llvm\/Support\/raw_os_ostream.h\"\n#include \"llvm\/Support\/FormattedStream.h\"\n#include \"llvm\/PassManager.h\"\n\nnamespace Realm {\n\n extern Logger log_llvmjit; \/\/ defined in llvmjit_module.cc\n\n namespace LLVMJit {\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/\n \/\/ class LLVMJitInternal\n\n LLVMJitInternal::LLVMJitInternal(void)\n {\n context = new llvm::LLVMContext;\n\n \/\/ generative native target\n {\n\tllvm::InitializeNativeTarget();\n\n\tstd::string triple = llvm::sys::getDefaultTargetTriple();\n\tlog_llvmjit.debug() << \"default target triple = \" << triple;\n\n\tstd::string err;\n\tconst llvm::Target *target = llvm::TargetRegistry::lookupTarget(triple, err);\n\tif(!target) {\n\t log_llvmjit.fatal() << \"target not found: triple='\" << triple << \"'\";\n\t assert(0);\n\t}\n\n\t\/\/ TODO - allow configuration options to steer these\n\tllvm::Reloc::Model reloc_model = llvm::Reloc::Default;\n\tllvm::CodeModel::Model code_model = llvm::CodeModel::Large;\n\tllvm::CodeGenOpt::Level opt_level = llvm::CodeGenOpt::Aggressive;\n\n\tllvm::TargetOptions options;\n\toptions.NoFramePointerElim = true;\n\n\tllvm::TargetMachine *host_cpu_machine = target->createTargetMachine(triple, \"\", \n\t\t\t\t\t\t\t\t\t 0\/*HostHasAVX()*\/ ? \"+avx\" : \"\", \n\t\t\t\t\t\t\t\t\t options,\n\t\t\t\t\t\t\t\t\t reloc_model,\n\t\t\t\t\t\t\t\t\t code_model,\n\t\t\t\t\t\t\t\t\t opt_level);\n\tassert(host_cpu_machine != 0);\n\n\t\/\/ you have to have a module to build an execution engine, so create\n\t\/\/ a dummy one\n\t{\n\t llvm::Module *m = new llvm::Module(\"eebuilder\", *context);\n\t m->setTargetTriple(triple);\n\t llvm::EngineBuilder eb(m);\n\n\t std::string err;\n \n\t eb\n\t .setErrorStr(&err)\n\t .setEngineKind(llvm::EngineKind::JIT)\n\t .setAllocateGVsWithCode(false)\n\t .setUseMCJIT(true);\n\t \n\t host_exec_engine = eb.create(host_cpu_machine);\n\n\t if(!host_exec_engine) {\n\t log_llvmjit.fatal() << \"failed to create execution engine: \" << err;\n\t assert(0);\n\t }\n\t}\n }\n\n nvptx_machine = 0;\n }\n\n LLVMJitInternal::~LLVMJitInternal(void)\n {\n delete host_exec_engine;\n delete context;\n }\n \n void *LLVMJitInternal::llvmir_to_fnptr(const ByteArray& ir,\n\t\t\t\t\t const std::string& entry_symbol)\n {\n \/\/ do we even know how to jit?\n if(!host_exec_engine)\n\treturn 0;\n\n llvm::SMDiagnostic sm;\n llvm::MemoryBuffer *mb = llvm::MemoryBuffer::getMemBuffer((const char *)ir.base());\n llvm::Module *m = llvm::ParseIR(mb, sm, *context);\n if(!m) {\n\tstd::string errstr;\n\tllvm::raw_string_ostream s(errstr);\n\tsm.print(entry_symbol.c_str(), s);\n\tlog_llvmjit.fatal() << \"LLVM IR PARSE ERROR:\\n\" << s.str();\n\tassert(0);\n }\n m->setDataLayout(\"e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-f32:32:32-f64:64:64-v16:16:16-v32:32:32-v64:64:64-v128:128:128-n16:32:64\");\n\n host_exec_engine->addModule(m);\n\n llvm::Function* func = host_exec_engine->FindFunctionNamed(entry_symbol.c_str());\n if(!func) {\n\tlog_llvmjit.fatal() << \"entry symbol not found: \" << entry_symbol;\n\tassert(0);\n }\n \n void *fnptr = host_exec_engine->getPointerToFunction(func);\n assert(fnptr != 0);\n\n return fnptr;\n }\n\n }; \/\/ namespace LLVMJit\n\n}; \/\/ namespace Realm\n<commit_msg>llvmjit: make sure we find the entry symbol in the current LLVM blob<commit_after>\/* Copyright 2016 Stanford University, NVIDIA Corporation\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"llvmjit_internal.h\"\n\n#include \"realm\/logging.h\"\n\n#include <iostream>\n\n\/\/ xcode's clang isn't defining these?\n#define __STDC_LIMIT_MACROS\n#define __STDC_CONSTANT_MACROS\n\n#include <cstdint>\n\n#include <llvm\/IR\/LLVMContext.h>\n#include <llvm\/IR\/Constants.h>\n#include <llvm\/IR\/Module.h>\n#include <llvm\/IR\/DataLayout.h>\n#include <llvm\/IRReader\/IRReader.h>\n#include <llvm\/Support\/Host.h>\n#include <llvm\/Support\/TargetRegistry.h>\n#include <llvm\/Support\/TargetSelect.h>\n#include <llvm\/Target\/TargetMachine.h>\n#include <llvm\/Support\/SourceMgr.h>\n#include <llvm\/Bitcode\/ReaderWriter.h>\n#include <llvm\/ExecutionEngine\/ExecutionEngine.h>\n#include <llvm\/Support\/MemoryBuffer.h>\n#include <llvm\/ExecutionEngine\/JIT.h>\n#include \"llvm\/Support\/raw_ostream.h\"\n#include \"llvm\/Support\/raw_os_ostream.h\"\n#include \"llvm\/Support\/FormattedStream.h\"\n#include \"llvm\/PassManager.h\"\n\nnamespace Realm {\n\n extern Logger log_llvmjit; \/\/ defined in llvmjit_module.cc\n\n namespace LLVMJit {\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/\n \/\/ class LLVMJitInternal\n\n LLVMJitInternal::LLVMJitInternal(void)\n {\n context = new llvm::LLVMContext;\n\n \/\/ generative native target\n {\n\tllvm::InitializeNativeTarget();\n\n\tstd::string triple = llvm::sys::getDefaultTargetTriple();\n\tlog_llvmjit.debug() << \"default target triple = \" << triple;\n\n\tstd::string err;\n\tconst llvm::Target *target = llvm::TargetRegistry::lookupTarget(triple, err);\n\tif(!target) {\n\t log_llvmjit.fatal() << \"target not found: triple='\" << triple << \"'\";\n\t assert(0);\n\t}\n\n\t\/\/ TODO - allow configuration options to steer these\n\tllvm::Reloc::Model reloc_model = llvm::Reloc::Default;\n\tllvm::CodeModel::Model code_model = llvm::CodeModel::Large;\n\tllvm::CodeGenOpt::Level opt_level = llvm::CodeGenOpt::Aggressive;\n\n\tllvm::TargetOptions options;\n\toptions.NoFramePointerElim = true;\n\n\tllvm::TargetMachine *host_cpu_machine = target->createTargetMachine(triple, \"\", \n\t\t\t\t\t\t\t\t\t 0\/*HostHasAVX()*\/ ? \"+avx\" : \"\", \n\t\t\t\t\t\t\t\t\t options,\n\t\t\t\t\t\t\t\t\t reloc_model,\n\t\t\t\t\t\t\t\t\t code_model,\n\t\t\t\t\t\t\t\t\t opt_level);\n\tassert(host_cpu_machine != 0);\n\n\t\/\/ you have to have a module to build an execution engine, so create\n\t\/\/ a dummy one\n\t{\n\t llvm::Module *m = new llvm::Module(\"eebuilder\", *context);\n\t m->setTargetTriple(triple);\n\t m->setDataLayout(\"e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-f32:32:32-f64:64:64-v16:16:16-v32:32:32-v64:64:64-v128:128:128-n16:32:64\");\n\t llvm::EngineBuilder eb(m);\n\n\t std::string err;\n \n\t eb\n\t .setErrorStr(&err)\n\t .setEngineKind(llvm::EngineKind::JIT)\n\t .setAllocateGVsWithCode(false)\n\t .setUseMCJIT(true);\n\t \n\t host_exec_engine = eb.create(host_cpu_machine);\n\n\t if(!host_exec_engine) {\n\t log_llvmjit.fatal() << \"failed to create execution engine: \" << err;\n\t assert(0);\n\t }\n\t}\n }\n\n nvptx_machine = 0;\n }\n\n LLVMJitInternal::~LLVMJitInternal(void)\n {\n delete host_exec_engine;\n delete context;\n }\n \n void *LLVMJitInternal::llvmir_to_fnptr(const ByteArray& ir,\n\t\t\t\t\t const std::string& entry_symbol)\n {\n \/\/ do we even know how to jit?\n if(!host_exec_engine)\n\treturn 0;\n\n llvm::SMDiagnostic sm;\n llvm::MemoryBuffer *mb = llvm::MemoryBuffer::getMemBuffer((const char *)ir.base());\n llvm::Module *m = llvm::ParseIR(mb, sm, *context);\n if(!m) {\n\tstd::string errstr;\n\tllvm::raw_string_ostream s(errstr);\n\tsm.print(entry_symbol.c_str(), s);\n\tlog_llvmjit.fatal() << \"LLVM IR PARSE ERROR:\\n\" << s.str();\n\tassert(0);\n }\n\n \/\/ get the entry function from the module before we add it to the exec engine - that way\n \/\/ we're sure to get the one we want\n llvm::Function *func = m->getFunction(entry_symbol.c_str());\n if(!func) {\n\tlog_llvmjit.fatal() << \"entry symbol not found: \" << entry_symbol;\n\tassert(0);\n }\n\n host_exec_engine->addModule(m);\n\n void *fnptr = host_exec_engine->getPointerToFunction(func);\n assert(fnptr != 0);\n\n return fnptr;\n }\n\n }; \/\/ namespace LLVMJit\n\n}; \/\/ namespace Realm\n<|endoftext|>"} {"text":"<commit_before>#ifndef DUNE_FUNCTIONALS_ASSEMLBER_LOCAL_CODIM0_MATRIX_HH\n#define DUNE_FUNCTIONALS_ASSEMLBER_LOCAL_CODIM0_MATRIX_HH\n\n\/\/ local includes\n#include \"vector.hh\"\n\nnamespace Dune\n{\n\nnamespace Functionals\n{\n\nnamespace Assembler\n{\n\nnamespace Local\n{\n\nnamespace Codim0\n{\n\ntemplate< class LocalOperatorImp >\nclass Matrix\n{\npublic:\n\n typedef LocalOperatorImp\n LocalOperatorType;\n\n typedef Matrix< LocalOperatorType >\n ThisType;\n\n typedef typename LocalOperatorType::RangeFieldType\n RangeFieldType;\n\n template< class InducingDiscreteFunctionType >\n class LocalVectorAssembler\n {\n private:\n typedef typename LocalOperatorType::template LocalFunctional< InducingDiscreteFunctionType >::Type\n InducingFunctionalType;\n\n public:\n typedef Dune::Functionals::Assembler::Local::Codim0::Vector< InducingFunctionalType >\n Type;\n };\n\n \/\/! constructor\n Matrix( const LocalOperatorType& localOperator )\n : localOperator_( localOperator )\n {\n }\n\nprivate:\n \/\/! copy constructor\n Matrix( const ThisType& other )\n : localOperator_( other.localOperator() )\n {\n }\n\npublic:\n const LocalOperatorType& localOperator() const\n {\n return localOperator_;\n }\n\n template< class InducingDiscreteFunctionType >\n typename LocalVectorAssembler< InducingDiscreteFunctionType >::Type localVectorAssembler( const InducingDiscreteFunctionType& inducingDiscreteFunction ) const\n {\n typedef typename LocalVectorAssembler< InducingDiscreteFunctionType >::Type\n LocalVectorAssemblerType;\n\n return LocalVectorAssemblerType( localOperator_.localFunctional( inducingDiscreteFunction ) );\n }\n\n template< class AnsatzSpaceType,\n class TestSpaceType,\n class EntityType,\n class MatrixType,\n class LocalMatrixType >\n void assembleLocal( const AnsatzSpaceType& ansatzSpace,\n const TestSpaceType& testSpace,\n const EntityType& entity,\n MatrixType& matrix,\n LocalMatrixType& tmpLocalMatrix ) const\n {\n \/\/ write local operator application to tmpLocalMatrix\n localOperator_.applyLocal( ansatzSpace.baseFunctionSet().local( entity ), testSpace.baseFunctionSet().local( entity ), tmpLocalMatrix );\n\n \/\/ write local matrix to global\n addToMatrix( ansatzSpace, testSpace, entity, tmpLocalMatrix, matrix );\n }\n\nprivate:\n\n \/\/! assignment operator\n ThisType& operator=( const ThisType& );\n\n template< class AnsatzSpaceType,\n class TestSpaceType,\n class EntityType,\n class LocalMatrixType,\n class MatrixType >\n void addToMatrix( const AnsatzSpaceType& ansatzSpace,\n const TestSpaceType& testSpace,\n const EntityType& entity,\n const LocalMatrixType& localMatrix,\n MatrixType& matrix ) const\n {\n for( unsigned int i = 0; i < ansatzSpace.baseFunctionSet().local( entity ).size(); ++i )\n {\n for( unsigned int j = 0; j < testSpace.baseFunctionSet().local( entity ).size(); ++j )\n {\n const unsigned int globalI = ansatzSpace.map().toGlobal( entity, i );\n const unsigned int globalJ = testSpace.map().toGlobal( entity, j );\n\n matrix[globalI][globalJ] += localMatrix[i][j];\n }\n }\n } \/\/ end method addToMatrix\n\n const LocalOperatorType& localOperator_;\n\n}; \/\/ end class Matrix\n\n} \/\/ end namespace Codim0\n\n} \/\/ end namespace Local\n\n} \/\/ end namespace Assembler\n\n} \/\/ end namespace Functionals\n\n} \/\/ end namespace Dune\n\n#endif \/\/ DUNE_FUNCTIONALS_ASSEMLBER_LOCAL_CODIM0_MATRIX_HH\n<commit_msg>some beautyfication<commit_after>#ifndef DUNE_FUNCTIONALS_ASSEMLBER_LOCAL_CODIM0_MATRIX_HH\n#define DUNE_FUNCTIONALS_ASSEMLBER_LOCAL_CODIM0_MATRIX_HH\n\n\/\/ local includes\n#include \"vector.hh\"\n\nnamespace Dune\n{\n\nnamespace Functionals\n{\n\nnamespace Assembler\n{\n\nnamespace Local\n{\n\nnamespace Codim0\n{\n\ntemplate< class LocalOperatorImp >\nclass Matrix\n{\npublic:\n\n typedef LocalOperatorImp\n LocalOperatorType;\n\n typedef Matrix< LocalOperatorType >\n ThisType;\n\n typedef typename LocalOperatorType::RangeFieldType\n RangeFieldType;\n\n template< class InducingDiscreteFunctionType >\n class LocalVectorAssembler\n {\n private:\n typedef typename LocalOperatorType::template LocalFunctional< InducingDiscreteFunctionType >::Type\n InducingFunctionalType;\n\n public:\n typedef Dune::Functionals::Assembler::Local::Codim0::Vector< InducingFunctionalType >\n Type;\n };\n\n \/\/! constructor\n Matrix( const LocalOperatorType& localOperator )\n : localOperator_( localOperator )\n {\n }\n\nprivate:\n \/\/! copy constructor\n Matrix( const ThisType& other )\n : localOperator_( other.localOperator() )\n {\n }\n\npublic:\n const LocalOperatorType& localOperator() const\n {\n return localOperator_;\n }\n\n template< class InducingDiscreteFunctionType >\n typename LocalVectorAssembler< InducingDiscreteFunctionType >::Type\n localVectorAssembler( const InducingDiscreteFunctionType& inducingDiscreteFunction ) const\n {\n typedef typename LocalVectorAssembler< InducingDiscreteFunctionType >::Type\n LocalVectorAssemblerType;\n\n return LocalVectorAssemblerType( localOperator_.localFunctional( inducingDiscreteFunction ) );\n }\n\n template< class AnsatzSpaceType,\n class TestSpaceType,\n class EntityType,\n class MatrixType,\n class LocalMatrixType >\n void assembleLocal( const AnsatzSpaceType& ansatzSpace,\n const TestSpaceType& testSpace,\n const EntityType& entity,\n MatrixType& matrix,\n LocalMatrixType& tmpLocalMatrix ) const\n {\n \/\/ write local operator application to tmpLocalMatrix\n localOperator_.applyLocal( ansatzSpace.baseFunctionSet().local( entity ),\n testSpace.baseFunctionSet().local( entity ),\n tmpLocalMatrix );\n\n \/\/ write local matrix to global\n addToMatrix( ansatzSpace, testSpace, entity, tmpLocalMatrix, matrix );\n }\n\nprivate:\n\n \/\/! assignment operator\n ThisType& operator=( const ThisType& );\n\n template< class AnsatzSpaceType,\n class TestSpaceType,\n class EntityType,\n class LocalMatrixType,\n class MatrixType >\n void addToMatrix( const AnsatzSpaceType& ansatzSpace,\n const TestSpaceType& testSpace,\n const EntityType& entity,\n const LocalMatrixType& localMatrix,\n MatrixType& matrix ) const\n {\n for( unsigned int i = 0; i < ansatzSpace.baseFunctionSet().local( entity ).size(); ++i )\n {\n for( unsigned int j = 0; j < testSpace.baseFunctionSet().local( entity ).size(); ++j )\n {\n const unsigned int globalI = ansatzSpace.map().toGlobal( entity, i );\n const unsigned int globalJ = testSpace.map().toGlobal( entity, j );\n\n matrix[globalI][globalJ] += localMatrix[i][j];\n }\n }\n } \/\/ end method addToMatrix\n\n const LocalOperatorType& localOperator_;\n\n}; \/\/ end class Matrix\n\n} \/\/ end namespace Codim0\n\n} \/\/ end namespace Local\n\n} \/\/ end namespace Assembler\n\n} \/\/ end namespace Functionals\n\n} \/\/ end namespace Dune\n\n#endif \/\/ DUNE_FUNCTIONALS_ASSEMLBER_LOCAL_CODIM0_MATRIX_HH\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\r\n> File Name: Interface.cpp\r\n> Project Name: Hearthstone++\r\n> Author: Young-Joong Kim\r\n> Purpose: Interface for Hearthstone Game Agent\r\n> Created Time: 2017\/10\/04\r\n> Copyright (c) 2017, Young-Joong Kim\r\n*************************************************************************\/\r\n#include <Agents\/Interface.h>\r\n\r\nnamespace Hearthstonepp\r\n{\r\n\tInteractBuffer::InteractBuffer(int capacity)\r\n\t{\r\n\t\tthis->capacity = capacity; \/\/ size of the buffer\r\n\t\tthis->head = 0;\r\n\t\tthis->tail = 0;\r\n\t\tthis->usage = 0; \/\/ size of the data in the buffer\r\n\t\tthis->readable = false; \/\/ whether the buffer has data\r\n\t\tthis->buffer = new BYTE[capacity]; \/\/ buffer, circular queue\r\n\t}\r\n\r\n\tint InteractBuffer::ReadBuffer(BYTE *data, int maxSize)\r\n\t{\r\n\t\tstd::unique_lock<std::mutex> lock(mtx);\r\n\t\tcv.wait(lock, [this]() { return readable; }); \/\/ wait until the buffer can be read\r\n\r\n\t\tint read = 0;\r\n\t\tfor (int i = 0; (i < usage) && maxSize; ++i) \/\/ read data from buffer\r\n\t\t{\r\n\t\t\tdata[i] = buffer[head];\r\n\r\n\t\t\thead = (head + 1) % capacity;\r\n\t\t\tmaxSize -= 1;\r\n\t\t\tread += 1;\r\n\t\t}\r\n\r\n\t\tusage -= read; \/\/ calculate remaining capacity to read\r\n\r\n\t\treadable = false;\r\n\t\tcv.notify_one(); \/\/ inform buffer is writable\r\n\r\n\t\treturn read;\r\n\t}\r\n\r\n\tint InteractBuffer::WriteBuffer(BYTE *data, int size)\r\n\t{\r\n\t\tstd::unique_lock<std::mutex> lock(mtx);\r\n\t\tcv.wait(lock, [this]() { return !readable; }); \/\/ wait until the buffer can be write\r\n\r\n\t\tfor (int i = 0; (i < size) && (usage < capacity); ++i) \/\/ write data to buffer\r\n\t\t{\r\n\t\t\tbuffer[tail] = data[i];\r\n\r\n\t\t\ttail = (tail + 1) % capacity;\r\n\t\t\tusage += 1;\r\n\t\t}\r\n\r\n\t\treadable = true;\r\n\t\tcv.notify_one(); \/\/ inform buffer is readable\r\n\r\n\t\treturn usage;\r\n\t}\r\n}<commit_msg>Update Interface - InteractBuffer ctor initialize with list<commit_after>\/*************************************************************************\r\n> File Name: Interface.cpp\r\n> Project Name: Hearthstone++\r\n> Author: Young-Joong Kim\r\n> Purpose: Interface for Hearthstone Game Agent\r\n> Created Time: 2017\/10\/04\r\n> Copyright (c) 2017, Young-Joong Kim\r\n*************************************************************************\/\r\n#include <Agents\/Interface.h>\r\n\r\nnamespace Hearthstonepp\r\n{\r\n\tInteractBuffer::InteractBuffer(int capacity)\r\n\t\t: capacity(capacity), head(0), tail(0), usage(0), readable(false)\r\n\t{\r\n\t\tbuffer = new BYTE[capacity]; \/\/ buffer, circular queue\r\n\t}\r\n\r\n\tint InteractBuffer::ReadBuffer(BYTE *data, int maxSize)\r\n\t{\r\n\t\tstd::unique_lock<std::mutex> lock(mtx);\r\n\t\tcv.wait(lock, [this]() { return readable; }); \/\/ wait until the buffer can be read\r\n\r\n\t\tint read = 0;\r\n\t\tfor (int i = 0; (i < usage) && maxSize; ++i) \/\/ read data from buffer\r\n\t\t{\r\n\t\t\tdata[i] = buffer[head];\r\n\r\n\t\t\thead = (head + 1) % capacity;\r\n\t\t\tmaxSize -= 1;\r\n\t\t\tread += 1;\r\n\t\t}\r\n\r\n\t\tusage -= read; \/\/ calculate remaining capacity to read\r\n\r\n\t\treadable = false;\r\n\t\tcv.notify_one(); \/\/ inform buffer is writable\r\n\r\n\t\treturn read;\r\n\t}\r\n\r\n\tint InteractBuffer::WriteBuffer(BYTE *data, int size)\r\n\t{\r\n\t\tstd::unique_lock<std::mutex> lock(mtx);\r\n\t\tcv.wait(lock, [this]() { return !readable; }); \/\/ wait until the buffer can be write\r\n\r\n\t\tfor (int i = 0; (i < size) && (usage < capacity); ++i) \/\/ write data to buffer\r\n\t\t{\r\n\t\t\tbuffer[tail] = data[i];\r\n\r\n\t\t\ttail = (tail + 1) % capacity;\r\n\t\t\tusage += 1;\r\n\t\t}\r\n\r\n\t\treadable = true;\r\n\t\tcv.notify_one(); \/\/ inform buffer is readable\r\n\r\n\t\treturn usage;\r\n\t}\r\n}<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 2011-2012 Stephen Williams (steve@icarus.com)\n *\n * This source code is free software; you can redistribute it\n * and\/or modify it in source code form under the terms of the GNU\n * General Public License as published by the Free Software\n * Foundation; either version 2 of the License, or (at your option)\n * any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n *\/\n\n# include \"architec.h\"\n# include \"entity.h\"\n# include \"expression.h\"\n# include \"sequential.h\"\n# include <typeinfo>\n# include <cassert>\n\nint Architecture::elaborate(Entity*entity)\n{\n int errors = 0;\n\n\t\/\/ Constant assignments in the architecture get their types\n\t\/\/ from the constant declaration itself. Elaborate the value\n\t\/\/ expression with the declared type.\n\n for (map<perm_string,struct const_t*>::iterator cur = use_constants_.begin()\n\t\t ; cur != use_constants_.end() ; ++cur) {\n\t cur->second->val->elaborate_expr(entity, this, cur->second->typ);\n }\n for (map<perm_string,struct const_t*>::iterator cur = cur_constants_.begin()\n\t\t ; cur != cur_constants_.end() ; ++cur) {\n\t cur->second->val->elaborate_expr(entity, this, cur->second->typ);\n }\n\n \/\/ Elaborate initializer expressions for signals & variables\n for (map<perm_string,Signal*>::iterator cur = old_signals_.begin()\n\t\t ; cur != old_signals_.end() ; ++cur) {\n\t cur->second->elaborate_init_expr(entity, this);\n }\n for (map<perm_string,Signal*>::iterator cur = new_signals_.begin()\n\t\t ; cur != new_signals_.end() ; ++cur) {\n\t cur->second->elaborate_init_expr(entity, this);\n }\n for (map<perm_string,Variable*>::iterator cur = old_variables_.begin()\n\t\t ; cur != old_variables_.end() ; ++cur) {\n\t cur->second->elaborate_init_expr(entity, this);\n }\n for (map<perm_string,Variable*>::iterator cur = new_variables_.begin()\n\t\t ; cur != new_variables_.end() ; ++cur) {\n\t cur->second->elaborate_init_expr(entity, this);\n }\n\n for (list<Architecture::Statement*>::iterator cur = statements_.begin()\n\t\t ; cur != statements_.end() ; ++cur) {\n\n\t int cur_errors = (*cur)->elaborate(entity, this);\n\t errors += cur_errors;\n }\n\n if (errors > 0) {\n\t cerr << errors << \" errors in \"\n\t\t << name_ << \" architecture of \"\n\t\t << entity->get_name() << \".\" << endl;\n }\n\n return errors;\n}\n\nint Architecture::Statement::elaborate(Entity*, Architecture*)\n{\n return 0;\n}\n\nint ComponentInstantiation::elaborate(Entity*ent, Architecture*arc)\n{\n int errors = 0;\n\n ComponentBase*base = arc->find_component(cname_);\n if (base == 0) {\n\t cerr << get_fileline() << \": error: No component declaration\"\n\t\t << \" for instance \" << iname_\n\t\t << \" of \" << cname_ << \".\" << endl;\n\t return 1;\n }\n\n for (map<perm_string,Expression*>::const_iterator cur = generic_map_.begin()\n\t\t ; cur != generic_map_.end() ; ++cur) {\n\t \/\/ check if generic from component instantiation\n\t \/\/ exists in the component declaration\n\t const InterfacePort*iparm = base->find_generic(cur->first);\n\t if (iparm == 0) {\n\t\t cerr << get_fileline() << \": warning: No generic \" << cur->first\n\t\t << \" in component \" << cname_ << \".\" << endl;\n\t\t continue;\n\t }\n\n\t ExpName* tmp;\n\t if (cur->second && (tmp = dynamic_cast<ExpName*>(cur->second)))\n\t\t errors += tmp->elaborate_rval(ent, arc, iparm);\n\n\t if (cur->second)\n\t\t errors += cur->second->elaborate_expr(ent, arc, iparm->type);\n }\n\n for (map<perm_string,Expression*>::const_iterator cur = port_map_.begin()\n\t\t ; cur != port_map_.end() ; ++cur) {\n\t \/\/ check if a port from component instantiation\n\t \/\/ exists in the component declaration\n\t const InterfacePort*iport = base->find_port(cur->first);\n\t if (iport == 0) {\n\t\t cerr << get_fileline() << \": error: No port \" << cur->first\n\t\t << \" in component \" << cname_ << \".\" << endl;\n\t\t errors += 1;\n\t\t continue;\n\t }\n\n\t ExpName* tmp;\n\t if (cur->second && (tmp = dynamic_cast<ExpName*>(cur->second)))\n\t\t errors += tmp->elaborate_rval(ent, arc, iport);\n\t \/* It is possible for the port to be explicitly\n\t\t unconnected. In that case, the Expression will be nil *\/\n\n\t if (cur->second)\n\t\t cur->second->elaborate_expr(ent, arc, iport->type);\n }\n\n return errors;\n}\n\nint GenerateStatement::elaborate_statements(Entity*ent, Architecture*arc)\n{\n int errors = 0;\n for (list<Architecture::Statement*>::iterator cur = statements_.begin()\n\t\t ; cur != statements_.end() ; ++cur) {\n\t Architecture::Statement*curp = *cur;\n\t errors += curp->elaborate(ent, arc);\n }\n return errors;\n}\n\nint ForGenerate::elaborate(Entity*ent, Architecture*arc)\n{\n int errors = 0;\n arc->push_genvar_type(genvar_, lsb_->probe_type(ent, arc));\n errors += elaborate_statements(ent, arc);\n arc->pop_genvar_type();\n return errors;\n}\n\nint IfGenerate::elaborate(Entity*ent, Architecture*arc)\n{\n int errors = 0;\n errors += elaborate_statements(ent, arc);\n return errors;\n}\n\n\/*\n * This method attempts to rewrite the process content as an\n * always-@(n-edge <expr>) version of the same statement. This makes\n * for a more natural translation to Verilog, if it comes to that.\n *\/\nint ProcessStatement::rewrite_as_always_edge_(Entity*, Architecture*)\n{\n\t\/\/ If there are multiple sensitivity expressions, I give up.\n if (sensitivity_list_.size() != 1)\n\t return -1;\n\n\t\/\/ If there are multiple statements, I give up.\n if (statements_list_.size() != 1)\n\t return -1;\n\n Expression*se = sensitivity_list_.front();\n SequentialStmt*stmt_raw = statements_list_.front();\n\n\t\/\/ If the statement is not an if-statement, I give up.\n IfSequential*stmt = dynamic_cast<IfSequential*> (stmt_raw);\n if (stmt == 0)\n\t return -1;\n\n\t\/\/ If the \"if\" statement has a false clause, then give up.\n if (stmt->false_size() != 0)\n\t return -1;\n\n const Expression*ce_raw = stmt->peek_condition();\n\t\/\/ Now we have matched this pattern:\n\t\/\/ process(<expr>) begin if <ce_raw>...\n\t\/\/ The <ce_raw> is the condition.\n\n if (const ExpFunc*ce_func = dynamic_cast<const ExpFunc*>(ce_raw)) {\n\t if (ce_func->func_args() != 1)\n\t\t return -1;\n\t if (ce_func->func_name()!=\"rising_edge\" && ce_func->func_name()!=\"falling_edge\")\n\t\t return -1;\n\n\t if (! se->symbolic_compare(ce_func->func_arg(0)))\n\t\treturn -1;\n\n\t \/\/ We've matched this pattern:\n\t \/\/ process(<se>) if (rising_edge(<se>)) then ...\n\t \/\/ and we can convert it to:\n\t \/\/ always @(posedge <se>) ...\n\n\t ExpEdge::fun_t use_edge;\n\t if (ce_func->func_name()==\"rising_edge\")\n\t\t use_edge = ExpEdge::POSEDGE;\n\t else if (ce_func->func_name()==\"falling_edge\")\n\t\t use_edge = ExpEdge::NEGEDGE;\n\t else\n\t\t use_edge = ExpEdge::ANYEDGE;\n\n\t \/\/ Replace the sensitivity expression with an edge\n\t \/\/ expression. The ExpEdge expression signals that this\n\t \/\/ is an always-@(edge) statement.\n\t ExpEdge*edge = new ExpEdge(use_edge, se);\n\t assert(sensitivity_list_.size() == 1);\n\t sensitivity_list_.pop_front();\n\t sensitivity_list_.push_front(edge);\n\n\t \/\/ Replace the statement with the body of the always\n\t \/\/ statement, which is the true clause of the top \"if\"\n\t \/\/ statement. There should be no \"else\" clause.\n\t assert(statements_list_.size() == 1);\n\t statements_list_.pop_front();\n\t stmt->extract_true(statements_list_);\n\n\t delete stmt;\n\t return 0;\n }\n\n\t\/\/ Here we expect the condition to be\n\t\/\/ <name>'event AND <name>='1'.\n\t\/\/ So if ce_raw is not a logical AND, I give up.\n const ExpLogical*ce = dynamic_cast<const ExpLogical*> (ce_raw);\n if (ce == 0)\n\t return -1;\n if (ce->logic_fun() != ExpLogical::AND)\n\t return -1;\n\n const Expression*op1_raw = ce->peek_operand1();\n const Expression*op2_raw = ce->peek_operand2();\n if (dynamic_cast<const ExpAttribute*>(op2_raw)) {\n\t const Expression*tmp = op1_raw;\n\t op1_raw = op2_raw;\n\t op2_raw = tmp;\n }\n\n\t\/\/ If operand1 is not an 'event attribute, I give up.\n const ExpAttribute*op1 = dynamic_cast<const ExpAttribute*>(op1_raw);\n if (op1 == 0)\n\t return -1;\n if (op1->peek_attribute() != \"event\")\n\t return -1;\n\n const ExpRelation*op2 = dynamic_cast<const ExpRelation*>(op2_raw);\n if (op2 == 0)\n\t return -1;\n if (op2->relation_fun() != ExpRelation::EQ)\n\t return -1;\n\n const Expression*op2a_raw = op2->peek_operand1();\n const Expression*op2b_raw = op2->peek_operand2();\n\n if (dynamic_cast<const ExpCharacter*>(op2a_raw)) {\n\t const Expression*tmp = op2b_raw;\n\t op2b_raw = op2a_raw;\n\t op2a_raw = tmp;\n }\n\n if (! se->symbolic_compare(op1->peek_base()))\n\t return -1;\n\n const ExpCharacter*op2b = dynamic_cast<const ExpCharacter*>(op2b_raw);\n if (op2b->value() != '1' && op2b->value() != '0')\n\t return -1;\n\n\t\/\/ We've matched this pattern:\n\t\/\/ process (<se>) if (<se>'event and <se> = <op2b>) then ...\n\t\/\/ And we can convert it to:\n\t\/\/ always @(<N>edge <se>) ...\n\n\t\/\/ Replace the sensitivity expression with an edge\n\t\/\/ expression. The ExpEdge expression signals that this is an\n\t\/\/ always-@(edge) statement.\n ExpEdge*edge = new ExpEdge(op2b->value()=='1'? ExpEdge::POSEDGE : ExpEdge::NEGEDGE, se);\n assert(sensitivity_list_.size() == 1);\n sensitivity_list_.pop_front();\n sensitivity_list_.push_front(edge);\n\n\t\/\/ Replace the statement with the body of the always\n\t\/\/ statement, which is the true clause of the top \"if\"\n\t\/\/ statement. There should be no \"else\" clause.\n assert(statements_list_.size() == 1);\n statements_list_.pop_front();\n\n stmt->extract_true(statements_list_);\n\n delete stmt;\n\n return 0;\n}\n\n\/*\n * Change the \"process (<expr>) <stmt>\" into \"always @(<expr>) ...\"\n *\/\nint ProcessStatement::extract_anyedge_(Entity*, Architecture*)\n{\n\n vector<Expression*> se;\n while (! sensitivity_list_.empty()) {\n\t se.push_back(sensitivity_list_.front());\n\t sensitivity_list_.pop_front();\n }\n\n for (size_t idx = 0 ; idx < se.size() ; idx += 1) {\n\t ExpEdge*edge = new ExpEdge(ExpEdge::ANYEDGE, se[idx]);\n\t FILE_NAME(edge, se[idx]);\n\t sensitivity_list_.push_back(edge);\n }\n\n return 0;\n}\n\nint ProcessStatement::elaborate(Entity*ent, Architecture*arc)\n{\n int errors = 0;\n\n if (rewrite_as_always_edge_(ent, arc) >= 0) {\n\n } else if (extract_anyedge_(ent, arc) >= 0) {\n\n } else {\n }\n\n for (list<SequentialStmt*>::iterator cur = statements_list_.begin()\n\t\t ; cur != statements_list_.end() ; ++cur) {\n\t errors += (*cur)->elaborate(ent, arc);\n }\n\n return errors;\n}\n\nint SignalAssignment::elaborate(Entity*ent, Architecture*arc)\n{\n int errors = 0;\n\n\t\/\/ Elaborate the l-value expression.\n errors += lval_->elaborate_lval(ent, arc, false);\n\n\t\/\/ The elaborate_lval should have resolved the type of the\n\t\/\/ l-value expression. We'll use that type to elaborate the\n\t\/\/ r-value.\n const VType*lval_type = lval_->peek_type();\n if (lval_type == 0) {\n\t if (errors == 0) {\n\t\t errors += 1;\n\t\t cerr << get_fileline() << \": error: Unable to calculate type for l-value expression.\" << endl;\n\t }\n\t return errors;\n }\n\n for (list<Expression*>::iterator cur = rval_.begin()\n\t\t ; cur != rval_.end() ; ++cur) {\n\t (*cur)->elaborate_expr(ent, arc, lval_type);\n\n \/\/ Handle functions that return unbounded arrays\n }\n\n return errors;\n}\n<commit_msg>vhdlpp: Unnecessary comment.<commit_after>\/*\n * Copyright (c) 2011-2012 Stephen Williams (steve@icarus.com)\n *\n * This source code is free software; you can redistribute it\n * and\/or modify it in source code form under the terms of the GNU\n * General Public License as published by the Free Software\n * Foundation; either version 2 of the License, or (at your option)\n * any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n *\/\n\n# include \"architec.h\"\n# include \"entity.h\"\n# include \"expression.h\"\n# include \"sequential.h\"\n# include <typeinfo>\n# include <cassert>\n\nint Architecture::elaborate(Entity*entity)\n{\n int errors = 0;\n\n\t\/\/ Constant assignments in the architecture get their types\n\t\/\/ from the constant declaration itself. Elaborate the value\n\t\/\/ expression with the declared type.\n\n for (map<perm_string,struct const_t*>::iterator cur = use_constants_.begin()\n\t\t ; cur != use_constants_.end() ; ++cur) {\n\t cur->second->val->elaborate_expr(entity, this, cur->second->typ);\n }\n for (map<perm_string,struct const_t*>::iterator cur = cur_constants_.begin()\n\t\t ; cur != cur_constants_.end() ; ++cur) {\n\t cur->second->val->elaborate_expr(entity, this, cur->second->typ);\n }\n\n \/\/ Elaborate initializer expressions for signals & variables\n for (map<perm_string,Signal*>::iterator cur = old_signals_.begin()\n\t\t ; cur != old_signals_.end() ; ++cur) {\n\t cur->second->elaborate_init_expr(entity, this);\n }\n for (map<perm_string,Signal*>::iterator cur = new_signals_.begin()\n\t\t ; cur != new_signals_.end() ; ++cur) {\n\t cur->second->elaborate_init_expr(entity, this);\n }\n for (map<perm_string,Variable*>::iterator cur = old_variables_.begin()\n\t\t ; cur != old_variables_.end() ; ++cur) {\n\t cur->second->elaborate_init_expr(entity, this);\n }\n for (map<perm_string,Variable*>::iterator cur = new_variables_.begin()\n\t\t ; cur != new_variables_.end() ; ++cur) {\n\t cur->second->elaborate_init_expr(entity, this);\n }\n\n for (list<Architecture::Statement*>::iterator cur = statements_.begin()\n\t\t ; cur != statements_.end() ; ++cur) {\n\n\t int cur_errors = (*cur)->elaborate(entity, this);\n\t errors += cur_errors;\n }\n\n if (errors > 0) {\n\t cerr << errors << \" errors in \"\n\t\t << name_ << \" architecture of \"\n\t\t << entity->get_name() << \".\" << endl;\n }\n\n return errors;\n}\n\nint Architecture::Statement::elaborate(Entity*, Architecture*)\n{\n return 0;\n}\n\nint ComponentInstantiation::elaborate(Entity*ent, Architecture*arc)\n{\n int errors = 0;\n\n ComponentBase*base = arc->find_component(cname_);\n if (base == 0) {\n\t cerr << get_fileline() << \": error: No component declaration\"\n\t\t << \" for instance \" << iname_\n\t\t << \" of \" << cname_ << \".\" << endl;\n\t return 1;\n }\n\n for (map<perm_string,Expression*>::const_iterator cur = generic_map_.begin()\n\t\t ; cur != generic_map_.end() ; ++cur) {\n\t \/\/ check if generic from component instantiation\n\t \/\/ exists in the component declaration\n\t const InterfacePort*iparm = base->find_generic(cur->first);\n\t if (iparm == 0) {\n\t\t cerr << get_fileline() << \": warning: No generic \" << cur->first\n\t\t << \" in component \" << cname_ << \".\" << endl;\n\t\t continue;\n\t }\n\n\t ExpName* tmp;\n\t if (cur->second && (tmp = dynamic_cast<ExpName*>(cur->second)))\n\t\t errors += tmp->elaborate_rval(ent, arc, iparm);\n\n\t if (cur->second)\n\t\t errors += cur->second->elaborate_expr(ent, arc, iparm->type);\n }\n\n for (map<perm_string,Expression*>::const_iterator cur = port_map_.begin()\n\t\t ; cur != port_map_.end() ; ++cur) {\n\t \/\/ check if a port from component instantiation\n\t \/\/ exists in the component declaration\n\t const InterfacePort*iport = base->find_port(cur->first);\n\t if (iport == 0) {\n\t\t cerr << get_fileline() << \": error: No port \" << cur->first\n\t\t << \" in component \" << cname_ << \".\" << endl;\n\t\t errors += 1;\n\t\t continue;\n\t }\n\n\t ExpName* tmp;\n\t if (cur->second && (tmp = dynamic_cast<ExpName*>(cur->second)))\n\t\t errors += tmp->elaborate_rval(ent, arc, iport);\n\t \/* It is possible for the port to be explicitly\n\t\t unconnected. In that case, the Expression will be nil *\/\n\n\t if (cur->second)\n\t\t cur->second->elaborate_expr(ent, arc, iport->type);\n }\n\n return errors;\n}\n\nint GenerateStatement::elaborate_statements(Entity*ent, Architecture*arc)\n{\n int errors = 0;\n for (list<Architecture::Statement*>::iterator cur = statements_.begin()\n\t\t ; cur != statements_.end() ; ++cur) {\n\t Architecture::Statement*curp = *cur;\n\t errors += curp->elaborate(ent, arc);\n }\n return errors;\n}\n\nint ForGenerate::elaborate(Entity*ent, Architecture*arc)\n{\n int errors = 0;\n arc->push_genvar_type(genvar_, lsb_->probe_type(ent, arc));\n errors += elaborate_statements(ent, arc);\n arc->pop_genvar_type();\n return errors;\n}\n\nint IfGenerate::elaborate(Entity*ent, Architecture*arc)\n{\n int errors = 0;\n errors += elaborate_statements(ent, arc);\n return errors;\n}\n\n\/*\n * This method attempts to rewrite the process content as an\n * always-@(n-edge <expr>) version of the same statement. This makes\n * for a more natural translation to Verilog, if it comes to that.\n *\/\nint ProcessStatement::rewrite_as_always_edge_(Entity*, Architecture*)\n{\n\t\/\/ If there are multiple sensitivity expressions, I give up.\n if (sensitivity_list_.size() != 1)\n\t return -1;\n\n\t\/\/ If there are multiple statements, I give up.\n if (statements_list_.size() != 1)\n\t return -1;\n\n Expression*se = sensitivity_list_.front();\n SequentialStmt*stmt_raw = statements_list_.front();\n\n\t\/\/ If the statement is not an if-statement, I give up.\n IfSequential*stmt = dynamic_cast<IfSequential*> (stmt_raw);\n if (stmt == 0)\n\t return -1;\n\n\t\/\/ If the \"if\" statement has a false clause, then give up.\n if (stmt->false_size() != 0)\n\t return -1;\n\n const Expression*ce_raw = stmt->peek_condition();\n\t\/\/ Now we have matched this pattern:\n\t\/\/ process(<expr>) begin if <ce_raw>...\n\t\/\/ The <ce_raw> is the condition.\n\n if (const ExpFunc*ce_func = dynamic_cast<const ExpFunc*>(ce_raw)) {\n\t if (ce_func->func_args() != 1)\n\t\t return -1;\n\t if (ce_func->func_name()!=\"rising_edge\" && ce_func->func_name()!=\"falling_edge\")\n\t\t return -1;\n\n\t if (! se->symbolic_compare(ce_func->func_arg(0)))\n\t\treturn -1;\n\n\t \/\/ We've matched this pattern:\n\t \/\/ process(<se>) if (rising_edge(<se>)) then ...\n\t \/\/ and we can convert it to:\n\t \/\/ always @(posedge <se>) ...\n\n\t ExpEdge::fun_t use_edge;\n\t if (ce_func->func_name()==\"rising_edge\")\n\t\t use_edge = ExpEdge::POSEDGE;\n\t else if (ce_func->func_name()==\"falling_edge\")\n\t\t use_edge = ExpEdge::NEGEDGE;\n\t else\n\t\t use_edge = ExpEdge::ANYEDGE;\n\n\t \/\/ Replace the sensitivity expression with an edge\n\t \/\/ expression. The ExpEdge expression signals that this\n\t \/\/ is an always-@(edge) statement.\n\t ExpEdge*edge = new ExpEdge(use_edge, se);\n\t assert(sensitivity_list_.size() == 1);\n\t sensitivity_list_.pop_front();\n\t sensitivity_list_.push_front(edge);\n\n\t \/\/ Replace the statement with the body of the always\n\t \/\/ statement, which is the true clause of the top \"if\"\n\t \/\/ statement. There should be no \"else\" clause.\n\t assert(statements_list_.size() == 1);\n\t statements_list_.pop_front();\n\t stmt->extract_true(statements_list_);\n\n\t delete stmt;\n\t return 0;\n }\n\n\t\/\/ Here we expect the condition to be\n\t\/\/ <name>'event AND <name>='1'.\n\t\/\/ So if ce_raw is not a logical AND, I give up.\n const ExpLogical*ce = dynamic_cast<const ExpLogical*> (ce_raw);\n if (ce == 0)\n\t return -1;\n if (ce->logic_fun() != ExpLogical::AND)\n\t return -1;\n\n const Expression*op1_raw = ce->peek_operand1();\n const Expression*op2_raw = ce->peek_operand2();\n if (dynamic_cast<const ExpAttribute*>(op2_raw)) {\n\t const Expression*tmp = op1_raw;\n\t op1_raw = op2_raw;\n\t op2_raw = tmp;\n }\n\n\t\/\/ If operand1 is not an 'event attribute, I give up.\n const ExpAttribute*op1 = dynamic_cast<const ExpAttribute*>(op1_raw);\n if (op1 == 0)\n\t return -1;\n if (op1->peek_attribute() != \"event\")\n\t return -1;\n\n const ExpRelation*op2 = dynamic_cast<const ExpRelation*>(op2_raw);\n if (op2 == 0)\n\t return -1;\n if (op2->relation_fun() != ExpRelation::EQ)\n\t return -1;\n\n const Expression*op2a_raw = op2->peek_operand1();\n const Expression*op2b_raw = op2->peek_operand2();\n\n if (dynamic_cast<const ExpCharacter*>(op2a_raw)) {\n\t const Expression*tmp = op2b_raw;\n\t op2b_raw = op2a_raw;\n\t op2a_raw = tmp;\n }\n\n if (! se->symbolic_compare(op1->peek_base()))\n\t return -1;\n\n const ExpCharacter*op2b = dynamic_cast<const ExpCharacter*>(op2b_raw);\n if (op2b->value() != '1' && op2b->value() != '0')\n\t return -1;\n\n\t\/\/ We've matched this pattern:\n\t\/\/ process (<se>) if (<se>'event and <se> = <op2b>) then ...\n\t\/\/ And we can convert it to:\n\t\/\/ always @(<N>edge <se>) ...\n\n\t\/\/ Replace the sensitivity expression with an edge\n\t\/\/ expression. The ExpEdge expression signals that this is an\n\t\/\/ always-@(edge) statement.\n ExpEdge*edge = new ExpEdge(op2b->value()=='1'? ExpEdge::POSEDGE : ExpEdge::NEGEDGE, se);\n assert(sensitivity_list_.size() == 1);\n sensitivity_list_.pop_front();\n sensitivity_list_.push_front(edge);\n\n\t\/\/ Replace the statement with the body of the always\n\t\/\/ statement, which is the true clause of the top \"if\"\n\t\/\/ statement. There should be no \"else\" clause.\n assert(statements_list_.size() == 1);\n statements_list_.pop_front();\n\n stmt->extract_true(statements_list_);\n\n delete stmt;\n\n return 0;\n}\n\n\/*\n * Change the \"process (<expr>) <stmt>\" into \"always @(<expr>) ...\"\n *\/\nint ProcessStatement::extract_anyedge_(Entity*, Architecture*)\n{\n\n vector<Expression*> se;\n while (! sensitivity_list_.empty()) {\n\t se.push_back(sensitivity_list_.front());\n\t sensitivity_list_.pop_front();\n }\n\n for (size_t idx = 0 ; idx < se.size() ; idx += 1) {\n\t ExpEdge*edge = new ExpEdge(ExpEdge::ANYEDGE, se[idx]);\n\t FILE_NAME(edge, se[idx]);\n\t sensitivity_list_.push_back(edge);\n }\n\n return 0;\n}\n\nint ProcessStatement::elaborate(Entity*ent, Architecture*arc)\n{\n int errors = 0;\n\n if (rewrite_as_always_edge_(ent, arc) >= 0) {\n\n } else if (extract_anyedge_(ent, arc) >= 0) {\n\n } else {\n }\n\n for (list<SequentialStmt*>::iterator cur = statements_list_.begin()\n\t\t ; cur != statements_list_.end() ; ++cur) {\n\t errors += (*cur)->elaborate(ent, arc);\n }\n\n return errors;\n}\n\nint SignalAssignment::elaborate(Entity*ent, Architecture*arc)\n{\n int errors = 0;\n\n\t\/\/ Elaborate the l-value expression.\n errors += lval_->elaborate_lval(ent, arc, false);\n\n\t\/\/ The elaborate_lval should have resolved the type of the\n\t\/\/ l-value expression. We'll use that type to elaborate the\n\t\/\/ r-value.\n const VType*lval_type = lval_->peek_type();\n if (lval_type == 0) {\n\t if (errors == 0) {\n\t\t errors += 1;\n\t\t cerr << get_fileline() << \": error: Unable to calculate type for l-value expression.\" << endl;\n\t }\n\t return errors;\n }\n\n for (list<Expression*>::iterator cur = rval_.begin()\n\t\t ; cur != rval_.end() ; ++cur) {\n\t (*cur)->elaborate_expr(ent, arc, lval_type);\n }\n\n return errors;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Scintilla source code edit control\n\/** @file Style.cxx\n ** Defines the font and colour style for a class of text.\n **\/\n\/\/ Copyright 1998-2001 by Neil Hodgson <neilh@scintilla.org>\n\/\/ The License.txt file describes the conditions under which this software may be distributed.\n\n#include <string.h>\n\n#include \"Platform.h\"\n\n#include \"Scintilla.h\"\n#include \"Style.h\"\n\n#ifdef SCI_NAMESPACE\nusing namespace Scintilla;\n#endif\n\nFontAlias::FontAlias() {\n}\n\nFontAlias::FontAlias(const FontAlias &other) {\n\tSetID(other.fid);\n}\n\nFontAlias::~FontAlias() {\n\tSetID(0);\n\t\/\/ ~Font will not release the actual font resource since it is now 0\n}\n\nvoid FontAlias::MakeAlias(Font &fontOrigin) {\n\tSetID(fontOrigin.GetID());\n}\n\nvoid FontAlias::ClearFont() {\n\tSetID(0);\n}\n\nbool FontSpecification::operator==(const FontSpecification &other) const {\n\treturn fontName == other.fontName &&\n\t weight == other.weight &&\n\t italic == other.italic &&\n\t size == other.size &&\n\t characterSet == other.characterSet &&\n\t extraFontFlag == other.extraFontFlag;\n}\n\nbool FontSpecification::operator<(const FontSpecification &other) const {\n\tif (fontName != other.fontName)\n\t\treturn fontName < other.fontName;\n\tif (weight != other.weight)\n\t\treturn weight < other.weight;\n\tif (italic != other.italic)\n\t\treturn italic == false;\n\tif (size != other.size)\n\t\treturn size < other.size;\n\tif (characterSet != other.characterSet)\n\t\treturn characterSet < other.characterSet;\n\tif (extraFontFlag != other.extraFontFlag)\n\t\treturn extraFontFlag < other.extraFontFlag;\n\treturn false;\n}\n\nFontMeasurements::FontMeasurements() {\n\tClear();\n}\n\nvoid FontMeasurements::Clear() {\n\tascent = 1;\n\tdescent = 1;\n\taveCharWidth = 1;\n\tspaceWidth = 1;\n\tsizeZoomed = 2;\n}\n\nStyle::Style() : FontSpecification() {\n\tClear(ColourDesired(0, 0, 0), ColourDesired(0xff, 0xff, 0xff),\n\t Platform::DefaultFontSize() * SC_FONT_SIZE_MULTIPLIER, 0, SC_CHARSET_DEFAULT,\n\t SC_WEIGHT_NORMAL, false, false, false, caseMixed, true, true, false);\n}\n\nStyle::Style(const Style &source) : FontSpecification(), FontMeasurements() {\n\tClear(ColourDesired(0, 0, 0), ColourDesired(0xff, 0xff, 0xff),\n\t 0, 0, 0,\n\t SC_WEIGHT_NORMAL, false, false, false, caseMixed, true, true, false);\n\tfore = source.fore;\n\tback = source.back;\n\tcharacterSet = source.characterSet;\n\tweight = source.weight;\n\titalic = source.italic;\n\tsize = source.size;\n\tfontName = source.fontName;\n\teolFilled = source.eolFilled;\n\tunderline = source.underline;\n\tcaseForce = source.caseForce;\n\tvisible = source.visible;\n\tchangeable = source.changeable;\n\thotspot = source.hotspot;\n}\n\nStyle::~Style() {\n}\n\nStyle &Style::operator=(const Style &source) {\n\tif (this == &source)\n\t\treturn * this;\n\tClear(ColourDesired(0, 0, 0), ColourDesired(0xff, 0xff, 0xff),\n\t 0, 0, SC_CHARSET_DEFAULT,\n\t SC_WEIGHT_NORMAL, false, false, false, caseMixed, true, true, false);\n\tfore = source.fore;\n\tback = source.back;\n\tcharacterSet = source.characterSet;\n\tweight = source.weight;\n\titalic = source.italic;\n\tsize = source.size;\n\tfontName = source.fontName;\n\teolFilled = source.eolFilled;\n\tunderline = source.underline;\n\tcaseForce = source.caseForce;\n\tvisible = source.visible;\n\tchangeable = source.changeable;\n\treturn *this;\n}\n\nvoid Style::Clear(ColourDesired fore_, ColourDesired back_, int size_,\n const char *fontName_, int characterSet_,\n int weight_, bool italic_, bool eolFilled_,\n bool underline_, ecaseForced caseForce_,\n bool visible_, bool changeable_, bool hotspot_) {\n\tfore = fore_;\n\tback = back_;\n\tcharacterSet = characterSet_;\n\tweight = weight_;\n\titalic = italic_;\n\tsize = size_;\n\tfontName = fontName_;\n\teolFilled = eolFilled_;\n\tunderline = underline_;\n\tcaseForce = caseForce_;\n\tvisible = visible_;\n\tchangeable = changeable_;\n\thotspot = hotspot_;\n\tfont.ClearFont();\n\tFontMeasurements::Clear();\n}\n\nvoid Style::ClearTo(const Style &source) {\n\tClear(\n\t source.fore,\n\t source.back,\n\t source.size,\n\t source.fontName,\n\t source.characterSet,\n\t source.weight,\n\t source.italic,\n\t source.eolFilled,\n\t source.underline,\n\t source.caseForce,\n\t source.visible,\n\t source.changeable,\n\t source.hotspot);\n}\n\nvoid Style::Copy(Font &font_, const FontMeasurements &fm_) {\n\tfont.MakeAlias(font_);\n#if PLAT_WX\n\tfont.SetAscent(fm_.ascent);\n#endif\n\t(FontMeasurements &)(*this) = fm_;\n}\n<commit_msg>Avoid warning from g++.<commit_after>\/\/ Scintilla source code edit control\n\/** @file Style.cxx\n ** Defines the font and colour style for a class of text.\n **\/\n\/\/ Copyright 1998-2001 by Neil Hodgson <neilh@scintilla.org>\n\/\/ The License.txt file describes the conditions under which this software may be distributed.\n\n#include <string.h>\n\n#include \"Platform.h\"\n\n#include \"Scintilla.h\"\n#include \"Style.h\"\n\n#ifdef SCI_NAMESPACE\nusing namespace Scintilla;\n#endif\n\nFontAlias::FontAlias() {\n}\n\nFontAlias::FontAlias(const FontAlias &other) : Font() {\n\tSetID(other.fid);\n}\n\nFontAlias::~FontAlias() {\n\tSetID(0);\n\t\/\/ ~Font will not release the actual font resource since it is now 0\n}\n\nvoid FontAlias::MakeAlias(Font &fontOrigin) {\n\tSetID(fontOrigin.GetID());\n}\n\nvoid FontAlias::ClearFont() {\n\tSetID(0);\n}\n\nbool FontSpecification::operator==(const FontSpecification &other) const {\n\treturn fontName == other.fontName &&\n\t weight == other.weight &&\n\t italic == other.italic &&\n\t size == other.size &&\n\t characterSet == other.characterSet &&\n\t extraFontFlag == other.extraFontFlag;\n}\n\nbool FontSpecification::operator<(const FontSpecification &other) const {\n\tif (fontName != other.fontName)\n\t\treturn fontName < other.fontName;\n\tif (weight != other.weight)\n\t\treturn weight < other.weight;\n\tif (italic != other.italic)\n\t\treturn italic == false;\n\tif (size != other.size)\n\t\treturn size < other.size;\n\tif (characterSet != other.characterSet)\n\t\treturn characterSet < other.characterSet;\n\tif (extraFontFlag != other.extraFontFlag)\n\t\treturn extraFontFlag < other.extraFontFlag;\n\treturn false;\n}\n\nFontMeasurements::FontMeasurements() {\n\tClear();\n}\n\nvoid FontMeasurements::Clear() {\n\tascent = 1;\n\tdescent = 1;\n\taveCharWidth = 1;\n\tspaceWidth = 1;\n\tsizeZoomed = 2;\n}\n\nStyle::Style() : FontSpecification() {\n\tClear(ColourDesired(0, 0, 0), ColourDesired(0xff, 0xff, 0xff),\n\t Platform::DefaultFontSize() * SC_FONT_SIZE_MULTIPLIER, 0, SC_CHARSET_DEFAULT,\n\t SC_WEIGHT_NORMAL, false, false, false, caseMixed, true, true, false);\n}\n\nStyle::Style(const Style &source) : FontSpecification(), FontMeasurements() {\n\tClear(ColourDesired(0, 0, 0), ColourDesired(0xff, 0xff, 0xff),\n\t 0, 0, 0,\n\t SC_WEIGHT_NORMAL, false, false, false, caseMixed, true, true, false);\n\tfore = source.fore;\n\tback = source.back;\n\tcharacterSet = source.characterSet;\n\tweight = source.weight;\n\titalic = source.italic;\n\tsize = source.size;\n\tfontName = source.fontName;\n\teolFilled = source.eolFilled;\n\tunderline = source.underline;\n\tcaseForce = source.caseForce;\n\tvisible = source.visible;\n\tchangeable = source.changeable;\n\thotspot = source.hotspot;\n}\n\nStyle::~Style() {\n}\n\nStyle &Style::operator=(const Style &source) {\n\tif (this == &source)\n\t\treturn * this;\n\tClear(ColourDesired(0, 0, 0), ColourDesired(0xff, 0xff, 0xff),\n\t 0, 0, SC_CHARSET_DEFAULT,\n\t SC_WEIGHT_NORMAL, false, false, false, caseMixed, true, true, false);\n\tfore = source.fore;\n\tback = source.back;\n\tcharacterSet = source.characterSet;\n\tweight = source.weight;\n\titalic = source.italic;\n\tsize = source.size;\n\tfontName = source.fontName;\n\teolFilled = source.eolFilled;\n\tunderline = source.underline;\n\tcaseForce = source.caseForce;\n\tvisible = source.visible;\n\tchangeable = source.changeable;\n\treturn *this;\n}\n\nvoid Style::Clear(ColourDesired fore_, ColourDesired back_, int size_,\n const char *fontName_, int characterSet_,\n int weight_, bool italic_, bool eolFilled_,\n bool underline_, ecaseForced caseForce_,\n bool visible_, bool changeable_, bool hotspot_) {\n\tfore = fore_;\n\tback = back_;\n\tcharacterSet = characterSet_;\n\tweight = weight_;\n\titalic = italic_;\n\tsize = size_;\n\tfontName = fontName_;\n\teolFilled = eolFilled_;\n\tunderline = underline_;\n\tcaseForce = caseForce_;\n\tvisible = visible_;\n\tchangeable = changeable_;\n\thotspot = hotspot_;\n\tfont.ClearFont();\n\tFontMeasurements::Clear();\n}\n\nvoid Style::ClearTo(const Style &source) {\n\tClear(\n\t source.fore,\n\t source.back,\n\t source.size,\n\t source.fontName,\n\t source.characterSet,\n\t source.weight,\n\t source.italic,\n\t source.eolFilled,\n\t source.underline,\n\t source.caseForce,\n\t source.visible,\n\t source.changeable,\n\t source.hotspot);\n}\n\nvoid Style::Copy(Font &font_, const FontMeasurements &fm_) {\n\tfont.MakeAlias(font_);\n#if PLAT_WX\n\tfont.SetAscent(fm_.ascent);\n#endif\n\t(FontMeasurements &)(*this) = fm_;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"ffmpegdecoder.h\"\n#include \"makeguard.h\"\n#include \"interlockedadd.h\"\n\n#include <boost\/log\/trivial.hpp>\n\n#include <functional>\n#include <memory>\n#include <tuple>\n\n\nnamespace {\n\nuint8_t** getAudioData(AVFrame* audioFrame)\n{\n return audioFrame->extended_data != nullptr\n ? audioFrame->extended_data\n : &audioFrame->data[0];\n}\n\nint64_t getChannelLayout(AVFrame* audioFrame)\n{\n\tconst int audioFrameChannels = audioFrame->channels; \/\/av_frame_get_channels(audioFrame);\n return ((audioFrame->channel_layout != 0u) &&\n audioFrameChannels == av_get_channel_layout_nb_channels(audioFrame->channel_layout))\n ? audioFrame->channel_layout\n : av_get_default_channel_layout(audioFrameChannels);\n}\n\n} \/\/ namespace\n\n\nvoid FFmpegDecoder::audioParseRunnable()\n{\n CHANNEL_LOG(ffmpeg_threads) << \"Audio thread started\";\n AVPacket packet;\n\n bool initialized = false;\n bool failed = false;\n\n m_audioPlayer->InitializeThread();\n auto deinitializeThread = MakeGuard(\n m_audioPlayer.get(),\n std::mem_fn(&IAudioPlayer::DeinitializeThread));\n\n std::vector<uint8_t> resampleBuffer;\n\n double scheduledEndTime = 0;\n\n auto useHandleAudioResultLam = [this, &failed](bool result)\n {\n if (result)\n {\n if (failed)\n {\n failed = false;\n boost::lock_guard<boost::mutex> locker(m_isPausedMutex);\n if (m_videoStartClock != VIDEO_START_CLOCK_NOT_INITIALIZED)\n {\n m_audioPTS = (m_isPaused ? m_pauseTimer : GetHiResTime()) - m_videoStartClock;\n }\n }\n }\n else\n {\n failed = true;\n }\n };\n\n while (!boost::this_thread::interruption_requested())\n {\n if (!m_audioPacketsQueue.pop(packet))\n {\n break;\n }\n\n auto packetGuard = MakeGuard(&packet, av_packet_unref);\n\n if (m_audioStreamNumber != packet.stream_index)\n {\n continue;\n }\n\n if (!initialized)\n {\n if (packet.pts == AV_NOPTS_VALUE)\n {\n if (packet.data == nullptr)\n continue;\n\n assert(false && \"No audio pts found\");\n return;\n }\n const double pts = av_q2d(m_audioStream->time_base) * packet.pts;\n m_audioPTS = pts;\n scheduledEndTime = pts;\n \/\/ invoke changedFramePosition() if needed\n \/\/AppendFrameClock(0);\n }\n else if (packet.pts != AV_NOPTS_VALUE)\n {\n const double diff = av_q2d(m_audioStream->time_base) * packet.pts - scheduledEndTime;\n if (diff > 0.01)\n {\n CHANNEL_LOG(ffmpeg_sync) << \"Patching audio frame diff: \" << diff;\n if (m_formatContexts.size() == 1 && m_videoStartClock != VIDEO_START_CLOCK_NOT_INITIALIZED)\n {\n InterlockedAdd(m_videoStartClock, -diff);\n InterlockedAdd(m_audioPTS, diff);\n }\n else\n {\n const int size_multiplier = m_audioSettings.channels *\n av_get_bytes_per_sample(m_audioSettings.format);\n\n const int numSteps = (diff + 0.1) \/ 0.1;\n const auto frame_clock = diff \/ numSteps;\n for (int i = 0; i < numSteps; ++i)\n {\n const auto speed = getSpeedRational();\n const int nb_samples = frame_clock * m_audioSettings.frequency * speed.denominator \/ speed.numerator;\n const auto write_size = nb_samples * size_multiplier;\n std::vector<uint8_t> buf(write_size, 0);\n useHandleAudioResultLam(handleAudioFrame(frame_clock, buf.data(), write_size, failed));\n }\n }\n }\n\n scheduledEndTime += diff;\n }\n\n initialized = true;\n\n useHandleAudioResultLam(handleAudioPacket(packet, resampleBuffer, failed, scheduledEndTime));\n }\n}\n\nbool FFmpegDecoder::handleAudioPacket(\n const AVPacket& packet,\n std::vector<uint8_t>& resampleBuffer,\n bool failed, double& scheduledEndTime)\n{\n if (packet.stream_index != m_audioStream->index)\n {\n avcodec_close(m_audioCodecContext);\n m_audioStream = m_formatContexts[m_audioContextIndex]->streams[packet.stream_index];\n if (!setupAudioCodec())\n {\n return false;\n }\n }\n\n const int ret = avcodec_send_packet(m_audioCodecContext, &packet);\n if (ret < 0) {\n return ret == AVERROR(EAGAIN) || ret == AVERROR_EOF;\n }\n\n AVFramePtr audioFrame(av_frame_alloc());\n bool result = true;\n while (avcodec_receive_frame(m_audioCodecContext, audioFrame.get()) == 0)\n {\n if (audioFrame->nb_samples <= 0)\n {\n continue;\n }\n\n const int original_buffer_size = av_samples_get_buffer_size(\n nullptr, audioFrame->channels,\n audioFrame->nb_samples,\n static_cast<AVSampleFormat>(audioFrame->format), 1);\n\n \/\/ write buffer\n uint8_t* write_data = *getAudioData(audioFrame.get());\n int64_t write_size = original_buffer_size;\n\n setupAudioSwrContext(audioFrame.get());\n\n if (m_audioSwrContext != nullptr)\n {\n enum { EXTRA_SPACE = 256 };\n\n const int out_count = static_cast<int64_t>(audioFrame->nb_samples) *\n m_audioSettings.frequency \/\n m_audioCurrentPref.frequency + EXTRA_SPACE;\n\n const int size_multiplier = m_audioSettings.channels *\n av_get_bytes_per_sample(m_audioSettings.format);\n\n const size_t buffer_size = out_count * size_multiplier;\n\n if (resampleBuffer.size() < buffer_size)\n {\n resampleBuffer.resize(buffer_size);\n }\n\n \/\/ Code for resampling\n uint8_t *out = resampleBuffer.data();\n const int converted_size = swr_convert(\n m_audioSwrContext, \n &out,\n out_count,\n const_cast<const uint8_t**>(getAudioData(audioFrame.get())),\n audioFrame->nb_samples);\n\n if (converted_size < 0)\n {\n BOOST_LOG_TRIVIAL(error) << \"swr_convert() failed\";\n break;\n }\n\n if (converted_size == out_count)\n {\n BOOST_LOG_TRIVIAL(warning) << \"audio buffer is probably too small\";\n swr_init(m_audioSwrContext);\n }\n\n write_data = out;\n write_size = converted_size * size_multiplier;\n\n assert(write_size < buffer_size);\n }\n\n const double frame_clock \n = audioFrame->sample_rate != 0? double(audioFrame->nb_samples) \/ audioFrame->sample_rate : 0;\n\n scheduledEndTime += frame_clock;\n\n if (!handleAudioFrame(frame_clock, write_data, write_size, failed))\n {\n result = false;\n }\n }\n\n return result;\n}\n\nvoid FFmpegDecoder::setupAudioSwrContext(AVFrame* audioFrame)\n{\n const auto audioFrameFormat = static_cast<AVSampleFormat>(audioFrame->format);\n const int audioFrameChannels = audioFrame->channels;\n\n const int64_t dec_channel_layout = getChannelLayout(audioFrame);\n\n const auto speed = getSpeedRational();\n\n \/\/ Check if the new swr context required\n if (audioFrameFormat != m_audioCurrentPref.format ||\n dec_channel_layout != m_audioCurrentPref.channel_layout ||\n (audioFrame->sample_rate * speed.numerator) \/ speed.denominator != m_audioCurrentPref.frequency)\n {\n swr_free(&m_audioSwrContext);\n m_audioSwrContext = swr_alloc_set_opts(\n nullptr, m_audioSettings.channel_layout, m_audioSettings.format,\n m_audioSettings.frequency * speed.denominator,\n dec_channel_layout, audioFrameFormat,\n audioFrame->sample_rate * speed.numerator, 0, nullptr);\n\n if ((m_audioSwrContext == nullptr) || swr_init(m_audioSwrContext) < 0)\n {\n BOOST_LOG_TRIVIAL(error) << \"unable to initialize swr convert context\";\n }\n\n m_audioCurrentPref.format = audioFrameFormat;\n m_audioCurrentPref.channels = audioFrameChannels;\n m_audioCurrentPref.channel_layout = dec_channel_layout;\n m_audioCurrentPref.frequency = (audioFrame->sample_rate * speed.numerator) \/ speed.denominator;\n }\n}\n\nbool FFmpegDecoder::handleAudioFrame(\n double frame_clock, uint8_t* write_data, int64_t write_size, bool failed)\n{\n bool skipAll = false;\n double delta = 0;\n bool isPaused = false;\n\n {\n boost::lock_guard<boost::mutex> locker(m_isPausedMutex);\n isPaused = m_isPaused;\n if (!isPaused)\n {\n delta = (m_videoStartClock != VIDEO_START_CLOCK_NOT_INITIALIZED)\n ? GetHiResTime() - m_videoStartClock - m_audioPTS : 0;\n }\n }\n\n if (isPaused)\n {\n if (!m_audioPaused)\n {\n m_audioPlayer->WaveOutPause();\n m_audioPaused = true;\n }\n\n const bool hasVideo = m_mainVideoThread != nullptr;\n\n boost::unique_lock<boost::mutex> locker(m_isPausedMutex);\n\n while (m_isVideoSeekingWhilePaused && hasVideo\n || (delta = (m_videoStartClock != VIDEO_START_CLOCK_NOT_INITIALIZED)\n ? (m_isPaused ? m_pauseTimer : GetHiResTime()) - m_videoStartClock - m_audioPTS : 0\n , m_isPaused && !(skipAll = delta >= frame_clock)))\n {\n m_isPausedCV.wait(locker);\n }\n }\n else if (delta > 1 && m_formatContexts.size() > 1 && delta > frame_clock)\n {\n CHANNEL_LOG(ffmpeg_sync) << \"Skip audio frame\";\n skipAll = true;\n }\n\n \/\/ Audio sync\n if (!failed && !skipAll && fabs(delta) > 0.1)\n {\n CHANNEL_LOG(ffmpeg_sync) << \"Audio sync delta = \" << delta;\n InterlockedAdd(m_videoStartClock, delta \/ 2);\n }\n\n if (m_audioPaused && !skipAll)\n {\n m_audioPlayer->WaveOutRestart();\n m_audioPaused = false;\n }\n\n boost::this_thread::interruption_point();\n\n if (skipAll)\n {\n InterlockedAdd(m_audioPTS, frame_clock);\n }\n else if (!(m_audioPlayer->WriteAudio(write_data, write_size)\n || initAudioOutput() && m_audioPlayer->WriteAudio(write_data, write_size)))\n {\n return false;\n }\n\n return true;\n}\n<commit_msg>audio past video case fixed<commit_after>#include \"ffmpegdecoder.h\"\n#include \"makeguard.h\"\n#include \"interlockedadd.h\"\n\n#include <boost\/log\/trivial.hpp>\n\n#include <algorithm>\n#include <functional>\n#include <memory>\n#include <tuple>\n\n\nnamespace {\n\nuint8_t** getAudioData(AVFrame* audioFrame)\n{\n return audioFrame->extended_data != nullptr\n ? audioFrame->extended_data\n : &audioFrame->data[0];\n}\n\nint64_t getChannelLayout(AVFrame* audioFrame)\n{\n\tconst int audioFrameChannels = audioFrame->channels; \/\/av_frame_get_channels(audioFrame);\n return ((audioFrame->channel_layout != 0u) &&\n audioFrameChannels == av_get_channel_layout_nb_channels(audioFrame->channel_layout))\n ? audioFrame->channel_layout\n : av_get_default_channel_layout(audioFrameChannels);\n}\n\n} \/\/ namespace\n\n\nvoid FFmpegDecoder::audioParseRunnable()\n{\n CHANNEL_LOG(ffmpeg_threads) << \"Audio thread started\";\n AVPacket packet;\n\n bool initialized = false;\n bool failed = false;\n\n m_audioPlayer->InitializeThread();\n auto deinitializeThread = MakeGuard(\n m_audioPlayer.get(),\n std::mem_fn(&IAudioPlayer::DeinitializeThread));\n\n std::vector<uint8_t> resampleBuffer;\n\n double scheduledEndTime = 0;\n\n auto useHandleAudioResultLam = [this, &failed](bool result)\n {\n if (result)\n {\n if (failed)\n {\n failed = false;\n boost::lock_guard<boost::mutex> locker(m_isPausedMutex);\n if (m_videoStartClock != VIDEO_START_CLOCK_NOT_INITIALIZED)\n {\n m_audioPTS = (m_isPaused ? m_pauseTimer : GetHiResTime()) - m_videoStartClock;\n }\n }\n }\n else\n {\n failed = true;\n }\n };\n\n while (!boost::this_thread::interruption_requested())\n {\n if (!m_audioPacketsQueue.pop(packet))\n {\n break;\n }\n\n auto packetGuard = MakeGuard(&packet, av_packet_unref);\n\n if (m_audioStreamNumber != packet.stream_index)\n {\n continue;\n }\n\n if (!initialized)\n {\n if (packet.pts == AV_NOPTS_VALUE)\n {\n if (packet.data == nullptr)\n continue;\n\n assert(false && \"No audio pts found\");\n return;\n }\n const double pts = av_q2d(m_audioStream->time_base) * packet.pts;\n m_audioPTS = pts;\n scheduledEndTime = pts;\n \/\/ invoke changedFramePosition() if needed\n \/\/AppendFrameClock(0);\n }\n else if (packet.pts != AV_NOPTS_VALUE)\n {\n const double diff = av_q2d(m_audioStream->time_base) * packet.pts - scheduledEndTime;\n if (diff > 0.01)\n {\n CHANNEL_LOG(ffmpeg_sync) << \"Patching audio frame diff: \" << diff;\n if (m_formatContexts.size() == 1 && m_videoStartClock != VIDEO_START_CLOCK_NOT_INITIALIZED)\n {\n InterlockedAdd(m_videoStartClock, -diff);\n InterlockedAdd(m_audioPTS, diff);\n }\n else\n {\n const int size_multiplier = m_audioSettings.channels *\n av_get_bytes_per_sample(m_audioSettings.format);\n\n const int numSteps = (diff + 0.1) \/ 0.1;\n const auto frame_clock = diff \/ numSteps;\n for (int i = 0; i < numSteps; ++i)\n {\n const auto speed = getSpeedRational();\n const int nb_samples = frame_clock * m_audioSettings.frequency * speed.denominator \/ speed.numerator;\n const auto write_size = nb_samples * size_multiplier;\n std::vector<uint8_t> buf(write_size, 0);\n useHandleAudioResultLam(handleAudioFrame(frame_clock, buf.data(), write_size, failed));\n }\n }\n }\n\n scheduledEndTime += diff;\n }\n\n initialized = true;\n\n useHandleAudioResultLam(handleAudioPacket(packet, resampleBuffer, failed, scheduledEndTime));\n }\n}\n\nbool FFmpegDecoder::handleAudioPacket(\n const AVPacket& packet,\n std::vector<uint8_t>& resampleBuffer,\n bool failed, double& scheduledEndTime)\n{\n if (packet.stream_index != m_audioStream->index)\n {\n avcodec_close(m_audioCodecContext);\n m_audioStream = m_formatContexts[m_audioContextIndex]->streams[packet.stream_index];\n if (!setupAudioCodec())\n {\n return false;\n }\n }\n\n const int ret = avcodec_send_packet(m_audioCodecContext, &packet);\n if (ret < 0) {\n return ret == AVERROR(EAGAIN) || ret == AVERROR_EOF;\n }\n\n AVFramePtr audioFrame(av_frame_alloc());\n bool result = true;\n while (avcodec_receive_frame(m_audioCodecContext, audioFrame.get()) == 0)\n {\n if (audioFrame->nb_samples <= 0)\n {\n continue;\n }\n\n const int original_buffer_size = av_samples_get_buffer_size(\n nullptr, audioFrame->channels,\n audioFrame->nb_samples,\n static_cast<AVSampleFormat>(audioFrame->format), 1);\n\n \/\/ write buffer\n uint8_t* write_data = *getAudioData(audioFrame.get());\n int64_t write_size = original_buffer_size;\n\n setupAudioSwrContext(audioFrame.get());\n\n if (m_audioSwrContext != nullptr)\n {\n enum { EXTRA_SPACE = 256 };\n\n const int out_count = static_cast<int64_t>(audioFrame->nb_samples) *\n m_audioSettings.frequency \/\n m_audioCurrentPref.frequency + EXTRA_SPACE;\n\n const int size_multiplier = m_audioSettings.channels *\n av_get_bytes_per_sample(m_audioSettings.format);\n\n const size_t buffer_size = out_count * size_multiplier;\n\n if (resampleBuffer.size() < buffer_size)\n {\n resampleBuffer.resize(buffer_size);\n }\n\n \/\/ Code for resampling\n uint8_t *out = resampleBuffer.data();\n const int converted_size = swr_convert(\n m_audioSwrContext, \n &out,\n out_count,\n const_cast<const uint8_t**>(getAudioData(audioFrame.get())),\n audioFrame->nb_samples);\n\n if (converted_size < 0)\n {\n BOOST_LOG_TRIVIAL(error) << \"swr_convert() failed\";\n break;\n }\n\n if (converted_size == out_count)\n {\n BOOST_LOG_TRIVIAL(warning) << \"audio buffer is probably too small\";\n swr_init(m_audioSwrContext);\n }\n\n write_data = out;\n write_size = converted_size * size_multiplier;\n\n assert(write_size < buffer_size);\n }\n\n const double frame_clock \n = audioFrame->sample_rate != 0? double(audioFrame->nb_samples) \/ audioFrame->sample_rate : 0;\n\n scheduledEndTime += frame_clock;\n\n if (!handleAudioFrame(frame_clock, write_data, write_size, failed))\n {\n result = false;\n }\n }\n\n return result;\n}\n\nvoid FFmpegDecoder::setupAudioSwrContext(AVFrame* audioFrame)\n{\n const auto audioFrameFormat = static_cast<AVSampleFormat>(audioFrame->format);\n const int audioFrameChannels = audioFrame->channels;\n\n const int64_t dec_channel_layout = getChannelLayout(audioFrame);\n\n const auto speed = getSpeedRational();\n\n \/\/ Check if the new swr context required\n if (audioFrameFormat != m_audioCurrentPref.format ||\n dec_channel_layout != m_audioCurrentPref.channel_layout ||\n (audioFrame->sample_rate * speed.numerator) \/ speed.denominator != m_audioCurrentPref.frequency)\n {\n swr_free(&m_audioSwrContext);\n m_audioSwrContext = swr_alloc_set_opts(\n nullptr, m_audioSettings.channel_layout, m_audioSettings.format,\n m_audioSettings.frequency * speed.denominator,\n dec_channel_layout, audioFrameFormat,\n audioFrame->sample_rate * speed.numerator, 0, nullptr);\n\n if ((m_audioSwrContext == nullptr) || swr_init(m_audioSwrContext) < 0)\n {\n BOOST_LOG_TRIVIAL(error) << \"unable to initialize swr convert context\";\n }\n\n m_audioCurrentPref.format = audioFrameFormat;\n m_audioCurrentPref.channels = audioFrameChannels;\n m_audioCurrentPref.channel_layout = dec_channel_layout;\n m_audioCurrentPref.frequency = (audioFrame->sample_rate * speed.numerator) \/ speed.denominator;\n }\n}\n\nbool FFmpegDecoder::handleAudioFrame(\n double frame_clock, uint8_t* write_data, int64_t write_size, bool failed)\n{\n bool skipAll = false;\n double delta = 0;\n bool isPaused = false;\n\n {\n boost::lock_guard<boost::mutex> locker(m_isPausedMutex);\n isPaused = m_isPaused;\n if (!isPaused)\n {\n delta = (m_videoStartClock != VIDEO_START_CLOCK_NOT_INITIALIZED)\n ? GetHiResTime() - m_videoStartClock - m_audioPTS : 0;\n }\n }\n\n if (isPaused)\n {\n if (!m_audioPaused)\n {\n m_audioPlayer->WaveOutPause();\n m_audioPaused = true;\n }\n\n const bool hasVideo = m_mainVideoThread != nullptr;\n\n boost::unique_lock<boost::mutex> locker(m_isPausedMutex);\n\n while (m_isVideoSeekingWhilePaused && hasVideo\n || (delta = (m_videoStartClock != VIDEO_START_CLOCK_NOT_INITIALIZED)\n ? (m_isPaused ? m_pauseTimer : GetHiResTime()) - m_videoStartClock - m_audioPTS : 0\n , m_isPaused && !(skipAll = delta >= frame_clock)))\n {\n m_isPausedCV.wait(locker);\n }\n }\n else if (delta > 1 && m_formatContexts.size() > 1 && delta > frame_clock)\n {\n CHANNEL_LOG(ffmpeg_sync) << \"Skip audio frame\";\n skipAll = true;\n }\n\n if (!skipAll && m_mainVideoThread != nullptr\n && std::all_of(write_data, write_data + write_size, [](uint8_t data) { return data == 0; })\n && m_videoStartClock != VIDEO_START_CLOCK_NOT_INITIALIZED\n && m_videoPacketsQueue.empty()\n && (boost::lock_guard<boost::mutex>(m_videoFramesMutex), !m_videoFramesQueue.canPop()))\n {\n return true; \/\/ just ignore?\n }\n\n \/\/ Audio sync\n if (!failed && !skipAll && fabs(delta) > 0.1)\n {\n CHANNEL_LOG(ffmpeg_sync) << \"Audio sync delta = \" << delta;\n InterlockedAdd(m_videoStartClock, delta \/ 2);\n }\n\n if (m_audioPaused && !skipAll)\n {\n m_audioPlayer->WaveOutRestart();\n m_audioPaused = false;\n }\n\n boost::this_thread::interruption_point();\n\n if (skipAll)\n {\n InterlockedAdd(m_audioPTS, frame_clock);\n }\n else if (!(m_audioPlayer->WriteAudio(write_data, write_size)\n || initAudioOutput() && m_audioPlayer->WriteAudio(write_data, write_size)))\n {\n return false;\n }\n\n return true;\n}\n<|endoftext|>"} {"text":"<commit_before>#ifndef UTILS_HPP\n#define UTILS_HPP\n\n#include <type_traits>\n#include <utility>\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ Tuple unpack utils\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ http:\/\/stackoverflow.com\/questions\/7858817\/unpacking-a-tuple-to-call-a-matching-function-pointer\n\nnamespace util\n{\n\t\/\/ helper class\n\ttemplate <\n\t\ttypename F,\n\t\ttypename... Args,\n\t\tstd::size_t... I\n\t>\n\tauto call_helper(const F& func, const std::tuple<Args...> & params) -> std::result_of_t<F(Args...)>\n\t{\n\t\treturn func(std::get<I>(params)...);\n\t}\n\n\ttemplate<\n\t\ttypename F,\n\t\ttypename... Args\n\t>\n\tauto call(const F& func, const std::tuple<Args...> & params) -> std::result_of_t<F(Args...)>\n\t{\n\t\treturn call_helper<F, Args..., std::index_sequence_for<Args...> >(func, params);\n\t}\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ Bitflags enumerations\ntemplate <typename T> struct is_enum_flags : std::false_type\n{\n\t\/\/static_assert(std::is_enum<T>::value, \"T must be an enum type\");\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ operator| \ntemplate <\n\ttypename T,\n\ttypename = std::enable_if_t<is_enum_flags<T>::value>\n>\ninline T operator|(T a, T b)\n{\n\treturn static_cast<T>(static_cast<std::underlying_type_t<T>>(a) | static_cast<std::underlying_type_t<T>>(b));\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ operator|=\ntemplate <\n\ttypename T,\n\ttypename = std::enable_if_t<is_enum_flags<T>::value>\n>\ninline T& operator|=(T& a, T b)\n{\n\ta = a | b;\n\treturn a;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ operator&=\ntemplate <\n\ttypename T,\n\ttypename = std::enable_if_t<is_enum_flags<T>::value>\n>\ninline T operator&(T a, T b)\n{\n\treturn static_cast<T>(static_cast<std::underlying_type_t<T>>(a) & static_cast<std::underlying_type_t<T>>(b));\n}\n\n#endif \/\/ !UTILS_HPP\n<commit_msg>Fix Utils.hpp call_helper<commit_after>#ifndef UTILS_HPP\n#define UTILS_HPP\n\n#include <type_traits>\n#include <utility>\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ Tuple unpack utils\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ http:\/\/stackoverflow.com\/questions\/7858817\/unpacking-a-tuple-to-call-a-matching-function-pointer\n\nnamespace util\n{\n\t\/\/ helper class\n\ttemplate <\n\t\ttypename F,\n\t\ttypename... Args,\n\t\tstd::size_t... I\n\t>\n\tauto call_helper(const F& func, const std::tuple<Args...> & params, std::index_sequence<I>) -> std::result_of_t<F(Args...)>\n\t{\n\t\treturn func(std::get<I>(params)...);\n\t}\n\n\ttemplate<\n\t\ttypename F,\n\t\ttypename... Args\n\t>\n\tauto call(const F& func, const std::tuple<Args...> & params) -> std::result_of_t<F(Args...)>\n\t{\n\t\treturn call_helper<F, Args...>(func, params, std::index_sequence_for<Args...>);\n\t}\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ Bitflags enumerations\ntemplate <typename T> struct is_enum_flags : std::false_type\n{\n\t\/\/static_assert(std::is_enum<T>::value, \"T must be an enum type\");\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ operator| \ntemplate <\n\ttypename T,\n\ttypename = std::enable_if_t<is_enum_flags<T>::value>\n>\ninline T operator|(T a, T b)\n{\n\treturn static_cast<T>(static_cast<std::underlying_type_t<T>>(a) | static_cast<std::underlying_type_t<T>>(b));\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ operator|=\ntemplate <\n\ttypename T,\n\ttypename = std::enable_if_t<is_enum_flags<T>::value>\n>\ninline T& operator|=(T& a, T b)\n{\n\ta = a | b;\n\treturn a;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ operator&=\ntemplate <\n\ttypename T,\n\ttypename = std::enable_if_t<is_enum_flags<T>::value>\n>\ninline T operator&(T a, T b)\n{\n\treturn static_cast<T>(static_cast<std::underlying_type_t<T>>(a) & static_cast<std::underlying_type_t<T>>(b));\n}\n\n#endif \/\/ !UTILS_HPP\n<|endoftext|>"} {"text":"<commit_before>\/* $Id: OutputFormat.C,v 1.17 1999-11-09 17:11:37 wilson Exp $ *\/\n#include \"OutputFormat.h\"\n\n#include \"Input\/CoolingTime.h\"\n#include \"Input\/Volume.h\"\n#include \"Input\/Mixture.h\"\n#include \"Input\/Loading.h\"\n\n#include \"Chains\/Node.h\"\n\n#define Bq2Ci 2.7027e-11\n#define m32cm3 1e6\n\nconst char *Out_Types = \"ucnstabgw\";\n\nconst int nOutTypes = 9;\nconst int firstResponse = 2;\nconst int lastSingularResponse = 8;\nconst char *Out_Types_Str[nOutTypes] = {\n \"Response Units\",\n \"Break-down by Component\",\n \"Number Density [atoms\/%s]\",\n \"Specific Activity [%s\/%s]\",\n \"Total Decay Heat [W\/%s]\",\n \"Alpha Decay Heat [W\/%s]\",\n \"Beta Decay Heat [W\/%s]\",\n \"Gamma Decay Heat [W\/%s]\",\n \"WDR\/Clearance index\"};\n\n\/***************************\n ********* Service *********\n **************************\/\n\nOutputFormat::OutputFormat(int type)\n{\n resolution = type;\n outTypes = 0;\n actUnits = new char[3];\n strcpy(actUnits,\"Bq\");\n actMult = 1;\n\n normUnits = new char[4];\n strcpy(normUnits,\"cm3\");\n normMult = 1;\n\n next = NULL;\n}\n\nOutputFormat::OutputFormat(const OutputFormat& o) :\n resolution(o.resolution), outTypes(o.outTypes), actMult(o.actMult), \n normMult(o.normMult)\n{\n actUnits = new char[strlen(o.actUnits)+1];\n strcpy(actUnits,o.actUnits);\n\n normUnits = new char[strlen(o.normUnits)+1];\n strcpy(normUnits,o.normUnits);\n\n next = NULL;\n}\n \nOutputFormat::~OutputFormat()\n{\n delete actUnits;\n delete normUnits;\n delete next;\n}\n\nOutputFormat& OutputFormat::operator=(const OutputFormat& o)\n{\n if (this == &o)\n return *this;\n\n resolution = o.resolution;\n outTypes = o.outTypes;\n delete actUnits;\n actUnits = new char[strlen(o.actUnits)+1];\n strcpy(actUnits,o.actUnits);\n actMult = o.actMult;\n\n delete normUnits;\n normUnits = new char[strlen(o.normUnits)+1];\n strcpy(normUnits,o.normUnits);\n normMult = o.normMult;\n\n return *this;\n}\n\n\/***************************\n ********** Input **********\n **************************\/\n\nOutputFormat* OutputFormat::getOutFmts(istream& input)\n{\n const char *Out_Res = \" izm\";\n\n int type;\n char token[64];\n char *fileNamePtr;\n\n input >> token;\n type = strchr(Out_Res,tolower(token[0]))-Out_Res;\n\n next = new OutputFormat(type);\n\n verbose(2,\"Added output at resolution %d (%s)\",type,token);\n \n \/* read a list of output types until keyword \"end\" *\/\n clearComment(input);\n input >> token;\n while (strcmp(token,\"end\"))\n {\n \/* match the first character of the type in the constant string *\/\n type = strchr(Out_Types,tolower(token[0]))-Out_Types;\n if (type<0)\n\terror(230,\"Output type '%s' is not currently supported.\",\n\t token);\n\n \/* use logical and to set the correct bit in the outTypes field *\/\n next->outTypes |= 1<<type;\n\n verbose(3,\"Added output type %d (%s)\",1<<type,token);\n\n switch (1<<type)\n\t{\n\tcase OUTFMT_UNITS:\n\t input >> token;\n\t next->actUnits = new char[strlen(token)+1];\n\t strcpy(next->actUnits,token);\n\t next->actMult = (tolower(token[0]) == 'c'?Bq2Ci:1);\n\n\t input >> token;\n\t next->normUnits = new char[strlen(token)+1];\n\t strcpy(next->normUnits,token);\n\t next->normMult = (tolower(token[0]) == 'm'?m32cm3:1);\n\t break;\n\tcase OUTFMT_WDR:\n\t input >> token;\n\t fileNamePtr = new char[strlen(token)+1];\n\t strcpy(fileNamePtr,token);\n\t next->wdrFilenames.insert(fileNamePtr);\n\t verbose(4,\"Added WDR\/Clearance file %s\", token);\n\t}\n\n\n clearComment(input);\n input >> token;\n }\t \n\n return next;\n\n}\n\n\nvoid OutputFormat::write(Volume* volList, Mixture* mixList, Loading* loadList,\n\t\t\t CoolingTime *coolList, int targetKza)\n{\n \n\n OutputFormat *ptr = this;\n char buffer[64];\n\n int outTypeNum;\n\n \/* for each output description *\/\n while (ptr->next != NULL)\n {\n \n ptr = ptr->next;\n\n \/* write a header *\/\n switch(ptr->resolution)\n\t{\n\tcase OUTRES_INT:\n\t cout << \"Interval output requested:\"<< endl;\n\t break;\n\tcase OUTRES_ZONE:\n\t cout << \"Zone output requested:\"<< endl;\n\t break;\n\tcase OUTRES_MIX:\n\t cout << \"Mixture output requested:\"<< endl;\n\t break;\n\t}\n \n \/* list the reponses and features to come *\/\n \/* units *\/\n outTypeNum = 0;\n cout << \"\\t\" << Out_Types_Str[outTypeNum] << \": \"\n\t << ptr->actUnits << \" \" << ptr->normUnits << endl;\n \/* regular singular responses *\/\n for (++outTypeNum;outTypeNum<lastSingularResponse;outTypeNum++)\n\tif (ptr->outTypes & 1<<outTypeNum)\n\t {\n\t switch(1<<outTypeNum)\n\t {\n\t case (OUTFMT_ACT):\n\t\tsprintf(buffer,Out_Types_Str[outTypeNum],\n\t\t\tptr->actUnits,ptr->normUnits);\n\t\tbreak;\n\t default:\n\t\tsprintf(buffer,Out_Types_Str[outTypeNum],\n\t\t\tptr->normUnits);\n\t }\n\t cout << \"\\t\" << buffer << endl;\n\t }\n \n \/* WDR header *\/\n if (ptr->outTypes & OUTFMT_WDR)\n\tfor(filenameList::iterator fileName = ptr->wdrFilenames.begin();\n\t fileName != ptr->wdrFilenames.end(); ++fileName)\n\t cout << \"\\t\" << Out_Types_Str[outTypeNum] << \": \" \n\t << *fileName << endl;\n\t \n\t\n\n cout << endl << endl;\n \n \/* set units for activity *\/\n Result::setNorm(ptr->actMult, ptr->normMult);\n\n \/* for each indicated response *\/\n for (outTypeNum=firstResponse;outTypeNum<lastSingularResponse;outTypeNum++)\n\tif (ptr->outTypes & 1<<outTypeNum)\n\t {\n\t \/* write a response title *\/\n\t switch(1<<outTypeNum)\n\t {\n\t case(OUTFMT_ACT):\n\t\tsprintf(buffer,Out_Types_Str[outTypeNum],\n\t\t\tptr->actUnits,ptr->normUnits);\n\t default:\n\t\tsprintf(buffer,Out_Types_Str[outTypeNum],ptr->normUnits);\n\t }\n\t cout << \"*** \" << buffer << \" ***\" << endl;\n\n\t \/* call write() on the appropriate object determined by\n the resulotition *\/\n\t switch(ptr->resolution)\n\t {\n\t case OUTRES_INT:\n\t\tvolList->write(1<<outTypeNum,ptr->outTypes & OUTFMT_COMP,\n\t\t\t coolList,targetKza);\n\t\tbreak;\n\t case OUTRES_ZONE:\n\t\tloadList->write(1<<outTypeNum,ptr->outTypes & OUTFMT_COMP,\n\t\t\t\tcoolList,targetKza);\n\t\tbreak;\n\t case OUTRES_MIX:\n\t\tmixList->write(1<<outTypeNum,ptr->outTypes & OUTFMT_COMP,\n\t\t\t coolList,targetKza);\n\t\tbreak;\n\t }\n\n\t cout << endl << endl << endl;\n\t }\n\n if (ptr->outTypes & OUTFMT_WDR)\n\t{\n\t cout << \"*** WDR ***\" << endl;\n\t for(filenameList::iterator fileName = ptr->wdrFilenames.begin();\n\t fileName != ptr->wdrFilenames.end(); ++fileName)\n\t {\n\t \n\t \/* write a response title *\/\n\t cout << \"*** \" << Out_Types_Str[outTypeNum] << \": \" \n\t\t << *fileName << \" ***\" << endl;\n\t \n\t Node::loadWDR(*fileName);\n\t \n\t \/* call write() on the appropriate object determined by\n\t\t the resulotition *\/\n\t switch(ptr->resolution)\n\t\t{\n\t\tcase OUTRES_INT:\n\t\t volList->write(OUTFMT_WDR,ptr->outTypes & OUTFMT_COMP,\n\t\t\t\t coolList,targetKza);\n\t\t break;\n\t\tcase OUTRES_ZONE:\n\t\t loadList->write(OUTFMT_WDR,ptr->outTypes & OUTFMT_COMP,\n\t\t\t\t coolList,targetKza);\n\t\t break;\n\t\tcase OUTRES_MIX:\n\t\t mixList->write(OUTFMT_WDR,ptr->outTypes & OUTFMT_COMP,\n\t\t\t\t coolList,targetKza);\n\t\t break;\n\t\t}\n\t \n\t delete [] *fileName;\n\t cout << endl << endl << endl;\n\t }\n\t \n\t} \n }\n\n}\n<commit_msg>Rationalize support for normalization multiplier m3 as alternative to cm3. - make sure the correct conversion is used to be consistent with implementation in Result.C<commit_after>\/* $Id: OutputFormat.C,v 1.18 1999-11-09 17:17:52 wilson Exp $ *\/\n#include \"OutputFormat.h\"\n\n#include \"Input\/CoolingTime.h\"\n#include \"Input\/Volume.h\"\n#include \"Input\/Mixture.h\"\n#include \"Input\/Loading.h\"\n\n#include \"Chains\/Node.h\"\n\n#define Bq2Ci 2.7027e-11\n#define cm32m3 1e-6\n\nconst char *Out_Types = \"ucnstabgw\";\n\nconst int nOutTypes = 9;\nconst int firstResponse = 2;\nconst int lastSingularResponse = 8;\nconst char *Out_Types_Str[nOutTypes] = {\n \"Response Units\",\n \"Break-down by Component\",\n \"Number Density [atoms\/%s]\",\n \"Specific Activity [%s\/%s]\",\n \"Total Decay Heat [W\/%s]\",\n \"Alpha Decay Heat [W\/%s]\",\n \"Beta Decay Heat [W\/%s]\",\n \"Gamma Decay Heat [W\/%s]\",\n \"WDR\/Clearance index\"};\n\n\/***************************\n ********* Service *********\n **************************\/\n\nOutputFormat::OutputFormat(int type)\n{\n resolution = type;\n outTypes = 0;\n actUnits = new char[3];\n strcpy(actUnits,\"Bq\");\n actMult = 1;\n\n normUnits = new char[4];\n strcpy(normUnits,\"cm3\");\n normMult = 1;\n\n next = NULL;\n}\n\nOutputFormat::OutputFormat(const OutputFormat& o) :\n resolution(o.resolution), outTypes(o.outTypes), actMult(o.actMult), \n normMult(o.normMult)\n{\n actUnits = new char[strlen(o.actUnits)+1];\n strcpy(actUnits,o.actUnits);\n\n normUnits = new char[strlen(o.normUnits)+1];\n strcpy(normUnits,o.normUnits);\n\n next = NULL;\n}\n \nOutputFormat::~OutputFormat()\n{\n delete actUnits;\n delete normUnits;\n delete next;\n}\n\nOutputFormat& OutputFormat::operator=(const OutputFormat& o)\n{\n if (this == &o)\n return *this;\n\n resolution = o.resolution;\n outTypes = o.outTypes;\n delete actUnits;\n actUnits = new char[strlen(o.actUnits)+1];\n strcpy(actUnits,o.actUnits);\n actMult = o.actMult;\n\n delete normUnits;\n normUnits = new char[strlen(o.normUnits)+1];\n strcpy(normUnits,o.normUnits);\n normMult = o.normMult;\n\n return *this;\n}\n\n\/***************************\n ********** Input **********\n **************************\/\n\nOutputFormat* OutputFormat::getOutFmts(istream& input)\n{\n const char *Out_Res = \" izm\";\n\n int type;\n char token[64];\n char *fileNamePtr;\n\n input >> token;\n type = strchr(Out_Res,tolower(token[0]))-Out_Res;\n\n next = new OutputFormat(type);\n\n verbose(2,\"Added output at resolution %d (%s)\",type,token);\n \n \/* read a list of output types until keyword \"end\" *\/\n clearComment(input);\n input >> token;\n while (strcmp(token,\"end\"))\n {\n \/* match the first character of the type in the constant string *\/\n type = strchr(Out_Types,tolower(token[0]))-Out_Types;\n if (type<0)\n\terror(230,\"Output type '%s' is not currently supported.\",\n\t token);\n\n \/* use logical and to set the correct bit in the outTypes field *\/\n next->outTypes |= 1<<type;\n\n verbose(3,\"Added output type %d (%s)\",1<<type,token);\n\n switch (1<<type)\n\t{\n\tcase OUTFMT_UNITS:\n\t input >> token;\n\t next->actUnits = new char[strlen(token)+1];\n\t strcpy(next->actUnits,token);\n\t next->actMult = (tolower(token[0]) == 'c'?Bq2Ci:1);\n\n\t input >> token;\n\t next->normUnits = new char[strlen(token)+1];\n\t strcpy(next->normUnits,token);\n\t next->normMult = (tolower(token[0]) == 'm'?cm32m3:1);\n\t break;\n\tcase OUTFMT_WDR:\n\t input >> token;\n\t fileNamePtr = new char[strlen(token)+1];\n\t strcpy(fileNamePtr,token);\n\t next->wdrFilenames.insert(fileNamePtr);\n\t verbose(4,\"Added WDR\/Clearance file %s\", token);\n\t}\n\n\n clearComment(input);\n input >> token;\n }\t \n\n return next;\n\n}\n\n\nvoid OutputFormat::write(Volume* volList, Mixture* mixList, Loading* loadList,\n\t\t\t CoolingTime *coolList, int targetKza)\n{\n \n\n OutputFormat *ptr = this;\n char buffer[64];\n\n int outTypeNum;\n\n \/* for each output description *\/\n while (ptr->next != NULL)\n {\n \n ptr = ptr->next;\n\n \/* write a header *\/\n switch(ptr->resolution)\n\t{\n\tcase OUTRES_INT:\n\t cout << \"Interval output requested:\"<< endl;\n\t break;\n\tcase OUTRES_ZONE:\n\t cout << \"Zone output requested:\"<< endl;\n\t break;\n\tcase OUTRES_MIX:\n\t cout << \"Mixture output requested:\"<< endl;\n\t break;\n\t}\n \n \/* list the reponses and features to come *\/\n \/* units *\/\n outTypeNum = 0;\n cout << \"\\t\" << Out_Types_Str[outTypeNum] << \": \"\n\t << ptr->actUnits << \" \" << ptr->normUnits << endl;\n \/* regular singular responses *\/\n for (++outTypeNum;outTypeNum<lastSingularResponse;outTypeNum++)\n\tif (ptr->outTypes & 1<<outTypeNum)\n\t {\n\t switch(1<<outTypeNum)\n\t {\n\t case (OUTFMT_ACT):\n\t\tsprintf(buffer,Out_Types_Str[outTypeNum],\n\t\t\tptr->actUnits,ptr->normUnits);\n\t\tbreak;\n\t default:\n\t\tsprintf(buffer,Out_Types_Str[outTypeNum],\n\t\t\tptr->normUnits);\n\t }\n\t cout << \"\\t\" << buffer << endl;\n\t }\n \n \/* WDR header *\/\n if (ptr->outTypes & OUTFMT_WDR)\n\tfor(filenameList::iterator fileName = ptr->wdrFilenames.begin();\n\t fileName != ptr->wdrFilenames.end(); ++fileName)\n\t cout << \"\\t\" << Out_Types_Str[outTypeNum] << \": \" \n\t << *fileName << endl;\n\t \n\t\n\n cout << endl << endl;\n \n \/* set units for activity *\/\n Result::setNorm(ptr->actMult, ptr->normMult);\n\n \/* for each indicated response *\/\n for (outTypeNum=firstResponse;outTypeNum<lastSingularResponse;outTypeNum++)\n\tif (ptr->outTypes & 1<<outTypeNum)\n\t {\n\t \/* write a response title *\/\n\t switch(1<<outTypeNum)\n\t {\n\t case(OUTFMT_ACT):\n\t\tsprintf(buffer,Out_Types_Str[outTypeNum],\n\t\t\tptr->actUnits,ptr->normUnits);\n\t default:\n\t\tsprintf(buffer,Out_Types_Str[outTypeNum],ptr->normUnits);\n\t }\n\t cout << \"*** \" << buffer << \" ***\" << endl;\n\n\t \/* call write() on the appropriate object determined by\n the resulotition *\/\n\t switch(ptr->resolution)\n\t {\n\t case OUTRES_INT:\n\t\tvolList->write(1<<outTypeNum,ptr->outTypes & OUTFMT_COMP,\n\t\t\t coolList,targetKza);\n\t\tbreak;\n\t case OUTRES_ZONE:\n\t\tloadList->write(1<<outTypeNum,ptr->outTypes & OUTFMT_COMP,\n\t\t\t\tcoolList,targetKza);\n\t\tbreak;\n\t case OUTRES_MIX:\n\t\tmixList->write(1<<outTypeNum,ptr->outTypes & OUTFMT_COMP,\n\t\t\t coolList,targetKza);\n\t\tbreak;\n\t }\n\n\t cout << endl << endl << endl;\n\t }\n\n if (ptr->outTypes & OUTFMT_WDR)\n\t{\n\t cout << \"*** WDR ***\" << endl;\n\t for(filenameList::iterator fileName = ptr->wdrFilenames.begin();\n\t fileName != ptr->wdrFilenames.end(); ++fileName)\n\t {\n\t \n\t \/* write a response title *\/\n\t cout << \"*** \" << Out_Types_Str[outTypeNum] << \": \" \n\t\t << *fileName << \" ***\" << endl;\n\t \n\t Node::loadWDR(*fileName);\n\t \n\t \/* call write() on the appropriate object determined by\n\t\t the resulotition *\/\n\t switch(ptr->resolution)\n\t\t{\n\t\tcase OUTRES_INT:\n\t\t volList->write(OUTFMT_WDR,ptr->outTypes & OUTFMT_COMP,\n\t\t\t\t coolList,targetKza);\n\t\t break;\n\t\tcase OUTRES_ZONE:\n\t\t loadList->write(OUTFMT_WDR,ptr->outTypes & OUTFMT_COMP,\n\t\t\t\t coolList,targetKza);\n\t\t break;\n\t\tcase OUTRES_MIX:\n\t\t mixList->write(OUTFMT_WDR,ptr->outTypes & OUTFMT_COMP,\n\t\t\t\t coolList,targetKza);\n\t\t break;\n\t\t}\n\t \n\t delete [] *fileName;\n\t cout << endl << endl << endl;\n\t }\n\t \n\t} \n }\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/*=========================================================================\n\n Program: Visualization Toolkit\n Module: $RCSfile$\n\n Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen\n All rights reserved.\n See Copyright.txt or http:\/\/www.kitware.com\/Copyright.htm for details.\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notice for more information.\n\n=========================================================================*\/\n\/\/This test demonstrates the use of sort last distributed memory parallel\n\/\/rendering with Piston.\n\/\/\n\/\/The pipeline is created in parallel and each process is\n\/\/assigned 1 piece to process. Each node then renders its local image and\n\/\/the image results are depth composited to produce a correct image on the\n\/\/root node.\n\n#include <mpi.h>\n\n#include \"vtkActor.h\"\n#include \"vtkCamera.h\"\n#include \"vtkCompositeRenderManager.h\"\n#include \"vtkContourFilter.h\"\n#include \"vtkDataSetToPiston.h\"\n#include \"vtkImageMandelbrotSource.h\"\n#include \"vtkLookupTable.h\"\n#include \"vtkMPICommunicator.h\"\n#include \"vtkMPIController.h\"\n#include \"vtkObjectFactory.h\"\n#include \"vtkOpenGLRenderWindow.h\"\n#include \"vtkPieceScalars.h\"\n#include \"vtkPistonContour.h\"\n#include \"vtkPistonMapper.h\"\n#include \"vtkPolyDataMapper.h\"\n#include \"vtkProcess.h\"\n#include \"vtkRegressionTestImage.h\"\n#include \"vtkRenderWindowInteractor.h\"\n#include \"vtkRenderer.h\"\n#include \"vtkSphereSource.h\"\n#include \"vtkStreamingDemandDrivenPipeline.h\"\n#include \"vtkSynchronizedRenderWindows.h\"\n#include \"vtkSynchronizedRenderers.h\"\n#include \"vtkTestUtilities.h\"\n\nclass MyProcess : public vtkProcess\n{\npublic:\n static MyProcess *New();\n vtkTypeMacro(MyProcess, vtkProcess);\n\n virtual void Execute();\n\n void SetArgs(int argc, char *argv[])\n {\n this->Argc = argc;\n this->Argv = argv;\n }\n\n void CreatePipeline(vtkRenderer *renderer)\n {\n int num_procs = this->Controller->GetNumberOfProcesses();\n int my_id = this->Controller->GetLocalProcessId();\n\n vtkSmartPointer<vtkImageMandelbrotSource> src =\n vtkSmartPointer<vtkImageMandelbrotSource>::New();\n vtkSmartPointer<vtkDataSetToPiston> d2p =\n vtkSmartPointer<vtkDataSetToPiston>::New();\n vtkSmartPointer<vtkPistonContour> contour =\n vtkSmartPointer<vtkPistonContour>::New();\n vtkSmartPointer<vtkContourFilter> vtkcontour =\n vtkSmartPointer<vtkContourFilter>::New();\n\n vtkSmartPointer<vtkSphereSource> sphere =\n vtkSmartPointer<vtkSphereSource>::New();\n vtkSmartPointer<vtkPieceScalars> piecescalars =\n vtkSmartPointer<vtkPieceScalars>::New();\n vtkSmartPointer<vtkPistonMapper> mapper =\n vtkSmartPointer<vtkPistonMapper>::New();\n vtkSmartPointer<vtkPolyDataMapper> pdm =\n vtkSmartPointer<vtkPolyDataMapper>::New();\n vtkSmartPointer<vtkActor> actor =\n vtkSmartPointer<vtkActor>::New();\n\n#define TESTPISTON 1\n#define TESTUNSTRUCTURED 1\n\n#if TESTPISTON\n#if TESTUNSTRUCTURED\n sphere->SetPhiResolution(100);\n sphere->SetThetaResolution(100);\n piecescalars->SetInputConnection(sphere->GetOutputPort());\n piecescalars->SetScalarModeToCellData();\n d2p->SetInputConnection(piecescalars->GetOutputPort());\n\n mapper->SetInputConnection(d2p->GetOutputPort());\n mapper->SetPiece(my_id);\n mapper->SetNumberOfPieces(num_procs);\n\n#else \/\/ TESTSTRUCTURED\n src->SetWholeExtent(0,40,0,40,0,40);\n d2p->SetInputConnection(src->GetOutputPort());\n contour->SetInputConnection(d2p->GetOutputPort());\n contour->SetIsoValue(50.0);\n\n mapper->SetInputConnection(contour->GetOutputPort());\n mapper->SetPiece(my_id);\n mapper->SetNumberOfPieces(num_procs);\n\n#endif\n mapper->Update(); \/\/ TODO: shouldn't need this\n actor->SetMapper(mapper);\n#else \/\/ TESTPISTON\n\n#if TESTUNSTRUCTURED\n sphere->SetPhiResolution(100);\n sphere->SetThetaResolution(100);\n piecescalars->SetInputConnection(sphere->GetOutputPort());\n piecescalars->SetScalarModeToCellData();\n\n pdm->SetInputConnection(piecescalars->GetOutputPort());\n pdm->SetScalarModeToUseCellFieldData();\n pdm->SelectColorArray(\"Piece\");\n pdm->SetScalarRange(0, num_procs-1);\n pdm->SetPiece(my_id);\n pdm->SetNumberOfPieces(num_procs);\n\n#else \/\/ TESTSTRUCTURED\n src->SetWholeExtent(0,40,0,40,0,40);\n vtkcontour->SetInputConnection(src->GetOutputPort());\n vtkcontour->SetNumberOfContours(1);\n vtkcontour->SetValue(0, 50.0);\n\n pdm->SetInputConnection(vtkcontour->GetOutputPort());\n pdm->SetPiece(my_id);\n pdm->SetNumberOfPieces(num_procs);\n\n#endif\n\n pdm->Update(); \/\/TODO: Why is this needed?\n actor->SetMapper(pdm);\n#endif\n\n renderer->AddActor(actor);\n }\n\nprotected:\n MyProcess() { this->Argc = 0; this->Argv = NULL; }\n\n int Argc;\n char **Argv;\n};\n\n\/\/#vtkCxxRevisionMacro(MyProcess, \"1.0\");\nvtkStandardNewMacro(MyProcess);\n\nvoid MyProcess::Execute()\n{\n int my_id = this->Controller->GetLocalProcessId();\n\n int go;\n vtkMPICommunicator *comm =\n vtkMPICommunicator::SafeDownCast(this->Controller->GetCommunicator());\n comm->Barrier();\n\n \/\/ TODO: Update to utkarsh's new architecture\n vtkSmartPointer<vtkCompositeRenderManager> prm =\n vtkSmartPointer<vtkCompositeRenderManager>::New();\n vtkRenderer *renderer = prm->MakeRenderer();\n vtkRenderWindow *renWin = prm->MakeRenderWindow();\n renWin->AddRenderer(renderer);\n renWin->DoubleBufferOn();\n renWin->Render();\n\n \/\/ TODO: Add an argument to decide if use interop or not\n vtkPistonMapper::InitCudaGL(renWin);\n\n this->CreatePipeline(renderer);\n prm->SetRenderWindow(renWin);\n prm->SetController(this->Controller);\n\n if (my_id == 0)\n {\n prm->ResetAllCameras();\n\n vtkRenderWindowInteractor* iren = vtkRenderWindowInteractor::New();\n iren->SetRenderWindow(renWin);\n this->ReturnValue =\n vtkRegressionTester::Test(this->Argc, this->Argv, renWin, 10);\n\n\n if (this->ReturnValue == vtkRegressionTester::DO_INTERACTOR)\n {\n prm->StartInteractor();\n }\n\n iren->Delete();\n\n this->Controller->TriggerBreakRMIs();\n this->Controller->Barrier();\n }\n else\n {\n prm->StartServices();\n this->Controller->Barrier();\n\n \/\/ No testing is done here so mark it passed\n this->ReturnValue = vtkTesting::PASSED;\n }\n\n renderer->Delete();\n renWin->Delete();\n}\n\n\nint main(int argc, char **argv)\n{\n \/\/ This is here to avoid false leak messages from vtkDebugLeaks when\n \/\/ using mpich. It appears that the root process which spawns all the\n \/\/ main processes waits in MPI_Init() and calls exit() when\n \/\/ the others are done, causing apparent memory leaks for any objects\n \/\/ created before MPI_Init().\n MPI_Init(&argc, &argv);\n\n \/\/ Note that this will create a vtkMPIController if MPI\n \/\/ is configured, vtkThreadedController otherwise.\n vtkMPIController *contr = vtkMPIController::New();\n contr->Initialize(&argc, &argv, 1);\n\n int retVal = 1; \/\/ 1 == failed\n\n int numProcs = contr->GetNumberOfProcesses();\n\n if (numProcs < 2 && false)\n {\n cout << \"This test requires at least 2 processes\" << endl;\n contr->Delete();\n return retVal;\n }\n\n vtkMultiProcessController::SetGlobalController(contr);\n\n MyProcess *p = MyProcess::New();\n p->SetArgs(argc, argv);\n\n contr->SetSingleProcessObject(p);\n contr->SingleMethodExecute();\n\n retVal = p->GetReturnValue();\n\n p->Delete();\n contr->Finalize();\n contr->Delete();\n vtkMultiProcessController::SetGlobalController(0);\n return !retVal;\n}\n<commit_msg>Fix parallel piston test on linux<commit_after>\/*=========================================================================\n\n Program: Visualization Toolkit\n Module: $RCSfile$\n\n Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen\n All rights reserved.\n See Copyright.txt or http:\/\/www.kitware.com\/Copyright.htm for details.\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notice for more information.\n\n=========================================================================*\/\n\/\/This test demonstrates the use of sort last distributed memory parallel\n\/\/rendering with Piston.\n\/\/\n\/\/The pipeline is created in parallel and each process is\n\/\/assigned 1 piece to process. Each node then renders its local image and\n\/\/the image results are depth composited to produce a correct image on the\n\/\/root node.\n\n#include <mpi.h>\n\n#include \"vtkActor.h\"\n#include \"vtkCamera.h\"\n#include \"vtkCompositeRenderManager.h\"\n#include \"vtkContourFilter.h\"\n#include \"vtkDataSetToPiston.h\"\n#include \"vtkImageMandelbrotSource.h\"\n#include \"vtkLookupTable.h\"\n#include \"vtkMPICommunicator.h\"\n#include \"vtkMPIController.h\"\n#include \"vtkObjectFactory.h\"\n#include \"vtkOpenGLRenderWindow.h\"\n#include \"vtkPieceScalars.h\"\n#include \"vtkPistonContour.h\"\n#include \"vtkPistonMapper.h\"\n#include \"vtkPolyDataMapper.h\"\n#include \"vtkProcess.h\"\n#include \"vtkRegressionTestImage.h\"\n#include \"vtkRenderWindowInteractor.h\"\n#include \"vtkRenderer.h\"\n#include \"vtkSphereSource.h\"\n#include \"vtkStreamingDemandDrivenPipeline.h\"\n#include \"vtkSynchronizedRenderWindows.h\"\n#include \"vtkSynchronizedRenderers.h\"\n#include \"vtkTestUtilities.h\"\n\nclass MyProcess : public vtkProcess\n{\npublic:\n static MyProcess *New();\n vtkTypeMacro(MyProcess, vtkProcess);\n\n virtual void Execute();\n\n void SetArgs(int argc, char *argv[])\n {\n this->Argc = argc;\n this->Argv = argv;\n }\n\n void CreatePipeline(vtkRenderer *renderer)\n {\n int num_procs = this->Controller->GetNumberOfProcesses();\n int my_id = this->Controller->GetLocalProcessId();\n\n vtkSmartPointer<vtkImageMandelbrotSource> src =\n vtkSmartPointer<vtkImageMandelbrotSource>::New();\n vtkSmartPointer<vtkDataSetToPiston> d2p =\n vtkSmartPointer<vtkDataSetToPiston>::New();\n vtkSmartPointer<vtkPistonContour> contour =\n vtkSmartPointer<vtkPistonContour>::New();\n vtkSmartPointer<vtkContourFilter> vtkcontour =\n vtkSmartPointer<vtkContourFilter>::New();\n\n vtkSmartPointer<vtkSphereSource> sphere =\n vtkSmartPointer<vtkSphereSource>::New();\n vtkSmartPointer<vtkPieceScalars> piecescalars =\n vtkSmartPointer<vtkPieceScalars>::New();\n vtkSmartPointer<vtkPistonMapper> mapper =\n vtkSmartPointer<vtkPistonMapper>::New();\n vtkSmartPointer<vtkPolyDataMapper> pdm =\n vtkSmartPointer<vtkPolyDataMapper>::New();\n vtkSmartPointer<vtkActor> actor =\n vtkSmartPointer<vtkActor>::New();\n\n#define TESTPISTON 1\n#define TESTUNSTRUCTURED 1\n\n#if TESTPISTON\n#if TESTUNSTRUCTURED\n sphere->SetPhiResolution(100);\n sphere->SetThetaResolution(100);\n piecescalars->SetInputConnection(sphere->GetOutputPort());\n piecescalars->SetScalarModeToCellData();\n d2p->SetInputConnection(piecescalars->GetOutputPort());\n\n mapper->SetInputConnection(d2p->GetOutputPort());\n mapper->SetPiece(my_id);\n mapper->SetNumberOfPieces(num_procs);\n\n#else \/\/ TESTSTRUCTURED\n src->SetWholeExtent(0,40,0,40,0,40);\n d2p->SetInputConnection(src->GetOutputPort());\n contour->SetInputConnection(d2p->GetOutputPort());\n contour->SetIsoValue(50.0);\n\n mapper->SetInputConnection(contour->GetOutputPort());\n mapper->SetPiece(my_id);\n mapper->SetNumberOfPieces(num_procs);\n\n#endif\n mapper->Update(); \/\/ TODO: shouldn't need this\n actor->SetMapper(mapper);\n#else \/\/ TESTPISTON\n\n#if TESTUNSTRUCTURED\n sphere->SetPhiResolution(100);\n sphere->SetThetaResolution(100);\n piecescalars->SetInputConnection(sphere->GetOutputPort());\n piecescalars->SetScalarModeToCellData();\n\n pdm->SetInputConnection(piecescalars->GetOutputPort());\n pdm->SetScalarModeToUseCellFieldData();\n pdm->SelectColorArray(\"Piece\");\n pdm->SetScalarRange(0, num_procs-1);\n pdm->SetPiece(my_id);\n pdm->SetNumberOfPieces(num_procs);\n\n#else \/\/ TESTSTRUCTURED\n src->SetWholeExtent(0,40,0,40,0,40);\n vtkcontour->SetInputConnection(src->GetOutputPort());\n vtkcontour->SetNumberOfContours(1);\n vtkcontour->SetValue(0, 50.0);\n\n pdm->SetInputConnection(vtkcontour->GetOutputPort());\n pdm->SetPiece(my_id);\n pdm->SetNumberOfPieces(num_procs);\n\n#endif\n\n pdm->Update(); \/\/TODO: Why is this needed?\n actor->SetMapper(pdm);\n#endif\n\n renderer->AddActor(actor);\n }\n\nprotected:\n MyProcess() { this->Argc = 0; this->Argv = NULL; }\n\n int Argc;\n char **Argv;\n};\n\n\/\/#vtkCxxRevisionMacro(MyProcess, \"1.0\");\nvtkStandardNewMacro(MyProcess);\n\nvoid MyProcess::Execute()\n{\n int my_id = this->Controller->GetLocalProcessId();\n\n int go;\n vtkMPICommunicator *comm =\n vtkMPICommunicator::SafeDownCast(this->Controller->GetCommunicator());\n comm->Barrier();\n\n \/\/ TODO: Update to utkarsh's new architecture\n vtkSmartPointer<vtkCompositeRenderManager> prm =\n vtkSmartPointer<vtkCompositeRenderManager>::New();\n vtkRenderer *renderer = prm->MakeRenderer();\n vtkRenderWindow *renWin = prm->MakeRenderWindow();\n renWin->AddRenderer(renderer);\n renWin->DoubleBufferOn();\n renWin->SetMultiSamples(0);\n vtkRenderWindowInteractor* iren = vtkRenderWindowInteractor::New();\n iren->SetRenderWindow(renWin);\n renWin->Render();\n\n \/\/ TODO: Add an argument to decide if use interop or not\n vtkPistonMapper::InitCudaGL(renWin);\n\n this->CreatePipeline(renderer);\n prm->SetRenderWindow(renWin);\n prm->SetController(this->Controller);\n\n if (my_id == 0)\n {\n prm->ResetAllCameras();\n\n this->ReturnValue =\n vtkRegressionTester::Test(this->Argc, this->Argv, renWin, 10);\n if (this->ReturnValue == vtkRegressionTester::DO_INTERACTOR)\n {\n renWin->Render();\n prm->StartInteractor();\n }\n\n this->Controller->TriggerBreakRMIs();\n this->Controller->Barrier();\n }\n else\n {\n prm->StartServices();\n this->Controller->Barrier();\n\n \/\/ No testing is done here so mark it passed\n this->ReturnValue = vtkTesting::PASSED;\n }\n\n renderer->Delete();\n renWin->Delete();\n iren->Delete();\n}\n\n\nint main(int argc, char **argv)\n{\n \/\/ This is here to avoid false leak messages from vtkDebugLeaks when\n \/\/ using mpich. It appears that the root process which spawns all the\n \/\/ main processes waits in MPI_Init() and calls exit() when\n \/\/ the others are done, causing apparent memory leaks for any objects\n \/\/ created before MPI_Init().\n MPI_Init(&argc, &argv);\n\n \/\/ Note that this will create a vtkMPIController if MPI\n \/\/ is configured, vtkThreadedController otherwise.\n vtkMPIController *contr = vtkMPIController::New();\n contr->Initialize(&argc, &argv, 1);\n\n int retVal = 1; \/\/ 1 == failed\n\n int numProcs = contr->GetNumberOfProcesses();\n\n if (numProcs < 2 && false)\n {\n cout << \"This test requires at least 2 processes\" << endl;\n contr->Delete();\n return retVal;\n }\n\n vtkMultiProcessController::SetGlobalController(contr);\n\n MyProcess *p = MyProcess::New();\n p->SetArgs(argc, argv);\n\n contr->SetSingleProcessObject(p);\n contr->SingleMethodExecute();\n\n retVal = p->GetReturnValue();\n\n p->Delete();\n contr->Finalize();\n contr->Delete();\n vtkMultiProcessController::SetGlobalController(0);\n return !retVal;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (C) 2015 Cloudius Systems, Ltd.\n *\/\n\n#pragma once\n\n#include \"core\/reactor.hh\"\n#include \"core\/iostream.hh\"\n#include \"core\/distributed.hh\"\n#include \"core\/print.hh\"\n#include \"core\/sstring.hh\"\n#include \"net\/api.hh\"\n#include \"util\/serialization.hh\"\n#include \"gms\/inet_address.hh\"\n#include \"rpc\/rpc.hh\"\n#include <unordered_map>\n#include \"db\/config.hh\"\n#include \"frozen_mutation.hh\"\n#include \"query-request.hh\"\n#include \"db\/serializer.hh\"\n#include \"mutation_query.hh\"\n\n\/\/ forward declarations\nnamespace streaming { namespace messages {\n class stream_init_message;\n}}\n\nnamespace net {\n\n\/* All verb handler identifiers *\/\nenum class messaging_verb : int32_t {\n MUTATION,\n MUTATION_DONE,\n BINARY, \/\/ Deprecated\n READ_REPAIR,\n READ,\n READ_DATA,\n READ_MUTATION_DATA, \/\/ urchin-only\n READ_DIGEST,\n REQUEST_RESPONSE, \/\/ client-initiated reads and writes\n STREAM_INITIATE, \/\/ Deprecated\n STREAM_INITIATE_DONE, \/\/ Deprecated\n STREAM_REPLY, \/\/ Deprecated\n STREAM_REQUEST, \/\/ Deprecated\n RANGE_SLICE,\n BOOTSTRAP_TOKEN, \/\/ Deprecated\n TREE_REQUEST, \/\/ Deprecated\n TREE_RESPONSE, \/\/ Deprecated\n JOIN, \/\/ Deprecated\n GOSSIP_DIGEST_SYN,\n GOSSIP_DIGEST_ACK,\n GOSSIP_DIGEST_ACK2,\n DEFINITIONS_ANNOUNCE, \/\/ Deprecated\n DEFINITIONS_UPDATE,\n TRUNCATE,\n SCHEMA_CHECK,\n INDEX_SCAN, \/\/ Deprecated\n REPLICATION_FINISHED,\n INTERNAL_RESPONSE, \/\/ responses to internal calls\n COUNTER_MUTATION,\n STREAMING_REPAIR_REQUEST, \/\/ Deprecated\n STREAMING_REPAIR_RESPONSE, \/\/ Deprecated\n SNAPSHOT, \/\/ Similar to nt snapshot\n MIGRATION_REQUEST,\n GOSSIP_SHUTDOWN,\n _TRACE,\n ECHO,\n REPAIR_MESSAGE,\n PAXOS_PREPARE,\n PAXOS_PROPOSE,\n PAXOS_COMMIT,\n PAGED_RANGE,\n UNUSED_1,\n UNUSED_2,\n UNUSED_3,\n \/\/ Used by streaming\n STREAM_INIT_MESSAGE,\n PREPARE_MESSAGE,\n STREAM_MUTATION,\n INCOMING_FILE_MESSAGE,\n OUTGOING_FILE_MESSAGE,\n RECEIVED_MESSAGE,\n RETRY_MESSAGE,\n COMPLETE_MESSAGE,\n SESSION_FAILED_MESSAGE,\n LAST,\n};\n\n} \/\/ namespace net\n\nnamespace std {\ntemplate <>\nclass hash<net::messaging_verb> {\npublic:\n size_t operator()(const net::messaging_verb& x) const {\n return hash<int32_t>()(int32_t(x));\n }\n};\n} \/\/ namespace std\n\nnamespace net {\n\nfuture<> ser_messaging_verb(output_stream<char>& out, messaging_verb& v);\nfuture<> des_messaging_verb(input_stream<char>& in, messaging_verb& v);\nfuture<> ser_sstring(output_stream<char>& out, sstring& v);\nfuture<> des_sstring(input_stream<char>& in, sstring& v);\n\n\/\/ NOTE: operator(input_stream<char>&, T&) takes a reference to uninitialized\n\/\/ T object and should use placement new in case T is non POD\nstruct serializer {\n template<typename T>\n inline future<T> read_integral(input_stream<char>& in) {\n static_assert(std::is_integral<T>::value, \"T should be integral\");\n\n return in.read_exactly(sizeof(T)).then([] (temporary_buffer<char> buf) {\n if (buf.size() != sizeof(T)) {\n throw rpc::closed_error();\n }\n return make_ready_future<T>(net::ntoh(*unaligned_cast<T*>(buf.get())));\n });\n }\n\n \/\/ Adaptor for writing objects having db::serializer<>\n template<typename Serializable>\n inline future<> write_serializable(output_stream<char>& out, const Serializable& v) {\n db::serializer<Serializable> ser(v);\n bytes b(bytes::initialized_later(), ser.size() + data_output::serialized_size<uint32_t>());\n data_output d_out(b);\n d_out.write<uint32_t>(ser.size());\n ser.write(d_out);\n return out.write(reinterpret_cast<const char*>(b.c_str()), b.size());\n }\n\n \/\/ Adaptor for reading objects having db::serializer<>\n template<typename Serializable>\n inline future<> read_serializable(input_stream<char>& in, Serializable& v) {\n return read_integral<uint32_t>(in).then([&in, &v] (auto sz) mutable {\n return in.read_exactly(sz).then([sz, &v] (temporary_buffer<char> buf) mutable {\n if (buf.size() != sz) {\n throw rpc::closed_error();\n }\n bytes_view bv(reinterpret_cast<const int8_t*>(buf.get()), sz);\n data_input in(bv);\n db::serializer<Serializable>::read(v, in);\n });\n });\n }\n\n \/\/ For integer type\n template<typename T>\n inline auto operator()(output_stream<char>& out, T&& v, std::enable_if_t<std::is_integral<std::remove_reference_t<T>>::value, void*> = nullptr) {\n auto v_ = net::hton(v);\n return out.write(reinterpret_cast<const char*>(&v_), sizeof(T));\n }\n template<typename T>\n inline auto operator()(input_stream<char>& in, T& v, std::enable_if_t<std::is_integral<T>::value, void*> = nullptr) {\n return in.read_exactly(sizeof(v)).then([&v] (temporary_buffer<char> buf) mutable {\n if (buf.size() != sizeof(v)) {\n throw rpc::closed_error();\n }\n v = net::ntoh(*reinterpret_cast<const net::packed<T>*>(buf.get()));\n });\n }\n\n \/\/ For vectors\n template<typename T>\n inline auto operator()(output_stream<char>& out, std::vector<T>& v) {\n return operator()(out, v.size()).then([&out, &v, this] {\n return do_for_each(v.begin(), v.end(), [&out, this] (T& e) {\n return operator()(out, e);\n });\n });\n }\n template<typename T>\n inline auto operator()(input_stream<char>& in, std::vector<T>& v) {\n using size_type = typename std::vector<T>::size_type;\n return read_integral<size_type>(in).then([&v, &in, this] (size_type c) {\n new (&v) std::vector<T>;\n v.reserve(c);\n union U {\n U(){}\n ~U(){}\n U(U&&) {}\n T v;\n };\n return do_with(U(), [c, &v, &in, this] (U& u) {\n return do_until([c = c] () mutable {return !c--;}, [&v, &in, &u, this] () mutable {\n return operator()(in, u.v).then([&u, &v] {\n v.emplace_back(std::move(u.v));\n });\n });\n });\n });\n }\n\n \/\/ For messaging_verb\n inline auto operator()(output_stream<char>& out, messaging_verb& v) {\n return ser_messaging_verb(out, v);\n }\n inline auto operator()(input_stream<char>& in, messaging_verb& v) {\n return des_messaging_verb(in, v);\n }\n\n \/\/ For sstring\n inline auto operator()(output_stream<char>& out, sstring& v) {\n return ser_sstring(out, v);\n }\n inline auto operator()(input_stream<char>& in, sstring& v) {\n return des_sstring(in, v);\n }\n\n \/\/ For frozen_mutation\n inline auto operator()(output_stream<char>& out, const frozen_mutation& v) {\n return write_serializable(out, v);\n }\n inline auto operator()(output_stream<char>& out, frozen_mutation& v) {\n return write_serializable(out, v);\n }\n inline auto operator()(input_stream<char>& in, frozen_mutation& v) {\n return read_serializable(in, v);\n }\n\n \/\/ For reconcilable_result\n inline auto operator()(output_stream<char>& out, const reconcilable_result& v) {\n return write_serializable(out, v);\n }\n inline auto operator()(output_stream<char>& out, reconcilable_result& v) {\n return write_serializable(out, v);\n }\n inline auto operator()(input_stream<char>& in, reconcilable_result& v) {\n return read_serializable(in, v);\n }\n\n \/\/ For complex types which have serialize()\/deserialize(), e.g. gms::gossip_digest_syn, gms::gossip_digest_ack2\n template<typename T>\n inline auto operator()(output_stream<char>& out, T&& v, std::enable_if_t<!std::is_integral<std::remove_reference_t<T>>::value &&\n !std::is_enum<std::remove_reference_t<T>>::value, void*> = nullptr) {\n auto sz = serialize_int32_size + v.serialized_size();\n bytes b(bytes::initialized_later(), sz);\n auto _out = b.begin();\n serialize_int32(_out, int32_t(sz - serialize_int32_size));\n v.serialize(_out);\n return out.write(reinterpret_cast<const char*>(b.c_str()), sz);\n }\n template<typename T>\n inline auto operator()(input_stream<char>& in, T& v, std::enable_if_t<!std::is_integral<T>::value &&\n !std::is_enum<T>::value, void*> = nullptr) {\n return in.read_exactly(serialize_int32_size).then([&in, &v] (temporary_buffer<char> buf) mutable {\n if (buf.size() != serialize_int32_size) {\n throw rpc::closed_error();\n }\n size_t sz = net::ntoh(*reinterpret_cast<const net::packed<int32_t>*>(buf.get()));\n return in.read_exactly(sz).then([sz, &v] (temporary_buffer<char> buf) mutable {\n if (buf.size() != sz) {\n throw rpc::closed_error();\n }\n bytes_view bv(reinterpret_cast<const int8_t*>(buf.get()), sz);\n new (&v) T(T::deserialize(bv));\n assert(bv.size() == 0);\n return make_ready_future<>();\n });\n });\n }\n};\n\nstruct shard_id {\n gms::inet_address addr;\n uint32_t cpu_id;\n friend bool operator==(const shard_id& x, const shard_id& y);\n friend bool operator<(const shard_id& x, const shard_id& y);\n friend std::ostream& operator<<(std::ostream& os, const shard_id& x);\n struct hash {\n size_t operator()(const shard_id& id) const;\n };\n};\n\nclass messaging_service {\npublic:\n using shard_id = net::shard_id;\n\n using rpc_protocol = rpc::protocol<serializer, messaging_verb>;\n struct rpc_protocol_wrapper : public rpc_protocol { using rpc_protocol::rpc_protocol; };\n struct rpc_protocol_client_wrapper : public rpc_protocol::client { using rpc_protocol::client::client; };\n struct rpc_protocol_server_wrapper : public rpc_protocol::server { using rpc_protocol::server::server; };\n\n \/\/ FIXME: messaging service versioning\n static constexpr int32_t current_version = 0;\n\n struct shard_info {\n shard_info(std::unique_ptr<rpc_protocol_client_wrapper>&& client);\n std::unique_ptr<rpc_protocol_client_wrapper> rpc_client;\n };\n\n void foreach_client(std::function<void(const shard_id& id, const shard_info& info)> f) const;\n\n void increment_dropped_messages(messaging_verb verb);\n\n uint64_t get_dropped_messages(messaging_verb verb) const;\n\n const uint64_t* get_dropped_messages() const;\n\n int32_t get_raw_version(const gms::inet_address& endpoint) const;\n\n bool knows_version(const gms::inet_address& endpoint) const;\n\nprivate:\n static constexpr uint16_t _default_port = 7000;\n gms::inet_address _listen_address;\n uint16_t _port;\n std::unique_ptr<rpc_protocol_wrapper> _rpc;\n std::unique_ptr<rpc_protocol_server_wrapper> _server;\n std::unordered_map<shard_id, shard_info, shard_id::hash> _clients;\n uint64_t _dropped_messages[static_cast<int32_t>(messaging_verb::LAST)] = {};\npublic:\n messaging_service(gms::inet_address ip = gms::inet_address(\"0.0.0.0\"));\npublic:\n uint16_t port();\n gms::inet_address listen_address();\n future<> stop();\n static rpc::no_wait_type no_wait();\npublic:\n \/\/ Register a handler (a callback lambda) for verb\n template <typename Func>\n void register_handler(messaging_verb verb, Func&& func) {\n _rpc->register_handler(verb, std::move(func));\n }\n\n \/\/ Send a message for verb\n template <typename MsgIn, typename... MsgOut>\n auto send_message(messaging_verb verb, shard_id id, MsgOut&&... msg) {\n auto& rpc_client = get_rpc_client(id);\n auto rpc_handler = _rpc->make_client<MsgIn(MsgOut...)>(verb);\n return rpc_handler(rpc_client, std::forward<MsgOut>(msg)...).then_wrapped([this, id, verb] (auto&& f) {\n try {\n if (f.failed()) {\n this->increment_dropped_messages(verb);\n f.get();\n assert(false); \/\/ never reached\n }\n return std::move(f);\n } catch(...) {\n \/\/ FIXME: we need to distinguish between a transport error and\n \/\/ a server error.\n \/\/ remove_rpc_client(id);\n throw;\n }\n });\n }\n\n template <typename... MsgOut>\n auto send_message_oneway(messaging_verb verb, shard_id id, MsgOut&&... msg) {\n return send_message<rpc::no_wait_type>(std::move(verb), std::move(id), std::forward<MsgOut>(msg)...);\n }\n\n \/\/ Wrapper fro STREAM_INIT_MESSAGE verb\n future<unsigned> send_stream_init_message(shard_id id, streaming::messages::stream_init_message&& msg, unsigned src_cpu_id);\n void register_stream_init_message(std::function<future<unsigned> (streaming::messages::stream_init_message msg, unsigned src_cpu_id)>&& func);\n\nprivate:\n \/\/ Return rpc::protocol::client for a shard which is a ip + cpuid pair.\n rpc_protocol_client_wrapper& get_rpc_client(shard_id id);\n void remove_rpc_client(shard_id id);\n};\n\nextern distributed<messaging_service> _the_messaging_service;\n\ninline distributed<messaging_service>& get_messaging_service() {\n return _the_messaging_service;\n}\n\ninline messaging_service& get_local_messaging_service() {\n return _the_messaging_service.local();\n}\n\nfuture<> init_messaging_service(sstring listen_address, db::config::seed_provider_type seed_provider);\n} \/\/ namespace net\n<commit_msg>messaging_service: Fix read_serializable()<commit_after>\/*\n * Copyright (C) 2015 Cloudius Systems, Ltd.\n *\/\n\n#pragma once\n\n#include \"core\/reactor.hh\"\n#include \"core\/iostream.hh\"\n#include \"core\/distributed.hh\"\n#include \"core\/print.hh\"\n#include \"core\/sstring.hh\"\n#include \"net\/api.hh\"\n#include \"util\/serialization.hh\"\n#include \"gms\/inet_address.hh\"\n#include \"rpc\/rpc.hh\"\n#include <unordered_map>\n#include \"db\/config.hh\"\n#include \"frozen_mutation.hh\"\n#include \"query-request.hh\"\n#include \"db\/serializer.hh\"\n#include \"mutation_query.hh\"\n\n\/\/ forward declarations\nnamespace streaming { namespace messages {\n class stream_init_message;\n}}\n\nnamespace net {\n\n\/* All verb handler identifiers *\/\nenum class messaging_verb : int32_t {\n MUTATION,\n MUTATION_DONE,\n BINARY, \/\/ Deprecated\n READ_REPAIR,\n READ,\n READ_DATA,\n READ_MUTATION_DATA, \/\/ urchin-only\n READ_DIGEST,\n REQUEST_RESPONSE, \/\/ client-initiated reads and writes\n STREAM_INITIATE, \/\/ Deprecated\n STREAM_INITIATE_DONE, \/\/ Deprecated\n STREAM_REPLY, \/\/ Deprecated\n STREAM_REQUEST, \/\/ Deprecated\n RANGE_SLICE,\n BOOTSTRAP_TOKEN, \/\/ Deprecated\n TREE_REQUEST, \/\/ Deprecated\n TREE_RESPONSE, \/\/ Deprecated\n JOIN, \/\/ Deprecated\n GOSSIP_DIGEST_SYN,\n GOSSIP_DIGEST_ACK,\n GOSSIP_DIGEST_ACK2,\n DEFINITIONS_ANNOUNCE, \/\/ Deprecated\n DEFINITIONS_UPDATE,\n TRUNCATE,\n SCHEMA_CHECK,\n INDEX_SCAN, \/\/ Deprecated\n REPLICATION_FINISHED,\n INTERNAL_RESPONSE, \/\/ responses to internal calls\n COUNTER_MUTATION,\n STREAMING_REPAIR_REQUEST, \/\/ Deprecated\n STREAMING_REPAIR_RESPONSE, \/\/ Deprecated\n SNAPSHOT, \/\/ Similar to nt snapshot\n MIGRATION_REQUEST,\n GOSSIP_SHUTDOWN,\n _TRACE,\n ECHO,\n REPAIR_MESSAGE,\n PAXOS_PREPARE,\n PAXOS_PROPOSE,\n PAXOS_COMMIT,\n PAGED_RANGE,\n UNUSED_1,\n UNUSED_2,\n UNUSED_3,\n \/\/ Used by streaming\n STREAM_INIT_MESSAGE,\n PREPARE_MESSAGE,\n STREAM_MUTATION,\n INCOMING_FILE_MESSAGE,\n OUTGOING_FILE_MESSAGE,\n RECEIVED_MESSAGE,\n RETRY_MESSAGE,\n COMPLETE_MESSAGE,\n SESSION_FAILED_MESSAGE,\n LAST,\n};\n\n} \/\/ namespace net\n\nnamespace std {\ntemplate <>\nclass hash<net::messaging_verb> {\npublic:\n size_t operator()(const net::messaging_verb& x) const {\n return hash<int32_t>()(int32_t(x));\n }\n};\n} \/\/ namespace std\n\nnamespace net {\n\nfuture<> ser_messaging_verb(output_stream<char>& out, messaging_verb& v);\nfuture<> des_messaging_verb(input_stream<char>& in, messaging_verb& v);\nfuture<> ser_sstring(output_stream<char>& out, sstring& v);\nfuture<> des_sstring(input_stream<char>& in, sstring& v);\n\n\/\/ NOTE: operator(input_stream<char>&, T&) takes a reference to uninitialized\n\/\/ T object and should use placement new in case T is non POD\nstruct serializer {\n template<typename T>\n inline future<T> read_integral(input_stream<char>& in) {\n static_assert(std::is_integral<T>::value, \"T should be integral\");\n\n return in.read_exactly(sizeof(T)).then([] (temporary_buffer<char> buf) {\n if (buf.size() != sizeof(T)) {\n throw rpc::closed_error();\n }\n return make_ready_future<T>(net::ntoh(*unaligned_cast<T*>(buf.get())));\n });\n }\n\n \/\/ Adaptor for writing objects having db::serializer<>\n template<typename Serializable>\n inline future<> write_serializable(output_stream<char>& out, const Serializable& v) {\n db::serializer<Serializable> ser(v);\n bytes b(bytes::initialized_later(), ser.size() + data_output::serialized_size<uint32_t>());\n data_output d_out(b);\n d_out.write<uint32_t>(ser.size());\n ser.write(d_out);\n return out.write(reinterpret_cast<const char*>(b.c_str()), b.size());\n }\n\n \/\/ Adaptor for reading objects having db::serializer<>\n template<typename Serializable>\n inline future<> read_serializable(input_stream<char>& in, Serializable& v) {\n return read_integral<uint32_t>(in).then([&in, &v] (auto sz) mutable {\n return in.read_exactly(sz).then([sz, &v] (temporary_buffer<char> buf) mutable {\n if (buf.size() != sz) {\n throw rpc::closed_error();\n }\n bytes_view bv(reinterpret_cast<const int8_t*>(buf.get()), sz);\n data_input in(bv);\n new (&v) Serializable(db::serializer<Serializable>::read(in));\n });\n });\n }\n\n \/\/ For integer type\n template<typename T>\n inline auto operator()(output_stream<char>& out, T&& v, std::enable_if_t<std::is_integral<std::remove_reference_t<T>>::value, void*> = nullptr) {\n auto v_ = net::hton(v);\n return out.write(reinterpret_cast<const char*>(&v_), sizeof(T));\n }\n template<typename T>\n inline auto operator()(input_stream<char>& in, T& v, std::enable_if_t<std::is_integral<T>::value, void*> = nullptr) {\n return in.read_exactly(sizeof(v)).then([&v] (temporary_buffer<char> buf) mutable {\n if (buf.size() != sizeof(v)) {\n throw rpc::closed_error();\n }\n v = net::ntoh(*reinterpret_cast<const net::packed<T>*>(buf.get()));\n });\n }\n\n \/\/ For vectors\n template<typename T>\n inline auto operator()(output_stream<char>& out, std::vector<T>& v) {\n return operator()(out, v.size()).then([&out, &v, this] {\n return do_for_each(v.begin(), v.end(), [&out, this] (T& e) {\n return operator()(out, e);\n });\n });\n }\n template<typename T>\n inline auto operator()(input_stream<char>& in, std::vector<T>& v) {\n using size_type = typename std::vector<T>::size_type;\n return read_integral<size_type>(in).then([&v, &in, this] (size_type c) {\n new (&v) std::vector<T>;\n v.reserve(c);\n union U {\n U(){}\n ~U(){}\n U(U&&) {}\n T v;\n };\n return do_with(U(), [c, &v, &in, this] (U& u) {\n return do_until([c = c] () mutable {return !c--;}, [&v, &in, &u, this] () mutable {\n return operator()(in, u.v).then([&u, &v] {\n v.emplace_back(std::move(u.v));\n });\n });\n });\n });\n }\n\n \/\/ For messaging_verb\n inline auto operator()(output_stream<char>& out, messaging_verb& v) {\n return ser_messaging_verb(out, v);\n }\n inline auto operator()(input_stream<char>& in, messaging_verb& v) {\n return des_messaging_verb(in, v);\n }\n\n \/\/ For sstring\n inline auto operator()(output_stream<char>& out, sstring& v) {\n return ser_sstring(out, v);\n }\n inline auto operator()(input_stream<char>& in, sstring& v) {\n return des_sstring(in, v);\n }\n\n \/\/ For frozen_mutation\n inline auto operator()(output_stream<char>& out, const frozen_mutation& v) {\n return write_serializable(out, v);\n }\n inline auto operator()(output_stream<char>& out, frozen_mutation& v) {\n return write_serializable(out, v);\n }\n inline auto operator()(input_stream<char>& in, frozen_mutation& v) {\n return read_serializable(in, v);\n }\n\n \/\/ For reconcilable_result\n inline auto operator()(output_stream<char>& out, const reconcilable_result& v) {\n return write_serializable(out, v);\n }\n inline auto operator()(output_stream<char>& out, reconcilable_result& v) {\n return write_serializable(out, v);\n }\n inline auto operator()(input_stream<char>& in, reconcilable_result& v) {\n return read_serializable(in, v);\n }\n\n \/\/ For complex types which have serialize()\/deserialize(), e.g. gms::gossip_digest_syn, gms::gossip_digest_ack2\n template<typename T>\n inline auto operator()(output_stream<char>& out, T&& v, std::enable_if_t<!std::is_integral<std::remove_reference_t<T>>::value &&\n !std::is_enum<std::remove_reference_t<T>>::value, void*> = nullptr) {\n auto sz = serialize_int32_size + v.serialized_size();\n bytes b(bytes::initialized_later(), sz);\n auto _out = b.begin();\n serialize_int32(_out, int32_t(sz - serialize_int32_size));\n v.serialize(_out);\n return out.write(reinterpret_cast<const char*>(b.c_str()), sz);\n }\n template<typename T>\n inline auto operator()(input_stream<char>& in, T& v, std::enable_if_t<!std::is_integral<T>::value &&\n !std::is_enum<T>::value, void*> = nullptr) {\n return in.read_exactly(serialize_int32_size).then([&in, &v] (temporary_buffer<char> buf) mutable {\n if (buf.size() != serialize_int32_size) {\n throw rpc::closed_error();\n }\n size_t sz = net::ntoh(*reinterpret_cast<const net::packed<int32_t>*>(buf.get()));\n return in.read_exactly(sz).then([sz, &v] (temporary_buffer<char> buf) mutable {\n if (buf.size() != sz) {\n throw rpc::closed_error();\n }\n bytes_view bv(reinterpret_cast<const int8_t*>(buf.get()), sz);\n new (&v) T(T::deserialize(bv));\n assert(bv.size() == 0);\n return make_ready_future<>();\n });\n });\n }\n};\n\nstruct shard_id {\n gms::inet_address addr;\n uint32_t cpu_id;\n friend bool operator==(const shard_id& x, const shard_id& y);\n friend bool operator<(const shard_id& x, const shard_id& y);\n friend std::ostream& operator<<(std::ostream& os, const shard_id& x);\n struct hash {\n size_t operator()(const shard_id& id) const;\n };\n};\n\nclass messaging_service {\npublic:\n using shard_id = net::shard_id;\n\n using rpc_protocol = rpc::protocol<serializer, messaging_verb>;\n struct rpc_protocol_wrapper : public rpc_protocol { using rpc_protocol::rpc_protocol; };\n struct rpc_protocol_client_wrapper : public rpc_protocol::client { using rpc_protocol::client::client; };\n struct rpc_protocol_server_wrapper : public rpc_protocol::server { using rpc_protocol::server::server; };\n\n \/\/ FIXME: messaging service versioning\n static constexpr int32_t current_version = 0;\n\n struct shard_info {\n shard_info(std::unique_ptr<rpc_protocol_client_wrapper>&& client);\n std::unique_ptr<rpc_protocol_client_wrapper> rpc_client;\n };\n\n void foreach_client(std::function<void(const shard_id& id, const shard_info& info)> f) const;\n\n void increment_dropped_messages(messaging_verb verb);\n\n uint64_t get_dropped_messages(messaging_verb verb) const;\n\n const uint64_t* get_dropped_messages() const;\n\n int32_t get_raw_version(const gms::inet_address& endpoint) const;\n\n bool knows_version(const gms::inet_address& endpoint) const;\n\nprivate:\n static constexpr uint16_t _default_port = 7000;\n gms::inet_address _listen_address;\n uint16_t _port;\n std::unique_ptr<rpc_protocol_wrapper> _rpc;\n std::unique_ptr<rpc_protocol_server_wrapper> _server;\n std::unordered_map<shard_id, shard_info, shard_id::hash> _clients;\n uint64_t _dropped_messages[static_cast<int32_t>(messaging_verb::LAST)] = {};\npublic:\n messaging_service(gms::inet_address ip = gms::inet_address(\"0.0.0.0\"));\npublic:\n uint16_t port();\n gms::inet_address listen_address();\n future<> stop();\n static rpc::no_wait_type no_wait();\npublic:\n \/\/ Register a handler (a callback lambda) for verb\n template <typename Func>\n void register_handler(messaging_verb verb, Func&& func) {\n _rpc->register_handler(verb, std::move(func));\n }\n\n \/\/ Send a message for verb\n template <typename MsgIn, typename... MsgOut>\n auto send_message(messaging_verb verb, shard_id id, MsgOut&&... msg) {\n auto& rpc_client = get_rpc_client(id);\n auto rpc_handler = _rpc->make_client<MsgIn(MsgOut...)>(verb);\n return rpc_handler(rpc_client, std::forward<MsgOut>(msg)...).then_wrapped([this, id, verb] (auto&& f) {\n try {\n if (f.failed()) {\n this->increment_dropped_messages(verb);\n f.get();\n assert(false); \/\/ never reached\n }\n return std::move(f);\n } catch(...) {\n \/\/ FIXME: we need to distinguish between a transport error and\n \/\/ a server error.\n \/\/ remove_rpc_client(id);\n throw;\n }\n });\n }\n\n template <typename... MsgOut>\n auto send_message_oneway(messaging_verb verb, shard_id id, MsgOut&&... msg) {\n return send_message<rpc::no_wait_type>(std::move(verb), std::move(id), std::forward<MsgOut>(msg)...);\n }\n\n \/\/ Wrapper fro STREAM_INIT_MESSAGE verb\n future<unsigned> send_stream_init_message(shard_id id, streaming::messages::stream_init_message&& msg, unsigned src_cpu_id);\n void register_stream_init_message(std::function<future<unsigned> (streaming::messages::stream_init_message msg, unsigned src_cpu_id)>&& func);\n\nprivate:\n \/\/ Return rpc::protocol::client for a shard which is a ip + cpuid pair.\n rpc_protocol_client_wrapper& get_rpc_client(shard_id id);\n void remove_rpc_client(shard_id id);\n};\n\nextern distributed<messaging_service> _the_messaging_service;\n\ninline distributed<messaging_service>& get_messaging_service() {\n return _the_messaging_service;\n}\n\ninline messaging_service& get_local_messaging_service() {\n return _the_messaging_service.local();\n}\n\nfuture<> init_messaging_service(sstring listen_address, db::config::seed_provider_type seed_provider);\n} \/\/ namespace net\n<|endoftext|>"} {"text":"<commit_before>\/**************************************************************************\n * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *\n * *\n * Author: The ALICE Off-line Project. *\n * Contributors are mentioned in the code where appropriate. *\n * *\n * Permission to use, copy, modify and distribute this software and its *\n * documentation strictly for non-commercial purposes is hereby granted *\n * without fee, provided that the above copyright notice appears in all *\n * copies and that both the copyright notice and this permission notice *\n * appear in the supporting documentation. The authors make no claims *\n * about the suitability of this software for any purpose. It is *\n * provided \"as is\" without express or implied warranty. *\n **************************************************************************\/\n\n\/* $Id$ *\/\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ \/\/\n\/\/ class for T0 calibration TM--AM_6-02-2006 \/\/\n\/\/ \/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"AliT0CalibData.h\"\n#include \"AliT0LookUpValue.h\"\n#include \"AliT0LookUpKey.h\"\n#include \"AliLog.h\"\n\n#include <Riostream.h>\n\n\/\/#include <string>\n\nusing std::ifstream;\nClassImp(AliT0CalibData)\n\n\/\/________________________________________________________________\n AliT0CalibData::AliT0CalibData(): TNamed(),\n\t\t\t\t fLookup(0),\n\t\t\t\t fNumberOfTRMs(0)\n\n{\n \/\/\n}\n\n\/\/________________________________________________________________\nAliT0CalibData::AliT0CalibData(const char* name):TNamed(),\n\t\t\t\t fLookup(0),\n\t\t\t\t fNumberOfTRMs(0)\n{\n TString namst = \"Calib_\";\n namst += name;\n SetName(namst.Data());\n SetTitle(namst.Data());\n\n}\n\n\/\/________________________________________________________________\nAliT0CalibData::AliT0CalibData(const AliT0CalibData& calibda) :\n TNamed(calibda),\t\t\n fLookup(0),\n fNumberOfTRMs(0)\n\n{\n\/\/ copy constructor\n SetName(calibda.GetName());\n SetTitle(calibda.GetName());\n\n\n}\n\n\/\/________________________________________________________________\nAliT0CalibData &AliT0CalibData::operator =(const AliT0CalibData& calibda)\n{\n\/\/ assignment operator\n SetName(calibda.GetName());\n SetTitle(calibda.GetName());\n \n return *this;\n}\n\n\/\/________________________________________________________________\nAliT0CalibData::~AliT0CalibData()\n{\n \/\/\n}\n\/\/________________________________________________________________\nvoid AliT0CalibData::PrintLookup(Option_t*, Int_t iTRM, Int_t iTDC, Int_t iChannel) const\n{\n \/\/ print lookup table\n\n AliT0LookUpKey* lookkey; \/\/= new AliT0LookUpKey();\n AliT0LookUpValue* lookvalue= new AliT0LookUpValue();\n printf(\"Number Of TRMs in setup %i\\n\",GetNumberOfTRMs());\n\n iTRM=0; iTDC=0; Int_t chain=0; iChannel=0;\n\n for (Int_t ik=0; ik<105; ik++){\n lookvalue->SetTRM(iTRM);\n lookvalue->SetTDC(iTDC);\n lookvalue->SetChain(chain);\n lookvalue->SetChannel(iChannel);\n \n if (iChannel<6) iChannel +=2;\n else {iChannel = 0; iTDC++;}\n if(ik==57) { iTDC=0; iChannel=0; iTRM=1;}\n \n printf(\" AliT0CalibData::PrintLookup ::start GetValue %i %i %i %i\\n\",iTRM, iTDC,chain, iChannel);\n lookkey = (AliT0LookUpKey*) fLookup.GetValue((TObject*)lookvalue);\n \/\/ TString name= lookkey->GetChannelName();\n \/\/ cout<<name.Data()<<endl;\n if (lookkey)\n {\n\tTString name= lookkey->GetChannelName();\n\t\/*\tcout<<\" lookup KEY!!! \"<<name.Data()<<\" \"<<lookkey->GetKey()<<\" VALUE \"<<lookvalue->GetTRM()<<\" \"\n\t <<lookvalue->GetTDC()<<\" \"\n\t << lookvalue->GetChain()<<\" \"\n\t <<lookvalue->GetChannel()<<endl;*\/\n }\n }\n \n}\n\/\/________________________________________________________________\n\nvoid AliT0CalibData::ReadAsciiLookup(const Char_t *filename)\n{\n \/\/ read lookup table from ascii file\n\n Int_t key, trm, tdc, chain, channel;\n\n if(filename == 0){\n AliError(Form(\"Please, specify file with database\")) ;\n return ;\n }\n cout<<\" read file \"<<filename<<endl;\n\n ifstream lookup;\n lookup.open(filename);\n if(!lookup)\n {\n AliError(Form(\"!!!!!!!!!!!!!!No look up table in CDB!\" ));\n \n }\n Char_t varname[11];\n Int_t ntrms;\n if(lookup)\n {\n lookup>>ntrms;\n \/\/ fNumberOfTRMs=ntrms;\n SetNumberOfTRMs(ntrms);\n cout<<\" N TRMS \"<<ntrms<<endl;\n while(!lookup.eof())\n\t{\n\t AliT0LookUpKey * lookkey= new AliT0LookUpKey();\n\t AliT0LookUpValue * lookvalue= new AliT0LookUpValue();\n\t \n\t lookup>>varname>>key>>trm>>chain>>tdc>>channel;\n\t lookvalue->SetTRM(trm);\n\t lookvalue->SetTDC(tdc);\n\t lookvalue->SetChain(chain);\n\t lookvalue->SetChannel(channel);\n\t lookkey->SetKey(key);\n\t lookkey->SetChannelName(varname);\n\t cout<<trm<<\" \"<<chain<<\" \"<<tdc<<\" \"<<channel<<\" \"<<key<<\" \"<<varname<<endl;\n\t fLookup.Add((TObject*)lookvalue,(TObject*)lookkey);\n\t \n\t}\n \n lookup.close();\n \n }\n}\n\/\/________________________________________________________________\n\nInt_t AliT0CalibData::GetChannel(Int_t trm, Int_t tdc, Int_t chain, Int_t channel)\n{\n \/\/ read number of channel according physical addres \n\n\n AliT0LookUpKey * lookkey;\/\/= new AliT0LookUpKey();\n AliT0LookUpValue * lookvalue= new AliT0LookUpValue(trm,tdc,chain,channel);\n\n lookkey = (AliT0LookUpKey*) fLookup.GetValue((TObject*)lookvalue);\n\n return lookkey->GetKey();\n\n}\n\n<commit_msg>some c++11 fixes<commit_after>\/**************************************************************************\n * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *\n * *\n * Author: The ALICE Off-line Project. *\n * Contributors are mentioned in the code where appropriate. *\n * *\n * Permission to use, copy, modify and distribute this software and its *\n * documentation strictly for non-commercial purposes is hereby granted *\n * without fee, provided that the above copyright notice appears in all *\n * copies and that both the copyright notice and this permission notice *\n * appear in the supporting documentation. The authors make no claims *\n * about the suitability of this software for any purpose. It is *\n * provided \"as is\" without express or implied warranty. *\n **************************************************************************\/\n\n\/* $Id$ *\/\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ \/\/\n\/\/ class for T0 calibration TM--AM_6-02-2006 \/\/\n\/\/ \/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"AliT0CalibData.h\"\n#include \"AliT0LookUpValue.h\"\n#include \"AliT0LookUpKey.h\"\n#include \"AliLog.h\"\n\n#include <Riostream.h>\n\n\/\/#include <string>\n\nusing std::ifstream;\nusing std::cout;\nusing std::endl;\n\nClassImp(AliT0CalibData)\n\n\/\/________________________________________________________________\n AliT0CalibData::AliT0CalibData(): TNamed(),\n\t\t\t\t fLookup(0),\n\t\t\t\t fNumberOfTRMs(0)\n\n{\n \/\/\n}\n\n\/\/________________________________________________________________\nAliT0CalibData::AliT0CalibData(const char* name):TNamed(),\n\t\t\t\t fLookup(0),\n\t\t\t\t fNumberOfTRMs(0)\n{\n TString namst = \"Calib_\";\n namst += name;\n SetName(namst.Data());\n SetTitle(namst.Data());\n\n}\n\n\/\/________________________________________________________________\nAliT0CalibData::AliT0CalibData(const AliT0CalibData& calibda) :\n TNamed(calibda),\t\t\n fLookup(0),\n fNumberOfTRMs(0)\n\n{\n\/\/ copy constructor\n SetName(calibda.GetName());\n SetTitle(calibda.GetName());\n\n\n}\n\n\/\/________________________________________________________________\nAliT0CalibData &AliT0CalibData::operator =(const AliT0CalibData& calibda)\n{\n\/\/ assignment operator\n SetName(calibda.GetName());\n SetTitle(calibda.GetName());\n \n return *this;\n}\n\n\/\/________________________________________________________________\nAliT0CalibData::~AliT0CalibData()\n{\n \/\/\n}\n\/\/________________________________________________________________\nvoid AliT0CalibData::PrintLookup(Option_t*, Int_t iTRM, Int_t iTDC, Int_t iChannel) const\n{\n \/\/ print lookup table\n\n AliT0LookUpKey* lookkey; \/\/= new AliT0LookUpKey();\n AliT0LookUpValue* lookvalue= new AliT0LookUpValue();\n printf(\"Number Of TRMs in setup %i\\n\",GetNumberOfTRMs());\n\n iTRM=0; iTDC=0; Int_t chain=0; iChannel=0;\n\n for (Int_t ik=0; ik<105; ik++){\n lookvalue->SetTRM(iTRM);\n lookvalue->SetTDC(iTDC);\n lookvalue->SetChain(chain);\n lookvalue->SetChannel(iChannel);\n \n if (iChannel<6) iChannel +=2;\n else {iChannel = 0; iTDC++;}\n if(ik==57) { iTDC=0; iChannel=0; iTRM=1;}\n \n printf(\" AliT0CalibData::PrintLookup ::start GetValue %i %i %i %i\\n\",iTRM, iTDC,chain, iChannel);\n lookkey = (AliT0LookUpKey*) fLookup.GetValue((TObject*)lookvalue);\n \/\/ TString name= lookkey->GetChannelName();\n \/\/ cout<<name.Data()<<endl;\n if (lookkey)\n {\n\tTString name= lookkey->GetChannelName();\n\t\/*\tcout<<\" lookup KEY!!! \"<<name.Data()<<\" \"<<lookkey->GetKey()<<\" VALUE \"<<lookvalue->GetTRM()<<\" \"\n\t <<lookvalue->GetTDC()<<\" \"\n\t << lookvalue->GetChain()<<\" \"\n\t <<lookvalue->GetChannel()<<endl;*\/\n }\n }\n \n}\n\/\/________________________________________________________________\n\nvoid AliT0CalibData::ReadAsciiLookup(const Char_t *filename)\n{\n \/\/ read lookup table from ascii file\n\n Int_t key, trm, tdc, chain, channel;\n\n if(filename == 0){\n AliError(Form(\"Please, specify file with database\")) ;\n return ;\n }\n cout<<\" read file \"<<filename<<endl;\n\n ifstream lookup;\n lookup.open(filename);\n if(!lookup)\n {\n AliError(Form(\"!!!!!!!!!!!!!!No look up table in CDB!\" ));\n \n }\n Char_t varname[11];\n Int_t ntrms;\n if(lookup)\n {\n lookup>>ntrms;\n \/\/ fNumberOfTRMs=ntrms;\n SetNumberOfTRMs(ntrms);\n cout<<\" N TRMS \"<<ntrms<<endl;\n while(!lookup.eof())\n\t{\n\t AliT0LookUpKey * lookkey= new AliT0LookUpKey();\n\t AliT0LookUpValue * lookvalue= new AliT0LookUpValue();\n\t \n\t lookup>>varname>>key>>trm>>chain>>tdc>>channel;\n\t lookvalue->SetTRM(trm);\n\t lookvalue->SetTDC(tdc);\n\t lookvalue->SetChain(chain);\n\t lookvalue->SetChannel(channel);\n\t lookkey->SetKey(key);\n\t lookkey->SetChannelName(varname);\n\t cout<<trm<<\" \"<<chain<<\" \"<<tdc<<\" \"<<channel<<\" \"<<key<<\" \"<<varname<<endl;\n\t fLookup.Add((TObject*)lookvalue,(TObject*)lookkey);\n\t \n\t}\n \n lookup.close();\n \n }\n}\n\/\/________________________________________________________________\n\nInt_t AliT0CalibData::GetChannel(Int_t trm, Int_t tdc, Int_t chain, Int_t channel)\n{\n \/\/ read number of channel according physical addres \n\n\n AliT0LookUpKey * lookkey;\/\/= new AliT0LookUpKey();\n AliT0LookUpValue * lookvalue= new AliT0LookUpValue(trm,tdc,chain,channel);\n\n lookkey = (AliT0LookUpKey*) fLookup.GetValue((TObject*)lookvalue);\n\n return lookkey->GetKey();\n\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: rtl_old_teststrbuf.cxx,v $\n *\n * $Revision: 1.4 $\n *\n * last change: $Author: rt $ $Date: 2005-09-08 15:58:52 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\/\/ LLA:\n\/\/ this file is converted to use with testshl2\n\/\/ original was placed in sal\/test\/textenc.cxx\n\n\n\/\/ -----------------------------------------------------------------------------\n\n#include <string.h>\n#include <stdio.h>\n\n\/\/ #ifndef _OSL_DIAGNOSE_H_\n\/\/ #include <osl\/diagnose.h>\n\/\/ #endif\n\n#ifndef _RTL_STRBUF_HXX\n#include <rtl\/strbuf.hxx>\n#endif\n\n#ifndef _RTL_WSTRBUF_HXX\n#include <rtl\/ustrbuf.hxx>\n#endif\n\n#include <cppunit\/simpleheader.hxx>\n\nusing namespace rtl;\n\n#define TEST_ENSURE(c, m) CPPUNIT_ASSERT_MESSAGE((m), (c))\n\n\/\/ #if OSL_DEBUG_LEVEL > 0\n\/\/ #define TEST_ENSHURE(c, m) OSL_ENSURE(c, m)\n\/\/ #else\n\/\/ #define TEST_ENSHURE(c, m) OSL_VERIFY(c)\n\/\/ #endif\n\n\/\/ -----------------------------------------------------------------------------\nnamespace rtl_OStringBuffer\n{\n class oldtests : public CppUnit::TestFixture\n {\n public:\n void test_OStringBuffer();\n\n CPPUNIT_TEST_SUITE( oldtests );\n CPPUNIT_TEST( test_OStringBuffer );\n CPPUNIT_TEST_SUITE_END( );\n };\n\n\nvoid oldtests::test_OStringBuffer()\n{\n \/\/ \"Mein erster RTL OString\\n\"\n \/\/ | | | | |\n \/\/ Index 0 5 10 15 20\n OString s1(\"Mein erster RTL OString\\n\");\n\n OStringBuffer b1(s1);\n\n TEST_ENSURE( b1.getCapacity() == 16 + s1.getLength(), \"test_OStringBuffer error 1\");\n\n b1.insert(b1.getLength() - 1, \"Buffer\");\n s1 = \"Mein erster RTL OStringBuffer\\n\";\n TEST_ENSURE( s1 == b1.getStr(), \"test_OStringBuffer error 2\");\n\n b1.insert(b1.getLength() - 1, \" ist viel zu gross fuer den alten Buffer\");\n TEST_ENSURE( b1.getCapacity() == b1.getLength(), \"test_OStringBuffer error 3\");\n\n OStringBuffer b2(30);\n\n s1 = \"false\";\n sal_Bool b = sal_False;\n b2.append(b);\n TEST_ENSURE( s1 == b2.getStr(), \"test_OStringBuffer error 4\");\n\n sal_Int32 n = 123456789L;\n s1 += \" 123456789\";\n b2.append(\" \");\n b2.append(n);\n TEST_ENSURE( s1 == b2.getStr(), \"test_OStringBuffer error 5\");\n\n#ifndef SAL_OS2\n#ifdef SAL_UNX\n sal_Int64 m = -3223372036854775807LL;\n#elif defined(SAL_OS2)\n sal_Int64 m;\n sal_setInt64(&m, 3965190145L, -750499787L);\n#else\n sal_Int64 m = -3223372036854775807;\n#endif\n s1 += \" -3223372036854775807\";\n b2.append(\" \");\n b2.append(m);\n TEST_ENSURE( s1 == b2.getStr(), \"test_OStringBuffer error 6\");\n#endif\n\n OString s2(b2.makeStringAndClear());\n TEST_ENSURE( s1 == s2, \"test_OStringBuffer error 7\");\n\n b2.ensureCapacity(50);\n TEST_ENSURE( b2.getCapacity() == 50, \"test_OStringBuffer error 8\");\n\n b2.append(\"Hier fuege ich jetzt ein > <\\n\");\n b2.insert(26, \" Hallo\");\n s2 = \"Hier fuege ich jetzt ein > Hallo <\\n\";\n TEST_ENSURE( s2 == b2.getStr(), \"test_OStringBuffer error 9\");\n\n b2.insert(26, b);\n b2.insert(26, \" \");\n s2 = \"Hier fuege ich jetzt ein > false Hallo <\\n\";\n TEST_ENSURE( s2 == b2.getStr(), \"test_OStringBuffer error 10\");\n\n b2.insert(26, n);\n b2.insert(26, \" \");\n s2 = \"Hier fuege ich jetzt ein > 123456789 false Hallo <\\n\";\n TEST_ENSURE( s2 == b2.getStr(), \"test_OStringBuffer error 11\");\n\n#ifndef SAL_OS2\n b2.insert(26, m);\n b2.insert(26, \" \");\n s2 = \"Hier fuege ich jetzt ein > -3223372036854775807 123456789 false Hallo <\\n\";\n TEST_ENSURE( s2 == b2.getStr(), \"test_OStringBuffer error 12\");\n#endif\n\n printf(\"test_OStringBuffer OK !!!\\n\");\n return;\n}\n} \/\/ namespace rtl_OStringBuffer\n\n\/\/ -----------------------------------------------------------------------------\n\nnamespace rtl_OUStringBuffer\n{\n class oldtests : public CppUnit::TestFixture\n {\n public:\n void test_OUStringBuffer();\n\n CPPUNIT_TEST_SUITE( oldtests );\n CPPUNIT_TEST( test_OUStringBuffer );\n CPPUNIT_TEST_SUITE_END( );\n };\n\n\nvoid oldtests::test_OUStringBuffer()\n{\n \/\/ \"Mein erster RTL OUString\\n\"\n \/\/ | | | | |\n \/\/ Index 0 5 10 15 20\n OUString s1(OUString::createFromAscii(\"Mein erster RTL OUString\\n\"));\n\n OUStringBuffer b1(s1);\n\n TEST_ENSURE( b1.getCapacity() == 16 + s1.getLength(), \"test_OWStringBuffer error 1\");\n\n b1.insert(b1.getLength() - 1, OUString::createFromAscii(\"Buffer\"));\n s1 = OUString::createFromAscii(\"Mein erster RTL OUStringBuffer\\n\");\n TEST_ENSURE( s1 == b1.getStr(), \"test_OWStringBuffer error 2\");\n\n b1.insert(b1.getLength() - 1, OUString::createFromAscii(\" ist viel zu gross fuer den alten Buffer\"));\n \/\/TEST_ENSURE( b1.getCapacity() == b1.getLength(), \"test_OWStringBuffer error 3\");\n\n OUStringBuffer b2(30);\n\n s1 = OUString::createFromAscii(\"false\");\n sal_Bool b = sal_False;\n b2.append(b);\n TEST_ENSURE( s1 == b2.getStr(), \"test_OWStringBuffer error 4\");\n\n sal_Int32 n = 123456789L;\n s1 += OUString::createFromAscii(\" 123456789\");\n b2.append(OUString::createFromAscii(\" \"));\n b2.append(n);\n TEST_ENSURE( s1 == b2.getStr(), \"test_OWStringBuffer error 5\");\n\n#ifndef SAL_OS2\n#ifdef SAL_UNX\n sal_Int64 m = -3223372036854775807LL;\n#elif defined(SAL_OS2)\n sal_Int64 m;\n sal_setInt64(&m, 3965190145L, -750499787L);\n#else\n sal_Int64 m = -3223372036854775807;\n#endif\n s1 += OUString::createFromAscii(\" -3223372036854775807\");\n b2.append(OUString::createFromAscii(\" \"));\n b2.append(m);\n TEST_ENSURE( s1 == b2.getStr(), \"test_OWStringBuffer error 6\");\n#endif\n\n OUString s2(b2.makeStringAndClear());\n TEST_ENSURE( s1 == s2, \"test_OWStringBuffer error 7\");\n\n b2.ensureCapacity(50);\n TEST_ENSURE( b2.getCapacity() == 50, \"test_OWStringBuffer error 8\");\n\n b2.append(OUString::createFromAscii(\"Hier fuege ich jetzt ein > <\\n\"));\n b2.insert(26, OUString::createFromAscii(\" Hallo\"));\n s2 = OUString::createFromAscii(\"Hier fuege ich jetzt ein > Hallo <\\n\");\n TEST_ENSURE( s2 == b2.getStr(), \"test_OWStringBuffer error 9\");\n\n b2.insert(26, b);\n b2.insert(26, OUString::createFromAscii(\" \"));\n s2 = OUString::createFromAscii(\"Hier fuege ich jetzt ein > false Hallo <\\n\");\n TEST_ENSURE( s2 == b2.getStr(), \"test_OWStringBuffer error 10\");\n\n b2.insert(26, n);\n b2.insert(26, OUString::createFromAscii(\" \"));\n s2 = OUString::createFromAscii(\"Hier fuege ich jetzt ein > 123456789 false Hallo <\\n\");\n TEST_ENSURE( s2 == b2.getStr(), \"test_OWStringBuffer error 11\");\n\n#ifndef SAL_OS2\n b2.insert(26, m);\n b2.insert(26, OUString::createFromAscii(\" \"));\n s2 = OUString::createFromAscii(\"Hier fuege ich jetzt ein > -3223372036854775807 123456789 false Hallo <\\n\");\n TEST_ENSURE( s2 == b2.getStr(), \"test_OWStringBuffer error 12\");\n#endif\n\n \/\/ ASCII-Schnittstelle, AB 15.10.1999\n OUString s3(OUString::createFromAscii(\"Noch'n RTL OUString\"));\n OUStringBuffer b3(s3);\n sal_Char aAsciiStr[] = \" mit appendetem ASCII\\n\";\n b3.appendAscii( aAsciiStr );\n s3 = OUString::createFromAscii(\"Noch'n RTL OUString mit appendetem ASCII\\n\");\n TEST_ENSURE( b3.getStr() == s3 , \"test_OWStringBuffer error 13\");\n\n\n\n printf(\"test_OWStringBuffer OK !!!\\n\");\n return;\n}\n\n} \/\/ namespace rtl_OUStringBuffer\n\n\n\/\/ -----------------------------------------------------------------------------\nCPPUNIT_TEST_SUITE_NAMED_REGISTRATION( rtl_OUStringBuffer::oldtests, \"rtl_OUStringBuffer\" );\nCPPUNIT_TEST_SUITE_NAMED_REGISTRATION( rtl_OStringBuffer::oldtests, \"rtl_OStringBuffer\" );\n\n\/\/ -----------------------------------------------------------------------------\nNOADDITIONAL;\n<commit_msg>INTEGRATION: CWS pchfix02 (1.4.140); FILE MERGED 2006\/09\/01 17:34:16 kaib 1.4.140.1: #i68856# Added header markers and pch files<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: rtl_old_teststrbuf.cxx,v $\n *\n * $Revision: 1.5 $\n *\n * last change: $Author: obo $ $Date: 2006-09-17 09:03:29 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_sal.hxx\"\n\n\/\/ LLA:\n\/\/ this file is converted to use with testshl2\n\/\/ original was placed in sal\/test\/textenc.cxx\n\n\n\/\/ -----------------------------------------------------------------------------\n\n#include <string.h>\n#include <stdio.h>\n\n\/\/ #ifndef _OSL_DIAGNOSE_H_\n\/\/ #include <osl\/diagnose.h>\n\/\/ #endif\n\n#ifndef _RTL_STRBUF_HXX\n#include <rtl\/strbuf.hxx>\n#endif\n\n#ifndef _RTL_WSTRBUF_HXX\n#include <rtl\/ustrbuf.hxx>\n#endif\n\n#include <cppunit\/simpleheader.hxx>\n\nusing namespace rtl;\n\n#define TEST_ENSURE(c, m) CPPUNIT_ASSERT_MESSAGE((m), (c))\n\n\/\/ #if OSL_DEBUG_LEVEL > 0\n\/\/ #define TEST_ENSHURE(c, m) OSL_ENSURE(c, m)\n\/\/ #else\n\/\/ #define TEST_ENSHURE(c, m) OSL_VERIFY(c)\n\/\/ #endif\n\n\/\/ -----------------------------------------------------------------------------\nnamespace rtl_OStringBuffer\n{\n class oldtests : public CppUnit::TestFixture\n {\n public:\n void test_OStringBuffer();\n\n CPPUNIT_TEST_SUITE( oldtests );\n CPPUNIT_TEST( test_OStringBuffer );\n CPPUNIT_TEST_SUITE_END( );\n };\n\n\nvoid oldtests::test_OStringBuffer()\n{\n \/\/ \"Mein erster RTL OString\\n\"\n \/\/ | | | | |\n \/\/ Index 0 5 10 15 20\n OString s1(\"Mein erster RTL OString\\n\");\n\n OStringBuffer b1(s1);\n\n TEST_ENSURE( b1.getCapacity() == 16 + s1.getLength(), \"test_OStringBuffer error 1\");\n\n b1.insert(b1.getLength() - 1, \"Buffer\");\n s1 = \"Mein erster RTL OStringBuffer\\n\";\n TEST_ENSURE( s1 == b1.getStr(), \"test_OStringBuffer error 2\");\n\n b1.insert(b1.getLength() - 1, \" ist viel zu gross fuer den alten Buffer\");\n TEST_ENSURE( b1.getCapacity() == b1.getLength(), \"test_OStringBuffer error 3\");\n\n OStringBuffer b2(30);\n\n s1 = \"false\";\n sal_Bool b = sal_False;\n b2.append(b);\n TEST_ENSURE( s1 == b2.getStr(), \"test_OStringBuffer error 4\");\n\n sal_Int32 n = 123456789L;\n s1 += \" 123456789\";\n b2.append(\" \");\n b2.append(n);\n TEST_ENSURE( s1 == b2.getStr(), \"test_OStringBuffer error 5\");\n\n#ifndef SAL_OS2\n#ifdef SAL_UNX\n sal_Int64 m = -3223372036854775807LL;\n#elif defined(SAL_OS2)\n sal_Int64 m;\n sal_setInt64(&m, 3965190145L, -750499787L);\n#else\n sal_Int64 m = -3223372036854775807;\n#endif\n s1 += \" -3223372036854775807\";\n b2.append(\" \");\n b2.append(m);\n TEST_ENSURE( s1 == b2.getStr(), \"test_OStringBuffer error 6\");\n#endif\n\n OString s2(b2.makeStringAndClear());\n TEST_ENSURE( s1 == s2, \"test_OStringBuffer error 7\");\n\n b2.ensureCapacity(50);\n TEST_ENSURE( b2.getCapacity() == 50, \"test_OStringBuffer error 8\");\n\n b2.append(\"Hier fuege ich jetzt ein > <\\n\");\n b2.insert(26, \" Hallo\");\n s2 = \"Hier fuege ich jetzt ein > Hallo <\\n\";\n TEST_ENSURE( s2 == b2.getStr(), \"test_OStringBuffer error 9\");\n\n b2.insert(26, b);\n b2.insert(26, \" \");\n s2 = \"Hier fuege ich jetzt ein > false Hallo <\\n\";\n TEST_ENSURE( s2 == b2.getStr(), \"test_OStringBuffer error 10\");\n\n b2.insert(26, n);\n b2.insert(26, \" \");\n s2 = \"Hier fuege ich jetzt ein > 123456789 false Hallo <\\n\";\n TEST_ENSURE( s2 == b2.getStr(), \"test_OStringBuffer error 11\");\n\n#ifndef SAL_OS2\n b2.insert(26, m);\n b2.insert(26, \" \");\n s2 = \"Hier fuege ich jetzt ein > -3223372036854775807 123456789 false Hallo <\\n\";\n TEST_ENSURE( s2 == b2.getStr(), \"test_OStringBuffer error 12\");\n#endif\n\n printf(\"test_OStringBuffer OK !!!\\n\");\n return;\n}\n} \/\/ namespace rtl_OStringBuffer\n\n\/\/ -----------------------------------------------------------------------------\n\nnamespace rtl_OUStringBuffer\n{\n class oldtests : public CppUnit::TestFixture\n {\n public:\n void test_OUStringBuffer();\n\n CPPUNIT_TEST_SUITE( oldtests );\n CPPUNIT_TEST( test_OUStringBuffer );\n CPPUNIT_TEST_SUITE_END( );\n };\n\n\nvoid oldtests::test_OUStringBuffer()\n{\n \/\/ \"Mein erster RTL OUString\\n\"\n \/\/ | | | | |\n \/\/ Index 0 5 10 15 20\n OUString s1(OUString::createFromAscii(\"Mein erster RTL OUString\\n\"));\n\n OUStringBuffer b1(s1);\n\n TEST_ENSURE( b1.getCapacity() == 16 + s1.getLength(), \"test_OWStringBuffer error 1\");\n\n b1.insert(b1.getLength() - 1, OUString::createFromAscii(\"Buffer\"));\n s1 = OUString::createFromAscii(\"Mein erster RTL OUStringBuffer\\n\");\n TEST_ENSURE( s1 == b1.getStr(), \"test_OWStringBuffer error 2\");\n\n b1.insert(b1.getLength() - 1, OUString::createFromAscii(\" ist viel zu gross fuer den alten Buffer\"));\n \/\/TEST_ENSURE( b1.getCapacity() == b1.getLength(), \"test_OWStringBuffer error 3\");\n\n OUStringBuffer b2(30);\n\n s1 = OUString::createFromAscii(\"false\");\n sal_Bool b = sal_False;\n b2.append(b);\n TEST_ENSURE( s1 == b2.getStr(), \"test_OWStringBuffer error 4\");\n\n sal_Int32 n = 123456789L;\n s1 += OUString::createFromAscii(\" 123456789\");\n b2.append(OUString::createFromAscii(\" \"));\n b2.append(n);\n TEST_ENSURE( s1 == b2.getStr(), \"test_OWStringBuffer error 5\");\n\n#ifndef SAL_OS2\n#ifdef SAL_UNX\n sal_Int64 m = -3223372036854775807LL;\n#elif defined(SAL_OS2)\n sal_Int64 m;\n sal_setInt64(&m, 3965190145L, -750499787L);\n#else\n sal_Int64 m = -3223372036854775807;\n#endif\n s1 += OUString::createFromAscii(\" -3223372036854775807\");\n b2.append(OUString::createFromAscii(\" \"));\n b2.append(m);\n TEST_ENSURE( s1 == b2.getStr(), \"test_OWStringBuffer error 6\");\n#endif\n\n OUString s2(b2.makeStringAndClear());\n TEST_ENSURE( s1 == s2, \"test_OWStringBuffer error 7\");\n\n b2.ensureCapacity(50);\n TEST_ENSURE( b2.getCapacity() == 50, \"test_OWStringBuffer error 8\");\n\n b2.append(OUString::createFromAscii(\"Hier fuege ich jetzt ein > <\\n\"));\n b2.insert(26, OUString::createFromAscii(\" Hallo\"));\n s2 = OUString::createFromAscii(\"Hier fuege ich jetzt ein > Hallo <\\n\");\n TEST_ENSURE( s2 == b2.getStr(), \"test_OWStringBuffer error 9\");\n\n b2.insert(26, b);\n b2.insert(26, OUString::createFromAscii(\" \"));\n s2 = OUString::createFromAscii(\"Hier fuege ich jetzt ein > false Hallo <\\n\");\n TEST_ENSURE( s2 == b2.getStr(), \"test_OWStringBuffer error 10\");\n\n b2.insert(26, n);\n b2.insert(26, OUString::createFromAscii(\" \"));\n s2 = OUString::createFromAscii(\"Hier fuege ich jetzt ein > 123456789 false Hallo <\\n\");\n TEST_ENSURE( s2 == b2.getStr(), \"test_OWStringBuffer error 11\");\n\n#ifndef SAL_OS2\n b2.insert(26, m);\n b2.insert(26, OUString::createFromAscii(\" \"));\n s2 = OUString::createFromAscii(\"Hier fuege ich jetzt ein > -3223372036854775807 123456789 false Hallo <\\n\");\n TEST_ENSURE( s2 == b2.getStr(), \"test_OWStringBuffer error 12\");\n#endif\n\n \/\/ ASCII-Schnittstelle, AB 15.10.1999\n OUString s3(OUString::createFromAscii(\"Noch'n RTL OUString\"));\n OUStringBuffer b3(s3);\n sal_Char aAsciiStr[] = \" mit appendetem ASCII\\n\";\n b3.appendAscii( aAsciiStr );\n s3 = OUString::createFromAscii(\"Noch'n RTL OUString mit appendetem ASCII\\n\");\n TEST_ENSURE( b3.getStr() == s3 , \"test_OWStringBuffer error 13\");\n\n\n\n printf(\"test_OWStringBuffer OK !!!\\n\");\n return;\n}\n\n} \/\/ namespace rtl_OUStringBuffer\n\n\n\/\/ -----------------------------------------------------------------------------\nCPPUNIT_TEST_SUITE_NAMED_REGISTRATION( rtl_OUStringBuffer::oldtests, \"rtl_OUStringBuffer\" );\nCPPUNIT_TEST_SUITE_NAMED_REGISTRATION( rtl_OStringBuffer::oldtests, \"rtl_OStringBuffer\" );\n\n\/\/ -----------------------------------------------------------------------------\nNOADDITIONAL;\n<|endoftext|>"} {"text":"<commit_before>\/* bzflag\n * Copyright (c) 1993 - 2005 Tim Riker\n *\n * This package is free software; you can redistribute it and\/or\n * modify it under the terms of the license found in the file\n * named COPYING that should have accompanied this file.\n *\n * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR\n * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED\n * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.\n *\/\n\n#include \"XDisplay.h\"\n#include \"XWindow.h\"\n#include \"BzfEvent.h\"\n#include <string.h>\n#include <X11\/keysym.h>\n\n\/\/\n\/\/ XDisplay::Rep\n\/\/\n\nXDisplay::Rep::Rep(const char* displayName) :\n\t\t\t\trefCount(1),\n\t\t\t\tdisplay(NULL),\n\t\t\t\tscreen(0)\n{\n \/\/ open display\n display = XOpenDisplay(displayName);\n if (!display) return;\n\n \/\/ other initialization\n screen = DefaultScreen(display);\n}\n\nXDisplay::Rep::~Rep()\n{\n if (display) XCloseDisplay(display);\n}\n\nvoid\t\t\tXDisplay::Rep::ref()\n{\n refCount++;\n}\n\nvoid\t\t\tXDisplay::Rep::unref()\n{\n if (--refCount <= 0) delete this;\n}\n\nWindow\t\t\tXDisplay::Rep::getRootWindow() const\n{\n return display ? RootWindow(display, screen) : None;\n}\n\n\/\/\n\/\/ XDisplay\n\/\/\n\nXDisplay::XDisplay(const char* displayName, XDisplayMode* _mode) :\n\t\t\t\trep(NULL),\n\t\t\t\tmode(_mode)\n{\n \/\/ open display\n rep = new Rep(displayName);\n\n \/\/ make default mode changer if one wasn't supplied\n if (!mode)\n mode = new XDisplayMode;\n\n if (rep->getDisplay()) {\n \/\/ get resolutions\n int numModes, currentMode;\n ResInfo** resInfo = mode->init(this, numModes, currentMode);\n\n \/\/ if no modes then make default\n if (!resInfo) {\n resInfo = new ResInfo*[1];\n resInfo[0] = new ResInfo(\"default\",\n\t\t\tDisplayWidth(rep->getDisplay(), rep->getScreen()),\n\t\t\tDisplayHeight(rep->getDisplay(), rep->getScreen()), 0);\n numModes = 1;\n currentMode = 0;\n }\n\n \/\/ register modes\n initResolutions(resInfo, numModes, currentMode);\n }\n}\n\nXDisplay::~XDisplay()\n{\n setDefaultResolution();\n delete mode;\n rep->unref();\n}\n\nbool\t\t\tXDisplay::isValid() const\n{\n return rep->getDisplay() != NULL;\n}\n\nbool\t\t\tXDisplay::isEventPending() const\n{\n return (XPending(rep->getDisplay()) != 0);\n}\n\nbool\t\t\tXDisplay::peekEvent(BzfEvent& event) const\n{\n return false;\n}\n\nbool\t\t\tXDisplay::getEvent(BzfEvent& event) const\n{\n XEvent xevent;\n XNextEvent(rep->getDisplay(), &xevent);\n\n switch (xevent.type) {\n case Expose:\n case ConfigureNotify:\n case MotionNotify:\n case MapNotify:\n case UnmapNotify:\n case ButtonPress:\n case ButtonRelease:\n case KeyPress:\n case KeyRelease:\n case ClientMessage:\n event.window = XWindow::lookupWindow(xevent.xexpose.window);\n if (!event.window) return false;\n break;\n\n default:\n return false;\n }\n\n switch (xevent.type) {\n case Expose:\n if (xevent.xexpose.count != 0) return false;\n event.type = BzfEvent::Redraw;\n break;\n\n case ConfigureNotify: {\n\/* attempt to filter out non-size changes, but getSize() returns the\n * current size so it always matches the size in the event.\n int width, height;\n event.window->getSize(width, height);\n if (width == xevent.xconfigure.width &&\n\t height == xevent.xconfigure.height)\n\treturn false;\n*\/\n event.type = BzfEvent::Resize;\n event.resize.width = xevent.xconfigure.width;\n event.resize.height = xevent.xconfigure.height;\n break;\n }\n\n case MotionNotify:\n event.type = BzfEvent::MouseMove;\n event.mouseMove.x = xevent.xmotion.x;\n event.mouseMove.y = xevent.xmotion.y;\n break;\n\n case MapNotify:\n event.type = BzfEvent::Map;\n break;\n\n case UnmapNotify:\n event.type = BzfEvent::Unmap;\n break;\n\n case ButtonPress:\n event.type = BzfEvent::KeyDown;\n event.keyDown.ascii = 0;\n event.keyDown.shift = 0;\n switch (xevent.xbutton.button) {\n\tcase Button1: event.keyDown.button = BzfKeyEvent::LeftMouse; break;\n\tcase Button2: event.keyDown.button = BzfKeyEvent::MiddleMouse; break;\n\tcase Button3: event.keyDown.button = BzfKeyEvent::RightMouse; break;\n\tdefault: return false;\n }\n break;\n\n case ButtonRelease:\n event.type = BzfEvent::KeyUp;\n event.keyUp.ascii = 0;\n event.keyUp.shift = 0;\n switch (xevent.xbutton.button) {\n\tcase Button1: event.keyUp.button = BzfKeyEvent::LeftMouse; break;\n\tcase Button2: event.keyUp.button = BzfKeyEvent::MiddleMouse; break;\n\tcase Button3: event.keyUp.button = BzfKeyEvent::RightMouse; break;\n\tdefault: return false;\n }\n break;\n\n case KeyPress:\n event.type = BzfEvent::KeyDown;\n if (!getKey(xevent, event.keyDown)) return false;\n break;\n\n case KeyRelease:\n event.type = BzfEvent::KeyUp;\n if (!getKey(xevent, event.keyUp)) return false;\n break;\n\n case ClientMessage: {\n XClientMessageEvent* cme = (XClientMessageEvent*)&xevent;\n if (cme->format == 32) {\n\tif ((Atom)cme->data.l[0] == XInternAtom(rep->getDisplay(),\n\t\t\t\t\t\"WM_DELETE_WINDOW\", true)) {\n\t event.type = BzfEvent::Quit;\n\t break;\n\t}\n }\n return false;\n }\n }\n\n return true;\n}\n\nbool\t\t\tXDisplay::getKey(const XEvent& xevent,\n\t\t\t\t\t\tBzfKeyEvent& key) const\n{\n char buf[3];\n KeySym keysym;\n if (XLookupString((XKeyEvent*)&xevent.xkey, buf, 1, &keysym, NULL) == 1) {\n key.ascii = buf[0];\n key.button = BzfKeyEvent::NoButton;\n\n if (keysym == XK_Delete) {\n key.ascii = 0;\n key.button = BzfKeyEvent::Delete;\n }\n }\n else {\n key.ascii = 0;\n switch (keysym) {\n case XK_Pause:\tkey.button = BzfKeyEvent::Pause; break;\n case XK_Home:\tkey.button = BzfKeyEvent::Home; break;\n case XK_End:\tkey.button = BzfKeyEvent::End; break;\n case XK_Left:\tkey.button = BzfKeyEvent::Left; break;\n case XK_Right:\tkey.button = BzfKeyEvent::Right; break;\n case XK_Up:\tkey.button = BzfKeyEvent::Up; break;\n case XK_Down:\tkey.button = BzfKeyEvent::Down; break;\n case XK_Page_Up:\tkey.button = BzfKeyEvent::PageUp; break;\n case XK_Page_Down: key.button = BzfKeyEvent::PageDown; break;\n case XK_Insert:\tkey.button = BzfKeyEvent::Insert; break;\n case XK_Delete:\tkey.button = BzfKeyEvent::Delete; break;\n case XK_F1:\tkey.button = BzfKeyEvent::F1; break;\n case XK_F2:\tkey.button = BzfKeyEvent::F2; break;\n case XK_F3:\tkey.button = BzfKeyEvent::F3; break;\n case XK_F4:\tkey.button = BzfKeyEvent::F4; break;\n case XK_F5:\tkey.button = BzfKeyEvent::F5; break;\n case XK_F6:\tkey.button = BzfKeyEvent::F6; break;\n case XK_F7:\tkey.button = BzfKeyEvent::F7; break;\n case XK_F8:\tkey.button = BzfKeyEvent::F8; break;\n case XK_F9:\tkey.button = BzfKeyEvent::F9; break;\n case XK_F10:\tkey.button = BzfKeyEvent::F10; break;\n case XK_F11:\tkey.button = BzfKeyEvent::F11; break;\n case XK_F12:\tkey.button = BzfKeyEvent::F12; break;\n default:\t\treturn false;\n }\n }\n\n key.shift = 0;\n if (xevent.xkey.state & ShiftMask) key.shift |= BzfKeyEvent::ShiftKey;\n if (xevent.xkey.state & ControlMask) key.shift |= BzfKeyEvent::ControlKey;\n if (xevent.xkey.state & Mod1Mask) key.shift |= BzfKeyEvent::AltKey;\n return true;\n}\n\nbool\t\t\tXDisplay::doSetResolution(int modeIndex)\n{\n return mode->set(modeIndex);\n}\n\nbool\t\t\tXDisplay::doSetDefaultResolution()\n{\n return mode->setDefault(getDefaultResolution());\n}\n\n\/\/\n\/\/ XDisplayMode\n\/\/\n\nXDisplayMode::XDisplayMode()\n{\n \/\/ do nothing\n}\n\nXDisplayMode::~XDisplayMode()\n{\n \/\/ do nothing\n}\n\nXDisplayMode::ResInfo**\tXDisplayMode::init(XDisplay*, int&, int&)\n{\n \/\/ no switching\n return NULL;\n}\n\nbool\t\t\tXDisplayMode::set(int)\n{\n \/\/ no switching\n return false;\n}\n\nbool\t\t\tXDisplayMode::setDefault(int mode)\n{\n return set(mode);\n}\n\n\/\/ Local Variables: ***\n\/\/ mode:C++ ***\n\/\/ tab-width: 8 ***\n\/\/ c-basic-offset: 2 ***\n\/\/ indent-tabs-mode: t ***\n\/\/ End: ***\n\/\/ ex: shiftwidth=2 tabstop=8\n\n<commit_msg>warning<commit_after>\/* bzflag\n * Copyright (c) 1993 - 2005 Tim Riker\n *\n * This package is free software; you can redistribute it and\/or\n * modify it under the terms of the license found in the file\n * named COPYING that should have accompanied this file.\n *\n * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR\n * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED\n * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.\n *\/\n\n#include \"XDisplay.h\"\n#include \"XWindow.h\"\n#include \"BzfEvent.h\"\n#include <string.h>\n#include <X11\/keysym.h>\n\n\/\/\n\/\/ XDisplay::Rep\n\/\/\n\nXDisplay::Rep::Rep(const char* displayName) :\n\t\t\t\trefCount(1),\n\t\t\t\tdisplay(NULL),\n\t\t\t\tscreen(0)\n{\n \/\/ open display\n display = XOpenDisplay(displayName);\n if (!display) return;\n\n \/\/ other initialization\n screen = DefaultScreen(display);\n}\n\nXDisplay::Rep::~Rep()\n{\n if (display) XCloseDisplay(display);\n}\n\nvoid\t\t\tXDisplay::Rep::ref()\n{\n refCount++;\n}\n\nvoid\t\t\tXDisplay::Rep::unref()\n{\n if (--refCount <= 0) delete this;\n}\n\nWindow\t\t\tXDisplay::Rep::getRootWindow() const\n{\n return display ? RootWindow(display, screen) : None;\n}\n\n\/\/\n\/\/ XDisplay\n\/\/\n\nXDisplay::XDisplay(const char* displayName, XDisplayMode* _mode) :\n\t\t\t\trep(NULL),\n\t\t\t\tmode(_mode)\n{\n \/\/ open display\n rep = new Rep(displayName);\n\n \/\/ make default mode changer if one wasn't supplied\n if (!mode)\n mode = new XDisplayMode;\n\n if (rep->getDisplay()) {\n \/\/ get resolutions\n int numModes, currentMode;\n ResInfo** resInfo = mode->init(this, numModes, currentMode);\n\n \/\/ if no modes then make default\n if (!resInfo) {\n resInfo = new ResInfo*[1];\n resInfo[0] = new ResInfo(\"default\",\n\t\t\tDisplayWidth(rep->getDisplay(), rep->getScreen()),\n\t\t\tDisplayHeight(rep->getDisplay(), rep->getScreen()), 0);\n numModes = 1;\n currentMode = 0;\n }\n\n \/\/ register modes\n initResolutions(resInfo, numModes, currentMode);\n }\n}\n\nXDisplay::~XDisplay()\n{\n setDefaultResolution();\n delete mode;\n rep->unref();\n}\n\nbool\t\t\tXDisplay::isValid() const\n{\n return rep->getDisplay() != NULL;\n}\n\nbool\t\t\tXDisplay::isEventPending() const\n{\n return (XPending(rep->getDisplay()) != 0);\n}\n\nbool\t\t\tXDisplay::peekEvent(BzfEvent& \/* event *\/) const\n{\n return false;\n}\n\nbool\t\t\tXDisplay::getEvent(BzfEvent& event) const\n{\n XEvent xevent;\n XNextEvent(rep->getDisplay(), &xevent);\n\n switch (xevent.type) {\n case Expose:\n case ConfigureNotify:\n case MotionNotify:\n case MapNotify:\n case UnmapNotify:\n case ButtonPress:\n case ButtonRelease:\n case KeyPress:\n case KeyRelease:\n case ClientMessage:\n event.window = XWindow::lookupWindow(xevent.xexpose.window);\n if (!event.window) return false;\n break;\n\n default:\n return false;\n }\n\n switch (xevent.type) {\n case Expose:\n if (xevent.xexpose.count != 0) return false;\n event.type = BzfEvent::Redraw;\n break;\n\n case ConfigureNotify: {\n\/* attempt to filter out non-size changes, but getSize() returns the\n * current size so it always matches the size in the event.\n int width, height;\n event.window->getSize(width, height);\n if (width == xevent.xconfigure.width &&\n\t height == xevent.xconfigure.height)\n\treturn false;\n*\/\n event.type = BzfEvent::Resize;\n event.resize.width = xevent.xconfigure.width;\n event.resize.height = xevent.xconfigure.height;\n break;\n }\n\n case MotionNotify:\n event.type = BzfEvent::MouseMove;\n event.mouseMove.x = xevent.xmotion.x;\n event.mouseMove.y = xevent.xmotion.y;\n break;\n\n case MapNotify:\n event.type = BzfEvent::Map;\n break;\n\n case UnmapNotify:\n event.type = BzfEvent::Unmap;\n break;\n\n case ButtonPress:\n event.type = BzfEvent::KeyDown;\n event.keyDown.ascii = 0;\n event.keyDown.shift = 0;\n switch (xevent.xbutton.button) {\n\tcase Button1: event.keyDown.button = BzfKeyEvent::LeftMouse; break;\n\tcase Button2: event.keyDown.button = BzfKeyEvent::MiddleMouse; break;\n\tcase Button3: event.keyDown.button = BzfKeyEvent::RightMouse; break;\n\tdefault: return false;\n }\n break;\n\n case ButtonRelease:\n event.type = BzfEvent::KeyUp;\n event.keyUp.ascii = 0;\n event.keyUp.shift = 0;\n switch (xevent.xbutton.button) {\n\tcase Button1: event.keyUp.button = BzfKeyEvent::LeftMouse; break;\n\tcase Button2: event.keyUp.button = BzfKeyEvent::MiddleMouse; break;\n\tcase Button3: event.keyUp.button = BzfKeyEvent::RightMouse; break;\n\tdefault: return false;\n }\n break;\n\n case KeyPress:\n event.type = BzfEvent::KeyDown;\n if (!getKey(xevent, event.keyDown)) return false;\n break;\n\n case KeyRelease:\n event.type = BzfEvent::KeyUp;\n if (!getKey(xevent, event.keyUp)) return false;\n break;\n\n case ClientMessage: {\n XClientMessageEvent* cme = (XClientMessageEvent*)&xevent;\n if (cme->format == 32) {\n\tif ((Atom)cme->data.l[0] == XInternAtom(rep->getDisplay(),\n\t\t\t\t\t\"WM_DELETE_WINDOW\", true)) {\n\t event.type = BzfEvent::Quit;\n\t break;\n\t}\n }\n return false;\n }\n }\n\n return true;\n}\n\nbool\t\t\tXDisplay::getKey(const XEvent& xevent,\n\t\t\t\t\t\tBzfKeyEvent& key) const\n{\n char buf[3];\n KeySym keysym;\n if (XLookupString((XKeyEvent*)&xevent.xkey, buf, 1, &keysym, NULL) == 1) {\n key.ascii = buf[0];\n key.button = BzfKeyEvent::NoButton;\n\n if (keysym == XK_Delete) {\n key.ascii = 0;\n key.button = BzfKeyEvent::Delete;\n }\n }\n else {\n key.ascii = 0;\n switch (keysym) {\n case XK_Pause:\tkey.button = BzfKeyEvent::Pause; break;\n case XK_Home:\tkey.button = BzfKeyEvent::Home; break;\n case XK_End:\tkey.button = BzfKeyEvent::End; break;\n case XK_Left:\tkey.button = BzfKeyEvent::Left; break;\n case XK_Right:\tkey.button = BzfKeyEvent::Right; break;\n case XK_Up:\tkey.button = BzfKeyEvent::Up; break;\n case XK_Down:\tkey.button = BzfKeyEvent::Down; break;\n case XK_Page_Up:\tkey.button = BzfKeyEvent::PageUp; break;\n case XK_Page_Down: key.button = BzfKeyEvent::PageDown; break;\n case XK_Insert:\tkey.button = BzfKeyEvent::Insert; break;\n case XK_Delete:\tkey.button = BzfKeyEvent::Delete; break;\n case XK_F1:\tkey.button = BzfKeyEvent::F1; break;\n case XK_F2:\tkey.button = BzfKeyEvent::F2; break;\n case XK_F3:\tkey.button = BzfKeyEvent::F3; break;\n case XK_F4:\tkey.button = BzfKeyEvent::F4; break;\n case XK_F5:\tkey.button = BzfKeyEvent::F5; break;\n case XK_F6:\tkey.button = BzfKeyEvent::F6; break;\n case XK_F7:\tkey.button = BzfKeyEvent::F7; break;\n case XK_F8:\tkey.button = BzfKeyEvent::F8; break;\n case XK_F9:\tkey.button = BzfKeyEvent::F9; break;\n case XK_F10:\tkey.button = BzfKeyEvent::F10; break;\n case XK_F11:\tkey.button = BzfKeyEvent::F11; break;\n case XK_F12:\tkey.button = BzfKeyEvent::F12; break;\n default:\t\treturn false;\n }\n }\n\n key.shift = 0;\n if (xevent.xkey.state & ShiftMask) key.shift |= BzfKeyEvent::ShiftKey;\n if (xevent.xkey.state & ControlMask) key.shift |= BzfKeyEvent::ControlKey;\n if (xevent.xkey.state & Mod1Mask) key.shift |= BzfKeyEvent::AltKey;\n return true;\n}\n\nbool\t\t\tXDisplay::doSetResolution(int modeIndex)\n{\n return mode->set(modeIndex);\n}\n\nbool\t\t\tXDisplay::doSetDefaultResolution()\n{\n return mode->setDefault(getDefaultResolution());\n}\n\n\/\/\n\/\/ XDisplayMode\n\/\/\n\nXDisplayMode::XDisplayMode()\n{\n \/\/ do nothing\n}\n\nXDisplayMode::~XDisplayMode()\n{\n \/\/ do nothing\n}\n\nXDisplayMode::ResInfo**\tXDisplayMode::init(XDisplay*, int&, int&)\n{\n \/\/ no switching\n return NULL;\n}\n\nbool\t\t\tXDisplayMode::set(int)\n{\n \/\/ no switching\n return false;\n}\n\nbool\t\t\tXDisplayMode::setDefault(int mode)\n{\n return set(mode);\n}\n\n\/\/ Local Variables: ***\n\/\/ mode:C++ ***\n\/\/ tab-width: 8 ***\n\/\/ c-basic-offset: 2 ***\n\/\/ indent-tabs-mode: t ***\n\/\/ End: ***\n\/\/ ex: shiftwidth=2 tabstop=8\n\n<|endoftext|>"} {"text":"<commit_before>\/\/===- JITEmitter.cpp - Unit tests for the JIT code emitter ---------------===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"gtest\/gtest.h\"\n#include \"llvm\/ADT\/OwningPtr.h\"\n#include \"llvm\/BasicBlock.h\"\n#include \"llvm\/Constant.h\"\n#include \"llvm\/Constants.h\"\n#include \"llvm\/DerivedTypes.h\"\n#include \"llvm\/ExecutionEngine\/JIT.h\"\n#include \"llvm\/ExecutionEngine\/JITMemoryManager.h\"\n#include \"llvm\/Function.h\"\n#include \"llvm\/GlobalValue.h\"\n#include \"llvm\/GlobalVariable.h\"\n#include \"llvm\/Module.h\"\n#include \"llvm\/ModuleProvider.h\"\n#include \"llvm\/Support\/IRBuilder.h\"\n#include \"llvm\/Target\/TargetSelect.h\"\n#include \"llvm\/Type.h\"\n\nusing namespace llvm;\n\nnamespace {\n\nFunction *makeReturnGlobal(std::string Name, GlobalVariable *G, Module *M) {\n std::vector<const Type*> params;\n const FunctionType *FTy = FunctionType::get(Type::VoidTy, params, false);\n Function *F = Function::Create(FTy, GlobalValue::ExternalLinkage, Name, M);\n BasicBlock *Entry = BasicBlock::Create(\"entry\", F);\n IRBuilder<> builder(Entry);\n Value *Load = builder.CreateLoad(G);\n const Type *GTy = G->getType()->getElementType();\n Value *Add = builder.CreateAdd(Load, ConstantInt::get(GTy, 1LL));\n builder.CreateStore(Add, G);\n builder.CreateRet(Add);\n return F;\n}\n\n\/\/ Regression test for a bug. The JIT used to allocate globals inside the same\n\/\/ memory block used for the function, and when the function code was freed,\n\/\/ the global was left in the same place. This test allocates a function\n\/\/ that uses and global, deallocates it, and then makes sure that the global\n\/\/ stays alive after that.\nTEST(JIT, GlobalInFunction) {\n LLVMContext context;\n Module *M = new Module(\"<main>\", context);\n ExistingModuleProvider *MP = new ExistingModuleProvider(M);\n\n JITMemoryManager *MemMgr = JITMemoryManager::CreateDefaultMemManager();\n \/\/ Tell the memory manager to poison freed memory so that accessing freed\n \/\/ memory is more easily tested.\n MemMgr->setPoisonMemory(true);\n std::string Error;\n OwningPtr<ExecutionEngine> JIT(ExecutionEngine::createJIT(\n MP,\n &Error,\n MemMgr,\n CodeGenOpt::Default,\n false)); \/\/ This last argument enables the fix.\n ASSERT_EQ(Error, \"\");\n\n \/\/ Create a global variable.\n const Type *GTy = Type::Int32Ty;\n GlobalVariable *G = new GlobalVariable(\n *M,\n GTy,\n false, \/\/ Not constant.\n GlobalValue::InternalLinkage,\n Constant::getNullValue(GTy),\n \"myglobal\");\n\n \/\/ Make a function that points to a global.\n Function *F1 = makeReturnGlobal(\"F1\", G, M);\n\n \/\/ Get the pointer to the native code to force it to JIT the function and\n \/\/ allocate space for the global.\n void (*F1Ptr)();\n \/\/ Hack to avoid ISO C++ warning about casting function pointers.\n *(void**)(void*)&F1Ptr = JIT->getPointerToFunction(F1);\n\n \/\/ Since F1 was codegen'd, a pointer to G should be available.\n int32_t *GPtr = (int32_t*)JIT->getPointerToGlobalIfAvailable(G);\n ASSERT_NE((int32_t*)NULL, GPtr);\n EXPECT_EQ(0, *GPtr);\n\n \/\/ F1() should increment G.\n F1Ptr();\n EXPECT_EQ(1, *GPtr);\n\n \/\/ Make a second function identical to the first, referring to the same\n \/\/ global.\n Function *F2 = makeReturnGlobal(\"F2\", G, M);\n \/\/ Hack to avoid ISO C++ warning about casting function pointers.\n void (*F2Ptr)();\n *(void**)(void*)&F2Ptr = JIT->getPointerToFunction(F2);\n\n \/\/ F2() should increment G.\n F2Ptr();\n EXPECT_EQ(2, *GPtr);\n\n \/\/ Deallocate F1.\n JIT->freeMachineCodeForFunction(F1);\n\n \/\/ F2() should *still* increment G.\n F2Ptr();\n EXPECT_EQ(3, *GPtr);\n}\n\n\/\/ TODO(rnk): This seems to only run once for both tests, which is unexpected.\n\/\/ That works just fine, but we shouldn't duplicate the code.\nclass JITEnvironment : public testing::Environment {\n virtual void SetUp() {\n \/\/ Required for ExecutionEngine::createJIT to create a JIT.\n InitializeNativeTarget();\n }\n};\ntesting::Environment* const jit_env =\n testing::AddGlobalTestEnvironment(new JITEnvironment);\n\n}\n<commit_msg>Don't use a void return type with a function that returns a value.<commit_after>\/\/===- JITEmitter.cpp - Unit tests for the JIT code emitter ---------------===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"gtest\/gtest.h\"\n#include \"llvm\/ADT\/OwningPtr.h\"\n#include \"llvm\/BasicBlock.h\"\n#include \"llvm\/Constant.h\"\n#include \"llvm\/Constants.h\"\n#include \"llvm\/DerivedTypes.h\"\n#include \"llvm\/ExecutionEngine\/JIT.h\"\n#include \"llvm\/ExecutionEngine\/JITMemoryManager.h\"\n#include \"llvm\/Function.h\"\n#include \"llvm\/GlobalValue.h\"\n#include \"llvm\/GlobalVariable.h\"\n#include \"llvm\/Module.h\"\n#include \"llvm\/ModuleProvider.h\"\n#include \"llvm\/Support\/IRBuilder.h\"\n#include \"llvm\/Target\/TargetSelect.h\"\n#include \"llvm\/Type.h\"\n\nusing namespace llvm;\n\nnamespace {\n\nFunction *makeReturnGlobal(std::string Name, GlobalVariable *G, Module *M) {\n std::vector<const Type*> params;\n const FunctionType *FTy = FunctionType::get(G->getType()->getElementType(),\n params, false);\n Function *F = Function::Create(FTy, GlobalValue::ExternalLinkage, Name, M);\n BasicBlock *Entry = BasicBlock::Create(\"entry\", F);\n IRBuilder<> builder(Entry);\n Value *Load = builder.CreateLoad(G);\n const Type *GTy = G->getType()->getElementType();\n Value *Add = builder.CreateAdd(Load, ConstantInt::get(GTy, 1LL));\n builder.CreateStore(Add, G);\n builder.CreateRet(Add);\n return F;\n}\n\n\/\/ Regression test for a bug. The JIT used to allocate globals inside the same\n\/\/ memory block used for the function, and when the function code was freed,\n\/\/ the global was left in the same place. This test allocates a function\n\/\/ that uses and global, deallocates it, and then makes sure that the global\n\/\/ stays alive after that.\nTEST(JIT, GlobalInFunction) {\n LLVMContext context;\n Module *M = new Module(\"<main>\", context);\n ExistingModuleProvider *MP = new ExistingModuleProvider(M);\n\n JITMemoryManager *MemMgr = JITMemoryManager::CreateDefaultMemManager();\n \/\/ Tell the memory manager to poison freed memory so that accessing freed\n \/\/ memory is more easily tested.\n MemMgr->setPoisonMemory(true);\n std::string Error;\n OwningPtr<ExecutionEngine> JIT(ExecutionEngine::createJIT(\n MP,\n &Error,\n MemMgr,\n CodeGenOpt::Default,\n false)); \/\/ This last argument enables the fix.\n ASSERT_EQ(Error, \"\");\n\n \/\/ Create a global variable.\n const Type *GTy = Type::Int32Ty;\n GlobalVariable *G = new GlobalVariable(\n *M,\n GTy,\n false, \/\/ Not constant.\n GlobalValue::InternalLinkage,\n Constant::getNullValue(GTy),\n \"myglobal\");\n\n \/\/ Make a function that points to a global.\n Function *F1 = makeReturnGlobal(\"F1\", G, M);\n\n \/\/ Get the pointer to the native code to force it to JIT the function and\n \/\/ allocate space for the global.\n void (*F1Ptr)();\n \/\/ Hack to avoid ISO C++ warning about casting function pointers.\n *(void**)(void*)&F1Ptr = JIT->getPointerToFunction(F1);\n\n \/\/ Since F1 was codegen'd, a pointer to G should be available.\n int32_t *GPtr = (int32_t*)JIT->getPointerToGlobalIfAvailable(G);\n ASSERT_NE((int32_t*)NULL, GPtr);\n EXPECT_EQ(0, *GPtr);\n\n \/\/ F1() should increment G.\n F1Ptr();\n EXPECT_EQ(1, *GPtr);\n\n \/\/ Make a second function identical to the first, referring to the same\n \/\/ global.\n Function *F2 = makeReturnGlobal(\"F2\", G, M);\n \/\/ Hack to avoid ISO C++ warning about casting function pointers.\n void (*F2Ptr)();\n *(void**)(void*)&F2Ptr = JIT->getPointerToFunction(F2);\n\n \/\/ F2() should increment G.\n F2Ptr();\n EXPECT_EQ(2, *GPtr);\n\n \/\/ Deallocate F1.\n JIT->freeMachineCodeForFunction(F1);\n\n \/\/ F2() should *still* increment G.\n F2Ptr();\n EXPECT_EQ(3, *GPtr);\n}\n\n\/\/ TODO(rnk): This seems to only run once for both tests, which is unexpected.\n\/\/ That works just fine, but we shouldn't duplicate the code.\nclass JITEnvironment : public testing::Environment {\n virtual void SetUp() {\n \/\/ Required for ExecutionEngine::createJIT to create a JIT.\n InitializeNativeTarget();\n }\n};\ntesting::Environment* const jit_env =\n testing::AddGlobalTestEnvironment(new JITEnvironment);\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/===---- QueryParserTest.cpp - clang-query test --------------------------===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"QueryParser.h\"\n#include \"Query.h\"\n#include \"QuerySession.h\"\n#include \"llvm\/LineEditor\/LineEditor.h\"\n#include \"gtest\/gtest.h\"\n\nusing namespace clang;\nusing namespace clang::query;\n\nclass QueryParserTest : public ::testing::Test {\nprotected:\n QueryParserTest() : QS(llvm::ArrayRef<std::unique_ptr<ASTUnit>>()) {}\n QueryRef parse(StringRef Code) { return QueryParser::parse(Code, QS); }\n\n QuerySession QS;\n};\n\nTEST_F(QueryParserTest, NoOp) {\n QueryRef Q = parse(\"\");\n EXPECT_TRUE(isa<NoOpQuery>(Q));\n\n Q = parse(\"\\n\");\n EXPECT_TRUE(isa<NoOpQuery>(Q));\n}\n\nTEST_F(QueryParserTest, Invalid) {\n QueryRef Q = parse(\"foo\");\n ASSERT_TRUE(isa<InvalidQuery>(Q));\n EXPECT_EQ(\"unknown command: foo\", cast<InvalidQuery>(Q)->ErrStr);\n}\n\nTEST_F(QueryParserTest, Help) {\n QueryRef Q = parse(\"help\");\n ASSERT_TRUE(isa<HelpQuery>(Q));\n\n Q = parse(\"help me\");\n ASSERT_TRUE(isa<InvalidQuery>(Q));\n EXPECT_EQ(\"unexpected extra input: ' me'\", cast<InvalidQuery>(Q)->ErrStr);\n}\n\nTEST_F(QueryParserTest, Set) {\n QueryRef Q = parse(\"set\");\n ASSERT_TRUE(isa<InvalidQuery>(Q));\n EXPECT_EQ(\"expected variable name\", cast<InvalidQuery>(Q)->ErrStr);\n\n Q = parse(\"set foo bar\");\n ASSERT_TRUE(isa<InvalidQuery>(Q));\n EXPECT_EQ(\"unknown variable: 'foo'\", cast<InvalidQuery>(Q)->ErrStr);\n\n Q = parse(\"set output\");\n ASSERT_TRUE(isa<InvalidQuery>(Q));\n EXPECT_EQ(\"expected 'diag', 'print' or 'dump', got ''\",\n cast<InvalidQuery>(Q)->ErrStr);\n\n Q = parse(\"set bind-root true foo\");\n ASSERT_TRUE(isa<InvalidQuery>(Q));\n EXPECT_EQ(\"unexpected extra input: ' foo'\", cast<InvalidQuery>(Q)->ErrStr);\n\n Q = parse(\"set output foo\");\n ASSERT_TRUE(isa<InvalidQuery>(Q));\n EXPECT_EQ(\"expected 'diag', 'print' or 'dump', got 'foo'\",\n cast<InvalidQuery>(Q)->ErrStr);\n\n Q = parse(\"set output dump\");\n ASSERT_TRUE(isa<SetQuery<OutputKind> >(Q));\n EXPECT_EQ(&QuerySession::OutKind, cast<SetQuery<OutputKind> >(Q)->Var);\n EXPECT_EQ(OK_Dump, cast<SetQuery<OutputKind> >(Q)->Value);\n\n Q = parse(\"set bind-root foo\");\n ASSERT_TRUE(isa<InvalidQuery>(Q));\n EXPECT_EQ(\"expected 'true' or 'false', got 'foo'\",\n cast<InvalidQuery>(Q)->ErrStr);\n\n Q = parse(\"set bind-root true\");\n ASSERT_TRUE(isa<SetQuery<bool> >(Q));\n EXPECT_EQ(&QuerySession::BindRoot, cast<SetQuery<bool> >(Q)->Var);\n EXPECT_EQ(true, cast<SetQuery<bool> >(Q)->Value);\n}\n\nTEST_F(QueryParserTest, Match) {\n QueryRef Q = parse(\"match decl()\");\n ASSERT_TRUE(isa<MatchQuery>(Q));\n EXPECT_TRUE(cast<MatchQuery>(Q)->Matcher.canConvertTo<Decl>());\n\n Q = parse(\"m stmt()\");\n ASSERT_TRUE(isa<MatchQuery>(Q));\n EXPECT_TRUE(cast<MatchQuery>(Q)->Matcher.canConvertTo<Stmt>());\n}\n\nTEST_F(QueryParserTest, LetUnlet) {\n QueryRef Q = parse(\"let foo decl()\");\n ASSERT_TRUE(isa<LetQuery>(Q));\n EXPECT_EQ(\"foo\", cast<LetQuery>(Q)->Name);\n EXPECT_TRUE(cast<LetQuery>(Q)->Value.isMatcher());\n EXPECT_TRUE(cast<LetQuery>(Q)->Value.getMatcher().hasTypedMatcher<Decl>());\n\n Q = parse(\"let bar \\\"str\\\"\");\n ASSERT_TRUE(isa<LetQuery>(Q));\n EXPECT_EQ(\"bar\", cast<LetQuery>(Q)->Name);\n EXPECT_TRUE(cast<LetQuery>(Q)->Value.isString());\n EXPECT_EQ(\"str\", cast<LetQuery>(Q)->Value.getString());\n\n Q = parse(\"let\");\n ASSERT_TRUE(isa<InvalidQuery>(Q));\n EXPECT_EQ(\"expected variable name\", cast<InvalidQuery>(Q)->ErrStr);\n\n Q = parse(\"unlet x\");\n ASSERT_TRUE(isa<LetQuery>(Q));\n EXPECT_EQ(\"x\", cast<LetQuery>(Q)->Name);\n EXPECT_FALSE(cast<LetQuery>(Q)->Value.hasValue());\n\n Q = parse(\"unlet\");\n ASSERT_TRUE(isa<InvalidQuery>(Q));\n EXPECT_EQ(\"expected variable name\", cast<InvalidQuery>(Q)->ErrStr);\n\n Q = parse(\"unlet x bad_data\");\n ASSERT_TRUE(isa<InvalidQuery>(Q));\n EXPECT_EQ(\"unexpected extra input: ' bad_data'\",\n cast<InvalidQuery>(Q)->ErrStr);\n}\n\nTEST_F(QueryParserTest, Complete) {\n std::vector<llvm::LineEditor::Completion> Comps =\n QueryParser::complete(\"\", 0, QS);\n ASSERT_EQ(5u, Comps.size());\n EXPECT_EQ(\"help \", Comps[0].TypedText);\n EXPECT_EQ(\"help\", Comps[0].DisplayText);\n EXPECT_EQ(\"let \", Comps[1].TypedText);\n EXPECT_EQ(\"let\", Comps[1].DisplayText);\n EXPECT_EQ(\"match \", Comps[2].TypedText);\n EXPECT_EQ(\"match\", Comps[2].DisplayText);\n EXPECT_EQ(\"set \", Comps[3].TypedText);\n EXPECT_EQ(\"set\", Comps[3].DisplayText);\n EXPECT_EQ(\"unlet \", Comps[4].TypedText);\n EXPECT_EQ(\"unlet\", Comps[4].DisplayText);\n\n Comps = QueryParser::complete(\"set o\", 5, QS);\n ASSERT_EQ(1u, Comps.size());\n EXPECT_EQ(\"utput \", Comps[0].TypedText);\n EXPECT_EQ(\"output\", Comps[0].DisplayText);\n\n Comps = QueryParser::complete(\"match while\", 11, QS);\n ASSERT_EQ(1u, Comps.size());\n EXPECT_EQ(\"Stmt(\", Comps[0].TypedText);\n EXPECT_EQ(\"Matcher<Stmt> whileStmt(Matcher<WhileStmt>...)\",\n Comps[0].DisplayText);\n}\n<commit_msg>Correcting and adding tests for r244206.<commit_after>\/\/===---- QueryParserTest.cpp - clang-query test --------------------------===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"QueryParser.h\"\n#include \"Query.h\"\n#include \"QuerySession.h\"\n#include \"llvm\/LineEditor\/LineEditor.h\"\n#include \"gtest\/gtest.h\"\n\nusing namespace clang;\nusing namespace clang::query;\n\nclass QueryParserTest : public ::testing::Test {\nprotected:\n QueryParserTest() : QS(llvm::ArrayRef<std::unique_ptr<ASTUnit>>()) {}\n QueryRef parse(StringRef Code) { return QueryParser::parse(Code, QS); }\n\n QuerySession QS;\n};\n\nTEST_F(QueryParserTest, NoOp) {\n QueryRef Q = parse(\"\");\n EXPECT_TRUE(isa<NoOpQuery>(Q));\n\n Q = parse(\"\\n\");\n EXPECT_TRUE(isa<NoOpQuery>(Q));\n}\n\nTEST_F(QueryParserTest, Invalid) {\n QueryRef Q = parse(\"foo\");\n ASSERT_TRUE(isa<InvalidQuery>(Q));\n EXPECT_EQ(\"unknown command: foo\", cast<InvalidQuery>(Q)->ErrStr);\n}\n\nTEST_F(QueryParserTest, Help) {\n QueryRef Q = parse(\"help\");\n ASSERT_TRUE(isa<HelpQuery>(Q));\n\n Q = parse(\"help me\");\n ASSERT_TRUE(isa<InvalidQuery>(Q));\n EXPECT_EQ(\"unexpected extra input: ' me'\", cast<InvalidQuery>(Q)->ErrStr);\n}\n\nTEST_F(QueryParserTest, Set) {\n QueryRef Q = parse(\"set\");\n ASSERT_TRUE(isa<InvalidQuery>(Q));\n EXPECT_EQ(\"expected variable name\", cast<InvalidQuery>(Q)->ErrStr);\n\n Q = parse(\"set foo bar\");\n ASSERT_TRUE(isa<InvalidQuery>(Q));\n EXPECT_EQ(\"unknown variable: 'foo'\", cast<InvalidQuery>(Q)->ErrStr);\n\n Q = parse(\"set output\");\n ASSERT_TRUE(isa<InvalidQuery>(Q));\n EXPECT_EQ(\"expected 'diag', 'print' or 'dump', got ''\",\n cast<InvalidQuery>(Q)->ErrStr);\n\n Q = parse(\"set bind-root true foo\");\n ASSERT_TRUE(isa<InvalidQuery>(Q));\n EXPECT_EQ(\"unexpected extra input: ' foo'\", cast<InvalidQuery>(Q)->ErrStr);\n\n Q = parse(\"set output foo\");\n ASSERT_TRUE(isa<InvalidQuery>(Q));\n EXPECT_EQ(\"expected 'diag', 'print' or 'dump', got 'foo'\",\n cast<InvalidQuery>(Q)->ErrStr);\n\n Q = parse(\"set output dump\");\n ASSERT_TRUE(isa<SetQuery<OutputKind> >(Q));\n EXPECT_EQ(&QuerySession::OutKind, cast<SetQuery<OutputKind> >(Q)->Var);\n EXPECT_EQ(OK_Dump, cast<SetQuery<OutputKind> >(Q)->Value);\n\n Q = parse(\"set bind-root foo\");\n ASSERT_TRUE(isa<InvalidQuery>(Q));\n EXPECT_EQ(\"expected 'true' or 'false', got 'foo'\",\n cast<InvalidQuery>(Q)->ErrStr);\n\n Q = parse(\"set bind-root true\");\n ASSERT_TRUE(isa<SetQuery<bool> >(Q));\n EXPECT_EQ(&QuerySession::BindRoot, cast<SetQuery<bool> >(Q)->Var);\n EXPECT_EQ(true, cast<SetQuery<bool> >(Q)->Value);\n}\n\nTEST_F(QueryParserTest, Match) {\n QueryRef Q = parse(\"match decl()\");\n ASSERT_TRUE(isa<MatchQuery>(Q));\n EXPECT_TRUE(cast<MatchQuery>(Q)->Matcher.canConvertTo<Decl>());\n\n Q = parse(\"m stmt()\");\n ASSERT_TRUE(isa<MatchQuery>(Q));\n EXPECT_TRUE(cast<MatchQuery>(Q)->Matcher.canConvertTo<Stmt>());\n}\n\nTEST_F(QueryParserTest, LetUnlet) {\n QueryRef Q = parse(\"let foo decl()\");\n ASSERT_TRUE(isa<LetQuery>(Q));\n EXPECT_EQ(\"foo\", cast<LetQuery>(Q)->Name);\n EXPECT_TRUE(cast<LetQuery>(Q)->Value.isMatcher());\n EXPECT_TRUE(cast<LetQuery>(Q)->Value.getMatcher().hasTypedMatcher<Decl>());\n\n Q = parse(\"let bar \\\"str\\\"\");\n ASSERT_TRUE(isa<LetQuery>(Q));\n EXPECT_EQ(\"bar\", cast<LetQuery>(Q)->Name);\n EXPECT_TRUE(cast<LetQuery>(Q)->Value.isString());\n EXPECT_EQ(\"str\", cast<LetQuery>(Q)->Value.getString());\n\n Q = parse(\"let\");\n ASSERT_TRUE(isa<InvalidQuery>(Q));\n EXPECT_EQ(\"expected variable name\", cast<InvalidQuery>(Q)->ErrStr);\n\n Q = parse(\"unlet x\");\n ASSERT_TRUE(isa<LetQuery>(Q));\n EXPECT_EQ(\"x\", cast<LetQuery>(Q)->Name);\n EXPECT_FALSE(cast<LetQuery>(Q)->Value.hasValue());\n\n Q = parse(\"unlet\");\n ASSERT_TRUE(isa<InvalidQuery>(Q));\n EXPECT_EQ(\"expected variable name\", cast<InvalidQuery>(Q)->ErrStr);\n\n Q = parse(\"unlet x bad_data\");\n ASSERT_TRUE(isa<InvalidQuery>(Q));\n EXPECT_EQ(\"unexpected extra input: ' bad_data'\",\n cast<InvalidQuery>(Q)->ErrStr);\n}\n\nTEST_F(QueryParserTest, Complete) {\n std::vector<llvm::LineEditor::Completion> Comps =\n QueryParser::complete(\"\", 0, QS);\n ASSERT_EQ(6u, Comps.size());\n EXPECT_EQ(\"help \", Comps[0].TypedText);\n EXPECT_EQ(\"help\", Comps[0].DisplayText);\n EXPECT_EQ(\"let \", Comps[1].TypedText);\n EXPECT_EQ(\"let\", Comps[1].DisplayText);\n EXPECT_EQ(\"match \", Comps[2].TypedText);\n EXPECT_EQ(\"match\", Comps[2].DisplayText);\n EXPECT_EQ(\"set \", Comps[3].TypedText);\n EXPECT_EQ(\"set\", Comps[3].DisplayText);\n EXPECT_EQ(\"unlet \", Comps[4].TypedText);\n EXPECT_EQ(\"unlet\", Comps[4].DisplayText);\n EXPECT_EQ(\"quit\", Comps[5].DisplayText);\n EXPECT_EQ(\"quit \", Comps[5].TypedText);\n\n Comps = QueryParser::complete(\"set o\", 5, QS);\n ASSERT_EQ(1u, Comps.size());\n EXPECT_EQ(\"utput \", Comps[0].TypedText);\n EXPECT_EQ(\"output\", Comps[0].DisplayText);\n\n Comps = QueryParser::complete(\"match while\", 11, QS);\n ASSERT_EQ(1u, Comps.size());\n EXPECT_EQ(\"Stmt(\", Comps[0].TypedText);\n EXPECT_EQ(\"Matcher<Stmt> whileStmt(Matcher<WhileStmt>...)\",\n Comps[0].DisplayText);\n}\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: calendarwrapper.hxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: er $ $Date: 2001-07-10 12:54:06 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef _UNOTOOLS_CALENDARWRAPPER_HXX\n#define _UNOTOOLS_CALENDARWRAPPER_HXX\n\n#ifndef _DATETIME_HXX\n#include <tools\/datetime.hxx>\n#endif\n\n#ifndef _COM_SUN_STAR_UNO_REFERENCE_HXX_\n#include <com\/sun\/star\/uno\/Reference.hxx>\n#endif\n#ifndef _COM_SUN_STAR_UNO_SEQUENCE_HXX_\n#include <com\/sun\/star\/uno\/Sequence.hxx>\n#endif\n#ifndef _COM_SUN_STAR_I18N_CALENDAR_HPP_\n#include <com\/sun\/star\/i18n\/Calendar.hpp>\n#endif\n#ifndef _COM_SUN_STAR_LANG_LOCALE_HPP_\n#include <com\/sun\/star\/lang\/Locale.hpp>\n#endif\n\nnamespace com { namespace sun { namespace star {\n namespace lang {\n class XMultiServiceFactory;\n }\n namespace i18n {\n class XCalendar;\n }\n}}}\n\n\nclass CalendarWrapper\n{\n ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > xSMgr;\n ::com::sun::star::uno::Reference< ::com::sun::star::i18n::XCalendar > xC;\n\n DateTime aEpochStart; \/\/ 1Jan1970\n\npublic:\n CalendarWrapper(\n const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > & xSF\n );\n ~CalendarWrapper();\n\n\n \/\/ wrapper implementations of XCalendar\n\n void loadDefaultCalendar( const ::com::sun::star::lang::Locale& rLocale );\n void loadCalendar( const ::rtl::OUString& rUniqueID, const ::com::sun::star::lang::Locale& rLocale );\n ::com::sun::star::i18n::Calendar getLoadedCalendar() const;\n ::com::sun::star::uno::Sequence< ::rtl::OUString > getAllCalendars( const ::com::sun::star::lang::Locale& rLocale ) const;\n ::rtl::OUString getUniqueID() const;\n void setDateTime( double nTimeInDays );\n double getDateTime() const;\n void setValue( sal_Int16 nFieldIndex, sal_Int16 nValue );\n sal_Bool isValid() const;\n sal_Int16 getValue( sal_Int16 nFieldIndex ) const;\n void addValue( sal_Int16 nFieldIndex, sal_Int32 nAmount );\n sal_Int16 getFirstDayOfWeek() const;\n void setFirstDayOfWeek( sal_Int16 nDay );\n void setMinimumNumberOfDaysForFirstWeek( sal_Int16 nDays );\n sal_Int16 getMinimumNumberOfDaysForFirstWeek() const;\n sal_Int16 getNumberOfMonthsInYear() const;\n sal_Int16 getNumberOfDaysInWeek() const;\n ::com::sun::star::uno::Sequence< ::com::sun::star::i18n::CalendarItem > getMonths() const;\n ::com::sun::star::uno::Sequence< ::com::sun::star::i18n::CalendarItem > getDays() const;\n String getDisplayName( sal_Int16 nCalendarDisplayIndex, sal_Int16 nIdx, sal_Int16 nNameType ) const;\n\n\n \/\/ convenience methods\n\n \/\/\/ set a gregorian DateTime\n inline void setGregorianDateTime( const DateTime& rDateTime )\n { setDateTime( rDateTime - aEpochStart ); }\n\n \/\/\/ get the DateTime as a gregorian DateTime\n inline DateTime getGregorianDateTime() const\n { return aEpochStart + getDateTime(); }\n\n};\n\n#endif\n<commit_msg>add: getEpochStart<commit_after>\/*************************************************************************\n *\n * $RCSfile: calendarwrapper.hxx,v $\n *\n * $Revision: 1.4 $\n *\n * last change: $Author: er $ $Date: 2001-08-27 15:18:38 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef _UNOTOOLS_CALENDARWRAPPER_HXX\n#define _UNOTOOLS_CALENDARWRAPPER_HXX\n\n#ifndef _DATETIME_HXX\n#include <tools\/datetime.hxx>\n#endif\n\n#ifndef _COM_SUN_STAR_UNO_REFERENCE_HXX_\n#include <com\/sun\/star\/uno\/Reference.hxx>\n#endif\n#ifndef _COM_SUN_STAR_UNO_SEQUENCE_HXX_\n#include <com\/sun\/star\/uno\/Sequence.hxx>\n#endif\n#ifndef _COM_SUN_STAR_I18N_CALENDAR_HPP_\n#include <com\/sun\/star\/i18n\/Calendar.hpp>\n#endif\n#ifndef _COM_SUN_STAR_LANG_LOCALE_HPP_\n#include <com\/sun\/star\/lang\/Locale.hpp>\n#endif\n\nnamespace com { namespace sun { namespace star {\n namespace lang {\n class XMultiServiceFactory;\n }\n namespace i18n {\n class XCalendar;\n }\n}}}\n\n\nclass CalendarWrapper\n{\n ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > xSMgr;\n ::com::sun::star::uno::Reference< ::com::sun::star::i18n::XCalendar > xC;\n\n DateTime aEpochStart; \/\/ 1Jan1970\n\npublic:\n CalendarWrapper(\n const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > & xSF\n );\n ~CalendarWrapper();\n\n\n \/\/ wrapper implementations of XCalendar\n\n void loadDefaultCalendar( const ::com::sun::star::lang::Locale& rLocale );\n void loadCalendar( const ::rtl::OUString& rUniqueID, const ::com::sun::star::lang::Locale& rLocale );\n ::com::sun::star::i18n::Calendar getLoadedCalendar() const;\n ::com::sun::star::uno::Sequence< ::rtl::OUString > getAllCalendars( const ::com::sun::star::lang::Locale& rLocale ) const;\n ::rtl::OUString getUniqueID() const;\n void setDateTime( double nTimeInDays );\n double getDateTime() const;\n void setValue( sal_Int16 nFieldIndex, sal_Int16 nValue );\n sal_Bool isValid() const;\n sal_Int16 getValue( sal_Int16 nFieldIndex ) const;\n void addValue( sal_Int16 nFieldIndex, sal_Int32 nAmount );\n sal_Int16 getFirstDayOfWeek() const;\n void setFirstDayOfWeek( sal_Int16 nDay );\n void setMinimumNumberOfDaysForFirstWeek( sal_Int16 nDays );\n sal_Int16 getMinimumNumberOfDaysForFirstWeek() const;\n sal_Int16 getNumberOfMonthsInYear() const;\n sal_Int16 getNumberOfDaysInWeek() const;\n ::com::sun::star::uno::Sequence< ::com::sun::star::i18n::CalendarItem > getMonths() const;\n ::com::sun::star::uno::Sequence< ::com::sun::star::i18n::CalendarItem > getDays() const;\n String getDisplayName( sal_Int16 nCalendarDisplayIndex, sal_Int16 nIdx, sal_Int16 nNameType ) const;\n\n\n \/\/ convenience methods\n\n \/\/\/ get epoch start (should be 01Jan1970)\n inline const DateTime& getEpochStart() const\n { return aEpochStart; }\n\n \/\/\/ set a gregorian DateTime\n inline void setGregorianDateTime( const DateTime& rDateTime )\n { setDateTime( rDateTime - aEpochStart ); }\n\n \/\/\/ get the DateTime as a gregorian DateTime\n inline DateTime getGregorianDateTime() const\n { return aEpochStart + getDateTime(); }\n\n};\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/*********************************************************************\n *\n * Copyright 2011 Intel Corporation\n * All Rights Reserved.\n *\n * Permission is hereby granted, free of charge, to any person\n * obtaining a copy of this software and associated documentation\n * files (the \"Software\"), to deal in the Software without\n * restriction, including without limitation the rights to use, copy,\n * modify, merge, publish, distribute, sublicense, and\/or sell copies\n * of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be\n * included in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS\n * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN\n * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n *\n *********************************************************************\/\n\n\n#include <assert.h>\n#include <string.h>\n#include <stdlib.h>\n#include <getopt.h>\n\n#include <iostream>\n\n#include \"os_string.hpp\"\n#include \"os_process.hpp\"\n#include \"os_version.hpp\"\n\n#include \"cli.hpp\"\n#include \"cli_resources.hpp\"\n\n\n#if defined(__APPLE__)\n#define TRACE_VARIABLE \"DYLD_FRAMEWORK_PATH\"\n#define GL_TRACE_WRAPPER \"OpenGL.framework\/OpenGL\"\n#elif defined(_WIN32)\n#define GL_TRACE_WRAPPER \"opengl32.dll\"\n#else\n#define TRACE_VARIABLE \"LD_PRELOAD\"\n#define GL_TRACE_WRAPPER \"glxtrace.so\"\n#define EGL_TRACE_WRAPPER \"egltrace.so\"\n#endif\n\n\nstatic inline bool\ncopyWrapper(const os::String & wrapperPath,\n const char *programPath,\n bool verbose)\n{\n os::String wrapperFilename(wrapperPath);\n wrapperFilename.trimDirectory();\n\n os::String tmpWrapper(programPath);\n tmpWrapper.trimFilename();\n tmpWrapper.join(wrapperFilename);\n\n if (verbose) {\n std::cerr << wrapperPath << \" -> \" << tmpWrapper << \"\\n\";\n }\n\n if (tmpWrapper.exists()) {\n std::cerr << \"error: not overwriting \" << tmpWrapper << \"\\n\";\n return false;\n }\n\n if (!os::copyFile(wrapperPath, tmpWrapper, false)) {\n std::cerr << \"error: failed to copy \" << wrapperPath << \" into \" << tmpWrapper << \"\\n\";\n return false;\n }\n\n return true;\n}\n\n\nstatic int\ntraceProgram(trace::API api,\n char * const *argv,\n const char *output,\n bool verbose,\n bool debug)\n{\n const char *wrapperFilename;\n std::vector<const char *> args;\n int status = 1;\n\n \/*\n * TODO: simplify code\n *\/\n\n bool useInject = false;\n switch (api) {\n case trace::API_GL:\n wrapperFilename = GL_TRACE_WRAPPER;\n break;\n#ifdef EGL_TRACE_WRAPPER\n case trace::API_EGL:\n wrapperFilename = EGL_TRACE_WRAPPER;\n break;\n#endif\n#ifdef _WIN32\n case trace::API_D3D7:\n wrapperFilename = \"ddraw.dll\";\n break;\n case trace::API_D3D8:\n wrapperFilename = \"d3d8.dll\";\n break;\n case trace::API_D3D9:\n wrapperFilename = \"d3d9.dll\";\n break;\n case trace::API_DXGI:\n wrapperFilename = \"dxgitrace.dll\";\n useInject = true;\n break;\n case trace::API_D2D1:\n wrapperFilename = \"d2d1trace.dll\";\n useInject = true;\n break;\n#endif\n default:\n std::cerr << \"error: unsupported API\\n\";\n return 1;\n }\n\n os::String wrapperPath = findWrapper(wrapperFilename, verbose);\n if (!wrapperPath.length()) {\n std::cerr << \"error: failed to find \" << wrapperFilename << \" wrapper (rerun with -v option for more details)\\n\";\n goto exit;\n }\n\n#if defined(_WIN32)\n \/*\n * Use DLL injection method on Windows, even for APIs that don't stricly\n * need it.\n *\/\n useInject = true;\n\n if (useInject) {\n args.push_back(\"inject\");\n args.push_back(wrapperPath);\n } else {\n \/* On Windows copy the wrapper to the program directory.\n *\/\n if (!copyWrapper(wrapperPath, argv[0], verbose)) {\n goto exit;\n }\n }\n#else \/* !_WIN32 *\/\n (void)useInject;\n#endif \/* !_WIN32 *\/\n\n#if defined(__APPLE__)\n \/* On Mac OS X, using DYLD_LIBRARY_PATH, we actually set the\n * parent directory, not the file. *\/\n wrapperPath.trimFilename();\n wrapperPath.trimFilename();\n#endif\n\n \/*\n * Spawn child process.\n *\/\n\n {\n#if defined(TRACE_VARIABLE)\n const char *oldEnvVarValue = getenv(TRACE_VARIABLE);\n if (oldEnvVarValue) {\n wrapperPath.append(OS_PATH_SEP);\n wrapperPath.append(oldEnvVarValue);\n }\n\n if (debug) {\n std::string ex(\"set exec-wrapper env \" TRACE_VARIABLE \"=\");\n ex.append(wrapperPath.str());\n\n args.push_back(\"gdb\");\n args.push_back(\"--ex\");\n args.push_back(ex.c_str());\n args.push_back(\"--args\");\n\n os::unsetEnvironment(TRACE_VARIABLE);\n } else {\n \/* FIXME: Don't modify our (ie parent) environment *\/\n os::setEnvironment(TRACE_VARIABLE, wrapperPath.str());\n }\n\n if (verbose) {\n std::cerr << TRACE_VARIABLE << \"=\" << wrapperPath.str() << \"\\n\";\n }\n#endif \/* TRACE_VARIABLE *\/\n\n if (output) {\n os::setEnvironment(\"TRACE_FILE\", output);\n }\n\n for (char * const * arg = argv; *arg; ++arg) {\n args.push_back(*arg);\n }\n\n if (verbose) {\n const char *sep = \"\";\n for (unsigned i = 0; i < args.size(); ++i) {\n const char *quote;\n if (strchr(args[i], ' ') != NULL) {\n quote = \"\\\"\";\n } else {\n quote = \"\";\n }\n std::cerr << sep << quote << args[i] << quote;\n sep = \" \";\n }\n std::cerr << \"\\n\";\n }\n\n args.push_back(NULL);\n\n status = os::execute((char * const *)&args[0]);\n\n#if defined(TRACE_VARIABLE)\n if (oldEnvVarValue) {\n os::setEnvironment(TRACE_VARIABLE, oldEnvVarValue);\n } else {\n os::unsetEnvironment(TRACE_VARIABLE);\n }\n#endif\n }\n\nexit:\n#if defined(_WIN32)\n if (!useInject) {\n os::String tmpWrapper(argv[0]);\n tmpWrapper.trimFilename();\n tmpWrapper.join(wrapperFilename);\n os::removeFile(tmpWrapper);\n }\n#endif\n\n if (output) {\n os::unsetEnvironment(\"TRACE_FILE\");\n }\n \n return status;\n\n}\n\n\nstatic const char *synopsis = \"Generate a new trace by executing the given program.\";\n\nstatic void\nusage(void)\n{\n std::cout << \"usage: apitrace trace [OPTIONS] PROGRAM [ARGS ...]\\n\"\n << synopsis << \"\\n\"\n \"\\n\"\n \" The given program will be executed with the given arguments.\\n\"\n \" During execution, all OpenGL calls will be captured to a trace\\n\"\n \" file. That trace file can then be used\\n\"\n \" with other apitrace utilities for replay or analysis.\\n\"\n \"\\n\"\n \" -v, --verbose verbose output\\n\"\n \" -a, --api=API specify API to trace (\"\n#ifdef _WIN32\n \"gl, d3d7, d3d8, d3d9, or dxgi (for d3d10 and higher) \"\n#else\n \"gl or egl\"\n#endif\n \");\\n\"\n \" default is `gl`\\n\"\n \" -o, --output=TRACE specify output trace file;\\n\"\n \" default is `PROGRAM.trace`\\n\"\n#ifdef TRACE_VARIABLE\n \" -d, --debug debug with gdb\\n\"\n#endif\n ;\n}\n\nconst static char *\nshortOptions = \"+hva:o:d\";\n\nconst static struct option\nlongOptions[] = {\n {\"help\", no_argument, 0, 'h'},\n {\"verbose\", no_argument, 0, 'v'},\n {\"api\", required_argument, 0, 'a'},\n {\"output\", required_argument, 0, 'o'},\n {\"debug\", no_argument, 0, 'd'},\n {0, 0, 0, 0}\n};\n\nstatic int\ncommand(int argc, char *argv[])\n{\n bool verbose = false;\n trace::API api = trace::API_GL;\n const char *output = NULL;\n bool debug = false;\n\n int opt;\n while ((opt = getopt_long(argc, argv, shortOptions, longOptions, NULL)) != -1) {\n switch (opt) {\n case 'h':\n usage();\n return 0;\n case 'v':\n verbose = true;\n break;\n case 'a':\n if (strcmp(optarg, \"gl\") == 0) {\n api = trace::API_GL;\n } else if (strcmp(optarg, \"egl\") == 0) {\n api = trace::API_EGL;\n } else if (strcmp(optarg, \"d3d7\") == 0) {\n api = trace::API_D3D7;\n } else if (strcmp(optarg, \"d3d8\") == 0) {\n api = trace::API_D3D8;\n } else if (strcmp(optarg, \"d3d9\") == 0) {\n api = trace::API_D3D9;\n } else if (strcmp(optarg, \"dxgi\") == 0 ||\n strcmp(optarg, \"d3d10\") == 0 ||\n strcmp(optarg, \"d3d10_1\") == 0 ||\n strcmp(optarg, \"d3d11\") == 0 ||\n strcmp(optarg, \"d3d11_1\") == 0) {\n api = trace::API_DXGI;\n } else if (strcmp(optarg, \"d2d\") == 0 ||\n strcmp(optarg, \"d2d1\") == 0) {\n api = trace::API_D2D1;\n } else {\n std::cerr << \"error: unknown API `\" << optarg << \"`\\n\";\n usage();\n return 1;\n }\n break;\n case 'o':\n output = optarg;\n break;\n case 'd':\n debug = true;\n break;\n default:\n std::cerr << \"error: unexpected option `\" << (char)opt << \"`\\n\";\n usage();\n return 1;\n }\n }\n\n if (optind == argc) {\n std::cerr << \"error: no command specified\\n\";\n usage();\n return 1;\n }\n\n assert(argv[argc] == 0);\n return traceProgram(api, argv + optind, output, verbose, debug);\n}\n\nconst Command trace_command = {\n \"trace\",\n synopsis,\n usage,\n command\n};\n<commit_msg>cli: Use LLDB on MacOSX when tracing inside debugger.<commit_after>\/*********************************************************************\n *\n * Copyright 2011 Intel Corporation\n * All Rights Reserved.\n *\n * Permission is hereby granted, free of charge, to any person\n * obtaining a copy of this software and associated documentation\n * files (the \"Software\"), to deal in the Software without\n * restriction, including without limitation the rights to use, copy,\n * modify, merge, publish, distribute, sublicense, and\/or sell copies\n * of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be\n * included in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS\n * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN\n * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n *\n *********************************************************************\/\n\n\n#include <assert.h>\n#include <string.h>\n#include <stdlib.h>\n#include <getopt.h>\n\n#include <iostream>\n#include <fstream>\n\n#include \"os_string.hpp\"\n#include \"os_process.hpp\"\n#include \"os_version.hpp\"\n\n#include \"cli.hpp\"\n#include \"cli_resources.hpp\"\n\n\n#if defined(__APPLE__)\n#define TRACE_VARIABLE \"DYLD_FRAMEWORK_PATH\"\n#define GL_TRACE_WRAPPER \"OpenGL.framework\/OpenGL\"\n#elif defined(_WIN32)\n#define GL_TRACE_WRAPPER \"opengl32.dll\"\n#else\n#define TRACE_VARIABLE \"LD_PRELOAD\"\n#define GL_TRACE_WRAPPER \"glxtrace.so\"\n#define EGL_TRACE_WRAPPER \"egltrace.so\"\n#endif\n\n\nstatic inline bool\ncopyWrapper(const os::String & wrapperPath,\n const char *programPath,\n bool verbose)\n{\n os::String wrapperFilename(wrapperPath);\n wrapperFilename.trimDirectory();\n\n os::String tmpWrapper(programPath);\n tmpWrapper.trimFilename();\n tmpWrapper.join(wrapperFilename);\n\n if (verbose) {\n std::cerr << wrapperPath << \" -> \" << tmpWrapper << \"\\n\";\n }\n\n if (tmpWrapper.exists()) {\n std::cerr << \"error: not overwriting \" << tmpWrapper << \"\\n\";\n return false;\n }\n\n if (!os::copyFile(wrapperPath, tmpWrapper, false)) {\n std::cerr << \"error: failed to copy \" << wrapperPath << \" into \" << tmpWrapper << \"\\n\";\n return false;\n }\n\n return true;\n}\n\n\nstatic int\ntraceProgram(trace::API api,\n char * const *argv,\n const char *output,\n bool verbose,\n bool debug)\n{\n const char *wrapperFilename;\n std::vector<const char *> args;\n int status = 1;\n\n \/*\n * TODO: simplify code\n *\/\n\n bool useInject = false;\n switch (api) {\n case trace::API_GL:\n wrapperFilename = GL_TRACE_WRAPPER;\n break;\n#ifdef EGL_TRACE_WRAPPER\n case trace::API_EGL:\n wrapperFilename = EGL_TRACE_WRAPPER;\n break;\n#endif\n#ifdef _WIN32\n case trace::API_D3D7:\n wrapperFilename = \"ddraw.dll\";\n break;\n case trace::API_D3D8:\n wrapperFilename = \"d3d8.dll\";\n break;\n case trace::API_D3D9:\n wrapperFilename = \"d3d9.dll\";\n break;\n case trace::API_DXGI:\n wrapperFilename = \"dxgitrace.dll\";\n useInject = true;\n break;\n case trace::API_D2D1:\n wrapperFilename = \"d2d1trace.dll\";\n useInject = true;\n break;\n#endif\n default:\n std::cerr << \"error: unsupported API\\n\";\n return 1;\n }\n\n os::String wrapperPath = findWrapper(wrapperFilename, verbose);\n if (!wrapperPath.length()) {\n std::cerr << \"error: failed to find \" << wrapperFilename << \" wrapper (rerun with -v option for more details)\\n\";\n goto exit;\n }\n\n#if defined(_WIN32)\n \/*\n * Use DLL injection method on Windows, even for APIs that don't stricly\n * need it.\n *\/\n useInject = true;\n\n if (useInject) {\n args.push_back(\"inject\");\n args.push_back(wrapperPath);\n } else {\n \/* On Windows copy the wrapper to the program directory.\n *\/\n if (!copyWrapper(wrapperPath, argv[0], verbose)) {\n goto exit;\n }\n }\n#else \/* !_WIN32 *\/\n (void)useInject;\n#endif \/* !_WIN32 *\/\n\n#if defined(__APPLE__)\n \/* On Mac OS X, using DYLD_LIBRARY_PATH, we actually set the\n * parent directory, not the file. *\/\n wrapperPath.trimFilename();\n wrapperPath.trimFilename();\n#endif\n\n \/*\n * Spawn child process.\n *\/\n\n {\n#if defined(TRACE_VARIABLE)\n const char *oldEnvVarValue = getenv(TRACE_VARIABLE);\n if (oldEnvVarValue) {\n wrapperPath.append(OS_PATH_SEP);\n wrapperPath.append(oldEnvVarValue);\n }\n\n if (debug) {\n#if defined(__APPLE__)\n bool lldb = true;\n#else\n bool lldb = false;\n#endif\n\n if (lldb) {\n \/*\n * Debug with LLDB.\n *\n * See also http:\/\/lldb.llvm.org\/lldb-gdb.html\n *\/\n\n char scriptFileName[] = \"\/tmp\/apitrace.XXXXXX\";\n if (mktemp(scriptFileName) == NULL) {\n std::cerr << \"error: failed to create temporary lldb script file\\n\";\n exit(1);\n }\n\n {\n std::ofstream scriptStream(scriptFileName);\n scriptStream << \"env \" TRACE_VARIABLE \"='\" << wrapperPath.str() << \"'\\n\";\n }\n\n args.push_back(\"lldb\");\n args.push_back(\"-s\");\n args.push_back(scriptFileName);\n args.push_back(\"--\");\n } else {\n \/*\n * Debug with GDB.\n *\/\n\n std::string ex(\"set exec-wrapper env \" TRACE_VARIABLE \"='\");\n ex.append(wrapperPath.str());\n ex.append(\"'\");\n\n args.push_back(\"gdb\");\n args.push_back(\"--ex\");\n args.push_back(ex.c_str());\n args.push_back(\"--args\");\n }\n\n os::unsetEnvironment(TRACE_VARIABLE);\n } else {\n \/* FIXME: Don't modify our (ie parent) environment *\/\n os::setEnvironment(TRACE_VARIABLE, wrapperPath.str());\n }\n\n if (verbose) {\n std::cerr << TRACE_VARIABLE << \"=\" << wrapperPath.str() << \"\\n\";\n }\n#endif \/* TRACE_VARIABLE *\/\n\n if (output) {\n os::setEnvironment(\"TRACE_FILE\", output);\n }\n\n for (char * const * arg = argv; *arg; ++arg) {\n args.push_back(*arg);\n }\n\n if (verbose) {\n const char *sep = \"\";\n for (unsigned i = 0; i < args.size(); ++i) {\n const char *quote;\n if (strchr(args[i], ' ') != NULL) {\n quote = \"\\\"\";\n } else {\n quote = \"\";\n }\n std::cerr << sep << quote << args[i] << quote;\n sep = \" \";\n }\n std::cerr << \"\\n\";\n }\n\n args.push_back(NULL);\n\n status = os::execute((char * const *)&args[0]);\n\n#if defined(TRACE_VARIABLE)\n if (oldEnvVarValue) {\n os::setEnvironment(TRACE_VARIABLE, oldEnvVarValue);\n } else {\n os::unsetEnvironment(TRACE_VARIABLE);\n }\n#endif\n }\n\nexit:\n#if defined(_WIN32)\n if (!useInject) {\n os::String tmpWrapper(argv[0]);\n tmpWrapper.trimFilename();\n tmpWrapper.join(wrapperFilename);\n os::removeFile(tmpWrapper);\n }\n#endif\n\n if (output) {\n os::unsetEnvironment(\"TRACE_FILE\");\n }\n \n return status;\n\n}\n\n\nstatic const char *synopsis = \"Generate a new trace by executing the given program.\";\n\nstatic void\nusage(void)\n{\n std::cout << \"usage: apitrace trace [OPTIONS] PROGRAM [ARGS ...]\\n\"\n << synopsis << \"\\n\"\n \"\\n\"\n \" The given program will be executed with the given arguments.\\n\"\n \" During execution, all OpenGL calls will be captured to a trace\\n\"\n \" file. That trace file can then be used\\n\"\n \" with other apitrace utilities for replay or analysis.\\n\"\n \"\\n\"\n \" -v, --verbose verbose output\\n\"\n \" -a, --api=API specify API to trace (\"\n#ifdef _WIN32\n \"gl, d3d7, d3d8, d3d9, or dxgi (for d3d10 and higher) \"\n#else\n \"gl or egl\"\n#endif\n \");\\n\"\n \" default is `gl`\\n\"\n \" -o, --output=TRACE specify output trace file;\\n\"\n \" default is `PROGRAM.trace`\\n\"\n#ifdef TRACE_VARIABLE\n \" -d, --debug run inside debugger (gdb\/lldb)\\n\"\n#endif\n ;\n}\n\nconst static char *\nshortOptions = \"+hva:o:d\";\n\nconst static struct option\nlongOptions[] = {\n {\"help\", no_argument, 0, 'h'},\n {\"verbose\", no_argument, 0, 'v'},\n {\"api\", required_argument, 0, 'a'},\n {\"output\", required_argument, 0, 'o'},\n {\"debug\", no_argument, 0, 'd'},\n {0, 0, 0, 0}\n};\n\nstatic int\ncommand(int argc, char *argv[])\n{\n bool verbose = false;\n trace::API api = trace::API_GL;\n const char *output = NULL;\n bool debug = false;\n\n int opt;\n while ((opt = getopt_long(argc, argv, shortOptions, longOptions, NULL)) != -1) {\n switch (opt) {\n case 'h':\n usage();\n return 0;\n case 'v':\n verbose = true;\n break;\n case 'a':\n if (strcmp(optarg, \"gl\") == 0) {\n api = trace::API_GL;\n } else if (strcmp(optarg, \"egl\") == 0) {\n api = trace::API_EGL;\n } else if (strcmp(optarg, \"d3d7\") == 0) {\n api = trace::API_D3D7;\n } else if (strcmp(optarg, \"d3d8\") == 0) {\n api = trace::API_D3D8;\n } else if (strcmp(optarg, \"d3d9\") == 0) {\n api = trace::API_D3D9;\n } else if (strcmp(optarg, \"dxgi\") == 0 ||\n strcmp(optarg, \"d3d10\") == 0 ||\n strcmp(optarg, \"d3d10_1\") == 0 ||\n strcmp(optarg, \"d3d11\") == 0 ||\n strcmp(optarg, \"d3d11_1\") == 0) {\n api = trace::API_DXGI;\n } else if (strcmp(optarg, \"d2d\") == 0 ||\n strcmp(optarg, \"d2d1\") == 0) {\n api = trace::API_D2D1;\n } else {\n std::cerr << \"error: unknown API `\" << optarg << \"`\\n\";\n usage();\n return 1;\n }\n break;\n case 'o':\n output = optarg;\n break;\n case 'd':\n debug = true;\n break;\n default:\n std::cerr << \"error: unexpected option `\" << (char)opt << \"`\\n\";\n usage();\n return 1;\n }\n }\n\n if (optind == argc) {\n std::cerr << \"error: no command specified\\n\";\n usage();\n return 1;\n }\n\n assert(argv[argc] == 0);\n return traceProgram(api, argv + optind, output, verbose, debug);\n}\n\nconst Command trace_command = {\n \"trace\",\n synopsis,\n usage,\n command\n};\n<|endoftext|>"} {"text":"<commit_before>\/* Copyright (C) 2003 MySQL AB\n\n This program is free software; you can redistribute it and\/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation; either version 2 of the License, or\n (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with this program; if not, write to the Free Software\n Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *\/\n\n#include <ndb_global.h>\n#include <SimpleProperties.hpp>\n#include <NdbOut.hpp>\n#include <NdbTCP.h>\n#include <UtilBuffer.hpp>\n\nbool\nSimpleProperties::Writer::first(){\n return reset();\n}\n\nbool \nSimpleProperties::Writer::add(Uint16 key, Uint32 value){\n Uint32 head = Uint32Value; \n head <<= 16;\n head += key;\n if(!putWord(htonl(head)))\n return false;\n \n return putWord(htonl(value));\n}\n\nbool\nSimpleProperties::Writer::add(const char * value, int len){\n const Uint32 valLen = (len + 3) \/ 4;\n\n if ((len % 4) == 0)\n return putWords((Uint32*)value, valLen);\n\n const Uint32 putLen= valLen - 1;\n if (!putWords((Uint32*)value, putLen))\n return false;\n\n \/\/ Special handling of last bytes\n union {\n Uint32 lastWord;\n char lastBytes[4];\n };\n memcpy(lastBytes,\n value + putLen*4,\n len - putLen*4);\n return putWord(lastWord);\n}\n\nbool\nSimpleProperties::Writer::add(Uint16 key, const char * value){\n Uint32 head = StringValue;\n head <<= 16;\n head += key;\n if(!putWord(htonl(head)))\n return false;\n Uint32 strLen = strlen(value) + 1; \/\/ Including NULL-byte\n if(!putWord(htonl(strLen)))\n return false;\n\n return add(value, (int)strLen);\n\n}\n\nbool\nSimpleProperties::Writer::add(Uint16 key, const void* value, int len){\n Uint32 head = BinaryValue;\n head <<= 16;\n head += key;\n if(!putWord(htonl(head)))\n return false;\n if(!putWord(htonl(len)))\n return false;\n\n return add((const char*)value, len);\n}\n\nSimpleProperties::Reader::Reader(){\n m_itemLen = 0;\n}\n\nbool \nSimpleProperties::Reader::first(){\n reset();\n m_itemLen = 0;\n return readValue();\n}\n\nbool\nSimpleProperties::Reader::next(){\n return readValue();\n}\n \nbool\nSimpleProperties::Reader::valid() const {\n return m_type != InvalidValue;\n}\n\nUint16\nSimpleProperties::Reader::getKey() const{\n return m_key;\n}\n\nUint16\nSimpleProperties::Reader::getValueLen() const {\n switch(m_type){\n case Uint32Value:\n return 4;\n case StringValue:\n case BinaryValue:\n return m_strLen;\n case InvalidValue:\n return 0;\n }\n return 0;\n}\n\nSimpleProperties::ValueType\nSimpleProperties::Reader::getValueType() const {\n return m_type;\n}\n \nUint32\nSimpleProperties::Reader::getUint32() const {\n return m_ui32_value;\n}\n\nchar * \nSimpleProperties::Reader::getString(char * dst) const {\n if(peekWords((Uint32*)dst, m_itemLen))\n return dst;\n return 0;\n}\n\nbool\nSimpleProperties::Reader::readValue(){\n if(!step(m_itemLen)){\n m_type = InvalidValue;\n return false;\n }\n \n Uint32 tmp;\n if(!getWord(&tmp)){\n m_type = InvalidValue;\n return false;\n }\n\n tmp = ntohl(tmp);\n m_key = tmp & 0xFFFF;\n m_type = (SimpleProperties::ValueType)(tmp >> 16);\n switch(m_type){\n case Uint32Value:\n m_itemLen = 1;\n if(!peekWord(&m_ui32_value))\n return false;\n m_ui32_value = ntohl(m_ui32_value);\n return true;\n case StringValue:\n case BinaryValue:\n if(!getWord(&tmp))\n return false;\n m_strLen = ntohl(tmp);\n m_itemLen = (m_strLen + 3)\/4;\n return true;\n default:\n m_itemLen = 0;\n m_type = InvalidValue;\n return false;\n }\n}\n\nSimpleProperties::UnpackStatus \nSimpleProperties::unpack(Reader & it, void * dst, \n\t\t\t const SP2StructMapping _map[], Uint32 mapSz,\n\t\t\t bool ignoreMinMax,\n\t\t\t bool ignoreUnknownKeys){\n do {\n if(!it.valid())\n break;\n \n bool found = false;\n Uint16 key = it.getKey();\n for(Uint32 i = 0; i<mapSz; i++){\n if(key == _map[i].Key){\n\tfound = true;\n\tif(_map[i].Type == InvalidValue)\n\t return Break;\n\tif(_map[i].Type != it.getValueType())\n\t return TypeMismatch;\n\t\n\tchar * _dst = (char *)dst;\n\t_dst += _map[i].Offset;\n\t\n\tswitch(it.getValueType()){\n\tcase Uint32Value:{\n\t const Uint32 val = it.getUint32();\n\t if(!ignoreMinMax){\n\t if(val < _map[i].minValue)\n\t return ValueTooLow;\n\t if(val > _map[i].maxValue)\n\t return ValueTooHigh;\n\t }\n\t * ((Uint32 *)_dst) = val;\n\t break;\n }\n\tcase BinaryValue:\n case StringValue:{\n\t unsigned len = it.getValueLen();\n\t if(len < _map[i].minValue)\n\t return ValueTooLow;\n\t if(len > _map[i].maxValue)\n\t return ValueTooHigh;\n it.getString(_dst);\n break;\n\t}\n\tdefault:\n\t abort();\n\t}\n\tbreak;\n }\n }\n if(!found && !ignoreUnknownKeys)\n return UnknownKey;\n } while(it.next());\n \n return Eof;\n}\n\nSimpleProperties::UnpackStatus \nSimpleProperties::pack(Writer & it, const void * __src, \n\t\t const SP2StructMapping _map[], Uint32 mapSz,\n\t\t bool ignoreMinMax){\n\n const char * _src = (const char *)__src;\n\n for(Uint32 i = 0; i<mapSz; i++){\n bool ok = false;\n const char * src = _src + _map[i].Offset;\n switch(_map[i].Type){\n case SimpleProperties::InvalidValue:\n ok = true;\n break;\n case SimpleProperties::Uint32Value:{\n Uint32 val = * ((Uint32*)src);\n if(!ignoreMinMax){\n\tif(val < _map[i].minValue)\n\t return ValueTooLow;\n\tif(val > _map[i].maxValue)\n\t return ValueTooHigh;\n }\n ok = it.add(_map[i].Key, val);\n }\n break;\n case SimpleProperties::BinaryValue:{\n const char * src_len = _src + _map[i].Length_Offset;\n Uint32 len = *((Uint32*)src_len);\n if(!ignoreMinMax){\n\tif(len == _map[i].maxValue)\n\t return ValueTooHigh;\n }\n ok = it.add(_map[i].Key, src, len);\n break;\n }\n case SimpleProperties::StringValue:\n if(!ignoreMinMax){\n\tsize_t len = strlen(src);\n\tif(len == _map[i].maxValue)\n\t return ValueTooHigh;\n }\n ok = it.add(_map[i].Key, src);\n break;\n }\n if(!ok)\n return OutOfMemory;\n }\n \n return Eof;\n}\n\nvoid\nSimpleProperties::Reader::printAll(NdbOut& ndbout){\n char tmp[1024];\n for(first(); valid(); next()){\n switch(getValueType()){\n case SimpleProperties::Uint32Value:\n ndbout << \"Key: \" << getKey()\n << \" value(\" << getValueLen() << \") : \" \n << getUint32() << endl;\n break;\n case SimpleProperties::BinaryValue:\n case SimpleProperties::StringValue:\n if(getValueLen() < 1024){\n\tgetString(tmp);\n\tndbout << \"Key: \" << getKey()\n\t << \" value(\" << getValueLen() << \") : \" \n\t << \"\\\"\" << tmp << \"\\\"\" << endl;\n } else {\n\tndbout << \"Key: \" << getKey()\n\t << \" value(\" << getValueLen() << \") : \" \n\t << \"\\\"\" << \"<TOO LONG>\" << \"\\\"\" << endl;\n\t\n }\n break;\n default:\n ndbout << \"Unknown type for key: \" << getKey() \n << \" type: \" << (Uint32)getValueType() << endl;\n }\n }\n}\n\nSimplePropertiesLinearReader::SimplePropertiesLinearReader\n(const Uint32 * src, Uint32 len){\n m_src = src;\n m_len = len;\n m_pos = 0;\n first();\n}\n\nvoid \nSimplePropertiesLinearReader::reset() { \n m_pos = 0;\n}\n\nbool \nSimplePropertiesLinearReader::step(Uint32 len){\n m_pos += len;\n return m_pos < m_len;\n}\n \nbool\nSimplePropertiesLinearReader::getWord(Uint32 * dst) { \n if(m_pos<m_len){\n * dst = m_src[m_pos++];\n return true;\n } \n return false;\n}\n\nbool \nSimplePropertiesLinearReader::peekWord(Uint32 * dst) const {\n if(m_pos<m_len){\n * dst = m_src[m_pos];\n return true;\n } \n return false;\n}\n\nbool \nSimplePropertiesLinearReader::peekWords(Uint32 * dst, Uint32 len) const {\n if(m_pos + len <= m_len){\n memcpy(dst, &m_src[m_pos], 4 * len);\n return true;\n }\n return false;\n}\n\nLinearWriter::LinearWriter(Uint32 * src, Uint32 len){\n m_src = src;\n m_len = len;\n reset();\n}\n\nbool LinearWriter::reset() { m_pos = 0; return m_len > 0;}\n\nbool \nLinearWriter::putWord(Uint32 val){\n if(m_pos < m_len){\n m_src[m_pos++] = val;\n return true;\n }\n return false;\n}\n\nbool \nLinearWriter::putWords(const Uint32 * src, Uint32 len){\n if(m_pos + len <= m_len){\n memcpy(&m_src[m_pos], src, 4 * len);\n m_pos += len;\n return true;\n }\n return false;\n}\n\nUint32\nLinearWriter::getWordsUsed() const { return m_pos;}\n\nUtilBufferWriter::UtilBufferWriter(UtilBuffer & b)\n : m_buf(b)\n{\n reset();\n}\n\nbool UtilBufferWriter::reset() { m_buf.clear(); return true;}\n\nbool \nUtilBufferWriter::putWord(Uint32 val){\n return (m_buf.append(&val, 4) == 0);\n}\n\nbool \nUtilBufferWriter::putWords(const Uint32 * src, Uint32 len){\n return (m_buf.append(src, 4 * len) == 0);\n}\n\n\nUint32\nUtilBufferWriter::getWordsUsed() const { return m_buf.length() \/ 4;}\n\n#if 0\nLinearPagesReader::LinearPagesReader(const Uint32 * base, \n\t\t\t\t Uint32 pageSize, \n\t\t\t\t Uint32 headerSize,\n\t\t\t\t Uint32 noOfPages, \n\t\t\t\t Uint32 len){\n m_base = base;\n m_pageSz = pageSize;\n m_noOfPages = noOfPages;\n m_pageHeaderSz = headerSize;\n m_len = len;\n reset();\n}\n\nvoid \nLinearPagesReader::reset() { m_pos = 0;}\n\nbool \nLinearPagesReader::step(Uint32 len){\n m_pos += len;\n return m_pos < m_len;\n}\n\nbool \nLinearPagesReader::getWord(Uint32 * dst) { \n if(m_pos<m_len){\n * dst = m_base[getPos(m_pos++)];\n return true;\n } \n return false;\n}\n\nbool \nLinearPagesReader::peekWord(Uint32 * dst) const {\n if(m_pos<m_len){\n * dst = m_base[getPos(m_pos)];\n return true;\n } \n return false;\n}\n\nbool \nLinearPagesReader::peekWords(Uint32 * dst, Uint32 len) const {\n if(m_pos + len <= m_len){\n for(Uint32 i = 0; i<len; i++)\n * (dst + i) = m_base[getPos(m_pos + i)];\n return true;\n }\n return false;\n}\n\nUint32 \nLinearPagesReader::getPos(Uint32 pos) const {\n const Uint32 sz = (m_pageSz - m_pageHeaderSz);\n Uint32 no = pos \/ sz;\n Uint32 in = pos % sz;\n return no * m_pageSz + m_pageHeaderSz + in;\n}\n\nLinearPagesWriter::LinearPagesWriter(Uint32 * base, \n\t\t\t\t Uint32 pageSize, \n\t\t\t\t Uint32 noOfPages, \n\t\t\t\t Uint32 headerSize){\n m_base = base;\n m_pageSz = pageSize;\n m_noOfPages = noOfPages;\n m_pageHeaderSz = headerSize;\n m_len = noOfPages * (pageSize - headerSize);\n reset();\n}\n\nbool \nLinearPagesWriter::putWord(Uint32 val){\n if(m_pos < m_len){\n m_base[getPos(m_pos++)] = val;\n return true;\n }\n return false;\n}\n\nbool \nLinearPagesWriter::putWords(const Uint32 * src, Uint32 len){\n if(m_pos + len <= m_len){\n for(Uint32 i = 0; i<len; i++)\n m_base[getPos(m_pos++)] = src[i];\n return true;\n }\n return false;\n}\n\n#if 0\nUint32 \nLinearPagesWriter::getWordsUsed() const { \n return getPos(m_pos);\n}\n#endif\n\nUint32 \nLinearPagesWriter::getPagesUsed() const { \n return m_pos \/ (m_pageSz - m_pageHeaderSz);\n}\n\nUint32 \nLinearPagesWriter::getPos(Uint32 pos) const {\n const Uint32 sz = (m_pageSz - m_pageHeaderSz);\n Uint32 no = pos \/ sz;\n Uint32 in = pos % sz;\n return no * m_pageSz + m_pageHeaderSz + in;\n}\n#endif\n<commit_msg>ndb - Fix compile error with gcc296<commit_after>\/* Copyright (C) 2003 MySQL AB\n\n This program is free software; you can redistribute it and\/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation; either version 2 of the License, or\n (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with this program; if not, write to the Free Software\n Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *\/\n\n#include <ndb_global.h>\n#include <SimpleProperties.hpp>\n#include <NdbOut.hpp>\n#include <NdbTCP.h>\n#include <UtilBuffer.hpp>\n\nbool\nSimpleProperties::Writer::first(){\n return reset();\n}\n\nbool \nSimpleProperties::Writer::add(Uint16 key, Uint32 value){\n Uint32 head = Uint32Value; \n head <<= 16;\n head += key;\n if(!putWord(htonl(head)))\n return false;\n \n return putWord(htonl(value));\n}\n\nbool\nSimpleProperties::Writer::add(const char * value, int len){\n const Uint32 valLen = (len + 3) \/ 4;\n\n if ((len % 4) == 0)\n return putWords((Uint32*)value, valLen);\n\n const Uint32 putLen= valLen - 1;\n if (!putWords((Uint32*)value, putLen))\n return false;\n\n \/\/ Special handling of last bytes\n union {\n Uint32 lastWord;\n char lastBytes[4];\n } tmp;\n tmp.lastWord =0 ;\n memcpy(tmp.lastBytes,\n value + putLen*4,\n len - putLen*4);\n return putWord(tmp.lastWord);\n}\n\nbool\nSimpleProperties::Writer::add(Uint16 key, const char * value){\n Uint32 head = StringValue;\n head <<= 16;\n head += key;\n if(!putWord(htonl(head)))\n return false;\n Uint32 strLen = strlen(value) + 1; \/\/ Including NULL-byte\n if(!putWord(htonl(strLen)))\n return false;\n\n return add(value, (int)strLen);\n\n}\n\nbool\nSimpleProperties::Writer::add(Uint16 key, const void* value, int len){\n Uint32 head = BinaryValue;\n head <<= 16;\n head += key;\n if(!putWord(htonl(head)))\n return false;\n if(!putWord(htonl(len)))\n return false;\n\n return add((const char*)value, len);\n}\n\nSimpleProperties::Reader::Reader(){\n m_itemLen = 0;\n}\n\nbool \nSimpleProperties::Reader::first(){\n reset();\n m_itemLen = 0;\n return readValue();\n}\n\nbool\nSimpleProperties::Reader::next(){\n return readValue();\n}\n \nbool\nSimpleProperties::Reader::valid() const {\n return m_type != InvalidValue;\n}\n\nUint16\nSimpleProperties::Reader::getKey() const{\n return m_key;\n}\n\nUint16\nSimpleProperties::Reader::getValueLen() const {\n switch(m_type){\n case Uint32Value:\n return 4;\n case StringValue:\n case BinaryValue:\n return m_strLen;\n case InvalidValue:\n return 0;\n }\n return 0;\n}\n\nSimpleProperties::ValueType\nSimpleProperties::Reader::getValueType() const {\n return m_type;\n}\n \nUint32\nSimpleProperties::Reader::getUint32() const {\n return m_ui32_value;\n}\n\nchar * \nSimpleProperties::Reader::getString(char * dst) const {\n if(peekWords((Uint32*)dst, m_itemLen))\n return dst;\n return 0;\n}\n\nbool\nSimpleProperties::Reader::readValue(){\n if(!step(m_itemLen)){\n m_type = InvalidValue;\n return false;\n }\n \n Uint32 tmp;\n if(!getWord(&tmp)){\n m_type = InvalidValue;\n return false;\n }\n\n tmp = ntohl(tmp);\n m_key = tmp & 0xFFFF;\n m_type = (SimpleProperties::ValueType)(tmp >> 16);\n switch(m_type){\n case Uint32Value:\n m_itemLen = 1;\n if(!peekWord(&m_ui32_value))\n return false;\n m_ui32_value = ntohl(m_ui32_value);\n return true;\n case StringValue:\n case BinaryValue:\n if(!getWord(&tmp))\n return false;\n m_strLen = ntohl(tmp);\n m_itemLen = (m_strLen + 3)\/4;\n return true;\n default:\n m_itemLen = 0;\n m_type = InvalidValue;\n return false;\n }\n}\n\nSimpleProperties::UnpackStatus \nSimpleProperties::unpack(Reader & it, void * dst, \n\t\t\t const SP2StructMapping _map[], Uint32 mapSz,\n\t\t\t bool ignoreMinMax,\n\t\t\t bool ignoreUnknownKeys){\n do {\n if(!it.valid())\n break;\n \n bool found = false;\n Uint16 key = it.getKey();\n for(Uint32 i = 0; i<mapSz; i++){\n if(key == _map[i].Key){\n\tfound = true;\n\tif(_map[i].Type == InvalidValue)\n\t return Break;\n\tif(_map[i].Type != it.getValueType())\n\t return TypeMismatch;\n\t\n\tchar * _dst = (char *)dst;\n\t_dst += _map[i].Offset;\n\t\n\tswitch(it.getValueType()){\n\tcase Uint32Value:{\n\t const Uint32 val = it.getUint32();\n\t if(!ignoreMinMax){\n\t if(val < _map[i].minValue)\n\t return ValueTooLow;\n\t if(val > _map[i].maxValue)\n\t return ValueTooHigh;\n\t }\n\t * ((Uint32 *)_dst) = val;\n\t break;\n }\n\tcase BinaryValue:\n case StringValue:{\n\t unsigned len = it.getValueLen();\n\t if(len < _map[i].minValue)\n\t return ValueTooLow;\n\t if(len > _map[i].maxValue)\n\t return ValueTooHigh;\n it.getString(_dst);\n break;\n\t}\n\tdefault:\n\t abort();\n\t}\n\tbreak;\n }\n }\n if(!found && !ignoreUnknownKeys)\n return UnknownKey;\n } while(it.next());\n \n return Eof;\n}\n\nSimpleProperties::UnpackStatus \nSimpleProperties::pack(Writer & it, const void * __src, \n\t\t const SP2StructMapping _map[], Uint32 mapSz,\n\t\t bool ignoreMinMax){\n\n const char * _src = (const char *)__src;\n\n for(Uint32 i = 0; i<mapSz; i++){\n bool ok = false;\n const char * src = _src + _map[i].Offset;\n switch(_map[i].Type){\n case SimpleProperties::InvalidValue:\n ok = true;\n break;\n case SimpleProperties::Uint32Value:{\n Uint32 val = * ((Uint32*)src);\n if(!ignoreMinMax){\n\tif(val < _map[i].minValue)\n\t return ValueTooLow;\n\tif(val > _map[i].maxValue)\n\t return ValueTooHigh;\n }\n ok = it.add(_map[i].Key, val);\n }\n break;\n case SimpleProperties::BinaryValue:{\n const char * src_len = _src + _map[i].Length_Offset;\n Uint32 len = *((Uint32*)src_len);\n if(!ignoreMinMax){\n\tif(len == _map[i].maxValue)\n\t return ValueTooHigh;\n }\n ok = it.add(_map[i].Key, src, len);\n break;\n }\n case SimpleProperties::StringValue:\n if(!ignoreMinMax){\n\tsize_t len = strlen(src);\n\tif(len == _map[i].maxValue)\n\t return ValueTooHigh;\n }\n ok = it.add(_map[i].Key, src);\n break;\n }\n if(!ok)\n return OutOfMemory;\n }\n \n return Eof;\n}\n\nvoid\nSimpleProperties::Reader::printAll(NdbOut& ndbout){\n char tmp[1024];\n for(first(); valid(); next()){\n switch(getValueType()){\n case SimpleProperties::Uint32Value:\n ndbout << \"Key: \" << getKey()\n << \" value(\" << getValueLen() << \") : \" \n << getUint32() << endl;\n break;\n case SimpleProperties::BinaryValue:\n case SimpleProperties::StringValue:\n if(getValueLen() < 1024){\n\tgetString(tmp);\n\tndbout << \"Key: \" << getKey()\n\t << \" value(\" << getValueLen() << \") : \" \n\t << \"\\\"\" << tmp << \"\\\"\" << endl;\n } else {\n\tndbout << \"Key: \" << getKey()\n\t << \" value(\" << getValueLen() << \") : \" \n\t << \"\\\"\" << \"<TOO LONG>\" << \"\\\"\" << endl;\n\t\n }\n break;\n default:\n ndbout << \"Unknown type for key: \" << getKey() \n << \" type: \" << (Uint32)getValueType() << endl;\n }\n }\n}\n\nSimplePropertiesLinearReader::SimplePropertiesLinearReader\n(const Uint32 * src, Uint32 len){\n m_src = src;\n m_len = len;\n m_pos = 0;\n first();\n}\n\nvoid \nSimplePropertiesLinearReader::reset() { \n m_pos = 0;\n}\n\nbool \nSimplePropertiesLinearReader::step(Uint32 len){\n m_pos += len;\n return m_pos < m_len;\n}\n \nbool\nSimplePropertiesLinearReader::getWord(Uint32 * dst) { \n if(m_pos<m_len){\n * dst = m_src[m_pos++];\n return true;\n } \n return false;\n}\n\nbool \nSimplePropertiesLinearReader::peekWord(Uint32 * dst) const {\n if(m_pos<m_len){\n * dst = m_src[m_pos];\n return true;\n } \n return false;\n}\n\nbool \nSimplePropertiesLinearReader::peekWords(Uint32 * dst, Uint32 len) const {\n if(m_pos + len <= m_len){\n memcpy(dst, &m_src[m_pos], 4 * len);\n return true;\n }\n return false;\n}\n\nLinearWriter::LinearWriter(Uint32 * src, Uint32 len){\n m_src = src;\n m_len = len;\n reset();\n}\n\nbool LinearWriter::reset() { m_pos = 0; return m_len > 0;}\n\nbool \nLinearWriter::putWord(Uint32 val){\n if(m_pos < m_len){\n m_src[m_pos++] = val;\n return true;\n }\n return false;\n}\n\nbool \nLinearWriter::putWords(const Uint32 * src, Uint32 len){\n if(m_pos + len <= m_len){\n memcpy(&m_src[m_pos], src, 4 * len);\n m_pos += len;\n return true;\n }\n return false;\n}\n\nUint32\nLinearWriter::getWordsUsed() const { return m_pos;}\n\nUtilBufferWriter::UtilBufferWriter(UtilBuffer & b)\n : m_buf(b)\n{\n reset();\n}\n\nbool UtilBufferWriter::reset() { m_buf.clear(); return true;}\n\nbool \nUtilBufferWriter::putWord(Uint32 val){\n return (m_buf.append(&val, 4) == 0);\n}\n\nbool \nUtilBufferWriter::putWords(const Uint32 * src, Uint32 len){\n return (m_buf.append(src, 4 * len) == 0);\n}\n\n\nUint32\nUtilBufferWriter::getWordsUsed() const { return m_buf.length() \/ 4;}\n\n#if 0\nLinearPagesReader::LinearPagesReader(const Uint32 * base, \n\t\t\t\t Uint32 pageSize, \n\t\t\t\t Uint32 headerSize,\n\t\t\t\t Uint32 noOfPages, \n\t\t\t\t Uint32 len){\n m_base = base;\n m_pageSz = pageSize;\n m_noOfPages = noOfPages;\n m_pageHeaderSz = headerSize;\n m_len = len;\n reset();\n}\n\nvoid \nLinearPagesReader::reset() { m_pos = 0;}\n\nbool \nLinearPagesReader::step(Uint32 len){\n m_pos += len;\n return m_pos < m_len;\n}\n\nbool \nLinearPagesReader::getWord(Uint32 * dst) { \n if(m_pos<m_len){\n * dst = m_base[getPos(m_pos++)];\n return true;\n } \n return false;\n}\n\nbool \nLinearPagesReader::peekWord(Uint32 * dst) const {\n if(m_pos<m_len){\n * dst = m_base[getPos(m_pos)];\n return true;\n } \n return false;\n}\n\nbool \nLinearPagesReader::peekWords(Uint32 * dst, Uint32 len) const {\n if(m_pos + len <= m_len){\n for(Uint32 i = 0; i<len; i++)\n * (dst + i) = m_base[getPos(m_pos + i)];\n return true;\n }\n return false;\n}\n\nUint32 \nLinearPagesReader::getPos(Uint32 pos) const {\n const Uint32 sz = (m_pageSz - m_pageHeaderSz);\n Uint32 no = pos \/ sz;\n Uint32 in = pos % sz;\n return no * m_pageSz + m_pageHeaderSz + in;\n}\n\nLinearPagesWriter::LinearPagesWriter(Uint32 * base, \n\t\t\t\t Uint32 pageSize, \n\t\t\t\t Uint32 noOfPages, \n\t\t\t\t Uint32 headerSize){\n m_base = base;\n m_pageSz = pageSize;\n m_noOfPages = noOfPages;\n m_pageHeaderSz = headerSize;\n m_len = noOfPages * (pageSize - headerSize);\n reset();\n}\n\nbool \nLinearPagesWriter::putWord(Uint32 val){\n if(m_pos < m_len){\n m_base[getPos(m_pos++)] = val;\n return true;\n }\n return false;\n}\n\nbool \nLinearPagesWriter::putWords(const Uint32 * src, Uint32 len){\n if(m_pos + len <= m_len){\n for(Uint32 i = 0; i<len; i++)\n m_base[getPos(m_pos++)] = src[i];\n return true;\n }\n return false;\n}\n\n#if 0\nUint32 \nLinearPagesWriter::getWordsUsed() const { \n return getPos(m_pos);\n}\n#endif\n\nUint32 \nLinearPagesWriter::getPagesUsed() const { \n return m_pos \/ (m_pageSz - m_pageHeaderSz);\n}\n\nUint32 \nLinearPagesWriter::getPos(Uint32 pos) const {\n const Uint32 sz = (m_pageSz - m_pageHeaderSz);\n Uint32 no = pos \/ sz;\n Uint32 in = pos % sz;\n return no * m_pageSz + m_pageHeaderSz + in;\n}\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/* -------------------------------------------------------------------------- *\/\n\/* Copyright 2002-2013, OpenNebula Project (OpenNebula.org), C12G Labs *\/\n\/* *\/\n\/* Licensed under the Apache License, Version 2.0 (the \"License\"); you may *\/\n\/* not use this file except in compliance with the License. You may obtain *\/\n\/* a copy of the License at *\/\n\/* *\/\n\/* http:\/\/www.apache.org\/licenses\/LICENSE-2.0 *\/\n\/* *\/\n\/* Unless required by applicable law or agreed to in writing, software *\/\n\/* distributed under the License is distributed on an \"AS IS\" BASIS, *\/\n\/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. *\/\n\/* See the License for the specific language governing permissions and *\/\n\/* limitations under the License. *\/\n\/* -------------------------------------------------------------------------- *\/\n\n#include \"PoolObjectSQL.h\"\n#include \"PoolObjectAuth.h\"\n#include \"SSLTools.h\"\n#include \"Nebula.h\"\n#include \"Clusterable.h\"\n\n\/* -------------------------------------------------------------------------- *\/\n\/* -------------------------------------------------------------------------- *\/\n\nstring& PoolObjectSQL::to_xml64(string &xml64)\n{\n string *str64;\n\n to_xml(xml64);\n\n str64 = SSLTools::base64_encode(xml64);\n\n xml64 = *str64;\n\n delete str64;\n\n return xml64;\n}\n\n\/* -------------------------------------------------------------------------- *\/\n\/* -------------------------------------------------------------------------- *\/\n\nint PoolObjectSQL::select(SqlDB *db)\n{\n ostringstream oss;\n int rc;\n int boid;\n\n set_callback(\n static_cast<Callbackable::Callback>(&PoolObjectSQL::select_cb));\n\n oss << \"SELECT body FROM \" << table << \" WHERE oid = \" << oid;\n\n boid = oid;\n oid = -1;\n\n rc = db->exec(oss, this);\n\n unset_callback();\n\n if ((rc != 0) || (oid != boid ))\n {\n return -1;\n }\n\n return 0;\n}\n\n\/* -------------------------------------------------------------------------- *\/\n\/* -------------------------------------------------------------------------- *\/\n\nint PoolObjectSQL::select(SqlDB *db, const string& _name, int _uid)\n{\n ostringstream oss;\n\n int rc;\n char * sql_name;\n\n sql_name = db->escape_str(_name.c_str());\n\n if ( sql_name == 0 )\n {\n return -1;\n }\n\n set_callback(\n static_cast<Callbackable::Callback>(&PoolObjectSQL::select_cb));\n\n oss << \"SELECT body FROM \" << table << \" WHERE name = '\" << sql_name << \"'\";\n\n if ( _uid != -1 )\n {\n oss << \" AND uid = \" << _uid;\n }\n\n name = \"\";\n uid = -1;\n\n rc = db->exec(oss, this);\n\n unset_callback();\n\n db->free_str(sql_name);\n\n if ((rc != 0) || (_name != name) || (_uid != -1 && _uid != uid))\n {\n return -1;\n }\n\n return 0;\n}\n\n\/* -------------------------------------------------------------------------- *\/\n\/* -------------------------------------------------------------------------- *\/\n\nint PoolObjectSQL::drop(SqlDB *db)\n{\n ostringstream oss;\n int rc;\n\n oss << \"DELETE FROM \" << table << \" WHERE oid=\" << oid;\n\n rc = db->exec(oss);\n\n if ( rc == 0 )\n {\n set_valid(false);\n }\n\n return rc;\n}\n\n\/* -------------------------------------------------------------------------- *\/\n\/* -------------------------------------------------------------------------- *\/\n\nconst char * PoolObjectSQL::error_attribute_name = \"ERROR\";\n\nvoid PoolObjectSQL::set_template_error_message(const string& message)\n{\n VectorAttribute * attr;\n map<string,string> error_value;\n\n char str[26];\n time_t the_time;\n\n the_time = time(NULL);\n\n#ifdef SOLARIS\n ctime_r(&(the_time),str,sizeof(char)*26);\n#else\n ctime_r(&(the_time),str);\n#endif\n\n str[24] = '\\0'; \/\/ Get rid of final enter character\n\n error_value.insert(make_pair(\"TIMESTAMP\",str));\n error_value.insert(make_pair(\"MESSAGE\",message));\n\n \/\/Replace previous error message and insert the new one\n\n attr = new VectorAttribute(error_attribute_name,error_value);\n\n obj_template->erase(error_attribute_name);\n obj_template->set(attr);\n}\n\n\/* -------------------------------------------------------------------------- *\/\n\/* -------------------------------------------------------------------------- *\/\n\nint PoolObjectSQL::replace_template(const string& tmpl_str, string& error)\n{\n Template * new_tmpl = get_new_template();\n\n if ( new_tmpl == 0 )\n {\n error = \"Cannot allocate a new template\";\n return -1;\n }\n\n if ( new_tmpl->parse_str_or_xml(tmpl_str, error) != 0 )\n {\n delete new_tmpl;\n return -1;\n }\n\n if ( obj_template != 0 )\n {\n delete obj_template;\n }\n\n obj_template = new_tmpl;\n\n return 0;\n}\n\n\/* -------------------------------------------------------------------------- *\/\n\/* -------------------------------------------------------------------------- *\/\n\nstring& PoolObjectSQL::perms_to_xml(string& xml) const\n{\n ostringstream oss;\n\n oss <<\n \"<PERMISSIONS>\" <<\n \"<OWNER_U>\" << owner_u << \"<\/OWNER_U>\" <<\n \"<OWNER_M>\" << owner_m << \"<\/OWNER_M>\" <<\n \"<OWNER_A>\" << owner_a << \"<\/OWNER_A>\" <<\n \"<GROUP_U>\" << group_u << \"<\/GROUP_U>\" <<\n \"<GROUP_M>\" << group_m << \"<\/GROUP_M>\" <<\n \"<GROUP_A>\" << group_a << \"<\/GROUP_A>\" <<\n \"<OTHER_U>\" << other_u << \"<\/OTHER_U>\" <<\n \"<OTHER_M>\" << other_m << \"<\/OTHER_M>\" <<\n \"<OTHER_A>\" << other_a << \"<\/OTHER_A>\" <<\n \"<\/PERMISSIONS>\";\n\n xml = oss.str();\n return xml;\n}\n\n\/* -------------------------------------------------------------------------- *\/\n\/* -------------------------------------------------------------------------- *\/\n\nint PoolObjectSQL::perms_from_xml()\n{\n int rc = 0;\n\n rc += xpath(owner_u, \"\/*\/PERMISSIONS\/OWNER_U\", 0);\n rc += xpath(owner_m, \"\/*\/PERMISSIONS\/OWNER_M\", 0);\n rc += xpath(owner_a, \"\/*\/PERMISSIONS\/OWNER_A\", 0);\n\n rc += xpath(group_u, \"\/*\/PERMISSIONS\/GROUP_U\", 0);\n rc += xpath(group_m, \"\/*\/PERMISSIONS\/GROUP_M\", 0);\n rc += xpath(group_a, \"\/*\/PERMISSIONS\/GROUP_A\", 0);\n\n rc += xpath(other_u, \"\/*\/PERMISSIONS\/OTHER_U\", 0);\n rc += xpath(other_m, \"\/*\/PERMISSIONS\/OTHER_M\", 0);\n rc += xpath(other_a, \"\/*\/PERMISSIONS\/OTHER_A\", 0);\n\n return rc;\n}\n\n\/* -------------------------------------------------------------------------- *\/\n\/* -------------------------------------------------------------------------- *\/\n\nvoid PoolObjectSQL::get_permissions(PoolObjectAuth& auth)\n{\n auth.obj_type = obj_type;\n\n auth.oid = oid;\n auth.uid = uid;\n auth.gid = gid;\n\n auth.owner_u = owner_u;\n auth.owner_m = owner_m;\n auth.owner_a = owner_a;\n\n auth.group_u = group_u;\n auth.group_m = group_m;\n auth.group_a = group_a;\n\n auth.other_u = other_u;\n auth.other_m = other_m;\n auth.other_a = other_a;\n\n Clusterable* cl = dynamic_cast<Clusterable*>(this);\n\n if(cl != 0)\n {\n auth.cid = cl->get_cluster_id();\n }\n}\n\n\/* -------------------------------------------------------------------------- *\/\n\/* -------------------------------------------------------------------------- *\/\n\nint PoolObjectSQL::set_permissions( int _owner_u,\n int _owner_m,\n int _owner_a,\n int _group_u,\n int _group_m,\n int _group_a,\n int _other_u,\n int _other_m,\n int _other_a,\n string& error_str)\n{\n if ( _owner_u < -1 || _owner_u > 1 ) goto error_value;\n if ( _owner_m < -1 || _owner_m > 1 ) goto error_value;\n if ( _owner_a < -1 || _owner_a > 1 ) goto error_value;\n if ( _group_u < -1 || _group_u > 1 ) goto error_value;\n if ( _group_m < -1 || _group_m > 1 ) goto error_value;\n if ( _group_a < -1 || _group_a > 1 ) goto error_value;\n if ( _other_u < -1 || _other_u > 1 ) goto error_value;\n if ( _other_m < -1 || _other_m > 1 ) goto error_value;\n if ( _other_a < -1 || _other_a > 1 ) goto error_value;\n\n set_perm(owner_u, _owner_u);\n set_perm(owner_m, _owner_m);\n set_perm(owner_a, _owner_a);\n set_perm(group_u, _group_u);\n set_perm(group_m, _group_m);\n set_perm(group_a, _group_a);\n set_perm(other_u, _other_u);\n set_perm(other_m, _other_m);\n set_perm(other_a, _other_a);\n\n return 0;\n\nerror_value:\n error_str = \"New permission values must be -1, 0 or 1\";\n return -1;\n}\n\n\/* -------------------------------------------------------------------------- *\/\n\/* -------------------------------------------------------------------------- *\/\n\nvoid PoolObjectSQL::set_umask(int umask)\n{\n int perms;\n bool enable_other;\n\n Nebula::instance().get_configuration_attribute(\n \"ENABLE_OTHER_PERMISSIONS\", enable_other);\n\n if (uid == 0 || gid == 0)\n {\n perms = 0777;\n }\n else if (enable_other)\n {\n perms = 0666;\n }\n else\n {\n perms = 0660;\n }\n\n perms = perms & ~umask;\n\n owner_u = ( (perms & 0400) != 0 ) ? 1 : 0;\n owner_m = ( (perms & 0200) != 0 ) ? 1 : 0;\n owner_a = ( (perms & 0100) != 0 ) ? 1 : 0;\n group_u = ( (perms & 0040) != 0 ) ? 1 : 0;\n group_m = ( (perms & 0020) != 0 ) ? 1 : 0;\n group_a = ( (perms & 0010) != 0 ) ? 1 : 0;\n other_u = ( (perms & 0004) != 0 ) ? 1 : 0;\n other_m = ( (perms & 0002) != 0 ) ? 1 : 0;\n other_a = ( (perms & 0001) != 0 ) ? 1 : 0;\n\n}\n\n\/* -------------------------------------------------------------------------- *\/\n\/* -------------------------------------------------------------------------- *\/\n<commit_msg>feature #1664: Error messages as single attribute in templates<commit_after>\/* -------------------------------------------------------------------------- *\/\n\/* Copyright 2002-2013, OpenNebula Project (OpenNebula.org), C12G Labs *\/\n\/* *\/\n\/* Licensed under the Apache License, Version 2.0 (the \"License\"); you may *\/\n\/* not use this file except in compliance with the License. You may obtain *\/\n\/* a copy of the License at *\/\n\/* *\/\n\/* http:\/\/www.apache.org\/licenses\/LICENSE-2.0 *\/\n\/* *\/\n\/* Unless required by applicable law or agreed to in writing, software *\/\n\/* distributed under the License is distributed on an \"AS IS\" BASIS, *\/\n\/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. *\/\n\/* See the License for the specific language governing permissions and *\/\n\/* limitations under the License. *\/\n\/* -------------------------------------------------------------------------- *\/\n\n#include \"PoolObjectSQL.h\"\n#include \"PoolObjectAuth.h\"\n#include \"SSLTools.h\"\n#include \"Nebula.h\"\n#include \"Clusterable.h\"\n\n\/* -------------------------------------------------------------------------- *\/\n\/* -------------------------------------------------------------------------- *\/\n\nstring& PoolObjectSQL::to_xml64(string &xml64)\n{\n string *str64;\n\n to_xml(xml64);\n\n str64 = SSLTools::base64_encode(xml64);\n\n xml64 = *str64;\n\n delete str64;\n\n return xml64;\n}\n\n\/* -------------------------------------------------------------------------- *\/\n\/* -------------------------------------------------------------------------- *\/\n\nint PoolObjectSQL::select(SqlDB *db)\n{\n ostringstream oss;\n int rc;\n int boid;\n\n set_callback(\n static_cast<Callbackable::Callback>(&PoolObjectSQL::select_cb));\n\n oss << \"SELECT body FROM \" << table << \" WHERE oid = \" << oid;\n\n boid = oid;\n oid = -1;\n\n rc = db->exec(oss, this);\n\n unset_callback();\n\n if ((rc != 0) || (oid != boid ))\n {\n return -1;\n }\n\n return 0;\n}\n\n\/* -------------------------------------------------------------------------- *\/\n\/* -------------------------------------------------------------------------- *\/\n\nint PoolObjectSQL::select(SqlDB *db, const string& _name, int _uid)\n{\n ostringstream oss;\n\n int rc;\n char * sql_name;\n\n sql_name = db->escape_str(_name.c_str());\n\n if ( sql_name == 0 )\n {\n return -1;\n }\n\n set_callback(\n static_cast<Callbackable::Callback>(&PoolObjectSQL::select_cb));\n\n oss << \"SELECT body FROM \" << table << \" WHERE name = '\" << sql_name << \"'\";\n\n if ( _uid != -1 )\n {\n oss << \" AND uid = \" << _uid;\n }\n\n name = \"\";\n uid = -1;\n\n rc = db->exec(oss, this);\n\n unset_callback();\n\n db->free_str(sql_name);\n\n if ((rc != 0) || (_name != name) || (_uid != -1 && _uid != uid))\n {\n return -1;\n }\n\n return 0;\n}\n\n\/* -------------------------------------------------------------------------- *\/\n\/* -------------------------------------------------------------------------- *\/\n\nint PoolObjectSQL::drop(SqlDB *db)\n{\n ostringstream oss;\n int rc;\n\n oss << \"DELETE FROM \" << table << \" WHERE oid=\" << oid;\n\n rc = db->exec(oss);\n\n if ( rc == 0 )\n {\n set_valid(false);\n }\n\n return rc;\n}\n\n\/* -------------------------------------------------------------------------- *\/\n\/* -------------------------------------------------------------------------- *\/\n\nconst char * PoolObjectSQL::error_attribute_name = \"ERROR\";\n\nvoid PoolObjectSQL::set_template_error_message(const string& message)\n{\n SingleAttribute * attr;\n ostringstream error_value;\n\n char str[26];\n time_t the_time;\n\n the_time = time(NULL);\n\n#ifdef SOLARIS\n ctime_r(&(the_time),str,sizeof(char)*26);\n#else\n ctime_r(&(the_time),str);\n#endif\n\n str[24] = '\\0'; \/\/ Get rid of final enter character\n\n error_value << str << \" : \" << message;\n\n \/\/Replace previous error message and insert the new one\n\n attr = new SingleAttribute(error_attribute_name, error_value.str());\n\n obj_template->erase(error_attribute_name);\n obj_template->set(attr);\n}\n\n\/* -------------------------------------------------------------------------- *\/\n\/* -------------------------------------------------------------------------- *\/\n\nint PoolObjectSQL::replace_template(const string& tmpl_str, string& error)\n{\n Template * new_tmpl = get_new_template();\n\n if ( new_tmpl == 0 )\n {\n error = \"Cannot allocate a new template\";\n return -1;\n }\n\n if ( new_tmpl->parse_str_or_xml(tmpl_str, error) != 0 )\n {\n delete new_tmpl;\n return -1;\n }\n\n if ( obj_template != 0 )\n {\n delete obj_template;\n }\n\n obj_template = new_tmpl;\n\n return 0;\n}\n\n\/* -------------------------------------------------------------------------- *\/\n\/* -------------------------------------------------------------------------- *\/\n\nstring& PoolObjectSQL::perms_to_xml(string& xml) const\n{\n ostringstream oss;\n\n oss <<\n \"<PERMISSIONS>\" <<\n \"<OWNER_U>\" << owner_u << \"<\/OWNER_U>\" <<\n \"<OWNER_M>\" << owner_m << \"<\/OWNER_M>\" <<\n \"<OWNER_A>\" << owner_a << \"<\/OWNER_A>\" <<\n \"<GROUP_U>\" << group_u << \"<\/GROUP_U>\" <<\n \"<GROUP_M>\" << group_m << \"<\/GROUP_M>\" <<\n \"<GROUP_A>\" << group_a << \"<\/GROUP_A>\" <<\n \"<OTHER_U>\" << other_u << \"<\/OTHER_U>\" <<\n \"<OTHER_M>\" << other_m << \"<\/OTHER_M>\" <<\n \"<OTHER_A>\" << other_a << \"<\/OTHER_A>\" <<\n \"<\/PERMISSIONS>\";\n\n xml = oss.str();\n return xml;\n}\n\n\/* -------------------------------------------------------------------------- *\/\n\/* -------------------------------------------------------------------------- *\/\n\nint PoolObjectSQL::perms_from_xml()\n{\n int rc = 0;\n\n rc += xpath(owner_u, \"\/*\/PERMISSIONS\/OWNER_U\", 0);\n rc += xpath(owner_m, \"\/*\/PERMISSIONS\/OWNER_M\", 0);\n rc += xpath(owner_a, \"\/*\/PERMISSIONS\/OWNER_A\", 0);\n\n rc += xpath(group_u, \"\/*\/PERMISSIONS\/GROUP_U\", 0);\n rc += xpath(group_m, \"\/*\/PERMISSIONS\/GROUP_M\", 0);\n rc += xpath(group_a, \"\/*\/PERMISSIONS\/GROUP_A\", 0);\n\n rc += xpath(other_u, \"\/*\/PERMISSIONS\/OTHER_U\", 0);\n rc += xpath(other_m, \"\/*\/PERMISSIONS\/OTHER_M\", 0);\n rc += xpath(other_a, \"\/*\/PERMISSIONS\/OTHER_A\", 0);\n\n return rc;\n}\n\n\/* -------------------------------------------------------------------------- *\/\n\/* -------------------------------------------------------------------------- *\/\n\nvoid PoolObjectSQL::get_permissions(PoolObjectAuth& auth)\n{\n auth.obj_type = obj_type;\n\n auth.oid = oid;\n auth.uid = uid;\n auth.gid = gid;\n\n auth.owner_u = owner_u;\n auth.owner_m = owner_m;\n auth.owner_a = owner_a;\n\n auth.group_u = group_u;\n auth.group_m = group_m;\n auth.group_a = group_a;\n\n auth.other_u = other_u;\n auth.other_m = other_m;\n auth.other_a = other_a;\n\n Clusterable* cl = dynamic_cast<Clusterable*>(this);\n\n if(cl != 0)\n {\n auth.cid = cl->get_cluster_id();\n }\n}\n\n\/* -------------------------------------------------------------------------- *\/\n\/* -------------------------------------------------------------------------- *\/\n\nint PoolObjectSQL::set_permissions( int _owner_u,\n int _owner_m,\n int _owner_a,\n int _group_u,\n int _group_m,\n int _group_a,\n int _other_u,\n int _other_m,\n int _other_a,\n string& error_str)\n{\n if ( _owner_u < -1 || _owner_u > 1 ) goto error_value;\n if ( _owner_m < -1 || _owner_m > 1 ) goto error_value;\n if ( _owner_a < -1 || _owner_a > 1 ) goto error_value;\n if ( _group_u < -1 || _group_u > 1 ) goto error_value;\n if ( _group_m < -1 || _group_m > 1 ) goto error_value;\n if ( _group_a < -1 || _group_a > 1 ) goto error_value;\n if ( _other_u < -1 || _other_u > 1 ) goto error_value;\n if ( _other_m < -1 || _other_m > 1 ) goto error_value;\n if ( _other_a < -1 || _other_a > 1 ) goto error_value;\n\n set_perm(owner_u, _owner_u);\n set_perm(owner_m, _owner_m);\n set_perm(owner_a, _owner_a);\n set_perm(group_u, _group_u);\n set_perm(group_m, _group_m);\n set_perm(group_a, _group_a);\n set_perm(other_u, _other_u);\n set_perm(other_m, _other_m);\n set_perm(other_a, _other_a);\n\n return 0;\n\nerror_value:\n error_str = \"New permission values must be -1, 0 or 1\";\n return -1;\n}\n\n\/* -------------------------------------------------------------------------- *\/\n\/* -------------------------------------------------------------------------- *\/\n\nvoid PoolObjectSQL::set_umask(int umask)\n{\n int perms;\n bool enable_other;\n\n Nebula::instance().get_configuration_attribute(\n \"ENABLE_OTHER_PERMISSIONS\", enable_other);\n\n if (uid == 0 || gid == 0)\n {\n perms = 0777;\n }\n else if (enable_other)\n {\n perms = 0666;\n }\n else\n {\n perms = 0660;\n }\n\n perms = perms & ~umask;\n\n owner_u = ( (perms & 0400) != 0 ) ? 1 : 0;\n owner_m = ( (perms & 0200) != 0 ) ? 1 : 0;\n owner_a = ( (perms & 0100) != 0 ) ? 1 : 0;\n group_u = ( (perms & 0040) != 0 ) ? 1 : 0;\n group_m = ( (perms & 0020) != 0 ) ? 1 : 0;\n group_a = ( (perms & 0010) != 0 ) ? 1 : 0;\n other_u = ( (perms & 0004) != 0 ) ? 1 : 0;\n other_m = ( (perms & 0002) != 0 ) ? 1 : 0;\n other_a = ( (perms & 0001) != 0 ) ? 1 : 0;\n\n}\n\n\/* -------------------------------------------------------------------------- *\/\n\/* -------------------------------------------------------------------------- *\/\n<|endoftext|>"} {"text":"<commit_before>\/** @file\n *\n * @ingroup dspFunctionLib\n *\n * @brief #TTFreeHandFunction Unit for Jamoms DSP\n *\n * @details A piecewise function unit that allows to load a function unit per defined domain. @n\n * The default configuration is a linear function for X[0::1], Y[0::1] domain. @n\n * Setup the curveList attribute to change the configuration. @n\n * For example setting curveList to the < 0.3 0.6 exponential base 0.5 1. 1. logarithm base 0.8 > value @n\n * you will imply the following behavior :\n * - if x belongs to [0::0.3] domain, it will use the exponential function and the result will belong to [0.::0.6] domain.\n * - if x belongs to ]0.3::1.] domain, it will use the logarithm function and the result will belong to ]0.6::1.] domain.\n *\n * @authors Théo de la Hogue, Trond Lossius\n *\n * @copyright Copyright © 2013 by Théo de la Hogue @n\n * This code is licensed under the terms of the \"New BSD License\" @n\n * http:\/\/creativecommons.org\/licenses\/BSD\/\n *\/\n\n\n#include \"TTFreeHandFunction.h\"\n#include <math.h>\n\n#define thisTTClass\t\t\tTTFreeHandFunction\n#define thisTTClassName\t\t\"freehand\"\n#define thisTTClassTags\t\t\"dspFunctionLib, audio, processor, function\"\n\n\nTT_AUDIO_CONSTRUCTOR\n{\n registerAttribute(TTSymbol(\"curveList\"), kTypeLocalValue, NULL, (TTGetterMethod)&TTFreeHandFunction::getCurveList, (TTSetterMethod)&TTFreeHandFunction::setCurveList);\n \n\tsetProcessMethod(processAudio);\n\tsetCalculateMethod(calculateValue);\n \n Clear();\n}\n\nTTFreeHandFunction::~TTFreeHandFunction()\n{\n\t;\n}\n\nTTErr TTFreeHandFunction::getCurveList(TTValue& value)\n{\n TTObject aFunction;\n TTValue v, attributeNames;\n TTSymbol aName;\n TTUInt8 i;\n TTBoolean firstFunction = YES;\n \n mFunctions.begin();\n \n \/\/ for each point\n for (mPoints.begin(); mPoints.end(); mPoints.next()) {\n \n \/\/ append the point coordinate\n value.append(mPoints.current());\n \n \/\/ the first function is always an exponential base 1. function\n if (firstFunction) {\n \n value.append(TTSymbol(\"exponential\"));\n value.append(TTSymbol(\"base\"));\n value.append(1.);\n \n firstFunction = NO;\n continue;\n }\n \n \/\/ append function info\n if (mFunctions.end()) {\n \n aFunction = mFunctions.current()[0];\n \n if (aFunction.valid()) {\n \n \/\/ append function name\n value.append(aFunction.name());\n \n \/\/ for all attributes\n aFunction.attributes(attributeNames);\n \n for (i = 0; i < attributeNames.size(); i++) {\n \n aName = attributeNames[i];\n if (aName == kTTSym_bypass || aName == TTSymbol(\"mute\") || aName == kTTSym_maxNumChannels || aName == kTTSym_sampleRate)\n continue;\t\t\t\t\t\t\t\t\t\t\/\/ don't publish these datas\n \n \/\/ append attribute name and value\n aFunction.get(aName, v);\n value.append(attributeNames[i]);\n value.append(v);\n }\n }\n \n mFunctions.next();\n }\n }\n \n return kTTErrNone;\n}\n\nTTErr TTFreeHandFunction::setCurveList(const TTValue& value)\n{\n TTUInt8 curveId;\n TTUInt32 i, next, size;\n TTFloat64 x, y;\n TTSymbol function, parameterName;\n TTObject aFunction;\n TTValue v;\n TTErr err = kTTErrNone;\n \n locked = YES;\n \n \/\/ clear all existing points\n mPoints.clear();\n \n \/\/ clear all existing functions\n mFunctions.clear();\n\n \/\/ set all points and curves\n size = value.size();\n curveId = 0;\n for (i = 0; i < size; i = i + next) {\n \n \/\/ check size\n if (i+1 >= size)\n err = kTTErrGeneric;\n \n \/\/ append a point : x y\n if (value[i].type() == kTypeFloat64 && value[i+1].type() == kTypeFloat64) {\n \n x = value[i];\n y = value[i+1];\n \n v = TTValue(x);\n v.append(y);\n mPoints.append(v);\n \n next = 2;\n }\n else\n err = kTTErrGeneric;\n \n \/\/ create a function\n aFunction = NULL;\n \n \/\/ check size\n if (i+2 >= size) {\n aFunction = TTObject(\"linear\", 1); \/\/ 1 is the numChannel\n \n \/\/ set function type\n } else if (value[i+2].type() == kTypeSymbol) {\n \n function = value[i+2];\n aFunction = TTObject(function, 1); \/\/ 1 is the numChannel\n \n next = 3;\n \n \/\/ check size\n if (i+5 > size)\n ;\n \n \/\/ set function parameter\n else if (value[i+3].type() == kTypeSymbol) {\n \n parameterName = value[i+3];\n \n v.copyRange(value, i+4, i+5);\n aFunction.set(parameterName, v);\n \n next = 5;\n }\n else\n err = kTTErrGeneric;\n }\n else\n aFunction = TTObject(\"linear\", 1); \/\/ 1 is the numChannel\n \n \/\/ for the first point : release the function\n if (!curveId)\n aFunction = TTObject();\n \n \/\/ append the function\n else\n mFunctions.append(aFunction);\n \n curveId++;\n }\n \n locked = NO;\n \n return err;\n}\n\nTTErr TTFreeHandFunction::Clear()\n{\n TTValue init;\n \n init.append(0.);\n init.append(0.);\n \n init.append(1.);\n init.append(1.);\n \n return setCurveList(init);\n}\n\nTTErr TTFreeHandFunction::calculateValue(const TTFloat64& x, TTFloat64& y, TTPtrSizedInt data)\n{\n TTFloat64 lastX, lastY;\n TTFloat64 currentX, currentY;\n TTFloat64 scaledX, scaledY;\n TTObject aFunction;\n TTErr err;\n \n if (locked)\n return kTTErrGeneric;\n \n if (mPoints.isEmpty())\n return kTTErrNone;\n \n mPoints.begin();\n lastX = mPoints.current()[0];\n lastY = mPoints.current()[1];\n \n if (x < lastX) {\n y = lastY;\n return kTTErrNone;\n }\n \n mPoints.next();\n \n \/\/ select the function to use\n for (mFunctions.begin(); mFunctions.end(); mFunctions.next()) {\n \n currentX = mPoints.current()[0];\n currentY = mPoints.current()[1];\n \n if (x < currentX) {\n \n aFunction = mFunctions.current()[0];\n \n \/\/ scale x\n scaledX = (x - lastX) \/ (currentX - lastX);\n \n \/\/ use function\n err = TTAudioObjectBasePtr(aFunction.instance())->calculate(scaledX, scaledY);\n \n \/\/ scale y\n y = (currentY - lastY) * scaledY + lastY;\n\n return err;\n }\n \n lastX = currentX;\n lastY = currentY;\n mPoints.next();\n }\n \n y = lastY;\n\n\treturn kTTErrNone;\n}\n\n\nTTErr TTFreeHandFunction::processAudio(TTAudioSignalArrayPtr inputs, TTAudioSignalArrayPtr outputs)\n{\n\tTT_WRAP_CALCULATE_METHOD(calculateValue);\n}\n\n<commit_msg>Cleaning get curve list accessor<commit_after>\/** @file\n *\n * @ingroup dspFunctionLib\n *\n * @brief #TTFreeHandFunction Unit for Jamoms DSP\n *\n * @details A piecewise function unit that allows to load a function unit per defined domain. @n\n * The default configuration is a linear function for X[0::1], Y[0::1] domain. @n\n * Setup the curveList attribute to change the configuration. @n\n * For example setting curveList to the < 0.3 0.6 exponential base 0.5 1. 1. logarithm base 0.8 > value @n\n * you will imply the following behavior :\n * - if x belongs to [0::0.3] domain, it will use the exponential function and the result will belong to [0.::0.6] domain.\n * - if x belongs to ]0.3::1.] domain, it will use the logarithm function and the result will belong to ]0.6::1.] domain.\n *\n * @authors Théo de la Hogue, Trond Lossius\n *\n * @copyright Copyright © 2013 by Théo de la Hogue @n\n * This code is licensed under the terms of the \"New BSD License\" @n\n * http:\/\/creativecommons.org\/licenses\/BSD\/\n *\/\n\n\n#include \"TTFreeHandFunction.h\"\n#include <math.h>\n\n#define thisTTClass\t\t\tTTFreeHandFunction\n#define thisTTClassName\t\t\"freehand\"\n#define thisTTClassTags\t\t\"dspFunctionLib, audio, processor, function\"\n\n\nTT_AUDIO_CONSTRUCTOR\n{\n registerAttribute(TTSymbol(\"curveList\"), kTypeLocalValue, NULL, (TTGetterMethod)&TTFreeHandFunction::getCurveList, (TTSetterMethod)&TTFreeHandFunction::setCurveList);\n \n\tsetProcessMethod(processAudio);\n\tsetCalculateMethod(calculateValue);\n \n Clear();\n}\n\nTTFreeHandFunction::~TTFreeHandFunction()\n{\n\t;\n}\n\nTTErr TTFreeHandFunction::getCurveList(TTValue& value)\n{\n TTBoolean firstFunction = YES;\n \n mFunctions.begin();\n \n \/\/ for each point\n for (mPoints.begin(); mPoints.end(); mPoints.next()) {\n \n \/\/ append the point coordinate\n value.append(mPoints.current());\n \n \/\/ the first function is always an exponential base 1. function\n if (firstFunction) {\n \n value.append(TTSymbol(\"exponential\"));\n value.append(TTSymbol(\"base\"));\n value.append(1.);\n \n firstFunction = NO;\n continue;\n }\n \n \/\/ append function info\n if (mFunctions.end()) {\n \n TTObject aFunction = mFunctions.current()[0];\n \n if (aFunction.valid()) {\n \n TTValue attributeNames;\n TTUInt8 i;\n \n \/\/ append function name\n value.append(aFunction.name());\n\n \/\/ for all attributes\n aFunction.attributes(attributeNames);\n \n for (i = 0; i < attributeNames.size(); i++) {\n \n TTSymbol aName = attributeNames[i];\n \n if (aName == kTTSym_bypass || aName == TTSymbol(\"mute\") || aName == kTTSym_maxNumChannels || aName == kTTSym_sampleRate)\n continue;\t\t\t\t\t\t\t\t\t\t\/\/ don't publish these datas\n\n \/\/ append attribute name\n value.append(aName);\n \n \/\/ append attribute value\n TTValue v;\n aFunction.get(aName, v);\n value.append(v);\n }\n }\n \n mFunctions.next();\n }\n }\n\n return kTTErrNone;\n}\n\nTTErr TTFreeHandFunction::setCurveList(const TTValue& value)\n{\n TTUInt8 curveId;\n TTUInt32 i, next, size;\n TTFloat64 x, y;\n TTSymbol function, parameterName;\n TTObject aFunction;\n TTValue v;\n TTErr err = kTTErrNone;\n \n locked = YES;\n \n \/\/ clear all existing points\n mPoints.clear();\n \n \/\/ clear all existing functions\n mFunctions.clear();\n\n \/\/ set all points and curves\n size = value.size();\n curveId = 0;\n for (i = 0; i < size; i = i + next) {\n \n \/\/ check size\n if (i+1 >= size)\n err = kTTErrGeneric;\n \n \/\/ append a point : x y\n if (value[i].type() == kTypeFloat64 && value[i+1].type() == kTypeFloat64) {\n \n x = value[i];\n y = value[i+1];\n \n v = TTValue(x);\n v.append(y);\n mPoints.append(v);\n \n next = 2;\n }\n else\n err = kTTErrGeneric;\n \n \/\/ create a function\n aFunction = NULL;\n \n \/\/ check size\n if (i+2 >= size) {\n aFunction = TTObject(\"linear\", 1); \/\/ 1 is the numChannel\n \n \/\/ set function type\n } else if (value[i+2].type() == kTypeSymbol) {\n \n function = value[i+2];\n aFunction = TTObject(function, 1); \/\/ 1 is the numChannel\n \n next = 3;\n \n \/\/ check size\n if (i+5 > size)\n ;\n \n \/\/ set function parameter\n else if (value[i+3].type() == kTypeSymbol) {\n \n parameterName = value[i+3];\n \n v.copyRange(value, i+4, i+5);\n aFunction.set(parameterName, v);\n \n next = 5;\n }\n else\n err = kTTErrGeneric;\n }\n else\n aFunction = TTObject(\"linear\", 1); \/\/ 1 is the numChannel\n \n \/\/ for the first point : release the function\n if (!curveId)\n aFunction = TTObject();\n \n \/\/ append the function\n else\n mFunctions.append(aFunction);\n \n curveId++;\n }\n \n locked = NO;\n\n return err;\n}\n\nTTErr TTFreeHandFunction::Clear()\n{\n TTValue init;\n \n init.append(0.);\n init.append(0.);\n \n init.append(1.);\n init.append(1.);\n \n return setCurveList(init);\n}\n\nTTErr TTFreeHandFunction::calculateValue(const TTFloat64& x, TTFloat64& y, TTPtrSizedInt data)\n{\n TTFloat64 lastX, lastY;\n TTFloat64 currentX, currentY;\n TTFloat64 scaledX, scaledY;\n TTObject aFunction;\n TTErr err;\n \n if (locked)\n return kTTErrGeneric;\n \n if (mPoints.isEmpty())\n return kTTErrNone;\n \n mPoints.begin();\n lastX = mPoints.current()[0];\n lastY = mPoints.current()[1];\n \n if (x < lastX) {\n y = lastY;\n return kTTErrNone;\n }\n \n mPoints.next();\n \n \/\/ select the function to use\n for (mFunctions.begin(); mFunctions.end(); mFunctions.next()) {\n \n currentX = mPoints.current()[0];\n currentY = mPoints.current()[1];\n \n if (x < currentX) {\n \n aFunction = mFunctions.current()[0];\n \n \/\/ scale x\n scaledX = (x - lastX) \/ (currentX - lastX);\n \n \/\/ use function\n err = TTAudioObjectBasePtr(aFunction.instance())->calculate(scaledX, scaledY);\n \n \/\/ scale y\n y = (currentY - lastY) * scaledY + lastY;\n\n return err;\n }\n \n lastX = currentX;\n lastY = currentY;\n mPoints.next();\n }\n \n y = lastY;\n\n\treturn kTTErrNone;\n}\n\n\nTTErr TTFreeHandFunction::processAudio(TTAudioSignalArrayPtr inputs, TTAudioSignalArrayPtr outputs)\n{\n\tTT_WRAP_CALCULATE_METHOD(calculateValue);\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"net\/socket\/tcp_server_socket.h\"\n\n#include <string>\n#include <vector>\n\n#include \"base\/compiler_specific.h\"\n#include \"base\/memory\/ref_counted.h\"\n#include \"base\/memory\/scoped_ptr.h\"\n#include \"net\/base\/address_list.h\"\n#include \"net\/base\/io_buffer.h\"\n#include \"net\/base\/ip_endpoint.h\"\n#include \"net\/base\/net_errors.h\"\n#include \"net\/base\/test_completion_callback.h\"\n#include \"net\/socket\/tcp_client_socket.h\"\n#include \"testing\/gtest\/include\/gtest\/gtest.h\"\n#include \"testing\/platform_test.h\"\n\nnamespace net {\n\nnamespace {\nconst int kListenBacklog = 5;\n\nclass TCPServerSocketTest : public PlatformTest {\n protected:\n TCPServerSocketTest()\n : socket_(NULL, NetLog::Source()) {\n }\n\n void SetUpIPv4() {\n IPEndPoint address;\n ParseAddress(\"127.0.0.1\", 0, &address);\n ASSERT_EQ(OK, socket_.Listen(address, kListenBacklog));\n ASSERT_EQ(OK, socket_.GetLocalAddress(&local_address_));\n }\n\n void SetUpIPv6(bool* success) {\n *success = false;\n IPEndPoint address;\n ParseAddress(\"::1\", 0, &address);\n if (socket_.Listen(address, kListenBacklog) != 0) {\n LOG(ERROR) << \"Failed to listen on ::1 - probably because IPv6 is \"\n \"disabled. Skipping the test\";\n return;\n }\n ASSERT_EQ(OK, socket_.GetLocalAddress(&local_address_));\n *success = true;\n }\n\n void ParseAddress(std::string ip_str, int port, IPEndPoint* address) {\n IPAddressNumber ip_number;\n bool rv = ParseIPLiteralToNumber(ip_str, &ip_number);\n if (!rv)\n return;\n *address = IPEndPoint(ip_number, port);\n }\n\n static IPEndPoint GetPeerAddress(StreamSocket* socket) {\n IPEndPoint address;\n EXPECT_EQ(OK, socket->GetPeerAddress(&address));\n return address;\n }\n\n AddressList local_address_list() const {\n return AddressList(local_address_);\n }\n\n TCPServerSocket socket_;\n IPEndPoint local_address_;\n};\n\nTEST_F(TCPServerSocketTest, Accept) {\n ASSERT_NO_FATAL_FAILURE(SetUpIPv4());\n\n TestCompletionCallback connect_callback;\n TCPClientSocket connecting_socket(local_address_list(),\n NULL, NetLog::Source());\n connecting_socket.Connect(connect_callback.callback());\n\n TestCompletionCallback accept_callback;\n scoped_ptr<StreamSocket> accepted_socket;\n int result = socket_.Accept(&accepted_socket, accept_callback.callback());\n if (result == ERR_IO_PENDING)\n result = accept_callback.WaitForResult();\n ASSERT_EQ(OK, result);\n\n ASSERT_TRUE(accepted_socket.get() != NULL);\n\n \/\/ Both sockets should be on the loopback network interface.\n EXPECT_EQ(GetPeerAddress(accepted_socket.get()).address(),\n local_address_.address());\n\n EXPECT_EQ(OK, connect_callback.WaitForResult());\n}\n\n\/\/ Test Accept() callback.\nTEST_F(TCPServerSocketTest, AcceptAsync) {\n ASSERT_NO_FATAL_FAILURE(SetUpIPv4());\n\n TestCompletionCallback accept_callback;\n scoped_ptr<StreamSocket> accepted_socket;\n\n ASSERT_EQ(ERR_IO_PENDING,\n socket_.Accept(&accepted_socket, accept_callback.callback()));\n\n TestCompletionCallback connect_callback;\n TCPClientSocket connecting_socket(local_address_list(),\n NULL, NetLog::Source());\n connecting_socket.Connect(connect_callback.callback());\n\n EXPECT_EQ(OK, connect_callback.WaitForResult());\n EXPECT_EQ(OK, accept_callback.WaitForResult());\n\n EXPECT_TRUE(accepted_socket != NULL);\n\n \/\/ Both sockets should be on the loopback network interface.\n EXPECT_EQ(GetPeerAddress(accepted_socket.get()).address(),\n local_address_.address());\n}\n\n\/\/ Accept two connections simultaneously.\nTEST_F(TCPServerSocketTest, Accept2Connections) {\n ASSERT_NO_FATAL_FAILURE(SetUpIPv4());\n\n TestCompletionCallback accept_callback;\n scoped_ptr<StreamSocket> accepted_socket;\n\n ASSERT_EQ(ERR_IO_PENDING,\n socket_.Accept(&accepted_socket, accept_callback.callback()));\n\n TestCompletionCallback connect_callback;\n TCPClientSocket connecting_socket(local_address_list(),\n NULL, NetLog::Source());\n connecting_socket.Connect(connect_callback.callback());\n\n TestCompletionCallback connect_callback2;\n TCPClientSocket connecting_socket2(local_address_list(),\n NULL, NetLog::Source());\n connecting_socket2.Connect(connect_callback2.callback());\n\n EXPECT_EQ(OK, accept_callback.WaitForResult());\n\n TestCompletionCallback accept_callback2;\n scoped_ptr<StreamSocket> accepted_socket2;\n int result = socket_.Accept(&accepted_socket2, accept_callback2.callback());\n if (result == ERR_IO_PENDING)\n result = accept_callback2.WaitForResult();\n ASSERT_EQ(OK, result);\n\n EXPECT_EQ(OK, connect_callback.WaitForResult());\n\n EXPECT_TRUE(accepted_socket != NULL);\n EXPECT_TRUE(accepted_socket2 != NULL);\n EXPECT_NE(accepted_socket.get(), accepted_socket2.get());\n\n EXPECT_EQ(GetPeerAddress(accepted_socket.get()).address(),\n local_address_.address());\n EXPECT_EQ(GetPeerAddress(accepted_socket2.get()).address(),\n local_address_.address());\n}\n\nTEST_F(TCPServerSocketTest, AcceptIPv6) {\n bool initialized = false;\n ASSERT_NO_FATAL_FAILURE(SetUpIPv6(&initialized));\n if (!initialized)\n return;\n\n TestCompletionCallback connect_callback;\n TCPClientSocket connecting_socket(local_address_list(),\n NULL, NetLog::Source());\n connecting_socket.Connect(connect_callback.callback());\n\n TestCompletionCallback accept_callback;\n scoped_ptr<StreamSocket> accepted_socket;\n int result = socket_.Accept(&accepted_socket, accept_callback.callback());\n if (result == ERR_IO_PENDING)\n result = accept_callback.WaitForResult();\n ASSERT_EQ(OK, result);\n\n ASSERT_TRUE(accepted_socket.get() != NULL);\n\n \/\/ Both sockets should be on the loopback network interface.\n EXPECT_EQ(GetPeerAddress(accepted_socket.get()).address(),\n local_address_.address());\n\n EXPECT_EQ(OK, connect_callback.WaitForResult());\n}\n\nTEST_F(TCPServerSocketTest, AcceptIO) {\n ASSERT_NO_FATAL_FAILURE(SetUpIPv4());\n\n TestCompletionCallback connect_callback;\n TCPClientSocket connecting_socket(local_address_list(),\n NULL, NetLog::Source());\n connecting_socket.Connect(connect_callback.callback());\n\n TestCompletionCallback accept_callback;\n scoped_ptr<StreamSocket> accepted_socket;\n int result = socket_.Accept(&accepted_socket, accept_callback.callback());\n ASSERT_EQ(OK, accept_callback.GetResult(result));\n\n ASSERT_TRUE(accepted_socket.get() != NULL);\n\n \/\/ Both sockets should be on the loopback network interface.\n EXPECT_EQ(GetPeerAddress(accepted_socket.get()).address(),\n local_address_.address());\n\n EXPECT_EQ(OK, connect_callback.WaitForResult());\n\n const std::string message(\"test message\");\n std::vector<char> buffer(message.size());\n\n size_t bytes_written = 0;\n while (bytes_written < message.size()) {\n scoped_refptr<net::IOBufferWithSize> write_buffer(\n new net::IOBufferWithSize(message.size() - bytes_written));\n memmove(write_buffer->data(), message.data(), message.size());\n\n TestCompletionCallback write_callback;\n int write_result = accepted_socket->Write(\n write_buffer.get(), write_buffer->size(), write_callback.callback());\n write_result = write_callback.GetResult(write_result);\n ASSERT_TRUE(write_result >= 0);\n ASSERT_TRUE(bytes_written + write_result <= message.size());\n bytes_written += write_result;\n }\n\n size_t bytes_read = 0;\n while (bytes_read < message.size()) {\n scoped_refptr<net::IOBufferWithSize> read_buffer(\n new net::IOBufferWithSize(message.size() - bytes_read));\n TestCompletionCallback read_callback;\n int read_result = connecting_socket.Read(\n read_buffer.get(), read_buffer->size(), read_callback.callback());\n read_result = read_callback.GetResult(read_result);\n ASSERT_TRUE(read_result >= 0);\n ASSERT_TRUE(bytes_read + read_result <= message.size());\n memmove(&buffer[bytes_read], read_buffer->data(), read_result);\n bytes_read += read_result;\n }\n\n std::string received_message(buffer.begin(), buffer.end());\n ASSERT_EQ(message, received_message);\n}\n\n} \/\/ namespace\n\n} \/\/ namespace net\n<commit_msg>After removing allowReuseAddress and always setting SO_REUSEADDR, we need a test to ensure that the ports are not reused on *nix systems.<commit_after>\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"net\/socket\/tcp_server_socket.h\"\n\n#include <string>\n#include <vector>\n\n#include \"base\/compiler_specific.h\"\n#include \"base\/memory\/ref_counted.h\"\n#include \"base\/memory\/scoped_ptr.h\"\n#include \"net\/base\/address_list.h\"\n#include \"net\/base\/io_buffer.h\"\n#include \"net\/base\/ip_endpoint.h\"\n#include \"net\/base\/net_errors.h\"\n#include \"net\/base\/test_completion_callback.h\"\n#include \"net\/socket\/tcp_client_socket.h\"\n#include \"testing\/gtest\/include\/gtest\/gtest.h\"\n#include \"testing\/platform_test.h\"\n\nnamespace net {\n\nnamespace {\nconst int kListenBacklog = 5;\n\nclass TCPServerSocketTest : public PlatformTest {\n protected:\n TCPServerSocketTest()\n : socket_(NULL, NetLog::Source()) {\n }\n\n void SetUpIPv4() {\n IPEndPoint address;\n ParseAddress(\"127.0.0.1\", 0, &address);\n ASSERT_EQ(OK, socket_.Listen(address, kListenBacklog));\n ASSERT_EQ(OK, socket_.GetLocalAddress(&local_address_));\n }\n\n void SetUpIPv6(bool* success) {\n *success = false;\n IPEndPoint address;\n ParseAddress(\"::1\", 0, &address);\n if (socket_.Listen(address, kListenBacklog) != 0) {\n LOG(ERROR) << \"Failed to listen on ::1 - probably because IPv6 is \"\n \"disabled. Skipping the test\";\n return;\n }\n ASSERT_EQ(OK, socket_.GetLocalAddress(&local_address_));\n *success = true;\n }\n\n void ParseAddress(std::string ip_str, int port, IPEndPoint* address) {\n IPAddressNumber ip_number;\n bool rv = ParseIPLiteralToNumber(ip_str, &ip_number);\n if (!rv)\n return;\n *address = IPEndPoint(ip_number, port);\n }\n\n static IPEndPoint GetPeerAddress(StreamSocket* socket) {\n IPEndPoint address;\n EXPECT_EQ(OK, socket->GetPeerAddress(&address));\n return address;\n }\n\n AddressList local_address_list() const {\n return AddressList(local_address_);\n }\n\n TCPServerSocket socket_;\n IPEndPoint local_address_;\n};\n\nTEST_F(TCPServerSocketTest, Accept) {\n ASSERT_NO_FATAL_FAILURE(SetUpIPv4());\n\n TestCompletionCallback connect_callback;\n TCPClientSocket connecting_socket(local_address_list(),\n NULL, NetLog::Source());\n connecting_socket.Connect(connect_callback.callback());\n\n TestCompletionCallback accept_callback;\n scoped_ptr<StreamSocket> accepted_socket;\n int result = socket_.Accept(&accepted_socket, accept_callback.callback());\n if (result == ERR_IO_PENDING)\n result = accept_callback.WaitForResult();\n ASSERT_EQ(OK, result);\n\n ASSERT_TRUE(accepted_socket.get() != NULL);\n\n \/\/ Both sockets should be on the loopback network interface.\n EXPECT_EQ(GetPeerAddress(accepted_socket.get()).address(),\n local_address_.address());\n\n EXPECT_EQ(OK, connect_callback.WaitForResult());\n}\n\n\/\/ Test Accept() callback.\nTEST_F(TCPServerSocketTest, AcceptAsync) {\n ASSERT_NO_FATAL_FAILURE(SetUpIPv4());\n\n TestCompletionCallback accept_callback;\n scoped_ptr<StreamSocket> accepted_socket;\n\n ASSERT_EQ(ERR_IO_PENDING,\n socket_.Accept(&accepted_socket, accept_callback.callback()));\n\n TestCompletionCallback connect_callback;\n TCPClientSocket connecting_socket(local_address_list(),\n NULL, NetLog::Source());\n connecting_socket.Connect(connect_callback.callback());\n\n EXPECT_EQ(OK, connect_callback.WaitForResult());\n EXPECT_EQ(OK, accept_callback.WaitForResult());\n\n EXPECT_TRUE(accepted_socket != NULL);\n\n \/\/ Both sockets should be on the loopback network interface.\n EXPECT_EQ(GetPeerAddress(accepted_socket.get()).address(),\n local_address_.address());\n}\n\n\/\/ Accept two connections simultaneously.\nTEST_F(TCPServerSocketTest, Accept2Connections) {\n ASSERT_NO_FATAL_FAILURE(SetUpIPv4());\n\n TestCompletionCallback accept_callback;\n scoped_ptr<StreamSocket> accepted_socket;\n\n ASSERT_EQ(ERR_IO_PENDING,\n socket_.Accept(&accepted_socket, accept_callback.callback()));\n\n TestCompletionCallback connect_callback;\n TCPClientSocket connecting_socket(local_address_list(),\n NULL, NetLog::Source());\n connecting_socket.Connect(connect_callback.callback());\n\n TestCompletionCallback connect_callback2;\n TCPClientSocket connecting_socket2(local_address_list(),\n NULL, NetLog::Source());\n connecting_socket2.Connect(connect_callback2.callback());\n\n EXPECT_EQ(OK, accept_callback.WaitForResult());\n\n TestCompletionCallback accept_callback2;\n scoped_ptr<StreamSocket> accepted_socket2;\n int result = socket_.Accept(&accepted_socket2, accept_callback2.callback());\n if (result == ERR_IO_PENDING)\n result = accept_callback2.WaitForResult();\n ASSERT_EQ(OK, result);\n\n EXPECT_EQ(OK, connect_callback.WaitForResult());\n\n EXPECT_TRUE(accepted_socket != NULL);\n EXPECT_TRUE(accepted_socket2 != NULL);\n EXPECT_NE(accepted_socket.get(), accepted_socket2.get());\n\n EXPECT_EQ(GetPeerAddress(accepted_socket.get()).address(),\n local_address_.address());\n EXPECT_EQ(GetPeerAddress(accepted_socket2.get()).address(),\n local_address_.address());\n}\n\nTEST_F(TCPServerSocketTest, AcceptIPv6) {\n bool initialized = false;\n ASSERT_NO_FATAL_FAILURE(SetUpIPv6(&initialized));\n if (!initialized)\n return;\n\n TestCompletionCallback connect_callback;\n TCPClientSocket connecting_socket(local_address_list(),\n NULL, NetLog::Source());\n connecting_socket.Connect(connect_callback.callback());\n\n TestCompletionCallback accept_callback;\n scoped_ptr<StreamSocket> accepted_socket;\n int result = socket_.Accept(&accepted_socket, accept_callback.callback());\n if (result == ERR_IO_PENDING)\n result = accept_callback.WaitForResult();\n ASSERT_EQ(OK, result);\n\n ASSERT_TRUE(accepted_socket.get() != NULL);\n\n \/\/ Both sockets should be on the loopback network interface.\n EXPECT_EQ(GetPeerAddress(accepted_socket.get()).address(),\n local_address_.address());\n\n EXPECT_EQ(OK, connect_callback.WaitForResult());\n}\n\nTEST_F(TCPServerSocketTest, AcceptIO) {\n ASSERT_NO_FATAL_FAILURE(SetUpIPv4());\n\n TestCompletionCallback connect_callback;\n TCPClientSocket connecting_socket(local_address_list(),\n NULL, NetLog::Source());\n connecting_socket.Connect(connect_callback.callback());\n\n TestCompletionCallback accept_callback;\n scoped_ptr<StreamSocket> accepted_socket;\n int result = socket_.Accept(&accepted_socket, accept_callback.callback());\n ASSERT_EQ(OK, accept_callback.GetResult(result));\n\n ASSERT_TRUE(accepted_socket.get() != NULL);\n\n \/\/ Both sockets should be on the loopback network interface.\n EXPECT_EQ(GetPeerAddress(accepted_socket.get()).address(),\n local_address_.address());\n\n EXPECT_EQ(OK, connect_callback.WaitForResult());\n\n const std::string message(\"test message\");\n std::vector<char> buffer(message.size());\n\n size_t bytes_written = 0;\n while (bytes_written < message.size()) {\n scoped_refptr<net::IOBufferWithSize> write_buffer(\n new net::IOBufferWithSize(message.size() - bytes_written));\n memmove(write_buffer->data(), message.data(), message.size());\n\n TestCompletionCallback write_callback;\n int write_result = accepted_socket->Write(\n write_buffer.get(), write_buffer->size(), write_callback.callback());\n write_result = write_callback.GetResult(write_result);\n ASSERT_TRUE(write_result >= 0);\n ASSERT_TRUE(bytes_written + write_result <= message.size());\n bytes_written += write_result;\n }\n\n size_t bytes_read = 0;\n while (bytes_read < message.size()) {\n scoped_refptr<net::IOBufferWithSize> read_buffer(\n new net::IOBufferWithSize(message.size() - bytes_read));\n TestCompletionCallback read_callback;\n int read_result = connecting_socket.Read(\n read_buffer.get(), read_buffer->size(), read_callback.callback());\n read_result = read_callback.GetResult(read_result);\n ASSERT_TRUE(read_result >= 0);\n ASSERT_TRUE(bytes_read + read_result <= message.size());\n memmove(&buffer[bytes_read], read_buffer->data(), read_result);\n bytes_read += read_result;\n }\n\n std::string received_message(buffer.begin(), buffer.end());\n ASSERT_EQ(message, received_message);\n}\n\nTEST_F(TCPServerSocketTest, Rebind) {\n IPEndPoint address;\n \/\/ Bind to a random, unused port.\n ParseAddress(\"127.0.0.1\", 0, &address);\n\n scoped_ptr<TCPServerSocket> socket(\n new TCPServerSocket(NULL, NetLog::Source()));\n ASSERT_EQ(OK, socket->Listen(address, kListenBacklog));\n\n \/\/ Retrieve the real endpoint bound.\n ASSERT_EQ(OK, socket->GetLocalAddress(&address));\n\n scoped_ptr<TCPServerSocket> conflict_socket(\n new TCPServerSocket(NULL, NetLog::Source()));\n ASSERT_NE(OK, conflict_socket->Listen(address, kListenBacklog));\n\n \/\/ Unbind.\n socket.reset(NULL);\n\n ASSERT_EQ(OK, conflict_socket->Listen(address, kListenBacklog));\n}\n\n} \/\/ namespace\n\n} \/\/ namespace net\n<|endoftext|>"} {"text":"<commit_before>\/*\n\nCopyright (c) 2013, Project OSRM, Dennis Luxen, others\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without modification,\nare permitted provided that the following conditions are met:\n\nRedistributions of source code must retain the above copyright notice, this list\nof conditions and the following disclaimer.\nRedistributions in binary form must reproduce the above copyright notice, this\nlist of conditions and the following disclaimer in the documentation and\/or\nother materials provided with the distribution.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\nANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\nWARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR\nANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\nLOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON\nANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\nSOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#include \"..\/Util\/GitDescription.h\"\n#include \"..\/Util\/SimpleLogger.h\"\n#include \"..\/Server\/DataStructures\/SharedBarriers.h\"\n\n#include <iostream>\n\nint main() {\n LogPolicy::GetInstance().Unmute();\n SimpleLogger().Write() <<\n \"starting up engines, \" << g_GIT_DESCRIPTION << \", \" <<\n \"compiled at \" << __DATE__ << \", \" __TIME__;\n SimpleLogger().Write() << \"Releasing all locks\";\n SharedBarriers barrier;\n barrier.pending_update_mutex.unlock();\n barrier.query_mutex.unlock();\n barrier.update_mutex.unlock();\n return 0;\n}\n<commit_msg>catch exceptions that may occur, coverity issue 1198846<commit_after>\/*\n\nCopyright (c) 2013, Project OSRM, Dennis Luxen, others\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without modification,\nare permitted provided that the following conditions are met:\n\nRedistributions of source code must retain the above copyright notice, this list\nof conditions and the following disclaimer.\nRedistributions in binary form must reproduce the above copyright notice, this\nlist of conditions and the following disclaimer in the documentation and\/or\nother materials provided with the distribution.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\nANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\nWARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR\nANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\nLOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON\nANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\nSOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#include \"..\/Util\/GitDescription.h\"\n#include \"..\/Util\/SimpleLogger.h\"\n#include \"..\/Server\/DataStructures\/SharedBarriers.h\"\n\n#include <iostream>\n\nint main() {\n LogPolicy::GetInstance().Unmute();\n try\n {\n SimpleLogger().Write() <<\n \"starting up engines, \" << g_GIT_DESCRIPTION << \", \" <<\n \"compiled at \" << __DATE__ << \", \" __TIME__;\n SimpleLogger().Write() << \"Releasing all locks\";\n SharedBarriers barrier;\n barrier.pending_update_mutex.unlock();\n barrier.query_mutex.unlock();\n barrier.update_mutex.unlock();\n }\n catch(const std::exception & e)\n {\n SimpleLogger().Write(logWARNING) << \"[excpetion] \" << e.what();\n }\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (C) 2005 by Thorsten Staerk <kde@staerk.de>\n * 2007 the ktimetracker developers\n *\n * This program is free software; you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License along\n * with this program; if not, write to the\n * Free Software Foundation, Inc.\n * 51 Franklin Street, Fifth Floor\n * Boston, MA 02110-1301 USA.\n *\n *\/\n\n#include \"karm_part.h\"\n\n#include <QByteArray>\n#include <QFile>\n#include <QMenu>\n#include <QTextStream>\n#include <QtDBus>\n\n#include <KAboutData>\n#include <KAction>\n#include <KActionCollection>\n#include <KComponentData>\n#include <KFileDialog>\n#include <KGlobal>\n#include <KIcon>\n#include <KLocale>\n#include <KStandardAction>\n#include <KStandardDirs>\n#include <KXMLGUIFactory>\n\n#include <kdemacros.h>\n\n#include \"mainwindow.h\"\n#include \"kaccelmenuwatch.h\"\n#include \"karmerrors.h\"\n#include \"task.h\"\n#include \"preferences.h\"\n#include \"tray.h\"\n#include \"version.h\"\n#include \"ktimetracker.h\"\n#include \"timetrackerwidget.h\"\n\nkarmPart::karmPart( QWidget *parentWidget, QObject *parent )\n : KParts::ReadWritePart(parent)\n{\n \/\/ we need an instance\n setComponentData( karmPartFactory::componentData() );\n\n mMainWidget = new TimetrackerWidget( parentWidget );\n setWidget( mMainWidget );\n makeMenus();\n mMainWidget->openFile( KStandardDirs::locateLocal( \"appdata\", \n QString::fromLatin1( \"karm.ics\" ) ) );\n\n \/\/ connections\n connect( mMainWidget, SIGNAL( totalTimesChanged( long, long ) ),\n this, SLOT( updateTime( long, long ) ) );\n connect( mMainWidget, SIGNAL( statusBarTextChangeRequested( QString ) ),\n this, SLOT( setStatusBar( QString ) ) );\n\n \/\/ Setup context menu request handling\n connect( mMainWidget,\n SIGNAL( contextMenuRequested( const QPoint& ) ),\n this,\n SLOT( taskViewCustomContextMenuRequested( const QPoint& ) ) );\n\n if ( KTimeTrackerSettings::trayIcon() ) mTray = new TrayIcon( this );\n else mTray = new TrayIcon( );\n\n connect( mTray, SIGNAL( quitSelected() ), SLOT( quit() ) );\n\n connect( mMainWidget, SIGNAL( timersActive() ), mTray, SLOT( startClock() ) );\n connect( mMainWidget, SIGNAL( timersInactive() ), mTray, SLOT( stopClock() ) );\n connect( mMainWidget, SIGNAL( tasksChanged( const QList<Task*>& ) ),\n mTray, SLOT( updateToolTip( QList<Task*> ) ));\n}\n\nkarmPart::~karmPart()\n{\n}\n\nvoid karmPart::makeMenus()\n{\n mMainWidget->setupActions( actionCollection() );\n KAction *actionKeyBindings;\n\n actionKeyBindings = KStandardAction::keyBindings( this, SLOT( keyBindings() ),\n actionCollection() );\n\n setXMLFile( QString::fromLatin1( \"karmui.rc\" ) );\n\n \/\/ Tool tops must be set after the createGUI.\n actionKeyBindings->setToolTip( i18n(\"Configure key bindings\") );\n actionKeyBindings->setWhatsThis( i18n(\"This will let you configure key\"\n \"bindings which is specific to ktimetracer\") );\n}\n\nvoid karmPart::setStatusBar(const QString & qs)\n{\n kDebug(5970) <<\"Entering setStatusBar\";\n emit setStatusBarText(qs);\n}\n\nbool karmPart::openFile()\n{\n mMainWidget->openFile();\n\n return true;\n}\n\nbool karmPart::saveFile()\n{\n mMainWidget->saveFile();\n\n return true;\n}\n\n\/\/ It's usually safe to leave the factory code alone.. with the\n\/\/ notable exception of the KAboutData data\nKComponentData *karmPartFactory::s_instance = 0L;\nKAboutData* karmPartFactory::s_about = 0L;\n\nkarmPartFactory::karmPartFactory()\n : KParts::Factory()\n{\n}\n\nkarmPartFactory::~karmPartFactory()\n{\n delete s_instance;\n delete s_about;\n\n s_instance = 0L;\n}\n\nKParts::Part* karmPartFactory::createPartObject( QWidget *parentWidget, QObject *parent,\n const char* classname, const QStringList &args )\n{\n Q_UNUSED( args );\n\n \/\/ Create an instance of our Part\n karmPart* obj = new karmPart( parentWidget, parent );\n\n \/\/ See if we are to be read-write or not\n if ( QLatin1String( classname ) == QLatin1String( \"KParts::ReadOnlyPart\" ) )\n obj->setReadWrite(false);\n\n return obj;\n}\n\nconst KComponentData &karmPartFactory::componentData()\n{\n if( !s_instance )\n {\n s_about = new KAboutData(\"karmpart\", 0, ki18n(\"karmPart\"), \"0.1\");\n s_about->addAuthor(ki18n(\"Thorsten Staerk\"), KLocalizedString(), \"thorsten@staerk.de\");\n s_instance = new KComponentData(s_about);\n }\n return *s_instance;\n}\n\nextern \"C\"\n{\n KDE_EXPORT void* init_libkarmpart()\n {\n\tKGlobal::locale()->insertCatalog(\"karm\");\n return new karmPartFactory;\n }\n}\n\nvoid karmPart::taskViewCustomContextMenuRequested( const QPoint& point )\n{\n QMenu* pop = dynamic_cast<QMenu*>(\n factory()->container( i18n( \"task_popup\" ), this ) );\n if ( pop )\n pop->popup( point );\n}\n\n#include \"karm_part.moc\"\n<commit_msg>* Type<commit_after>\/*\n * Copyright (C) 2005 by Thorsten Staerk <kde@staerk.de>\n * 2007 the ktimetracker developers\n *\n * This program is free software; you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License along\n * with this program; if not, write to the\n * Free Software Foundation, Inc.\n * 51 Franklin Street, Fifth Floor\n * Boston, MA 02110-1301 USA.\n *\n *\/\n\n#include \"karm_part.h\"\n\n#include <QByteArray>\n#include <QFile>\n#include <QMenu>\n#include <QTextStream>\n#include <QtDBus>\n\n#include <KAboutData>\n#include <KAction>\n#include <KActionCollection>\n#include <KComponentData>\n#include <KFileDialog>\n#include <KGlobal>\n#include <KIcon>\n#include <KLocale>\n#include <KStandardAction>\n#include <KStandardDirs>\n#include <KXMLGUIFactory>\n\n#include <kdemacros.h>\n\n#include \"mainwindow.h\"\n#include \"kaccelmenuwatch.h\"\n#include \"karmerrors.h\"\n#include \"task.h\"\n#include \"preferences.h\"\n#include \"tray.h\"\n#include \"version.h\"\n#include \"ktimetracker.h\"\n#include \"timetrackerwidget.h\"\n\nkarmPart::karmPart( QWidget *parentWidget, QObject *parent )\n : KParts::ReadWritePart(parent)\n{\n \/\/ we need an instance\n setComponentData( karmPartFactory::componentData() );\n\n mMainWidget = new TimetrackerWidget( parentWidget );\n setWidget( mMainWidget );\n makeMenus();\n mMainWidget->openFile( KStandardDirs::locateLocal( \"appdata\", \n QString::fromLatin1( \"karm.ics\" ) ) );\n\n \/\/ connections\n connect( mMainWidget, SIGNAL( totalTimesChanged( long, long ) ),\n this, SLOT( updateTime( long, long ) ) );\n connect( mMainWidget, SIGNAL( statusBarTextChangeRequested( QString ) ),\n this, SLOT( setStatusBar( QString ) ) );\n\n \/\/ Setup context menu request handling\n connect( mMainWidget,\n SIGNAL( contextMenuRequested( const QPoint& ) ),\n this,\n SLOT( taskViewCustomContextMenuRequested( const QPoint& ) ) );\n\n if ( KTimeTrackerSettings::trayIcon() ) mTray = new TrayIcon( this );\n else mTray = new TrayIcon( );\n\n connect( mTray, SIGNAL( quitSelected() ), SLOT( quit() ) );\n\n connect( mMainWidget, SIGNAL( timersActive() ), mTray, SLOT( startClock() ) );\n connect( mMainWidget, SIGNAL( timersInactive() ), mTray, SLOT( stopClock() ) );\n connect( mMainWidget, SIGNAL( tasksChanged( const QList<Task*>& ) ),\n mTray, SLOT( updateToolTip( QList<Task*> ) ));\n}\n\nkarmPart::~karmPart()\n{\n}\n\nvoid karmPart::makeMenus()\n{\n mMainWidget->setupActions( actionCollection() );\n KAction *actionKeyBindings;\n\n actionKeyBindings = KStandardAction::keyBindings( this, SLOT( keyBindings() ),\n actionCollection() );\n\n setXMLFile( QString::fromLatin1( \"karmui.rc\" ) );\n\n \/\/ Tool tops must be set after the createGUI.\n actionKeyBindings->setToolTip( i18n(\"Configure key bindings\") );\n actionKeyBindings->setWhatsThis( i18n(\"This will let you configure key\"\n \"bindings which is specific to ktimetracker\") );\n}\n\nvoid karmPart::setStatusBar(const QString & qs)\n{\n kDebug(5970) <<\"Entering setStatusBar\";\n emit setStatusBarText(qs);\n}\n\nbool karmPart::openFile()\n{\n mMainWidget->openFile();\n\n return true;\n}\n\nbool karmPart::saveFile()\n{\n mMainWidget->saveFile();\n\n return true;\n}\n\n\/\/ It's usually safe to leave the factory code alone.. with the\n\/\/ notable exception of the KAboutData data\nKComponentData *karmPartFactory::s_instance = 0L;\nKAboutData* karmPartFactory::s_about = 0L;\n\nkarmPartFactory::karmPartFactory()\n : KParts::Factory()\n{\n}\n\nkarmPartFactory::~karmPartFactory()\n{\n delete s_instance;\n delete s_about;\n\n s_instance = 0L;\n}\n\nKParts::Part* karmPartFactory::createPartObject( QWidget *parentWidget, QObject *parent,\n const char* classname, const QStringList &args )\n{\n Q_UNUSED( args );\n\n \/\/ Create an instance of our Part\n karmPart* obj = new karmPart( parentWidget, parent );\n\n \/\/ See if we are to be read-write or not\n if ( QLatin1String( classname ) == QLatin1String( \"KParts::ReadOnlyPart\" ) )\n obj->setReadWrite(false);\n\n return obj;\n}\n\nconst KComponentData &karmPartFactory::componentData()\n{\n if( !s_instance )\n {\n s_about = new KAboutData(\"karmpart\", 0, ki18n(\"karmPart\"), \"0.1\");\n s_about->addAuthor(ki18n(\"Thorsten Staerk\"), KLocalizedString(), \"thorsten@staerk.de\");\n s_instance = new KComponentData(s_about);\n }\n return *s_instance;\n}\n\nextern \"C\"\n{\n KDE_EXPORT void* init_libkarmpart()\n {\n\tKGlobal::locale()->insertCatalog(\"karm\");\n return new karmPartFactory;\n }\n}\n\nvoid karmPart::taskViewCustomContextMenuRequested( const QPoint& point )\n{\n QMenu* pop = dynamic_cast<QMenu*>(\n factory()->container( i18n( \"task_popup\" ), this ) );\n if ( pop )\n pop->popup( point );\n}\n\n#include \"karm_part.moc\"\n<|endoftext|>"} {"text":"<commit_before>\/*\n *\n * synchronization_tests\n * ledger-core\n *\n * Created by Khalil Bellakrid on 15\/05\/2018.\n *\n * The MIT License (MIT)\n *\n * Copyright (c) 2018 Ledger\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n *\n *\/\n\n#include <gtest\/gtest.h>\n#include \"..\/BaseFixture.h\"\n#include <set>\n#include <api\/KeychainEngines.hpp>\n#include <utils\/DateUtils.hpp>\n#include <wallet\/bitcoin\/database\/BitcoinLikeAccountDatabaseHelper.h>\n#include <wallet\/bitcoin\/api_impl\/BitcoinLikeTransactionApi.h>\n\nclass BitcoinLikeWalletP2SHSynchronization : public BaseFixture {\n\n};\n\nTEST_F(BitcoinLikeWalletP2SHSynchronization, MediumXpubSynchronization) {\n auto pool = newDefaultPool();\n {\n auto configuration = DynamicObject::newInstance();\n configuration->putString(api::Configuration::KEYCHAIN_ENGINE,api::KeychainEngines::BIP49_P2SH);\n configuration->putString(api::Configuration::KEYCHAIN_DERIVATION_SCHEME,\"49'\/<coin_type>'\/<account>'\/<node>\/<address>\");\n\n auto wallet = uv::wait(pool->createWallet(\"e847815f-488a-4301-b67c-378a5e9c8a61\", \"bitcoin_testnet\", configuration));\n {\n auto nextIndex = uv::wait(wallet->getNextAccountIndex());\n EXPECT_EQ(nextIndex, 0);\n\n auto account = createBitcoinLikeAccount(wallet, nextIndex, P2SH_XPUB_INFO);\n\n auto receiver = make_receiver([=](const std::shared_ptr<api::Event> &event) {\n fmt::print(\"Received event {}\\n\", api::to_string(event->getCode()));\n if (event->getCode() == api::EventCode::SYNCHRONIZATION_STARTED)\n return;\n EXPECT_NE(event->getCode(), api::EventCode::SYNCHRONIZATION_FAILED);\n EXPECT_EQ(event->getCode(),\n api::EventCode::SYNCHRONIZATION_SUCCEED_ON_PREVIOUSLY_EMPTY_ACCOUNT);\n dispatcher->stop();\n });\n\n auto bus = account->synchronize();\n bus->subscribe(getTestExecutionContext(),receiver);\n\n dispatcher->waitUntilStopped();\n\n auto block = uv::wait(account->getLastBlock());\n auto blockHash = block.blockHash;\n }\n }\n}\n\nTEST_F(BitcoinLikeWalletP2SHSynchronization, SynchronizeOnceAtATime) {\n auto pool = newDefaultPool();\n {\n auto configuration = DynamicObject::newInstance();\n configuration->putString(api::Configuration::KEYCHAIN_ENGINE,api::KeychainEngines::BIP49_P2SH);\n configuration->putString(api::Configuration::KEYCHAIN_DERIVATION_SCHEME,\"49'\/<coin_type>'\/<account>'\/<node>\/<address>\");\n\n auto wallet = uv::wait(pool->createWallet(\"e847815f-488a-4301-b67c-378a5e9c8a62\", \"bitcoin_testnet\",configuration));\n {\n auto nextIndex = uv::wait(wallet->getNextAccountIndex());\n EXPECT_EQ(nextIndex, 0);\n auto account = createBitcoinLikeAccount(wallet, nextIndex, P2SH_XPUB_INFO);\n auto eventBus = pool->getEventBus();\n eventBus->subscribe(getTestExecutionContext(),\n make_receiver([](const std::shared_ptr<api::Event> &event) {\n fmt::print(\"Received event {}\\n\", api::to_string(event->getCode()));\n }));\n auto bus = account->synchronize();\n bus->subscribe(getTestExecutionContext(),\n make_receiver([=](const std::shared_ptr<api::Event> &event) {\n fmt::print(\"Received event {}\\n\", api::to_string(event->getCode()));\n if (event->getCode() == api::EventCode::SYNCHRONIZATION_STARTED)\n return;\n EXPECT_NE(event->getCode(), api::EventCode::SYNCHRONIZATION_FAILED);\n EXPECT_EQ(event->getCode(),\n api::EventCode::SYNCHRONIZATION_SUCCEED_ON_PREVIOUSLY_EMPTY_ACCOUNT);\n dispatcher->stop();\n }));\n EXPECT_EQ(bus, account->synchronize());\n dispatcher->waitUntilStopped();\n }\n }\n}\n\nTEST_F(BitcoinLikeWalletP2SHSynchronization, SynchronizeFromLastBlock) {\n auto pool = newDefaultPool();\n {\n auto configuration = DynamicObject::newInstance();\n configuration->putString(api::Configuration::KEYCHAIN_ENGINE,api::KeychainEngines::BIP49_P2SH);\n configuration->putString(api::Configuration::KEYCHAIN_DERIVATION_SCHEME,\"49'\/<coin_type>'\/<account>'\/<node>\/<address>\");\n\n auto wallet = uv::wait(pool->createWallet(\"e847815f-488a-4301-b67c-378a5e9c8a63\", \"bitcoin_testnet\",configuration));\n createBitcoinLikeAccount(wallet, 0, P2SH_XPUB_INFO);\n auto synchronize = [wallet, pool, this] (bool expectNewOp) {\n auto account = uv::wait(wallet->getAccount(0));\n auto numberOfOp = 0;\n\n auto receiverNumberOp = make_receiver([&numberOfOp](const std::shared_ptr<api::Event> &event) {\n numberOfOp += 1;\n });\n\n auto eventBus = pool->getEventBus();\n eventBus->subscribe(getTestExecutionContext(),receiverNumberOp);\n auto bus = account->synchronize();\n\n auto receiver = make_receiver([=, &numberOfOp](const std::shared_ptr<api::Event> &event) {\n fmt::print(\"Received event {}\\n\", api::to_string(event->getCode()));\n if (event->getCode() == api::EventCode::SYNCHRONIZATION_STARTED)\n return;\n\n EXPECT_NE(event->getCode(), api::EventCode::SYNCHRONIZATION_FAILED);\n EXPECT_EQ(expectNewOp, (numberOfOp > 0));\n dispatcher->stop();\n });\n\n bus->subscribe(getTestExecutionContext(),receiver);\n auto newBus = account->synchronize();\n EXPECT_EQ(bus, newBus);\n dispatcher->waitUntilStopped();\n return bus;\n };\n\n auto b1 = synchronize(true);\n auto b2 = synchronize(false);\n EXPECT_NE(b1, b2);\n }\n}\n\nTEST_F(BitcoinLikeWalletP2SHSynchronization, EraseDataSinceAfterSynchronization) {\n auto pool = newDefaultPool();\n const auto walletName = randomWalletName();\n {\n \/\/Set configuration\n auto configuration = DynamicObject::newInstance();\n configuration->putString(api::Configuration::KEYCHAIN_ENGINE, api::KeychainEngines::BIP49_P2SH);\n configuration->putString(api::Configuration::KEYCHAIN_DERIVATION_SCHEME,\n \"49'\/<coin_type>'\/<account>'\/<node>\/<address>\");\n \/\/Create wallet\n auto wallet = uv::wait(pool->createWallet(walletName, \"bitcoin_testnet\", configuration));\n \/\/Create account\n auto account = createBitcoinLikeAccount(wallet, 0, P2SH_XPUB_INFO);\n \/\/Sync account\n auto bus = account->synchronize();\n auto receiver = make_receiver([=](const std::shared_ptr<api::Event> &event) {\n fmt::print(\"Received event {}\\n\", api::to_string(event->getCode()));\n if (event->getCode() == api::EventCode::SYNCHRONIZATION_STARTED)\n return;\n\n EXPECT_NE(event->getCode(), api::EventCode::SYNCHRONIZATION_FAILED);\n dispatcher->stop();\n });\n bus->subscribe(getTestExecutionContext(),receiver);\n dispatcher->waitUntilStopped();\n\n auto accountCount = uv::wait(wallet->getAccountCount());\n EXPECT_EQ(accountCount, 1);\n auto accountFromWallet = uv::wait(wallet->getAccount(0));\n EXPECT_EQ(account, accountFromWallet);\n\n auto date = \"2000-03-27T09:10:22Z\";\n auto formatedDate = DateUtils::fromJSON(date);\n\n \/\/Delete account\n auto code = uv::wait(wallet->eraseDataSince(formatedDate));\n EXPECT_EQ(code, api::ErrorCode::FUTURE_WAS_SUCCESSFULL);\n\n \/\/Check if account was successfully deleted\n auto newAccountCount = uv::wait(wallet->getAccountCount());\n EXPECT_EQ(newAccountCount, 0);\n {\n soci::session sql(pool->getDatabaseSessionPool()->getPool());\n BitcoinLikeAccountDatabaseEntry entry;\n auto result = BitcoinLikeAccountDatabaseHelper::queryAccount(sql, account->getAccountUid(), entry);\n EXPECT_EQ(result, false);\n }\n\n \/\/Delete wallet\n auto walletCode = uv::wait(pool->eraseDataSince(formatedDate));\n EXPECT_EQ(walletCode, api::ErrorCode::FUTURE_WAS_SUCCESSFULL);\n\n \/\/Check if wallet was successfully deleted\n auto walletCount = uv::wait(pool->getWalletCount());\n EXPECT_EQ(walletCount, 0);\n }\n}\nTEST_F(BitcoinLikeWalletP2SHSynchronization, TestNetSynchronization) {\n auto pool = newDefaultPool();\n {\n auto configuration = DynamicObject::newInstance();\n configuration->putString(api::Configuration::KEYCHAIN_ENGINE,api::KeychainEngines::BIP49_P2SH);\n configuration->putString(api::Configuration::KEYCHAIN_DERIVATION_SCHEME,\"49'\/<coin_type>'\/<account>'\/<node>\/<address>\");\n auto wallet = uv::wait(pool->createWallet(\"testnet_wallet\", \"bitcoin_testnet\",configuration));\n {\n auto nextIndex = uv::wait(wallet->getNextAccountIndex());\n auto info = uv::wait(wallet->getNextExtendedKeyAccountCreationInfo());\n info.extendedKeys.push_back(\"tpubDCcvqEHx7prGddpWTfEviiew5YLMrrKy4oJbt14teJZenSi6AYMAs2SNXwYXFzkrNYwECSmobwxESxMCrpfqw4gsUt88bcr8iMrJmbb8P2q\");\n EXPECT_EQ(nextIndex, 0);\n auto account = createBitcoinLikeAccount(wallet, nextIndex, info);\n auto receiver = make_receiver([=](const std::shared_ptr<api::Event> &event) {\n fmt::print(\"Received event {}\\n\", api::to_string(event->getCode()));\n if (event->getCode() == api::EventCode::SYNCHRONIZATION_STARTED)\n return;\n EXPECT_NE(event->getCode(), api::EventCode::SYNCHRONIZATION_FAILED);\n dispatcher->stop();\n });\n\n auto bus = account->synchronize();\n bus->subscribe(getTestExecutionContext(),receiver);\n dispatcher->waitUntilStopped();\n }\n }\n}\n\nTEST_F(BitcoinLikeWalletP2SHSynchronization, DecredParsingAndSerialization) {\n auto pool = newDefaultPool();\n {\n auto wallet = uv::wait(pool->createWallet(\"testnet_wallet\", \"decred\",DynamicObject::newInstance()));\n auto strTx = \"01000000016b9b4d4cdd2cf78907e62cddf31911ae4d4af1d89228ae4afc4459edee6a60c40100000000ffffff000240420f000000000000001976a9141d19445f397f6f0d3e2e6d741f61ba66b53886cf88acf0d31d000000000000001976a91415101bac61dca29add75996a0836a469dc8eee0788ac00000000ffffffff01000000000000000000000000ffffffff6a47304402200466bbc2aa8a742e85c3b68911502e73cdcb620ceaaa7a3cd199dbb4f8e9b969022063afeedd37d05e44b655a9de92eb36124acc045baf7b9e2941f81e41af91f1150121030ac79bab351084fdc82b4fa46eaa6a9cd2b5eb97ee93e367422bf47219b54a14\";\n auto tx = BitcoinLikeTransactionApi::parseRawSignedTransaction(wallet->getCurrency(), hex::toByteArray(strTx), 0);\n EXPECT_EQ(hex::toString(tx->serialize()), strTx);\n }\n}\n<commit_msg>Update and disable BitcoinLikeWalletP2SHSynchronization.SynchronizeFromLastBlock<commit_after>\/*\n *\n * synchronization_tests\n * ledger-core\n *\n * Created by Khalil Bellakrid on 15\/05\/2018.\n *\n * The MIT License (MIT)\n *\n * Copyright (c) 2018 Ledger\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n *\n *\/\n\n#include <gtest\/gtest.h>\n#include \"..\/BaseFixture.h\"\n#include <set>\n#include <api\/KeychainEngines.hpp>\n#include <utils\/DateUtils.hpp>\n#include <wallet\/bitcoin\/database\/BitcoinLikeAccountDatabaseHelper.h>\n#include <wallet\/bitcoin\/api_impl\/BitcoinLikeTransactionApi.h>\n\nclass BitcoinLikeWalletP2SHSynchronization : public BaseFixture {\n\n};\n\nTEST_F(BitcoinLikeWalletP2SHSynchronization, MediumXpubSynchronization) {\n auto pool = newDefaultPool();\n {\n auto configuration = DynamicObject::newInstance();\n configuration->putString(api::Configuration::KEYCHAIN_ENGINE,api::KeychainEngines::BIP49_P2SH);\n configuration->putString(api::Configuration::KEYCHAIN_DERIVATION_SCHEME,\"49'\/<coin_type>'\/<account>'\/<node>\/<address>\");\n\n auto wallet = uv::wait(pool->createWallet(\"e847815f-488a-4301-b67c-378a5e9c8a61\", \"bitcoin_testnet\", configuration));\n {\n auto nextIndex = uv::wait(wallet->getNextAccountIndex());\n EXPECT_EQ(nextIndex, 0);\n\n auto account = createBitcoinLikeAccount(wallet, nextIndex, P2SH_XPUB_INFO);\n\n auto receiver = make_receiver([=](const std::shared_ptr<api::Event> &event) {\n fmt::print(\"Received event {}\\n\", api::to_string(event->getCode()));\n if (event->getCode() == api::EventCode::SYNCHRONIZATION_STARTED)\n return;\n EXPECT_NE(event->getCode(), api::EventCode::SYNCHRONIZATION_FAILED);\n EXPECT_EQ(event->getCode(),\n api::EventCode::SYNCHRONIZATION_SUCCEED_ON_PREVIOUSLY_EMPTY_ACCOUNT);\n dispatcher->stop();\n });\n\n auto bus = account->synchronize();\n bus->subscribe(getTestExecutionContext(),receiver);\n\n dispatcher->waitUntilStopped();\n\n auto block = uv::wait(account->getLastBlock());\n auto blockHash = block.blockHash;\n }\n }\n}\n\nTEST_F(BitcoinLikeWalletP2SHSynchronization, SynchronizeOnceAtATime) {\n auto pool = newDefaultPool();\n {\n auto configuration = DynamicObject::newInstance();\n configuration->putString(api::Configuration::KEYCHAIN_ENGINE,api::KeychainEngines::BIP49_P2SH);\n configuration->putString(api::Configuration::KEYCHAIN_DERIVATION_SCHEME,\"49'\/<coin_type>'\/<account>'\/<node>\/<address>\");\n\n auto wallet = uv::wait(pool->createWallet(\"e847815f-488a-4301-b67c-378a5e9c8a62\", \"bitcoin_testnet\",configuration));\n {\n auto nextIndex = uv::wait(wallet->getNextAccountIndex());\n EXPECT_EQ(nextIndex, 0);\n auto account = createBitcoinLikeAccount(wallet, nextIndex, P2SH_XPUB_INFO);\n auto eventBus = pool->getEventBus();\n eventBus->subscribe(getTestExecutionContext(),\n make_receiver([](const std::shared_ptr<api::Event> &event) {\n fmt::print(\"Received event {}\\n\", api::to_string(event->getCode()));\n }));\n auto bus = account->synchronize();\n bus->subscribe(getTestExecutionContext(),\n make_receiver([=](const std::shared_ptr<api::Event> &event) {\n fmt::print(\"Received event {}\\n\", api::to_string(event->getCode()));\n if (event->getCode() == api::EventCode::SYNCHRONIZATION_STARTED)\n return;\n EXPECT_NE(event->getCode(), api::EventCode::SYNCHRONIZATION_FAILED);\n EXPECT_EQ(event->getCode(),\n api::EventCode::SYNCHRONIZATION_SUCCEED_ON_PREVIOUSLY_EMPTY_ACCOUNT);\n dispatcher->stop();\n }));\n EXPECT_EQ(bus, account->synchronize());\n dispatcher->waitUntilStopped();\n }\n }\n}\n\nTEST_F(BitcoinLikeWalletP2SHSynchronization, DISABLED_SynchronizeFromLastBlock) {\n auto pool = newDefaultPool();\n {\n auto configuration = DynamicObject::newInstance();\n configuration->putString(api::Configuration::KEYCHAIN_ENGINE,api::KeychainEngines::BIP49_P2SH);\n configuration->putString(api::Configuration::KEYCHAIN_DERIVATION_SCHEME,\"49'\/<coin_type>'\/<account>'\/<node>\/<address>\");\n const auto walletName = randomWalletName();\n auto wallet = uv::wait(pool->createWallet(walletName, \"bitcoin_testnet\",configuration));\n createBitcoinLikeAccount(wallet, 0, P2SH_XPUB_INFO);\n auto synchronize = [wallet, pool, this] (std::shared_ptr<uv::SequentialExecutionContext> context, bool expectNewOp) {\n auto account = uv::wait(wallet->getAccount(0));\n auto numberOfOp = 0;\n\n auto receiverNumberOp = make_receiver([&numberOfOp](const std::shared_ptr<api::Event> &event) {\n numberOfOp += 1;\n });\n\n auto eventBus = pool->getEventBus();\n eventBus->subscribe(context, receiverNumberOp);\n auto bus = account->synchronize();\n\n auto receiver = make_receiver([=, &numberOfOp](const std::shared_ptr<api::Event> &event) {\n fmt::print(\"Received event {}\\n\", api::to_string(event->getCode()));\n if (event->getCode() == api::EventCode::SYNCHRONIZATION_STARTED)\n return;\n\n EXPECT_NE(event->getCode(), api::EventCode::SYNCHRONIZATION_FAILED);\n EXPECT_EQ(expectNewOp, (numberOfOp > 0));\n context->stop();\n });\n\n bus->subscribe(context, receiver);\n auto newBus = account->synchronize();\n EXPECT_EQ(bus, newBus);\n context->waitUntilStopped();\n return bus;\n };\n\n auto b1 = synchronize(std::dynamic_pointer_cast<uv::SequentialExecutionContext>(\n dispatcher->getSerialExecutionContext(\"__sync1__\")), true);\n auto b2 = synchronize(std::dynamic_pointer_cast<uv::SequentialExecutionContext>(\n dispatcher->getSerialExecutionContext(\"__sync2__\")), false);\n EXPECT_NE(b1, b2);\n }\n}\n\nTEST_F(BitcoinLikeWalletP2SHSynchronization, EraseDataSinceAfterSynchronization) {\n auto pool = newDefaultPool();\n const auto walletName = randomWalletName();\n {\n \/\/Set configuration\n auto configuration = DynamicObject::newInstance();\n configuration->putString(api::Configuration::KEYCHAIN_ENGINE, api::KeychainEngines::BIP49_P2SH);\n configuration->putString(api::Configuration::KEYCHAIN_DERIVATION_SCHEME,\n \"49'\/<coin_type>'\/<account>'\/<node>\/<address>\");\n \/\/Create wallet\n auto wallet = uv::wait(pool->createWallet(walletName, \"bitcoin_testnet\", configuration));\n \/\/Create account\n auto account = createBitcoinLikeAccount(wallet, 0, P2SH_XPUB_INFO);\n \/\/Sync account\n auto bus = account->synchronize();\n auto receiver = make_receiver([=](const std::shared_ptr<api::Event> &event) {\n fmt::print(\"Received event {}\\n\", api::to_string(event->getCode()));\n if (event->getCode() == api::EventCode::SYNCHRONIZATION_STARTED)\n return;\n\n EXPECT_NE(event->getCode(), api::EventCode::SYNCHRONIZATION_FAILED);\n dispatcher->stop();\n });\n bus->subscribe(getTestExecutionContext(),receiver);\n dispatcher->waitUntilStopped();\n\n auto accountCount = uv::wait(wallet->getAccountCount());\n EXPECT_EQ(accountCount, 1);\n auto accountFromWallet = uv::wait(wallet->getAccount(0));\n EXPECT_EQ(account, accountFromWallet);\n\n auto date = \"2000-03-27T09:10:22Z\";\n auto formatedDate = DateUtils::fromJSON(date);\n\n \/\/Delete account\n auto code = uv::wait(wallet->eraseDataSince(formatedDate));\n EXPECT_EQ(code, api::ErrorCode::FUTURE_WAS_SUCCESSFULL);\n\n \/\/Check if account was successfully deleted\n auto newAccountCount = uv::wait(wallet->getAccountCount());\n EXPECT_EQ(newAccountCount, 0);\n {\n soci::session sql(pool->getDatabaseSessionPool()->getPool());\n BitcoinLikeAccountDatabaseEntry entry;\n auto result = BitcoinLikeAccountDatabaseHelper::queryAccount(sql, account->getAccountUid(), entry);\n EXPECT_EQ(result, false);\n }\n\n \/\/Delete wallet\n auto walletCode = uv::wait(pool->eraseDataSince(formatedDate));\n EXPECT_EQ(walletCode, api::ErrorCode::FUTURE_WAS_SUCCESSFULL);\n\n \/\/Check if wallet was successfully deleted\n auto walletCount = uv::wait(pool->getWalletCount());\n EXPECT_EQ(walletCount, 0);\n }\n}\nTEST_F(BitcoinLikeWalletP2SHSynchronization, TestNetSynchronization) {\n auto pool = newDefaultPool();\n {\n auto configuration = DynamicObject::newInstance();\n configuration->putString(api::Configuration::KEYCHAIN_ENGINE,api::KeychainEngines::BIP49_P2SH);\n configuration->putString(api::Configuration::KEYCHAIN_DERIVATION_SCHEME,\"49'\/<coin_type>'\/<account>'\/<node>\/<address>\");\n auto wallet = uv::wait(pool->createWallet(\"testnet_wallet\", \"bitcoin_testnet\",configuration));\n {\n auto nextIndex = uv::wait(wallet->getNextAccountIndex());\n auto info = uv::wait(wallet->getNextExtendedKeyAccountCreationInfo());\n info.extendedKeys.push_back(\"tpubDCcvqEHx7prGddpWTfEviiew5YLMrrKy4oJbt14teJZenSi6AYMAs2SNXwYXFzkrNYwECSmobwxESxMCrpfqw4gsUt88bcr8iMrJmbb8P2q\");\n EXPECT_EQ(nextIndex, 0);\n auto account = createBitcoinLikeAccount(wallet, nextIndex, info);\n auto receiver = make_receiver([=](const std::shared_ptr<api::Event> &event) {\n fmt::print(\"Received event {}\\n\", api::to_string(event->getCode()));\n if (event->getCode() == api::EventCode::SYNCHRONIZATION_STARTED)\n return;\n EXPECT_NE(event->getCode(), api::EventCode::SYNCHRONIZATION_FAILED);\n dispatcher->stop();\n });\n\n auto bus = account->synchronize();\n bus->subscribe(getTestExecutionContext(),receiver);\n dispatcher->waitUntilStopped();\n }\n }\n}\n\nTEST_F(BitcoinLikeWalletP2SHSynchronization, DecredParsingAndSerialization) {\n auto pool = newDefaultPool();\n {\n auto wallet = uv::wait(pool->createWallet(\"testnet_wallet\", \"decred\",DynamicObject::newInstance()));\n auto strTx = \"01000000016b9b4d4cdd2cf78907e62cddf31911ae4d4af1d89228ae4afc4459edee6a60c40100000000ffffff000240420f000000000000001976a9141d19445f397f6f0d3e2e6d741f61ba66b53886cf88acf0d31d000000000000001976a91415101bac61dca29add75996a0836a469dc8eee0788ac00000000ffffffff01000000000000000000000000ffffffff6a47304402200466bbc2aa8a742e85c3b68911502e73cdcb620ceaaa7a3cd199dbb4f8e9b969022063afeedd37d05e44b655a9de92eb36124acc045baf7b9e2941f81e41af91f1150121030ac79bab351084fdc82b4fa46eaa6a9cd2b5eb97ee93e367422bf47219b54a14\";\n auto tx = BitcoinLikeTransactionApi::parseRawSignedTransaction(wallet->getCurrency(), hex::toByteArray(strTx), 0);\n EXPECT_EQ(hex::toString(tx->serialize()), strTx);\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ License: Apache 2.0. See LICENSE file in root directory.\n\/\/ Copyright(c) 2020 Intel Corporation. All Rights Reserved.\n\n#include \"split-filter.h\"\n\nnamespace librealsense\n{\n split_filter::split_filter()\n : generic_processing_block(\"Split Filter\"),\n _selected_stream_id(0.f)\n {\n auto selected_stream_id = std::make_shared<ptr_option<float>>(0.f, 3.f, 1.f, 1.f, \n &_selected_stream_id, \"Selected stream id for display\");\n register_option(RS2_OPTION_SELECT_ID, selected_stream_id);\n\n _last_frame[0] = nullptr;\n _last_frame[1] = nullptr;\n _last_frame[2] = nullptr;\n }\n\n \/\/ processing only simple frames (not framesets)\n \/\/ only depth frames\n \/\/ only index 0\n bool split_filter::should_process(const rs2::frame& frame)\n {\n if (!frame)\n return false;\n\n auto set = frame.as<rs2::frameset>();\n if (set)\n return false;\n\n auto depth_frame = frame.as<rs2::depth_frame>();\n if (!depth_frame)\n return false;\n\n auto profile = frame.get_profile();\n rs2_stream stream = profile.stream_type();\n if (stream != RS2_STREAM_DEPTH)\n return false;\n\n int index = profile.stream_index();\n if (index != 0)\n return false;\n\n return true;\n }\n\n rs2::frame split_filter::process_frame(const rs2::frame_source& source, const rs2::frame& f)\n {\n \/\/ steps:\n \/\/ only for depth: \n \/\/ 1. check hdr seq id in metadata - if not as the option selected id, return last frame\n \/\/ 2. create new profile with stream index so that:\n \/\/ - stream with seq_id 1 will have index 1 \n \/\/ - stream with seq_id 2 will have index 2\n \/\/ 3. allocate new frame\n \/\/ 4. memcpy src to target for data\n\n \/\/ 1. check hdr seq id in metadata\n auto depth_frame = f.as<rs2::depth_frame>();\n auto depth_exposure = depth_frame.get_frame_metadata(RS2_FRAME_METADATA_ACTUAL_EXPOSURE);\n \/\/int hdr_seq_id = depth_frame.get_frame_metadata(RS2_FRAME_METADATA_HDR_SEQUENCE_ID);\n int hdr_seq_id = 1;\n if (depth_exposure == 1.f)\n {\n hdr_seq_id = 2;\n }\n\n if (!is_selected_id(hdr_seq_id))\n {\n if (_last_frame[hdr_seq_id])\n {\n auto lf_exposure = _last_frame[hdr_seq_id].get_frame_metadata(RS2_FRAME_METADATA_ACTUAL_EXPOSURE);\n return _last_frame[hdr_seq_id];\n }\n return f;\n }\n\n \/\/ 2. create new profile with stream index so that:\n \/\/ - stream with seq_id 1 will have index 1 \n \/\/ - stream with seq_id 2 will have index 2\n rs2::stream_profile new_profile = depth_frame.get_profile().\n clone(depth_frame.get_profile().stream_type(), hdr_seq_id, depth_frame.get_profile().format());\n\n \/\/ 3. allocate new frame\n auto width = depth_frame.get_width();\n auto height = depth_frame.get_height();\n auto split_frame = source.allocate_video_frame(new_profile, f, depth_frame.get_bytes_per_pixel(),\n width, height, depth_frame.get_stride_in_bytes(), RS2_EXTENSION_DEPTH_FRAME);\n\n \/\/ 4. memcpy src to target for data\n if (split_frame)\n {\n auto ptr = dynamic_cast<librealsense::depth_frame*>((librealsense::frame_interface*)split_frame.get());\n auto orig = dynamic_cast<librealsense::depth_frame*>((librealsense::frame_interface*)f.get());\n\n auto new_data = (uint16_t*)(ptr->get_frame_data());\n auto orig_data = (uint16_t*)(orig->get_frame_data());\n memcpy(new_data, orig_data, width * height * sizeof(uint16_t));\n\n ptr->set_sensor(orig->get_sensor());\n\n _last_frame[hdr_seq_id] = split_frame;\n\n return split_frame;\n }\n\n return f;\n }\n\n bool split::is_selected_id(int sequence_id)\n {\n if (_selected_stream_id != 0 && sequence_id != _selected_stream_id)\n return false;\n return true;\n }\n}<commit_msg>few improvements in split pb<commit_after>\/\/ License: Apache 2.0. See LICENSE file in root directory.\n\/\/ Copyright(c) 2020 Intel Corporation. All Rights Reserved.\n\n#include \"split-filter.h\"\n\nnamespace librealsense\n{\n split_filter::split_filter()\n : generic_processing_block(\"Split Filter\"),\n _selected_stream_id(1.f)\n {\n auto selected_stream_id = std::make_shared<ptr_option<float>>(0.f, 3.f, 1.f, 1.f, \n &_selected_stream_id, \"Selected stream id for display\");\n register_option(RS2_OPTION_SELECT_ID, selected_stream_id);\n\n _last_frame[0] = nullptr;\n _last_frame[1] = nullptr;\n _last_frame[2] = nullptr;\n }\n\n \/\/ processing only simple frames (not framesets)\n \/\/ only depth frames\n \/\/ only index 0\n bool split_filter::should_process(const rs2::frame& frame)\n {\n if (!frame)\n return false;\n\n auto set = frame.as<rs2::frameset>();\n if (set)\n return false;\n\n auto depth_frame = frame.as<rs2::depth_frame>();\n if (!depth_frame)\n return false;\n\n auto profile = frame.get_profile();\n rs2_stream stream = profile.stream_type();\n if (stream != RS2_STREAM_DEPTH)\n return false;\n\n int index = profile.stream_index();\n if (index != 0)\n return false;\n\n return true;\n }\n\n rs2::frame split_filter::process_frame(const rs2::frame_source& source, const rs2::frame& f)\n {\n \/\/ steps:\n \/\/ only for depth: \n \/\/ 1. check hdr seq id in metadata - if not as the option selected id, return last frame\n \/\/ 2. create new profile with stream index so that:\n \/\/ - stream with seq_id 1 will have index 1 \n \/\/ - stream with seq_id 2 will have index 2\n \/\/ 3. allocate new frame\n \/\/ 4. memcpy src to target for data\n\n \/\/ 1. check hdr seq id in metadata\n auto depth_frame = f.as<rs2::depth_frame>();\n auto depth_exposure = depth_frame.get_frame_metadata(RS2_FRAME_METADATA_ACTUAL_EXPOSURE);\n \/\/int hdr_seq_id = depth_frame.get_frame_metadata(RS2_FRAME_METADATA_HDR_SEQUENCE_ID);\n int hdr_seq_id = 1;\n if (depth_exposure == 1.f)\n {\n hdr_seq_id = 2;\n }\n\n if (!is_selected_id(hdr_seq_id))\n {\n if (_last_frame[static_cast<int>(_selected_stream_id)])\n return _last_frame[static_cast<int>(_selected_stream_id)];\n return f;\n }\n\n \/\/ 2. create new profile with stream index so that:\n \/\/ - stream with seq_id 1 will have index 1 \n \/\/ - stream with seq_id 2 will have index 2\n rs2::stream_profile new_profile = depth_frame.get_profile().\n clone(depth_frame.get_profile().stream_type(), hdr_seq_id, depth_frame.get_profile().format());\n\n \/\/ 3. allocate new frame\n auto width = depth_frame.get_width();\n auto height = depth_frame.get_height();\n auto split_frame = source.allocate_video_frame(new_profile, f, depth_frame.get_bytes_per_pixel(),\n width, height, depth_frame.get_stride_in_bytes(), RS2_EXTENSION_DEPTH_FRAME);\n\n \/\/ 4. memcpy src to target for data\n if (split_frame)\n {\n auto ptr = dynamic_cast<librealsense::depth_frame*>((librealsense::frame_interface*)split_frame.get());\n auto orig = dynamic_cast<librealsense::depth_frame*>((librealsense::frame_interface*)f.get());\n\n auto new_data = (uint16_t*)(ptr->get_frame_data());\n auto orig_data = (uint16_t*)(orig->get_frame_data());\n memcpy(new_data, orig_data, width * height * sizeof(uint16_t));\n\n ptr->set_sensor(orig->get_sensor());\n\n _last_frame[hdr_seq_id] = split_frame;\n\n return split_frame;\n }\n\n return f;\n }\n\n bool split::is_selected_id(int sequence_id)\n {\n if ( 0 != static_cast<int>(_selected_stream_id) && \n sequence_id != static_cast<int>(_selected_stream_id))\n return false;\n return true;\n }\n}<|endoftext|>"} {"text":"<commit_before><commit_msg>Consider \"certificate revoked\" as the most serious certificate error.<commit_after><|endoftext|>"} {"text":"<commit_before><commit_msg>Enable a test, by masking failures if the system does not support IPv6.<commit_after><|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) [2004-2014] Novell, Inc.\n * Copyright (c) [2016-2018] SUSE LLC\n *\n * All Rights Reserved.\n *\n * This program is free software; you can redistribute it and\/or modify it\n * under the terms of version 2 of the GNU General Public License as published\n * by the Free Software Foundation.\n *\n * This program is distributed in the hope that it will be useful, but WITHOUT\n * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for\n * more details.\n *\n * You should have received a copy of the GNU General Public License along\n * with this program; if not, contact Novell, Inc.\n *\n * To contact Novell about this file by physical or electronic mail, you may\n * find current contact information at www.novell.com.\n *\/\n\n\n#include <locale>\n#include <cmath>\n#include <vector>\n#include <sstream>\n#include <boost\/algorithm\/string.hpp>\n\n#include \"storage\/Utils\/Text.h\"\n#include \"storage\/Utils\/HumanString.h\"\n#include \"storage\/Utils\/Math.h\"\n#include \"storage\/Utils\/ExceptionImpl.h\"\n\n\nnamespace storage\n{\n using std::string;\n\n\n int\n num_suffixes()\n {\n\treturn 7;\n }\n\n\n vector<Text>\n get_all_suffixes(int i, bool all = false, bool sloppy = false)\n {\n\tvector<Text> ret;\n\n\tswitch (i)\n\t{\n\t case 0:\n\t\t\/\/ TRANSLATORS: symbol for \"bytes\" (best keep untranslated)\n\t\tret.push_back(_(\"B\"));\n\t\tif (sloppy)\n\t\t ret.push_back(Text(\"\", \"\"));\n\t\tbreak;\n\n\t case 1:\n\t\t\/\/ TRANSLATORS: symbol for \"kibi bytes\" (best keep untranslated)\n\t\tret.push_back(_(\"KiB\"));\n\t\tif (all)\n\t\t \/\/ TRANSLATORS: symbol for \"kilo bytes\" (best keep untranslated)\n\t\t ret.push_back(_(\"kB\"));\n\t\tif (sloppy)\n\t\t \/\/ TRANSLATORS: symbol for \"kilo\" (best keep untranslated)\n\t\t ret.push_back(_(\"k\"));\n\t\tbreak;\n\n\t case 2:\n\t\t\/\/ TRANSLATORS: symbol for \"mebi bytes\" (best keep untranslated)\n\t\tret.push_back(_(\"MiB\"));\n\t\tif (all)\n\t\t \/\/ TRANSLATORS: symbol for \"mega bytes\" (best keep untranslated)\n\t\t ret.push_back(_(\"MB\"));\n\t\tif (sloppy)\n\t\t \/\/ TRANSLATORS: symbol for \"mega\" (best keep untranslated)\n\t\t ret.push_back(_(\"M\"));\n\t\tbreak;\n\n\t case 3:\n\t\t\/\/ TRANSLATORS: symbol for \"gibi bytes\" (best keep untranslated)\n\t\tret.push_back(_(\"GiB\"));\n\t\tif (all)\n\t\t \/\/ TRANSLATORS: symbol for \"giga bytes\" (best keep untranslated)\n\t\t ret.push_back(_(\"GB\"));\n\t\tif (sloppy)\n\t\t \/\/ TRANSLATORS: symbol for \"giga\" (best keep untranslated)\n\t\t ret.push_back(_(\"G\"));\n\t\tbreak;\n\n\t case 4:\n\t\t\/\/ TRANSLATORS: symbol for \"tebi bytes\" (best keep untranslated)\n\t\tret.push_back(_(\"TiB\"));\n\t\tif (all)\n\t\t \/\/ TRANSLATORS: symbol for \"tera bytes\" (best keep untranslated)\n\t\t ret.push_back(_(\"TB\"));\n\t\tif (sloppy)\n\t\t \/\/ TRANSLATORS: symbol for \"tera\" (best keep untranslated)\n\t\t ret.push_back(_(\"T\"));\n\t\tbreak;\n\n\t case 5:\n\t\t\/\/ TRANSLATORS: symbol for \"pebi bytes\" (best keep untranslated)\n\t\tret.push_back(_(\"PiB\"));\n\t\tif (all)\n\t\t \/\/ TRANSLATORS: symbol for \"peta bytes\" (best keep untranslated)\n\t\t ret.push_back(_(\"PB\"));\n\t\tif (sloppy)\n\t\t \/\/ TRANSLATORS: symbol for \"peta\" (best keep untranslated)\n\t\t ret.push_back(_(\"P\"));\n\t\tbreak;\n\n\t case 6:\n\t\t\/\/ TRANSLATORS: symbol for \"exbi bytes\" (best keep untranslated)\n\t\tret.push_back(_(\"EiB\"));\n\t\tif (all)\n\t\t \/\/ TRANSLATORS: symbol for \"exa bytes\" (best keep untranslated)\n\t\t ret.push_back(_(\"EB\"));\n\t\tif (sloppy)\n\t\t \/\/ TRANSLATORS: symbol for \"exa\" (best keep untranslated)\n\t\t ret.push_back(_(\"E\"));\n\t\tbreak;\n\t}\n\n\treturn ret;\n }\n\n\n string\n get_suffix(int i, bool classic)\n {\n\treturn classic ? get_all_suffixes(i).front().native : get_all_suffixes(i).front().translated;\n }\n\n\n \/\/ Both byte_to_humanstring and humanstring_to_byte use integer arithmetic\n \/\/ as long as possible to provide exact results for those cases.\n\n\n string\n byte_to_humanstring(unsigned long long size, bool classic, int precision, bool omit_zeroes)\n {\n\tconst locale loc = classic ? locale::classic() : locale();\n\n\t\/\/ Calculate the index of the suffix to use. The index increases by 1\n\t\/\/ when the number of leading zeros decreases by 10.\n\n\tint i = size > 0 ? (64 - (clz(size) + 1)) \/ 10 : 0;\n\n\tif ((i == 0) || (omit_zeroes && is_multiple_of(size, 1ULL << 10 * i)))\n\t{\n\t unsigned long long v = size >> 10 * i;\n\n\t std::ostringstream s;\n\t s.imbue(loc);\n\t s << v << ' ' << get_suffix(i, classic);\n\t return s.str();\n\t}\n\telse\n\t{\n\t long double v = std::ldexp((long double)(size), - 10 * i);\n\n\t std::ostringstream s;\n\t s.imbue(loc);\n\t s.setf(ios::fixed);\n\t s.precision(precision);\n\t s << v << ' ' << get_suffix(i, classic);\n\t return s.str();\n\t}\n }\n\n\n namespace\n {\n\t\/\/ Helper functions to parse a number as int or float, multiply\n\t\/\/ according to the suffix. Do all required error checks.\n\n\tpair<bool, unsigned long long>\n\tparse_i(const string& str, int i, const locale& loc)\n\t{\n\t istringstream s(str);\n\t s.imbue(loc);\n\n\t unsigned long long v;\n\t s >> v;\n\n\t if (!s.eof())\n\t\treturn make_pair(false, 0);\n\n\t if (s.fail())\n\t {\n\t\tif (v == std::numeric_limits<unsigned long long>::max())\n\t\t ST_THROW(OverflowException());\n\n\t\treturn make_pair(false, 0);\n\t }\n\n\t if (v != 0 && str[0] == '-')\n\t\tST_THROW(OverflowException());\n\n\t if (v > 0 && clz(v) < 10 * i)\n\t\tST_THROW(OverflowException());\n\n\t v <<= 10 * i;\n\n\t return make_pair(true, v);\n\t}\n\n\n\tpair<bool, unsigned long long>\n\tparse_f(const string& str, int i, const locale& loc)\n\t{\n\t istringstream s(str);\n\t s.imbue(loc);\n\n\t long double v;\n\t s >> v;\n\n\t if (!s.eof())\n\t\treturn make_pair(false, 0);\n\n\t if (s.fail())\n\t {\n\t\tif (v == std::numeric_limits<long double>::max())\n\t\t ST_THROW(OverflowException());\n\n\t\treturn make_pair(false, 0);\n\t }\n\n\t if (v < 0.0)\n\t\tST_THROW(OverflowException());\n\n\t v = std::round(std::ldexp(v, 10 * i));\n\n\t if (v > std::numeric_limits<unsigned long long>::max())\n\t\tST_THROW(OverflowException());\n\n\t return make_pair(true, v);\n\t}\n\n }\n\n\n unsigned long long\n humanstring_to_byte(const string& str, bool classic)\n {\n\tconst locale loc = classic ? locale::classic() : locale();\n\n\tconst string str_trimmed = boost::trim_copy(str, loc);\n\n\tfor (int i = 0; i < num_suffixes(); ++i)\n\t{\n\t vector<Text> suffixes = get_all_suffixes(i, true, !classic);\n\n\t for (const Text& suffix : suffixes)\n\t {\n\t\tconst string& tmp = classic ? suffix.native : suffix.translated;\n\n\t\tif (boost::iends_with(str_trimmed, tmp, loc))\n\t\t{\n\t\t string number = boost::trim_copy(str_trimmed.substr(0, str_trimmed.size() - tmp.size()), loc);\n\n\t\t pair<bool, unsigned long long> v;\n\n\t\t v = parse_i(number, i, loc);\n\t\t if (v.first)\n\t\t\treturn v.second;\n\n\t\t v = parse_f(number, i, loc);\n\t\t if (v.first)\n\t\t\treturn v.second;\n\t\t}\n\t }\n\t}\n\n\tST_THROW(ParseException(\"failed to parse\", str, \"something like 1 GiB\"));\n }\n\n}\n<commit_msg>- ported check from snapper<commit_after>\/*\n * Copyright (c) [2004-2014] Novell, Inc.\n * Copyright (c) [2016-2018] SUSE LLC\n *\n * All Rights Reserved.\n *\n * This program is free software; you can redistribute it and\/or modify it\n * under the terms of version 2 of the GNU General Public License as published\n * by the Free Software Foundation.\n *\n * This program is distributed in the hope that it will be useful, but WITHOUT\n * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for\n * more details.\n *\n * You should have received a copy of the GNU General Public License along\n * with this program; if not, contact Novell, Inc.\n *\n * To contact Novell about this file by physical or electronic mail, you may\n * find current contact information at www.novell.com.\n *\/\n\n\n#include <locale>\n#include <cmath>\n#include <vector>\n#include <sstream>\n#include <boost\/algorithm\/string.hpp>\n\n#include \"storage\/Utils\/Text.h\"\n#include \"storage\/Utils\/HumanString.h\"\n#include \"storage\/Utils\/Math.h\"\n#include \"storage\/Utils\/ExceptionImpl.h\"\n\n\nnamespace storage\n{\n using std::string;\n\n\n int\n num_suffixes()\n {\n\treturn 7;\n }\n\n\n vector<Text>\n get_all_suffixes(int i, bool all = false, bool sloppy = false)\n {\n\tvector<Text> ret;\n\n\tswitch (i)\n\t{\n\t case 0:\n\t\t\/\/ TRANSLATORS: symbol for \"bytes\" (best keep untranslated)\n\t\tret.push_back(_(\"B\"));\n\t\tif (sloppy)\n\t\t ret.push_back(Text(\"\", \"\"));\n\t\tbreak;\n\n\t case 1:\n\t\t\/\/ TRANSLATORS: symbol for \"kibi bytes\" (best keep untranslated)\n\t\tret.push_back(_(\"KiB\"));\n\t\tif (all)\n\t\t \/\/ TRANSLATORS: symbol for \"kilo bytes\" (best keep untranslated)\n\t\t ret.push_back(_(\"kB\"));\n\t\tif (sloppy)\n\t\t \/\/ TRANSLATORS: symbol for \"kilo\" (best keep untranslated)\n\t\t ret.push_back(_(\"k\"));\n\t\tbreak;\n\n\t case 2:\n\t\t\/\/ TRANSLATORS: symbol for \"mebi bytes\" (best keep untranslated)\n\t\tret.push_back(_(\"MiB\"));\n\t\tif (all)\n\t\t \/\/ TRANSLATORS: symbol for \"mega bytes\" (best keep untranslated)\n\t\t ret.push_back(_(\"MB\"));\n\t\tif (sloppy)\n\t\t \/\/ TRANSLATORS: symbol for \"mega\" (best keep untranslated)\n\t\t ret.push_back(_(\"M\"));\n\t\tbreak;\n\n\t case 3:\n\t\t\/\/ TRANSLATORS: symbol for \"gibi bytes\" (best keep untranslated)\n\t\tret.push_back(_(\"GiB\"));\n\t\tif (all)\n\t\t \/\/ TRANSLATORS: symbol for \"giga bytes\" (best keep untranslated)\n\t\t ret.push_back(_(\"GB\"));\n\t\tif (sloppy)\n\t\t \/\/ TRANSLATORS: symbol for \"giga\" (best keep untranslated)\n\t\t ret.push_back(_(\"G\"));\n\t\tbreak;\n\n\t case 4:\n\t\t\/\/ TRANSLATORS: symbol for \"tebi bytes\" (best keep untranslated)\n\t\tret.push_back(_(\"TiB\"));\n\t\tif (all)\n\t\t \/\/ TRANSLATORS: symbol for \"tera bytes\" (best keep untranslated)\n\t\t ret.push_back(_(\"TB\"));\n\t\tif (sloppy)\n\t\t \/\/ TRANSLATORS: symbol for \"tera\" (best keep untranslated)\n\t\t ret.push_back(_(\"T\"));\n\t\tbreak;\n\n\t case 5:\n\t\t\/\/ TRANSLATORS: symbol for \"pebi bytes\" (best keep untranslated)\n\t\tret.push_back(_(\"PiB\"));\n\t\tif (all)\n\t\t \/\/ TRANSLATORS: symbol for \"peta bytes\" (best keep untranslated)\n\t\t ret.push_back(_(\"PB\"));\n\t\tif (sloppy)\n\t\t \/\/ TRANSLATORS: symbol for \"peta\" (best keep untranslated)\n\t\t ret.push_back(_(\"P\"));\n\t\tbreak;\n\n\t case 6:\n\t\t\/\/ TRANSLATORS: symbol for \"exbi bytes\" (best keep untranslated)\n\t\tret.push_back(_(\"EiB\"));\n\t\tif (all)\n\t\t \/\/ TRANSLATORS: symbol for \"exa bytes\" (best keep untranslated)\n\t\t ret.push_back(_(\"EB\"));\n\t\tif (sloppy)\n\t\t \/\/ TRANSLATORS: symbol for \"exa\" (best keep untranslated)\n\t\t ret.push_back(_(\"E\"));\n\t\tbreak;\n\t}\n\n\treturn ret;\n }\n\n\n string\n get_suffix(int i, bool classic)\n {\n\treturn classic ? get_all_suffixes(i).front().native : get_all_suffixes(i).front().translated;\n }\n\n\n \/\/ Both byte_to_humanstring and humanstring_to_byte use integer arithmetic\n \/\/ as long as possible to provide exact results for those cases.\n\n\n string\n byte_to_humanstring(unsigned long long size, bool classic, int precision, bool omit_zeroes)\n {\n\tconst locale loc = classic ? locale::classic() : locale();\n\n\t\/\/ Calculate the index of the suffix to use. The index increases by 1\n\t\/\/ when the number of leading zeros decreases by 10.\n\n\tstatic_assert(sizeof(size) == 8, \"unsigned long long not 64 bit\");\n\n\tint i = size > 0 ? (64 - (clz(size) + 1)) \/ 10 : 0;\n\n\tif ((i == 0) || (omit_zeroes && is_multiple_of(size, 1ULL << 10 * i)))\n\t{\n\t unsigned long long v = size >> 10 * i;\n\n\t std::ostringstream s;\n\t s.imbue(loc);\n\t s << v << ' ' << get_suffix(i, classic);\n\t return s.str();\n\t}\n\telse\n\t{\n\t long double v = std::ldexp((long double)(size), - 10 * i);\n\n\t std::ostringstream s;\n\t s.imbue(loc);\n\t s.setf(ios::fixed);\n\t s.precision(precision);\n\t s << v << ' ' << get_suffix(i, classic);\n\t return s.str();\n\t}\n }\n\n\n namespace\n {\n\t\/\/ Helper functions to parse a number as int or float, multiply\n\t\/\/ according to the suffix. Do all required error checks.\n\n\tpair<bool, unsigned long long>\n\tparse_i(const string& str, int i, const locale& loc)\n\t{\n\t istringstream s(str);\n\t s.imbue(loc);\n\n\t unsigned long long v;\n\t s >> v;\n\n\t if (!s.eof())\n\t\treturn make_pair(false, 0);\n\n\t if (s.fail())\n\t {\n\t\tif (v == std::numeric_limits<unsigned long long>::max())\n\t\t ST_THROW(OverflowException());\n\n\t\treturn make_pair(false, 0);\n\t }\n\n\t if (v != 0 && str[0] == '-')\n\t\tST_THROW(OverflowException());\n\n\t if (v > 0 && clz(v) < 10 * i)\n\t\tST_THROW(OverflowException());\n\n\t v <<= 10 * i;\n\n\t return make_pair(true, v);\n\t}\n\n\n\tpair<bool, unsigned long long>\n\tparse_f(const string& str, int i, const locale& loc)\n\t{\n\t istringstream s(str);\n\t s.imbue(loc);\n\n\t long double v;\n\t s >> v;\n\n\t if (!s.eof())\n\t\treturn make_pair(false, 0);\n\n\t if (s.fail())\n\t {\n\t\tif (v == std::numeric_limits<long double>::max())\n\t\t ST_THROW(OverflowException());\n\n\t\treturn make_pair(false, 0);\n\t }\n\n\t if (v < 0.0)\n\t\tST_THROW(OverflowException());\n\n\t v = std::round(std::ldexp(v, 10 * i));\n\n\t if (v > std::numeric_limits<unsigned long long>::max())\n\t\tST_THROW(OverflowException());\n\n\t return make_pair(true, v);\n\t}\n\n }\n\n\n unsigned long long\n humanstring_to_byte(const string& str, bool classic)\n {\n\tconst locale loc = classic ? locale::classic() : locale();\n\n\tconst string str_trimmed = boost::trim_copy(str, loc);\n\n\tfor (int i = 0; i < num_suffixes(); ++i)\n\t{\n\t vector<Text> suffixes = get_all_suffixes(i, true, !classic);\n\n\t for (const Text& suffix : suffixes)\n\t {\n\t\tconst string& tmp = classic ? suffix.native : suffix.translated;\n\n\t\tif (boost::iends_with(str_trimmed, tmp, loc))\n\t\t{\n\t\t string number = boost::trim_copy(str_trimmed.substr(0, str_trimmed.size() - tmp.size()), loc);\n\n\t\t pair<bool, unsigned long long> v;\n\n\t\t v = parse_i(number, i, loc);\n\t\t if (v.first)\n\t\t\treturn v.second;\n\n\t\t v = parse_f(number, i, loc);\n\t\t if (v.first)\n\t\t\treturn v.second;\n\t\t}\n\t }\n\t}\n\n\tST_THROW(ParseException(\"failed to parse\", str, \"something like 1 GiB\"));\n }\n\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"UI\/lyricdownloaderwindow.h\"\n#include <QMessageBox>\n#include <QMimeData>\n#include <QFileInfo>\n#include <QDir>\n#include <QMessageBox>\n#include <QAction>\n\nLyricDownloaderWindow::LyricDownloaderWindow(QWidget *parent) : QMainWindow(parent) {\n qRegisterMetaType<LyricStatus>(\"LyricStatus\");\n\n fileList = new QTreeWidget;\n fileList->setIndentation(0);\n fileList->setColumnCount(2);\n fileList->setHeaderLabels({ \"Lyrics?\", \"File\" });\n fileList->header()->setStretchLastSection(true);\n fileList->header()->setSectionResizeMode(0, QHeaderView::ResizeToContents);\n fileList->header()->setSectionResizeMode(1, QHeaderView::ResizeToContents);\n fileList->header()->setStretchLastSection(true);\n\/\/ fileList->model()->setHeaderData(0, Qt::Horizontal, Qt::AlignCenter, Qt::TextAlignmentRole);\n fileList->setSelectionMode(QAbstractItemView::ExtendedSelection);\n fileList->installEventFilter(this);\n\n vbox = new QVBoxLayout;\n bottomHbox = new QHBoxLayout;\n\n addFolderButton = new QPushButton(\"Add folder...\");\n addFilesButton = new QPushButton(\"Add file(s)...\");\n startDownloadButton = new QPushButton(\"Start download\");\n startDownloadButton->setEnabled(false);\n overwriteLyricsCheckBox = new QCheckBox(\"Download and overwrite lyrics for files that already have them\");\n progressBar = new QProgressBar;\n progressBar->setMinimum(0);\n progressBar->setMaximum(10);\n progressBar->setValue(0);\n progressBar->setTextVisible(false);\n\n bottomHbox->addStretch();\n bottomHbox->addWidget(addFolderButton);\n bottomHbox->addWidget(addFilesButton);\n bottomHbox->addWidget(startDownloadButton);\n\n QWidget *central = new QWidget;\n central->setLayout(vbox);\n vbox->addWidget(fileList);\n vbox->addWidget(progressBar);\n vbox->addWidget(overwriteLyricsCheckBox);\n vbox->addLayout(bottomHbox);\n setCentralWidget(central);\n\n connect(addFolderButton, &QPushButton::clicked, [&] {\n QFileDialog fileDialog;\n fileDialog.setFileMode(QFileDialog::Directory);\n fileDialog.setOption(QFileDialog::ShowDirsOnly, true);\n if (fileDialog.exec()) {\n if (fileDialog.selectedFiles().length() > 0)\n startDownloadButton->setEnabled(true);\n \/\/ Only one directory is supposed to be selectable, but just in case...\n for (const QString &dir : fileDialog.selectedFiles()) {\n addFilesRecursively(dir, 15);\n }\n }\n\n if (fileList->topLevelItemCount() > 0)\n startDownloadButton->setEnabled(true);\n });\n\n connect(addFilesButton, &QPushButton::clicked, [&] {\n QFileDialog fileDialog;\n fileDialog.setNameFilter(\"Supported files (*.mp3 *.m4a);;MP3 files (*.mp3);;M4A files (*.m4a)\");\n fileDialog.setFileMode(QFileDialog::ExistingFiles);\n if (fileDialog.exec()) {\n if (fileDialog.selectedFiles().length() > 0)\n startDownloadButton->setEnabled(true);\n for (const QString &file : fileDialog.selectedFiles()) {\n addFile(file);\n }\n }\n\n if (fileList->topLevelItemCount() > 0)\n startDownloadButton->setEnabled(true);\n });\n\n connect(startDownloadButton, &QPushButton::clicked, this, &LyricDownloaderWindow::startButtonClicked);\n\n resize(900, 600);\n\n setAcceptDrops(true);\n}\n\nvoid LyricDownloaderWindow::startButtonClicked() {\n if (workerThread) {\n Q_ASSERT(!workerThread->isRunning());\n delete workerThread;\n workerThread = nullptr;\n }\n if (worker) {\n delete worker;\n worker = nullptr;\n }\n\n \/\/ <index, path> -- this is used because the index into filesToProcess may not equal the index of the fileList.\n \/\/ They only match if every track is NotProcessed, so this would fail if a previous operation had been aborted\n \/\/ and then resumed.\n \/\/ The worker needs to know the index into the fileList (for status updates), so we include it here.\n QList<QPair<int, QString>> filesToProcess;\n for (int i = 0; i < fileList->topLevelItemCount(); i++) {\n auto *item = fileList->topLevelItem(i);\n LyricStatus status = item->data(0, Qt::UserRole).value<LyricStatus>();\n if (status == LyricStatus::NotProcessed)\n filesToProcess.append({ i, item->data(1, Qt::DisplayRole).toString() });\n }\n\n if (filesToProcess.length() == 0) {\n QMessageBox::information(this, \"Done\", \"Nothing to do -- all tracks are already processed!\", QMessageBox::Ok);\n return;\n }\n\n progressBar->setValue(0);\n progressBar->setMaximum(filesToProcess.length());\n progressBar->setTextVisible(true);\n\n worker = new LyricDownloaderWorker(filesToProcess, overwriteLyricsCheckBox->isChecked()); \/\/ Copy the data to the worker\n workerThread = new QThread;\n worker->moveToThread(workerThread);\n\n connect(workerThread, &QThread::started, worker, &LyricDownloaderWorker::process);\n connect(worker, &LyricDownloaderWorker::finished, workerThread, &QThread::quit);\n\n connect(worker, &LyricDownloaderWorker::updateProgress, this, &LyricDownloaderWindow::progressUpdate);\n connect(worker, &LyricDownloaderWorker::finished, this, [this] {\n progressBar->setValue(0);\n progressBar->setTextVisible(false);\n\n disconnect(startDownloadButton, &QPushButton::clicked, 0, 0);\n connect(startDownloadButton, &QPushButton::clicked, this, &LyricDownloaderWindow::startButtonClicked);\n startDownloadButton->setText(\"Start download\");\n startDownloadButton->setEnabled(true);\n }, Qt::QueuedConnection);\n\n fileList->topLevelItem(0)->setBackgroundColor(0, QColor(133, 137, 255)); \/\/ Highlight the current item in blue\n\n workerThread->start();\n\n connect(worker, &LyricDownloaderWorker::aborted, this, [this](int lastProcessedIndex) {\n auto *item = fileList->topLevelItem(lastProcessedIndex + 1);\n if (item)\n item->setBackgroundColor(0, QColor(Qt::red));\n }, Qt::QueuedConnection);\n\n disconnect(startDownloadButton, &QPushButton::clicked, 0, 0);\n connect(startDownloadButton, &QPushButton::clicked, worker, &LyricDownloaderWorker::abort);\n startDownloadButton->setText(\"Stop download\");\n startDownloadButton->setEnabled(true);\n}\n\nvoid LyricDownloaderWindow::progressUpdate(int index, LyricStatus status) {\n Q_ASSERT(index < fileList->topLevelItemCount());\n auto *item = fileList->topLevelItem(index);\n\n item->setData(0, Qt::UserRole, qVariantFromValue(status));\n\n if (status == LyricStatus::DownloadFailed) {\n item->setBackgroundColor(0, QColor(Qt::red));\n item->setData(0, Qt::DisplayRole, \"Error\");\n }\n else if (status == LyricStatus::NoLyricsFound) {\n item->setBackgroundColor(0, QColor(Qt::yellow));\n item->setData(0, Qt::DisplayRole, \"No\");\n }\n else if (status == LyricStatus::HadLyrics || status == LyricStatus::LyricsDownloaded) {\n item->setBackground(0, QColor(Qt::green));\n item->setData(0, Qt::DisplayRole, \"Yes\");\n }\n\n auto *nextItem = fileList->topLevelItem(index + 1);\n if (nextItem) {\n nextItem->setBackgroundColor(0, QColor(133, 137, 255)); \/\/ Highlight the current item in blue\n fileList->scrollToItem(nextItem);\n }\n else\n fileList->scrollToItem(item);\n\n progressBar->setValue(index + 1);\n}\n\nbool LyricDownloaderWindow::eventFilter(QObject *target, QEvent *event) {\n Q_ASSERT(target == fileList);\n if (event->type() == QEvent::KeyPress) {\n QKeyEvent *keyEvent = static_cast<QKeyEvent*>(event);\n if (keyEvent->key() == Qt::Key_Delete) {\n for (const auto &item : fileList->selectedItems()) {\n delete item;\n }\n\n if (fileList->topLevelItemCount() == 0)\n startDownloadButton->setEnabled(false);\n }\n }\n\n return QMainWindow::eventFilter(target, event);\n}\n\nvoid LyricDownloaderWindow::dragEnterEvent(QDragEnterEvent *e) {\n if (workerThread && workerThread->isRunning())\n return;\n\n \/\/ If at least one of the files dragged inside is an MP3 file, an M4A file, or a folder, accept the drop.\n \/\/ If not, deny it.\n \/\/ This means we might get a folder full of JPEG files, but we can't recursively check everything here,\n \/\/ or the UI will be laggy like all hell when big folders are dragged.\n \/\/ Careful checking will need to happen on drop.\n for (const QUrl &url : e->mimeData()->urls()) {\n QString local = url.toLocalFile();\n QFileInfo fileInfo(local);\n if (fileInfo.isDir() || fileInfo.suffix() == \"mp3\" || fileInfo.suffix() == \"m4a\") {\n e->acceptProposedAction();\n return;\n }\n }\n}\n\nvoid LyricDownloaderWindow::dropEvent(QDropEvent *e) {\n QStringList types = { \"mp3\", \"m4a\" };\n for (const QUrl &url : e->mimeData()->urls()) {\n QString local = url.toLocalFile();\n QFileInfo fileInfo(local);\n if (fileInfo.suffix() == \"mp3\" || fileInfo.suffix() == \"m4a\") {\n addFile(local);\n }\n else if (fileInfo.isDir()) {\n addFilesRecursively(local, 15);\n }\n else\n continue;\n }\n\n if (fileList->topLevelItemCount() > 0)\n startDownloadButton->setEnabled(true);\n}\n\nvoid LyricDownloaderWindow::addFile(const QString &file) {\n auto *item = new QTreeWidgetItem({\"?\", file});\n item->setData(0, Qt::UserRole, qVariantFromValue(LyricStatus::NotProcessed));\n fileList->addTopLevelItem(item);\n}\n\nvoid LyricDownloaderWindow::addFilesRecursively(const QString &sDir, int max_depth) {\n QDir dir(sDir);\n QFileInfoList list = dir.entryInfoList(dir.nameFilters(), QDir::AllEntries | QDir::NoDotAndDotDot);\n\n for (QFileInfo info : list) {\n\/\/ if (Application::shouldTerminate)\n\/\/ return {};\n QString sFilePath = info.filePath();\n QString absPath = info.absoluteFilePath();\n\n if (absPath.endsWith(\".mp3\", Qt::CaseInsensitive)|| absPath.endsWith(\".m4a\", Qt::CaseInsensitive)) {\n addFile(absPath);\n }\n\n if (max_depth > 0 && info.isDir() && !info.isSymLink()) {\n addFilesRecursively(sFilePath, max_depth - 1);\n }\n }\n}\n\n<commit_msg>Disable buttons and checkboxes when the downloader is running<commit_after>#include \"UI\/lyricdownloaderwindow.h\"\n#include <QMessageBox>\n#include <QMimeData>\n#include <QFileInfo>\n#include <QDir>\n#include <QMessageBox>\n#include <QAction>\n\nLyricDownloaderWindow::LyricDownloaderWindow(QWidget *parent) : QMainWindow(parent) {\n qRegisterMetaType<LyricStatus>(\"LyricStatus\");\n\n fileList = new QTreeWidget;\n fileList->setIndentation(0);\n fileList->setColumnCount(2);\n fileList->setHeaderLabels({ \"Lyrics?\", \"File\" });\n fileList->header()->setStretchLastSection(true);\n fileList->header()->setSectionResizeMode(0, QHeaderView::ResizeToContents);\n fileList->header()->setSectionResizeMode(1, QHeaderView::ResizeToContents);\n fileList->header()->setStretchLastSection(true);\n\/\/ fileList->model()->setHeaderData(0, Qt::Horizontal, Qt::AlignCenter, Qt::TextAlignmentRole);\n fileList->setSelectionMode(QAbstractItemView::ExtendedSelection);\n fileList->installEventFilter(this);\n\n vbox = new QVBoxLayout;\n bottomHbox = new QHBoxLayout;\n\n addFolderButton = new QPushButton(\"Add folder...\");\n addFilesButton = new QPushButton(\"Add file(s)...\");\n startDownloadButton = new QPushButton(\"Start download\");\n startDownloadButton->setEnabled(false);\n overwriteLyricsCheckBox = new QCheckBox(\"Download and overwrite lyrics for files that already have them\");\n progressBar = new QProgressBar;\n progressBar->setMinimum(0);\n progressBar->setMaximum(10);\n progressBar->setValue(0);\n progressBar->setTextVisible(false);\n\n bottomHbox->addStretch();\n bottomHbox->addWidget(addFolderButton);\n bottomHbox->addWidget(addFilesButton);\n bottomHbox->addWidget(startDownloadButton);\n\n QWidget *central = new QWidget;\n central->setLayout(vbox);\n vbox->addWidget(fileList);\n vbox->addWidget(progressBar);\n vbox->addWidget(overwriteLyricsCheckBox);\n vbox->addLayout(bottomHbox);\n setCentralWidget(central);\n\n connect(addFolderButton, &QPushButton::clicked, [&] {\n QFileDialog fileDialog;\n fileDialog.setFileMode(QFileDialog::Directory);\n fileDialog.setOption(QFileDialog::ShowDirsOnly, true);\n if (fileDialog.exec()) {\n if (fileDialog.selectedFiles().length() > 0)\n startDownloadButton->setEnabled(true);\n \/\/ Only one directory is supposed to be selectable, but just in case...\n for (const QString &dir : fileDialog.selectedFiles()) {\n addFilesRecursively(dir, 15);\n }\n }\n\n if (fileList->topLevelItemCount() > 0)\n startDownloadButton->setEnabled(true);\n });\n\n connect(addFilesButton, &QPushButton::clicked, [&] {\n QFileDialog fileDialog;\n fileDialog.setNameFilter(\"Supported files (*.mp3 *.m4a);;MP3 files (*.mp3);;M4A files (*.m4a)\");\n fileDialog.setFileMode(QFileDialog::ExistingFiles);\n if (fileDialog.exec()) {\n if (fileDialog.selectedFiles().length() > 0)\n startDownloadButton->setEnabled(true);\n for (const QString &file : fileDialog.selectedFiles()) {\n addFile(file);\n }\n }\n\n if (fileList->topLevelItemCount() > 0)\n startDownloadButton->setEnabled(true);\n });\n\n connect(startDownloadButton, &QPushButton::clicked, this, &LyricDownloaderWindow::startButtonClicked);\n\n resize(900, 600);\n\n setAcceptDrops(true);\n}\n\nvoid LyricDownloaderWindow::startButtonClicked() {\n if (workerThread) {\n Q_ASSERT(!workerThread->isRunning());\n delete workerThread;\n workerThread = nullptr;\n }\n if (worker) {\n delete worker;\n worker = nullptr;\n }\n\n \/\/ <index, path> -- this is used because the index into filesToProcess may not equal the index of the fileList.\n \/\/ They only match if every track is NotProcessed, so this would fail if a previous operation had been aborted\n \/\/ and then resumed.\n \/\/ The worker needs to know the index into the fileList (for status updates), so we include it here.\n QList<QPair<int, QString>> filesToProcess;\n for (int i = 0; i < fileList->topLevelItemCount(); i++) {\n auto *item = fileList->topLevelItem(i);\n LyricStatus status = item->data(0, Qt::UserRole).value<LyricStatus>();\n if (status == LyricStatus::NotProcessed)\n filesToProcess.append({ i, item->data(1, Qt::DisplayRole).toString() });\n }\n\n if (filesToProcess.length() == 0) {\n QMessageBox::information(this, \"Done\", \"Nothing to do -- all tracks are already processed!\", QMessageBox::Ok);\n return;\n }\n\n progressBar->setValue(0);\n progressBar->setMaximum(filesToProcess.length());\n progressBar->setTextVisible(true);\n\n worker = new LyricDownloaderWorker(filesToProcess, overwriteLyricsCheckBox->isChecked()); \/\/ Copy the data to the worker\n workerThread = new QThread;\n worker->moveToThread(workerThread);\n\n connect(workerThread, &QThread::started, worker, &LyricDownloaderWorker::process);\n connect(worker, &LyricDownloaderWorker::finished, workerThread, &QThread::quit);\n\n connect(worker, &LyricDownloaderWorker::updateProgress, this, &LyricDownloaderWindow::progressUpdate);\n connect(worker, &LyricDownloaderWorker::finished, this, [this] {\n progressBar->setValue(0);\n progressBar->setTextVisible(false);\n\n disconnect(startDownloadButton, &QPushButton::clicked, 0, 0);\n connect(startDownloadButton, &QPushButton::clicked, this, &LyricDownloaderWindow::startButtonClicked);\n startDownloadButton->setText(\"Start download\");\n startDownloadButton->setEnabled(true);\n\n addFilesButton->setEnabled(true);\n addFolderButton->setEnabled(true);\n overwriteLyricsCheckBox->setEnabled(true);\n }, Qt::QueuedConnection);\n\n fileList->topLevelItem(0)->setBackgroundColor(0, QColor(133, 137, 255)); \/\/ Highlight the current item in blue\n\n workerThread->start();\n\n connect(worker, &LyricDownloaderWorker::aborted, this, [this](int lastProcessedIndex) {\n auto *item = fileList->topLevelItem(lastProcessedIndex + 1);\n if (item)\n item->setBackgroundColor(0, QColor(Qt::red));\n }, Qt::QueuedConnection);\n\n disconnect(startDownloadButton, &QPushButton::clicked, 0, 0);\n connect(startDownloadButton, &QPushButton::clicked, worker, &LyricDownloaderWorker::abort);\n startDownloadButton->setText(\"Stop download\");\n startDownloadButton->setEnabled(true);\n\n addFilesButton->setEnabled(false);\n addFolderButton->setEnabled(false);\n overwriteLyricsCheckBox->setEnabled(false);\n}\n\nvoid LyricDownloaderWindow::progressUpdate(int index, LyricStatus status) {\n Q_ASSERT(index < fileList->topLevelItemCount());\n auto *item = fileList->topLevelItem(index);\n\n item->setData(0, Qt::UserRole, qVariantFromValue(status));\n\n if (status == LyricStatus::DownloadFailed) {\n item->setBackgroundColor(0, QColor(Qt::red));\n item->setData(0, Qt::DisplayRole, \"Error\");\n }\n else if (status == LyricStatus::NoLyricsFound) {\n item->setBackgroundColor(0, QColor(Qt::yellow));\n item->setData(0, Qt::DisplayRole, \"No\");\n }\n else if (status == LyricStatus::HadLyrics || status == LyricStatus::LyricsDownloaded) {\n item->setBackground(0, QColor(Qt::green));\n item->setData(0, Qt::DisplayRole, \"Yes\");\n }\n\n auto *nextItem = fileList->topLevelItem(index + 1);\n if (nextItem) {\n nextItem->setBackgroundColor(0, QColor(133, 137, 255)); \/\/ Highlight the current item in blue\n fileList->scrollToItem(nextItem);\n }\n else\n fileList->scrollToItem(item);\n\n progressBar->setValue(index + 1);\n}\n\nbool LyricDownloaderWindow::eventFilter(QObject *target, QEvent *event) {\n Q_ASSERT(target == fileList);\n if (event->type() == QEvent::KeyPress) {\n QKeyEvent *keyEvent = static_cast<QKeyEvent*>(event);\n if (keyEvent->key() == Qt::Key_Delete && (workerThread == nullptr || !workerThread->isRunning())) {\n for (const auto &item : fileList->selectedItems()) {\n delete item;\n }\n\n if (fileList->topLevelItemCount() == 0)\n startDownloadButton->setEnabled(false);\n }\n }\n\n return QMainWindow::eventFilter(target, event);\n}\n\nvoid LyricDownloaderWindow::dragEnterEvent(QDragEnterEvent *e) {\n if (workerThread && workerThread->isRunning())\n return;\n\n \/\/ If at least one of the files dragged inside is an MP3 file, an M4A file, or a folder, accept the drop.\n \/\/ If not, deny it.\n \/\/ This means we might get a folder full of JPEG files, but we can't recursively check everything here,\n \/\/ or the UI will be laggy like all hell when big folders are dragged.\n \/\/ Careful checking will need to happen on drop.\n for (const QUrl &url : e->mimeData()->urls()) {\n QString local = url.toLocalFile();\n QFileInfo fileInfo(local);\n if (fileInfo.isDir() || fileInfo.suffix() == \"mp3\" || fileInfo.suffix() == \"m4a\") {\n e->acceptProposedAction();\n return;\n }\n }\n}\n\nvoid LyricDownloaderWindow::dropEvent(QDropEvent *e) {\n QStringList types = { \"mp3\", \"m4a\" };\n for (const QUrl &url : e->mimeData()->urls()) {\n QString local = url.toLocalFile();\n QFileInfo fileInfo(local);\n if (fileInfo.suffix() == \"mp3\" || fileInfo.suffix() == \"m4a\") {\n addFile(local);\n }\n else if (fileInfo.isDir()) {\n addFilesRecursively(local, 15);\n }\n else\n continue;\n }\n\n if (fileList->topLevelItemCount() > 0)\n startDownloadButton->setEnabled(true);\n}\n\nvoid LyricDownloaderWindow::addFile(const QString &file) {\n auto *item = new QTreeWidgetItem({\"?\", file});\n item->setData(0, Qt::UserRole, qVariantFromValue(LyricStatus::NotProcessed));\n fileList->addTopLevelItem(item);\n}\n\nvoid LyricDownloaderWindow::addFilesRecursively(const QString &sDir, int max_depth) {\n QDir dir(sDir);\n QFileInfoList list = dir.entryInfoList(dir.nameFilters(), QDir::AllEntries | QDir::NoDotAndDotDot);\n\n for (QFileInfo info : list) {\n\/\/ if (Application::shouldTerminate)\n\/\/ return {};\n QString sFilePath = info.filePath();\n QString absPath = info.absoluteFilePath();\n\n if (absPath.endsWith(\".mp3\", Qt::CaseInsensitive)|| absPath.endsWith(\".m4a\", Qt::CaseInsensitive)) {\n addFile(absPath);\n }\n\n if (max_depth > 0 && info.isDir() && !info.isSymLink()) {\n addFilesRecursively(sFilePath, max_depth - 1);\n }\n }\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/* Copyright (C) 2012-2017 IBM Corp.\n * This program is Licensed under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License. See accompanying LICENSE file.\n *\/\n\n\/* Test_Permutations.cpp - Applying plaintext permutation to encrypted vector\n *\/\n#include <NTL\/ZZ.h>\nNTL_CLIENT\n\n#include \"NumbTh.h\"\n#include \"timing.h\"\n#include \"permutations.h\"\n#include \"EncryptedArray.h\"\n\nstatic bool noPrint = false;\n\nvoid testCtxt(long m, long p, long widthBound=0, long L=0, long r=1);\n\nvoid usage(char *prog) \n{\n cout << \"Usage: \"<<prog<<\" [test=? [optional parameters...]]\\n\";\n cout << \" optional parameters have the form 'attr1=val1 attr2=val2 ...'\\n\";\n cout << \" e.g, 'test=1 m=108 p=2 r=1\\n\";\n cout << \" test is either 0 (plaintext) or 1 (ciphertext)[default=1]\\n\\n\";\n cout << \"test=0, permuting plaintext hypercubes (dimension upto 4):\\n\";\n cout << \" ord1,ord2,ord3,ord4 size of dimensions 1..4 [default ord1=30, ord2,3,4=0]\\n\";\n cout << \" good1,good2,good3,good4 native rotation flags (0\/1) [default=1]\\n\";\n cout << \" depth bounds the depth of permutation network [default=5]\\n\";\n cout << \"\\ntest=1, permuting ciphertext slots:\\n\";\n cout << \" m is the cyclotomic field [default=4369]\\n\";\n cout << \" p,r define the plaintext space p^r [default p=2,r=1]\\n\";\n cout << \" depth bounds the depth of permutation network [default=5]\\n\";\n cout << \" L is number of levels in chain [default=depth]\\n\\n\";\n cout << \"dry=1 for dry run [default=0]\\n\";\n exit(0);\n}\n\nvoid testCube(Vec<GenDescriptor>& vec, long widthBound)\n{\n GeneratorTrees trees;\n long cost = trees.buildOptimalTrees(vec, widthBound);\n if (!noPrint) {\n cout << \"@TestCube: trees=\" << trees << endl;\n cout << \" cost =\" << cost << endl;\n }\n Vec<long> dims;\n trees.getCubeDims(dims);\n CubeSignature sig(dims);\n\n for (long cnt=0; cnt<3; cnt++) {\n Permut pi;\n randomPerm(pi, trees.getSize());\n\n PermNetwork net;\n net.buildNetwork(pi, trees);\n\n HyperCube<long> cube1(sig), cube2(sig);\n for (long i=0; i<cube1.getSize(); i++) cube1[i] = i;\n HyperCube<long> cube3 = cube1;\n applyPermToVec(cube2.getData(), cube1.getData(), pi); \/\/ direct application\n net.applyToCube(cube3); \/\/ applying permutation netwrok\n if (cube2==cube3) cout << \"GOOD\\n\";\n else {\n cout << \"BAD\\n\";\n if (cube1.getSize()<100) {\n\tcout << \"in=\"<<cube1.getData() << endl;\n\tcout << \"out1=\"<<cube2.getData()<<\", out2=\"\n\t << cube3.getData()<<endl<<endl;\n }\n }\n }\n}\n\nvoid testCtxt(long m, long p, long widthBound, long L, long r)\n{\n if (!noPrint)\n cout << \"@testCtxt(m=\"<<m<<\",p=\"<<p<<\",depth=\"<<widthBound<< \",r=\"<<r<<\")\";\n\n FHEcontext context(m,p,r);\n EncryptedArray ea(context); \/\/ Use G(X)=X for this ea object\n\n \/\/ Some arbitrary initial plaintext array\n vector<long> in(ea.size());\n for (long i=0; i<ea.size(); i++) in[i] = i % p;\n\n \/\/ Setup generator-descriptors for the PAlgebra generators\n Vec<GenDescriptor> vec(INIT_SIZE, ea.dimension());\n for (long i=0; i<ea.dimension(); i++)\n vec[i] = GenDescriptor(\/*order=*\/ea.sizeOfDimension(i),\n\t\t\t \/*good=*\/ ea.nativeDimension(i), \/*genIdx=*\/i);\n\n \/\/ Some default for the width-bound, if not provided\n if (widthBound<=0) widthBound = 1+log2((double)ea.size());\n\n \/\/ Get the generator-tree structures and the corresponding hypercube\n GeneratorTrees trees;\n long cost = trees.buildOptimalTrees(vec, widthBound);\n if (!noPrint) {\n cout << \": trees=\" << trees << endl;\n cout << \" cost =\" << cost << endl;\n }\n \/\/ Vec<long> dims;\n \/\/ trees.getCubeDims(dims);\n \/\/ CubeSignature sig(dims);\n\n \/\/ 1\/2 prime per level should be more or less enough, here we use 1 per layer\n if (L<=0) L = 1+trees.numLayers();\n buildModChain(context, \/*nLevels=*\/L, \/*nDigits=*\/3);\n if (!noPrint) cout << \"**Using \"<<L<<\" primes (of which \"\n\t\t << context.ctxtPrimes.card() << \" are Ctxt-primes)\\n\";\n\n \/\/ Generate a sk\/pk pair\n FHESecKey secretKey(context);\n const FHEPubKey& publicKey = secretKey;\n secretKey.GenSecKey(64); \/\/ A Hamming-weight-64 secret key\n Ctxt ctxt(publicKey);\n\n for (long cnt=0; cnt<3; cnt++) {\n resetAllTimers();\n \/\/ Choose a random permutation\n Permut pi;\n randomPerm(pi, trees.getSize());\n\n \/\/ Build a permutation network for pi\n PermNetwork net;\n net.buildNetwork(pi, trees);\n\n \/\/ make sure we have the key-switching matrices needed for this network\n addMatrices4Network(secretKey, net);\n\n \/\/ Apply the permutation pi to the plaintext\n vector<long> out1(ea.size());\n vector<long> out2(ea.size());\n applyPermToVec(out1, in, pi); \/\/ direct application\n\n \/\/ Encrypt plaintext array, then apply permutation network to ciphertext\n ea.encrypt(ctxt, publicKey, in);\n if (!noPrint)\n cout << \" ** applying permutation network to ciphertext... \" << flush;\n double t = GetTime();\n net.applyToCtxt(ctxt, ea); \/\/ applying permutation netwrok\n t = GetTime() -t;\n if (!noPrint)\n cout << \"done in \" << t << \" seconds\" << endl;\n ea.decrypt(ctxt, secretKey, out2);\n\n if (out1==out2) cout << \"GOOD\\n\";\n else {\n cout << \"************ BAD\\n\";\n }\n \/\/ printAllTimers();\n }\n}\n\n\n\/* m = 31, p = 2, phi(m) = 30\n ord(p)=5\n generator 6 has order (== Z_m^*) of 6\n T = [1 6 5 30 25 26 ]\n\n m = 61, p = 3, phi(m) = 60\n ord(p)=10\n generator 13 has order (== Z_m^*) of 3\n generator 2 has order (!= Z_m^*) of 2\n T = [1 2 13 26 47 33 ]\n\n m = 683, p = 2, phi(m) = 682\n ord(p)=22\n generator 3 has order (== Z_m^*) of 31\n\n m = 47127, p = 2, phi(m) = 30008\n ord(p)=22\n generator 5 has order (== Z_m^*) of 682\n generator 13661 has order (== Z_m^*) of 2\n*\/\n\nint main(int argc, char *argv[])\n{\n argmap_t argmap;\n argmap[\"test\"] = \"1\";\n argmap[\"m\"] = \"4369\";\n argmap[\"p\"] = \"2\";\n argmap[\"r\"] = \"1\";\n argmap[\"depth\"] = \"5\";\n argmap[\"L\"] = \"0\";\n argmap[\"ord1\"] = \"30\";\n argmap[\"ord2\"] = \"0\";\n argmap[\"ord3\"] = \"0\";\n argmap[\"ord4\"] = \"0\";\n argmap[\"good1\"] = \"1\";\n argmap[\"good2\"] = \"1\";\n argmap[\"good3\"] = \"1\";\n argmap[\"good4\"] = \"1\";\n argmap[\"dry\"] = \"1\";\n argmap[\"noPrint\"] = \"0\";\n\n \/\/ get parameters from the command line\n\n if (!parseArgs(argc, argv, argmap)) usage(argv[0]);\n\n long test = atoi(argmap[\"test\"]);\n long p = atoi(argmap[\"p\"]);\n long r = atoi(argmap[\"r\"]);\n long m = atoi(argmap[\"m\"]);\n long depth = atoi(argmap[\"depth\"]);\n long L = atoi(argmap[\"L\"]);\n\n long ord1 = atoi(argmap[\"ord1\"]);\n long ord2 = atoi(argmap[\"ord2\"]);\n long ord3 = atoi(argmap[\"ord3\"]);\n long ord4 = atoi(argmap[\"ord4\"]);\n long good1 = atoi(argmap[\"good1\"]);\n long good2 = atoi(argmap[\"good2\"]);\n long good3 = atoi(argmap[\"good3\"]);\n long good4 = atoi(argmap[\"good4\"]);\n\n bool dry = atoi(argmap[\"dry\"]);\n noPrint = atoi(argmap[\"noPrint\"]);\n\n setDryRun(dry);\n if (test==0) {\n Vec<GenDescriptor> vec;\n long nGens;\n if (ord2<=1) nGens=1;\n else if (ord3<=1) nGens=2;\n else if (ord4<=1) nGens=3;\n else nGens=4;\n vec.SetLength(nGens);\n\n switch (nGens) {\n case 4: vec[3] = GenDescriptor(ord4, good4, \/*genIdx=*\/3);\n case 3: vec[2] = GenDescriptor(ord3, good3, \/*genIdx=*\/2);\n case 2: vec[1] = GenDescriptor(ord2, good2, \/*genIdx=*\/1);\n default: vec[0] = GenDescriptor(ord1, good1, \/*genIdx=*\/0);\n }\n cout << \"***Testing \";\n if (isDryRun()) cout << \"(dry run) \";\n for (long i=0; i<vec.length(); i++)\n cout << \"(\"<<vec[i].order<<\",\"<<vec[i].good<<\")\";\n cout << \", depth=\"<<depth<<\"\\n\";\n testCube(vec, depth);\n }\n else {\n setTimersOn();\n cout << \"***Testing m=\"<<m<<\", p=\"<<p<<\", depth=\"<<depth<< endl;\n testCtxt(m,p,depth,L,r);\n }\n}\n\n\n\n#if 0\n cout << \"***Testing m=31, p=2, width=3\\n\"; \/\/ (6 good)\n testCtxt(\/*m=*\/31, \/*p=*\/2, \/*width=*\/3);\n\n cout << \"\\n***Testing m=61, p=3, width=3\\n\"; \/\/ (3 good), (2, bad)\n testCtxt(\/*m=*\/61, \/*p=*\/3, \/*width=*\/3);\n\n cout << \"\\n***Testing m=683, p=2, width=5\\n\"; \/\/ (31, good)\n testCtxt(\/*m=*\/683, \/*p=*\/2, \/*width=*\/5);\n\n \/\/ cout << \"\\n***Testing m=47127, p=2, width=11\\n\"; \/\/ (682,good),(2,good)\n \/\/ testCtxt(\/*m=*\/47127, \/*p=*\/2, \/*width=*\/11);\n\n \/\/ Test 1: a single good small prime-order generator (3)\n {\n Vec<GenDescriptor> vec(INIT_SIZE, 1);\n vec[0] = GenDescriptor(\/*order=*\/3, \/*good=*\/true, \/*genIdx=*\/0);\n cout << \"***Testing (3,good), width=1\\n\";\n testCube(vec, \/*width=*\/1);\n }\n\n \/\/ Test 2: a single bad larger prime-order generator (31)\n {\n Vec<GenDescriptor> vec(INIT_SIZE, 1);\n vec[0] = GenDescriptor(\/*order=*\/31, \/*good=*\/false, \/*genIdx=*\/0);\n cout << \"\\n***Testing (31,bad), width=5\\n\";\n testCube(vec, \/*width=*\/5);\n }\n\n \/\/ Test 3: two generators with small prime orders (2,3), both bad\n {\n Vec<GenDescriptor> vec(INIT_SIZE, 2);\n vec[0] = GenDescriptor(\/*order=*\/2, \/*good=*\/false, \/*genIdx=*\/0);\n vec[1] = GenDescriptor(\/*order=*\/3, \/*good=*\/false, \/*genIdx=*\/1);\n cout << \"\\n***Testing [(2,bad),(3,bad)], width=3\\n\";\n testCube(vec, \/*width=*\/3);\n }\n\n \/\/ Test 4: two generators with small prime orders (2,3), one good\n {\n Vec<GenDescriptor> vec(INIT_SIZE, 2);\n vec[0] = GenDescriptor(\/*order=*\/3, \/*good=*\/true, \/*genIdx=*\/0);\n vec[1] = GenDescriptor(\/*order=*\/2, \/*good=*\/false, \/*genIdx=*\/1);\n cout << \"\\n***Testing [(3,good),(2,bad)], width=3\\n\";\n testCube(vec, \/*width=*\/3);\n }\n\n \/\/ Test 5: a single good composite-order generator (6)\n {\n Vec<GenDescriptor> vec(INIT_SIZE, 1);\n vec[0] = GenDescriptor(\/*order=*\/6, \/*good=*\/true, \/*genIdx=*\/0);\n cout << \"\\n***Testing (6,good), width=3\\n\";\n testCube(vec, \/*width=*\/3);\n }\n\n \/\/ Test 6: (6,good),(2,bad)\n {\n Vec<GenDescriptor> vec(INIT_SIZE, 2);\n vec[0] = GenDescriptor(\/*order=*\/6,\/*good=*\/true, \/*genIdx=*\/0);\n vec[1] = GenDescriptor(\/*order=*\/ 2, \/*good=*\/false,\/*genIdx=*\/1);\n cout << \"\\n**Testing [(6,good),(2,bad)], width=5\\n\";\n testCube(vec, \/*width=*\/5);\n }\n\n \/\/ Test 7: the \"general case\", (682,good),(2,bad)\n {\n Vec<GenDescriptor> vec(INIT_SIZE, 2);\n vec[0] = GenDescriptor(\/*order=*\/682,\/*good=*\/true, \/*genIdx=*\/0);\n vec[1] = GenDescriptor(\/*order=*\/ 2, \/*good=*\/false,\/*genIdx=*\/1);\n cout << \"\\n**Testing [(682,good),(2,bad)], width=11\\n\";\n testCube(vec, \/*width=*\/11);\n }\n#endif\n<commit_msg>dry=0 by default in Test_Permutations<commit_after>\/* Copyright (C) 2012-2017 IBM Corp.\n * This program is Licensed under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License. See accompanying LICENSE file.\n *\/\n\n\/* Test_Permutations.cpp - Applying plaintext permutation to encrypted vector\n *\/\n#include <NTL\/ZZ.h>\nNTL_CLIENT\n\n#include \"NumbTh.h\"\n#include \"timing.h\"\n#include \"permutations.h\"\n#include \"EncryptedArray.h\"\n\nstatic bool noPrint = false;\n\nvoid testCtxt(long m, long p, long widthBound=0, long L=0, long r=1);\n\nvoid usage(char *prog) \n{\n cout << \"Usage: \"<<prog<<\" [test=? [optional parameters...]]\\n\";\n cout << \" optional parameters have the form 'attr1=val1 attr2=val2 ...'\\n\";\n cout << \" e.g, 'test=1 m=108 p=2 r=1\\n\";\n cout << \" test is either 0 (plaintext) or 1 (ciphertext)[default=1]\\n\\n\";\n cout << \"test=0, permuting plaintext hypercubes (dimension upto 4):\\n\";\n cout << \" ord1,ord2,ord3,ord4 size of dimensions 1..4 [default ord1=30, ord2,3,4=0]\\n\";\n cout << \" good1,good2,good3,good4 native rotation flags (0\/1) [default=1]\\n\";\n cout << \" depth bounds the depth of permutation network [default=5]\\n\";\n cout << \"\\ntest=1, permuting ciphertext slots:\\n\";\n cout << \" m is the cyclotomic field [default=4369]\\n\";\n cout << \" p,r define the plaintext space p^r [default p=2,r=1]\\n\";\n cout << \" depth bounds the depth of permutation network [default=5]\\n\";\n cout << \" L is number of levels in chain [default=depth]\\n\\n\";\n cout << \"dry=1 for dry run [default=0]\\n\";\n exit(0);\n}\n\nvoid testCube(Vec<GenDescriptor>& vec, long widthBound)\n{\n GeneratorTrees trees;\n long cost = trees.buildOptimalTrees(vec, widthBound);\n if (!noPrint) {\n cout << \"@TestCube: trees=\" << trees << endl;\n cout << \" cost =\" << cost << endl;\n }\n Vec<long> dims;\n trees.getCubeDims(dims);\n CubeSignature sig(dims);\n\n for (long cnt=0; cnt<3; cnt++) {\n Permut pi;\n randomPerm(pi, trees.getSize());\n\n PermNetwork net;\n net.buildNetwork(pi, trees);\n\n HyperCube<long> cube1(sig), cube2(sig);\n for (long i=0; i<cube1.getSize(); i++) cube1[i] = i;\n HyperCube<long> cube3 = cube1;\n applyPermToVec(cube2.getData(), cube1.getData(), pi); \/\/ direct application\n net.applyToCube(cube3); \/\/ applying permutation netwrok\n if (cube2==cube3) cout << \"GOOD\\n\";\n else {\n cout << \"BAD\\n\";\n if (cube1.getSize()<100) {\n\tcout << \"in=\"<<cube1.getData() << endl;\n\tcout << \"out1=\"<<cube2.getData()<<\", out2=\"\n\t << cube3.getData()<<endl<<endl;\n }\n }\n }\n}\n\nvoid testCtxt(long m, long p, long widthBound, long L, long r)\n{\n if (!noPrint)\n cout << \"@testCtxt(m=\"<<m<<\",p=\"<<p<<\",depth=\"<<widthBound<< \",r=\"<<r<<\")\";\n\n FHEcontext context(m,p,r);\n EncryptedArray ea(context); \/\/ Use G(X)=X for this ea object\n\n \/\/ Some arbitrary initial plaintext array\n vector<long> in(ea.size());\n for (long i=0; i<ea.size(); i++) in[i] = i % p;\n\n \/\/ Setup generator-descriptors for the PAlgebra generators\n Vec<GenDescriptor> vec(INIT_SIZE, ea.dimension());\n for (long i=0; i<ea.dimension(); i++)\n vec[i] = GenDescriptor(\/*order=*\/ea.sizeOfDimension(i),\n\t\t\t \/*good=*\/ ea.nativeDimension(i), \/*genIdx=*\/i);\n\n \/\/ Some default for the width-bound, if not provided\n if (widthBound<=0) widthBound = 1+log2((double)ea.size());\n\n \/\/ Get the generator-tree structures and the corresponding hypercube\n GeneratorTrees trees;\n long cost = trees.buildOptimalTrees(vec, widthBound);\n if (!noPrint) {\n context.zMStar.printout();\n cout << \": trees=\" << trees << endl;\n cout << \" cost =\" << cost << endl;\n }\n \/\/ Vec<long> dims;\n \/\/ trees.getCubeDims(dims);\n \/\/ CubeSignature sig(dims);\n\n \/\/ 1\/2 prime per level should be more or less enough, here we use 1 per layer\n if (L<=0) L = 1+trees.numLayers();\n buildModChain(context, \/*nLevels=*\/L, \/*nDigits=*\/3);\n if (!noPrint) cout << \"**Using \"<<L<<\" primes (of which \"\n\t\t << context.ctxtPrimes.card() << \" are Ctxt-primes)\\n\";\n\n \/\/ Generate a sk\/pk pair\n FHESecKey secretKey(context);\n const FHEPubKey& publicKey = secretKey;\n secretKey.GenSecKey(64); \/\/ A Hamming-weight-64 secret key\n Ctxt ctxt(publicKey);\n\n for (long cnt=0; cnt<3; cnt++) {\n resetAllTimers();\n \/\/ Choose a random permutation\n Permut pi;\n randomPerm(pi, trees.getSize());\n\n \/\/ Build a permutation network for pi\n PermNetwork net;\n net.buildNetwork(pi, trees);\n\n \/\/ make sure we have the key-switching matrices needed for this network\n addMatrices4Network(secretKey, net);\n\n \/\/ Apply the permutation pi to the plaintext\n vector<long> out1(ea.size());\n vector<long> out2(ea.size());\n applyPermToVec(out1, in, pi); \/\/ direct application\n\n \/\/ Encrypt plaintext array, then apply permutation network to ciphertext\n ea.encrypt(ctxt, publicKey, in);\n if (!noPrint)\n cout << \" ** applying permutation network to ciphertext... \" << flush;\n double t = GetTime();\n net.applyToCtxt(ctxt, ea); \/\/ applying permutation netwrok\n t = GetTime() -t;\n if (!noPrint)\n cout << \"done in \" << t << \" seconds\" << endl;\n ea.decrypt(ctxt, secretKey, out2);\n\n if (out1==out2) cout << \"GOOD\\n\";\n else {\n cout << \"************ BAD\\n\";\n }\n \/\/ printAllTimers();\n }\n}\n\n\n\/* m = 31, p = 2, phi(m) = 30\n ord(p)=5\n generator 6 has order (== Z_m^*) of 6\n T = [1 6 5 30 25 26 ]\n\n m = 61, p = 3, phi(m) = 60\n ord(p)=10\n generator 13 has order (== Z_m^*) of 3\n generator 2 has order (!= Z_m^*) of 2\n T = [1 2 13 26 47 33 ]\n\n m = 683, p = 2, phi(m) = 682\n ord(p)=22\n generator 3 has order (== Z_m^*) of 31\n\n m = 47127, p = 2, phi(m) = 30008\n ord(p)=22\n generator 5 has order (== Z_m^*) of 682\n generator 13661 has order (== Z_m^*) of 2\n*\/\n\nint main(int argc, char *argv[])\n{\n argmap_t argmap;\n argmap[\"test\"] = \"1\";\n argmap[\"m\"] = \"4369\";\n argmap[\"p\"] = \"2\";\n argmap[\"r\"] = \"1\";\n argmap[\"depth\"] = \"5\";\n argmap[\"L\"] = \"0\";\n argmap[\"ord1\"] = \"30\";\n argmap[\"ord2\"] = \"0\";\n argmap[\"ord3\"] = \"0\";\n argmap[\"ord4\"] = \"0\";\n argmap[\"good1\"] = \"1\";\n argmap[\"good2\"] = \"1\";\n argmap[\"good3\"] = \"1\";\n argmap[\"good4\"] = \"1\";\n argmap[\"dry\"] = \"0\";\n argmap[\"noPrint\"] = \"0\";\n\n \/\/ get parameters from the command line\n\n if (!parseArgs(argc, argv, argmap)) usage(argv[0]);\n\n long test = atoi(argmap[\"test\"]);\n long p = atoi(argmap[\"p\"]);\n long r = atoi(argmap[\"r\"]);\n long m = atoi(argmap[\"m\"]);\n long depth = atoi(argmap[\"depth\"]);\n long L = atoi(argmap[\"L\"]);\n\n long ord1 = atoi(argmap[\"ord1\"]);\n long ord2 = atoi(argmap[\"ord2\"]);\n long ord3 = atoi(argmap[\"ord3\"]);\n long ord4 = atoi(argmap[\"ord4\"]);\n long good1 = atoi(argmap[\"good1\"]);\n long good2 = atoi(argmap[\"good2\"]);\n long good3 = atoi(argmap[\"good3\"]);\n long good4 = atoi(argmap[\"good4\"]);\n\n bool dry = atoi(argmap[\"dry\"]);\n noPrint = atoi(argmap[\"noPrint\"]);\n\n setDryRun(dry);\n if (test==0 || dry!=0) {\n Vec<GenDescriptor> vec;\n long nGens;\n if (ord2<=1) nGens=1;\n else if (ord3<=1) nGens=2;\n else if (ord4<=1) nGens=3;\n else nGens=4;\n vec.SetLength(nGens);\n\n switch (nGens) {\n case 4: vec[3] = GenDescriptor(ord4, good4, \/*genIdx=*\/3);\n case 3: vec[2] = GenDescriptor(ord3, good3, \/*genIdx=*\/2);\n case 2: vec[1] = GenDescriptor(ord2, good2, \/*genIdx=*\/1);\n default: vec[0] = GenDescriptor(ord1, good1, \/*genIdx=*\/0);\n }\n cout << \"***Testing \";\n if (isDryRun()) cout << \"(dry run) \";\n for (long i=0; i<vec.length(); i++)\n cout << \"(\"<<vec[i].order<<\",\"<<vec[i].good<<\")\";\n cout << \", depth=\"<<depth<<\"\\n\";\n testCube(vec, depth);\n }\n else {\n setTimersOn();\n cout << \"***Testing m=\"<<m<<\", p=\"<<p<<\", depth=\"<<depth<< endl;\n testCtxt(m,p,depth,L,r);\n }\n}\n\n\n\n#if 0\n cout << \"***Testing m=31, p=2, width=3\\n\"; \/\/ (6 good)\n testCtxt(\/*m=*\/31, \/*p=*\/2, \/*width=*\/3);\n\n cout << \"\\n***Testing m=61, p=3, width=3\\n\"; \/\/ (3 good), (2, bad)\n testCtxt(\/*m=*\/61, \/*p=*\/3, \/*width=*\/3);\n\n cout << \"\\n***Testing m=683, p=2, width=5\\n\"; \/\/ (31, good)\n testCtxt(\/*m=*\/683, \/*p=*\/2, \/*width=*\/5);\n\n \/\/ cout << \"\\n***Testing m=47127, p=2, width=11\\n\"; \/\/ (682,good),(2,good)\n \/\/ testCtxt(\/*m=*\/47127, \/*p=*\/2, \/*width=*\/11);\n\n \/\/ Test 1: a single good small prime-order generator (3)\n {\n Vec<GenDescriptor> vec(INIT_SIZE, 1);\n vec[0] = GenDescriptor(\/*order=*\/3, \/*good=*\/true, \/*genIdx=*\/0);\n cout << \"***Testing (3,good), width=1\\n\";\n testCube(vec, \/*width=*\/1);\n }\n\n \/\/ Test 2: a single bad larger prime-order generator (31)\n {\n Vec<GenDescriptor> vec(INIT_SIZE, 1);\n vec[0] = GenDescriptor(\/*order=*\/31, \/*good=*\/false, \/*genIdx=*\/0);\n cout << \"\\n***Testing (31,bad), width=5\\n\";\n testCube(vec, \/*width=*\/5);\n }\n\n \/\/ Test 3: two generators with small prime orders (2,3), both bad\n {\n Vec<GenDescriptor> vec(INIT_SIZE, 2);\n vec[0] = GenDescriptor(\/*order=*\/2, \/*good=*\/false, \/*genIdx=*\/0);\n vec[1] = GenDescriptor(\/*order=*\/3, \/*good=*\/false, \/*genIdx=*\/1);\n cout << \"\\n***Testing [(2,bad),(3,bad)], width=3\\n\";\n testCube(vec, \/*width=*\/3);\n }\n\n \/\/ Test 4: two generators with small prime orders (2,3), one good\n {\n Vec<GenDescriptor> vec(INIT_SIZE, 2);\n vec[0] = GenDescriptor(\/*order=*\/3, \/*good=*\/true, \/*genIdx=*\/0);\n vec[1] = GenDescriptor(\/*order=*\/2, \/*good=*\/false, \/*genIdx=*\/1);\n cout << \"\\n***Testing [(3,good),(2,bad)], width=3\\n\";\n testCube(vec, \/*width=*\/3);\n }\n\n \/\/ Test 5: a single good composite-order generator (6)\n {\n Vec<GenDescriptor> vec(INIT_SIZE, 1);\n vec[0] = GenDescriptor(\/*order=*\/6, \/*good=*\/true, \/*genIdx=*\/0);\n cout << \"\\n***Testing (6,good), width=3\\n\";\n testCube(vec, \/*width=*\/3);\n }\n\n \/\/ Test 6: (6,good),(2,bad)\n {\n Vec<GenDescriptor> vec(INIT_SIZE, 2);\n vec[0] = GenDescriptor(\/*order=*\/6,\/*good=*\/true, \/*genIdx=*\/0);\n vec[1] = GenDescriptor(\/*order=*\/ 2, \/*good=*\/false,\/*genIdx=*\/1);\n cout << \"\\n**Testing [(6,good),(2,bad)], width=5\\n\";\n testCube(vec, \/*width=*\/5);\n }\n\n \/\/ Test 7: the \"general case\", (682,good),(2,bad)\n {\n Vec<GenDescriptor> vec(INIT_SIZE, 2);\n vec[0] = GenDescriptor(\/*order=*\/682,\/*good=*\/true, \/*genIdx=*\/0);\n vec[1] = GenDescriptor(\/*order=*\/ 2, \/*good=*\/false,\/*genIdx=*\/1);\n cout << \"\\n**Testing [(682,good),(2,bad)], width=11\\n\";\n testCube(vec, \/*width=*\/11);\n }\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/* bzflag\n * Copyright (c) 1993 - 2005 Tim Riker\n *\n * This package is free software; you can redistribute it and\/or\n * modify it under the terms of the license found in the file\n * named COPYING that should have accompanied this file.\n *\n * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR\n * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED\n * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.\n *\/\n \n#include \"common.h\"\n\n\/\/ implementation header\n#include \"MeshDrawMgr.h\"\n\n\/\/ common headers\n#include \"bzfgl.h\"\n#include \"OpenGLGState.h\"\n#include \"MeshDrawInfo.h\"\n#include \"bzfio.h\" \/\/ for DEBUGx()\n\n\nGLuint MeshDrawMgr::unloadList = INVALID_GL_LIST_ID;\n\nstatic bool haveVBOs = false;\nstatic void (*bzGenBuffers)(GLsizei, GLuint*) = NULL;\nstatic void (*bzBufferData)(GLenum, GLsizeiptr, const GLvoid*, GLenum) = NULL;\nstatic void (*bzBindBuffer)(GLenum, GLuint) = NULL;\nstatic void (*bzDeleteBuffers)(GLsizei, const GLuint*) = NULL;\n\n\nvoid MeshDrawMgr::init()\n{\n haveVBOs = false;\n bzGenBuffers = NULL;\n bzBufferData = NULL;\n bzBindBuffer = NULL;\n bzDeleteBuffers = NULL;\n}\n\n\nvoid MeshDrawMgr::kill()\n{\n haveVBOs = false;\n bzGenBuffers = NULL;\n bzBufferData = NULL;\n bzBindBuffer = NULL;\n bzDeleteBuffers = NULL;\n}\n\n\nMeshDrawMgr::MeshDrawMgr(const MeshDrawInfo* _drawInfo)\n{\n drawInfo = _drawInfo;\n if ((drawInfo == NULL) || !drawInfo->isValid()) {\n printf(\"MeshDrawMgr: invalid drawInfo\\n\");\n fflush(stdout);\n return;\n } else {\n DEBUG4(\"MeshDrawMgr: initializing\\n\");\n fflush(stdout);\n }\n\n drawLods = drawInfo->getDrawLods();\n vertices = (const GLfloat*)drawInfo->getVertices(); \n normals = (const GLfloat*)drawInfo->getNormals();\n texcoords = (const GLfloat*)drawInfo->getTexcoords();\n\n lodCount = drawInfo->getLodCount();\n lodLists = new LodList[lodCount];\n \n for (int i = 0; i < lodCount; i++) {\n LodList& lodList = lodLists[i];\n lodList.count = drawLods[i].count;\n lodList.setLists = new GLuint[lodList.count];\n for (int j = 0; j < lodList.count; j++) {\n lodList.setLists[j] = INVALID_GL_LIST_ID;\n }\n }\n\n makeLists();\n OpenGLGState::registerContextInitializer(freeContext, initContext, this);\n return;\n}\n\n\nMeshDrawMgr::~MeshDrawMgr()\n{\n DEBUG4(\"MeshDrawMgr: killing\\n\");\n \n OpenGLGState::unregisterContextInitializer(freeContext, initContext, this);\n freeLists();\n\n for (int i = 0; i < lodCount; i++) {\n delete[] lodLists[i].setLists;\n }\n delete[] lodLists;\n\n return;\n}\n \n\ninline void MeshDrawMgr::rawExecuteCommands(int lod, int set)\n{\n const DrawLod& drawLod = drawLods[lod];\n const DrawSet& drawSet = drawLod.sets[set];\n const int cmdCount = drawSet.count;\n for (int i = 0; i < cmdCount; i++) {\n const DrawCmd& cmd = drawSet.cmds[i];\n glDrawElements(cmd.drawMode, cmd.count, cmd.indexType, cmd.indices);\n }\n return;\n}\n\n\nvoid MeshDrawMgr::executeSet(int lod, int set, bool _normals, bool _texcoords)\n{\n \/\/ FIXME\n const AnimationInfo* animInfo = drawInfo->getAnimationInfo();\n if (animInfo != NULL) {\n glPushMatrix();\n glRotatef(animInfo->angle, 0.0f, 0.0f, 1.0f);\n }\n \n const GLuint list = lodLists[lod].setLists[set];\n if (list != INVALID_GL_LIST_ID) {\n glCallList(list);\n } else {\n glVertexPointer(3, GL_FLOAT, 0, vertices);\n glEnableClientState(GL_VERTEX_ARRAY);\n if (_normals) {\n glNormalPointer(GL_FLOAT, 0, normals);\n glEnableClientState(GL_NORMAL_ARRAY);\n }\n if (_texcoords) {\n glTexCoordPointer(2, GL_FLOAT, 0, texcoords);\n glEnableClientState(GL_TEXTURE_COORD_ARRAY);\n }\n rawExecuteCommands(lod, set);\n disableArrays();\n }\n\n if (animInfo != NULL) {\n glPopMatrix();\n }\n \n return;\n}\n \n\ninline void MeshDrawMgr::rawDisableArrays()\n{\n glDisableClientState(GL_VERTEX_ARRAY);\n glDisableClientState(GL_NORMAL_ARRAY);\n glDisableClientState(GL_TEXTURE_COORD_ARRAY);\n return;\n}\n\n\nvoid MeshDrawMgr::disableArrays()\n{\n if (unloadList == INVALID_GL_LIST_ID) {\n rawDisableArrays();\n } else {\n glCallList(unloadList);\n }\n return;\n}\n\n\nvoid MeshDrawMgr::makeLists()\n{\n int errCount = 0;\n \/\/ reset the error state\n while (glGetError() != GL_NO_ERROR) {\n errCount++; \/\/ avoid a possible spin-lock?\n if (errCount > 666) {\n DEBUG1(\"MeshDrawMgr::makeLists() glError\\n\");\n return; \/\/ don't make the lists, something is borked\n }\n };\n\n if (unloadList == INVALID_GL_LIST_ID) {\n unloadList = glGenLists(1);\n glNewList(unloadList, GL_COMPILE);\n {\n disableArrays();\n }\n glEndList();\n if (glGetError() != GL_NO_ERROR) {\n DEBUG1(\"MeshDrawMgr::makeLists() glError\\n\");\n unloadList = INVALID_GL_LIST_ID;\n }\n }\n \n glVertexPointer(3, GL_FLOAT, 0, vertices);\n glEnableClientState(GL_VERTEX_ARRAY);\n glNormalPointer(GL_FLOAT, 0, normals);\n glEnableClientState(GL_NORMAL_ARRAY);\n glTexCoordPointer(2, GL_FLOAT, 0, texcoords);\n glEnableClientState(GL_TEXTURE_COORD_ARRAY);\n \n for (int lod = 0; lod < lodCount; lod++) {\n const DrawLod& drawLod = drawLods[lod];\n for (int set = 0; set < drawLod.count; set++) {\n const DrawSet& drawSet = drawLod.sets[set];\n if (drawSet.wantList) {\n lodLists[lod].setLists[set] = glGenLists(1);\n\n glNewList(lodLists[lod].setLists[set], GL_COMPILE);\n {\n rawExecuteCommands(lod, set);\n }\n glEndList();\n \n if (glGetError() != GL_NO_ERROR) {\n DEBUG1(\"MeshDrawMgr::makeLists() %i\/%i glError\\n\", lod, set);\n lodLists[lod].setLists[set] = INVALID_GL_LIST_ID;\n } else {\n DEBUG3(\"MeshDrawMgr::makeLists() %i\/%i created\\n\", lod, set);\n }\n }\n }\n }\n \n disableArrays();\n \n return;\n}\n\n\nvoid MeshDrawMgr::freeLists()\n{\n if (unloadList != INVALID_GL_LIST_ID) {\n glDeleteLists(unloadList, 1);\n unloadList = INVALID_GL_LIST_ID;\n }\n \n for (int lod = 0; lod < lodCount; lod++) {\n for (int set = 0; set < lodLists[lod].count; set++) {\n if (lodLists[lod].setLists[set] != INVALID_GL_LIST_ID) {\n glDeleteLists(lodLists[lod].setLists[set], 1);\n lodLists[lod].setLists[set] = INVALID_GL_LIST_ID;\n }\n }\n }\n\n return;\n}\n \n\nvoid MeshDrawMgr::initContext(void* data)\n{\n ((MeshDrawMgr*)data)->makeLists();\n return;\n}\n\n\nvoid MeshDrawMgr::freeContext(void* data)\n{\n ((MeshDrawMgr*)data)->freeLists();\n return;\n}\n\n\n\/\/ Local Variables: ***\n\/\/ mode:C++ ***\n\/\/ tab-width: 8 ***\n\/\/ c-basic-offset: 2 ***\n\/\/ indent-tabs-mode: t ***\n\/\/ End: ***\n\/\/ ex: shiftwidth=2 tabstop=8\n\n<commit_msg>oops, thought those were cleaned out<commit_after>\/* bzflag\n * Copyright (c) 1993 - 2005 Tim Riker\n *\n * This package is free software; you can redistribute it and\/or\n * modify it under the terms of the license found in the file\n * named COPYING that should have accompanied this file.\n *\n * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR\n * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED\n * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.\n *\/\n \n#include \"common.h\"\n\n\/\/ implementation header\n#include \"MeshDrawMgr.h\"\n\n\/\/ common headers\n#include \"bzfgl.h\"\n#include \"OpenGLGState.h\"\n#include \"MeshDrawInfo.h\"\n#include \"bzfio.h\" \/\/ for DEBUGx()\n\n\nGLuint MeshDrawMgr::unloadList = INVALID_GL_LIST_ID;\n\n\nvoid MeshDrawMgr::init()\n{\n}\n\n\nvoid MeshDrawMgr::kill()\n{\n}\n\n\nMeshDrawMgr::MeshDrawMgr(const MeshDrawInfo* _drawInfo)\n{\n drawInfo = _drawInfo;\n if ((drawInfo == NULL) || !drawInfo->isValid()) {\n printf(\"MeshDrawMgr: invalid drawInfo\\n\");\n fflush(stdout);\n return;\n } else {\n DEBUG4(\"MeshDrawMgr: initializing\\n\");\n fflush(stdout);\n }\n\n drawLods = drawInfo->getDrawLods();\n vertices = (const GLfloat*)drawInfo->getVertices(); \n normals = (const GLfloat*)drawInfo->getNormals();\n texcoords = (const GLfloat*)drawInfo->getTexcoords();\n\n lodCount = drawInfo->getLodCount();\n lodLists = new LodList[lodCount];\n \n for (int i = 0; i < lodCount; i++) {\n LodList& lodList = lodLists[i];\n lodList.count = drawLods[i].count;\n lodList.setLists = new GLuint[lodList.count];\n for (int j = 0; j < lodList.count; j++) {\n lodList.setLists[j] = INVALID_GL_LIST_ID;\n }\n }\n\n makeLists();\n OpenGLGState::registerContextInitializer(freeContext, initContext, this);\n return;\n}\n\n\nMeshDrawMgr::~MeshDrawMgr()\n{\n DEBUG4(\"MeshDrawMgr: killing\\n\");\n \n OpenGLGState::unregisterContextInitializer(freeContext, initContext, this);\n freeLists();\n\n for (int i = 0; i < lodCount; i++) {\n delete[] lodLists[i].setLists;\n }\n delete[] lodLists;\n\n return;\n}\n \n\ninline void MeshDrawMgr::rawExecuteCommands(int lod, int set)\n{\n const DrawLod& drawLod = drawLods[lod];\n const DrawSet& drawSet = drawLod.sets[set];\n const int cmdCount = drawSet.count;\n for (int i = 0; i < cmdCount; i++) {\n const DrawCmd& cmd = drawSet.cmds[i];\n glDrawElements(cmd.drawMode, cmd.count, cmd.indexType, cmd.indices);\n }\n return;\n}\n\n\nvoid MeshDrawMgr::executeSet(int lod, int set, bool _normals, bool _texcoords)\n{\n \/\/ FIXME\n const AnimationInfo* animInfo = drawInfo->getAnimationInfo();\n if (animInfo != NULL) {\n glPushMatrix();\n glRotatef(animInfo->angle, 0.0f, 0.0f, 1.0f);\n }\n \n const GLuint list = lodLists[lod].setLists[set];\n if (list != INVALID_GL_LIST_ID) {\n glCallList(list);\n } else {\n glVertexPointer(3, GL_FLOAT, 0, vertices);\n glEnableClientState(GL_VERTEX_ARRAY);\n if (_normals) {\n glNormalPointer(GL_FLOAT, 0, normals);\n glEnableClientState(GL_NORMAL_ARRAY);\n }\n if (_texcoords) {\n glTexCoordPointer(2, GL_FLOAT, 0, texcoords);\n glEnableClientState(GL_TEXTURE_COORD_ARRAY);\n }\n rawExecuteCommands(lod, set);\n disableArrays();\n }\n\n if (animInfo != NULL) {\n glPopMatrix();\n }\n \n return;\n}\n \n\ninline void MeshDrawMgr::rawDisableArrays()\n{\n glDisableClientState(GL_VERTEX_ARRAY);\n glDisableClientState(GL_NORMAL_ARRAY);\n glDisableClientState(GL_TEXTURE_COORD_ARRAY);\n return;\n}\n\n\nvoid MeshDrawMgr::disableArrays()\n{\n if (unloadList == INVALID_GL_LIST_ID) {\n rawDisableArrays();\n } else {\n glCallList(unloadList);\n }\n return;\n}\n\n\nvoid MeshDrawMgr::makeLists()\n{\n int errCount = 0;\n \/\/ reset the error state\n while (glGetError() != GL_NO_ERROR) {\n errCount++; \/\/ avoid a possible spin-lock?\n if (errCount > 666) {\n DEBUG1(\"MeshDrawMgr::makeLists() glError\\n\");\n return; \/\/ don't make the lists, something is borked\n }\n };\n\n if (unloadList == INVALID_GL_LIST_ID) {\n unloadList = glGenLists(1);\n glNewList(unloadList, GL_COMPILE);\n {\n disableArrays();\n }\n glEndList();\n if (glGetError() != GL_NO_ERROR) {\n DEBUG1(\"MeshDrawMgr::makeLists() glError\\n\");\n unloadList = INVALID_GL_LIST_ID;\n }\n }\n \n glVertexPointer(3, GL_FLOAT, 0, vertices);\n glEnableClientState(GL_VERTEX_ARRAY);\n glNormalPointer(GL_FLOAT, 0, normals);\n glEnableClientState(GL_NORMAL_ARRAY);\n glTexCoordPointer(2, GL_FLOAT, 0, texcoords);\n glEnableClientState(GL_TEXTURE_COORD_ARRAY);\n \n for (int lod = 0; lod < lodCount; lod++) {\n const DrawLod& drawLod = drawLods[lod];\n for (int set = 0; set < drawLod.count; set++) {\n const DrawSet& drawSet = drawLod.sets[set];\n if (drawSet.wantList) {\n lodLists[lod].setLists[set] = glGenLists(1);\n\n glNewList(lodLists[lod].setLists[set], GL_COMPILE);\n {\n rawExecuteCommands(lod, set);\n }\n glEndList();\n \n if (glGetError() != GL_NO_ERROR) {\n DEBUG1(\"MeshDrawMgr::makeLists() %i\/%i glError\\n\", lod, set);\n lodLists[lod].setLists[set] = INVALID_GL_LIST_ID;\n } else {\n DEBUG3(\"MeshDrawMgr::makeLists() %i\/%i created\\n\", lod, set);\n }\n }\n }\n }\n \n disableArrays();\n \n return;\n}\n\n\nvoid MeshDrawMgr::freeLists()\n{\n if (unloadList != INVALID_GL_LIST_ID) {\n glDeleteLists(unloadList, 1);\n unloadList = INVALID_GL_LIST_ID;\n }\n \n for (int lod = 0; lod < lodCount; lod++) {\n for (int set = 0; set < lodLists[lod].count; set++) {\n if (lodLists[lod].setLists[set] != INVALID_GL_LIST_ID) {\n glDeleteLists(lodLists[lod].setLists[set], 1);\n lodLists[lod].setLists[set] = INVALID_GL_LIST_ID;\n }\n }\n }\n\n return;\n}\n \n\nvoid MeshDrawMgr::initContext(void* data)\n{\n ((MeshDrawMgr*)data)->makeLists();\n return;\n}\n\n\nvoid MeshDrawMgr::freeContext(void* data)\n{\n ((MeshDrawMgr*)data)->freeLists();\n return;\n}\n\n\n\/\/ Local Variables: ***\n\/\/ mode:C++ ***\n\/\/ tab-width: 8 ***\n\/\/ c-basic-offset: 2 ***\n\/\/ indent-tabs-mode: t ***\n\/\/ End: ***\n\/\/ ex: shiftwidth=2 tabstop=8\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright 2013-2014 Paul Colby\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"ConsoleUtils.h\"\n\n#include <qpid\/console\/Value.h>\n\n#include <boost\/lexical_cast.hpp>\n\nstd::string ConsoleUtils::getName(const qpid::console::Object &object,\n const bool allowNodeName)\n{\n const qpid::console::Object::AttributeMap &attributes = object.getAttributes();\n qpid::console::Object::AttributeMap::const_iterator name = attributes.find(\"name\");\n if ((name == attributes.end()) && (allowNodeName)) {\n name == attributes.find(\"nodeName\");\n }\n return (name == attributes.end()) ? std::string() : name->second->asString();\n}\n\nConsoleUtils::ObjectSchemaType ConsoleUtils::getType(const qpid::console::Object &object)\n{\n return getType(object.getClassKey());\n}\n\nConsoleUtils::ObjectSchemaType ConsoleUtils::getType(const qpid::console::ClassKey &classKey)\n{\n if (classKey.getPackageName() == \"org.apache.qpid.broker\") {\n const std::string &className = classKey.getClassName();\n if (className == \"broker\") return Broker;\n if (className == \"queue\") return Queue;\n if (className == \"system\") return System;\n }\n return Other;\n}\n\nstd::string ConsoleUtils::toString(const qpid::console::ClassKey &classKey)\n{\n return classKey.getPackageName() + ':' + classKey.getClassName();\n}\n\nstd::string ConsoleUtils::toString(const qpid::console::Object &object,\n bool includePackageName)\n{\n const qpid::console::ClassKey &classKey = object.getClassKey();\n return (includePackageName ? toString(classKey) : classKey.getClassName()) +\n \" '\" + getName(object) + \"' (\" + toString(object.getObjectId()) + ')';\n}\n\nstd::string ConsoleUtils::toString(const qpid::console::ObjectId &id)\n{\n std::ostringstream stream;\n stream << id;\n return stream.str();\n}\n\nstd::string ConsoleUtils::toString(const qpid::console::SchemaProperty &property)\n{\n return property.name + ':' + qmfTypeCodeToString(property.typeCode) + ':' +\n property.unit + ':' + property.desc;\n}\n\nstd::string ConsoleUtils::toString(const qpid::console::SchemaStatistic &statistic)\n{\n return statistic.name + ':' + qmfTypeCodeToString(statistic.typeCode) + ':' +\n statistic.unit + ':' + statistic.desc;\n}\n\nstd::string ConsoleUtils::qmfTypeCodeToString(const uint8_t typeCode)\n{\n \/\/ See Qpid's cpp\/include\/qmf\/engine\/Typecode.h\n switch (typeCode) {\n case 1: return \"UINT8\";\n case 2: return \"UINT16\";\n case 3: return \"UINT32\";\n case 4: return \"UINT64\";\n \/\/case 5: \/\/ There is no type 5.\n case 6: return \"SSTR\";\n case 7: return \"LSTR\";\n case 8: return \"ABSTIME\";\n case 9: return \"DELTATIME\";\n case 10: return \"REF\";\n case 11: return \"BOOL\";\n case 12: return \"FLOAT\";\n case 13: return \"DOUBLE\";\n case 14: return \"UUID\";\n case 15: return \"MAP\";\n case 16: return \"INT8\";\n case 17: return \"INT16\";\n case 18: return \"INT32\";\n case 19: return \"INT64\";\n case 20: return \"OBJECT\";\n case 21: return \"LIST\";\n case 22: return \"ARRAY\";\n default:\n return \"unknown (\" + boost::lexical_cast<std::string>(typeCode) + ')';\n }\n}\n<commit_msg>Small typo fix.<commit_after>\/*\n * Copyright 2013-2014 Paul Colby\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"ConsoleUtils.h\"\n\n#include <qpid\/console\/Value.h>\n\n#include <boost\/lexical_cast.hpp>\n\nstd::string ConsoleUtils::getName(const qpid::console::Object &object,\n const bool allowNodeName)\n{\n const qpid::console::Object::AttributeMap &attributes = object.getAttributes();\n qpid::console::Object::AttributeMap::const_iterator name = attributes.find(\"name\");\n if ((name == attributes.end()) && (allowNodeName)) {\n name = attributes.find(\"nodeName\");\n }\n return (name == attributes.end()) ? std::string() : name->second->asString();\n}\n\nConsoleUtils::ObjectSchemaType ConsoleUtils::getType(const qpid::console::Object &object)\n{\n return getType(object.getClassKey());\n}\n\nConsoleUtils::ObjectSchemaType ConsoleUtils::getType(const qpid::console::ClassKey &classKey)\n{\n if (classKey.getPackageName() == \"org.apache.qpid.broker\") {\n const std::string &className = classKey.getClassName();\n if (className == \"broker\") return Broker;\n if (className == \"queue\") return Queue;\n if (className == \"system\") return System;\n }\n return Other;\n}\n\nstd::string ConsoleUtils::toString(const qpid::console::ClassKey &classKey)\n{\n return classKey.getPackageName() + ':' + classKey.getClassName();\n}\n\nstd::string ConsoleUtils::toString(const qpid::console::Object &object,\n bool includePackageName)\n{\n const qpid::console::ClassKey &classKey = object.getClassKey();\n return (includePackageName ? toString(classKey) : classKey.getClassName()) +\n \" '\" + getName(object) + \"' (\" + toString(object.getObjectId()) + ')';\n}\n\nstd::string ConsoleUtils::toString(const qpid::console::ObjectId &id)\n{\n std::ostringstream stream;\n stream << id;\n return stream.str();\n}\n\nstd::string ConsoleUtils::toString(const qpid::console::SchemaProperty &property)\n{\n return property.name + ':' + qmfTypeCodeToString(property.typeCode) + ':' +\n property.unit + ':' + property.desc;\n}\n\nstd::string ConsoleUtils::toString(const qpid::console::SchemaStatistic &statistic)\n{\n return statistic.name + ':' + qmfTypeCodeToString(statistic.typeCode) + ':' +\n statistic.unit + ':' + statistic.desc;\n}\n\nstd::string ConsoleUtils::qmfTypeCodeToString(const uint8_t typeCode)\n{\n \/\/ See Qpid's cpp\/include\/qmf\/engine\/Typecode.h\n switch (typeCode) {\n case 1: return \"UINT8\";\n case 2: return \"UINT16\";\n case 3: return \"UINT32\";\n case 4: return \"UINT64\";\n \/\/case 5: \/\/ There is no type 5.\n case 6: return \"SSTR\";\n case 7: return \"LSTR\";\n case 8: return \"ABSTIME\";\n case 9: return \"DELTATIME\";\n case 10: return \"REF\";\n case 11: return \"BOOL\";\n case 12: return \"FLOAT\";\n case 13: return \"DOUBLE\";\n case 14: return \"UUID\";\n case 15: return \"MAP\";\n case 16: return \"INT8\";\n case 17: return \"INT16\";\n case 18: return \"INT32\";\n case 19: return \"INT64\";\n case 20: return \"OBJECT\";\n case 21: return \"LIST\";\n case 22: return \"ARRAY\";\n default:\n return \"unknown (\" + boost::lexical_cast<std::string>(typeCode) + ')';\n }\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"sendcoinsentry.h\"\n#include \"ui_sendcoinsentry.h\"\n\n#include \"guiutil.h\"\n#include \"bitcoinunits.h\"\n#include \"addressbookpage.h\"\n#include \"walletmodel.h\"\n#include \"optionsmodel.h\"\n#include \"addresstablemodel.h\"\n\n#include <QApplication>\n#include <QClipboard>\n\nSendCoinsEntry::SendCoinsEntry(QWidget *parent) :\n QStackedWidget(parent),\n ui(new Ui::SendCoinsEntry),\n model(0)\n{\n ui->setupUi(this);\n\n setCurrentWidget(ui->SendCoinsInsecure);\n\n#ifdef Q_OS_MAC\n ui->payToLayout->setSpacing(4);\n#endif\n#if QT_VERSION >= 0x040700\n \/* Do not move this to the XML file, Qt before 4.7 will choke on it *\/\n ui->addAsLabel->setPlaceholderText(tr(\"Enter a label for this address to add it to your address book\"));\n ui->payTo->setPlaceholderText(tr(\"Enter a Bitcoin address (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)\"));\n#endif\n setFocusPolicy(Qt::TabFocus);\n setFocusProxy(ui->payTo);\n\n GUIUtil::setupAddressWidget(ui->payTo, this);\n}\n\nSendCoinsEntry::~SendCoinsEntry()\n{\n delete ui;\n}\n\nvoid SendCoinsEntry::on_pasteButton_clicked()\n{\n \/\/ Paste text from clipboard into recipient field\n ui->payTo->setText(QApplication::clipboard()->text());\n}\n\nvoid SendCoinsEntry::on_addressBookButton_clicked()\n{\n if(!model)\n return;\n AddressBookPage dlg(AddressBookPage::ForSending, AddressBookPage::SendingTab, this);\n dlg.setModel(model->getAddressTableModel());\n if(dlg.exec())\n {\n ui->payTo->setText(dlg.getReturnValue());\n ui->payAmount->setFocus();\n }\n}\n\nvoid SendCoinsEntry::on_payTo_textChanged(const QString &address)\n{\n if(!model)\n return;\n \/\/ Fill in label from address book, if address has an associated label\n QString associatedLabel = model->getAddressTableModel()->labelForAddress(address);\n if(!associatedLabel.isEmpty())\n ui->addAsLabel->setText(associatedLabel);\n}\n\nvoid SendCoinsEntry::setModel(WalletModel *model)\n{\n this->model = model;\n\n if(model && model->getOptionsModel())\n connect(model->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit()));\n\n clear();\n}\n\nvoid SendCoinsEntry::setRemoveEnabled(bool enabled)\n{\n ui->deleteButton->setEnabled(enabled);\n}\n\nvoid SendCoinsEntry::clear()\n{\n ui->payTo->clear();\n ui->addAsLabel->clear();\n ui->payAmount->clear();\n ui->payTo->setFocus();\n \/\/ update the display unit, to not use the default (\"BTC\")\n updateDisplayUnit();\n}\n\nvoid SendCoinsEntry::on_deleteButton_clicked()\n{\n emit removeEntry(this);\n}\n\nbool SendCoinsEntry::validate()\n{\n \/\/ Check input validity\n bool retval = true;\n\n if (!recipient.authenticatedMerchant.isEmpty())\n return retval;\n\n if (!ui->payTo->hasAcceptableInput() ||\n (model && !model->validateAddress(ui->payTo->text())))\n {\n ui->payTo->setValid(false);\n retval = false;\n }\n\n if(!ui->payAmount->validate())\n {\n retval = false;\n }\n\n \/\/ Reject dust outputs:\n if (retval && GUIUtil::isDust(ui->payTo->text(), ui->payAmount->value())) {\n ui->payAmount->setValid(false);\n retval = false;\n }\n\n return retval;\n}\n\nSendCoinsRecipient SendCoinsEntry::getValue()\n{\n if (!recipient.authenticatedMerchant.isEmpty())\n return recipient;\n\n \/\/ User-entered or non-authenticated:\n recipient.address = ui->payTo->text();\n recipient.label = ui->addAsLabel->text();\n recipient.amount = ui->payAmount->value();\n\n return recipient;\n}\n\nQWidget *SendCoinsEntry::setupTabChain(QWidget *prev)\n{\n QWidget::setTabOrder(prev, ui->payTo);\n QWidget::setTabOrder(ui->payTo, ui->addressBookButton);\n QWidget::setTabOrder(ui->addressBookButton, ui->pasteButton);\n QWidget::setTabOrder(ui->pasteButton, ui->deleteButton);\n QWidget::setTabOrder(ui->deleteButton, ui->addAsLabel);\n return ui->payAmount->setupTabChain(ui->addAsLabel);\n}\n\nvoid SendCoinsEntry::setValue(const SendCoinsRecipient &value)\n{\n recipient = value;\n\n ui->payTo->setText(value.address);\n ui->addAsLabel->setText(value.label);\n ui->payAmount->setValue(value.amount);\n\n if (!recipient.authenticatedMerchant.isEmpty())\n {\n const payments::PaymentDetails& details = value.paymentRequest.getDetails();\n\n ui->payTo_s->setText(value.authenticatedMerchant);\n ui->memoTextLabel_s->setText(QString::fromStdString(details.memo()));\n ui->payAmount_s->setValue(value.amount);\n setCurrentWidget(ui->SendCoinsSecure);\n }\n}\n\nvoid SendCoinsEntry::setAddress(const QString &address)\n{\n ui->payTo->setText(address);\n ui->payAmount->setFocus();\n}\n\nbool SendCoinsEntry::isClear()\n{\n return ui->payTo->text().isEmpty() && ui->payTo_s->text().isEmpty();\n}\n\nvoid SendCoinsEntry::setFocus()\n{\n ui->payTo->setFocus();\n}\n\nvoid SendCoinsEntry::updateDisplayUnit()\n{\n if(model && model->getOptionsModel())\n {\n \/\/ Update payAmount with the current unit\n ui->payAmount->setDisplayUnit(model->getOptionsModel()->getDisplayUnit());\n ui->payAmount_s->setDisplayUnit(model->getOptionsModel()->getDisplayUnit());\n }\n}\n<commit_msg>sendcoinsentry: small clear() and setValue() changes<commit_after>#include \"sendcoinsentry.h\"\n#include \"ui_sendcoinsentry.h\"\n\n#include \"guiutil.h\"\n#include \"bitcoinunits.h\"\n#include \"addressbookpage.h\"\n#include \"walletmodel.h\"\n#include \"optionsmodel.h\"\n#include \"addresstablemodel.h\"\n\n#include <QApplication>\n#include <QClipboard>\n\nSendCoinsEntry::SendCoinsEntry(QWidget *parent) :\n QStackedWidget(parent),\n ui(new Ui::SendCoinsEntry),\n model(0)\n{\n ui->setupUi(this);\n\n setCurrentWidget(ui->SendCoinsInsecure);\n\n#ifdef Q_OS_MAC\n ui->payToLayout->setSpacing(4);\n#endif\n#if QT_VERSION >= 0x040700\n \/* Do not move this to the XML file, Qt before 4.7 will choke on it *\/\n ui->addAsLabel->setPlaceholderText(tr(\"Enter a label for this address to add it to your address book\"));\n ui->payTo->setPlaceholderText(tr(\"Enter a Bitcoin address (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)\"));\n#endif\n setFocusPolicy(Qt::TabFocus);\n setFocusProxy(ui->payTo);\n\n GUIUtil::setupAddressWidget(ui->payTo, this);\n}\n\nSendCoinsEntry::~SendCoinsEntry()\n{\n delete ui;\n}\n\nvoid SendCoinsEntry::on_pasteButton_clicked()\n{\n \/\/ Paste text from clipboard into recipient field\n ui->payTo->setText(QApplication::clipboard()->text());\n}\n\nvoid SendCoinsEntry::on_addressBookButton_clicked()\n{\n if(!model)\n return;\n AddressBookPage dlg(AddressBookPage::ForSending, AddressBookPage::SendingTab, this);\n dlg.setModel(model->getAddressTableModel());\n if(dlg.exec())\n {\n ui->payTo->setText(dlg.getReturnValue());\n ui->payAmount->setFocus();\n }\n}\n\nvoid SendCoinsEntry::on_payTo_textChanged(const QString &address)\n{\n if(!model)\n return;\n \/\/ Fill in label from address book, if address has an associated label\n QString associatedLabel = model->getAddressTableModel()->labelForAddress(address);\n if(!associatedLabel.isEmpty())\n ui->addAsLabel->setText(associatedLabel);\n}\n\nvoid SendCoinsEntry::setModel(WalletModel *model)\n{\n this->model = model;\n\n if(model && model->getOptionsModel())\n connect(model->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit()));\n\n clear();\n}\n\nvoid SendCoinsEntry::setRemoveEnabled(bool enabled)\n{\n ui->deleteButton->setEnabled(enabled);\n}\n\nvoid SendCoinsEntry::clear()\n{\n \/\/ clear UI elements for insecure payments\n ui->payTo->clear();\n ui->addAsLabel->clear();\n ui->payAmount->clear();\n \/\/ and the ones for secure payments just to be sure\n ui->payTo_s->clear();\n ui->memoTextLabel_s->clear();\n ui->payAmount_s->clear();\n\n ui->payTo->setFocus();\n\n \/\/ update the display unit, to not use the default (\"BTC\")\n updateDisplayUnit();\n}\n\nvoid SendCoinsEntry::on_deleteButton_clicked()\n{\n emit removeEntry(this);\n}\n\nbool SendCoinsEntry::validate()\n{\n \/\/ Check input validity\n bool retval = true;\n\n if (!recipient.authenticatedMerchant.isEmpty())\n return retval;\n\n if (!ui->payTo->hasAcceptableInput() ||\n (model && !model->validateAddress(ui->payTo->text())))\n {\n ui->payTo->setValid(false);\n retval = false;\n }\n\n if(!ui->payAmount->validate())\n {\n retval = false;\n }\n\n \/\/ Reject dust outputs:\n if (retval && GUIUtil::isDust(ui->payTo->text(), ui->payAmount->value())) {\n ui->payAmount->setValid(false);\n retval = false;\n }\n\n return retval;\n}\n\nSendCoinsRecipient SendCoinsEntry::getValue()\n{\n if (!recipient.authenticatedMerchant.isEmpty())\n return recipient;\n\n \/\/ User-entered or non-authenticated:\n recipient.address = ui->payTo->text();\n recipient.label = ui->addAsLabel->text();\n recipient.amount = ui->payAmount->value();\n\n return recipient;\n}\n\nQWidget *SendCoinsEntry::setupTabChain(QWidget *prev)\n{\n QWidget::setTabOrder(prev, ui->payTo);\n QWidget::setTabOrder(ui->payTo, ui->addressBookButton);\n QWidget::setTabOrder(ui->addressBookButton, ui->pasteButton);\n QWidget::setTabOrder(ui->pasteButton, ui->deleteButton);\n QWidget::setTabOrder(ui->deleteButton, ui->addAsLabel);\n return ui->payAmount->setupTabChain(ui->addAsLabel);\n}\n\nvoid SendCoinsEntry::setValue(const SendCoinsRecipient &value)\n{\n recipient = value;\n\n if (recipient.authenticatedMerchant.isEmpty())\n {\n ui->payTo->setText(recipient.address);\n ui->addAsLabel->setText(recipient.label);\n ui->payAmount->setValue(recipient.amount);\n }\n else\n {\n const payments::PaymentDetails& details = recipient.paymentRequest.getDetails();\n\n ui->payTo_s->setText(recipient.authenticatedMerchant);\n ui->memoTextLabel_s->setText(QString::fromStdString(details.memo()));\n ui->payAmount_s->setValue(recipient.amount);\n setCurrentWidget(ui->SendCoinsSecure);\n }\n}\n\nvoid SendCoinsEntry::setAddress(const QString &address)\n{\n ui->payTo->setText(address);\n ui->payAmount->setFocus();\n}\n\nbool SendCoinsEntry::isClear()\n{\n return ui->payTo->text().isEmpty() && ui->payTo_s->text().isEmpty();\n}\n\nvoid SendCoinsEntry::setFocus()\n{\n ui->payTo->setFocus();\n}\n\nvoid SendCoinsEntry::updateDisplayUnit()\n{\n if(model && model->getOptionsModel())\n {\n \/\/ Update payAmount with the current unit\n ui->payAmount->setDisplayUnit(model->getOptionsModel()->getDisplayUnit());\n ui->payAmount_s->setDisplayUnit(model->getOptionsModel()->getDisplayUnit());\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\n#include \"OrientationSensorsWrapper.h\"\n#include \"TireContactModule.h\"\n\n\/\/ a module that determines whether the tires have contact to the surface, based on AHRS data\n\nstatic float thresholdForTireLostContact;\n\n\/\/ init the module\nvoid tiresContactInit(float thresholdForLostOfContact)\n{\n thresholdForTireLostContact = thresholdForLostOfContact;\n}\n\n\/\/ read left tire contact state\nuint8_t getLeftTireContactState()\n{\n \/\/ TODO validate\n if(position.getPitch > thresholdForTireLostContact)\n {\n return 0;\n }\n else\n {\n return 1;\n }\n}\n\n\/\/ read right tire contact state\nuint8_t getRightTireContactState()\n{\n \/\/ TODO validate\n if(position.getPitch < -thresholdForTireLostContact)\n {\n return 0;\n }\n else\n {\n return 1;\n }\n}<commit_msg>bug fix<commit_after>\n#include \"OrientationSensorsWrapper.h\"\n#include \"TireContactModule.h\"\n\n\/\/ a module that determines whether the tires have contact to the surface, based on AHRS data\n\nstatic float thresholdForTireLostContact;\n\n\/\/ init the module\nvoid tiresContactInit(float thresholdForLostOfContact)\n{\n thresholdForTireLostContact = thresholdForLostOfContact;\n}\n\n\/\/ read left tire contact state\nuint8_t getLeftTireContactState()\n{\n \/\/ TODO validate\n if(position.getPitch() > thresholdForTireLostContact)\n {\n return 0;\n }\n else\n {\n return 1;\n }\n}\n\n\/\/ read right tire contact state\nuint8_t getRightTireContactState()\n{\n \/\/ TODO validate\n if(position.getPitch() < -thresholdForTireLostContact)\n {\n return 0;\n }\n else\n {\n return 1;\n }\n}<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 2015 Srijan R Shetty <srijan.shetty+code@gmail.com>\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy of\n * this software and associated documentation files (the \"Software\"), to deal in\n * the Software without restriction, including without limitation the rights to\n * use, copy, modify, merge, publish, distribute, sublicense, and\/or sell copies of\n * the Software, and to permit persons to whom the Software is furnished to do so,\n * subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS\n * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\n * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\n * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n *\/\n\n\n\/\/ Configuration parameters\n#include \".\/config.h\"\n\n\/\/ CONSTANTS\n#define NODE_PREFIX \"leaves\/leaf_\"\n#define SESSION_FILE \".tree.session\"\n#define DEFAULT -1\n\n\/\/ Standard Streams\n#include <iostream>\n#include <fstream>\n\n\/\/ STL\n#include <string>\n#include <cstring>\n#include <vector>\n#include <queue>\n#include <algorithm>\n\n\/\/ Math\n#include <math.h>\n#include <limits>\n\n\/\/ Timing\n#include <chrono>\n\n#include <stdlib.h>\n\nusing namespace std;\n\nnamespace RTree {\n class Node {\n private:\n static long fileCount;\n static long lowerBound;\n static long upperBound;\n\n public:\n \/\/ Initialize the lower and upper bounds\n static void initialize();\n\n \/\/ Get the fileCount\n static long getFileCount() { return fileCount; }\n\n \/\/ Set the fileCount\n static void setFileCount(long _fileCount) { Node::fileCount = _fileCount; }\n\n private:\n \/\/ Entries required to completely specify a node\n bool leaf = false;\n long fileIndex = DEFAULT;\n long parentIndex = DEFAULT;\n long sizeOfSubtree = DEFAULT;\n vector<long> upperPoints = vector<long>(DIMENSION, DEFAULT);\n vector<long> lowerPoints = vector<long>(DIMENSION, DEFAULT);\n\n \/\/ A node can store either of the below\n vector<long> childIndices;\n vector<long> objectIndices;\n\n public:\n \/\/ Construct a node object for the first time\n Node ();\n\n \/\/ Read a node from disk\n Node (long _fileIndex);\n\n \/\/ Get the role of the node\n bool isLeaf() const { return leaf; }\n\n \/\/ Get the index of the file\n long getFileIndex() const { return fileIndex; }\n\n \/\/ Get the name of the file\n string getFileName() const { return NODE_PREFIX + to_string(fileIndex); };\n\n \/\/ Store the node to disk\n void storeNodeToDisk() const;\n\n \/\/ Read the node from the disk\n void readNodeFromDisk();\n };\n\n \/\/ The root of the tree\n Node *RRoot = nullptr;\n\n \/\/ Initial static values\n long Node::fileCount = 0;\n long Node::lowerBound = 0;\n long Node::upperBound = 0;\n\n Node::Node() {\n \/\/ Assign a fileIndex to the current node\n fileIndex = ++fileCount;\n }\n\n Node::Node(long _fileIndex) {\n \/\/ Assign the given fileIndex to the node\n fileIndex = _fileIndex;\n\n \/\/ Load the node from the disk\n readNodeFromDisk();\n }\n\n void Node::initialize() {\n \/\/ Save some place in the file for the header\n long headerSize =\n sizeof(leaf)\n + sizeof(fileIndex)\n + sizeof(parentIndex)\n + sizeof(sizeOfSubtree);\n long pageSize = PAGESIZE - headerSize;\n long keySize = sizeof(childIndices.front());\n long nodeSize = sizeof(fileIndex);\n\n \/\/ Compute the bounds\n upperBound = pageSize \/ (2 * DIMENSION * keySize + nodeSize);\n lowerBound = upperBound \/ 2;\n\n \/\/ TODO: clear this up\n upperBound = 10;\n lowerBound = 5;\n }\n\n void Node::storeNodeToDisk() const {\n char buffer[PAGESIZE];\n long location = 0;\n\n \/\/ Store the contents to disk\n memcpy(buffer + location, &leaf, sizeof(leaf));\n location += sizeof(leaf);\n\n memcpy(buffer + location, &fileIndex, sizeof(fileIndex));\n location +=sizeof(fileIndex);\n\n memcpy(buffer + location, &parentIndex, sizeof(parentIndex));\n location += sizeof(parentIndex);\n\n memcpy(buffer + location, &sizeOfSubtree, sizeof(sizeOfSubtree));\n location += sizeof(sizeOfSubtree);\n\n \/\/ Add the bounds of the MBR to the tree\n for (auto upperPoint : upperPoints) {\n memcpy(buffer + location, &upperPoint, sizeof(upperPoint));\n location += sizeof(upperPoint);\n }\n\n for (auto lowerPoint : lowerPoints) {\n memcpy(buffer + location, &lowerPoint, sizeof(lowerPoint));\n location += sizeof(lowerPoint);\n }\n\n \/\/ We store the objects for a leaf and children for internal node\n if (!leaf) {\n \/\/ We have to store the bumber of children so that we can load them properly\n long numberOfChildren = childIndices.size();\n memcpy(buffer + location, &numberOfChildren, sizeof(numberOfChildren));\n location += sizeof(numberOfChildren);\n\n \/\/ Now we get the childIndices from the buffer\n for (long i = 0, childIndex = 0; i < numberOfChildren; ++i) {\n memcpy(buffer + location, &childIndex, sizeof(childIndex));\n location += sizeof(childIndex);\n }\n }\n\n \/\/ Now we copy the buffer to disk\n ofstream nodeFile(getFileName(), ios::binary | ios::out);\n nodeFile.write(buffer, PAGESIZE);\n nodeFile.close();\n }\n\n void Node::readNodeFromDisk() {\n \/\/ Create a char buffer to read contents from disk\n char buffer[PAGESIZE];\n long location = 0;\n\n \/\/ Open the binary file ane read into memory\n ifstream nodeFile(getFileName(), ios::binary | ios::in);\n nodeFile.read(buffer, PAGESIZE);\n nodeFile.close();\n\n \/\/ Retrieve the contents\n memcpy((char *) &leaf, buffer + location, sizeof(leaf));\n location += sizeof(leaf);\n\n memcpy((char *) &fileIndex, buffer + location, sizeof(fileIndex));\n location += sizeof(fileIndex);\n\n memcpy((char *) &parentIndex, buffer + location, sizeof(parentIndex));\n location += sizeof(parentIndex);\n\n memcpy((char *) &sizeOfSubtree, buffer + location, sizeof(sizeOfSubtree));\n location += sizeof(sizeOfSubtree);\n\n \/\/ Retrieve upperPoints\n upperPoints.clear();\n for (long i = 0, upperPoint = 0; i < DIMENSION; ++i) {\n memcpy((char *) &upperPoint, buffer + location, sizeof(upperPoint));\n upperPoints.push_back(upperPoint);\n location += sizeof(upperPoint);\n }\n\n \/\/ Retrieve lowerPoints\n lowerPoints.clear();\n for (long i = 0, lowerPoint = 0; i < DIMENSION; ++i) {\n memcpy((char *) &lowerPoint, buffer + location, sizeof(lowerPoint));\n lowerPoints.push_back(lowerPoint);\n location += sizeof(lowerPoint);\n }\n\n \/\/ We load the objects for a leaf and children for internal node\n if (!leaf) {\n \/\/ We need to get the number of children in this case\n long numberOfChildren = 0;\n memcpy((char *) &numberOfChildren, buffer + location, sizeof(numberOfChildren));\n location += sizeof(numberOfChildren);\n\n \/\/ Now we get the childIndices from the buffer\n childIndices.clear();\n for (long i = 0, childIndex = 0; i < numberOfChildren; ++i) {\n memcpy((char *) &childIndex, buffer + location, sizeof(childIndex));\n childIndices.push_back(childIndex);\n location += sizeof(childIndex);\n }\n }\n }\n\n \/\/ Store the current session to disk\n void storeSession() {\n \/\/ Create a character buffer which will be written to disk\n char buffer[PAGESIZE];\n long location = 0;\n\n \/\/ Store RRoot's fileIndex\n long fileIndex = RRoot->getFileIndex();\n memcpy(buffer + location, &fileIndex, sizeof(fileIndex));\n location += sizeof(fileIndex);\n\n \/\/ Store the global fileCount\n long fileCount = Node::getFileCount();\n memcpy(buffer + location, &fileCount, sizeof(fileCount));\n location += sizeof(fileCount);\n\n \/\/ Create a binary file and write to memory\n ofstream sessionFile(SESSION_FILE, ios::binary | ios::out);\n sessionFile.write(buffer, PAGESIZE);\n sessionFile.close();\n }\n\n void loadSession() {\n \/\/ Create a character buffer which will be written to disk\n long location = 0;\n char buffer[PAGESIZE];\n\n \/\/ Open the binary file ane read into memory\n ifstream sessionFile(SESSION_FILE, ios::binary | ios::in);\n sessionFile.read(buffer, PAGESIZE);\n sessionFile.close();\n\n \/\/ Retrieve the fileIndex of RRoot\n long fileIndex = 0;\n memcpy((char *) &fileIndex, buffer + location, sizeof(fileIndex));\n location += sizeof(fileIndex);\n\n \/\/ Retreive the global fileCount\n long fileCount = 0;\n memcpy((char *) &fileCount, buffer + location, sizeof(fileCount));\n location += sizeof(fileCount);\n\n \/\/ Store the session variables\n Node::setFileCount(fileCount);\n\n \/\/ Delete the current root and load it from disk\n delete RRoot;\n RRoot = new Node(fileIndex);\n RRoot->readNodeFromDisk();\n }\n};\n\nusing namespace RTree;\n\nint main() {\n \/\/ Initialize the BPlusTree module\n Node::initialize();\n\n \/\/ Create a new tree\n RRoot = new Node();\n\n \/\/ Load session or build a new tree\n \/\/ ifstream sessionFile(SESSION_FILE);\n \/\/ if (sessionFile.good()) {\n \/\/ loadSession();\n \/\/ } else {\n \/\/ buildTree();\n \/\/ }\n\n \/\/ Process queries\n \/\/ processQuery();\n\n cout << RRoot->getFileName();\n\n \/\/ Store the session\n \/\/ storeSession();\n\n return 0;\n}\n<commit_msg>Reorder static functions<commit_after>\/*\n * Copyright (c) 2015 Srijan R Shetty <srijan.shetty+code@gmail.com>\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy of\n * this software and associated documentation files (the \"Software\"), to deal in\n * the Software without restriction, including without limitation the rights to\n * use, copy, modify, merge, publish, distribute, sublicense, and\/or sell copies of\n * the Software, and to permit persons to whom the Software is furnished to do so,\n * subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS\n * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\n * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\n * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n *\/\n\n\n\/\/ Configuration parameters\n#include \".\/config.h\"\n\n\/\/ CONSTANTS\n#define NODE_PREFIX \"leaves\/leaf_\"\n#define SESSION_FILE \".tree.session\"\n#define DEFAULT -1\n\n\/\/ Standard Streams\n#include <iostream>\n#include <fstream>\n\n\/\/ STL\n#include <string>\n#include <cstring>\n#include <vector>\n#include <queue>\n#include <algorithm>\n\n\/\/ Math\n#include <math.h>\n#include <limits>\n\n\/\/ Timing\n#include <chrono>\n\n#include <stdlib.h>\n\nusing namespace std;\n\nnamespace RTree {\n class Node {\n private:\n static long fileCount;\n static long lowerBound;\n static long upperBound;\n\n public:\n \/\/ Initialize the lower and upper bounds\n static void initialize();\n\n \/\/ Get the fileCount\n static long getFileCount() { return fileCount; }\n\n \/\/ Set the fileCount\n static void setFileCount(long _fileCount) { Node::fileCount = _fileCount; }\n\n private:\n \/\/ Entries required to completely specify a node\n bool leaf = false;\n long fileIndex = DEFAULT;\n long parentIndex = DEFAULT;\n long sizeOfSubtree = DEFAULT;\n vector<long> upperPoints = vector<long>(DIMENSION, DEFAULT);\n vector<long> lowerPoints = vector<long>(DIMENSION, DEFAULT);\n\n \/\/ A node can store either of the below\n vector<long> childIndices;\n vector<long> objectIndices;\n\n public:\n \/\/ Construct a node object for the first time\n Node ();\n\n \/\/ Read a node from disk\n Node (long _fileIndex);\n\n \/\/ Get the role of the node\n bool isLeaf() const { return leaf; }\n\n \/\/ Get the index of the file\n long getFileIndex() const { return fileIndex; }\n\n \/\/ Get the name of the file\n string getFileName() const { return NODE_PREFIX + to_string(fileIndex); };\n\n \/\/ Store the node to disk\n void storeNodeToDisk() const;\n\n \/\/ Read the node from the disk\n void readNodeFromDisk();\n };\n\n \/\/ The root of the tree\n Node *RRoot = nullptr;\n\n \/\/ Initial static values\n long Node::fileCount = 0;\n long Node::lowerBound = 0;\n long Node::upperBound = 0;\n\n void Node::initialize() {\n \/\/ Save some place in the file for the header\n long headerSize =\n sizeof(leaf)\n + sizeof(fileIndex)\n + sizeof(parentIndex)\n + sizeof(sizeOfSubtree);\n long pageSize = PAGESIZE - headerSize;\n long keySize = sizeof(childIndices.front());\n long nodeSize = sizeof(fileIndex);\n\n \/\/ Compute the bounds\n upperBound = pageSize \/ (2 * DIMENSION * keySize + nodeSize);\n lowerBound = upperBound \/ 2;\n\n \/\/ TODO: clear this up\n upperBound = 10;\n lowerBound = 5;\n }\n\n Node::Node() {\n \/\/ Assign a fileIndex to the current node\n fileIndex = ++fileCount;\n }\n\n Node::Node(long _fileIndex) {\n \/\/ Assign the given fileIndex to the node\n fileIndex = _fileIndex;\n\n \/\/ Load the node from the disk\n readNodeFromDisk();\n }\n\n void Node::storeNodeToDisk() const {\n char buffer[PAGESIZE];\n long location = 0;\n\n \/\/ Store the contents to disk\n memcpy(buffer + location, &leaf, sizeof(leaf));\n location += sizeof(leaf);\n\n memcpy(buffer + location, &fileIndex, sizeof(fileIndex));\n location +=sizeof(fileIndex);\n\n memcpy(buffer + location, &parentIndex, sizeof(parentIndex));\n location += sizeof(parentIndex);\n\n memcpy(buffer + location, &sizeOfSubtree, sizeof(sizeOfSubtree));\n location += sizeof(sizeOfSubtree);\n\n \/\/ Add the bounds of the MBR to the tree\n for (auto upperPoint : upperPoints) {\n memcpy(buffer + location, &upperPoint, sizeof(upperPoint));\n location += sizeof(upperPoint);\n }\n\n for (auto lowerPoint : lowerPoints) {\n memcpy(buffer + location, &lowerPoint, sizeof(lowerPoint));\n location += sizeof(lowerPoint);\n }\n\n \/\/ We store the objects for a leaf and children for internal node\n if (!leaf) {\n \/\/ We have to store the bumber of children so that we can load them properly\n long numberOfChildren = childIndices.size();\n memcpy(buffer + location, &numberOfChildren, sizeof(numberOfChildren));\n location += sizeof(numberOfChildren);\n\n \/\/ Now we get the childIndices from the buffer\n for (long i = 0, childIndex = 0; i < numberOfChildren; ++i) {\n memcpy(buffer + location, &childIndex, sizeof(childIndex));\n location += sizeof(childIndex);\n }\n }\n\n \/\/ Now we copy the buffer to disk\n ofstream nodeFile(getFileName(), ios::binary | ios::out);\n nodeFile.write(buffer, PAGESIZE);\n nodeFile.close();\n }\n\n void Node::readNodeFromDisk() {\n \/\/ Create a char buffer to read contents from disk\n char buffer[PAGESIZE];\n long location = 0;\n\n \/\/ Open the binary file ane read into memory\n ifstream nodeFile(getFileName(), ios::binary | ios::in);\n nodeFile.read(buffer, PAGESIZE);\n nodeFile.close();\n\n \/\/ Retrieve the contents\n memcpy((char *) &leaf, buffer + location, sizeof(leaf));\n location += sizeof(leaf);\n\n memcpy((char *) &fileIndex, buffer + location, sizeof(fileIndex));\n location += sizeof(fileIndex);\n\n memcpy((char *) &parentIndex, buffer + location, sizeof(parentIndex));\n location += sizeof(parentIndex);\n\n memcpy((char *) &sizeOfSubtree, buffer + location, sizeof(sizeOfSubtree));\n location += sizeof(sizeOfSubtree);\n\n \/\/ Retrieve upperPoints\n upperPoints.clear();\n for (long i = 0, upperPoint = 0; i < DIMENSION; ++i) {\n memcpy((char *) &upperPoint, buffer + location, sizeof(upperPoint));\n upperPoints.push_back(upperPoint);\n location += sizeof(upperPoint);\n }\n\n \/\/ Retrieve lowerPoints\n lowerPoints.clear();\n for (long i = 0, lowerPoint = 0; i < DIMENSION; ++i) {\n memcpy((char *) &lowerPoint, buffer + location, sizeof(lowerPoint));\n lowerPoints.push_back(lowerPoint);\n location += sizeof(lowerPoint);\n }\n\n \/\/ We load the objects for a leaf and children for internal node\n if (!leaf) {\n \/\/ We need to get the number of children in this case\n long numberOfChildren = 0;\n memcpy((char *) &numberOfChildren, buffer + location, sizeof(numberOfChildren));\n location += sizeof(numberOfChildren);\n\n \/\/ Now we get the childIndices from the buffer\n childIndices.clear();\n for (long i = 0, childIndex = 0; i < numberOfChildren; ++i) {\n memcpy((char *) &childIndex, buffer + location, sizeof(childIndex));\n childIndices.push_back(childIndex);\n location += sizeof(childIndex);\n }\n }\n }\n\n \/\/ Store the current session to disk\n void storeSession() {\n \/\/ Create a character buffer which will be written to disk\n char buffer[PAGESIZE];\n long location = 0;\n\n \/\/ Store RRoot's fileIndex\n long fileIndex = RRoot->getFileIndex();\n memcpy(buffer + location, &fileIndex, sizeof(fileIndex));\n location += sizeof(fileIndex);\n\n \/\/ Store the global fileCount\n long fileCount = Node::getFileCount();\n memcpy(buffer + location, &fileCount, sizeof(fileCount));\n location += sizeof(fileCount);\n\n \/\/ Create a binary file and write to memory\n ofstream sessionFile(SESSION_FILE, ios::binary | ios::out);\n sessionFile.write(buffer, PAGESIZE);\n sessionFile.close();\n }\n\n void loadSession() {\n \/\/ Create a character buffer which will be written to disk\n long location = 0;\n char buffer[PAGESIZE];\n\n \/\/ Open the binary file ane read into memory\n ifstream sessionFile(SESSION_FILE, ios::binary | ios::in);\n sessionFile.read(buffer, PAGESIZE);\n sessionFile.close();\n\n \/\/ Retrieve the fileIndex of RRoot\n long fileIndex = 0;\n memcpy((char *) &fileIndex, buffer + location, sizeof(fileIndex));\n location += sizeof(fileIndex);\n\n \/\/ Retreive the global fileCount\n long fileCount = 0;\n memcpy((char *) &fileCount, buffer + location, sizeof(fileCount));\n location += sizeof(fileCount);\n\n \/\/ Store the session variables\n Node::setFileCount(fileCount);\n\n \/\/ Delete the current root and load it from disk\n delete RRoot;\n RRoot = new Node(fileIndex);\n RRoot->readNodeFromDisk();\n }\n};\n\nusing namespace RTree;\n\nint main() {\n \/\/ Initialize the BPlusTree module\n Node::initialize();\n\n \/\/ Create a new tree\n RRoot = new Node();\n\n \/\/ Load session or build a new tree\n \/\/ ifstream sessionFile(SESSION_FILE);\n \/\/ if (sessionFile.good()) {\n \/\/ loadSession();\n \/\/ } else {\n \/\/ buildTree();\n \/\/ }\n\n \/\/ Process queries\n \/\/ processQuery();\n\n cout << RRoot->getFileName();\n\n \/\/ Store the session\n \/\/ storeSession();\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>#ifndef ID_HXX_HQ5DONMJ\n#define ID_HXX_HQ5DONMJ\n\n#include \"string.hxx\"\n#include \"ptr.hxx\"\n#include \"ppr.hxx\"\n\n#include <string>\n#include <ostream>\n#include <functional>\n\nnamespace miniml\n{\n\n\/\/\/ Identifiers keep a hash for quick equality testing.\nclass Id final\n{\npublic:\n \/\/\/ Creates an identifier. \\a str isn't copied.\n Id(const Ptr<String> str):\n m_val(str),\n m_hash(make_hash(*str))\n { }\n\n \/\/\/ If the hashes are the same then the values are also checked in case of a\n \/\/\/ collision.\n \/\/\/ \\return Whether the two identifiers are the same.\n bool operator==(const Id &other) const\n { return m_hash == other.m_hash && m_val == other.m_val; }\n\n \/\/\/ \\return The value of the identifier.\n const Ptr<String> val() const { return m_val; }\n\n \/\/\/ \\return The identifier in \\ref String form.\n operator const Ptr<String>() const { return val(); }\n\n \/\/\/ Pretty prints an identifier.\n \/\/\/ \\relates PprString\n const Ptr<Ppr> ppr() const { return ppr::string(*val()); }\n\nprivate:\n \/\/\/ Hash function for \\ref String.\n static std::hash<String> make_hash;\n\n const Ptr<String> m_val; \/\/\/< Value.\n unsigned long m_hash; \/\/\/< Hash.\n};\n\n\n\/\/\/ Outputs an identifier to the given output stream.\ninline OStream& operator<<(OStream &out, const Id &id)\n{\n return out << *id.val();\n}\n\n}\n\n#endif \/* end of include guard: ID_HXX_HQ5DONMJ *\/\n<commit_msg>Add constructor Id(const String&)<commit_after>#ifndef ID_HXX_HQ5DONMJ\n#define ID_HXX_HQ5DONMJ\n\n#include \"string.hxx\"\n#include \"ptr.hxx\"\n#include \"ppr.hxx\"\n\n#include <string>\n#include <ostream>\n#include <functional>\n\nnamespace miniml\n{\n\n\/\/\/ Identifiers keep a hash for quick equality testing.\nclass Id final\n{\npublic:\n \/\/\/ Creates an identifier. \\a str isn't copied.\n Id(const Ptr<String> str):\n m_val(str),\n m_hash(make_hash(*str))\n { }\n\n \/\/\/ Copies a string onto the heap and constructs an identifier from it.\n Id(const String &str):\n Id(ptr<String>(str))\n { }\n\n \/\/\/ If the hashes are the same then the values are also checked in case of a\n \/\/\/ collision.\n \/\/\/ \\return Whether the two identifiers are the same.\n bool operator==(const Id &other) const\n { return m_hash == other.m_hash && m_val == other.m_val; }\n\n \/\/\/ \\return The value of the identifier.\n const Ptr<String> val() const { return m_val; }\n\n \/\/\/ \\return The identifier in \\ref String form.\n operator const Ptr<String>() const { return val(); }\n\n \/\/\/ Pretty prints an identifier.\n \/\/\/ \\relates PprString\n const Ptr<Ppr> ppr() const { return ppr::string(*val()); }\n\nprivate:\n \/\/\/ Hash function for \\ref String.\n static std::hash<String> make_hash;\n\n const Ptr<String> m_val; \/\/\/< Value.\n unsigned long m_hash; \/\/\/< Hash.\n};\n\n\n\/\/\/ Outputs an identifier to the given output stream.\ninline OStream& operator<<(OStream &out, const Id &id)\n{\n return out << *id.val();\n}\n\n}\n\n#endif \/* end of include guard: ID_HXX_HQ5DONMJ *\/\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * Copyright 2016 Realm Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n **************************************************************************\/\n\n#ifndef REALM_UTIL_ASSERT_HPP\n#define REALM_UTIL_ASSERT_HPP\n\n#include <realm\/util\/features.h>\n#include <realm\/util\/terminate.hpp>\n\n#if REALM_ENABLE_ASSERTIONS || defined(REALM_DEBUG)\n#define REALM_ASSERTIONS_ENABLED 1\n#else\n#define REALM_ASSERTIONS_ENABLED 0\n#endif\n\n#define REALM_ASSERT_RELEASE(condition) \\\n (REALM_LIKELY(condition) ? static_cast<void>(0) \\\n : realm::util::terminate(\"Assertion failed: \" #condition, __FILE__, __LINE__))\n\n#if REALM_ASSERTIONS_ENABLED\n#define REALM_ASSERT(condition) REALM_ASSERT_RELEASE(condition)\n#else\n#define REALM_ASSERT(condition) static_cast<void>(sizeof bool(condition))\n#endif\n\n#ifdef REALM_DEBUG\n#define REALM_ASSERT_DEBUG(condition) REALM_ASSERT_RELEASE(condition)\n#else\n#define REALM_ASSERT_DEBUG(condition) static_cast<void>(sizeof bool(condition))\n#endif\n\n#define REALM_STRINGIFY(X) #X\n\n#define REALM_ASSERT_RELEASE_EX(condition, ...) \\\n (REALM_LIKELY(condition) ? static_cast<void>(0) \\\n : realm::util::terminate_with_info(\"Assertion failed: \" #condition, __LINE__, __FILE__, \\\n REALM_STRINGIFY((__VA_ARGS__)), __VA_ARGS__))\n\n#ifdef REALM_DEBUG\n#define REALM_ASSERT_DEBUG_EX REALM_ASSERT_RELEASE_EX\n#else\n#define REALM_ASSERT_DEBUG_EX(condition, ...) static_cast<void>(sizeof bool(condition))\n#endif\n\n\/\/ Becase the assert is used in noexcept methods, it's a bad idea to allocate\n\/\/ buffer space for the message so therefore we must pass it to terminate which\n\/\/ will 'cerr' it for us without needing any buffer\n#if REALM_ENABLE_ASSERTIONS || defined(REALM_DEBUG)\n\n#define REALM_ASSERT_EX REALM_ASSERT_RELEASE_EX\n\n#define REALM_ASSERT_3(left, cmp, right) \\\n (REALM_LIKELY((left)cmp(right)) ? static_cast<void>(0) \\\n : realm::util::terminate(\"Assertion failed: \" \\\n \"\" #left \" \" #cmp \" \" #right, \\\n __FILE__, __LINE__, left, right))\n\n#define REALM_ASSERT_7(left1, cmp1, right1, logical, left2, cmp2, right2) \\\n (REALM_LIKELY(((left1)cmp1(right1))logical((left2)cmp2(right2))) \\\n ? static_cast<void>(0) \\\n : realm::util::terminate(\"Assertion failed: \" \\\n \"\" #left1 \" \" #cmp1 \" \" #right1 \" \" #logical \" \" \\\n \"\" #left2 \" \" #cmp2 \" \" #right2, \\\n __FILE__, __LINE__, left1, right1, left2, right2))\n\n#define REALM_ASSERT_11(left1, cmp1, right1, logical1, left2, cmp2, right2, logical2, left3, cmp3, right3) \\\n (REALM_LIKELY(((left1)cmp1(right1))logical1((left2)cmp2(right2)) logical2((left3)cmp3(right3))) \\\n ? static_cast<void>(0) \\\n : realm::util::terminate(\"Assertion failed: \" \\\n \"\" #left1 \" \" #cmp1 \" \" #right1 \" \" #logical1 \" \" \\\n \"\" #left2 \" \" #cmp2 \" \" #right2 \" \" #logical2 \" \" \\\n \"\" #left3 \" \" #cmp3 \" \" #right3, \\\n __FILE__, __LINE__, left1, right1, left2, right2, left3, right3))\n#else\n#define REALM_ASSERT_EX(condition, ...) static_cast<void>(sizeof bool(condition))\n#define REALM_ASSERT_3(left, cmp, right) static_cast<void>(sizeof bool((left)cmp(right)))\n#define REALM_ASSERT_7(left1, cmp1, right1, logical, left2, cmp2, right2) \\\n static_cast<void>(sizeof bool(((left1)cmp1(right1))logical((left2)cmp2(right2))))\n#define REALM_ASSERT_11(left1, cmp1, right1, logical1, left2, cmp2, right2, logical2, left3, cmp3, right3) \\\n static_cast<void>(sizeof bool(((left1)cmp1(right1))logical1((left2)cmp2(right2)) logical2((left3)cmp3(right3))))\n#endif\n\n#ifdef REALM_COVER\n#define REALM_UNREACHABLE()\n#define REALM_COVER_NEVER(x) false\n#define REALM_COVER_ALWAYS(x) true\n#else\n#define REALM_UNREACHABLE() realm::util::terminate(\"Unreachable code\", __FILE__, __LINE__)\n#define REALM_COVER_NEVER(x) (x)\n#define REALM_COVER_ALWAYS(x) (x)\n#endif\n\n#endif \/\/ REALM_UTIL_ASSERT_HPP\n<commit_msg>Always call realm::util::terminate() from REALM_UNREACHABLE() to avoid noreturn warnings in coverage mode<commit_after>\/*************************************************************************\n *\n * Copyright 2016 Realm Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n **************************************************************************\/\n\n#ifndef REALM_UTIL_ASSERT_HPP\n#define REALM_UTIL_ASSERT_HPP\n\n#include <realm\/util\/features.h>\n#include <realm\/util\/terminate.hpp>\n\n#if REALM_ENABLE_ASSERTIONS || defined(REALM_DEBUG)\n#define REALM_ASSERTIONS_ENABLED 1\n#else\n#define REALM_ASSERTIONS_ENABLED 0\n#endif\n\n#define REALM_ASSERT_RELEASE(condition) \\\n (REALM_LIKELY(condition) ? static_cast<void>(0) \\\n : realm::util::terminate(\"Assertion failed: \" #condition, __FILE__, __LINE__))\n\n#if REALM_ASSERTIONS_ENABLED\n#define REALM_ASSERT(condition) REALM_ASSERT_RELEASE(condition)\n#else\n#define REALM_ASSERT(condition) static_cast<void>(sizeof bool(condition))\n#endif\n\n#ifdef REALM_DEBUG\n#define REALM_ASSERT_DEBUG(condition) REALM_ASSERT_RELEASE(condition)\n#else\n#define REALM_ASSERT_DEBUG(condition) static_cast<void>(sizeof bool(condition))\n#endif\n\n#define REALM_STRINGIFY(X) #X\n\n#define REALM_ASSERT_RELEASE_EX(condition, ...) \\\n (REALM_LIKELY(condition) ? static_cast<void>(0) \\\n : realm::util::terminate_with_info(\"Assertion failed: \" #condition, __LINE__, __FILE__, \\\n REALM_STRINGIFY((__VA_ARGS__)), __VA_ARGS__))\n\n#ifdef REALM_DEBUG\n#define REALM_ASSERT_DEBUG_EX REALM_ASSERT_RELEASE_EX\n#else\n#define REALM_ASSERT_DEBUG_EX(condition, ...) static_cast<void>(sizeof bool(condition))\n#endif\n\n\/\/ Becase the assert is used in noexcept methods, it's a bad idea to allocate\n\/\/ buffer space for the message so therefore we must pass it to terminate which\n\/\/ will 'cerr' it for us without needing any buffer\n#if REALM_ENABLE_ASSERTIONS || defined(REALM_DEBUG)\n\n#define REALM_ASSERT_EX REALM_ASSERT_RELEASE_EX\n\n#define REALM_ASSERT_3(left, cmp, right) \\\n (REALM_LIKELY((left)cmp(right)) ? static_cast<void>(0) \\\n : realm::util::terminate(\"Assertion failed: \" \\\n \"\" #left \" \" #cmp \" \" #right, \\\n __FILE__, __LINE__, left, right))\n\n#define REALM_ASSERT_7(left1, cmp1, right1, logical, left2, cmp2, right2) \\\n (REALM_LIKELY(((left1)cmp1(right1))logical((left2)cmp2(right2))) \\\n ? static_cast<void>(0) \\\n : realm::util::terminate(\"Assertion failed: \" \\\n \"\" #left1 \" \" #cmp1 \" \" #right1 \" \" #logical \" \" \\\n \"\" #left2 \" \" #cmp2 \" \" #right2, \\\n __FILE__, __LINE__, left1, right1, left2, right2))\n\n#define REALM_ASSERT_11(left1, cmp1, right1, logical1, left2, cmp2, right2, logical2, left3, cmp3, right3) \\\n (REALM_LIKELY(((left1)cmp1(right1))logical1((left2)cmp2(right2)) logical2((left3)cmp3(right3))) \\\n ? static_cast<void>(0) \\\n : realm::util::terminate(\"Assertion failed: \" \\\n \"\" #left1 \" \" #cmp1 \" \" #right1 \" \" #logical1 \" \" \\\n \"\" #left2 \" \" #cmp2 \" \" #right2 \" \" #logical2 \" \" \\\n \"\" #left3 \" \" #cmp3 \" \" #right3, \\\n __FILE__, __LINE__, left1, right1, left2, right2, left3, right3))\n#else\n#define REALM_ASSERT_EX(condition, ...) static_cast<void>(sizeof bool(condition))\n#define REALM_ASSERT_3(left, cmp, right) static_cast<void>(sizeof bool((left)cmp(right)))\n#define REALM_ASSERT_7(left1, cmp1, right1, logical, left2, cmp2, right2) \\\n static_cast<void>(sizeof bool(((left1)cmp1(right1))logical((left2)cmp2(right2))))\n#define REALM_ASSERT_11(left1, cmp1, right1, logical1, left2, cmp2, right2, logical2, left3, cmp3, right3) \\\n static_cast<void>(sizeof bool(((left1)cmp1(right1))logical1((left2)cmp2(right2)) logical2((left3)cmp3(right3))))\n#endif\n\n#define REALM_UNREACHABLE() realm::util::terminate(\"Unreachable code\", __FILE__, __LINE__)\n#ifdef REALM_COVER\n#define REALM_COVER_NEVER(x) false\n#define REALM_COVER_ALWAYS(x) true\n#else\n#define REALM_COVER_NEVER(x) (x)\n#define REALM_COVER_ALWAYS(x) (x)\n#endif\n\n#endif \/\/ REALM_UTIL_ASSERT_HPP\n<|endoftext|>"} {"text":"<commit_before>\/*\r\n-----------------------------------------------------------------------------\r\nFilename: BaseApplication.cpp\r\n-----------------------------------------------------------------------------\r\n\r\nThis source file is part of the\r\n ___ __ __ _ _ _ \r\n \/___\\__ _ _ __ ___ \/ \/ \/\\ \\ (_) | _(_)\r\n \/\/ \/\/ _` | '__\/ _ \\ \\ \\\/ \\\/ \/ | |\/ \/ |\r\n\/ \\_\/\/ (_| | | | __\/ \\ \/\\ \/| | <| |\r\n\\___\/ \\__, |_| \\___| \\\/ \\\/ |_|_|\\_\\_|\r\n |___\/ \r\n Tutorial Framework\r\n http:\/\/www.ogre3d.org\/tikiwiki\/\r\n-----------------------------------------------------------------------------\r\n*\/\r\n#include \"stdafx.h\"\r\n#include \"BaseApplication.h\"\r\n\r\n\/\/-------------------------------------------------------------------------------------\r\nBaseApplication::BaseApplication(void)\r\n : mRoot(0),\r\n mSceneMgr(0),\r\n mWindow(0),\r\n mResourcesCfg(Ogre::StringUtil::BLANK),\r\n mPluginsCfg(Ogre::StringUtil::BLANK),\r\n mCursorWasVisible(false),\r\n mShutDown(false),\r\n mInputManager(0),\r\n mMouse(0),\r\n mKeyboard(0)\r\n{\r\n}\r\n\r\n\/\/-------------------------------------------------------------------------------------\r\nBaseApplication::~BaseApplication(void)\r\n{\r\n\tdelete mController;\r\n \/\/Remove ourself as a Window listener\r\n Ogre::WindowEventUtilities::removeWindowEventListener(mWindow, this);\r\n windowClosed(mWindow);\r\n delete mRoot;\r\n}\r\n\r\n\tHWND mWindowHandle ;\r\n\tHWND mExternalWindow = (HWND)(0x000707EC);\r\n\r\nLRESULT CALLBACK _WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)\r\n{\r\n\t\/\/note can use with OIS but need to pass more than just the mouse down message\r\n\tDWORD dwPID;\r\n\tbool posted = false;\r\n\tDWORD hThread ;\r\n\thThread = GetWindowThreadProcessId(mExternalWindow, &dwPID); \r\n\tif (dwPID != NULL && hThread!= NULL ) \r\n\t{\r\n\t\tSendMessage(mExternalWindow, msg, wParam, lParam);\r\n\t}\r\n\treturn DefWindowProc( hwnd, msg, wParam, lParam );\r\n\treturn 0;\r\n}\r\n\r\n\/\/-------------------------------------------------------------------------------------\r\nbool BaseApplication::configure(void)\r\n{\r\n \/\/ Show the configuration dialog and initialise the system\r\n \/\/ You can skip this and use root.restoreConfig() to load configuration\r\n \/\/ settings if you were sure there are valid ones saved in ogre.cfg\r\n if(mRoot->showConfigDialog())\r\n {\r\n\t\t\/\/ If returned true, user clicked OK so initialise\r\n\t\t\t\/\/ Here we choose to let the system create a default rendering window by passing 'true'\r\n\t\t\t\/\/mWindow = mRoot->initialise(true, \"Riftop\");\r\n\t\tmRoot->initialise(false);\r\n\t\tUINT classStyle = 0;\r\n\r\n\t\tHINSTANCE hInst = NULL;\r\n\r\n\t\t\/\/ Register the window class\r\n\t\t\/\/ NB allow 4 bytes of window data for D3D11RenderWindow pointer\r\n\t\tWNDCLASS wc = { classStyle, _WndProc, 0, 0, hInst,\r\n\t\t\tLoadIcon(0, IDI_APPLICATION), LoadCursor(NULL, IDC_ARROW),\r\n\t\t\t(HBRUSH)GetStockObject(BLACK_BRUSH), 0, \"rwnd\" };\t\r\n\r\n\t\tRegisterClass(&wc);\r\n\r\n\t\tDWORD dwStyle = WS_VISIBLE | WS_CLIPCHILDREN;\r\n\r\n\t\t\/\/ Create our main window\r\n\t\t\/\/ Pass pointer to self\r\n\t\tmWindowHandle = CreateWindowA(\"rwnd\", \"Riftop\", dwStyle,\r\n\t\t\t0, 0, 1280, 800, NULL, 0, hInst, this);\r\n\r\n\t\tNameValuePairList misc;\r\n\t\tmisc[\"externalWindowHandle\"] = StringConverter::toString((int)mWindowHandle);\r\n\t\t\/\/misc[\"fullScreen\"] = true;\r\n\t\tmWindow = mRoot->createRenderWindow(\"Main RenderWindow\", 1280, 800, false, &misc);\r\n\t\t\/\/Ogre::WindowEventUtilities::_addRenderWindow(mWindow);\r\n\r\n return true;\r\n }\r\n else\r\n {\r\n return false;\r\n }\r\n}\r\n\/\/-------------------------------------------------------------------------------------\r\nvoid BaseApplication::chooseSceneManager(void)\r\n{\r\n \/\/ Get the SceneManager, in this case a generic one\r\n mSceneMgr = mRoot->createSceneManager(Ogre::ST_GENERIC);\r\n}\r\n\/\/-------------------------------------------------------------------------------------\r\n\/\/-------------------------------------------------------------------------------------\r\nvoid BaseApplication::createFrameListener(void)\r\n{\r\n Ogre::LogManager::getSingletonPtr()->logMessage(\"*** Initializing OIS ***\");\r\n OIS::ParamList pl;\r\n size_t windowHnd = 0;\r\n std::ostringstream windowHndStr;\r\n\r\n mWindow->getCustomAttribute(\"WINDOW\", &windowHnd);\r\n windowHndStr << windowHnd;\r\n pl.insert(std::make_pair(std::string(\"WINDOW\"), windowHndStr.str()));\r\n\r\n mInputManager = OIS::InputManager::createInputSystem( pl );\r\n\r\n mKeyboard = static_cast<OIS::Keyboard*>(mInputManager->createInputObject( OIS::OISKeyboard, true ));\r\n mMouse = static_cast<OIS::Mouse*>(mInputManager->createInputObject( OIS::OISMouse, true ));\r\n\r\n mMouse->setEventCallback(this);\r\n mKeyboard->setEventCallback(this);\r\n\r\n \/\/Set initial mouse clipping size\r\n windowResized(mWindow);\r\n\r\n \/\/Register as a Window listener\r\n Ogre::WindowEventUtilities::addWindowEventListener(mWindow, this);\r\n\r\n \/\/ create a params panel for displaying sample details\r\n Ogre::StringVector items;\r\n items.push_back(\"cam.pX\");\r\n items.push_back(\"cam.pY\");\r\n items.push_back(\"cam.pZ\");\r\n items.push_back(\"\");\r\n items.push_back(\"cam.oW\");\r\n items.push_back(\"cam.oX\");\r\n items.push_back(\"cam.oY\");\r\n items.push_back(\"cam.oZ\");\r\n items.push_back(\"\");\r\n items.push_back(\"Filtering\");\r\n items.push_back(\"Poly Mode\");\r\n\r\n mRoot->addFrameListener(this);\r\n}\r\n\/\/-------------------------------------------------------------------------------------\r\nvoid BaseApplication::destroyScene(void)\r\n{\r\n}\r\n\/\/-------------------------------------------------------------------------------------\r\nvoid BaseApplication::createViewports(void)\r\n{\r\n\t\r\n}\r\n\/\/-------------------------------------------------------------------------------------\r\nvoid BaseApplication::setupResources(void)\r\n{\r\n \/\/ Load resource paths from config file\r\n Ogre::ConfigFile cf;\r\n cf.load(mResourcesCfg);\r\n\r\n \/\/ Go through all sections & settings in the file\r\n Ogre::ConfigFile::SectionIterator seci = cf.getSectionIterator();\r\n\r\n Ogre::String secName, typeName, archName;\r\n while (seci.hasMoreElements())\r\n {\r\n secName = seci.peekNextKey();\r\n Ogre::ConfigFile::SettingsMultiMap *settings = seci.getNext();\r\n Ogre::ConfigFile::SettingsMultiMap::iterator i;\r\n for (i = settings->begin(); i != settings->end(); ++i)\r\n {\r\n typeName = i->first;\r\n archName = i->second;\r\n Ogre::ResourceGroupManager::getSingleton().addResourceLocation(\r\n archName, typeName, secName);\r\n }\r\n }\r\n}\r\n\/\/-------------------------------------------------------------------------------------\r\nvoid BaseApplication::createResourceListener(void)\r\n{\r\n\r\n}\r\n\/\/-------------------------------------------------------------------------------------\r\nvoid BaseApplication::loadResources(void)\r\n{\r\n\tOgre::ResourceGroupManager::getSingleton().createResourceGroup(Ogre::RTShader::ShaderGenerator::DEFAULT_SCHEME_NAME);\r\n Ogre::ResourceGroupManager::getSingleton().initialiseAllResourceGroups();\r\n\r\n\tif (Ogre::RTShader::ShaderGenerator::initialize())\r\n\t{\r\n\t\t\/\/ Grab the shader generator pointer.\r\n\t\tmShaderGenerator = Ogre::RTShader::ShaderGenerator::getSingletonPtr();\r\n \r\n\t\t\/\/ Add the shader libs resource location.\r\n\t\tOgre::ResourceGroupManager::getSingleton().addResourceLocation(\"D:\\\\Project\\\\Ogre\\\\OgreSource\\\\Samples\\\\Media\\\\RTShaderLib\\\\Cg\", \"FileSystem\");\r\n \r\n\t\t\/\/ Set shader cache path.\r\n\t\tmShaderGenerator->setShaderCachePath(\"D:\\\\Project\\\\WolfGame\\\\WolfGame\\\\Debug\\\\shaders\");\t\t\r\n\t\t\/\/mShaderGenerator->\r\n\t\t\/\/ Set the scene manager.\r\n\t\tmShaderGenerator->addSceneManager(mSceneMgr);\r\n \r\n\t\t\/\/ Add a specialized sub-render (per-pixel lighting) state to the default scheme render state\r\n\t\tOgre::RTShader::RenderState* pMainRenderState = \r\n\t\t\tmShaderGenerator->createOrRetrieveRenderState(Ogre::RTShader::ShaderGenerator::DEFAULT_SCHEME_NAME).first;\r\n\t\tpMainRenderState->reset();\r\n \r\n\t\t\/\/mShaderGenerator->addSubRenderStateFactory(new Ogre::RTShader::PerPixelLightingFactory);\r\n\t\tpMainRenderState->addTemplateSubRenderState(\r\n\t\t\tmShaderGenerator->createSubRenderState(Ogre::RTShader::FFPTexturing::Type));\t\r\n \r\n\t\t\/\/return true;\r\n\t}\r\n\t\r\n\tmShaderGenerator->createShaderBasedTechnique(\"box\/singlelight\", Ogre::MaterialManager::DEFAULT_SCHEME_NAME, Ogre::RTShader::ShaderGenerator::DEFAULT_SCHEME_NAME);\r\n\t\r\n}\r\n\/\/-------------------------------------------------------------------------------------\r\nvoid BaseApplication::go(void)\r\n{\r\n#ifdef _DEBUG\r\n mResourcesCfg = \"D:\\\\Project\\\\WolfGame\\\\WolfGame\\\\Debug\\\\resources_d.cfg\";\r\n mPluginsCfg = \"D:\\\\Project\\\\WolfGame\\\\WolfGame\\\\Debug\\\\plugins_d.cfg\";\r\n#else\r\n mResourcesCfg = \".\\\\resources.cfg\";\r\n mPluginsCfg = \".\\\\plugins.cfg\";\r\n#endif\r\n\r\n if (!setup())\r\n return;\r\n\r\n mRoot->startRendering();\r\n\r\n \/\/ clean up\r\n destroyScene();\r\n}\r\n\/\/-------------------------------------------------------------------------------------\r\nbool BaseApplication::setup(void)\r\n{\r\n mRoot = new Ogre::Root(mPluginsCfg);\r\n\r\n setupResources();\r\n\r\n bool carryOn = configure();\r\n if (!carryOn) return false;\r\n\r\n chooseSceneManager();\r\n\r\n\t\/\/ Set default mipmap level (NB some APIs ignore this)\r\n Ogre::TextureManager::getSingleton().setDefaultNumMipmaps(5);\r\n\r\n \/\/ Create any resource listeners (for loading screens)\r\n createResourceListener();\r\n \/\/ Load resources\r\n loadResources();\r\n\r\n\tm_Windows = new SystemWindowManager( mSceneMgr, mShaderGenerator);\r\n\tm_Windows->RefreshWindowHandles();\r\n\t\/\/window->DisplayWindow();\r\n\r\n\tmOculus = new OculusControl();\r\n\tmController = new CameraController::Controller(mWindow);\r\n mController->createCameras(mSceneMgr);\r\n\r\n\tif(mOculus->isInitialised())\r\n\t{\r\n\t\tmController->createViewports(mOculus->getDeviceInfo());\r\n\t}\r\n\telse\r\n\t{\r\n\t\tmController->createViewports();\r\n\t}\r\n\t\r\n\r\n\t\r\n\tmPlayer = new Player(mSceneMgr, mController->mBodyRotationNode);\r\n\r\n\tmScene = new WarehouseFloor(mSceneMgr);\r\n\tmWarehouseShown = true;\r\n createScene();\r\n\r\n createFrameListener();\r\n\r\n return true;\r\n};\r\n\/\/-------------------------------------------------------------------------------------\r\nbool BaseApplication::frameRenderingQueued(const Ogre::FrameEvent& evt)\r\n{\r\n if(mWindow->isClosed())\r\n return false;\r\n\r\n if(mShutDown)\r\n return false;\r\n\t\r\n\r\n\r\n \/\/Need to capture\/update each device\r\n mKeyboard->capture();\r\n mMouse->capture();\r\n\t\/\/mBullet->StepPhysics(evt.timeSinceLastFrame);\r\n\tmController->mRotationNode->setOrientation(mOculus->getOrientation());\r\n\tmPlayer->processMovement(evt.timeSinceLastFrame);\r\n return true;\r\n}\r\n\/\/-------------------------------------------------------------------------------------\r\nbool BaseApplication::keyPressed( const OIS::KeyEvent &arg )\r\n{\r\n\t\/*if(arg.key == OIS::KC_1)\r\n {\r\n\t\tif(!mWarehouseShown )\r\n\t\t{\r\n\t\t\tmScene = new WarehouseFloor(mSceneMgr);\r\n\t\t\tmWarehouseShown = true;\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tdelete mScene;\r\n\t\t\tmWarehouseShown = false;\r\n\t\t}\r\n }*\/\r\n\r\n\r\n\tif(arg.key == OIS::KC_A)\r\n {\r\n\t\tmPlayer->addKeyboardInput(Ogre::Vector3(-1,0,0));\r\n }\r\n\telse if(arg.key == OIS::KC_D)\r\n {\r\n mPlayer->addKeyboardInput(Ogre::Vector3(1,0,0));\r\n }\r\n\telse if(arg.key == OIS::KC_S)\r\n {\r\n mPlayer->addKeyboardInput(Ogre::Vector3(0,0,1));\r\n }\r\n\telse if(arg.key == OIS::KC_W)\r\n {\r\n mPlayer->addKeyboardInput(Ogre::Vector3(0,0,-1));\r\n }\r\n else if(arg.key == OIS::KC_F5) \/\/ refresh all textures\r\n {\r\n Ogre::TextureManager::getSingleton().reloadAll();\r\n }\r\n\telse if(arg.key == OIS::KC_SPACE)\r\n {\r\n\t\tm_Windows->ShowThumbnails();\r\n \/\/mPlayer->jump();\r\n }\r\n else if (arg.key == OIS::KC_SYSRQ) \/\/ take a screenshot\r\n {\r\n mWindow->writeContentsToTimestampedFile(\"screenshot\", \".jpg\");\r\n }\r\n else if (arg.key == OIS::KC_ESCAPE)\r\n {\r\n mShutDown = true;\r\n }\r\n\telse if(arg.key == OIS::KC_LCONTROL)\r\n {\r\n mPlayer->changeHeight(true);\r\n }\r\n return true;\r\n}\r\n\r\nbool BaseApplication::keyReleased( const OIS::KeyEvent &arg )\r\n{\r\n\tif(arg.key == OIS::KC_A)\r\n {\r\n\t\tmPlayer->addKeyboardInput(Ogre::Vector3(1,0,0));\r\n }\r\n\telse if(arg.key == OIS::KC_D)\r\n {\r\n mPlayer->addKeyboardInput(Ogre::Vector3(-1,0,0));\r\n }\r\n\telse if(arg.key == OIS::KC_S)\r\n {\r\n mPlayer->addKeyboardInput(Ogre::Vector3(0,0,-1));\r\n }\r\n\telse if(arg.key == OIS::KC_W)\r\n {\r\n mPlayer->addKeyboardInput(Ogre::Vector3(0,0,1));\r\n }\r\n\telse if(arg.key == OIS::KC_LCONTROL)\r\n {\r\n mPlayer->changeHeight(false);\r\n }\r\n\telse if(arg.key == OIS::KC_SPACE)\r\n {\r\n\t\tm_Windows->RemoveThumbnails();\r\n \/\/mPlayer->jump();\r\n }\r\n\t\r\n return true;\r\n}\r\n\r\nbool BaseApplication::mouseMoved( const OIS::MouseEvent &arg )\r\n{\r\n\tmPlayer->mouseInput(Ogre::Vector2(arg.state.X.rel, arg.state.Y.rel));\r\n return true;\r\n}\r\n\r\nbool BaseApplication::mousePressed( const OIS::MouseEvent &arg, OIS::MouseButtonID id )\r\n{\r\n\tmPlayer->step();\r\n return true;\r\n}\r\n\r\nbool BaseApplication::mouseReleased( const OIS::MouseEvent &arg, OIS::MouseButtonID id )\r\n{\r\n return true;\r\n}\r\n\r\n\/\/Adjust mouse clipping area\r\nvoid BaseApplication::windowResized(Ogre::RenderWindow* rw)\r\n{\r\n unsigned int width, height, depth;\r\n int left, top;\r\n rw->getMetrics(width, height, depth, left, top);\r\n\r\n const OIS::MouseState &ms = mMouse->getMouseState();\r\n ms.width = width;\r\n ms.height = height;\r\n}\r\n\r\n\/\/Unattach OIS before window shutdown (very important under Linux)\r\nvoid BaseApplication::windowClosed(Ogre::RenderWindow* rw)\r\n{\r\n \/\/Only close for window that created OIS (the main window in these demos)\r\n if( rw == mWindow )\r\n {\r\n if( mInputManager )\r\n {\r\n \/\/mInputManager->destroyInputObject( mMouse );\r\n \/\/mInputManager->destroyInputObject( mKeyboard );\r\n\r\n OIS::InputManager::destroyInputSystem(mInputManager);\r\n mInputManager = 0;\r\n }\r\n }\r\n}\r\n<commit_msg>a bit of cleanup for unused control<commit_after>\/*\r\n-----------------------------------------------------------------------------\r\nFilename: BaseApplication.cpp\r\n-----------------------------------------------------------------------------\r\n\r\nThis source file is part of the\r\n ___ __ __ _ _ _ \r\n \/___\\__ _ _ __ ___ \/ \/ \/\\ \\ (_) | _(_)\r\n \/\/ \/\/ _` | '__\/ _ \\ \\ \\\/ \\\/ \/ | |\/ \/ |\r\n\/ \\_\/\/ (_| | | | __\/ \\ \/\\ \/| | <| |\r\n\\___\/ \\__, |_| \\___| \\\/ \\\/ |_|_|\\_\\_|\r\n |___\/ \r\n Tutorial Framework\r\n http:\/\/www.ogre3d.org\/tikiwiki\/\r\n-----------------------------------------------------------------------------\r\n*\/\r\n#include \"stdafx.h\"\r\n#include \"BaseApplication.h\"\r\n\r\n\/\/-------------------------------------------------------------------------------------\r\nBaseApplication::BaseApplication(void)\r\n : mRoot(0),\r\n mSceneMgr(0),\r\n mWindow(0),\r\n mResourcesCfg(Ogre::StringUtil::BLANK),\r\n mPluginsCfg(Ogre::StringUtil::BLANK),\r\n mCursorWasVisible(false),\r\n mShutDown(false),\r\n mInputManager(0),\r\n mMouse(0),\r\n mKeyboard(0)\r\n{\r\n}\r\n\r\n\/\/-------------------------------------------------------------------------------------\r\nBaseApplication::~BaseApplication(void)\r\n{\r\n\tdelete mController;\r\n \/\/Remove ourself as a Window listener\r\n Ogre::WindowEventUtilities::removeWindowEventListener(mWindow, this);\r\n windowClosed(mWindow);\r\n delete mRoot;\r\n}\r\n\r\n\tHWND mWindowHandle ;\r\n\tHWND mExternalWindow = (HWND)(0x000707EC);\r\n\r\nLRESULT CALLBACK _WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)\r\n{\r\n\t\/\/note can use with OIS but need to pass more than just the mouse down message\r\n\tDWORD dwPID;\r\n\tbool posted = false;\r\n\tDWORD hThread ;\r\n\thThread = GetWindowThreadProcessId(mExternalWindow, &dwPID); \r\n\tif (dwPID != NULL && hThread!= NULL ) \r\n\t{\r\n\t\tSendMessage(mExternalWindow, msg, wParam, lParam);\r\n\t}\r\n\treturn DefWindowProc( hwnd, msg, wParam, lParam );\r\n\treturn 0;\r\n}\r\n\r\n\/\/-------------------------------------------------------------------------------------\r\nbool BaseApplication::configure(void)\r\n{\r\n \/\/ Show the configuration dialog and initialise the system\r\n \/\/ You can skip this and use root.restoreConfig() to load configuration\r\n \/\/ settings if you were sure there are valid ones saved in ogre.cfg\r\n if(mRoot->showConfigDialog())\r\n {\r\n\t\t\/\/ If returned true, user clicked OK so initialise\r\n\t\t\t\/\/ Here we choose to let the system create a default rendering window by passing 'true'\r\n\t\t\t\/\/mWindow = mRoot->initialise(true, \"Riftop\");\r\n\t\tmRoot->initialise(false);\r\n\t\tUINT classStyle = 0;\r\n\r\n\t\tHINSTANCE hInst = NULL;\r\n\r\n\t\t\/\/ Register the window class\r\n\t\t\/\/ NB allow 4 bytes of window data for D3D11RenderWindow pointer\r\n\t\tWNDCLASS wc = { classStyle, _WndProc, 0, 0, hInst,\r\n\t\t\tLoadIcon(0, IDI_APPLICATION), LoadCursor(NULL, IDC_ARROW),\r\n\t\t\t(HBRUSH)GetStockObject(BLACK_BRUSH), 0, \"rwnd\" };\t\r\n\r\n\t\tRegisterClass(&wc);\r\n\r\n\t\tDWORD dwStyle = WS_VISIBLE | WS_CLIPCHILDREN;\r\n\r\n\t\t\/\/ Create our main window\r\n\t\t\/\/ Pass pointer to self\r\n\t\tmWindowHandle = CreateWindowA(\"rwnd\", \"Riftop\", dwStyle,\r\n\t\t\t0, 0, 1280, 800, NULL, 0, hInst, this);\r\n\r\n\t\tNameValuePairList misc;\r\n\t\tmisc[\"externalWindowHandle\"] = StringConverter::toString((int)mWindowHandle);\r\n\t\t\/\/misc[\"fullScreen\"] = true;\r\n\t\tmWindow = mRoot->createRenderWindow(\"Main RenderWindow\", 1280, 800, false, &misc);\r\n\t\t\/\/Ogre::WindowEventUtilities::_addRenderWindow(mWindow);\r\n\r\n return true;\r\n }\r\n else\r\n {\r\n return false;\r\n }\r\n}\r\n\/\/-------------------------------------------------------------------------------------\r\nvoid BaseApplication::chooseSceneManager(void)\r\n{\r\n \/\/ Get the SceneManager, in this case a generic one\r\n mSceneMgr = mRoot->createSceneManager(Ogre::ST_GENERIC);\r\n}\r\n\/\/-------------------------------------------------------------------------------------\r\n\/\/-------------------------------------------------------------------------------------\r\nvoid BaseApplication::createFrameListener(void)\r\n{\r\n Ogre::LogManager::getSingletonPtr()->logMessage(\"*** Initializing OIS ***\");\r\n OIS::ParamList pl;\r\n size_t windowHnd = 0;\r\n std::ostringstream windowHndStr;\r\n\r\n mWindow->getCustomAttribute(\"WINDOW\", &windowHnd);\r\n windowHndStr << windowHnd;\r\n pl.insert(std::make_pair(std::string(\"WINDOW\"), windowHndStr.str()));\r\n\r\n mInputManager = OIS::InputManager::createInputSystem( pl );\r\n\r\n mKeyboard = static_cast<OIS::Keyboard*>(mInputManager->createInputObject( OIS::OISKeyboard, true ));\r\n mMouse = static_cast<OIS::Mouse*>(mInputManager->createInputObject( OIS::OISMouse, true ));\r\n\r\n mMouse->setEventCallback(this);\r\n mKeyboard->setEventCallback(this);\r\n\r\n \/\/Set initial mouse clipping size\r\n windowResized(mWindow);\r\n\r\n \/\/Register as a Window listener\r\n Ogre::WindowEventUtilities::addWindowEventListener(mWindow, this);\r\n\r\n \/\/ create a params panel for displaying sample details\r\n Ogre::StringVector items;\r\n items.push_back(\"cam.pX\");\r\n items.push_back(\"cam.pY\");\r\n items.push_back(\"cam.pZ\");\r\n items.push_back(\"\");\r\n items.push_back(\"cam.oW\");\r\n items.push_back(\"cam.oX\");\r\n items.push_back(\"cam.oY\");\r\n items.push_back(\"cam.oZ\");\r\n items.push_back(\"\");\r\n items.push_back(\"Filtering\");\r\n items.push_back(\"Poly Mode\");\r\n\r\n mRoot->addFrameListener(this);\r\n}\r\n\/\/-------------------------------------------------------------------------------------\r\nvoid BaseApplication::destroyScene(void)\r\n{\r\n}\r\n\/\/-------------------------------------------------------------------------------------\r\nvoid BaseApplication::createViewports(void)\r\n{\r\n\t\r\n}\r\n\/\/-------------------------------------------------------------------------------------\r\nvoid BaseApplication::setupResources(void)\r\n{\r\n \/\/ Load resource paths from config file\r\n Ogre::ConfigFile cf;\r\n cf.load(mResourcesCfg);\r\n\r\n \/\/ Go through all sections & settings in the file\r\n Ogre::ConfigFile::SectionIterator seci = cf.getSectionIterator();\r\n\r\n Ogre::String secName, typeName, archName;\r\n while (seci.hasMoreElements())\r\n {\r\n secName = seci.peekNextKey();\r\n Ogre::ConfigFile::SettingsMultiMap *settings = seci.getNext();\r\n Ogre::ConfigFile::SettingsMultiMap::iterator i;\r\n for (i = settings->begin(); i != settings->end(); ++i)\r\n {\r\n typeName = i->first;\r\n archName = i->second;\r\n Ogre::ResourceGroupManager::getSingleton().addResourceLocation(\r\n archName, typeName, secName);\r\n }\r\n }\r\n}\r\n\/\/-------------------------------------------------------------------------------------\r\nvoid BaseApplication::createResourceListener(void)\r\n{\r\n\r\n}\r\n\/\/-------------------------------------------------------------------------------------\r\nvoid BaseApplication::loadResources(void)\r\n{\r\n\tOgre::ResourceGroupManager::getSingleton().createResourceGroup(Ogre::RTShader::ShaderGenerator::DEFAULT_SCHEME_NAME);\r\n Ogre::ResourceGroupManager::getSingleton().initialiseAllResourceGroups();\r\n\r\n\tif (Ogre::RTShader::ShaderGenerator::initialize())\r\n\t{\r\n\t\t\/\/ Grab the shader generator pointer.\r\n\t\tmShaderGenerator = Ogre::RTShader::ShaderGenerator::getSingletonPtr();\r\n \r\n\t\t\/\/ Add the shader libs resource location.\r\n\t\tOgre::ResourceGroupManager::getSingleton().addResourceLocation(\"D:\\\\Project\\\\Ogre\\\\OgreSource\\\\Samples\\\\Media\\\\RTShaderLib\\\\Cg\", \"FileSystem\");\r\n \r\n\t\t\/\/ Set shader cache path.\r\n\t\tmShaderGenerator->setShaderCachePath(\"D:\\\\Project\\\\WolfGame\\\\WolfGame\\\\Debug\\\\shaders\");\t\t\r\n\t\t\/\/mShaderGenerator->\r\n\t\t\/\/ Set the scene manager.\r\n\t\tmShaderGenerator->addSceneManager(mSceneMgr);\r\n \r\n\t\t\/\/ Add a specialized sub-render (per-pixel lighting) state to the default scheme render state\r\n\t\tOgre::RTShader::RenderState* pMainRenderState = \r\n\t\t\tmShaderGenerator->createOrRetrieveRenderState(Ogre::RTShader::ShaderGenerator::DEFAULT_SCHEME_NAME).first;\r\n\t\tpMainRenderState->reset();\r\n \r\n\t\t\/\/mShaderGenerator->addSubRenderStateFactory(new Ogre::RTShader::PerPixelLightingFactory);\r\n\t\tpMainRenderState->addTemplateSubRenderState(\r\n\t\t\tmShaderGenerator->createSubRenderState(Ogre::RTShader::FFPTexturing::Type));\t\r\n \r\n\t\t\/\/return true;\r\n\t}\r\n\t\r\n\tmShaderGenerator->createShaderBasedTechnique(\"box\/singlelight\", Ogre::MaterialManager::DEFAULT_SCHEME_NAME, Ogre::RTShader::ShaderGenerator::DEFAULT_SCHEME_NAME);\r\n\t\r\n}\r\n\/\/-------------------------------------------------------------------------------------\r\nvoid BaseApplication::go(void)\r\n{\r\n#ifdef _DEBUG\r\n mResourcesCfg = \"D:\\\\Project\\\\WolfGame\\\\WolfGame\\\\Debug\\\\resources_d.cfg\";\r\n mPluginsCfg = \"D:\\\\Project\\\\WolfGame\\\\WolfGame\\\\Debug\\\\plugins_d.cfg\";\r\n#else\r\n mResourcesCfg = \".\\\\resources.cfg\";\r\n mPluginsCfg = \".\\\\plugins.cfg\";\r\n#endif\r\n\r\n if (!setup())\r\n return;\r\n\r\n mRoot->startRendering();\r\n\r\n \/\/ clean up\r\n destroyScene();\r\n}\r\n\/\/-------------------------------------------------------------------------------------\r\nbool BaseApplication::setup(void)\r\n{\r\n mRoot = new Ogre::Root(mPluginsCfg);\r\n\r\n setupResources();\r\n\r\n bool carryOn = configure();\r\n if (!carryOn) return false;\r\n\r\n chooseSceneManager();\r\n\r\n\t\/\/ Set default mipmap level (NB some APIs ignore this)\r\n Ogre::TextureManager::getSingleton().setDefaultNumMipmaps(5);\r\n\r\n \/\/ Create any resource listeners (for loading screens)\r\n createResourceListener();\r\n \/\/ Load resources\r\n loadResources();\r\n\r\n\tm_Windows = new SystemWindowManager( mSceneMgr, mShaderGenerator);\r\n\tm_Windows->RefreshWindowHandles();\r\n\t\/\/window->DisplayWindow();\r\n\r\n\tmOculus = new OculusControl();\r\n\tmController = new CameraController::Controller(mWindow);\r\n mController->createCameras(mSceneMgr);\r\n\r\n\tif(mOculus->isInitialised())\r\n\t{\r\n\t\tmController->createViewports(mOculus->getDeviceInfo());\r\n\t}\r\n\telse\r\n\t{\r\n\t\tmController->createViewports();\r\n\t}\r\n\t\r\n\tmPlayer = new Player(mSceneMgr, mController->mBodyRotationNode);\r\n\r\n\tmScene = new WarehouseFloor(mSceneMgr);\r\n\tmWarehouseShown = true;\r\n createScene();\r\n\r\n createFrameListener();\r\n\r\n return true;\r\n};\r\n\/\/-------------------------------------------------------------------------------------\r\nbool BaseApplication::frameRenderingQueued(const Ogre::FrameEvent& evt)\r\n{\r\n if(mWindow->isClosed())\r\n return false;\r\n\r\n if(mShutDown)\r\n return false;\r\n\r\n \/\/Need to capture\/update each device\r\n mKeyboard->capture();\r\n mMouse->capture();\r\n\tmController->mRotationNode->setOrientation(mOculus->getOrientation());\r\n\tmPlayer->processMovement(evt.timeSinceLastFrame);\r\n return true;\r\n}\r\n\/\/-------------------------------------------------------------------------------------\r\nbool BaseApplication::keyPressed( const OIS::KeyEvent &arg )\r\n{\r\n\tif(arg.key == OIS::KC_SPACE)\r\n {\r\n\t\tm_Windows->ShowThumbnails();\r\n }\r\n return true;\r\n}\r\n\r\nbool BaseApplication::keyReleased( const OIS::KeyEvent &arg )\r\n{\r\n\tif(arg.key == OIS::KC_SPACE)\r\n {\r\n\t\tm_Windows->RemoveThumbnails();\r\n }\r\n\t\r\n return true;\r\n}\r\n\r\nbool BaseApplication::mouseMoved( const OIS::MouseEvent &arg )\r\n{\r\n\tmPlayer->mouseInput(Ogre::Vector2(arg.state.X.rel, arg.state.Y.rel));\r\n return true;\r\n}\r\n\r\nbool BaseApplication::mousePressed( const OIS::MouseEvent &arg, OIS::MouseButtonID id )\r\n{\r\n\tmPlayer->step();\r\n return true;\r\n}\r\n\r\nbool BaseApplication::mouseReleased( const OIS::MouseEvent &arg, OIS::MouseButtonID id )\r\n{\r\n return true;\r\n}\r\n\r\n\/\/Adjust mouse clipping area\r\nvoid BaseApplication::windowResized(Ogre::RenderWindow* rw)\r\n{\r\n unsigned int width, height, depth;\r\n int left, top;\r\n rw->getMetrics(width, height, depth, left, top);\r\n\r\n const OIS::MouseState &ms = mMouse->getMouseState();\r\n ms.width = width;\r\n ms.height = height;\r\n}\r\n\r\n\/\/Unattach OIS before window shutdown (very important under Linux)\r\nvoid BaseApplication::windowClosed(Ogre::RenderWindow* rw)\r\n{\r\n \/\/Only close for window that created OIS (the main window in these demos)\r\n if( rw == mWindow )\r\n {\r\n if( mInputManager )\r\n {\r\n \/\/mInputManager->destroyInputObject( mMouse );\r\n \/\/mInputManager->destroyInputObject( mKeyboard );\r\n\r\n OIS::InputManager::destroyInputSystem(mInputManager);\r\n mInputManager = 0;\r\n }\r\n }\r\n}\r\n<|endoftext|>"} {"text":"<commit_before>\/******************************************************************************\n * This file is part of the Mula project\n * Copyright (c) 2011 Laszlo Papp <lpapp@kde.org>\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n *\/\n\n#include \"dictionarymanager.h\"\n\n#include \"pluginmanager.h\"\n\n#include <QtCore\/QFileInfoList>\n#include <QtCore\/QDir>\n#include <QtCore\/QSettings>\n#include <QtCore\/QPluginLoader>\n\nusing namespace MulaCore;\n\nMULA_DEFINE_SINGLETON( DictionaryManager )\n\nclass DictionaryManager::Private\n{\n public:\n Private()\n {\n }\n\n ~Private()\n {\n }\n\n QMultiHash<QString, QString> loadedDictionaryList;\n};\n\nDictionaryManager::DictionaryManager(QObject *parent)\n : MulaCore::Singleton< MulaCore::DictionaryManager >( parent )\n , d(new Private)\n{\n loadDictionarySettings();\n}\n\nDictionaryManager::~DictionaryManager()\n{\n saveDictionarySettings();\n}\n\nbool\nDictionaryManager::isTranslatable(const QString &word)\n{\n for (QMultiHash<QString, QString>::const_iterator i = d->loadedDictionaryList.begin(); i != d->loadedDictionaryList.end(); ++i)\n {\n MulaCore::DictionaryPlugin* dictionaryPlugin = MulaCore::PluginManager::instance()->plugin(i.key());\n if (!dictionaryPlugin)\n continue;\n\n if (dictionaryPlugin->isTranslatable(i.value(), word))\n return true;\n }\n\n return false;\n}\n\nQString\nDictionaryManager::translate(const QString &word)\n{\n QString simplifiedWord = word.simplified();\n QString translatedWord;\n\n for (QMultiHash<QString, QString>::const_iterator i = d->loadedDictionaryList.begin(); i != d->loadedDictionaryList.end(); ++i)\n {\n MulaCore::DictionaryPlugin* dictionaryPlugin = MulaCore::PluginManager::instance()->plugin(i.key());\n if (!dictionaryPlugin)\n continue;\n\n if (!dictionaryPlugin->isTranslatable(i.key(), simplifiedWord))\n continue;\n\n MulaCore::Translation translation = dictionaryPlugin->translate(i.key(), simplifiedWord);\n translatedWord.append(QString(\"<p>\\n\")\n + \"<font class=\\\"dict_name\\\">\" + translation.dictionaryName() + \"<\/font><br>\\n\"\n + \"<font class=\\\"title\\\">\" + translation.title() + \"<\/font><br>\\n\"\n + translation.translation() + \"<\/p>\\n\");\n }\n\n return translatedWord;\n}\n\nQStringList\nDictionaryManager::findSimilarWords(const QString &word)\n{\n QString simplifiedWord = word.simplified();\n QStringList similarWords;\n\n for (QMultiHash<QString, QString>::const_iterator i = d->loadedDictionaryList.begin(); i != d->loadedDictionaryList.end(); ++i)\n {\n MulaCore::DictionaryPlugin* dictionaryPlugin = MulaCore::PluginManager::instance()->plugin(i.key());\n if (!dictionaryPlugin)\n continue;\n\n if (!dictionaryPlugin->features().testFlag(DictionaryPlugin::SearchSimilar))\n continue;\n\n QStringList similarWords = dictionaryPlugin->findSimilarWords(i.value(), simplifiedWord);\n foreach (const QString& similarWord, similarWords)\n {\n if (!similarWords.contains(similarWord, Qt::CaseSensitive))\n similarWords.append(similarWord);\n }\n }\n\n return similarWords;\n}\n\nQMultiHash<QString, QString>\nDictionaryManager::availableDictionaryList() const\n{\n QMultiHash<QString, QString> availableDictionaryList;\n\n \/\/ for (QHash<QString, QPluginLoader*>::const_iterator i = m_plugins.begin(); i != m_plugins.end(); ++i)\n \/\/ {\n \/\/ DictionaryPlugin *plugin = qobject_cast<DictionaryPlugin*>((*i)->instance());\n \/\/ QStringList dictionaries = plugin->availableDictionaryList();\n \/\/ foreach (const QString& dictionary, dictionaries)\n \/\/ availableDictionaryList.append(DictionaryDataItem(i.key(), dictionary));\n \/\/ }\n\n return availableDictionaryList;\n}\n\nvoid\nDictionaryManager::setLoadedDictionaryList(const QMultiHash<QString, QString> &loadedDictionaryList)\n{\n QMultiHash<QString, QString> dictionaries = loadedDictionaryList;\n\n foreach (const QString& pluginName, dictionaries.keys())\n {\n MulaCore::DictionaryPlugin* dictionaryPlugin = MulaCore::PluginManager::instance()->plugin(pluginName);\n if (!dictionaryPlugin)\n continue;\n\n dictionaryPlugin->setLoadedDictionaryList(dictionaries.values());\n foreach (const QString& dictionaryName, dictionaryPlugin->loadedDictionaryList())\n dictionaries.insert(pluginName, dictionaryName);\n }\n\n d->loadedDictionaryList.clear();\n for (QMultiHash<QString, QString>::const_iterator i = loadedDictionaryList.begin(); i != loadedDictionaryList.end(); ++i)\n {\n if (dictionaries.keys().contains(i.key()) && dictionaries.value(i.key()).contains(i.value()))\n d->loadedDictionaryList.insert(i.key(), i.value());\n }\n}\n\nvoid\nDictionaryManager::saveDictionarySettings()\n{\n QStringList rawDictionaryList;\n\n for (QMultiHash<QString, QString>::const_iterator i = d->loadedDictionaryList.begin(); i != d->loadedDictionaryList.end(); ++i)\n {\n rawDictionaryList.append(i.key());\n rawDictionaryList.append(i.value());\n }\n\n QSettings settings;\n settings.setValue(\"DictionaryManager\/loadedDictionaryList\", rawDictionaryList);\n}\n\nvoid\nDictionaryManager::loadDictionarySettings()\n{\n QSettings settings;\n QStringList rawDictionaryList = settings.value(\"DictionaryManager\/loadedDictionaryList\").toStringList();\n\n if (rawDictionaryList.isEmpty())\n {\n setLoadedDictionaryList(availableDictionaryList());\n }\n else\n {\n QMultiHash<QString, QString> dictionaries;\n for (QStringList::const_iterator i = rawDictionaryList.begin(); i != rawDictionaryList.end(); i += 2)\n dictionaries.insert(*i, *(i + 1));\n\n setLoadedDictionaryList(dictionaries);\n }\n}\n\nvoid\nDictionaryManager::reloadDictionaryList()\n{\n QMultiHash<QString, QString> loadedDictionaryList;\n \/\/ for (QHash<QString, QPluginLoader*>::const_iterator i = d->plugins.begin(); i != d->plugins.end(); ++i)\n \/\/ {\n \/\/ DictionaryPlugin *plugin = qobject_cast<DictionaryPlugin*>((*i)->instance());\n \/\/ plugin->setLoadedDictionaryList(plugin->loadedDictionaryList());\n\n \/\/ foreach(const QString& dictionaryName, plugin->loadedDictionaryList())\n \/\/ loadedDictionaryList.append(DictionaryDataItem(i.key(), dictionaryName));\n \/\/ }\n\n QMultiHash<QString, QString> oldDictionaryList = d->loadedDictionaryList;\n d->loadedDictionaryList.clear();\n \n for (QMultiHash<QString, QString>::const_iterator i = oldDictionaryList.begin(); i != oldDictionaryList.end(); ++i)\n {\n if (loadedDictionaryList.contains(i.key(), i.value()))\n d->loadedDictionaryList.insert(i.key(), i.value());\n }\n}\n\n#include \"dictionarymanager.moc\"\n<commit_msg>Reimplement the internals of the availableDictionaryList \"getter\".<commit_after>\/******************************************************************************\n * This file is part of the Mula project\n * Copyright (c) 2011 Laszlo Papp <lpapp@kde.org>\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n *\/\n\n#include \"dictionarymanager.h\"\n\n#include \"pluginmanager.h\"\n\n#include <QtCore\/QFileInfoList>\n#include <QtCore\/QDir>\n#include <QtCore\/QSettings>\n#include <QtCore\/QPluginLoader>\n\nusing namespace MulaCore;\n\nMULA_DEFINE_SINGLETON( DictionaryManager )\n\nclass DictionaryManager::Private\n{\n public:\n Private()\n {\n }\n\n ~Private()\n {\n }\n\n QMultiHash<QString, QString> loadedDictionaryList;\n};\n\nDictionaryManager::DictionaryManager(QObject *parent)\n : MulaCore::Singleton< MulaCore::DictionaryManager >( parent )\n , d(new Private)\n{\n loadDictionarySettings();\n}\n\nDictionaryManager::~DictionaryManager()\n{\n saveDictionarySettings();\n}\n\nbool\nDictionaryManager::isTranslatable(const QString &word)\n{\n for (QMultiHash<QString, QString>::const_iterator i = d->loadedDictionaryList.begin(); i != d->loadedDictionaryList.end(); ++i)\n {\n MulaCore::DictionaryPlugin* dictionaryPlugin = MulaCore::PluginManager::instance()->plugin(i.key());\n if (!dictionaryPlugin)\n continue;\n\n if (dictionaryPlugin->isTranslatable(i.value(), word))\n return true;\n }\n\n return false;\n}\n\nQString\nDictionaryManager::translate(const QString &word)\n{\n QString simplifiedWord = word.simplified();\n QString translatedWord;\n\n for (QMultiHash<QString, QString>::const_iterator i = d->loadedDictionaryList.begin(); i != d->loadedDictionaryList.end(); ++i)\n {\n MulaCore::DictionaryPlugin* dictionaryPlugin = MulaCore::PluginManager::instance()->plugin(i.key());\n if (!dictionaryPlugin)\n continue;\n\n if (!dictionaryPlugin->isTranslatable(i.key(), simplifiedWord))\n continue;\n\n MulaCore::Translation translation = dictionaryPlugin->translate(i.key(), simplifiedWord);\n translatedWord.append(QString(\"<p>\\n\")\n + \"<font class=\\\"dict_name\\\">\" + translation.dictionaryName() + \"<\/font><br>\\n\"\n + \"<font class=\\\"title\\\">\" + translation.title() + \"<\/font><br>\\n\"\n + translation.translation() + \"<\/p>\\n\");\n }\n\n return translatedWord;\n}\n\nQStringList\nDictionaryManager::findSimilarWords(const QString &word)\n{\n QString simplifiedWord = word.simplified();\n QStringList similarWords;\n\n for (QMultiHash<QString, QString>::const_iterator i = d->loadedDictionaryList.begin(); i != d->loadedDictionaryList.end(); ++i)\n {\n MulaCore::DictionaryPlugin* dictionaryPlugin = MulaCore::PluginManager::instance()->plugin(i.key());\n if (!dictionaryPlugin)\n continue;\n\n if (!dictionaryPlugin->features().testFlag(DictionaryPlugin::SearchSimilar))\n continue;\n\n QStringList similarWords = dictionaryPlugin->findSimilarWords(i.value(), simplifiedWord);\n foreach (const QString& similarWord, similarWords)\n {\n if (!similarWords.contains(similarWord, Qt::CaseSensitive))\n similarWords.append(similarWord);\n }\n }\n\n return similarWords;\n}\n\nQMultiHash<QString, QString>\nDictionaryManager::availableDictionaryList() const\n{\n QMultiHash<QString, QString> availableDictionaryList;\n\n foreach (const QString& pluginName, MulaCore::PluginManager::instance()->availablePlugins())\n {\n DictionaryPlugin *dictionaryPlugin = MulaCore::PluginManager::instance()->plugin(pluginName);\n QStringList dictionaries = dictionaryPlugin->availableDictionaryList();\n foreach (const QString& dictionary, dictionaries)\n availableDictionaryList.insert(pluginName, dictionary);\n }\n\n return availableDictionaryList;\n}\n\nvoid\nDictionaryManager::setLoadedDictionaryList(const QMultiHash<QString, QString> &loadedDictionaryList)\n{\n QMultiHash<QString, QString> dictionaries = loadedDictionaryList;\n\n foreach (const QString& pluginName, dictionaries.keys())\n {\n MulaCore::DictionaryPlugin* dictionaryPlugin = MulaCore::PluginManager::instance()->plugin(pluginName);\n if (!dictionaryPlugin)\n continue;\n\n dictionaryPlugin->setLoadedDictionaryList(dictionaries.values());\n foreach (const QString& dictionaryName, dictionaryPlugin->loadedDictionaryList())\n dictionaries.insert(pluginName, dictionaryName);\n }\n\n d->loadedDictionaryList.clear();\n for (QMultiHash<QString, QString>::const_iterator i = loadedDictionaryList.begin(); i != loadedDictionaryList.end(); ++i)\n {\n if (dictionaries.keys().contains(i.key()) && dictionaries.value(i.key()).contains(i.value()))\n d->loadedDictionaryList.insert(i.key(), i.value());\n }\n}\n\nvoid\nDictionaryManager::saveDictionarySettings()\n{\n QStringList rawDictionaryList;\n\n for (QMultiHash<QString, QString>::const_iterator i = d->loadedDictionaryList.begin(); i != d->loadedDictionaryList.end(); ++i)\n {\n rawDictionaryList.append(i.key());\n rawDictionaryList.append(i.value());\n }\n\n QSettings settings;\n settings.setValue(\"DictionaryManager\/loadedDictionaryList\", rawDictionaryList);\n}\n\nvoid\nDictionaryManager::loadDictionarySettings()\n{\n QSettings settings;\n QStringList rawDictionaryList = settings.value(\"DictionaryManager\/loadedDictionaryList\").toStringList();\n\n if (rawDictionaryList.isEmpty())\n {\n setLoadedDictionaryList(availableDictionaryList());\n }\n else\n {\n QMultiHash<QString, QString> dictionaries;\n for (QStringList::const_iterator i = rawDictionaryList.begin(); i != rawDictionaryList.end(); i += 2)\n dictionaries.insert(*i, *(i + 1));\n\n setLoadedDictionaryList(dictionaries);\n }\n}\n\nvoid\nDictionaryManager::reloadDictionaryList()\n{\n QMultiHash<QString, QString> loadedDictionaryList;\n \/\/ for (QHash<QString, QPluginLoader*>::const_iterator i = d->plugins.begin(); i != d->plugins.end(); ++i)\n \/\/ {\n \/\/ DictionaryPlugin *plugin = qobject_cast<DictionaryPlugin*>((*i)->instance());\n \/\/ plugin->setLoadedDictionaryList(plugin->loadedDictionaryList());\n\n \/\/ foreach(const QString& dictionaryName, plugin->loadedDictionaryList())\n \/\/ loadedDictionaryList.append(DictionaryDataItem(i.key(), dictionaryName));\n \/\/ }\n\n QMultiHash<QString, QString> oldDictionaryList = d->loadedDictionaryList;\n d->loadedDictionaryList.clear();\n \n for (QMultiHash<QString, QString>::const_iterator i = oldDictionaryList.begin(); i != oldDictionaryList.end(); ++i)\n {\n if (loadedDictionaryList.contains(i.key(), i.value()))\n d->loadedDictionaryList.insert(i.key(), i.value());\n }\n}\n\n#include \"dictionarymanager.moc\"\n<|endoftext|>"} {"text":"<commit_before>#include \"HTTPServer.hpp\"\n#include <czmq.h>\n#include <iostream>\n#include <sstream>\n#include <cstring>\n#include <sys\/mman.h>\n#include <sys\/types.h>\n#include <fcntl.h>\n#include <unistd.h>\n#include <sys\/stat.h>\n#include <assert.h>\n#include \"zutil.hpp\"\n\n#define controlEndpoint \"inproc:\/\/http\/control\"\n\nstatic size_t getFilesize(const char* filename) {\n struct stat st;\n stat(filename, &st);\n return st.st_size; \n}\n\nstatic bool fileExists(const char* file) {\n struct stat buf;\n return (stat(file, &buf) == 0);\n}\n\n\/**\n * Represents a readonly static file instance which has been mmapped\n * into vmem and possible pre-cached by the kernel.\n *\/\nclass MMappedStaticFile {\npublic:\n \/**\n * mmap a new static file.\n *\/\n MMappedStaticFile(const char* filename) {\n this->size = getFilesize(filename);\n fd = open(filename, O_RDONLY, 0);\n mem = mmap(nullptr, size, PROT_READ, MAP_PRIVATE | MAP_POPULATE, fd, 0);\n assert(mem != nullptr);\n \/\/File will always be sent sequentially\n madvise(mem, size, MADV_SEQUENTIAL);\n }\n ~MMappedStaticFile() {\n assert(munmap(mem, size) == 0);\n close(fd);\n }\n \/\/The mmapped memory\n void* mem;\n size_t size;\nprivate:\n \/\/The file descriptor that is mmapped\n int fd;\n};\n\nusing namespace std;\n\nYakHTTPServer::YakHTTPServer(zctx_t* ctxParam, const std::string& endpointParam, const std::string& staticFileRoot) : endpoint(endpointParam), ctx(ctxParam), thread(nullptr), logger(ctx, \"HTTP Server\"), staticFileRoot(staticFileRoot) {\n controlSocket = zsocket_new_bind(ctx, ZMQ_PAIR, controlEndpoint);\n \/\/Start thread\n thread = new std::thread(std::mem_fun(&YakHTTPServer::workerMain), this);\n}\n\n\/\/Static HTTP error msgs\nstatic const char securityErrorMessage[] = \"HTTP\/1.1 403 Forbidden\\r\\nContent-type: text\/plain\\r\\n\\r\\nSecurity error: Path must not contain ..\";\nstatic const char notFoundError[] = \"HTTP\/1.1 404 Not Found\\r\\nContent-type: text\/plain\\r\\n\\r\\nFile not found\";\n\n\n\/**\n * @return A constant string representing the MIME type, e.g. \"text\/plain\")\n *\/\nstatic const char* getMIMEType(const char* buffer) {\n \/\/Find the beginning of the file ext === the last '.' occurrence -> strRchr\n const char* fileExtensionPtr = strrchr(buffer, '.');\n if(fileExtensionPtr == nullptr) {\n return \"text\/plain\";\n }\n\n \/\/We found an extension\n if(strcmp(\".html\", fileExtensionPtr) == 0) {\n return \"text\/html\";\n } else if(strcmp(\".js\", fileExtensionPtr) == 0) {\n return \"text\/javascript\";\n } else if(strcmp(\".css\", fileExtensionPtr) == 0) {\n return \"text\/css\";\n } else if(strcmp(\".jpg\", fileExtensionPtr) == 0\n || strcmp(\".jpeg\", fileExtensionPtr) == 0) {\n return \"image\/jpeg\";\n } else if(strcmp(\".png\", fileExtensionPtr) == 0) {\n return \"image\/png\";\n } else if(strcmp(\".ico\", fileExtensionPtr) == 0) {\n return \"image\/x-icon\";\n } else {\n return \"text\/plain\";\n }\n}\n\nvoid YakHTTPServer::serveStaticFile(const char* fileURL) {\n sendReplyIdentity();\n \/\/Security: Check if the file contains relative paths\n if(strstr(fileURL, \"..\") != nullptr) {\n if(zmq_send_const(httpSocket, securityErrorMessage, sizeof(securityErrorMessage), 0) == -1) {\n logger.warn(\"Sending security violation error to HTTP client failed: \" + string(zmq_strerror(errno)));\n }\n return;\n }\n \/\/No security violation, check if the file exists\n if(fileURL[0] == '\/') {\n fileURL++;\n }\n if(fileURL[0] == '\\0') {\n fileURL = \"index.html\";\n }\n string absoluteFilePath = staticFileRoot + string(fileURL);\n if(!fileExists(absoluteFilePath.c_str())) {\n if(zmq_send_const(httpSocket, notFoundError, sizeof(notFoundError), 0) == -1) {\n logger.warn(\"Sending HTTP 404 to client failed: \" + string(zmq_strerror(errno)));\n }\n return;\n }\n \/\/File exists, mmap if neccessary\n if(mappedFiles.count(absoluteFilePath) == 0) {\n logger.trace(\"mmap'ing static file \" + absoluteFilePath);\n mappedFiles[absoluteFilePath] = new MMappedStaticFile(absoluteFilePath.c_str());\n }\n MMappedStaticFile* file = mappedFiles[absoluteFilePath];\n const char* mimeType = getMIMEType(fileURL);\n \/\/Send the header\n string header(\"HTTP\/1.1 200 OK\\r\\nContent-type: \" + string(mimeType) \n + \"\\r\\nContent-Length: \" + std::to_string(file->size) + \"\\r\\n\\r\\n\");\n if(zmq_send_const(httpSocket, header.data(), header.size(), 0) == -1) {\n logger.warn(\"Sending HTTP header to client failed: \" + string(zmq_strerror(errno))); \n }\n \/\/Send data\n sendReplyIdentity();\n if(zmq_send_const(httpSocket, file->mem, file->size, 0) == -1) {\n logger.warn(\"Sending HTTP body to client failed: \" + string(zmq_strerror(errno)));\n }\n}\n\nvoid YakHTTPServer::sendReplyIdentity() {\n if(unlikely(zmq_send_const (httpSocket, replyAddr, replyAddrSize, ZMQ_SNDMORE) == -1)) {\n logger.error(\"Error while sending stream reply adress: \" + string(zmq_strerror(errno)));\n }\n}\n\nvoid YakHTTPServer::workerMain() {\n \/\/TODO proper error handling\n logger.trace(\"HTTP Server starting on \" + endpoint);\n \/\/Initialize router socket\n httpSocket = zsocket_new(ctx, ZMQ_STREAM);\n assert(zsocket_bind(httpSocket, endpoint.c_str()) != -1);\n \/\/Initialize other stuff\n zmq_msg_t replyAddrFrame;\n zmq_msg_init(&replyAddrFrame);\n zmq_msg_t request;\n zmq_msg_init(&request);\n zmq_msg_t response;\n zmq_msg_init(&response);\n \/\/Initialize control socket (receives STOP cmd etc.)\n void* controlRecvSocket = zsocket_new_connect(ctx, ZMQ_PAIR, controlEndpoint);\n zmq_pollitem_t items[2];\n items[0].socket = httpSocket;\n items[0].events = ZMQ_POLLIN;\n items[1].socket = controlRecvSocket;\n items[1].events = ZMQ_POLLIN;\n while(true) {\n \/\/ Get HTTP request\n assert(zmq_poll(items, 2, -1) != -1);\n \/\/Check if we received a control msg\n if(items[1].revents) {\n \/\/Valid control msgs: STOP, HUP\n char* controlMsg = zstr_recv(controlRecvSocket);\n if(strcmp(controlMsg, \"HUP\") == 0) {\n \/\/HUP: munmap all static files --> 'reload' static files\n logger.trace(\"HUP received, reloading all mmap'ed files\");\n for(auto pair : mappedFiles) {\n delete pair.second;\n }\n free(controlMsg);\n continue;\n } else if(strcmp(controlMsg, \"STOP\") == 0) {\n free(controlMsg);\n break;\n } else {\n logger.warn(\"Received unknown control message: '\" + string(controlMsg) + \"'\");\n continue;\n }\n }\n assert(items[0].revents);\n \/\/Receive the reply adress\n zmq_msg_init(&replyAddrFrame);\n if(unlikely(zmq_msg_recv(&replyAddrFrame, httpSocket, 0) == -1)) {\n logger.error(\"HTTP critical error: Reply address could not be received correctly: \" + string(zmq_strerror(errno)));\n continue;\n }\n \/\/Receive the request itself (might be multi-part but we're ATM not interested in all the header\n if(unlikely(zmq_msg_recv(&request, httpSocket, 0) == -1)) {\n logger.error(\"Error while receiving HTTP request: \" + std::string(zmq_strerror(errno)));\n continue;\n }\n \/\/Extract the request type from the request\n char* requestData = (char*)zmq_msg_data(&request);\n bool isGETRequest = (memcmp(requestData, \"GET \", 4) == 0);\n assert(isGETRequest);\n \/\/Ensure there are no frames left to receive!\n recvAndIgnore(httpSocket);\n \/\/Make a NUL-delimited string from the request path\n char* requestPath = strchr(requestData, ' ') + 1;\n *(strchr(requestPath, ' ')) = '\\0';\n \/**\n * NOTE: Even if the reply adress is non-const data,\n * it is deallocated by the IO thread when the connection is closed\n * and certainly won't change, so we can treat it as constant\n * and therefore zero-copy data while the HTTP connection is open\n *\/\n replyAddr = (char*) zmq_msg_data(&replyAddrFrame);\n replyAddrSize = zmq_msg_size(&replyAddrFrame);\n \/\/TODO Check routes\n serveStaticFile(requestPath);\n \/\/Cleanup\n closeTCPConnection();\n zmq_msg_close(&replyAddrFrame);\n }\n logger.debug(\"HTTP Server terminating...\");\n zsocket_destroy(ctx, controlRecvSocket);\n zsocket_destroy(ctx, httpSocket);\n httpSocket = nullptr;\n}\n\nvoid YakHTTPServer::closeTCPConnection() {\n sendReplyIdentity();\n sendEmptyFrameMessage(httpSocket);\n}\n\nvoid YakHTTPServer::terminate() {\n if(thread != nullptr) {\n \/\/Send control msg\n zstr_send(controlSocket, \"STOP\");\n zsocket_destroy(ctx, controlSocket);\n \/\/Wait until the thread exists\n thread->join();\n delete thread;\n thread = nullptr;\n }\n logger.terminate();\n}\n\nYakHTTPServer::~YakHTTPServer() {\n terminate();\n \/\/munmap all mmapped files\n for(auto pair : mappedFiles) {\n delete pair.second;\n }\n}<commit_msg>Improve HTTP server safety<commit_after>#include \"HTTPServer.hpp\"\n#include <czmq.h>\n#include <iostream>\n#include <sstream>\n#include <cstring>\n#include <sys\/mman.h>\n#include <sys\/types.h>\n#include <fcntl.h>\n#include <unistd.h>\n#include <sys\/stat.h>\n#include <assert.h>\n#include \"zutil.hpp\"\n\n#define controlEndpoint \"inproc:\/\/http\/control\"\n\nstatic size_t getFilesize(const char* filename) {\n struct stat st;\n stat(filename, &st);\n return st.st_size; \n}\n\nstatic bool fileExists(const char* file) {\n struct stat buf;\n return (stat(file, &buf) == 0);\n}\n\n\/**\n * Represents a readonly static file instance which has been mmapped\n * into vmem and possible pre-cached by the kernel.\n *\/\nclass MMappedStaticFile {\npublic:\n \/**\n * mmap a new static file.\n *\/\n MMappedStaticFile(const char* filename) {\n this->size = getFilesize(filename);\n fd = open(filename, O_RDONLY, 0);\n mem = mmap(nullptr, size, PROT_READ, MAP_PRIVATE | MAP_POPULATE, fd, 0);\n assert(mem != nullptr);\n \/\/File will always be sent sequentially\n madvise(mem, size, MADV_SEQUENTIAL);\n }\n ~MMappedStaticFile() {\n assert(munmap(mem, size) == 0);\n close(fd);\n }\n \/\/The mmapped memory\n void* mem;\n size_t size;\nprivate:\n \/\/The file descriptor that is mmapped\n int fd;\n};\n\nusing namespace std;\n\nYakHTTPServer::YakHTTPServer(zctx_t* ctxParam, const std::string& endpointParam, const std::string& staticFileRoot) : endpoint(endpointParam), ctx(ctxParam), thread(nullptr), logger(ctx, \"HTTP Server\"), staticFileRoot(staticFileRoot) {\n controlSocket = zsocket_new_bind(ctx, ZMQ_PAIR, controlEndpoint);\n \/\/Start thread\n thread = new std::thread(std::mem_fun(&YakHTTPServer::workerMain), this);\n}\n\n\/\/Static HTTP error msgs\nstatic const char securityErrorMessage[] = \"HTTP\/1.1 403 Forbidden\\r\\nContent-type: text\/plain\\r\\n\\r\\nSecurity error: Path must not contain ..\";\nstatic const char notFoundError[] = \"HTTP\/1.1 404 Not Found\\r\\nContent-type: text\/plain\\r\\n\\r\\nFile not found\";\n\n\n\/**\n * @return A constant string representing the MIME type, e.g. \"text\/plain\")\n *\/\nstatic const char* getMIMEType(const char* buffer) {\n \/\/Find the beginning of the file ext === the last '.' occurrence -> strRchr\n const char* fileExtensionPtr = strrchr(buffer, '.');\n if(fileExtensionPtr == nullptr) {\n return \"text\/plain\";\n }\n\n \/\/We found an extension\n if(strcmp(\".html\", fileExtensionPtr) == 0) {\n return \"text\/html\";\n } else if(strcmp(\".js\", fileExtensionPtr) == 0) {\n return \"text\/javascript\";\n } else if(strcmp(\".css\", fileExtensionPtr) == 0) {\n return \"text\/css\";\n } else if(strcmp(\".jpg\", fileExtensionPtr) == 0\n || strcmp(\".jpeg\", fileExtensionPtr) == 0) {\n return \"image\/jpeg\";\n } else if(strcmp(\".png\", fileExtensionPtr) == 0) {\n return \"image\/png\";\n } else if(strcmp(\".ico\", fileExtensionPtr) == 0) {\n return \"image\/x-icon\";\n } else {\n return \"text\/plain\";\n }\n}\n\nvoid YakHTTPServer::serveStaticFile(const char* fileURL) {\n sendReplyIdentity();\n \/\/Security: Check if the file contains relative paths\n if(strstr(fileURL, \"..\") != nullptr) {\n if(zmq_send_const(httpSocket, securityErrorMessage, sizeof(securityErrorMessage), 0) == -1) {\n logger.warn(\"Sending security violation error to HTTP client failed: \" + string(zmq_strerror(errno)));\n }\n return;\n }\n \/\/No security violation, check if the file exists\n if(fileURL[0] == '\/') {\n fileURL++;\n }\n if(fileURL[0] == '\\0') {\n fileURL = \"index.html\";\n }\n string absoluteFilePath = staticFileRoot + string(fileURL);\n if(!fileExists(absoluteFilePath.c_str())) {\n if(zmq_send_const(httpSocket, notFoundError, sizeof(notFoundError), 0) == -1) {\n logger.warn(\"Sending HTTP 404 to client failed: \" + string(zmq_strerror(errno)));\n }\n return;\n }\n \/\/File exists, mmap if neccessary\n if(mappedFiles.count(absoluteFilePath) == 0) {\n logger.trace(\"mmap'ing static file \" + absoluteFilePath);\n mappedFiles[absoluteFilePath] = new MMappedStaticFile(absoluteFilePath.c_str());\n }\n MMappedStaticFile* file = mappedFiles[absoluteFilePath];\n const char* mimeType = getMIMEType(fileURL);\n \/\/Send the header\n string header(\"HTTP\/1.1 200 OK\\r\\nContent-type: \" + string(mimeType) \n + \"\\r\\nContent-Length: \" + std::to_string(file->size) + \"\\r\\n\\r\\n\");\n if(zmq_send_const(httpSocket, header.data(), header.size(), 0) == -1) {\n logger.warn(\"Sending HTTP header to client failed: \" + string(zmq_strerror(errno))); \n }\n \/\/Send data\n sendReplyIdentity();\n if(zmq_send_const(httpSocket, file->mem, file->size, 0) == -1) {\n logger.warn(\"Sending HTTP body to client failed: \" + string(zmq_strerror(errno)));\n }\n}\n\nvoid YakHTTPServer::sendReplyIdentity() {\n if(unlikely(zmq_send (httpSocket, replyAddr, replyAddrSize, ZMQ_SNDMORE) == -1)) {\n logger.error(\"Error while sending stream reply adress: \" + string(zmq_strerror(errno)));\n }\n}\n\nvoid YakHTTPServer::workerMain() {\n \/\/TODO proper error handling\n logger.trace(\"HTTP Server starting on \" + endpoint);\n \/\/Initialize router socket\n httpSocket = zsocket_new(ctx, ZMQ_STREAM);\n assert(zsocket_bind(httpSocket, endpoint.c_str()) != -1);\n \/\/Initialize other stuff\n zmq_msg_t replyAddrFrame;\n zmq_msg_init(&replyAddrFrame);\n zmq_msg_t request;\n zmq_msg_init(&request);\n zmq_msg_t response; \n zmq_msg_init(&response);\n \/\/Initialize control socket (receives STOP cmd etc.)\n void* controlRecvSocket = zsocket_new_connect(ctx, ZMQ_PAIR, controlEndpoint);\n zmq_pollitem_t items[2];\n items[0].socket = httpSocket;\n items[0].events = ZMQ_POLLIN;\n items[1].socket = controlRecvSocket;\n items[1].events = ZMQ_POLLIN;\n while(true) {\n \/\/ Get HTTP request\n assert(zmq_poll(items, 2, -1) != -1);\n \/\/Check if we received a control msg\n if(items[1].revents) {\n \/\/Valid control msgs: STOP, HUP\n char* controlMsg = zstr_recv(controlRecvSocket);\n if(strcmp(controlMsg, \"HUP\") == 0) {\n \/\/HUP: munmap all static files --> 'reload' static files\n logger.trace(\"HUP received, reloading all mmap'ed files\");\n for(auto pair : mappedFiles) {\n delete pair.second;\n }\n free(controlMsg);\n continue;\n } else if(strcmp(controlMsg, \"STOP\") == 0) {\n free(controlMsg);\n break;\n } else {\n logger.warn(\"Received unknown control message: '\" + string(controlMsg) + \"'\");\n continue;\n }\n }\n assert(items[0].revents);\n \/\/Receive the reply adress\n zmq_msg_init(&replyAddrFrame);\n if(unlikely(zmq_msg_recv(&replyAddrFrame, httpSocket, 0) == -1)) {\n logger.error(\"HTTP critical error: Reply address could not be received correctly: \" + string(zmq_strerror(errno)));\n continue;\n }\n \/\/Receive the request itself (might be multi-part but we're ATM not interested in all the header\n if(unlikely(zmq_msg_recv(&request, httpSocket, 0) == -1)) {\n logger.error(\"Error while receiving HTTP request: \" + std::string(zmq_strerror(errno)));\n continue;\n }\n \/\/Extract the request type from the request\n char* requestData = (char*)zmq_msg_data(&request);\n bool isGETRequest = (memcmp(requestData, \"GET \", 4) == 0);\n assert(isGETRequest);\n \/\/Ensure there are no frames left to receive!\n recvAndIgnore(httpSocket);\n \/\/Make a NUL-delimited string from the request path\n char* requestPath = strchr(requestData, ' ') + 1;\n *(strchr(requestPath, ' ')) = '\\0';\n \/**\n * NOTE: Even if the reply adress is non-const data,\n * it is deallocated by the IO thread when the connection is closed\n * and certainly won't change, so we can treat it as constant\n * and therefore zero-copy data while the HTTP connection is open\n *\/\n replyAddr = (char*) zmq_msg_data(&replyAddrFrame);\n replyAddrSize = zmq_msg_size(&replyAddrFrame);\n \/\/TODO Check routes\n serveStaticFile(requestPath);\n \/\/Cleanup\n closeTCPConnection();\n zmq_msg_close(&replyAddrFrame);\n }\n logger.debug(\"HTTP Server terminating...\");\n zsocket_destroy(ctx, controlRecvSocket);\n zsocket_destroy(ctx, httpSocket);\n httpSocket = nullptr;\n}\n\nvoid YakHTTPServer::closeTCPConnection() {\n sendReplyIdentity();\n sendEmptyFrameMessage(httpSocket);\n}\n\nvoid YakHTTPServer::terminate() {\n if(thread != nullptr) {\n \/\/Send control msg\n zstr_send(controlSocket, \"STOP\");\n zsocket_destroy(ctx, controlSocket);\n \/\/Wait until the thread exists\n thread->join();\n delete thread;\n thread = nullptr;\n }\n logger.terminate();\n}\n\nYakHTTPServer::~YakHTTPServer() {\n terminate();\n \/\/munmap all mmapped files\n for(auto pair : mappedFiles) {\n delete pair.second;\n }\n}<|endoftext|>"} {"text":"<commit_before>#include \"Controller.h\"\n\n#include \"boost\/thread.hpp\"\n#include \"boost\/bind.hpp\"\n#include \"boost\/progress.hpp\"\n\n\n#include \"comm\/FalconCommLibFTDI.h\"\n#include \"grip\/FalconGripFourButton.h\"\n#include \"firmware\/FalconFirmwareNovintSDK.h\"\n\n#include \"kinematic\/stamper\/InverseKinematic.h\"\n#include \"kinematic\/stamper\/JacobianMatrix.h\"\n\n#include <iostream>\n\nnamespace controller\n{\n\n\tController::Controller()\n\t{\n\t\tfalconKinematic = new libnifalcon::FalconKinematicStamper(false);\n\t\tstd::cout << \"Falcon initialization\" << std::endl;\n\t\t\/\/Don't set a kinematics model, since we're handing that ourselves\n\t\tfalconModel = new libnifalcon::FalconDeviceBoostThread();\n\t\tint8_t i;\n\t\tfalconModel->setFalconComm<libnifalcon::FalconCommLibFTDI>();\n\t\tfalconModel->setFalconFirmware<libnifalcon::FalconFirmwareNovintSDK>();\n\t\tfalconModel->setFalconGrip<libnifalcon::FalconGripFourButton>();\n\n\t\tif(!falconModel->open(0))\n\t\t{\n\t\t\tstd::cout << \"Can't open!\" << std::endl;\n\t\t}\n\t\t\n\t\tfalconModel->getFalconFirmware()->setHomingMode(true);\n\t\tint8_t count;\n\t\tif(!falconModel->isFirmwareLoaded())\n\t\t{\n\t\t\tstd::cout << \"Loading firmware...\" << std::endl;\n\t\t\tstd::cout << falconModel->setFirmwareFile(\"test_firmware.bin\") << std::endl;\t\t\n\t\t\tfor(int i = 0; i < 10; ++i)\n\t\t\t{\t\t\t\n\t\t\t\tif(falconModel->loadFirmware(10)) break;\n\t\t\t}\n\t\t}\n\t\tstd::cout << \"Kinematics initialization\" << std::endl;\n\t\tif(falconModel->isFirmwareLoaded())\n\t\t{\n\t\t\tfalconKinematic->initialize();\n\t\t\tstd::cout << \"Initialization finished\" << std::endl;\n\t\t\t\/\/boost::thread thread(boost::bind( &libnifalcon::FalconDevice::runThreadLoop, falconModel));\n\t\t\tfalconModel->startThread();\n\t\t}\n\t}\n\n\tController::~Controller()\n\t{\n\t\tdelete toolbox;\n\t\tdelete viewer;\n\t\tdelete falconModel;\n\t\tdelete falconView;\n\t}\n\n\tvoid Controller::display()\n\t{\n\t\tif (viewer)\n\t\t\tviewer->display();\n\t}\n\n\tvoid Controller::reshape(int w, int h)\n\t{\n\t\tif (viewer)\n\t\t\tviewer->reshape(w, h);\n\t}\n\n\tvoid Controller::mouseButton(int button, int state, int x, int y)\n\t{\n\t\tif (viewer)\n\t\t\tviewer->mouseButton(button, state, x, y);\n\t}\n\n\tvoid Controller::mouseMove(int x, int y)\n\t{\n\t\tif (viewer)\n\t\t\tviewer->mouseMove(x, y);\n\t}\n\n\tvoid Controller::keyboard(unsigned char key, int x, int y)\n\t{\n\t\tif (viewer)\n\t\t\tviewer->keyboard(key, x, y);\n\t}\n\n\tvoid Controller::idle()\n\t{\n\n\t\tif(!falconModel->getFalconFirmware()->isHomed())\n\t\t{\n\t\t\tfalconModel->getFalconFirmware()->setLEDStatus(libnifalcon::FalconFirmware::RED_LED);\n\t\t\treturn;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tfalconModel->getFalconFirmware()->setLEDStatus(libnifalcon::FalconFirmware::GREEN_LED);\n\t\t}\n\t\tint16_t* encoders = new int16_t[3];\n\t\tencoders = falconModel->getFalconFirmware()->getEncoderValues();\n\t\tangle1 = falconKinematic->getTheta(encoders[0]);\n\t\tangle2 = falconKinematic->getTheta(encoders[1]);\n\t\tangle3 = falconKinematic->getTheta(encoders[2]);\n\t\n\t\tif (toolbox)\n\t\t\ttoolbox->sync();\n\n\t\tgmtl::Vec3f angle_vec(gmtl::Math::deg2Rad(angle1), gmtl::Math::deg2Rad(angle2), gmtl::Math::deg2Rad(angle3));\n\tgmtl::Point3f position = falconKinematic->getDirectKinematic()->calculate(angle_vec);\n\t\n\t\tfalconView->getEffector()->setPosition(position);\n\t\n\t\tlibnifalcon::StamperKinematicImpl::Angle angle = libnifalcon::StamperKinematicImpl::InverseKinematic::calculate(position);\n\t\n\t\tfalconView->getArm(view::Falcon::ARM_1)->setAngle(angle.theta1[view::Falcon::ARM_1]);\n\t\tfalconView->getArm(view::Falcon::ARM_2)->setAngle(angle.theta1[view::Falcon::ARM_2]);\n\t\tfalconView->getArm(view::Falcon::ARM_3)->setAngle(angle.theta1[view::Falcon::ARM_3]);\n\t\n\t\tfalconView->getParallel(view::Falcon::ARM_1)->update(angle.theta1[view::Falcon::ARM_1],\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t angle.theta2[view::Falcon::ARM_1],\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t angle.theta3[view::Falcon::ARM_1]);\n\t\n\t\tfalconView->getParallel(view::Falcon::ARM_2)->update(angle.theta1[view::Falcon::ARM_2],\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t angle.theta2[view::Falcon::ARM_2],\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t angle.theta3[view::Falcon::ARM_2]);\n\t\n\t\tfalconView->getParallel(view::Falcon::ARM_3)->update(angle.theta1[view::Falcon::ARM_3],\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t angle.theta2[view::Falcon::ARM_3],\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t angle.theta3[view::Falcon::ARM_3]);\n\/\/\t\tdelete[] encoders;\n\/*\n\t\tif(falconModel->isHomed())\n\t\t{\n\t\t\tgmtl::Vec3f forceVector(0,0,torque1);\n\t\t\tgmtl::Matrix44f rotation;\n\t\t\trotation.set(rotationMatrix[0], rotationMatrix[1], rotationMatrix[2], rotationMatrix[3],\n\t\t\t\t\t\t rotationMatrix[4], rotationMatrix[5], rotationMatrix[6], rotationMatrix[7],\n\t\t\t\t\t\t rotationMatrix[8], rotationMatrix[9], rotationMatrix[10], rotationMatrix[11],\n\t\t\t\t\t\t rotationMatrix[12], rotationMatrix[13], rotationMatrix[14], rotationMatrix[15]);\n\t\t\tforceVector = rotation*forceVector;\n\t\n\t\t\tgmtl::Vec3f angularVelocity = libnifalcon::StamperKinematicImpl::JacobianMatrix::calculate(angle, forceVector);\n\t\n\t\t\tfalconView->force->update(position, forceVector, rotation);\n\t\n\t\t\tfloat new_torque1 = -angularVelocity[libnifalcon::StamperKinematicImpl::ARM_1];\n\t\t\tfloat new_torque2 = -angularVelocity[libnifalcon::StamperKinematicImpl::ARM_2];\n\t\t\tfloat new_torque3 = -angularVelocity[libnifalcon::StamperKinematicImpl::ARM_3];\n\t\n\t\t\tfalconModel->setTorque(libnifalcon::StamperKinematicImpl::ARM_1, new_torque1);\n\t\t\tfalconModel->setTorque(libnifalcon::StamperKinematicImpl::ARM_2, new_torque2);\n\t\t\tfalconModel->setTorque(libnifalcon::StamperKinematicImpl::ARM_3, new_torque3);\n\t\t}\n*\/\n\n\t}\n\n\tvoid Controller::createViewer()\n\t{\n\t\tviewer = new view::Viewer();\n\t\tfalconView = new view::Falcon();\n\t\tviewer->setRootModel(falconView->getModel());\n\t}\n\n\tvoid Controller::createToolbox(int windowId, void (*idle)(void))\n\t{\n\t\tangle1 = 0;\n\t\tangle2 = 0;\n\t\tangle3 = 0;\n\t\ttorque1 = 0;\n\t\ttorque2 = 0;\n\t\ttorque3 = 0;\n\t\n\t\tview::Toolbox::Parameter parameter;\n\t\tparameter.angle1 = &angle1;\n\t\tparameter.angle2 = &angle2;\n\t\tparameter.angle3 = &angle3;\n\t\tparameter.torque1 = &torque1;\n\t\tparameter.torque2 = &torque2;\n\t\tparameter.torque3 = &torque3;\n\t\tparameter.rotationMatrix = rotationMatrix;\n\t\ttoolbox = new view::Toolbox(windowId, idle, parameter);\t\n\t}\n\n\tvoid Controller::hapticLoop()\n\t{\n\t\t\n\t\twhile(1)\n\t\t{\n\t\t\t\n\t\t\tfalconModel->runIOLoop();\n\t\t\t\/*\n\t\t\tangle1 = falconModel->getTheta(model::Falcon::ARM_1);\n\t\t\tangle2 = falconModel->getTheta(model::Falcon::ARM_2);\n\t\t\tangle3 = falconModel->getTheta(model::Falcon::ARM_3);\n\n\t\t\tgmtl::Point3f position = directKinematic->calculate(gmtl::Vec3f(gmtl::Math::deg2Rad(angle1), gmtl::Math::deg2Rad(angle2), gmtl::Math::deg2Rad(angle3)));\n\t\t\t\n\t\t\tmodel::falcon::Angle angle = model::InverseKinematic::calculate(position);\n\t\t\n\t\t\tgmtl::Vec3f center(0,0,120);\n\n\n\t\t\tgmtl::Vec3f vecSphere(position-center);\n\t\t\tfloat radius = 20;\n\t\t\tfloat norme = 0;\n\t\t\tif (length(vecSphere)<radius)\n\t\t\t{\n\t\t\t\tnorme = ((radius-length(vecSphere))\/3)+20;\n\t\t\t\t\/\/norme = 50;\n\n\t\t\t}\n\t\t\tnormalize(vecSphere);\n\t\t\tgmtl::Vec3f forceVector = vecSphere;\n\t\t\n\t\t\tgmtl::Vec3f angularVelocity = model::JacobianMatrix::calculate(angle, forceVector);\n\t\t\t\n\t\t\tfloat torque1 = -angularVelocity[model::Falcon::ARM_1]*norme;\n\t\t\tfloat torque2 = -angularVelocity[model::Falcon::ARM_2]*norme;\n\t\t\tfloat torque3 = -angularVelocity[model::Falcon::ARM_3]*norme;\n\t\t\n\t\t\tfalconModel->setTorque(model::Falcon::ARM_1, torque1);\n\t\t\tfalconModel->setTorque(model::Falcon::ARM_2, torque2);\n\t\t\tfalconModel->setTorque(model::Falcon::ARM_3, torque3);\n\n*\/\n\t\t}\n\n\t}\n\n}\n<commit_msg>Changed controller to use binary firmware headers for firmware loading Fixed position coordinate scaling<commit_after>#include \"Controller.h\"\n\n#include \"boost\/thread.hpp\"\n#include \"boost\/bind.hpp\"\n#include \"boost\/progress.hpp\"\n\n\n#include \"falcon\/comm\/FalconCommLibFTDI.h\"\n#include \"falcon\/grip\/FalconGripFourButton.h\"\n#include \"falcon\/firmware\/FalconFirmwareNovintSDK.h\"\n#include \"falcon\/util\/FalconFirmwareBinaryNvent.h\"\n\n#include \"falcon\/kinematic\/stamper\/InverseKinematic.h\"\n#include \"falcon\/kinematic\/stamper\/JacobianMatrix.h\"\n\n#include <iostream>\n\nnamespace controller\n{\n\n\tController::Controller()\n\t{\n\t\tfalconKinematic = new libnifalcon::FalconKinematicStamper(false);\n\t\tstd::cout << \"Falcon initialization\" << std::endl;\n\t\t\/\/Don't set a kinematics model, since we're handing that ourselves\n\t\tfalconModel = new libnifalcon::FalconDeviceBoostThread();\n\t\tint8_t i;\n\t\tfalconModel->setFalconComm<libnifalcon::FalconCommLibFTDI>();\n\t\tfalconModel->setFalconFirmware<libnifalcon::FalconFirmwareNovintSDK>();\n\t\tfalconModel->setFalconGrip<libnifalcon::FalconGripFourButton>();\n\n\t\tif(!falconModel->open(0))\n\t\t{\n\t\t\tstd::cout << \"Can't open!\" << std::endl;\n\t\t}\n\t\t\n\t\tfalconModel->getFalconFirmware()->setHomingMode(true);\n\t\tint8_t count;\n\t\tif(!falconModel->isFirmwareLoaded())\n\t\t{\n\t\t\tstd::cout << \"Loading firmware...\" << std::endl;\n\t\t\tfor(int i = 0; i < 10; ++i)\n\t\t\t{\t\t\t\n\t\t\t\tif(!falconModel->getFalconFirmware()->loadFirmware(true, NOVINT_FALCON_NVENT_FIRMWARE_SIZE, const_cast<uint8_t*>(NOVINT_FALCON_NVENT_FIRMWARE)))\n\t\t\t\t{\n\t\t\t\t\tstd::cout << \"Could not load firmware\" << std::endl;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tstd::cout << \"Kinematics initialization\" << std::endl;\n\t\tif(falconModel->isFirmwareLoaded())\n\t\t{\n\t\t\tfalconKinematic->initialize();\n\t\t\tstd::cout << \"Initialization finished\" << std::endl;\n\t\t\t\/\/boost::thread thread(boost::bind( &libnifalcon::FalconDevice::runThreadLoop, falconModel));\n\t\t\tfalconModel->startThread();\n\t\t}\n\t}\n\n\tController::~Controller()\n\t{\n\t\tdelete toolbox;\n\t\tdelete viewer;\n\t\tdelete falconModel;\n\t\tdelete falconView;\n\t}\n\n\tvoid Controller::display()\n\t{\n\t\tif (viewer)\n\t\t\tviewer->display();\n\t}\n\n\tvoid Controller::reshape(int w, int h)\n\t{\n\t\tif (viewer)\n\t\t\tviewer->reshape(w, h);\n\t}\n\n\tvoid Controller::mouseButton(int button, int state, int x, int y)\n\t{\n\t\tif (viewer)\n\t\t\tviewer->mouseButton(button, state, x, y);\n\t}\n\n\tvoid Controller::mouseMove(int x, int y)\n\t{\n\t\tif (viewer)\n\t\t\tviewer->mouseMove(x, y);\n\t}\n\n\tvoid Controller::keyboard(unsigned char key, int x, int y)\n\t{\n\t\tif (viewer)\n\t\t\tviewer->keyboard(key, x, y);\n\t}\n\n\tvoid Controller::idle()\n\t{\n\n\t\tif(!falconModel->getFalconFirmware()->isHomed())\n\t\t{\n\t\t\tfalconModel->getFalconFirmware()->setLEDStatus(libnifalcon::FalconFirmware::RED_LED);\n\t\t\treturn;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tfalconModel->getFalconFirmware()->setLEDStatus(libnifalcon::FalconFirmware::GREEN_LED);\n\t\t}\n\t\tint16_t* encoders = new int16_t[3];\n\t\tencoders = falconModel->getFalconFirmware()->getEncoderValues();\n\t\tangle1 = falconKinematic->getTheta(encoders[0]);\n\t\tangle2 = falconKinematic->getTheta(encoders[1]);\n\t\tangle3 = falconKinematic->getTheta(encoders[2]);\n\t\n\t\tif (toolbox)\n\t\t\ttoolbox->sync();\n\n\t\tgmtl::Vec3f angle_vec(gmtl::Math::deg2Rad(angle1), gmtl::Math::deg2Rad(angle2), gmtl::Math::deg2Rad(angle3));\n\t\tgmtl::Point3f position = falconKinematic->getDirectKinematic()->calculate(angle_vec);\n\t\tgmtl::Point3f position_new = position;\n\t\tposition_new *= 1000.0;\n\t\tfalconView->getEffector()->setPosition(position_new);\n\t\n\t\tlibnifalcon::StamperKinematicImpl::Angle angle = libnifalcon::StamperKinematicImpl::InverseKinematic::calculate(position);\n\t\n\t\tfalconView->getArm(view::Falcon::ARM_1)->setAngle(angle.theta1[view::Falcon::ARM_1]);\n\t\tfalconView->getArm(view::Falcon::ARM_2)->setAngle(angle.theta1[view::Falcon::ARM_2]);\n\t\tfalconView->getArm(view::Falcon::ARM_3)->setAngle(angle.theta1[view::Falcon::ARM_3]);\n\t\n\t\tfalconView->getParallel(view::Falcon::ARM_1)->update(angle.theta1[view::Falcon::ARM_1],\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t angle.theta2[view::Falcon::ARM_1],\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t angle.theta3[view::Falcon::ARM_1]);\n\t\n\t\tfalconView->getParallel(view::Falcon::ARM_2)->update(angle.theta1[view::Falcon::ARM_2],\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t angle.theta2[view::Falcon::ARM_2],\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t angle.theta3[view::Falcon::ARM_2]);\n\t\n\t\tfalconView->getParallel(view::Falcon::ARM_3)->update(angle.theta1[view::Falcon::ARM_3],\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t angle.theta2[view::Falcon::ARM_3],\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t angle.theta3[view::Falcon::ARM_3]);\n\/\/\t\tdelete[] encoders;\n\/*\n\t\tif(falconModel->isHomed())\n\t\t{\n\t\t\tgmtl::Vec3f forceVector(0,0,torque1);\n\t\t\tgmtl::Matrix44f rotation;\n\t\t\trotation.set(rotationMatrix[0], rotationMatrix[1], rotationMatrix[2], rotationMatrix[3],\n\t\t\t\t\t\t rotationMatrix[4], rotationMatrix[5], rotationMatrix[6], rotationMatrix[7],\n\t\t\t\t\t\t rotationMatrix[8], rotationMatrix[9], rotationMatrix[10], rotationMatrix[11],\n\t\t\t\t\t\t rotationMatrix[12], rotationMatrix[13], rotationMatrix[14], rotationMatrix[15]);\n\t\t\tforceVector = rotation*forceVector;\n\t\n\t\t\tgmtl::Vec3f angularVelocity = libnifalcon::StamperKinematicImpl::JacobianMatrix::calculate(angle, forceVector);\n\t\n\t\t\tfalconView->force->update(position, forceVector, rotation);\n\t\n\t\t\tfloat new_torque1 = -angularVelocity[libnifalcon::StamperKinematicImpl::ARM_1];\n\t\t\tfloat new_torque2 = -angularVelocity[libnifalcon::StamperKinematicImpl::ARM_2];\n\t\t\tfloat new_torque3 = -angularVelocity[libnifalcon::StamperKinematicImpl::ARM_3];\n\t\n\t\t\tfalconModel->setTorque(libnifalcon::StamperKinematicImpl::ARM_1, new_torque1);\n\t\t\tfalconModel->setTorque(libnifalcon::StamperKinematicImpl::ARM_2, new_torque2);\n\t\t\tfalconModel->setTorque(libnifalcon::StamperKinematicImpl::ARM_3, new_torque3);\n\t\t}\n*\/\n\n\t}\n\n\tvoid Controller::createViewer()\n\t{\n\t\tviewer = new view::Viewer();\n\t\tfalconView = new view::Falcon();\n\t\tviewer->setRootModel(falconView->getModel());\n\t}\n\n\tvoid Controller::createToolbox(int windowId, void (*idle)(void))\n\t{\n\t\tangle1 = 0;\n\t\tangle2 = 0;\n\t\tangle3 = 0;\n\t\ttorque1 = 0;\n\t\ttorque2 = 0;\n\t\ttorque3 = 0;\n\t\n\t\tview::Toolbox::Parameter parameter;\n\t\tparameter.angle1 = &angle1;\n\t\tparameter.angle2 = &angle2;\n\t\tparameter.angle3 = &angle3;\n\t\tparameter.torque1 = &torque1;\n\t\tparameter.torque2 = &torque2;\n\t\tparameter.torque3 = &torque3;\n\t\tparameter.rotationMatrix = rotationMatrix;\n\t\ttoolbox = new view::Toolbox(windowId, idle, parameter);\t\n\t}\n\n\tvoid Controller::hapticLoop()\n\t{\n\t\t\n\t\twhile(1)\n\t\t{\n\t\t\t\n\t\t\tfalconModel->runIOLoop();\n\t\t\t\/*\n\t\t\tangle1 = falconModel->getTheta(model::Falcon::ARM_1);\n\t\t\tangle2 = falconModel->getTheta(model::Falcon::ARM_2);\n\t\t\tangle3 = falconModel->getTheta(model::Falcon::ARM_3);\n\n\t\t\tgmtl::Point3f position = directKinematic->calculate(gmtl::Vec3f(gmtl::Math::deg2Rad(angle1), gmtl::Math::deg2Rad(angle2), gmtl::Math::deg2Rad(angle3)));\n\t\t\t\n\t\t\tmodel::falcon::Angle angle = model::InverseKinematic::calculate(position);\n\t\t\n\t\t\tgmtl::Vec3f center(0,0,120);\n\n\n\t\t\tgmtl::Vec3f vecSphere(position-center);\n\t\t\tfloat radius = 20;\n\t\t\tfloat norme = 0;\n\t\t\tif (length(vecSphere)<radius)\n\t\t\t{\n\t\t\t\tnorme = ((radius-length(vecSphere))\/3)+20;\n\t\t\t\t\/\/norme = 50;\n\n\t\t\t}\n\t\t\tnormalize(vecSphere);\n\t\t\tgmtl::Vec3f forceVector = vecSphere;\n\t\t\n\t\t\tgmtl::Vec3f angularVelocity = model::JacobianMatrix::calculate(angle, forceVector);\n\t\t\t\n\t\t\tfloat torque1 = -angularVelocity[model::Falcon::ARM_1]*norme;\n\t\t\tfloat torque2 = -angularVelocity[model::Falcon::ARM_2]*norme;\n\t\t\tfloat torque3 = -angularVelocity[model::Falcon::ARM_3]*norme;\n\t\t\n\t\t\tfalconModel->setTorque(model::Falcon::ARM_1, torque1);\n\t\t\tfalconModel->setTorque(model::Falcon::ARM_2, torque2);\n\t\t\tfalconModel->setTorque(model::Falcon::ARM_3, torque3);\n\n*\/\n\t\t}\n\n\t}\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright 2011-2013 Blender Foundation\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"render\/colorspace.h\"\n\n#include \"util\/util_color.h\"\n#include \"util\/util_image.h\"\n#include \"util\/util_half.h\"\n#include \"util\/util_logging.h\"\n#include \"util\/util_math.h\"\n#include \"util\/util_thread.h\"\n#include \"util\/util_vector.h\"\n\n#ifdef WITH_OCIO\n# include <OpenColorIO\/OpenColorIO.h>\nnamespace OCIO = OCIO_NAMESPACE;\n#endif\n\nCCL_NAMESPACE_BEGIN\n\n\/* Builtin colorspaces. *\/\nustring u_colorspace_auto;\nustring u_colorspace_raw(\"__builtin_raw\");\nustring u_colorspace_srgb(\"__builtin_srgb\");\n\n\/* Cached data. *\/\n#ifdef WITH_OCIO\nstatic thread_mutex cache_mutex;\nstatic unordered_map<ustring, ustring, ustringHash> cached_colorspaces;\nstatic unordered_map<ustring, OCIO::ConstProcessorRcPtr, ustringHash> cached_processors;\n#endif\n\nColorSpaceProcessor *ColorSpaceManager::get_processor(ustring colorspace)\n{\n#ifdef WITH_OCIO\n \/* Only use this for OpenColorIO color spaces, not the builtin ones. *\/\n assert(colorspace != u_colorspace_srgb && colorspace != u_colorspace_auto);\n\n if (colorspace == u_colorspace_raw) {\n return NULL;\n }\n\n OCIO::ConstConfigRcPtr config = OCIO::GetCurrentConfig();\n if (!config) {\n return NULL;\n }\n\n \/* Cache processor until free_memory(), memory overhead is expected to be\n * small and the processor is likely to be reused. *\/\n thread_scoped_lock cache_lock(cache_mutex);\n if (cached_processors.find(colorspace) == cached_processors.end()) {\n try {\n cached_processors[colorspace] = config->getProcessor(colorspace.c_str(), \"scene_linear\");\n }\n catch (OCIO::Exception &exception) {\n cached_processors[colorspace] = OCIO::ConstProcessorRcPtr();\n VLOG(1) << \"Colorspace \" << colorspace.c_str()\n << \" can't be converted to scene_linear: \" << exception.what();\n }\n }\n\n const OCIO::Processor *processor = cached_processors[colorspace].get();\n return (ColorSpaceProcessor *)processor;\n#else\n \/* No OpenColorIO. *\/\n (void)colorspace;\n return NULL;\n#endif\n}\n\nustring ColorSpaceManager::detect_known_colorspace(ustring colorspace,\n const char *file_format,\n bool is_float)\n{\n if (colorspace == u_colorspace_auto) {\n \/* Auto detect sRGB or raw if none specified. *\/\n if (is_float) {\n bool srgb = (colorspace == \"sRGB\" || colorspace == \"GammaCorrected\" ||\n (colorspace.empty() &&\n (strcmp(file_format, \"png\") == 0 || strcmp(file_format, \"tiff\") == 0 ||\n strcmp(file_format, \"dpx\") == 0 || strcmp(file_format, \"jpeg2000\") == 0)));\n return srgb ? u_colorspace_srgb : u_colorspace_raw;\n }\n else {\n return u_colorspace_srgb;\n }\n }\n else if (colorspace == u_colorspace_srgb || colorspace == u_colorspace_raw) {\n \/* Builtin colorspaces. *\/\n return colorspace;\n }\n else {\n \/* Use OpenColorIO. *\/\n#ifdef WITH_OCIO\n {\n thread_scoped_lock cache_lock(cache_mutex);\n \/* Cached lookup. *\/\n if (cached_colorspaces.find(colorspace) != cached_colorspaces.end()) {\n return cached_colorspaces[colorspace];\n }\n }\n\n \/* Detect if it matches a simple builtin colorspace. *\/\n bool is_no_op, is_srgb;\n is_builtin_colorspace(colorspace, is_no_op, is_srgb);\n\n thread_scoped_lock cache_lock(cache_mutex);\n if (is_no_op) {\n VLOG(1) << \"Colorspace \" << colorspace.string() << \" is no-op\";\n cached_colorspaces[colorspace] = u_colorspace_raw;\n return u_colorspace_raw;\n }\n else if (is_srgb) {\n VLOG(1) << \"Colorspace \" << colorspace.string() << \" is sRGB\";\n cached_colorspaces[colorspace] = u_colorspace_srgb;\n return u_colorspace_srgb;\n }\n\n \/* Verify if we can convert from the requested color space. *\/\n if (!get_processor(colorspace)) {\n OCIO::ConstConfigRcPtr config = OCIO::GetCurrentConfig();\n if (!config || !config->getColorSpace(colorspace.c_str())) {\n VLOG(1) << \"Colorspace \" << colorspace.c_str() << \" not found, using raw instead\";\n }\n else {\n VLOG(1) << \"Colorspace \" << colorspace.c_str()\n << \" can't be converted to scene_linear, using raw instead\";\n }\n cached_colorspaces[colorspace] = u_colorspace_raw;\n return u_colorspace_raw;\n }\n\n \/* Convert to\/from colorspace with OpenColorIO. *\/\n VLOG(1) << \"Colorspace \" << colorspace.string() << \" handled through OpenColorIO\";\n cached_colorspaces[colorspace] = colorspace;\n return colorspace;\n#else\n VLOG(1) << \"Colorspace \" << colorspace.c_str() << \" not available, built without OpenColorIO\";\n return u_colorspace_raw;\n#endif\n }\n}\n\nvoid ColorSpaceManager::is_builtin_colorspace(ustring colorspace, bool &is_no_op, bool &is_srgb)\n{\n#ifdef WITH_OCIO\n const OCIO::Processor *processor = (const OCIO::Processor *)get_processor(colorspace);\n if (!processor) {\n is_no_op = false;\n is_srgb = false;\n return;\n }\n\n is_no_op = true;\n is_srgb = true;\n for (int i = 0; i < 256; i++) {\n float v = i \/ 255.0f;\n\n float cR[3] = {v, 0, 0};\n float cG[3] = {0, v, 0};\n float cB[3] = {0, 0, v};\n float cW[3] = {v, v, v};\n processor->applyRGB(cR);\n processor->applyRGB(cG);\n processor->applyRGB(cB);\n processor->applyRGB(cW);\n\n \/* Make sure that there is no channel crosstalk. *\/\n if (fabsf(cR[1]) > 1e-5f || fabsf(cR[2]) > 1e-5f || fabsf(cG[0]) > 1e-5f ||\n fabsf(cG[2]) > 1e-5f || fabsf(cB[0]) > 1e-5f || fabsf(cB[1]) > 1e-5f) {\n is_no_op = false;\n is_srgb = false;\n break;\n }\n \/* Make sure that the three primaries combine linearly. *\/\n if (!compare_floats(cR[0], cW[0], 1e-6f, 64) || !compare_floats(cG[1], cW[1], 1e-6f, 64) ||\n !compare_floats(cB[2], cW[2], 1e-6f, 64)) {\n is_no_op = false;\n is_srgb = false;\n break;\n }\n \/* Make sure that the three channels behave identically. *\/\n if (!compare_floats(cW[0], cW[1], 1e-6f, 64) || !compare_floats(cW[1], cW[2], 1e-6f, 64)) {\n is_no_op = false;\n is_srgb = false;\n break;\n }\n\n float out_v = average(make_float3(cW[0], cW[1], cW[2]));\n if (!compare_floats(v, out_v, 1e-6f, 64)) {\n is_no_op = false;\n }\n if (!compare_floats(color_srgb_to_linear(v), out_v, 1e-6f, 64)) {\n is_srgb = false;\n }\n }\n#else\n (void)colorspace;\n is_no_op = false;\n is_srgb = false;\n#endif\n}\n\n#ifdef WITH_OCIO\n\ntemplate<typename T> inline float4 cast_to_float4(T *data)\n{\n return make_float4(util_image_cast_to_float(data[0]),\n util_image_cast_to_float(data[1]),\n util_image_cast_to_float(data[2]),\n util_image_cast_to_float(data[3]));\n}\n\ntemplate<typename T> inline void cast_from_float4(T *data, float4 value)\n{\n data[0] = util_image_cast_from_float<T>(value.x);\n data[1] = util_image_cast_from_float<T>(value.y);\n data[2] = util_image_cast_from_float<T>(value.z);\n data[3] = util_image_cast_from_float<T>(value.w);\n}\n\n\/* Slower versions for other all data types, which needs to convert to float and back. *\/\ntemplate<typename T, bool compress_as_srgb = false>\ninline void processor_apply_pixels(const OCIO::Processor *processor,\n T *pixels,\n size_t width,\n size_t height)\n{\n \/* Process large images in chunks to keep temporary memory requirement down. *\/\n size_t y_chunk_size = max(1, 16 * 1024 * 1024 \/ (sizeof(float4) * width));\n vector<float4> float_pixels(y_chunk_size * width);\n\n for (size_t y0 = 0; y0 < height; y0 += y_chunk_size) {\n size_t y1 = std::min(y0 + y_chunk_size, height);\n size_t i = 0;\n\n for (size_t y = y0; y < y1; y++) {\n for (size_t x = 0; x < width; x++, i++) {\n float_pixels[i] = cast_to_float4(pixels + 4 * (y * width + x));\n }\n }\n\n OCIO::PackedImageDesc desc((float *)float_pixels.data(), width, y_chunk_size, 4);\n processor->apply(desc);\n\n i = 0;\n for (size_t y = y0; y < y1; y++) {\n for (size_t x = 0; x < width; x++, i++) {\n float4 value = float_pixels[i];\n if (compress_as_srgb) {\n value = color_linear_to_srgb_v4(value);\n }\n cast_from_float4(pixels + 4 * (y * width + x), value);\n }\n }\n }\n}\n\n\/* Fast version for float images, which OpenColorIO can handle natively. *\/\ntemplate<>\ninline void processor_apply_pixels(const OCIO::Processor *processor,\n float *pixels,\n size_t width,\n size_t height)\n{\n OCIO::PackedImageDesc desc(pixels, width, height, 4);\n processor->apply(desc);\n}\n#endif\n\ntemplate<typename T>\nvoid ColorSpaceManager::to_scene_linear(ustring colorspace,\n T *pixels,\n size_t width,\n size_t height,\n size_t depth,\n bool compress_as_srgb)\n{\n#ifdef WITH_OCIO\n const OCIO::Processor *processor = (const OCIO::Processor *)get_processor(colorspace);\n\n if (processor) {\n if (compress_as_srgb) {\n \/* Compress output as sRGB. *\/\n for (size_t z = 0; z < depth; z++) {\n processor_apply_pixels<T, true>(processor, &pixels[z * width * height], width, height);\n }\n }\n else {\n \/* Write output as scene linear directly. *\/\n for (size_t z = 0; z < depth; z++) {\n processor_apply_pixels<T>(processor, &pixels[z * width * height], width, height);\n }\n }\n }\n#else\n (void)colorspace;\n (void)pixels;\n (void)width;\n (void)height;\n (void)depth;\n (void)compress_as_srgb;\n#endif\n}\n\nvoid ColorSpaceManager::to_scene_linear(ColorSpaceProcessor *processor_,\n float *pixel,\n int channels)\n{\n#ifdef WITH_OCIO\n const OCIO::Processor *processor = (const OCIO::Processor *)processor_;\n\n if (processor) {\n if (channels == 3) {\n processor->applyRGB(pixel);\n }\n else if (channels == 4) {\n if (pixel[3] == 1.0f || pixel[3] == 0.0f) {\n \/* Fast path for RGBA. *\/\n processor->applyRGB(pixel);\n }\n else {\n \/* Unassociate and associate alpha since color management should not\n * be affected by transparency. *\/\n float alpha = pixel[3];\n float inv_alpha = 1.0f \/ alpha;\n\n pixel[0] *= inv_alpha;\n pixel[1] *= inv_alpha;\n pixel[2] *= inv_alpha;\n\n processor->applyRGB(pixel);\n\n pixel[0] *= alpha;\n pixel[1] *= alpha;\n pixel[2] *= alpha;\n }\n }\n }\n#else\n (void)processor_;\n (void)pixel;\n (void)channels;\n#endif\n}\n\nvoid ColorSpaceManager::free_memory()\n{\n#ifdef WITH_OCIO\n map_free_memory(cached_colorspaces);\n map_free_memory(cached_colorspaces);\n#endif\n}\n\n\/* Template instanstations so we don't have to inline functions. *\/\ntemplate void ColorSpaceManager::to_scene_linear(ustring, uchar *, size_t, size_t, size_t, bool);\ntemplate void ColorSpaceManager::to_scene_linear(ustring, ushort *, size_t, size_t, size_t, bool);\ntemplate void ColorSpaceManager::to_scene_linear(ustring, half *, size_t, size_t, size_t, bool);\ntemplate void ColorSpaceManager::to_scene_linear(ustring, float *, size_t, size_t, size_t, bool);\n\nCCL_NAMESPACE_END\n<commit_msg>Color management: add functions to detect scene linear and sRGB color spaces<commit_after>\/*\n * Copyright 2011-2013 Blender Foundation\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"render\/colorspace.h\"\n\n#include \"util\/util_color.h\"\n#include \"util\/util_image.h\"\n#include \"util\/util_half.h\"\n#include \"util\/util_logging.h\"\n#include \"util\/util_math.h\"\n#include \"util\/util_thread.h\"\n#include \"util\/util_vector.h\"\n\n#ifdef WITH_OCIO\n# include <OpenColorIO\/OpenColorIO.h>\nnamespace OCIO = OCIO_NAMESPACE;\n#endif\n\nCCL_NAMESPACE_BEGIN\n\n\/* Builtin colorspaces. *\/\nustring u_colorspace_auto;\nustring u_colorspace_raw(\"__builtin_raw\");\nustring u_colorspace_srgb(\"__builtin_srgb\");\n\n\/* Cached data. *\/\n#ifdef WITH_OCIO\nstatic thread_mutex cache_mutex;\nstatic unordered_map<ustring, ustring, ustringHash> cached_colorspaces;\nstatic unordered_map<ustring, OCIO::ConstProcessorRcPtr, ustringHash> cached_processors;\n#endif\n\nColorSpaceProcessor *ColorSpaceManager::get_processor(ustring colorspace)\n{\n#ifdef WITH_OCIO\n \/* Only use this for OpenColorIO color spaces, not the builtin ones. *\/\n assert(colorspace != u_colorspace_srgb && colorspace != u_colorspace_auto);\n\n if (colorspace == u_colorspace_raw) {\n return NULL;\n }\n\n OCIO::ConstConfigRcPtr config = OCIO::GetCurrentConfig();\n if (!config) {\n return NULL;\n }\n\n \/* Cache processor until free_memory(), memory overhead is expected to be\n * small and the processor is likely to be reused. *\/\n thread_scoped_lock cache_lock(cache_mutex);\n if (cached_processors.find(colorspace) == cached_processors.end()) {\n try {\n cached_processors[colorspace] = config->getProcessor(colorspace.c_str(), \"scene_linear\");\n }\n catch (OCIO::Exception &exception) {\n cached_processors[colorspace] = OCIO::ConstProcessorRcPtr();\n VLOG(1) << \"Colorspace \" << colorspace.c_str()\n << \" can't be converted to scene_linear: \" << exception.what();\n }\n }\n\n const OCIO::Processor *processor = cached_processors[colorspace].get();\n return (ColorSpaceProcessor *)processor;\n#else\n \/* No OpenColorIO. *\/\n (void)colorspace;\n return NULL;\n#endif\n}\n\nustring ColorSpaceManager::detect_known_colorspace(ustring colorspace,\n const char *file_format,\n bool is_float)\n{\n if (colorspace == u_colorspace_auto) {\n \/* Auto detect sRGB or raw if none specified. *\/\n if (is_float) {\n bool srgb = (colorspace == \"sRGB\" || colorspace == \"GammaCorrected\" ||\n (colorspace.empty() &&\n (strcmp(file_format, \"png\") == 0 || strcmp(file_format, \"tiff\") == 0 ||\n strcmp(file_format, \"dpx\") == 0 || strcmp(file_format, \"jpeg2000\") == 0)));\n return srgb ? u_colorspace_srgb : u_colorspace_raw;\n }\n else {\n return u_colorspace_srgb;\n }\n }\n else if (colorspace == u_colorspace_srgb || colorspace == u_colorspace_raw) {\n \/* Builtin colorspaces. *\/\n return colorspace;\n }\n else {\n \/* Use OpenColorIO. *\/\n#ifdef WITH_OCIO\n {\n thread_scoped_lock cache_lock(cache_mutex);\n \/* Cached lookup. *\/\n if (cached_colorspaces.find(colorspace) != cached_colorspaces.end()) {\n return cached_colorspaces[colorspace];\n }\n }\n\n \/* Detect if it matches a simple builtin colorspace. *\/\n bool is_scene_linear, is_srgb;\n is_builtin_colorspace(colorspace, is_scene_linear, is_srgb);\n\n thread_scoped_lock cache_lock(cache_mutex);\n if (is_scene_linear) {\n VLOG(1) << \"Colorspace \" << colorspace.string() << \" is no-op\";\n cached_colorspaces[colorspace] = u_colorspace_raw;\n return u_colorspace_raw;\n }\n else if (is_srgb) {\n VLOG(1) << \"Colorspace \" << colorspace.string() << \" is sRGB\";\n cached_colorspaces[colorspace] = u_colorspace_srgb;\n return u_colorspace_srgb;\n }\n\n \/* Verify if we can convert from the requested color space. *\/\n if (!get_processor(colorspace)) {\n OCIO::ConstConfigRcPtr config = OCIO::GetCurrentConfig();\n if (!config || !config->getColorSpace(colorspace.c_str())) {\n VLOG(1) << \"Colorspace \" << colorspace.c_str() << \" not found, using raw instead\";\n }\n else {\n VLOG(1) << \"Colorspace \" << colorspace.c_str()\n << \" can't be converted to scene_linear, using raw instead\";\n }\n cached_colorspaces[colorspace] = u_colorspace_raw;\n return u_colorspace_raw;\n }\n\n \/* Convert to\/from colorspace with OpenColorIO. *\/\n VLOG(1) << \"Colorspace \" << colorspace.string() << \" handled through OpenColorIO\";\n cached_colorspaces[colorspace] = colorspace;\n return colorspace;\n#else\n VLOG(1) << \"Colorspace \" << colorspace.c_str() << \" not available, built without OpenColorIO\";\n return u_colorspace_raw;\n#endif\n }\n}\n\nvoid ColorSpaceManager::is_builtin_colorspace(ustring colorspace,\n bool &is_scene_linear,\n bool &is_srgb)\n{\n#ifdef WITH_OCIO\n const OCIO::Processor *processor = (const OCIO::Processor *)get_processor(colorspace);\n if (!processor) {\n is_scene_linear = false;\n is_srgb = false;\n return;\n }\n\n is_scene_linear = true;\n is_srgb = true;\n for (int i = 0; i < 256; i++) {\n float v = i \/ 255.0f;\n\n float cR[3] = {v, 0, 0};\n float cG[3] = {0, v, 0};\n float cB[3] = {0, 0, v};\n float cW[3] = {v, v, v};\n processor->applyRGB(cR);\n processor->applyRGB(cG);\n processor->applyRGB(cB);\n processor->applyRGB(cW);\n\n \/* Make sure that there is no channel crosstalk. *\/\n if (fabsf(cR[1]) > 1e-5f || fabsf(cR[2]) > 1e-5f || fabsf(cG[0]) > 1e-5f ||\n fabsf(cG[2]) > 1e-5f || fabsf(cB[0]) > 1e-5f || fabsf(cB[1]) > 1e-5f) {\n is_scene_linear = false;\n is_srgb = false;\n break;\n }\n \/* Make sure that the three primaries combine linearly. *\/\n if (!compare_floats(cR[0], cW[0], 1e-6f, 64) || !compare_floats(cG[1], cW[1], 1e-6f, 64) ||\n !compare_floats(cB[2], cW[2], 1e-6f, 64)) {\n is_scene_linear = false;\n is_srgb = false;\n break;\n }\n \/* Make sure that the three channels behave identically. *\/\n if (!compare_floats(cW[0], cW[1], 1e-6f, 64) || !compare_floats(cW[1], cW[2], 1e-6f, 64)) {\n is_scene_linear = false;\n is_srgb = false;\n break;\n }\n\n float out_v = average(make_float3(cW[0], cW[1], cW[2]));\n if (!compare_floats(v, out_v, 1e-6f, 64)) {\n is_scene_linear = false;\n }\n if (!compare_floats(color_srgb_to_linear(v), out_v, 1e-6f, 64)) {\n is_srgb = false;\n }\n }\n#else\n (void)colorspace;\n is_scene_linear = false;\n is_srgb = false;\n#endif\n}\n\n#ifdef WITH_OCIO\n\ntemplate<typename T> inline float4 cast_to_float4(T *data)\n{\n return make_float4(util_image_cast_to_float(data[0]),\n util_image_cast_to_float(data[1]),\n util_image_cast_to_float(data[2]),\n util_image_cast_to_float(data[3]));\n}\n\ntemplate<typename T> inline void cast_from_float4(T *data, float4 value)\n{\n data[0] = util_image_cast_from_float<T>(value.x);\n data[1] = util_image_cast_from_float<T>(value.y);\n data[2] = util_image_cast_from_float<T>(value.z);\n data[3] = util_image_cast_from_float<T>(value.w);\n}\n\n\/* Slower versions for other all data types, which needs to convert to float and back. *\/\ntemplate<typename T, bool compress_as_srgb = false>\ninline void processor_apply_pixels(const OCIO::Processor *processor,\n T *pixels,\n size_t width,\n size_t height)\n{\n \/* Process large images in chunks to keep temporary memory requirement down. *\/\n size_t y_chunk_size = max(1, 16 * 1024 * 1024 \/ (sizeof(float4) * width));\n vector<float4> float_pixels(y_chunk_size * width);\n\n for (size_t y0 = 0; y0 < height; y0 += y_chunk_size) {\n size_t y1 = std::min(y0 + y_chunk_size, height);\n size_t i = 0;\n\n for (size_t y = y0; y < y1; y++) {\n for (size_t x = 0; x < width; x++, i++) {\n float_pixels[i] = cast_to_float4(pixels + 4 * (y * width + x));\n }\n }\n\n OCIO::PackedImageDesc desc((float *)float_pixels.data(), width, y_chunk_size, 4);\n processor->apply(desc);\n\n i = 0;\n for (size_t y = y0; y < y1; y++) {\n for (size_t x = 0; x < width; x++, i++) {\n float4 value = float_pixels[i];\n if (compress_as_srgb) {\n value = color_linear_to_srgb_v4(value);\n }\n cast_from_float4(pixels + 4 * (y * width + x), value);\n }\n }\n }\n}\n\n\/* Fast version for float images, which OpenColorIO can handle natively. *\/\ntemplate<>\ninline void processor_apply_pixels(const OCIO::Processor *processor,\n float *pixels,\n size_t width,\n size_t height)\n{\n OCIO::PackedImageDesc desc(pixels, width, height, 4);\n processor->apply(desc);\n}\n#endif\n\ntemplate<typename T>\nvoid ColorSpaceManager::to_scene_linear(ustring colorspace,\n T *pixels,\n size_t width,\n size_t height,\n size_t depth,\n bool compress_as_srgb)\n{\n#ifdef WITH_OCIO\n const OCIO::Processor *processor = (const OCIO::Processor *)get_processor(colorspace);\n\n if (processor) {\n if (compress_as_srgb) {\n \/* Compress output as sRGB. *\/\n for (size_t z = 0; z < depth; z++) {\n processor_apply_pixels<T, true>(processor, &pixels[z * width * height], width, height);\n }\n }\n else {\n \/* Write output as scene linear directly. *\/\n for (size_t z = 0; z < depth; z++) {\n processor_apply_pixels<T>(processor, &pixels[z * width * height], width, height);\n }\n }\n }\n#else\n (void)colorspace;\n (void)pixels;\n (void)width;\n (void)height;\n (void)depth;\n (void)compress_as_srgb;\n#endif\n}\n\nvoid ColorSpaceManager::to_scene_linear(ColorSpaceProcessor *processor_,\n float *pixel,\n int channels)\n{\n#ifdef WITH_OCIO\n const OCIO::Processor *processor = (const OCIO::Processor *)processor_;\n\n if (processor) {\n if (channels == 3) {\n processor->applyRGB(pixel);\n }\n else if (channels == 4) {\n if (pixel[3] == 1.0f || pixel[3] == 0.0f) {\n \/* Fast path for RGBA. *\/\n processor->applyRGB(pixel);\n }\n else {\n \/* Unassociate and associate alpha since color management should not\n * be affected by transparency. *\/\n float alpha = pixel[3];\n float inv_alpha = 1.0f \/ alpha;\n\n pixel[0] *= inv_alpha;\n pixel[1] *= inv_alpha;\n pixel[2] *= inv_alpha;\n\n processor->applyRGB(pixel);\n\n pixel[0] *= alpha;\n pixel[1] *= alpha;\n pixel[2] *= alpha;\n }\n }\n }\n#else\n (void)processor_;\n (void)pixel;\n (void)channels;\n#endif\n}\n\nvoid ColorSpaceManager::free_memory()\n{\n#ifdef WITH_OCIO\n map_free_memory(cached_colorspaces);\n map_free_memory(cached_colorspaces);\n#endif\n}\n\n\/* Template instanstations so we don't have to inline functions. *\/\ntemplate void ColorSpaceManager::to_scene_linear(ustring, uchar *, size_t, size_t, size_t, bool);\ntemplate void ColorSpaceManager::to_scene_linear(ustring, ushort *, size_t, size_t, size_t, bool);\ntemplate void ColorSpaceManager::to_scene_linear(ustring, half *, size_t, size_t, size_t, bool);\ntemplate void ColorSpaceManager::to_scene_linear(ustring, float *, size_t, size_t, size_t, bool);\n\nCCL_NAMESPACE_END\n<|endoftext|>"} {"text":"<commit_before>#include \"sampler.hpp\"\n#include \"context.hpp\"\n#include \"texture.hpp\"\n\n#include \"internal\/wrapper.hpp\"\n\n#include \"internal\/modules.hpp\"\n#include \"internal\/tools.hpp\"\n#include \"internal\/glsl.hpp\"\n\n\/* MGLContext.sampler(texture)\n *\/\nPyObject * MGLContext_meth_sampler(MGLContext * self, PyObject * const * args, Py_ssize_t nargs) {\n if (nargs != 1) {\n \/\/ TODO: error\n return 0;\n }\n\n PyObject * texture = args[0];\n\n MGLSampler * sampler = MGLContext_new_object(self, Sampler);\n\n const GLMethods & gl = self->gl;\n gl.GenSamplers(1, (GLuint *)&sampler->sampler_obj);\n\n if (!sampler->sampler_obj) {\n PyErr_Format(moderngl_error, \"cannot create sampler\");\n Py_DECREF(sampler);\n return 0;\n }\n\n gl.SamplerParameteri(sampler->sampler_obj, GL_TEXTURE_MIN_FILTER, GL_NEAREST);\n gl.SamplerParameteri(sampler->sampler_obj, GL_TEXTURE_MAG_FILTER, GL_NEAREST);\n\n SLOT(sampler->wrapper, PyObject, Sampler_class_texture) = texture;\n return NEW_REF(sampler->wrapper);\n}\n\n\/* MGLSampler.use(location)\n *\/\nPyObject * MGLSampler_meth_use(MGLSampler * self, PyObject * arg) {\n PyObject * wrapper = SLOT(self->wrapper, PyObject, Sampler_class_texture);\n MGLTexture * texture = SLOT(wrapper, MGLTexture, Texture_class_mglo);\n\n int location = PyLong_AsLong(arg);\n self->context->bind_sampler(location, texture->texture_target, texture->texture_obj, self->sampler_obj);\n Py_RETURN_NONE;\n}\n\nint MGLSampler_set_filter(MGLSampler * self, PyObject * value) {\n return 0;\n}\n\nenum MGLSamplerWrapModes {\n MGL_CLAMP_TO_EDGE = 0x01,\n MGL_REPEAT = 0x02,\n MGL_MIRRORED_REPEAT = 0x04,\n MGL_MIRROR_CLAMP_TO_EDGE = 0x08,\n MGL_CLAMP_TO_BORDER = 0x10,\n};\n\nint MGLSampler_set_wrap(MGLSampler * self, PyObject * value) {\n int wrap = PyLong_AsLong(value);\n SLOT(self->wrapper, PyObject, Sampler_class_wrap) = PyLong_FromLong(wrap);\n switch (((unsigned char *)&wrap)[0]) {\n case 0:\n case MGL_CLAMP_TO_EDGE:\n \t\tself->context->gl.SamplerParameteri(self->sampler_obj, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);\n break;\n case MGL_REPEAT:\n \t\tself->context->gl.SamplerParameteri(self->sampler_obj, GL_TEXTURE_WRAP_S, GL_REPEAT);\n break;\n case MGL_MIRRORED_REPEAT:\n \t\tself->context->gl.SamplerParameteri(self->sampler_obj, GL_TEXTURE_WRAP_S, GL_MIRRORED_REPEAT);\n break;\n case MGL_MIRROR_CLAMP_TO_EDGE:\n \t\tself->context->gl.SamplerParameteri(self->sampler_obj, GL_TEXTURE_WRAP_S, GL_MIRROR_CLAMP_TO_EDGE);\n break;\n case MGL_CLAMP_TO_BORDER:\n \t\tself->context->gl.SamplerParameteri(self->sampler_obj, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER);\n break;\n default:\n \/\/ TODO: error\n return -1;\n }\n switch (((unsigned char *)&wrap)[1]) {\n case 0:\n case MGL_CLAMP_TO_EDGE:\n \t\tself->context->gl.SamplerParameteri(self->sampler_obj, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);\n break;\n case MGL_REPEAT:\n \t\tself->context->gl.SamplerParameteri(self->sampler_obj, GL_TEXTURE_WRAP_T, GL_REPEAT);\n break;\n case MGL_MIRRORED_REPEAT:\n \t\tself->context->gl.SamplerParameteri(self->sampler_obj, GL_TEXTURE_WRAP_T, GL_MIRRORED_REPEAT);\n break;\n case MGL_MIRROR_CLAMP_TO_EDGE:\n \t\tself->context->gl.SamplerParameteri(self->sampler_obj, GL_TEXTURE_WRAP_T, GL_MIRROR_CLAMP_TO_EDGE);\n break;\n case MGL_CLAMP_TO_BORDER:\n \t\tself->context->gl.SamplerParameteri(self->sampler_obj, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER);\n break;\n default:\n \/\/ TODO: error\n return -1;\n }\n PyObject * wrapper = SLOT(self->wrapper, PyObject, Sampler_class_texture);\n MGLTexture * texture = SLOT(wrapper, MGLTexture, Texture_class_mglo);\n if (texture->texture_target == GL_TEXTURE_3D) {\n switch (((unsigned char *)&wrap)[2]) {\n case 0:\n case MGL_CLAMP_TO_EDGE:\n self->context->gl.SamplerParameteri(self->sampler_obj, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);\n break;\n case MGL_REPEAT:\n self->context->gl.SamplerParameteri(self->sampler_obj, GL_TEXTURE_WRAP_R, GL_REPEAT);\n break;\n case MGL_MIRRORED_REPEAT:\n self->context->gl.SamplerParameteri(self->sampler_obj, GL_TEXTURE_WRAP_R, GL_MIRRORED_REPEAT);\n break;\n case MGL_MIRROR_CLAMP_TO_EDGE:\n self->context->gl.SamplerParameteri(self->sampler_obj, GL_TEXTURE_WRAP_R, GL_MIRROR_CLAMP_TO_EDGE);\n break;\n case MGL_CLAMP_TO_BORDER:\n self->context->gl.SamplerParameteri(self->sampler_obj, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_BORDER);\n break;\n default:\n \/\/ TODO: error\n return -1;\n }\n } else if (((unsigned char *)&wrap)[2]) {\n return -1;\n }\n return 0;\n}\n\nint MGLSampler_set_border_color(MGLSampler * self, PyObject * value) {\n PyObject * border_color = PySequence_Fast(value, \"not iterable\");\n if (!border_color) {\n return -1;\n }\n float color[4] = {};\n switch (PySequence_Fast_GET_SIZE(border_color)) {\n case 4:\n color[3] = (float)PyFloat_AsDouble(PySequence_Fast_GET_ITEM(border_color, 3));\n case 3:\n color[2] = (float)PyFloat_AsDouble(PySequence_Fast_GET_ITEM(border_color, 2));\n case 2:\n color[1] = (float)PyFloat_AsDouble(PySequence_Fast_GET_ITEM(border_color, 1));\n case 1:\n color[0] = (float)PyFloat_AsDouble(PySequence_Fast_GET_ITEM(border_color, 0));\n default:\n \/\/ TODO: error\n return -1;\n }\n\n\tself->context->gl.SamplerParameterfv(self->sampler_obj, GL_TEXTURE_BORDER_COLOR, color);\n return 0;\n}\n\nint MGLSampler_set_anisotropy(MGLSampler * self, PyObject * value) {\n\tfloat anisotropy = PyFloat_AsDouble(value);\n if (anisotropy < 1.0) {\n anisotropy = 1.0;\n }\n \/\/ if (anisotropy > max_anisotropy) {\n \/\/ anisotropy = max_anisotropy;\n \/\/ }\n SLOT(self->wrapper, PyObject, Sampler_class_max_lod) = PyFloat_FromDouble(anisotropy);\n\tself->context->gl.SamplerParameterf(self->sampler_obj, GL_TEXTURE_MAX_ANISOTROPY, anisotropy);\n return 0;\n}\n\nint MGLSampler_set_lod_range(MGLSampler * self, PyObject * value) {\n PyObject * lod_range = PySequence_Fast(value, \"not iterable\");\n if (!lod_range) {\n return -1;\n }\n\n int min_lod;\n int max_lod;\n float lod_bias = 0.0f;\n switch (PySequence_Fast_GET_SIZE(lod_range)) {\n case 3:\n lod_bias = (float)PyFloat_AsDouble(PySequence_Fast_GET_ITEM(lod_range, 2));\n case 2:\n min_lod = PyLong_AsLong(PySequence_Fast_GET_ITEM(lod_range, 0));\n max_lod = PyLong_AsLong(PySequence_Fast_GET_ITEM(lod_range, 1));\n default:\n \/\/ TODO: error\n return -1;\n }\n\n \/\/ SLOT(self->wrapper, PyObject, Sampler_class_max_lod) = PyFloat_FromDouble(anisotropy);\n\tself->context->gl.SamplerParameteri(self->sampler_obj, GL_TEXTURE_MIN_LOD, min_lod);\n\tself->context->gl.SamplerParameteri(self->sampler_obj, GL_TEXTURE_MIN_LOD, max_lod);\n\tself->context->gl.SamplerParameterf(self->sampler_obj, GL_TEXTURE_LOD_BIAS, lod_bias);\n return 0;\n}\n\n#if PY_VERSION_HEX >= 0x03070000\n\nPyMethodDef MGLSampler_methods[] = {\n {\"use\", (PyCFunction)MGLSampler_meth_use, METH_O, 0},\n {0},\n};\n\n#else\n\nPyMethodDef MGLSampler_methods[] = {\n {\"use\", (PyCFunction)MGLSampler_meth_use, METH_O, 0},\n {0},\n};\n\n#endif\n\nPyGetSetDef MGLSampler_getset[] = {\n {\"filter\", 0, (setter)MGLSampler_set_filter, 0, 0},\n {\"wrap\", 0, (setter)MGLSampler_set_wrap, 0, 0},\n {\"anisotropy\", 0, (setter)MGLSampler_set_anisotropy, 0, 0},\n {\"border_color\", 0, (setter)MGLSampler_set_border_color, 0, 0},\n {\"lod_range\", 0, (setter)MGLSampler_set_lod_range, 0, 0},\n {0},\n};\n\nPyType_Slot MGLSampler_slots[] = {\n {Py_tp_methods, MGLSampler_methods},\n {Py_tp_getset, MGLSampler_getset},\n {0},\n};\n\nPyType_Spec MGLSampler_spec = {\n mgl_ext \".Sampler\",\n sizeof(MGLSampler),\n 0,\n Py_TPFLAGS_DEFAULT,\n MGLSampler_slots,\n};\n<commit_msg>fix anisotropy setter<commit_after>#include \"sampler.hpp\"\n#include \"context.hpp\"\n#include \"texture.hpp\"\n\n#include \"internal\/wrapper.hpp\"\n\n#include \"internal\/modules.hpp\"\n#include \"internal\/tools.hpp\"\n#include \"internal\/glsl.hpp\"\n\n\/* MGLContext.sampler(texture)\n *\/\nPyObject * MGLContext_meth_sampler(MGLContext * self, PyObject * const * args, Py_ssize_t nargs) {\n if (nargs != 1) {\n \/\/ TODO: error\n return 0;\n }\n\n PyObject * texture = args[0];\n\n MGLSampler * sampler = MGLContext_new_object(self, Sampler);\n\n const GLMethods & gl = self->gl;\n gl.GenSamplers(1, (GLuint *)&sampler->sampler_obj);\n\n if (!sampler->sampler_obj) {\n PyErr_Format(moderngl_error, \"cannot create sampler\");\n Py_DECREF(sampler);\n return 0;\n }\n\n gl.SamplerParameteri(sampler->sampler_obj, GL_TEXTURE_MIN_FILTER, GL_NEAREST);\n gl.SamplerParameteri(sampler->sampler_obj, GL_TEXTURE_MAG_FILTER, GL_NEAREST);\n\n SLOT(sampler->wrapper, PyObject, Sampler_class_texture) = texture;\n return NEW_REF(sampler->wrapper);\n}\n\n\/* MGLSampler.use(location)\n *\/\nPyObject * MGLSampler_meth_use(MGLSampler * self, PyObject * arg) {\n PyObject * wrapper = SLOT(self->wrapper, PyObject, Sampler_class_texture);\n MGLTexture * texture = SLOT(wrapper, MGLTexture, Texture_class_mglo);\n\n int location = PyLong_AsLong(arg);\n self->context->bind_sampler(location, texture->texture_target, texture->texture_obj, self->sampler_obj);\n Py_RETURN_NONE;\n}\n\nint MGLSampler_set_filter(MGLSampler * self, PyObject * value) {\n return 0;\n}\n\nenum MGLSamplerWrapModes {\n MGL_CLAMP_TO_EDGE = 0x01,\n MGL_REPEAT = 0x02,\n MGL_MIRRORED_REPEAT = 0x04,\n MGL_MIRROR_CLAMP_TO_EDGE = 0x08,\n MGL_CLAMP_TO_BORDER = 0x10,\n};\n\nint MGLSampler_set_wrap(MGLSampler * self, PyObject * value) {\n int wrap = PyLong_AsLong(value);\n SLOT(self->wrapper, PyObject, Sampler_class_wrap) = PyLong_FromLong(wrap);\n switch (((unsigned char *)&wrap)[0]) {\n case 0:\n case MGL_CLAMP_TO_EDGE:\n \t\tself->context->gl.SamplerParameteri(self->sampler_obj, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);\n break;\n case MGL_REPEAT:\n \t\tself->context->gl.SamplerParameteri(self->sampler_obj, GL_TEXTURE_WRAP_S, GL_REPEAT);\n break;\n case MGL_MIRRORED_REPEAT:\n \t\tself->context->gl.SamplerParameteri(self->sampler_obj, GL_TEXTURE_WRAP_S, GL_MIRRORED_REPEAT);\n break;\n case MGL_MIRROR_CLAMP_TO_EDGE:\n \t\tself->context->gl.SamplerParameteri(self->sampler_obj, GL_TEXTURE_WRAP_S, GL_MIRROR_CLAMP_TO_EDGE);\n break;\n case MGL_CLAMP_TO_BORDER:\n \t\tself->context->gl.SamplerParameteri(self->sampler_obj, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER);\n break;\n default:\n \/\/ TODO: error\n return -1;\n }\n switch (((unsigned char *)&wrap)[1]) {\n case 0:\n case MGL_CLAMP_TO_EDGE:\n \t\tself->context->gl.SamplerParameteri(self->sampler_obj, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);\n break;\n case MGL_REPEAT:\n \t\tself->context->gl.SamplerParameteri(self->sampler_obj, GL_TEXTURE_WRAP_T, GL_REPEAT);\n break;\n case MGL_MIRRORED_REPEAT:\n \t\tself->context->gl.SamplerParameteri(self->sampler_obj, GL_TEXTURE_WRAP_T, GL_MIRRORED_REPEAT);\n break;\n case MGL_MIRROR_CLAMP_TO_EDGE:\n \t\tself->context->gl.SamplerParameteri(self->sampler_obj, GL_TEXTURE_WRAP_T, GL_MIRROR_CLAMP_TO_EDGE);\n break;\n case MGL_CLAMP_TO_BORDER:\n \t\tself->context->gl.SamplerParameteri(self->sampler_obj, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER);\n break;\n default:\n \/\/ TODO: error\n return -1;\n }\n PyObject * wrapper = SLOT(self->wrapper, PyObject, Sampler_class_texture);\n MGLTexture * texture = SLOT(wrapper, MGLTexture, Texture_class_mglo);\n if (texture->texture_target == GL_TEXTURE_3D) {\n switch (((unsigned char *)&wrap)[2]) {\n case 0:\n case MGL_CLAMP_TO_EDGE:\n self->context->gl.SamplerParameteri(self->sampler_obj, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);\n break;\n case MGL_REPEAT:\n self->context->gl.SamplerParameteri(self->sampler_obj, GL_TEXTURE_WRAP_R, GL_REPEAT);\n break;\n case MGL_MIRRORED_REPEAT:\n self->context->gl.SamplerParameteri(self->sampler_obj, GL_TEXTURE_WRAP_R, GL_MIRRORED_REPEAT);\n break;\n case MGL_MIRROR_CLAMP_TO_EDGE:\n self->context->gl.SamplerParameteri(self->sampler_obj, GL_TEXTURE_WRAP_R, GL_MIRROR_CLAMP_TO_EDGE);\n break;\n case MGL_CLAMP_TO_BORDER:\n self->context->gl.SamplerParameteri(self->sampler_obj, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_BORDER);\n break;\n default:\n \/\/ TODO: error\n return -1;\n }\n } else if (((unsigned char *)&wrap)[2]) {\n return -1;\n }\n return 0;\n}\n\nint MGLSampler_set_border_color(MGLSampler * self, PyObject * value) {\n PyObject * border_color = PySequence_Fast(value, \"not iterable\");\n if (!border_color) {\n return -1;\n }\n float color[4] = {};\n switch (PySequence_Fast_GET_SIZE(border_color)) {\n case 4:\n color[3] = (float)PyFloat_AsDouble(PySequence_Fast_GET_ITEM(border_color, 3));\n case 3:\n color[2] = (float)PyFloat_AsDouble(PySequence_Fast_GET_ITEM(border_color, 2));\n case 2:\n color[1] = (float)PyFloat_AsDouble(PySequence_Fast_GET_ITEM(border_color, 1));\n case 1:\n color[0] = (float)PyFloat_AsDouble(PySequence_Fast_GET_ITEM(border_color, 0));\n default:\n \/\/ TODO: error\n return -1;\n }\n\n\tself->context->gl.SamplerParameterfv(self->sampler_obj, GL_TEXTURE_BORDER_COLOR, color);\n return 0;\n}\n\nint MGLSampler_set_anisotropy(MGLSampler * self, PyObject * value) {\n\tfloat anisotropy = (float)PyFloat_AsDouble(value);\n if (anisotropy < 1.0) {\n anisotropy = 1.0;\n }\n \/\/ if (anisotropy > max_anisotropy) {\n \/\/ anisotropy = max_anisotropy;\n \/\/ }\n \/\/ SLOT(self->wrapper, PyObject, Sampler_class_max_lod) = PyFloat_FromDouble(anisotropy);\n\tself->context->gl.SamplerParameterf(self->sampler_obj, GL_TEXTURE_MAX_ANISOTROPY, anisotropy);\n return 0;\n}\n\nint MGLSampler_set_lod_range(MGLSampler * self, PyObject * value) {\n PyObject * lod_range = PySequence_Fast(value, \"not iterable\");\n if (!lod_range) {\n return -1;\n }\n\n int min_lod;\n int max_lod;\n float lod_bias = 0.0f;\n switch (PySequence_Fast_GET_SIZE(lod_range)) {\n case 3:\n lod_bias = (float)PyFloat_AsDouble(PySequence_Fast_GET_ITEM(lod_range, 2));\n case 2:\n min_lod = PyLong_AsLong(PySequence_Fast_GET_ITEM(lod_range, 0));\n max_lod = PyLong_AsLong(PySequence_Fast_GET_ITEM(lod_range, 1));\n default:\n \/\/ TODO: error\n return -1;\n }\n\n \/\/ SLOT(self->wrapper, PyObject, Sampler_class_max_lod) = PyFloat_FromDouble(anisotropy);\n\tself->context->gl.SamplerParameteri(self->sampler_obj, GL_TEXTURE_MIN_LOD, min_lod);\n\tself->context->gl.SamplerParameteri(self->sampler_obj, GL_TEXTURE_MIN_LOD, max_lod);\n\tself->context->gl.SamplerParameterf(self->sampler_obj, GL_TEXTURE_LOD_BIAS, lod_bias);\n return 0;\n}\n\n#if PY_VERSION_HEX >= 0x03070000\n\nPyMethodDef MGLSampler_methods[] = {\n {\"use\", (PyCFunction)MGLSampler_meth_use, METH_O, 0},\n {0},\n};\n\n#else\n\nPyMethodDef MGLSampler_methods[] = {\n {\"use\", (PyCFunction)MGLSampler_meth_use, METH_O, 0},\n {0},\n};\n\n#endif\n\nPyGetSetDef MGLSampler_getset[] = {\n {\"filter\", 0, (setter)MGLSampler_set_filter, 0, 0},\n {\"wrap\", 0, (setter)MGLSampler_set_wrap, 0, 0},\n {\"anisotropy\", 0, (setter)MGLSampler_set_anisotropy, 0, 0},\n {\"border_color\", 0, (setter)MGLSampler_set_border_color, 0, 0},\n {\"lod_range\", 0, (setter)MGLSampler_set_lod_range, 0, 0},\n {0},\n};\n\nPyType_Slot MGLSampler_slots[] = {\n {Py_tp_methods, MGLSampler_methods},\n {Py_tp_getset, MGLSampler_getset},\n {0},\n};\n\nPyType_Spec MGLSampler_spec = {\n mgl_ext \".Sampler\",\n sizeof(MGLSampler),\n 0,\n Py_TPFLAGS_DEFAULT,\n MGLSampler_slots,\n};\n<|endoftext|>"} {"text":"<commit_before>\/*\n* Copyright 2016 Nu-book Inc.\n* Copyright 2016 ZXing authors\n* Copyright 2017 Axel Waggershauser\n*\n* Licensed under the Apache License, Version 2.0 (the \"License\");\n* you may not use this file except in compliance with the License.\n* You may obtain a copy of the License at\n*\n* http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n*\n* Unless required by applicable law or agreed to in writing, software\n* distributed under the License is distributed on an \"AS IS\" BASIS,\n* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n* See the License for the specific language governing permissions and\n* limitations under the License.\n*\/\n\n#include \"GenericGFPoly.h\"\n\n#include \"GenericGF.h\"\n#include \"ZXConfig.h\"\n#include \"ZXContainerAlgorithms.h\"\n\n#include <algorithm>\n#include <cassert>\n#include <stdexcept>\n\nnamespace ZXing {\n\nint\nGenericGFPoly::evaluateAt(int a) const\n{\n\tif (a == 0)\n\t\t\/\/ Just return the x^0 coefficient\n\t\treturn constant();\n\n\tif (a == 1)\n\t\t\/\/ Just the sum of the coefficients\n\t\treturn Reduce(_coefficients, 0, [](auto a, auto b) { return a ^ b; });\n\n\tint result = _coefficients[0];\n\tfor (size_t i = 1; i < _coefficients.size(); ++i)\n\t\tresult = _field->multiply(a, result) ^ _coefficients[i];\n\treturn result;\n}\n\nGenericGFPoly& GenericGFPoly::addOrSubtract(GenericGFPoly& other)\n{\n\tassert(_field == other._field); \/\/ \"GenericGFPolys do not have same GenericGF field\"\n\t\n\tif (isZero()) {\n\t\tswap(*this, other);\n\t\treturn *this;\n\t}\n\t\n\tif (other.isZero())\n\t\treturn *this;\n\n\tauto& smallerCoefs = other._coefficients;\n\tauto& largerCoefs = _coefficients;\n\tif (smallerCoefs.size() > largerCoefs.size())\n\t\tstd::swap(smallerCoefs, largerCoefs);\n\n\tsize_t lengthDiff = largerCoefs.size() - smallerCoefs.size();\n\n\t\/\/ high-order terms only found in higher-degree polynomial's coefficients stay untouched\n\tfor (size_t i = lengthDiff; i < largerCoefs.size(); ++i)\n\t\tlargerCoefs[i] ^= smallerCoefs[i - lengthDiff];\n\n\tnormalize();\n\treturn *this;\n}\n\nGenericGFPoly&\nGenericGFPoly::multiply(const GenericGFPoly& other)\n{\n\tassert(_field == other._field); \/\/ \"GenericGFPolys do not have same GenericGF field\"\n\n\tif (isZero() || other.isZero())\n\t\treturn setMonomial(0);\n\n\tauto& a = _coefficients;\n\tauto& b = other._coefficients;\n\n\t\/\/ To disable the use of the malloc cache, simply uncomment:\n\t\/\/ Coefficients _cache;\n\t_cache.resize(a.size() + b.size() - 1);\n\tstd::fill(_cache.begin(), _cache.end(), 0);\n\tfor (size_t i = 0; i < a.size(); ++i)\n\t\tfor (size_t j = 0; j < b.size(); ++j)\n\t\t\t_cache[i + j] ^= _field->multiply(a[i], b[j]);\n\n\t_coefficients.swap(_cache);\n\n\tnormalize();\n\treturn *this;\n}\n\nGenericGFPoly&\nGenericGFPoly::multiplyByMonomial(int coefficient, int degree)\n{\n\tassert(degree >= 0);\n\n\tif (coefficient == 0)\n\t\treturn setMonomial(0);\n\n\tfor (int& c : _coefficients)\n\t\tc = _field->multiply(c, coefficient);\n\n\t_coefficients.resize(_coefficients.size() + degree, 0);\n\n\tnormalize();\n\treturn *this;\n}\n\nGenericGFPoly&\nGenericGFPoly::divide(const GenericGFPoly& other, GenericGFPoly& quotient)\n{\n\tassert(_field == other._field); \/\/ \"GenericGFPolys do not have same GenericGF field\"\n\n\tif (other.isZero())\n\t\tthrow std::invalid_argument(\"Divide by 0\");\n\n\tquotient.setField(*_field);\n\tquotient.setMonomial(0);\n\tauto& remainder = *this;\n\n\tconst int inverseDenominatorLeadingTerm = _field->inverse(other.leadingCoefficient());\n\n\tZX_THREAD_LOCAL GenericGFPoly temp;\n\ttemp.setField(*_field);\n\n\twhile (remainder.degree() >= other.degree() && !remainder.isZero()) {\n\t\tint degreeDifference = remainder.degree() - other.degree();\n\t\tint scale = _field->multiply(remainder.leadingCoefficient(), inverseDenominatorLeadingTerm);\n\t\ttemp.setMonomial(scale, degreeDifference);\n\t\tquotient.addOrSubtract(temp);\n\t\ttemp = other;\n\t\ttemp.multiplyByMonomial(scale, degreeDifference);\n\t\tremainder.addOrSubtract(temp);\n\t}\n\n\treturn *this;\n}\n\nvoid GenericGFPoly::normalize()\n{\n\tauto firstNonZero = FindIf(_coefficients, [](int c){ return c != 0; });\n\t\/\/ Leading term must be non-zero for anything except the constant polynomial \"0\"\n\tif (firstNonZero != _coefficients.begin()) {\n\t\tif (firstNonZero == _coefficients.end()) {\n\t\t\t_coefficients.resize(1, 0);\n\t\t} else {\n\t\t\tstd::copy(firstNonZero, _coefficients.end(), _coefficients.begin());\n\t\t\t_coefficients.resize(_coefficients.end() - firstNonZero);\n\t\t}\n\t}\n}\n\n} \/\/ namespace ZXing\n<commit_msg>ReedSolomon: use expanded synthetic division instead of long division<commit_after>\/*\n* Copyright 2016 Nu-book Inc.\n* Copyright 2016 ZXing authors\n* Copyright 2017 Axel Waggershauser\n*\n* Licensed under the Apache License, Version 2.0 (the \"License\");\n* you may not use this file except in compliance with the License.\n* You may obtain a copy of the License at\n*\n* http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n*\n* Unless required by applicable law or agreed to in writing, software\n* distributed under the License is distributed on an \"AS IS\" BASIS,\n* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n* See the License for the specific language governing permissions and\n* limitations under the License.\n*\/\n\n#include \"GenericGFPoly.h\"\n\n#include \"GenericGF.h\"\n#include \"ZXConfig.h\"\n#include \"ZXContainerAlgorithms.h\"\n\n#include <algorithm>\n#include <cassert>\n#include <stdexcept>\n\nnamespace ZXing {\n\nint\nGenericGFPoly::evaluateAt(int a) const\n{\n\tif (a == 0)\n\t\t\/\/ Just return the x^0 coefficient\n\t\treturn constant();\n\n\tif (a == 1)\n\t\t\/\/ Just the sum of the coefficients\n\t\treturn Reduce(_coefficients, 0, [](auto a, auto b) { return a ^ b; });\n\n\tint result = _coefficients[0];\n\tfor (size_t i = 1; i < _coefficients.size(); ++i)\n\t\tresult = _field->multiply(a, result) ^ _coefficients[i];\n\treturn result;\n}\n\nGenericGFPoly& GenericGFPoly::addOrSubtract(GenericGFPoly& other)\n{\n\tassert(_field == other._field); \/\/ \"GenericGFPolys do not have same GenericGF field\"\n\t\n\tif (isZero()) {\n\t\tswap(*this, other);\n\t\treturn *this;\n\t}\n\t\n\tif (other.isZero())\n\t\treturn *this;\n\n\tauto& smallerCoefs = other._coefficients;\n\tauto& largerCoefs = _coefficients;\n\tif (smallerCoefs.size() > largerCoefs.size())\n\t\tstd::swap(smallerCoefs, largerCoefs);\n\n\tsize_t lengthDiff = largerCoefs.size() - smallerCoefs.size();\n\n\t\/\/ high-order terms only found in higher-degree polynomial's coefficients stay untouched\n\tfor (size_t i = lengthDiff; i < largerCoefs.size(); ++i)\n\t\tlargerCoefs[i] ^= smallerCoefs[i - lengthDiff];\n\n\tnormalize();\n\treturn *this;\n}\n\nGenericGFPoly&\nGenericGFPoly::multiply(const GenericGFPoly& other)\n{\n\tassert(_field == other._field); \/\/ \"GenericGFPolys do not have same GenericGF field\"\n\n\tif (isZero() || other.isZero())\n\t\treturn setMonomial(0);\n\n\tauto& a = _coefficients;\n\tauto& b = other._coefficients;\n\n\t\/\/ To disable the use of the malloc cache, simply uncomment:\n\t\/\/ Coefficients _cache;\n\t_cache.resize(a.size() + b.size() - 1);\n\tstd::fill(_cache.begin(), _cache.end(), 0);\n\tfor (size_t i = 0; i < a.size(); ++i)\n\t\tfor (size_t j = 0; j < b.size(); ++j)\n\t\t\t_cache[i + j] ^= _field->multiply(a[i], b[j]);\n\n\t_coefficients.swap(_cache);\n\n\tnormalize();\n\treturn *this;\n}\n\nGenericGFPoly&\nGenericGFPoly::multiplyByMonomial(int coefficient, int degree)\n{\n\tassert(degree >= 0);\n\n\tif (coefficient == 0)\n\t\treturn setMonomial(0);\n\n\tfor (int& c : _coefficients)\n\t\tc = _field->multiply(c, coefficient);\n\n\t_coefficients.resize(_coefficients.size() + degree, 0);\n\n\tnormalize();\n\treturn *this;\n}\n\nGenericGFPoly&\nGenericGFPoly::divide(const GenericGFPoly& other, GenericGFPoly& quotient)\n{\n\tassert(_field == other._field); \/\/ \"GenericGFPolys do not have same GenericGF field\"\n\n\tif (other.isZero())\n\t\tthrow std::invalid_argument(\"Divide by 0\");\n\n\tquotient.setField(*_field);\n\tif (degree() < other.degree()) {\n\t\t\/\/ the remainder is this and the quotient is 0\n\t\tquotient.setMonomial(0);\n\t\treturn *this;\n\t}\n\n\t\/\/ use Expanded Synthetic Division (see https:\/\/en.wikiversity.org\/wiki\/Reed%E2%80%93Solomon_codes_for_coders):\n\t\/\/ we use the memory from this (the divident) and swap it with quotient, wich will then accumulate the result as\n\t\/\/ [quotient : remainder]. we later copy back the remainder into this and shorten the quotient.\n\tstd::swap(*this, quotient);\n\tauto& divisor = other._coefficients;\n\tauto& result = quotient._coefficients;\n\tauto normalizer = _field->inverse(divisor[0]);\n\tfor (int i = 0; i < Size(result) - (Size(divisor) - 1); ++i) {\n\t\tauto& ci = result[i];\n\t\tif (ci == 0)\n\t\t\tcontinue;\n\n\t\tci = _field->multiply(ci, normalizer);\n\n\t\t\/\/ we always skip the first coefficient of the divisior, because it's only used to normalize the dividend coefficient\n\t\tfor (int j = 1; j < Size(divisor); ++j)\n\t\t\tresult[i + j] ^= _field->multiply(divisor[j], ci); \/\/ equivalent to: result[i + j] += -divisor[j] * ci\n\t}\n\n\t\/\/ extract the normalized remainder from result\n\tauto firstNonZero = std::find_if(result.end() - other.degree(), result.end(), [](int c){ return c != 0; });\n\tif (firstNonZero == result.end()) {\n\t\tsetMonomial(0);\n\t} else {\n\t\t_coefficients.resize(result.end() - firstNonZero);\n\t\tstd::copy(firstNonZero, result.end(), _coefficients.begin());\n\t}\n\t\/\/ cut off the tail with the remainder to leave the quotient\n\tresult.resize(result.size() - other.degree());\n\n\treturn *this;\n}\n\nvoid GenericGFPoly::normalize()\n{\n\tauto firstNonZero = FindIf(_coefficients, [](int c){ return c != 0; });\n\t\/\/ Leading term must be non-zero for anything except the constant polynomial \"0\"\n\tif (firstNonZero != _coefficients.begin()) {\n\t\tif (firstNonZero == _coefficients.end()) {\n\t\t\t_coefficients.resize(1, 0);\n\t\t} else {\n\t\t\tstd::copy(firstNonZero, _coefficients.end(), _coefficients.begin());\n\t\t\t_coefficients.resize(_coefficients.end() - firstNonZero);\n\t\t}\n\t}\n}\n\n} \/\/ namespace ZXing\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright © 2011, Université catholique de Louvain\n\/\/ All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright notice,\n\/\/ this list of conditions and the following disclaimer.\n\/\/ * Redistributions in binary form must reproduce the above copyright notice,\n\/\/ this list of conditions and the following disclaimer in the documentation\n\/\/ and\/or other materials provided with the distribution.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n\/\/ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\/\/ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\/\/ ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n\/\/ LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n\/\/ CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n\/\/ SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n\/\/ INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n\/\/ CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n\/\/ ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n\/\/ POSSIBILITY OF SUCH DAMAGE.\n\n#ifndef __VM_H\n#define __VM_H\n\n#include <stdlib.h>\n\n#include \"memmanager.hh\"\n#include \"store.hh\"\n#include \"threadpool.hh\"\n#include \"atomtable.hh\"\n\ntypedef bool (*PreemptionTest)(void* data);\n\nclass VirtualMachine {\npublic:\n VirtualMachine(PreemptionTest preemptionTest,\n void* preemptionTestData = nullptr) :\n _preemptionTest(preemptionTest), _preemptionTestData(preemptionTestData) {\n\n memoryManager.init();\n }\n\n StableNode* newVariable();\n\n void* malloc(size_t size) {\n return memoryManager.malloc(size);\n }\n\n void free(void* ptr, size_t size) {\n memoryManager.free(ptr, size);\n }\n\n void run();\n\n inline\n bool testPreemption();\n\n ThreadPool& getThreadPool() { return threadPool; }\nprivate:\n friend class Thread;\n friend class Implementation<Atom>;\n\n VirtualMachine(const VirtualMachine& src) {}\n\n friend void* operator new (size_t size, VM vm);\n friend void* operator new[] (size_t size, VM vm);\n\n void* getMemory(size_t size) {\n return memoryManager.getMemory(size);\n }\n\n \/\/ Called from the constructor of Thread\n void scheduleThread(Thread* thread);\n\n ThreadPool threadPool;\n AtomTable atomTable;\n\n PreemptionTest _preemptionTest;\n void* _preemptionTestData;\n\n MemoryManager memoryManager;\n};\n\nvoid* operator new (size_t size, VM vm) {\n return vm->getMemory(size);\n}\n\nvoid* operator new[] (size_t size, VM vm) {\n return vm->getMemory(size);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Inline VirtualMachine \/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nbool VirtualMachine::testPreemption() {\n return _preemptionTest(_preemptionTestData);\n}\n\n#endif \/\/ __VM_H\n<commit_msg>Add methods newStaticArray and deleteStaticArray in VM.<commit_after>\/\/ Copyright © 2011, Université catholique de Louvain\n\/\/ All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright notice,\n\/\/ this list of conditions and the following disclaimer.\n\/\/ * Redistributions in binary form must reproduce the above copyright notice,\n\/\/ this list of conditions and the following disclaimer in the documentation\n\/\/ and\/or other materials provided with the distribution.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n\/\/ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\/\/ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\/\/ ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n\/\/ LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n\/\/ CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n\/\/ SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n\/\/ INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n\/\/ CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n\/\/ ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n\/\/ POSSIBILITY OF SUCH DAMAGE.\n\n#ifndef __VM_H\n#define __VM_H\n\n#include <stdlib.h>\n\n#include \"memmanager.hh\"\n#include \"store.hh\"\n#include \"threadpool.hh\"\n#include \"atomtable.hh\"\n\ntypedef bool (*PreemptionTest)(void* data);\n\nclass VirtualMachine {\npublic:\n VirtualMachine(PreemptionTest preemptionTest,\n void* preemptionTestData = nullptr) :\n _preemptionTest(preemptionTest), _preemptionTestData(preemptionTestData) {\n\n memoryManager.init();\n }\n\n StableNode* newVariable();\n\n void* malloc(size_t size) {\n return memoryManager.malloc(size);\n }\n\n void free(void* ptr, size_t size) {\n memoryManager.free(ptr, size);\n }\n\n template <class T>\n StaticArray<T> newStaticArray(size_t size) {\n void* memory = malloc(size * sizeof(T));\n return StaticArray<T>(static_cast<T*>(memory), size);\n }\n\n template <class T>\n void deleteStaticArray(StaticArray<T> array, size_t size) {\n void* memory = static_cast<void*>((T*) array);\n free(memory, size * sizeof(T));\n }\n\n void run();\n\n inline\n bool testPreemption();\n\n ThreadPool& getThreadPool() { return threadPool; }\nprivate:\n friend class Thread;\n friend class Implementation<Atom>;\n\n VirtualMachine(const VirtualMachine& src) {}\n\n friend void* operator new (size_t size, VM vm);\n friend void* operator new[] (size_t size, VM vm);\n\n void* getMemory(size_t size) {\n return memoryManager.getMemory(size);\n }\n\n \/\/ Called from the constructor of Thread\n void scheduleThread(Thread* thread);\n\n ThreadPool threadPool;\n AtomTable atomTable;\n\n PreemptionTest _preemptionTest;\n void* _preemptionTestData;\n\n MemoryManager memoryManager;\n};\n\nvoid* operator new (size_t size, VM vm) {\n return vm->getMemory(size);\n}\n\nvoid* operator new[] (size_t size, VM vm) {\n return vm->getMemory(size);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Inline VirtualMachine \/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nbool VirtualMachine::testPreemption() {\n return _preemptionTest(_preemptionTestData);\n}\n\n#endif \/\/ __VM_H\n<|endoftext|>"} {"text":"<commit_before>\/* Copyright (C) 2018, Project Pluto. See LICENSE. *\/\n\n#include <string.h>\n#include <stdint.h>\n#include <assert.h>\n#include <stdlib.h>\n#include <stdio.h>\n#include \"norad.h\"\n\n#define PI 3.141592653589793238462643383279502884197\n#define TWOPI (2. * PI)\n#define MINUTES_PER_DAY 1440.\n#define MINUTES_PER_DAY_SQUARED (MINUTES_PER_DAY * MINUTES_PER_DAY)\n#define MINUTES_PER_DAY_CUBED (MINUTES_PER_DAY * MINUTES_PER_DAY_SQUARED)\n#define AE 1.0\n \/* distance units, earth radii *\/\n\n\/* TLEs have four angles on line 2, given in the form DDD.DDDD. This\ncan be parsed more quickly as an integer, then cast to double and\nconverted to radians, all in one step. *\/\n\nstatic int get_angle( const char *buff)\n{\n int rval = 0;\n\n while( *buff == ' ')\n buff++;\n while( *buff != ' ')\n {\n if( *buff != '.')\n rval = rval * 10 + (int)( *buff - '0');\n buff++;\n }\n return( rval);\n}\n\n\/* Converts the quasi scientific notation of the \"Motion Dot Dot\/6\" or\n\"BSTAR\" field to double. The input will always be of the form\n\nsdddddSe\n\n ....where s is blank or + or -; ddddd is a five-digit mantissa;\nS is + or - or blank; and e is a single-digit exponent. A decimal\npoint is assumed before the five-digit mantissa. *\/\n\nstatic double sci( const char *string)\n{\n double rval = 0.;\n\n if( string[1] != ' ')\n {\n const int ival = atoi( string);\n\n if( ival)\n {\n rval = (double)ival * 1.e-5;\n if( string[7] != '0')\n {\n int exponent = string[7] - '0';\n\n if( string[6] == '-')\n while( exponent--)\n rval *= .1;\n else\n while( exponent--)\n rval *= 10.;\n }\n }\n }\n return( rval);\n}\n\n\n\/* Does a checksum modulo 10 on the given line. Digits = their\nvalue, '-' = 1, all other chars = 0. Returns 0 if ok, a negative\nvalue if it's definitely not a TLE line, positive if it's all OK\nexcept the checksum. This last was added because people sometimes\nwant to use TLEs without worrying about the checksum. *\/\n\nint DLL_FUNC tle_checksum( const char *buff)\n{\n int rval = 0;\n int count = 69;\n\n if( (*buff != '1' && *buff != '2') || buff[1] != ' ')\n return( -1);\n while( --count)\n {\n if( *buff > '0' && *buff <= '9')\n rval += *buff - '0';\n else if( *buff == '-')\n rval++;\n if( *buff < ' ' || *buff > 'z') \/* invalid character *\/\n return( -2);\n buff++;\n }\n rval -= *buff++ - '0';\n if( *buff > ' ') \/* line unterminated *\/\n rval = -3;\n else\n {\n rval %= 10;\n if( rval < 0)\n rval += 10;\n }\n return( rval % 10);\n}\n\nstatic inline int mutant_dehex( const char ichar)\n{\n int rval;\n\n if( ichar <= '9' && ichar >= '0')\n rval = ichar - '0';\n else if( ichar >= 'A' && ichar <= 'Z')\n rval = ichar + 10 - 'A';\n else\n rval = -1;\n return( rval);\n}\n\n\/* The \"standard\" SDP4 model fails badly for very high-flying satellites.\nAs a non-standard extension, I'm simply storing state vectors for them,\nusing the following somewhat odd scheme :\n\n1 40391U 15007B 15091.99922241 sxxxxxxxx syyyyyyyy szzzzzzzzH 9997\n2 49391 [valid range, accuracy] saaaaaaaa sbbbbbbbb scccccccc 0 8\n\n Epoch, int'l & NORAD IDs are stored in the standard manner. The\n'ephemeris type' is H (rather than the otherwise universal 0). The\nxyz position and vx, vy, vz velocity are stored as 8-digit signed\nbase-36 integers, hence a range of +\/- 36^8 = about +\/- 2.82x10^12.\n\n x, y, z are in meters, and hence cover a range +\/- 18.9 AU.\nvx, vy, vz are in 10^-4 m\/s, range +\/- 94% c. *\/\n\nstatic double get_high_value( const char *iptr)\n{\n int64_t rval = 0;\n\n assert( *iptr == '+' || *iptr == '-');\n if( *iptr == '+' || *iptr == '-')\n {\n int i, digit;\n\n for( i = 1; i < 9; i++)\n {\n digit = mutant_dehex( iptr[i]);\n assert( digit >= 0);\n rval = rval * (int64_t)36 + (int64_t)digit;\n }\n if( *iptr == '-')\n rval = -rval;\n }\n return( (double)rval);\n}\n\n\/* Traditionally, NORAD numbers were stored as five digits. In 2020, new\ndetectors threatened to go past 100K objects; the 'Alpha-5' scheme allows\nthe first byte to be replaced by an uppercase letter, with I and O\nskipped. That gets us to 339999. Note that NORAD is encouraging us to\nswitch to other formats (XML, JSON, etc.) that allow nine-digit numbers.\n\n Should 340K numbers prove insufficient, the following scheme would\nuse all 34^5 = 45435424 possible combinations. d = digit, L = letter,\nx = either. We also could use lowercase letters and some others to\nget 10^9 combinations within five bytes with backward compatibility.\n\n(1) ddddd = 'traditional' scheme provides 100000 combinations;\n(2) Ldddd = Alpha5 scheme adds 240000;\n(3) xxxxL = 34^4*24 = 32072064 more;\n(4) xxxLd = 34^3*24*10 = 9432960 more;\n(5) xxLdd = 34^2*24*100 = 2774400 more;\n(6) xLddd = 34*24*1000 = 816000 more. *\/\n\nstatic int base34_to_int( const char c)\n{\n int offset;\n\n if( c >= '0' && c <= '9')\n offset = '0';\n else if( c >= 'A' && c <= 'H')\n offset = 'A' - 10;\n else if( c >= 'J' && c <= 'N')\n offset = 'J' - 18;\n else if( c >= 'P' && c <= 'Z')\n offset = 'P' - 23;\n else\n return( -1);\n return( c - offset);\n}\n\nstatic int get_norad_number( const char *buff)\n{\n const int ten_thousands = base34_to_int( *buff);\n\n if( ten_thousands >= 0)\n return( ten_thousands * 10000 + atoi( buff + 1));\n else\n return( 0);\n}\n\nstatic inline double get_eight_places( const char *ptr)\n{\n return( (double)atoi( ptr) + (double)atoi(ptr + 4) * 1e-8);\n}\n\n\/* Meteor 2-08 *\/\n\/* 1 13113U 88245.60005115 0.00000076 63463-4 0 5998 *\/\n\/* 2 13113 82.5386 288.0994 0015973 147.1294 213.0868 13.83869004325321 *\/\n\n#define J2000 2451545.5\n#define J1900 (J2000 - 36525. - 1.)\n\n\/* parse_elements returns:\n 0 if the elements are parsed without error;\n 1 if they're OK except the first line has a checksum error;\n 2 if they're OK except the second line has a checksum error;\n 3 if they're OK except both lines have checksum errors;\n a negative value if the lines aren't at all parseable *\/\n\nint DLL_FUNC parse_elements( const char *line1, const char *line2, tle_t *sat)\n{\n int rval, checksum_problem = 0;\n\n if( *line1 != '1' || *line2 != '2')\n rval = -4;\n else\n {\n rval = tle_checksum( line1);\n if( rval > 0)\n {\n checksum_problem = 1; \/* there's a checksum problem, but it's *\/\n rval = 0; \/* not fatal; continue processing the TLE *\/\n }\n }\n\n if( rval)\n rval -= 100;\n else\n {\n rval = tle_checksum( line2);\n if( rval > 0)\n {\n checksum_problem |= 2; \/* there's a checksum problem, but it's *\/\n rval = 0; \/* not fatal; continue processing the TLE *\/\n }\n }\n\n if( !rval)\n {\n char tbuff[13];\n int year = line1[19] - '0';\n\n if( line1[18] >= '0')\n year += (line1[18] - '0') * 10;\n if( year < 57) \/* cycle around Y2K *\/\n year += 100;\n sat->epoch = get_eight_places( line1 + 20) + J1900\n + (double)( year * 365 + (year - 1) \/ 4);\n sat->norad_number = get_norad_number( line1 + 2);\n memcpy( tbuff, line1 + 64, 4);\n tbuff[4] = '\\0';\n sat->bulletin_number = atoi( tbuff);\n sat->classification = line1[7]; \/* almost always 'U' *\/\n memcpy( sat->intl_desig, line1 + 9, 8);\n sat->intl_desig[8] = '\\0';\n memcpy( tbuff, line2 + 63, 5);\n tbuff[5] = '\\0';\n sat->revolution_number = atoi( tbuff);\n sat->ephemeris_type = line1[62];\n if( sat->ephemeris_type == 'H')\n {\n size_t i;\n double *state_vect = &sat->xincl;\n\n for( i = 0; i < 3; i++)\n {\n state_vect[i] = get_high_value( line1 + 33 + i * 10);\n state_vect[i + 3] = get_high_value( line2 + 33 + i * 10) * 1e-4;\n }\n return( 0);\n }\n\n sat->xmo = (double)get_angle( line2 + 43) * (PI \/ 180e+4);\n sat->xnodeo = (double)get_angle( line2 + 17) * (PI \/ 180e+4);\n sat->omegao = (double)get_angle( line2 + 34) * (PI \/ 180e+4);\n sat->xincl = (double)get_angle( line2 + 8) * (PI \/ 180e+4);\n sat->eo = atoi( line2 + 26) * 1.e-7;\n\n \/* Make sure mean motion is null-terminated, since rev. no.\n may immediately follow. *\/\n memcpy( tbuff, line2 + 51, 12);\n tbuff[12] = '\\0';\n \/* Input mean motion, derivative of mean motion and second *\/\n \/* deriv of mean motion, are all in revolutions and days. *\/\n \/* Convert them here to radians and minutes: *\/\n sat->xno = get_eight_places( tbuff) * TWOPI \/ MINUTES_PER_DAY;\n sat->xndt2o = (double)atoi( line1 + 35)\n * 1.e-8 * TWOPI \/ MINUTES_PER_DAY_SQUARED;\n if( line1[33] == '-')\n sat->xndt2o *= -1.;\n sat->xndd6o = sci( line1 + 44) * TWOPI \/ MINUTES_PER_DAY_CUBED;\n\n sat->bstar = sci( line1 + 53) * AE;\n }\n return( rval ? rval : checksum_problem);\n}\n<commit_msg>Many TLEs store the NORAD number with spaces instead of leading zeroes.<commit_after>\/* Copyright (C) 2018, Project Pluto. See LICENSE. *\/\n\n#include <string.h>\n#include <stdint.h>\n#include <assert.h>\n#include <stdlib.h>\n#include <stdio.h>\n#include \"norad.h\"\n\n#define PI 3.141592653589793238462643383279502884197\n#define TWOPI (2. * PI)\n#define MINUTES_PER_DAY 1440.\n#define MINUTES_PER_DAY_SQUARED (MINUTES_PER_DAY * MINUTES_PER_DAY)\n#define MINUTES_PER_DAY_CUBED (MINUTES_PER_DAY * MINUTES_PER_DAY_SQUARED)\n#define AE 1.0\n \/* distance units, earth radii *\/\n\n\/* TLEs have four angles on line 2, given in the form DDD.DDDD. This\ncan be parsed more quickly as an integer, then cast to double and\nconverted to radians, all in one step. *\/\n\nstatic int get_angle( const char *buff)\n{\n int rval = 0;\n\n while( *buff == ' ')\n buff++;\n while( *buff != ' ')\n {\n if( *buff != '.')\n rval = rval * 10 + (int)( *buff - '0');\n buff++;\n }\n return( rval);\n}\n\n\/* Converts the quasi scientific notation of the \"Motion Dot Dot\/6\" or\n\"BSTAR\" field to double. The input will always be of the form\n\nsdddddSe\n\n ....where s is blank or + or -; ddddd is a five-digit mantissa;\nS is + or - or blank; and e is a single-digit exponent. A decimal\npoint is assumed before the five-digit mantissa. *\/\n\nstatic double sci( const char *string)\n{\n double rval = 0.;\n\n if( string[1] != ' ')\n {\n const int ival = atoi( string);\n\n if( ival)\n {\n rval = (double)ival * 1.e-5;\n if( string[7] != '0')\n {\n int exponent = string[7] - '0';\n\n if( string[6] == '-')\n while( exponent--)\n rval *= .1;\n else\n while( exponent--)\n rval *= 10.;\n }\n }\n }\n return( rval);\n}\n\n\n\/* Does a checksum modulo 10 on the given line. Digits = their\nvalue, '-' = 1, all other chars = 0. Returns 0 if ok, a negative\nvalue if it's definitely not a TLE line, positive if it's all OK\nexcept the checksum. This last was added because people sometimes\nwant to use TLEs without worrying about the checksum. *\/\n\nint DLL_FUNC tle_checksum( const char *buff)\n{\n int rval = 0;\n int count = 69;\n\n if( (*buff != '1' && *buff != '2') || buff[1] != ' ')\n return( -1);\n while( --count)\n {\n if( *buff > '0' && *buff <= '9')\n rval += *buff - '0';\n else if( *buff == '-')\n rval++;\n if( *buff < ' ' || *buff > 'z') \/* invalid character *\/\n return( -2);\n buff++;\n }\n rval -= *buff++ - '0';\n if( *buff > ' ') \/* line unterminated *\/\n rval = -3;\n else\n {\n rval %= 10;\n if( rval < 0)\n rval += 10;\n }\n return( rval % 10);\n}\n\nstatic inline int mutant_dehex( const char ichar)\n{\n int rval;\n\n if( ichar <= '9' && ichar >= '0')\n rval = ichar - '0';\n else if( ichar >= 'A' && ichar <= 'Z')\n rval = ichar + 10 - 'A';\n else\n rval = -1;\n return( rval);\n}\n\n\/* The \"standard\" SDP4 model fails badly for very high-flying satellites.\nAs a non-standard extension, I'm simply storing state vectors for them,\nusing the following somewhat odd scheme :\n\n1 40391U 15007B 15091.99922241 sxxxxxxxx syyyyyyyy szzzzzzzzH 9997\n2 49391 [valid range, accuracy] saaaaaaaa sbbbbbbbb scccccccc 0 8\n\n Epoch, int'l & NORAD IDs are stored in the standard manner. The\n'ephemeris type' is H (rather than the otherwise universal 0). The\nxyz position and vx, vy, vz velocity are stored as 8-digit signed\nbase-36 integers, hence a range of +\/- 36^8 = about +\/- 2.82x10^12.\n\n x, y, z are in meters, and hence cover a range +\/- 18.9 AU.\nvx, vy, vz are in 10^-4 m\/s, range +\/- 94% c. *\/\n\nstatic double get_high_value( const char *iptr)\n{\n int64_t rval = 0;\n\n assert( *iptr == '+' || *iptr == '-');\n if( *iptr == '+' || *iptr == '-')\n {\n int i, digit;\n\n for( i = 1; i < 9; i++)\n {\n digit = mutant_dehex( iptr[i]);\n assert( digit >= 0);\n rval = rval * (int64_t)36 + (int64_t)digit;\n }\n if( *iptr == '-')\n rval = -rval;\n }\n return( (double)rval);\n}\n\n\/* Traditionally, NORAD numbers were stored as five digits. In 2020, new\ndetectors threatened to go past 100K objects; the 'Alpha-5' scheme allows\nthe first byte to be replaced by an uppercase letter, with I and O\nskipped. That gets us to 339999. Note that NORAD is encouraging us to\nswitch to other formats (XML, JSON, etc.) that allow nine-digit numbers.\n\n Should 340K numbers prove insufficient, the following scheme would\nuse all 34^5 = 45435424 possible combinations. d = digit, L = letter,\nx = either. We also could use lowercase letters and some others to\nget 10^9 combinations within five bytes with backward compatibility.\n\n(1) ddddd = 'traditional' scheme provides 100000 combinations;\n(2) Ldddd = Alpha5 scheme adds 240000;\n(3) xxxxL = 34^4*24 = 32072064 more;\n(4) xxxLd = 34^3*24*10 = 9432960 more;\n(5) xxLdd = 34^2*24*100 = 2774400 more;\n(6) xLddd = 34*24*1000 = 816000 more. *\/\n\nstatic int base34_to_int( const char c)\n{\n int offset;\n\n if( c == ' ')\n return( 0);\n if( c >= '0' && c <= '9')\n offset = '0';\n else if( c >= 'A' && c <= 'H')\n offset = 'A' - 10;\n else if( c >= 'J' && c <= 'N')\n offset = 'J' - 18;\n else if( c >= 'P' && c <= 'Z')\n offset = 'P' - 23;\n else\n return( -1);\n return( c - offset);\n}\n\nstatic int get_norad_number( const char *buff)\n{\n const int ten_thousands = base34_to_int( *buff);\n\n if( ten_thousands >= 0)\n return( ten_thousands * 10000 + atoi( buff + 1));\n else\n return( 0);\n}\n\nstatic inline double get_eight_places( const char *ptr)\n{\n return( (double)atoi( ptr) + (double)atoi(ptr + 4) * 1e-8);\n}\n\n\/* Meteor 2-08 *\/\n\/* 1 13113U 88245.60005115 0.00000076 63463-4 0 5998 *\/\n\/* 2 13113 82.5386 288.0994 0015973 147.1294 213.0868 13.83869004325321 *\/\n\n#define J2000 2451545.5\n#define J1900 (J2000 - 36525. - 1.)\n\n\/* parse_elements returns:\n 0 if the elements are parsed without error;\n 1 if they're OK except the first line has a checksum error;\n 2 if they're OK except the second line has a checksum error;\n 3 if they're OK except both lines have checksum errors;\n a negative value if the lines aren't at all parseable *\/\n\nint DLL_FUNC parse_elements( const char *line1, const char *line2, tle_t *sat)\n{\n int rval, checksum_problem = 0;\n\n if( *line1 != '1' || *line2 != '2')\n rval = -4;\n else\n {\n rval = tle_checksum( line1);\n if( rval > 0)\n {\n checksum_problem = 1; \/* there's a checksum problem, but it's *\/\n rval = 0; \/* not fatal; continue processing the TLE *\/\n }\n }\n\n if( rval)\n rval -= 100;\n else\n {\n rval = tle_checksum( line2);\n if( rval > 0)\n {\n checksum_problem |= 2; \/* there's a checksum problem, but it's *\/\n rval = 0; \/* not fatal; continue processing the TLE *\/\n }\n }\n\n if( !rval)\n {\n char tbuff[13];\n int year = line1[19] - '0';\n\n if( line1[18] >= '0')\n year += (line1[18] - '0') * 10;\n if( year < 57) \/* cycle around Y2K *\/\n year += 100;\n sat->epoch = get_eight_places( line1 + 20) + J1900\n + (double)( year * 365 + (year - 1) \/ 4);\n sat->norad_number = get_norad_number( line1 + 2);\n memcpy( tbuff, line1 + 64, 4);\n tbuff[4] = '\\0';\n sat->bulletin_number = atoi( tbuff);\n sat->classification = line1[7]; \/* almost always 'U' *\/\n memcpy( sat->intl_desig, line1 + 9, 8);\n sat->intl_desig[8] = '\\0';\n memcpy( tbuff, line2 + 63, 5);\n tbuff[5] = '\\0';\n sat->revolution_number = atoi( tbuff);\n sat->ephemeris_type = line1[62];\n if( sat->ephemeris_type == 'H')\n {\n size_t i;\n double *state_vect = &sat->xincl;\n\n for( i = 0; i < 3; i++)\n {\n state_vect[i] = get_high_value( line1 + 33 + i * 10);\n state_vect[i + 3] = get_high_value( line2 + 33 + i * 10) * 1e-4;\n }\n return( 0);\n }\n\n sat->xmo = (double)get_angle( line2 + 43) * (PI \/ 180e+4);\n sat->xnodeo = (double)get_angle( line2 + 17) * (PI \/ 180e+4);\n sat->omegao = (double)get_angle( line2 + 34) * (PI \/ 180e+4);\n sat->xincl = (double)get_angle( line2 + 8) * (PI \/ 180e+4);\n sat->eo = atoi( line2 + 26) * 1.e-7;\n\n \/* Make sure mean motion is null-terminated, since rev. no.\n may immediately follow. *\/\n memcpy( tbuff, line2 + 51, 12);\n tbuff[12] = '\\0';\n \/* Input mean motion, derivative of mean motion and second *\/\n \/* deriv of mean motion, are all in revolutions and days. *\/\n \/* Convert them here to radians and minutes: *\/\n sat->xno = get_eight_places( tbuff) * TWOPI \/ MINUTES_PER_DAY;\n sat->xndt2o = (double)atoi( line1 + 35)\n * 1.e-8 * TWOPI \/ MINUTES_PER_DAY_SQUARED;\n if( line1[33] == '-')\n sat->xndt2o *= -1.;\n sat->xndd6o = sci( line1 + 44) * TWOPI \/ MINUTES_PER_DAY_CUBED;\n\n sat->bstar = sci( line1 + 53) * AE;\n }\n return( rval ? rval : checksum_problem);\n}\n<|endoftext|>"} {"text":"<commit_before>#include <string>\n#include <iostream>\n#include <stdio.h>\n#include \"language.h\"\n#include \"runner.h\"\nusing namespace std;\n\nRunner::Runner(string source_file, string testcase_file){\n _source_file = source_file;\n _testcase_file = testcase_file;\n}\nstring Runner::source_file() const{\n return _source_file;\n}\nstring Runner::testcase_file() const{\n return _testcase_file;\n}\nLanguage Runner::language() const{\n return Unknown;\n}\nint Runner::compile() const{\n return 0;\n}\nint Runner::execute() const{\n FILE* fp;\n char buf[1024];\n if((fp = popen(execute_command().c_str(), \"r\")) != NULL){\n fputs(\"test0\\n\", fp);\n fputs(\"test1\\n\", fp);\n cout << language() << \": executing...\\n\";\n while(fgets(buf, sizeof(buf), fp) != NULL){\n cout << buf << endl;\n }\n cout << language() << \": executing...\\n\";\n return pclose(fp);\n }\n return -1;\n}\nint Runner::cleanup() const{\n return 0;\n}\nvoid Runner::run() const{\n cout << \"compiling...\" << endl;\n compile();\n cout << \"executing...\" << endl;\n execute();\n}\n<commit_msg>Feature child process<commit_after>#include <string>\n#include <iostream>\n#include <cstdlib>\n#include <stdio.h>\n#include <unistd.h>\n#include \"language.h\"\n#include \"runner.h\"\nusing namespace std;\n\n\nRunner::Runner(string source_file, string testcase_file){\n _source_file = source_file;\n _testcase_file = testcase_file;\n}\nstring Runner::source_file() const{\n return _source_file;\n}\nstring Runner::testcase_file() const{\n return _testcase_file;\n}\nLanguage Runner::language() const{\n return Unknown;\n}\nint Runner::compile() const{\n return 0;\n}\nint Runner::execute() const{\n int pipe_to_child[2];\n int pipe_from_child[2];\n if(pipe(pipe_to_child) < 0){\n perror(\"popen\");\n exit(EXIT_FAILURE);\n }\n if(pipe(pipe_from_child) < 0){\n perror(\"popen\");\n close(pipe_to_child[0]);\n close(pipe_to_child[1]);\n exit(EXIT_FAILURE);\n }\n int pid = fork();\n if(pid < 0){\n perror(\"fork\");\n close(pipe_to_child[0]);\n close(pipe_to_child[1]);\n close(pipe_from_child[0]);\n close(pipe_from_child[1]);\n exit(EXIT_FAILURE);\n }\n if(pid == 0){\n close(pipe_to_child[1]);\n close(pipe_from_child[0]);\n dup2(pipe_to_child[0], fileno(stdin));\n dup2(pipe_from_child[1], fileno(stdout));\n close(pipe_to_child[0]);\n close(pipe_from_child[1]);\n if(execlp(\"sh\", \"sh\", \"-c\", execute_command().c_str(), NULL) < 0){\n perror(\"execute\");\n exit(EXIT_FAILURE);\n }\n }\n write(pipe_to_child[1], \"send message\\n\", 13);\n write(pipe_to_child[1], \"send mesg\\n\", 10);\n close(pipe_to_child[1]);\n char buff[255];\n read(pipe_from_child[0], buff, 255);\n printf(\"parent process:\\n\\n%s\", buff);\n return 0;\n}\nint Runner::cleanup() const{\n return 0;\n}\nvoid Runner::run() const{\n cout << \"compiling...\" << endl;\n if(compile() != 0){\n cerr << \"Failed compile.\" << endl;\n exit(EXIT_FAILURE);\n }\n cout << \"executing...\" << endl;\n execute();\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/include <tclap\/CmdLine.h>\n#include <algorithm>\n#include <boost\/program_options\/options_description.hpp>\n#include <boost\/program_options\/parsers.hpp>\n#include <boost\/program_options\/variables_map.hpp>\n#include <fstream>\n#include <iostream>\n#include <sstream>\n#include <stdexcept>\n#include <vector>\n#include \"bin_file.hpp\"\n#include \"prenexusrenderer.hpp\"\n#include \"renderer.hpp\"\n#include \"version.hpp\"\n\nusing std::cerr;\nusing std::cout;\nusing std::endl;\nusing std::invalid_argument;\nusing std::string;\nusing std::stringstream;\nusing std::vector;\nnamespace po = boost::program_options;\n\ntypedef uint32_t event_t;\n\nstruct Config{\n bool byte_swap;\n bool show_data;\n bool show_line_num;\n bool multi_file;\n bool sum_data;\n bool sum_block;\n bool is_event;\n bool get_pix_range;\n vector<size_t> integrate;\n};\n\nstatic const size_t BLOCK_SIZE=1024;\nstatic const event_t ERROR=0x80000000;\nstatic const string DEFAULT_TYPE=\"char\";\n\nstatic string::size_type count_occur(const string &str, const string &ch){\n string::size_type count = 0;\n string::size_type index = 0;\n\n \/\/ infinite loop to make sure that the entire string is parsed.\n while(true)\n {\n index = str.find(ch,index+1);\n if(index==string::npos)\n {\n break;\n }\n count++;\n }\n return count;\n}\n\nstatic bool my_isnotdigit(char c){\n return !isdigit(c);\n}\n\nstatic int str_to_int(const string &str){\n if(str.substr(0,1)==\"-\")\n return -1*str_to_int(str.substr(1,str.size()));\n\n string::const_iterator it = str.begin();\n it = std::find_if(it,str.end(),my_isnotdigit);\n\n if(it!=str.end())\n throw invalid_argument(\"str_to_int(string) argument is not an integer\");\n\n return atol(str.c_str());\n}\n\nextern vector<string> split(const string &source,const string &split)\n{\n string::size_type number=count_occur(source,split);\n if(number==0)\n {\n vector<string> result;\n result.push_back(source);\n return result;\n }\n\n vector<string> result;\n string::size_type start=0;\n string::size_type stop=0;\n string inner;\n while(true)\n {\n stop=source.find(split,start);\n if(stop==string::npos)\n {\n result.push_back(source.substr(start));\n break;\n }\n else\n {\n result.push_back(source.substr(start,stop-start));\n start=stop+split.size();\n }\n }\n return result;\n}\n\nstatic vector<int> str_to_intArray(const string & array){\n vector<string> str_array = split(array, \",\");\n vector<int> result(0);\n size_t length = str_array.size();\n for (size_t i = 0; i < length; ++i) {\n result.push_back(str_to_int(str_array[i]));\n }\n return result;\n}\n\ntemplate <typename NumT>\nstring thing_to_str(const NumT thing) {\n std::stringstream s;\n s << thing;\n return s.str();\n}\n\ntemplate <typename NumT>\nstring thing_to_str(const vector<NumT> &thing) {\n std::stringstream s;\n size_t length = thing.size();\n for ( size_t i = 0 ; i < length ; ++i ){\n s << thing[i] << \" \";\n }\n return s.str();\n}\n\nstring pixid_str(const size_t pixid, const vector<size_t> &bounds) {\n size_t rank = bounds.size();\n if (rank<=0) {\n return \"\";\n }\n size_t max_index=1;\n for (size_t i = 0 ; i<rank ; ++i ){\n max_index*=bounds[i];\n }\n if(pixid>max_index) {\n std::stringstream s;\n s << \"Pixel id outside of known bounds: \" << pixid << \">\" << max_index;\n throw std::runtime_error(s.str());\n }\n size_t my_id = pixid;\n vector<size_t> indices(bounds.size());\n for (size_t i = 0 ; i < rank-1 ; ++i ) {\n indices[i] = my_id \/ bounds[i+1];\n my_id = my_id - indices[i] * bounds[i+1];\n }\n indices[rank-1] = my_id;\n\n return thing_to_str(indices);\n}\n\n\/**\n * The main entry point for the program.\n *\/\nint main(int argc, char** argv)\n{\n \/\/ ---------- Declare the supported options.\n po::options_description generic_options(\"Generic options\");\n generic_options.add_options()\n (\"help,h\", \"Produce this help message.\")\n (\"version,v\", \"Print version string.\")\n ;\n\n stringstream typesHelp;\n typesHelp << \"Set the type of the data. Allowed values are: \" << render::getKnownDataDescr() << \", \" << prenexus::getKnownDataDescr();\n po::options_description config_options(\"Configuration\");\n config_options.add_options()\n (\"type,t\", po::value<string>()->default_value(DEFAULT_TYPE), typesHelp.str().c_str())\n (\"offset\", po::value<size_t>()->default_value(0), \"Skip to this position (in bytes) in the file.\")\n (\"length\", po::value<size_t>()->default_value(0), \"Number of items to read (NOT in bytes). Zero means read to end of file.\")\n (\"records\", po::value<size_t>()->default_value(1), \"Number of items to print per line\")\n (\"byteswap\", \"Perform byte swapping on the data\")\n (\"quiet,q\", \"Do not print out values\")\n (\"lines\", \"show line numbers\")\n ;\n\n po::options_description hidden_options;\n hidden_options.add_options()\n (\"filename\", po::value< vector<string> >(), \"input files\")\n ;\n\n \/\/ all options available on the command line\n po::options_description cmdline_options;\n cmdline_options.add(generic_options).add(config_options).add(hidden_options);\n\n \/\/ all options visible to the user\n po::options_description visible_options(\"Allowed options\");\n visible_options.add(generic_options).add(config_options);\n\n \/\/ ---------- parse the command line\n po::positional_options_description p;\n p.add(\"filename\", -1);\n po::variables_map vm;\n po::store(po::command_line_parser(argc, argv).options(cmdline_options)\n\t .positional(p).run(), vm);\n po::notify(vm);\n\n \/\/ ---------- get everything out of the options\n \/\/ work with generic options\n if (vm.count(\"help\")) {\n cout << \"Usage: \" << argv[0] << \" [options] <filenames>\" << endl;\n cout << endl;\n cout << visible_options << endl;\n return 1;\n }\n if (vm.count(\"version\")) {\n cout << \"morebin version \" << VERSION << \" built \" << DATE << endl;\n cout << endl;\n cout << \"http:\/\/github.com\/peterfpeterson\/morebin\/\";\n if (VERSION.find(\"SNAPSHOT\") == string::npos)\n cout << \"tree\/v\" << VERSION;\n cout << endl;\n return 0;\n }\n\n \/\/ config options\n size_t offset = 0;\n if (vm.count(\"offset\"))\n offset = vm[\"offset\"].as<size_t>();\n size_t length = 0;\n if (vm.count(\"length\"))\n length = vm[\"length\"].as<size_t>();\n size_t numItemsPerLine = 1;\n if (vm.count(\"records\"))\n numItemsPerLine = vm[\"records\"].as<size_t>();\n bool byteswap = (vm.count(\"byteswap\") > 0);\n bool quiet = (vm.count(\"quiet\") > 0);\n string dataType = DEFAULT_TYPE;\n if (vm.count(\"type\"))\n dataType = vm[\"type\"].as<string>();\n bool showLines = (vm.count(\"lines\") > 0);\n\n \/\/ hidden options\n vector<string> files;\n if (vm.count(\"filename\"))\n {\n files = vm[\"filename\"].as< vector<string> >();\n }\n else\n {\n cerr << \"ERROR: failed to supply <filename>\" << endl;\n \/\/cmd.getOutput()->usage(cmd);\n return -1;\n }\n\n \/\/ ---------- push through the list of files\n try {\n bool multiFile = (files.size() > 1);\n render::Renderer * renderer = NULL;\n try {\n renderer = new render::Renderer();\n renderer->setDataDescr(dataType);\n } catch (std::runtime_error &e) {\n \/\/ TODO should print a warning\n renderer = new prenexus::PrenexusRenderer();\n renderer->setDataDescr(dataType);\n }\n renderer->quiet(quiet);\n renderer->showLines(showLines);\n renderer->numItemsPerLine(numItemsPerLine);\n\n for (std::size_t i = 0; i < files.size(); i++) {\n BinFile file(files[i]);\n file.setByteSwap(byteswap);\n if (multiFile) {\n\tcout << \"******************************\" << endl;\n\tcout << \"* \" << files[i] << \" size:\" << file.size_in_bytes() << endl;\n\tcout << \"******************************\" << endl;\n }\n renderer->showData(file, offset, length);\n }\n\n delete renderer;\n } catch(std::runtime_error &e) {\n cerr << \"RUNTIME ERROR:\" << e.what() << endl;\n return -1;\n }\n\n return 0;\n}\n<commit_msg>Adding better description of the types.<commit_after>\/\/include <tclap\/CmdLine.h>\n#include <algorithm>\n#include <boost\/program_options\/options_description.hpp>\n#include <boost\/program_options\/parsers.hpp>\n#include <boost\/program_options\/variables_map.hpp>\n#include <fstream>\n#include <iostream>\n#include <sstream>\n#include <stdexcept>\n#include <vector>\n#include \"bin_file.hpp\"\n#include \"prenexusrenderer.hpp\"\n#include \"renderer.hpp\"\n#include \"version.hpp\"\n\nusing std::cerr;\nusing std::cout;\nusing std::endl;\nusing std::invalid_argument;\nusing std::string;\nusing std::stringstream;\nusing std::vector;\nnamespace po = boost::program_options;\n\ntypedef uint32_t event_t;\n\nstruct Config{\n bool byte_swap;\n bool show_data;\n bool show_line_num;\n bool multi_file;\n bool sum_data;\n bool sum_block;\n bool is_event;\n bool get_pix_range;\n vector<size_t> integrate;\n};\n\nstatic const size_t BLOCK_SIZE=1024;\nstatic const event_t ERROR=0x80000000;\nstatic const string DEFAULT_TYPE=\"char\";\n\nstatic string::size_type count_occur(const string &str, const string &ch){\n string::size_type count = 0;\n string::size_type index = 0;\n\n \/\/ infinite loop to make sure that the entire string is parsed.\n while(true)\n {\n index = str.find(ch,index+1);\n if(index==string::npos)\n {\n break;\n }\n count++;\n }\n return count;\n}\n\nstatic bool my_isnotdigit(char c){\n return !isdigit(c);\n}\n\nstatic int str_to_int(const string &str){\n if(str.substr(0,1)==\"-\")\n return -1*str_to_int(str.substr(1,str.size()));\n\n string::const_iterator it = str.begin();\n it = std::find_if(it,str.end(),my_isnotdigit);\n\n if(it!=str.end())\n throw invalid_argument(\"str_to_int(string) argument is not an integer\");\n\n return atol(str.c_str());\n}\n\nextern vector<string> split(const string &source,const string &split)\n{\n string::size_type number=count_occur(source,split);\n if(number==0)\n {\n vector<string> result;\n result.push_back(source);\n return result;\n }\n\n vector<string> result;\n string::size_type start=0;\n string::size_type stop=0;\n string inner;\n while(true)\n {\n stop=source.find(split,start);\n if(stop==string::npos)\n {\n result.push_back(source.substr(start));\n break;\n }\n else\n {\n result.push_back(source.substr(start,stop-start));\n start=stop+split.size();\n }\n }\n return result;\n}\n\nstatic vector<int> str_to_intArray(const string & array){\n vector<string> str_array = split(array, \",\");\n vector<int> result(0);\n size_t length = str_array.size();\n for (size_t i = 0; i < length; ++i) {\n result.push_back(str_to_int(str_array[i]));\n }\n return result;\n}\n\ntemplate <typename NumT>\nstring thing_to_str(const NumT thing) {\n std::stringstream s;\n s << thing;\n return s.str();\n}\n\ntemplate <typename NumT>\nstring thing_to_str(const vector<NumT> &thing) {\n std::stringstream s;\n size_t length = thing.size();\n for ( size_t i = 0 ; i < length ; ++i ){\n s << thing[i] << \" \";\n }\n return s.str();\n}\n\nstring pixid_str(const size_t pixid, const vector<size_t> &bounds) {\n size_t rank = bounds.size();\n if (rank<=0) {\n return \"\";\n }\n size_t max_index=1;\n for (size_t i = 0 ; i<rank ; ++i ){\n max_index*=bounds[i];\n }\n if(pixid>max_index) {\n std::stringstream s;\n s << \"Pixel id outside of known bounds: \" << pixid << \">\" << max_index;\n throw std::runtime_error(s.str());\n }\n size_t my_id = pixid;\n vector<size_t> indices(bounds.size());\n for (size_t i = 0 ; i < rank-1 ; ++i ) {\n indices[i] = my_id \/ bounds[i+1];\n my_id = my_id - indices[i] * bounds[i+1];\n }\n indices[rank-1] = my_id;\n\n return thing_to_str(indices);\n}\n\n\/**\n * The main entry point for the program.\n *\/\nint main(int argc, char** argv)\n{\n \/\/ ---------- Declare the supported options.\n po::options_description generic_options(\"Generic options\");\n generic_options.add_options()\n (\"help,h\", \"Produce this help message.\")\n (\"version,v\", \"Print version string.\")\n ;\n\n stringstream typesHelp;\n typesHelp << \"Set the type of the data. Allowed values are: \" << render::getKnownDataDescr() << \", \" << prenexus::getKnownDataDescr();\n po::options_description config_options(\"Configuration\");\n config_options.add_options()\n (\"type,t\", po::value<string>()->default_value(DEFAULT_TYPE), typesHelp.str().c_str())\n (\"offset\", po::value<size_t>()->default_value(0), \"Skip to this position (in bytes) in the file.\")\n (\"length\", po::value<size_t>()->default_value(0), \"Number of items to read (NOT in bytes). Zero means read to end of file.\")\n (\"records\", po::value<size_t>()->default_value(1), \"Number of items to print per line\")\n (\"byteswap\", \"Perform byte swapping on the data\")\n (\"quiet,q\", \"Do not print out values\")\n (\"lines\", \"show line numbers\")\n ;\n\n po::options_description hidden_options;\n hidden_options.add_options()\n (\"filename\", po::value< vector<string> >(), \"input files\")\n ;\n\n \/\/ all options available on the command line\n po::options_description cmdline_options;\n cmdline_options.add(generic_options).add(config_options).add(hidden_options);\n\n \/\/ all options visible to the user\n po::options_description visible_options(\"Allowed options\");\n visible_options.add(generic_options).add(config_options);\n\n \/\/ ---------- parse the command line\n po::positional_options_description p;\n p.add(\"filename\", -1);\n po::variables_map vm;\n po::store(po::command_line_parser(argc, argv).options(cmdline_options)\n\t .positional(p).run(), vm);\n po::notify(vm);\n\n \/\/ ---------- get everything out of the options\n \/\/ work with generic options\n if (vm.count(\"help\")) {\n cout << \"Usage: \" << argv[0] << \" [options] <filenames>\" << endl;\n cout << endl;\n\n cout << \"Source code located at http:\/\/github.com\/peterfpeterson\/morebin\" << endl;\n cout << endl;\n\n cout << visible_options << endl;\n cout << endl;\n\n cout << \"Notes on complex types:\" << endl;\n cout << \" The following types are printed in colums (in order)\" << endl;\n cout << endl;\n cout << \" event\" << endl;\n cout << \"\\ttof(uint32_t) Time of flight.\" << endl;\n cout << \"\\tpid(uint32_t) Pixel identifier as published by the DAS\/DAE\/DAQ.\" << endl;\n cout << \" oldpulseid\" << endl;\n cout << \"\\ttime(uint32_t,uint32_t) Time of the pulse\" << endl;\n cout << \"\\tevent_index(uint64_t) The index of the first event for this pulse.\" << endl;\n cout << \" pulseid\" << endl;\n cout << \"\\ttime(uint32_t,uint32_t) Time of the pulse\" << endl;\n cout << \"\\tevent_index(uint64_t) The index of the first event for this pulse.\" << endl;\n cout << \"\\tpCurrent(double) The proton charge for the pulse.\" << endl;\n cout << \" rtdl\" << endl;\n cout << \"\\ttime(uint32_t,uint32_t) Time of the pulse\" << endl;\n cout << \"\\tpulseType(uint32_t)\" << endl;\n cout << \"\\tvetoStatus(uint32_t)\" << endl;\n cout << \"\\tpCurrent(uint32_t) The proton charge for the pulse.\" << endl;\n cout << \"\\tspare(uint32_t)\" << endl;\n return 1;\n }\n if (vm.count(\"version\")) {\n cout << \"morebin version \" << VERSION << \" built \" << DATE << endl;\n cout << endl;\n cout << \"http:\/\/github.com\/peterfpeterson\/morebin\/\";\n if (VERSION.find(\"SNAPSHOT\") == string::npos)\n cout << \"tree\/v\" << VERSION;\n cout << endl;\n return 0;\n }\n\n \/\/ config options\n size_t offset = 0;\n if (vm.count(\"offset\"))\n offset = vm[\"offset\"].as<size_t>();\n size_t length = 0;\n if (vm.count(\"length\"))\n length = vm[\"length\"].as<size_t>();\n size_t numItemsPerLine = 1;\n if (vm.count(\"records\"))\n numItemsPerLine = vm[\"records\"].as<size_t>();\n bool byteswap = (vm.count(\"byteswap\") > 0);\n bool quiet = (vm.count(\"quiet\") > 0);\n string dataType = DEFAULT_TYPE;\n if (vm.count(\"type\"))\n dataType = vm[\"type\"].as<string>();\n bool showLines = (vm.count(\"lines\") > 0);\n\n \/\/ hidden options\n vector<string> files;\n if (vm.count(\"filename\"))\n {\n files = vm[\"filename\"].as< vector<string> >();\n }\n else\n {\n cerr << \"ERROR: failed to supply <filename>\" << endl;\n \/\/cmd.getOutput()->usage(cmd);\n return -1;\n }\n\n \/\/ ---------- push through the list of files\n try {\n bool multiFile = (files.size() > 1);\n render::Renderer * renderer = NULL;\n try {\n renderer = new render::Renderer();\n renderer->setDataDescr(dataType);\n } catch (std::runtime_error &e) {\n \/\/ TODO should print a warning\n renderer = new prenexus::PrenexusRenderer();\n renderer->setDataDescr(dataType);\n }\n renderer->quiet(quiet);\n renderer->showLines(showLines);\n renderer->numItemsPerLine(numItemsPerLine);\n\n for (std::size_t i = 0; i < files.size(); i++) {\n BinFile file(files[i]);\n file.setByteSwap(byteswap);\n if (multiFile) {\n\tcout << \"******************************\" << endl;\n\tcout << \"* \" << files[i] << \" size:\" << file.size_in_bytes() << endl;\n\tcout << \"******************************\" << endl;\n }\n renderer->showData(file, offset, length);\n }\n\n delete renderer;\n } catch(std::runtime_error &e) {\n cerr << \"RUNTIME ERROR:\" << e.what() << endl;\n return -1;\n }\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/* Copyright 2017 Istio Authors. All Rights Reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n#include \"src\/grpc_transport.h\"\n#include <mutex>\n#include <thread>\n\nnamespace istio {\nnamespace mixer_client {\nnamespace {\n\n\/\/ A gRPC stream\ntemplate <class RequestType, class ResponseType>\nclass GrpcStream final : public WriteInterface<RequestType> {\n public:\n typedef std::unique_ptr<\n ::grpc::ClientReaderWriterInterface<RequestType, ResponseType>>\n StreamPtr;\n typedef std::function<StreamPtr(::grpc::ClientContext&)> StreamNewFunc;\n\n GrpcStream(ReadInterface<ResponseType>* reader, StreamNewFunc create_func)\n : reader_(reader), write_closed_(false) {\n stream_ = create_func(context_);\n }\n\n static void Start(\n std::shared_ptr<GrpcStream<RequestType, ResponseType>> grpc_stream) {\n std::thread t([grpc_stream]() { grpc_stream->ReadMainLoop(); });\n t.detach();\n }\n\n void Write(const RequestType& request) override {\n std::lock_guard<std::mutex> lock(write_mutex_);\n if (!stream_->Write(request)) {\n stream_->WritesDone();\n write_closed_ = true;\n }\n }\n\n void WritesDone() override {\n std::lock_guard<std::mutex> lock(write_mutex_);\n stream_->WritesDone();\n write_closed_ = true;\n }\n\n bool is_write_closed() const override { return write_closed_; }\n\n private:\n \/\/ The worker loop to read response messages.\n void ReadMainLoop() {\n ResponseType response;\n while (stream_->Read(&response)) {\n reader_->OnRead(response);\n }\n ::grpc::Status status = stream_->Finish();\n \/\/ Convert grpc status to protobuf status.\n ::google::protobuf::util::Status pb_status(\n ::google::protobuf::util::error::Code(status.error_code()),\n ::google::protobuf::StringPiece(status.error_message()));\n reader_->OnClose(pb_status);\n }\n\n \/\/ The client context.\n ::grpc::ClientContext context_;\n \/\/ Mutex to make sure not calling stream_->Write() parallelly.\n std::mutex write_mutex_;\n \/\/ The reader writer stream.\n StreamPtr stream_;\n \/\/ The reader interface from caller.\n ReadInterface<ResponseType>* reader_;\n \/\/ Indicates if write is closed.\n bool write_closed_;\n};\n\ntypedef GrpcStream<::istio::mixer::v1::CheckRequest,\n ::istio::mixer::v1::CheckResponse>\n CheckGrpcStream;\ntypedef GrpcStream<::istio::mixer::v1::ReportRequest,\n ::istio::mixer::v1::ReportResponse>\n ReportGrpcStream;\ntypedef GrpcStream<::istio::mixer::v1::QuotaRequest,\n ::istio::mixer::v1::QuotaResponse>\n QuotaGrpcStream;\n\n} \/\/ namespace\n\nGrpcTransport::GrpcTransport(const std::string& mixer_server) {\n channel_ = CreateChannel(mixer_server, ::grpc::InsecureChannelCredentials());\n stub_ = ::istio::mixer::v1::Mixer::NewStub(channel_);\n}\n\nCheckWriterPtr GrpcTransport::NewStream(CheckReaderRawPtr reader) {\n auto writer = std::make_shared<CheckGrpcStream>(\n reader,\n [this](::grpc::ClientContext& context) -> CheckGrpcStream::StreamPtr {\n return stub_->Check(&context);\n });\n CheckGrpcStream::Start(writer);\n return writer;\n}\n\nReportWriterPtr GrpcTransport::NewStream(ReportReaderRawPtr reader) {\n auto writer = std::make_shared<ReportGrpcStream>(\n reader,\n [this](::grpc::ClientContext& context) -> ReportGrpcStream::StreamPtr {\n return stub_->Report(&context);\n });\n ReportGrpcStream::Start(writer);\n return writer;\n}\n\nQuotaWriterPtr GrpcTransport::NewStream(QuotaReaderRawPtr reader) {\n auto writer = std::make_shared<QuotaGrpcStream>(\n reader,\n [this](::grpc::ClientContext& context) -> QuotaGrpcStream::StreamPtr {\n return stub_->Quota(&context);\n });\n QuotaGrpcStream::Start(writer);\n return writer;\n}\n\n} \/\/ namespace mixer_client\n} \/\/ namespace istio\n<commit_msg>Add fast_fail for gRPC (#36)<commit_after>\/* Copyright 2017 Istio Authors. All Rights Reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n#include \"src\/grpc_transport.h\"\n#include <mutex>\n#include <thread>\n\nnamespace istio {\nnamespace mixer_client {\nnamespace {\n\n\/\/ A gRPC stream\ntemplate <class RequestType, class ResponseType>\nclass GrpcStream final : public WriteInterface<RequestType> {\n public:\n typedef std::unique_ptr<\n ::grpc::ClientReaderWriterInterface<RequestType, ResponseType>>\n StreamPtr;\n typedef std::function<StreamPtr(::grpc::ClientContext&)> StreamNewFunc;\n\n GrpcStream(ReadInterface<ResponseType>* reader, StreamNewFunc create_func)\n : reader_(reader), write_closed_(false) {\n context_.set_fail_fast(true);\n stream_ = create_func(context_);\n }\n\n static void Start(\n std::shared_ptr<GrpcStream<RequestType, ResponseType>> grpc_stream) {\n std::thread t([grpc_stream]() { grpc_stream->ReadMainLoop(); });\n t.detach();\n }\n\n void Write(const RequestType& request) override {\n std::lock_guard<std::mutex> lock(write_mutex_);\n if (!stream_->Write(request)) {\n stream_->Finish();\n }\n }\n\n void WritesDone() override {\n std::lock_guard<std::mutex> lock(write_mutex_);\n stream_->WritesDone();\n write_closed_ = true;\n }\n\n bool is_write_closed() const override { return write_closed_; }\n\n private:\n \/\/ The worker loop to read response messages.\n void ReadMainLoop() {\n ResponseType response;\n while (stream_->Read(&response)) {\n reader_->OnRead(response);\n }\n ::grpc::Status status = stream_->Finish();\n \/\/ Convert grpc status to protobuf status.\n ::google::protobuf::util::Status pb_status(\n ::google::protobuf::util::error::Code(status.error_code()),\n ::google::protobuf::StringPiece(status.error_message()));\n reader_->OnClose(pb_status);\n }\n\n \/\/ The client context.\n ::grpc::ClientContext context_;\n \/\/ Mutex to make sure not calling stream_->Write() parallelly.\n std::mutex write_mutex_;\n \/\/ The reader writer stream.\n StreamPtr stream_;\n \/\/ The reader interface from caller.\n ReadInterface<ResponseType>* reader_;\n \/\/ Indicates if write is closed.\n bool write_closed_;\n};\n\ntypedef GrpcStream<::istio::mixer::v1::CheckRequest,\n ::istio::mixer::v1::CheckResponse>\n CheckGrpcStream;\ntypedef GrpcStream<::istio::mixer::v1::ReportRequest,\n ::istio::mixer::v1::ReportResponse>\n ReportGrpcStream;\ntypedef GrpcStream<::istio::mixer::v1::QuotaRequest,\n ::istio::mixer::v1::QuotaResponse>\n QuotaGrpcStream;\n\n} \/\/ namespace\n\nGrpcTransport::GrpcTransport(const std::string& mixer_server) {\n channel_ = CreateChannel(mixer_server, ::grpc::InsecureChannelCredentials());\n stub_ = ::istio::mixer::v1::Mixer::NewStub(channel_);\n}\n\nCheckWriterPtr GrpcTransport::NewStream(CheckReaderRawPtr reader) {\n auto writer = std::make_shared<CheckGrpcStream>(\n reader,\n [this](::grpc::ClientContext& context) -> CheckGrpcStream::StreamPtr {\n return stub_->Check(&context);\n });\n CheckGrpcStream::Start(writer);\n return writer;\n}\n\nReportWriterPtr GrpcTransport::NewStream(ReportReaderRawPtr reader) {\n auto writer = std::make_shared<ReportGrpcStream>(\n reader,\n [this](::grpc::ClientContext& context) -> ReportGrpcStream::StreamPtr {\n return stub_->Report(&context);\n });\n ReportGrpcStream::Start(writer);\n return writer;\n}\n\nQuotaWriterPtr GrpcTransport::NewStream(QuotaReaderRawPtr reader) {\n auto writer = std::make_shared<QuotaGrpcStream>(\n reader,\n [this](::grpc::ClientContext& context) -> QuotaGrpcStream::StreamPtr {\n return stub_->Quota(&context);\n });\n QuotaGrpcStream::Start(writer);\n return writer;\n}\n\n} \/\/ namespace mixer_client\n} \/\/ namespace istio\n<|endoftext|>"} {"text":"<commit_before>\t\/\/ This file is a part of the OpenSurgSim project.\n\/\/ Copyright 2013, SimQuest Solutions Inc.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include <math.h>\n#include <iostream>\n#include <fstream>\n#include \"SurgSim\/Physics\/RenderTests\/RenderTest.h\"\n\n#include \"SurgSim\/Framework\/ApplicationData.h\"\n#include \"SurgSim\/Graphics\/PointCloudRepresentation.h\"\n#include \"SurgSim\/Graphics\/OsgPointCloudRepresentation.h\"\n#include \"SurgSim\/Math\/Quaternion.h\"\n#include \"SurgSim\/Math\/Vector.h\"\n#include \"SurgSim\/Math\/RigidTransform.h\"\n\n#include \"SurgSim\/Physics\/PhysicsManager.h\"\n#include \"SurgSim\/Physics\/Fem3DRepresentation.h\"\n#include \"SurgSim\/Physics\/FemElement3DCube.h\"\n#include \"SurgSim\/Physics\/PhysicsManager.h\"\n#include \"SurgSim\/Graphics\/OsgViewElement.h\"\n#include \"SurgSim\/Framework\/SceneElement.h\"\n#include \"SurgSim\/Graphics\/OsgCamera.h\"\n#include \"SurgSim\/Graphics\/OsgManager.h\"\n#include \"SurgSim\/Graphics\/OsgView.h\"\n#include \"SurgSim\/Math\/Quaternion.h\"\n\nusing SurgSim::Math::Vector3d;\nusing SurgSim::Math::Quaterniond;\nusing SurgSim::Math::RigidTransform3d;\nusing SurgSim::Math::makeRigidTransform;\nusing SurgSim::Framework::SceneElement;\nusing SurgSim::Graphics::OsgPointCloudRepresentation;\nusing SurgSim::Physics::PhysicsManager;\nusing SurgSim::Framework::SceneElement;\n\n\nnamespace SurgSim\n{\nnamespace Physics\n{\n\n\/\/\/ Truth cube implementation by Fem3DRepresentation\nclass TruthCubeRepresentation : public Fem3DRepresentation\n{\npublic:\n\t\/\/\/ Constructor\n\t\/\/\/ \\param name\tThe name of the truth cube representation.\n\t\/\/\/ \\param size\tThe original length of the truth cube in mm.\n\t\/\/\/ \\param level\tThe subdivision level.\n\texplicit TruthCubeRepresentation(const std::string& name, double size, unsigned int level) :\n\t\tm_name(name),\n\t\tm_size(size),\n\t\tm_levelSubdivision(level),\n\t\tFem3DRepresentation(name)\n\t{\n\t\tconst int dofPerNode = 3;\n\n\t\tm_numNodesPerAxis = pow(2, m_levelSubdivision) + 1;\n\t\tm_displacement.resize(m_numNodesPerAxis * m_numNodesPerAxis * m_numNodesPerAxis * dofPerNode);\n\t\tm_boundary.resize(m_numNodesPerAxis * m_numNodesPerAxis * m_numNodesPerAxis * dofPerNode);\n\t\tm_cubeNodes = createCube(m_size);\n\t}\n\n\t\/\/\/ Destructor \n\t~TruthCubeRepresentation()\n\t{\n\t}\n\n\t\/\/\/ Gets the number of nodes per axis of truth cube\n\t\/\/\/ \\return The number of nodes per axis.\n\tunsigned int getNumNodesPerAxis()\n\t{\n\t\treturn m_numNodesPerAxis;\n\t}\n\n\t\/\/\/ Gets displacement values\n\t\/\/\/ \\return The vector of displacement\n\tstd::vector<double> getDisplacements()\n\t{\n\t\treturn m_displacement;\n\t}\n\n\t\/\/\/ Get number of displacement \n\t\/\/\/ \\return the size of displacement vector\n\tint getNumofDisplacements()\n\t{\n\t\treturn m_displacement.size();\n\t}\n\n\t\/\/\/ Creates the subdivision truth cube nodes\n\tvoid createTruthCubeMesh()\n\t{\n\t\tm_nodes.resize(m_numNodesPerAxis);\n\t\tfor (int i = 0; i < m_numNodesPerAxis; i++)\n\t\t{\n\t\t\tm_nodes[i].resize(m_numNodesPerAxis);\n\t\t\tVector3d extremitiesX0[4] = {m_cubeNodes[0], m_cubeNodes[2], m_cubeNodes[4], m_cubeNodes[6]};\n\t\t\tVector3d extremitiesX1[4] = {m_cubeNodes[1], m_cubeNodes[3], m_cubeNodes[5], m_cubeNodes[7]};\n\n\t\t\tVector3d extremitiesXi[4];\n\t\t\tfor (int index = 0; index < 4; index++)\n\t\t\t{\n\t\t\t\textremitiesXi[index] = extremitiesX0[index] * (1.0 - i \/ (m_numNodesPerAxis - 1.0)) +\n\t\t\t\t\textremitiesX1[index] * i \/ (m_numNodesPerAxis - 1.0);\n\t\t\t}\n\n\t\t\tfor (int j = 0; j < m_numNodesPerAxis; j++)\n\t\t\t{\n\t\t\t\tVector3d extremitiesY0[2] = {extremitiesXi[0], extremitiesXi[2]};\n\t\t\t\tVector3d extremitiesY1[2] = {extremitiesXi[1], extremitiesXi[3]};\n\n\t\t\t\tVector3d extremitiesYi[2];\n\t\t\t\tfor (int index = 0; index < 2; index++)\n\t\t\t\t{\n\t\t\t\t\textremitiesYi[index] = extremitiesY0[index] * (1.0 - j\/(m_numNodesPerAxis - 1.0)) +\n\t\t\t\t\t\textremitiesY1[index] * j \/ (m_numNodesPerAxis - 1.0);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tm_nodes[i][j].resize(m_numNodesPerAxis);\n\t\t\t\tfor (int k=0; k < m_numNodesPerAxis; k++)\n\t\t\t\t{\n\t\t\t\t\tm_nodes[i][j][k] = extremitiesYi[0] * (1.0 - k \/ (m_numNodesPerAxis - 1.0)) + extremitiesYi[1]\n\t\t\t\t\t\t\t\t\t\t* k \/ (m_numNodesPerAxis - 1.0);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/\/ Adds the Fem3D elements of small cubes\n\t\/\/\/ \\param state\tThe deformable state for initialization.\n\tvoid addFemCubes(std::shared_ptr<DeformableRepresentationState> state)\n\t{\n\t\tfor (int i = 0; i < m_numNodesPerAxis - 1; i++)\n\t\t{\n\t\t\tfor (int j = 0; j < m_numNodesPerAxis - 1; j++)\n\t\t\t{\n\t\t\t\tfor (int k = 0; k < m_numNodesPerAxis - 1; k++)\n\t\t\t\t{\n\t\t\t\t\tstd::array<int, 8> cubeNodeIds;\n\t\t\t\t\tcubeNodeIds[0] = k * (m_numNodesPerAxis * m_numNodesPerAxis) + j * m_numNodesPerAxis + i;\n\t\t\t\t\tcubeNodeIds[1] = k * (m_numNodesPerAxis * m_numNodesPerAxis) + j * m_numNodesPerAxis + i + 1;\n\t\t\t\t\tcubeNodeIds[2] = k * (m_numNodesPerAxis * m_numNodesPerAxis) + (j + 1) * m_numNodesPerAxis + i;\n\t\t\t\t\tcubeNodeIds[3] = k * (m_numNodesPerAxis * m_numNodesPerAxis) + (j + 1) * m_numNodesPerAxis + i + 1;\n\t\t\t\t\tcubeNodeIds[4] = (k + 1) * (m_numNodesPerAxis * m_numNodesPerAxis) + j * m_numNodesPerAxis + i;\n\t\t\t\t\tcubeNodeIds[5] = (k + 1) * (m_numNodesPerAxis * m_numNodesPerAxis) + j * m_numNodesPerAxis + i + 1;\n\t\t\t\t\tcubeNodeIds[6] = (k + 1) * (m_numNodesPerAxis * m_numNodesPerAxis) +\n\t\t\t\t\t\t\t\t\t\t(j + 1) * m_numNodesPerAxis + i;\n\t\t\t\t\tcubeNodeIds[7] = (k + 1) * (m_numNodesPerAxis * m_numNodesPerAxis) +\n\t\t\t\t\t\t\t\t\t\t(j+1) * m_numNodesPerAxis + i + 1;\n\n\t\t\t\t\tstd::array<unsigned int, 8> cube = {\n\t\t\t\t\t\tcubeNodeIds[0], cubeNodeIds[1], cubeNodeIds[3], cubeNodeIds[2],\n\t\t\t\t\t\tcubeNodeIds[4], cubeNodeIds[5], cubeNodeIds[7], cubeNodeIds[6]};\n\n\t\t\t\t\t\/\/ Add FemElement3DCube for each cube\n\t\t\t\t\tstd::shared_ptr<FemElement3DCube> femElement = std::make_shared<FemElement3DCube>(cube, *state);\n\t\t\t\t\tfemElement->setMassDensity(1250.0);\n\t\t\t\t\tfemElement->setPoissonRatio(0.499);\n\t\t\t\t\tfemElement->setYoungModulus(15.3e5);\n\t\t\t\t\tfemElement->initialize(*state);\n\t\t\t\t\t\n\t\t\t\t\tthis->addFemElement(femElement);\n\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\nprivate:\n\ttypedef std::array<SurgSim::Math::Vector3d, 8> CubeNodesType;\n\n\t\/\/\/ Creates the truth cube nodes\n\t\/\/\/ \\param size\tThe size in m of the truth cube.\n\tCubeNodesType createCube(double size)\n\t{\n\t\tCubeNodesType cubeNodes;\n\t\tcubeNodes[0] = Vector3d(-0.5,-0.5,-0.5) * size; cubeNodes[1] = Vector3d(0.5,-0.5,-0.5) * size;\n\t\tcubeNodes[2] = Vector3d(-0.5, 0.5,-0.5) * size; cubeNodes[3] = Vector3d( 0.5, 0.5,-0.5) * size;\n\t\tcubeNodes[4] = Vector3d(-0.5,-0.5, 0.5) * size; cubeNodes[5] = Vector3d( 0.5,-0.5, 0.5) * size;\n\t\tcubeNodes[6] = Vector3d(-0.5, 0.5, 0.5) * size; cubeNodes[7] = Vector3d( 0.5, 0.5, 0.5) * size;\n\n\t\treturn cubeNodes;\n\t}\n\n\t\/\/ Name of the truth cube representation\n\tstd::string m_name;\n\t\/\/ Size in m of the original truth cube\n\tdouble m_size; \n\n\t\/\/ Level of subdivision \n\tunsigned int m_levelSubdivision;\n\n\t\/\/ Number of point per dimensions for each subdivision level\n\tint m_numNodesPerAxis; \n\n\t\/\/ Displacement\n\tstd::vector<double> m_displacement;\n\n\t\/\/ BoundaryCondition\n\tstd::vector<bool> m_boundary;\n\n\t\/\/ Nodes of the original truth cube \n\tCubeNodesType m_cubeNodes;\n\n\t\/\/ Nodes of the subdivision cubes in 3D\n\tstd::vector<std::vector<std::vector<Vector3d>>> m_nodes;\n};\n\n}; \/\/ namespace Physics\n}; \/\/ namespace SurgSim\n\n<commit_msg>Add accessors for boundary conditions and state of the truth cube.<commit_after>\t\/\/ This file is a part of the OpenSurgSim project.\n\/\/ Copyright 2013, SimQuest Solutions Inc.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include <math.h>\n#include <iostream>\n#include <fstream>\n#include \"SurgSim\/Physics\/RenderTests\/RenderTest.h\"\n\n#include \"SurgSim\/Framework\/ApplicationData.h\"\n#include \"SurgSim\/Graphics\/PointCloudRepresentation.h\"\n#include \"SurgSim\/Graphics\/OsgPointCloudRepresentation.h\"\n#include \"SurgSim\/Math\/Quaternion.h\"\n#include \"SurgSim\/Math\/Vector.h\"\n#include \"SurgSim\/Math\/RigidTransform.h\"\n\n#include \"SurgSim\/Physics\/PhysicsManager.h\"\n#include \"SurgSim\/Physics\/Fem3DRepresentation.h\"\n#include \"SurgSim\/Physics\/FemElement3DCube.h\"\n#include \"SurgSim\/Physics\/PhysicsManager.h\"\n#include \"SurgSim\/Graphics\/OsgViewElement.h\"\n#include \"SurgSim\/Framework\/SceneElement.h\"\n#include \"SurgSim\/Graphics\/OsgCamera.h\"\n#include \"SurgSim\/Graphics\/OsgManager.h\"\n#include \"SurgSim\/Graphics\/OsgView.h\"\n#include \"SurgSim\/Math\/Quaternion.h\"\n\nusing SurgSim::Math::Vector3d;\nusing SurgSim::Math::Quaterniond;\nusing SurgSim::Math::RigidTransform3d;\nusing SurgSim::Math::makeRigidTransform;\nusing SurgSim::Framework::SceneElement;\nusing SurgSim::Graphics::OsgPointCloudRepresentation;\nusing SurgSim::Physics::PhysicsManager;\nusing SurgSim::Framework::SceneElement;\n\n\nnamespace SurgSim\n{\nnamespace Physics\n{\n\n\/\/\/ Truth cube implementation by Fem3DRepresentation\nclass TruthCubeRepresentation : public Fem3DRepresentation\n{\npublic:\n\t\/\/\/ Constructor\n\t\/\/\/ \\param name\tThe name of the truth cube representation.\n\t\/\/\/ \\param size\tThe original length of the truth cube in mm.\n\t\/\/\/ \\param level\tThe subdivision level.\n\texplicit TruthCubeRepresentation(const std::string& name, double size, unsigned int level) :\n\t\tm_name(name),\n\t\tm_size(size),\n\t\tm_levelSubdivision(level),\n\t\tFem3DRepresentation(name)\n\t{\n\t\tconst int dofPerNode = 3;\n\n\t\tm_numNodesPerAxis = pow(2, m_levelSubdivision) + 1;\n\t\tm_displacement.resize(m_numNodesPerAxis * m_numNodesPerAxis * m_numNodesPerAxis * dofPerNode);\n\t\tm_boundary.resize(m_numNodesPerAxis * m_numNodesPerAxis * m_numNodesPerAxis * dofPerNode);\n\t\tm_cubeNodes = createCube(m_size);\n\t}\n\n\t\/\/\/ Destructor \n\t~TruthCubeRepresentation()\n\t{\n\t}\n\n\t\/\/\/ Gets the number of nodes per axis of truth cube\n\t\/\/\/ \\return The number of nodes per axis.\n\tunsigned int getNumNodesPerAxis()\n\t{\n\t\treturn m_numNodesPerAxis;\n\t}\n\n\t\/\/\/ Gets displacement values\n\t\/\/\/ \\return The vector of displacement\n\tstd::vector<double> getDisplacements()\n\t{\n\t\treturn m_displacement;\n\t}\n\n\t\/\/\/ Get number of displacement \n\t\/\/\/ \\return the size of displacement vector\n\tint getNumofDisplacements()\n\t{\n\t\treturn m_displacement.size();\n\t}\n\n\t\/\/\/ Sets state for the truth cube representation\n\t\/\/\/ \\param state\tThe deformable state. \n\tvoid setDeformableState(std::shared_ptr<DeformableRepresentationState> state)\n\t{\n\t\tint nodeId = 0;\n\t\tfor (int k = 0; k < m_numNodesPerAxis; k++)\n\t\t{\n\t\t\tfor (int j = 0; j < m_numNodesPerAxis; j++)\n\t\t\t{\n\t\t\t\tfor (int i = 0; i < m_numNodesPerAxis; i++)\n\t\t\t\t{\n\t\t\t\t\tstate->getPositions()[nodeId * 3 + 0] = m_nodes[i][j][k][0];\n\t\t\t\t\tstate->getPositions()[nodeId * 3 + 1] = m_nodes[i][j][k][1];\n\t\t\t\t\tstate->getPositions()[nodeId * 3 + 2] = m_nodes[i][j][k][2];\n\t\t\t\t\tnodeId++;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/\/ Sets the boundary condition for the truth cube\n\t\/\/\/ \\param displacement\tThe displacement of the boundary conditions\n\tvoid setBoundaryCondition(double displacement)\n\t{\n\t\tint nodeId = 0;\n\t\tfor (int k = 0; k < m_numNodesPerAxis; k++)\n\t\t{\n\t\t\tfor (int j = 0; j < m_numNodesPerAxis; j++)\n\t\t\t{\n\t\t\t\tfor (int i = 0; i < m_numNodesPerAxis; i++)\n\t\t\t\t{\n\n\t\t\t\t\t\/\/ Boundary conditions at bottom layer\n\t\t\t\t\tif (j == 0)\n\t\t\t\t\t{\n\t\t\t\t\t\tm_boundary[nodeId * 3 + 0] = true;\n\t\t\t\t\t\tm_boundary[nodeId * 3 + 1] = true;\n\t\t\t\t\t\tm_boundary[nodeId * 3 + 2] = true;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (j == m_numNodesPerAxis-1)\n\t\t\t\t\t{\n\t\t\t\t\t\t\/\/ Apply displacement value\n\t\t\t\t\t\tm_displacement[nodeId * 3 + 1] = displacement;\n\n\t\t\t\t\t}\n\t\t\t\t\tnodeId++;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tstd::vector<bool> getBoundaryConditions()\n\t{\n\t\treturn m_boundary;\n\t}\n\n\t\/\/\/ Creates the subdivision truth cube nodes\n\tvoid createTruthCubeMesh()\n\t{\n\t\tm_nodes.resize(m_numNodesPerAxis);\n\t\tfor (int i = 0; i < m_numNodesPerAxis; i++)\n\t\t{\n\t\t\tm_nodes[i].resize(m_numNodesPerAxis);\n\t\t\tVector3d extremitiesX0[4] = {m_cubeNodes[0], m_cubeNodes[2], m_cubeNodes[4], m_cubeNodes[6]};\n\t\t\tVector3d extremitiesX1[4] = {m_cubeNodes[1], m_cubeNodes[3], m_cubeNodes[5], m_cubeNodes[7]};\n\n\t\t\tVector3d extremitiesXi[4];\n\t\t\tfor (int index = 0; index < 4; index++)\n\t\t\t{\n\t\t\t\textremitiesXi[index] = extremitiesX0[index] * (1.0 - i \/ (m_numNodesPerAxis - 1.0)) +\n\t\t\t\t\textremitiesX1[index] * i \/ (m_numNodesPerAxis - 1.0);\n\t\t\t}\n\n\t\t\tfor (int j = 0; j < m_numNodesPerAxis; j++)\n\t\t\t{\n\t\t\t\tVector3d extremitiesY0[2] = {extremitiesXi[0], extremitiesXi[2]};\n\t\t\t\tVector3d extremitiesY1[2] = {extremitiesXi[1], extremitiesXi[3]};\n\n\t\t\t\tVector3d extremitiesYi[2];\n\t\t\t\tfor (int index = 0; index < 2; index++)\n\t\t\t\t{\n\t\t\t\t\textremitiesYi[index] = extremitiesY0[index] * (1.0 - j\/(m_numNodesPerAxis - 1.0)) +\n\t\t\t\t\t\textremitiesY1[index] * j \/ (m_numNodesPerAxis - 1.0);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tm_nodes[i][j].resize(m_numNodesPerAxis);\n\t\t\t\tfor (int k=0; k < m_numNodesPerAxis; k++)\n\t\t\t\t{\n\t\t\t\t\tm_nodes[i][j][k] = extremitiesYi[0] * (1.0 - k \/ (m_numNodesPerAxis - 1.0)) + extremitiesYi[1]\n\t\t\t\t\t\t\t\t\t\t* k \/ (m_numNodesPerAxis - 1.0);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/\/ Adds the Fem3D elements of small cubes\n\t\/\/\/ \\param state\tThe deformable state for initialization.\n\tvoid addFemCubes(std::shared_ptr<DeformableRepresentationState> state)\n\t{\n\t\tfor (int i = 0; i < m_numNodesPerAxis - 1; i++)\n\t\t{\n\t\t\tfor (int j = 0; j < m_numNodesPerAxis - 1; j++)\n\t\t\t{\n\t\t\t\tfor (int k = 0; k < m_numNodesPerAxis - 1; k++)\n\t\t\t\t{\n\t\t\t\t\tstd::array<int, 8> cubeNodeIds;\n\t\t\t\t\tcubeNodeIds[0] = k * (m_numNodesPerAxis * m_numNodesPerAxis) + j * m_numNodesPerAxis + i;\n\t\t\t\t\tcubeNodeIds[1] = k * (m_numNodesPerAxis * m_numNodesPerAxis) + j * m_numNodesPerAxis + i + 1;\n\t\t\t\t\tcubeNodeIds[2] = k * (m_numNodesPerAxis * m_numNodesPerAxis) + (j + 1) * m_numNodesPerAxis + i;\n\t\t\t\t\tcubeNodeIds[3] = k * (m_numNodesPerAxis * m_numNodesPerAxis) + (j + 1) * m_numNodesPerAxis + i + 1;\n\t\t\t\t\tcubeNodeIds[4] = (k + 1) * (m_numNodesPerAxis * m_numNodesPerAxis) + j * m_numNodesPerAxis + i;\n\t\t\t\t\tcubeNodeIds[5] = (k + 1) * (m_numNodesPerAxis * m_numNodesPerAxis) + j * m_numNodesPerAxis + i + 1;\n\t\t\t\t\tcubeNodeIds[6] = (k + 1) * (m_numNodesPerAxis * m_numNodesPerAxis) +\n\t\t\t\t\t\t\t\t\t\t(j + 1) * m_numNodesPerAxis + i;\n\t\t\t\t\tcubeNodeIds[7] = (k + 1) * (m_numNodesPerAxis * m_numNodesPerAxis) +\n\t\t\t\t\t\t\t\t\t\t(j+1) * m_numNodesPerAxis + i + 1;\n\n\t\t\t\t\tstd::array<unsigned int, 8> cube = {\n\t\t\t\t\t\tcubeNodeIds[0], cubeNodeIds[1], cubeNodeIds[3], cubeNodeIds[2],\n\t\t\t\t\t\tcubeNodeIds[4], cubeNodeIds[5], cubeNodeIds[7], cubeNodeIds[6]};\n\n\t\t\t\t\t\/\/ Add FemElement3DCube for each cube\n\t\t\t\t\tstd::shared_ptr<FemElement3DCube> femElement = std::make_shared<FemElement3DCube>(cube, *state);\n\t\t\t\t\tfemElement->setMassDensity(1250.0);\n\t\t\t\t\tfemElement->setPoissonRatio(0.499);\n\t\t\t\t\tfemElement->setYoungModulus(15.3e5);\n\t\t\t\t\tfemElement->initialize(*state);\n\t\t\t\t\t\n\t\t\t\t\tthis->addFemElement(femElement);\n\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\nprivate:\n\ttypedef std::array<SurgSim::Math::Vector3d, 8> CubeNodesType;\n\n\t\/\/\/ Creates the truth cube nodes\n\t\/\/\/ \\param size\tThe size in m of the truth cube.\n\tCubeNodesType createCube(double size)\n\t{\n\t\tCubeNodesType cubeNodes;\n\t\tcubeNodes[0] = Vector3d(-0.5,-0.5,-0.5) * size; cubeNodes[1] = Vector3d(0.5,-0.5,-0.5) * size;\n\t\tcubeNodes[2] = Vector3d(-0.5, 0.5,-0.5) * size; cubeNodes[3] = Vector3d( 0.5, 0.5,-0.5) * size;\n\t\tcubeNodes[4] = Vector3d(-0.5,-0.5, 0.5) * size; cubeNodes[5] = Vector3d( 0.5,-0.5, 0.5) * size;\n\t\tcubeNodes[6] = Vector3d(-0.5, 0.5, 0.5) * size; cubeNodes[7] = Vector3d( 0.5, 0.5, 0.5) * size;\n\n\t\treturn cubeNodes;\n\t}\n\n\t\/\/ Name of the truth cube representation\n\tstd::string m_name;\n\t\/\/ Size in m of the original truth cube\n\tdouble m_size; \n\n\t\/\/ Level of subdivision \n\tunsigned int m_levelSubdivision;\n\n\t\/\/ Number of point per dimensions for each subdivision level\n\tint m_numNodesPerAxis; \n\n\t\/\/ Displacement\n\tstd::vector<double> m_displacement;\n\n\t\/\/ BoundaryCondition\n\tstd::vector<bool> m_boundary;\n\n\t\/\/ Nodes of the original truth cube \n\tCubeNodesType m_cubeNodes;\n\n\t\/\/ Nodes of the subdivision cubes in 3D\n\tstd::vector<std::vector<std::vector<Vector3d>>> m_nodes;\n};\n\n}; \/\/ namespace Physics\n}; \/\/ namespace SurgSim\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright 2019 Centreon (https:\/\/www.centreon.com\/)\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n * For more information : contact@centreon.com\n *\n *\/\n\n#include \"com\/centreon\/broker\/brokerrpc.hh\"\n\n#include <gtest\/gtest.h>\n\n#include <cstdio>\n#include <fstream>\n#include <json11.hpp>\n\n#include \"com\/centreon\/broker\/log_v2.hh\"\n#include \"com\/centreon\/broker\/version.hh\"\n\nusing namespace com::centreon;\nusing namespace com::centreon::broker;\n\nclass BrokerRpc : public ::testing::Test {\n public:\n void SetUp() override {}\n\n void TearDown() override {}\n\n std::list<std::string> execute(const std::string& command) {\n std::list<std::string> retval;\n char path[1024];\n std::ostringstream oss;\n oss << \"test\/rpc_client \" << command;\n\n FILE* fp = popen(oss.str().c_str(), \"r\");\n while (fgets(path, sizeof(path), fp) != nullptr) {\n size_t count = strlen(path);\n if (count > 0)\n --count;\n retval.push_back(std::string(path, count));\n }\n pclose(fp);\n return retval;\n }\n};\n\nTEST_F(BrokerRpc, StartStop) {\n brokerrpc brpc(\"0.0.0.0\", 40000, \"test\");\n ASSERT_NO_THROW(brpc.shutdown());\n}\n\nTEST_F(BrokerRpc, GetVersion) {\n std::ostringstream oss;\n oss << \"GetVersion: major: \" << version::major;\n brokerrpc brpc(\"0.0.0.0\", 40000, \"test\");\n auto output = execute(\"GetVersion\");\n ASSERT_EQ(output.size(), 3);\n ASSERT_EQ(output.front(), oss.str());\n oss.str(\"\");\n oss << \"patch: \" << version::patch;\n ASSERT_EQ(output.back(), oss.str());\n brpc.shutdown();\n}\n\nTEST_F(BrokerRpc, ConfReloadBad) {\n brokerrpc brpc(\"0.0.0.0\", 40000, \"test\");\n auto output = execute(\"DebugConfReload \/root\/testfail.json\");\n ASSERT_EQ(output.size(), 1);\n ASSERT_EQ(output.back(),\n \"DebugConfReload failed for file \/root\/testfail.json : file '\/root\/testfail.json' does not exist\");\n brpc.shutdown();\n}\n\nTEST_F(BrokerRpc, ConfReloadOK) {\n json11::Json my_json = json11::Json::object{\n {\"console\", true}, {\"loggers\", json11::Json::array{}}};\n std::string output_str;\n my_json.dump(output_str);\n\n std::remove(\"\/tmp\/testok.json\");\n std::ofstream conf(\"\/tmp\/testok.json\");\n conf << output_str;\n conf.close();\n\n testing::internal::CaptureStdout();\n\n brokerrpc brpc(\"0.0.0.0\", 40000, \"broker\");\n auto output = execute(\"DebugConfReload \/tmp\/testok.json\");\n ASSERT_EQ(output.size(), 1);\n ASSERT_EQ(output.back(), \"DebugConfReload OK\");\n log_v2::core()->info(\"test\");\n brpc.shutdown();\n\n std::string log_output = testing::internal::GetCapturedStdout();\n\n ASSERT_NE(log_output.find(\"] broker :\"), std::string::npos);\n ASSERT_NE(log_output.find(\"] test\"), std::string::npos);\n\n std::remove(\"\/tmp\/testok.json\");\n}\n<commit_msg>fix(test): fix BrokerRpc.GetVersion unit test.<commit_after>\/*\n * Copyright 2019 Centreon (https:\/\/www.centreon.com\/)\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n * For more information : contact@centreon.com\n *\n *\/\n\n#include \"com\/centreon\/broker\/brokerrpc.hh\"\n\n#include <gtest\/gtest.h>\n\n#include <cstdio>\n#include <fstream>\n#include <json11.hpp>\n\n#include \"com\/centreon\/broker\/log_v2.hh\"\n#include \"com\/centreon\/broker\/version.hh\"\n\nusing namespace com::centreon;\nusing namespace com::centreon::broker;\n\nclass BrokerRpc : public ::testing::Test {\n public:\n void SetUp() override {}\n\n void TearDown() override {}\n\n std::list<std::string> execute(const std::string& command) {\n std::list<std::string> retval;\n char path[1024];\n std::ostringstream oss;\n oss << \"test\/rpc_client \" << command;\n\n FILE* fp = popen(oss.str().c_str(), \"r\");\n while (fgets(path, sizeof(path), fp) != nullptr) {\n size_t count = strlen(path);\n if (count > 0)\n --count;\n retval.push_back(std::string(path, count));\n }\n pclose(fp);\n return retval;\n }\n};\n\nTEST_F(BrokerRpc, StartStop) {\n brokerrpc brpc(\"0.0.0.0\", 40000, \"test\");\n ASSERT_NO_THROW(brpc.shutdown());\n}\n\nTEST_F(BrokerRpc, GetVersion) {\n std::ostringstream oss;\n oss << \"GetVersion: major: \" << version::major;\n brokerrpc brpc(\"0.0.0.0\", 40000, \"test\");\n auto output = execute(\"GetVersion\");\n#if CENTREON_BROKER_PATCH == 0\n ASSERT_EQ(output.size(), 2);\n ASSERT_EQ(output.front(), oss.str());\n oss.str(\"\");\n oss << \"minor: \" << version::minor;\n ASSERT_EQ(output.back(), oss.str());\n#else\n ASSERT_EQ(output.size(), 3);\n ASSERT_EQ(output.front(), oss.str());\n oss.str(\"\");\n oss << \"patch: \" << version::patch;\n ASSERT_EQ(output.back(), oss.str());\n#endif\n brpc.shutdown();\n}\n\nTEST_F(BrokerRpc, ConfReloadBad) {\n brokerrpc brpc(\"0.0.0.0\", 40000, \"test\");\n auto output = execute(\"DebugConfReload \/root\/testfail.json\");\n ASSERT_EQ(output.size(), 1);\n ASSERT_EQ(output.back(),\n \"DebugConfReload failed for file \/root\/testfail.json : file '\/root\/testfail.json' does not exist\");\n brpc.shutdown();\n}\n\nTEST_F(BrokerRpc, ConfReloadOK) {\n json11::Json my_json = json11::Json::object{\n {\"console\", true}, {\"loggers\", json11::Json::array{}}};\n std::string output_str;\n my_json.dump(output_str);\n\n std::remove(\"\/tmp\/testok.json\");\n std::ofstream conf(\"\/tmp\/testok.json\");\n conf << output_str;\n conf.close();\n\n testing::internal::CaptureStdout();\n\n brokerrpc brpc(\"0.0.0.0\", 40000, \"broker\");\n auto output = execute(\"DebugConfReload \/tmp\/testok.json\");\n ASSERT_EQ(output.size(), 1);\n ASSERT_EQ(output.back(), \"DebugConfReload OK\");\n log_v2::core()->info(\"test\");\n brpc.shutdown();\n\n std::string log_output = testing::internal::GetCapturedStdout();\n\n ASSERT_NE(log_output.find(\"] broker :\"), std::string::npos);\n ASSERT_NE(log_output.find(\"] test\"), std::string::npos);\n\n std::remove(\"\/tmp\/testok.json\");\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Android File Transfer for Linux: MTP client for android devices\n * Copyright (C) 2015 Vladimir Menshakov\n\n * This program is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU General Public License\n * as published by the Free Software Foundation; either version 2\n * of the License, or (at your option) any later version.\n\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n\n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n *\/\n#include <stdio.h>\n#include <stdexcept>\n\n#include <usb\/BulkPipe.h>\n#include <usb\/Context.h>\n#include <mtp\/ptp\/Container.h>\n#include <mtp\/ptp\/Device.h>\n#include <mtp\/ptp\/Messages.h>\n\nint main(int argc, char **argv)\n{\n\tusing namespace mtp;\n\t\/\/USB_CALL(libusb_reset_device(device->GetHandle()));\n\n\t\/\/printf(\"claiming interface %d...\\n\", interface->GetIndex());\n\t\/\/USB_CALL(libusb_claim_interface(device->GetHandle(), interface->GetIndex()));\n\t\/\/printf(\"claimed interface\\n\");\n\t\/\/USB_CALL(libusb_set_interface_alt_setting(device->GetHandle(), mtp_interface, 0));\n\n\tDevicePtr mtp(Device::Find());\n\tif (!mtp)\n\t{\n\t\tprintf(\"no mtp device found\\n\");\n\t\treturn 1;\n\t}\n\n\tmsg::DeviceInfo gdi = mtp->GetDeviceInfo();\n\tprintf(\"%s\\n\", gdi.VendorExtensionDesc.c_str());\n\tprintf(\"%s \", gdi.Manufactorer.c_str());\n\tprintf(\"%s \", gdi.Model.c_str());\n\tprintf(\"%s \", gdi.DeviceVersion.c_str());\n\tprintf(\"%s\\n\", gdi.SerialNumber.c_str());\n\tprintf(\"supported op codes: \");\n\tfor(u16 code : gdi.OperationsSupported)\n\t{\n\t\tprintf(\"%04x \", (unsigned)code);\n\t}\n\tprintf(\"\\n\");\n\tprintf(\"supported properties: \");\n\tfor(u16 code : gdi.DevicePropertiesSupported)\n\t{\n\t\tprintf(\"%04x \", (unsigned)code);\n\t}\n\tprintf(\"\\n\");\n\n\tif (argc < 2)\n\t\treturn 0;\n\n\tSessionPtr session = mtp->OpenSession(1);\n\tstd::string command = argv[1];\n\tif (command == \"list\")\n\t{\n\t\tmtp::u32 parent = mtp::Session::Root;\n\t\tif (argc > 2)\n\t\t\tif (sscanf(argv[2], \"%x\", &parent) != 1)\n\t\t\t\treturn 1;\n\n\t\tmsg::ObjectHandles handles = session->GetObjectHandles(mtp::Session::AllStorages, mtp::Session::AllFormats, parent);\n\n\t\tfor(u32 objectId : handles.ObjectHandles)\n\t\t{\n\t\t\ttry\n\t\t\t{\n\t\t\t\tmsg::ObjectInfo info = session->GetObjectInfo(objectId);\n\t\t\t\tprintf(\"%08x %04x %s %u %ux%u, %s\\n\", objectId, info.ObjectFormat, info.Filename.c_str(), info.ObjectCompressedSize, info.ImagePixWidth, info.ImagePixHeight, info.CaptureDate.c_str());\n\t\t\t}\n\t\t\tcatch(const std::exception &ex)\n\t\t\t{\n\t\t\t\tprintf(\"error: %s\\n\", ex.what());\n\t\t\t}\n\t\t}\n\t\t\/\/libusb_release_interface(device->GetHandle(), interface->GetIndex());\n\t}\n\telse if (command == \"get\")\n\t{\n\t\tif (argc < 3)\n\t\t\treturn 1;\n\t\tmtp::u32 objectId;\n\t\tif (sscanf(argv[2], \"%x\", &objectId) != 1)\n\t\t\treturn 1;\n\t\tprintf(\"object id = %08x\\n\", objectId);\n\t\tmsg::ObjectInfo info = session->GetObjectInfo(objectId);\n\t\tprintf(\"filename = %s\\n\", info.Filename.c_str());\n\t\tFILE *f = fopen(info.Filename.c_str(), \"wb\");\n\t\tif (!f)\n\t\t{\n\t\t\tperror(\"open\");\n\t\t\treturn 1;\n\t\t}\n\t\tByteArray object = session->GetObject(objectId);\n\t\tif (fwrite(object.data(), object.size(), 1, f) != 1)\n\t\t\tperror(\"fwriter\");\n\t\tfclose(f);\n\t}\n\telse if (command == \"set\")\n\t{\n\t\tif (argc < 4)\n\t\t\treturn 1;\n\n\t\tmtp::u32 parentObjectId;\n\t\tif (sscanf(argv[2], \"%x\", &parentObjectId) != 1)\n\t\t\treturn 1;\n\n\t\tstd::string filename(argv[3]);\n\t\tprintf(\"uploading %s to %08x\\n\", filename.c_str(), parentObjectId);\n\t\tFILE *f = fopen(filename.c_str(), \"rb\");\n\t\tif (!f)\n\t\t{\n\t\t\tperror(\"open\");\n\t\t\treturn 1;\n\t\t}\n\t\tmsg::ObjectInfo oi;\n\t\toi.Filename = filename;\n\t\toi.ObjectFormat = ObjectFormatFromFilename(filename);\n\n\t\tfseek(f, 0, SEEK_END);\n\t\toi.ObjectCompressedSize = ftell(f);\n\t\trewind(f);\n\n\t\tByteArray data(oi.ObjectCompressedSize);\n\t\tif (fread(data.data(), data.size(), 1, f) != 1)\n\t\t\tthrow std::runtime_error(\"read failed\");\n\n\t\tfclose(f);\n\n\t\tSession::NewObjectInfo noi = session->SendObjectInfo(oi, 0, parentObjectId);\n\t\tprintf(\"new object id = %08x\\n\", noi.ObjectId);\n\t\tsession->SendObject(data);\n\t\tprintf(\"done\\n\");\n\t}\n\telse if (command == \"delete\")\n\t{\n\t\tif (argc < 3)\n\t\t\treturn 1;\n\n\t\tmtp::u32 objectId;\n\t\tif (sscanf(argv[2], \"%x\", &objectId) != 1)\n\t\t\treturn 1;\n\n\t\tprintf(\"object id = %08x\\n\", objectId);\n\t\tsession->DeleteObject(objectId);\n\t}\n\telse if (command == \"mkdir\")\n\t{\n\t\tif (argc < 3)\n\t\t\treturn 1;\n\n\t\tmtp::u32 parentObjectId = mtp::Session::Root;\n\t\tif (argc > 3 && sscanf(argv[3], \"%x\", &parentObjectId) != 1)\n\t\t\treturn 1;\n\n\t\tstd::string filename = argv[2];\n\t\tmsg::ObjectInfo oi;\n\t\toi.Filename = filename;\n\t\toi.ObjectFormat = ObjectFormat::Association;\n\t\tsession->SendObjectInfo(oi, 0, parentObjectId);\n\t}\n\telse if (command == \"properties\")\n\t{\n\t\tif (argc < 3)\n\t\t\treturn 1;\n\n\t\tmtp::u32 objectId;\n\t\tif (sscanf(argv[2], \"%x\", &objectId) != 1)\n\t\t\treturn 1;\n\t\tmsg::ObjectPropsSupported ops = session->GetObjectPropsSupported(objectId);\n\t\tprintf(\"properties supported: \");\n\t\tfor(u16 prop: ops.ObjectPropCodes)\n\t\t{\n\t\t\tprintf(\"%02x \", prop);\n\t\t}\n\t\tprintf(\"\\n\");\n\t}\n\n\treturn 0;\n}\n<commit_msg>replaced hexadecimal ids with decimal<commit_after>\/*\n * Android File Transfer for Linux: MTP client for android devices\n * Copyright (C) 2015 Vladimir Menshakov\n\n * This program is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU General Public License\n * as published by the Free Software Foundation; either version 2\n * of the License, or (at your option) any later version.\n\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n\n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n *\/\n#include <stdio.h>\n#include <stdexcept>\n\n#include <usb\/BulkPipe.h>\n#include <usb\/Context.h>\n#include <mtp\/ptp\/Container.h>\n#include <mtp\/ptp\/Device.h>\n#include <mtp\/ptp\/Messages.h>\n\nint main(int argc, char **argv)\n{\n\tusing namespace mtp;\n\t\/\/USB_CALL(libusb_reset_device(device->GetHandle()));\n\n\t\/\/printf(\"claiming interface %d...\\n\", interface->GetIndex());\n\t\/\/USB_CALL(libusb_claim_interface(device->GetHandle(), interface->GetIndex()));\n\t\/\/printf(\"claimed interface\\n\");\n\t\/\/USB_CALL(libusb_set_interface_alt_setting(device->GetHandle(), mtp_interface, 0));\n\n\tDevicePtr mtp(Device::Find());\n\tif (!mtp)\n\t{\n\t\tprintf(\"no mtp device found\\n\");\n\t\treturn 1;\n\t}\n\n\tmsg::DeviceInfo gdi = mtp->GetDeviceInfo();\n\tprintf(\"%s\\n\", gdi.VendorExtensionDesc.c_str());\n\tprintf(\"%s \", gdi.Manufactorer.c_str());\n\tprintf(\"%s \", gdi.Model.c_str());\n\tprintf(\"%s \", gdi.DeviceVersion.c_str());\n\tprintf(\"%s\\n\", gdi.SerialNumber.c_str());\n\tprintf(\"supported op codes: \");\n\tfor(u16 code : gdi.OperationsSupported)\n\t{\n\t\tprintf(\"%04x \", (unsigned)code);\n\t}\n\tprintf(\"\\n\");\n\tprintf(\"supported properties: \");\n\tfor(u16 code : gdi.DevicePropertiesSupported)\n\t{\n\t\tprintf(\"%04x \", (unsigned)code);\n\t}\n\tprintf(\"\\n\");\n\n\tif (argc < 2)\n\t\treturn 0;\n\n\tSessionPtr session = mtp->OpenSession(1);\n\tstd::string command = argv[1];\n\tif (command == \"list\")\n\t{\n\t\tmtp::u32 parent = mtp::Session::Root;\n\t\tif (argc > 2)\n\t\t\tif (sscanf(argv[2], \"%u\", &parent) != 1)\n\t\t\t\treturn 1;\n\n\t\tmsg::ObjectHandles handles = session->GetObjectHandles(mtp::Session::AllStorages, mtp::Session::AllFormats, parent);\n\n\t\tfor(u32 objectId : handles.ObjectHandles)\n\t\t{\n\t\t\ttry\n\t\t\t{\n\t\t\t\tmsg::ObjectInfo info = session->GetObjectInfo(objectId);\n\t\t\t\tprintf(\"%-10u %04x %s %u %ux%u, %s\\n\", objectId, info.ObjectFormat, info.Filename.c_str(), info.ObjectCompressedSize, info.ImagePixWidth, info.ImagePixHeight, info.CaptureDate.c_str());\n\t\t\t}\n\t\t\tcatch(const std::exception &ex)\n\t\t\t{\n\t\t\t\tprintf(\"error: %s\\n\", ex.what());\n\t\t\t}\n\t\t}\n\t\t\/\/libusb_release_interface(device->GetHandle(), interface->GetIndex());\n\t}\n\telse if (command == \"get\")\n\t{\n\t\tif (argc < 3)\n\t\t\treturn 1;\n\t\tmtp::u32 objectId;\n\t\tif (sscanf(argv[2], \"%u\", &objectId) != 1)\n\t\t\treturn 1;\n\t\tprintf(\"object id = %u\\n\", objectId);\n\t\tmsg::ObjectInfo info = session->GetObjectInfo(objectId);\n\t\tprintf(\"filename = %s\\n\", info.Filename.c_str());\n\t\tFILE *f = fopen(info.Filename.c_str(), \"wb\");\n\t\tif (!f)\n\t\t{\n\t\t\tperror(\"open\");\n\t\t\treturn 1;\n\t\t}\n\t\tByteArray object = session->GetObject(objectId);\n\t\tif (fwrite(object.data(), object.size(), 1, f) != 1)\n\t\t\tperror(\"fwriter\");\n\t\tfclose(f);\n\t}\n\telse if (command == \"set\")\n\t{\n\t\tif (argc < 4)\n\t\t\treturn 1;\n\n\t\tmtp::u32 parentObjectId;\n\t\tif (sscanf(argv[2], \"%u\", &parentObjectId) != 1)\n\t\t\treturn 1;\n\n\t\tstd::string filename(argv[3]);\n\t\tprintf(\"uploading %s to %u\\n\", filename.c_str(), parentObjectId);\n\t\tFILE *f = fopen(filename.c_str(), \"rb\");\n\t\tif (!f)\n\t\t{\n\t\t\tperror(\"open\");\n\t\t\treturn 1;\n\t\t}\n\t\tmsg::ObjectInfo oi;\n\t\toi.Filename = filename;\n\t\toi.ObjectFormat = ObjectFormatFromFilename(filename);\n\n\t\tfseek(f, 0, SEEK_END);\n\t\toi.ObjectCompressedSize = ftell(f);\n\t\trewind(f);\n\n\t\tByteArray data(oi.ObjectCompressedSize);\n\t\tif (fread(data.data(), data.size(), 1, f) != 1)\n\t\t\tthrow std::runtime_error(\"read failed\");\n\n\t\tfclose(f);\n\n\t\tSession::NewObjectInfo noi = session->SendObjectInfo(oi, 0, parentObjectId);\n\t\tprintf(\"new object id = %u\\n\", noi.ObjectId);\n\t\tsession->SendObject(data);\n\t\tprintf(\"done\\n\");\n\t}\n\telse if (command == \"delete\")\n\t{\n\t\tif (argc < 3)\n\t\t\treturn 1;\n\n\t\tmtp::u32 objectId;\n\t\tif (sscanf(argv[2], \"%u\", &objectId) != 1)\n\t\t\treturn 1;\n\n\t\tprintf(\"object id = %u\\n\", objectId);\n\t\tsession->DeleteObject(objectId);\n\t}\n\telse if (command == \"mkdir\")\n\t{\n\t\tif (argc < 3)\n\t\t\treturn 1;\n\n\t\tmtp::u32 parentObjectId = mtp::Session::Root;\n\t\tif (argc > 3 && sscanf(argv[3], \"%u\", &parentObjectId) != 1)\n\t\t\treturn 1;\n\n\t\tstd::string filename = argv[2];\n\t\tmsg::ObjectInfo oi;\n\t\toi.Filename = filename;\n\t\toi.ObjectFormat = ObjectFormat::Association;\n\t\tsession->SendObjectInfo(oi, 0, parentObjectId);\n\t}\n\telse if (command == \"properties\")\n\t{\n\t\tif (argc < 3)\n\t\t\treturn 1;\n\n\t\tmtp::u32 objectId;\n\t\tif (sscanf(argv[2], \"%u\", &objectId) != 1)\n\t\t\treturn 1;\n\t\tmsg::ObjectPropsSupported ops = session->GetObjectPropsSupported(objectId);\n\t\tprintf(\"properties supported: \");\n\t\tfor(u16 prop: ops.ObjectPropCodes)\n\t\t{\n\t\t\tprintf(\"%02x \", prop);\n\t\t}\n\t\tprintf(\"\\n\");\n\t}\n\n\treturn 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: twolinesitem.hxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: kz $ $Date: 2007-05-10 14:33:00 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n#ifndef _SVX_TWOLINESITEM_HXX\n#define _SVX_TWOLINESITEM_HXX\n\n#ifndef _SAL_TYPES_H_\n#include <sal\/types.h>\n#endif\n#ifndef _SFXPOOLITEM_HXX\n#include <svtools\/poolitem.hxx>\n#endif\n#ifndef _SVX_SVXIDS_HRC\n#include <svx\/svxids.hrc>\n#endif\n\n#ifndef INCLUDED_SVXDLLAPI_H\n#include \"svx\/svxdllapi.h\"\n#endif\n\nclass SvXMLUnitConverter;\nnamespace rtl\n{\n class OUString;\n}\n\nclass SVX_DLLPUBLIC SvxTwoLinesItem : public SfxPoolItem\n{\n sal_Unicode cStartBracket, cEndBracket;\n sal_Bool bOn;\npublic:\n TYPEINFO();\n SvxTwoLinesItem( sal_Bool bOn \/*= TRUE*\/,\n sal_Unicode nStartBracket \/*= 0*\/,\n sal_Unicode nEndBracket \/*= 0*\/,\n sal_uInt16 nId );\n SvxTwoLinesItem( const SvxTwoLinesItem& rAttr );\n virtual ~SvxTwoLinesItem();\n\n \/\/ \"pure virtual Methoden\" vom SfxPoolItem\n virtual int operator==( const SfxPoolItem& ) const;\n virtual SfxPoolItem* Clone( SfxItemPool* pPool = 0 ) const;\n virtual SfxPoolItem* Create(SvStream &, USHORT nVer) const;\n virtual SvStream& Store(SvStream &, USHORT nIVer) const;\n virtual SfxItemPresentation GetPresentation( SfxItemPresentation ePres,\n SfxMapUnit eCoreMetric,\n SfxMapUnit ePresMetric,\n String &rText,\n const IntlWrapper* pIntl = 0 ) const;\n\n virtual sal_Bool QueryValue( com::sun::star::uno::Any& rVal,\n BYTE nMemberId = 0 ) const;\n virtual sal_Bool PutValue( const com::sun::star::uno::Any& rVal,\n BYTE nMemberId = 0 );\n\n virtual USHORT GetVersion( USHORT nFFVer ) const;\n\n SvxTwoLinesItem& operator=( const SvxTwoLinesItem& rCpy )\n {\n SetValue( rCpy.GetValue() );\n SetStartBracket( rCpy.GetStartBracket() );\n SetEndBracket( rCpy.GetEndBracket() );\n return *this;\n }\n\n sal_Bool GetValue() const { return bOn; }\n void SetValue( sal_Bool bFlag ) { bOn = bFlag; }\n\n sal_Unicode GetStartBracket() const { return cStartBracket; }\n void SetStartBracket( sal_Unicode c ) { cStartBracket = c; }\n\n sal_Unicode GetEndBracket() const { return cEndBracket; }\n void SetEndBracket( sal_Unicode c ) { cEndBracket = c; }\n};\n\n#endif\n\n<commit_msg>INTEGRATION: CWS changefileheader (1.3.446); FILE MERGED 2008\/04\/01 15:49:40 thb 1.3.446.3: #i85898# Stripping all external header guards 2008\/04\/01 12:47:01 thb 1.3.446.2: #i85898# Stripping all external header guards 2008\/03\/31 14:18:21 rt 1.3.446.1: #i87441# Change license header to LPGL v3.<commit_after>\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2008 by Sun Microsystems, Inc.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: twolinesitem.hxx,v $\n * $Revision: 1.4 $\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * <http:\/\/www.openoffice.org\/license.html>\n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n#ifndef _SVX_TWOLINESITEM_HXX\n#define _SVX_TWOLINESITEM_HXX\n\n#include <sal\/types.h>\n#include <svtools\/poolitem.hxx>\n#ifndef _SVX_SVXIDS_HRC\n#include <svx\/svxids.hrc>\n#endif\n#include \"svx\/svxdllapi.h\"\n\nclass SvXMLUnitConverter;\nnamespace rtl\n{\n class OUString;\n}\n\nclass SVX_DLLPUBLIC SvxTwoLinesItem : public SfxPoolItem\n{\n sal_Unicode cStartBracket, cEndBracket;\n sal_Bool bOn;\npublic:\n TYPEINFO();\n SvxTwoLinesItem( sal_Bool bOn \/*= TRUE*\/,\n sal_Unicode nStartBracket \/*= 0*\/,\n sal_Unicode nEndBracket \/*= 0*\/,\n sal_uInt16 nId );\n SvxTwoLinesItem( const SvxTwoLinesItem& rAttr );\n virtual ~SvxTwoLinesItem();\n\n \/\/ \"pure virtual Methoden\" vom SfxPoolItem\n virtual int operator==( const SfxPoolItem& ) const;\n virtual SfxPoolItem* Clone( SfxItemPool* pPool = 0 ) const;\n virtual SfxPoolItem* Create(SvStream &, USHORT nVer) const;\n virtual SvStream& Store(SvStream &, USHORT nIVer) const;\n virtual SfxItemPresentation GetPresentation( SfxItemPresentation ePres,\n SfxMapUnit eCoreMetric,\n SfxMapUnit ePresMetric,\n String &rText,\n const IntlWrapper* pIntl = 0 ) const;\n\n virtual sal_Bool QueryValue( com::sun::star::uno::Any& rVal,\n BYTE nMemberId = 0 ) const;\n virtual sal_Bool PutValue( const com::sun::star::uno::Any& rVal,\n BYTE nMemberId = 0 );\n\n virtual USHORT GetVersion( USHORT nFFVer ) const;\n\n SvxTwoLinesItem& operator=( const SvxTwoLinesItem& rCpy )\n {\n SetValue( rCpy.GetValue() );\n SetStartBracket( rCpy.GetStartBracket() );\n SetEndBracket( rCpy.GetEndBracket() );\n return *this;\n }\n\n sal_Bool GetValue() const { return bOn; }\n void SetValue( sal_Bool bFlag ) { bOn = bFlag; }\n\n sal_Unicode GetStartBracket() const { return cStartBracket; }\n void SetStartBracket( sal_Unicode c ) { cStartBracket = c; }\n\n sal_Unicode GetEndBracket() const { return cEndBracket; }\n void SetEndBracket( sal_Unicode c ) { cEndBracket = c; }\n};\n\n#endif\n\n<|endoftext|>"} {"text":"<commit_before>#include <stdio.h>\n#include <sstream>\n#include <stdexcept>\n\n#include <mtp\/usb\/Context.h>\n#include <mtp\/usb\/call.h>\n#include <mtp\/ptp\/OperationRequest.h>\n#include <mtp\/ptp\/Container.h>\n\nstatic void callback(struct libusb_transfer *transfer)\n{\n\tprintf(\"CALLBACK, status: %d\\n\", transfer->status);\n\tfor(int i = 0; i < transfer->actual_length; ++i)\n\t\tprintf(\"%02x \", transfer->buffer[i]);\n\tprintf(\"\\n\");\n}\n\nint main(int argc, char **argv)\n{\n\tusing namespace mtp;\n\tusb::Context ctx;\n\tusb::DeviceDescriptorPtr desc;\n\tfor (usb::DeviceDescriptorPtr dd : ctx.GetDevices())\n\t{\n\t\tif (dd->GetVendorId() == 0x18d1)\n\t\t{\n\t\t\tdesc = dd;\n\t\t\tbreak;\n\t\t}\n\t}\n\tif (!desc)\n\t\tthrow std::runtime_error(\"no mtp device found\");\n\n\tusb::DevicePtr device = desc->Open();\n\tint confs = desc->GetConfigurationsCount();\n\tprintf(\"configurations: %d\\n\", confs);\n\n\tint mtp_configuration = -1;\n\tint mtp_interface = -1;\n\n\tusb::ConfigurationPtr\t\tconfiguration;\n\tusb::InterfacePtr\t\t\tinterface;\n\n\tfor(int i = 0; i < confs; ++i)\n\t{\n\t\tusb::ConfigurationPtr conf = desc->GetConfiguration(i);\n\t\tint interfaces = conf->GetInterfaceCount();\n\t\tprintf(\"interfaces: %d\\n\", interfaces);\n\t\tfor(int j = 0; j < interfaces; ++j)\n\t\t{\n\t\t\tusb::InterfacePtr iface = conf->GetInterface(j, 0);\n\t\t\tprintf(\"%d:%d index %u, eps %u\\n\", i, j, iface->GetIndex(), iface->GetEndpointsCount());\n\t\t\tint name_idx = iface->GetNameIndex();\n\t\t\tif (!name_idx)\n\t\t\t\tcontinue;\n\t\t\tstd::string name = device->GetString(name_idx);\n\t\t\tif (name == \"MTP\")\n\t\t\t{\n\t\t\t\tconfiguration = conf;\n\t\t\t\tinterface = iface;\n\t\t\t\tmtp_configuration = i;\n\t\t\t\tmtp_interface = j;\n\t\t\t\ti = confs;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\n\tif (!interface || mtp_interface < 0 || mtp_configuration < 0)\n\t\tthrow std::runtime_error(\"no mtp interface found\");\n\n\tdevice->SetConfiguration(configuration->GetIndex());\n\tint epn = interface->GetEndpointsCount();\n\n\tusb::EndpointPtr out, in, interrupt;\n\tprintf(\"endpoints: %d\\n\", epn);\n\tfor(int i = 0; i < epn; ++i)\n\t{\n\t\tusb::EndpointPtr ep = interface->GetEndpoint(i);\n\t\tprintf(\"endpoint: %d: %02x\\n\", i, ep->GetAddress());\n\t\t\/\/check for bulk here\n\t\tif (ep->GetDirection() == usb::EndpointDirection::Out)\n\t\t{\n\t\t\tif (ep->GetType() == usb::EndpointType::Bulk)\n\t\t\t{\n\t\t\t\tprintf(\"OUT\\n\");\n\t\t\t\tout = ep;\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif (ep->GetType() == usb::EndpointType::Bulk)\n\t\t\t{\n\t\t\t\tprintf(\"IN\\n\");\n\t\t\t\tin = ep;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tprintf(\"INTERRUPT\\n\");\n\t\t\t\tinterrupt = ep;\n\t\t\t}\n\t\t}\n\t}\n\tif (!in || !out || !interrupt)\n\t\tthrow std::runtime_error(\"invalid endpoint\");\n\n\t\/\/USB_CALL(libusb_reset_device(device->GetHandle()));\n\n\tprintf(\"claiming interface %d...\\n\", interface->GetIndex());\n\tUSB_CALL(libusb_claim_interface(device->GetHandle(), interface->GetIndex()));\n\tprintf(\"claimed interface\\n\");\n\tUSB_CALL(libusb_set_interface_alt_setting(device->GetHandle(), mtp_interface, 0));\n\n\t\/\/OperationRequest req(OperationCode::OpenSession, 0, 1);\n\tOperationRequest req(OperationCode::GetDeviceInfo, 0, 1);\n\tContainer container(req);\n\n\t\/*\n\tfor(size_t i = 0; i < container.Data.size(); ++i)\n\t\tprintf(\"%02x \", container.Data[i]);\n\tprintf(\"\\n\");\n\t*\/\n\n\tlibusb_clear_halt(device->GetHandle(), out->GetAddress());\n\tlibusb_clear_halt(device->GetHandle(), in->GetAddress());\n\n\tstd::vector<u8> data(in->GetMaxPacketSize());\n\t\/\/std::vector<u8> data(64);\n#if 0\n\tlibusb_transfer *transfer_out = libusb_alloc_transfer(0);\n\t\/\/transfer_out->flags |= LIBUSB_TRANSFER_ADD_ZERO_PACKET | LIBUSB_TRANSFER_SHORT_NOT_OK;\n\tprintf(\"data size: %u\\n\", (unsigned)container.Data.size());\n\tlibusb_fill_bulk_transfer(transfer_out, device->GetHandle(), out->GetAddress(), container.Data.data(), container.Data.size(), &callback, 0, 3000);\n\tUSB_CALL(libusb_submit_transfer(transfer_out));\n\t{\n\t\tctx.Wait();\n\t\tprintf(\"WAIT COMPLETED\\n\");\n\t}\n\n\t\/\/libusb_free_transfer(transfer_out);\n\tlibusb_transfer *transfer_in = libusb_alloc_transfer(0);\n\tlibusb_fill_bulk_transfer(transfer_in, device->GetHandle(), in->GetAddress(), data.data(), data.size(), &callback, 0, 3000);\n\tUSB_CALL(libusb_submit_transfer(transfer_in));\n\n\n\t{\n\t\tctx.Wait();\n\t\tprintf(\"WAIT COMPLETED\\n\");\n\t}\n\n#else\n\tprintf(\"bulk transfer start, endpoint: %02x\\n\", out->GetAddress());\n\tint tr = 0;\n\tint r = libusb_bulk_transfer(device->GetHandle(), out->GetAddress(), container.Data.data(), container.Data.size(), &tr, 1000);\n\tprintf(\"bulk transfer end %d %d\\n\", r, tr);\n\ttr = data.size();\n\tr = libusb_bulk_transfer(device->GetHandle(), in->GetAddress(), data.data(), data.size(), &tr, 3000);\n\t\/\/r = libusb_interrupt_transfer(device->GetHandle(), interrupt->GetAddress(), data.data(), data.size(), &tr, 2000);\n\tprintf(\"bulk transfer end %d %d\\n\", r, tr);\n#endif\n\tlibusb_release_interface(device->GetHandle(), interface->GetIndex());\n\n\treturn 0;\n}\n<commit_msg>removed all configuration changes<commit_after>#include <stdio.h>\n#include <sstream>\n#include <stdexcept>\n\n#include <mtp\/usb\/Context.h>\n#include <mtp\/usb\/call.h>\n#include <mtp\/ptp\/OperationRequest.h>\n#include <mtp\/ptp\/Container.h>\n\nstatic void callback(struct libusb_transfer *transfer)\n{\n\tprintf(\"CALLBACK, status: %d\\n\", transfer->status);\n\tfor(int i = 0; i < transfer->actual_length; ++i)\n\t\tprintf(\"%02x \", transfer->buffer[i]);\n\tprintf(\"\\n\");\n}\n\nint main(int argc, char **argv)\n{\n\tusing namespace mtp;\n\tusb::Context ctx;\n\tusb::DeviceDescriptorPtr desc;\n\tfor (usb::DeviceDescriptorPtr dd : ctx.GetDevices())\n\t{\n\t\tif (dd->GetVendorId() == 0x18d1)\n\t\t{\n\t\t\tdesc = dd;\n\t\t\tbreak;\n\t\t}\n\t}\n\tif (!desc)\n\t\tthrow std::runtime_error(\"no mtp device found\");\n\n\tusb::DevicePtr device = desc->Open();\n\tint confs = desc->GetConfigurationsCount();\n\tprintf(\"configurations: %d\\n\", confs);\n\n\tint mtp_configuration = -1;\n\tint mtp_interface = -1;\n\n\tusb::ConfigurationPtr\t\tconfiguration;\n\tusb::InterfacePtr\t\t\tinterface;\n\n\tfor(int i = 0; i < confs; ++i)\n\t{\n\t\tusb::ConfigurationPtr conf = desc->GetConfiguration(i);\n\t\tint interfaces = conf->GetInterfaceCount();\n\t\tprintf(\"interfaces: %d\\n\", interfaces);\n\t\tfor(int j = 0; j < interfaces; ++j)\n\t\t{\n\t\t\tusb::InterfacePtr iface = conf->GetInterface(j, 0);\n\t\t\tprintf(\"%d:%d index %u, eps %u\\n\", i, j, iface->GetIndex(), iface->GetEndpointsCount());\n\t\t\tint name_idx = iface->GetNameIndex();\n\t\t\tif (!name_idx)\n\t\t\t\tcontinue;\n\t\t\tstd::string name = device->GetString(name_idx);\n\t\t\tif (name == \"MTP\")\n\t\t\t{\n\t\t\t\tconfiguration = conf;\n\t\t\t\tinterface = iface;\n\t\t\t\tmtp_configuration = i;\n\t\t\t\tmtp_interface = j;\n\t\t\t\ti = confs;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\n\tif (!interface || mtp_interface < 0 || mtp_configuration < 0)\n\t\tthrow std::runtime_error(\"no mtp interface found\");\n\n\t\/\/device->SetConfiguration(configuration->GetIndex());\n\tint epn = interface->GetEndpointsCount();\n\n\tusb::EndpointPtr out, in, interrupt;\n\tprintf(\"endpoints: %d\\n\", epn);\n\tfor(int i = 0; i < epn; ++i)\n\t{\n\t\tusb::EndpointPtr ep = interface->GetEndpoint(i);\n\t\tprintf(\"endpoint: %d: %02x\\n\", i, ep->GetAddress());\n\t\t\/\/check for bulk here\n\t\tif (ep->GetDirection() == usb::EndpointDirection::Out)\n\t\t{\n\t\t\tif (ep->GetType() == usb::EndpointType::Bulk)\n\t\t\t{\n\t\t\t\tprintf(\"OUT\\n\");\n\t\t\t\tout = ep;\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif (ep->GetType() == usb::EndpointType::Bulk)\n\t\t\t{\n\t\t\t\tprintf(\"IN\\n\");\n\t\t\t\tin = ep;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tprintf(\"INTERRUPT\\n\");\n\t\t\t\tinterrupt = ep;\n\t\t\t}\n\t\t}\n\t}\n\tif (!in || !out || !interrupt)\n\t\tthrow std::runtime_error(\"invalid endpoint\");\n\n\t\/\/USB_CALL(libusb_reset_device(device->GetHandle()));\n\n\tprintf(\"claiming interface %d...\\n\", interface->GetIndex());\n\t\/\/USB_CALL(libusb_claim_interface(device->GetHandle(), interface->GetIndex()));\n\tprintf(\"claimed interface\\n\");\n\t\/\/USB_CALL(libusb_set_interface_alt_setting(device->GetHandle(), mtp_interface, 0));\n\n\t\/\/OperationRequest req(OperationCode::OpenSession, 0, 1);\n\tOperationRequest req(OperationCode::GetDeviceInfo, 0, 0);\n\tContainer container(req);\n\n\t\/*\n\tfor(size_t i = 0; i < container.Data.size(); ++i)\n\t\tprintf(\"%02x \", container.Data[i]);\n\tprintf(\"\\n\");\n\t*\/\n\n\tlibusb_clear_halt(device->GetHandle(), out->GetAddress());\n\tlibusb_clear_halt(device->GetHandle(), in->GetAddress());\n\n\tstd::vector<u8> data(in->GetMaxPacketSize());\n\t\/\/std::vector<u8> data(64);\n#if 0\n\tlibusb_transfer *transfer_out = libusb_alloc_transfer(0);\n\t\/\/transfer_out->flags |= LIBUSB_TRANSFER_ADD_ZERO_PACKET | LIBUSB_TRANSFER_SHORT_NOT_OK;\n\tprintf(\"data size: %u\\n\", (unsigned)container.Data.size());\n\tlibusb_fill_bulk_transfer(transfer_out, device->GetHandle(), out->GetAddress(), container.Data.data(), container.Data.size(), &callback, 0, 3000);\n\tUSB_CALL(libusb_submit_transfer(transfer_out));\n\t{\n\t\tctx.Wait();\n\t\tprintf(\"WAIT COMPLETED\\n\");\n\t}\n\n\t\/\/libusb_free_transfer(transfer_out);\n\tlibusb_transfer *transfer_in = libusb_alloc_transfer(0);\n\tlibusb_fill_bulk_transfer(transfer_in, device->GetHandle(), in->GetAddress(), data.data(), data.size(), &callback, 0, 3000);\n\tUSB_CALL(libusb_submit_transfer(transfer_in));\n\n\n\t{\n\t\tctx.Wait();\n\t\tprintf(\"WAIT COMPLETED\\n\");\n\t}\n\n#else\n\tprintf(\"bulk transfer start, endpoint: %02x\\n\", out->GetAddress());\n\tint tr = 0;\n\tint r = libusb_bulk_transfer(device->GetHandle(), out->GetAddress(), container.Data.data(), container.Data.size(), &tr, 1000);\n\tprintf(\"bulk transfer end %d %d\\n\", r, tr);\n\ttr = data.size();\n\tr = libusb_bulk_transfer(device->GetHandle(), in->GetAddress(), data.data(), data.size(), &tr, 3000);\n\t\/\/r = libusb_interrupt_transfer(device->GetHandle(), interrupt->GetAddress(), data.data(), data.size(), &tr, 2000);\n\tprintf(\"bulk transfer end %d %d\\n\", r, tr);\n#endif\n\tlibusb_release_interface(device->GetHandle(), interface->GetIndex());\n\n\treturn 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n Copyright (c) Mario Garcia, under MIT license. Like anyone is going to use this shit anyway...\n*\/\n#ifndef __VIKR_MATRIX_H\n#define __VIKR_MATRIX_H\n\n#include <vikr\/platform\/vikr_api.hpp>\n#include <vikr\/math\/alg\/vect.hpp>\n\n\nnamespace vikr {\nnamespace math {\n\ntemplate<typename _Value = float>\nclass Matrix2 {\npublic:\nprivate:\n _Value mat[2][2];\n};\n\n\ntemplate<typename _Value = float >\nclass Matrix3 {\npublic:\n Matrix3();\nprivate:\n _Value mat[3][3];\n};\n\n\ntemplate<typename _Value = float>\nclass Matrix4 {\n VIKR_DISALLOW_COPY_AND_ASSIGN(Matrix4<_Value>);\npublic:\n VIKR_DEFAULT_MOVE_AND_ASSIGN(Matrix4<_Value>);\n \n Matrix4(\n Vector4<_Value> &row1, \n Vector4<_Value> &row2, \n Vector4<_Value> &row3, \n Vector4<_Value> &row4) \n {\n mat[0][0] = row1.x; mat[1][0] = row1.y; mat[2][0] = row1.z; mat[3][0] = row1.w;\n mat[0][1] = row2.x; mat[1][1] = row2.y; mat[2][1] = row2.z; mat[3][1] = row2.w;\n mat[0][2] = row3.x; mat[1][2] = row3.y; mat[2][2] = row3.z; mat[3][2] = row3.w;\n mat[0][3] = row4.x; mat[1][3] = row4.y; mat[2][3] = row4.z; mat[3][3] = row4.w;\n }\n\n \n \/**\n Initialize Column-Major format.\n *\/\n Matrix4(\n _Value a00, _Value a01, _Value a02, _Value a03,\n _Value a10, _Value a11, _Value a12, _Value a13,\n _Value a20, _Value a21, _Value a22, _Value a23,\n _Value a30, _Value a31, _Value a32, _Value a33) \n {\n mat[0][0] = a00; mat[1][0] = a10; mat[2][0] = a20; mat[3][0] = a30;\n mat[0][1] = a01; mat[1][1] = a11; mat[2][1] = a21; mat[3][1] = a31;\n mat[0][2] = a02; mat[1][2] = a12; mat[2][2] = a22; mat[3][2] = a32;\n mat[0][3] = a03; mat[1][3] = a13; mat[2][3] = a23; mat[3][3] = a33;\n }\n \n Matrix4 operator+(Matrix4 &mat1) {\n \/\/ Matrix Addition without the need of loop sequence.\n Matrix4 mat_sol;\n mat_sol[0][0] = mat[0][0] + mat1[0][0];\n mat_sol[0][1] = mat[0][1] + mat1[0][1];\n mat_sol[0][2] = mat[0][2] + mat1[0][2];\n mat_sol[0][3] = mat[0][3] + mat1[0][3];\n \n mat_sol[1][0] = mat[1][0] + mat1[1][0];\n mat_sol[1][1] = mat[1][1] + mat1[1][1];\n mat_sol[1][2] = mat[1][2] + mat1[1][2];\n mat_sol[1][3] = mat[1][3] + mat1[1][3];\n \n mat_sol[2][0] = mat[2][0] + mat1[2][0];\n mat_sol[2][1] = mat[2][1] + mat1[2][1];\n mat_sol[2][2] = mat[2][2] + mat1[2][2];\n mat_sol[2][3] = mat[2][3] + mat1[2][3];\n \n mat_sol[3][0] = mat[3][0] + mat1[3][0];\n mat_sol[3][1] = mat[3][1] + mat1[3][1];\n mat_sol[3][2] = mat[3][2] + mat1[3][2];\n mat_sol[3][3] = mat[3][3] + mat1[3][3];\n return mat_sol;\n }\n\n\n Matrix4 operator-(Matrix4 &mat1) {\n Matrix4 mat_ans;\n mat_ans[0][0] = mat[0][0] - mat1[0][0];\n mat_ans[0][1] = mat[0][1] - mat1[0][1];\n mat_ans[0][2] = mat[0][2] - mat1[0][2];\n mat_ans[0][3] = mat[0][3] - mat1[0][3];\n\n mat_ans[1][0] = mat[1][0] - mat1[1][0];\n mat_ans[1][1] = mat[1][1] - mat1[1][1];\n mat_ans[1][2] = mat[1][2] - mat1[1][2];\n mat_ans[1][3] = mat[1][3] - mat1[1][3];\n\n mat_ans[2][0] = mat[2][0] - mat1[2][0];\n mat_ans[2][1] = mat[2][1] - mat1[2][1];\n mat_ans[2][2] = mat[2][2] - mat1[2][2];\n mat_ans[2][3] = mat[2][3] - mat1[2][3];\n\n mat_ans[3][0] = mat[3][0] - mat1[3][0];\n mat_ans[3][1] = mat[3][1] - mat1[3][1];\n mat_ans[3][2] = mat[3][1] - mat1[3][2];\n mat_ans[3][3] = mat[3][1] - mat1[3][3];\n return mat_ans;\n }\n\n\n Matrix4& operator*(Matrix4& matrix) {\n \n }\n\n _Value& operator[](unsigned int index) {\n return mat[index];\n }\n\nprivate:\n\n \/\/ Col-Major matrix.\n \/\/ mat[col][row]\n \/\/ \n \/\/ example.\n \/\/ 0 1 2 3\n \/\/ 0 | 1 5 9 13 | mat[0][0] = 1 mat[1][0] = 5 mat[2][0] = 9 mat[3][0] = 13 \n \/\/ 1 | 2 6 10 14 | mat[0][1] = 2 mat[1][1] = 6 mat[2][1] = 10 mat[3][1] = 14\n \/\/ 2 | 3 7 11 15 | mat[0][2] = 3 mat[1][2] = 7 mat[2][2] = 11 mat[3][2] = 15\n \/\/ 3 | 4 8 12 16 | mat[0][3] = 4 mat[1][3] = 8 mat[2][3] = 12 mat[3][3] = 16\n _Value mat[4][4];\n};\n} \/\/ math\n} \/\/ vikr\n#endif \/\/ __VIKR_MATRIX_H<commit_msg>shift params for matrix4<commit_after>\/*\n Copyright (c) Mario Garcia, under MIT license. Like anyone is going to use this shit anyway...\n*\/\n#ifndef __VIKR_MATRIX_H\n#define __VIKR_MATRIX_H\n\n#include <vikr\/platform\/vikr_api.hpp>\n#include <vikr\/math\/alg\/vect.hpp>\n\n\nnamespace vikr {\nnamespace math {\n\ntemplate<typename _Value = float>\nclass Matrix2 {\npublic:\nprivate:\n _Value mat[2][2];\n};\n\n\ntemplate<typename _Value = float >\nclass Matrix3 {\npublic:\n Matrix3();\nprivate:\n _Value mat[3][3];\n};\n\n\ntemplate<typename _Value = float>\nclass Matrix4 {\n VIKR_DISALLOW_COPY_AND_ASSIGN(Matrix4<_Value>);\npublic:\n VIKR_DEFAULT_MOVE_AND_ASSIGN(Matrix4<_Value>);\n \n Matrix4(\n Vector4<_Value> &row1, \n Vector4<_Value> &row2, \n Vector4<_Value> &row3, \n Vector4<_Value> &row4) \n {\n mat[0][0] = row1.x; mat[1][0] = row1.y; mat[2][0] = row1.z; mat[3][0] = row1.w;\n mat[0][1] = row2.x; mat[1][1] = row2.y; mat[2][1] = row2.z; mat[3][1] = row2.w;\n mat[0][2] = row3.x; mat[1][2] = row3.y; mat[2][2] = row3.z; mat[3][2] = row3.w;\n mat[0][3] = row4.x; mat[1][3] = row4.y; mat[2][3] = row4.z; mat[3][3] = row4.w;\n }\n\n \n \/**\n Initialize Column-Major format.\n *\/\n Matrix4(\n _Value a00, _Value a10, _Value a20, _Value a30,\n _Value a01, _Value a11, _Value a21, _Value a31,\n _Value a02, _Value a12, _Value a22, _Value a32,\n _Value a03, _Value a13, _Value a23, _Value a33) \n {\n mat[0][0] = a00; mat[1][0] = a10; mat[2][0] = a20; mat[3][0] = a30;\n mat[0][1] = a01; mat[1][1] = a11; mat[2][1] = a21; mat[3][1] = a31;\n mat[0][2] = a02; mat[1][2] = a12; mat[2][2] = a22; mat[3][2] = a32;\n mat[0][3] = a03; mat[1][3] = a13; mat[2][3] = a23; mat[3][3] = a33;\n }\n \n Matrix4 operator+(Matrix4 &mat1) {\n \/\/ Matrix Addition without the need of loop sequence.\n Matrix4 mat_sol;\n mat_sol[0][0] = mat[0][0] + mat1[0][0];\n mat_sol[0][1] = mat[0][1] + mat1[0][1];\n mat_sol[0][2] = mat[0][2] + mat1[0][2];\n mat_sol[0][3] = mat[0][3] + mat1[0][3];\n \n mat_sol[1][0] = mat[1][0] + mat1[1][0];\n mat_sol[1][1] = mat[1][1] + mat1[1][1];\n mat_sol[1][2] = mat[1][2] + mat1[1][2];\n mat_sol[1][3] = mat[1][3] + mat1[1][3];\n \n mat_sol[2][0] = mat[2][0] + mat1[2][0];\n mat_sol[2][1] = mat[2][1] + mat1[2][1];\n mat_sol[2][2] = mat[2][2] + mat1[2][2];\n mat_sol[2][3] = mat[2][3] + mat1[2][3];\n \n mat_sol[3][0] = mat[3][0] + mat1[3][0];\n mat_sol[3][1] = mat[3][1] + mat1[3][1];\n mat_sol[3][2] = mat[3][2] + mat1[3][2];\n mat_sol[3][3] = mat[3][3] + mat1[3][3];\n return mat_sol;\n }\n\n\n Matrix4 operator-(Matrix4 &mat1) {\n Matrix4 mat_ans;\n mat_ans[0][0] = mat[0][0] - mat1[0][0];\n mat_ans[0][1] = mat[0][1] - mat1[0][1];\n mat_ans[0][2] = mat[0][2] - mat1[0][2];\n mat_ans[0][3] = mat[0][3] - mat1[0][3];\n\n mat_ans[1][0] = mat[1][0] - mat1[1][0];\n mat_ans[1][1] = mat[1][1] - mat1[1][1];\n mat_ans[1][2] = mat[1][2] - mat1[1][2];\n mat_ans[1][3] = mat[1][3] - mat1[1][3];\n\n mat_ans[2][0] = mat[2][0] - mat1[2][0];\n mat_ans[2][1] = mat[2][1] - mat1[2][1];\n mat_ans[2][2] = mat[2][2] - mat1[2][2];\n mat_ans[2][3] = mat[2][3] - mat1[2][3];\n\n mat_ans[3][0] = mat[3][0] - mat1[3][0];\n mat_ans[3][1] = mat[3][1] - mat1[3][1];\n mat_ans[3][2] = mat[3][1] - mat1[3][2];\n mat_ans[3][3] = mat[3][1] - mat1[3][3];\n return mat_ans;\n }\n\n\n Matrix4& operator*(Matrix4& matrix) {\n \n }\n\n _Value& operator[](unsigned int index) {\n return mat[index];\n }\n\nprivate:\n\n \/\/ Col-Major matrix.\n \/\/ mat[col][row]\n \/\/ \n \/\/ example.\n \/\/ 0 1 2 3\n \/\/ 0 | 1 5 9 13 | mat[0][0] = 1 mat[1][0] = 5 mat[2][0] = 9 mat[3][0] = 13 \n \/\/ 1 | 2 6 10 14 | mat[0][1] = 2 mat[1][1] = 6 mat[2][1] = 10 mat[3][1] = 14\n \/\/ 2 | 3 7 11 15 | mat[0][2] = 3 mat[1][2] = 7 mat[2][2] = 11 mat[3][2] = 15\n \/\/ 3 | 4 8 12 16 | mat[0][3] = 4 mat[1][3] = 8 mat[2][3] = 12 mat[3][3] = 16\n _Value mat[4][4];\n};\n} \/\/ math\n} \/\/ vikr\n#endif \/\/ __VIKR_MATRIX_H<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\/\n\/* fbx_skeleton.cpp *\/\n\/*************************************************************************\/\n\/* This file is part of: *\/\n\/* GODOT ENGINE *\/\n\/* https:\/\/godotengine.org *\/\n\/*************************************************************************\/\n\/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. *\/\n\/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). *\/\n\/* *\/\n\/* Permission is hereby granted, free of charge, to any person obtaining *\/\n\/* a copy of this software and associated documentation files (the *\/\n\/* \"Software\"), to deal in the Software without restriction, including *\/\n\/* without limitation the rights to use, copy, modify, merge, publish, *\/\n\/* distribute, sublicense, and\/or sell copies of the Software, and to *\/\n\/* permit persons to whom the Software is furnished to do so, subject to *\/\n\/* the following conditions: *\/\n\/* *\/\n\/* The above copyright notice and this permission notice shall be *\/\n\/* included in all copies or substantial portions of the Software. *\/\n\/* *\/\n\/* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, *\/\n\/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF *\/\n\/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*\/\n\/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY *\/\n\/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, *\/\n\/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE *\/\n\/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *\/\n\/*************************************************************************\/\n\n#include \"fbx_skeleton.h\"\n\n#include \"import_state.h\"\n\n#include \"tools\/import_utils.h\"\n\nvoid FBXSkeleton::init_skeleton(const ImportState &state) {\n\tint skeleton_bone_count = skeleton_bones.size();\n\n\tif (skeleton == nullptr && skeleton_bone_count > 0) {\n\t\tskeleton = memnew(Skeleton3D);\n\n\t\tif (fbx_node.is_valid()) {\n\t\t\t\/\/ cache skeleton attachment for later during node creation\n\t\t\t\/\/ can't be done until after node hierarchy is built\n\t\t\tif (fbx_node->godot_node != state.root) {\n\t\t\t\tfbx_node->skeleton_node = Ref<FBXSkeleton>(this);\n\t\t\t\tprint_verbose(\"cached armature skeleton attachment for node \" + fbx_node->node_name);\n\t\t\t} else {\n\t\t\t\t\/\/ root node must never be a skeleton to prevent cyclic skeletons from being allowed (skeleton in a skeleton)\n\t\t\t\tfbx_node->godot_node->add_child(skeleton);\n\t\t\t\tskeleton->set_owner(state.root_owner);\n\t\t\t\tskeleton->set_name(\"Skeleton3D\");\n\t\t\t\tprint_verbose(\"created armature skeleton for root\");\n\t\t\t}\n\t\t} else {\n\t\t\tmemfree(skeleton);\n\t\t\tskeleton = nullptr;\n\t\t\tprint_error(\"[doc] skeleton has no valid node to parent nodes to - erasing\");\n\t\t\tskeleton_bones.clear();\n\t\t\treturn;\n\t\t}\n\t}\n\n\t\/\/ Make the bone name uniques.\n\tfor (int x = 0; x < skeleton_bone_count; x++) {\n\t\tRef<FBXBone> bone = skeleton_bones[x];\n\t\tif (bone.is_valid()) {\n\t\t\t\/\/ Make sure the bone name is unique.\n\t\t\tconst String bone_name = bone->bone_name;\n\t\t\tint same_name_count = 0;\n\t\t\tfor (int y = x; y < skeleton_bone_count; y++) {\n\t\t\t\tRef<FBXBone> other_bone = skeleton_bones[y];\n\t\t\t\tif (other_bone.is_valid()) {\n\t\t\t\t\tif (other_bone->bone_name == bone_name) {\n\t\t\t\t\t\tsame_name_count += 1;\n\t\t\t\t\t\tother_bone->bone_name += \"_\" + itos(same_name_count);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tMap<int, Ref<FBXBone>> bone_map;\n\t\/\/ implement fbx cluster skin logic here this is where it goes\n\tint bone_count = 0;\n\tfor (int x = 0; x < skeleton_bone_count; x++) {\n\t\tRef<FBXBone> bone = skeleton_bones[x];\n\t\tif (bone.is_valid()) {\n\t\t\tskeleton->add_bone(bone->bone_name);\n\t\t\tbone->godot_bone_id = bone_count;\n\t\t\tbone->fbx_skeleton = Ref<FBXSkeleton>(this);\n\t\t\tbone_map.insert(bone_count, bone);\n\t\t\tprint_verbose(\"added bone \" + itos(bone->bone_id) + \" \" + bone->bone_name);\n\t\t\tbone_count++;\n\t\t}\n\t}\n\n\tERR_FAIL_COND_MSG(skeleton->get_bone_count() != bone_count, \"Not all bones got added, is the file corrupted?\");\n\n\tfor (Map<int, Ref<FBXBone>>::Element *bone_element = bone_map.front(); bone_element; bone_element = bone_element->next()) {\n\t\tconst Ref<FBXBone> bone = bone_element->value();\n\t\tint bone_index = bone_element->key();\n\t\tprint_verbose(\"working on bone: \" + itos(bone_index) + \" bone name:\" + bone->bone_name);\n\n\t\tskeleton->set_bone_rest(bone->godot_bone_id, get_unscaled_transform(bone->node->pivot_transform->LocalTransform, state.scale));\n\n\t\t\/\/ lookup parent ID\n\t\tif (bone->valid_parent && state.fbx_bone_map.has(bone->parent_bone_id)) {\n\t\t\tRef<FBXBone> parent_bone = state.fbx_bone_map[bone->parent_bone_id];\n\t\t\tint bone_id = skeleton->find_bone(parent_bone->bone_name);\n\t\t\tif (bone_id != -1) {\n\t\t\t\tskeleton->set_bone_parent(bone_index, bone_id);\n\t\t\t} else {\n\t\t\t\tprint_error(\"invalid bone parent: \" + parent_bone->bone_name);\n\t\t\t}\n\t\t} else {\n\t\t\tif (bone->godot_bone_id != -1) {\n\t\t\t\tskeleton->set_bone_parent(bone_index, -1); \/\/ no parent for this bone\n\t\t\t}\n\t\t}\n\t}\n}\n<commit_msg>FBX: Fix first bone getting unnecessary '_1' suffix<commit_after>\/*************************************************************************\/\n\/* fbx_skeleton.cpp *\/\n\/*************************************************************************\/\n\/* This file is part of: *\/\n\/* GODOT ENGINE *\/\n\/* https:\/\/godotengine.org *\/\n\/*************************************************************************\/\n\/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. *\/\n\/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). *\/\n\/* *\/\n\/* Permission is hereby granted, free of charge, to any person obtaining *\/\n\/* a copy of this software and associated documentation files (the *\/\n\/* \"Software\"), to deal in the Software without restriction, including *\/\n\/* without limitation the rights to use, copy, modify, merge, publish, *\/\n\/* distribute, sublicense, and\/or sell copies of the Software, and to *\/\n\/* permit persons to whom the Software is furnished to do so, subject to *\/\n\/* the following conditions: *\/\n\/* *\/\n\/* The above copyright notice and this permission notice shall be *\/\n\/* included in all copies or substantial portions of the Software. *\/\n\/* *\/\n\/* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, *\/\n\/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF *\/\n\/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*\/\n\/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY *\/\n\/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, *\/\n\/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE *\/\n\/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *\/\n\/*************************************************************************\/\n\n#include \"fbx_skeleton.h\"\n\n#include \"import_state.h\"\n\n#include \"tools\/import_utils.h\"\n\nvoid FBXSkeleton::init_skeleton(const ImportState &state) {\n\tint skeleton_bone_count = skeleton_bones.size();\n\n\tif (skeleton == nullptr && skeleton_bone_count > 0) {\n\t\tskeleton = memnew(Skeleton3D);\n\n\t\tif (fbx_node.is_valid()) {\n\t\t\t\/\/ cache skeleton attachment for later during node creation\n\t\t\t\/\/ can't be done until after node hierarchy is built\n\t\t\tif (fbx_node->godot_node != state.root) {\n\t\t\t\tfbx_node->skeleton_node = Ref<FBXSkeleton>(this);\n\t\t\t\tprint_verbose(\"cached armature skeleton attachment for node \" + fbx_node->node_name);\n\t\t\t} else {\n\t\t\t\t\/\/ root node must never be a skeleton to prevent cyclic skeletons from being allowed (skeleton in a skeleton)\n\t\t\t\tfbx_node->godot_node->add_child(skeleton);\n\t\t\t\tskeleton->set_owner(state.root_owner);\n\t\t\t\tskeleton->set_name(\"Skeleton3D\");\n\t\t\t\tprint_verbose(\"created armature skeleton for root\");\n\t\t\t}\n\t\t} else {\n\t\t\tmemfree(skeleton);\n\t\t\tskeleton = nullptr;\n\t\t\tprint_error(\"[doc] skeleton has no valid node to parent nodes to - erasing\");\n\t\t\tskeleton_bones.clear();\n\t\t\treturn;\n\t\t}\n\t}\n\n\t\/\/ Make the bone name uniques.\n\tfor (int x = 0; x < skeleton_bone_count; x++) {\n\t\tRef<FBXBone> bone = skeleton_bones[x];\n\t\tif (bone.is_valid()) {\n\t\t\t\/\/ Make sure the bone name is unique.\n\t\t\tconst String bone_name = bone->bone_name;\n\t\t\tint same_name_count = 0;\n\t\t\tfor (int y = x + 1; y < skeleton_bone_count; y++) {\n\t\t\t\tRef<FBXBone> other_bone = skeleton_bones[y];\n\t\t\t\tif (other_bone.is_valid()) {\n\t\t\t\t\tif (other_bone->bone_name == bone_name) {\n\t\t\t\t\t\tsame_name_count += 1;\n\t\t\t\t\t\tother_bone->bone_name += \"_\" + itos(same_name_count);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tMap<int, Ref<FBXBone>> bone_map;\n\t\/\/ implement fbx cluster skin logic here this is where it goes\n\tint bone_count = 0;\n\tfor (int x = 0; x < skeleton_bone_count; x++) {\n\t\tRef<FBXBone> bone = skeleton_bones[x];\n\t\tif (bone.is_valid()) {\n\t\t\tskeleton->add_bone(bone->bone_name);\n\t\t\tbone->godot_bone_id = bone_count;\n\t\t\tbone->fbx_skeleton = Ref<FBXSkeleton>(this);\n\t\t\tbone_map.insert(bone_count, bone);\n\t\t\tprint_verbose(\"added bone \" + itos(bone->bone_id) + \" \" + bone->bone_name);\n\t\t\tbone_count++;\n\t\t}\n\t}\n\n\tERR_FAIL_COND_MSG(skeleton->get_bone_count() != bone_count, \"Not all bones got added, is the file corrupted?\");\n\n\tfor (Map<int, Ref<FBXBone>>::Element *bone_element = bone_map.front(); bone_element; bone_element = bone_element->next()) {\n\t\tconst Ref<FBXBone> bone = bone_element->value();\n\t\tint bone_index = bone_element->key();\n\t\tprint_verbose(\"working on bone: \" + itos(bone_index) + \" bone name:\" + bone->bone_name);\n\n\t\tskeleton->set_bone_rest(bone->godot_bone_id, get_unscaled_transform(bone->node->pivot_transform->LocalTransform, state.scale));\n\n\t\t\/\/ lookup parent ID\n\t\tif (bone->valid_parent && state.fbx_bone_map.has(bone->parent_bone_id)) {\n\t\t\tRef<FBXBone> parent_bone = state.fbx_bone_map[bone->parent_bone_id];\n\t\t\tint bone_id = skeleton->find_bone(parent_bone->bone_name);\n\t\t\tif (bone_id != -1) {\n\t\t\t\tskeleton->set_bone_parent(bone_index, bone_id);\n\t\t\t} else {\n\t\t\t\tprint_error(\"invalid bone parent: \" + parent_bone->bone_name);\n\t\t\t}\n\t\t} else {\n\t\t\tif (bone->godot_bone_id != -1) {\n\t\t\t\tskeleton->set_bone_parent(bone_index, -1); \/\/ no parent for this bone\n\t\t\t}\n\t\t}\n\t}\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"test.h\"\n#include \"Constants.h\"\n#include \"Configuration.h\"\n#include \"FilesystemInclude.h\"\n#include \"FstreamInclude.h\"\n\nTEST(NoConfigurationFile)\n{\n const filesystem::path tempDir = filesystem::unique_path(filesystem::temp_directory_path() \/ \"%%%%%-%%%%%\");\n ASSERT(filesystem::create_directories(tempDir));\n const filesystem::path curDir = filesystem::current_path();\n filesystem::current_path(tempDir);\n\n Configuration config;\n ASSERT(config.companyName == \"YourCompany\");\n ASSERT(config.regenTag == \"GENERATED BY CPP-DEPENDENCIES\");\n ASSERT(config.versionUsed == CURRENT_VERSION);\n ASSERT(config.cycleColor == \"orange\");\n ASSERT(config.publicDepColor == \"blue\");\n ASSERT(config.privateDepColor == \"lightblue\");\n ASSERT(config.componentLinkLimit == 30);\n ASSERT(config.componentLocLowerLimit == 200);\n ASSERT(config.componentLocUpperLimit == 20000);\n ASSERT(config.fileLocUpperLimit == 2000);\n ASSERT(config.addLibraryAliases.size() == 1);\n ASSERT(config.addLibraryAliases.count(\"add_library\") == 1);\n ASSERT(config.addExecutableAliases.size() == 1);\n ASSERT(config.addExecutableAliases.count(\"add_executable\") == 1);\n\n filesystem::current_path(curDir);\n}\n\nTEST(ReadConfigurationFile)\n{\n const filesystem::path tempDir = filesystem::unique_path(filesystem::temp_directory_path() \/ \"%%%%%-%%%%%\");\n ASSERT(filesystem::create_directories(tempDir));\n const filesystem::path curDir = filesystem::current_path();\n filesystem::current_path(tempDir);\n\n streams::ofstream out(CONFIG_FILE);\n out << \"versionUsed: 3\\n\"\n << \"companyName: MyCompany\\n\"\n << \"regenTag: MY_REGEN_TAG\\n\"\n << \"cycleColor: brown\\n\"\n << \"publicDepColor: black\\n\"\n << \"privateDepColor: grey\\n\"\n << \"componentLinkLimit: 2\\n\"\n << \"componentLocLowerLimit: 1\\n\"\n << \"componentLocUpperLimit: 123\\n\"\n << \"fileLocUpperLimit: 567\\n\";\n out.close();\n\n Configuration config;\n ASSERT(config.companyName == \"MyCompany\");\n ASSERT(config.regenTag == \"MY_REGEN_TAG\");\n ASSERT(config.versionUsed == \"3\");\n ASSERT(config.cycleColor == \"brown\");\n ASSERT(config.publicDepColor == \"black\");\n ASSERT(config.privateDepColor == \"grey\");\n ASSERT(config.componentLinkLimit == 2);\n ASSERT(config.componentLocLowerLimit == 1);\n ASSERT(config.componentLocUpperLimit == 123);\n ASSERT(config.fileLocUpperLimit == 567);\n ASSERT(config.addLibraryAliases.size() == 1);\n ASSERT(config.addLibraryAliases.count(\"add_library\") == 1);\n ASSERT(config.addExecutableAliases.size() == 1);\n ASSERT(config.addExecutableAliases.count(\"add_executable\") == 1);\n\n filesystem::current_path(curDir);\n}\n\nTEST(ReadConfigurationFile_Aliases)\n{\n const filesystem::path tempDir = filesystem::unique_path(filesystem::temp_directory_path() \/ \"%%%%%-%%%%%\");\n ASSERT(filesystem::create_directories(tempDir));\n const filesystem::path curDir = filesystem::current_path();\n filesystem::current_path(tempDir);\n\n streams::ofstream out(CONFIG_FILE);\n out << \"addLibraryAlias: add_special_library\\n\"\n << \"addLibraryAlias: add_test_lib\\n\"\n << \"addExecutableAlias: add_special_exe\\n\"\n << \"addExecutableAlias: add_test\\n\";\n out.close();\n\n Configuration config;\n ASSERT(config.addLibraryAliases.size() == 3);\n ASSERT(config.addLibraryAliases.count(\"add_library\") == 1);\n ASSERT(config.addLibraryAliases.count(\"add_special_library\") == 1);\n ASSERT(config.addLibraryAliases.count(\"add_test_lib\") == 1);\n\n ASSERT(config.addExecutableAliases.size() == 3);\n ASSERT(config.addExecutableAliases.count(\"add_executable\") == 1);\n ASSERT(config.addExecutableAliases.count(\"add_special_exe\") == 1);\n ASSERT(config.addExecutableAliases.count(\"add_test\") == 1);\n\n filesystem::current_path(curDir);\n}\n<commit_msg>Put writing to out file in separate scope.<commit_after>#include \"test.h\"\n#include \"Constants.h\"\n#include \"Configuration.h\"\n#include \"FilesystemInclude.h\"\n#include \"FstreamInclude.h\"\n\nTEST(NoConfigurationFile)\n{\n const filesystem::path tempDir = filesystem::unique_path(filesystem::temp_directory_path() \/ \"%%%%%-%%%%%\");\n ASSERT(filesystem::create_directories(tempDir));\n const filesystem::path curDir = filesystem::current_path();\n filesystem::current_path(tempDir);\n\n Configuration config;\n ASSERT(config.companyName == \"YourCompany\");\n ASSERT(config.regenTag == \"GENERATED BY CPP-DEPENDENCIES\");\n ASSERT(config.versionUsed == CURRENT_VERSION);\n ASSERT(config.cycleColor == \"orange\");\n ASSERT(config.publicDepColor == \"blue\");\n ASSERT(config.privateDepColor == \"lightblue\");\n ASSERT(config.componentLinkLimit == 30);\n ASSERT(config.componentLocLowerLimit == 200);\n ASSERT(config.componentLocUpperLimit == 20000);\n ASSERT(config.fileLocUpperLimit == 2000);\n ASSERT(config.addLibraryAliases.size() == 1);\n ASSERT(config.addLibraryAliases.count(\"add_library\") == 1);\n ASSERT(config.addExecutableAliases.size() == 1);\n ASSERT(config.addExecutableAliases.count(\"add_executable\") == 1);\n\n filesystem::current_path(curDir);\n}\n\nTEST(ReadConfigurationFile)\n{\n const filesystem::path tempDir = filesystem::unique_path(filesystem::temp_directory_path() \/ \"%%%%%-%%%%%\");\n ASSERT(filesystem::create_directories(tempDir));\n const filesystem::path curDir = filesystem::current_path();\n filesystem::current_path(tempDir);\n\n {\n streams::ofstream out(CONFIG_FILE);\n out << \"versionUsed: 3\\n\"\n << \"companyName: MyCompany\\n\"\n << \"regenTag: MY_REGEN_TAG\\n\"\n << \"cycleColor: brown\\n\"\n << \"publicDepColor: black\\n\"\n << \"privateDepColor: grey\\n\"\n << \"componentLinkLimit: 2\\n\"\n << \"componentLocLowerLimit: 1\\n\"\n << \"componentLocUpperLimit: 123\\n\"\n << \"fileLocUpperLimit: 567\\n\";\n }\n\n Configuration config;\n ASSERT(config.companyName == \"MyCompany\");\n ASSERT(config.regenTag == \"MY_REGEN_TAG\");\n ASSERT(config.versionUsed == \"3\");\n ASSERT(config.cycleColor == \"brown\");\n ASSERT(config.publicDepColor == \"black\");\n ASSERT(config.privateDepColor == \"grey\");\n ASSERT(config.componentLinkLimit == 2);\n ASSERT(config.componentLocLowerLimit == 1);\n ASSERT(config.componentLocUpperLimit == 123);\n ASSERT(config.fileLocUpperLimit == 567);\n ASSERT(config.addLibraryAliases.size() == 1);\n ASSERT(config.addLibraryAliases.count(\"add_library\") == 1);\n ASSERT(config.addExecutableAliases.size() == 1);\n ASSERT(config.addExecutableAliases.count(\"add_executable\") == 1);\n\n filesystem::current_path(curDir);\n}\n\nTEST(ReadConfigurationFile_Aliases)\n{\n const filesystem::path tempDir = filesystem::unique_path(filesystem::temp_directory_path() \/ \"%%%%%-%%%%%\");\n ASSERT(filesystem::create_directories(tempDir));\n const filesystem::path curDir = filesystem::current_path();\n filesystem::current_path(tempDir);\n\n {\n streams::ofstream out(CONFIG_FILE);\n out << \"addLibraryAlias: add_special_library\\n\"\n << \"addLibraryAlias: add_test_lib\\n\"\n << \"addExecutableAlias: add_special_exe\\n\"\n << \"addExecutableAlias: add_test\\n\";\n }\n\n Configuration config;\n ASSERT(config.addLibraryAliases.size() == 3);\n ASSERT(config.addLibraryAliases.count(\"add_library\") == 1);\n ASSERT(config.addLibraryAliases.count(\"add_special_library\") == 1);\n ASSERT(config.addLibraryAliases.count(\"add_test_lib\") == 1);\n\n ASSERT(config.addExecutableAliases.size() == 3);\n ASSERT(config.addExecutableAliases.count(\"add_executable\") == 1);\n ASSERT(config.addExecutableAliases.count(\"add_special_exe\") == 1);\n ASSERT(config.addExecutableAliases.count(\"add_test\") == 1);\n\n filesystem::current_path(curDir);\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright 2014 Matthew Harvey\n * \n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * \n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"reporting_command.hpp\"\n#include \"command.hpp\"\n#include \"config.hpp\"\n#include \"csv_list_report_writer.hpp\"\n#include \"csv_summary_report_writer.hpp\"\n#include \"help_line.hpp\"\n#include \"human_list_report_writer.hpp\"\n#include \"human_summary_report_writer.hpp\"\n#include \"list_report_writer.hpp\"\n#include \"placeholder.hpp\"\n#include \"string_utilities.hpp\"\n#include \"summary_report_writer.hpp\"\n#include \"time_log.hpp\"\n#include <iostream>\n#include <memory>\n#include <ostream>\n#include <string>\n#include <vector>\n\nusing std::endl;\nusing std::ostream;\nusing std::string;\nusing std::unique_ptr;\nusing std::vector;\n\nnamespace swx\n{\n\nReportingCommand::ReportingCommand\n( string const& p_command_word,\n vector<string> const& p_aliases,\n string const& p_usage_summary,\n vector<HelpLine> const& p_help_line,\n TimeLog& p_time_log\n):\n Command(p_command_word, p_aliases, p_usage_summary, p_help_line),\n m_time_log(p_time_log)\n{\n add_option\n ( 'r',\n \"Treat ACTIVITY as a (POSIX extended) regular expression, and include \"\n \"all activities that match it\",\n &m_use_regex\n );\n add_option\n ( 'l',\n \"Instead of printing a summary, print a date-ordered list of \"\n \"individual activity stints during the relevant period\",\n &m_show_stints\n );\n add_option\n ( 'b',\n \"In addition to any other information, output the earliest time at \"\n \"which each activity was conducted during the relevant period (ignored \"\n \"in list mode)\",\n &m_show_beginning\n );\n add_option\n ( 'e',\n \"Output in a column to the right of any other info, the latest time at \"\n \"which each activity was conducted during the relevant period (ignored \"\n \"in list mode)\",\n &m_show_end\n );\n add_option\n ( 'c',\n \"Output in CSV format\",\n &m_produce_csv\n );\n add_option\n ( 'v',\n \"Instead of printing the summary in \\\"tree\\\" form, print the full name of \"\\\n \"each activity (ignored in list mode or succinct mode)\",\n &m_be_verbose\n );\n add_option\n ( 's',\n \"Succinct output: show grand total only (ignored in list mode)\",\n &m_be_succinct\n );\n}\n\nReportingCommand::~ReportingCommand() = default;\n\nostream&\nReportingCommand::print_report\n( ostream& p_os,\n Config const& p_config,\n vector<string> const& p_activity_components,\n TimePoint const* p_begin,\n TimePoint const* p_end\n)\n{\n unique_ptr<string> activity_ptr;\n if (!p_activity_components.empty())\n {\n auto const expanded = expand_placeholders(p_activity_components, m_time_log);\n activity_ptr.reset(new string(squish(expanded.begin(), expanded.end())));\n }\n auto const stints = \n m_time_log.get_stints(activity_ptr.get(), p_begin, p_end, m_use_regex);\n ReportWriter::Options const options\n ( p_config.output_rounding_numerator(),\n p_config.output_rounding_denominator(),\n p_config.output_precision(),\n p_config.output_width(),\n p_config.formatted_buf_len(),\n p_config.time_format()\n );\n unique_ptr<ReportWriter> report_writer;\n if (m_show_stints)\n {\n if (m_produce_csv)\n {\n report_writer.reset(new CsvListReportWriter(stints, options));\n }\n else\n {\n report_writer.reset(new HumanListReportWriter(stints, options));\n }\n }\n else\n {\n if (m_produce_csv)\n {\n report_writer.reset\n ( new CsvSummaryReportWriter\n ( stints,\n options,\n m_show_beginning,\n m_show_end,\n m_be_succinct\n )\n );\n }\n else\n {\n report_writer.reset\n ( new HumanSummaryReportWriter\n ( stints,\n options,\n m_show_beginning,\n m_show_end,\n !m_be_verbose,\n m_be_succinct\n )\n );\n }\n }\n report_writer->write(p_os);\n return p_os; \n}\n\nbool\nReportingCommand::does_support_placeholders() const\n{\n return true;\n}\n\n} \/\/ namespace swx\n<commit_msg>Fix behaviour of -v option to reporting commands.<commit_after>\/*\n * Copyright 2014 Matthew Harvey\n * \n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * \n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"reporting_command.hpp\"\n#include \"command.hpp\"\n#include \"config.hpp\"\n#include \"csv_list_report_writer.hpp\"\n#include \"csv_summary_report_writer.hpp\"\n#include \"help_line.hpp\"\n#include \"human_list_report_writer.hpp\"\n#include \"human_summary_report_writer.hpp\"\n#include \"list_report_writer.hpp\"\n#include \"placeholder.hpp\"\n#include \"string_utilities.hpp\"\n#include \"summary_report_writer.hpp\"\n#include \"time_log.hpp\"\n#include <iostream>\n#include <memory>\n#include <ostream>\n#include <string>\n#include <vector>\n\nusing std::endl;\nusing std::ostream;\nusing std::string;\nusing std::unique_ptr;\nusing std::vector;\n\nnamespace swx\n{\n\nReportingCommand::ReportingCommand\n( string const& p_command_word,\n vector<string> const& p_aliases,\n string const& p_usage_summary,\n vector<HelpLine> const& p_help_line,\n TimeLog& p_time_log\n):\n Command(p_command_word, p_aliases, p_usage_summary, p_help_line),\n m_time_log(p_time_log)\n{\n add_option\n ( 'r',\n \"Treat ACTIVITY as a (POSIX extended) regular expression, and include \"\n \"all activities that match it\",\n &m_use_regex\n );\n add_option\n ( 'l',\n \"Instead of printing a summary, print a date-ordered list of \"\n \"individual activity stints during the relevant period\",\n &m_show_stints\n );\n add_option\n ( 'b',\n \"In addition to any other information, output the earliest time at \"\n \"which each activity was conducted during the relevant period (ignored \"\n \"in list mode)\",\n &m_show_beginning\n );\n add_option\n ( 'e',\n \"Output in a column to the right of any other info, the latest time at \"\n \"which each activity was conducted during the relevant period (ignored \"\n \"in list mode)\",\n &m_show_end\n );\n add_option\n ( 'c',\n \"Output in CSV format\",\n &m_produce_csv\n );\n add_option\n ( 'v',\n \"Instead of printing the summary in \\\"tree\\\" form, print the full name of \"\\\n \"each activity (ignored in list mode or succinct mode)\",\n &m_be_verbose\n );\n add_option\n ( 's',\n \"Succinct output: show grand total only (ignored in list mode)\",\n &m_be_succinct\n );\n}\n\nReportingCommand::~ReportingCommand() = default;\n\nostream&\nReportingCommand::print_report\n( ostream& p_os,\n Config const& p_config,\n vector<string> const& p_activity_components,\n TimePoint const* p_begin,\n TimePoint const* p_end\n)\n{\n unique_ptr<string> activity_ptr;\n if (!p_activity_components.empty())\n {\n auto const expanded = expand_placeholders(p_activity_components, m_time_log);\n activity_ptr.reset(new string(squish(expanded.begin(), expanded.end())));\n }\n auto const stints = \n m_time_log.get_stints(activity_ptr.get(), p_begin, p_end, m_use_regex);\n ReportWriter::Options const options\n ( p_config.output_rounding_numerator(),\n p_config.output_rounding_denominator(),\n p_config.output_precision(),\n p_config.output_width(),\n p_config.formatted_buf_len(),\n p_config.time_format()\n );\n unique_ptr<ReportWriter> report_writer;\n if (m_show_stints)\n {\n if (m_produce_csv)\n {\n report_writer.reset(new CsvListReportWriter(stints, options));\n }\n else\n {\n report_writer.reset(new HumanListReportWriter(stints, options));\n }\n }\n else\n {\n if (m_produce_csv)\n {\n report_writer.reset\n ( new CsvSummaryReportWriter\n ( stints,\n options,\n m_show_beginning,\n m_show_end,\n m_be_succinct\n )\n );\n }\n else\n {\n report_writer.reset\n ( new HumanSummaryReportWriter\n ( stints,\n options,\n m_show_beginning,\n m_show_end,\n m_be_verbose,\n m_be_succinct\n )\n );\n }\n }\n report_writer->write(p_os);\n return p_os; \n}\n\nbool\nReportingCommand::does_support_placeholders() const\n{\n return true;\n}\n\n} \/\/ namespace swx\n<|endoftext|>"} {"text":"<commit_before>\/** \\file add_author_synonyms.cc\n * \\brief Adds author synonyms to each record.\n * \\author Oliver Obenland\n *\/\n\n\/*\n Copyright (C) 2016-2018, Library of the University of Tübingen\n\n This program is free software: you can redistribute it and\/or modify\n it under the terms of the GNU Affero General Public License as\n published by the Free Software Foundation, either version 3 of the\n License, or (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU Affero General Public License for more details.\n\n You should have received a copy of the GNU Affero General Public License\n along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n*\/\n\n#include <iostream>\n#include <map>\n#include <vector>\n#include <cstdlib>\n#include \"Compiler.h\"\n#include \"MARC.h\"\n#include \"StringUtil.h\"\n#include \"util.h\"\n\n\nstatic unsigned modified_count(0);\nstatic unsigned record_count(0);\n\n\nnamespace {\n\n[[noreturn]] void Usage() {\n std::cerr << \"Usage: \" << ::progname << \" master_marc_input norm_data_marc_input marc_output\\n\";\n std::exit(EXIT_FAILURE);\n}\n\n\nvoid RemoveCommasDuplicatesAndEmptyEntries(std::vector<std::string> * const vector) {\n std::vector<std::string> cleaned_up_vector;\n std::set<std::string> unique_entries;\n\n for (auto &entry : *vector) {\n StringUtil::RemoveChars(\",\", &entry);\n\n if (entry.empty())\n continue;\n\n const bool is_new_entry(unique_entries.emplace(entry).second);\n if (is_new_entry)\n cleaned_up_vector.emplace_back(std::move(entry));\n }\n vector->swap(cleaned_up_vector);\n}\n\n\nstd::string ExtractNameFromSubfields(const MARC::Record::Field &field, const std::string &subfield_codes) {\n auto subfield_values(field.getSubfields().extractSubfields(subfield_codes));\n\n if (subfield_values.empty())\n return \"\";\n\n std::sort(subfield_values.begin(), subfield_values.end());\n return StringUtil::Join(subfield_values, ' ');\n}\n\n\nvoid ExtractSynonyms(MARC::Reader * const marc_reader, std::map<std::string, std::string> &author_to_synonyms_map,\n const std::string &field_list)\n{\n std::set<std::string> synonyms;\n std::vector<std::string> tags_and_subfield_codes;\n if (unlikely(StringUtil::Split(field_list, ':', &tags_and_subfield_codes) < 2))\n LOG_ERROR(\"in ExtractSynonymsAndWriteSynonymMap: need at least two fields!\");\n unsigned count(0);\n while (const MARC::Record record = marc_reader->read()) {\n ++count;\n\n const auto primary_name_field(record.findTag(tags_and_subfield_codes[0].substr(0, 3)));\n if (primary_name_field != record.end())\n continue;\n\n const std::string primary_name(ExtractNameFromSubfields(*primary_name_field,\n tags_and_subfield_codes[0].substr(3)));\n if (unlikely(primary_name.empty()))\n continue;\n\n std::vector<std::string> alternatives;\n alternatives.emplace_back(primary_name);\n if (author_to_synonyms_map.find(primary_name) != author_to_synonyms_map.end())\n continue;\n\n for (unsigned i(1); i < tags_and_subfield_codes.size(); ++i) {\n const std::string tag(tags_and_subfield_codes[i].substr(0, 3));\n const std::string secondary_field_subfield_codes(tags_and_subfield_codes[i].substr(3));\n for (auto secondary_name_field(record.findTag(tag));\n secondary_name_field != record.end();\n ++secondary_name_field)\n {\n const std::string secondary_name(ExtractNameFromSubfields(*secondary_name_field,\n secondary_field_subfield_codes));\n if (not secondary_name.empty())\n alternatives.emplace_back(secondary_name);\n }\n }\n RemoveCommasDuplicatesAndEmptyEntries(&alternatives);\n if (alternatives.size() <= 1)\n continue;\n\n alternatives.erase(alternatives.begin());\n author_to_synonyms_map.emplace(primary_name, StringUtil::Join(alternatives, ','));\n }\n\n std::cout << \"Found synonyms for \" << author_to_synonyms_map.size() << \" authors while processing \" << count\n << \" norm data records.\\n\";\n}\n\n\nconst std::string SYNOMYM_FIELD(\"109\"); \/\/ This must be an o\/w unused field!\n\n\nvoid ProcessRecord(MARC::Record * const record, const std::map<std::string, std::string> &author_to_synonyms_map,\n const std::string &primary_author_field)\n{\n if (unlikely(record->findTag(SYNOMYM_FIELD) != record->end()))\n LOG_ERROR(\"field \" + SYNOMYM_FIELD + \" is apparently already in use in at least some title records!\");\n\n const auto primary_name_field(record->findTag(primary_author_field.substr(0, 3)));\n if (primary_name_field == record->end())\n return;\n\n const std::string primary_name(ExtractNameFromSubfields(*primary_name_field,\n primary_author_field.substr(3)));\n if (unlikely(primary_name.empty()))\n return;\n\n const auto synonyms_iterator = author_to_synonyms_map.find(primary_name);\n if (synonyms_iterator == author_to_synonyms_map.end())\n return;\n\n const std::string synonyms = synonyms_iterator->second;\n MARC::Subfields subfields;\n subfields.addSubfield('a', synonyms);\n\n if (not record->insertField(SYNOMYM_FIELD, subfields)) {\n LOG_WARNING(\"Not enough room to add a \" + SYNOMYM_FIELD + \" field! (Control number: \"\n + record->getControlNumber() + \")\");\n return;\n }\n ++modified_count;\n}\n\n\nvoid AddAuthorSynonyms(MARC::Reader * const marc_reader, MARC::Writer * marc_writer,\n const std::map<std::string, std::string> &author_to_synonyms_map,\n const std::string &primary_author_field)\n{\n while (MARC::Record record = marc_reader->read()) {\n ProcessRecord(&record, author_to_synonyms_map, primary_author_field);\n marc_writer->write(record);\n ++record_count;\n }\n\n std::cerr << \"Modified \" << modified_count << \" of \" << record_count << \" record(s).\\n\";\n}\n\n\n} \/\/ unnamed namespace\n\n\nint Main(int argc, char **argv) {\n if (argc != 4)\n Usage();\n\n const std::string marc_input_filename(argv[1]);\n const std::string authority_data_marc_input_filename(argv[2]);\n const std::string marc_output_filename(argv[3]);\n\n if (unlikely(marc_input_filename == marc_output_filename))\n LOG_ERROR(\"Title input file name equals title output file name!\");\n if (unlikely(authority_data_marc_input_filename == marc_output_filename))\n LOG_ERROR(\"Authority data input file name equals MARC output file name!\");\n\n auto marc_reader(MARC::Reader::Factory(marc_input_filename));\n auto authority_reader(MARC::Reader::Factory(authority_data_marc_input_filename));\n auto marc_writer(MARC::Writer::Factory(marc_output_filename));\n\n try {\n std::map<std::string, std::string> author_to_synonyms_map;\n ExtractSynonyms(authority_reader.get(), author_to_synonyms_map, \"100abcd:400abcd\");\n AddAuthorSynonyms(marc_reader.get(), marc_writer.get(), author_to_synonyms_map, \"100abcd\");\n } catch (const std::exception &x) {\n LOG_ERROR(\"caught exception: \" + std::string(x.what()));\n }\n\n return EXIT_SUCCESS;\n}\n<commit_msg>Fixed a trivial bug.<commit_after>\/** \\file add_author_synonyms.cc\n * \\brief Adds author synonyms to each record.\n * \\author Oliver Obenland\n *\/\n\n\/*\n Copyright (C) 2016-2018, Library of the University of Tübingen\n\n This program is free software: you can redistribute it and\/or modify\n it under the terms of the GNU Affero General Public License as\n published by the Free Software Foundation, either version 3 of the\n License, or (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU Affero General Public License for more details.\n\n You should have received a copy of the GNU Affero General Public License\n along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n*\/\n\n#include <iostream>\n#include <map>\n#include <vector>\n#include <cstdlib>\n#include \"Compiler.h\"\n#include \"MARC.h\"\n#include \"StringUtil.h\"\n#include \"util.h\"\n\n\nstatic unsigned modified_count(0);\nstatic unsigned record_count(0);\n\n\nnamespace {\n\n[[noreturn]] void Usage() {\n std::cerr << \"Usage: \" << ::progname << \" master_marc_input norm_data_marc_input marc_output\\n\";\n std::exit(EXIT_FAILURE);\n}\n\n\nvoid RemoveCommasDuplicatesAndEmptyEntries(std::vector<std::string> * const vector) {\n std::vector<std::string> cleaned_up_vector;\n std::set<std::string> unique_entries;\n\n for (auto &entry : *vector) {\n StringUtil::RemoveChars(\",\", &entry);\n\n if (entry.empty())\n continue;\n\n const bool is_new_entry(unique_entries.emplace(entry).second);\n if (is_new_entry)\n cleaned_up_vector.emplace_back(std::move(entry));\n }\n vector->swap(cleaned_up_vector);\n}\n\n\nstd::string ExtractNameFromSubfields(const MARC::Record::Field &field, const std::string &subfield_codes) {\n auto subfield_values(field.getSubfields().extractSubfields(subfield_codes));\n\n if (subfield_values.empty())\n return \"\";\n\n std::sort(subfield_values.begin(), subfield_values.end());\n return StringUtil::Join(subfield_values, ' ');\n}\n\n\nvoid ExtractSynonyms(MARC::Reader * const marc_reader, std::map<std::string, std::string> &author_to_synonyms_map,\n const std::string &field_list)\n{\n std::set<std::string> synonyms;\n std::vector<std::string> tags_and_subfield_codes;\n if (unlikely(StringUtil::Split(field_list, ':', &tags_and_subfield_codes) < 2))\n LOG_ERROR(\"need at least two fields!\");\n unsigned count(0);\n while (const MARC::Record record = marc_reader->read()) {\n ++count;\n\n const auto primary_name_field(record.findTag(tags_and_subfield_codes[0].substr(0, MARC::Record::TAG_LENGTH)));\n if (primary_name_field == record.end())\n continue;\n\n const std::string primary_name(ExtractNameFromSubfields(*primary_name_field,\n tags_and_subfield_codes[0].substr(3)));\n if (unlikely(primary_name.empty()))\n continue;\n\n std::vector<std::string> alternatives;\n alternatives.emplace_back(primary_name);\n if (author_to_synonyms_map.find(primary_name) != author_to_synonyms_map.end())\n continue;\n\n for (unsigned i(1); i < tags_and_subfield_codes.size(); ++i) {\n const std::string tag(tags_and_subfield_codes[i].substr(0, 3));\n const std::string secondary_field_subfield_codes(tags_and_subfield_codes[i].substr(3));\n for (auto secondary_name_field(record.findTag(tag));\n secondary_name_field != record.end();\n ++secondary_name_field)\n {\n const std::string secondary_name(ExtractNameFromSubfields(*secondary_name_field,\n secondary_field_subfield_codes));\n if (not secondary_name.empty())\n alternatives.emplace_back(secondary_name);\n }\n }\n RemoveCommasDuplicatesAndEmptyEntries(&alternatives);\n if (alternatives.size() <= 1)\n continue;\n\n alternatives.erase(alternatives.begin());\n author_to_synonyms_map.emplace(primary_name, StringUtil::Join(alternatives, ','));\n }\n\n std::cout << \"Found synonyms for \" << author_to_synonyms_map.size() << \" authors while processing \" << count\n << \" norm data records.\\n\";\n}\n\n\nconst std::string SYNOMYM_FIELD(\"109\"); \/\/ This must be an o\/w unused field!\n\n\nvoid ProcessRecord(MARC::Record * const record, const std::map<std::string, std::string> &author_to_synonyms_map,\n const std::string &primary_author_field)\n{\n if (unlikely(record->findTag(SYNOMYM_FIELD) != record->end()))\n LOG_ERROR(\"field \" + SYNOMYM_FIELD + \" is apparently already in use in at least some title records!\");\n\n const auto primary_name_field(record->findTag(primary_author_field.substr(0, 3)));\n if (primary_name_field == record->end())\n return;\n\n const std::string primary_name(ExtractNameFromSubfields(*primary_name_field,\n primary_author_field.substr(3)));\n if (unlikely(primary_name.empty()))\n return;\n\n const auto synonyms_iterator = author_to_synonyms_map.find(primary_name);\n if (synonyms_iterator == author_to_synonyms_map.end())\n return;\n\n const std::string synonyms = synonyms_iterator->second;\n MARC::Subfields subfields;\n subfields.addSubfield('a', synonyms);\n\n if (not record->insertField(SYNOMYM_FIELD, subfields)) {\n LOG_WARNING(\"Not enough room to add a \" + SYNOMYM_FIELD + \" field! (Control number: \"\n + record->getControlNumber() + \")\");\n return;\n }\n ++modified_count;\n}\n\n\nvoid AddAuthorSynonyms(MARC::Reader * const marc_reader, MARC::Writer * marc_writer,\n const std::map<std::string, std::string> &author_to_synonyms_map,\n const std::string &primary_author_field)\n{\n while (MARC::Record record = marc_reader->read()) {\n ProcessRecord(&record, author_to_synonyms_map, primary_author_field);\n marc_writer->write(record);\n ++record_count;\n }\n\n std::cerr << \"Modified \" << modified_count << \" of \" << record_count << \" record(s).\\n\";\n}\n\n\n} \/\/ unnamed namespace\n\n\nint Main(int argc, char **argv) {\n if (argc != 4)\n Usage();\n\n const std::string marc_input_filename(argv[1]);\n const std::string authority_data_marc_input_filename(argv[2]);\n const std::string marc_output_filename(argv[3]);\n\n if (unlikely(marc_input_filename == marc_output_filename))\n LOG_ERROR(\"Title input file name equals title output file name!\");\n if (unlikely(authority_data_marc_input_filename == marc_output_filename))\n LOG_ERROR(\"Authority data input file name equals MARC output file name!\");\n\n auto marc_reader(MARC::Reader::Factory(marc_input_filename));\n auto authority_reader(MARC::Reader::Factory(authority_data_marc_input_filename));\n auto marc_writer(MARC::Writer::Factory(marc_output_filename));\n\n try {\n std::map<std::string, std::string> author_to_synonyms_map;\n ExtractSynonyms(authority_reader.get(), author_to_synonyms_map, \"100abcd:400abcd\");\n AddAuthorSynonyms(marc_reader.get(), marc_writer.get(), author_to_synonyms_map, \"100abcd\");\n } catch (const std::exception &x) {\n LOG_ERROR(\"caught exception: \" + std::string(x.what()));\n }\n\n return EXIT_SUCCESS;\n}\n<|endoftext|>"} {"text":"<commit_before>\n#include \"lcio.h\"\n\n#include \"IO\/LCWriter.h\"\n#include \"EVENT\/LCIO.h\"\n#include \"DATA\/LCFloatVec.h\"\n#include \"DATA\/LCIntVec.h\"\n\n#include \"IMPL\/LCEventImpl.h\" \n#include \"IMPL\/LCRunHeaderImpl.h\" \n#include \"IMPL\/LCCollectionVec.h\"\n#include \"IMPL\/SimCalorimeterHitImpl.h\"\n#include \"IMPL\/SimTrackerHitImpl.h\"\n#include \"IMPL\/MCParticleImpl.h\" \n#include \"IMPL\/LCFlagImpl.h\" \n#include \"IMPL\/LCTOOLS.h\"\n#include \"IMPL\/TPCHitImpl.h\"\n#include \"UTIL\/LCRelationNavigator.h\"\n\n#include <cstdlib>\n#include <iostream>\n#include <sstream>\n\n\nusing namespace std ;\nusing namespace lcio ;\n\nstatic const int NRUN = 10 ;\nstatic const int NEVENT = 10 ; \/\/ events\nstatic const int NMCPART = 10 ; \/\/ mc particles per event\nstatic const int NHITS = 50 ; \/\/ calorimeter hits per event\n\nstatic string FILEN = \"simjob.slcio\" ;\n\n\n\/** Simple test program to demonstrate writing of data with lcio.\n *\/\n\nint main(int argc, char** argv ){\n \n try{\n \n \/\/ loop over runs\n for(int rn=0;rn<NRUN;rn++){\n \n \/\/ create sio writer\n LCWriter* lcWrt = LCFactory::getInstance()->createLCWriter() ;\n \n if( argc > 1 ) { FILEN = argv[1] ; }\n \n if( rn==0 )\n\tlcWrt->open( FILEN , LCIO::WRITE_NEW ) ;\n else\n\tlcWrt->open( FILEN , LCIO::WRITE_APPEND ) ;\n\n \/\/ NB: in order to test writing multiple files we create a new LCWriter\n \/\/ for every run even though we are in fact writing to one file only;\n \/\/ so for a simple job writing one file the \n \/\/ 'createLCWriter\/open' and 'close\/delete' will be outside the run loop...\n\n\n LCRunHeaderImpl* runHdr = new LCRunHeaderImpl ; \n runHdr->setRunNumber( rn ) ;\n \n string detName(\"D09TileHcal\") ;\n runHdr->setDetectorName( detName ) ;\n \n stringstream description ; \n description << \" run: \" << rn <<\" just for testing lcio - no physics !\" ;\n runHdr->setDescription( description.str() ) ;\n \n string ecalName(\"ECAL007\") ;\n runHdr->addActiveSubdetector( ecalName ) ;\n \n string tpcName(\"TPC4711\") ;\n runHdr->addActiveSubdetector( tpcName ) ;\n \n\n \/\/ add some parameters to the run header \n\/\/ StringVec sv1 ;\n\/\/ sv1.push_back(\"simjob.cc\") ;\n\/\/ runHdr->parameters().setValues( \"SimulationProgram\" , sv1 ) ; \n runHdr->parameters().setValue( \"SimulationProgram\" , \"simjob.cc\" ) ; \n IntVec iv(3) ;\n iv[0] = 1 ;\n iv[1] = 2 ;\n iv[2] = 3 ;\n runHdr->parameters().setValues( \"SomeIndices\" , iv ) ; \n \n lcWrt->writeRunHeader( runHdr ) ;\n \n \/\/ EventLoop - create some events and write them to the file\n for(int i=0;i<NEVENT;i++){\n\t\n\t\/\/ we need to use the implementation classes here \n\tLCEventImpl* evt = new LCEventImpl() ;\n\t\n\t\n\tevt->setRunNumber( rn ) ;\n\tevt->setEventNumber( i ) ;\n\tevt->setTimeStamp( 9223372036854775807LL ) ;\n\tevt->setDetectorName( detName ) ;\n\t\n\t\/\/ create and add some mc particles \n\tLCCollectionVec* mcVec = new LCCollectionVec( LCIO::MCPARTICLE ) ;\n\t\n\t\/\/ debug only - don't write MCParticles to output file:\n\t\/\/ mcVec->setTransient() ;\n\n\t\/\/ debug only - add the same particle to more than one collection\n\t\/\/LCCollectionVec* mcVec2 = new LCCollectionVec( LCIO::MCPARTICLE ) ;\n\n\tMCParticleImpl* mom = new MCParticleImpl ;\n\tmom->setPDG( 1 ) ;\n\tfloat p0[3] = { 0. , 0. , 1000. } ;\n\tmom->setMomentum( p0 ) ;\n\tmom->setMass( 3.01 ) ;\n\n\tfor(int j=0;j<NMCPART;j++){\n\n\t MCParticleImpl* mcp = new MCParticleImpl ;\n\n\t mcp->setPDG( 1000 * (j+1) ) ;\n\t float p[3] = { j*1. , 4.\/1024. , 8.\/1024. } ;\n\t mcp->setMomentum( p ) ;\n\t mcp->setMass( .135 ) ;\n\n\t \/\/ create and add some daughters\n\t for(int k=0;k<3;k++){\n\t MCParticleImpl* d1 = new MCParticleImpl ;\n\n\t d1->setPDG( 1000 * (j+1) + 100 * (k+1) ) ;\n\t float pd1[3] = { k*1. , 4.1 , 8.1 } ;\n\t d1->setMomentum( pd1 ) ;\n\t d1->setMass( .135 ) ;\n\n\t for(int l=0;l<2;l++){\n\t MCParticleImpl* d2 = new MCParticleImpl ;\n\t \n\t d2->setPDG( 1000 * (j+1) + 100 * (k+1) + 10 * (l+1) ) ;\n\t float pd2[3] = { l*1. , 0.41 , 4.1 } ;\n\t d2->setMomentum( pd2 ) ;\n\t d2->setMass( .135 ) ;\n\t \n\t double ep[3] = { 1.111111 , 2.2222222, 3.3333333 } ;\n\t d2->setEndpoint( ep ) ;\n\t \/\/\t d2->setSimulatorStatus( 1234 ) ;\n\t d2->setCreatedInSimulation(true) ;\n\t d2->setBackscatter(true) ;\n\t d2->setDecayedInTracker(true) ;\n\t d2->setDecayedInCalorimeter(false);\n\t d2->setHasLeftDetector(false) ;\n\t d2->setStopped(true) ;\n\n\t d2->addParent( d1 );\n\t mcVec->push_back( d2 ) ;\n\n\t \/\/ debug only - add the same particle to more than one collection\n\t \/\/mcVec2->push_back( d2 ) ;\n\t }\n\t d1->addParent( mcp );\n\t mcVec->push_back( d1 ) ;\n\t }\n\t \n\t mcp->addParent( mom );\n\t mcVec->push_back( mcp ) ;\n\t}\n\tmcVec->push_back( mom ) ;\n\t\n\t\/\/ now add some calorimeter hits\n\tLCCollectionVec* calVec = new LCCollectionVec( LCIO::SIMCALORIMETERHIT ) ;\n \n\t\/\/ set flag for long format (including position )\n\t\/\/ and PDG and cellid1\n\tLCFlagImpl chFlag(0) ;\n\tchFlag.setBit( LCIO::CHBIT_LONG ) ;\n\tchFlag.setBit( LCIO::CHBIT_PDG ) ;\n\tchFlag.setBit( LCIO::CHBIT_ID1 ) ;\n\tcalVec->setFlag( chFlag.getFlag() ) ;\n\t\n\t\n\tfor(int j=0;j<NHITS;j++){\n\t \n\t SimCalorimeterHitImpl* hit = new SimCalorimeterHitImpl ;\n\t \n\t hit->setEnergy( 3.1415 * rand()\/RAND_MAX ) ;\n\t \n\t float pos[3] = { 1.1* rand()\/RAND_MAX , 2.2* rand()\/RAND_MAX , 3.3* rand()\/RAND_MAX } ;\n\t \n\t hit->setCellID0( j+65335 ) ;\n\t hit->setCellID1( 65535 ) ;\n\n\t hit->setPosition( pos ) ;\n\t \n\t calVec->push_back( hit ) ;\n\t \n\t \/\/ assign the hits randomly to MC particles\n\t float rn = .99999*rand()\/RAND_MAX ;\n\t int mcIndx = static_cast<int>( NMCPART * rn ) ;\n\t \n\t \/\/ in order to access a MCParticle, we need a dynamic cast as the \n\t \/\/ LCCollection returns an LCIOObject - this is like vectors in Java \n\t hit->addMCParticleContribution( dynamic_cast<MCParticle*>(mcVec->getElementAt( mcIndx )) , \n\t\t\t\t\t 0.314159, 0.1155 ) ; \/\/ no pdg\n\t \n\t}\n\t\n\t\/\/ -------- data can be modified as long as is not not made persistent --------\n\n\tfor(int j=0;j<NHITS;j++){\n\t SimCalorimeterHitImpl* existingHit \n\t = dynamic_cast<SimCalorimeterHitImpl*>( calVec->getElementAt(j) ) ; \/\/ << Ok now\n\n \t \/\/\t = dynamic_cast<SimCalorimeterHitImpl*>( (*calVec)[j] ) ; \/\/ << not needed \n\t \n\t existingHit->addMCParticleContribution( dynamic_cast<MCParticle*>\n\t\t\t\t\t\t (mcVec->getElementAt(0)), \n\t\t\t\t\t\t 0.1, 0. ) ;\n\t}\n\n\t\/\/ and finally some tracker hits\n\t\/\/ with some user extensions (4 floats and 2 ints) per track:\n\t\/\/ we just need to create parallel collections of float and int vectors\n\tLCCollectionVec* trkVec = new LCCollectionVec( LCIO::SIMTRACKERHIT ) ;\n\tLCCollectionVec* extFVec = new LCCollectionVec( LCIO::LCFLOATVEC ) ;\n\tLCCollectionVec* extIVec = new LCCollectionVec( LCIO::LCINTVEC ) ;\n\t\n\tfor(int j=0;j<NHITS;j++){\n\t \n\t SimTrackerHitImpl* hit = new SimTrackerHitImpl ;\n\t LCFloatVec* extF = new LCFloatVec ;\n\t LCIntVec* extI = new LCIntVec ;\n\t \n\t hit->setdEdx( 30e-9 ) ; \n\n\t double pos[3] = { 1.1* rand()\/RAND_MAX , 2.2* rand()\/RAND_MAX , 3.3* rand()\/RAND_MAX } ;\n\t \n\t hit->setPosition( pos ) ; \n\t \n\t \/\/ assign the hits randomly to MC particles\n\t float rn = .99999*rand()\/RAND_MAX ;\n\t int mcIndx = static_cast<int>( NMCPART * rn ) ;\n\t \n\t hit->setMCParticle( dynamic_cast<MCParticle*>(mcVec->getElementAt( mcIndx ) ) ) ;\n\t \n\t \n\t \/\/ fill the extension vectors (4 floats, 2 ints)\n\t extF->push_back( 3.14159 ) ; \n\t for(int k=0;k<3;k++) extF->push_back( pos[k] * 0.1 ) ;\n\n\t extI->push_back( 123456789 ) ;\n\t extI->push_back( mcIndx ) ;\n\n\t \/\/ add the hit and the extensions to their corresponding collections\n\t trkVec->push_back( hit ) ;\n\t extFVec->push_back( extF ) ;\n\t extIVec->push_back( extI ) ;\n\t}\n\t\n\t\n\t\/\/ add all collections to the event\n\tevt->addCollection( mcVec , \"MCParticle\" ) ;\n\n\t\/\/deubg only \n\t\/\/evt->addCollection( mcVec2, \"MCParticle2\" ) ;\n\n\tevt->addCollection( calVec , ecalName ) ;\n\tevt->addCollection( trkVec , tpcName ) ;\n\tevt->addCollection( extFVec , tpcName+\"UserFloatExtension\" ) ;\n\tevt->addCollection( extIVec , tpcName+\"UserIntExtension\" ) ;\n\t\n\t\/\/ test: add a collection for one event only:\n\/\/ \tif( rn == NRUN-1 && i == 0 ) { \/\/ first event o last run\n\tif( rn == 1 && i == 0 ) { \/\/ first event o last run\n\t LCCollectionVec* addExtVec = new LCCollectionVec( LCIO::LCFLOATVEC ) ;\n\t LCFloatVec* addExt = new LCFloatVec ;\n\t addExt->push_back( 1. );\n\t addExt->push_back( 2. );\n\t addExt->push_back( 3. );\n\t addExt->push_back( 4. );\n\t addExtVec->push_back( addExt ) ;\n\t evt->addCollection( addExtVec , \"AdditionalExtension\" ) ;\n\t}\n\n\t\/\/ even though this is a simjob we can store 'real data' objects :)\n\t\/\/ --- for example we can store TPC hits ------------\n\n\tLCCollectionVec* TPCVec = new LCCollectionVec( LCIO::TPCHIT ) ;\n\n\t\/\/---- test new relation navigator object\n\/\/ \tLCRelationNavigator* relNav = \n\/\/ \t new LCRelationNavigator( LCIO::TPCHIT, LCIO::SIMTRACKERHIT ) ;\n\n\tLCRelationNavigator relNav( LCIO::TPCHIT, LCIO::SIMTRACKERHIT ) ;\n\n\tbool storeRawData = true ;\n\n\tLCFlagImpl tpcFlag(0) ;\n\tif( storeRawData ) \/\/ if we want to store the raw data we need to set the flag\n\t tpcFlag.setBit( LCIO::TPCBIT_RAW ) ;\n\tTPCVec->setFlag( tpcFlag.getFlag() ) ;\n\t\n\tfor(int j=0;j<NHITS;j++){\n\t \n\t TPCHitImpl* tpcHit = new TPCHitImpl ;\n\t \n\t \/\/---- test new relation navigator object\n\t relNav.addRelation( tpcHit , trkVec->getElementAt(j) , 0.95 ) ;\n\t \n\t tpcHit->setCellID( j ) ;\n\t tpcHit->setTime( 0.1234567 ) ;\n\t tpcHit->setCharge( 3.14159 ) ;\n\t tpcHit->setQuality( 0xbad ) ;\n\n\t if( storeRawData ) {\n\t int rawData[10] ;\n\t \/\/ fill some random numbers \n\t int size = int( (double(rand()) \/ RAND_MAX ) * 10 ) ; \n\t for(int k=0;k<size;k++){\n\t rawData[k] = int( (double(rand()) \/ RAND_MAX ) * INT_MAX ) ; \n\t }\n\n\t tpcHit->setRawData( rawData , size ) ;\n\t }\n\n\t TPCVec->push_back( tpcHit ) ;\n\t}\t\n\tevt->addCollection( TPCVec , \"TPCRawFADC\" ) ;\n\tevt->addCollection( relNav.createLCCollection() , \"TPCRawFADCMCTruth\" ) ;\n\n\/\/ \tdelete relNav ;\n\t\/\/-------------- all for TPC --------------------\n\n\n\t\/\/ write the event to the file\n\tlcWrt->writeEvent( evt ) ;\n\t\n\t\/\/ dump the event to the screen \n\tLCTOOLS::dumpEvent( evt ) ;\n\n\t\/\/ ------------ IMPORTANT ------------- !\n\t\/\/ we created the event so we need to delete it ...\n\tdelete evt ;\n\t\/\/ -------------------------------------\n\n\t\/\/ dont use this (compatibility with Fortran simjob.F)\n\t\/\/ if( ! (i%100) ) cout << \". \" << flush ;\n\t\n } \/\/ evt loop\n\n delete runHdr ;\n\n lcWrt->close() ;\n delete lcWrt ;\n\n } \/\/ run loop\n \n cout << endl \n\t << \" created \" << NRUN << \" runs with \" << NRUN*NEVENT << \" events\" \n\t << endl << endl ;\n \n \n \n \n } catch( Exception& ex){\n\n cout << \" an excpetion occured: \" << endl ;\n cout << \" \" << ex.what() << endl ;\n return 1 ;\n }\n\n return 0 ;\n}\n\n<commit_msg>use current time stamp and not infinity<commit_after>\n#include \"lcio.h\"\n\n#include \"IO\/LCWriter.h\"\n#include \"EVENT\/LCIO.h\"\n#include \"DATA\/LCFloatVec.h\"\n#include \"DATA\/LCIntVec.h\"\n\n#include \"IMPL\/LCEventImpl.h\" \n#include \"IMPL\/LCRunHeaderImpl.h\" \n#include \"IMPL\/LCCollectionVec.h\"\n#include \"IMPL\/SimCalorimeterHitImpl.h\"\n#include \"IMPL\/SimTrackerHitImpl.h\"\n#include \"IMPL\/MCParticleImpl.h\" \n#include \"IMPL\/LCFlagImpl.h\" \n#include \"IMPL\/LCTOOLS.h\"\n#include \"IMPL\/TPCHitImpl.h\"\n#include \"UTIL\/LCRelationNavigator.h\"\n#include \"UTIL\/LCTime.h\"\n\n#include <cstdlib>\n#include <iostream>\n#include <sstream>\n\n\nusing namespace std ;\nusing namespace lcio ;\n\nstatic const int NRUN = 10 ;\nstatic const int NEVENT = 10 ; \/\/ events\nstatic const int NMCPART = 10 ; \/\/ mc particles per event\nstatic const int NHITS = 50 ; \/\/ calorimeter hits per event\n\nstatic string FILEN = \"simjob.slcio\" ;\n\n\n\/** Simple test program to demonstrate writing of data with lcio.\n *\/\n\nint main(int argc, char** argv ){\n \n try{\n \n \/\/ loop over runs\n for(int rn=0;rn<NRUN;rn++){\n \n \/\/ create sio writer\n LCWriter* lcWrt = LCFactory::getInstance()->createLCWriter() ;\n \n if( argc > 1 ) { FILEN = argv[1] ; }\n \n if( rn==0 )\n\tlcWrt->open( FILEN , LCIO::WRITE_NEW ) ;\n else\n\tlcWrt->open( FILEN , LCIO::WRITE_APPEND ) ;\n\n \/\/ NB: in order to test writing multiple files we create a new LCWriter\n \/\/ for every run even though we are in fact writing to one file only;\n \/\/ so for a simple job writing one file the \n \/\/ 'createLCWriter\/open' and 'close\/delete' will be outside the run loop...\n\n\n LCRunHeaderImpl* runHdr = new LCRunHeaderImpl ; \n runHdr->setRunNumber( rn ) ;\n \n string detName(\"D09TileHcal\") ;\n runHdr->setDetectorName( detName ) ;\n \n stringstream description ; \n description << \" run: \" << rn <<\" just for testing lcio - no physics !\" ;\n runHdr->setDescription( description.str() ) ;\n \n string ecalName(\"ECAL007\") ;\n runHdr->addActiveSubdetector( ecalName ) ;\n \n string tpcName(\"TPC4711\") ;\n runHdr->addActiveSubdetector( tpcName ) ;\n \n\n \/\/ add some parameters to the run header \n\/\/ StringVec sv1 ;\n\/\/ sv1.push_back(\"simjob.cc\") ;\n\/\/ runHdr->parameters().setValues( \"SimulationProgram\" , sv1 ) ; \n runHdr->parameters().setValue( \"SimulationProgram\" , \"simjob.cc\" ) ; \n IntVec iv(3) ;\n iv[0] = 1 ;\n iv[1] = 2 ;\n iv[2] = 3 ;\n runHdr->parameters().setValues( \"SomeIndices\" , iv ) ; \n \n lcWrt->writeRunHeader( runHdr ) ;\n \n \/\/ EventLoop - create some events and write them to the file\n for(int i=0;i<NEVENT;i++){\n\t\n\t\/\/ we need to use the implementation classes here \n\tLCEventImpl* evt = new LCEventImpl() ;\n\t\n\t\n\tevt->setRunNumber( rn ) ;\n\tevt->setEventNumber( i ) ;\n\tLCTime now ;\n\tevt->setTimeStamp( now.timeStamp() ) ;\n\tevt->setDetectorName( detName ) ;\n\t\n\t\/\/ create and add some mc particles \n\tLCCollectionVec* mcVec = new LCCollectionVec( LCIO::MCPARTICLE ) ;\n\t\n\t\/\/ debug only - don't write MCParticles to output file:\n\t\/\/ mcVec->setTransient() ;\n\n\t\/\/ debug only - add the same particle to more than one collection\n\t\/\/LCCollectionVec* mcVec2 = new LCCollectionVec( LCIO::MCPARTICLE ) ;\n\n\tMCParticleImpl* mom = new MCParticleImpl ;\n\tmom->setPDG( 1 ) ;\n\tfloat p0[3] = { 0. , 0. , 1000. } ;\n\tmom->setMomentum( p0 ) ;\n\tmom->setMass( 3.01 ) ;\n\n\tfor(int j=0;j<NMCPART;j++){\n\n\t MCParticleImpl* mcp = new MCParticleImpl ;\n\n\t mcp->setPDG( 1000 * (j+1) ) ;\n\t float p[3] = { j*1. , 4.\/1024. , 8.\/1024. } ;\n\t mcp->setMomentum( p ) ;\n\t mcp->setMass( .135 ) ;\n\n\t \/\/ create and add some daughters\n\t for(int k=0;k<3;k++){\n\t MCParticleImpl* d1 = new MCParticleImpl ;\n\n\t d1->setPDG( 1000 * (j+1) + 100 * (k+1) ) ;\n\t float pd1[3] = { k*1. , 4.1 , 8.1 } ;\n\t d1->setMomentum( pd1 ) ;\n\t d1->setMass( .135 ) ;\n\n\t for(int l=0;l<2;l++){\n\t MCParticleImpl* d2 = new MCParticleImpl ;\n\t \n\t d2->setPDG( 1000 * (j+1) + 100 * (k+1) + 10 * (l+1) ) ;\n\t float pd2[3] = { l*1. , 0.41 , 4.1 } ;\n\t d2->setMomentum( pd2 ) ;\n\t d2->setMass( .135 ) ;\n\t \n\t double ep[3] = { 1.111111 , 2.2222222, 3.3333333 } ;\n\t d2->setEndpoint( ep ) ;\n\t \/\/\t d2->setSimulatorStatus( 1234 ) ;\n\t d2->setCreatedInSimulation(true) ;\n\t d2->setBackscatter(true) ;\n\t d2->setDecayedInTracker(true) ;\n\t d2->setDecayedInCalorimeter(false);\n\t d2->setHasLeftDetector(false) ;\n\t d2->setStopped(true) ;\n\n\t d2->addParent( d1 );\n\t mcVec->push_back( d2 ) ;\n\n\t \/\/ debug only - add the same particle to more than one collection\n\t \/\/mcVec2->push_back( d2 ) ;\n\t }\n\t d1->addParent( mcp );\n\t mcVec->push_back( d1 ) ;\n\t }\n\t \n\t mcp->addParent( mom );\n\t mcVec->push_back( mcp ) ;\n\t}\n\tmcVec->push_back( mom ) ;\n\t\n\t\/\/ now add some calorimeter hits\n\tLCCollectionVec* calVec = new LCCollectionVec( LCIO::SIMCALORIMETERHIT ) ;\n \n\t\/\/ set flag for long format (including position )\n\t\/\/ and PDG and cellid1\n\tLCFlagImpl chFlag(0) ;\n\tchFlag.setBit( LCIO::CHBIT_LONG ) ;\n\tchFlag.setBit( LCIO::CHBIT_PDG ) ;\n\tchFlag.setBit( LCIO::CHBIT_ID1 ) ;\n\tcalVec->setFlag( chFlag.getFlag() ) ;\n\t\n\t\n\tfor(int j=0;j<NHITS;j++){\n\t \n\t SimCalorimeterHitImpl* hit = new SimCalorimeterHitImpl ;\n\t \n\t hit->setEnergy( 3.1415 * rand()\/RAND_MAX ) ;\n\t \n\t float pos[3] = { 1.1* rand()\/RAND_MAX , 2.2* rand()\/RAND_MAX , 3.3* rand()\/RAND_MAX } ;\n\t \n\t hit->setCellID0( j+65335 ) ;\n\t hit->setCellID1( 65535 ) ;\n\n\t hit->setPosition( pos ) ;\n\t \n\t calVec->push_back( hit ) ;\n\t \n\t \/\/ assign the hits randomly to MC particles\n\t float rn = .99999*rand()\/RAND_MAX ;\n\t int mcIndx = static_cast<int>( NMCPART * rn ) ;\n\t \n\t \/\/ in order to access a MCParticle, we need a dynamic cast as the \n\t \/\/ LCCollection returns an LCIOObject - this is like vectors in Java \n\t hit->addMCParticleContribution( dynamic_cast<MCParticle*>(mcVec->getElementAt( mcIndx )) , \n\t\t\t\t\t 0.314159, 0.1155 ) ; \/\/ no pdg\n\t \n\t}\n\t\n\t\/\/ -------- data can be modified as long as is not not made persistent --------\n\n\tfor(int j=0;j<NHITS;j++){\n\t SimCalorimeterHitImpl* existingHit \n\t = dynamic_cast<SimCalorimeterHitImpl*>( calVec->getElementAt(j) ) ; \/\/ << Ok now\n\n \t \/\/\t = dynamic_cast<SimCalorimeterHitImpl*>( (*calVec)[j] ) ; \/\/ << not needed \n\t \n\t existingHit->addMCParticleContribution( dynamic_cast<MCParticle*>\n\t\t\t\t\t\t (mcVec->getElementAt(0)), \n\t\t\t\t\t\t 0.1, 0. ) ;\n\t}\n\n\t\/\/ and finally some tracker hits\n\t\/\/ with some user extensions (4 floats and 2 ints) per track:\n\t\/\/ we just need to create parallel collections of float and int vectors\n\tLCCollectionVec* trkVec = new LCCollectionVec( LCIO::SIMTRACKERHIT ) ;\n\tLCCollectionVec* extFVec = new LCCollectionVec( LCIO::LCFLOATVEC ) ;\n\tLCCollectionVec* extIVec = new LCCollectionVec( LCIO::LCINTVEC ) ;\n\t\n\tfor(int j=0;j<NHITS;j++){\n\t \n\t SimTrackerHitImpl* hit = new SimTrackerHitImpl ;\n\t LCFloatVec* extF = new LCFloatVec ;\n\t LCIntVec* extI = new LCIntVec ;\n\t \n\t hit->setdEdx( 30e-9 ) ; \n\n\t double pos[3] = { 1.1* rand()\/RAND_MAX , 2.2* rand()\/RAND_MAX , 3.3* rand()\/RAND_MAX } ;\n\t \n\t hit->setPosition( pos ) ; \n\t \n\t \/\/ assign the hits randomly to MC particles\n\t float rn = .99999*rand()\/RAND_MAX ;\n\t int mcIndx = static_cast<int>( NMCPART * rn ) ;\n\t \n\t hit->setMCParticle( dynamic_cast<MCParticle*>(mcVec->getElementAt( mcIndx ) ) ) ;\n\t \n\t \n\t \/\/ fill the extension vectors (4 floats, 2 ints)\n\t extF->push_back( 3.14159 ) ; \n\t for(int k=0;k<3;k++) extF->push_back( pos[k] * 0.1 ) ;\n\n\t extI->push_back( 123456789 ) ;\n\t extI->push_back( mcIndx ) ;\n\n\t \/\/ add the hit and the extensions to their corresponding collections\n\t trkVec->push_back( hit ) ;\n\t extFVec->push_back( extF ) ;\n\t extIVec->push_back( extI ) ;\n\t}\n\t\n\t\n\t\/\/ add all collections to the event\n\tevt->addCollection( mcVec , \"MCParticle\" ) ;\n\n\t\/\/deubg only \n\t\/\/evt->addCollection( mcVec2, \"MCParticle2\" ) ;\n\n\tevt->addCollection( calVec , ecalName ) ;\n\tevt->addCollection( trkVec , tpcName ) ;\n\tevt->addCollection( extFVec , tpcName+\"UserFloatExtension\" ) ;\n\tevt->addCollection( extIVec , tpcName+\"UserIntExtension\" ) ;\n\t\n\t\/\/ test: add a collection for one event only:\n\/\/ \tif( rn == NRUN-1 && i == 0 ) { \/\/ first event o last run\n\tif( rn == 1 && i == 0 ) { \/\/ first event o last run\n\t LCCollectionVec* addExtVec = new LCCollectionVec( LCIO::LCFLOATVEC ) ;\n\t LCFloatVec* addExt = new LCFloatVec ;\n\t addExt->push_back( 1. );\n\t addExt->push_back( 2. );\n\t addExt->push_back( 3. );\n\t addExt->push_back( 4. );\n\t addExtVec->push_back( addExt ) ;\n\t evt->addCollection( addExtVec , \"AdditionalExtension\" ) ;\n\t}\n\n\t\/\/ even though this is a simjob we can store 'real data' objects :)\n\t\/\/ --- for example we can store TPC hits ------------\n\n\tLCCollectionVec* TPCVec = new LCCollectionVec( LCIO::TPCHIT ) ;\n\n\t\/\/---- test new relation navigator object\n\/\/ \tLCRelationNavigator* relNav = \n\/\/ \t new LCRelationNavigator( LCIO::TPCHIT, LCIO::SIMTRACKERHIT ) ;\n\n\tLCRelationNavigator relNav( LCIO::TPCHIT, LCIO::SIMTRACKERHIT ) ;\n\n\tbool storeRawData = true ;\n\n\tLCFlagImpl tpcFlag(0) ;\n\tif( storeRawData ) \/\/ if we want to store the raw data we need to set the flag\n\t tpcFlag.setBit( LCIO::TPCBIT_RAW ) ;\n\tTPCVec->setFlag( tpcFlag.getFlag() ) ;\n\t\n\tfor(int j=0;j<NHITS;j++){\n\t \n\t TPCHitImpl* tpcHit = new TPCHitImpl ;\n\t \n\t \/\/---- test new relation navigator object\n\t relNav.addRelation( tpcHit , trkVec->getElementAt(j) , 0.95 ) ;\n\t \n\t tpcHit->setCellID( j ) ;\n\t tpcHit->setTime( 0.1234567 ) ;\n\t tpcHit->setCharge( 3.14159 ) ;\n\t tpcHit->setQuality( 0xbad ) ;\n\n\t if( storeRawData ) {\n\t int rawData[10] ;\n\t \/\/ fill some random numbers \n\t int size = int( (double(rand()) \/ RAND_MAX ) * 10 ) ; \n\t for(int k=0;k<size;k++){\n\t rawData[k] = int( (double(rand()) \/ RAND_MAX ) * INT_MAX ) ; \n\t }\n\n\t tpcHit->setRawData( rawData , size ) ;\n\t }\n\n\t TPCVec->push_back( tpcHit ) ;\n\t}\t\n\tevt->addCollection( TPCVec , \"TPCRawFADC\" ) ;\n\tevt->addCollection( relNav.createLCCollection() , \"TPCRawFADCMCTruth\" ) ;\n\n\/\/ \tdelete relNav ;\n\t\/\/-------------- all for TPC --------------------\n\n\n\t\/\/ write the event to the file\n\tlcWrt->writeEvent( evt ) ;\n\t\n\t\/\/ dump the event to the screen \n\tLCTOOLS::dumpEvent( evt ) ;\n\n\t\/\/ ------------ IMPORTANT ------------- !\n\t\/\/ we created the event so we need to delete it ...\n\tdelete evt ;\n\t\/\/ -------------------------------------\n\n\t\/\/ dont use this (compatibility with Fortran simjob.F)\n\t\/\/ if( ! (i%100) ) cout << \". \" << flush ;\n\t\n } \/\/ evt loop\n\n delete runHdr ;\n\n lcWrt->close() ;\n delete lcWrt ;\n\n } \/\/ run loop\n \n cout << endl \n\t << \" created \" << NRUN << \" runs with \" << NRUN*NEVENT << \" events\" \n\t << endl << endl ;\n \n \n \n \n } catch( Exception& ex){\n\n cout << \" an excpetion occured: \" << endl ;\n cout << \" \" << ex.what() << endl ;\n return 1 ;\n }\n\n return 0 ;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/*******************************************************************************\n* ALMA - Atacama Large Millimiter Array\n* (c) National Research Council of Canada, 2006 \n* \n* This library is free software; you can redistribute it and\/or\n* modify it under the terms of the GNU Lesser General Public\n* License as published by the Free Software Foundation; either\n* version 2.1 of the License, or (at your option) any later version.\n* \n* This library is distributed in the hope that it will be useful,\n* but WITHOUT ANY WARRANTY; without even the implied warranty of\n* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n* Lesser General Public License for more details.\n* \n* You should have received a copy of the GNU Lesser General Public\n* License along with this library; if not, write to the Free Software\n* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n*\n* \"@(#) $Id: acsstartupIrFeed.cpp,v 1.1 2006\/03\/24 23:24:53 dfugate Exp $\"\n*\n* who when what\n* -------- -------- ----------------------------------------------\n* dfugate 2006-03-24 created\n*\/\n\n\/************************************************************************\n* NAME\n* \n* \n* SYNOPSIS\n* \n* \n* DESCRIPTION\n*\n* FILES\n*\n* ENVIRONMENT\n*\n* COMMANDS\n*\n* RETURN VALUES\n*\n* CAUTIONS \n*\n* EXAMPLES\n*\n* SEE ALSO\n*\n* BUGS \n* \n*------------------------------------------------------------------------\n*\/\n\n\/\/ Uncomment this if you are using the VLT environment\n\/\/ #include \"vltPort.h\"\n\n\n#include <stdlib.h>\n#include <stdio.h>\n#include <string.h>\n\nstatic char *rcsId=\"@(#) $Id: acsstartupIrFeed.cpp,v 1.1 2006\/03\/24 23:24:53 dfugate Exp $\"; \nstatic void *use_rcsId = ((void)&use_rcsId,(void *) &rcsId);\n\n#include <iostream>\n#include <list>\n#include <acsutilPorts.h>\n#include <dirent.h>\n#include <fstream>\n\n\nusing std::string;\nusing std::list;\nusing std::cout;\n\n\/**\n * Helper function adds all IDL files found within dirName\n * to files list.\n *\/\nvoid addIdlFiles(std::string dirName,\n\t\t list<string> & files)\n{\n \/\/open the directory\n DIR* dir = opendir(dirName.c_str());\n\n \/\/sanity check\n if (dir==0)\n\t{\n\treturn;\n\t}\n\n \/\/traverse the directory looking for files that end in \".idl\"\n struct dirent * file = readdir(dir);\n while(file!=0)\n\t{\n\tstring t_file = file->d_name;\n\n\t\/\/good, found a match\n\tif(t_file.rfind(\".idl\") != string::npos)\n\t {\n\t files.push_back(t_file);\n\t }\n\t\n\tfile = readdir(dir);\n\t}\n\n closedir(dir);\n}\n\nint main(int argc, char *argv[])\n{\n list<string> idlFiles;\n\n std::string managerHost = ACSPorts::getIP();\n std::string ifrPort = ACSPorts::getIRPort();\n std::string ifrCorbaloc = \"corbaloc::\" + managerHost + \":\" + ifrPort + \"\/DefaultRepository\";\n std::string aceRoot = getenv(\"ACE_ROOT\");\n std::string idlPath = getenv(\"IDL_PATH\");\n std::string outFile = argv[1];\n std::string processId = argv[2];\n \n std::ofstream file(outFile.c_str());\n\n\n \/\/\/Split idlPath after the first $ACE_ROOT\n\n \/\/find first reference to ACE_ROOT\n std::string::size_type aceRootIndex = idlPath.find(aceRoot);\n\n \/\/chop off everything after and including ACE_ROOT\n idlPath = idlPath.substr(0, aceRootIndex);\n \n \/\/get rid of all the nasty \"-I\"s\n while(true)\n\t{\n\tstd::string::size_type includeIndex = idlPath.find(\"-I\");\n\t\/\/sanity check\n\tif (includeIndex == string::npos)\n\t {\n\t break;\n\t }\n\n\tidlPath.erase(includeIndex, 2);\n\t}\n\n \/\/cycle through each area of IDL path\n while(idlPath.length()!=0)\n\t{\n\t\/\/find the next whitespace to...\n\tstd::string::size_type wsIndex = idlPath.find(\" \");\n\t\/\/sanity check\n\tif (wsIndex == string::npos)\n\t {\n\t break;\n\t }\n\n\t\/\/...get the next IDL directory\n\tstring idlDir = idlPath.substr(0, wsIndex);\n\t\n\t\/\/examine the IDL directory adding all IDLs found\n\taddIdlFiles(idlDir, idlFiles);\n\n\t\n\t\/\/shrink the idlPath\n\tidlPath.erase(0, wsIndex + 1);\n\t}\n \n \/\/remove duplicates\n idlFiles.unique();\n\n file << \"#ifndef acsIrfeedDyn_\" << processId <<\"_idl\" << std::endl;\n file << \"#define acsIrfeedDyn_\" << processId <<\"_idl\" << std::endl;\n file << \"\/*******************************************************************************\" << std::endl;\n file << \"* ALMA Project\" << std::endl;\n file << \"*\" << std::endl;\n file << \"* This file is dynamically created by acsIrfeed to load\" << std::endl;\n file << \"* in the Orbacus Interface Repository\" << std::endl;\n file << \"* the complete set of IDL interfaces\" << std::endl;\n file << \"*\" << std::endl;\n file << \"*\/\" << std::endl;\n file << \"\" << std::endl;\n file << \"#define local\" << std::endl;\n file << \"#include <CosPropertyService.idl>\" << std::endl;\n file << \"#undef local\" << std::endl;\n file << \"\" << std::endl;\n file << \"#include <acserr.idl>\" << std::endl;\n file << \"\" << std::endl;\n\n while (idlFiles.empty() == false)\n\t{\n\tfile << \"#include <\" << idlFiles.front() << \">\" << std::endl;\n\tidlFiles.pop_front();\n\t}\n\n file << \"#endif\" << std::endl;\n \n return 0;\n\n}\n\n\n\n\n\n\n\n\n<commit_msg>Refactored a tiny bit.<commit_after>\/*******************************************************************************\n* ALMA - Atacama Large Millimiter Array\n* (c) National Research Council of Canada, 2006 \n* \n* This library is free software; you can redistribute it and\/or\n* modify it under the terms of the GNU Lesser General Public\n* License as published by the Free Software Foundation; either\n* version 2.1 of the License, or (at your option) any later version.\n* \n* This library is distributed in the hope that it will be useful,\n* but WITHOUT ANY WARRANTY; without even the implied warranty of\n* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n* Lesser General Public License for more details.\n* \n* You should have received a copy of the GNU Lesser General Public\n* License along with this library; if not, write to the Free Software\n* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n*\n* \"@(#) $Id: acsstartupIrFeed.cpp,v 1.2 2006\/05\/05 21:04:50 dfugate Exp $\"\n*\n* who when what\n* -------- -------- ----------------------------------------------\n* dfugate 2006-03-24 created\n*\/\n\n\/************************************************************************\n* NAME\n* \n* \n* SYNOPSIS\n* \n* \n* DESCRIPTION\n*\n* FILES\n*\n* ENVIRONMENT\n*\n* COMMANDS\n*\n* RETURN VALUES\n*\n* CAUTIONS \n*\n* EXAMPLES\n*\n* SEE ALSO\n*\n* BUGS \n* \n*------------------------------------------------------------------------\n*\/\n\n\/\/ Uncomment this if you are using the VLT environment\n\/\/ #include \"vltPort.h\"\n\n\n#include <stdlib.h>\n#include <stdio.h>\n#include <string.h>\n\nstatic char *rcsId=\"@(#) $Id: acsstartupIrFeed.cpp,v 1.2 2006\/05\/05 21:04:50 dfugate Exp $\"; \nstatic void *use_rcsId = ((void)&use_rcsId,(void *) &rcsId);\n\n#include <iostream>\n#include <list>\n#include <acsutilPorts.h>\n#include <dirent.h>\n#include <fstream>\n\n\nusing std::string;\nusing std::list;\nusing std::cout;\n\n\/**\n * Helper function adds all IDL files found within dirName\n * to files list.\n *\/\nvoid addIdlFiles(std::string dirName,\n\t\t list<string> & files)\n{\n \/\/open the directory\n DIR* dir = opendir(dirName.c_str());\n\n \/\/sanity check\n if (dir==0)\n\t{\n\treturn;\n\t}\n\n \/\/traverse the directory looking for files that end in \".idl\"\n struct dirent * file = readdir(dir);\n while(file!=0)\n\t{\n\tstring t_file = file->d_name;\n\n\t\/\/good, found a match\n\tif(t_file.rfind(\".idl\") != string::npos)\n\t {\n\t files.push_back(t_file);\n\t }\n\t\n\tfile = readdir(dir);\n\t}\n\n closedir(dir);\n}\n\nint main(int argc, char *argv[])\n{\n list<string> idlFiles;\n \n std::string aceRoot = getenv(\"ACE_ROOT\");\n std::string idlPath = getenv(\"IDL_PATH\");\n std::string outFile = argv[1];\n std::string processId = argv[2];\n \n std::ofstream file(outFile.c_str());\n\n\n \/\/\/Split idlPath after the first $ACE_ROOT\n\n \/\/find first reference to ACE_ROOT\n std::string::size_type aceRootIndex = idlPath.find(aceRoot);\n\n \/\/chop off everything after and including ACE_ROOT\n idlPath = idlPath.substr(0, aceRootIndex);\n \n \/\/get rid of all the nasty \"-I\"s\n while(true)\n\t{\n\tstd::string::size_type includeIndex = idlPath.find(\"-I\");\n\t\/\/sanity check\n\tif (includeIndex == string::npos)\n\t {\n\t break;\n\t }\n\n\tidlPath.erase(includeIndex, 2);\n\t}\n\n \/\/cycle through each area of IDL path\n while(idlPath.length()!=0)\n\t{\n\t\/\/find the next whitespace to...\n\tstd::string::size_type wsIndex = idlPath.find(\" \");\n\t\/\/sanity check\n\tif (wsIndex == string::npos)\n\t {\n\t break;\n\t }\n\n\t\/\/...get the next IDL directory\n\tstring idlDir = idlPath.substr(0, wsIndex);\n\t\n\t\/\/examine the IDL directory adding all IDLs found\n\taddIdlFiles(idlDir, idlFiles);\n\n\t\n\t\/\/shrink the idlPath\n\tidlPath.erase(0, wsIndex + 1);\n\t}\n \n \/\/remove duplicates\n idlFiles.unique();\n\n file << \"#ifndef acsIrfeedDyn_\" << processId <<\"_idl\" << std::endl;\n file << \"#define acsIrfeedDyn_\" << processId <<\"_idl\" << std::endl;\n file << \"\/*******************************************************************************\" << std::endl;\n file << \"* ALMA Project\" << std::endl;\n file << \"*\" << std::endl;\n file << \"* This file is dynamically created by acsIrfeed to load\" << std::endl;\n file << \"* in the Orbacus Interface Repository\" << std::endl;\n file << \"* the complete set of IDL interfaces\" << std::endl;\n file << \"*\" << std::endl;\n file << \"*\/\" << std::endl;\n file << \"\" << std::endl;\n file << \"#define local\" << std::endl;\n file << \"#include <CosPropertyService.idl>\" << std::endl;\n file << \"#undef local\" << std::endl;\n file << \"\" << std::endl;\n file << \"#include <acserr.idl>\" << std::endl;\n file << \"\" << std::endl;\n\n while (idlFiles.empty() == false)\n\t{\n\tfile << \"#include <\" << idlFiles.front() << \">\" << std::endl;\n\tidlFiles.pop_front();\n\t}\n\n file << \"#endif\" << std::endl;\n \n return 0;\n\n}\n\n\n\n\n\n\n\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright 2008-2010 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"esnpapi.h\"\n#include \"proxyImpl.h\"\n\n#include <org\/w3c\/dom.h>\n\nusing namespace org::w3c::dom;\n\nvoid initializeHtmlMetaDataO_U()\n{\n ProxyControl::registerMetaData(html::HTMLObjectElement::getMetaData(), Proxy_Impl<ProxyObject, html::HTMLObjectElement_Bridge<Any, invoke> >::createInstance);\n ProxyControl::registerMetaData(html::HTMLOListElement::getMetaData(), Proxy_Impl<ProxyObject, html::HTMLOListElement_Bridge<Any, invoke> >::createInstance);\n ProxyControl::registerMetaData(html::HTMLOptGroupElement::getMetaData(), Proxy_Impl<ProxyObject, html::HTMLOptGroupElement_Bridge<Any, invoke> >::createInstance);\n ProxyControl::registerMetaData(html::HTMLOptionElement::getMetaData(), Proxy_Impl<ProxyObject, html::HTMLOptionElement_Bridge<Any, invoke> >::createInstance);\n ProxyControl::registerMetaData(html::HTMLOptionsCollection::getMetaData(), Proxy_Impl<ProxyObject, html::HTMLOptionsCollection_Bridge<Any, invoke> >::createInstance);\n ProxyControl::registerMetaData(html::HTMLOutputElement::getMetaData(), Proxy_Impl<ProxyObject, html::HTMLOutputElement_Bridge<Any, invoke> >::createInstance);\n ProxyControl::registerMetaData(html::HTMLParagraphElement::getMetaData(), Proxy_Impl<ProxyObject, html::HTMLParagraphElement_Bridge<Any, invoke> >::createInstance);\n ProxyControl::registerMetaData(html::HTMLParamElement::getMetaData(), Proxy_Impl<ProxyObject, html::HTMLParamElement_Bridge<Any, invoke> >::createInstance);\n ProxyControl::registerMetaData(html::HTMLPreElement::getMetaData(), Proxy_Impl<ProxyObject, html::HTMLPreElement_Bridge<Any, invoke> >::createInstance);\n ProxyControl::registerMetaData(html::HTMLProgressElement::getMetaData(), Proxy_Impl<ProxyObject, html::HTMLProgressElement_Bridge<Any, invoke> >::createInstance);\n \/\/ TODO: HTMLPropertiesCollection overrides HTMLCollection in a way the current Bridge classes can not handle.\n ProxyControl::registerMetaData(html::HTMLPropertiesCollection::getMetaData(), Proxy_Impl<ProxyObject, html::HTMLPropertiesCollection_Bridge<Any, invoke> >::createInstance);\n ProxyControl::registerMetaData(html::HTMLQuoteElement::getMetaData(), Proxy_Impl<ProxyObject, html::HTMLQuoteElement_Bridge<Any, invoke> >::createInstance);\n ProxyControl::registerMetaData(html::HTMLScriptElement::getMetaData(), Proxy_Impl<ProxyObject, html::HTMLScriptElement_Bridge<Any, invoke> >::createInstance);\n ProxyControl::registerMetaData(html::HTMLSelectElement::getMetaData(), Proxy_Impl<ProxyObject, html::HTMLSelectElement_Bridge<Any, invoke> >::createInstance);\n ProxyControl::registerMetaData(html::HTMLSourceElement::getMetaData(), Proxy_Impl<ProxyObject, html::HTMLSourceElement_Bridge<Any, invoke> >::createInstance);\n ProxyControl::registerMetaData(html::HTMLSpanElement::getMetaData(), Proxy_Impl<ProxyObject, html::HTMLSpanElement_Bridge<Any, invoke> >::createInstance);\n ProxyControl::registerMetaData(html::HTMLStyleElement::getMetaData(), Proxy_Impl<ProxyObject, html::HTMLStyleElement_Bridge<Any, invoke> >::createInstance);\n ProxyControl::registerMetaData(html::HTMLTableCaptionElement::getMetaData(), Proxy_Impl<ProxyObject, html::HTMLTableCaptionElement_Bridge<Any, invoke> >::createInstance);\n ProxyControl::registerMetaData(html::HTMLTableCellElement::getMetaData(), Proxy_Impl<ProxyObject, html::HTMLTableCellElement_Bridge<Any, invoke> >::createInstance);\n ProxyControl::registerMetaData(html::HTMLTableColElement::getMetaData(), Proxy_Impl<ProxyObject, html::HTMLTableColElement_Bridge<Any, invoke> >::createInstance);\n ProxyControl::registerMetaData(html::HTMLTableDataCellElement::getMetaData(), Proxy_Impl<ProxyObject, html::HTMLTableDataCellElement_Bridge<Any, invoke> >::createInstance);\n ProxyControl::registerMetaData(html::HTMLTableElement::getMetaData(), Proxy_Impl<ProxyObject, html::HTMLTableElement_Bridge<Any, invoke> >::createInstance);\n ProxyControl::registerMetaData(html::HTMLTableHeaderCellElement::getMetaData(), Proxy_Impl<ProxyObject, html::HTMLTableHeaderCellElement_Bridge<Any, invoke> >::createInstance);\n ProxyControl::registerMetaData(html::HTMLTableRowElement::getMetaData(), Proxy_Impl<ProxyObject, html::HTMLTableRowElement_Bridge<Any, invoke> >::createInstance);\n ProxyControl::registerMetaData(html::HTMLTableSectionElement::getMetaData(), Proxy_Impl<ProxyObject, html::HTMLTableSectionElement_Bridge<Any, invoke> >::createInstance);\n ProxyControl::registerMetaData(html::HTMLTextAreaElement::getMetaData(), Proxy_Impl<ProxyObject, html::HTMLTextAreaElement_Bridge<Any, invoke> >::createInstance);\n ProxyControl::registerMetaData(html::HTMLTimeElement::getMetaData(), Proxy_Impl<ProxyObject, html::HTMLTimeElement_Bridge<Any, invoke> >::createInstance);\n ProxyControl::registerMetaData(html::HTMLTitleElement::getMetaData(), Proxy_Impl<ProxyObject, html::HTMLTitleElement_Bridge<Any, invoke> >::createInstance);\n ProxyControl::registerMetaData(html::HTMLUListElement::getMetaData(), Proxy_Impl<ProxyObject, html::HTMLUListElement_Bridge<Any, invoke> >::createInstance);\n ProxyControl::registerMetaData(html::HTMLUnknownElement::getMetaData(), Proxy_Impl<ProxyObject, html::HTMLUnknownElement_Bridge<Any, invoke> >::createInstance);\n}\n<commit_msg>(initializeHtmlMetaDataO_U) : Clean up.<commit_after>\/*\n * Copyright 2008-2010 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"esnpapi.h\"\n#include \"proxyImpl.h\"\n\n#include <org\/w3c\/dom.h>\n\nusing namespace org::w3c::dom;\n\nvoid initializeHtmlMetaDataO_U()\n{\n ProxyControl::registerMetaData(html::HTMLObjectElement::getMetaData(), Proxy_Impl<ProxyObject, html::HTMLObjectElement_Bridge<Any, invoke> >::createInstance);\n ProxyControl::registerMetaData(html::HTMLOListElement::getMetaData(), Proxy_Impl<ProxyObject, html::HTMLOListElement_Bridge<Any, invoke> >::createInstance);\n ProxyControl::registerMetaData(html::HTMLOptGroupElement::getMetaData(), Proxy_Impl<ProxyObject, html::HTMLOptGroupElement_Bridge<Any, invoke> >::createInstance);\n ProxyControl::registerMetaData(html::HTMLOptionElement::getMetaData(), Proxy_Impl<ProxyObject, html::HTMLOptionElement_Bridge<Any, invoke> >::createInstance);\n ProxyControl::registerMetaData(html::HTMLOptionsCollection::getMetaData(), Proxy_Impl<ProxyObject, html::HTMLOptionsCollection_Bridge<Any, invoke> >::createInstance);\n ProxyControl::registerMetaData(html::HTMLOutputElement::getMetaData(), Proxy_Impl<ProxyObject, html::HTMLOutputElement_Bridge<Any, invoke> >::createInstance);\n ProxyControl::registerMetaData(html::HTMLParagraphElement::getMetaData(), Proxy_Impl<ProxyObject, html::HTMLParagraphElement_Bridge<Any, invoke> >::createInstance);\n ProxyControl::registerMetaData(html::HTMLParamElement::getMetaData(), Proxy_Impl<ProxyObject, html::HTMLParamElement_Bridge<Any, invoke> >::createInstance);\n ProxyControl::registerMetaData(html::HTMLPreElement::getMetaData(), Proxy_Impl<ProxyObject, html::HTMLPreElement_Bridge<Any, invoke> >::createInstance);\n ProxyControl::registerMetaData(html::HTMLProgressElement::getMetaData(), Proxy_Impl<ProxyObject, html::HTMLProgressElement_Bridge<Any, invoke> >::createInstance);\n ProxyControl::registerMetaData(html::HTMLPropertiesCollection::getMetaData(), Proxy_Impl<ProxyObject, html::HTMLPropertiesCollection_Bridge<Any, invoke> >::createInstance);\n ProxyControl::registerMetaData(html::HTMLQuoteElement::getMetaData(), Proxy_Impl<ProxyObject, html::HTMLQuoteElement_Bridge<Any, invoke> >::createInstance);\n ProxyControl::registerMetaData(html::HTMLScriptElement::getMetaData(), Proxy_Impl<ProxyObject, html::HTMLScriptElement_Bridge<Any, invoke> >::createInstance);\n ProxyControl::registerMetaData(html::HTMLSelectElement::getMetaData(), Proxy_Impl<ProxyObject, html::HTMLSelectElement_Bridge<Any, invoke> >::createInstance);\n ProxyControl::registerMetaData(html::HTMLSourceElement::getMetaData(), Proxy_Impl<ProxyObject, html::HTMLSourceElement_Bridge<Any, invoke> >::createInstance);\n ProxyControl::registerMetaData(html::HTMLSpanElement::getMetaData(), Proxy_Impl<ProxyObject, html::HTMLSpanElement_Bridge<Any, invoke> >::createInstance);\n ProxyControl::registerMetaData(html::HTMLStyleElement::getMetaData(), Proxy_Impl<ProxyObject, html::HTMLStyleElement_Bridge<Any, invoke> >::createInstance);\n ProxyControl::registerMetaData(html::HTMLTableCaptionElement::getMetaData(), Proxy_Impl<ProxyObject, html::HTMLTableCaptionElement_Bridge<Any, invoke> >::createInstance);\n ProxyControl::registerMetaData(html::HTMLTableCellElement::getMetaData(), Proxy_Impl<ProxyObject, html::HTMLTableCellElement_Bridge<Any, invoke> >::createInstance);\n ProxyControl::registerMetaData(html::HTMLTableColElement::getMetaData(), Proxy_Impl<ProxyObject, html::HTMLTableColElement_Bridge<Any, invoke> >::createInstance);\n ProxyControl::registerMetaData(html::HTMLTableDataCellElement::getMetaData(), Proxy_Impl<ProxyObject, html::HTMLTableDataCellElement_Bridge<Any, invoke> >::createInstance);\n ProxyControl::registerMetaData(html::HTMLTableElement::getMetaData(), Proxy_Impl<ProxyObject, html::HTMLTableElement_Bridge<Any, invoke> >::createInstance);\n ProxyControl::registerMetaData(html::HTMLTableHeaderCellElement::getMetaData(), Proxy_Impl<ProxyObject, html::HTMLTableHeaderCellElement_Bridge<Any, invoke> >::createInstance);\n ProxyControl::registerMetaData(html::HTMLTableRowElement::getMetaData(), Proxy_Impl<ProxyObject, html::HTMLTableRowElement_Bridge<Any, invoke> >::createInstance);\n ProxyControl::registerMetaData(html::HTMLTableSectionElement::getMetaData(), Proxy_Impl<ProxyObject, html::HTMLTableSectionElement_Bridge<Any, invoke> >::createInstance);\n ProxyControl::registerMetaData(html::HTMLTextAreaElement::getMetaData(), Proxy_Impl<ProxyObject, html::HTMLTextAreaElement_Bridge<Any, invoke> >::createInstance);\n ProxyControl::registerMetaData(html::HTMLTimeElement::getMetaData(), Proxy_Impl<ProxyObject, html::HTMLTimeElement_Bridge<Any, invoke> >::createInstance);\n ProxyControl::registerMetaData(html::HTMLTitleElement::getMetaData(), Proxy_Impl<ProxyObject, html::HTMLTitleElement_Bridge<Any, invoke> >::createInstance);\n ProxyControl::registerMetaData(html::HTMLUListElement::getMetaData(), Proxy_Impl<ProxyObject, html::HTMLUListElement_Bridge<Any, invoke> >::createInstance);\n ProxyControl::registerMetaData(html::HTMLUnknownElement::getMetaData(), Proxy_Impl<ProxyObject, html::HTMLUnknownElement_Bridge<Any, invoke> >::createInstance);\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright 2014–2016 The SmartSqlite contributors (see NOTICE.txt)\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n#include <cstdio>\n#include <memory>\n#include <string>\n\n#include <gmock\/gmock.h>\n\n#include \"smartsqlite\/connection.h\"\n#include \"smartsqlite\/exceptions.h\"\n\nusing namespace testing;\n\nnamespace {\n\n\/\/ 96B = 768b\nstd::string SOME_KEY =\n \"MTIzNDU2Nzg5MDEyMzQ1Njc4OTAxMjM0\"\n \"NTY3ODkwMTIxMjM0NTY3ODkwMTIzNDU2\"\n \"Nzg5MDEyMzQ1Njc4OTAxMjEyMzQ1Njc4\"\n \"OTAxMjM0NTY3ODkwMTIzNDU2Nzg5MDEy\";\nstd::string ANOTHER_KEY =\n \"MDk4NzY1NDMyMTA5ODc2NTQzMjEwOTg3\"\n \"NjU0MzIxMDkwOTg3NjU0MzIxMDk4NzY1\"\n \"NDMyMTA5ODc2NTQzMjEwOTA5ODc2NTQz\"\n \"MjEwOTg3NjU0MzIxMDk4NzY1NDMyMTA5\";\n\n}\n\nclass BotanSqlite3: public Test\n{\nprotected:\n BotanSqlite3()\n : dbFilename_(tempDbName())\n , attachedFilename_(tempDbName())\n {\n }\n\n std::string tempDbName()\n {\n return std::string(std::tmpnam(nullptr)) + \".db\";\n }\n\n void connect(std::string filename = \"\")\n {\n if (filename.empty()) filename = dbFilename_;\n connection_ = std::unique_ptr<SmartSqlite::Connection>(\n new SmartSqlite::Connection(filename));\n }\n\n void disconnect()\n {\n ASSERT_THAT(connection_, Not(IsNull()));\n connection_.reset();\n }\n\n void deleteDb(const std::string &path)\n {\n ASSERT_THAT(path, Not(IsEmpty()));\n std::remove(path.c_str());\n }\n\n void setKey(const std::string &key)\n {\n connection_->setKey(key);\n }\n\n void rekey(const std::string &key)\n {\n connection_->changeKey(key);\n }\n\n void createTable(const std::string db = \"main\")\n {\n connection_->exec(std::string(\"CREATE TABLE \") + db + \".tbl (foo INT, bar TEXT)\");\n connection_->exec(std::string(\"INSERT INTO \") + db + \".tbl VALUES (21, 'half the truth')\");\n connection_->exec(std::string(\"INSERT INTO \") + db + \".tbl VALUES (42, 'the truth')\");\n }\n\n void attach()\n {\n connection_->exec(\n std::string(\"ATTACH DATABASE '\") + attachedFilename_ + \"' \"\n + \"AS att\");\n }\n\n void attachWithKey(const std::string &key)\n {\n connection_->exec(\n std::string(\"ATTACH DATABASE '\") + attachedFilename_ + \"' \"\n + \"AS att KEY '\" + key + \"'\");\n }\n\n void checkForTestData()\n {\n auto stmt = connection_->prepare(\"SELECT * FROM tbl\");\n\n auto rowIter = stmt.begin();\n ASSERT_THAT(rowIter, Not(Eq(stmt.end())));\n\n EXPECT_THAT(rowIter->get<int>(0), Eq(21));\n EXPECT_THAT(rowIter->get<std::string>(1), Eq(\"half the truth\"));\n\n ++rowIter;\n ASSERT_THAT(rowIter, Not(Eq(stmt.end())));\n\n EXPECT_THAT(rowIter->get<int>(0), Eq(42));\n EXPECT_THAT(rowIter->get<std::string>(1), Eq(\"the truth\"));\n\n ++rowIter;\n ASSERT_THAT(rowIter, Eq(stmt.end()));\n }\n\n std::string dbFilename_;\n std::string attachedFilename_;\n std::unique_ptr<SmartSqlite::Connection> connection_;\n};\n\n\nTEST_F(BotanSqlite3, canAccessEncryptedDatabase)\n{\n connect();\n setKey(SOME_KEY);\n createTable();\n disconnect();\n\n connect();\n setKey(SOME_KEY);\n checkForTestData();\n disconnect();\n deleteDb(dbFilename_);\n}\n\nTEST_F(BotanSqlite3, preventsAccessWithoutKey)\n{\n connect();\n setKey(SOME_KEY);\n createTable();\n disconnect();\n\n connect();\n EXPECT_THROW(checkForTestData(), SmartSqlite::SqliteException);\n disconnect();\n deleteDb(dbFilename_);\n}\n\nTEST_F(BotanSqlite3, preventsAccessWithWrongKey)\n{\n connect();\n setKey(SOME_KEY);\n createTable();\n disconnect();\n\n connect();\n setKey(ANOTHER_KEY);\n EXPECT_THROW(checkForTestData(), SmartSqlite::SqliteException);\n disconnect();\n deleteDb(dbFilename_);\n}\n\nTEST_F(BotanSqlite3, preventsShortKey)\n{\n auto shortKey = SOME_KEY;\n shortKey.pop_back();\n\n connect();\n EXPECT_THROW(setKey(shortKey), SmartSqlite::SqliteException);\n disconnect();\n deleteDb(dbFilename_);\n}\n\nTEST_F(BotanSqlite3, preventsLongKey)\n{\n auto longKey = SOME_KEY;\n longKey.push_back('0');\n\n connect();\n EXPECT_THROW(setKey(longKey), SmartSqlite::SqliteException);\n disconnect();\n deleteDb(dbFilename_);\n}\n\nTEST_F(BotanSqlite3, preventsInvalidBase64Key)\n{\n auto invalidKey = SOME_KEY;\n invalidKey.back() = 'x';\n\n connect();\n EXPECT_THROW(setKey(invalidKey), SmartSqlite::SqliteException);\n disconnect();\n deleteDb(dbFilename_);\n}\n\nTEST_F(BotanSqlite3, encryptDatabase)\n{\n connect();\n createTable();\n disconnect();\n\n connect();\n rekey(SOME_KEY);\n checkForTestData();\n disconnect();\n\n connect();\n setKey(SOME_KEY);\n checkForTestData();\n disconnect();\n\n deleteDb(dbFilename_);\n}\n\nTEST_F(BotanSqlite3, changeKey)\n{\n connect();\n setKey(SOME_KEY);\n createTable();\n disconnect();\n\n connect();\n setKey(SOME_KEY);\n rekey(ANOTHER_KEY);\n checkForTestData();\n disconnect();\n\n connect();\n setKey(ANOTHER_KEY);\n checkForTestData();\n disconnect();\n\n deleteDb(dbFilename_);\n}\n\nTEST_F(BotanSqlite3, decryptDatabase)\n{\n connect();\n setKey(SOME_KEY);\n createTable();\n disconnect();\n\n connect();\n setKey(SOME_KEY);\n rekey(\"\");\n checkForTestData();\n disconnect();\n\n connect();\n checkForTestData();\n disconnect();\n\n deleteDb(dbFilename_);\n}\n\nTEST_F(BotanSqlite3, vacuumWorks)\n{\n connect();\n setKey(SOME_KEY);\n createTable();\n disconnect();\n\n connect();\n setKey(SOME_KEY);\n connection_->exec(\"VACUUM\");\n disconnect();\n\n connect();\n setKey(SOME_KEY);\n checkForTestData();\n disconnect();\n deleteDb(dbFilename_);\n}\n\nTEST_F(BotanSqlite3, attachWithSameKey)\n{\n connect();\n setKey(SOME_KEY);\n createTable();\n\n attach();\n createTable(\"att\");\n disconnect();\n\n connect(attachedFilename_);\n setKey(SOME_KEY);\n checkForTestData();\n disconnect();\n\n deleteDb(dbFilename_);\n deleteDb(attachedFilename_);\n}\n\nTEST_F(BotanSqlite3, attachWithoutKey)\n{\n connect();\n setKey(SOME_KEY);\n createTable();\n\n attachWithKey(\"\");\n createTable(\"att\");\n disconnect();\n\n connect(attachedFilename_);\n checkForTestData();\n disconnect();\n\n deleteDb(dbFilename_);\n deleteDb(attachedFilename_);\n}\n\nTEST_F(BotanSqlite3, attachWithDifferentKey)\n{\n connect();\n setKey(SOME_KEY);\n createTable();\n\n attachWithKey(ANOTHER_KEY);\n createTable(\"att\");\n disconnect();\n\n connect(attachedFilename_);\n setKey(ANOTHER_KEY);\n checkForTestData();\n disconnect();\n\n deleteDb(dbFilename_);\n deleteDb(attachedFilename_);\n}\n\nTEST_F(BotanSqlite3, attachWhenMainIsUnencrypted)\n{\n connect();\n createTable();\n\n attachWithKey(SOME_KEY);\n createTable(\"att\");\n disconnect();\n\n connect(attachedFilename_);\n setKey(SOME_KEY);\n checkForTestData();\n disconnect();\n\n deleteDb(dbFilename_);\n deleteDb(attachedFilename_);\n}\n<commit_msg>botansqlite3: Fix key validation tests<commit_after>\/*\n * Copyright 2014–2016 The SmartSqlite contributors (see NOTICE.txt)\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n#include <cstdio>\n#include <memory>\n#include <string>\n\n#include <gmock\/gmock.h>\n\n#include \"smartsqlite\/connection.h\"\n#include \"smartsqlite\/exceptions.h\"\n\nusing namespace testing;\n\nnamespace {\n\n\/\/ 96B = 768b\nstd::string SOME_KEY =\n \"MTIzNDU2Nzg5MDEyMzQ1Njc4OTAxMjM0\"\n \"NTY3ODkwMTIxMjM0NTY3ODkwMTIzNDU2\"\n \"Nzg5MDEyMzQ1Njc4OTAxMjEyMzQ1Njc4\"\n \"OTAxMjM0NTY3ODkwMTIzNDU2Nzg5MDEy\";\nstd::string ANOTHER_KEY =\n \"MDk4NzY1NDMyMTA5ODc2NTQzMjEwOTg3\"\n \"NjU0MzIxMDkwOTg3NjU0MzIxMDk4NzY1\"\n \"NDMyMTA5ODc2NTQzMjEwOTA5ODc2NTQz\"\n \"MjEwOTg3NjU0MzIxMDk4NzY1NDMyMTA5\";\n\n}\n\nclass BotanSqlite3: public Test\n{\nprotected:\n BotanSqlite3()\n : dbFilename_(tempDbName())\n , attachedFilename_(tempDbName())\n {\n }\n\n std::string tempDbName()\n {\n return std::string(std::tmpnam(nullptr)) + \".db\";\n }\n\n void connect(std::string filename = \"\")\n {\n if (filename.empty()) filename = dbFilename_;\n connection_ = std::unique_ptr<SmartSqlite::Connection>(\n new SmartSqlite::Connection(filename));\n }\n\n void disconnect()\n {\n ASSERT_THAT(connection_, Not(IsNull()));\n connection_.reset();\n }\n\n void deleteDb(const std::string &path)\n {\n ASSERT_THAT(path, Not(IsEmpty()));\n std::remove(path.c_str());\n }\n\n void setKey(const std::string &key)\n {\n connection_->setKey(key);\n }\n\n void rekey(const std::string &key)\n {\n connection_->changeKey(key);\n }\n\n void createTable(const std::string db = \"main\")\n {\n connection_->exec(std::string(\"CREATE TABLE \") + db + \".tbl (foo INT, bar TEXT)\");\n connection_->exec(std::string(\"INSERT INTO \") + db + \".tbl VALUES (21, 'half the truth')\");\n connection_->exec(std::string(\"INSERT INTO \") + db + \".tbl VALUES (42, 'the truth')\");\n }\n\n void attach()\n {\n connection_->exec(\n std::string(\"ATTACH DATABASE '\") + attachedFilename_ + \"' \"\n + \"AS att\");\n }\n\n void attachWithKey(const std::string &key)\n {\n connection_->exec(\n std::string(\"ATTACH DATABASE '\") + attachedFilename_ + \"' \"\n + \"AS att KEY '\" + key + \"'\");\n }\n\n void checkForTestData()\n {\n auto stmt = connection_->prepare(\"SELECT * FROM tbl\");\n\n auto rowIter = stmt.begin();\n ASSERT_THAT(rowIter, Not(Eq(stmt.end())));\n\n EXPECT_THAT(rowIter->get<int>(0), Eq(21));\n EXPECT_THAT(rowIter->get<std::string>(1), Eq(\"half the truth\"));\n\n ++rowIter;\n ASSERT_THAT(rowIter, Not(Eq(stmt.end())));\n\n EXPECT_THAT(rowIter->get<int>(0), Eq(42));\n EXPECT_THAT(rowIter->get<std::string>(1), Eq(\"the truth\"));\n\n ++rowIter;\n ASSERT_THAT(rowIter, Eq(stmt.end()));\n }\n\n std::string dbFilename_;\n std::string attachedFilename_;\n std::unique_ptr<SmartSqlite::Connection> connection_;\n};\n\n\nTEST_F(BotanSqlite3, canAccessEncryptedDatabase)\n{\n connect();\n setKey(SOME_KEY);\n createTable();\n disconnect();\n\n connect();\n setKey(SOME_KEY);\n checkForTestData();\n disconnect();\n deleteDb(dbFilename_);\n}\n\nTEST_F(BotanSqlite3, preventsAccessWithoutKey)\n{\n connect();\n setKey(SOME_KEY);\n createTable();\n disconnect();\n\n connect();\n EXPECT_THROW(checkForTestData(), SmartSqlite::SqliteException);\n disconnect();\n deleteDb(dbFilename_);\n}\n\nTEST_F(BotanSqlite3, preventsAccessWithWrongKey)\n{\n connect();\n setKey(SOME_KEY);\n createTable();\n disconnect();\n\n connect();\n setKey(ANOTHER_KEY);\n EXPECT_THROW(checkForTestData(), SmartSqlite::SqliteException);\n disconnect();\n deleteDb(dbFilename_);\n}\n\nTEST_F(BotanSqlite3, preventsShortKey)\n{\n auto shortKey = SOME_KEY;\n shortKey.back() = '='; \/\/ remove last char\n\n connect();\n EXPECT_THROW(setKey(shortKey), SmartSqlite::SqliteException);\n disconnect();\n deleteDb(dbFilename_);\n}\n\nTEST_F(BotanSqlite3, preventsLongKey)\n{\n auto longKey = SOME_KEY;\n longKey.append(\"Mw==\"); \/\/ \"3\" + padding\n\n connect();\n EXPECT_THROW(setKey(longKey), SmartSqlite::SqliteException);\n disconnect();\n deleteDb(dbFilename_);\n}\n\nTEST_F(BotanSqlite3, preventsInvalidBase64Key)\n{\n auto invalidKey = SOME_KEY;\n invalidKey.back() = '%';\n\n connect();\n EXPECT_THROW(setKey(invalidKey), SmartSqlite::SqliteException);\n disconnect();\n deleteDb(dbFilename_);\n}\n\nTEST_F(BotanSqlite3, encryptDatabase)\n{\n connect();\n createTable();\n disconnect();\n\n connect();\n rekey(SOME_KEY);\n checkForTestData();\n disconnect();\n\n connect();\n setKey(SOME_KEY);\n checkForTestData();\n disconnect();\n\n deleteDb(dbFilename_);\n}\n\nTEST_F(BotanSqlite3, changeKey)\n{\n connect();\n setKey(SOME_KEY);\n createTable();\n disconnect();\n\n connect();\n setKey(SOME_KEY);\n rekey(ANOTHER_KEY);\n checkForTestData();\n disconnect();\n\n connect();\n setKey(ANOTHER_KEY);\n checkForTestData();\n disconnect();\n\n deleteDb(dbFilename_);\n}\n\nTEST_F(BotanSqlite3, decryptDatabase)\n{\n connect();\n setKey(SOME_KEY);\n createTable();\n disconnect();\n\n connect();\n setKey(SOME_KEY);\n rekey(\"\");\n checkForTestData();\n disconnect();\n\n connect();\n checkForTestData();\n disconnect();\n\n deleteDb(dbFilename_);\n}\n\nTEST_F(BotanSqlite3, vacuumWorks)\n{\n connect();\n setKey(SOME_KEY);\n createTable();\n disconnect();\n\n connect();\n setKey(SOME_KEY);\n connection_->exec(\"VACUUM\");\n disconnect();\n\n connect();\n setKey(SOME_KEY);\n checkForTestData();\n disconnect();\n deleteDb(dbFilename_);\n}\n\nTEST_F(BotanSqlite3, attachWithSameKey)\n{\n connect();\n setKey(SOME_KEY);\n createTable();\n\n attach();\n createTable(\"att\");\n disconnect();\n\n connect(attachedFilename_);\n setKey(SOME_KEY);\n checkForTestData();\n disconnect();\n\n deleteDb(dbFilename_);\n deleteDb(attachedFilename_);\n}\n\nTEST_F(BotanSqlite3, attachWithoutKey)\n{\n connect();\n setKey(SOME_KEY);\n createTable();\n\n attachWithKey(\"\");\n createTable(\"att\");\n disconnect();\n\n connect(attachedFilename_);\n checkForTestData();\n disconnect();\n\n deleteDb(dbFilename_);\n deleteDb(attachedFilename_);\n}\n\nTEST_F(BotanSqlite3, attachWithDifferentKey)\n{\n connect();\n setKey(SOME_KEY);\n createTable();\n\n attachWithKey(ANOTHER_KEY);\n createTable(\"att\");\n disconnect();\n\n connect(attachedFilename_);\n setKey(ANOTHER_KEY);\n checkForTestData();\n disconnect();\n\n deleteDb(dbFilename_);\n deleteDb(attachedFilename_);\n}\n\nTEST_F(BotanSqlite3, attachWhenMainIsUnencrypted)\n{\n connect();\n createTable();\n\n attachWithKey(SOME_KEY);\n createTable(\"att\");\n disconnect();\n\n connect(attachedFilename_);\n setKey(SOME_KEY);\n checkForTestData();\n disconnect();\n\n deleteDb(dbFilename_);\n deleteDb(attachedFilename_);\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2012-2013 The Cryptonote developers\n\/\/ Distributed under the MIT\/X11 software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n\n#include <sstream>\n#include <numeric>\n#include <boost\/utility\/value_init.hpp>\n#include <boost\/interprocess\/detail\/atomic.hpp>\n#include <boost\/limits.hpp>\n#include <boost\/foreach.hpp>\n#include \"misc_language.h\"\n#include \"include_base_utils.h\"\n#include \"cryptonote_basic_impl.h\"\n#include \"cryptonote_format_utils.h\"\n#include \"file_io_utils.h\"\n#include \"common\/command_line.h\"\n#include \"string_coding.h\"\n#include \"storages\/portable_storage_template_helper.h\"\n\nusing namespace epee;\n\n#include \"miner.h\"\n\n\n\nnamespace cryptonote\n{\n\n namespace\n {\n const command_line::arg_descriptor<std::string> arg_extra_messages = {\"extra-messages-file\", \"Specify file for extra messages to include into coinbase transactions\", \"\", true};\n const command_line::arg_descriptor<std::string> arg_start_mining = {\"start-mining\", \"Specify wallet address to mining for\", \"\", true};\n const command_line::arg_descriptor<uint32_t> arg_mining_threads = {\"mining-threads\", \"Specify mining threads count\", 0, true};\n }\n\n\n miner::miner(i_miner_handler* phandler):m_stop(1),\n m_template(boost::value_initialized<block>()),\n m_template_no(0),\n m_diffic(0),\n m_thread_index(0),\n m_phandler(phandler),\n m_height(0),\n m_pausers_count(0), \n m_threads_total(0),\n m_starter_nonce(0), \n m_last_hr_merge_time(0),\n m_hashes(0),\n m_do_print_hashrate(false),\n m_do_mining(false),\n m_current_hash_rate(0)\n {\n\n }\n \/\/-----------------------------------------------------------------------------------------------------\n miner::~miner()\n {\n stop();\n }\n \/\/-----------------------------------------------------------------------------------------------------\n bool miner::set_block_template(const block& bl, const difficulty_type& di, uint64_t height)\n {\n CRITICAL_REGION_LOCAL(m_template_lock);\n m_template = bl;\n m_diffic = di;\n m_height = height;\n ++m_template_no;\n m_starter_nonce = crypto::rand<uint32_t>();\n return true;\n }\n \/\/-----------------------------------------------------------------------------------------------------\n bool miner::on_block_chain_update()\n {\n if(!is_mining())\n return true;\n\n return request_block_template();\n }\n \/\/-----------------------------------------------------------------------------------------------------\n bool miner::request_block_template()\n {\n block bl = AUTO_VAL_INIT(bl);\n difficulty_type di = AUTO_VAL_INIT(di);\n uint64_t height = AUTO_VAL_INIT(height);\n cryptonote::blobdata extra_nonce; \n if(m_extra_messages.size() && m_config.current_extra_message_index < m_extra_messages.size())\n {\n extra_nonce = m_extra_messages[m_config.current_extra_message_index];\n }\n\n if(!m_phandler->get_block_template(bl, m_mine_address, di, height, extra_nonce))\n {\n LOG_ERROR(\"Failed to get_block_template(), stopping mining\");\n return false;\n }\n set_block_template(bl, di, height);\n return true;\n }\n \/\/-----------------------------------------------------------------------------------------------------\n bool miner::on_idle()\n {\n m_update_block_template_interval.do_call([&](){\n if(is_mining())request_block_template();\n return true;\n });\n\n m_update_merge_hr_interval.do_call([&](){\n merge_hr();\n return true;\n });\n \n return true;\n }\n \/\/-----------------------------------------------------------------------------------------------------\n void miner::do_print_hashrate(bool do_hr)\n {\n m_do_print_hashrate = do_hr;\n }\n \/\/-----------------------------------------------------------------------------------------------------\n void miner::merge_hr()\n {\n if(m_last_hr_merge_time && is_mining())\n {\n m_current_hash_rate = m_hashes * 1000 \/ ((misc_utils::get_tick_count() - m_last_hr_merge_time + 1));\n CRITICAL_REGION_LOCAL(m_last_hash_rates_lock);\n m_last_hash_rates.push_back(m_current_hash_rate);\n if(m_last_hash_rates.size() > 19)\n m_last_hash_rates.pop_front();\n if(m_do_print_hashrate)\n {\n uint64_t total_hr = std::accumulate(m_last_hash_rates.begin(), m_last_hash_rates.end(), 0);\n float hr = static_cast<float>(total_hr)\/static_cast<float>(m_last_hash_rates.size());\n std::cout << \"hashrate: \" << std::setprecision(4) << std::fixed << hr << ENDL;\n }\n }\n m_last_hr_merge_time = misc_utils::get_tick_count();\n m_hashes = 0;\n }\n \/\/-----------------------------------------------------------------------------------------------------\n void miner::init_options(boost::program_options::options_description& desc)\n {\n command_line::add_arg(desc, arg_extra_messages);\n command_line::add_arg(desc, arg_start_mining);\n command_line::add_arg(desc, arg_mining_threads);\n }\n \/\/-----------------------------------------------------------------------------------------------------\n bool miner::init(const boost::program_options::variables_map& vm)\n {\n if(command_line::has_arg(vm, arg_extra_messages))\n {\n std::string buff;\n bool r = file_io_utils::load_file_to_string(command_line::get_arg(vm, arg_extra_messages), buff);\n CHECK_AND_ASSERT_MES(r, false, \"Failed to load file with extra messages: \" << command_line::get_arg(vm, arg_extra_messages));\n std::vector<std::string> extra_vec;\n boost::split(extra_vec, buff, boost::is_any_of(\"\\n\"), boost::token_compress_on );\n m_extra_messages.resize(extra_vec.size());\n for(size_t i = 0; i != extra_vec.size(); i++)\n {\n string_tools::trim(extra_vec[i]);\n if(!extra_vec[i].size())\n continue;\n std::string buff = string_encoding::base64_decode(extra_vec[i]);\n if(buff != \"0\")\n m_extra_messages[i] = buff;\n }\n m_config_folder_path = boost::filesystem::path(command_line::get_arg(vm, arg_extra_messages)).parent_path().string();\n m_config = AUTO_VAL_INIT(m_config);\n epee::serialization::load_t_from_json_file(m_config, m_config_folder_path + \"\/\" + MINER_CONFIG_FILE_NAME);\n LOG_PRINT_L0(\"Loaded \" << m_extra_messages.size() << \" extra messages, current index \" << m_config.current_extra_message_index);\n }\n\n if(command_line::has_arg(vm, arg_start_mining))\n {\n if(!cryptonote::get_account_address_from_str(m_mine_address, command_line::get_arg(vm, arg_start_mining)))\n {\n LOG_ERROR(\"Target account address \" << command_line::get_arg(vm, arg_start_mining) << \" has wrong format, starting daemon canceled\");\n return false;\n }\n m_threads_total = 1;\n m_do_mining = true;\n if(command_line::has_arg(vm, arg_mining_threads))\n {\n m_threads_total = command_line::get_arg(vm, arg_mining_threads);\n }\n }\n\n return true;\n }\n \/\/-----------------------------------------------------------------------------------------------------\n bool miner::is_mining() const\n {\n return !m_stop;\n }\n \/\/-----------------------------------------------------------------------------------------------------\n const account_public_address& miner::get_mining_address() const\n {\n return m_mine_address;\n }\n \/\/-----------------------------------------------------------------------------------------------------\n uint32_t miner::get_threads_count() const {\n return m_threads_total;\n }\n \/\/----------------------------------------------------------------------------------------------------- \n bool miner::start(const account_public_address& adr, size_t threads_count, const boost::thread::attributes& attrs)\n {\n m_mine_address = adr;\n m_threads_total = static_cast<uint32_t>(threads_count);\n m_starter_nonce = crypto::rand<uint32_t>();\n CRITICAL_REGION_LOCAL(m_threads_lock);\n if(is_mining())\n {\n LOG_ERROR(\"Starting miner but it's already started\");\n return false;\n }\n\n if(!m_threads.empty())\n {\n LOG_ERROR(\"Unable to start miner because there are active mining threads\");\n return false;\n }\n\n if(!m_template_no)\n request_block_template();\/\/lets update block template\n\n boost::interprocess::ipcdetail::atomic_write32(&m_stop, 0);\n boost::interprocess::ipcdetail::atomic_write32(&m_thread_index, 0);\n\n for(size_t i = 0; i != threads_count; i++)\n {\n m_threads.push_back(boost::thread(attrs, boost::bind(&miner::worker_thread, this)));\n }\n\n LOG_PRINT_L0(\"Mining has started with \" << threads_count << \" threads, good luck!\" )\n return true;\n }\n \/\/-----------------------------------------------------------------------------------------------------\n uint64_t miner::get_speed() const\n {\n if(is_mining()) {\n return m_current_hash_rate;\n }\n else {\n return 0;\n }\n }\n \/\/-----------------------------------------------------------------------------------------------------\n void miner::send_stop_signal()\n {\n boost::interprocess::ipcdetail::atomic_write32(&m_stop, 1);\n }\n \/\/-----------------------------------------------------------------------------------------------------\n bool miner::stop()\n {\n send_stop_signal();\n CRITICAL_REGION_LOCAL(m_threads_lock);\n\n BOOST_FOREACH(boost::thread& th, m_threads)\n th.join();\n\n m_threads.clear();\n LOG_PRINT_L0(\"Mining has been stopped, \" << m_threads.size() << \" finished\" );\n return true;\n }\n \/\/-----------------------------------------------------------------------------------------------------\n bool miner::find_nonce_for_given_block(block& bl, const difficulty_type& diffic, uint64_t height)\n {\n for(; bl.nonce != std::numeric_limits<uint32_t>::max(); bl.nonce++)\n {\n crypto::hash h;\n get_block_longhash(bl, h, height);\n\n if(check_hash(h, diffic))\n {\n return true;\n }\n }\n return false;\n }\n \/\/-----------------------------------------------------------------------------------------------------\n void miner::on_synchronized()\n {\n if(m_do_mining)\n {\n boost::thread::attributes attrs;\n attrs.set_stack_size(THREAD_STACK_SIZE);\n\n start(m_mine_address, m_threads_total, attrs);\n }\n }\n \/\/-----------------------------------------------------------------------------------------------------\n void miner::pause()\n {\n CRITICAL_REGION_LOCAL(m_miners_count_lock);\n ++m_pausers_count;\n if(m_pausers_count == 1 && is_mining())\n LOG_PRINT_L2(\"MINING PAUSED\");\n }\n \/\/-----------------------------------------------------------------------------------------------------\n void miner::resume()\n {\n CRITICAL_REGION_LOCAL(m_miners_count_lock);\n --m_pausers_count;\n if(m_pausers_count < 0)\n {\n m_pausers_count = 0;\n LOG_PRINT_RED_L0(\"Unexpected miner::resume() called\");\n }\n if(!m_pausers_count && is_mining())\n LOG_PRINT_L2(\"MINING RESUMED\");\n }\n \/\/-----------------------------------------------------------------------------------------------------\n bool miner::worker_thread()\n {\n uint32_t th_local_index = boost::interprocess::ipcdetail::atomic_inc32(&m_thread_index);\n LOG_PRINT_L0(\"Miner thread was started [\"<< th_local_index << \"]\");\n log_space::log_singletone::set_thread_log_prefix(std::string(\"[miner \") + std::to_string(th_local_index) + \"]\");\n uint32_t nonce = m_starter_nonce + th_local_index;\n uint64_t height = 0;\n difficulty_type local_diff = 0;\n uint32_t local_template_ver = 0;\n block b;\n while(!m_stop)\n {\n if(m_pausers_count)\/\/anti split workaround\n {\n misc_utils::sleep_no_w(100);\n continue;\n }\n\n if(local_template_ver != m_template_no)\n {\n \n CRITICAL_REGION_BEGIN(m_template_lock);\n b = m_template;\n local_diff = m_diffic;\n height = m_height;\n CRITICAL_REGION_END();\n local_template_ver = m_template_no;\n nonce = m_starter_nonce + th_local_index;\n }\n\n if(!local_template_ver)\/\/no any set_block_template call\n {\n LOG_PRINT_L2(\"Block template not set yet\");\n epee::misc_utils::sleep_no_w(1000);\n continue;\n }\n\n b.nonce = nonce;\n crypto::hash h;\n get_block_longhash(b, h, height);\n\n if(check_hash(h, local_diff))\n {\n \/\/we lucky!\n ++m_config.current_extra_message_index;\n LOG_PRINT_GREEN(\"Found block for difficulty: \" << local_diff, LOG_LEVEL_0);\n if(!m_phandler->handle_block_found(b))\n {\n --m_config.current_extra_message_index;\n }else\n {\n \/\/success update, lets update config\n epee::serialization::store_t_to_json_file(m_config, m_config_folder_path + \"\/\" + MINER_CONFIG_FILE_NAME);\n }\n }\n nonce+=m_threads_total;\n ++m_hashes;\n }\n LOG_PRINT_L0(\"Miner thread stopped [\"<< th_local_index << \"]\");\n return true;\n }\n \/\/-----------------------------------------------------------------------------------------------------\n}\n\n<commit_msg>Update miner.cpp<commit_after>\/\/ Copyright (c) 2012-2013 The Cryptonote developers\n\/\/ Distributed under the MIT\/X11 software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n\n#include <sstream>\n#include <numeric>\n#include <boost\/utility\/value_init.hpp>\n#include <boost\/interprocess\/detail\/atomic.hpp>\n#include <boost\/limits.hpp>\n#include <boost\/foreach.hpp>\n#include \"misc_language.h\"\n#include \"include_base_utils.h\"\n#include \"cryptonote_basic_impl.h\"\n#include \"cryptonote_format_utils.h\"\n#include \"file_io_utils.h\"\n#include \"common\/command_line.h\"\n#include \"string_coding.h\"\n#include \"storages\/portable_storage_template_helper.h\"\n\nusing namespace epee;\n\n#include \"miner.h\"\n\n\nextern \"C\" void slow_hash_allocate_state();\nextern \"C\" void slow_hash_free_state();\nnamespace cryptonote\n{\n\n namespace\n {\n const command_line::arg_descriptor<std::string> arg_extra_messages = {\"extra-messages-file\", \"Specify file for extra messages to include into coinbase transactions\", \"\", true};\n const command_line::arg_descriptor<std::string> arg_start_mining = {\"start-mining\", \"Specify wallet address to mining for\", \"\", true};\n const command_line::arg_descriptor<uint32_t> arg_mining_threads = {\"mining-threads\", \"Specify mining threads count\", 0, true};\n }\n\n\n miner::miner(i_miner_handler* phandler):m_stop(1),\n m_template(boost::value_initialized<block>()),\n m_template_no(0),\n m_diffic(0),\n m_thread_index(0),\n m_phandler(phandler),\n m_height(0),\n m_pausers_count(0), \n m_threads_total(0),\n m_starter_nonce(0), \n m_last_hr_merge_time(0),\n m_hashes(0),\n m_do_print_hashrate(false),\n m_do_mining(false),\n m_current_hash_rate(0)\n {\n\n }\n \/\/-----------------------------------------------------------------------------------------------------\n miner::~miner()\n {\n stop();\n }\n \/\/-----------------------------------------------------------------------------------------------------\n bool miner::set_block_template(const block& bl, const difficulty_type& di, uint64_t height)\n {\n CRITICAL_REGION_LOCAL(m_template_lock);\n m_template = bl;\n m_diffic = di;\n m_height = height;\n ++m_template_no;\n m_starter_nonce = crypto::rand<uint32_t>();\n return true;\n }\n \/\/-----------------------------------------------------------------------------------------------------\n bool miner::on_block_chain_update()\n {\n if(!is_mining())\n return true;\n\n return request_block_template();\n }\n \/\/-----------------------------------------------------------------------------------------------------\n bool miner::request_block_template()\n {\n block bl = AUTO_VAL_INIT(bl);\n difficulty_type di = AUTO_VAL_INIT(di);\n uint64_t height = AUTO_VAL_INIT(height);\n cryptonote::blobdata extra_nonce; \n if(m_extra_messages.size() && m_config.current_extra_message_index < m_extra_messages.size())\n {\n extra_nonce = m_extra_messages[m_config.current_extra_message_index];\n }\n\n if(!m_phandler->get_block_template(bl, m_mine_address, di, height, extra_nonce))\n {\n LOG_ERROR(\"Failed to get_block_template(), stopping mining\");\n return false;\n }\n set_block_template(bl, di, height);\n return true;\n }\n \/\/-----------------------------------------------------------------------------------------------------\n bool miner::on_idle()\n {\n m_update_block_template_interval.do_call([&](){\n if(is_mining())request_block_template();\n return true;\n });\n\n m_update_merge_hr_interval.do_call([&](){\n merge_hr();\n return true;\n });\n \n return true;\n }\n \/\/-----------------------------------------------------------------------------------------------------\n void miner::do_print_hashrate(bool do_hr)\n {\n m_do_print_hashrate = do_hr;\n }\n \/\/-----------------------------------------------------------------------------------------------------\n void miner::merge_hr()\n {\n if(m_last_hr_merge_time && is_mining())\n {\n m_current_hash_rate = m_hashes * 1000 \/ ((misc_utils::get_tick_count() - m_last_hr_merge_time + 1));\n CRITICAL_REGION_LOCAL(m_last_hash_rates_lock);\n m_last_hash_rates.push_back(m_current_hash_rate);\n if(m_last_hash_rates.size() > 19)\n m_last_hash_rates.pop_front();\n if(m_do_print_hashrate)\n {\n uint64_t total_hr = std::accumulate(m_last_hash_rates.begin(), m_last_hash_rates.end(), 0);\n float hr = static_cast<float>(total_hr)\/static_cast<float>(m_last_hash_rates.size());\n std::cout << \"hashrate: \" << std::setprecision(4) << std::fixed << hr << ENDL;\n }\n }\n m_last_hr_merge_time = misc_utils::get_tick_count();\n m_hashes = 0;\n }\n \/\/-----------------------------------------------------------------------------------------------------\n void miner::init_options(boost::program_options::options_description& desc)\n {\n command_line::add_arg(desc, arg_extra_messages);\n command_line::add_arg(desc, arg_start_mining);\n command_line::add_arg(desc, arg_mining_threads);\n }\n \/\/-----------------------------------------------------------------------------------------------------\n bool miner::init(const boost::program_options::variables_map& vm)\n {\n if(command_line::has_arg(vm, arg_extra_messages))\n {\n std::string buff;\n bool r = file_io_utils::load_file_to_string(command_line::get_arg(vm, arg_extra_messages), buff);\n CHECK_AND_ASSERT_MES(r, false, \"Failed to load file with extra messages: \" << command_line::get_arg(vm, arg_extra_messages));\n std::vector<std::string> extra_vec;\n boost::split(extra_vec, buff, boost::is_any_of(\"\\n\"), boost::token_compress_on );\n m_extra_messages.resize(extra_vec.size());\n for(size_t i = 0; i != extra_vec.size(); i++)\n {\n string_tools::trim(extra_vec[i]);\n if(!extra_vec[i].size())\n continue;\n std::string buff = string_encoding::base64_decode(extra_vec[i]);\n if(buff != \"0\")\n m_extra_messages[i] = buff;\n }\n m_config_folder_path = boost::filesystem::path(command_line::get_arg(vm, arg_extra_messages)).parent_path().string();\n m_config = AUTO_VAL_INIT(m_config);\n epee::serialization::load_t_from_json_file(m_config, m_config_folder_path + \"\/\" + MINER_CONFIG_FILE_NAME);\n LOG_PRINT_L0(\"Loaded \" << m_extra_messages.size() << \" extra messages, current index \" << m_config.current_extra_message_index);\n }\n\n if(command_line::has_arg(vm, arg_start_mining))\n {\n if(!cryptonote::get_account_address_from_str(m_mine_address, command_line::get_arg(vm, arg_start_mining)))\n {\n LOG_ERROR(\"Target account address \" << command_line::get_arg(vm, arg_start_mining) << \" has wrong format, starting daemon canceled\");\n return false;\n }\n m_threads_total = 1;\n m_do_mining = true;\n if(command_line::has_arg(vm, arg_mining_threads))\n {\n m_threads_total = command_line::get_arg(vm, arg_mining_threads);\n }\n }\n\n return true;\n }\n \/\/-----------------------------------------------------------------------------------------------------\n bool miner::is_mining() const\n {\n return !m_stop;\n }\n \/\/-----------------------------------------------------------------------------------------------------\n const account_public_address& miner::get_mining_address() const\n {\n return m_mine_address;\n }\n \/\/-----------------------------------------------------------------------------------------------------\n uint32_t miner::get_threads_count() const {\n return m_threads_total;\n }\n \/\/----------------------------------------------------------------------------------------------------- \n bool miner::start(const account_public_address& adr, size_t threads_count, const boost::thread::attributes& attrs)\n {\n m_mine_address = adr;\n m_threads_total = static_cast<uint32_t>(threads_count);\n m_starter_nonce = crypto::rand<uint32_t>();\n CRITICAL_REGION_LOCAL(m_threads_lock);\n if(is_mining())\n {\n LOG_ERROR(\"Starting miner but it's already started\");\n return false;\n }\n\n if(!m_threads.empty())\n {\n LOG_ERROR(\"Unable to start miner because there are active mining threads\");\n return false;\n }\n\n if(!m_template_no)\n request_block_template();\/\/lets update block template\n\n boost::interprocess::ipcdetail::atomic_write32(&m_stop, 0);\n boost::interprocess::ipcdetail::atomic_write32(&m_thread_index, 0);\n\n for(size_t i = 0; i != threads_count; i++)\n {\n m_threads.push_back(boost::thread(attrs, boost::bind(&miner::worker_thread, this)));\n }\n\n LOG_PRINT_L0(\"Mining has started with \" << threads_count << \" threads, good luck!\" )\n return true;\n }\n \/\/-----------------------------------------------------------------------------------------------------\n uint64_t miner::get_speed() const\n {\n if(is_mining()) {\n return m_current_hash_rate;\n }\n else {\n return 0;\n }\n }\n \/\/-----------------------------------------------------------------------------------------------------\n void miner::send_stop_signal()\n {\n boost::interprocess::ipcdetail::atomic_write32(&m_stop, 1);\n }\n \/\/-----------------------------------------------------------------------------------------------------\n bool miner::stop()\n {\n send_stop_signal();\n CRITICAL_REGION_LOCAL(m_threads_lock);\n\n BOOST_FOREACH(boost::thread& th, m_threads)\n th.join();\n\n m_threads.clear();\n LOG_PRINT_L0(\"Mining has been stopped, \" << m_threads.size() << \" finished\" );\n return true;\n }\n \/\/-----------------------------------------------------------------------------------------------------\n bool miner::find_nonce_for_given_block(block& bl, const difficulty_type& diffic, uint64_t height)\n {\n for(; bl.nonce != std::numeric_limits<uint32_t>::max(); bl.nonce++)\n {\n crypto::hash h;\n get_block_longhash(bl, h, height);\n\n if(check_hash(h, diffic))\n {\n return true;\n }\n }\n return false;\n }\n \/\/-----------------------------------------------------------------------------------------------------\n void miner::on_synchronized()\n {\n if(m_do_mining)\n {\n boost::thread::attributes attrs;\n attrs.set_stack_size(THREAD_STACK_SIZE);\n\n start(m_mine_address, m_threads_total, attrs);\n }\n }\n \/\/-----------------------------------------------------------------------------------------------------\n void miner::pause()\n {\n CRITICAL_REGION_LOCAL(m_miners_count_lock);\n ++m_pausers_count;\n if(m_pausers_count == 1 && is_mining())\n LOG_PRINT_L2(\"MINING PAUSED\");\n }\n \/\/-----------------------------------------------------------------------------------------------------\n void miner::resume()\n {\n CRITICAL_REGION_LOCAL(m_miners_count_lock);\n --m_pausers_count;\n if(m_pausers_count < 0)\n {\n m_pausers_count = 0;\n LOG_PRINT_RED_L0(\"Unexpected miner::resume() called\");\n }\n if(!m_pausers_count && is_mining())\n LOG_PRINT_L2(\"MINING RESUMED\");\n }\n \/\/-----------------------------------------------------------------------------------------------------\n bool miner::worker_thread()\n {\n uint32_t th_local_index = boost::interprocess::ipcdetail::atomic_inc32(&m_thread_index);\n LOG_PRINT_L0(\"Miner thread was started [\"<< th_local_index << \"]\");\n log_space::log_singletone::set_thread_log_prefix(std::string(\"[miner \") + std::to_string(th_local_index) + \"]\");\n uint32_t nonce = m_starter_nonce + th_local_index;\n uint64_t height = 0;\n difficulty_type local_diff = 0;\n uint32_t local_template_ver = 0;\n block b;\n\t slow_hash_allocate_state();\n while(!m_stop)\n {\n if(m_pausers_count)\/\/anti split workaround\n {\n misc_utils::sleep_no_w(100);\n continue;\n }\n\n if(local_template_ver != m_template_no)\n {\n \n CRITICAL_REGION_BEGIN(m_template_lock);\n b = m_template;\n local_diff = m_diffic;\n height = m_height;\n CRITICAL_REGION_END();\n local_template_ver = m_template_no;\n nonce = m_starter_nonce + th_local_index;\n }\n\n if(!local_template_ver)\/\/no any set_block_template call\n {\n LOG_PRINT_L2(\"Block template not set yet\");\n epee::misc_utils::sleep_no_w(1000);\n continue;\n }\n\n b.nonce = nonce;\n crypto::hash h;\n get_block_longhash(b, h, height);\n\n if(check_hash(h, local_diff))\n {\n \/\/we lucky!\n ++m_config.current_extra_message_index;\n LOG_PRINT_GREEN(\"Found block for difficulty: \" << local_diff, LOG_LEVEL_0);\n if(!m_phandler->handle_block_found(b))\n {\n --m_config.current_extra_message_index;\n }else\n {\n \/\/success update, lets update config\n epee::serialization::store_t_to_json_file(m_config, m_config_folder_path + \"\/\" + MINER_CONFIG_FILE_NAME);\n }\n }\n nonce+=m_threads_total;\n ++m_hashes;\n }\n\t slow_hash_free_state();\n LOG_PRINT_L0(\"Miner thread stopped [\"<< th_local_index << \"]\");\n return true;\n }\n \/\/-----------------------------------------------------------------------------------------------------\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright(c) Sophist Solutions, Inc. 1990-2015. All rights reserved\n *\/\n#include \"..\/StroikaPreComp.h\"\n\n#if qHas_Syslog\n#include <syslog.h>\n#endif\n\n#include \"..\/Characters\/CString\/Utilities.h\"\n#include \"..\/Characters\/Format.h\"\n#include \"..\/Debug\/Trace.h\"\n#include \"BlockingQueue.h\"\n#include \"Common.h\"\n#include \"Process.h\"\n#include \"Synchronized.h\"\n#include \"Thread.h\"\n#include \"TimeOutException.h\"\n\n#include \"Logger.h\"\n\n\nusing namespace Stroika::Foundation;\nusing namespace Stroika::Foundation::Configuration;\nusing namespace Stroika::Foundation::Execution;\n\nusing Memory::Optional;\nusing Time::DurationSecondsType;\n\n\n\n\/\/ Comment this in to turn on aggressive noisy DbgTrace in this module\n\/\/#define USE_NOISY_TRACE_IN_THIS_MODULE_ 1\n\n\n\n\n\n\/*\n ********************************************************************************\n ******************************** Execution::Logger *****************************\n ********************************************************************************\n *\/\nLogger Logger::sThe_;\n\nconst EnumNames<Logger::Priority> Logger::Stroika_Enum_Names(Priority)\n{\n { Logger::Priority::eDebug, L\"Debug\" },\n { Logger::Priority::eInfo, L\"Info\" },\n { Logger::Priority::eNotice, L\"Notice\" },\n { Logger::Priority::eWarning, L\"Warning\" },\n { Logger::Priority::eError, L\"Error\" },\n { Logger::Priority::eCriticalError, L\"CriticalError\" },\n { Logger::Priority::eAlertError, L\"AlertError\" },\n { Logger::Priority::eEmergency, L\"Emergency\" },\n};\n\n\n\nnamespace {\n BlockingQueue<pair<Logger::Priority, String>> sOutMsgQ_;\n Execution::Thread sBookkeepingThread_;\n bool sOutQMaybeNeedsFlush_ = true; \/\/ sligt optimziation of not using buffering\n\n Synchronized<Memory::Optional<DurationSecondsType>> sSuppressDuplicatesThreshold_;\n\n struct LastMsg_ {\n pair<Logger::Priority, String> fLastMsgSent_;\n Time::DurationSecondsType fLastSentAt = 0.0;\n unsigned int fRepeatCount_ = 0;\n };\n Synchronized<LastMsg_> sLastMsg_;\n}\n\n\nLogger::Logger ()\n : fAppender_ ()\n , fMinLogLevel_ (Priority::eInfo)\n , fBufferingEnabled_ (false)\n{\n}\n\nvoid Logger::SetAppender (const shared_ptr<IAppenderRep>& rep)\n{\n fAppender_ = rep;\n}\n\nvoid Logger::Log_ (Priority logLevel, const String& format, va_list argList)\n{\n shared_ptr<IAppenderRep> tmp = sThe_.fAppender_; \/\/ avoid races and critical sections\n if (tmp.get () != nullptr) {\n auto p = pair<Logger::Priority, String> (logLevel, Characters::FormatV (format.c_str (), argList));\n if (sSuppressDuplicatesThreshold_->IsPresent ()) {\n auto lastMsgLocked = sLastMsg_.GetReference ();\n if (p == lastMsgLocked->fLastMsgSent_) {\n lastMsgLocked->fRepeatCount_++;\n lastMsgLocked->fLastSentAt = Time::GetTickCount ();\n return; \/\/ so will be handled later\n }\n else {\n if (lastMsgLocked->fRepeatCount_ > 0) {\n FlushDupsWarning_ ();\n }\n lastMsgLocked->fLastMsgSent_ = p;\n lastMsgLocked->fRepeatCount_ = 0;\n lastMsgLocked->fLastSentAt = Time::GetTickCount ();\n }\n }\n if (GetBufferingEnabled ()) {\n sOutQMaybeNeedsFlush_ = true;\n sOutMsgQ_.AddTail (p);\n }\n else {\n if (sOutQMaybeNeedsFlush_) {\n FlushBuffer (); \/\/ in case recently disabled\n }\n tmp->Log (p.first, p.second);\n }\n }\n}\n\nvoid Logger::SetBufferingEnabled (bool logBufferingEnabled)\n{\n#if USE_NOISY_TRACE_IN_THIS_MODULE_\n Debug::TraceContextBumper ctx (\"Logger::SetBufferingEnabled\");\n DbgTrace (L\"(logBufferingEnabled=%d)\", logBufferingEnabled);\n#endif\n sThe_.fBufferingEnabled_ = logBufferingEnabled;\n UpdateBookkeepingThread_ ();\n}\n\nvoid Logger::FlushBuffer ()\n{\n shared_ptr<IAppenderRep> tmp = sThe_.fAppender_; \/\/ avoid races and critical sections\n if (tmp != nullptr) {\n while (true) {\n Optional<pair<Logger::Priority, String>> p = sOutMsgQ_.RemoveHeadIfPossible ();\n if (p.IsPresent ()) {\n tmp->Log (p->first, p->second);\n }\n else {\n return; \/\/ no more entries\n }\n }\n }\n sOutQMaybeNeedsFlush_ = false;\n}\n\nMemory::Optional<Time::DurationSecondsType> Logger::GetSuppressDuplicates ()\n{\n return Memory::Optional<Time::DurationSecondsType> (sSuppressDuplicatesThreshold_);\n}\n\nvoid Logger::SetSuppressDuplicates (const Memory::Optional<DurationSecondsType>& suppressDuplicatesThreshold)\n{\n#if USE_NOISY_TRACE_IN_THIS_MODULE_\n Debug::TraceContextBumper ctx (\"Logger::SetSuppressDuplicates\");\n DbgTrace (L\"(suppressDuplicatesThreshold=%f)\", suppressDuplicatesThreshold.Value (-1));\n#endif\n Require (suppressDuplicatesThreshold.IsMissing () or * suppressDuplicatesThreshold > 0.0);\n auto critSec { Execution::make_unique_lock (sSuppressDuplicatesThreshold_) };\n if (sSuppressDuplicatesThreshold_ != suppressDuplicatesThreshold) {\n sSuppressDuplicatesThreshold_ = suppressDuplicatesThreshold;\n UpdateBookkeepingThread_ ();\n }\n}\n\nvoid Logger::FlushDupsWarning_ ()\n{\n#if USE_NOISY_TRACE_IN_THIS_MODULE_\n Debug::TraceContextBumper ctx (\"Logger::FlushDupsWarning_\");\n#endif\n auto lastMsgLocked = sLastMsg_.GetReference ();\n if (lastMsgLocked->fRepeatCount_ > 0) {\n#if USE_NOISY_TRACE_IN_THIS_MODULE_\n DbgTrace (L\"sLastMsg_.fRepeatCount_ = %d\", lastMsgLocked->fRepeatCount_);\n#endif\n shared_ptr<IAppenderRep> tmp = sThe_.fAppender_; \/\/ avoid races and critical sections\n if (tmp != nullptr) {\n if (lastMsgLocked->fRepeatCount_ == 1) {\n tmp->Log (lastMsgLocked->fLastMsgSent_.first, lastMsgLocked->fLastMsgSent_.second);\n }\n else {\n tmp->Log (lastMsgLocked->fLastMsgSent_.first, Characters::Format (L\"[%d duplicates suppressed]: %s\", lastMsgLocked->fRepeatCount_ - 1, lastMsgLocked->fLastMsgSent_.second.c_str ()));\n }\n }\n lastMsgLocked->fRepeatCount_ = 0;\n lastMsgLocked->fLastMsgSent_.second.clear ();\n }\n}\n\nvoid Logger::UpdateBookkeepingThread_ ()\n{\n sBookkeepingThread_.AbortAndWaitForDone ();\n sBookkeepingThread_ = Thread (); \/\/ so null\n\n Time::DurationSecondsType suppressDuplicatesThreshold = sSuppressDuplicatesThreshold_->Value (0);\n bool suppressDuplicates = suppressDuplicatesThreshold > 0;\n if (suppressDuplicates or GetBufferingEnabled ()) {\n if (suppressDuplicates) {\n sBookkeepingThread_ = Thread ([suppressDuplicatesThreshold] () {\n while (true) {\n DurationSecondsType time2Wait = max (static_cast<DurationSecondsType> (2), suppressDuplicatesThreshold); \/\/ never wait less than this\n try {\n auto p = sOutMsgQ_.RemoveHead (time2Wait);\n shared_ptr<IAppenderRep> tmp = sThe_.fAppender_; \/\/ avoid races and critical sections\n if (tmp != nullptr) {\n tmp->Log (p.first, p.second);\n }\n }\n catch (const TimeOutException&) {\n }\n {\n auto lastMsgLocked = sLastMsg_.GetReference ();\n if (lastMsgLocked->fRepeatCount_ > 0 and lastMsgLocked->fLastSentAt + suppressDuplicatesThreshold < Time::GetTickCount ()) {\n FlushDupsWarning_ ();\n }\n }\n }\n });\n }\n else {\n sBookkeepingThread_ = Thread ([] () {\n while (true) {\n auto p = sOutMsgQ_.RemoveHead ();\n shared_ptr<IAppenderRep> tmp = sThe_.fAppender_; \/\/ avoid races and critical sections\n if (tmp != nullptr) {\n tmp->Log (p.first, p.second);\n }\n }\n });\n }\n sBookkeepingThread_.SetThreadName (L\"Logger Bookkeeping\");\n sBookkeepingThread_.SetThreadPriority (Thread::Priority::eBelowNormal);\n sBookkeepingThread_.Start ();\n }\n\n \/\/ manually push out pending messages\n FlushBuffer ();\n}\n\n\n\n\n\n\n\/*\n ********************************************************************************\n ************************** Execution::IAppenderRep *****************************\n ********************************************************************************\n *\/\nLogger::IAppenderRep::~IAppenderRep ()\n{\n}\n\n\n\n\n\n\n#if qHas_Syslog\n\/*\n ********************************************************************************\n ************************ Execution::SysLogAppender *****************************\n ********************************************************************************\n *\/\nnamespace {\n string mkMsg_ (const String& applicationName)\n {\n return Characters::CString::Format (\"%s[%d]\", applicationName.AsNarrowSDKString ().c_str (), GetCurrentProcessID ());\n }\n}\nLogger::SysLogAppender::SysLogAppender (const String& applicationName)\n : fApplicationName_ (mkMsg_ (applicationName))\n{\n openlog (fApplicationName_.c_str (), 0, LOG_DAEMON); \/\/ not sure what facility to pass?\n}\n\nLogger::SysLogAppender::SysLogAppender (const String& applicationName, int facility)\n : fApplicationName_ (mkMsg_ (applicationName))\n{\n openlog (fApplicationName_.c_str (), 0, facility);\n}\n\nLogger::SysLogAppender::~SysLogAppender ()\n{\n closelog ();\n}\n\nvoid Logger::SysLogAppender::Log (Priority logLevel, const String& message)\n{\n DbgTrace (L\"SYSLOG: %s: %s\", Stroika_Enum_Names(Priority).GetName (logLevel), message.c_str ());\n int sysLogLevel = LOG_NOTICE; \/\/ doesnt matter cuz assert error if hit\n switch (logLevel) {\n case Priority::eDebug:\n sysLogLevel = LOG_DEBUG;\n break;\n case Priority::eInfo:\n sysLogLevel = LOG_INFO;\n break;\n case Priority::eNotice:\n sysLogLevel = LOG_NOTICE;\n break;\n case Priority::eWarning:\n sysLogLevel = LOG_WARNING;\n break;\n case Priority::eError:\n sysLogLevel = LOG_ERR;\n break;\n case Priority::eCriticalError:\n sysLogLevel = LOG_CRIT;\n break;\n case Priority::eAlertError:\n sysLogLevel = LOG_ALERT;\n break;\n case Priority::eEmergency:\n sysLogLevel = LOG_EMERG;\n break;\n default:\n RequireNotReached ();\n }\n syslog (sysLogLevel, \"%s\", message.AsNarrowSDKString ().c_str ());\n}\n#endif\n\n\n\n\n\n\n\/*\n ********************************************************************************\n ************************** Execution::FileAppender *****************************\n ********************************************************************************\n *\/\nLogger::FileAppender::FileAppender (const String& fileName)\n{\n AssertNotImplemented ();\n}\n\nvoid Logger::FileAppender::Log (Priority logLevel, const String& message)\n{\n AssertNotImplemented ();\n}\n\n\n\n\n\n\n#if qPlatform_Windows\n\/*\n ********************************************************************************\n ************************ Execution::SysLogAppender *****************************\n ********************************************************************************\n *\/\nLogger::WindowsEventLogAppender::WindowsEventLogAppender (const String& eventSourceName)\n : fEventSourceName_ (eventSourceName)\n{\n}\n\nvoid Logger::WindowsEventLogAppender::Log (Priority logLevel, const String& message)\n{\n \/*\n * VERY QUICK HACK - AT LEAST DUMPS SOME INFO TO EVENTLOG - BUT MUCH TWEAKING LEFT TODO\n *\/\n WORD eventType = EVENTLOG_ERROR_TYPE;\n switch (logLevel) {\n case Priority::eDebug:\n eventType = EVENTLOG_INFORMATION_TYPE;\n break;\n case Priority::eInfo:\n eventType = EVENTLOG_INFORMATION_TYPE;\n break;\n case Priority::eNotice:\n eventType = EVENTLOG_INFORMATION_TYPE;\n break;\n case Priority::eWarning:\n eventType = EVENTLOG_WARNING_TYPE;\n break;\n case Priority::eError:\n eventType = EVENTLOG_ERROR_TYPE;\n break;\n case Priority::eAlertError:\n eventType = EVENTLOG_ERROR_TYPE;\n break;\n case Priority::eEmergency:\n eventType = EVENTLOG_ERROR_TYPE;\n break;\n }\n#define CATEGORY_Normal 0x00000001L\n WORD eventCategoryID = CATEGORY_Normal;\n \/\/ See SPR#565 for wierdness - where I cannot really get these paid attention to\n \/\/ by the Windows EventLog. So had to use the .Net eventlogger. It SEEMS\n#define EVENT_Message 0x00000064L\n const DWORD kEventID = EVENT_Message;\n HANDLE hEventSource = RegisterEventSource (NULL, fEventSourceName_.AsSDKString ().c_str ());\n Verify (hEventSource != NULL);\n SDKString tmp = message.AsSDKString ();\n const Characters::SDKChar* msg = tmp.c_str ();\n Verify (::ReportEvent (\n hEventSource,\n eventType,\n eventCategoryID,\n kEventID,\n NULL,\n (WORD)1,\n 0,\n &msg,\n NULL\n )\n );\n Verify (::DeregisterEventSource (hEventSource));\n}\n#endif\n<commit_msg>exerpiemtn in Foundation\/Execution\/Logger - started but finish later - RemoveHeadIfPossible<commit_after>\/*\n * Copyright(c) Sophist Solutions, Inc. 1990-2015. All rights reserved\n *\/\n#include \"..\/StroikaPreComp.h\"\n\n#if qHas_Syslog\n#include <syslog.h>\n#endif\n\n#include \"..\/Characters\/CString\/Utilities.h\"\n#include \"..\/Characters\/Format.h\"\n#include \"..\/Debug\/Trace.h\"\n#include \"BlockingQueue.h\"\n#include \"Common.h\"\n#include \"Process.h\"\n#include \"Synchronized.h\"\n#include \"Thread.h\"\n#include \"TimeOutException.h\"\n\n#include \"Logger.h\"\n\n\nusing namespace Stroika::Foundation;\nusing namespace Stroika::Foundation::Configuration;\nusing namespace Stroika::Foundation::Execution;\n\nusing Memory::Optional;\nusing Time::DurationSecondsType;\n\n\n\n\/\/ Comment this in to turn on aggressive noisy DbgTrace in this module\n\/\/#define USE_NOISY_TRACE_IN_THIS_MODULE_ 1\n\n\n\n\n\n\/*\n ********************************************************************************\n ******************************** Execution::Logger *****************************\n ********************************************************************************\n *\/\nLogger Logger::sThe_;\n\nconst EnumNames<Logger::Priority> Logger::Stroika_Enum_Names(Priority)\n{\n { Logger::Priority::eDebug, L\"Debug\" },\n { Logger::Priority::eInfo, L\"Info\" },\n { Logger::Priority::eNotice, L\"Notice\" },\n { Logger::Priority::eWarning, L\"Warning\" },\n { Logger::Priority::eError, L\"Error\" },\n { Logger::Priority::eCriticalError, L\"CriticalError\" },\n { Logger::Priority::eAlertError, L\"AlertError\" },\n { Logger::Priority::eEmergency, L\"Emergency\" },\n};\n\n\n\nnamespace {\n BlockingQueue<pair<Logger::Priority, String>> sOutMsgQ_;\n Execution::Thread sBookkeepingThread_;\n bool sOutQMaybeNeedsFlush_ = true; \/\/ sligt optimziation of not using buffering\n\n Synchronized<Memory::Optional<DurationSecondsType>> sSuppressDuplicatesThreshold_;\n\n struct LastMsg_ {\n pair<Logger::Priority, String> fLastMsgSent_;\n Time::DurationSecondsType fLastSentAt = 0.0;\n unsigned int fRepeatCount_ = 0;\n };\n Synchronized<LastMsg_> sLastMsg_;\n}\n\n\nLogger::Logger ()\n : fAppender_ ()\n , fMinLogLevel_ (Priority::eInfo)\n , fBufferingEnabled_ (false)\n{\n}\n\nvoid Logger::SetAppender (const shared_ptr<IAppenderRep>& rep)\n{\n fAppender_ = rep;\n}\n\nvoid Logger::Log_ (Priority logLevel, const String& format, va_list argList)\n{\n shared_ptr<IAppenderRep> tmp = sThe_.fAppender_; \/\/ avoid races and critical sections\n if (tmp.get () != nullptr) {\n auto p = pair<Logger::Priority, String> (logLevel, Characters::FormatV (format.c_str (), argList));\n if (sSuppressDuplicatesThreshold_->IsPresent ()) {\n auto lastMsgLocked = sLastMsg_.GetReference ();\n if (p == lastMsgLocked->fLastMsgSent_) {\n lastMsgLocked->fRepeatCount_++;\n lastMsgLocked->fLastSentAt = Time::GetTickCount ();\n return; \/\/ so will be handled later\n }\n else {\n if (lastMsgLocked->fRepeatCount_ > 0) {\n FlushDupsWarning_ ();\n }\n lastMsgLocked->fLastMsgSent_ = p;\n lastMsgLocked->fRepeatCount_ = 0;\n lastMsgLocked->fLastSentAt = Time::GetTickCount ();\n }\n }\n if (GetBufferingEnabled ()) {\n sOutQMaybeNeedsFlush_ = true;\n sOutMsgQ_.AddTail (p);\n }\n else {\n if (sOutQMaybeNeedsFlush_) {\n FlushBuffer (); \/\/ in case recently disabled\n }\n tmp->Log (p.first, p.second);\n }\n }\n}\n\nvoid Logger::SetBufferingEnabled (bool logBufferingEnabled)\n{\n#if USE_NOISY_TRACE_IN_THIS_MODULE_\n Debug::TraceContextBumper ctx (\"Logger::SetBufferingEnabled\");\n DbgTrace (L\"(logBufferingEnabled=%d)\", logBufferingEnabled);\n#endif\n sThe_.fBufferingEnabled_ = logBufferingEnabled;\n UpdateBookkeepingThread_ ();\n}\n\nvoid Logger::FlushBuffer ()\n{\n shared_ptr<IAppenderRep> tmp = sThe_.fAppender_; \/\/ avoid races and critical sections\n if (tmp != nullptr) {\n while (true) {\n Optional<pair<Logger::Priority, String>> p = sOutMsgQ_.RemoveHeadIfPossible ();\n if (p.IsPresent ()) {\n tmp->Log (p->first, p->second);\n }\n else {\n return; \/\/ no more entries\n }\n }\n }\n sOutQMaybeNeedsFlush_ = false;\n}\n\nMemory::Optional<Time::DurationSecondsType> Logger::GetSuppressDuplicates ()\n{\n return Memory::Optional<Time::DurationSecondsType> (sSuppressDuplicatesThreshold_);\n}\n\nvoid Logger::SetSuppressDuplicates (const Memory::Optional<DurationSecondsType>& suppressDuplicatesThreshold)\n{\n#if USE_NOISY_TRACE_IN_THIS_MODULE_\n Debug::TraceContextBumper ctx (\"Logger::SetSuppressDuplicates\");\n DbgTrace (L\"(suppressDuplicatesThreshold=%f)\", suppressDuplicatesThreshold.Value (-1));\n#endif\n Require (suppressDuplicatesThreshold.IsMissing () or * suppressDuplicatesThreshold > 0.0);\n auto critSec { Execution::make_unique_lock (sSuppressDuplicatesThreshold_) };\n if (sSuppressDuplicatesThreshold_ != suppressDuplicatesThreshold) {\n sSuppressDuplicatesThreshold_ = suppressDuplicatesThreshold;\n UpdateBookkeepingThread_ ();\n }\n}\n\nvoid Logger::FlushDupsWarning_ ()\n{\n#if USE_NOISY_TRACE_IN_THIS_MODULE_\n Debug::TraceContextBumper ctx (\"Logger::FlushDupsWarning_\");\n#endif\n auto lastMsgLocked = sLastMsg_.GetReference ();\n if (lastMsgLocked->fRepeatCount_ > 0) {\n#if USE_NOISY_TRACE_IN_THIS_MODULE_\n DbgTrace (L\"sLastMsg_.fRepeatCount_ = %d\", lastMsgLocked->fRepeatCount_);\n#endif\n shared_ptr<IAppenderRep> tmp = sThe_.fAppender_; \/\/ avoid races and critical sections\n if (tmp != nullptr) {\n if (lastMsgLocked->fRepeatCount_ == 1) {\n tmp->Log (lastMsgLocked->fLastMsgSent_.first, lastMsgLocked->fLastMsgSent_.second);\n }\n else {\n tmp->Log (lastMsgLocked->fLastMsgSent_.first, Characters::Format (L\"[%d duplicates suppressed]: %s\", lastMsgLocked->fRepeatCount_ - 1, lastMsgLocked->fLastMsgSent_.second.c_str ()));\n }\n }\n lastMsgLocked->fRepeatCount_ = 0;\n lastMsgLocked->fLastMsgSent_.second.clear ();\n }\n}\n\nvoid Logger::UpdateBookkeepingThread_ ()\n{\n sBookkeepingThread_.AbortAndWaitForDone ();\n sBookkeepingThread_ = Thread (); \/\/ so null\n\n Time::DurationSecondsType suppressDuplicatesThreshold = sSuppressDuplicatesThreshold_->Value (0);\n bool suppressDuplicates = suppressDuplicatesThreshold > 0;\n if (suppressDuplicates or GetBufferingEnabled ()) {\n if (suppressDuplicates) {\n sBookkeepingThread_ = Thread ([suppressDuplicatesThreshold] () {\n while (true) {\n DurationSecondsType time2Wait = max (static_cast<DurationSecondsType> (2), suppressDuplicatesThreshold); \/\/ never wait less than this\n#if 0\n \/\/\/ Not ready fo prime time because BlockinqQ RemoveHeadIfPossible currently ignores time2Wait... Must fix that first...\n if (auto p = sOutMsgQ_.RemoveHeadIfPossible (time2Wait)) {\n shared_ptr<IAppenderRep> tmp = sThe_.fAppender_; \/\/ avoid races and critical sections\n if (tmp != nullptr) {\n tmp->Log (p->first, p->second);\n }\n }\n#else\n try {\n auto p = sOutMsgQ_.RemoveHead (time2Wait);\n shared_ptr<IAppenderRep> tmp = sThe_.fAppender_; \/\/ avoid races and critical sections\n if (tmp != nullptr) {\n tmp->Log (p.first, p.second);\n }\n }\n catch (const TimeOutException&) {\n }\n#endif\n {\n auto lastMsgLocked = sLastMsg_.GetReference ();\n if (lastMsgLocked->fRepeatCount_ > 0 and lastMsgLocked->fLastSentAt + suppressDuplicatesThreshold < Time::GetTickCount ()) {\n FlushDupsWarning_ ();\n }\n }\n }\n });\n }\n else {\n sBookkeepingThread_ = Thread ([] () {\n while (true) {\n auto p = sOutMsgQ_.RemoveHead ();\n shared_ptr<IAppenderRep> tmp = sThe_.fAppender_; \/\/ avoid races and critical sections\n if (tmp != nullptr) {\n tmp->Log (p.first, p.second);\n }\n }\n });\n }\n sBookkeepingThread_.SetThreadName (L\"Logger Bookkeeping\");\n sBookkeepingThread_.SetThreadPriority (Thread::Priority::eBelowNormal);\n sBookkeepingThread_.Start ();\n }\n\n \/\/ manually push out pending messages\n FlushBuffer ();\n}\n\n\n\n\n\n\n\/*\n ********************************************************************************\n ************************** Execution::IAppenderRep *****************************\n ********************************************************************************\n *\/\nLogger::IAppenderRep::~IAppenderRep ()\n{\n}\n\n\n\n\n\n\n#if qHas_Syslog\n\/*\n ********************************************************************************\n ************************ Execution::SysLogAppender *****************************\n ********************************************************************************\n *\/\nnamespace {\n string mkMsg_ (const String& applicationName)\n {\n return Characters::CString::Format (\"%s[%d]\", applicationName.AsNarrowSDKString ().c_str (), GetCurrentProcessID ());\n }\n}\nLogger::SysLogAppender::SysLogAppender (const String& applicationName)\n : fApplicationName_ (mkMsg_ (applicationName))\n{\n openlog (fApplicationName_.c_str (), 0, LOG_DAEMON); \/\/ not sure what facility to pass?\n}\n\nLogger::SysLogAppender::SysLogAppender (const String& applicationName, int facility)\n : fApplicationName_ (mkMsg_ (applicationName))\n{\n openlog (fApplicationName_.c_str (), 0, facility);\n}\n\nLogger::SysLogAppender::~SysLogAppender ()\n{\n closelog ();\n}\n\nvoid Logger::SysLogAppender::Log (Priority logLevel, const String& message)\n{\n DbgTrace (L\"SYSLOG: %s: %s\", Stroika_Enum_Names(Priority).GetName (logLevel), message.c_str ());\n int sysLogLevel = LOG_NOTICE; \/\/ doesnt matter cuz assert error if hit\n switch (logLevel) {\n case Priority::eDebug:\n sysLogLevel = LOG_DEBUG;\n break;\n case Priority::eInfo:\n sysLogLevel = LOG_INFO;\n break;\n case Priority::eNotice:\n sysLogLevel = LOG_NOTICE;\n break;\n case Priority::eWarning:\n sysLogLevel = LOG_WARNING;\n break;\n case Priority::eError:\n sysLogLevel = LOG_ERR;\n break;\n case Priority::eCriticalError:\n sysLogLevel = LOG_CRIT;\n break;\n case Priority::eAlertError:\n sysLogLevel = LOG_ALERT;\n break;\n case Priority::eEmergency:\n sysLogLevel = LOG_EMERG;\n break;\n default:\n RequireNotReached ();\n }\n syslog (sysLogLevel, \"%s\", message.AsNarrowSDKString ().c_str ());\n}\n#endif\n\n\n\n\n\n\n\/*\n ********************************************************************************\n ************************** Execution::FileAppender *****************************\n ********************************************************************************\n *\/\nLogger::FileAppender::FileAppender (const String& fileName)\n{\n AssertNotImplemented ();\n}\n\nvoid Logger::FileAppender::Log (Priority logLevel, const String& message)\n{\n AssertNotImplemented ();\n}\n\n\n\n\n\n\n#if qPlatform_Windows\n\/*\n ********************************************************************************\n ************************ Execution::SysLogAppender *****************************\n ********************************************************************************\n *\/\nLogger::WindowsEventLogAppender::WindowsEventLogAppender (const String& eventSourceName)\n : fEventSourceName_ (eventSourceName)\n{\n}\n\nvoid Logger::WindowsEventLogAppender::Log (Priority logLevel, const String& message)\n{\n \/*\n * VERY QUICK HACK - AT LEAST DUMPS SOME INFO TO EVENTLOG - BUT MUCH TWEAKING LEFT TODO\n *\/\n WORD eventType = EVENTLOG_ERROR_TYPE;\n switch (logLevel) {\n case Priority::eDebug:\n eventType = EVENTLOG_INFORMATION_TYPE;\n break;\n case Priority::eInfo:\n eventType = EVENTLOG_INFORMATION_TYPE;\n break;\n case Priority::eNotice:\n eventType = EVENTLOG_INFORMATION_TYPE;\n break;\n case Priority::eWarning:\n eventType = EVENTLOG_WARNING_TYPE;\n break;\n case Priority::eError:\n eventType = EVENTLOG_ERROR_TYPE;\n break;\n case Priority::eAlertError:\n eventType = EVENTLOG_ERROR_TYPE;\n break;\n case Priority::eEmergency:\n eventType = EVENTLOG_ERROR_TYPE;\n break;\n }\n#define CATEGORY_Normal 0x00000001L\n WORD eventCategoryID = CATEGORY_Normal;\n \/\/ See SPR#565 for wierdness - where I cannot really get these paid attention to\n \/\/ by the Windows EventLog. So had to use the .Net eventlogger. It SEEMS\n#define EVENT_Message 0x00000064L\n const DWORD kEventID = EVENT_Message;\n HANDLE hEventSource = RegisterEventSource (NULL, fEventSourceName_.AsSDKString ().c_str ());\n Verify (hEventSource != NULL);\n SDKString tmp = message.AsSDKString ();\n const Characters::SDKChar* msg = tmp.c_str ();\n Verify (::ReportEvent (\n hEventSource,\n eventType,\n eventCategoryID,\n kEventID,\n NULL,\n (WORD)1,\n 0,\n &msg,\n NULL\n )\n );\n Verify (::DeregisterEventSource (hEventSource));\n}\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: ZipEnumeration.cxx,v $\n *\n * $Revision: 1.4 $\n *\n * last change: $Author: mtg $ $Date: 2000-11-29 03:14:55 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n#ifndef _ZIP_ENUMERATION_HXX\n#include \"ZipEnumeration.hxx\"\n#endif\n\n#ifndef _COM_SUN_STAR_PACKAGE_ZIPCONSTANTS_HPP_\n#include <com\/sun\/star\/package\/ZipConstants.hpp>\n#endif\n\n#include <iostream.h>\nusing namespace rtl;\nusing namespace com::sun::star;\n\n\/** Provides an Enumeration over the contents of a Zip file *\/\n\nZipEnumeration::ZipEnumeration( EntryHash & rNewEntryHash)\n: rEntryHash(rNewEntryHash)\n, aIterator(rEntryHash.begin())\n{\n}\nZipEnumeration::~ZipEnumeration( void )\n{\n}\nsal_Bool SAL_CALL ZipEnumeration::hasMoreElements() throw (uno::RuntimeException)\n{\n return (aIterator != rEntryHash.end());\n}\n\nuno::Any SAL_CALL ZipEnumeration::nextElement() throw (uno::RuntimeException)\n{\n uno::Any aAny;\n if (aIterator == rEntryHash.end())\n throw (container::NoSuchElementException());\n aAny <<= (*aIterator).second;\n aIterator++;\n return aAny;\n}\n<commit_msg>#65293# Parse error linux throw()<commit_after>\/*************************************************************************\n *\n * $RCSfile: ZipEnumeration.cxx,v $\n *\n * $Revision: 1.5 $\n *\n * last change: $Author: obo $ $Date: 2000-12-04 16:04:49 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n#ifndef _ZIP_ENUMERATION_HXX\n#include \"ZipEnumeration.hxx\"\n#endif\n\n#ifndef _COM_SUN_STAR_PACKAGE_ZIPCONSTANTS_HPP_\n#include <com\/sun\/star\/package\/ZipConstants.hpp>\n#endif\n\n#include <iostream.h>\nusing namespace rtl;\nusing namespace com::sun::star;\n\n\/** Provides an Enumeration over the contents of a Zip file *\/\n\nZipEnumeration::ZipEnumeration( EntryHash & rNewEntryHash)\n: rEntryHash(rNewEntryHash)\n, aIterator(rEntryHash.begin())\n{\n}\nZipEnumeration::~ZipEnumeration( void )\n{\n}\nsal_Bool SAL_CALL ZipEnumeration::hasMoreElements() throw (uno::RuntimeException)\n{\n return (aIterator != rEntryHash.end());\n}\n\nuno::Any SAL_CALL ZipEnumeration::nextElement() throw (uno::RuntimeException)\n{\n uno::Any aAny;\n if (aIterator == rEntryHash.end())\n throw container::NoSuchElementException();\n aAny <<= (*aIterator).second;\n aIterator++;\n return aAny;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: fldtdlg.hxx,v $\n *\n * $Revision: 1.6 $\n *\n * last change: $Author: hr $ $Date: 2007-09-27 11:59:31 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n#ifndef _SWFLDTDLG_HXX\n#define _SWFLDTDLG_HXX\n#ifndef _SFXTABDLG_HXX \/\/autogen\n#include <sfx2\/tabdlg.hxx>\n#endif\n\nclass SfxBindings;\nclass SfxTabPage;\nclass SwChildWinWrapper;\nstruct SfxChildWinInfo;\n\n\/*--------------------------------------------------------------------\n Beschreibung:\n --------------------------------------------------------------------*\/\n\nclass SwFldDlg: public SfxTabDialog\n{\n SwChildWinWrapper* m_pChildWin;\n SfxBindings* m_pBindings;\n BOOL m_bHtmlMode;\n BOOL m_bDataBaseMode;\n\n virtual BOOL Close();\n virtual SfxItemSet* CreateInputItemSet( USHORT nId );\n virtual void Activate();\n virtual void PageCreated(USHORT nId, SfxTabPage& rPage);\n\n void ReInitTabPage( USHORT nPageId,\n BOOL bOnlyActivate = FALSE );\n\npublic:\n SwFldDlg(SfxBindings* pB, SwChildWinWrapper* pCW, Window *pParent);\n virtual ~SwFldDlg();\n\n DECL_LINK( OKHdl, Button * );\n\n void Initialize(SfxChildWinInfo *pInfo);\n void ReInitDlg();\n void EnableInsert(BOOL bEnable);\n void InsertHdl();\n void ActivateDatabasePage();\n};\n\n#endif\n<commit_msg>INTEGRATION: CWS changefileheader (1.6.242); FILE MERGED 2008\/04\/01 15:59:11 thb 1.6.242.2: #i85898# Stripping all external header guards 2008\/03\/31 16:58:31 rt 1.6.242.1: #i87441# Change license header to LPGL v3.<commit_after>\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2008 by Sun Microsystems, Inc.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: fldtdlg.hxx,v $\n * $Revision: 1.7 $\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * <http:\/\/www.openoffice.org\/license.html>\n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n#ifndef _SWFLDTDLG_HXX\n#define _SWFLDTDLG_HXX\n#include <sfx2\/tabdlg.hxx>\n\nclass SfxBindings;\nclass SfxTabPage;\nclass SwChildWinWrapper;\nstruct SfxChildWinInfo;\n\n\/*--------------------------------------------------------------------\n Beschreibung:\n --------------------------------------------------------------------*\/\n\nclass SwFldDlg: public SfxTabDialog\n{\n SwChildWinWrapper* m_pChildWin;\n SfxBindings* m_pBindings;\n BOOL m_bHtmlMode;\n BOOL m_bDataBaseMode;\n\n virtual BOOL Close();\n virtual SfxItemSet* CreateInputItemSet( USHORT nId );\n virtual void Activate();\n virtual void PageCreated(USHORT nId, SfxTabPage& rPage);\n\n void ReInitTabPage( USHORT nPageId,\n BOOL bOnlyActivate = FALSE );\n\npublic:\n SwFldDlg(SfxBindings* pB, SwChildWinWrapper* pCW, Window *pParent);\n virtual ~SwFldDlg();\n\n DECL_LINK( OKHdl, Button * );\n\n void Initialize(SfxChildWinInfo *pInfo);\n void ReInitDlg();\n void EnableInsert(BOOL bEnable);\n void InsertHdl();\n void ActivateDatabasePage();\n};\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>#include <type_traits> \/\/ std::is_same<>.\n\n#include <gtest\/gtest.h>\n\n\/\/ TODO(dkorolev): Complete this test. Remaining:\n\/\/ * iterating over data via the StreamManager, going around the Db.\n\/\/ * merging input streams.\n\/\/ * producing data.\n\/\/ * starting jobs.\n\/\/ * serialization.\n\n#include \"..\/..\/src\/tailproduce.h\"\n\n#include \"mocks\/stream_manager.h\"\n#include \"mocks\/data_storage.h\"\n\n\/\/ TODO(dkorolev): Entry implementations should inherit from their base class.\n\/\/ TODO(dkorolev): Current serialization is a prototype, move to a more robust version.\n\n\/\/ Test plan:\n\/\/ * One basic stream, that is being populated \"externally\".\n\/\/ In other words, mocked, since each entry will be added independently.\n\/\/ * A few derived streams:\n\/\/ - The one that listens to an input stream and outputs only the prime numbers from it.\n\/\/ - The one that listens to an input stream and outputs aggregates each N=10 entires.\n\n\/\/ Ordering key.\nstruct SimpleIntegerOrderKey : TailProduce::OrderKey {\n SimpleIntegerOrderKey(uint32_t key) : key(key) {\n }\n uint32_t key;\n \/\/ TODO(dkorolev): Methods to serialize \/ deserialize the key.\n \/\/ TODO(dkorolev): A static function to extract the key w\/o parsing the binary format.\n};\n\n\/\/ The SimpleIntegerEntry keeps the key\/value pairs to test on. For this test they are { uint32, string } pairs.\nstruct SimpleIntegerEntry {\n \/\/ Used as order key, 1, 2, 3, etc.\n uint32_t key;\n \/\/ To test data extraction, \"one\", \"two\", \"three\", or anything else for the sake of this test.\n const std::string data;\n\n template<typename T> T OrderKey() const;\n \/\/ TODO(dkorolev): Serialization \/ deserialization.\n \/\/ TOOD(dkorolev): Extracting the order key as uint32_t,\n \/\/ failing to extract it as any other type at compine time.\n};\ntemplate<> SimpleIntegerOrderKey SimpleIntegerEntry::OrderKey<SimpleIntegerOrderKey>() const {\n return SimpleIntegerOrderKey(key);\n}\n\n\/\/ EphemeralMarkerEntryType is \"fired\" every N=10 entries, so that TailProduce jobs don't have to keep their counters.\nstruct EphemeralMarkerEntryType {\n};\n\n\/\/ An example TailProduce job, effectively acting as a filter.\n\/\/ TODO(dkorolev): TailProduceFilter<T_PREDICATE> should probably be a part of the standard TailProduce library.\n\/\/ TODO(dkorolev): Standardize typing convention to be able to extract order key types from T_OUTPUT.\ntemplate<typename T_OUTPUT> struct PrimeNumbersTailProduce {\n void Consume(const SimpleIntegerEntry& entry, T_OUTPUT& output) {\n if (is_prime(entry.key)) {\n output.Produce(entry);\n }\n }\n\n private:\n static bool is_prime(const uint32_t& x) {\n for (uint32_t i = 2; i * i <= x; ++i) {\n if ((x % i) == 0) {\n return false;\n }\n }\n return true;\n }\n};\n\n\/\/ An example TailProduce job, effectively acting as an aggregator.\n\/\/ TODO(dkorolev): TailProduceAggregator<T_MARKER> should probably be a part of the standard TailProduce library.\ntemplate<typename T_OUTPUT> struct PrimesAggregatorTailProduce {\n void Consume(const SimpleIntegerEntry& entry, T_OUTPUT& output) {\n intermediate_.push_back(entry.data);\n }\n void Consume(const EphemeralMarkerEntryType&) {\n std::ostringstream os;\n for (size_t i = 0; i < intermediate_.size(); ++i) {\n if (i) {\n os << ',';\n }\n os << intermediate_[i];\n }\n intermediate_.clear();\n }\n std::vector<std::string> intermediate_;\n};\n\ntemplate<typename T> class StreamManagerTest : public ::testing::Test {};\n\n\/\/ Unit test for TailProduce static framework.\n\/\/ TODO(dkorolev): Add more stream managers and data storages here.\ntypedef ::testing::Types<MockStreamManager<MockDataStorage>> DataStorageImplementations;\nTYPED_TEST_CASE(StreamManagerTest, DataStorageImplementations);\n\n\/\/ Tests stream creation macros.\nTYPED_TEST(StreamManagerTest, UserFriendlySyntaxCompiles) {\n TAILPRODUCE_STATIC_FRAMEWORK_BEGIN(StreamManagerImpl, TypeParam);\n TAILPRODUCE_STREAM(test, SimpleIntegerEntry, SimpleIntegerOrderKey);\n TAILPRODUCE_STATIC_FRAMEWORK_END();\n\n StreamManagerImpl impl;\n ASSERT_EQ(1, impl.registry().streams.size());\n EXPECT_EQ(\"test\", impl.registry().streams[0].name);\n EXPECT_EQ(\"SimpleIntegerEntry\", impl.registry().streams[0].entry_type);\n EXPECT_EQ(\"SimpleIntegerOrderKey\", impl.registry().streams[0].order_key_type);\n EXPECT_TRUE(impl.registry().streams[0].impl == static_cast<TailProduce::Stream*>(&impl.test));\n EXPECT_TRUE((std::is_same<SimpleIntegerEntry, typename StreamManagerImpl::STREAM_TYPE_test::ENTRY_TYPE>::value));\n EXPECT_TRUE((std::is_same<SimpleIntegerOrderKey, typename StreamManagerImpl::STREAM_TYPE_test::ORDER_KEY_TYPE>::value));\n}\n\n\/\/ This test explicitly lists what stream definition macros expand into.\n\/\/ Used as a reference point, as well as to ensure the macros do what they have been intended to.\nTYPED_TEST(StreamManagerTest, ExpandedMacroSyntaxCompiles) {\n class StreamManagerImpl : public TypeParam {\n private:\n ::TailProduce::StreamsRegistry registry_;\n\n public:\n const ::TailProduce::StreamsRegistry& registry() const { return registry_; }\n typedef ::TailProduce::StreamInstance<SimpleIntegerEntry, SimpleIntegerOrderKey> STREAM_TYPE_test;\n STREAM_TYPE_test test = STREAM_TYPE_test(registry_, \"test\", \"SimpleIntegerEntry\", \"SimpleIntegerOrderKey\");\n };\n\n StreamManagerImpl impl;\n ASSERT_EQ(1, impl.registry().streams.size());\n EXPECT_EQ(\"test\", impl.registry().streams[0].name);\n EXPECT_EQ(\"SimpleIntegerEntry\", impl.registry().streams[0].entry_type);\n EXPECT_EQ(\"SimpleIntegerOrderKey\", impl.registry().streams[0].order_key_type);\n EXPECT_TRUE(impl.registry().streams[0].impl == static_cast<TailProduce::Stream*>(&impl.test));\n EXPECT_TRUE((std::is_same<SimpleIntegerEntry, typename StreamManagerImpl::STREAM_TYPE_test::ENTRY_TYPE>::value));\n EXPECT_TRUE((std::is_same<SimpleIntegerOrderKey, typename StreamManagerImpl::STREAM_TYPE_test::ORDER_KEY_TYPE>::value));\n}\n<commit_msg>Adhering to 117 characters line width limit.<commit_after>#include <type_traits> \/\/ std::is_same<>.\n\n#include <gtest\/gtest.h>\n\n\/\/ TODO(dkorolev): Complete this test. Remaining:\n\/\/ * iterating over data via the StreamManager, going around the Db.\n\/\/ * merging input streams.\n\/\/ * producing data.\n\/\/ * starting jobs.\n\/\/ * serialization.\n\n#include \"..\/..\/src\/tailproduce.h\"\n\n#include \"mocks\/stream_manager.h\"\n#include \"mocks\/data_storage.h\"\n\n\/\/ TODO(dkorolev): Entry implementations should inherit from their base class.\n\/\/ TODO(dkorolev): Current serialization is a prototype, move to a more robust version.\n\n\/\/ Test plan:\n\/\/ * One basic stream, that is being populated \"externally\".\n\/\/ In other words, mocked, since each entry will be added independently.\n\/\/ * A few derived streams:\n\/\/ - The one that listens to an input stream and outputs only the prime numbers from it.\n\/\/ - The one that listens to an input stream and outputs aggregates each N=10 entires.\n\n\/\/ Ordering key.\nstruct SimpleIntegerOrderKey : TailProduce::OrderKey {\n SimpleIntegerOrderKey(uint32_t key) : key(key) {\n }\n uint32_t key;\n \/\/ TODO(dkorolev): Methods to serialize \/ deserialize the key.\n \/\/ TODO(dkorolev): A static function to extract the key w\/o parsing the binary format.\n};\n\n\/\/ The SimpleIntegerEntry keeps the key\/value pairs to test on. For this test they are { uint32, string } pairs.\nstruct SimpleIntegerEntry {\n \/\/ Used as order key, 1, 2, 3, etc.\n uint32_t key;\n \/\/ To test data extraction, \"one\", \"two\", \"three\", or anything else for the sake of this test.\n const std::string data;\n\n template<typename T> T OrderKey() const;\n \/\/ TODO(dkorolev): Serialization \/ deserialization.\n \/\/ TOOD(dkorolev): Extracting the order key as uint32_t,\n \/\/ failing to extract it as any other type at compine time.\n};\ntemplate<> SimpleIntegerOrderKey SimpleIntegerEntry::OrderKey<SimpleIntegerOrderKey>() const {\n return SimpleIntegerOrderKey(key);\n}\n\n\/\/ EphemeralMarkerEntryType is fired every N=10 entries, so that TailProduce jobs don't have to keep their counters.\nstruct EphemeralMarkerEntryType {\n};\n\n\/\/ An example TailProduce job, effectively acting as a filter.\n\/\/ TODO(dkorolev): TailProduceFilter<T_PREDICATE> should probably be a part of the standard TailProduce library.\n\/\/ TODO(dkorolev): Standardize typing convention to be able to extract order key types from T_OUTPUT.\ntemplate<typename T_OUTPUT> struct PrimeNumbersTailProduce {\n void Consume(const SimpleIntegerEntry& entry, T_OUTPUT& output) {\n if (is_prime(entry.key)) {\n output.Produce(entry);\n }\n }\n\n private:\n static bool is_prime(const uint32_t& x) {\n for (uint32_t i = 2; i * i <= x; ++i) {\n if ((x % i) == 0) {\n return false;\n }\n }\n return true;\n }\n};\n\n\/\/ An example TailProduce job, effectively acting as an aggregator.\n\/\/ TODO(dkorolev): TailProduceAggregator<T_MARKER> should probably be a part of the standard TailProduce library.\ntemplate<typename T_OUTPUT> struct PrimesAggregatorTailProduce {\n void Consume(const SimpleIntegerEntry& entry, T_OUTPUT& output) {\n intermediate_.push_back(entry.data);\n }\n void Consume(const EphemeralMarkerEntryType&) {\n std::ostringstream os;\n for (size_t i = 0; i < intermediate_.size(); ++i) {\n if (i) {\n os << ',';\n }\n os << intermediate_[i];\n }\n intermediate_.clear();\n }\n std::vector<std::string> intermediate_;\n};\n\ntemplate<typename T> class StreamManagerTest : public ::testing::Test {};\n\n\/\/ Unit test for TailProduce static framework.\n\/\/ TODO(dkorolev): Add more stream managers and data storages here.\ntypedef ::testing::Types<MockStreamManager<MockDataStorage>> DataStorageImplementations;\nTYPED_TEST_CASE(StreamManagerTest, DataStorageImplementations);\n\n\/\/ Tests stream creation macros.\nTYPED_TEST(StreamManagerTest, UserFriendlySyntaxCompiles) {\n TAILPRODUCE_STATIC_FRAMEWORK_BEGIN(StreamManagerImpl, TypeParam);\n TAILPRODUCE_STREAM(test, SimpleIntegerEntry, SimpleIntegerOrderKey);\n TAILPRODUCE_STATIC_FRAMEWORK_END();\n\n StreamManagerImpl impl;\n ASSERT_EQ(1, impl.registry().streams.size());\n EXPECT_EQ(\"test\", impl.registry().streams[0].name);\n EXPECT_EQ(\"SimpleIntegerEntry\", impl.registry().streams[0].entry_type);\n EXPECT_EQ(\"SimpleIntegerOrderKey\", impl.registry().streams[0].order_key_type);\n EXPECT_TRUE(impl.registry().streams[0].impl == static_cast<TailProduce::Stream*>(&impl.test));\n EXPECT_TRUE((std::is_same<SimpleIntegerEntry, typename StreamManagerImpl::STREAM_TYPE_test::ENTRY_TYPE>::value));\n EXPECT_TRUE((std::is_same<SimpleIntegerOrderKey,\n typename StreamManagerImpl::STREAM_TYPE_test::ORDER_KEY_TYPE>::value));\n}\n\n\/\/ This test explicitly lists what stream definition macros expand into.\n\/\/ Used as a reference point, as well as to ensure the macros do what they have been intended to.\nTYPED_TEST(StreamManagerTest, ExpandedMacroSyntaxCompiles) {\n class StreamManagerImpl : public TypeParam {\n private:\n ::TailProduce::StreamsRegistry registry_;\n\n public:\n const ::TailProduce::StreamsRegistry& registry() const { return registry_; }\n typedef ::TailProduce::StreamInstance<SimpleIntegerEntry, SimpleIntegerOrderKey> STREAM_TYPE_test;\n STREAM_TYPE_test test = STREAM_TYPE_test(registry_, \"test\", \"SimpleIntegerEntry\", \"SimpleIntegerOrderKey\");\n };\n\n StreamManagerImpl impl;\n ASSERT_EQ(1, impl.registry().streams.size());\n EXPECT_EQ(\"test\", impl.registry().streams[0].name);\n EXPECT_EQ(\"SimpleIntegerEntry\", impl.registry().streams[0].entry_type);\n EXPECT_EQ(\"SimpleIntegerOrderKey\", impl.registry().streams[0].order_key_type);\n EXPECT_TRUE(impl.registry().streams[0].impl == static_cast<TailProduce::Stream*>(&impl.test));\n EXPECT_TRUE((std::is_same<SimpleIntegerEntry, typename StreamManagerImpl::STREAM_TYPE_test::ENTRY_TYPE>::value));\n EXPECT_TRUE((std::is_same<SimpleIntegerOrderKey,\n typename StreamManagerImpl::STREAM_TYPE_test::ORDER_KEY_TYPE>::value));\n}\n<|endoftext|>"} {"text":"<commit_before>#include <node.h>\n#include <stdlib.h>\n#include <mysql\/mysql.h>\n\nusing namespace node;\nusing namespace v8;\n\nstatic Persistent<FunctionTemplate> Client_constructor;\nstatic Persistent<String> emit_symbol;\n\nconst int STATE_CLOSE = -2,\n STATE_CLOSED = -1,\n STATE_CONNECT = 0,\n STATE_CONNECTING = 1,\n STATE_CONNECTED = 2,\n STATE_QUERY = 3,\n STATE_QUERYING = 4,\n STATE_QUERIED = 5,\n STATE_ROWSTREAM = 6,\n STATE_ROWSTREAMING = 7,\n STATE_ROWSTREAMED = 8;\n\nstruct sql_config {\n char* user;\n char* password;\n char* ip;\n char* db;\n unsigned int port;\n bool compress;\n};\n\n#include <stdio.h>\n#define DEBUG(s) fprintf(stderr, \"BINDING: \" s \"\\n\")\n\nclass Client : public ObjectWrap {\n public:\n uv_poll_t poll_handle;\n MYSQL mysql, *mysql_ret;\n MYSQL_RES *mysql_res;\n MYSQL_ROW mysql_row;\n int mysql_qerr;\n char* cur_query;\n sql_config config;\n bool hadError;\n int state;\n\n Client() {\n state = STATE_CLOSED;\n }\n\n ~Client() {\n close();\n }\n\n void init() {\n config.user = NULL;\n config.password = NULL;\n config.ip = NULL;\n config.db = NULL;\n cur_query = NULL;\n hadError = false;\n poll_handle.type = UV_UNKNOWN_HANDLE;\n\n mysql_init(&mysql);\n mysql_options(&mysql, MYSQL_OPT_NONBLOCK, 0);\n }\n\n void connect() {\n if (state == STATE_CLOSED) {\n state = STATE_CONNECT;\n doWork();\n }\n }\n\n void close() {\n if (state != STATE_CLOSED) {\n if (config.user) {\n free(config.user);\n config.user = NULL;\n }\n if (config.password) {\n free(config.password);\n config.password = NULL;\n }\n if (config.ip) {\n free(config.ip);\n config.ip = NULL;\n }\n if (config.db) {\n free(config.db);\n config.db = NULL;\n }\n if (cur_query) {\n free(cur_query);\n cur_query = NULL;\n }\n \n state = STATE_CLOSE;\n doWork();\n }\n }\n\n char* escape(const char* str) {\n unsigned int str_len = strlen(str);\n char* dest = (char*) malloc(str_len * 2 + 1);\n mysql_real_escape_string(&mysql, dest, str, str_len);\n return dest;\n }\n\n void query(const char* qry) {\n if (state == STATE_CONNECTED) {\n cur_query = strdup(qry);\n state = STATE_QUERY;\n doWork();\n }\n }\n\n void doWork(int event = 0) {\n int status = 0, new_events = 0;\n bool done = false;\n while (!done) {\n switch (state) {\n case STATE_CONNECT:\n\/\/DEBUG(\"STATE_CONNECT\");\n status = mysql_real_connect_start(&mysql_ret, &mysql,\n config.ip,\n config.user,\n config.password,\n config.db,\n config.port, NULL, 0);\n uv_poll_init_socket(uv_default_loop(), &poll_handle,\n mysql_get_socket(&mysql));\n poll_handle.data = this;\n if (status) {\n state = STATE_CONNECTING;\n done = true;\n } else {\n state = STATE_CONNECTED;\n emit(\"connect\");\n }\n break;\n case STATE_CONNECTING:\n\/\/DEBUG(\"STATE_CONNECTING\");\n status = mysql_real_connect_cont(&mysql_ret, &mysql, event);\n if (status)\n done = true;\n else {\n if (!mysql_ret)\n return emitError(\"conn\", true);\n state = STATE_CONNECTED;\n emit(\"connect\");\n }\n break;\n case STATE_CONNECTED:\n\/\/DEBUG(\"STATE_CONNECTED\");\n done = true;\n break;\n case STATE_QUERY:\n\/\/DEBUG(\"STATE_QUERY\");\n status = mysql_real_query_start(&mysql_qerr, &mysql, cur_query,\n strlen(cur_query));\n if (status) {\n state = STATE_QUERYING;\n done = true;\n } else\n state = STATE_QUERIED;\n break;\n case STATE_QUERYING:\n\/\/DEBUG(\"STATE_QUERYING\");\n status = mysql_real_query_cont(&mysql_qerr, &mysql,\n mysql_status(event));\n if (status)\n done = true;\n else {\n if (cur_query) {\n free(cur_query);\n cur_query = NULL;\n }\n if (mysql_qerr)\n return emitError(\"query\");\n state = STATE_QUERIED;\n }\n break;\n case STATE_QUERIED:\n\/\/DEBUG(\"STATE_QUERIED\");\n mysql_res = mysql_use_result(&mysql);\n if (!mysql_res)\n return emitError(\"query\");\n state = STATE_ROWSTREAM;\n break;\n case STATE_ROWSTREAM:\n\/\/DEBUG(\"STATE_ROWSTREAM\");\n status = mysql_fetch_row_start(&mysql_row, mysql_res);\n if (status) {\n done = true;\n state = STATE_ROWSTREAMING;\n } else\n state = STATE_ROWSTREAMED;\n break;\n case STATE_ROWSTREAMING:\n\/\/DEBUG(\"STATE_ROWSTREAMING\");\n status = mysql_fetch_row_cont(&mysql_row, mysql_res,\n mysql_status(event));\n if (status)\n done = true;\n else\n state = STATE_ROWSTREAMED;\n break;\n case STATE_ROWSTREAMED:\n\/\/DEBUG(\"STATE_ROWSTREAMED\");\n if (mysql_row) {\n state = STATE_ROWSTREAM;\n emitRow();\n } else {\n if (mysql_errno(&mysql)) {\n mysql_free_result(mysql_res);\n return emitError(\"result\");\n } else {\n \/\/ no more rows\n mysql_free_result(mysql_res);\n state = STATE_CONNECTED;\n emit(\"done\");\n }\n }\n break;\n case STATE_CLOSE:\n\/\/DEBUG(\"STATE_CLOSE\");\n mysql_close(&mysql);\n state = STATE_CLOSED;\n uv_close((uv_handle_t*) &poll_handle, cbClose);\n return;\n case STATE_CLOSED:\n return;\n }\n }\n if (status & MYSQL_WAIT_READ)\n new_events |= UV_READABLE;\n if (status & MYSQL_WAIT_WRITE)\n new_events |= UV_WRITABLE;\n uv_poll_start(&poll_handle, new_events, cbPoll);\n }\n\n void emitError(const char* when, bool doClose = false) {\n HandleScope scope;\n hadError = true;\n Local<Function> Emit = Local<Function>::Cast(handle_->Get(emit_symbol));\n Local<Value> err = Exception::Error(String::New(mysql_error(&mysql)));\n Local<Object> err_obj = err->ToObject();\n err_obj->Set(String::New(\"code\"),\n Integer::NewFromUnsigned(mysql_errno(&mysql)));\n err_obj->Set(String::New(\"when\"), String::New(when));\n Local<Value> emit_argv[2] = {\n String::New(\"error\"),\n err\n };\n TryCatch try_catch;\n Emit->Call(handle_, 2, emit_argv);\n if (try_catch.HasCaught())\n FatalException(try_catch);\n if (doClose)\n close();\n }\n\n void emit(const char* eventName) {\n HandleScope scope;\n Local<Function> Emit = Local<Function>::Cast(handle_->Get(emit_symbol));\n Local<Value> emit_argv[1] = {\n String::New(eventName)\n };\n TryCatch try_catch;\n Emit->Call(handle_, 1, emit_argv);\n if (try_catch.HasCaught())\n FatalException(try_catch);\n }\n\n void emitRow() {\n HandleScope scope;\n unsigned int i = 0, len = mysql_num_fields(mysql_res);\n char* field;\n Local<Function> Emit = Local<Function>::Cast(handle_->Get(emit_symbol));\n Local<Object> row = Object::New();\n for (; i<len; ++i) {\n field = mysql_fetch_field_direct(mysql_res, i)->name;\n row->Set(String::New(field), (mysql_row[i]\n ? String::New(mysql_row[i])\n : Null()));\n }\n Local<Value> emit_argv[2] = {\n String::New(\"result\"),\n row\n };\n TryCatch try_catch;\n Emit->Call(handle_, 2, emit_argv);\n if (try_catch.HasCaught())\n FatalException(try_catch);\n }\n\n static void cbPoll(uv_poll_t* handle, int status, int events) {\n HandleScope scope;\n Client* obj = (Client*) handle->data;\n assert(status == 0);\n\n int mysql_status = 0;\n if (events & UV_READABLE)\n mysql_status |= MYSQL_WAIT_READ;\n if (events & UV_WRITABLE)\n mysql_status |= MYSQL_WAIT_WRITE;\n \/*if (events & UV_TIMEOUT)\n mysql_status |= MYSQL_WAIT_TIMEOUT;*\/\n obj->doWork(mysql_status);\n }\n\n static void cbClose(uv_handle_t* handle) {\n HandleScope scope;\n Client* obj = (Client*) handle->data;\n Local<Function> Emit = Local<Function>::Cast(obj->handle_->Get(emit_symbol));\n TryCatch try_catch;\n Local<Value> emit_argv[2] = {\n String::New(\"close\"),\n Local<Boolean>::New(Boolean::New(obj->hadError))\n };\n Emit->Call(obj->handle_, 2, emit_argv);\n if (try_catch.HasCaught())\n FatalException(try_catch);\n }\n\n static Handle<Value> New(const Arguments& args) {\n HandleScope scope;\n\n if (!args.IsConstructCall()) {\n return ThrowException(Exception::TypeError(\n String::New(\"Use `new` to create instances of this object.\"))\n );\n }\n\n Client* obj = new Client();\n obj->Wrap(args.This());\n\n return args.This();\n }\n\n static Handle<Value> Escape(const Arguments& args) {\n HandleScope scope;\n Client* obj = ObjectWrap::Unwrap<Client>(args.This());\n\n if (obj->state < STATE_CONNECTED) {\n return ThrowException(Exception::Error(\n String::New(\"Not connected\"))\n );\n } else if (args.Length() == 0 || !args[0]->IsString()) {\n return ThrowException(Exception::Error(\n String::New(\"You must supply a string\"))\n );\n }\n String::Utf8Value arg_s(args[0]);\n char* newstr = obj->escape(*arg_s);\n Local<String> escaped_s = String::New(newstr);\n free(newstr);\n return scope.Close(escaped_s);\n }\n\n static Handle<Value> Connect(const Arguments& args) {\n HandleScope scope;\n Client* obj = ObjectWrap::Unwrap<Client>(args.This());\n\n if (obj->state != STATE_CLOSED) {\n return ThrowException(Exception::Error(\n String::New(\"Not ready to connect\"))\n );\n }\n\n obj->init();\n\n Local<Object> cfg = args[0]->ToObject();\n Local<Value> user_v = cfg->Get(String::New(\"user\"));\n Local<Value> password_v = cfg->Get(String::New(\"password\"));\n Local<Value> ip_v = cfg->Get(String::New(\"host\"));\n Local<Value> port_v = cfg->Get(String::New(\"port\"));\n Local<Value> db_v = cfg->Get(String::New(\"db\"));\n Local<Value> compress_v = cfg->Get(String::New(\"compress\"));\n Local<Value> ssl_v = cfg->Get(String::New(\"secure\"));\n\n if (!user_v->IsString() || user_v->ToString()->Length() == 0)\n obj->config.user = NULL;\n else {\n String::Utf8Value user_s(user_v);\n obj->config.user = strdup(*user_s);\n }\n if (!password_v->IsString() || password_v->ToString()->Length() == 0)\n obj->config.password = NULL;\n else {\n String::Utf8Value password_s(password_v);\n obj->config.password = strdup(*password_s);\n }\n if (!ip_v->IsString() || ip_v->ToString()->Length() == 0)\n obj->config.ip = NULL;\n else {\n String::Utf8Value ip_s(ip_v);\n obj->config.ip = strdup(*ip_s);\n }\n if (!port_v->IsUint32() || port_v->Uint32Value() == 0)\n obj->config.port = 3306;\n else\n obj->config.port = port_v->Uint32Value();\n\n if (db_v->IsString() && db_v->ToString()->Length() > 0) {\n String::Utf8Value db_s(db_v);\n obj->config.db = strdup(*db_s);\n }\n\n obj->connect();\n\n return Undefined();\n }\n\n static Handle<Value> Query(const Arguments& args) {\n HandleScope scope;\n Client* obj = ObjectWrap::Unwrap<Client>(args.This());\n if (obj->state != STATE_CONNECTED) {\n return ThrowException(Exception::Error(\n String::New(\"Not ready to query\"))\n );\n }\n if (args.Length() == 0 || !args[0]->IsString()) {\n return ThrowException(Exception::Error(\n String::New(\"Query expected\"))\n );\n }\n String::Utf8Value query(args[0]);\n obj->query(*query);\n return Undefined();\n }\n\n static Handle<Value> Close(const Arguments& args) {\n HandleScope scope;\n Client* obj = ObjectWrap::Unwrap<Client>(args.This());\n if (obj->state == STATE_CLOSED) {\n return ThrowException(Exception::Error(\n String::New(\"Already closed\"))\n );\n }\n obj->close();\n return Undefined();\n }\n\n static void Initialize(Handle<Object> target) {\n HandleScope scope;\n\n Local<FunctionTemplate> tpl = FunctionTemplate::New(New);\n Local<String> name = String::NewSymbol(\"Client\");\n\n Client_constructor = Persistent<FunctionTemplate>::New(tpl);\n Client_constructor->InstanceTemplate()->SetInternalFieldCount(1);\n Client_constructor->SetClassName(name);\n\n NODE_SET_PROTOTYPE_METHOD(Client_constructor, \"connect\", Connect);\n NODE_SET_PROTOTYPE_METHOD(Client_constructor, \"query\", Query);\n NODE_SET_PROTOTYPE_METHOD(Client_constructor, \"escape\", Escape);\n NODE_SET_PROTOTYPE_METHOD(Client_constructor, \"end\", Close);\n\n emit_symbol = NODE_PSYMBOL(\"emit\");\n target->Set(name, Client_constructor->GetFunction());\n }\n};\n\nstatic Handle<Value> Version(const Arguments& args) {\n HandleScope scope;\n unsigned long client_ver = mysql_get_client_version();\n char major = (client_ver >> 16) & 0xFF,\n release = (client_ver >> 8) & 0xFF,\n rel_ver = client_ver & 0xFF;\n int slen = (major < 10 ? 1 : 2)\n + (release < 10 ? 1 : 2)\n + (rel_ver < 10 ? 1 : 2);\n char* ver = (char*) malloc(slen + 3);\n sprintf(ver, \"%u.%u.%u\", major, release, rel_ver);\n Local<String> ver_str = String::New(ver);\n free(ver);\n return scope.Close(ver_str);\n}\n\nextern \"C\" {\n void init(Handle<Object> target) {\n HandleScope scope;\n Client::Initialize(target);\n target->Set(String::NewSymbol(\"version\"),\n FunctionTemplate::New(Version)->GetFunction());\n }\n\n NODE_MODULE(sqlclient, init);\n}<commit_msg>Fix for queries that do not return a result<commit_after>#include <node.h>\n#include <stdlib.h>\n#include <mysql\/mysql.h>\n\nusing namespace node;\nusing namespace v8;\n\nstatic Persistent<FunctionTemplate> Client_constructor;\nstatic Persistent<String> emit_symbol;\n\nconst int STATE_CLOSE = -2,\n STATE_CLOSED = -1,\n STATE_CONNECT = 0,\n STATE_CONNECTING = 1,\n STATE_CONNECTED = 2,\n STATE_QUERY = 3,\n STATE_QUERYING = 4,\n STATE_QUERIED = 5,\n STATE_ROWSTREAM = 6,\n STATE_ROWSTREAMING = 7,\n STATE_ROWSTREAMED = 8;\n\nstruct sql_config {\n char* user;\n char* password;\n char* ip;\n char* db;\n unsigned int port;\n bool compress;\n};\n\n#include <stdio.h>\n#define DEBUG(s) fprintf(stderr, \"BINDING: \" s \"\\n\")\n\nclass Client : public ObjectWrap {\n public:\n uv_poll_t poll_handle;\n MYSQL mysql, *mysql_ret;\n MYSQL_RES *mysql_res;\n MYSQL_ROW mysql_row;\n int mysql_qerr;\n char* cur_query;\n sql_config config;\n bool hadError;\n int state;\n\n Client() {\n state = STATE_CLOSED;\n }\n\n ~Client() {\n close();\n }\n\n void init() {\n config.user = NULL;\n config.password = NULL;\n config.ip = NULL;\n config.db = NULL;\n cur_query = NULL;\n hadError = false;\n poll_handle.type = UV_UNKNOWN_HANDLE;\n\n mysql_init(&mysql);\n mysql_options(&mysql, MYSQL_OPT_NONBLOCK, 0);\n }\n\n void connect() {\n if (state == STATE_CLOSED) {\n state = STATE_CONNECT;\n doWork();\n }\n }\n\n void close() {\n if (state != STATE_CLOSED) {\n if (config.user) {\n free(config.user);\n config.user = NULL;\n }\n if (config.password) {\n free(config.password);\n config.password = NULL;\n }\n if (config.ip) {\n free(config.ip);\n config.ip = NULL;\n }\n if (config.db) {\n free(config.db);\n config.db = NULL;\n }\n if (cur_query) {\n free(cur_query);\n cur_query = NULL;\n }\n \n state = STATE_CLOSE;\n doWork();\n }\n }\n\n char* escape(const char* str) {\n unsigned int str_len = strlen(str);\n char* dest = (char*) malloc(str_len * 2 + 1);\n mysql_real_escape_string(&mysql, dest, str, str_len);\n return dest;\n }\n\n void query(const char* qry) {\n if (state == STATE_CONNECTED) {\n cur_query = strdup(qry);\n state = STATE_QUERY;\n doWork();\n }\n }\n\n void doWork(int event = 0) {\n int status = 0, new_events = 0;\n bool done = false;\n while (!done) {\n switch (state) {\n case STATE_CONNECT:\n\/\/DEBUG(\"STATE_CONNECT\");\n status = mysql_real_connect_start(&mysql_ret, &mysql,\n config.ip,\n config.user,\n config.password,\n config.db,\n config.port, NULL, 0);\n uv_poll_init_socket(uv_default_loop(), &poll_handle,\n mysql_get_socket(&mysql));\n poll_handle.data = this;\n if (status) {\n state = STATE_CONNECTING;\n done = true;\n } else {\n state = STATE_CONNECTED;\n emit(\"connect\");\n }\n break;\n case STATE_CONNECTING:\n\/\/DEBUG(\"STATE_CONNECTING\");\n status = mysql_real_connect_cont(&mysql_ret, &mysql, event);\n if (status)\n done = true;\n else {\n if (!mysql_ret)\n return emitError(\"conn\", true);\n state = STATE_CONNECTED;\n emit(\"connect\");\n }\n break;\n case STATE_CONNECTED:\n\/\/DEBUG(\"STATE_CONNECTED\");\n done = true;\n break;\n case STATE_QUERY:\n\/\/DEBUG(\"STATE_QUERY\");\n status = mysql_real_query_start(&mysql_qerr, &mysql, cur_query,\n strlen(cur_query));\n if (status) {\n state = STATE_QUERYING;\n done = true;\n } else\n state = STATE_QUERIED;\n break;\n case STATE_QUERYING:\n\/\/DEBUG(\"STATE_QUERYING\");\n status = mysql_real_query_cont(&mysql_qerr, &mysql,\n mysql_status(event));\n if (status)\n done = true;\n else {\n if (cur_query) {\n free(cur_query);\n cur_query = NULL;\n }\n if (mysql_qerr)\n return emitError(\"query\");\n state = STATE_QUERIED;\n }\n break;\n case STATE_QUERIED:\n\/\/DEBUG(\"STATE_QUERIED\");\n mysql_res = mysql_use_result(&mysql);\n if (!mysql_res) {\n if (mysql_errno(&mysql))\n return emitError(\"query\");\n state = STATE_CONNECTED;\n emit(\"done\");\n } else\n state = STATE_ROWSTREAM;\n break;\n case STATE_ROWSTREAM:\n\/\/DEBUG(\"STATE_ROWSTREAM\");\n status = mysql_fetch_row_start(&mysql_row, mysql_res);\n if (status) {\n done = true;\n state = STATE_ROWSTREAMING;\n } else\n state = STATE_ROWSTREAMED;\n break;\n case STATE_ROWSTREAMING:\n\/\/DEBUG(\"STATE_ROWSTREAMING\");\n status = mysql_fetch_row_cont(&mysql_row, mysql_res,\n mysql_status(event));\n if (status)\n done = true;\n else\n state = STATE_ROWSTREAMED;\n break;\n case STATE_ROWSTREAMED:\n\/\/DEBUG(\"STATE_ROWSTREAMED\");\n if (mysql_row) {\n state = STATE_ROWSTREAM;\n emitRow();\n } else {\n if (mysql_errno(&mysql)) {\n mysql_free_result(mysql_res);\n return emitError(\"result\");\n } else {\n \/\/ no more rows\n mysql_free_result(mysql_res);\n state = STATE_CONNECTED;\n emit(\"done\");\n }\n }\n break;\n case STATE_CLOSE:\n\/\/DEBUG(\"STATE_CLOSE\");\n mysql_close(&mysql);\n state = STATE_CLOSED;\n uv_close((uv_handle_t*) &poll_handle, cbClose);\n return;\n case STATE_CLOSED:\n return;\n }\n }\n if (status & MYSQL_WAIT_READ)\n new_events |= UV_READABLE;\n if (status & MYSQL_WAIT_WRITE)\n new_events |= UV_WRITABLE;\n uv_poll_start(&poll_handle, new_events, cbPoll);\n }\n\n void emitError(const char* when, bool doClose = false) {\n HandleScope scope;\n hadError = true;\n Local<Function> Emit = Local<Function>::Cast(handle_->Get(emit_symbol));\n Local<Value> err = Exception::Error(String::New(mysql_error(&mysql)));\n Local<Object> err_obj = err->ToObject();\n err_obj->Set(String::New(\"code\"),\n Integer::NewFromUnsigned(mysql_errno(&mysql)));\n err_obj->Set(String::New(\"when\"), String::New(when));\n Local<Value> emit_argv[2] = {\n String::New(\"error\"),\n err\n };\n TryCatch try_catch;\n Emit->Call(handle_, 2, emit_argv);\n if (try_catch.HasCaught())\n FatalException(try_catch);\n if (doClose)\n close();\n }\n\n void emit(const char* eventName) {\n HandleScope scope;\n Local<Function> Emit = Local<Function>::Cast(handle_->Get(emit_symbol));\n Local<Value> emit_argv[1] = {\n String::New(eventName)\n };\n TryCatch try_catch;\n Emit->Call(handle_, 1, emit_argv);\n if (try_catch.HasCaught())\n FatalException(try_catch);\n }\n\n void emitRow() {\n HandleScope scope;\n unsigned int i = 0, len = mysql_num_fields(mysql_res);\n char* field;\n Local<Function> Emit = Local<Function>::Cast(handle_->Get(emit_symbol));\n Local<Object> row = Object::New();\n for (; i<len; ++i) {\n field = mysql_fetch_field_direct(mysql_res, i)->name;\n row->Set(String::New(field), (mysql_row[i]\n ? String::New(mysql_row[i])\n : Null()));\n }\n Local<Value> emit_argv[2] = {\n String::New(\"result\"),\n row\n };\n TryCatch try_catch;\n Emit->Call(handle_, 2, emit_argv);\n if (try_catch.HasCaught())\n FatalException(try_catch);\n }\n\n static void cbPoll(uv_poll_t* handle, int status, int events) {\n HandleScope scope;\n Client* obj = (Client*) handle->data;\n assert(status == 0);\n\n int mysql_status = 0;\n if (events & UV_READABLE)\n mysql_status |= MYSQL_WAIT_READ;\n if (events & UV_WRITABLE)\n mysql_status |= MYSQL_WAIT_WRITE;\n \/*if (events & UV_TIMEOUT)\n mysql_status |= MYSQL_WAIT_TIMEOUT;*\/\n obj->doWork(mysql_status);\n }\n\n static void cbClose(uv_handle_t* handle) {\n HandleScope scope;\n Client* obj = (Client*) handle->data;\n Local<Function> Emit = Local<Function>::Cast(obj->handle_->Get(emit_symbol));\n TryCatch try_catch;\n Local<Value> emit_argv[2] = {\n String::New(\"close\"),\n Local<Boolean>::New(Boolean::New(obj->hadError))\n };\n Emit->Call(obj->handle_, 2, emit_argv);\n if (try_catch.HasCaught())\n FatalException(try_catch);\n }\n\n static Handle<Value> New(const Arguments& args) {\n HandleScope scope;\n\n if (!args.IsConstructCall()) {\n return ThrowException(Exception::TypeError(\n String::New(\"Use `new` to create instances of this object.\"))\n );\n }\n\n Client* obj = new Client();\n obj->Wrap(args.This());\n\n return args.This();\n }\n\n static Handle<Value> Escape(const Arguments& args) {\n HandleScope scope;\n Client* obj = ObjectWrap::Unwrap<Client>(args.This());\n\n if (obj->state < STATE_CONNECTED) {\n return ThrowException(Exception::Error(\n String::New(\"Not connected\"))\n );\n } else if (args.Length() == 0 || !args[0]->IsString()) {\n return ThrowException(Exception::Error(\n String::New(\"You must supply a string\"))\n );\n }\n String::Utf8Value arg_s(args[0]);\n char* newstr = obj->escape(*arg_s);\n Local<String> escaped_s = String::New(newstr);\n free(newstr);\n return scope.Close(escaped_s);\n }\n\n static Handle<Value> Connect(const Arguments& args) {\n HandleScope scope;\n Client* obj = ObjectWrap::Unwrap<Client>(args.This());\n\n if (obj->state != STATE_CLOSED) {\n return ThrowException(Exception::Error(\n String::New(\"Not ready to connect\"))\n );\n }\n\n obj->init();\n\n Local<Object> cfg = args[0]->ToObject();\n Local<Value> user_v = cfg->Get(String::New(\"user\"));\n Local<Value> password_v = cfg->Get(String::New(\"password\"));\n Local<Value> ip_v = cfg->Get(String::New(\"host\"));\n Local<Value> port_v = cfg->Get(String::New(\"port\"));\n Local<Value> db_v = cfg->Get(String::New(\"db\"));\n Local<Value> compress_v = cfg->Get(String::New(\"compress\"));\n Local<Value> ssl_v = cfg->Get(String::New(\"secure\"));\n\n if (!user_v->IsString() || user_v->ToString()->Length() == 0)\n obj->config.user = NULL;\n else {\n String::Utf8Value user_s(user_v);\n obj->config.user = strdup(*user_s);\n }\n if (!password_v->IsString() || password_v->ToString()->Length() == 0)\n obj->config.password = NULL;\n else {\n String::Utf8Value password_s(password_v);\n obj->config.password = strdup(*password_s);\n }\n if (!ip_v->IsString() || ip_v->ToString()->Length() == 0)\n obj->config.ip = NULL;\n else {\n String::Utf8Value ip_s(ip_v);\n obj->config.ip = strdup(*ip_s);\n }\n if (!port_v->IsUint32() || port_v->Uint32Value() == 0)\n obj->config.port = 3306;\n else\n obj->config.port = port_v->Uint32Value();\n\n if (db_v->IsString() && db_v->ToString()->Length() > 0) {\n String::Utf8Value db_s(db_v);\n obj->config.db = strdup(*db_s);\n }\n\n obj->connect();\n\n return Undefined();\n }\n\n static Handle<Value> Query(const Arguments& args) {\n HandleScope scope;\n Client* obj = ObjectWrap::Unwrap<Client>(args.This());\n if (obj->state != STATE_CONNECTED) {\n return ThrowException(Exception::Error(\n String::New(\"Not ready to query\"))\n );\n }\n if (args.Length() == 0 || !args[0]->IsString()) {\n return ThrowException(Exception::Error(\n String::New(\"Query expected\"))\n );\n }\n String::Utf8Value query(args[0]);\n obj->query(*query);\n return Undefined();\n }\n\n static Handle<Value> Close(const Arguments& args) {\n HandleScope scope;\n Client* obj = ObjectWrap::Unwrap<Client>(args.This());\n if (obj->state == STATE_CLOSED) {\n return ThrowException(Exception::Error(\n String::New(\"Already closed\"))\n );\n }\n obj->close();\n return Undefined();\n }\n\n static void Initialize(Handle<Object> target) {\n HandleScope scope;\n\n Local<FunctionTemplate> tpl = FunctionTemplate::New(New);\n Local<String> name = String::NewSymbol(\"Client\");\n\n Client_constructor = Persistent<FunctionTemplate>::New(tpl);\n Client_constructor->InstanceTemplate()->SetInternalFieldCount(1);\n Client_constructor->SetClassName(name);\n\n NODE_SET_PROTOTYPE_METHOD(Client_constructor, \"connect\", Connect);\n NODE_SET_PROTOTYPE_METHOD(Client_constructor, \"query\", Query);\n NODE_SET_PROTOTYPE_METHOD(Client_constructor, \"escape\", Escape);\n NODE_SET_PROTOTYPE_METHOD(Client_constructor, \"end\", Close);\n\n emit_symbol = NODE_PSYMBOL(\"emit\");\n target->Set(name, Client_constructor->GetFunction());\n }\n};\n\nstatic Handle<Value> Version(const Arguments& args) {\n HandleScope scope;\n unsigned long client_ver = mysql_get_client_version();\n char major = (client_ver >> 16) & 0xFF,\n release = (client_ver >> 8) & 0xFF,\n rel_ver = client_ver & 0xFF;\n int slen = (major < 10 ? 1 : 2)\n + (release < 10 ? 1 : 2)\n + (rel_ver < 10 ? 1 : 2);\n char* ver = (char*) malloc(slen + 3);\n sprintf(ver, \"%u.%u.%u\", major, release, rel_ver);\n Local<String> ver_str = String::New(ver);\n free(ver);\n return scope.Close(ver_str);\n}\n\nextern \"C\" {\n void init(Handle<Object> target) {\n HandleScope scope;\n Client::Initialize(target);\n target->Set(String::NewSymbol(\"version\"),\n FunctionTemplate::New(Version)->GetFunction());\n }\n\n NODE_MODULE(sqlclient, init);\n}<|endoftext|>"} {"text":"<commit_before>\/*\n * cdirectory.cc\n *\n * Created on: 16.09.2013\n * Author: andreas\n *\/\n\n#include \"cdirectory.h\"\n\nusing namespace rutils;\n\n\ncdirectory::cdirectory(std::string const& dirpath) :\n\t\tdirpath(dirpath)\n{\n\tif ((dir_handle = opendir(dirpath.c_str())) == 0) {\n\t\tswitch (errno) {\n\t\tcase EACCES: throw eDirAccess();\n\t\tcase EMFILE: throw eDirEMfile();\n\t\tcase ENFILE: throw eDirENfile();\n\t\tcase ENOENT: throw eDirNoEnt();\n\t\tcase ENOMEM: throw eDirNoMem();\n\t\tcase ENOTDIR: throw eDirNotDir();\n\t\t}\n\t}\n\n\treaddir();\n}\n\n\n\ncdirectory::~cdirectory()\n{\n\tpurge_dirs();\n\n\tpurge_files();\n\n\tif (closedir(dir_handle) < 0) {\n\t\tswitch (errno) {\n\t\tcase EBADF: throw eDirBadFd();\n\t\t}\n\t}\n}\n\n\n\nvoid\ncdirectory::purge_files()\n{\n\tfor (std::map<std::string, cfile*>::iterator\n\t\t\tit = files.begin(); it != files.end(); ++it) {\n\t\tdelete (it->second);\n\t}\n\tfiles.clear();\n}\n\n\n\nvoid\ncdirectory::purge_dirs()\n{\n\tfor (std::map<std::string, cdirectory*>::iterator\n\t\t\tit = dirs.begin(); it != dirs.end(); ++it) {\n\t\tdelete (it->second);\n\t}\n\tdirs.clear();\n}\n\n\n\nvoid\ncdirectory::readdir()\n{\n\tpurge_dirs();\n\n\tpurge_files();\n\n\tstruct dirent **namelist;\n\tint n;\n\n n = scandir(dirpath.c_str(), &namelist, &select, alphasort);\n if (n < 0)\n perror(\"scandir\");\n else {\n while (n--) {\n fprintf(stderr, \"%s\\n\", namelist[n]->d_name);\n \t\tstruct stat statbuf;\n\n \t\tif (::stat(namelist[n]->d_name, &statbuf) < 0) {\n \t\t\tcontinue;\n \t\t}\n\n \t\tif (S_ISREG(statbuf.st_mode)) {\n \t\t\taddfile(namelist[n]->d_name);\n \t\t}\n \t\telse if (S_ISDIR(statbuf.st_mode)) {\n \t\t\tadddir(namelist[n]->d_name);\n \t\t}\n \t\telse {\n\n \t\t}\n free(namelist[n]);\n }\n free(namelist);\n }\n\n#if 0\n\tstruct dirent *dp = (struct dirent*)0;\n\n\n\twhile ((dp = ::readdir(dir_handle)) != 0) {\n\n\t\tstruct stat statbuf;\n\n\t\tif (::stat(dp->d_name, &statbuf) < 0) {\n\t\t\tthrow eDirSyscall();\n\t\t}\n\n\t\tif (S_ISREG(statbuf.st_mode)) {\n\t\t\taddfile(dp->d_name);\n\t\t}\n\t\telse if (S_ISDIR(statbuf.st_mode)) {\n\t\t\tadddir(dp->d_name);\n\t\t}\n\t\telse {\n\n\t\t}\n\t}\n#endif\n}\n\n\n\nint\ncdirectory::select(const struct dirent* dir)\n{\n\tstd::string name(dir->d_name);\n\n\tif (name == \"..\")\n\t\treturn 0;\n\tif (name == \".\")\n\t\treturn 0;\n\n\treturn 1;\n}\n\n\n\nvoid\ncdirectory::addfile(std::string const& filename)\n{\n\tif (files.find(filename) != files.end()) {\n\t\tthrow eDirExists();\n\t}\n\tfiles[filename] = new cfile(filename, dirpath);\n}\n\n\n\nvoid\ncdirectory::delfile(std::string const& filename)\n{\n\tif (files.find(filename) == files.end()) {\n\t\tthrow eDirNotFound();\n\t}\n\tdelete files[filename];\n\tfiles.erase(filename);\n}\n\n\n\nvoid\ncdirectory::adddir(\n\t\tstd::string const& dirname)\n{\n\tif (dirs.find(dirname) != dirs.end()) {\n\t\tthrow eDirExists();\n\t}\n\tdirs[dirname] = new cdirectory(dirname);\n}\n\n\n\nvoid\ncdirectory::deldir(\n\t\tstd::string const& dirname)\n{\n\tif (dirs.find(dirname) == dirs.end()) {\n\t\tthrow eDirNotFound();\n\t}\n\tdelete dirs[dirname];\n\tdirs.erase(dirname);\n}\n\n\n\n<commit_msg>cdirectory: avoid exceptions in addfile(), delfile(), adddir(), deldir()<commit_after>\/*\n * cdirectory.cc\n *\n * Created on: 16.09.2013\n * Author: andreas\n *\/\n\n#include \"cdirectory.h\"\n\nusing namespace rutils;\n\n\ncdirectory::cdirectory(std::string const& dirpath) :\n\t\tdirpath(dirpath)\n{\n\tif ((dir_handle = opendir(dirpath.c_str())) == 0) {\n\t\tswitch (errno) {\n\t\tcase EACCES: throw eDirAccess();\n\t\tcase EMFILE: throw eDirEMfile();\n\t\tcase ENFILE: throw eDirENfile();\n\t\tcase ENOENT: throw eDirNoEnt();\n\t\tcase ENOMEM: throw eDirNoMem();\n\t\tcase ENOTDIR: throw eDirNotDir();\n\t\t}\n\t}\n\n\treaddir();\n}\n\n\n\ncdirectory::~cdirectory()\n{\n\tpurge_dirs();\n\n\tpurge_files();\n\n\tif (closedir(dir_handle) < 0) {\n\t\tswitch (errno) {\n\t\tcase EBADF: throw eDirBadFd();\n\t\t}\n\t}\n}\n\n\n\nvoid\ncdirectory::purge_files()\n{\n\tfor (std::map<std::string, cfile*>::iterator\n\t\t\tit = files.begin(); it != files.end(); ++it) {\n\t\tdelete (it->second);\n\t}\n\tfiles.clear();\n}\n\n\n\nvoid\ncdirectory::purge_dirs()\n{\n\tfor (std::map<std::string, cdirectory*>::iterator\n\t\t\tit = dirs.begin(); it != dirs.end(); ++it) {\n\t\tdelete (it->second);\n\t}\n\tdirs.clear();\n}\n\n\n\nvoid\ncdirectory::readdir()\n{\n\tpurge_dirs();\n\n\tpurge_files();\n\n\tstruct dirent **namelist;\n\tint n;\n\n n = scandir(dirpath.c_str(), &namelist, &select, alphasort);\n if (n < 0)\n perror(\"scandir\");\n else {\n while (n--) {\n fprintf(stderr, \"%s\\n\", namelist[n]->d_name);\n \t\tstruct stat statbuf;\n\n \t\tif (::stat(namelist[n]->d_name, &statbuf) < 0) {\n \t\t\tcontinue;\n \t\t}\n\n \t\tif (S_ISREG(statbuf.st_mode)) {\n \t\t\taddfile(namelist[n]->d_name);\n \t\t}\n \t\telse if (S_ISDIR(statbuf.st_mode)) {\n \t\t\tadddir(namelist[n]->d_name);\n \t\t}\n \t\telse {\n\n \t\t}\n free(namelist[n]);\n }\n free(namelist);\n }\n}\n\n\n\nint\ncdirectory::select(const struct dirent* dir)\n{\n\tstd::string name(dir->d_name);\n\n\tif (name == \"..\")\n\t\treturn 0;\n\tif (name == \".\")\n\t\treturn 0;\n\n\treturn 1;\n}\n\n\n\nvoid\ncdirectory::addfile(std::string const& filename)\n{\n\tif (files.find(filename) != files.end()) {\n\t\treturn;\n\t}\n\tfiles[filename] = new cfile(filename, dirpath);\n}\n\n\n\nvoid\ncdirectory::delfile(std::string const& filename)\n{\n\tif (files.find(filename) == files.end()) {\n\t\treturn;\n\t}\n\tdelete files[filename];\n\tfiles.erase(filename);\n}\n\n\n\nvoid\ncdirectory::adddir(\n\t\tstd::string const& dirname)\n{\n\tif (dirs.find(dirname) != dirs.end()) {\n\t\treturn;\n\t}\n\tdirs[dirname] = new cdirectory(dirname);\n}\n\n\n\nvoid\ncdirectory::deldir(\n\t\tstd::string const& dirname)\n{\n\tif (dirs.find(dirname) == dirs.end()) {\n\t\treturn;\n\t}\n\tdelete dirs[dirname];\n\tdirs.erase(dirname);\n}\n\n\n\n<|endoftext|>"} {"text":"<commit_before>\/******************************************************************************\n* SOFA, Simulation Open-Framework Architecture, development version *\n* (c) 2006-2016 INRIA, USTL, UJF, CNRS, MGH *\n* *\n* This program is free software; you can redistribute it and\/or modify it *\n* under the terms of the GNU General Public License as published by the Free *\n* Software Foundation; either version 2 of the License, or (at your option) *\n* any later version. *\n* *\n* This program is distributed in the hope that it will be useful, but WITHOUT *\n* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or *\n* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for *\n* more details. *\n* *\n* You should have received a copy of the GNU General Public License along *\n* with this program; if not, write to the Free Software Foundation, Inc., 51 *\n* Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. *\n*******************************************************************************\n* SOFA :: Applications *\n* *\n* Authors: The SOFA Team and external contributors (see Authors.txt) *\n* *\n* Contact information: contact@sofa-framework.org *\n******************************************************************************\/\n#include <iostream>\n#include <sstream>\n#include <fstream>\n#include <sofa\/helper\/ArgumentParser.h>\n#include <sofa\/helper\/UnitTest.h>\n#include <sofa\/helper\/vector_algebra.h>\n#include <sofa\/helper\/vector.h>\n#include <sofa\/helper\/BackTrace.h>\n#include <sofa\/helper\/system\/PluginManager.h>\n\n#include <sofa\/simulation\/Node.h>\n#include <sofa\/simulation\/Simulation.h>\n#include <SofaSimulationTree\/init.h>\n#include <SofaSimulationTree\/TreeSimulation.h>\n\n#include <sofa\/gui\/GUIManager.h>\n#include <sofa\/gui\/Main.h>\n#include <sofa\/helper\/system\/FileRepository.h>\n\n#include <SofaComponentBase\/initComponentBase.h>\n#include <SofaComponentCommon\/initComponentCommon.h>\n#include <SofaComponentGeneral\/initComponentGeneral.h>\n#include <SofaComponentAdvanced\/initComponentAdvanced.h>\n#include <SofaComponentMisc\/initComponentMisc.h>\n#include <SofaMiscMapping\/SubsetMultiMapping.h>\n#include <SofaBaseTopology\/MeshTopology.h>\n#include <SofaBaseTopology\/EdgeSetTopologyContainer.h>\n#include <SofaBaseTopology\/RegularGridTopology.h>\n#include <SofaBaseCollision\/SphereModel.h>\n#include <SofaGeneralTopology\/CubeTopology.h>\n#include <SofaBaseVisual\/VisualStyle.h>\n#include <SofaImplicitOdeSolver\/EulerImplicitSolver.h>\n#include <SofaBaseLinearSolver\/CGLinearSolver.h>\n\n\/\/Using double by default, if you have SOFA_FLOAT in use in you sofa-default.cfg, then it will be FLOAT.\n#include <sofa\/component\/typedef\/Sofa_typedef.h>\n\n#include <utility>\n\n\n\nusing namespace sofa;\nusing namespace sofa::helper;\nusing helper::vector;\nusing namespace sofa::simulation;\nusing namespace sofa::core::objectmodel;\nusing namespace sofa::component::container;\nusing namespace sofa::component::topology;\nusing namespace sofa::component::collision;\nusing namespace sofa::component::visualmodel;\nusing namespace sofa::component::mapping;\nusing namespace sofa::component::forcefield;\n\ntypedef SReal Scalar;\ntypedef Vec<3,SReal> Vec3;\ntypedef Vec<1,SReal> Vec1;\ntypedef component::odesolver::EulerImplicitSolver EulerImplicitSolver;\ntypedef component::linearsolver::CGLinearSolver<component::linearsolver::GraphScatteredMatrix, component::linearsolver::GraphScatteredVector> CGLinearSolver;\n\n\nbool startAnim = true;\nbool verbose = false;\nSReal complianceValue = 0.1;\nVec3 gravity(0,-1,0);\nSReal dt = 0.01;\n\n\/\/\/ helper for more compact component creation\ntemplate<class Component>\ntypename Component::SPtr addNew( Node::SPtr parentNode, std::string name=\"\" )\n{\n typename Component::SPtr component = New<Component>();\n parentNode->addObject(component);\n component->setName(parentNode->getName()+\"_\"+name);\n return component;\n}\n\n\n\/\/\/ Create an assembly of a siff hexahedral grid with other objects\nsimulation::Node::SPtr createGridScene(Vec3 startPoint, Vec3 endPoint, unsigned numX, unsigned numY, unsigned numZ, double totalMass\/*, double stiffnessValue, double dampingRatio=0.0*\/ )\n{\n using helper::vector;\n\n \/\/ The graph root node\n Node::SPtr root = simulation::getSimulation()->createNewGraph(\"root\");\n root->setGravity( Coord3(0,-10,0) );\n root->setAnimate(false);\n root->setDt(0.01);\n addVisualStyle(root)->setShowVisual(false).setShowCollision(false).setShowMapping(true).setShowBehavior(true);\n\n Node::SPtr simulatedScene = root->createChild(\"simulatedScene\");\n\n EulerImplicitSolver::SPtr eulerImplicitSolver = New<EulerImplicitSolver>();\n simulatedScene->addObject( eulerImplicitSolver );\n CGLinearSolver::SPtr cgLinearSolver = New<CGLinearSolver>();\n simulatedScene->addObject(cgLinearSolver);\n\n \/\/ The rigid object\n Node::SPtr rigidNode = simulatedScene->createChild(\"rigidNode\");\n MechanicalObjectRigid3::SPtr rigid_dof = addNew<MechanicalObjectRigid3>(rigidNode, \"dof\");\n UniformMassRigid3::SPtr rigid_mass = addNew<UniformMassRigid3>(rigidNode,\"mass\");\n FixedConstraintRigid3::SPtr rigid_fixedConstraint = addNew<FixedConstraintRigid3>(rigidNode,\"fixedConstraint\");\n\n \/\/ Particles mapped to the rigid object\n Node::SPtr mappedParticles = rigidNode->createChild(\"mappedParticles\");\n MechanicalObject3::SPtr mappedParticles_dof = addNew< MechanicalObject3>(mappedParticles,\"dof\");\n RigidMappingRigid3_to_3::SPtr mappedParticles_mapping = addNew<RigidMappingRigid3_to_3>(mappedParticles,\"mapping\");\n mappedParticles_mapping->setModels( rigid_dof.get(), mappedParticles_dof.get() );\n\n \/\/ The independent particles\n Node::SPtr independentParticles = simulatedScene->createChild(\"independentParticles\");\n MechanicalObject3::SPtr independentParticles_dof = addNew< MechanicalObject3>(independentParticles,\"dof\");\n\n \/\/ The deformable grid, connected to its 2 parents using a MultiMapping\n Node::SPtr deformableGrid = independentParticles->createChild(\"deformableGrid\"); \/\/ first parent\n mappedParticles->addChild(deformableGrid); \/\/ second parent\n\n RegularGridTopology::SPtr deformableGrid_grid = addNew<RegularGridTopology>( deformableGrid, \"grid\" );\n deformableGrid_grid->setNumVertices(numX,numY,numZ);\n deformableGrid_grid->setPos(startPoint[0],endPoint[0],startPoint[1],endPoint[1],startPoint[2],endPoint[2]);\n\n MechanicalObject3::SPtr deformableGrid_dof = addNew< MechanicalObject3>(deformableGrid,\"dof\");\n\n SubsetMultiMapping3_to_3::SPtr deformableGrid_mapping = addNew<SubsetMultiMapping3_to_3>(deformableGrid,\"mapping\");\n deformableGrid_mapping->addInputModel(independentParticles_dof.get()); \/\/ first parent\n deformableGrid_mapping->addInputModel(mappedParticles_dof.get()); \/\/ second parent\n deformableGrid_mapping->addOutputModel(deformableGrid_dof.get());\n\n UniformMass3::SPtr mass = addNew<UniformMass3>(deformableGrid,\"mass\" );\n mass->mass.setValue( totalMass\/(numX*numY*numZ) );\n\n HexahedronFEMForceField3::SPtr hexaFem = addNew<HexahedronFEMForceField3>(deformableGrid, \"hexaFEM\");\n hexaFem->f_youngModulus.setValue(1000);\n hexaFem->f_poissonRatio.setValue(0.4);\n\n\n \/\/ ====== Set up the multimapping and its parents, based on its child\n deformableGrid_grid->init(); \/\/ initialize the grid, so that the particles are located in space\n deformableGrid_dof->init(); \/\/ create the state vectors\n MechanicalObject3::ReadVecCoord xgrid = deformableGrid_dof->readPositions(); \/\/ cerr<<\"xgrid = \" << xgrid << endl;\n\n\n \/\/ create the rigid frames and their bounding boxes\n unsigned numRigid = 2;\n vector<sofa::defaulttype::BoundingBox> boxes(numRigid);\n vector< vector<unsigned> > indices(numRigid); \/\/ indices of the particles in each box\n double eps = (endPoint[0]-startPoint[0])\/(numX*2);\n\n \/\/ first box, x=xmin\n boxes[0] = sofa::defaulttype::BoundingBox(sofa::defaulttype::Vec3d(startPoint[0]-eps, startPoint[1]-eps, startPoint[2]-eps),\n sofa::defaulttype::Vec3d(startPoint[0]+eps, endPoint[1]+eps, endPoint[2]+eps));\n\n \/\/ second box, x=xmax\n boxes[1] = sofa::defaulttype::BoundingBox(sofa::defaulttype::Vec3d(endPoint[0]-eps, startPoint[1]-eps, startPoint[2]-eps),\n sofa::defaulttype::Vec3d(endPoint[0]+eps, endPoint[1]+eps, endPoint[2]+eps));\n rigid_dof->resize(numRigid);\n MechanicalObjectRigid3::WriteVecCoord xrigid = rigid_dof->writePositions();\n xrigid[0].getCenter()=sofa::defaulttype::Vec3d(startPoint[0], 0.5*(startPoint[1]+endPoint[1]), 0.5*(startPoint[2]+endPoint[2]));\n xrigid[1].getCenter()=sofa::defaulttype::Vec3d( endPoint[0], 0.5*(startPoint[1]+endPoint[1]), 0.5*(startPoint[2]+endPoint[2]));\n\n \/\/ find the particles in each box\n vector<bool> isFree(xgrid.size(),true);\n unsigned numMapped = 0;\n for(unsigned i=0; i<xgrid.size(); i++){\n for(unsigned b=0; b<numRigid; b++ )\n {\n if( isFree[i] && boxes[b].contains(xgrid[i]) )\n {\n indices[b].push_back(i); \/\/ associate the particle with the box\n isFree[i] = false;\n numMapped++;\n }\n }\n }\n\n \/\/ distribution of the grid particles to the different parents (independent particle or solids.\n vector< std::pair<MechanicalObject3*,unsigned> > parentParticles(xgrid.size());\n\n \/\/ Copy the independent particles to their parent DOF\n independentParticles_dof->resize( numX*numY*numZ - numMapped );\n MechanicalObject3::WriteVecCoord xindependent = independentParticles_dof->writePositions(); \/\/ parent positions\n unsigned independentIndex=0;\n for( unsigned i=0; i<xgrid.size(); i++ ){\n if( isFree[i] ){\n parentParticles[i]=std::make_pair(independentParticles_dof.get(),independentIndex);\n xindependent[independentIndex] = xgrid[i];\n independentIndex++;\n }\n }\n\n \/\/ Mapped particles. The RigidMapping requires to cluster the particles based on their parent frame.\n mappedParticles_dof->resize(numMapped);\n MechanicalObject3::WriteVecCoord xmapped = mappedParticles_dof->writePositions(); \/\/ parent positions\n mappedParticles_mapping->globalToLocalCoords.setValue(true); \/\/ to define the mapped positions in world coordinates\n\n vector<unsigned>& rigidIndexPerPoint = *mappedParticles_mapping->rigidIndexPerPoint.beginEdit(); \/\/ to set to which rigid frame is attached each mapped particle\n rigidIndexPerPoint.clear();\n rigidIndexPerPoint.reserve( numMapped );\n unsigned mappedIndex=0;\n for( unsigned b=0; b<numRigid; b++ )\n {\n const vector<unsigned>& ind = indices[b];\n for(unsigned i=0; i<ind.size(); i++)\n {\n rigidIndexPerPoint.push_back( b );\n parentParticles[ind[i]]=std::make_pair(mappedParticles_dof.get(),mappedIndex);\n xmapped[mappedIndex] = xgrid[ ind[i] ];\n mappedIndex++;\n }\n }\n mappedParticles_mapping->rigidIndexPerPoint.endEdit();\n\n \/\/ Declare all the particles to the multimapping\n for( unsigned i=0; i<xgrid.size(); i++ )\n {\n deformableGrid_mapping->addPoint( parentParticles[i].first, parentParticles[i].second );\n }\n\n return root;\n}\n\nint main(int argc, char** argv)\n{\n sofa::simulation::tree::init();\n sofa::helper::BackTrace::autodump();\n sofa::core::ExecParams::defaultInstance()->setAspectID(0);\n\n sofa::helper::parse(\"This is a SOFA application. Here are the command line arguments\")\n .option(&startAnim,'a',\"start\",\"start the animation loop\")\n .option(&verbose,'v',\"verbose\",\"print debug info\")\n (argc,argv);\n\n sofa::component::initComponentBase();\n sofa::component::initComponentCommon();\n sofa::component::initComponentGeneral();\n sofa::component::initComponentAdvanced();\n sofa::component::initComponentMisc();\n sofa::gui::initMain();\n\n if (int err = sofa::gui::GUIManager::Init(argv[0],\"\")) return err;\n if (int err=sofa::gui::GUIManager::createGUI(NULL)) return err;\n sofa::gui::GUIManager::SetDimension(800,600);\n\n sofa::simulation::setSimulation(new sofa::simulation::tree::TreeSimulation());\n\n \/\/=================================================\n sofa::simulation::Node::SPtr groot = createGridScene(Vec3(0,0,0), Vec3(5,1,1), 6,2,2, 1.0 );\n \/\/=================================================\n\n sofa::simulation::getSimulation()->init(groot.get());\n sofa::gui::GUIManager::SetScene(groot);\n\n#ifdef PS3\n\tgroot->setAnimate(true);\n#endif\n\n \/\/ Run the main loop\n if (int err = sofa::gui::GUIManager::MainLoop(groot))\n return err;\n\n sofa::simulation::getSimulation()->unload(groot);\n sofa::gui::GUIManager::closeGUI();\n\n sofa::simulation::tree::cleanup();\n return 0;\n}\n\n\n\n<commit_msg>[CLEAN] Fix compilation problem because of previous commit.<commit_after>\/******************************************************************************\n* SOFA, Simulation Open-Framework Architecture, development version *\n* (c) 2006-2016 INRIA, USTL, UJF, CNRS, MGH *\n* *\n* This program is free software; you can redistribute it and\/or modify it *\n* under the terms of the GNU General Public License as published by the Free *\n* Software Foundation; either version 2 of the License, or (at your option) *\n* any later version. *\n* *\n* This program is distributed in the hope that it will be useful, but WITHOUT *\n* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or *\n* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for *\n* more details. *\n* *\n* You should have received a copy of the GNU General Public License along *\n* with this program; if not, write to the Free Software Foundation, Inc., 51 *\n* Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. *\n*******************************************************************************\n* SOFA :: Applications *\n* *\n* Authors: The SOFA Team and external contributors (see Authors.txt) *\n* *\n* Contact information: contact@sofa-framework.org *\n******************************************************************************\/\n#include <iostream>\n#include <sstream>\n#include <fstream>\n#include <sofa\/helper\/ArgumentParser.h>\n#include <sofa\/helper\/UnitTest.h>\n#include <sofa\/helper\/vector_algebra.h>\n#include <sofa\/helper\/vector.h>\n#include <sofa\/helper\/BackTrace.h>\n#include <sofa\/helper\/system\/PluginManager.h>\n\n#include <sofa\/simulation\/Node.h>\n#include <sofa\/simulation\/Simulation.h>\n#include <SofaSimulationTree\/init.h>\n#include <SofaSimulationTree\/TreeSimulation.h>\n\n#include <sofa\/gui\/GUIManager.h>\n#include <sofa\/gui\/Main.h>\n#include <sofa\/helper\/system\/FileRepository.h>\n\n#include <SofaComponentBase\/initComponentBase.h>\n#include <SofaComponentCommon\/initComponentCommon.h>\n#include <SofaComponentGeneral\/initComponentGeneral.h>\n#include <SofaComponentAdvanced\/initComponentAdvanced.h>\n#include <SofaComponentMisc\/initComponentMisc.h>\n#include <SofaMiscMapping\/SubsetMultiMapping.h>\n#include <SofaBaseTopology\/MeshTopology.h>\n#include <SofaBaseTopology\/EdgeSetTopologyContainer.h>\n#include <SofaBaseTopology\/RegularGridTopology.h>\n#include <SofaBaseCollision\/SphereModel.h>\n#include <SofaGeneralTopology\/CubeTopology.h>\n#include <SofaBaseVisual\/VisualStyle.h>\n#include <SofaImplicitOdeSolver\/EulerImplicitSolver.h>\n#include <SofaBaseLinearSolver\/CGLinearSolver.h>\n\n\/\/Using double by default, if you have SOFA_FLOAT in use in you sofa-default.cfg, then it will be FLOAT.\n#include <sofa\/component\/typedef\/Sofa_typedef.h>\n\n#include <utility>\n\n\n\nusing namespace sofa;\nusing namespace sofa::helper;\nusing helper::vector;\nusing namespace sofa::simulation;\nusing namespace sofa::core::objectmodel;\nusing namespace sofa::component::container;\nusing namespace sofa::component::topology;\nusing namespace sofa::component::collision;\nusing namespace sofa::component::visualmodel;\nusing namespace sofa::component::mapping;\nusing namespace sofa::component::forcefield;\n\ntypedef SReal Scalar;\ntypedef Vec<3,SReal> Vec3;\ntypedef Vec<1,SReal> Vec1;\ntypedef component::odesolver::EulerImplicitSolver EulerImplicitSolver;\ntypedef component::linearsolver::CGLinearSolver<component::linearsolver::GraphScatteredMatrix, component::linearsolver::GraphScatteredVector> CGLinearSolver;\n\n\nbool startAnim = true;\nbool verbose = false;\nSReal complianceValue = 0.1;\nVec3 gravity(0,-1,0);\nSReal dt = 0.01;\n\n\/\/\/ helper for more compact component creation\ntemplate<class Component>\ntypename Component::SPtr addNew( Node::SPtr parentNode, std::string name=\"\" )\n{\n typename Component::SPtr component = New<Component>();\n parentNode->addObject(component);\n component->setName(parentNode->getName()+\"_\"+name);\n return component;\n}\n\n\n\/\/\/ Create an assembly of a siff hexahedral grid with other objects\nsimulation::Node::SPtr createGridScene(Vec3 startPoint, Vec3 endPoint, unsigned numX, unsigned numY, unsigned numZ, double totalMass\/*, double stiffnessValue, double dampingRatio=0.0*\/ )\n{\n using helper::vector;\n\n \/\/ The graph root node\n Node::SPtr root = simulation::getSimulation()->createNewGraph(\"root\");\n root->setGravity( Coord3(0,-10,0) );\n root->setAnimate(false);\n root->setDt(0.01);\n addVisualStyle(root)->setShowVisual(false).setShowCollision(false).setShowMapping(true).setShowBehavior(true);\n\n Node::SPtr simulatedScene = root->createChild(\"simulatedScene\");\n\n EulerImplicitSolver::SPtr eulerImplicitSolver = New<EulerImplicitSolver>();\n simulatedScene->addObject( eulerImplicitSolver );\n CGLinearSolver::SPtr cgLinearSolver = New<CGLinearSolver>();\n simulatedScene->addObject(cgLinearSolver);\n\n \/\/ The rigid object\n Node::SPtr rigidNode = simulatedScene->createChild(\"rigidNode\");\n MechanicalObjectRigid3::SPtr rigid_dof = addNew<MechanicalObjectRigid3>(rigidNode, \"dof\");\n UniformMassRigid3::SPtr rigid_mass = addNew<UniformMassRigid3>(rigidNode,\"mass\");\n FixedConstraintRigid3::SPtr rigid_fixedConstraint = addNew<FixedConstraintRigid3>(rigidNode,\"fixedConstraint\");\n\n \/\/ Particles mapped to the rigid object\n Node::SPtr mappedParticles = rigidNode->createChild(\"mappedParticles\");\n MechanicalObject3::SPtr mappedParticles_dof = addNew< MechanicalObject3>(mappedParticles,\"dof\");\n RigidMappingRigid3_to_3::SPtr mappedParticles_mapping = addNew<RigidMappingRigid3_to_3>(mappedParticles,\"mapping\");\n mappedParticles_mapping->setModels( rigid_dof.get(), mappedParticles_dof.get() );\n\n \/\/ The independent particles\n Node::SPtr independentParticles = simulatedScene->createChild(\"independentParticles\");\n MechanicalObject3::SPtr independentParticles_dof = addNew< MechanicalObject3>(independentParticles,\"dof\");\n\n \/\/ The deformable grid, connected to its 2 parents using a MultiMapping\n Node::SPtr deformableGrid = independentParticles->createChild(\"deformableGrid\"); \/\/ first parent\n mappedParticles->addChild(deformableGrid); \/\/ second parent\n\n RegularGridTopology::SPtr deformableGrid_grid = addNew<RegularGridTopology>( deformableGrid, \"grid\" );\n deformableGrid_grid->setNumVertices(numX,numY,numZ);\n deformableGrid_grid->setPos(startPoint[0],endPoint[0],startPoint[1],endPoint[1],startPoint[2],endPoint[2]);\n\n MechanicalObject3::SPtr deformableGrid_dof = addNew< MechanicalObject3>(deformableGrid,\"dof\");\n\n SubsetMultiMapping3_to_3::SPtr deformableGrid_mapping = addNew<SubsetMultiMapping3_to_3>(deformableGrid,\"mapping\");\n deformableGrid_mapping->addInputModel(independentParticles_dof.get()); \/\/ first parent\n deformableGrid_mapping->addInputModel(mappedParticles_dof.get()); \/\/ second parent\n deformableGrid_mapping->addOutputModel(deformableGrid_dof.get());\n\n UniformMass3::SPtr mass = addNew<UniformMass3>(deformableGrid,\"mass\" );\n mass->d_mass.setValue( totalMass\/(numX*numY*numZ) );\n\n HexahedronFEMForceField3::SPtr hexaFem = addNew<HexahedronFEMForceField3>(deformableGrid, \"hexaFEM\");\n hexaFem->f_youngModulus.setValue(1000);\n hexaFem->f_poissonRatio.setValue(0.4);\n\n\n \/\/ ====== Set up the multimapping and its parents, based on its child\n deformableGrid_grid->init(); \/\/ initialize the grid, so that the particles are located in space\n deformableGrid_dof->init(); \/\/ create the state vectors\n MechanicalObject3::ReadVecCoord xgrid = deformableGrid_dof->readPositions(); \/\/ cerr<<\"xgrid = \" << xgrid << endl;\n\n\n \/\/ create the rigid frames and their bounding boxes\n unsigned numRigid = 2;\n vector<sofa::defaulttype::BoundingBox> boxes(numRigid);\n vector< vector<unsigned> > indices(numRigid); \/\/ indices of the particles in each box\n double eps = (endPoint[0]-startPoint[0])\/(numX*2);\n\n \/\/ first box, x=xmin\n boxes[0] = sofa::defaulttype::BoundingBox(sofa::defaulttype::Vec3d(startPoint[0]-eps, startPoint[1]-eps, startPoint[2]-eps),\n sofa::defaulttype::Vec3d(startPoint[0]+eps, endPoint[1]+eps, endPoint[2]+eps));\n\n \/\/ second box, x=xmax\n boxes[1] = sofa::defaulttype::BoundingBox(sofa::defaulttype::Vec3d(endPoint[0]-eps, startPoint[1]-eps, startPoint[2]-eps),\n sofa::defaulttype::Vec3d(endPoint[0]+eps, endPoint[1]+eps, endPoint[2]+eps));\n rigid_dof->resize(numRigid);\n MechanicalObjectRigid3::WriteVecCoord xrigid = rigid_dof->writePositions();\n xrigid[0].getCenter()=sofa::defaulttype::Vec3d(startPoint[0], 0.5*(startPoint[1]+endPoint[1]), 0.5*(startPoint[2]+endPoint[2]));\n xrigid[1].getCenter()=sofa::defaulttype::Vec3d( endPoint[0], 0.5*(startPoint[1]+endPoint[1]), 0.5*(startPoint[2]+endPoint[2]));\n\n \/\/ find the particles in each box\n vector<bool> isFree(xgrid.size(),true);\n unsigned numMapped = 0;\n for(unsigned i=0; i<xgrid.size(); i++){\n for(unsigned b=0; b<numRigid; b++ )\n {\n if( isFree[i] && boxes[b].contains(xgrid[i]) )\n {\n indices[b].push_back(i); \/\/ associate the particle with the box\n isFree[i] = false;\n numMapped++;\n }\n }\n }\n\n \/\/ distribution of the grid particles to the different parents (independent particle or solids.\n vector< std::pair<MechanicalObject3*,unsigned> > parentParticles(xgrid.size());\n\n \/\/ Copy the independent particles to their parent DOF\n independentParticles_dof->resize( numX*numY*numZ - numMapped );\n MechanicalObject3::WriteVecCoord xindependent = independentParticles_dof->writePositions(); \/\/ parent positions\n unsigned independentIndex=0;\n for( unsigned i=0; i<xgrid.size(); i++ ){\n if( isFree[i] ){\n parentParticles[i]=std::make_pair(independentParticles_dof.get(),independentIndex);\n xindependent[independentIndex] = xgrid[i];\n independentIndex++;\n }\n }\n\n \/\/ Mapped particles. The RigidMapping requires to cluster the particles based on their parent frame.\n mappedParticles_dof->resize(numMapped);\n MechanicalObject3::WriteVecCoord xmapped = mappedParticles_dof->writePositions(); \/\/ parent positions\n mappedParticles_mapping->globalToLocalCoords.setValue(true); \/\/ to define the mapped positions in world coordinates\n\n vector<unsigned>& rigidIndexPerPoint = *mappedParticles_mapping->rigidIndexPerPoint.beginEdit(); \/\/ to set to which rigid frame is attached each mapped particle\n rigidIndexPerPoint.clear();\n rigidIndexPerPoint.reserve( numMapped );\n unsigned mappedIndex=0;\n for( unsigned b=0; b<numRigid; b++ )\n {\n const vector<unsigned>& ind = indices[b];\n for(unsigned i=0; i<ind.size(); i++)\n {\n rigidIndexPerPoint.push_back( b );\n parentParticles[ind[i]]=std::make_pair(mappedParticles_dof.get(),mappedIndex);\n xmapped[mappedIndex] = xgrid[ ind[i] ];\n mappedIndex++;\n }\n }\n mappedParticles_mapping->rigidIndexPerPoint.endEdit();\n\n \/\/ Declare all the particles to the multimapping\n for( unsigned i=0; i<xgrid.size(); i++ )\n {\n deformableGrid_mapping->addPoint( parentParticles[i].first, parentParticles[i].second );\n }\n\n return root;\n}\n\nint main(int argc, char** argv)\n{\n sofa::simulation::tree::init();\n sofa::helper::BackTrace::autodump();\n sofa::core::ExecParams::defaultInstance()->setAspectID(0);\n\n sofa::helper::parse(\"This is a SOFA application. Here are the command line arguments\")\n .option(&startAnim,'a',\"start\",\"start the animation loop\")\n .option(&verbose,'v',\"verbose\",\"print debug info\")\n (argc,argv);\n\n sofa::component::initComponentBase();\n sofa::component::initComponentCommon();\n sofa::component::initComponentGeneral();\n sofa::component::initComponentAdvanced();\n sofa::component::initComponentMisc();\n sofa::gui::initMain();\n\n if (int err = sofa::gui::GUIManager::Init(argv[0],\"\")) return err;\n if (int err=sofa::gui::GUIManager::createGUI(NULL)) return err;\n sofa::gui::GUIManager::SetDimension(800,600);\n\n sofa::simulation::setSimulation(new sofa::simulation::tree::TreeSimulation());\n\n \/\/=================================================\n sofa::simulation::Node::SPtr groot = createGridScene(Vec3(0,0,0), Vec3(5,1,1), 6,2,2, 1.0 );\n \/\/=================================================\n\n sofa::simulation::getSimulation()->init(groot.get());\n sofa::gui::GUIManager::SetScene(groot);\n\n#ifdef PS3\n groot->setAnimate(true);\n#endif\n\n \/\/ Run the main loop\n if (int err = sofa::gui::GUIManager::MainLoop(groot))\n return err;\n\n sofa::simulation::getSimulation()->unload(groot);\n sofa::gui::GUIManager::closeGUI();\n\n sofa::simulation::tree::cleanup();\n return 0;\n}\n\n\n\n<|endoftext|>"} {"text":"<commit_before><commit_msg>Linux: Implement WebCursorInfo::TypeNone (i.e., invisible) cursor.<commit_after><|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: usrpref.hxx,v $\n *\n * $Revision: 1.11 $\n *\n * last change: $Author: hr $ $Date: 2007-06-27 12:50:12 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n#ifndef _USRPREF_HXX\n#define _USRPREF_HXX\n\n\n\n#ifndef _UTL_CONFIGITEM_HXX_\n#include <unotools\/configitem.hxx>\n#endif\n#ifndef _FLDUPDE_HXX\n#include <fldupde.hxx>\n#endif\n#include \"viewopt.hxx\"\n\n#ifndef _VCL_FLDUNIT_HXX\n#include <vcl\/fldunit.hxx>\n#endif\n\n\/* -----------------------------28.09.00 09:45--------------------------------\n\n ---------------------------------------------------------------------------*\/\nclass SwMasterUsrPref;\nclass SwContentViewConfig : public utl::ConfigItem\n{\n SwMasterUsrPref& rParent;\n BOOL bWeb;\n\n com::sun::star::uno::Sequence<rtl::OUString> GetPropertyNames();\n public:\n SwContentViewConfig(BOOL bWeb, SwMasterUsrPref& rParent);\n ~SwContentViewConfig();\n\n \/\/ utl::ConfigItem\n virtual void Notify( const com::sun::star::uno::Sequence< rtl::OUString > &rPropertyNames );\n virtual void Commit();\n\n void Load();\n void SetModified(){ConfigItem::SetModified();}\n};\n\/* -----------------------------28.09.00 09:45--------------------------------\n\n ---------------------------------------------------------------------------*\/\nclass SwLayoutViewConfig : public utl::ConfigItem\n{\n SwMasterUsrPref& rParent;\n BOOL bWeb;\n\n com::sun::star::uno::Sequence<rtl::OUString> GetPropertyNames();\n public:\n SwLayoutViewConfig(BOOL bWeb, SwMasterUsrPref& rParent);\n ~SwLayoutViewConfig();\n\n virtual void Commit();\n void Load();\n void SetModified(){ConfigItem::SetModified();}\n};\n\/* -----------------------------19.01.01 13:06--------------------------------\n\n ---------------------------------------------------------------------------*\/\nclass SwGridConfig : public utl::ConfigItem\n{\n SwMasterUsrPref& rParent;\n BOOL bWeb;\n\n com::sun::star::uno::Sequence<rtl::OUString> GetPropertyNames();\n public:\n SwGridConfig(BOOL bWeb, SwMasterUsrPref& rParent);\n ~SwGridConfig();\n\n virtual void Commit();\n void Load();\n void SetModified(){ConfigItem::SetModified();}\n};\n\/* -----------------------------19.01.01 13:06--------------------------------\n\n ---------------------------------------------------------------------------*\/\nclass SwCursorConfig : public utl::ConfigItem\n{\n SwMasterUsrPref& rParent;\n\n com::sun::star::uno::Sequence<rtl::OUString> GetPropertyNames();\n public:\n SwCursorConfig(SwMasterUsrPref& rParent);\n ~SwCursorConfig();\n\n virtual void Commit();\n void Load();\n void SetModified(){ConfigItem::SetModified();}\n};\n\/* -----------------------------28.09.00 09:45--------------------------------\n\n ---------------------------------------------------------------------------*\/\nclass SwWebColorConfig : public utl::ConfigItem\n{\n SwMasterUsrPref& rParent;\n com::sun::star::uno::Sequence<rtl::OUString> aPropNames;\n\n public:\n SwWebColorConfig(SwMasterUsrPref& rParent);\n ~SwWebColorConfig();\n\n virtual void Commit();\n void Load();\n void SetModified(){ConfigItem::SetModified();}\n};\n\/* -----------------------------28.09.00 09:45--------------------------------\n\n ---------------------------------------------------------------------------*\/\nclass SwMasterUsrPref : public SwViewOption\n{\n friend class SwContentViewConfig;\n friend class SwLayoutViewConfig;\n friend class SwGridConfig;\n friend class SwCursorConfig;\n friend class SwWebColorConfig;\n\n SwContentViewConfig aContentConfig;\n SwLayoutViewConfig aLayoutConfig;\n SwGridConfig aGridConfig;\n SwCursorConfig aCursorConfig;\n SwWebColorConfig* pWebColorConfig;\n\n sal_Int32 nFldUpdateFlags; \/\/udpate of fields and charts\n sal_Int32 nLinkUpdateMode;\n FieldUnit eUserMetric;\n FieldUnit eHScrollMetric;\n sal_Bool bIsHScrollMetricSet;\n FieldUnit eVScrollMetric;\n sal_Bool bIsVScrollMetricSet;\n\n\n sal_Int32 nDefTab; \/\/default tab stop distance\n\npublic:\n SwMasterUsrPref(BOOL bWeb);\n ~SwMasterUsrPref();\n\n void SetUsrPref(const SwViewOption &rCopy);\n\n void Commit()\n {\n aContentConfig.Commit();\n aLayoutConfig.Commit();\n aGridConfig.Commit();\n aCursorConfig.Commit();\n if(pWebColorConfig)\n pWebColorConfig->Commit();\n }\n void SetModified()\n {\n aContentConfig.SetModified();\n aLayoutConfig.SetModified();\n aGridConfig.SetModified();\n aCursorConfig.SetModified();\n if(pWebColorConfig)\n pWebColorConfig->SetModified();\n }\n\n void SetUpdateLinkMode(sal_Int32 nSet, sal_Bool bNoModify = sal_False)\n {\n nLinkUpdateMode = nSet;\n if(!bNoModify)\n aContentConfig.SetModified();\n }\n sal_Int32 GetUpdateLinkMode() const {return nLinkUpdateMode; }\n\n void SetUpdateFields(BOOL bSet, sal_Bool bNoModify = sal_False)\n {\n if(bSet && nFldUpdateFlags == AUTOUPD_OFF)\n {\n nFldUpdateFlags = AUTOUPD_FIELD_ONLY;\n if(!bNoModify)\n aContentConfig.SetModified();\n }\n else if(!bSet)\n {\n nFldUpdateFlags = AUTOUPD_OFF;\n if(!bNoModify)\n aContentConfig.SetModified();\n }\n };\n sal_Bool IsUpdateFields()const {return nFldUpdateFlags != AUTOUPD_OFF; }\n\n sal_Int32 GetFldUpdateFlags()const {return nFldUpdateFlags;}\n void SetFldUpdateFlags(sal_Int32 nSet, sal_Bool bNoModify = sal_False)\n {\n nFldUpdateFlags = nSet;\n if(!bNoModify)\n aContentConfig.SetModified();\n }\n\n void SetUpdateCharts(BOOL bSet, sal_Bool bNoModify = sal_False)\n {\n if(bSet)\n {\n nFldUpdateFlags = AUTOUPD_FIELD_AND_CHARTS;\n if(!bNoModify)\n aContentConfig.SetModified();\n }\n else if(nFldUpdateFlags == AUTOUPD_FIELD_AND_CHARTS)\n {\n nFldUpdateFlags = AUTOUPD_FIELD_ONLY;\n if(!bNoModify)\n aContentConfig.SetModified();\n }\n };\n sal_Bool IsUpdateCharts()const {return nFldUpdateFlags == AUTOUPD_FIELD_AND_CHARTS; }\n\n FieldUnit GetMetric() const { return eUserMetric;}\n void SetMetric(FieldUnit eSet, sal_Bool bNoModify = sal_False)\n {\n eUserMetric = eSet;\n if(!bNoModify)\n aLayoutConfig.SetModified();\n }\n\n sal_Bool IsHScrollMetric()const {return bIsHScrollMetricSet;}\n FieldUnit GetHScrollMetric() const { return bIsHScrollMetricSet ? eHScrollMetric : eUserMetric;}\n void SetHScrollMetric(FieldUnit eSet, sal_Bool bNoModify = sal_False)\n {\n eHScrollMetric = eSet; bIsHScrollMetricSet = sal_True;\n if(!bNoModify)\n aLayoutConfig.SetModified();\n }\n\n sal_Bool IsVScrollMetric()const {return bIsVScrollMetricSet;}\n FieldUnit GetVScrollMetric() const { return bIsVScrollMetricSet ? eVScrollMetric : eUserMetric;}\n void SetVScrollMetric(FieldUnit eSet, sal_Bool bNoModify = sal_False)\n {\n eVScrollMetric = eSet; bIsVScrollMetricSet = sal_True;\n if(!bNoModify)\n aLayoutConfig.SetModified();\n }\n\n sal_Int32 GetDefTab() const { return nDefTab;}\n void SetDefTab( sal_Int32 nSet, sal_Bool bNoModify = sal_False )\n {\n nDefTab = nSet;\n if(!bNoModify)\n aLayoutConfig.SetModified();\n }\n\n};\n\n#endif\n\n<commit_msg>INTEGRATION: CWS swwarnings (1.10.710); FILE MERGED 2007\/08\/20 15:53:43 tl 1.10.710.2: RESYNC: (1.10-1.11); FILE MERGED 2007\/03\/26 12:09:10 tl 1.10.710.1: #i69287# warning-free code<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: usrpref.hxx,v $\n *\n * $Revision: 1.12 $\n *\n * last change: $Author: hr $ $Date: 2007-09-27 12:13:49 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n#ifndef _USRPREF_HXX\n#define _USRPREF_HXX\n\n\n\n#ifndef _UTL_CONFIGITEM_HXX_\n#include <unotools\/configitem.hxx>\n#endif\n#ifndef _FLDUPDE_HXX\n#include <fldupde.hxx>\n#endif\n#include \"viewopt.hxx\"\n\n#ifndef _VCL_FLDUNIT_HXX\n#include <vcl\/fldunit.hxx>\n#endif\n\n\/* -----------------------------28.09.00 09:45--------------------------------\n\n ---------------------------------------------------------------------------*\/\nclass SwMasterUsrPref;\nclass SwContentViewConfig : public utl::ConfigItem\n{\n SwMasterUsrPref& rParent;\n BOOL bWeb;\n\n com::sun::star::uno::Sequence<rtl::OUString> GetPropertyNames();\n public:\n SwContentViewConfig(BOOL bWeb, SwMasterUsrPref& rParent);\n ~SwContentViewConfig();\n\n \/\/ utl::ConfigItem\n virtual void Notify( const com::sun::star::uno::Sequence< rtl::OUString > &rPropertyNames );\n virtual void Commit();\n\n void Load();\n void SetModified(){ConfigItem::SetModified();}\n};\n\/* -----------------------------28.09.00 09:45--------------------------------\n\n ---------------------------------------------------------------------------*\/\nclass SwLayoutViewConfig : public utl::ConfigItem\n{\n SwMasterUsrPref& rParent;\n BOOL bWeb;\n\n com::sun::star::uno::Sequence<rtl::OUString> GetPropertyNames();\n public:\n SwLayoutViewConfig(BOOL bWeb, SwMasterUsrPref& rParent);\n ~SwLayoutViewConfig();\n\n virtual void Commit();\n void Load();\n void SetModified(){ConfigItem::SetModified();}\n};\n\/* -----------------------------19.01.01 13:06--------------------------------\n\n ---------------------------------------------------------------------------*\/\nclass SwGridConfig : public utl::ConfigItem\n{\n SwMasterUsrPref& rParent;\n BOOL bWeb;\n\n com::sun::star::uno::Sequence<rtl::OUString> GetPropertyNames();\n public:\n SwGridConfig(BOOL bWeb, SwMasterUsrPref& rParent);\n ~SwGridConfig();\n\n virtual void Commit();\n void Load();\n void SetModified(){ConfigItem::SetModified();}\n};\n\/* -----------------------------19.01.01 13:06--------------------------------\n\n ---------------------------------------------------------------------------*\/\nclass SwCursorConfig : public utl::ConfigItem\n{\n SwMasterUsrPref& rParent;\n\n com::sun::star::uno::Sequence<rtl::OUString> GetPropertyNames();\n public:\n SwCursorConfig(SwMasterUsrPref& rParent);\n ~SwCursorConfig();\n\n virtual void Commit();\n void Load();\n void SetModified(){ConfigItem::SetModified();}\n};\n\/* -----------------------------28.09.00 09:45--------------------------------\n\n ---------------------------------------------------------------------------*\/\nclass SwWebColorConfig : public utl::ConfigItem\n{\n SwMasterUsrPref& rParent;\n com::sun::star::uno::Sequence<rtl::OUString> aPropNames;\n\n public:\n SwWebColorConfig(SwMasterUsrPref& rParent);\n ~SwWebColorConfig();\n\n virtual void Commit();\n void Load();\n void SetModified(){ConfigItem::SetModified();}\n};\n\/* -----------------------------28.09.00 09:45--------------------------------\n\n ---------------------------------------------------------------------------*\/\nclass SwMasterUsrPref : public SwViewOption\n{\n friend class SwContentViewConfig;\n friend class SwLayoutViewConfig;\n friend class SwGridConfig;\n friend class SwCursorConfig;\n friend class SwWebColorConfig;\n\n SwContentViewConfig aContentConfig;\n SwLayoutViewConfig aLayoutConfig;\n SwGridConfig aGridConfig;\n SwCursorConfig aCursorConfig;\n SwWebColorConfig* pWebColorConfig;\n\n SwFldUpdateFlags eFldUpdateFlags; \/\/udpate of fields and charts\n sal_Int32 nLinkUpdateMode;\n FieldUnit eUserMetric;\n FieldUnit eHScrollMetric;\n sal_Bool bIsHScrollMetricSet;\n FieldUnit eVScrollMetric;\n sal_Bool bIsVScrollMetricSet;\n\n\n sal_Int32 nDefTab; \/\/default tab stop distance\n\npublic:\n SwMasterUsrPref(BOOL bWeb);\n ~SwMasterUsrPref();\n\n void SetUsrPref(const SwViewOption &rCopy);\n\n void Commit()\n {\n aContentConfig.Commit();\n aLayoutConfig.Commit();\n aGridConfig.Commit();\n aCursorConfig.Commit();\n if(pWebColorConfig)\n pWebColorConfig->Commit();\n }\n void SetModified()\n {\n aContentConfig.SetModified();\n aLayoutConfig.SetModified();\n aGridConfig.SetModified();\n aCursorConfig.SetModified();\n if(pWebColorConfig)\n pWebColorConfig->SetModified();\n }\n\n void SetUpdateLinkMode(sal_Int32 nSet, sal_Bool bNoModify = sal_False)\n {\n nLinkUpdateMode = nSet;\n if(!bNoModify)\n aContentConfig.SetModified();\n }\n sal_Int32 GetUpdateLinkMode() const {return nLinkUpdateMode; }\n\n void SetUpdateFields(BOOL bSet, sal_Bool bNoModify = sal_False)\n {\n if(bSet && eFldUpdateFlags == AUTOUPD_OFF)\n {\n eFldUpdateFlags = AUTOUPD_FIELD_ONLY;\n if(!bNoModify)\n aContentConfig.SetModified();\n }\n else if(!bSet)\n {\n eFldUpdateFlags = AUTOUPD_OFF;\n if(!bNoModify)\n aContentConfig.SetModified();\n }\n };\n sal_Bool IsUpdateFields()const {return eFldUpdateFlags != AUTOUPD_OFF; }\n\n SwFldUpdateFlags GetFldUpdateFlags()const {return eFldUpdateFlags;}\n void SetFldUpdateFlags(SwFldUpdateFlags eSet, sal_Bool bNoModify = sal_False)\n {\n eFldUpdateFlags = eSet;\n if(!bNoModify)\n aContentConfig.SetModified();\n }\n\n void SetUpdateCharts(BOOL bSet, sal_Bool bNoModify = sal_False)\n {\n if(bSet)\n {\n eFldUpdateFlags = AUTOUPD_FIELD_AND_CHARTS;\n if(!bNoModify)\n aContentConfig.SetModified();\n }\n else if(eFldUpdateFlags == AUTOUPD_FIELD_AND_CHARTS)\n {\n eFldUpdateFlags = AUTOUPD_FIELD_ONLY;\n if(!bNoModify)\n aContentConfig.SetModified();\n }\n };\n sal_Bool IsUpdateCharts()const {return eFldUpdateFlags == AUTOUPD_FIELD_AND_CHARTS; }\n\n FieldUnit GetMetric() const { return eUserMetric;}\n void SetMetric(FieldUnit eSet, sal_Bool bNoModify = sal_False)\n {\n eUserMetric = eSet;\n if(!bNoModify)\n aLayoutConfig.SetModified();\n }\n\n sal_Bool IsHScrollMetric()const {return bIsHScrollMetricSet;}\n FieldUnit GetHScrollMetric() const { return bIsHScrollMetricSet ? eHScrollMetric : eUserMetric;}\n void SetHScrollMetric(FieldUnit eSet, sal_Bool bNoModify = sal_False)\n {\n eHScrollMetric = eSet; bIsHScrollMetricSet = sal_True;\n if(!bNoModify)\n aLayoutConfig.SetModified();\n }\n\n sal_Bool IsVScrollMetric()const {return bIsVScrollMetricSet;}\n FieldUnit GetVScrollMetric() const { return bIsVScrollMetricSet ? eVScrollMetric : eUserMetric;}\n void SetVScrollMetric(FieldUnit eSet, sal_Bool bNoModify = sal_False)\n {\n eVScrollMetric = eSet; bIsVScrollMetricSet = sal_True;\n if(!bNoModify)\n aLayoutConfig.SetModified();\n }\n\n sal_Int32 GetDefTab() const { return nDefTab;}\n void SetDefTab( sal_Int32 nSet, sal_Bool bNoModify = sal_False )\n {\n nDefTab = nSet;\n if(!bNoModify)\n aLayoutConfig.SetModified();\n }\n\n};\n\n#endif\n\n<|endoftext|>"} {"text":"<commit_before>\n#include \"density_clustering.hpp\"\n#include \"tools.hpp\"\n\n#include <sstream>\n#include <fstream>\n#include <iterator>\n#include <utility>\n#include <functional>\n#include <algorithm>\n#include <limits>\n\n#include <time.h>\n\n#include <omp.h>\n#include <boost\/program_options.hpp>\n\nnamespace b_po = boost::program_options;\n\nvoid\nlog(std::string msg) {\n std::cout << msg << std::endl;\n}\n\nvoid\nlog(std::string name, float value) {\n std::cout << name << \": \" << value << std::endl;\n}\n\n\n\nstd::vector<std::size_t>\ncalculate_populations(const CoordsPointer<float>& coords_pointer,\n const std::size_t n_rows,\n const std::size_t n_cols,\n const float radius) {\n\n \/\/ provide easy access to coordinates data\n \/\/ and give hint to compiler that it is readily\n \/\/ aligned for vectorization\n \/\/\n \/\/ DC_MEM_ALIGNMENT is defined during cmake and\n \/\/ set depending on usage of SSE2, SSE4_1, AVX or Xeon Phi\n #if defined(__INTEL_COMPILER)\n float* coords = coords_pointer.get();\n __assume_aligned(coords, DC_MEM_ALIGNMENT);\n #else\n \/\/ assume gnu compiler\n float* coords = (float*) __builtin_assume_aligned(coords_pointer.get(), DC_MEM_ALIGNMENT);\n #endif\n\n std::vector<std::size_t> pops(n_rows, 1);\n const float rad2 = radius * radius;\n std::size_t i, j, k;\n float dist, c;\n #pragma omp parallel for default(shared) private(i,j,k,c,dist) firstprivate(n_rows,n_cols,rad2) schedule(dynamic)\n for (i=0; i < n_rows; ++i) {\n for (j=i+1; j < n_rows; ++j) {\n dist = 0.0f;\n for (k=0; k < n_cols; ++k) {\n c = coords[i*n_cols+k] - coords[j*n_cols+k];\n dist += c*c;\n }\n if (dist < rad2) {\n pops[i] += 1;\n }\n }\n }\n return pops;\n}\n\nstd::vector<float>\ncalculate_densities(const std::vector<std::size_t>& pops) {\n std::size_t i;\n const std::size_t n_frames = pops.size();\n const float max_pop = (float) ( * std::max_element(pops.begin(), pops.end()));\n std::vector<float> dens(n_frames);\n #pragma omp parallel for default(shared) private(i) firstprivate(max_pop, n_frames)\n for (i=0; i < n_frames; ++i) {\n dens[i] = (float) pops[i] \/ max_pop;\n }\n return dens;\n}\n\n\n\/*\n * returns the smallest squared distance between two clusters defined\n * by ids in 'frames_cluster_1' and 'frames_cluster_2' based on the\n * given coordinate set.\n *\/\nfloat\ncluster_min_dist2(const CoordsPointer<float>& coords_pointer,\n std::size_t n_cols,\n const std::vector<std::size_t>& frames_cluster_1,\n const std::vector<std::size_t>& frames_cluster_2) {\n #if defined(__INTEL_COMPILER)\n float* coords = coords_pointer.get();\n __assume_aligned(coords, DC_MEM_ALIGNMENT);\n #else \/\/ assume gnu compiler\n float* coords = (float*) __builtin_assume_aligned(coords_pointer.get(), DC_MEM_ALIGNMENT);\n #endif\n std::size_t n_frames_1 = frames_cluster_1.size();\n std::size_t n_frames_2 = frames_cluster_2.size();\n std::size_t i,j,c;\n float dist,d;\n float min_dist = std::numeric_limits<float>::max();\n #pragma omp parallel for \\\n default(shared) \\\n private(i,j,c,d,dist) \\\n firstprivate(n_frames_1,n_frames_2,n_cols) \\\n collapse(2) \\\n reduction(min: min_dist)\n for (i=0; i < n_frames_1; ++i) {\n for (j=0; j < n_frames_2; ++j) {\n dist = 0.0f;\n for (c=0; c < n_cols; ++c) {\n d = coords[frames_cluster_1[i]*n_cols+c] - coords[frames_cluster_2[j]*n_cols+c];\n dist += d*d;\n }\n if (dist < min_dist) {\n min_dist = dist;\n }\n }\n }\n return min_dist;\n}\n\n\nconst std::pair<std::size_t, float>\nnearest_neighbor(const CoordsPointer<float>& coords_pointer,\n const std::vector<Density>& sorted_density,\n std::size_t n_cols,\n std::size_t frame_id,\n std::pair<std::size_t, std::size_t> search_range) {\n\n #if defined(__INTEL_COMPILER)\n float* coords = coords_pointer.get();\n __assume_aligned(coords, DC_MEM_ALIGNMENT);\n #else \/\/ assume gnu compiler\n float* coords = (float*) __builtin_assume_aligned(coords_pointer.get(), DC_MEM_ALIGNMENT);\n #endif\n std::size_t c,j;\n float d, dist;\n std::vector<float> distances(search_range.second-search_range.first);\n #pragma omp parallel for default(shared) private(dist,j,c,d) firstprivate(n_cols)\n for (j=search_range.first; j < search_range.second; ++j) {\n dist = 0.0f;\n for (c=0; c < n_cols; ++c) {\n d = coords[sorted_density[frame_id].first*n_cols+c] - coords[sorted_density[j].first*n_cols+c];\n dist += d*d;\n }\n distances[j-search_range.first] = dist;\n }\n if (distances.size() == 0) {\n return {0, 0.0f};\n } else {\n std::size_t min_ndx = std::min_element(distances.begin(), distances.end()) - distances.begin();\n return {min_ndx+search_range.first, distances[min_ndx]};\n }\n}\n\n\nstd::vector<std::size_t>\ndensity_clustering(const std::vector<float>& dens,\n const float density_threshold,\n const float density_radius,\n const CoordsPointer<float>& coords_pointer,\n const std::size_t n_rows,\n const std::size_t n_cols) {\n\n std::vector<Density> density_sorted;\n for (std::size_t i=0; i < dens.size(); ++i) {\n density_sorted.push_back({i, dens[i]});\n }\n \/\/ sort for density: highest to lowest\n std::sort(density_sorted.begin(),\n density_sorted.end(),\n [] (const Density& d1, const Density& d2) -> bool {return d1.second > d2.second;});\n auto lb = std::lower_bound(density_sorted.begin(),\n density_sorted.end(),\n Density(0, density_threshold), \n [](const Density& d1, const Density& d2) -> bool {return d1.second > d2.second;});\n std::size_t last_frame_below_threshold = (lb - density_sorted.begin());\n \/\/ find initial clusters\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n std::vector<std::size_t> clustering;\n\n std::cout << \"computing sigma ...\" << std::endl;\n \/\/ compute sigma as standard deviation of nearest-neighbor distances\n float sigma = 0.0f;\n for (std::size_t i=0; i < n_rows; ++i) {\n if (i % 1000 == 0) std::cout << i << \" \/ \" << n_rows << std::endl;\n sigma += nearest_neighbor(coords_pointer, density_sorted, n_cols, i, {0,n_rows}).second;\n }\n sigma \/= n_rows;\n\n std::cout << \"sigma: \" << sigma << std::endl;\n\n exit(2);\n\n\n std::size_t n_clusters = 1;\n std::map<std::size_t, std::vector<std::size_t>> clusters;\n \/\/ initialize with highest populated frame\n clusters[1] = {density_sorted[0].first};\n\n for (std::size_t i=1; i < last_frame_below_threshold; ++i) {\n \/\/ find (existing) cluster for this frame\n std::vector<std::size_t> fake_cluster = {i};\n float min_dist2 = std::numeric_limits<float>::max();\n std::size_t min_clust = 0;\n for (auto& cluster: clusters) {\n float dist2 = cluster_min_dist2(coords_pointer, n_cols, fake_cluster, cluster.second);\n if (dist2 < min_dist2) {\n min_dist2 = dist2;\n min_clust = cluster.first;\n }\n }\n \/\/ decide on new cluster vs appending\n if (min_dist2 < sigma*sigma) {\n \/\/ in range of cluster: append\n \/\/TODO\n } else {\n \/\/ outside every cluster-bound: new cluster from this frame\n \/\/TODO\n }\n }\n\n\n exit(3);\n\n\/\/ for (std::size_t i=1; i < last_frame_below_threshold; ++i) {\n\/\/ \/\/ nn_pair: first := index in traj, second := distance to reference (i)\n\/\/ auto nn_pair = nearest_neighbor(coords_pointer, density_sorted, n_cols, i, {0,i});\n\/\/ if (nn_pair.second < density_radius*density_radius) {\n\/\/ \/\/ add to existing cluster of frame with 'min_dist'\n\/\/ clustering[density_sorted[i].first] = clustering[density_sorted[nn_pair.first].first];\n\/\/ } else {\n\/\/ \/\/ create new cluster\n\/\/ ++n_clusters;\n\/\/ clustering[density_sorted[i].first] = n_clusters;\n\/\/ }\n\/\/ }\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n \/\/ find nearest neighbors for all unassigned frames\n std::map<std::size_t, std::size_t> nearest_neighbors;\n for (std::size_t i=last_frame_below_threshold; i < density_sorted.size(); ++i) {\n if (i % 100 == 0) std::cout << i << \" \/ \" << density_sorted.size() << std::endl;\n \/\/ nn_pair: first := index in traj, second := distance to reference (i)\n auto nn_pair = nearest_neighbor(coords_pointer, density_sorted, n_cols, i, {0, density_sorted.size()});\n nearest_neighbors[i] = nn_pair.first;\n }\n log(\"assign frames to clusters\");\n \/\/ assign clusters to unassigned frames via neighbor-info\n bool nothing_happened = true;\n while (nearest_neighbors.size() > 0 && ( ! nothing_happened)) {\n nothing_happened = true;\n \/\/ it: first := index in traj, second := distance to reference (i)\n for (auto it=nearest_neighbors.begin(); it != nearest_neighbors.end(); ++it) {\n if (clustering[it->second] != 0) {\n clustering[it->first] = it->second;\n nearest_neighbors.erase(it);\n nothing_happened = false;\n }\n }\n }\n return clustering;\n}\n\n\/\/\/\/\/\/\/\/\n\nint main(int argc, char* argv[]) {\n\n b_po::variables_map args;\n b_po::options_description desc (std::string(argv[0]).append(\n \"\\n\\n\"\n \"perform clustering of MD data based on phase space densities.\\n\"\n \"densities are approximated by counting neighboring frames inside\\n\"\n \"a n-dimensional hypersphere of specified radius.\\n\"\n \"distances are measured with n-dim P2-norm.\\n\"\n \"\\n\"\n \"options\"));\n desc.add_options()\n (\"help,h\", b_po::bool_switch()->default_value(false), \"show this help.\")\n \/\/ required\n (\"file,f\", b_po::value<std::string>()->required(), \"input (required): phase space coordinates (space separated ASCII).\")\n (\"output,o\", b_po::value<std::string>()->required(), \"output (required): clustering information.\")\n (\"radius,r\", b_po::value<float>()->required(), \"parameter (required): hypersphere radius.\")\n (\"threshold,t\", b_po::value<float>()->required(), \"parameter (required, elem. of [0.0, 1.0]): density threshold for clustering.\")\n \/\/ optional\n (\"population,p\", b_po::value<std::string>(), \"output (optional): population per frame.\")\n (\"density,d\", b_po::value<std::string>(), \"output (optional): density per frame.\")\n (\"density-input,D\", b_po::value<std::string>(), \"input (optional): reuse density info.\")\n \/\/ defaults\n (\"nthreads,n\", b_po::value<int>()->default_value(0), \"number of OpenMP threads. default: 0; i.e. use OMP_NUM_THREADS env-variable.\")\n (\"verbose,v\", b_po::bool_switch()->default_value(false), \"verbose mode: print max density, runtime information, etc. to STDOUT.\")\n ;\n\n try {\n b_po::store(b_po::command_line_parser(argc, argv).options(desc).run(), args);\n b_po::notify(args);\n } catch (b_po::error& e) {\n if ( ! args[\"help\"].as<bool>()) {\n std::cout << \"\\n\" << e.what() << \"\\n\\n\" << std::endl;\n }\n std::cout << desc << std::endl;\n return 2;\n }\n\n if (args[\"help\"].as<bool>()) {\n std::cout << desc << std::endl;\n return 1;\n }\n\n \/\/\/\/\n\n const std::string input_file = args[\"file\"].as<std::string>();\n const std::string output_file = args[\"output\"].as<std::string>();\n\n const float radius = args[\"radius\"].as<float>();\n const float threshold = args[\"threshold\"].as<float>();\n\n \/\/ setup OpenMP\n const int n_threads = args[\"nthreads\"].as<int>();\n if (n_threads > 0) {\n omp_set_num_threads(n_threads);\n }\n\n bool verbose = args[\"verbose\"].as<bool>();\n\n CoordsPointer<float> coords_pointer;\n std::size_t n_rows;\n std::size_t n_cols;\n std::tie(coords_pointer, n_rows, n_cols) = read_coords<float>(input_file);\n\n std::vector<float> densities;\n\n if (args.count(\"density-input\")) {\n if (verbose) {\n log(\"re-using density data.\");\n }\n \/\/ reuse density info\n std::ifstream ifs(args[\"density-input\"].as<std::string>());\n if (ifs.fail()) {\n std::cerr << \"error: cannot open file '\" << args[\"density-input\"].as<std::string>() << \"'\" << std::endl;\n return 3;\n } else {\n while(ifs.good()) {\n float buf;\n ifs >> buf;\n densities.push_back(buf);\n }\n }\n } else {\n if (verbose) {\n log(\"calculating densities\");\n }\n densities = calculate_densities(\n calculate_populations(coords_pointer, n_rows, n_cols, radius));\n if (args.count(\"density\")) {\n std::ofstream ofs(args[\"density\"].as<std::string>());\n ofs << std::scientific;\n for (float d: densities) {\n ofs << d << \"\\n\";\n }\n }\n }\n\n if (verbose) {\n log(\"calculating clusters\");\n }\n std::vector<std::size_t> clustering = density_clustering(densities, threshold, radius, coords_pointer, n_rows, n_cols);\n \/\/ write clusters to file\n {\n std::ofstream ofs(output_file);\n if (ofs.fail()) {\n std::cerr << \"error: cannot open file '\" << output_file << \"' for writing.\" << std::endl;\n return 3;\n }\n for (std::size_t i: clustering) {\n ofs << i << \"\\n\";\n }\n }\n return 0;\n}\n\n<commit_msg>prepare merge<commit_after>\n#include \"density_clustering.hpp\"\n#include \"tools.hpp\"\n\n#include <sstream>\n#include <fstream>\n#include <iterator>\n#include <utility>\n#include <functional>\n#include <algorithm>\n#include <limits>\n\n#include <time.h>\n\n#include <omp.h>\n#include <boost\/program_options.hpp>\n\nnamespace b_po = boost::program_options;\n\nvoid\nlog(std::string msg) {\n std::cout << msg << std::endl;\n}\n\nvoid\nlog(std::string name, float value) {\n std::cout << name << \": \" << value << std::endl;\n}\n\n\n\nstd::vector<std::size_t>\ncalculate_populations(const CoordsPointer<float>& coords_pointer,\n const std::size_t n_rows,\n const std::size_t n_cols,\n const float radius) {\n\n \/\/ provide easy access to coordinates data\n \/\/ and give hint to compiler that it is readily\n \/\/ aligned for vectorization\n \/\/\n \/\/ DC_MEM_ALIGNMENT is defined during cmake and\n \/\/ set depending on usage of SSE2, SSE4_1, AVX or Xeon Phi\n #if defined(__INTEL_COMPILER)\n float* coords = coords_pointer.get();\n __assume_aligned(coords, DC_MEM_ALIGNMENT);\n #else\n \/\/ assume gnu compiler\n float* coords = (float*) __builtin_assume_aligned(coords_pointer.get(), DC_MEM_ALIGNMENT);\n #endif\n\n std::vector<std::size_t> pops(n_rows, 1);\n const float rad2 = radius * radius;\n std::size_t i, j, k;\n float dist, c;\n #pragma omp parallel for default(shared) private(i,j,k,c,dist) firstprivate(n_rows,n_cols,rad2) schedule(dynamic)\n for (i=0; i < n_rows; ++i) {\n for (j=i+1; j < n_rows; ++j) {\n dist = 0.0f;\n for (k=0; k < n_cols; ++k) {\n c = coords[i*n_cols+k] - coords[j*n_cols+k];\n dist += c*c;\n }\n if (dist < rad2) {\n pops[i] += 1;\n }\n }\n }\n return pops;\n}\n\nstd::vector<float>\ncalculate_densities(const std::vector<std::size_t>& pops) {\n std::size_t i;\n const std::size_t n_frames = pops.size();\n const float max_pop = (float) ( * std::max_element(pops.begin(), pops.end()));\n std::vector<float> dens(n_frames);\n #pragma omp parallel for default(shared) private(i) firstprivate(max_pop, n_frames)\n for (i=0; i < n_frames; ++i) {\n dens[i] = (float) pops[i] \/ max_pop;\n }\n return dens;\n}\n\n\n\/*\n * returns the smallest squared distance between two clusters defined\n * by ids in 'frames_cluster_1' and 'frames_cluster_2' based on the\n * given coordinate set.\n *\/\nfloat\ncluster_min_dist2(const CoordsPointer<float>& coords_pointer,\n std::size_t n_cols,\n const std::vector<std::size_t>& frames_cluster_1,\n const std::vector<std::size_t>& frames_cluster_2) {\n #if defined(__INTEL_COMPILER)\n float* coords = coords_pointer.get();\n __assume_aligned(coords, DC_MEM_ALIGNMENT);\n #else \/\/ assume gnu compiler\n float* coords = (float*) __builtin_assume_aligned(coords_pointer.get(), DC_MEM_ALIGNMENT);\n #endif\n std::size_t n_frames_1 = frames_cluster_1.size();\n std::size_t n_frames_2 = frames_cluster_2.size();\n std::size_t i,j,c;\n float dist,d;\n float min_dist = std::numeric_limits<float>::max();\n #pragma omp parallel for \\\n default(shared) \\\n private(i,j,c,d,dist) \\\n firstprivate(n_frames_1,n_frames_2,n_cols) \\\n collapse(2) \\\n reduction(min: min_dist)\n for (i=0; i < n_frames_1; ++i) {\n for (j=0; j < n_frames_2; ++j) {\n dist = 0.0f;\n for (c=0; c < n_cols; ++c) {\n d = coords[frames_cluster_1[i]*n_cols+c] - coords[frames_cluster_2[j]*n_cols+c];\n dist += d*d;\n }\n if (dist < min_dist) {\n min_dist = dist;\n }\n }\n }\n return min_dist;\n}\n\n\nconst std::pair<std::size_t, float>\nnearest_neighbor(const CoordsPointer<float>& coords_pointer,\n const std::vector<Density>& sorted_density,\n std::size_t n_cols,\n std::size_t frame_id,\n std::pair<std::size_t, std::size_t> search_range) {\n\n #if defined(__INTEL_COMPILER)\n float* coords = coords_pointer.get();\n __assume_aligned(coords, DC_MEM_ALIGNMENT);\n #else \/\/ assume gnu compiler\n float* coords = (float*) __builtin_assume_aligned(coords_pointer.get(), DC_MEM_ALIGNMENT);\n #endif\n std::size_t c,j;\n float d, dist;\n std::vector<float> distances(search_range.second-search_range.first);\n #pragma omp parallel for default(shared) private(dist,j,c,d) firstprivate(n_cols)\n for (j=search_range.first; j < search_range.second; ++j) {\n if (frame_id == j) {\n continue;\n }\n dist = 0.0f;\n for (c=0; c < n_cols; ++c) {\n d = coords[sorted_density[frame_id].first*n_cols+c] - coords[sorted_density[j].first*n_cols+c];\n dist += d*d;\n }\n distances[j-search_range.first] = dist;\n }\n if (distances.size() == 0) {\n return {0, 0.0f};\n } else {\n std::size_t min_ndx = std::min_element(distances.begin(), distances.end()) - distances.begin();\n return {min_ndx+search_range.first, distances[min_ndx]};\n }\n}\n\n\nstd::vector<std::size_t>\ndensity_clustering(const std::vector<float>& dens,\n const float density_threshold,\n const float density_radius,\n const CoordsPointer<float>& coords_pointer,\n const std::size_t n_rows,\n const std::size_t n_cols) {\n\n std::vector<Density> density_sorted;\n for (std::size_t i=0; i < dens.size(); ++i) {\n density_sorted.push_back({i, dens[i]});\n }\n \/\/ sort for density: highest to lowest\n std::sort(density_sorted.begin(),\n density_sorted.end(),\n [] (const Density& d1, const Density& d2) -> bool {return d1.second > d2.second;});\n auto lb = std::lower_bound(density_sorted.begin(),\n density_sorted.end(),\n Density(0, density_threshold), \n [](const Density& d1, const Density& d2) -> bool {return d1.second > d2.second;});\n std::size_t last_frame_below_threshold = (lb - density_sorted.begin());\n \/\/ find initial clusters\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n std::vector<std::size_t> clustering;\n\n std::cout << \"computing sigma ...\" << std::endl;\n \/\/ compute sigma as standard deviation of nearest-neighbor distances\n float sigma = 0.0f;\n for (std::size_t i=0; i < n_rows; ++i) {\n if (i % 1000 == 0) std::cout << i << \" \/ \" << n_rows << \"; sum(sigma): \" << sigma << std::endl;\n sigma += nearest_neighbor(coords_pointer, density_sorted, n_cols, i, {0,n_rows}).second;\n }\n sigma \/= n_rows;\n\n std::cout << \"sigma: \" << sigma << std::endl;\n\n exit(2);\n\n\n std::size_t n_clusters = 1;\n std::map<std::size_t, std::vector<std::size_t>> clusters;\n \/\/ initialize with highest populated frame\n clusters[1] = {density_sorted[0].first};\n\n for (std::size_t i=1; i < last_frame_below_threshold; ++i) {\n \/\/ find (existing) cluster for this frame\n std::vector<std::size_t> fake_cluster = {i};\n float min_dist2 = std::numeric_limits<float>::max();\n std::size_t min_clust = 0;\n for (auto& cluster: clusters) {\n float dist2 = cluster_min_dist2(coords_pointer, n_cols, fake_cluster, cluster.second);\n if (dist2 < min_dist2) {\n min_dist2 = dist2;\n min_clust = cluster.first;\n }\n }\n \/\/ decide on new cluster vs appending\n if (min_dist2 < sigma*sigma) {\n \/\/ in range of cluster: append\n \/\/TODO\n } else {\n \/\/ outside every cluster-bound: new cluster from this frame\n \/\/TODO\n }\n }\n\n\n exit(3);\n\n\/\/ for (std::size_t i=1; i < last_frame_below_threshold; ++i) {\n\/\/ \/\/ nn_pair: first := index in traj, second := distance to reference (i)\n\/\/ auto nn_pair = nearest_neighbor(coords_pointer, density_sorted, n_cols, i, {0,i});\n\/\/ if (nn_pair.second < density_radius*density_radius) {\n\/\/ \/\/ add to existing cluster of frame with 'min_dist'\n\/\/ clustering[density_sorted[i].first] = clustering[density_sorted[nn_pair.first].first];\n\/\/ } else {\n\/\/ \/\/ create new cluster\n\/\/ ++n_clusters;\n\/\/ clustering[density_sorted[i].first] = n_clusters;\n\/\/ }\n\/\/ }\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n \/\/ find nearest neighbors for all unassigned frames\n std::map<std::size_t, std::size_t> nearest_neighbors;\n for (std::size_t i=last_frame_below_threshold; i < density_sorted.size(); ++i) {\n if (i % 100 == 0) std::cout << i << \" \/ \" << density_sorted.size() << std::endl;\n \/\/ nn_pair: first := index in traj, second := distance to reference (i)\n auto nn_pair = nearest_neighbor(coords_pointer, density_sorted, n_cols, i, {0, density_sorted.size()});\n nearest_neighbors[i] = nn_pair.first;\n }\n log(\"assign frames to clusters\");\n \/\/ assign clusters to unassigned frames via neighbor-info\n bool nothing_happened = true;\n while (nearest_neighbors.size() > 0 && ( ! nothing_happened)) {\n nothing_happened = true;\n \/\/ it: first := index in traj, second := distance to reference (i)\n for (auto it=nearest_neighbors.begin(); it != nearest_neighbors.end(); ++it) {\n if (clustering[it->second] != 0) {\n clustering[it->first] = it->second;\n nearest_neighbors.erase(it);\n nothing_happened = false;\n }\n }\n }\n return clustering;\n}\n\n\/\/\/\/\/\/\/\/\n\nint main(int argc, char* argv[]) {\n\n b_po::variables_map args;\n b_po::options_description desc (std::string(argv[0]).append(\n \"\\n\\n\"\n \"perform clustering of MD data based on phase space densities.\\n\"\n \"densities are approximated by counting neighboring frames inside\\n\"\n \"a n-dimensional hypersphere of specified radius.\\n\"\n \"distances are measured with n-dim P2-norm.\\n\"\n \"\\n\"\n \"options\"));\n desc.add_options()\n (\"help,h\", b_po::bool_switch()->default_value(false), \"show this help.\")\n \/\/ required\n (\"file,f\", b_po::value<std::string>()->required(), \"input (required): phase space coordinates (space separated ASCII).\")\n (\"output,o\", b_po::value<std::string>()->required(), \"output (required): clustering information.\")\n (\"radius,r\", b_po::value<float>()->required(), \"parameter (required): hypersphere radius.\")\n (\"threshold,t\", b_po::value<float>()->required(), \"parameter (required, elem. of [0.0, 1.0]): density threshold for clustering.\")\n \/\/ optional\n (\"population,p\", b_po::value<std::string>(), \"output (optional): population per frame.\")\n (\"density,d\", b_po::value<std::string>(), \"output (optional): density per frame.\")\n (\"density-input,D\", b_po::value<std::string>(), \"input (optional): reuse density info.\")\n \/\/ defaults\n (\"nthreads,n\", b_po::value<int>()->default_value(0), \"number of OpenMP threads. default: 0; i.e. use OMP_NUM_THREADS env-variable.\")\n (\"verbose,v\", b_po::bool_switch()->default_value(false), \"verbose mode: print max density, runtime information, etc. to STDOUT.\")\n ;\n\n try {\n b_po::store(b_po::command_line_parser(argc, argv).options(desc).run(), args);\n b_po::notify(args);\n } catch (b_po::error& e) {\n if ( ! args[\"help\"].as<bool>()) {\n std::cout << \"\\n\" << e.what() << \"\\n\\n\" << std::endl;\n }\n std::cout << desc << std::endl;\n return 2;\n }\n\n if (args[\"help\"].as<bool>()) {\n std::cout << desc << std::endl;\n return 1;\n }\n\n \/\/\/\/\n\n const std::string input_file = args[\"file\"].as<std::string>();\n const std::string output_file = args[\"output\"].as<std::string>();\n\n const float radius = args[\"radius\"].as<float>();\n const float threshold = args[\"threshold\"].as<float>();\n\n \/\/ setup OpenMP\n const int n_threads = args[\"nthreads\"].as<int>();\n if (n_threads > 0) {\n omp_set_num_threads(n_threads);\n }\n\n bool verbose = args[\"verbose\"].as<bool>();\n\n CoordsPointer<float> coords_pointer;\n std::size_t n_rows;\n std::size_t n_cols;\n std::tie(coords_pointer, n_rows, n_cols) = read_coords<float>(input_file);\n\n std::vector<float> densities;\n\n if (args.count(\"density-input\")) {\n if (verbose) {\n log(\"re-using density data.\");\n }\n \/\/ reuse density info\n std::ifstream ifs(args[\"density-input\"].as<std::string>());\n if (ifs.fail()) {\n std::cerr << \"error: cannot open file '\" << args[\"density-input\"].as<std::string>() << \"'\" << std::endl;\n return 3;\n } else {\n while(ifs.good()) {\n float buf;\n ifs >> buf;\n densities.push_back(buf);\n }\n }\n } else {\n if (verbose) {\n log(\"calculating densities\");\n }\n densities = calculate_densities(\n calculate_populations(coords_pointer, n_rows, n_cols, radius));\n if (args.count(\"density\")) {\n std::ofstream ofs(args[\"density\"].as<std::string>());\n ofs << std::scientific;\n for (float d: densities) {\n ofs << d << \"\\n\";\n }\n }\n }\n\n if (verbose) {\n log(\"calculating clusters\");\n }\n std::vector<std::size_t> clustering = density_clustering(densities, threshold, radius, coords_pointer, n_rows, n_cols);\n \/\/ write clusters to file\n {\n std::ofstream ofs(output_file);\n if (ofs.fail()) {\n std::cerr << \"error: cannot open file '\" << output_file << \"' for writing.\" << std::endl;\n return 3;\n }\n for (std::size_t i: clustering) {\n ofs << i << \"\\n\";\n }\n }\n return 0;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/* RTcmix - Copyright (C) 2000 The RTcmix Development Team\n See ``AUTHORS'' for a list of contributors. See ``LICENSE'' for\n the license to this software and for a DISCLAIMER OF ALL WARRANTIES.\n*\/\n#include \"prototypes.h\"\n#include \"mixerr.h\"\n\n\nextern \"C\" {\n\tdouble rtdispatch(char *fname, double *pp, int n_args, void **inst)\n\t{\n\t\tdouble rv;\n\n\t\trv = checkInsts(fname, pp, n_args, inst);\n\t\treturn rv;\n\t}\n}\n\n\n<commit_msg>The file\/function was no longer being used -- BGG<commit_after><|endoftext|>"} {"text":"<commit_before>\/** \\file LocalDataDB.cc\n * \\brief Implementation of the LocalDataDB class.\n * \\author Dr. Johannes Ruscheinski (johannes.ruscheinski@uni-tuebingen.de)\n *\n * \\copyright 2020 Universitätsbibliothek Tübingen. All rights reserved.\n *\n * This program is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License as\n * published by the Free Software Foundation, either version 3 of the\n * License, or (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Affero General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public License\n * along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n#include \"LocalDataDB.h\"\n#include \"Compiler.h\"\n#include \"DbConnection.h\"\n#include \"StringUtil.h\"\n#include \"UBTools.h\"\n\n\nLocalDataDB::LocalDataDB(const OpenMode open_mode) {\n db_connection_ = new DbConnection(UBTools::GetTuelibPath() + \"local_data.sq3\" \/* must be the same path as in fetch_marc_updates.py *\/,\n (open_mode == READ_WRITE) ? DbConnection::CREATE : DbConnection::READONLY);\n if (open_mode == READ_ONLY)\n return;\n\n db_connection_->queryOrDie(\"CREATE TABLE IF NOT EXISTS local_data (\"\n \" title_ppn TEXT PRIMARY KEY,\"\n \" local_fields BLOB NOT NULL\"\n \") WITHOUT ROWID\");\n db_connection_->queryOrDie(\"CREATE UNIQUE INDEX IF NOT EXISTS local_data_index ON local_data (title_ppn)\");\n\n db_connection_->queryOrDie(\"CREATE TABLE IF NOT EXISTS local_ppns_to_title_ppns_map (\"\n \" local_ppn TEXT PRIMARY KEY,\"\n \" title_ppn TEXT NOT NULL,\"\n \" FOREIGN KEY(title_ppn) REFERENCES local_data(title_ppn)\"\n \") WITHOUT ROWID\");\n db_connection_->queryOrDie(\"CREATE UNIQUE INDEX IF NOT EXISTS local_ppns_to_title_ppns_mapindex \"\n \"ON local_ppns_to_title_ppns_map (local_ppn)\");\n}\n\n\nLocalDataDB::~LocalDataDB() {\n delete db_connection_;\n}\n\n\nvoid LocalDataDB::clear() {\n db_connection_->queryOrDie(\"DROP TABLE IF EXISTSlocal_data\");\n db_connection_->queryOrDie(\"DROP TABLE IF EXISTSlocal_ppns_to_title_ppns_map\");\n}\n\n\nstatic std::vector<std::string> BlobToLocalFieldsVector(const std::string &local_fields_blob, const std::string &title_ppn) {\n std::vector<std::string> local_fields;\n\n size_t processed_size(0);\n do {\n \/\/ Convert the 4 character hex string to the size of the following field contents:\n const size_t field_contents_size(StringUtil::ToUnsignedLong(local_fields_blob.substr(processed_size, 4), 16));\n processed_size += 4;\n\n \/\/ Sanity check:\n if (unlikely(processed_size + field_contents_size > local_fields_blob.size()))\n LOG_ERROR(\"inconsistent blob length for record with PPN \" + title_ppn + \" (1)\");\n\n local_fields.emplace_back(local_fields_blob.substr(processed_size, field_contents_size));\n processed_size += field_contents_size;\n } while (processed_size < local_fields_blob.size());\n\n \/\/ Sanity check:\n if (unlikely(processed_size != local_fields_blob.size()))\n LOG_ERROR(\"inconsistent blob length for record with PPN \" + title_ppn + \" (2))\");\n\n return local_fields;\n}\n\n\nstd::vector<std::string> ExtractLocalPPNsFromLocalFieldsVector(const std::vector<std::string> &local_fields) {\n std::vector<std::string> local_ppns;\n\n for (const auto &local_field : local_fields) {\n if (StringUtil::StartsWith(local_field, \"001 \"))\n local_ppns.emplace_back(local_field.substr(__builtin_strlen(\"001 \")));\n }\n\n return local_ppns;\n}\n\n\nstatic std::string ConvertLocalFieldsVectorToBlob(const std::vector<std::string> &local_fields) {\n std::string local_fields_blob;\n for (const auto &local_field : local_fields) {\n local_fields_blob += StringUtil::ToString(local_field.length(), \/* radix = *\/16,\n \/* width = *\/4, \/* padding_char = *\/'0');\n local_fields_blob += local_field;\n }\n\n return local_fields_blob;\n}\n\n\nvoid LocalDataDB::insertOrReplace(const std::string &title_ppn, const std::vector<std::string> &local_fields) {\n \/\/ 1. Clear out any local PPNs associated with \"title_ppn\":\n db_connection_->queryOrDie(\"SELECT local_fields FROM local_data WHERE title_ppn = \"\n + db_connection_->escapeAndQuoteString(title_ppn));\n auto result_set(db_connection_->getLastResultSet());\n if (not result_set.empty()) {\n const auto row(result_set.getNextRow());\n const auto previous_local_fields(BlobToLocalFieldsVector(row[\"local_fields\"], title_ppn));\n const auto local_ppns(ExtractLocalPPNsFromLocalFieldsVector(previous_local_fields));\n for (const auto &local_ppn : local_ppns)\n db_connection_->queryOrDie(\"DELETE FROM local_ppns_to_title_ppns_map WHERE local_ppn=\"\n + db_connection_->escapeAndQuoteString(local_ppn));\n }\n\n \/\/ 2. Replace or insert the local data keyed by the title PPN's:\n db_connection_->queryOrDie(\"REPLACE INTO local_data (title_ppn, local_fields) VALUES(\"\n + db_connection_->escapeAndQuoteString(title_ppn) + \",\"\n + db_connection_->sqliteEscapeBlobData(ConvertLocalFieldsVectorToBlob(local_fields)) + \")\");\n\n \/\/ 3. Insert the mappings from the local PPN's to the title PPN's:\n for (const auto &local_ppn : ExtractLocalPPNsFromLocalFieldsVector(local_fields)) {\n db_connection_->queryOrDie(\"INSERT INTO local_ppns_to_title_ppns_map (local_ppn, title_ppn) VALUES(\"\n + db_connection_->escapeAndQuoteString(local_ppn) + \",\"\n + db_connection_->escapeAndQuoteString(title_ppn) + \")\");\n }\n}\n\n\nstd::vector<std::string> LocalDataDB::getLocalFields(const std::string &title_ppn) const {\n db_connection_->queryOrDie(\"SELECT local_fields FROM local_data WHERE title_ppn = \"\n + db_connection_->escapeAndQuoteString(title_ppn));\n auto result_set(db_connection_->getLastResultSet());\n if (result_set.empty())\n return {}; \/\/ empty vector\n\n const auto row(result_set.getNextRow());\n return BlobToLocalFieldsVector(row[\"local_fields\"], title_ppn);\n}\n\n\nbool LocalDataDB::removeTitleDataSet(const std::string &title_ppn) {\n \/\/ 1. Clear out any local PPNs associated with \"title_ppn\":\n db_connection_->queryOrDie(\"SELECT local_fields FROM local_data WHERE title_ppn = \"\n + db_connection_->escapeAndQuoteString(title_ppn));\n auto result_set(db_connection_->getLastResultSet());\n if (result_set.empty())\n return false;\n\n const auto row(result_set.getNextRow());\n const auto previous_local_fields(BlobToLocalFieldsVector(row[\"local_fields\"], title_ppn));\n const auto local_ppns(ExtractLocalPPNsFromLocalFieldsVector(previous_local_fields));\n for (const auto &local_ppn : local_ppns)\n db_connection_->queryOrDie(\"DELETE FROM local_ppns_to_title_ppns_map WHERE local_ppn=\"\n + db_connection_->escapeAndQuoteString(local_ppn));\n\n \/\/ 2. Delete the local data for the title PPN:\n db_connection_->queryOrDie(\"DELETE FROM local_data WHERE title_ppn = \"\n + db_connection_->escapeAndQuoteString(title_ppn));\n\n return true;\n}\n\n\n\/\/ Removes all fields from \"local_fields\" that are associated w\/ \"local_ppn\".\nstatic std::vector<std::string> RemoveLocalDataSet(const std::string &local_ppn,\n const std::vector<std::string> &local_fields)\n{\n std::vector<std::string> filtered_local_fields;\n filtered_local_fields.reserve(local_fields.size());\n\n bool skipping(false);\n for (const auto &local_field : local_fields) {\n if (StringUtil::StartsWith(local_field, \"001 \"))\n skipping = local_field.substr(__builtin_strlen(\"001 \")) == local_ppn;\n if (not skipping)\n filtered_local_fields.emplace_back(local_field);\n }\n\n return filtered_local_fields;\n}\n\n\nbool LocalDataDB::removeLocalDataSet(const std::string &local_ppn) {\n \/\/ 1. Determine the title PPN associated w\/ the local PPN:\n db_connection_->queryOrDie(\"SELECT title_ppn FROM local_ppns_to_title_ppns_map WHERE local_ppn=\"\n + db_connection_->escapeAndQuoteString(local_ppn));\n auto result_set(db_connection_->getLastResultSet());\n if (result_set.empty())\n return false;\n const auto row(result_set.getNextRow());\n const auto title_ppn(row[\"title_ppn\"]);\n\n \/\/ 2. Retrieve the local data associated w\/ the title PPN:\n auto local_fields(getLocalFields(title_ppn));\n\n \/\/ 3. Remove the local data associsted w\/ the local PPN:\n const auto filtered_local_fields(RemoveLocalDataSet(local_ppn, local_fields));\n\n \/\/ 4. Update our SQL tables:\n db_connection_->queryOrDie(\"DELETE FROM local_ppns_to_title_ppns_map WHERE ocal_ppn=\"\n + db_connection_->escapeAndQuoteString(local_ppn));\n if (filtered_local_fields.empty())\n db_connection_->queryOrDie(\"DELETE FROM local_fields WHERE title_ppn=\"\n + db_connection_->escapeAndQuoteString(title_ppn));\n else\n db_connection_->queryOrDie(\"REPLACE INTO local_data (titel_ppn, local_fields) VALUES(\"\n + db_connection_->escapeAndQuoteString(title_ppn) + \",\"\n + db_connection_->sqliteEscapeBlobData(ConvertLocalFieldsVectorToBlob(local_fields)) + \")\");\n\n return true;\n}\n<commit_msg>Various typo fixes.<commit_after>\/** \\file LocalDataDB.cc\n * \\brief Implementation of the LocalDataDB class.\n * \\author Dr. Johannes Ruscheinski (johannes.ruscheinski@uni-tuebingen.de)\n *\n * \\copyright 2020 Universitätsbibliothek Tübingen. All rights reserved.\n *\n * This program is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License as\n * published by the Free Software Foundation, either version 3 of the\n * License, or (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Affero General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public License\n * along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n#include \"LocalDataDB.h\"\n#include \"Compiler.h\"\n#include \"DbConnection.h\"\n#include \"StringUtil.h\"\n#include \"UBTools.h\"\n\n\nLocalDataDB::LocalDataDB(const OpenMode open_mode) {\n db_connection_ = new DbConnection(UBTools::GetTuelibPath() + \"local_data.sq3\" \/* must be the same path as in fetch_marc_updates.py *\/,\n (open_mode == READ_WRITE) ? DbConnection::CREATE : DbConnection::READONLY);\n if (open_mode == READ_ONLY)\n return;\n\n db_connection_->queryOrDie(\"CREATE TABLE IF NOT EXISTS local_data (\"\n \" title_ppn TEXT PRIMARY KEY,\"\n \" local_fields BLOB NOT NULL\"\n \") WITHOUT ROWID\");\n db_connection_->queryOrDie(\"CREATE UNIQUE INDEX IF NOT EXISTS local_data_index ON local_data (title_ppn)\");\n\n db_connection_->queryOrDie(\"CREATE TABLE IF NOT EXISTS local_ppns_to_title_ppns_map (\"\n \" local_ppn TEXT PRIMARY KEY,\"\n \" title_ppn TEXT NOT NULL,\"\n \" FOREIGN KEY(title_ppn) REFERENCES local_data(title_ppn)\"\n \") WITHOUT ROWID\");\n db_connection_->queryOrDie(\"CREATE UNIQUE INDEX IF NOT EXISTS local_ppns_to_title_ppns_mapindex \"\n \"ON local_ppns_to_title_ppns_map (local_ppn)\");\n}\n\n\nLocalDataDB::~LocalDataDB() {\n delete db_connection_;\n}\n\n\nvoid LocalDataDB::clear() {\n db_connection_->queryOrDie(\"DROP TABLE IF EXISTS local_data\");\n db_connection_->queryOrDie(\"DROP TABLE IF EXISTS local_ppns_to_title_ppns_map\");\n}\n\n\nstatic std::vector<std::string> BlobToLocalFieldsVector(const std::string &local_fields_blob, const std::string &title_ppn) {\n std::vector<std::string> local_fields;\n\n size_t processed_size(0);\n do {\n \/\/ Convert the 4 character hex string to the size of the following field contents:\n const size_t field_contents_size(StringUtil::ToUnsignedLong(local_fields_blob.substr(processed_size, 4), 16));\n processed_size += 4;\n\n \/\/ Sanity check:\n if (unlikely(processed_size + field_contents_size > local_fields_blob.size()))\n LOG_ERROR(\"inconsistent blob length for record with PPN \" + title_ppn + \" (1)\");\n\n local_fields.emplace_back(local_fields_blob.substr(processed_size, field_contents_size));\n processed_size += field_contents_size;\n } while (processed_size < local_fields_blob.size());\n\n \/\/ Sanity check:\n if (unlikely(processed_size != local_fields_blob.size()))\n LOG_ERROR(\"inconsistent blob length for record with PPN \" + title_ppn + \" (2))\");\n\n return local_fields;\n}\n\n\nstd::vector<std::string> ExtractLocalPPNsFromLocalFieldsVector(const std::vector<std::string> &local_fields) {\n std::vector<std::string> local_ppns;\n\n for (const auto &local_field : local_fields) {\n if (StringUtil::StartsWith(local_field, \"001 \"))\n local_ppns.emplace_back(local_field.substr(__builtin_strlen(\"001 \")));\n }\n\n return local_ppns;\n}\n\n\nstatic std::string ConvertLocalFieldsVectorToBlob(const std::vector<std::string> &local_fields) {\n std::string local_fields_blob;\n for (const auto &local_field : local_fields) {\n local_fields_blob += StringUtil::ToString(local_field.length(), \/* radix = *\/16,\n \/* width = *\/4, \/* padding_char = *\/'0');\n local_fields_blob += local_field;\n }\n\n return local_fields_blob;\n}\n\n\nvoid LocalDataDB::insertOrReplace(const std::string &title_ppn, const std::vector<std::string> &local_fields) {\n \/\/ 1. Clear out any local PPNs associated with \"title_ppn\":\n db_connection_->queryOrDie(\"SELECT local_fields FROM local_data WHERE title_ppn = \"\n + db_connection_->escapeAndQuoteString(title_ppn));\n auto result_set(db_connection_->getLastResultSet());\n if (not result_set.empty()) {\n const auto row(result_set.getNextRow());\n const auto previous_local_fields(BlobToLocalFieldsVector(row[\"local_fields\"], title_ppn));\n const auto local_ppns(ExtractLocalPPNsFromLocalFieldsVector(previous_local_fields));\n for (const auto &local_ppn : local_ppns)\n db_connection_->queryOrDie(\"DELETE FROM local_ppns_to_title_ppns_map WHERE local_ppn=\"\n + db_connection_->escapeAndQuoteString(local_ppn));\n }\n\n \/\/ 2. Replace or insert the local data keyed by the title PPN's:\n db_connection_->queryOrDie(\"REPLACE INTO local_data (title_ppn, local_fields) VALUES(\"\n + db_connection_->escapeAndQuoteString(title_ppn) + \",\"\n + db_connection_->sqliteEscapeBlobData(ConvertLocalFieldsVectorToBlob(local_fields)) + \")\");\n\n \/\/ 3. Insert the mappings from the local PPN's to the title PPN's:\n for (const auto &local_ppn : ExtractLocalPPNsFromLocalFieldsVector(local_fields)) {\n db_connection_->queryOrDie(\"INSERT INTO local_ppns_to_title_ppns_map (local_ppn, title_ppn) VALUES(\"\n + db_connection_->escapeAndQuoteString(local_ppn) + \",\"\n + db_connection_->escapeAndQuoteString(title_ppn) + \")\");\n }\n}\n\n\nstd::vector<std::string> LocalDataDB::getLocalFields(const std::string &title_ppn) const {\n db_connection_->queryOrDie(\"SELECT local_fields FROM local_data WHERE title_ppn = \"\n + db_connection_->escapeAndQuoteString(title_ppn));\n auto result_set(db_connection_->getLastResultSet());\n if (result_set.empty())\n return {}; \/\/ empty vector\n\n const auto row(result_set.getNextRow());\n return BlobToLocalFieldsVector(row[\"local_fields\"], title_ppn);\n}\n\n\nbool LocalDataDB::removeTitleDataSet(const std::string &title_ppn) {\n \/\/ 1. Clear out any local PPNs associated with \"title_ppn\":\n db_connection_->queryOrDie(\"SELECT local_fields FROM local_data WHERE title_ppn = \"\n + db_connection_->escapeAndQuoteString(title_ppn));\n auto result_set(db_connection_->getLastResultSet());\n if (result_set.empty())\n return false;\n\n const auto row(result_set.getNextRow());\n const auto previous_local_fields(BlobToLocalFieldsVector(row[\"local_fields\"], title_ppn));\n const auto local_ppns(ExtractLocalPPNsFromLocalFieldsVector(previous_local_fields));\n for (const auto &local_ppn : local_ppns)\n db_connection_->queryOrDie(\"DELETE FROM local_ppns_to_title_ppns_map WHERE local_ppn=\"\n + db_connection_->escapeAndQuoteString(local_ppn));\n\n \/\/ 2. Delete the local data for the title PPN:\n db_connection_->queryOrDie(\"DELETE FROM local_data WHERE title_ppn = \"\n + db_connection_->escapeAndQuoteString(title_ppn));\n\n return true;\n}\n\n\n\/\/ Removes all fields from \"local_fields\" that are associated w\/ \"local_ppn\".\nstatic std::vector<std::string> RemoveLocalDataSet(const std::string &local_ppn,\n const std::vector<std::string> &local_fields)\n{\n std::vector<std::string> filtered_local_fields;\n filtered_local_fields.reserve(local_fields.size());\n\n bool skipping(false);\n for (const auto &local_field : local_fields) {\n if (StringUtil::StartsWith(local_field, \"001 \"))\n skipping = local_field.substr(__builtin_strlen(\"001 \")) == local_ppn;\n if (not skipping)\n filtered_local_fields.emplace_back(local_field);\n }\n\n return filtered_local_fields;\n}\n\n\nbool LocalDataDB::removeLocalDataSet(const std::string &local_ppn) {\n \/\/ 1. Determine the title PPN associated w\/ the local PPN:\n db_connection_->queryOrDie(\"SELECT title_ppn FROM local_ppns_to_title_ppns_map WHERE local_ppn=\"\n + db_connection_->escapeAndQuoteString(local_ppn));\n auto result_set(db_connection_->getLastResultSet());\n if (result_set.empty())\n return false;\n const auto row(result_set.getNextRow());\n const auto title_ppn(row[\"title_ppn\"]);\n\n \/\/ 2. Retrieve the local data associated w\/ the title PPN:\n auto local_fields(getLocalFields(title_ppn));\n\n \/\/ 3. Remove the local data associated w\/ the local PPN:\n const auto filtered_local_fields(RemoveLocalDataSet(local_ppn, local_fields));\n\n \/\/ 4. Update our SQL tables:\n db_connection_->queryOrDie(\"DELETE FROM local_ppns_to_title_ppns_map WHERE local_ppn=\"\n + db_connection_->escapeAndQuoteString(local_ppn));\n if (filtered_local_fields.empty())\n db_connection_->queryOrDie(\"DELETE FROM local_fields WHERE title_ppn=\"\n + db_connection_->escapeAndQuoteString(title_ppn));\n else\n db_connection_->queryOrDie(\"REPLACE INTO local_data (titel_ppn, local_fields) VALUES(\"\n + db_connection_->escapeAndQuoteString(title_ppn) + \",\"\n + db_connection_->sqliteEscapeBlobData(ConvertLocalFieldsVectorToBlob(local_fields)) + \")\");\n\n return true;\n}\n<|endoftext|>"} {"text":"<commit_before>\/* ---------------------------------------------------------------------------\n** This software is in the public domain, furnished \"as is\", without technical\n** support, and with no warranty, express or implied, as to its usefulness for\n** any purpose.\n**\n** rtspvideocapturer.cpp\n**\n** -------------------------------------------------------------------------*\/\n\n#ifdef HAVE_LIVE555\n\n#include <chrono>\n\n#include \"rtc_base\/timeutils.h\"\n#include \"rtc_base\/logging.h\"\n\n#include \"modules\/video_coding\/h264_sprop_parameter_sets.h\"\n#include \"api\/video\/i420_buffer.h\"\n\n#include \"libyuv\/video_common.h\"\n#include \"libyuv\/convert.h\"\n\n#include \"rtspvideocapturer.h\"\n\nuint8_t marker[] = { 0, 0, 0, 1};\n\nint decodeTimeoutOption(const std::map<std::string,std::string> & opts) {\n\tint timeout = 10;\n\tif (opts.find(\"timeout\") != opts.end()) \n\t{\n\t\tstd::string timeoutString = opts.at(\"timeout\");\n\t\ttimeout = std::stoi(timeoutString);\n\t}\n\treturn timeout;\n}\n\nint decodeRTPTransport(const std::map<std::string,std::string> & opts) \n{\n\tint rtptransport = RTSPConnection::RTPUDPUNICAST;\n\tif (opts.find(\"rtptransport\") != opts.end()) \n\t{\n\t\tstd::string rtpTransportString = opts.at(\"rtptransport\");\n\t\tif (rtpTransportString == \"tcp\") {\n\t\t\trtptransport = RTSPConnection::RTPOVERTCP;\n\t\t} else if (rtpTransportString == \"http\") {\n\t\t\trtptransport = RTSPConnection::RTPOVERHTTP;\n\t\t} else if (rtpTransportString == \"multicast\") {\n\t\t\trtptransport = RTSPConnection::RTPUDPMULTICAST;\n\t\t}\n\t}\n\treturn rtptransport;\n}\n\nRTSPVideoCapturer::RTSPVideoCapturer(const std::string & uri, const std::map<std::string,std::string> & opts) \n\t: m_connection(m_env, this, uri.c_str(), decodeTimeoutOption(opts), decodeRTPTransport(opts), rtc::LogMessage::GetLogToDebug()<=3)\n{\n\tRTC_LOG(INFO) << \"RTSPVideoCapturer\" << uri ;\n\tm_h264 = h264_new();\n}\n\nRTSPVideoCapturer::~RTSPVideoCapturer()\n{\n\th264_free(m_h264);\n}\n\nbool RTSPVideoCapturer::onNewSession(const char* id,const char* media, const char* codec, const char* sdp)\n{\n\tbool success = false;\n\tif (strcmp(media, \"video\") == 0) {\t\n\t\tRTC_LOG(INFO) << \"RTSPVideoCapturer::onNewSession \" << media << \"\/\" << codec << \" \" << sdp;\n\t\t\n\t\tif (strcmp(codec, \"H264\") == 0)\n\t\t{\n\t\t\tm_codec = codec;\n\t\t\tconst char* pattern=\"sprop-parameter-sets=\";\n\t\t\tconst char* sprop=strstr(sdp, pattern);\n\t\t\tif (sprop)\n\t\t\t{\n\t\t\t\tstd::string sdpstr(sprop+strlen(pattern));\n\t\t\t\tsize_t pos = sdpstr.find_first_of(\" ;\\r\\n\");\n\t\t\t\tif (pos != std::string::npos)\n\t\t\t\t{\n\t\t\t\t\tsdpstr.erase(pos);\n\t\t\t\t}\n\t\t\t\twebrtc::H264SpropParameterSets sprops;\n\t\t\t\tif (sprops.DecodeSprop(sdpstr))\n\t\t\t\t{\n\t\t\t\t\tstruct timeval presentationTime;\n\t\t\t\t\ttimerclear(&presentationTime);\n\n\t\t\t\t\tstd::vector<uint8_t> sps;\n\t\t\t\t\tsps.insert(sps.end(), marker, marker+sizeof(marker));\n\t\t\t\t\tsps.insert(sps.end(), sprops.sps_nalu().begin(), sprops.sps_nalu().end());\n\t\t\t\t\tonData(id, sps.data(), sps.size(), presentationTime);\n\n\t\t\t\t\tstd::vector<uint8_t> pps;\n\t\t\t\t\tpps.insert(pps.end(), marker, marker+sizeof(marker));\n\t\t\t\t\tpps.insert(pps.end(), sprops.pps_nalu().begin(), sprops.pps_nalu().end());\n\t\t\t\t\tonData(id, pps.data(), pps.size(), presentationTime);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tRTC_LOG(WARNING) << \"Cannot decode SPS:\" << sprop;\n\t\t\t\t}\n\t\t\t}\n\t\t\tsuccess = true;\n\t\t}\n\t\telse if (strcmp(codec, \"JPEG\") == 0) \n\t\t{\n\t\t\tm_codec = codec;\n\t\t\tsuccess = true;\n\t\t}\n\t}\n\treturn success;\n}\n\nbool RTSPVideoCapturer::onData(const char* id, unsigned char* buffer, ssize_t size, struct timeval presentationTime)\n{\n\tint64_t ts = presentationTime.tv_sec;\n\tts = ts*1000 + presentationTime.tv_usec\/1000;\n\tRTC_LOG(LS_VERBOSE) << \"RTSPVideoCapturer:onData size:\" << size << \" ts:\" << ts;\n\tint res = 0;\n\n\tif (m_codec == \"H264\") {\n\t\tint nal_start = 0;\n\t\tint nal_end = 0;\n\t\tfind_nal_unit(buffer, size, &nal_start, &nal_end);\n\t\tread_nal_unit(m_h264, &buffer[nal_start], nal_end - nal_start);\n\t\tif (m_h264->nal->nal_unit_type == NAL_UNIT_TYPE_SPS) {\n\t\t\tRTC_LOG(LS_VERBOSE) << \"RTSPVideoCapturer:onData SPS\";\n\t\t\tm_cfg.clear();\n\t\t\tm_cfg.insert(m_cfg.end(), buffer, buffer+size);\n\n\t\t\tunsigned int width = ((m_h264->sps->pic_width_in_mbs_minus1 +1)*16) - m_h264->sps->frame_crop_left_offset*2 - m_h264->sps->frame_crop_right_offset*2;\n\t\t\tunsigned int height= ((2 - m_h264->sps->frame_mbs_only_flag)* (m_h264->sps->pic_height_in_map_units_minus1 +1) * 16) - (m_h264->sps->frame_crop_top_offset * 2) - (m_h264->sps->frame_crop_bottom_offset * 2);\n\t\t\tunsigned int fps=25;\n\t\t\tRTC_LOG(LS_VERBOSE) << \"RTSPVideoCapturer:onData SPS set timing_info_present_flag:\" << m_h264->sps->vui.timing_info_present_flag << \" \" << m_h264->sps->vui.time_scale << \" \" << m_h264->sps->vui.num_units_in_tick;\n\t\t\tif (m_decoder.get()) {\n\t\t\t\tif ( (GetCaptureFormat()->width != width) || (GetCaptureFormat()->height != height) ) {\n\t\t\t\t\tRTC_LOG(INFO) << \"format changed => set format from \" << GetCaptureFormat()->width << \"x\" << GetCaptureFormat()->height\t << \" to \" << width << \"x\" << height;\n\t\t\t\t\tm_decoder.reset(NULL);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (!m_decoder.get()) {\n\t\t\t\tRTC_LOG(INFO) << \"RTSPVideoCapturer:onData SPS set format \" << width << \"x\" << height << \" fps:\" << fps;\n\t\t\t\tcricket::VideoFormat videoFormat(width, height, cricket::VideoFormat::FpsToInterval(fps), cricket::FOURCC_I420);\n\t\t\t\tSetCaptureFormat(&videoFormat);\n\n\t\t\t\tm_decoder=m_factory.CreateVideoDecoder(webrtc::SdpVideoFormat(cricket::kH264CodecName));\n\t\t\t\twebrtc::VideoCodec codec_settings;\n\t\t\t\tcodec_settings.codecType = webrtc::VideoCodecType::kVideoCodecH264;\n\t\t\t\tm_decoder->InitDecode(&codec_settings,2);\n\t\t\t\tm_decoder->RegisterDecodeCompleteCallback(this);\n\t\t\t}\n\t\t}\n\t\telse if (m_h264->nal->nal_unit_type == NAL_UNIT_TYPE_PPS) {\n\t\t\tRTC_LOG(LS_VERBOSE) << \"RTSPVideoCapturer:onData PPS\";\n\t\t\tm_cfg.insert(m_cfg.end(), buffer, buffer+size);\n\t\t}\n\t\telse if (m_decoder.get()) {\n\t\t\tstd::vector<uint8_t> content;\n\t\t\tif (m_h264->nal->nal_unit_type == NAL_UNIT_TYPE_CODED_SLICE_IDR) {\n\t\t\t\tRTC_LOG(LS_VERBOSE) << \"RTSPVideoCapturer:onData IDR\";\t\t\t\t\n\t\t\t\tcontent.insert(content.end(), m_cfg.begin(), m_cfg.end());\n\t\t\t}\n\t\t\telse {\n\t\t\t\tRTC_LOG(LS_VERBOSE) << \"RTSPVideoCapturer:onData SLICE NALU:\" << m_h264->nal->nal_unit_type;\n\t\t\t}\n\t\t\tcontent.insert(content.end(), buffer, buffer+size);\n\t\t\tFrame frame(std::move(content), ts);\t\t\t\n\t\t\t{\n\t\t\t\tstd::unique_lock<std::mutex> lock(m_queuemutex);\n\t\t\t\tm_queue.push(frame);\n\t\t\t}\n\t\t\tm_queuecond.notify_all();\n\t\t} else {\n\t\t\tRTC_LOG(LS_ERROR) << \"RTSPVideoCapturer:onData no decoder\";\n\t\t\tres = -1;\n\t\t}\n\t} else if (m_codec == \"JPEG\") {\n\t\tint32_t width = 0;\n\t\tint32_t height = 0;\n\t\tif (libyuv::MJPGSize(buffer, size, &width, &height) == 0) {\n\t\t\tint stride_y = width;\n\t\t\tint stride_uv = (width + 1) \/ 2;\n\t\t\t\t\t\n\t\t\trtc::scoped_refptr<webrtc::I420Buffer> I420buffer = webrtc::I420Buffer::Create(width, height, stride_y, stride_uv, stride_uv);\n\t\t\tconst int conversionResult = libyuv::ConvertToI420((const uint8*)buffer, size,\n\t\t\t\t\t\t\t(uint8*)I420buffer->DataY(), I420buffer->StrideY(),\n\t\t\t\t\t\t\t(uint8*)I420buffer->DataU(), I420buffer->StrideU(),\n\t\t\t\t\t\t\t(uint8*)I420buffer->DataV(), I420buffer->StrideV(),\n\t\t\t\t\t\t\t0, 0,\n\t\t\t\t\t\t\twidth, height,\n\t\t\t\t\t\t\twidth, height,\n\t\t\t\t\t\t\tlibyuv::kRotate0, ::libyuv::FOURCC_MJPG);\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\n\t\t\tif (conversionResult >= 0) {\n\t\t\t\twebrtc::VideoFrame frame(I420buffer, 0, ts, webrtc::kVideoRotation_0);\n\t\t\t\tthis->Decoded(frame);\n\t\t\t} else {\n\t\t\t\tRTC_LOG(LS_ERROR) << \"RTSPVideoCapturer:onData decoder error:\" << conversionResult;\n\t\t\t\tres = -1;\n\t\t\t}\n\t\t} else {\n\t\t\tRTC_LOG(LS_ERROR) << \"RTSPVideoCapturer:onData cannot JPEG dimension\";\n\t\t\tres = -1;\n\t\t}\n\t\t\t \n\t}\n\n\treturn (res == 0);\n}\n\nvoid RTSPVideoCapturer::DecoderThread() \n{\n\twhile (IsRunning()) {\n\t\tstd::unique_lock<std::mutex> mlock(m_queuemutex);\n\t\twhile (m_queue.empty())\n\t\t{\n\t\t\tm_queuecond.wait(mlock);\n\t\t}\n\t\tFrame frame = m_queue.front();\n\t\tm_queue.pop();\t\t\n\t\tmlock.unlock();\n\t\t\n\t\tRTC_LOG(LS_VERBOSE) << \"RTSPVideoCapturer:DecoderThread size:\" << frame.m_content.size() << \" ts:\" << frame.m_timestamp_ms;\n\t\tuint8_t* data = frame.m_content.data();\n\t\tssize_t size = frame.m_content.size();\n\t\t\n\t\tif (size) {\n\t\t\tsize_t allocsize = size + webrtc::EncodedImage::GetBufferPaddingBytes(webrtc::VideoCodecType::kVideoCodecH264);\n\t\t\tuint8_t buf[allocsize];\n\t\t\tmemcpy( buf, data, size );\n\n\t\t\twebrtc::EncodedImage input_image(buf, size, allocsize);\t\t\n\t\t\tinput_image._timeStamp = frame.m_timestamp_ms; \/\/ store time in ms that overflow the 32bits\n\t\t\tm_decoder->Decode(input_image, false, NULL);\n\t\t}\n\t}\n}\n\nint32_t RTSPVideoCapturer::Decoded(webrtc::VideoFrame& decodedImage)\n{\n\tint64_t ts = std::chrono::high_resolution_clock::now().time_since_epoch().count()\/1000\/1000;\n\n\tRTC_LOG(LS_VERBOSE) << \"RTSPVideoCapturer::Decoded size:\" << decodedImage.size() \n\t\t\t\t<< \" decode ts:\" << decodedImage.timestamp() \n\t\t\t\t<< \" source ts:\" << ts;\n\n\t\/\/ avoid to block the encoder that drop frames when sent too quickly\n\tstatic int64_t previmagets = 0;\t\n\tstatic int64_t prevts = 0;\n\tif (prevts != 0) {\n\t\tint64_t periodSource = decodedImage.timestamp() - previmagets;\n\t\tint64_t periodDecode = ts-prevts;\n\t\t\t\n\t\tRTC_LOG(LS_VERBOSE) << \"RTSPVideoCapturer::Decoded interframe decode:\" << periodDecode << \" source:\" << periodSource;\n\t\tint64_t delayms = periodSource-periodDecode;\n\t\tif ( (delayms > 0) && (delayms < 1000) ) {\n\t\t\tusleep(delayms*1000);\n\t\t}\n\t}\n\t\n\tthis->OnFrame(decodedImage, decodedImage.height(), decodedImage.width());\n\t\n\tprevimagets = decodedImage.timestamp();\n\tprevts = std::chrono::high_resolution_clock::now().time_since_epoch().count()\/1000\/1000;\n\t\n\treturn true;\n}\n\ncricket::CaptureState RTSPVideoCapturer::Start(const cricket::VideoFormat& format)\n{\n\tSetCaptureFormat(&format);\n\tSetCaptureState(cricket::CS_RUNNING);\n\trtc::Thread::Start();\n\tm_decoderthread = std::thread(&RTSPVideoCapturer::DecoderThread, this);\n\treturn cricket::CS_RUNNING;\n}\n\nvoid RTSPVideoCapturer::Stop()\n{\n\tm_env.stop();\n\trtc::Thread::Stop();\n\tSetCaptureFormat(NULL);\n\tSetCaptureState(cricket::CS_STOPPED);\n\tFrame frame;\t\t\t\n\t{\n\t\tstd::unique_lock<std::mutex> lock(m_queuemutex);\n\t\tm_queue.push(frame);\n\t}\n\tm_queuecond.notify_all();\n\tm_decoderthread.join();\n}\n\nvoid RTSPVideoCapturer::Run()\n{\n\tm_env.mainloop();\n}\n\nbool RTSPVideoCapturer::GetPreferredFourccs(std::vector<unsigned int>* fourccs)\n{\n\treturn true;\n}\n#endif\n<commit_msg>fix #123: build with lastest WebRTC<commit_after>\/* ---------------------------------------------------------------------------\n** This software is in the public domain, furnished \"as is\", without technical\n** support, and with no warranty, express or implied, as to its usefulness for\n** any purpose.\n**\n** rtspvideocapturer.cpp\n**\n** -------------------------------------------------------------------------*\/\n\n#ifdef HAVE_LIVE555\n\n#include <chrono>\n\n#include \"rtc_base\/timeutils.h\"\n#include \"rtc_base\/logging.h\"\n\n#include \"modules\/video_coding\/h264_sprop_parameter_sets.h\"\n#include \"api\/video\/i420_buffer.h\"\n\n#include \"libyuv\/video_common.h\"\n#include \"libyuv\/convert.h\"\n\n#include \"rtspvideocapturer.h\"\n\nuint8_t marker[] = { 0, 0, 0, 1};\n\nint decodeTimeoutOption(const std::map<std::string,std::string> & opts) {\n\tint timeout = 10;\n\tif (opts.find(\"timeout\") != opts.end()) \n\t{\n\t\tstd::string timeoutString = opts.at(\"timeout\");\n\t\ttimeout = std::stoi(timeoutString);\n\t}\n\treturn timeout;\n}\n\nint decodeRTPTransport(const std::map<std::string,std::string> & opts) \n{\n\tint rtptransport = RTSPConnection::RTPUDPUNICAST;\n\tif (opts.find(\"rtptransport\") != opts.end()) \n\t{\n\t\tstd::string rtpTransportString = opts.at(\"rtptransport\");\n\t\tif (rtpTransportString == \"tcp\") {\n\t\t\trtptransport = RTSPConnection::RTPOVERTCP;\n\t\t} else if (rtpTransportString == \"http\") {\n\t\t\trtptransport = RTSPConnection::RTPOVERHTTP;\n\t\t} else if (rtpTransportString == \"multicast\") {\n\t\t\trtptransport = RTSPConnection::RTPUDPMULTICAST;\n\t\t}\n\t}\n\treturn rtptransport;\n}\n\nRTSPVideoCapturer::RTSPVideoCapturer(const std::string & uri, const std::map<std::string,std::string> & opts) \n\t: m_connection(m_env, this, uri.c_str(), decodeTimeoutOption(opts), decodeRTPTransport(opts), rtc::LogMessage::GetLogToDebug()<=3)\n{\n\tRTC_LOG(INFO) << \"RTSPVideoCapturer\" << uri ;\n\tm_h264 = h264_new();\n}\n\nRTSPVideoCapturer::~RTSPVideoCapturer()\n{\n\th264_free(m_h264);\n}\n\nbool RTSPVideoCapturer::onNewSession(const char* id,const char* media, const char* codec, const char* sdp)\n{\n\tbool success = false;\n\tif (strcmp(media, \"video\") == 0) {\t\n\t\tRTC_LOG(INFO) << \"RTSPVideoCapturer::onNewSession \" << media << \"\/\" << codec << \" \" << sdp;\n\t\t\n\t\tif (strcmp(codec, \"H264\") == 0)\n\t\t{\n\t\t\tm_codec = codec;\n\t\t\tconst char* pattern=\"sprop-parameter-sets=\";\n\t\t\tconst char* sprop=strstr(sdp, pattern);\n\t\t\tif (sprop)\n\t\t\t{\n\t\t\t\tstd::string sdpstr(sprop+strlen(pattern));\n\t\t\t\tsize_t pos = sdpstr.find_first_of(\" ;\\r\\n\");\n\t\t\t\tif (pos != std::string::npos)\n\t\t\t\t{\n\t\t\t\t\tsdpstr.erase(pos);\n\t\t\t\t}\n\t\t\t\twebrtc::H264SpropParameterSets sprops;\n\t\t\t\tif (sprops.DecodeSprop(sdpstr))\n\t\t\t\t{\n\t\t\t\t\tstruct timeval presentationTime;\n\t\t\t\t\ttimerclear(&presentationTime);\n\n\t\t\t\t\tstd::vector<uint8_t> sps;\n\t\t\t\t\tsps.insert(sps.end(), marker, marker+sizeof(marker));\n\t\t\t\t\tsps.insert(sps.end(), sprops.sps_nalu().begin(), sprops.sps_nalu().end());\n\t\t\t\t\tonData(id, sps.data(), sps.size(), presentationTime);\n\n\t\t\t\t\tstd::vector<uint8_t> pps;\n\t\t\t\t\tpps.insert(pps.end(), marker, marker+sizeof(marker));\n\t\t\t\t\tpps.insert(pps.end(), sprops.pps_nalu().begin(), sprops.pps_nalu().end());\n\t\t\t\t\tonData(id, pps.data(), pps.size(), presentationTime);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tRTC_LOG(WARNING) << \"Cannot decode SPS:\" << sprop;\n\t\t\t\t}\n\t\t\t}\n\t\t\tsuccess = true;\n\t\t}\n\t\telse if (strcmp(codec, \"JPEG\") == 0) \n\t\t{\n\t\t\tm_codec = codec;\n\t\t\tsuccess = true;\n\t\t}\n\t}\n\treturn success;\n}\n\nbool RTSPVideoCapturer::onData(const char* id, unsigned char* buffer, ssize_t size, struct timeval presentationTime)\n{\n\tint64_t ts = presentationTime.tv_sec;\n\tts = ts*1000 + presentationTime.tv_usec\/1000;\n\tRTC_LOG(LS_VERBOSE) << \"RTSPVideoCapturer:onData size:\" << size << \" ts:\" << ts;\n\tint res = 0;\n\n\tif (m_codec == \"H264\") {\n\t\tint nal_start = 0;\n\t\tint nal_end = 0;\n\t\tfind_nal_unit(buffer, size, &nal_start, &nal_end);\n\t\tread_nal_unit(m_h264, &buffer[nal_start], nal_end - nal_start);\n\t\tif (m_h264->nal->nal_unit_type == NAL_UNIT_TYPE_SPS) {\n\t\t\tRTC_LOG(LS_VERBOSE) << \"RTSPVideoCapturer:onData SPS\";\n\t\t\tm_cfg.clear();\n\t\t\tm_cfg.insert(m_cfg.end(), buffer, buffer+size);\n\n\t\t\tunsigned int width = ((m_h264->sps->pic_width_in_mbs_minus1 +1)*16) - m_h264->sps->frame_crop_left_offset*2 - m_h264->sps->frame_crop_right_offset*2;\n\t\t\tunsigned int height= ((2 - m_h264->sps->frame_mbs_only_flag)* (m_h264->sps->pic_height_in_map_units_minus1 +1) * 16) - (m_h264->sps->frame_crop_top_offset * 2) - (m_h264->sps->frame_crop_bottom_offset * 2);\n\t\t\tunsigned int fps=25;\n\t\t\tRTC_LOG(LS_VERBOSE) << \"RTSPVideoCapturer:onData SPS set timing_info_present_flag:\" << m_h264->sps->vui.timing_info_present_flag << \" \" << m_h264->sps->vui.time_scale << \" \" << m_h264->sps->vui.num_units_in_tick;\n\t\t\tif (m_decoder.get()) {\n\t\t\t\tif ( (GetCaptureFormat()->width != width) || (GetCaptureFormat()->height != height) ) {\n\t\t\t\t\tRTC_LOG(INFO) << \"format changed => set format from \" << GetCaptureFormat()->width << \"x\" << GetCaptureFormat()->height\t << \" to \" << width << \"x\" << height;\n\t\t\t\t\tm_decoder.reset(NULL);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (!m_decoder.get()) {\n\t\t\t\tRTC_LOG(INFO) << \"RTSPVideoCapturer:onData SPS set format \" << width << \"x\" << height << \" fps:\" << fps;\n\t\t\t\tcricket::VideoFormat videoFormat(width, height, cricket::VideoFormat::FpsToInterval(fps), cricket::FOURCC_I420);\n\t\t\t\tSetCaptureFormat(&videoFormat);\n\n\t\t\t\tm_decoder=m_factory.CreateVideoDecoder(webrtc::SdpVideoFormat(cricket::kH264CodecName));\n\t\t\t\twebrtc::VideoCodec codec_settings;\n\t\t\t\tcodec_settings.codecType = webrtc::VideoCodecType::kVideoCodecH264;\n\t\t\t\tm_decoder->InitDecode(&codec_settings,2);\n\t\t\t\tm_decoder->RegisterDecodeCompleteCallback(this);\n\t\t\t}\n\t\t}\n\t\telse if (m_h264->nal->nal_unit_type == NAL_UNIT_TYPE_PPS) {\n\t\t\tRTC_LOG(LS_VERBOSE) << \"RTSPVideoCapturer:onData PPS\";\n\t\t\tm_cfg.insert(m_cfg.end(), buffer, buffer+size);\n\t\t}\n\t\telse if (m_decoder.get()) {\n\t\t\tstd::vector<uint8_t> content;\n\t\t\tif (m_h264->nal->nal_unit_type == NAL_UNIT_TYPE_CODED_SLICE_IDR) {\n\t\t\t\tRTC_LOG(LS_VERBOSE) << \"RTSPVideoCapturer:onData IDR\";\t\t\t\t\n\t\t\t\tcontent.insert(content.end(), m_cfg.begin(), m_cfg.end());\n\t\t\t}\n\t\t\telse {\n\t\t\t\tRTC_LOG(LS_VERBOSE) << \"RTSPVideoCapturer:onData SLICE NALU:\" << m_h264->nal->nal_unit_type;\n\t\t\t}\n\t\t\tcontent.insert(content.end(), buffer, buffer+size);\n\t\t\tFrame frame(std::move(content), ts);\t\t\t\n\t\t\t{\n\t\t\t\tstd::unique_lock<std::mutex> lock(m_queuemutex);\n\t\t\t\tm_queue.push(frame);\n\t\t\t}\n\t\t\tm_queuecond.notify_all();\n\t\t} else {\n\t\t\tRTC_LOG(LS_ERROR) << \"RTSPVideoCapturer:onData no decoder\";\n\t\t\tres = -1;\n\t\t}\n\t} else if (m_codec == \"JPEG\") {\n\t\tint32_t width = 0;\n\t\tint32_t height = 0;\n\t\tif (libyuv::MJPGSize(buffer, size, &width, &height) == 0) {\n\t\t\tint stride_y = width;\n\t\t\tint stride_uv = (width + 1) \/ 2;\n\t\t\t\t\t\n\t\t\trtc::scoped_refptr<webrtc::I420Buffer> I420buffer = webrtc::I420Buffer::Create(width, height, stride_y, stride_uv, stride_uv);\n\t\t\tconst int conversionResult = libyuv::ConvertToI420((const uint8*)buffer, size,\n\t\t\t\t\t\t\t(uint8*)I420buffer->DataY(), I420buffer->StrideY(),\n\t\t\t\t\t\t\t(uint8*)I420buffer->DataU(), I420buffer->StrideU(),\n\t\t\t\t\t\t\t(uint8*)I420buffer->DataV(), I420buffer->StrideV(),\n\t\t\t\t\t\t\t0, 0,\n\t\t\t\t\t\t\twidth, height,\n\t\t\t\t\t\t\twidth, height,\n\t\t\t\t\t\t\tlibyuv::kRotate0, ::libyuv::FOURCC_MJPG);\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\n\t\t\tif (conversionResult >= 0) {\n\t\t\t\twebrtc::VideoFrame frame(I420buffer, 0, ts, webrtc::kVideoRotation_0);\n\t\t\t\tthis->Decoded(frame);\n\t\t\t} else {\n\t\t\t\tRTC_LOG(LS_ERROR) << \"RTSPVideoCapturer:onData decoder error:\" << conversionResult;\n\t\t\t\tres = -1;\n\t\t\t}\n\t\t} else {\n\t\t\tRTC_LOG(LS_ERROR) << \"RTSPVideoCapturer:onData cannot JPEG dimension\";\n\t\t\tres = -1;\n\t\t}\n\t\t\t \n\t}\n\n\treturn (res == 0);\n}\n\nvoid RTSPVideoCapturer::DecoderThread() \n{\n\twhile (IsRunning()) {\n\t\tstd::unique_lock<std::mutex> mlock(m_queuemutex);\n\t\twhile (m_queue.empty())\n\t\t{\n\t\t\tm_queuecond.wait(mlock);\n\t\t}\n\t\tFrame frame = m_queue.front();\n\t\tm_queue.pop();\t\t\n\t\tmlock.unlock();\n\t\t\n\t\tRTC_LOG(LS_VERBOSE) << \"RTSPVideoCapturer:DecoderThread size:\" << frame.m_content.size() << \" ts:\" << frame.m_timestamp_ms;\n\t\tuint8_t* data = frame.m_content.data();\n\t\tssize_t size = frame.m_content.size();\n\t\t\n\t\tif (size) {\n\t\t\tsize_t allocsize = size + webrtc::EncodedImage::GetBufferPaddingBytes(webrtc::VideoCodecType::kVideoCodecH264);\n\t\t\tuint8_t buf[allocsize];\n\t\t\tmemcpy( buf, data, size );\n\n\t\t\twebrtc::EncodedImage input_image(buf, size, allocsize);\t\t\n\t\t\tinput_image._timeStamp = frame.m_timestamp_ms; \/\/ store time in ms that overflow the 32bits\n\t\t\tm_decoder->Decode(input_image, false, NULL,0);\n\t\t}\n\t}\n}\n\nint32_t RTSPVideoCapturer::Decoded(webrtc::VideoFrame& decodedImage)\n{\n\tint64_t ts = std::chrono::high_resolution_clock::now().time_since_epoch().count()\/1000\/1000;\n\n\tRTC_LOG(LS_VERBOSE) << \"RTSPVideoCapturer::Decoded size:\" << decodedImage.size() \n\t\t\t\t<< \" decode ts:\" << decodedImage.timestamp() \n\t\t\t\t<< \" source ts:\" << ts;\n\n\t\/\/ avoid to block the encoder that drop frames when sent too quickly\n\tstatic int64_t previmagets = 0;\t\n\tstatic int64_t prevts = 0;\n\tif (prevts != 0) {\n\t\tint64_t periodSource = decodedImage.timestamp() - previmagets;\n\t\tint64_t periodDecode = ts-prevts;\n\t\t\t\n\t\tRTC_LOG(LS_VERBOSE) << \"RTSPVideoCapturer::Decoded interframe decode:\" << periodDecode << \" source:\" << periodSource;\n\t\tint64_t delayms = periodSource-periodDecode;\n\t\tif ( (delayms > 0) && (delayms < 1000) ) {\n\t\t\tusleep(delayms*1000);\n\t\t}\n\t}\n\t\n\tthis->OnFrame(decodedImage, decodedImage.height(), decodedImage.width());\n\t\n\tprevimagets = decodedImage.timestamp();\n\tprevts = std::chrono::high_resolution_clock::now().time_since_epoch().count()\/1000\/1000;\n\t\n\treturn true;\n}\n\ncricket::CaptureState RTSPVideoCapturer::Start(const cricket::VideoFormat& format)\n{\n\tSetCaptureFormat(&format);\n\tSetCaptureState(cricket::CS_RUNNING);\n\trtc::Thread::Start();\n\tm_decoderthread = std::thread(&RTSPVideoCapturer::DecoderThread, this);\n\treturn cricket::CS_RUNNING;\n}\n\nvoid RTSPVideoCapturer::Stop()\n{\n\tm_env.stop();\n\trtc::Thread::Stop();\n\tSetCaptureFormat(NULL);\n\tSetCaptureState(cricket::CS_STOPPED);\n\tFrame frame;\t\t\t\n\t{\n\t\tstd::unique_lock<std::mutex> lock(m_queuemutex);\n\t\tm_queue.push(frame);\n\t}\n\tm_queuecond.notify_all();\n\tm_decoderthread.join();\n}\n\nvoid RTSPVideoCapturer::Run()\n{\n\tm_env.mainloop();\n}\n\nbool RTSPVideoCapturer::GetPreferredFourccs(std::vector<unsigned int>* fourccs)\n{\n\treturn true;\n}\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/****************************************************************************\n *\n * Copyright (c) 2012-2015 PX4 Development Team. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in\n * the documentation and\/or other materials provided with the\n * distribution.\n * 3. Neither the name PX4 nor the names of its contributors may be\n * used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS\n * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED\n * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n ****************************************************************************\/\n\n\/**\n * @file irlock.cpp\n * @author Michael Landes\n *\n * Driver for an IR-Lock and Pixy vision sensor connected via I2C.\n *\n * Created on: Nov 12, 2014\n **\/\n\n#include <string.h>\n\n#include <drivers\/device\/i2c.h>\n#include <drivers\/device\/ringbuffer.h>\n\n#include <px4_platform_common\/getopt.h>\n#include <px4_platform_common\/module.h>\n#include <px4_platform_common\/i2c_spi_buses.h>\n\n#include <uORB\/Publication.hpp>\n#include <uORB\/topics\/irlock_report.h>\n\n\/** Configuration Constants **\/\n#define IRLOCK_I2C_ADDRESS\t\t0x54 \/** 7-bit address (non shifted) **\/\n#define IRLOCK_CONVERSION_INTERVAL_US\t20000U \/** us = 20ms = 50Hz **\/\n\n#define IRLOCK_SYNC\t\t\t0xAA55\n#define IRLOCK_RESYNC\t\t0x5500\n#define IRLOCK_ADJUST\t\t0xAA\n\n#define IRLOCK_RES_X 320\n#define IRLOCK_RES_Y 200\n\n#define IRLOCK_CENTER_X\t\t\t\t(IRLOCK_RES_X\/2)\t\t\t\/\/ the x-axis center pixel position\n#define IRLOCK_CENTER_Y\t\t\t\t(IRLOCK_RES_Y\/2)\t\t\t\/\/ the y-axis center pixel position\n\n#define IRLOCK_FOV_X (60.0f*M_PI_F\/180.0f)\n#define IRLOCK_FOV_Y (35.0f*M_PI_F\/180.0f)\n\n#define IRLOCK_TAN_HALF_FOV_X 0.57735026919f \/\/ tan(0.5 * 60 * pi\/180)\n#define IRLOCK_TAN_HALF_FOV_Y 0.31529878887f \/\/ tan(0.5 * 35 * pi\/180)\n\n#define IRLOCK_TAN_ANG_PER_PIXEL_X\t(2*IRLOCK_TAN_HALF_FOV_X\/IRLOCK_RES_X)\n#define IRLOCK_TAN_ANG_PER_PIXEL_Y\t(2*IRLOCK_TAN_HALF_FOV_Y\/IRLOCK_RES_Y)\n\n#define IRLOCK_OBJECTS_MAX\t5\t\/** up to 5 objects can be detected\/reported **\/\n\nstruct irlock_target_s {\n\tuint16_t signature;\t\/** target signature **\/\n\tfloat pos_x;\t\/** x-axis distance from center of image to center of target in units of tan(theta) **\/\n\tfloat pos_y;\t\/** y-axis distance from center of image to center of target in units of tan(theta) **\/\n\tfloat size_x;\t\/** size of target along x-axis in units of tan(theta) **\/\n\tfloat size_y;\t\/** size of target along y-axis in units of tan(theta) **\/\n};\n\n\/** irlock_s structure returned from read calls **\/\nstruct irlock_s {\n\thrt_abstime timestamp; \/** microseconds since system start **\/\n\tuint8_t num_targets;\n\tstruct irlock_target_s targets[IRLOCK_OBJECTS_MAX];\n};\n\nclass IRLOCK : public device::I2C, public I2CSPIDriver<IRLOCK>\n{\npublic:\n\tIRLOCK(I2CSPIBusOption bus_option, const int bus, int bus_frequency, const int address);\n\tvirtual ~IRLOCK();\n\n\tstatic I2CSPIDriverBase *instantiate(const BusCLIArguments &cli, const BusInstanceIterator &iterator,\n\t\t\t\t\t int runtime_instance);\n\tstatic void print_usage();\n\n\tvoid custom_method(const BusCLIArguments &cli) override;\n\n\tint init() override;\n\tint probe() override;\n\tvoid print_status() override;\n\tint test();\n\n\tvirtual ssize_t read(struct file *filp, char *buffer, size_t buflen);\n\n\t\/** read from device and schedule next read **\/\n\tvoid\t\tRunImpl();\nprivate:\n\n\t\/** start periodic reads from sensor **\/\n\tvoid \t\tstart();\n\n\t\/** low level communication with sensor **\/\n\tint \t\tread_device();\n\tbool \t\tsync_device();\n\tint \t\tread_device_word(uint16_t *word);\n\tint \t\tread_device_block(struct irlock_target_s *block);\n\n\t\/** internal variables **\/\n\tringbuffer::RingBuffer *_reports;\n\tbool _sensor_ok;\n\tuint32_t _read_failures;\n\n\tint _orb_class_instance;\n\tuORB::Publication<irlock_report_s> _irlock_report_topic{ORB_ID(irlock_report)};\n};\n\nextern \"C\" __EXPORT int irlock_main(int argc, char *argv[]);\n\nIRLOCK::IRLOCK(I2CSPIBusOption bus_option, const int bus, int bus_frequency, const int address) :\n\tI2C(DRV_SENS_DEVTYPE_IRLOCK, MODULE_NAME, bus, address, bus_frequency),\n\tI2CSPIDriver(MODULE_NAME, px4::device_bus_to_wq(get_device_id()), bus_option, bus, address),\n\t_reports(nullptr),\n\t_sensor_ok(false),\n\t_read_failures(0),\n\t_orb_class_instance(-1)\n{\n}\n\nIRLOCK::~IRLOCK()\n{\n\tif (_reports != nullptr) {\n\t\tdelete _reports;\n\t}\n}\n\n\/** initialise driver to communicate with sensor **\/\nint IRLOCK::init()\n{\n\t\/** initialise I2C bus **\/\n\tint ret = I2C::init();\n\n\tif (ret != OK) {\n\t\treturn ret;\n\t}\n\n\t\/** allocate buffer storing values read from sensor **\/\n\t_reports = new ringbuffer::RingBuffer(2, sizeof(struct irlock_s));\n\n\tif (_reports == nullptr) {\n\t\treturn ENOTTY;\n\n\t} else {\n\t\t_sensor_ok = true;\n\t\t\/** start work queue **\/\n\t\tstart();\n\t\treturn OK;\n\t}\n}\n\n\/** probe the device is on the I2C bus **\/\nint IRLOCK::probe()\n{\n\t\/*\n\t * IRLock defaults to sending 0x00 when there is no block\n\t * data to return, so really all we can do is check to make\n\t * sure a transfer completes successfully.\n\t **\/\n\tuint8_t byte;\n\n\tif (transfer(nullptr, 0, &byte, 1) != OK) {\n\t\treturn -EIO;\n\t}\n\n\treturn OK;\n}\n\nvoid IRLOCK::print_status()\n{\n\t\/** display reports in queue **\/\n\tif (_sensor_ok) {\n\t\t_reports->print_info(\"report queue: \");\n\t\tPX4_INFO(\"read errors:%lu\", (unsigned long)_read_failures);\n\n\t} else {\n\t\tPX4_WARN(\"sensor is not healthy\");\n\t}\n}\n\n\/** test driver **\/\nint IRLOCK::test()\n{\n\t\/** exit immediately if sensor is not healty **\/\n\tif (!_sensor_ok) {\n\t\tPX4_ERR(\"sensor is not healthy\");\n\t\treturn -1;\n\t}\n\n\t\/** instructions to user **\/\n\tPX4_INFO(\"searching for object for 10 seconds\");\n\n\t\/** read from sensor for 10 seconds **\/\n\tstruct irlock_s report;\n\tuint64_t start_time = hrt_absolute_time();\n\n\twhile ((hrt_absolute_time() - start_time) < 10000000) {\n\t\tif (_reports->get(&report)) {\n\t\t\t\/** output all objects found **\/\n\t\t\tfor (uint8_t i = 0; i < report.num_targets; i++) {\n\t\t\t\tPX4_INFO(\"sig:%d x:%4.3f y:%4.3f width:%4.3f height:%4.3f\",\n\t\t\t\t\t (int)report.targets[i].signature,\n\t\t\t\t\t (double)report.targets[i].pos_x,\n\t\t\t\t\t (double)report.targets[i].pos_y,\n\t\t\t\t\t (double)report.targets[i].size_x,\n\t\t\t\t\t (double)report.targets[i].size_y);\n\t\t\t}\n\t\t}\n\n\t\t\/** sleep for 0.05 seconds **\/\n\t\tusleep(50000);\n\t}\n\n\treturn OK;\n}\n\n\/** start periodic reads from sensor **\/\nvoid IRLOCK::start()\n{\n\t\/** flush ring and reset state machine **\/\n\t_reports->flush();\n\n\t\/** start work queue cycle **\/\n\tScheduleNow();\n}\n\nvoid IRLOCK::RunImpl()\n{\n\t\/** ignoring failure, if we do, we will be back again right away... **\/\n\tread_device();\n\n\t\/** schedule the next cycle **\/\n\tScheduleDelayed(IRLOCK_CONVERSION_INTERVAL_US);\n}\n\nssize_t IRLOCK::read(struct file *filp, char *buffer, size_t buflen)\n{\n\tunsigned count = buflen \/ sizeof(struct irlock_s);\n\tstruct irlock_s *rbuf = reinterpret_cast<struct irlock_s *>(buffer);\n\tint ret = 0;\n\n\tif (count < 1) {\n\t\treturn -ENOSPC;\n\t}\n\n\t\/** try to read **\/\n\twhile (count--) {\n\t\tif (_reports->get(rbuf)) {\n\t\t\tret += sizeof(*rbuf);\n\t\t\t++rbuf;\n\t\t}\n\t}\n\n\treturn ret ? ret : -EAGAIN;\n\n\treturn ret;\n}\n\n\/** sync device to ensure reading starts at new frame*\/\nbool IRLOCK::sync_device()\n{\n\tuint8_t sync_byte;\n\tuint16_t sync_word;\n\n\tif (read_device_word(&sync_word) != OK) {\n\t\treturn false;\n\t}\n\n\tif (sync_word == IRLOCK_RESYNC) {\n\t\ttransfer(nullptr, 0, &sync_byte, 1);\n\n\t\tif (sync_byte == IRLOCK_ADJUST) {\n\t\t\treturn true;\n\t\t}\n\n\t} else if (sync_word == IRLOCK_SYNC) {\n\t\treturn true;\n\t}\n\n\treturn false;\n}\n\n\/** read all available frames from sensor **\/\nint IRLOCK::read_device()\n{\n\t\/** if we sync, then we are starting a new frame, else fail **\/\n\tif (!sync_device()) {\n\t\treturn -ENOTTY;\n\t}\n\n\tstruct irlock_s report;\n\n\treport.timestamp = hrt_absolute_time();\n\n\treport.num_targets = 0;\n\n\twhile (report.num_targets < IRLOCK_OBJECTS_MAX) {\n\t\tif (!sync_device() || read_device_block(&report.targets[report.num_targets]) != OK) {\n\t\t\tbreak;\n\t\t}\n\n\t\treport.num_targets++;\n\t}\n\n\t_reports->force(&report);\n\n\t\/\/ publish over uORB\n\tif (report.num_targets > 0) {\n\t\tirlock_report_s orb_report{};\n\t\torb_report.timestamp = report.timestamp;\n\t\torb_report.signature = report.targets[0].signature;\n\t\torb_report.pos_x = report.targets[0].pos_x;\n\t\torb_report.pos_y = report.targets[0].pos_y;\n\t\torb_report.size_x = report.targets[0].size_x;\n\t\torb_report.size_y = report.targets[0].size_y;\n\n\t\t_irlock_report_topic.publish(orb_report);\n\t}\n\n\treturn OK;\n}\n\n\/** read a word (two bytes) from sensor **\/\nint IRLOCK::read_device_word(uint16_t *word)\n{\n\tuint8_t bytes[2];\n\tmemset(bytes, 0, sizeof bytes);\n\n\tint status = transfer(nullptr, 0, &bytes[0], 2);\n\t*word = bytes[1] << 8 | bytes[0];\n\n\treturn status;\n}\n\n\/** read a single block (a full frame) from sensor **\/\nint IRLOCK::read_device_block(struct irlock_target_s *block)\n{\n\tuint8_t bytes[12];\n\tmemset(bytes, 0, sizeof bytes);\n\n\tint status = transfer(nullptr, 0, &bytes[0], 12);\n\tuint16_t checksum = bytes[1] << 8 | bytes[0];\n\tuint16_t signature = bytes[3] << 8 | bytes[2];\n\tuint16_t pixel_x = bytes[5] << 8 | bytes[4];\n\tuint16_t pixel_y = bytes[7] << 8 | bytes[6];\n\tuint16_t pixel_size_x = bytes[9] << 8 | bytes[8];\n\tuint16_t pixel_size_y = bytes[11] << 8 | bytes[10];\n\n\t\/** crc check **\/\n\tif (signature + pixel_x + pixel_y + pixel_size_x + pixel_size_y != checksum) {\n\t\t_read_failures++;\n\t\treturn -EIO;\n\t}\n\n\t\/** convert to angles **\/\n\tblock->signature = signature;\n\tblock->pos_x = (pixel_x - IRLOCK_CENTER_X) * IRLOCK_TAN_ANG_PER_PIXEL_X;\n\tblock->pos_y = (pixel_y - IRLOCK_CENTER_Y) * IRLOCK_TAN_ANG_PER_PIXEL_Y;\n\tblock->size_x = pixel_size_x * IRLOCK_TAN_ANG_PER_PIXEL_X;\n\tblock->size_y = pixel_size_y * IRLOCK_TAN_ANG_PER_PIXEL_Y;\n\treturn status;\n}\n\nvoid\nIRLOCK::print_usage()\n{\n\tPRINT_MODULE_USAGE_NAME(\"irlock\", \"driver\");\n\tPRINT_MODULE_USAGE_COMMAND(\"start\");\n\tPRINT_MODULE_USAGE_PARAMS_I2C_SPI_DRIVER(true, false);\n\tPRINT_MODULE_USAGE_PARAMS_I2C_ADDRESS(0x54);\n\tPRINT_MODULE_USAGE_COMMAND(\"test\");\n\tPRINT_MODULE_USAGE_DEFAULT_COMMANDS();\n}\n\nI2CSPIDriverBase *IRLOCK::instantiate(const BusCLIArguments &cli, const BusInstanceIterator &iterator,\n\t\t\t\t int runtime_instance)\n{\n\tIRLOCK *instance = new IRLOCK(iterator.configuredBusOption(), iterator.bus(), cli.bus_frequency, cli.i2c_address);\n\n\tif (instance == nullptr) {\n\t\tPX4_ERR(\"alloc failed\");\n\t\treturn nullptr;\n\t}\n\n\tif (instance->init() != PX4_OK) {\n\t\tdelete instance;\n\t\treturn nullptr;\n\t}\n\n\treturn instance;\n}\nvoid\nIRLOCK::custom_method(const BusCLIArguments &cli)\n{\n\ttest();\n}\n\nextern \"C\" __EXPORT int irlock_main(int argc, char *argv[])\n{\n\tusing ThisDriver = IRLOCK;\n\tBusCLIArguments cli{true, false};\n\tcli.i2c_address = IRLOCK_I2C_ADDRESS;\n\tcli.default_i2c_frequency = 400000;\n\n\tconst char *verb = cli.parseDefaultArguments(argc, argv);\n\n\tif (!verb) {\n\t\tThisDriver::print_usage();\n\t\treturn -1;\n\t}\n\n\tBusInstanceIterator iterator(MODULE_NAME, cli, DRV_SENS_DEVTYPE_IRLOCK);\n\n\tif (!strcmp(verb, \"start\")) {\n\t\treturn ThisDriver::module_start(cli, iterator);\n\t}\n\n\tif (!strcmp(verb, \"stop\")) {\n\t\treturn ThisDriver::module_stop(iterator);\n\t}\n\n\tif (!strcmp(verb, \"status\")) {\n\t\treturn ThisDriver::module_status(iterator);\n\t}\n\n\tif (!strcmp(verb, \"test\")) {\n\t\treturn ThisDriver::module_custom_method(cli, iterator, false);\n\t}\n\n\tThisDriver::print_usage();\n\treturn -1;\n}\n<commit_msg>irlock: remove ioctl(), read(), and RingBuffer<commit_after>\/****************************************************************************\n *\n * Copyright (c) 2012-2015 PX4 Development Team. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in\n * the documentation and\/or other materials provided with the\n * distribution.\n * 3. Neither the name PX4 nor the names of its contributors may be\n * used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS\n * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED\n * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n ****************************************************************************\/\n\n\/**\n * @file irlock.cpp\n * @author Michael Landes\n *\n * Driver for an IR-Lock and Pixy vision sensor connected via I2C.\n *\n * Created on: Nov 12, 2014\n **\/\n\n#include <string.h>\n\n#include <drivers\/device\/i2c.h>\n#include <px4_platform_common\/getopt.h>\n#include <px4_platform_common\/module.h>\n#include <px4_platform_common\/i2c_spi_buses.h>\n#include <uORB\/Publication.hpp>\n#include <uORB\/topics\/irlock_report.h>\n\n\/** Configuration Constants **\/\n#define IRLOCK_I2C_ADDRESS\t\t0x54 \/** 7-bit address (non shifted) **\/\n#define IRLOCK_CONVERSION_INTERVAL_US\t20000U \/** us = 20ms = 50Hz **\/\n\n#define IRLOCK_SYNC\t\t\t0xAA55\n#define IRLOCK_RESYNC\t\t0x5500\n#define IRLOCK_ADJUST\t\t0xAA\n\n#define IRLOCK_RES_X 320\n#define IRLOCK_RES_Y 200\n\n#define IRLOCK_CENTER_X\t\t\t\t(IRLOCK_RES_X\/2)\t\t\t\/\/ the x-axis center pixel position\n#define IRLOCK_CENTER_Y\t\t\t\t(IRLOCK_RES_Y\/2)\t\t\t\/\/ the y-axis center pixel position\n\n#define IRLOCK_FOV_X (60.0f*M_PI_F\/180.0f)\n#define IRLOCK_FOV_Y (35.0f*M_PI_F\/180.0f)\n\n#define IRLOCK_TAN_HALF_FOV_X 0.57735026919f \/\/ tan(0.5 * 60 * pi\/180)\n#define IRLOCK_TAN_HALF_FOV_Y 0.31529878887f \/\/ tan(0.5 * 35 * pi\/180)\n\n#define IRLOCK_TAN_ANG_PER_PIXEL_X\t(2*IRLOCK_TAN_HALF_FOV_X\/IRLOCK_RES_X)\n#define IRLOCK_TAN_ANG_PER_PIXEL_Y\t(2*IRLOCK_TAN_HALF_FOV_Y\/IRLOCK_RES_Y)\n\n#define IRLOCK_OBJECTS_MAX\t5\t\/** up to 5 objects can be detected\/reported **\/\n\nstruct irlock_target_s {\n\tuint16_t signature;\t\/** target signature **\/\n\tfloat pos_x;\t\/** x-axis distance from center of image to center of target in units of tan(theta) **\/\n\tfloat pos_y;\t\/** y-axis distance from center of image to center of target in units of tan(theta) **\/\n\tfloat size_x;\t\/** size of target along x-axis in units of tan(theta) **\/\n\tfloat size_y;\t\/** size of target along y-axis in units of tan(theta) **\/\n};\n\n\/** irlock_s structure returned from read calls **\/\nstruct irlock_s {\n\thrt_abstime timestamp; \/** microseconds since system start **\/\n\tuint8_t num_targets;\n\tirlock_target_s targets[IRLOCK_OBJECTS_MAX];\n};\n\nclass IRLOCK : public device::I2C, public I2CSPIDriver<IRLOCK>\n{\npublic:\n\tIRLOCK(I2CSPIBusOption bus_option, const int bus, int bus_frequency, const int address);\n\t~IRLOCK() override = default;\n\n\tstatic I2CSPIDriverBase *instantiate(const BusCLIArguments &cli, const BusInstanceIterator &iterator,\n\t\t\t\t\t int runtime_instance);\n\tstatic void print_usage();\n\n\tint init() override;\n\tint probe() override;\n\tvoid print_status() override;\n\n\t\/** read from device and schedule next read **\/\n\tvoid\t\tRunImpl();\nprivate:\n\n\t\/** low level communication with sensor **\/\n\tint \t\tread_device();\n\tbool \t\tsync_device();\n\tint \t\tread_device_word(uint16_t *word);\n\tint \t\tread_device_block(struct irlock_target_s *block);\n\n\t\/** internal variables **\/\n\tuint32_t _read_failures{0};\n\n\tuORB::Publication<irlock_report_s> _irlock_report_topic{ORB_ID(irlock_report)};\n};\n\nIRLOCK::IRLOCK(I2CSPIBusOption bus_option, const int bus, int bus_frequency, const int address) :\n\tI2C(DRV_SENS_DEVTYPE_IRLOCK, MODULE_NAME, bus, address, bus_frequency),\n\tI2CSPIDriver(MODULE_NAME, px4::device_bus_to_wq(get_device_id()), bus_option, bus, address)\n{\n}\n\nint IRLOCK::init()\n{\n\t\/** initialise I2C bus **\/\n\tint ret = I2C::init();\n\n\tif (ret != OK) {\n\t\treturn ret;\n\t}\n\n\tScheduleNow();\n\treturn OK;\n}\n\nint IRLOCK::probe()\n{\n\t\/*\n\t * IRLock defaults to sending 0x00 when there is no block\n\t * data to return, so really all we can do is check to make\n\t * sure a transfer completes successfully.\n\t **\/\n\tuint8_t byte;\n\n\tif (transfer(nullptr, 0, &byte, 1) != OK) {\n\t\treturn -EIO;\n\t}\n\n\treturn OK;\n}\n\nvoid IRLOCK::print_status()\n{\n\tPX4_INFO(\"read errors: %lu\", (unsigned long)_read_failures);\n}\n\nvoid IRLOCK::RunImpl()\n{\n\t\/** ignoring failure, if we do, we will be back again right away... **\/\n\tread_device();\n\n\tScheduleDelayed(IRLOCK_CONVERSION_INTERVAL_US);\n}\n\nbool IRLOCK::sync_device()\n{\n\tuint8_t sync_byte;\n\tuint16_t sync_word;\n\n\tif (read_device_word(&sync_word) != OK) {\n\t\treturn false;\n\t}\n\n\tif (sync_word == IRLOCK_RESYNC) {\n\t\ttransfer(nullptr, 0, &sync_byte, 1);\n\n\t\tif (sync_byte == IRLOCK_ADJUST) {\n\t\t\treturn true;\n\t\t}\n\n\t} else if (sync_word == IRLOCK_SYNC) {\n\t\treturn true;\n\t}\n\n\treturn false;\n}\n\nint IRLOCK::read_device()\n{\n\t\/** if we sync, then we are starting a new frame, else fail **\/\n\tif (!sync_device()) {\n\t\treturn -ENOTTY;\n\t}\n\n\tirlock_s report{};\n\treport.timestamp = hrt_absolute_time();\n\treport.num_targets = 0;\n\n\twhile (report.num_targets < IRLOCK_OBJECTS_MAX) {\n\t\tif (!sync_device() || read_device_block(&report.targets[report.num_targets]) != OK) {\n\t\t\tbreak;\n\t\t}\n\n\t\treport.num_targets++;\n\t}\n\n\t\/\/ publish over uORB\n\tif (report.num_targets > 0) {\n\t\tirlock_report_s orb_report{};\n\t\torb_report.timestamp = report.timestamp;\n\t\torb_report.signature = report.targets[0].signature;\n\t\torb_report.pos_x = report.targets[0].pos_x;\n\t\torb_report.pos_y = report.targets[0].pos_y;\n\t\torb_report.size_x = report.targets[0].size_x;\n\t\torb_report.size_y = report.targets[0].size_y;\n\n\t\t_irlock_report_topic.publish(orb_report);\n\t}\n\n\treturn OK;\n}\n\nint IRLOCK::read_device_word(uint16_t *word)\n{\n\tuint8_t bytes[2] {};\n\n\tint status = transfer(nullptr, 0, &bytes[0], 2);\n\t*word = bytes[1] << 8 | bytes[0];\n\n\treturn status;\n}\n\nint IRLOCK::read_device_block(irlock_target_s *block)\n{\n\tuint8_t bytes[12];\n\tmemset(bytes, 0, sizeof bytes);\n\n\tint status = transfer(nullptr, 0, &bytes[0], 12);\n\tuint16_t checksum = bytes[1] << 8 | bytes[0];\n\tuint16_t signature = bytes[3] << 8 | bytes[2];\n\tuint16_t pixel_x = bytes[5] << 8 | bytes[4];\n\tuint16_t pixel_y = bytes[7] << 8 | bytes[6];\n\tuint16_t pixel_size_x = bytes[9] << 8 | bytes[8];\n\tuint16_t pixel_size_y = bytes[11] << 8 | bytes[10];\n\n\t\/** crc check **\/\n\tif (signature + pixel_x + pixel_y + pixel_size_x + pixel_size_y != checksum) {\n\t\t_read_failures++;\n\t\treturn -EIO;\n\t}\n\n\t\/** convert to angles **\/\n\tblock->signature = signature;\n\tblock->pos_x = (pixel_x - IRLOCK_CENTER_X) * IRLOCK_TAN_ANG_PER_PIXEL_X;\n\tblock->pos_y = (pixel_y - IRLOCK_CENTER_Y) * IRLOCK_TAN_ANG_PER_PIXEL_Y;\n\tblock->size_x = pixel_size_x * IRLOCK_TAN_ANG_PER_PIXEL_X;\n\tblock->size_y = pixel_size_y * IRLOCK_TAN_ANG_PER_PIXEL_Y;\n\treturn status;\n}\n\nvoid IRLOCK::print_usage()\n{\n\tPRINT_MODULE_USAGE_NAME(\"irlock\", \"driver\");\n\tPRINT_MODULE_USAGE_COMMAND(\"start\");\n\tPRINT_MODULE_USAGE_PARAMS_I2C_SPI_DRIVER(true, false);\n\tPRINT_MODULE_USAGE_PARAMS_I2C_ADDRESS(0x54);\n\tPRINT_MODULE_USAGE_DEFAULT_COMMANDS();\n}\n\nI2CSPIDriverBase *IRLOCK::instantiate(const BusCLIArguments &cli, const BusInstanceIterator &iterator,\n\t\t\t\t int runtime_instance)\n{\n\tIRLOCK *instance = new IRLOCK(iterator.configuredBusOption(), iterator.bus(), cli.bus_frequency, cli.i2c_address);\n\n\tif (instance == nullptr) {\n\t\tPX4_ERR(\"alloc failed\");\n\t\treturn nullptr;\n\t}\n\n\tif (instance->init() != PX4_OK) {\n\t\tdelete instance;\n\t\treturn nullptr;\n\t}\n\n\treturn instance;\n}\n\nextern \"C\" __EXPORT int irlock_main(int argc, char *argv[])\n{\n\tusing ThisDriver = IRLOCK;\n\tBusCLIArguments cli{true, false};\n\tcli.i2c_address = IRLOCK_I2C_ADDRESS;\n\tcli.default_i2c_frequency = 400000;\n\n\tconst char *verb = cli.parseDefaultArguments(argc, argv);\n\n\tif (!verb) {\n\t\tThisDriver::print_usage();\n\t\treturn -1;\n\t}\n\n\tBusInstanceIterator iterator(MODULE_NAME, cli, DRV_SENS_DEVTYPE_IRLOCK);\n\n\tif (!strcmp(verb, \"start\")) {\n\t\treturn ThisDriver::module_start(cli, iterator);\n\t}\n\n\tif (!strcmp(verb, \"stop\")) {\n\t\treturn ThisDriver::module_stop(iterator);\n\t}\n\n\tif (!strcmp(verb, \"status\")) {\n\t\treturn ThisDriver::module_status(iterator);\n\t}\n\n\tThisDriver::print_usage();\n\treturn -1;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"controlwindow.h\"\r\n#include \"ui_controlwindow.h\"\r\n\r\n#include <QCoreApplication>\r\n#include <QSound>\r\n#include <iostream>\r\n\r\n#define MapSize 1\r\n#define VisionRange 2\r\n#define NHexonInit 3\r\n#define NObstacleInit 4\r\n\r\n\/\/ Constructor for ControlWindow\r\n\/\/ Generates interactive elements, and attaches signals\r\nControlWindow::ControlWindow(QWidget *parent) :\r\n QMainWindow(parent),\r\n ui(new Ui::ControlWindow)\r\n{\r\n ui->setupUi(this);\r\n\r\n QPushButton * startButton = new QPushButton(\"Start\",this);\r\n startButton->setGeometry(QRect(QPoint(100,100),QSize(50,25)));\r\n\r\n connect(startButton, SIGNAL(clicked()), this, SLOT(on_startButton_clicked()));\r\n \/\/connect(&timer, SIGNAL(timeout()), &scene, SLOT(tick_update()));\r\n\r\n inputs[MapSize] = new InputWidget(this,100,150,10,999,20,\"Map Radius\");\r\n inputs[VisionRange] = new InputWidget(this,100,200,0,9,2,\"Vision Range\");\r\n inputs[NHexonInit] = new InputWidget(this,200,150,0,999,50,\"Starting Hexons\");\r\n inputs[NObstacleInit] = new InputWidget(this,200,200,0,999,100,\"Starting Obstacles\");\r\n}\r\n\r\n\/\/ Destructor\r\n\/\/ Stops timer, and deletes UI before exiting\r\nControlWindow::~ControlWindow()\r\n{\r\n timer.stop();\r\n delete ui;\r\n}\r\n\r\n\/\/ Slot for when start button is pressed\r\n\/\/ Sets up view, hex_map, and timer\r\nvoid ControlWindow::on_startButton_clicked()\r\n{\r\n \/\/ Set Global variables - #from control window values\r\n set_map_size(inputs[MapSize]->value()); \/\/ radius of map\r\n set_visibility(inputs[VisionRange]->value()); \/\/ visibility range of Hexons\r\n int size = get_map_size();\r\n\r\n \/\/ Scaled size of scene\r\n scene.setSceneRect(-50*size, -50*size, 100*size, 100*size);\r\n\r\n scene.setItemIndexMethod(QGraphicsScene::NoIndex);\r\n\r\n srand(0);\r\n \/\/ Generate random Hexons\r\n for (int i = 0; i < inputs[NHexonInit]->value(); i++) \/\/ #from control window value\r\n {\r\n bool s = false;\r\n while (!s)\r\n {\r\n \/\/ generate random position in hexagon #make new function?\r\n int a = (rand() % (2*size+1)) - size;\r\n int b = (rand() % (2*size-std::abs(a)+1)) - size;\r\n if (a < 0)\r\n {\r\n b = b - a;\r\n }\r\n cube h = {a,b,-a-b};\r\n \/\/ add hexon to map\r\n s = hex_map.AddHexItem(new Hexon(h), &scene);\r\n }\r\n }\r\n\r\n for (int i = 0; i < inputs[NObstacleInit]->value(); i++) \/\/ #from control window value\r\n {\r\n bool s = false;\r\n while (!s)\r\n {\r\n \/\/ generate random position in hexagon #make new function?\r\n int a = (rand() % (2*size+1)) - size;\r\n int b = (rand() % (2*size-std::abs(a)+1)) - size;\r\n if (a < 0)\r\n {\r\n b = b - a;\r\n }\r\n cube h = {a,b,-a-b};\r\n \/\/ add obstacle to map\r\n s = hex_map.AddHexItem(new Obstacle(h), &scene);\r\n }\r\n }\r\n\r\n \/\/ attach scene to view, and adjust settings\r\n view.setScene(&scene);\r\n view.setRenderHint(QPainter::Antialiasing);\r\n view.setBackgroundBrush(Qt::black);\r\n\r\n view.setCacheMode(QGraphicsView::CacheBackground);\r\n view.setViewportUpdateMode(QGraphicsView::BoundingRectViewportUpdate); \/\/ FullViewportUpdate\r\n view.setDragMode(QGraphicsView::ScrollHandDrag);\r\n\r\n view.setWindowTitle(QT_TRANSLATE_NOOP(QGraphicsView, \"Hexons\"));\r\n view.resize(800, 800);\r\n\r\n \/\/ display view (new window)\r\n view.showMaximized();\r\n\r\n \/\/ play music\r\n QSound music(\"song_of_storms5.wav\");\r\n \/\/music.play(\"song_of_storms5.wav\");\r\n music.play(\"lost_woods.wav\");\r\n\r\n \/\/ connect timer to update function\r\n connect(&timer, SIGNAL(timeout()), this, SLOT(tick_update()));\r\n \/\/ start timer with msec milliseconds\r\n timer.start(1000\/2);\r\n}\r\n\r\n\/\/ Slot for timer tick\r\n\/\/ runs map update\r\nvoid ControlWindow::tick_update()\r\n{\r\n hex_map.map_update();\r\n return;\r\n}\r\n<commit_msg>Fixed music file paths<commit_after>#include \"controlwindow.h\"\r\n#include \"ui_controlwindow.h\"\r\n\r\n#include <QCoreApplication>\r\n#include <QSound>\r\n#include <iostream>\r\n\r\n#define MapSize 1\r\n#define VisionRange 2\r\n#define NHexonInit 3\r\n#define NObstacleInit 4\r\n\r\n\/\/ Constructor for ControlWindow\r\n\/\/ Generates interactive elements, and attaches signals\r\nControlWindow::ControlWindow(QWidget *parent) :\r\n QMainWindow(parent),\r\n ui(new Ui::ControlWindow)\r\n{\r\n ui->setupUi(this);\r\n\r\n QPushButton * startButton = new QPushButton(\"Start\",this);\r\n startButton->setGeometry(QRect(QPoint(100,100),QSize(50,25)));\r\n\r\n connect(startButton, SIGNAL(clicked()), this, SLOT(on_startButton_clicked()));\r\n \/\/connect(&timer, SIGNAL(timeout()), &scene, SLOT(tick_update()));\r\n\r\n inputs[MapSize] = new InputWidget(this,100,150,10,999,20,\"Map Radius\");\r\n inputs[VisionRange] = new InputWidget(this,100,200,0,9,2,\"Vision Range\");\r\n inputs[NHexonInit] = new InputWidget(this,200,150,0,999,50,\"Starting Hexons\");\r\n inputs[NObstacleInit] = new InputWidget(this,200,200,0,999,100,\"Starting Obstacles\");\r\n}\r\n\r\n\/\/ Destructor\r\n\/\/ Stops timer, and deletes UI before exiting\r\nControlWindow::~ControlWindow()\r\n{\r\n timer.stop();\r\n delete ui;\r\n}\r\n\r\n\/\/ Slot for when start button is pressed\r\n\/\/ Sets up view, hex_map, and timer\r\nvoid ControlWindow::on_startButton_clicked()\r\n{\r\n \/\/ Set Global variables - #from control window values\r\n set_map_size(inputs[MapSize]->value()); \/\/ radius of map\r\n set_visibility(inputs[VisionRange]->value()); \/\/ visibility range of Hexons\r\n int size = get_map_size();\r\n\r\n \/\/ Scaled size of scene\r\n scene.setSceneRect(-50*size, -50*size, 100*size, 100*size);\r\n\r\n scene.setItemIndexMethod(QGraphicsScene::NoIndex);\r\n\r\n srand(0);\r\n \/\/ Generate random Hexons\r\n for (int i = 0; i < inputs[NHexonInit]->value(); i++) \/\/ #from control window value\r\n {\r\n bool s = false;\r\n while (!s)\r\n {\r\n \/\/ generate random position in hexagon #make new function?\r\n int a = (rand() % (2*size+1)) - size;\r\n int b = (rand() % (2*size-std::abs(a)+1)) - size;\r\n if (a < 0)\r\n {\r\n b = b - a;\r\n }\r\n cube h = {a,b,-a-b};\r\n \/\/ add hexon to map\r\n s = hex_map.AddHexItem(new Hexon(h), &scene);\r\n }\r\n }\r\n\r\n for (int i = 0; i < inputs[NObstacleInit]->value(); i++) \/\/ #from control window value\r\n {\r\n bool s = false;\r\n while (!s)\r\n {\r\n \/\/ generate random position in hexagon #make new function?\r\n int a = (rand() % (2*size+1)) - size;\r\n int b = (rand() % (2*size-std::abs(a)+1)) - size;\r\n if (a < 0)\r\n {\r\n b = b - a;\r\n }\r\n cube h = {a,b,-a-b};\r\n \/\/ add obstacle to map\r\n s = hex_map.AddHexItem(new Obstacle(h), &scene);\r\n }\r\n }\r\n\r\n \/\/ attach scene to view, and adjust settings\r\n view.setScene(&scene);\r\n view.setRenderHint(QPainter::Antialiasing);\r\n view.setBackgroundBrush(Qt::black);\r\n\r\n view.setCacheMode(QGraphicsView::CacheBackground);\r\n view.setViewportUpdateMode(QGraphicsView::BoundingRectViewportUpdate); \/\/ FullViewportUpdate\r\n view.setDragMode(QGraphicsView::ScrollHandDrag);\r\n\r\n view.setWindowTitle(QT_TRANSLATE_NOOP(QGraphicsView, \"Hexons\"));\r\n view.resize(800, 800);\r\n\r\n \/\/ display view (new window)\r\n view.showMaximized();\r\n\r\n \/\/ play music\r\n QSound music(\"..\/Hexons\/song_of_storms5.wav\");\r\n \/\/music.play(\"..\/Hexons\/song_of_storms5.wav\");\r\n music.play(\"..\/Hexons\/lost_woods.wav\");\r\n\r\n \/\/ connect timer to update function\r\n connect(&timer, SIGNAL(timeout()), this, SLOT(tick_update()));\r\n \/\/ start timer with msec milliseconds\r\n timer.start(1000\/2);\r\n}\r\n\r\n\/\/ Slot for timer tick\r\n\/\/ runs map update\r\nvoid ControlWindow::tick_update()\r\n{\r\n hex_map.map_update();\r\n return;\r\n}\r\n<|endoftext|>"} {"text":"<commit_before>\/\/ This file is part of the dune-gdt project:\n\/\/ http:\/\/users.dune-project.org\/projects\/dune-gdt\n\/\/ Copyright holders: Felix Schindler\n\/\/ License: BSD 2-Clause License (http:\/\/opensource.org\/licenses\/BSD-2-Clause)\n\n#ifndef DUNE_GDT_TEST_HMM_DISCRETIZATION_HH\n#define DUNE_GDT_TEST_HMM_DISCRETIZATION_HH\n\n#if !HAVE_DUNE_PDELAB\n# error \"This one requires dune-pdelab!\"\n#endif\n\n#include <memory>\n#include <vector>\n#include <limits>\n#include <complex>\n#include <type_traits>\n\n#include <dune\/common\/timer.hh>\n\n#include <dune\/stuff\/common\/memory.hh>\n#include <dune\/stuff\/grid\/boundaryinfo.hh>\n#include <dune\/stuff\/grid\/information.hh>\n#include <dune\/stuff\/la\/container.hh>\n#include <dune\/stuff\/la\/solver.hh>\n#include <dune\/stuff\/functions\/interfaces.hh>\n#include <dune\/stuff\/functions\/combined.hh>\n#include <dune\/stuff\/functions\/constant.hh>\n\n#include <dune\/gdt\/spaces\/nedelec\/pdelab.hh>\n#include <dune\/gdt\/localevaluation\/hmm.hh>\n#include <dune\/gdt\/localoperator\/codim0.hh>\n#include <dune\/gdt\/assembler\/local\/codim0.hh>\n#include <dune\/gdt\/assembler\/system.hh>\n#include <dune\/gdt\/functionals\/l2.hh>\n#include <dune\/gdt\/spaces\/constraints.hh>\n\ntemplate< class MacroGridViewType, class CellGridViewType, int polynomialOrder >\nclass HMMDiscretization\n{\npublic:\n typedef typename MacroGridViewType::ctype MacroDomainFieldType;\n static const size_t dimDomain = MacroGridViewType::dimension;\n static const size_t dimRange = dimDomain;\n static const unsigned int polOrder = polynomialOrder;\n\n typedef Dune::Stuff::Grid::BoundaryInfoInterface< typename MacroGridViewType::Intersection > BoundaryInfoType;\n typedef Dune::Stuff::LocalizableFunctionInterface< typename MacroGridViewType::template Codim< 0 >::Entity, DomainFieldType, dimDomain, double, dimRange > Vectorfct;\n typedef Dune::Stuff::LocalizableFunctionInterface< typename MacroGridViewType::template Codim< 0 >::Entity, DomainFieldType, dimDomain, double, 1 > ScalarFct;\n\n typedef Dune::Stuff::LA::Container< double, Dune::Stuff::LA::ChooseBackend::eigen_sparse>::MatrixType MatrixType;\n typedef Dune::Stuff::LA::Container< double, Dune::Stuff::LA::ChooseBackend::eigen_sparse>::VectorType VectorType;\n\n typedef Dune::GDT::Spaces::Nedelec::PdelabBased< MacroGridViewType, polOrder, double, dimRange > SpaceType;\n\n typedef Dune::GDT::ConstDiscreteFunction < SpaceType, VectorType > ConstDiscreteFunctionType;\n\n\n HMMDiscretization(const MacroGridViewType& macrogridview,\n const CellGridViewType& cellgridview,\n const BoundaryInfoType& info,\n const ScalarFct& mu,\n const ScalarFct& kappa,\n const Vectorfct& source,\n const ScalarFct& divparam)\n : space_(macrogridview)\n , cellgridview_(cellgridview)\n , bdry_info_(info)\n , mu_(mu)\n , kappa_(kappa)\n , source_(source)\n , divparam_(divparam)\n , is_assembled_(false)\n , system_matrix_(0,0)\n , rhs_vector_(0)\n {}\n\n const SpaceType& space() const\n {\n return space_;\n }\n\n VectorType create_vector() const\n {\n return VectorType(space_.mapper().size());\n }\n\n void assemble() const\n {\n using namespace Dune;\n using namespace Dune::GDT;\n if (!is_assembled_) {\n Stuff::LA::SparsityPatternDefault sparsity_pattern = space_.compute_volume_pattern();\n system_matrix_ = MatrixType(space_.mapper().size(), space_.mapper().size(), sparsity_pattern);\n rhs_vector_ = VectorType(space_.mapper().size());\n SystemAssembler< SpaceType > walker(space_);\n\n \/\/rhs\n auto source_functional = Functionals::make_l2_volume(source_, rhs_vector_, space_);\n walker.add(*source_functional);\n\n \/\/lhs\n typedef LocalOperator::Codim0Integral< LocalEvaluation::HMMCurlcurl< ScalarFct, CellGridViewType, polOrder > > HMMcurlOp;\n const HMMcurlOp hmmcurl(mu_, divparam_, cellgridview_);\n const LocalAssembler::Codim0Matrix< HMMcurlOp > curlassembler(hmmcurl);\n walker.add(curlassembler, system_matrix_);\n typedef LocalOperator::Codim0Integral< LocalEvaluation::HMMIdentity< ScalarFct, CellGridViewType, polOrder > > HMMidOp;\n const HMMidOp hmmid(kappa_, cellgridview_);\n const LocalAssembler::Codim0Matrix< HMMidOp > idassembler(hmmid);\n walker.add(idassembler, system_matrix_);\n\n \/\/apply the homogenous (!) Dirichlet constraints on the macro grid\n Spaces::DirichletConstraints< typename MacroGridViewType::Intersection >\n dirichlet_constraints(bdry_info_, space_.mapper().size());\n walker.add(dirichlet_constraints);\n walker.assemble();\n dirichlet_constraints.apply(system_matrix_, rhs_vector_);\n\n is_assembled_ = true;\n }\n } \/\/assemble\n\n bool assembled() const\n {\n return is_assembled_;\n }\n\n\n const MatrixType& system_matrix() const\n {\n return system_matrix_;\n }\n\n\n const VectorType& rhs_vector() const\n {\n return rhs_vector_;\n }\n\n void solve(VectorType& solution) const\n {\n if (!is_assembled_)\n assemble();\n\n Dune::Stuff::LA::Solver< MatrixType > solver(system_matrix_);\n solver.apply(rhs_vector_, solution, \"bicgstab.diagonal\");\n } \/\/solve\n\nprivate:\n const SpaceType& space_;\n const CellGridViewType& cellgridview_;\n const BoundaryInfoType& bdry_info_;\n const ScalarFct& mu_;\n const ScalarFct& kappa_;\n const Vectorfct& source_;\n const ScalarFct& divparam_;\n mutable bool is_assembled_;\n mutable MatrixType system_matrix_;\n mutable VectorType rhs_vector_;\n};\n\n#endif \/\/ DUNE_GDT_TEST_HMM_DISCRETIZATION_HH\n<commit_msg>[test\/hmm-discretization] minor updates, fix typos<commit_after>\/\/ This file is part of the dune-gdt project:\n\/\/ http:\/\/users.dune-project.org\/projects\/dune-gdt\n\/\/ Copyright holders: Felix Schindler\n\/\/ License: BSD 2-Clause License (http:\/\/opensource.org\/licenses\/BSD-2-Clause)\n\n#ifndef DUNE_GDT_TEST_HMM_DISCRETIZATION_HH\n#define DUNE_GDT_TEST_HMM_DISCRETIZATION_HH\n\n#if !HAVE_DUNE_PDELAB\n# error \"This one requires dune-pdelab!\"\n#endif\n\n#include <memory>\n#include <vector>\n#include <limits>\n#include <complex>\n#include <type_traits>\n\n#include <dune\/common\/timer.hh>\n\n#include <dune\/stuff\/common\/memory.hh>\n#include <dune\/stuff\/grid\/boundaryinfo.hh>\n#include <dune\/stuff\/grid\/information.hh>\n#include <dune\/stuff\/la\/container.hh>\n#include <dune\/stuff\/la\/solver.hh>\n#include <dune\/stuff\/functions\/interfaces.hh>\n#include <dune\/stuff\/functions\/combined.hh>\n#include <dune\/stuff\/functions\/constant.hh>\n\n#include <dune\/gdt\/spaces\/nedelec\/pdelab.hh>\n#include <dune\/gdt\/localevaluation\/hmm.hh>\n#include <dune\/gdt\/localoperator\/codim0.hh>\n#include <dune\/gdt\/assembler\/local\/codim0.hh>\n#include <dune\/gdt\/assembler\/system.hh>\n#include <dune\/gdt\/functionals\/l2.hh>\n#include <dune\/gdt\/spaces\/constraints.hh>\n\ntemplate< class MacroGridViewType, class CellGridViewType, int polynomialOrder >\nclass HMMDiscretization\n{\npublic:\n typedef typename MacroGridViewType::ctype MacroDomainFieldType;\n static const size_t dimDomain = MacroGridViewType::dimension;\n static const size_t dimRange = dimDomain;\n static const unsigned int polOrder = polynomialOrder;\n\n typedef Dune::Stuff::Grid::BoundaryInfoInterface< typename MacroGridViewType::Intersection > BoundaryInfoType;\n typedef Dune::Stuff::LocalizableFunctionInterface< typename MacroGridViewType::template Codim< 0 >::Entity, MacroDomainFieldType, dimDomain, double, dimRange > Vectorfct;\n typedef Dune::Stuff::LocalizableFunctionInterface< typename MacroGridViewType::template Codim< 0 >::Entity, MacroDomainFieldType, dimDomain, double, 1 > ScalarFct;\n\n typedef Dune::Stuff::LA::Container< double, Dune::Stuff::LA::ChooseBackend::eigen_sparse>::MatrixType MatrixType;\n typedef Dune::Stuff::LA::Container< double, Dune::Stuff::LA::ChooseBackend::eigen_sparse>::VectorType VectorType;\n\n typedef Dune::GDT::Spaces::Nedelec::PdelabBased< MacroGridViewType, polOrder, double, dimRange > SpaceType;\n\n typedef Dune::GDT::ConstDiscreteFunction < SpaceType, VectorType > ConstDiscreteFunctionType;\n\n\n HMMDiscretization(const MacroGridViewType& macrogridview,\n const CellGridViewType& cellgridview,\n const BoundaryInfoType& info,\n const ScalarFct& mu,\n const ScalarFct& kappa,\n const Vectorfct& source,\n const ScalarFct& divparam)\n : space_(macrogridview)\n , cellgridview_(cellgridview)\n , bdry_info_(info)\n , mu_(mu)\n , kappa_(kappa)\n , source_(source)\n , divparam_(divparam)\n , is_assembled_(false)\n , system_matrix_(0,0)\n , rhs_vector_(0)\n {}\n\n const SpaceType& space() const\n {\n return space_;\n }\n\n VectorType create_vector() const\n {\n return VectorType(space_.mapper().size());\n }\n\n void assemble() const\n {\n using namespace Dune;\n using namespace Dune::GDT;\n if (!is_assembled_) {\n Stuff::LA::SparsityPatternDefault sparsity_pattern = space_.compute_volume_pattern();\n system_matrix_ = MatrixType(space_.mapper().size(), space_.mapper().size(), sparsity_pattern);\n rhs_vector_ = VectorType(space_.mapper().size());\n SystemAssembler< SpaceType > walker(space_);\n\n \/\/rhs\n auto source_functional = Functionals::make_l2_volume(source_, rhs_vector_, space_);\n walker.add(*source_functional);\n\n \/\/lhs\n typedef LocalOperator::Codim0Integral< LocalEvaluation::HMMCurlcurl< ScalarFct, CellGridViewType, polOrder > > HMMcurlOp;\n const HMMcurlOp hmmcurl(mu_, divparam_, cellgridview_);\n const LocalAssembler::Codim0Matrix< HMMcurlOp > curlassembler(hmmcurl);\n walker.add(curlassembler, system_matrix_);\n typedef LocalOperator::Codim0Integral< LocalEvaluation::HMMIdentity< ScalarFct, CellGridViewType, polOrder > > HMMidOp;\n const HMMidOp hmmid(kappa_, cellgridview_);\n const LocalAssembler::Codim0Matrix< HMMidOp > idassembler(hmmid);\n walker.add(idassembler, system_matrix_);\n\n \/\/apply the homogenous (!) Dirichlet constraints on the macro grid\n Spaces::DirichletConstraints< typename MacroGridViewType::Intersection >\n dirichlet_constraints(bdry_info_, space_.mapper().size());\n walker.add(dirichlet_constraints);\n walker.assemble();\n dirichlet_constraints.apply(system_matrix_, rhs_vector_);\n\n is_assembled_ = true;\n }\n } \/\/assemble\n\n bool assembled() const\n {\n return is_assembled_;\n }\n\n\n const MatrixType& system_matrix() const\n {\n return system_matrix_;\n }\n\n\n const VectorType& rhs_vector() const\n {\n return rhs_vector_;\n }\n\n void solve(VectorType& solution) const\n {\n if (!is_assembled_)\n assemble();\n\n Dune::Stuff::LA::Solver< MatrixType > solver(system_matrix_);\n solver.apply(rhs_vector_, solution, \"bicgstab.diagonal\");\n } \/\/solve\n\nprivate:\n const SpaceType space_;\n const CellGridViewType& cellgridview_;\n const BoundaryInfoType& bdry_info_;\n const ScalarFct& mu_;\n const ScalarFct& kappa_;\n const Vectorfct& source_;\n const ScalarFct& divparam_;\n mutable bool is_assembled_;\n mutable MatrixType system_matrix_;\n mutable VectorType rhs_vector_;\n};\n\n#endif \/\/ DUNE_GDT_TEST_HMM_DISCRETIZATION_HH\n<|endoftext|>"} {"text":"<commit_before>\/******************************************************************************\n * Copyright 2018 The Apollo Authors. All Rights Reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *****************************************************************************\/\n\n#include <cmath>\n#include <iostream>\n\n#include <QPainter>\n#include <QPen>\n\n#include \"arrow.h\"\n#include \"compositeitem.h\"\n\nconstexpr double PI = 3.14159265358979323846264338327950288419716939937510;\nconstexpr double ArrowSize = 10;\n\nArrow::Arrow(CompositeItem *startItem, CompositeItem *endItem,\n QGraphicsItem *parent)\n : QGraphicsLineItem(parent),\n start_item_(startItem),\n end_item_(endItem),\n polygon_() {\n setPen(QPen(Qt::black, 2, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin));\n}\n\nQRectF Arrow::boundingRect() const {\n qreal extra = (pen().width() + 20) \/ 2.0;\n\n return QRectF(line().p1(), QSizeF(line().p2().x() - line().p1().x(),\n line().p2().y() - line().p1().y()))\n .normalized()\n .adjusted(-extra, -extra, extra, extra);\n}\n\nQPainterPath Arrow::shape() const {\n QPainterPath path = QGraphicsLineItem::shape();\n path.addPolygon(polygon_);\n return path;\n}\n\nvoid Arrow::updatePosition() {\n QLineF line(mapFromItem(start_item_, 0, 0), mapFromItem(end_item_, 0, 0));\n setLine(line);\n}\n\nQPointF Arrow::Intersect(const QPolygonF &polygon, const QPointF &point,\n const QLineF &line) {\n QPointF p1 = polygon.first() + point;\n QPointF p2;\n QPointF intersectPoint(0, 0);\n QLineF polyLine;\n for (int i = 1; i < polygon.count(); ++i) {\n p2 = polygon.at(i) + point;\n polyLine = QLineF(p1, p2);\n QLineF::IntersectType intersectType =\n polyLine.intersect(line, &intersectPoint);\n if (intersectType == QLineF::BoundedIntersection) break;\n p1 = p2;\n }\n return intersectPoint;\n}\n\nvoid Arrow::paint(QPainter *painter, const QStyleOptionGraphicsItem *,\n QWidget *) {\n if (start_item_->collidesWithItem(end_item_)) {\n return;\n }\n\n painter->setPen(pen());\n painter->setBrush(pen().color());\n\n QPointF startPoint =\n start_item_->pos() + QPointF(start_item_->boundingRect().width() \/ 2,\n start_item_->boundingRect().height() \/ 2);\n QPointF endPoint =\n end_item_->pos() + QPointF(end_item_->boundingRect().width() \/ 2,\n end_item_->boundingRect().height() \/ 2);\n\n QLineF centerLine(startPoint, endPoint);\n\n endPoint = Intersect(end_item_->polygon(), end_item_->pos(), centerLine);\n startPoint =\n Intersect(start_item_->polygon(), start_item_->pos(), centerLine);\n\n setLine(QLineF(endPoint, startPoint));\n\n double angle = std::acos(line().dx() \/ line().length());\n if (line().dy() >= 0) angle = (PI * 2) - angle;\n\n QPointF arrowP1 = line().p1() + QPointF(std::sin(angle + PI \/ 3) * ArrowSize,\n std::cos(angle + PI \/ 3) * ArrowSize);\n QPointF arrowP2 =\n line().p1() + QPointF(std::sin(angle + PI - PI \/ 3) * ArrowSize,\n std::cos(angle + PI - PI \/ 3) * ArrowSize);\n\n polygon_.clear();\n polygon_ << line().p1() << arrowP1 << arrowP2;\n\n painter->drawLine(line());\n painter->drawPolygon(polygon_);\n}\n<commit_msg>Framework: fix issue<commit_after>\/******************************************************************************\n * Copyright 2018 The Apollo Authors. All Rights Reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *****************************************************************************\/\n\n#include <cmath>\n#include <iostream>\n\n#include <QPainter>\n#include <QPen>\n\n#include \"arrow.h\"\n#include \"composite_item.h\"\n\nconstexpr double PI = 3.14159265358979323846264338327950288419716939937510;\nconstexpr double ArrowSize = 10;\n\nArrow::Arrow(CompositeItem *startItem, CompositeItem *endItem,\n QGraphicsItem *parent)\n : QGraphicsLineItem(parent),\n start_item_(startItem),\n end_item_(endItem),\n polygon_() {\n setPen(QPen(Qt::black, 2, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin));\n}\n\nQRectF Arrow::boundingRect() const {\n qreal extra = (pen().width() + 20) \/ 2.0;\n\n return QRectF(line().p1(), QSizeF(line().p2().x() - line().p1().x(),\n line().p2().y() - line().p1().y()))\n .normalized()\n .adjusted(-extra, -extra, extra, extra);\n}\n\nQPainterPath Arrow::shape() const {\n QPainterPath path = QGraphicsLineItem::shape();\n path.addPolygon(polygon_);\n return path;\n}\n\nvoid Arrow::updatePosition() {\n QLineF line(mapFromItem(start_item_, 0, 0), mapFromItem(end_item_, 0, 0));\n setLine(line);\n}\n\nQPointF Arrow::Intersect(const QPolygonF &polygon, const QPointF &point,\n const QLineF &line) {\n QPointF p1 = polygon.first() + point;\n QPointF p2;\n QPointF intersectPoint(0, 0);\n QLineF polyLine;\n for (int i = 1; i < polygon.count(); ++i) {\n p2 = polygon.at(i) + point;\n polyLine = QLineF(p1, p2);\n QLineF::IntersectType intersectType =\n polyLine.intersect(line, &intersectPoint);\n if (intersectType == QLineF::BoundedIntersection) break;\n p1 = p2;\n }\n return intersectPoint;\n}\n\nvoid Arrow::paint(QPainter *painter, const QStyleOptionGraphicsItem *,\n QWidget *) {\n if (start_item_->collidesWithItem(end_item_)) {\n return;\n }\n\n painter->setPen(pen());\n painter->setBrush(pen().color());\n\n QPointF startPoint =\n start_item_->pos() + QPointF(start_item_->boundingRect().width() \/ 2,\n start_item_->boundingRect().height() \/ 2);\n QPointF endPoint =\n end_item_->pos() + QPointF(end_item_->boundingRect().width() \/ 2,\n end_item_->boundingRect().height() \/ 2);\n\n QLineF centerLine(startPoint, endPoint);\n\n endPoint = Intersect(end_item_->polygon(), end_item_->pos(), centerLine);\n startPoint =\n Intersect(start_item_->polygon(), start_item_->pos(), centerLine);\n\n setLine(QLineF(endPoint, startPoint));\n\n double angle = std::acos(line().dx() \/ line().length());\n if (line().dy() >= 0) angle = (PI * 2) - angle;\n\n QPointF arrowP1 = line().p1() + QPointF(std::sin(angle + PI \/ 3) * ArrowSize,\n std::cos(angle + PI \/ 3) * ArrowSize);\n QPointF arrowP2 =\n line().p1() + QPointF(std::sin(angle + PI - PI \/ 3) * ArrowSize,\n std::cos(angle + PI - PI \/ 3) * ArrowSize);\n\n polygon_.clear();\n polygon_ << line().p1() << arrowP1 << arrowP2;\n\n painter->drawLine(line());\n painter->drawPolygon(polygon_);\n}\n<|endoftext|>"} {"text":"<commit_before>using namespace std;\n#include \"models\/c.h\"\nchar testip[] = \"float x;\\nstatic int z;\\nchar text[64] = \\\"hello\\\"; static int bob(char x, char *harry) { stuff { inside } }\";\n\n\/* Perform rangecheck on getChild before checking the type. Uses -1 as a sentinel \n for the type of an out of range child to simplify calling contexts.\n*\/\nint getChildType(pANTLR3_BASE_TREE parent, int idx)\n{\n int count = parent->getChildCount(parent);\n if( idx<0 || idx>=count )\n return -1;\n pANTLR3_BASE_TREE child = (pANTLR3_BASE_TREE)parent->getChild(parent,idx);\n return child->getType(child);\n}\n\n\nclass TranslationU\n{\npublic:\n list<Decl*> globals;\n list<FuncDef*> functions;\n TranslationU(pANTLR3_BASE_TREE root);\n void processTopLevel(pANTLR3_BASE_TREE node);\n void dump();\n};\n\nTranslationU::TranslationU(pANTLR3_BASE_TREE root)\n{\n if( root->getType(root)==0 ) \n {\n TokList tops = extractChildren(root, 0, -1);\n tmplForeach(list, pANTLR3_BASE_TREE, tok, tops)\n processTopLevel(tok);\n tmplEnd\n }\n else\n processTopLevel(root);\n}\n\nvoid TranslationU::processTopLevel(pANTLR3_BASE_TREE node)\n{\nint type = node->getType(node);\nint count = node->getChildCount(node);\n switch(type)\n {\n case PREPRO:\n \/\/case HASHINCLUDE:\n \/\/case HASHDEFINE:\n \/\/case HASHUNDEF:\n break;\n case DECL:\n try {\n Decl::parse(node,globals);\n }\n catch(BrokenTree bt) {\n printf(\"ERROR(%u): %s\\n\", bt.blame->getLine(bt.blame), bt.explain);\n dumpTree(bt.blame,1);\n }\n break;\n case FUNC:\n try\n {\n FuncDef *f = new FuncDef;\n f->parse(node);\n functions.push_back(f);\n }\n catch(BrokenTree bt) {\n printf(\"ERROR(%u): %s\\n\", bt.blame->getLine(bt.blame), bt.explain);\n dumpTree(bt.blame,1);\n }\n break;\n case SEMI:\n break;\n default:\n printf(\"Unknown Type %u Children %u \", type, count);\n dumpTree(node,1);\n break;\n }\n}\n\nvoid TranslationU::dump()\n{\n tmplForeach(list,Decl*,decl,globals) \n printf(\"Declation: %s is %s\\n\", decl->identifier, decl->type.str().c_str());\n tmplEnd\n tmplForeach(list,FuncDef*,f,functions) \n printf(\"Function: %s is \", f->identifier);\n printf(\"%s <- \", f->retType.str().c_str());\n tmplForeach(list,Decl*,p,f->args)\n printf(\"%s \", p->type.str().c_str());\n printf(\"%s \", p->identifier);\n tmplEnd\n printf(\"\\n\");\n tmplEnd\n}\n\nint main(int argc, char **argv)\n{\npANTLR3_INPUT_STREAM ip;\npANTLR3_COMMON_TOKEN_STREAM tokens;\npcInCLexer lex;\npcInCParser parser;\ncInCParser_translationUnit_return retVal;\n\n if( argc==1 )\n ip = antlr3NewAsciiStringInPlaceStream((uint8_t*)testip, strlen(testip), NULL);\n else\n ip = antlr3AsciiFileStreamNew((pANTLR3_UINT8)argv[1]);\n \/\/ Todo: error checking for IO errors !\n lex = cInCLexerNew(ip);\n tokens = antlr3CommonTokenStreamSourceNew(ANTLR3_SIZE_HINT, TOKENSOURCE(lex));\n parser = cInCParserNew(tokens);\n retVal = parser->translationUnit(parser);\n\nTranslationU model = TranslationU(retVal.tree);\n model.dump();\n dumpTree(retVal.tree,0);\n\n}\n<commit_msg>Missing seek interface.<commit_after>using namespace std;\n#include \"models\/c.h\"\nchar testip[] = \"float x;\\nstatic int z;\\nchar text[64] = \\\"hello\\\"; static int bob(char x, char *harry) { stuff { inside } }\";\n\n\/* Perform rangecheck on getChild before checking the type. Uses -1 as a sentinel \n for the type of an out of range child to simplify calling contexts.\n*\/\nint getChildType(pANTLR3_BASE_TREE parent, int idx)\n{\n int count = parent->getChildCount(parent);\n if( idx<0 || idx>=count )\n return -1;\n pANTLR3_BASE_TREE child = (pANTLR3_BASE_TREE)parent->getChild(parent,idx);\n return child->getType(child);\n}\n\n\nclass TranslationU\n{\npublic:\n list<Decl*> globals;\n list<FuncDef*> functions;\n TranslationU(pANTLR3_BASE_TREE root);\n void processTopLevel(pANTLR3_BASE_TREE node);\n void dump();\n};\n\nTranslationU::TranslationU(pANTLR3_BASE_TREE root)\n{\n if( root->getType(root)==0 ) \n {\n TokList tops = extractChildren(root, 0, -1);\n tmplForeach(list, pANTLR3_BASE_TREE, tok, tops)\n processTopLevel(tok);\n tmplEnd\n }\n else\n processTopLevel(root);\n}\n\nvoid TranslationU::processTopLevel(pANTLR3_BASE_TREE node)\n{\nint type = node->getType(node);\nint count = node->getChildCount(node);\n switch(type)\n {\n case PREPRO:\n \/\/case HASHINCLUDE:\n \/\/case HASHDEFINE:\n \/\/case HASHUNDEF:\n break;\n case DECL:\n try {\n Decl::parse(node,globals);\n }\n catch(BrokenTree bt) {\n printf(\"ERROR(%u): %s\\n\", bt.blame->getLine(bt.blame), bt.explain);\n dumpTree(bt.blame,1);\n }\n break;\n case FUNC:\n try\n {\n FuncDef *f = new FuncDef;\n f->parse(node);\n functions.push_back(f);\n }\n catch(BrokenTree bt) {\n printf(\"ERROR(%u): %s\\n\", bt.blame->getLine(bt.blame), bt.explain);\n dumpTree(bt.blame,1);\n }\n break;\n case SEMI:\n break;\n default:\n printf(\"Unknown Type %u Children %u \", type, count);\n dumpTree(node,1);\n break;\n }\n}\n\nvoid TranslationU::dump()\n{\n tmplForeach(list,Decl*,decl,globals) \n printf(\"Declation: %s is %s\\n\", decl->identifier, decl->type.str().c_str());\n tmplEnd\n tmplForeach(list,FuncDef*,f,functions) \n printf(\"Function: %s is \", f->identifier);\n printf(\"%s <- \", f->retType.str().c_str());\n tmplForeach(list,Decl*,p,f->args)\n printf(\"%s \", p->type.str().c_str());\n printf(\"%s \", p->identifier);\n tmplEnd\n printf(\"\\n\");\n tmplEnd\n}\n\nint main(int argc, char **argv)\n{\npANTLR3_INPUT_STREAM ip;\npANTLR3_COMMON_TOKEN_STREAM tokens;\npcInCLexer lex;\npcInCParser parser;\ncInCParser_translationUnit_return retVal;\ncInCParser_declaration_return retVal2;\n\n if( argc==1 )\n ip = antlr3NewAsciiStringInPlaceStream((uint8_t*)testip, strlen(testip), NULL);\n else\n ip = antlr3AsciiFileStreamNew((pANTLR3_UINT8)argv[1]);\n \/\/ Todo: error checking for IO errors !\n lex = cInCLexerNew(ip);\n tokens = antlr3CommonTokenStreamSourceNew(ANTLR3_SIZE_HINT, TOKENSOURCE(lex));\n printf(\"%u\\n\",tokens->p);\n parser = cInCParserNew(tokens);\n retVal = parser->translationUnit(parser);\n tokens->p = 0;\n retVal2 = parser->declaration(parser);\n dumpTree(retVal2.tree,0);\n\nTranslationU model = TranslationU(retVal.tree);\n model.dump();\n dumpTree(retVal.tree,0);\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ License: Apache 2.0. See LICENSE file in root directory.\n\/\/ Copyright(c) 2016 Intel Corporation. All Rights Reserved.\n\n#include <mutex>\n#include <chrono>\n#include <vector>\n#include <iterator>\n#include <cstddef>\n\n#include \"device.h\"\n#include \"context.h\"\n#include \"image.h\"\n#include \"metadata-parser.h\"\n\n#include \"ds5-nonmonochrome.h\"\n#include \"ds5-private.h\"\n#include \"ds5-options.h\"\n#include \"ds5-timestamp.h\"\n\nnamespace librealsense\n{\n ds5_nonmonochrome::ds5_nonmonochrome(std::shared_ptr<context> ctx,\n const platform::backend_device_group& group)\n : device(ctx, group), ds5_device(ctx, group)\n {\n using namespace ds;\n\n auto pid = group.uvc_devices.front().pid;\n if ((_fw_version >= firmware_version(\"5.5.8.0\")) && (pid != RS_USB2_PID))\n {\n get_depth_sensor().register_option(RS2_OPTION_ENABLE_AUTO_WHITE_BALANCE,\n std::make_shared<uvc_xu_option<uint8_t>>(get_depth_sensor(),\n depth_xu,\n DS5_ENABLE_AUTO_WHITE_BALANCE,\n \"Enable Auto White Balance\"));\n\n \/\/ RS400 rolling-shutter Skus allow to get low-quality color image from the same viewport as the depth\n get_depth_sensor().register_pixel_format(pf_uyvyl);\n get_depth_sensor().register_pixel_format(pf_rgb888);\n get_depth_sensor().register_pixel_format(pf_w10);\n }\n\n get_depth_sensor().unregister_option(RS2_OPTION_EMITTER_ON_OFF);\n\n if ((_fw_version >= firmware_version(\"5.9.13.6\") &&\n _fw_version < firmware_version(\"5.9.15.1\")))\n {\n get_depth_sensor().register_option(RS2_OPTION_INTER_CAM_SYNC_MODE,\n std::make_shared<external_sync_mode>(*_hw_monitor));\n }\n }\n}\n<commit_msg>Disable Auto WB depth control for D465<commit_after>\/\/ License: Apache 2.0. See LICENSE file in root directory.\n\/\/ Copyright(c) 2016 Intel Corporation. All Rights Reserved.\n\n#include <mutex>\n#include <chrono>\n#include <vector>\n#include <iterator>\n#include <cstddef>\n\n#include \"device.h\"\n#include \"context.h\"\n#include \"image.h\"\n#include \"metadata-parser.h\"\n\n#include \"ds5-nonmonochrome.h\"\n#include \"ds5-private.h\"\n#include \"ds5-options.h\"\n#include \"ds5-timestamp.h\"\n\nnamespace librealsense\n{\n ds5_nonmonochrome::ds5_nonmonochrome(std::shared_ptr<context> ctx,\n const platform::backend_device_group& group)\n : device(ctx, group), ds5_device(ctx, group)\n {\n using namespace ds;\n\n auto pid = group.uvc_devices.front().pid;\n if ((_fw_version >= firmware_version(\"5.5.8.0\")) && (!val_in_range(pid, { RS_USB2_PID, RS465_PID })))\n {\n get_depth_sensor().register_option(RS2_OPTION_ENABLE_AUTO_WHITE_BALANCE,\n std::make_shared<uvc_xu_option<uint8_t>>(get_depth_sensor(),\n depth_xu,\n DS5_ENABLE_AUTO_WHITE_BALANCE,\n \"Enable Auto White Balance\"));\n\n \/\/ RS400 rolling-shutter SKUs allow to get low-quality color image from the same viewport as the depth\n get_depth_sensor().register_pixel_format(pf_uyvyl);\n get_depth_sensor().register_pixel_format(pf_rgb888);\n get_depth_sensor().register_pixel_format(pf_w10);\n }\n\n get_depth_sensor().unregister_option(RS2_OPTION_EMITTER_ON_OFF);\n\n if ((_fw_version >= firmware_version(\"5.9.13.6\") &&\n _fw_version < firmware_version(\"5.9.15.1\")))\n {\n get_depth_sensor().register_option(RS2_OPTION_INTER_CAM_SYNC_MODE,\n std::make_shared<external_sync_mode>(*_hw_monitor));\n }\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright 2017 The Cartographer Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include <fstream>\n#include <iostream>\n#include <map>\n#include <set>\n#include <string>\n\n#include \"cartographer\/common\/histogram.h\"\n#include \"cartographer\/common\/make_unique.h\"\n#include \"cartographer_ros\/msg_conversion.h\"\n#include \"gflags\/gflags.h\"\n#include \"glog\/logging.h\"\n#include \"nav_msgs\/Odometry.h\"\n#include \"ros\/ros.h\"\n#include \"ros\/time.h\"\n#include \"rosbag\/bag.h\"\n#include \"rosbag\/view.h\"\n#include \"sensor_msgs\/Imu.h\"\n#include \"sensor_msgs\/LaserScan.h\"\n#include \"sensor_msgs\/MultiEchoLaserScan.h\"\n#include \"sensor_msgs\/PointCloud2.h\"\n#include \"tf2_eigen\/tf2_eigen.h\"\n#include \"tf2_msgs\/TFMessage.h\"\n#include \"tf2_ros\/buffer.h\"\n#include \"urdf\/model.h\"\n\nDEFINE_string(bag_filename, \"\", \"Bag to process.\");\nDEFINE_bool(dump_timing, false,\n \"Dump per-sensor timing information in files called \"\n \"timing_<frame_id>.csv in the current directory.\");\n\nnamespace cartographer_ros {\nnamespace {\n\nstruct FrameProperties {\n ros::Time last_timestamp;\n std::string topic;\n std::vector<float> time_deltas;\n std::unique_ptr<std::ofstream> timing_file;\n std::string data_type;\n};\n\nconst double kMinLinearAcceleration = 3.;\nconst double kMaxLinearAcceleration = 30.;\nconst double kTimeDeltaSerializationSensorWarning = 0.1;\nconst double kTimeDeltaSerializationSensorError = 0.5;\nconst double kMinAverageAcceleration = 9.5;\nconst double kMaxAverageAcceleration = 10.5;\nconst double kMaxGapPointsData = 0.1;\nconst double kMaxGapImuData = 0.05;\nconst std::set<std::string> kPointDataTypes = {\n std::string(\n ros::message_traits::DataType<sensor_msgs::PointCloud2>::value()),\n std::string(ros::message_traits::DataType<\n sensor_msgs::MultiEchoLaserScan>::value()),\n std::string(\n ros::message_traits::DataType<sensor_msgs::LaserScan>::value())};\n\nstd::unique_ptr<std::ofstream> CreateTimingFile(const std::string& frame_id) {\n auto timing_file = ::cartographer::common::make_unique<std::ofstream>(\n std::string(\"timing_\") + frame_id + \".csv\", std::ios_base::out);\n\n (*timing_file)\n << \"# Timing information for sensor with frame id: \" << frame_id\n << std::endl\n << \"# Columns are in order\" << std::endl\n << \"# - packet index of the packet in the bag, first packet is 1\"\n << std::endl\n << \"# - timestamp when rosbag wrote the packet, i.e. \"\n \"rosbag::MessageInstance::getTime().toNSec()\"\n << std::endl\n << \"# - timestamp when data was acquired, i.e. \"\n \"message.header.stamp.toNSec()\"\n << std::endl\n << \"#\" << std::endl\n << \"# The data can be read in python using\" << std::endl\n << \"# import numpy\" << std::endl\n << \"# np.loadtxt(<filename>, dtype='uint64')\" << std::endl;\n\n return timing_file;\n}\n\nvoid CheckImuMessage(const sensor_msgs::Imu& imu_message) {\n auto linear_acceleration = ToEigen(imu_message.linear_acceleration);\n if (std::isnan(linear_acceleration.norm()) ||\n linear_acceleration.norm() < kMinLinearAcceleration ||\n linear_acceleration.norm() > kMaxLinearAcceleration) {\n LOG_FIRST_N(WARNING, 3)\n << \"frame_id \" << imu_message.header.frame_id << \" time \"\n << imu_message.header.stamp.toNSec() << \": IMU linear acceleration is \"\n << linear_acceleration.norm() << \" m\/s^2,\"\n << \" expected is [\" << kMinLinearAcceleration << \", \"\n << kMaxLinearAcceleration << \"] m\/s^2.\"\n << \" (It should include gravity and be given in m\/s^2.)\"\n << \" linear_acceleration \" << linear_acceleration.transpose();\n }\n}\n\nbool IsValidPose(const geometry_msgs::Pose& pose) {\n return ToRigid3d(pose).IsValid();\n}\n\nvoid CheckOdometryMessage(const nav_msgs::Odometry& message) {\n const auto& pose = message.pose.pose;\n if (!IsValidPose(pose)) {\n LOG_FIRST_N(ERROR, 3) << \"frame_id \" << message.header.frame_id << \" time \"\n << message.header.stamp.toNSec()\n << \": Odometry pose is invalid.\"\n << \" pose \" << pose;\n }\n}\n\nvoid CheckTfMessage(const tf2_msgs::TFMessage& message) {\n for (const auto& transform : message.transforms) {\n if (transform.header.frame_id == \"map\") {\n LOG_FIRST_N(ERROR, 1)\n << \"Input contains transform message from frame_id \\\"\"\n << transform.header.frame_id << \"\\\" to child_frame_id \\\"\"\n << transform.child_frame_id\n << \"\\\". This is almost always output published by cartographer and \"\n \"should not appear as input. (Unless you have some complex \"\n \"remove_frames configuration, this is will not work. Simplest \"\n \"solution is to record input without cartographer running.)\";\n }\n }\n}\n\nbool IsPointDataType(const std::string& data_type) {\n return (kPointDataTypes.count(data_type) != 0);\n}\n\nclass RangeDataChecker {\n public:\n template <typename MessageType>\n void CheckMessage(const MessageType& message) {\n const std::string& frame_id = message.header.frame_id;\n RangeChecksum current_checksum = ComputeRangeChecksum(message);\n if (current_checksum.first == 0) {\n return;\n }\n auto it = frame_id_to_range_checksum_.find(frame_id);\n if (it != frame_id_to_range_checksum_.end()) {\n RangeChecksum previous_checksum = it->second;\n if (previous_checksum == current_checksum) {\n LOG_FIRST_N(ERROR, 3)\n << \"Sensor with frame_id \\\"\" << frame_id\n << \"\\\" sends exactly the same range measurements multiple times. \"\n << \"Range data at time \" << message.header.stamp\n << \" equals preceding data.\";\n }\n }\n frame_id_to_range_checksum_[frame_id] = current_checksum;\n }\n\n private:\n typedef std::pair<size_t \/* num_points *\/, Eigen::Vector4f \/* points_sum *\/>\n RangeChecksum;\n\n template <typename MessageType>\n RangeChecksum ComputeRangeChecksum(const MessageType& message) {\n const cartographer::sensor::TimedPointCloud& point_cloud =\n std::get<0>(ToPointCloudWithIntensities(message)).points;\n Eigen::Vector4f points_sum = Eigen::Vector4f::Zero();\n for (const auto& point : point_cloud) {\n points_sum += point;\n }\n return {point_cloud.size(), points_sum};\n }\n\n std::map<std::string, RangeChecksum> frame_id_to_range_checksum_;\n};\n\nvoid Run(const std::string& bag_filename, const bool dump_timing) {\n rosbag::Bag bag;\n bag.open(bag_filename, rosbag::bagmode::Read);\n rosbag::View view(bag);\n\n std::map<std::string, FrameProperties> frame_id_to_properties;\n size_t message_index = 0;\n int num_imu_messages = 0;\n double sum_imu_acceleration = 0.;\n RangeDataChecker range_data_checker;\n for (const rosbag::MessageInstance& message : view) {\n ++message_index;\n std::string frame_id;\n ros::Time time;\n if (message.isType<sensor_msgs::PointCloud2>()) {\n auto msg = message.instantiate<sensor_msgs::PointCloud2>();\n time = msg->header.stamp;\n frame_id = msg->header.frame_id;\n range_data_checker.CheckMessage(*msg);\n } else if (message.isType<sensor_msgs::MultiEchoLaserScan>()) {\n auto msg = message.instantiate<sensor_msgs::MultiEchoLaserScan>();\n time = msg->header.stamp;\n frame_id = msg->header.frame_id;\n range_data_checker.CheckMessage(*msg);\n } else if (message.isType<sensor_msgs::LaserScan>()) {\n auto msg = message.instantiate<sensor_msgs::LaserScan>();\n time = msg->header.stamp;\n frame_id = msg->header.frame_id;\n range_data_checker.CheckMessage(*msg);\n } else if (message.isType<sensor_msgs::Imu>()) {\n auto msg = message.instantiate<sensor_msgs::Imu>();\n time = msg->header.stamp;\n frame_id = msg->header.frame_id;\n CheckImuMessage(*msg);\n num_imu_messages++;\n sum_imu_acceleration += ToEigen(msg->linear_acceleration).norm();\n } else if (message.isType<nav_msgs::Odometry>()) {\n auto msg = message.instantiate<nav_msgs::Odometry>();\n time = msg->header.stamp;\n frame_id = msg->header.frame_id;\n CheckOdometryMessage(*msg);\n } else if (message.isType<tf2_msgs::TFMessage>()) {\n auto msg = message.instantiate<tf2_msgs::TFMessage>();\n CheckTfMessage(*msg);\n continue;\n } else {\n continue;\n }\n\n bool first_packet = false;\n if (!frame_id_to_properties.count(frame_id)) {\n frame_id_to_properties.emplace(\n frame_id,\n FrameProperties{time, message.getTopic(), std::vector<float>(),\n dump_timing ? CreateTimingFile(frame_id) : nullptr,\n message.getDataType()});\n first_packet = true;\n }\n\n auto& entry = frame_id_to_properties.at(frame_id);\n if (!first_packet) {\n const double delta_t_sec = (time - entry.last_timestamp).toSec();\n if (delta_t_sec < 0) {\n LOG_FIRST_N(ERROR, 3)\n << \"Sensor with frame_id \\\"\" << frame_id\n << \"\\\" jumps backwards in time. Make sure that the bag \"\n \"contains the data for each frame_id sorted by \"\n \"header.stamp, i.e. the order in which they were \"\n \"acquired from the sensor.\";\n }\n entry.time_deltas.push_back(delta_t_sec);\n }\n\n if (entry.topic != message.getTopic()) {\n LOG_FIRST_N(ERROR, 3)\n << \"frame_id \\\"\" << frame_id\n << \"\\\" is send on multiple topics. It was seen at least on \"\n << entry.topic << \" and \" << message.getTopic();\n }\n entry.last_timestamp = time;\n\n if (dump_timing) {\n CHECK(entry.timing_file != nullptr);\n (*entry.timing_file) << message_index << \"\\t\"\n << message.getTime().toNSec() << \"\\t\"\n << time.toNSec() << std::endl;\n }\n\n double duration_serialization_sensor = (time - message.getTime()).toSec();\n if (std::abs(duration_serialization_sensor) >\n kTimeDeltaSerializationSensorWarning) {\n std::stringstream stream;\n stream << \"frame_id \\\"\" << frame_id << \"\\\" on topic \"\n << message.getTopic() << \" has serialization time \"\n << message.getTime() << \" but sensor time \" << time\n << \" differing by \" << duration_serialization_sensor << \" s.\";\n if (std::abs(duration_serialization_sensor) >\n kTimeDeltaSerializationSensorError) {\n LOG_FIRST_N(ERROR, 3) << stream.str();\n } else {\n LOG_FIRST_N(WARNING, 1) << stream.str();\n }\n }\n }\n bag.close();\n\n if (num_imu_messages > 0) {\n double average_imu_acceleration = sum_imu_acceleration \/ num_imu_messages;\n if (std::isnan(average_imu_acceleration) ||\n average_imu_acceleration < kMinAverageAcceleration ||\n average_imu_acceleration > kMaxAverageAcceleration) {\n LOG(ERROR) << \"Average IMU linear acceleration is \"\n << average_imu_acceleration << \" m\/s^2,\"\n << \" expected is [\" << kMinAverageAcceleration << \", \"\n << kMaxAverageAcceleration\n << \"] m\/s^2. Linear acceleration data \"\n \"should include gravity and be given in m\/s^2.\";\n }\n }\n\n constexpr int kNumBucketsForHistogram = 10;\n for (const auto& entry_pair : frame_id_to_properties) {\n const FrameProperties& frame_properties = entry_pair.second;\n float max_time_delta =\n *std::max_element(frame_properties.time_deltas.begin(),\n frame_properties.time_deltas.end());\n if (IsPointDataType(frame_properties.data_type) &&\n max_time_delta > kMaxGapPointsData) {\n LOG(ERROR) << \"Point data (frame_id: \\\"\" << entry_pair.first\n << \"\\\") has a large gap, largest is \" << max_time_delta\n << \" s, recommended is [0.0005, 0.05] s with no jitter.\";\n }\n if (frame_properties.data_type ==\n ros::message_traits::DataType<sensor_msgs::Imu>::value() &&\n max_time_delta > kMaxGapImuData) {\n LOG(ERROR) << \"IMU data (frame_id: \\\"\" << entry_pair.first\n << \"\\\") has a large gap, largest is \" << max_time_delta\n << \" s, recommended is [0.0005, 0.005] s with no jitter.\";\n }\n\n cartographer::common::Histogram histogram;\n for (float time_delta : frame_properties.time_deltas) {\n histogram.Add(time_delta);\n }\n LOG(INFO) << \"Time delta histogram for consecutive messages on topic \\\"\"\n << frame_properties.topic << \"\\\" (frame_id: \\\"\"\n << entry_pair.first << \"\\\"):\\n\"\n << histogram.ToString(kNumBucketsForHistogram);\n }\n\n if (dump_timing) {\n for (const auto& entry_pair : frame_id_to_properties) {\n entry_pair.second.timing_file->close();\n CHECK(*entry_pair.second.timing_file)\n << \"Could not write timing information for \\\"\" << entry_pair.first\n << \"\\\"\";\n }\n }\n}\n\n} \/\/ namespace\n} \/\/ namespace cartographer_ros\n\nint main(int argc, char** argv) {\n FLAGS_alsologtostderr = true;\n google::InitGoogleLogging(argv[0]);\n google::ParseCommandLineFlags(&argc, &argv, true);\n\n CHECK(!FLAGS_bag_filename.empty()) << \"-bag_filename is missing.\";\n ::cartographer_ros::Run(FLAGS_bag_filename, FLAGS_dump_timing);\n}\n<commit_msg>Fix segfault in rosbag_validate (#685)<commit_after>\/*\n * Copyright 2017 The Cartographer Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include <fstream>\n#include <iostream>\n#include <map>\n#include <set>\n#include <string>\n\n#include \"cartographer\/common\/histogram.h\"\n#include \"cartographer\/common\/make_unique.h\"\n#include \"cartographer_ros\/msg_conversion.h\"\n#include \"gflags\/gflags.h\"\n#include \"glog\/logging.h\"\n#include \"nav_msgs\/Odometry.h\"\n#include \"ros\/ros.h\"\n#include \"ros\/time.h\"\n#include \"rosbag\/bag.h\"\n#include \"rosbag\/view.h\"\n#include \"sensor_msgs\/Imu.h\"\n#include \"sensor_msgs\/LaserScan.h\"\n#include \"sensor_msgs\/MultiEchoLaserScan.h\"\n#include \"sensor_msgs\/PointCloud2.h\"\n#include \"tf2_eigen\/tf2_eigen.h\"\n#include \"tf2_msgs\/TFMessage.h\"\n#include \"tf2_ros\/buffer.h\"\n#include \"urdf\/model.h\"\n\nDEFINE_string(bag_filename, \"\", \"Bag to process.\");\nDEFINE_bool(dump_timing, false,\n \"Dump per-sensor timing information in files called \"\n \"timing_<frame_id>.csv in the current directory.\");\n\nnamespace cartographer_ros {\nnamespace {\n\nstruct FrameProperties {\n ros::Time last_timestamp;\n std::string topic;\n std::vector<float> time_deltas;\n std::unique_ptr<std::ofstream> timing_file;\n std::string data_type;\n};\n\nconst double kMinLinearAcceleration = 3.;\nconst double kMaxLinearAcceleration = 30.;\nconst double kTimeDeltaSerializationSensorWarning = 0.1;\nconst double kTimeDeltaSerializationSensorError = 0.5;\nconst double kMinAverageAcceleration = 9.5;\nconst double kMaxAverageAcceleration = 10.5;\nconst double kMaxGapPointsData = 0.1;\nconst double kMaxGapImuData = 0.05;\nconst std::set<std::string> kPointDataTypes = {\n std::string(\n ros::message_traits::DataType<sensor_msgs::PointCloud2>::value()),\n std::string(ros::message_traits::DataType<\n sensor_msgs::MultiEchoLaserScan>::value()),\n std::string(\n ros::message_traits::DataType<sensor_msgs::LaserScan>::value())};\n\nstd::unique_ptr<std::ofstream> CreateTimingFile(const std::string& frame_id) {\n auto timing_file = ::cartographer::common::make_unique<std::ofstream>(\n std::string(\"timing_\") + frame_id + \".csv\", std::ios_base::out);\n\n (*timing_file)\n << \"# Timing information for sensor with frame id: \" << frame_id\n << std::endl\n << \"# Columns are in order\" << std::endl\n << \"# - packet index of the packet in the bag, first packet is 1\"\n << std::endl\n << \"# - timestamp when rosbag wrote the packet, i.e. \"\n \"rosbag::MessageInstance::getTime().toNSec()\"\n << std::endl\n << \"# - timestamp when data was acquired, i.e. \"\n \"message.header.stamp.toNSec()\"\n << std::endl\n << \"#\" << std::endl\n << \"# The data can be read in python using\" << std::endl\n << \"# import numpy\" << std::endl\n << \"# np.loadtxt(<filename>, dtype='uint64')\" << std::endl;\n\n return timing_file;\n}\n\nvoid CheckImuMessage(const sensor_msgs::Imu& imu_message) {\n auto linear_acceleration = ToEigen(imu_message.linear_acceleration);\n if (std::isnan(linear_acceleration.norm()) ||\n linear_acceleration.norm() < kMinLinearAcceleration ||\n linear_acceleration.norm() > kMaxLinearAcceleration) {\n LOG_FIRST_N(WARNING, 3)\n << \"frame_id \" << imu_message.header.frame_id << \" time \"\n << imu_message.header.stamp.toNSec() << \": IMU linear acceleration is \"\n << linear_acceleration.norm() << \" m\/s^2,\"\n << \" expected is [\" << kMinLinearAcceleration << \", \"\n << kMaxLinearAcceleration << \"] m\/s^2.\"\n << \" (It should include gravity and be given in m\/s^2.)\"\n << \" linear_acceleration \" << linear_acceleration.transpose();\n }\n}\n\nbool IsValidPose(const geometry_msgs::Pose& pose) {\n return ToRigid3d(pose).IsValid();\n}\n\nvoid CheckOdometryMessage(const nav_msgs::Odometry& message) {\n const auto& pose = message.pose.pose;\n if (!IsValidPose(pose)) {\n LOG_FIRST_N(ERROR, 3) << \"frame_id \" << message.header.frame_id << \" time \"\n << message.header.stamp.toNSec()\n << \": Odometry pose is invalid.\"\n << \" pose \" << pose;\n }\n}\n\nvoid CheckTfMessage(const tf2_msgs::TFMessage& message) {\n for (const auto& transform : message.transforms) {\n if (transform.header.frame_id == \"map\") {\n LOG_FIRST_N(ERROR, 1)\n << \"Input contains transform message from frame_id \\\"\"\n << transform.header.frame_id << \"\\\" to child_frame_id \\\"\"\n << transform.child_frame_id\n << \"\\\". This is almost always output published by cartographer and \"\n \"should not appear as input. (Unless you have some complex \"\n \"remove_frames configuration, this is will not work. Simplest \"\n \"solution is to record input without cartographer running.)\";\n }\n }\n}\n\nbool IsPointDataType(const std::string& data_type) {\n return (kPointDataTypes.count(data_type) != 0);\n}\n\nclass RangeDataChecker {\n public:\n template <typename MessageType>\n void CheckMessage(const MessageType& message) {\n const std::string& frame_id = message.header.frame_id;\n RangeChecksum current_checksum = ComputeRangeChecksum(message);\n if (current_checksum.first == 0) {\n return;\n }\n auto it = frame_id_to_range_checksum_.find(frame_id);\n if (it != frame_id_to_range_checksum_.end()) {\n RangeChecksum previous_checksum = it->second;\n if (previous_checksum == current_checksum) {\n LOG_FIRST_N(ERROR, 3)\n << \"Sensor with frame_id \\\"\" << frame_id\n << \"\\\" sends exactly the same range measurements multiple times. \"\n << \"Range data at time \" << message.header.stamp\n << \" equals preceding data.\";\n }\n }\n frame_id_to_range_checksum_[frame_id] = current_checksum;\n }\n\n private:\n typedef std::pair<size_t \/* num_points *\/, Eigen::Vector4f \/* points_sum *\/>\n RangeChecksum;\n\n template <typename MessageType>\n RangeChecksum ComputeRangeChecksum(const MessageType& message) {\n auto point_cloud_with_intensities = ToPointCloudWithIntensities(message);\n const cartographer::sensor::TimedPointCloud& point_cloud =\n std::get<0>(point_cloud_with_intensities).points;\n Eigen::Vector4f points_sum = Eigen::Vector4f::Zero();\n for (const auto& point : point_cloud) {\n points_sum += point;\n }\n return {point_cloud.size(), points_sum};\n }\n\n std::map<std::string, RangeChecksum> frame_id_to_range_checksum_;\n};\n\nvoid Run(const std::string& bag_filename, const bool dump_timing) {\n rosbag::Bag bag;\n bag.open(bag_filename, rosbag::bagmode::Read);\n rosbag::View view(bag);\n\n std::map<std::string, FrameProperties> frame_id_to_properties;\n size_t message_index = 0;\n int num_imu_messages = 0;\n double sum_imu_acceleration = 0.;\n RangeDataChecker range_data_checker;\n for (const rosbag::MessageInstance& message : view) {\n ++message_index;\n std::string frame_id;\n ros::Time time;\n if (message.isType<sensor_msgs::PointCloud2>()) {\n auto msg = message.instantiate<sensor_msgs::PointCloud2>();\n time = msg->header.stamp;\n frame_id = msg->header.frame_id;\n range_data_checker.CheckMessage(*msg);\n } else if (message.isType<sensor_msgs::MultiEchoLaserScan>()) {\n auto msg = message.instantiate<sensor_msgs::MultiEchoLaserScan>();\n time = msg->header.stamp;\n frame_id = msg->header.frame_id;\n range_data_checker.CheckMessage(*msg);\n } else if (message.isType<sensor_msgs::LaserScan>()) {\n auto msg = message.instantiate<sensor_msgs::LaserScan>();\n time = msg->header.stamp;\n frame_id = msg->header.frame_id;\n range_data_checker.CheckMessage(*msg);\n } else if (message.isType<sensor_msgs::Imu>()) {\n auto msg = message.instantiate<sensor_msgs::Imu>();\n time = msg->header.stamp;\n frame_id = msg->header.frame_id;\n CheckImuMessage(*msg);\n num_imu_messages++;\n sum_imu_acceleration += ToEigen(msg->linear_acceleration).norm();\n } else if (message.isType<nav_msgs::Odometry>()) {\n auto msg = message.instantiate<nav_msgs::Odometry>();\n time = msg->header.stamp;\n frame_id = msg->header.frame_id;\n CheckOdometryMessage(*msg);\n } else if (message.isType<tf2_msgs::TFMessage>()) {\n auto msg = message.instantiate<tf2_msgs::TFMessage>();\n CheckTfMessage(*msg);\n continue;\n } else {\n continue;\n }\n\n bool first_packet = false;\n if (!frame_id_to_properties.count(frame_id)) {\n frame_id_to_properties.emplace(\n frame_id,\n FrameProperties{time, message.getTopic(), std::vector<float>(),\n dump_timing ? CreateTimingFile(frame_id) : nullptr,\n message.getDataType()});\n first_packet = true;\n }\n\n auto& entry = frame_id_to_properties.at(frame_id);\n if (!first_packet) {\n const double delta_t_sec = (time - entry.last_timestamp).toSec();\n if (delta_t_sec < 0) {\n LOG_FIRST_N(ERROR, 3)\n << \"Sensor with frame_id \\\"\" << frame_id\n << \"\\\" jumps backwards in time. Make sure that the bag \"\n \"contains the data for each frame_id sorted by \"\n \"header.stamp, i.e. the order in which they were \"\n \"acquired from the sensor.\";\n }\n entry.time_deltas.push_back(delta_t_sec);\n }\n\n if (entry.topic != message.getTopic()) {\n LOG_FIRST_N(ERROR, 3)\n << \"frame_id \\\"\" << frame_id\n << \"\\\" is send on multiple topics. It was seen at least on \"\n << entry.topic << \" and \" << message.getTopic();\n }\n entry.last_timestamp = time;\n\n if (dump_timing) {\n CHECK(entry.timing_file != nullptr);\n (*entry.timing_file) << message_index << \"\\t\"\n << message.getTime().toNSec() << \"\\t\"\n << time.toNSec() << std::endl;\n }\n\n double duration_serialization_sensor = (time - message.getTime()).toSec();\n if (std::abs(duration_serialization_sensor) >\n kTimeDeltaSerializationSensorWarning) {\n std::stringstream stream;\n stream << \"frame_id \\\"\" << frame_id << \"\\\" on topic \"\n << message.getTopic() << \" has serialization time \"\n << message.getTime() << \" but sensor time \" << time\n << \" differing by \" << duration_serialization_sensor << \" s.\";\n if (std::abs(duration_serialization_sensor) >\n kTimeDeltaSerializationSensorError) {\n LOG_FIRST_N(ERROR, 3) << stream.str();\n } else {\n LOG_FIRST_N(WARNING, 1) << stream.str();\n }\n }\n }\n bag.close();\n\n if (num_imu_messages > 0) {\n double average_imu_acceleration = sum_imu_acceleration \/ num_imu_messages;\n if (std::isnan(average_imu_acceleration) ||\n average_imu_acceleration < kMinAverageAcceleration ||\n average_imu_acceleration > kMaxAverageAcceleration) {\n LOG(ERROR) << \"Average IMU linear acceleration is \"\n << average_imu_acceleration << \" m\/s^2,\"\n << \" expected is [\" << kMinAverageAcceleration << \", \"\n << kMaxAverageAcceleration\n << \"] m\/s^2. Linear acceleration data \"\n \"should include gravity and be given in m\/s^2.\";\n }\n }\n\n constexpr int kNumBucketsForHistogram = 10;\n for (const auto& entry_pair : frame_id_to_properties) {\n const FrameProperties& frame_properties = entry_pair.second;\n float max_time_delta =\n *std::max_element(frame_properties.time_deltas.begin(),\n frame_properties.time_deltas.end());\n if (IsPointDataType(frame_properties.data_type) &&\n max_time_delta > kMaxGapPointsData) {\n LOG(ERROR) << \"Point data (frame_id: \\\"\" << entry_pair.first\n << \"\\\") has a large gap, largest is \" << max_time_delta\n << \" s, recommended is [0.0005, 0.05] s with no jitter.\";\n }\n if (frame_properties.data_type ==\n ros::message_traits::DataType<sensor_msgs::Imu>::value() &&\n max_time_delta > kMaxGapImuData) {\n LOG(ERROR) << \"IMU data (frame_id: \\\"\" << entry_pair.first\n << \"\\\") has a large gap, largest is \" << max_time_delta\n << \" s, recommended is [0.0005, 0.005] s with no jitter.\";\n }\n\n cartographer::common::Histogram histogram;\n for (float time_delta : frame_properties.time_deltas) {\n histogram.Add(time_delta);\n }\n LOG(INFO) << \"Time delta histogram for consecutive messages on topic \\\"\"\n << frame_properties.topic << \"\\\" (frame_id: \\\"\"\n << entry_pair.first << \"\\\"):\\n\"\n << histogram.ToString(kNumBucketsForHistogram);\n }\n\n if (dump_timing) {\n for (const auto& entry_pair : frame_id_to_properties) {\n entry_pair.second.timing_file->close();\n CHECK(*entry_pair.second.timing_file)\n << \"Could not write timing information for \\\"\" << entry_pair.first\n << \"\\\"\";\n }\n }\n}\n\n} \/\/ namespace\n} \/\/ namespace cartographer_ros\n\nint main(int argc, char** argv) {\n FLAGS_alsologtostderr = true;\n google::InitGoogleLogging(argv[0]);\n google::ParseCommandLineFlags(&argc, &argv, true);\n\n CHECK(!FLAGS_bag_filename.empty()) << \"-bag_filename is missing.\";\n ::cartographer_ros::Run(FLAGS_bag_filename, FLAGS_dump_timing);\n}\n<|endoftext|>"} {"text":"<commit_before>\/*******************************************************************************\n * Copyright (c) 2009-04-24 Joacim Jacobsson.\n * All rights reserved. This program and the accompanying materials\n * are made available under the terms of the Eclipse Public License v1.0\n * which accompanies this distribution, and is available at\n * http:\/\/www.eclipse.org\/legal\/epl-v10.html\n *\n * Contributors:\n * Joacim Jacobsson - first implementation\n *******************************************************************************\/\n\n#include <QtGui\/QtGui>\n\n#include \"BehaviorTreeList.h\"\n#include \"..\/standard_resources.h\"\n#include \"..\/x-node.h\"\n\n#include <btree\/btree_func.h>\n\nBehaviorTreeList::BehaviorTreeList( QWidget *parent ) :\n QListWidget( parent )\n{\n setDragEnabled( true );\n setViewMode( QListView::ListMode );\n setIconSize( QSize( 16, 16 ) );\n setSpacing( 2 );\n setAcceptDrops( false );\n setDropIndicatorShown( false );\n\n XNodeData node_data;\n\n {\n QListWidgetItem *nodeItem = new QListWidgetItem( this );\n QPixmap pixmap(32,32);\n pixmap = QPixmap( \":\/nodes\/tree.svg\" ).scaled(\n 32, 32, Qt::IgnoreAspectRatio, Qt::SmoothTransformation\n );\n nodeItem->setIcon( QIcon(pixmap) );\n nodeItem->setData( Qt::UserRole + 0, pixmap );\n\n node_data.m_Type = E_XNDT_TREE;\n node_data.m_NodeGrist = E_GRIST_UNKOWN;\n node_data.m_FuncId = 0;\n\n nodeItem->setData( Qt::UserRole + 1,\n QByteArray( (const char*)(&node_data), sizeof(XNodeData)) );\n\n nodeItem->setFlags( Qt::ItemIsEnabled | Qt::ItemIsSelectable\n | Qt::ItemIsDragEnabled );\n nodeItem->setText( tr(\"Tree\") );\n }\n\n for( int i = 1; i < E_GRIST_DECORATOR; ++i )\n {\n QListWidgetItem *nodeItem = new QListWidgetItem( this );\n QPixmap pixmap(32,32);\n\n pixmap = QPixmap(g_NodeSVGResourcePaths[i]).scaled(\n 32, 32, Qt::IgnoreAspectRatio, Qt::SmoothTransformation\n );\n\n nodeItem->setIcon( QIcon(pixmap) );\n nodeItem->setData( Qt::UserRole + 0, pixmap );\n\n node_data.m_Type = E_XNDT_NODE;\n node_data.m_NodeGrist = i;\n node_data.m_FuncId = 0;\n\n nodeItem->setData( Qt::UserRole + 1,\n QByteArray( (const char*)(&node_data), sizeof(XNodeData)) );\n\n nodeItem->setFlags( Qt::ItemIsEnabled | Qt::ItemIsSelectable\n | Qt::ItemIsDragEnabled );\n nodeItem->setText( g_NodeNames[i] );\n }\n\n}\n\nvoid BehaviorTreeList::loadSymbols( BehaviorTreeContext ctx )\n{\n\n QMessageBox::warning( this, tr( \"Calltree Studio\" ), tr(\n \"The behavior keps has been modified.\\n\"\n \"Do you want to save your changes?\" ), QMessageBox::Yes\n | QMessageBox::Default, QMessageBox::No, QMessageBox::Cancel\n | QMessageBox::Escape );\n int c;\n NamedSymbol* ns = BehaviorTreeContextAccessSymbols( ctx, &c );\n\n XNodeData node_data;\n\n for( int i = 0; i < c; ++i )\n {\n bool set = false;\n const char* name = 0x0;\n switch( ns[i].m_Type )\n {\n case E_ST_ACTION:\n if( ns[i].m_Symbol.m_Action->m_Declared )\n {\n node_data.m_Type = E_XNDT_NODE;\n node_data.m_NodeGrist = E_GRIST_ACTION;\n node_data.m_FuncId = ns[i].m_Symbol.m_Action->m_Id.m_Hash;\n name = ns[i].m_Symbol.m_Action->m_Id.m_Text;\n set = true;\n }\n break;\n case E_ST_DECORATOR:\n if( ns[i].m_Symbol.m_Decorator->m_Declared )\n {\n node_data.m_Type = E_XNDT_NODE;\n node_data.m_NodeGrist = E_GRIST_DECORATOR;\n node_data.m_FuncId = ns[i].m_Symbol.m_Decorator->m_Id.m_Hash;\n name = ns[i].m_Symbol.m_Decorator->m_Id.m_Text;\n set = true;\n }\n break;\n }\n if( !set )\n continue;\n\n QListWidgetItem *nodeItem = new QListWidgetItem( this );\n QPixmap pixmap(32,32);\n\n pixmap = QPixmap(g_NodeSVGResourcePaths[node_data.m_NodeGrist]).scaled(\n 32, 32, Qt::IgnoreAspectRatio, Qt::SmoothTransformation\n );\n\n nodeItem->setIcon( QIcon(pixmap) );\n nodeItem->setData( Qt::UserRole + 0, pixmap );\n nodeItem->setData( Qt::UserRole + 1,\n QByteArray( (const char*)(&node_data), sizeof(XNodeData)) );\n\n nodeItem->setFlags( Qt::ItemIsEnabled | Qt::ItemIsSelectable\n | Qt::ItemIsDragEnabled );\n nodeItem->setText( name );\n }\n}\n\nvoid BehaviorTreeList::startDrag( Qt::DropActions \/*supportedActions*\/ )\n{\n QListWidgetItem *item = currentItem();\n\n\n QPixmap pixmap = qVariantValue<QPixmap> ( item->data( Qt::UserRole + 0 ) );\n QMimeData *mimeData = new QMimeData;\n mimeData->setData( \"ctstudio\/x-node\", item->data( Qt::UserRole + 1 ).toByteArray() );\n\n QDrag *drag = new QDrag( this );\n drag->setMimeData( mimeData );\n drag->setHotSpot( QPoint( pixmap.width(), pixmap.height() ) );\n \/\/drag->setPixmap( pixmap );\n\n drag->exec( Qt::CopyAction );\n}\n<commit_msg>Removed annoying test-popup<commit_after>\/*******************************************************************************\n * Copyright (c) 2009-04-24 Joacim Jacobsson.\n * All rights reserved. This program and the accompanying materials\n * are made available under the terms of the Eclipse Public License v1.0\n * which accompanies this distribution, and is available at\n * http:\/\/www.eclipse.org\/legal\/epl-v10.html\n *\n * Contributors:\n * Joacim Jacobsson - first implementation\n *******************************************************************************\/\n\n#include <QtGui\/QtGui>\n\n#include \"BehaviorTreeList.h\"\n#include \"..\/standard_resources.h\"\n#include \"..\/x-node.h\"\n\n#include <btree\/btree_func.h>\n\nBehaviorTreeList::BehaviorTreeList( QWidget *parent ) :\n QListWidget( parent )\n{\n setDragEnabled( true );\n setViewMode( QListView::ListMode );\n setIconSize( QSize( 16, 16 ) );\n setSpacing( 2 );\n setAcceptDrops( false );\n setDropIndicatorShown( false );\n\n XNodeData node_data;\n\n {\n QListWidgetItem *nodeItem = new QListWidgetItem( this );\n QPixmap pixmap(32,32);\n pixmap = QPixmap( \":\/nodes\/tree.svg\" ).scaled(\n 32, 32, Qt::IgnoreAspectRatio, Qt::SmoothTransformation\n );\n nodeItem->setIcon( QIcon(pixmap) );\n nodeItem->setData( Qt::UserRole + 0, pixmap );\n\n node_data.m_Type = E_XNDT_TREE;\n node_data.m_NodeGrist = E_GRIST_UNKOWN;\n node_data.m_FuncId = 0;\n\n nodeItem->setData( Qt::UserRole + 1,\n QByteArray( (const char*)(&node_data), sizeof(XNodeData)) );\n\n nodeItem->setFlags( Qt::ItemIsEnabled | Qt::ItemIsSelectable\n | Qt::ItemIsDragEnabled );\n nodeItem->setText( tr(\"Tree\") );\n }\n\n for( int i = 1; i < E_GRIST_DECORATOR; ++i )\n {\n QListWidgetItem *nodeItem = new QListWidgetItem( this );\n QPixmap pixmap(32,32);\n\n pixmap = QPixmap(g_NodeSVGResourcePaths[i]).scaled(\n 32, 32, Qt::IgnoreAspectRatio, Qt::SmoothTransformation\n );\n\n nodeItem->setIcon( QIcon(pixmap) );\n nodeItem->setData( Qt::UserRole + 0, pixmap );\n\n node_data.m_Type = E_XNDT_NODE;\n node_data.m_NodeGrist = i;\n node_data.m_FuncId = 0;\n\n nodeItem->setData( Qt::UserRole + 1,\n QByteArray( (const char*)(&node_data), sizeof(XNodeData)) );\n\n nodeItem->setFlags( Qt::ItemIsEnabled | Qt::ItemIsSelectable\n | Qt::ItemIsDragEnabled );\n nodeItem->setText( g_NodeNames[i] );\n }\n\n}\n\nvoid BehaviorTreeList::loadSymbols( BehaviorTreeContext ctx )\n{\n int c;\n NamedSymbol* ns = BehaviorTreeContextAccessSymbols( ctx, &c );\n\n XNodeData node_data;\n\n for( int i = 0; i < c; ++i )\n {\n bool set = false;\n const char* name = 0x0;\n switch( ns[i].m_Type )\n {\n case E_ST_ACTION:\n if( ns[i].m_Symbol.m_Action->m_Declared )\n {\n node_data.m_Type = E_XNDT_NODE;\n node_data.m_NodeGrist = E_GRIST_ACTION;\n node_data.m_FuncId = ns[i].m_Symbol.m_Action->m_Id.m_Hash;\n name = ns[i].m_Symbol.m_Action->m_Id.m_Text;\n set = true;\n }\n break;\n case E_ST_DECORATOR:\n if( ns[i].m_Symbol.m_Decorator->m_Declared )\n {\n node_data.m_Type = E_XNDT_NODE;\n node_data.m_NodeGrist = E_GRIST_DECORATOR;\n node_data.m_FuncId = ns[i].m_Symbol.m_Decorator->m_Id.m_Hash;\n name = ns[i].m_Symbol.m_Decorator->m_Id.m_Text;\n set = true;\n }\n break;\n }\n if( !set )\n continue;\n\n QListWidgetItem *nodeItem = new QListWidgetItem( this );\n QPixmap pixmap(32,32);\n\n pixmap = QPixmap(g_NodeSVGResourcePaths[node_data.m_NodeGrist]).scaled(\n 32, 32, Qt::IgnoreAspectRatio, Qt::SmoothTransformation\n );\n\n nodeItem->setIcon( QIcon(pixmap) );\n nodeItem->setData( Qt::UserRole + 0, pixmap );\n nodeItem->setData( Qt::UserRole + 1,\n QByteArray( (const char*)(&node_data), sizeof(XNodeData)) );\n\n nodeItem->setFlags( Qt::ItemIsEnabled | Qt::ItemIsSelectable\n | Qt::ItemIsDragEnabled );\n nodeItem->setText( name );\n }\n}\n\nvoid BehaviorTreeList::startDrag( Qt::DropActions \/*supportedActions*\/ )\n{\n QListWidgetItem *item = currentItem();\n\n\n QPixmap pixmap = qVariantValue<QPixmap> ( item->data( Qt::UserRole + 0 ) );\n QMimeData *mimeData = new QMimeData;\n mimeData->setData( \"ctstudio\/x-node\", item->data( Qt::UserRole + 1 ).toByteArray() );\n\n QDrag *drag = new QDrag( this );\n drag->setMimeData( mimeData );\n drag->setHotSpot( QPoint( pixmap.width(), pixmap.height() ) );\n \/\/drag->setPixmap( pixmap );\n\n drag->exec( Qt::CopyAction );\n}\n<|endoftext|>"} {"text":"<commit_before><commit_msg>Trim the lsb_release output in GetLinuxDistro.<commit_after><|endoftext|>"} {"text":"<commit_before>#include \"stdafx.h\"\r\n\r\n#include \"SendIpUpdate.h\"\r\n\r\n#include \"MiscUtil.h\"\r\n#include \"Http.h\"\r\n#include \"JsonParser.h\"\r\n#include \"Prefs.h\"\r\n#include \"StrUtil.h\"\r\n\r\nchar* SendIpUpdate()\r\n{\r\n\tassert(CanSendIPUpdates());\r\n\tif (!CanSendIPUpdates())\r\n\t\treturn NULL;\r\n\r\n\tchar *res = NULL;\r\n\r\n\t\/\/ host = updates.opendns.com or website.dev6.sfo.opendns.com\r\n\t\/\/ url: \/nic\/update?token=mytoken&api_key=mykey?hostname=\r\n\t\/\/ responses:\r\n\t\/\/ \"badauth\"\r\n\t\/\/ \"nohost\"\r\n\t\/\/ \"good ${ip-addr}\"\r\n\tif (!g_pref_token)\r\n\t\treturn NULL;\r\n\tassert(g_pref_hostname);\r\n\r\n\tconst char *urlTxt = GetIpUpdateUrl(TRUE);\r\n\tconst char *host = GetIpUpdateHost();\r\n\r\n\tHttpResult *httpResult = HttpGet(host, urlTxt, INTERNET_DEFAULT_HTTPS_PORT);\r\n\tfree((void*)urlTxt);\r\n\tif (httpResult && httpResult->IsValid()) {\r\n\t\tres = (char*)httpResult->data.getData(NULL);\r\n\t}\r\n\tdelete httpResult;\r\n\treturn res;\r\n}\r\n\r\nchar *SendDnsOmaticUpdate()\r\n{\r\n\tassert(CanSendIPUpdates());\r\n\tif (!CanSendIPUpdates())\r\n\t\treturn NULL;\r\n\r\n\tchar *res = NULL;\r\n\r\n\t\/\/ TODO: do I need to append the following in url from GetIpUpdateUrl()?\r\n\t\/*URL$ = SetURLPart(URL$, \"myip\", ip$)\r\n\tURL$ = SetURLPart(URL$, \"wildcard\", \"NOCHG\")\r\n\tURL$ = SetURLPart(URL$, \"mx\", \"NOCHG\")\r\n\tURL$ = SetURLPart(URL$, \"backmx\", \"NOCHG\")*\/\r\n\r\n\tconst char *urlTxt = GetIpUpdateUrl(TRUE);\r\n\tconst char *host = GetIpUpdateDnsOMaticHost();\r\n\r\n\tHttpResult *httpResult = HttpGet(host, urlTxt, INTERNET_DEFAULT_HTTPS_PORT);\r\n\tfree((void*)urlTxt);\r\n\tif (httpResult && httpResult->IsValid()) {\r\n\t\tres = (char*)httpResult->data.getData(NULL);\r\n\t}\r\n\tdelete httpResult;\r\n\treturn res;\r\n}\r\n\r\nIpUpdateResult IpUpdateResultFromString(const char *s)\r\n{\r\n\tif (StrStartsWithI(s, \"The service is not available\"))\r\n\t\treturn IpUpdateNotAvailable;\r\n\tif (StrStartsWithI(s, \"good\"))\r\n\t\treturn IpUpdateOk;\r\n\tif (StrStartsWithI(s, \"nochg\"))\r\n\t\treturn IpUpdateOk;\r\n\tif (StrStartsWithI(s, \"!yours\"))\r\n\t\treturn IpUpdateNotYours;\r\n\tif (StrStartsWithI(s, \"badauth\"))\r\n\t\treturn IpUpdateBadAuth;\r\n\tif (StrStartsWithI(s, \"nohost\"))\r\n\t\treturn IpUpdateNoHost;\r\n\r\n\t\/\/ not sure if those really happen, they're supported by 1.3 client\r\n\tif (StrStartsWithI(s, \"dnserr\"))\r\n\t\treturn IpUpdateDnsErr;\r\n\r\n\tif (StrStartsWithI(s, \"911\"))\r\n\t\treturn IpUpdateDnsErr;\r\n\r\n\tif (StrStartsWithI(s, \"abuse\"))\r\n\t\treturn IpUpdateMiscErr;\r\n\r\n\tif (StrStartsWithI(s, \"notfqdn\"))\r\n\t\treturn IpUpdateMiscErr;\r\n\r\n\tif (StrStartsWithI(s, \"numhost\"))\r\n\t\treturn IpUpdateMiscErr;\r\n\r\n\tif (StrStartsWithI(s, \"badagent\"))\r\n\t\treturn IpUpdateMiscErr;\r\n\r\n\tif (StrStartsWithI(s, \"!donator\"))\r\n\t\treturn IpUpdateMiscErr;\r\n\r\n\tassert(0);\r\n\treturn IpUpdateOk;\r\n}\r\n\r\n#if 0\r\n\/\/ another way is to use username\/password and http basic auth\r\nchar* SendIpUpdate()\r\n{\r\n\t\/\/ host = \"updates.opendns.com\"\r\n\t\/\/ url = \"\/nic\/update?hostname=\" + network\r\n\t\/\/ responses:\r\n\t\/\/ \"badauth\"\r\n\t\/\/ \"nohost\"\r\n\t\/\/ \"good ${ip-addr}\"\r\n\tconst char *userName = \"\";\r\n\tconst char *pwd = \"\";\r\n\tHttpResult *httpResult = HttpGetWithBasicAuth(\"updates.opendns.com\", \"\/nic\/update\", userName, pwd, true);\r\n\tif (httpResult && httpResult->IsValid()) {\r\n\t\tDWORD dataLen;\r\n\t\tchar *data = (char*)httpResult->data.getData(&dataLen);\r\n\t\tfree(data);\r\n\t}\r\n\tdelete httpResult;\r\n}\r\n#endif\r\n\r\nTCHAR *DownloadUpdateIfNotDownloaded(const char *url)\r\n{\r\n\tconst TCHAR *filePathStr = NULL;\r\n\tconst char *fileName = StrFindLastChar(url, '\/');\r\n\tif (!fileName)\r\n\t\treturn NULL;\r\n\t++fileName;\r\n\tCString filePath = AppDataDir();\r\n\tfilePath += PATH_SEP_STR;\r\n\tfilePath += fileName;\r\n\r\n\tfilePathStr = filePath;\r\n\tif (FileOrDirExists(filePathStr))\r\n\t\treturn tstrdup(filePathStr);\r\n\r\n\tHttpResult *httpResult = HttpGet(url);\r\n\tif (!httpResult || !httpResult->IsValid())\r\n\t\tgoto Error;\r\n\r\n\tDWORD size;\r\n\tvoid *s = httpResult->data.getData(&size);\r\n\tif (!s)\r\n\t\tgoto Error;\r\n\r\n\tBOOL ok = FileWriteAll(filePathStr, (const char*)s, size);\r\n\tif (!ok)\r\n\t\tgoto Error;\r\n\r\n\treturn tstrdup(filePathStr);\r\nError:\r\n\tfree((void*)filePathStr);\r\n\treturn NULL;\r\n}\r\n\r\n\/\/ sends auto-update check. Returns url of the new version to download\r\n\/\/ if an update is available or NULL if update is not available\r\n\/\/ (or there was an error getting the upgrade info)\r\n\/\/ Caller needs to free() the result.\r\n\/\/ TODO: we ignore (and don't propagate) 'force' field in json response\r\nchar *GetUpdateUrl(const TCHAR *version, VersionUpdateCheckType type)\r\n{\r\n\tchar *downloadUrl = NULL;\r\n\tJsonEl *json = NULL;\r\n\r\n\tchar *typeStr = \"c\";\r\n\tif (UpdateCheckInstall == type)\r\n\t\ttypeStr = \"i\";\r\n\telse if (UpdateCheckUninstall == type)\r\n\t\ttypeStr = \"u\";\r\n\telse if (UpdateCheckVersionCheck == type)\r\n\t\ttypeStr = \"c\";\r\n\telse\r\n\t\tassert(0);\r\n\r\n\tCString url = AutoUpdateUrl(version, typeStr);\r\n\tHttpResult *res = HttpGet(AUTO_UPDATE_HOST, url);\r\n\tif (!res || !res->IsValid())\r\n\t\treturn NULL;\r\n\tchar *s = (char *)res->data.getData(NULL);\r\n\tjson = ParseJsonToDoc(s);\r\n\tJsonEl *upgradeAvailable = GetMapElByName(json, \"upgrade\");\r\n\tJsonElBool *upgradeAvailableBool = JsonElAsBool(upgradeAvailable);\r\n\tif (!upgradeAvailableBool || !upgradeAvailableBool->boolVal)\r\n\t\tgoto Exit;\r\n\tJsonEl *updateUrl = GetMapElByName(json, \"download\");\r\n\tif (!updateUrl)\r\n\t\tgoto Exit;\r\n\tdownloadUrl = StrDupSafe(JsonElAsStringVal(updateUrl));\r\nExit:\r\n\tJsonElFree(json);\r\n\tfree(s);\r\n\treturn downloadUrl;\r\n}\r\n<commit_msg>make it possible to test updates using local server<commit_after>#include \"stdafx.h\"\r\n\r\n#include \"SendIpUpdate.h\"\r\n\r\n#include \"MiscUtil.h\"\r\n#include \"Http.h\"\r\n#include \"JsonParser.h\"\r\n#include \"Prefs.h\"\r\n#include \"StrUtil.h\"\r\n\r\nchar* SendIpUpdate()\r\n{\r\n\tassert(CanSendIPUpdates());\r\n\tif (!CanSendIPUpdates())\r\n\t\treturn NULL;\r\n\r\n\tchar *res = NULL;\r\n\r\n\t\/\/ host = updates.opendns.com or website.dev6.sfo.opendns.com\r\n\t\/\/ url: \/nic\/update?token=mytoken&api_key=mykey?hostname=\r\n\t\/\/ responses:\r\n\t\/\/ \"badauth\"\r\n\t\/\/ \"nohost\"\r\n\t\/\/ \"good ${ip-addr}\"\r\n\tif (!g_pref_token)\r\n\t\treturn NULL;\r\n\tassert(g_pref_hostname);\r\n\r\n\tconst char *urlTxt = GetIpUpdateUrl(TRUE);\r\n\tconst char *host = GetIpUpdateHost();\r\n\r\n\tHttpResult *httpResult = HttpGet(host, urlTxt, INTERNET_DEFAULT_HTTPS_PORT);\r\n\tfree((void*)urlTxt);\r\n\tif (httpResult && httpResult->IsValid()) {\r\n\t\tres = (char*)httpResult->data.getData(NULL);\r\n\t}\r\n\tdelete httpResult;\r\n\treturn res;\r\n}\r\n\r\nchar *SendDnsOmaticUpdate()\r\n{\r\n\tassert(CanSendIPUpdates());\r\n\tif (!CanSendIPUpdates())\r\n\t\treturn NULL;\r\n\r\n\tchar *res = NULL;\r\n\r\n\t\/\/ TODO: do I need to append the following in url from GetIpUpdateUrl()?\r\n\t\/*URL$ = SetURLPart(URL$, \"myip\", ip$)\r\n\tURL$ = SetURLPart(URL$, \"wildcard\", \"NOCHG\")\r\n\tURL$ = SetURLPart(URL$, \"mx\", \"NOCHG\")\r\n\tURL$ = SetURLPart(URL$, \"backmx\", \"NOCHG\")*\/\r\n\r\n\tconst char *urlTxt = GetIpUpdateUrl(TRUE);\r\n\tconst char *host = GetIpUpdateDnsOMaticHost();\r\n\r\n\tHttpResult *httpResult = HttpGet(host, urlTxt, INTERNET_DEFAULT_HTTPS_PORT);\r\n\tfree((void*)urlTxt);\r\n\tif (httpResult && httpResult->IsValid()) {\r\n\t\tres = (char*)httpResult->data.getData(NULL);\r\n\t}\r\n\tdelete httpResult;\r\n\treturn res;\r\n}\r\n\r\nIpUpdateResult IpUpdateResultFromString(const char *s)\r\n{\r\n\tif (StrStartsWithI(s, \"The service is not available\"))\r\n\t\treturn IpUpdateNotAvailable;\r\n\tif (StrStartsWithI(s, \"good\"))\r\n\t\treturn IpUpdateOk;\r\n\tif (StrStartsWithI(s, \"nochg\"))\r\n\t\treturn IpUpdateOk;\r\n\tif (StrStartsWithI(s, \"!yours\"))\r\n\t\treturn IpUpdateNotYours;\r\n\tif (StrStartsWithI(s, \"badauth\"))\r\n\t\treturn IpUpdateBadAuth;\r\n\tif (StrStartsWithI(s, \"nohost\"))\r\n\t\treturn IpUpdateNoHost;\r\n\r\n\t\/\/ not sure if those really happen, they're supported by 1.3 client\r\n\tif (StrStartsWithI(s, \"dnserr\"))\r\n\t\treturn IpUpdateDnsErr;\r\n\r\n\tif (StrStartsWithI(s, \"911\"))\r\n\t\treturn IpUpdateDnsErr;\r\n\r\n\tif (StrStartsWithI(s, \"abuse\"))\r\n\t\treturn IpUpdateMiscErr;\r\n\r\n\tif (StrStartsWithI(s, \"notfqdn\"))\r\n\t\treturn IpUpdateMiscErr;\r\n\r\n\tif (StrStartsWithI(s, \"numhost\"))\r\n\t\treturn IpUpdateMiscErr;\r\n\r\n\tif (StrStartsWithI(s, \"badagent\"))\r\n\t\treturn IpUpdateMiscErr;\r\n\r\n\tif (StrStartsWithI(s, \"!donator\"))\r\n\t\treturn IpUpdateMiscErr;\r\n\r\n\tassert(0);\r\n\treturn IpUpdateOk;\r\n}\r\n\r\n#if 0\r\n\/\/ another way is to use username\/password and http basic auth\r\nchar* SendIpUpdate()\r\n{\r\n\t\/\/ host = \"updates.opendns.com\"\r\n\t\/\/ url = \"\/nic\/update?hostname=\" + network\r\n\t\/\/ responses:\r\n\t\/\/ \"badauth\"\r\n\t\/\/ \"nohost\"\r\n\t\/\/ \"good ${ip-addr}\"\r\n\tconst char *userName = \"\";\r\n\tconst char *pwd = \"\";\r\n\tHttpResult *httpResult = HttpGetWithBasicAuth(\"updates.opendns.com\", \"\/nic\/update\", userName, pwd, true);\r\n\tif (httpResult && httpResult->IsValid()) {\r\n\t\tDWORD dataLen;\r\n\t\tchar *data = (char*)httpResult->data.getData(&dataLen);\r\n\t\tfree(data);\r\n\t}\r\n\tdelete httpResult;\r\n}\r\n#endif\r\n\r\nTCHAR *DownloadUpdateIfNotDownloaded(const char *url)\r\n{\r\n\tconst TCHAR *filePathStr = NULL;\r\n\tconst char *fileName = StrFindLastChar(url, '\/');\r\n\tif (!fileName)\r\n\t\treturn NULL;\r\n\t++fileName;\r\n\tCString filePath = AppDataDir();\r\n\tfilePath += PATH_SEP_STR;\r\n\tfilePath += fileName;\r\n\r\n\tfilePathStr = filePath;\r\n\tif (FileOrDirExists(filePathStr))\r\n\t\treturn tstrdup(filePathStr);\r\n\r\n\tHttpResult *httpResult = HttpGet(url);\r\n\tif (!httpResult || !httpResult->IsValid())\r\n\t\tgoto Error;\r\n\r\n\tDWORD size;\r\n\tvoid *s = httpResult->data.getData(&size);\r\n\tif (!s)\r\n\t\tgoto Error;\r\n\r\n\tBOOL ok = FileWriteAll(filePathStr, (const char*)s, size);\r\n\tif (!ok)\r\n\t\tgoto Error;\r\n\r\n\treturn tstrdup(filePathStr);\r\nError:\r\n\tfree((void*)filePathStr);\r\n\treturn NULL;\r\n}\r\n\r\n#define TEST_UPDATE_LOCALLY 0\r\n\r\n\/\/ sends auto-update check. Returns url of the new version to download\r\n\/\/ if an update is available or NULL if update is not available\r\n\/\/ (or there was an error getting the upgrade info)\r\n\/\/ Caller needs to free() the result.\r\n\/\/ TODO: we ignore (and don't propagate) 'force' field in json response\r\nchar *GetUpdateUrl(const TCHAR *version, VersionUpdateCheckType type)\r\n{\r\n\tchar *downloadUrl = NULL;\r\n\tJsonEl *json = NULL;\r\n\r\n\tchar *typeStr = \"c\";\r\n\tif (UpdateCheckInstall == type)\r\n\t\ttypeStr = \"i\";\r\n\telse if (UpdateCheckUninstall == type)\r\n\t\ttypeStr = \"u\";\r\n\telse if (UpdateCheckVersionCheck == type)\r\n\t\ttypeStr = \"c\";\r\n\telse\r\n\t\tassert(0);\r\n\r\n\tCString url = AutoUpdateUrl(version, typeStr);\r\n#if TEST_UPDATE_LOCALLY\r\n\tHttpResult *res = HttpGet(\"127.0.0.1\", url, 8080);\r\n#else\r\n\tHttpResult *res = HttpGet(AUTO_UPDATE_HOST, url);\r\n#endif\r\n\tif (!res || !res->IsValid())\r\n\t\treturn NULL;\r\n\tchar *s = (char *)res->data.getData(NULL);\r\n\tjson = ParseJsonToDoc(s);\r\n\tJsonEl *upgradeAvailable = GetMapElByName(json, \"upgrade\");\r\n\tJsonElBool *upgradeAvailableBool = JsonElAsBool(upgradeAvailable);\r\n\tif (!upgradeAvailableBool || !upgradeAvailableBool->boolVal)\r\n\t\tgoto Exit;\r\n\tJsonEl *updateUrl = GetMapElByName(json, \"download\");\r\n\tif (!updateUrl)\r\n\t\tgoto Exit;\r\n\tdownloadUrl = StrDupSafe(JsonElAsStringVal(updateUrl));\r\nExit:\r\n\tJsonElFree(json);\r\n\tfree(s);\r\n\treturn downloadUrl;\r\n}\r\n<|endoftext|>"} {"text":"<commit_before>\/*\n Copyright 2010 Google Inc.\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n *\/\n\n#include \"SkBitmapCache.h\"\n\nstruct SkBitmapCache::Entry {\n Entry* fPrev;\n Entry* fNext;\n\n void* fBuffer;\n size_t fSize;\n SkBitmap fBitmap;\n\n Entry(const void* buffer, size_t size, const SkBitmap& bm) : fBitmap(bm) {\n fBuffer = sk_malloc_throw(size);\n fSize = size;\n memcpy(fBuffer, buffer, size);\n }\n\n ~Entry() { sk_free(fBuffer); }\n\n bool equals(const void* buffer, size_t size) const {\n return (fSize == size) && !memcmp(fBuffer, buffer, size);\n }\n};\n\nSkBitmapCache::SkBitmapCache(int max) : fMaxEntries(max) {\n fEntryCount = 0;\n fHead = fTail = NULL;\n\n this->validate();\n}\n\nSkBitmapCache::~SkBitmapCache() {\n this->validate();\n\n Entry* entry = fHead;\n while (entry) {\n Entry* next = entry->fNext;\n delete entry;\n entry = next;\n }\n}\n\nSkBitmapCache::Entry* SkBitmapCache::detach(Entry* entry) const {\n if (entry->fPrev) {\n SkASSERT(fHead != entry);\n entry->fPrev->fNext = entry->fNext;\n } else {\n SkASSERT(fHead == entry);\n fHead = entry->fNext;\n }\n if (entry->fNext) {\n SkASSERT(fTail != entry);\n entry->fNext->fPrev = entry->fPrev;\n } else {\n SkASSERT(fTail == entry);\n fTail = entry->fPrev;\n }\n return entry;\n}\n\nvoid SkBitmapCache::attachToHead(Entry* entry) const {\n entry->fPrev = NULL;\n entry->fNext = fHead;\n if (fHead) {\n fHead->fPrev = entry;\n } else {\n fTail = entry;\n }\n fHead = entry;\n}\n\nbool SkBitmapCache::find(const void* buffer, size_t size, SkBitmap* bm) const {\n AutoValidate av(this);\n\n Entry* entry = fHead;\n while (entry) {\n if (entry->equals(buffer, size)) {\n if (bm) {\n *bm = entry->fBitmap;\n }\n \/\/ move to the head of our list, so we purge it last\n this->detach(entry);\n this->attachToHead(entry);\n return true;\n }\n entry = entry->fNext;\n }\n return false;\n}\n\nvoid SkBitmapCache::add(const void* buffer, size_t len, const SkBitmap& bm) {\n AutoValidate av(this);\n \n if (fEntryCount == fMaxEntries) {\n if (fTail) {\n delete this->detach(fTail);\n }\n }\n\n Entry* entry = new Entry(buffer, len, bm);\n this->attachToHead(entry);\n fEntryCount += 1;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#ifdef SK_DEBUG\n\nvoid SkBitmapCache::validate() const {\n SkASSERT(fEntryCount >= 0 && fEntryCount <= fMaxEntries);\n \n if (fEntryCount > 0) {\n SkASSERT(NULL == fHead->fPrev);\n SkASSERT(NULL == fTail->fNext);\n\n if (fEntryCount == 1) {\n SkASSERT(fHead == fTail);\n } else {\n SkASSERT(fHead != fTail);\n }\n\n Entry* entry = fHead;\n int count = 0;\n while (entry) {\n count += 1;\n entry = entry->fNext;\n }\n SkASSERT(count == fEntryCount);\n \n entry = fTail;\n while (entry) {\n count -= 1;\n entry = entry->fPrev;\n }\n SkASSERT(0 == count);\n } else {\n SkASSERT(NULL == fHead);\n SkASSERT(NULL == fTail);\n } \n}\n\n#endif\n\n<commit_msg>fix fEntryCount when we purge a cache entry (bug caught by our validate())<commit_after>\/*\n Copyright 2010 Google Inc.\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n *\/\n\n#include \"SkBitmapCache.h\"\n\nstruct SkBitmapCache::Entry {\n Entry* fPrev;\n Entry* fNext;\n\n void* fBuffer;\n size_t fSize;\n SkBitmap fBitmap;\n\n Entry(const void* buffer, size_t size, const SkBitmap& bm) : fBitmap(bm) {\n fBuffer = sk_malloc_throw(size);\n fSize = size;\n memcpy(fBuffer, buffer, size);\n }\n\n ~Entry() { sk_free(fBuffer); }\n\n bool equals(const void* buffer, size_t size) const {\n return (fSize == size) && !memcmp(fBuffer, buffer, size);\n }\n};\n\nSkBitmapCache::SkBitmapCache(int max) : fMaxEntries(max) {\n fEntryCount = 0;\n fHead = fTail = NULL;\n\n this->validate();\n}\n\nSkBitmapCache::~SkBitmapCache() {\n this->validate();\n\n Entry* entry = fHead;\n while (entry) {\n Entry* next = entry->fNext;\n delete entry;\n entry = next;\n }\n}\n\nSkBitmapCache::Entry* SkBitmapCache::detach(Entry* entry) const {\n if (entry->fPrev) {\n SkASSERT(fHead != entry);\n entry->fPrev->fNext = entry->fNext;\n } else {\n SkASSERT(fHead == entry);\n fHead = entry->fNext;\n }\n if (entry->fNext) {\n SkASSERT(fTail != entry);\n entry->fNext->fPrev = entry->fPrev;\n } else {\n SkASSERT(fTail == entry);\n fTail = entry->fPrev;\n }\n return entry;\n}\n\nvoid SkBitmapCache::attachToHead(Entry* entry) const {\n entry->fPrev = NULL;\n entry->fNext = fHead;\n if (fHead) {\n fHead->fPrev = entry;\n } else {\n fTail = entry;\n }\n fHead = entry;\n}\n\nbool SkBitmapCache::find(const void* buffer, size_t size, SkBitmap* bm) const {\n AutoValidate av(this);\n\n Entry* entry = fHead;\n while (entry) {\n if (entry->equals(buffer, size)) {\n if (bm) {\n *bm = entry->fBitmap;\n }\n \/\/ move to the head of our list, so we purge it last\n this->detach(entry);\n this->attachToHead(entry);\n return true;\n }\n entry = entry->fNext;\n }\n return false;\n}\n\nvoid SkBitmapCache::add(const void* buffer, size_t len, const SkBitmap& bm) {\n AutoValidate av(this);\n\n if (fEntryCount == fMaxEntries) {\n SkASSERT(fTail);\n delete this->detach(fTail);\n fEntryCount -= 1;\n }\n\n Entry* entry = new Entry(buffer, len, bm);\n this->attachToHead(entry);\n fEntryCount += 1;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#ifdef SK_DEBUG\n\nvoid SkBitmapCache::validate() const {\n SkASSERT(fEntryCount >= 0 && fEntryCount <= fMaxEntries);\n\n if (fEntryCount > 0) {\n SkASSERT(NULL == fHead->fPrev);\n SkASSERT(NULL == fTail->fNext);\n\n if (fEntryCount == 1) {\n SkASSERT(fHead == fTail);\n } else {\n SkASSERT(fHead != fTail);\n }\n\n Entry* entry = fHead;\n int count = 0;\n while (entry) {\n count += 1;\n entry = entry->fNext;\n }\n SkASSERT(count == fEntryCount);\n\n entry = fTail;\n while (entry) {\n count -= 1;\n entry = entry->fPrev;\n }\n SkASSERT(0 == count);\n } else {\n SkASSERT(NULL == fHead);\n SkASSERT(NULL == fTail);\n }\n}\n\n#endif\n\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: ChartController_EditData.cxx,v $\n *\n * $Revision: 1.5 $\n *\n * last change: $Author: vg $ $Date: 2007-05-22 18:03:19 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_chart2.hxx\"\n#include \"ChartController.hxx\"\n#include \"macros.hxx\"\n\n#include \"dlg_DataEditor.hxx\"\n#include \"DataSourceHelper.hxx\"\n#include \"DiagramHelper.hxx\"\n#include \"ControllerLockGuard.hxx\"\n#include \"UndoGuard.hxx\"\n#include \"ResId.hxx\"\n#include \"Strings.hrc\"\n\n\/\/ for RET_OK\n#ifndef _SV_MSGBOX_HXX\n#include <vcl\/msgbox.hxx>\n#endif\n\n#ifndef _SV_SVAPP_HXX\n#include <vcl\/svapp.hxx>\n#endif\n#ifndef _VOS_MUTEX_HXX_\n#include <vos\/mutex.hxx>\n#endif\n\n#ifndef _COM_SUN_STAR_CHART2_XCHARTDOCUMENT_HPP_\n#include <com\/sun\/star\/chart2\/XChartDocument.hpp>\n#endif\n\nusing namespace ::com::sun::star;\n\nusing ::com::sun::star::uno::Reference;\nusing ::com::sun::star::uno::Sequence;\n\nnamespace chart\n{\n\nvoid ChartController::executeDispatch_EditData()\n{\n Reference< chart2::XChartDocument > xChartDoc( m_aModel->getModel(), uno::UNO_QUERY );\n if( xChartDoc.is())\n {\n Window* pParent( NULL );\n\n Reference< ::com::sun::star::chart2::data::XDataProvider > xDataProvider( xChartDoc->getDataProvider());\n\n {\n \/\/ \/--\n ::vos::OGuard aSolarGuard( Application::GetSolarMutex());\n UndoLiveUpdateGuardWithData aUndoGuard(\n ::rtl::OUString( String( SchResId( STR_ACTION_EDIT_CHART_DATA ))),\n m_aUndoManager, m_aModel->getModel());\n DataEditor aDataEditorDialog( pParent, xChartDoc, m_xCC );\n \/\/ the dialog has no OK\/Cancel\n aDataEditorDialog.Execute();\n aUndoGuard.commitAction();\n \/\/ \\--\n }\n }\n}\n\n} \/\/ namespace chart\n<commit_msg>INTEGRATION: CWS chart07 (1.5.12); FILE MERGED 2007\/06\/26 11:09:57 bm 1.5.12.2: #i78790# fix for (broken) gcc 3.3 for Mac OS\/X Panther applied 2007\/06\/25 12:52:11 bm 1.5.12.1: #i74653# store undo manager at model to be able to do an undo even after inplace re-activation<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: ChartController_EditData.cxx,v $\n *\n * $Revision: 1.6 $\n *\n * last change: $Author: rt $ $Date: 2007-07-25 08:42:58 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_chart2.hxx\"\n#include \"ChartController.hxx\"\n#include \"macros.hxx\"\n\n#include \"dlg_DataEditor.hxx\"\n#include \"DataSourceHelper.hxx\"\n#include \"DiagramHelper.hxx\"\n#include \"ControllerLockGuard.hxx\"\n#include \"UndoGuard.hxx\"\n#include \"ResId.hxx\"\n#include \"Strings.hrc\"\n\n\/\/ for RET_OK\n#ifndef _SV_MSGBOX_HXX\n#include <vcl\/msgbox.hxx>\n#endif\n\n#ifndef _SV_SVAPP_HXX\n#include <vcl\/svapp.hxx>\n#endif\n#ifndef _VOS_MUTEX_HXX_\n#include <vos\/mutex.hxx>\n#endif\n\n#ifndef _COM_SUN_STAR_CHART2_XCHARTDOCUMENT_HPP_\n#include <com\/sun\/star\/chart2\/XChartDocument.hpp>\n#endif\n\nusing namespace ::com::sun::star;\n\nusing ::com::sun::star::uno::Reference;\nusing ::com::sun::star::uno::Sequence;\n\nnamespace chart\n{\n\nvoid ChartController::executeDispatch_EditData()\n{\n Reference< chart2::XChartDocument > xChartDoc( m_aModel->getModel(), uno::UNO_QUERY );\n if( xChartDoc.is())\n {\n Window* pParent( NULL );\n\n Reference< ::com::sun::star::chart2::data::XDataProvider > xDataProvider( xChartDoc->getDataProvider());\n\n {\n \/\/ \/--\n ::vos::OGuard aSolarGuard( Application::GetSolarMutex());\n \/\/ using assignment for broken gcc 3.3\n UndoLiveUpdateGuardWithData aUndoGuard = UndoLiveUpdateGuardWithData(\n ::rtl::OUString( String( SchResId( STR_ACTION_EDIT_CHART_DATA ))),\n m_xUndoManager, m_aModel->getModel());\n DataEditor aDataEditorDialog( pParent, xChartDoc, m_xCC );\n \/\/ the dialog has no OK\/Cancel\n aDataEditorDialog.Execute();\n aUndoGuard.commitAction();\n \/\/ \\--\n }\n }\n}\n\n} \/\/ namespace chart\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n#include <exception>\nusing namespace std;\n\nclass QUEUE_FULL_EXCEPTION : public exception {\n const char * what() const throw() {\n return \"Queue is full\\n\";\n }\n};\n\nclass QUEUE_EMPTY_EXCEPTION : public exception {\n const char * what() const throw() {\n return \"Queue is empty\\n\";\n }\n};\n\n\ntemplate <class T>\nclass s_queue {\n T *arr;\n unsigned long long size;\n unsigned long long head;\n unsigned long long tail;\n unsigned long long items;\n \npublic:\n s_queue(unsigned long long size) {\n this-> size = size;\n arr = new T[size];\n head = 0;\n tail = 0;\n items = 0;\n }\n \n ~s_queue() {\n delete[] arr;\n }\n \n bool is_empty() {\n return items == 0;\n }\n \n void enqueue(T x) {\n \/\/ if queue is full, throw exception\n if (items == size) throw QUEUE_FULL_EXCEPTION();\n \n \/\/ when the queue is empty, set head to 0, tail to 1\n \/\/ and insert the new item\n if (is_empty()) {\n arr[0] = x;\n head = 0;\n tail = 1;\n items++;\n return;\n }\n \n \/\/ insert the item at current tail (tail is always empty)\n arr[tail] = x;\n\n \/\/ calculate new tail, if it goes beyond queue size, set it to start (0)\n if (++tail >= size) {\n tail = 0;\n }\n\n \/\/ increase the number of items\n items++;\n }\n \n T dequeue() {\n \/\/ if queue is empty, throw exception\n if (is_empty()) throw QUEUE_EMPTY_EXCEPTION();\n \n \/\/ hold the current element at 'head', this will be returned\n T item = arr[head];\n \n \/\/ calculate new head, if it goes beyond queue size, set it to start (0)\n if (++head >= size) {\n head = 0;\n }\n \n \/\/ decrease the number of items\n items--;\n \n return item;\n }\n};\n\nint main() {\n s_queue<int> queue(5);\n queue.enqueue(1);\n queue.enqueue(2);\n queue.enqueue(3);\n queue.enqueue(4);\n queue.enqueue(5);\n cout << queue.dequeue() << endl;\n cout << queue.dequeue() << endl;\n cout << queue.dequeue() << endl;\n cout << queue.dequeue() << endl;\n cout << queue.dequeue() << endl;\n \n s_queue<string> string_queue(5);\n string_queue.enqueue(\"hello!\");\n cout << string_queue.dequeue() << endl;\n\n return 0;\n}<commit_msg>Add ability to fetch item at head in circular queue<commit_after>#include <iostream>\n#include <exception>\nusing namespace std;\n\nclass QUEUE_FULL_EXCEPTION : public exception {\n const char * what() const throw() {\n return \"Queue is full\\n\";\n }\n};\n\nclass QUEUE_EMPTY_EXCEPTION : public exception {\n const char * what() const throw() {\n return \"Queue is empty\\n\";\n }\n};\n\n\ntemplate <class T>\nclass s_queue {\n T *arr;\n unsigned long long size;\n unsigned long long head;\n unsigned long long tail;\n unsigned long long items;\n \npublic:\n s_queue(unsigned long long size) {\n this-> size = size;\n arr = new T[size];\n head = 0;\n tail = 0;\n items = 0;\n }\n \n ~s_queue() {\n delete[] arr;\n }\n \n bool is_empty() {\n return items == 0;\n }\n \n \/\/ returns the item at the head\n T front() {\n if (is_empty()) throw QUEUE_EMPTY_EXCEPTION();\n return arr[head];\n }\n \n void enqueue(T x) {\n \/\/ if queue is full, throw exception\n if (items == size) throw QUEUE_FULL_EXCEPTION();\n \n \/\/ when the queue is empty, set head to 0, tail to 1\n \/\/ and insert the new item\n if (is_empty()) {\n arr[0] = x;\n head = 0;\n tail = 1;\n items++;\n return;\n }\n \n \/\/ insert the item at current tail (tail is always empty)\n arr[tail] = x;\n\n \/\/ calculate new tail, if it goes beyond queue size, set it to start (0)\n if (++tail >= size) {\n tail = 0;\n }\n\n \/\/ increase the number of items\n items++;\n }\n \n T dequeue() {\n \/\/ if queue is empty, throw exception\n if (is_empty()) throw QUEUE_EMPTY_EXCEPTION();\n \n \/\/ hold the current element at 'head', this will be returned\n T item = arr[head];\n \n \/\/ calculate new head, if it goes beyond queue size, set it to start (0)\n if (++head >= size) {\n head = 0;\n }\n \n \/\/ decrease the number of items\n items--;\n \n return item;\n }\n};\n\nint main() {\n s_queue<int> queue(5);\n queue.enqueue(1);\n queue.enqueue(2);\n queue.enqueue(3);\n queue.enqueue(4);\n queue.enqueue(5);\n cout << queue.dequeue() << endl;\n cout << queue.dequeue() << endl;\n cout << queue.dequeue() << endl;\n cout << queue.dequeue() << endl;\n cout << queue.dequeue() << endl;\n \n s_queue<string> string_queue(5);\n string_queue.enqueue(\"hello!\");\n cout << string_queue.dequeue() << endl;\n\n return 0;\n}<|endoftext|>"} {"text":"<commit_before>\/*\n Copyright (c) 2008 Tobias Koenig <tokoe@kde.org>\n Copyright (c) 2010 Volker Krause <vkrause@kde.org>\n\n This library is free software; you can redistribute it and\/or modify it\n under the terms of the GNU Library General Public License as published by\n the Free Software Foundation; either version 2 of the License, or (at your\n option) any later version.\n\n This library is distributed in the hope that it will be useful, but WITHOUT\n ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public\n License for more details.\n\n You should have received a copy of the GNU Library General Public License\n along with this library; see the file COPYING.LIB. If not, write to the\n Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA\n 02110-1301, USA.\n*\/\n\n#include \"nepomuksearchengine.h\"\n\n#include <akdebug.h>\n#include \"src\/nepomuk\/result.h\"\n\n#include \"entities.h\"\n#include \"storage\/notificationcollector.h\"\n#include \"storage\/selectquerybuilder.h\"\n#include \"notificationmanager.h\"\n#include \"libs\/xdgbasedirs_p.h\"\n\n#include <QtCore\/QDebug>\n#include <QtCore\/QUrl>\n#include <QMetaObject>\n#include <qdbusservicewatcher.h>\n#include <qdbusconnection.h>\n#include <QSettings>\n\nusing namespace Akonadi;\n\nstatic qint64 resultToId( const Nepomuk::Query::Result &result )\n{\n const Soprano::Node &property = result.requestProperty(QUrl( QLatin1String( \"http:\/\/akonadi-project.org\/ontologies\/aneo#akonadiItemId\" ) ));\n if (!(property.isValid() && property.isLiteral() && property.literal().isString())) {\n qWarning() << \"Failed to get requested akonadiItemId property\";\n qDebug() << \"AkonadiItemId missing in query results!\" << result.resourceUri() << property.isValid() << property.isLiteral() << property.literal().isString() << property.literal().type() << result.requestProperties().size();\n\/\/ qDebug() << result.requestProperties().values().first().toString();\n return -1;\n }\n return property.literal().toString().toLongLong();\n}\n\nNepomukSearchEngine::NepomukSearchEngine( QObject* parent )\n : QObject( parent ),\n mCollector( new NotificationCollector( this ) ),\n m_liveSearchEnabled( true )\n{\n NotificationManager::self()->connectNotificationCollector( mCollector );\n\n QDBusServiceWatcher *watcher =\n new QDBusServiceWatcher( QLatin1String(\"org.kde.nepomuk.services.nepomukqueryservice\"),\n QDBusConnection::sessionBus(),\n QDBusServiceWatcher::WatchForRegistration, this );\n connect( watcher, SIGNAL(serviceRegistered(QString)), SLOT(reloadSearches()) );\n\n if ( Nepomuk::Query::QueryServiceClient::serviceAvailable() ) {\n reloadSearches();\n } else {\n \/\/ FIXME: try to start the nepomuk server\n akError() << \"Nepomuk Query Server not available\";\n }\n\n const QSettings settings(XdgBaseDirs::akonadiServerConfigFile(), QSettings::IniFormat);\n m_liveSearchEnabled = settings.value(QLatin1String(\"Nepomuk\/LiveSearchEnabled\"), false).toBool();\n}\n\nNepomukSearchEngine::~NepomukSearchEngine()\n{\n stopSearches();\n}\n\nvoid NepomukSearchEngine::addSearch( const Collection &collection )\n{\n if ( collection.queryLanguage() != QLatin1String( \"SPARQL\" ) )\n return;\n const QString &q = collection.queryString();\n\n if ( q.size() >= 32768 ) {\n qWarning() << \"The query is at least 32768 chars long, which is the maximum size supported by the akonadi db schema. The query is therefore most likely truncated and will not be executed.\";\n return;\n }\n\n \/\/FIXME the requested property must be passed to here from the calling code\n \/\/Ideally the Query is passed as object so we can check here for the akonadiItemId property, and add it if missing\n if (!q.contains(QString::fromLatin1(\"reqProp1\")) || !q.contains(QString::fromLatin1(\"http:\/\/akonadi-project.org\/ontologies\/aneo#akonadiItemId\"))) {\n qWarning() << \"The query MUST contain exactly one required property (http:\/\/akonadi-project.org\/ontologies\/aneo#akonadiItemId), if another property is additionally requested or the akonadiItemId is missing the search will fail (due to this hack)\";\n qWarning() << q;\n return;\n }\n\n Nepomuk::Query::QueryServiceClient *query = new Nepomuk::Query::QueryServiceClient( this );\n\n connect( query, SIGNAL(newEntries(QList<Nepomuk::Query::Result>)),\n this, SLOT(hitsAdded(QList<Nepomuk::Query::Result>)) );\n connect( query, SIGNAL(entriesRemoved(QList<Nepomuk::Query::Result>)),\n this, SLOT(hitsRemoved(QList<Nepomuk::Query::Result>)) );\n connect( query, SIGNAL(finishedListing()),\n this, SLOT(finishedListing()) );\n\n mMutex.lock();\n mQueryMap.insert( query, collection.id() );\n mQueryInvMap.insert( collection.id(), query ); \/\/ needed for fast lookup in removeSearch()\n mMutex.unlock();\n\n QHash<QString, QString> encodedRps;\n encodedRps.insert( QString::fromLatin1( \"reqProp1\" ), QUrl(QString::fromLatin1(\"http:\/\/akonadi-project.org\/ontologies\/aneo#akonadiItemId\")).toString() ); \/\/FIXME hack because the reqProp is not passed to here by the caller\n query->query( collection.queryString(), encodedRps );\n}\n\nvoid NepomukSearchEngine::removeSearch( qint64 collectionId )\n{\n Nepomuk::Query::QueryServiceClient *query = mQueryInvMap.value( collectionId );\n if ( !query ) {\n qWarning() << \"Nepomuk QueryServer: Query could not be removed!\";\n return;\n }\n\n query->close();\n\n \/\/ cleanup mappings\n mMutex.lock();\n mQueryInvMap.remove( collectionId );\n mQueryMap.remove( query );\n mMutex.unlock();\n\n query->deleteLater();\n}\n\nvoid NepomukSearchEngine::reloadSearches()\n{\n akDebug() << this << sender();\n SelectQueryBuilder<Collection> qb;\n qb.addValueCondition( Collection::queryLanguageFullColumnName(), Query::Equals, QLatin1String( \"SPARQL\" ) );\n if ( !qb.exec() ) {\n qWarning() << \"Nepomuk QueryServer: Unable to execute query!\";\n return;\n }\n\n Q_FOREACH ( const Collection &collection, qb.result() ) {\n mMutex.lock();\n if ( mQueryInvMap.contains( collection.id() ) ) {\n mMutex.unlock();\n akDebug() << \"updating search\" << collection.name();\n removeSearch( collection.id() );\n } else {\n mMutex.unlock();\n akDebug() << \"adding search\" << collection.name();\n }\n addSearch( collection );\n }\n}\n\nvoid NepomukSearchEngine::stopSearches()\n{\n SelectQueryBuilder<Collection> qb;\n qb.addValueCondition( Collection::queryLanguageFullColumnName(), Query::Equals, QLatin1String( \"SPARQL\" ) );\n if ( !qb.exec() ) {\n qWarning() << \"Nepomuk QueryServer: Unable to execute query!\";\n return;\n }\n\n Q_FOREACH ( const Collection &collection, qb.result() ) {\n akDebug() << \"removing search\" << collection.name();\n removeSearch( collection.id() );\n }\n}\n\nvoid NepomukSearchEngine::hitsAdded( const QList<Nepomuk::Query::Result>& entries )\n{\n Nepomuk::Query::QueryServiceClient *query = qobject_cast<Nepomuk::Query::QueryServiceClient*>( sender() );\n if ( !query ) {\n qWarning() << \"Nepomuk QueryServer: Got signal from non-existing search query!\";\n return;\n }\n\n mMutex.lock();\n qint64 collectionId = mQueryMap.value( query );\n mMutex.unlock();\n const Collection collection = Collection::retrieveById( collectionId );\n\n PimItem::List items;\n Q_FOREACH( const Nepomuk::Query::Result &result, entries ) {\n const qint64 itemId = resultToId( result );\n\n if ( itemId == -1 )\n continue;\n\n Entity::addToRelation<CollectionPimItemRelation>( collectionId, itemId );\n items << PimItem::retrieveById( itemId );\n }\n mCollector->itemsLinked( items, collection );\n mCollector->dispatchNotifications();\n}\n\nvoid NepomukSearchEngine::hitsRemoved( const QList<Nepomuk::Query::Result>& entries )\n{\n Nepomuk::Query::QueryServiceClient *query = qobject_cast<Nepomuk::Query::QueryServiceClient*>( sender() );\n if ( !query ) {\n qWarning() << \"Nepomuk QueryServer: Got signal from non-existing search query!\";\n return;\n }\n\n mMutex.lock();\n qint64 collectionId = mQueryMap.value( query );\n mMutex.unlock();\n const Collection collection = Collection::retrieveById( collectionId );\n PimItem::List items;\n Q_FOREACH( const Nepomuk::Query::Result &result, entries ) {\n const qint64 itemId = resultToId( result );\n\n if ( itemId == -1 )\n continue;\n\n Entity::removeFromRelation<CollectionPimItemRelation>( collectionId, itemId );\n items << PimItem::retrieveById( itemId );\n }\n\n mCollector->itemsUnlinked( items, collection );\n mCollector->dispatchNotifications();\n}\n\nvoid NepomukSearchEngine::finishedListing()\n{\n if (m_liveSearchEnabled)\n return;\n\n Nepomuk::Query::QueryServiceClient *query = qobject_cast<Nepomuk::Query::QueryServiceClient*>( sender() );\n if ( !query ) {\n qWarning() << Q_FUNC_INFO << \"Nepomuk QueryServer: Got signal from non-existing search query!\";\n return;\n }\n\n mMutex.lock();\n qint64 collectionId = mQueryMap.value( query );\n mMutex.unlock();\n\n removeSearch(collectionId);\n}\n<commit_msg>coding style for nepomuksearchengine.cpp<commit_after>\/*\n Copyright (c) 2008 Tobias Koenig <tokoe@kde.org>\n Copyright (c) 2010 Volker Krause <vkrause@kde.org>\n\n This library is free software; you can redistribute it and\/or modify it\n under the terms of the GNU Library General Public License as published by\n the Free Software Foundation; either version 2 of the License, or (at your\n option) any later version.\n\n This library is distributed in the hope that it will be useful, but WITHOUT\n ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public\n License for more details.\n\n You should have received a copy of the GNU Library General Public License\n along with this library; see the file COPYING.LIB. If not, write to the\n Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA\n 02110-1301, USA.\n*\/\n\n#include \"nepomuksearchengine.h\"\n\n#include <akdebug.h>\n#include \"src\/nepomuk\/result.h\"\n\n#include \"entities.h\"\n#include \"storage\/notificationcollector.h\"\n#include \"storage\/selectquerybuilder.h\"\n#include \"notificationmanager.h\"\n#include \"libs\/xdgbasedirs_p.h\"\n\n#include <QtCore\/QDebug>\n#include <QtCore\/QUrl>\n#include <QMetaObject>\n#include <qdbusservicewatcher.h>\n#include <qdbusconnection.h>\n#include <QSettings>\n\nusing namespace Akonadi;\n\nstatic qint64 resultToId( const Nepomuk::Query::Result &result )\n{\n const Soprano::Node &property = result.requestProperty(QUrl( QLatin1String( \"http:\/\/akonadi-project.org\/ontologies\/aneo#akonadiItemId\" ) ));\n if (!(property.isValid() && property.isLiteral() && property.literal().isString())) {\n qWarning() << \"Failed to get requested akonadiItemId property\";\n qDebug() << \"AkonadiItemId missing in query results!\" << result.resourceUri() << property.isValid() << property.isLiteral() << property.literal().isString() << property.literal().type() << result.requestProperties().size();\n\/\/ qDebug() << result.requestProperties().values().first().toString();\n return -1;\n }\n return property.literal().toString().toLongLong();\n}\n\nNepomukSearchEngine::NepomukSearchEngine( QObject* parent )\n : QObject( parent ),\n mCollector( new NotificationCollector( this ) ),\n m_liveSearchEnabled( true )\n{\n NotificationManager::self()->connectNotificationCollector( mCollector );\n\n QDBusServiceWatcher *watcher =\n new QDBusServiceWatcher( QLatin1String(\"org.kde.nepomuk.services.nepomukqueryservice\"),\n QDBusConnection::sessionBus(),\n QDBusServiceWatcher::WatchForRegistration, this );\n connect( watcher, SIGNAL(serviceRegistered(QString)), SLOT(reloadSearches()) );\n\n if ( Nepomuk::Query::QueryServiceClient::serviceAvailable() ) {\n reloadSearches();\n } else {\n \/\/ FIXME: try to start the nepomuk server\n akError() << \"Nepomuk Query Server not available\";\n }\n\n const QSettings settings(XdgBaseDirs::akonadiServerConfigFile(), QSettings::IniFormat);\n m_liveSearchEnabled = settings.value(QLatin1String(\"Nepomuk\/LiveSearchEnabled\"), false).toBool();\n}\n\nNepomukSearchEngine::~NepomukSearchEngine()\n{\n stopSearches();\n}\n\nvoid NepomukSearchEngine::addSearch( const Collection &collection )\n{\n if ( collection.queryLanguage() != QLatin1String( \"SPARQL\" ) ) {\n return;\n }\n const QString &q = collection.queryString();\n\n if ( q.size() >= 32768 ) {\n qWarning() << \"The query is at least 32768 chars long, which is the maximum size supported by the akonadi db schema. The query is therefore most likely truncated and will not be executed.\";\n return;\n }\n\n \/\/FIXME the requested property must be passed to here from the calling code\n \/\/Ideally the Query is passed as object so we can check here for the akonadiItemId property, and add it if missing\n if (!q.contains(QString::fromLatin1(\"reqProp1\")) || !q.contains(QString::fromLatin1(\"http:\/\/akonadi-project.org\/ontologies\/aneo#akonadiItemId\"))) {\n qWarning() << \"The query MUST contain exactly one required property (http:\/\/akonadi-project.org\/ontologies\/aneo#akonadiItemId), if another property is additionally requested or the akonadiItemId is missing the search will fail (due to this hack)\";\n qWarning() << q;\n return;\n }\n\n Nepomuk::Query::QueryServiceClient *query = new Nepomuk::Query::QueryServiceClient( this );\n\n connect( query, SIGNAL(newEntries(QList<Nepomuk::Query::Result>)),\n this, SLOT(hitsAdded(QList<Nepomuk::Query::Result>)) );\n connect( query, SIGNAL(entriesRemoved(QList<Nepomuk::Query::Result>)),\n this, SLOT(hitsRemoved(QList<Nepomuk::Query::Result>)) );\n connect( query, SIGNAL(finishedListing()),\n this, SLOT(finishedListing()) );\n\n mMutex.lock();\n mQueryMap.insert( query, collection.id() );\n mQueryInvMap.insert( collection.id(), query ); \/\/ needed for fast lookup in removeSearch()\n mMutex.unlock();\n\n QHash<QString, QString> encodedRps;\n encodedRps.insert( QString::fromLatin1( \"reqProp1\" ), QUrl(QString::fromLatin1(\"http:\/\/akonadi-project.org\/ontologies\/aneo#akonadiItemId\")).toString() ); \/\/FIXME hack because the reqProp is not passed to here by the caller\n query->query( collection.queryString(), encodedRps );\n}\n\nvoid NepomukSearchEngine::removeSearch( qint64 collectionId )\n{\n Nepomuk::Query::QueryServiceClient *query = mQueryInvMap.value( collectionId );\n if ( !query ) {\n qWarning() << \"Nepomuk QueryServer: Query could not be removed!\";\n return;\n }\n\n query->close();\n\n \/\/ cleanup mappings\n mMutex.lock();\n mQueryInvMap.remove( collectionId );\n mQueryMap.remove( query );\n mMutex.unlock();\n\n query->deleteLater();\n}\n\nvoid NepomukSearchEngine::reloadSearches()\n{\n akDebug() << this << sender();\n SelectQueryBuilder<Collection> qb;\n qb.addValueCondition( Collection::queryLanguageFullColumnName(), Query::Equals, QLatin1String( \"SPARQL\" ) );\n if ( !qb.exec() ) {\n qWarning() << \"Nepomuk QueryServer: Unable to execute query!\";\n return;\n }\n\n Q_FOREACH ( const Collection &collection, qb.result() ) {\n mMutex.lock();\n if ( mQueryInvMap.contains( collection.id() ) ) {\n mMutex.unlock();\n akDebug() << \"updating search\" << collection.name();\n removeSearch( collection.id() );\n } else {\n mMutex.unlock();\n akDebug() << \"adding search\" << collection.name();\n }\n addSearch( collection );\n }\n}\n\nvoid NepomukSearchEngine::stopSearches()\n{\n SelectQueryBuilder<Collection> qb;\n qb.addValueCondition( Collection::queryLanguageFullColumnName(), Query::Equals, QLatin1String( \"SPARQL\" ) );\n if ( !qb.exec() ) {\n qWarning() << \"Nepomuk QueryServer: Unable to execute query!\";\n return;\n }\n\n Q_FOREACH ( const Collection &collection, qb.result() ) {\n akDebug() << \"removing search\" << collection.name();\n removeSearch( collection.id() );\n }\n}\n\nvoid NepomukSearchEngine::hitsAdded( const QList<Nepomuk::Query::Result>& entries )\n{\n Nepomuk::Query::QueryServiceClient *query = qobject_cast<Nepomuk::Query::QueryServiceClient*>( sender() );\n if ( !query ) {\n qWarning() << \"Nepomuk QueryServer: Got signal from non-existing search query!\";\n return;\n }\n\n mMutex.lock();\n qint64 collectionId = mQueryMap.value( query );\n mMutex.unlock();\n const Collection collection = Collection::retrieveById( collectionId );\n\n PimItem::List items;\n Q_FOREACH( const Nepomuk::Query::Result &result, entries ) {\n const qint64 itemId = resultToId( result );\n\n if ( itemId == -1 ) {\n continue;\n }\n\n Entity::addToRelation<CollectionPimItemRelation>( collectionId, itemId );\n items << PimItem::retrieveById( itemId );\n }\n mCollector->itemsLinked( items, collection );\n mCollector->dispatchNotifications();\n}\n\nvoid NepomukSearchEngine::hitsRemoved( const QList<Nepomuk::Query::Result>& entries )\n{\n Nepomuk::Query::QueryServiceClient *query = qobject_cast<Nepomuk::Query::QueryServiceClient*>( sender() );\n if ( !query ) {\n qWarning() << \"Nepomuk QueryServer: Got signal from non-existing search query!\";\n return;\n }\n\n mMutex.lock();\n qint64 collectionId = mQueryMap.value( query );\n mMutex.unlock();\n const Collection collection = Collection::retrieveById( collectionId );\n PimItem::List items;\n Q_FOREACH( const Nepomuk::Query::Result &result, entries ) {\n const qint64 itemId = resultToId( result );\n\n if ( itemId == -1 ) {\n continue;\n }\n\n Entity::removeFromRelation<CollectionPimItemRelation>( collectionId, itemId );\n items << PimItem::retrieveById( itemId );\n }\n\n mCollector->itemsUnlinked( items, collection );\n mCollector->dispatchNotifications();\n}\n\nvoid NepomukSearchEngine::finishedListing()\n{\n if (m_liveSearchEnabled) {\n return;\n }\n\n Nepomuk::Query::QueryServiceClient *query = qobject_cast<Nepomuk::Query::QueryServiceClient*>( sender() );\n if ( !query ) {\n qWarning() << Q_FUNC_INFO << \"Nepomuk QueryServer: Got signal from non-existing search query!\";\n return;\n }\n\n mMutex.lock();\n qint64 collectionId = mQueryMap.value( query );\n mMutex.unlock();\n\n removeSearch(collectionId);\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"browser\/win\/inspectable_web_contents_view_win.h\"\n\n#include \"browser\/browser_client.h\"\n#include \"browser\/inspectable_web_contents_impl.h\"\n#include \"browser\/win\/devtools_window.h\"\n\n#include \"content\/public\/browser\/web_contents_view.h\"\n#include \"ui\/gfx\/win\/hwnd_util.h\"\n#include \"ui\/views\/controls\/single_split_view.h\"\n#include \"ui\/views\/controls\/webview\/webview.h\"\n#include \"ui\/views\/view.h\"\n\nnamespace brightray {\n\nnamespace {\n\nconst int kWindowInset = 100;\n\n}\n\nclass ContainerView : public views::View {\n public:\n explicit ContainerView(InspectableWebContentsViewWin* web_contents_view)\n : container_view_created_(false),\n web_view_(new views::WebView(NULL)),\n web_contents_view_(web_contents_view) {\n set_owned_by_client();\n web_view_->set_owned_by_client();\n web_view_->SetWebContents(\n web_contents_view_->inspectable_web_contents()->GetWebContents());\n }\n\n views::View* GetWebView() const {\n return web_view_.get();\n }\n\n void ShowDevTools() {\n if (IsDevToolsViewShowing())\n return;\n\n RemoveChildView(web_view_.get());\n devtools_view_ = new views::WebView(NULL);\n devtools_view_->SetWebContents(web_contents_view_->\n inspectable_web_contents()->devtools_web_contents());\n split_view_.reset(new views::SingleSplitView(\n web_view_.get(),\n devtools_view_,\n views::SingleSplitView::VERTICAL_SPLIT,\n NULL));\n AddChildView(split_view_.get());\n Layout();\n devtools_view_->RequestFocus();\n }\n\n void CloseDevTools() {\n if (!IsDevToolsViewShowing())\n return;\n\n RemoveChildView(split_view_.get());\n split_view_.reset();\n AddChildView(web_view_.get());\n Layout();\n }\n\n bool IsDevToolsViewShowing() {\n return split_view_;\n }\n\n private:\n \/\/ views::View:\n virtual void Layout() OVERRIDE {\n if (split_view_)\n split_view_->SetBounds(0, 0, width(), height());\n else\n web_view_->SetBounds(0, 0, width(), height());\n }\n\n virtual void ViewHierarchyChanged(\n const ViewHierarchyChangedDetails& details) OVERRIDE {\n View::ViewHierarchyChanged(details);\n \/\/ We're not using child == this because a Widget may not be\n \/\/ available when this is added to the hierarchy.\n if (details.is_add && GetWidget() && !container_view_created_) {\n container_view_created_ = true;\n AddChildView(web_view_.get());\n }\n }\n\n \/\/ True if the container view has already been created, or false otherwise.\n bool container_view_created_;\n\n scoped_ptr<views::WebView> web_view_;\n scoped_ptr<views::SingleSplitView> split_view_;\n views::WebView* devtools_view_; \/\/ Owned by split_view_.\n\n InspectableWebContentsViewWin* web_contents_view_;\n};\n\nInspectableWebContentsView* CreateInspectableContentsView(\n InspectableWebContentsImpl* inspectable_web_contents) {\n return new InspectableWebContentsViewWin(inspectable_web_contents);\n}\n\nInspectableWebContentsViewWin::InspectableWebContentsViewWin(\n InspectableWebContentsImpl* inspectable_web_contents)\n : inspectable_web_contents_(inspectable_web_contents),\n container_(new ContainerView(this)) {\n}\n\nInspectableWebContentsViewWin::~InspectableWebContentsViewWin() {\n if (devtools_window_)\n DestroyWindow(devtools_window_->hwnd());\n}\n\nviews::View* InspectableWebContentsViewWin::GetView() const {\n return container_.get();\n}\n\nviews::View* InspectableWebContentsViewWin::GetWebView() const {\n return container_->GetWebView();\n}\n\ngfx::NativeView InspectableWebContentsViewWin::GetNativeView() const {\n auto web_contents = inspectable_web_contents_->GetWebContents();\n return web_contents->GetView()->GetNativeView();\n}\n\nvoid InspectableWebContentsViewWin::ShowDevTools() {\n container_->ShowDevTools();\n return;\n\n if (!devtools_window_) {\n devtools_window_ = DevToolsWindow::Create(this)->AsWeakPtr();\n devtools_window_->Init(HWND_DESKTOP, gfx::Rect());\n }\n\n auto contents_view = inspectable_web_contents_->GetWebContents()->GetView();\n auto size = contents_view->GetContainerSize();\n size.Enlarge(-kWindowInset, -kWindowInset);\n gfx::CenterAndSizeWindow(contents_view->GetNativeView(),\n devtools_window_->hwnd(),\n size);\n\n ShowWindow(devtools_window_->hwnd(), SW_SHOWNORMAL);\n}\n\nvoid InspectableWebContentsViewWin::CloseDevTools() {\n container_->CloseDevTools();\n return;\n\n if (!devtools_window_)\n return;\n SendMessage(devtools_window_->hwnd(), WM_CLOSE, 0, 0);\n}\n\nbool InspectableWebContentsViewWin::IsDevToolsViewShowing() {\n return container_->IsDevToolsViewShowing() || devtools_window_;\n}\n\nbool InspectableWebContentsViewWin::SetDockSide(const std::string& side) {\n return false;\n}\n\n} \/\/ namespace brightray\n<commit_msg>Implement setting dock side.<commit_after>#include \"browser\/win\/inspectable_web_contents_view_win.h\"\n\n#include \"browser\/browser_client.h\"\n#include \"browser\/inspectable_web_contents_impl.h\"\n#include \"browser\/win\/devtools_window.h\"\n\n#include \"content\/public\/browser\/web_contents_view.h\"\n#include \"ui\/gfx\/win\/hwnd_util.h\"\n#include \"ui\/views\/controls\/single_split_view.h\"\n#include \"ui\/views\/controls\/webview\/webview.h\"\n#include \"ui\/views\/view.h\"\n\nnamespace brightray {\n\nnamespace {\n\nconst int kWindowInset = 100;\n\n}\n\nclass ContainerView : public views::View {\n public:\n explicit ContainerView(InspectableWebContentsViewWin* web_contents_view)\n : container_view_created_(false),\n dockside_(\"bottom\"),\n web_view_(new views::WebView(NULL)),\n web_contents_view_(web_contents_view) {\n set_owned_by_client();\n web_view_->set_owned_by_client();\n web_view_->SetWebContents(\n web_contents_view_->inspectable_web_contents()->GetWebContents());\n }\n\n views::View* GetWebView() const {\n return web_view_.get();\n }\n\n void ShowDevTools() {\n if (IsDevToolsViewShowing())\n return;\n\n RemoveChildView(web_view_.get());\n devtools_view_ = new views::WebView(NULL);\n devtools_view_->SetWebContents(web_contents_view_->\n inspectable_web_contents()->devtools_web_contents());\n split_view_.reset(new views::SingleSplitView(\n web_view_.get(),\n devtools_view_,\n GetSplitViewOrientation(),\n NULL));\n split_view_->set_divider_offset(GetSplitVievDividerOffset());\n AddChildView(split_view_.get());\n Layout();\n\n devtools_view_->RequestFocus();\n }\n\n void CloseDevTools() {\n if (!IsDevToolsViewShowing())\n return;\n\n RemoveChildView(split_view_.get());\n split_view_.reset();\n AddChildView(web_view_.get());\n Layout();\n }\n\n bool IsDevToolsViewShowing() {\n return split_view_;\n }\n\n bool SetDockSide(const std::string& side) {\n if (side != \"bottom\" && side != \"right\")\n return false; \/\/ unsupported display location\n if (dockside_ == side)\n return true; \/\/ no change from current location\n\n dockside_ = side;\n if (!IsDevToolsViewShowing())\n return true;\n\n split_view_->set_orientation(GetSplitViewOrientation());\n split_view_->set_divider_offset(GetSplitVievDividerOffset());\n split_view_->Layout();\n return true;\n }\n\n private:\n \/\/ views::View:\n virtual void Layout() OVERRIDE {\n if (split_view_)\n split_view_->SetBounds(0, 0, width(), height());\n else\n web_view_->SetBounds(0, 0, width(), height());\n }\n\n virtual void ViewHierarchyChanged(\n const ViewHierarchyChangedDetails& details) OVERRIDE {\n View::ViewHierarchyChanged(details);\n \/\/ We're not using child == this because a Widget may not be\n \/\/ available when this is added to the hierarchy.\n if (details.is_add && GetWidget() && !container_view_created_) {\n container_view_created_ = true;\n AddChildView(web_view_.get());\n }\n }\n\n views::SingleSplitView::Orientation GetSplitViewOrientation() const {\n if (dockside_ == \"bottom\")\n return views::SingleSplitView::VERTICAL_SPLIT;\n else\n return views::SingleSplitView::HORIZONTAL_SPLIT;\n }\n\n int GetSplitVievDividerOffset() const {\n if (dockside_ == \"bottom\")\n return height() * 2 \/ 3;\n else\n return width() * 2 \/ 3;\n }\n\n \/\/ True if the container view has already been created, or false otherwise.\n bool container_view_created_;\n\n std::string dockside_;\n\n scoped_ptr<views::WebView> web_view_;\n scoped_ptr<views::SingleSplitView> split_view_;\n views::WebView* devtools_view_; \/\/ Owned by split_view_.\n\n InspectableWebContentsViewWin* web_contents_view_;\n};\n\nInspectableWebContentsView* CreateInspectableContentsView(\n InspectableWebContentsImpl* inspectable_web_contents) {\n return new InspectableWebContentsViewWin(inspectable_web_contents);\n}\n\nInspectableWebContentsViewWin::InspectableWebContentsViewWin(\n InspectableWebContentsImpl* inspectable_web_contents)\n : inspectable_web_contents_(inspectable_web_contents),\n container_(new ContainerView(this)) {\n}\n\nInspectableWebContentsViewWin::~InspectableWebContentsViewWin() {\n if (devtools_window_)\n DestroyWindow(devtools_window_->hwnd());\n}\n\nviews::View* InspectableWebContentsViewWin::GetView() const {\n return container_.get();\n}\n\nviews::View* InspectableWebContentsViewWin::GetWebView() const {\n return container_->GetWebView();\n}\n\ngfx::NativeView InspectableWebContentsViewWin::GetNativeView() const {\n auto web_contents = inspectable_web_contents_->GetWebContents();\n return web_contents->GetView()->GetNativeView();\n}\n\nvoid InspectableWebContentsViewWin::ShowDevTools() {\n container_->ShowDevTools();\n return;\n\n if (!devtools_window_) {\n devtools_window_ = DevToolsWindow::Create(this)->AsWeakPtr();\n devtools_window_->Init(HWND_DESKTOP, gfx::Rect());\n }\n\n auto contents_view = inspectable_web_contents_->GetWebContents()->GetView();\n auto size = contents_view->GetContainerSize();\n size.Enlarge(-kWindowInset, -kWindowInset);\n gfx::CenterAndSizeWindow(contents_view->GetNativeView(),\n devtools_window_->hwnd(),\n size);\n\n ShowWindow(devtools_window_->hwnd(), SW_SHOWNORMAL);\n}\n\nvoid InspectableWebContentsViewWin::CloseDevTools() {\n container_->CloseDevTools();\n return;\n\n if (!devtools_window_)\n return;\n SendMessage(devtools_window_->hwnd(), WM_CLOSE, 0, 0);\n}\n\nbool InspectableWebContentsViewWin::IsDevToolsViewShowing() {\n return container_->IsDevToolsViewShowing() || devtools_window_;\n}\n\nbool InspectableWebContentsViewWin::SetDockSide(const std::string& side) {\n return container_->SetDockSide(side);\n}\n\n} \/\/ namespace brightray\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.\n#include <vespa\/vespalib\/testkit\/test_kit.h>\n\n#include <vespa\/eval\/eval\/value_type.h>\n#include <vespa\/searchlib\/fef\/feature_type.h>\n#include <vespa\/searchlib\/fef\/featurenameparser.h>\n#include <vespa\/searchlib\/features\/rankingexpressionfeature.h>\n#include <vespa\/searchlib\/fef\/test\/dummy_dependency_handler.h>\n#include <vespa\/searchlib\/fef\/test\/indexenvironment.h>\n#include <vespa\/searchlib\/fef\/test\/queryenvironment.h>\n\nusing namespace search::features;\nusing namespace search::features::rankingexpression;\nusing namespace search::fef::test;\nusing namespace search::fef;\nusing namespace vespalib::eval;\n\nusing TypeMap = std::map<vespalib::string,vespalib::string>;\n\nstruct DummyExecutor : FeatureExecutor {\n void execute(uint32_t) override {}\n};\n\nstruct DummyExpression : IntrinsicExpression {\n FeatureType type;\n DummyExpression(const FeatureType &type_in) : type(type_in) {}\n vespalib::string describe_self() const override { return \"dummy\"; }\n const FeatureType &result_type() const override { return type; }\n void prepare_shared_state(const QueryEnv &, IObjectStore &) const override {\n }\n FeatureExecutor &create_executor(const QueryEnv &, vespalib::Stash &stash) const override {\n return stash.create<DummyExecutor>();\n }\n};\n\nstruct DummyReplacer : ExpressionReplacer {\n vespalib::string trigger;\n FeatureType type;\n DummyReplacer(const vespalib::string trigger_in, const FeatureType &type_in)\n : trigger(trigger_in),\n type(type_in)\n {}\n IntrinsicExpression::UP maybe_replace(const vespalib::eval::Function &function,\n const search::fef::IIndexEnvironment &) const override\n {\n for (size_t i = 0; i < function.num_params(); ++i) {\n if (function.param_name(i) == trigger) {\n return std::make_unique<DummyExpression>(type);\n }\n }\n return IntrinsicExpression::UP(nullptr);\n }\n};\n\nExpressionReplacer::SP make_replacer() {\n auto replacer = std::make_shared<ListExpressionReplacer>();\n replacer->add(std::make_unique<NullExpressionReplacer>());\n replacer->add(std::make_unique<DummyReplacer>(\"foo\", FeatureType::number()));\n replacer->add(std::make_unique<DummyReplacer>(\"bar\", FeatureType::object(ValueType::from_spec(\"tensor(x[5])\"))));\n return replacer;\n}\n\nstruct SetupResult {\n vespalib::Stash stash;\n IndexEnvironment index_env;\n QueryEnvironment query_env;\n RankingExpressionBlueprint rank;\n DummyDependencyHandler deps;\n bool setup_ok;\n SetupResult(const TypeMap &object_inputs, const vespalib::string &expression);\n ~SetupResult();\n};\n\nSetupResult::SetupResult(const TypeMap &object_inputs,\n const vespalib::string &expression)\n : stash(), index_env(), query_env(&index_env), rank(make_replacer()), deps(rank), setup_ok(false)\n{\n rank.setName(\"self\");\n index_env.getProperties().add(\"self.rankingScript\", expression);\n for (const auto &input: object_inputs) {\n deps.define_object_input(input.first, ValueType::from_spec(input.second));\n }\n setup_ok = rank.setup(index_env, {});\n EXPECT_TRUE(!deps.accept_type_mismatch);\n}\nSetupResult::~SetupResult() {}\n\nvoid verify_output_type(const TypeMap &object_inputs,\n const vespalib::string &expression, const FeatureType &expect)\n{\n SetupResult result(object_inputs, expression);\n EXPECT_TRUE(result.setup_ok);\n EXPECT_EQUAL(1u, result.deps.output.size());\n ASSERT_EQUAL(1u, result.deps.output_type.size());\n if (expect.is_object()) {\n EXPECT_EQUAL(expect.type(), result.deps.output_type[0].type());\n } else {\n EXPECT_TRUE(!result.deps.output_type[0].is_object());\n }\n}\n\nvoid verify_setup_fail(const TypeMap &object_inputs,\n const vespalib::string &expression)\n{\n SetupResult result(object_inputs, expression);\n EXPECT_TRUE(!result.setup_ok);\n EXPECT_EQUAL(0u, result.deps.output.size());\n}\n\nvoid verify_input_count(const vespalib::string &expression, size_t expect) {\n SetupResult result({}, expression);\n EXPECT_TRUE(result.setup_ok);\n EXPECT_EQUAL(result.deps.input.size(), expect);\n}\n\nTEST(\"require that expression with only number inputs produce number output (compiled)\") {\n TEST_DO(verify_output_type({}, \"a*b\", FeatureType::number()));\n}\n\nTEST(\"require that expression with object input produces object output (interpreted)\") {\n TEST_DO(verify_output_type({{\"b\", \"double\"}}, \"a*b\", FeatureType::object(ValueType::double_type())));\n}\n\nTEST(\"require that ranking expression can resolve to concrete complex type\") {\n TEST_DO(verify_output_type({{\"a\", \"tensor(x{},y{})\"}, {\"b\", \"tensor(y{},z{})\"}}, \"a*b\",\n FeatureType::object(ValueType::from_spec(\"tensor(x{},y{},z{})\"))));\n}\n\nTEST(\"require that setup fails for incompatible types\") {\n TEST_DO(verify_setup_fail({{\"a\", \"tensor(x{},y{})\"}, {\"b\", \"tensor(y[10],z{})\"}}, \"a*b\"));\n}\n\nTEST(\"require that replaced expressions have no inputs\") {\n TEST_DO(verify_input_count(\"a*b*c\", 3u));\n TEST_DO(verify_input_count(\"foo*b*c\", 0u));\n TEST_DO(verify_input_count(\"a*b*bar\", 0u));\n TEST_DO(verify_input_count(\"foo*b*bar\", 0u));\n}\n\nTEST(\"require that replaced expressions override result type\") {\n TEST_DO(verify_output_type({{\"b\", \"tensor(z{})\"}}, \"a*b*c\",\n FeatureType::object(ValueType::from_spec(\"tensor(z{})\"))));\n TEST_DO(verify_output_type({{\"b\", \"tensor(z{})\"}}, \"foo*b*c\",\n FeatureType::number()));\n TEST_DO(verify_output_type({{\"b\", \"tensor(z{})\"}}, \"a*b*bar\",\n FeatureType::object(ValueType::from_spec(\"tensor(x[5])\"))));\n TEST_DO(verify_output_type({{\"b\", \"tensor(z{})\"}}, \"foo*b*bar\",\n FeatureType::number()));\n}\n\nTEST_F(\"require that replaced expressions create the appropriate executor\", SetupResult({}, \"foo\")) {\n EXPECT_TRUE(f1.setup_ok);\n FeatureExecutor &executor = f1.rank.createExecutor(f1.query_env, f1.stash);\n EXPECT_TRUE(dynamic_cast<DummyExecutor*>(&executor) != nullptr);\n}\n\nTEST_MAIN() { TEST_RUN_ALL(); }\n<commit_msg>= default<commit_after>\/\/ Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.\n#include <vespa\/vespalib\/testkit\/test_kit.h>\n\n#include <vespa\/eval\/eval\/value_type.h>\n#include <vespa\/searchlib\/fef\/feature_type.h>\n#include <vespa\/searchlib\/fef\/featurenameparser.h>\n#include <vespa\/searchlib\/features\/rankingexpressionfeature.h>\n#include <vespa\/searchlib\/fef\/test\/dummy_dependency_handler.h>\n#include <vespa\/searchlib\/fef\/test\/indexenvironment.h>\n#include <vespa\/searchlib\/fef\/test\/queryenvironment.h>\n\nusing namespace search::features;\nusing namespace search::features::rankingexpression;\nusing namespace search::fef::test;\nusing namespace search::fef;\nusing namespace vespalib::eval;\n\nusing TypeMap = std::map<vespalib::string,vespalib::string>;\n\nstruct DummyExecutor : FeatureExecutor {\n void execute(uint32_t) override {}\n};\n\nstruct DummyExpression : IntrinsicExpression {\n FeatureType type;\n DummyExpression(const FeatureType &type_in) : type(type_in) {}\n vespalib::string describe_self() const override { return \"dummy\"; }\n const FeatureType &result_type() const override { return type; }\n void prepare_shared_state(const QueryEnv &, IObjectStore &) const override {\n }\n FeatureExecutor &create_executor(const QueryEnv &, vespalib::Stash &stash) const override {\n return stash.create<DummyExecutor>();\n }\n};\n\nstruct DummyReplacer : ExpressionReplacer {\n vespalib::string trigger;\n FeatureType type;\n DummyReplacer(const vespalib::string trigger_in, const FeatureType &type_in)\n : trigger(trigger_in),\n type(type_in)\n {}\n IntrinsicExpression::UP maybe_replace(const vespalib::eval::Function &function,\n const search::fef::IIndexEnvironment &) const override\n {\n for (size_t i = 0; i < function.num_params(); ++i) {\n if (function.param_name(i) == trigger) {\n return std::make_unique<DummyExpression>(type);\n }\n }\n return IntrinsicExpression::UP(nullptr);\n }\n};\n\nExpressionReplacer::SP make_replacer() {\n auto replacer = std::make_shared<ListExpressionReplacer>();\n replacer->add(std::make_unique<NullExpressionReplacer>());\n replacer->add(std::make_unique<DummyReplacer>(\"foo\", FeatureType::number()));\n replacer->add(std::make_unique<DummyReplacer>(\"bar\", FeatureType::object(ValueType::from_spec(\"tensor(x[5])\"))));\n return replacer;\n}\n\nstruct SetupResult {\n vespalib::Stash stash;\n IndexEnvironment index_env;\n QueryEnvironment query_env;\n RankingExpressionBlueprint rank;\n DummyDependencyHandler deps;\n bool setup_ok;\n SetupResult(const TypeMap &object_inputs, const vespalib::string &expression);\n ~SetupResult();\n};\n\nSetupResult::SetupResult(const TypeMap &object_inputs,\n const vespalib::string &expression)\n : stash(), index_env(), query_env(&index_env), rank(make_replacer()), deps(rank), setup_ok(false)\n{\n rank.setName(\"self\");\n index_env.getProperties().add(\"self.rankingScript\", expression);\n for (const auto &input: object_inputs) {\n deps.define_object_input(input.first, ValueType::from_spec(input.second));\n }\n setup_ok = rank.setup(index_env, {});\n EXPECT_TRUE(!deps.accept_type_mismatch);\n}\nSetupResult::~SetupResult() = default;\n\nvoid verify_output_type(const TypeMap &object_inputs,\n const vespalib::string &expression, const FeatureType &expect)\n{\n SetupResult result(object_inputs, expression);\n EXPECT_TRUE(result.setup_ok);\n EXPECT_EQUAL(1u, result.deps.output.size());\n ASSERT_EQUAL(1u, result.deps.output_type.size());\n if (expect.is_object()) {\n EXPECT_EQUAL(expect.type(), result.deps.output_type[0].type());\n } else {\n EXPECT_TRUE(!result.deps.output_type[0].is_object());\n }\n}\n\nvoid verify_setup_fail(const TypeMap &object_inputs,\n const vespalib::string &expression)\n{\n SetupResult result(object_inputs, expression);\n EXPECT_TRUE(!result.setup_ok);\n EXPECT_EQUAL(0u, result.deps.output.size());\n}\n\nvoid verify_input_count(const vespalib::string &expression, size_t expect) {\n SetupResult result({}, expression);\n EXPECT_TRUE(result.setup_ok);\n EXPECT_EQUAL(result.deps.input.size(), expect);\n}\n\nTEST(\"require that expression with only number inputs produce number output (compiled)\") {\n TEST_DO(verify_output_type({}, \"a*b\", FeatureType::number()));\n}\n\nTEST(\"require that expression with object input produces object output (interpreted)\") {\n TEST_DO(verify_output_type({{\"b\", \"double\"}}, \"a*b\", FeatureType::object(ValueType::double_type())));\n}\n\nTEST(\"require that ranking expression can resolve to concrete complex type\") {\n TEST_DO(verify_output_type({{\"a\", \"tensor(x{},y{})\"}, {\"b\", \"tensor(y{},z{})\"}}, \"a*b\",\n FeatureType::object(ValueType::from_spec(\"tensor(x{},y{},z{})\"))));\n}\n\nTEST(\"require that setup fails for incompatible types\") {\n TEST_DO(verify_setup_fail({{\"a\", \"tensor(x{},y{})\"}, {\"b\", \"tensor(y[10],z{})\"}}, \"a*b\"));\n}\n\nTEST(\"require that replaced expressions have no inputs\") {\n TEST_DO(verify_input_count(\"a*b*c\", 3u));\n TEST_DO(verify_input_count(\"foo*b*c\", 0u));\n TEST_DO(verify_input_count(\"a*b*bar\", 0u));\n TEST_DO(verify_input_count(\"foo*b*bar\", 0u));\n}\n\nTEST(\"require that replaced expressions override result type\") {\n TEST_DO(verify_output_type({{\"b\", \"tensor(z{})\"}}, \"a*b*c\",\n FeatureType::object(ValueType::from_spec(\"tensor(z{})\"))));\n TEST_DO(verify_output_type({{\"b\", \"tensor(z{})\"}}, \"foo*b*c\",\n FeatureType::number()));\n TEST_DO(verify_output_type({{\"b\", \"tensor(z{})\"}}, \"a*b*bar\",\n FeatureType::object(ValueType::from_spec(\"tensor(x[5])\"))));\n TEST_DO(verify_output_type({{\"b\", \"tensor(z{})\"}}, \"foo*b*bar\",\n FeatureType::number()));\n}\n\nTEST_F(\"require that replaced expressions create the appropriate executor\", SetupResult({}, \"foo\")) {\n EXPECT_TRUE(f1.setup_ok);\n FeatureExecutor &executor = f1.rank.createExecutor(f1.query_env, f1.stash);\n EXPECT_TRUE(dynamic_cast<DummyExecutor*>(&executor) != nullptr);\n}\n\nTEST_MAIN() { TEST_RUN_ALL(); }\n<|endoftext|>"} {"text":"<commit_before>#include \"SharedMessagePool.hpp\"\n#include \"Statistics.hpp\"\n#include \"ConditionVariable.hpp\"\n#include <stack>\n\nDEFINE_int64(shared_pool_size, 1L << 20, \"Size (in bytes) of global SharedMessagePool (on each Core)\");\n\n\/\/\/ Note: max is enforced only for blockable callers, and is enforced early to avoid callers\n\/\/\/ that cannot block (callers from message handlers) to have a greater chance of proceeding.\nDEFINE_int64(shared_pool_max, -1, \"Maximum number of shared pools allowed to be allocated (per core).\");\n\nGRAPPA_DEFINE_STAT(SimpleStatistic<uint64_t>, shared_message_pools_allocated, 0);\n\nnamespace Grappa {\n\n \/\/\/ type T must have a member: 'T * next'\n template< typename T, void *(*Allocator)(size_t) = malloc >\n class PiggybackStack {\n protected:\n T* pop() {\n T* r = top;\n if (r != nullptr) {\n top = r->next;\n if (top) CHECK(top->allocated == 0);\n r->next = nullptr;\n }\n return r;\n }\n \n bool is_emergency() { return global_scheduler.in_no_switch_region(); }\n public:\n long allocated;\n const long max_alloc;\n const long emergency_alloc;\n T * top;\n \n PiggybackStack(long max_alloc = -1, long emergency_alloc = 0): allocated(0), max_alloc(max_alloc), emergency_alloc(emergency_alloc), top(nullptr) {}\n \n ~PiggybackStack() {\n CHECK(false) << \"didn't think this was being cleaned up.\";\n while (!empty()) {\n delete pop();\n }\n }\n \n void release(T * s) {\n DCHECK(s->allocated == 0);\n s->next = top;\n top = s;\n }\n \n T* take() {\n T* r = nullptr;\n if (!empty()) {\n r = pop();\n } else if ((max_alloc == -1) || (allocated < (max_alloc-emergency_alloc))\n || (is_emergency() && allocated < max_alloc)) {\n allocated++;\n shared_message_pools_allocated++;\n r = new (Allocator(sizeof(T))) T();\n }\n \/\/ DCHECK(r != nullptr);\n \/\/ new (r) T();\n return r;\n }\n \n bool empty() { return top == nullptr; }\n \n long find(T *o) {\n long id = 0;\n for (auto *i = top; i; i = i->next, id++) {\n if (i == o) return id;\n }\n return -1;\n }\n \n long size() {\n long id = 0;\n for (auto *i = top; i; i = i->next, id++);\n return id;\n }\n \n };\n\n SharedMessagePool * shared_pool = nullptr;\n \n PiggybackStack<SharedMessagePool,locale_alloc<void>> *pool_stack;\n \n ConditionVariable blocked_senders;\n\n void* _shared_pool_alloc_message(size_t sz) {\n DCHECK_GE(shared_pool->remaining(), sz);\n DCHECK( !shared_pool->emptying );\n shared_pool->to_send++;\n return shared_pool->PoolAllocator::allocate(sz);\n }\n \n void init_shared_pool() {\n pool_stack = new PiggybackStack<SharedMessagePool,locale_alloc<void>>(FLAGS_shared_pool_max, FLAGS_shared_pool_max\/4);\n shared_pool = pool_stack->take();\n }\n \n void* _shared_pool_alloc(size_t sz) {\n\/\/ #ifdef DEBUG\n \/\/ auto i = pool_stack->find(shared_pool);\n \/\/ if (i >= 0) VLOG(0) << \"found: \" << shared_pool << \": \" << i << \" \/ \" << pool_stack->size();\n\/\/ #endif\n DCHECK(!shared_pool || shared_pool->next == nullptr);\n if (shared_pool && !shared_pool->emptying && shared_pool->remaining() >= sz) {\n return _shared_pool_alloc_message(sz);\n } else {\n \/\/ if not emptying already, do it\n auto *o = shared_pool;\n shared_pool = nullptr;\n if (o && !o->emptying) {\n CHECK_GT(o->allocated, 0);\n o->emptying = true;\n if (o->to_send == 0) {\n o->on_empty();\n }\n }\n DCHECK(pool_stack->empty() || pool_stack->top->allocated == 0);\n \/\/ find new shared_pool\n SharedMessagePool *p = pool_stack->take();\n if (p) {\n CHECK_EQ(p->allocated, 0) << \"not a fresh pool!\";\n shared_pool = p;\n return _shared_pool_alloc_message(sz);\n } else {\n \/\/ can't allocate any more\n \/\/ try to block until a pool frees up\n do {\n Grappa::wait(&blocked_senders);\n if (shared_pool && !shared_pool->emptying && shared_pool->remaining() >= sz) {\n p = shared_pool;\n } else {\n p = pool_stack->take();\n }\n } while (!p);\n \n \/\/ p must be able to allocate\n shared_pool = p;\n return _shared_pool_alloc_message(sz);\n }\n }\n }\n \n void SharedMessagePool::message_sent(impl::MessageBase* m) {\n DCHECK(this->next == nullptr);\n#ifdef DEBUG\n validate_in_pool(m);\n#endif\n this->to_send--;\n if (this->emptying && this->to_send == 0) {\n \/\/ CHECK(this != shared_pool);\n DCHECK_GT(this->allocated, 0);\n this->on_empty();\n }\n }\n \n void SharedMessagePool::on_empty() {\n CHECK(this->next == nullptr);\n CHECK(this != shared_pool);\n \n DCHECK_EQ(this->to_send, 0);\n DVLOG(3) << \"empty and emptying, to_send:\"<< to_send << \", allocated:\" << allocated << \"\/\" << buffer_size << \" @ \" << this << \", buf:\" << (void*)buffer << \" completions_received:\" << completions_received << \", allocated_count:\" << allocated_count;\n\/\/ #ifdef DEBUG\n \/\/ verify everything sent\n \/\/ this->iterate([](impl::MessageBase* m) {\n \/\/ if (!m->is_sent_ || !m->is_delivered_ || !m->is_enqueued_) {\n \/\/ CHECK(false) << \"!! message(\" << m << \", is_sent_:\" << m->is_sent_ << \", is_delivered_:\" << m->is_delivered_ << \", m->is_enqueued_:\" << m->is_enqueued_ << \", extra:\" << m->pool << \")\";\n \/\/ }\n \/\/ });\n \n memset(buffer, (0x11*locale_mycore()) | 0xf0, buffer_size); \/\/ poison\n \n\/\/ #endif\n DCHECK( pool_stack->find(this) == -1 );\n DCHECK( this->next == nullptr );\n \n this->reset();\n pool_stack->release(this);\n broadcast(&blocked_senders);\n }\n\n} \/\/ namespace Grappa\n<commit_msg>set reasonably-sensible default shared_pool_max<commit_after>#include \"SharedMessagePool.hpp\"\n#include \"Statistics.hpp\"\n#include \"ConditionVariable.hpp\"\n#include <stack>\n\nDEFINE_int64(shared_pool_size, 1L << 18, \"Size (in bytes) of global SharedMessagePool (on each Core)\");\n\n\/\/\/ Note: max is enforced only for blockable callers, and is enforced early to avoid callers\n\/\/\/ that cannot block (callers from message handlers) to have a greater chance of proceeding.\n\/\/\/ In 'init_shared_pool()', 'emergency_alloc' margin is set, currently, to 1\/4 of the max.\n\/\/\/\n\/\/\/ Currently setting this max to cap shared_pool usage at ~1GB, though this may be too much\n\/\/\/ for some apps & machines, as it is allocated out of the locale-shared heap. It's also\n\/\/\/ worth noting that under current settings, most apps don't reach this point at steady state.\nDEFINE_int64(shared_pool_max, 1L << 12, \"Maximum number of shared pools allowed to be allocated (per core).\");\n\nGRAPPA_DEFINE_STAT(SimpleStatistic<uint64_t>, shared_message_pools_allocated, 0);\n\nnamespace Grappa {\n\n \/\/\/ type T must have a member: 'T * next'\n template< typename T, void *(*Allocator)(size_t) = malloc >\n class PiggybackStack {\n protected:\n T* pop() {\n T* r = top;\n if (r != nullptr) {\n top = r->next;\n if (top) CHECK(top->allocated == 0);\n r->next = nullptr;\n }\n return r;\n }\n \n bool is_emergency() { return global_scheduler.in_no_switch_region(); }\n public:\n long allocated;\n const long max_alloc;\n const long emergency_alloc;\n T * top;\n \n PiggybackStack(long max_alloc = -1, long emergency_alloc = 0): allocated(0), max_alloc(max_alloc), emergency_alloc(emergency_alloc), top(nullptr) {}\n \n ~PiggybackStack() {\n CHECK(false) << \"didn't think this was being cleaned up.\";\n while (!empty()) {\n delete pop();\n }\n }\n \n void release(T * s) {\n DCHECK(s->allocated == 0);\n s->next = top;\n top = s;\n }\n \n T* take() {\n T* r = nullptr;\n if (!empty()) {\n r = pop();\n } else if ((max_alloc == -1) || (allocated < (max_alloc-emergency_alloc))\n || (is_emergency() && allocated < max_alloc)) {\n allocated++;\n shared_message_pools_allocated++;\n r = new (Allocator(sizeof(T))) T();\n }\n \/\/ DCHECK(r != nullptr);\n \/\/ new (r) T();\n return r;\n }\n \n bool empty() { return top == nullptr; }\n \n long find(T *o) {\n long id = 0;\n for (auto *i = top; i; i = i->next, id++) {\n if (i == o) return id;\n }\n return -1;\n }\n \n long size() {\n long id = 0;\n for (auto *i = top; i; i = i->next, id++);\n return id;\n }\n \n };\n\n SharedMessagePool * shared_pool = nullptr;\n \n PiggybackStack<SharedMessagePool,locale_alloc<void>> *pool_stack;\n \n ConditionVariable blocked_senders;\n\n void* _shared_pool_alloc_message(size_t sz) {\n DCHECK_GE(shared_pool->remaining(), sz);\n DCHECK( !shared_pool->emptying );\n shared_pool->to_send++;\n return shared_pool->PoolAllocator::allocate(sz);\n }\n \n void init_shared_pool() {\n pool_stack = new PiggybackStack<SharedMessagePool,locale_alloc<void>>(FLAGS_shared_pool_max, FLAGS_shared_pool_max\/4);\n shared_pool = pool_stack->take();\n }\n \n void* _shared_pool_alloc(size_t sz) {\n\/\/ #ifdef DEBUG\n \/\/ auto i = pool_stack->find(shared_pool);\n \/\/ if (i >= 0) VLOG(0) << \"found: \" << shared_pool << \": \" << i << \" \/ \" << pool_stack->size();\n\/\/ #endif\n DCHECK(!shared_pool || shared_pool->next == nullptr);\n if (shared_pool && !shared_pool->emptying && shared_pool->remaining() >= sz) {\n return _shared_pool_alloc_message(sz);\n } else {\n \/\/ if not emptying already, do it\n auto *o = shared_pool;\n shared_pool = nullptr;\n if (o && !o->emptying) {\n CHECK_GT(o->allocated, 0);\n o->emptying = true;\n if (o->to_send == 0) {\n o->on_empty();\n }\n }\n DCHECK(pool_stack->empty() || pool_stack->top->allocated == 0);\n \/\/ find new shared_pool\n SharedMessagePool *p = pool_stack->take();\n if (p) {\n CHECK_EQ(p->allocated, 0) << \"not a fresh pool!\";\n shared_pool = p;\n return _shared_pool_alloc_message(sz);\n } else {\n \/\/ can't allocate any more\n \/\/ try to block until a pool frees up\n do {\n Grappa::wait(&blocked_senders);\n if (shared_pool && !shared_pool->emptying && shared_pool->remaining() >= sz) {\n p = shared_pool;\n } else {\n p = pool_stack->take();\n }\n } while (!p);\n \n \/\/ p must be able to allocate\n shared_pool = p;\n return _shared_pool_alloc_message(sz);\n }\n }\n }\n \n void SharedMessagePool::message_sent(impl::MessageBase* m) {\n DCHECK(this->next == nullptr);\n#ifdef DEBUG\n validate_in_pool(m);\n#endif\n this->to_send--;\n if (this->emptying && this->to_send == 0) {\n \/\/ CHECK(this != shared_pool);\n DCHECK_GT(this->allocated, 0);\n this->on_empty();\n }\n }\n \n void SharedMessagePool::on_empty() {\n CHECK(this->next == nullptr);\n CHECK(this != shared_pool);\n \n DCHECK_EQ(this->to_send, 0);\n DVLOG(3) << \"empty and emptying, to_send:\"<< to_send << \", allocated:\" << allocated << \"\/\" << buffer_size << \" @ \" << this << \", buf:\" << (void*)buffer << \" completions_received:\" << completions_received << \", allocated_count:\" << allocated_count;\n\/\/ #ifdef DEBUG\n \/\/ verify everything sent\n \/\/ this->iterate([](impl::MessageBase* m) {\n \/\/ if (!m->is_sent_ || !m->is_delivered_ || !m->is_enqueued_) {\n \/\/ CHECK(false) << \"!! message(\" << m << \", is_sent_:\" << m->is_sent_ << \", is_delivered_:\" << m->is_delivered_ << \", m->is_enqueued_:\" << m->is_enqueued_ << \", extra:\" << m->pool << \")\";\n \/\/ }\n \/\/ });\n \n memset(buffer, (0x11*locale_mycore()) | 0xf0, buffer_size); \/\/ poison\n \n\/\/ #endif\n DCHECK( pool_stack->find(this) == -1 );\n DCHECK( this->next == nullptr );\n \n this->reset();\n pool_stack->release(this);\n broadcast(&blocked_senders);\n }\n\n} \/\/ namespace Grappa\n<|endoftext|>"} {"text":"<commit_before>\/*\n\nCopyright (c) 2006, Arvid Norberg\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in\n the documentation and\/or other materials provided with the distribution.\n * Neither the name of the author nor the names of its\n contributors may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#include <boost\/date_time\/posix_time\/posix_time_types.hpp>\n#include <boost\/date_time\/posix_time\/ptime.hpp>\n#include <boost\/bind.hpp>\n\n#include <libtorrent\/io.hpp>\n#include <libtorrent\/invariant_check.hpp>\n#include <libtorrent\/kademlia\/rpc_manager.hpp>\n#include <libtorrent\/kademlia\/logging.hpp>\n#include <libtorrent\/kademlia\/routing_table.hpp>\n#include <libtorrent\/hasher.hpp>\n\n#include <fstream>\n\nusing boost::posix_time::ptime;\nusing boost::posix_time::time_duration;\nusing boost::posix_time::microsec_clock;\nusing boost::posix_time::seconds;\nusing boost::posix_time::milliseconds;\nusing boost::shared_ptr;\nusing boost::bind;\n\nnamespace libtorrent { namespace dht\n{\n\nnamespace io = libtorrent::detail;\n\n#ifdef TORRENT_DHT_VERBOSE_LOGGING\nTORRENT_DEFINE_LOG(rpc)\n#endif\n\nnode_id generate_id();\n\nrpc_manager::rpc_manager(fun const& f, node_id const& our_id\n\t, routing_table& table, send_fun const& sf)\n\t: m_next_transaction_id(rand() % max_transactions)\n\t, m_oldest_transaction_id(m_next_transaction_id)\n\t, m_incoming(f)\n\t, m_send(sf)\n\t, m_our_id(our_id)\n\t, m_table(table)\n\t, m_timer(boost::posix_time::microsec_clock::universal_time())\n\t, m_random_number(generate_id())\n\t, m_destructing(false)\n{\n\tstd::srand(time(0));\n}\n\nrpc_manager::~rpc_manager()\n{\n\tm_destructing = true;\n#ifdef TORRENT_DHT_VERBOSE_LOGGING\n\tTORRENT_LOG(rpc) << \"Destructing\";\n#endif\n\tstd::for_each(m_aborted_transactions.begin(), m_aborted_transactions.end()\n\t\t, bind(&observer::abort, _1));\n\t\n\tfor (transactions_t::iterator i = m_transactions.begin()\n\t\t, end(m_transactions.end()); i != end; ++i)\n\t{\n\t\tif (*i) (*i)->abort();\n\t}\n}\n\n#ifndef NDEBUG\nvoid rpc_manager::check_invariant() const\n{\n\tassert(m_oldest_transaction_id >= 0);\n\tassert(m_oldest_transaction_id < max_transactions);\n\tassert(m_next_transaction_id >= 0);\n\tassert(m_next_transaction_id < max_transactions);\n\tassert(!m_transactions[m_next_transaction_id]);\n\n\tfor (int i = (m_next_transaction_id + 1) % max_transactions;\n\t\ti != m_oldest_transaction_id; i = (i + 1) % max_transactions)\n\t{\n\t\tassert(!m_transactions[i]);\n\t}\n}\n#endif\n\nbool rpc_manager::incoming(msg const& m)\n{\n\tINVARIANT_CHECK;\n\n\tif (m_destructing) return false;\n\n\tif (m.reply)\n\t{\n\t\t\/\/ if we don't have the transaction id in our\n\t\t\/\/ request list, ignore the packet\n\n\t\tif (m.transaction_id.size() != 2)\n\t\t{\n#ifdef TORRENT_DHT_VERBOSE_LOGGING\n\t\t\tTORRENT_LOG(rpc) << \"Reply with invalid transaction id size: \" \n\t\t\t\t<< m.transaction_id.size() << \" from \" << m.addr;\n#endif\n\t\t\treturn false;\n\t\t}\n\t\n\t\tstd::string::const_iterator i = m.transaction_id.begin();\t\n\t\tint tid = io::read_uint16(i);\n\n\t\tif (tid >= (int)m_transactions.size()\n\t\t\t|| tid < 0)\n\t\t{\n#ifdef TORRENT_DHT_VERBOSE_LOGGING\n\t\t\tTORRENT_LOG(rpc) << \"Reply with unknown transaction id: \" \n\t\t\t\t<< tid << \" from \" << m.addr;\n#endif\n\t\t\treturn false;\n\t\t}\n\t\t\n\t\tboost::shared_ptr<observer> o = m_transactions[tid];\n\n\t\tif (!o)\n\t\t{\n#ifdef TORRENT_DHT_VERBOSE_LOGGING\n\t\t\tTORRENT_LOG(rpc) << \"Reply with unknown transaction id: \" \n\t\t\t\t<< tid << \" from \" << m.addr;\n#endif\n\t\t\treturn false;\n\t\t}\n\t\t\n\t\tif (m.addr != o->target_addr)\n\t\t{\n#ifdef TORRENT_DHT_VERBOSE_LOGGING\n\t\t\tTORRENT_LOG(rpc) << \"Reply with incorrect address and valid transaction id: \" \n\t\t\t\t<< tid << \" from \" << m.addr;\n#endif\n\t\t\treturn false;\n\t\t}\n\n#ifdef TORRENT_DHT_VERBOSE_LOGGING\n\t\tstd::ofstream reply_stats(\"libtorrent_logs\/round_trip_ms.log\", std::ios::app);\n\t\treply_stats << m.addr << \"\\t\" << (microsec_clock::universal_time()\n\t\t\t- o->sent).total_milliseconds() << std::endl;\n#endif\n\t\to->reply(m);\n\t\tm_transactions[tid].reset();\n\t\t\n\t\tif (m.piggy_backed_ping)\n\t\t{\n\t\t\t\/\/ there is a ping request piggy\n\t\t\t\/\/ backed in this reply\n\t\t\tmsg ph;\n\t\t\tph.message_id = messages::ping;\n\t\t\tph.transaction_id = m.ping_transaction_id;\n\t\t\tph.id = m_our_id;\n\t\t\tph.addr = m.addr;\n\n\t\t\tmsg empty;\n\t\t\t\n\t\t\treply(empty, ph);\n\t\t}\n\t\treturn m_table.node_seen(m.id, m.addr);\n\t}\n\telse\n\t{\n\t\t\/\/ this is an incoming request\n\t\tm_incoming(m);\n\t}\n\treturn false;\n}\n\ntime_duration rpc_manager::tick()\n{\n\tINVARIANT_CHECK;\n\n\tusing boost::posix_time::microsec_clock;\n\n\tconst int timeout_ms = 10 * 1000;\n\n\t\/\/\tlook for observers that has timed out\n\n\tif (m_next_transaction_id == m_oldest_transaction_id) return milliseconds(timeout_ms);\n\n\tstd::vector<shared_ptr<observer> > timeouts;\n\n\tfor (;m_next_transaction_id != m_oldest_transaction_id;\n\t\tm_oldest_transaction_id = (m_oldest_transaction_id + 1) % max_transactions)\n\t{\n\t\tassert(m_oldest_transaction_id >= 0);\n\t\tassert(m_oldest_transaction_id < max_transactions);\n\n\t\tboost::shared_ptr<observer> o = m_transactions[m_oldest_transaction_id];\n\t\tif (!o) continue;\n\n\t\ttime_duration diff = o->sent + milliseconds(timeout_ms)\n\t\t\t- microsec_clock::universal_time();\n\t\tif (diff > seconds(0))\n\t\t{\n\t\t\tif (diff < seconds(1)) return seconds(1);\n\t\t\treturn diff;\n\t\t}\n\t\t\n\t\ttry\n\t\t{\n\t\t\tm_transactions[m_oldest_transaction_id].reset();\n\t\t\ttimeouts.push_back(o);\n\t\t} catch (std::exception) {}\n\t}\n\t\n\tstd::for_each(timeouts.begin(), timeouts.end(), bind(&observer::timeout, _1));\n\ttimeouts.clear();\n\t\n\t\/\/ clear the aborted transactions, will likely\n\t\/\/ generate new requests. We need to swap, since the\n\t\/\/ destrutors may add more observers to the m_aborted_transactions\n\tstd::vector<shared_ptr<observer> >().swap(m_aborted_transactions);\n\treturn milliseconds(timeout_ms);\n}\n\nunsigned int rpc_manager::new_transaction_id(shared_ptr<observer> o)\n{\n\tINVARIANT_CHECK;\n\n\tunsigned int tid = m_next_transaction_id;\n\tm_next_transaction_id = (m_next_transaction_id + 1) % max_transactions;\n\tif (m_transactions[m_next_transaction_id])\n\t{\n\t\t\/\/ moving the observer into the set of aborted transactions\n\t\t\/\/ it will prevent it from spawning new requests right now,\n\t\t\/\/ since that would break the invariant\n\t\tm_aborted_transactions.push_back(m_transactions[m_next_transaction_id]);\n\t\tm_transactions[m_next_transaction_id].reset();\n\t\tassert(m_oldest_transaction_id == m_next_transaction_id);\n\t}\n\tassert(!m_transactions[tid]);\n\tm_transactions[tid] = o;\n\tif (m_oldest_transaction_id == m_next_transaction_id)\n\t{\n\t\tm_oldest_transaction_id = (m_oldest_transaction_id + 1) % max_transactions;\n#ifdef TORRENT_DHT_VERBOSE_LOGGING\n\t\tTORRENT_LOG(rpc) << \"WARNING: transaction limit reached! Too many concurrent\"\n\t\t\t\" messages! limit: \" << (int)max_transactions;\n#endif\n\t\tupdate_oldest_transaction_id();\n\t}\n\n\treturn tid;\n}\n\nvoid rpc_manager::update_oldest_transaction_id()\n{\n\tINVARIANT_CHECK;\n\n\tassert(m_oldest_transaction_id != m_next_transaction_id);\n\twhile (!m_transactions[m_oldest_transaction_id])\n\t{\n\t\tm_oldest_transaction_id = (m_oldest_transaction_id + 1)\n\t\t\t% max_transactions;\n\t\tif (m_oldest_transaction_id == m_next_transaction_id)\n\t\t\tbreak;\n\t}\n}\n\nvoid rpc_manager::invoke(int message_id, udp::endpoint target_addr\n\t, shared_ptr<observer> o)\n{\n\tINVARIANT_CHECK;\n\n\tif (m_destructing)\n\t{\n\t\to->abort();\n\t\treturn;\n\t}\n\n\tmsg m;\n\tm.message_id = message_id;\n\tm.reply = false;\n\tm.id = m_our_id;\n\tm.addr = target_addr;\n\tassert(!m_transactions[m_next_transaction_id]);\n\ttry\n\t{\n\t\tm.transaction_id.clear();\n\t\tstd::back_insert_iterator<std::string> out(m.transaction_id);\n\t\tio::write_uint16(m_next_transaction_id, out);\n\t\t\n\t\to->send(m);\n\n\t\to->sent = boost::posix_time::microsec_clock::universal_time();\n\t\to->target_addr = target_addr;\n\n\t#ifdef TORRENT_DHT_VERBOSE_LOGGING\n\t\tTORRENT_LOG(rpc) << \"Invoking \" << messages::ids[message_id] \n\t\t\t<< \" -> \" << target_addr;\n\t#endif\t\n\t\tm_send(m);\n\t\tnew_transaction_id(o);\n\t}\n\tcatch (std::exception& e)\n\t{\n#ifndef NDEBUG\n\t\tstd::cerr << e.what() << \"\\n\";\n#endif\n\t\tassert(false);\n\t}\n}\n\nvoid rpc_manager::reply(msg& m, msg const& reply_to)\n{\n\tINVARIANT_CHECK;\n\n\tif (m_destructing) return;\n\n\tif (m.message_id != messages::error)\n\t\tm.message_id = reply_to.message_id;\n\tm.addr = reply_to.addr;\n\tm.reply = true;\n\tm.piggy_backed_ping = false;\n\tm.id = m_our_id;\n\tm.transaction_id = reply_to.transaction_id;\n\t\n\tm_send(m);\n}\n\nnamespace\n{\n\tstruct dummy_observer : observer\n\t{\n\t\tvirtual void reply(msg const&) {}\n\t\tvirtual void timeout() {}\n\t\tvirtual void send(msg&) {}\n\t\tvoid abort() {}\n\t};\n}\n\nvoid rpc_manager::reply_with_ping(msg& m, msg const& reply_to)\n{\n\tINVARIANT_CHECK;\n\n\tif (m_destructing) return;\n\n\tif (m.message_id != messages::error)\n\t\tm.message_id = reply_to.message_id;\n\tm.addr = reply_to.addr;\n\tm.reply = true;\n\tm.piggy_backed_ping = true;\n\tm.id = m_our_id;\n\tm.transaction_id = reply_to.transaction_id;\n\n\ttry\n\t{\n\t\tm.ping_transaction_id.clear();\n\t\tstd::back_insert_iterator<std::string> out(m.ping_transaction_id);\n\t\tio::write_uint16(m_next_transaction_id, out);\n\n\t\tboost::shared_ptr<observer> o(new dummy_observer);\n\t\tassert(!m_transactions[m_next_transaction_id]);\n\t\to->sent = boost::posix_time::microsec_clock::universal_time();\n\t\to->target_addr = m.addr;\n\t\t\n\t\tm_send(m);\n\t\tnew_transaction_id(o);\n\t}\n\tcatch (std::exception& e)\n\t{\n#ifndef NDEBUG\n\t\tstd::cerr << e.what() << \"\\n\";\n#endif\n\t\tassert(false);\n\t}\n}\n\n\n\n} } \/\/ namespace libtorrent::dht\n\n<commit_msg>removed unnecessary assert(false) from rpc_manager<commit_after>\/*\n\nCopyright (c) 2006, Arvid Norberg\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in\n the documentation and\/or other materials provided with the distribution.\n * Neither the name of the author nor the names of its\n contributors may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#include <boost\/date_time\/posix_time\/posix_time_types.hpp>\n#include <boost\/date_time\/posix_time\/ptime.hpp>\n#include <boost\/bind.hpp>\n\n#include <libtorrent\/io.hpp>\n#include <libtorrent\/invariant_check.hpp>\n#include <libtorrent\/kademlia\/rpc_manager.hpp>\n#include <libtorrent\/kademlia\/logging.hpp>\n#include <libtorrent\/kademlia\/routing_table.hpp>\n#include <libtorrent\/hasher.hpp>\n\n#include <fstream>\n\nusing boost::posix_time::ptime;\nusing boost::posix_time::time_duration;\nusing boost::posix_time::microsec_clock;\nusing boost::posix_time::seconds;\nusing boost::posix_time::milliseconds;\nusing boost::shared_ptr;\nusing boost::bind;\n\nnamespace libtorrent { namespace dht\n{\n\nnamespace io = libtorrent::detail;\n\n#ifdef TORRENT_DHT_VERBOSE_LOGGING\nTORRENT_DEFINE_LOG(rpc)\n#endif\n\nnode_id generate_id();\n\nrpc_manager::rpc_manager(fun const& f, node_id const& our_id\n\t, routing_table& table, send_fun const& sf)\n\t: m_next_transaction_id(rand() % max_transactions)\n\t, m_oldest_transaction_id(m_next_transaction_id)\n\t, m_incoming(f)\n\t, m_send(sf)\n\t, m_our_id(our_id)\n\t, m_table(table)\n\t, m_timer(boost::posix_time::microsec_clock::universal_time())\n\t, m_random_number(generate_id())\n\t, m_destructing(false)\n{\n\tstd::srand(time(0));\n}\n\nrpc_manager::~rpc_manager()\n{\n\tm_destructing = true;\n#ifdef TORRENT_DHT_VERBOSE_LOGGING\n\tTORRENT_LOG(rpc) << \"Destructing\";\n#endif\n\tstd::for_each(m_aborted_transactions.begin(), m_aborted_transactions.end()\n\t\t, bind(&observer::abort, _1));\n\t\n\tfor (transactions_t::iterator i = m_transactions.begin()\n\t\t, end(m_transactions.end()); i != end; ++i)\n\t{\n\t\tif (*i) (*i)->abort();\n\t}\n}\n\n#ifndef NDEBUG\nvoid rpc_manager::check_invariant() const\n{\n\tassert(m_oldest_transaction_id >= 0);\n\tassert(m_oldest_transaction_id < max_transactions);\n\tassert(m_next_transaction_id >= 0);\n\tassert(m_next_transaction_id < max_transactions);\n\tassert(!m_transactions[m_next_transaction_id]);\n\n\tfor (int i = (m_next_transaction_id + 1) % max_transactions;\n\t\ti != m_oldest_transaction_id; i = (i + 1) % max_transactions)\n\t{\n\t\tassert(!m_transactions[i]);\n\t}\n}\n#endif\n\nbool rpc_manager::incoming(msg const& m)\n{\n\tINVARIANT_CHECK;\n\n\tif (m_destructing) return false;\n\n\tif (m.reply)\n\t{\n\t\t\/\/ if we don't have the transaction id in our\n\t\t\/\/ request list, ignore the packet\n\n\t\tif (m.transaction_id.size() != 2)\n\t\t{\n#ifdef TORRENT_DHT_VERBOSE_LOGGING\n\t\t\tTORRENT_LOG(rpc) << \"Reply with invalid transaction id size: \" \n\t\t\t\t<< m.transaction_id.size() << \" from \" << m.addr;\n#endif\n\t\t\treturn false;\n\t\t}\n\t\n\t\tstd::string::const_iterator i = m.transaction_id.begin();\t\n\t\tint tid = io::read_uint16(i);\n\n\t\tif (tid >= (int)m_transactions.size()\n\t\t\t|| tid < 0)\n\t\t{\n#ifdef TORRENT_DHT_VERBOSE_LOGGING\n\t\t\tTORRENT_LOG(rpc) << \"Reply with unknown transaction id: \" \n\t\t\t\t<< tid << \" from \" << m.addr;\n#endif\n\t\t\treturn false;\n\t\t}\n\t\t\n\t\tboost::shared_ptr<observer> o = m_transactions[tid];\n\n\t\tif (!o)\n\t\t{\n#ifdef TORRENT_DHT_VERBOSE_LOGGING\n\t\t\tTORRENT_LOG(rpc) << \"Reply with unknown transaction id: \" \n\t\t\t\t<< tid << \" from \" << m.addr;\n#endif\n\t\t\treturn false;\n\t\t}\n\t\t\n\t\tif (m.addr != o->target_addr)\n\t\t{\n#ifdef TORRENT_DHT_VERBOSE_LOGGING\n\t\t\tTORRENT_LOG(rpc) << \"Reply with incorrect address and valid transaction id: \" \n\t\t\t\t<< tid << \" from \" << m.addr;\n#endif\n\t\t\treturn false;\n\t\t}\n\n#ifdef TORRENT_DHT_VERBOSE_LOGGING\n\t\tstd::ofstream reply_stats(\"libtorrent_logs\/round_trip_ms.log\", std::ios::app);\n\t\treply_stats << m.addr << \"\\t\" << (microsec_clock::universal_time()\n\t\t\t- o->sent).total_milliseconds() << std::endl;\n#endif\n\t\to->reply(m);\n\t\tm_transactions[tid].reset();\n\t\t\n\t\tif (m.piggy_backed_ping)\n\t\t{\n\t\t\t\/\/ there is a ping request piggy\n\t\t\t\/\/ backed in this reply\n\t\t\tmsg ph;\n\t\t\tph.message_id = messages::ping;\n\t\t\tph.transaction_id = m.ping_transaction_id;\n\t\t\tph.id = m_our_id;\n\t\t\tph.addr = m.addr;\n\n\t\t\tmsg empty;\n\t\t\t\n\t\t\treply(empty, ph);\n\t\t}\n\t\treturn m_table.node_seen(m.id, m.addr);\n\t}\n\telse\n\t{\n\t\t\/\/ this is an incoming request\n\t\tm_incoming(m);\n\t}\n\treturn false;\n}\n\ntime_duration rpc_manager::tick()\n{\n\tINVARIANT_CHECK;\n\n\tusing boost::posix_time::microsec_clock;\n\n\tconst int timeout_ms = 10 * 1000;\n\n\t\/\/\tlook for observers that has timed out\n\n\tif (m_next_transaction_id == m_oldest_transaction_id) return milliseconds(timeout_ms);\n\n\tstd::vector<shared_ptr<observer> > timeouts;\n\n\tfor (;m_next_transaction_id != m_oldest_transaction_id;\n\t\tm_oldest_transaction_id = (m_oldest_transaction_id + 1) % max_transactions)\n\t{\n\t\tassert(m_oldest_transaction_id >= 0);\n\t\tassert(m_oldest_transaction_id < max_transactions);\n\n\t\tboost::shared_ptr<observer> o = m_transactions[m_oldest_transaction_id];\n\t\tif (!o) continue;\n\n\t\ttime_duration diff = o->sent + milliseconds(timeout_ms)\n\t\t\t- microsec_clock::universal_time();\n\t\tif (diff > seconds(0))\n\t\t{\n\t\t\tif (diff < seconds(1)) return seconds(1);\n\t\t\treturn diff;\n\t\t}\n\t\t\n\t\ttry\n\t\t{\n\t\t\tm_transactions[m_oldest_transaction_id].reset();\n\t\t\ttimeouts.push_back(o);\n\t\t} catch (std::exception) {}\n\t}\n\t\n\tstd::for_each(timeouts.begin(), timeouts.end(), bind(&observer::timeout, _1));\n\ttimeouts.clear();\n\t\n\t\/\/ clear the aborted transactions, will likely\n\t\/\/ generate new requests. We need to swap, since the\n\t\/\/ destrutors may add more observers to the m_aborted_transactions\n\tstd::vector<shared_ptr<observer> >().swap(m_aborted_transactions);\n\treturn milliseconds(timeout_ms);\n}\n\nunsigned int rpc_manager::new_transaction_id(shared_ptr<observer> o)\n{\n\tINVARIANT_CHECK;\n\n\tunsigned int tid = m_next_transaction_id;\n\tm_next_transaction_id = (m_next_transaction_id + 1) % max_transactions;\n\tif (m_transactions[m_next_transaction_id])\n\t{\n\t\t\/\/ moving the observer into the set of aborted transactions\n\t\t\/\/ it will prevent it from spawning new requests right now,\n\t\t\/\/ since that would break the invariant\n\t\tm_aborted_transactions.push_back(m_transactions[m_next_transaction_id]);\n\t\tm_transactions[m_next_transaction_id].reset();\n\t\tassert(m_oldest_transaction_id == m_next_transaction_id);\n\t}\n\tassert(!m_transactions[tid]);\n\tm_transactions[tid] = o;\n\tif (m_oldest_transaction_id == m_next_transaction_id)\n\t{\n\t\tm_oldest_transaction_id = (m_oldest_transaction_id + 1) % max_transactions;\n#ifdef TORRENT_DHT_VERBOSE_LOGGING\n\t\tTORRENT_LOG(rpc) << \"WARNING: transaction limit reached! Too many concurrent\"\n\t\t\t\" messages! limit: \" << (int)max_transactions;\n#endif\n\t\tupdate_oldest_transaction_id();\n\t}\n\n\treturn tid;\n}\n\nvoid rpc_manager::update_oldest_transaction_id()\n{\n\tINVARIANT_CHECK;\n\n\tassert(m_oldest_transaction_id != m_next_transaction_id);\n\twhile (!m_transactions[m_oldest_transaction_id])\n\t{\n\t\tm_oldest_transaction_id = (m_oldest_transaction_id + 1)\n\t\t\t% max_transactions;\n\t\tif (m_oldest_transaction_id == m_next_transaction_id)\n\t\t\tbreak;\n\t}\n}\n\nvoid rpc_manager::invoke(int message_id, udp::endpoint target_addr\n\t, shared_ptr<observer> o)\n{\n\tINVARIANT_CHECK;\n\n\tif (m_destructing)\n\t{\n\t\to->abort();\n\t\treturn;\n\t}\n\n\tmsg m;\n\tm.message_id = message_id;\n\tm.reply = false;\n\tm.id = m_our_id;\n\tm.addr = target_addr;\n\tassert(!m_transactions[m_next_transaction_id]);\n\ttry\n\t{\n\t\tm.transaction_id.clear();\n\t\tstd::back_insert_iterator<std::string> out(m.transaction_id);\n\t\tio::write_uint16(m_next_transaction_id, out);\n\t\t\n\t\to->send(m);\n\n\t\to->sent = boost::posix_time::microsec_clock::universal_time();\n\t\to->target_addr = target_addr;\n\n\t#ifdef TORRENT_DHT_VERBOSE_LOGGING\n\t\tTORRENT_LOG(rpc) << \"Invoking \" << messages::ids[message_id] \n\t\t\t<< \" -> \" << target_addr;\n\t#endif\t\n\t\tm_send(m);\n\t\tnew_transaction_id(o);\n\t}\n\tcatch (std::exception& e)\n\t{\n\t\t\/\/ m_send may fail with \"no route to host\"\n\t}\n}\n\nvoid rpc_manager::reply(msg& m, msg const& reply_to)\n{\n\tINVARIANT_CHECK;\n\n\tif (m_destructing) return;\n\n\tif (m.message_id != messages::error)\n\t\tm.message_id = reply_to.message_id;\n\tm.addr = reply_to.addr;\n\tm.reply = true;\n\tm.piggy_backed_ping = false;\n\tm.id = m_our_id;\n\tm.transaction_id = reply_to.transaction_id;\n\t\n\tm_send(m);\n}\n\nnamespace\n{\n\tstruct dummy_observer : observer\n\t{\n\t\tvirtual void reply(msg const&) {}\n\t\tvirtual void timeout() {}\n\t\tvirtual void send(msg&) {}\n\t\tvoid abort() {}\n\t};\n}\n\nvoid rpc_manager::reply_with_ping(msg& m, msg const& reply_to)\n{\n\tINVARIANT_CHECK;\n\n\tif (m_destructing) return;\n\n\tif (m.message_id != messages::error)\n\t\tm.message_id = reply_to.message_id;\n\tm.addr = reply_to.addr;\n\tm.reply = true;\n\tm.piggy_backed_ping = true;\n\tm.id = m_our_id;\n\tm.transaction_id = reply_to.transaction_id;\n\n\ttry\n\t{\n\t\tm.ping_transaction_id.clear();\n\t\tstd::back_insert_iterator<std::string> out(m.ping_transaction_id);\n\t\tio::write_uint16(m_next_transaction_id, out);\n\n\t\tboost::shared_ptr<observer> o(new dummy_observer);\n\t\tassert(!m_transactions[m_next_transaction_id]);\n\t\to->sent = boost::posix_time::microsec_clock::universal_time();\n\t\to->target_addr = m.addr;\n\t\t\n\t\tm_send(m);\n\t\tnew_transaction_id(o);\n\t}\n\tcatch (std::exception& e)\n\t{\n\t\t\/\/ m_send may fail with \"no route to host\"\n\t}\n}\n\n\n\n} } \/\/ namespace libtorrent::dht\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2011 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"base\/command_line.h\"\n#include \"base\/memory\/scoped_ptr.h\"\n#include \"base\/message_loop.h\"\n#include \"chrome\/browser\/automation\/ui_controls.h\"\n#include \"chrome\/browser\/chromeos\/cros\/cros_in_process_browser_test.h\"\n#include \"chrome\/browser\/chromeos\/cros\/mock_input_method_library.h\"\n#include \"chrome\/browser\/chromeos\/cros\/mock_screen_lock_library.h\"\n#include \"chrome\/browser\/chromeos\/login\/mock_authenticator.h\"\n#include \"chrome\/browser\/chromeos\/login\/screen_locker.h\"\n#include \"chrome\/browser\/chromeos\/login\/screen_locker_tester.h\"\n#include \"chrome\/browser\/chromeos\/login\/user_manager.h\"\n#include \"chrome\/browser\/profiles\/profile_manager.h\"\n#include \"chrome\/browser\/ui\/browser.h\"\n#include \"chrome\/browser\/ui\/browser_window.h\"\n#include \"chrome\/browser\/ui\/views\/browser_dialogs.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/test\/ui_test_utils.h\"\n#include \"content\/common\/notification_service.h\"\n#include \"content\/common\/notification_type.h\"\n#include \"testing\/gmock\/include\/gmock\/gmock.h\"\n#include \"testing\/gtest\/include\/gtest\/gtest.h\"\n#include \"views\/controls\/textfield\/textfield.h\"\n#include \"views\/window\/window_gtk.h\"\n\nnamespace {\n\n\/\/ An object that wait for lock state and fullscreen state.\nclass Waiter : public NotificationObserver {\n public:\n explicit Waiter(Browser* browser)\n : browser_(browser),\n running_(false) {\n registrar_.Add(this,\n NotificationType::SCREEN_LOCK_STATE_CHANGED,\n NotificationService::AllSources());\n handler_id_ = g_signal_connect(\n G_OBJECT(browser_->window()->GetNativeHandle()),\n \"window-state-event\",\n G_CALLBACK(OnWindowStateEventThunk),\n this);\n }\n\n ~Waiter() {\n g_signal_handler_disconnect(\n G_OBJECT(browser_->window()->GetNativeHandle()),\n handler_id_);\n }\n\n virtual void Observe(NotificationType type,\n const NotificationSource& source,\n const NotificationDetails& details) {\n DCHECK(type == NotificationType::SCREEN_LOCK_STATE_CHANGED);\n if (running_)\n MessageLoop::current()->Quit();\n }\n\n \/\/ Wait until the two conditions are met.\n void Wait(bool locker_state, bool fullscreen) {\n running_ = true;\n scoped_ptr<chromeos::test::ScreenLockerTester>\n tester(chromeos::ScreenLocker::GetTester());\n while (tester->IsLocked() != locker_state ||\n browser_->window()->IsFullscreen() != fullscreen) {\n ui_test_utils::RunMessageLoop();\n }\n \/\/ Make sure all pending tasks are executed.\n ui_test_utils::RunAllPendingInMessageLoop();\n running_ = false;\n }\n\n CHROMEGTK_CALLBACK_1(Waiter, gboolean, OnWindowStateEvent,\n GdkEventWindowState*);\n\n private:\n Browser* browser_;\n gulong handler_id_;\n NotificationRegistrar registrar_;\n\n \/\/ Are we currently running the message loop?\n bool running_;\n\n DISALLOW_COPY_AND_ASSIGN(Waiter);\n};\n\ngboolean Waiter::OnWindowStateEvent(GtkWidget* widget,\n GdkEventWindowState* event) {\n MessageLoop::current()->Quit();\n return false;\n}\n\n} \/\/ namespace\n\nnamespace chromeos {\n\nclass ScreenLockerTest : public CrosInProcessBrowserTest {\n public:\n ScreenLockerTest() : mock_screen_lock_library_(NULL),\n mock_input_method_library_(NULL) {\n }\n\n protected:\n MockScreenLockLibrary *mock_screen_lock_library_;\n MockInputMethodLibrary *mock_input_method_library_;\n\n \/\/ Test the no password mode with different unlock scheme given by\n \/\/ |unlock| function.\n void TestNoPassword(void (unlock)(views::Widget*)) {\n EXPECT_CALL(*mock_screen_lock_library_, NotifyScreenUnlockRequested())\n .Times(1)\n .RetiresOnSaturation();\n EXPECT_CALL(*mock_screen_lock_library_, NotifyScreenLockCompleted())\n .Times(1)\n .RetiresOnSaturation();\n UserManager::Get()->OffTheRecordUserLoggedIn();\n ScreenLocker::Show();\n scoped_ptr<test::ScreenLockerTester> tester(ScreenLocker::GetTester());\n tester->EmulateWindowManagerReady();\n if (!chromeos::ScreenLocker::GetTester()->IsLocked())\n ui_test_utils::WaitForNotification(\n NotificationType::SCREEN_LOCK_STATE_CHANGED);\n EXPECT_TRUE(tester->IsLocked());\n tester->InjectMockAuthenticator(\"\", \"\");\n\n unlock(tester->GetWidget());\n\n ui_test_utils::RunAllPendingInMessageLoop();\n EXPECT_TRUE(tester->IsLocked());\n\n \/\/ Emulate LockScreen request from PowerManager (via SessionManager).\n ScreenLocker::Hide();\n ui_test_utils::RunAllPendingInMessageLoop();\n EXPECT_FALSE(tester->IsLocked());\n }\n\n void LockScreenWithUser(test::ScreenLockerTester* tester,\n const std::string& user) {\n UserManager::Get()->UserLoggedIn(user);\n ScreenLocker::Show();\n tester->EmulateWindowManagerReady();\n if (!tester->IsLocked()) {\n ui_test_utils::WaitForNotification(\n NotificationType::SCREEN_LOCK_STATE_CHANGED);\n }\n EXPECT_TRUE(tester->IsLocked());\n }\n\n private:\n virtual void SetUpInProcessBrowserTestFixture() {\n cros_mock_->InitStatusAreaMocks();\n cros_mock_->InitMockScreenLockLibrary();\n mock_screen_lock_library_ = cros_mock_->mock_screen_lock_library();\n mock_input_method_library_ = cros_mock_->mock_input_method_library();\n EXPECT_CALL(*mock_screen_lock_library_, AddObserver(testing::_))\n .Times(1)\n .RetiresOnSaturation();\n EXPECT_CALL(*mock_screen_lock_library_, NotifyScreenUnlockCompleted())\n .Times(1)\n .RetiresOnSaturation();\n \/\/ Expectations for the status are on the screen lock window.\n cros_mock_->SetStatusAreaMocksExpectations();\n \/\/ Expectations for the status area on the browser window.\n cros_mock_->SetStatusAreaMocksExpectations();\n }\n\n virtual void SetUpCommandLine(CommandLine* command_line) {\n command_line->AppendSwitchASCII(switches::kLoginProfile, \"user\");\n command_line->AppendSwitch(switches::kNoFirstRun);\n }\n\n DISALLOW_COPY_AND_ASSIGN(ScreenLockerTest);\n};\n\nIN_PROC_BROWSER_TEST_F(ScreenLockerTest, TestBasic) {\n EXPECT_CALL(*mock_input_method_library_, GetNumActiveInputMethods())\n .Times(1)\n .WillRepeatedly((testing::Return(0)))\n .RetiresOnSaturation();\n EXPECT_CALL(*mock_screen_lock_library_, NotifyScreenUnlockRequested())\n .Times(1)\n .RetiresOnSaturation();\n EXPECT_CALL(*mock_screen_lock_library_, NotifyScreenLockCompleted())\n .Times(1)\n .RetiresOnSaturation();\n UserManager::Get()->UserLoggedIn(\"user\");\n ScreenLocker::Show();\n scoped_ptr<test::ScreenLockerTester> tester(ScreenLocker::GetTester());\n tester->EmulateWindowManagerReady();\n if (!chromeos::ScreenLocker::GetTester()->IsLocked())\n ui_test_utils::WaitForNotification(\n NotificationType::SCREEN_LOCK_STATE_CHANGED);\n\n \/\/ Test to make sure that the widget is actually appearing and is of\n \/\/ reasonable size, preventing a regression of\n \/\/ http:\/\/code.google.com\/p\/chromium-os\/issues\/detail?id=5987\n gfx::Rect lock_bounds = tester->GetChildWidget()->GetWindowScreenBounds();\n EXPECT_GT(lock_bounds.width(), 10);\n EXPECT_GT(lock_bounds.height(), 10);\n\n tester->InjectMockAuthenticator(\"user\", \"pass\");\n EXPECT_TRUE(tester->IsLocked());\n tester->EnterPassword(\"fail\");\n ui_test_utils::RunAllPendingInMessageLoop();\n EXPECT_TRUE(tester->IsLocked());\n tester->EnterPassword(\"pass\");\n ui_test_utils::RunAllPendingInMessageLoop();\n \/\/ Successful authentication simply send a unlock request to PowerManager.\n EXPECT_TRUE(tester->IsLocked());\n\n \/\/ Emulate LockScreen request from PowerManager (via SessionManager).\n \/\/ TODO(oshima): Find out better way to handle this in mock.\n ScreenLocker::Hide();\n ui_test_utils::RunAllPendingInMessageLoop();\n EXPECT_FALSE(tester->IsLocked());\n}\n\nIN_PROC_BROWSER_TEST_F(ScreenLockerTest, TestFullscreenExit) {\n EXPECT_CALL(*mock_screen_lock_library_, NotifyScreenUnlockRequested())\n .Times(1)\n .RetiresOnSaturation();\n EXPECT_CALL(*mock_screen_lock_library_, NotifyScreenLockCompleted())\n .Times(1)\n .RetiresOnSaturation();\n scoped_ptr<test::ScreenLockerTester> tester(ScreenLocker::GetTester());\n {\n Waiter waiter(browser());\n browser()->ToggleFullscreenMode();\n waiter.Wait(false \/* not locked *\/, true \/* full screen *\/);\n EXPECT_TRUE(browser()->window()->IsFullscreen());\n EXPECT_FALSE(tester->IsLocked());\n }\n {\n Waiter waiter(browser());\n UserManager::Get()->UserLoggedIn(\"user\");\n ScreenLocker::Show();\n tester->EmulateWindowManagerReady();\n waiter.Wait(true \/* locked *\/, false \/* full screen *\/);\n EXPECT_FALSE(browser()->window()->IsFullscreen());\n EXPECT_TRUE(tester->IsLocked());\n }\n tester->InjectMockAuthenticator(\"user\", \"pass\");\n tester->EnterPassword(\"pass\");\n ui_test_utils::RunAllPendingInMessageLoop();\n ScreenLocker::Hide();\n ui_test_utils::RunAllPendingInMessageLoop();\n EXPECT_FALSE(tester->IsLocked());\n}\n\nvoid MouseMove(views::Widget* widget) {\n ui_controls::SendMouseMove(10, 10);\n}\n\nIN_PROC_BROWSER_TEST_F(ScreenLockerTest, DISABLED_TestNoPasswordWithMouseMove) {\n TestNoPassword(MouseMove);\n}\n\nvoid MouseClick(views::Widget* widget) {\n ui_controls::SendMouseClick(ui_controls::RIGHT);\n}\n\nIN_PROC_BROWSER_TEST_F(ScreenLockerTest,\n DISABLED_TestNoPasswordWithMouseClick) {\n TestNoPassword(MouseClick);\n}\n\nvoid KeyPress(views::Widget* widget) {\n ui_controls::SendKeyPress(GTK_WINDOW(widget->GetNativeView()),\n ui::VKEY_SPACE, false, false, false, false);\n}\n\nIN_PROC_BROWSER_TEST_F(ScreenLockerTest, DISABLED_TestNoPasswordWithKeyPress) {\n TestNoPassword(KeyPress);\n}\n\n\/\/ See http:\/\/crbug.com\/78764.\nIN_PROC_BROWSER_TEST_F(ScreenLockerTest, DISABLED_TestShowTwice) {\n EXPECT_CALL(*mock_screen_lock_library_, NotifyScreenLockCompleted())\n .Times(2)\n .RetiresOnSaturation();\n scoped_ptr<test::ScreenLockerTester> tester(ScreenLocker::GetTester());\n LockScreenWithUser(tester.get(), \"user\");\n\n \/\/ Ensure there's a profile or this test crashes.\n ProfileManager::GetDefaultProfile();\n\n \/\/ Calling Show again simply send LockCompleted signal.\n ScreenLocker::Show();\n EXPECT_TRUE(tester->IsLocked());\n\n \/\/ Close the locker to match expectations.\n ScreenLocker::Hide();\n ui_test_utils::RunAllPendingInMessageLoop();\n EXPECT_FALSE(tester->IsLocked());\n}\n\n\/\/ See http:\/\/crbug.com\/78764.\nIN_PROC_BROWSER_TEST_F(ScreenLockerTest, DISABLED_TestEscape) {\n EXPECT_CALL(*mock_screen_lock_library_, NotifyScreenLockCompleted())\n .Times(1)\n .RetiresOnSaturation();\n scoped_ptr<test::ScreenLockerTester> tester(ScreenLocker::GetTester());\n LockScreenWithUser(tester.get(), \"user\");\n\n \/\/ Ensure there's a profile or this test crashes.\n ProfileManager::GetDefaultProfile();\n\n tester->SetPassword(\"password\");\n EXPECT_EQ(\"password\", tester->GetPassword());\n \/\/ Escape clears the password.\n ui_controls::SendKeyPress(GTK_WINDOW(tester->GetWidget()->GetNativeView()),\n ui::VKEY_ESCAPE, false, false, false, false);\n ui_test_utils::RunAllPendingInMessageLoop();\n EXPECT_EQ(\"\", tester->GetPassword());\n\n \/\/ Close the locker to match expectations.\n ScreenLocker::Hide();\n ui_test_utils::RunAllPendingInMessageLoop();\n EXPECT_FALSE(tester->IsLocked());\n}\n\n} \/\/ namespace chromeos\n<commit_msg>Add documentation for why tests are disabled per http:\/\/www.chromium.org\/developers\/tree-sheriffs\/sheriff-details-chromium\/handling-a-failing-test<commit_after>\/\/ Copyright (c) 2011 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"base\/command_line.h\"\n#include \"base\/memory\/scoped_ptr.h\"\n#include \"base\/message_loop.h\"\n#include \"chrome\/browser\/automation\/ui_controls.h\"\n#include \"chrome\/browser\/chromeos\/cros\/cros_in_process_browser_test.h\"\n#include \"chrome\/browser\/chromeos\/cros\/mock_input_method_library.h\"\n#include \"chrome\/browser\/chromeos\/cros\/mock_screen_lock_library.h\"\n#include \"chrome\/browser\/chromeos\/login\/mock_authenticator.h\"\n#include \"chrome\/browser\/chromeos\/login\/screen_locker.h\"\n#include \"chrome\/browser\/chromeos\/login\/screen_locker_tester.h\"\n#include \"chrome\/browser\/chromeos\/login\/user_manager.h\"\n#include \"chrome\/browser\/profiles\/profile_manager.h\"\n#include \"chrome\/browser\/ui\/browser.h\"\n#include \"chrome\/browser\/ui\/browser_window.h\"\n#include \"chrome\/browser\/ui\/views\/browser_dialogs.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/test\/ui_test_utils.h\"\n#include \"content\/common\/notification_service.h\"\n#include \"content\/common\/notification_type.h\"\n#include \"testing\/gmock\/include\/gmock\/gmock.h\"\n#include \"testing\/gtest\/include\/gtest\/gtest.h\"\n#include \"views\/controls\/textfield\/textfield.h\"\n#include \"views\/window\/window_gtk.h\"\n\nnamespace {\n\n\/\/ An object that wait for lock state and fullscreen state.\nclass Waiter : public NotificationObserver {\n public:\n explicit Waiter(Browser* browser)\n : browser_(browser),\n running_(false) {\n registrar_.Add(this,\n NotificationType::SCREEN_LOCK_STATE_CHANGED,\n NotificationService::AllSources());\n handler_id_ = g_signal_connect(\n G_OBJECT(browser_->window()->GetNativeHandle()),\n \"window-state-event\",\n G_CALLBACK(OnWindowStateEventThunk),\n this);\n }\n\n ~Waiter() {\n g_signal_handler_disconnect(\n G_OBJECT(browser_->window()->GetNativeHandle()),\n handler_id_);\n }\n\n virtual void Observe(NotificationType type,\n const NotificationSource& source,\n const NotificationDetails& details) {\n DCHECK(type == NotificationType::SCREEN_LOCK_STATE_CHANGED);\n if (running_)\n MessageLoop::current()->Quit();\n }\n\n \/\/ Wait until the two conditions are met.\n void Wait(bool locker_state, bool fullscreen) {\n running_ = true;\n scoped_ptr<chromeos::test::ScreenLockerTester>\n tester(chromeos::ScreenLocker::GetTester());\n while (tester->IsLocked() != locker_state ||\n browser_->window()->IsFullscreen() != fullscreen) {\n ui_test_utils::RunMessageLoop();\n }\n \/\/ Make sure all pending tasks are executed.\n ui_test_utils::RunAllPendingInMessageLoop();\n running_ = false;\n }\n\n CHROMEGTK_CALLBACK_1(Waiter, gboolean, OnWindowStateEvent,\n GdkEventWindowState*);\n\n private:\n Browser* browser_;\n gulong handler_id_;\n NotificationRegistrar registrar_;\n\n \/\/ Are we currently running the message loop?\n bool running_;\n\n DISALLOW_COPY_AND_ASSIGN(Waiter);\n};\n\ngboolean Waiter::OnWindowStateEvent(GtkWidget* widget,\n GdkEventWindowState* event) {\n MessageLoop::current()->Quit();\n return false;\n}\n\n} \/\/ namespace\n\nnamespace chromeos {\n\nclass ScreenLockerTest : public CrosInProcessBrowserTest {\n public:\n ScreenLockerTest() : mock_screen_lock_library_(NULL),\n mock_input_method_library_(NULL) {\n }\n\n protected:\n MockScreenLockLibrary *mock_screen_lock_library_;\n MockInputMethodLibrary *mock_input_method_library_;\n\n \/\/ Test the no password mode with different unlock scheme given by\n \/\/ |unlock| function.\n void TestNoPassword(void (unlock)(views::Widget*)) {\n EXPECT_CALL(*mock_screen_lock_library_, NotifyScreenUnlockRequested())\n .Times(1)\n .RetiresOnSaturation();\n EXPECT_CALL(*mock_screen_lock_library_, NotifyScreenLockCompleted())\n .Times(1)\n .RetiresOnSaturation();\n UserManager::Get()->OffTheRecordUserLoggedIn();\n ScreenLocker::Show();\n scoped_ptr<test::ScreenLockerTester> tester(ScreenLocker::GetTester());\n tester->EmulateWindowManagerReady();\n if (!chromeos::ScreenLocker::GetTester()->IsLocked())\n ui_test_utils::WaitForNotification(\n NotificationType::SCREEN_LOCK_STATE_CHANGED);\n EXPECT_TRUE(tester->IsLocked());\n tester->InjectMockAuthenticator(\"\", \"\");\n\n unlock(tester->GetWidget());\n\n ui_test_utils::RunAllPendingInMessageLoop();\n EXPECT_TRUE(tester->IsLocked());\n\n \/\/ Emulate LockScreen request from PowerManager (via SessionManager).\n ScreenLocker::Hide();\n ui_test_utils::RunAllPendingInMessageLoop();\n EXPECT_FALSE(tester->IsLocked());\n }\n\n void LockScreenWithUser(test::ScreenLockerTester* tester,\n const std::string& user) {\n UserManager::Get()->UserLoggedIn(user);\n ScreenLocker::Show();\n tester->EmulateWindowManagerReady();\n if (!tester->IsLocked()) {\n ui_test_utils::WaitForNotification(\n NotificationType::SCREEN_LOCK_STATE_CHANGED);\n }\n EXPECT_TRUE(tester->IsLocked());\n }\n\n private:\n virtual void SetUpInProcessBrowserTestFixture() {\n cros_mock_->InitStatusAreaMocks();\n cros_mock_->InitMockScreenLockLibrary();\n mock_screen_lock_library_ = cros_mock_->mock_screen_lock_library();\n mock_input_method_library_ = cros_mock_->mock_input_method_library();\n EXPECT_CALL(*mock_screen_lock_library_, AddObserver(testing::_))\n .Times(1)\n .RetiresOnSaturation();\n EXPECT_CALL(*mock_screen_lock_library_, NotifyScreenUnlockCompleted())\n .Times(1)\n .RetiresOnSaturation();\n \/\/ Expectations for the status are on the screen lock window.\n cros_mock_->SetStatusAreaMocksExpectations();\n \/\/ Expectations for the status area on the browser window.\n cros_mock_->SetStatusAreaMocksExpectations();\n }\n\n virtual void SetUpCommandLine(CommandLine* command_line) {\n command_line->AppendSwitchASCII(switches::kLoginProfile, \"user\");\n command_line->AppendSwitch(switches::kNoFirstRun);\n }\n\n DISALLOW_COPY_AND_ASSIGN(ScreenLockerTest);\n};\n\nIN_PROC_BROWSER_TEST_F(ScreenLockerTest, TestBasic) {\n EXPECT_CALL(*mock_input_method_library_, GetNumActiveInputMethods())\n .Times(1)\n .WillRepeatedly((testing::Return(0)))\n .RetiresOnSaturation();\n EXPECT_CALL(*mock_screen_lock_library_, NotifyScreenUnlockRequested())\n .Times(1)\n .RetiresOnSaturation();\n EXPECT_CALL(*mock_screen_lock_library_, NotifyScreenLockCompleted())\n .Times(1)\n .RetiresOnSaturation();\n UserManager::Get()->UserLoggedIn(\"user\");\n ScreenLocker::Show();\n scoped_ptr<test::ScreenLockerTester> tester(ScreenLocker::GetTester());\n tester->EmulateWindowManagerReady();\n if (!chromeos::ScreenLocker::GetTester()->IsLocked())\n ui_test_utils::WaitForNotification(\n NotificationType::SCREEN_LOCK_STATE_CHANGED);\n\n \/\/ Test to make sure that the widget is actually appearing and is of\n \/\/ reasonable size, preventing a regression of\n \/\/ http:\/\/code.google.com\/p\/chromium-os\/issues\/detail?id=5987\n gfx::Rect lock_bounds = tester->GetChildWidget()->GetWindowScreenBounds();\n EXPECT_GT(lock_bounds.width(), 10);\n EXPECT_GT(lock_bounds.height(), 10);\n\n tester->InjectMockAuthenticator(\"user\", \"pass\");\n EXPECT_TRUE(tester->IsLocked());\n tester->EnterPassword(\"fail\");\n ui_test_utils::RunAllPendingInMessageLoop();\n EXPECT_TRUE(tester->IsLocked());\n tester->EnterPassword(\"pass\");\n ui_test_utils::RunAllPendingInMessageLoop();\n \/\/ Successful authentication simply send a unlock request to PowerManager.\n EXPECT_TRUE(tester->IsLocked());\n\n \/\/ Emulate LockScreen request from PowerManager (via SessionManager).\n \/\/ TODO(oshima): Find out better way to handle this in mock.\n ScreenLocker::Hide();\n ui_test_utils::RunAllPendingInMessageLoop();\n EXPECT_FALSE(tester->IsLocked());\n}\n\nIN_PROC_BROWSER_TEST_F(ScreenLockerTest, TestFullscreenExit) {\n EXPECT_CALL(*mock_screen_lock_library_, NotifyScreenUnlockRequested())\n .Times(1)\n .RetiresOnSaturation();\n EXPECT_CALL(*mock_screen_lock_library_, NotifyScreenLockCompleted())\n .Times(1)\n .RetiresOnSaturation();\n scoped_ptr<test::ScreenLockerTester> tester(ScreenLocker::GetTester());\n {\n Waiter waiter(browser());\n browser()->ToggleFullscreenMode();\n waiter.Wait(false \/* not locked *\/, true \/* full screen *\/);\n EXPECT_TRUE(browser()->window()->IsFullscreen());\n EXPECT_FALSE(tester->IsLocked());\n }\n {\n Waiter waiter(browser());\n UserManager::Get()->UserLoggedIn(\"user\");\n ScreenLocker::Show();\n tester->EmulateWindowManagerReady();\n waiter.Wait(true \/* locked *\/, false \/* full screen *\/);\n EXPECT_FALSE(browser()->window()->IsFullscreen());\n EXPECT_TRUE(tester->IsLocked());\n }\n tester->InjectMockAuthenticator(\"user\", \"pass\");\n tester->EnterPassword(\"pass\");\n ui_test_utils::RunAllPendingInMessageLoop();\n ScreenLocker::Hide();\n ui_test_utils::RunAllPendingInMessageLoop();\n EXPECT_FALSE(tester->IsLocked());\n}\n\nvoid MouseMove(views::Widget* widget) {\n ui_controls::SendMouseMove(10, 10);\n}\n\n\/\/ Crashes on chromeos. http:\/\/crbug.com\/79164\nIN_PROC_BROWSER_TEST_F(ScreenLockerTest, DISABLED_TestNoPasswordWithMouseMove) {\n TestNoPassword(MouseMove);\n}\n\nvoid MouseClick(views::Widget* widget) {\n ui_controls::SendMouseClick(ui_controls::RIGHT);\n}\n\n\/\/ Crashes on chromeos. http:\/\/crbug.com\/79164\nIN_PROC_BROWSER_TEST_F(ScreenLockerTest,\n DISABLED_TestNoPasswordWithMouseClick) {\n TestNoPassword(MouseClick);\n}\n\nvoid KeyPress(views::Widget* widget) {\n ui_controls::SendKeyPress(GTK_WINDOW(widget->GetNativeView()),\n ui::VKEY_SPACE, false, false, false, false);\n}\n\n\/\/ Crashes on chromeos. http:\/\/crbug.com\/79164\nIN_PROC_BROWSER_TEST_F(ScreenLockerTest, DISABLED_TestNoPasswordWithKeyPress) {\n TestNoPassword(KeyPress);\n}\n\n\/\/ See http:\/\/crbug.com\/78764.\nIN_PROC_BROWSER_TEST_F(ScreenLockerTest, DISABLED_TestShowTwice) {\n EXPECT_CALL(*mock_screen_lock_library_, NotifyScreenLockCompleted())\n .Times(2)\n .RetiresOnSaturation();\n scoped_ptr<test::ScreenLockerTester> tester(ScreenLocker::GetTester());\n LockScreenWithUser(tester.get(), \"user\");\n\n \/\/ Ensure there's a profile or this test crashes.\n ProfileManager::GetDefaultProfile();\n\n \/\/ Calling Show again simply send LockCompleted signal.\n ScreenLocker::Show();\n EXPECT_TRUE(tester->IsLocked());\n\n \/\/ Close the locker to match expectations.\n ScreenLocker::Hide();\n ui_test_utils::RunAllPendingInMessageLoop();\n EXPECT_FALSE(tester->IsLocked());\n}\n\n\/\/ See http:\/\/crbug.com\/78764.\nIN_PROC_BROWSER_TEST_F(ScreenLockerTest, DISABLED_TestEscape) {\n EXPECT_CALL(*mock_screen_lock_library_, NotifyScreenLockCompleted())\n .Times(1)\n .RetiresOnSaturation();\n scoped_ptr<test::ScreenLockerTester> tester(ScreenLocker::GetTester());\n LockScreenWithUser(tester.get(), \"user\");\n\n \/\/ Ensure there's a profile or this test crashes.\n ProfileManager::GetDefaultProfile();\n\n tester->SetPassword(\"password\");\n EXPECT_EQ(\"password\", tester->GetPassword());\n \/\/ Escape clears the password.\n ui_controls::SendKeyPress(GTK_WINDOW(tester->GetWidget()->GetNativeView()),\n ui::VKEY_ESCAPE, false, false, false, false);\n ui_test_utils::RunAllPendingInMessageLoop();\n EXPECT_EQ(\"\", tester->GetPassword());\n\n \/\/ Close the locker to match expectations.\n ScreenLocker::Hide();\n ui_test_utils::RunAllPendingInMessageLoop();\n EXPECT_FALSE(tester->IsLocked());\n}\n\n} \/\/ namespace chromeos\n<|endoftext|>"} {"text":"<commit_before>\/** \\brief Utility for removing unreferences authority records\n * \\author Dr. Johannes Ruscheinski (johannes.ruscheinski@uni-tuebingen.de)\n *\n * \\copyright 2015-2017 Universitätsbibliothek Tübingen. All rights reserved.\n *\n * This program is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License as\n * published by the Free Software Foundation, either version 3 of the\n * License, or (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Affero General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public License\n * along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n*\/\n\n#include <iostream>\n#include <stdexcept>\n#include <unordered_set>\n#include <vector>\n#include <cstdio>\n#include <cstdlib>\n#include \"FileUtil.h\"\n#include \"Leader.h\"\n#include \"MarcReader.h\"\n#include \"MarcRecord.h\"\n#include \"MarcWriter.h\"\n#include \"RegexMatcher.h\"\n#include \"StringUtil.h\"\n#include \"util.h\"\n\n\nnamespace {\n\n\nvoid Usage() __attribute__((noreturn));\n\n\nvoid Usage() {\n std::cerr << \"Usage: \" << ::progname << \" title_data authority_data filtered_authority_data\\n\";\n std::exit(EXIT_FAILURE);\n}\n\n\nvoid CollectGNDReferences(MarcReader * const marc_reader, std::unordered_set<std::string> * const gnd_numbers) {\n std::string err_msg;\n RegexMatcher * const matcher(RegexMatcher::RegexMatcherFactory(\"\\x1F\"\"0\\\\(DE-588\\\\)([^\\x1F]+).*\\x1F\"\"2gnd\",\n &err_msg));\n if (matcher == nullptr)\n logger->error(\"failed to compile a regex in CollectGNDReferences: \" + err_msg);\n\n unsigned record_count(0);\n while (const MarcRecord record = marc_reader->read()) {\n ++record_count;\n\n for (const auto field_contents : record) {\n if (matcher->matched(field_contents))\n gnd_numbers->emplace((*matcher)[1]);\n }\n }\n\n std::cout << \"Extracted \" << gnd_numbers->size() << \" GND number(s) from \" << record_count\n << \" title record(s).\\n\";\n}\n\n\nstd::string GetGNDNumber(const MarcRecord &record) {\n std::vector<size_t> _035_indices;\n record.getFieldIndices(\"035\", &_035_indices);\n\n for (const auto index : _035_indices) {\n const Subfields _035_subfields(record.getFieldData(index));\n const std::string _035a_contents(_035_subfields.getFirstSubfieldValue('a'));\n if (StringUtil::StartsWith(_035a_contents, \"(DE-588)\"))\n return _035a_contents.substr(__builtin_strlen(\"(DE-588)\"));\n }\n\n return \"\";\n}\n\n\nconst std::string DROPPED_GND_LIST_FILE(\"\/usr\/local\/var\/log\/tuelib\/dropped_gnd_numbers.list\");\n\n\nvoid FilterAuthorityData(MarcReader * const marc_reader, MarcWriter * const marc_writer,\n const std::unordered_set<std::string> &gnd_numbers)\n{\n std::unique_ptr<File> gnd_list_file(FileUtil::OpenOutputFileOrDie(DROPPED_GND_LIST_FILE));\n unsigned record_count(0), dropped_count(0);\n while (const MarcRecord record = marc_reader->read()) {\n ++record_count;\n\n const std::string gnd_number(GetGNDNumber(record));\n if (gnd_number.empty())\n std::cerr << \"Did not find a GND number for authirity record witnb PPN \" << record.getControlNumber()\n << \".\\n\";\n else if (gnd_numbers.find(gnd_number) != gnd_numbers.cend()) {\n gnd_list_file->write(gnd_number + \"\\n\");\n ++dropped_count;\n } else\n marc_writer->write(record);\n }\n\n std::cerr << \"Read \" << record_count << \" authority record(s) of which \" << dropped_count << \" were dropped.\\n\";\n}\n\n\n} \/\/ unnamed namespace\n\n\nint main(int argc, char *argv[]) {\n ::progname = argv[0];\n\n if (argc != 4)\n Usage();\n\n try {\n std::unique_ptr<MarcReader> marc_title_reader(MarcReader::Factory(argv[1]));\n std::unique_ptr<MarcReader> marc_authority_reader(MarcReader::Factory(argv[2]));\n std::unique_ptr<MarcWriter> marc_authority_writer(MarcWriter::Factory(argv[3]));\n\n std::unordered_set<std::string> gnd_numbers;\n CollectGNDReferences(marc_title_reader.get(), &gnd_numbers);\n FilterAuthorityData(marc_authority_reader.get(), marc_authority_writer.get(), gnd_numbers);\n } catch (const std::exception &e) {\n logger->error(\"Caught exception: \" + std::string(e.what()));\n }\n}\n<commit_msg>Update remove_unused_authority_records.cc<commit_after>\/** \\brief Utility for removing unreferences authority records\n * \\author Dr. Johannes Ruscheinski (johannes.ruscheinski@uni-tuebingen.de)\n *\n * \\copyright 2015-2017 Universitätsbibliothek Tübingen. All rights reserved.\n *\n * This program is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License as\n * published by the Free Software Foundation, either version 3 of the\n * License, or (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Affero General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public License\n * along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n*\/\n\n#include <iostream>\n#include <stdexcept>\n#include <unordered_set>\n#include <vector>\n#include <cstdio>\n#include <cstdlib>\n#include \"FileUtil.h\"\n#include \"Leader.h\"\n#include \"MarcReader.h\"\n#include \"MarcRecord.h\"\n#include \"MarcWriter.h\"\n#include \"RegexMatcher.h\"\n#include \"StringUtil.h\"\n#include \"util.h\"\n\n\nnamespace {\n\n\nvoid Usage() __attribute__((noreturn));\n\n\nvoid Usage() {\n std::cerr << \"Usage: \" << ::progname << \" title_data authority_data filtered_authority_data\\n\";\n std::exit(EXIT_FAILURE);\n}\n\n\nvoid CollectGNDReferences(MarcReader * const marc_reader, std::unordered_set<std::string> * const gnd_numbers) {\n std::string err_msg;\n RegexMatcher * const matcher(RegexMatcher::RegexMatcherFactory(\"\\x1F\"\"0\\\\(DE-588\\\\)([^\\x1F]+).*\\x1F\"\"2gnd\",\n &err_msg));\n if (matcher == nullptr)\n logger->error(\"failed to compile a regex in CollectGNDReferences: \" + err_msg);\n\n unsigned record_count(0);\n while (const MarcRecord record = marc_reader->read()) {\n ++record_count;\n\n for (const auto field_contents : record) {\n if (matcher->matched(field_contents))\n gnd_numbers->emplace((*matcher)[1]);\n }\n }\n\n std::cout << \"Extracted \" << gnd_numbers->size() << \" GND number(s) from \" << record_count\n << \" title record(s).\\n\";\n}\n\n\nstd::string GetGNDNumber(const MarcRecord &record) {\n std::vector<size_t> _035_indices;\n record.getFieldIndices(\"035\", &_035_indices);\n\n for (const auto index : _035_indices) {\n const Subfields _035_subfields(record.getFieldData(index));\n const std::string _035a_contents(_035_subfields.getFirstSubfieldValue('a'));\n if (StringUtil::StartsWith(_035a_contents, \"(DE-588)\"))\n return _035a_contents.substr(__builtin_strlen(\"(DE-588)\"));\n }\n\n return \"\";\n}\n\n\nconst std::string DROPPED_GND_LIST_FILE(\"\/usr\/local\/var\/log\/tufind\/dropped_gnd_numbers.list\");\n\n\nvoid FilterAuthorityData(MarcReader * const marc_reader, MarcWriter * const marc_writer,\n const std::unordered_set<std::string> &gnd_numbers)\n{\n std::unique_ptr<File> gnd_list_file(FileUtil::OpenOutputFileOrDie(DROPPED_GND_LIST_FILE));\n unsigned record_count(0), dropped_count(0);\n while (const MarcRecord record = marc_reader->read()) {\n ++record_count;\n\n const std::string gnd_number(GetGNDNumber(record));\n if (gnd_number.empty())\n std::cerr << \"Did not find a GND number for authirity record witnb PPN \" << record.getControlNumber()\n << \".\\n\";\n else if (gnd_numbers.find(gnd_number) != gnd_numbers.cend()) {\n gnd_list_file->write(gnd_number + \"\\n\");\n ++dropped_count;\n } else\n marc_writer->write(record);\n }\n\n std::cerr << \"Read \" << record_count << \" authority record(s) of which \" << dropped_count << \" were dropped.\\n\";\n}\n\n\n} \/\/ unnamed namespace\n\n\nint main(int argc, char *argv[]) {\n ::progname = argv[0];\n\n if (argc != 4)\n Usage();\n\n try {\n std::unique_ptr<MarcReader> marc_title_reader(MarcReader::Factory(argv[1]));\n std::unique_ptr<MarcReader> marc_authority_reader(MarcReader::Factory(argv[2]));\n std::unique_ptr<MarcWriter> marc_authority_writer(MarcWriter::Factory(argv[3]));\n\n std::unordered_set<std::string> gnd_numbers;\n CollectGNDReferences(marc_title_reader.get(), &gnd_numbers);\n FilterAuthorityData(marc_authority_reader.get(), marc_authority_writer.get(), gnd_numbers);\n } catch (const std::exception &e) {\n logger->error(\"Caught exception: \" + std::string(e.what()));\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2011 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"net\/disk_cache\/file.h\"\n\n#include <fcntl.h>\n\n#include \"base\/logging.h\"\n#include \"base\/threading\/worker_pool.h\"\n#include \"net\/base\/net_errors.h\"\n#include \"net\/disk_cache\/disk_cache.h\"\n#include \"net\/disk_cache\/in_flight_io.h\"\n\nnamespace {\n\n\/\/ This class represents a single asynchronous IO operation while it is being\n\/\/ bounced between threads.\nclass FileBackgroundIO : public disk_cache::BackgroundIO {\n public:\n \/\/ Other than the actual parameters for the IO operation (including the\n \/\/ |callback| that must be notified at the end), we need the controller that\n \/\/ is keeping track of all operations. When done, we notify the controller\n \/\/ (we do NOT invoke the callback), in the worker thead that completed the\n \/\/ operation.\n FileBackgroundIO(disk_cache::File* file, const void* buf, size_t buf_len,\n size_t offset, disk_cache::FileIOCallback* callback,\n disk_cache::InFlightIO* controller)\n : disk_cache::BackgroundIO(controller), callback_(callback), file_(file),\n buf_(buf), buf_len_(buf_len), offset_(offset) {\n }\n\n disk_cache::FileIOCallback* callback() {\n return callback_;\n }\n\n disk_cache::File* file() {\n return file_;\n }\n\n \/\/ Read and Write are the operations that can be performed asynchronously.\n \/\/ The actual parameters for the operation are setup in the constructor of\n \/\/ the object. Both methods should be called from a worker thread, by posting\n \/\/ a task to the WorkerPool (they are RunnableMethods). When finished,\n \/\/ controller->OnIOComplete() is called.\n void Read();\n void Write();\n\n private:\n ~FileBackgroundIO() {}\n\n disk_cache::FileIOCallback* callback_;\n\n disk_cache::File* file_;\n const void* buf_;\n size_t buf_len_;\n size_t offset_;\n\n DISALLOW_COPY_AND_ASSIGN(FileBackgroundIO);\n};\n\n\n\/\/ The specialized controller that keeps track of current operations.\nclass FileInFlightIO : public disk_cache::InFlightIO {\n public:\n FileInFlightIO() {}\n ~FileInFlightIO() {}\n\n \/\/ These methods start an asynchronous operation. The arguments have the same\n \/\/ semantics of the File asynchronous operations, with the exception that the\n \/\/ operation never finishes synchronously.\n void PostRead(disk_cache::File* file, void* buf, size_t buf_len,\n size_t offset, disk_cache::FileIOCallback* callback);\n void PostWrite(disk_cache::File* file, const void* buf, size_t buf_len,\n size_t offset, disk_cache::FileIOCallback* callback);\n\n protected:\n \/\/ Invokes the users' completion callback at the end of the IO operation.\n \/\/ |cancel| is true if the actual task posted to the thread is still\n \/\/ queued (because we are inside WaitForPendingIO), and false if said task is\n \/\/ the one performing the call.\n virtual void OnOperationComplete(disk_cache::BackgroundIO* operation,\n bool cancel);\n\n private:\n DISALLOW_COPY_AND_ASSIGN(FileInFlightIO);\n};\n\n\/\/ ---------------------------------------------------------------------------\n\n\/\/ Runs on a worker thread.\nvoid FileBackgroundIO::Read() {\n if (file_->Read(const_cast<void*>(buf_), buf_len_, offset_)) {\n result_ = static_cast<int>(buf_len_);\n } else {\n result_ = net::ERR_CACHE_READ_FAILURE;\n }\n controller_->OnIOComplete(this);\n}\n\n\/\/ Runs on a worker thread.\nvoid FileBackgroundIO::Write() {\n bool rv = file_->Write(buf_, buf_len_, offset_);\n\n result_ = rv ? static_cast<int>(buf_len_) : net::ERR_CACHE_WRITE_FAILURE;\n controller_->OnIOComplete(this);\n}\n\n\/\/ ---------------------------------------------------------------------------\n\nvoid FileInFlightIO::PostRead(disk_cache::File *file, void* buf, size_t buf_len,\n size_t offset, disk_cache::FileIOCallback *callback) {\n scoped_refptr<FileBackgroundIO> operation(\n new FileBackgroundIO(file, buf, buf_len, offset, callback, this));\n file->AddRef(); \/\/ Balanced on OnOperationComplete()\n\n base::WorkerPool::PostTask(FROM_HERE,\n NewRunnableMethod(operation.get(), &FileBackgroundIO::Read), true);\n OnOperationPosted(operation);\n}\n\nvoid FileInFlightIO::PostWrite(disk_cache::File* file, const void* buf,\n size_t buf_len, size_t offset,\n disk_cache::FileIOCallback* callback) {\n scoped_refptr<FileBackgroundIO> operation(\n new FileBackgroundIO(file, buf, buf_len, offset, callback, this));\n file->AddRef(); \/\/ Balanced on OnOperationComplete()\n\n base::WorkerPool::PostTask(FROM_HERE,\n NewRunnableMethod(operation.get(), &FileBackgroundIO::Write), true);\n OnOperationPosted(operation);\n}\n\n\/\/ Runs on the IO thread.\nvoid FileInFlightIO::OnOperationComplete(disk_cache::BackgroundIO* operation,\n bool cancel) {\n FileBackgroundIO* op = static_cast<FileBackgroundIO*>(operation);\n\n disk_cache::FileIOCallback* callback = op->callback();\n int bytes = operation->result();\n\n \/\/ Release the references acquired in PostRead \/ PostWrite.\n op->file()->Release();\n callback->OnFileIOComplete(bytes);\n}\n\n\/\/ A static object tha will broker all async operations.\nFileInFlightIO* s_file_operations = NULL;\n\n\/\/ Returns the current FileInFlightIO.\nFileInFlightIO* GetFileInFlightIO() {\n if (!s_file_operations) {\n s_file_operations = new FileInFlightIO;\n }\n return s_file_operations;\n}\n\n\/\/ Deletes the current FileInFlightIO.\nvoid DeleteFileInFlightIO() {\n DCHECK(s_file_operations);\n delete s_file_operations;\n s_file_operations = NULL;\n}\n\n} \/\/ namespace\n\nnamespace disk_cache {\n\nFile::File(base::PlatformFile file)\n : init_(true),\n mixed_(true),\n platform_file_(file),\n sync_platform_file_(base::kInvalidPlatformFileValue) {\n}\n\nbool File::Init(const FilePath& name) {\n if (init_)\n return false;\n\n int flags = base::PLATFORM_FILE_OPEN |\n base::PLATFORM_FILE_READ |\n base::PLATFORM_FILE_WRITE;\n platform_file_ = base::CreatePlatformFile(name, flags, NULL, NULL);\n if (platform_file_ < 0) {\n platform_file_ = 0;\n return false;\n }\n\n init_ = true;\n return true;\n}\n\nbase::PlatformFile File::platform_file() const {\n return platform_file_;\n}\n\nbool File::IsValid() const {\n if (!init_)\n return false;\n return (base::kInvalidPlatformFileValue != platform_file_);\n}\n\nbool File::Read(void* buffer, size_t buffer_len, size_t offset) {\n DCHECK(init_);\n if (buffer_len > ULONG_MAX || offset > LONG_MAX)\n return false;\n\n int ret = pread(platform_file_, buffer, buffer_len, offset);\n return (static_cast<size_t>(ret) == buffer_len);\n}\n\nbool File::Write(const void* buffer, size_t buffer_len, size_t offset) {\n DCHECK(init_);\n if (buffer_len > ULONG_MAX || offset > ULONG_MAX)\n return false;\n\n int ret = pwrite(platform_file_, buffer, buffer_len, offset);\n return (static_cast<size_t>(ret) == buffer_len);\n}\n\n\/\/ We have to increase the ref counter of the file before performing the IO to\n\/\/ prevent the completion to happen with an invalid handle (if the file is\n\/\/ closed while the IO is in flight).\nbool File::Read(void* buffer, size_t buffer_len, size_t offset,\n FileIOCallback* callback, bool* completed) {\n DCHECK(init_);\n if (!callback) {\n if (completed)\n *completed = true;\n return Read(buffer, buffer_len, offset);\n }\n\n if (buffer_len > ULONG_MAX || offset > ULONG_MAX)\n return false;\n\n GetFileInFlightIO()->PostRead(this, buffer, buffer_len, offset, callback);\n\n *completed = false;\n return true;\n}\n\nbool File::Write(const void* buffer, size_t buffer_len, size_t offset,\n FileIOCallback* callback, bool* completed) {\n DCHECK(init_);\n if (!callback) {\n if (completed)\n *completed = true;\n return Write(buffer, buffer_len, offset);\n }\n\n return AsyncWrite(buffer, buffer_len, offset, callback, completed);\n}\n\nbool File::SetLength(size_t length) {\n DCHECK(init_);\n if (length > ULONG_MAX)\n return false;\n\n return 0 == ftruncate(platform_file_, length);\n}\n\nsize_t File::GetLength() {\n DCHECK(init_);\n off_t ret = lseek(platform_file_, 0, SEEK_END);\n if (ret < 0)\n return 0;\n return ret;\n}\n\n\/\/ Static.\nvoid File::WaitForPendingIO(int* num_pending_io) {\n \/\/ We may be running unit tests so we should allow be able to reset the\n \/\/ message loop.\n GetFileInFlightIO()->WaitForPendingIO();\n DeleteFileInFlightIO();\n}\n\nFile::~File() {\n if (IsValid())\n close(platform_file_);\n}\n\nbool File::AsyncWrite(const void* buffer, size_t buffer_len, size_t offset,\n FileIOCallback* callback, bool* completed) {\n DCHECK(init_);\n if (buffer_len > ULONG_MAX || offset > ULONG_MAX)\n return false;\n\n GetFileInFlightIO()->PostWrite(this, buffer, buffer_len, offset, callback);\n\n if (completed)\n *completed = false;\n return true;\n}\n\n} \/\/ namespace disk_cache\n<commit_msg>Disk cache: Use platform_file functions for POSIX.<commit_after>\/\/ Copyright (c) 2011 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"net\/disk_cache\/file.h\"\n\n#include <fcntl.h>\n\n#include \"base\/logging.h\"\n#include \"base\/threading\/worker_pool.h\"\n#include \"net\/base\/net_errors.h\"\n#include \"net\/disk_cache\/disk_cache.h\"\n#include \"net\/disk_cache\/in_flight_io.h\"\n\nnamespace {\n\n\/\/ This class represents a single asynchronous IO operation while it is being\n\/\/ bounced between threads.\nclass FileBackgroundIO : public disk_cache::BackgroundIO {\n public:\n \/\/ Other than the actual parameters for the IO operation (including the\n \/\/ |callback| that must be notified at the end), we need the controller that\n \/\/ is keeping track of all operations. When done, we notify the controller\n \/\/ (we do NOT invoke the callback), in the worker thead that completed the\n \/\/ operation.\n FileBackgroundIO(disk_cache::File* file, const void* buf, size_t buf_len,\n size_t offset, disk_cache::FileIOCallback* callback,\n disk_cache::InFlightIO* controller)\n : disk_cache::BackgroundIO(controller), callback_(callback), file_(file),\n buf_(buf), buf_len_(buf_len), offset_(offset) {\n }\n\n disk_cache::FileIOCallback* callback() {\n return callback_;\n }\n\n disk_cache::File* file() {\n return file_;\n }\n\n \/\/ Read and Write are the operations that can be performed asynchronously.\n \/\/ The actual parameters for the operation are setup in the constructor of\n \/\/ the object. Both methods should be called from a worker thread, by posting\n \/\/ a task to the WorkerPool (they are RunnableMethods). When finished,\n \/\/ controller->OnIOComplete() is called.\n void Read();\n void Write();\n\n private:\n ~FileBackgroundIO() {}\n\n disk_cache::FileIOCallback* callback_;\n\n disk_cache::File* file_;\n const void* buf_;\n size_t buf_len_;\n size_t offset_;\n\n DISALLOW_COPY_AND_ASSIGN(FileBackgroundIO);\n};\n\n\n\/\/ The specialized controller that keeps track of current operations.\nclass FileInFlightIO : public disk_cache::InFlightIO {\n public:\n FileInFlightIO() {}\n ~FileInFlightIO() {}\n\n \/\/ These methods start an asynchronous operation. The arguments have the same\n \/\/ semantics of the File asynchronous operations, with the exception that the\n \/\/ operation never finishes synchronously.\n void PostRead(disk_cache::File* file, void* buf, size_t buf_len,\n size_t offset, disk_cache::FileIOCallback* callback);\n void PostWrite(disk_cache::File* file, const void* buf, size_t buf_len,\n size_t offset, disk_cache::FileIOCallback* callback);\n\n protected:\n \/\/ Invokes the users' completion callback at the end of the IO operation.\n \/\/ |cancel| is true if the actual task posted to the thread is still\n \/\/ queued (because we are inside WaitForPendingIO), and false if said task is\n \/\/ the one performing the call.\n virtual void OnOperationComplete(disk_cache::BackgroundIO* operation,\n bool cancel);\n\n private:\n DISALLOW_COPY_AND_ASSIGN(FileInFlightIO);\n};\n\n\/\/ ---------------------------------------------------------------------------\n\n\/\/ Runs on a worker thread.\nvoid FileBackgroundIO::Read() {\n if (file_->Read(const_cast<void*>(buf_), buf_len_, offset_)) {\n result_ = static_cast<int>(buf_len_);\n } else {\n result_ = net::ERR_CACHE_READ_FAILURE;\n }\n controller_->OnIOComplete(this);\n}\n\n\/\/ Runs on a worker thread.\nvoid FileBackgroundIO::Write() {\n bool rv = file_->Write(buf_, buf_len_, offset_);\n\n result_ = rv ? static_cast<int>(buf_len_) : net::ERR_CACHE_WRITE_FAILURE;\n controller_->OnIOComplete(this);\n}\n\n\/\/ ---------------------------------------------------------------------------\n\nvoid FileInFlightIO::PostRead(disk_cache::File *file, void* buf, size_t buf_len,\n size_t offset, disk_cache::FileIOCallback *callback) {\n scoped_refptr<FileBackgroundIO> operation(\n new FileBackgroundIO(file, buf, buf_len, offset, callback, this));\n file->AddRef(); \/\/ Balanced on OnOperationComplete()\n\n base::WorkerPool::PostTask(FROM_HERE,\n NewRunnableMethod(operation.get(), &FileBackgroundIO::Read), true);\n OnOperationPosted(operation);\n}\n\nvoid FileInFlightIO::PostWrite(disk_cache::File* file, const void* buf,\n size_t buf_len, size_t offset,\n disk_cache::FileIOCallback* callback) {\n scoped_refptr<FileBackgroundIO> operation(\n new FileBackgroundIO(file, buf, buf_len, offset, callback, this));\n file->AddRef(); \/\/ Balanced on OnOperationComplete()\n\n base::WorkerPool::PostTask(FROM_HERE,\n NewRunnableMethod(operation.get(), &FileBackgroundIO::Write), true);\n OnOperationPosted(operation);\n}\n\n\/\/ Runs on the IO thread.\nvoid FileInFlightIO::OnOperationComplete(disk_cache::BackgroundIO* operation,\n bool cancel) {\n FileBackgroundIO* op = static_cast<FileBackgroundIO*>(operation);\n\n disk_cache::FileIOCallback* callback = op->callback();\n int bytes = operation->result();\n\n \/\/ Release the references acquired in PostRead \/ PostWrite.\n op->file()->Release();\n callback->OnFileIOComplete(bytes);\n}\n\n\/\/ A static object tha will broker all async operations.\nFileInFlightIO* s_file_operations = NULL;\n\n\/\/ Returns the current FileInFlightIO.\nFileInFlightIO* GetFileInFlightIO() {\n if (!s_file_operations) {\n s_file_operations = new FileInFlightIO;\n }\n return s_file_operations;\n}\n\n\/\/ Deletes the current FileInFlightIO.\nvoid DeleteFileInFlightIO() {\n DCHECK(s_file_operations);\n delete s_file_operations;\n s_file_operations = NULL;\n}\n\n} \/\/ namespace\n\nnamespace disk_cache {\n\nFile::File(base::PlatformFile file)\n : init_(true),\n mixed_(true),\n platform_file_(file),\n sync_platform_file_(base::kInvalidPlatformFileValue) {\n}\n\nbool File::Init(const FilePath& name) {\n if (init_)\n return false;\n\n int flags = base::PLATFORM_FILE_OPEN |\n base::PLATFORM_FILE_READ |\n base::PLATFORM_FILE_WRITE;\n platform_file_ = base::CreatePlatformFile(name, flags, NULL, NULL);\n if (platform_file_ < 0) {\n platform_file_ = 0;\n return false;\n }\n\n init_ = true;\n return true;\n}\n\nbase::PlatformFile File::platform_file() const {\n return platform_file_;\n}\n\nbool File::IsValid() const {\n if (!init_)\n return false;\n return (base::kInvalidPlatformFileValue != platform_file_);\n}\n\nbool File::Read(void* buffer, size_t buffer_len, size_t offset) {\n DCHECK(init_);\n if (buffer_len > static_cast<size_t>(kint32max) ||\n offset > static_cast<size_t>(kint32max))\n return false;\n\n int ret = base::ReadPlatformFile(platform_file_, offset,\n static_cast<char*>(buffer), buffer_len);\n return (static_cast<size_t>(ret) == buffer_len);\n}\n\nbool File::Write(const void* buffer, size_t buffer_len, size_t offset) {\n DCHECK(init_);\n if (buffer_len > static_cast<size_t>(kint32max) ||\n offset > static_cast<size_t>(kint32max))\n return false;\n\n int ret = base::WritePlatformFile(platform_file_, offset,\n static_cast<const char*>(buffer),\n buffer_len);\n return (static_cast<size_t>(ret) == buffer_len);\n}\n\n\/\/ We have to increase the ref counter of the file before performing the IO to\n\/\/ prevent the completion to happen with an invalid handle (if the file is\n\/\/ closed while the IO is in flight).\nbool File::Read(void* buffer, size_t buffer_len, size_t offset,\n FileIOCallback* callback, bool* completed) {\n DCHECK(init_);\n if (!callback) {\n if (completed)\n *completed = true;\n return Read(buffer, buffer_len, offset);\n }\n\n if (buffer_len > ULONG_MAX || offset > ULONG_MAX)\n return false;\n\n GetFileInFlightIO()->PostRead(this, buffer, buffer_len, offset, callback);\n\n *completed = false;\n return true;\n}\n\nbool File::Write(const void* buffer, size_t buffer_len, size_t offset,\n FileIOCallback* callback, bool* completed) {\n DCHECK(init_);\n if (!callback) {\n if (completed)\n *completed = true;\n return Write(buffer, buffer_len, offset);\n }\n\n return AsyncWrite(buffer, buffer_len, offset, callback, completed);\n}\n\nbool File::SetLength(size_t length) {\n DCHECK(init_);\n if (length > ULONG_MAX)\n return false;\n\n return base::TruncatePlatformFile(platform_file_, length);\n}\n\nsize_t File::GetLength() {\n DCHECK(init_);\n off_t ret = lseek(platform_file_, 0, SEEK_END);\n if (ret < 0)\n return 0;\n return ret;\n}\n\n\/\/ Static.\nvoid File::WaitForPendingIO(int* num_pending_io) {\n \/\/ We may be running unit tests so we should allow be able to reset the\n \/\/ message loop.\n GetFileInFlightIO()->WaitForPendingIO();\n DeleteFileInFlightIO();\n}\n\nFile::~File() {\n if (IsValid())\n base::ClosePlatformFile(platform_file_);\n}\n\nbool File::AsyncWrite(const void* buffer, size_t buffer_len, size_t offset,\n FileIOCallback* callback, bool* completed) {\n DCHECK(init_);\n if (buffer_len > ULONG_MAX || offset > ULONG_MAX)\n return false;\n\n GetFileInFlightIO()->PostWrite(this, buffer, buffer_len, offset, callback);\n\n if (completed)\n *completed = false;\n return true;\n}\n\n} \/\/ namespace disk_cache\n<|endoftext|>"} {"text":"<commit_before>\/* \n * Copyright 2010-2011 PathScale, Inc. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * 1. Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n *\n * 2. Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and\/or other materials provided with the distribution.\n * \n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS\n * IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,\n * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR\n * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;\n * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR\n * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF\n * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n\/**\n * memory.cc - Contains stub definition of C++ new\/delete operators.\n *\n * These definitions are intended to be used for testing and are weak symbols\n * to allow them to be replaced by definitions from a STL implementation.\n * These versions simply wrap malloc() and free(), they do not provide a\n * C++-specific allocator.\n *\/\n\n#include <stddef.h>\n#include <stdlib.h>\n#include \"stdexcept.h\"\n#include \"atomic.h\"\n\n\nnamespace std\n{\n\tstruct nothrow_t {};\n}\n\n\n\/\/\/ The type of the function called when allocation fails.\ntypedef void (*new_handler)();\n\/**\n * The function to call when allocation fails. By default, there is no\n * handler and a bad allocation exception is thrown if an allocation fails.\n *\/\nstatic new_handler new_handl;\n\nnamespace std\n{\n\t\/**\n\t * Sets a function to be called when there is a failure in new.\n\t *\/\n\t__attribute__((weak))\n\tnew_handler set_new_handler(new_handler handler)\n\t{\n\t\treturn ATOMIC_SWAP(&new_handl, handler);\n\t}\n\t__attribute__((weak))\n\tnew_handler get_new_handler(void)\n\t{\n\t\treturn ATOMIC_LOAD(&new_handl);\n\t}\n}\n\n\n__attribute__((weak))\nvoid* operator new(size_t size)\n{\n\tif (0 == size)\n\t{\n\t\tsize = 1;\n\t}\n\tvoid * mem = malloc(size);\n\twhile (0 == mem)\n\t{\n\t\tnew_handler h = std::get_new_handler();\n\t\tif (0 != h)\n\t\t{\n\t\t\th();\n\t\t}\n\t\telse\n\t\t{\n\t\t\tthrow std::bad_alloc();\n\t\t}\n\t\tmem = malloc(size);\n\t}\n\n\treturn mem;\n}\n\n__attribute__((weak))\nvoid* operator new(size_t size, const std::nothrow_t &) throw()\n{\n\ttry {\n\t\treturn :: operator new(size);\n\t} catch (...) {\n\t\t\/\/ nothrow operator new should return NULL in case of\n\t\t\/\/ std::bad_alloc exception in new handler\n\t\treturn NULL;\n\t}\n}\n\n\n__attribute__((weak))\nvoid operator delete(void * ptr)\n{\n\tfree(ptr);\n}\n\n\n__attribute__((weak))\nvoid * operator new[](size_t size)\n{\n\treturn ::operator new(size);\n}\n\n\n__attribute__((weak))\nvoid * operator new[](size_t size, const std::nothrow_t &) throw()\n{\n\ttry {\n\t\treturn ::operator new[](size);\n\t} catch (...) {\n\t\t\/\/ nothrow operator new should return NULL in case of\n\t\t\/\/ std::bad_alloc exception in new handler\n\t\treturn NULL;\n\t}\n}\n\n\n__attribute__((weak))\nvoid operator delete[](void * ptr) throw()\n{\n\t::operator delete(ptr);\n}\n\n\n<commit_msg>am 67917c05: Make exception specifications conditional on language dialect for new \/ delete operators (fixes warnings when compiling as C++11)<commit_after>\/* \n * Copyright 2010-2011 PathScale, Inc. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * 1. Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n *\n * 2. Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and\/or other materials provided with the distribution.\n * \n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS\n * IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,\n * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR\n * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;\n * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR\n * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF\n * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n\/**\n * memory.cc - Contains stub definition of C++ new\/delete operators.\n *\n * These definitions are intended to be used for testing and are weak symbols\n * to allow them to be replaced by definitions from a STL implementation.\n * These versions simply wrap malloc() and free(), they do not provide a\n * C++-specific allocator.\n *\/\n\n#include <stddef.h>\n#include <stdlib.h>\n#include \"stdexcept.h\"\n#include \"atomic.h\"\n\n\nnamespace std\n{\n\tstruct nothrow_t {};\n}\n\n\n\/\/\/ The type of the function called when allocation fails.\ntypedef void (*new_handler)();\n\/**\n * The function to call when allocation fails. By default, there is no\n * handler and a bad allocation exception is thrown if an allocation fails.\n *\/\nstatic new_handler new_handl;\n\nnamespace std\n{\n\t\/**\n\t * Sets a function to be called when there is a failure in new.\n\t *\/\n\t__attribute__((weak))\n\tnew_handler set_new_handler(new_handler handler)\n\t{\n\t\treturn ATOMIC_SWAP(&new_handl, handler);\n\t}\n\t__attribute__((weak))\n\tnew_handler get_new_handler(void)\n\t{\n\t\treturn ATOMIC_LOAD(&new_handl);\n\t}\n}\n\n\n__attribute__((weak))\nvoid* operator new(size_t size)\n{\n\tif (0 == size)\n\t{\n\t\tsize = 1;\n\t}\n\tvoid * mem = malloc(size);\n\twhile (0 == mem)\n\t{\n\t\tnew_handler h = std::get_new_handler();\n\t\tif (0 != h)\n\t\t{\n\t\t\th();\n\t\t}\n\t\telse\n\t\t{\n\t\t\tthrow std::bad_alloc();\n\t\t}\n\t\tmem = malloc(size);\n\t}\n\n\treturn mem;\n}\n\n__attribute__((weak))\nvoid* operator new(size_t size, const std::nothrow_t &) throw()\n{\n\ttry {\n\t\treturn :: operator new(size);\n\t} catch (...) {\n\t\t\/\/ nothrow operator new should return NULL in case of\n\t\t\/\/ std::bad_alloc exception in new handler\n\t\treturn NULL;\n\t}\n}\n\n\n__attribute__((weak))\nvoid operator delete(void * ptr)\n#if __cplusplus < 201000L\nthrow()\n#endif\n{\n\tfree(ptr);\n}\n\n\n__attribute__((weak))\nvoid * operator new[](size_t size)\n#if __cplusplus < 201000L\nthrow(std::bad_alloc)\n#endif\n{\n\treturn ::operator new(size);\n}\n\n\n__attribute__((weak))\nvoid * operator new[](size_t size, const std::nothrow_t &) throw()\n{\n\ttry {\n\t\treturn ::operator new[](size);\n\t} catch (...) {\n\t\t\/\/ nothrow operator new should return NULL in case of\n\t\t\/\/ std::bad_alloc exception in new handler\n\t\treturn NULL;\n\t}\n}\n\n\n__attribute__((weak))\nvoid operator delete[](void * ptr)\n#if __cplusplus < 201000L\nthrow()\n#endif\n{\n\t::operator delete(ptr);\n}\n\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 2004-2005 The Regents of The University of Michigan\n * Copyright (c) 2016 The University of Virginia\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met: redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer;\n * redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution;\n * neither the name of the copyright holders nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n * Authors: Gabe Black\n * Ali Saidi\n * Korey Sewell\n * Alec Roelke\n *\/\n#include \"arch\/riscv\/process.hh\"\n\n#include <algorithm>\n#include <cstddef>\n#include <iostream>\n#include <map>\n#include <string>\n#include <vector>\n\n#include \"arch\/riscv\/isa_traits.hh\"\n#include \"base\/loader\/elf_object.hh\"\n#include \"base\/loader\/object_file.hh\"\n#include \"base\/logging.hh\"\n#include \"cpu\/thread_context.hh\"\n#include \"debug\/Stack.hh\"\n#include \"mem\/page_table.hh\"\n#include \"params\/Process.hh\"\n#include \"sim\/aux_vector.hh\"\n#include \"sim\/process.hh\"\n#include \"sim\/process_impl.hh\"\n#include \"sim\/syscall_return.hh\"\n#include \"sim\/system.hh\"\n\nusing namespace std;\nusing namespace RiscvISA;\n\nRiscvProcess::RiscvProcess(ProcessParams * params,\n ObjectFile *objFile) : Process(params, objFile)\n{\n const Addr stack_base = 0x7FFFFFFFFFFFFFFFL;\n const Addr max_stack_size = 8 * 1024 * 1024;\n const Addr next_thread_stack_base = stack_base - max_stack_size;\n const Addr brk_point = roundUp(objFile->bssBase() + objFile->bssSize(),\n PageBytes);\n const Addr mmap_end = 0x4000000000000000L;\n memState = make_shared<MemState>(brk_point, stack_base, max_stack_size,\n next_thread_stack_base, mmap_end);\n}\n\nvoid\nRiscvProcess::initState()\n{\n Process::initState();\n\n argsInit<uint64_t>(PageBytes);\n}\n\ntemplate<class IntType> void\nRiscvProcess::argsInit(int pageSize)\n{\n updateBias();\n objFile->loadSections(initVirtMem);\n ElfObject* elfObject = dynamic_cast<ElfObject*>(objFile);\n memState->setStackMin(memState->getStackBase());\n\n \/\/ Determine stack size and populate auxv\n Addr stack_top = memState->getStackMin();\n stack_top -= elfObject->programHeaderSize();\n for (const string& arg: argv)\n stack_top -= arg.size() + 1;\n for (const string& env: envp)\n stack_top -= env.size() + 1;\n stack_top &= -sizeof(Addr);\n\n vector<AuxVector<IntType>> auxv;\n if (elfObject != nullptr) {\n auxv.push_back({M5_AT_ENTRY, objFile->entryPoint()});\n auxv.push_back({M5_AT_PHNUM, elfObject->programHeaderCount()});\n auxv.push_back({M5_AT_PHENT, elfObject->programHeaderSize()});\n auxv.push_back({M5_AT_PHDR, elfObject->programHeaderTable()});\n auxv.push_back({M5_AT_PAGESZ, PageBytes});\n auxv.push_back({M5_AT_SECURE, 0});\n auxv.push_back({M5_AT_RANDOM, stack_top});\n auxv.push_back({M5_AT_NULL, 0});\n }\n stack_top -= (1 + argv.size()) * sizeof(Addr) +\n (1 + envp.size()) * sizeof(Addr) +\n sizeof(Addr) + 2 * sizeof(IntType) * auxv.size();\n stack_top &= -2*sizeof(Addr);\n memState->setStackSize(memState->getStackBase() - stack_top);\n allocateMem(roundDown(stack_top, pageSize),\n roundUp(memState->getStackSize(), pageSize));\n\n \/\/ Copy program headers to stack\n memState->setStackMin(memState->getStackMin() -\n elfObject->programHeaderSize());\n uint8_t* phdr = new uint8_t[elfObject->programHeaderSize()];\n initVirtMem.readBlob(elfObject->programHeaderTable(), phdr,\n elfObject->programHeaderSize());\n initVirtMem.writeBlob(memState->getStackMin(), phdr,\n elfObject->programHeaderSize());\n delete phdr;\n\n \/\/ Copy argv to stack\n vector<Addr> argPointers;\n for (const string& arg: argv) {\n memState->setStackMin(memState->getStackMin() - (arg.size() + 1));\n initVirtMem.writeString(memState->getStackMin(), arg.c_str());\n argPointers.push_back(memState->getStackMin());\n if (DTRACE(Stack)) {\n string wrote;\n initVirtMem.readString(wrote, argPointers.back());\n DPRINTFN(\"Wrote arg \\\"%s\\\" to address %p\\n\",\n wrote, (void*)memState->getStackMin());\n }\n }\n argPointers.push_back(0);\n\n \/\/ Copy envp to stack\n vector<Addr> envPointers;\n for (const string& env: envp) {\n memState->setStackMin(memState->getStackMin() - (env.size() + 1));\n initVirtMem.writeString(memState->getStackMin(), env.c_str());\n envPointers.push_back(memState->getStackMin());\n DPRINTF(Stack, \"Wrote env \\\"%s\\\" to address %p\\n\",\n env, (void*)memState->getStackMin());\n }\n envPointers.push_back(0);\n\n \/\/ Align stack\n memState->setStackMin(memState->getStackMin() & -sizeof(Addr));\n\n \/\/ Calculate bottom of stack\n memState->setStackMin(memState->getStackMin() -\n ((1 + argv.size()) * sizeof(Addr) +\n (1 + envp.size()) * sizeof(Addr) +\n sizeof(Addr) + 2 * sizeof(IntType) * auxv.size()));\n memState->setStackMin(memState->getStackMin() & -2*sizeof(Addr));\n Addr sp = memState->getStackMin();\n const auto pushOntoStack =\n [this, &sp](const uint8_t* data, const size_t size) {\n initVirtMem.writeBlob(sp, data, size);\n sp += size;\n };\n\n \/\/ Push argc and argv pointers onto stack\n IntType argc = htog((IntType)argv.size());\n DPRINTF(Stack, \"Wrote argc %d to address %p\\n\",\n argv.size(), (void*)sp);\n pushOntoStack((uint8_t*)&argc, sizeof(IntType));\n for (const Addr& argPointer: argPointers) {\n DPRINTF(Stack, \"Wrote argv pointer %p to address %p\\n\",\n (void*)argPointer, (void*)sp);\n pushOntoStack((uint8_t*)&argPointer, sizeof(Addr));\n }\n\n \/\/ Push env pointers onto stack\n for (const Addr& envPointer: envPointers) {\n DPRINTF(Stack, \"Wrote envp pointer %p to address %p\\n\",\n (void*)envPointer, (void*)sp);\n pushOntoStack((uint8_t*)&envPointer, sizeof(Addr));\n }\n\n \/\/ Push aux vector onto stack\n std::map<IntType, string> aux_keys = {\n {M5_AT_ENTRY, \"M5_AT_ENTRY\"},\n {M5_AT_PHNUM, \"M5_AT_PHNUM\"},\n {M5_AT_PHENT, \"M5_AT_PHENT\"},\n {M5_AT_PHDR, \"M5_AT_PHDR\"},\n {M5_AT_PAGESZ, \"M5_AT_PAGESZ\"},\n {M5_AT_SECURE, \"M5_AT_SECURE\"},\n {M5_AT_RANDOM, \"M5_AT_RANDOM\"},\n {M5_AT_NULL, \"M5_AT_NULL\"}\n };\n for (const AuxVector<IntType>& aux: auxv) {\n DPRINTF(Stack, \"Wrote aux key %s to address %p\\n\",\n aux_keys[aux.a_type], (void*)sp);\n pushOntoStack((uint8_t*)&aux.a_type, sizeof(IntType));\n DPRINTF(Stack, \"Wrote aux value %x to address %p\\n\",\n aux.a_val, (void*)sp);\n pushOntoStack((uint8_t*)&aux.a_val, sizeof(IntType));\n }\n\n ThreadContext *tc = system->getThreadContext(contextIds[0]);\n tc->setIntReg(StackPointerReg, memState->getStackMin());\n tc->pcState(getStartPC());\n\n memState->setStackMin(roundDown(memState->getStackMin(), pageSize));\n}\n\nRiscvISA::IntReg\nRiscvProcess::getSyscallArg(ThreadContext *tc, int &i)\n{\n \/\/ RISC-V only has four system call argument registers by convention, so\n \/\/ if a larger index is requested return 0\n RiscvISA::IntReg retval = 0;\n if (i < 4)\n retval = tc->readIntReg(SyscallArgumentRegs[i]);\n i++;\n return retval;\n}\n\nvoid\nRiscvProcess::setSyscallArg(ThreadContext *tc, int i, RiscvISA::IntReg val)\n{\n tc->setIntReg(SyscallArgumentRegs[i], val);\n}\n\nvoid\nRiscvProcess::setSyscallReturn(ThreadContext *tc, SyscallReturn sysret)\n{\n if (sysret.successful()) {\n \/\/ no error\n tc->setIntReg(SyscallPseudoReturnReg, sysret.returnValue());\n } else {\n \/\/ got an error, return details\n tc->setIntReg(SyscallPseudoReturnReg, sysret.errnoValue());\n }\n}\n<commit_msg>arch-riscv: Define AT_RANDOM properly<commit_after>\/*\n * Copyright (c) 2004-2005 The Regents of The University of Michigan\n * Copyright (c) 2016 The University of Virginia\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met: redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer;\n * redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution;\n * neither the name of the copyright holders nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n * Authors: Gabe Black\n * Ali Saidi\n * Korey Sewell\n * Alec Roelke\n *\/\n#include \"arch\/riscv\/process.hh\"\n\n#include <algorithm>\n#include <cstddef>\n#include <iostream>\n#include <iterator>\n#include <map>\n#include <string>\n#include <vector>\n\n#include \"arch\/riscv\/isa_traits.hh\"\n#include \"base\/loader\/elf_object.hh\"\n#include \"base\/loader\/object_file.hh\"\n#include \"base\/logging.hh\"\n#include \"base\/random.hh\"\n#include \"cpu\/thread_context.hh\"\n#include \"debug\/Stack.hh\"\n#include \"mem\/page_table.hh\"\n#include \"params\/Process.hh\"\n#include \"sim\/aux_vector.hh\"\n#include \"sim\/process.hh\"\n#include \"sim\/process_impl.hh\"\n#include \"sim\/syscall_return.hh\"\n#include \"sim\/system.hh\"\n\nusing namespace std;\nusing namespace RiscvISA;\n\nRiscvProcess::RiscvProcess(ProcessParams * params,\n ObjectFile *objFile) : Process(params, objFile)\n{\n const Addr stack_base = 0x7FFFFFFFFFFFFFFFL;\n const Addr max_stack_size = 8 * 1024 * 1024;\n const Addr next_thread_stack_base = stack_base - max_stack_size;\n const Addr brk_point = roundUp(objFile->bssBase() + objFile->bssSize(),\n PageBytes);\n const Addr mmap_end = 0x4000000000000000L;\n memState = make_shared<MemState>(brk_point, stack_base, max_stack_size,\n next_thread_stack_base, mmap_end);\n}\n\nvoid\nRiscvProcess::initState()\n{\n Process::initState();\n\n argsInit<uint64_t>(PageBytes);\n}\n\ntemplate<class IntType> void\nRiscvProcess::argsInit(int pageSize)\n{\n const int RandomBytes = 16;\n\n updateBias();\n objFile->loadSections(initVirtMem);\n ElfObject* elfObject = dynamic_cast<ElfObject*>(objFile);\n memState->setStackMin(memState->getStackBase());\n\n \/\/ Determine stack size and populate auxv\n Addr stack_top = memState->getStackMin();\n stack_top -= RandomBytes;\n for (const string& arg: argv)\n stack_top -= arg.size() + 1;\n for (const string& env: envp)\n stack_top -= env.size() + 1;\n stack_top &= -sizeof(Addr);\n\n vector<AuxVector<IntType>> auxv;\n if (elfObject != nullptr) {\n auxv.push_back({M5_AT_ENTRY, objFile->entryPoint()});\n auxv.push_back({M5_AT_PHNUM, elfObject->programHeaderCount()});\n auxv.push_back({M5_AT_PHENT, elfObject->programHeaderSize()});\n auxv.push_back({M5_AT_PHDR, elfObject->programHeaderTable()});\n auxv.push_back({M5_AT_PAGESZ, PageBytes});\n auxv.push_back({M5_AT_SECURE, 0});\n auxv.push_back({M5_AT_RANDOM, stack_top});\n auxv.push_back({M5_AT_NULL, 0});\n }\n stack_top -= (1 + argv.size()) * sizeof(Addr) +\n (1 + envp.size()) * sizeof(Addr) +\n sizeof(Addr) + 2 * sizeof(IntType) * auxv.size();\n stack_top &= -2*sizeof(Addr);\n memState->setStackSize(memState->getStackBase() - stack_top);\n allocateMem(roundDown(stack_top, pageSize),\n roundUp(memState->getStackSize(), pageSize));\n\n \/\/ Copy random bytes (for AT_RANDOM) to stack\n memState->setStackMin(memState->getStackMin() - RandomBytes);\n uint8_t at_random[RandomBytes];\n generate(begin(at_random), end(at_random),\n [&]{ return random_mt.random(0, 0xFF); });\n initVirtMem.writeBlob(memState->getStackMin(), at_random, RandomBytes);\n\n \/\/ Copy argv to stack\n vector<Addr> argPointers;\n for (const string& arg: argv) {\n memState->setStackMin(memState->getStackMin() - (arg.size() + 1));\n initVirtMem.writeString(memState->getStackMin(), arg.c_str());\n argPointers.push_back(memState->getStackMin());\n if (DTRACE(Stack)) {\n string wrote;\n initVirtMem.readString(wrote, argPointers.back());\n DPRINTFN(\"Wrote arg \\\"%s\\\" to address %p\\n\",\n wrote, (void*)memState->getStackMin());\n }\n }\n argPointers.push_back(0);\n\n \/\/ Copy envp to stack\n vector<Addr> envPointers;\n for (const string& env: envp) {\n memState->setStackMin(memState->getStackMin() - (env.size() + 1));\n initVirtMem.writeString(memState->getStackMin(), env.c_str());\n envPointers.push_back(memState->getStackMin());\n DPRINTF(Stack, \"Wrote env \\\"%s\\\" to address %p\\n\",\n env, (void*)memState->getStackMin());\n }\n envPointers.push_back(0);\n\n \/\/ Align stack\n memState->setStackMin(memState->getStackMin() & -sizeof(Addr));\n\n \/\/ Calculate bottom of stack\n memState->setStackMin(memState->getStackMin() -\n ((1 + argv.size()) * sizeof(Addr) +\n (1 + envp.size()) * sizeof(Addr) +\n sizeof(Addr) + 2 * sizeof(IntType) * auxv.size()));\n memState->setStackMin(memState->getStackMin() & -2*sizeof(Addr));\n Addr sp = memState->getStackMin();\n const auto pushOntoStack =\n [this, &sp](const uint8_t* data, const size_t size) {\n initVirtMem.writeBlob(sp, data, size);\n sp += size;\n };\n\n \/\/ Push argc and argv pointers onto stack\n IntType argc = htog((IntType)argv.size());\n DPRINTF(Stack, \"Wrote argc %d to address %p\\n\",\n argv.size(), (void*)sp);\n pushOntoStack((uint8_t*)&argc, sizeof(IntType));\n for (const Addr& argPointer: argPointers) {\n DPRINTF(Stack, \"Wrote argv pointer %p to address %p\\n\",\n (void*)argPointer, (void*)sp);\n pushOntoStack((uint8_t*)&argPointer, sizeof(Addr));\n }\n\n \/\/ Push env pointers onto stack\n for (const Addr& envPointer: envPointers) {\n DPRINTF(Stack, \"Wrote envp pointer %p to address %p\\n\",\n (void*)envPointer, (void*)sp);\n pushOntoStack((uint8_t*)&envPointer, sizeof(Addr));\n }\n\n \/\/ Push aux vector onto stack\n std::map<IntType, string> aux_keys = {\n {M5_AT_ENTRY, \"M5_AT_ENTRY\"},\n {M5_AT_PHNUM, \"M5_AT_PHNUM\"},\n {M5_AT_PHENT, \"M5_AT_PHENT\"},\n {M5_AT_PHDR, \"M5_AT_PHDR\"},\n {M5_AT_PAGESZ, \"M5_AT_PAGESZ\"},\n {M5_AT_SECURE, \"M5_AT_SECURE\"},\n {M5_AT_RANDOM, \"M5_AT_RANDOM\"},\n {M5_AT_NULL, \"M5_AT_NULL\"}\n };\n for (const AuxVector<IntType>& aux: auxv) {\n DPRINTF(Stack, \"Wrote aux key %s to address %p\\n\",\n aux_keys[aux.a_type], (void*)sp);\n pushOntoStack((uint8_t*)&aux.a_type, sizeof(IntType));\n DPRINTF(Stack, \"Wrote aux value %x to address %p\\n\",\n aux.a_val, (void*)sp);\n pushOntoStack((uint8_t*)&aux.a_val, sizeof(IntType));\n }\n\n ThreadContext *tc = system->getThreadContext(contextIds[0]);\n tc->setIntReg(StackPointerReg, memState->getStackMin());\n tc->pcState(getStartPC());\n\n memState->setStackMin(roundDown(memState->getStackMin(), pageSize));\n}\n\nRiscvISA::IntReg\nRiscvProcess::getSyscallArg(ThreadContext *tc, int &i)\n{\n \/\/ RISC-V only has four system call argument registers by convention, so\n \/\/ if a larger index is requested return 0\n RiscvISA::IntReg retval = 0;\n if (i < 4)\n retval = tc->readIntReg(SyscallArgumentRegs[i]);\n i++;\n return retval;\n}\n\nvoid\nRiscvProcess::setSyscallArg(ThreadContext *tc, int i, RiscvISA::IntReg val)\n{\n tc->setIntReg(SyscallArgumentRegs[i], val);\n}\n\nvoid\nRiscvProcess::setSyscallReturn(ThreadContext *tc, SyscallReturn sysret)\n{\n if (sysret.successful()) {\n \/\/ no error\n tc->setIntReg(SyscallPseudoReturnReg, sysret.returnValue());\n } else {\n \/\/ got an error, return details\n tc->setIntReg(SyscallPseudoReturnReg, sysret.errnoValue());\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\r\n * Copyright 2010-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved.\r\n * \r\n * Licensed under the Apache License, Version 2.0 (the \"License\").\r\n * You may not use this file except in compliance with the License.\r\n * A copy of the License is located at\r\n * \r\n * http:\/\/aws.amazon.com\/apache2.0\r\n * \r\n * or in the \"license\" file accompanying this file. This file is distributed\r\n * on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\r\n * express or implied. See the License for the specific language governing\r\n * permissions and limitations under the License.\r\n *\/\r\n\r\n\r\n#include <aws\/core\/utils\/StringUtils.h>\r\n\r\n#include <aws\/core\/utils\/memory\/stl\/AWSStringStream.h>\r\n#include <algorithm>\r\n#include <iomanip>\r\n#include <cstdlib>\r\n#include <cstring>\r\n#include <functional>\r\n\r\nusing namespace Aws::Utils;\r\n\r\nvoid StringUtils::Replace(Aws::String &s, const char* search, const char* replace)\r\n{\r\n if(!search || !replace)\r\n {\r\n return;\r\n }\r\n\r\n size_t replaceLength = strlen(replace);\r\n size_t searchLength = strlen(search);\r\n\r\n for (std::size_t pos = 0;; pos += replaceLength)\r\n {\r\n pos = s.find(search, pos);\r\n if (pos == Aws::String::npos)\r\n break;\r\n\r\n s.erase(pos, searchLength);\r\n s.insert(pos, replace);\r\n }\r\n}\r\n\r\n\r\nAws::String StringUtils::ToLower(const char* source)\r\n{\r\n Aws::String copy;\r\n size_t sourceLength = strlen(source);\r\n copy.resize(sourceLength);\r\n std::transform(source, source + sourceLength, copy.begin(), ::tolower);\r\n\r\n return std::move(copy);\r\n}\r\n\r\n\r\nAws::String StringUtils::ToUpper(const char* source)\r\n{\r\n Aws::String copy;\r\n size_t sourceLength = strlen(source);\r\n copy.resize(sourceLength);\r\n std::transform(source, source + sourceLength, copy.begin(), ::toupper);\r\n\r\n return std::move(copy);\r\n}\r\n\r\n\r\nbool StringUtils::CaselessCompare(const char* value1, const char* value2)\r\n{\r\n Aws::String value1Lower = ToLower(value1);\r\n Aws::String value2Lower = ToLower(value2);\r\n\r\n return value1Lower == value2Lower;\r\n}\r\n\r\n\r\nAws::Vector<Aws::String> StringUtils::Split(const Aws::String& toSplit, char splitOn)\r\n{\r\n Aws::StringStream input(toSplit);\r\n Aws::Vector<Aws::String> returnValues;\r\n Aws::String item;\r\n\r\n while(std::getline(input, item, splitOn))\r\n {\r\n if(item.size() > 0)\r\n {\r\n returnValues.push_back(item);\r\n }\r\n }\r\n\r\n return std::move(returnValues);\r\n}\r\n\r\n\r\nAws::Vector<Aws::String> StringUtils::SplitOnLine(const Aws::String& toSplit)\r\n{\r\n Aws::StringStream input(toSplit);\r\n Aws::Vector<Aws::String> returnValues;\r\n Aws::String item;\r\n\r\n while (std::getline(input, item))\r\n {\r\n if (item.size() > 0)\r\n {\r\n returnValues.push_back(item);\r\n }\r\n }\r\n\r\n return std::move(returnValues);\r\n}\r\n\r\n\r\nAws::String StringUtils::URLEncode(const char* unsafe)\r\n{\r\n Aws::StringStream escaped;\r\n escaped.fill('0');\r\n escaped << std::hex << std::uppercase;\r\n\r\n size_t unsafeLength = strlen(unsafe);\r\n for (auto i = unsafe, n = unsafe + unsafeLength; i != n; ++i)\r\n {\r\n char c = *i;\r\n if (isalnum(c) || c == '-' || c == '_' || c == '.' || c == '~')\r\n {\r\n escaped << c;\r\n }\r\n else\r\n {\r\n escaped << '%' << std::setw(2) << ((int) c) << std::setw(0);\r\n }\r\n }\r\n\r\n return escaped.str();\r\n}\r\n\r\nAws::String StringUtils::URLEncode(double unsafe)\r\n{\r\n char buffer[32];\r\n snprintf(buffer, sizeof(buffer), \"%g\", unsafe);\r\n return URLEncode(buffer);\r\n\r\n}\r\n\r\n\r\nAws::String StringUtils::URLDecode(const char* safe)\r\n{\r\n Aws::StringStream unescaped;\r\n unescaped.fill('0');\r\n unescaped << std::hex;\r\n\r\n size_t safeLength = strlen(safe);\r\n for (auto i = safe, n = safe + safeLength; i != n; ++i)\r\n {\r\n char c = *i;\r\n if(c == '%')\r\n {\r\n char hex[3];\r\n hex[0] = *(i + 1);\r\n hex[1] = *(i + 2);\r\n hex[2] = 0;\r\n i += 2;\r\n int hexAsInteger = strtol(hex, nullptr, 16);\r\n unescaped << (char)hexAsInteger;\r\n }\r\n else\r\n {\r\n unescaped << *i;\r\n }\r\n }\r\n\r\n return unescaped.str();\r\n}\r\n\r\nAws::String StringUtils::LTrim(const char* source)\r\n{\r\n Aws::String copy(source);\r\n copy.erase(copy.begin(), std::find_if(copy.begin(), copy.end(), std::not1(std::ptr_fun<int, int>(::isspace))));\r\n return std::move(copy);\r\n}\r\n\r\n\/\/ trim from end\r\nAws::String StringUtils::RTrim(const char* source)\r\n{\r\n Aws::String copy(source);\r\n copy.erase(std::find_if(copy.rbegin(), copy.rend(), std::not1(std::ptr_fun<int, int>(::isspace))).base(), copy.end());\r\n return std::move(copy);\r\n}\r\n\r\n\/\/ trim from both ends\r\nAws::String StringUtils::Trim(const char* source)\r\n{\r\n return LTrim(RTrim(source).c_str());\r\n}\r\n\r\nlong long StringUtils::ConvertToInt64(const char* source)\r\n{\r\n if(!source)\r\n {\r\n return 0;\r\n }\r\n\r\n#ifdef __ANDROID__\r\n return atoll(source);\r\n#else\r\n return std::atoll(source);\r\n#endif \/\/ __ANDROID__\r\n}\r\n\r\n\r\nlong StringUtils::ConvertToInt32(const char* source)\r\n{\r\n if (!source)\r\n {\r\n return 0;\r\n }\r\n\r\n return std::atol(source);\r\n}\r\n\r\n\r\nbool StringUtils::ConvertToBool(const char* source)\r\n{\r\n if(!source)\r\n {\r\n return false;\r\n }\r\n\r\n Aws::String strValue = ToLower(source);\r\n if(strValue == \"true\" || strValue == \"1\")\r\n {\r\n return true;\r\n }\r\n\r\n return false;\r\n}\r\n\r\n\r\ndouble StringUtils::ConvertToDouble(const char* source)\r\n{\r\n if(!source)\r\n {\r\n return 0.0;\r\n }\r\n\r\n return std::strtod(source, NULL);\r\n}\r\n\r\n#ifdef _WIN32\r\n\r\nAws::WString StringUtils::ToWString(const char* source)\r\n{\r\n Aws::WString outString;\r\n\r\n outString.resize(std::strlen(source));\r\n std::copy(source, source + std::strlen(source), outString.begin());\r\n return outString;\r\n}\r\n\r\nAws::String StringUtils::FromWString(const wchar_t* source)\r\n{\r\n Aws::WString inWString(source);\r\n\r\n Aws::String outString(inWString.begin(), inWString.end());\r\n return outString;\r\n}\r\n\r\n#endif\r\n\r\n\r\n<commit_msg>Forgot about windows not having a fully functioning c99 implementation.<commit_after>\/*\r\n * Copyright 2010-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved.\r\n * \r\n * Licensed under the Apache License, Version 2.0 (the \"License\").\r\n * You may not use this file except in compliance with the License.\r\n * A copy of the License is located at\r\n * \r\n * http:\/\/aws.amazon.com\/apache2.0\r\n * \r\n * or in the \"license\" file accompanying this file. This file is distributed\r\n * on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\r\n * express or implied. See the License for the specific language governing\r\n * permissions and limitations under the License.\r\n *\/\r\n\r\n\r\n#include <aws\/core\/utils\/StringUtils.h>\r\n\r\n#include <aws\/core\/utils\/memory\/stl\/AWSStringStream.h>\r\n#include <algorithm>\r\n#include <iomanip>\r\n#include <cstdlib>\r\n#include <cstring>\r\n#include <functional>\r\n\r\nusing namespace Aws::Utils;\r\n\r\nvoid StringUtils::Replace(Aws::String &s, const char* search, const char* replace)\r\n{\r\n if(!search || !replace)\r\n {\r\n return;\r\n }\r\n\r\n size_t replaceLength = strlen(replace);\r\n size_t searchLength = strlen(search);\r\n\r\n for (std::size_t pos = 0;; pos += replaceLength)\r\n {\r\n pos = s.find(search, pos);\r\n if (pos == Aws::String::npos)\r\n break;\r\n\r\n s.erase(pos, searchLength);\r\n s.insert(pos, replace);\r\n }\r\n}\r\n\r\n\r\nAws::String StringUtils::ToLower(const char* source)\r\n{\r\n Aws::String copy;\r\n size_t sourceLength = strlen(source);\r\n copy.resize(sourceLength);\r\n std::transform(source, source + sourceLength, copy.begin(), ::tolower);\r\n\r\n return std::move(copy);\r\n}\r\n\r\n\r\nAws::String StringUtils::ToUpper(const char* source)\r\n{\r\n Aws::String copy;\r\n size_t sourceLength = strlen(source);\r\n copy.resize(sourceLength);\r\n std::transform(source, source + sourceLength, copy.begin(), ::toupper);\r\n\r\n return std::move(copy);\r\n}\r\n\r\n\r\nbool StringUtils::CaselessCompare(const char* value1, const char* value2)\r\n{\r\n Aws::String value1Lower = ToLower(value1);\r\n Aws::String value2Lower = ToLower(value2);\r\n\r\n return value1Lower == value2Lower;\r\n}\r\n\r\n\r\nAws::Vector<Aws::String> StringUtils::Split(const Aws::String& toSplit, char splitOn)\r\n{\r\n Aws::StringStream input(toSplit);\r\n Aws::Vector<Aws::String> returnValues;\r\n Aws::String item;\r\n\r\n while(std::getline(input, item, splitOn))\r\n {\r\n if(item.size() > 0)\r\n {\r\n returnValues.push_back(item);\r\n }\r\n }\r\n\r\n return std::move(returnValues);\r\n}\r\n\r\n\r\nAws::Vector<Aws::String> StringUtils::SplitOnLine(const Aws::String& toSplit)\r\n{\r\n Aws::StringStream input(toSplit);\r\n Aws::Vector<Aws::String> returnValues;\r\n Aws::String item;\r\n\r\n while (std::getline(input, item))\r\n {\r\n if (item.size() > 0)\r\n {\r\n returnValues.push_back(item);\r\n }\r\n }\r\n\r\n return std::move(returnValues);\r\n}\r\n\r\n\r\nAws::String StringUtils::URLEncode(const char* unsafe)\r\n{\r\n Aws::StringStream escaped;\r\n escaped.fill('0');\r\n escaped << std::hex << std::uppercase;\r\n\r\n size_t unsafeLength = strlen(unsafe);\r\n for (auto i = unsafe, n = unsafe + unsafeLength; i != n; ++i)\r\n {\r\n char c = *i;\r\n if (isalnum(c) || c == '-' || c == '_' || c == '.' || c == '~')\r\n {\r\n escaped << c;\r\n }\r\n else\r\n {\r\n escaped << '%' << std::setw(2) << ((int) c) << std::setw(0);\r\n }\r\n }\r\n\r\n return escaped.str();\r\n}\r\n\r\nAws::String StringUtils::URLEncode(double unsafe)\r\n{\r\n char buffer[32];\r\n#if defined(_MSC_VER) && _MSC_VER < 1900\r\n _vsnprintf_s(buffer, sizeof(buffer), _TRUNCATE, \"%g\", unsafe);\r\n#else\r\n snprintf(buffer, sizeof(buffer), \"%g\", unsafe);\r\n return URLEncode(buffer);\r\n#endif\r\n\r\n}\r\n\r\n\r\nAws::String StringUtils::URLDecode(const char* safe)\r\n{\r\n Aws::StringStream unescaped;\r\n unescaped.fill('0');\r\n unescaped << std::hex;\r\n\r\n size_t safeLength = strlen(safe);\r\n for (auto i = safe, n = safe + safeLength; i != n; ++i)\r\n {\r\n char c = *i;\r\n if(c == '%')\r\n {\r\n char hex[3];\r\n hex[0] = *(i + 1);\r\n hex[1] = *(i + 2);\r\n hex[2] = 0;\r\n i += 2;\r\n int hexAsInteger = strtol(hex, nullptr, 16);\r\n unescaped << (char)hexAsInteger;\r\n }\r\n else\r\n {\r\n unescaped << *i;\r\n }\r\n }\r\n\r\n return unescaped.str();\r\n}\r\n\r\nAws::String StringUtils::LTrim(const char* source)\r\n{\r\n Aws::String copy(source);\r\n copy.erase(copy.begin(), std::find_if(copy.begin(), copy.end(), std::not1(std::ptr_fun<int, int>(::isspace))));\r\n return std::move(copy);\r\n}\r\n\r\n\/\/ trim from end\r\nAws::String StringUtils::RTrim(const char* source)\r\n{\r\n Aws::String copy(source);\r\n copy.erase(std::find_if(copy.rbegin(), copy.rend(), std::not1(std::ptr_fun<int, int>(::isspace))).base(), copy.end());\r\n return std::move(copy);\r\n}\r\n\r\n\/\/ trim from both ends\r\nAws::String StringUtils::Trim(const char* source)\r\n{\r\n return LTrim(RTrim(source).c_str());\r\n}\r\n\r\nlong long StringUtils::ConvertToInt64(const char* source)\r\n{\r\n if(!source)\r\n {\r\n return 0;\r\n }\r\n\r\n#ifdef __ANDROID__\r\n return atoll(source);\r\n#else\r\n return std::atoll(source);\r\n#endif \/\/ __ANDROID__\r\n}\r\n\r\n\r\nlong StringUtils::ConvertToInt32(const char* source)\r\n{\r\n if (!source)\r\n {\r\n return 0;\r\n }\r\n\r\n return std::atol(source);\r\n}\r\n\r\n\r\nbool StringUtils::ConvertToBool(const char* source)\r\n{\r\n if(!source)\r\n {\r\n return false;\r\n }\r\n\r\n Aws::String strValue = ToLower(source);\r\n if(strValue == \"true\" || strValue == \"1\")\r\n {\r\n return true;\r\n }\r\n\r\n return false;\r\n}\r\n\r\n\r\ndouble StringUtils::ConvertToDouble(const char* source)\r\n{\r\n if(!source)\r\n {\r\n return 0.0;\r\n }\r\n\r\n return std::strtod(source, NULL);\r\n}\r\n\r\n#ifdef _WIN32\r\n\r\nAws::WString StringUtils::ToWString(const char* source)\r\n{\r\n Aws::WString outString;\r\n\r\n outString.resize(std::strlen(source));\r\n std::copy(source, source + std::strlen(source), outString.begin());\r\n return outString;\r\n}\r\n\r\nAws::String StringUtils::FromWString(const wchar_t* source)\r\n{\r\n Aws::WString inWString(source);\r\n\r\n Aws::String outString(inWString.begin(), inWString.end());\r\n return outString;\r\n}\r\n\r\n#endif\r\n\r\n\r\n<|endoftext|>"} {"text":"<commit_before>\/*\n * SchemeSmobAV.c\n *\n * Scheme small objects (SMOBS) for attention values.\n *\n * Copyright (c) 2008,2009 Linas Vepstas <linas@linas.org>\n *\/\n\n#ifdef HAVE_GUILE\n\n#include <libguile.h>\n\n#include <opencog\/atomspace\/AttentionValue.h>\n#include <opencog\/guile\/SchemeSmob.h>\n\nusing namespace opencog;\n\n\/* ============================================================== *\/\n\/**\n * Search for an attention value in a list of values.\n * Return the attention value if found, else return null.\n * Throw errors if the list is not stictly just key-value pairs\n *\/\nAttentionValue * SchemeSmob::get_av_from_list(SCM slist)\n{\n\twhile (scm_is_pair(slist))\n\t{\n\t\tSCM sval = SCM_CAR(slist);\n\t\tif (SCM_SMOB_PREDICATE(SchemeSmob::cog_misc_tag, sval))\n\t\t{\n\t\t\tscm_t_bits misctype = SCM_SMOB_FLAGS(sval);\n\t\t\tswitch (misctype)\n\t\t\t{\n\t\t\t\tcase COG_AV:\n\t\t\t\t\treturn (AttentionValue *) SCM_SMOB_DATA(sval);\n\t\t\t\tdefault:\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\tslist = SCM_CDR(slist);\n\t}\n\n\treturn NULL;\n}\n\n\/* ============================================================== *\/\n\nstd::string SchemeSmob::av_to_string(const AttentionValue *av)\n{\n#define BUFLEN 120\n\tchar buff[BUFLEN];\n\n\tsnprintf(buff, BUFLEN, \"(av %d %d %u)\",\n\t av->getSTI(), av->getLTI(), av->getVLTI());\n\n\tstd::string ret = buff;\n\treturn ret;\n}\n\n\/* ============================================================== *\/\n\/**\n * Take over memory management of an attention value\n *\/\nSCM SchemeSmob::take_av (AttentionValue *av)\n{\n\tscm_gc_register_collectable_memory (av,\n\t sizeof(*av), \"opencog av\");\n\n\tSCM smob;\n\tSCM_NEWSMOB (smob, cog_misc_tag, av);\n\tSCM_SET_SMOB_FLAGS(smob, COG_AV);\n\treturn smob;\n}\n\n\/* ============================================================== *\/\n\/**\n * Create a new attention value, with indicated sti\/lti\/vlti\n *\/\nSCM SchemeSmob::ss_new_av (SCM ssti, SCM slti, SCM svlti)\n{\n\tif (!scm_is_integer(ssti)) {\n\t\tscm_wrong_type_arg_msg(\"cog-new-av\", 1, svlti, \"unsigned short\");\n\t}\n\tif (!scm_is_integer(slti)) {\n\t\tscm_wrong_type_arg_msg(\"cog-new-av\", 2, svlti, \"unsigned short\");\n\t}\n\tif (!scm_is_integer(svlti)) {\n\t\tscm_wrong_type_arg_msg(\"cog-new-av\", 3, svlti, \"unsigned short\");\n\t}\n\tAttentionValue::sti_t sti = scm_to_short(ssti);\n\tAttentionValue::lti_t lti = scm_to_short(slti);\n AttentionValue::vlti_t vlti = scm_to_ushort(svlti);\n\tAttentionValue *av = new AttentionValue(sti, lti, vlti);\n\treturn take_av(av);\n}\n\n\/* ============================================================== *\/\n\/**\n * Return true if the scm is an attention value\n *\/\nSCM SchemeSmob::ss_av_p (SCM s)\n{\n\tif (SCM_SMOB_PREDICATE(SchemeSmob::cog_misc_tag, s))\n\t{\n\t\tscm_t_bits misctype = SCM_SMOB_FLAGS(s);\n\t\tswitch (misctype)\n\t\t{\n\t\t\tcase COG_AV:\n\t\t\t\treturn SCM_BOOL_T;\n\n\t\t\tdefault:\n\t\t\t\treturn SCM_BOOL_F;\n\t\t}\n\t}\n\treturn SCM_BOOL_F;\n}\n\n\/* ============================================================== *\/\n\nAttentionValue * SchemeSmob::verify_av(SCM sav, const char *subrname, int pos)\n{\n\tif (!SCM_SMOB_PREDICATE(SchemeSmob::cog_misc_tag, sav))\n\t\tscm_wrong_type_arg_msg(subrname, pos, sav, \"opencog attention value\");\n\n\tscm_t_bits misctype = SCM_SMOB_FLAGS(sav);\n\tif (COG_AV != misctype)\n\t\tscm_wrong_type_arg_msg(subrname, pos, sav, \"opencog attention value\");\n\n\tAttentionValue *av = (AttentionValue *) SCM_SMOB_DATA(sav);\n\treturn av;\n}\n\n\/**\n * Return association list holding contents of an attention value\n *\/\nSCM SchemeSmob::ss_av_get_value (SCM s)\n{\n\tAttentionValue *av = verify_av(s, \"cog-av->alist\");\n\n\tSCM sti = scm_from_short(av->getSTI());\n\tSCM lti = scm_from_short(av->getLTI());\n\tSCM vlti = scm_from_ushort(av->getVLTI());\n\n\tSCM ssti = scm_from_locale_symbol(\"sti\");\n\tSCM slti = scm_from_locale_symbol(\"lti\");\n\tSCM svlti = scm_from_locale_symbol(\"vlti\");\n\n\tSCM rc = SCM_EOL;\n\trc = scm_acons(svlti, vlti, rc);\n\trc = scm_acons(slti, lti, rc);\n\trc = scm_acons(ssti, sti, rc);\n\treturn rc;\n}\n\n#endif \/* HAVE_GUILE *\/\n\/* ===================== END OF FILE ============================ *\/\n<commit_msg>Minor trite bugfix in error reporting<commit_after>\/*\n * SchemeSmobAV.c\n *\n * Scheme small objects (SMOBS) for attention values.\n *\n * Copyright (c) 2008,2009 Linas Vepstas <linas@linas.org>\n *\/\n\n#ifdef HAVE_GUILE\n\n#include <libguile.h>\n\n#include <opencog\/atomspace\/AttentionValue.h>\n#include <opencog\/guile\/SchemeSmob.h>\n\nusing namespace opencog;\n\n\/* ============================================================== *\/\n\/**\n * Search for an attention value in a list of values.\n * Return the attention value if found, else return null.\n * Throw errors if the list is not stictly just key-value pairs\n *\/\nAttentionValue * SchemeSmob::get_av_from_list(SCM slist)\n{\n\twhile (scm_is_pair(slist))\n\t{\n\t\tSCM sval = SCM_CAR(slist);\n\t\tif (SCM_SMOB_PREDICATE(SchemeSmob::cog_misc_tag, sval))\n\t\t{\n\t\t\tscm_t_bits misctype = SCM_SMOB_FLAGS(sval);\n\t\t\tswitch (misctype)\n\t\t\t{\n\t\t\t\tcase COG_AV:\n\t\t\t\t\treturn (AttentionValue *) SCM_SMOB_DATA(sval);\n\t\t\t\tdefault:\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\tslist = SCM_CDR(slist);\n\t}\n\n\treturn NULL;\n}\n\n\/* ============================================================== *\/\n\nstd::string SchemeSmob::av_to_string(const AttentionValue *av)\n{\n#define BUFLEN 120\n\tchar buff[BUFLEN];\n\n\tsnprintf(buff, BUFLEN, \"(av %d %d %u)\",\n\t av->getSTI(), av->getLTI(), av->getVLTI());\n\n\treturn buff;\n}\n\n\/* ============================================================== *\/\n\/**\n * Take over memory management of an attention value\n *\/\nSCM SchemeSmob::take_av (AttentionValue *av)\n{\n\tscm_gc_register_collectable_memory (av,\n\t sizeof(*av), \"opencog av\");\n\n\tSCM smob;\n\tSCM_NEWSMOB (smob, cog_misc_tag, av);\n\tSCM_SET_SMOB_FLAGS(smob, COG_AV);\n\treturn smob;\n}\n\n\/* ============================================================== *\/\n\/**\n * Create a new attention value, with indicated sti\/lti\/vlti\n *\/\nSCM SchemeSmob::ss_new_av (SCM ssti, SCM slti, SCM svlti)\n{\n\tif (!scm_is_integer(ssti)) {\n\t\tscm_wrong_type_arg_msg(\"cog-new-av\", 1, ssti, \"signed short\");\n\t}\n\tif (!scm_is_integer(slti)) {\n\t\tscm_wrong_type_arg_msg(\"cog-new-av\", 2, slti, \"signed short\");\n\t}\n\tif (!scm_is_integer(svlti)) {\n\t\tscm_wrong_type_arg_msg(\"cog-new-av\", 3, svlti, \"unsigned short\");\n\t}\n\tAttentionValue::sti_t sti = scm_to_short(ssti);\n\tAttentionValue::lti_t lti = scm_to_short(slti);\n\tAttentionValue::vlti_t vlti = scm_to_ushort(svlti);\n\tAttentionValue *av = new AttentionValue(sti, lti, vlti);\n\treturn take_av(av);\n}\n\n\/* ============================================================== *\/\n\/**\n * Return true if the scm is an attention value\n *\/\nSCM SchemeSmob::ss_av_p (SCM s)\n{\n\tif (SCM_SMOB_PREDICATE(SchemeSmob::cog_misc_tag, s))\n\t{\n\t\tscm_t_bits misctype = SCM_SMOB_FLAGS(s);\n\t\tswitch (misctype)\n\t\t{\n\t\t\tcase COG_AV:\n\t\t\t\treturn SCM_BOOL_T;\n\n\t\t\tdefault:\n\t\t\t\treturn SCM_BOOL_F;\n\t\t}\n\t}\n\treturn SCM_BOOL_F;\n}\n\n\/* ============================================================== *\/\n\nAttentionValue * SchemeSmob::verify_av(SCM sav, const char *subrname, int pos)\n{\n\tif (!SCM_SMOB_PREDICATE(SchemeSmob::cog_misc_tag, sav))\n\t\tscm_wrong_type_arg_msg(subrname, pos, sav, \"opencog attention value\");\n\n\tscm_t_bits misctype = SCM_SMOB_FLAGS(sav);\n\tif (COG_AV != misctype)\n\t\tscm_wrong_type_arg_msg(subrname, pos, sav, \"opencog attention value\");\n\n\tAttentionValue *av = (AttentionValue *) SCM_SMOB_DATA(sav);\n\treturn av;\n}\n\n\/**\n * Return association list holding contents of an attention value\n *\/\nSCM SchemeSmob::ss_av_get_value (SCM s)\n{\n\tAttentionValue *av = verify_av(s, \"cog-av->alist\");\n\n\tSCM sti = scm_from_short(av->getSTI());\n\tSCM lti = scm_from_short(av->getLTI());\n\tSCM vlti = scm_from_ushort(av->getVLTI());\n\n\tSCM ssti = scm_from_locale_symbol(\"sti\");\n\tSCM slti = scm_from_locale_symbol(\"lti\");\n\tSCM svlti = scm_from_locale_symbol(\"vlti\");\n\n\tSCM rc = SCM_EOL;\n\trc = scm_acons(svlti, vlti, rc);\n\trc = scm_acons(slti, lti, rc);\n\trc = scm_acons(ssti, sti, rc);\n\treturn rc;\n}\n\n#endif \/* HAVE_GUILE *\/\n\/* ===================== END OF FILE ============================ *\/\n<|endoftext|>"} {"text":"<commit_before>\/*\n This file is a part of libcds - Concurrent Data Structures library\n\n (C) Copyright Maxim Khizhinsky (libcds.dev@gmail.com) 2006-2016\n\n Source code repo: http:\/\/github.com\/khizmax\/libcds\/\n Download: http:\/\/sourceforge.net\/projects\/libcds\/files\/\n \n Redistribution and use in source and binary forms, with or without\n modification, are permitted provided that the following conditions are met:\n\n * Redistributions of source code must retain the above copyright notice, this\n list of conditions and the following disclaimer.\n\n * Redistributions in binary form must reproduce the above copyright notice,\n this list of conditions and the following disclaimer in the documentation\n and\/or other materials provided with the distribution.\n\n THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*\/\n\n#include \"pqueue_type.h\"\n#include \"item.h\"\n\nnamespace {\n static size_t s_nThreadCount = 8;\n static size_t s_nQueueSize = 2000000;\n\n class pqueue_pop: public cds_test::stress_fixture\n {\n typedef cds_test::stress_fixture base_class;\n\n protected:\n template <class PQueue>\n class Producer: public cds_test::thread\n {\n typedef cds_test::thread base_class;\n\n public:\n Producer( cds_test::thread_pool& pool, PQueue& queue )\n : base_class( pool )\n , m_Queue( queue )\n {}\n\n Producer( Producer& src )\n : base_class( src )\n , m_Queue( src.m_Queue )\n {}\n\n virtual thread * clone()\n {\n return new Producer( *this );\n }\n\n virtual void test()\n {\n typedef typename PQueue::value_type value_type;\n for ( array_type::const_iterator it = m_arr.begin(); it != m_arr.end(); ++it ) {\n if ( !m_Queue.push( value_type( *it ) ))\n ++m_nPushError;\n }\n }\n\n void prepare( size_t nStart, size_t nEnd )\n {\n m_arr.reserve( nEnd - nStart );\n for ( size_t i = nStart; i < nEnd; ++i )\n m_arr.push_back( i );\n shuffle( m_arr.begin(), m_arr.end() );\n }\n\n public:\n PQueue& m_Queue;\n size_t m_nPushError = 0;\n\n typedef std::vector<size_t> array_type;\n array_type m_arr;\n };\n\n template <class PQueue>\n class Consumer: public cds_test::thread\n {\n typedef cds_test::thread base_class;\n\n public:\n Consumer( cds_test::thread_pool& pool, PQueue& queue )\n : base_class( pool )\n , m_Queue( queue )\n {}\n\n Consumer( Consumer& src )\n : base_class( src )\n , m_Queue( src.m_Queue )\n {}\n\n virtual thread * clone()\n {\n return new Consumer( *this );\n }\n\n virtual void test()\n {\n typedef typename PQueue::value_type value_type;\n size_t nPrevKey;\n value_type val;\n if ( m_Queue.pop( val )) {\n ++m_nPopSuccess;\n nPrevKey = val.key;\n\n while ( !m_Queue.empty() ) {\n if ( m_Queue.pop( val )) {\n ++m_nPopSuccess;\n if ( val.key > nPrevKey )\n ++m_nPopError;\n else if ( val.key == nPrevKey )\n ++m_nPopErrorEq;\n nPrevKey = val.key;\n }\n else\n ++m_nPopFailed;\n }\n }\n else\n ++m_nPopFailed;\n }\n\n public:\n PQueue& m_Queue;\n size_t m_nPopError = 0;\n size_t m_nPopErrorEq = 0;\n size_t m_nPopSuccess = 0;\n size_t m_nPopFailed = 0;\n };\n\n protected:\n\n template <class PQueue>\n void test( PQueue& q )\n {\n size_t const nThreadItemCount = s_nQueueSize \/ s_nThreadCount;\n s_nQueueSize = nThreadItemCount * s_nThreadCount;\n\n cds_test::thread_pool& pool = get_pool();\n\n propout() << std::make_pair( \"thread_count\", s_nThreadCount )\n << std::make_pair( \"push_count\", s_nQueueSize );\n\n \/\/ push\n {\n pool.add( new Producer<PQueue>( pool, q ), s_nThreadCount );\n\n size_t nStart = 0;\n for ( size_t i = 0; i < pool.size(); ++i ) {\n static_cast<Producer<PQueue>&>( pool.get(i) ).prepare( nStart, nStart + nThreadItemCount );\n nStart += nThreadItemCount;\n }\n\n std::chrono::milliseconds duration = pool.run();\n propout() << std::make_pair( \"producer_duration\", duration );\n }\n\n \/\/ pop\n {\n pool.clear();\n pool.add( new Consumer<PQueue>( pool, q ), s_nThreadCount );\n\n std::chrono::milliseconds duration = pool.run();\n propout() << std::make_pair( \"consumer_duration\", duration );\n\n \/\/ Analyze result\n size_t nTotalPopped = 0;\n size_t nTotalError = 0;\n size_t nTotalErrorEq = 0;\n size_t nTotalFailed = 0;\n for ( size_t i = 0; i < pool.size(); ++i ) {\n Consumer<PQueue>& cons = static_cast<Consumer<PQueue>&>( pool.get(i));\n\n nTotalPopped += cons.m_nPopSuccess;\n nTotalError += cons.m_nPopError;\n nTotalErrorEq += cons.m_nPopErrorEq;\n nTotalFailed += cons.m_nPopFailed;\n }\n\n propout()\n << std::make_pair( \"total_popped\", nTotalPopped )\n << std::make_pair( \"error_pop_double\", nTotalErrorEq )\n << std::make_pair( \"error_priority_violation\", nTotalError );\n\n EXPECT_EQ( nTotalPopped, s_nQueueSize );\n EXPECT_EQ( nTotalError, 0 );\n EXPECT_EQ( nTotalErrorEq, 0 );\n }\n\n propout() << q.statistics();\n }\n\n public:\n static void SetUpTestCase()\r\n {\r\n cds_test::config const& cfg = get_config( \"pqueue_pop\" );\r\n\r\n s_nThreadCount = cfg.get_size_t( \"ThreadCount\", s_nThreadCount );\n s_nQueueSize = cfg.get_size_t( \"QueueSize\", s_nQueueSize );\n\n if ( s_nThreadCount == 0 )\n s_nThreadCount = 1;\n if ( s_nQueueSize == 0 )\n s_nQueueSize = 1000;\r\n }\n\n \/\/static void TearDownTestCase();\n };\n\n#define CDSSTRESS_MSPriorityQueue( fixture_t, pqueue_t ) \\\n TEST_F( fixture_t, pqueue_t ) \\\n { \\\n typedef pqueue::Types<pqueue::simple_value>::pqueue_t pqueue_type; \\\n pqueue_type pq( s_nQueueSize ); \\\n test( pq ); \\\n }\n CDSSTRESS_MSPriorityQueue( pqueue_pop, MSPriorityQueue_dyn_less )\n CDSSTRESS_MSPriorityQueue( pqueue_pop, MSPriorityQueue_dyn_less_stat )\n CDSSTRESS_MSPriorityQueue( pqueue_pop, MSPriorityQueue_dyn_cmp )\n \/\/CDSSTRESS_MSPriorityQueue( pqueue_pop, MSPriorityQueue_dyn_mutex ) \/\/ too slow\n\n#define CDSSTRESS_MSPriorityQueue_static( fixture_t, pqueue_t ) \\\n TEST_F( fixture_t, pqueue_t ) \\\n { \\\n typedef pqueue::Types<pqueue::simple_value>::pqueue_t pqueue_type; \\\n std::unique_ptr< pqueue_type > pq( new pqueue_type ); \\\n test( *pq.get() ); \\\n }\n \/\/CDSSTRESS_MSPriorityQueue( pqueue_pop, MSPriorityQueue_static_less )\n \/\/CDSSTRESS_MSPriorityQueue( pqueue_pop, MSPriorityQueue_static_less_stat )\n \/\/CDSSTRESS_MSPriorityQueue( pqueue_pop, MSPriorityQueue_static_cmp )\n \/\/CDSSTRESS_MSPriorityQueue( pqueue_pop, 1MSPriorityQueue_static_mutex )\n\n\n#define CDSSTRESS_PriorityQueue( fixture_t, pqueue_t ) \\\n TEST_F( fixture_t, pqueue_t ) \\\n { \\\n typedef pqueue::Types<pqueue::simple_value>::pqueue_t pqueue_type; \\\n pqueue_type pq; \\\n test( pq ); \\\n }\n CDSSTRESS_PriorityQueue( pqueue_pop, FCPQueue_vector )\n CDSSTRESS_PriorityQueue( pqueue_pop, FCPQueue_vector_stat )\n CDSSTRESS_PriorityQueue( pqueue_pop, FCPQueue_deque )\n CDSSTRESS_PriorityQueue( pqueue_pop, FCPQueue_deque_stat )\n CDSSTRESS_PriorityQueue( pqueue_pop, FCPQueue_boost_deque )\n CDSSTRESS_PriorityQueue( pqueue_pop, FCPQueue_boost_deque_stat )\n CDSSTRESS_PriorityQueue( pqueue_pop, FCPQueue_boost_stable_vector )\n CDSSTRESS_PriorityQueue( pqueue_pop, FCPQueue_boost_stable_vector_stat )\n\n CDSSTRESS_PriorityQueue( pqueue_pop, EllenBinTree_HP_max )\n CDSSTRESS_PriorityQueue( pqueue_pop, EllenBinTree_HP_max_stat )\n CDSSTRESS_PriorityQueue( pqueue_pop, EllenBinTree_HP_min )\n CDSSTRESS_PriorityQueue( pqueue_pop, EllenBinTree_HP_min_stat )\n CDSSTRESS_PriorityQueue( pqueue_pop, EllenBinTree_DHP_max )\n CDSSTRESS_PriorityQueue( pqueue_pop, EllenBinTree_DHP_max_stat )\n CDSSTRESS_PriorityQueue( pqueue_pop, EllenBinTree_DHP_min )\n CDSSTRESS_PriorityQueue( pqueue_pop, EllenBinTree_DHP_min_stat )\n \/\/ CDSSTRESS_PriorityQueue( pqueue_pop, EllenBinTree_RCU_gpi_max )\n \/\/ CDSSTRESS_PriorityQueue( pqueue_pop, EllenBinTree_RCU_gpi_max_stat )\n \/\/ CDSSTRESS_PriorityQueue( pqueue_pop, EllenBinTree_RCU_gpi_min )\n \/\/ CDSSTRESS_PriorityQueue( pqueue_pop, EllenBinTree_RCU_gpi_min_stat )\n CDSSTRESS_PriorityQueue( pqueue_pop, EllenBinTree_RCU_gpb_max )\n CDSSTRESS_PriorityQueue( pqueue_pop, EllenBinTree_RCU_gpb_max_stat )\n CDSSTRESS_PriorityQueue( pqueue_pop, EllenBinTree_RCU_gpb_min )\n CDSSTRESS_PriorityQueue( pqueue_pop, EllenBinTree_RCU_gpb_min_stat )\n CDSSTRESS_PriorityQueue( pqueue_pop, EllenBinTree_RCU_gpt_max )\n CDSSTRESS_PriorityQueue( pqueue_pop, EllenBinTree_RCU_gpt_max_stat )\n CDSSTRESS_PriorityQueue( pqueue_pop, EllenBinTree_RCU_gpt_min )\n CDSSTRESS_PriorityQueue( pqueue_pop, EllenBinTree_RCU_gpt_min_stat )\n#ifdef CDS_URCU_SIGNAL_HANDLING_ENABLED\n CDSSTRESS_PriorityQueue( pqueue_pop, EllenBinTree_RCU_shb_max )\n CDSSTRESS_PriorityQueue( pqueue_pop, EllenBinTree_RCU_shb_max_stat )\n CDSSTRESS_PriorityQueue( pqueue_pop, EllenBinTree_RCU_shb_min )\n CDSSTRESS_PriorityQueue( pqueue_pop, EllenBinTree_RCU_shb_min_stat )\n CDSSTRESS_PriorityQueue( pqueue_pop, EllenBinTree_RCU_sht_max )\n CDSSTRESS_PriorityQueue( pqueue_pop, EllenBinTree_RCU_sht_max_stat )\n CDSSTRESS_PriorityQueue( pqueue_pop, EllenBinTree_RCU_sht_min )\n CDSSTRESS_PriorityQueue( pqueue_pop, EllenBinTree_RCU_sht_min_stat )\n#endif\n\n CDSSTRESS_PriorityQueue( pqueue_pop, SkipList_HP_max )\n CDSSTRESS_PriorityQueue( pqueue_pop, SkipList_HP_max_stat )\n CDSSTRESS_PriorityQueue( pqueue_pop, SkipList_HP_min )\n CDSSTRESS_PriorityQueue( pqueue_pop, SkipList_HP_min_stat )\n CDSSTRESS_PriorityQueue( pqueue_pop, SkipList_DHP_max )\n CDSSTRESS_PriorityQueue( pqueue_pop, SkipList_DHP_max_stat )\n CDSSTRESS_PriorityQueue( pqueue_pop, SkipList_DHP_min )\n CDSSTRESS_PriorityQueue( pqueue_pop, SkipList_DHP_min_stat )\n CDSSTRESS_PriorityQueue( pqueue_pop, SkipList_RCU_gpi_max )\n CDSSTRESS_PriorityQueue( pqueue_pop, SkipList_RCU_gpi_min )\n CDSSTRESS_PriorityQueue( pqueue_pop, SkipList_RCU_gpb_max )\n CDSSTRESS_PriorityQueue( pqueue_pop, SkipList_RCU_gpb_min )\n CDSSTRESS_PriorityQueue( pqueue_pop, SkipList_RCU_gpt_max )\n CDSSTRESS_PriorityQueue( pqueue_pop, SkipList_RCU_gpt_min )\n#ifdef CDS_URCU_SIGNAL_HANDLING_ENABLED\n CDSSTRESS_PriorityQueue( pqueue_pop, SkipList_RCU_shb_max )\n CDSSTRESS_PriorityQueue( pqueue_pop, SkipList_RCU_shb_min )\n CDSSTRESS_PriorityQueue( pqueue_pop, SkipList_RCU_sht_max )\n CDSSTRESS_PriorityQueue( pqueue_pop, SkipList_RCU_sht_min )\n#endif\n\n CDSSTRESS_PriorityQueue( pqueue_pop, StdPQueue_vector_spin )\n CDSSTRESS_PriorityQueue( pqueue_pop, StdPQueue_vector_mutex )\n CDSSTRESS_PriorityQueue( pqueue_pop, StdPQueue_deque_spin )\n CDSSTRESS_PriorityQueue( pqueue_pop, StdPQueue_deque_mutex )\n\n} \/\/ namespace\n<commit_msg>Added more error messages<commit_after>\/*\n This file is a part of libcds - Concurrent Data Structures library\n\n (C) Copyright Maxim Khizhinsky (libcds.dev@gmail.com) 2006-2016\n\n Source code repo: http:\/\/github.com\/khizmax\/libcds\/\n Download: http:\/\/sourceforge.net\/projects\/libcds\/files\/\n \n Redistribution and use in source and binary forms, with or without\n modification, are permitted provided that the following conditions are met:\n\n * Redistributions of source code must retain the above copyright notice, this\n list of conditions and the following disclaimer.\n\n * Redistributions in binary form must reproduce the above copyright notice,\n this list of conditions and the following disclaimer in the documentation\n and\/or other materials provided with the distribution.\n\n THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*\/\n\n#include \"pqueue_type.h\"\n#include \"item.h\"\n\nnamespace {\n static size_t s_nThreadCount = 8;\n static size_t s_nQueueSize = 2000000;\n\n class pqueue_pop: public cds_test::stress_fixture\n {\n typedef cds_test::stress_fixture base_class;\n\n protected:\n template <class PQueue>\n class Producer: public cds_test::thread\n {\n typedef cds_test::thread base_class;\n\n public:\n Producer( cds_test::thread_pool& pool, PQueue& queue )\n : base_class( pool )\n , m_Queue( queue )\n {}\n\n Producer( Producer& src )\n : base_class( src )\n , m_Queue( src.m_Queue )\n {}\n\n virtual thread * clone()\n {\n return new Producer( *this );\n }\n\n virtual void test()\n {\n typedef typename PQueue::value_type value_type;\n for ( array_type::const_iterator it = m_arr.begin(); it != m_arr.end(); ++it ) {\n if ( !m_Queue.push( value_type( *it ) ))\n ++m_nPushError;\n }\n }\n\n void prepare( size_t nStart, size_t nEnd )\n {\n m_arr.reserve( nEnd - nStart );\n for ( size_t i = nStart; i < nEnd; ++i )\n m_arr.push_back( i );\n shuffle( m_arr.begin(), m_arr.end() );\n }\n\n public:\n PQueue& m_Queue;\n size_t m_nPushError = 0;\n\n typedef std::vector<size_t> array_type;\n array_type m_arr;\n };\n\n template <class PQueue>\n class Consumer: public cds_test::thread\n {\n typedef cds_test::thread base_class;\n\n public:\n Consumer( cds_test::thread_pool& pool, PQueue& queue )\n : base_class( pool )\n , m_Queue( queue )\n {}\n\n Consumer( Consumer& src )\n : base_class( src )\n , m_Queue( src.m_Queue )\n {}\n\n virtual thread * clone()\n {\n return new Consumer( *this );\n }\n\n virtual void test()\n {\n typedef typename PQueue::value_type value_type;\n size_t nPrevKey;\n value_type val;\n if ( m_Queue.pop( val )) {\n ++m_nPopSuccess;\n nPrevKey = val.key;\n\n while ( !m_Queue.empty() ) {\n if ( m_Queue.pop( val )) {\n ++m_nPopSuccess;\n if ( val.key > nPrevKey ) {\n ++m_nPopError;\n m_arrFailedPops.emplace_back( failed_pops{ nPrevKey, val.key } );\n }\n else if ( val.key == nPrevKey ) {\n ++m_nPopErrorEq;\n m_arrFailedPops.emplace_back( failed_pops{ nPrevKey, val.key } );\n }\n nPrevKey = val.key;\n }\n else\n ++m_nPopFailed;\n }\n }\n else\n ++m_nPopFailed;\n }\n\n public:\n PQueue& m_Queue;\n size_t m_nPopError = 0;\n size_t m_nPopErrorEq = 0;\n size_t m_nPopSuccess = 0;\n size_t m_nPopFailed = 0;\n\n struct failed_pops {\n size_t prev_key;\n size_t popped_key;\n };\n std::vector< failed_pops > m_arrFailedPops;\n };\n\n protected:\n\n template <class PQueue>\n void test( PQueue& q )\n {\n size_t const nThreadItemCount = s_nQueueSize \/ s_nThreadCount;\n s_nQueueSize = nThreadItemCount * s_nThreadCount;\n\n cds_test::thread_pool& pool = get_pool();\n\n propout() << std::make_pair( \"thread_count\", s_nThreadCount )\n << std::make_pair( \"push_count\", s_nQueueSize );\n\n \/\/ push\n {\n pool.add( new Producer<PQueue>( pool, q ), s_nThreadCount );\n\n size_t nStart = 0;\n for ( size_t i = 0; i < pool.size(); ++i ) {\n static_cast<Producer<PQueue>&>( pool.get(i) ).prepare( nStart, nStart + nThreadItemCount );\n nStart += nThreadItemCount;\n }\n\n std::chrono::milliseconds duration = pool.run();\n propout() << std::make_pair( \"producer_duration\", duration );\n }\n\n \/\/ pop\n {\n pool.clear();\n pool.add( new Consumer<PQueue>( pool, q ), s_nThreadCount );\n\n std::chrono::milliseconds duration = pool.run();\n propout() << std::make_pair( \"consumer_duration\", duration );\n\n \/\/ Analyze result\n size_t nTotalPopped = 0;\n size_t nTotalError = 0;\n size_t nTotalErrorEq = 0;\n size_t nTotalFailed = 0;\n for ( size_t i = 0; i < pool.size(); ++i ) {\n Consumer<PQueue>& cons = static_cast<Consumer<PQueue>&>( pool.get(i));\n\n nTotalPopped += cons.m_nPopSuccess;\n nTotalError += cons.m_nPopError;\n nTotalErrorEq += cons.m_nPopErrorEq;\n nTotalFailed += cons.m_nPopFailed;\n\n if ( !cons.m_arrFailedPops.empty() ) {\n std::cerr << \"Failed pop:\";\n for ( size_t k = 0; k < cons.m_arrFailedPops.size(); ++k ) {\n std::cerr << \"\\nThread \" << i << \": prev_key=\" << cons.m_arrFailedPops[k].prev_key << \" popped_key=\" << cons.m_arrFailedPops[k].popped_key;\n }\n std::cerr << std::endl;\n }\n }\n\n propout()\n << std::make_pair( \"total_popped\", nTotalPopped )\n << std::make_pair( \"error_pop_double\", nTotalErrorEq )\n << std::make_pair( \"error_priority_violation\", nTotalError );\n\n EXPECT_EQ( nTotalPopped, s_nQueueSize );\n EXPECT_EQ( nTotalError, 0 );\n EXPECT_EQ( nTotalErrorEq, 0 );\n }\n\n propout() << q.statistics();\n }\n\n public:\n static void SetUpTestCase()\r\n {\r\n cds_test::config const& cfg = get_config( \"pqueue_pop\" );\r\n\r\n s_nThreadCount = cfg.get_size_t( \"ThreadCount\", s_nThreadCount );\n s_nQueueSize = cfg.get_size_t( \"QueueSize\", s_nQueueSize );\n\n if ( s_nThreadCount == 0 )\n s_nThreadCount = 1;\n if ( s_nQueueSize == 0 )\n s_nQueueSize = 1000;\r\n }\n\n \/\/static void TearDownTestCase();\n };\n\n#define CDSSTRESS_MSPriorityQueue( fixture_t, pqueue_t ) \\\n TEST_F( fixture_t, pqueue_t ) \\\n { \\\n typedef pqueue::Types<pqueue::simple_value>::pqueue_t pqueue_type; \\\n pqueue_type pq( s_nQueueSize ); \\\n test( pq ); \\\n }\n CDSSTRESS_MSPriorityQueue( pqueue_pop, MSPriorityQueue_dyn_less )\n CDSSTRESS_MSPriorityQueue( pqueue_pop, MSPriorityQueue_dyn_less_stat )\n CDSSTRESS_MSPriorityQueue( pqueue_pop, MSPriorityQueue_dyn_cmp )\n \/\/CDSSTRESS_MSPriorityQueue( pqueue_pop, MSPriorityQueue_dyn_mutex ) \/\/ too slow\n\n#define CDSSTRESS_MSPriorityQueue_static( fixture_t, pqueue_t ) \\\n TEST_F( fixture_t, pqueue_t ) \\\n { \\\n typedef pqueue::Types<pqueue::simple_value>::pqueue_t pqueue_type; \\\n std::unique_ptr< pqueue_type > pq( new pqueue_type ); \\\n test( *pq.get() ); \\\n }\n \/\/CDSSTRESS_MSPriorityQueue( pqueue_pop, MSPriorityQueue_static_less )\n \/\/CDSSTRESS_MSPriorityQueue( pqueue_pop, MSPriorityQueue_static_less_stat )\n \/\/CDSSTRESS_MSPriorityQueue( pqueue_pop, MSPriorityQueue_static_cmp )\n \/\/CDSSTRESS_MSPriorityQueue( pqueue_pop, 1MSPriorityQueue_static_mutex )\n\n\n#define CDSSTRESS_PriorityQueue( fixture_t, pqueue_t ) \\\n TEST_F( fixture_t, pqueue_t ) \\\n { \\\n typedef pqueue::Types<pqueue::simple_value>::pqueue_t pqueue_type; \\\n pqueue_type pq; \\\n test( pq ); \\\n }\n CDSSTRESS_PriorityQueue( pqueue_pop, FCPQueue_vector )\n CDSSTRESS_PriorityQueue( pqueue_pop, FCPQueue_vector_stat )\n CDSSTRESS_PriorityQueue( pqueue_pop, FCPQueue_deque )\n CDSSTRESS_PriorityQueue( pqueue_pop, FCPQueue_deque_stat )\n CDSSTRESS_PriorityQueue( pqueue_pop, FCPQueue_boost_deque )\n CDSSTRESS_PriorityQueue( pqueue_pop, FCPQueue_boost_deque_stat )\n CDSSTRESS_PriorityQueue( pqueue_pop, FCPQueue_boost_stable_vector )\n CDSSTRESS_PriorityQueue( pqueue_pop, FCPQueue_boost_stable_vector_stat )\n\n CDSSTRESS_PriorityQueue( pqueue_pop, EllenBinTree_HP_max )\n CDSSTRESS_PriorityQueue( pqueue_pop, EllenBinTree_HP_max_stat )\n CDSSTRESS_PriorityQueue( pqueue_pop, EllenBinTree_HP_min )\n CDSSTRESS_PriorityQueue( pqueue_pop, EllenBinTree_HP_min_stat )\n CDSSTRESS_PriorityQueue( pqueue_pop, EllenBinTree_DHP_max )\n CDSSTRESS_PriorityQueue( pqueue_pop, EllenBinTree_DHP_max_stat )\n CDSSTRESS_PriorityQueue( pqueue_pop, EllenBinTree_DHP_min )\n CDSSTRESS_PriorityQueue( pqueue_pop, EllenBinTree_DHP_min_stat )\n \/\/ CDSSTRESS_PriorityQueue( pqueue_pop, EllenBinTree_RCU_gpi_max )\n \/\/ CDSSTRESS_PriorityQueue( pqueue_pop, EllenBinTree_RCU_gpi_max_stat )\n \/\/ CDSSTRESS_PriorityQueue( pqueue_pop, EllenBinTree_RCU_gpi_min )\n \/\/ CDSSTRESS_PriorityQueue( pqueue_pop, EllenBinTree_RCU_gpi_min_stat )\n CDSSTRESS_PriorityQueue( pqueue_pop, EllenBinTree_RCU_gpb_max )\n CDSSTRESS_PriorityQueue( pqueue_pop, EllenBinTree_RCU_gpb_max_stat )\n CDSSTRESS_PriorityQueue( pqueue_pop, EllenBinTree_RCU_gpb_min )\n CDSSTRESS_PriorityQueue( pqueue_pop, EllenBinTree_RCU_gpb_min_stat )\n CDSSTRESS_PriorityQueue( pqueue_pop, EllenBinTree_RCU_gpt_max )\n CDSSTRESS_PriorityQueue( pqueue_pop, EllenBinTree_RCU_gpt_max_stat )\n CDSSTRESS_PriorityQueue( pqueue_pop, EllenBinTree_RCU_gpt_min )\n CDSSTRESS_PriorityQueue( pqueue_pop, EllenBinTree_RCU_gpt_min_stat )\n#ifdef CDS_URCU_SIGNAL_HANDLING_ENABLED\n CDSSTRESS_PriorityQueue( pqueue_pop, EllenBinTree_RCU_shb_max )\n CDSSTRESS_PriorityQueue( pqueue_pop, EllenBinTree_RCU_shb_max_stat )\n CDSSTRESS_PriorityQueue( pqueue_pop, EllenBinTree_RCU_shb_min )\n CDSSTRESS_PriorityQueue( pqueue_pop, EllenBinTree_RCU_shb_min_stat )\n CDSSTRESS_PriorityQueue( pqueue_pop, EllenBinTree_RCU_sht_max )\n CDSSTRESS_PriorityQueue( pqueue_pop, EllenBinTree_RCU_sht_max_stat )\n CDSSTRESS_PriorityQueue( pqueue_pop, EllenBinTree_RCU_sht_min )\n CDSSTRESS_PriorityQueue( pqueue_pop, EllenBinTree_RCU_sht_min_stat )\n#endif\n\n CDSSTRESS_PriorityQueue( pqueue_pop, SkipList_HP_max )\n CDSSTRESS_PriorityQueue( pqueue_pop, SkipList_HP_max_stat )\n CDSSTRESS_PriorityQueue( pqueue_pop, SkipList_HP_min )\n CDSSTRESS_PriorityQueue( pqueue_pop, SkipList_HP_min_stat )\n CDSSTRESS_PriorityQueue( pqueue_pop, SkipList_DHP_max )\n CDSSTRESS_PriorityQueue( pqueue_pop, SkipList_DHP_max_stat )\n CDSSTRESS_PriorityQueue( pqueue_pop, SkipList_DHP_min )\n CDSSTRESS_PriorityQueue( pqueue_pop, SkipList_DHP_min_stat )\n CDSSTRESS_PriorityQueue( pqueue_pop, SkipList_RCU_gpi_max )\n CDSSTRESS_PriorityQueue( pqueue_pop, SkipList_RCU_gpi_min )\n CDSSTRESS_PriorityQueue( pqueue_pop, SkipList_RCU_gpb_max )\n CDSSTRESS_PriorityQueue( pqueue_pop, SkipList_RCU_gpb_min )\n CDSSTRESS_PriorityQueue( pqueue_pop, SkipList_RCU_gpt_max )\n CDSSTRESS_PriorityQueue( pqueue_pop, SkipList_RCU_gpt_min )\n#ifdef CDS_URCU_SIGNAL_HANDLING_ENABLED\n CDSSTRESS_PriorityQueue( pqueue_pop, SkipList_RCU_shb_max )\n CDSSTRESS_PriorityQueue( pqueue_pop, SkipList_RCU_shb_min )\n CDSSTRESS_PriorityQueue( pqueue_pop, SkipList_RCU_sht_max )\n CDSSTRESS_PriorityQueue( pqueue_pop, SkipList_RCU_sht_min )\n#endif\n\n CDSSTRESS_PriorityQueue( pqueue_pop, StdPQueue_vector_spin )\n CDSSTRESS_PriorityQueue( pqueue_pop, StdPQueue_vector_mutex )\n CDSSTRESS_PriorityQueue( pqueue_pop, StdPQueue_deque_spin )\n CDSSTRESS_PriorityQueue( pqueue_pop, StdPQueue_deque_mutex )\n\n} \/\/ namespace\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n\/\/ For 64-bit file access (off_t = off64_t, lseek64, etc).\n#define _FILE_OFFSET_BITS 64\n\n#include \"net\/base\/file_stream.h\"\n\n#include <sys\/types.h>\n#include <sys\/stat.h>\n#include <fcntl.h>\n#include <unistd.h>\n#include <errno.h>\n\n#include \"base\/basictypes.h\"\n#include \"base\/callback.h\"\n#include \"base\/eintr_wrapper.h\"\n#include \"base\/file_path.h\"\n#include \"base\/logging.h\"\n#include \"base\/message_loop.h\"\n#include \"base\/metrics\/histogram.h\"\n#include \"base\/string_util.h\"\n#include \"base\/threading\/thread_restrictions.h\"\n#include \"base\/threading\/worker_pool.h\"\n#include \"base\/synchronization\/waitable_event.h\"\n#include \"net\/base\/net_errors.h\"\n\n\/\/ We cast back and forth, so make sure it's the size we're expecting.\nCOMPILE_ASSERT(sizeof(int64) == sizeof(off_t), off_t_64_bit);\n\n\/\/ Make sure our Whence mappings match the system headers.\nCOMPILE_ASSERT(net::FROM_BEGIN == SEEK_SET &&\n net::FROM_CURRENT == SEEK_CUR &&\n net::FROM_END == SEEK_END, whence_matches_system);\n\nnamespace net {\nnamespace {\n\n\/\/ Map from errno to net error codes.\nint64 MapErrorCode(int err) {\n switch (err) {\n case ENOENT:\n return ERR_FILE_NOT_FOUND;\n case EACCES:\n return ERR_ACCESS_DENIED;\n default:\n LOG(WARNING) << \"Unknown error \" << err << \" mapped to net::ERR_FAILED\";\n return ERR_FAILED;\n }\n}\n\n\/\/ ReadFile() is a simple wrapper around read() that handles EINTR signals and\n\/\/ calls MapErrorCode() to map errno to net error codes.\nint ReadFile(base::PlatformFile file, char* buf, int buf_len) {\n base::ThreadRestrictions::AssertIOAllowed();\n \/\/ read(..., 0) returns 0 to indicate end-of-file.\n\n \/\/ Loop in the case of getting interrupted by a signal.\n ssize_t res = HANDLE_EINTR(read(file, buf, static_cast<size_t>(buf_len)));\n if (res == static_cast<ssize_t>(-1))\n return MapErrorCode(errno);\n return static_cast<int>(res);\n}\n\n\/\/ WriteFile() is a simple wrapper around write() that handles EINTR signals and\n\/\/ calls MapErrorCode() to map errno to net error codes. It tries to write to\n\/\/ completion.\nint WriteFile(base::PlatformFile file, const char* buf, int buf_len) {\n base::ThreadRestrictions::AssertIOAllowed();\n ssize_t res = HANDLE_EINTR(write(file, buf, buf_len));\n if (res == -1)\n return MapErrorCode(errno);\n return res;\n}\n\n\/\/ FlushFile() is a simple wrapper around fsync() that handles EINTR signals and\n\/\/ calls MapErrorCode() to map errno to net error codes. It tries to flush to\n\/\/ completion.\nint FlushFile(base::PlatformFile file) {\n base::ThreadRestrictions::AssertIOAllowed();\n ssize_t res = HANDLE_EINTR(fsync(file));\n if (res == -1)\n return MapErrorCode(errno);\n return res;\n}\n\n\/\/ BackgroundReadTask is a simple task that reads a file and then runs\n\/\/ |callback|. AsyncContext will post this task to the WorkerPool.\nclass BackgroundReadTask : public Task {\n public:\n BackgroundReadTask(base::PlatformFile file, char* buf, int buf_len,\n CompletionCallback* callback);\n ~BackgroundReadTask();\n\n virtual void Run();\n\n private:\n const base::PlatformFile file_;\n char* const buf_;\n const int buf_len_;\n CompletionCallback* const callback_;\n\n DISALLOW_COPY_AND_ASSIGN(BackgroundReadTask);\n};\n\nBackgroundReadTask::BackgroundReadTask(\n base::PlatformFile file, char* buf, int buf_len,\n CompletionCallback* callback)\n : file_(file), buf_(buf), buf_len_(buf_len), callback_(callback) {}\n\nBackgroundReadTask::~BackgroundReadTask() {}\n\nvoid BackgroundReadTask::Run() {\n int result = ReadFile(file_, buf_, buf_len_);\n callback_->Run(result);\n}\n\n\/\/ BackgroundWriteTask is a simple task that writes to a file and then runs\n\/\/ |callback|. AsyncContext will post this task to the WorkerPool.\nclass BackgroundWriteTask : public Task {\n public:\n BackgroundWriteTask(base::PlatformFile file, const char* buf, int buf_len,\n CompletionCallback* callback);\n ~BackgroundWriteTask();\n\n virtual void Run();\n\n private:\n const base::PlatformFile file_;\n const char* const buf_;\n const int buf_len_;\n CompletionCallback* const callback_;\n\n DISALLOW_COPY_AND_ASSIGN(BackgroundWriteTask);\n};\n\nBackgroundWriteTask::BackgroundWriteTask(\n base::PlatformFile file, const char* buf, int buf_len,\n CompletionCallback* callback)\n : file_(file), buf_(buf), buf_len_(buf_len), callback_(callback) {}\n\nBackgroundWriteTask::~BackgroundWriteTask() {}\n\nvoid BackgroundWriteTask::Run() {\n int result = WriteFile(file_, buf_, buf_len_);\n callback_->Run(result);\n}\n\n} \/\/ namespace\n\n\/\/ CancelableCallbackTask takes ownership of the Callback. This task gets\n\/\/ posted to the MessageLoopForIO instance.\nclass CancelableCallbackTask : public CancelableTask {\n public:\n explicit CancelableCallbackTask(Callback0::Type* callback)\n : canceled_(false), callback_(callback) {}\n\n virtual void Run() {\n if (!canceled_)\n callback_->Run();\n }\n\n virtual void Cancel() {\n canceled_ = true;\n }\n\n private:\n bool canceled_;\n scoped_ptr<Callback0::Type> callback_;\n};\n\n\/\/ FileStream::AsyncContext ----------------------------------------------\n\nclass FileStream::AsyncContext {\n public:\n AsyncContext();\n ~AsyncContext();\n\n \/\/ These methods post synchronous read() and write() calls to a WorkerThread.\n void InitiateAsyncRead(\n base::PlatformFile file, char* buf, int buf_len,\n CompletionCallback* callback);\n void InitiateAsyncWrite(\n base::PlatformFile file, const char* buf, int buf_len,\n CompletionCallback* callback);\n\n CompletionCallback* callback() const { return callback_; }\n\n \/\/ Called by the WorkerPool thread executing the IO after the IO completes.\n \/\/ This method queues RunAsynchronousCallback() on the MessageLoop and signals\n \/\/ |background_io_completed_callback_|, in case the destructor is waiting. In\n \/\/ that case, the destructor will call RunAsynchronousCallback() instead, and\n \/\/ cancel |message_loop_task_|.\n \/\/ |result| is the result of the Read\/Write task.\n void OnBackgroundIOCompleted(int result);\n\n private:\n \/\/ Always called on the IO thread, either directly by a task on the\n \/\/ MessageLoop or by ~AsyncContext().\n void RunAsynchronousCallback();\n\n \/\/ The MessageLoopForIO that this AsyncContext is running on.\n MessageLoopForIO* const message_loop_;\n CompletionCallback* callback_; \/\/ The user provided callback.\n\n \/\/ A callback wrapper around OnBackgroundIOCompleted(). Run by the WorkerPool\n \/\/ thread doing the background IO on our behalf.\n CompletionCallbackImpl<AsyncContext> background_io_completed_callback_;\n\n \/\/ This is used to synchronize between the AsyncContext destructor (which runs\n \/\/ on the IO thread and OnBackgroundIOCompleted() which runs on the WorkerPool\n \/\/ thread.\n base::WaitableEvent background_io_completed_;\n\n \/\/ These variables are only valid when background_io_completed is signaled.\n int result_;\n CancelableCallbackTask* message_loop_task_;\n\n bool is_closing_;\n\n DISALLOW_COPY_AND_ASSIGN(AsyncContext);\n};\n\nFileStream::AsyncContext::AsyncContext()\n : message_loop_(MessageLoopForIO::current()),\n callback_(NULL),\n background_io_completed_callback_(\n this, &AsyncContext::OnBackgroundIOCompleted),\n background_io_completed_(true, false),\n message_loop_task_(NULL),\n is_closing_(false) {}\n\nFileStream::AsyncContext::~AsyncContext() {\n is_closing_ = true;\n if (callback_) {\n \/\/ If |callback_| is non-NULL, that implies either the worker thread is\n \/\/ still running the IO task, or the completion callback is queued up on the\n \/\/ MessageLoopForIO, but AsyncContext() got deleted before then.\n const bool need_to_wait = !background_io_completed_.IsSignaled();\n base::TimeTicks start = base::TimeTicks::Now();\n RunAsynchronousCallback();\n if (need_to_wait) {\n \/\/ We want to see if we block the message loop for too long.\n UMA_HISTOGRAM_TIMES(\"AsyncIO.FileStreamClose\",\n base::TimeTicks::Now() - start);\n }\n }\n}\n\nvoid FileStream::AsyncContext::InitiateAsyncRead(\n base::PlatformFile file, char* buf, int buf_len,\n CompletionCallback* callback) {\n DCHECK(!callback_);\n callback_ = callback;\n\n base::WorkerPool::PostTask(FROM_HERE,\n new BackgroundReadTask(\n file, buf, buf_len,\n &background_io_completed_callback_),\n true \/* task_is_slow *\/);\n}\n\nvoid FileStream::AsyncContext::InitiateAsyncWrite(\n base::PlatformFile file, const char* buf, int buf_len,\n CompletionCallback* callback) {\n DCHECK(!callback_);\n callback_ = callback;\n\n base::WorkerPool::PostTask(FROM_HERE,\n new BackgroundWriteTask(\n file, buf, buf_len,\n &background_io_completed_callback_),\n true \/* task_is_slow *\/);\n}\n\nvoid FileStream::AsyncContext::OnBackgroundIOCompleted(int result) {\n result_ = result;\n message_loop_task_ = new CancelableCallbackTask(\n NewCallback(this, &AsyncContext::RunAsynchronousCallback));\n message_loop_->PostTask(FROM_HERE, message_loop_task_);\n background_io_completed_.Signal();\n}\n\nvoid FileStream::AsyncContext::RunAsynchronousCallback() {\n \/\/ Wait() here ensures that all modifications from the WorkerPool thread are\n \/\/ now visible.\n background_io_completed_.Wait();\n\n \/\/ Either we're in the MessageLoop's task, in which case Cancel() doesn't do\n \/\/ anything, or we're in ~AsyncContext(), in which case this prevents the call\n \/\/ from happening again. Must do it here after calling Wait().\n message_loop_task_->Cancel();\n message_loop_task_ = NULL;\n\n if (is_closing_) {\n callback_ = NULL;\n return;\n }\n\n DCHECK(callback_);\n CompletionCallback* temp = NULL;\n std::swap(temp, callback_);\n background_io_completed_.Reset();\n temp->Run(result_);\n}\n\n\/\/ FileStream ------------------------------------------------------------\n\nFileStream::FileStream()\n : file_(base::kInvalidPlatformFileValue),\n open_flags_(0),\n auto_closed_(true) {\n DCHECK(!IsOpen());\n}\n\nFileStream::FileStream(base::PlatformFile file, int flags)\n : file_(file),\n open_flags_(flags),\n auto_closed_(false) {\n \/\/ If the file handle is opened with base::PLATFORM_FILE_ASYNC, we need to\n \/\/ make sure we will perform asynchronous File IO to it.\n if (flags & base::PLATFORM_FILE_ASYNC) {\n async_context_.reset(new AsyncContext());\n }\n}\n\nFileStream::~FileStream() {\n if (auto_closed_)\n Close();\n}\n\nvoid FileStream::Close() {\n \/\/ Abort any existing asynchronous operations.\n async_context_.reset();\n\n if (file_ != base::kInvalidPlatformFileValue) {\n if (close(file_) != 0) {\n NOTREACHED();\n }\n file_ = base::kInvalidPlatformFileValue;\n }\n}\n\nint FileStream::Open(const FilePath& path, int open_flags) {\n if (IsOpen()) {\n DLOG(FATAL) << \"File is already open!\";\n return ERR_UNEXPECTED;\n }\n\n open_flags_ = open_flags;\n file_ = base::CreatePlatformFile(path, open_flags_, NULL, NULL);\n if (file_ == base::kInvalidPlatformFileValue) {\n return MapErrorCode(errno);\n }\n\n if (open_flags_ & base::PLATFORM_FILE_ASYNC) {\n async_context_.reset(new AsyncContext());\n }\n\n return OK;\n}\n\nbool FileStream::IsOpen() const {\n return file_ != base::kInvalidPlatformFileValue;\n}\n\nint64 FileStream::Seek(Whence whence, int64 offset) {\n base::ThreadRestrictions::AssertIOAllowed();\n\n if (!IsOpen())\n return ERR_UNEXPECTED;\n\n \/\/ If we're in async, make sure we don't have a request in flight.\n DCHECK(!async_context_.get() || !async_context_->callback());\n\n off_t res = lseek(file_, static_cast<off_t>(offset),\n static_cast<int>(whence));\n if (res == static_cast<off_t>(-1))\n return MapErrorCode(errno);\n\n return res;\n}\n\nint64 FileStream::Available() {\n base::ThreadRestrictions::AssertIOAllowed();\n\n if (!IsOpen())\n return ERR_UNEXPECTED;\n\n int64 cur_pos = Seek(FROM_CURRENT, 0);\n if (cur_pos < 0)\n return cur_pos;\n\n struct stat info;\n if (fstat(file_, &info) != 0)\n return MapErrorCode(errno);\n\n int64 size = static_cast<int64>(info.st_size);\n DCHECK_GT(size, cur_pos);\n\n return size - cur_pos;\n}\n\nint FileStream::Read(\n char* buf, int buf_len, CompletionCallback* callback) {\n if (!IsOpen())\n return ERR_UNEXPECTED;\n\n \/\/ read(..., 0) will return 0, which indicates end-of-file.\n DCHECK(buf_len > 0);\n DCHECK(open_flags_ & base::PLATFORM_FILE_READ);\n\n if (async_context_.get()) {\n DCHECK(open_flags_ & base::PLATFORM_FILE_ASYNC);\n \/\/ If we're in async, make sure we don't have a request in flight.\n DCHECK(!async_context_->callback());\n async_context_->InitiateAsyncRead(file_, buf, buf_len, callback);\n return ERR_IO_PENDING;\n } else {\n return ReadFile(file_, buf, buf_len);\n }\n}\n\nint FileStream::ReadUntilComplete(char *buf, int buf_len) {\n int to_read = buf_len;\n int bytes_total = 0;\n\n do {\n int bytes_read = Read(buf, to_read, NULL);\n if (bytes_read <= 0) {\n if (bytes_total == 0)\n return bytes_read;\n\n return bytes_total;\n }\n\n bytes_total += bytes_read;\n buf += bytes_read;\n to_read -= bytes_read;\n } while (bytes_total < buf_len);\n\n return bytes_total;\n}\n\nint FileStream::Write(\n const char* buf, int buf_len, CompletionCallback* callback) {\n \/\/ write(..., 0) will return 0, which indicates end-of-file.\n DCHECK_GT(buf_len, 0);\n\n if (!IsOpen())\n return ERR_UNEXPECTED;\n\n if (async_context_.get()) {\n DCHECK(open_flags_ & base::PLATFORM_FILE_ASYNC);\n \/\/ If we're in async, make sure we don't have a request in flight.\n DCHECK(!async_context_->callback());\n async_context_->InitiateAsyncWrite(file_, buf, buf_len, callback);\n return ERR_IO_PENDING;\n } else {\n return WriteFile(file_, buf, buf_len);\n }\n}\n\nint64 FileStream::Truncate(int64 bytes) {\n base::ThreadRestrictions::AssertIOAllowed();\n\n if (!IsOpen())\n return ERR_UNEXPECTED;\n\n \/\/ We better be open for reading.\n DCHECK(open_flags_ & base::PLATFORM_FILE_WRITE);\n\n \/\/ Seek to the position to truncate from.\n int64 seek_position = Seek(FROM_BEGIN, bytes);\n if (seek_position != bytes)\n return ERR_UNEXPECTED;\n\n \/\/ And truncate the file.\n int result = ftruncate(file_, bytes);\n return result == 0 ? seek_position : MapErrorCode(errno);\n}\n\nint FileStream::Flush() {\n if (!IsOpen())\n return ERR_UNEXPECTED;\n\n return FlushFile(file_);\n}\n\n} \/\/ namespace net\n<commit_msg>Use NewRunnableFunction in file_stream_posix.cc to get rid of custom Task subclasses.<commit_after>\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n\/\/ For 64-bit file access (off_t = off64_t, lseek64, etc).\n#define _FILE_OFFSET_BITS 64\n\n#include \"net\/base\/file_stream.h\"\n\n#include <sys\/types.h>\n#include <sys\/stat.h>\n#include <fcntl.h>\n#include <unistd.h>\n#include <errno.h>\n\n#include \"base\/basictypes.h\"\n#include \"base\/callback.h\"\n#include \"base\/eintr_wrapper.h\"\n#include \"base\/file_path.h\"\n#include \"base\/logging.h\"\n#include \"base\/message_loop.h\"\n#include \"base\/metrics\/histogram.h\"\n#include \"base\/string_util.h\"\n#include \"base\/task.h\"\n#include \"base\/threading\/thread_restrictions.h\"\n#include \"base\/threading\/worker_pool.h\"\n#include \"base\/synchronization\/waitable_event.h\"\n#include \"net\/base\/net_errors.h\"\n\n\/\/ We cast back and forth, so make sure it's the size we're expecting.\nCOMPILE_ASSERT(sizeof(int64) == sizeof(off_t), off_t_64_bit);\n\n\/\/ Make sure our Whence mappings match the system headers.\nCOMPILE_ASSERT(net::FROM_BEGIN == SEEK_SET &&\n net::FROM_CURRENT == SEEK_CUR &&\n net::FROM_END == SEEK_END, whence_matches_system);\n\nnamespace net {\nnamespace {\n\n\/\/ Map from errno to net error codes.\nint64 MapErrorCode(int err) {\n switch (err) {\n case ENOENT:\n return ERR_FILE_NOT_FOUND;\n case EACCES:\n return ERR_ACCESS_DENIED;\n default:\n LOG(WARNING) << \"Unknown error \" << err << \" mapped to net::ERR_FAILED\";\n return ERR_FAILED;\n }\n}\n\n\/\/ ReadFile() is a simple wrapper around read() that handles EINTR signals and\n\/\/ calls MapErrorCode() to map errno to net error codes.\nint ReadFile(base::PlatformFile file, char* buf, int buf_len) {\n base::ThreadRestrictions::AssertIOAllowed();\n \/\/ read(..., 0) returns 0 to indicate end-of-file.\n\n \/\/ Loop in the case of getting interrupted by a signal.\n ssize_t res = HANDLE_EINTR(read(file, buf, static_cast<size_t>(buf_len)));\n if (res == static_cast<ssize_t>(-1))\n return MapErrorCode(errno);\n return static_cast<int>(res);\n}\n\nvoid ReadFileTask(base::PlatformFile file,\n char* buf,\n int buf_len,\n CompletionCallback* callback) {\n callback->Run(ReadFile(file, buf, buf_len));\n}\n\n\/\/ WriteFile() is a simple wrapper around write() that handles EINTR signals and\n\/\/ calls MapErrorCode() to map errno to net error codes. It tries to write to\n\/\/ completion.\nint WriteFile(base::PlatformFile file, const char* buf, int buf_len) {\n base::ThreadRestrictions::AssertIOAllowed();\n ssize_t res = HANDLE_EINTR(write(file, buf, buf_len));\n if (res == -1)\n return MapErrorCode(errno);\n return res;\n}\n\nvoid WriteFileTask(base::PlatformFile file,\n const char* buf,\n int buf_len,\n CompletionCallback* callback) {\n callback->Run(WriteFile(file, buf, buf_len));\n}\n\n\/\/ FlushFile() is a simple wrapper around fsync() that handles EINTR signals and\n\/\/ calls MapErrorCode() to map errno to net error codes. It tries to flush to\n\/\/ completion.\nint FlushFile(base::PlatformFile file) {\n base::ThreadRestrictions::AssertIOAllowed();\n ssize_t res = HANDLE_EINTR(fsync(file));\n if (res == -1)\n return MapErrorCode(errno);\n return res;\n}\n\n} \/\/ namespace\n\n\/\/ CancelableCallbackTask takes ownership of the Callback. This task gets\n\/\/ posted to the MessageLoopForIO instance.\nclass CancelableCallbackTask : public CancelableTask {\n public:\n explicit CancelableCallbackTask(Callback0::Type* callback)\n : canceled_(false), callback_(callback) {}\n\n virtual void Run() {\n if (!canceled_)\n callback_->Run();\n }\n\n virtual void Cancel() {\n canceled_ = true;\n }\n\n private:\n bool canceled_;\n scoped_ptr<Callback0::Type> callback_;\n};\n\n\/\/ FileStream::AsyncContext ----------------------------------------------\n\nclass FileStream::AsyncContext {\n public:\n AsyncContext();\n ~AsyncContext();\n\n \/\/ These methods post synchronous read() and write() calls to a WorkerThread.\n void InitiateAsyncRead(\n base::PlatformFile file, char* buf, int buf_len,\n CompletionCallback* callback);\n void InitiateAsyncWrite(\n base::PlatformFile file, const char* buf, int buf_len,\n CompletionCallback* callback);\n\n CompletionCallback* callback() const { return callback_; }\n\n \/\/ Called by the WorkerPool thread executing the IO after the IO completes.\n \/\/ This method queues RunAsynchronousCallback() on the MessageLoop and signals\n \/\/ |background_io_completed_callback_|, in case the destructor is waiting. In\n \/\/ that case, the destructor will call RunAsynchronousCallback() instead, and\n \/\/ cancel |message_loop_task_|.\n \/\/ |result| is the result of the Read\/Write task.\n void OnBackgroundIOCompleted(int result);\n\n private:\n \/\/ Always called on the IO thread, either directly by a task on the\n \/\/ MessageLoop or by ~AsyncContext().\n void RunAsynchronousCallback();\n\n \/\/ The MessageLoopForIO that this AsyncContext is running on.\n MessageLoopForIO* const message_loop_;\n CompletionCallback* callback_; \/\/ The user provided callback.\n\n \/\/ A callback wrapper around OnBackgroundIOCompleted(). Run by the WorkerPool\n \/\/ thread doing the background IO on our behalf.\n CompletionCallbackImpl<AsyncContext> background_io_completed_callback_;\n\n \/\/ This is used to synchronize between the AsyncContext destructor (which runs\n \/\/ on the IO thread and OnBackgroundIOCompleted() which runs on the WorkerPool\n \/\/ thread.\n base::WaitableEvent background_io_completed_;\n\n \/\/ These variables are only valid when background_io_completed is signaled.\n int result_;\n CancelableCallbackTask* message_loop_task_;\n\n bool is_closing_;\n\n DISALLOW_COPY_AND_ASSIGN(AsyncContext);\n};\n\nFileStream::AsyncContext::AsyncContext()\n : message_loop_(MessageLoopForIO::current()),\n callback_(NULL),\n background_io_completed_callback_(\n this, &AsyncContext::OnBackgroundIOCompleted),\n background_io_completed_(true, false),\n message_loop_task_(NULL),\n is_closing_(false) {}\n\nFileStream::AsyncContext::~AsyncContext() {\n is_closing_ = true;\n if (callback_) {\n \/\/ If |callback_| is non-NULL, that implies either the worker thread is\n \/\/ still running the IO task, or the completion callback is queued up on the\n \/\/ MessageLoopForIO, but AsyncContext() got deleted before then.\n const bool need_to_wait = !background_io_completed_.IsSignaled();\n base::TimeTicks start = base::TimeTicks::Now();\n RunAsynchronousCallback();\n if (need_to_wait) {\n \/\/ We want to see if we block the message loop for too long.\n UMA_HISTOGRAM_TIMES(\"AsyncIO.FileStreamClose\",\n base::TimeTicks::Now() - start);\n }\n }\n}\n\nvoid FileStream::AsyncContext::InitiateAsyncRead(\n base::PlatformFile file, char* buf, int buf_len,\n CompletionCallback* callback) {\n DCHECK(!callback_);\n callback_ = callback;\n\n base::WorkerPool::PostTask(FROM_HERE,\n NewRunnableFunction(\n &ReadFileTask,\n file, buf, buf_len,\n &background_io_completed_callback_),\n true \/* task_is_slow *\/);\n}\n\nvoid FileStream::AsyncContext::InitiateAsyncWrite(\n base::PlatformFile file, const char* buf, int buf_len,\n CompletionCallback* callback) {\n DCHECK(!callback_);\n callback_ = callback;\n\n base::WorkerPool::PostTask(FROM_HERE,\n NewRunnableFunction(\n &WriteFileTask,\n file, buf, buf_len,\n &background_io_completed_callback_),\n true \/* task_is_slow *\/);\n}\n\nvoid FileStream::AsyncContext::OnBackgroundIOCompleted(int result) {\n result_ = result;\n message_loop_task_ = new CancelableCallbackTask(\n NewCallback(this, &AsyncContext::RunAsynchronousCallback));\n message_loop_->PostTask(FROM_HERE, message_loop_task_);\n background_io_completed_.Signal();\n}\n\nvoid FileStream::AsyncContext::RunAsynchronousCallback() {\n \/\/ Wait() here ensures that all modifications from the WorkerPool thread are\n \/\/ now visible.\n background_io_completed_.Wait();\n\n \/\/ Either we're in the MessageLoop's task, in which case Cancel() doesn't do\n \/\/ anything, or we're in ~AsyncContext(), in which case this prevents the call\n \/\/ from happening again. Must do it here after calling Wait().\n message_loop_task_->Cancel();\n message_loop_task_ = NULL;\n\n if (is_closing_) {\n callback_ = NULL;\n return;\n }\n\n DCHECK(callback_);\n CompletionCallback* temp = NULL;\n std::swap(temp, callback_);\n background_io_completed_.Reset();\n temp->Run(result_);\n}\n\n\/\/ FileStream ------------------------------------------------------------\n\nFileStream::FileStream()\n : file_(base::kInvalidPlatformFileValue),\n open_flags_(0),\n auto_closed_(true) {\n DCHECK(!IsOpen());\n}\n\nFileStream::FileStream(base::PlatformFile file, int flags)\n : file_(file),\n open_flags_(flags),\n auto_closed_(false) {\n \/\/ If the file handle is opened with base::PLATFORM_FILE_ASYNC, we need to\n \/\/ make sure we will perform asynchronous File IO to it.\n if (flags & base::PLATFORM_FILE_ASYNC) {\n async_context_.reset(new AsyncContext());\n }\n}\n\nFileStream::~FileStream() {\n if (auto_closed_)\n Close();\n}\n\nvoid FileStream::Close() {\n \/\/ Abort any existing asynchronous operations.\n async_context_.reset();\n\n if (file_ != base::kInvalidPlatformFileValue) {\n if (close(file_) != 0) {\n NOTREACHED();\n }\n file_ = base::kInvalidPlatformFileValue;\n }\n}\n\nint FileStream::Open(const FilePath& path, int open_flags) {\n if (IsOpen()) {\n DLOG(FATAL) << \"File is already open!\";\n return ERR_UNEXPECTED;\n }\n\n open_flags_ = open_flags;\n file_ = base::CreatePlatformFile(path, open_flags_, NULL, NULL);\n if (file_ == base::kInvalidPlatformFileValue) {\n return MapErrorCode(errno);\n }\n\n if (open_flags_ & base::PLATFORM_FILE_ASYNC) {\n async_context_.reset(new AsyncContext());\n }\n\n return OK;\n}\n\nbool FileStream::IsOpen() const {\n return file_ != base::kInvalidPlatformFileValue;\n}\n\nint64 FileStream::Seek(Whence whence, int64 offset) {\n base::ThreadRestrictions::AssertIOAllowed();\n\n if (!IsOpen())\n return ERR_UNEXPECTED;\n\n \/\/ If we're in async, make sure we don't have a request in flight.\n DCHECK(!async_context_.get() || !async_context_->callback());\n\n off_t res = lseek(file_, static_cast<off_t>(offset),\n static_cast<int>(whence));\n if (res == static_cast<off_t>(-1))\n return MapErrorCode(errno);\n\n return res;\n}\n\nint64 FileStream::Available() {\n base::ThreadRestrictions::AssertIOAllowed();\n\n if (!IsOpen())\n return ERR_UNEXPECTED;\n\n int64 cur_pos = Seek(FROM_CURRENT, 0);\n if (cur_pos < 0)\n return cur_pos;\n\n struct stat info;\n if (fstat(file_, &info) != 0)\n return MapErrorCode(errno);\n\n int64 size = static_cast<int64>(info.st_size);\n DCHECK_GT(size, cur_pos);\n\n return size - cur_pos;\n}\n\nint FileStream::Read(\n char* buf, int buf_len, CompletionCallback* callback) {\n if (!IsOpen())\n return ERR_UNEXPECTED;\n\n \/\/ read(..., 0) will return 0, which indicates end-of-file.\n DCHECK(buf_len > 0);\n DCHECK(open_flags_ & base::PLATFORM_FILE_READ);\n\n if (async_context_.get()) {\n DCHECK(open_flags_ & base::PLATFORM_FILE_ASYNC);\n \/\/ If we're in async, make sure we don't have a request in flight.\n DCHECK(!async_context_->callback());\n async_context_->InitiateAsyncRead(file_, buf, buf_len, callback);\n return ERR_IO_PENDING;\n } else {\n return ReadFile(file_, buf, buf_len);\n }\n}\n\nint FileStream::ReadUntilComplete(char *buf, int buf_len) {\n int to_read = buf_len;\n int bytes_total = 0;\n\n do {\n int bytes_read = Read(buf, to_read, NULL);\n if (bytes_read <= 0) {\n if (bytes_total == 0)\n return bytes_read;\n\n return bytes_total;\n }\n\n bytes_total += bytes_read;\n buf += bytes_read;\n to_read -= bytes_read;\n } while (bytes_total < buf_len);\n\n return bytes_total;\n}\n\nint FileStream::Write(\n const char* buf, int buf_len, CompletionCallback* callback) {\n \/\/ write(..., 0) will return 0, which indicates end-of-file.\n DCHECK_GT(buf_len, 0);\n\n if (!IsOpen())\n return ERR_UNEXPECTED;\n\n if (async_context_.get()) {\n DCHECK(open_flags_ & base::PLATFORM_FILE_ASYNC);\n \/\/ If we're in async, make sure we don't have a request in flight.\n DCHECK(!async_context_->callback());\n async_context_->InitiateAsyncWrite(file_, buf, buf_len, callback);\n return ERR_IO_PENDING;\n } else {\n return WriteFile(file_, buf, buf_len);\n }\n}\n\nint64 FileStream::Truncate(int64 bytes) {\n base::ThreadRestrictions::AssertIOAllowed();\n\n if (!IsOpen())\n return ERR_UNEXPECTED;\n\n \/\/ We better be open for reading.\n DCHECK(open_flags_ & base::PLATFORM_FILE_WRITE);\n\n \/\/ Seek to the position to truncate from.\n int64 seek_position = Seek(FROM_BEGIN, bytes);\n if (seek_position != bytes)\n return ERR_UNEXPECTED;\n\n \/\/ And truncate the file.\n int result = ftruncate(file_, bytes);\n return result == 0 ? seek_position : MapErrorCode(errno);\n}\n\nint FileStream::Flush() {\n if (!IsOpen())\n return ERR_UNEXPECTED;\n\n return FlushFile(file_);\n}\n\n} \/\/ namespace net\n<|endoftext|>"} {"text":"<commit_before>\/\/ lerc.cc\n\/\/\n\/\/ Copyright (c) 2016 Frank Lin (lin.xiaoe.f@gmail.com)\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n\/\/ THE SOFTWARE.\n\n#include \"lerc_util.h\"\n\n#include \"tiffio.h\"\n\n#include \"Lerc\/Lerc.h\"\n\nNS_GAGO_BEGIN\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Lerc, public:\n\n\/\/ Tiff --------------------------------------------------------\n\nbool LercUtil::EncodeTiffOrDie(const std::string& path_to_file, const std::string& output_path,\n double max_z_error, LercVersion lerc_ver, DataType data_type,\n uint16_t band, bool signed_type) {\n Logger::LogD(\"Encoding %s\", path_to_file.c_str());\n TIFF* tif = TIFFOpen(path_to_file.c_str(), \"r\");\n if (tif == nullptr) {\n Logger::LogD(\"ERROR when TIFFOpen %s\\n\", path_to_file.c_str());\n return false;\n }\n \n uint32_t width = 0;\n uint32_t height = 0;\n tdata_t buf;\n \n uint32_t tiff_dt = 0;\n \n uint32_t bits_per_sample = 0;\n \n TIFFGetField(tif, TIFFTAG_IMAGEWIDTH, &width);\n TIFFGetField(tif, TIFFTAG_IMAGELENGTH, &height);\n TIFFGetField(tif, TIFFTAG_DATATYPE, &tiff_dt);\n TIFFGetField(tif, TIFFTAG_BITSPERSAMPLE, &bits_per_sample);\n \n uint32_t type_size = 0;\n if (tiff_dt == SAMPLEFORMAT_INT) {\n if (bits_per_sample == 8) {\n data_type = signed_type ? DataType::CHAR : DataType::BYTE;\n type_size = sizeof(int8_t);\n } else if (bits_per_sample == 16) {\n data_type = signed_type ? DataType::SHORT : DataType::USHORT;\n type_size = sizeof(int16_t);\n } else if (bits_per_sample == 32) {\n data_type = signed_type ? DataType::INT : DataType::UINT;\n type_size = sizeof(int32_t);\n } else {\n Logger::LogD(\"Unknown bits per sample %s\", path_to_file.c_str());\n }\n } else if (tiff_dt == SAMPLEFORMAT_IEEEFP) {\n data_type = DataType::FLOAT;\n type_size = 4;\n } else {\n Logger::LogD(\"Unsupported TIFF data format %s\", path_to_file.c_str());\n return false;\n }\n \n \/\/ data\n unsigned char* data = new unsigned char[width * height * type_size];\n \n size_t line_size = TIFFScanlineSize(tif);\n \n for (int row = 0; row < height; ++row) {\n buf = _TIFFmalloc(line_size);\n TIFFReadScanline(tif, buf, row, bits_per_sample);\n \n memcpy(data + width * row * type_size, buf, line_size);\n \n _TIFFfree(buf);\n }\n \n TIFFClose(tif);\n \n \/\/ compress float buffer to lerc\n size_t num_bytes_needed = 0;\n size_t num_bytes_written = 0;\n LercNS::Lerc lerc;\n \n \/\/ convert data type to proper one\n LercNS::Lerc::DataType lerc_dt = static_cast<LercNS::Lerc::DataType>(data_type);\n if (lerc_dt == LercNS::Lerc::DataType::DT_Double ||\n lerc_dt == LercNS::Lerc::DataType::DT_Char ||\n lerc_dt == LercNS::Lerc::DataType::DT_Short ||\n lerc_dt == LercNS::Lerc::DataType::DT_UShort ||\n lerc_dt == LercNS::Lerc::DataType::DT_Undefined) {\n Logger::LogD(\"ERROR input data type %s\\n\", path_to_file.c_str());\n return false;\n }\n \n if (!lerc.ComputeBufferSize((void*)data, \/\/ raw image data, row by row, band by band\n lerc_dt,\n width, height, band,\n 0, \/\/ set 0 if all pixels are valid\n max_z_error, \/\/ max coding error per pixel, or precision\n num_bytes_needed)) { \/\/ size of outgoing Lerc blob\n Logger::LogD(\"ERROR when ComputeBufferSize %s\\n\", path_to_file.c_str());\n return false;\n }\n \n size_t num_bytes_blob = num_bytes_needed;\n LercNS::Byte* lerc_buffer = new LercNS::Byte[num_bytes_blob];\n \n if (!lerc.Encode((void*)data, \/\/ raw image data, row by row, band by band\n lerc_dt,\n width, height, band,\n 0, \/\/ 0 if all pixels are valid\n max_z_error, \/\/ max coding error per pixel, or precision\n lerc_buffer, \/\/ buffer to write to, function will fail if buffer too small\n num_bytes_blob, \/\/ buffer size\n num_bytes_written)) { \/\/ num bytes written to buffer\n Logger::LogD(\"ERROR when Encode %s\\n\", path_to_file.c_str());\n return false;\n }\n \n \/\/ write to file\n FILE* file = fopen(output_path.c_str(), \"wb\");\n fwrite(lerc_buffer, 1, num_bytes_written, file); \/\/ write bytes\n fclose(file);\n \n \/\/ clean memory\n delete[] data;\n \n return true;\n}\n\nNS_GAGO_END\n<commit_msg>Add missing stdio.h include.<commit_after>\/\/ lerc.cc\n\/\/\n\/\/ Copyright (c) 2016 Frank Lin (lin.xiaoe.f@gmail.com)\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n\/\/ THE SOFTWARE.\n\n#include \"lerc_util.h\"\n\n#include <stdio.h>\n\n#include \"tiffio.h\"\n\n#include \"Lerc\/Lerc.h\"\n\nNS_GAGO_BEGIN\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Lerc, public:\n\n\/\/ Tiff --------------------------------------------------------\n\nbool LercUtil::EncodeTiffOrDie(const std::string& path_to_file, const std::string& output_path,\n double max_z_error, LercVersion lerc_ver, DataType data_type,\n uint16_t band, bool signed_type) {\n Logger::LogD(\"Encoding %s\", path_to_file.c_str());\n TIFF* tif = TIFFOpen(path_to_file.c_str(), \"r\");\n if (tif == nullptr) {\n Logger::LogD(\"ERROR when TIFFOpen %s\\n\", path_to_file.c_str());\n return false;\n }\n \n uint32_t width = 0;\n uint32_t height = 0;\n tdata_t buf;\n \n uint32_t tiff_dt = 0;\n \n uint32_t bits_per_sample = 0;\n \n TIFFGetField(tif, TIFFTAG_IMAGEWIDTH, &width);\n TIFFGetField(tif, TIFFTAG_IMAGELENGTH, &height);\n TIFFGetField(tif, TIFFTAG_DATATYPE, &tiff_dt);\n TIFFGetField(tif, TIFFTAG_BITSPERSAMPLE, &bits_per_sample);\n \n uint32_t type_size = 0;\n if (tiff_dt == SAMPLEFORMAT_INT) {\n if (bits_per_sample == 8) {\n data_type = signed_type ? DataType::CHAR : DataType::BYTE;\n type_size = sizeof(int8_t);\n } else if (bits_per_sample == 16) {\n data_type = signed_type ? DataType::SHORT : DataType::USHORT;\n type_size = sizeof(int16_t);\n } else if (bits_per_sample == 32) {\n data_type = signed_type ? DataType::INT : DataType::UINT;\n type_size = sizeof(int32_t);\n } else {\n Logger::LogD(\"Unknown bits per sample %s\", path_to_file.c_str());\n }\n } else if (tiff_dt == SAMPLEFORMAT_IEEEFP) {\n data_type = DataType::FLOAT;\n type_size = 4;\n } else {\n Logger::LogD(\"Unsupported TIFF data format %s\", path_to_file.c_str());\n return false;\n }\n \n \/\/ data\n unsigned char* data = new unsigned char[width * height * type_size];\n \n size_t line_size = TIFFScanlineSize(tif);\n \n for (int row = 0; row < height; ++row) {\n buf = _TIFFmalloc(line_size);\n TIFFReadScanline(tif, buf, row, bits_per_sample);\n \n memcpy(data + width * row * type_size, buf, line_size);\n \n _TIFFfree(buf);\n }\n \n TIFFClose(tif);\n \n \/\/ compress float buffer to lerc\n size_t num_bytes_needed = 0;\n size_t num_bytes_written = 0;\n LercNS::Lerc lerc;\n \n \/\/ convert data type to proper one\n LercNS::Lerc::DataType lerc_dt = static_cast<LercNS::Lerc::DataType>(data_type);\n if (lerc_dt == LercNS::Lerc::DataType::DT_Double ||\n lerc_dt == LercNS::Lerc::DataType::DT_Char ||\n lerc_dt == LercNS::Lerc::DataType::DT_Short ||\n lerc_dt == LercNS::Lerc::DataType::DT_UShort ||\n lerc_dt == LercNS::Lerc::DataType::DT_Undefined) {\n Logger::LogD(\"ERROR input data type %s\\n\", path_to_file.c_str());\n return false;\n }\n \n if (!lerc.ComputeBufferSize((void*)data, \/\/ raw image data, row by row, band by band\n lerc_dt,\n width, height, band,\n 0, \/\/ set 0 if all pixels are valid\n max_z_error, \/\/ max coding error per pixel, or precision\n num_bytes_needed)) { \/\/ size of outgoing Lerc blob\n Logger::LogD(\"ERROR when ComputeBufferSize %s\\n\", path_to_file.c_str());\n return false;\n }\n \n size_t num_bytes_blob = num_bytes_needed;\n LercNS::Byte* lerc_buffer = new LercNS::Byte[num_bytes_blob];\n \n if (!lerc.Encode((void*)data, \/\/ raw image data, row by row, band by band\n lerc_dt,\n width, height, band,\n 0, \/\/ 0 if all pixels are valid\n max_z_error, \/\/ max coding error per pixel, or precision\n lerc_buffer, \/\/ buffer to write to, function will fail if buffer too small\n num_bytes_blob, \/\/ buffer size\n num_bytes_written)) { \/\/ num bytes written to buffer\n Logger::LogD(\"ERROR when Encode %s\\n\", path_to_file.c_str());\n return false;\n }\n \n \/\/ write to file\n FILE* file = fopen(output_path.c_str(), \"wb\");\n fwrite(lerc_buffer, 1, num_bytes_written, file); \/\/ write bytes\n fclose(file);\n \n \/\/ clean memory\n delete[] data;\n \n return true;\n}\n\nNS_GAGO_END\n<|endoftext|>"} {"text":"<commit_before>\/******************************************************************************\nThe MIT License(MIT)\n\nEmbedded Template Library.\nhttps:\/\/github.com\/ETLCPP\/etl\nhttp:\/\/www.etlcpp.com\n\nCopyright(c) 2014 jwellbelove\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files(the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and \/ or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions :\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n******************************************************************************\/\n\n#include <UnitTest++\/UnitTest++.h>\n\n#include <iterator>\n#include <string>\n#include <vector>\n#include <stdint.h>\n\n#include \"..\/bsd_checksum.h\"\n#include \"..\/endian.h\"\n\ntemplate <typename TSum, typename TIterator>\nTSum reference_checksum(TIterator begin, TIterator end)\n{\n typedef typename std::iterator_traits<TIterator>::value_type value_type;\n TSum checksum = 0;\n\n while (begin != end)\n {\n value_type value = *begin++;\n\n for (int i = 0; i < sizeof(value_type); ++i)\n {\n uint8_t byte = (value >> (i * 8)) & 0xFF;\n checksum = etl::rotate_right(checksum) + byte;\n }\n }\n\n return checksum;\n}\n\nnamespace\n{\t\t\n SUITE(test_checksum)\n {\n \/\/*************************************************************************\n TEST(test_checksum_constructor)\n {\n std::string data(\"123456789\");\n\n uint8_t sum = etl::bsd_checksum<uint8_t>(data.begin(), data.end());\n uint8_t compare = reference_checksum<uint8_t>(data.begin(), data.end());\n\n CHECK_EQUAL(int(compare), int(sum));\n }\n\n \/\/*************************************************************************\n TEST(test_checksum_add_values8_add)\n {\n std::string data(\"123456789\");\n\n etl::bsd_checksum<uint8_t> checksum_calculator;\n\n for (size_t i = 0; i < data.size(); ++i)\n {\n checksum_calculator.add(data[i]);\n }\n \n uint8_t sum = checksum_calculator;\n uint8_t compare = reference_checksum<uint8_t>(data.begin(), data.end());\n\n CHECK_EQUAL(int(compare), int(sum));\n }\n\n \/\/*************************************************************************\n TEST(test_checksum_add_values8_operator_plus_equals)\n {\n std::string data(\"123456789\");\n\n etl::bsd_checksum<uint8_t> checksum_calculator;\n\n for (size_t i = 0; i < data.size(); ++i)\n {\n checksum_calculator.add(data[i]);\n }\n\n uint8_t sum = checksum_calculator;\n uint8_t compare = reference_checksum<uint8_t>(data.begin(), data.end());\n\n CHECK_EQUAL(int(compare), int(sum));\n }\n\n \/\/*************************************************************************\n TEST(test_checksum_add_range)\n {\n std::string data(\"123456789\");\n\n etl::bsd_checksum<uint8_t> checksum_calculator;\n\n checksum_calculator.add(data.begin(), data.end());\n\n uint8_t sum = checksum_calculator.value();\n uint8_t compare = reference_checksum<uint8_t>(data.begin(), data.end());\n\n CHECK_EQUAL(int(compare), int(sum));\n }\n\n \/\/*************************************************************************\n TEST(test_checksum_add_range_sum32)\n {\n std::string data(\"1\");\n\n etl::bsd_checksum<uint32_t> checksum_calculator;\n\n checksum_calculator.add(data.begin(), data.end());\n\n uint32_t sum = checksum_calculator.value();\n uint32_t compare = reference_checksum<uint32_t>(data.begin(), data.end());\n\n CHECK_EQUAL(compare, sum);\n }\n\n \/\/*************************************************************************\n TEST(test_checksum_add_range_endian)\n {\n std::vector<uint8_t> data1 = { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08 };\n std::vector<uint32_t> data2 = { 0x04030201, 0x08070605 };\n std::vector<uint8_t> data3 = { 0x08, 0x07, 0x06, 0x05, 0x04, 0x03, 0x02, 0x01 };\n\n uint64_t hash1 = etl::bsd_checksum<uint8_t>(data1.begin(), data1.end());\n uint64_t hash2 = etl::bsd_checksum<uint8_t>((uint8_t*)&data2[0], (uint8_t*)&data2[0] + (data2.size() * sizeof(uint32_t)));\n uint64_t hash3 = etl::bsd_checksum<uint8_t>(data3.rbegin(), data3.rend());\n CHECK_EQUAL(hash1, hash2);\n CHECK_EQUAL(hash1, hash3);\n }\n };\n}\n\n<commit_msg>Modified checksum class to be easily customised. Added sum, bsd & xor policies. Deleted bsd_checksum.h<commit_after>\/******************************************************************************\nThe MIT License(MIT)\n\nEmbedded Template Library.\nhttps:\/\/github.com\/ETLCPP\/etl\nhttp:\/\/www.etlcpp.com\n\nCopyright(c) 2014 jwellbelove\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files(the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and \/ or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions :\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n******************************************************************************\/\n\n#include <UnitTest++\/UnitTest++.h>\n\n#include <iterator>\n#include <string>\n#include <vector>\n#include <stdint.h>\n\n#include \"..\/checksum.h\"\n\nnamespace\n{\n template <typename TSum, typename TIterator>\n TSum reference_checksum(TIterator begin, TIterator end)\n {\n typedef typename std::iterator_traits<TIterator>::value_type value_type;\n TSum checksum = 0;\n\n while (begin != end)\n {\n value_type value = *begin++;\n\n for (int i = 0; i < sizeof(value_type); ++i)\n {\n uint8_t byte = (value >> (i * 8)) & 0xFF;\n checksum = etl::rotate_right(checksum) + byte;\n }\n }\n\n return checksum;\n }\n\n SUITE(test_checksum)\n {\n \/\/*************************************************************************\n TEST(test_checksum_constructor)\n {\n std::string data(\"123456789\");\n\n uint8_t sum = etl::bsd_checksum<uint8_t>(data.begin(), data.end());\n uint8_t compare = reference_checksum<uint8_t>(data.begin(), data.end());\n\n CHECK_EQUAL(int(compare), int(sum));\n }\n\n \/\/*************************************************************************\n TEST(test_checksum_add_values8_add)\n {\n std::string data(\"123456789\");\n\n etl::bsd_checksum<uint8_t> checksum_calculator;\n\n for (size_t i = 0; i < data.size(); ++i)\n {\n checksum_calculator.add(data[i]);\n }\n \n uint8_t sum = checksum_calculator;\n uint8_t compare = reference_checksum<uint8_t>(data.begin(), data.end());\n\n CHECK_EQUAL(int(compare), int(sum));\n }\n\n \/\/*************************************************************************\n TEST(test_checksum_add_values8_operator_plus_equals)\n {\n std::string data(\"123456789\");\n\n etl::bsd_checksum<uint8_t> checksum_calculator;\n\n for (size_t i = 0; i < data.size(); ++i)\n {\n checksum_calculator.add(data[i]);\n }\n\n uint8_t sum = checksum_calculator;\n uint8_t compare = reference_checksum<uint8_t>(data.begin(), data.end());\n\n CHECK_EQUAL(int(compare), int(sum));\n }\n\n \/\/*************************************************************************\n TEST(test_checksum_add_range)\n {\n std::string data(\"123456789\");\n\n etl::bsd_checksum<uint8_t> checksum_calculator;\n\n checksum_calculator.add(data.begin(), data.end());\n\n uint8_t sum = checksum_calculator.value();\n uint8_t compare = reference_checksum<uint8_t>(data.begin(), data.end());\n\n CHECK_EQUAL(int(compare), int(sum));\n }\n\n \/\/*************************************************************************\n TEST(test_checksum_add_range_sum32)\n {\n std::string data(\"1\");\n\n etl::bsd_checksum<uint32_t> checksum_calculator;\n\n checksum_calculator.add(data.begin(), data.end());\n\n uint32_t sum = checksum_calculator.value();\n uint32_t compare = reference_checksum<uint32_t>(data.begin(), data.end());\n\n CHECK_EQUAL(compare, sum);\n }\n\n \/\/*************************************************************************\n TEST(test_checksum_add_range_endian)\n {\n std::vector<uint8_t> data1 = { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08 };\n std::vector<uint32_t> data2 = { 0x04030201, 0x08070605 };\n std::vector<uint8_t> data3 = { 0x08, 0x07, 0x06, 0x05, 0x04, 0x03, 0x02, 0x01 };\n\n uint64_t hash1 = etl::bsd_checksum<uint8_t>(data1.begin(), data1.end());\n uint64_t hash2 = etl::bsd_checksum<uint8_t>((uint8_t*)&data2[0], (uint8_t*)&data2[0] + (data2.size() * sizeof(uint32_t)));\n uint64_t hash3 = etl::bsd_checksum<uint8_t>(data3.rbegin(), data3.rend());\n CHECK_EQUAL(hash1, hash2);\n CHECK_EQUAL(hash1, hash3);\n }\n };\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/* tcpstream.cpp\n Copyright (C) 2003-2005 Tommi Maekitalo\n\nThis file is part of cxxtools.\n\nCxxtools is free software; you can redistribute it and\/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation; either version 2 of the License, or\n(at your option) any later version.\n\nCxxtools is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License\nalong with Cxxtools; if not, write to the Free Software\nFoundation, Inc., 59 Temple Place, Suite 330,\nBoston, MA 02111-1307 USA\n*\/\n\n#include \"cxxtools\/tcpstream.h\"\n#include <stdexcept>\n#include <sys\/types.h>\n#include <sys\/socket.h>\n#include <unistd.h>\n#include <netinet\/in.h>\n#include <arpa\/inet.h>\n#include <fcntl.h>\n#include <sys\/poll.h>\n#include <errno.h>\n#include <netdb.h>\n\n#undef log_warn\n#undef log_debug\n\n#define log_warn(expr)\n#define log_debug(expr)\n\/\/#define log_warn(expr) do { std::cerr << \"WARN: \" << expr << std::endl; } while(false)\n\/\/#define log_debug(expr) do { std::cerr << \"DEBUG: \" << expr << std::endl; } while(false)\n\nnamespace cxxtools\n{\n\nnamespace tcp\n{\n using namespace std;\n\n Exception::Exception(int Errno, const string& msg)\n : runtime_error(msg + \": \" + strerror(Errno)),\n m_Errno(Errno)\n { }\n\n Exception::Exception(const string& msg)\n : runtime_error(msg + \": \" + strerror(errno)),\n m_Errno(errno)\n { }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ implementation of Socket\n \/\/\n Socket::Socket(int domain, int type, int protocol) throw (Exception)\n : m_timeout(-1)\n {\n if ((m_sockFd = ::socket(domain, type, protocol)) < 0)\n throw Exception(\"cannot create socket\");\n }\n\n Socket::~Socket()\n {\n if (m_sockFd >= 0)\n {\n if (::close(m_sockFd) < 0)\n fprintf(stderr, \"error in close(%d)\\n\", (int)m_sockFd);\n }\n }\n\n void Socket::create(int domain, int type, int protocol) throw (Exception)\n {\n close();\n\n if ((m_sockFd = ::socket(domain, type, protocol)) < 0)\n throw Exception(\"cannot create socket\");\n }\n\n void Socket::close()\n {\n if (m_sockFd >= 0)\n {\n ::close(m_sockFd);\n m_sockFd = -1;\n }\n }\n\n struct sockaddr Socket::getSockAddr() const throw (Exception)\n {\n struct sockaddr ret;\n\n socklen_t slen = sizeof(ret);\n if (::getsockname(getFd(), &ret, &slen) < 0)\n throw Exception(\"error in getsockname\");\n\n return ret;\n }\n\n void Socket::setTimeout(int t)\n {\n m_timeout = t;\n\n if (getFd() >= 0)\n {\n long a = m_timeout >= 0 ? O_NONBLOCK : 0;\n log_debug(\"fcntl(\" << getFd() << \", F_SETFL, \" << a << ')');\n fcntl(getFd(), F_SETFL, a);\n }\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ implementation of Server\n \/\/\n Server::Server()\n : Socket(AF_INET, SOCK_STREAM, 0)\n { }\n\n Server::Server(const std::string& ipaddr, unsigned short int port, int backlog)\n throw (Exception)\n : Socket(AF_INET, SOCK_STREAM, 0)\n {\n Listen(ipaddr, port, backlog);\n }\n\n Server::Server(const char* ipaddr, unsigned short int port,\n int backlog) throw (Exception)\n : Socket(AF_INET, SOCK_STREAM, 0)\n {\n Listen(ipaddr, port, backlog);\n }\n\n void Server::Listen(const char* ipaddr, unsigned short int port,\n int backlog) throw (Exception)\n {\n struct hostent* host = ::gethostbyname(ipaddr);\n if (host == 0)\n throw Exception(std::string(\"invalid ipaddress \") + ipaddr);\n\n memset(&servaddr.sockaddr_in, 0, sizeof(servaddr.sockaddr_in));\n\n servaddr.sockaddr_in.sin_family = AF_INET;\n servaddr.sockaddr_in.sin_port = htons(port);\n\n memmove(&(servaddr.sockaddr_in.sin_addr.s_addr), host->h_addr, host->h_length);\n int reuseAddr = 1;\n if (::setsockopt(getFd(), SOL_SOCKET, SO_REUSEADDR,\n &reuseAddr, sizeof(reuseAddr)) < 0)\n throw Exception(\"error in setsockopt\");\n\n if (::bind(getFd(),\n (struct sockaddr *)&servaddr.sockaddr_in,\n sizeof(servaddr.sockaddr_in)) < 0)\n throw Exception(\"error in bind\");\n\n if (::listen(getFd(), backlog) < 0)\n throw Exception(\"error in listen\");\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ implementation of Stream\n \/\/\n Stream::Stream()\n { }\n\n Stream::Stream(const Server& server)\n {\n Accept(server);\n }\n\n Stream::Stream(const string& ipaddr, unsigned short int port)\n : Socket(AF_INET, SOCK_STREAM, 0)\n {\n Connect(ipaddr, port);\n }\n\n Stream::Stream(const char* ipaddr, unsigned short int port)\n : Socket(AF_INET, SOCK_STREAM, 0)\n {\n Connect(ipaddr, port);\n }\n\n void Stream::Accept(const Server& server)\n {\n close();\n\n socklen_t peeraddr_len;\n peeraddr_len = sizeof(peeraddr);\n setFd(accept(server.getFd(), &peeraddr.sockaddr, &peeraddr_len));\n if (bad())\n throw Exception(\"error in accept\");\n\n setTimeout(getTimeout());\n }\n\n void Stream::Connect(const char* ipaddr, unsigned short int port)\n {\n if (getFd() < 0)\n create(AF_INET, SOCK_STREAM, 0);\n\n struct hostent* host = ::gethostbyname(ipaddr);\n if (host == 0)\n throw Exception(std::string(\"invalid ipaddress \") + ipaddr);\n\n memset(&peeraddr, 0, sizeof(peeraddr));\n peeraddr.sockaddr_in.sin_family = AF_INET;\n peeraddr.sockaddr_in.sin_port = htons(port);\n\n memmove(&(peeraddr.sockaddr_in.sin_addr.s_addr), host->h_addr, host->h_length);\n\n if (::connect(getFd(), &peeraddr.sockaddr,\n sizeof(peeraddr)) < 0)\n throw Exception(\"error in connect\");\n\n setTimeout(getTimeout());\n }\n\n Stream::size_type Stream::Read(char* buffer, Stream::size_type bufsize) const\n {\n ssize_t n;\n\n if (getTimeout() < 0)\n {\n \/\/ blocking read\n log_debug(\"blocking read\");\n n = ::read(getFd(), buffer, bufsize);\n log_debug(\"blocking read ready, return \" << n);\n if (n < 0)\n {\n int errnum = errno;\n throw Exception(strerror(errnum));\n }\n }\n else\n {\n \/\/ non-blocking read\n\n \/\/ try reading without timeout\n log_debug(\"non blocking read fd=\" << getFd());\n n = ::read(getFd(), buffer, bufsize);\n log_debug(\"non blocking read returns \" << n);\n\n if (n < 0)\n {\n \/\/ no data available\n\n if (errno == EAGAIN)\n {\n if (getTimeout() == 0)\n {\n log_warn(\"timeout\");\n throw Timeout();\n }\n\n struct pollfd fds;\n fds.fd = getFd();\n fds.events = POLLIN;\n log_debug(\"poll timeout \" << getTimeout());\n int p = poll(&fds, 1, getTimeout());\n log_debug(\"poll returns \" << p);\n if (p < 0)\n {\n int errnum = errno;\n throw Exception(strerror(errnum));\n }\n else if (p == 0)\n throw Timeout();\n\n log_debug(\"read\");\n n = ::read(getFd(), buffer, bufsize);\n log_debug(\"read returns \" << n);\n }\n else\n {\n int errnum = errno;\n throw Exception(strerror(errnum));\n }\n }\n\n }\n\n return n;\n }\n\n Stream::size_type Stream::Write(const char* buffer,\n Stream::size_type bufsize) const\n {\n size_t n = ::write(getFd(), buffer, bufsize);\n if (n <= 0)\n \/\/ au weia - das ging schief\n throw Exception(\"tcp::Stream: error in write\");\n\n while (n < bufsize)\n {\n buffer += n;\n bufsize -= n;\n\n struct pollfd fds;\n fds.fd = getFd();\n fds.events = POLLOUT;\n int p = poll(&fds, 1, -1);\n\n if (p < 0)\n {\n int errnum = errno;\n throw Exception(strerror(errnum));\n }\n else if (p == 0)\n throw Timeout();\n\n n = ::write(getFd(), buffer, bufsize);\n }\n\n return n;\n }\n\n streambuf::streambuf(Stream& stream, unsigned bufsize, int timeout)\n : m_stream(stream),\n m_bufsize(bufsize),\n m_buffer(new char_type[bufsize])\n {\n setTimeout(timeout);\n }\n\n streambuf::int_type streambuf::overflow(streambuf::int_type c)\n {\n if (pptr() != pbase())\n {\n int n = m_stream.Write(pbase(), pptr() - pbase());\n if (n <= 0)\n return traits_type::eof();\n }\n\n setp(m_buffer, m_buffer + m_bufsize);\n if (c != traits_type::eof())\n {\n *pptr() = (char_type)c;\n pbump(1);\n }\n\n return 0;\n }\n\n streambuf::int_type streambuf::underflow()\n {\n Stream::size_type n = m_stream.Read(m_buffer, m_bufsize);\n if (n <= 0)\n return traits_type::eof();\n\n setg(m_buffer, m_buffer, m_buffer + n);\n return (int_type)(unsigned char)m_buffer[0];\n }\n\n int streambuf::sync()\n {\n if (pptr() != pbase())\n {\n int n = m_stream.Write(pbase(), pptr() - pbase());\n if (n <= 0)\n return -1;\n else\n setp(m_buffer, m_buffer + m_bufsize);\n }\n return 0;\n }\n\n} \/\/ namespace tcp\n\n} \/\/ namespace cxxtools\n<commit_msg>simplified Write-method<commit_after>\/* tcpstream.cpp\n Copyright (C) 2003-2005 Tommi Maekitalo\n\nThis file is part of cxxtools.\n\nCxxtools is free software; you can redistribute it and\/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation; either version 2 of the License, or\n(at your option) any later version.\n\nCxxtools is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License\nalong with Cxxtools; if not, write to the Free Software\nFoundation, Inc., 59 Temple Place, Suite 330,\nBoston, MA 02111-1307 USA\n*\/\n\n#include \"cxxtools\/tcpstream.h\"\n#include <stdexcept>\n#include <sys\/types.h>\n#include <sys\/socket.h>\n#include <unistd.h>\n#include <netinet\/in.h>\n#include <arpa\/inet.h>\n#include <fcntl.h>\n#include <sys\/poll.h>\n#include <errno.h>\n#include <netdb.h>\n\n#undef log_warn\n#undef log_debug\n\n#define log_warn(expr)\n#define log_debug(expr)\n\/\/#define log_warn(expr) do { std::cerr << \"WARN: \" << expr << std::endl; } while(false)\n\/\/#define log_debug(expr) do { std::cerr << \"DEBUG: \" << expr << std::endl; } while(false)\n\nnamespace cxxtools\n{\n\nnamespace tcp\n{\n using namespace std;\n\n Exception::Exception(int Errno, const string& msg)\n : runtime_error(msg + \": \" + strerror(Errno)),\n m_Errno(Errno)\n { }\n\n Exception::Exception(const string& msg)\n : runtime_error(msg + \": \" + strerror(errno)),\n m_Errno(errno)\n { }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ implementation of Socket\n \/\/\n Socket::Socket(int domain, int type, int protocol) throw (Exception)\n : m_timeout(-1)\n {\n if ((m_sockFd = ::socket(domain, type, protocol)) < 0)\n throw Exception(\"cannot create socket\");\n }\n\n Socket::~Socket()\n {\n if (m_sockFd >= 0)\n {\n if (::close(m_sockFd) < 0)\n fprintf(stderr, \"error in close(%d)\\n\", (int)m_sockFd);\n }\n }\n\n void Socket::create(int domain, int type, int protocol) throw (Exception)\n {\n close();\n\n if ((m_sockFd = ::socket(domain, type, protocol)) < 0)\n throw Exception(\"cannot create socket\");\n }\n\n void Socket::close()\n {\n if (m_sockFd >= 0)\n {\n ::close(m_sockFd);\n m_sockFd = -1;\n }\n }\n\n struct sockaddr Socket::getSockAddr() const throw (Exception)\n {\n struct sockaddr ret;\n\n socklen_t slen = sizeof(ret);\n if (::getsockname(getFd(), &ret, &slen) < 0)\n throw Exception(\"error in getsockname\");\n\n return ret;\n }\n\n void Socket::setTimeout(int t)\n {\n m_timeout = t;\n\n if (getFd() >= 0)\n {\n long a = m_timeout >= 0 ? O_NONBLOCK : 0;\n log_debug(\"fcntl(\" << getFd() << \", F_SETFL, \" << a << ')');\n fcntl(getFd(), F_SETFL, a);\n }\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ implementation of Server\n \/\/\n Server::Server()\n : Socket(AF_INET, SOCK_STREAM, 0)\n { }\n\n Server::Server(const std::string& ipaddr, unsigned short int port, int backlog)\n throw (Exception)\n : Socket(AF_INET, SOCK_STREAM, 0)\n {\n Listen(ipaddr, port, backlog);\n }\n\n Server::Server(const char* ipaddr, unsigned short int port,\n int backlog) throw (Exception)\n : Socket(AF_INET, SOCK_STREAM, 0)\n {\n Listen(ipaddr, port, backlog);\n }\n\n void Server::Listen(const char* ipaddr, unsigned short int port,\n int backlog) throw (Exception)\n {\n struct hostent* host = ::gethostbyname(ipaddr);\n if (host == 0)\n throw Exception(std::string(\"invalid ipaddress \") + ipaddr);\n\n memset(&servaddr.sockaddr_in, 0, sizeof(servaddr.sockaddr_in));\n\n servaddr.sockaddr_in.sin_family = AF_INET;\n servaddr.sockaddr_in.sin_port = htons(port);\n\n memmove(&(servaddr.sockaddr_in.sin_addr.s_addr), host->h_addr, host->h_length);\n int reuseAddr = 1;\n if (::setsockopt(getFd(), SOL_SOCKET, SO_REUSEADDR,\n &reuseAddr, sizeof(reuseAddr)) < 0)\n throw Exception(\"error in setsockopt\");\n\n if (::bind(getFd(),\n (struct sockaddr *)&servaddr.sockaddr_in,\n sizeof(servaddr.sockaddr_in)) < 0)\n throw Exception(\"error in bind\");\n\n if (::listen(getFd(), backlog) < 0)\n throw Exception(\"error in listen\");\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ implementation of Stream\n \/\/\n Stream::Stream()\n { }\n\n Stream::Stream(const Server& server)\n {\n Accept(server);\n }\n\n Stream::Stream(const string& ipaddr, unsigned short int port)\n : Socket(AF_INET, SOCK_STREAM, 0)\n {\n Connect(ipaddr, port);\n }\n\n Stream::Stream(const char* ipaddr, unsigned short int port)\n : Socket(AF_INET, SOCK_STREAM, 0)\n {\n Connect(ipaddr, port);\n }\n\n void Stream::Accept(const Server& server)\n {\n close();\n\n socklen_t peeraddr_len;\n peeraddr_len = sizeof(peeraddr);\n setFd(accept(server.getFd(), &peeraddr.sockaddr, &peeraddr_len));\n if (bad())\n throw Exception(\"error in accept\");\n\n setTimeout(getTimeout());\n }\n\n void Stream::Connect(const char* ipaddr, unsigned short int port)\n {\n if (getFd() < 0)\n create(AF_INET, SOCK_STREAM, 0);\n\n struct hostent* host = ::gethostbyname(ipaddr);\n if (host == 0)\n throw Exception(std::string(\"invalid ipaddress \") + ipaddr);\n\n memset(&peeraddr, 0, sizeof(peeraddr));\n peeraddr.sockaddr_in.sin_family = AF_INET;\n peeraddr.sockaddr_in.sin_port = htons(port);\n\n memmove(&(peeraddr.sockaddr_in.sin_addr.s_addr), host->h_addr, host->h_length);\n\n if (::connect(getFd(), &peeraddr.sockaddr,\n sizeof(peeraddr)) < 0)\n throw Exception(\"error in connect\");\n\n setTimeout(getTimeout());\n }\n\n Stream::size_type Stream::Read(char* buffer, Stream::size_type bufsize) const\n {\n ssize_t n;\n\n if (getTimeout() < 0)\n {\n \/\/ blocking read\n log_debug(\"blocking read\");\n n = ::read(getFd(), buffer, bufsize);\n log_debug(\"blocking read ready, return \" << n);\n if (n < 0)\n {\n int errnum = errno;\n throw Exception(strerror(errnum));\n }\n }\n else\n {\n \/\/ non-blocking read\n\n \/\/ try reading without timeout\n log_debug(\"non blocking read fd=\" << getFd());\n n = ::read(getFd(), buffer, bufsize);\n log_debug(\"non blocking read returns \" << n);\n\n if (n < 0)\n {\n \/\/ no data available\n\n if (errno == EAGAIN)\n {\n if (getTimeout() == 0)\n {\n log_warn(\"timeout\");\n throw Timeout();\n }\n\n struct pollfd fds;\n fds.fd = getFd();\n fds.events = POLLIN;\n log_debug(\"poll timeout \" << getTimeout());\n int p = poll(&fds, 1, getTimeout());\n log_debug(\"poll returns \" << p);\n if (p < 0)\n {\n int errnum = errno;\n throw Exception(strerror(errnum));\n }\n else if (p == 0)\n throw Timeout();\n\n log_debug(\"read\");\n n = ::read(getFd(), buffer, bufsize);\n log_debug(\"read returns \" << n);\n }\n else\n {\n int errnum = errno;\n throw Exception(strerror(errnum));\n }\n }\n\n }\n\n return n;\n }\n\n Stream::size_type Stream::Write(const char* buffer,\n Stream::size_type bufsize) const\n {\n size_t n = 0;\n size_type s = bufsize;\n\n while (n < s)\n {\n n = ::write(getFd(), buffer, s);\n if (n <= 0)\n \/\/ au weia - das ging schief\n throw Exception(\"tcp::Stream: error in write\");\n\n buffer += n;\n s -= n;\n\n if (s == 0)\n break;\n\n struct pollfd fds;\n fds.fd = getFd();\n fds.events = POLLOUT;\n int p = poll(&fds, 1, -1);\n\n if (p < 0)\n {\n int errnum = errno;\n throw Exception(strerror(errnum));\n }\n else if (p == 0)\n throw Timeout();\n }\n\n return bufsize;\n }\n\n streambuf::streambuf(Stream& stream, unsigned bufsize, int timeout)\n : m_stream(stream),\n m_bufsize(bufsize),\n m_buffer(new char_type[bufsize])\n {\n setTimeout(timeout);\n }\n\n streambuf::int_type streambuf::overflow(streambuf::int_type c)\n {\n if (pptr() != pbase())\n {\n int n = m_stream.Write(pbase(), pptr() - pbase());\n if (n <= 0)\n return traits_type::eof();\n }\n\n setp(m_buffer, m_buffer + m_bufsize);\n if (c != traits_type::eof())\n {\n *pptr() = (char_type)c;\n pbump(1);\n }\n\n return 0;\n }\n\n streambuf::int_type streambuf::underflow()\n {\n Stream::size_type n = m_stream.Read(m_buffer, m_bufsize);\n if (n <= 0)\n return traits_type::eof();\n\n setg(m_buffer, m_buffer, m_buffer + n);\n return (int_type)(unsigned char)m_buffer[0];\n }\n\n int streambuf::sync()\n {\n if (pptr() != pbase())\n {\n int n = m_stream.Write(pbase(), pptr() - pbase());\n if (n <= 0)\n return -1;\n else\n setp(m_buffer, m_buffer + m_bufsize);\n }\n return 0;\n }\n\n} \/\/ namespace tcp\n\n} \/\/ namespace cxxtools\n<|endoftext|>"} {"text":"<commit_before>#include <functional>\n#include <iostream>\n#include <fstream>\n#include <queue>\n#include <tuple>\n#include <vector>\n\n#include <libfuzzymatch\/levenshteinLimit.h>\n#include <libfuzzymatch\/util.h>\n\n#include \"..\/common\/pairwise.h\"\n#include \"..\/common\/plain_index.h\"\n#include \"..\/common\/timer.h\"\n\nint main(int argc, char *argv[]) {\n if (argc != 4) {\n std::cerr << \"Usage: \\n\\t query-index <index> <query-file> <threshold>\" << std::endl;\n exit(EXIT_FAILURE);\n }\n\n std::vector<std::string> queries;\n std::ifstream file(argv[2]);\n for (std::string line; std::getline(file, line);) {\n queries.push_back(line);\n }\n file.close();\n\n std::vector<std::vector<uint32_t>> index;\n loadIndex(argv[1], index);\n\n const uint32_t threshold(atoi(argv[3]));\n\n Timer timer;\n\n benchLevenshtein(queries, index, [=](const std::vector<uint32_t> &s, const std::vector<uint32_t> &t) {\n return levenshteinLimit(s, t, threshold);\n });\n std::cout << \"Took \" << timer.getAndReset() << \"s to execute the queries.\" << std::endl;\n std::cout << \"RESULT algo=limit threshold=\" << threshold << \" index=\" << argv[1] << \" queries=\" << argv[2] << std::endl;\n}\n<commit_msg>print time in limited levenshtein benchmark<commit_after>#include <functional>\n#include <iostream>\n#include <fstream>\n#include <queue>\n#include <tuple>\n#include <vector>\n\n#include <libfuzzymatch\/levenshteinLimit.h>\n#include <libfuzzymatch\/util.h>\n\n#include \"..\/common\/pairwise.h\"\n#include \"..\/common\/plain_index.h\"\n#include \"..\/common\/timer.h\"\n\nint main(int argc, char *argv[]) {\n if (argc != 4) {\n std::cerr << \"Usage: \\n\\t query-index <index> <query-file> <threshold>\" << std::endl;\n exit(EXIT_FAILURE);\n }\n\n std::vector<std::string> queries;\n std::ifstream file(argv[2]);\n for (std::string line; std::getline(file, line);) {\n queries.push_back(line);\n }\n file.close();\n\n std::vector<std::vector<uint32_t>> index;\n loadIndex(argv[1], index);\n\n const uint32_t threshold(atoi(argv[3]));\n\n Timer timer;\n\n benchLevenshtein(queries, index, [=](const std::vector<uint32_t> &s, const std::vector<uint32_t> &t) {\n return levenshteinLimit(s, t, threshold);\n });\n auto t = timer.get();\n std::cout << \"Took \" << t << \"s to execute the queries.\" << std::endl;\n std::cout << \"RESULT algo=limit threshold=\" << threshold << \" index=\" << argv[1] << \" queries=\" << argv[2] << \" time=\" << t << std::endl;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\/\/\n\n#include \"base\/logging.h\"\n#include \"base\/time.h\"\n#include \"testing\/gtest\/include\/gtest\/gtest.h\"\n#include \"chrome\/browser\/safe_browsing\/protocol_manager.h\"\n\n\n\/\/ Ensure that we respect section 5 of the SafeBrowsing protocol specification.\nTEST(SafeBrowsingProtocolManagerTest, TestBackOffTimes) {\n SafeBrowsingProtocolManager pm(NULL, NULL, \"\", \"\");\n pm.next_update_sec_ = 1800;\n DCHECK(pm.back_off_fuzz_ >= 0.0 && pm.back_off_fuzz_ <= 1.0);\n\n \/\/ No errors received so far.\n EXPECT_EQ(pm.GetNextUpdateTime(false), 1800 * 1000);\n\n \/\/ 1 error.\n EXPECT_EQ(pm.GetNextUpdateTime(true), 60 * 1000);\n\n \/\/ 2 errors.\n int next_time = pm.GetNextUpdateTime(true) \/ (60 * 1000); \/\/ Minutes\n EXPECT_TRUE(next_time >= 30 && next_time <= 60);\n\n \/\/ 3 errors.\n next_time = pm.GetNextUpdateTime(true) \/ (60 * 1000);\n EXPECT_TRUE(next_time >= 60 && next_time <= 120);\n\n \/\/ 4 errors.\n next_time = pm.GetNextUpdateTime(true) \/ (60 * 1000);\n EXPECT_TRUE(next_time >= 120 && next_time <= 240);\n\n \/\/ 5 errors.\n next_time = pm.GetNextUpdateTime(true) \/ (60 * 1000);\n EXPECT_TRUE(next_time >= 240 && next_time <= 480);\n\n \/\/ 6 errors, reached max backoff.\n EXPECT_EQ(pm.GetNextUpdateTime(true), 480 * 60 * 1000);\n\n \/\/ 7 errors.\n EXPECT_EQ(pm.GetNextUpdateTime(true), 480 * 60 * 1000);\n\n \/\/ Received a successful response.\n EXPECT_EQ(pm.GetNextUpdateTime(false), 1800 * 1000);\n}\n\n\/\/ Test string combinations with and without MAC.\nTEST(SafeBrowsingProtocolManagerTest, TestChunkStrings) {\n SafeBrowsingProtocolManager pm(NULL, NULL, \"\", \"\");\n\n \/\/ Add and Sub chunks.\n SBListChunkRanges phish(\"goog-phish-shavar\");\n phish.adds = \"1,4,6,8-20,99\";\n phish.subs = \"16,32,64-96\";\n EXPECT_EQ(pm.FormatList(phish, false),\n \"goog-phish-shavar;a:1,4,6,8-20,99:s:16,32,64-96\\n\");\n EXPECT_EQ(pm.FormatList(phish, true),\n \"goog-phish-shavar;a:1,4,6,8-20,99:s:16,32,64-96:mac\\n\");\n\n \/\/ Add chunks only.\n phish.subs = \"\";\n EXPECT_EQ(pm.FormatList(phish, false),\n \"goog-phish-shavar;a:1,4,6,8-20,99\\n\");\n EXPECT_EQ(pm.FormatList(phish, true),\n \"goog-phish-shavar;a:1,4,6,8-20,99:mac\\n\");\n\n \/\/ Sub chunks only.\n phish.adds = \"\";\n phish.subs = \"16,32,64-96\";\n EXPECT_EQ(pm.FormatList(phish, false), \"goog-phish-shavar;s:16,32,64-96\\n\");\n EXPECT_EQ(pm.FormatList(phish, true), \"goog-phish-shavar;s:16,32,64-96:mac\\n\");\n\n \/\/ No chunks of either type.\n phish.adds = \"\";\n phish.subs = \"\";\n EXPECT_EQ(pm.FormatList(phish, false), \"goog-phish-shavar;\\n\");\n EXPECT_EQ(pm.FormatList(phish, true), \"goog-phish-shavar;mac\\n\");\n}\n\nTEST(SafeBrowsingProtocolManagerTest, TestGetHashBackOffTimes) {\n SafeBrowsingProtocolManager pm(NULL, NULL, \"\", \"\");\n\n \/\/ No errors or back off time yet.\n EXPECT_EQ(pm.gethash_error_count_, 0);\n EXPECT_TRUE(pm.next_gethash_time_.is_null());\n\n Time now = Time::Now();\n\n \/\/ 1 error.\n pm.HandleGetHashError();\n EXPECT_EQ(pm.gethash_error_count_, 1);\n TimeDelta margin = TimeDelta::FromSeconds(5); \/\/ Fudge factor.\n Time future = now + TimeDelta::FromMinutes(1);\n EXPECT_TRUE(pm.next_gethash_time_ >= future - margin &&\n pm.next_gethash_time_ <= future + margin);\n\n \/\/ 2 errors.\n pm.HandleGetHashError();\n EXPECT_EQ(pm.gethash_error_count_, 2);\n EXPECT_TRUE(pm.next_gethash_time_ >= now + TimeDelta::FromMinutes(30));\n EXPECT_TRUE(pm.next_gethash_time_ <= now + TimeDelta::FromMinutes(60));\n\n \/\/ 3 errors.\n pm.HandleGetHashError();\n EXPECT_EQ(pm.gethash_error_count_, 3);\n EXPECT_TRUE(pm.next_gethash_time_ >= now + TimeDelta::FromMinutes(60));\n EXPECT_TRUE(pm.next_gethash_time_ <= now + TimeDelta::FromMinutes(120));\n\n \/\/ 4 errors.\n pm.HandleGetHashError();\n EXPECT_EQ(pm.gethash_error_count_, 4);\n EXPECT_TRUE(pm.next_gethash_time_ >= now + TimeDelta::FromMinutes(120));\n EXPECT_TRUE(pm.next_gethash_time_ <= now + TimeDelta::FromMinutes(240));\n\n \/\/ 5 errors.\n pm.HandleGetHashError();\n EXPECT_EQ(pm.gethash_error_count_, 5);\n EXPECT_TRUE(pm.next_gethash_time_ >= now + TimeDelta::FromMinutes(240));\n EXPECT_TRUE(pm.next_gethash_time_ <= now + TimeDelta::FromMinutes(480));\n\n \/\/ 6 errors, reached max backoff.\n pm.HandleGetHashError();\n EXPECT_EQ(pm.gethash_error_count_, 6);\n EXPECT_TRUE(pm.next_gethash_time_ == now + TimeDelta::FromMinutes(480));\n\n \/\/ 7 errors.\n pm.HandleGetHashError();\n EXPECT_EQ(pm.gethash_error_count_, 7);\n EXPECT_TRUE(pm.next_gethash_time_== now + TimeDelta::FromMinutes(480));\n}\n\n<commit_msg>Disable a flakey test. BUG=http:\/\/code.google.com\/p\/chromium\/issues\/detail?id=1880 Review URL: http:\/\/codereview.chromium.org\/1816<commit_after>\/\/ Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\/\/\n\n#include \"base\/logging.h\"\n#include \"base\/time.h\"\n#include \"testing\/gtest\/include\/gtest\/gtest.h\"\n#include \"chrome\/browser\/safe_browsing\/protocol_manager.h\"\n\n\n\/\/ Ensure that we respect section 5 of the SafeBrowsing protocol specification.\nTEST(SafeBrowsingProtocolManagerTest, TestBackOffTimes) {\n SafeBrowsingProtocolManager pm(NULL, NULL, \"\", \"\");\n pm.next_update_sec_ = 1800;\n DCHECK(pm.back_off_fuzz_ >= 0.0 && pm.back_off_fuzz_ <= 1.0);\n\n \/\/ No errors received so far.\n EXPECT_EQ(pm.GetNextUpdateTime(false), 1800 * 1000);\n\n \/\/ 1 error.\n EXPECT_EQ(pm.GetNextUpdateTime(true), 60 * 1000);\n\n \/\/ 2 errors.\n int next_time = pm.GetNextUpdateTime(true) \/ (60 * 1000); \/\/ Minutes\n EXPECT_TRUE(next_time >= 30 && next_time <= 60);\n\n \/\/ 3 errors.\n next_time = pm.GetNextUpdateTime(true) \/ (60 * 1000);\n EXPECT_TRUE(next_time >= 60 && next_time <= 120);\n\n \/\/ 4 errors.\n next_time = pm.GetNextUpdateTime(true) \/ (60 * 1000);\n EXPECT_TRUE(next_time >= 120 && next_time <= 240);\n\n \/\/ 5 errors.\n next_time = pm.GetNextUpdateTime(true) \/ (60 * 1000);\n EXPECT_TRUE(next_time >= 240 && next_time <= 480);\n\n \/\/ 6 errors, reached max backoff.\n EXPECT_EQ(pm.GetNextUpdateTime(true), 480 * 60 * 1000);\n\n \/\/ 7 errors.\n EXPECT_EQ(pm.GetNextUpdateTime(true), 480 * 60 * 1000);\n\n \/\/ Received a successful response.\n EXPECT_EQ(pm.GetNextUpdateTime(false), 1800 * 1000);\n}\n\n\/\/ Test string combinations with and without MAC.\nTEST(SafeBrowsingProtocolManagerTest, TestChunkStrings) {\n SafeBrowsingProtocolManager pm(NULL, NULL, \"\", \"\");\n\n \/\/ Add and Sub chunks.\n SBListChunkRanges phish(\"goog-phish-shavar\");\n phish.adds = \"1,4,6,8-20,99\";\n phish.subs = \"16,32,64-96\";\n EXPECT_EQ(pm.FormatList(phish, false),\n \"goog-phish-shavar;a:1,4,6,8-20,99:s:16,32,64-96\\n\");\n EXPECT_EQ(pm.FormatList(phish, true),\n \"goog-phish-shavar;a:1,4,6,8-20,99:s:16,32,64-96:mac\\n\");\n\n \/\/ Add chunks only.\n phish.subs = \"\";\n EXPECT_EQ(pm.FormatList(phish, false),\n \"goog-phish-shavar;a:1,4,6,8-20,99\\n\");\n EXPECT_EQ(pm.FormatList(phish, true),\n \"goog-phish-shavar;a:1,4,6,8-20,99:mac\\n\");\n\n \/\/ Sub chunks only.\n phish.adds = \"\";\n phish.subs = \"16,32,64-96\";\n EXPECT_EQ(pm.FormatList(phish, false), \"goog-phish-shavar;s:16,32,64-96\\n\");\n EXPECT_EQ(pm.FormatList(phish, true), \"goog-phish-shavar;s:16,32,64-96:mac\\n\");\n\n \/\/ No chunks of either type.\n phish.adds = \"\";\n phish.subs = \"\";\n EXPECT_EQ(pm.FormatList(phish, false), \"goog-phish-shavar;\\n\");\n EXPECT_EQ(pm.FormatList(phish, true), \"goog-phish-shavar;mac\\n\");\n}\n\n\/\/ Flakey, see http:\/\/code.google.com\/p\/chromium\/issues\/detail?id=1880\nTEST(SafeBrowsingProtocolManagerTest, DISABLED_TestGetHashBackOffTimes) {\n SafeBrowsingProtocolManager pm(NULL, NULL, \"\", \"\");\n\n \/\/ No errors or back off time yet.\n EXPECT_EQ(pm.gethash_error_count_, 0);\n EXPECT_TRUE(pm.next_gethash_time_.is_null());\n\n Time now = Time::Now();\n\n \/\/ 1 error.\n pm.HandleGetHashError();\n EXPECT_EQ(pm.gethash_error_count_, 1);\n TimeDelta margin = TimeDelta::FromSeconds(5); \/\/ Fudge factor.\n Time future = now + TimeDelta::FromMinutes(1);\n EXPECT_TRUE(pm.next_gethash_time_ >= future - margin &&\n pm.next_gethash_time_ <= future + margin);\n\n \/\/ 2 errors.\n pm.HandleGetHashError();\n EXPECT_EQ(pm.gethash_error_count_, 2);\n EXPECT_TRUE(pm.next_gethash_time_ >= now + TimeDelta::FromMinutes(30));\n EXPECT_TRUE(pm.next_gethash_time_ <= now + TimeDelta::FromMinutes(60));\n\n \/\/ 3 errors.\n pm.HandleGetHashError();\n EXPECT_EQ(pm.gethash_error_count_, 3);\n EXPECT_TRUE(pm.next_gethash_time_ >= now + TimeDelta::FromMinutes(60));\n EXPECT_TRUE(pm.next_gethash_time_ <= now + TimeDelta::FromMinutes(120));\n\n \/\/ 4 errors.\n pm.HandleGetHashError();\n EXPECT_EQ(pm.gethash_error_count_, 4);\n EXPECT_TRUE(pm.next_gethash_time_ >= now + TimeDelta::FromMinutes(120));\n EXPECT_TRUE(pm.next_gethash_time_ <= now + TimeDelta::FromMinutes(240));\n\n \/\/ 5 errors.\n pm.HandleGetHashError();\n EXPECT_EQ(pm.gethash_error_count_, 5);\n EXPECT_TRUE(pm.next_gethash_time_ >= now + TimeDelta::FromMinutes(240));\n EXPECT_TRUE(pm.next_gethash_time_ <= now + TimeDelta::FromMinutes(480));\n\n \/\/ 6 errors, reached max backoff.\n pm.HandleGetHashError();\n EXPECT_EQ(pm.gethash_error_count_, 6);\n EXPECT_TRUE(pm.next_gethash_time_ == now + TimeDelta::FromMinutes(480));\n\n \/\/ 7 errors.\n pm.HandleGetHashError();\n EXPECT_EQ(pm.gethash_error_count_, 7);\n EXPECT_TRUE(pm.next_gethash_time_== now + TimeDelta::FromMinutes(480));\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"mainwindow.h\"\n#include \"ui_mainwindow.h\"\n#include \"assetbrowser.h\"\n#include \"editor\/entity_template_system.h\"\n#include \"editor\/world_editor.h\"\n#include \"engine\/engine.h\"\n#include \"entity_list.h\"\n#include \"entity_template_list.h\"\n#include \"fileserverwidget.h\"\n#include \"gameview.h\"\n#include \"log_widget.h\"\n#include \"notifications.h\"\n#include \"property_view.h\"\n#include \"sceneview.h\"\n#include \"scripts\/scriptcompilerwidget.h\"\n#include \"profilerui.h\"\n#include <qcombobox.h>\n#include <qdir.h>\n#include <qevent.h>\n#include <qfiledialog.h>\n#include <qinputdialog.h>\n#include <qlabel.h>\n#include <qsettings.h>\n\n\nMainWindow::MainWindow(QWidget* parent) :\n\tQMainWindow(parent),\n\tm_ui(new Ui::MainWindow)\n{\n\tm_ui->setupUi(this);\n\tm_ui->centralWidget->hide();\n\tsetDockOptions(AllowNestedDocks | AnimatedDocks | AllowTabbedDocks);\n\n\tm_log = new LogWidget;\n\tm_property_view = new PropertyView;\n\tm_scene_view = new SceneView;\n\tm_game_view = new GameView;\n\tm_asset_browser = new AssetBrowser;\n\tm_script_compiler_ui = new ScriptCompilerWidget;\n\tm_file_server_ui = new FileServerWidget;\n\tm_profiler_ui = new ProfilerUI;\n\tm_entity_template_list_ui = new EntityTemplateList;\n\tm_notifications = Notifications::create(*this);\n\tm_entity_list = new EntityList(NULL);\n\n\tQSettings settings(\"Lumix\", \"QtEditor\");\n\tbool geometry_restored = restoreGeometry(settings.value(\"mainWindowGeometry\").toByteArray());\n\t\n\tm_window_menu = new QMenu(\"Windows\", m_ui->menuView);\n\tm_ui->menuView->addMenu(m_window_menu);\n\tm_window_menu->connect(m_window_menu, &QMenu::aboutToShow, [this]()\n\t{\n\t\tfor (auto info : m_dock_infos)\n\t\t{\n\t\t\tinfo.m_action->setChecked(info.m_widget->isVisible());\n\t\t}\n\t});\n\taddEditorDock(static_cast<Qt::DockWidgetArea>(2), m_asset_browser, &MainWindow::on_actionAsset_Browser_triggered);\n\taddEditorDock(static_cast<Qt::DockWidgetArea>(2), m_entity_list, &MainWindow::on_actionEntity_list_triggered);\n\taddEditorDock(static_cast<Qt::DockWidgetArea>(2), m_entity_template_list_ui, &MainWindow::on_actionEntity_templates_triggered);\n\taddEditorDock(static_cast<Qt::DockWidgetArea>(8), m_file_server_ui, &MainWindow::on_actionFile_server_triggered);\n\taddEditorDock(static_cast<Qt::DockWidgetArea>(1), m_game_view, &MainWindow::on_actionGame_view_triggered);\n\taddEditorDock(static_cast<Qt::DockWidgetArea>(8), m_log, &MainWindow::on_actionLog_triggered);\n\taddEditorDock(static_cast<Qt::DockWidgetArea>(1), m_profiler_ui, &MainWindow::on_actionProfiler_triggered);\n\taddEditorDock(static_cast<Qt::DockWidgetArea>(1), m_property_view, &MainWindow::on_actionProperties_triggered);\n\taddEditorDock(static_cast<Qt::DockWidgetArea>(2), m_scene_view, &MainWindow::on_actionScene_View_triggered);\n\taddEditorDock(static_cast<Qt::DockWidgetArea>(8), m_script_compiler_ui, &MainWindow::on_actionScript_compiler_triggered);\n\n\tcreateLayoutCombobox();\n\n\tm_property_view->setScriptCompiler(m_script_compiler_ui->getCompiler());\n\tm_property_view->setAssetBrowser(*m_asset_browser);\n\tm_property_view->setEntityTemplateList(m_entity_template_list_ui);\n\n\tint size = settings.beginReadArray(\"recent_files\");\n\tfor (int i = 0; i < size; ++i)\n\t{\n\t\tsettings.setArrayIndex(i);\n\t\tm_recent_files.push_back(settings.value(\"filename\").toString());\n\t}\n\tsettings.endArray();\n\tm_recent_files_menu = new QMenu(m_ui->menuFile);\n\tm_recent_files_menu->setTitle(\"Recent Files\");\n\tm_ui->menuFile->insertMenu(m_ui->actionSave, m_recent_files_menu);\n\tm_recent_files_menu->connect(m_recent_files_menu, &QMenu::triggered, [this](QAction* action)\n\t{\n\t\tauto path = action->text().toLatin1();\n\t\tm_world_editor->loadUniverse(path.data());\n\t});\n\tfillRecentFiles();\n\n\tgeometry_restored = geometry_restored && restoreState(settings.value(\"mainWindowState\").toByteArray());\n\tif (!geometry_restored)\n\t{\n\t\tQFile file(\"editor\/layouts\/main.bin\");\n\t\tif (file.open(QIODevice::ReadWrite))\n\t\t{\n\t\t\tint size;\n\t\t\tfile.read((char*)&size, sizeof(size));\n\t\t\tQByteArray geom = file.read(size);\n\t\t\trestoreGeometry(geom);\n\t\t\tfile.read((char*)&size, sizeof(size));\n\t\t\tQByteArray state = file.read(size);\n\t\t\trestoreState(state);\n\t\t}\n\t}\n}\n\n\nvoid MainWindow::createLayoutCombobox()\n{\n\tm_layout_combobox = new QComboBox();\n\tQWidget* widget = new QWidget(m_ui->menuBar);\n\tQHBoxLayout* layout = new QHBoxLayout(widget);\n\tQLabel* label = new QLabel(\"Layout\");\n\tlayout->setContentsMargins(0, 0, 0, 0);\n\tlayout->addWidget(label);\n\tlayout->addWidget(m_layout_combobox);\n\tm_ui->menuBar->setCornerWidget(widget);\n\tQDir dir(\"editor\/layouts\/\");\n\tauto files = dir.entryInfoList();\n\tfor (auto file : files)\n\t{\n\t\tif (file.baseName() != \"\")\n\t\t{\n\t\t\tm_layout_combobox->addItem(file.baseName());\n\t\t}\n\t}\n\tconnect(m_layout_combobox, &QComboBox::currentTextChanged, [this](const QString & text)\n\t{\n\t\tQFile file(QString(\"editor\/layouts\/%1.bin\").arg(text));\n\t\tif (file.open(QIODevice::ReadWrite))\n\t\t{\n\t\t\tint size;\n\t\t\tfile.read((char*)&size, sizeof(size));\n\t\t\tQByteArray geom = file.read(size);\n\t\t\trestoreGeometry(geom);\n\t\t\tfile.read((char*)&size, sizeof(size));\n\t\t\tQByteArray state = file.read(size);\n\t\t\trestoreState(state);\n\t\t}\n\t});;\n}\n\n\nvoid MainWindow::addEditorDock(Qt::DockWidgetArea area, QDockWidget* widget, void (MainWindow::*callback)())\n{\n\tDockInfo info;\n\tinfo.m_widget = widget;\n\tQAction* action = new QAction(widget->windowTitle(), m_window_menu);\n\taction->setCheckable(true);\n\tm_window_menu->addAction(action);\n\tinfo.m_action = action;\n\taction->connect(action, &QAction::triggered, this, callback);\n\tm_dock_infos.push_back(info);\n\taddDockWidget(area, widget);\n}\n\n\nvoid MainWindow::fillRecentFiles()\n{\n\tm_recent_files_menu->clear();\n\tfor (auto file : m_recent_files)\n\t{\n\t\tm_recent_files_menu->addAction(file);\n\t}\n}\n\n\nvoid MainWindow::resizeEvent(QResizeEvent* event)\n{\n\tm_resized.invoke(event->size());\n}\n\n\nvoid MainWindow::update()\n{\n\tm_notifications->update(m_world_editor->getEngine().getLastTimeDelta());\n}\n\n\nvoid MainWindow::closeEvent(QCloseEvent *event)\n{\n\tQSettings settings(\"Lumix\", \"QtEditor\");\n\tsettings.setValue(\"mainWindowGeometry\", saveGeometry());\n\tsettings.setValue(\"mainWindowState\", saveState());\n\tsettings.beginWriteArray(\"recent_files\");\n\tint i = 0;\n\tfor (auto file : m_recent_files)\n\t{\n\t\tsettings.setArrayIndex(i);\n\t\tsettings.setValue(\"filename\", file);\n\t\t++i;\n\t}\n\tsettings.endArray();\n\tQMainWindow::closeEvent(event);\n}\n\nMainWindow::~MainWindow()\n{\n\tdelete m_log;\n\tdelete m_ui;\n\tdelete m_scene_view;\n\tdelete m_property_view;\n\tdelete m_game_view;\n\tdelete m_asset_browser;\n\tdelete m_script_compiler_ui;\n\tdelete m_file_server_ui;\n\tdelete m_profiler_ui;\n\tdelete m_entity_template_list_ui;\n\tNotifications::destroy(m_notifications);\n}\n\n\nvoid MainWindow::setWorldEditor(Lumix::WorldEditor& editor)\n{\n\tm_world_editor = &editor;\n\tm_file_server_ui->setWorldEditor(editor);\n\tm_asset_browser->setWorldEditor(editor);\n\tm_property_view->setWorldEditor(editor);\n\tm_entity_template_list_ui->setWorldEditor(editor);\n\tm_game_view->setWorldEditor(editor);\n\tm_entity_list->setWorldEditor(editor);\n\n\tm_world_editor->universeLoaded().bind<MainWindow, &MainWindow::onUniverseLoaded>(this);\n}\n\nvoid MainWindow::onUniverseLoaded()\n{\n\tconst char* path = m_world_editor->getUniversePath().c_str();\n\t\n\tif (m_recent_files.indexOf(path, 0) < 0)\n\t{\n\t\tm_recent_files.push_back(path);\n\t\tif (m_recent_files.size() > 6)\n\t\t{\n\t\t\tm_recent_files.pop_front();\n\t\t}\n\t\tfillRecentFiles();\n\t}\n}\n\nGameView* MainWindow::getGameView() const\n{\n\treturn m_game_view;\n}\n\n\nSceneView* MainWindow::getSceneView() const\n{\n\treturn m_scene_view;\n}\n\n\nvoid MainWindow::on_actionLog_triggered()\n{\n\tm_log->show();\n}\n\n\nvoid MainWindow::on_actionOpen_triggered()\n{\n\tQString filename = QFileDialog::getOpenFileName(NULL, QString(), QString(), \"universe (*.unv)\");\n\tQByteArray path = filename.toLocal8Bit();\n\tif (!path.isEmpty())\n\t{\n\t\tm_world_editor->loadUniverse(path.data());\n\t}\n}\n\nvoid MainWindow::on_actionSave_As_triggered()\n{\n\tQByteArray path = QFileDialog::getSaveFileName().toLocal8Bit();\n\tif (!path.isEmpty())\n\t{\n\t\tm_world_editor->saveUniverse(path.data());\n\t}\n}\n\nvoid MainWindow::on_actionCreate_triggered()\n{\n\tm_world_editor->addEntity();\n}\n\nvoid MainWindow::on_actionProperties_triggered()\n{\n\tm_property_view->show();\n}\n\nvoid MainWindow::on_actionE_xit_triggered()\n{\n\tclose();\n}\n\nvoid MainWindow::on_actionGame_view_triggered()\n{\n\tm_game_view->show();\n}\n\nvoid MainWindow::on_actionScript_compiler_triggered()\n{\n\tm_script_compiler_ui->show();\n}\n\nvoid MainWindow::on_actionFile_server_triggered()\n{\n\tm_file_server_ui->show();\n}\n\nvoid MainWindow::on_actionAsset_Browser_triggered()\n{\n\tm_asset_browser->show();\n}\n\nvoid MainWindow::on_actionScene_View_triggered()\n{\n\tm_scene_view->show();\n}\n\nvoid MainWindow::on_actionProfiler_triggered()\n{\n\tm_profiler_ui->show();\n}\n\nvoid MainWindow::on_actionPolygon_Mode_changed()\n{\n\tm_world_editor->setWireframe(m_ui->actionPolygon_Mode->isChecked());\n}\n\nvoid MainWindow::on_actionGame_mode_triggered()\n{\n\tm_world_editor->toggleGameMode();\n}\n\nvoid MainWindow::on_actionLook_at_selected_entity_triggered()\n{\n\tm_world_editor->lookAtSelected();\n}\n\nvoid MainWindow::on_actionNew_triggered()\n{\n\tm_world_editor->newUniverse();\n}\n\nvoid MainWindow::on_actionSave_triggered()\n{\n\tif (m_world_editor->getUniversePath()[0] == '\\0')\n\t{\n\t\ton_actionSave_As_triggered();\n\t}\n\telse\n\t{\n\t\tm_world_editor->saveUniverse(m_world_editor->getUniversePath());\n\t}\n}\n\nvoid MainWindow::on_actionSnap_to_terrain_triggered()\n{\n\tm_world_editor->snapToTerrain();\n}\n\nvoid MainWindow::on_actionSave_as_template_triggered()\n{\n\tif (m_world_editor->getSelectedEntities().size() == 1)\n\t{\n\t\tbool ok = false;\n\t\tQString text = QInputDialog::getText(this, tr(\"Entity template\"), tr(\"Template name:\"), QLineEdit::Normal, tr(\"\"), &ok);\n\t\tif (ok)\n\t\t{\n\t\t\tm_world_editor->getEntityTemplateSystem().createTemplateFromEntity(text.toLatin1().data(), m_world_editor->getSelectedEntities()[0]);\n\t\t}\n\t}\n}\n\nvoid MainWindow::on_actionEntity_templates_triggered()\n{\n\tm_entity_template_list_ui->show();\n}\n\nvoid MainWindow::on_actionInstantiate_template_triggered()\n{\n\tm_entity_template_list_ui->instantiateTemplate();\n}\n\nvoid MainWindow::on_actionUndo_triggered()\n{\n\tm_world_editor->undo();\n}\n\nvoid MainWindow::on_actionRedo_triggered()\n{\n\tm_world_editor->redo();\n}\n\nvoid MainWindow::on_actionRemove_triggered()\n{\n\tif (!m_world_editor->getSelectedEntities().empty())\n\t{\n\t\tm_world_editor->destroyEntities(&m_world_editor->getSelectedEntities()[0], m_world_editor->getSelectedEntities().size());\n\t}\n}\n\nvoid MainWindow::on_actionEntity_list_triggered()\n{\n\tm_entity_list->show();\n}\n\nvoid MainWindow::on_actionMeasure_triggered()\n{\n\tm_world_editor->toggleMeasure();\n}\n\nvoid MainWindow::on_actionSave_Layout_triggered()\n{\n\tbool ok;\n\tQString text = QInputDialog::getText(this, \"Save layout\", \"Layout name:\", QLineEdit::Normal, \"\", &ok);\n\tif (ok && !text.isEmpty())\n\t{\n\t\tQFile file(QString(\"editor\/layouts\/%1.bin\").arg(text));\n\t\tif (file.open(QIODevice::ReadWrite))\n\t\t{\n\t\t\tauto geom = saveGeometry();\n\t\t\tauto state = saveState();\n\t\t\tint size = geom.size();\n\t\t\tfile.write((const char*)&size, sizeof(size));\n\t\t\tfile.write(geom);\n\t\t\tsize = state.size();\n\t\t\tfile.write((const char*)&size, sizeof(size));\n\t\t\tfile.write(state);\n\t\t\tbool item_exists = false;\n\t\t\tfor (int i = 0; i < m_layout_combobox->count(); ++i)\n\t\t\t{\n\t\t\t\tif (m_layout_combobox->itemText(i) == text)\n\t\t\t\t{\n\t\t\t\t\titem_exists = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (!item_exists)\n\t\t\t{\n\t\t\t\tm_layout_combobox->addItem(text);\n\t\t\t}\n\t\t}\n\t}\n}\n<commit_msg>reviewed code - missing reference added<commit_after>#include \"mainwindow.h\"\n#include \"ui_mainwindow.h\"\n#include \"assetbrowser.h\"\n#include \"editor\/entity_template_system.h\"\n#include \"editor\/world_editor.h\"\n#include \"engine\/engine.h\"\n#include \"entity_list.h\"\n#include \"entity_template_list.h\"\n#include \"fileserverwidget.h\"\n#include \"gameview.h\"\n#include \"log_widget.h\"\n#include \"notifications.h\"\n#include \"property_view.h\"\n#include \"sceneview.h\"\n#include \"scripts\/scriptcompilerwidget.h\"\n#include \"profilerui.h\"\n#include <qcombobox.h>\n#include <qdir.h>\n#include <qevent.h>\n#include <qfiledialog.h>\n#include <qinputdialog.h>\n#include <qlabel.h>\n#include <qsettings.h>\n\n\nMainWindow::MainWindow(QWidget* parent) :\n\tQMainWindow(parent),\n\tm_ui(new Ui::MainWindow)\n{\n\tm_ui->setupUi(this);\n\tm_ui->centralWidget->hide();\n\tsetDockOptions(AllowNestedDocks | AnimatedDocks | AllowTabbedDocks);\n\n\tm_log = new LogWidget;\n\tm_property_view = new PropertyView;\n\tm_scene_view = new SceneView;\n\tm_game_view = new GameView;\n\tm_asset_browser = new AssetBrowser;\n\tm_script_compiler_ui = new ScriptCompilerWidget;\n\tm_file_server_ui = new FileServerWidget;\n\tm_profiler_ui = new ProfilerUI;\n\tm_entity_template_list_ui = new EntityTemplateList;\n\tm_notifications = Notifications::create(*this);\n\tm_entity_list = new EntityList(NULL);\n\n\tQSettings settings(\"Lumix\", \"QtEditor\");\n\tbool geometry_restored = restoreGeometry(settings.value(\"mainWindowGeometry\").toByteArray());\n\t\n\tm_window_menu = new QMenu(\"Windows\", m_ui->menuView);\n\tm_ui->menuView->addMenu(m_window_menu);\n\tm_window_menu->connect(m_window_menu, &QMenu::aboutToShow, [this]()\n\t{\n\t\tfor (auto info : m_dock_infos)\n\t\t{\n\t\t\tinfo.m_action->setChecked(info.m_widget->isVisible());\n\t\t}\n\t});\n\taddEditorDock(static_cast<Qt::DockWidgetArea>(2), m_asset_browser, &MainWindow::on_actionAsset_Browser_triggered);\n\taddEditorDock(static_cast<Qt::DockWidgetArea>(2), m_entity_list, &MainWindow::on_actionEntity_list_triggered);\n\taddEditorDock(static_cast<Qt::DockWidgetArea>(2), m_entity_template_list_ui, &MainWindow::on_actionEntity_templates_triggered);\n\taddEditorDock(static_cast<Qt::DockWidgetArea>(8), m_file_server_ui, &MainWindow::on_actionFile_server_triggered);\n\taddEditorDock(static_cast<Qt::DockWidgetArea>(1), m_game_view, &MainWindow::on_actionGame_view_triggered);\n\taddEditorDock(static_cast<Qt::DockWidgetArea>(8), m_log, &MainWindow::on_actionLog_triggered);\n\taddEditorDock(static_cast<Qt::DockWidgetArea>(1), m_profiler_ui, &MainWindow::on_actionProfiler_triggered);\n\taddEditorDock(static_cast<Qt::DockWidgetArea>(1), m_property_view, &MainWindow::on_actionProperties_triggered);\n\taddEditorDock(static_cast<Qt::DockWidgetArea>(2), m_scene_view, &MainWindow::on_actionScene_View_triggered);\n\taddEditorDock(static_cast<Qt::DockWidgetArea>(8), m_script_compiler_ui, &MainWindow::on_actionScript_compiler_triggered);\n\n\tcreateLayoutCombobox();\n\n\tm_property_view->setScriptCompiler(m_script_compiler_ui->getCompiler());\n\tm_property_view->setAssetBrowser(*m_asset_browser);\n\tm_property_view->setEntityTemplateList(m_entity_template_list_ui);\n\n\tint size = settings.beginReadArray(\"recent_files\");\n\tfor (int i = 0; i < size; ++i)\n\t{\n\t\tsettings.setArrayIndex(i);\n\t\tm_recent_files.push_back(settings.value(\"filename\").toString());\n\t}\n\tsettings.endArray();\n\tm_recent_files_menu = new QMenu(m_ui->menuFile);\n\tm_recent_files_menu->setTitle(\"Recent Files\");\n\tm_ui->menuFile->insertMenu(m_ui->actionSave, m_recent_files_menu);\n\tm_recent_files_menu->connect(m_recent_files_menu, &QMenu::triggered, [this](QAction* action)\n\t{\n\t\tauto path = action->text().toLatin1();\n\t\tm_world_editor->loadUniverse(path.data());\n\t});\n\tfillRecentFiles();\n\n\tgeometry_restored = geometry_restored && restoreState(settings.value(\"mainWindowState\").toByteArray());\n\tif (!geometry_restored)\n\t{\n\t\tQFile file(\"editor\/layouts\/main.bin\");\n\t\tif (file.open(QIODevice::ReadWrite))\n\t\t{\n\t\t\tint size;\n\t\t\tfile.read((char*)&size, sizeof(size));\n\t\t\tQByteArray geom = file.read(size);\n\t\t\trestoreGeometry(geom);\n\t\t\tfile.read((char*)&size, sizeof(size));\n\t\t\tQByteArray state = file.read(size);\n\t\t\trestoreState(state);\n\t\t}\n\t}\n}\n\n\nvoid MainWindow::createLayoutCombobox()\n{\n\tm_layout_combobox = new QComboBox();\n\tQWidget* widget = new QWidget(m_ui->menuBar);\n\tQHBoxLayout* layout = new QHBoxLayout(widget);\n\tQLabel* label = new QLabel(\"Layout\");\n\tlayout->setContentsMargins(0, 0, 0, 0);\n\tlayout->addWidget(label);\n\tlayout->addWidget(m_layout_combobox);\n\tm_ui->menuBar->setCornerWidget(widget);\n\tQDir dir(\"editor\/layouts\/\");\n\tauto files = dir.entryInfoList();\n\tfor (const auto& file : files)\n\t{\n\t\tif (file.baseName() != \"\")\n\t\t{\n\t\t\tm_layout_combobox->addItem(file.baseName());\n\t\t}\n\t}\n\tconnect(m_layout_combobox, &QComboBox::currentTextChanged, [this](const QString & text)\n\t{\n\t\tQFile file(QString(\"editor\/layouts\/%1.bin\").arg(text));\n\t\tif (file.open(QIODevice::ReadWrite))\n\t\t{\n\t\t\tint size;\n\t\t\tfile.read((char*)&size, sizeof(size));\n\t\t\tQByteArray geom = file.read(size);\n\t\t\trestoreGeometry(geom);\n\t\t\tfile.read((char*)&size, sizeof(size));\n\t\t\tQByteArray state = file.read(size);\n\t\t\trestoreState(state);\n\t\t}\n\t});;\n}\n\n\nvoid MainWindow::addEditorDock(Qt::DockWidgetArea area, QDockWidget* widget, void (MainWindow::*callback)())\n{\n\tDockInfo info;\n\tinfo.m_widget = widget;\n\tQAction* action = new QAction(widget->windowTitle(), m_window_menu);\n\taction->setCheckable(true);\n\tm_window_menu->addAction(action);\n\tinfo.m_action = action;\n\taction->connect(action, &QAction::triggered, this, callback);\n\tm_dock_infos.push_back(info);\n\taddDockWidget(area, widget);\n}\n\n\nvoid MainWindow::fillRecentFiles()\n{\n\tm_recent_files_menu->clear();\n\tfor (auto file : m_recent_files)\n\t{\n\t\tm_recent_files_menu->addAction(file);\n\t}\n}\n\n\nvoid MainWindow::resizeEvent(QResizeEvent* event)\n{\n\tm_resized.invoke(event->size());\n}\n\n\nvoid MainWindow::update()\n{\n\tm_notifications->update(m_world_editor->getEngine().getLastTimeDelta());\n}\n\n\nvoid MainWindow::closeEvent(QCloseEvent *event)\n{\n\tQSettings settings(\"Lumix\", \"QtEditor\");\n\tsettings.setValue(\"mainWindowGeometry\", saveGeometry());\n\tsettings.setValue(\"mainWindowState\", saveState());\n\tsettings.beginWriteArray(\"recent_files\");\n\tint i = 0;\n\tfor (auto file : m_recent_files)\n\t{\n\t\tsettings.setArrayIndex(i);\n\t\tsettings.setValue(\"filename\", file);\n\t\t++i;\n\t}\n\tsettings.endArray();\n\tQMainWindow::closeEvent(event);\n}\n\nMainWindow::~MainWindow()\n{\n\tdelete m_log;\n\tdelete m_ui;\n\tdelete m_scene_view;\n\tdelete m_property_view;\n\tdelete m_game_view;\n\tdelete m_asset_browser;\n\tdelete m_script_compiler_ui;\n\tdelete m_file_server_ui;\n\tdelete m_profiler_ui;\n\tdelete m_entity_template_list_ui;\n\tNotifications::destroy(m_notifications);\n}\n\n\nvoid MainWindow::setWorldEditor(Lumix::WorldEditor& editor)\n{\n\tm_world_editor = &editor;\n\tm_file_server_ui->setWorldEditor(editor);\n\tm_asset_browser->setWorldEditor(editor);\n\tm_property_view->setWorldEditor(editor);\n\tm_entity_template_list_ui->setWorldEditor(editor);\n\tm_game_view->setWorldEditor(editor);\n\tm_entity_list->setWorldEditor(editor);\n\n\tm_world_editor->universeLoaded().bind<MainWindow, &MainWindow::onUniverseLoaded>(this);\n}\n\nvoid MainWindow::onUniverseLoaded()\n{\n\tconst char* path = m_world_editor->getUniversePath().c_str();\n\t\n\tif (m_recent_files.indexOf(path, 0) < 0)\n\t{\n\t\tm_recent_files.push_back(path);\n\t\tif (m_recent_files.size() > 6)\n\t\t{\n\t\t\tm_recent_files.pop_front();\n\t\t}\n\t\tfillRecentFiles();\n\t}\n}\n\nGameView* MainWindow::getGameView() const\n{\n\treturn m_game_view;\n}\n\n\nSceneView* MainWindow::getSceneView() const\n{\n\treturn m_scene_view;\n}\n\n\nvoid MainWindow::on_actionLog_triggered()\n{\n\tm_log->show();\n}\n\n\nvoid MainWindow::on_actionOpen_triggered()\n{\n\tQString filename = QFileDialog::getOpenFileName(NULL, QString(), QString(), \"universe (*.unv)\");\n\tQByteArray path = filename.toLocal8Bit();\n\tif (!path.isEmpty())\n\t{\n\t\tm_world_editor->loadUniverse(path.data());\n\t}\n}\n\nvoid MainWindow::on_actionSave_As_triggered()\n{\n\tQByteArray path = QFileDialog::getSaveFileName().toLocal8Bit();\n\tif (!path.isEmpty())\n\t{\n\t\tm_world_editor->saveUniverse(path.data());\n\t}\n}\n\nvoid MainWindow::on_actionCreate_triggered()\n{\n\tm_world_editor->addEntity();\n}\n\nvoid MainWindow::on_actionProperties_triggered()\n{\n\tm_property_view->show();\n}\n\nvoid MainWindow::on_actionE_xit_triggered()\n{\n\tclose();\n}\n\nvoid MainWindow::on_actionGame_view_triggered()\n{\n\tm_game_view->show();\n}\n\nvoid MainWindow::on_actionScript_compiler_triggered()\n{\n\tm_script_compiler_ui->show();\n}\n\nvoid MainWindow::on_actionFile_server_triggered()\n{\n\tm_file_server_ui->show();\n}\n\nvoid MainWindow::on_actionAsset_Browser_triggered()\n{\n\tm_asset_browser->show();\n}\n\nvoid MainWindow::on_actionScene_View_triggered()\n{\n\tm_scene_view->show();\n}\n\nvoid MainWindow::on_actionProfiler_triggered()\n{\n\tm_profiler_ui->show();\n}\n\nvoid MainWindow::on_actionPolygon_Mode_changed()\n{\n\tm_world_editor->setWireframe(m_ui->actionPolygon_Mode->isChecked());\n}\n\nvoid MainWindow::on_actionGame_mode_triggered()\n{\n\tm_world_editor->toggleGameMode();\n}\n\nvoid MainWindow::on_actionLook_at_selected_entity_triggered()\n{\n\tm_world_editor->lookAtSelected();\n}\n\nvoid MainWindow::on_actionNew_triggered()\n{\n\tm_world_editor->newUniverse();\n}\n\nvoid MainWindow::on_actionSave_triggered()\n{\n\tif (m_world_editor->getUniversePath()[0] == '\\0')\n\t{\n\t\ton_actionSave_As_triggered();\n\t}\n\telse\n\t{\n\t\tm_world_editor->saveUniverse(m_world_editor->getUniversePath());\n\t}\n}\n\nvoid MainWindow::on_actionSnap_to_terrain_triggered()\n{\n\tm_world_editor->snapToTerrain();\n}\n\nvoid MainWindow::on_actionSave_as_template_triggered()\n{\n\tif (m_world_editor->getSelectedEntities().size() == 1)\n\t{\n\t\tbool ok = false;\n\t\tQString text = QInputDialog::getText(this, tr(\"Entity template\"), tr(\"Template name:\"), QLineEdit::Normal, tr(\"\"), &ok);\n\t\tif (ok)\n\t\t{\n\t\t\tm_world_editor->getEntityTemplateSystem().createTemplateFromEntity(text.toLatin1().data(), m_world_editor->getSelectedEntities()[0]);\n\t\t}\n\t}\n}\n\nvoid MainWindow::on_actionEntity_templates_triggered()\n{\n\tm_entity_template_list_ui->show();\n}\n\nvoid MainWindow::on_actionInstantiate_template_triggered()\n{\n\tm_entity_template_list_ui->instantiateTemplate();\n}\n\nvoid MainWindow::on_actionUndo_triggered()\n{\n\tm_world_editor->undo();\n}\n\nvoid MainWindow::on_actionRedo_triggered()\n{\n\tm_world_editor->redo();\n}\n\nvoid MainWindow::on_actionRemove_triggered()\n{\n\tif (!m_world_editor->getSelectedEntities().empty())\n\t{\n\t\tm_world_editor->destroyEntities(&m_world_editor->getSelectedEntities()[0], m_world_editor->getSelectedEntities().size());\n\t}\n}\n\nvoid MainWindow::on_actionEntity_list_triggered()\n{\n\tm_entity_list->show();\n}\n\nvoid MainWindow::on_actionMeasure_triggered()\n{\n\tm_world_editor->toggleMeasure();\n}\n\nvoid MainWindow::on_actionSave_Layout_triggered()\n{\n\tbool ok;\n\tQString text = QInputDialog::getText(this, \"Save layout\", \"Layout name:\", QLineEdit::Normal, \"\", &ok);\n\tif (ok && !text.isEmpty())\n\t{\n\t\tQFile file(QString(\"editor\/layouts\/%1.bin\").arg(text));\n\t\tif (file.open(QIODevice::ReadWrite))\n\t\t{\n\t\t\tauto geom = saveGeometry();\n\t\t\tauto state = saveState();\n\t\t\tint size = geom.size();\n\t\t\tfile.write((const char*)&size, sizeof(size));\n\t\t\tfile.write(geom);\n\t\t\tsize = state.size();\n\t\t\tfile.write((const char*)&size, sizeof(size));\n\t\t\tfile.write(state);\n\t\t\tbool item_exists = false;\n\t\t\tfor (int i = 0; i < m_layout_combobox->count(); ++i)\n\t\t\t{\n\t\t\t\tif (m_layout_combobox->itemText(i) == text)\n\t\t\t\t{\n\t\t\t\t\titem_exists = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (!item_exists)\n\t\t\t{\n\t\t\t\tm_layout_combobox->addItem(text);\n\t\t\t}\n\t\t}\n\t}\n}\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\/\n\/* input.cpp *\/\n\/*************************************************************************\/\n\/* This file is part of: *\/\n\/* GODOT ENGINE *\/\n\/* http:\/\/www.godotengine.org *\/\n\/*************************************************************************\/\n\/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. *\/\n\/* *\/\n\/* Permission is hereby granted, free of charge, to any person obtaining *\/\n\/* a copy of this software and associated documentation files (the *\/\n\/* \"Software\"), to deal in the Software without restriction, including *\/\n\/* without limitation the rights to use, copy, modify, merge, publish, *\/\n\/* distribute, sublicense, and\/or sell copies of the Software, and to *\/\n\/* permit persons to whom the Software is furnished to do so, subject to *\/\n\/* the following conditions: *\/\n\/* *\/\n\/* The above copyright notice and this permission notice shall be *\/\n\/* included in all copies or substantial portions of the Software. *\/\n\/* *\/\n\/* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, *\/\n\/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF *\/\n\/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*\/\n\/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY *\/\n\/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, *\/\n\/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE *\/\n\/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *\/\n\/*************************************************************************\/\n#include \"input.h\"\n#include \"input_map.h\"\n#include \"os\/os.h\"\n#include \"globals.h\"\nInput *Input::singleton=NULL;\n\nInput *Input::get_singleton() {\n\n\treturn singleton;\n}\n\nvoid Input::set_mouse_mode(MouseMode p_mode) {\n\tERR_FAIL_INDEX(p_mode,3);\n\tOS::get_singleton()->set_mouse_mode((OS::MouseMode)p_mode);\n}\n\nInput::MouseMode Input::get_mouse_mode() const {\n\n\treturn (MouseMode)OS::get_singleton()->get_mouse_mode();\n}\n\nvoid Input::_bind_methods() {\n\n\tObjectTypeDB::bind_method(_MD(\"is_key_pressed\",\"scancode\"),&Input::is_key_pressed);\n\tObjectTypeDB::bind_method(_MD(\"is_mouse_button_pressed\",\"button\"),&Input::is_mouse_button_pressed);\n\tObjectTypeDB::bind_method(_MD(\"is_joy_button_pressed\",\"device\",\"button\"),&Input::is_joy_button_pressed);\n\tObjectTypeDB::bind_method(_MD(\"is_action_pressed\",\"action\"),&Input::is_action_pressed);\n\tObjectTypeDB::bind_method(_MD(\"is_action_just_pressed\",\"action\"),&Input::is_action_just_pressed);\n\tObjectTypeDB::bind_method(_MD(\"is_action_just_released\",\"action\"),&Input::is_action_just_released);\n\tObjectTypeDB::bind_method(_MD(\"add_joy_mapping\",\"mapping\", \"update_existing\"),&Input::add_joy_mapping, DEFVAL(false));\n\tObjectTypeDB::bind_method(_MD(\"remove_joy_mapping\",\"guid\"),&Input::remove_joy_mapping);\n\tObjectTypeDB::bind_method(_MD(\"is_joy_known\",\"device\"),&Input::is_joy_known);\n\tObjectTypeDB::bind_method(_MD(\"get_joy_axis\",\"device\",\"axis\"),&Input::get_joy_axis);\n\tObjectTypeDB::bind_method(_MD(\"get_joy_name\",\"device\"),&Input::get_joy_name);\n\tObjectTypeDB::bind_method(_MD(\"get_joy_guid\",\"device\"),&Input::get_joy_guid);\n\tObjectTypeDB::bind_method(_MD(\"get_connected_joysticks\"),&Input::get_connected_joysticks);\n\tObjectTypeDB::bind_method(_MD(\"get_joy_vibration_strength\", \"device\"), &Input::get_joy_vibration_strength);\n\tObjectTypeDB::bind_method(_MD(\"get_joy_vibration_duration\", \"device\"), &Input::get_joy_vibration_duration);\n\tObjectTypeDB::bind_method(_MD(\"get_joy_button_string\", \"button_index\"), &Input::get_joy_button_string);\n\tObjectTypeDB::bind_method(_MD(\"get_joy_button_index_from_string\", \"button\"), &Input::get_joy_button_index_from_string);\n\tObjectTypeDB::bind_method(_MD(\"get_joy_axis_string\", \"axis_index\"), &Input::get_joy_axis_string);\n\tObjectTypeDB::bind_method(_MD(\"get_joy_axis_index_from_string\", \"axis\"), &Input::get_joy_axis_index_from_string);\n\tObjectTypeDB::bind_method(_MD(\"start_joy_vibration\", \"device\", \"weak_magnitude\", \"strong_magnitude\", \"duration\"), &Input::start_joy_vibration, DEFVAL(0));\n\tObjectTypeDB::bind_method(_MD(\"stop_joy_vibration\", \"device\"), &Input::stop_joy_vibration);\n\tObjectTypeDB::bind_method(_MD(\"get_accelerometer\"),&Input::get_accelerometer);\n\tObjectTypeDB::bind_method(_MD(\"get_magnetometer\"),&Input::get_magnetometer);\n\tObjectTypeDB::bind_method(_MD(\"get_gyroscope\"),&Input::get_gyroscope);\n\t\/\/ObjectTypeDB::bind_method(_MD(\"get_mouse_pos\"),&Input::get_mouse_pos); - this is not the function you want\n\tObjectTypeDB::bind_method(_MD(\"get_mouse_speed\"),&Input::get_mouse_speed);\n\tObjectTypeDB::bind_method(_MD(\"get_mouse_button_mask\"),&Input::get_mouse_button_mask);\n\tObjectTypeDB::bind_method(_MD(\"set_mouse_mode\",\"mode\"),&Input::set_mouse_mode);\n\tObjectTypeDB::bind_method(_MD(\"get_mouse_mode\"),&Input::get_mouse_mode);\n\tObjectTypeDB::bind_method(_MD(\"warp_mouse_pos\",\"to\"),&Input::warp_mouse_pos);\n\tObjectTypeDB::bind_method(_MD(\"action_press\",\"action\"),&Input::action_press);\n\tObjectTypeDB::bind_method(_MD(\"action_release\",\"action\"),&Input::action_release);\n\tObjectTypeDB::bind_method(_MD(\"set_custom_mouse_cursor\",\"image:Texture\",\"hotspot\"),&Input::set_custom_mouse_cursor,DEFVAL(Vector2()));\n\n\tBIND_CONSTANT( MOUSE_MODE_VISIBLE );\n\tBIND_CONSTANT( MOUSE_MODE_HIDDEN );\n\tBIND_CONSTANT( MOUSE_MODE_CAPTURED );\n\n\tADD_SIGNAL( MethodInfo(\"joy_connection_changed\", PropertyInfo(Variant::INT, \"index\"), PropertyInfo(Variant::BOOL, \"connected\")) );\n}\n\nvoid Input::get_argument_options(const StringName& p_function,int p_idx,List<String>*r_options) const {\n#ifdef TOOLS_ENABLED\n\n\tString pf=p_function;\n\tif (p_idx==0 && (pf==\"is_action_pressed\" || pf==\"action_press\" || pf==\"action_release\")) {\n\n\t\tList<PropertyInfo> pinfo;\n\t\tGlobals::get_singleton()->get_property_list(&pinfo);\n\n\t\tfor(List<PropertyInfo>::Element *E=pinfo.front();E;E=E->next()) {\n\t\t\tconst PropertyInfo &pi=E->get();\n\n\t\t\tif (!pi.name.begins_with(\"input\/\"))\n\t\t\t\tcontinue;\n\n\t\t\tString name = pi.name.substr(pi.name.find(\"\/\")+1,pi.name.length());\n\t\t\tr_options->push_back(\"\\\"\"+name+\"\\\"\");\n\n\t\t}\n\t}\n#endif\n\n}\n\nInput::Input() {\n\n\tsingleton=this;\n}\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n<commit_msg>Code completion for is_action_just_{pressed, released}<commit_after>\/*************************************************************************\/\n\/* input.cpp *\/\n\/*************************************************************************\/\n\/* This file is part of: *\/\n\/* GODOT ENGINE *\/\n\/* http:\/\/www.godotengine.org *\/\n\/*************************************************************************\/\n\/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. *\/\n\/* *\/\n\/* Permission is hereby granted, free of charge, to any person obtaining *\/\n\/* a copy of this software and associated documentation files (the *\/\n\/* \"Software\"), to deal in the Software without restriction, including *\/\n\/* without limitation the rights to use, copy, modify, merge, publish, *\/\n\/* distribute, sublicense, and\/or sell copies of the Software, and to *\/\n\/* permit persons to whom the Software is furnished to do so, subject to *\/\n\/* the following conditions: *\/\n\/* *\/\n\/* The above copyright notice and this permission notice shall be *\/\n\/* included in all copies or substantial portions of the Software. *\/\n\/* *\/\n\/* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, *\/\n\/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF *\/\n\/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*\/\n\/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY *\/\n\/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, *\/\n\/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE *\/\n\/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *\/\n\/*************************************************************************\/\n#include \"input.h\"\n#include \"input_map.h\"\n#include \"os\/os.h\"\n#include \"globals.h\"\nInput *Input::singleton=NULL;\n\nInput *Input::get_singleton() {\n\n\treturn singleton;\n}\n\nvoid Input::set_mouse_mode(MouseMode p_mode) {\n\tERR_FAIL_INDEX(p_mode,3);\n\tOS::get_singleton()->set_mouse_mode((OS::MouseMode)p_mode);\n}\n\nInput::MouseMode Input::get_mouse_mode() const {\n\n\treturn (MouseMode)OS::get_singleton()->get_mouse_mode();\n}\n\nvoid Input::_bind_methods() {\n\n\tObjectTypeDB::bind_method(_MD(\"is_key_pressed\",\"scancode\"),&Input::is_key_pressed);\n\tObjectTypeDB::bind_method(_MD(\"is_mouse_button_pressed\",\"button\"),&Input::is_mouse_button_pressed);\n\tObjectTypeDB::bind_method(_MD(\"is_joy_button_pressed\",\"device\",\"button\"),&Input::is_joy_button_pressed);\n\tObjectTypeDB::bind_method(_MD(\"is_action_pressed\",\"action\"),&Input::is_action_pressed);\n\tObjectTypeDB::bind_method(_MD(\"is_action_just_pressed\",\"action\"),&Input::is_action_just_pressed);\n\tObjectTypeDB::bind_method(_MD(\"is_action_just_released\",\"action\"),&Input::is_action_just_released);\n\tObjectTypeDB::bind_method(_MD(\"add_joy_mapping\",\"mapping\", \"update_existing\"),&Input::add_joy_mapping, DEFVAL(false));\n\tObjectTypeDB::bind_method(_MD(\"remove_joy_mapping\",\"guid\"),&Input::remove_joy_mapping);\n\tObjectTypeDB::bind_method(_MD(\"is_joy_known\",\"device\"),&Input::is_joy_known);\n\tObjectTypeDB::bind_method(_MD(\"get_joy_axis\",\"device\",\"axis\"),&Input::get_joy_axis);\n\tObjectTypeDB::bind_method(_MD(\"get_joy_name\",\"device\"),&Input::get_joy_name);\n\tObjectTypeDB::bind_method(_MD(\"get_joy_guid\",\"device\"),&Input::get_joy_guid);\n\tObjectTypeDB::bind_method(_MD(\"get_connected_joysticks\"),&Input::get_connected_joysticks);\n\tObjectTypeDB::bind_method(_MD(\"get_joy_vibration_strength\", \"device\"), &Input::get_joy_vibration_strength);\n\tObjectTypeDB::bind_method(_MD(\"get_joy_vibration_duration\", \"device\"), &Input::get_joy_vibration_duration);\n\tObjectTypeDB::bind_method(_MD(\"get_joy_button_string\", \"button_index\"), &Input::get_joy_button_string);\n\tObjectTypeDB::bind_method(_MD(\"get_joy_button_index_from_string\", \"button\"), &Input::get_joy_button_index_from_string);\n\tObjectTypeDB::bind_method(_MD(\"get_joy_axis_string\", \"axis_index\"), &Input::get_joy_axis_string);\n\tObjectTypeDB::bind_method(_MD(\"get_joy_axis_index_from_string\", \"axis\"), &Input::get_joy_axis_index_from_string);\n\tObjectTypeDB::bind_method(_MD(\"start_joy_vibration\", \"device\", \"weak_magnitude\", \"strong_magnitude\", \"duration\"), &Input::start_joy_vibration, DEFVAL(0));\n\tObjectTypeDB::bind_method(_MD(\"stop_joy_vibration\", \"device\"), &Input::stop_joy_vibration);\n\tObjectTypeDB::bind_method(_MD(\"get_accelerometer\"),&Input::get_accelerometer);\n\tObjectTypeDB::bind_method(_MD(\"get_magnetometer\"),&Input::get_magnetometer);\n\tObjectTypeDB::bind_method(_MD(\"get_gyroscope\"),&Input::get_gyroscope);\n\t\/\/ObjectTypeDB::bind_method(_MD(\"get_mouse_pos\"),&Input::get_mouse_pos); - this is not the function you want\n\tObjectTypeDB::bind_method(_MD(\"get_mouse_speed\"),&Input::get_mouse_speed);\n\tObjectTypeDB::bind_method(_MD(\"get_mouse_button_mask\"),&Input::get_mouse_button_mask);\n\tObjectTypeDB::bind_method(_MD(\"set_mouse_mode\",\"mode\"),&Input::set_mouse_mode);\n\tObjectTypeDB::bind_method(_MD(\"get_mouse_mode\"),&Input::get_mouse_mode);\n\tObjectTypeDB::bind_method(_MD(\"warp_mouse_pos\",\"to\"),&Input::warp_mouse_pos);\n\tObjectTypeDB::bind_method(_MD(\"action_press\",\"action\"),&Input::action_press);\n\tObjectTypeDB::bind_method(_MD(\"action_release\",\"action\"),&Input::action_release);\n\tObjectTypeDB::bind_method(_MD(\"set_custom_mouse_cursor\",\"image:Texture\",\"hotspot\"),&Input::set_custom_mouse_cursor,DEFVAL(Vector2()));\n\n\tBIND_CONSTANT( MOUSE_MODE_VISIBLE );\n\tBIND_CONSTANT( MOUSE_MODE_HIDDEN );\n\tBIND_CONSTANT( MOUSE_MODE_CAPTURED );\n\n\tADD_SIGNAL( MethodInfo(\"joy_connection_changed\", PropertyInfo(Variant::INT, \"index\"), PropertyInfo(Variant::BOOL, \"connected\")) );\n}\n\nvoid Input::get_argument_options(const StringName& p_function,int p_idx,List<String>*r_options) const {\n#ifdef TOOLS_ENABLED\n\n\tString pf=p_function;\n\tif (p_idx==0 && (pf==\"is_action_pressed\" || pf==\"action_press\" || pf==\"action_release\" || pf==\"is_action_just_pressed\" || pf==\"is_action_just_released\")) {\n\n\t\tList<PropertyInfo> pinfo;\n\t\tGlobals::get_singleton()->get_property_list(&pinfo);\n\n\t\tfor(List<PropertyInfo>::Element *E=pinfo.front();E;E=E->next()) {\n\t\t\tconst PropertyInfo &pi=E->get();\n\n\t\t\tif (!pi.name.begins_with(\"input\/\"))\n\t\t\t\tcontinue;\n\n\t\t\tString name = pi.name.substr(pi.name.find(\"\/\")+1,pi.name.length());\n\t\t\tr_options->push_back(\"\\\"\"+name+\"\\\"\");\n\n\t\t}\n\t}\n#endif\n\n}\n\nInput::Input() {\n\n\tsingleton=this;\n}\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/chromeos\/login\/google_authenticator.h\"\n\n#include <string>\n#include <vector>\n\n#include \"base\/file_path.h\"\n#include \"base\/file_util.h\"\n#include \"base\/logging.h\"\n#include \"base\/path_service.h\"\n#include \"base\/sha2.h\"\n#include \"base\/string_util.h\"\n#include \"base\/third_party\/nss\/blapi.h\"\n#include \"base\/third_party\/nss\/sha256.h\"\n#include \"chrome\/browser\/browser_process.h\"\n#include \"chrome\/browser\/chrome_thread.h\"\n#include \"chrome\/browser\/chromeos\/cros\/cryptohome_library.h\"\n#include \"chrome\/browser\/chromeos\/login\/auth_response_handler.h\"\n#include \"chrome\/browser\/chromeos\/login\/authentication_notification_details.h\"\n#include \"chrome\/browser\/chromeos\/login\/login_status_consumer.h\"\n#include \"chrome\/browser\/net\/chrome_url_request_context.h\"\n#include \"chrome\/browser\/profile.h\"\n#include \"chrome\/browser\/profile_manager.h\"\n#include \"chrome\/common\/chrome_paths.h\"\n#include \"chrome\/common\/net\/url_fetcher.h\"\n#include \"chrome\/common\/notification_service.h\"\n#include \"net\/base\/load_flags.h\"\n#include \"net\/base\/net_errors.h\"\n#include \"net\/url_request\/url_request_status.h\"\n#include \"third_party\/libjingle\/source\/talk\/base\/urlencode.h\"\n\nusing base::Time;\nusing base::TimeDelta;\nusing file_util::GetFileSize;\nusing file_util::PathExists;\nusing file_util::ReadFile;\nusing file_util::ReadFileToString;\n\nnamespace chromeos {\n\n\/\/ static\nconst char GoogleAuthenticator::kCookiePersistence[] = \"true\";\n\/\/ static\nconst char GoogleAuthenticator::kAccountType[] = \"HOSTED_OR_GOOGLE\";\n\/\/ static\nconst char GoogleAuthenticator::kSource[] = \"chromeos\";\n\/\/ static\n\/\/ Service name for Google Contacts API. API is used to get user's image.\nconst char GoogleAuthenticator::kService[] = \"cp\";\n\/\/ static\nconst char GoogleAuthenticator::kFormat[] =\n \"Email=%s&\"\n \"Passwd=%s&\"\n \"PersistentCookie=%s&\"\n \"accountType=%s&\"\n \"source=%s&\"\n \"service=%s\";\n\/\/ static\nconst char GoogleAuthenticator::kFormatCaptcha[] =\n \"Email=%s&\"\n \"Passwd=%s&\"\n \"PersistentCookie=%s&\"\n \"accountType=%s&\"\n \"source=%s&\"\n \"service=%s&\"\n \"logintoken=%s&\"\n \"logincaptcha=%s\";\n\/\/ static\nconst char GoogleAuthenticator::kSecondFactor[] = \"Info=InvalidSecondFactor\";\n\n\/\/ static\nconst char GoogleAuthenticator::kSystemSalt[] = \"\/home\/.shadow\/salt\";\n\/\/ static\nconst char GoogleAuthenticator::kOpenSSLMagic[] = \"Salted__\";\n\/\/ static\nconst char GoogleAuthenticator::kLocalaccountFile[] = \"localaccount\";\n\/\/ static\nconst char GoogleAuthenticator::kTmpfsTrigger[] = \"incognito\";\n\n\/\/ static\nconst int GoogleAuthenticator::kClientLoginTimeoutMs = 5000;\n\nconst int kPassHashLen = 32;\n\nGoogleAuthenticator::GoogleAuthenticator(LoginStatusConsumer* consumer)\n : Authenticator(consumer),\n fetcher_(NULL),\n getter_(NULL),\n checked_for_localaccount_(false),\n unlock_(false),\n try_again_(true),\n fetch_completed_(false) {\n CHECK(chromeos::CrosLibrary::Get()->EnsureLoaded());\n}\n\nGoogleAuthenticator::~GoogleAuthenticator() {\n delete fetcher_;\n}\n\n\/\/ static\nURLFetcher* GoogleAuthenticator::CreateClientLoginFetcher(\n URLRequestContextGetter* getter,\n const std::string& body,\n URLFetcher::Delegate* delegate) {\n URLFetcher* to_return =\n URLFetcher::Create(0,\n GURL(AuthResponseHandler::kClientLoginUrl),\n URLFetcher::POST,\n delegate);\n to_return->set_request_context(getter);\n to_return->set_load_flags(net::LOAD_DO_NOT_SEND_COOKIES);\n to_return->set_upload_data(\"application\/x-www-form-urlencoded\", body);\n return to_return;\n}\n\nbool GoogleAuthenticator::AuthenticateToLogin(\n Profile* profile,\n const std::string& username,\n const std::string& password,\n const std::string& login_token,\n const std::string& login_captcha) {\n unlock_ = false;\n getter_ = profile->GetRequestContext();\n\n \/\/ TODO(cmasone): be more careful about zeroing memory that stores\n \/\/ the user's password.\n if (login_token.empty() || login_captcha.empty()) {\n request_body_ = StringPrintf(kFormat,\n UrlEncodeString(username).c_str(),\n UrlEncodeString(password).c_str(),\n kCookiePersistence,\n kAccountType,\n kSource,\n kService);\n } else {\n request_body_ = StringPrintf(kFormatCaptcha,\n UrlEncodeString(username).c_str(),\n UrlEncodeString(password).c_str(),\n kCookiePersistence,\n kAccountType,\n kSource,\n kService,\n UrlEncodeString(login_token).c_str(),\n UrlEncodeString(login_captcha).c_str());\n }\n \/\/ TODO(cmasone): Figure out how to parallelize fetch, username\/password\n \/\/ processing without impacting testability.\n username_.assign(Canonicalize(username));\n StoreHashedPassword(password);\n TryClientLogin();\n return true;\n}\n\nbool GoogleAuthenticator::AuthenticateToUnlock(const std::string& username,\n const std::string& password) {\n username_.assign(Canonicalize(username));\n StoreHashedPassword(password);\n unlock_ = true;\n ChromeThread::PostTask(\n ChromeThread::UI, FROM_HERE,\n NewRunnableMethod(this, &GoogleAuthenticator::CheckOffline,\n std::string(\"unlock failed\")));\n return true;\n}\n\nvoid GoogleAuthenticator::LoginOffTheRecord() {\n DCHECK(ChromeThread::CurrentlyOn(ChromeThread::UI));\n if (CrosLibrary::Get()->GetCryptohomeLibrary()->Mount(kTmpfsTrigger, \"\")) {\n AuthenticationNotificationDetails details(true);\n NotificationService::current()->Notify(\n NotificationType::LOGIN_AUTHENTICATION,\n NotificationService::AllSources(),\n Details<AuthenticationNotificationDetails>(&details));\n consumer_->OnOffTheRecordLoginSuccess();\n } else {\n consumer_->OnLoginFailure(\"Could not mount tmpfs cryptohome\");\n }\n}\n\nvoid GoogleAuthenticator::OnURLFetchComplete(const URLFetcher* source,\n const GURL& url,\n const URLRequestStatus& status,\n int response_code,\n const ResponseCookies& cookies,\n const std::string& data) {\n fetch_completed_ = true;\n if (status.is_success() && response_code == kHttpSuccess) {\n LOG(INFO) << \"Online login successful!\";\n ChromeThread::PostTask(\n ChromeThread::UI, FROM_HERE,\n NewRunnableMethod(this, &GoogleAuthenticator::OnLoginSuccess, data));\n } else if (!status.is_success()) {\n if (status.status() == URLRequestStatus::CANCELED) {\n if (try_again_) {\n try_again_ = false;\n LOG(ERROR) << \"Login attempt canceled!?!? Trying again.\";\n TryClientLogin();\n fetch_completed_ = false;\n return;\n }\n LOG(ERROR) << \"Login attempt canceled again? Already retried...\";\n }\n LOG(WARNING) << \"Could not reach Google Accounts servers: errno \"\n << status.os_error();\n \/\/ The fetch failed for network reasons, try offline login.\n LoadLocalaccount(kLocalaccountFile);\n ChromeThread::PostTask(\n ChromeThread::UI, FROM_HERE,\n NewRunnableMethod(this, &GoogleAuthenticator::CheckOffline,\n net::ErrorToString(status.os_error())));\n } else {\n if (IsSecondFactorSuccess(data)) {\n ChromeThread::PostTask(\n ChromeThread::UI, FROM_HERE,\n NewRunnableMethod(this,\n &GoogleAuthenticator::OnLoginSuccess,\n std::string()));\n } else {\n \/\/ The fetch succeeded, but ClientLogin said no.\n LoadLocalaccount(kLocalaccountFile);\n ChromeThread::PostTask(\n ChromeThread::UI, FROM_HERE,\n NewRunnableMethod(this,\n &GoogleAuthenticator::CheckLocalaccount,\n data));\n }\n }\n}\n\nvoid GoogleAuthenticator::OnLoginSuccess(const std::string& data) {\n \/\/ Send notification of success\n AuthenticationNotificationDetails details(true);\n NotificationService::current()->Notify(\n NotificationType::LOGIN_AUTHENTICATION,\n NotificationService::AllSources(),\n Details<AuthenticationNotificationDetails>(&details));\n\n if (unlock_ ||\n CrosLibrary::Get()->GetCryptohomeLibrary()->Mount(username_.c_str(),\n ascii_hash_.c_str())) {\n consumer_->OnLoginSuccess(username_, data);\n } else {\n OnLoginFailure(\"Could not mount cryptohome\");\n }\n}\n\nvoid GoogleAuthenticator::CheckOffline(const std::string& error) {\n LOG(INFO) << \"Attempting offline login\";\n if (CrosLibrary::Get()->GetCryptohomeLibrary()->CheckKey(\n username_.c_str(),\n ascii_hash_.c_str())) {\n \/\/ The fetch didn't succeed, but offline login did.\n LOG(INFO) << \"Offline login successful!\";\n OnLoginSuccess(std::string());\n } else {\n \/\/ We couldn't hit the network, and offline login failed.\n GoogleAuthenticator::CheckLocalaccount(error);\n }\n}\n\nvoid GoogleAuthenticator::CheckLocalaccount(const std::string& error) {\n if (!localaccount_.empty() && localaccount_ == username_ &&\n CrosLibrary::Get()->GetCryptohomeLibrary()->Mount(kTmpfsTrigger, \"\")) {\n LOG(WARNING) << \"Logging in with localaccount: \" << localaccount_;\n consumer_->OnLoginSuccess(username_, std::string());\n } else {\n OnLoginFailure(error);\n }\n}\n\nvoid GoogleAuthenticator::OnLoginFailure(const std::string& data) {\n \/\/ Send notification of failure\n AuthenticationNotificationDetails details(false);\n NotificationService::current()->Notify(\n NotificationType::LOGIN_AUTHENTICATION,\n NotificationService::AllSources(),\n Details<AuthenticationNotificationDetails>(&details));\n LOG(WARNING) << \"Login failed: \" << data;\n \/\/ TODO(cmasone): what can we do to expose these OS\/server-side error strings\n \/\/ in an internationalizable way?\n consumer_->OnLoginFailure(data);\n}\n\nvoid GoogleAuthenticator::LoadSystemSalt() {\n if (!system_salt_.empty())\n return;\n system_salt_ = CrosLibrary::Get()->GetCryptohomeLibrary()->GetSystemSalt();\n CHECK(!system_salt_.empty());\n CHECK_EQ(system_salt_.size() % 2, 0U);\n}\n\nvoid GoogleAuthenticator::LoadLocalaccount(const std::string& filename) {\n if (checked_for_localaccount_)\n return;\n FilePath localaccount_file;\n std::string localaccount;\n if (PathService::Get(base::DIR_EXE, &localaccount_file)) {\n localaccount_file = localaccount_file.Append(filename);\n LOG(INFO) << \"looking for localaccount in \" << localaccount_file.value();\n\n ReadFileToString(localaccount_file, &localaccount);\n TrimWhitespaceASCII(localaccount, TRIM_TRAILING, &localaccount);\n LOG(INFO) << \"Loading localaccount: \" << localaccount;\n } else {\n LOG(INFO) << \"Assuming no localaccount\";\n }\n set_localaccount(localaccount);\n}\n\nvoid GoogleAuthenticator::StoreHashedPassword(const std::string& password) {\n \/\/ Get salt, ascii encode, update sha with that, then update with ascii\n \/\/ of password, then end.\n std::string ascii_salt = SaltAsAscii();\n unsigned char passhash_buf[kPassHashLen];\n char ascii_buf[kPassHashLen + 1];\n\n \/\/ Hash salt and password\n SHA256Context ctx;\n SHA256_Begin(&ctx);\n SHA256_Update(&ctx,\n reinterpret_cast<const unsigned char*>(ascii_salt.data()),\n static_cast<unsigned int>(ascii_salt.length()));\n SHA256_Update(&ctx,\n reinterpret_cast<const unsigned char*>(password.data()),\n static_cast<unsigned int>(password.length()));\n SHA256_End(&ctx,\n passhash_buf,\n NULL,\n static_cast<unsigned int>(sizeof(passhash_buf)));\n\n std::vector<unsigned char> passhash(passhash_buf,\n passhash_buf + sizeof(passhash_buf));\n BinaryToHex(passhash,\n passhash.size() \/ 2, \/\/ only want top half, at least for now.\n ascii_buf,\n sizeof(ascii_buf));\n ascii_hash_.assign(ascii_buf, sizeof(ascii_buf) - 1);\n}\n\nstd::string GoogleAuthenticator::SaltAsAscii() {\n LoadSystemSalt(); \/\/ no-op if it's already loaded.\n unsigned int salt_len = system_salt_.size();\n char ascii_salt[2 * salt_len + 1];\n if (GoogleAuthenticator::BinaryToHex(system_salt_,\n salt_len,\n ascii_salt,\n sizeof(ascii_salt))) {\n return std::string(ascii_salt, sizeof(ascii_salt) - 1);\n } else {\n return std::string();\n }\n}\n\nvoid GoogleAuthenticator::Cancel() {\n if (!fetch_completed_ && fetcher_) {\n delete fetcher_;\n fetcher_ = NULL;\n }\n OnLoginFailure(\"Login has timed out; please try again!\");\n}\n\nvoid GoogleAuthenticator::TryClientLogin() {\n if (fetcher_)\n delete fetcher_;\n fetcher_ = CreateClientLoginFetcher(getter_, request_body_, this);\n fetcher_->Start();\n ChromeThread::PostDelayedTask(\n ChromeThread::UI, FROM_HERE,\n NewRunnableMethod(this,\n &GoogleAuthenticator::Cancel), kClientLoginTimeoutMs);\n}\n\n\/\/ static\nbool GoogleAuthenticator::IsSecondFactorSuccess(\n const std::string& alleged_error) {\n return alleged_error.find(GoogleAuthenticator::kSecondFactor) !=\n std::string::npos;\n}\n\n\/\/ static\nbool GoogleAuthenticator::BinaryToHex(const std::vector<unsigned char>& binary,\n const unsigned int binary_len,\n char* hex_string,\n const unsigned int len) {\n if (len < 2*binary_len)\n return false;\n memset(hex_string, 0, len);\n for (uint i = 0, j = 0; i < binary_len; i++, j+=2)\n snprintf(hex_string + j, len - j, \"%02x\", binary[i]);\n return true;\n}\n\n\/\/ static\nstd::string GoogleAuthenticator::Canonicalize(\n const std::string& email_address) {\n std::vector<std::string> parts;\n char at = '@';\n SplitString(email_address, at, &parts);\n DCHECK_EQ(parts.size(), 2U) << \"email_address should have only one @\";\n RemoveChars(parts[0], \".\", &parts[0]);\n if (parts[0].find('+') != std::string::npos)\n parts[0].erase(parts[0].find('+'));\n std::string new_email = StringToLowerASCII(JoinString(parts, at));\n LOG(INFO) << \"Canonicalized \" << email_address << \" to \" << new_email;\n return new_email;\n}\n\n} \/\/ namespace chromeos\n<commit_msg>In case of successful login attempt do nothing in Cancel task. Fixes crash introduced in http:\/\/codereview.chromium.org\/2867012<commit_after>\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/chromeos\/login\/google_authenticator.h\"\n\n#include <string>\n#include <vector>\n\n#include \"base\/file_path.h\"\n#include \"base\/file_util.h\"\n#include \"base\/logging.h\"\n#include \"base\/path_service.h\"\n#include \"base\/sha2.h\"\n#include \"base\/string_util.h\"\n#include \"base\/third_party\/nss\/blapi.h\"\n#include \"base\/third_party\/nss\/sha256.h\"\n#include \"chrome\/browser\/browser_process.h\"\n#include \"chrome\/browser\/chrome_thread.h\"\n#include \"chrome\/browser\/chromeos\/cros\/cryptohome_library.h\"\n#include \"chrome\/browser\/chromeos\/login\/auth_response_handler.h\"\n#include \"chrome\/browser\/chromeos\/login\/authentication_notification_details.h\"\n#include \"chrome\/browser\/chromeos\/login\/login_status_consumer.h\"\n#include \"chrome\/browser\/net\/chrome_url_request_context.h\"\n#include \"chrome\/browser\/profile.h\"\n#include \"chrome\/browser\/profile_manager.h\"\n#include \"chrome\/common\/chrome_paths.h\"\n#include \"chrome\/common\/net\/url_fetcher.h\"\n#include \"chrome\/common\/notification_service.h\"\n#include \"net\/base\/load_flags.h\"\n#include \"net\/base\/net_errors.h\"\n#include \"net\/url_request\/url_request_status.h\"\n#include \"third_party\/libjingle\/source\/talk\/base\/urlencode.h\"\n\nusing base::Time;\nusing base::TimeDelta;\nusing file_util::GetFileSize;\nusing file_util::PathExists;\nusing file_util::ReadFile;\nusing file_util::ReadFileToString;\n\nnamespace chromeos {\n\n\/\/ static\nconst char GoogleAuthenticator::kCookiePersistence[] = \"true\";\n\/\/ static\nconst char GoogleAuthenticator::kAccountType[] = \"HOSTED_OR_GOOGLE\";\n\/\/ static\nconst char GoogleAuthenticator::kSource[] = \"chromeos\";\n\/\/ static\n\/\/ Service name for Google Contacts API. API is used to get user's image.\nconst char GoogleAuthenticator::kService[] = \"cp\";\n\/\/ static\nconst char GoogleAuthenticator::kFormat[] =\n \"Email=%s&\"\n \"Passwd=%s&\"\n \"PersistentCookie=%s&\"\n \"accountType=%s&\"\n \"source=%s&\"\n \"service=%s\";\n\/\/ static\nconst char GoogleAuthenticator::kFormatCaptcha[] =\n \"Email=%s&\"\n \"Passwd=%s&\"\n \"PersistentCookie=%s&\"\n \"accountType=%s&\"\n \"source=%s&\"\n \"service=%s&\"\n \"logintoken=%s&\"\n \"logincaptcha=%s\";\n\/\/ static\nconst char GoogleAuthenticator::kSecondFactor[] = \"Info=InvalidSecondFactor\";\n\n\/\/ static\nconst char GoogleAuthenticator::kSystemSalt[] = \"\/home\/.shadow\/salt\";\n\/\/ static\nconst char GoogleAuthenticator::kOpenSSLMagic[] = \"Salted__\";\n\/\/ static\nconst char GoogleAuthenticator::kLocalaccountFile[] = \"localaccount\";\n\/\/ static\nconst char GoogleAuthenticator::kTmpfsTrigger[] = \"incognito\";\n\n\/\/ static\nconst int GoogleAuthenticator::kClientLoginTimeoutMs = 5000;\n\nconst int kPassHashLen = 32;\n\nGoogleAuthenticator::GoogleAuthenticator(LoginStatusConsumer* consumer)\n : Authenticator(consumer),\n fetcher_(NULL),\n getter_(NULL),\n checked_for_localaccount_(false),\n unlock_(false),\n try_again_(true),\n fetch_completed_(false) {\n CHECK(chromeos::CrosLibrary::Get()->EnsureLoaded());\n}\n\nGoogleAuthenticator::~GoogleAuthenticator() {\n delete fetcher_;\n}\n\n\/\/ static\nURLFetcher* GoogleAuthenticator::CreateClientLoginFetcher(\n URLRequestContextGetter* getter,\n const std::string& body,\n URLFetcher::Delegate* delegate) {\n URLFetcher* to_return =\n URLFetcher::Create(0,\n GURL(AuthResponseHandler::kClientLoginUrl),\n URLFetcher::POST,\n delegate);\n to_return->set_request_context(getter);\n to_return->set_load_flags(net::LOAD_DO_NOT_SEND_COOKIES);\n to_return->set_upload_data(\"application\/x-www-form-urlencoded\", body);\n return to_return;\n}\n\nbool GoogleAuthenticator::AuthenticateToLogin(\n Profile* profile,\n const std::string& username,\n const std::string& password,\n const std::string& login_token,\n const std::string& login_captcha) {\n unlock_ = false;\n getter_ = profile->GetRequestContext();\n\n \/\/ TODO(cmasone): be more careful about zeroing memory that stores\n \/\/ the user's password.\n if (login_token.empty() || login_captcha.empty()) {\n request_body_ = StringPrintf(kFormat,\n UrlEncodeString(username).c_str(),\n UrlEncodeString(password).c_str(),\n kCookiePersistence,\n kAccountType,\n kSource,\n kService);\n } else {\n request_body_ = StringPrintf(kFormatCaptcha,\n UrlEncodeString(username).c_str(),\n UrlEncodeString(password).c_str(),\n kCookiePersistence,\n kAccountType,\n kSource,\n kService,\n UrlEncodeString(login_token).c_str(),\n UrlEncodeString(login_captcha).c_str());\n }\n \/\/ TODO(cmasone): Figure out how to parallelize fetch, username\/password\n \/\/ processing without impacting testability.\n username_.assign(Canonicalize(username));\n StoreHashedPassword(password);\n TryClientLogin();\n return true;\n}\n\nbool GoogleAuthenticator::AuthenticateToUnlock(const std::string& username,\n const std::string& password) {\n username_.assign(Canonicalize(username));\n StoreHashedPassword(password);\n unlock_ = true;\n ChromeThread::PostTask(\n ChromeThread::UI, FROM_HERE,\n NewRunnableMethod(this, &GoogleAuthenticator::CheckOffline,\n std::string(\"unlock failed\")));\n return true;\n}\n\nvoid GoogleAuthenticator::LoginOffTheRecord() {\n DCHECK(ChromeThread::CurrentlyOn(ChromeThread::UI));\n if (CrosLibrary::Get()->GetCryptohomeLibrary()->Mount(kTmpfsTrigger, \"\")) {\n AuthenticationNotificationDetails details(true);\n NotificationService::current()->Notify(\n NotificationType::LOGIN_AUTHENTICATION,\n NotificationService::AllSources(),\n Details<AuthenticationNotificationDetails>(&details));\n consumer_->OnOffTheRecordLoginSuccess();\n } else {\n consumer_->OnLoginFailure(\"Could not mount tmpfs cryptohome\");\n }\n}\n\nvoid GoogleAuthenticator::OnURLFetchComplete(const URLFetcher* source,\n const GURL& url,\n const URLRequestStatus& status,\n int response_code,\n const ResponseCookies& cookies,\n const std::string& data) {\n fetch_completed_ = true;\n if (status.is_success() && response_code == kHttpSuccess) {\n LOG(INFO) << \"Online login successful!\";\n ChromeThread::PostTask(\n ChromeThread::UI, FROM_HERE,\n NewRunnableMethod(this, &GoogleAuthenticator::OnLoginSuccess, data));\n } else if (!status.is_success()) {\n if (status.status() == URLRequestStatus::CANCELED) {\n if (try_again_) {\n try_again_ = false;\n LOG(ERROR) << \"Login attempt canceled!?!? Trying again.\";\n TryClientLogin();\n fetch_completed_ = false;\n return;\n }\n LOG(ERROR) << \"Login attempt canceled again? Already retried...\";\n }\n LOG(WARNING) << \"Could not reach Google Accounts servers: errno \"\n << status.os_error();\n \/\/ The fetch failed for network reasons, try offline login.\n LoadLocalaccount(kLocalaccountFile);\n ChromeThread::PostTask(\n ChromeThread::UI, FROM_HERE,\n NewRunnableMethod(this, &GoogleAuthenticator::CheckOffline,\n net::ErrorToString(status.os_error())));\n } else {\n if (IsSecondFactorSuccess(data)) {\n ChromeThread::PostTask(\n ChromeThread::UI, FROM_HERE,\n NewRunnableMethod(this,\n &GoogleAuthenticator::OnLoginSuccess,\n std::string()));\n } else {\n \/\/ The fetch succeeded, but ClientLogin said no.\n LoadLocalaccount(kLocalaccountFile);\n ChromeThread::PostTask(\n ChromeThread::UI, FROM_HERE,\n NewRunnableMethod(this,\n &GoogleAuthenticator::CheckLocalaccount,\n data));\n }\n }\n}\n\nvoid GoogleAuthenticator::OnLoginSuccess(const std::string& data) {\n \/\/ Send notification of success\n AuthenticationNotificationDetails details(true);\n NotificationService::current()->Notify(\n NotificationType::LOGIN_AUTHENTICATION,\n NotificationService::AllSources(),\n Details<AuthenticationNotificationDetails>(&details));\n\n if (unlock_ ||\n CrosLibrary::Get()->GetCryptohomeLibrary()->Mount(username_.c_str(),\n ascii_hash_.c_str())) {\n consumer_->OnLoginSuccess(username_, data);\n } else {\n OnLoginFailure(\"Could not mount cryptohome\");\n }\n}\n\nvoid GoogleAuthenticator::CheckOffline(const std::string& error) {\n LOG(INFO) << \"Attempting offline login\";\n if (CrosLibrary::Get()->GetCryptohomeLibrary()->CheckKey(\n username_.c_str(),\n ascii_hash_.c_str())) {\n \/\/ The fetch didn't succeed, but offline login did.\n LOG(INFO) << \"Offline login successful!\";\n OnLoginSuccess(std::string());\n } else {\n \/\/ We couldn't hit the network, and offline login failed.\n GoogleAuthenticator::CheckLocalaccount(error);\n }\n}\n\nvoid GoogleAuthenticator::CheckLocalaccount(const std::string& error) {\n if (!localaccount_.empty() && localaccount_ == username_ &&\n CrosLibrary::Get()->GetCryptohomeLibrary()->Mount(kTmpfsTrigger, \"\")) {\n LOG(WARNING) << \"Logging in with localaccount: \" << localaccount_;\n consumer_->OnLoginSuccess(username_, std::string());\n } else {\n OnLoginFailure(error);\n }\n}\n\nvoid GoogleAuthenticator::OnLoginFailure(const std::string& data) {\n \/\/ Send notification of failure\n AuthenticationNotificationDetails details(false);\n NotificationService::current()->Notify(\n NotificationType::LOGIN_AUTHENTICATION,\n NotificationService::AllSources(),\n Details<AuthenticationNotificationDetails>(&details));\n LOG(WARNING) << \"Login failed: \" << data;\n \/\/ TODO(cmasone): what can we do to expose these OS\/server-side error strings\n \/\/ in an internationalizable way?\n consumer_->OnLoginFailure(data);\n}\n\nvoid GoogleAuthenticator::LoadSystemSalt() {\n if (!system_salt_.empty())\n return;\n system_salt_ = CrosLibrary::Get()->GetCryptohomeLibrary()->GetSystemSalt();\n CHECK(!system_salt_.empty());\n CHECK_EQ(system_salt_.size() % 2, 0U);\n}\n\nvoid GoogleAuthenticator::LoadLocalaccount(const std::string& filename) {\n if (checked_for_localaccount_)\n return;\n FilePath localaccount_file;\n std::string localaccount;\n if (PathService::Get(base::DIR_EXE, &localaccount_file)) {\n localaccount_file = localaccount_file.Append(filename);\n LOG(INFO) << \"looking for localaccount in \" << localaccount_file.value();\n\n ReadFileToString(localaccount_file, &localaccount);\n TrimWhitespaceASCII(localaccount, TRIM_TRAILING, &localaccount);\n LOG(INFO) << \"Loading localaccount: \" << localaccount;\n } else {\n LOG(INFO) << \"Assuming no localaccount\";\n }\n set_localaccount(localaccount);\n}\n\nvoid GoogleAuthenticator::StoreHashedPassword(const std::string& password) {\n \/\/ Get salt, ascii encode, update sha with that, then update with ascii\n \/\/ of password, then end.\n std::string ascii_salt = SaltAsAscii();\n unsigned char passhash_buf[kPassHashLen];\n char ascii_buf[kPassHashLen + 1];\n\n \/\/ Hash salt and password\n SHA256Context ctx;\n SHA256_Begin(&ctx);\n SHA256_Update(&ctx,\n reinterpret_cast<const unsigned char*>(ascii_salt.data()),\n static_cast<unsigned int>(ascii_salt.length()));\n SHA256_Update(&ctx,\n reinterpret_cast<const unsigned char*>(password.data()),\n static_cast<unsigned int>(password.length()));\n SHA256_End(&ctx,\n passhash_buf,\n NULL,\n static_cast<unsigned int>(sizeof(passhash_buf)));\n\n std::vector<unsigned char> passhash(passhash_buf,\n passhash_buf + sizeof(passhash_buf));\n BinaryToHex(passhash,\n passhash.size() \/ 2, \/\/ only want top half, at least for now.\n ascii_buf,\n sizeof(ascii_buf));\n ascii_hash_.assign(ascii_buf, sizeof(ascii_buf) - 1);\n}\n\nstd::string GoogleAuthenticator::SaltAsAscii() {\n LoadSystemSalt(); \/\/ no-op if it's already loaded.\n unsigned int salt_len = system_salt_.size();\n char ascii_salt[2 * salt_len + 1];\n if (GoogleAuthenticator::BinaryToHex(system_salt_,\n salt_len,\n ascii_salt,\n sizeof(ascii_salt))) {\n return std::string(ascii_salt, sizeof(ascii_salt) - 1);\n } else {\n return std::string();\n }\n}\n\nvoid GoogleAuthenticator::Cancel() {\n if (fetch_completed_)\n return;\n\n if (fetcher_) {\n delete fetcher_;\n fetcher_ = NULL;\n }\n OnLoginFailure(\"Login has timed out; please try again!\");\n}\n\nvoid GoogleAuthenticator::TryClientLogin() {\n if (fetcher_)\n delete fetcher_;\n fetcher_ = CreateClientLoginFetcher(getter_, request_body_, this);\n fetcher_->Start();\n ChromeThread::PostDelayedTask(\n ChromeThread::UI, FROM_HERE,\n NewRunnableMethod(this,\n &GoogleAuthenticator::Cancel), kClientLoginTimeoutMs);\n}\n\n\/\/ static\nbool GoogleAuthenticator::IsSecondFactorSuccess(\n const std::string& alleged_error) {\n return alleged_error.find(GoogleAuthenticator::kSecondFactor) !=\n std::string::npos;\n}\n\n\/\/ static\nbool GoogleAuthenticator::BinaryToHex(const std::vector<unsigned char>& binary,\n const unsigned int binary_len,\n char* hex_string,\n const unsigned int len) {\n if (len < 2*binary_len)\n return false;\n memset(hex_string, 0, len);\n for (uint i = 0, j = 0; i < binary_len; i++, j+=2)\n snprintf(hex_string + j, len - j, \"%02x\", binary[i]);\n return true;\n}\n\n\/\/ static\nstd::string GoogleAuthenticator::Canonicalize(\n const std::string& email_address) {\n std::vector<std::string> parts;\n char at = '@';\n SplitString(email_address, at, &parts);\n DCHECK_EQ(parts.size(), 2U) << \"email_address should have only one @\";\n RemoveChars(parts[0], \".\", &parts[0]);\n if (parts[0].find('+') != std::string::npos)\n parts[0].erase(parts[0].find('+'));\n std::string new_email = StringToLowerASCII(JoinString(parts, at));\n LOG(INFO) << \"Canonicalized \" << email_address << \" to \" << new_email;\n return new_email;\n}\n\n} \/\/ namespace chromeos\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2011 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/chromeos\/status\/network_menu_button.h\"\n\n#include <algorithm>\n#include <limits>\n\n#include \"base\/logging.h\"\n#include \"base\/message_loop.h\"\n#include \"base\/string_util.h\"\n#include \"base\/stringprintf.h\"\n#include \"base\/utf_string_conversions.h\"\n#include \"chrome\/browser\/browser_process.h\"\n#include \"chrome\/browser\/chromeos\/cros\/cros_library.h\"\n#include \"chrome\/browser\/chromeos\/login\/helper.h\"\n#include \"chrome\/browser\/chromeos\/login\/user_manager.h\"\n#include \"chrome\/browser\/chromeos\/options\/network_config_view.h\"\n#include \"chrome\/browser\/chromeos\/sim_dialog_delegate.h\"\n#include \"chrome\/browser\/chromeos\/status\/status_area_host.h\"\n#include \"chrome\/browser\/prefs\/pref_service.h\"\n#include \"chrome\/browser\/profiles\/profile.h\"\n#include \"chrome\/browser\/ui\/browser.h\"\n#include \"chrome\/browser\/ui\/browser_list.h\"\n#include \"chrome\/common\/pref_names.h\"\n#include \"grit\/generated_resources.h\"\n#include \"grit\/theme_resources.h\"\n#include \"ui\/base\/l10n\/l10n_util.h\"\n#include \"ui\/base\/resource\/resource_bundle.h\"\n#include \"views\/widget\/widget.h\"\n\nnamespace {\n\n\/\/ Time in milliseconds to delay showing of promo\n\/\/ notification when Chrome window is not on screen.\nconst int kPromoShowDelayMs = 10000;\n\nconst int kNotificationCountPrefDefault = -1;\n\nbool GetBooleanPref(const char* pref_name) {\n Browser* browser = BrowserList::GetLastActive();\n \/\/ Default to safe value which is false (not to show bubble).\n if (!browser || !browser->profile())\n return false;\n\n PrefService* prefs = browser->profile()->GetPrefs();\n return prefs->GetBoolean(pref_name);\n}\n\nint GetIntegerLocalPref(const char* pref_name) {\n PrefService* prefs = g_browser_process->local_state();\n return prefs->GetInteger(pref_name);\n}\n\nvoid SetBooleanPref(const char* pref_name, bool value) {\n Browser* browser = BrowserList::GetLastActive();\n if (!browser || !browser->profile())\n return;\n\n PrefService* prefs = browser->profile()->GetPrefs();\n prefs->SetBoolean(pref_name, value);\n}\n\nvoid SetIntegerLocalPref(const char* pref_name, int value) {\n PrefService* prefs = g_browser_process->local_state();\n prefs->SetInteger(pref_name, value);\n}\n\n\/\/ Returns prefs::kShow3gPromoNotification or false\n\/\/ if there's no active browser.\nbool ShouldShow3gPromoNotification() {\n return GetBooleanPref(prefs::kShow3gPromoNotification);\n}\n\nvoid SetShow3gPromoNotification(bool value) {\n SetBooleanPref(prefs::kShow3gPromoNotification, value);\n}\n\n\/\/ Returns prefs::kCarrierDealPromoShown which is number of times\n\/\/ carrier deal notification has been shown to users on this machine.\nint GetCarrierDealPromoShown() {\n return GetIntegerLocalPref(prefs::kCarrierDealPromoShown);\n}\n\nvoid SetCarrierDealPromoShown(int value) {\n SetIntegerLocalPref(prefs::kCarrierDealPromoShown, value);\n}\n\n} \/\/ namespace\n\nnamespace chromeos {\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ NetworkMenuButton\n\nNetworkMenuButton::NetworkMenuButton(StatusAreaHost* host)\n : StatusAreaButton(host, this),\n mobile_data_bubble_(NULL),\n is_browser_mode_(false),\n check_for_promo_(true),\n was_sim_locked_(false),\n ALLOW_THIS_IN_INITIALIZER_LIST(method_factory_(this)) {\n is_browser_mode_ = (host->GetScreenMode() == StatusAreaHost::kBrowserMode);\n network_menu_.reset(new NetworkMenu(this, is_browser_mode_));\n network_icon_.reset(\n new NetworkMenuIcon(this, NetworkMenuIcon::MENU_MODE));\n\n NetworkLibrary* network_library = CrosLibrary::Get()->GetNetworkLibrary();\n OnNetworkManagerChanged(network_library);\n network_library->AddNetworkManagerObserver(this);\n network_library->AddCellularDataPlanObserver(this);\n const NetworkDevice* cellular = network_library->FindCellularDevice();\n if (cellular) {\n cellular_device_path_ = cellular->device_path();\n was_sim_locked_ = cellular->is_sim_locked();\n network_library->AddNetworkDeviceObserver(cellular_device_path_, this);\n }\n}\n\nNetworkMenuButton::~NetworkMenuButton() {\n NetworkLibrary* netlib = CrosLibrary::Get()->GetNetworkLibrary();\n netlib->RemoveNetworkManagerObserver(this);\n netlib->RemoveObserverForAllNetworks(this);\n netlib->RemoveCellularDataPlanObserver(this);\n if (!cellular_device_path_.empty())\n netlib->RemoveNetworkDeviceObserver(cellular_device_path_, this);\n if (mobile_data_bubble_)\n mobile_data_bubble_->Close();\n}\n\n\/\/ static\nvoid NetworkMenuButton::RegisterPrefs(PrefService* local_state) {\n \/\/ Carrier deal notification shown count defaults to 0.\n local_state->RegisterIntegerPref(prefs::kCarrierDealPromoShown, 0);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ NetworkLibrary::NetworkDeviceObserver implementation:\n\nvoid NetworkMenuButton::OnNetworkDeviceChanged(NetworkLibrary* cros,\n const NetworkDevice* device) {\n \/\/ Device status, such as SIMLock may have changed.\n SetNetworkIcon();\n network_menu_->UpdateMenu();\n const NetworkDevice* cellular = cros->FindCellularDevice();\n if (cellular) {\n \/\/ We make an assumption (which is valid for now) that the SIM\n \/\/ unlock dialog is put up only when the user is trying to enable\n \/\/ mobile data. So if the SIM is now unlocked, initiate the\n \/\/ enable operation that the user originally requested.\n if (was_sim_locked_ && !cellular->is_sim_locked() &&\n !cros->cellular_enabled()) {\n cros->EnableCellularNetworkDevice(true);\n }\n was_sim_locked_ = cellular->is_sim_locked();\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ NetworkMenuButton, NetworkLibrary::NetworkManagerObserver implementation:\n\nvoid NetworkMenuButton::OnNetworkManagerChanged(NetworkLibrary* cros) {\n \/\/ This gets called on initialization, so any changes should be reflected\n \/\/ in CrosMock::SetNetworkLibraryStatusAreaExpectations().\n SetNetworkIcon();\n network_menu_->UpdateMenu();\n RefreshNetworkObserver(cros);\n RefreshNetworkDeviceObserver(cros);\n ShowOptionalMobileDataPromoNotification(cros);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ NetworkMenuButton, NetworkLibrary::NetworkObserver implementation:\nvoid NetworkMenuButton::OnNetworkChanged(NetworkLibrary* cros,\n const Network* network) {\n SetNetworkIcon();\n network_menu_->UpdateMenu();\n}\n\nvoid NetworkMenuButton::OnCellularDataPlanChanged(NetworkLibrary* cros) {\n \/\/ Call OnNetworkManagerChanged which will update the icon.\n SetNetworkIcon();\n network_menu_->UpdateMenu();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ NetworkMenuButton, NetworkMenu implementation:\n\nviews::MenuButton* NetworkMenuButton::GetMenuButton() {\n return this;\n}\n\ngfx::NativeWindow NetworkMenuButton::GetNativeWindow() const {\n return host_->GetNativeWindow();\n}\n\nvoid NetworkMenuButton::OpenButtonOptions() {\n host_->OpenButtonOptions(this);\n}\n\nbool NetworkMenuButton::ShouldOpenButtonOptions() const {\n return host_->ShouldOpenButtonOptions(this);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ NetworkMenuButton, views::View implementation:\n\nvoid NetworkMenuButton::OnLocaleChanged() {\n SetNetworkIcon();\n network_menu_->UpdateMenu();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ NetworkMenuButton, views::ViewMenuDelegate implementation:\nvoid NetworkMenuButton::RunMenu(views::View* source, const gfx::Point& pt) {\n network_menu_->RunMenu(source);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ NetworkMenuButton, NetworkMenuIcon::Delegate implementation:\nvoid NetworkMenuButton::NetworkMenuIconChanged() {\n const SkBitmap* bitmap = network_icon_->GetIconAndText(NULL);\n SetIcon(*bitmap);\n SchedulePaint();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ MessageBubbleDelegate implementation:\n\nvoid NetworkMenuButton::BubbleClosing(Bubble* bubble, bool closed_by_escape) {\n mobile_data_bubble_ = NULL;\n deal_info_url_.clear();\n deal_topup_url_.clear();\n}\n\nbool NetworkMenuButton::CloseOnEscape() {\n return true;\n}\n\nbool NetworkMenuButton::FadeInOnShow() {\n return false;\n}\n\nvoid NetworkMenuButton::OnLinkActivated(size_t index) {\n \/\/ If we have deal info URL defined that means that there're\n \/\/ 2 links in bubble. Let the user close it manually then thus giving ability\n \/\/ to navigate to second link.\n \/\/ mobile_data_bubble_ will be set to NULL in BubbleClosing callback.\n if (deal_info_url_.empty() && mobile_data_bubble_)\n mobile_data_bubble_->Close();\n\n std::string deal_url_to_open;\n if (index == 0) {\n if (!deal_topup_url_.empty()) {\n deal_url_to_open = deal_topup_url_;\n } else {\n const Network* cellular =\n CrosLibrary::Get()->GetNetworkLibrary()->cellular_network();\n if (!cellular)\n return;\n network_menu_->ShowTabbedNetworkSettings(cellular);\n return;\n }\n } else if (index == 1) {\n deal_url_to_open = deal_info_url_;\n }\n\n if (!deal_url_to_open.empty()) {\n Browser* browser = BrowserList::GetLastActive();\n if (!browser)\n return;\n browser->ShowSingletonTab(GURL(deal_url_to_open));\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ NetworkMenuButton, private methods:\n\nconst ServicesCustomizationDocument::CarrierDeal*\nNetworkMenuButton::GetCarrierDeal(\n NetworkLibrary* cros) {\n std::string carrier_id = cros->GetCellularHomeCarrierId();\n if (carrier_id.empty()) {\n LOG(ERROR) << \"Empty carrier ID with a cellular connected.\";\n return NULL;\n }\n\n ServicesCustomizationDocument* customization =\n ServicesCustomizationDocument::GetInstance();\n if (!customization->IsReady())\n return NULL;\n\n const ServicesCustomizationDocument::CarrierDeal* deal =\n customization->GetCarrierDeal(carrier_id, true);\n if (deal) {\n \/\/ Check deal for validity.\n int carrier_deal_promo_pref = GetCarrierDealPromoShown();\n if (carrier_deal_promo_pref >= deal->notification_count())\n return NULL;\n const std::string locale = g_browser_process->GetApplicationLocale();\n std::string deal_text = deal->GetLocalizedString(locale,\n \"notification_text\");\n if (deal_text.empty())\n return NULL;\n }\n return deal;\n}\n\nvoid NetworkMenuButton::SetNetworkIcon() {\n string16 tooltip;\n const SkBitmap* bitmap = network_icon_->GetIconAndText(&tooltip);\n SetIcon(*bitmap);\n SetTooltipAndAccessibleName(tooltip);\n SchedulePaint();\n}\n\nvoid NetworkMenuButton::RefreshNetworkObserver(NetworkLibrary* cros) {\n const Network* network = cros->active_network();\n std::string new_network = network ? network->service_path() : std::string();\n if (active_network_ != new_network) {\n if (!active_network_.empty()) {\n cros->RemoveNetworkObserver(active_network_, this);\n }\n if (!new_network.empty()) {\n cros->AddNetworkObserver(new_network, this);\n }\n active_network_ = new_network;\n }\n}\n\nvoid NetworkMenuButton::RefreshNetworkDeviceObserver(NetworkLibrary* cros) {\n const NetworkDevice* cellular = cros->FindCellularDevice();\n std::string new_cellular_device_path = cellular ?\n cellular->device_path() : std::string();\n if (cellular_device_path_ != new_cellular_device_path) {\n if (!cellular_device_path_.empty()) {\n cros->RemoveNetworkDeviceObserver(cellular_device_path_, this);\n }\n if (!new_cellular_device_path.empty()) {\n was_sim_locked_ = cellular->is_sim_locked();\n cros->AddNetworkDeviceObserver(new_cellular_device_path, this);\n }\n cellular_device_path_ = new_cellular_device_path;\n }\n}\n\nvoid NetworkMenuButton::ShowOptionalMobileDataPromoNotification(\n NetworkLibrary* cros) {\n \/\/ Display one-time notification for non-Guest users on first use\n \/\/ of Mobile Data connection or if there's a carrier deal defined\n \/\/ show that even if user has already seen generic promo.\n if (is_browser_mode_ && !UserManager::Get()->IsLoggedInAsGuest() &&\n check_for_promo_ && BrowserList::GetLastActive() &&\n cros->cellular_connected() && !cros->ethernet_connected() &&\n !cros->wifi_connected()) {\n const ServicesCustomizationDocument::CarrierDeal* deal =\n GetCarrierDeal(cros);\n std::string deal_text;\n int carrier_deal_promo_pref = -1;\n if (deal) {\n carrier_deal_promo_pref = GetCarrierDealPromoShown();\n const std::string locale = g_browser_process->GetApplicationLocale();\n deal_text = deal->GetLocalizedString(locale, \"notification_text\");\n deal_info_url_ = deal->info_url();\n deal_topup_url_ = deal->top_up_url();\n } else if (!ShouldShow3gPromoNotification()) {\n check_for_promo_ = false;\n return;\n }\n\n gfx::Rect button_bounds = GetScreenBounds();\n \/\/ StatusArea button Y position is usually -1, fix it so that\n \/\/ Contains() method for screen bounds works correctly.\n button_bounds.set_y(button_bounds.y() + 1);\n gfx::Rect screen_bounds(chromeos::CalculateScreenBounds(gfx::Size()));\n\n \/\/ Chrome window is initialized in visible state off screen and then is\n \/\/ moved into visible screen area. Make sure that we're on screen\n \/\/ so that bubble is shown correctly.\n if (!screen_bounds.Contains(button_bounds)) {\n \/\/ If we're not on screen yet, delay notification display.\n \/\/ It may be shown earlier, on next NetworkLibrary callback processing.\n if (method_factory_.empty()) {\n MessageLoop::current()->PostDelayedTask(FROM_HERE,\n method_factory_.NewRunnableMethod(\n &NetworkMenuButton::ShowOptionalMobileDataPromoNotification,\n cros),\n kPromoShowDelayMs);\n }\n return;\n }\n\n \/\/ Add deal text if it's defined.\n std::wstring notification_text;\n std::wstring default_text =\n UTF16ToWide(l10n_util::GetStringUTF16(IDS_3G_NOTIFICATION_MESSAGE));\n if (!deal_text.empty()) {\n notification_text = StringPrintf(L\"%ls\\n\\n%ls\",\n UTF8ToWide(deal_text).c_str(),\n default_text.c_str());\n } else {\n notification_text = default_text;\n }\n\n \/\/ Use deal URL if it's defined or general \"Network Settings\" URL.\n int link_message_id;\n if (deal_topup_url_.empty())\n link_message_id = IDS_OFFLINE_NETWORK_SETTINGS;\n else\n link_message_id = IDS_STATUSBAR_NETWORK_VIEW_ACCOUNT;\n\n std::vector<std::wstring> links;\n links.push_back(UTF16ToWide(l10n_util::GetStringUTF16(link_message_id)));\n if (!deal_topup_url_.empty())\n links.push_back(UTF16ToWide(l10n_util::GetStringUTF16(IDS_LEARN_MORE)));\n mobile_data_bubble_ = MessageBubble::ShowWithLinks(\n GetWidget(),\n button_bounds,\n BubbleBorder::TOP_RIGHT ,\n ResourceBundle::GetSharedInstance().GetBitmapNamed(IDR_NOTIFICATION_3G),\n notification_text,\n links,\n this);\n\n check_for_promo_ = false;\n SetShow3gPromoNotification(false);\n if (carrier_deal_promo_pref != kNotificationCountPrefDefault)\n SetCarrierDealPromoShown(carrier_deal_promo_pref + 1);\n }\n}\n\nvoid NetworkMenuButton::SetTooltipAndAccessibleName(const string16& label) {\n SetTooltipText(UTF16ToWide(label));\n SetAccessibleName(label);\n}\n\n} \/\/ namespace chromeos\n<commit_msg>Show Learn more link in 3G promo bubble only if deal_info_url is not empty<commit_after>\/\/ Copyright (c) 2011 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/chromeos\/status\/network_menu_button.h\"\n\n#include <algorithm>\n#include <limits>\n\n#include \"base\/logging.h\"\n#include \"base\/message_loop.h\"\n#include \"base\/string_util.h\"\n#include \"base\/stringprintf.h\"\n#include \"base\/utf_string_conversions.h\"\n#include \"chrome\/browser\/browser_process.h\"\n#include \"chrome\/browser\/chromeos\/cros\/cros_library.h\"\n#include \"chrome\/browser\/chromeos\/login\/helper.h\"\n#include \"chrome\/browser\/chromeos\/login\/user_manager.h\"\n#include \"chrome\/browser\/chromeos\/options\/network_config_view.h\"\n#include \"chrome\/browser\/chromeos\/sim_dialog_delegate.h\"\n#include \"chrome\/browser\/chromeos\/status\/status_area_host.h\"\n#include \"chrome\/browser\/prefs\/pref_service.h\"\n#include \"chrome\/browser\/profiles\/profile.h\"\n#include \"chrome\/browser\/ui\/browser.h\"\n#include \"chrome\/browser\/ui\/browser_list.h\"\n#include \"chrome\/common\/pref_names.h\"\n#include \"grit\/generated_resources.h\"\n#include \"grit\/theme_resources.h\"\n#include \"ui\/base\/l10n\/l10n_util.h\"\n#include \"ui\/base\/resource\/resource_bundle.h\"\n#include \"views\/widget\/widget.h\"\n\nnamespace {\n\n\/\/ Time in milliseconds to delay showing of promo\n\/\/ notification when Chrome window is not on screen.\nconst int kPromoShowDelayMs = 10000;\n\nconst int kNotificationCountPrefDefault = -1;\n\nbool GetBooleanPref(const char* pref_name) {\n Browser* browser = BrowserList::GetLastActive();\n \/\/ Default to safe value which is false (not to show bubble).\n if (!browser || !browser->profile())\n return false;\n\n PrefService* prefs = browser->profile()->GetPrefs();\n return prefs->GetBoolean(pref_name);\n}\n\nint GetIntegerLocalPref(const char* pref_name) {\n PrefService* prefs = g_browser_process->local_state();\n return prefs->GetInteger(pref_name);\n}\n\nvoid SetBooleanPref(const char* pref_name, bool value) {\n Browser* browser = BrowserList::GetLastActive();\n if (!browser || !browser->profile())\n return;\n\n PrefService* prefs = browser->profile()->GetPrefs();\n prefs->SetBoolean(pref_name, value);\n}\n\nvoid SetIntegerLocalPref(const char* pref_name, int value) {\n PrefService* prefs = g_browser_process->local_state();\n prefs->SetInteger(pref_name, value);\n}\n\n\/\/ Returns prefs::kShow3gPromoNotification or false\n\/\/ if there's no active browser.\nbool ShouldShow3gPromoNotification() {\n return GetBooleanPref(prefs::kShow3gPromoNotification);\n}\n\nvoid SetShow3gPromoNotification(bool value) {\n SetBooleanPref(prefs::kShow3gPromoNotification, value);\n}\n\n\/\/ Returns prefs::kCarrierDealPromoShown which is number of times\n\/\/ carrier deal notification has been shown to users on this machine.\nint GetCarrierDealPromoShown() {\n return GetIntegerLocalPref(prefs::kCarrierDealPromoShown);\n}\n\nvoid SetCarrierDealPromoShown(int value) {\n SetIntegerLocalPref(prefs::kCarrierDealPromoShown, value);\n}\n\n} \/\/ namespace\n\nnamespace chromeos {\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ NetworkMenuButton\n\nNetworkMenuButton::NetworkMenuButton(StatusAreaHost* host)\n : StatusAreaButton(host, this),\n mobile_data_bubble_(NULL),\n is_browser_mode_(false),\n check_for_promo_(true),\n was_sim_locked_(false),\n ALLOW_THIS_IN_INITIALIZER_LIST(method_factory_(this)) {\n is_browser_mode_ = (host->GetScreenMode() == StatusAreaHost::kBrowserMode);\n network_menu_.reset(new NetworkMenu(this, is_browser_mode_));\n network_icon_.reset(\n new NetworkMenuIcon(this, NetworkMenuIcon::MENU_MODE));\n\n NetworkLibrary* network_library = CrosLibrary::Get()->GetNetworkLibrary();\n OnNetworkManagerChanged(network_library);\n network_library->AddNetworkManagerObserver(this);\n network_library->AddCellularDataPlanObserver(this);\n const NetworkDevice* cellular = network_library->FindCellularDevice();\n if (cellular) {\n cellular_device_path_ = cellular->device_path();\n was_sim_locked_ = cellular->is_sim_locked();\n network_library->AddNetworkDeviceObserver(cellular_device_path_, this);\n }\n}\n\nNetworkMenuButton::~NetworkMenuButton() {\n NetworkLibrary* netlib = CrosLibrary::Get()->GetNetworkLibrary();\n netlib->RemoveNetworkManagerObserver(this);\n netlib->RemoveObserverForAllNetworks(this);\n netlib->RemoveCellularDataPlanObserver(this);\n if (!cellular_device_path_.empty())\n netlib->RemoveNetworkDeviceObserver(cellular_device_path_, this);\n if (mobile_data_bubble_)\n mobile_data_bubble_->Close();\n}\n\n\/\/ static\nvoid NetworkMenuButton::RegisterPrefs(PrefService* local_state) {\n \/\/ Carrier deal notification shown count defaults to 0.\n local_state->RegisterIntegerPref(prefs::kCarrierDealPromoShown, 0);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ NetworkLibrary::NetworkDeviceObserver implementation:\n\nvoid NetworkMenuButton::OnNetworkDeviceChanged(NetworkLibrary* cros,\n const NetworkDevice* device) {\n \/\/ Device status, such as SIMLock may have changed.\n SetNetworkIcon();\n network_menu_->UpdateMenu();\n const NetworkDevice* cellular = cros->FindCellularDevice();\n if (cellular) {\n \/\/ We make an assumption (which is valid for now) that the SIM\n \/\/ unlock dialog is put up only when the user is trying to enable\n \/\/ mobile data. So if the SIM is now unlocked, initiate the\n \/\/ enable operation that the user originally requested.\n if (was_sim_locked_ && !cellular->is_sim_locked() &&\n !cros->cellular_enabled()) {\n cros->EnableCellularNetworkDevice(true);\n }\n was_sim_locked_ = cellular->is_sim_locked();\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ NetworkMenuButton, NetworkLibrary::NetworkManagerObserver implementation:\n\nvoid NetworkMenuButton::OnNetworkManagerChanged(NetworkLibrary* cros) {\n \/\/ This gets called on initialization, so any changes should be reflected\n \/\/ in CrosMock::SetNetworkLibraryStatusAreaExpectations().\n SetNetworkIcon();\n network_menu_->UpdateMenu();\n RefreshNetworkObserver(cros);\n RefreshNetworkDeviceObserver(cros);\n ShowOptionalMobileDataPromoNotification(cros);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ NetworkMenuButton, NetworkLibrary::NetworkObserver implementation:\nvoid NetworkMenuButton::OnNetworkChanged(NetworkLibrary* cros,\n const Network* network) {\n SetNetworkIcon();\n network_menu_->UpdateMenu();\n}\n\nvoid NetworkMenuButton::OnCellularDataPlanChanged(NetworkLibrary* cros) {\n \/\/ Call OnNetworkManagerChanged which will update the icon.\n SetNetworkIcon();\n network_menu_->UpdateMenu();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ NetworkMenuButton, NetworkMenu implementation:\n\nviews::MenuButton* NetworkMenuButton::GetMenuButton() {\n return this;\n}\n\ngfx::NativeWindow NetworkMenuButton::GetNativeWindow() const {\n return host_->GetNativeWindow();\n}\n\nvoid NetworkMenuButton::OpenButtonOptions() {\n host_->OpenButtonOptions(this);\n}\n\nbool NetworkMenuButton::ShouldOpenButtonOptions() const {\n return host_->ShouldOpenButtonOptions(this);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ NetworkMenuButton, views::View implementation:\n\nvoid NetworkMenuButton::OnLocaleChanged() {\n SetNetworkIcon();\n network_menu_->UpdateMenu();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ NetworkMenuButton, views::ViewMenuDelegate implementation:\nvoid NetworkMenuButton::RunMenu(views::View* source, const gfx::Point& pt) {\n network_menu_->RunMenu(source);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ NetworkMenuButton, NetworkMenuIcon::Delegate implementation:\nvoid NetworkMenuButton::NetworkMenuIconChanged() {\n const SkBitmap* bitmap = network_icon_->GetIconAndText(NULL);\n SetIcon(*bitmap);\n SchedulePaint();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ MessageBubbleDelegate implementation:\n\nvoid NetworkMenuButton::BubbleClosing(Bubble* bubble, bool closed_by_escape) {\n mobile_data_bubble_ = NULL;\n deal_info_url_.clear();\n deal_topup_url_.clear();\n}\n\nbool NetworkMenuButton::CloseOnEscape() {\n return true;\n}\n\nbool NetworkMenuButton::FadeInOnShow() {\n return false;\n}\n\nvoid NetworkMenuButton::OnLinkActivated(size_t index) {\n \/\/ If we have deal info URL defined that means that there're\n \/\/ 2 links in bubble. Let the user close it manually then thus giving ability\n \/\/ to navigate to second link.\n \/\/ mobile_data_bubble_ will be set to NULL in BubbleClosing callback.\n if (deal_info_url_.empty() && mobile_data_bubble_)\n mobile_data_bubble_->Close();\n\n std::string deal_url_to_open;\n if (index == 0) {\n if (!deal_topup_url_.empty()) {\n deal_url_to_open = deal_topup_url_;\n } else {\n const Network* cellular =\n CrosLibrary::Get()->GetNetworkLibrary()->cellular_network();\n if (!cellular)\n return;\n network_menu_->ShowTabbedNetworkSettings(cellular);\n return;\n }\n } else if (index == 1) {\n deal_url_to_open = deal_info_url_;\n }\n\n if (!deal_url_to_open.empty()) {\n Browser* browser = BrowserList::GetLastActive();\n if (!browser)\n return;\n browser->ShowSingletonTab(GURL(deal_url_to_open));\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ NetworkMenuButton, private methods:\n\nconst ServicesCustomizationDocument::CarrierDeal*\nNetworkMenuButton::GetCarrierDeal(\n NetworkLibrary* cros) {\n std::string carrier_id = cros->GetCellularHomeCarrierId();\n if (carrier_id.empty()) {\n LOG(ERROR) << \"Empty carrier ID with a cellular connected.\";\n return NULL;\n }\n\n ServicesCustomizationDocument* customization =\n ServicesCustomizationDocument::GetInstance();\n if (!customization->IsReady())\n return NULL;\n\n const ServicesCustomizationDocument::CarrierDeal* deal =\n customization->GetCarrierDeal(carrier_id, true);\n if (deal) {\n \/\/ Check deal for validity.\n int carrier_deal_promo_pref = GetCarrierDealPromoShown();\n if (carrier_deal_promo_pref >= deal->notification_count())\n return NULL;\n const std::string locale = g_browser_process->GetApplicationLocale();\n std::string deal_text = deal->GetLocalizedString(locale,\n \"notification_text\");\n if (deal_text.empty())\n return NULL;\n }\n return deal;\n}\n\nvoid NetworkMenuButton::SetNetworkIcon() {\n string16 tooltip;\n const SkBitmap* bitmap = network_icon_->GetIconAndText(&tooltip);\n SetIcon(*bitmap);\n SetTooltipAndAccessibleName(tooltip);\n SchedulePaint();\n}\n\nvoid NetworkMenuButton::RefreshNetworkObserver(NetworkLibrary* cros) {\n const Network* network = cros->active_network();\n std::string new_network = network ? network->service_path() : std::string();\n if (active_network_ != new_network) {\n if (!active_network_.empty()) {\n cros->RemoveNetworkObserver(active_network_, this);\n }\n if (!new_network.empty()) {\n cros->AddNetworkObserver(new_network, this);\n }\n active_network_ = new_network;\n }\n}\n\nvoid NetworkMenuButton::RefreshNetworkDeviceObserver(NetworkLibrary* cros) {\n const NetworkDevice* cellular = cros->FindCellularDevice();\n std::string new_cellular_device_path = cellular ?\n cellular->device_path() : std::string();\n if (cellular_device_path_ != new_cellular_device_path) {\n if (!cellular_device_path_.empty()) {\n cros->RemoveNetworkDeviceObserver(cellular_device_path_, this);\n }\n if (!new_cellular_device_path.empty()) {\n was_sim_locked_ = cellular->is_sim_locked();\n cros->AddNetworkDeviceObserver(new_cellular_device_path, this);\n }\n cellular_device_path_ = new_cellular_device_path;\n }\n}\n\nvoid NetworkMenuButton::ShowOptionalMobileDataPromoNotification(\n NetworkLibrary* cros) {\n \/\/ Display one-time notification for non-Guest users on first use\n \/\/ of Mobile Data connection or if there's a carrier deal defined\n \/\/ show that even if user has already seen generic promo.\n if (is_browser_mode_ && !UserManager::Get()->IsLoggedInAsGuest() &&\n check_for_promo_ && BrowserList::GetLastActive() &&\n cros->cellular_connected() && !cros->ethernet_connected() &&\n !cros->wifi_connected()) {\n const ServicesCustomizationDocument::CarrierDeal* deal =\n GetCarrierDeal(cros);\n std::string deal_text;\n int carrier_deal_promo_pref = -1;\n if (deal) {\n carrier_deal_promo_pref = GetCarrierDealPromoShown();\n const std::string locale = g_browser_process->GetApplicationLocale();\n deal_text = deal->GetLocalizedString(locale, \"notification_text\");\n deal_info_url_ = deal->info_url();\n deal_topup_url_ = deal->top_up_url();\n } else if (!ShouldShow3gPromoNotification()) {\n check_for_promo_ = false;\n return;\n }\n\n gfx::Rect button_bounds = GetScreenBounds();\n \/\/ StatusArea button Y position is usually -1, fix it so that\n \/\/ Contains() method for screen bounds works correctly.\n button_bounds.set_y(button_bounds.y() + 1);\n gfx::Rect screen_bounds(chromeos::CalculateScreenBounds(gfx::Size()));\n\n \/\/ Chrome window is initialized in visible state off screen and then is\n \/\/ moved into visible screen area. Make sure that we're on screen\n \/\/ so that bubble is shown correctly.\n if (!screen_bounds.Contains(button_bounds)) {\n \/\/ If we're not on screen yet, delay notification display.\n \/\/ It may be shown earlier, on next NetworkLibrary callback processing.\n if (method_factory_.empty()) {\n MessageLoop::current()->PostDelayedTask(FROM_HERE,\n method_factory_.NewRunnableMethod(\n &NetworkMenuButton::ShowOptionalMobileDataPromoNotification,\n cros),\n kPromoShowDelayMs);\n }\n return;\n }\n\n \/\/ Add deal text if it's defined.\n std::wstring notification_text;\n std::wstring default_text =\n UTF16ToWide(l10n_util::GetStringUTF16(IDS_3G_NOTIFICATION_MESSAGE));\n if (!deal_text.empty()) {\n notification_text = StringPrintf(L\"%ls\\n\\n%ls\",\n UTF8ToWide(deal_text).c_str(),\n default_text.c_str());\n } else {\n notification_text = default_text;\n }\n\n \/\/ Use deal URL if it's defined or general \"Network Settings\" URL.\n int link_message_id;\n if (deal_topup_url_.empty())\n link_message_id = IDS_OFFLINE_NETWORK_SETTINGS;\n else\n link_message_id = IDS_STATUSBAR_NETWORK_VIEW_ACCOUNT;\n\n std::vector<std::wstring> links;\n links.push_back(UTF16ToWide(l10n_util::GetStringUTF16(link_message_id)));\n if (!deal_info_url_.empty())\n links.push_back(UTF16ToWide(l10n_util::GetStringUTF16(IDS_LEARN_MORE)));\n mobile_data_bubble_ = MessageBubble::ShowWithLinks(\n GetWidget(),\n button_bounds,\n BubbleBorder::TOP_RIGHT ,\n ResourceBundle::GetSharedInstance().GetBitmapNamed(IDR_NOTIFICATION_3G),\n notification_text,\n links,\n this);\n\n check_for_promo_ = false;\n SetShow3gPromoNotification(false);\n if (carrier_deal_promo_pref != kNotificationCountPrefDefault)\n SetCarrierDealPromoShown(carrier_deal_promo_pref + 1);\n }\n}\n\nvoid NetworkMenuButton::SetTooltipAndAccessibleName(const string16& label) {\n SetTooltipText(UTF16ToWide(label));\n SetAccessibleName(label);\n}\n\n} \/\/ namespace chromeos\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/app\/chrome_command_ids.h\"\n#include \"chrome\/browser\/automation\/automation_util.h\"\n#include \"chrome\/browser\/tab_contents\/render_view_context_menu.h\"\n#include \"chrome\/browser\/extensions\/extension_test_message_listener.h\"\n#include \"chrome\/browser\/extensions\/platform_app_browsertest_util.h\"\n#include \"chrome\/browser\/extensions\/shell_window_registry.h\"\n#include \"chrome\/browser\/ui\/browser.h\"\n#include \"chrome\/browser\/ui\/browser_tabstrip.h\"\n#include \"chrome\/browser\/ui\/extensions\/shell_window.h\"\n#include \"chrome\/common\/chrome_notification_types.h\"\n#include \"chrome\/test\/base\/ui_test_utils.h\"\n#include \"content\/public\/browser\/render_process_host.h\"\n\nusing content::WebContents;\nusing extensions::Extension;\n\nnamespace {\n\/\/ Non-abstract RenderViewContextMenu class.\nclass PlatformAppContextMenu : public RenderViewContextMenu {\n public:\n PlatformAppContextMenu(WebContents* web_contents,\n const content::ContextMenuParams& params)\n : RenderViewContextMenu(web_contents, params) {}\n\n bool HasCommandWithId(int command_id) {\n return menu_model_.GetIndexOfCommandId(command_id) != -1;\n }\n\n protected:\n \/\/ These two functions implement pure virtual methods of\n \/\/ RenderViewContextMenu.\n virtual bool GetAcceleratorForCommandId(int command_id,\n ui::Accelerator* accelerator) {\n return false;\n }\n virtual void PlatformInit() {}\n virtual void PlatformCancel() {}\n};\n\n} \/\/ namespace\n\n\/\/ Tests that CreateShellWindow doesn't crash if you close it straight away.\n\/\/ LauncherPlatformAppBrowserTest relies on this behaviour, but is only run for\n\/\/ ash, so we test that it works here.\nIN_PROC_BROWSER_TEST_F(PlatformAppBrowserTest, CreateAndCloseShellWindow) {\n const Extension* extension = LoadAndLaunchPlatformApp(\"minimal\");\n ShellWindow* window = CreateShellWindow(extension);\n CloseShellWindow(window);\n}\n\n\/\/ Tests that platform apps received the \"launch\" event when launched.\nIN_PROC_BROWSER_TEST_F(PlatformAppBrowserTest, OnLaunchedEvent) {\n ASSERT_TRUE(RunPlatformAppTest(\"platform_apps\/launch\")) << message_;\n}\n\nIN_PROC_BROWSER_TEST_F(PlatformAppBrowserTest, EmptyContextMenu) {\n ExtensionTestMessageListener launched_listener(\"Launched\", false);\n LoadAndLaunchPlatformApp(\"minimal\");\n\n ASSERT_TRUE(launched_listener.WaitUntilSatisfied());\n\n \/\/ The empty app doesn't add any context menu items, so its menu should\n \/\/ only include the developer tools.\n WebContents* web_contents = GetFirstShellWindowWebContents();\n ASSERT_TRUE(web_contents);\n WebKit::WebContextMenuData data;\n content::ContextMenuParams params(data);\n PlatformAppContextMenu* menu = new PlatformAppContextMenu(web_contents,\n params);\n menu->Init();\n ASSERT_TRUE(menu->HasCommandWithId(IDC_CONTENT_CONTEXT_INSPECTELEMENT));\n ASSERT_TRUE(menu->HasCommandWithId(IDC_RELOAD));\n ASSERT_FALSE(menu->HasCommandWithId(IDC_BACK));\n ASSERT_FALSE(menu->HasCommandWithId(IDC_SAVE_PAGE));\n}\n\nIN_PROC_BROWSER_TEST_F(PlatformAppBrowserTest, AppWithContextMenu) {\n ExtensionTestMessageListener launched_listener(\"Launched\", false);\n LoadAndLaunchPlatformApp(\"context_menu\");\n\n \/\/ Wait for the extension to tell us it's initialized its context menus and\n \/\/ launched a window.\n ASSERT_TRUE(launched_listener.WaitUntilSatisfied());\n\n \/\/ The context_menu app has one context menu item. This, along with a\n \/\/ separator and the developer tools, is all that should be in the menu.\n WebContents* web_contents = GetFirstShellWindowWebContents();\n ASSERT_TRUE(web_contents);\n WebKit::WebContextMenuData data;\n content::ContextMenuParams params(data);\n PlatformAppContextMenu* menu = new PlatformAppContextMenu(web_contents,\n params);\n menu->Init();\n ASSERT_TRUE(menu->HasCommandWithId(IDC_EXTENSIONS_CONTEXT_CUSTOM_FIRST));\n ASSERT_TRUE(menu->HasCommandWithId(IDC_CONTENT_CONTEXT_INSPECTELEMENT));\n ASSERT_TRUE(menu->HasCommandWithId(IDC_RELOAD));\n ASSERT_FALSE(menu->HasCommandWithId(IDC_BACK));\n ASSERT_FALSE(menu->HasCommandWithId(IDC_SAVE_PAGE));\n}\n\nIN_PROC_BROWSER_TEST_F(PlatformAppBrowserTest, DisallowNavigation) {\n ASSERT_TRUE(StartTestServer());\n ASSERT_TRUE(RunPlatformAppTest(\"platform_apps\/navigation\")) << message_;\n}\n\nIN_PROC_BROWSER_TEST_F(PlatformAppBrowserTest, Iframes) {\n ASSERT_TRUE(StartTestServer());\n ASSERT_TRUE(RunPlatformAppTest(\"platform_apps\/iframes\")) << message_;\n}\n\n\/\/ Tests that localStorage and WebSQL are disabled for platform apps.\nIN_PROC_BROWSER_TEST_F(PlatformAppBrowserTest, DisallowStorage) {\n ASSERT_TRUE(RunPlatformAppTest(\"platform_apps\/storage\")) << message_;\n}\n\nIN_PROC_BROWSER_TEST_F(PlatformAppBrowserTest, Restrictions) {\n ASSERT_TRUE(RunPlatformAppTest(\"platform_apps\/restrictions\")) << message_;\n}\n\n\/\/ Tests that platform apps can use the chrome.appWindow.* API.\nIN_PROC_BROWSER_TEST_F(PlatformAppBrowserTest, WindowsApi) {\n ASSERT_TRUE(RunPlatformAppTest(\"platform_apps\/windows_api\")) << message_;\n}\n\n\/\/ Tests that platform apps have isolated storage by default.\nIN_PROC_BROWSER_TEST_F(PlatformAppBrowserTest, Isolation) {\n ASSERT_TRUE(StartTestServer());\n\n \/\/ Load a (non-app) page under the \"localhost\" origin that sets a cookie.\n GURL set_cookie_url = test_server()->GetURL(\n \"files\/extensions\/platform_apps\/isolation\/set_cookie.html\");\n GURL::Replacements replace_host;\n std::string host_str(\"localhost\"); \/\/ Must stay in scope with replace_host.\n replace_host.SetHostStr(host_str);\n set_cookie_url = set_cookie_url.ReplaceComponents(replace_host);\n\n ui_test_utils::NavigateToURLWithDisposition(\n browser(), set_cookie_url,\n CURRENT_TAB, ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION);\n\n \/\/ Make sure the cookie is set.\n int cookie_size;\n std::string cookie_value;\n automation_util::GetCookies(\n set_cookie_url,\n chrome::GetWebContentsAt(browser(), 0),\n &cookie_size,\n &cookie_value);\n ASSERT_EQ(\"testCookie=1\", cookie_value);\n\n \/\/ Let the platform app request the same URL, and make sure that it doesn't\n \/\/ see the cookie.\n ASSERT_TRUE(RunPlatformAppTest(\"platform_apps\/isolation\")) << message_;\n}\n\nIN_PROC_BROWSER_TEST_F(PlatformAppBrowserTest, ExtensionWindowingApis) {\n \/\/ Initially there should be just the one browser window visible to the\n \/\/ extensions API.\n const Extension* extension = LoadExtension(\n test_data_dir_.AppendASCII(\"common\/background_page\"));\n ASSERT_EQ(1U, RunGetWindowsFunctionForExtension(extension));\n\n \/\/ And no shell windows.\n ASSERT_EQ(0U, GetShellWindowCount());\n\n \/\/ Launch a platform app that shows a window.\n ExtensionTestMessageListener launched_listener(\"Launched\", false);\n LoadAndLaunchPlatformApp(\"minimal\");\n ASSERT_TRUE(launched_listener.WaitUntilSatisfied());\n ASSERT_EQ(1U, GetShellWindowCount());\n ShellWindowRegistry::ShellWindowSet shell_windows =\n ShellWindowRegistry::Get(browser()->profile())->shell_windows();\n int shell_window_id = (*shell_windows.begin())->session_id().id();\n\n \/\/ But it's not visible to the extensions API, it still thinks there's just\n \/\/ one browser window.\n ASSERT_EQ(1U, RunGetWindowsFunctionForExtension(extension));\n \/\/ It can't look it up by ID either\n ASSERT_FALSE(RunGetWindowFunctionForExtension(shell_window_id, extension));\n\n \/\/ The app can also only see one window (its own).\n \/\/ TODO(jeremya): add an extension function to get a shell window by ID, and\n \/\/ to get a list of all the shell windows, so we can test this.\n\n \/\/ Launch another platform app that also shows a window.\n ExtensionTestMessageListener launched_listener2(\"Launched\", false);\n LoadAndLaunchPlatformApp(\"context_menu\");\n ASSERT_TRUE(launched_listener2.WaitUntilSatisfied());\n\n \/\/ There are two total shell windows, but each app can only see its own.\n ASSERT_EQ(2U, GetShellWindowCount());\n \/\/ TODO(jeremya): as above, this requires more extension functions.\n}\n\n\/\/ TODO(benwells): fix these tests for ChromeOS.\n#if !defined(OS_CHROMEOS)\n\/\/ Tests that command line parameters get passed through to platform apps\n\/\/ via launchData correctly when launching with a file.\nIN_PROC_BROWSER_TEST_F(PlatformAppBrowserTest, LaunchWithFile) {\n SetCommandLineArg( \"platform_apps\/launch_files\/test.txt\");\n ASSERT_TRUE(RunPlatformAppTest(\"platform_apps\/launch_file\"))\n << message_;\n}\n\n\/\/ Tests that no launch data is sent through if the platform app provides\n\/\/ an intent with the wrong action.\nIN_PROC_BROWSER_TEST_F(PlatformAppBrowserTest, LaunchWithWrongIntent) {\n SetCommandLineArg(\"platform_apps\/launch_files\/test.txt\");\n ASSERT_TRUE(RunPlatformAppTest(\"platform_apps\/launch_wrong_intent\"))\n << message_;\n}\n\n\/\/ Tests that no launch data is sent through if the file is of the wrong MIME\n\/\/ type.\nIN_PROC_BROWSER_TEST_F(PlatformAppBrowserTest, LaunchWithWrongType) {\n SetCommandLineArg(\"platform_apps\/launch_files\/test.txt\");\n ASSERT_TRUE(RunPlatformAppTest(\"platform_apps\/launch_wrong_type\"))\n << message_;\n}\n\n\/\/ Tests that no launch data is sent through if the platform app does not\n\/\/ provide an intent.\nIN_PROC_BROWSER_TEST_F(PlatformAppBrowserTest, LaunchWithNoIntent) {\n SetCommandLineArg(\"platform_apps\/launch_files\/test.txt\");\n ASSERT_TRUE(RunPlatformAppTest(\"platform_apps\/launch_no_intent\"))\n << message_;\n}\n\n\/\/ Tests that no launch data is sent through if the file MIME type cannot\n\/\/ be read.\nIN_PROC_BROWSER_TEST_F(PlatformAppBrowserTest, LaunchNoType) {\n SetCommandLineArg(\"platform_apps\/launch_files\/test.unknownextension\");\n ASSERT_TRUE(RunPlatformAppTest(\"platform_apps\/launch_invalid\"))\n << message_;\n}\n\n\/\/ Tests that no launch data is sent through if the file does not exist.\nIN_PROC_BROWSER_TEST_F(PlatformAppBrowserTest, LaunchNoFile) {\n SetCommandLineArg(\"platform_apps\/launch_files\/doesnotexist.txt\");\n ASSERT_TRUE(RunPlatformAppTest(\"platform_apps\/launch_invalid\"))\n << message_;\n}\n\n\/\/ Tests that no launch data is sent through if the argument is a directory.\nIN_PROC_BROWSER_TEST_F(PlatformAppBrowserTest, LaunchWithDirectory) {\n SetCommandLineArg(\"platform_apps\/launch_files\");\n ASSERT_TRUE(RunPlatformAppTest(\"platform_apps\/launch_invalid\"))\n << message_;\n}\n\n\/\/ Tests that no launch data is sent through if there are no arguments passed\n\/\/ on the command line\nIN_PROC_BROWSER_TEST_F(PlatformAppBrowserTest, LaunchWithNothing) {\n ClearCommandLineArgs();\n ASSERT_TRUE(RunPlatformAppTest(\"platform_apps\/launch_nothing\"))\n << message_;\n}\n\n\/\/ Test that platform apps can use the chrome.fileSystem.getDisplayPath\n\/\/ function to get the native file system path of a file they are launched with.\nIN_PROC_BROWSER_TEST_F(PlatformAppBrowserTest, GetDisplayPath) {\n SetCommandLineArg(\"platform_apps\/launch_files\/test.txt\");\n ASSERT_TRUE(RunPlatformAppTest(\"platform_apps\/get_display_path\"))\n << message_;\n}\n\n#endif \/\/ defined(OS_CHROMEOS)\n\nIN_PROC_BROWSER_TEST_F(PlatformAppBrowserTest, OpenLink) {\n ASSERT_TRUE(StartTestServer());\n ui_test_utils::WindowedNotificationObserver observer(\n chrome::NOTIFICATION_TAB_ADDED,\n content::Source<content::WebContentsDelegate>(browser()));\n LoadAndLaunchPlatformApp(\"open_link\");\n observer.Wait();\n ASSERT_EQ(2, browser()->tab_count());\n}\n\nIN_PROC_BROWSER_TEST_F(PlatformAppBrowserTest, BrowserTag) {\n ASSERT_TRUE(RunPlatformAppTest(\"platform_apps\/browser_tag\")) << message_;\n}\n\nIN_PROC_BROWSER_TEST_F(PlatformAppBrowserTest, BrowserTagIsolation) {\n ASSERT_TRUE(StartTestServer());\n\n \/\/ Load a (non-app) page under the \"localhost\" origin that sets a cookie.\n GURL set_cookie_url = test_server()->GetURL(\n \"files\/extensions\/platform_apps\/isolation\/set_cookie.html\");\n GURL::Replacements replace_host;\n std::string host_str(\"localhost\"); \/\/ Must stay in scope with replace_host.\n replace_host.SetHostStr(host_str);\n set_cookie_url = set_cookie_url.ReplaceComponents(replace_host);\n\n ui_test_utils::NavigateToURLWithDisposition(\n browser(), set_cookie_url,\n CURRENT_TAB, ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION);\n\n \/\/ Make sure the cookie is set.\n int cookie_size;\n std::string cookie_value;\n automation_util::GetCookies(set_cookie_url,\n chrome::GetWebContentsAt(browser(), 0),\n &cookie_size, &cookie_value);\n ASSERT_EQ(\"testCookie=1\", cookie_value);\n\n \/\/ Create a listener to JS message to know when the app has launched.\n ExtensionTestMessageListener launched_listener(\"Launched\", false);\n LoadAndLaunchPlatformApp(\"browser_tag_isolation\");\n ASSERT_TRUE(launched_listener.WaitUntilSatisfied());\n\n ui_test_utils::WindowedNotificationObserver load_stop_observer(\n content::NOTIFICATION_LOAD_STOP,\n content::NotificationService::AllSources());\n load_stop_observer.Wait();\n content::Source<content::NavigationController> source =\n load_stop_observer.source();\n\n \/\/ Test the regular browser context to ensure we still have only one cookie.\n automation_util::GetCookies(GURL(\"http:\/\/localhost\"),\n chrome::GetWebContentsAt(browser(), 0),\n &cookie_size, &cookie_value);\n ASSERT_EQ(\"testCookie=1\", cookie_value);\n\n ASSERT_TRUE(source->GetWebContents()->GetRenderProcessHost()->IsGuest());\n\n \/\/ Now, test the browser tag to ensure we have properly set the cookie and\n \/\/ we have only one.\n automation_util::GetCookies(GURL(\"http:\/\/localhost\"),\n source->GetWebContents(),\n &cookie_size, &cookie_value);\n ASSERT_EQ(\"isolation_guest=true\", cookie_value);\n}\n<commit_msg>Disable PlatformAppBrowserTest.BrowserTagIsolation because it crashes on chromiumos<commit_after>\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/app\/chrome_command_ids.h\"\n#include \"chrome\/browser\/automation\/automation_util.h\"\n#include \"chrome\/browser\/tab_contents\/render_view_context_menu.h\"\n#include \"chrome\/browser\/extensions\/extension_test_message_listener.h\"\n#include \"chrome\/browser\/extensions\/platform_app_browsertest_util.h\"\n#include \"chrome\/browser\/extensions\/shell_window_registry.h\"\n#include \"chrome\/browser\/ui\/browser.h\"\n#include \"chrome\/browser\/ui\/browser_tabstrip.h\"\n#include \"chrome\/browser\/ui\/extensions\/shell_window.h\"\n#include \"chrome\/common\/chrome_notification_types.h\"\n#include \"chrome\/test\/base\/ui_test_utils.h\"\n#include \"content\/public\/browser\/render_process_host.h\"\n\nusing content::WebContents;\nusing extensions::Extension;\n\nnamespace {\n\/\/ Non-abstract RenderViewContextMenu class.\nclass PlatformAppContextMenu : public RenderViewContextMenu {\n public:\n PlatformAppContextMenu(WebContents* web_contents,\n const content::ContextMenuParams& params)\n : RenderViewContextMenu(web_contents, params) {}\n\n bool HasCommandWithId(int command_id) {\n return menu_model_.GetIndexOfCommandId(command_id) != -1;\n }\n\n protected:\n \/\/ These two functions implement pure virtual methods of\n \/\/ RenderViewContextMenu.\n virtual bool GetAcceleratorForCommandId(int command_id,\n ui::Accelerator* accelerator) {\n return false;\n }\n virtual void PlatformInit() {}\n virtual void PlatformCancel() {}\n};\n\n} \/\/ namespace\n\n\/\/ Tests that CreateShellWindow doesn't crash if you close it straight away.\n\/\/ LauncherPlatformAppBrowserTest relies on this behaviour, but is only run for\n\/\/ ash, so we test that it works here.\nIN_PROC_BROWSER_TEST_F(PlatformAppBrowserTest, CreateAndCloseShellWindow) {\n const Extension* extension = LoadAndLaunchPlatformApp(\"minimal\");\n ShellWindow* window = CreateShellWindow(extension);\n CloseShellWindow(window);\n}\n\n\/\/ Tests that platform apps received the \"launch\" event when launched.\nIN_PROC_BROWSER_TEST_F(PlatformAppBrowserTest, OnLaunchedEvent) {\n ASSERT_TRUE(RunPlatformAppTest(\"platform_apps\/launch\")) << message_;\n}\n\nIN_PROC_BROWSER_TEST_F(PlatformAppBrowserTest, EmptyContextMenu) {\n ExtensionTestMessageListener launched_listener(\"Launched\", false);\n LoadAndLaunchPlatformApp(\"minimal\");\n\n ASSERT_TRUE(launched_listener.WaitUntilSatisfied());\n\n \/\/ The empty app doesn't add any context menu items, so its menu should\n \/\/ only include the developer tools.\n WebContents* web_contents = GetFirstShellWindowWebContents();\n ASSERT_TRUE(web_contents);\n WebKit::WebContextMenuData data;\n content::ContextMenuParams params(data);\n PlatformAppContextMenu* menu = new PlatformAppContextMenu(web_contents,\n params);\n menu->Init();\n ASSERT_TRUE(menu->HasCommandWithId(IDC_CONTENT_CONTEXT_INSPECTELEMENT));\n ASSERT_TRUE(menu->HasCommandWithId(IDC_RELOAD));\n ASSERT_FALSE(menu->HasCommandWithId(IDC_BACK));\n ASSERT_FALSE(menu->HasCommandWithId(IDC_SAVE_PAGE));\n}\n\nIN_PROC_BROWSER_TEST_F(PlatformAppBrowserTest, AppWithContextMenu) {\n ExtensionTestMessageListener launched_listener(\"Launched\", false);\n LoadAndLaunchPlatformApp(\"context_menu\");\n\n \/\/ Wait for the extension to tell us it's initialized its context menus and\n \/\/ launched a window.\n ASSERT_TRUE(launched_listener.WaitUntilSatisfied());\n\n \/\/ The context_menu app has one context menu item. This, along with a\n \/\/ separator and the developer tools, is all that should be in the menu.\n WebContents* web_contents = GetFirstShellWindowWebContents();\n ASSERT_TRUE(web_contents);\n WebKit::WebContextMenuData data;\n content::ContextMenuParams params(data);\n PlatformAppContextMenu* menu = new PlatformAppContextMenu(web_contents,\n params);\n menu->Init();\n ASSERT_TRUE(menu->HasCommandWithId(IDC_EXTENSIONS_CONTEXT_CUSTOM_FIRST));\n ASSERT_TRUE(menu->HasCommandWithId(IDC_CONTENT_CONTEXT_INSPECTELEMENT));\n ASSERT_TRUE(menu->HasCommandWithId(IDC_RELOAD));\n ASSERT_FALSE(menu->HasCommandWithId(IDC_BACK));\n ASSERT_FALSE(menu->HasCommandWithId(IDC_SAVE_PAGE));\n}\n\nIN_PROC_BROWSER_TEST_F(PlatformAppBrowserTest, DisallowNavigation) {\n ASSERT_TRUE(StartTestServer());\n ASSERT_TRUE(RunPlatformAppTest(\"platform_apps\/navigation\")) << message_;\n}\n\nIN_PROC_BROWSER_TEST_F(PlatformAppBrowserTest, Iframes) {\n ASSERT_TRUE(StartTestServer());\n ASSERT_TRUE(RunPlatformAppTest(\"platform_apps\/iframes\")) << message_;\n}\n\n\/\/ Tests that localStorage and WebSQL are disabled for platform apps.\nIN_PROC_BROWSER_TEST_F(PlatformAppBrowserTest, DisallowStorage) {\n ASSERT_TRUE(RunPlatformAppTest(\"platform_apps\/storage\")) << message_;\n}\n\nIN_PROC_BROWSER_TEST_F(PlatformAppBrowserTest, Restrictions) {\n ASSERT_TRUE(RunPlatformAppTest(\"platform_apps\/restrictions\")) << message_;\n}\n\n\/\/ Tests that platform apps can use the chrome.appWindow.* API.\nIN_PROC_BROWSER_TEST_F(PlatformAppBrowserTest, WindowsApi) {\n ASSERT_TRUE(RunPlatformAppTest(\"platform_apps\/windows_api\")) << message_;\n}\n\n\/\/ Tests that platform apps have isolated storage by default.\nIN_PROC_BROWSER_TEST_F(PlatformAppBrowserTest, Isolation) {\n ASSERT_TRUE(StartTestServer());\n\n \/\/ Load a (non-app) page under the \"localhost\" origin that sets a cookie.\n GURL set_cookie_url = test_server()->GetURL(\n \"files\/extensions\/platform_apps\/isolation\/set_cookie.html\");\n GURL::Replacements replace_host;\n std::string host_str(\"localhost\"); \/\/ Must stay in scope with replace_host.\n replace_host.SetHostStr(host_str);\n set_cookie_url = set_cookie_url.ReplaceComponents(replace_host);\n\n ui_test_utils::NavigateToURLWithDisposition(\n browser(), set_cookie_url,\n CURRENT_TAB, ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION);\n\n \/\/ Make sure the cookie is set.\n int cookie_size;\n std::string cookie_value;\n automation_util::GetCookies(\n set_cookie_url,\n chrome::GetWebContentsAt(browser(), 0),\n &cookie_size,\n &cookie_value);\n ASSERT_EQ(\"testCookie=1\", cookie_value);\n\n \/\/ Let the platform app request the same URL, and make sure that it doesn't\n \/\/ see the cookie.\n ASSERT_TRUE(RunPlatformAppTest(\"platform_apps\/isolation\")) << message_;\n}\n\nIN_PROC_BROWSER_TEST_F(PlatformAppBrowserTest, ExtensionWindowingApis) {\n \/\/ Initially there should be just the one browser window visible to the\n \/\/ extensions API.\n const Extension* extension = LoadExtension(\n test_data_dir_.AppendASCII(\"common\/background_page\"));\n ASSERT_EQ(1U, RunGetWindowsFunctionForExtension(extension));\n\n \/\/ And no shell windows.\n ASSERT_EQ(0U, GetShellWindowCount());\n\n \/\/ Launch a platform app that shows a window.\n ExtensionTestMessageListener launched_listener(\"Launched\", false);\n LoadAndLaunchPlatformApp(\"minimal\");\n ASSERT_TRUE(launched_listener.WaitUntilSatisfied());\n ASSERT_EQ(1U, GetShellWindowCount());\n ShellWindowRegistry::ShellWindowSet shell_windows =\n ShellWindowRegistry::Get(browser()->profile())->shell_windows();\n int shell_window_id = (*shell_windows.begin())->session_id().id();\n\n \/\/ But it's not visible to the extensions API, it still thinks there's just\n \/\/ one browser window.\n ASSERT_EQ(1U, RunGetWindowsFunctionForExtension(extension));\n \/\/ It can't look it up by ID either\n ASSERT_FALSE(RunGetWindowFunctionForExtension(shell_window_id, extension));\n\n \/\/ The app can also only see one window (its own).\n \/\/ TODO(jeremya): add an extension function to get a shell window by ID, and\n \/\/ to get a list of all the shell windows, so we can test this.\n\n \/\/ Launch another platform app that also shows a window.\n ExtensionTestMessageListener launched_listener2(\"Launched\", false);\n LoadAndLaunchPlatformApp(\"context_menu\");\n ASSERT_TRUE(launched_listener2.WaitUntilSatisfied());\n\n \/\/ There are two total shell windows, but each app can only see its own.\n ASSERT_EQ(2U, GetShellWindowCount());\n \/\/ TODO(jeremya): as above, this requires more extension functions.\n}\n\n\/\/ TODO(benwells): fix these tests for ChromeOS.\n#if !defined(OS_CHROMEOS)\n\/\/ Tests that command line parameters get passed through to platform apps\n\/\/ via launchData correctly when launching with a file.\nIN_PROC_BROWSER_TEST_F(PlatformAppBrowserTest, LaunchWithFile) {\n SetCommandLineArg( \"platform_apps\/launch_files\/test.txt\");\n ASSERT_TRUE(RunPlatformAppTest(\"platform_apps\/launch_file\"))\n << message_;\n}\n\n\/\/ Tests that no launch data is sent through if the platform app provides\n\/\/ an intent with the wrong action.\nIN_PROC_BROWSER_TEST_F(PlatformAppBrowserTest, LaunchWithWrongIntent) {\n SetCommandLineArg(\"platform_apps\/launch_files\/test.txt\");\n ASSERT_TRUE(RunPlatformAppTest(\"platform_apps\/launch_wrong_intent\"))\n << message_;\n}\n\n\/\/ Tests that no launch data is sent through if the file is of the wrong MIME\n\/\/ type.\nIN_PROC_BROWSER_TEST_F(PlatformAppBrowserTest, LaunchWithWrongType) {\n SetCommandLineArg(\"platform_apps\/launch_files\/test.txt\");\n ASSERT_TRUE(RunPlatformAppTest(\"platform_apps\/launch_wrong_type\"))\n << message_;\n}\n\n\/\/ Tests that no launch data is sent through if the platform app does not\n\/\/ provide an intent.\nIN_PROC_BROWSER_TEST_F(PlatformAppBrowserTest, LaunchWithNoIntent) {\n SetCommandLineArg(\"platform_apps\/launch_files\/test.txt\");\n ASSERT_TRUE(RunPlatformAppTest(\"platform_apps\/launch_no_intent\"))\n << message_;\n}\n\n\/\/ Tests that no launch data is sent through if the file MIME type cannot\n\/\/ be read.\nIN_PROC_BROWSER_TEST_F(PlatformAppBrowserTest, LaunchNoType) {\n SetCommandLineArg(\"platform_apps\/launch_files\/test.unknownextension\");\n ASSERT_TRUE(RunPlatformAppTest(\"platform_apps\/launch_invalid\"))\n << message_;\n}\n\n\/\/ Tests that no launch data is sent through if the file does not exist.\nIN_PROC_BROWSER_TEST_F(PlatformAppBrowserTest, LaunchNoFile) {\n SetCommandLineArg(\"platform_apps\/launch_files\/doesnotexist.txt\");\n ASSERT_TRUE(RunPlatformAppTest(\"platform_apps\/launch_invalid\"))\n << message_;\n}\n\n\/\/ Tests that no launch data is sent through if the argument is a directory.\nIN_PROC_BROWSER_TEST_F(PlatformAppBrowserTest, LaunchWithDirectory) {\n SetCommandLineArg(\"platform_apps\/launch_files\");\n ASSERT_TRUE(RunPlatformAppTest(\"platform_apps\/launch_invalid\"))\n << message_;\n}\n\n\/\/ Tests that no launch data is sent through if there are no arguments passed\n\/\/ on the command line\nIN_PROC_BROWSER_TEST_F(PlatformAppBrowserTest, LaunchWithNothing) {\n ClearCommandLineArgs();\n ASSERT_TRUE(RunPlatformAppTest(\"platform_apps\/launch_nothing\"))\n << message_;\n}\n\n\/\/ Test that platform apps can use the chrome.fileSystem.getDisplayPath\n\/\/ function to get the native file system path of a file they are launched with.\nIN_PROC_BROWSER_TEST_F(PlatformAppBrowserTest, GetDisplayPath) {\n SetCommandLineArg(\"platform_apps\/launch_files\/test.txt\");\n ASSERT_TRUE(RunPlatformAppTest(\"platform_apps\/get_display_path\"))\n << message_;\n}\n\n#endif \/\/ defined(OS_CHROMEOS)\n\nIN_PROC_BROWSER_TEST_F(PlatformAppBrowserTest, OpenLink) {\n ASSERT_TRUE(StartTestServer());\n ui_test_utils::WindowedNotificationObserver observer(\n chrome::NOTIFICATION_TAB_ADDED,\n content::Source<content::WebContentsDelegate>(browser()));\n LoadAndLaunchPlatformApp(\"open_link\");\n observer.Wait();\n ASSERT_EQ(2, browser()->tab_count());\n}\n\nIN_PROC_BROWSER_TEST_F(PlatformAppBrowserTest, BrowserTag) {\n ASSERT_TRUE(RunPlatformAppTest(\"platform_apps\/browser_tag\")) << message_;\n}\n\n\/\/ This test is disabled. nasko is working on a fix and it should be committed\n\/\/ within the hour. The test crashed on linux chromiumos.\nIN_PROC_BROWSER_TEST_F(PlatformAppBrowserTest, DISABLED_BrowserTagIsolation) {\n ASSERT_TRUE(StartTestServer());\n\n \/\/ Load a (non-app) page under the \"localhost\" origin that sets a cookie.\n GURL set_cookie_url = test_server()->GetURL(\n \"files\/extensions\/platform_apps\/isolation\/set_cookie.html\");\n GURL::Replacements replace_host;\n std::string host_str(\"localhost\"); \/\/ Must stay in scope with replace_host.\n replace_host.SetHostStr(host_str);\n set_cookie_url = set_cookie_url.ReplaceComponents(replace_host);\n\n ui_test_utils::NavigateToURLWithDisposition(\n browser(), set_cookie_url,\n CURRENT_TAB, ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION);\n\n \/\/ Make sure the cookie is set.\n int cookie_size;\n std::string cookie_value;\n automation_util::GetCookies(set_cookie_url,\n chrome::GetWebContentsAt(browser(), 0),\n &cookie_size, &cookie_value);\n ASSERT_EQ(\"testCookie=1\", cookie_value);\n\n \/\/ Create a listener to JS message to know when the app has launched.\n ExtensionTestMessageListener launched_listener(\"Launched\", false);\n LoadAndLaunchPlatformApp(\"browser_tag_isolation\");\n ASSERT_TRUE(launched_listener.WaitUntilSatisfied());\n\n ui_test_utils::WindowedNotificationObserver load_stop_observer(\n content::NOTIFICATION_LOAD_STOP,\n content::NotificationService::AllSources());\n load_stop_observer.Wait();\n content::Source<content::NavigationController> source =\n load_stop_observer.source();\n\n \/\/ Test the regular browser context to ensure we still have only one cookie.\n automation_util::GetCookies(GURL(\"http:\/\/localhost\"),\n chrome::GetWebContentsAt(browser(), 0),\n &cookie_size, &cookie_value);\n ASSERT_EQ(\"testCookie=1\", cookie_value);\n\n ASSERT_TRUE(source->GetWebContents()->GetRenderProcessHost()->IsGuest());\n\n \/\/ Now, test the browser tag to ensure we have properly set the cookie and\n \/\/ we have only one.\n automation_util::GetCookies(GURL(\"http:\/\/localhost\"),\n source->GetWebContents(),\n &cookie_size, &cookie_value);\n ASSERT_EQ(\"isolation_guest=true\", cookie_value);\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2013 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/prefs\/pref_hash_calculator.h\"\n\n#include <string>\n\n#include \"base\/values.h\"\n#include \"testing\/gtest\/include\/gtest\/gtest.h\"\n\nTEST(PrefHashCalculatorTest, TestCurrentAlgorithm) {\n base::StringValue string_value_1(\"string value 1\");\n base::StringValue string_value_2(\"string value 2\");\n base::DictionaryValue dictionary_value_1;\n dictionary_value_1.SetInteger(\"int value\", 1);\n dictionary_value_1.Set(\"nested empty map\", new base::DictionaryValue);\n base::DictionaryValue dictionary_value_1_equivalent;\n dictionary_value_1_equivalent.SetInteger(\"int value\", 1);\n base::DictionaryValue dictionary_value_2;\n dictionary_value_2.SetInteger(\"int value\", 2);\n\n PrefHashCalculator calc1(\"seed1\", \"deviceid\");\n PrefHashCalculator calc1_dup(\"seed1\", \"deviceid\");\n PrefHashCalculator calc2(\"seed2\", \"deviceid\");\n PrefHashCalculator calc3(\"seed1\", \"deviceid2\");\n\n \/\/ Two calculators with same seed produce same hash.\n ASSERT_EQ(calc1.Calculate(\"pref_path\", &string_value_1),\n calc1_dup.Calculate(\"pref_path\", &string_value_1));\n ASSERT_EQ(PrefHashCalculator::VALID,\n calc1_dup.Validate(\n \"pref_path\",\n &string_value_1,\n calc1.Calculate(\"pref_path\", &string_value_1)));\n\n \/\/ Different seeds, different hashes.\n ASSERT_NE(calc1.Calculate(\"pref_path\", &string_value_1),\n calc2.Calculate(\"pref_path\", &string_value_1));\n ASSERT_EQ(PrefHashCalculator::INVALID,\n calc2.Validate(\n \"pref_path\",\n &string_value_1,\n calc1.Calculate(\"pref_path\", &string_value_1)));\n\n \/\/ Different device IDs, different hashes.\n ASSERT_NE(calc1.Calculate(\"pref_path\", &string_value_1),\n calc3.Calculate(\"pref_path\", &string_value_1));\n\n \/\/ Different values, different hashes.\n ASSERT_NE(calc1.Calculate(\"pref_path\", &string_value_1),\n calc1.Calculate(\"pref_path\", &string_value_2));\n\n \/\/ Different paths, different hashes.\n ASSERT_NE(calc1.Calculate(\"pref_path\", &string_value_1),\n calc1.Calculate(\"pref_path_2\", &string_value_1));\n\n \/\/ Works for dictionaries.\n ASSERT_EQ(calc1.Calculate(\"pref_path\", &dictionary_value_1),\n calc1.Calculate(\"pref_path\", &dictionary_value_1));\n ASSERT_NE(calc1.Calculate(\"pref_path\", &dictionary_value_1),\n calc1.Calculate(\"pref_path\", &dictionary_value_2));\n\n \/\/ Empty dictionary children are pruned.\n ASSERT_EQ(calc1.Calculate(\"pref_path\", &dictionary_value_1),\n calc1.Calculate(\"pref_path\", &dictionary_value_1_equivalent));\n\n \/\/ NULL value is supported.\n ASSERT_FALSE(calc1.Calculate(\"pref_path\", NULL).empty());\n}\n\n\/\/ Tests the output against a known value to catch unexpected algorithm changes.\nTEST(PrefHashCalculatorTest, CatchHashChanges) {\n static const char kSeed[] = \"0123456789ABCDEF0123456789ABCDEF\";\n static const char kDeviceId[] = \"test_device_id1\";\n {\n static const char kExpectedValue[] =\n \"D8137B8E767D3D910DCD3821CAC61D26ABB042E6EC406AEB0E347ED73A3A4EC1\";\n\n base::ListValue list;\n list.Set(0, new base::FundamentalValue(true));\n list.Set(1, new base::FundamentalValue(100));\n list.Set(2, new base::FundamentalValue(1.0));\n\n EXPECT_EQ(PrefHashCalculator::VALID,\n PrefHashCalculator(kSeed, kDeviceId).Validate(\n \"pref.path2\", &list, kExpectedValue));\n }\n {\n static const char kExpectedValue[] =\n \"3F947A044DE9E421A735525385B4C789693682E6F6E3E4CB4741E58724B28F96\";\n\n base::DictionaryValue dict;\n dict.Set(\"a\", new base::StringValue(\"foo\"));\n dict.Set(\"d\", new base::StringValue(\"bad\"));\n dict.Set(\"b\", new base::StringValue(\"bar\"));\n dict.Set(\"c\", new base::StringValue(\"baz\"));\n\n EXPECT_EQ(PrefHashCalculator::VALID,\n PrefHashCalculator(kSeed, kDeviceId).Validate(\n \"pref.path1\", &dict, kExpectedValue));\n }\n}\n\nTEST(PrefHashCalculatorTest, TestCompatibilityWithPrefMetricsService) {\n static const char kSeed[] = {\n 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,\n 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F,\n 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,\n 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F,\n 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,\n 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F,\n 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,\n 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F\n };\n static const char kDeviceId[] =\n \"D730D9CBD98C734A4FB097A1922275FE9F7E026A4EA1BE0E84\";\n static const char kExpectedValue[] =\n \"845EF34663FF8D32BE6707F40258FBA531C2BFC532E3B014AFB3476115C2A9DE\";\n\n base::ListValue startup_urls;\n startup_urls.Set(0, new base::StringValue(\"http:\/\/www.chromium.org\/\"));\n\n EXPECT_EQ(PrefHashCalculator::VALID,\n PrefHashCalculator(std::string(kSeed, arraysize(kSeed)), kDeviceId).\n Validate(\"session.startup_urls\", &startup_urls, kExpectedValue));\n}\n\nTEST(PrefHashCalculatorTest, TestLegacyAlgorithm) {\n static const char kExpectedValue[] =\n \"C503FB7C65EEFD5C07185F616A0AA67923C069909933F362022B1F187E73E9A2\";\n static const char kDeviceId[] = \"not_used\";\n\n base::DictionaryValue dict;\n dict.Set(\"a\", new base::StringValue(\"foo\"));\n dict.Set(\"d\", new base::StringValue(\"bad\"));\n dict.Set(\"b\", new base::StringValue(\"bar\"));\n dict.Set(\"c\", new base::StringValue(\"baz\"));\n\n \/\/ 32 NULL bytes is the seed that was used to generate the legacy hash.\n EXPECT_EQ(PrefHashCalculator::VALID_LEGACY,\n PrefHashCalculator(std::string(32u, 0), kDeviceId).Validate(\n \"pref.path1\", &dict, kExpectedValue));\n}\n<commit_msg>Ensure no changes to the JSONSerializer or PrefHashCalculator ever end up producing different hashes for all existing Value::Type.<commit_after>\/\/ Copyright 2013 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/prefs\/pref_hash_calculator.h\"\n\n#include <string>\n\n#include \"base\/memory\/scoped_ptr.h\"\n#include \"base\/values.h\"\n#include \"testing\/gtest\/include\/gtest\/gtest.h\"\n\nTEST(PrefHashCalculatorTest, TestCurrentAlgorithm) {\n base::StringValue string_value_1(\"string value 1\");\n base::StringValue string_value_2(\"string value 2\");\n base::DictionaryValue dictionary_value_1;\n dictionary_value_1.SetInteger(\"int value\", 1);\n dictionary_value_1.Set(\"nested empty map\", new base::DictionaryValue);\n base::DictionaryValue dictionary_value_1_equivalent;\n dictionary_value_1_equivalent.SetInteger(\"int value\", 1);\n base::DictionaryValue dictionary_value_2;\n dictionary_value_2.SetInteger(\"int value\", 2);\n\n PrefHashCalculator calc1(\"seed1\", \"deviceid\");\n PrefHashCalculator calc1_dup(\"seed1\", \"deviceid\");\n PrefHashCalculator calc2(\"seed2\", \"deviceid\");\n PrefHashCalculator calc3(\"seed1\", \"deviceid2\");\n\n \/\/ Two calculators with same seed produce same hash.\n ASSERT_EQ(calc1.Calculate(\"pref_path\", &string_value_1),\n calc1_dup.Calculate(\"pref_path\", &string_value_1));\n ASSERT_EQ(PrefHashCalculator::VALID,\n calc1_dup.Validate(\n \"pref_path\",\n &string_value_1,\n calc1.Calculate(\"pref_path\", &string_value_1)));\n\n \/\/ Different seeds, different hashes.\n ASSERT_NE(calc1.Calculate(\"pref_path\", &string_value_1),\n calc2.Calculate(\"pref_path\", &string_value_1));\n ASSERT_EQ(PrefHashCalculator::INVALID,\n calc2.Validate(\n \"pref_path\",\n &string_value_1,\n calc1.Calculate(\"pref_path\", &string_value_1)));\n\n \/\/ Different device IDs, different hashes.\n ASSERT_NE(calc1.Calculate(\"pref_path\", &string_value_1),\n calc3.Calculate(\"pref_path\", &string_value_1));\n\n \/\/ Different values, different hashes.\n ASSERT_NE(calc1.Calculate(\"pref_path\", &string_value_1),\n calc1.Calculate(\"pref_path\", &string_value_2));\n\n \/\/ Different paths, different hashes.\n ASSERT_NE(calc1.Calculate(\"pref_path\", &string_value_1),\n calc1.Calculate(\"pref_path_2\", &string_value_1));\n\n \/\/ Works for dictionaries.\n ASSERT_EQ(calc1.Calculate(\"pref_path\", &dictionary_value_1),\n calc1.Calculate(\"pref_path\", &dictionary_value_1));\n ASSERT_NE(calc1.Calculate(\"pref_path\", &dictionary_value_1),\n calc1.Calculate(\"pref_path\", &dictionary_value_2));\n\n \/\/ Empty dictionary children are pruned.\n ASSERT_EQ(calc1.Calculate(\"pref_path\", &dictionary_value_1),\n calc1.Calculate(\"pref_path\", &dictionary_value_1_equivalent));\n\n \/\/ NULL value is supported.\n ASSERT_FALSE(calc1.Calculate(\"pref_path\", NULL).empty());\n}\n\n\/\/ Tests the output against a known value to catch unexpected algorithm changes.\n\/\/ The test hashes below must NEVER be updated, the serialization algorithm used\n\/\/ must always be able to generate data that will produce these exact hashes.\nTEST(PrefHashCalculatorTest, CatchHashChanges) {\n static const char kSeed[] = \"0123456789ABCDEF0123456789ABCDEF\";\n static const char kDeviceId[] = \"test_device_id1\";\n\n scoped_ptr<base::Value> null_value(base::Value::CreateNullValue());\n scoped_ptr<base::Value> bool_value(base::Value::CreateBooleanValue(false));\n scoped_ptr<base::Value> int_value(\n base::Value::CreateIntegerValue(1234567890));\n scoped_ptr<base::Value> double_value(\n base::Value::CreateDoubleValue(123.0987654321));\n scoped_ptr<base::Value> string_value(base::Value::CreateStringValue(\n \"testing with special chars:\\n<>{}:^^@#$\\\\\/\"));\n\n scoped_ptr<base::DictionaryValue> dict_value(new base::DictionaryValue);\n dict_value->Set(\"a\", new base::StringValue(\"foo\"));\n dict_value->Set(\"d\", new base::StringValue(\"bad\"));\n dict_value->Set(\"b\", new base::StringValue(\"bar\"));\n dict_value->Set(\"c\", new base::StringValue(\"baz\"));\n\n scoped_ptr<base::ListValue> list_value(new base::ListValue);\n list_value->AppendBoolean(true);\n list_value->AppendInteger(100);\n list_value->AppendDouble(1.0);\n\n ASSERT_EQ(base::Value::TYPE_NULL, null_value->GetType());\n ASSERT_EQ(base::Value::TYPE_BOOLEAN, bool_value->GetType());\n ASSERT_EQ(base::Value::TYPE_INTEGER, int_value->GetType());\n ASSERT_EQ(base::Value::TYPE_DOUBLE, double_value->GetType());\n ASSERT_EQ(base::Value::TYPE_STRING, string_value->GetType());\n ASSERT_EQ(base::Value::TYPE_DICTIONARY, dict_value->GetType());\n ASSERT_EQ(base::Value::TYPE_LIST, list_value->GetType());\n\n \/\/ Test every value type independently. Intentionally omits TYPE_BINARY which\n \/\/ isn't even allowed in JSONWriter's input.\n static const char kExpectedNullValue[] =\n \"C2871D0AC76176E39948C50A9A562B863E610FDA90C675A6A8AD16B4DC4F53DC\";\n EXPECT_EQ(PrefHashCalculator::VALID,\n PrefHashCalculator(kSeed, kDeviceId).Validate(\n \"pref.path\", null_value.get(), kExpectedNullValue));\n\n static const char kExpectedBooleanValue[] =\n \"A326E2F405CFE05D08289CDADD9DB4F529592F0945A8CE204289E4C930D8AA43\";\n EXPECT_EQ(PrefHashCalculator::VALID,\n PrefHashCalculator(kSeed, kDeviceId).Validate(\n \"pref.path\", bool_value.get(), kExpectedBooleanValue));\n\n static const char kExpectedIntegerValue[] =\n \"4B69938F802A2A26D69467F3E1E4A474F6323C64EFC54DBDB4A5708A7D005042\";\n EXPECT_EQ(PrefHashCalculator::VALID,\n PrefHashCalculator(kSeed, kDeviceId).Validate(\n \"pref.path\", int_value.get(), kExpectedIntegerValue));\n\n static const char kExpectedDoubleValue[] =\n \"1734C9C745B9C92D896B9A710994BF1B56D55BFB0F00C207EC995152AF02F08F\";\n EXPECT_EQ(PrefHashCalculator::VALID,\n PrefHashCalculator(kSeed, kDeviceId).Validate(\n \"pref.path\", double_value.get(), kExpectedDoubleValue));\n\n static const char kExpectedStringValue[] =\n \"154D15522C856AA944BFA5A9E3FFB46925BF2B95A10199564651CA1C13E98433\";\n EXPECT_EQ(PrefHashCalculator::VALID,\n PrefHashCalculator(kSeed, kDeviceId).Validate(\n \"pref.path\", string_value.get(), kExpectedStringValue));\n\n static const char kExpectedDictValue[] =\n \"3F947A044DE9E421A735525385B4C789693682E6F6E3E4CB4741E58724B28F96\";\n EXPECT_EQ(PrefHashCalculator::VALID,\n PrefHashCalculator(kSeed, kDeviceId).Validate(\n \"pref.path1\", dict_value.get(), kExpectedDictValue));\n\n static const char kExpectedListValue[] =\n \"D8137B8E767D3D910DCD3821CAC61D26ABB042E6EC406AEB0E347ED73A3A4EC1\";\n EXPECT_EQ(PrefHashCalculator::VALID,\n PrefHashCalculator(kSeed, kDeviceId).Validate(\n \"pref.path2\", list_value.get(), kExpectedListValue));\n\n \/\/ Also test every value type together in the same dictionary.\n base::DictionaryValue everything;\n everything.Set(\"null\", null_value.release());\n everything.Set(\"bool\", bool_value.release());\n everything.Set(\"int\", int_value.release());\n everything.Set(\"double\", double_value.release());\n everything.Set(\"string\", string_value.release());\n everything.Set(\"list\", list_value.release());\n everything.Set(\"dict\", dict_value.release());\n static const char kExpectedEverythingValue[] =\n \"0A546480C7AB7699779B2FCFA326D65E0AE1446EA62398AE1D338119C6913943\";\n EXPECT_EQ(PrefHashCalculator::VALID,\n PrefHashCalculator(kSeed, kDeviceId).Validate(\n \"pref.path1\", &everything, kExpectedEverythingValue));\n}\n\nTEST(PrefHashCalculatorTest, TestCompatibilityWithPrefMetricsService) {\n static const char kSeed[] = {\n 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,\n 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F,\n 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,\n 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F,\n 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,\n 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F,\n 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,\n 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F\n };\n static const char kDeviceId[] =\n \"D730D9CBD98C734A4FB097A1922275FE9F7E026A4EA1BE0E84\";\n static const char kExpectedValue[] =\n \"845EF34663FF8D32BE6707F40258FBA531C2BFC532E3B014AFB3476115C2A9DE\";\n\n base::ListValue startup_urls;\n startup_urls.Set(0, new base::StringValue(\"http:\/\/www.chromium.org\/\"));\n\n EXPECT_EQ(PrefHashCalculator::VALID,\n PrefHashCalculator(std::string(kSeed, arraysize(kSeed)), kDeviceId).\n Validate(\"session.startup_urls\", &startup_urls, kExpectedValue));\n}\n\nTEST(PrefHashCalculatorTest, TestLegacyAlgorithm) {\n static const char kExpectedValue[] =\n \"C503FB7C65EEFD5C07185F616A0AA67923C069909933F362022B1F187E73E9A2\";\n static const char kDeviceId[] = \"not_used\";\n\n base::DictionaryValue dict;\n dict.Set(\"a\", new base::StringValue(\"foo\"));\n dict.Set(\"d\", new base::StringValue(\"bad\"));\n dict.Set(\"b\", new base::StringValue(\"bar\"));\n dict.Set(\"c\", new base::StringValue(\"baz\"));\n\n \/\/ 32 NULL bytes is the seed that was used to generate the legacy hash.\n EXPECT_EQ(PrefHashCalculator::VALID_LEGACY,\n PrefHashCalculator(std::string(32u, 0), kDeviceId).Validate(\n \"pref.path1\", &dict, kExpectedValue));\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/prefs\/session_startup_pref.h\"\n#include \"chrome\/common\/pref_names.h\"\n#include \"chrome\/test\/base\/testing_pref_service.h\"\n#include \"testing\/gmock\/include\/gmock\/gmock.h\"\n#include \"testing\/gtest\/include\/gtest\/gtest.h\"\n\n\/\/ Unit tests for SessionStartupPref.\nclass SessionStartupPrefTest : public testing::Test {\n public:\n virtual void SetUp() {\n pref_service_.reset(new TestingPrefService);\n SessionStartupPref::RegisterUserPrefs(pref_service_.get());\n pref_service_->RegisterBooleanPref(prefs::kHomePageIsNewTabPage, true);\n }\n\n scoped_ptr<TestingPrefService> pref_service_;\n};\n\nTEST_F(SessionStartupPrefTest, URLListIsFixedUp) {\n ListValue* url_pref_list = new ListValue;\n url_pref_list->Set(0, Value::CreateStringValue(\"google.com\"));\n url_pref_list->Set(1, Value::CreateStringValue(\"chromium.org\"));\n pref_service_->SetUserPref(prefs::kURLsToRestoreOnStartup, url_pref_list);\n\n SessionStartupPref result =\n SessionStartupPref::GetStartupPref(pref_service_.get());\n EXPECT_EQ(2u, result.urls.size());\n EXPECT_EQ(\"http:\/\/google.com\/\", result.urls[0].spec());\n EXPECT_EQ(\"http:\/\/chromium.org\/\", result.urls[1].spec());\n}\n\nTEST_F(SessionStartupPrefTest, URLListManagedOverridesUser) {\n ListValue* url_pref_list1 = new ListValue;\n url_pref_list1->Set(0, Value::CreateStringValue(\"chromium.org\"));\n pref_service_->SetUserPref(prefs::kURLsToRestoreOnStartup, url_pref_list1);\n\n ListValue* url_pref_list2 = new ListValue;\n url_pref_list2->Set(0, Value::CreateStringValue(\"chromium.org\"));\n url_pref_list2->Set(1, Value::CreateStringValue(\"chromium.org\"));\n url_pref_list2->Set(2, Value::CreateStringValue(\"chromium.org\"));\n pref_service_->SetManagedPref(prefs::kURLsToRestoreOnStartup,\n url_pref_list2);\n\n SessionStartupPref result =\n SessionStartupPref::GetStartupPref(pref_service_.get());\n EXPECT_EQ(3u, result.urls.size());\n\n SessionStartupPref override_test =\n SessionStartupPref(SessionStartupPref::URLS);\n override_test.urls.push_back(GURL(\"dev.chromium.org\"));\n SessionStartupPref::SetStartupPref(pref_service_.get(), override_test);\n\n result = SessionStartupPref::GetStartupPref(pref_service_.get());\n EXPECT_EQ(3u, result.urls.size());\n}\n\n\/\/ Checks to make sure that if the user had previously not selected anything\n\/\/ (so that, in effect, the default value \"Open the homepage\" was selected),\n\/\/ their preferences are migrated on upgrade to m19.\nTEST_F(SessionStartupPrefTest, DefaultMigration) {\n pref_service_->RegisterStringPref(prefs::kHomePage, \"http:\/\/google.com\/\");\n pref_service_->SetString(prefs::kHomePage, \"http:\/\/chromium.org\/\");\n pref_service_->SetBoolean(prefs::kHomePageIsNewTabPage, false);\n\n EXPECT_FALSE(pref_service_->HasPrefPath(prefs::kRestoreOnStartup));\n\n SessionStartupPref pref = SessionStartupPref::GetStartupPref(\n pref_service_.get());\n\n#if defined(OS_CHROMEOS)\n \/\/ On ChromeOS, the default is LAST, so no migration should happen.\n EXPECT_EQ(SessionStartupPref::LAST, pref.type);\n EXPECT_EQ(0U, pref.urls.size());\n#else\n EXPECT_EQ(SessionStartupPref::URLS, pref.type);\n EXPECT_EQ(1U, pref.urls.size());\n EXPECT_EQ(GURL(\"http:\/\/chromium.org\/\"), pref.urls[0]);\n#endif\n}\n\n\/\/ Checks to make sure that if the user had previously not selected anything\n\/\/ (so that, in effect, the default value \"Open the homepage\" was selected),\n\/\/ and the NTP is being used for the homepage, their preferences are migrated\n\/\/ to \"Open the New Tab Page\" on upgrade to M19.\nTEST_F(SessionStartupPrefTest, DefaultMigrationHomepageIsNTP) {\n pref_service_->RegisterStringPref(prefs::kHomePage, \"http:\/\/google.com\/\");\n pref_service_->SetString(prefs::kHomePage, \"http:\/\/chromium.org\/\");\n pref_service_->SetBoolean(prefs::kHomePageIsNewTabPage, true);\n\n EXPECT_FALSE(pref_service_->HasPrefPath(prefs::kRestoreOnStartup));\n\n SessionStartupPref pref = SessionStartupPref::GetStartupPref(\n pref_service_.get());\n\n#if defined(OS_CHROMEOS)\n \/\/ On ChromeOS, the default is LAST, so no migration should happen.\n EXPECT_EQ(SessionStartupPref::LAST, pref.type);\n#else\n EXPECT_EQ(SessionStartupPref::DEFAULT, pref.type);\n#endif\n\n \/\/ The \"URLs to restore on startup\" shouldn't get migrated.\n EXPECT_EQ(0U, pref.urls.size());\n}\n\n\/\/ Checks to make sure that if the user had previously selected \"Open the\n\/\/ \"homepage\", their preferences are migrated on upgrade to M19.\nTEST_F(SessionStartupPrefTest, HomePageMigration) {\n pref_service_->RegisterStringPref(prefs::kHomePage, \"http:\/\/google.com\/\");\n\n \/\/ By design, it's impossible to set the 'restore on startup' pref to 0\n \/\/ (\"open the homepage\") using SessionStartupPref::SetStartupPref(), so set it\n \/\/ using the pref service directly.\n pref_service_->SetInteger(prefs::kRestoreOnStartup, \/*kPrefValueHomePage*\/ 0);\n pref_service_->SetString(prefs::kHomePage, \"http:\/\/chromium.org\/\");\n pref_service_->SetBoolean(prefs::kHomePageIsNewTabPage, false);\n\n SessionStartupPref pref = SessionStartupPref::GetStartupPref(\n pref_service_.get());\n\n EXPECT_EQ(SessionStartupPref::URLS, pref.type);\n EXPECT_EQ(1U, pref.urls.size());\n EXPECT_EQ(GURL(\"http:\/\/chromium.org\/\"), pref.urls[0]);\n}\n\n\/\/ Checks to make sure that if the user had previously selected \"Open the\n\/\/ \"homepage\", and the NTP is being used for the homepage, their preferences\n\/\/ are migrated on upgrade to M19.\nTEST_F(SessionStartupPrefTest, HomePageMigrationHomepageIsNTP) {\n pref_service_->RegisterStringPref(prefs::kHomePage, \"http:\/\/google.com\/\");\n\n \/\/ By design, it's impossible to set the 'restore on startup' pref to 0\n \/\/ (\"open the homepage\") using SessionStartupPref::SetStartupPref(), so set it\n \/\/ using the pref service directly.\n pref_service_->SetInteger(prefs::kRestoreOnStartup, \/*kPrefValueHomePage*\/ 0);\n pref_service_->SetString(prefs::kHomePage, \"http:\/\/chromium.org\/\");\n pref_service_->SetBoolean(prefs::kHomePageIsNewTabPage, true);\n\n SessionStartupPref pref = SessionStartupPref::GetStartupPref(\n pref_service_.get());\n\n EXPECT_EQ(SessionStartupPref::DEFAULT, pref.type);\n}\n<commit_msg>[Mac] Fix a crash in SessionStartupPrefTest on 10.7.<commit_after>\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/prefs\/session_startup_pref.h\"\n#include \"chrome\/common\/pref_names.h\"\n#include \"chrome\/test\/base\/testing_pref_service.h\"\n#include \"testing\/gmock\/include\/gmock\/gmock.h\"\n#include \"testing\/gtest\/include\/gtest\/gtest.h\"\n\n#if defined(OS_MACOSX)\n#include \"chrome\/browser\/ui\/cocoa\/window_restore_utils.h\"\n#endif\n\n\/\/ Unit tests for SessionStartupPref.\nclass SessionStartupPrefTest : public testing::Test {\n public:\n virtual void SetUp() {\n pref_service_.reset(new TestingPrefService);\n SessionStartupPref::RegisterUserPrefs(pref_service_.get());\n pref_service_->RegisterBooleanPref(prefs::kHomePageIsNewTabPage, true);\n }\n\n bool IsUseLastOpenDefault() {\n \/\/ On ChromeOS and OS X 10.7+, the default SessionStartupPref is LAST.\n#if defined(OS_CHROMEOS)\n return true;\n#elif defined(OS_MACOSX)\n return restore_utils::IsWindowRestoreEnabled();\n#else\n return false;\n#endif\n }\n\n scoped_ptr<TestingPrefService> pref_service_;\n};\n\nTEST_F(SessionStartupPrefTest, URLListIsFixedUp) {\n ListValue* url_pref_list = new ListValue;\n url_pref_list->Set(0, Value::CreateStringValue(\"google.com\"));\n url_pref_list->Set(1, Value::CreateStringValue(\"chromium.org\"));\n pref_service_->SetUserPref(prefs::kURLsToRestoreOnStartup, url_pref_list);\n\n SessionStartupPref result =\n SessionStartupPref::GetStartupPref(pref_service_.get());\n EXPECT_EQ(2u, result.urls.size());\n EXPECT_EQ(\"http:\/\/google.com\/\", result.urls[0].spec());\n EXPECT_EQ(\"http:\/\/chromium.org\/\", result.urls[1].spec());\n}\n\nTEST_F(SessionStartupPrefTest, URLListManagedOverridesUser) {\n ListValue* url_pref_list1 = new ListValue;\n url_pref_list1->Set(0, Value::CreateStringValue(\"chromium.org\"));\n pref_service_->SetUserPref(prefs::kURLsToRestoreOnStartup, url_pref_list1);\n\n ListValue* url_pref_list2 = new ListValue;\n url_pref_list2->Set(0, Value::CreateStringValue(\"chromium.org\"));\n url_pref_list2->Set(1, Value::CreateStringValue(\"chromium.org\"));\n url_pref_list2->Set(2, Value::CreateStringValue(\"chromium.org\"));\n pref_service_->SetManagedPref(prefs::kURLsToRestoreOnStartup,\n url_pref_list2);\n\n SessionStartupPref result =\n SessionStartupPref::GetStartupPref(pref_service_.get());\n EXPECT_EQ(3u, result.urls.size());\n\n SessionStartupPref override_test =\n SessionStartupPref(SessionStartupPref::URLS);\n override_test.urls.push_back(GURL(\"dev.chromium.org\"));\n SessionStartupPref::SetStartupPref(pref_service_.get(), override_test);\n\n result = SessionStartupPref::GetStartupPref(pref_service_.get());\n EXPECT_EQ(3u, result.urls.size());\n}\n\n\/\/ Checks to make sure that if the user had previously not selected anything\n\/\/ (so that, in effect, the default value \"Open the homepage\" was selected),\n\/\/ their preferences are migrated on upgrade to m19.\nTEST_F(SessionStartupPrefTest, DefaultMigration) {\n pref_service_->RegisterStringPref(prefs::kHomePage, \"http:\/\/google.com\/\");\n pref_service_->SetString(prefs::kHomePage, \"http:\/\/chromium.org\/\");\n pref_service_->SetBoolean(prefs::kHomePageIsNewTabPage, false);\n\n EXPECT_FALSE(pref_service_->HasPrefPath(prefs::kRestoreOnStartup));\n\n SessionStartupPref pref = SessionStartupPref::GetStartupPref(\n pref_service_.get());\n\n if (IsUseLastOpenDefault()) {\n EXPECT_EQ(SessionStartupPref::LAST, pref.type);\n EXPECT_EQ(0U, pref.urls.size());\n } else {\n EXPECT_EQ(SessionStartupPref::URLS, pref.type);\n EXPECT_EQ(1U, pref.urls.size());\n EXPECT_EQ(GURL(\"http:\/\/chromium.org\/\"), pref.urls[0]);\n }\n}\n\n\/\/ Checks to make sure that if the user had previously not selected anything\n\/\/ (so that, in effect, the default value \"Open the homepage\" was selected),\n\/\/ and the NTP is being used for the homepage, their preferences are migrated\n\/\/ to \"Open the New Tab Page\" on upgrade to M19.\nTEST_F(SessionStartupPrefTest, DefaultMigrationHomepageIsNTP) {\n pref_service_->RegisterStringPref(prefs::kHomePage, \"http:\/\/google.com\/\");\n pref_service_->SetString(prefs::kHomePage, \"http:\/\/chromium.org\/\");\n pref_service_->SetBoolean(prefs::kHomePageIsNewTabPage, true);\n\n EXPECT_FALSE(pref_service_->HasPrefPath(prefs::kRestoreOnStartup));\n\n SessionStartupPref pref = SessionStartupPref::GetStartupPref(\n pref_service_.get());\n\n if (IsUseLastOpenDefault())\n EXPECT_EQ(SessionStartupPref::LAST, pref.type);\n else\n EXPECT_EQ(SessionStartupPref::DEFAULT, pref.type);\n\n \/\/ The \"URLs to restore on startup\" shouldn't get migrated.\n EXPECT_EQ(0U, pref.urls.size());\n}\n\n\/\/ Checks to make sure that if the user had previously selected \"Open the\n\/\/ \"homepage\", their preferences are migrated on upgrade to M19.\nTEST_F(SessionStartupPrefTest, HomePageMigration) {\n pref_service_->RegisterStringPref(prefs::kHomePage, \"http:\/\/google.com\/\");\n\n \/\/ By design, it's impossible to set the 'restore on startup' pref to 0\n \/\/ (\"open the homepage\") using SessionStartupPref::SetStartupPref(), so set it\n \/\/ using the pref service directly.\n pref_service_->SetInteger(prefs::kRestoreOnStartup, \/*kPrefValueHomePage*\/ 0);\n pref_service_->SetString(prefs::kHomePage, \"http:\/\/chromium.org\/\");\n pref_service_->SetBoolean(prefs::kHomePageIsNewTabPage, false);\n\n SessionStartupPref pref = SessionStartupPref::GetStartupPref(\n pref_service_.get());\n\n EXPECT_EQ(SessionStartupPref::URLS, pref.type);\n EXPECT_EQ(1U, pref.urls.size());\n EXPECT_EQ(GURL(\"http:\/\/chromium.org\/\"), pref.urls[0]);\n}\n\n\/\/ Checks to make sure that if the user had previously selected \"Open the\n\/\/ \"homepage\", and the NTP is being used for the homepage, their preferences\n\/\/ are migrated on upgrade to M19.\nTEST_F(SessionStartupPrefTest, HomePageMigrationHomepageIsNTP) {\n pref_service_->RegisterStringPref(prefs::kHomePage, \"http:\/\/google.com\/\");\n\n \/\/ By design, it's impossible to set the 'restore on startup' pref to 0\n \/\/ (\"open the homepage\") using SessionStartupPref::SetStartupPref(), so set it\n \/\/ using the pref service directly.\n pref_service_->SetInteger(prefs::kRestoreOnStartup, \/*kPrefValueHomePage*\/ 0);\n pref_service_->SetString(prefs::kHomePage, \"http:\/\/chromium.org\/\");\n pref_service_->SetBoolean(prefs::kHomePageIsNewTabPage, true);\n\n SessionStartupPref pref = SessionStartupPref::GetStartupPref(\n pref_service_.get());\n\n EXPECT_EQ(SessionStartupPref::DEFAULT, pref.type);\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/ui\/views\/extensions\/extension_popup.h\"\n\n#include \"base\/bind.h\"\n#include \"base\/message_loop.h\"\n#include \"chrome\/browser\/devtools\/devtools_window.h\"\n#include \"chrome\/browser\/extensions\/extension_process_manager.h\"\n#include \"chrome\/browser\/extensions\/extension_system.h\"\n#include \"chrome\/browser\/platform_util.h\"\n#include \"chrome\/browser\/profiles\/profile.h\"\n#include \"chrome\/browser\/ui\/browser.h\"\n#include \"chrome\/browser\/ui\/browser_window.h\"\n#include \"chrome\/common\/chrome_notification_types.h\"\n#include \"content\/public\/browser\/notification_details.h\"\n#include \"content\/public\/browser\/notification_source.h\"\n#include \"content\/public\/browser\/render_view_host.h\"\n#include \"content\/public\/browser\/web_contents.h\"\n#include \"ui\/gfx\/insets.h\"\n#include \"ui\/views\/layout\/fill_layout.h\"\n#include \"ui\/views\/widget\/widget.h\"\n\n#if defined(USE_AURA)\n#include \"ui\/aura\/window.h\"\n#include \"ui\/views\/corewm\/window_animations.h\"\n#endif\n\nusing content::RenderViewHost;\nusing content::WebContents;\n\nnamespace {\n\n\/\/ Returns true if |possible_parent| is a parent window of |child|.\nbool IsParent(gfx::NativeView child, gfx::NativeView possible_parent) {\n if (!child)\n return false;\n#if !defined(USE_AURA) && defined(OS_WIN)\n if (::GetWindow(child, GW_OWNER) == possible_parent)\n return true;\n#endif\n gfx::NativeView parent = child;\n while ((parent = platform_util::GetParent(parent))) {\n if (possible_parent == parent)\n return true;\n }\n\n return false;\n}\n\n} \/\/ namespace\n\n\/\/ The minimum\/maximum dimensions of the popup.\n\/\/ The minimum is just a little larger than the size of the button itself.\n\/\/ The maximum is an arbitrary number that should be smaller than most screens.\nconst int ExtensionPopup::kMinWidth = 25;\nconst int ExtensionPopup::kMinHeight = 25;\nconst int ExtensionPopup::kMaxWidth = 800;\nconst int ExtensionPopup::kMaxHeight = 600;\n\nExtensionPopup::ExtensionPopup(\n Browser* browser,\n extensions::ExtensionHost* host,\n views::View* anchor_view,\n views::BubbleBorder::ArrowLocation arrow_location,\n ShowAction show_action)\n : BubbleDelegateView(anchor_view, arrow_location),\n extension_host_(host),\n close_bubble_factory_(this) {\n inspect_with_devtools_ = show_action == SHOW_AND_INSPECT;\n \/\/ Adjust the margin so that contents fit better.\n const int margin = views::BubbleBorder::GetCornerRadius() \/ 2;\n set_margins(gfx::Insets(margin, margin, margin, margin));\n SetLayoutManager(new views::FillLayout());\n AddChildView(host->view());\n host->view()->SetContainer(this);\n \/\/ Use OnNativeFocusChange to check for child window activation on deactivate.\n set_close_on_deactivate(false);\n \/\/ Make the bubble move with its anchor (during inspection, etc.).\n set_move_with_anchor(true);\n\n \/\/ Wait to show the popup until the contained host finishes loading.\n registrar_.Add(this, content::NOTIFICATION_LOAD_COMPLETED_MAIN_FRAME,\n content::Source<WebContents>(host->host_contents()));\n\n \/\/ Listen for the containing view calling window.close();\n registrar_.Add(this, chrome::NOTIFICATION_EXTENSION_HOST_VIEW_SHOULD_CLOSE,\n content::Source<Profile>(host->profile()));\n\n \/\/ Listen for the dev tools opening on this popup, so we can stop it going\n \/\/ away when the dev tools get focus.\n registrar_.Add(this, content::NOTIFICATION_DEVTOOLS_AGENT_ATTACHED,\n content::Source<Profile>(host->profile()));\n\n \/\/ Listen for the dev tools closing, so we can close this window if it is\n \/\/ being inspected and the inspector is closed.\n registrar_.Add(this, content::NOTIFICATION_DEVTOOLS_AGENT_DETACHED,\n content::Source<content::BrowserContext>(host->profile()));\n}\n\nExtensionPopup::~ExtensionPopup() {\n views::WidgetFocusManager::GetInstance()->RemoveFocusChangeListener(this);\n}\n\nvoid ExtensionPopup::Observe(int type,\n const content::NotificationSource& source,\n const content::NotificationDetails& details) {\n switch (type) {\n case content::NOTIFICATION_LOAD_COMPLETED_MAIN_FRAME:\n DCHECK(content::Source<WebContents>(host()->host_contents()) == source);\n \/\/ Show when the content finishes loading and its width is computed.\n ShowBubble();\n break;\n case chrome::NOTIFICATION_EXTENSION_HOST_VIEW_SHOULD_CLOSE:\n \/\/ If we aren't the host of the popup, then disregard the notification.\n if (content::Details<extensions::ExtensionHost>(host()) == details)\n GetWidget()->Close();\n break;\n case content::NOTIFICATION_DEVTOOLS_AGENT_DETACHED:\n \/\/ Make sure it's the devtools window that inspecting our popup.\n \/\/ Widget::Close posts a task, which should give the devtools window a\n \/\/ chance to finish detaching from the inspected RenderViewHost.\n if (content::Details<RenderViewHost>(host()->render_view_host()) ==\n details) {\n GetWidget()->Close();\n }\n break;\n case content::NOTIFICATION_DEVTOOLS_AGENT_ATTACHED:\n \/\/ First check that the devtools are being opened on this popup.\n if (content::Details<RenderViewHost>(host()->render_view_host()) ==\n details) {\n \/\/ Set inspect_with_devtools_ so the popup will be kept open while\n \/\/ the devtools are open.\n inspect_with_devtools_ = true;\n }\n break;\n default:\n NOTREACHED() << L\"Received unexpected notification\";\n }\n}\n\nvoid ExtensionPopup::OnExtensionSizeChanged(ExtensionViewViews* view) {\n SizeToContents();\n}\n\ngfx::Size ExtensionPopup::GetPreferredSize() {\n \/\/ Constrain the size to popup min\/max.\n gfx::Size sz = views::View::GetPreferredSize();\n sz.set_width(std::max(kMinWidth, std::min(kMaxWidth, sz.width())));\n sz.set_height(std::max(kMinHeight, std::min(kMaxHeight, sz.height())));\n return sz;\n}\n\nvoid ExtensionPopup::OnNativeFocusChange(gfx::NativeView focused_before,\n gfx::NativeView focused_now) {\n \/\/ Don't close if a child of this window is activated (only needed on Win).\n \/\/ ExtensionPopups can create Javascipt dialogs; see crbug.com\/106723.\n gfx::NativeView this_window = GetWidget()->GetNativeView();\n if (inspect_with_devtools_ || focused_now == this_window ||\n IsParent(focused_now, this_window))\n return;\n \/\/ Delay closing the widget because on Aura, closing right away makes the\n \/\/ activation controller trigger another focus change before the current focus\n \/\/ change is complete.\n if (!close_bubble_factory_.HasWeakPtrs()) {\n MessageLoop::current()->PostTask(FROM_HERE,\n base::Bind(&ExtensionPopup::CloseBubble,\n close_bubble_factory_.GetWeakPtr()));\n }\n}\n\n\/\/ static\nExtensionPopup* ExtensionPopup::ShowPopup(\n const GURL& url,\n Browser* browser,\n views::View* anchor_view,\n views::BubbleBorder::ArrowLocation arrow_location,\n ShowAction show_action) {\n ExtensionProcessManager* manager =\n extensions::ExtensionSystem::Get(browser->profile())->process_manager();\n extensions::ExtensionHost* host = manager->CreatePopupHost(url, browser);\n ExtensionPopup* popup = new ExtensionPopup(browser, host, anchor_view,\n arrow_location, show_action);\n views::BubbleDelegateView::CreateBubble(popup);\n\n#if defined(USE_AURA)\n gfx::NativeView native_view = popup->GetWidget()->GetNativeView();\n views::corewm::SetWindowVisibilityAnimationType(\n native_view,\n views::corewm::WINDOW_VISIBILITY_ANIMATION_TYPE_VERTICAL);\n views::corewm::SetWindowVisibilityAnimationVerticalPosition(\n native_view,\n -3.0f);\n#endif\n\n \/\/ If the host had somehow finished loading, then we'd miss the notification\n \/\/ and not show. This seems to happen in single-process mode.\n if (host->did_stop_loading())\n popup->ShowBubble();\n\n return popup;\n}\n\nvoid ExtensionPopup::ShowBubble() {\n Show();\n\n \/\/ Focus on the host contents when the bubble is first shown.\n host()->host_contents()->Focus();\n\n \/\/ Listen for widget focus changes after showing (used for non-aura win).\n views::WidgetFocusManager::GetInstance()->AddFocusChangeListener(this);\n\n if (inspect_with_devtools_) {\n DevToolsWindow::ToggleDevToolsWindow(host()->render_view_host(),\n true,\n DEVTOOLS_TOGGLE_ACTION_SHOW_CONSOLE);\n }\n}\n\nvoid ExtensionPopup::CloseBubble() {\n GetWidget()->Close();\n}\n<commit_msg>Fix bug where extension popups would not properly receive input focus when first shown.<commit_after>\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/ui\/views\/extensions\/extension_popup.h\"\n\n#include \"base\/bind.h\"\n#include \"base\/message_loop.h\"\n#include \"chrome\/browser\/devtools\/devtools_window.h\"\n#include \"chrome\/browser\/extensions\/extension_process_manager.h\"\n#include \"chrome\/browser\/extensions\/extension_system.h\"\n#include \"chrome\/browser\/platform_util.h\"\n#include \"chrome\/browser\/profiles\/profile.h\"\n#include \"chrome\/browser\/ui\/browser.h\"\n#include \"chrome\/browser\/ui\/browser_window.h\"\n#include \"chrome\/common\/chrome_notification_types.h\"\n#include \"content\/public\/browser\/notification_details.h\"\n#include \"content\/public\/browser\/notification_source.h\"\n#include \"content\/public\/browser\/render_view_host.h\"\n#include \"content\/public\/browser\/web_contents.h\"\n#include \"ui\/gfx\/insets.h\"\n#include \"ui\/views\/layout\/fill_layout.h\"\n#include \"ui\/views\/widget\/widget.h\"\n\n#if defined(USE_AURA)\n#include \"ui\/aura\/window.h\"\n#include \"ui\/views\/corewm\/window_animations.h\"\n#endif\n\nusing content::RenderViewHost;\nusing content::WebContents;\n\nnamespace {\n\n\/\/ Returns true if |possible_parent| is a parent window of |child|.\nbool IsParent(gfx::NativeView child, gfx::NativeView possible_parent) {\n if (!child)\n return false;\n#if !defined(USE_AURA) && defined(OS_WIN)\n if (::GetWindow(child, GW_OWNER) == possible_parent)\n return true;\n#endif\n gfx::NativeView parent = child;\n while ((parent = platform_util::GetParent(parent))) {\n if (possible_parent == parent)\n return true;\n }\n\n return false;\n}\n\n} \/\/ namespace\n\n\/\/ The minimum\/maximum dimensions of the popup.\n\/\/ The minimum is just a little larger than the size of the button itself.\n\/\/ The maximum is an arbitrary number that should be smaller than most screens.\nconst int ExtensionPopup::kMinWidth = 25;\nconst int ExtensionPopup::kMinHeight = 25;\nconst int ExtensionPopup::kMaxWidth = 800;\nconst int ExtensionPopup::kMaxHeight = 600;\n\nExtensionPopup::ExtensionPopup(\n Browser* browser,\n extensions::ExtensionHost* host,\n views::View* anchor_view,\n views::BubbleBorder::ArrowLocation arrow_location,\n ShowAction show_action)\n : BubbleDelegateView(anchor_view, arrow_location),\n extension_host_(host),\n close_bubble_factory_(this) {\n inspect_with_devtools_ = show_action == SHOW_AND_INSPECT;\n \/\/ Adjust the margin so that contents fit better.\n const int margin = views::BubbleBorder::GetCornerRadius() \/ 2;\n set_margins(gfx::Insets(margin, margin, margin, margin));\n SetLayoutManager(new views::FillLayout());\n AddChildView(host->view());\n host->view()->SetContainer(this);\n \/\/ Use OnNativeFocusChange to check for child window activation on deactivate.\n set_close_on_deactivate(false);\n \/\/ Make the bubble move with its anchor (during inspection, etc.).\n set_move_with_anchor(true);\n\n \/\/ Wait to show the popup until the contained host finishes loading.\n registrar_.Add(this, content::NOTIFICATION_LOAD_COMPLETED_MAIN_FRAME,\n content::Source<WebContents>(host->host_contents()));\n\n \/\/ Listen for the containing view calling window.close();\n registrar_.Add(this, chrome::NOTIFICATION_EXTENSION_HOST_VIEW_SHOULD_CLOSE,\n content::Source<Profile>(host->profile()));\n\n \/\/ Listen for the dev tools opening on this popup, so we can stop it going\n \/\/ away when the dev tools get focus.\n registrar_.Add(this, content::NOTIFICATION_DEVTOOLS_AGENT_ATTACHED,\n content::Source<Profile>(host->profile()));\n\n \/\/ Listen for the dev tools closing, so we can close this window if it is\n \/\/ being inspected and the inspector is closed.\n registrar_.Add(this, content::NOTIFICATION_DEVTOOLS_AGENT_DETACHED,\n content::Source<content::BrowserContext>(host->profile()));\n}\n\nExtensionPopup::~ExtensionPopup() {\n views::WidgetFocusManager::GetInstance()->RemoveFocusChangeListener(this);\n}\n\nvoid ExtensionPopup::Observe(int type,\n const content::NotificationSource& source,\n const content::NotificationDetails& details) {\n switch (type) {\n case content::NOTIFICATION_LOAD_COMPLETED_MAIN_FRAME:\n DCHECK(content::Source<WebContents>(host()->host_contents()) == source);\n \/\/ Show when the content finishes loading and its width is computed.\n ShowBubble();\n break;\n case chrome::NOTIFICATION_EXTENSION_HOST_VIEW_SHOULD_CLOSE:\n \/\/ If we aren't the host of the popup, then disregard the notification.\n if (content::Details<extensions::ExtensionHost>(host()) == details)\n GetWidget()->Close();\n break;\n case content::NOTIFICATION_DEVTOOLS_AGENT_DETACHED:\n \/\/ Make sure it's the devtools window that inspecting our popup.\n \/\/ Widget::Close posts a task, which should give the devtools window a\n \/\/ chance to finish detaching from the inspected RenderViewHost.\n if (content::Details<RenderViewHost>(host()->render_view_host()) ==\n details) {\n GetWidget()->Close();\n }\n break;\n case content::NOTIFICATION_DEVTOOLS_AGENT_ATTACHED:\n \/\/ First check that the devtools are being opened on this popup.\n if (content::Details<RenderViewHost>(host()->render_view_host()) ==\n details) {\n \/\/ Set inspect_with_devtools_ so the popup will be kept open while\n \/\/ the devtools are open.\n inspect_with_devtools_ = true;\n }\n break;\n default:\n NOTREACHED() << L\"Received unexpected notification\";\n }\n}\n\nvoid ExtensionPopup::OnExtensionSizeChanged(ExtensionViewViews* view) {\n SizeToContents();\n}\n\ngfx::Size ExtensionPopup::GetPreferredSize() {\n \/\/ Constrain the size to popup min\/max.\n gfx::Size sz = views::View::GetPreferredSize();\n sz.set_width(std::max(kMinWidth, std::min(kMaxWidth, sz.width())));\n sz.set_height(std::max(kMinHeight, std::min(kMaxHeight, sz.height())));\n return sz;\n}\n\nvoid ExtensionPopup::OnNativeFocusChange(gfx::NativeView focused_before,\n gfx::NativeView focused_now) {\n \/\/ Don't close if a child of this window is activated (only needed on Win).\n \/\/ ExtensionPopups can create Javascipt dialogs; see crbug.com\/106723.\n gfx::NativeView this_window = GetWidget()->GetNativeView();\n if (inspect_with_devtools_ || focused_now == this_window ||\n IsParent(focused_now, this_window))\n return;\n \/\/ Delay closing the widget because on Aura, closing right away makes the\n \/\/ activation controller trigger another focus change before the current focus\n \/\/ change is complete.\n if (!close_bubble_factory_.HasWeakPtrs()) {\n MessageLoop::current()->PostTask(FROM_HERE,\n base::Bind(&ExtensionPopup::CloseBubble,\n close_bubble_factory_.GetWeakPtr()));\n }\n}\n\n\/\/ static\nExtensionPopup* ExtensionPopup::ShowPopup(\n const GURL& url,\n Browser* browser,\n views::View* anchor_view,\n views::BubbleBorder::ArrowLocation arrow_location,\n ShowAction show_action) {\n ExtensionProcessManager* manager =\n extensions::ExtensionSystem::Get(browser->profile())->process_manager();\n extensions::ExtensionHost* host = manager->CreatePopupHost(url, browser);\n ExtensionPopup* popup = new ExtensionPopup(browser, host, anchor_view,\n arrow_location, show_action);\n views::BubbleDelegateView::CreateBubble(popup);\n\n#if defined(USE_AURA)\n gfx::NativeView native_view = popup->GetWidget()->GetNativeView();\n views::corewm::SetWindowVisibilityAnimationType(\n native_view,\n views::corewm::WINDOW_VISIBILITY_ANIMATION_TYPE_VERTICAL);\n views::corewm::SetWindowVisibilityAnimationVerticalPosition(\n native_view,\n -3.0f);\n#endif\n\n \/\/ If the host had somehow finished loading, then we'd miss the notification\n \/\/ and not show. This seems to happen in single-process mode.\n if (host->did_stop_loading())\n popup->ShowBubble();\n\n return popup;\n}\n\nvoid ExtensionPopup::ShowBubble() {\n Show();\n\n \/\/ Request focus for the View. Without this, the FocusManager gets confused.\n host()->view()->SetVisible(true);\n host()->view()->RequestFocus();\n\n \/\/ Focus on the host contents when the bubble is first shown.\n host()->host_contents()->Focus();\n\n \/\/ Listen for widget focus changes after showing (used for non-aura win).\n views::WidgetFocusManager::GetInstance()->AddFocusChangeListener(this);\n\n if (inspect_with_devtools_) {\n DevToolsWindow::ToggleDevToolsWindow(host()->render_view_host(),\n true,\n DEVTOOLS_TOGGLE_ACTION_SHOW_CONSOLE);\n }\n}\n\nvoid ExtensionPopup::CloseBubble() {\n GetWidget()->Close();\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * APSP.cpp\n *\n * Created on: 07.07.2015\n * Author: Arie Slobbe\n *\/\n\n#include \"APSP.h\"\n#include \"..\/auxiliary\/Log.h\"\n#include \"Dijkstra.h\"\n\nnamespace NetworKit {\n\nAPSP::APSP(const Graph& G) : Algorithm(), G(G) {}\n\nvoid APSP::run() {\n\tstd::vector<edgeweight> distanceVector(G.upperNodeIdBound(), 0.0);\n\tdistances.resize(G.upperNodeIdBound(), distanceVector);\n\tG.parallelForNodes([&](node u){\n\t\tDijkstra dijk(G, u);\n\t\tdijk.run();\n\t\tdistances[u] = dijk.getDistances();\n\t});\n\thasRun = true;\n}\n\nstd::string NetworKit::APSP::toString() const {\n\treturn \"All-Pairs Shortest Path Algorithm\";\n}\n\n} \/* namespace NetworKit *\/\n<commit_msg>modified apsp to use bfs when the graph is unweighted<commit_after>\/*\n * APSP.cpp\n *\n * Created on: 07.07.2015\n * Author: Arie Slobbe\n *\/\n\n#include \"APSP.h\"\n#include \"..\/auxiliary\/Log.h\"\n#include \"Dijkstra.h\"\n#include \"BFS.h\"\n\nnamespace NetworKit {\n\nAPSP::APSP(const Graph& G) : Algorithm(), G(G) {}\n\nvoid APSP::run() {\n\tstd::vector<edgeweight> distanceVector(G.upperNodeIdBound(), 0.0);\n\tdistances.resize(G.upperNodeIdBound(), distanceVector);\n\tif (G.isWeighted()) {\n\t\tG.parallelForNodes([&](node u){\n\t\t\tDijkstra dijk(G, u);\n\t\t\tdijk.run();\n\t\t\tdistances[u] = dijk.getDistances();\n\t\t});\n\t} else {\n\t\tG.parallelForNodes([&](node u){\n\t\t\tBFS bfs(G, u);\n\t\t\tbfs.run();\n\t\t\tdistances[u] = bfs.getDistances();\n\t\t});\n\t}\n\thasRun = true;\n}\n\nstd::string NetworKit::APSP::toString() const {\n\treturn \"All-Pairs Shortest Path Algorithm\";\n}\n\n} \/* namespace NetworKit *\/\n<|endoftext|>"} {"text":"<commit_before>\/*\n *\n * MIT License\n *\n * Copyright (c) 2016-2017 The Cats Project\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n *\n *\/\n\n#ifndef CATS_CORECAT_TIME_HIGHRESOLUTIONCLOCK_HPP\n#define CATS_CORECAT_TIME_HIGHRESOLUTIONCLOCK_HPP\n\n\n#include <chrono>\n\n#include \"..\/Win32\/Windows.hpp\"\n\n\nnamespace Cats {\nnamespace Corecat {\nnamespace Time {\n\nstruct HighResolutionClock {\n \n using rep = double;\n using period = std::ratio<1>;\n using duration = std::chrono::duration<rep, period>;\n using time_point = std::chrono::time_point<BenchmarkClock>;\n \n static constexpr bool is_steady = false;\n \n static time_point now() noexcept {\n \n LARGE_INTEGER nf, n;\n QueryPerformanceFrequency(&nf);\n QueryPerformanceCounter(&n);\n return time_point(duration(double(n.QuadPart) \/ nf.QuadPart));\n \n }\n \n};\n\n}\n}\n}\n\n\n#endif\n<commit_msg>Update HighResolutionClock<commit_after>\/*\n *\n * MIT License\n *\n * Copyright (c) 2016-2017 The Cats Project\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n *\n *\/\n\n#ifndef CATS_CORECAT_TIME_HIGHRESOLUTIONCLOCK_HPP\n#define CATS_CORECAT_TIME_HIGHRESOLUTIONCLOCK_HPP\n\n\n#include <chrono>\n\n#include \"..\/Win32\/Windows.hpp\"\n\n\nnamespace Cats {\nnamespace Corecat {\nnamespace Time {\n\nstruct HighResolutionClock {\n \n using rep = double;\n using period = std::ratio<1>;\n using duration = std::chrono::duration<rep, period>;\n using time_point = std::chrono::time_point<HighResolutionClock>;\n \n static constexpr bool is_steady = false;\n \n static time_point now() noexcept {\n \n LARGE_INTEGER nf, n;\n QueryPerformanceFrequency(&nf);\n QueryPerformanceCounter(&n);\n return time_point(duration(double(n.QuadPart) \/ nf.QuadPart));\n \n }\n \n};\n\n}\n}\n}\n\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>#include \"ostree.h\"\n#include <stdio.h>\n#include <boost\/algorithm\/string.hpp>\n#include <boost\/algorithm\/string\/classification.hpp>\n#include <boost\/algorithm\/string\/split.hpp>\n#include <boost\/filesystem.hpp>\n#include <fstream>\n#include \"logger.h\"\n\n#include <gio\/gio.h>\n\nOstreeSysroot *Ostree::LoadSysroot(const std::string &path) {\n OstreeSysroot *sysroot = NULL;\n\n if (path.size()) {\n sysroot = ostree_sysroot_new(g_file_new_for_path(path.c_str()));\n } else {\n sysroot = ostree_sysroot_new_default();\n }\n GCancellable *cancellable = NULL;\n GError **error = NULL;\n if (!ostree_sysroot_load(sysroot, cancellable, error)) throw std::runtime_error(\"could not load sysroot\");\n return sysroot;\n}\n\nOstreeDeployment *Ostree::getBootedDeployment(const std::string &path) {\n OstreeSysroot *sysroot = Ostree::LoadSysroot(path);\n OstreeRepo *repo = NULL;\n OstreeDeployment *booted_deployment = NULL;\n\n GCancellable *cancellable = NULL;\n GError **error = NULL;\n\n if (!ostree_sysroot_get_repo(sysroot, &repo, cancellable, error)) throw std::runtime_error(\"could not get repo\");\n\n booted_deployment = ostree_sysroot_get_booted_deployment(sysroot);\n \/\/ booted_deployment = (OstreeDeployment *)ostree_sysroot_get_deployments(sysroot)->pdata[0];\n return booted_deployment;\n}\n\nbool Ostree::addRemote(OstreeRepo *repo, const std::string &remote, const std::string &url,\n const data::PackageManagerCredentials &cred) {\n GCancellable *cancellable = NULL;\n GError *error = NULL;\n GVariantBuilder b;\n GVariant *options;\n\n g_variant_builder_init(&b, G_VARIANT_TYPE(\"a{sv}\"));\n g_variant_builder_add(&b, \"{s@v}\", \"gpg-verify\", g_variant_new_variant(g_variant_new_boolean(FALSE)));\n\n if (cred.cert_file.size() && cred.pkey_file.size() && cred.ca_file.size()) {\n g_variant_builder_add(&b, \"{s@v}\", \"tls-client-cert-path\",\n g_variant_new_variant(g_variant_new_string(cred.cert_file.c_str())));\n g_variant_builder_add(&b, \"{s@v}\", \"tls-client-key-path\",\n g_variant_new_variant(g_variant_new_string(cred.pkey_file.c_str())));\n g_variant_builder_add(&b, \"{s@v}\", \"tls-ca-path\",\n g_variant_new_variant(g_variant_new_string(cred.ca_file.c_str())));\n }\n options = g_variant_builder_end(&b);\n\n if (!ostree_repo_remote_change(repo, NULL, OSTREE_REPO_REMOTE_CHANGE_DELETE_IF_EXISTS, remote.c_str(), url.c_str(),\n options, cancellable, &error)) {\n LOGGER_LOG(LVL_error, \"Error of adding remote: \" << error->message);\n return false;\n }\n if (!ostree_repo_remote_change(repo, NULL, OSTREE_REPO_REMOTE_CHANGE_ADD_IF_NOT_EXISTS, remote.c_str(), url.c_str(),\n options, cancellable, &error)) {\n LOGGER_LOG(LVL_error, \"Error of adding remote: \" << error->message);\n return false;\n }\n return true;\n}\n\n#include \"ostree-1\/ostree.h\"\n\nOstreePackage::OstreePackage(const std::string &ecu_serial_in, const std::string &ref_name_in,\n const std::string &commit_in, const std::string &desc_in, const std::string &treehub_in)\n : ecu_serial(ecu_serial_in), ref_name(ref_name_in), commit(boost::algorithm::to_lower_copy(commit_in)), description(desc_in), pull_uri(treehub_in) {}\n\ndata::InstallOutcome OstreePackage::install(const data::PackageManagerCredentials &cred, OstreeConfig config) {\n const char remote[] = \"aktualizr-remote\";\n const char *const refs[] = {commit.c_str()};\n const char *opt_osname = NULL;\n OstreeRepo *repo = NULL;\n GCancellable *cancellable = NULL;\n GError *error = NULL;\n char *revision;\n GVariantBuilder builder;\n GVariant *options;\n\n if (config.os.size()) {\n opt_osname = config.os.c_str();\n }\n OstreeSysroot *sysroot = Ostree::LoadSysroot(config.sysroot);\n if (!ostree_sysroot_get_repo(sysroot, &repo, cancellable, &error)) {\n LOGGER_LOG(LVL_error, \"could not get repo\");\n return data::InstallOutcome(data::INSTALL_FAILED, \"could not get repo\");\n }\n\n if (!Ostree::addRemote(repo, remote, pull_uri, cred)) {\n return data::InstallOutcome(data::INSTALL_FAILED, \"Error of adding remote\");\n }\n\n g_variant_builder_init(&builder, G_VARIANT_TYPE(\"a{sv}\"));\n g_variant_builder_add(&builder, \"{s@v}\", \"flags\", g_variant_new_variant(g_variant_new_int32(0)));\n\n g_variant_builder_add(&builder, \"{s@v}\", \"refs\", g_variant_new_variant(g_variant_new_strv(refs, 1)));\n\n if (cred.access_token.size()) {\n GVariantBuilder hdr_builder;\n std::string av(\"Bearer \");\n av += cred.access_token;\n g_variant_builder_init(&hdr_builder, G_VARIANT_TYPE(\"a(ss)\"));\n g_variant_builder_add(&hdr_builder, \"(ss)\", \"Authorization\", av.c_str());\n g_variant_builder_add(&builder, \"{s@v}\", \"http-headers\",\n g_variant_new_variant(g_variant_builder_end(&hdr_builder)));\n }\n options = g_variant_ref_sink(g_variant_builder_end(&builder));\n\n if (!ostree_repo_pull_with_options(repo, remote, options, NULL, cancellable, &error)) {\n LOGGER_LOG(LVL_error, \"Error of pulling image: \" << error->message);\n return data::InstallOutcome(data::INSTALL_FAILED, error->message);\n }\n\n OstreeDeployment *booted_deployment = Ostree::getBootedDeployment(config.sysroot);\n if (booted_deployment == NULL && !config.os.size() && !config.sysroot.size()) {\n LOGGER_LOG(LVL_error, \"No booted deplyment\");\n return data::InstallOutcome(data::INSTALL_FAILED, \"No booted deplyment\");\n }\n\n GKeyFile *origin = ostree_sysroot_origin_new_from_refspec(sysroot, commit.c_str());\n if (!ostree_repo_resolve_rev(repo, commit.c_str(), FALSE, &revision, &error)) {\n LOGGER_LOG(LVL_error, error->message);\n return data::InstallOutcome(data::INSTALL_FAILED, error->message);\n }\n\n OstreeDeployment *merge_deployment = ostree_sysroot_get_merge_deployment(sysroot, opt_osname);\n\n if (!ostree_sysroot_prepare_cleanup(sysroot, cancellable, &error)) {\n LOGGER_LOG(LVL_error, error->message);\n return data::InstallOutcome(data::INSTALL_FAILED, error->message);\n }\n\n std::ifstream args_stream(\"\/proc\/cmdline\");\n std::string args_content((std::istreambuf_iterator<char>(args_stream)), std::istreambuf_iterator<char>());\n std::vector<std::string> args_vector;\n boost::split(args_vector, args_content, boost::is_any_of(\" \"));\n\n std::vector<const char *> kargs_strv_vector;\n kargs_strv_vector.reserve(args_vector.size() + 1);\n\n for (std::vector<std::string>::iterator it = args_vector.begin(); it != args_vector.end(); ++it) {\n kargs_strv_vector.push_back((*it).c_str());\n }\n kargs_strv_vector[args_vector.size()] = 0;\n GStrv kargs_strv = const_cast<char **>(&kargs_strv_vector[0]);\n\n OstreeDeployment *new_deployment = NULL;\n if (!ostree_sysroot_deploy_tree(sysroot, opt_osname, revision, origin, merge_deployment, kargs_strv, &new_deployment,\n cancellable, &error)) {\n LOGGER_LOG(LVL_error, \"ostree_sysroot_deploy_tree: \" << error->message);\n return data::InstallOutcome(data::INSTALL_FAILED, error->message);\n }\n\n if (!ostree_sysroot_simple_write_deployment(sysroot, \"\", new_deployment, merge_deployment,\n OSTREE_SYSROOT_SIMPLE_WRITE_DEPLOYMENT_FLAGS_RETAIN, cancellable,\n &error)) {\n LOGGER_LOG(LVL_error, \"ostree_sysroot_simple_write_deployment:\" << error->message);\n return data::InstallOutcome(data::INSTALL_FAILED, error->message);\n }\n return data::InstallOutcome(data::OK, \"Installation succesfull\");\n}\n\nOstreeBranch OstreeBranch::getCurrent(const std::string &ecu_serial, const std::string &branch,\n const std::string &ostree_sysroot, const std::string &ostree_os) {\n OstreeDeployment *booted_deployment = Ostree::getBootedDeployment(ostree_sysroot);\n\n if (!booted_deployment)\n booted_deployment = ostree_sysroot_get_merge_deployment(Ostree::LoadSysroot(ostree_sysroot), ostree_os.c_str());\n\n GKeyFile *origin = ostree_deployment_get_origin(booted_deployment);\n const char *ref = ostree_deployment_get_csum(booted_deployment);\n char *origin_refspec = g_key_file_get_string(origin, \"origin\", \"refspec\", NULL);\n OstreePackage package(ecu_serial, (branch + \"-\") + ref, ref, origin_refspec, \"\");\n g_free(origin_refspec);\n return OstreeBranch(true, ostree_deployment_get_osname(booted_deployment), package);\n}\n\nOstreePackage OstreePackage::fromJson(const Json::Value &json) {\n return OstreePackage(json[\"ecu_serial\"].asString(), json[\"ref_name\"].asString(), json[\"commit\"].asString(),\n json[\"description\"].asString(), json[\"pull_uri\"].asString());\n}\n\nJson::Value OstreePackage::toEcuVersion(const Json::Value &custom) {\n Json::Value installed_image;\n installed_image[\"filepath\"] = ref_name;\n installed_image[\"fileinfo\"][\"length\"] = 0;\n installed_image[\"fileinfo\"][\"hashes\"][\"sha256\"] = commit;\n\n Json::Value value;\n value[\"attacks_detected\"] = \"\";\n value[\"installed_image\"] = installed_image;\n value[\"ecu_serial\"] = ecu_serial;\n value[\"previous_timeserver_time\"] = \"1970-01-01T00:00:00Z\";\n value[\"timeserver_time\"] = \"1970-01-01T00:00:00Z\";\n if (custom != Json::nullValue) {\n value[\"custom\"] = custom;\n }\n return value;\n}\n\nOstreePackage OstreePackage::getEcu(const std::string &ecu_serial, const std::string &ostree_sysroot,\n const std::string &ostree_os) {\n if (boost::filesystem::exists(NEW_PACKAGE)) {\n std::ifstream path_stream(NEW_PACKAGE.c_str());\n std::string json_content((std::istreambuf_iterator<char>(path_stream)), std::istreambuf_iterator<char>());\n return OstreePackage::fromJson(json_content);\n } else {\n if (boost::filesystem::exists(BOOT_BRANCH)) {\n std::ifstream boot_branch_stream(BOOT_BRANCH.c_str());\n std::string branch_name((std::istreambuf_iterator<char>(boot_branch_stream)), std::istreambuf_iterator<char>());\n branch_name.erase(std::remove(branch_name.begin(), branch_name.end(), '\\n'), branch_name.end());\n return OstreeBranch::getCurrent(ecu_serial, branch_name, ostree_sysroot, ostree_os).package;\n }\n }\n throw std::runtime_error(\"unknown current branch\");\n}\n<commit_msg>Reformat with clang-format<commit_after>#include \"ostree.h\"\n#include <stdio.h>\n#include <boost\/algorithm\/string.hpp>\n#include <boost\/algorithm\/string\/classification.hpp>\n#include <boost\/algorithm\/string\/split.hpp>\n#include <boost\/filesystem.hpp>\n#include <fstream>\n#include \"logger.h\"\n\n#include <gio\/gio.h>\n\nOstreeSysroot *Ostree::LoadSysroot(const std::string &path) {\n OstreeSysroot *sysroot = NULL;\n\n if (path.size()) {\n sysroot = ostree_sysroot_new(g_file_new_for_path(path.c_str()));\n } else {\n sysroot = ostree_sysroot_new_default();\n }\n GCancellable *cancellable = NULL;\n GError **error = NULL;\n if (!ostree_sysroot_load(sysroot, cancellable, error)) throw std::runtime_error(\"could not load sysroot\");\n return sysroot;\n}\n\nOstreeDeployment *Ostree::getBootedDeployment(const std::string &path) {\n OstreeSysroot *sysroot = Ostree::LoadSysroot(path);\n OstreeRepo *repo = NULL;\n OstreeDeployment *booted_deployment = NULL;\n\n GCancellable *cancellable = NULL;\n GError **error = NULL;\n\n if (!ostree_sysroot_get_repo(sysroot, &repo, cancellable, error)) throw std::runtime_error(\"could not get repo\");\n\n booted_deployment = ostree_sysroot_get_booted_deployment(sysroot);\n \/\/ booted_deployment = (OstreeDeployment *)ostree_sysroot_get_deployments(sysroot)->pdata[0];\n return booted_deployment;\n}\n\nbool Ostree::addRemote(OstreeRepo *repo, const std::string &remote, const std::string &url,\n const data::PackageManagerCredentials &cred) {\n GCancellable *cancellable = NULL;\n GError *error = NULL;\n GVariantBuilder b;\n GVariant *options;\n\n g_variant_builder_init(&b, G_VARIANT_TYPE(\"a{sv}\"));\n g_variant_builder_add(&b, \"{s@v}\", \"gpg-verify\", g_variant_new_variant(g_variant_new_boolean(FALSE)));\n\n if (cred.cert_file.size() && cred.pkey_file.size() && cred.ca_file.size()) {\n g_variant_builder_add(&b, \"{s@v}\", \"tls-client-cert-path\",\n g_variant_new_variant(g_variant_new_string(cred.cert_file.c_str())));\n g_variant_builder_add(&b, \"{s@v}\", \"tls-client-key-path\",\n g_variant_new_variant(g_variant_new_string(cred.pkey_file.c_str())));\n g_variant_builder_add(&b, \"{s@v}\", \"tls-ca-path\",\n g_variant_new_variant(g_variant_new_string(cred.ca_file.c_str())));\n }\n options = g_variant_builder_end(&b);\n\n if (!ostree_repo_remote_change(repo, NULL, OSTREE_REPO_REMOTE_CHANGE_DELETE_IF_EXISTS, remote.c_str(), url.c_str(),\n options, cancellable, &error)) {\n LOGGER_LOG(LVL_error, \"Error of adding remote: \" << error->message);\n return false;\n }\n if (!ostree_repo_remote_change(repo, NULL, OSTREE_REPO_REMOTE_CHANGE_ADD_IF_NOT_EXISTS, remote.c_str(), url.c_str(),\n options, cancellable, &error)) {\n LOGGER_LOG(LVL_error, \"Error of adding remote: \" << error->message);\n return false;\n }\n return true;\n}\n\n#include \"ostree-1\/ostree.h\"\n\nOstreePackage::OstreePackage(const std::string &ecu_serial_in, const std::string &ref_name_in,\n const std::string &commit_in, const std::string &desc_in, const std::string &treehub_in)\n : ecu_serial(ecu_serial_in),\n ref_name(ref_name_in),\n commit(boost::algorithm::to_lower_copy(commit_in)),\n description(desc_in),\n pull_uri(treehub_in) {}\n\ndata::InstallOutcome OstreePackage::install(const data::PackageManagerCredentials &cred, OstreeConfig config) {\n const char remote[] = \"aktualizr-remote\";\n const char *const refs[] = {commit.c_str()};\n const char *opt_osname = NULL;\n OstreeRepo *repo = NULL;\n GCancellable *cancellable = NULL;\n GError *error = NULL;\n char *revision;\n GVariantBuilder builder;\n GVariant *options;\n\n if (config.os.size()) {\n opt_osname = config.os.c_str();\n }\n OstreeSysroot *sysroot = Ostree::LoadSysroot(config.sysroot);\n if (!ostree_sysroot_get_repo(sysroot, &repo, cancellable, &error)) {\n LOGGER_LOG(LVL_error, \"could not get repo\");\n return data::InstallOutcome(data::INSTALL_FAILED, \"could not get repo\");\n }\n\n if (!Ostree::addRemote(repo, remote, pull_uri, cred)) {\n return data::InstallOutcome(data::INSTALL_FAILED, \"Error of adding remote\");\n }\n\n g_variant_builder_init(&builder, G_VARIANT_TYPE(\"a{sv}\"));\n g_variant_builder_add(&builder, \"{s@v}\", \"flags\", g_variant_new_variant(g_variant_new_int32(0)));\n\n g_variant_builder_add(&builder, \"{s@v}\", \"refs\", g_variant_new_variant(g_variant_new_strv(refs, 1)));\n\n if (cred.access_token.size()) {\n GVariantBuilder hdr_builder;\n std::string av(\"Bearer \");\n av += cred.access_token;\n g_variant_builder_init(&hdr_builder, G_VARIANT_TYPE(\"a(ss)\"));\n g_variant_builder_add(&hdr_builder, \"(ss)\", \"Authorization\", av.c_str());\n g_variant_builder_add(&builder, \"{s@v}\", \"http-headers\",\n g_variant_new_variant(g_variant_builder_end(&hdr_builder)));\n }\n options = g_variant_ref_sink(g_variant_builder_end(&builder));\n\n if (!ostree_repo_pull_with_options(repo, remote, options, NULL, cancellable, &error)) {\n LOGGER_LOG(LVL_error, \"Error of pulling image: \" << error->message);\n return data::InstallOutcome(data::INSTALL_FAILED, error->message);\n }\n\n OstreeDeployment *booted_deployment = Ostree::getBootedDeployment(config.sysroot);\n if (booted_deployment == NULL && !config.os.size() && !config.sysroot.size()) {\n LOGGER_LOG(LVL_error, \"No booted deplyment\");\n return data::InstallOutcome(data::INSTALL_FAILED, \"No booted deplyment\");\n }\n\n GKeyFile *origin = ostree_sysroot_origin_new_from_refspec(sysroot, commit.c_str());\n if (!ostree_repo_resolve_rev(repo, commit.c_str(), FALSE, &revision, &error)) {\n LOGGER_LOG(LVL_error, error->message);\n return data::InstallOutcome(data::INSTALL_FAILED, error->message);\n }\n\n OstreeDeployment *merge_deployment = ostree_sysroot_get_merge_deployment(sysroot, opt_osname);\n\n if (!ostree_sysroot_prepare_cleanup(sysroot, cancellable, &error)) {\n LOGGER_LOG(LVL_error, error->message);\n return data::InstallOutcome(data::INSTALL_FAILED, error->message);\n }\n\n std::ifstream args_stream(\"\/proc\/cmdline\");\n std::string args_content((std::istreambuf_iterator<char>(args_stream)), std::istreambuf_iterator<char>());\n std::vector<std::string> args_vector;\n boost::split(args_vector, args_content, boost::is_any_of(\" \"));\n\n std::vector<const char *> kargs_strv_vector;\n kargs_strv_vector.reserve(args_vector.size() + 1);\n\n for (std::vector<std::string>::iterator it = args_vector.begin(); it != args_vector.end(); ++it) {\n kargs_strv_vector.push_back((*it).c_str());\n }\n kargs_strv_vector[args_vector.size()] = 0;\n GStrv kargs_strv = const_cast<char **>(&kargs_strv_vector[0]);\n\n OstreeDeployment *new_deployment = NULL;\n if (!ostree_sysroot_deploy_tree(sysroot, opt_osname, revision, origin, merge_deployment, kargs_strv, &new_deployment,\n cancellable, &error)) {\n LOGGER_LOG(LVL_error, \"ostree_sysroot_deploy_tree: \" << error->message);\n return data::InstallOutcome(data::INSTALL_FAILED, error->message);\n }\n\n if (!ostree_sysroot_simple_write_deployment(sysroot, \"\", new_deployment, merge_deployment,\n OSTREE_SYSROOT_SIMPLE_WRITE_DEPLOYMENT_FLAGS_RETAIN, cancellable,\n &error)) {\n LOGGER_LOG(LVL_error, \"ostree_sysroot_simple_write_deployment:\" << error->message);\n return data::InstallOutcome(data::INSTALL_FAILED, error->message);\n }\n return data::InstallOutcome(data::OK, \"Installation succesfull\");\n}\n\nOstreeBranch OstreeBranch::getCurrent(const std::string &ecu_serial, const std::string &branch,\n const std::string &ostree_sysroot, const std::string &ostree_os) {\n OstreeDeployment *booted_deployment = Ostree::getBootedDeployment(ostree_sysroot);\n\n if (!booted_deployment)\n booted_deployment = ostree_sysroot_get_merge_deployment(Ostree::LoadSysroot(ostree_sysroot), ostree_os.c_str());\n\n GKeyFile *origin = ostree_deployment_get_origin(booted_deployment);\n const char *ref = ostree_deployment_get_csum(booted_deployment);\n char *origin_refspec = g_key_file_get_string(origin, \"origin\", \"refspec\", NULL);\n OstreePackage package(ecu_serial, (branch + \"-\") + ref, ref, origin_refspec, \"\");\n g_free(origin_refspec);\n return OstreeBranch(true, ostree_deployment_get_osname(booted_deployment), package);\n}\n\nOstreePackage OstreePackage::fromJson(const Json::Value &json) {\n return OstreePackage(json[\"ecu_serial\"].asString(), json[\"ref_name\"].asString(), json[\"commit\"].asString(),\n json[\"description\"].asString(), json[\"pull_uri\"].asString());\n}\n\nJson::Value OstreePackage::toEcuVersion(const Json::Value &custom) {\n Json::Value installed_image;\n installed_image[\"filepath\"] = ref_name;\n installed_image[\"fileinfo\"][\"length\"] = 0;\n installed_image[\"fileinfo\"][\"hashes\"][\"sha256\"] = commit;\n\n Json::Value value;\n value[\"attacks_detected\"] = \"\";\n value[\"installed_image\"] = installed_image;\n value[\"ecu_serial\"] = ecu_serial;\n value[\"previous_timeserver_time\"] = \"1970-01-01T00:00:00Z\";\n value[\"timeserver_time\"] = \"1970-01-01T00:00:00Z\";\n if (custom != Json::nullValue) {\n value[\"custom\"] = custom;\n }\n return value;\n}\n\nOstreePackage OstreePackage::getEcu(const std::string &ecu_serial, const std::string &ostree_sysroot,\n const std::string &ostree_os) {\n if (boost::filesystem::exists(NEW_PACKAGE)) {\n std::ifstream path_stream(NEW_PACKAGE.c_str());\n std::string json_content((std::istreambuf_iterator<char>(path_stream)), std::istreambuf_iterator<char>());\n return OstreePackage::fromJson(json_content);\n } else {\n if (boost::filesystem::exists(BOOT_BRANCH)) {\n std::ifstream boot_branch_stream(BOOT_BRANCH.c_str());\n std::string branch_name((std::istreambuf_iterator<char>(boot_branch_stream)), std::istreambuf_iterator<char>());\n branch_name.erase(std::remove(branch_name.begin(), branch_name.end(), '\\n'), branch_name.end());\n return OstreeBranch::getCurrent(ecu_serial, branch_name, ostree_sysroot, ostree_os).package;\n }\n }\n throw std::runtime_error(\"unknown current branch\");\n}\n<|endoftext|>"} {"text":"<commit_before>\/**\r\n * \\file\r\n * \\brief RoundRobinQuantum class header\r\n *\r\n * \\author Copyright (C) 2014 Kamil Szczygiel http:\/\/www.distortec.com http:\/\/www.freddiechopin.info\r\n *\r\n * \\par License\r\n * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not\r\n * distributed with this file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\r\n *\r\n * \\date 2014-08-05\r\n *\/\r\n\r\n#ifndef INCLUDE_DISTORTOS_SCHEDULER_ROUNDROBINQUANTUM_HPP_\r\n#define INCLUDE_DISTORTOS_SCHEDULER_ROUNDROBINQUANTUM_HPP_\r\n\r\n#include <cstdint>\r\n\r\nnamespace distortos\r\n{\r\n\r\nnamespace scheduler\r\n{\r\n\r\n\/\/\/ RoundRobinQuantum class is a quantum of time for round-robin scheduling\r\nclass RoundRobinQuantum\r\n{\r\npublic:\r\n\r\n\t\/**\r\n\t * \\brief RoundRobinQuantum's constructor\r\n\t *\r\n\t * Initializes quantum value to 0.\r\n\t *\/\r\n\r\n\tconstexpr RoundRobinQuantum() :\r\n\t\t\tquantum_{}\r\n\t{}\r\n\r\n\t\/**\r\n\t * \\brief Decrements round-robin's quantum.\r\n\t *\r\n\t * This function should be called from tick interrupt for the currently running thread. Underflow of quantum after\r\n\t * this decrement is not possible.\r\n\t *\r\n\t * \\note this function must be called with enabled interrupt masking\r\n\t *\/\r\n\r\n\tvoid decrement();\r\n\r\n\t\/**\r\n\t * \\brief Gets current value of round-robin's quantum.\r\n\t *\r\n\t * \\return current value of round-robin's quantum of the thread\r\n\t *\/\r\n\r\n\tuint8_t get() const { return quantum_; }\r\n\r\n\t\/**\r\n\t * \\brief Resets value of round-robin's quantum.\r\n\t *\r\n\t * This function should be called from context switcher after selecting new task that will be run.\r\n\t *\/\r\n\r\n\tvoid reset();\r\n\r\nprivate:\r\n\r\n\t\/\/\/ round-robin quantum\r\n\tuint8_t quantum_;\r\n};\r\n\r\n}\t\/\/ namespace scheduler\r\n\r\n}\t\/\/ namespace distortos\r\n\r\n#endif\t\/\/ INCLUDE_DISTORTOS_SCHEDULER_ROUNDROBINQUANTUM_HPP_\r\n<commit_msg>RoundRobinQuantum: add convenience RoundRobinQuantum::isZero() function<commit_after>\/**\r\n * \\file\r\n * \\brief RoundRobinQuantum class header\r\n *\r\n * \\author Copyright (C) 2014 Kamil Szczygiel http:\/\/www.distortec.com http:\/\/www.freddiechopin.info\r\n *\r\n * \\par License\r\n * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not\r\n * distributed with this file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\r\n *\r\n * \\date 2014-09-16\r\n *\/\r\n\r\n#ifndef INCLUDE_DISTORTOS_SCHEDULER_ROUNDROBINQUANTUM_HPP_\r\n#define INCLUDE_DISTORTOS_SCHEDULER_ROUNDROBINQUANTUM_HPP_\r\n\r\n#include <cstdint>\r\n\r\nnamespace distortos\r\n{\r\n\r\nnamespace scheduler\r\n{\r\n\r\n\/\/\/ RoundRobinQuantum class is a quantum of time for round-robin scheduling\r\nclass RoundRobinQuantum\r\n{\r\npublic:\r\n\r\n\t\/**\r\n\t * \\brief RoundRobinQuantum's constructor\r\n\t *\r\n\t * Initializes quantum value to 0.\r\n\t *\/\r\n\r\n\tconstexpr RoundRobinQuantum() :\r\n\t\t\tquantum_{}\r\n\t{}\r\n\r\n\t\/**\r\n\t * \\brief Decrements round-robin's quantum.\r\n\t *\r\n\t * This function should be called from tick interrupt for the currently running thread. Underflow of quantum after\r\n\t * this decrement is not possible.\r\n\t *\r\n\t * \\note this function must be called with enabled interrupt masking\r\n\t *\/\r\n\r\n\tvoid decrement();\r\n\r\n\t\/**\r\n\t * \\brief Gets current value of round-robin's quantum.\r\n\t *\r\n\t * \\return current value of round-robin's quantum of the thread\r\n\t *\/\r\n\r\n\tuint8_t get() const { return quantum_; }\r\n\r\n\t\/**\r\n\t * \\brief Convenience function to test whether the quantum is already at 0.\r\n\t *\r\n\t * \\return true if quantum is zero, false otherwise\r\n\t *\/\r\n\r\n\tbool isZero() const\r\n\t{\r\n\t\treturn quantum_ == 0;\r\n\t}\r\n\r\n\t\/**\r\n\t * \\brief Resets value of round-robin's quantum.\r\n\t *\r\n\t * This function should be called from context switcher after selecting new task that will be run.\r\n\t *\/\r\n\r\n\tvoid reset();\r\n\r\nprivate:\r\n\r\n\t\/\/\/ round-robin quantum\r\n\tuint8_t quantum_;\r\n};\r\n\r\n}\t\/\/ namespace scheduler\r\n\r\n}\t\/\/ namespace distortos\r\n\r\n#endif\t\/\/ INCLUDE_DISTORTOS_SCHEDULER_ROUNDROBINQUANTUM_HPP_\r\n<|endoftext|>"} {"text":"<commit_before>\/\/\/\n\/\/ This file is part of the Marble Virtual Globe.\n\/\/\n\/\/ This program is free software licensed under the GNU LGPL. You can\n\/\/ find a copy of this license in LICENSE.txt in the top directory of\n\/\/ the source code.\n\/\/\n\/\/ Copyright 2004-2007 Torsten Rahn <tackat@kde.org>\n\/\/ Copyright 2007 Inge Wallin <ingwa@kde.org>\n\/\/ Copyright 2007 Thomas Zander <zander@kde.org>\n\/\/ Copyright 2010 Bastian Holst <bastianholst@gmx.de>\n\/\/\n\n\/\/ Self\n#include \"NavigationWidget.h\"\n\n\/\/ Marble\n#include \"MarbleDebug.h\"\n#include \"MarbleModel.h\"\n#include \"MarbleWidget.h\"\n#include \"MarbleRunnerManager.h\"\n#include \"MarblePlacemarkModel.h\"\n#include \"GeoDataDocument.h\"\n#include \"GeoDataTreeModel.h\"\n#include \"GeoSceneDocument.h\"\n#include \"GeoSceneHead.h\"\n\n\/\/ Qt\n#include <QtCore\/QTime>\n#include <QtCore\/QTimer>\n#include <QtGui\/QSortFilterProxyModel>\n\nusing namespace Marble;\n\n#include \"ui_NavigationWidget.h\"\n\nnamespace Marble\n{\n\nclass NavigationWidgetPrivate\n{\n public:\n Ui::NavigationWidget m_navigationUi;\n MarbleWidget *m_widget;\n QSortFilterProxyModel *m_sortproxy;\n QString m_searchTerm;\n MarbleRunnerManager *m_runnerManager;\n QTimer m_deferSearch;\n GeoDataTreeModel m_treeModel;\n GeoDataDocument *m_document;\n\n NavigationWidgetPrivate()\n : m_document( new GeoDataDocument ) {\n m_document->setDocumentRole( SearchResultDocument );\n m_treeModel.setRootDocument( m_document );\n };\n\n};\n\nNavigationWidget::NavigationWidget( QWidget *parent, Qt::WindowFlags f )\n : QWidget( parent, f ),\n d( new NavigationWidgetPrivate() )\n{\n d->m_searchTerm.clear();\n d->m_widget = 0;\n\n d->m_navigationUi.setupUi( this );\n\n d->m_sortproxy = new QSortFilterProxyModel( this );\n d->m_navigationUi.locationListView->setModel( d->m_sortproxy );\n d->m_deferSearch.setSingleShot( true );\n connect ( &d->m_deferSearch, SIGNAL( timeout() ),\n this, SLOT( search()) );\n\n connect( d->m_navigationUi.goHomeButton, SIGNAL( clicked() ),\n this, SIGNAL( goHome() ) );\n connect( d->m_navigationUi.zoomSlider, SIGNAL( valueChanged( int ) ),\n this, SIGNAL( zoomChanged( int ) ) );\n connect( d->m_navigationUi.zoomInButton, SIGNAL( clicked() ),\n this, SIGNAL( zoomIn() ) );\n connect( d->m_navigationUi.zoomOutButton, SIGNAL( clicked() ),\n this, SIGNAL( zoomOut() ) );\n\n connect( d->m_navigationUi.zoomSlider, SIGNAL( valueChanged( int ) ),\n this, SLOT( updateButtons( int ) ) );\n\n connect( d->m_navigationUi.moveLeftButton, SIGNAL( clicked() ),\n this, SIGNAL( moveLeft() ) );\n connect( d->m_navigationUi.moveRightButton, SIGNAL( clicked() ),\n this, SIGNAL( moveRight() ) );\n connect( d->m_navigationUi.moveUpButton, SIGNAL( clicked() ),\n this, SIGNAL( moveUp() ) );\n connect( d->m_navigationUi.moveDownButton, SIGNAL( clicked() ),\n this, SIGNAL( moveDown() ) );\n\n connect( d->m_navigationUi.locationListView, SIGNAL( activated( const QModelIndex& ) ),\n this, SLOT( mapCenterOnSignal( const QModelIndex& ) ) );\n\n connect( d->m_navigationUi.searchLineEdit, SIGNAL( textChanged( const QString& ) ),\n this, SLOT( searchLineChanged( const QString& ) ) );\n connect( d->m_navigationUi.searchLineEdit, SIGNAL( returnPressed() ),\n this, SLOT( searchReturnPressed() ) );\n\n connect( d->m_navigationUi.zoomSlider, SIGNAL( sliderPressed() ),\n this, SLOT( adjustForAnimation() ) );\n connect( d->m_navigationUi.zoomSlider, SIGNAL( sliderReleased() ),\n this, SLOT( adjustForStill() ) );\n}\n\nNavigationWidget::~NavigationWidget()\n{\n delete d;\n}\n\nvoid NavigationWidget::setMarbleWidget( MarbleWidget *widget )\n{\n d->m_runnerManager = new MarbleRunnerManager( widget->model()->pluginManager(), this );\n connect( d->m_runnerManager, SIGNAL( searchResultChanged( QVector<GeoDataPlacemark*> ) ),\n this, SLOT( setLocations( QVector<GeoDataPlacemark*> ) ) );\n\n d->m_widget = widget;\n d->m_runnerManager->setModel( widget->model() );\n d->m_widget->model()->treeModel()->addDocument( d->m_document );\n\n d->m_sortproxy->setSortLocaleAware( true );\n d->m_sortproxy->setDynamicSortFilter( true );\n\n \/\/ Make us aware of all the Placemarks in the MarbleModel so that\n \/\/ we can search them.\n d->m_sortproxy->setSourceModel( d->m_widget->model()->placemarkModel() );\n d->m_sortproxy->sort( 0 );\n\n \/\/ Connect necessary signals.\n connect( this, SIGNAL( goHome() ), d->m_widget, SLOT( goHome() ) );\n connect( this, SIGNAL( zoomChanged(int) ), d->m_widget, SLOT( zoomView( int ) ) );\n connect( this, SIGNAL( zoomIn() ), d->m_widget, SLOT( zoomIn() ) );\n connect( this, SIGNAL( zoomOut() ), d->m_widget, SLOT( zoomOut() ) );\n\n connect( this, SIGNAL( moveLeft() ), d->m_widget, SLOT( moveLeft() ) );\n connect( this, SIGNAL( moveRight() ), d->m_widget, SLOT( moveRight() ) );\n connect( this, SIGNAL( moveUp() ), d->m_widget, SLOT( moveUp() ) );\n connect( this, SIGNAL( moveDown() ), d->m_widget, SLOT( moveDown() ) );\n\n connect( d->m_widget, SIGNAL( zoomChanged( int ) ),\n this, SLOT( changeZoom( int ) ) );\n\n connect( d->m_widget, SIGNAL( themeChanged( QString ) ),\n this, SLOT( selectTheme( QString ) ) );\n}\n\nvoid NavigationWidget::changeZoom( int zoom )\n{\n \/\/ There exists a circular signal\/slot connection between MarbleWidget and this widget's\n \/\/ zoom slider. MarbleWidget prevents recursion, but it still loops one time unless\n \/\/ blocked here. Note that it would be possible to only connect the sliders\n \/\/ sliderMoved signal instead of its valueChanged signal above to break up the loop.\n \/\/ This however means that the slider cannot be operated with the mouse wheel, as this\n \/\/ does not emit the sliderMoved signal for some reason. Therefore the signal is blocked\n \/\/ below before calling setValue on the slider to avoid that it calls back to MarbleWidget,\n \/\/ and then un-blocked again to make user interaction possible.\n\n d->m_navigationUi.zoomSlider->blockSignals( true );\n\n d->m_navigationUi.zoomSlider->setValue( zoom );\n \/\/ As we have disabled all zoomSlider Signals, we have to update our buttons seperately.\n updateButtons( zoom );\n\n d->m_navigationUi.zoomSlider->blockSignals( false );\n}\n\nvoid NavigationWidget::searchLineChanged( const QString &search )\n{\n d->m_searchTerm = search;\n \/\/ if search line is empty, restore original geonames\n if ( d->m_searchTerm.isEmpty() ) {\n \/\/ set the proxy list to the placemarkModel\n d->m_sortproxy->setSourceModel( d->m_widget->model()->placemarkModel() );\n d->m_sortproxy->sort( 0 );\n d->m_widget->model()->placemarkSelectionModel()->clear();\n\n \/\/ clear the local document\n d->m_widget->model()->treeModel()->removeDocument( d->m_document );\n d->m_document->clear();\n d->m_widget->model()->treeModel()->addDocument( d->m_document );\n }\n d->m_deferSearch.start( 500 );\n}\n\nvoid NavigationWidget::searchReturnPressed()\n{\n \/\/ do nothing if search term empty\n if ( !d->m_searchTerm.isEmpty() ) {\n d->m_runnerManager->findPlacemarks( d->m_searchTerm );\n }\n}\n\nvoid NavigationWidget::search()\n{\n d->m_deferSearch.stop();\n int currentSelected = d->m_navigationUi.locationListView->currentIndex().row();\n d->m_navigationUi.locationListView->selectItem( d->m_searchTerm );\n if ( currentSelected != d->m_navigationUi.locationListView->currentIndex().row() )\n d->m_navigationUi.locationListView->activate();\n}\n\nvoid NavigationWidget::setLocations( QVector<GeoDataPlacemark*> locations )\n{\n QTime t;\n t.start();\n\n \/\/ fill the local document with results\n d->m_widget->model()->placemarkSelectionModel()->clear();\n d->m_widget->model()->treeModel()->removeDocument( d->m_document );\n d->m_document->clear();\n foreach (GeoDataPlacemark *placemark, locations ) {\n d->m_document->append( new GeoDataPlacemark( *placemark ) );\n }\n d->m_widget->model()->treeModel()->addDocument( d->m_document );\n d->m_widget->centerOn( d->m_document->latLonAltBox() );\n\n \/\/ set the proxy list to the list of results\n d->m_sortproxy->setSourceModel( &d->m_treeModel );\n d->m_sortproxy->sort( 0 );\n mDebug() << \"NavigationWidget (sort): Time elapsed:\"<< t.elapsed() << \" ms\";\n}\n\nvoid NavigationWidget::selectTheme( const QString &theme )\n{\n Q_UNUSED( theme )\n\n if( !d->m_widget )\n return;\n\n d->m_navigationUi.zoomSlider->setMinimum( d->m_widget->minimumZoom() );\n d->m_navigationUi.zoomSlider->setMaximum( d->m_widget->maximumZoom() );\n updateButtons( d->m_navigationUi.zoomSlider->value() );\n}\n\nvoid NavigationWidget::updateButtons( int value )\n{\n if ( value <= d->m_navigationUi.zoomSlider->minimum() ) {\n d->m_navigationUi.zoomInButton->setEnabled( true );\n d->m_navigationUi.zoomOutButton->setEnabled( false );\n } else if ( value >= d->m_navigationUi.zoomSlider->maximum() ) {\n d->m_navigationUi.zoomInButton->setEnabled( false );\n d->m_navigationUi.zoomOutButton->setEnabled( true );\n } else {\n d->m_navigationUi.zoomInButton->setEnabled( true );\n d->m_navigationUi.zoomOutButton->setEnabled( true );\n }\n}\n\nvoid NavigationWidget::mapCenterOnSignal( const QModelIndex &index )\n{\n if( !index.isValid() ) {\n return;\n }\n GeoDataObject *object\n = qVariantValue<GeoDataObject*>( index.model()->data(index, MarblePlacemarkModel::ObjectPointerRole ) );\n if ( dynamic_cast<GeoDataPlacemark*>(object) )\n {\n GeoDataPlacemark *placemark = static_cast<GeoDataPlacemark*>(object);\n d->m_widget->centerOn( *placemark, true );\n d->m_widget->model()->placemarkSelectionModel()->select( d->m_sortproxy->mapToSource( index ), QItemSelectionModel::ClearAndSelect );\n }\n}\n\nvoid NavigationWidget::adjustForAnimation()\n{\n \/\/ TODO: use signals here as well\n if ( !d->m_widget )\n return;\n\n d->m_widget->setViewContext( Animation );\n}\n\nvoid NavigationWidget::adjustForStill()\n{\n \/\/ TODO: use signals here as well\n if ( !d->m_widget )\n return;\n\n d->m_widget->setViewContext( Still );\n}\n\nvoid NavigationWidget::resizeEvent ( QResizeEvent * )\n{\n bool smallScreen = MarbleGlobal::getInstance()->profiles() & MarbleGlobal::SmallScreen;\n\n if ( smallScreen || height() < 390 ) {\n if ( !d->m_navigationUi.zoomSlider->isHidden() ) {\n setUpdatesEnabled(false);\n d->m_navigationUi.zoomSlider->hide();\n d->m_navigationUi.m_pSpacerFrame->setSizePolicy( QSizePolicy::Preferred,\n QSizePolicy::Expanding );\n setUpdatesEnabled(true);\n }\n } else {\n if ( d->m_navigationUi.zoomSlider->isHidden() ) {\n setUpdatesEnabled(false);\n d->m_navigationUi.zoomSlider->show();\n d->m_navigationUi.m_pSpacerFrame->setSizePolicy( QSizePolicy::Preferred,\n QSizePolicy::Fixed );\n setUpdatesEnabled(true);\n }\n }\n}\n\n}\n\n#include \"NavigationWidget.moc\"\n<commit_msg>NavigationWidget: name the results document<commit_after>\/\/\/\n\/\/ This file is part of the Marble Virtual Globe.\n\/\/\n\/\/ This program is free software licensed under the GNU LGPL. You can\n\/\/ find a copy of this license in LICENSE.txt in the top directory of\n\/\/ the source code.\n\/\/\n\/\/ Copyright 2004-2007 Torsten Rahn <tackat@kde.org>\n\/\/ Copyright 2007 Inge Wallin <ingwa@kde.org>\n\/\/ Copyright 2007 Thomas Zander <zander@kde.org>\n\/\/ Copyright 2010 Bastian Holst <bastianholst@gmx.de>\n\/\/\n\n\/\/ Self\n#include \"NavigationWidget.h\"\n\n\/\/ Marble\n#include \"MarbleDebug.h\"\n#include \"MarbleModel.h\"\n#include \"MarbleWidget.h\"\n#include \"MarbleRunnerManager.h\"\n#include \"MarblePlacemarkModel.h\"\n#include \"GeoDataDocument.h\"\n#include \"GeoDataTreeModel.h\"\n#include \"GeoSceneDocument.h\"\n#include \"GeoSceneHead.h\"\n\n\/\/ Qt\n#include <QtCore\/QTime>\n#include <QtCore\/QTimer>\n#include <QtGui\/QSortFilterProxyModel>\n\nusing namespace Marble;\n\n#include \"ui_NavigationWidget.h\"\n\nnamespace Marble\n{\n\nclass NavigationWidgetPrivate\n{\n public:\n Ui::NavigationWidget m_navigationUi;\n MarbleWidget *m_widget;\n QSortFilterProxyModel *m_sortproxy;\n QString m_searchTerm;\n MarbleRunnerManager *m_runnerManager;\n QTimer m_deferSearch;\n GeoDataTreeModel m_treeModel;\n GeoDataDocument *m_document;\n\n NavigationWidgetPrivate()\n : m_document( new GeoDataDocument ) {\n m_document->setDocumentRole( SearchResultDocument );\n m_document->setName(\"Search Results\");\n m_treeModel.setRootDocument( m_document );\n };\n\n};\n\nNavigationWidget::NavigationWidget( QWidget *parent, Qt::WindowFlags f )\n : QWidget( parent, f ),\n d( new NavigationWidgetPrivate() )\n{\n d->m_searchTerm.clear();\n d->m_widget = 0;\n\n d->m_navigationUi.setupUi( this );\n\n d->m_sortproxy = new QSortFilterProxyModel( this );\n d->m_navigationUi.locationListView->setModel( d->m_sortproxy );\n d->m_deferSearch.setSingleShot( true );\n connect ( &d->m_deferSearch, SIGNAL( timeout() ),\n this, SLOT( search()) );\n\n connect( d->m_navigationUi.goHomeButton, SIGNAL( clicked() ),\n this, SIGNAL( goHome() ) );\n connect( d->m_navigationUi.zoomSlider, SIGNAL( valueChanged( int ) ),\n this, SIGNAL( zoomChanged( int ) ) );\n connect( d->m_navigationUi.zoomInButton, SIGNAL( clicked() ),\n this, SIGNAL( zoomIn() ) );\n connect( d->m_navigationUi.zoomOutButton, SIGNAL( clicked() ),\n this, SIGNAL( zoomOut() ) );\n\n connect( d->m_navigationUi.zoomSlider, SIGNAL( valueChanged( int ) ),\n this, SLOT( updateButtons( int ) ) );\n\n connect( d->m_navigationUi.moveLeftButton, SIGNAL( clicked() ),\n this, SIGNAL( moveLeft() ) );\n connect( d->m_navigationUi.moveRightButton, SIGNAL( clicked() ),\n this, SIGNAL( moveRight() ) );\n connect( d->m_navigationUi.moveUpButton, SIGNAL( clicked() ),\n this, SIGNAL( moveUp() ) );\n connect( d->m_navigationUi.moveDownButton, SIGNAL( clicked() ),\n this, SIGNAL( moveDown() ) );\n\n connect( d->m_navigationUi.locationListView, SIGNAL( activated( const QModelIndex& ) ),\n this, SLOT( mapCenterOnSignal( const QModelIndex& ) ) );\n\n connect( d->m_navigationUi.searchLineEdit, SIGNAL( textChanged( const QString& ) ),\n this, SLOT( searchLineChanged( const QString& ) ) );\n connect( d->m_navigationUi.searchLineEdit, SIGNAL( returnPressed() ),\n this, SLOT( searchReturnPressed() ) );\n\n connect( d->m_navigationUi.zoomSlider, SIGNAL( sliderPressed() ),\n this, SLOT( adjustForAnimation() ) );\n connect( d->m_navigationUi.zoomSlider, SIGNAL( sliderReleased() ),\n this, SLOT( adjustForStill() ) );\n}\n\nNavigationWidget::~NavigationWidget()\n{\n delete d;\n}\n\nvoid NavigationWidget::setMarbleWidget( MarbleWidget *widget )\n{\n d->m_runnerManager = new MarbleRunnerManager( widget->model()->pluginManager(), this );\n connect( d->m_runnerManager, SIGNAL( searchResultChanged( QVector<GeoDataPlacemark*> ) ),\n this, SLOT( setLocations( QVector<GeoDataPlacemark*> ) ) );\n\n d->m_widget = widget;\n d->m_runnerManager->setModel( widget->model() );\n d->m_widget->model()->treeModel()->addDocument( d->m_document );\n\n d->m_sortproxy->setSortLocaleAware( true );\n d->m_sortproxy->setDynamicSortFilter( true );\n\n \/\/ Make us aware of all the Placemarks in the MarbleModel so that\n \/\/ we can search them.\n d->m_sortproxy->setSourceModel( d->m_widget->model()->placemarkModel() );\n d->m_sortproxy->sort( 0 );\n\n \/\/ Connect necessary signals.\n connect( this, SIGNAL( goHome() ), d->m_widget, SLOT( goHome() ) );\n connect( this, SIGNAL( zoomChanged(int) ), d->m_widget, SLOT( zoomView( int ) ) );\n connect( this, SIGNAL( zoomIn() ), d->m_widget, SLOT( zoomIn() ) );\n connect( this, SIGNAL( zoomOut() ), d->m_widget, SLOT( zoomOut() ) );\n\n connect( this, SIGNAL( moveLeft() ), d->m_widget, SLOT( moveLeft() ) );\n connect( this, SIGNAL( moveRight() ), d->m_widget, SLOT( moveRight() ) );\n connect( this, SIGNAL( moveUp() ), d->m_widget, SLOT( moveUp() ) );\n connect( this, SIGNAL( moveDown() ), d->m_widget, SLOT( moveDown() ) );\n\n connect( d->m_widget, SIGNAL( zoomChanged( int ) ),\n this, SLOT( changeZoom( int ) ) );\n\n connect( d->m_widget, SIGNAL( themeChanged( QString ) ),\n this, SLOT( selectTheme( QString ) ) );\n}\n\nvoid NavigationWidget::changeZoom( int zoom )\n{\n \/\/ There exists a circular signal\/slot connection between MarbleWidget and this widget's\n \/\/ zoom slider. MarbleWidget prevents recursion, but it still loops one time unless\n \/\/ blocked here. Note that it would be possible to only connect the sliders\n \/\/ sliderMoved signal instead of its valueChanged signal above to break up the loop.\n \/\/ This however means that the slider cannot be operated with the mouse wheel, as this\n \/\/ does not emit the sliderMoved signal for some reason. Therefore the signal is blocked\n \/\/ below before calling setValue on the slider to avoid that it calls back to MarbleWidget,\n \/\/ and then un-blocked again to make user interaction possible.\n\n d->m_navigationUi.zoomSlider->blockSignals( true );\n\n d->m_navigationUi.zoomSlider->setValue( zoom );\n \/\/ As we have disabled all zoomSlider Signals, we have to update our buttons seperately.\n updateButtons( zoom );\n\n d->m_navigationUi.zoomSlider->blockSignals( false );\n}\n\nvoid NavigationWidget::searchLineChanged( const QString &search )\n{\n d->m_searchTerm = search;\n \/\/ if search line is empty, restore original geonames\n if ( d->m_searchTerm.isEmpty() ) {\n \/\/ set the proxy list to the placemarkModel\n d->m_sortproxy->setSourceModel( d->m_widget->model()->placemarkModel() );\n d->m_sortproxy->sort( 0 );\n d->m_widget->model()->placemarkSelectionModel()->clear();\n\n \/\/ clear the local document\n d->m_widget->model()->treeModel()->removeDocument( d->m_document );\n d->m_document->clear();\n d->m_widget->model()->treeModel()->addDocument( d->m_document );\n }\n d->m_deferSearch.start( 500 );\n}\n\nvoid NavigationWidget::searchReturnPressed()\n{\n \/\/ do nothing if search term empty\n if ( !d->m_searchTerm.isEmpty() ) {\n d->m_runnerManager->findPlacemarks( d->m_searchTerm );\n }\n}\n\nvoid NavigationWidget::search()\n{\n d->m_deferSearch.stop();\n int currentSelected = d->m_navigationUi.locationListView->currentIndex().row();\n d->m_navigationUi.locationListView->selectItem( d->m_searchTerm );\n if ( currentSelected != d->m_navigationUi.locationListView->currentIndex().row() )\n d->m_navigationUi.locationListView->activate();\n}\n\nvoid NavigationWidget::setLocations( QVector<GeoDataPlacemark*> locations )\n{\n QTime t;\n t.start();\n\n \/\/ fill the local document with results\n d->m_widget->model()->placemarkSelectionModel()->clear();\n d->m_widget->model()->treeModel()->removeDocument( d->m_document );\n d->m_document->clear();\n foreach (GeoDataPlacemark *placemark, locations ) {\n d->m_document->append( new GeoDataPlacemark( *placemark ) );\n }\n d->m_widget->model()->treeModel()->addDocument( d->m_document );\n d->m_widget->centerOn( d->m_document->latLonAltBox() );\n\n \/\/ set the proxy list to the list of results\n d->m_sortproxy->setSourceModel( &d->m_treeModel );\n d->m_sortproxy->sort( 0 );\n mDebug() << \"NavigationWidget (sort): Time elapsed:\"<< t.elapsed() << \" ms\";\n}\n\nvoid NavigationWidget::selectTheme( const QString &theme )\n{\n Q_UNUSED( theme )\n\n if( !d->m_widget )\n return;\n\n d->m_navigationUi.zoomSlider->setMinimum( d->m_widget->minimumZoom() );\n d->m_navigationUi.zoomSlider->setMaximum( d->m_widget->maximumZoom() );\n updateButtons( d->m_navigationUi.zoomSlider->value() );\n}\n\nvoid NavigationWidget::updateButtons( int value )\n{\n if ( value <= d->m_navigationUi.zoomSlider->minimum() ) {\n d->m_navigationUi.zoomInButton->setEnabled( true );\n d->m_navigationUi.zoomOutButton->setEnabled( false );\n } else if ( value >= d->m_navigationUi.zoomSlider->maximum() ) {\n d->m_navigationUi.zoomInButton->setEnabled( false );\n d->m_navigationUi.zoomOutButton->setEnabled( true );\n } else {\n d->m_navigationUi.zoomInButton->setEnabled( true );\n d->m_navigationUi.zoomOutButton->setEnabled( true );\n }\n}\n\nvoid NavigationWidget::mapCenterOnSignal( const QModelIndex &index )\n{\n if( !index.isValid() ) {\n return;\n }\n GeoDataObject *object\n = qVariantValue<GeoDataObject*>( index.model()->data(index, MarblePlacemarkModel::ObjectPointerRole ) );\n if ( dynamic_cast<GeoDataPlacemark*>(object) )\n {\n GeoDataPlacemark *placemark = static_cast<GeoDataPlacemark*>(object);\n d->m_widget->centerOn( *placemark, true );\n d->m_widget->model()->placemarkSelectionModel()->select( d->m_sortproxy->mapToSource( index ), QItemSelectionModel::ClearAndSelect );\n }\n}\n\nvoid NavigationWidget::adjustForAnimation()\n{\n \/\/ TODO: use signals here as well\n if ( !d->m_widget )\n return;\n\n d->m_widget->setViewContext( Animation );\n}\n\nvoid NavigationWidget::adjustForStill()\n{\n \/\/ TODO: use signals here as well\n if ( !d->m_widget )\n return;\n\n d->m_widget->setViewContext( Still );\n}\n\nvoid NavigationWidget::resizeEvent ( QResizeEvent * )\n{\n bool smallScreen = MarbleGlobal::getInstance()->profiles() & MarbleGlobal::SmallScreen;\n\n if ( smallScreen || height() < 390 ) {\n if ( !d->m_navigationUi.zoomSlider->isHidden() ) {\n setUpdatesEnabled(false);\n d->m_navigationUi.zoomSlider->hide();\n d->m_navigationUi.m_pSpacerFrame->setSizePolicy( QSizePolicy::Preferred,\n QSizePolicy::Expanding );\n setUpdatesEnabled(true);\n }\n } else {\n if ( d->m_navigationUi.zoomSlider->isHidden() ) {\n setUpdatesEnabled(false);\n d->m_navigationUi.zoomSlider->show();\n d->m_navigationUi.m_pSpacerFrame->setSizePolicy( QSizePolicy::Preferred,\n QSizePolicy::Fixed );\n setUpdatesEnabled(true);\n }\n }\n}\n\n}\n\n#include \"NavigationWidget.moc\"\n<|endoftext|>"} {"text":"<commit_before>\/\/===-- InstCount.cpp - Collects the count of all instructions ------------===\/\/\n\/\/\n\/\/ This pass collects the count of all instructions and reports them \n\/\/\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/Pass.h\"\n#include \"llvm\/Module.h\"\n#include \"llvm\/iMemory.h\"\n#include \"llvm\/iTerminators.h\"\n#include \"llvm\/iPHINode.h\"\n#include \"llvm\/iOther.h\"\n#include \"llvm\/iOperators.h\"\n#include \"llvm\/Support\/InstVisitor.h\"\n#include \"llvm\/Support\/InstIterator.h\"\n#include \"llvm\/Support\/InstIterator.h\"\n#include \"Support\/Statistic.h\"\n#include <algorithm>\n\nnamespace {\n static Statistic<> NumReturnInst(\"instcount\",\"Number of ReturnInsts\");\n static Statistic<> NumBranchInst(\"instcount\", \"Number of BranchInsts\");\n static Statistic<> NumPHINode(\"instcount\", \"Number of PHINodes\");\n static Statistic<> NumCastInst(\"instcount\", \"Number of CastInsts\");\n static Statistic<> NumCallInst(\"instcount\", \"Number of CallInsts\");\n static Statistic<> NumMallocInst(\"instcount\", \"Number of MallocInsts\");\n static Statistic<> NumAllocaInst(\"instcount\", \"Number of AllocaInsts\");\n static Statistic<> NumFreeInst(\"instcount\", \"Number of FreeInsts\");\n static Statistic<> NumLoadInst(\"instcount\", \"Number of LoadInsts\");\n static Statistic<> NumStoreInst(\"instcount\", \"Number of StoreInsts\");\n static Statistic<> NumGetElementPtrInst(\"instcount\",\n\t\t\t\t\t \"Number of GetElementPtrInsts\");\n \n static Statistic<> NumSwitchInst(\"instcount\", \"Number of SwitchInsts\");\n static Statistic<> NumInvokeInst(\"instcount\", \"Number of InvokeInsts\");\n static Statistic<> NumBinaryOperator(\"instcount\",\n\t\t\t\t \"Total Number of BinaryOperators\");\n \n static Statistic<> NumShiftInst(\"instcount\", \" Total Number of ShiftInsts\");\n static Statistic<> NumShlInst(\"instcount\", \"Number of Left ShiftInsts\");\n \n static Statistic<> NumShrInst(\"instcount\", \"Number of Right ShiftInsts\");\n \n\n static Statistic<> NumAddInst(\"instcount\", \"Number of AddInsts\");\n static Statistic<> NumSubInst(\"instcount\", \"Number of SubInsts\");\n static Statistic<> NumMulInst(\"instcount\", \"Number of MulInsts\");\n static Statistic<> NumDivInst(\"instcount\", \"Number of DivInsts\");\n static Statistic<> NumRemInst(\"instcount\", \"Number of RemInsts\");\n static Statistic<> NumAndInst(\"instcount\", \"Number of AndInsts\");\n static Statistic<> NumOrInst(\"instcount\", \"Number of OrInsts\");\n static Statistic<> NumXorInst(\"instcount\", \"Number of XorInsts\");\n static Statistic<> NumSetCondInst(\"instcount\", \"Total Number of SetCondInsts\");\n static Statistic<> NumSetEQInst(\"instcount\", \"Number of SetEQInsts\");\n static Statistic<> NumSetNEInst(\"instcount\", \"Number of SetNEInsts\");\n static Statistic<> NumSetLEInst(\"instcount\", \"Number of SetLEInsts\");\n static Statistic<> NumSetGEInst(\"instcount\", \"Number of SetGEInsts\");\n static Statistic<> NumSetLTInst(\"instcount\", \"Number of SetLTInsts\");\n static Statistic<> NumSetGTInst(\"instcount\", \"Number of SetGTInsts\");\n \n class InstCount : public Pass, public InstVisitor<InstCount> {\n private:\n friend class InstVisitor<InstCount>;\n\n\n void visitBinaryOperator(BinaryOperator &I);\n void visitShiftInst(ShiftInst &I);\n void visitSetCondInst(SetCondInst &I);\n \n inline void visitSwitchInst(SwitchInst &I) { NumSwitchInst++; }\n inline void visitInvokeInst(InvokeInst &I) { NumInvokeInst++; }\n inline void visitReturnInst(ReturnInst &I) { NumReturnInst++; }\n inline void visitBranchInst(BranchInst &I) { NumBranchInst++; }\n inline void visitPHINode(PHINode &I) { NumPHINode++; }\n inline void visitCastInst (CastInst &I) { NumCastInst++; }\n inline void visitCallInst (CallInst &I) { NumCallInst++; }\n inline void visitMallocInst(MallocInst &I) { NumMallocInst++; }\n inline void visitAllocaInst(AllocaInst &I) { NumAllocaInst++; }\n inline void visitFreeInst (FreeInst &I) { NumFreeInst++; }\n inline void visitLoadInst (LoadInst &I) { NumLoadInst++; }\n inline void visitStoreInst (StoreInst &I) { NumStoreInst++; }\n inline void visitGetElementPtrInst(GetElementPtrInst &I) {\n NumGetElementPtrInst++; }\n\n inline void visitInstruction(Instruction &I) {\n std::cerr << \"Instruction Count does not know about \" << I;\n abort();\n }\n public:\n virtual bool run(Module &M);\n\n virtual void getAnalysisUsage(AnalysisUsage &AU) const {\n AU.setPreservesAll();\n }\n };\n\n RegisterAnalysis<InstCount> X(\"instcount\",\n\t\t \t \"Counts the various types of Instructions\");\n \n}\n\n\/\/ createInstCountPass - The public interface to this file...\nPass *createInstCountPass() { return new InstCount(); }\n\n\n\/\/ InstCount::run - This is the main Analysis entry point for a\n\/\/ function.\n\/\/\nbool InstCount::run(Module &M) {\n for (Module::iterator mI = M.begin(), mE = M.end(); mI != mE; ++mI)\n for (inst_iterator I = inst_begin(*mI), E = inst_end(*mI); I != E; ++I)\n visit(*I);\n return false;\n}\n\n\n\nvoid InstCount::visitBinaryOperator(BinaryOperator &I) {\n NumBinaryOperator++;\n switch (I.getOpcode()) {\n case Instruction::Add: NumAddInst++; break;\n case Instruction::Sub: NumSubInst++; break;\n case Instruction::Mul: NumMulInst++; break;\n case Instruction::Div: NumDivInst++; break;\n case Instruction::Rem: NumRemInst++; break;\n case Instruction::And: NumAndInst++; break;\n case Instruction::Or: NumOrInst++; break;\n case Instruction::Xor: NumXorInst++; break;\n default : std::cerr<< \" Wrong binary operator \\n\";\n }\n}\n\nvoid InstCount::visitSetCondInst(SetCondInst &I) {\n NumBinaryOperator++;\n NumSetCondInst++;\n switch (I.getOpcode()) {\n case Instruction::SetEQ: NumSetEQInst++; break;\n case Instruction::SetNE: NumSetNEInst++; break;\n case Instruction::SetLE: NumSetLEInst++; break;\n case Instruction::SetGE: NumSetGEInst++; break;\n case Instruction::SetLT: NumSetLTInst++; break;\n case Instruction::SetGT: NumSetGTInst++; break;\n default : std::cerr<< \" Wrong SetCond Inst \\n\";\n }\n}\n\nvoid InstCount::visitShiftInst(ShiftInst &I) { \n NumShiftInst++;\n switch (I.getOpcode()) {\n case Instruction::Shl: NumShlInst++; break;\n case Instruction::Shr: NumShrInst++; break;\n default : std::cerr<< \" Wrong ShiftInst \\n\";\n }\n}\n<commit_msg>Simplify code<commit_after>\/\/===-- InstCount.cpp - Collects the count of all instructions ------------===\/\/\n\/\/\n\/\/ This pass collects the count of all instructions and reports them \n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/Pass.h\"\n#include \"llvm\/Module.h\"\n#include \"llvm\/Support\/InstVisitor.h\"\n#include \"Support\/Statistic.h\"\n\nnamespace {\n#define HANDLE_INST(N, OPCODE, CLASS) \\\n Statistic<> Num##OPCODE##Inst(\"instcount\", \"Number of \" #OPCODE \" insts\");\n\n#include \"llvm\/Instruction.def\"\n\n class InstCount : public Pass, public InstVisitor<InstCount> {\n friend class InstVisitor<InstCount>;\n\n#define HANDLE_INST(N, OPCODE, CLASS) \\\n void visit##OPCODE(CLASS &) { Num##OPCODE##Inst++; }\n\n#include \"llvm\/Instruction.def\"\n\n void visitInstruction(Instruction &I) {\n std::cerr << \"Instruction Count does not know about \" << I;\n abort();\n }\n public:\n virtual bool run(Module &M);\n\n virtual void getAnalysisUsage(AnalysisUsage &AU) const {\n AU.setPreservesAll();\n }\n virtual void print(std::ostream &O, Module *M) const {}\n\n };\n\n RegisterAnalysis<InstCount> X(\"instcount\",\n \"Counts the various types of Instructions\");\n}\n\n\/\/ InstCount::run - This is the main Analysis entry point for a\n\/\/ function.\n\/\/\nbool InstCount::run(Module &M) {\n visit(M);\n return false;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ This file is part of the Marble Desktop Globe.\n\/\/\n\/\/ This program is free software licensed under the GNU LGPL. You can\n\/\/ find a copy of this license in LICENSE.txt in the top directory of\n\/\/ the source code.\n\/\/\n\/\/ Copyright 2006-2007 Torsten Rahn <tackat@kde.org>\"\n\/\/ Copyright 2007 Inge Wallin <ingwa@kde.org>\"\n\/\/ Copyright 2008 Carlos Licea <carlos.licea@kdemail.net>\n\/\/\n\n#include \"TextureColorizer.h\"\n\n#include <cmath>\n\n#include <QtCore\/QDebug>\n#include <QtCore\/QFile>\n#include <QtCore\/QString>\n#include <QtGui\/QColor>\n#include <QtGui\/QImage>\n#include <QtGui\/QPainter>\n\n#include \"global.h\"\n#include \"GeoSceneDocument.h\"\n#include \"GeoSceneSettings.h\"\n#include \"ViewParams.h\"\n#include \"ViewportParams.h\"\n#include \"AbstractProjection.h\"\n#include \"MathHelper.h\"\n\nusing namespace Marble;\n\nuint TextureColorizer::texturepalette[16][512];\n\nTextureColorizer::TextureColorizer( const QString& seafile, \n const QString& landfile )\n{\n generatePalette(seafile, landfile);\n}\n\nQString TextureColorizer::seafile() const\n{\n return m_seafile;\n}\n\nQString TextureColorizer::landfile() const\n{\n return m_landfile;\n}\n\n\/\/ This function takes two images, both in viewParams:\n\/\/ - The coast image, which has a number of colors where each color\n\/\/ represents a sort of terrain (ex: land\/sea)\n\/\/ - The canvas image, which has a gray scale image, often\n\/\/ representing a height field.\n\/\/\n\/\/ It then uses the values of the pixels in the coast image to select\n\/\/ a color map. The value of the pixel in the canvas image is used as\n\/\/ an index into the selected color map and the resulting color is\n\/\/ written back to the canvas image. This way we can have different\n\/\/ color schemes for land and water.\n\/\/\n\/\/ In addition to this, a simple form of bump mapping is performed to\n\/\/ increase the illusion of height differences (see the variable\n\/\/ showRelief).\n\/\/ \n\nvoid TextureColorizer::colorize(ViewParams *viewParams)\n{\n QImage *origimg = viewParams->canvasImage();\n const QImage *coastimg = viewParams->coastImage();\n const qint64 radius = viewParams->radius();\n\n const int imgheight = origimg->height();\n const int imgwidth = origimg->width();\n const int imgrx = imgwidth \/ 2;\n const int imgry = imgheight \/ 2;\n \/\/ This variable is not used anywhere..\n const int imgradius = imgrx * imgrx + imgry * imgry;\n\n const uint landoffscreen = qRgb(255,0,0);\n \/\/ const uint seaoffscreen = qRgb(0,0,0);\n const uint lakeoffscreen = qRgb(0,0,0);\n \/\/ const uint glaciercolor = qRgb(200,200,200);\n\n int bump = 8;\n GpFifo emboss;\n emboss.buffer = 0;\n\n bool showRelief;\n viewParams->mapTheme()->settings()->propertyValue( \"relief\", showRelief );\n\n if ( radius * radius > imgradius\n || viewParams->projection() == Equirectangular\n || viewParams->projection() == Mercator )\n {\n int yTop = 0;\n int yBottom = imgheight;\n\n if( viewParams->projection() == Equirectangular\n || viewParams->projection() == Mercator )\n {\n \/\/ Calculate translation of center point\n double centerLon;\n double centerLat;\n viewParams->centerCoordinates( centerLon, centerLat );\n\n const float rad2Pixel = (double)( 2 * radius ) \/ M_PI;\n if ( viewParams->projection() == Equirectangular ) {\n int yCenterOffset = (int)( centerLat * rad2Pixel );\n yTop = ( imgry - radius + yCenterOffset < 0)? 0 : imgry - radius + yCenterOffset;\n yBottom = ( imgry + yCenterOffset + radius > imgheight )? imgheight : imgry + yCenterOffset + radius;\n }\n else if ( viewParams->projection() == Mercator ) {\n int yCenterOffset = (int)( asinh( tan( centerLat ) ) * rad2Pixel );\n yTop = ( imgry - 2 * radius + yCenterOffset < 0 ) ? 0 : imgry - 2 * radius + yCenterOffset;\n yBottom = ( imgry + 2 * radius + yCenterOffset > imgheight )? imgheight : imgry + 2 * radius + yCenterOffset;\n }\n }\n\n for (int y = yTop; y < yBottom; ++y) {\n\n QRgb *writeData = (QRgb*)( origimg->scanLine( y ) );\n const QRgb *coastData = (QRgb*)( coastimg->scanLine( y ) );\n\n uchar *readDataStart = origimg->scanLine( y );\n const uchar *readDataEnd = readDataStart + imgwidth*4;\n\n emboss.buffer = 0;\n\t\t\n for ( uchar* readData = readDataStart; \n\t\t readData < readDataEnd; \n\t\t readData += 4, ++writeData, ++coastData )\n\t {\n\n \/\/ Cheap Emboss \/ Bumpmapping\n const uchar& grey = *readData; \/\/ qBlue(*data);\n\n if ( showRelief ) {\n emboss.gpuint.x4 = grey;\n emboss.buffer = emboss.buffer >> 8;\n bump = ( emboss.gpuint.x1 + 8 - grey );\n if ( bump < 0 ) bump = 0;\n if ( bump > 15 ) bump = 15;\n }\n\n int alpha = qRed( *coastData );\n if ( alpha == 255 || alpha == 0 ) {\n if ( *coastData == landoffscreen )\n *writeData = texturepalette[bump][grey + 0x100]; \n else {\n if (*coastData == lakeoffscreen)\n *writeData = texturepalette[bump][0x055];\n else {\n *writeData = texturepalette[bump][grey];\n }\n }\n }\n else {\n double c = 1.0 \/ 255.0;\n\n if ( qRed( *coastData ) != 0 && qGreen( *coastData ) == 0) {\n\n QRgb landcolor = (QRgb)(texturepalette[bump][grey + 0x100]);\n QRgb watercolor = (QRgb)(texturepalette[bump][grey]);\n\n *writeData = qRgb( \n (int) ( c * ( alpha * qRed( landcolor )\n + ( 255 - alpha ) * qRed( watercolor ) ) ),\n (int) ( c * ( alpha * qGreen( landcolor )\n + ( 255 - alpha ) * qGreen( watercolor ) ) ),\n (int) ( c * ( alpha * qBlue( landcolor )\n + ( 255 - alpha ) * qBlue( watercolor ) ) )\n );\n }\n else {\n\n if ( qGreen( *coastData ) != 0 ) {\n\n QRgb landcolor = (QRgb)(texturepalette[bump][grey + 0x100]);\n QRgb glaciercolor = (QRgb)(texturepalette[bump][grey]);\n \n *writeData = qRgb( \n (int) ( c * ( alpha * qRed( glaciercolor )\n + ( 255 - alpha ) * qRed( landcolor ) ) ),\n (int) ( c * ( alpha * qGreen( glaciercolor )\n + ( 255 - alpha ) * qGreen( landcolor ) ) ),\n (int) ( c * ( alpha * qBlue( glaciercolor )\n + ( 255 - alpha ) * qBlue( landcolor ) ) )\n ); \n }\n }\n }\n }\n }\n }\n else {\n int yTop = ( imgry-radius < 0 ) ? 0 : imgry-radius;\n const int yBottom = ( yTop == 0 ) ? imgheight : imgry + radius;\n\n for ( int y = yTop; y < yBottom; ++y ) {\n const int dy = imgry - y;\n int rx = (int)sqrt( (double)( radius * radius - dy * dy ) );\n int xLeft = 0; \n int xRight = imgwidth;\n\n if ( imgrx-rx > 0 ) {\n xLeft = imgrx - rx; \n xRight = imgrx + rx;\n }\n\n QRgb *writeData = (QRgb*)( origimg->scanLine( y ) ) + xLeft;\n const QRgb *coastData = (QRgb*)( coastimg->scanLine( y ) ) + xLeft;\n\n uchar *readDataStart = origimg->scanLine( y ) + xLeft * 4;\n const uchar *readDataEnd = origimg->scanLine( y ) + xRight * 4;\n\n \n for ( uchar* readData = readDataStart;\n\t\t readData < readDataEnd;\n\t\t readData += 4, ++writeData, ++coastData )\n\t {\n \/\/ Cheap Embosss \/ Bumpmapping\n\n const uchar& grey = *readData; \/\/ qBlue(*data);\n\n if ( showRelief == true ) {\n emboss.buffer = emboss.buffer >> 8;\n emboss.gpuint.x4 = grey; \n bump = ( emboss.gpuint.x1 + 16 - grey ) >> 1;\n\n if ( bump > 15 ) bump = 15;\n if ( bump < 0 ) bump = 0;\n }\n\n int alpha = qRed( *coastData );\n if ( alpha == 255 || alpha == 0 ) {\n if ( *coastData == landoffscreen )\n *writeData = texturepalette[bump][grey + 0x100]; \n else {\n if (*coastData == lakeoffscreen)\n *writeData = texturepalette[bump][0x055];\n else {\n *writeData = texturepalette[bump][grey];\n }\n }\n }\n else {\n double c = 1.0 \/ 255.0;\n\n if ( qRed( *coastData ) != 0 && qGreen( *coastData ) == 0) {\n\n QRgb landcolor = (QRgb)(texturepalette[bump][grey + 0x100]);\n QRgb watercolor = (QRgb)(texturepalette[bump][grey]);\n\n *writeData = qRgb( \n (int) ( c * ( alpha * qRed( landcolor )\n + ( 255 - alpha ) * qRed( watercolor ) ) ),\n (int) ( c * ( alpha * qGreen( landcolor )\n + ( 255 - alpha ) * qGreen( watercolor ) ) ),\n (int) ( c * ( alpha * qBlue( landcolor )\n + ( 255 - alpha ) * qBlue( watercolor ) ) )\n );\n }\n else {\n\n if ( qGreen( *coastData ) != 0 ) {\n\n QRgb landcolor = (QRgb)(texturepalette[bump][grey + 0x100]);\n QRgb glaciercolor = (QRgb)(texturepalette[bump][grey]);\n \n *writeData = qRgb( \n (int) ( c * ( alpha * qRed( glaciercolor )\n + ( 255 - alpha ) * qRed( landcolor ) ) ),\n (int) ( c * ( alpha * qGreen( glaciercolor )\n + ( 255 - alpha ) * qGreen( landcolor ) ) ),\n (int) ( c * ( alpha * qBlue( glaciercolor )\n + ( 255 - alpha ) * qBlue( landcolor ) ) )\n ); \n }\n }\n }\n }\n }\n }\n}\n\nvoid TextureColorizer::generatePalette(const QString& seafile,\n\t\t\t\t const QString& landfile)\n{\n for(int i = 0; i < 16; i++) {\n for(int j = 0; j < 512; j++) {\n texturepalette[i][j] = 0;\n }\n }\n QImage gradientImage ( 256, 10, QImage::Format_RGB32 );\n QPainter gradientPainter;\n gradientPainter.begin( &gradientImage );\n gradientPainter.setPen( Qt::NoPen );\n\n QImage shadingImage ( 256, 10, QImage::Format_RGB32 );\n QPainter shadingPainter;\n shadingPainter.begin( &shadingImage );\n shadingPainter.setPen( Qt::NoPen );\n\n int offset = 0;\n\n QStringList filelist;\n filelist << seafile << landfile;\n\n foreach ( const QString &filename, filelist ) {\n\n QLinearGradient gradient( 0, 0, 256, 0 );\n\n QFile file( filename );\n file.open( QIODevice::ReadOnly );\n QTextStream stream( &file ); \/\/ read the data from the file\n QString evalstrg;\n\n while ( !stream.atEnd() ) {\n stream >> evalstrg;\n if ( !evalstrg.isEmpty() && evalstrg.contains( \"=\" ) ) {\n QString colorValue = evalstrg.section( \"=\", 0, 0 );\n QString colorPosition = evalstrg.section( \"=\", 1, 1 );\n gradient.setColorAt( colorPosition.toDouble(),\n\t\t\t\t QColor( colorValue ) );\n }\n }\n gradientPainter.setBrush( gradient );\n gradientPainter.drawRect( 0, 0, 256, 3 );\t\n\n for ( int j = 0; j < 16; ++j ) {\n \n int shadeIndex = 120 + j;\n\n for ( int i = 0; i < 256; ++i ) {\n\n QRgb shadeColor = gradientImage.pixel( i, 1 );\n QLinearGradient shadeGradient( 0, 0, 256, 0 );\n shadeGradient.setColorAt(0.15, QColor(Qt::white));\n shadeGradient.setColorAt(0.496, shadeColor);\n shadeGradient.setColorAt(0.504, shadeColor);\n shadeGradient.setColorAt(0.75, QColor(Qt::black));\n shadingPainter.setBrush( shadeGradient );\n shadingPainter.drawRect( 0, 0, 256, 3 ); \n QRgb paletteColor = shadingImage.pixel( shadeIndex, 1 );\n\n \/\/ populate texturepalette[][]\n texturepalette[j][offset + i] = (uint)paletteColor;\n }\n }\n offset += 256;\n }\n shadingPainter.end(); \/\/ Need to explicitely tell painter lifetime to avoid crash\n gradientPainter.end(); \/\/ on some systems. \n\n m_seafile = seafile;\n m_landfile = landfile;\n}\n<commit_msg>Fix Krazy Error: spelling<commit_after>\/\/\n\/\/ This file is part of the Marble Desktop Globe.\n\/\/\n\/\/ This program is free software licensed under the GNU LGPL. You can\n\/\/ find a copy of this license in LICENSE.txt in the top directory of\n\/\/ the source code.\n\/\/\n\/\/ Copyright 2006-2007 Torsten Rahn <tackat@kde.org>\"\n\/\/ Copyright 2007 Inge Wallin <ingwa@kde.org>\"\n\/\/ Copyright 2008 Carlos Licea <carlos.licea@kdemail.net>\n\/\/\n\n#include \"TextureColorizer.h\"\n\n#include <cmath>\n\n#include <QtCore\/QDebug>\n#include <QtCore\/QFile>\n#include <QtCore\/QString>\n#include <QtGui\/QColor>\n#include <QtGui\/QImage>\n#include <QtGui\/QPainter>\n\n#include \"global.h\"\n#include \"GeoSceneDocument.h\"\n#include \"GeoSceneSettings.h\"\n#include \"ViewParams.h\"\n#include \"ViewportParams.h\"\n#include \"AbstractProjection.h\"\n#include \"MathHelper.h\"\n\nusing namespace Marble;\n\nuint TextureColorizer::texturepalette[16][512];\n\nTextureColorizer::TextureColorizer( const QString& seafile, \n const QString& landfile )\n{\n generatePalette(seafile, landfile);\n}\n\nQString TextureColorizer::seafile() const\n{\n return m_seafile;\n}\n\nQString TextureColorizer::landfile() const\n{\n return m_landfile;\n}\n\n\/\/ This function takes two images, both in viewParams:\n\/\/ - The coast image, which has a number of colors where each color\n\/\/ represents a sort of terrain (ex: land\/sea)\n\/\/ - The canvas image, which has a gray scale image, often\n\/\/ representing a height field.\n\/\/\n\/\/ It then uses the values of the pixels in the coast image to select\n\/\/ a color map. The value of the pixel in the canvas image is used as\n\/\/ an index into the selected color map and the resulting color is\n\/\/ written back to the canvas image. This way we can have different\n\/\/ color schemes for land and water.\n\/\/\n\/\/ In addition to this, a simple form of bump mapping is performed to\n\/\/ increase the illusion of height differences (see the variable\n\/\/ showRelief).\n\/\/ \n\nvoid TextureColorizer::colorize(ViewParams *viewParams)\n{\n QImage *origimg = viewParams->canvasImage();\n const QImage *coastimg = viewParams->coastImage();\n const qint64 radius = viewParams->radius();\n\n const int imgheight = origimg->height();\n const int imgwidth = origimg->width();\n const int imgrx = imgwidth \/ 2;\n const int imgry = imgheight \/ 2;\n \/\/ This variable is not used anywhere..\n const int imgradius = imgrx * imgrx + imgry * imgry;\n\n const uint landoffscreen = qRgb(255,0,0);\n \/\/ const uint seaoffscreen = qRgb(0,0,0);\n const uint lakeoffscreen = qRgb(0,0,0);\n \/\/ const uint glaciercolor = qRgb(200,200,200);\n\n int bump = 8;\n GpFifo emboss;\n emboss.buffer = 0;\n\n bool showRelief;\n viewParams->mapTheme()->settings()->propertyValue( \"relief\", showRelief );\n\n if ( radius * radius > imgradius\n || viewParams->projection() == Equirectangular\n || viewParams->projection() == Mercator )\n {\n int yTop = 0;\n int yBottom = imgheight;\n\n if( viewParams->projection() == Equirectangular\n || viewParams->projection() == Mercator )\n {\n \/\/ Calculate translation of center point\n double centerLon;\n double centerLat;\n viewParams->centerCoordinates( centerLon, centerLat );\n\n const float rad2Pixel = (double)( 2 * radius ) \/ M_PI;\n if ( viewParams->projection() == Equirectangular ) {\n int yCenterOffset = (int)( centerLat * rad2Pixel );\n yTop = ( imgry - radius + yCenterOffset < 0)? 0 : imgry - radius + yCenterOffset;\n yBottom = ( imgry + yCenterOffset + radius > imgheight )? imgheight : imgry + yCenterOffset + radius;\n }\n else if ( viewParams->projection() == Mercator ) {\n int yCenterOffset = (int)( asinh( tan( centerLat ) ) * rad2Pixel );\n yTop = ( imgry - 2 * radius + yCenterOffset < 0 ) ? 0 : imgry - 2 * radius + yCenterOffset;\n yBottom = ( imgry + 2 * radius + yCenterOffset > imgheight )? imgheight : imgry + 2 * radius + yCenterOffset;\n }\n }\n\n for (int y = yTop; y < yBottom; ++y) {\n\n QRgb *writeData = (QRgb*)( origimg->scanLine( y ) );\n const QRgb *coastData = (QRgb*)( coastimg->scanLine( y ) );\n\n uchar *readDataStart = origimg->scanLine( y );\n const uchar *readDataEnd = readDataStart + imgwidth*4;\n\n emboss.buffer = 0;\n\t\t\n for ( uchar* readData = readDataStart; \n\t\t readData < readDataEnd; \n\t\t readData += 4, ++writeData, ++coastData )\n\t {\n\n \/\/ Cheap Emboss \/ Bumpmapping\n const uchar& grey = *readData; \/\/ qBlue(*data);\n\n if ( showRelief ) {\n emboss.gpuint.x4 = grey;\n emboss.buffer = emboss.buffer >> 8;\n bump = ( emboss.gpuint.x1 + 8 - grey );\n if ( bump < 0 ) bump = 0;\n if ( bump > 15 ) bump = 15;\n }\n\n int alpha = qRed( *coastData );\n if ( alpha == 255 || alpha == 0 ) {\n if ( *coastData == landoffscreen )\n *writeData = texturepalette[bump][grey + 0x100]; \n else {\n if (*coastData == lakeoffscreen)\n *writeData = texturepalette[bump][0x055];\n else {\n *writeData = texturepalette[bump][grey];\n }\n }\n }\n else {\n double c = 1.0 \/ 255.0;\n\n if ( qRed( *coastData ) != 0 && qGreen( *coastData ) == 0) {\n\n QRgb landcolor = (QRgb)(texturepalette[bump][grey + 0x100]);\n QRgb watercolor = (QRgb)(texturepalette[bump][grey]);\n\n *writeData = qRgb( \n (int) ( c * ( alpha * qRed( landcolor )\n + ( 255 - alpha ) * qRed( watercolor ) ) ),\n (int) ( c * ( alpha * qGreen( landcolor )\n + ( 255 - alpha ) * qGreen( watercolor ) ) ),\n (int) ( c * ( alpha * qBlue( landcolor )\n + ( 255 - alpha ) * qBlue( watercolor ) ) )\n );\n }\n else {\n\n if ( qGreen( *coastData ) != 0 ) {\n\n QRgb landcolor = (QRgb)(texturepalette[bump][grey + 0x100]);\n QRgb glaciercolor = (QRgb)(texturepalette[bump][grey]);\n \n *writeData = qRgb( \n (int) ( c * ( alpha * qRed( glaciercolor )\n + ( 255 - alpha ) * qRed( landcolor ) ) ),\n (int) ( c * ( alpha * qGreen( glaciercolor )\n + ( 255 - alpha ) * qGreen( landcolor ) ) ),\n (int) ( c * ( alpha * qBlue( glaciercolor )\n + ( 255 - alpha ) * qBlue( landcolor ) ) )\n ); \n }\n }\n }\n }\n }\n }\n else {\n int yTop = ( imgry-radius < 0 ) ? 0 : imgry-radius;\n const int yBottom = ( yTop == 0 ) ? imgheight : imgry + radius;\n\n for ( int y = yTop; y < yBottom; ++y ) {\n const int dy = imgry - y;\n int rx = (int)sqrt( (double)( radius * radius - dy * dy ) );\n int xLeft = 0; \n int xRight = imgwidth;\n\n if ( imgrx-rx > 0 ) {\n xLeft = imgrx - rx; \n xRight = imgrx + rx;\n }\n\n QRgb *writeData = (QRgb*)( origimg->scanLine( y ) ) + xLeft;\n const QRgb *coastData = (QRgb*)( coastimg->scanLine( y ) ) + xLeft;\n\n uchar *readDataStart = origimg->scanLine( y ) + xLeft * 4;\n const uchar *readDataEnd = origimg->scanLine( y ) + xRight * 4;\n\n \n for ( uchar* readData = readDataStart;\n\t\t readData < readDataEnd;\n\t\t readData += 4, ++writeData, ++coastData )\n\t {\n \/\/ Cheap Embosss \/ Bumpmapping\n\n const uchar& grey = *readData; \/\/ qBlue(*data);\n\n if ( showRelief == true ) {\n emboss.buffer = emboss.buffer >> 8;\n emboss.gpuint.x4 = grey; \n bump = ( emboss.gpuint.x1 + 16 - grey ) >> 1;\n\n if ( bump > 15 ) bump = 15;\n if ( bump < 0 ) bump = 0;\n }\n\n int alpha = qRed( *coastData );\n if ( alpha == 255 || alpha == 0 ) {\n if ( *coastData == landoffscreen )\n *writeData = texturepalette[bump][grey + 0x100]; \n else {\n if (*coastData == lakeoffscreen)\n *writeData = texturepalette[bump][0x055];\n else {\n *writeData = texturepalette[bump][grey];\n }\n }\n }\n else {\n double c = 1.0 \/ 255.0;\n\n if ( qRed( *coastData ) != 0 && qGreen( *coastData ) == 0) {\n\n QRgb landcolor = (QRgb)(texturepalette[bump][grey + 0x100]);\n QRgb watercolor = (QRgb)(texturepalette[bump][grey]);\n\n *writeData = qRgb( \n (int) ( c * ( alpha * qRed( landcolor )\n + ( 255 - alpha ) * qRed( watercolor ) ) ),\n (int) ( c * ( alpha * qGreen( landcolor )\n + ( 255 - alpha ) * qGreen( watercolor ) ) ),\n (int) ( c * ( alpha * qBlue( landcolor )\n + ( 255 - alpha ) * qBlue( watercolor ) ) )\n );\n }\n else {\n\n if ( qGreen( *coastData ) != 0 ) {\n\n QRgb landcolor = (QRgb)(texturepalette[bump][grey + 0x100]);\n QRgb glaciercolor = (QRgb)(texturepalette[bump][grey]);\n \n *writeData = qRgb( \n (int) ( c * ( alpha * qRed( glaciercolor )\n + ( 255 - alpha ) * qRed( landcolor ) ) ),\n (int) ( c * ( alpha * qGreen( glaciercolor )\n + ( 255 - alpha ) * qGreen( landcolor ) ) ),\n (int) ( c * ( alpha * qBlue( glaciercolor )\n + ( 255 - alpha ) * qBlue( landcolor ) ) )\n ); \n }\n }\n }\n }\n }\n }\n}\n\nvoid TextureColorizer::generatePalette(const QString& seafile,\n\t\t\t\t const QString& landfile)\n{\n for(int i = 0; i < 16; i++) {\n for(int j = 0; j < 512; j++) {\n texturepalette[i][j] = 0;\n }\n }\n QImage gradientImage ( 256, 10, QImage::Format_RGB32 );\n QPainter gradientPainter;\n gradientPainter.begin( &gradientImage );\n gradientPainter.setPen( Qt::NoPen );\n\n QImage shadingImage ( 256, 10, QImage::Format_RGB32 );\n QPainter shadingPainter;\n shadingPainter.begin( &shadingImage );\n shadingPainter.setPen( Qt::NoPen );\n\n int offset = 0;\n\n QStringList filelist;\n filelist << seafile << landfile;\n\n foreach ( const QString &filename, filelist ) {\n\n QLinearGradient gradient( 0, 0, 256, 0 );\n\n QFile file( filename );\n file.open( QIODevice::ReadOnly );\n QTextStream stream( &file ); \/\/ read the data from the file\n QString evalstrg;\n\n while ( !stream.atEnd() ) {\n stream >> evalstrg;\n if ( !evalstrg.isEmpty() && evalstrg.contains( \"=\" ) ) {\n QString colorValue = evalstrg.section( \"=\", 0, 0 );\n QString colorPosition = evalstrg.section( \"=\", 1, 1 );\n gradient.setColorAt( colorPosition.toDouble(),\n\t\t\t\t QColor( colorValue ) );\n }\n }\n gradientPainter.setBrush( gradient );\n gradientPainter.drawRect( 0, 0, 256, 3 );\t\n\n for ( int j = 0; j < 16; ++j ) {\n \n int shadeIndex = 120 + j;\n\n for ( int i = 0; i < 256; ++i ) {\n\n QRgb shadeColor = gradientImage.pixel( i, 1 );\n QLinearGradient shadeGradient( 0, 0, 256, 0 );\n shadeGradient.setColorAt(0.15, QColor(Qt::white));\n shadeGradient.setColorAt(0.496, shadeColor);\n shadeGradient.setColorAt(0.504, shadeColor);\n shadeGradient.setColorAt(0.75, QColor(Qt::black));\n shadingPainter.setBrush( shadeGradient );\n shadingPainter.drawRect( 0, 0, 256, 3 ); \n QRgb paletteColor = shadingImage.pixel( shadeIndex, 1 );\n\n \/\/ populate texturepalette[][]\n texturepalette[j][offset + i] = (uint)paletteColor;\n }\n }\n offset += 256;\n }\n shadingPainter.end(); \/\/ Need to explicitly tell painter lifetime to avoid crash\n gradientPainter.end(); \/\/ on some systems. \n\n m_seafile = seafile;\n m_landfile = landfile;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*=========================================================================\n\n Program: Insight Segmentation & Registration Toolkit\n Module: itkCenteredEuler3DTransformTest.cxx\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n Copyright (c) Insight Software Consortium. All rights reserved.\n See ITKCopyright.txt or http:\/\/www.itk.org\/HTML\/Copyright.htm for details.\n\n This software is distributed WITHOUT ANY WARRANTY; without even \n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR \n PURPOSE. See the above copyright notices for more information.\n\n=========================================================================*\/\n#if defined(_MSC_VER)\n#pragma warning ( disable : 4786 )\n#endif\n\n#include <iostream>\n\n#include \"itkCenteredEuler3DTransform.h\"\n#include \"vnl\/vnl_vector_fixed.h\"\n#include \"itkVector.h\"\n\n\nint itkCenteredEuler3DTransformTest(int,char *[] )\n{\n\n std::cout << \"==================================\" << std::endl;\n std::cout << \"Testing Centered Euler Angles 3D Transform\" << std::endl << std::endl;\n\n const double epsilon = 1e-10;\n const unsigned int N = 3;\n bool Ok = true;\n\n typedef itk::CenteredEuler3DTransform<double> EulerTransformType;\n EulerTransformType::Pointer eulerTransform = EulerTransformType::New();\n \n\n \/\/ Testing Identity\n std::cout << \"Testing identity transform: \";\n eulerTransform->SetIdentity();\n\n EulerTransformType::OffsetType offset = eulerTransform->GetOffset();\n if( offset[0] != 0.0 \n || offset[1] != 0.0 \n || offset[2] != 0.0 \n )\n {\n std::cout << \"[ FAILED ]\" << std::endl;\n return EXIT_FAILURE;\n }\n\n std::cout << \"[ PASSED ]\" << std::endl;\n\n\n \/\/ 15 degrees in radians\n const double angleX = 15.0 * atan( 1.0f ) \/ 45.0; \n const double cx = cos(angleX);\n const double sx = sin(angleX);\n \n \/\/ 10 degrees in radians\n const double angleY = 10.0 * atan( 1.0f ) \/ 45.0; \n const double cy = cos(angleY);\n const double sy = sin(angleY);\n\n \/\/ 5 degrees in radians\n const double angleZ = 5.0 * atan( 1.0f ) \/ 45.0; \n const double cz = cos(angleZ);\n const double sz = sin(angleZ);\n\n std::cout << \"Testing Rotation:\";\n eulerTransform->SetRotation(angleX,angleY,angleZ);\n\n \/\/ Rotate an itk::Point\n EulerTransformType::InputPointType::ValueType pInit[3] = {10,-5,3};\n EulerTransformType::InputPointType p = pInit;\n EulerTransformType::InputPointType q;\n\n itk::Matrix<double,3,3> RotationX;\n RotationX[0][0]=1;RotationX[0][1]=0;RotationX[0][2]=0;\n RotationX[1][0]=0;RotationX[1][1]=cx;RotationX[1][2]=-sx;\n RotationX[2][0]=0;RotationX[2][1]=sx;RotationX[2][2]=cx;\n\n\n itk::Matrix<double,3,3> RotationY;\n RotationY[0][0]=cy;RotationY[0][1]=0;RotationY[0][2]=sy;\n RotationY[1][0]=0;RotationY[1][1]=1;RotationY[1][2]=0;\n RotationY[2][0]=-sy;RotationY[2][1]=0;RotationY[2][2]=cy;\n\n \n itk::Matrix<double,3,3> RotationZ;\n RotationZ[0][0]=cz;RotationZ[0][1]=-sz;RotationZ[0][2]=0;\n RotationZ[1][0]=sz;RotationZ[1][1]=cz;RotationZ[1][2]=0;\n RotationZ[2][0]=0;RotationZ[2][1]=0;RotationZ[2][2]=1;\n\n\n q = RotationZ*RotationX*RotationY*p; \/\/ standard transformation\n \n \n EulerTransformType::OutputPointType r;\n r = eulerTransform->TransformPoint( p );\n for(unsigned int i=0; i<N; i++)\n {\n if( fabs( q[i]- r[i] ) > epsilon )\n {\n Ok = false;\n break; \n }\n }\n if( !Ok )\n { \n std::cerr << \"Error rotating point : \" << p << std::endl;\n std::cerr << \"Result should be : \" << q << std::endl;\n std::cerr << \"Reported Result is : \" << r << std::endl;\n return EXIT_FAILURE;\n }\n else\n {\n std::cout << \" [ PASSED ] \" << std::endl;\n }\n\n \n std::cout << \"Testing Translation:\";\n\n eulerTransform->SetRotation(0,0,0);\n \n EulerTransformType::OffsetType::ValueType ioffsetInit[3] = {1,-4,8};\n EulerTransformType::OffsetType ioffset = ioffsetInit;\n\n eulerTransform->SetOffset( ioffset );\n std::cout << \"eulerTransform: \" << eulerTransform;\n \n q = p + ioffset;\n \n r = eulerTransform->TransformPoint( p );\n for(unsigned int i=0; i<N; i++)\n {\n if( fabs( q[i]- r[i] ) > epsilon )\n {\n Ok = false;\n break; \n }\n }\n if( !Ok )\n { \n std::cerr << \"Error translating point: \" << p << std::endl;\n std::cerr << \"Result should be : \" << q << std::endl;\n std::cerr << \"Reported Result is : \" << r << std::endl;\n return EXIT_FAILURE;\n }\n else\n {\n std::cout << \" [ PASSED ] \" << std::endl;\n }\n\n\n \/\/ Testing Parameters\n std::cout << \"Testing Set\/Get Parameters: \" ;\n EulerTransformType::ParametersType parameters(6);\n for(unsigned int i=0;i<6;i++)\n {\n parameters[i]=i;\n }\n \n eulerTransform->SetParameters(parameters);\n EulerTransformType::ParametersType parameters_result = eulerTransform->GetParameters();\n \n if( parameters_result[0] != 0.0\n || parameters_result[1] != 1.0\n || parameters_result[2] != 2.0\n || parameters_result[3] != 3.0\n || parameters_result[4] != 4.0\n || parameters_result[5] != 5.0\n )\n {\n std::cout << \" [ FAILED ] \" << std::endl;\n return EXIT_FAILURE; \n }\n std::cout << \" [ PASSED ] \" << std::endl;\n\n\n \/\/ Testing Jacobian\n std::cout << \"Testing Jacobian: \";\n for(unsigned int i=0;i<3;i++)\n {\n pInit[i]=0;\n }\n\n EulerTransformType::JacobianType jacobian = eulerTransform->GetJacobian(pInit);\n \n if( jacobian[0][0] != 0.0 || jacobian[0][1] != 0.0 \n || jacobian[0][2] != 0.0 ||jacobian[0][3] != 1.0\n || jacobian[0][4] != 0.0 ||jacobian[0][5] != 0.0\n || jacobian[1][0] != 0.0 || jacobian[1][1] != 0.0 \n || jacobian[1][2] != 0.0 ||jacobian[1][3] != 0.0\n || jacobian[1][4] != 1.0 ||jacobian[1][5] != 0.0\n || jacobian[2][0] != 0.0 || jacobian[2][1] != 0.0 \n || jacobian[2][2] != 0.0 ||jacobian[2][3] != 0.0\n || jacobian[2][4] != 0.0 ||jacobian[2][5] != 1.0\n )\n {\n std::cout << \" [ FAILED ] \" << std::endl;\n return EXIT_FAILURE; \n }\n std::cout << \" [ PASSED ] \" << std::endl;\n\n \/\/ Really test the Jacobian\n for( unsigned int p = 0; p < 2; p++ )\n {\n std::cout << \"Testing Jacobian when ComputeZYX is \";\n if ( p == 0 )\n {\n std::cout << \"true\" << std::endl;\n eulerTransform->SetComputeZYX( true );\n }\n else\n {\n std::cout << \"false\" << std::endl;\n eulerTransform->SetComputeZYX( false );\n }\n\n parameters.Fill( 0.0 );\n parameters[0] = 0.2 \/ 180.0 * vnl_math::pi;\n parameters[1] = -1.0 \/ 180.0 * vnl_math::pi;\n parameters[2] = 2.4 \/ 180.0 * vnl_math::pi;\n parameters[3] = 5.0;\n parameters[4] = 6.0;\n parameters[5] = 8.0;\n\n eulerTransform->SetParameters( parameters );\n \n pInit[0] = 1.0;\n pInit[1] = 1.5;\n pInit[2] = 2.6;\n\n jacobian = eulerTransform->GetJacobian( pInit );\n std::cout << jacobian << std::endl;\n\n EulerTransformType::JacobianType approxJacobian = jacobian;\n\n for( unsigned int k = 0; k < eulerTransform->GetNumberOfParameters(); k++ )\n {\n const double delta = 0.001;\n EulerTransformType::ParametersType plusParameters;\n EulerTransformType::ParametersType minusParameters;\n\n plusParameters = parameters;\n minusParameters = parameters;\n plusParameters[k] += delta;\n minusParameters[k] -= delta;\n\n EulerTransformType::OutputPointType plusPoint;\n EulerTransformType::OutputPointType minusPoint;\n\n eulerTransform->SetParameters( plusParameters );\n plusPoint = eulerTransform->TransformPoint( pInit );\n eulerTransform->SetParameters( minusParameters );\n minusPoint = eulerTransform->TransformPoint( pInit );\n\n for( unsigned int j = 0; j < 3; j++ )\n {\n double approxDerivative = ( plusPoint[j] - minusPoint[j] ) \/ ( 2.0 * delta );\n double computedDerivative = jacobian[j][k];\n approxJacobian[j][k] = approxDerivative;\n if ( vnl_math_abs( approxDerivative - computedDerivative ) > 1e-5 )\n {\n std::cerr << \"Error computing Jacobian [\" << j << \"][\" << k << \"]\" << std::endl;\n std::cerr << \"Result should be: \" << approxDerivative << std::endl;\n std::cerr << \"Reported result is: \" << computedDerivative << std::endl;\n std::cerr << \" [ FAILED ] \" << std::endl;\n return EXIT_FAILURE;\n }\n }\n }\n\n std::cout << approxJacobian << std::endl;\n std::cout << \" [ PASSED ] \" << std::endl;\n\n }\n\n \n std::cout << \"Testing Angle from matrix : \";\n eulerTransform->SetIdentity();\n\n eulerTransform->SetRotation(0.2,0.1,0.3);\n \n EulerTransformType::Pointer t2 = EulerTransformType::New();\n t2->SetIdentity();\n t2->Compose(eulerTransform);\n if( (fabs(t2->GetParameters()[0]-0.2)>0.0001)\n || (fabs(t2->GetParameters()[1]-0.1)>0.0001)\n || (fabs(t2->GetParameters()[2]-0.3)>0.0001) \n )\n {\n std::cout << \" [ FAILED ] \" << std::endl;\n return EXIT_FAILURE; \n }\n std::cout << \" [ PASSED ] \" << std::endl;\n\n std::cout << \"Testing Angle from matrix (ZYX) : \";\n eulerTransform->SetIdentity();\n eulerTransform->SetComputeZYX(true);\n eulerTransform->SetRotation(0.2,0.1,0.3);\n \n t2->SetIdentity();\n t2->SetComputeZYX(true);\n t2->Compose(eulerTransform);\n \n if( (fabs(t2->GetParameters()[0]-0.2)>0.0001)\n || (fabs(t2->GetParameters()[1]-0.1)>0.0001)\n || (fabs(t2->GetParameters()[2]-0.3)>0.0001) \n )\n {\n std::cout << \" [ FAILED ] \" << std::endl;\n return EXIT_FAILURE; \n }\n std::cout << \" [ PASSED ] \" << std::endl;\n\n EulerTransformType::Pointer t3 = EulerTransformType::New();\n\n t2->GetInverse( t3 );\n\n return EXIT_SUCCESS;\n\n}\n<commit_msg>STYLE: added a non-zero center to verify the correct computation of the Jacobian. (BUG #1257).<commit_after>\/*=========================================================================\n\n Program: Insight Segmentation & Registration Toolkit\n Module: itkCenteredEuler3DTransformTest.cxx\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n Copyright (c) Insight Software Consortium. All rights reserved.\n See ITKCopyright.txt or http:\/\/www.itk.org\/HTML\/Copyright.htm for details.\n\n This software is distributed WITHOUT ANY WARRANTY; without even \n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR \n PURPOSE. See the above copyright notices for more information.\n\n=========================================================================*\/\n#if defined(_MSC_VER)\n#pragma warning ( disable : 4786 )\n#endif\n\n#include <iostream>\n\n#include \"itkCenteredEuler3DTransform.h\"\n#include \"vnl\/vnl_vector_fixed.h\"\n#include \"itkVector.h\"\n\n\nint itkCenteredEuler3DTransformTest(int,char *[] )\n{\n\n std::cout << \"==================================\" << std::endl;\n std::cout << \"Testing Centered Euler Angles 3D Transform\" << std::endl << std::endl;\n\n const double epsilon = 1e-10;\n const unsigned int N = 3;\n bool Ok = true;\n\n typedef itk::CenteredEuler3DTransform<double> EulerTransformType;\n EulerTransformType::Pointer eulerTransform = EulerTransformType::New();\n \n\n \/\/ Testing Identity\n std::cout << \"Testing identity transform: \";\n eulerTransform->SetIdentity();\n\n EulerTransformType::OffsetType offset = eulerTransform->GetOffset();\n if( offset[0] != 0.0 \n || offset[1] != 0.0 \n || offset[2] != 0.0 \n )\n {\n std::cout << \"[ FAILED ]\" << std::endl;\n return EXIT_FAILURE;\n }\n\n std::cout << \"[ PASSED ]\" << std::endl;\n\n\n \/\/ 15 degrees in radians\n const double angleX = 15.0 * atan( 1.0f ) \/ 45.0; \n const double cx = cos(angleX);\n const double sx = sin(angleX);\n \n \/\/ 10 degrees in radians\n const double angleY = 10.0 * atan( 1.0f ) \/ 45.0; \n const double cy = cos(angleY);\n const double sy = sin(angleY);\n\n \/\/ 5 degrees in radians\n const double angleZ = 5.0 * atan( 1.0f ) \/ 45.0; \n const double cz = cos(angleZ);\n const double sz = sin(angleZ);\n\n std::cout << \"Testing Rotation:\";\n eulerTransform->SetRotation(angleX,angleY,angleZ);\n\n \/\/ Rotate an itk::Point\n EulerTransformType::InputPointType::ValueType pInit[3] = {10,-5,3};\n EulerTransformType::InputPointType p = pInit;\n EulerTransformType::InputPointType q;\n\n itk::Matrix<double,3,3> RotationX;\n RotationX[0][0]=1;RotationX[0][1]=0;RotationX[0][2]=0;\n RotationX[1][0]=0;RotationX[1][1]=cx;RotationX[1][2]=-sx;\n RotationX[2][0]=0;RotationX[2][1]=sx;RotationX[2][2]=cx;\n\n\n itk::Matrix<double,3,3> RotationY;\n RotationY[0][0]=cy;RotationY[0][1]=0;RotationY[0][2]=sy;\n RotationY[1][0]=0;RotationY[1][1]=1;RotationY[1][2]=0;\n RotationY[2][0]=-sy;RotationY[2][1]=0;RotationY[2][2]=cy;\n\n \n itk::Matrix<double,3,3> RotationZ;\n RotationZ[0][0]=cz;RotationZ[0][1]=-sz;RotationZ[0][2]=0;\n RotationZ[1][0]=sz;RotationZ[1][1]=cz;RotationZ[1][2]=0;\n RotationZ[2][0]=0;RotationZ[2][1]=0;RotationZ[2][2]=1;\n\n\n q = RotationZ*RotationX*RotationY*p; \/\/ standard transformation\n \n \n EulerTransformType::OutputPointType r;\n r = eulerTransform->TransformPoint( p );\n for(unsigned int i=0; i<N; i++)\n {\n if( fabs( q[i]- r[i] ) > epsilon )\n {\n Ok = false;\n break; \n }\n }\n if( !Ok )\n { \n std::cerr << \"Error rotating point : \" << p << std::endl;\n std::cerr << \"Result should be : \" << q << std::endl;\n std::cerr << \"Reported Result is : \" << r << std::endl;\n return EXIT_FAILURE;\n }\n else\n {\n std::cout << \" [ PASSED ] \" << std::endl;\n }\n\n \n std::cout << \"Testing Translation:\";\n\n eulerTransform->SetRotation(0,0,0);\n \n EulerTransformType::OffsetType::ValueType ioffsetInit[3] = {1,-4,8};\n EulerTransformType::OffsetType ioffset = ioffsetInit;\n\n eulerTransform->SetOffset( ioffset );\n std::cout << \"eulerTransform: \" << eulerTransform;\n \n q = p + ioffset;\n \n r = eulerTransform->TransformPoint( p );\n for(unsigned int i=0; i<N; i++)\n {\n if( fabs( q[i]- r[i] ) > epsilon )\n {\n Ok = false;\n break; \n }\n }\n if( !Ok )\n { \n std::cerr << \"Error translating point: \" << p << std::endl;\n std::cerr << \"Result should be : \" << q << std::endl;\n std::cerr << \"Reported Result is : \" << r << std::endl;\n return EXIT_FAILURE;\n }\n else\n {\n std::cout << \" [ PASSED ] \" << std::endl;\n }\n\n\n \/\/ Testing Parameters\n std::cout << \"Testing Set\/Get Parameters: \" ;\n EulerTransformType::ParametersType parameters(6);\n for(unsigned int i=0;i<6;i++)\n {\n parameters[i]=i;\n }\n \n eulerTransform->SetParameters(parameters);\n EulerTransformType::ParametersType parameters_result = eulerTransform->GetParameters();\n \n if( parameters_result[0] != 0.0\n || parameters_result[1] != 1.0\n || parameters_result[2] != 2.0\n || parameters_result[3] != 3.0\n || parameters_result[4] != 4.0\n || parameters_result[5] != 5.0\n )\n {\n std::cout << \" [ FAILED ] \" << std::endl;\n return EXIT_FAILURE; \n }\n std::cout << \" [ PASSED ] \" << std::endl;\n\n\n \/\/ Testing Jacobian\n std::cout << \"Testing Jacobian: \";\n for(unsigned int i=0;i<3;i++)\n {\n pInit[i]=0;\n }\n\n EulerTransformType::JacobianType jacobian = eulerTransform->GetJacobian(pInit);\n \n if( jacobian[0][0] != 0.0 || jacobian[0][1] != 0.0 \n || jacobian[0][2] != 0.0 ||jacobian[0][3] != 1.0\n || jacobian[0][4] != 0.0 ||jacobian[0][5] != 0.0\n || jacobian[1][0] != 0.0 || jacobian[1][1] != 0.0 \n || jacobian[1][2] != 0.0 ||jacobian[1][3] != 0.0\n || jacobian[1][4] != 1.0 ||jacobian[1][5] != 0.0\n || jacobian[2][0] != 0.0 || jacobian[2][1] != 0.0 \n || jacobian[2][2] != 0.0 ||jacobian[2][3] != 0.0\n || jacobian[2][4] != 0.0 ||jacobian[2][5] != 1.0\n )\n {\n std::cout << \" [ FAILED ] \" << std::endl;\n return EXIT_FAILURE; \n }\n std::cout << \" [ PASSED ] \" << std::endl;\n\n \/\/ Really test the Jacobian\n EulerTransformType::InputPointType center;\n center[0] = 0.2;\n center[1] = 7.0;\n center[2] = 4.0;\n eulerTransform->SetCenter( center );\n\n eulerTransform->Print( std::cout );\n\n for( unsigned int p = 0; p < 2; p++ )\n {\n std::cout << \"Testing Jacobian when ComputeZYX is \";\n if ( p == 0 )\n {\n std::cout << \"true\" << std::endl;\n eulerTransform->SetComputeZYX( true );\n }\n else\n {\n std::cout << \"false\" << std::endl;\n eulerTransform->SetComputeZYX( false );\n }\n\n parameters.Fill( 0.0 );\n parameters[0] = 0.2 \/ 180.0 * vnl_math::pi;\n parameters[1] = -1.0 \/ 180.0 * vnl_math::pi;\n parameters[2] = 2.4 \/ 180.0 * vnl_math::pi;\n parameters[3] = 5.0;\n parameters[4] = 6.0;\n parameters[5] = 8.0;\n\n eulerTransform->SetParameters( parameters );\n \n pInit[0] = 1.0;\n pInit[1] = 1.5;\n pInit[2] = 2.6;\n\n jacobian = eulerTransform->GetJacobian( pInit );\n std::cout << jacobian << std::endl;\n\n EulerTransformType::JacobianType approxJacobian = jacobian;\n\n for( unsigned int k = 0; k < eulerTransform->GetNumberOfParameters(); k++ )\n {\n const double delta = 0.001;\n EulerTransformType::ParametersType plusParameters;\n EulerTransformType::ParametersType minusParameters;\n\n plusParameters = parameters;\n minusParameters = parameters;\n plusParameters[k] += delta;\n minusParameters[k] -= delta;\n\n EulerTransformType::OutputPointType plusPoint;\n EulerTransformType::OutputPointType minusPoint;\n\n eulerTransform->SetParameters( plusParameters );\n plusPoint = eulerTransform->TransformPoint( pInit );\n eulerTransform->SetParameters( minusParameters );\n minusPoint = eulerTransform->TransformPoint( pInit );\n\n for( unsigned int j = 0; j < 3; j++ )\n {\n double approxDerivative = ( plusPoint[j] - minusPoint[j] ) \/ ( 2.0 * delta );\n double computedDerivative = jacobian[j][k];\n approxJacobian[j][k] = approxDerivative;\n if ( vnl_math_abs( approxDerivative - computedDerivative ) > 1e-5 )\n {\n std::cerr << \"Error computing Jacobian [\" << j << \"][\" << k << \"]\" << std::endl;\n std::cerr << \"Result should be: \" << approxDerivative << std::endl;\n std::cerr << \"Reported result is: \" << computedDerivative << std::endl;\n std::cerr << \" [ FAILED ] \" << std::endl;\n return EXIT_FAILURE;\n }\n }\n }\n\n std::cout << approxJacobian << std::endl;\n std::cout << \" [ PASSED ] \" << std::endl;\n\n }\n\n \n std::cout << \"Testing Angle from matrix : \";\n eulerTransform->SetIdentity();\n\n eulerTransform->SetRotation(0.2,0.1,0.3);\n \n EulerTransformType::Pointer t2 = EulerTransformType::New();\n t2->SetIdentity();\n t2->Compose(eulerTransform);\n if( (fabs(t2->GetParameters()[0]-0.2)>0.0001)\n || (fabs(t2->GetParameters()[1]-0.1)>0.0001)\n || (fabs(t2->GetParameters()[2]-0.3)>0.0001) \n )\n {\n std::cout << \" [ FAILED ] \" << std::endl;\n return EXIT_FAILURE; \n }\n std::cout << \" [ PASSED ] \" << std::endl;\n\n std::cout << \"Testing Angle from matrix (ZYX) : \";\n eulerTransform->SetIdentity();\n eulerTransform->SetComputeZYX(true);\n eulerTransform->SetRotation(0.2,0.1,0.3);\n \n t2->SetIdentity();\n t2->SetComputeZYX(true);\n t2->Compose(eulerTransform);\n \n if( (fabs(t2->GetParameters()[0]-0.2)>0.0001)\n || (fabs(t2->GetParameters()[1]-0.1)>0.0001)\n || (fabs(t2->GetParameters()[2]-0.3)>0.0001) \n )\n {\n std::cout << \" [ FAILED ] \" << std::endl;\n return EXIT_FAILURE; \n }\n std::cout << \" [ PASSED ] \" << std::endl;\n\n EulerTransformType::Pointer t3 = EulerTransformType::New();\n\n t2->GetInverse( t3 );\n\n return EXIT_SUCCESS;\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/*******************************************************\n * Copyright (c) 2014, ArrayFire\n * All rights reserved.\n *\n * This file is distributed under 3-clause BSD license.\n * The complete license agreement can be obtained at:\n * http:\/\/arrayfire.com\/licenses\/BSD-3-Clause\n ********************************************************\/\n\n#include <blas.hpp>\n#include <cublas_v2.h>\n#include <cuda_runtime.h>\n#include <platform.hpp>\n\n#include <arith.hpp>\n#include <common\/err_common.hpp>\n#include <complex.hpp>\n#include <cublas.hpp>\n#include <err_cuda.hpp>\n#include <math.hpp>\n#include <reduce.hpp>\n#include <cassert>\n#include <stdexcept>\n#include <string>\n\nnamespace cuda {\n\ncublasOperation_t toCblasTranspose(af_mat_prop opt) {\n cublasOperation_t out = CUBLAS_OP_N;\n switch (opt) {\n case AF_MAT_NONE: out = CUBLAS_OP_N; break;\n case AF_MAT_TRANS: out = CUBLAS_OP_T; break;\n case AF_MAT_CTRANS: out = CUBLAS_OP_C; break;\n default: AF_ERROR(\"INVALID af_mat_prop\", AF_ERR_ARG);\n }\n return out;\n}\n\ntemplate<typename T>\nstruct gemm_func_def_t {\n typedef cublasStatus_t (*gemm_func_def)(cublasHandle_t, cublasOperation_t,\n cublasOperation_t, int, int, int,\n const T *, const T *, int,\n const T *, int, const T *, T *,\n int);\n};\n\ntemplate<typename T>\nstruct gemmBatched_func_def_t {\n typedef cublasStatus_t (*gemmBatched_func_def)(\n cublasHandle_t, cublasOperation_t, cublasOperation_t, int, int, int,\n const T *, const T **, int, const T **, int, const T *, T **, int, int);\n};\n\ntemplate<typename T>\nstruct gemv_func_def_t {\n typedef cublasStatus_t (*gemv_func_def)(cublasHandle_t, cublasOperation_t,\n int, int, const T *, const T *, int,\n const T *, int, const T *, T *,\n int);\n};\n\ntemplate<typename T>\nstruct trsm_func_def_t {\n typedef cublasStatus_t (*trsm_func_def)(cublasHandle_t, cublasSideMode_t,\n cublasFillMode_t, cublasOperation_t,\n cublasDiagType_t, int, int,\n const T *, const T *, int, T *,\n int);\n};\n\n#define BLAS_FUNC_DEF(FUNC) \\\n template<typename T> \\\n typename FUNC##_func_def_t<T>::FUNC##_func_def FUNC##_func();\n\n#define BLAS_FUNC(FUNC, TYPE, PREFIX) \\\n template<> \\\n typename FUNC##_func_def_t<TYPE>::FUNC##_func_def FUNC##_func<TYPE>() { \\\n return (FUNC##_func_def_t<TYPE>::FUNC##_func_def) & \\\n cublas##PREFIX##FUNC; \\\n }\n\nBLAS_FUNC_DEF(gemm)\nBLAS_FUNC(gemm, float, S)\nBLAS_FUNC(gemm, cfloat, C)\nBLAS_FUNC(gemm, double, D)\nBLAS_FUNC(gemm, cdouble, Z)\n\nBLAS_FUNC_DEF(gemmBatched)\nBLAS_FUNC(gemmBatched, float, S)\nBLAS_FUNC(gemmBatched, cfloat, C)\nBLAS_FUNC(gemmBatched, double, D)\nBLAS_FUNC(gemmBatched, cdouble, Z)\n\nBLAS_FUNC_DEF(gemv)\nBLAS_FUNC(gemv, float, S)\nBLAS_FUNC(gemv, cfloat, C)\nBLAS_FUNC(gemv, double, D)\nBLAS_FUNC(gemv, cdouble, Z)\n\nBLAS_FUNC_DEF(trsm)\nBLAS_FUNC(trsm, float, S)\nBLAS_FUNC(trsm, cfloat, C)\nBLAS_FUNC(trsm, double, D)\nBLAS_FUNC(trsm, cdouble, Z)\n\n#undef BLAS_FUNC\n#undef BLAS_FUNC_DEF\n\ntemplate<typename T, bool conjugate>\nstruct dot_func_def_t {\n typedef cublasStatus_t (*dot_func_def)(cublasHandle_t, int, const T *, int,\n const T *, int, T *);\n};\n\n#define BLAS_FUNC_DEF(FUNC) \\\n template<typename T, bool conjugate> \\\n typename FUNC##_func_def_t<T, conjugate>::FUNC##_func_def FUNC##_func();\n\n#define BLAS_FUNC(FUNC, TYPE, CONJUGATE, PREFIX) \\\n template<> \\\n typename FUNC##_func_def_t<TYPE, CONJUGATE>::FUNC##_func_def \\\n FUNC##_func<TYPE, CONJUGATE>() { \\\n return (FUNC##_func_def_t<TYPE, CONJUGATE>::FUNC##_func_def) & \\\n cublas##PREFIX##FUNC; \\\n }\n\nBLAS_FUNC_DEF(dot)\nBLAS_FUNC(dot, float, true, S)\nBLAS_FUNC(dot, double, true, D)\nBLAS_FUNC(dot, float, false, S)\nBLAS_FUNC(dot, double, false, D)\n\n#undef BLAS_FUNC\n\n#define BLAS_FUNC(FUNC, TYPE, CONJUGATE, PREFIX, SUFFIX) \\\n template<> \\\n typename FUNC##_func_def_t<TYPE, CONJUGATE>::FUNC##_func_def \\\n FUNC##_func<TYPE, CONJUGATE>() { \\\n return (FUNC##_func_def_t<TYPE, CONJUGATE>::FUNC##_func_def) & \\\n cublas##PREFIX##FUNC##SUFFIX; \\\n }\n\nBLAS_FUNC_DEF(dot)\nBLAS_FUNC(dot, cfloat, true, C, c)\nBLAS_FUNC(dot, cdouble, true, Z, c)\nBLAS_FUNC(dot, cfloat, false, C, u)\nBLAS_FUNC(dot, cdouble, false, Z, u)\n\n#undef BLAS_FUNC\n#undef BLAS_FUNC_DEF\n\nusing namespace std;\n\ntemplate<typename T>\nArray<T> matmul(const Array<T> &lhs, const Array<T> &rhs, af_mat_prop optLhs,\n af_mat_prop optRhs) {\n cublasOperation_t lOpts = toCblasTranspose(optLhs);\n cublasOperation_t rOpts = toCblasTranspose(optRhs);\n\n int aRowDim = (lOpts == CUBLAS_OP_N) ? 0 : 1;\n int aColDim = (lOpts == CUBLAS_OP_N) ? 1 : 0;\n int bColDim = (rOpts == CUBLAS_OP_N) ? 1 : 0;\n\n dim4 lDims = lhs.dims();\n dim4 rDims = rhs.dims();\n int M = lDims[aRowDim];\n int N = rDims[bColDim];\n int K = lDims[aColDim];\n\n dim_t d2 = std::max(lDims[2], rDims[2]);\n dim_t d3 = std::max(lDims[3], rDims[3]);\n dim4 oDims = dim4(M, N, d2, d3);\n Array<T> out = createEmptyArray<T>(oDims);\n\n T alpha = scalar<T>(1);\n T beta = scalar<T>(0);\n\n dim4 lStrides = lhs.strides();\n dim4 rStrides = rhs.strides();\n dim4 oStrides = out.strides();\n\n if (oDims.ndims() <= 2) {\n if (rDims[bColDim] == 1) {\n dim_t incr = (optRhs == AF_MAT_NONE) ? rStrides[0] : rStrides[1];\n N = lDims[aColDim];\n CUBLAS_CHECK(gemv_func<T>()(blasHandle(), lOpts, lDims[0], lDims[1],\n &alpha, lhs.get(), lStrides[1],\n rhs.get(), incr, &beta, out.get(), 1));\n } else {\n CUBLAS_CHECK(gemm_func<T>()(blasHandle(), lOpts, rOpts, M, N, K,\n &alpha, lhs.get(), lStrides[1],\n rhs.get(), rStrides[1], &beta,\n out.get(), oDims[0]));\n }\n } else {\n int batchSize = oDims[2] * oDims[3];\n std::vector<const T *> lptrs(batchSize);\n std::vector<const T *> rptrs(batchSize);\n std::vector<T *> optrs(batchSize);\n\n bool is_l_d2_batched = oDims[2] == lDims[2];\n bool is_l_d3_batched = oDims[3] == lDims[3];\n\n bool is_r_d2_batched = oDims[2] == rDims[2];\n bool is_r_d3_batched = oDims[3] == rDims[3];\n\n const T *lptr = lhs.get();\n const T *rptr = rhs.get();\n T *optr = out.get();\n\n for (int n = 0; n < batchSize; n++) {\n int w = n \/ oDims[2];\n int z = n - w * oDims[2];\n int loff = z * (is_l_d2_batched * lStrides[2]) +\n w * (is_l_d3_batched * lStrides[3]);\n int roff = z * (is_r_d2_batched * rStrides[2]) +\n w * (is_r_d3_batched * rStrides[3]);\n lptrs[n] = lptr + loff;\n rptrs[n] = rptr + roff;\n optrs[n] = optr + z * oStrides[2] + w * oStrides[3];\n }\n\n auto d_lptrs = memAlloc<uchar>(batchSize);\n auto d_rptrs = memAlloc<uchar>(batchSize);\n auto d_optrs = memAlloc<uchar>(batchSize);\n\n size_t bytes = batchSize * sizeof(T **);\n CUDA_CHECK(cudaMemcpyAsync(d_lptrs.get(), lptrs.data(), bytes,\n cudaMemcpyHostToDevice, getActiveStream()));\n CUDA_CHECK(cudaMemcpyAsync(d_rptrs.get(), rptrs.data(), bytes,\n cudaMemcpyHostToDevice, getActiveStream()));\n CUDA_CHECK(cudaMemcpyAsync(d_optrs.get(), optrs.data(), bytes,\n cudaMemcpyHostToDevice, getActiveStream()));\n\n CUDA_CHECK(cudaStreamSynchronize(getActiveStream()));\n\n CUBLAS_CHECK(gemmBatched_func<T>()(\n blasHandle(), lOpts, rOpts, M, N, K, &alpha,\n (const T **)d_lptrs.get(), lStrides[1], (const T **)d_rptrs.get(),\n rStrides[1], &beta, (T **)d_optrs.get(), oStrides[1], batchSize));\n }\n\n return out;\n}\n\ntemplate<typename T>\nArray<T> dot(const Array<T> &lhs, const Array<T> &rhs, af_mat_prop optLhs,\n af_mat_prop optRhs) {\n const Array<T> lhs_ = (optLhs == AF_MAT_NONE ? lhs : conj<T>(lhs));\n const Array<T> rhs_ = (optRhs == AF_MAT_NONE ? rhs : conj<T>(rhs));\n\n const Array<T> temp = arithOp<T, af_mul_t>(lhs_, rhs_, lhs_.dims());\n return reduce<af_add_t, T, T>(temp, 0, false, 0);\n}\n\ntemplate<typename T>\nvoid trsm(const Array<T> &lhs, Array<T> &rhs, af_mat_prop trans, bool is_upper,\n bool is_left, bool is_unit) {\n \/\/ dim4 lDims = lhs.dims();\n dim4 rDims = rhs.dims();\n int M = rDims[0];\n int N = rDims[1];\n\n T alpha = scalar<T>(1);\n\n dim4 lStrides = lhs.strides();\n dim4 rStrides = rhs.strides();\n\n CUBLAS_CHECK(trsm_func<T>()(\n blasHandle(), is_left ? CUBLAS_SIDE_LEFT : CUBLAS_SIDE_RIGHT,\n is_upper ? CUBLAS_FILL_MODE_UPPER : CUBLAS_FILL_MODE_LOWER,\n toCblasTranspose(trans),\n is_unit ? CUBLAS_DIAG_UNIT : CUBLAS_DIAG_NON_UNIT, M, N, &alpha,\n lhs.get(), lStrides[1], rhs.get(), rStrides[1]));\n}\n\n#define INSTANTIATE_BLAS(TYPE) \\\n template Array<TYPE> matmul<TYPE>(const Array<TYPE> &lhs, \\\n const Array<TYPE> &rhs, \\\n af_mat_prop optLhs, af_mat_prop optRhs);\n\nINSTANTIATE_BLAS(float)\nINSTANTIATE_BLAS(cfloat)\nINSTANTIATE_BLAS(double)\nINSTANTIATE_BLAS(cdouble)\n\n#define INSTANTIATE_DOT(TYPE) \\\n template Array<TYPE> dot<TYPE>(const Array<TYPE> &lhs, \\\n const Array<TYPE> &rhs, af_mat_prop optLhs, \\\n af_mat_prop optRhs);\n\nINSTANTIATE_DOT(float)\nINSTANTIATE_DOT(double)\nINSTANTIATE_DOT(cfloat)\nINSTANTIATE_DOT(cdouble)\n\n#define INSTANTIATE_TRSM(TYPE) \\\n template void trsm<TYPE>(const Array<TYPE> &lhs, Array<TYPE> &rhs, \\\n af_mat_prop trans, bool is_upper, bool is_left, \\\n bool is_unit);\n\nINSTANTIATE_TRSM(float)\nINSTANTIATE_TRSM(cfloat)\nINSTANTIATE_TRSM(double)\nINSTANTIATE_TRSM(cdouble)\n\n} \/\/ namespace cuda\n<commit_msg>Fix error in batch matmul because of invalid buffer size<commit_after>\/*******************************************************\n * Copyright (c) 2014, ArrayFire\n * All rights reserved.\n *\n * This file is distributed under 3-clause BSD license.\n * The complete license agreement can be obtained at:\n * http:\/\/arrayfire.com\/licenses\/BSD-3-Clause\n ********************************************************\/\n\n#include <blas.hpp>\n#include <cublas_v2.h>\n#include <cuda_runtime.h>\n#include <platform.hpp>\n\n#include <arith.hpp>\n#include <common\/err_common.hpp>\n#include <complex.hpp>\n#include <cublas.hpp>\n#include <err_cuda.hpp>\n#include <math.hpp>\n#include <reduce.hpp>\n#include <cassert>\n#include <stdexcept>\n#include <string>\n\nnamespace cuda {\n\ncublasOperation_t toCblasTranspose(af_mat_prop opt) {\n cublasOperation_t out = CUBLAS_OP_N;\n switch (opt) {\n case AF_MAT_NONE: out = CUBLAS_OP_N; break;\n case AF_MAT_TRANS: out = CUBLAS_OP_T; break;\n case AF_MAT_CTRANS: out = CUBLAS_OP_C; break;\n default: AF_ERROR(\"INVALID af_mat_prop\", AF_ERR_ARG);\n }\n return out;\n}\n\ntemplate<typename T>\nstruct gemm_func_def_t {\n typedef cublasStatus_t (*gemm_func_def)(cublasHandle_t, cublasOperation_t,\n cublasOperation_t, int, int, int,\n const T *, const T *, int,\n const T *, int, const T *, T *,\n int);\n};\n\ntemplate<typename T>\nstruct gemmBatched_func_def_t {\n typedef cublasStatus_t (*gemmBatched_func_def)(\n cublasHandle_t, cublasOperation_t, cublasOperation_t, int, int, int,\n const T *, const T **, int, const T **, int, const T *, T **, int, int);\n};\n\ntemplate<typename T>\nstruct gemv_func_def_t {\n typedef cublasStatus_t (*gemv_func_def)(cublasHandle_t, cublasOperation_t,\n int, int, const T *, const T *, int,\n const T *, int, const T *, T *,\n int);\n};\n\ntemplate<typename T>\nstruct trsm_func_def_t {\n typedef cublasStatus_t (*trsm_func_def)(cublasHandle_t, cublasSideMode_t,\n cublasFillMode_t, cublasOperation_t,\n cublasDiagType_t, int, int,\n const T *, const T *, int, T *,\n int);\n};\n\n#define BLAS_FUNC_DEF(FUNC) \\\n template<typename T> \\\n typename FUNC##_func_def_t<T>::FUNC##_func_def FUNC##_func();\n\n#define BLAS_FUNC(FUNC, TYPE, PREFIX) \\\n template<> \\\n typename FUNC##_func_def_t<TYPE>::FUNC##_func_def FUNC##_func<TYPE>() { \\\n return (FUNC##_func_def_t<TYPE>::FUNC##_func_def) & \\\n cublas##PREFIX##FUNC; \\\n }\n\nBLAS_FUNC_DEF(gemm)\nBLAS_FUNC(gemm, float, S)\nBLAS_FUNC(gemm, cfloat, C)\nBLAS_FUNC(gemm, double, D)\nBLAS_FUNC(gemm, cdouble, Z)\n\nBLAS_FUNC_DEF(gemmBatched)\nBLAS_FUNC(gemmBatched, float, S)\nBLAS_FUNC(gemmBatched, cfloat, C)\nBLAS_FUNC(gemmBatched, double, D)\nBLAS_FUNC(gemmBatched, cdouble, Z)\n\nBLAS_FUNC_DEF(gemv)\nBLAS_FUNC(gemv, float, S)\nBLAS_FUNC(gemv, cfloat, C)\nBLAS_FUNC(gemv, double, D)\nBLAS_FUNC(gemv, cdouble, Z)\n\nBLAS_FUNC_DEF(trsm)\nBLAS_FUNC(trsm, float, S)\nBLAS_FUNC(trsm, cfloat, C)\nBLAS_FUNC(trsm, double, D)\nBLAS_FUNC(trsm, cdouble, Z)\n\n#undef BLAS_FUNC\n#undef BLAS_FUNC_DEF\n\ntemplate<typename T, bool conjugate>\nstruct dot_func_def_t {\n typedef cublasStatus_t (*dot_func_def)(cublasHandle_t, int, const T *, int,\n const T *, int, T *);\n};\n\n#define BLAS_FUNC_DEF(FUNC) \\\n template<typename T, bool conjugate> \\\n typename FUNC##_func_def_t<T, conjugate>::FUNC##_func_def FUNC##_func();\n\n#define BLAS_FUNC(FUNC, TYPE, CONJUGATE, PREFIX) \\\n template<> \\\n typename FUNC##_func_def_t<TYPE, CONJUGATE>::FUNC##_func_def \\\n FUNC##_func<TYPE, CONJUGATE>() { \\\n return (FUNC##_func_def_t<TYPE, CONJUGATE>::FUNC##_func_def) & \\\n cublas##PREFIX##FUNC; \\\n }\n\nBLAS_FUNC_DEF(dot)\nBLAS_FUNC(dot, float, true, S)\nBLAS_FUNC(dot, double, true, D)\nBLAS_FUNC(dot, float, false, S)\nBLAS_FUNC(dot, double, false, D)\n\n#undef BLAS_FUNC\n\n#define BLAS_FUNC(FUNC, TYPE, CONJUGATE, PREFIX, SUFFIX) \\\n template<> \\\n typename FUNC##_func_def_t<TYPE, CONJUGATE>::FUNC##_func_def \\\n FUNC##_func<TYPE, CONJUGATE>() { \\\n return (FUNC##_func_def_t<TYPE, CONJUGATE>::FUNC##_func_def) & \\\n cublas##PREFIX##FUNC##SUFFIX; \\\n }\n\nBLAS_FUNC_DEF(dot)\nBLAS_FUNC(dot, cfloat, true, C, c)\nBLAS_FUNC(dot, cdouble, true, Z, c)\nBLAS_FUNC(dot, cfloat, false, C, u)\nBLAS_FUNC(dot, cdouble, false, Z, u)\n\n#undef BLAS_FUNC\n#undef BLAS_FUNC_DEF\n\nusing namespace std;\n\ntemplate<typename T>\nArray<T> matmul(const Array<T> &lhs, const Array<T> &rhs, af_mat_prop optLhs,\n af_mat_prop optRhs) {\n cublasOperation_t lOpts = toCblasTranspose(optLhs);\n cublasOperation_t rOpts = toCblasTranspose(optRhs);\n\n int aRowDim = (lOpts == CUBLAS_OP_N) ? 0 : 1;\n int aColDim = (lOpts == CUBLAS_OP_N) ? 1 : 0;\n int bColDim = (rOpts == CUBLAS_OP_N) ? 1 : 0;\n\n dim4 lDims = lhs.dims();\n dim4 rDims = rhs.dims();\n int M = lDims[aRowDim];\n int N = rDims[bColDim];\n int K = lDims[aColDim];\n\n dim_t d2 = std::max(lDims[2], rDims[2]);\n dim_t d3 = std::max(lDims[3], rDims[3]);\n dim4 oDims = dim4(M, N, d2, d3);\n Array<T> out = createEmptyArray<T>(oDims);\n\n T alpha = scalar<T>(1);\n T beta = scalar<T>(0);\n\n dim4 lStrides = lhs.strides();\n dim4 rStrides = rhs.strides();\n dim4 oStrides = out.strides();\n\n if (oDims.ndims() <= 2) {\n if (rDims[bColDim] == 1) {\n dim_t incr = (optRhs == AF_MAT_NONE) ? rStrides[0] : rStrides[1];\n N = lDims[aColDim];\n CUBLAS_CHECK(gemv_func<T>()(blasHandle(), lOpts, lDims[0], lDims[1],\n &alpha, lhs.get(), lStrides[1],\n rhs.get(), incr, &beta, out.get(), 1));\n } else {\n CUBLAS_CHECK(gemm_func<T>()(blasHandle(), lOpts, rOpts, M, N, K,\n &alpha, lhs.get(), lStrides[1],\n rhs.get(), rStrides[1], &beta,\n out.get(), oDims[0]));\n }\n } else {\n int batchSize = oDims[2] * oDims[3];\n std::vector<const T *> lptrs(batchSize);\n std::vector<const T *> rptrs(batchSize);\n std::vector<T *> optrs(batchSize);\n\n bool is_l_d2_batched = oDims[2] == lDims[2];\n bool is_l_d3_batched = oDims[3] == lDims[3];\n\n bool is_r_d2_batched = oDims[2] == rDims[2];\n bool is_r_d3_batched = oDims[3] == rDims[3];\n\n const T *lptr = lhs.get();\n const T *rptr = rhs.get();\n T *optr = out.get();\n\n for (int n = 0; n < batchSize; n++) {\n int w = n \/ oDims[2];\n int z = n - w * oDims[2];\n int loff = z * (is_l_d2_batched * lStrides[2]) +\n w * (is_l_d3_batched * lStrides[3]);\n int roff = z * (is_r_d2_batched * rStrides[2]) +\n w * (is_r_d3_batched * rStrides[3]);\n lptrs[n] = lptr + loff;\n rptrs[n] = rptr + roff;\n optrs[n] = optr + z * oStrides[2] + w * oStrides[3];\n }\n\n size_t bytes = batchSize * sizeof(T **);\n auto d_lptrs = memAlloc<uchar>(bytes);\n auto d_rptrs = memAlloc<uchar>(bytes);\n auto d_optrs = memAlloc<uchar>(bytes);\n CUDA_CHECK(cudaMemcpyAsync(d_lptrs.get(), lptrs.data(), bytes,\n cudaMemcpyHostToDevice, getActiveStream()));\n CUDA_CHECK(cudaMemcpyAsync(d_rptrs.get(), rptrs.data(), bytes,\n cudaMemcpyHostToDevice, getActiveStream()));\n CUDA_CHECK(cudaMemcpyAsync(d_optrs.get(), optrs.data(), bytes,\n cudaMemcpyHostToDevice, getActiveStream()));\n\n \/\/ Call this before the gemm call so that you don't have to wait for the\n \/\/ computation. Even though it would make more sense to put it\n \/\/ afterwards\n CUDA_CHECK(cudaStreamSynchronize(getActiveStream()));\n\n CUBLAS_CHECK(gemmBatched_func<T>()(\n blasHandle(), lOpts, rOpts, M, N, K, &alpha,\n (const T **)d_lptrs.get(), lStrides[1], (const T **)d_rptrs.get(),\n rStrides[1], &beta, (T **)d_optrs.get(), oStrides[1], batchSize));\n }\n\n return out;\n}\n\ntemplate<typename T>\nArray<T> dot(const Array<T> &lhs, const Array<T> &rhs, af_mat_prop optLhs,\n af_mat_prop optRhs) {\n const Array<T> lhs_ = (optLhs == AF_MAT_NONE ? lhs : conj<T>(lhs));\n const Array<T> rhs_ = (optRhs == AF_MAT_NONE ? rhs : conj<T>(rhs));\n\n const Array<T> temp = arithOp<T, af_mul_t>(lhs_, rhs_, lhs_.dims());\n return reduce<af_add_t, T, T>(temp, 0, false, 0);\n}\n\ntemplate<typename T>\nvoid trsm(const Array<T> &lhs, Array<T> &rhs, af_mat_prop trans, bool is_upper,\n bool is_left, bool is_unit) {\n \/\/ dim4 lDims = lhs.dims();\n dim4 rDims = rhs.dims();\n int M = rDims[0];\n int N = rDims[1];\n\n T alpha = scalar<T>(1);\n\n dim4 lStrides = lhs.strides();\n dim4 rStrides = rhs.strides();\n\n CUBLAS_CHECK(trsm_func<T>()(\n blasHandle(), is_left ? CUBLAS_SIDE_LEFT : CUBLAS_SIDE_RIGHT,\n is_upper ? CUBLAS_FILL_MODE_UPPER : CUBLAS_FILL_MODE_LOWER,\n toCblasTranspose(trans),\n is_unit ? CUBLAS_DIAG_UNIT : CUBLAS_DIAG_NON_UNIT, M, N, &alpha,\n lhs.get(), lStrides[1], rhs.get(), rStrides[1]));\n}\n\n#define INSTANTIATE_BLAS(TYPE) \\\n template Array<TYPE> matmul<TYPE>(const Array<TYPE> &lhs, \\\n const Array<TYPE> &rhs, \\\n af_mat_prop optLhs, af_mat_prop optRhs);\n\nINSTANTIATE_BLAS(float)\nINSTANTIATE_BLAS(cfloat)\nINSTANTIATE_BLAS(double)\nINSTANTIATE_BLAS(cdouble)\n\n#define INSTANTIATE_DOT(TYPE) \\\n template Array<TYPE> dot<TYPE>(const Array<TYPE> &lhs, \\\n const Array<TYPE> &rhs, af_mat_prop optLhs, \\\n af_mat_prop optRhs);\n\nINSTANTIATE_DOT(float)\nINSTANTIATE_DOT(double)\nINSTANTIATE_DOT(cfloat)\nINSTANTIATE_DOT(cdouble)\n\n#define INSTANTIATE_TRSM(TYPE) \\\n template void trsm<TYPE>(const Array<TYPE> &lhs, Array<TYPE> &rhs, \\\n af_mat_prop trans, bool is_upper, bool is_left, \\\n bool is_unit);\n\nINSTANTIATE_TRSM(float)\nINSTANTIATE_TRSM(cfloat)\nINSTANTIATE_TRSM(double)\nINSTANTIATE_TRSM(cdouble)\n\n} \/\/ namespace cuda\n<|endoftext|>"} {"text":"<commit_before>\/*\n\nCopyright (c) 2009-2012, Arvid Norberg\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in\n the documentation and\/or other materials provided with the distribution.\n * Neither the name of the author nor the names of its\n contributors may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#include \"libtorrent\/bandwidth_manager.hpp\"\n#include \"libtorrent\/time.hpp\"\n\nnamespace libtorrent\n{\n\n\tbandwidth_manager::bandwidth_manager(int channel\n#ifdef TORRENT_VERBOSE_BANDWIDTH_LIMIT\n\t\t, bool log = false\n#endif\t\t\n\t\t)\n\t\t: m_queued_bytes(0)\n\t\t, m_channel(channel)\n\t\t, m_abort(false)\n\t{\n#ifdef TORRENT_VERBOSE_BANDWIDTH_LIMIT\n\t\tif (log)\n\t\t\tm_log.open(\"bandwidth_limiter.log\", std::ios::trunc);\n\t\tm_start = time_now();\n#endif\n\t}\n\n\tvoid bandwidth_manager::close()\n\t{\n\t\tm_abort = true;\n\t\tm_queue.clear();\n\t\tm_queued_bytes = 0;\n\t}\n\n#if defined TORRENT_DEBUG || TORRENT_RELEASE_ASSERTS\n\tbool bandwidth_manager::is_queued(bandwidth_socket const* peer) const\n\t{\n\t\tfor (queue_t::const_iterator i = m_queue.begin()\n\t\t\t, end(m_queue.end()); i != end; ++i)\n\t\t{\n\t\t\tif (i->peer.get() == peer) return true;\n\t\t}\n\t\treturn false;\n\t}\n#endif\n\n\tint bandwidth_manager::queue_size() const\n\t{\n\t\treturn m_queue.size();\n\t}\n\n\tint bandwidth_manager::queued_bytes() const\n\t{\n\t\treturn m_queued_bytes;\n\t}\n\t\n\t\/\/ non prioritized means that, if there's a line for bandwidth,\n\t\/\/ others will cut in front of the non-prioritized peers.\n\t\/\/ this is used by web seeds\n\tint bandwidth_manager::request_bandwidth(boost::intrusive_ptr<bandwidth_socket> const& peer\n\t\t, int blk, int priority\n\t\t, bandwidth_channel* chan1\n\t\t, bandwidth_channel* chan2\n\t\t, bandwidth_channel* chan3\n\t\t, bandwidth_channel* chan4\n\t\t, bandwidth_channel* chan5\n\t\t)\n\t{\n\t\tINVARIANT_CHECK;\n\t\tif (m_abort) return 0;\n\n\t\tTORRENT_ASSERT(blk > 0);\n\t\tTORRENT_ASSERT(priority > 0);\n\t\tTORRENT_ASSERT(!is_queued(peer.get()));\n\n\t\tbw_request bwr(peer, blk, priority);\n\t\tint i = 0;\n\t\tif (chan1 && chan1->throttle() > 0) bwr.channel[i++] = chan1;\n\t\tif (chan2 && chan2->throttle() > 0) bwr.channel[i++] = chan2;\n\t\tif (chan3 && chan3->throttle() > 0) bwr.channel[i++] = chan3;\n\t\tif (chan4 && chan4->throttle() > 0) bwr.channel[i++] = chan4;\n\t\tif (chan5 && chan5->throttle() > 0) bwr.channel[i++] = chan5;\n\t\tif (i == 0)\n\t\t{\n\t\t\t\/\/ the connection is not rate limited by any of its\n\t\t\t\/\/ bandwidth channels, or it doesn't belong to any\n\t\t\t\/\/ channels. There's no point in adding it to\n\t\t\t\/\/ the queue, just satisfy the request immediately\n\t\t\treturn blk;\n\t\t}\n\t\tm_queued_bytes += blk;\n\t\tm_queue.push_back(bwr);\n\t\treturn 0;\n\t}\n\n#if defined TORRENT_DEBUG && !defined TORRENT_DISABLE_INVARIANT_CHECKS\n\tvoid bandwidth_manager::check_invariant() const\n\t{\n\t\tint queued = 0;\n\t\tfor (queue_t::const_iterator i = m_queue.begin()\n\t\t\t, end(m_queue.end()); i != end; ++i)\n\t\t{\n\t\t\tqueued += i->request_size - i->assigned;\n\t\t}\n\t\tTORRENT_ASSERT(queued == m_queued_bytes);\n\t}\n#endif\n\n\tvoid bandwidth_manager::update_quotas(time_duration const& dt)\n\t{\n\t\tif (m_abort) return;\n\t\tif (m_queue.empty()) return;\n\n\t\tINVARIANT_CHECK;\n\n\t\tint dt_milliseconds = total_milliseconds(dt);\n\t\tif (dt_milliseconds > 3000) dt_milliseconds = 3000;\n\n\t\t\/\/ for each bandwidth channel, call update_quota(dt)\n\n\t\tstd::vector<bandwidth_channel*> channels;\n\n\t\tfor (queue_t::iterator i = m_queue.begin();\n\t\t\ti != m_queue.end();)\n\t\t{\n\t\t\tif (i->peer->is_disconnecting())\n\t\t\t{\n\t\t\t\tm_queued_bytes -= i->request_size - i->assigned;\n\n\t\t\t\t\/\/ return all assigned quota to all the\n\t\t\t\t\/\/ bandwidth channels this peer belongs to\n\t\t\t\tfor (int j = 0; j < 5 && i->channel[j]; ++j)\n\t\t\t\t{\n\t\t\t\t\tbandwidth_channel* bwc = i->channel[j];\n\t\t\t\t\tbwc->return_quota(i->assigned);\n\t\t\t\t}\n\n\t\t\t\ti = m_queue.erase(i);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tfor (int j = 0; j < 5 && i->channel[j]; ++j)\n\t\t\t{\n\t\t\t\tbandwidth_channel* bwc = i->channel[j];\n\t\t\t\tbwc->tmp = 0;\n\t\t\t}\n\t\t\t++i;\n\t\t}\n\n\t\tfor (queue_t::iterator i = m_queue.begin()\n\t\t\t, end(m_queue.end()); i != end; ++i)\n\t\t{\n\t\t\tfor (int j = 0; j < 5 && i->channel[j]; ++j)\n\t\t\t{\n\t\t\t\tbandwidth_channel* bwc = i->channel[j];\n\t\t\t\tif (bwc->tmp == 0) channels.push_back(bwc);\n\t\t\t\tTORRENT_ASSERT(INT_MAX - bwc->tmp > i->priority);\n\t\t\t\tbwc->tmp += i->priority;\n\t\t\t}\n\t\t}\n\n\t\tfor (std::vector<bandwidth_channel*>::iterator i = channels.begin()\n\t\t\t, end(channels.end()); i != end; ++i)\n\t\t{\n\t\t\t(*i)->update_quota(dt_milliseconds);\n\t\t}\n\n\t\tqueue_t tm;\n\n\t\tfor (queue_t::iterator i = m_queue.begin();\n\t\t\ti != m_queue.end();)\n\t\t{\n\t\t\tint a = i->assign_bandwidth();\n\t\t\tif (i->assigned == i->request_size\n\t\t\t\t|| (i->ttl <= 0 && i->assigned > 0))\n\t\t\t{\n\t\t\t\ta += i->request_size - i->assigned;\n\t\t\t\tTORRENT_ASSERT(i->assigned <= i->request_size);\n\t\t\t\ttm.push_back(*i);\n\t\t\t\ti = m_queue.erase(i);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\t++i;\n\t\t\t}\n\t\t\tm_queued_bytes -= a;\n\t\t}\n\n\t\twhile (!tm.empty())\n\t\t{\n\t\t\tbw_request& bwr = tm.back();\n\t\t\tbwr.peer->assign_bandwidth(m_channel, bwr.assigned);\n\t\t\ttm.pop_back();\n\t\t}\n\t}\n}\n\n<commit_msg>fix bandwidth-limit-logging build<commit_after>\/*\n\nCopyright (c) 2009-2012, Arvid Norberg\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in\n the documentation and\/or other materials provided with the distribution.\n * Neither the name of the author nor the names of its\n contributors may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#include \"libtorrent\/bandwidth_manager.hpp\"\n#include \"libtorrent\/time.hpp\"\n\nnamespace libtorrent\n{\n\n\tbandwidth_manager::bandwidth_manager(int channel\n#ifdef TORRENT_VERBOSE_BANDWIDTH_LIMIT\n\t\t, bool log\n#endif\t\t\n\t\t)\n\t\t: m_queued_bytes(0)\n\t\t, m_channel(channel)\n\t\t, m_abort(false)\n\t{\n#ifdef TORRENT_VERBOSE_BANDWIDTH_LIMIT\n\t\tif (log)\n\t\t\tm_log.open(\"bandwidth_limiter.log\", std::ios::trunc);\n\t\tm_start = time_now();\n#endif\n\t}\n\n\tvoid bandwidth_manager::close()\n\t{\n\t\tm_abort = true;\n\t\tm_queue.clear();\n\t\tm_queued_bytes = 0;\n\t}\n\n#if defined TORRENT_DEBUG || TORRENT_RELEASE_ASSERTS\n\tbool bandwidth_manager::is_queued(bandwidth_socket const* peer) const\n\t{\n\t\tfor (queue_t::const_iterator i = m_queue.begin()\n\t\t\t, end(m_queue.end()); i != end; ++i)\n\t\t{\n\t\t\tif (i->peer.get() == peer) return true;\n\t\t}\n\t\treturn false;\n\t}\n#endif\n\n\tint bandwidth_manager::queue_size() const\n\t{\n\t\treturn m_queue.size();\n\t}\n\n\tint bandwidth_manager::queued_bytes() const\n\t{\n\t\treturn m_queued_bytes;\n\t}\n\t\n\t\/\/ non prioritized means that, if there's a line for bandwidth,\n\t\/\/ others will cut in front of the non-prioritized peers.\n\t\/\/ this is used by web seeds\n\tint bandwidth_manager::request_bandwidth(boost::intrusive_ptr<bandwidth_socket> const& peer\n\t\t, int blk, int priority\n\t\t, bandwidth_channel* chan1\n\t\t, bandwidth_channel* chan2\n\t\t, bandwidth_channel* chan3\n\t\t, bandwidth_channel* chan4\n\t\t, bandwidth_channel* chan5\n\t\t)\n\t{\n\t\tINVARIANT_CHECK;\n\t\tif (m_abort) return 0;\n\n\t\tTORRENT_ASSERT(blk > 0);\n\t\tTORRENT_ASSERT(priority > 0);\n\t\tTORRENT_ASSERT(!is_queued(peer.get()));\n\n\t\tbw_request bwr(peer, blk, priority);\n\t\tint i = 0;\n\t\tif (chan1 && chan1->throttle() > 0) bwr.channel[i++] = chan1;\n\t\tif (chan2 && chan2->throttle() > 0) bwr.channel[i++] = chan2;\n\t\tif (chan3 && chan3->throttle() > 0) bwr.channel[i++] = chan3;\n\t\tif (chan4 && chan4->throttle() > 0) bwr.channel[i++] = chan4;\n\t\tif (chan5 && chan5->throttle() > 0) bwr.channel[i++] = chan5;\n\t\tif (i == 0)\n\t\t{\n\t\t\t\/\/ the connection is not rate limited by any of its\n\t\t\t\/\/ bandwidth channels, or it doesn't belong to any\n\t\t\t\/\/ channels. There's no point in adding it to\n\t\t\t\/\/ the queue, just satisfy the request immediately\n\t\t\treturn blk;\n\t\t}\n\t\tm_queued_bytes += blk;\n\t\tm_queue.push_back(bwr);\n\t\treturn 0;\n\t}\n\n#if defined TORRENT_DEBUG && !defined TORRENT_DISABLE_INVARIANT_CHECKS\n\tvoid bandwidth_manager::check_invariant() const\n\t{\n\t\tint queued = 0;\n\t\tfor (queue_t::const_iterator i = m_queue.begin()\n\t\t\t, end(m_queue.end()); i != end; ++i)\n\t\t{\n\t\t\tqueued += i->request_size - i->assigned;\n\t\t}\n\t\tTORRENT_ASSERT(queued == m_queued_bytes);\n\t}\n#endif\n\n\tvoid bandwidth_manager::update_quotas(time_duration const& dt)\n\t{\n\t\tif (m_abort) return;\n\t\tif (m_queue.empty()) return;\n\n\t\tINVARIANT_CHECK;\n\n\t\tint dt_milliseconds = total_milliseconds(dt);\n\t\tif (dt_milliseconds > 3000) dt_milliseconds = 3000;\n\n\t\t\/\/ for each bandwidth channel, call update_quota(dt)\n\n\t\tstd::vector<bandwidth_channel*> channels;\n\n\t\tfor (queue_t::iterator i = m_queue.begin();\n\t\t\ti != m_queue.end();)\n\t\t{\n\t\t\tif (i->peer->is_disconnecting())\n\t\t\t{\n\t\t\t\tm_queued_bytes -= i->request_size - i->assigned;\n\n\t\t\t\t\/\/ return all assigned quota to all the\n\t\t\t\t\/\/ bandwidth channels this peer belongs to\n\t\t\t\tfor (int j = 0; j < 5 && i->channel[j]; ++j)\n\t\t\t\t{\n\t\t\t\t\tbandwidth_channel* bwc = i->channel[j];\n\t\t\t\t\tbwc->return_quota(i->assigned);\n\t\t\t\t}\n\n\t\t\t\ti = m_queue.erase(i);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tfor (int j = 0; j < 5 && i->channel[j]; ++j)\n\t\t\t{\n\t\t\t\tbandwidth_channel* bwc = i->channel[j];\n\t\t\t\tbwc->tmp = 0;\n\t\t\t}\n\t\t\t++i;\n\t\t}\n\n\t\tfor (queue_t::iterator i = m_queue.begin()\n\t\t\t, end(m_queue.end()); i != end; ++i)\n\t\t{\n\t\t\tfor (int j = 0; j < 5 && i->channel[j]; ++j)\n\t\t\t{\n\t\t\t\tbandwidth_channel* bwc = i->channel[j];\n\t\t\t\tif (bwc->tmp == 0) channels.push_back(bwc);\n\t\t\t\tTORRENT_ASSERT(INT_MAX - bwc->tmp > i->priority);\n\t\t\t\tbwc->tmp += i->priority;\n\t\t\t}\n\t\t}\n\n\t\tfor (std::vector<bandwidth_channel*>::iterator i = channels.begin()\n\t\t\t, end(channels.end()); i != end; ++i)\n\t\t{\n\t\t\t(*i)->update_quota(dt_milliseconds);\n\t\t}\n\n\t\tqueue_t tm;\n\n\t\tfor (queue_t::iterator i = m_queue.begin();\n\t\t\ti != m_queue.end();)\n\t\t{\n\t\t\tint a = i->assign_bandwidth();\n\t\t\tif (i->assigned == i->request_size\n\t\t\t\t|| (i->ttl <= 0 && i->assigned > 0))\n\t\t\t{\n\t\t\t\ta += i->request_size - i->assigned;\n\t\t\t\tTORRENT_ASSERT(i->assigned <= i->request_size);\n\t\t\t\ttm.push_back(*i);\n\t\t\t\ti = m_queue.erase(i);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\t++i;\n\t\t\t}\n\t\t\tm_queued_bytes -= a;\n\t\t}\n\n\t\twhile (!tm.empty())\n\t\t{\n\t\t\tbw_request& bwr = tm.back();\n\t\t\tbwr.peer->assign_bandwidth(m_channel, bwr.assigned);\n\t\t\ttm.pop_back();\n\t\t}\n\t}\n}\n\n<|endoftext|>"} {"text":"<commit_before>#ifdef LINUX_PLATFORM\n\n#include \"LinuxEventLoop.hpp\"\n\n#include \"Application.hpp\"\n#include \"Context.hpp\"\n#include \"InputService.hpp\"\n#include \"TimeService.hpp\"\n#include \"Global.hpp\"\n#include \"Profiler.hpp\"\n#include \"Render.hpp\"\n#include \"Log.hpp\"\n\nusing namespace std;\n\nnamespace MPACK\n{\n\tnamespace Core\n\t{\n\t\ttypedef GLXContext ( * PFNGLXCREATECONTEXTATTRIBSARBPROC) (Display *dpy, GLXFBConfig config, GLXContext share_context, Bool direct, const int *attrib_list);\n\n\n\t\tLinuxEventLoop::LinuxEventLoop(void *data)\n\t\t\t: m_isFullscreen(false), m_isRunning(false), m_width(0), m_height(0),\n\t\t\t m_newWidth(0), m_newHeight(0), m_enabled(false), m_glContext(NULL),\n\t\t\t m_isResizing(false)\n\t\t{\n\t\t}\n\n\t\tReturnValue LinuxEventLoop::Run(Application* pApplication)\n\t\t{\n\t\t\tm_pApplication = pApplication;\n\t\t\tm_isRunning=true;\n\n\t\t\tif(InitializeDisplay() == RETURN_VALUE_KO)\n\t\t\t{\n\t\t\t\tLOGE(\"LinuxEventLoop::Run failed to InitializeDisplay()\");\n\t\t\t\treturn RETURN_VALUE_KO;\n\t\t\t}\n\t\t\tGraphics::Render::SetScreenSize(m_width,m_height);\n\t\t\tm_pApplication->onActivate();\n\n\t\t\t\/\/ Global step loop.\n\t\t\twhile(m_isRunning)\n\t\t\t{\n\t\t\t\tProcessEvents();\n\t\t\t\tif(!m_isResizing)\n\t\t\t\t{\n\t\t\t\t\tif(m_pApplication->onStep() != RETURN_VALUE_OK)\n\t\t\t\t\t{\n\t\t\t\t\t\tm_isRunning=false;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tSwapBuffers();\n\t\t\t}\n\n\t\t\tm_pApplication->onDeactivate();\n\t\t\tDestroyDisplay();\n\t\t\treturn RETURN_VALUE_OK;\n\t\t}\n\n\t\tvoid LinuxEventLoop::ShowCursor()\n\t\t{\n\t\t\tDisplay* mainDisplay = XOpenDisplay(NULL);\n\n\t\t\tXUndefineCursor(mainDisplay, m_XWindow);\n\n\t\t\tXCloseDisplay(mainDisplay);\n\t\t}\n\n\t\tvoid LinuxEventLoop::HideCursor()\n\t\t{\n\t\t\tDisplay* mainDisplay = XOpenDisplay(NULL);\n\n\t\t\tPixmap blank;\n\t\t\tXColor dummy;\n\t\t\tchar data[1] = {0};\n\n\t\t\t\/* make a blank cursor *\/\n\t\t\tblank = XCreateBitmapFromData (mainDisplay, m_XWindow, data, 1, 1);\n\t\t\tCursor m_cursor = XCreatePixmapCursor(mainDisplay, blank, blank, &dummy, &dummy, 0, 0);\n\t\t\tXFreePixmap (mainDisplay, blank);\n\n\t\t\tXDefineCursor(mainDisplay, m_XWindow, m_cursor);\n\n\t\t\tXCloseDisplay(mainDisplay);\n\t\t}\n\n\t\tvoid* LinuxEventLoop::GetWindowHandle() const\n\t\t{\n\t\t\treturn (void *)(&m_XWindow);\n\t\t}\n\n\t\tReturnValue LinuxEventLoop::InitializeDisplay()\n\t\t{\n\t\t\tint width = 800;\n\t\t\tint height = 600;\n\t\t\tm_width = width;\n\t\t\tm_height = height;\n\t\t\tm_newWidth = width;\n\t\t\tm_newHeight = height;\n\t\t\tint bpp = 32;\n\t\t\tbool fullscreen=false;\n\n\t\t\tm_display = XOpenDisplay(0);\n\n\t\t\tif (m_display == NULL)\n\t\t\t{\n\t\t\t\tLOGE(\"Could not open the display\");\n\t\t\t\treturn RETURN_VALUE_KO;\n\t\t\t}\n\n\t\t\tm_screenID = DefaultScreen(m_display); \/\/Get the default screen id\n\t\t\tWindow root = RootWindow(m_display, m_screenID);\n\n\t\t\tint n = 0, modeNum = 0;\n\t\t\tXF86VidModeModeInfo **modes;\n\t\t\tif (!XF86VidModeGetAllModeLines(m_display, m_screenID, &modeNum, &modes))\n\t\t\t{\n\t\t\t\tLOGE(\"Could not query the video modes\");\n\t\t\t\treturn RETURN_VALUE_KO;\n\t\t\t}\n\n\t\t\tm_XF86DeskMode = *modes[0];\n\n\t\t\tint bestMode = -1;\n\t\t\tfor (int i = 0; i < modeNum; i++)\n\t\t\t{\n\t\t\t\tif ((modes[i]->hdisplay == width) &&\n\t\t\t\t\t(modes[i]->vdisplay == height))\n\t\t\t\t{\n\t\t\t\t\tbestMode = i;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (bestMode == -1)\n\t\t\t{\n\t\t\t\tLOGE(\"Could not find a suitable graphics mode\");\n\t\t\t\treturn RETURN_VALUE_KO;\n\t\t\t}\n\n\n\t\t\tint doubleBufferedAttribList [] = {\n\t\t\t\tGLX_RGBA, GLX_DOUBLEBUFFER,\n\t\t\t\tGLX_RED_SIZE, 4,\n\t\t\t\tGLX_GREEN_SIZE, 4,\n\t\t\t\tGLX_BLUE_SIZE, 4,\n\t\t\t\tGLX_ALPHA_SIZE, 4,\n\t\t\t\tGLX_DEPTH_SIZE, 16,\n\t\t\t\tNone\n\t\t\t};\n\n\t\t\tXVisualInfo* vi = NULL;\n\t\t\t\/\/Attempt to create a double buffered window\n\t\t\tvi = glXChooseVisual(m_display, m_screenID, doubleBufferedAttribList);\n\n\t\t\tif (vi == NULL)\n\t\t\t{\n\t\t\t\tLOGE(\"Could not create a double buffered window\");\n\t\t\t\treturn RETURN_VALUE_KO;\n\t\t\t}\n\n\t\t\tColormap cmap = XCreateColormap(m_display, root, vi->visual, AllocNone);\n\n\t\t\tm_XSetAttr.background_pixel = 0;\n\t\t\tm_XSetAttr.border_pixel = 0;\n\t\t\tm_XSetAttr.colormap = cmap;\n\t\t\tm_XSetAttr.event_mask = ExposureMask | KeyPressMask | KeyReleaseMask | ButtonPressMask |\n\t\t\t\t\t\t\t\t\t\tStructureNotifyMask;\n\t\t\tm_XSetAttr.override_redirect = False;\n\n\t\t\tunsigned long windowAttributes = CWBackPixel | CWBorderPixel | CWColormap | CWEventMask | CWOverrideRedirect;\n\n\t\t\tif (fullscreen)\n\t\t\t{\n\t\t\t\twindowAttributes = CWBorderPixel | CWColormap | CWEventMask | CWOverrideRedirect;\n\n\t\t\t\tXF86VidModeSwitchToMode(m_display, m_screenID, modes[bestMode]);\n\t\t\t\tXF86VidModeSetViewPort(m_display, m_screenID, 0, 0);\n\t\t\t\tm_XSetAttr.override_redirect = True;\n\t\t\t}\n\n\t\t\tm_XWindow = XCreateWindow(m_display, root,\n\t\t\t\t\t\t\t\t\t\t 0, 0, width, height, 0, vi->depth, InputOutput, vi->visual,\n\t\t\t\t\t\t\t\t\t\t windowAttributes, &m_XSetAttr);\n\n\t\t\t{\n\t\t\t\tXSizeHints sizehints;\n\t\t\t\tsizehints.x = 0;\n\t\t\t\tsizehints.y = 0;\n\t\t\t\tsizehints.width = width;\n\t\t\t\tsizehints.height = height;\n\t\t\t\tsizehints.flags = USSize | USPosition;\n\t\t\t\tXSetNormalHints(m_display, m_XWindow, &sizehints);\n\t\t\t}\n\n\t\t\t\/\/Create a GL 2.1 context\n\t\t\tGLXContext m_glContext = glXCreateContext(m_display, vi, 0, GL_TRUE);\n\t\t\tXFree(vi);\n\n\t\t\tif (m_glContext == NULL)\n\t\t\t{\n\t\t\t\tLOGE(\"Could not create a GL 2.1 context, please check your graphics drivers\");\n\t\t\t\treturn RETURN_VALUE_KO;\n\t\t\t}\n\n\t\t\tm_GL3Supported = false; \/\/we're not using GL3.0 here!\n\n\t\t\tstring title = \"MPACK\";\n\n\t\t\tif (fullscreen)\n\t\t\t{\n\t\t\t\tXWarpPointer(m_display, None, m_XWindow, 0, 0, 0, 0, 0, 0);\n\t\t\t\tXMapRaised(m_display, m_XWindow);\n\t\t\t\tXGrabKeyboard(m_display, m_XWindow, True, GrabModeAsync, GrabModeAsync, CurrentTime);\n\t\t\t\tXGrabPointer(m_display, m_XWindow, True, ButtonPressMask,\n\t\t\t\t\t\t\t GrabModeAsync, GrabModeAsync, m_XWindow, None, CurrentTime);\n\n\t\t\t\tm_isFullscreen = true;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tAtom wmDelete = XInternAtom(m_display, \"WM_DELETE_WINDOW\", True);\n\t\t\t\tXSetWMProtocols(m_display, m_XWindow, &wmDelete, 1);\n\n\t\t\t\tXSetStandardProperties(m_display, m_XWindow, title.c_str(), None, 0, NULL, 0, NULL);\n\t\t\t\tXMapRaised(m_display, m_XWindow);\n\t\t\t}\n\n\t\t\tXFree(modes);\n\n\t\t\t\/\/Make the new context current\n\t\t\tglXMakeCurrent(m_display, m_XWindow, m_glContext);\n\n\t\t\ttypedef int (*PFNGLXSWAPINTERVALMESA)(int interval);\n\t\t\tPFNGLXSWAPINTERVALMESA glXSwapIntervalMESA = NULL;\n\n\t\t\tglXSwapIntervalMESA = (PFNGLXSWAPINTERVALMESA)glXGetProcAddress((unsigned char*)\"glXSwapIntervalMESA\");\n\t\t\tif( !glXSwapIntervalMESA )\n\t\t\t{\n\t\t\t\t return RETURN_VALUE_KO;\n\t\t\t}\n\n\t\t\tglXSwapIntervalMESA(0);\n\n\t\t\treturn RETURN_VALUE_OK;\n\t\t}\n\n\t\tvoid LinuxEventLoop::DestroyDisplay()\n\t\t{\n\t\t\tif(m_glContext)\n\t\t\t{\n\t\t\t\tglXMakeCurrent(m_display, None, NULL);\n\t\t\t\tglXDestroyContext(m_display, m_glContext);\n\t\t\t\tm_glContext = NULL;\n\t\t\t}\n\n\t\t\tif(m_isFullscreen)\n\t\t\t{\n\t\t\t\tXF86VidModeSwitchToMode(m_display, m_screenID, &m_XF86DeskMode);\n\t\t\t\tXF86VidModeSetViewPort(m_display, m_screenID, 0, 0);\n\t\t\t}\n\n\t\t\tXCloseDisplay(m_display);\n\t\t}\n\n\t\tvoid LinuxEventLoop::ProcessEvents()\n\t\t{\n\t\t\tGlobal::pContext->pTimeService->Update();\n\t\t\tGlobal::pContext->pInputService->Update();\n\n\t\t\tXEvent event;\n\n\t\t\tint width, height;\n\n\t\t\twhile (XPending(m_display) > 0)\n\t\t\t{\n\t\t\t\tXNextEvent(m_display, &event);\n\t\t\t\tswitch (event.type)\n\t\t\t\t{\n\t\t\t\t\tcase Expose:\n\t\t\t\t\tbreak;\n\t\t\t\t\tcase ConfigureNotify:\n\t\t\t\t\t\twidth = event.xconfigure.width;\n\t\t\t\t\t\theight = event.xconfigure.height;\n\t\t\t\t\t\tif(width != m_newWidth || height != m_newHeight)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tm_newWidth = width;\n\t\t\t\t\t\t\tm_newHeight = height;\n\t\t\t\t\t\t\tm_isResizing = true;\n\t\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\t\tcase KeyPress:\n\t\t\t\t\t\tGlobal::pContext->pInputService->GetKeyboard()->HandleKeyDown(Global::pContext->pInputService->GetKeyboard()->TranslateCode(XLookupKeysym(&event.xkey,0)));\n\t\t\t\t\tbreak;\n\t\t\t\t\tcase KeyRelease:\n\t\t\t\t\t\tGlobal::pContext->pInputService->GetKeyboard()->HandleKeyUp(Global::pContext->pInputService->GetKeyboard()->TranslateCode(XLookupKeysym(&event.xkey,0)));\n\t\t\t\t\tbreak;\n\t\t\t\t\tcase ClientMessage:\n\t\t\t\t\t\tif (string(XGetAtomName(m_display, event.xclient.message_type)) == string(\"WM_PROTOCOLS\"))\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tm_isRunning = false;\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\t\tdefault:\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (Global::pContext->pInputService->GetMouse()->ButtonUp(Input::MouseButton::MBC_LEFT) == 1)\n\t\t\t{\n\t\t\t\tif(m_isResizing)\n\t\t\t\t{\n\t\t\t\t\tif (m_newWidth != m_width || m_newHeight != m_height)\n\t\t\t\t\t{\n\t\t\t\t\t\tm_width = m_newWidth;\n\t\t\t\t\t\tm_height = m_newHeight;\n\t\t\t\t\t\tm_pApplication->onDeactivate();\n\t\t\t\t\t\tGraphics::Render::SetScreenSize(m_width,m_height);\n\t\t\t\t\t\tm_pApplication->onActivate();\n\t\t\t\t\t}\n\t\t\t\t\tm_isResizing = false;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tvoid LinuxEventLoop::SwapBuffers()\n\t\t{\n\t\t\tPROFILE_BEGIN(\"SwapBuffers\");\n\t\t\tglXSwapBuffers(m_display, m_XWindow);\n\t\t\tPROFILE_END();\n\t\t}\n\t}\n}\n\n#endif\n<commit_msg>Refactor error messages<commit_after>#ifdef LINUX_PLATFORM\n\n#include \"LinuxEventLoop.hpp\"\n\n#include \"Application.hpp\"\n#include \"Context.hpp\"\n#include \"InputService.hpp\"\n#include \"TimeService.hpp\"\n#include \"Global.hpp\"\n#include \"Profiler.hpp\"\n#include \"Render.hpp\"\n#include \"Log.hpp\"\n\nusing namespace std;\n\nnamespace MPACK\n{\n\tnamespace Core\n\t{\n\t\ttypedef GLXContext ( * PFNGLXCREATECONTEXTATTRIBSARBPROC) (Display *dpy, GLXFBConfig config, GLXContext share_context, Bool direct, const int *attrib_list);\n\n\n\t\tLinuxEventLoop::LinuxEventLoop(void *data)\n\t\t\t: m_isFullscreen(false), m_isRunning(false), m_width(0), m_height(0),\n\t\t\t m_newWidth(0), m_newHeight(0), m_enabled(false), m_glContext(NULL),\n\t\t\t m_isResizing(false)\n\t\t{\n\t\t}\n\n\t\tReturnValue LinuxEventLoop::Run(Application* pApplication)\n\t\t{\n\t\t\tm_pApplication = pApplication;\n\t\t\tm_isRunning=true;\n\n\t\t\tif(InitializeDisplay() == RETURN_VALUE_KO)\n\t\t\t{\n\t\t\t\tLOGE(\"LinuxEventLoop::Run() failed to InitializeDisplay()\");\n\t\t\t\treturn RETURN_VALUE_KO;\n\t\t\t}\n\t\t\tGraphics::Render::SetScreenSize(m_width,m_height);\n\t\t\tm_pApplication->onActivate();\n\n\t\t\t\/\/ Global step loop.\n\t\t\twhile(m_isRunning)\n\t\t\t{\n\t\t\t\tProcessEvents();\n\t\t\t\tif(!m_isResizing)\n\t\t\t\t{\n\t\t\t\t\tif(m_pApplication->onStep() != RETURN_VALUE_OK)\n\t\t\t\t\t{\n\t\t\t\t\t\tm_isRunning=false;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tSwapBuffers();\n\t\t\t}\n\n\t\t\tm_pApplication->onDeactivate();\n\t\t\tDestroyDisplay();\n\t\t\treturn RETURN_VALUE_OK;\n\t\t}\n\n\t\tvoid LinuxEventLoop::ShowCursor()\n\t\t{\n\t\t\tDisplay* mainDisplay = XOpenDisplay(NULL);\n\n\t\t\tXUndefineCursor(mainDisplay, m_XWindow);\n\n\t\t\tXCloseDisplay(mainDisplay);\n\t\t}\n\n\t\tvoid LinuxEventLoop::HideCursor()\n\t\t{\n\t\t\tDisplay* mainDisplay = XOpenDisplay(NULL);\n\n\t\t\tPixmap blank;\n\t\t\tXColor dummy;\n\t\t\tchar data[1] = {0};\n\n\t\t\t\/* make a blank cursor *\/\n\t\t\tblank = XCreateBitmapFromData (mainDisplay, m_XWindow, data, 1, 1);\n\t\t\tCursor m_cursor = XCreatePixmapCursor(mainDisplay, blank, blank, &dummy, &dummy, 0, 0);\n\t\t\tXFreePixmap (mainDisplay, blank);\n\n\t\t\tXDefineCursor(mainDisplay, m_XWindow, m_cursor);\n\n\t\t\tXCloseDisplay(mainDisplay);\n\t\t}\n\n\t\tvoid* LinuxEventLoop::GetWindowHandle() const\n\t\t{\n\t\t\treturn (void *)(&m_XWindow);\n\t\t}\n\n\t\tReturnValue LinuxEventLoop::InitializeDisplay()\n\t\t{\n\t\t\tint width = 800;\n\t\t\tint height = 600;\n\t\t\tm_width = width;\n\t\t\tm_height = height;\n\t\t\tm_newWidth = width;\n\t\t\tm_newHeight = height;\n\t\t\tint bpp = 32;\n\t\t\tbool fullscreen=false;\n\n\t\t\tm_display = XOpenDisplay(0);\n\n\t\t\tif (m_display == NULL)\n\t\t\t{\n\t\t\t\tLOGE(\"LinuxEventLoop::InitializeDisplay() could not open the display\");\n\t\t\t\treturn RETURN_VALUE_KO;\n\t\t\t}\n\n\t\t\tm_screenID = DefaultScreen(m_display); \/\/Get the default screen id\n\t\t\tWindow root = RootWindow(m_display, m_screenID);\n\n\t\t\tint n = 0, modeNum = 0;\n\t\t\tXF86VidModeModeInfo **modes;\n\t\t\tif (!XF86VidModeGetAllModeLines(m_display, m_screenID, &modeNum, &modes))\n\t\t\t{\n\t\t\t\tLOGE(\"LinuxEventLoop::InitializeDisplay() could not query the video modes\");\n\t\t\t\treturn RETURN_VALUE_KO;\n\t\t\t}\n\n\t\t\tm_XF86DeskMode = *modes[0];\n\n\t\t\tint bestMode = -1;\n\t\t\tfor (int i = 0; i < modeNum; i++)\n\t\t\t{\n\t\t\t\tif ((modes[i]->hdisplay == width) &&\n\t\t\t\t\t(modes[i]->vdisplay == height))\n\t\t\t\t{\n\t\t\t\t\tbestMode = i;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (bestMode == -1)\n\t\t\t{\n\t\t\t\tLOGE(\"LinuxEventLoop::InitializeDisplay() could not find a suitable graphics mode\");\n\t\t\t\treturn RETURN_VALUE_KO;\n\t\t\t}\n\n\n\t\t\tint doubleBufferedAttribList [] = {\n\t\t\t\tGLX_RGBA, GLX_DOUBLEBUFFER,\n\t\t\t\tGLX_RED_SIZE, 4,\n\t\t\t\tGLX_GREEN_SIZE, 4,\n\t\t\t\tGLX_BLUE_SIZE, 4,\n\t\t\t\tGLX_ALPHA_SIZE, 4,\n\t\t\t\tGLX_DEPTH_SIZE, 16,\n\t\t\t\tNone\n\t\t\t};\n\n\t\t\tXVisualInfo* vi = NULL;\n\t\t\t\/\/Attempt to create a double buffered window\n\t\t\tvi = glXChooseVisual(m_display, m_screenID, doubleBufferedAttribList);\n\n\t\t\tif (vi == NULL)\n\t\t\t{\n\t\t\t\tLOGE(\"LinuxEventLoop::InitializeDisplay() could not create a double buffered window\");\n\t\t\t\treturn RETURN_VALUE_KO;\n\t\t\t}\n\n\t\t\tColormap cmap = XCreateColormap(m_display, root, vi->visual, AllocNone);\n\n\t\t\tm_XSetAttr.background_pixel = 0;\n\t\t\tm_XSetAttr.border_pixel = 0;\n\t\t\tm_XSetAttr.colormap = cmap;\n\t\t\tm_XSetAttr.event_mask = ExposureMask | KeyPressMask | KeyReleaseMask | ButtonPressMask |\n\t\t\t\t\t\t\t\t\t\tStructureNotifyMask;\n\t\t\tm_XSetAttr.override_redirect = False;\n\n\t\t\tunsigned long windowAttributes = CWBackPixel | CWBorderPixel | CWColormap | CWEventMask | CWOverrideRedirect;\n\n\t\t\tif (fullscreen)\n\t\t\t{\n\t\t\t\twindowAttributes = CWBorderPixel | CWColormap | CWEventMask | CWOverrideRedirect;\n\n\t\t\t\tXF86VidModeSwitchToMode(m_display, m_screenID, modes[bestMode]);\n\t\t\t\tXF86VidModeSetViewPort(m_display, m_screenID, 0, 0);\n\t\t\t\tm_XSetAttr.override_redirect = True;\n\t\t\t}\n\n\t\t\tm_XWindow = XCreateWindow(m_display, root,\n\t\t\t\t\t\t\t\t\t\t 0, 0, width, height, 0, vi->depth, InputOutput, vi->visual,\n\t\t\t\t\t\t\t\t\t\t windowAttributes, &m_XSetAttr);\n\n\t\t\t{\n\t\t\t\tXSizeHints sizehints;\n\t\t\t\tsizehints.x = 0;\n\t\t\t\tsizehints.y = 0;\n\t\t\t\tsizehints.width = width;\n\t\t\t\tsizehints.height = height;\n\t\t\t\tsizehints.flags = USSize | USPosition;\n\t\t\t\tXSetNormalHints(m_display, m_XWindow, &sizehints);\n\t\t\t}\n\n\t\t\t\/\/Create a GL 2.1 context\n\t\t\tGLXContext m_glContext = glXCreateContext(m_display, vi, 0, GL_TRUE);\n\t\t\tXFree(vi);\n\n\t\t\tif (m_glContext == NULL)\n\t\t\t{\n\t\t\t\tLOGE(\"LinuxEventLoop::InitializeDisplay() could not create a GL 2.1 context, please check your graphics drivers\");\n\t\t\t\treturn RETURN_VALUE_KO;\n\t\t\t}\n\n\t\t\tm_GL3Supported = false; \/\/we're not using GL3.0 here!\n\n\t\t\tstring title = \"MPACK\";\n\n\t\t\tif (fullscreen)\n\t\t\t{\n\t\t\t\tXWarpPointer(m_display, None, m_XWindow, 0, 0, 0, 0, 0, 0);\n\t\t\t\tXMapRaised(m_display, m_XWindow);\n\t\t\t\tXGrabKeyboard(m_display, m_XWindow, True, GrabModeAsync, GrabModeAsync, CurrentTime);\n\t\t\t\tXGrabPointer(m_display, m_XWindow, True, ButtonPressMask,\n\t\t\t\t\t\t\t GrabModeAsync, GrabModeAsync, m_XWindow, None, CurrentTime);\n\n\t\t\t\tm_isFullscreen = true;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tAtom wmDelete = XInternAtom(m_display, \"WM_DELETE_WINDOW\", True);\n\t\t\t\tXSetWMProtocols(m_display, m_XWindow, &wmDelete, 1);\n\n\t\t\t\tXSetStandardProperties(m_display, m_XWindow, title.c_str(), None, 0, NULL, 0, NULL);\n\t\t\t\tXMapRaised(m_display, m_XWindow);\n\t\t\t}\n\n\t\t\tXFree(modes);\n\n\t\t\t\/\/Make the new context current\n\t\t\tglXMakeCurrent(m_display, m_XWindow, m_glContext);\n\n\t\t\ttypedef int (*PFNGLXSWAPINTERVALMESA)(int interval);\n\t\t\tPFNGLXSWAPINTERVALMESA glXSwapIntervalMESA = NULL;\n\n\t\t\tglXSwapIntervalMESA = (PFNGLXSWAPINTERVALMESA)glXGetProcAddress((unsigned char*)\"glXSwapIntervalMESA\");\n\t\t\tif( !glXSwapIntervalMESA )\n\t\t\t{\n\t\t\t\t return RETURN_VALUE_KO;\n\t\t\t}\n\n\t\t\tglXSwapIntervalMESA(0);\n\n\t\t\treturn RETURN_VALUE_OK;\n\t\t}\n\n\t\tvoid LinuxEventLoop::DestroyDisplay()\n\t\t{\n\t\t\tif(m_glContext)\n\t\t\t{\n\t\t\t\tglXMakeCurrent(m_display, None, NULL);\n\t\t\t\tglXDestroyContext(m_display, m_glContext);\n\t\t\t\tm_glContext = NULL;\n\t\t\t}\n\n\t\t\tif(m_isFullscreen)\n\t\t\t{\n\t\t\t\tXF86VidModeSwitchToMode(m_display, m_screenID, &m_XF86DeskMode);\n\t\t\t\tXF86VidModeSetViewPort(m_display, m_screenID, 0, 0);\n\t\t\t}\n\n\t\t\tXCloseDisplay(m_display);\n\t\t}\n\n\t\tvoid LinuxEventLoop::ProcessEvents()\n\t\t{\n\t\t\tGlobal::pContext->pTimeService->Update();\n\t\t\tGlobal::pContext->pInputService->Update();\n\n\t\t\tXEvent event;\n\n\t\t\tint width, height;\n\n\t\t\twhile (XPending(m_display) > 0)\n\t\t\t{\n\t\t\t\tXNextEvent(m_display, &event);\n\t\t\t\tswitch (event.type)\n\t\t\t\t{\n\t\t\t\t\tcase Expose:\n\t\t\t\t\tbreak;\n\t\t\t\t\tcase ConfigureNotify:\n\t\t\t\t\t\twidth = event.xconfigure.width;\n\t\t\t\t\t\theight = event.xconfigure.height;\n\t\t\t\t\t\tif(width != m_newWidth || height != m_newHeight)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tm_newWidth = width;\n\t\t\t\t\t\t\tm_newHeight = height;\n\t\t\t\t\t\t\tm_isResizing = true;\n\t\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\t\tcase KeyPress:\n\t\t\t\t\t\tGlobal::pContext->pInputService->GetKeyboard()->HandleKeyDown(Global::pContext->pInputService->GetKeyboard()->TranslateCode(XLookupKeysym(&event.xkey,0)));\n\t\t\t\t\tbreak;\n\t\t\t\t\tcase KeyRelease:\n\t\t\t\t\t\tGlobal::pContext->pInputService->GetKeyboard()->HandleKeyUp(Global::pContext->pInputService->GetKeyboard()->TranslateCode(XLookupKeysym(&event.xkey,0)));\n\t\t\t\t\tbreak;\n\t\t\t\t\tcase ClientMessage:\n\t\t\t\t\t\tif (string(XGetAtomName(m_display, event.xclient.message_type)) == string(\"WM_PROTOCOLS\"))\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tm_isRunning = false;\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\t\tdefault:\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (Global::pContext->pInputService->GetMouse()->ButtonUp(Input::MouseButton::MBC_LEFT) == 1)\n\t\t\t{\n\t\t\t\tif(m_isResizing)\n\t\t\t\t{\n\t\t\t\t\tif (m_newWidth != m_width || m_newHeight != m_height)\n\t\t\t\t\t{\n\t\t\t\t\t\tm_width = m_newWidth;\n\t\t\t\t\t\tm_height = m_newHeight;\n\t\t\t\t\t\tm_pApplication->onDeactivate();\n\t\t\t\t\t\tGraphics::Render::SetScreenSize(m_width,m_height);\n\t\t\t\t\t\tm_pApplication->onActivate();\n\t\t\t\t\t}\n\t\t\t\t\tm_isResizing = false;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tvoid LinuxEventLoop::SwapBuffers()\n\t\t{\n\t\t\tPROFILE_BEGIN(\"SwapBuffers\");\n\t\t\tglXSwapBuffers(m_display, m_XWindow);\n\t\t\tPROFILE_END();\n\t\t}\n\t}\n}\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2011 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"base\/command_line.h\"\n#include \"base\/memory\/scoped_ptr.h\"\n#include \"base\/message_loop.h\"\n#include \"chrome\/browser\/automation\/ui_controls.h\"\n#include \"chrome\/browser\/chromeos\/cros\/cros_in_process_browser_test.h\"\n#include \"chrome\/browser\/chromeos\/cros\/mock_input_method_library.h\"\n#include \"chrome\/browser\/chromeos\/cros\/mock_screen_lock_library.h\"\n#include \"chrome\/browser\/chromeos\/login\/mock_authenticator.h\"\n#include \"chrome\/browser\/chromeos\/login\/screen_locker.h\"\n#include \"chrome\/browser\/chromeos\/login\/screen_locker_tester.h\"\n#include \"chrome\/browser\/chromeos\/login\/user_manager.h\"\n#include \"chrome\/browser\/profiles\/profile_manager.h\"\n#include \"chrome\/browser\/ui\/browser.h\"\n#include \"chrome\/browser\/ui\/browser_window.h\"\n#include \"chrome\/browser\/ui\/views\/browser_dialogs.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/test\/ui_test_utils.h\"\n#include \"content\/common\/notification_service.h\"\n#include \"content\/common\/notification_type.h\"\n#include \"testing\/gmock\/include\/gmock\/gmock.h\"\n#include \"testing\/gtest\/include\/gtest\/gtest.h\"\n#include \"views\/controls\/textfield\/textfield.h\"\n#include \"views\/window\/window_gtk.h\"\n\nnamespace {\n\n\/\/ An object that wait for lock state and fullscreen state.\nclass Waiter : public NotificationObserver {\n public:\n explicit Waiter(Browser* browser)\n : browser_(browser),\n running_(false) {\n registrar_.Add(this,\n NotificationType::SCREEN_LOCK_STATE_CHANGED,\n NotificationService::AllSources());\n handler_id_ = g_signal_connect(\n G_OBJECT(browser_->window()->GetNativeHandle()),\n \"window-state-event\",\n G_CALLBACK(OnWindowStateEventThunk),\n this);\n }\n\n ~Waiter() {\n g_signal_handler_disconnect(\n G_OBJECT(browser_->window()->GetNativeHandle()),\n handler_id_);\n }\n\n virtual void Observe(NotificationType type,\n const NotificationSource& source,\n const NotificationDetails& details) {\n DCHECK(type == NotificationType::SCREEN_LOCK_STATE_CHANGED);\n if (running_)\n MessageLoop::current()->Quit();\n }\n\n \/\/ Wait until the two conditions are met.\n void Wait(bool locker_state, bool fullscreen) {\n running_ = true;\n scoped_ptr<chromeos::test::ScreenLockerTester>\n tester(chromeos::ScreenLocker::GetTester());\n while (tester->IsLocked() != locker_state ||\n browser_->window()->IsFullscreen() != fullscreen) {\n ui_test_utils::RunMessageLoop();\n }\n \/\/ Make sure all pending tasks are executed.\n ui_test_utils::RunAllPendingInMessageLoop();\n running_ = false;\n }\n\n CHROMEGTK_CALLBACK_1(Waiter, gboolean, OnWindowStateEvent,\n GdkEventWindowState*);\n\n private:\n Browser* browser_;\n gulong handler_id_;\n NotificationRegistrar registrar_;\n\n \/\/ Are we currently running the message loop?\n bool running_;\n\n DISALLOW_COPY_AND_ASSIGN(Waiter);\n};\n\ngboolean Waiter::OnWindowStateEvent(GtkWidget* widget,\n GdkEventWindowState* event) {\n MessageLoop::current()->Quit();\n return false;\n}\n\n} \/\/ namespace\n\nnamespace chromeos {\n\nclass ScreenLockerTest : public CrosInProcessBrowserTest {\n public:\n ScreenLockerTest() : mock_screen_lock_library_(NULL),\n mock_input_method_library_(NULL) {\n }\n\n protected:\n MockScreenLockLibrary *mock_screen_lock_library_;\n MockInputMethodLibrary *mock_input_method_library_;\n\n \/\/ Test the no password mode with different unlock scheme given by\n \/\/ |unlock| function.\n void TestNoPassword(void (unlock)(views::Widget*)) {\n EXPECT_CALL(*mock_screen_lock_library_, NotifyScreenUnlockRequested())\n .Times(1)\n .RetiresOnSaturation();\n EXPECT_CALL(*mock_screen_lock_library_, NotifyScreenLockCompleted())\n .Times(1)\n .RetiresOnSaturation();\n UserManager::Get()->OffTheRecordUserLoggedIn();\n ScreenLocker::Show();\n scoped_ptr<test::ScreenLockerTester> tester(ScreenLocker::GetTester());\n tester->EmulateWindowManagerReady();\n if (!chromeos::ScreenLocker::GetTester()->IsLocked())\n ui_test_utils::WaitForNotification(\n NotificationType::SCREEN_LOCK_STATE_CHANGED);\n EXPECT_TRUE(tester->IsLocked());\n tester->InjectMockAuthenticator(\"\", \"\");\n\n unlock(tester->GetWidget());\n\n ui_test_utils::RunAllPendingInMessageLoop();\n EXPECT_TRUE(tester->IsLocked());\n\n \/\/ Emulate LockScreen request from PowerManager (via SessionManager).\n ScreenLocker::Hide();\n ui_test_utils::RunAllPendingInMessageLoop();\n EXPECT_FALSE(tester->IsLocked());\n }\n\n void LockScreenWithUser(test::ScreenLockerTester* tester,\n const std::string& user) {\n UserManager::Get()->UserLoggedIn(user);\n ScreenLocker::Show();\n tester->EmulateWindowManagerReady();\n if (!tester->IsLocked()) {\n ui_test_utils::WaitForNotification(\n NotificationType::SCREEN_LOCK_STATE_CHANGED);\n }\n EXPECT_TRUE(tester->IsLocked());\n }\n\n private:\n virtual void SetUpInProcessBrowserTestFixture() {\n cros_mock_->InitStatusAreaMocks();\n cros_mock_->InitMockScreenLockLibrary();\n mock_screen_lock_library_ = cros_mock_->mock_screen_lock_library();\n mock_input_method_library_ = cros_mock_->mock_input_method_library();\n EXPECT_CALL(*mock_screen_lock_library_, AddObserver(testing::_))\n .Times(1)\n .RetiresOnSaturation();\n EXPECT_CALL(*mock_screen_lock_library_, NotifyScreenUnlockCompleted())\n .Times(1)\n .RetiresOnSaturation();\n \/\/ Expectations for the status are on the screen lock window.\n cros_mock_->SetStatusAreaMocksExpectations();\n \/\/ Expectations for the status area on the browser window.\n cros_mock_->SetStatusAreaMocksExpectations();\n }\n\n virtual void SetUpCommandLine(CommandLine* command_line) {\n command_line->AppendSwitchASCII(switches::kLoginProfile, \"user\");\n command_line->AppendSwitch(switches::kNoFirstRun);\n }\n\n DISALLOW_COPY_AND_ASSIGN(ScreenLockerTest);\n};\n\nIN_PROC_BROWSER_TEST_F(ScreenLockerTest, TestBasic) {\n EXPECT_CALL(*mock_input_method_library_, GetNumActiveInputMethods())\n .Times(1)\n .WillRepeatedly((testing::Return(0)))\n .RetiresOnSaturation();\n EXPECT_CALL(*mock_screen_lock_library_, NotifyScreenUnlockRequested())\n .Times(1)\n .RetiresOnSaturation();\n EXPECT_CALL(*mock_screen_lock_library_, NotifyScreenLockCompleted())\n .Times(1)\n .RetiresOnSaturation();\n UserManager::Get()->UserLoggedIn(\"user\");\n ScreenLocker::Show();\n scoped_ptr<test::ScreenLockerTester> tester(ScreenLocker::GetTester());\n tester->EmulateWindowManagerReady();\n if (!chromeos::ScreenLocker::GetTester()->IsLocked())\n ui_test_utils::WaitForNotification(\n NotificationType::SCREEN_LOCK_STATE_CHANGED);\n\n \/\/ Test to make sure that the widget is actually appearing and is of\n \/\/ reasonable size, preventing a regression of\n \/\/ http:\/\/code.google.com\/p\/chromium-os\/issues\/detail?id=5987\n gfx::Rect lock_bounds = tester->GetChildWidget()->GetWindowScreenBounds();\n EXPECT_GT(lock_bounds.width(), 10);\n EXPECT_GT(lock_bounds.height(), 10);\n\n tester->InjectMockAuthenticator(\"user\", \"pass\");\n EXPECT_TRUE(tester->IsLocked());\n tester->EnterPassword(\"fail\");\n ui_test_utils::RunAllPendingInMessageLoop();\n EXPECT_TRUE(tester->IsLocked());\n tester->EnterPassword(\"pass\");\n ui_test_utils::RunAllPendingInMessageLoop();\n \/\/ Successful authentication simply send a unlock request to PowerManager.\n EXPECT_TRUE(tester->IsLocked());\n\n \/\/ Emulate LockScreen request from PowerManager (via SessionManager).\n \/\/ TODO(oshima): Find out better way to handle this in mock.\n ScreenLocker::Hide();\n ui_test_utils::RunAllPendingInMessageLoop();\n EXPECT_FALSE(tester->IsLocked());\n}\n\nIN_PROC_BROWSER_TEST_F(ScreenLockerTest, TestFullscreenExit) {\n EXPECT_CALL(*mock_screen_lock_library_, NotifyScreenUnlockRequested())\n .Times(1)\n .RetiresOnSaturation();\n EXPECT_CALL(*mock_screen_lock_library_, NotifyScreenLockCompleted())\n .Times(1)\n .RetiresOnSaturation();\n scoped_ptr<test::ScreenLockerTester> tester(ScreenLocker::GetTester());\n {\n Waiter waiter(browser());\n browser()->ToggleFullscreenMode();\n waiter.Wait(false \/* not locked *\/, true \/* full screen *\/);\n EXPECT_TRUE(browser()->window()->IsFullscreen());\n EXPECT_FALSE(tester->IsLocked());\n }\n {\n Waiter waiter(browser());\n UserManager::Get()->UserLoggedIn(\"user\");\n ScreenLocker::Show();\n tester->EmulateWindowManagerReady();\n waiter.Wait(true \/* locked *\/, false \/* full screen *\/);\n EXPECT_FALSE(browser()->window()->IsFullscreen());\n EXPECT_TRUE(tester->IsLocked());\n }\n tester->InjectMockAuthenticator(\"user\", \"pass\");\n tester->EnterPassword(\"pass\");\n ui_test_utils::RunAllPendingInMessageLoop();\n ScreenLocker::Hide();\n ui_test_utils::RunAllPendingInMessageLoop();\n EXPECT_FALSE(tester->IsLocked());\n}\n\nvoid MouseMove(views::Widget* widget) {\n ui_controls::SendMouseMove(10, 10);\n}\n\nIN_PROC_BROWSER_TEST_F(ScreenLockerTest, FLAKY_TestNoPasswordWithMouseMove) {\n TestNoPassword(MouseMove);\n}\n\nvoid MouseClick(views::Widget* widget) {\n ui_controls::SendMouseClick(ui_controls::RIGHT);\n}\n\nIN_PROC_BROWSER_TEST_F(ScreenLockerTest, FLAKY_TestNoPasswordWithMouseClick) {\n TestNoPassword(MouseClick);\n}\n\nvoid KeyPress(views::Widget* widget) {\n ui_controls::SendKeyPress(GTK_WINDOW(widget->GetNativeView()),\n ui::VKEY_SPACE, false, false, false, false);\n}\n\nIN_PROC_BROWSER_TEST_F(ScreenLockerTest, FLAKY_TestNoPasswordWithKeyPress) {\n TestNoPassword(KeyPress);\n}\n\n\/\/ See http:\/\/crbug.com\/78764.\nIN_PROC_BROWSER_TEST_F(ScreenLockerTest, DISABLED_TestShowTwice) {\n EXPECT_CALL(*mock_screen_lock_library_, NotifyScreenLockCompleted())\n .Times(2)\n .RetiresOnSaturation();\n scoped_ptr<test::ScreenLockerTester> tester(ScreenLocker::GetTester());\n LockScreenWithUser(tester.get(), \"user\");\n\n \/\/ Ensure there's a profile or this test crashes.\n ProfileManager::GetDefaultProfile();\n\n \/\/ Calling Show again simply send LockCompleted signal.\n ScreenLocker::Show();\n EXPECT_TRUE(tester->IsLocked());\n\n \/\/ Close the locker to match expectations.\n ScreenLocker::Hide();\n ui_test_utils::RunAllPendingInMessageLoop();\n EXPECT_FALSE(tester->IsLocked());\n}\n\n\/\/ See http:\/\/crbug.com\/78764.\nIN_PROC_BROWSER_TEST_F(ScreenLockerTest, DISABLED_TestEscape) {\n EXPECT_CALL(*mock_screen_lock_library_, NotifyScreenLockCompleted())\n .Times(1)\n .RetiresOnSaturation();\n scoped_ptr<test::ScreenLockerTester> tester(ScreenLocker::GetTester());\n LockScreenWithUser(tester.get(), \"user\");\n\n \/\/ Ensure there's a profile or this test crashes.\n ProfileManager::GetDefaultProfile();\n\n tester->SetPassword(\"password\");\n EXPECT_EQ(\"password\", tester->GetPassword());\n \/\/ Escape clears the password.\n ui_controls::SendKeyPress(GTK_WINDOW(tester->GetWidget()->GetNativeView()),\n ui::VKEY_ESCAPE, false, false, false, false);\n ui_test_utils::RunAllPendingInMessageLoop();\n EXPECT_EQ(\"\", tester->GetPassword());\n\n \/\/ Close the locker to match expectations.\n ScreenLocker::Hide();\n ui_test_utils::RunAllPendingInMessageLoop();\n EXPECT_FALSE(tester->IsLocked());\n}\n\n} \/\/ namespace chromeos\n<commit_msg>Disable crashing tests, my previous checkin to mark them flaky did not help.<commit_after>\/\/ Copyright (c) 2011 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"base\/command_line.h\"\n#include \"base\/memory\/scoped_ptr.h\"\n#include \"base\/message_loop.h\"\n#include \"chrome\/browser\/automation\/ui_controls.h\"\n#include \"chrome\/browser\/chromeos\/cros\/cros_in_process_browser_test.h\"\n#include \"chrome\/browser\/chromeos\/cros\/mock_input_method_library.h\"\n#include \"chrome\/browser\/chromeos\/cros\/mock_screen_lock_library.h\"\n#include \"chrome\/browser\/chromeos\/login\/mock_authenticator.h\"\n#include \"chrome\/browser\/chromeos\/login\/screen_locker.h\"\n#include \"chrome\/browser\/chromeos\/login\/screen_locker_tester.h\"\n#include \"chrome\/browser\/chromeos\/login\/user_manager.h\"\n#include \"chrome\/browser\/profiles\/profile_manager.h\"\n#include \"chrome\/browser\/ui\/browser.h\"\n#include \"chrome\/browser\/ui\/browser_window.h\"\n#include \"chrome\/browser\/ui\/views\/browser_dialogs.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/test\/ui_test_utils.h\"\n#include \"content\/common\/notification_service.h\"\n#include \"content\/common\/notification_type.h\"\n#include \"testing\/gmock\/include\/gmock\/gmock.h\"\n#include \"testing\/gtest\/include\/gtest\/gtest.h\"\n#include \"views\/controls\/textfield\/textfield.h\"\n#include \"views\/window\/window_gtk.h\"\n\nnamespace {\n\n\/\/ An object that wait for lock state and fullscreen state.\nclass Waiter : public NotificationObserver {\n public:\n explicit Waiter(Browser* browser)\n : browser_(browser),\n running_(false) {\n registrar_.Add(this,\n NotificationType::SCREEN_LOCK_STATE_CHANGED,\n NotificationService::AllSources());\n handler_id_ = g_signal_connect(\n G_OBJECT(browser_->window()->GetNativeHandle()),\n \"window-state-event\",\n G_CALLBACK(OnWindowStateEventThunk),\n this);\n }\n\n ~Waiter() {\n g_signal_handler_disconnect(\n G_OBJECT(browser_->window()->GetNativeHandle()),\n handler_id_);\n }\n\n virtual void Observe(NotificationType type,\n const NotificationSource& source,\n const NotificationDetails& details) {\n DCHECK(type == NotificationType::SCREEN_LOCK_STATE_CHANGED);\n if (running_)\n MessageLoop::current()->Quit();\n }\n\n \/\/ Wait until the two conditions are met.\n void Wait(bool locker_state, bool fullscreen) {\n running_ = true;\n scoped_ptr<chromeos::test::ScreenLockerTester>\n tester(chromeos::ScreenLocker::GetTester());\n while (tester->IsLocked() != locker_state ||\n browser_->window()->IsFullscreen() != fullscreen) {\n ui_test_utils::RunMessageLoop();\n }\n \/\/ Make sure all pending tasks are executed.\n ui_test_utils::RunAllPendingInMessageLoop();\n running_ = false;\n }\n\n CHROMEGTK_CALLBACK_1(Waiter, gboolean, OnWindowStateEvent,\n GdkEventWindowState*);\n\n private:\n Browser* browser_;\n gulong handler_id_;\n NotificationRegistrar registrar_;\n\n \/\/ Are we currently running the message loop?\n bool running_;\n\n DISALLOW_COPY_AND_ASSIGN(Waiter);\n};\n\ngboolean Waiter::OnWindowStateEvent(GtkWidget* widget,\n GdkEventWindowState* event) {\n MessageLoop::current()->Quit();\n return false;\n}\n\n} \/\/ namespace\n\nnamespace chromeos {\n\nclass ScreenLockerTest : public CrosInProcessBrowserTest {\n public:\n ScreenLockerTest() : mock_screen_lock_library_(NULL),\n mock_input_method_library_(NULL) {\n }\n\n protected:\n MockScreenLockLibrary *mock_screen_lock_library_;\n MockInputMethodLibrary *mock_input_method_library_;\n\n \/\/ Test the no password mode with different unlock scheme given by\n \/\/ |unlock| function.\n void TestNoPassword(void (unlock)(views::Widget*)) {\n EXPECT_CALL(*mock_screen_lock_library_, NotifyScreenUnlockRequested())\n .Times(1)\n .RetiresOnSaturation();\n EXPECT_CALL(*mock_screen_lock_library_, NotifyScreenLockCompleted())\n .Times(1)\n .RetiresOnSaturation();\n UserManager::Get()->OffTheRecordUserLoggedIn();\n ScreenLocker::Show();\n scoped_ptr<test::ScreenLockerTester> tester(ScreenLocker::GetTester());\n tester->EmulateWindowManagerReady();\n if (!chromeos::ScreenLocker::GetTester()->IsLocked())\n ui_test_utils::WaitForNotification(\n NotificationType::SCREEN_LOCK_STATE_CHANGED);\n EXPECT_TRUE(tester->IsLocked());\n tester->InjectMockAuthenticator(\"\", \"\");\n\n unlock(tester->GetWidget());\n\n ui_test_utils::RunAllPendingInMessageLoop();\n EXPECT_TRUE(tester->IsLocked());\n\n \/\/ Emulate LockScreen request from PowerManager (via SessionManager).\n ScreenLocker::Hide();\n ui_test_utils::RunAllPendingInMessageLoop();\n EXPECT_FALSE(tester->IsLocked());\n }\n\n void LockScreenWithUser(test::ScreenLockerTester* tester,\n const std::string& user) {\n UserManager::Get()->UserLoggedIn(user);\n ScreenLocker::Show();\n tester->EmulateWindowManagerReady();\n if (!tester->IsLocked()) {\n ui_test_utils::WaitForNotification(\n NotificationType::SCREEN_LOCK_STATE_CHANGED);\n }\n EXPECT_TRUE(tester->IsLocked());\n }\n\n private:\n virtual void SetUpInProcessBrowserTestFixture() {\n cros_mock_->InitStatusAreaMocks();\n cros_mock_->InitMockScreenLockLibrary();\n mock_screen_lock_library_ = cros_mock_->mock_screen_lock_library();\n mock_input_method_library_ = cros_mock_->mock_input_method_library();\n EXPECT_CALL(*mock_screen_lock_library_, AddObserver(testing::_))\n .Times(1)\n .RetiresOnSaturation();\n EXPECT_CALL(*mock_screen_lock_library_, NotifyScreenUnlockCompleted())\n .Times(1)\n .RetiresOnSaturation();\n \/\/ Expectations for the status are on the screen lock window.\n cros_mock_->SetStatusAreaMocksExpectations();\n \/\/ Expectations for the status area on the browser window.\n cros_mock_->SetStatusAreaMocksExpectations();\n }\n\n virtual void SetUpCommandLine(CommandLine* command_line) {\n command_line->AppendSwitchASCII(switches::kLoginProfile, \"user\");\n command_line->AppendSwitch(switches::kNoFirstRun);\n }\n\n DISALLOW_COPY_AND_ASSIGN(ScreenLockerTest);\n};\n\nIN_PROC_BROWSER_TEST_F(ScreenLockerTest, TestBasic) {\n EXPECT_CALL(*mock_input_method_library_, GetNumActiveInputMethods())\n .Times(1)\n .WillRepeatedly((testing::Return(0)))\n .RetiresOnSaturation();\n EXPECT_CALL(*mock_screen_lock_library_, NotifyScreenUnlockRequested())\n .Times(1)\n .RetiresOnSaturation();\n EXPECT_CALL(*mock_screen_lock_library_, NotifyScreenLockCompleted())\n .Times(1)\n .RetiresOnSaturation();\n UserManager::Get()->UserLoggedIn(\"user\");\n ScreenLocker::Show();\n scoped_ptr<test::ScreenLockerTester> tester(ScreenLocker::GetTester());\n tester->EmulateWindowManagerReady();\n if (!chromeos::ScreenLocker::GetTester()->IsLocked())\n ui_test_utils::WaitForNotification(\n NotificationType::SCREEN_LOCK_STATE_CHANGED);\n\n \/\/ Test to make sure that the widget is actually appearing and is of\n \/\/ reasonable size, preventing a regression of\n \/\/ http:\/\/code.google.com\/p\/chromium-os\/issues\/detail?id=5987\n gfx::Rect lock_bounds = tester->GetChildWidget()->GetWindowScreenBounds();\n EXPECT_GT(lock_bounds.width(), 10);\n EXPECT_GT(lock_bounds.height(), 10);\n\n tester->InjectMockAuthenticator(\"user\", \"pass\");\n EXPECT_TRUE(tester->IsLocked());\n tester->EnterPassword(\"fail\");\n ui_test_utils::RunAllPendingInMessageLoop();\n EXPECT_TRUE(tester->IsLocked());\n tester->EnterPassword(\"pass\");\n ui_test_utils::RunAllPendingInMessageLoop();\n \/\/ Successful authentication simply send a unlock request to PowerManager.\n EXPECT_TRUE(tester->IsLocked());\n\n \/\/ Emulate LockScreen request from PowerManager (via SessionManager).\n \/\/ TODO(oshima): Find out better way to handle this in mock.\n ScreenLocker::Hide();\n ui_test_utils::RunAllPendingInMessageLoop();\n EXPECT_FALSE(tester->IsLocked());\n}\n\nIN_PROC_BROWSER_TEST_F(ScreenLockerTest, TestFullscreenExit) {\n EXPECT_CALL(*mock_screen_lock_library_, NotifyScreenUnlockRequested())\n .Times(1)\n .RetiresOnSaturation();\n EXPECT_CALL(*mock_screen_lock_library_, NotifyScreenLockCompleted())\n .Times(1)\n .RetiresOnSaturation();\n scoped_ptr<test::ScreenLockerTester> tester(ScreenLocker::GetTester());\n {\n Waiter waiter(browser());\n browser()->ToggleFullscreenMode();\n waiter.Wait(false \/* not locked *\/, true \/* full screen *\/);\n EXPECT_TRUE(browser()->window()->IsFullscreen());\n EXPECT_FALSE(tester->IsLocked());\n }\n {\n Waiter waiter(browser());\n UserManager::Get()->UserLoggedIn(\"user\");\n ScreenLocker::Show();\n tester->EmulateWindowManagerReady();\n waiter.Wait(true \/* locked *\/, false \/* full screen *\/);\n EXPECT_FALSE(browser()->window()->IsFullscreen());\n EXPECT_TRUE(tester->IsLocked());\n }\n tester->InjectMockAuthenticator(\"user\", \"pass\");\n tester->EnterPassword(\"pass\");\n ui_test_utils::RunAllPendingInMessageLoop();\n ScreenLocker::Hide();\n ui_test_utils::RunAllPendingInMessageLoop();\n EXPECT_FALSE(tester->IsLocked());\n}\n\nvoid MouseMove(views::Widget* widget) {\n ui_controls::SendMouseMove(10, 10);\n}\n\nIN_PROC_BROWSER_TEST_F(ScreenLockerTest, DISABLED_TestNoPasswordWithMouseMove) {\n TestNoPassword(MouseMove);\n}\n\nvoid MouseClick(views::Widget* widget) {\n ui_controls::SendMouseClick(ui_controls::RIGHT);\n}\n\nIN_PROC_BROWSER_TEST_F(ScreenLockerTest,\n DISABLED_TestNoPasswordWithMouseClick) {\n TestNoPassword(MouseClick);\n}\n\nvoid KeyPress(views::Widget* widget) {\n ui_controls::SendKeyPress(GTK_WINDOW(widget->GetNativeView()),\n ui::VKEY_SPACE, false, false, false, false);\n}\n\nIN_PROC_BROWSER_TEST_F(ScreenLockerTest, DISABLED_TestNoPasswordWithKeyPress) {\n TestNoPassword(KeyPress);\n}\n\n\/\/ See http:\/\/crbug.com\/78764.\nIN_PROC_BROWSER_TEST_F(ScreenLockerTest, DISABLED_TestShowTwice) {\n EXPECT_CALL(*mock_screen_lock_library_, NotifyScreenLockCompleted())\n .Times(2)\n .RetiresOnSaturation();\n scoped_ptr<test::ScreenLockerTester> tester(ScreenLocker::GetTester());\n LockScreenWithUser(tester.get(), \"user\");\n\n \/\/ Ensure there's a profile or this test crashes.\n ProfileManager::GetDefaultProfile();\n\n \/\/ Calling Show again simply send LockCompleted signal.\n ScreenLocker::Show();\n EXPECT_TRUE(tester->IsLocked());\n\n \/\/ Close the locker to match expectations.\n ScreenLocker::Hide();\n ui_test_utils::RunAllPendingInMessageLoop();\n EXPECT_FALSE(tester->IsLocked());\n}\n\n\/\/ See http:\/\/crbug.com\/78764.\nIN_PROC_BROWSER_TEST_F(ScreenLockerTest, DISABLED_TestEscape) {\n EXPECT_CALL(*mock_screen_lock_library_, NotifyScreenLockCompleted())\n .Times(1)\n .RetiresOnSaturation();\n scoped_ptr<test::ScreenLockerTester> tester(ScreenLocker::GetTester());\n LockScreenWithUser(tester.get(), \"user\");\n\n \/\/ Ensure there's a profile or this test crashes.\n ProfileManager::GetDefaultProfile();\n\n tester->SetPassword(\"password\");\n EXPECT_EQ(\"password\", tester->GetPassword());\n \/\/ Escape clears the password.\n ui_controls::SendKeyPress(GTK_WINDOW(tester->GetWidget()->GetNativeView()),\n ui::VKEY_ESCAPE, false, false, false, false);\n ui_test_utils::RunAllPendingInMessageLoop();\n EXPECT_EQ(\"\", tester->GetPassword());\n\n \/\/ Close the locker to match expectations.\n ScreenLocker::Hide();\n ui_test_utils::RunAllPendingInMessageLoop();\n EXPECT_FALSE(tester->IsLocked());\n}\n\n} \/\/ namespace chromeos\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2008 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include <vector>\n\n#include \"base\/command_line.h\"\n#include \"base\/file_path.h\"\n#include \"base\/file_util.h\"\n#include \"base\/path_service.h\"\n#include \"chrome\/browser\/browser.h\"\n#include \"chrome\/browser\/extensions\/extensions_service.h\"\n#include \"chrome\/browser\/extensions\/user_script_master.h\"\n#include \"chrome\/browser\/profile.h\"\n#include \"chrome\/browser\/tab_contents\/tab_contents.h\"\n#include \"chrome\/common\/chrome_paths.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/common\/notification_details.h\"\n#include \"chrome\/common\/notification_observer.h\"\n#include \"chrome\/common\/notification_registrar.h\"\n#include \"chrome\/common\/notification_service.h\"\n#include \"chrome\/common\/notification_type.h\"\n#include \"chrome\/test\/in_process_browser_test.h\"\n#include \"chrome\/test\/ui_test_utils.h\"\n#include \"net\/base\/net_util.h\"\n\n\/\/ This file contains high-level startup tests for the extensions system. We've\n\/\/ had many silly bugs where command line flags did not get propagated correctly\n\/\/ into the services, so we didn't start correctly.\n\nclass ExtensionStartupTestBase : public InProcessBrowserTest {\n public:\n ExtensionStartupTestBase() : enable_extensions_(false) {\n }\n\n protected:\n \/\/ InProcessBrowserTest\n virtual void SetUpCommandLine(CommandLine* command_line) {\n EnableDOMAutomation();\n\n FilePath profile_dir;\n PathService::Get(chrome::DIR_USER_DATA, &profile_dir);\n profile_dir = profile_dir.AppendASCII(\"Default\");\n file_util::CreateDirectory(profile_dir);\n\n preferences_file_ = profile_dir.AppendASCII(\"Preferences\");\n user_scripts_dir_ = profile_dir.AppendASCII(\"User Scripts\");\n extensions_dir_ = profile_dir.AppendASCII(\"Extensions\");\n\n if (enable_extensions_) {\n FilePath src_dir;\n PathService::Get(chrome::DIR_TEST_DATA, &src_dir);\n src_dir = src_dir.AppendASCII(\"extensions\").AppendASCII(\"good\");\n\n file_util::CopyFile(src_dir.AppendASCII(\"Preferences\"),\n preferences_file_);\n file_util::CopyDirectory(src_dir.AppendASCII(\"Extensions\"),\n profile_dir, true); \/\/ recursive\n } else {\n command_line->AppendSwitch(switches::kDisableExtensions);\n }\n\n if (!load_extension_.value().empty()) {\n command_line->AppendSwitchWithValue(switches::kLoadExtension,\n load_extension_.ToWStringHack());\n command_line->AppendSwitch(switches::kDisableExtensionsFileAccessCheck);\n }\n }\n\n virtual void TearDown() {\n EXPECT_TRUE(file_util::Delete(preferences_file_, false));\n\n \/\/ TODO(phajdan.jr): Check return values of the functions below, carefully.\n file_util::Delete(user_scripts_dir_, true);\n file_util::Delete(extensions_dir_, true);\n }\n\n void WaitForServicesToStart(int num_expected_extensions,\n bool expect_extensions_enabled) {\n ExtensionsService* service = browser()->profile()->GetExtensionsService();\n if (!service->is_ready())\n ui_test_utils::WaitForNotification(NotificationType::EXTENSIONS_READY);\n ASSERT_TRUE(service->is_ready());\n\n ASSERT_EQ(static_cast<uint32>(num_expected_extensions),\n service->extensions()->size());\n ASSERT_EQ(expect_extensions_enabled, service->extensions_enabled());\n\n UserScriptMaster* master = browser()->profile()->GetUserScriptMaster();\n if (!master->ScriptsReady()) {\n ui_test_utils::WaitForNotification(\n NotificationType::USER_SCRIPTS_UPDATED);\n }\n ASSERT_TRUE(master->ScriptsReady());\n }\n\n void TestInjection(bool expect_css, bool expect_script) {\n \/\/ Load a page affected by the content script and test to see the effect.\n FilePath test_file;\n PathService::Get(chrome::DIR_TEST_DATA, &test_file);\n test_file = test_file.AppendASCII(\"extensions\")\n .AppendASCII(\"test_file.html\");\n\n ui_test_utils::NavigateToURL(browser(), net::FilePathToFileURL(test_file));\n\n bool result = false;\n ui_test_utils::ExecuteJavaScriptAndExtractBool(\n browser()->GetSelectedTabContents()->render_view_host(), L\"\",\n L\"window.domAutomationController.send(\"\n L\"document.defaultView.getComputedStyle(document.body, null).\"\n L\"getPropertyValue('background-color') == 'rgb(245, 245, 220)')\",\n &result);\n EXPECT_EQ(expect_css, result);\n\n result = false;\n ui_test_utils::ExecuteJavaScriptAndExtractBool(\n browser()->GetSelectedTabContents()->render_view_host(), L\"\",\n L\"window.domAutomationController.send(document.title == 'Modified')\",\n &result);\n EXPECT_EQ(expect_script, result);\n }\n\n FilePath preferences_file_;\n FilePath extensions_dir_;\n FilePath user_scripts_dir_;\n bool enable_extensions_;\n FilePath load_extension_;\n};\n\n\n\/\/ ExtensionsStartupTest\n\/\/ Ensures that we can startup the browser with --enable-extensions and some\n\/\/ extensions installed and see them run and do basic things.\n\nclass ExtensionsStartupTest : public ExtensionStartupTestBase {\n public:\n ExtensionsStartupTest() {\n enable_extensions_ = true;\n }\n};\n\nIN_PROC_BROWSER_TEST_F(ExtensionsStartupTest, Test) {\n WaitForServicesToStart(4, true); \/\/ 1 component extension and 3 others.\n TestInjection(true, true);\n}\n\n\/\/ Tests that disallowing file access on an extension prevents it from injecting\n\/\/ script into a page with a file URL.\nIN_PROC_BROWSER_TEST_F(ExtensionsStartupTest, NoFileAccess) {\n WaitForServicesToStart(4, true); \/\/ 1 component extension and 3 others.\n\n ExtensionsService* service = browser()->profile()->GetExtensionsService();\n for (size_t i = 0; i < service->extensions()->size(); ++i) {\n if (service->AllowFileAccess(service->extensions()->at(i))) {\n service->SetAllowFileAccess(service->extensions()->at(i), false);\n ui_test_utils::WaitForNotification(\n NotificationType::USER_SCRIPTS_UPDATED);\n }\n }\n\n TestInjection(false, false);\n}\n\n\/\/ ExtensionsLoadTest\n\/\/ Ensures that we can startup the browser with --load-extension and see them\n\/\/ run.\n\nclass ExtensionsLoadTest : public ExtensionStartupTestBase {\n public:\n ExtensionsLoadTest() {\n PathService::Get(chrome::DIR_TEST_DATA, &load_extension_);\n load_extension_ = load_extension_\n .AppendASCII(\"extensions\")\n .AppendASCII(\"good\")\n .AppendASCII(\"Extensions\")\n .AppendASCII(\"behllobkkfkfnphdnhnkndlbkcpglgmj\")\n .AppendASCII(\"1.0.0.0\");\n }\n};\n\n\/\/ Flaky (times out) on Mac\/Windows. http:\/\/crbug.com\/46301.\n#if defined(OS_MACOSX) || defined(OS_WIN)\n#define MAYBE_Test FLAKY_Test\n#else\n#define MAYBE_Test Test\n#endif\nIN_PROC_BROWSER_TEST_F(ExtensionsLoadTest, MAYBE_Test) {\n WaitForServicesToStart(1, false);\n TestInjection(true, true);\n}\n<commit_msg>Disable ExtensionsStartupTest.NoFileAccess on Mac.<commit_after>\/\/ Copyright (c) 2008 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include <vector>\n\n#include \"base\/command_line.h\"\n#include \"base\/file_path.h\"\n#include \"base\/file_util.h\"\n#include \"base\/path_service.h\"\n#include \"chrome\/browser\/browser.h\"\n#include \"chrome\/browser\/extensions\/extensions_service.h\"\n#include \"chrome\/browser\/extensions\/user_script_master.h\"\n#include \"chrome\/browser\/profile.h\"\n#include \"chrome\/browser\/tab_contents\/tab_contents.h\"\n#include \"chrome\/common\/chrome_paths.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/common\/notification_details.h\"\n#include \"chrome\/common\/notification_observer.h\"\n#include \"chrome\/common\/notification_registrar.h\"\n#include \"chrome\/common\/notification_service.h\"\n#include \"chrome\/common\/notification_type.h\"\n#include \"chrome\/test\/in_process_browser_test.h\"\n#include \"chrome\/test\/ui_test_utils.h\"\n#include \"net\/base\/net_util.h\"\n\n\/\/ This file contains high-level startup tests for the extensions system. We've\n\/\/ had many silly bugs where command line flags did not get propagated correctly\n\/\/ into the services, so we didn't start correctly.\n\nclass ExtensionStartupTestBase : public InProcessBrowserTest {\n public:\n ExtensionStartupTestBase() : enable_extensions_(false) {\n }\n\n protected:\n \/\/ InProcessBrowserTest\n virtual void SetUpCommandLine(CommandLine* command_line) {\n EnableDOMAutomation();\n\n FilePath profile_dir;\n PathService::Get(chrome::DIR_USER_DATA, &profile_dir);\n profile_dir = profile_dir.AppendASCII(\"Default\");\n file_util::CreateDirectory(profile_dir);\n\n preferences_file_ = profile_dir.AppendASCII(\"Preferences\");\n user_scripts_dir_ = profile_dir.AppendASCII(\"User Scripts\");\n extensions_dir_ = profile_dir.AppendASCII(\"Extensions\");\n\n if (enable_extensions_) {\n FilePath src_dir;\n PathService::Get(chrome::DIR_TEST_DATA, &src_dir);\n src_dir = src_dir.AppendASCII(\"extensions\").AppendASCII(\"good\");\n\n file_util::CopyFile(src_dir.AppendASCII(\"Preferences\"),\n preferences_file_);\n file_util::CopyDirectory(src_dir.AppendASCII(\"Extensions\"),\n profile_dir, true); \/\/ recursive\n } else {\n command_line->AppendSwitch(switches::kDisableExtensions);\n }\n\n if (!load_extension_.value().empty()) {\n command_line->AppendSwitchWithValue(switches::kLoadExtension,\n load_extension_.ToWStringHack());\n command_line->AppendSwitch(switches::kDisableExtensionsFileAccessCheck);\n }\n }\n\n virtual void TearDown() {\n EXPECT_TRUE(file_util::Delete(preferences_file_, false));\n\n \/\/ TODO(phajdan.jr): Check return values of the functions below, carefully.\n file_util::Delete(user_scripts_dir_, true);\n file_util::Delete(extensions_dir_, true);\n }\n\n void WaitForServicesToStart(int num_expected_extensions,\n bool expect_extensions_enabled) {\n ExtensionsService* service = browser()->profile()->GetExtensionsService();\n if (!service->is_ready())\n ui_test_utils::WaitForNotification(NotificationType::EXTENSIONS_READY);\n ASSERT_TRUE(service->is_ready());\n\n ASSERT_EQ(static_cast<uint32>(num_expected_extensions),\n service->extensions()->size());\n ASSERT_EQ(expect_extensions_enabled, service->extensions_enabled());\n\n UserScriptMaster* master = browser()->profile()->GetUserScriptMaster();\n if (!master->ScriptsReady()) {\n ui_test_utils::WaitForNotification(\n NotificationType::USER_SCRIPTS_UPDATED);\n }\n ASSERT_TRUE(master->ScriptsReady());\n }\n\n void TestInjection(bool expect_css, bool expect_script) {\n \/\/ Load a page affected by the content script and test to see the effect.\n FilePath test_file;\n PathService::Get(chrome::DIR_TEST_DATA, &test_file);\n test_file = test_file.AppendASCII(\"extensions\")\n .AppendASCII(\"test_file.html\");\n\n ui_test_utils::NavigateToURL(browser(), net::FilePathToFileURL(test_file));\n\n bool result = false;\n ui_test_utils::ExecuteJavaScriptAndExtractBool(\n browser()->GetSelectedTabContents()->render_view_host(), L\"\",\n L\"window.domAutomationController.send(\"\n L\"document.defaultView.getComputedStyle(document.body, null).\"\n L\"getPropertyValue('background-color') == 'rgb(245, 245, 220)')\",\n &result);\n EXPECT_EQ(expect_css, result);\n\n result = false;\n ui_test_utils::ExecuteJavaScriptAndExtractBool(\n browser()->GetSelectedTabContents()->render_view_host(), L\"\",\n L\"window.domAutomationController.send(document.title == 'Modified')\",\n &result);\n EXPECT_EQ(expect_script, result);\n }\n\n FilePath preferences_file_;\n FilePath extensions_dir_;\n FilePath user_scripts_dir_;\n bool enable_extensions_;\n FilePath load_extension_;\n};\n\n\n\/\/ ExtensionsStartupTest\n\/\/ Ensures that we can startup the browser with --enable-extensions and some\n\/\/ extensions installed and see them run and do basic things.\n\nclass ExtensionsStartupTest : public ExtensionStartupTestBase {\n public:\n ExtensionsStartupTest() {\n enable_extensions_ = true;\n }\n};\n\nIN_PROC_BROWSER_TEST_F(ExtensionsStartupTest, Test) {\n WaitForServicesToStart(4, true); \/\/ 1 component extension and 3 others.\n TestInjection(true, true);\n}\n\n\/\/ Sometimes times out on Mac. http:\/\/crbug.com\/48151\n#if defined(OS_MACOSX)\n#define MAYBE_NoFileAccess DISABLED_NoFileAccess\n#else\n#define MAYBE_NoFileAccess NoFileAccess\n#endif\n\/\/ Tests that disallowing file access on an extension prevents it from injecting\n\/\/ script into a page with a file URL.\nIN_PROC_BROWSER_TEST_F(ExtensionsStartupTest, MAYBE_NoFileAccess) {\n WaitForServicesToStart(4, true); \/\/ 1 component extension and 3 others.\n\n ExtensionsService* service = browser()->profile()->GetExtensionsService();\n for (size_t i = 0; i < service->extensions()->size(); ++i) {\n if (service->AllowFileAccess(service->extensions()->at(i))) {\n service->SetAllowFileAccess(service->extensions()->at(i), false);\n ui_test_utils::WaitForNotification(\n NotificationType::USER_SCRIPTS_UPDATED);\n }\n }\n\n TestInjection(false, false);\n}\n\n\/\/ ExtensionsLoadTest\n\/\/ Ensures that we can startup the browser with --load-extension and see them\n\/\/ run.\n\nclass ExtensionsLoadTest : public ExtensionStartupTestBase {\n public:\n ExtensionsLoadTest() {\n PathService::Get(chrome::DIR_TEST_DATA, &load_extension_);\n load_extension_ = load_extension_\n .AppendASCII(\"extensions\")\n .AppendASCII(\"good\")\n .AppendASCII(\"Extensions\")\n .AppendASCII(\"behllobkkfkfnphdnhnkndlbkcpglgmj\")\n .AppendASCII(\"1.0.0.0\");\n }\n};\n\n\/\/ Flaky (times out) on Mac\/Windows. http:\/\/crbug.com\/46301.\n#if defined(OS_MACOSX) || defined(OS_WIN)\n#define MAYBE_Test FLAKY_Test\n#else\n#define MAYBE_Test Test\n#endif\nIN_PROC_BROWSER_TEST_F(ExtensionsLoadTest, MAYBE_Test) {\n WaitForServicesToStart(1, false);\n TestInjection(true, true);\n}\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: HTerminateListener.hxx,v $\n *\n * $Revision: 1.2 $\n *\n * last change: $Author: kz $ $Date: 2005-01-21 16:40:43 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the License); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an AS IS basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): Ocke Janssen\n *\n *\n ************************************************************************\/\n#ifndef CONNECTIVITY_HSQLDB_TERMINATELISTENER_HXX\n#define CONNECTIVITY_HSQLDB_TERMINATELISTENER_HXX\n\n#ifndef _CPPUHELPER_COMPBASE2_HXX_\n#include <cppuhelper\/compbase2.hxx>\n#endif\n#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_\n#include <com\/sun\/star\/lang\/XServiceInfo.hpp>\n#endif\n#ifndef _COM_SUN_STAR_FRAME_XTERMINATELISTENER_HPP_\n#include <com\/sun\/star\/frame\/XTerminateListener.hpp>\n#endif\n\n\/\/........................................................................\nnamespace connectivity\n{\n\/\/........................................................................\n\n namespace hsqldb\n {\n class ODriverDelegator;\n class OConnectionController : public ::cppu::WeakImplHelper2<\n ::com::sun::star::lang::XServiceInfo,\n ::com::sun::star::frame::XTerminateListener >\n {\n ODriverDelegator* m_pDriver;\n protected:\n virtual ~OConnectionController() {m_pDriver = NULL;}\n public:\n OConnectionController(ODriverDelegator* _pDriver) : m_pDriver(_pDriver){}\n\n \/\/ XServiceInfo\n virtual ::rtl::OUString SAL_CALL getImplementationName()\n throw ( ::com::sun::star::uno::RuntimeException );\n virtual sal_Bool SAL_CALL supportsService( const ::rtl::OUString& ServiceName )\n throw ( ::com::sun::star::uno::RuntimeException );\n virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames()\n throw ( ::com::sun::star::uno::RuntimeException );\n\n \/\/ XEventListener\n virtual void SAL_CALL disposing( const ::com::sun::star::lang::EventObject& Source )\n throw( ::com::sun::star::uno::RuntimeException );\n\n \/\/ XTerminateListener\n virtual void SAL_CALL queryTermination( const ::com::sun::star::lang::EventObject& aEvent )\n throw( ::com::sun::star::frame::TerminationVetoException, ::com::sun::star::uno::RuntimeException );\n virtual void SAL_CALL notifyTermination( const ::com::sun::star::lang::EventObject& aEvent )\n throw( ::com::sun::star::uno::RuntimeException );\n };\n }\n\/\/........................................................................\n} \/\/ namespace connectivity\n\/\/........................................................................\n#endif \/\/ CONNECTIVITY_HSQLDB_TERMINATELISTENER_HXX\n<commit_msg>INTEGRATION: CWS ooo19126 (1.2.94); FILE MERGED 2005\/09\/05 17:24:03 rt 1.2.94.1: #i54170# Change license header: remove SISSL<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: HTerminateListener.hxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: rt $ $Date: 2005-09-08 06:05:02 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n#ifndef CONNECTIVITY_HSQLDB_TERMINATELISTENER_HXX\n#define CONNECTIVITY_HSQLDB_TERMINATELISTENER_HXX\n\n#ifndef _CPPUHELPER_COMPBASE2_HXX_\n#include <cppuhelper\/compbase2.hxx>\n#endif\n#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_\n#include <com\/sun\/star\/lang\/XServiceInfo.hpp>\n#endif\n#ifndef _COM_SUN_STAR_FRAME_XTERMINATELISTENER_HPP_\n#include <com\/sun\/star\/frame\/XTerminateListener.hpp>\n#endif\n\n\/\/........................................................................\nnamespace connectivity\n{\n\/\/........................................................................\n\n namespace hsqldb\n {\n class ODriverDelegator;\n class OConnectionController : public ::cppu::WeakImplHelper2<\n ::com::sun::star::lang::XServiceInfo,\n ::com::sun::star::frame::XTerminateListener >\n {\n ODriverDelegator* m_pDriver;\n protected:\n virtual ~OConnectionController() {m_pDriver = NULL;}\n public:\n OConnectionController(ODriverDelegator* _pDriver) : m_pDriver(_pDriver){}\n\n \/\/ XServiceInfo\n virtual ::rtl::OUString SAL_CALL getImplementationName()\n throw ( ::com::sun::star::uno::RuntimeException );\n virtual sal_Bool SAL_CALL supportsService( const ::rtl::OUString& ServiceName )\n throw ( ::com::sun::star::uno::RuntimeException );\n virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames()\n throw ( ::com::sun::star::uno::RuntimeException );\n\n \/\/ XEventListener\n virtual void SAL_CALL disposing( const ::com::sun::star::lang::EventObject& Source )\n throw( ::com::sun::star::uno::RuntimeException );\n\n \/\/ XTerminateListener\n virtual void SAL_CALL queryTermination( const ::com::sun::star::lang::EventObject& aEvent )\n throw( ::com::sun::star::frame::TerminationVetoException, ::com::sun::star::uno::RuntimeException );\n virtual void SAL_CALL notifyTermination( const ::com::sun::star::lang::EventObject& aEvent )\n throw( ::com::sun::star::uno::RuntimeException );\n };\n }\n\/\/........................................................................\n} \/\/ namespace connectivity\n\/\/........................................................................\n#endif \/\/ CONNECTIVITY_HSQLDB_TERMINATELISTENER_HXX\n<|endoftext|>"} {"text":"<commit_before><commit_msg>Throw sane exception when wrong type used in PreparedStatement.<commit_after><|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2011 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/ui\/views\/location_bar\/location_icon_view.h\"\n\nLocationIconView::LocationIconView(const LocationBarView* location_bar)\n : ALLOW_THIS_IN_INITIALIZER_LIST(click_handler_(this, location_bar)) {\n}\n\nLocationIconView::~LocationIconView() {\n}\n\nbool LocationIconView::OnMousePressed(const views::MouseEvent& event) {\n \/\/ We want to show the dialog on mouse release; that is the standard behavior\n \/\/ for buttons.\n return true;\n}\n\nvoid LocationIconView::OnMouseReleased(const views::MouseEvent& event,\n bool canceled) {\n click_handler_.OnMouseReleased(event, canceled);\n}\n<commit_msg>views: Show a tooltip for the location icon in the omnibox.<commit_after>\/\/ Copyright (c) 2011 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/ui\/views\/location_bar\/location_icon_view.h\"\n\n#include \"base\/utf_string_conversions.h\"\n#include \"grit\/generated_resources.h\"\n#include \"ui\/base\/l10n\/l10n_util.h\"\n\nLocationIconView::LocationIconView(const LocationBarView* location_bar)\n : ALLOW_THIS_IN_INITIALIZER_LIST(click_handler_(this, location_bar)) {\n SetTooltipText(UTF16ToWide(l10n_util::GetStringUTF16(\n IDS_TOOLTIP_LOCATION_ICON)));\n}\n\nLocationIconView::~LocationIconView() {\n}\n\nbool LocationIconView::OnMousePressed(const views::MouseEvent& event) {\n \/\/ We want to show the dialog on mouse release; that is the standard behavior\n \/\/ for buttons.\n return true;\n}\n\nvoid LocationIconView::OnMouseReleased(const views::MouseEvent& event,\n bool canceled) {\n click_handler_.OnMouseReleased(event, canceled);\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (C) 2018 Elviss Strazdins\n\/\/ This file is part of the Ouzel engine.\n\n#include \"ImageDataSTB.hpp\"\n#include \"utils\/Log.hpp\"\n#include \"core\/Engine.hpp\"\n#include \"files\/FileSystem.hpp\"\n#define STBI_NO_PSD\n#define STBI_NO_HDR\n#define STBI_NO_PIC\n#define STBI_NO_GIF\n#define STBI_NO_PNM\n#define STB_IMAGE_IMPLEMENTATION\n#include \"stb_image.h\"\n#define STB_IMAGE_WRITE_IMPLEMENTATION\n#include \"stb_image_write.h\"\n\nnamespace ouzel\n{\n namespace graphics\n {\n bool ImageDataSTB::init(const std::string& filename,\n PixelFormat newPixelFormat)\n {\n std::vector<uint8_t> newData;\n if (!engine->getFileSystem()->readFile(filename, newData))\n {\n return false;\n }\n\n return init(newData, newPixelFormat);\n }\n\n bool ImageDataSTB::init(const std::vector<uint8_t>& newData,\n PixelFormat newPixelFormat)\n {\n int width;\n int height;\n int comp;\n\n int reqComp;\n switch (newPixelFormat)\n {\n case PixelFormat::R8_UNORM: reqComp = STBI_grey; break;\n case PixelFormat::RG8_UNORM: reqComp = STBI_grey_alpha; break;\n case PixelFormat::RGBA8_UNORM: reqComp = STBI_rgb_alpha; break;\n default: reqComp = STBI_default;\n }\n\n stbi_uc* tempData = stbi_load_from_memory(newData.data(), static_cast<int>(newData.size()), &width, &height, &comp, reqComp);\n\n if (!tempData)\n {\n Log(Log::Level::ERR) << \"Failed to load texture, reason: \" << stbi_failure_reason();\n return false;\n }\n\n if (reqComp != STBI_default) comp = reqComp;\n\n size_t pixelSize;\n switch (comp)\n {\n case STBI_grey: pixelFormat = PixelFormat::R8_UNORM; pixelSize = 1; break;\n case STBI_grey_alpha: pixelFormat = PixelFormat::RG8_UNORM; pixelSize = 2; break;\n case STBI_rgb_alpha: pixelFormat = PixelFormat::RGBA8_UNORM; pixelSize = 4; break;\n default:\n Log(Log::Level::ERR) << \"Unknown pixel size\";\n return false;\n }\n\n data.assign(tempData, tempData + (width * height * pixelSize));\n\n stbi_image_free(tempData);\n\n size.width = static_cast<float>(width);\n size.height = static_cast<float>(height);\n\n return true;\n }\n\n bool ImageDataSTB::writeToFile(const std::string& newFilename)\n {\n int depth = static_cast<int>(getPixelSize(pixelFormat));\n int width = static_cast<int>(size.width);\n int height = static_cast<int>(size.height);\n\n if (!stbi_write_png(newFilename.c_str(), width, height, depth, data.data(), width * depth))\n {\n Log(Log::Level::ERR) << \"Failed to save image to file\";\n return false;\n }\n\n return true;\n }\n\n } \/\/ namespace graphics\n} \/\/ namespace ouzel\n<commit_msg>FIx memory leak in ImageDataSTB<commit_after>\/\/ Copyright (C) 2018 Elviss Strazdins\n\/\/ This file is part of the Ouzel engine.\n\n#include \"ImageDataSTB.hpp\"\n#include \"utils\/Log.hpp\"\n#include \"core\/Engine.hpp\"\n#include \"files\/FileSystem.hpp\"\n#define STBI_NO_PSD\n#define STBI_NO_HDR\n#define STBI_NO_PIC\n#define STBI_NO_GIF\n#define STBI_NO_PNM\n#define STB_IMAGE_IMPLEMENTATION\n#include \"stb_image.h\"\n#define STB_IMAGE_WRITE_IMPLEMENTATION\n#include \"stb_image_write.h\"\n\nnamespace ouzel\n{\n namespace graphics\n {\n bool ImageDataSTB::init(const std::string& filename,\n PixelFormat newPixelFormat)\n {\n std::vector<uint8_t> newData;\n if (!engine->getFileSystem()->readFile(filename, newData))\n {\n return false;\n }\n\n return init(newData, newPixelFormat);\n }\n\n bool ImageDataSTB::init(const std::vector<uint8_t>& newData,\n PixelFormat newPixelFormat)\n {\n int width;\n int height;\n int comp;\n\n int reqComp;\n switch (newPixelFormat)\n {\n case PixelFormat::R8_UNORM: reqComp = STBI_grey; break;\n case PixelFormat::RG8_UNORM: reqComp = STBI_grey_alpha; break;\n case PixelFormat::RGBA8_UNORM: reqComp = STBI_rgb_alpha; break;\n default: reqComp = STBI_default;\n }\n\n stbi_uc* tempData = stbi_load_from_memory(newData.data(), static_cast<int>(newData.size()), &width, &height, &comp, reqComp);\n\n if (!tempData)\n {\n Log(Log::Level::ERR) << \"Failed to load texture, reason: \" << stbi_failure_reason();\n return false;\n }\n\n if (reqComp != STBI_default) comp = reqComp;\n\n size_t pixelSize;\n switch (comp)\n {\n case STBI_grey: pixelFormat = PixelFormat::R8_UNORM; pixelSize = 1; break;\n case STBI_grey_alpha: pixelFormat = PixelFormat::RG8_UNORM; pixelSize = 2; break;\n case STBI_rgb_alpha: pixelFormat = PixelFormat::RGBA8_UNORM; pixelSize = 4; break;\n default:\n Log(Log::Level::ERR) << \"Unknown pixel size\";\n stbi_image_free(tempData);\n return false;\n }\n\n data.assign(tempData, tempData + (width * height * pixelSize));\n\n stbi_image_free(tempData);\n\n size.width = static_cast<float>(width);\n size.height = static_cast<float>(height);\n\n return true;\n }\n\n bool ImageDataSTB::writeToFile(const std::string& newFilename)\n {\n int depth = static_cast<int>(getPixelSize(pixelFormat));\n int width = static_cast<int>(size.width);\n int height = static_cast<int>(size.height);\n\n if (!stbi_write_png(newFilename.c_str(), width, height, depth, data.data(), width * depth))\n {\n Log(Log::Level::ERR) << \"Failed to save image to file\";\n return false;\n }\n\n return true;\n }\n\n } \/\/ namespace graphics\n} \/\/ namespace ouzel\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (C) 2018 Elviss Strazdins\n\/\/ This file is part of the Ouzel engine.\n\n#include <algorithm>\n#include \"RenderDevice.hpp\"\n#include \"thread\/Lock.hpp\"\n#include \"utils\/Log.hpp\"\n\nnamespace ouzel\n{\n namespace graphics\n {\n RenderDevice::RenderDevice(Renderer::Driver aDriver):\n driver(aDriver),\n projectionTransform(Matrix4::IDENTITY),\n renderTargetProjectionTransform(Matrix4::IDENTITY),\n refillQueue(true),\n currentFPS(0.0F),\n accumulatedFPS(0.0F)\n {\n }\n\n RenderDevice::~RenderDevice()\n {\n }\n\n bool RenderDevice::init(Window* newWindow,\n const Size2& newSize,\n uint32_t newSampleCount,\n Texture::Filter newTextureFilter,\n uint32_t newMaxAnisotropy,\n bool newVerticalSync,\n bool newDepth,\n bool newDebugRenderer)\n {\n window = newWindow;\n size = newSize;\n sampleCount = newSampleCount;\n textureFilter = newTextureFilter;\n maxAnisotropy = newMaxAnisotropy;\n verticalSync = newVerticalSync;\n depth = newDepth;\n debugRenderer = newDebugRenderer;\n clearColor = Color::BLACK;\n\n previousFrameTime = std::chrono::steady_clock::now();\n\n return true;\n }\n\n bool RenderDevice::process()\n {\n std::chrono::steady_clock::time_point currentTime = std::chrono::steady_clock::now();\n auto diff = std::chrono::duration_cast<std::chrono::nanoseconds>(currentTime - previousFrameTime);\n previousFrameTime = currentTime;\n\n float delta = diff.count() \/ 1000000000.0F;\n\n if (delta > 0.0F)\n {\n currentFPS = 1.0F \/ delta;\n }\n\n accumulatedTime += delta;\n currentAccumulatedFPS += 1.0F;\n\n if (accumulatedTime > 1.0F)\n {\n accumulatedFPS = currentAccumulatedFPS;\n accumulatedTime = 0.0F;\n currentAccumulatedFPS = 0.0F;\n }\n\n std::vector<std::unique_ptr<RenderResource>> deleteResources; \/\/ will be cleared at the end of the scope\n {\n Lock lock(resourceMutex);\n deleteResources = std::move(resourceDeleteSet);\n }\n\n executeAll();\n\n {\n#if OUZEL_MULTITHREADED\n Lock lock(commandQueueMutex);\n while (!queueFinished) commandQueueCondition.wait(commandQueueMutex);\n#endif\n\n processCommands(*renderBuffer);\n\n queueFinished = false;\n \/\/ refills the draw queue\n refillQueue = true;\n }\n\n return true;\n }\n\n void RenderDevice::setClearColorBuffer(bool clear)\n {\n clearColorBuffer = clear;\n }\n\n void RenderDevice::setClearDepthBuffer(bool clear)\n {\n clearDepthBuffer = clear;\n }\n\n void RenderDevice::setClearColor(Color color)\n {\n clearColor = color;\n }\n\n void RenderDevice::setClearDepth(float newClearDepth)\n {\n clearDepth = newClearDepth;\n }\n\n void RenderDevice::setSize(const Size2& newSize)\n {\n size = newSize;\n }\n\n std::vector<Size2> RenderDevice::getSupportedResolutions() const\n {\n return std::vector<Size2>();\n }\n\n void RenderDevice::deleteResource(RenderResource* resource)\n {\n Lock lock(resourceMutex);\n\n auto resourceIterator = std::find_if(resources.begin(), resources.end(), [resource](const std::unique_ptr<RenderResource>& ptr) {\n return ptr.get() == resource;\n });\n\n if (resourceIterator != resources.end())\n {\n resourceDeleteSet.push_back(std::move(*resourceIterator));\n resources.erase(resourceIterator);\n }\n }\n\n bool RenderDevice::addCommand(Command&& command)\n {\n fillBuffer->push_back(std::move(command));\n\n return true;\n }\n\n void RenderDevice::flushCommands()\n {\n#if OUZEL_MULTITHREADED\n Lock lock(commandQueueMutex);\n#endif\n\n refillQueue = false;\n\n std::swap(fillBuffer, renderBuffer);\n fillBuffer->clear();\n\n queueFinished = true;\n drawCallCount = static_cast<uint32_t>(renderBuffer->size());\n\n#if OUZEL_MULTITHREADED\n commandQueueCondition.signal();\n#endif\n }\n\n bool RenderDevice::generateScreenshot(const std::string&)\n {\n return true;\n }\n\n void RenderDevice::executeOnRenderThread(const std::function<void(void)>& func)\n {\n Lock lock(executeMutex);\n\n executeQueue.push(func);\n }\n\n void RenderDevice::executeAll()\n {\n std::function<void(void)> func;\n\n for (;;)\n {\n {\n Lock lock(executeMutex);\n if (executeQueue.empty()) break;\n\n func = std::move(executeQueue.front());\n executeQueue.pop();\n }\n\n if (func)\n {\n func();\n }\n }\n }\n } \/\/ namespace graphics\n} \/\/ namespace ouzel\n<commit_msg>Allow filling the render queue paralelly to rendering<commit_after>\/\/ Copyright (C) 2018 Elviss Strazdins\n\/\/ This file is part of the Ouzel engine.\n\n#include <algorithm>\n#include \"RenderDevice.hpp\"\n#include \"thread\/Lock.hpp\"\n#include \"utils\/Log.hpp\"\n\nnamespace ouzel\n{\n namespace graphics\n {\n RenderDevice::RenderDevice(Renderer::Driver aDriver):\n driver(aDriver),\n projectionTransform(Matrix4::IDENTITY),\n renderTargetProjectionTransform(Matrix4::IDENTITY),\n refillQueue(true),\n currentFPS(0.0F),\n accumulatedFPS(0.0F)\n {\n }\n\n RenderDevice::~RenderDevice()\n {\n }\n\n bool RenderDevice::init(Window* newWindow,\n const Size2& newSize,\n uint32_t newSampleCount,\n Texture::Filter newTextureFilter,\n uint32_t newMaxAnisotropy,\n bool newVerticalSync,\n bool newDepth,\n bool newDebugRenderer)\n {\n window = newWindow;\n size = newSize;\n sampleCount = newSampleCount;\n textureFilter = newTextureFilter;\n maxAnisotropy = newMaxAnisotropy;\n verticalSync = newVerticalSync;\n depth = newDepth;\n debugRenderer = newDebugRenderer;\n clearColor = Color::BLACK;\n\n previousFrameTime = std::chrono::steady_clock::now();\n\n return true;\n }\n\n bool RenderDevice::process()\n {\n std::chrono::steady_clock::time_point currentTime = std::chrono::steady_clock::now();\n auto diff = std::chrono::duration_cast<std::chrono::nanoseconds>(currentTime - previousFrameTime);\n previousFrameTime = currentTime;\n\n float delta = diff.count() \/ 1000000000.0F;\n\n if (delta > 0.0F)\n {\n currentFPS = 1.0F \/ delta;\n }\n\n accumulatedTime += delta;\n currentAccumulatedFPS += 1.0F;\n\n if (accumulatedTime > 1.0F)\n {\n accumulatedFPS = currentAccumulatedFPS;\n accumulatedTime = 0.0F;\n currentAccumulatedFPS = 0.0F;\n }\n\n std::vector<std::unique_ptr<RenderResource>> deleteResources; \/\/ will be cleared at the end of the scope\n {\n Lock lock(resourceMutex);\n deleteResources = std::move(resourceDeleteSet);\n }\n\n executeAll();\n\n#if OUZEL_MULTITHREADED\n Lock lock(commandQueueMutex);\n while (!queueFinished) commandQueueCondition.wait(commandQueueMutex);\n#endif\n\n std::swap(fillBuffer, renderBuffer);\n fillBuffer->clear();\n\n queueFinished = false;\n\n \/\/ refills the draw queue\n refillQueue = true;\n\n processCommands(*renderBuffer);\n\n return true;\n }\n\n void RenderDevice::setClearColorBuffer(bool clear)\n {\n clearColorBuffer = clear;\n }\n\n void RenderDevice::setClearDepthBuffer(bool clear)\n {\n clearDepthBuffer = clear;\n }\n\n void RenderDevice::setClearColor(Color color)\n {\n clearColor = color;\n }\n\n void RenderDevice::setClearDepth(float newClearDepth)\n {\n clearDepth = newClearDepth;\n }\n\n void RenderDevice::setSize(const Size2& newSize)\n {\n size = newSize;\n }\n\n std::vector<Size2> RenderDevice::getSupportedResolutions() const\n {\n return std::vector<Size2>();\n }\n\n void RenderDevice::deleteResource(RenderResource* resource)\n {\n Lock lock(resourceMutex);\n\n auto resourceIterator = std::find_if(resources.begin(), resources.end(), [resource](const std::unique_ptr<RenderResource>& ptr) {\n return ptr.get() == resource;\n });\n\n if (resourceIterator != resources.end())\n {\n resourceDeleteSet.push_back(std::move(*resourceIterator));\n resources.erase(resourceIterator);\n }\n }\n\n bool RenderDevice::addCommand(Command&& command)\n {\n fillBuffer->push_back(std::move(command));\n\n return true;\n }\n\n void RenderDevice::flushCommands()\n {\n#if OUZEL_MULTITHREADED\n Lock lock(commandQueueMutex);\n#endif\n\n drawCallCount = static_cast<uint32_t>(fillBuffer->size());\n\n refillQueue = false;\n queueFinished = true;\n\n#if OUZEL_MULTITHREADED\n commandQueueCondition.signal();\n#endif\n }\n\n bool RenderDevice::generateScreenshot(const std::string&)\n {\n return true;\n }\n\n void RenderDevice::executeOnRenderThread(const std::function<void(void)>& func)\n {\n Lock lock(executeMutex);\n\n executeQueue.push(func);\n }\n\n void RenderDevice::executeAll()\n {\n std::function<void(void)> func;\n\n for (;;)\n {\n {\n Lock lock(executeMutex);\n if (executeQueue.empty()) break;\n\n func = std::move(executeQueue.front());\n executeQueue.pop();\n }\n\n if (func)\n {\n func();\n }\n }\n }\n } \/\/ namespace graphics\n} \/\/ namespace ouzel\n<|endoftext|>"} {"text":"<commit_before>\/*\n*\n* Copyright 2013 Telefonica Investigacion y Desarrollo, S.A.U\n*\n* This file is part of Orion Context Broker.\n*\n* Orion Context Broker is free software: you can redistribute it and\/or\n* modify it under the terms of the GNU Affero General Public License as\n* published by the Free Software Foundation, either version 3 of the\n* License, or (at your option) any later version.\n*\n* Orion Context Broker is distributed in the hope that it will be useful,\n* but WITHOUT ANY WARRANTY; without even the implied warranty of\n* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero\n* General Public License for more details.\n*\n* You should have received a copy of the GNU Affero General Public License\n* along with Orion Context Broker. If not, see http:\/\/www.gnu.org\/licenses\/.\n*\n* For those usages not covered by this license please contact with\n* fermin at tid dot es\n*\n* Author: Ken Zangelin\n*\/\n#include <string>\n\n#include \"xmlParse\/xmlRequest.h\"\n#include \"jsonParse\/jsonRequest.h\"\n\n#include \"logMsg\/logMsg.h\"\n#include \"logMsg\/traceLevels.h\"\n\n#include \"common\/globals.h\"\n#include \"common\/statistics.h\"\n#include \"common\/string.h\"\n#include \"rest\/ConnectionInfo.h\"\n#include \"rest\/OrionError.h\"\n#include \"rest\/RestService.h\"\n#include \"rest\/restReply.h\"\n#include \"rest\/rest.h\"\n#include \"ngsi\/ParseData.h\"\n\n\n\n\/* ****************************************************************************\n*\n* payloadParse - \n*\/\nstd::string payloadParse(ConnectionInfo* ciP, ParseData* parseDataP, RestService* service, XmlRequest** reqPP, JsonRequest** jsonPP)\n{\n std::string result = \"NONE\";\n\n LM_T(LmtParsedPayload, (\"parsing data for service '%s'. Method: '%s'\", requestType(service->request), ciP->method.c_str()));\n LM_T(LmtParsedPayload, (\"outFormat: %s\", formatToString(ciP->outFormat)));\n\n if (ciP->inFormat == XML)\n {\n LM_T(LmtParsedPayload, (\"Calling xmlTreat for service request %d, payloadWord '%s'\", service->request, service->payloadWord.c_str()));\n result = xmlTreat(ciP->payload, ciP, parseDataP, service->request, service->payloadWord, reqPP);\n }\n else if (ciP->inFormat == JSON)\n result = jsonTreat(ciP->payload, ciP, parseDataP, service->request, service->payloadWord, jsonPP);\n else\n {\n LM_E((\"Bad inFormat: %d\", (int) ciP->inFormat));\n return \"Bad inFormat\";\n }\n\n LM_T(LmtParsedPayload, (\"result: '%s'\", result.c_str()));\n LM_T(LmtParsedPayload, (\"outFormat: %s\", formatToString(ciP->outFormat)));\n\n if (result != \"OK\")\n {\n restReply(ciP, result);\n }\n\n return result;\n}\n\n\n\n\/* ****************************************************************************\n*\n* tenantCheck - \n*\/\nstatic std::string tenantCheck(std::string tenant)\n{\n const char* ctenant = tenant.c_str();\n\n if ((strcasecmp(ctenant, \"ngsi9\") == 0) ||\n (strcasecmp(ctenant, \"ngsi10\") == 0) ||\n (strcasecmp(ctenant, \"log\") == 0) ||\n (strcasecmp(ctenant, \"version\") == 0) ||\n (strcasecmp(ctenant, \"statistics\") == 0) ||\n (strcasecmp(ctenant, \"leak\") == 0) ||\n (strcasecmp(ctenant, \"exit\") == 0))\n {\n LM_E((\"tenant name coincides with Orion reserved name: '%s'\", tenant.c_str()));\n return \"tenant name coincides with Orion reserved name\";\n }\n\n char* name = (char*) tenant.c_str();\n\n if (strlen(name) > 20)\n {\n LM_E((\"bad length - a tenant name can be max 20 characters long (length: %d)\", strlen(name)));\n return \"bad length - a tenant name can be max 20 characters long\";\n }\n\n while (*name != 0)\n {\n if ((!isalnum(*name)) && (*name != '_'))\n {\n LM_E((\"offending character: %c\", *name));\n return \"bad character in tenant name - only underscore and alphanumeric characters are allowed\";\n }\n\n ++name;\n }\n\n return \"OK\";\n}\n\n\n\n\/* ****************************************************************************\n*\n* restService - \n*\/\nstd::string restService(ConnectionInfo* ciP, RestService* serviceV)\n{\n std::vector<std::string> compV;\n int components;\n XmlRequest* reqP = NULL;\n JsonRequest* jsonReqP = NULL;\n ParseData parseData;\n\n if ((ciP->url.length() == 0) || ((ciP->url.length() == 1) && (ciP->url.c_str()[0] == '\/')))\n {\n OrionError error(SccBadRequest, \"The Orion Context Broker is a REST service, not a 'web page'\");\n std::string response = error.render(ciP->outFormat, \"\");\n restReply(ciP, response);\n return std::string(\"Empty URL\");\n }\n\n ciP->httpStatusCode = SccOk;\n\n components = stringSplit(ciP->url, '\/', compV);\n\n for (unsigned int ix = 0; serviceV[ix].treat != NULL; ++ix)\n {\n if ((serviceV[ix].components != 0) && (serviceV[ix].components != components))\n continue;\n\n if ((ciP->method != serviceV[ix].verb) && (serviceV[ix].verb != \"*\"))\n continue;\n\n strncpy(ciP->payloadWord, serviceV[ix].payloadWord.c_str(), sizeof(ciP->payloadWord));\n bool match = true;\n for (int compNo = 0; compNo < components; ++compNo)\n {\n if (serviceV[ix].compV[compNo] == \"*\")\n continue;\n\n if (strcasecmp(serviceV[ix].compV[compNo].c_str(), compV[compNo].c_str()) != 0)\n {\n match = false;\n break;\n }\n }\n\n if (match == false)\n continue;\n\n if ((ciP->payload != NULL) && (ciP->payloadSize != 0) && (serviceV[ix].verb != \"*\"))\n {\n std::string response;\n\n LM_T(LmtParsedPayload, (\"Parsing payload for URL '%s', method '%s', service vector index: %d\", ciP->url.c_str(), ciP->method.c_str(), ix));\n ciP->parseDataP = &parseData;\n response = payloadParse(ciP, &parseData, &serviceV[ix], &reqP, &jsonReqP);\n LM_T(LmtParsedPayload, (\"payloadParse returns '%s'\", response.c_str()));\n if (response != \"OK\")\n {\n restReply(ciP, response);\n\n if (reqP != NULL)\n reqP->release(&parseData);\n if (jsonReqP != NULL)\n jsonReqP->release(&parseData);\n\n compV.clear();\n return response;\n }\n }\n\n LM_T(LmtService, (\"Treating service %s %s\", serviceV[ix].verb.c_str(), ciP->url.c_str())); \/\/ Sacred - used in 'heavyTest'\n statisticsUpdate(serviceV[ix].request, ciP->inFormat);\n\n \/\/ Tenant to connectionInfo\n if (serviceV[ix].compV[0] == \"*\")\n {\n LM_T(LmtTenant, (\"URL tenant: '%s'\", compV[0].c_str()));\n ciP->tenantFromUrl = compV[0];\n }\n\n if (multitenant == \"url\")\n ciP->tenant = ciP->tenantFromUrl;\n else if (multitenant == \"header\")\n ciP->tenant = ciP->tenantFromHttpHeader;\n else \/\/ multitenant == \"off\"\n ciP->tenant = \"\";\n\n \/\/\n \/\/ A tenant string must not be longer that 20 characters and may only contain\n \/\/ underscores and alphanumeric characters.\n \/\/\n std::string result;\n if ((ciP->tenant != \"\") && ((result = tenantCheck(ciP->tenant)) != \"OK\"))\n {\n OrionError error(SccBadRequest, \"tenant format not accepted (a tenant string must not be longer that 20 characters and may only contain underscores and alphanumeric characters)\");\n std::string response = error.render(ciP->outFormat, \"\");\n\n LM_E((\"tenant name error: %s\", result.c_str()));\n restReply(ciP, response);\n return response;\n }\n\n LM_T(LmtTenant, (\"tenant: '%s'\", ciP->tenant.c_str()));\n std::string response = serviceV[ix].treat(ciP, components, compV, &parseData);\n\n if (reqP != NULL)\n {\n reqP->release(&parseData);\n }\n\n if (jsonReqP != NULL)\n {\n jsonReqP->release(&parseData);\n }\n\n compV.clear();\n\n if (response == \"DIE\")\n orionExitFunction(1, \"Received a 'DIE' request\");\n\n\n restReply(ciP, response);\n return response;\n }\n\n LM_E((\"Service '%s' not recognized\", ciP->url.c_str()));\n ciP->httpStatusCode = SccBadRequest;\n std::string answer = restErrorReplyGet(ciP, ciP->outFormat, \"\", ciP->payloadWord, SccBadRequest, std::string(\"Service not recognized: \") + ciP->url);\n restReply(ciP, answer);\n\n compV.clear();\n return answer;\n}\n<commit_msg>Fixed a memory leak<commit_after>\/*\n*\n* Copyright 2013 Telefonica Investigacion y Desarrollo, S.A.U\n*\n* This file is part of Orion Context Broker.\n*\n* Orion Context Broker is free software: you can redistribute it and\/or\n* modify it under the terms of the GNU Affero General Public License as\n* published by the Free Software Foundation, either version 3 of the\n* License, or (at your option) any later version.\n*\n* Orion Context Broker is distributed in the hope that it will be useful,\n* but WITHOUT ANY WARRANTY; without even the implied warranty of\n* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero\n* General Public License for more details.\n*\n* You should have received a copy of the GNU Affero General Public License\n* along with Orion Context Broker. If not, see http:\/\/www.gnu.org\/licenses\/.\n*\n* For those usages not covered by this license please contact with\n* fermin at tid dot es\n*\n* Author: Ken Zangelin\n*\/\n#include <string>\n\n#include \"xmlParse\/xmlRequest.h\"\n#include \"jsonParse\/jsonRequest.h\"\n\n#include \"logMsg\/logMsg.h\"\n#include \"logMsg\/traceLevels.h\"\n\n#include \"common\/globals.h\"\n#include \"common\/statistics.h\"\n#include \"common\/string.h\"\n#include \"rest\/ConnectionInfo.h\"\n#include \"rest\/OrionError.h\"\n#include \"rest\/RestService.h\"\n#include \"rest\/restReply.h\"\n#include \"rest\/rest.h\"\n#include \"ngsi\/ParseData.h\"\n\n\n\n\/* ****************************************************************************\n*\n* payloadParse - \n*\/\nstd::string payloadParse(ConnectionInfo* ciP, ParseData* parseDataP, RestService* service, XmlRequest** reqPP, JsonRequest** jsonPP)\n{\n std::string result = \"NONE\";\n\n LM_T(LmtParsedPayload, (\"parsing data for service '%s'. Method: '%s'\", requestType(service->request), ciP->method.c_str()));\n LM_T(LmtParsedPayload, (\"outFormat: %s\", formatToString(ciP->outFormat)));\n\n if (ciP->inFormat == XML)\n {\n LM_T(LmtParsedPayload, (\"Calling xmlTreat for service request %d, payloadWord '%s'\", service->request, service->payloadWord.c_str()));\n result = xmlTreat(ciP->payload, ciP, parseDataP, service->request, service->payloadWord, reqPP);\n }\n else if (ciP->inFormat == JSON)\n result = jsonTreat(ciP->payload, ciP, parseDataP, service->request, service->payloadWord, jsonPP);\n else\n {\n LM_E((\"Bad inFormat: %d\", (int) ciP->inFormat));\n return \"Bad inFormat\";\n }\n\n LM_T(LmtParsedPayload, (\"result: '%s'\", result.c_str()));\n LM_T(LmtParsedPayload, (\"outFormat: %s\", formatToString(ciP->outFormat)));\n\n if (result != \"OK\")\n {\n restReply(ciP, result);\n }\n\n return result;\n}\n\n\n\n\/* ****************************************************************************\n*\n* tenantCheck - \n*\/\nstatic std::string tenantCheck(std::string tenant)\n{\n const char* ctenant = tenant.c_str();\n\n if ((strcasecmp(ctenant, \"ngsi9\") == 0) ||\n (strcasecmp(ctenant, \"ngsi10\") == 0) ||\n (strcasecmp(ctenant, \"log\") == 0) ||\n (strcasecmp(ctenant, \"version\") == 0) ||\n (strcasecmp(ctenant, \"statistics\") == 0) ||\n (strcasecmp(ctenant, \"leak\") == 0) ||\n (strcasecmp(ctenant, \"exit\") == 0))\n {\n LM_E((\"tenant name coincides with Orion reserved name: '%s'\", tenant.c_str()));\n return \"tenant name coincides with Orion reserved name\";\n }\n\n char* name = (char*) tenant.c_str();\n\n if (strlen(name) > 20)\n {\n LM_E((\"bad length - a tenant name can be max 20 characters long (length: %d)\", strlen(name)));\n return \"bad length - a tenant name can be max 20 characters long\";\n }\n\n while (*name != 0)\n {\n if ((!isalnum(*name)) && (*name != '_'))\n {\n LM_E((\"offending character: %c\", *name));\n return \"bad character in tenant name - only underscore and alphanumeric characters are allowed\";\n }\n\n ++name;\n }\n\n return \"OK\";\n}\n\n\n\n\/* ****************************************************************************\n*\n* restService - \n*\/\nstd::string restService(ConnectionInfo* ciP, RestService* serviceV)\n{\n std::vector<std::string> compV;\n int components;\n XmlRequest* reqP = NULL;\n JsonRequest* jsonReqP = NULL;\n ParseData parseData;\n\n if ((ciP->url.length() == 0) || ((ciP->url.length() == 1) && (ciP->url.c_str()[0] == '\/')))\n {\n OrionError error(SccBadRequest, \"The Orion Context Broker is a REST service, not a 'web page'\");\n std::string response = error.render(ciP->outFormat, \"\");\n restReply(ciP, response);\n return std::string(\"Empty URL\");\n }\n\n ciP->httpStatusCode = SccOk;\n\n components = stringSplit(ciP->url, '\/', compV);\n\n for (unsigned int ix = 0; serviceV[ix].treat != NULL; ++ix)\n {\n if ((serviceV[ix].components != 0) && (serviceV[ix].components != components))\n continue;\n\n if ((ciP->method != serviceV[ix].verb) && (serviceV[ix].verb != \"*\"))\n continue;\n\n strncpy(ciP->payloadWord, serviceV[ix].payloadWord.c_str(), sizeof(ciP->payloadWord));\n bool match = true;\n for (int compNo = 0; compNo < components; ++compNo)\n {\n if (serviceV[ix].compV[compNo] == \"*\")\n continue;\n\n if (strcasecmp(serviceV[ix].compV[compNo].c_str(), compV[compNo].c_str()) != 0)\n {\n match = false;\n break;\n }\n }\n\n if (match == false)\n continue;\n\n if ((ciP->payload != NULL) && (ciP->payloadSize != 0) && (serviceV[ix].verb != \"*\"))\n {\n std::string response;\n\n LM_T(LmtParsedPayload, (\"Parsing payload for URL '%s', method '%s', service vector index: %d\", ciP->url.c_str(), ciP->method.c_str(), ix));\n ciP->parseDataP = &parseData;\n response = payloadParse(ciP, &parseData, &serviceV[ix], &reqP, &jsonReqP);\n LM_T(LmtParsedPayload, (\"payloadParse returns '%s'\", response.c_str()));\n if (response != \"OK\")\n {\n restReply(ciP, response);\n\n if (reqP != NULL)\n reqP->release(&parseData);\n if (jsonReqP != NULL)\n jsonReqP->release(&parseData);\n\n compV.clear();\n return response;\n }\n }\n\n LM_T(LmtService, (\"Treating service %s %s\", serviceV[ix].verb.c_str(), ciP->url.c_str())); \/\/ Sacred - used in 'heavyTest'\n statisticsUpdate(serviceV[ix].request, ciP->inFormat);\n\n \/\/ Tenant to connectionInfo\n if (serviceV[ix].compV[0] == \"*\")\n {\n LM_T(LmtTenant, (\"URL tenant: '%s'\", compV[0].c_str()));\n ciP->tenantFromUrl = compV[0];\n }\n\n if (multitenant == \"url\")\n ciP->tenant = ciP->tenantFromUrl;\n else if (multitenant == \"header\")\n ciP->tenant = ciP->tenantFromHttpHeader;\n else \/\/ multitenant == \"off\"\n ciP->tenant = \"\";\n\n \/\/\n \/\/ A tenant string must not be longer that 20 characters and may only contain\n \/\/ underscores and alphanumeric characters.\n \/\/\n std::string result;\n if ((ciP->tenant != \"\") && ((result = tenantCheck(ciP->tenant)) != \"OK\"))\n {\n OrionError error(SccBadRequest, \"tenant format not accepted (a tenant string must not be longer that 20 characters and may only contain underscores and alphanumeric characters)\");\n std::string response = error.render(ciP->outFormat, \"\");\n\n LM_E((\"tenant name error: %s\", result.c_str()));\n restReply(ciP, response);\n\n if (reqP != NULL)\n reqP->release(&parseData);\n if (jsonReqP != NULL)\n jsonReqP->release(&parseData);\n\n compV.clear();\n \n return response;\n }\n\n LM_T(LmtTenant, (\"tenant: '%s'\", ciP->tenant.c_str()));\n std::string response = serviceV[ix].treat(ciP, components, compV, &parseData);\n\n if (reqP != NULL)\n {\n reqP->release(&parseData);\n }\n\n if (jsonReqP != NULL)\n {\n jsonReqP->release(&parseData);\n }\n\n compV.clear();\n\n if (response == \"DIE\")\n orionExitFunction(1, \"Received a 'DIE' request\");\n\n\n restReply(ciP, response);\n return response;\n }\n\n LM_E((\"Service '%s' not recognized\", ciP->url.c_str()));\n ciP->httpStatusCode = SccBadRequest;\n std::string answer = restErrorReplyGet(ciP, ciP->outFormat, \"\", ciP->payloadWord, SccBadRequest, std::string(\"Service not recognized: \") + ciP->url);\n restReply(ciP, answer);\n\n compV.clear();\n return answer;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ libavg - Media Playback Engine. \n\/\/ Copyright (C) 2003-2014 Ulrich von Zadow\n\/\/\n\/\/ This library is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU Lesser General Public\n\/\/ License as published by the Free Software Foundation; either\n\/\/ version 2 of the License, or (at your option) any later version.\n\/\/\n\/\/ This library is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ Lesser General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License along with this library; if not, write to the Free Software\n\/\/ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n\/\/\n\/\/ Current versions can be found at www.libavg.de\n\/\/\n\n#include \"StringHelper.h\"\n\nusing namespace std;\n\nnamespace avg {\n\nbool isWhitespace(const string& s)\n{\n return s.find_first_not_of(\" \\n\\r\\t\") == s.npos;\n}\n\nvoid skipWhitespace(std::istream& is)\n{\n string sWhitespace(\" \\n\\r\\t\");\n bool bWhitespace;\n do {\n int i = is.peek();\n if (i == EOF) {\n bWhitespace = false;\n } else {\n bWhitespace = (sWhitespace.find(char(i)) != sWhitespace.npos);\n }\n if (bWhitespace) {\n is.ignore();\n }\n } while (bWhitespace);\n}\n\nvoid skipToken(std::istream& is, char token)\n{\n skipWhitespace(is);\n int i = is.peek();\n if (i == token) {\n is.ignore();\n } else {\n is.setstate(ios::failbit);\n }\n}\n\nint stringToInt(const string& s)\n{\n int i;\n fromString(s, i);\n return i;\n}\n\nfloat stringToFloat(const string& s)\n{\n float d;\n fromString(s, d);\n return d;\n}\n\nbool stringToBool(const string& s)\n{\n \/\/ avg usually wants xml attributes in lowercase, but python only\n \/\/ sees 'True' as true, so we'll accept that too. Also, python 2.3\n \/\/ has 1 as true, so that has to be ok too.\n if (s == \"True\" || s == \"true\" || s == \"1\") {\n return true;\n }\n if (s == \"False\" || s == \"false\" || s == \"0\") {\n return false;\n }\n throw (Exception(AVG_ERR_TYPE, string(\"Could not convert \")+s+\" to bool.\"));\n}\n\nstd::string removeStartEndSpaces(const string& s)\n{\n string sResult = s;\n while (sResult.size() > 0 && (sResult[0] == ' ' || sResult[0] == '\\n' \n || sResult[0] == '\\r' || sResult[0] == '\\t')) \n {\n sResult.erase(0, 1);\n }\n if (sResult.size() == 0) {\n return sResult;\n }\n char c = sResult[sResult.length()-1];\n while (c == ' ' || c == '\\n' || c == '\\r' || c == '\\t') {\n sResult.erase(sResult.length()-1, 1);\n c = sResult[sResult.length()-1];\n }\n return sResult;\n}\n\nstring toLowerCase(const string& s)\n{\n string sResult;\n for (unsigned i=0; i<s.length(); ++i) {\n sResult.push_back(::tolower(s[i]));\n }\n return sResult;\n}\n\nbool equalIgnoreCase(const string& s1, const string& s2)\n{\n if (s1.length() != s2.length()) {\n return false;\n }\n string sUpper1;\n string sUpper2;\n transform(s1.begin(), s1.end(), std::back_inserter(sUpper1), (int(*)(int)) toupper);\n transform(s2.begin(), s2.end(), std::back_inserter(sUpper2), (int(*)(int)) toupper);\n return sUpper1 == sUpper2;\n}\n\nstring toString(const bool& b)\n{\n if (b) {\n return \"true\";\n } else {\n return \"false\";\n }\n}\n\n}\n\n<commit_msg>Linux build fix.<commit_after>\/\/\n\/\/ libavg - Media Playback Engine. \n\/\/ Copyright (C) 2003-2014 Ulrich von Zadow\n\/\/\n\/\/ This library is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU Lesser General Public\n\/\/ License as published by the Free Software Foundation; either\n\/\/ version 2 of the License, or (at your option) any later version.\n\/\/\n\/\/ This library is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ Lesser General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License along with this library; if not, write to the Free Software\n\/\/ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n\/\/\n\/\/ Current versions can be found at www.libavg.de\n\/\/\n\n#include \"StringHelper.h\"\n\n#include <cstdio>\n#include <algorithm>\n\nusing namespace std;\n\nnamespace avg {\n\nbool isWhitespace(const string& s)\n{\n return s.find_first_not_of(\" \\n\\r\\t\") == s.npos;\n}\n\nvoid skipWhitespace(std::istream& is)\n{\n string sWhitespace(\" \\n\\r\\t\");\n bool bWhitespace;\n do {\n int i = is.peek();\n if (i == EOF) {\n bWhitespace = false;\n } else {\n bWhitespace = (sWhitespace.find(char(i)) != sWhitespace.npos);\n }\n if (bWhitespace) {\n is.ignore();\n }\n } while (bWhitespace);\n}\n\nvoid skipToken(std::istream& is, char token)\n{\n skipWhitespace(is);\n int i = is.peek();\n if (i == token) {\n is.ignore();\n } else {\n is.setstate(ios::failbit);\n }\n}\n\nint stringToInt(const string& s)\n{\n int i;\n fromString(s, i);\n return i;\n}\n\nfloat stringToFloat(const string& s)\n{\n float d;\n fromString(s, d);\n return d;\n}\n\nbool stringToBool(const string& s)\n{\n \/\/ avg usually wants xml attributes in lowercase, but python only\n \/\/ sees 'True' as true, so we'll accept that too. Also, python 2.3\n \/\/ has 1 as true, so that has to be ok too.\n if (s == \"True\" || s == \"true\" || s == \"1\") {\n return true;\n }\n if (s == \"False\" || s == \"false\" || s == \"0\") {\n return false;\n }\n throw (Exception(AVG_ERR_TYPE, string(\"Could not convert \")+s+\" to bool.\"));\n}\n\nstd::string removeStartEndSpaces(const string& s)\n{\n string sResult = s;\n while (sResult.size() > 0 && (sResult[0] == ' ' || sResult[0] == '\\n' \n || sResult[0] == '\\r' || sResult[0] == '\\t')) \n {\n sResult.erase(0, 1);\n }\n if (sResult.size() == 0) {\n return sResult;\n }\n char c = sResult[sResult.length()-1];\n while (c == ' ' || c == '\\n' || c == '\\r' || c == '\\t') {\n sResult.erase(sResult.length()-1, 1);\n c = sResult[sResult.length()-1];\n }\n return sResult;\n}\n\nstring toLowerCase(const string& s)\n{\n string sResult;\n for (unsigned i=0; i<s.length(); ++i) {\n sResult.push_back(::tolower(s[i]));\n }\n return sResult;\n}\n\nbool equalIgnoreCase(const string& s1, const string& s2)\n{\n if (s1.length() != s2.length()) {\n return false;\n }\n string sUpper1;\n string sUpper2;\n transform(s1.begin(), s1.end(), std::back_inserter(sUpper1), (int(*)(int)) toupper);\n transform(s2.begin(), s2.end(), std::back_inserter(sUpper2), (int(*)(int)) toupper);\n return sUpper1 == sUpper2;\n}\n\nstring toString(const bool& b)\n{\n if (b) {\n return \"true\";\n } else {\n return \"false\";\n }\n}\n\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2008 by Sun Microsystems, Inc.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: RelationDlg.cxx,v $\n * $Revision: 1.27 $\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * <http:\/\/www.openoffice.org\/license.html>\n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_dbaccess.hxx\"\n\/\/#ifndef _SVX_TABWIN_HXX\n\/\/#include \"tabwin.hxx\"\n\/\/#endif\n#ifndef DBAUI_RELATIONDIALOG_HRC\n#include \"RelationDlg.hrc\"\n#endif\n#ifndef DBAUI_RELATIONDIALOG_HXX\n#include \"RelationDlg.hxx\"\n#endif\n\n#ifndef _WRKWIN_HXX \/\/autogen\n#include <vcl\/wrkwin.hxx>\n#endif\n\n#ifndef _SV_SVAPP_HXX \/\/autogen\n#include <vcl\/svapp.hxx>\n#endif\n#ifndef _DBU_DLG_HRC_\n#include \"dbu_dlg.hrc\"\n#endif\n#ifndef _DBA_DBACCESS_HELPID_HRC_\n#include \"dbaccess_helpid.hrc\"\n#endif\n#ifndef _COM_SUN_STAR_SDBC_KEYRULE_HPP_\n#include <com\/sun\/star\/sdbc\/KeyRule.hpp>\n#endif\n\n#ifndef _TOOLS_DEBUG_HXX\n#include <tools\/debug.hxx>\n#endif\n#ifndef DBAUI_TOOLS_HXX\n#include \"UITools.hxx\"\n#endif\n#ifndef DBAUI_JOINDESIGNVIEW_HXX\n#include \"JoinDesignView.hxx\"\n#endif\n#ifndef DBAUI_JOINCONTROLLER_HXX\n#include \"JoinController.hxx\"\n#endif\n#ifndef _DBHELPER_DBEXCEPTION_HXX_\n#include <connectivity\/dbexception.hxx>\n#endif\n#ifndef DBAUI_RTABLECONNECTIONDATA_HXX\n#include \"RTableConnectionData.hxx\"\n#endif\n#ifndef DBAUI_RELATIONCONTROL_HXX\n#include \"RelationControl.hxx\"\n#endif\n\n#include <algorithm>\n\nusing namespace ::com::sun::star::uno;\nusing namespace ::com::sun::star::sdbc;\nusing namespace ::com::sun::star::container;\nusing namespace ::com::sun::star::beans;\nusing namespace ::dbaui;\nusing namespace ::dbtools;\n\n\/\/========================================================================\n\/\/ class ORelationDialog\nDBG_NAME(ORelationDialog)\n\/\/========================================================================\nORelationDialog::ORelationDialog( OJoinTableView* pParent,\n const TTableConnectionData::value_type& pConnectionData,\n BOOL bAllowTableSelect )\n :ModalDialog( pParent, ModuleRes(DLG_REL_PROPERTIES) )\n ,m_pTableMap(pParent->GetTabWinMap())\n\n ,aFL_CascUpd( this, ModuleRes(FL_CASC_UPD) )\n ,aRB_NoCascUpd( this, ModuleRes(RB_NO_CASC_UPD) )\n ,aRB_CascUpd( this, ModuleRes(RB_CASC_UPD) )\n ,aRB_CascUpdNull( this, ModuleRes(RB_CASC_UPD_NULL) )\n ,aRB_CascUpdDefault( this, ModuleRes(RB_CASC_UPD_DEFAULT) )\n ,aFL_CascDel( this, ModuleRes(FL_CASC_DEL) )\n ,aRB_NoCascDel( this, ModuleRes(RB_NO_CASC_DEL) )\n ,aRB_CascDel( this, ModuleRes(RB_CASC_DEL) )\n ,aRB_CascDelNull( this, ModuleRes(RB_CASC_DEL_NULL) )\n ,aRB_CascDelDefault( this, ModuleRes(RB_CASC_DEL_DEFAULT) )\n\n ,aPB_OK( this, ModuleRes( PB_OK ) )\n ,aPB_CANCEL( this, ModuleRes( PB_CANCEL ) )\n ,aPB_HELP( this, ModuleRes( PB_HELP ) )\n\n ,m_pOrigConnData( pConnectionData )\n ,m_bTriedOneUpdate(FALSE)\n{\n DBG_CTOR(ORelationDialog,NULL);\n\n m_xConnection = pParent->getDesignView()->getController()->getConnection();\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ Connection kopieren\n m_pConnData.reset( static_cast<ORelationTableConnectionData*>(pConnectionData->NewInstance()) );\n m_pConnData->CopyFrom( *pConnectionData );\n\n Init(m_pConnData);\n m_pTableControl.reset( new OTableListBoxControl(this,ModuleRes(WND_CONTROL),m_pTableMap,this) );\n\n aPB_OK.SetClickHdl( LINK(this, ORelationDialog, OKClickHdl) );\n\n m_pTableControl->Init( m_pConnData );\n if ( bAllowTableSelect )\n m_pTableControl->fillListBoxes();\n else\n m_pTableControl->fillAndDisable(pConnectionData);\n\n m_pTableControl->lateInit();\n\n m_pTableControl->NotifyCellChange();\n\n FreeResource();\n}\n\n\/\/------------------------------------------------------------------------\nvoid ORelationDialog::Init(const TTableConnectionData::value_type& _pConnectionData)\n{\n ORelationTableConnectionData* pConnData = static_cast<ORelationTableConnectionData*>(_pConnectionData.get());\n \/\/ Update Rules\n switch (pConnData->GetUpdateRules())\n {\n case KeyRule::NO_ACTION:\n case KeyRule::RESTRICT:\n aRB_NoCascUpd.Check( TRUE );\n break;\n\n case KeyRule::CASCADE:\n aRB_CascUpd.Check( TRUE );\n break;\n\n case KeyRule::SET_NULL:\n aRB_CascUpdNull.Check( TRUE );\n break;\n case KeyRule::SET_DEFAULT:\n aRB_CascUpdDefault.Check( TRUE );\n break;\n }\n\n \/\/ Delete Rules\n switch (pConnData->GetDeleteRules())\n {\n case KeyRule::NO_ACTION:\n case KeyRule::RESTRICT:\n aRB_NoCascDel.Check( TRUE );\n break;\n\n case KeyRule::CASCADE:\n aRB_CascDel.Check( TRUE );\n break;\n\n case KeyRule::SET_NULL:\n aRB_CascDelNull.Check( TRUE );\n break;\n case KeyRule::SET_DEFAULT:\n aRB_CascDelDefault.Check( TRUE );\n break;\n }\n}\n\n\/\/------------------------------------------------------------------------\nORelationDialog::~ORelationDialog()\n{\n DBG_DTOR(ORelationDialog,NULL);\n}\n\n\/\/------------------------------------------------------------------------\n\n\n\/\/------------------------------------------------------------------------\nIMPL_LINK( ORelationDialog, OKClickHdl, Button*, \/*pButton*\/ )\n{\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ RadioButtons auslesen\n UINT16 nAttrib = 0;\n\n \/\/ Delete Rules\n if( aRB_NoCascDel.IsChecked() )\n nAttrib |= KeyRule::NO_ACTION;\n if( aRB_CascDel.IsChecked() )\n nAttrib |= KeyRule::CASCADE;\n if( aRB_CascDelNull.IsChecked() )\n nAttrib |= KeyRule::SET_NULL;\n if( aRB_CascDelDefault.IsChecked() )\n nAttrib |= KeyRule::SET_DEFAULT;\n\n ORelationTableConnectionData* pConnData = static_cast<ORelationTableConnectionData*>(m_pConnData.get());\n pConnData->SetDeleteRules( nAttrib );\n\n \/\/ Update Rules\n nAttrib = 0;\n if( aRB_NoCascUpd.IsChecked() )\n nAttrib |= KeyRule::NO_ACTION;\n if( aRB_CascUpd.IsChecked() )\n nAttrib |= KeyRule::CASCADE;\n if( aRB_CascUpdNull.IsChecked() )\n nAttrib |= KeyRule::SET_NULL;\n if( aRB_CascUpdDefault.IsChecked() )\n nAttrib |= KeyRule::SET_DEFAULT;\n pConnData->SetUpdateRules( nAttrib );\n\n m_pTableControl->SaveModified();\n\n \/\/\/\/ wenn die ComboBoxen fuer die Tabellenauswahl enabled sind (Constructor mit bAllowTableSelect==TRUE), dann muss ich in die\n \/\/\/\/ Connection auch die Tabellennamen stecken\n \/\/m_pConnData->SetSourceWinName(m_pTableControl->getSourceWinName());\n \/\/m_pConnData->SetDestWinName(m_pTableControl->getDestWinName());\n\n \/\/ try to create the relation\n try\n {\n ORelationTableConnectionData* pOrigConnData = static_cast<ORelationTableConnectionData*>(m_pOrigConnData.get());\n if (*pConnData != *pOrigConnData || pConnData->Update())\n {\n m_pOrigConnData->CopyFrom( *m_pConnData );\n EndDialog( RET_OK );\n return 0L;\n }\n }\n catch(const SQLException& e)\n {\n ::dbaui::showError( SQLExceptionInfo(e),\n this,\n static_cast<OJoinTableView*>(GetParent())->getDesignView()->getController()->getORB());\n }\n catch(const Exception&)\n {\n \/\/OSL_ENSURE(sal_False, \"ORelationDialog, OKClickHdl: caught an exception!\");\n }\n\n m_bTriedOneUpdate = TRUE;\n \/\/ this means that the original connection may be lost (if m_pConnData was not a newly created but an\n \/\/ existent conn to be modified), which we reflect by returning RET_NO (see ::Execute)\n\n \/\/ try again\n Init(m_pConnData);\n m_pTableControl->Init( m_pConnData );\n m_pTableControl->lateInit();\n\n return 0;\n}\n\n\n\/\/------------------------------------------------------------------------\nshort ORelationDialog::Execute()\n{\n short nResult = ModalDialog::Execute();\n if ((nResult != RET_OK) && m_bTriedOneUpdate)\n return RET_NO;\n\n return nResult;\n}\n\/\/ -----------------------------------------------------------------------------\nTTableConnectionData::value_type ORelationDialog::getConnectionData() const\n{\n return m_pConnData;\n}\n\/\/ -----------------------------------------------------------------------------\nvoid ORelationDialog::setValid(sal_Bool _bValid)\n{\n aPB_OK.Enable(_bValid);\n}\n\/\/ -----------------------------------------------------------------------------\nvoid ORelationDialog::notifyConnectionChange()\n{\n Init(m_pConnData);\n}\n\/\/ -----------------------------------------------------------------------------\n\n\n<commit_msg>INTEGRATION: CWS dba30b (1.26.78); FILE MERGED 2008\/04\/15 22:13:23 fs 1.26.78.2: RESYNC: (1.26-1.27); FILE MERGED 2008\/03\/16 14:09:02 fs 1.26.78.1: some exception handling re-factoring<commit_after>\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2008 by Sun Microsystems, Inc.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: RelationDlg.cxx,v $\n * $Revision: 1.28 $\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * <http:\/\/www.openoffice.org\/license.html>\n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_dbaccess.hxx\"\n\/\/#ifndef _SVX_TABWIN_HXX\n\/\/#include \"tabwin.hxx\"\n\/\/#endif\n#ifndef DBAUI_RELATIONDIALOG_HRC\n#include \"RelationDlg.hrc\"\n#endif\n#ifndef DBAUI_RELATIONDIALOG_HXX\n#include \"RelationDlg.hxx\"\n#endif\n\n#ifndef _WRKWIN_HXX \/\/autogen\n#include <vcl\/wrkwin.hxx>\n#endif\n\n#ifndef _SV_SVAPP_HXX \/\/autogen\n#include <vcl\/svapp.hxx>\n#endif\n#ifndef _DBU_DLG_HRC_\n#include \"dbu_dlg.hrc\"\n#endif\n#ifndef _DBA_DBACCESS_HELPID_HRC_\n#include \"dbaccess_helpid.hrc\"\n#endif\n#ifndef _COM_SUN_STAR_SDBC_KEYRULE_HPP_\n#include <com\/sun\/star\/sdbc\/KeyRule.hpp>\n#endif\n\n#ifndef _TOOLS_DEBUG_HXX\n#include <tools\/debug.hxx>\n#endif\n#ifndef TOOLS_DIAGNOSE_EX_H\n#include <tools\/diagnose_ex.h>\n#endif\n#ifndef DBAUI_TOOLS_HXX\n#include \"UITools.hxx\"\n#endif\n#ifndef DBAUI_JOINDESIGNVIEW_HXX\n#include \"JoinDesignView.hxx\"\n#endif\n#ifndef DBAUI_JOINCONTROLLER_HXX\n#include \"JoinController.hxx\"\n#endif\n#ifndef _DBHELPER_DBEXCEPTION_HXX_\n#include <connectivity\/dbexception.hxx>\n#endif\n#ifndef DBAUI_RTABLECONNECTIONDATA_HXX\n#include \"RTableConnectionData.hxx\"\n#endif\n#ifndef DBAUI_RELATIONCONTROL_HXX\n#include \"RelationControl.hxx\"\n#endif\n#ifndef _CPPUHELPER_EXC_HLP_HXX_\n#include <cppuhelper\/exc_hlp.hxx>\n#endif\n\n#include <algorithm>\n\nusing namespace ::com::sun::star::uno;\nusing namespace ::com::sun::star::sdbc;\nusing namespace ::com::sun::star::container;\nusing namespace ::com::sun::star::beans;\nusing namespace ::dbaui;\nusing namespace ::dbtools;\n\n\/\/========================================================================\n\/\/ class ORelationDialog\nDBG_NAME(ORelationDialog)\n\/\/========================================================================\nORelationDialog::ORelationDialog( OJoinTableView* pParent,\n const TTableConnectionData::value_type& pConnectionData,\n BOOL bAllowTableSelect )\n :ModalDialog( pParent, ModuleRes(DLG_REL_PROPERTIES) )\n ,m_pTableMap(pParent->GetTabWinMap())\n\n ,aFL_CascUpd( this, ModuleRes(FL_CASC_UPD) )\n ,aRB_NoCascUpd( this, ModuleRes(RB_NO_CASC_UPD) )\n ,aRB_CascUpd( this, ModuleRes(RB_CASC_UPD) )\n ,aRB_CascUpdNull( this, ModuleRes(RB_CASC_UPD_NULL) )\n ,aRB_CascUpdDefault( this, ModuleRes(RB_CASC_UPD_DEFAULT) )\n ,aFL_CascDel( this, ModuleRes(FL_CASC_DEL) )\n ,aRB_NoCascDel( this, ModuleRes(RB_NO_CASC_DEL) )\n ,aRB_CascDel( this, ModuleRes(RB_CASC_DEL) )\n ,aRB_CascDelNull( this, ModuleRes(RB_CASC_DEL_NULL) )\n ,aRB_CascDelDefault( this, ModuleRes(RB_CASC_DEL_DEFAULT) )\n\n ,aPB_OK( this, ModuleRes( PB_OK ) )\n ,aPB_CANCEL( this, ModuleRes( PB_CANCEL ) )\n ,aPB_HELP( this, ModuleRes( PB_HELP ) )\n\n ,m_pOrigConnData( pConnectionData )\n ,m_bTriedOneUpdate(FALSE)\n{\n DBG_CTOR(ORelationDialog,NULL);\n\n m_xConnection = pParent->getDesignView()->getController()->getConnection();\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ Connection kopieren\n m_pConnData.reset( static_cast<ORelationTableConnectionData*>(pConnectionData->NewInstance()) );\n m_pConnData->CopyFrom( *pConnectionData );\n\n Init(m_pConnData);\n m_pTableControl.reset( new OTableListBoxControl(this,ModuleRes(WND_CONTROL),m_pTableMap,this) );\n\n aPB_OK.SetClickHdl( LINK(this, ORelationDialog, OKClickHdl) );\n\n m_pTableControl->Init( m_pConnData );\n if ( bAllowTableSelect )\n m_pTableControl->fillListBoxes();\n else\n m_pTableControl->fillAndDisable(pConnectionData);\n\n m_pTableControl->lateInit();\n\n m_pTableControl->NotifyCellChange();\n\n FreeResource();\n}\n\n\/\/------------------------------------------------------------------------\nvoid ORelationDialog::Init(const TTableConnectionData::value_type& _pConnectionData)\n{\n ORelationTableConnectionData* pConnData = static_cast<ORelationTableConnectionData*>(_pConnectionData.get());\n \/\/ Update Rules\n switch (pConnData->GetUpdateRules())\n {\n case KeyRule::NO_ACTION:\n case KeyRule::RESTRICT:\n aRB_NoCascUpd.Check( TRUE );\n break;\n\n case KeyRule::CASCADE:\n aRB_CascUpd.Check( TRUE );\n break;\n\n case KeyRule::SET_NULL:\n aRB_CascUpdNull.Check( TRUE );\n break;\n case KeyRule::SET_DEFAULT:\n aRB_CascUpdDefault.Check( TRUE );\n break;\n }\n\n \/\/ Delete Rules\n switch (pConnData->GetDeleteRules())\n {\n case KeyRule::NO_ACTION:\n case KeyRule::RESTRICT:\n aRB_NoCascDel.Check( TRUE );\n break;\n\n case KeyRule::CASCADE:\n aRB_CascDel.Check( TRUE );\n break;\n\n case KeyRule::SET_NULL:\n aRB_CascDelNull.Check( TRUE );\n break;\n case KeyRule::SET_DEFAULT:\n aRB_CascDelDefault.Check( TRUE );\n break;\n }\n}\n\n\/\/------------------------------------------------------------------------\nORelationDialog::~ORelationDialog()\n{\n DBG_DTOR(ORelationDialog,NULL);\n}\n\n\/\/------------------------------------------------------------------------\n\n\n\/\/------------------------------------------------------------------------\nIMPL_LINK( ORelationDialog, OKClickHdl, Button*, \/*pButton*\/ )\n{\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ RadioButtons auslesen\n UINT16 nAttrib = 0;\n\n \/\/ Delete Rules\n if( aRB_NoCascDel.IsChecked() )\n nAttrib |= KeyRule::NO_ACTION;\n if( aRB_CascDel.IsChecked() )\n nAttrib |= KeyRule::CASCADE;\n if( aRB_CascDelNull.IsChecked() )\n nAttrib |= KeyRule::SET_NULL;\n if( aRB_CascDelDefault.IsChecked() )\n nAttrib |= KeyRule::SET_DEFAULT;\n\n ORelationTableConnectionData* pConnData = static_cast<ORelationTableConnectionData*>(m_pConnData.get());\n pConnData->SetDeleteRules( nAttrib );\n\n \/\/ Update Rules\n nAttrib = 0;\n if( aRB_NoCascUpd.IsChecked() )\n nAttrib |= KeyRule::NO_ACTION;\n if( aRB_CascUpd.IsChecked() )\n nAttrib |= KeyRule::CASCADE;\n if( aRB_CascUpdNull.IsChecked() )\n nAttrib |= KeyRule::SET_NULL;\n if( aRB_CascUpdDefault.IsChecked() )\n nAttrib |= KeyRule::SET_DEFAULT;\n pConnData->SetUpdateRules( nAttrib );\n\n m_pTableControl->SaveModified();\n\n \/\/\/\/ wenn die ComboBoxen fuer die Tabellenauswahl enabled sind (Constructor mit bAllowTableSelect==TRUE), dann muss ich in die\n \/\/\/\/ Connection auch die Tabellennamen stecken\n \/\/m_pConnData->SetSourceWinName(m_pTableControl->getSourceWinName());\n \/\/m_pConnData->SetDestWinName(m_pTableControl->getDestWinName());\n\n \/\/ try to create the relation\n try\n {\n ORelationTableConnectionData* pOrigConnData = static_cast<ORelationTableConnectionData*>(m_pOrigConnData.get());\n if (*pConnData != *pOrigConnData || pConnData->Update())\n {\n m_pOrigConnData->CopyFrom( *m_pConnData );\n EndDialog( RET_OK );\n return 0L;\n }\n }\n catch( const SQLException& )\n {\n ::dbaui::showError( SQLExceptionInfo( ::cppu::getCaughtException() ),\n this,\n static_cast<OJoinTableView*>(GetParent())->getDesignView()->getController()->getORB());\n }\n catch( const Exception& )\n {\n DBG_UNHANDLED_EXCEPTION();\n }\n\n m_bTriedOneUpdate = TRUE;\n \/\/ this means that the original connection may be lost (if m_pConnData was not a newly created but an\n \/\/ existent conn to be modified), which we reflect by returning RET_NO (see ::Execute)\n\n \/\/ try again\n Init(m_pConnData);\n m_pTableControl->Init( m_pConnData );\n m_pTableControl->lateInit();\n\n return 0;\n}\n\n\n\/\/------------------------------------------------------------------------\nshort ORelationDialog::Execute()\n{\n short nResult = ModalDialog::Execute();\n if ((nResult != RET_OK) && m_bTriedOneUpdate)\n return RET_NO;\n\n return nResult;\n}\n\/\/ -----------------------------------------------------------------------------\nTTableConnectionData::value_type ORelationDialog::getConnectionData() const\n{\n return m_pConnData;\n}\n\/\/ -----------------------------------------------------------------------------\nvoid ORelationDialog::setValid(sal_Bool _bValid)\n{\n aPB_OK.Enable(_bValid);\n}\n\/\/ -----------------------------------------------------------------------------\nvoid ORelationDialog::notifyConnectionChange()\n{\n Init(m_pConnData);\n}\n\/\/ -----------------------------------------------------------------------------\n\n\n<|endoftext|>"} {"text":"<commit_before>#pragma once\n\n#include <list>\n#include <random>\n#include <unordered_map>\n#include <utility>\n#include <vector>\n\n#include \"abstract_cache.hpp\"\n\nnamespace opossum {\n\n\/\/ Generic cache implementation using a random eviction policy.\n\/\/ Note: This implementation is not thread-safe.\ntemplate <typename Key, typename Value>\nclass RandomCache : public AbstractCache<Key, Value> {\n public:\n typedef typename std::pair<Key, Value> KeyValuePair;\n\n explicit RandomCache(size_t capacity) : AbstractCache<Key, Value>(capacity), _gen(_rd()), _rand(0, capacity - 1) {\n _list.reserve(capacity);\n }\n\n \/\/ Sets the value to be cached at the given key.\n void set(const Key& key, const Value& value, double cost = 1.0, double size = 1.0) {\n \/\/ Override old element at that key, if it exists.\n auto it = _map.find(key);\n if (it != _map.end()) {\n _list[it->second].second = value;\n return;\n }\n\n \/\/ If capacity is exceeded, pick a random element and replace it.\n if (_list.size() >= this->_capacity) {\n size_t index = _rand(_gen);\n _map.erase(_list[index].first);\n\n _list[index] = KeyValuePair(key, value);\n _map[key] = index;\n return;\n }\n\n \/\/ Otherwise simply add to the end of the vector.\n _list.push_back(KeyValuePair(key, value));\n _map[key] = _list.size() - 1;\n }\n\n \/\/ Retrieves the value cached at the key.\n Value& get(const Key& key) {\n auto it = _map.find(key);\n return _list[it->second].second;\n }\n\n bool has(const Key& key) const { return _map.find(key) != _map.end(); }\n\n size_t size() const { return _map.size(); }\n\n void clear() {\n _list.clear();\n _map.clear();\n }\n\n void resize(size_t capacity) {\n while (_list.size() > capacity) {\n _evict();\n }\n\n this->_capacity = capacity;\n _rand = std::uniform_int_distribution<>(0, capacity - 1);\n }\n\n protected:\n \/\/ List to hold all elements.\n std::vector<KeyValuePair> _list;\n\n \/\/ Map to point towards element in the list.\n std::unordered_map<Key, size_t> _map;\n\n \/\/ Random number generation to determine which item to evict.\n std::random_device _rd;\n std::mt19937 _gen;\n std::uniform_int_distribution<> _rand;\n\n void _evict() {\n _map.erase(_list[0].first);\n _list.erase(_list.cbegin());\n }\n};\n\n} \/\/ namespace opossum\n<commit_msg>Add fix for random_cache evict (#925)<commit_after>#pragma once\n\n#include <list>\n#include <random>\n#include <unordered_map>\n#include <utility>\n#include <vector>\n\n#include \"abstract_cache.hpp\"\n\nnamespace opossum {\n\n\/\/ Generic cache implementation using a random eviction policy.\n\/\/ Note: This implementation is not thread-safe.\ntemplate <typename Key, typename Value>\nclass RandomCache : public AbstractCache<Key, Value> {\n public:\n typedef typename std::pair<Key, Value> KeyValuePair;\n\n explicit RandomCache(size_t capacity) : AbstractCache<Key, Value>(capacity), _gen(_rd()), _rand(0, capacity - 1) {\n _list.reserve(capacity);\n }\n\n \/\/ Sets the value to be cached at the given key.\n void set(const Key& key, const Value& value, double cost = 1.0, double size = 1.0) {\n \/\/ Override old element at that key, if it exists.\n auto it = _map.find(key);\n if (it != _map.end()) {\n _list[it->second].second = value;\n return;\n }\n\n \/\/ If capacity is exceeded, pick a random element and replace it.\n if (_list.size() >= this->_capacity) {\n size_t index = _rand(_gen);\n _map.erase(_list[index].first);\n\n _list[index] = KeyValuePair(key, value);\n _map[key] = index;\n return;\n }\n\n \/\/ Otherwise simply add to the end of the vector.\n _list.push_back(KeyValuePair(key, value));\n _map[key] = _list.size() - 1;\n }\n\n \/\/ Retrieves the value cached at the key.\n Value& get(const Key& key) {\n auto it = _map.find(key);\n return _list[it->second].second;\n }\n\n bool has(const Key& key) const { return _map.find(key) != _map.end(); }\n\n size_t size() const { return _map.size(); }\n\n void clear() {\n _list.clear();\n _map.clear();\n }\n\n void resize(size_t capacity) {\n while (_list.size() > capacity) {\n _evict();\n }\n\n this->_capacity = capacity;\n _rand = std::uniform_int_distribution<>(0, capacity - 1);\n }\n\n protected:\n \/\/ List to hold all elements.\n std::vector<KeyValuePair> _list;\n\n \/\/ Map to point towards element in the list.\n std::unordered_map<Key, size_t> _map;\n\n \/\/ Random number generation to determine which item to evict.\n std::random_device _rd;\n std::mt19937 _gen;\n std::uniform_int_distribution<> _rand;\n\n void _evict() {\n _map.erase(_list[0].first);\n _list.erase(_list.cbegin());\n\n for (auto it = _map.cbegin(); it != _map.cend();) {\n _map[it->first] = it->second - 1;\n ++it;\n }\n }\n};\n\n} \/\/ namespace opossum\n<|endoftext|>"} {"text":"<commit_before>#include <bitstring.h>\r\n#include <command.h>\r\n#include <ict.h>\r\n\r\nusing std::cerr;\r\n\r\nvoid out_bits() {\r\n}\r\n\r\ntemplate <typename Op>\r\nvoid time_op(int n, Op op) {\r\n ict::timer time;\r\n time.start();\r\n for (int i = 0; i < n; ++i) op();\r\n time.stop();\r\n cerr << time << '\\n';\r\n};\r\n\r\ntemplate <typename Op, typename EndOp>\r\nvoid time_op(int n, Op op, EndOp end_op) {\r\n ict::timer time;\r\n time.start();\r\n for (int i = 0; i < n; ++i) op();\r\n end_op();\r\n time.stop();\r\n cerr << time << '\\n';\r\n};\r\n\r\nvoid in_bits(int s, int n) {\r\n \/\/ create a giant bitstring\r\n auto bits = ict::random_bitstring(1024);\r\n\r\n time_op(n, [&]() {\r\n ict::ibitstream ibs(bits);\r\n while (!ibs.eobits()) {\r\n auto bits = ibs.read(s);\r\n }\r\n });\r\n}\r\n\r\nvoid out_bits(int s, int n) {\r\n \/\/ create a giant bitstring\r\n auto bits = ict::random_bitstring(s);\r\n\r\n ict::obitstream obs;\r\n time_op(n, \r\n [&]() {\r\n obs << bits;\r\n },\r\n [&]() {\r\n auto x = obs.bits();\r\n }\r\n );\r\n}\r\n\r\nint main(int argc, char **argv) {\r\n bool input = false;\r\n bool output = false;\r\n try {\r\n ict::command line(\"ictperf\", \"ict performance tests\", \"ictperf [options]\");\r\n line.add(ict::option(\"ibits\", 'i', \"input bitstream\", [&]{ input = true; }));\r\n line.add(ict::option(\"obits\", 'o', \"output bitstream\", [&]{ output = true; }));\r\n\r\n line.parse(argc, argv);\r\n if (input) {\r\n in_bits(3, 100000);\r\n in_bits(5, 100000);\r\n in_bits(8, 100000);\r\n in_bits(11, 100000);\r\n };\r\n\r\n if (output) {\r\n out_bits(3, 10000000);\r\n out_bits(5, 10000000);\r\n out_bits(8, 10000000);\r\n out_bits(11, 10000000);\r\n }\r\n } catch (std::exception & e) {\r\n }\r\n\r\n}\r\n<commit_msg>cleaned up perf test<commit_after>#include <bitstring.h>\n#include <command.h>\n#include <ict.h>\n\nusing std::cerr;\n\nvoid out_bits() {}\n\ntemplate <typename Op> void time_op(int n, Op op) {\n ict::timer time;\n time.start();\n for (int i = 0; i < n; ++i)\n op();\n time.stop();\n cerr << time << '\\n';\n}\n\ntemplate <typename Op, typename EndOp>\nvoid time_op(int n, Op op, EndOp end_op) {\n ict::timer time;\n time.start();\n for (int i = 0; i < n; ++i)\n op();\n end_op();\n time.stop();\n cerr << time << '\\n';\n}\n\nvoid in_bits(int s, int n) {\n \/\/ create a giant bitstring\n auto bits = ict::random_bitstring(1024);\n\n time_op(n, [&]() {\n ict::ibitstream ibs(bits);\n while (!ibs.eobits()) {\n auto bits = ibs.read(s);\n }\n });\n}\n\nvoid out_bits(int s, int n) {\n \/\/ create a giant bitstring\n auto bits = ict::random_bitstring(s);\n\n ict::obitstream obs;\n time_op(n, [&]() { obs << bits; }, [&]() { auto x = obs.bits(); });\n}\n\nint main(int argc, char **argv) {\n bool input = false;\n bool output = false;\n try {\n ict::command line(\"ictperf\", \"ict performance tests\",\n \"ictperf [options]\");\n line.add(ict::option(\"ibits\", 'i', \"input bitstream\",\n [&] { input = true; }));\n line.add(ict::option(\"obits\", 'o', \"output bitstream\",\n [&] { output = true; }));\n\n line.parse(argc, argv);\n if (input) {\n in_bits(3, 100000);\n in_bits(5, 100000);\n in_bits(8, 100000);\n in_bits(11, 100000);\n };\n\n if (output) {\n out_bits(3, 10000000);\n out_bits(5, 10000000);\n out_bits(8, 10000000);\n out_bits(11, 10000000);\n }\n } catch (std::exception &e) {\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: generalpage.hxx,v $\n *\n * $Revision: 1.14 $\n *\n * last change: $Author: kz $ $Date: 2005-06-30 16:33:40 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc..\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef _DBAUI_GENERALPAGE_HXX_\n#define _DBAUI_GENERALPAGE_HXX_\n\n#ifndef _DBAUI_ADMINPAGES_HXX_\n#include \"adminpages.hxx\"\n#endif\n#ifndef DBACCESS_SOURCE_UI_INC_OPENDOCCONTROLS_HXX\n#include \"opendoccontrols.hxx\"\n#endif\n#ifndef _SV_FIXED_HXX\n#include <vcl\/fixed.hxx>\n#endif\n#ifndef _SV_LSTBOX_HXX\n#include <vcl\/lstbox.hxx>\n#endif\n#ifndef _SV_EDIT_HXX\n#include <vcl\/edit.hxx>\n#endif\n#include <memory>\n\n\/\/.........................................................................\nnamespace dbaui\n{\n\/\/.........................................................................\n class IAdminHelper;\n class RadioDependentEnabler;\n \/\/=========================================================================\n \/\/= OGeneralPage\n \/\/=========================================================================\n class OGeneralPage : public OGenericAdministrationPage\n {\n OGeneralPage(Window* pParent, const SfxItemSet& _rItems, sal_Bool _bDBWizardMode = sal_False);\n ~OGeneralPage();\n\n public:\n enum CreationMode\n {\n eCreateNew,\n eConnectExternal,\n eOpenExisting\n };\n\n struct DocumentDescriptor\n {\n String sURL;\n String sFilter;\n };\n\n private:\n \/\/ dialog controls\n FixedText m_aFTHeaderText;\n FixedText m_aFTHelpText;\n FixedText m_aFT_DatasourceTypeHeader;\n RadioButton m_aRB_CreateDatabase;\n RadioButton m_aRB_OpenDocument;\n RadioButton m_aRB_GetExistingDatabase;\n FixedText m_aFT_DocListLabel;\n ::std::auto_ptr< OpenDocumentListBox >\n m_pLB_DocumentList;\n OpenDocumentButton m_aPB_OpenDocument;\n FixedText m_aTypePreLabel;\n FixedText m_aDatasourceTypeLabel;\n ListBox m_aDatasourceType;\n FixedText m_aFTDataSourceAppendix;\n FixedText m_aTypePostLabel;\n FixedText m_aSpecialMessage;\n sal_Bool m_DBWizardMode;\n String m_sMySQLEntry;\n CreationMode m_eOriginalCreationMode;\n DocumentDescriptor m_aBrowsedDocument;\n\n ::std::auto_ptr< RadioDependentEnabler >\n m_pSelectTypeController;\n ::std::auto_ptr< RadioDependentEnabler >\n m_pOpenDocController;\n\n\n ODsnTypeCollection* m_pCollection; \/\/\/ the DSN type collection instance\n DECLARE_STL_MAP(DATASOURCE_TYPE, String, ::std::less< DATASOURCE_TYPE >, SelectionHistory);\n DATASOURCE_TYPE m_eCurrentSelection; \/\/\/ currently selected type\n DATASOURCE_TYPE m_eNotSupportedKnownType; \/\/\/ if a data source of an unsupported, but known type is encountered ....\n SelectionHistory m_aSelectionHistory; \/\/\/ last selected ConnectURLs for all types\n\n enum SPECIAL_MESSAGE\n {\n smNone,\n smUnsupportedType\n };\n SPECIAL_MESSAGE m_eLastMessage;\n\n Link m_aTypeSelectHandler; \/\/\/ to be called if a new type is selected\n Link m_aCreationModeHandler; \/\/\/ to be called if a new type is selected\n Link m_aDocumentSelectionHandler; \/\/\/ to be called when a document in the RecentDoc list is selected\n Link m_aChooseDocumentHandler; \/\/\/ to be called when a recent document has been definately chosen\n sal_Bool m_bDisplayingInvalid : 1; \/\/ the currently displayed data source is deleted\n sal_Bool m_bUserGrabFocus : 1;\n String VerifyDisplayName(DATASOURCE_TYPE eType, String _sDisplayName);\n void insertDatasourceTypeEntryData(DATASOURCE_TYPE eType, String sDisplayName);\n\n public:\n static SfxTabPage* Create(Window* pParent, const SfxItemSet& _rAttrSet, sal_Bool _bDBWizardMode = sal_False);\n\n \/\/\/ set a handler which gets called every time the user selects a new type\n void SetTypeSelectHandler(const Link& _rHandler) { m_aTypeSelectHandler = _rHandler; }\n void SetCreationModeHandler(const Link& _rHandler) { m_aCreationModeHandler = _rHandler; }\n void SetDocumentSelectionHandler( const Link& _rHandler) { m_aDocumentSelectionHandler = _rHandler; }\n void SetChooseDocumentHandler( const Link& _rHandler) { m_aChooseDocumentHandler = _rHandler; }\n CreationMode GetDatabaseCreationMode() const;\n\n DocumentDescriptor GetSelectedDocument() const;\n\n \/\/\/ get the currently selected datasource type\n DATASOURCE_TYPE GetSelectedType() const { return m_eCurrentSelection; }\n\n protected:\n \/\/ SfxTabPage overridables\n virtual BOOL FillItemSet(SfxItemSet& _rCoreAttrs);\n virtual void Reset(const SfxItemSet& _rCoreAttrs);\n\n virtual void implInitControls(const SfxItemSet& _rSet, sal_Bool _bSaveValue);\n\n virtual void GetFocus();\n\n \/\/ <method>OGenericAdministrationPage::fillControls<\/method>\n virtual void fillControls(::std::vector< ISaveValueWrapper* >& _rControlList);\n \/\/ <method>OGenericAdministrationPage::fillWindows<\/method>\n virtual void fillWindows(::std::vector< ISaveValueWrapper* >& _rControlList);\n\n protected:\n\n void onTypeSelected(const DATASOURCE_TYPE _eType);\n void initializeHistory();\n void initializeTypeList();\n\n void implSetCurrentType( const DATASOURCE_TYPE _eType );\n\n void switchMessage(sal_Bool _bDeleted,const DATASOURCE_TYPE _eType);\n\n \/\/\/ sets the the title of the parent dialog\n void setParentTitle(DATASOURCE_TYPE _eSelectedType);\n\n DECL_LINK(OnDatasourceTypeSelected, ListBox*);\n DECL_LINK(OnSetupModeSelected, RadioButton*);\n DECL_LINK(OnDocumentSelected, ListBox*);\n DECL_LINK(OnOpenDocument, PushButton*);\n };\n\n\/\/.........................................................................\n} \/\/ namespace dbaui\n\/\/.........................................................................\n#endif \/\/ _DBAUI_GENERALPAGE_HXX_\n<commit_msg>INTEGRATION: CWS dba20blocker (1.13.134); FILE MERGED 2005\/07\/04 08:25:59 fs 1.13.134.2: RESYNC: (1.13-1.14); FILE MERGED 2005\/06\/23 15:22:37 fs 1.13.134.1: copying fix for #i45899# into this CWS<commit_after>\/*************************************************************************\n *\n * $RCSfile: generalpage.hxx,v $\n *\n * $Revision: 1.15 $\n *\n * last change: $Author: obo $ $Date: 2005-07-08 10:39:24 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc..\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef _DBAUI_GENERALPAGE_HXX_\n#define _DBAUI_GENERALPAGE_HXX_\n\n#ifndef _DBAUI_ADMINPAGES_HXX_\n#include \"adminpages.hxx\"\n#endif\n#ifndef DBACCESS_SOURCE_UI_INC_OPENDOCCONTROLS_HXX\n#include \"opendoccontrols.hxx\"\n#endif\n#ifndef _SV_FIXED_HXX\n#include <vcl\/fixed.hxx>\n#endif\n#ifndef _SV_LSTBOX_HXX\n#include <vcl\/lstbox.hxx>\n#endif\n#ifndef _SV_EDIT_HXX\n#include <vcl\/edit.hxx>\n#endif\n#include <memory>\n\n\/\/.........................................................................\nnamespace dbaui\n{\n\/\/.........................................................................\n class IAdminHelper;\n class RadioDependentEnabler;\n \/\/=========================================================================\n \/\/= OGeneralPage\n \/\/=========================================================================\n class OGeneralPage : public OGenericAdministrationPage\n {\n OGeneralPage(Window* pParent, const SfxItemSet& _rItems, sal_Bool _bDBWizardMode = sal_False);\n ~OGeneralPage();\n\n public:\n enum CreationMode\n {\n eCreateNew,\n eConnectExternal,\n eOpenExisting\n };\n\n struct DocumentDescriptor\n {\n String sURL;\n String sFilter;\n };\n\n private:\n \/\/ dialog controls\n FixedText m_aFTHeaderText;\n FixedText m_aFTHelpText;\n FixedText m_aFT_DatasourceTypeHeader;\n RadioButton m_aRB_CreateDatabase;\n RadioButton m_aRB_OpenDocument;\n RadioButton m_aRB_GetExistingDatabase;\n FixedText m_aFT_DocListLabel;\n ::std::auto_ptr< OpenDocumentListBox >\n m_pLB_DocumentList;\n OpenDocumentButton m_aPB_OpenDocument;\n FixedText m_aTypePreLabel;\n FixedText m_aDatasourceTypeLabel;\n ::std::auto_ptr< ListBox >\n m_pDatasourceType;\n FixedText m_aFTDataSourceAppendix;\n FixedText m_aTypePostLabel;\n FixedText m_aSpecialMessage;\n sal_Bool m_DBWizardMode;\n String m_sMySQLEntry;\n CreationMode m_eOriginalCreationMode;\n DocumentDescriptor m_aBrowsedDocument;\n\n ::std::auto_ptr< RadioDependentEnabler >\n m_pSelectTypeController;\n ::std::auto_ptr< RadioDependentEnabler >\n m_pOpenDocController;\n\n\n ODsnTypeCollection* m_pCollection; \/\/\/ the DSN type collection instance\n DECLARE_STL_MAP(DATASOURCE_TYPE, String, ::std::less< DATASOURCE_TYPE >, SelectionHistory);\n DATASOURCE_TYPE m_eCurrentSelection; \/\/\/ currently selected type\n DATASOURCE_TYPE m_eNotSupportedKnownType; \/\/\/ if a data source of an unsupported, but known type is encountered ....\n SelectionHistory m_aSelectionHistory; \/\/\/ last selected ConnectURLs for all types\n\n enum SPECIAL_MESSAGE\n {\n smNone,\n smUnsupportedType\n };\n SPECIAL_MESSAGE m_eLastMessage;\n\n Link m_aTypeSelectHandler; \/\/\/ to be called if a new type is selected\n Link m_aCreationModeHandler; \/\/\/ to be called if a new type is selected\n Link m_aDocumentSelectionHandler; \/\/\/ to be called when a document in the RecentDoc list is selected\n Link m_aChooseDocumentHandler; \/\/\/ to be called when a recent document has been definately chosen\n sal_Bool m_bDisplayingInvalid : 1; \/\/ the currently displayed data source is deleted\n sal_Bool m_bUserGrabFocus : 1;\n String VerifyDisplayName(DATASOURCE_TYPE eType, String _sDisplayName);\n void insertDatasourceTypeEntryData(DATASOURCE_TYPE eType, String sDisplayName);\n\n public:\n static SfxTabPage* Create(Window* pParent, const SfxItemSet& _rAttrSet, sal_Bool _bDBWizardMode = sal_False);\n\n \/\/\/ set a handler which gets called every time the user selects a new type\n void SetTypeSelectHandler(const Link& _rHandler) { m_aTypeSelectHandler = _rHandler; }\n void SetCreationModeHandler(const Link& _rHandler) { m_aCreationModeHandler = _rHandler; }\n void SetDocumentSelectionHandler( const Link& _rHandler) { m_aDocumentSelectionHandler = _rHandler; }\n void SetChooseDocumentHandler( const Link& _rHandler) { m_aChooseDocumentHandler = _rHandler; }\n CreationMode GetDatabaseCreationMode() const;\n\n DocumentDescriptor GetSelectedDocument() const;\n\n \/\/\/ get the currently selected datasource type\n DATASOURCE_TYPE GetSelectedType() const { return m_eCurrentSelection; }\n\n protected:\n \/\/ SfxTabPage overridables\n virtual BOOL FillItemSet(SfxItemSet& _rCoreAttrs);\n virtual void Reset(const SfxItemSet& _rCoreAttrs);\n\n virtual void implInitControls(const SfxItemSet& _rSet, sal_Bool _bSaveValue);\n\n virtual void GetFocus();\n\n \/\/ <method>OGenericAdministrationPage::fillControls<\/method>\n virtual void fillControls(::std::vector< ISaveValueWrapper* >& _rControlList);\n \/\/ <method>OGenericAdministrationPage::fillWindows<\/method>\n virtual void fillWindows(::std::vector< ISaveValueWrapper* >& _rControlList);\n\n protected:\n\n void onTypeSelected(const DATASOURCE_TYPE _eType);\n void initializeHistory();\n void initializeTypeList();\n\n void implSetCurrentType( const DATASOURCE_TYPE _eType );\n\n void switchMessage(sal_Bool _bDeleted,const DATASOURCE_TYPE _eType);\n\n \/\/\/ sets the the title of the parent dialog\n void setParentTitle(DATASOURCE_TYPE _eSelectedType);\n\n DECL_LINK(OnDatasourceTypeSelected, ListBox*);\n DECL_LINK(OnSetupModeSelected, RadioButton*);\n DECL_LINK(OnDocumentSelected, ListBox*);\n DECL_LINK(OnOpenDocument, PushButton*);\n };\n\n\/\/.........................................................................\n} \/\/ namespace dbaui\n\/\/.........................................................................\n#endif \/\/ _DBAUI_GENERALPAGE_HXX_\n<|endoftext|>"} {"text":"<commit_before>\n#pragma once\n\n#include <functional>\n\n#include \"geometry\/hilbert.hpp\"\n#include \"quantities\/named_quantities.hpp\"\n#include \"quantities\/quantities.hpp\"\n\nnamespace principia {\nnamespace numerics {\nnamespace internal_gradient_descent {\n\nusing geometry::Hilbert;\nusing quantities::Difference;\nusing quantities::Length;\nusing quantities::Product;\nusing quantities::Quotient;\n\n\/\/ In this file |Argument| must be a 3-dimensional entity.\n\ntemplate<typename Scalar, typename Argument>\nusing Field = std::function<Scalar(Argument const&)>;\n\ntemplate<typename Scalar, typename Argument>\nusing Gradient =\n Product<Scalar,\n Quotient<Difference<Argument>,\n typename Hilbert<Difference<Argument>>::NormType>>;\n\ntemplate<typename Scalar, typename Argument>\nArgument BroydenFletcherGoldfarbShanno(\n Argument const& start_argument,\n Field<Scalar, Argument> const& f,\n Field<Gradient<Scalar, Argument>, Argument> const& grad_f,\n Length const& tolerance);\n\n} \/\/ namespace internal_gradient_descent\n\nusing internal_gradient_descent::BroydenFletcherGoldfarbShanno;\n\n} \/\/ namespace numerics\n} \/\/ namespace principia\n\n#include \"numerics\/gradient_descent_body.hpp\"\n<commit_msg>Comment.<commit_after>\n#pragma once\n\n#include <functional>\n\n#include \"geometry\/hilbert.hpp\"\n#include \"quantities\/named_quantities.hpp\"\n#include \"quantities\/quantities.hpp\"\n\nnamespace principia {\nnamespace numerics {\nnamespace internal_gradient_descent {\n\nusing geometry::Hilbert;\nusing quantities::Difference;\nusing quantities::Length;\nusing quantities::Product;\nusing quantities::Quotient;\n\n\/\/ In this file |Argument| must be such that its difference belongs to a Hilbert\n\/\/ space.\n\ntemplate<typename Scalar, typename Argument>\nusing Field = std::function<Scalar(Argument const&)>;\n\ntemplate<typename Scalar, typename Argument>\nusing Gradient =\n Product<Scalar,\n Quotient<Difference<Argument>,\n typename Hilbert<Difference<Argument>>::NormType>>;\n\ntemplate<typename Scalar, typename Argument>\nArgument BroydenFletcherGoldfarbShanno(\n Argument const& start_argument,\n Field<Scalar, Argument> const& f,\n Field<Gradient<Scalar, Argument>, Argument> const& grad_f,\n Length const& tolerance);\n\n} \/\/ namespace internal_gradient_descent\n\nusing internal_gradient_descent::BroydenFletcherGoldfarbShanno;\n\n} \/\/ namespace numerics\n} \/\/ namespace principia\n\n#include \"numerics\/gradient_descent_body.hpp\"\n<|endoftext|>"} {"text":"<commit_before>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Copyright 2015 Realm Inc.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#ifndef REALM_PROPERTY_HPP\n#define REALM_PROPERTY_HPP\n\n#include <string>\n\nnamespace realm {\n enum PropertyType {\n \/** Integer type: NSInteger, int, long, Int (Swift) *\/\n PropertyTypeInt = 0,\n \/** Boolean type: BOOL, bool, Bool (Swift) *\/\n PropertyTypeBool = 1,\n \/** Float type: CGFloat (32bit), float, Float (Swift) *\/\n PropertyTypeFloat = 9,\n \/** Double type: CGFloat (64bit), double, Double (Swift) *\/\n PropertyTypeDouble = 10,\n \/** String type: NSString, String (Swift) *\/\n PropertyTypeString = 2,\n \/** Data type: NSData *\/\n PropertyTypeData = 4,\n \/** Any type: id, **not supported in Swift** *\/\n PropertyTypeAny = 6,\n \/** Date type: NSDate *\/\n PropertyTypeDate = 7,\n \/** Object type. See [Realm Models](http:\/\/realm.io\/docs\/cocoa\/latest\/#models) *\/\n PropertyTypeObject = 12,\n \/** Array type. See [Realm Models](http:\/\/realm.io\/docs\/cocoa\/latest\/#models) *\/\n PropertyTypeArray = 13,\n };\n\n struct Property {\n public:\n Property() : object_type(\"\"), is_primary(false), is_indexed(false), is_nullable(false) {}\n\n std::string name;\n PropertyType type;\n std::string object_type;\n bool is_primary;\n bool is_indexed;\n bool is_nullable;\n\n size_t table_column;\n bool requires_index() { return is_primary || is_indexed; }\n };\n\n static inline const char *string_for_property_type(PropertyType type) {\n switch (type) {\n case PropertyTypeString:\n return \"string\";\n case PropertyTypeInt:\n return \"int\";\n case PropertyTypeBool:\n return \"bool\";\n case PropertyTypeDate:\n return \"date\";\n case PropertyTypeData:\n return \"data\";\n case PropertyTypeDouble:\n return \"double\";\n case PropertyTypeFloat:\n return \"float\";\n case PropertyTypeAny:\n return \"any\";\n case PropertyTypeObject:\n return \"object\";\n case PropertyTypeArray:\n return \"array\";\n }\n }\n}\n\n#endif \/* REALM_PROPERTY_HPP *\/\n<commit_msg>Use NSDMIs for realm::Property<commit_after>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Copyright 2015 Realm Inc.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#ifndef REALM_PROPERTY_HPP\n#define REALM_PROPERTY_HPP\n\n#include <string>\n\nnamespace realm {\n enum PropertyType {\n \/** Integer type: NSInteger, int, long, Int (Swift) *\/\n PropertyTypeInt = 0,\n \/** Boolean type: BOOL, bool, Bool (Swift) *\/\n PropertyTypeBool = 1,\n \/** Float type: CGFloat (32bit), float, Float (Swift) *\/\n PropertyTypeFloat = 9,\n \/** Double type: CGFloat (64bit), double, Double (Swift) *\/\n PropertyTypeDouble = 10,\n \/** String type: NSString, String (Swift) *\/\n PropertyTypeString = 2,\n \/** Data type: NSData *\/\n PropertyTypeData = 4,\n \/** Any type: id, **not supported in Swift** *\/\n PropertyTypeAny = 6,\n \/** Date type: NSDate *\/\n PropertyTypeDate = 7,\n \/** Object type. See [Realm Models](http:\/\/realm.io\/docs\/cocoa\/latest\/#models) *\/\n PropertyTypeObject = 12,\n \/** Array type. See [Realm Models](http:\/\/realm.io\/docs\/cocoa\/latest\/#models) *\/\n PropertyTypeArray = 13,\n };\n\n struct Property {\n std::string name;\n PropertyType type;\n std::string object_type;\n bool is_primary = false;\n bool is_indexed = false;\n bool is_nullable = false;\n\n size_t table_column;\n bool requires_index() { return is_primary || is_indexed; }\n };\n\n static inline const char *string_for_property_type(PropertyType type) {\n switch (type) {\n case PropertyTypeString:\n return \"string\";\n case PropertyTypeInt:\n return \"int\";\n case PropertyTypeBool:\n return \"bool\";\n case PropertyTypeDate:\n return \"date\";\n case PropertyTypeData:\n return \"data\";\n case PropertyTypeDouble:\n return \"double\";\n case PropertyTypeFloat:\n return \"float\";\n case PropertyTypeAny:\n return \"any\";\n case PropertyTypeObject:\n return \"object\";\n case PropertyTypeArray:\n return \"array\";\n }\n }\n}\n\n#endif \/* REALM_PROPERTY_HPP *\/\n<|endoftext|>"} {"text":"<commit_before>\/*\n * projectM -- Milkdrop-esque visualisation SDK\n * Copyright (C)2003-2007 projectM Team\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n * See 'LICENSE.txt' included within this release\n *\n *\/\n\/**\n * $Id: projectM.hpp,v 1.1.1.1 2005\/12\/23 18:05:11 psperl Exp $\n *\n * Encapsulation of ProjectM engine\n *\n * $Log$\n *\/\n\n#ifndef _PROJECTM_HPP\n#define _PROJECTM_HPP\n\n#ifdef WIN32\n#include \"win32-dirent.h\"\n#else\n#include <dirent.h>\n#endif \/** WIN32 *\/\n#include <cmath>\n#include <cstdio>\n#include <string>\n#include <cstdlib>\n#ifndef WIN32\n#include <unistd.h>\n#endif\n#include <sys\/types.h>\n\n#ifdef MACOS\n\/\/#include <MacWindows.h>\n\/\/#include <gl.h>\n\/\/#include <glu.h>\n#else\n#ifdef WIN32\n#include <windows.h>\n#endif \/** WIN32 *\/\n\n#endif \/** MACOS *\/\n#ifdef WIN322\n#define inline\n#endif \/** WIN32 *\/\n\n#include \"dlldefs.h\"\n#include \"event.h\"\n#include \"fatal.h\"\n#include \"PCM.hpp\"\n#include \"pthread.h\"\nclass PipelineContext;\n\n#include <memory>\n\nclass BeatDetect;\nclass PCM;\nclass Func;\nclass Renderer;\nclass Preset;\nclass PresetIterator;\nclass PresetChooser;\nclass PresetLoader;\nclass TimeKeeper;\nclass Pipeline;\nclass RenderItemMatcher;\nclass MasterRenderItemMerge;\n\n#include <memory>\n#ifdef WIN32\n#pragma warning (disable:4244)\n#pragma warning (disable:4305)\n#endif \/** WIN32 *\/\n\n#ifdef MACOS2\n#define inline\n#endif\n\n\/** KEEP THIS UP TO DATE! *\/\n#define PROJECTM_VERSION \"1.1.00\"\n#define PROJECTM_TITLE \"projectM 1.1.00\"\n\n\/** Interface types *\/\ntypedef enum {\n MENU_INTERFACE,\n SHELL_INTERFACE,\n EDITOR_INTERFACE,\n DEFAULT_INTERFACE,\n BROWSER_INTERFACE\n } interface_t;\n\n\/\/\/ A functor class that allows users of this library to specify random preset behavior\nclass RandomizerFunctor {\n\n public:\n\tRandomizerFunctor(PresetChooser & chooser) ;\n\tvirtual ~RandomizerFunctor();\n \tvirtual double operator() (int index);\n private:\n\tconst PresetChooser & m_chooser;\n};\n\n\nclass DLLEXPORT projectM\n{\npublic:\n\tstatic const int FLAG_NONE = 0;\n\tstatic const int FLAG_DISABLE_PLAYLIST_LOAD = 1 << 0;\n\n struct Settings {\n int meshX;\n int meshY;\n int fps;\n int textureSize;\n int windowWidth;\n int windowHeight;\n std::string presetURL;\n std::string titleFontURL;\n std::string menuFontURL;\n int smoothPresetDuration;\n int presetDuration;\n float beatSensitivity;\n bool aspectCorrection;\n float easterEgg;\n bool shuffleEnabled;\n };\n\n projectM(std::string config_file, int flags = FLAG_NONE);\n projectM(Settings settings, int flags = FLAG_NONE);\n\n \/\/DLLEXPORT projectM(int gx, int gy, int fps, int texsize, int width, int height,std::string preset_url,std::string title_fonturl, std::string title_menuurl);\n\n void projectM_resetGL( int width, int height );\n void projectM_resetTextures();\n void projectM_setTitle( std::string title );\n void renderFrame();\n unsigned initRenderToTexture();\n void key_handler( projectMEvent event,\n\t\t projectMKeycode keycode, projectMModifier modifier );\n\n virtual ~projectM();\n\n\n\n\n\n const Settings & settings() const {\n\t\treturn _settings;\n }\n\n \/\/\/ Writes a settings configuration to the specified file\n static bool writeConfig(const std::string & configFile, const Settings & settings);\n\n\n \/\/\/ Sets preset iterator position to the passed in index\n void selectPresetPosition(unsigned int index);\n\n \/\/\/ Plays a preset immediately\n void selectPreset(unsigned int index, bool hardCut = true);\n\n \/\/\/ Removes a preset from the play list. If it is playing then it will continue as normal until next switch\n void removePreset(unsigned int index);\n\n \/\/\/ Sets the randomization functor. If set to null, the traversal will move in order according to the playlist\n void setRandomizer(RandomizerFunctor * functor);\n\n \/\/\/ Tell projectM to play a particular preset when it chooses to switch\n \/\/\/ If the preset is locked the queued item will be not switched to until the lock is released\n \/\/\/ Subsequent calls to this function effectively nullifies previous calls.\n void queuePreset(unsigned int index);\n\n \/\/\/ Returns true if a preset is queued up to play next\n bool isPresetQueued() const;\n\n \/\/\/ Removes entire playlist, The currently loaded preset will end up sticking until new presets are added\n void clearPlaylist();\n\n \/\/\/ Turn on or off a lock that prevents projectM from switching to another preset\n void setPresetLock(bool isLocked);\n\n \/\/\/ Returns true if the active preset is locked\n bool isPresetLocked() const;\n\n \/\/\/ Returns index of currently active preset. In the case where the active\n \/\/\/ preset was removed from the playlist, this function will return the element\n \/\/\/ before active preset (thus the next in order preset is invariant with respect\n \/\/\/ to the removal)\n bool selectedPresetIndex(unsigned int & index) const;\n\n \/\/\/ Add a preset url to the play list. Appended to bottom. Returns index of preset\n unsigned int addPresetURL(const std::string & presetURL, const std::string & presetName, int rating);\n\n \/\/\/ Insert a preset url to the play list at the suggested index.\n void insertPresetURL(unsigned int index,\n\t\t\t const std::string & presetURL, const std::string & presetName, int rating);\n\n \/\/\/ Returns true if the selected preset position points to an actual preset in the\n \/\/\/ currently loaded playlist\n bool presetPositionValid() const;\n\n \/\/\/ Returns the url associated with a preset index\n std::string getPresetURL(unsigned int index) const;\n\n \/\/\/ Returns the preset name associated with a preset index\n std::string getPresetName ( unsigned int index ) const;\n\n \/\/\/ Returns the rating associated with a preset index\n int getPresetRating (unsigned int index) const;\n\n void changePresetRating (unsigned int index, int rating);\n\n \/\/\/ Returns the size of the play list\n unsigned int getPlaylistSize() const;\n\n void evaluateSecondPreset();\n\n inline void setShuffleEnabled(bool value)\n {\n\t _settings.shuffleEnabled = value;\n\n\t\/\/\/ idea@ call a virtualfunction shuffleChanged()\n }\n\n\n inline bool isShuffleEnabled() const\n {\n\treturn _settings.shuffleEnabled;\n }\n\n \/\/\/ Occurs when active preset has switched. Switched to index is returned\n virtual void presetSwitchedEvent(bool isHardCut, unsigned int index) const {};\n virtual void shuffleEnabledValueChanged(bool isEnabled) const {};\n\n\n inline PCM * pcm() {\n\t return _pcm;\n }\n void *thread_func(void *vptr_args);\n PipelineContext & pipelineContext() { return *_pipelineContext; }\n PipelineContext & pipelineContext2() { return *_pipelineContext2; }\n\nprivate:\n PCM * _pcm;\n double sampledPresetDuration();\n BeatDetect * beatDetect;\n Renderer *renderer;\n PipelineContext * _pipelineContext;\n PipelineContext * _pipelineContext2;\n Settings _settings;\n\n\n int wvw; \/\/windowed dimensions\n int wvh;\n\n \/** Timing information *\/\n int mspf;\n int timed;\n int timestart;\n int count;\n float fpsstart;\n\n void readConfig(const std::string &configFile);\n void readSettings(const Settings &settings);\n void projectM_init(int gx, int gy, int fps, int texsize, int width, int height);\n void projectM_reset();\n void selectPrevious(const bool);\n void selectNext(const bool);\n void selectRandom(const bool);\n\n void projectM_initengine();\n void projectM_resetengine();\n\n \/\/\/ Initializes preset loading \/ management libraries\n int initPresetTools(int gx, int gy);\n\n \/\/\/ Deinitialize all preset related tools. Usually done before projectM cleanup\n void destroyPresetTools();\n\n void default_key_handler( projectMEvent event, projectMKeycode keycode );\n \/\/\/ The current position of the directory iterator\n PresetIterator * m_presetPos;\n\n \/\/\/ Required by the preset chooser. Manages a loaded preset directory\n PresetLoader * m_presetLoader;\n\n \/\/\/ Provides accessor functions to choose presets\n PresetChooser * m_presetChooser;\n\n \/\/\/ Currently loaded preset\n std::auto_ptr<Preset> m_activePreset;\n\n \/\/\/ Destination preset when smooth preset switching\n std::auto_ptr<Preset> m_activePreset2;\n\n TimeKeeper *timeKeeper;\n\n int m_flags;\n\n RenderItemMatcher * _matcher;\n MasterRenderItemMerge * _merger;\n pthread_mutex_t mutex;\n pthread_cond_t condition;\n pthread_t thread;\n bool running;\n\n Pipeline* currentPipe;\n\nvoid switchPreset(std::auto_ptr<Preset> & targetPreset);\n\n\n};\n#endif\n<commit_msg>version bump.<commit_after>\/*\n * projectM -- Milkdrop-esque visualisation SDK\n * Copyright (C)2003-2007 projectM Team\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n * See 'LICENSE.txt' included within this release\n *\n *\/\n\/**\n * $Id: projectM.hpp,v 1.1.1.1 2005\/12\/23 18:05:11 psperl Exp $\n *\n * Encapsulation of ProjectM engine\n *\n * $Log$\n *\/\n\n#ifndef _PROJECTM_HPP\n#define _PROJECTM_HPP\n\n#ifdef WIN32\n#include \"win32-dirent.h\"\n#else\n#include <dirent.h>\n#endif \/** WIN32 *\/\n#include <cmath>\n#include <cstdio>\n#include <string>\n#include <cstdlib>\n#ifndef WIN32\n#include <unistd.h>\n#endif\n#include <sys\/types.h>\n\n#ifdef MACOS\n\/\/#include <MacWindows.h>\n\/\/#include <gl.h>\n\/\/#include <glu.h>\n#else\n#ifdef WIN32\n#include <windows.h>\n#endif \/** WIN32 *\/\n\n#endif \/** MACOS *\/\n#ifdef WIN322\n#define inline\n#endif \/** WIN32 *\/\n\n#include \"dlldefs.h\"\n#include \"event.h\"\n#include \"fatal.h\"\n#include \"PCM.hpp\"\n#include \"pthread.h\"\nclass PipelineContext;\n\n#include <memory>\n\nclass BeatDetect;\nclass PCM;\nclass Func;\nclass Renderer;\nclass Preset;\nclass PresetIterator;\nclass PresetChooser;\nclass PresetLoader;\nclass TimeKeeper;\nclass Pipeline;\nclass RenderItemMatcher;\nclass MasterRenderItemMerge;\n\n#include <memory>\n#ifdef WIN32\n#pragma warning (disable:4244)\n#pragma warning (disable:4305)\n#endif \/** WIN32 *\/\n\n#ifdef MACOS2\n#define inline\n#endif\n\n\/** KEEP THIS UP TO DATE! *\/\n#define PROJECTM_VERSION \"2.0.00\"\n#define PROJECTM_TITLE \"projectM 2.0.00\"\n\n\/** Interface types *\/\ntypedef enum {\n MENU_INTERFACE,\n SHELL_INTERFACE,\n EDITOR_INTERFACE,\n DEFAULT_INTERFACE,\n BROWSER_INTERFACE\n } interface_t;\n\n\/\/\/ A functor class that allows users of this library to specify random preset behavior\nclass RandomizerFunctor {\n\n public:\n\tRandomizerFunctor(PresetChooser & chooser) ;\n\tvirtual ~RandomizerFunctor();\n \tvirtual double operator() (int index);\n private:\n\tconst PresetChooser & m_chooser;\n};\n\n\nclass DLLEXPORT projectM\n{\npublic:\n\tstatic const int FLAG_NONE = 0;\n\tstatic const int FLAG_DISABLE_PLAYLIST_LOAD = 1 << 0;\n\n struct Settings {\n int meshX;\n int meshY;\n int fps;\n int textureSize;\n int windowWidth;\n int windowHeight;\n std::string presetURL;\n std::string titleFontURL;\n std::string menuFontURL;\n int smoothPresetDuration;\n int presetDuration;\n float beatSensitivity;\n bool aspectCorrection;\n float easterEgg;\n bool shuffleEnabled;\n };\n\n projectM(std::string config_file, int flags = FLAG_NONE);\n projectM(Settings settings, int flags = FLAG_NONE);\n\n \/\/DLLEXPORT projectM(int gx, int gy, int fps, int texsize, int width, int height,std::string preset_url,std::string title_fonturl, std::string title_menuurl);\n\n void projectM_resetGL( int width, int height );\n void projectM_resetTextures();\n void projectM_setTitle( std::string title );\n void renderFrame();\n unsigned initRenderToTexture();\n void key_handler( projectMEvent event,\n\t\t projectMKeycode keycode, projectMModifier modifier );\n\n virtual ~projectM();\n\n\n\n\n\n const Settings & settings() const {\n\t\treturn _settings;\n }\n\n \/\/\/ Writes a settings configuration to the specified file\n static bool writeConfig(const std::string & configFile, const Settings & settings);\n\n\n \/\/\/ Sets preset iterator position to the passed in index\n void selectPresetPosition(unsigned int index);\n\n \/\/\/ Plays a preset immediately\n void selectPreset(unsigned int index, bool hardCut = true);\n\n \/\/\/ Removes a preset from the play list. If it is playing then it will continue as normal until next switch\n void removePreset(unsigned int index);\n\n \/\/\/ Sets the randomization functor. If set to null, the traversal will move in order according to the playlist\n void setRandomizer(RandomizerFunctor * functor);\n\n \/\/\/ Tell projectM to play a particular preset when it chooses to switch\n \/\/\/ If the preset is locked the queued item will be not switched to until the lock is released\n \/\/\/ Subsequent calls to this function effectively nullifies previous calls.\n void queuePreset(unsigned int index);\n\n \/\/\/ Returns true if a preset is queued up to play next\n bool isPresetQueued() const;\n\n \/\/\/ Removes entire playlist, The currently loaded preset will end up sticking until new presets are added\n void clearPlaylist();\n\n \/\/\/ Turn on or off a lock that prevents projectM from switching to another preset\n void setPresetLock(bool isLocked);\n\n \/\/\/ Returns true if the active preset is locked\n bool isPresetLocked() const;\n\n \/\/\/ Returns index of currently active preset. In the case where the active\n \/\/\/ preset was removed from the playlist, this function will return the element\n \/\/\/ before active preset (thus the next in order preset is invariant with respect\n \/\/\/ to the removal)\n bool selectedPresetIndex(unsigned int & index) const;\n\n \/\/\/ Add a preset url to the play list. Appended to bottom. Returns index of preset\n unsigned int addPresetURL(const std::string & presetURL, const std::string & presetName, int rating);\n\n \/\/\/ Insert a preset url to the play list at the suggested index.\n void insertPresetURL(unsigned int index,\n\t\t\t const std::string & presetURL, const std::string & presetName, int rating);\n\n \/\/\/ Returns true if the selected preset position points to an actual preset in the\n \/\/\/ currently loaded playlist\n bool presetPositionValid() const;\n\n \/\/\/ Returns the url associated with a preset index\n std::string getPresetURL(unsigned int index) const;\n\n \/\/\/ Returns the preset name associated with a preset index\n std::string getPresetName ( unsigned int index ) const;\n\n \/\/\/ Returns the rating associated with a preset index\n int getPresetRating (unsigned int index) const;\n\n void changePresetRating (unsigned int index, int rating);\n\n \/\/\/ Returns the size of the play list\n unsigned int getPlaylistSize() const;\n\n void evaluateSecondPreset();\n\n inline void setShuffleEnabled(bool value)\n {\n\t _settings.shuffleEnabled = value;\n\n\t\/\/\/ idea@ call a virtualfunction shuffleChanged()\n }\n\n\n inline bool isShuffleEnabled() const\n {\n\treturn _settings.shuffleEnabled;\n }\n\n \/\/\/ Occurs when active preset has switched. Switched to index is returned\n virtual void presetSwitchedEvent(bool isHardCut, unsigned int index) const {};\n virtual void shuffleEnabledValueChanged(bool isEnabled) const {};\n\n\n inline PCM * pcm() {\n\t return _pcm;\n }\n void *thread_func(void *vptr_args);\n PipelineContext & pipelineContext() { return *_pipelineContext; }\n PipelineContext & pipelineContext2() { return *_pipelineContext2; }\n\nprivate:\n PCM * _pcm;\n double sampledPresetDuration();\n BeatDetect * beatDetect;\n Renderer *renderer;\n PipelineContext * _pipelineContext;\n PipelineContext * _pipelineContext2;\n Settings _settings;\n\n\n int wvw; \/\/windowed dimensions\n int wvh;\n\n \/** Timing information *\/\n int mspf;\n int timed;\n int timestart;\n int count;\n float fpsstart;\n\n void readConfig(const std::string &configFile);\n void readSettings(const Settings &settings);\n void projectM_init(int gx, int gy, int fps, int texsize, int width, int height);\n void projectM_reset();\n void selectPrevious(const bool);\n void selectNext(const bool);\n void selectRandom(const bool);\n\n void projectM_initengine();\n void projectM_resetengine();\n\n \/\/\/ Initializes preset loading \/ management libraries\n int initPresetTools(int gx, int gy);\n\n \/\/\/ Deinitialize all preset related tools. Usually done before projectM cleanup\n void destroyPresetTools();\n\n void default_key_handler( projectMEvent event, projectMKeycode keycode );\n \/\/\/ The current position of the directory iterator\n PresetIterator * m_presetPos;\n\n \/\/\/ Required by the preset chooser. Manages a loaded preset directory\n PresetLoader * m_presetLoader;\n\n \/\/\/ Provides accessor functions to choose presets\n PresetChooser * m_presetChooser;\n\n \/\/\/ Currently loaded preset\n std::auto_ptr<Preset> m_activePreset;\n\n \/\/\/ Destination preset when smooth preset switching\n std::auto_ptr<Preset> m_activePreset2;\n\n TimeKeeper *timeKeeper;\n\n int m_flags;\n\n RenderItemMatcher * _matcher;\n MasterRenderItemMerge * _merger;\n pthread_mutex_t mutex;\n pthread_cond_t condition;\n pthread_t thread;\n bool running;\n\n Pipeline* currentPipe;\n\nvoid switchPreset(std::auto_ptr<Preset> & targetPreset);\n\n\n};\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2015 Google Inc. All rights reserved.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \"benchmark_register.h\"\n\n#ifndef BENCHMARK_OS_WINDOWS\n#ifndef BENCHMARK_OS_FUCHSIA\n#include <sys\/resource.h>\n#endif\n#include <sys\/time.h>\n#include <unistd.h>\n#endif\n\n#include <algorithm>\n#include <atomic>\n#include <cinttypes>\n#include <condition_variable>\n#include <cstdio>\n#include <cstdlib>\n#include <cstring>\n#include <fstream>\n#include <iostream>\n#include <memory>\n#include <numeric>\n#include <sstream>\n#include <thread>\n\n#include \"benchmark\/benchmark.h\"\n#include \"benchmark_api_internal.h\"\n#include \"check.h\"\n#include \"commandlineflags.h\"\n#include \"complexity.h\"\n#include \"internal_macros.h\"\n#include \"log.h\"\n#include \"mutex.h\"\n#include \"re.h\"\n#include \"statistics.h\"\n#include \"string_util.h\"\n#include \"timers.h\"\n\nnamespace benchmark {\n\nnamespace {\n\/\/ For non-dense Range, intermediate values are powers of kRangeMultiplier.\nstatic const int kRangeMultiplier = 8;\n\/\/ The size of a benchmark family determines is the number of inputs to repeat\n\/\/ the benchmark on. If this is \"large\" then warn the user during configuration.\nstatic const size_t kMaxFamilySize = 100;\n} \/\/ end namespace\n\nnamespace internal {\n\n\/\/=============================================================================\/\/\n\/\/ BenchmarkFamilies\n\/\/=============================================================================\/\/\n\n\/\/ Class for managing registered benchmarks. Note that each registered\n\/\/ benchmark identifies a family of related benchmarks to run.\nclass BenchmarkFamilies {\n public:\n static BenchmarkFamilies* GetInstance();\n\n \/\/ Registers a benchmark family and returns the index assigned to it.\n size_t AddBenchmark(std::unique_ptr<Benchmark> family);\n\n \/\/ Clear all registered benchmark families.\n void ClearBenchmarks();\n\n \/\/ Extract the list of benchmark instances that match the specified\n \/\/ regular expression.\n bool FindBenchmarks(std::string re,\n std::vector<BenchmarkInstance>* benchmarks,\n std::ostream* Err);\n\n private:\n BenchmarkFamilies() {}\n\n std::vector<std::unique_ptr<Benchmark>> families_;\n Mutex mutex_;\n};\n\nBenchmarkFamilies* BenchmarkFamilies::GetInstance() {\n static BenchmarkFamilies instance;\n return &instance;\n}\n\nsize_t BenchmarkFamilies::AddBenchmark(std::unique_ptr<Benchmark> family) {\n MutexLock l(mutex_);\n size_t index = families_.size();\n families_.push_back(std::move(family));\n return index;\n}\n\nvoid BenchmarkFamilies::ClearBenchmarks() {\n MutexLock l(mutex_);\n families_.clear();\n families_.shrink_to_fit();\n}\n\nbool BenchmarkFamilies::FindBenchmarks(\n std::string spec, std::vector<BenchmarkInstance>* benchmarks,\n std::ostream* ErrStream) {\n CHECK(ErrStream);\n auto& Err = *ErrStream;\n \/\/ Make regular expression out of command-line flag\n std::string error_msg;\n Regex re;\n bool isNegativeFilter = false;\n if (spec[0] == '-') {\n spec.replace(0, 1, \"\");\n isNegativeFilter = true;\n }\n if (!re.Init(spec, &error_msg)) {\n Err << \"Could not compile benchmark re: \" << error_msg << std::endl;\n return false;\n }\n\n \/\/ Special list of thread counts to use when none are specified\n const std::vector<int> one_thread = {1};\n\n MutexLock l(mutex_);\n for (std::unique_ptr<Benchmark>& family : families_) {\n \/\/ Family was deleted or benchmark doesn't match\n if (!family) continue;\n\n if (family->ArgsCnt() == -1) {\n family->Args({});\n }\n const std::vector<int>* thread_counts =\n (family->thread_counts_.empty()\n ? &one_thread\n : &static_cast<const std::vector<int>&>(family->thread_counts_));\n const size_t family_size = family->args_.size() * thread_counts->size();\n \/\/ The benchmark will be run at least 'family_size' different inputs.\n \/\/ If 'family_size' is very large warn the user.\n if (family_size > kMaxFamilySize) {\n Err << \"The number of inputs is very large. \" << family->name_\n << \" will be repeated at least \" << family_size << \" times.\\n\";\n }\n \/\/ reserve in the special case the regex \".\", since we know the final\n \/\/ family size.\n if (spec == \".\") benchmarks->reserve(family_size);\n\n for (auto const& args : family->args_) {\n for (int num_threads : *thread_counts) {\n BenchmarkInstance instance(family.get(), args, num_threads);\n\n const auto full_name = instance.name().str();\n if ((re.Match(full_name) && !isNegativeFilter) ||\n (!re.Match(full_name) && isNegativeFilter)) {\n instance.last_benchmark_instance = (&args == &family->args_.back());\n benchmarks->push_back(std::move(instance));\n }\n }\n }\n }\n return true;\n}\n\nBenchmark* RegisterBenchmarkInternal(Benchmark* bench) {\n std::unique_ptr<Benchmark> bench_ptr(bench);\n BenchmarkFamilies* families = BenchmarkFamilies::GetInstance();\n families->AddBenchmark(std::move(bench_ptr));\n return bench;\n}\n\n\/\/ FIXME: This function is a hack so that benchmark.cc can access\n\/\/ `BenchmarkFamilies`\nbool FindBenchmarksInternal(const std::string& re,\n std::vector<BenchmarkInstance>* benchmarks,\n std::ostream* Err) {\n return BenchmarkFamilies::GetInstance()->FindBenchmarks(re, benchmarks, Err);\n}\n\n\/\/=============================================================================\/\/\n\/\/ Benchmark\n\/\/=============================================================================\/\/\n\nBenchmark::Benchmark(const char* name)\n : name_(name),\n aggregation_report_mode_(ARM_Unspecified),\n time_unit_(kNanosecond),\n range_multiplier_(kRangeMultiplier),\n min_time_(0),\n iterations_(0),\n repetitions_(0),\n measure_process_cpu_time_(false),\n use_real_time_(false),\n use_manual_time_(false),\n complexity_(oNone),\n complexity_lambda_(nullptr) {\n ComputeStatistics(\"mean\", StatisticsMean);\n ComputeStatistics(\"median\", StatisticsMedian);\n ComputeStatistics(\"stddev\", StatisticsStdDev);\n}\n\nBenchmark::~Benchmark() {}\n\nBenchmark* Benchmark::Name(const std::string& name) {\n SetName(name.c_str());\n return this;\n}\n\nBenchmark* Benchmark::Arg(int64_t x) {\n CHECK(ArgsCnt() == -1 || ArgsCnt() == 1);\n args_.push_back({x});\n return this;\n}\n\nBenchmark* Benchmark::Unit(TimeUnit unit) {\n time_unit_ = unit;\n return this;\n}\n\nBenchmark* Benchmark::Range(int64_t start, int64_t limit) {\n CHECK(ArgsCnt() == -1 || ArgsCnt() == 1);\n std::vector<int64_t> arglist;\n AddRange(&arglist, start, limit, range_multiplier_);\n\n for (int64_t i : arglist) {\n args_.push_back({i});\n }\n return this;\n}\n\nBenchmark* Benchmark::Ranges(\n const std::vector<std::pair<int64_t, int64_t>>& ranges) {\n CHECK(ArgsCnt() == -1 || ArgsCnt() == static_cast<int>(ranges.size()));\n std::vector<std::vector<int64_t>> arglists(ranges.size());\n for (std::size_t i = 0; i < ranges.size(); i++) {\n AddRange(&arglists[i], ranges[i].first, ranges[i].second,\n range_multiplier_);\n }\n\n ArgsProduct(arglists);\n\n return this;\n}\n\nBenchmark* Benchmark::ArgsProduct(\n const std::vector<std::vector<int64_t>>& arglists) {\n CHECK(ArgsCnt() == -1 || ArgsCnt() == static_cast<int>(arglists.size()));\n\n std::vector<std::size_t> indices(arglists.size());\n const std::size_t total = std::accumulate(\n std::begin(arglists), std::end(arglists), std::size_t{1},\n [](const std::size_t res, const std::vector<int64_t>& arglist) {\n return res * arglist.size();\n });\n std::vector<int64_t> args;\n args.reserve(arglists.size());\n for (std::size_t i = 0; i < total; i++) {\n for (std::size_t arg = 0; arg < arglists.size(); arg++) {\n args.push_back(arglists[arg][indices[arg]]);\n }\n args_.push_back(args);\n args.clear();\n\n std::size_t arg = 0;\n do {\n indices[arg] = (indices[arg] + 1) % arglists[arg].size();\n } while (indices[arg++] == 0 && arg < arglists.size());\n }\n\n return this;\n}\n\nBenchmark* Benchmark::ArgName(const std::string& name) {\n CHECK(ArgsCnt() == -1 || ArgsCnt() == 1);\n arg_names_ = {name};\n return this;\n}\n\nBenchmark* Benchmark::ArgNames(const std::vector<std::string>& names) {\n CHECK(ArgsCnt() == -1 || ArgsCnt() == static_cast<int>(names.size()));\n arg_names_ = names;\n return this;\n}\n\nBenchmark* Benchmark::DenseRange(int64_t start, int64_t limit, int step) {\n CHECK(ArgsCnt() == -1 || ArgsCnt() == 1);\n CHECK_LE(start, limit);\n for (int64_t arg = start; arg <= limit; arg += step) {\n args_.push_back({arg});\n }\n return this;\n}\n\nBenchmark* Benchmark::Args(const std::vector<int64_t>& args) {\n CHECK(ArgsCnt() == -1 || ArgsCnt() == static_cast<int>(args.size()));\n args_.push_back(args);\n return this;\n}\n\nBenchmark* Benchmark::Apply(void (*custom_arguments)(Benchmark* benchmark)) {\n custom_arguments(this);\n return this;\n}\n\nBenchmark* Benchmark::RangeMultiplier(int multiplier) {\n CHECK(multiplier > 1);\n range_multiplier_ = multiplier;\n return this;\n}\n\nBenchmark* Benchmark::MinTime(double t) {\n CHECK(t > 0.0);\n CHECK(iterations_ == 0);\n min_time_ = t;\n return this;\n}\n\nBenchmark* Benchmark::Iterations(IterationCount n) {\n CHECK(n > 0);\n CHECK(IsZero(min_time_));\n iterations_ = n;\n return this;\n}\n\nBenchmark* Benchmark::Repetitions(int n) {\n CHECK(n > 0);\n repetitions_ = n;\n return this;\n}\n\nBenchmark* Benchmark::ReportAggregatesOnly(bool value) {\n aggregation_report_mode_ = value ? ARM_ReportAggregatesOnly : ARM_Default;\n return this;\n}\n\nBenchmark* Benchmark::DisplayAggregatesOnly(bool value) {\n \/\/ If we were called, the report mode is no longer 'unspecified', in any case.\n aggregation_report_mode_ = static_cast<AggregationReportMode>(\n aggregation_report_mode_ | ARM_Default);\n\n if (value) {\n aggregation_report_mode_ = static_cast<AggregationReportMode>(\n aggregation_report_mode_ | ARM_DisplayReportAggregatesOnly);\n } else {\n aggregation_report_mode_ = static_cast<AggregationReportMode>(\n aggregation_report_mode_ & ~ARM_DisplayReportAggregatesOnly);\n }\n\n return this;\n}\n\nBenchmark* Benchmark::MeasureProcessCPUTime() {\n \/\/ Can be used together with UseRealTime() \/ UseManualTime().\n measure_process_cpu_time_ = true;\n return this;\n}\n\nBenchmark* Benchmark::UseRealTime() {\n CHECK(!use_manual_time_)\n << \"Cannot set UseRealTime and UseManualTime simultaneously.\";\n use_real_time_ = true;\n return this;\n}\n\nBenchmark* Benchmark::UseManualTime() {\n CHECK(!use_real_time_)\n << \"Cannot set UseRealTime and UseManualTime simultaneously.\";\n use_manual_time_ = true;\n return this;\n}\n\nBenchmark* Benchmark::Complexity(BigO complexity) {\n complexity_ = complexity;\n return this;\n}\n\nBenchmark* Benchmark::Complexity(BigOFunc* complexity) {\n complexity_lambda_ = complexity;\n complexity_ = oLambda;\n return this;\n}\n\nBenchmark* Benchmark::ComputeStatistics(std::string name,\n StatisticsFunc* statistics) {\n statistics_.emplace_back(name, statistics);\n return this;\n}\n\nBenchmark* Benchmark::Threads(int t) {\n CHECK_GT(t, 0);\n thread_counts_.push_back(t);\n return this;\n}\n\nBenchmark* Benchmark::ThreadRange(int min_threads, int max_threads) {\n CHECK_GT(min_threads, 0);\n CHECK_GE(max_threads, min_threads);\n\n AddRange(&thread_counts_, min_threads, max_threads, 2);\n return this;\n}\n\nBenchmark* Benchmark::DenseThreadRange(int min_threads, int max_threads,\n int stride) {\n CHECK_GT(min_threads, 0);\n CHECK_GE(max_threads, min_threads);\n CHECK_GE(stride, 1);\n\n for (auto i = min_threads; i < max_threads; i += stride) {\n thread_counts_.push_back(i);\n }\n thread_counts_.push_back(max_threads);\n return this;\n}\n\nBenchmark* Benchmark::ThreadPerCpu() {\n thread_counts_.push_back(CPUInfo::Get().num_cpus);\n return this;\n}\n\nvoid Benchmark::SetName(const char* name) { name_ = name; }\n\nint Benchmark::ArgsCnt() const {\n if (args_.empty()) {\n if (arg_names_.empty()) return -1;\n return static_cast<int>(arg_names_.size());\n }\n return static_cast<int>(args_.front().size());\n}\n\n\/\/=============================================================================\/\/\n\/\/ FunctionBenchmark\n\/\/=============================================================================\/\/\n\nvoid FunctionBenchmark::Run(State& st) { func_(st); }\n\n} \/\/ end namespace internal\n\nvoid ClearRegisteredBenchmarks() {\n internal::BenchmarkFamilies::GetInstance()->ClearBenchmarks();\n}\n\n} \/\/ end namespace benchmark\n<commit_msg>Change a check in DenseRange: on the one hand, going from -5 to 3 with step of 1 makes perfect sense, on the other hand a negative step would cause trouble.<commit_after>\/\/ Copyright 2015 Google Inc. All rights reserved.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \"benchmark_register.h\"\n\n#ifndef BENCHMARK_OS_WINDOWS\n#ifndef BENCHMARK_OS_FUCHSIA\n#include <sys\/resource.h>\n#endif\n#include <sys\/time.h>\n#include <unistd.h>\n#endif\n\n#include <algorithm>\n#include <atomic>\n#include <cinttypes>\n#include <condition_variable>\n#include <cstdio>\n#include <cstdlib>\n#include <cstring>\n#include <fstream>\n#include <iostream>\n#include <memory>\n#include <numeric>\n#include <sstream>\n#include <thread>\n\n#include \"benchmark\/benchmark.h\"\n#include \"benchmark_api_internal.h\"\n#include \"check.h\"\n#include \"commandlineflags.h\"\n#include \"complexity.h\"\n#include \"internal_macros.h\"\n#include \"log.h\"\n#include \"mutex.h\"\n#include \"re.h\"\n#include \"statistics.h\"\n#include \"string_util.h\"\n#include \"timers.h\"\n\nnamespace benchmark {\n\nnamespace {\n\/\/ For non-dense Range, intermediate values are powers of kRangeMultiplier.\nstatic const int kRangeMultiplier = 8;\n\/\/ The size of a benchmark family determines is the number of inputs to repeat\n\/\/ the benchmark on. If this is \"large\" then warn the user during configuration.\nstatic const size_t kMaxFamilySize = 100;\n} \/\/ end namespace\n\nnamespace internal {\n\n\/\/=============================================================================\/\/\n\/\/ BenchmarkFamilies\n\/\/=============================================================================\/\/\n\n\/\/ Class for managing registered benchmarks. Note that each registered\n\/\/ benchmark identifies a family of related benchmarks to run.\nclass BenchmarkFamilies {\n public:\n static BenchmarkFamilies* GetInstance();\n\n \/\/ Registers a benchmark family and returns the index assigned to it.\n size_t AddBenchmark(std::unique_ptr<Benchmark> family);\n\n \/\/ Clear all registered benchmark families.\n void ClearBenchmarks();\n\n \/\/ Extract the list of benchmark instances that match the specified\n \/\/ regular expression.\n bool FindBenchmarks(std::string re,\n std::vector<BenchmarkInstance>* benchmarks,\n std::ostream* Err);\n\n private:\n BenchmarkFamilies() {}\n\n std::vector<std::unique_ptr<Benchmark>> families_;\n Mutex mutex_;\n};\n\nBenchmarkFamilies* BenchmarkFamilies::GetInstance() {\n static BenchmarkFamilies instance;\n return &instance;\n}\n\nsize_t BenchmarkFamilies::AddBenchmark(std::unique_ptr<Benchmark> family) {\n MutexLock l(mutex_);\n size_t index = families_.size();\n families_.push_back(std::move(family));\n return index;\n}\n\nvoid BenchmarkFamilies::ClearBenchmarks() {\n MutexLock l(mutex_);\n families_.clear();\n families_.shrink_to_fit();\n}\n\nbool BenchmarkFamilies::FindBenchmarks(\n std::string spec, std::vector<BenchmarkInstance>* benchmarks,\n std::ostream* ErrStream) {\n CHECK(ErrStream);\n auto& Err = *ErrStream;\n \/\/ Make regular expression out of command-line flag\n std::string error_msg;\n Regex re;\n bool isNegativeFilter = false;\n if (spec[0] == '-') {\n spec.replace(0, 1, \"\");\n isNegativeFilter = true;\n }\n if (!re.Init(spec, &error_msg)) {\n Err << \"Could not compile benchmark re: \" << error_msg << std::endl;\n return false;\n }\n\n \/\/ Special list of thread counts to use when none are specified\n const std::vector<int> one_thread = {1};\n\n MutexLock l(mutex_);\n for (std::unique_ptr<Benchmark>& family : families_) {\n \/\/ Family was deleted or benchmark doesn't match\n if (!family) continue;\n\n if (family->ArgsCnt() == -1) {\n family->Args({});\n }\n const std::vector<int>* thread_counts =\n (family->thread_counts_.empty()\n ? &one_thread\n : &static_cast<const std::vector<int>&>(family->thread_counts_));\n const size_t family_size = family->args_.size() * thread_counts->size();\n \/\/ The benchmark will be run at least 'family_size' different inputs.\n \/\/ If 'family_size' is very large warn the user.\n if (family_size > kMaxFamilySize) {\n Err << \"The number of inputs is very large. \" << family->name_\n << \" will be repeated at least \" << family_size << \" times.\\n\";\n }\n \/\/ reserve in the special case the regex \".\", since we know the final\n \/\/ family size.\n if (spec == \".\") benchmarks->reserve(family_size);\n\n for (auto const& args : family->args_) {\n for (int num_threads : *thread_counts) {\n BenchmarkInstance instance(family.get(), args, num_threads);\n\n const auto full_name = instance.name().str();\n if ((re.Match(full_name) && !isNegativeFilter) ||\n (!re.Match(full_name) && isNegativeFilter)) {\n instance.last_benchmark_instance = (&args == &family->args_.back());\n benchmarks->push_back(std::move(instance));\n }\n }\n }\n }\n return true;\n}\n\nBenchmark* RegisterBenchmarkInternal(Benchmark* bench) {\n std::unique_ptr<Benchmark> bench_ptr(bench);\n BenchmarkFamilies* families = BenchmarkFamilies::GetInstance();\n families->AddBenchmark(std::move(bench_ptr));\n return bench;\n}\n\n\/\/ FIXME: This function is a hack so that benchmark.cc can access\n\/\/ `BenchmarkFamilies`\nbool FindBenchmarksInternal(const std::string& re,\n std::vector<BenchmarkInstance>* benchmarks,\n std::ostream* Err) {\n return BenchmarkFamilies::GetInstance()->FindBenchmarks(re, benchmarks, Err);\n}\n\n\/\/=============================================================================\/\/\n\/\/ Benchmark\n\/\/=============================================================================\/\/\n\nBenchmark::Benchmark(const char* name)\n : name_(name),\n aggregation_report_mode_(ARM_Unspecified),\n time_unit_(kNanosecond),\n range_multiplier_(kRangeMultiplier),\n min_time_(0),\n iterations_(0),\n repetitions_(0),\n measure_process_cpu_time_(false),\n use_real_time_(false),\n use_manual_time_(false),\n complexity_(oNone),\n complexity_lambda_(nullptr) {\n ComputeStatistics(\"mean\", StatisticsMean);\n ComputeStatistics(\"median\", StatisticsMedian);\n ComputeStatistics(\"stddev\", StatisticsStdDev);\n}\n\nBenchmark::~Benchmark() {}\n\nBenchmark* Benchmark::Name(const std::string& name) {\n SetName(name.c_str());\n return this;\n}\n\nBenchmark* Benchmark::Arg(int64_t x) {\n CHECK(ArgsCnt() == -1 || ArgsCnt() == 1);\n args_.push_back({x});\n return this;\n}\n\nBenchmark* Benchmark::Unit(TimeUnit unit) {\n time_unit_ = unit;\n return this;\n}\n\nBenchmark* Benchmark::Range(int64_t start, int64_t limit) {\n CHECK(ArgsCnt() == -1 || ArgsCnt() == 1);\n std::vector<int64_t> arglist;\n AddRange(&arglist, start, limit, range_multiplier_);\n\n for (int64_t i : arglist) {\n args_.push_back({i});\n }\n return this;\n}\n\nBenchmark* Benchmark::Ranges(\n const std::vector<std::pair<int64_t, int64_t>>& ranges) {\n CHECK(ArgsCnt() == -1 || ArgsCnt() == static_cast<int>(ranges.size()));\n std::vector<std::vector<int64_t>> arglists(ranges.size());\n for (std::size_t i = 0; i < ranges.size(); i++) {\n AddRange(&arglists[i], ranges[i].first, ranges[i].second,\n range_multiplier_);\n }\n\n ArgsProduct(arglists);\n\n return this;\n}\n\nBenchmark* Benchmark::ArgsProduct(\n const std::vector<std::vector<int64_t>>& arglists) {\n CHECK(ArgsCnt() == -1 || ArgsCnt() == static_cast<int>(arglists.size()));\n\n std::vector<std::size_t> indices(arglists.size());\n const std::size_t total = std::accumulate(\n std::begin(arglists), std::end(arglists), std::size_t{1},\n [](const std::size_t res, const std::vector<int64_t>& arglist) {\n return res * arglist.size();\n });\n std::vector<int64_t> args;\n args.reserve(arglists.size());\n for (std::size_t i = 0; i < total; i++) {\n for (std::size_t arg = 0; arg < arglists.size(); arg++) {\n args.push_back(arglists[arg][indices[arg]]);\n }\n args_.push_back(args);\n args.clear();\n\n std::size_t arg = 0;\n do {\n indices[arg] = (indices[arg] + 1) % arglists[arg].size();\n } while (indices[arg++] == 0 && arg < arglists.size());\n }\n\n return this;\n}\n\nBenchmark* Benchmark::ArgName(const std::string& name) {\n CHECK(ArgsCnt() == -1 || ArgsCnt() == 1);\n arg_names_ = {name};\n return this;\n}\n\nBenchmark* Benchmark::ArgNames(const std::vector<std::string>& names) {\n CHECK(ArgsCnt() == -1 || ArgsCnt() == static_cast<int>(names.size()));\n arg_names_ = names;\n return this;\n}\n\nBenchmark* Benchmark::DenseRange(int64_t start, int64_t limit, int step) {\n CHECK(ArgsCnt() == -1 || ArgsCnt() == 1);\n CHECK_GT(step, 0);\n CHECK_LE(start, limit);\n for (int64_t arg = start; arg <= limit; arg += step) {\n args_.push_back({arg});\n }\n return this;\n}\n\nBenchmark* Benchmark::Args(const std::vector<int64_t>& args) {\n CHECK(ArgsCnt() == -1 || ArgsCnt() == static_cast<int>(args.size()));\n args_.push_back(args);\n return this;\n}\n\nBenchmark* Benchmark::Apply(void (*custom_arguments)(Benchmark* benchmark)) {\n custom_arguments(this);\n return this;\n}\n\nBenchmark* Benchmark::RangeMultiplier(int multiplier) {\n CHECK(multiplier > 1);\n range_multiplier_ = multiplier;\n return this;\n}\n\nBenchmark* Benchmark::MinTime(double t) {\n CHECK(t > 0.0);\n CHECK(iterations_ == 0);\n min_time_ = t;\n return this;\n}\n\nBenchmark* Benchmark::Iterations(IterationCount n) {\n CHECK(n > 0);\n CHECK(IsZero(min_time_));\n iterations_ = n;\n return this;\n}\n\nBenchmark* Benchmark::Repetitions(int n) {\n CHECK(n > 0);\n repetitions_ = n;\n return this;\n}\n\nBenchmark* Benchmark::ReportAggregatesOnly(bool value) {\n aggregation_report_mode_ = value ? ARM_ReportAggregatesOnly : ARM_Default;\n return this;\n}\n\nBenchmark* Benchmark::DisplayAggregatesOnly(bool value) {\n \/\/ If we were called, the report mode is no longer 'unspecified', in any case.\n aggregation_report_mode_ = static_cast<AggregationReportMode>(\n aggregation_report_mode_ | ARM_Default);\n\n if (value) {\n aggregation_report_mode_ = static_cast<AggregationReportMode>(\n aggregation_report_mode_ | ARM_DisplayReportAggregatesOnly);\n } else {\n aggregation_report_mode_ = static_cast<AggregationReportMode>(\n aggregation_report_mode_ & ~ARM_DisplayReportAggregatesOnly);\n }\n\n return this;\n}\n\nBenchmark* Benchmark::MeasureProcessCPUTime() {\n \/\/ Can be used together with UseRealTime() \/ UseManualTime().\n measure_process_cpu_time_ = true;\n return this;\n}\n\nBenchmark* Benchmark::UseRealTime() {\n CHECK(!use_manual_time_)\n << \"Cannot set UseRealTime and UseManualTime simultaneously.\";\n use_real_time_ = true;\n return this;\n}\n\nBenchmark* Benchmark::UseManualTime() {\n CHECK(!use_real_time_)\n << \"Cannot set UseRealTime and UseManualTime simultaneously.\";\n use_manual_time_ = true;\n return this;\n}\n\nBenchmark* Benchmark::Complexity(BigO complexity) {\n complexity_ = complexity;\n return this;\n}\n\nBenchmark* Benchmark::Complexity(BigOFunc* complexity) {\n complexity_lambda_ = complexity;\n complexity_ = oLambda;\n return this;\n}\n\nBenchmark* Benchmark::ComputeStatistics(std::string name,\n StatisticsFunc* statistics) {\n statistics_.emplace_back(name, statistics);\n return this;\n}\n\nBenchmark* Benchmark::Threads(int t) {\n CHECK_GT(t, 0);\n thread_counts_.push_back(t);\n return this;\n}\n\nBenchmark* Benchmark::ThreadRange(int min_threads, int max_threads) {\n CHECK_GT(min_threads, 0);\n CHECK_GE(max_threads, min_threads);\n\n AddRange(&thread_counts_, min_threads, max_threads, 2);\n return this;\n}\n\nBenchmark* Benchmark::DenseThreadRange(int min_threads, int max_threads,\n int stride) {\n CHECK_GT(min_threads, 0);\n CHECK_GE(max_threads, min_threads);\n CHECK_GE(stride, 1);\n\n for (auto i = min_threads; i < max_threads; i += stride) {\n thread_counts_.push_back(i);\n }\n thread_counts_.push_back(max_threads);\n return this;\n}\n\nBenchmark* Benchmark::ThreadPerCpu() {\n thread_counts_.push_back(CPUInfo::Get().num_cpus);\n return this;\n}\n\nvoid Benchmark::SetName(const char* name) { name_ = name; }\n\nint Benchmark::ArgsCnt() const {\n if (args_.empty()) {\n if (arg_names_.empty()) return -1;\n return static_cast<int>(arg_names_.size());\n }\n return static_cast<int>(args_.front().size());\n}\n\n\/\/=============================================================================\/\/\n\/\/ FunctionBenchmark\n\/\/=============================================================================\/\/\n\nvoid FunctionBenchmark::Run(State& st) { func_(st); }\n\n} \/\/ end namespace internal\n\nvoid ClearRegisteredBenchmarks() {\n internal::BenchmarkFamilies::GetInstance()->ClearBenchmarks();\n}\n\n} \/\/ end namespace benchmark\n<|endoftext|>"} {"text":"<commit_before>\/****************************************************************************\n**\n** Copyright (C) 2012 Nokia Corporation and\/or its subsidiary(-ies).\n** Contact: http:\/\/www.qt-project.org\/\n**\n** This file is part of the QtCore module of the Qt Toolkit.\n**\n** $QT_BEGIN_LICENSE:LGPL$\n** GNU Lesser General Public License Usage\n** This file may be used under the terms of the GNU Lesser General Public\n** License version 2.1 as published by the Free Software Foundation and\n** appearing in the file LICENSE.LGPL included in the packaging of this\n** file. Please review the following information to ensure the GNU Lesser\n** General Public License version 2.1 requirements will be met:\n** http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Nokia gives you certain additional\n** rights. These rights are described in the Nokia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n** GNU General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU General\n** Public License version 3.0 as published by the Free Software Foundation\n** and appearing in the file LICENSE.GPL included in the packaging of this\n** file. Please review the following information to ensure the GNU General\n** Public License version 3.0 requirements will be met:\n** http:\/\/www.gnu.org\/copyleft\/gpl.html.\n**\n** Other Usage\n** Alternatively, this file may be used in accordance with the terms and\n** conditions contained in a signed written agreement between you and Nokia.\n**\n**\n**\n**\n**\n**\n** $QT_END_LICENSE$\n**\n****************************************************************************\/\n\n#include \"elfreader.h\"\n#include \"qtcassert.h\"\n\n#include <QFile>\n#include <QLibrary>\n#include <QDebug>\n\nnamespace Utils {\n\nquint16 getHalfWord(const unsigned char *&s, const ElfData &context)\n{\n quint16 res;\n if (context.endian == Elf_ELFDATA2MSB)\n res = qFromBigEndian<quint16>(s);\n else\n res = qFromLittleEndian<quint16>(s);\n s += 2;\n return res;\n}\n\nquint32 getWord(const unsigned char *&s, const ElfData &context)\n{\n quint32 res;\n if (context.endian == Elf_ELFDATA2MSB)\n res = qFromBigEndian<quint32>(s);\n else\n res = qFromLittleEndian<quint32>(s);\n s += 4;\n return res;\n}\n\nquint64 getAddress(const unsigned char *&s, const ElfData &context)\n{\n quint64 res;\n if (context.elfclass == Elf_ELFCLASS32) {\n if (context.endian == Elf_ELFDATA2MSB)\n res = qFromBigEndian<quint32>(s);\n else\n res = qFromLittleEndian<quint32>(s);\n s += 4;\n } else {\n if (context.endian == Elf_ELFDATA2MSB)\n res = qFromBigEndian<quint64>(s);\n else\n res = qFromLittleEndian<quint64>(s);\n s += 8;\n }\n return res;\n}\n\nquint64 getOffset(const unsigned char *&s, const ElfData &context)\n{\n return getAddress(s, context);\n}\n\nstatic void parseSectionHeader(const uchar *s, ElfSectionHeader *sh, const ElfData &context)\n{\n sh->index = getWord(s, context);\n sh->type = getWord(s, context);\n sh->flags = getOffset(s, context);\n sh->addr = getAddress(s, context);\n sh->offset = getOffset(s, context);\n sh->size = getOffset(s, context);\n}\n\nstatic void parseProgramHeader(const uchar *s, ElfProgramHeader *sh, const ElfData &context)\n{\n sh->type = getWord(s, context);\n sh->offset = getOffset(s, context);\n \/* p_vaddr = *\/ getAddress(s, context);\n \/* p_paddr = *\/ getAddress(s, context);\n sh->filesz = getWord(s, context);\n sh->memsz = getWord(s, context);\n}\n\nclass ElfMapper\n{\npublic:\n ElfMapper(const ElfReader *reader) : file(reader->m_binary) {}\n\n bool map()\n {\n if (!file.open(QIODevice::ReadOnly))\n return false;\n\n fdlen = file.size();\n ustart = file.map(0, fdlen);\n if (ustart == 0) {\n \/\/ Try reading the data into memory instead.\n raw = file.readAll();\n start = raw.constData();\n fdlen = raw.size();\n }\n return true;\n }\n\npublic:\n QFile file;\n QByteArray raw;\n union { const char *start; const uchar *ustart; };\n quint64 fdlen;\n};\n\nElfReader::ElfReader(const QString &binary)\n : m_binary(binary)\n{\n}\n\nElfData ElfReader::readHeaders()\n{\n readIt();\n return m_elfData;\n}\n\nElfReader::Result ElfReader::readIt()\n{\n if (!m_elfData.sectionHeaders.isEmpty())\n return Ok;\n if (!m_elfData.programHeaders.isEmpty())\n return Ok;\n\n ElfMapper mapper(this);\n if (!mapper.map())\n return Corrupt;\n\n const quint64 fdlen = mapper.fdlen;\n\n if (fdlen < 64) {\n m_errorString = QLibrary::tr(\"'%1' is not an ELF object (%2)\")\n .arg(m_binary).arg(QLatin1String(\"file too small\"));\n return NotElf;\n }\n\n if (strncmp(mapper.start, \"\\177ELF\", 4) != 0) {\n m_errorString = QLibrary::tr(\"'%1' is not an ELF object\")\n .arg(m_binary);\n return NotElf;\n }\n\n \/\/ 32 or 64 bit\n m_elfData.elfclass = ElfClass(mapper.start[4]);\n const bool is64Bit = m_elfData.elfclass == Elf_ELFCLASS64;\n if (m_elfData.elfclass != Elf_ELFCLASS32 && m_elfData.elfclass != Elf_ELFCLASS64) {\n m_errorString = QLibrary::tr(\"'%1' is an invalid ELF object (%2)\")\n .arg(m_binary).arg(QLatin1String(\"odd cpu architecture\"));\n return Corrupt;\n }\n\n \/\/ int bits = (data[4] << 5);\n \/\/ If you remove this check to read ELF objects of a different arch,\n \/\/ please make sure you modify the typedefs\n \/\/ to match the _plugin_ architecture.\n \/\/ if ((sizeof(void*) == 4 && bits != 32)\n \/\/ || (sizeof(void*) == 8 && bits != 64)) {\n \/\/ if (errorString)\n \/\/ *errorString = QLibrary::tr(\"'%1' is an invalid ELF object (%2)\")\n \/\/ .arg(m_binary).arg(QLatin1String(\"wrong cpu architecture\"));\n \/\/ return Corrupt;\n \/\/ }\n\n \/\/ Read Endianess.\n m_elfData.endian = ElfEndian(mapper.ustart[5]);\n if (m_elfData.endian != Elf_ELFDATA2LSB && m_elfData.endian != Elf_ELFDATA2MSB) {\n m_errorString = QLibrary::tr(\"'%1' is an invalid ELF object (%2)\")\n .arg(m_binary).arg(QLatin1String(\"odd endianess\"));\n return Corrupt;\n }\n\n const uchar *data = mapper.ustart + 16; \/\/ e_ident\n m_elfData.elftype = ElfType(getHalfWord(data, m_elfData));\n m_elfData.elfmachine = ElfMachine(getHalfWord(data, m_elfData));\n \/* e_version = *\/ getWord(data, m_elfData);\n m_elfData.entryPoint = getAddress(data, m_elfData);\n\n quint64 e_phoff = getOffset(data, m_elfData);\n quint64 e_shoff = getOffset(data, m_elfData);\n \/* e_flags = *\/ getWord(data, m_elfData);\n\n quint32 e_shsize = getHalfWord(data, m_elfData);\n\n if (e_shsize > fdlen) {\n m_errorString = QLibrary::tr(\"'%1' is an invalid ELF object (%2)\")\n .arg(m_binary).arg(QLatin1String(\"unexpected e_shsize\"));\n return Corrupt;\n }\n\n quint32 e_phentsize = getHalfWord(data, m_elfData);\n QTC_CHECK(e_phentsize == (is64Bit ? 44 : 32));\n quint32 e_phnum = getHalfWord(data, m_elfData);\n\n quint32 e_shentsize = getHalfWord(data, m_elfData);\n\n if (e_shentsize % 4) {\n m_errorString = QLibrary::tr(\"'%1' is an invalid ELF object (%2)\")\n .arg(m_binary).arg(QLatin1String(\"unexpected e_shentsize\"));\n return Corrupt;\n }\n\n quint32 e_shnum = getHalfWord(data, m_elfData);\n quint32 e_shtrndx = getHalfWord(data, m_elfData);\n QTC_CHECK(data == mapper.ustart + (is64Bit ? 58 : 52));\n\n if (quint64(e_shnum) * e_shentsize > fdlen) {\n m_errorString = QLibrary::tr(\"'%1' is an invalid ELF object (%2)\")\n .arg(m_binary)\n .arg(QLatin1String(\"announced %2 sections, each %3 bytes, exceed file size\"))\n .arg(e_shnum).arg(e_shentsize);\n return Corrupt;\n }\n\n quint64 soff = e_shoff + e_shentsize * e_shtrndx;\n\n\/\/ if ((soff + e_shentsize) > fdlen || soff % 4 || soff == 0) {\n\/\/ m_errorString = QLibrary::tr(\"'%1' is an invalid ELF object (%2)\")\n\/\/ .arg(m_binary)\n\/\/ .arg(QLatin1String(\"shstrtab section header seems to be at %1\"))\n\/\/ .arg(QString::number(soff, 16));\n\/\/ return Corrupt;\n\/\/ }\n\n if (e_shoff) {\n ElfSectionHeader strtab;\n parseSectionHeader(mapper.ustart + soff, &strtab, m_elfData);\n const quint64 stringTableFileOffset = strtab.offset;\n\n if (quint32(stringTableFileOffset + e_shentsize) >= fdlen\n || stringTableFileOffset == 0) {\n m_errorString = QLibrary::tr(\"'%1' is an invalid ELF object (%2)\")\n .arg(m_binary)\n .arg(QLatin1String(\"string table seems to be at %1\"))\n .arg(QString::number(soff, 16));\n return Corrupt;\n }\n\n for (int i = 0; i < e_shnum; ++i) {\n const uchar *s = mapper.ustart + e_shoff + i * e_shentsize;\n ElfSectionHeader sh;\n parseSectionHeader(s, &sh, m_elfData);\n\n if (stringTableFileOffset + sh.index > fdlen) {\n m_errorString = QLibrary::tr(\"'%1' is an invalid ELF object (%2)\")\n .arg(m_binary)\n .arg(QLatin1String(\"section name %2 of %3 behind end of file\"))\n .arg(i).arg(e_shnum);\n return Corrupt;\n }\n\n sh.name = mapper.start + stringTableFileOffset + sh.index;\n if (sh.name == \".gdb_index\") {\n m_elfData.symbolsType = FastSymbols;\n } else if (sh.name == \".debug_info\") {\n m_elfData.symbolsType = PlainSymbols;\n } else if (sh.name == \".gnu_debuglink\") {\n m_elfData.debugLink = QByteArray(mapper.start + sh.offset);\n m_elfData.symbolsType = LinkedSymbols;\n } else if (sh.name == \".note.gnu.build-id\") {\n m_elfData.symbolsType = BuildIdSymbols;\n if (sh.size > 16)\n m_elfData.buildId = QByteArray(mapper.start + sh.offset + 16,\n sh.size - 16).toHex();\n }\n m_elfData.sectionHeaders.append(sh);\n }\n }\n\n if (e_phoff) {\n for (int i = 0; i < e_phnum; ++i) {\n const uchar *s = mapper.ustart + e_phoff + i * e_phentsize;\n ElfProgramHeader ph;\n parseProgramHeader(s, &ph, m_elfData);\n m_elfData.programHeaders.append(ph);\n }\n }\n return Ok;\n}\n\nQByteArray ElfReader::readSection(const QByteArray &name)\n{\n readIt();\n int i = m_elfData.indexOf(name);\n if (i == -1)\n return QByteArray();\n\n ElfMapper mapper(this);\n if (!mapper.map())\n return QByteArray();\n\n const ElfSectionHeader §ion = m_elfData.sectionHeaders.at(i);\n return QByteArray(mapper.start + section.offset, section.size);\n}\n\nQByteArray ElfReader::readCoreName(bool *isCore)\n{\n *isCore = false;\n\n readIt();\n\n ElfMapper mapper(this);\n if (!mapper.map())\n return QByteArray();\n\n if (m_elfData.elftype != Elf_ET_CORE)\n return QByteArray();\n\n *isCore = true;\n\n for (int i = 0, n = m_elfData.sectionHeaders.size(); i != n; ++i)\n if (m_elfData.sectionHeaders.at(i).type == Elf_SHT_NOTE) {\n const ElfSectionHeader &header = m_elfData.sectionHeaders.at(i);\n const char *s = mapper.start + header.offset + 0x40;\n return QByteArray(s);\n }\n\n for (int i = 0, n = m_elfData.programHeaders.size(); i != n; ++i)\n if (m_elfData.programHeaders.at(i).type == Elf_PT_NOTE) {\n const ElfProgramHeader &header = m_elfData.programHeaders.at(i);\n const char *s = mapper.start + header.offset + 0xec;\n return QByteArray(s);\n }\n\n return QByteArray();\n}\n\nint ElfData::indexOf(const QByteArray &name) const\n{\n for (int i = 0, n = sectionHeaders.size(); i != n; ++i)\n if (sectionHeaders.at(i).name == name)\n return i;\n return -1;\n}\n\n} \/\/ namespace Utils\n<commit_msg>Elf reader: Fix asserts for 64 bit hosts.<commit_after>\/****************************************************************************\n**\n** Copyright (C) 2012 Nokia Corporation and\/or its subsidiary(-ies).\n** Contact: http:\/\/www.qt-project.org\/\n**\n** This file is part of the QtCore module of the Qt Toolkit.\n**\n** $QT_BEGIN_LICENSE:LGPL$\n** GNU Lesser General Public License Usage\n** This file may be used under the terms of the GNU Lesser General Public\n** License version 2.1 as published by the Free Software Foundation and\n** appearing in the file LICENSE.LGPL included in the packaging of this\n** file. Please review the following information to ensure the GNU Lesser\n** General Public License version 2.1 requirements will be met:\n** http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Nokia gives you certain additional\n** rights. These rights are described in the Nokia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n** GNU General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU General\n** Public License version 3.0 as published by the Free Software Foundation\n** and appearing in the file LICENSE.GPL included in the packaging of this\n** file. Please review the following information to ensure the GNU General\n** Public License version 3.0 requirements will be met:\n** http:\/\/www.gnu.org\/copyleft\/gpl.html.\n**\n** Other Usage\n** Alternatively, this file may be used in accordance with the terms and\n** conditions contained in a signed written agreement between you and Nokia.\n**\n**\n**\n**\n**\n**\n** $QT_END_LICENSE$\n**\n****************************************************************************\/\n\n#include \"elfreader.h\"\n#include \"qtcassert.h\"\n\n#include <QFile>\n#include <QLibrary>\n#include <QDebug>\n\nnamespace Utils {\n\nquint16 getHalfWord(const unsigned char *&s, const ElfData &context)\n{\n quint16 res;\n if (context.endian == Elf_ELFDATA2MSB)\n res = qFromBigEndian<quint16>(s);\n else\n res = qFromLittleEndian<quint16>(s);\n s += 2;\n return res;\n}\n\nquint32 getWord(const unsigned char *&s, const ElfData &context)\n{\n quint32 res;\n if (context.endian == Elf_ELFDATA2MSB)\n res = qFromBigEndian<quint32>(s);\n else\n res = qFromLittleEndian<quint32>(s);\n s += 4;\n return res;\n}\n\nquint64 getAddress(const unsigned char *&s, const ElfData &context)\n{\n quint64 res;\n if (context.elfclass == Elf_ELFCLASS32) {\n if (context.endian == Elf_ELFDATA2MSB)\n res = qFromBigEndian<quint32>(s);\n else\n res = qFromLittleEndian<quint32>(s);\n s += 4;\n } else {\n if (context.endian == Elf_ELFDATA2MSB)\n res = qFromBigEndian<quint64>(s);\n else\n res = qFromLittleEndian<quint64>(s);\n s += 8;\n }\n return res;\n}\n\nquint64 getOffset(const unsigned char *&s, const ElfData &context)\n{\n return getAddress(s, context);\n}\n\nstatic void parseSectionHeader(const uchar *s, ElfSectionHeader *sh, const ElfData &context)\n{\n sh->index = getWord(s, context);\n sh->type = getWord(s, context);\n sh->flags = getOffset(s, context);\n sh->addr = getAddress(s, context);\n sh->offset = getOffset(s, context);\n sh->size = getOffset(s, context);\n}\n\nstatic void parseProgramHeader(const uchar *s, ElfProgramHeader *sh, const ElfData &context)\n{\n sh->type = getWord(s, context);\n sh->offset = getOffset(s, context);\n \/* p_vaddr = *\/ getAddress(s, context);\n \/* p_paddr = *\/ getAddress(s, context);\n sh->filesz = getWord(s, context);\n sh->memsz = getWord(s, context);\n}\n\nclass ElfMapper\n{\npublic:\n ElfMapper(const ElfReader *reader) : file(reader->m_binary) {}\n\n bool map()\n {\n if (!file.open(QIODevice::ReadOnly))\n return false;\n\n fdlen = file.size();\n ustart = file.map(0, fdlen);\n if (ustart == 0) {\n \/\/ Try reading the data into memory instead.\n raw = file.readAll();\n start = raw.constData();\n fdlen = raw.size();\n }\n return true;\n }\n\npublic:\n QFile file;\n QByteArray raw;\n union { const char *start; const uchar *ustart; };\n quint64 fdlen;\n};\n\nElfReader::ElfReader(const QString &binary)\n : m_binary(binary)\n{\n}\n\nElfData ElfReader::readHeaders()\n{\n readIt();\n return m_elfData;\n}\n\nElfReader::Result ElfReader::readIt()\n{\n if (!m_elfData.sectionHeaders.isEmpty())\n return Ok;\n if (!m_elfData.programHeaders.isEmpty())\n return Ok;\n\n ElfMapper mapper(this);\n if (!mapper.map())\n return Corrupt;\n\n const quint64 fdlen = mapper.fdlen;\n\n if (fdlen < 64) {\n m_errorString = QLibrary::tr(\"'%1' is not an ELF object (%2)\")\n .arg(m_binary).arg(QLatin1String(\"file too small\"));\n return NotElf;\n }\n\n if (strncmp(mapper.start, \"\\177ELF\", 4) != 0) {\n m_errorString = QLibrary::tr(\"'%1' is not an ELF object\")\n .arg(m_binary);\n return NotElf;\n }\n\n \/\/ 32 or 64 bit\n m_elfData.elfclass = ElfClass(mapper.start[4]);\n const bool is64Bit = m_elfData.elfclass == Elf_ELFCLASS64;\n if (m_elfData.elfclass != Elf_ELFCLASS32 && m_elfData.elfclass != Elf_ELFCLASS64) {\n m_errorString = QLibrary::tr(\"'%1' is an invalid ELF object (%2)\")\n .arg(m_binary).arg(QLatin1String(\"odd cpu architecture\"));\n return Corrupt;\n }\n\n \/\/ int bits = (data[4] << 5);\n \/\/ If you remove this check to read ELF objects of a different arch,\n \/\/ please make sure you modify the typedefs\n \/\/ to match the _plugin_ architecture.\n \/\/ if ((sizeof(void*) == 4 && bits != 32)\n \/\/ || (sizeof(void*) == 8 && bits != 64)) {\n \/\/ if (errorString)\n \/\/ *errorString = QLibrary::tr(\"'%1' is an invalid ELF object (%2)\")\n \/\/ .arg(m_binary).arg(QLatin1String(\"wrong cpu architecture\"));\n \/\/ return Corrupt;\n \/\/ }\n\n \/\/ Read Endianess.\n m_elfData.endian = ElfEndian(mapper.ustart[5]);\n if (m_elfData.endian != Elf_ELFDATA2LSB && m_elfData.endian != Elf_ELFDATA2MSB) {\n m_errorString = QLibrary::tr(\"'%1' is an invalid ELF object (%2)\")\n .arg(m_binary).arg(QLatin1String(\"odd endianess\"));\n return Corrupt;\n }\n\n const uchar *data = mapper.ustart + 16; \/\/ e_ident\n m_elfData.elftype = ElfType(getHalfWord(data, m_elfData));\n m_elfData.elfmachine = ElfMachine(getHalfWord(data, m_elfData));\n \/* e_version = *\/ getWord(data, m_elfData);\n m_elfData.entryPoint = getAddress(data, m_elfData);\n\n quint64 e_phoff = getOffset(data, m_elfData);\n quint64 e_shoff = getOffset(data, m_elfData);\n \/* e_flags = *\/ getWord(data, m_elfData);\n\n quint32 e_shsize = getHalfWord(data, m_elfData);\n\n if (e_shsize > fdlen) {\n m_errorString = QLibrary::tr(\"'%1' is an invalid ELF object (%2)\")\n .arg(m_binary).arg(QLatin1String(\"unexpected e_shsize\"));\n return Corrupt;\n }\n\n quint32 e_phentsize = getHalfWord(data, m_elfData);\n QTC_CHECK(e_phentsize == (is64Bit ? 56 : 32));\n quint32 e_phnum = getHalfWord(data, m_elfData);\n\n quint32 e_shentsize = getHalfWord(data, m_elfData);\n\n if (e_shentsize % 4) {\n m_errorString = QLibrary::tr(\"'%1' is an invalid ELF object (%2)\")\n .arg(m_binary).arg(QLatin1String(\"unexpected e_shentsize\"));\n return Corrupt;\n }\n\n quint32 e_shnum = getHalfWord(data, m_elfData);\n quint32 e_shtrndx = getHalfWord(data, m_elfData);\n QTC_CHECK(data == mapper.ustart + (is64Bit ? 64 : 52));\n\n if (quint64(e_shnum) * e_shentsize > fdlen) {\n m_errorString = QLibrary::tr(\"'%1' is an invalid ELF object (%2)\")\n .arg(m_binary)\n .arg(QLatin1String(\"announced %2 sections, each %3 bytes, exceed file size\"))\n .arg(e_shnum).arg(e_shentsize);\n return Corrupt;\n }\n\n quint64 soff = e_shoff + e_shentsize * e_shtrndx;\n\n\/\/ if ((soff + e_shentsize) > fdlen || soff % 4 || soff == 0) {\n\/\/ m_errorString = QLibrary::tr(\"'%1' is an invalid ELF object (%2)\")\n\/\/ .arg(m_binary)\n\/\/ .arg(QLatin1String(\"shstrtab section header seems to be at %1\"))\n\/\/ .arg(QString::number(soff, 16));\n\/\/ return Corrupt;\n\/\/ }\n\n if (e_shoff) {\n ElfSectionHeader strtab;\n parseSectionHeader(mapper.ustart + soff, &strtab, m_elfData);\n const quint64 stringTableFileOffset = strtab.offset;\n\n if (quint32(stringTableFileOffset + e_shentsize) >= fdlen\n || stringTableFileOffset == 0) {\n m_errorString = QLibrary::tr(\"'%1' is an invalid ELF object (%2)\")\n .arg(m_binary)\n .arg(QLatin1String(\"string table seems to be at %1\"))\n .arg(QString::number(soff, 16));\n return Corrupt;\n }\n\n for (int i = 0; i < e_shnum; ++i) {\n const uchar *s = mapper.ustart + e_shoff + i * e_shentsize;\n ElfSectionHeader sh;\n parseSectionHeader(s, &sh, m_elfData);\n\n if (stringTableFileOffset + sh.index > fdlen) {\n m_errorString = QLibrary::tr(\"'%1' is an invalid ELF object (%2)\")\n .arg(m_binary)\n .arg(QLatin1String(\"section name %2 of %3 behind end of file\"))\n .arg(i).arg(e_shnum);\n return Corrupt;\n }\n\n sh.name = mapper.start + stringTableFileOffset + sh.index;\n if (sh.name == \".gdb_index\") {\n m_elfData.symbolsType = FastSymbols;\n } else if (sh.name == \".debug_info\") {\n m_elfData.symbolsType = PlainSymbols;\n } else if (sh.name == \".gnu_debuglink\") {\n m_elfData.debugLink = QByteArray(mapper.start + sh.offset);\n m_elfData.symbolsType = LinkedSymbols;\n } else if (sh.name == \".note.gnu.build-id\") {\n m_elfData.symbolsType = BuildIdSymbols;\n if (sh.size > 16)\n m_elfData.buildId = QByteArray(mapper.start + sh.offset + 16,\n sh.size - 16).toHex();\n }\n m_elfData.sectionHeaders.append(sh);\n }\n }\n\n if (e_phoff) {\n for (int i = 0; i < e_phnum; ++i) {\n const uchar *s = mapper.ustart + e_phoff + i * e_phentsize;\n ElfProgramHeader ph;\n parseProgramHeader(s, &ph, m_elfData);\n m_elfData.programHeaders.append(ph);\n }\n }\n return Ok;\n}\n\nQByteArray ElfReader::readSection(const QByteArray &name)\n{\n readIt();\n int i = m_elfData.indexOf(name);\n if (i == -1)\n return QByteArray();\n\n ElfMapper mapper(this);\n if (!mapper.map())\n return QByteArray();\n\n const ElfSectionHeader §ion = m_elfData.sectionHeaders.at(i);\n return QByteArray(mapper.start + section.offset, section.size);\n}\n\nQByteArray ElfReader::readCoreName(bool *isCore)\n{\n *isCore = false;\n\n readIt();\n\n ElfMapper mapper(this);\n if (!mapper.map())\n return QByteArray();\n\n if (m_elfData.elftype != Elf_ET_CORE)\n return QByteArray();\n\n *isCore = true;\n\n for (int i = 0, n = m_elfData.sectionHeaders.size(); i != n; ++i)\n if (m_elfData.sectionHeaders.at(i).type == Elf_SHT_NOTE) {\n const ElfSectionHeader &header = m_elfData.sectionHeaders.at(i);\n const char *s = mapper.start + header.offset + 0x40;\n return QByteArray(s);\n }\n\n for (int i = 0, n = m_elfData.programHeaders.size(); i != n; ++i)\n if (m_elfData.programHeaders.at(i).type == Elf_PT_NOTE) {\n const ElfProgramHeader &header = m_elfData.programHeaders.at(i);\n const char *s = mapper.start + header.offset + 0xec;\n return QByteArray(s);\n }\n\n return QByteArray();\n}\n\nint ElfData::indexOf(const QByteArray &name) const\n{\n for (int i = 0, n = sectionHeaders.size(); i != n; ++i)\n if (sectionHeaders.at(i).name == name)\n return i;\n return -1;\n}\n\n} \/\/ namespace Utils\n<|endoftext|>"} {"text":"<commit_before>\/\/---------------------------------------------------------------------------\n\/\/ $Id$\n\/\/ Version: $Name$\n\/\/\n\/\/ Copyright (C) 2005, 2006, 2007, 2009, 2012 by the deal.II authors\n\/\/\n\/\/ This file is subject to QPL and may not be distributed\n\/\/ without copyright and license information. Please refer\n\/\/ to the file deal.II\/doc\/license.html for the text and\n\/\/ further information on this license.\n\/\/\n\/\/---------------------------------------------------------------------------\n\n#include <deal.II\/base\/function_parser.h>\n#include <deal.II\/base\/utilities.h>\n#include <deal.II\/lac\/vector.h>\n\n#ifdef HAVE_FUNCTIONPARSER\nnamespace fparser\n{\n# include <fparser.hh>\n}\n#else\n\nnamespace fparser\n{\n class FunctionParser\n {};\n}\n\n#endif\n\nDEAL_II_NAMESPACE_OPEN\n\n\n\ntemplate <int dim>\nFunctionParser<dim>::FunctionParser(const unsigned int n_components,\n const double initial_time)\n :\n Function<dim>(n_components, initial_time),\n fp (0)\n{\n fp = new fparser::FunctionParser[n_components];\n}\n\n\n\ntemplate <int dim>\nFunctionParser<dim>::~FunctionParser()\n{\n delete[] fp;\n}\n\n\n#ifdef HAVE_FUNCTIONPARSER\ntemplate <int dim>\nvoid FunctionParser<dim>::initialize (const std::string &variables,\n const std::vector<std::string> &expressions,\n const std::map<std::string, double> &constants,\n const bool time_dependent,\n const bool use_degrees)\n{\n initialize (variables,\n expressions,\n constants,\n std::map< std::string, double >(),\n time_dependent,\n use_degrees);\n}\n\n\n\ntemplate <int dim>\nvoid FunctionParser<dim>::initialize (const std::string &variables,\n const std::vector<std::string> &expressions,\n const std::map<std::string, double> &constants,\n const std::map<std::string, double> &units,\n const bool time_dependent,\n const bool use_degrees)\n{\n \/\/ We check that the number of\n \/\/ components of this function\n \/\/ matches the number of components\n \/\/ passed in as a vector of\n \/\/ strings.\n AssertThrow(this->n_components == expressions.size(),\n ExcInvalidExpressionSize(this->n_components,\n expressions.size()) );\n\n\n\n for (unsigned int i=0; i<this->n_components; ++i)\n {\n\n \/\/ Add the various units to\n \/\/ the parser.\n std::map< std::string, double >::const_iterator\n unit = units.begin(),\n endu = units.end();\n for (; unit != endu; ++unit)\n {\n const bool success = fp[i].AddUnit(unit->first, unit->second);\n AssertThrow (success,\n ExcMessage(\"Invalid Unit Name [error adding a unit]\"));\n }\n\n\n\n \/\/ Add the various constants to\n \/\/ the parser.\n std::map< std::string, double >::const_iterator\n constant = constants.begin(),\n endc = constants.end();\n for(; constant != endc; ++constant)\n {\n const bool success = fp[i].AddConstant(constant->first, constant->second);\n AssertThrow (success, ExcMessage(\"Invalid Constant Name\"));\n }\n\n const int ret_value = fp[i].Parse(expressions[i],\n variables,\n use_degrees);\n AssertThrow (ret_value == -1,\n ExcParseError(ret_value, fp[i].ErrorMsg()));\n\n \/\/ The fact that the parser did\n \/\/ not throw an error does not\n \/\/ mean that everything went\n \/\/ ok... we can still have\n \/\/ problems with the number of\n \/\/ variables...\n }\n\/*\nTODO: Remove or port to fparser 4.5\n \/\/ Now we define how many variables\n \/\/ we expect to read in. We\n \/\/ distinguish between two cases:\n \/\/ Time dependent problems, and not\n \/\/ time dependent problems. In the\n \/\/ first case the number of\n \/\/ variables is given by the\n \/\/ dimension plus one. In the other\n \/\/ case, the number of variables is\n \/\/ equal to the dimension. Once we\n \/\/ parsed the variables string, if\n \/\/ none of this is the case, then\n \/\/ an exception is thrown.\n if (time_dependent)\n n_vars = dim+1;\n else\n n_vars = dim;\n\n \/\/ Let's check if the number of\n \/\/ variables is correct...\n AssertThrow (n_vars == fp[0].NVars(),\n ExcDimensionMismatch(n_vars,fp[0].NVars()));\n\n \/\/ Now set the initialization bit.\n*\/\n initialized = true;\n}\n\n\n\ntemplate <int dim>\nvoid FunctionParser<dim>::initialize (const std::string &variables,\n const std::string &expression,\n const std::map<std::string, double> &constants,\n const bool time_dependent,\n const bool use_degrees)\n{\n \/\/ initialize with the things\n \/\/ we got.\n initialize (variables,\n Utilities::split_string_list (expression, ';'),\n constants,\n time_dependent,\n use_degrees);\n}\n\n\n\ntemplate <int dim>\nvoid FunctionParser<dim>::initialize (const std::string &variables,\n const std::string &expression,\n const std::map<std::string, double> &constants,\n const std::map<std::string, double> &units,\n const bool time_dependent,\n const bool use_degrees)\n{\n \/\/ initialize with the things\n \/\/ we got.\n initialize (variables,\n Utilities::split_string_list (expression, ';'),\n constants,\n units,\n time_dependent,\n use_degrees);\n}\n\n\n\ntemplate <int dim>\ndouble FunctionParser<dim>::value (const Point<dim> &p,\n const unsigned int component) const\n{\n Assert (initialized==true, ExcNotInitialized());\n Assert (component < this->n_components,\n ExcIndexRange(component, 0, this->n_components));\n\n \/\/ Statically allocate dim+1\n \/\/ double variables.\n double vars[dim+1];\n\n for (unsigned int i=0; i<dim; ++i)\n vars[i] = p(i);\n\n \/\/ We need the time variable only\n \/\/ if the number of variables is\n \/\/ different from the dimension. In\n \/\/ this case it can only be dim+1,\n \/\/ otherwise an exception would\n \/\/ have already been thrown\n if (dim != n_vars)\n vars[dim] = this->get_time();\n\n double my_value = fp[component].Eval((double*)vars);\n\n AssertThrow (fp[component].EvalError() == 0,\n ExcMessage(fp[component].ErrorMsg()));\n return my_value;\n}\n\n\n\ntemplate <int dim>\nvoid FunctionParser<dim>::vector_value (const Point<dim> &p,\n Vector<double> &values) const\n{\n Assert (initialized==true, ExcNotInitialized());\n Assert (values.size() == this->n_components,\n ExcDimensionMismatch (values.size(), this->n_components));\n\n \/\/ Statically allocates dim+1\n \/\/ double variables.\n double vars[dim+1];\n\n for(unsigned int i=0; i<dim; ++i)\n vars[i] = p(i);\n\n \/\/ We need the time variable only\n \/\/ if the number of variables is\n \/\/ different from the dimension. In\n \/\/ this case it can only be dim+1,\n \/\/ otherwise an exception would\n \/\/ have already been thrown\n if(dim != n_vars)\n vars[dim] = this->get_time();\n\n for(unsigned int component = 0; component < this->n_components;\n ++component)\n {\n values(component) = fp[component].Eval((double*)vars);\n AssertThrow(fp[component].EvalError() == 0,\n ExcMessage(fp[component].ErrorMsg()));\n }\n}\n\n#else\n\n\ntemplate <int dim>\nvoid\nFunctionParser<dim>::initialize(const std::string &,\n const std::vector<std::string> &,\n const std::map<std::string, double> &,\n const bool,\n const bool)\n{\n Assert(false, ExcDisabled(\"parser\"));\n}\n\n\ntemplate <int dim>\nvoid\nFunctionParser<dim>::initialize(const std::string &,\n const std::string &,\n const std::map<std::string, double> &,\n const bool,\n const bool)\n{\n Assert(false, ExcDisabled(\"parser\"));\n}\n\n\ntemplate <int dim>\ndouble FunctionParser<dim>::value (\n const Point<dim> &, unsigned int) const\n{\n Assert(false, ExcDisabled(\"parser\"));\n return 0.;\n}\n\n\ntemplate <int dim>\nvoid FunctionParser<dim>::vector_value (\n const Point<dim>&, Vector<double>&) const\n{\n Assert(false, ExcDisabled(\"parser\"));\n}\n\n\n#endif\n\n\/\/ Explicit Instantiations.\n\ntemplate class FunctionParser<1>;\ntemplate class FunctionParser<2>;\ntemplate class FunctionParser<3>;\n\nDEAL_II_NAMESPACE_CLOSE\n<commit_msg>Bugfix<commit_after>\/\/---------------------------------------------------------------------------\n\/\/ $Id$\n\/\/ Version: $Name$\n\/\/\n\/\/ Copyright (C) 2005, 2006, 2007, 2009, 2012 by the deal.II authors\n\/\/\n\/\/ This file is subject to QPL and may not be distributed\n\/\/ without copyright and license information. Please refer\n\/\/ to the file deal.II\/doc\/license.html for the text and\n\/\/ further information on this license.\n\/\/\n\/\/---------------------------------------------------------------------------\n\n#include <deal.II\/base\/function_parser.h>\n#include <deal.II\/base\/utilities.h>\n#include <deal.II\/lac\/vector.h>\n\n#ifdef HAVE_FUNCTIONPARSER\n#include <fparser.hh>\nnamespace fparser\n{\n class FunctionParser: public ::FunctionParser\n {};\n}\n#else\n\nnamespace fparser\n{\n class FunctionParser\n {};\n}\n\n#endif\n\nDEAL_II_NAMESPACE_OPEN\n\n\n\ntemplate <int dim>\nFunctionParser<dim>::FunctionParser(const unsigned int n_components,\n const double initial_time)\n :\n Function<dim>(n_components, initial_time),\n fp (0)\n{\n fp = new fparser::FunctionParser[n_components];\n}\n\n\n\ntemplate <int dim>\nFunctionParser<dim>::~FunctionParser()\n{\n delete[] fp;\n}\n\n\n#ifdef HAVE_FUNCTIONPARSER\ntemplate <int dim>\nvoid FunctionParser<dim>::initialize (const std::string &variables,\n const std::vector<std::string> &expressions,\n const std::map<std::string, double> &constants,\n const bool time_dependent,\n const bool use_degrees)\n{\n initialize (variables,\n expressions,\n constants,\n std::map< std::string, double >(),\n time_dependent,\n use_degrees);\n}\n\n\n\ntemplate <int dim>\nvoid FunctionParser<dim>::initialize (const std::string &variables,\n const std::vector<std::string> &expressions,\n const std::map<std::string, double> &constants,\n const std::map<std::string, double> &units,\n const bool time_dependent,\n const bool use_degrees)\n{\n \/\/ We check that the number of\n \/\/ components of this function\n \/\/ matches the number of components\n \/\/ passed in as a vector of\n \/\/ strings.\n AssertThrow(this->n_components == expressions.size(),\n ExcInvalidExpressionSize(this->n_components,\n expressions.size()) );\n\n\n\n for (unsigned int i=0; i<this->n_components; ++i)\n {\n\n \/\/ Add the various units to\n \/\/ the parser.\n std::map< std::string, double >::const_iterator\n unit = units.begin(),\n endu = units.end();\n for (; unit != endu; ++unit)\n {\n const bool success = fp[i].AddUnit(unit->first, unit->second);\n AssertThrow (success,\n ExcMessage(\"Invalid Unit Name [error adding a unit]\"));\n }\n\n\n\n \/\/ Add the various constants to\n \/\/ the parser.\n std::map< std::string, double >::const_iterator\n constant = constants.begin(),\n endc = constants.end();\n for(; constant != endc; ++constant)\n {\n const bool success = fp[i].AddConstant(constant->first, constant->second);\n AssertThrow (success, ExcMessage(\"Invalid Constant Name\"));\n }\n\n const int ret_value = fp[i].Parse(expressions[i],\n variables,\n use_degrees);\n AssertThrow (ret_value == -1,\n ExcParseError(ret_value, fp[i].ErrorMsg()));\n\n \/\/ The fact that the parser did\n \/\/ not throw an error does not\n \/\/ mean that everything went\n \/\/ ok... we can still have\n \/\/ problems with the number of\n \/\/ variables...\n }\n\/*\nTODO: Remove or port to fparser 4.5\n \/\/ Now we define how many variables\n \/\/ we expect to read in. We\n \/\/ distinguish between two cases:\n \/\/ Time dependent problems, and not\n \/\/ time dependent problems. In the\n \/\/ first case the number of\n \/\/ variables is given by the\n \/\/ dimension plus one. In the other\n \/\/ case, the number of variables is\n \/\/ equal to the dimension. Once we\n \/\/ parsed the variables string, if\n \/\/ none of this is the case, then\n \/\/ an exception is thrown.\n if (time_dependent)\n n_vars = dim+1;\n else\n n_vars = dim;\n\n \/\/ Let's check if the number of\n \/\/ variables is correct...\n AssertThrow (n_vars == fp[0].NVars(),\n ExcDimensionMismatch(n_vars,fp[0].NVars()));\n\n \/\/ Now set the initialization bit.\n*\/\n initialized = true;\n}\n\n\n\ntemplate <int dim>\nvoid FunctionParser<dim>::initialize (const std::string &variables,\n const std::string &expression,\n const std::map<std::string, double> &constants,\n const bool time_dependent,\n const bool use_degrees)\n{\n \/\/ initialize with the things\n \/\/ we got.\n initialize (variables,\n Utilities::split_string_list (expression, ';'),\n constants,\n time_dependent,\n use_degrees);\n}\n\n\n\ntemplate <int dim>\nvoid FunctionParser<dim>::initialize (const std::string &variables,\n const std::string &expression,\n const std::map<std::string, double> &constants,\n const std::map<std::string, double> &units,\n const bool time_dependent,\n const bool use_degrees)\n{\n \/\/ initialize with the things\n \/\/ we got.\n initialize (variables,\n Utilities::split_string_list (expression, ';'),\n constants,\n units,\n time_dependent,\n use_degrees);\n}\n\n\n\ntemplate <int dim>\ndouble FunctionParser<dim>::value (const Point<dim> &p,\n const unsigned int component) const\n{\n Assert (initialized==true, ExcNotInitialized());\n Assert (component < this->n_components,\n ExcIndexRange(component, 0, this->n_components));\n\n \/\/ Statically allocate dim+1\n \/\/ double variables.\n double vars[dim+1];\n\n for (unsigned int i=0; i<dim; ++i)\n vars[i] = p(i);\n\n \/\/ We need the time variable only\n \/\/ if the number of variables is\n \/\/ different from the dimension. In\n \/\/ this case it can only be dim+1,\n \/\/ otherwise an exception would\n \/\/ have already been thrown\n if (dim != n_vars)\n vars[dim] = this->get_time();\n\n double my_value = fp[component].Eval((double*)vars);\n\n AssertThrow (fp[component].EvalError() == 0,\n ExcMessage(fp[component].ErrorMsg()));\n return my_value;\n}\n\n\n\ntemplate <int dim>\nvoid FunctionParser<dim>::vector_value (const Point<dim> &p,\n Vector<double> &values) const\n{\n Assert (initialized==true, ExcNotInitialized());\n Assert (values.size() == this->n_components,\n ExcDimensionMismatch (values.size(), this->n_components));\n\n \/\/ Statically allocates dim+1\n \/\/ double variables.\n double vars[dim+1];\n\n for(unsigned int i=0; i<dim; ++i)\n vars[i] = p(i);\n\n \/\/ We need the time variable only\n \/\/ if the number of variables is\n \/\/ different from the dimension. In\n \/\/ this case it can only be dim+1,\n \/\/ otherwise an exception would\n \/\/ have already been thrown\n if(dim != n_vars)\n vars[dim] = this->get_time();\n\n for(unsigned int component = 0; component < this->n_components;\n ++component)\n {\n values(component) = fp[component].Eval((double*)vars);\n AssertThrow(fp[component].EvalError() == 0,\n ExcMessage(fp[component].ErrorMsg()));\n }\n}\n\n#else\n\n\ntemplate <int dim>\nvoid\nFunctionParser<dim>::initialize(const std::string &,\n const std::vector<std::string> &,\n const std::map<std::string, double> &,\n const bool,\n const bool)\n{\n Assert(false, ExcDisabled(\"parser\"));\n}\n\n\ntemplate <int dim>\nvoid\nFunctionParser<dim>::initialize(const std::string &,\n const std::string &,\n const std::map<std::string, double> &,\n const bool,\n const bool)\n{\n Assert(false, ExcDisabled(\"parser\"));\n}\n\n\ntemplate <int dim>\ndouble FunctionParser<dim>::value (\n const Point<dim> &, unsigned int) const\n{\n Assert(false, ExcDisabled(\"parser\"));\n return 0.;\n}\n\n\ntemplate <int dim>\nvoid FunctionParser<dim>::vector_value (\n const Point<dim>&, Vector<double>&) const\n{\n Assert(false, ExcDisabled(\"parser\"));\n}\n\n\n#endif\n\n\/\/ Explicit Instantiations.\n\ntemplate class FunctionParser<1>;\ntemplate class FunctionParser<2>;\ntemplate class FunctionParser<3>;\n\nDEAL_II_NAMESPACE_CLOSE\n<|endoftext|>"} {"text":"<commit_before>\/\/ ---------------------------------------------------------------------\n\/\/ $Id$\n\/\/\n\/\/ Copyright (C) 2005 - 2013 by the deal.II authors\n\/\/\n\/\/ This file is part of the deal.II library.\n\/\/\n\/\/ The deal.II library is free software; you can use it, redistribute\n\/\/ it, and\/or modify it under the terms of the GNU Lesser General\n\/\/ Public License as published by the Free Software Foundation; either\n\/\/ version 2.1 of the License, or (at your option) any later version.\n\/\/ The full text of the license can be found in the file LICENSE at\n\/\/ the top level of the deal.II distribution.\n\/\/\n\/\/ ---------------------------------------------------------------------\n\n\n#include <deal.II\/base\/function_parser.h>\n#include <deal.II\/base\/utilities.h>\n#include <deal.II\/lac\/vector.h>\n\n\n#ifdef DEAL_II_WITH_MUPARSER\n#include <muParser.h>\n#else\n\nnamespace fparser\n{\n class FunctionParser\n {};\n}\n#endif\n\nDEAL_II_NAMESPACE_OPEN\n\n\n\ntemplate <int dim>\nFunctionParser<dim>::FunctionParser(const unsigned int n_components,\n const double initial_time)\n :\n Function<dim>(n_components, initial_time)\n{}\n\n\n\ntemplate <int dim>\nFunctionParser<dim>::~FunctionParser()\n{}\n\n#ifdef DEAL_II_WITH_MUPARSER\ntemplate <int dim>\nvoid FunctionParser<dim>::initialize (const std::string &variables,\n const std::vector<std::string> &expressions,\n const std::map<std::string, double> &constants,\n const bool time_dependent,\n const bool use_degrees)\n{\n initialize (variables,\n expressions,\n constants,\n std::map< std::string, double >(),\n time_dependent,\n use_degrees);\n}\n\ntemplate <int dim>\nvoid FunctionParser<dim>::initialize (const std::string &vars,\n\t\t\t\t const std::vector<std::string> &expressions,\n\t\t\t\t const std::map<std::string, double> &constants,\n\t\t\t\t const bool time_dependent)\n {\n initialize(vars, expressions, constants, time_dependent, false);\n }\n\nnamespace internal\n{\n \/\/ convert double into int\n int mu_round(double val)\n {\n return static_cast<int>(val + ((val>=0.0) ? 0.5 : -0.5) );\n }\n \n double mu_if(double condition, double thenvalue, double elsevalue)\n {\n if (mu_round(condition))\n return thenvalue;\n else\n return elsevalue;\n }\n \n double mu_or(double left, double right)\n {\n return (mu_round(left)) || (mu_round(right));\n }\n \n double mu_and(double left, double right)\n {\n return (mu_round(left)) && (mu_round(right));\n }\n \n double mu_int(double value)\n {\n return static_cast<double>(mu_round(value));\n }\n double mu_ceil(double value)\n {\n return ceil(value);\n }\n double mu_floor(double value)\n {\n return floor(value);\n }\n double mu_cot(double value)\n {\n return 1.0\/tan(value);\n }\n double mu_csc(double value)\n {\n return 1.0\/sin(value);\n }\n double mu_sec(double value)\n {\n return 1.0\/cos(value);\n }\n double mu_log(double value)\n {\n return log(value);\n }\n \n\n \n}\n\ntemplate <int dim>\nvoid FunctionParser<dim>:: init_muparser() const\n{\n if (fp.get().size()>0)\n return;\n \n fp.get().resize(this->n_components);\n vars.get().resize(var_names.size());\n for (unsigned int i=0; i<this->n_components; ++i)\n {\n std::map< std::string, double >::const_iterator\n\tconstant = constants.begin(),\n\tendc = constants.end();\n\n for (; constant != endc; ++constant)\n {\n \t fp.get()[i].DefineConst(constant->first.c_str(), constant->second);\n\t}\n\n for (unsigned int iv=0;iv<var_names.size();++iv)\n\tfp.get()[i].DefineVar(var_names[iv].c_str(), &vars.get()[iv]);\n\n \/\/ define some compatibility functions:\n fp.get()[i].DefineFun(\"if\",internal::mu_if, true);\n fp.get()[i].DefineOprt(\"|\", internal::mu_or, 1);\n fp.get()[i].DefineOprt(\"&\", internal::mu_and, 2);\n fp.get()[i].DefineFun(\"int\", internal::mu_int, true);\n fp.get()[i].DefineFun(\"ceil\", internal::mu_ceil, true);\n fp.get()[i].DefineFun(\"cot\", internal::mu_cot, true);\n fp.get()[i].DefineFun(\"csc\", internal::mu_csc, true);\n fp.get()[i].DefineFun(\"floor\", internal::mu_floor, true);\n fp.get()[i].DefineFun(\"sec\", internal::mu_sec, true);\n fp.get()[i].DefineFun(\"log\", internal::mu_log, true);\n \n try\n\t{\n\t fp.get()[i].SetExpr(expressions[i]);\n\t}\n catch (mu::ParserError &e)\n\t{\n std::cerr << \"Message: \" << e.GetMsg() << \"\\n\";\n\t std::cerr << \"Formula: \" << e.GetExpr() << \"\\n\";\n\t std::cerr << \"Token: \" << e.GetToken() << \"\\n\";\n\t std::cerr << \"Position: \" << e.GetPos() << \"\\n\";\n\t std::cerr << \"Errc: \" << e.GetCode() << std::endl;\t \n\t AssertThrow(false, ExcParseError(e.GetCode(), e.GetMsg().c_str()));\n\t} \n }\n}\n\ntemplate <int dim>\nvoid FunctionParser<dim>::initialize (const std::string &variables,\n const std::vector<std::string> &expressions,\n const std::map<std::string, double> &constants,\n const std::map<std::string, double> &units,\n const bool time_dependent,\n const bool use_degrees)\n{\n\n this->fp.clear(); \/\/ this will reset all thread-local objects\n \n this->constants = constants;\n this->var_names = Utilities::split_string_list(variables, ',');\n this->expressions = expressions;\n AssertThrow(((time_dependent)?dim+1:dim) == var_names.size(),\n\t ExcMessage(\"wrong number of variables\"));\n AssertThrow(!use_degrees, ExcNotImplemented());\n\n \/\/ We check that the number of\n \/\/ components of this function\n \/\/ matches the number of components\n \/\/ passed in as a vector of\n \/\/ strings.\n AssertThrow(this->n_components == expressions.size(),\n ExcInvalidExpressionSize(this->n_components,\n expressions.size()) );\n\n \/\/ we no longer support units:\n AssertThrow(units.size()==0, ExcNotImplemented());\n\n \/\/ Now we define how many variables\n \/\/ we expect to read in. We\n \/\/ distinguish between two cases:\n \/\/ Time dependent problems, and not\n \/\/ time dependent problems. In the\n \/\/ first case the number of\n \/\/ variables is given by the\n \/\/ dimension plus one. In the other\n \/\/ case, the number of variables is\n \/\/ equal to the dimension. Once we\n \/\/ parsed the variables string, if\n \/\/ none of this is the case, then\n \/\/ an exception is thrown.\n if (time_dependent)\n n_vars = dim+1;\n else\n n_vars = dim;\n\n init_muparser();\n \n \/\/ Now set the initialization bit.\n initialized = true;\n}\n\ntemplate <int dim>\nvoid FunctionParser<dim>::initialize (const std::string &vars,\n const std::string &expression,\n const std::map<std::string, double> &constants,\n const bool time_dependent)\n{\n initialize(vars, expression, constants, time_dependent, false);\n}\n\n\ntemplate <int dim>\nvoid FunctionParser<dim>::initialize (const std::string &variables,\n const std::string &expression,\n const std::map<std::string, double> &constants,\n const bool time_dependent,\n const bool use_degrees)\n{\n \/\/ initialize with the things\n \/\/ we got.\n initialize (variables,\n Utilities::split_string_list (expression, ';'),\n constants,\n time_dependent,\n use_degrees);\n}\n\n\n\ntemplate <int dim>\nvoid FunctionParser<dim>::initialize (const std::string &variables,\n const std::string &expression,\n const std::map<std::string, double> &constants,\n const std::map<std::string, double> &units,\n const bool time_dependent,\n const bool use_degrees)\n{\n \/\/ initialize with the things\n \/\/ we got.\n initialize (variables,\n Utilities::split_string_list (expression, ';'),\n constants,\n units,\n time_dependent,\n use_degrees);\n}\n\n\n\ntemplate <int dim>\ndouble FunctionParser<dim>::value (const Point<dim> &p,\n const unsigned int component) const\n{\n Assert (initialized==true, ExcNotInitialized());\n Assert (component < this->n_components,\n ExcIndexRange(component, 0, this->n_components));\n\n \/\/ initialize if not done so on this thread yet:\n init_muparser();\n\n for (unsigned int i=0; i<dim; ++i)\n vars.get()[i] = p(i);\n if (dim != n_vars)\n vars.get()[dim] = this->get_time();\n\n try\n {\n return fp.get()[component].Eval();\n }\n catch (mu::ParserError &e)\n {\n std::cerr << \"Message: \" << e.GetMsg() << \"\\n\";\n std::cerr << \"Formula: \" << e.GetExpr() << \"\\n\";\n std::cerr << \"Token: \" << e.GetToken() << \"\\n\";\n std::cerr << \"Position: \" << e.GetPos() << \"\\n\";\n std::cerr << \"Errc: \" << e.GetCode() << std::endl;\t \n AssertThrow(false, ExcParseError(e.GetCode(), e.GetMsg().c_str()));\n return 0.0;\n }\n}\n\n\n\ntemplate <int dim>\nvoid FunctionParser<dim>::vector_value (const Point<dim> &p,\n Vector<double> &values) const\n{\n Assert (initialized==true, ExcNotInitialized());\n Assert (values.size() == this->n_components,\n ExcDimensionMismatch (values.size(), this->n_components));\n\n\n \/\/ initialize if not done so on this thread yet:\n init_muparser();\n\n for (unsigned int i=0; i<dim; ++i)\n vars.get()[i] = p(i);\n if (dim != n_vars)\n vars.get()[dim] = this->get_time();\n \n for (unsigned int component = 0; component < this->n_components;\n ++component)\n values(component) = fp.get()[component].Eval();\n}\n\n#else\n\ntemplate <int dim>\nvoid\nFunctionParser<dim>::initialize(const std::string &,\n const std::vector<std::string> &,\n const std::map<std::string, double> &,\n const bool,\n const bool)\n{\n Assert(false, ExcNeedsFunctionparser());\n}\n\n\ntemplate <int dim>\nvoid\nFunctionParser<dim>::initialize(const std::string &,\n const std::vector<std::string> &,\n const std::map<std::string, double> &,\n const std::map<std::string, double> &,\n const bool,\n const bool)\n{\n Assert(false, ExcNeedsFunctionparser());\n}\n\n\ntemplate <int dim>\nvoid\nFunctionParser<dim>::initialize(const std::string &,\n const std::string &,\n const std::map<std::string, double> &,\n const bool,\n const bool)\n{\n Assert(false, ExcNeedsFunctionparser());\n}\n\n\ntemplate <int dim>\nvoid\nFunctionParser<dim>::initialize(const std::string &,\n const std::string &,\n const std::map<std::string, double> &,\n const std::map<std::string, double> &,\n const bool,\n const bool)\n{\n Assert(false, ExcNeedsFunctionparser());\n}\n\n\ntemplate <int dim>\ndouble FunctionParser<dim>::value (\n const Point<dim> &, unsigned int) const\n{\n Assert(false, ExcNeedsFunctionparser());\n return 0.;\n}\n\n\ntemplate <int dim>\nvoid FunctionParser<dim>::vector_value (\n const Point<dim> &, Vector<double> &) const\n{\n Assert(false, ExcNeedsFunctionparser());\n}\n\n\n#endif\n\n\/\/ Explicit Instantiations.\n\ntemplate class FunctionParser<1>;\ntemplate class FunctionParser<2>;\ntemplate class FunctionParser<3>;\n\nDEAL_II_NAMESPACE_CLOSE\n<commit_msg>add missing instantiations if not configuring muparser<commit_after>\/\/ ---------------------------------------------------------------------\n\/\/ $Id$\n\/\/\n\/\/ Copyright (C) 2005 - 2013 by the deal.II authors\n\/\/\n\/\/ This file is part of the deal.II library.\n\/\/\n\/\/ The deal.II library is free software; you can use it, redistribute\n\/\/ it, and\/or modify it under the terms of the GNU Lesser General\n\/\/ Public License as published by the Free Software Foundation; either\n\/\/ version 2.1 of the License, or (at your option) any later version.\n\/\/ The full text of the license can be found in the file LICENSE at\n\/\/ the top level of the deal.II distribution.\n\/\/\n\/\/ ---------------------------------------------------------------------\n\n\n#include <deal.II\/base\/function_parser.h>\n#include <deal.II\/base\/utilities.h>\n#include <deal.II\/lac\/vector.h>\n\n\n#ifdef DEAL_II_WITH_MUPARSER\n#include <muParser.h>\n#else\n\nnamespace fparser\n{\n class FunctionParser\n {};\n}\n#endif\n\nDEAL_II_NAMESPACE_OPEN\n\n\n\ntemplate <int dim>\nFunctionParser<dim>::FunctionParser(const unsigned int n_components,\n const double initial_time)\n :\n Function<dim>(n_components, initial_time)\n{}\n\n\n\ntemplate <int dim>\nFunctionParser<dim>::~FunctionParser()\n{}\n\n#ifdef DEAL_II_WITH_MUPARSER\ntemplate <int dim>\nvoid FunctionParser<dim>::initialize (const std::string &variables,\n const std::vector<std::string> &expressions,\n const std::map<std::string, double> &constants,\n const bool time_dependent,\n const bool use_degrees)\n{\n initialize (variables,\n expressions,\n constants,\n std::map< std::string, double >(),\n time_dependent,\n use_degrees);\n}\n\ntemplate <int dim>\nvoid FunctionParser<dim>::initialize (const std::string &vars,\n\t\t\t\t const std::vector<std::string> &expressions,\n\t\t\t\t const std::map<std::string, double> &constants,\n\t\t\t\t const bool time_dependent)\n {\n initialize(vars, expressions, constants, time_dependent, false);\n }\n\nnamespace internal\n{\n \/\/ convert double into int\n int mu_round(double val)\n {\n return static_cast<int>(val + ((val>=0.0) ? 0.5 : -0.5) );\n }\n \n double mu_if(double condition, double thenvalue, double elsevalue)\n {\n if (mu_round(condition))\n return thenvalue;\n else\n return elsevalue;\n }\n \n double mu_or(double left, double right)\n {\n return (mu_round(left)) || (mu_round(right));\n }\n \n double mu_and(double left, double right)\n {\n return (mu_round(left)) && (mu_round(right));\n }\n \n double mu_int(double value)\n {\n return static_cast<double>(mu_round(value));\n }\n double mu_ceil(double value)\n {\n return ceil(value);\n }\n double mu_floor(double value)\n {\n return floor(value);\n }\n double mu_cot(double value)\n {\n return 1.0\/tan(value);\n }\n double mu_csc(double value)\n {\n return 1.0\/sin(value);\n }\n double mu_sec(double value)\n {\n return 1.0\/cos(value);\n }\n double mu_log(double value)\n {\n return log(value);\n }\n \n\n \n}\n\ntemplate <int dim>\nvoid FunctionParser<dim>:: init_muparser() const\n{\n if (fp.get().size()>0)\n return;\n \n fp.get().resize(this->n_components);\n vars.get().resize(var_names.size());\n for (unsigned int i=0; i<this->n_components; ++i)\n {\n std::map< std::string, double >::const_iterator\n\tconstant = constants.begin(),\n\tendc = constants.end();\n\n for (; constant != endc; ++constant)\n {\n \t fp.get()[i].DefineConst(constant->first.c_str(), constant->second);\n\t}\n\n for (unsigned int iv=0;iv<var_names.size();++iv)\n\tfp.get()[i].DefineVar(var_names[iv].c_str(), &vars.get()[iv]);\n\n \/\/ define some compatibility functions:\n fp.get()[i].DefineFun(\"if\",internal::mu_if, true);\n fp.get()[i].DefineOprt(\"|\", internal::mu_or, 1);\n fp.get()[i].DefineOprt(\"&\", internal::mu_and, 2);\n fp.get()[i].DefineFun(\"int\", internal::mu_int, true);\n fp.get()[i].DefineFun(\"ceil\", internal::mu_ceil, true);\n fp.get()[i].DefineFun(\"cot\", internal::mu_cot, true);\n fp.get()[i].DefineFun(\"csc\", internal::mu_csc, true);\n fp.get()[i].DefineFun(\"floor\", internal::mu_floor, true);\n fp.get()[i].DefineFun(\"sec\", internal::mu_sec, true);\n fp.get()[i].DefineFun(\"log\", internal::mu_log, true);\n \n try\n\t{\n\t fp.get()[i].SetExpr(expressions[i]);\n\t}\n catch (mu::ParserError &e)\n\t{\n std::cerr << \"Message: \" << e.GetMsg() << \"\\n\";\n\t std::cerr << \"Formula: \" << e.GetExpr() << \"\\n\";\n\t std::cerr << \"Token: \" << e.GetToken() << \"\\n\";\n\t std::cerr << \"Position: \" << e.GetPos() << \"\\n\";\n\t std::cerr << \"Errc: \" << e.GetCode() << std::endl;\t \n\t AssertThrow(false, ExcParseError(e.GetCode(), e.GetMsg().c_str()));\n\t} \n }\n}\n\ntemplate <int dim>\nvoid FunctionParser<dim>::initialize (const std::string &variables,\n const std::vector<std::string> &expressions,\n const std::map<std::string, double> &constants,\n const std::map<std::string, double> &units,\n const bool time_dependent,\n const bool use_degrees)\n{\n\n this->fp.clear(); \/\/ this will reset all thread-local objects\n \n this->constants = constants;\n this->var_names = Utilities::split_string_list(variables, ',');\n this->expressions = expressions;\n AssertThrow(((time_dependent)?dim+1:dim) == var_names.size(),\n\t ExcMessage(\"wrong number of variables\"));\n AssertThrow(!use_degrees, ExcNotImplemented());\n\n \/\/ We check that the number of\n \/\/ components of this function\n \/\/ matches the number of components\n \/\/ passed in as a vector of\n \/\/ strings.\n AssertThrow(this->n_components == expressions.size(),\n ExcInvalidExpressionSize(this->n_components,\n expressions.size()) );\n\n \/\/ we no longer support units:\n AssertThrow(units.size()==0, ExcNotImplemented());\n\n \/\/ Now we define how many variables\n \/\/ we expect to read in. We\n \/\/ distinguish between two cases:\n \/\/ Time dependent problems, and not\n \/\/ time dependent problems. In the\n \/\/ first case the number of\n \/\/ variables is given by the\n \/\/ dimension plus one. In the other\n \/\/ case, the number of variables is\n \/\/ equal to the dimension. Once we\n \/\/ parsed the variables string, if\n \/\/ none of this is the case, then\n \/\/ an exception is thrown.\n if (time_dependent)\n n_vars = dim+1;\n else\n n_vars = dim;\n\n init_muparser();\n \n \/\/ Now set the initialization bit.\n initialized = true;\n}\n\ntemplate <int dim>\nvoid FunctionParser<dim>::initialize (const std::string &vars,\n const std::string &expression,\n const std::map<std::string, double> &constants,\n const bool time_dependent)\n{\n initialize(vars, expression, constants, time_dependent, false);\n}\n\n\ntemplate <int dim>\nvoid FunctionParser<dim>::initialize (const std::string &variables,\n const std::string &expression,\n const std::map<std::string, double> &constants,\n const bool time_dependent,\n const bool use_degrees)\n{\n \/\/ initialize with the things\n \/\/ we got.\n initialize (variables,\n Utilities::split_string_list (expression, ';'),\n constants,\n time_dependent,\n use_degrees);\n}\n\n\n\ntemplate <int dim>\nvoid FunctionParser<dim>::initialize (const std::string &variables,\n const std::string &expression,\n const std::map<std::string, double> &constants,\n const std::map<std::string, double> &units,\n const bool time_dependent,\n const bool use_degrees)\n{\n \/\/ initialize with the things\n \/\/ we got.\n initialize (variables,\n Utilities::split_string_list (expression, ';'),\n constants,\n units,\n time_dependent,\n use_degrees);\n}\n\n\n\ntemplate <int dim>\ndouble FunctionParser<dim>::value (const Point<dim> &p,\n const unsigned int component) const\n{\n Assert (initialized==true, ExcNotInitialized());\n Assert (component < this->n_components,\n ExcIndexRange(component, 0, this->n_components));\n\n \/\/ initialize if not done so on this thread yet:\n init_muparser();\n\n for (unsigned int i=0; i<dim; ++i)\n vars.get()[i] = p(i);\n if (dim != n_vars)\n vars.get()[dim] = this->get_time();\n\n try\n {\n return fp.get()[component].Eval();\n }\n catch (mu::ParserError &e)\n {\n std::cerr << \"Message: \" << e.GetMsg() << \"\\n\";\n std::cerr << \"Formula: \" << e.GetExpr() << \"\\n\";\n std::cerr << \"Token: \" << e.GetToken() << \"\\n\";\n std::cerr << \"Position: \" << e.GetPos() << \"\\n\";\n std::cerr << \"Errc: \" << e.GetCode() << std::endl;\t \n AssertThrow(false, ExcParseError(e.GetCode(), e.GetMsg().c_str()));\n return 0.0;\n }\n}\n\n\n\ntemplate <int dim>\nvoid FunctionParser<dim>::vector_value (const Point<dim> &p,\n Vector<double> &values) const\n{\n Assert (initialized==true, ExcNotInitialized());\n Assert (values.size() == this->n_components,\n ExcDimensionMismatch (values.size(), this->n_components));\n\n\n \/\/ initialize if not done so on this thread yet:\n init_muparser();\n\n for (unsigned int i=0; i<dim; ++i)\n vars.get()[i] = p(i);\n if (dim != n_vars)\n vars.get()[dim] = this->get_time();\n \n for (unsigned int component = 0; component < this->n_components;\n ++component)\n values(component) = fp.get()[component].Eval();\n}\n\n#else\n\n\ntemplate <int dim>\nvoid\nFunctionParser<dim>::initialize(const std::string &,\n const std::vector<std::string> &,\n const std::map<std::string, double> &,\n const bool,\n const bool)\n{\n Assert(false, ExcNeedsFunctionparser());\n}\n\n\ntemplate <int dim>\nvoid\nFunctionParser<dim>::initialize(const std::string &,\n const std::vector<std::string> &,\n const std::map<std::string, double> &,\n const std::map<std::string, double> &,\n const bool,\n const bool)\n{\n Assert(false, ExcNeedsFunctionparser());\n}\n\n\ntemplate <int dim>\nvoid\nFunctionParser<dim>::initialize(const std::string &,\n const std::string &,\n const std::map<std::string, double> &,\n const bool,\n const bool)\n{\n Assert(false, ExcNeedsFunctionparser());\n}\n\n\ntemplate <int dim>\nvoid\nFunctionParser<dim>::initialize(const std::string &,\n const std::string &,\n const std::map<std::string, double> &,\n const std::map<std::string, double> &,\n const bool,\n const bool)\n{\n Assert(false, ExcNeedsFunctionparser());\n}\n\ntemplate <int dim>\nvoid\nFunctionParser<dim>::initialize(const std::string &,\n const std::vector<std::string> &,\n const std::map<std::string, double> &,\n const bool)\n{\n Assert(false, ExcNeedsFunctionparser());\n}\n\ntemplate <int dim>\nvoid\nFunctionParser<dim>::initialize(const std::string &,\n const std::string &,\n const std::map<std::string, double> &,\n const bool)\n{\n Assert(false, ExcNeedsFunctionparser());\n}\n\n\n\ntemplate <int dim>\ndouble FunctionParser<dim>::value (\n const Point<dim> &, unsigned int) const\n{\n Assert(false, ExcNeedsFunctionparser());\n return 0.;\n}\n\n\ntemplate <int dim>\nvoid FunctionParser<dim>::vector_value (\n const Point<dim> &, Vector<double> &) const\n{\n Assert(false, ExcNeedsFunctionparser());\n}\n\n\n#endif\n\n\/\/ Explicit Instantiations.\n\ntemplate class FunctionParser<1>;\ntemplate class FunctionParser<2>;\ntemplate class FunctionParser<3>;\n\nDEAL_II_NAMESPACE_CLOSE\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright 2009-2019 The VOTCA Development Team\n * (http:\/\/www.votca.org)\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\")\n *\n * You may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *\/\n#include \"votca\/xtp\/diis.h\"\n#include <iostream>\n\nnamespace votca {\nnamespace xtp {\n\nvoid DIIS::Update(int maxerrorindex, const Eigen::MatrixXd& errormatrix) {\n\n if (int(_errormatrixhist.size()) == _histlength) {\n _errormatrixhist.erase(_errormatrixhist.begin() + maxerrorindex);\n _Diis_Bs.erase(_Diis_Bs.begin() + maxerrorindex);\n for (std::vector<double>& subvec : _Diis_Bs) {\n subvec.erase(subvec.begin() + maxerrorindex);\n }\n }\n\n _errormatrixhist.push_back(errormatrix);\n\n std::vector<double> Bijs;\n for (int i = 0; i < int(_errormatrixhist.size()) - 1; i++) {\n double value =\n errormatrix.cwiseProduct((_errormatrixhist[i]).transpose()).sum();\n Bijs.push_back(value);\n _Diis_Bs[i].push_back(value);\n }\n Bijs.push_back(errormatrix.cwiseProduct(errormatrix.transpose()).sum());\n _Diis_Bs.push_back(Bijs);\n return;\n}\n\nEigen::VectorXd DIIS::CalcCoeff() {\n success = true;\n const bool _useold = false;\n const int size = _errormatrixhist.size();\n\n \/\/ C2-DIIS\n Eigen::MatrixXd B = Eigen::MatrixXd::Zero(size, size);\n\n for (int i = 0; i < B.rows(); i++) {\n for (int j = 0; j <= i; j++) {\n B(i, j) = _Diis_Bs[i][j];\n if (i != j) {\n B(j, i) = B(i, j);\n }\n }\n }\n Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> es(B);\n Eigen::MatrixXd eigenvectors = Eigen::MatrixXd::Zero(size, size);\n\n for (int i = 0; i < es.eigenvectors().cols(); i++) {\n double norm = es.eigenvectors().col(i).sum();\n eigenvectors.col(i) = es.eigenvectors().col(i) \/ norm;\n }\n\n \/\/ Choose solution by picking out solution with smallest absolute error\n Eigen::VectorXd errors =\n (eigenvectors.transpose() * B * eigenvectors).diagonal().cwiseAbs();\n\n double MaxWeight = 10.0;\n int mincoeff = 0;\n success = false;\n for (int i = 0; i < errors.size(); i++) {\n errors.minCoeff(&mincoeff);\n if (std::abs(eigenvectors.col(mincoeff).maxCoeff()) > MaxWeight) {\n errors[mincoeff] = std::numeric_limits<double>::max();\n } else {\n success = true;\n break;\n }\n }\n\n Eigen::VectorXd coeffs = eigenvectors.col(mincoeff);\n\n if (std::abs(coeffs[coeffs.size() - 1]) < 0.001) {\n success = false;\n }\n\n return coeffs;\n}\n\n} \/\/ namespace xtp\n} \/\/ namespace votca\n<commit_msg>diis.cc: fix a warning<commit_after>\/*\n * Copyright 2009-2019 The VOTCA Development Team\n * (http:\/\/www.votca.org)\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\")\n *\n * You may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *\/\n#include \"votca\/xtp\/diis.h\"\n#include <iostream>\n\nnamespace votca {\nnamespace xtp {\n\nvoid DIIS::Update(int maxerrorindex, const Eigen::MatrixXd& errormatrix) {\n\n if (int(_errormatrixhist.size()) == _histlength) {\n _errormatrixhist.erase(_errormatrixhist.begin() + maxerrorindex);\n _Diis_Bs.erase(_Diis_Bs.begin() + maxerrorindex);\n for (std::vector<double>& subvec : _Diis_Bs) {\n subvec.erase(subvec.begin() + maxerrorindex);\n }\n }\n\n _errormatrixhist.push_back(errormatrix);\n\n std::vector<double> Bijs;\n for (int i = 0; i < int(_errormatrixhist.size()) - 1; i++) {\n double value =\n errormatrix.cwiseProduct((_errormatrixhist[i]).transpose()).sum();\n Bijs.push_back(value);\n _Diis_Bs[i].push_back(value);\n }\n Bijs.push_back(errormatrix.cwiseProduct(errormatrix.transpose()).sum());\n _Diis_Bs.push_back(Bijs);\n return;\n}\n\nEigen::VectorXd DIIS::CalcCoeff() {\n success = true;\n const int size = _errormatrixhist.size();\n\n \/\/ C2-DIIS\n Eigen::MatrixXd B = Eigen::MatrixXd::Zero(size, size);\n\n for (int i = 0; i < B.rows(); i++) {\n for (int j = 0; j <= i; j++) {\n B(i, j) = _Diis_Bs[i][j];\n if (i != j) {\n B(j, i) = B(i, j);\n }\n }\n }\n Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> es(B);\n Eigen::MatrixXd eigenvectors = Eigen::MatrixXd::Zero(size, size);\n\n for (int i = 0; i < es.eigenvectors().cols(); i++) {\n double norm = es.eigenvectors().col(i).sum();\n eigenvectors.col(i) = es.eigenvectors().col(i) \/ norm;\n }\n\n \/\/ Choose solution by picking out solution with smallest absolute error\n Eigen::VectorXd errors =\n (eigenvectors.transpose() * B * eigenvectors).diagonal().cwiseAbs();\n\n double MaxWeight = 10.0;\n int mincoeff = 0;\n success = false;\n for (int i = 0; i < errors.size(); i++) {\n errors.minCoeff(&mincoeff);\n if (std::abs(eigenvectors.col(mincoeff).maxCoeff()) > MaxWeight) {\n errors[mincoeff] = std::numeric_limits<double>::max();\n } else {\n success = true;\n break;\n }\n }\n\n Eigen::VectorXd coeffs = eigenvectors.col(mincoeff);\n\n if (std::abs(coeffs[coeffs.size() - 1]) < 0.001) {\n success = false;\n }\n\n return coeffs;\n}\n\n} \/\/ namespace xtp\n} \/\/ namespace votca\n<|endoftext|>"} {"text":"<commit_before>#include \"linear_interpolate_d.hpp\"\n\n#include <cmath>\n\n#include <algorithm>\n#include <map>\n#include <numeric>\n#include <string>\n#include <vector>\n\n#include \"sexp_matrix_iterator.hpp\"\n\n\nstd::vector<double> find_barycentric_coords(std::size_t size,\n Point const & point,\n std::vector<Point> const & simplex)\n{\n std::vector<double> a(size * size);\n for (size_t i = 0; i < size; ++i)\n {\n for (size_t j = 0; j < size; ++j)\n {\n a[i*size+j] = *(simplex[i].cartesian_begin()+j) - *(simplex[size].cartesian_begin()+j);\n }\n }\n\n std::vector<double> b(size + 1);\n for (size_t i = 0; i < size; ++i)\n {\n b[i] = *(point.cartesian_begin()+i) - *(simplex[size].cartesian_begin()+i);\n }\n\n \/\/ additional variables needed for LAPACK\n std::vector<int> ipiv(size);\n int info;\n int size_int = size;\n int b_size = 1;\n\n \/\/ solve a*x = b\n \/\/ result will be in b\n F77_NAME(dgesv)(&size_int, &b_size, &a[0], &size_int, &ipiv[0],\n &b[0], &size_int, &info);\n\n \/\/ calculate last coordinate\n b[size] = 1 - std::accumulate(b.begin(), b.end() - 1, 0.);\n\n return b;\n}\n\nvoid make_toroidal(std::size_t size,\n std::vector<Point> & points,\n std::vector<double> & values)\n{\n \/*shifts = [\n np.amax(points[:, i]) - np.amin(points[:, i])\n for i in xrange(points.shape[1])\n ]\n directions = np.array([0, 1, -1])\n all_shifts = itertools.product(*[\n directions * shift for shift in shifts\n ])\n\n toroidal = np.empty((0,) + points.shape[1:])\n for total_shift in all_shifts:\n toroidal = np.append(toroidal, points + np.array(total_shift), axis=0)*\/\n\n size_t old_values_size = values.size();\n size_t values_size = std::pow(3, size) * old_values_size;\n values.resize(values_size);\n for (size_t i = 1; i < values_size; ++i)\n {\n for (size_t j = 0; j < old_values_size; ++j)\n {\n values[i * old_values_size + j] = values[j];\n }\n }\n}\n\n\/\/vector<double>\nSEXP linear_interpolate_d(SEXP dimentions,\n SEXP points,\n SEXP values,\n SEXP xi,\n SEXP fill_value)\n{\n auto d = INTEGER(dimentions)[0];\n\n Delaunay triangulation(d);\n std::map<Vertex_handle, double> vertices_to_values;\n int points_count = length(values);\n for (auto i = 0; i < points_count; ++i)\n {\n Point point(\n d,\n sexp_matrix_iterator(points, points_count, i),\n sexp_matrix_iterator(points, points_count, i + d * points_count));\n auto vertex_handle = triangulation.insert(point);\n vertices_to_values[vertex_handle] = REAL(values)[i];\n }\n\n auto double_fill_value = REAL(fill_value)[0];\n\n auto recalc_point =\n [&]\n (Point const & point)\n {\n auto simplex = triangulation.locate(point);\n if (simplex == Delaunay::Simplex_handle())\n {\n return double_fill_value;\n }\n std::vector<Point> vertices(d + 1);\n std::vector<double> vertex_values(d + 1);\n for (auto i = 0; i <= triangulation.current_dimension(); ++i)\n {\n auto vertex = triangulation.vertex_of_simplex(simplex, i);\n double vertex_val = vertices_to_values[vertex];\n if (ISNAN(vertex_val))\n {\n return double_fill_value;\n }\n vertices[i] = triangulation.associated_point(vertex);\n vertex_values[i] = vertex_val;\n }\n auto barycentric = find_barycentric_coords(triangulation.current_dimension(), point, vertices);\n return std::inner_product(vertex_values.begin(), vertex_values.end(), barycentric.begin(), 0.);\n };\n\n auto result_length = length(xi) \/ d;\n SEXP results = PROTECT(allocVector(REALSXP, result_length));\n for(int i = 0; i < result_length; ++i)\n {\n Point point(\n d,\n sexp_matrix_iterator(xi, result_length, i),\n sexp_matrix_iterator(xi, result_length, i + result_length * d));\n REAL(results)[i] = recalc_point(point);\n }\n UNPROTECT(1);\n return results;\n}\n\n<commit_msg>Add R files<commit_after>#include \"linear_interpolate_d.hpp\"\n\n#include <cmath>\n\n#include <algorithm>\n#include <map>\n#include <numeric>\n#include <limits>\n#include <string>\n#include <tuple>\n#include <vector>\n\n#include \"sexp_matrix_iterator.hpp\"\n\n\nstd::vector<double> find_barycentric_coords(std::size_t size,\n Point const & point,\n std::vector<Point> const & simplex)\n{\n std::vector<double> a(size * size);\n for (size_t i = 0; i < size; ++i)\n {\n for (size_t j = 0; j < size; ++j)\n {\n a[i*size+j] = *(simplex[i].cartesian_begin()+j) - *(simplex[size].cartesian_begin()+j);\n }\n }\n\n std::vector<double> b(size + 1);\n for (size_t i = 0; i < size; ++i)\n {\n b[i] = *(point.cartesian_begin()+i) - *(simplex[size].cartesian_begin()+i);\n }\n\n \/\/ additional variables needed for LAPACK\n std::vector<int> ipiv(size);\n int info;\n int size_int = size;\n int b_size = 1;\n\n \/\/ solve a*x = b\n \/\/ result will be in b\n F77_NAME(dgesv)(&size_int, &b_size, &a[0], &size_int, &ipiv[0],\n &b[0], &size_int, &info);\n\n \/\/ calculate last coordinate\n b[size] = 1 - std::accumulate(b.begin(), b.end() - 1, 0.);\n\n return b;\n}\n\nvoid make_toroidal(std::size_t size,\n std::vector<Point> & points,\n std::vector<double> & values)\n{\n size_t old_length = points.size();\n size_t length = std::pow(3, size) * old_length;\n\n std::vector<std::tuple<double, double, double>> shifts(size);\n for (size_t i = 0; i < size; ++i)\n {\n double amin = std::numeric_limits<double>::max();\n double amax = std::numeric_limits<double>::min();\n for (auto const & p : points)\n {\n amin = std::min(amin, *(p.cartesian_begin() + i));\n amax = std::max(amax, *(p.cartesian_begin() + i));\n }\n shifts[i] = amax - amin;\n double shift = amax - amin;\n Rprintf(\"%lf\\n\", shift);\n }\n\n points.reserve(length);\n\n return;\n\n \/*shifts = [\n np.amax(points[:, i]) - np.amin(points[:, i])\n for i in xrange(points.shape[1])\n ]\n directions = np.array([0, 1, -1])\n all_shifts = itertools.product(*[\n directions * shift for shift in shifts\n ])*\/\n\n \/\/toroidal = np.empty((0,) + points.shape[1:])\n \/\/for total_shift in all_shifts:\n \/\/ toroidal = np.append(toroidal, points + np.array(total_shift), axis=0)\n\n values.resize(length);\n for (size_t i = 1; i < values_size; ++i)\n {\n for (size_t j = 0; j < old_values_size; ++j)\n {\n values[i * old_values_size + j] = values[j];\n }\n }\n}\n\n\/\/vector<double>\nSEXP linear_interpolate_d(SEXP dimentions,\n SEXP points,\n SEXP values,\n SEXP xi,\n SEXP fill_value)\n{\n auto d = INTEGER(dimentions)[0];\n\n Delaunay triangulation(d);\n std::map<Vertex_handle, double> vertices_to_values;\n int points_count = length(values);\n for (auto i = 0; i < points_count; ++i)\n {\n Point point(\n d,\n sexp_matrix_iterator(points, points_count, i),\n sexp_matrix_iterator(points, points_count, i + d * points_count));\n auto vertex_handle = triangulation.insert(point);\n vertices_to_values[vertex_handle] = REAL(values)[i];\n }\n\n auto double_fill_value = REAL(fill_value)[0];\n\n auto recalc_point =\n [&]\n (Point const & point)\n {\n auto simplex = triangulation.locate(point);\n if (simplex == Delaunay::Simplex_handle())\n {\n return double_fill_value;\n }\n std::vector<Point> vertices(d + 1);\n std::vector<double> vertex_values(d + 1);\n for (auto i = 0; i <= triangulation.current_dimension(); ++i)\n {\n auto vertex = triangulation.vertex_of_simplex(simplex, i);\n double vertex_val = vertices_to_values[vertex];\n if (ISNAN(vertex_val))\n {\n return double_fill_value;\n }\n vertices[i] = triangulation.associated_point(vertex);\n vertex_values[i] = vertex_val;\n }\n auto barycentric = find_barycentric_coords(triangulation.current_dimension(), point, vertices);\n return std::inner_product(vertex_values.begin(), vertex_values.end(), barycentric.begin(), 0.);\n };\n\n auto result_length = length(xi) \/ d;\n SEXP results = PROTECT(allocVector(REALSXP, result_length));\n for(int i = 0; i < result_length; ++i)\n {\n Point point(\n d,\n sexp_matrix_iterator(xi, result_length, i),\n sexp_matrix_iterator(xi, result_length, i + result_length * d));\n REAL(results)[i] = recalc_point(point);\n }\n UNPROTECT(1);\n return results;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/\n\/\/ The MIT License (MIT)\n\/\/\n\/\/ Copyright (c) 2014 Michael J. Wouters\n\/\/ \n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/ \n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/ \n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n\/\/ THE SOFTWARE.\n\n#include <sys\/types.h> \n#include <sys\/socket.h>\n#include <arpa\/inet.h>\n#include <string.h>\n#include <strings.h>\n#include <sys\/select.h>\n#include <pthread.h>\n#include <signal.h>\n#include <errno.h>\n#include <fcntl.h>\n#include <unistd.h>\n#include <cstdio>\n\n#include <iostream>\n#include <sstream>\n\n#include \"Client.h\"\n#include \"Debug.h\"\n#include \"OKCounterD.h\"\n#include \"Server.h\"\n\n#define BUFSIZE 8096\n#define MAXCLIENTS 16\n\nextern ostream* debugStream;\n\n\/\/\n\/\/ Public\n\/\/\n\nServer::Server(OKCounterD *a,int p)\n{\n\tthreadID = \"server\";\n\tapp = a;\n\tport=p; \n\tif (!init())\n\t\texit(EXIT_FAILURE);\n}\n\nServer::~Server()\n{\n\tclose(listenfd);\n\tfor (unsigned int i=0;i<clients.size();i++)\n\t\tclients.at(i)->stop();\n}\n\n\nvoid Server::sendData(vector<int> &data){\n\tfor (unsigned int i=0;i<clients.size();i++){\n\t\tclients.at(i)->sendData(data);\n\t}\n}\n\n\/\/\n\/\/ Protected\n\/\/\n\nvoid Server::doWork()\n{\n\t\/\/ SIGPIPE is delivered if the client closes the socket before we've finished replying\n\t\/\/ This kills the process\n\t\n\tDBGMSG(debugStream,\"working\");\n\t\n\tsigset_t blocked;\n\tsigemptyset(&blocked);\n\tsigaddset(&blocked,SIGPIPE);\n\tpthread_sigmask(SIG_BLOCK,&blocked,NULL);\n\t\n\tint socketfd;\n\tsocklen_t len;\n\tstruct sockaddr_in cli_addr; \n\tbzero(&cli_addr,sizeof(cli_addr));\n\n\tfd_set rfds;\n struct timeval tv;\n int retval;\n\t\n\twhile (!stopRequested) \n\t{\n\t\n\t\ttv.tv_sec=5;\n\t\ttv.tv_usec=0;\n\t\t\n\t\tFD_ZERO(&rfds);\n\t\tFD_SET(listenfd, &rfds);\n\n\t\tretval = select(listenfd+1, &rfds, NULL,NULL, &tv); \/\/ note number of file descriptors!\n\t\n\t\tif (retval) {\n\t\t\tlen= sizeof(cli_addr);\n\t\t\tif((socketfd = accept(listenfd, (struct sockaddr *)&cli_addr, &len)) < 0)\n\t\t\t\tapp->log(\"ERROR in accept()\");\n\t\t\telse{\n\t\t\t\tprocessRequest(socketfd);\n\t\t\t}\n\t\t}\n\t\t\n\t\tunsigned int j=0;\n\t\twhile (j<clients.size()){\n\t\t\tClient *c = clients.at(j);\n\t\t\tif (!c->isRunning()){\n\t\t\t\tDBGMSG(debugStream,\"stopping client\");\n\t\t\t\tc->stop();\n\t\t\t\tclients.erase(clients.begin()+j);\n\t\t\t\tdelete c;\n\t\t\t}\n\t\t\telse\n\t\t\t\tj++;\n\t\t}\n\t\t\n\t}\n\t\n\trunning=false;\n}\n\n\n\/\/\n\/\/ Private\n\/\/\n\nbool Server::init()\n{\n\tstruct sockaddr_in serv_addr; \n\tbzero(&serv_addr,sizeof(serv_addr));\n\t\n\t\/\/ Set up the socket\n\t#ifdef LINUX_PRE_2_6_27\n\tlistenfd = socket(AF_INET, SOCK_STREAM ,0);\n\tif (listenfd >=0){\n\t\tfcntl(listenfd, F_SETFL, O_NONBLOCK);\n\t}\n\telse{\n\t#else\n\tif((listenfd = socket(AF_INET, SOCK_STREAM | SOCK_NONBLOCK,0)) <0){\n\t#endif\n\t\tapp->log(\"ERROR in socket()\");\n\t\treturn false;\n\t}\n\t\n\tif(port < 0 || port >60000){\n\t\tapp->log(\"ERROR invalid port number (try 1->60000)\");\n\t\treturn false;\n\t}\n\t\n\tserv_addr.sin_family = AF_INET;\n\tserv_addr.sin_addr.s_addr = htonl(INADDR_ANY);\n\tserv_addr.sin_port = htons(port);\n\t\n\tif(bind(listenfd, (struct sockaddr *)&serv_addr,sizeof(serv_addr)) <0){\n\t\tapp->log(\"ERROR in bind()\");\n\t\treturn false;\n\t}\n\t\n\tif( listen(listenfd,64) <0){\n\t\tapp->log(\"ERROR in listen()\");\n\t\treturn false;\n\t}\n\t\n\tostringstream ss;\n\tss << \"listening on port \" << port;\n\tapp->log(ss.str());\n\t\n\treturn true;\n\t\n}\n\nbool Server::processRequest(int socketfd)\n{\n\t\/\/ Two requests:\n\t\/\/ LISTEN to counter readings\n\t\/\/ CONFIGURE the counter\n\t\/\/ QUERY the counter configuration\n\t\n\tlong ret;\n\tstatic char buffer[BUFSIZE+1]; \n\n\tret =read(socketfd,buffer,BUFSIZE); \t\/\/ read request in one go \n\tif(ret == 0 || ret == -1) {\t\/\/ read failure\n\t\t\/\/app->log(\"failed to read client request\");\n\t\treturn false;\n\t}\n\tif(ret > 0 && ret < BUFSIZE)\t\/\/ return code is valid chars \n\t\tbuffer[ret]=0;\t\t\/\/ terminate the buffer \n\telse buffer[0]=0;\n\t\n\tif (NULL != strstr(buffer,\"CONFIGURE\") ){\n\t\tDBGMSG(debugStream,\"received \" << buffer);\n\t\tif (NULL != strstr(buffer,\"PPSSOURCE\")){\n\t\t\tint src;\n\t\t\tsscanf(buffer,\"%*s%*s%i\",&src);\n\t\t\tapp->setOutputPPSSource(src);\n\t\t}\n\t\telse if (NULL != strstr(buffer,\"GPIO\")){\n\t\t\tint en;\n\t\t\tsscanf(buffer,\"%*s%*s%i\",&en);\n\t\t\tapp->setGPIOEnable((en==1));\n\t\t}\n\t\telse{\n\t\t\tDBGMSG(debugStream,\"unknown command\");\n\t\t}\n\t\t\n\t\t\/\/ done so close the connection\n\t\tif (-1==shutdown(socketfd,SHUT_RDWR)){\n\t\t\tapp->log(\"ERROR in shutdown()\");\n\t\t}\n\t\tif (-1==close(socketfd)){\n\t\t\tapp->log(\"ERROR in close()\");\n\t\t}\n\t}\n\telse if (NULL != strstr(buffer,\"QUERY CONFIGURATION\") ){\n\t\tDBGMSG(debugStream,\"received \" << buffer);\n\t\tstring cfg = app->getConfiguration();\n\t\twriteBuffer(cfg,socketfd);\n\t\tsleep(1); \/\/ wait a bit\n\t\t\/\/ done so close the connection\n\t\tif (-1==shutdown(socketfd,SHUT_RDWR)){\n\t\t\tapp->log(\"ERROR in shutdown()\");\n\t\t}\n\t\tif (-1==close(socketfd)){\n\t\t\tapp->log(\"ERROR in close()\");\n\t\t}\n\t}\n\telse if(NULL != strstr(buffer,\"LISTEN\") ){ \n\t\tDBGMSG(debugStream,\"received \" << buffer);\n\t\t\/\/ Sanity check on number of clients\n\t\tif (clients.size() == MAXCLIENTS){\n\t\t\tapp->log(\"Too many connections\");\n\t\t\tif (-1==shutdown(socketfd,SHUT_RDWR)){\n\t\t\t\tapp->log(\"ERROR in shutdown()\");\n\t\t\t}\n\t\t\tif (-1==close(socketfd)){\n\t\t\t\tapp->log(\"ERROR in close()\");\n\t\t\t}\n\t\t}\n\t\telse{\t\n\t\t\tClient *client = new Client(this,socketfd);\n\t\t\tclients.push_back(client);\n\t\t\tclient->go();\n\t\t}\n\t}\n\treturn true;\n}\n\nvoid Server::writeBuffer(string msg,int socketfd){\n\t\n\tint nw,nEINTR=0;\n\tint nleft = msg.size();\n\tconst char* pbuf=msg.c_str();\n\t\n\twhile (nleft > 0){\n\t\tif (( nw = write(socketfd,pbuf,nleft)) <= 0){\n\t\t\tif (errno==EINTR){ \/\/ interrupted by signal\n\t\t\t\tnw=0;\n\t\t\t\tnEINTR++;\n\t\t\t\tif (10==nEINTR){\n\t\t\t\t\tDBGMSG(debugStream, \"too many interrrupts - write() aborted\");\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse{\n\t\t\t\tDBGMSG(debugStream, strerror(errno));\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t\tDBGMSG(debugStream, \"wrote \" << nw);\n\t\tnleft -=nw;\n\t\tpbuf += nw;\n\t}\t\n}\n\n\t\n<commit_msg>socket reuse<commit_after>\/\/\n\/\/\n\/\/ The MIT License (MIT)\n\/\/\n\/\/ Copyright (c) 2014 Michael J. Wouters\n\/\/ \n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/ \n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/ \n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n\/\/ THE SOFTWARE.\n\n#include <sys\/types.h> \n#include <sys\/socket.h>\n#include <arpa\/inet.h>\n#include <string.h>\n#include <strings.h>\n#include <sys\/select.h>\n#include <pthread.h>\n#include <signal.h>\n#include <errno.h>\n#include <fcntl.h>\n#include <unistd.h>\n#include <cstdio>\n\n#include <iostream>\n#include <sstream>\n\n#include \"Client.h\"\n#include \"Debug.h\"\n#include \"OKCounterD.h\"\n#include \"Server.h\"\n\n#define BUFSIZE 8096\n#define MAXCLIENTS 16\n\nextern ostream* debugStream;\n\n\/\/\n\/\/ Public\n\/\/\n\nServer::Server(OKCounterD *a,int p)\n{\n\tthreadID = \"server\";\n\tapp = a;\n\tport=p; \n\tif (!init())\n\t\texit(EXIT_FAILURE);\n}\n\nServer::~Server()\n{\n\tclose(listenfd);\n\tfor (unsigned int i=0;i<clients.size();i++)\n\t\tclients.at(i)->stop();\n}\n\n\nvoid Server::sendData(vector<int> &data){\n\tfor (unsigned int i=0;i<clients.size();i++){\n\t\tclients.at(i)->sendData(data);\n\t}\n}\n\n\/\/\n\/\/ Protected\n\/\/\n\nvoid Server::doWork()\n{\n\t\/\/ SIGPIPE is delivered if the client closes the socket before we've finished replying\n\t\/\/ This kills the process\n\t\n\tDBGMSG(debugStream,\"working\");\n\t\n\tsigset_t blocked;\n\tsigemptyset(&blocked);\n\tsigaddset(&blocked,SIGPIPE);\n\tpthread_sigmask(SIG_BLOCK,&blocked,NULL);\n\t\n\tint socketfd;\n\tsocklen_t len;\n\tstruct sockaddr_in cli_addr; \n\tbzero(&cli_addr,sizeof(cli_addr));\n\n\tfd_set rfds;\n struct timeval tv;\n int retval;\n\t\n\twhile (!stopRequested) \n\t{\n\t\n\t\ttv.tv_sec=5;\n\t\ttv.tv_usec=0;\n\t\t\n\t\tFD_ZERO(&rfds);\n\t\tFD_SET(listenfd, &rfds);\n\n\t\tretval = select(listenfd+1, &rfds, NULL,NULL, &tv); \/\/ note number of file descriptors!\n\t\n\t\tif (retval) {\n\t\t\tlen= sizeof(cli_addr);\n\t\t\tif((socketfd = accept(listenfd, (struct sockaddr *)&cli_addr, &len)) < 0)\n\t\t\t\tapp->log(\"ERROR in accept()\");\n\t\t\telse{\n\t\t\t\tprocessRequest(socketfd);\n\t\t\t}\n\t\t}\n\t\t\n\t\tunsigned int j=0;\n\t\twhile (j<clients.size()){\n\t\t\tClient *c = clients.at(j);\n\t\t\tif (!c->isRunning()){\n\t\t\t\tDBGMSG(debugStream,\"stopping client\");\n\t\t\t\tc->stop();\n\t\t\t\tclients.erase(clients.begin()+j);\n\t\t\t\tdelete c;\n\t\t\t}\n\t\t\telse\n\t\t\t\tj++;\n\t\t}\n\t\t\n\t}\n\t\n\trunning=false;\n}\n\n\n\/\/\n\/\/ Private\n\/\/\n\nbool Server::init()\n{\n\tstruct sockaddr_in serv_addr; \n\tbzero(&serv_addr,sizeof(serv_addr));\n\t\n\t\/\/ Set up the socket\n\t#ifdef LINUX_PRE_2_6_27\n\tlistenfd = socket(AF_INET, SOCK_STREAM ,0);\n\tif (listenfd >=0){\n\t\tfcntl(listenfd, F_SETFL, O_NONBLOCK);\n\t}\n\telse{\n\t#else\n\tif((listenfd = socket(AF_INET, SOCK_STREAM | SOCK_NONBLOCK,0)) <0){\n\t#endif\n\t\tapp->log(\"ERROR in socket()\");\n\t\treturn false;\n\t}\n\t\n\tint on = 1;\n\tif (setsockopt(listenfd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) <0){\n\t\tapp->log(\"ERROR setsockopt()\");\n\t\t\/\/ don't return\n\t}\n\n\n\tif(port < 0 || port >60000){\n\t\tapp->log(\"ERROR invalid port number (try 1->60000)\");\n\t\treturn false;\n\t}\n\t\n\tserv_addr.sin_family = AF_INET;\n\tserv_addr.sin_addr.s_addr = htonl(INADDR_ANY);\n\tserv_addr.sin_port = htons(port);\n\t\n\tif(bind(listenfd, (struct sockaddr *)&serv_addr,sizeof(serv_addr)) <0){\n\t\tapp->log(\"ERROR in bind()\");\n\t\treturn false;\n\t}\n\t\n\tif( listen(listenfd,64) <0){\n\t\tapp->log(\"ERROR in listen()\");\n\t\treturn false;\n\t}\n\t\n\tostringstream ss;\n\tss << \"listening on port \" << port;\n\tapp->log(ss.str());\n\t\n\treturn true;\n\t\n}\n\nbool Server::processRequest(int socketfd)\n{\n\t\/\/ Two requests:\n\t\/\/ LISTEN to counter readings\n\t\/\/ CONFIGURE the counter\n\t\/\/ QUERY the counter configuration\n\t\n\tlong ret;\n\tstatic char buffer[BUFSIZE+1]; \n\n\tret =read(socketfd,buffer,BUFSIZE); \t\/\/ read request in one go \n\tif(ret == 0 || ret == -1) {\t\/\/ read failure\n\t\t\/\/app->log(\"failed to read client request\");\n\t\treturn false;\n\t}\n\tif(ret > 0 && ret < BUFSIZE)\t\/\/ return code is valid chars \n\t\tbuffer[ret]=0;\t\t\/\/ terminate the buffer \n\telse buffer[0]=0;\n\t\n\tif (NULL != strstr(buffer,\"CONFIGURE\") ){\n\t\tDBGMSG(debugStream,\"received \" << buffer);\n\t\tif (NULL != strstr(buffer,\"PPSSOURCE\")){\n\t\t\tint src;\n\t\t\tsscanf(buffer,\"%*s%*s%i\",&src);\n\t\t\tapp->setOutputPPSSource(src);\n\t\t}\n\t\telse if (NULL != strstr(buffer,\"GPIO\")){\n\t\t\tint en;\n\t\t\tsscanf(buffer,\"%*s%*s%i\",&en);\n\t\t\tapp->setGPIOEnable((en==1));\n\t\t}\n\t\telse{\n\t\t\tDBGMSG(debugStream,\"unknown command\");\n\t\t}\n\t\t\n\t\t\/\/ done so close the connection\n\t\tif (-1==shutdown(socketfd,SHUT_RDWR)){\n\t\t\tapp->log(\"ERROR in shutdown()\");\n\t\t}\n\t\tif (-1==close(socketfd)){\n\t\t\tapp->log(\"ERROR in close()\");\n\t\t}\n\t}\n\telse if (NULL != strstr(buffer,\"QUERY CONFIGURATION\") ){\n\t\tDBGMSG(debugStream,\"received \" << buffer);\n\t\tstring cfg = app->getConfiguration();\n\t\twriteBuffer(cfg,socketfd);\n\t\tsleep(1); \/\/ wait a bit\n\t\t\/\/ done so close the connection\n\t\tif (-1==shutdown(socketfd,SHUT_RDWR)){\n\t\t\tapp->log(\"ERROR in shutdown()\");\n\t\t}\n\t\tif (-1==close(socketfd)){\n\t\t\tapp->log(\"ERROR in close()\");\n\t\t}\n\t}\n\telse if(NULL != strstr(buffer,\"LISTEN\") ){ \n\t\tDBGMSG(debugStream,\"received \" << buffer);\n\t\t\/\/ Sanity check on number of clients\n\t\tif (clients.size() == MAXCLIENTS){\n\t\t\tapp->log(\"Too many connections\");\n\t\t\tif (-1==shutdown(socketfd,SHUT_RDWR)){\n\t\t\t\tapp->log(\"ERROR in shutdown()\");\n\t\t\t}\n\t\t\tif (-1==close(socketfd)){\n\t\t\t\tapp->log(\"ERROR in close()\");\n\t\t\t}\n\t\t}\n\t\telse{\t\n\t\t\tClient *client = new Client(this,socketfd);\n\t\t\tclients.push_back(client);\n\t\t\tclient->go();\n\t\t}\n\t}\n\treturn true;\n}\n\nvoid Server::writeBuffer(string msg,int socketfd){\n\t\n\tint nw,nEINTR=0;\n\tint nleft = msg.size();\n\tconst char* pbuf=msg.c_str();\n\t\n\twhile (nleft > 0){\n\t\tif (( nw = write(socketfd,pbuf,nleft)) <= 0){\n\t\t\tif (errno==EINTR){ \/\/ interrupted by signal\n\t\t\t\tnw=0;\n\t\t\t\tnEINTR++;\n\t\t\t\tif (10==nEINTR){\n\t\t\t\t\tDBGMSG(debugStream, \"too many interrrupts - write() aborted\");\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse{\n\t\t\t\tDBGMSG(debugStream, strerror(errno));\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t\tDBGMSG(debugStream, \"wrote \" << nw);\n\t\tnleft -=nw;\n\t\tpbuf += nw;\n\t}\t\n}\n\n\t\n<|endoftext|>"} {"text":"<commit_before>\/\/ -*- Mode: C++; tab-width: 2; -*-\n\/\/ vi: set ts=2:\n\/\/\n\/\/ $Id: modelSettingsDialog.C,v 1.14 2004\/01\/20 16:47:56 amoll Exp $\n\/\/\n\n#include <BALL\/VIEW\/DIALOGS\/modelSettingsDialog.h>\n#include <BALL\/DATATYPE\/string.h>\n#include <BALL\/FORMAT\/INIFile.h>\n\n#include <qslider.h>\n#include <qlabel.h>\n#include <qlistbox.h>\n#include <qwidgetstack.h>\n\nnamespace BALL\n{\n\tnamespace VIEW\n\t{\n\n\t\tModelSettingsDialog::ModelSettingsDialog( QWidget* parent, const char* name, WFlags fl )\n\t\t\t\t: ModelSettingsDialogData( parent, name, fl )\n\t\t{\n\t\t\tsetDefaults();\n\t\t}\n\n\t\tvoid ModelSettingsDialog::setDefaults(bool all)\n\t\t\tthrow()\n\t\t{\n\t\t\tif (all || list_box->currentItem() == 0)\n\t\t\t{\n\t\t\t\tstick_radius_slider->setValue(2);\n\t\t\t}\n\t\t\t\n\t\t\tif (all || list_box->currentItem() == 1)\n\t\t\t{\n\t\t\t\tball_stick_cylinder_radius_slider->setValue(2);\n\t\t\t\tball_stick_sphere_radius_slider->setValue(4);\n\t\t\t}\n\t\t\t\n\t\t\tif (all || list_box->currentItem() == 2)\n\t\t\t{\n\t\t\t\tvdw_radius_factor_slider->setValue(10);\n\t\t\t}\n\t\t\t\n\t\t\tif (all || list_box->currentItem() == 3)\n\t\t\t{\n\t\t\t\tsurface_probe_radius_slider->setValue(15);\n\t\t\t}\n\t\t\t\n\t\t\tif (all || list_box->currentItem() == 4)\n\t\t\t{\n\t\t\t\ttube_radius_slider->setValue(4);\n\t\t\t}\n\t\t\t\n\t\t\tif (all || list_box->currentItem() == 5)\n\t\t\t{\n\t\t\t\tcartoon_tube_radius_slider->setValue(4);\n\t\t\t\tcartoon_helix_radius_slider->setValue(20);\n\t\t\t\tcartoon_arrow_width_slider->setValue(4);\n\t\t\t\tcartoon_arrow_height_slider->setValue(8);\n\t\t\t}\n\t\t\t\n\t\t\tif (all || list_box->currentItem() == 6)\n\t\t\t{\n\t\t\t\thbonds_radius_slider->setValue(3);\n\t\t\t}\n\t\t}\n\n\t\tfloat ModelSettingsDialog::getFloatValue_(const QSlider* const& slider) const\n\t\t\tthrow()\n\t\t{\n\t\t\treturn (float(slider->value())) \/ 10.0;\n\t\t}\n\n\t\tvoid ModelSettingsDialog::setValue_(QSlider* le, float value)\n\t\t\tthrow()\n\t\t{\n\t\t\tle->setValue((Size)(value * 10.0));\n\t\t}\n\n\t\tvoid ModelSettingsDialog::setLabelText_(QLabel* label, const QSlider* const from)\n\t\t\tthrow()\n\t\t{\n\t\t\tString s((float)from->value() \/ 10.0);\n\t\t\ts.trimRight(\"0\");\n\t\t\tif (s.hasSuffix(\".\")) s+= \"0\";\n\t\t\tlabel->setText(s.c_str());\n\t\t}\n\n\t\tvoid ModelSettingsDialog::fetchPreference_(const INIFile& inifile, const String& entry, QSlider& slider)\n\t\t\tthrow()\n\t\t{\n\t\t\tif (!inifile.hasEntry(\"MODEL_OPTIONS\", entry)) return;\n\t\t\tsetValue_(&slider, inifile.getValue(\"MODEL_OPTIONS\", entry).toFloat());\n\t\t}\n\n\t\tvoid ModelSettingsDialog::writePreference_(INIFile& inifile, const String& entry, const QSlider& slider) const\n\t\t\tthrow()\n\t\t{\n\t\t\tinifile.insertValue(\"MODEL_OPTIONS\", entry, getFloatValue_(&slider));\n\t\t}\n\n\n\t\tvoid ModelSettingsDialog::writePreferences(INIFile& file)\n\t\t\tthrow()\n\t\t{\n\t\t\tfile.appendSection(\"MODEL_OPTIONS\");\n\t\t\twritePreference_(file, \"stick_radius\", *stick_radius_slider);\n\t\t\twritePreference_(file, \"ball_stick_cylinder_radius\", *ball_stick_cylinder_radius_slider);\n\t\t\twritePreference_(file, \"ball_stick_sphere_radius\", *ball_stick_sphere_radius_slider);\n\t\t\twritePreference_(file, \"vdw_radius_factor\", *vdw_radius_factor_slider);\n\t\t\twritePreference_(file, \"surface_probe_radius\", *surface_probe_radius_slider);\n\t\t\twritePreference_(file, \"tube_radius\", *tube_radius_slider);\n\t\t\twritePreference_(file, \"cartoon_tube_radius\", *cartoon_tube_radius_slider);\n\t\t\twritePreference_(file, \"cartoon_helix_radius\", *cartoon_helix_radius_slider);\n\t\t\twritePreference_(file, \"cartoon_arrow_height\", *cartoon_arrow_height_slider);\n\t\t\twritePreference_(file, \"cartoon_arrow_width\", *cartoon_arrow_width_slider);\n\t\t\twritePreference_(file, \"cartoon_arrow_width\", *cartoon_arrow_width_slider);\n\t\t\twritePreference_(file, \"hbonds_radius\", *hbonds_radius_slider);\n\t\t}\n\n\t\tvoid ModelSettingsDialog::fetchPreferences(const INIFile& file)\n\t\t\tthrow()\n\t\t{\n\t\t\tfetchPreference_(file, \"stick_radius\", *stick_radius_slider);\n\t\t\tfetchPreference_(file, \"ball_stick_cylinder_radius\", *ball_stick_cylinder_radius_slider);\n\t\t\tfetchPreference_(file, \"ball_stick_sphere_radius\", *ball_stick_sphere_radius_slider);\n\t\t\tfetchPreference_(file, \"vdw_radius_factor\", *vdw_radius_factor_slider);\n\t\t\tfetchPreference_(file, \"surface_probe_radius\", *surface_probe_radius_slider);\n\t\t\tfetchPreference_(file, \"tube_radius\", *tube_radius_slider);\n\t\t\tfetchPreference_(file, \"cartoon_tube_radius\", *cartoon_tube_radius_slider);\n\t\t\tfetchPreference_(file, \"cartoon_helix_radius\", *cartoon_helix_radius_slider);\n\t\t\tfetchPreference_(file, \"cartoon_arrow_height\", *cartoon_arrow_height_slider);\n\t\t\tfetchPreference_(file, \"cartoon_arrow_width\", *cartoon_arrow_width_slider);\n\t\t\tfetchPreference_(file, \"hbonds_radius\", *hbonds_radius_slider);\n\t\t}\n\n\t\tvoid ModelSettingsDialog::setDefaultValues()\n\t\t\tthrow()\n\t\t{\n\t\t\tsetDefaults(false);\n\t\t}\n\n\t\tvoid ModelSettingsDialog::showPage(int nr)\n\t\t{\n\t\t\tif (widget_stack->widget(nr) == 0)\n\t\t\t{\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (list_box->currentItem() != nr)\n\t\t\t{\n\t\t\t\tlist_box->setCurrentItem(nr);\n\t\t\t}\n\t\t\twidget_stack->raiseWidget(nr);\n\t\t}\n\n\n\t} \/\/ namespace VIEW\n} \/\/ namespace BALL\n<commit_msg>no message<commit_after>\/\/ -*- Mode: C++; tab-width: 2; -*-\n\/\/ vi: set ts=2:\n\/\/\n\/\/ $Id: modelSettingsDialog.C,v 1.15 2004\/02\/24 19:03:48 amoll Exp $\n\/\/\n\n#include <BALL\/VIEW\/DIALOGS\/modelSettingsDialog.h>\n#include <BALL\/DATATYPE\/string.h>\n#include <BALL\/FORMAT\/INIFile.h>\n\n#include <qslider.h>\n#include <qlabel.h>\n#include <qlistbox.h>\n#include <qwidgetstack.h>\n\nnamespace BALL\n{\n\tnamespace VIEW\n\t{\n\n\t\tModelSettingsDialog::ModelSettingsDialog( QWidget* parent, const char* name, WFlags fl )\n\t\t\t\t: ModelSettingsDialogData( parent, name, fl )\n\t\t{\n\t\t\tsetDefaults();\n\t\t}\n\n\t\tvoid ModelSettingsDialog::setDefaults(bool all)\n\t\t\tthrow()\n\t\t{\n\t\t\tif (all || list_box->currentItem() == 0)\n\t\t\t{\n\t\t\t\tstick_radius_slider->setValue(2);\n\t\t\t}\n\t\t\t\n\t\t\tif (all || list_box->currentItem() == 1)\n\t\t\t{\n\t\t\t\tball_stick_cylinder_radius_slider->setValue(2);\n\t\t\t\tball_stick_sphere_radius_slider->setValue(4);\n\t\t\t}\n\t\t\t\n\t\t\tif (all || list_box->currentItem() == 2)\n\t\t\t{\n\t\t\t\tvdw_radius_factor_slider->setValue(10);\n\t\t\t}\n\t\t\t\n\t\t\tif (all || list_box->currentItem() == 3)\n\t\t\t{\n\t\t\t\tsurface_probe_radius_slider->setValue(15);\n\t\t\t}\n\t\t\t\n\t\t\tif (all || list_box->currentItem() == 4)\n\t\t\t{\n\t\t\t\ttube_radius_slider->setValue(4);\n\t\t\t}\n\t\t\t\n\t\t\tif (all || list_box->currentItem() == 5)\n\t\t\t{\n\t\t\t\tcartoon_tube_radius_slider->setValue(4);\n\t\t\t\tcartoon_helix_radius_slider->setValue(20);\n\t\t\t\tcartoon_arrow_width_slider->setValue(20);\n\t\t\t\tcartoon_arrow_height_slider->setValue(4);\n\t\t\t}\n\t\t\t\n\t\t\tif (all || list_box->currentItem() == 6)\n\t\t\t{\n\t\t\t\thbonds_radius_slider->setValue(3);\n\t\t\t}\n\t\t}\n\n\t\tfloat ModelSettingsDialog::getFloatValue_(const QSlider* const& slider) const\n\t\t\tthrow()\n\t\t{\n\t\t\treturn (float(slider->value())) \/ 10.0;\n\t\t}\n\n\t\tvoid ModelSettingsDialog::setValue_(QSlider* le, float value)\n\t\t\tthrow()\n\t\t{\n\t\t\tle->setValue((Size)(value * 10.0));\n\t\t}\n\n\t\tvoid ModelSettingsDialog::setLabelText_(QLabel* label, const QSlider* const from)\n\t\t\tthrow()\n\t\t{\n\t\t\tString s((float)from->value() \/ 10.0);\n\t\t\ts.trimRight(\"0\");\n\t\t\tif (s.hasSuffix(\".\")) s+= \"0\";\n\t\t\tlabel->setText(s.c_str());\n\t\t}\n\n\t\tvoid ModelSettingsDialog::fetchPreference_(const INIFile& inifile, const String& entry, QSlider& slider)\n\t\t\tthrow()\n\t\t{\n\t\t\tif (!inifile.hasEntry(\"MODEL_OPTIONS\", entry)) return;\n\t\t\tsetValue_(&slider, inifile.getValue(\"MODEL_OPTIONS\", entry).toFloat());\n\t\t}\n\n\t\tvoid ModelSettingsDialog::writePreference_(INIFile& inifile, const String& entry, const QSlider& slider) const\n\t\t\tthrow()\n\t\t{\n\t\t\tinifile.insertValue(\"MODEL_OPTIONS\", entry, getFloatValue_(&slider));\n\t\t}\n\n\n\t\tvoid ModelSettingsDialog::writePreferences(INIFile& file)\n\t\t\tthrow()\n\t\t{\n\t\t\tfile.appendSection(\"MODEL_OPTIONS\");\n\t\t\twritePreference_(file, \"stick_radius\", *stick_radius_slider);\n\t\t\twritePreference_(file, \"ball_stick_cylinder_radius\", *ball_stick_cylinder_radius_slider);\n\t\t\twritePreference_(file, \"ball_stick_sphere_radius\", *ball_stick_sphere_radius_slider);\n\t\t\twritePreference_(file, \"vdw_radius_factor\", *vdw_radius_factor_slider);\n\t\t\twritePreference_(file, \"surface_probe_radius\", *surface_probe_radius_slider);\n\t\t\twritePreference_(file, \"tube_radius\", *tube_radius_slider);\n\t\t\twritePreference_(file, \"cartoon_tube_radius\", *cartoon_tube_radius_slider);\n\t\t\twritePreference_(file, \"cartoon_helix_radius\", *cartoon_helix_radius_slider);\n\t\t\twritePreference_(file, \"cartoon_arrow_height\", *cartoon_arrow_height_slider);\n\t\t\twritePreference_(file, \"cartoon_arrow_width\", *cartoon_arrow_width_slider);\n\t\t\twritePreference_(file, \"cartoon_arrow_width\", *cartoon_arrow_width_slider);\n\t\t\twritePreference_(file, \"hbonds_radius\", *hbonds_radius_slider);\n\t\t}\n\n\t\tvoid ModelSettingsDialog::fetchPreferences(const INIFile& file)\n\t\t\tthrow()\n\t\t{\n\t\t\tfetchPreference_(file, \"stick_radius\", *stick_radius_slider);\n\t\t\tfetchPreference_(file, \"ball_stick_cylinder_radius\", *ball_stick_cylinder_radius_slider);\n\t\t\tfetchPreference_(file, \"ball_stick_sphere_radius\", *ball_stick_sphere_radius_slider);\n\t\t\tfetchPreference_(file, \"vdw_radius_factor\", *vdw_radius_factor_slider);\n\t\t\tfetchPreference_(file, \"surface_probe_radius\", *surface_probe_radius_slider);\n\t\t\tfetchPreference_(file, \"tube_radius\", *tube_radius_slider);\n\t\t\tfetchPreference_(file, \"cartoon_tube_radius\", *cartoon_tube_radius_slider);\n\t\t\tfetchPreference_(file, \"cartoon_helix_radius\", *cartoon_helix_radius_slider);\n\t\t\tfetchPreference_(file, \"cartoon_arrow_height\", *cartoon_arrow_height_slider);\n\t\t\tfetchPreference_(file, \"cartoon_arrow_width\", *cartoon_arrow_width_slider);\n\t\t\tfetchPreference_(file, \"hbonds_radius\", *hbonds_radius_slider);\n\t\t}\n\n\t\tvoid ModelSettingsDialog::setDefaultValues()\n\t\t\tthrow()\n\t\t{\n\t\t\tsetDefaults(false);\n\t\t}\n\n\t\tvoid ModelSettingsDialog::showPage(int nr)\n\t\t{\n\t\t\tif (widget_stack->widget(nr) == 0)\n\t\t\t{\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (list_box->currentItem() != nr)\n\t\t\t{\n\t\t\t\tlist_box->setCurrentItem(nr);\n\t\t\t}\n\t\t\twidget_stack->raiseWidget(nr);\n\t\t}\n\n\n\t} \/\/ namespace VIEW\n} \/\/ namespace BALL\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2008 by Sun Microsystems, Inc.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: PostItMgr.hxx,v $\n * $Revision: 1.7 $\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * <http:\/\/www.openoffice.org\/license.html>\n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n#ifndef _POSTITMGR_HXX\n#define _POSTITMGR_HXX\n\n#include <svtools\/lstner.hxx>\n\n#include <list>\n#include <vector>\n\n#include <tools\/link.hxx>\n#include <swrect.hxx>\n\nclass SwWrtShell;\nclass SwDoc;\nclass SwView;\nclass SwPostItField;\nclass SwFmtFld;\nclass SwField;\nclass SfxBroadcaster;\nclass SfxHint;\nclass SwPostIt;\nclass SwEditWin;\nclass Color;\nclass SvxSearchItem;\nclass SvxLanguageItem;\n\n#define SORT_POS 1\n#define SORT_AUTHOR 2\n#define SORT_DATE 3\n\n#define COL_NOTES_SIDEPANE_ARROW_ENABLED RGB_COLORDATA(0,0,0)\n#define COL_NOTES_SIDEPANE_ARROW_DISABLED RGB_COLORDATA(172,168,153)\n\nstruct SwPostItItem;\n\ntypedef std::list<SwPostItItem*> SwPostItItem_list;\n\nstruct SwPostItPageItem\n{\n bool bScrollbar;\n bool bMarginSide;\n long lOffset;\n SwRect mPageRect;\n SwPostItItem_list* mList;\n SwPostItPageItem(): bScrollbar(false),lOffset(0)\n {\n mList = new SwPostItItem_list;\n }\n ~SwPostItPageItem()\n {\n mList->clear();\n delete mList;\n }\n\n};\n\nstruct FieldShadowState\n{\n const SwPostItField* mpShadowFld;\n bool bCursor;\n bool bMouse;\n FieldShadowState(): mpShadowFld(0),bCursor(false),bMouse(false)\n {\n }\n};\n\nclass SwPostItMgr: public SfxListener\n{\n private:\n SwView* mpView;\n SwWrtShell* mpWrtShell;\n SwEditWin* mpEditWin;\n std::list< SwPostItItem*> mvPostItFlds;\n std::vector<SwPostItPageItem*> mPages;\n ULONG mnEventId;\n bool mbWaitingForCalcRects;\n SwPostIt* mpActivePostIt;\n bool mbLayout;\n long mbLayoutHeight;\n long mbLayouting;\n bool mbReadOnly;\n bool mbDeleteNote;\n FieldShadowState mShadowState;\n\n typedef std::list<SwPostItItem*>::iterator SwPostItItem_iterator;\n typedef std::list<SwPostIt*>::iterator SwPostIt_iterator;\n\n void AddPostIts(bool bCheckExistance = true,bool bFocus = true);\n void RemovePostIts();\n void PreparePageContainer();\n void Scroll(const long lScroll,const unsigned long aPage );\n void AutoScroll(const SwPostIt* pPostIt,const unsigned long aPage );\n bool ScrollbarHit(const unsigned long aPage,const Point &aPoint);\n bool LayoutByPage(std::list<SwPostIt*> &aVisiblePostItList,const Rectangle aBorder,long lNeededHeight);\n void CheckForRemovedPostIts();\n bool ArrowEnabled(USHORT aDirection,unsigned long aPage) const;\n bool BorderOverPageBorder(unsigned long aPage) const;\n bool HasScrollbars() const;\n\n void SetColors(SwPostIt* pPostIt, SwPostItField* pFld);\n\n Color GetColorDark(sal_uInt16 aAuthorIndex);\n Color GetColorLight(sal_uInt16 aAuthorIndex);\n Color GetColorAnkor(sal_uInt16 aAuthorIndex);\n\n sal_Int32 GetInitialAnchorDistance() const;\n sal_Int32 GetScrollSize() const;\n sal_Int32 GetSpaceBetween() const;\n void SetReadOnlyState();\n DECL_LINK( CalcHdl, void*);\n\n protected:\n\n public:\n SwPostItMgr(SwView* aDoc);\n ~SwPostItMgr();\n\n typedef std::list< SwPostItItem* >::const_iterator const_iterator;\n const_iterator begin() const { return mvPostItFlds.begin(); }\n const_iterator end() const { return mvPostItFlds.end(); }\n\n void InsertFld( SwFmtFld* aField, bool bCheckExistance, bool bFocus);\n void RemoveFld( SfxBroadcaster* pFld );\n void Notify( SfxBroadcaster& rBC, const SfxHint& rHint );\n\n void LayoutPostIts();\n bool CalcRects();\n\n void MakeVisible(const SwPostIt* pPostIt,long aPage = -1);\n\n bool ShowScrollbar(const unsigned long aPage) const;\n bool HasNotes() const ;\n bool ShowNotes() const;\n unsigned long GetSidebarWidth(bool bPx = false) const;\n unsigned long GetSidebarBorderWidth(bool bPx = false) const;\n unsigned long GetNoteWidth();\n\n void PrepareView(bool bIgnoreCount = false);\n\n void CorrectPositions();\n\n void Sort(const short aType);\n\n void SetLayout() { mbLayout = true; };\n void Delete(String aAuthor);\n void Delete();\n\n void Hide( SwPostItField* pPostItField );\n void Hide( const String& rAuthor );\n void Hide();\n void Show();\n\n void Rescale();\n\n Rectangle GetBottomScrollRect(const unsigned long aPage) const;\n Rectangle GetTopScrollRect(const unsigned long aPage) const;\n\n bool IsHit(const Point &aPointPixel);\n Color GetArrowColor(USHORT aDirection,unsigned long aPage) const;\n\n SwPostIt* GetNextPostIt(USHORT aDirection, SwPostIt* aPostIt);\n long GetNextBorder();\n SwPostIt* GetActivePostIt() { return mpActivePostIt; }\n void SetActivePostIt( SwPostIt* p);\n sal_Int32 GetMinimumSizeWithMeta() const;\n sal_Int32 GetSidebarScrollerHeight() const;\n\n SwFmtFld* GetFmtFld(SwPostIt* mpPostIt) const;\n SwPostIt* GetPostIt(const SwFmtFld* pFld) const;\n SwPostIt* GetPostIt(const SwPostItField* pFld) const;\n SwPostIt* GetPostIt(SwFmtFld* pFld) const;\n SwPostIt* GetPostIt(SwPostItField* pFld) const;\n\n void SetShadowState(const SwPostItField* pFld,bool bCursor = true);\n\n void SetSpellChecking();\n\n bool ShowPreview(const SwField* pFld,SwFmtFld*& pFmtFld) const;\n};\n\n#endif\n<commit_msg>INTEGRATION: CWS notes6 (1.6.24); FILE MERGED 2008\/06\/10 18:29:37 mod 1.6.24.1: notes5 import<commit_after>\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2008 by Sun Microsystems, Inc.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: PostItMgr.hxx,v $\n * $Revision: 1.8 $\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * <http:\/\/www.openoffice.org\/license.html>\n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n#ifndef _POSTITMGR_HXX\n#define _POSTITMGR_HXX\n\n#include <svtools\/lstner.hxx>\n\n#include <list>\n#include <vector>\n\n#include <tools\/link.hxx>\n#include <swrect.hxx>\n\nclass SwWrtShell;\nclass SwDoc;\nclass SwView;\nclass SwPostItField;\nclass SwFmtFld;\nclass SwField;\nclass SfxBroadcaster;\nclass SfxHint;\nclass SwPostIt;\nclass SwEditWin;\nclass Color;\nclass SvxSearchItem;\nclass SvxLanguageItem;\n\n#define SORT_POS 1\n#define SORT_AUTHOR 2\n#define SORT_DATE 3\n\n#define COL_NOTES_SIDEPANE_ARROW_ENABLED RGB_COLORDATA(0,0,0)\n#define COL_NOTES_SIDEPANE_ARROW_DISABLED RGB_COLORDATA(172,168,153)\n\nstruct SwPostItItem;\n\ntypedef std::list<SwPostItItem*> SwPostItItem_list;\n\nstruct SwPostItPageItem\n{\n bool bScrollbar;\n bool bMarginSide;\n long lOffset;\n SwRect mPageRect;\n SwPostItItem_list* mList;\n SwPostItPageItem(): bScrollbar(false),lOffset(0)\n {\n mList = new SwPostItItem_list;\n }\n ~SwPostItPageItem()\n {\n mList->clear();\n delete mList;\n }\n\n};\n\nstruct FieldShadowState\n{\n const SwPostItField* mpShadowFld;\n bool bCursor;\n bool bMouse;\n FieldShadowState(): mpShadowFld(0),bCursor(false),bMouse(false)\n {\n }\n};\n\nclass SwPostItMgr: public SfxListener\n{\n private:\n SwView* mpView;\n SwWrtShell* mpWrtShell;\n SwEditWin* mpEditWin;\n std::list< SwPostItItem*> mvPostItFlds;\n std::vector<SwPostItPageItem*> mPages;\n ULONG mnEventId;\n bool mbWaitingForCalcRects;\n SwPostIt* mpActivePostIt;\n bool mbLayout;\n long mbLayoutHeight;\n long mbLayouting;\n bool mbReadOnly;\n bool mbDeleteNote;\n FieldShadowState mShadowState;\n\n typedef std::list<SwPostItItem*>::iterator SwPostItItem_iterator;\n typedef std::list<SwPostIt*>::iterator SwPostIt_iterator;\n\n void AddPostIts(bool bCheckExistance = true,bool bFocus = true);\n void RemovePostIts();\n void PreparePageContainer();\n void Scroll(const long lScroll,const unsigned long aPage );\n void AutoScroll(const SwPostIt* pPostIt,const unsigned long aPage );\n bool ScrollbarHit(const unsigned long aPage,const Point &aPoint);\n bool LayoutByPage(std::list<SwPostIt*> &aVisiblePostItList,const Rectangle aBorder,long lNeededHeight);\n void CheckForRemovedPostIts();\n bool ArrowEnabled(USHORT aDirection,unsigned long aPage) const;\n bool BorderOverPageBorder(unsigned long aPage) const;\n bool HasScrollbars() const;\n\n void SetColors(SwPostIt* pPostIt, SwPostItField* pFld);\n\n Color GetColorDark(sal_uInt16 aAuthorIndex);\n Color GetColorLight(sal_uInt16 aAuthorIndex);\n Color GetColorAnkor(sal_uInt16 aAuthorIndex);\n\n sal_Int32 GetInitialAnchorDistance() const;\n sal_Int32 GetScrollSize() const;\n sal_Int32 GetSpaceBetween() const;\n void SetReadOnlyState();\n DECL_LINK( CalcHdl, void*);\n\n protected:\n\n public:\n SwPostItMgr(SwView* aDoc);\n ~SwPostItMgr();\n\n typedef std::list< SwPostItItem* >::const_iterator const_iterator;\n const_iterator begin() const { return mvPostItFlds.begin(); }\n const_iterator end() const { return mvPostItFlds.end(); }\n\n void InsertFld( SwFmtFld* aField, bool bCheckExistance, bool bFocus);\n void RemoveFld( SfxBroadcaster* pFld );\n void Notify( SfxBroadcaster& rBC, const SfxHint& rHint );\n\n void LayoutPostIts();\n bool CalcRects();\n\n void MakeVisible(const SwPostIt* pPostIt,long aPage = -1);\n\n bool ShowScrollbar(const unsigned long aPage) const;\n bool HasNotes() const ;\n bool ShowNotes() const;\n unsigned long GetSidebarWidth(bool bPx = false) const;\n unsigned long GetSidebarBorderWidth(bool bPx = false) const;\n unsigned long GetNoteWidth();\n\n void PrepareView(bool bIgnoreCount = false);\n\n void CorrectPositions();\n\n void Sort(const short aType);\n\n void SetLayout() { mbLayout = true; };\n void Delete(String aAuthor);\n void Delete();\n\n void Hide( SwPostItField* pPostItField );\n void Hide( const String& rAuthor );\n void Hide();\n void Show();\n\n void Rescale();\n\n Rectangle GetBottomScrollRect(const unsigned long aPage) const;\n Rectangle GetTopScrollRect(const unsigned long aPage) const;\n\n bool IsHit(const Point &aPointPixel);\n Color GetArrowColor(USHORT aDirection,unsigned long aPage) const;\n\n SwPostIt* GetNextPostIt(USHORT aDirection, SwPostIt* aPostIt);\n long GetNextBorder();\n SwPostIt* GetActivePostIt() { return mpActivePostIt; }\n void SetActivePostIt( SwPostIt* p);\n sal_Int32 GetMinimumSizeWithMeta() const;\n sal_Int32 GetSidebarScrollerHeight() const;\n\n SwFmtFld* GetFmtFld(SwPostIt* mpPostIt) const;\n SwPostIt* GetPostIt(const SwFmtFld* pFld) const;\n SwPostIt* GetPostIt(const SwPostItField* pFld) const;\n SwPostIt* GetPostIt(SwFmtFld* pFld) const;\n SwPostIt* GetPostIt(SwPostItField* pFld) const;\n\n void SetShadowState(const SwPostItField* pFld,bool bCursor = true);\n\n void SetSpellChecking();\n\n bool ShowPreview(const SwField* pFld,SwFmtFld*& pFmtFld) const;\n};\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: PostItMgr.hxx,v $\n *\n * $Revision: 1.2 $\n *\n * last change: $Author: rt $ $Date: 2008-02-19 13:20:41 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef _POSTITMGR_HXX\n#define _POSTITMGR_HXX\n\n#ifndef _SFXLSTNER_HXX\n#include <svtools\/lstner.hxx>\n#endif\n\n#include <list>\n#include <vector>\n\n#include <tools\/link.hxx>\n#include <swrect.hxx>\n\nclass SwWrtShell;\nclass SwDoc;\nclass SwView;\nclass SwPostItField;\nclass SwFmtFld;\nclass SfxBroadcaster;\nclass SfxHint;\nclass SwPostIt;\nclass SwEditWin;\nclass Color;\n\n#define SORT_POS 1\n#define SORT_AUTHOR 2\n#define SORT_DATE 3\n\n#define COL_NOTES_SIDEPANE_ARROW_ENABLED RGB_COLORDATA(0,0,0)\n#define COL_NOTES_SIDEPANE_ARROW_DISABLED RGB_COLORDATA(172,168,153)\n\n\nstruct SwPostItItem\n{\n bool bShow;\n bool bFocus;\n SwFmtFld* pFmtFld;\n SwPostIt* pPostIt;\n SwRect mPos;\n SwRect mFramePos;\n SwRect mPagePos;\n SwPostItItem( SwFmtFld* p, bool aShow, bool aFocus)\n : bShow(aShow),\n bFocus(aFocus),\n pFmtFld(p),\n pPostIt(0)\n {\n }\n};\n\ntypedef std::list<SwPostItItem*> SwPostItItem_list;\n\nstruct SwPostItPageItem\n{\n bool bScrollbar;\n bool bMarginSide;\n long lOffset;\n SwRect mPageRect;\n SwPostItItem_list* mList;\n SwPostItPageItem(): bScrollbar(false),lOffset(0)\n {\n mList = new SwPostItItem_list;\n }\n ~SwPostItPageItem()\n {\n mList->clear();\n delete mList;\n }\n\n};\n\nclass SwPostItMgr: public SfxListener\n{\n private:\n SwView* mpView;\n SwWrtShell* mpWrtShell;\n SwEditWin* mpEditWin;\n std::list< SwPostItItem*> mvPostItFlds;\n std::vector<SwPostItPageItem*> mPages;\n ULONG mnEventId;\n bool mbWaitingForCalcRects;\n SwPostIt* mpActivePostIt;\n bool mbLayout;\n long mbLayoutHeight;\n long mbLayouting;\n bool mbDeletingSeveral;\n\n typedef std::list<SwPostItItem*>::iterator SwPostItItem_iterator;\n typedef std::list<SwPostIt*>::iterator SwPostIt_iterator;\n\n void AddPostIts(bool bCheckExistance = true,bool bFocus = true);\n void RemovePostIts();\n void PreparePageContainer();\n void Scroll(const long lScroll,const unsigned long aPage );\n void AutoScroll(const SwPostIt* pPostIt,const unsigned long aPage );\n bool ScrollbarHit(const unsigned long aPage,const Point &aPoint);\n bool LayoutByPage(std::list<SwPostIt*> &aVisiblePostItList,const Rectangle aBorder,long lNeededHeight);\n void CheckForRemovedPostIts();\n bool ArrowEnabled(USHORT aDirection,unsigned long aPage);\n bool BorderOverPageBorder(unsigned long aPage);\n bool HasScrollbars();\n sal_Int32 GetInitialAnchorDistance();\n sal_Int32 GetScrollSize();\n sal_Int32 GetSpaceBetween();\n void SetReadOnlyState();\n DECL_LINK( CalcHdl, void*);\n\n protected:\n\n public:\n SwPostItMgr(SwView* aDoc);\n ~SwPostItMgr();\n\n typedef std::list< SwPostItItem* >::const_iterator const_iterator;\n const_iterator begin() const { return mvPostItFlds.begin(); }\n const_iterator end() const { return mvPostItFlds.end(); }\n\n void InsertFld( SwFmtFld* aField, bool bCheckExistance, bool bFocus);\n void RemoveFld( SfxBroadcaster* pFld );\n void Notify( SfxBroadcaster& rBC, const SfxHint& rHint );\n\n void LayoutPostIts();\n bool CalcRects();\n\n void AutoScroll(const SwPostIt* pPostIt);\n bool ShowScrollbar(const unsigned long aPage);\n bool HasNotes();\n bool ShowNotes();\n unsigned long GetSidebarWidth(bool bPx = false);\n unsigned long GetSidebarBorderWidth(bool bPx = false);\n unsigned long GetNoteWidth();\n\n void PrepareView(bool bIgnoreCount = false);\n\n void CorrectPositions();\n void SetColors(SwPostIt* pPostIt, SwPostItField* pFld);\n\n void Sort(const short aType);\n\n void SetLayout() { mbLayout = true; };\n void Delete(String aAuthor);\n void Delete();\n\n void Hide(SwPostItField* aPostItField, bool All = false);\n void Hide();\n void Show();\n\n void Rescale();\n\n Rectangle GetBottomScrollRect(const unsigned long aPage);\n Rectangle GetTopScrollRect(const unsigned long aPage);\n\n bool IsHit(const Point &aPointPixel);\n Color GetArrowColor(USHORT aDirection,unsigned long aPage);\n\n SwPostIt* GetNextPostIt(USHORT aDirection, SwPostIt* aPostIt);\n long GetNextBorder();\n SwFmtFld* GetFmtFld(SwPostIt* mpPostIt);\n SwPostIt* GetActivePostIt() { return mpActivePostIt; }\n void SetActivePostIt( SwPostIt* p);\n sal_Int32 GetMinimumSizeWithMeta();\n sal_Int32 GetSidebarScrollerHeight();\n\n void SetSpellChecking(bool bEnable);\n};\n\n#endif\n\n\n<commit_msg>INTEGRATION: CWS pages01_DEV300 (1.2.4); FILE MERGED 2008\/02\/26 10:15:00 fme 1.2.4.1: #i1598# Multiple page view - sync with new notes feature<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: PostItMgr.hxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: kz $ $Date: 2008-03-07 14:48:41 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef _POSTITMGR_HXX\n#define _POSTITMGR_HXX\n\n#ifndef _SFXLSTNER_HXX\n#include <svtools\/lstner.hxx>\n#endif\n\n#include <list>\n#include <vector>\n\n#include <tools\/link.hxx>\n#include <swrect.hxx>\n\nclass SwWrtShell;\nclass SwDoc;\nclass SwView;\nclass SwPostItField;\nclass SwFmtFld;\nclass SfxBroadcaster;\nclass SfxHint;\nclass SwPostIt;\nclass SwEditWin;\nclass Color;\n\n#define SORT_POS 1\n#define SORT_AUTHOR 2\n#define SORT_DATE 3\n\n#define COL_NOTES_SIDEPANE_ARROW_ENABLED RGB_COLORDATA(0,0,0)\n#define COL_NOTES_SIDEPANE_ARROW_DISABLED RGB_COLORDATA(172,168,153)\n\n\nstruct SwPostItItem\n{\n bool bShow;\n bool bFocus;\n SwFmtFld* pFmtFld;\n SwPostIt* pPostIt;\n SwRect mPos;\n SwRect mFramePos;\n SwRect mPagePos;\n SwPostItItem( SwFmtFld* p, bool aShow, bool aFocus)\n : bShow(aShow),\n bFocus(aFocus),\n pFmtFld(p),\n pPostIt(0)\n {\n }\n};\n\ntypedef std::list<SwPostItItem*> SwPostItItem_list;\n\nstruct SwPostItPageItem\n{\n bool bScrollbar;\n bool bMarginSide;\n long lOffset;\n SwRect mPageRect;\n SwPostItItem_list* mList;\n SwPostItPageItem(): bScrollbar(false),lOffset(0)\n {\n mList = new SwPostItItem_list;\n }\n ~SwPostItPageItem()\n {\n mList->clear();\n delete mList;\n }\n\n};\n\nclass SwPostItMgr: public SfxListener\n{\n private:\n SwView* mpView;\n SwWrtShell* mpWrtShell;\n SwEditWin* mpEditWin;\n std::list< SwPostItItem*> mvPostItFlds;\n std::vector<SwPostItPageItem*> mPages;\n ULONG mnEventId;\n bool mbWaitingForCalcRects;\n SwPostIt* mpActivePostIt;\n bool mbLayout;\n long mbLayoutHeight;\n long mbLayouting;\n bool mbDeletingSeveral;\n\n typedef std::list<SwPostItItem*>::iterator SwPostItItem_iterator;\n typedef std::list<SwPostIt*>::iterator SwPostIt_iterator;\n\n void AddPostIts(bool bCheckExistance = true,bool bFocus = true);\n void RemovePostIts();\n void PreparePageContainer();\n void Scroll(const long lScroll,const unsigned long aPage );\n void AutoScroll(const SwPostIt* pPostIt,const unsigned long aPage );\n bool ScrollbarHit(const unsigned long aPage,const Point &aPoint);\n bool LayoutByPage(std::list<SwPostIt*> &aVisiblePostItList,const Rectangle aBorder,long lNeededHeight);\n void CheckForRemovedPostIts();\n bool ArrowEnabled(USHORT aDirection,unsigned long aPage) const;\n bool BorderOverPageBorder(unsigned long aPage) const;\n bool HasScrollbars() const;\n sal_Int32 GetInitialAnchorDistance() const;\n sal_Int32 GetScrollSize() const;\n sal_Int32 GetSpaceBetween() const;\n void SetReadOnlyState();\n DECL_LINK( CalcHdl, void*);\n\n protected:\n\n public:\n SwPostItMgr(SwView* aDoc);\n ~SwPostItMgr();\n\n typedef std::list< SwPostItItem* >::const_iterator const_iterator;\n const_iterator begin() const { return mvPostItFlds.begin(); }\n const_iterator end() const { return mvPostItFlds.end(); }\n\n void InsertFld( SwFmtFld* aField, bool bCheckExistance, bool bFocus);\n void RemoveFld( SfxBroadcaster* pFld );\n void Notify( SfxBroadcaster& rBC, const SfxHint& rHint );\n\n void LayoutPostIts();\n bool CalcRects();\n\n void AutoScroll(const SwPostIt* pPostIt);\n bool ShowScrollbar(const unsigned long aPage) const;\n bool HasNotes() const ;\n bool ShowNotes() const;\n unsigned long GetSidebarWidth(bool bPx = false) const;\n unsigned long GetSidebarBorderWidth(bool bPx = false) const;\n unsigned long GetNoteWidth();\n\n void PrepareView(bool bIgnoreCount = false);\n\n void CorrectPositions();\n void SetColors(SwPostIt* pPostIt, SwPostItField* pFld);\n\n void Sort(const short aType);\n\n void SetLayout() { mbLayout = true; };\n void Delete(String aAuthor);\n void Delete();\n\n void Hide(SwPostItField* aPostItField, bool All = false);\n void Hide();\n void Show();\n\n void Rescale();\n\n Rectangle GetBottomScrollRect(const unsigned long aPage) const;\n Rectangle GetTopScrollRect(const unsigned long aPage) const;\n\n bool IsHit(const Point &aPointPixel);\n Color GetArrowColor(USHORT aDirection,unsigned long aPage) const;\n\n SwPostIt* GetNextPostIt(USHORT aDirection, SwPostIt* aPostIt);\n long GetNextBorder();\n SwFmtFld* GetFmtFld(SwPostIt* mpPostIt);\n SwPostIt* GetActivePostIt() { return mpActivePostIt; }\n void SetActivePostIt( SwPostIt* p);\n sal_Int32 GetMinimumSizeWithMeta() const;\n sal_Int32 GetSidebarScrollerHeight() const;\n\n void SetSpellChecking(bool bEnable);\n};\n\n#endif\n\n\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: printdata.hxx,v $\n *\n * $Revision: 1.1 $\n *\n * last change: $Author: os $ $Date: 2001-05-10 08:40:24 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n#ifndef _SW_PRINTDATA_HXX\n#define _SW_PRINTDATA_HXX\n\n\n#ifndef _SAL_TYPES_H_\n#include <sal\/types.h>\n#endif\n#ifndef _RTL_USTRING_\n#include <rtl\/ustring>\n#endif\nstruct SwPrintData\n{\n sal_Bool\n bPrintGraphic ,\n bPrintTable ,\n bPrintDraw ,\n bPrintControl ,\n bPrintPageBackground,\n bPrintBlackFont ,\n\n bPrintLeftPage ,\n bPrintRightPage ,\n bPrintReverse ,\n bPrintProspect ,\n bPrintSingleJobs ,\n\n bPaperFromSetup ;\n\n sal_Int16 nPrintPostIts;\n rtl::OUString sFaxName;\n\n SwPrintData()\n {\n bPrintGraphic =\n bPrintTable =\n bPrintDraw =\n bPrintControl =\n bPrintLeftPage =\n bPrintRightPage =\n bPrintPageBackground = sal_True;\n\n bPaperFromSetup =\n bPrintReverse =\n bPrintProspect =\n bPrintSingleJobs =\n bPrintBlackFont = sal_False;\n\n nPrintPostIts = 0;\n }\n sal_Bool operator==(const SwPrintData& rData)const\n {\n return\n bPrintGraphic == rData.bPrintGraphic &&\n bPrintTable == rData.bPrintTable &&\n bPrintDraw == rData.bPrintDraw &&\n bPrintControl == rData.bPrintControl &&\n bPrintPageBackground== rData.bPrintPageBackground&&\n bPrintBlackFont == rData.bPrintBlackFont &&\n bPrintLeftPage == rData.bPrintLeftPage &&\n bPrintRightPage == rData.bPrintRightPage &&\n bPrintReverse == rData.bPrintReverse &&\n bPrintProspect == rData.bPrintProspect &&\n bPrintSingleJobs == rData.bPrintSingleJobs &&\n bPaperFromSetup == rData.bPaperFromSetup &&\n nPrintPostIts == rData.nPrintPostIts &&\n sFaxName == rData.sFaxName;\n }\n};\n\n#endif \/\/_SW_PRINTDATA_HXX\n\n<commit_msg>#90674# moved this functionality here from source\\ui\\inc\\prtopt.hxx<commit_after>\/*************************************************************************\n *\n * $RCSfile: printdata.hxx,v $\n *\n * $Revision: 1.2 $\n *\n * last change: $Author: mtg $ $Date: 2001-08-08 21:40:10 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n#ifndef _SW_PRINTDATA_HXX\n#define _SW_PRINTDATA_HXX\n\n\n#ifndef _SAL_TYPES_H_\n#include <sal\/types.h>\n#endif\n#ifndef _RTL_USTRING_\n#include <rtl\/ustring>\n#endif\n\nstruct SwPrintData\n{\n sal_Bool bPrintGraphic, bPrintTable, bPrintDraw, bPrintControl, bPrintPageBackground,\n bPrintBlackFont, bPrintLeftPage, bPrintRightPage, bPrintReverse, bPrintProspect,\n bPrintSingleJobs, bPaperFromSetup, bModified;\n\n sal_Int16 nPrintPostIts;\n rtl::OUString sFaxName;\n\n SwPrintData()\n {\n bPrintGraphic =\n bPrintTable =\n bPrintDraw =\n bPrintControl =\n bPrintLeftPage =\n bPrintRightPage =\n bPrintPageBackground = sal_True;\n\n bPaperFromSetup =\n bPrintReverse =\n bPrintProspect =\n bPrintSingleJobs =\n bModified =\n bPrintBlackFont = sal_False;\n\n nPrintPostIts = 0;\n }\n\n sal_Bool operator==(const SwPrintData& rData)const\n {\n return\n bPrintGraphic == rData.bPrintGraphic &&\n bPrintTable == rData.bPrintTable &&\n bPrintDraw == rData.bPrintDraw &&\n bPrintControl == rData.bPrintControl &&\n bPrintPageBackground== rData.bPrintPageBackground&&\n bPrintBlackFont == rData.bPrintBlackFont &&\n bPrintLeftPage == rData.bPrintLeftPage &&\n bPrintRightPage == rData.bPrintRightPage &&\n bPrintReverse == rData.bPrintReverse &&\n bPrintProspect == rData.bPrintProspect &&\n bPrintSingleJobs == rData.bPrintSingleJobs &&\n bPaperFromSetup == rData.bPaperFromSetup &&\n nPrintPostIts == rData.nPrintPostIts &&\n sFaxName == rData.sFaxName;\n }\n sal_Bool IsPrintGraphic() const { return bPrintGraphic; }\n sal_Bool IsPrintTable() const { return bPrintTable; }\n sal_Bool IsPrintDraw() const { return bPrintDraw; }\n sal_Bool IsPrintControl() const { return bPrintControl; }\n sal_Bool IsPrintLeftPage() const { return bPrintLeftPage; }\n sal_Bool IsPrintRightPage() const { return bPrintRightPage; }\n sal_Bool IsPrintReverse() const { return bPrintReverse; }\n sal_Bool IsPaperFromSetup() const { return bPaperFromSetup; }\n sal_Bool IsPrintProspect() const { return bPrintProspect; }\n sal_Bool IsPrintPageBackground() const { return bPrintPageBackground; }\n sal_Bool IsPrintBlackFont() const { return bPrintBlackFont;}\n sal_Bool IsPrintSingleJobs() const { return bPrintSingleJobs;}\n sal_Int16 GetPrintPostIts() const { return nPrintPostIts; }\n const rtl::OUString GetFaxName() const{return sFaxName;}\n\n void SetPrintGraphic ( sal_Bool b ) { doSetModified(); bPrintGraphic = b;}\n void SetPrintTable ( sal_Bool b ) { doSetModified(); bPrintTable = b;}\n void SetPrintDraw ( sal_Bool b ) { doSetModified(); bPrintDraw = b;}\n void SetPrintControl ( sal_Bool b ) { doSetModified(); bPrintControl = b; }\n void SetPrintLeftPage ( sal_Bool b ) { doSetModified(); bPrintLeftPage = b;}\n void SetPrintRightPage( sal_Bool b ) { doSetModified(); bPrintRightPage = b;}\n void SetPrintReverse ( sal_Bool b ) { doSetModified(); bPrintReverse = b;}\n void SetPaperFromSetup( sal_Bool b ) { doSetModified(); bPaperFromSetup = b;}\n void SetPrintPostIts ( sal_Int16 n){ doSetModified(); nPrintPostIts = n; }\n void SetPrintProspect ( sal_Bool b ) { doSetModified(); bPrintProspect = b; }\n void SetPrintPageBackground(sal_Bool b){ doSetModified(); bPrintPageBackground = b;}\n void SetPrintBlackFont(sal_Bool b){ doSetModified(); bPrintBlackFont = b;}\n void SetPrintSingleJobs(sal_Bool b){ doSetModified(); bPrintSingleJobs = b;}\n void SetFaxName(const rtl::OUString& rSet){sFaxName = rSet;}\n virtual void doSetModified () { bModified = sal_True;}\n sal_Bool WasModified () { return bModified; }\n};\n\n#endif \/\/_SW_PRINTDATA_HXX\n\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: printdata.hxx,v $\n *\n * $Revision: 1.8 $\n *\n * last change: $Author: rt $ $Date: 2007-04-03 13:46:03 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n#ifndef _SW_PRINTDATA_HXX\n#define _SW_PRINTDATA_HXX\n\n\n#ifndef _SAL_TYPES_H_\n#include <sal\/types.h>\n#endif\n#ifndef _RTL_USTRING_HXX_\n#include <rtl\/ustring.hxx>\n#endif\n\nstruct SwPrintData\n{\n sal_Bool bPrintGraphic, bPrintTable, bPrintDraw, bPrintControl, bPrintPageBackground,\n bPrintBlackFont, bPrintLeftPage, bPrintRightPage, bPrintReverse, bPrintProspect,\n bPrintProspect_RTL,\n bPrintSingleJobs, bPaperFromSetup,\n \/\/ --> FME 2005-12-13 #b6354161# Print empty pages\n bPrintEmptyPages,\n \/\/ <--\n \/\/ #i56195# no field update while printing mail merge documents\n bUpdateFieldsInPrinting,\n bModified;\n\n sal_Int16 nPrintPostIts;\n rtl::OUString sFaxName;\n\n SwPrintData()\n {\n bPrintGraphic =\n bPrintTable =\n bPrintDraw =\n bPrintControl =\n bPrintLeftPage =\n bPrintRightPage =\n bPrintPageBackground =\n bPrintEmptyPages =\n bUpdateFieldsInPrinting = sal_True;\n\n bPaperFromSetup =\n bPrintReverse =\n bPrintProspect =\n bPrintProspect_RTL =\n bPrintSingleJobs =\n bModified =\n bPrintBlackFont = sal_False;\n\n nPrintPostIts = 0;\n }\n\n sal_Bool operator==(const SwPrintData& rData)const\n {\n return\n bPrintGraphic == rData.bPrintGraphic &&\n bPrintTable == rData.bPrintTable &&\n bPrintDraw == rData.bPrintDraw &&\n bPrintControl == rData.bPrintControl &&\n bPrintPageBackground== rData.bPrintPageBackground&&\n bPrintBlackFont == rData.bPrintBlackFont &&\n bPrintLeftPage == rData.bPrintLeftPage &&\n bPrintRightPage == rData.bPrintRightPage &&\n bPrintReverse == rData.bPrintReverse &&\n bPrintProspect == rData.bPrintProspect &&\n bPrintProspect_RTL == rData.bPrintProspect_RTL &&\n bPrintSingleJobs == rData.bPrintSingleJobs &&\n bPaperFromSetup == rData.bPaperFromSetup &&\n bPrintEmptyPages == rData.bPrintEmptyPages &&\n bUpdateFieldsInPrinting == rData.bUpdateFieldsInPrinting &&\n nPrintPostIts == rData.nPrintPostIts &&\n sFaxName == rData.sFaxName;\n }\n sal_Bool IsPrintGraphic() const { return bPrintGraphic; }\n sal_Bool IsPrintTable() const { return bPrintTable; }\n sal_Bool IsPrintDraw() const { return bPrintDraw; }\n sal_Bool IsPrintControl() const { return bPrintControl; }\n sal_Bool IsPrintLeftPage() const { return bPrintLeftPage; }\n sal_Bool IsPrintRightPage() const { return bPrintRightPage; }\n sal_Bool IsPrintReverse() const { return bPrintReverse; }\n sal_Bool IsPaperFromSetup() const { return bPaperFromSetup; }\n sal_Bool IsPrintEmptyPages() const{ return bPrintEmptyPages; }\n sal_Bool IsPrintProspect() const { return bPrintProspect; }\n sal_Bool IsPrintProspect_RTL() const { return bPrintProspect_RTL; }\n sal_Bool IsPrintPageBackground() const { return bPrintPageBackground; }\n sal_Bool IsPrintBlackFont() const { return bPrintBlackFont;}\n sal_Bool IsPrintSingleJobs() const { return bPrintSingleJobs;}\n sal_Int16 GetPrintPostIts() const { return nPrintPostIts; }\n const rtl::OUString GetFaxName() const{return sFaxName;}\n\n void SetPrintGraphic ( sal_Bool b ) { doSetModified(); bPrintGraphic = b;}\n void SetPrintTable ( sal_Bool b ) { doSetModified(); bPrintTable = b;}\n void SetPrintDraw ( sal_Bool b ) { doSetModified(); bPrintDraw = b;}\n void SetPrintControl ( sal_Bool b ) { doSetModified(); bPrintControl = b; }\n void SetPrintLeftPage ( sal_Bool b ) { doSetModified(); bPrintLeftPage = b;}\n void SetPrintRightPage( sal_Bool b ) { doSetModified(); bPrintRightPage = b;}\n void SetPrintReverse ( sal_Bool b ) { doSetModified(); bPrintReverse = b;}\n void SetPaperFromSetup( sal_Bool b ) { doSetModified(); bPaperFromSetup = b;}\n void SetPrintEmptyPages(sal_Bool b ) { doSetModified(); bPrintEmptyPages = b;}\n void SetPrintPostIts ( sal_Int16 n){ doSetModified(); nPrintPostIts = n; }\n void SetPrintProspect ( sal_Bool b ) { doSetModified(); bPrintProspect = b; }\n void SetPrintPageBackground(sal_Bool b){ doSetModified(); bPrintPageBackground = b;}\n void SetPrintBlackFont(sal_Bool b){ doSetModified(); bPrintBlackFont = b;}\n void SetPrintSingleJobs(sal_Bool b){ doSetModified(); bPrintSingleJobs = b;}\n void SetFaxName(const rtl::OUString& rSet){sFaxName = rSet;}\n virtual void doSetModified () { bModified = sal_True;}\n};\n\n#endif \/\/_SW_PRINTDATA_HXX\n\n<commit_msg>INTEGRATION: CWS swwarnings (1.7.242); FILE MERGED 2007\/04\/11 10:27:50 os 1.7.242.2: RESYNC: (1.7-1.8); FILE MERGED 2007\/02\/22 15:05:38 tl 1.7.242.1: #i69287# warning-free code<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: printdata.hxx,v $\n *\n * $Revision: 1.9 $\n *\n * last change: $Author: hr $ $Date: 2007-09-27 08:08:10 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n#ifndef _SW_PRINTDATA_HXX\n#define _SW_PRINTDATA_HXX\n\n\n#ifndef _SAL_TYPES_H_\n#include <sal\/types.h>\n#endif\n#ifndef _RTL_USTRING_HXX_\n#include <rtl\/ustring.hxx>\n#endif\n\nstruct SwPrintData\n{\n sal_Bool bPrintGraphic, bPrintTable, bPrintDraw, bPrintControl, bPrintPageBackground,\n bPrintBlackFont, bPrintLeftPage, bPrintRightPage, bPrintReverse, bPrintProspect,\n bPrintProspect_RTL,\n bPrintSingleJobs, bPaperFromSetup,\n \/\/ --> FME 2005-12-13 #b6354161# Print empty pages\n bPrintEmptyPages,\n \/\/ <--\n \/\/ #i56195# no field update while printing mail merge documents\n bUpdateFieldsInPrinting,\n bModified;\n\n sal_Int16 nPrintPostIts;\n rtl::OUString sFaxName;\n\n SwPrintData()\n {\n bPrintGraphic =\n bPrintTable =\n bPrintDraw =\n bPrintControl =\n bPrintLeftPage =\n bPrintRightPage =\n bPrintPageBackground =\n bPrintEmptyPages =\n bUpdateFieldsInPrinting = sal_True;\n\n bPaperFromSetup =\n bPrintReverse =\n bPrintProspect =\n bPrintProspect_RTL =\n bPrintSingleJobs =\n bModified =\n bPrintBlackFont = sal_False;\n\n nPrintPostIts = 0;\n }\n\n virtual ~SwPrintData() {}\n\n sal_Bool operator==(const SwPrintData& rData)const\n {\n return\n bPrintGraphic == rData.bPrintGraphic &&\n bPrintTable == rData.bPrintTable &&\n bPrintDraw == rData.bPrintDraw &&\n bPrintControl == rData.bPrintControl &&\n bPrintPageBackground== rData.bPrintPageBackground&&\n bPrintBlackFont == rData.bPrintBlackFont &&\n bPrintLeftPage == rData.bPrintLeftPage &&\n bPrintRightPage == rData.bPrintRightPage &&\n bPrintReverse == rData.bPrintReverse &&\n bPrintProspect == rData.bPrintProspect &&\n bPrintProspect_RTL == rData.bPrintProspect_RTL &&\n bPrintSingleJobs == rData.bPrintSingleJobs &&\n bPaperFromSetup == rData.bPaperFromSetup &&\n bPrintEmptyPages == rData.bPrintEmptyPages &&\n bUpdateFieldsInPrinting == rData.bUpdateFieldsInPrinting &&\n nPrintPostIts == rData.nPrintPostIts &&\n sFaxName == rData.sFaxName;\n }\n sal_Bool IsPrintGraphic() const { return bPrintGraphic; }\n sal_Bool IsPrintTable() const { return bPrintTable; }\n sal_Bool IsPrintDraw() const { return bPrintDraw; }\n sal_Bool IsPrintControl() const { return bPrintControl; }\n sal_Bool IsPrintLeftPage() const { return bPrintLeftPage; }\n sal_Bool IsPrintRightPage() const { return bPrintRightPage; }\n sal_Bool IsPrintReverse() const { return bPrintReverse; }\n sal_Bool IsPaperFromSetup() const { return bPaperFromSetup; }\n sal_Bool IsPrintEmptyPages() const{ return bPrintEmptyPages; }\n sal_Bool IsPrintProspect() const { return bPrintProspect; }\n sal_Bool IsPrintProspect_RTL() const { return bPrintProspect_RTL; }\n sal_Bool IsPrintPageBackground() const { return bPrintPageBackground; }\n sal_Bool IsPrintBlackFont() const { return bPrintBlackFont;}\n sal_Bool IsPrintSingleJobs() const { return bPrintSingleJobs;}\n sal_Int16 GetPrintPostIts() const { return nPrintPostIts; }\n const rtl::OUString GetFaxName() const{return sFaxName;}\n\n void SetPrintGraphic ( sal_Bool b ) { doSetModified(); bPrintGraphic = b;}\n void SetPrintTable ( sal_Bool b ) { doSetModified(); bPrintTable = b;}\n void SetPrintDraw ( sal_Bool b ) { doSetModified(); bPrintDraw = b;}\n void SetPrintControl ( sal_Bool b ) { doSetModified(); bPrintControl = b; }\n void SetPrintLeftPage ( sal_Bool b ) { doSetModified(); bPrintLeftPage = b;}\n void SetPrintRightPage( sal_Bool b ) { doSetModified(); bPrintRightPage = b;}\n void SetPrintReverse ( sal_Bool b ) { doSetModified(); bPrintReverse = b;}\n void SetPaperFromSetup( sal_Bool b ) { doSetModified(); bPaperFromSetup = b;}\n void SetPrintEmptyPages(sal_Bool b ) { doSetModified(); bPrintEmptyPages = b;}\n void SetPrintPostIts ( sal_Int16 n){ doSetModified(); nPrintPostIts = n; }\n void SetPrintProspect ( sal_Bool b ) { doSetModified(); bPrintProspect = b; }\n void SetPrintPageBackground(sal_Bool b){ doSetModified(); bPrintPageBackground = b;}\n void SetPrintBlackFont(sal_Bool b){ doSetModified(); bPrintBlackFont = b;}\n void SetPrintSingleJobs(sal_Bool b){ doSetModified(); bPrintSingleJobs = b;}\n void SetFaxName(const rtl::OUString& rSet){sFaxName = rSet;}\n virtual void doSetModified () { bModified = sal_True;}\n};\n\n#endif \/\/_SW_PRINTDATA_HXX\n\n<|endoftext|>"} {"text":"<commit_before>\n#include \"PyMindAgent.h\"\n\n#include <opencog\/server\/CogServer.h>\n\n#include \"agent_finder_types.h\"\n#include \"agent_finder_api.h\"\n\nusing namespace opencog;\n\nPyMindAgent::PyMindAgent(CogServer& cs,\n const std::string& _moduleName,\n const std::string& _className) :\n Agent(cs)\n{\n PyGILState_STATE gstate;\n gstate = PyGILState_Ensure(); \n import_agent_finder();\n moduleName = _moduleName;\n className = _className;\n \/\/ call out to our helper module written in cython\n pyagent = instantiate_agent(moduleName, className, this);\n PyGILState_Release(gstate); \n if (pyagent == Py_None)\n throw RuntimeException(TRACE_INFO, \"Error creating Python MindAgent\");\n}\n\nconst ClassInfo& PyMindAgent::classinfo() const\n{ \n static const ClassInfo _ci(\"opencog::PyMindAgent(\" + moduleName+\".\"+className+\")\");\n return _ci;\n}\n\nPyMindAgent::~PyMindAgent()\n{\n PyGILState_STATE gstate;\n gstate = PyGILState_Ensure(); \n \/\/ decrement python object reference counter\n Py_DECREF(pyagent);\n PyGILState_Release(gstate); \n}\n\nvoid PyMindAgent::run()\n{\n string result = run_agent(pyagent, &_cogserver.getAtomSpace());\n \/\/ errors only with result is not empty... && duplicate errors are not reported.\n if (result.size() > 0 && result != last_result) {\n \/\/ Any string returned is a traceback\n logger().error(\"[%s::run] Python Exception:\\n%s\",\n this->classinfo().id.c_str(),result.c_str());\n }\n last_result = result;\n}\n\n<commit_msg>Python: Prevent crash on finalization<commit_after>\n#include \"PyMindAgent.h\"\n\n#include <opencog\/server\/CogServer.h>\n\n#include \"agent_finder_types.h\"\n#include \"agent_finder_api.h\"\n\nusing namespace opencog;\n\nPyMindAgent::PyMindAgent(CogServer& cs,\n const std::string& _moduleName,\n const std::string& _className) :\n Agent(cs)\n{\n PyGILState_STATE gstate;\n gstate = PyGILState_Ensure(); \n import_agent_finder();\n moduleName = _moduleName;\n className = _className;\n \/\/ call out to our helper module written in cython\n pyagent = instantiate_agent(moduleName, className, this);\n PyGILState_Release(gstate); \n if (pyagent == Py_None)\n throw RuntimeException(TRACE_INFO, \"Error creating Python MindAgent\");\n}\n\nconst ClassInfo& PyMindAgent::classinfo() const\n{ \n static const ClassInfo _ci(\"opencog::PyMindAgent(\" + moduleName+\".\"+className+\")\");\n return _ci;\n}\n\nstatic bool in_fini = false;\n#if __GNUC__\nstatic __attribute__ ((destructor (65535))) void pyagent_fini(void)\n{\n in_fini = true;\n}\n#endif\n\nPyMindAgent::~PyMindAgent()\n{\n \/\/ Do nothing if we are in finalizer ... because at this point,\n \/\/ python is probably already dead, and doing the below will just\n \/\/ segfault.\n if (in_fini) return;\n\n \/\/ Still fails XXX don't know how to fix this...\n \/\/ Maybe we can ask python if its been finalized?\n return;\n\n \/\/ decrement python object reference counter\n PyGILState_STATE gstate = PyGILState_Ensure(); \n Py_DECREF(pyagent);\n PyGILState_Release(gstate); \n}\n\nvoid PyMindAgent::run()\n{\n string result = run_agent(pyagent, &_cogserver.getAtomSpace());\n \/\/ errors only with result is not empty... && duplicate errors are not reported.\n if (result.size() > 0 && result != last_result) {\n \/\/ Any string returned is a traceback\n logger().error(\"[%s::run] Python Exception:\\n%s\",\n this->classinfo().id.c_str(),result.c_str());\n }\n last_result = result;\n}\n\n<|endoftext|>"} {"text":"<commit_before>#include <gtest\/gtest.h>\n\n#include <blackhole\/attributes.hpp>\n#include <blackhole\/cpp17\/string_view.hpp>\n#include <blackhole\/extensions\/writer.hpp>\n#include <blackhole\/formatter\/string.hpp>\n#include <blackhole\/record.hpp>\n\nnamespace blackhole {\nnamespace testing {\n\nTEST(string_t, Message) {\n formatter::string_t formatter(\"[{message}]\");\n\n const string_view message(\"value\");\n const attribute_pack pack;\n record_t record(0, message, pack);\n writer_t writer;\n formatter.format(record, writer);\n\n EXPECT_EQ(\"[value]\", writer.result().to_string());\n}\n\nTEST(string_t, Severity) {\n \/\/ NOTE: No severity mapping provided, formatter falls back to the numeric case.\n formatter::string_t formatter(\"[{severity}]\");\n\n const string_view message(\"-\");\n const attribute_pack pack;\n record_t record(0, message, pack);\n writer_t writer;\n formatter.format(record, writer);\n\n EXPECT_EQ(\"[0]\", writer.result().to_string());\n}\n\nTEST(string_t, SeverityNum) {\n formatter::string_t formatter(\"[{severity:d}]\");\n\n const string_view message(\"-\");\n const attribute_pack pack;\n record_t record(0, message, pack);\n writer_t writer;\n formatter.format(record, writer);\n\n EXPECT_EQ(\"[0]\", writer.result().to_string());\n}\n\nTEST(string_t, SeverityUser) {\n formatter::string_t formatter(\"[{severity}]\", [](int severity, const std::string&, writer_t& writer) {\n writer.write(\"DEBUG\");\n });\n\n const string_view message(\"-\");\n const attribute_pack pack;\n record_t record(0, message, pack);\n writer_t writer;\n formatter.format(record, writer);\n\n EXPECT_EQ(\"[DEBUG]\", writer.result().to_string());\n}\n\nTEST(string_t, SeverityUserExplicit) {\n formatter::string_t formatter(\"[{severity:s}]\", [](int severity, const std::string&, writer_t& writer) {\n writer.write(\"DEBUG\");\n });\n\n const string_view message(\"-\");\n const attribute_pack pack;\n record_t record(0, message, pack);\n writer_t writer;\n formatter.format(record, writer);\n\n EXPECT_EQ(\"[DEBUG]\", writer.result().to_string());\n}\n\nTEST(string_t, SeverityNumWithMappingProvided) {\n formatter::string_t formatter(\"[{severity:d}]\", [](int severity, const std::string&, writer_t& writer) {\n writer.write(\"DEBUG\");\n });\n\n const string_view message(\"-\");\n const attribute_pack pack;\n record_t record(0, message, pack);\n writer_t writer;\n formatter.format(record, writer);\n\n EXPECT_EQ(\"[0]\", writer.result().to_string());\n}\n\nTEST(string_t, SeverityUserWithSpec) {\n formatter::string_t formatter(\"[{severity:<7}]\", [](int severity, const std::string& spec, writer_t& writer) {\n writer.write(spec, \"DEBUG\");\n });\n\n const string_view message(\"-\");\n const attribute_pack pack;\n record_t record(0, message, pack);\n writer_t writer;\n formatter.format(record, writer);\n\n EXPECT_EQ(\"[DEBUG ]\", writer.result().to_string());\n}\n\nTEST(string_t, CombinedSeverityNumWithMessage) {\n formatter::string_t formatter(\"[{severity:d}]: {message}\");\n\n const string_view message(\"value\");\n const attribute_pack pack;\n record_t record(0, message, pack);\n writer_t writer;\n formatter.format(record, writer);\n\n EXPECT_EQ(\"[0]: value\", writer.result().to_string());\n}\n\n\/\/ TODO: Check error when setting an option to reserved name, i.e. timestamp or message.\n\/\/ TODO: Check error when ph in pattern was not found.\n\n} \/\/ namespace testing\n} \/\/ namespace blackhole\n<commit_msg>feat(tests): add severity num test with spec<commit_after>#include <gtest\/gtest.h>\n\n#include <blackhole\/attributes.hpp>\n#include <blackhole\/cpp17\/string_view.hpp>\n#include <blackhole\/extensions\/writer.hpp>\n#include <blackhole\/formatter\/string.hpp>\n#include <blackhole\/record.hpp>\n\nnamespace blackhole {\nnamespace testing {\n\nTEST(string_t, Message) {\n formatter::string_t formatter(\"[{message}]\");\n\n const string_view message(\"value\");\n const attribute_pack pack;\n record_t record(0, message, pack);\n writer_t writer;\n formatter.format(record, writer);\n\n EXPECT_EQ(\"[value]\", writer.result().to_string());\n}\n\nTEST(string_t, Severity) {\n \/\/ NOTE: No severity mapping provided, formatter falls back to the numeric case.\n formatter::string_t formatter(\"[{severity}]\");\n\n const string_view message(\"-\");\n const attribute_pack pack;\n record_t record(0, message, pack);\n writer_t writer;\n formatter.format(record, writer);\n\n EXPECT_EQ(\"[0]\", writer.result().to_string());\n}\n\nTEST(string_t, SeverityNum) {\n formatter::string_t formatter(\"[{severity:d}]\");\n\n const string_view message(\"-\");\n const attribute_pack pack;\n record_t record(0, message, pack);\n writer_t writer;\n formatter.format(record, writer);\n\n EXPECT_EQ(\"[0]\", writer.result().to_string());\n}\n\nTEST(string_t, SeverityUser) {\n formatter::string_t formatter(\"[{severity}]\", [](int severity, const std::string&, writer_t& writer) {\n writer.write(\"DEBUG\");\n });\n\n const string_view message(\"-\");\n const attribute_pack pack;\n record_t record(0, message, pack);\n writer_t writer;\n formatter.format(record, writer);\n\n EXPECT_EQ(\"[DEBUG]\", writer.result().to_string());\n}\n\nTEST(string_t, SeverityUserExplicit) {\n formatter::string_t formatter(\"[{severity:s}]\", [](int severity, const std::string&, writer_t& writer) {\n writer.write(\"DEBUG\");\n });\n\n const string_view message(\"-\");\n const attribute_pack pack;\n record_t record(0, message, pack);\n writer_t writer;\n formatter.format(record, writer);\n\n EXPECT_EQ(\"[DEBUG]\", writer.result().to_string());\n}\n\nTEST(string_t, SeverityNumWithMappingProvided) {\n formatter::string_t formatter(\"[{severity:d}]\", [](int severity, const std::string&, writer_t& writer) {\n writer.write(\"DEBUG\");\n });\n\n const string_view message(\"-\");\n const attribute_pack pack;\n record_t record(0, message, pack);\n writer_t writer;\n formatter.format(record, writer);\n\n EXPECT_EQ(\"[0]\", writer.result().to_string());\n}\n\nTEST(string_t, SeverityNumWithSpec) {\n formatter::string_t formatter(\"[{severity:*^3d}]\");\n\n const string_view message(\"-\");\n const attribute_pack pack;\n record_t record(0, message, pack);\n writer_t writer;\n formatter.format(record, writer);\n\n EXPECT_EQ(\"[*0*]\", writer.result().to_string());\n}\n\nTEST(string_t, SeverityUserWithSpec) {\n formatter::string_t formatter(\"[{severity:<7}]\", [](int severity, const std::string& spec, writer_t& writer) {\n writer.write(spec, \"DEBUG\");\n });\n\n const string_view message(\"-\");\n const attribute_pack pack;\n record_t record(0, message, pack);\n writer_t writer;\n formatter.format(record, writer);\n\n EXPECT_EQ(\"[DEBUG ]\", writer.result().to_string());\n}\n\nTEST(string_t, CombinedSeverityNumWithMessage) {\n formatter::string_t formatter(\"[{severity:d}]: {message}\");\n\n const string_view message(\"value\");\n const attribute_pack pack;\n record_t record(0, message, pack);\n writer_t writer;\n formatter.format(record, writer);\n\n EXPECT_EQ(\"[0]: value\", writer.result().to_string());\n}\n\n\/\/ TODO: Check error when setting an option to reserved name, i.e. timestamp or message.\n\/\/ TODO: Check error when ph in pattern was not found.\n\n} \/\/ namespace testing\n} \/\/ namespace blackhole\n<|endoftext|>"} {"text":"<commit_before>\/*\n Copyright (c) 2009 Stephen Kelly <steveire@gmail.com>\n\n This library is free software; you can redistribute it and\/or modify it\n under the terms of the GNU Library General Public License as published by\n the Free Software Foundation; either version 2 of the License, or (at your\n option) any later version.\n\n This library is distributed in the hope that it will be useful, but WITHOUT\n ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public\n License for more details.\n\n You should have received a copy of the GNU Library General Public License\n along with this library; see the file COPYING.LIB. If not, write to the\n Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA\n 02110-1301, USA.\n*\/\n\n#include <QtTest>\n#include <QtCore>\n#include <qtest_kde.h>\n#include <qtestevent.h>\n\n#include \"dynamictreemodel.h\"\n#include \"..\/modeltest.h\"\n#include \"..\/descendantentitiesproxymodel.h\"\n\n\/\/ #include \"fakemonitor.h\"\n\n#include <QTreeView>\n\n#include <kdebug.h>\n\nusing namespace Akonadi;\n\n\nclass DescendantEntitiesProxyModelTest : public QObject\n{\n Q_OBJECT\n\nprivate slots:\n void testInsertionChangeAndRemoval();\n void testSameParentUp();\n void testSameParentDown();\n void testDifferentParentUp();\n void testDifferentParentDown();\n void testDifferentParentSameLevel();\n void testInsertionWithDescendants();\n};\n\nvoid DescendantEntitiesProxyModelTest::testInsertionChangeAndRemoval()\n{\n DynamicTreeModel *model = new DynamicTreeModel(this);\n\n DescendantEntitiesProxyModel *proxy = new DescendantEntitiesProxyModel(this);\n proxy->setSourceModel(model);\n\n\n QList<int> ancestorRows;\n\n ModelInsertCommand *ins;\n int max_runs = 2;\n for (int i = 0; i < max_runs; i++)\n {\n ins = new ModelInsertCommand(model, this);\n ins->setAncestorRowNumbers(ancestorRows);\n ins->setStartRow(0);\n ins->setEndRow(9);\n ins->doCommand();\n ancestorRows << 2;\n }\n\n ModelDataChangeCommand *mch;\n mch = new ModelDataChangeCommand(model, this);\n mch->setStartRow(0);\n mch->setEndRow(4);\n mch->doCommand();\n\n \/\/ Item 0-0\n \/\/ Item 1-0\n \/\/ Item 2-0\n \/\/ Item 3-0\n \/\/ Item 4-0\n\n \/\/ Item 0-0\n \/\/ Item 2-0\n \/\/ Item 3-0\n \/\/ Item 1-0\n \/\/ Item 4-0\n\/\/ 2, 3 -1\n\/\/ 1 2\n\n \/\/ Item 0-0\n \/\/ Item 3-0\n \/\/ Item 1-0\n \/\/ Item 2-0\n \/\/ Item 4-0\n\/\/ 3 -2\n\/\/ 1,2 +1\n\n\n\n ModelRemoveCommand *rem;\n rem = new ModelRemoveCommand(model, this);\n rem->setStartRow(2);\n rem->setEndRow(2);\n rem->doCommand();\n\n \/\/ If we get this far, modeltest didn't assert.\n QVERIFY(true);\n}\n\nvoid DescendantEntitiesProxyModelTest::testSameParentDown()\n{\n DynamicTreeModel *model = new DynamicTreeModel(this);\n\n DescendantEntitiesProxyModel *proxy = new DescendantEntitiesProxyModel(this);\n proxy->setSourceModel(model);\n\n QList<int> ancestorRows;\n\n ModelInsertCommand *ins;\n int max_runs = 1;\n for (int i = 0; i < max_runs; i++)\n {\n ins = new ModelInsertCommand(model, this);\n ins->setAncestorRowNumbers(ancestorRows);\n ins->setStartRow(0);\n ins->setEndRow(9);\n ins->doCommand();\n ancestorRows << 2;\n }\n\n ModelMoveCommand *mmc;\n mmc = new ModelMoveCommand(model, this);\n mmc->setStartRow(3);\n mmc->setEndRow(5);\n mmc->setDestRow(8);\n mmc->doCommand();\n\n QVERIFY(true);\n}\n\nvoid DescendantEntitiesProxyModelTest::testSameParentUp()\n{\n DynamicTreeModel *model = new DynamicTreeModel(this);\n\n DescendantEntitiesProxyModel *proxy = new DescendantEntitiesProxyModel(this);\n proxy->setSourceModel(model);\n\n QList<int> ancestorRows;\n\n ModelInsertCommand *ins;\n ins = new ModelInsertCommand(model, this);\n ins->setAncestorRowNumbers(ancestorRows);\n ins->setStartRow(0);\n ins->setEndRow(9);\n ins->doCommand();\n\n ModelMoveCommand *mmc;\n\n mmc = new ModelMoveCommand(model, this);\n mmc->setStartRow(8);\n mmc->setEndRow(8);\n mmc->setDestRow(1);\n mmc->doCommand();\n\n mmc = new ModelMoveCommand(model, this);\n mmc->setStartRow(7);\n mmc->setEndRow(8);\n mmc->setDestRow(1);\n mmc->doCommand();\n\n mmc = new ModelMoveCommand(model, this);\n mmc->setStartRow(6);\n mmc->setEndRow(8);\n mmc->setDestRow(1);\n mmc->doCommand();\n\n mmc = new ModelMoveCommand(model, this);\n mmc->setStartRow(5);\n mmc->setEndRow(8);\n mmc->setDestRow(1);\n mmc->doCommand();\n\n mmc = new ModelMoveCommand(model, this);\n mmc->setStartRow(4);\n mmc->setEndRow(8);\n mmc->setDestRow(1);\n mmc->doCommand();\n\n QVERIFY(true);\n}\n\nvoid DescendantEntitiesProxyModelTest::testDifferentParentUp()\n{\n DynamicTreeModel *model = new DynamicTreeModel(this);\n\n DescendantEntitiesProxyModel *proxy = new DescendantEntitiesProxyModel(this);\n proxy->setSourceModel(model);\n\n QList<int> ancestorRows;\n\n ModelInsertCommand *ins;\n int max_runs = 2;\n for (int i = 0; i < max_runs; i++)\n {\n ins = new ModelInsertCommand(model, this);\n ins->setAncestorRowNumbers(ancestorRows);\n ins->setStartRow(0);\n ins->setEndRow(9);\n ins->doCommand();\n ancestorRows << 2;\n }\n\n ancestorRows.clear();\n ancestorRows << 2;\n\n ModelMoveCommand *mmc;\n mmc = new ModelMoveCommand(model, this);\n mmc->setDestAncestors(ancestorRows);\n mmc->setStartRow(7);\n mmc->setEndRow(8);\n mmc->setDestRow(1);\n mmc->doCommand();\n\n QVERIFY(true);\n}\n\nvoid DescendantEntitiesProxyModelTest::testDifferentParentDown()\n{\n DynamicTreeModel *model = new DynamicTreeModel(this);\n\n DescendantEntitiesProxyModel *proxy = new DescendantEntitiesProxyModel(this);\n proxy->setSourceModel(model);\n\n QList<int> ancestorRows;\n\n ModelInsertCommand *ins;\n int max_runs = 2;\n for (int i = 0; i < max_runs; i++)\n {\n ins = new ModelInsertCommand(model, this);\n ins->setAncestorRowNumbers(ancestorRows);\n ins->setStartRow(0);\n ins->setEndRow(9);\n ins->doCommand();\n ancestorRows << 2;\n }\n\n ancestorRows.clear();\n ancestorRows << 2;\n\n ModelMoveCommand *mmc;\n mmc = new ModelMoveCommand(model, this);\n mmc->setDestAncestors(ancestorRows);\n mmc->setStartRow(6);\n mmc->setEndRow(7);\n mmc->setDestRow(9);\n mmc->doCommand();\n\n QVERIFY(true);\n}\n\nvoid DescendantEntitiesProxyModelTest::testDifferentParentSameLevel()\n{\n DynamicTreeModel *model = new DynamicTreeModel(this);\n\n DescendantEntitiesProxyModel *proxy = new DescendantEntitiesProxyModel(this);\n proxy->setSourceModel(model);\n\n QList<int> ancestorRows;\n\n ModelInsertCommand *ins;\n int max_runs = 2;\n for (int i = 0; i < max_runs; i++)\n {\n ins = new ModelInsertCommand(model, this);\n ins->setAncestorRowNumbers(ancestorRows);\n ins->setStartRow(0);\n ins->setEndRow(9);\n ins->doCommand();\n ancestorRows << 2;\n }\n\n ancestorRows.clear();\n ancestorRows << 2;\n\n ModelMoveCommand *mmc;\n\n mmc = new ModelMoveCommand(model, this);\n mmc->setDestAncestors(ancestorRows);\n mmc->setStartRow(6);\n mmc->setEndRow(7);\n mmc->setDestRow(6);\n mmc->doCommand();\n\n QVERIFY(true);\n\n}\n\nvoid DescendantEntitiesProxyModelTest::testInsertionWithDescendants()\n{\n DynamicTreeModel *model = new DynamicTreeModel(this);\n\n DescendantEntitiesProxyModel *proxy = new DescendantEntitiesProxyModel(this);\n proxy->setSourceModel(model);\n\n \/\/ First insert 4 items to the root.\n ModelInsertCommand *ins = new ModelInsertCommand(model, this);\n ins->setStartRow(0);\n ins->setEndRow(3);\n ins->doCommand();\n\n ModelInsertWithDescendantsCommand *insDesc = new ModelInsertWithDescendantsCommand(model, this);\n QList<QPair<int, int> > descs;\n QPair<int, int> pair;\n pair.first = 1; \/\/ On the first row,\n pair.second = 4; \/\/ insert 4 items.\n descs << pair;\n pair.first = 2; \/\/ Make the 6th new item\n pair.second = 5; \/\/ have 5 descendants itself.\n descs << pair;\n insDesc->setNumDescendants(descs);\n insDesc->doCommand();\n\n QVERIFY(true);\n}\n\n\nQTEST_KDEMAIN(DescendantEntitiesProxyModelTest, GUI)\n#include \"descendantentitiesproxymodeltest.moc\"\n<commit_msg>Port descentent model tests to ProxyModelTest.<commit_after>\/*\n Copyright (c) 2009 Stephen Kelly <steveire@gmail.com>\n\n This library is free software; you can redistribute it and\/or modify it\n under the terms of the GNU Library General Public License as published by\n the Free Software Foundation; either version 2 of the License, or (at your\n option) any later version.\n\n This library is distributed in the hope that it will be useful, but WITHOUT\n ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public\n License for more details.\n\n You should have received a copy of the GNU Library General Public License\n along with this library; see the file COPYING.LIB. If not, write to the\n Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA\n 02110-1301, USA.\n*\/\n\n#include <QtTest>\n#include <QtCore>\n#include <qtest_kde.h>\n#include <qtestevent.h>\n\n#include \"dynamictreemodel.h\"\n#include \"..\/modeltest.h\"\n#include \"..\/descendantentitiesproxymodel.h\"\n#include \"proxymodeltest.h\"\n\n\n\/\/ #include \"fakemonitor.h\"\n\n#include <QTreeView>\n\n#include <kdebug.h>\n\nusing namespace Akonadi;\n\n\nclass DescendantEntitiesProxyModelTest : public ProxyModelTest\n{\n Q_OBJECT\npublic:\n DescendantEntitiesProxyModelTest( QObject *parent = 0 )\n : ProxyModelTest( parent )\n {\n }\n\n protected:\n QVariantList getSignal(SignalType type, int start, int end)\n {\n return ProxyModelTest::getSignal(type, IndexFinder(), start, end);\n }\n\n void signalInsertion(const QString &name, int startRow, int rowsAffected)\n {\n ProxyModelTest::signalInsertion(name, IndexFinder(), startRow, rowsAffected, m_rowCount);\n m_rowCount += rowsAffected;\n }\n\n void signalRemoval(const QString &name, int startRow, int rowsAffected)\n {\n ProxyModelTest::signalRemoval(name, IndexFinder(), startRow, rowsAffected, m_rowCount);\n m_rowCount -= rowsAffected;\n }\n\n PersistentIndexChange getChange(int start, int end, int difference, bool toInvalid = false)\n {\n return ProxyModelTest::getChange(IndexFinder(), start, end, difference, toInvalid);\n }\n\nprivate slots:\n void initTestCase();\n\n \/\/ TODO: Split these into tests in ProxyModelTest and initTestCase\n void testInsertionChangeAndRemoval();\n void testSameParentUp();\n void testSameParentDown();\n void testDifferentParentUp();\n void testDifferentParentDown();\n void testDifferentParentSameLevel();\n void testInsertionWithDescendants();\n\nprivate:\n DescendantEntitiesProxyModel *m_proxyModel;\n IndexFinder m_rootIdxFinder;\n int m_rowCount;\n};\n\n\nvoid DescendantEntitiesProxyModelTest::initTestCase()\n{\n m_proxyModel = new DescendantEntitiesProxyModel(this);\n setProxyModel(m_proxyModel);\n\n QList<QVariantList> signalList;\n QVariantList expected;\n QList<PersistentIndexChange> persistentList;\n m_rowCount = 0;\n int startRow = 0;\n int rowsInserted = 1;\n\n signalInsertion(\"insert01\", startRow, rowsInserted);\n\n startRow = 1;\n rowsInserted = 10;\n signalInsertion(\"insert02\", startRow, rowsInserted);\n\n startRow = 0;\n signalInsertion(\"insert03\", startRow, rowsInserted);\n\n startRow = 21;\n signalInsertion(\"insert04\", startRow, rowsInserted);\n\n startRow = 11;\n signalInsertion(\"insert05\", startRow, rowsInserted);\n\n startRow = 31;\n signalInsertion(\"insert06\", startRow, rowsInserted);\n\n startRow = 21;\n signalInsertion(\"insert07\", startRow, rowsInserted);\n\n int accumulatedChange = 0;\n startRow = 17;\n signalList << getSignal(RowsAboutToBeInserted, startRow, startRow + rowsInserted - 1);\n signalList << getSignal(RowsInserted, startRow, startRow + rowsInserted - 1);\n accumulatedChange += 10;\n\n startRow = 23;\n signalList << getSignal(RowsAboutToBeInserted, startRow, startRow + rowsInserted - 1);\n signalList << getSignal(RowsInserted, startRow, startRow + rowsInserted - 1);\n accumulatedChange += 10;\n\n startRow = 29;\n signalList << getSignal(RowsAboutToBeInserted, startRow, startRow + rowsInserted - 1);\n signalList << getSignal(RowsInserted, startRow, startRow + rowsInserted - 1);\n accumulatedChange += 10;\n persistentList << getChange(17, 17, accumulatedChange);\n\n startRow = 48;\n signalList << getSignal(RowsAboutToBeInserted, startRow, startRow + rowsInserted - 1);\n signalList << getSignal(RowsInserted, startRow, startRow + rowsInserted - 1);\n accumulatedChange += 10;\n persistentList << getChange(18, 18, accumulatedChange);\n\n startRow = 59;\n signalList << getSignal(RowsAboutToBeInserted, startRow, startRow + rowsInserted - 1);\n signalList << getSignal(RowsInserted, startRow, startRow + rowsInserted - 1);\n accumulatedChange += 10;\n\n persistentList << getChange(19, m_rowCount - 1, accumulatedChange);\n\n setExpected(\"insert08\", signalList, persistentList);\n signalList.clear();\n persistentList.clear();\n m_rowCount += accumulatedChange;\n\n startRow = 11;\n int rowsRemoved = 1;\n signalRemoval(\"remove01\", startRow, rowsRemoved);\n\n startRow = 57;\n rowsRemoved = 11;\n signalRemoval(\"remove02\", startRow, rowsRemoved);\n\n startRow = 47;\n rowsRemoved = 1;\n signalRemoval(\"remove03\", startRow, rowsRemoved);\n\n startRow = 55;\n signalRemoval(\"remove04\", startRow, rowsRemoved);\n\n startRow = 50;\n signalRemoval(\"remove05\", startRow, rowsRemoved);\n\n startRow = 47;\n rowsRemoved = 7;\n signalRemoval(\"remove06\", startRow, rowsRemoved);\n\n startRow = 15;\n rowsRemoved = 31;\n signalRemoval(\"remove07\", startRow, rowsRemoved);\n\n}\n\n\nvoid DescendantEntitiesProxyModelTest::testInsertionChangeAndRemoval()\n{\n DynamicTreeModel *model = new DynamicTreeModel(this);\n\n DescendantEntitiesProxyModel *proxy = new DescendantEntitiesProxyModel(this);\n proxy->setSourceModel(model);\n\n\n QList<int> ancestorRows;\n\n ModelInsertCommand *ins;\n int max_runs = 2;\n for (int i = 0; i < max_runs; i++)\n {\n ins = new ModelInsertCommand(model, this);\n ins->setAncestorRowNumbers(ancestorRows);\n ins->setStartRow(0);\n ins->setEndRow(9);\n ins->doCommand();\n ancestorRows << 2;\n }\n\n ModelDataChangeCommand *mch;\n mch = new ModelDataChangeCommand(model, this);\n mch->setStartRow(0);\n mch->setEndRow(4);\n mch->doCommand();\n\n \/\/ Item 0-0\n \/\/ Item 1-0\n \/\/ Item 2-0\n \/\/ Item 3-0\n \/\/ Item 4-0\n\n \/\/ Item 0-0\n \/\/ Item 2-0\n \/\/ Item 3-0\n \/\/ Item 1-0\n \/\/ Item 4-0\n\/\/ 2, 3 -1\n\/\/ 1 2\n\n \/\/ Item 0-0\n \/\/ Item 3-0\n \/\/ Item 1-0\n \/\/ Item 2-0\n \/\/ Item 4-0\n\/\/ 3 -2\n\/\/ 1,2 +1\n\n\n\n ModelRemoveCommand *rem;\n rem = new ModelRemoveCommand(model, this);\n rem->setStartRow(2);\n rem->setEndRow(2);\n rem->doCommand();\n\n \/\/ If we get this far, modeltest didn't assert.\n QVERIFY(true);\n}\n\nvoid DescendantEntitiesProxyModelTest::testSameParentDown()\n{\n DynamicTreeModel *model = new DynamicTreeModel(this);\n\n DescendantEntitiesProxyModel *proxy = new DescendantEntitiesProxyModel(this);\n proxy->setSourceModel(model);\n\n QList<int> ancestorRows;\n\n ModelInsertCommand *ins;\n int max_runs = 1;\n for (int i = 0; i < max_runs; i++)\n {\n ins = new ModelInsertCommand(model, this);\n ins->setAncestorRowNumbers(ancestorRows);\n ins->setStartRow(0);\n ins->setEndRow(9);\n ins->doCommand();\n ancestorRows << 2;\n }\n\n ModelMoveCommand *mmc;\n mmc = new ModelMoveCommand(model, this);\n mmc->setStartRow(3);\n mmc->setEndRow(5);\n mmc->setDestRow(8);\n mmc->doCommand();\n\n QVERIFY(true);\n}\n\nvoid DescendantEntitiesProxyModelTest::testSameParentUp()\n{\n DynamicTreeModel *model = new DynamicTreeModel(this);\n\n DescendantEntitiesProxyModel *proxy = new DescendantEntitiesProxyModel(this);\n proxy->setSourceModel(model);\n\n QList<int> ancestorRows;\n\n ModelInsertCommand *ins;\n ins = new ModelInsertCommand(model, this);\n ins->setAncestorRowNumbers(ancestorRows);\n ins->setStartRow(0);\n ins->setEndRow(9);\n ins->doCommand();\n\n ModelMoveCommand *mmc;\n\n mmc = new ModelMoveCommand(model, this);\n mmc->setStartRow(8);\n mmc->setEndRow(8);\n mmc->setDestRow(1);\n mmc->doCommand();\n\n mmc = new ModelMoveCommand(model, this);\n mmc->setStartRow(7);\n mmc->setEndRow(8);\n mmc->setDestRow(1);\n mmc->doCommand();\n\n mmc = new ModelMoveCommand(model, this);\n mmc->setStartRow(6);\n mmc->setEndRow(8);\n mmc->setDestRow(1);\n mmc->doCommand();\n\n mmc = new ModelMoveCommand(model, this);\n mmc->setStartRow(5);\n mmc->setEndRow(8);\n mmc->setDestRow(1);\n mmc->doCommand();\n\n mmc = new ModelMoveCommand(model, this);\n mmc->setStartRow(4);\n mmc->setEndRow(8);\n mmc->setDestRow(1);\n mmc->doCommand();\n\n QVERIFY(true);\n}\n\nvoid DescendantEntitiesProxyModelTest::testDifferentParentUp()\n{\n DynamicTreeModel *model = new DynamicTreeModel(this);\n\n DescendantEntitiesProxyModel *proxy = new DescendantEntitiesProxyModel(this);\n proxy->setSourceModel(model);\n\n QList<int> ancestorRows;\n\n ModelInsertCommand *ins;\n int max_runs = 2;\n for (int i = 0; i < max_runs; i++)\n {\n ins = new ModelInsertCommand(model, this);\n ins->setAncestorRowNumbers(ancestorRows);\n ins->setStartRow(0);\n ins->setEndRow(9);\n ins->doCommand();\n ancestorRows << 2;\n }\n\n ancestorRows.clear();\n ancestorRows << 2;\n\n ModelMoveCommand *mmc;\n mmc = new ModelMoveCommand(model, this);\n mmc->setDestAncestors(ancestorRows);\n mmc->setStartRow(7);\n mmc->setEndRow(8);\n mmc->setDestRow(1);\n mmc->doCommand();\n\n QVERIFY(true);\n}\n\nvoid DescendantEntitiesProxyModelTest::testDifferentParentDown()\n{\n DynamicTreeModel *model = new DynamicTreeModel(this);\n\n DescendantEntitiesProxyModel *proxy = new DescendantEntitiesProxyModel(this);\n proxy->setSourceModel(model);\n\n QList<int> ancestorRows;\n\n ModelInsertCommand *ins;\n int max_runs = 2;\n for (int i = 0; i < max_runs; i++)\n {\n ins = new ModelInsertCommand(model, this);\n ins->setAncestorRowNumbers(ancestorRows);\n ins->setStartRow(0);\n ins->setEndRow(9);\n ins->doCommand();\n ancestorRows << 2;\n }\n\n ancestorRows.clear();\n ancestorRows << 2;\n\n ModelMoveCommand *mmc;\n mmc = new ModelMoveCommand(model, this);\n mmc->setDestAncestors(ancestorRows);\n mmc->setStartRow(6);\n mmc->setEndRow(7);\n mmc->setDestRow(9);\n mmc->doCommand();\n\n QVERIFY(true);\n}\n\nvoid DescendantEntitiesProxyModelTest::testDifferentParentSameLevel()\n{\n DynamicTreeModel *model = new DynamicTreeModel(this);\n\n DescendantEntitiesProxyModel *proxy = new DescendantEntitiesProxyModel(this);\n proxy->setSourceModel(model);\n\n QList<int> ancestorRows;\n\n ModelInsertCommand *ins;\n int max_runs = 2;\n for (int i = 0; i < max_runs; i++)\n {\n ins = new ModelInsertCommand(model, this);\n ins->setAncestorRowNumbers(ancestorRows);\n ins->setStartRow(0);\n ins->setEndRow(9);\n ins->doCommand();\n ancestorRows << 2;\n }\n\n ancestorRows.clear();\n ancestorRows << 2;\n\n ModelMoveCommand *mmc;\n\n mmc = new ModelMoveCommand(model, this);\n mmc->setDestAncestors(ancestorRows);\n mmc->setStartRow(6);\n mmc->setEndRow(7);\n mmc->setDestRow(6);\n mmc->doCommand();\n\n QVERIFY(true);\n\n}\n\nvoid DescendantEntitiesProxyModelTest::testInsertionWithDescendants()\n{\n DynamicTreeModel *model = new DynamicTreeModel(this);\n\n DescendantEntitiesProxyModel *proxy = new DescendantEntitiesProxyModel(this);\n proxy->setSourceModel(model);\n\n \/\/ First insert 4 items to the root.\n ModelInsertCommand *ins = new ModelInsertCommand(model, this);\n ins->setStartRow(0);\n ins->setEndRow(3);\n ins->doCommand();\n\n ModelInsertWithDescendantsCommand *insDesc = new ModelInsertWithDescendantsCommand(model, this);\n QList<QPair<int, int> > descs;\n QPair<int, int> pair;\n pair.first = 1; \/\/ On the first row,\n pair.second = 4; \/\/ insert 4 items.\n descs << pair;\n pair.first = 2; \/\/ Make the 6th new item\n pair.second = 5; \/\/ have 5 descendants itself.\n descs << pair;\n insDesc->setNumDescendants(descs);\n insDesc->doCommand();\n\n QVERIFY(true);\n}\n\n\nQTEST_KDEMAIN(DescendantEntitiesProxyModelTest, GUI)\n#include \"descendantentitiesproxymodeltest.moc\"\n<|endoftext|>"} {"text":"<commit_before>\/*\n * gaussian_smoother.cc\n *\n * Copyright (C) (2016) STFC Rutherford Appleton Laboratory, UK.\n *\n * Author: David Waterman.\n *\n * This code is distributed under the BSD license, a copy of which is\n * included in the root directory of this package.\n *\/\n#include <boost\/python.hpp>\n#include <boost\/python\/def.hpp>\n#include \"..\/gaussian_smoother.h\"\n\nusing namespace boost::python;\n\nnamespace dials { namespace refinement { namespace boost_python {\n\n void export_gaussian_smoother()\n {\n class_<GaussianSmoother>(\"GaussianSmoother\", no_init)\n .def(init< vec2<double>,\n std::size_t >((\n arg(\"x_range\"),\n arg(\"num_intervals\"))))\n .def(\"num_values\", &GaussianSmoother::num_values)\n .def(\"num_samples\", &GaussianSmoother::num_samples)\n .def(\"num_average\", &GaussianSmoother::num_average)\n .def(\"sigma\", &GaussianSmoother::sigma)\n .def(\"spacing\", &GaussianSmoother::spacing)\n .def(\"positions\", &GaussianSmoother::positions)\n .def(\"value_weight\", &GaussianSmoother::value_weight)\n .def(\"multi_value_weight\", &GaussianSmoother::multi_value_weight)\n ;\n\n class_<SingleValueWeights>(\"SingleValueWeights\", no_init)\n .def(\"get_value\", &SingleValueWeights::get_value)\n .def(\"get_weight\", &SingleValueWeights::get_weight)\n .def(\"get_sumweight\", &SingleValueWeights::get_sumweight)\n ;\n\n class_<MultiValueWeights>(\"MultiValueWeights\", no_init)\n .def(\"get_value\", &MultiValueWeights::get_value)\n .def(\"get_weight\", &MultiValueWeights::get_weight)\n .def(\"get_sumweight\", &MultiValueWeights::get_sumweight)\n ;\n }\n\n}}} \/\/ namespace dials::refinement::boost_python\n<commit_msg>Expose GaussianSmoother.set_smoothing in Python for JBE<commit_after>\/*\n * gaussian_smoother.cc\n *\n * Copyright (C) (2016) STFC Rutherford Appleton Laboratory, UK.\n *\n * Author: David Waterman.\n *\n * This code is distributed under the BSD license, a copy of which is\n * included in the root directory of this package.\n *\/\n#include <boost\/python.hpp>\n#include <boost\/python\/def.hpp>\n#include \"..\/gaussian_smoother.h\"\n\nusing namespace boost::python;\n\nnamespace dials { namespace refinement { namespace boost_python {\n\n void export_gaussian_smoother()\n {\n class_<GaussianSmoother>(\"GaussianSmoother\", no_init)\n .def(init< vec2<double>,\n std::size_t >((\n arg(\"x_range\"),\n arg(\"num_intervals\"))))\n .def(\"set_smoothing\", &GaussianSmoother::set_smoothing)\n .def(\"num_values\", &GaussianSmoother::num_values)\n .def(\"num_samples\", &GaussianSmoother::num_samples)\n .def(\"num_average\", &GaussianSmoother::num_average)\n .def(\"sigma\", &GaussianSmoother::sigma)\n .def(\"spacing\", &GaussianSmoother::spacing)\n .def(\"positions\", &GaussianSmoother::positions)\n .def(\"value_weight\", &GaussianSmoother::value_weight)\n .def(\"multi_value_weight\", &GaussianSmoother::multi_value_weight)\n ;\n\n class_<SingleValueWeights>(\"SingleValueWeights\", no_init)\n .def(\"get_value\", &SingleValueWeights::get_value)\n .def(\"get_weight\", &SingleValueWeights::get_weight)\n .def(\"get_sumweight\", &SingleValueWeights::get_sumweight)\n ;\n\n class_<MultiValueWeights>(\"MultiValueWeights\", no_init)\n .def(\"get_value\", &MultiValueWeights::get_value)\n .def(\"get_weight\", &MultiValueWeights::get_weight)\n .def(\"get_sumweight\", &MultiValueWeights::get_sumweight)\n ;\n }\n\n}}} \/\/ namespace dials::refinement::boost_python\n<|endoftext|>"} {"text":"<commit_before>\/*\n-----------------------------------------------------------------------------\nThis source file is part of OGRE\n (Object-oriented Graphics Rendering Engine)\nFor the latest info, see http:\/\/www.ogre3d.org\/\n\nCopyright (c) 2000-2014 Torus Knot Software Ltd\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n-----------------------------------------------------------------------------\n*\/\n#include \"OgreGLES2Prerequisites.h\"\n#include \"OgreGpuProgram.h\"\n#include \"OgreHighLevelGpuProgramManager.h\"\n#include \"OgreLogManager.h\"\n#include \"OgreRoot.h\"\n#include \"OgreStringConverter.h\"\n#include \"OgreGLUtil.h\"\n#include \"OgreGLES2RenderSystem.h\"\n#include \"OgreGLNativeSupport.h\"\n\n#include \"OgreGLSLESProgram.h\"\n#include \"OgreGLSLESProgramManager.h\"\n#include \"OgreGLSLPreprocessor.h\"\n\nnamespace Ogre {\n \/\/-----------------------------------------------------------------------\n#if !OGRE_NO_GLES2_GLSL_OPTIMISER\n GLSLESProgram::CmdOptimisation GLSLESProgram::msCmdOptimisation;\n#endif\n \/\/-----------------------------------------------------------------------\n \/\/-----------------------------------------------------------------------\n GLSLESProgram::GLSLESProgram(ResourceManager* creator, \n const String& name, ResourceHandle handle,\n const String& group, bool isManual, ManualResourceLoader* loader)\n : GLSLShaderCommon(creator, name, handle, group, isManual, loader)\n , mGLShaderHandle(0)\n , mGLProgramHandle(0)\n#if !OGRE_NO_GLES2_GLSL_OPTIMISER\n , mIsOptimised(false)\n , mOptimiserEnabled(false)\n#endif\n {\n if (createParamDictionary(\"GLSLESProgram\"))\n {\n setupBaseParamDictionary();\n ParamDictionary* dict = getParamDictionary();\n\n dict->addParameter(ParameterDef(\"preprocessor_defines\", \n \"Preprocessor defines use to compile the program.\",\n PT_STRING),&msCmdPreprocessorDefines);\n#if !OGRE_NO_GLES2_GLSL_OPTIMISER\n dict->addParameter(ParameterDef(\"use_optimiser\", \n \"Should the GLSL optimiser be used. Default is false.\",\n PT_BOOL),&msCmdOptimisation);\n#endif\n }\n \/\/ Manually assign language now since we use it immediately\n mSyntaxCode = \"glsles\";\n\n \/\/ There is nothing to load\n mLoadFromFile = false;\n }\n \/\/---------------------------------------------------------------------------\n GLSLESProgram::~GLSLESProgram()\n {\n \/\/ Have to call this here reather than in Resource destructor\n \/\/ since calling virtual methods in base destructors causes crash\n if (isLoaded())\n {\n unload();\n }\n else\n {\n unloadHighLevel();\n }\n }\n \/\/---------------------------------------------------------------------------\n#if OGRE_PLATFORM == OGRE_PLATFORM_ANDROID || OGRE_PLATFORM == OGRE_PLATFORM_EMSCRIPTEN\n void GLSLESProgram::notifyOnContextLost()\n {\n unloadHighLevelImpl();\n }\n\n void GLSLESProgram::notifyOnContextReset()\n {\n try {\n compile(true);\n }\n catch(Exception& e)\n {\n \/\/ we already compiled this once, this should not happen\n LogManager::getSingleton().stream(LML_WARNING) << e.what();\n }\n }\n#endif\n GLuint GLSLESProgram::createGLProgramHandle() {\n if(!Root::getSingleton().getRenderSystem()->getCapabilities()->hasCapability(RSC_SEPARATE_SHADER_OBJECTS))\n return 0;\n\n if (mGLProgramHandle)\n return mGLProgramHandle;\n\n OGRE_CHECK_GL_ERROR(mGLProgramHandle = glCreateProgram());\n if(Root::getSingleton().getRenderSystem()->getCapabilities()->hasCapability(RSC_DEBUG))\n {\n glLabelObjectEXT(GL_PROGRAM_OBJECT_EXT, mGLProgramHandle, 0, mName.c_str());\n }\n\n return mGLProgramHandle;\n }\n\n bool GLSLESProgram::compile(bool checkErrors)\n {\n \/\/ Only create a shader object if glsl es is supported\n if (isSupported())\n {\n \/\/ Create shader object\n GLenum shaderType = 0x0000;\n if (mType == GPT_VERTEX_PROGRAM)\n {\n shaderType = GL_VERTEX_SHADER;\n }\n else if (mType == GPT_FRAGMENT_PROGRAM)\n {\n shaderType = GL_FRAGMENT_SHADER;\n }\n OGRE_CHECK_GL_ERROR(mGLShaderHandle = glCreateShader(shaderType));\n\n if(Root::getSingleton().getRenderSystem()->getCapabilities()->hasCapability(RSC_DEBUG))\n {\n glLabelObjectEXT(GL_SHADER_OBJECT_EXT, mGLShaderHandle, 0, mName.c_str());\n }\n\n createGLProgramHandle();\n }\n\n const RenderSystemCapabilities* caps = Root::getSingleton().getRenderSystem()->getCapabilities();\n\n \/\/ Add preprocessor extras and main source\n if (!mSource.empty())\n {\n \/\/ Fix up the source in case someone forgot to redeclare gl_Position\n if (caps->hasCapability(RSC_GLSL_SSO_REDECLARE) && mType == GPT_VERTEX_PROGRAM)\n {\n size_t versionPos = mSource.find(\"#version\");\n int shaderVersion = StringConverter::parseInt(mSource.substr(versionPos+9, 3));\n size_t belowVersionPos = mSource.find('\\n', versionPos) + 1;\n\n if(shaderVersion >= 300) {\n \/\/ Check that it's missing and that this shader has a main function, ie. not a child shader.\n if(mSource.find(\"out highp vec4 gl_Position\") == String::npos)\n {\n mSource.insert(belowVersionPos, \"out highp vec4 gl_Position;\\nout highp float gl_PointSize;\\n\");\n }\n if(mSource.find(\"#extension GL_EXT_separate_shader_objects : require\") == String::npos)\n {\n mSource.insert(belowVersionPos, \"#extension GL_EXT_separate_shader_objects : require\\n\");\n }\n }\n }\n \n#if !OGRE_NO_GLES2_GLSL_OPTIMISER\n const char *source = (getOptimiserEnabled() && getIsOptimised()) ? mOptimisedSource.c_str() : mSource.c_str();\n#else\n const char *source = mSource.c_str();\n#endif\n\n OGRE_CHECK_GL_ERROR(glShaderSource(mGLShaderHandle, 1, &source, NULL));\n }\n\n OGRE_CHECK_GL_ERROR(glCompileShader(mGLShaderHandle));\n\n \/\/ Check for compile errors\n int compiled;\n OGRE_CHECK_GL_ERROR(glGetShaderiv(mGLShaderHandle, GL_COMPILE_STATUS, &compiled));\n\n if(!checkErrors)\n return compiled == 1;\n\n if(!compiled && caps->getVendor() == GPU_QUALCOMM)\n {\n String message = GLSLES::getObjectInfo(mGLShaderHandle);\n checkAndFixInvalidDefaultPrecisionError(message);\n OGRE_CHECK_GL_ERROR(glGetShaderiv(mGLShaderHandle, GL_COMPILE_STATUS, &compiled));\n }\n\n String compileInfo = GLSLES::getObjectInfo(mGLShaderHandle);\n\n if (!compiled)\n OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, getResourceLogName() + \" \" + compileInfo, \"compile\");\n\n \/\/ probably we have warnings\n if (!compileInfo.empty())\n LogManager::getSingleton().stream(LML_WARNING) << getResourceLogName() << \" \" << compileInfo;\n\n return compiled == 1;\n }\n\n#if !OGRE_NO_GLES2_GLSL_OPTIMISER \n \/\/-----------------------------------------------------------------------\n void GLSLESProgram::setOptimiserEnabled(bool enabled) \n { \n if(mOptimiserEnabled != enabled && mOptimiserEnabled && mCompiled == 1)\n {\n OGRE_CHECK_GL_ERROR(glDeleteShader(mGLShaderHandle));\n\n if(Root::getSingleton().getRenderSystem()->getCapabilities()->hasCapability(RSC_SEPARATE_SHADER_OBJECTS))\n {\n OGRE_CHECK_GL_ERROR(glDeleteProgram(mGLProgramHandle));\n }\n \n mGLShaderHandle = 0;\n mGLProgramHandle = 0;\n mCompiled = 0;\n }\n mOptimiserEnabled = enabled; \n }\n#endif\n \/\/-----------------------------------------------------------------------\n void GLSLESProgram::createLowLevelImpl(void)\n {\n }\n \/\/-----------------------------------------------------------------------\n void GLSLESProgram::unloadHighLevelImpl(void)\n {\n if (isSupported())\n {\n\/\/ LogManager::getSingleton().logMessage(\"Deleting shader \" + StringConverter::toString(mGLShaderHandle) +\n\/\/ \" and program \" + StringConverter::toString(mGLProgramHandle));\n OGRE_CHECK_GL_ERROR(glDeleteShader(mGLShaderHandle));\n\n if(Root::getSingleton().getRenderSystem()->getCapabilities()->hasCapability(RSC_SEPARATE_SHADER_OBJECTS))\n {\n OGRE_CHECK_GL_ERROR(glDeleteProgram(mGLProgramHandle));\n }\n \/\/ destroy all programs using this shader\n GLSLESProgramManager::getSingletonPtr()->destroyAllByShader(this);\n\n \n mGLShaderHandle = 0;\n mGLProgramHandle = 0;\n mLinked = 0;\n }\n }\n \/\/-----------------------------------------------------------------------\n void GLSLESProgram::buildConstantDefinitions() const\n {\n \/\/ We need an accurate list of all the uniforms in the shader, but we\n \/\/ can't get at them until we link all the shaders into a program object.\n\n \/\/ Therefore instead, parse the source code manually and extract the uniforms\n createParameterMappingStructures(true);\n GLSLESProgramManager::getSingleton().extractUniformsFromGLSL(mSource, *mConstantDefs, mName);\n }\n\n \/\/-----------------------------------------------------------------------\n#if !OGRE_NO_GLES2_GLSL_OPTIMISER\n String GLSLESProgram::CmdOptimisation::doGet(const void *target) const\n {\n return StringConverter::toString(static_cast<const GLSLESProgram*>(target)->getOptimiserEnabled());\n }\n void GLSLESProgram::CmdOptimisation::doSet(void *target, const String& val)\n {\n static_cast<GLSLESProgram*>(target)->setOptimiserEnabled(StringConverter::parseBool(val));\n }\n#endif\n \/\/-----------------------------------------------------------------------\n void GLSLESProgram::attachToProgramObject( const GLuint programObject )\n {\n\/\/ LogManager::getSingleton().logMessage(\"Attaching shader \" + StringConverter::toString(mGLShaderHandle) +\n\/\/ \" to program \" + StringConverter::toString(programObject));\n OGRE_CHECK_GL_ERROR(glAttachShader(programObject, mGLShaderHandle));\n }\n \/\/-----------------------------------------------------------------------\n void GLSLESProgram::detachFromProgramObject( const GLuint programObject )\n {\n\/\/ LogManager::getSingleton().logMessage(\"Detaching shader \" + StringConverter::toString(mGLShaderHandle) +\n\/\/ \" to program \" + StringConverter::toString(programObject));\n OGRE_CHECK_GL_ERROR(glDetachShader(programObject, mGLShaderHandle));\n }\n\n \/\/-----------------------------------------------------------------------\n const String& GLSLESProgram::getLanguage(void) const\n {\n static const String language = \"glsles\";\n\n return language;\n }\n \/\/-----------------------------------------------------------------------\n Ogre::GpuProgramParametersSharedPtr GLSLESProgram::createParameters( void )\n {\n GpuProgramParametersSharedPtr params = HighLevelGpuProgram::createParameters();\n params->setTransposeMatrices(true);\n return params;\n }\n \/\/-----------------------------------------------------------------------\n void GLSLESProgram::checkAndFixInvalidDefaultPrecisionError( String &message )\n {\n String precisionQualifierErrorString = \": 'Default Precision Qualifier' : invalid type Type for default precision qualifier can be only float or int\";\n std::vector< String > linesOfSource = StringUtil::split(mSource, \"\\n\");\n if( message.find(precisionQualifierErrorString) != String::npos )\n {\n LogManager::getSingleton().logMessage(\"Fixing invalid type Type for default precision qualifier by deleting bad lines the re-compiling\");\n\n \/\/ remove relevant lines from source\n std::vector< String > errors = StringUtil::split(message, \"\\n\");\n\n \/\/ going from the end so when we delete a line the numbers of the lines before will not change\n for(int i = static_cast<int>(errors.size()) - 1 ; i != -1 ; i--)\n {\n String & curError = errors[i];\n size_t foundPos = curError.find(precisionQualifierErrorString);\n if(foundPos != String::npos)\n {\n String lineNumber = curError.substr(0, foundPos);\n size_t posOfStartOfNumber = lineNumber.find_last_of(':');\n if (posOfStartOfNumber != String::npos)\n {\n lineNumber = lineNumber.substr(posOfStartOfNumber + 1, lineNumber.size() - (posOfStartOfNumber + 1));\n if (StringConverter::isNumber(lineNumber))\n {\n int iLineNumber = StringConverter::parseInt(lineNumber);\n linesOfSource.erase(linesOfSource.begin() + iLineNumber - 1);\n }\n }\n }\n } \n \/\/ rebuild source\n StringStream newSource; \n for(size_t i = 0; i < linesOfSource.size() ; i++)\n {\n newSource << linesOfSource[i] << \"\\n\";\n }\n mSource = newSource.str();\n\n const char *source = mSource.c_str();\n OGRE_CHECK_GL_ERROR(glShaderSource(mGLShaderHandle, 1, &source, NULL));\n\n if (compile())\n {\n LogManager::getSingleton().logMessage(\"The removing of the lines fixed the invalid type Type for default precision qualifier error.\");\n }\n else\n {\n LogManager::getSingleton().logMessage(\"The removing of the lines didn't help.\");\n }\n }\n }\n\n \/\/-----------------------------------------------------------------------------\n void GLSLESProgram::bindProgram(void)\n {\n \/\/ Tell the Link Program Manager what shader is to become active\n switch (mType)\n {\n case GPT_VERTEX_PROGRAM:\n GLSLESProgramManager::getSingleton().setActiveVertexShader( this );\n break;\n case GPT_FRAGMENT_PROGRAM:\n GLSLESProgramManager::getSingleton().setActiveFragmentShader( this );\n break;\n case GPT_GEOMETRY_PROGRAM:\n default:\n break;\n }\n }\n\n \/\/-----------------------------------------------------------------------------\n void GLSLESProgram::unbindProgram(void)\n {\n \/\/ Tell the Link Program Manager what shader is to become inactive\n if (mType == GPT_VERTEX_PROGRAM)\n {\n GLSLESProgramManager::getSingleton().setActiveVertexShader( NULL );\n }\n else if (mType == GPT_FRAGMENT_PROGRAM)\n {\n GLSLESProgramManager::getSingleton().setActiveFragmentShader( NULL );\n }\n }\n\n \/\/-----------------------------------------------------------------------------\n void GLSLESProgram::bindProgramParameters(GpuProgramParametersSharedPtr params, uint16 mask)\n {\n \/\/ Link can throw exceptions, ignore them at this point\n try\n {\n \/\/ Activate the link program object\n GLSLESProgramCommon* linkProgram = GLSLESProgramManager::getSingleton().getActiveProgram();\n \/\/ Pass on parameters from params to program object uniforms\n linkProgram->updateUniforms(params, mask, mType);\n\n }\n catch (Exception& e) {}\n }\n\n \/\/-----------------------------------------------------------------------------\n void GLSLESProgram::bindProgramSharedParameters(GpuProgramParametersSharedPtr params, uint16 mask)\n {\n \/\/ Link can throw exceptions, ignore them at this point\n try\n {\n \/\/ Activate the link program object\n GLSLESProgramCommon* linkProgram = GLSLESProgramManager::getSingleton().getActiveProgram();\n \/\/ Pass on parameters from params to program object uniforms\n linkProgram->updateUniformBlocks(params, mask, mType);\n }\n catch (Exception& e) {}\n }\n\n \/\/-----------------------------------------------------------------------------\n void GLSLESProgram::bindProgramPassIterationParameters(GpuProgramParametersSharedPtr params)\n {\n \/\/ Activate the link program object\n GLSLESProgramCommon* linkProgram = GLSLESProgramManager::getSingleton().getActiveProgram();\n \/\/ Pass on parameters from params to program object uniforms\n linkProgram->updatePassIterationUniforms( params );\n }\n\n \/\/-----------------------------------------------------------------------------\n size_t GLSLESProgram::calculateSize(void) const\n {\n size_t memSize = 0;\n\n \/\/ Delegate Names\n memSize += sizeof(GLuint);\n memSize += sizeof(GLenum);\n memSize += GpuProgram::calculateSize();\n\n return memSize;\n }\n}\n<commit_msg>GLES2: auto insert precision qualifier into fragment shaders<commit_after>\/*\n-----------------------------------------------------------------------------\nThis source file is part of OGRE\n (Object-oriented Graphics Rendering Engine)\nFor the latest info, see http:\/\/www.ogre3d.org\/\n\nCopyright (c) 2000-2014 Torus Knot Software Ltd\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n-----------------------------------------------------------------------------\n*\/\n#include \"OgreGLES2Prerequisites.h\"\n#include \"OgreGpuProgram.h\"\n#include \"OgreHighLevelGpuProgramManager.h\"\n#include \"OgreLogManager.h\"\n#include \"OgreRoot.h\"\n#include \"OgreStringConverter.h\"\n#include \"OgreGLUtil.h\"\n#include \"OgreGLES2RenderSystem.h\"\n#include \"OgreGLNativeSupport.h\"\n\n#include \"OgreGLSLESProgram.h\"\n#include \"OgreGLSLESProgramManager.h\"\n#include \"OgreGLSLPreprocessor.h\"\n\nnamespace Ogre {\n \/\/-----------------------------------------------------------------------\n#if !OGRE_NO_GLES2_GLSL_OPTIMISER\n GLSLESProgram::CmdOptimisation GLSLESProgram::msCmdOptimisation;\n#endif\n \/\/-----------------------------------------------------------------------\n \/\/-----------------------------------------------------------------------\n GLSLESProgram::GLSLESProgram(ResourceManager* creator, \n const String& name, ResourceHandle handle,\n const String& group, bool isManual, ManualResourceLoader* loader)\n : GLSLShaderCommon(creator, name, handle, group, isManual, loader)\n , mGLShaderHandle(0)\n , mGLProgramHandle(0)\n#if !OGRE_NO_GLES2_GLSL_OPTIMISER\n , mIsOptimised(false)\n , mOptimiserEnabled(false)\n#endif\n {\n if (createParamDictionary(\"GLSLESProgram\"))\n {\n setupBaseParamDictionary();\n ParamDictionary* dict = getParamDictionary();\n\n dict->addParameter(ParameterDef(\"preprocessor_defines\", \n \"Preprocessor defines use to compile the program.\",\n PT_STRING),&msCmdPreprocessorDefines);\n#if !OGRE_NO_GLES2_GLSL_OPTIMISER\n dict->addParameter(ParameterDef(\"use_optimiser\", \n \"Should the GLSL optimiser be used. Default is false.\",\n PT_BOOL),&msCmdOptimisation);\n#endif\n }\n \/\/ Manually assign language now since we use it immediately\n mSyntaxCode = \"glsles\";\n\n \/\/ There is nothing to load\n mLoadFromFile = false;\n }\n \/\/---------------------------------------------------------------------------\n GLSLESProgram::~GLSLESProgram()\n {\n \/\/ Have to call this here reather than in Resource destructor\n \/\/ since calling virtual methods in base destructors causes crash\n if (isLoaded())\n {\n unload();\n }\n else\n {\n unloadHighLevel();\n }\n }\n \/\/---------------------------------------------------------------------------\n#if OGRE_PLATFORM == OGRE_PLATFORM_ANDROID || OGRE_PLATFORM == OGRE_PLATFORM_EMSCRIPTEN\n void GLSLESProgram::notifyOnContextLost()\n {\n unloadHighLevelImpl();\n }\n\n void GLSLESProgram::notifyOnContextReset()\n {\n try {\n compile(true);\n }\n catch(Exception& e)\n {\n \/\/ we already compiled this once, this should not happen\n LogManager::getSingleton().stream(LML_WARNING) << e.what();\n }\n }\n#endif\n GLuint GLSLESProgram::createGLProgramHandle() {\n if(!Root::getSingleton().getRenderSystem()->getCapabilities()->hasCapability(RSC_SEPARATE_SHADER_OBJECTS))\n return 0;\n\n if (mGLProgramHandle)\n return mGLProgramHandle;\n\n OGRE_CHECK_GL_ERROR(mGLProgramHandle = glCreateProgram());\n if(Root::getSingleton().getRenderSystem()->getCapabilities()->hasCapability(RSC_DEBUG))\n {\n glLabelObjectEXT(GL_PROGRAM_OBJECT_EXT, mGLProgramHandle, 0, mName.c_str());\n }\n\n return mGLProgramHandle;\n }\n\n bool GLSLESProgram::compile(bool checkErrors)\n {\n \/\/ Only create a shader object if glsl es is supported\n if (isSupported())\n {\n \/\/ Create shader object\n GLenum shaderType = 0x0000;\n if (mType == GPT_VERTEX_PROGRAM)\n {\n shaderType = GL_VERTEX_SHADER;\n }\n else if (mType == GPT_FRAGMENT_PROGRAM)\n {\n shaderType = GL_FRAGMENT_SHADER;\n }\n OGRE_CHECK_GL_ERROR(mGLShaderHandle = glCreateShader(shaderType));\n\n if(Root::getSingleton().getRenderSystem()->getCapabilities()->hasCapability(RSC_DEBUG))\n {\n glLabelObjectEXT(GL_SHADER_OBJECT_EXT, mGLShaderHandle, 0, mName.c_str());\n }\n\n createGLProgramHandle();\n }\n\n const RenderSystemCapabilities* caps = Root::getSingleton().getRenderSystem()->getCapabilities();\n\n \/\/ Add preprocessor extras and main source\n if (!mSource.empty())\n {\n size_t versionPos = mSource.find(\"#version\");\n int shaderVersion = 100;\n size_t belowVersionPos = 0;\n\n if(versionPos != String::npos)\n {\n shaderVersion = StringConverter::parseInt(mSource.substr(versionPos+9, 3));\n belowVersionPos = mSource.find('\\n', versionPos) + 1;\n }\n\n \/\/ insert precision qualifier for improved compatibility\n if(mType == GPT_FRAGMENT_PROGRAM && mSource.find(\"precision \") == String::npos)\n mSource.insert(belowVersionPos, \"precision mediump float;\\n\");\n\n \/\/ Fix up the source in case someone forgot to redeclare gl_Position\n if (caps->hasCapability(RSC_GLSL_SSO_REDECLARE) && mType == GPT_VERTEX_PROGRAM)\n {\n if(shaderVersion >= 300) {\n \/\/ Check that it's missing and that this shader has a main function, ie. not a child shader.\n if(mSource.find(\"out highp vec4 gl_Position\") == String::npos)\n {\n mSource.insert(belowVersionPos, \"out highp vec4 gl_Position;\\nout highp float gl_PointSize;\\n\");\n }\n if(mSource.find(\"#extension GL_EXT_separate_shader_objects : require\") == String::npos)\n {\n mSource.insert(belowVersionPos, \"#extension GL_EXT_separate_shader_objects : require\\n\");\n }\n }\n }\n \n#if !OGRE_NO_GLES2_GLSL_OPTIMISER\n const char *source = (getOptimiserEnabled() && getIsOptimised()) ? mOptimisedSource.c_str() : mSource.c_str();\n#else\n const char *source = mSource.c_str();\n#endif\n\n OGRE_CHECK_GL_ERROR(glShaderSource(mGLShaderHandle, 1, &source, NULL));\n }\n\n OGRE_CHECK_GL_ERROR(glCompileShader(mGLShaderHandle));\n\n \/\/ Check for compile errors\n int compiled;\n OGRE_CHECK_GL_ERROR(glGetShaderiv(mGLShaderHandle, GL_COMPILE_STATUS, &compiled));\n\n if(!checkErrors)\n return compiled == 1;\n\n if(!compiled && caps->getVendor() == GPU_QUALCOMM)\n {\n String message = GLSLES::getObjectInfo(mGLShaderHandle);\n checkAndFixInvalidDefaultPrecisionError(message);\n OGRE_CHECK_GL_ERROR(glGetShaderiv(mGLShaderHandle, GL_COMPILE_STATUS, &compiled));\n }\n\n String compileInfo = GLSLES::getObjectInfo(mGLShaderHandle);\n\n if (!compiled)\n OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, getResourceLogName() + \" \" + compileInfo, \"compile\");\n\n \/\/ probably we have warnings\n if (!compileInfo.empty())\n LogManager::getSingleton().stream(LML_WARNING) << getResourceLogName() << \" \" << compileInfo;\n\n return compiled == 1;\n }\n\n#if !OGRE_NO_GLES2_GLSL_OPTIMISER \n \/\/-----------------------------------------------------------------------\n void GLSLESProgram::setOptimiserEnabled(bool enabled) \n { \n if(mOptimiserEnabled != enabled && mOptimiserEnabled && mCompiled == 1)\n {\n OGRE_CHECK_GL_ERROR(glDeleteShader(mGLShaderHandle));\n\n if(Root::getSingleton().getRenderSystem()->getCapabilities()->hasCapability(RSC_SEPARATE_SHADER_OBJECTS))\n {\n OGRE_CHECK_GL_ERROR(glDeleteProgram(mGLProgramHandle));\n }\n \n mGLShaderHandle = 0;\n mGLProgramHandle = 0;\n mCompiled = 0;\n }\n mOptimiserEnabled = enabled; \n }\n#endif\n \/\/-----------------------------------------------------------------------\n void GLSLESProgram::createLowLevelImpl(void)\n {\n }\n \/\/-----------------------------------------------------------------------\n void GLSLESProgram::unloadHighLevelImpl(void)\n {\n if (isSupported())\n {\n\/\/ LogManager::getSingleton().logMessage(\"Deleting shader \" + StringConverter::toString(mGLShaderHandle) +\n\/\/ \" and program \" + StringConverter::toString(mGLProgramHandle));\n OGRE_CHECK_GL_ERROR(glDeleteShader(mGLShaderHandle));\n\n if(Root::getSingleton().getRenderSystem()->getCapabilities()->hasCapability(RSC_SEPARATE_SHADER_OBJECTS))\n {\n OGRE_CHECK_GL_ERROR(glDeleteProgram(mGLProgramHandle));\n }\n \/\/ destroy all programs using this shader\n GLSLESProgramManager::getSingletonPtr()->destroyAllByShader(this);\n\n \n mGLShaderHandle = 0;\n mGLProgramHandle = 0;\n mLinked = 0;\n }\n }\n \/\/-----------------------------------------------------------------------\n void GLSLESProgram::buildConstantDefinitions() const\n {\n \/\/ We need an accurate list of all the uniforms in the shader, but we\n \/\/ can't get at them until we link all the shaders into a program object.\n\n \/\/ Therefore instead, parse the source code manually and extract the uniforms\n createParameterMappingStructures(true);\n GLSLESProgramManager::getSingleton().extractUniformsFromGLSL(mSource, *mConstantDefs, mName);\n }\n\n \/\/-----------------------------------------------------------------------\n#if !OGRE_NO_GLES2_GLSL_OPTIMISER\n String GLSLESProgram::CmdOptimisation::doGet(const void *target) const\n {\n return StringConverter::toString(static_cast<const GLSLESProgram*>(target)->getOptimiserEnabled());\n }\n void GLSLESProgram::CmdOptimisation::doSet(void *target, const String& val)\n {\n static_cast<GLSLESProgram*>(target)->setOptimiserEnabled(StringConverter::parseBool(val));\n }\n#endif\n \/\/-----------------------------------------------------------------------\n void GLSLESProgram::attachToProgramObject( const GLuint programObject )\n {\n\/\/ LogManager::getSingleton().logMessage(\"Attaching shader \" + StringConverter::toString(mGLShaderHandle) +\n\/\/ \" to program \" + StringConverter::toString(programObject));\n OGRE_CHECK_GL_ERROR(glAttachShader(programObject, mGLShaderHandle));\n }\n \/\/-----------------------------------------------------------------------\n void GLSLESProgram::detachFromProgramObject( const GLuint programObject )\n {\n\/\/ LogManager::getSingleton().logMessage(\"Detaching shader \" + StringConverter::toString(mGLShaderHandle) +\n\/\/ \" to program \" + StringConverter::toString(programObject));\n OGRE_CHECK_GL_ERROR(glDetachShader(programObject, mGLShaderHandle));\n }\n\n \/\/-----------------------------------------------------------------------\n const String& GLSLESProgram::getLanguage(void) const\n {\n static const String language = \"glsles\";\n\n return language;\n }\n \/\/-----------------------------------------------------------------------\n Ogre::GpuProgramParametersSharedPtr GLSLESProgram::createParameters( void )\n {\n GpuProgramParametersSharedPtr params = HighLevelGpuProgram::createParameters();\n params->setTransposeMatrices(true);\n return params;\n }\n \/\/-----------------------------------------------------------------------\n void GLSLESProgram::checkAndFixInvalidDefaultPrecisionError( String &message )\n {\n String precisionQualifierErrorString = \": 'Default Precision Qualifier' : invalid type Type for default precision qualifier can be only float or int\";\n std::vector< String > linesOfSource = StringUtil::split(mSource, \"\\n\");\n if( message.find(precisionQualifierErrorString) != String::npos )\n {\n LogManager::getSingleton().logMessage(\"Fixing invalid type Type for default precision qualifier by deleting bad lines the re-compiling\");\n\n \/\/ remove relevant lines from source\n std::vector< String > errors = StringUtil::split(message, \"\\n\");\n\n \/\/ going from the end so when we delete a line the numbers of the lines before will not change\n for(int i = static_cast<int>(errors.size()) - 1 ; i != -1 ; i--)\n {\n String & curError = errors[i];\n size_t foundPos = curError.find(precisionQualifierErrorString);\n if(foundPos != String::npos)\n {\n String lineNumber = curError.substr(0, foundPos);\n size_t posOfStartOfNumber = lineNumber.find_last_of(':');\n if (posOfStartOfNumber != String::npos)\n {\n lineNumber = lineNumber.substr(posOfStartOfNumber + 1, lineNumber.size() - (posOfStartOfNumber + 1));\n if (StringConverter::isNumber(lineNumber))\n {\n int iLineNumber = StringConverter::parseInt(lineNumber);\n linesOfSource.erase(linesOfSource.begin() + iLineNumber - 1);\n }\n }\n }\n } \n \/\/ rebuild source\n StringStream newSource; \n for(size_t i = 0; i < linesOfSource.size() ; i++)\n {\n newSource << linesOfSource[i] << \"\\n\";\n }\n mSource = newSource.str();\n\n const char *source = mSource.c_str();\n OGRE_CHECK_GL_ERROR(glShaderSource(mGLShaderHandle, 1, &source, NULL));\n\n if (compile())\n {\n LogManager::getSingleton().logMessage(\"The removing of the lines fixed the invalid type Type for default precision qualifier error.\");\n }\n else\n {\n LogManager::getSingleton().logMessage(\"The removing of the lines didn't help.\");\n }\n }\n }\n\n \/\/-----------------------------------------------------------------------------\n void GLSLESProgram::bindProgram(void)\n {\n \/\/ Tell the Link Program Manager what shader is to become active\n switch (mType)\n {\n case GPT_VERTEX_PROGRAM:\n GLSLESProgramManager::getSingleton().setActiveVertexShader( this );\n break;\n case GPT_FRAGMENT_PROGRAM:\n GLSLESProgramManager::getSingleton().setActiveFragmentShader( this );\n break;\n case GPT_GEOMETRY_PROGRAM:\n default:\n break;\n }\n }\n\n \/\/-----------------------------------------------------------------------------\n void GLSLESProgram::unbindProgram(void)\n {\n \/\/ Tell the Link Program Manager what shader is to become inactive\n if (mType == GPT_VERTEX_PROGRAM)\n {\n GLSLESProgramManager::getSingleton().setActiveVertexShader( NULL );\n }\n else if (mType == GPT_FRAGMENT_PROGRAM)\n {\n GLSLESProgramManager::getSingleton().setActiveFragmentShader( NULL );\n }\n }\n\n \/\/-----------------------------------------------------------------------------\n void GLSLESProgram::bindProgramParameters(GpuProgramParametersSharedPtr params, uint16 mask)\n {\n \/\/ Link can throw exceptions, ignore them at this point\n try\n {\n \/\/ Activate the link program object\n GLSLESProgramCommon* linkProgram = GLSLESProgramManager::getSingleton().getActiveProgram();\n \/\/ Pass on parameters from params to program object uniforms\n linkProgram->updateUniforms(params, mask, mType);\n\n }\n catch (Exception& e) {}\n }\n\n \/\/-----------------------------------------------------------------------------\n void GLSLESProgram::bindProgramSharedParameters(GpuProgramParametersSharedPtr params, uint16 mask)\n {\n \/\/ Link can throw exceptions, ignore them at this point\n try\n {\n \/\/ Activate the link program object\n GLSLESProgramCommon* linkProgram = GLSLESProgramManager::getSingleton().getActiveProgram();\n \/\/ Pass on parameters from params to program object uniforms\n linkProgram->updateUniformBlocks(params, mask, mType);\n }\n catch (Exception& e) {}\n }\n\n \/\/-----------------------------------------------------------------------------\n void GLSLESProgram::bindProgramPassIterationParameters(GpuProgramParametersSharedPtr params)\n {\n \/\/ Activate the link program object\n GLSLESProgramCommon* linkProgram = GLSLESProgramManager::getSingleton().getActiveProgram();\n \/\/ Pass on parameters from params to program object uniforms\n linkProgram->updatePassIterationUniforms( params );\n }\n\n \/\/-----------------------------------------------------------------------------\n size_t GLSLESProgram::calculateSize(void) const\n {\n size_t memSize = 0;\n\n \/\/ Delegate Names\n memSize += sizeof(GLuint);\n memSize += sizeof(GLenum);\n memSize += GpuProgram::calculateSize();\n\n return memSize;\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/===-- asan_dll_thunk.cc -------------------------------------------------===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This file is a part of AddressSanitizer, an address sanity checker.\n\/\/\n\/\/ This file defines a family of thunks that should be statically linked into\n\/\/ the DLLs that have ASan instrumentation in order to delegate the calls to the\n\/\/ shared runtime that lives in the main binary.\n\/\/ See https:\/\/code.google.com\/p\/address-sanitizer\/issues\/detail?id=209 for the\n\/\/ details.\n\/\/===----------------------------------------------------------------------===\/\/\n\n\/\/ Only compile this code when buidling asan_dll_thunk.lib\n\/\/ Using #ifdef rather than relying on Makefiles etc.\n\/\/ simplifies the build procedure.\n#ifdef ASAN_DLL_THUNK\n#include \"sanitizer_common\/sanitizer_interception.h\"\n\n\/\/ ----------------- Helper functions and macros --------------------- {{{1\nextern \"C\" {\nvoid *__stdcall GetModuleHandleA(const char *module_name);\nvoid *__stdcall GetProcAddress(void *module, const char *proc_name);\nvoid abort();\n}\n\nstatic void *getRealProcAddressOrDie(const char *name) {\n void *ret = GetProcAddress(GetModuleHandleA(0), name);\n if (!ret)\n abort();\n return ret;\n}\n\n#define WRAP_V_V(name) \\\n extern \"C\" void name() { \\\n typedef void (*fntype)(); \\\n static fntype fn = (fntype)getRealProcAddressOrDie(#name); \\\n fn(); \\\n }\n\n#define WRAP_V_W(name) \\\n extern \"C\" void name(void *arg) { \\\n typedef void (*fntype)(void *arg); \\\n static fntype fn = (fntype)getRealProcAddressOrDie(#name); \\\n fn(arg); \\\n }\n\n#define WRAP_V_WW(name) \\\n extern \"C\" void name(void *arg1, void *arg2) { \\\n typedef void (*fntype)(void *, void *); \\\n static fntype fn = (fntype)getRealProcAddressOrDie(#name); \\\n fn(arg1, arg2); \\\n }\n\n#define WRAP_V_WWW(name) \\\n extern \"C\" void name(void *arg1, void *arg2, void *arg3) { \\\n typedef void *(*fntype)(void *, void *, void *); \\\n static fntype fn = (fntype)getRealProcAddressOrDie(#name); \\\n fn(arg1, arg2, arg3); \\\n }\n\n#define WRAP_W_V(name) \\\n extern \"C\" void *name() { \\\n typedef void *(*fntype)(); \\\n static fntype fn = (fntype)getRealProcAddressOrDie(#name); \\\n return fn(); \\\n }\n\n#define WRAP_W_W(name) \\\n extern \"C\" void *name(void *arg) { \\\n typedef void *(*fntype)(void *arg); \\\n static fntype fn = (fntype)getRealProcAddressOrDie(#name); \\\n return fn(arg); \\\n }\n\n#define WRAP_W_WW(name) \\\n extern \"C\" void *name(void *arg1, void *arg2) { \\\n typedef void *(*fntype)(void *, void *); \\\n static fntype fn = (fntype)getRealProcAddressOrDie(#name); \\\n return fn(arg1, arg2); \\\n }\n\n#define WRAP_W_WWW(name) \\\n extern \"C\" void *name(void *arg1, void *arg2, void *arg3) { \\\n typedef void *(*fntype)(void *, void *, void *); \\\n static fntype fn = (fntype)getRealProcAddressOrDie(#name); \\\n return fn(arg1, arg2, arg3); \\\n }\n\n#define WRAP_W_WWWW(name) \\\n extern \"C\" void *name(void *arg1, void *arg2, void *arg3, void *arg4) { \\\n typedef void *(*fntype)(void *, void *, void *, void *); \\\n static fntype fn = (fntype)getRealProcAddressOrDie(#name); \\\n return fn(arg1, arg2, arg3, arg4); \\\n }\n\n#define WRAP_W_WWWWW(name) \\\n extern \"C\" void *name(void *arg1, void *arg2, void *arg3, void *arg4, \\\n void *arg5) { \\\n typedef void *(*fntype)(void *, void *, void *, void *, void *); \\\n static fntype fn = (fntype)getRealProcAddressOrDie(#name); \\\n return fn(arg1, arg2, arg3, arg4, arg5); \\\n }\n\n#define WRAP_W_WWWWWW(name) \\\n extern \"C\" void *name(void *arg1, void *arg2, void *arg3, void *arg4, \\\n void *arg5, void *arg6) { \\\n typedef void *(*fntype)(void *, void *, void *, void *, void *, void *); \\\n static fntype fn = (fntype)getRealProcAddressOrDie(#name); \\\n return fn(arg1, arg2, arg3, arg4, arg5, arg6); \\\n }\n\/\/ }}}\n\n\/\/ --------- Interface interception helper functions and macros ----------- {{{1\n\/\/ We need to intercept the ASan interface exported by the DLL thunk and forward\n\/\/ all the functions to the runtime in the main module.\n\/\/ However, we don't want to keep two lists of interface functions.\n\/\/ To avoid that, the list of interface functions should be defined using the\n\/\/ INTERFACE_FUNCTION macro. Then, all the interface can be intercepted at once\n\/\/ by calling INTERCEPT_ASAN_INTERFACE().\n\n\/\/ Use macro+template magic to automatically generate the list of interface\n\/\/ functions. Each interface function at line LINE defines a template class\n\/\/ with a static InterfaceInteceptor<LINE>::Execute() method intercepting the\n\/\/ function. The default implementation of InterfaceInteceptor<LINE> is to call\n\/\/ the Execute() method corresponding to the previous line.\ntemplate<int LINE>\nstruct InterfaceInteceptor {\n static void Execute() { InterfaceInteceptor<LINE-1>::Execute(); }\n};\n\n\/\/ There shouldn't be any interface function with negative line number.\ntemplate<>\nstruct InterfaceInteceptor<0> {\n static void Execute() {}\n};\n\n#define INTERFACE_FUNCTION(name) \\\n extern \"C\" void name() { __debugbreak(); } \\\n template<> struct InterfaceInteceptor<__LINE__> { \\\n static void Execute() { \\\n void *wrapper = getRealProcAddressOrDie(#name); \\\n if (!__interception::OverrideFunction((uptr)name, (uptr)wrapper, 0)) \\\n abort(); \\\n InterfaceInteceptor<__LINE__-1>::Execute(); \\\n } \\\n };\n\n\/\/ INTERCEPT_ASAN_INTERFACE must be used after the last INTERFACE_FUNCTION.\n#define INTERCEPT_ASAN_INTERFACE InterfaceInteceptor<__LINE__>::Execute\n\nstatic void InterceptASanInterface();\n\/\/ }}}\n\n\/\/ ----------------- ASan own interface functions --------------------\n\/\/ Don't use the INTERFACE_FUNCTION machinery for this function as we actually\n\/\/ want to call it in the __asan_init interceptor.\nWRAP_W_V(__asan_should_detect_stack_use_after_return)\n\nextern \"C\" {\n int __asan_option_detect_stack_use_after_return;\n\n \/\/ Manually wrap __asan_init as we need to initialize\n \/\/ __asan_option_detect_stack_use_after_return afterwards.\n void __asan_init_v3() {\n typedef void (*fntype)();\n static fntype fn = 0;\n if (fn) return;\n\n fn = (fntype)getRealProcAddressOrDie(\"__asan_init_v3\");\n fn();\n __asan_option_detect_stack_use_after_return =\n (__asan_should_detect_stack_use_after_return() != 0);\n\n InterceptASanInterface();\n }\n}\n\nINTERFACE_FUNCTION(__asan_handle_no_return)\n\nINTERFACE_FUNCTION(__asan_report_store1)\nINTERFACE_FUNCTION(__asan_report_store2)\nINTERFACE_FUNCTION(__asan_report_store4)\nINTERFACE_FUNCTION(__asan_report_store8)\nINTERFACE_FUNCTION(__asan_report_store16)\nINTERFACE_FUNCTION(__asan_report_store_n)\n\nINTERFACE_FUNCTION(__asan_report_load1)\nINTERFACE_FUNCTION(__asan_report_load2)\nINTERFACE_FUNCTION(__asan_report_load4)\nINTERFACE_FUNCTION(__asan_report_load8)\nINTERFACE_FUNCTION(__asan_report_load16)\nINTERFACE_FUNCTION(__asan_report_load_n)\n\nINTERFACE_FUNCTION(__asan_memcpy);\nINTERFACE_FUNCTION(__asan_memset);\nINTERFACE_FUNCTION(__asan_memmove);\n\nINTERFACE_FUNCTION(__asan_register_globals)\nINTERFACE_FUNCTION(__asan_unregister_globals)\n\nINTERFACE_FUNCTION(__asan_before_dynamic_init)\nINTERFACE_FUNCTION(__asan_after_dynamic_init)\n\nINTERFACE_FUNCTION(__asan_poison_stack_memory)\nINTERFACE_FUNCTION(__asan_unpoison_stack_memory)\n\nINTERFACE_FUNCTION(__asan_poison_memory_region)\nINTERFACE_FUNCTION(__asan_unpoison_memory_region)\n\nINTERFACE_FUNCTION(__asan_get_current_fake_stack)\nINTERFACE_FUNCTION(__asan_addr_is_in_fake_stack)\n\nINTERFACE_FUNCTION(__asan_stack_malloc_0)\nINTERFACE_FUNCTION(__asan_stack_malloc_1)\nINTERFACE_FUNCTION(__asan_stack_malloc_2)\nINTERFACE_FUNCTION(__asan_stack_malloc_3)\nINTERFACE_FUNCTION(__asan_stack_malloc_4)\nINTERFACE_FUNCTION(__asan_stack_malloc_5)\nINTERFACE_FUNCTION(__asan_stack_malloc_6)\nINTERFACE_FUNCTION(__asan_stack_malloc_7)\nINTERFACE_FUNCTION(__asan_stack_malloc_8)\nINTERFACE_FUNCTION(__asan_stack_malloc_9)\nINTERFACE_FUNCTION(__asan_stack_malloc_10)\n\nINTERFACE_FUNCTION(__asan_stack_free_0)\nINTERFACE_FUNCTION(__asan_stack_free_1)\nINTERFACE_FUNCTION(__asan_stack_free_2)\nINTERFACE_FUNCTION(__asan_stack_free_4)\nINTERFACE_FUNCTION(__asan_stack_free_5)\nINTERFACE_FUNCTION(__asan_stack_free_6)\nINTERFACE_FUNCTION(__asan_stack_free_7)\nINTERFACE_FUNCTION(__asan_stack_free_8)\nINTERFACE_FUNCTION(__asan_stack_free_9)\nINTERFACE_FUNCTION(__asan_stack_free_10)\n\n\/\/ TODO(timurrrr): Add more interface functions on the as-needed basis.\n\n\/\/ ----------------- Memory allocation functions ---------------------\nWRAP_V_W(free)\nWRAP_V_WW(_free_dbg)\n\nWRAP_W_W(malloc)\nWRAP_W_WWWW(_malloc_dbg)\n\nWRAP_W_WW(calloc)\nWRAP_W_WWWWW(_calloc_dbg)\nWRAP_W_WWW(_calloc_impl)\n\nWRAP_W_WW(realloc)\nWRAP_W_WWW(_realloc_dbg)\nWRAP_W_WWW(_recalloc)\n\nWRAP_W_W(_msize)\nWRAP_W_W(_expand)\nWRAP_W_W(_expand_dbg)\n\n\/\/ TODO(timurrrr): Might want to add support for _aligned_* allocation\n\/\/ functions to detect a bit more bugs. Those functions seem to wrap malloc().\n\n\/\/ TODO(timurrrr): Do we need to add _Crt* stuff here? (see asan_malloc_win.cc).\n\nvoid InterceptASanInterface() {\n INTERCEPT_ASAN_INTERFACE();\n}\n\n#endif \/\/ ASAN_DLL_THUNK\n<commit_msg>[ASan\/Win] Add a comment about DCL-using-static vs threads<commit_after>\/\/===-- asan_dll_thunk.cc -------------------------------------------------===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This file is a part of AddressSanitizer, an address sanity checker.\n\/\/\n\/\/ This file defines a family of thunks that should be statically linked into\n\/\/ the DLLs that have ASan instrumentation in order to delegate the calls to the\n\/\/ shared runtime that lives in the main binary.\n\/\/ See https:\/\/code.google.com\/p\/address-sanitizer\/issues\/detail?id=209 for the\n\/\/ details.\n\/\/===----------------------------------------------------------------------===\/\/\n\n\/\/ Only compile this code when buidling asan_dll_thunk.lib\n\/\/ Using #ifdef rather than relying on Makefiles etc.\n\/\/ simplifies the build procedure.\n#ifdef ASAN_DLL_THUNK\n#include \"sanitizer_common\/sanitizer_interception.h\"\n\n\/\/ ----------------- Helper functions and macros --------------------- {{{1\nextern \"C\" {\nvoid *__stdcall GetModuleHandleA(const char *module_name);\nvoid *__stdcall GetProcAddress(void *module, const char *proc_name);\nvoid abort();\n}\n\nstatic void *getRealProcAddressOrDie(const char *name) {\n void *ret = GetProcAddress(GetModuleHandleA(0), name);\n if (!ret)\n abort();\n return ret;\n}\n\n#define WRAP_V_V(name) \\\n extern \"C\" void name() { \\\n typedef void (*fntype)(); \\\n static fntype fn = (fntype)getRealProcAddressOrDie(#name); \\\n fn(); \\\n }\n\n#define WRAP_V_W(name) \\\n extern \"C\" void name(void *arg) { \\\n typedef void (*fntype)(void *arg); \\\n static fntype fn = (fntype)getRealProcAddressOrDie(#name); \\\n fn(arg); \\\n }\n\n#define WRAP_V_WW(name) \\\n extern \"C\" void name(void *arg1, void *arg2) { \\\n typedef void (*fntype)(void *, void *); \\\n static fntype fn = (fntype)getRealProcAddressOrDie(#name); \\\n fn(arg1, arg2); \\\n }\n\n#define WRAP_V_WWW(name) \\\n extern \"C\" void name(void *arg1, void *arg2, void *arg3) { \\\n typedef void *(*fntype)(void *, void *, void *); \\\n static fntype fn = (fntype)getRealProcAddressOrDie(#name); \\\n fn(arg1, arg2, arg3); \\\n }\n\n#define WRAP_W_V(name) \\\n extern \"C\" void *name() { \\\n typedef void *(*fntype)(); \\\n static fntype fn = (fntype)getRealProcAddressOrDie(#name); \\\n return fn(); \\\n }\n\n#define WRAP_W_W(name) \\\n extern \"C\" void *name(void *arg) { \\\n typedef void *(*fntype)(void *arg); \\\n static fntype fn = (fntype)getRealProcAddressOrDie(#name); \\\n return fn(arg); \\\n }\n\n#define WRAP_W_WW(name) \\\n extern \"C\" void *name(void *arg1, void *arg2) { \\\n typedef void *(*fntype)(void *, void *); \\\n static fntype fn = (fntype)getRealProcAddressOrDie(#name); \\\n return fn(arg1, arg2); \\\n }\n\n#define WRAP_W_WWW(name) \\\n extern \"C\" void *name(void *arg1, void *arg2, void *arg3) { \\\n typedef void *(*fntype)(void *, void *, void *); \\\n static fntype fn = (fntype)getRealProcAddressOrDie(#name); \\\n return fn(arg1, arg2, arg3); \\\n }\n\n#define WRAP_W_WWWW(name) \\\n extern \"C\" void *name(void *arg1, void *arg2, void *arg3, void *arg4) { \\\n typedef void *(*fntype)(void *, void *, void *, void *); \\\n static fntype fn = (fntype)getRealProcAddressOrDie(#name); \\\n return fn(arg1, arg2, arg3, arg4); \\\n }\n\n#define WRAP_W_WWWWW(name) \\\n extern \"C\" void *name(void *arg1, void *arg2, void *arg3, void *arg4, \\\n void *arg5) { \\\n typedef void *(*fntype)(void *, void *, void *, void *, void *); \\\n static fntype fn = (fntype)getRealProcAddressOrDie(#name); \\\n return fn(arg1, arg2, arg3, arg4, arg5); \\\n }\n\n#define WRAP_W_WWWWWW(name) \\\n extern \"C\" void *name(void *arg1, void *arg2, void *arg3, void *arg4, \\\n void *arg5, void *arg6) { \\\n typedef void *(*fntype)(void *, void *, void *, void *, void *, void *); \\\n static fntype fn = (fntype)getRealProcAddressOrDie(#name); \\\n return fn(arg1, arg2, arg3, arg4, arg5, arg6); \\\n }\n\/\/ }}}\n\n\/\/ --------- Interface interception helper functions and macros ----------- {{{1\n\/\/ We need to intercept the ASan interface exported by the DLL thunk and forward\n\/\/ all the functions to the runtime in the main module.\n\/\/ However, we don't want to keep two lists of interface functions.\n\/\/ To avoid that, the list of interface functions should be defined using the\n\/\/ INTERFACE_FUNCTION macro. Then, all the interface can be intercepted at once\n\/\/ by calling INTERCEPT_ASAN_INTERFACE().\n\n\/\/ Use macro+template magic to automatically generate the list of interface\n\/\/ functions. Each interface function at line LINE defines a template class\n\/\/ with a static InterfaceInteceptor<LINE>::Execute() method intercepting the\n\/\/ function. The default implementation of InterfaceInteceptor<LINE> is to call\n\/\/ the Execute() method corresponding to the previous line.\ntemplate<int LINE>\nstruct InterfaceInteceptor {\n static void Execute() { InterfaceInteceptor<LINE-1>::Execute(); }\n};\n\n\/\/ There shouldn't be any interface function with negative line number.\ntemplate<>\nstruct InterfaceInteceptor<0> {\n static void Execute() {}\n};\n\n#define INTERFACE_FUNCTION(name) \\\n extern \"C\" void name() { __debugbreak(); } \\\n template<> struct InterfaceInteceptor<__LINE__> { \\\n static void Execute() { \\\n void *wrapper = getRealProcAddressOrDie(#name); \\\n if (!__interception::OverrideFunction((uptr)name, (uptr)wrapper, 0)) \\\n abort(); \\\n InterfaceInteceptor<__LINE__-1>::Execute(); \\\n } \\\n };\n\n\/\/ INTERCEPT_ASAN_INTERFACE must be used after the last INTERFACE_FUNCTION.\n#define INTERCEPT_ASAN_INTERFACE InterfaceInteceptor<__LINE__>::Execute\n\nstatic void InterceptASanInterface();\n\/\/ }}}\n\n\/\/ ----------------- ASan own interface functions --------------------\n\/\/ Don't use the INTERFACE_FUNCTION machinery for this function as we actually\n\/\/ want to call it in the __asan_init interceptor.\nWRAP_W_V(__asan_should_detect_stack_use_after_return)\n\nextern \"C\" {\n int __asan_option_detect_stack_use_after_return;\n\n \/\/ Manually wrap __asan_init as we need to initialize\n \/\/ __asan_option_detect_stack_use_after_return afterwards.\n void __asan_init_v3() {\n typedef void (*fntype)();\n static fntype fn = 0;\n \/\/ __asan_init_v3 is expected to be called by only one thread.\n if (fn) return;\n\n fn = (fntype)getRealProcAddressOrDie(\"__asan_init_v3\");\n fn();\n __asan_option_detect_stack_use_after_return =\n (__asan_should_detect_stack_use_after_return() != 0);\n\n InterceptASanInterface();\n }\n}\n\nINTERFACE_FUNCTION(__asan_handle_no_return)\n\nINTERFACE_FUNCTION(__asan_report_store1)\nINTERFACE_FUNCTION(__asan_report_store2)\nINTERFACE_FUNCTION(__asan_report_store4)\nINTERFACE_FUNCTION(__asan_report_store8)\nINTERFACE_FUNCTION(__asan_report_store16)\nINTERFACE_FUNCTION(__asan_report_store_n)\n\nINTERFACE_FUNCTION(__asan_report_load1)\nINTERFACE_FUNCTION(__asan_report_load2)\nINTERFACE_FUNCTION(__asan_report_load4)\nINTERFACE_FUNCTION(__asan_report_load8)\nINTERFACE_FUNCTION(__asan_report_load16)\nINTERFACE_FUNCTION(__asan_report_load_n)\n\nINTERFACE_FUNCTION(__asan_memcpy);\nINTERFACE_FUNCTION(__asan_memset);\nINTERFACE_FUNCTION(__asan_memmove);\n\nINTERFACE_FUNCTION(__asan_register_globals)\nINTERFACE_FUNCTION(__asan_unregister_globals)\n\nINTERFACE_FUNCTION(__asan_before_dynamic_init)\nINTERFACE_FUNCTION(__asan_after_dynamic_init)\n\nINTERFACE_FUNCTION(__asan_poison_stack_memory)\nINTERFACE_FUNCTION(__asan_unpoison_stack_memory)\n\nINTERFACE_FUNCTION(__asan_poison_memory_region)\nINTERFACE_FUNCTION(__asan_unpoison_memory_region)\n\nINTERFACE_FUNCTION(__asan_get_current_fake_stack)\nINTERFACE_FUNCTION(__asan_addr_is_in_fake_stack)\n\nINTERFACE_FUNCTION(__asan_stack_malloc_0)\nINTERFACE_FUNCTION(__asan_stack_malloc_1)\nINTERFACE_FUNCTION(__asan_stack_malloc_2)\nINTERFACE_FUNCTION(__asan_stack_malloc_3)\nINTERFACE_FUNCTION(__asan_stack_malloc_4)\nINTERFACE_FUNCTION(__asan_stack_malloc_5)\nINTERFACE_FUNCTION(__asan_stack_malloc_6)\nINTERFACE_FUNCTION(__asan_stack_malloc_7)\nINTERFACE_FUNCTION(__asan_stack_malloc_8)\nINTERFACE_FUNCTION(__asan_stack_malloc_9)\nINTERFACE_FUNCTION(__asan_stack_malloc_10)\n\nINTERFACE_FUNCTION(__asan_stack_free_0)\nINTERFACE_FUNCTION(__asan_stack_free_1)\nINTERFACE_FUNCTION(__asan_stack_free_2)\nINTERFACE_FUNCTION(__asan_stack_free_4)\nINTERFACE_FUNCTION(__asan_stack_free_5)\nINTERFACE_FUNCTION(__asan_stack_free_6)\nINTERFACE_FUNCTION(__asan_stack_free_7)\nINTERFACE_FUNCTION(__asan_stack_free_8)\nINTERFACE_FUNCTION(__asan_stack_free_9)\nINTERFACE_FUNCTION(__asan_stack_free_10)\n\n\/\/ TODO(timurrrr): Add more interface functions on the as-needed basis.\n\n\/\/ ----------------- Memory allocation functions ---------------------\nWRAP_V_W(free)\nWRAP_V_WW(_free_dbg)\n\nWRAP_W_W(malloc)\nWRAP_W_WWWW(_malloc_dbg)\n\nWRAP_W_WW(calloc)\nWRAP_W_WWWWW(_calloc_dbg)\nWRAP_W_WWW(_calloc_impl)\n\nWRAP_W_WW(realloc)\nWRAP_W_WWW(_realloc_dbg)\nWRAP_W_WWW(_recalloc)\n\nWRAP_W_W(_msize)\nWRAP_W_W(_expand)\nWRAP_W_W(_expand_dbg)\n\n\/\/ TODO(timurrrr): Might want to add support for _aligned_* allocation\n\/\/ functions to detect a bit more bugs. Those functions seem to wrap malloc().\n\n\/\/ TODO(timurrrr): Do we need to add _Crt* stuff here? (see asan_malloc_win.cc).\n\nvoid InterceptASanInterface() {\n INTERCEPT_ASAN_INTERFACE();\n}\n\n#endif \/\/ ASAN_DLL_THUNK\n<|endoftext|>"} {"text":"<commit_before>\/* This is free and unencumbered software released into the public domain. *\/\n\n#ifdef HAVE_CONFIG_H\n#include <config.h>\n#endif\n\n#include \"buffer.h\"\n\n#include <cassert> \/* for assert() *\/\n#include <cerrno> \/* for errno *\/\n#include <stdexcept> \/* for std::bad_alloc *\/\n#include <sys\/mman.h> \/* for mmap(), munmap(), mremap() *\/\n#include <system_error> \/* for std::system_error *\/\n#include <unistd.h> \/* for sysconf() *\/\n\nusing namespace machinery::util;\n\nstatic const int mmap_prot = PROT_READ | PROT_WRITE | PROT_EXEC;\nstatic const int mmap_flags = MAP_PRIVATE | MAP_ANON;\nstatic const std::size_t mmap_size = sysconf(_SC_PAGESIZE);\n\nexecutable_buffer::executable_buffer()\n : _data(nullptr),\n _size(mmap_size),\n _capacity(mmap_size) {\n\n void* const addr = ::mmap(nullptr, _capacity, mmap_prot, mmap_flags, -1, 0);\n if (addr == MAP_FAILED) {\n switch (errno) {\n case ENOMEM: \/* Cannot allocate memory in kernel *\/\n throw std::bad_alloc();\n default:\n assert(errno != EBADF);\n throw std::system_error(errno, std::system_category());\n }\n }\n\n _data = reinterpret_cast<std::uint8_t*>(addr);\n}\n\nexecutable_buffer::~executable_buffer() noexcept {\n if (_data) {\n if (::munmap(reinterpret_cast<void*>(_data), _size) == -1) {\n \/* Ignore any errors from munmap(). *\/\n }\n _data = nullptr;\n _size = _capacity = 0;\n }\n}\n\nvoid\nexecutable_buffer::grow() {\n#ifdef __linux__\n \/\/ TODO: use mremap()\n#else\n \/\/ TODO: use mmap()\n#endif\n throw std::system_error(ENOSYS, std::system_category());\n}\n<commit_msg>Fixed a bug in executable_buffer construction.<commit_after>\/* This is free and unencumbered software released into the public domain. *\/\n\n#ifdef HAVE_CONFIG_H\n#include <config.h>\n#endif\n\n#include \"buffer.h\"\n\n#include <cassert> \/* for assert() *\/\n#include <cerrno> \/* for errno *\/\n#include <stdexcept> \/* for std::bad_alloc *\/\n#include <sys\/mman.h> \/* for mmap(), munmap(), mremap() *\/\n#include <system_error> \/* for std::system_error *\/\n#include <unistd.h> \/* for sysconf() *\/\n\nusing namespace machinery::util;\n\nstatic const int mmap_prot = PROT_READ | PROT_WRITE | PROT_EXEC;\nstatic const int mmap_flags = MAP_PRIVATE | MAP_ANON;\nstatic const std::size_t mmap_size = sysconf(_SC_PAGESIZE);\n\nexecutable_buffer::executable_buffer()\n : _data(nullptr),\n _size(0),\n _capacity(mmap_size) {\n\n void* const addr = ::mmap(nullptr, _capacity, mmap_prot, mmap_flags, -1, 0);\n if (addr == MAP_FAILED) {\n switch (errno) {\n case ENOMEM: \/* Cannot allocate memory in kernel *\/\n throw std::bad_alloc();\n default:\n assert(errno != EBADF);\n throw std::system_error(errno, std::system_category());\n }\n }\n\n _data = reinterpret_cast<std::uint8_t*>(addr);\n}\n\nexecutable_buffer::~executable_buffer() noexcept {\n if (_data) {\n if (::munmap(reinterpret_cast<void*>(_data), _size) == -1) {\n \/* Ignore any errors from munmap(). *\/\n }\n _data = nullptr;\n _size = _capacity = 0;\n }\n}\n\nvoid\nexecutable_buffer::grow() {\n#ifdef __linux__\n \/\/ TODO: use mremap()\n#else\n \/\/ TODO: use mmap()\n#endif\n throw std::system_error(ENOSYS, std::system_category());\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"xmlbinder.h\"\n#include \"raiden.h\"\n#include \"paramset.h\"\n#include <string>\nvoid XMLBinder::Init()\n{\n}\n\nvoid XMLBinder::Release()\n{\n}\n\nvoid PushInteger(ParamSet &set, const pugi::xml_node &node, const char *name = \"name\")\n{\n const char *v_name = node.attribute(name).as_string();\n auto v = node.attribute(\"value\").as_int();\n set.AddInt(v_name, std::unique_ptr<int[]>(new int[1]{v}), 1);\n LInfo << \"--->integer name:\" << v_name << \" value:\" << v;\n}\n\nvoid PushFloat(ParamSet &set, const pugi::xml_node &node, const char *name = \"name\")\n{\n const char *v_name = node.attribute(name).as_string();\n auto v = node.attribute(\"value\").as_float();\n set.AddFloat(v_name, std::unique_ptr<float[]>(new float[1]{v}), 1);\n LInfo << \"--->float name:\" << v_name << \" value:\" << v;\n}\n\nvoid PushBool(ParamSet &set, const pugi::xml_node &node, const char *name = \"name\")\n{\n const char *v_name = node.attribute(name).as_string();\n auto v = node.attribute(\"value\").as_bool();\n set.AddBool(v_name, std::unique_ptr<bool[]>(new bool[1]{v}), 1);\n LInfo << \"--->bool name:\" << v_name << \" value:\" << v;\n}\n\nvoid PushRGB(ParamSet &set, const pugi::xml_node &node, const char *name = \"name\")\n{\n const char *v_name = node.attribute(name).as_string();\n float r = node.attribute(\"r\").as_float();\n float g = node.attribute(\"g\").as_float();\n float b = node.attribute(\"b\").as_float();\n set.AddRGBSpectrum(v_name, std::unique_ptr<float[]>(new float[3]{r, g, b}), 3);\n LInfo << \"--->rgb name:\" << v_name << \" value:[\" << r << \",\" << g << \",\" << b << \"]\";\n}\n\nvoid PushPoint2f(ParamSet &set, const pugi::xml_node &node, const char *name = \"name\")\n{\n const char *v_name = node.attribute(name).as_string();\n float x = node.attribute(\"x\").as_float();\n float y = node.attribute(\"y\").as_float();\n set.AddPoint2f(v_name, std::unique_ptr<Point2f[]>(new Point2f[1]{Point2f(x, y)}), 1);\n LInfo << \"--->point2f name:\" << v_name << \" value:[\" << x << \",\" << y << \"]\";\n}\n\nvoid PushPoint3f(ParamSet &set, const pugi::xml_node &node, const char *name = \"name\")\n{\n const char *v_name = node.attribute(name).as_string();\n float x = node.attribute(\"x\").as_float();\n float y = node.attribute(\"y\").as_float();\n float z = node.attribute(\"z\").as_float();\n set.AddPoint3f(v_name, std::unique_ptr<Point3f[]>(new Point3f[1]{Point3f(x, y, z)}), 1);\n LInfo << \"--->point3f name:\" << v_name << \" value:[\" << x << \",\" << y << \",\" << z << \"]\";\n}\n\nvoid PushVector2f(ParamSet &set, const pugi::xml_node &node, const char *name = \"name\")\n{\n const char *v_name = node.attribute(name).as_string();\n float x = node.attribute(\"x\").as_float();\n float y = node.attribute(\"y\").as_float();\n set.AddVector2f(v_name, std::unique_ptr<Vector2f[]>(new Vector2f[1]{Vector2f(x, y)}), 1);\n LInfo << \"--->vector2f name:\" << v_name << \" value:[\" << x << \",\" << y << \"]\";\n}\n\nvoid PushVector3f(ParamSet &set, const pugi::xml_node &node, const char *name = \"name\")\n{\n const char *v_name = node.attribute(name).as_string();\n float x = node.attribute(\"x\").as_float();\n float y = node.attribute(\"y\").as_float();\n float z = node.attribute(\"z\").as_float();\n set.AddVector3f(v_name, std::unique_ptr<Vector3f[]>(new Vector3f[1]{Vector3f(x, y, z)}), 1);\n LInfo << \"--->vector3f name:\" << v_name << \" value:[\" << x << \",\" << y << \",\" << z << \"]\";\n}\n\nvoid PushNormal3f(ParamSet &set, const pugi::xml_node &node, const char *name = \"name\")\n{\n const char *v_name = node.attribute(name).as_string();\n float x = node.attribute(\"x\").as_float();\n float y = node.attribute(\"y\").as_float();\n float z = node.attribute(\"z\").as_float();\n set.AddNormal3f(v_name, std::unique_ptr<Normal3f[]>(new Normal3f[1]{Normal3f(x, y, z)}), 1);\n LInfo << \"--->normal3f name:\" << v_name << \" value:[\" << x << \",\" << y << \",\" << z << \"]\";\n}\n\nvoid PushIntegetArray(ParamSet &set, const pugi::xml_node &node, const char *name = \"name\")\n{\n const char *v_name = node.attribute(name).as_string();\n const char *v_value = node.child_value();\n char *t_value = (char *)malloc(strlen(v_value));\n memcpy(t_value, v_value, strlen(v_value));\n std::vector<int> splits;\n char *p = strtok(t_value, \",\");\n while (p != nullptr)\n {\n splits.push_back(atoi(p));\n p = strtok(nullptr, \",\");\n }\n std::unique_ptr<int[]> ints(new int[splits.size()]);\n for (uint32_t i = 0; i < splits.size(); ++i)\n {\n ints[i] = splits[i];\n }\n set.AddInt(v_value, std::move(ints), splits.size());\n LInfo << \"--->int[] name:\" << v_name << \" value:[\" << v_value << \"]\";\n}\n\nvoid PushFloatArray(ParamSet &set, const pugi::xml_node &node, const char *name = \"name\")\n{\n const char *v_name = node.attribute(name).as_string();\n const char *v_value = node.child_value();\n char *t_value = (char *)malloc(strlen(v_value));\n memcpy(t_value, v_value, strlen(v_value));\n std::vector<float> splits;\n char *p = strtok(t_value, \",\");\n while (p != nullptr)\n {\n splits.push_back(atof(p));\n p = strtok(nullptr, \",\");\n }\n std::unique_ptr<float[]> floats(new float[splits.size()]);\n for (uint32_t i = 0; i < splits.size(); ++i)\n {\n floats[i] = splits[i];\n }\n set.AddFloat(v_value, std::move(floats), splits.size());\n LInfo << \"--->float[] name:\" << v_name << \" value:[\" << v_value << \"]\";\n}\n\nvoid PushTexture(ParamSet &set, const pugi::xml_node &node, const char *name = \"name\")\n{\n const char *v_name = node.attribute(name).as_string();\n set.AddTexture(name, v_name);\n LInfo << \"--->texture name:\" << v_name;\n}\n\nvoid PushString(ParamSet &set, const pugi::xml_node &node, const char *name = \"name\")\n{\n const char *v_name = node.attribute(name).as_string();\n set.AddString(name, std::unique_ptr<std::string[]>(new std::string[1]{v_name}), 1);\n LInfo << \"--->string name:\" << v_name;\n}\n\nvoid XMLBinder::PharseChildNodeParamSet(ParamSet &set, const pugi::xml_node &root) const\n{\n\n for (pugi::xml_node node = root.first_child(); node; node = node.next_sibling())\n {\n const char *name = node.name();\n if (strcmp(name, \"integer\") == 0)\n {\n \/\/单个整数\n PushInteger(set, node);\n }\n else if (strcmp(name, \"float\") == 0)\n {\n \/\/单个浮点数\n PushFloat(set, node);\n }\n else if (strcmp(name, \"bool\") == 0)\n {\n \/\/单个布尔值\n PushBool(set, node);\n }\n else if (strcmp(name, \"rgb\") == 0)\n {\n PushRGB(set, node);\n }\n else if (strcmp(name, \"point2f\") == 0)\n {\n PushPoint2f(set, node);\n }\n else if (strcmp(name, \"point3f\") == 0)\n {\n PushPoint3f(set, node);\n }\n else if (strcmp(name, \"vector2f\") == 0)\n {\n PushVector2f(set, node);\n }\n else if (strcmp(name, \"vector3f\") == 0)\n {\n PushVector3f(set, node);\n }\n else if (strcmp(name, \"normal3f\") == 0)\n {\n PushNormal3f(set, node);\n }\n else if (strcmp(name, \"integer_array\") == 0)\n {\n PushIntegetArray(set, node);\n }\n else if (strcmp(name, \"float_array\") == 0)\n {\n PushFloatArray(set, node);\n }\n else if (strcmp(name, \"texture\") == 0)\n {\n PushTexture(set, node);\n }\n else if (strcmp(name, \"string\") == 0)\n {\n \/\/字符串\n PushString(set, node);\n }\n }\n}\n\nvoid XMLBinder::ExecScript(const char *fileName)\n{\n pugi::xml_parse_result result = _doc.load_file(fileName);\n LInfo << \"Loading XML state:\" << result.description();\n auto root = _doc.first_child();\n if (strcmp(root.name(), \"scene\") == 0)\n {\n \/\/开始解析scene层\n LInfo << \"->scene node\";\n for (pugi::xml_node node = root.first_child(); node; node = node.next_sibling())\n {\n const char *name = node.name();\n if (strcmp(name, \"world_begin\") == 0)\n {\n LInfo << \"-->world begin node\";\n raidenWorldBegin();\n }\n else if (strcmp(name, \"world_end\") == 0)\n {\n LInfo << \"-->world end node\";\n raidenWorldEnd();\n }\n else if (strcmp(name, \"translate\") == 0)\n {\n float dx = node.attribute(\"x\").as_float();\n float dy = node.attribute(\"y\").as_float();\n float dz = node.attribute(\"z\").as_float();\n LInfo << \"-->translate node:[\" << dx << \" ,\" << dy << \" ,\" << dz << \"]\";\n raidenTranslate(dx, dy, dz);\n }\n else if (strcmp(name, \"rotate\") == 0)\n {\n float angle = node.attribute(\"angle\").as_float();\n float dx = node.attribute(\"x\").as_float();\n float dy = node.attribute(\"y\").as_float();\n float dz = node.attribute(\"z\").as_float();\n LInfo << \"-->rotate node:[\" << angle << \"|\" << dx << \" ,\" << dy << \" ,\" << dz << \"]\";\n raidenRotate(angle, dx, dy, dz);\n }\n else if (strcmp(name, \"scale\") == 0)\n {\n float dx = node.attribute(\"x\").as_float();\n float dy = node.attribute(\"y\").as_float();\n float dz = node.attribute(\"z\").as_float();\n LInfo << \"-->scale node:[\" << dx << \" ,\" << dy << \" ,\" << dz << \"]\";\n raidenScale(dx, dy, dz);\n }\n else if (strcmp(name, \"frame_save\") == 0)\n {\n ParamSet params;\n auto frame_name = node.attribute(\"name\").as_string();\n raidenCoordinateSystem(frame_name);\n LInfo << \"-->save_frame:\" << frame_name;\n }\n else if (strcmp(name, \"frame_load\") == 0)\n {\n ParamSet params;\n auto frame_name = node.attribute(\"name\").as_string();\n raidenCoordSysTransform(frame_name);\n LInfo << \"-->load_frame:\" << frame_name;\n }\n \/\/TODO 和时间有关的API还没有绑定\n else if (strcmp(name, \"filter\") == 0)\n {\n LInfo << \"-->filter node\";\n ParamSet params;\n auto type = node.attribute(\"type\").as_string();\n PharseChildNodeParamSet(params, node);\n raidenPixelFilter(type, params);\n }\n else if (strcmp(name, \"accelerator\") == 0)\n {\n LInfo << \"-->accelerator node\";\n ParamSet params;\n auto type = node.attribute(\"type\").as_string();\n PharseChildNodeParamSet(params, node);\n raidenAccelerator(type, params);\n }\n else if (strcmp(name, \"integrator\") == 0)\n {\n LInfo << \"-->integrator node\";\n ParamSet params;\n auto type = node.attribute(\"type\").as_string();\n PharseChildNodeParamSet(params, node);\n raidenIntegrator(type, params);\n }\n else if (strcmp(name, \"camera\") == 0)\n {\n LInfo << \"-->camera node\";\n ParamSet params;\n auto type = node.attribute(\"type\").as_string();\n PharseChildNodeParamSet(params, node);\n raidenCamera(type, params);\n }\n else if (strcmp(name, \"film\") == 0)\n {\n LInfo << \"-->film node\";\n ParamSet params;\n auto type = node.attribute(\"type\").as_string();\n PharseChildNodeParamSet(params, node);\n raidenFilm(type, params);\n }\n else if (strcmp(name, \"sampler\") == 0)\n {\n LInfo << \"-->sampler node\";\n ParamSet params;\n auto type = node.attribute(\"type\").as_string();\n PharseChildNodeParamSet(params, node);\n raidenSampler(type, params);\n }\n else if (strcmp(name, \"shape\") == 0)\n {\n LInfo << \"-->shape node\";\n ParamSet params;\n auto type = node.attribute(\"type\").as_string();\n PharseChildNodeParamSet(params, node);\n raidenShape(type, params);\n }\n else if (strcmp(name, \"texture\") == 0)\n {\n LInfo << \"-->texture node\";\n ParamSet params;\n auto t_name = node.attribute(\"name\").as_string();\n auto type = node.attribute(\"type\").as_string();\n auto src = node.attribute(\"source\").as_string();\n PharseChildNodeParamSet(params, node);\n raidenTexture(t_name, type, src, params);\n }\n else if (strcmp(name, \"material\") == 0)\n {\n LInfo << \"-->material node\";\n ParamSet params;\n auto t_name = node.attribute(\"name\").as_string();\n PushString(params, node, \"type\");\n PharseChildNodeParamSet(params, node);\n raidenMakeNamedMaterial(t_name, params);\n }\n else if (strcmp(name, \"material_tmp\") == 0)\n {\n LInfo << \"-->temporary material node\";\n ParamSet params;\n auto type = node.attribute(\"type\").as_string();\n PharseChildNodeParamSet(params, node);\n raidenMaterial(type, params);\n }\n else if (strcmp(name, \"material_ref\") == 0)\n {\n LInfo << \"-->reference material node\";\n auto t_name = node.attribute(\"name\").as_string();\n raidenNamedMaterial(t_name);\n }\n else if (strcmp(name, \"transform_begin\") == 0)\n {\n LInfo << \"-->transfrom begin node\";\n raidenTransformBegin();\n }\n else if (strcmp(name, \"transform_end\") == 0)\n {\n LInfo << \"-->transfrom end node\";\n raidenTransformEnd();\n }\n else if (strcmp(name, \"light\") == 0)\n {\n ParamSet params;\n auto type = node.attribute(\"type\").as_string();\n PharseChildNodeParamSet(params, node);\n raidenLightSource(type, params);\n }\n else if (strcmp(name, \"area_light\") == 0)\n {\n ParamSet params;\n auto type = node.attribute(\"type\").as_string();\n PharseChildNodeParamSet(params, node);\n raidenAreaLightSource(type,params);\n }\n }\n }\n else\n {\n LWarning << \"XML file must has a root node \\\"scene\\\" but \\\"\" << root << \"\\\" now\";\n }\n}<commit_msg>重新修改xml的表情名,和LUA端统一<commit_after>#include \"xmlbinder.h\"\n#include \"raiden.h\"\n#include \"paramset.h\"\n#include <string>\nvoid XMLBinder::Init()\n{\n}\n\nvoid XMLBinder::Release()\n{\n}\n\nvoid PushInteger(ParamSet &set, const pugi::xml_node &node, const char *name = \"name\")\n{\n const char *v_name = node.attribute(name).as_string();\n auto v = node.attribute(\"value\").as_int();\n set.AddInt(v_name, std::unique_ptr<int[]>(new int[1]{v}), 1);\n}\n\nvoid PushFloat(ParamSet &set, const pugi::xml_node &node, const char *name = \"name\")\n{\n const char *v_name = node.attribute(name).as_string();\n auto v = node.attribute(\"value\").as_float();\n set.AddFloat(v_name, std::unique_ptr<float[]>(new float[1]{v}), 1);\n}\n\nvoid PushBool(ParamSet &set, const pugi::xml_node &node, const char *name = \"name\")\n{\n const char *v_name = node.attribute(name).as_string();\n auto v = node.attribute(\"value\").as_bool();\n set.AddBool(v_name, std::unique_ptr<bool[]>(new bool[1]{v}), 1);\n}\n\nvoid PushRGB(ParamSet &set, const pugi::xml_node &node, const char *name = \"name\")\n{\n const char *v_name = node.attribute(name).as_string();\n float r = node.attribute(\"r\").as_float();\n float g = node.attribute(\"g\").as_float();\n float b = node.attribute(\"b\").as_float();\n set.AddRGBSpectrum(v_name, std::unique_ptr<float[]>(new float[3]{r, g, b}), 3);\n}\n\nvoid PushPoint2f(ParamSet &set, const pugi::xml_node &node, const char *name = \"name\")\n{\n const char *v_name = node.attribute(name).as_string();\n float x = node.attribute(\"x\").as_float();\n float y = node.attribute(\"y\").as_float();\n set.AddPoint2f(v_name, std::unique_ptr<Point2f[]>(new Point2f[1]{Point2f(x, y)}), 1);\n}\n\nvoid PushPoint3f(ParamSet &set, const pugi::xml_node &node, const char *name = \"name\")\n{\n const char *v_name = node.attribute(name).as_string();\n float x = node.attribute(\"x\").as_float();\n float y = node.attribute(\"y\").as_float();\n float z = node.attribute(\"z\").as_float();\n set.AddPoint3f(v_name, std::unique_ptr<Point3f[]>(new Point3f[1]{Point3f(x, y, z)}), 1);\n}\n\nvoid PushVector2f(ParamSet &set, const pugi::xml_node &node, const char *name = \"name\")\n{\n const char *v_name = node.attribute(name).as_string();\n float x = node.attribute(\"x\").as_float();\n float y = node.attribute(\"y\").as_float();\n set.AddVector2f(v_name, std::unique_ptr<Vector2f[]>(new Vector2f[1]{Vector2f(x, y)}), 1);\n}\n\nvoid PushVector3f(ParamSet &set, const pugi::xml_node &node, const char *name = \"name\")\n{\n const char *v_name = node.attribute(name).as_string();\n float x = node.attribute(\"x\").as_float();\n float y = node.attribute(\"y\").as_float();\n float z = node.attribute(\"z\").as_float();\n set.AddVector3f(v_name, std::unique_ptr<Vector3f[]>(new Vector3f[1]{Vector3f(x, y, z)}), 1);\n}\n\nvoid PushNormal3f(ParamSet &set, const pugi::xml_node &node, const char *name = \"name\")\n{\n const char *v_name = node.attribute(name).as_string();\n float x = node.attribute(\"x\").as_float();\n float y = node.attribute(\"y\").as_float();\n float z = node.attribute(\"z\").as_float();\n set.AddNormal3f(v_name, std::unique_ptr<Normal3f[]>(new Normal3f[1]{Normal3f(x, y, z)}), 1);\n}\n\nvoid PushIntegetArray(ParamSet &set, const pugi::xml_node &node, const char *name = \"name\")\n{\n const char *v_name = node.attribute(name).as_string();\n const char *v_value = node.child_value();\n char *t_value = (char *)malloc(strlen(v_value));\n memcpy(t_value, v_value, strlen(v_value));\n std::vector<int> splits;\n char *p = strtok(t_value, \",\");\n while (p != nullptr)\n {\n splits.push_back(atoi(p));\n p = strtok(nullptr, \",\");\n }\n std::unique_ptr<int[]> ints(new int[splits.size()]);\n for (uint32_t i = 0; i < splits.size(); ++i)\n {\n ints[i] = splits[i];\n }\n set.AddInt(v_value, std::move(ints), splits.size());\n}\n\nvoid PushFloatArray(ParamSet &set, const pugi::xml_node &node, const char *name = \"name\")\n{\n const char *v_name = node.attribute(name).as_string();\n const char *v_value = node.child_value();\n char *t_value = (char *)malloc(strlen(v_value));\n memcpy(t_value, v_value, strlen(v_value));\n std::vector<float> splits;\n char *p = strtok(t_value, \",\");\n while (p != nullptr)\n {\n splits.push_back(atof(p));\n p = strtok(nullptr, \",\");\n }\n std::unique_ptr<float[]> floats(new float[splits.size()]);\n for (uint32_t i = 0; i < splits.size(); ++i)\n {\n floats[i] = splits[i];\n }\n set.AddFloat(v_value, std::move(floats), splits.size());\n}\n\nvoid PushTexture(ParamSet &set, const pugi::xml_node &node, const char *name = \"name\")\n{\n const char *v_name = node.attribute(name).as_string();\n set.AddTexture(name, v_name);\n}\n\nvoid PushString(ParamSet &set, const pugi::xml_node &node, const char *name = \"name\")\n{\n const char *v_name = node.attribute(name).as_string();\n set.AddString(name, std::unique_ptr<std::string[]>(new std::string[1]{v_name}), 1);\n}\n\nvoid XMLBinder::PharseChildNodeParamSet(ParamSet &set, const pugi::xml_node &root) const\n{\n\n for (pugi::xml_node node = root.first_child(); node; node = node.next_sibling())\n {\n const char *name = node.name();\n if (strcmp(name, \"integer\") == 0)\n {\n \/\/单个整数\n PushInteger(set, node);\n }\n else if (strcmp(name, \"float\") == 0)\n {\n \/\/单个浮点数\n PushFloat(set, node);\n }\n else if (strcmp(name, \"bool\") == 0)\n {\n \/\/单个布尔值\n PushBool(set, node);\n }\n else if (strcmp(name, \"rgb\") == 0)\n {\n PushRGB(set, node);\n }\n else if (strcmp(name, \"point2f\") == 0)\n {\n PushPoint2f(set, node);\n }\n else if (strcmp(name, \"point3f\") == 0)\n {\n PushPoint3f(set, node);\n }\n else if (strcmp(name, \"vector2f\") == 0)\n {\n PushVector2f(set, node);\n }\n else if (strcmp(name, \"vector3f\") == 0)\n {\n PushVector3f(set, node);\n }\n else if (strcmp(name, \"normal3f\") == 0)\n {\n PushNormal3f(set, node);\n }\n else if (strcmp(name, \"integer_array\") == 0)\n {\n PushIntegetArray(set, node);\n }\n else if (strcmp(name, \"float_array\") == 0)\n {\n PushFloatArray(set, node);\n }\n else if (strcmp(name, \"texture\") == 0)\n {\n PushTexture(set, node);\n }\n else if (strcmp(name, \"string\") == 0)\n {\n \/\/字符串\n PushString(set, node);\n }\n }\n}\n\nvoid XMLBinder::ExecScript(const char *fileName)\n{\n pugi::xml_parse_result result = _doc.load_file(fileName);\n LInfo << \"Loading XML state:\" << result.description();\n auto root = _doc.first_child();\n if (strcmp(root.name(), \"Scene\") == 0)\n {\n \/\/开始解析scene层\n LInfo << \"->scene node\";\n for (pugi::xml_node node = root.first_child(); node; node = node.next_sibling())\n {\n const char *name = node.name();\n if (strcmp(name, \"WorldBegin\") == 0)\n {\n raidenWorldBegin();\n }\n else if (strcmp(name, \"WorldEnd\") == 0)\n {\n raidenWorldEnd();\n }\n else if (strcmp(name, \"Translate\") == 0)\n {\n float dx = node.attribute(\"x\").as_float();\n float dy = node.attribute(\"y\").as_float();\n float dz = node.attribute(\"z\").as_float();\n raidenTranslate(dx, dy, dz);\n }\n else if (strcmp(name, \"Rotate\") == 0)\n {\n float angle = node.attribute(\"angle\").as_float();\n float dx = node.attribute(\"x\").as_float();\n float dy = node.attribute(\"y\").as_float();\n float dz = node.attribute(\"z\").as_float();\n raidenRotate(angle, dx, dy, dz);\n }\n else if (strcmp(name, \"Scale\") == 0)\n {\n float dx = node.attribute(\"x\").as_float();\n float dy = node.attribute(\"y\").as_float();\n float dz = node.attribute(\"z\").as_float();\n raidenScale(dx, dy, dz);\n }\n else if (strcmp(name, \"CoordinateSystem\") == 0)\n {\n ParamSet params;\n auto frame_name = node.attribute(\"name\").as_string();\n raidenCoordinateSystem(frame_name);\n }\n else if (strcmp(name, \"CoordSysTransform\") == 0)\n {\n ParamSet params;\n auto frame_name = node.attribute(\"name\").as_string();\n raidenCoordSysTransform(frame_name);\n }\n \/\/TODO 和时间有关的API还没有绑定\n else if (strcmp(name, \"PixelFilter\") == 0)\n {\n ParamSet params;\n auto type = node.attribute(\"type\").as_string();\n PharseChildNodeParamSet(params, node);\n raidenPixelFilter(type, params);\n }\n else if (strcmp(name, \"Accelerator\") == 0)\n {\n ParamSet params;\n auto type = node.attribute(\"type\").as_string();\n PharseChildNodeParamSet(params, node);\n raidenAccelerator(type, params);\n }\n else if (strcmp(name, \"Integrator\") == 0)\n {\n LInfo << \"-->integrator node\";\n ParamSet params;\n auto type = node.attribute(\"type\").as_string();\n PharseChildNodeParamSet(params, node);\n raidenIntegrator(type, params);\n }\n else if (strcmp(name, \"Camera\") == 0)\n {\n ParamSet params;\n auto type = node.attribute(\"type\").as_string();\n PharseChildNodeParamSet(params, node);\n raidenCamera(type, params);\n }\n else if (strcmp(name, \"Film\") == 0)\n {\n ParamSet params;\n auto type = node.attribute(\"type\").as_string();\n PharseChildNodeParamSet(params, node);\n raidenFilm(type, params);\n }\n else if (strcmp(name, \"Sampler\") == 0)\n {\n ParamSet params;\n auto type = node.attribute(\"type\").as_string();\n PharseChildNodeParamSet(params, node);\n raidenSampler(type, params);\n }\n else if (strcmp(name, \"Shape\") == 0)\n {\n ParamSet params;\n auto type = node.attribute(\"type\").as_string();\n PharseChildNodeParamSet(params, node);\n raidenShape(type, params);\n }\n else if (strcmp(name, \"Texture\") == 0)\n {\n ParamSet params;\n auto t_name = node.attribute(\"name\").as_string();\n auto type = node.attribute(\"type\").as_string();\n auto src = node.attribute(\"source\").as_string();\n PharseChildNodeParamSet(params, node);\n raidenTexture(t_name, type, src, params);\n }\n else if (strcmp(name, \"MakeNamedMaterial\") == 0)\n {\n ParamSet params;\n auto t_name = node.attribute(\"name\").as_string();\n PushString(params, node, \"type\");\n PharseChildNodeParamSet(params, node);\n raidenMakeNamedMaterial(t_name, params);\n }\n else if (strcmp(name, \"Material\") == 0)\n {\n ParamSet params;\n auto type = node.attribute(\"type\").as_string();\n PharseChildNodeParamSet(params, node);\n raidenMaterial(type, params);\n }\n else if (strcmp(name, \"NamedMaterial\") == 0)\n {\n auto t_name = node.attribute(\"name\").as_string();\n raidenNamedMaterial(t_name);\n }\n else if (strcmp(name, \"TransformBegin\") == 0)\n {\n raidenTransformBegin();\n }\n else if (strcmp(name, \"TransformEnd\") == 0)\n {\n raidenTransformEnd();\n }\n else if (strcmp(name, \"LightSource\") == 0)\n {\n ParamSet params;\n auto type = node.attribute(\"type\").as_string();\n PharseChildNodeParamSet(params, node);\n raidenLightSource(type, params);\n }\n else if (strcmp(name, \"AreaLightSource\") == 0)\n {\n ParamSet params;\n auto type = node.attribute(\"type\").as_string();\n PharseChildNodeParamSet(params, node);\n raidenAreaLightSource(type,params);\n }\n }\n }\n else\n {\n LWarning << \"XML file must has a root node \\\"scene\\\" but \\\"\" << root << \"\\\" now\";\n }\n}<|endoftext|>"} {"text":"<commit_before>\/*\n * This file is part of the \"libstx\" project\n * Copyright (c) 2015 Paul Asmuth, FnordCorp B.V.\n *\n * FnordMetric is free software: you can redistribute it and\/or modify it under\n * the terms of the GNU General Public License v3.0. You should have received a\n * copy of the GNU General Public License along with this program. If not, see\n * <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n#include \"stx\/stdtypes.h\"\n#include \"stx\/rpc\/RPCRequest.h\"\n#include \"stx\/rpc\/RPCContext.h\"\n\nnamespace stx {\nnamespace rpc {\n\nRPCRequest::RPCRequest(\n Function<void (RPCContext* ctx)> call_fn) :\n call_fn_(call_fn),\n ready_(false),\n error_(nullptr),\n running_(false) {}\n\nvoid RPCRequest::run() {\n {\n std::unique_lock<std::mutex> lk(mutex_);\n if (ready_ || running_) {\n RAISE(kRuntimeError, \"refusing to run a finished\/running job\");\n }\n\n running_ = true;\n }\n\n RPCContext ctx(this);\n try {\n call_fn_(&ctx);\n } catch (const StandardException& e) {\n returnError(e);\n return;\n }\n\n return returnSuccess();\n}\n\nvoid RPCRequest::returnSuccess() {\n {\n std::unique_lock<std::mutex> lk(mutex_);\n ready_ = true;\n }\n\n cv_.notify_all();\n\n if (on_ready_) {\n on_ready_();\n }\n\n on_ready_ = nullptr;\n on_cancel_ = nullptr;\n on_event_.clear();\n}\n\nvoid RPCRequest::returnError(const StandardException& e) {\n try {\n auto rte = dynamic_cast<const stx::Exception&>(e);\n returnError(rte.getType(), rte.getMessage());\n } catch (const std::exception& cast_error) {\n returnError(kRuntimeError, e.what());\n }\n}\n\nvoid RPCRequest::returnError(ExceptionType error_type, const String& message) {\n std::unique_lock<std::mutex> lk(mutex_);\n if (ready_) {\n RAISE(kRuntimeError, \"refusing to send an error to a finished job\");\n }\n\n error_ = error_type;\n error_message_ = message;\n ready_ = true;\n lk.unlock();\n\n cv_.notify_all();\n\n if (on_ready_) {\n on_ready_();\n }\n\n on_ready_ = nullptr;\n on_cancel_ = nullptr;\n on_event_.clear();\n}\n\nvoid RPCRequest::cancel() {\n std::unique_lock<std::mutex> lk(mutex_);\n if (ready_) {\n return;\n }\n\n error_ = kCancelledError;\n error_message_ = \"RPCRequest cancelled\";\n ready_ = true;\n lk.unlock();\n\n cv_.notify_all();\n\n if (on_cancel_) {\n on_cancel_();\n }\n\n if (on_ready_) {\n on_ready_();\n }\n\n on_ready_ = nullptr;\n on_cancel_ = nullptr;\n on_event_.clear();\n}\n\nvoid RPCRequest::wait() const {\n std::unique_lock<std::mutex> lk(mutex_);\n\n while (!ready_) {\n cv_.wait(lk);\n }\n}\n\nbool RPCRequest::waitFor(const Duration& timeout) const {\n std::unique_lock<std::mutex> lk(mutex_);\n\n if (ready_) {\n return true;\n }\n\n cv_.wait_for(lk, std::chrono::microseconds(timeout.microseconds()));\n return ready_;\n}\n\n} \/\/ namespace rpc\n} \/\/ namespace stx\n\n<commit_msg>RPCRequest::onReady<commit_after>\/*\n * This file is part of the \"libstx\" project\n * Copyright (c) 2015 Paul Asmuth, FnordCorp B.V.\n *\n * FnordMetric is free software: you can redistribute it and\/or modify it under\n * the terms of the GNU General Public License v3.0. You should have received a\n * copy of the GNU General Public License along with this program. If not, see\n * <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n#include \"stx\/stdtypes.h\"\n#include \"stx\/rpc\/RPCRequest.h\"\n#include \"stx\/rpc\/RPCContext.h\"\n\nnamespace stx {\nnamespace rpc {\n\nRPCRequest::RPCRequest(\n Function<void (RPCContext* ctx)> call_fn) :\n call_fn_(call_fn),\n ready_(false),\n error_(nullptr),\n running_(false) {}\n\nvoid RPCRequest::run() {\n {\n std::unique_lock<std::mutex> lk(mutex_);\n if (ready_ || running_) {\n RAISE(kRuntimeError, \"refusing to run a finished\/running job\");\n }\n\n running_ = true;\n }\n\n RPCContext ctx(this);\n try {\n call_fn_(&ctx);\n } catch (const StandardException& e) {\n returnError(e);\n return;\n }\n\n return returnSuccess();\n}\n\nvoid RPCRequest::onReady(Function<void ()> fn) {\n std::unique_lock<std::mutex> lk(mutex_);\n\n if (ready_) {\n fn();\n } else {\n on_ready_ = fn;\n }\n}\n\nvoid RPCRequest::returnSuccess() {\n {\n std::unique_lock<std::mutex> lk(mutex_);\n ready_ = true;\n }\n\n cv_.notify_all();\n\n if (on_ready_) {\n on_ready_();\n }\n\n on_ready_ = nullptr;\n on_cancel_ = nullptr;\n on_event_.clear();\n}\n\nvoid RPCRequest::returnError(const StandardException& e) {\n try {\n auto rte = dynamic_cast<const stx::Exception&>(e);\n returnError(rte.getType(), rte.getMessage());\n } catch (const std::exception& cast_error) {\n returnError(kRuntimeError, e.what());\n }\n}\n\nvoid RPCRequest::returnError(ExceptionType error_type, const String& message) {\n std::unique_lock<std::mutex> lk(mutex_);\n if (ready_) {\n RAISE(kRuntimeError, \"refusing to send an error to a finished job\");\n }\n\n error_ = error_type;\n error_message_ = message;\n ready_ = true;\n lk.unlock();\n\n cv_.notify_all();\n\n if (on_ready_) {\n on_ready_();\n }\n\n on_ready_ = nullptr;\n on_cancel_ = nullptr;\n on_event_.clear();\n}\n\nvoid RPCRequest::cancel() {\n std::unique_lock<std::mutex> lk(mutex_);\n if (ready_) {\n return;\n }\n\n error_ = kCancelledError;\n error_message_ = \"RPCRequest cancelled\";\n ready_ = true;\n lk.unlock();\n\n cv_.notify_all();\n\n if (on_cancel_) {\n on_cancel_();\n }\n\n if (on_ready_) {\n on_ready_();\n }\n\n on_ready_ = nullptr;\n on_cancel_ = nullptr;\n on_event_.clear();\n}\n\nvoid RPCRequest::wait() const {\n std::unique_lock<std::mutex> lk(mutex_);\n\n while (!ready_) {\n cv_.wait(lk);\n }\n}\n\nbool RPCRequest::waitFor(const Duration& timeout) const {\n std::unique_lock<std::mutex> lk(mutex_);\n\n if (ready_) {\n return true;\n }\n\n cv_.wait_for(lk, std::chrono::microseconds(timeout.microseconds()));\n return ready_;\n}\n\n} \/\/ namespace rpc\n} \/\/ namespace stx\n\n<|endoftext|>"} {"text":"<commit_before>\/*******************************************************************************\nFILE : choose_enumerator_class.hpp\n\nLAST MODIFIED : 10 March 2007\n\nDESCRIPTION :\nClass for implementing an wxList dialog control for choosing an object\nfrom its manager (subject to an optional conditional function). Handles manager\nmessages to keep the menu up-to-date.\nCalls the client-specified callback routine if a different object is chosen.\n==============================================================================*\/\n\/* ***** BEGIN LICENSE BLOCK *****\n * Version: MPL 1.1\/GPL 2.0\/LGPL 2.1\n *\n * The contents of this file are subject to the Mozilla Public License Version\n * 1.1 (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n * http:\/\/www.mozilla.org\/MPL\/\n *\n * Software distributed under the License is distributed on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License\n * for the specific language governing rights and limitations under the\n * License.\n *\n * The Original Code is cmgui.\n *\n * The Initial Developer of the Original Code is\n * Auckland Uniservices Ltd, Auckland, New Zealand.\n * Portions created by the Initial Developer are Copyright (C) 2005\n * the Initial Developer. All Rights Reserved.\n *\n * Contributor(s):\n *\n * Alternatively, the contents of this file may be used under the terms of\n * either the GNU General Public License Version 2 or later (the \"GPL\"), or\n * the GNU Lesser General Public License Version 2.1 or later (the \"LGPL\"),\n * in which case the provisions of the GPL or the LGPL are applicable instead\n * of those above. If you wish to allow use of your version of this file only\n * under the terms of either the GPL or the LGPL, and not to allow others to\n * use your version of this file under the terms of the MPL, indicate your\n * decision by deleting the provisions above and replace them with the notice\n * and other provisions required by the GPL or the LGPL. If you do not delete\n * the provisions above, a recipient may use your version of this file under\n * the terms of any one of the MPL, the GPL or the LGPL.\n *\n * ***** END LICENSE BLOCK ***** *\/\n#if !defined (CHOOSE_ENUMERATOR_CLASS_H)\n#define CHOOSE_ENUMERATOR_CLASS_H\n\ntemplate < class Enumerator > class wxEnumeratorChooser : public wxChoice\n\/*****************************************************************************\nLAST MODIFIED : 8 February 2007\n\nDESCRIPTION :\n============================================================================*\/\n{\nprivate:\n\tCallback_base< typename Enumerator::Enumerator_type > *callback;\n\npublic:\n\twxEnumeratorChooser<Enumerator>(wxPanel *parent, \n\t\tint number_of_items, \n\t\tconst char **item_names, typename Enumerator::Enumerator_type current_value,\n\t\tUser_interface *user_interface) :\n\t\twxChoice(parent, \/*id*\/-1, wxPoint(0,0), wxSize(-1,-1))\n\t{\n\t\tUSE_PARAMETER(user_interface);\n\t\tbuild_main_menu(number_of_items, item_names, current_value);\n\n\t\tConnect(wxEVT_COMMAND_CHOICE_SELECTED,\n\t\t\twxCommandEventHandler(wxEnumeratorChooser::OnChoiceSelected));\n\n\t\twxBoxSizer *sizer = new wxBoxSizer( wxHORIZONTAL );\n\t\tsizer->Add(this,\n\t\t\twxSizerFlags(1).Align(wxALIGN_CENTER).Expand());\n\t\tparent->SetSizer(sizer);\n\n\t\tShow();\n\t}\n\n\tvoid OnChoiceSelected(wxCommandEvent& event)\n\t{\n\t\tUSE_PARAMETER(event);\n\t\tif (callback)\n\t\t{\n\t\t\tcallback->callback_function(get_item());\n\t\t}\n }\n\t\n\ttypename Enumerator::Enumerator_type get_item()\n\t{\n\t\treturn (static_cast<typename Enumerator::Enumerator_type>\n\t\t\t(GetSelection()));\n\t}\n\n\tint set_callback(Callback_base< typename Enumerator::Enumerator_type >\n\t\t*callback_object)\n\t{\n\t\tcallback = callback_object;\n\t\treturn (1);\n\t}\n\n\tint set_item(typename Enumerator::Enumerator_type new_value)\n\t{\n\t\tunsigned int return_code;\n\t\t\n\t\tSetSelection(new_value);\n\n\t\t\/\/ Could check to see that the value was actually set\n\t\treturn_code = 1;\n\n\t\treturn (return_code);\n\t}\n\n\tint build_main_menu(int number_of_items, \n\t\tconst char **item_names, \n\t\ttypename Enumerator::Enumerator_type current_value)\n\t{\n\t\tint i;\n\t\tClear();\n\t\tfor (i = 0 ; i < number_of_items ; i++)\n\t\t{\n\t\t\tAppend(item_names[i]);\n\t\t}\n\t\tSetSelection(current_value);\n\t\treturn 1;\n\t}\n};\n\ntemplate < class Enumerator > class Enumerator_chooser\n\/*****************************************************************************\nLAST MODIFIED : 10 March 2007\n\nDESCRIPTION :\n============================================================================*\/\n{\nprivate:\n\tEnumerator *enumerator;\n\twxPanel *parent;\n\ttypename Enumerator::Conditional_function *conditional_function;\n\tvoid *conditional_function_user_data;\n\twxEnumeratorChooser<Enumerator> *chooser;\n\tCallback_base< typename Enumerator::Enumerator_type > *update_callback;\n int number_of_items;\n const char **item_names;\n\npublic:\n\tEnumerator_chooser(wxPanel *parent,\n\t\ttypename Enumerator::Enumerator_type current_value,\n\t\ttypename Enumerator::Conditional_function *conditional_function,\n\t\tvoid *conditional_function_user_data,\n\t\tUser_interface *user_interface) :\n\t\tenumerator(new Enumerator()), parent(parent),\n\t\tconditional_function(conditional_function),\n\t\tconditional_function_user_data(conditional_function_user_data)\n\/*****************************************************************************\nLAST MODIFIED : 10 March 2007\n\nDESCRIPTION :\n============================================================================*\/\n\t{\n\t\tchooser = (wxEnumeratorChooser<Enumerator> *)NULL;\n\t\tupdate_callback = (Callback_base< typename Enumerator::Enumerator_type > *)NULL;\n\t\tnumber_of_items = 0;\n\t\titem_names = (const char **)NULL;\n\t\tif (build_items())\n\t\t{\n\t\t\tchooser = new wxEnumeratorChooser<Enumerator>\n\t\t\t\t(parent, number_of_items,\n\t\t\t\titem_names, current_value,\n\t\t\t\tuser_interface);\n\t\t\ttypedef int (Enumerator_chooser::*Member_function)(typename Enumerator::Enumerator_type);\n\t\t\tCallback_base<typename Enumerator::Enumerator_type> *callback = \n\t\t\t\tnew Callback_member_callback< typename Enumerator::Enumerator_type, \n\t\t\t\tEnumerator_chooser, Member_function>(\n\t\t\t\tthis, &Enumerator_chooser::chooser_callback);\n\t\t\t\t\n\t\t\tchooser->set_callback(callback);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tdisplay_message(ERROR_MESSAGE,\n\t\t\t\t\"Enumerator_chooser::Enumerator_chooser. \"\n\t\t\t\t\" Could not get items\");\n\t\t}\n\n\t} \/* Enumerator_chooser::Enumerator_chooser *\/\n\n\t~Enumerator_chooser()\n\/*****************************************************************************\nLAST MODIFIED : 8 February 2007\n\nDESCRIPTION :\n============================================================================*\/\n\t{\n\t\tif (chooser)\n\t\t{\n\t\t\t chooser->Destroy();\n\t\t}\n\t\t\n\t\tdelete enumerator;\n\t\tif (item_names)\n\t\t{\n\t\t\t \/\/ We only free the array, not the strings themselves for\n\t\t\t \/\/ strings from an enumerator\n\t\t\tDEALLOCATE(item_names);\n\t\t}\n\t} \/* Enumerator_chooser::~Enumerator_chooser() *\/\n\n\tint chooser_callback(typename Enumerator::Enumerator_type value)\n\/*****************************************************************************\nLAST MODIFIED : 8 February 2007\n\nDESCRIPTION :\nCalled by the \n============================================================================*\/\n\t{\n\t\tint return_code;\n\t\t\n\t\tif (update_callback)\n\t\t{\n\t\t\t\/* now call the procedure with the user data *\/\n\t\t\tupdate_callback->callback_function(value);\n\t\t}\n\t\treturn_code=1;\n\t\t\n\t\treturn (return_code);\n\t} \/* Enumerator_chooser::get_callback *\/\n\n\tCallback_base< typename Enumerator::Enumerator_type > *get_callback()\n\/*****************************************************************************\nLAST MODIFIED : 8 February 2007\n\nDESCRIPTION :\nReturns a pointer to the callback item.\n============================================================================*\/\n\t{\n\t\treturn update_callback;\n\t} \/* Enumerator_chooser::get_callback *\/\n\n\tint set_callback(Callback_base< typename Enumerator::Enumerator_type > *new_callback)\n\/*****************************************************************************\nLAST MODIFIED : 8 February 2007\n\nDESCRIPTION :\nChanges the callback item.\n============================================================================*\/\n\t{\n\t\tupdate_callback = new_callback;\n\t\treturn(1);\n\t} \/* Enumerator_chooser::set_callback *\/\n\n\ttypename Enumerator::Enumerator_type get_value()\n\/*****************************************************************************\nLAST MODIFIED : 8 February 2007\n\nDESCRIPTION :\nReturns the currently chosen object.\n============================================================================*\/\n\t{\n\t\treturn(chooser->get_item());\n\t} \/* Enumerator_chooser::get_object *\/\n\n\tint set_value(typename Enumerator::Enumerator_type new_value)\n\/*****************************************************************************\nLAST MODIFIED : 8 February 2007\n\nDESCRIPTION :\nChanges the chosen object in the choose_object_widget.\n============================================================================*\/\n\t{\n\t\treturn(chooser->set_item(new_value));\n\t} \/* Enumerator_chooser::set_object *\/\n\n\tint set_conditional_function(\n\t\ttypename Enumerator::Conditional_function *conditional_function,\n\t\tvoid *conditional_function_user_data, typename Enumerator::Enumerator_type new_value)\n\/*****************************************************************************\nLAST MODIFIED : 10 March 2007\n\nDESCRIPTION :\nChanges the conditional_function and user_data limiting the available\nselection of objects. Also allows new_object to be set simultaneously.\n============================================================================*\/\n\t{\n\t\tint return_code;\n\n\t\tconditional_function = conditional_function;\n\t\tconditional_function_user_data = conditional_function_user_data;\n\t\tif (build_items())\n\t\t{\n\t\t\treturn_code=chooser->build_main_menu(\n\t\t\t\tnumber_of_items, item_names, new_value);\n\t\t}\n\t\telse\n\t\t{\n\t\t\treturn_code=0;\n\t\t}\n\t\tif (!return_code)\n\t\t{\n\t\t\tdisplay_message(ERROR_MESSAGE,\n\t\t\t\t\"Enumerator_chooser::set_conditional_function\"\n\t\t\t\t\"Could not update menu\");\n\t\t}\n\t\treturn (return_code);\n\t} \/* Enumerator_chooser::set_conditional_function *\/\n\nprivate:\n\n\tint is_item_in_chooser(typename Enumerator::Enumerator_type value)\n\/*****************************************************************************\nLAST MODIFIED : 8 February 2007\n\nDESCRIPTION :\n============================================================================*\/\n\t{\n\t\tint i, return_code;\n\n\t\tif ((value > 0) && (value <= number_of_items))\n\t\t{\n\t\t\treturn_code = 1;\n\t\t}\n\t\telse\n\t\t{\n\t\t\treturn_code=0;\n\t\t}\n\n\t\treturn (return_code);\n\t} \/* Enumerator_chooser::is_item_in_chooser *\/\n\n\tint build_items()\n\/*****************************************************************************\nLAST MODIFIED : 8 February 2007\n\nDESCRIPTION :\nUpdates the arrays of all the choosable objects and their names.\n============================================================================*\/\n\t{\n\t\tint return_code;\n\n\t\tif (item_names)\n\t\t{\n\t\t\t \/\/ We only free the array, not the strings themselves for\n\t\t\t \/\/ strings from an enumerator\n\t\t\tDEALLOCATE(item_names);\n\t\t}\n\n\t\titem_names = enumerator->get_valid_strings(&number_of_items,\n\t\t\tconditional_function, conditional_function_user_data);\n\t\treturn_code = 1;\n\n\t\treturn (return_code);\n\t} \/* Enumerator_chooser::build_items *\/\n\n}; \/* template < class Managed_object > class Enumerator_chooser *\/\n\n#endif \/* !defined (CHOOSE_ENUMERATOR_CLASS_H) *\/\n<commit_msg>Fixed enumerator chooser hold on to an callback object and do not release it at the end. Tracker item 2610, https:\/\/tracker.physiomeproject.org\/show_bug.cgi?id=2610<commit_after>\/*******************************************************************************\nFILE : choose_enumerator_class.hpp\n\nLAST MODIFIED : 10 March 2007\n\nDESCRIPTION :\nClass for implementing an wxList dialog control for choosing an object\nfrom its manager (subject to an optional conditional function). Handles manager\nmessages to keep the menu up-to-date.\nCalls the client-specified callback routine if a different object is chosen.\n==============================================================================*\/\n\/* ***** BEGIN LICENSE BLOCK *****\n * Version: MPL 1.1\/GPL 2.0\/LGPL 2.1\n *\n * The contents of this file are subject to the Mozilla Public License Version\n * 1.1 (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n * http:\/\/www.mozilla.org\/MPL\/\n *\n * Software distributed under the License is distributed on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License\n * for the specific language governing rights and limitations under the\n * License.\n *\n * The Original Code is cmgui.\n *\n * The Initial Developer of the Original Code is\n * Auckland Uniservices Ltd, Auckland, New Zealand.\n * Portions created by the Initial Developer are Copyright (C) 2005\n * the Initial Developer. All Rights Reserved.\n *\n * Contributor(s):\n *\n * Alternatively, the contents of this file may be used under the terms of\n * either the GNU General Public License Version 2 or later (the \"GPL\"), or\n * the GNU Lesser General Public License Version 2.1 or later (the \"LGPL\"),\n * in which case the provisions of the GPL or the LGPL are applicable instead\n * of those above. If you wish to allow use of your version of this file only\n * under the terms of either the GPL or the LGPL, and not to allow others to\n * use your version of this file under the terms of the MPL, indicate your\n * decision by deleting the provisions above and replace them with the notice\n * and other provisions required by the GPL or the LGPL. If you do not delete\n * the provisions above, a recipient may use your version of this file under\n * the terms of any one of the MPL, the GPL or the LGPL.\n *\n * ***** END LICENSE BLOCK ***** *\/\n#if !defined (CHOOSE_ENUMERATOR_CLASS_H)\n#define CHOOSE_ENUMERATOR_CLASS_H\n\ntemplate < class Enumerator > class wxEnumeratorChooser : public wxChoice\n\/*****************************************************************************\nLAST MODIFIED : 8 February 2007\n\nDESCRIPTION :\n============================================================================*\/\n{\nprivate:\n\tCallback_base< typename Enumerator::Enumerator_type > *callback;\n\npublic:\n\twxEnumeratorChooser<Enumerator>(wxPanel *parent, \n\t\tint number_of_items, \n\t\tconst char **item_names, typename Enumerator::Enumerator_type current_value,\n\t\tUser_interface *user_interface) :\n\t\twxChoice(parent, \/*id*\/-1, wxPoint(0,0), wxSize(-1,-1))\n\t{\n\t\tUSE_PARAMETER(user_interface);\n\t\tcallback = NULL;\n\t\tbuild_main_menu(number_of_items, item_names, current_value);\n\n\t\tConnect(wxEVT_COMMAND_CHOICE_SELECTED,\n\t\t\twxCommandEventHandler(wxEnumeratorChooser::OnChoiceSelected));\n\n\t\twxBoxSizer *sizer = new wxBoxSizer( wxHORIZONTAL );\n\t\tsizer->Add(this,\n\t\t\twxSizerFlags(1).Align(wxALIGN_CENTER).Expand());\n\t\tparent->SetSizer(sizer);\n\n\t\tShow();\n\t}\n\n\t~wxEnumeratorChooser<Enumerator>()\n\t\t{\n\t\t\tif (callback)\n\t\t\t\tdelete callback;\n\t\t}\n\n\tvoid OnChoiceSelected(wxCommandEvent& event)\n\t{\n\t\tUSE_PARAMETER(event);\n\t\tif (callback)\n\t\t{\n\t\t\tcallback->callback_function(get_item());\n\t\t}\n }\n\t\n\ttypename Enumerator::Enumerator_type get_item()\n\t{\n\t\treturn (static_cast<typename Enumerator::Enumerator_type>\n\t\t\t(GetSelection()));\n\t}\n\n\tint set_callback(Callback_base< typename Enumerator::Enumerator_type >\n\t\t*callback_object)\n\t{\n\t\tif (callback)\n\t\t\tdelete callback;\n\t\tcallback = callback_object;\n\t\treturn (1);\n\t}\n\n\tint set_item(typename Enumerator::Enumerator_type new_value)\n\t{\n\t\tunsigned int return_code;\n\t\t\n\t\tSetSelection(new_value);\n\n\t\t\/\/ Could check to see that the value was actually set\n\t\treturn_code = 1;\n\n\t\treturn (return_code);\n\t}\n\n\tint build_main_menu(int number_of_items, \n\t\tconst char **item_names, \n\t\ttypename Enumerator::Enumerator_type current_value)\n\t{\n\t\tint i;\n\t\tClear();\n\t\tfor (i = 0 ; i < number_of_items ; i++)\n\t\t{\n\t\t\tAppend(item_names[i]);\n\t\t}\n\t\tSetSelection(current_value);\n\t\treturn 1;\n\t}\n};\n\ntemplate < class Enumerator > class Enumerator_chooser\n\/*****************************************************************************\nLAST MODIFIED : 10 March 2007\n\nDESCRIPTION :\n============================================================================*\/\n{\nprivate:\n\tEnumerator *enumerator;\n\twxPanel *parent;\n\ttypename Enumerator::Conditional_function *conditional_function;\n\tvoid *conditional_function_user_data;\n\twxEnumeratorChooser<Enumerator> *chooser;\n\tCallback_base< typename Enumerator::Enumerator_type > *update_callback;\n int number_of_items;\n const char **item_names;\n\npublic:\n\tEnumerator_chooser(wxPanel *parent,\n\t\ttypename Enumerator::Enumerator_type current_value,\n\t\ttypename Enumerator::Conditional_function *conditional_function,\n\t\tvoid *conditional_function_user_data,\n\t\tUser_interface *user_interface) :\n\t\tenumerator(new Enumerator()), parent(parent),\n\t\tconditional_function(conditional_function),\n\t\tconditional_function_user_data(conditional_function_user_data)\n\/*****************************************************************************\nLAST MODIFIED : 10 March 2007\n\nDESCRIPTION :\n============================================================================*\/\n\t{\n\t\tchooser = (wxEnumeratorChooser<Enumerator> *)NULL;\n\t\tupdate_callback = (Callback_base< typename Enumerator::Enumerator_type > *)NULL;\n\t\tnumber_of_items = 0;\n\t\titem_names = (const char **)NULL;\n\t\tif (build_items())\n\t\t{\n\t\t\tchooser = new wxEnumeratorChooser<Enumerator>\n\t\t\t\t(parent, number_of_items,\n\t\t\t\titem_names, current_value,\n\t\t\t\tuser_interface);\n\t\t\ttypedef int (Enumerator_chooser::*Member_function)(typename Enumerator::Enumerator_type);\n\t\t\tCallback_base<typename Enumerator::Enumerator_type> *callback = \n\t\t\t\tnew Callback_member_callback< typename Enumerator::Enumerator_type, \n\t\t\t\tEnumerator_chooser, Member_function>(\n\t\t\t\tthis, &Enumerator_chooser::chooser_callback);\n\t\t\t\t\n\t\t\tchooser->set_callback(callback);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tdisplay_message(ERROR_MESSAGE,\n\t\t\t\t\"Enumerator_chooser::Enumerator_chooser. \"\n\t\t\t\t\" Could not get items\");\n\t\t}\n\n\t} \/* Enumerator_chooser::Enumerator_chooser *\/\n\n\t~Enumerator_chooser()\n\/*****************************************************************************\nLAST MODIFIED : 8 February 2007\n\nDESCRIPTION :\n============================================================================*\/\n\t{\n\t\tif (chooser)\n\t\t{\n\t\t\t chooser->Destroy();\n\t\t}\n\t\tif (update_callback)\n\t\t\tdelete update_callback;\n\t\tdelete enumerator;\n\t\tif (item_names)\n\t\t{\n\t\t\t \/\/ We only free the array, not the strings themselves for\n\t\t\t \/\/ strings from an enumerator\n\t\t\tDEALLOCATE(item_names);\n\t\t}\n\t} \/* Enumerator_chooser::~Enumerator_chooser() *\/\n\n\tint chooser_callback(typename Enumerator::Enumerator_type value)\n\/*****************************************************************************\nLAST MODIFIED : 8 February 2007\n\nDESCRIPTION :\nCalled by the \n============================================================================*\/\n\t{\n\t\tint return_code;\n\t\t\n\t\tif (update_callback)\n\t\t{\n\t\t\t\/* now call the procedure with the user data *\/\n\t\t\tupdate_callback->callback_function(value);\n\t\t}\n\t\treturn_code=1;\n\t\t\n\t\treturn (return_code);\n\t} \/* Enumerator_chooser::get_callback *\/\n\n\tCallback_base< typename Enumerator::Enumerator_type > *get_callback()\n\/*****************************************************************************\nLAST MODIFIED : 8 February 2007\n\nDESCRIPTION :\nReturns a pointer to the callback item.\n============================================================================*\/\n\t{\n\t\treturn update_callback;\n\t} \/* Enumerator_chooser::get_callback *\/\n\n\tint set_callback(Callback_base< typename Enumerator::Enumerator_type > *new_callback)\n\/*****************************************************************************\nLAST MODIFIED : 8 February 2007\n\nDESCRIPTION :\nChanges the callback item.\n============================================================================*\/\n\t{\n\t\tif (update_callback)\n\t\t{\n\t\t\tdelete update_callback;\n\t\t}\n\t\tupdate_callback = new_callback;\n\t\treturn(1);\n\t} \/* Enumerator_chooser::set_callback *\/\n\n\ttypename Enumerator::Enumerator_type get_value()\n\/*****************************************************************************\nLAST MODIFIED : 8 February 2007\n\nDESCRIPTION :\nReturns the currently chosen object.\n============================================================================*\/\n\t{\n\t\treturn(chooser->get_item());\n\t} \/* Enumerator_chooser::get_object *\/\n\n\tint set_value(typename Enumerator::Enumerator_type new_value)\n\/*****************************************************************************\nLAST MODIFIED : 8 February 2007\n\nDESCRIPTION :\nChanges the chosen object in the choose_object_widget.\n============================================================================*\/\n\t{\n\t\treturn(chooser->set_item(new_value));\n\t} \/* Enumerator_chooser::set_object *\/\n\n\tint set_conditional_function(\n\t\ttypename Enumerator::Conditional_function *conditional_function,\n\t\tvoid *conditional_function_user_data, typename Enumerator::Enumerator_type new_value)\n\/*****************************************************************************\nLAST MODIFIED : 10 March 2007\n\nDESCRIPTION :\nChanges the conditional_function and user_data limiting the available\nselection of objects. Also allows new_object to be set simultaneously.\n============================================================================*\/\n\t{\n\t\tint return_code;\n\n\t\tconditional_function = conditional_function;\n\t\tconditional_function_user_data = conditional_function_user_data;\n\t\tif (build_items())\n\t\t{\n\t\t\treturn_code=chooser->build_main_menu(\n\t\t\t\tnumber_of_items, item_names, new_value);\n\t\t}\n\t\telse\n\t\t{\n\t\t\treturn_code=0;\n\t\t}\n\t\tif (!return_code)\n\t\t{\n\t\t\tdisplay_message(ERROR_MESSAGE,\n\t\t\t\t\"Enumerator_chooser::set_conditional_function\"\n\t\t\t\t\"Could not update menu\");\n\t\t}\n\t\treturn (return_code);\n\t} \/* Enumerator_chooser::set_conditional_function *\/\n\nprivate:\n\n\tint is_item_in_chooser(typename Enumerator::Enumerator_type value)\n\/*****************************************************************************\nLAST MODIFIED : 8 February 2007\n\nDESCRIPTION :\n============================================================================*\/\n\t{\n\t\tint i, return_code;\n\n\t\tif ((value > 0) && (value <= number_of_items))\n\t\t{\n\t\t\treturn_code = 1;\n\t\t}\n\t\telse\n\t\t{\n\t\t\treturn_code=0;\n\t\t}\n\n\t\treturn (return_code);\n\t} \/* Enumerator_chooser::is_item_in_chooser *\/\n\n\tint build_items()\n\/*****************************************************************************\nLAST MODIFIED : 8 February 2007\n\nDESCRIPTION :\nUpdates the arrays of all the choosable objects and their names.\n============================================================================*\/\n\t{\n\t\tint return_code;\n\n\t\tif (item_names)\n\t\t{\n\t\t\t \/\/ We only free the array, not the strings themselves for\n\t\t\t \/\/ strings from an enumerator\n\t\t\tDEALLOCATE(item_names);\n\t\t}\n\n\t\titem_names = enumerator->get_valid_strings(&number_of_items,\n\t\t\tconditional_function, conditional_function_user_data);\n\t\treturn_code = 1;\n\n\t\treturn (return_code);\n\t} \/* Enumerator_chooser::build_items *\/\n\n}; \/* template < class Managed_object > class Enumerator_chooser *\/\n\n#endif \/* !defined (CHOOSE_ENUMERATOR_CLASS_H) *\/\n<|endoftext|>"} {"text":"<commit_before>\/\/ -*- coding: utf-8 -*-\n\/\/ Copyright (C) 2012-2014 MUJIN Inc. <rosen.diankov@mujin.co.jp>\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \"common.h\"\n#include \"controllerclientimpl.h\"\n#include \"binpickingtaskzmq.h\"\n#include <boost\/property_tree\/json_parser.hpp>\n#include <boost\/property_tree\/exceptions.hpp>\n#include \"mujincontrollerclient\/mujinzmq.h\"\n\n#include <algorithm> \/\/ find\n\n#include \"logging.h\"\n\nMUJIN_LOGGER(\"mujin.controllerclientcpp.binpickingtask.zmq\");\n\nnamespace\n{\nvoid ConvertTimestampToFloat(const std::string& in,\n std::stringstream& outss)\n{\n const std::size_t len = in.size();\n std::size_t processed = 0;\n while (processed != std::string::npos && processed < len) {\n const std::size_t deltabegin = in.substr(processed, len).find(\"\\\"timestamp\\\":\");\n if (deltabegin == std::string::npos) {\n outss << in.substr(processed, len);\n return;\n }\n const std::size_t timestampbegin = processed + deltabegin;\n const std::size_t comma = in.substr(timestampbegin, len).find(\",\");\n const std::size_t closingCurly = in.substr(timestampbegin, len).find(\"}\");\n if (comma == std::string::npos && closingCurly == std::string::npos)\n {\n throw mujinclient::MujinException(boost::str(boost::format(\"error while converting timestamp value format for %s\")%in), mujinclient::MEC_Failed);\n }\n const std::size_t timestampend = timestampbegin + std::min(comma, closingCurly);\n if (timestampend == std::string::npos) {\n throw mujinclient::MujinException(boost::str(boost::format(\"error while converting timestamp value format for %s\")%in), mujinclient::MEC_Failed);\n }\n const std::size_t period = in.substr(timestampbegin, len).find(\".\");\n\n if (period == std::string::npos || timestampbegin + period > timestampend) {\n \/\/ no comma, assume this is in integet format. so add period to make it a float format.\n outss << in.substr(processed, timestampend - processed) << \".\";\n }\n else {\n \/\/ already floating format. keep it that way\n outss << in.substr(processed, timestampend - processed);\n }\n processed = timestampend;\n }\n}\n}\n\nnamespace mujinclient {\nusing namespace utils;\n\nclass ZmqMujinControllerClient : public mujinzmq::ZmqClient\n{\n\npublic:\n ZmqMujinControllerClient(boost::shared_ptr<zmq::context_t> context, const std::string& host, const int port);\n\n virtual ~ZmqMujinControllerClient();\n\n};\n\nZmqMujinControllerClient::ZmqMujinControllerClient(boost::shared_ptr<zmq::context_t> context, const std::string& host, const int port) : ZmqClient(host, port)\n{\n _InitializeSocket(context);\n}\n\nZmqMujinControllerClient::~ZmqMujinControllerClient()\n{\n \/\/ _DestroySocket() is called in ~ZmqClient()\n}\n\nBinPickingTaskZmqResource::BinPickingTaskZmqResource(ControllerClientPtr c, const std::string& pk, const std::string& scenepk, const std::string& tasktype) : BinPickingTaskResource(c, pk, scenepk, tasktype)\n{\n}\n\nBinPickingTaskZmqResource::~BinPickingTaskZmqResource()\n{\n}\n\nvoid BinPickingTaskZmqResource::Initialize(const std::string& defaultTaskParameters, const int zmqPort, const int heartbeatPort, boost::shared_ptr<zmq::context_t> zmqcontext, const bool initializezmq, const double reinitializetimeout, const double timeout, const std::string& userinfo, const std::string& slaverequestid)\n{\n BinPickingTaskResource::Initialize(defaultTaskParameters, zmqPort, heartbeatPort, zmqcontext, initializezmq, reinitializetimeout, timeout, userinfo, slaverequestid);\n \n if (initializezmq) {\n InitializeZMQ(reinitializetimeout, timeout);\n }\n\n _zmqmujincontrollerclient.reset(new ZmqMujinControllerClient(_zmqcontext, _mujinControllerIp, _zmqPort));\n if (!_zmqmujincontrollerclient) {\n throw MujinException(boost::str(boost::format(\"Failed to establish ZMQ connection to mujin controller at %s:%d\")%_mujinControllerIp%_zmqPort), MEC_Failed);\n }\n if (!_pHeartbeatMonitorThread) {\n _bShutdownHeartbeatMonitor = false;\n if (reinitializetimeout > 0 ) {\n _pHeartbeatMonitorThread.reset(new boost::thread(boost::bind(&BinPickingTaskZmqResource::_HeartbeatMonitorThread, this, reinitializetimeout, timeout)));\n }\n }\n}\n\nboost::property_tree::ptree BinPickingTaskZmqResource::ExecuteCommand(const std::string& taskparameters, const double timeout \/* [sec] *\/, const bool getresult)\n{\n if (!_bIsInitialized) {\n throw MujinException(\"BinPicking task is not initialized, please call Initialzie() first.\", MEC_Failed);\n }\n\n if (!_zmqmujincontrollerclient) {\n MUJIN_LOG_ERROR(\"zmqcontrollerclient is not initialized! initialize\");\n _zmqmujincontrollerclient.reset(new ZmqMujinControllerClient(_zmqcontext, _mujinControllerIp, _zmqPort));\n }\n\n std::stringstream ss;\n ss << \"{\\\"fnname\\\": \\\"\";\n if (_tasktype == \"binpicking\") {\n ss << \"binpicking.\";\n }\n ss << \"RunCommand\\\", \\\"taskparams\\\": {\\\"tasktype\\\": \\\"\" << _tasktype << \"\\\", \";\n\n ss << \"\\\"taskparameters\\\": \" << taskparameters << \", \";\n ss << \"\\\"sceneparams\\\": \" << _sceneparams_json << \"}, \";\n ss << \"\\\"userinfo\\\": \" << _userinfo_json;\n if (_slaverequestid != \"\") {\n ss << \", \" << GetJsonString(\"slaverequestid\", _slaverequestid);\n }\n ss << \"}\";\n std::string command = ss.str();\n \/\/ std::cout << \"Sending \" << command << \" from \" << __func__ << std::endl;\n\n \/\/std::string task = \"{\\\"tasktype\\\": \\\"binpicking\\\", \\\"taskparameters\\\": \" + command + \"}\";\n boost::property_tree::ptree pt;\n if (getresult) {\n std::stringstream result_ss;\n\n try{\n result_ss << _zmqmujincontrollerclient->Call(command, timeout);\n }\n catch (const MujinException& e) {\n MUJIN_LOG_ERROR(e.what());\n if (e.GetCode() == MEC_ZMQNoResponse) {\n MUJIN_LOG_INFO(\"reinitializing zmq connection with the slave\");\n _zmqmujincontrollerclient.reset(new ZmqMujinControllerClient(_zmqcontext, _mujinControllerIp, _zmqPort));\n if (!_zmqmujincontrollerclient) {\n throw MujinException(boost::str(boost::format(\"Failed to establish ZMQ connection to mujin controller at %s:%d\")%_mujinControllerIp%_zmqPort), MEC_Failed);\n }\n }\n }\n\n try {\n \/\/ temporary fix until we move on to rapid json\n std::stringstream result_ss_float_timestamp;\n ConvertTimestampToFloat(result_ss.str(), result_ss_float_timestamp);\n std::cout << result_ss.str() << std::endl\n << result_ss_float_timestamp.str() << std::endl;\n boost::property_tree::read_json(result_ss_float_timestamp, pt);\n boost::property_tree::ptree::const_assoc_iterator iterror = pt.find(\"error\");\n if( iterror != pt.not_found() ) {\n boost::optional<std::string> erroroptional = iterror->second.get_optional<std::string>(\"errorcode\");\n boost::optional<std::string> descriptionoptional = iterror->second.get_optional<std::string>(\"description\");\n if (!!erroroptional && erroroptional.get().size() > 0 ) {\n std::string serror;\n if (!!descriptionoptional && descriptionoptional.get().size() > 0 ) {\n serror = descriptionoptional.get();\n }\n else {\n serror = erroroptional.get();\n }\n if( serror.size() > 1000 ) {\n MUJIN_LOG_ERROR(str(boost::format(\"truncated original error message from %d\")%serror.size()));\n serror = serror.substr(0,1000);\n }\n \n throw MujinException(str(boost::format(\"Error when calling binpicking.RunCommand: %s\")%serror), MEC_BinPickingError);\n }\n }\n } catch (boost::property_tree::ptree_error& e) {\n throw MujinException(boost::str(boost::format(\"Failed to parse json which is received from mujin controller: \\nreceived message: %s \\nerror message: %s\")%result_ss.str()%e.what()), MEC_Failed);\n }\n } else {\n try{\n _zmqmujincontrollerclient->Call(command, timeout);\n \/\/ TODO since not getting response, internal zmq will be in a bad state, have to recreate\n }\n catch (const MujinException& e) {\n MUJIN_LOG_ERROR(e.what());\n if (e.GetCode() == MEC_ZMQNoResponse) {\n MUJIN_LOG_INFO(\"reinitializing zmq connection with the slave\");\n _zmqmujincontrollerclient.reset(new ZmqMujinControllerClient(_zmqcontext, _mujinControllerIp, _zmqPort));\n if (!_zmqmujincontrollerclient) {\n throw MujinException(boost::str(boost::format(\"Failed to establish ZMQ connection to mujin controller at %s:%d\")%_mujinControllerIp%_zmqPort), MEC_Failed);\n }\n }\n }\n }\n return pt;\n}\n\nvoid BinPickingTaskZmqResource::InitializeZMQ(const double reinitializetimeout, const double timeout)\n{\n}\n\nvoid BinPickingTaskZmqResource::_HeartbeatMonitorThread(const double reinitializetimeout, const double commandtimeout)\n{\n boost::shared_ptr<zmq::socket_t> socket;\n boost::property_tree::ptree pt;\n BinPickingTaskResource::ResultHeartBeat heartbeat;\n heartbeat._slaverequestid = _slaverequestid;\n while (!_bShutdownHeartbeatMonitor) {\n if (!!socket) {\n socket->close();\n socket.reset();\n }\n socket.reset(new zmq::socket_t((*_zmqcontext.get()),ZMQ_SUB));\n std::stringstream ss;\n ss << _heartbeatPort;\n socket->connect ((\"tcp:\/\/\"+ _mujinControllerIp+\":\"+ss.str()).c_str());\n socket->setsockopt(ZMQ_SUBSCRIBE, \"\", 0);\n\n zmq::pollitem_t pollitem;\n memset(&pollitem, 0, sizeof(zmq::pollitem_t));\n pollitem.socket = socket->operator void*();\n pollitem.events = ZMQ_POLLIN;\n unsigned long long lastheartbeat = GetMilliTime();\n while (!_bShutdownHeartbeatMonitor && (GetMilliTime() - lastheartbeat) \/ 1000.0f < reinitializetimeout) {\n zmq::poll(&pollitem,1, 50); \/\/ wait 50 ms for message\n if (pollitem.revents & ZMQ_POLLIN) {\n zmq::message_t reply;\n socket->recv(&reply);\n std::string replystring((char *) reply.data (), (size_t) reply.size()); \n#ifdef _WIN32\n \/\/ sometimes buffer can container \\n or \\\\, which windows boost property_tree does not like\n std::string newbuffer;\n std::vector< std::pair<std::string, std::string> > serachpairs(1);\n serachpairs[0].first = \"\\\\\"; serachpairs[0].second = \"\";\n SearchAndReplace(newbuffer, replystring, serachpairs);\n std::stringstream replystring_ss(newbuffer);\n#else\n std::stringstream replystring_ss(replystring);\n#endif\n try{\n boost::property_tree::read_json(replystring_ss, pt);\n }\n catch (std::exception const &e) {\n MUJIN_LOG_ERROR(\"HeartBeat reply is not JSON\");\n MUJIN_LOG_ERROR(e.what());\n continue;\n }\n heartbeat.Parse(pt);\n {\n boost::mutex::scoped_lock lock(_mutexTaskState);\n _taskstate = heartbeat.taskstate;\n }\n \/\/BINPICKING_LOG_ERROR(replystring);\n\n if (heartbeat.status != std::string(\"lost\") && heartbeat.status.size() > 1) {\n lastheartbeat = GetMilliTime();\n }\n }\n }\n if (!_bShutdownHeartbeatMonitor) {\n std::stringstream ss;\n ss << (double)((GetMilliTime() - lastheartbeat)\/1000.0f) << \" seconds passed since last heartbeat signal, re-intializing ZMQ server.\";\n MUJIN_LOG_INFO(ss.str());\n }\n }\n}\n\n \n\n} \/\/ end namespace mujinclient\n<commit_msg>compile error fix for windows<commit_after>\/\/ -*- coding: utf-8 -*-\n\/\/ Copyright (C) 2012-2014 MUJIN Inc. <rosen.diankov@mujin.co.jp>\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \"common.h\"\n#include \"controllerclientimpl.h\"\n#include \"binpickingtaskzmq.h\"\n#include <boost\/property_tree\/json_parser.hpp>\n#include <boost\/property_tree\/exceptions.hpp>\n#include \"mujincontrollerclient\/mujinzmq.h\"\n\n#include <algorithm> \/\/ find\n\n#include \"logging.h\"\n\nMUJIN_LOGGER(\"mujin.controllerclientcpp.binpickingtask.zmq\");\n\nnamespace\n{\nvoid ConvertTimestampToFloat(const std::string& in,\n std::stringstream& outss)\n{\n const std::size_t len = in.size();\n std::size_t processed = 0;\n while (processed != std::string::npos && processed < len) {\n const std::size_t deltabegin = in.substr(processed, len).find(\"\\\"timestamp\\\":\");\n if (deltabegin == std::string::npos) {\n outss << in.substr(processed, len);\n return;\n }\n const std::size_t timestampbegin = processed + deltabegin;\n const std::size_t comma = in.substr(timestampbegin, len).find(\",\");\n const std::size_t closingCurly = in.substr(timestampbegin, len).find(\"}\");\n if (comma == std::string::npos && closingCurly == std::string::npos)\n {\n throw mujinclient::MujinException(boost::str(boost::format(\"error while converting timestamp value format for %s\")%in), mujinclient::MEC_Failed);\n }\n const std::size_t timestampend = timestampbegin + (comma < closingCurly ? comma : closingCurly);\n if (timestampend == std::string::npos) {\n throw mujinclient::MujinException(boost::str(boost::format(\"error while converting timestamp value format for %s\")%in), mujinclient::MEC_Failed);\n }\n const std::size_t period = in.substr(timestampbegin, len).find(\".\");\n\n if (period == std::string::npos || timestampbegin + period > timestampend) {\n \/\/ no comma, assume this is in integet format. so add period to make it a float format.\n outss << in.substr(processed, timestampend - processed) << \".\";\n }\n else {\n \/\/ already floating format. keep it that way\n outss << in.substr(processed, timestampend - processed);\n }\n processed = timestampend;\n }\n}\n}\n\nnamespace mujinclient {\nusing namespace utils;\n\nclass ZmqMujinControllerClient : public mujinzmq::ZmqClient\n{\n\npublic:\n ZmqMujinControllerClient(boost::shared_ptr<zmq::context_t> context, const std::string& host, const int port);\n\n virtual ~ZmqMujinControllerClient();\n\n};\n\nZmqMujinControllerClient::ZmqMujinControllerClient(boost::shared_ptr<zmq::context_t> context, const std::string& host, const int port) : ZmqClient(host, port)\n{\n _InitializeSocket(context);\n}\n\nZmqMujinControllerClient::~ZmqMujinControllerClient()\n{\n \/\/ _DestroySocket() is called in ~ZmqClient()\n}\n\nBinPickingTaskZmqResource::BinPickingTaskZmqResource(ControllerClientPtr c, const std::string& pk, const std::string& scenepk, const std::string& tasktype) : BinPickingTaskResource(c, pk, scenepk, tasktype)\n{\n}\n\nBinPickingTaskZmqResource::~BinPickingTaskZmqResource()\n{\n}\n\nvoid BinPickingTaskZmqResource::Initialize(const std::string& defaultTaskParameters, const int zmqPort, const int heartbeatPort, boost::shared_ptr<zmq::context_t> zmqcontext, const bool initializezmq, const double reinitializetimeout, const double timeout, const std::string& userinfo, const std::string& slaverequestid)\n{\n BinPickingTaskResource::Initialize(defaultTaskParameters, zmqPort, heartbeatPort, zmqcontext, initializezmq, reinitializetimeout, timeout, userinfo, slaverequestid);\n \n if (initializezmq) {\n InitializeZMQ(reinitializetimeout, timeout);\n }\n\n _zmqmujincontrollerclient.reset(new ZmqMujinControllerClient(_zmqcontext, _mujinControllerIp, _zmqPort));\n if (!_zmqmujincontrollerclient) {\n throw MujinException(boost::str(boost::format(\"Failed to establish ZMQ connection to mujin controller at %s:%d\")%_mujinControllerIp%_zmqPort), MEC_Failed);\n }\n if (!_pHeartbeatMonitorThread) {\n _bShutdownHeartbeatMonitor = false;\n if (reinitializetimeout > 0 ) {\n _pHeartbeatMonitorThread.reset(new boost::thread(boost::bind(&BinPickingTaskZmqResource::_HeartbeatMonitorThread, this, reinitializetimeout, timeout)));\n }\n }\n}\n\nboost::property_tree::ptree BinPickingTaskZmqResource::ExecuteCommand(const std::string& taskparameters, const double timeout \/* [sec] *\/, const bool getresult)\n{\n if (!_bIsInitialized) {\n throw MujinException(\"BinPicking task is not initialized, please call Initialzie() first.\", MEC_Failed);\n }\n\n if (!_zmqmujincontrollerclient) {\n MUJIN_LOG_ERROR(\"zmqcontrollerclient is not initialized! initialize\");\n _zmqmujincontrollerclient.reset(new ZmqMujinControllerClient(_zmqcontext, _mujinControllerIp, _zmqPort));\n }\n\n std::stringstream ss;\n ss << \"{\\\"fnname\\\": \\\"\";\n if (_tasktype == \"binpicking\") {\n ss << \"binpicking.\";\n }\n ss << \"RunCommand\\\", \\\"taskparams\\\": {\\\"tasktype\\\": \\\"\" << _tasktype << \"\\\", \";\n\n ss << \"\\\"taskparameters\\\": \" << taskparameters << \", \";\n ss << \"\\\"sceneparams\\\": \" << _sceneparams_json << \"}, \";\n ss << \"\\\"userinfo\\\": \" << _userinfo_json;\n if (_slaverequestid != \"\") {\n ss << \", \" << GetJsonString(\"slaverequestid\", _slaverequestid);\n }\n ss << \"}\";\n std::string command = ss.str();\n \/\/ std::cout << \"Sending \" << command << \" from \" << __func__ << std::endl;\n\n \/\/std::string task = \"{\\\"tasktype\\\": \\\"binpicking\\\", \\\"taskparameters\\\": \" + command + \"}\";\n boost::property_tree::ptree pt;\n if (getresult) {\n std::stringstream result_ss;\n\n try{\n result_ss << _zmqmujincontrollerclient->Call(command, timeout);\n }\n catch (const MujinException& e) {\n MUJIN_LOG_ERROR(e.what());\n if (e.GetCode() == MEC_ZMQNoResponse) {\n MUJIN_LOG_INFO(\"reinitializing zmq connection with the slave\");\n _zmqmujincontrollerclient.reset(new ZmqMujinControllerClient(_zmqcontext, _mujinControllerIp, _zmqPort));\n if (!_zmqmujincontrollerclient) {\n throw MujinException(boost::str(boost::format(\"Failed to establish ZMQ connection to mujin controller at %s:%d\")%_mujinControllerIp%_zmqPort), MEC_Failed);\n }\n }\n }\n\n try {\n \/\/ temporary fix until we move on to rapid json\n std::stringstream result_ss_float_timestamp;\n ConvertTimestampToFloat(result_ss.str(), result_ss_float_timestamp);\n std::cout << result_ss.str() << std::endl\n << result_ss_float_timestamp.str() << std::endl;\n boost::property_tree::read_json(result_ss_float_timestamp, pt);\n boost::property_tree::ptree::const_assoc_iterator iterror = pt.find(\"error\");\n if( iterror != pt.not_found() ) {\n boost::optional<std::string> erroroptional = iterror->second.get_optional<std::string>(\"errorcode\");\n boost::optional<std::string> descriptionoptional = iterror->second.get_optional<std::string>(\"description\");\n if (!!erroroptional && erroroptional.get().size() > 0 ) {\n std::string serror;\n if (!!descriptionoptional && descriptionoptional.get().size() > 0 ) {\n serror = descriptionoptional.get();\n }\n else {\n serror = erroroptional.get();\n }\n if( serror.size() > 1000 ) {\n MUJIN_LOG_ERROR(str(boost::format(\"truncated original error message from %d\")%serror.size()));\n serror = serror.substr(0,1000);\n }\n \n throw MujinException(str(boost::format(\"Error when calling binpicking.RunCommand: %s\")%serror), MEC_BinPickingError);\n }\n }\n } catch (boost::property_tree::ptree_error& e) {\n throw MujinException(boost::str(boost::format(\"Failed to parse json which is received from mujin controller: \\nreceived message: %s \\nerror message: %s\")%result_ss.str()%e.what()), MEC_Failed);\n }\n } else {\n try{\n _zmqmujincontrollerclient->Call(command, timeout);\n \/\/ TODO since not getting response, internal zmq will be in a bad state, have to recreate\n }\n catch (const MujinException& e) {\n MUJIN_LOG_ERROR(e.what());\n if (e.GetCode() == MEC_ZMQNoResponse) {\n MUJIN_LOG_INFO(\"reinitializing zmq connection with the slave\");\n _zmqmujincontrollerclient.reset(new ZmqMujinControllerClient(_zmqcontext, _mujinControllerIp, _zmqPort));\n if (!_zmqmujincontrollerclient) {\n throw MujinException(boost::str(boost::format(\"Failed to establish ZMQ connection to mujin controller at %s:%d\")%_mujinControllerIp%_zmqPort), MEC_Failed);\n }\n }\n }\n }\n return pt;\n}\n\nvoid BinPickingTaskZmqResource::InitializeZMQ(const double reinitializetimeout, const double timeout)\n{\n}\n\nvoid BinPickingTaskZmqResource::_HeartbeatMonitorThread(const double reinitializetimeout, const double commandtimeout)\n{\n boost::shared_ptr<zmq::socket_t> socket;\n boost::property_tree::ptree pt;\n BinPickingTaskResource::ResultHeartBeat heartbeat;\n heartbeat._slaverequestid = _slaverequestid;\n while (!_bShutdownHeartbeatMonitor) {\n if (!!socket) {\n socket->close();\n socket.reset();\n }\n socket.reset(new zmq::socket_t((*_zmqcontext.get()),ZMQ_SUB));\n std::stringstream ss;\n ss << _heartbeatPort;\n socket->connect ((\"tcp:\/\/\"+ _mujinControllerIp+\":\"+ss.str()).c_str());\n socket->setsockopt(ZMQ_SUBSCRIBE, \"\", 0);\n\n zmq::pollitem_t pollitem;\n memset(&pollitem, 0, sizeof(zmq::pollitem_t));\n pollitem.socket = socket->operator void*();\n pollitem.events = ZMQ_POLLIN;\n unsigned long long lastheartbeat = GetMilliTime();\n while (!_bShutdownHeartbeatMonitor && (GetMilliTime() - lastheartbeat) \/ 1000.0f < reinitializetimeout) {\n zmq::poll(&pollitem,1, 50); \/\/ wait 50 ms for message\n if (pollitem.revents & ZMQ_POLLIN) {\n zmq::message_t reply;\n socket->recv(&reply);\n std::string replystring((char *) reply.data (), (size_t) reply.size()); \n#ifdef _WIN32\n \/\/ sometimes buffer can container \\n or \\\\, which windows boost property_tree does not like\n std::string newbuffer;\n std::vector< std::pair<std::string, std::string> > serachpairs(1);\n serachpairs[0].first = \"\\\\\"; serachpairs[0].second = \"\";\n SearchAndReplace(newbuffer, replystring, serachpairs);\n std::stringstream replystring_ss(newbuffer);\n#else\n std::stringstream replystring_ss(replystring);\n#endif\n try{\n boost::property_tree::read_json(replystring_ss, pt);\n }\n catch (std::exception const &e) {\n MUJIN_LOG_ERROR(\"HeartBeat reply is not JSON\");\n MUJIN_LOG_ERROR(e.what());\n continue;\n }\n heartbeat.Parse(pt);\n {\n boost::mutex::scoped_lock lock(_mutexTaskState);\n _taskstate = heartbeat.taskstate;\n }\n \/\/BINPICKING_LOG_ERROR(replystring);\n\n if (heartbeat.status != std::string(\"lost\") && heartbeat.status.size() > 1) {\n lastheartbeat = GetMilliTime();\n }\n }\n }\n if (!_bShutdownHeartbeatMonitor) {\n std::stringstream ss;\n ss << (double)((GetMilliTime() - lastheartbeat)\/1000.0f) << \" seconds passed since last heartbeat signal, re-intializing ZMQ server.\";\n MUJIN_LOG_INFO(ss.str());\n }\n }\n}\n\n \n\n} \/\/ end namespace mujinclient\n<|endoftext|>"} {"text":"<commit_before>#include \"common\/runtime\/runtime_features.h\"\n\n#include \"absl\/strings\/match.h\"\n\nnamespace Envoy {\nnamespace Runtime {\n\nbool isRuntimeFeature(absl::string_view feature) {\n return RuntimeFeaturesDefaults::get().enabledByDefault(feature) ||\n RuntimeFeaturesDefaults::get().existsButDisabled(feature);\n}\n\nbool runtimeFeatureEnabled(absl::string_view feature) {\n ASSERT(isRuntimeFeature(feature));\n if (Runtime::LoaderSingleton::getExisting()) {\n return Runtime::LoaderSingleton::getExisting()->threadsafeSnapshot()->runtimeFeatureEnabled(\n feature);\n }\n ENVOY_LOG_TO_LOGGER(Envoy::Logger::Registry::getLog(Envoy::Logger::Id::runtime), warn,\n \"Unable to use runtime singleton for feature {}\", feature);\n return RuntimeFeaturesDefaults::get().enabledByDefault(feature);\n}\n\nuint64_t getInteger(absl::string_view feature, uint64_t default_value) {\n ASSERT(absl::StartsWith(feature, \"envoy.\"));\n if (Runtime::LoaderSingleton::getExisting()) {\n return Runtime::LoaderSingleton::getExisting()->threadsafeSnapshot()->getInteger(\n std::string(feature), default_value);\n }\n ENVOY_LOG_TO_LOGGER(Envoy::Logger::Registry::getLog(Envoy::Logger::Id::runtime), warn,\n \"Unable to use runtime singleton for feature {}\", feature);\n return default_value;\n}\n\n\/\/ Add additional features here to enable the new code paths by default.\n\/\/\n\/\/ Per documentation in CONTRIBUTING.md is expected that new high risk code paths be guarded\n\/\/ by runtime feature guards, i.e\n\/\/\n\/\/ if (Runtime::runtimeFeatureEnabled(\"envoy.reloadable_features.my_feature_name\")) {\n\/\/ [new code path]\n\/\/ else {\n\/\/ [old_code_path]\n\/\/ }\n\/\/\n\/\/ Runtime features are false by default, so the old code path is exercised.\n\/\/ To make a runtime feature true by default, add it to the array below.\n\/\/ New features should be true-by-default for an Envoy release cycle before the\n\/\/ old code path is removed.\n\/\/\n\/\/ If issues are found that require a runtime feature to be disabled, it should be reported\n\/\/ ASAP by filing a bug on github. Overriding non-buggy code is strongly discouraged to avoid the\n\/\/ problem of the bugs being found after the old code path has been removed.\nconstexpr const char* runtime_features[] = {\n \/\/ Enabled\n \"envoy.reloadable_features.http1_flood_protection\",\n \"envoy.reloadable_features.test_feature_true\",\n \/\/ Begin alphabetically sorted section.\n \"envoy.deprecated_features.allow_deprecated_extension_names\",\n \"envoy.reloadable_features.activate_fds_next_event_loop\",\n \"envoy.reloadable_features.activate_timers_next_event_loop\",\n \"envoy.reloadable_features.allow_500_after_100\",\n \"envoy.reloadable_features.allow_prefetch\",\n \"envoy.reloadable_features.allow_response_for_timeout\",\n \"envoy.reloadable_features.consume_all_retry_headers\",\n \"envoy.reloadable_features.disallow_unbounded_access_logs\",\n \"envoy.reloadable_features.early_errors_via_hcm\",\n \"envoy.reloadable_features.enable_deprecated_v2_api_warning\",\n \"envoy.reloadable_features.enable_dns_cache_circuit_breakers\",\n \"envoy.reloadable_features.ext_authz_http_service_enable_case_sensitive_string_matcher\",\n \"envoy.reloadable_features.fix_upgrade_response\",\n \"envoy.reloadable_features.fix_wildcard_matching\",\n \"envoy.reloadable_features.fixed_connection_close\",\n \"envoy.reloadable_features.hcm_stream_error_on_invalid_message\",\n \"envoy.reloadable_features.http_default_alpn\",\n \"envoy.reloadable_features.http_transport_failure_reason_in_body\",\n \"envoy.reloadable_features.http2_skip_encoding_empty_trailers\",\n \"envoy.reloadable_features.listener_in_place_filterchain_update\",\n \"envoy.reloadable_features.overload_manager_disable_keepalive_drain_http2\",\n \"envoy.reloadable_features.preserve_query_string_in_path_redirects\",\n \"envoy.reloadable_features.preserve_upstream_date\",\n \"envoy.reloadable_features.stop_faking_paths\",\n \"envoy.reloadable_features.strict_1xx_and_204_response_headers\",\n \"envoy.reloadable_features.tls_use_io_handle_bio\",\n};\n\n\/\/ This is a section for officially sanctioned runtime features which are too\n\/\/ high risk to be enabled by default. Examples where we have opted to land\n\/\/ features without enabling by default are swapping the underlying buffer\n\/\/ implementation or the HTTP\/1.1 codec implementation. Most features should be\n\/\/ enabled by default.\n\/\/\n\/\/ When features are added here, there should be a tracking bug assigned to the\n\/\/ code owner to flip the default after sufficient testing.\nconstexpr const char* disabled_runtime_features[] = {\n \/\/ TODO(asraa) flip this feature after codec errors are handled\n \"envoy.reloadable_features.new_codec_behavior\",\n \/\/ TODO(alyssawilk) flip true after the release.\n \"envoy.reloadable_features.new_tcp_connection_pool\",\n \/\/ Sentinel and test flag.\n \"envoy.reloadable_features.test_feature_false\",\n};\n\nRuntimeFeatures::RuntimeFeatures() {\n for (auto& feature : runtime_features) {\n enabled_features_.insert(feature);\n }\n for (auto& feature : disabled_runtime_features) {\n disabled_features_.insert(feature);\n }\n}\n\n} \/\/ namespace Runtime\n} \/\/ namespace Envoy\n<commit_msg>tcp: switching to the new pool (#13012)<commit_after>#include \"common\/runtime\/runtime_features.h\"\n\n#include \"absl\/strings\/match.h\"\n\nnamespace Envoy {\nnamespace Runtime {\n\nbool isRuntimeFeature(absl::string_view feature) {\n return RuntimeFeaturesDefaults::get().enabledByDefault(feature) ||\n RuntimeFeaturesDefaults::get().existsButDisabled(feature);\n}\n\nbool runtimeFeatureEnabled(absl::string_view feature) {\n ASSERT(isRuntimeFeature(feature));\n if (Runtime::LoaderSingleton::getExisting()) {\n return Runtime::LoaderSingleton::getExisting()->threadsafeSnapshot()->runtimeFeatureEnabled(\n feature);\n }\n ENVOY_LOG_TO_LOGGER(Envoy::Logger::Registry::getLog(Envoy::Logger::Id::runtime), warn,\n \"Unable to use runtime singleton for feature {}\", feature);\n return RuntimeFeaturesDefaults::get().enabledByDefault(feature);\n}\n\nuint64_t getInteger(absl::string_view feature, uint64_t default_value) {\n ASSERT(absl::StartsWith(feature, \"envoy.\"));\n if (Runtime::LoaderSingleton::getExisting()) {\n return Runtime::LoaderSingleton::getExisting()->threadsafeSnapshot()->getInteger(\n std::string(feature), default_value);\n }\n ENVOY_LOG_TO_LOGGER(Envoy::Logger::Registry::getLog(Envoy::Logger::Id::runtime), warn,\n \"Unable to use runtime singleton for feature {}\", feature);\n return default_value;\n}\n\n\/\/ Add additional features here to enable the new code paths by default.\n\/\/\n\/\/ Per documentation in CONTRIBUTING.md is expected that new high risk code paths be guarded\n\/\/ by runtime feature guards, i.e\n\/\/\n\/\/ if (Runtime::runtimeFeatureEnabled(\"envoy.reloadable_features.my_feature_name\")) {\n\/\/ [new code path]\n\/\/ else {\n\/\/ [old_code_path]\n\/\/ }\n\/\/\n\/\/ Runtime features are false by default, so the old code path is exercised.\n\/\/ To make a runtime feature true by default, add it to the array below.\n\/\/ New features should be true-by-default for an Envoy release cycle before the\n\/\/ old code path is removed.\n\/\/\n\/\/ If issues are found that require a runtime feature to be disabled, it should be reported\n\/\/ ASAP by filing a bug on github. Overriding non-buggy code is strongly discouraged to avoid the\n\/\/ problem of the bugs being found after the old code path has been removed.\nconstexpr const char* runtime_features[] = {\n \/\/ Enabled\n \"envoy.reloadable_features.http1_flood_protection\",\n \"envoy.reloadable_features.test_feature_true\",\n \/\/ Begin alphabetically sorted section.\n \"envoy.deprecated_features.allow_deprecated_extension_names\",\n \"envoy.reloadable_features.activate_fds_next_event_loop\",\n \"envoy.reloadable_features.activate_timers_next_event_loop\",\n \"envoy.reloadable_features.allow_500_after_100\",\n \"envoy.reloadable_features.allow_prefetch\",\n \"envoy.reloadable_features.allow_response_for_timeout\",\n \"envoy.reloadable_features.consume_all_retry_headers\",\n \"envoy.reloadable_features.disallow_unbounded_access_logs\",\n \"envoy.reloadable_features.early_errors_via_hcm\",\n \"envoy.reloadable_features.enable_deprecated_v2_api_warning\",\n \"envoy.reloadable_features.enable_dns_cache_circuit_breakers\",\n \"envoy.reloadable_features.ext_authz_http_service_enable_case_sensitive_string_matcher\",\n \"envoy.reloadable_features.fix_upgrade_response\",\n \"envoy.reloadable_features.fix_wildcard_matching\",\n \"envoy.reloadable_features.fixed_connection_close\",\n \"envoy.reloadable_features.hcm_stream_error_on_invalid_message\",\n \"envoy.reloadable_features.http_default_alpn\",\n \"envoy.reloadable_features.http_transport_failure_reason_in_body\",\n \"envoy.reloadable_features.http2_skip_encoding_empty_trailers\",\n \"envoy.reloadable_features.listener_in_place_filterchain_update\",\n \"envoy.reloadable_features.new_tcp_connection_pool\",\n \"envoy.reloadable_features.overload_manager_disable_keepalive_drain_http2\",\n \"envoy.reloadable_features.preserve_query_string_in_path_redirects\",\n \"envoy.reloadable_features.preserve_upstream_date\",\n \"envoy.reloadable_features.stop_faking_paths\",\n \"envoy.reloadable_features.strict_1xx_and_204_response_headers\",\n \"envoy.reloadable_features.tls_use_io_handle_bio\",\n};\n\n\/\/ This is a section for officially sanctioned runtime features which are too\n\/\/ high risk to be enabled by default. Examples where we have opted to land\n\/\/ features without enabling by default are swapping the underlying buffer\n\/\/ implementation or the HTTP\/1.1 codec implementation. Most features should be\n\/\/ enabled by default.\n\/\/\n\/\/ When features are added here, there should be a tracking bug assigned to the\n\/\/ code owner to flip the default after sufficient testing.\nconstexpr const char* disabled_runtime_features[] = {\n \/\/ TODO(asraa) flip this feature after codec errors are handled\n \"envoy.reloadable_features.new_codec_behavior\",\n \/\/ Sentinel and test flag.\n \"envoy.reloadable_features.test_feature_false\",\n};\n\nRuntimeFeatures::RuntimeFeatures() {\n for (auto& feature : runtime_features) {\n enabled_features_.insert(feature);\n }\n for (auto& feature : disabled_runtime_features) {\n disabled_features_.insert(feature);\n }\n}\n\n} \/\/ namespace Runtime\n} \/\/ namespace Envoy\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (C) 2010-2012 Joshua Boyce.\r\n\/\/ See the file COPYING for copying permission.\r\n\r\n#include \"hadesmem\/pelib\/dos_header.hpp\"\r\n\r\n#include <sstream>\r\n#include <utility>\r\n\r\n#define BOOST_TEST_MODULE dos_header\r\n#include \"hadesmem\/detail\/warning_disable_prefix.hpp\"\r\n#include <boost\/test\/unit_test.hpp>\r\n#include \"hadesmem\/detail\/warning_disable_suffix.hpp\"\r\n\r\n#include \"hadesmem\/read.hpp\"\r\n#include \"hadesmem\/error.hpp\"\r\n#include \"hadesmem\/config.hpp\"\r\n#include \"hadesmem\/module.hpp\"\r\n#include \"hadesmem\/process.hpp\"\r\n#include \"hadesmem\/module_list.hpp\"\r\n#include \"hadesmem\/pelib\/pe_file.hpp\"\r\n\r\n\/\/ Boost.Test causes the following warning under GCC:\r\n\/\/ error: base class 'struct boost::unit_test::ut_detail::nil_t' has a \r\n\/\/ non-virtual destructor [-Werror=effc++]\r\n#if defined(HADESMEM_GCC)\r\n#pragma GCC diagnostic ignored \"-Weffc++\"\r\n#endif \/\/ #if defined(HADESMEM_GCC)\r\n\r\n\/\/ Boost.Test causes the following warning under Clang:\r\n\/\/ error: declaration requires a global constructor \r\n\/\/ [-Werror,-Wglobal-constructors]\r\n#if defined(HADESMEM_CLANG)\r\n#pragma GCC diagnostic ignored \"-Wglobal-constructors\"\r\n#endif \/\/ #if defined(HADESMEM_CLANG)\r\n\r\nBOOST_AUTO_TEST_CASE(dos_header)\r\n{\r\n hadesmem::Process const process(::GetCurrentProcessId());\r\n\r\n hadesmem::PeFile pe_file_1(process, GetModuleHandle(nullptr), \r\n hadesmem::PeFileType::Image);\r\n\r\n hadesmem::DosHeader dos_header_1(process, pe_file_1);\r\n\r\n hadesmem::DosHeader dos_header_2(dos_header_1);\r\n BOOST_CHECK_EQUAL(dos_header_1, dos_header_2);\r\n dos_header_1 = dos_header_2;\r\n BOOST_CHECK_EQUAL(dos_header_1, dos_header_2);\r\n hadesmem::DosHeader dos_header_3(std::move(dos_header_2));\r\n BOOST_CHECK_EQUAL(dos_header_3, dos_header_1);\r\n dos_header_2 = std::move(dos_header_3);\r\n BOOST_CHECK_EQUAL(dos_header_1, dos_header_2);\r\n \r\n hadesmem::ModuleList modules(process);\r\n for (auto const& mod : modules)\r\n {\r\n \/\/ TODO: Also test FileType_Data\r\n hadesmem::PeFile const pe_file(process, mod.GetHandle(), \r\n hadesmem::PeFileType::Data);\r\n \r\n hadesmem::DosHeader dos_header(process, pe_file);\r\n \r\n auto const dos_header_raw = hadesmem::Read<IMAGE_DOS_HEADER>(process, \r\n dos_header.GetBase());\r\n \r\n BOOST_CHECK_EQUAL(dos_header.IsValid(), true);\r\n dos_header.EnsureValid();\r\n dos_header.SetMagic(dos_header.GetMagic());\r\n dos_header.SetBytesOnLastPage(dos_header.GetBytesOnLastPage());\r\n dos_header.SetPagesInFile(dos_header.GetPagesInFile());\r\n dos_header.SetRelocations(dos_header.GetRelocations());\r\n dos_header.SetSizeOfHeaderInParagraphs(dos_header.\r\n GetSizeOfHeaderInParagraphs());\r\n dos_header.SetMinExtraParagraphs(dos_header.GetMinExtraParagraphs());\r\n dos_header.SetMaxExtraParagraphs(dos_header.GetMaxExtraParagraphs());\r\n dos_header.SetInitialSS(dos_header.GetInitialSS());\r\n dos_header.SetInitialSP(dos_header.GetInitialSP());\r\n dos_header.SetChecksum(dos_header.GetChecksum());\r\n dos_header.SetInitialIP(dos_header.GetInitialIP());\r\n dos_header.SetInitialCS(dos_header.GetInitialCS());\r\n dos_header.SetRelocTableFileAddr(dos_header.GetRelocTableFileAddr());\r\n dos_header.SetOverlayNum(dos_header.GetOverlayNum());\r\n dos_header.SetReservedWords1(dos_header.GetReservedWords1());\r\n dos_header.SetOEMID(dos_header.GetOEMID());\r\n dos_header.SetOEMInfo(dos_header.GetOEMInfo());\r\n dos_header.SetReservedWords2(dos_header.GetReservedWords2());\r\n dos_header.SetNewHeaderOffset(dos_header.GetNewHeaderOffset());\r\n \r\n auto const dos_header_raw_new = hadesmem::Read<IMAGE_DOS_HEADER>(process, \r\n pe_file.GetBase());\r\n \r\n BOOST_CHECK_EQUAL(std::memcmp(&dos_header_raw, &dos_header_raw_new, \r\n sizeof(dos_header_raw)), 0);\r\n\r\n std::stringstream test_str_1;\r\n test_str_1.imbue(std::locale::classic());\r\n test_str_1 << pe_file;\r\n std::stringstream test_str_2;\r\n test_str_2.imbue(std::locale::classic());\r\n test_str_2 << pe_file.GetBase();\r\n BOOST_CHECK_EQUAL(test_str_1.str(), test_str_2.str());\r\n if (mod.GetHandle() != GetModuleHandle(L\"ntdll\"))\r\n {\r\n hadesmem::PeFile const pe_file_ntdll(process, GetModuleHandle(L\"ntdll\"), \r\n hadesmem::PeFileType::Image);\r\n std::stringstream test_str_3;\r\n test_str_3.imbue(std::locale::classic());\r\n test_str_3 << pe_file_ntdll.GetBase();\r\n BOOST_CHECK_NE(test_str_1.str(), test_str_3.str());\r\n }\r\n }\r\n}\r\n<commit_msg>* Fix tests.<commit_after>\/\/ Copyright (C) 2010-2012 Joshua Boyce.\r\n\/\/ See the file COPYING for copying permission.\r\n\r\n#include \"hadesmem\/pelib\/dos_header.hpp\"\r\n\r\n#include <sstream>\r\n#include <utility>\r\n\r\n#define BOOST_TEST_MODULE dos_header\r\n#include \"hadesmem\/detail\/warning_disable_prefix.hpp\"\r\n#include <boost\/test\/unit_test.hpp>\r\n#include \"hadesmem\/detail\/warning_disable_suffix.hpp\"\r\n\r\n#include \"hadesmem\/read.hpp\"\r\n#include \"hadesmem\/error.hpp\"\r\n#include \"hadesmem\/config.hpp\"\r\n#include \"hadesmem\/module.hpp\"\r\n#include \"hadesmem\/process.hpp\"\r\n#include \"hadesmem\/module_list.hpp\"\r\n#include \"hadesmem\/pelib\/pe_file.hpp\"\r\n\r\n\/\/ Boost.Test causes the following warning under GCC:\r\n\/\/ error: base class 'struct boost::unit_test::ut_detail::nil_t' has a \r\n\/\/ non-virtual destructor [-Werror=effc++]\r\n#if defined(HADESMEM_GCC)\r\n#pragma GCC diagnostic ignored \"-Weffc++\"\r\n#endif \/\/ #if defined(HADESMEM_GCC)\r\n\r\n\/\/ Boost.Test causes the following warning under Clang:\r\n\/\/ error: declaration requires a global constructor \r\n\/\/ [-Werror,-Wglobal-constructors]\r\n#if defined(HADESMEM_CLANG)\r\n#pragma GCC diagnostic ignored \"-Wglobal-constructors\"\r\n#endif \/\/ #if defined(HADESMEM_CLANG)\r\n\r\nBOOST_AUTO_TEST_CASE(dos_header)\r\n{\r\n hadesmem::Process const process(::GetCurrentProcessId());\r\n\r\n hadesmem::PeFile pe_file_1(process, GetModuleHandle(nullptr), \r\n hadesmem::PeFileType::Image);\r\n\r\n hadesmem::DosHeader dos_header_1(process, pe_file_1);\r\n\r\n hadesmem::DosHeader dos_header_2(dos_header_1);\r\n BOOST_CHECK_EQUAL(dos_header_1, dos_header_2);\r\n dos_header_1 = dos_header_2;\r\n BOOST_CHECK_EQUAL(dos_header_1, dos_header_2);\r\n hadesmem::DosHeader dos_header_3(std::move(dos_header_2));\r\n BOOST_CHECK_EQUAL(dos_header_3, dos_header_1);\r\n dos_header_2 = std::move(dos_header_3);\r\n BOOST_CHECK_EQUAL(dos_header_1, dos_header_2);\r\n \r\n hadesmem::ModuleList modules(process);\r\n for (auto const& mod : modules)\r\n {\r\n \/\/ TODO: Also test FileType_Data\r\n hadesmem::PeFile const pe_file(process, mod.GetHandle(), \r\n hadesmem::PeFileType::Data);\r\n \r\n hadesmem::DosHeader dos_header(process, pe_file);\r\n \r\n auto const dos_header_raw = hadesmem::Read<IMAGE_DOS_HEADER>(process, \r\n dos_header.GetBase());\r\n \r\n BOOST_CHECK_EQUAL(dos_header.IsValid(), true);\r\n dos_header.EnsureValid();\r\n dos_header.SetMagic(dos_header.GetMagic());\r\n dos_header.SetBytesOnLastPage(dos_header.GetBytesOnLastPage());\r\n dos_header.SetPagesInFile(dos_header.GetPagesInFile());\r\n dos_header.SetRelocations(dos_header.GetRelocations());\r\n dos_header.SetSizeOfHeaderInParagraphs(dos_header.\r\n GetSizeOfHeaderInParagraphs());\r\n dos_header.SetMinExtraParagraphs(dos_header.GetMinExtraParagraphs());\r\n dos_header.SetMaxExtraParagraphs(dos_header.GetMaxExtraParagraphs());\r\n dos_header.SetInitialSS(dos_header.GetInitialSS());\r\n dos_header.SetInitialSP(dos_header.GetInitialSP());\r\n dos_header.SetChecksum(dos_header.GetChecksum());\r\n dos_header.SetInitialIP(dos_header.GetInitialIP());\r\n dos_header.SetInitialCS(dos_header.GetInitialCS());\r\n dos_header.SetRelocTableFileAddr(dos_header.GetRelocTableFileAddr());\r\n dos_header.SetOverlayNum(dos_header.GetOverlayNum());\r\n dos_header.SetReservedWords1(dos_header.GetReservedWords1());\r\n dos_header.SetOEMID(dos_header.GetOEMID());\r\n dos_header.SetOEMInfo(dos_header.GetOEMInfo());\r\n dos_header.SetReservedWords2(dos_header.GetReservedWords2());\r\n dos_header.SetNewHeaderOffset(dos_header.GetNewHeaderOffset());\r\n \r\n auto const dos_header_raw_new = hadesmem::Read<IMAGE_DOS_HEADER>(process, \r\n pe_file.GetBase());\r\n \r\n BOOST_CHECK_EQUAL(std::memcmp(&dos_header_raw, &dos_header_raw_new, \r\n sizeof(dos_header_raw)), 0);\r\n\r\n std::stringstream test_str_1;\r\n test_str_1.imbue(std::locale::classic());\r\n test_str_1 << dos_header;\r\n std::stringstream test_str_2;\r\n test_str_2.imbue(std::locale::classic());\r\n test_str_2 << dos_header.GetBase();\r\n BOOST_CHECK_EQUAL(test_str_1.str(), test_str_2.str());\r\n if (mod.GetHandle() != GetModuleHandle(L\"ntdll\"))\r\n {\r\n hadesmem::PeFile const pe_file_ntdll(process, GetModuleHandle(L\"ntdll\"), \r\n hadesmem::PeFileType::Image);\r\n hadesmem::DosHeader const dos_header_ntdll(process, pe_file_ntdll);\r\n std::stringstream test_str_3;\r\n test_str_3.imbue(std::locale::classic());\r\n test_str_3 << dos_header_ntdll.GetBase();\r\n BOOST_CHECK_NE(test_str_1.str(), test_str_3.str());\r\n }\r\n }\r\n}\r\n<|endoftext|>"} {"text":"<commit_before>#include \"aquila\/global.h\"\n#include \"aquila\/source\/ArrayData.h\"\n#include <cstdint>\n#include <unittestpp.h>\n\n\nSUITE(ArrayData)\n{\n const int SIZE = 10;\n\n TEST(SampleFrequency)\n {\n Aquila::SampleType testArray[SIZE] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};\n Aquila::ArrayData<> data(testArray, SIZE, 22050);\n CHECK_EQUAL(22050, data.getSampleFrequency());\n }\n\n TEST(BitsPerSample8)\n {\n std::int8_t arr[SIZE] = {0};\n Aquila::ArrayData<std::int8_t> data(arr, SIZE, 22050);\n CHECK_EQUAL(8 * sizeof(Aquila::SampleType), data.getBitsPerSample());\n }\n\n TEST(BitsPerSample16)\n {\n std::int16_t arr[SIZE] = {0};\n Aquila::ArrayData<std::int16_t> data(arr, SIZE, 22050);\n CHECK_EQUAL(8 * sizeof(Aquila::SampleType), data.getBitsPerSample());\n }\n\n TEST(BitsPerSample32)\n {\n std::int32_t arr[SIZE] = {0};\n Aquila::ArrayData<std::int32_t> data(arr, SIZE, 22050);\n CHECK_EQUAL(8 * sizeof(Aquila::SampleType), data.getBitsPerSample());\n }\n\n TEST(BitsPerSample64)\n {\n std::int64_t arr[SIZE] = {0};\n Aquila::ArrayData<std::int64_t> data(arr, SIZE, 22050);\n CHECK_EQUAL(8 * sizeof(Aquila::SampleType), data.getBitsPerSample());\n }\n\n TEST(Iteration)\n {\n Aquila::SampleType testArray[SIZE] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};\n Aquila::ArrayData<> data(testArray, SIZE, 22050);\n std::size_t i = 0;\n for (auto it = data.begin(); it != data.end(); it++, i++)\n {\n CHECK_EQUAL(testArray[i], *it);\n }\n }\n}\n<commit_msg>Testing unsigned integer types with ArrayData.<commit_after>#include \"aquila\/global.h\"\n#include \"aquila\/source\/ArrayData.h\"\n#include <cstdint>\n#include <unittestpp.h>\n\n\nSUITE(ArrayData)\n{\n const int SIZE = 10;\n\n TEST(SampleFrequency)\n {\n Aquila::SampleType testArray[SIZE] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};\n Aquila::ArrayData<> data(testArray, SIZE, 22050);\n CHECK_EQUAL(22050, data.getSampleFrequency());\n }\n\n TEST(BitsPerSample8)\n {\n std::int8_t arr[SIZE] = {0};\n Aquila::ArrayData<std::int8_t> data(arr, SIZE, 22050);\n CHECK_EQUAL(8 * sizeof(Aquila::SampleType), data.getBitsPerSample());\n }\n\n TEST(BitsPerSample16)\n {\n std::int16_t arr[SIZE] = {0};\n Aquila::ArrayData<std::int16_t> data(arr, SIZE, 22050);\n CHECK_EQUAL(8 * sizeof(Aquila::SampleType), data.getBitsPerSample());\n }\n\n TEST(BitsPerSample32)\n {\n std::int32_t arr[SIZE] = {0};\n Aquila::ArrayData<std::int32_t> data(arr, SIZE, 22050);\n CHECK_EQUAL(8 * sizeof(Aquila::SampleType), data.getBitsPerSample());\n }\n\n TEST(BitsPerSample64)\n {\n std::int64_t arr[SIZE] = {0};\n Aquila::ArrayData<std::int64_t> data(arr, SIZE, 22050);\n CHECK_EQUAL(8 * sizeof(Aquila::SampleType), data.getBitsPerSample());\n }\n\n TEST(BitsPerSample_u8)\n {\n std::uint8_t arr[SIZE] = {0};\n Aquila::ArrayData<std::uint8_t> data(arr, SIZE, 22050);\n CHECK_EQUAL(8 * sizeof(Aquila::SampleType), data.getBitsPerSample());\n }\n\n TEST(BitsPerSample_u16)\n {\n std::uint16_t arr[SIZE] = {0};\n Aquila::ArrayData<std::uint16_t> data(arr, SIZE, 22050);\n CHECK_EQUAL(8 * sizeof(Aquila::SampleType), data.getBitsPerSample());\n }\n\n TEST(BitsPerSample_u32)\n {\n std::uint32_t arr[SIZE] = {0};\n Aquila::ArrayData<std::uint32_t> data(arr, SIZE, 22050);\n CHECK_EQUAL(8 * sizeof(Aquila::SampleType), data.getBitsPerSample());\n }\n\n TEST(BitsPerSample_u64)\n {\n std::uint64_t arr[SIZE] = {0};\n Aquila::ArrayData<std::uint64_t> data(arr, SIZE, 22050);\n CHECK_EQUAL(8 * sizeof(Aquila::SampleType), data.getBitsPerSample());\n }\n\n TEST(Iteration)\n {\n Aquila::SampleType testArray[SIZE] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};\n Aquila::ArrayData<> data(testArray, SIZE, 22050);\n std::size_t i = 0;\n for (auto it = data.begin(); it != data.end(); it++, i++)\n {\n CHECK_EQUAL(testArray[i], *it);\n }\n }\n}\n<|endoftext|>"} {"text":"<commit_before>#pragma once\n#include \"inc\/cxx\/json.hpp\"\n#include <arpa\/inet.h>\n\nnamespace cxx\n{\n auto const htonll = [](std::uint64_t x) -> std::uint64_t {\n return (static_cast<std::uint64_t>(htonl(static_cast<std::uint32_t>(x & 0xffffffff))) << 32) |\n htonl(static_cast<std::uint32_t>(x >> 32));\n };\n\n auto const ntohll = [](std::uint64_t x) -> std::uint64_t {\n auto const hi = static_cast<std::uint32_t>(x >> 32);\n auto const lo = static_cast<std::uint32_t>(x & 0xffffffff);\n return (static_cast<std::uint64_t>(ntohl(lo)) << 32) | ntohl(hi);\n };\n\n auto const htond = [](double d) -> double {\n static_assert(sizeof(double) == sizeof(std::uint64_t));\n static_assert(alignof(double) == alignof(std::uint64_t));\n auto* pu = static_cast<std::uint64_t*>(static_cast<void*>(&d));\n *pu = htonll(*pu);\n return d;\n };\n\n auto const ntohf = [](float f) -> float {\n static_assert(sizeof(float) == sizeof(std::uint32_t));\n static_assert(alignof(float) == alignof(std::uint32_t));\n auto* pu = static_cast<std::uint32_t*>(static_cast<void*>(&f));\n *pu = ntohl(*pu);\n return f;\n };\n\n auto const ntohd = [](double d) -> double {\n static_assert(sizeof(double) == sizeof(std::uint64_t));\n static_assert(alignof(double) == alignof(std::uint64_t));\n auto* pu = static_cast<std::uint64_t*>(static_cast<void*>(&d));\n *pu = ntohll(*pu);\n return d;\n };\n\n auto const ntoh = cxx::overload([](std::uint16_t x) -> std::uint16_t { return ::ntohs(x); },\n [](std::uint32_t x) -> std::uint32_t { return ::ntohl(x); },\n [](std::uint64_t x) -> std::uint64_t { return ntohll(x); },\n [](float x) -> float { return ntohf(x); },\n [](double x) -> double { return ntohd(x); });\n} \/\/ namespace cxx\n\nnamespace cxx::codec::cbor\n{\n template <typename T>\n constexpr auto base_type_impl()\n {\n if constexpr (std::is_enum_v<T>) { return std::underlying_type_t<T>{}; }\n else\n {\n return T{};\n }\n }\n\n template <typename T>\n using base_type = std::decay_t<decltype(base_type_impl<T>())>;\n\n struct initial_byte {\n struct type {\n static inline constexpr base_type<cxx::byte> positive = 0;\n static inline constexpr base_type<cxx::byte> negative = 1;\n static inline constexpr base_type<cxx::byte> bytes = 2;\n static inline constexpr base_type<cxx::byte> unicode = 3;\n static inline constexpr base_type<cxx::byte> array = 4;\n static inline constexpr base_type<cxx::byte> dictionary = 5;\n \/\/ static inline constexpr base_type<cxx::byte> tag = 6;\n static inline constexpr base_type<cxx::byte> special = 7;\n };\n struct value {\n static inline constexpr base_type<cxx::byte> max_insitu = 23;\n static inline constexpr base_type<cxx::byte> one_byte = 24;\n static inline constexpr base_type<cxx::byte> two_bytes = 25;\n static inline constexpr base_type<cxx::byte> four_bytes = 26;\n static inline constexpr base_type<cxx::byte> eigth_bytes = 27;\n\n static inline constexpr base_type<cxx::byte> False = 0xf4;\n static inline constexpr base_type<cxx::byte> True = 0xf5;\n static inline constexpr base_type<cxx::byte> Null = 0xf6;\n static inline constexpr base_type<cxx::byte> Simple = 0xf8;\n static inline constexpr base_type<cxx::byte> ieee_754_single = 0xfa;\n static inline constexpr base_type<cxx::byte> ieee_754_double = 0xfb;\n };\n\n base_type<cxx::byte> additional : 5; \/\/ lower\n base_type<cxx::byte> major : 3; \/\/ higher\n };\n static_assert(sizeof(initial_byte) == sizeof(cxx::byte));\n\n constexpr auto const initial = cxx::overload(\n [](cxx::json::byte_stream::reference byte) -> initial_byte* {\n return reinterpret_cast<initial_byte*>(&byte);\n },\n [](cxx::json::byte_stream::const_reference byte) -> initial_byte const* {\n return reinterpret_cast<initial_byte const*>(&byte);\n });\n} \/\/ namespace cxx::codec::cbor\n<commit_msg>gcc warning fix??<commit_after>#pragma once\n#include \"inc\/cxx\/json.hpp\"\n#include <arpa\/inet.h>\n\nnamespace cxx\n{\n auto const htonll = [](std::uint64_t x) -> std::uint64_t {\n return (static_cast<std::uint64_t>(htonl(static_cast<std::uint32_t>(x & 0xffffffff))) << 32) |\n htonl(static_cast<std::uint32_t>(x >> 32));\n };\n\n auto const ntohll = [](std::uint64_t x) -> std::uint64_t {\n auto const hi = static_cast<std::uint32_t>(x >> 32);\n auto const lo = static_cast<std::uint32_t>(x & 0xffffffff);\n return (static_cast<std::uint64_t>(ntohl(lo)) << 32) | ntohl(hi);\n };\n\n auto const htond = [](double d) -> double {\n static_assert(sizeof(double) == sizeof(std::uint64_t));\n static_assert(alignof(double) == alignof(std::uint64_t));\n auto* pu = static_cast<std::uint64_t*>(static_cast<void*>(&d));\n *pu = htonll(*pu);\n return d;\n };\n\n auto const ntohf = [](float f) -> float {\n static_assert(sizeof(float) == sizeof(std::uint32_t));\n static_assert(alignof(float) == alignof(std::uint32_t));\n auto* pu = static_cast<std::uint32_t*>(static_cast<void*>(&f));\n *pu = ntohl(*pu);\n return f;\n };\n\n auto const ntohd = [](double d) -> double {\n static_assert(sizeof(double) == sizeof(std::uint64_t));\n static_assert(alignof(double) == alignof(std::uint64_t));\n auto* pu = static_cast<std::uint64_t*>(static_cast<void*>(&d));\n *pu = ntohll(*pu);\n return d;\n };\n\n auto const ntoh = cxx::overload([](std::uint16_t x) -> std::uint16_t { return ntohs(x); },\n [](std::uint32_t x) -> std::uint32_t { return ntohl(x); },\n [](std::uint64_t x) -> std::uint64_t { return ntohll(x); },\n [](float x) -> float { return ntohf(x); },\n [](double x) -> double { return ntohd(x); });\n} \/\/ namespace cxx\n\nnamespace cxx::codec::cbor\n{\n template <typename T>\n constexpr auto base_type_impl()\n {\n if constexpr (std::is_enum_v<T>) { return std::underlying_type_t<T>{}; }\n else\n {\n return T{};\n }\n }\n\n template <typename T>\n using base_type = std::decay_t<decltype(base_type_impl<T>())>;\n\n struct initial_byte {\n struct type {\n static inline constexpr base_type<cxx::byte> positive = 0;\n static inline constexpr base_type<cxx::byte> negative = 1;\n static inline constexpr base_type<cxx::byte> bytes = 2;\n static inline constexpr base_type<cxx::byte> unicode = 3;\n static inline constexpr base_type<cxx::byte> array = 4;\n static inline constexpr base_type<cxx::byte> dictionary = 5;\n \/\/ static inline constexpr base_type<cxx::byte> tag = 6;\n static inline constexpr base_type<cxx::byte> special = 7;\n };\n struct value {\n static inline constexpr base_type<cxx::byte> max_insitu = 23;\n static inline constexpr base_type<cxx::byte> one_byte = 24;\n static inline constexpr base_type<cxx::byte> two_bytes = 25;\n static inline constexpr base_type<cxx::byte> four_bytes = 26;\n static inline constexpr base_type<cxx::byte> eigth_bytes = 27;\n\n static inline constexpr base_type<cxx::byte> False = 0xf4;\n static inline constexpr base_type<cxx::byte> True = 0xf5;\n static inline constexpr base_type<cxx::byte> Null = 0xf6;\n static inline constexpr base_type<cxx::byte> Simple = 0xf8;\n static inline constexpr base_type<cxx::byte> ieee_754_single = 0xfa;\n static inline constexpr base_type<cxx::byte> ieee_754_double = 0xfb;\n };\n\n base_type<cxx::byte> additional : 5; \/\/ lower\n base_type<cxx::byte> major : 3; \/\/ higher\n };\n static_assert(sizeof(initial_byte) == sizeof(cxx::byte));\n\n constexpr auto const initial = cxx::overload(\n [](cxx::json::byte_stream::reference byte) -> initial_byte* {\n return reinterpret_cast<initial_byte*>(&byte);\n },\n [](cxx::json::byte_stream::const_reference byte) -> initial_byte const* {\n return reinterpret_cast<initial_byte const*>(&byte);\n });\n} \/\/ namespace cxx::codec::cbor\n<|endoftext|>"} {"text":"<commit_before>#include \"..\/cshared\/shared.h\"\n#include \"..\/cshared\/opcodes.h\"\n#include \"..\/cshared\/opcodes_format.h\"\n#include \"..\/cshared\/opcodes_debug.h\"\n#include \"..\/cshared\/asm_stream.h\"\n#include \"..\/cshared\/stream.h\"\n\nstruct Arg\n{\n uint64_t fixnum = 0;\n std::string string;\n\n Arg(uint64_t fixnum) : fixnum(fixnum)\n {\n }\n Arg(dab_register_t reg) : fixnum(reg.value())\n {\n }\n Arg(std::vector<dab_register_t> regs)\n {\n (void)regs;\n }\n Arg(std::string string) : string(string)\n {\n }\n};\n\nstruct Op\n{\n size_t code;\n std::vector<Arg> data;\n\n uint16_t arg_uint16(size_t index)\n {\n return data[index].fixnum;\n }\n\n std::string arg_string(size_t index)\n {\n return data[index].string;\n }\n};\n\nvoid read_stream(Stream &stream)\n{\n byte buffer[1024];\n while (!feof(stdin))\n {\n size_t bytes = fread(buffer, 1, 1024, stdin);\n if (bytes)\n {\n stream.append(buffer, bytes);\n }\n }\n}\n\nvoid parse_stream(Stream &stream, std::function<void(Op)> func);\n\nvoid parse_asm(bool raw, std::function<void(Op)> func)\n{\n if (!raw)\n {\n \/\/ skip header\n const auto header_size = 3 + 4 * 8;\n unsigned char header[header_size];\n fread(header, 1, header_size, stdin);\n }\n\n Stream stream;\n read_stream(stream);\n\n parse_stream(stream, func);\n}\n\nvoid parse_stream(Stream &stream, std::function<void(Op)> func)\n{\n while (!stream.eof())\n {\n auto opcode = stream.read_uint8();\n assert(opcode < countof(g_opcodes));\n const auto &data = g_opcodes[opcode];\n Op op;\n op.code = opcode;\n for (const auto &arg : data.args)\n {\n switch (arg)\n {\n case OpcodeArg::ARG_INT8:\n op.data.push_back(stream.read_int8());\n break;\n case OpcodeArg::ARG_UINT8:\n op.data.push_back(stream.read_uint8());\n break;\n case OpcodeArg::ARG_UINT16:\n op.data.push_back(stream.read_uint16());\n break;\n case OpcodeArg::ARG_UINT64:\n op.data.push_back(stream.read_uint64());\n break;\n case OpcodeArg::ARG_INT16:\n op.data.push_back(stream.read_int16());\n break;\n case OpcodeArg::ARG_VLC:\n op.data.push_back(stream.read_vlc_string());\n break;\n case OpcodeArg::ARG_UINT32:\n op.data.push_back(stream.read_uint32());\n break;\n case OpcodeArg::ARG_INT32:\n op.data.push_back(stream.read_int32());\n break;\n case OpcodeArg::ARG_INT64:\n op.data.push_back(stream.read_int64());\n break;\n case OpcodeArg::ARG_REG:\n op.data.push_back(stream.read_reg());\n break;\n case OpcodeArg::ARG_SYMBOL:\n op.data.push_back(stream.read_symbol());\n break;\n case OpcodeArg::ARG_REGLIST:\n op.data.push_back(stream.read_reglist());\n break;\n case OpcodeArg::ARG_STRING4:\n op.data.push_back(stream.read_string4());\n break;\n case OpcodeArg::ARG_CSTRING:\n op.data.push_back(stream.read_cstring());\n break;\n }\n }\n func(op);\n }\n};\n\nint main()\n{\n std::map<uint64_t, std::string> files;\n std::map<uint64_t, std::set<uint64_t>> lines;\n\n Stream stream;\n read_stream(stream);\n auto header = stream.peek_header();\n fprintf(stderr, \"cdumpcov: %d sections\\n\", (int)header->section_count);\n for (size_t i = 0; i < header->section_count; i++)\n {\n auto section = header->sections[i];\n fprintf(stderr, \"cdumpcov: section[%d] '%s'\\n\", (int)i, section.name);\n std::string section_name = section.name;\n if (section_name == \"cove\")\n {\n auto size_of_cov_file = sizeof(uint64_t);\n auto number_of_cov_files = section.length \/ size_of_cov_file;\n fprintf(stderr, \"cdumpcov: %d cov files\\n\", (int)number_of_cov_files);\n for (size_t j = 0; j < number_of_cov_files; j++)\n {\n auto ptr = section.pos + size_of_cov_file * j;\n auto data = stream.uint64_data(ptr);\n auto string = stream.cstring_data(data);\n fprintf(stderr, \"cdumpcov: cov[%d] %p -> %p -> '%s'\\n\", (int)j, (void *)ptr,\n (void *)data, string.c_str());\n files[j + 1] = string;\n }\n }\n if (section_name == \"code\")\n {\n auto substream = stream.section_stream(i);\n parse_stream(substream, [&files, &lines](Op op) {\n if (op.code == OP_COV)\n {\n lines[op.arg_uint16(0)].insert(op.arg_uint16(1));\n }\n });\n }\n }\n\n printf(\"[\");\n int j = 0;\n for (auto f : files)\n {\n if (j++ > 0)\n printf(\",\");\n printf(\"{\\\"file\\\": \\\"%s\\\", \\\"lines\\\": [\", f.second.c_str());\n auto &file_lines = lines[f.first];\n int i = 0;\n for (auto line : file_lines)\n {\n if (i++ > 0)\n printf(\", \");\n printf(\"%d\", (int)line);\n }\n printf(\"]}\");\n }\n printf(\"]\\n\");\n\n return 0;\n}\n<commit_msg>cdumpcov: remove unused function<commit_after>#include \"..\/cshared\/shared.h\"\n#include \"..\/cshared\/opcodes.h\"\n#include \"..\/cshared\/opcodes_format.h\"\n#include \"..\/cshared\/opcodes_debug.h\"\n#include \"..\/cshared\/asm_stream.h\"\n#include \"..\/cshared\/stream.h\"\n\nstruct Arg\n{\n uint64_t fixnum = 0;\n std::string string;\n\n Arg(uint64_t fixnum) : fixnum(fixnum)\n {\n }\n Arg(dab_register_t reg) : fixnum(reg.value())\n {\n }\n Arg(std::vector<dab_register_t> regs)\n {\n (void)regs;\n }\n Arg(std::string string) : string(string)\n {\n }\n};\n\nstruct Op\n{\n size_t code;\n std::vector<Arg> data;\n\n uint16_t arg_uint16(size_t index)\n {\n return data[index].fixnum;\n }\n\n std::string arg_string(size_t index)\n {\n return data[index].string;\n }\n};\n\nvoid read_stream(Stream &stream)\n{\n byte buffer[1024];\n while (!feof(stdin))\n {\n size_t bytes = fread(buffer, 1, 1024, stdin);\n if (bytes)\n {\n stream.append(buffer, bytes);\n }\n }\n}\n\nvoid parse_stream(Stream &stream, std::function<void(Op)> func)\n{\n while (!stream.eof())\n {\n auto opcode = stream.read_uint8();\n assert(opcode < countof(g_opcodes));\n const auto &data = g_opcodes[opcode];\n Op op;\n op.code = opcode;\n for (const auto &arg : data.args)\n {\n switch (arg)\n {\n case OpcodeArg::ARG_INT8:\n op.data.push_back(stream.read_int8());\n break;\n case OpcodeArg::ARG_UINT8:\n op.data.push_back(stream.read_uint8());\n break;\n case OpcodeArg::ARG_UINT16:\n op.data.push_back(stream.read_uint16());\n break;\n case OpcodeArg::ARG_UINT64:\n op.data.push_back(stream.read_uint64());\n break;\n case OpcodeArg::ARG_INT16:\n op.data.push_back(stream.read_int16());\n break;\n case OpcodeArg::ARG_VLC:\n op.data.push_back(stream.read_vlc_string());\n break;\n case OpcodeArg::ARG_UINT32:\n op.data.push_back(stream.read_uint32());\n break;\n case OpcodeArg::ARG_INT32:\n op.data.push_back(stream.read_int32());\n break;\n case OpcodeArg::ARG_INT64:\n op.data.push_back(stream.read_int64());\n break;\n case OpcodeArg::ARG_REG:\n op.data.push_back(stream.read_reg());\n break;\n case OpcodeArg::ARG_SYMBOL:\n op.data.push_back(stream.read_symbol());\n break;\n case OpcodeArg::ARG_REGLIST:\n op.data.push_back(stream.read_reglist());\n break;\n case OpcodeArg::ARG_STRING4:\n op.data.push_back(stream.read_string4());\n break;\n case OpcodeArg::ARG_CSTRING:\n op.data.push_back(stream.read_cstring());\n break;\n }\n }\n func(op);\n }\n};\n\nint main()\n{\n std::map<uint64_t, std::string> files;\n std::map<uint64_t, std::set<uint64_t>> lines;\n\n Stream stream;\n read_stream(stream);\n auto header = stream.peek_header();\n fprintf(stderr, \"cdumpcov: %d sections\\n\", (int)header->section_count);\n for (size_t i = 0; i < header->section_count; i++)\n {\n auto section = header->sections[i];\n fprintf(stderr, \"cdumpcov: section[%d] '%s'\\n\", (int)i, section.name);\n std::string section_name = section.name;\n if (section_name == \"cove\")\n {\n auto size_of_cov_file = sizeof(uint64_t);\n auto number_of_cov_files = section.length \/ size_of_cov_file;\n fprintf(stderr, \"cdumpcov: %d cov files\\n\", (int)number_of_cov_files);\n for (size_t j = 0; j < number_of_cov_files; j++)\n {\n auto ptr = section.pos + size_of_cov_file * j;\n auto data = stream.uint64_data(ptr);\n auto string = stream.cstring_data(data);\n fprintf(stderr, \"cdumpcov: cov[%d] %p -> %p -> '%s'\\n\", (int)j, (void *)ptr,\n (void *)data, string.c_str());\n files[j + 1] = string;\n }\n }\n if (section_name == \"code\")\n {\n auto substream = stream.section_stream(i);\n parse_stream(substream, [&files, &lines](Op op) {\n if (op.code == OP_COV)\n {\n lines[op.arg_uint16(0)].insert(op.arg_uint16(1));\n }\n });\n }\n }\n\n printf(\"[\");\n int j = 0;\n for (auto f : files)\n {\n if (j++ > 0)\n printf(\",\");\n printf(\"{\\\"file\\\": \\\"%s\\\", \\\"lines\\\": [\", f.second.c_str());\n auto &file_lines = lines[f.first];\n int i = 0;\n for (auto line : file_lines)\n {\n if (i++ > 0)\n printf(\", \");\n printf(\"%d\", (int)line);\n }\n printf(\"]}\");\n }\n printf(\"]\\n\");\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"systems\/AccelSSGA.hpp\"\n\nAccelSSGA::AccelSSGA(SelectionStrategy * strategy) : SSGA(strategy) {}\n\nAccelSSGA::AccelSSGA(\n\tSelectionStrategy * strategy,\n\tunsigned seed\n) : SSGA(strategy, seed) {}\n\nAccelSSGA::AccelSSGA(\n\tSelectionStrategy * strategy,\n\tNichingStrategy * niching\n) : SSGA(strategy, niching) {}\n\nAccelSSGA::AccelSSGA(\n\tSelectionStrategy * strategy,\n\tNichingStrategy * niching,\n\tunsigned seed\n) : SSGA(strategy, niching, seed) {}\n\nstd::vector<Genome*> AccelSSGA::breedMutateSelect(\n\tstd::vector<Genome*> initialPopulation,\n\tstd::vector<int> & populationFitnesses,\n\tCrossoverOperation * cross,\n\tMutationOperation * mutation,\n\tstd::vector<ObjectiveFunction*> objectives\n) {\n\tstd::vector<Genome*> newPopulation;\n\tfor (int i = 0; i < initialPopulation.size()\/2; i++) {\n\t\tnewPopulation = SSGA::breedMutateSelect(\n\t\t\tinitialPopulation,\n\t\t\tpopulationFitnesses,\n\t\t\tcross,\n\t\t\tmutation,\n\t\t\tobjectives\n\t\t);\n\t}\n\n\treturn newPopulation;\n}\n<commit_msg>[AccelSSGA]: Fixed memory leak<commit_after>#include \"systems\/AccelSSGA.hpp\"\n\nAccelSSGA::AccelSSGA(SelectionStrategy * strategy) : SSGA(strategy) {}\n\nAccelSSGA::AccelSSGA(\n\tSelectionStrategy * strategy,\n\tunsigned seed\n) : SSGA(strategy, seed) {}\n\nAccelSSGA::AccelSSGA(\n\tSelectionStrategy * strategy,\n\tNichingStrategy * niching\n) : SSGA(strategy, niching) {}\n\nAccelSSGA::AccelSSGA(\n\tSelectionStrategy * strategy,\n\tNichingStrategy * niching,\n\tunsigned seed\n) : SSGA(strategy, niching, seed) {}\n\nstd::vector<Genome*> AccelSSGA::breedMutateSelect(\n\tstd::vector<Genome*> initialPopulation,\n\tstd::vector<int> & populationFitnesses,\n\tCrossoverOperation * cross,\n\tMutationOperation * mutation,\n\tstd::vector<ObjectiveFunction*> objectives\n) {\n\tstd::vector<Genome*> newPopulation;\n\tfor (int i = 0; i < initialPopulation.size(); i++)\n\t\tnewPopulation.push_back(new Genome(initialPopulation[i], false));\n\n\tfor (int i = 0; i < initialPopulation.size()\/2; i++) {\n\t\tstd::vector<Genome*> tempPopulation = SSGA::breedMutateSelect(\n\t\t\tnewPopulation,\n\t\t\tpopulationFitnesses,\n\t\t\tcross,\n\t\t\tmutation,\n\t\t\tobjectives\n\t\t);\n\n\t\tfor (int k = 0; k < newPopulation.size(); k++)\n\t\t\tdelete(newPopulation[k]);\n\t\tnewPopulation = tempPopulation;\n\t}\n\n\treturn newPopulation;\n}\n<|endoftext|>"} {"text":"<commit_before>#include <tagsouppullparser.h>\n#include <exceptions.h>\n#include <utils.h>\n#include <logger.h>\n#include <stdexcept>\n#include <istream>\n#include <sstream>\n#include <iostream>\n#include <cstdlib>\n\n#include <config.h>\n\nnamespace newsbeuter\n{\n\n\/*\n * This method implements an \"XML\" pull parser. In reality, it's more liberal\n * than any XML pull parser, as it basically accepts everything that even only\n * remotely looks like XML. We use this parser for the HTML renderer.\n *\/\n\ntagsouppullparser::tagsouppullparser() : inputstream(0), current_event(START_DOCUMENT)\n{\n}\n\ntagsouppullparser::~tagsouppullparser()\n{\n}\n\nvoid tagsouppullparser::setInput(std::istream& is) {\n\tinputstream = &is;\n\tcurrent_event = START_DOCUMENT;\n}\n\nstd::string tagsouppullparser::getAttributeValue(const std::string& name) const {\n\tfor (std::vector<attribute>::const_iterator it=attributes.begin();it!=attributes.end();++it) {\n\t\tif (it->first == name) {\n\t\t\treturn it->second;\n\t\t}\t\n\t}\t\n\tthrow std::invalid_argument(_(\"attribute not found\"));\n}\n\ntagsouppullparser::event tagsouppullparser::getEventType() const {\n\treturn current_event;\n}\n\nstd::string tagsouppullparser::getText() const {\n\treturn text;\n}\n\ntagsouppullparser::event tagsouppullparser::next() {\n\t\/*\n\t * the next() method returns the next event by parsing the\n\t * next element of the XML stream, depending on the current\n\t * event.\n\t *\/\n\tattributes.clear();\n\ttext = \"\";\n\n\tif (inputstream->eof()) {\n\t\tcurrent_event = END_DOCUMENT;\n\t}\n\n\tswitch (current_event) {\n\t\tcase START_DOCUMENT: \n\t\tcase START_TAG:\n\t\tcase END_TAG:\n\t\t\tskip_whitespace();\n\t\t\tif (inputstream->eof()) {\n\t\t\t\tcurrent_event = END_DOCUMENT;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tif (c != '<') {\n\t\t\t\thandle_text();\n\t\t\t\tbreak;\n\t\t\t}\n\t\tcase TEXT:\n\t\t\thandle_tag();\n\t\t\tbreak;\n\t\tcase END_DOCUMENT:\n\t\t\tbreak;\n\t}\n\treturn getEventType();\t\n}\n\nvoid tagsouppullparser::skip_whitespace() {\n\tc = '\\0';\n\tws = \"\";\n\tdo {\n\t\tinputstream->read(&c,1);\n\t\tif (!inputstream->eof()) {\n\t\t\tif (!isspace(c))\n\t\t\t\tbreak;\n\t\t\telse\n\t\t\t\tws.append(1,c);\n\t\t}\n\t} while (!inputstream->eof());\n}\n\nvoid tagsouppullparser::add_attribute(std::string s) {\n\tif (s.length() > 0 && s[s.length()-1] == '\/')\n\t\ts.erase(s.length()-1,1);\n\tif (s.length() == 0)\n\t\treturn;\n\tstd::string::size_type equalpos = s.find_first_of(\"=\",0);\n\tstd::string attribname, attribvalue;\n\t\n\tif (equalpos != std::string::npos) {\n\t\tattribname = s.substr(0,equalpos);\n\t\tattribvalue = s.substr(equalpos+1,s.length()-(equalpos+1));\n\t} else {\n\t\tattribname = attribvalue = s;\n\t}\n\tattribvalue = decode_attribute(attribvalue);\n\tattributes.push_back(attribute(attribname,attribvalue));\n}\n\nstd::string tagsouppullparser::read_tag() {\n\tstd::string s;\n\tgetline(*inputstream,s,'>');\n\tif (inputstream->eof()) {\n\t\tthrow xmlexception(_(\"EOF found while reading XML tag\"));\t\/\/ TODO: test whether this works reliably\n\t}\n\treturn s;\n}\n\ntagsouppullparser::event tagsouppullparser::determine_tag_type() {\n\tif (text.length() > 0 && text[0] == '\/') {\n\t\ttext.erase(0,1);\n\t\treturn END_TAG;\n\t}\n\treturn START_TAG;\t\n}\n\nstd::string tagsouppullparser::decode_attribute(const std::string& s) {\n\tstd::string s1 = s;\n\tif ((s1[0] == '\"' && s1[s1.length()-1] == '\"') || (s1[0] == '\\'' && s1[s1.length()-1] == '\\'')) {\n\t\tif (s1.length() > 0)\n\t\t\ts1.erase(0,1);\n\t\tif (s1.length() > 0)\n\t\t\ts1.erase(s1.length()-1,1);\t\n\t}\n\treturn decode_entities(s1);\n}\n\nstd::string tagsouppullparser::decode_entities(const std::string& s) {\n\tstd::string result, current_entity;\n\tstd::istringstream sbuf(s);\n\tstd::string tmp;\n\tgetline(sbuf,tmp,'&');\n\twhile (!sbuf.eof()) {\n\t\tresult.append(tmp);\n\t\tgetline(sbuf,tmp,';');\n\t\tresult.append(decode_entity(tmp));\n\t\tgetline(sbuf,tmp,'&');\n\t}\n\tresult.append(tmp);\n\treturn result;\n}\n\nstatic struct {\n\tconst char * entity;\n\tunsigned int value;\n} entity_table[] = {\n\t{ \"quot\", 34 },\n\t{ \"bdquo\", 34 },\n\t{ \"amp\", 38 },\n\t{ \"apos\", 39 },\n\t{ \"lt\", 60 },\n\t{ \"gt\", 62 },\n\t\/\/ this table was created with some vim regex magic from the this list: http:\/\/www.ramsch.org\/martin\/uni\/fmi-hp\/iso8859-1.html\n\t{ \"nbsp\", 160 },\n\t{ \"iexcl\", 161 },\n\t{ \"cent\", 162 },\n\t{ \"pound\", 163 },\n\t{ \"curren\", 164 },\n\t{ \"yen\", 165 },\n\t{ \"brvbar\", 166 },\n\t{ \"sect\", 167 },\n\t{ \"uml\", 168 },\n\t{ \"copy\", 169 },\n\t{ \"ordf\", 170 },\n\t{ \"laquo\", 171 },\n\t{ \"not\", 172 },\n\t{ \"shy\", 173 },\n\t{ \"reg\", 174 },\n\t{ \"macr\", 175 },\n\t{ \"deg\", 176 },\n\t{ \"plusmn\", 177 },\n\t{ \"sup2\", 178 },\n\t{ \"sup3\", 179 },\n\t{ \"acute\", 180 },\n\t{ \"micro\", 181 },\n\t{ \"para\", 182 },\n\t{ \"middot\", 183 },\n\t{ \"cedil\", 184 },\n\t{ \"sup1\", 185 },\n\t{ \"ordm\", 186 },\n\t{ \"raquo\", 187 },\n\t{ \"frac14\", 188 },\n\t{ \"frac12\", 189 },\n\t{ \"frac34\", 190 },\n\t{ \"iquest\", 191 },\n\t{ \"Agrave\", 192 },\n\t{ \"Aacute\", 193 },\n\t{ \"Acirc\", 194 },\n\t{ \"Atilde\", 195 },\n\t{ \"Auml\", 196 },\n\t{ \"Aring\", 197 },\n\t{ \"AElig\", 198 },\n\t{ \"Ccedil\", 199 },\n\t{ \"Egrave\", 200 },\n\t{ \"Eacute\", 201 },\n\t{ \"Ecirc\", 202 },\n\t{ \"Euml\", 203 },\n\t{ \"Igrave\", 204 },\n\t{ \"Iacute\", 205 },\n\t{ \"Icirc\", 206 },\n\t{ \"Iuml\", 207 },\n\t{ \"ETH\", 208 },\n\t{ \"Ntilde\", 209 },\n\t{ \"Ograve\", 210 },\n\t{ \"Oacute\", 211 },\n\t{ \"Ocirc\", 212 },\n\t{ \"Otilde\", 213 },\n\t{ \"Ouml\", 214 },\n\t{ \"times\", 215 },\n\t{ \"Oslash\", 216 },\n\t{ \"Ugrave\", 217 },\n\t{ \"Uacute\", 218 },\n\t{ \"Ucirc\", 219 },\n\t{ \"Uuml\", 220 },\n\t{ \"Yacute\", 221 },\n\t{ \"THORN\", 222 },\n\t{ \"szlig\", 223 },\n\t{ \"agrave\", 224 },\n\t{ \"aacute\", 225 },\n\t{ \"acirc\", 226 },\n\t{ \"atilde\", 227 },\n\t{ \"auml\", 228 },\n\t{ \"aring\", 229 },\n\t{ \"aelig\", 230 },\n\t{ \"ccedil\", 231 },\n\t{ \"egrave\", 232 },\n\t{ \"eacute\", 233 },\n\t{ \"ecirc\", 234 },\n\t{ \"euml\", 235 },\n\t{ \"igrave\", 236 },\n\t{ \"iacute\", 237 },\n\t{ \"icirc\", 238 },\n\t{ \"iuml\", 239 },\n\t{ \"eth\", 240 },\n\t{ \"ntilde\", 241 },\n\t{ \"ograve\", 242 },\n\t{ \"oacute\", 243 },\n\t{ \"ocirc\", 244 },\n\t{ \"otilde\", 245 },\n\t{ \"ouml\", 246 },\n\t{ \"divide\", 247 },\n\t{ \"oslash\", 248 },\n\t{ \"ugrave\", 249 },\n\t{ \"uacute\", 250 },\n\t{ \"ucirc\", 251 },\n\t{ \"uuml\", 252 },\n\t{ \"yacute\", 253 },\n\t{ \"thorn\", 254 },\n\t{ \"yuml\", 255 },\n\t\/* more entities *\/\n\t{ \"mdash\", 151 },\n\t{ \"ndash\", 8211 },\n\t{ 0, 0 }\n};\n\nstd::string tagsouppullparser::decode_entity(std::string s) {\n\tLOG(LOG_DEBUG, \"tagsouppullparser::decode_entity: decoding '%s'...\", s.c_str());\n\tif (s.length() > 1 && s[0] == '#') {\n\t\tstd::string result;\n\t\tunsigned int wc;\n\t\tchar mbc[MB_CUR_MAX];\n\t\tmbc[0] = '\\0';\n\t\tif (s[1] == 'x') {\n\t\t\ts.erase(0,2);\n\t\t\tstd::istringstream is(s);\n\t\t\tis >> std::hex >> wc;\n\t\t} else {\n\t\t\ts.erase(0,1);\n\t\t\tstd::istringstream is(s);\n\t\t\tis >> wc;\n\t\t}\n\t\tint pos = wctomb(mbc,static_cast<wchar_t>(wc));\n\t\t\/\/ std::cerr << \"value: \" << wc << \" \" << static_cast<wchar_t>(wc) << \" pos: \" << pos << std::endl;\n\t\tif (pos > 0) {\n\t\t\tmbc[pos] = '\\0';\n\t\t\tresult.append(mbc);\n\t\t}\n\t\tLOG(LOG_DEBUG,\"tagsouppullparser::decode_entity: wc = %u pos = %d mbc = '%s'\", wc, pos, mbc);\n\t\treturn result;\n\t} else {\n\t\tfor (unsigned int i=0;entity_table[i].entity;++i) {\n\t\t\tif (s == entity_table[i].entity) {\n\t\t\t\tchar mbc[MB_CUR_MAX];\n\t\t\t\tint pos = wctomb(mbc, entity_table[i].value);\n\t\t\t\tmbc[pos] = '\\0';\n\t\t\t\treturn std::string(mbc);\n\t\t\t}\n\t\t}\n\t}\n\treturn \"\"; \t\n}\n\nvoid tagsouppullparser::remove_trailing_whitespace(std::string& s) {\n\twhile (s.length() > 0 && isspace(s[s.length()-1])) {\n\t\ts.erase(s.length()-1,1);\n\t}\n}\n\nvoid tagsouppullparser::parse_tag(const std::string& tagstr) {\n\tstd::vector<std::string> tokens = utils::tokenize(tagstr);\n\tif (tokens.size() > 0) {\n\t\ttext = tokens[0];\n\t\tif (tokens.size() > 1) {\n\t\t\tstd::vector<std::string>::iterator it = tokens.begin();\n\t\t\t++it;\n\t\t\twhile (it != tokens.end()) {\n\t\t\t\tadd_attribute(*it);\n\t\t\t\t++it;\t\n\t\t\t}\n\t\t} else {\n\t\t\tif (text.length() > 0 && text[text.length()-1] == '\/')\n\t\t\t\ttext.erase(text.length()-1, 1);\n\t\t}\n\t}\n}\n\nvoid tagsouppullparser::handle_tag() {\n\tstd::string s;\n\ttry {\n\t\ts = read_tag();\n\t} catch (const xmlexception &) {\n\t\tcurrent_event = END_DOCUMENT;\n\t\treturn;\n\t}\n\tparse_tag(s);\n\tcurrent_event = determine_tag_type();\n}\n\nvoid tagsouppullparser::handle_text() {\n\tif (current_event != START_DOCUMENT) \n\t\ttext.append(ws);\n\ttext.append(1,c);\n\tstd::string tmp;\n\tgetline(*inputstream,tmp,'<');\n\ttext.append(tmp);\n\ttext = decode_entities(text);\n\tcurrent_event = TEXT;\n}\n\n}\n<commit_msg>Corrected entity mdash (source: en.wikipedia.org\/wiki\/Dash)<commit_after>#include <tagsouppullparser.h>\n#include <exceptions.h>\n#include <utils.h>\n#include <logger.h>\n#include <stdexcept>\n#include <istream>\n#include <sstream>\n#include <iostream>\n#include <cstdlib>\n\n#include <config.h>\n\nnamespace newsbeuter\n{\n\n\/*\n * This method implements an \"XML\" pull parser. In reality, it's more liberal\n * than any XML pull parser, as it basically accepts everything that even only\n * remotely looks like XML. We use this parser for the HTML renderer.\n *\/\n\ntagsouppullparser::tagsouppullparser() : inputstream(0), current_event(START_DOCUMENT)\n{\n}\n\ntagsouppullparser::~tagsouppullparser()\n{\n}\n\nvoid tagsouppullparser::setInput(std::istream& is) {\n\tinputstream = &is;\n\tcurrent_event = START_DOCUMENT;\n}\n\nstd::string tagsouppullparser::getAttributeValue(const std::string& name) const {\n\tfor (std::vector<attribute>::const_iterator it=attributes.begin();it!=attributes.end();++it) {\n\t\tif (it->first == name) {\n\t\t\treturn it->second;\n\t\t}\t\n\t}\t\n\tthrow std::invalid_argument(_(\"attribute not found\"));\n}\n\ntagsouppullparser::event tagsouppullparser::getEventType() const {\n\treturn current_event;\n}\n\nstd::string tagsouppullparser::getText() const {\n\treturn text;\n}\n\ntagsouppullparser::event tagsouppullparser::next() {\n\t\/*\n\t * the next() method returns the next event by parsing the\n\t * next element of the XML stream, depending on the current\n\t * event.\n\t *\/\n\tattributes.clear();\n\ttext = \"\";\n\n\tif (inputstream->eof()) {\n\t\tcurrent_event = END_DOCUMENT;\n\t}\n\n\tswitch (current_event) {\n\t\tcase START_DOCUMENT: \n\t\tcase START_TAG:\n\t\tcase END_TAG:\n\t\t\tskip_whitespace();\n\t\t\tif (inputstream->eof()) {\n\t\t\t\tcurrent_event = END_DOCUMENT;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tif (c != '<') {\n\t\t\t\thandle_text();\n\t\t\t\tbreak;\n\t\t\t}\n\t\tcase TEXT:\n\t\t\thandle_tag();\n\t\t\tbreak;\n\t\tcase END_DOCUMENT:\n\t\t\tbreak;\n\t}\n\treturn getEventType();\t\n}\n\nvoid tagsouppullparser::skip_whitespace() {\n\tc = '\\0';\n\tws = \"\";\n\tdo {\n\t\tinputstream->read(&c,1);\n\t\tif (!inputstream->eof()) {\n\t\t\tif (!isspace(c))\n\t\t\t\tbreak;\n\t\t\telse\n\t\t\t\tws.append(1,c);\n\t\t}\n\t} while (!inputstream->eof());\n}\n\nvoid tagsouppullparser::add_attribute(std::string s) {\n\tif (s.length() > 0 && s[s.length()-1] == '\/')\n\t\ts.erase(s.length()-1,1);\n\tif (s.length() == 0)\n\t\treturn;\n\tstd::string::size_type equalpos = s.find_first_of(\"=\",0);\n\tstd::string attribname, attribvalue;\n\t\n\tif (equalpos != std::string::npos) {\n\t\tattribname = s.substr(0,equalpos);\n\t\tattribvalue = s.substr(equalpos+1,s.length()-(equalpos+1));\n\t} else {\n\t\tattribname = attribvalue = s;\n\t}\n\tattribvalue = decode_attribute(attribvalue);\n\tattributes.push_back(attribute(attribname,attribvalue));\n}\n\nstd::string tagsouppullparser::read_tag() {\n\tstd::string s;\n\tgetline(*inputstream,s,'>');\n\tif (inputstream->eof()) {\n\t\tthrow xmlexception(_(\"EOF found while reading XML tag\"));\t\/\/ TODO: test whether this works reliably\n\t}\n\treturn s;\n}\n\ntagsouppullparser::event tagsouppullparser::determine_tag_type() {\n\tif (text.length() > 0 && text[0] == '\/') {\n\t\ttext.erase(0,1);\n\t\treturn END_TAG;\n\t}\n\treturn START_TAG;\t\n}\n\nstd::string tagsouppullparser::decode_attribute(const std::string& s) {\n\tstd::string s1 = s;\n\tif ((s1[0] == '\"' && s1[s1.length()-1] == '\"') || (s1[0] == '\\'' && s1[s1.length()-1] == '\\'')) {\n\t\tif (s1.length() > 0)\n\t\t\ts1.erase(0,1);\n\t\tif (s1.length() > 0)\n\t\t\ts1.erase(s1.length()-1,1);\t\n\t}\n\treturn decode_entities(s1);\n}\n\nstd::string tagsouppullparser::decode_entities(const std::string& s) {\n\tstd::string result, current_entity;\n\tstd::istringstream sbuf(s);\n\tstd::string tmp;\n\tgetline(sbuf,tmp,'&');\n\twhile (!sbuf.eof()) {\n\t\tresult.append(tmp);\n\t\tgetline(sbuf,tmp,';');\n\t\tresult.append(decode_entity(tmp));\n\t\tgetline(sbuf,tmp,'&');\n\t}\n\tresult.append(tmp);\n\treturn result;\n}\n\nstatic struct {\n\tconst char * entity;\n\tunsigned int value;\n} entity_table[] = {\n\t{ \"quot\", 34 },\n\t{ \"bdquo\", 34 },\n\t{ \"amp\", 38 },\n\t{ \"apos\", 39 },\n\t{ \"lt\", 60 },\n\t{ \"gt\", 62 },\n\t\/\/ this table was created with some vim regex magic from the this list: http:\/\/www.ramsch.org\/martin\/uni\/fmi-hp\/iso8859-1.html\n\t{ \"nbsp\", 160 },\n\t{ \"iexcl\", 161 },\n\t{ \"cent\", 162 },\n\t{ \"pound\", 163 },\n\t{ \"curren\", 164 },\n\t{ \"yen\", 165 },\n\t{ \"brvbar\", 166 },\n\t{ \"sect\", 167 },\n\t{ \"uml\", 168 },\n\t{ \"copy\", 169 },\n\t{ \"ordf\", 170 },\n\t{ \"laquo\", 171 },\n\t{ \"not\", 172 },\n\t{ \"shy\", 173 },\n\t{ \"reg\", 174 },\n\t{ \"macr\", 175 },\n\t{ \"deg\", 176 },\n\t{ \"plusmn\", 177 },\n\t{ \"sup2\", 178 },\n\t{ \"sup3\", 179 },\n\t{ \"acute\", 180 },\n\t{ \"micro\", 181 },\n\t{ \"para\", 182 },\n\t{ \"middot\", 183 },\n\t{ \"cedil\", 184 },\n\t{ \"sup1\", 185 },\n\t{ \"ordm\", 186 },\n\t{ \"raquo\", 187 },\n\t{ \"frac14\", 188 },\n\t{ \"frac12\", 189 },\n\t{ \"frac34\", 190 },\n\t{ \"iquest\", 191 },\n\t{ \"Agrave\", 192 },\n\t{ \"Aacute\", 193 },\n\t{ \"Acirc\", 194 },\n\t{ \"Atilde\", 195 },\n\t{ \"Auml\", 196 },\n\t{ \"Aring\", 197 },\n\t{ \"AElig\", 198 },\n\t{ \"Ccedil\", 199 },\n\t{ \"Egrave\", 200 },\n\t{ \"Eacute\", 201 },\n\t{ \"Ecirc\", 202 },\n\t{ \"Euml\", 203 },\n\t{ \"Igrave\", 204 },\n\t{ \"Iacute\", 205 },\n\t{ \"Icirc\", 206 },\n\t{ \"Iuml\", 207 },\n\t{ \"ETH\", 208 },\n\t{ \"Ntilde\", 209 },\n\t{ \"Ograve\", 210 },\n\t{ \"Oacute\", 211 },\n\t{ \"Ocirc\", 212 },\n\t{ \"Otilde\", 213 },\n\t{ \"Ouml\", 214 },\n\t{ \"times\", 215 },\n\t{ \"Oslash\", 216 },\n\t{ \"Ugrave\", 217 },\n\t{ \"Uacute\", 218 },\n\t{ \"Ucirc\", 219 },\n\t{ \"Uuml\", 220 },\n\t{ \"Yacute\", 221 },\n\t{ \"THORN\", 222 },\n\t{ \"szlig\", 223 },\n\t{ \"agrave\", 224 },\n\t{ \"aacute\", 225 },\n\t{ \"acirc\", 226 },\n\t{ \"atilde\", 227 },\n\t{ \"auml\", 228 },\n\t{ \"aring\", 229 },\n\t{ \"aelig\", 230 },\n\t{ \"ccedil\", 231 },\n\t{ \"egrave\", 232 },\n\t{ \"eacute\", 233 },\n\t{ \"ecirc\", 234 },\n\t{ \"euml\", 235 },\n\t{ \"igrave\", 236 },\n\t{ \"iacute\", 237 },\n\t{ \"icirc\", 238 },\n\t{ \"iuml\", 239 },\n\t{ \"eth\", 240 },\n\t{ \"ntilde\", 241 },\n\t{ \"ograve\", 242 },\n\t{ \"oacute\", 243 },\n\t{ \"ocirc\", 244 },\n\t{ \"otilde\", 245 },\n\t{ \"ouml\", 246 },\n\t{ \"divide\", 247 },\n\t{ \"oslash\", 248 },\n\t{ \"ugrave\", 249 },\n\t{ \"uacute\", 250 },\n\t{ \"ucirc\", 251 },\n\t{ \"uuml\", 252 },\n\t{ \"yacute\", 253 },\n\t{ \"thorn\", 254 },\n\t{ \"yuml\", 255 },\n\t\/* more entities *\/\n\t{ \"mdash\", 8212 },\n\t{ \"ndash\", 8211 },\n\t{ 0, 0 }\n};\n\nstd::string tagsouppullparser::decode_entity(std::string s) {\n\tLOG(LOG_DEBUG, \"tagsouppullparser::decode_entity: decoding '%s'...\", s.c_str());\n\tif (s.length() > 1 && s[0] == '#') {\n\t\tstd::string result;\n\t\tunsigned int wc;\n\t\tchar mbc[MB_CUR_MAX];\n\t\tmbc[0] = '\\0';\n\t\tif (s[1] == 'x') {\n\t\t\ts.erase(0,2);\n\t\t\tstd::istringstream is(s);\n\t\t\tis >> std::hex >> wc;\n\t\t} else {\n\t\t\ts.erase(0,1);\n\t\t\tstd::istringstream is(s);\n\t\t\tis >> wc;\n\t\t}\n\t\tint pos = wctomb(mbc,static_cast<wchar_t>(wc));\n\t\t\/\/ std::cerr << \"value: \" << wc << \" \" << static_cast<wchar_t>(wc) << \" pos: \" << pos << std::endl;\n\t\tif (pos > 0) {\n\t\t\tmbc[pos] = '\\0';\n\t\t\tresult.append(mbc);\n\t\t}\n\t\tLOG(LOG_DEBUG,\"tagsouppullparser::decode_entity: wc = %u pos = %d mbc = '%s'\", wc, pos, mbc);\n\t\treturn result;\n\t} else {\n\t\tfor (unsigned int i=0;entity_table[i].entity;++i) {\n\t\t\tif (s == entity_table[i].entity) {\n\t\t\t\tchar mbc[MB_CUR_MAX];\n\t\t\t\tint pos = wctomb(mbc, entity_table[i].value);\n\t\t\t\tmbc[pos] = '\\0';\n\t\t\t\treturn std::string(mbc);\n\t\t\t}\n\t\t}\n\t}\n\treturn \"\"; \t\n}\n\nvoid tagsouppullparser::remove_trailing_whitespace(std::string& s) {\n\twhile (s.length() > 0 && isspace(s[s.length()-1])) {\n\t\ts.erase(s.length()-1,1);\n\t}\n}\n\nvoid tagsouppullparser::parse_tag(const std::string& tagstr) {\n\tstd::vector<std::string> tokens = utils::tokenize(tagstr);\n\tif (tokens.size() > 0) {\n\t\ttext = tokens[0];\n\t\tif (tokens.size() > 1) {\n\t\t\tstd::vector<std::string>::iterator it = tokens.begin();\n\t\t\t++it;\n\t\t\twhile (it != tokens.end()) {\n\t\t\t\tadd_attribute(*it);\n\t\t\t\t++it;\t\n\t\t\t}\n\t\t} else {\n\t\t\tif (text.length() > 0 && text[text.length()-1] == '\/')\n\t\t\t\ttext.erase(text.length()-1, 1);\n\t\t}\n\t}\n}\n\nvoid tagsouppullparser::handle_tag() {\n\tstd::string s;\n\ttry {\n\t\ts = read_tag();\n\t} catch (const xmlexception &) {\n\t\tcurrent_event = END_DOCUMENT;\n\t\treturn;\n\t}\n\tparse_tag(s);\n\tcurrent_event = determine_tag_type();\n}\n\nvoid tagsouppullparser::handle_text() {\n\tif (current_event != START_DOCUMENT) \n\t\ttext.append(ws);\n\ttext.append(1,c);\n\tstd::string tmp;\n\tgetline(*inputstream,tmp,'<');\n\ttext.append(tmp);\n\ttext = decode_entities(text);\n\tcurrent_event = TEXT;\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/==========================================================================\n\/\/ Name: fdmdv2_plot_waterfall.cpp\n\/\/ Purpose: Implements a waterfall plot derivative of fdmdv2_plot.\n\/\/ Created: June 22, 2012\n\/\/ Initial author: David Witten\n\/\/ Derived from: code written by David Rowe\n\/\/ License:\n\/\/\n\/\/ Copyright (C) 2012 David Witten\n\/\/\n\/\/ All rights reserved.\n\/\/\n\/\/ This program is free software; you can redistribute it and\/or modify\n\/\/ it under the terms of the GNU Lesser General Public License version 2.1,\n\/\/ as published by the Free Software Foundation. This program is\n\/\/ distributed in the hope that it will be useful, but WITHOUT ANY\n\/\/ WARRANTY; without even the implied warranty of MERCHANTABILITY or\n\/\/ FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public\n\/\/ License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public License\n\/\/ along with this program; if not, see <http:\/\/www.gnu.org\/licenses\/>.\n\/\/\n\/\/==========================================================================\n#include <string.h>\n#include \"wx\/wx.h\"\n#include \"fdmdv2_main.h\"\n#include \"fdmdv2_plot_waterfall.h\"\n\n\/*\n\n Notes:\n\n The height h() pixels represents WATERFALL_SECS_Y of data. Every DT\n seconds we get a vector of FDMDV_NSPEC spectrum samples which we use\n to update the last row. The height of each row is dy pixels, which\n maps to DT seconds. We call each dy high rectangle of pixels a\n block.\n\n*\/\n\nextern float g_avmag[];\n\nBEGIN_EVENT_TABLE(PlotWaterfall, PlotPanel)\n EVT_PAINT (PlotWaterfall::OnPaint)\n EVT_MOTION (PlotWaterfall::OnMouseMove)\n EVT_LEFT_DOWN (PlotWaterfall::OnMouseDown)\n EVT_LEFT_UP (PlotWaterfall::OnMouseUp)\n EVT_MOUSEWHEEL (PlotWaterfall::OnMouseWheelMoved)\n EVT_SIZE (PlotWaterfall::OnSize)\n EVT_SHOW (PlotWaterfall::OnShow)\n\/\/ EVT_ERASE_BACKGROUND(PlotWaterfall::OnErase)\nEND_EVENT_TABLE()\n\n\/\/-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=--=-=-=-=\n\/\/ Class WaterfallPlot\n\/\/\n\/\/ @class WaterfallPlot\n\/\/ @author David Witten\n\/\/ @date $(Date)\n\/\/ @file $(CurrentFileName).$(CurrentFileExt)\n\/\/ @brief\n\/\/\n\/\/-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=--=-=-=-=\nPlotWaterfall::PlotWaterfall(wxFrame* parent): PlotPanel(parent)\n{\n for(int i = 0; i < 255; i++)\n {\n m_heatmap_lut[i] = heatmap((float)i, 0.0, 255.0);\n }\n m_greyscale = 0;\n m_Bufsz = GetMaxClientSize();\n m_newdata = false;\n m_firstPass = true;\n m_line_color = 0;\n SetLabelSize(10.0);\n}\n\n\/\/----------------------------------------------------------------\n\/\/ paintEvent()\n\/\/\n\/\/ @class $(Name)\n\/\/ @author $(User)\n\/\/ @date $(Date)\n\/\/ @file $(CurrentFileName).$(CurrentFileExt)\n\/\/ @brief\n\/\/\n\/\/ Called by the system of by wxWidgets when the panel needs\n\/\/ to be redrawn. You can also trigger this call by calling\n\/\/ Refresh()\/Update().\n\/\/----------------------------------------------------------------\nvoid PlotWaterfall::OnPaint(wxPaintEvent & evt)\n{\n wxAutoBufferedPaintDC pdc(this);\n draw(pdc);\n}\n\n\/\/----------------------------------------------------------------\n\/\/ OnShow()\n\/\/----------------------------------------------------------------\nvoid PlotWaterfall::OnShow(wxShowEvent& event)\n{\n}\n\n\/\/----------------------------------------------------------------\n\/\/ ~PlotWaterfall()\n\/\/----------------------------------------------------------------\nPlotWaterfall::~PlotWaterfall()\n{\n}\n\n\/\/----------------------------------------------------------------\n\/\/ heatmap()\n\/\/ map val to a rgb colour\n\/\/ from http:\/\/eddiema.ca\/2011\/01\/21\/c-sharp-heatmaps\/\n\/\/----------------------------------------------------------------\nunsigned PlotWaterfall::heatmap(float val, float min, float max)\n{\n unsigned r = 0;\n unsigned g = 0;\n unsigned b = 0;\n\n val = (val - min) \/ (max - min);\n if(val <= 0.2)\n {\n b = (unsigned)((val \/ 0.2) * 255);\n }\n else if(val > 0.2 && val <= 0.7)\n {\n b = (unsigned)((1.0 - ((val - 0.2) \/ 0.5)) * 255);\n }\n if(val >= 0.2 && val <= 0.6)\n {\n g = (unsigned)(((val - 0.2) \/ 0.4) * 255);\n }\n else if(val > 0.6 && val <= 0.9)\n {\n g = (unsigned)((1.0 - ((val - 0.6) \/ 0.3)) * 255);\n }\n if(val >= 0.5)\n {\n r = (unsigned)(((val - 0.5) \/ 0.5) * 255);\n }\n \/\/printf(\"%f %x %x %x\\n\", val, r, g, b);\n return (b << 16) + (g << 8) + r;\n}\n\n#define PLOT_BOTTOM 0\n#define PLOT_TOP 1\n\n\/\/static long paint_count;\n\n\/\/----------------------------------------------------------------\n\/\/ draw()\n\/\/----------------------------------------------------------------\nvoid PlotWaterfall::draw(wxAutoBufferedPaintDC& pDC)\n{\n wxMemoryDC m_mDC;\n m_mDC.SelectObject(*m_pBmp);\n m_rCtrl = GetClientRect();\n m_rGrid = m_rCtrl;\n\n m_rGrid = m_rGrid.Deflate(PLOT_BORDER + (XLEFT_OFFSET\/2), (PLOT_BORDER + (YBOTTOM_OFFSET\/2)));\n m_rGrid.Offset(PLOT_BORDER + XLEFT_OFFSET, PLOT_BORDER);\n\n pDC.Clear();\n\/\/ m_mDC.Clear();\n m_rPlot = wxRect(PLOT_BORDER + XLEFT_OFFSET, PLOT_BORDER, m_rGrid.GetWidth(), m_rGrid.GetHeight());\n\/\/ if(m_firstPass)\n\/\/ {\n\/\/ m_firstPass = false;\n\/\/ m_mDC.FloodFill(0, 0, VERY_LTGREY_COLOR);\n\n \/\/ Draw a filled rectangle with aborder\n\/\/ wxBrush ltGraphBkgBrush = wxBrush(DARK_BLUE_COLOR);\n\/\/ m_mDC.SetBrush(ltGraphBkgBrush);\n\/\/ m_mDC.SetPen(wxPen(BLACK_COLOR, 0));\n\/\/ m_mDC.DrawRectangle(m_rPlot);\n\n\/\/ }\n wxBrush ltGraphBkgBrush = wxBrush(DARK_BLUE_COLOR);\n pDC.SetBrush(ltGraphBkgBrush);\n pDC.SetPen(wxPen(BLACK_COLOR, 0));\n pDC.DrawRectangle(m_rPlot);\n drawGraticule(pDC);\n if(m_newdata)\n {\n m_newdata = false;\n plotPixelData(pDC);\n\/\/#ifdef _USE_TIMER\n int t = m_rPlot.GetTop();\n int l = m_rPlot.GetLeft();\n int h = m_rPlot.GetHeight();\n int w = m_rPlot.GetWidth();\n int t2 = t + 1;\n int w2 = w - 1;\n int ht = (h - DATA_LINE_HEIGHT);\n\n \/\/drawData(); \/\/ m_mDC, PLOT_BOTTOM);\n m_mDC.StretchBlit(l, t2, w2, ht, &m_mDC, l, t2 + DATA_LINE_HEIGHT, w2, ht - 2);\n\/\/ pDC.Blit(l, t, w, h, &m_mDC, l, t); \/\/ Scroll Up from Bottom\n pDC.StretchBlit(l, (h - t) + 4, w, (-h) + 4, &m_mDC, l, t, w, h); \/\/ Scroll Down from top\n\/\/#endif\n drawGraticule(pDC);\n }\n m_mDC.SetBrush(wxNullBrush);\n m_mDC.SelectObject(wxNullBitmap);\n}\n\n\/\/-------------------------------------------------------------------------\n\/\/ drawData()\n\/\/-------------------------------------------------------------------------\nvoid PlotWaterfall::drawData() \/\/wxMemoryDC& pDC)\n{\n wxNativePixelData dPix = wxNativePixelData(*m_pBmp, m_rCtrl);\n m_pPix = &dPix;\n if(m_pPix == NULL)\n {\n return;\n }\n wxNativePixelData::Iterator p(*m_pPix);\n\n int w = m_rPlot.GetWidth();\n int h = m_rPlot.GetHeight();\n p.Offset(*m_pPix, XLEFT_OFFSET + 3, h - (DATA_LINE_HEIGHT - 2));\n for(int y = 0; y < DATA_LINE_HEIGHT; ++y)\n {\n wxNativePixelData::Iterator rowStart = p;\n for(int x = 0; x < (w - 1); ++x, ++p)\n {\n\/\/ p.Red() = m_pTopFrame->m_rxPa->m_av_mag[x];\n\/\/ p.Green() = m_pTopFrame->m_rxPa->m_av_mag[x];\n\/\/ p.Blue() = m_pTopFrame->m_rxPa->m_av_mag[x];\n\n p.Red() = g_avmag[x];\n p.Green() = g_avmag[x];\n p.Blue() = g_avmag[x];\n }\n p = rowStart;\n p.OffsetY(*m_pPix, 1);\n }\n}\n\n\/\/-------------------------------------------------------------------------\n\/\/ drawGraticule()\n\/\/-------------------------------------------------------------------------\nvoid PlotWaterfall::drawGraticule(wxAutoBufferedPaintDC& pDC)\n{\n int p;\n char buf[15];\n\n wxString s;\n\n wxBrush ltGraphBkgBrush;\n ltGraphBkgBrush.SetStyle(wxBRUSHSTYLE_TRANSPARENT);\n ltGraphBkgBrush.SetColour(*wxBLACK);\n pDC.SetBrush(ltGraphBkgBrush);\n pDC.SetPen(wxPen(BLACK_COLOR, 1));\n\n \/\/ Vertical gridlines\n pDC.SetPen(m_penShortDash);\n for(p = (PLOT_BORDER + XLEFT_OFFSET + GRID_INCREMENT); p < ((m_rGrid.GetWidth() - XLEFT_OFFSET) + GRID_INCREMENT); p += GRID_INCREMENT)\n {\n pDC.DrawLine(p, (m_rGrid.GetHeight() + PLOT_BORDER), p, PLOT_BORDER);\n }\n \/\/ Horizontal gridlines\n pDC.SetPen(m_penDotDash);\n for(p = (m_rGrid.GetHeight() - GRID_INCREMENT); p > PLOT_BORDER; p -= GRID_INCREMENT)\n {\n pDC.DrawLine(PLOT_BORDER + XLEFT_OFFSET, (p + PLOT_BORDER), (m_rGrid.GetWidth() + PLOT_BORDER + XLEFT_OFFSET), (p + PLOT_BORDER));\n }\n \/\/ Label the X-Axis\n pDC.SetPen(wxPen(GREY_COLOR, 1));\n for(p = GRID_INCREMENT; p < (m_rGrid.GetWidth() - YBOTTOM_OFFSET); p += GRID_INCREMENT)\n {\n sprintf(buf, \"%1.1f Hz\",(double)(p \/ 10));\n pDC.DrawText(buf, p - PLOT_BORDER + XLEFT_OFFSET, m_rGrid.GetHeight() + YBOTTOM_OFFSET\/3);\n }\n \/\/ Label the Y-Axis\n for(p = (m_rGrid.GetHeight() - GRID_INCREMENT); p > PLOT_BORDER; p -= GRID_INCREMENT)\n {\n sprintf(buf, \"%1.0f\", (double)((m_rGrid.GetHeight() - p) * -10));\n pDC.DrawText(buf, XLEFT_TEXT_OFFSET, p);\n }\n}\n\n\/\/-------------------------------------------------------------------------\n\/\/ plotPixelData()\n\/\/-------------------------------------------------------------------------\nvoid PlotWaterfall::plotPixelData(wxAutoBufferedPaintDC& dc)\n{\n float spec_index_per_px;\n float intensity_per_dB;\n int px_per_sec;\n int index;\n int dy;\n int dy_blocks;\n int bytes_in_row_of_blocks;\n int b;\n int px;\n int py;\n int intensity;\n unsigned *last_row;\n unsigned *pdest;\n unsigned *psrc;\n\n \/\/ determine dy, the height of one \"block\"\n px_per_sec = (float)m_rCtrl.GetHeight() \/ WATERFALL_SECS_Y;\n dy = DT * px_per_sec;\n \/\/ number of dy high blocks in spectrogram\n dy_blocks = m_rCtrl.GetHeight()\/ dy;\n \/\/ shift previous bit map\n bytes_in_row_of_blocks = dy * m_rCtrl.GetWidth() * sizeof(unsigned);\n for(b = 0; b < dy_blocks - 1; b++)\n {\n pdest = (unsigned int *)m_pBmp + b * m_rCtrl.GetWidth() * dy;\n psrc = (unsigned int *)m_pBmp + (b + 1) * m_rCtrl.GetWidth() * dy;\n memcpy(pdest, psrc, bytes_in_row_of_blocks);\n }\n \/\/ create a new row of blocks at bottom\n spec_index_per_px = (float)FDMDV_NSPEC \/ (float) m_rCtrl.GetWidth();\n intensity_per_dB = (float)256 \/(MAX_DB - MIN_DB);\n last_row = (unsigned int *)m_pBmp + dy *(dy_blocks - 1)* m_rCtrl.GetWidth();\n\n wxNativePixelData data(*m_pBmp);\n if(!data)\n {\n wxMessageBox(wxT(\"Unable to access Bitmap Data\"), wxT(\"Error\"));\n return;\n }\n if(data.GetWidth() < 20 || data.GetHeight() < 20)\n {\n wxMessageBox(wxT(\"Bitmap is too small to use\"), wxT(\"Warning\"));\n return;\n }\n wxNativePixelData::Iterator p(data);\n \/\/ we draw a (10, 10)-(20, 20) rect manually using the given r, g, b\n p.Offset(data, 10, 10);\n for(px = 0; px < m_rCtrl.GetWidth(); px++)\n {\n index = px * spec_index_per_px;\n \/\/ intensity = intensity_per_dB * (m_av_mag[index] - MIN_DB);\n intensity = intensity_per_dB * (g_avmag[index] - MIN_DB);\n\/\/ intensity = intensity_per_dB * (((MainFrame *)GetParent())->m_rxPa->m_av_mag[index] - MIN_DB);\n\/\/ intensity = intensity_per_dB * (((MainFrame *)GetParent())->m_av_mag[index] - MIN_DB);\n if(intensity > 255)\n {\n intensity = 255;\n }\n if(intensity > 255)\n {\n intensity = 255;\n }\n if (intensity < 0)\n {\n intensity = 0;\n }\n if(m_greyscale)\n {\n for(py = 0; py < dy; py++)\n {\n last_row[px + py * m_rCtrl.GetWidth()] = intensity << 8;\n }\n }\n else\n {\n for(py = 0; py < dy; py++)\n {\n last_row[px + py * m_rCtrl.GetWidth()] = m_heatmap_lut[intensity];\n }\n }\n }\n}\n<commit_msg><commit_after>\/\/==========================================================================\n\/\/ Name: fdmdv2_plot_waterfall.cpp\n\/\/ Purpose: Implements a waterfall plot derivative of fdmdv2_plot.\n\/\/ Created: June 22, 2012\n\/\/ Initial author: David Witten\n\/\/ Derived from: code written by David Rowe\n\/\/ License:\n\/\/\n\/\/ Copyright (C) 2012 David Witten\n\/\/\n\/\/ All rights reserved.\n\/\/\n\/\/ This program is free software; you can redistribute it and\/or modify\n\/\/ it under the terms of the GNU Lesser General Public License version 2.1,\n\/\/ as published by the Free Software Foundation. This program is\n\/\/ distributed in the hope that it will be useful, but WITHOUT ANY\n\/\/ WARRANTY; without even the implied warranty of MERCHANTABILITY or\n\/\/ FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public\n\/\/ License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public License\n\/\/ along with this program; if not, see <http:\/\/www.gnu.org\/licenses\/>.\n\/\/\n\/\/==========================================================================\n#include <string.h>\n#include \"wx\/wx.h\"\n#include \"fdmdv2_main.h\"\n#include \"fdmdv2_plot_waterfall.h\"\n\n\/*\n\n Notes:\n\n The height h() pixels represents WATERFALL_SECS_Y of data. Every DT\n seconds we get a vector of FDMDV_NSPEC spectrum samples which we use\n to update the last row. The height of each row is dy pixels, which\n maps to DT seconds. We call each dy high rectangle of pixels a\n block.\n\n*\/\n\nextern float g_avmag[];\n\nBEGIN_EVENT_TABLE(PlotWaterfall, PlotPanel)\n EVT_PAINT (PlotWaterfall::OnPaint)\n EVT_MOTION (PlotWaterfall::OnMouseMove)\n EVT_LEFT_DOWN (PlotWaterfall::OnMouseDown)\n EVT_LEFT_UP (PlotWaterfall::OnMouseUp)\n EVT_MOUSEWHEEL (PlotWaterfall::OnMouseWheelMoved)\n EVT_SIZE (PlotWaterfall::OnSize)\n EVT_SHOW (PlotWaterfall::OnShow)\n\/\/ EVT_ERASE_BACKGROUND(PlotWaterfall::OnErase)\nEND_EVENT_TABLE()\n\n\/\/-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=--=-=-=-=\n\/\/ Class WaterfallPlot\n\/\/\n\/\/ @class WaterfallPlot\n\/\/ @author David Witten\n\/\/ @date $(Date)\n\/\/ @file $(CurrentFileName).$(CurrentFileExt)\n\/\/ @brief\n\/\/\n\/\/-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=--=-=-=-=\nPlotWaterfall::PlotWaterfall(wxFrame* parent): PlotPanel(parent)\n{\n for(int i = 0; i < 255; i++)\n {\n m_heatmap_lut[i] = heatmap((float)i, 0.0, 255.0);\n }\n m_greyscale = 0;\n m_Bufsz = GetMaxClientSize();\n m_newdata = false;\n m_firstPass = true;\n m_line_color = 0;\n SetLabelSize(10.0);\n}\n\n\/\/----------------------------------------------------------------\n\/\/ paintEvent()\n\/\/\n\/\/ @class $(Name)\n\/\/ @author $(User)\n\/\/ @date $(Date)\n\/\/ @file $(CurrentFileName).$(CurrentFileExt)\n\/\/ @brief\n\/\/\n\/\/ Called by the system of by wxWidgets when the panel needs\n\/\/ to be redrawn. You can also trigger this call by calling\n\/\/ Refresh()\/Update().\n\/\/----------------------------------------------------------------\nvoid PlotWaterfall::OnPaint(wxPaintEvent & evt)\n{\n wxAutoBufferedPaintDC pdc(this);\n draw(pdc);\n}\n\n\/\/----------------------------------------------------------------\n\/\/ OnShow()\n\/\/----------------------------------------------------------------\nvoid PlotWaterfall::OnShow(wxShowEvent& event)\n{\n}\n\n\/\/----------------------------------------------------------------\n\/\/ ~PlotWaterfall()\n\/\/----------------------------------------------------------------\nPlotWaterfall::~PlotWaterfall()\n{\n}\n\n\/\/----------------------------------------------------------------\n\/\/ heatmap()\n\/\/ map val to a rgb colour\n\/\/ from http:\/\/eddiema.ca\/2011\/01\/21\/c-sharp-heatmaps\/\n\/\/----------------------------------------------------------------\nunsigned PlotWaterfall::heatmap(float val, float min, float max)\n{\n unsigned r = 0;\n unsigned g = 0;\n unsigned b = 0;\n\n val = (val - min) \/ (max - min);\n if(val <= 0.2)\n {\n b = (unsigned)((val \/ 0.2) * 255);\n }\n else if(val > 0.2 && val <= 0.7)\n {\n b = (unsigned)((1.0 - ((val - 0.2) \/ 0.5)) * 255);\n }\n if(val >= 0.2 && val <= 0.6)\n {\n g = (unsigned)(((val - 0.2) \/ 0.4) * 255);\n }\n else if(val > 0.6 && val <= 0.9)\n {\n g = (unsigned)((1.0 - ((val - 0.6) \/ 0.3)) * 255);\n }\n if(val >= 0.5)\n {\n r = (unsigned)(((val - 0.5) \/ 0.5) * 255);\n }\n \/\/printf(\"%f %x %x %x\\n\", val, r, g, b);\n return (b << 16) + (g << 8) + r;\n}\n\n#define PLOT_BOTTOM 0\n#define PLOT_TOP 1\n\n\/\/static long paint_count;\n\n\/\/----------------------------------------------------------------\n\/\/ draw()\n\/\/----------------------------------------------------------------\nvoid PlotWaterfall::draw(wxAutoBufferedPaintDC& pDC)\n{\n wxMemoryDC m_mDC;\n m_mDC.SelectObject(*m_pBmp);\n m_rCtrl = GetClientRect();\n m_rGrid = m_rCtrl;\n\n m_rGrid = m_rGrid.Deflate(PLOT_BORDER + (XLEFT_OFFSET\/2), (PLOT_BORDER + (YBOTTOM_OFFSET\/2)));\n m_rGrid.Offset(PLOT_BORDER + XLEFT_OFFSET, PLOT_BORDER);\n\n pDC.Clear();\n\/\/ m_mDC.Clear();\n m_rPlot = wxRect(PLOT_BORDER + XLEFT_OFFSET, PLOT_BORDER, m_rGrid.GetWidth(), m_rGrid.GetHeight());\n\/\/ if(m_firstPass)\n\/\/ {\n\/\/ m_firstPass = false;\n\/\/ m_mDC.FloodFill(0, 0, VERY_LTGREY_COLOR);\n\n \/\/ Draw a filled rectangle with aborder\n\/\/ wxBrush ltGraphBkgBrush = wxBrush(DARK_BLUE_COLOR);\n\/\/ m_mDC.SetBrush(ltGraphBkgBrush);\n\/\/ m_mDC.SetPen(wxPen(BLACK_COLOR, 0));\n\/\/ m_mDC.DrawRectangle(m_rPlot);\n\n\/\/ }\n wxBrush ltGraphBkgBrush = wxBrush(DARK_BLUE_COLOR);\n pDC.SetBrush(ltGraphBkgBrush);\n pDC.SetPen(wxPen(BLACK_COLOR, 0));\n pDC.DrawRectangle(m_rPlot);\n drawGraticule(pDC);\n if(m_newdata)\n {\n m_newdata = false;\n \/\/plotPixelData(pDC);\n\/\/#ifdef _USE_TIMER\n int t = m_rPlot.GetTop();\n int l = m_rPlot.GetLeft();\n int h = m_rPlot.GetHeight();\n int w = m_rPlot.GetWidth();\n int t2 = t + 1;\n int w2 = w - 1;\n int ht = (h - DATA_LINE_HEIGHT);\n\n drawData(); \/\/ m_mDC, PLOT_BOTTOM);\n m_mDC.StretchBlit(l, t2, w2, ht, &m_mDC, l, t2 + DATA_LINE_HEIGHT, w2, ht - 2);\n \/\/ pDC.Blit(l, t, w, h, &m_mDC, l, t); \/\/ Scroll Up from Bottom\n pDC.StretchBlit(l, (h - t) + 4, w, (-h) + 4, &m_mDC, l, t, w, h); \/\/ Scroll Down from top\n\/\/#endif\n drawGraticule(pDC);\n }\n m_mDC.SetBrush(wxNullBrush);\n m_mDC.SelectObject(wxNullBitmap);\n}\n\n\/\/-------------------------------------------------------------------------\n\/\/ drawData()\n\/\/-------------------------------------------------------------------------\nvoid PlotWaterfall::drawData() \/\/wxMemoryDC& pDC)\n{\n wxNativePixelData dPix = wxNativePixelData(*m_pBmp, m_rCtrl);\n m_pPix = &dPix;\n if(m_pPix == NULL)\n {\n return;\n }\n wxNativePixelData::Iterator p(*m_pPix);\n\n int w = m_rPlot.GetWidth();\n int h = m_rPlot.GetHeight();\n p.Offset(*m_pPix, XLEFT_OFFSET + 3, h - (DATA_LINE_HEIGHT - 2));\n for(int y = 0; y < DATA_LINE_HEIGHT; ++y)\n {\n wxNativePixelData::Iterator rowStart = p;\n for(int x = 0; x < (w - 1); ++x, ++p)\n {\n\/\/ p.Red() = m_pTopFrame->m_rxPa->m_av_mag[x];\n\/\/ p.Green() = m_pTopFrame->m_rxPa->m_av_mag[x];\n\/\/ p.Blue() = m_pTopFrame->m_rxPa->m_av_mag[x];\n\n p.Red() = g_avmag[x];\n p.Green() = g_avmag[x];\n p.Blue() = g_avmag[x];\n }\n p = rowStart;\n p.OffsetY(*m_pPix, 1);\n }\n}\n\n\/\/-------------------------------------------------------------------------\n\/\/ drawGraticule()\n\/\/-------------------------------------------------------------------------\nvoid PlotWaterfall::drawGraticule(wxAutoBufferedPaintDC& pDC)\n{\n int p;\n char buf[15];\n\n wxString s;\n\n wxBrush ltGraphBkgBrush;\n ltGraphBkgBrush.SetStyle(wxBRUSHSTYLE_TRANSPARENT);\n ltGraphBkgBrush.SetColour(*wxBLACK);\n pDC.SetBrush(ltGraphBkgBrush);\n pDC.SetPen(wxPen(BLACK_COLOR, 1));\n\n \/\/ Vertical gridlines\n pDC.SetPen(m_penShortDash);\n for(p = (PLOT_BORDER + XLEFT_OFFSET + GRID_INCREMENT); p < ((m_rGrid.GetWidth() - XLEFT_OFFSET) + GRID_INCREMENT); p += GRID_INCREMENT)\n {\n pDC.DrawLine(p, (m_rGrid.GetHeight() + PLOT_BORDER), p, PLOT_BORDER);\n }\n \/\/ Horizontal gridlines\n pDC.SetPen(m_penDotDash);\n for(p = (m_rGrid.GetHeight() - GRID_INCREMENT); p > PLOT_BORDER; p -= GRID_INCREMENT)\n {\n pDC.DrawLine(PLOT_BORDER + XLEFT_OFFSET, (p + PLOT_BORDER), (m_rGrid.GetWidth() + PLOT_BORDER + XLEFT_OFFSET), (p + PLOT_BORDER));\n }\n \/\/ Label the X-Axis\n pDC.SetPen(wxPen(GREY_COLOR, 1));\n for(p = GRID_INCREMENT; p < (m_rGrid.GetWidth() - YBOTTOM_OFFSET); p += GRID_INCREMENT)\n {\n sprintf(buf, \"%1.1f Hz\",(double)(p \/ 10));\n pDC.DrawText(buf, p - PLOT_BORDER + XLEFT_OFFSET, m_rGrid.GetHeight() + YBOTTOM_OFFSET\/3);\n }\n \/\/ Label the Y-Axis\n for(p = (m_rGrid.GetHeight() - GRID_INCREMENT); p > PLOT_BORDER; p -= GRID_INCREMENT)\n {\n sprintf(buf, \"%1.0f\", (double)((m_rGrid.GetHeight() - p) * -10));\n pDC.DrawText(buf, XLEFT_TEXT_OFFSET, p);\n }\n}\n\n\/\/-------------------------------------------------------------------------\n\/\/ plotPixelData()\n\/\/-------------------------------------------------------------------------\nvoid PlotWaterfall::plotPixelData(wxAutoBufferedPaintDC& dc)\n{\n float spec_index_per_px;\n float intensity_per_dB;\n int px_per_sec;\n int index;\n int dy;\n int dy_blocks;\n int bytes_in_row_of_blocks;\n int b;\n int px;\n int py;\n int intensity;\n unsigned *last_row;\n unsigned *pdest;\n unsigned *psrc;\n\n \/\/ determine dy, the height of one \"block\"\n px_per_sec = (float)m_rCtrl.GetHeight() \/ WATERFALL_SECS_Y;\n dy = DT * px_per_sec;\n \/\/ number of dy high blocks in spectrogram\n dy_blocks = m_rCtrl.GetHeight()\/ dy;\n \/\/ shift previous bit map\n bytes_in_row_of_blocks = dy * m_rCtrl.GetWidth() * sizeof(unsigned);\n for(b = 0; b < dy_blocks - 1; b++)\n {\n pdest = (unsigned int *)m_pBmp + b * m_rCtrl.GetWidth() * dy;\n psrc = (unsigned int *)m_pBmp + (b + 1) * m_rCtrl.GetWidth() * dy;\n memcpy(pdest, psrc, bytes_in_row_of_blocks);\n }\n \/\/ create a new row of blocks at bottom\n spec_index_per_px = (float)FDMDV_NSPEC \/ (float) m_rCtrl.GetWidth();\n intensity_per_dB = (float)256 \/(MAX_DB - MIN_DB);\n last_row = (unsigned int *)m_pBmp + dy *(dy_blocks - 1)* m_rCtrl.GetWidth();\n\n wxNativePixelData data(*m_pBmp);\n if(!data)\n {\n wxMessageBox(wxT(\"Unable to access Bitmap Data\"), wxT(\"Error\"));\n return;\n }\n if(data.GetWidth() < 20 || data.GetHeight() < 20)\n {\n wxMessageBox(wxT(\"Bitmap is too small to use\"), wxT(\"Warning\"));\n return;\n }\n wxNativePixelData::Iterator p(data);\n \/\/ we draw a (10, 10)-(20, 20) rect manually using the given r, g, b\n p.Offset(data, 10, 10);\n for(px = 0; px < m_rCtrl.GetWidth(); px++)\n {\n index = px * spec_index_per_px;\n \/\/ intensity = intensity_per_dB * (m_av_mag[index] - MIN_DB);\n intensity = intensity_per_dB * (g_avmag[index] - MIN_DB);\n\/\/ intensity = intensity_per_dB * (((MainFrame *)GetParent())->m_rxPa->m_av_mag[index] - MIN_DB);\n\/\/ intensity = intensity_per_dB * (((MainFrame *)GetParent())->m_av_mag[index] - MIN_DB);\n if(intensity > 255)\n {\n intensity = 255;\n }\n if(intensity > 255)\n {\n intensity = 255;\n }\n if (intensity < 0)\n {\n intensity = 0;\n }\n if(m_greyscale)\n {\n for(py = 0; py < dy; py++)\n {\n last_row[px + py * m_rCtrl.GetWidth()] = intensity << 8;\n }\n }\n else\n {\n for(py = 0; py < dy; py++)\n {\n last_row[px + py * m_rCtrl.GetWidth()] = m_heatmap_lut[intensity];\n }\n }\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2012-2020 The Bitcoin Core developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include <test\/util\/setup_common.h>\n#include <util\/strencodings.h>\n\n#include <boost\/test\/unit_test.hpp>\n#include <string>\n\nusing namespace std::literals;\n\nBOOST_FIXTURE_TEST_SUITE(base32_tests, BasicTestingSetup)\n\nBOOST_AUTO_TEST_CASE(base32_testvectors)\n{\n static const std::string vstrIn[] = {\"\",\"f\",\"fo\",\"foo\",\"foob\",\"fooba\",\"foobar\"};\n static const std::string vstrOut[] = {\"\",\"my======\",\"mzxq====\",\"mzxw6===\",\"mzxw6yq=\",\"mzxw6ytb\",\"mzxw6ytboi======\"};\n static const std::string vstrOutNoPadding[] = {\"\",\"my\",\"mzxq\",\"mzxw6\",\"mzxw6yq\",\"mzxw6ytb\",\"mzxw6ytboi\"};\n for (unsigned int i=0; i<std::size(vstrIn); i++)\n {\n std::string strEnc = EncodeBase32(vstrIn[i]);\n BOOST_CHECK_EQUAL(strEnc, vstrOut[i]);\n strEnc = EncodeBase32(vstrIn[i], false);\n BOOST_CHECK_EQUAL(strEnc, vstrOutNoPadding[i]);\n std::string strDec = DecodeBase32(vstrOut[i]);\n BOOST_CHECK_EQUAL(strDec, vstrIn[i]);\n }\n\n \/\/ Decoding strings with embedded NUL characters should fail\n bool failure;\n (void)DecodeBase32(\"invalid\\0\"s, &failure); \/\/ correct size, invalid due to \\0\n BOOST_CHECK(failure);\n (void)DecodeBase32(\"AWSX3VPP\"s, &failure); \/\/ valid\n BOOST_CHECK(!failure);\n (void)DecodeBase32(\"AWSX3VPP\\0invalid\"s, &failure); \/\/ correct size, invalid due to \\0\n BOOST_CHECK(failure);\n (void)DecodeBase32(\"AWSX3VPPinvalid\"s, &failure); \/\/ invalid size\n BOOST_CHECK(failure);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n<commit_msg>test: remove BasicTestingSetup from base32 unit tests<commit_after>\/\/ Copyright (c) 2012-2020 The Bitcoin Core developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include <util\/strencodings.h>\n\n#include <boost\/test\/unit_test.hpp>\n#include <string>\n\nusing namespace std::literals;\n\nBOOST_AUTO_TEST_SUITE(base32_tests)\n\nBOOST_AUTO_TEST_CASE(base32_testvectors)\n{\n static const std::string vstrIn[] = {\"\",\"f\",\"fo\",\"foo\",\"foob\",\"fooba\",\"foobar\"};\n static const std::string vstrOut[] = {\"\",\"my======\",\"mzxq====\",\"mzxw6===\",\"mzxw6yq=\",\"mzxw6ytb\",\"mzxw6ytboi======\"};\n static const std::string vstrOutNoPadding[] = {\"\",\"my\",\"mzxq\",\"mzxw6\",\"mzxw6yq\",\"mzxw6ytb\",\"mzxw6ytboi\"};\n for (unsigned int i=0; i<std::size(vstrIn); i++)\n {\n std::string strEnc = EncodeBase32(vstrIn[i]);\n BOOST_CHECK_EQUAL(strEnc, vstrOut[i]);\n strEnc = EncodeBase32(vstrIn[i], false);\n BOOST_CHECK_EQUAL(strEnc, vstrOutNoPadding[i]);\n std::string strDec = DecodeBase32(vstrOut[i]);\n BOOST_CHECK_EQUAL(strDec, vstrIn[i]);\n }\n\n \/\/ Decoding strings with embedded NUL characters should fail\n bool failure;\n (void)DecodeBase32(\"invalid\\0\"s, &failure); \/\/ correct size, invalid due to \\0\n BOOST_CHECK(failure);\n (void)DecodeBase32(\"AWSX3VPP\"s, &failure); \/\/ valid\n BOOST_CHECK(!failure);\n (void)DecodeBase32(\"AWSX3VPP\\0invalid\"s, &failure); \/\/ correct size, invalid due to \\0\n BOOST_CHECK(failure);\n (void)DecodeBase32(\"AWSX3VPPinvalid\"s, &failure); \/\/ invalid size\n BOOST_CHECK(failure);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n<|endoftext|>"} {"text":"<commit_before><commit_msg>testing the interval munching functions too<commit_after><|endoftext|>"} {"text":"<commit_before>\n#include <cmath>\n#include <iostream>\n#include <random>\n#include <vector>\n\n#include <gtest\/gtest.h>\n\n#include <spii\/solver.h>\n\n\/\/ \"An analysis of the behavior of a glass of genetic adaptive systems.\"\n\/\/ K.A. De Jong. Ph.D. thesis, University of Michigan, 1975.\nstruct GeneralizedRosenbrockTerm\n{\n\ttemplate<typename R>\n\tR operator()(const R* const x1, const R* const x2)\n\t{\n\t\tR d0 = (*x1) * (*x1) - (*x2);\n\t\tR d1 = 1 - (*x1);\n\t\treturn 100 * d0*d0 + d1*d1;\n\t}\n};\n\n\/\/ An easier variant.\nstruct EasyRosenbrockTerm\n{\n\ttemplate<typename R>\n\tR operator()(const R* const x1, const R* const x2)\n\t{\n\t\tR d0 = (*x1) * (*x1) - (*x2);\n\t\tR d1 = 1 - (*x1);\n\t\treturn d0*d0 + d1*d1;\n\t}\n};\n\ntemplate<typename Functor, size_t n>\nvoid test_rosenbrock()\n{\n\tFunction f;\n\tstd::vector<double> x(n);\n\tfor (size_t i = 0; i < n; ++i) {\n\t\tf.add_variable(&x[i], 1);\n\t}\n\n\t\/\/ Initial values.\n\tfor (size_t i = 0; i < n; ++i) {\n\t\tif (i % 2 == 0) {\n\t\t\tx[i] = -1.2;\n\t\t}\n\t\telse {\n\t\t\tx[i] = 1.0;\n\t\t}\n\t}\n\n\t\/\/ Add all diagonal terms.\n\tfor (size_t i = 0; i < n - 1; ++i) {\n\t\tf.add_term(new AutoDiffTerm<Functor, 1, 1>\n\t\t (new Functor()), &x[i], &x[i+1]);\n\t}\n\n\tSolver solver;\n\tsolver.maximum_iterations = 10000;\n\tSolverResults results;\n\tsolver.Solve(f, &results);\n\tstd::cerr << results;\n\n\tEXPECT_TRUE(results.exit_condition == SolverResults::ARGUMENT_TOLERANCE ||\n\t results.exit_condition == SolverResults::FUNCTION_TOLERANCE ||\n\t results.exit_condition == SolverResults::GRADIENT_TOLERANCE);\n\n\tEXPECT_LT( std::abs(f.evaluate()), 1e-9);\n\n\tfor (size_t i = 0; i < n - 1; ++i) {\n\t\tASSERT_LT( std::abs(x[i] - 1.0), 1e-9);\n\t}\n}\n\n\nTEST(Solver, EasyRosenbrock1000)\n{\n\ttest_rosenbrock<EasyRosenbrockTerm, 1000>();\n}\n\nTEST(Solver, EasyRosenbrock10000)\n{\n\ttest_rosenbrock<EasyRosenbrockTerm, 10000>();\n}\n\nstruct LennardJones\n{\n\ttemplate<typename R>\n\tR operator()(const R* const p1, const R* const p2)\n\t{\n\t\tR dx = p1[0] - p2[0];\n\t\tR dy = p1[1] - p2[1];\n\t\tR dz = p1[2] - p2[2];\n\t\tR r2 = dx*dx + dy*dy + dz*dz;\n\t\tR r6 = r2*r2*r2;\n\t\tR r12 = r6*r6;\n\t\treturn 1.0 \/ r12 - 1.0 \/ r6;\n\t}\n};\n\nTEST(Solver, LennardJones)\n{\n\tstd::mt19937 prng(0);\n\tstd::normal_distribution<double> normal;\n\tstd::variate_generator<std::tr1::mt19937, std::tr1::normal_distribution<double> > randn(prng,normal);\n\n\tint n = 5;\n\n\tFunction potential;\n\n\tstd::vector<Eigen::Vector3d> points(n*n*n);\n\tfor (int x = 0; x < n; ++x) {\n\t\tfor (int y = 0; y < n; ++y) {\n\t\t\tfor (int z = 0; z < n; ++z) {\n\t\t\t\tpoints[x + y*n + z*n*n][0] = x + 0.05 * randn();\n\t\t\t\tpoints[x + y*n + z*n*n][1] = y + 0.05 * randn();\n\t\t\t\tpoints[x + y*n + z*n*n][2] = z + 0.05 * randn();\n\n\t\t\t\tpotential.add_variable(&points[x + y*n + z*n*n][0], 3);\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/ Add all pairwise terms\n\tfor (int i = 0; i < n*n*n; ++i) {\n\t\tfor (int j = i + 1; j < n*n*n; ++j) {\n\t\t\tpotential.add_term(\n\t\t\t\tnew AutoDiffTerm<LennardJones, 3, 3>(\n\t\t\t\t\tnew LennardJones),\n\t\t\t\t\t&points[i][0],\n\t\t\t\t\t&points[j][0]);\n\t\t}\n\t}\n\n\tSolver solver;\n\tsolver.maximum_iterations = 100;\n\t\/\/ All points interact with all points, so the Hessian\n\t\/\/ will be dense.\n\tsolver.sparsity_mode = Solver::DENSE;\n\tSolverResults results;\n\tsolver.Solve(potential, &results);\n\tstd::cerr << results;\n\n\tEXPECT_TRUE(results.exit_condition == SolverResults::ARGUMENT_TOLERANCE ||\n\t results.exit_condition == SolverResults::FUNCTION_TOLERANCE ||\n\t results.exit_condition == SolverResults::GRADIENT_TOLERANCE);\n}\n\nstruct Trid1\n{\n\ttemplate<typename R>\n\tR operator()(const R* const x)\n\t{\n\t\tR d = *x - 1.0;\n\t\treturn d*d;\n\t}\n};\n\nstruct Trid2\n{\n\ttemplate<typename R>\n\tR operator()(const R* const x1, const R* const x2)\n\t{\n\t\treturn - (*x1) * (*x2);\n\t}\n};\n\ntemplate<size_t n>\nvoid test_trid()\n{\n\tstd::mt19937 prng(0);\n\tstd::normal_distribution<double> normal;\n\tstd::variate_generator<std::tr1::mt19937, std::tr1::normal_distribution<double> > randn(prng,normal);\n\n\tFunction f;\n\n\tstd::vector<double> x(n, 1.0);\n\tfor (size_t i = 0; i < n; ++i) {\n\t\tf.add_variable(&x[i], 1);\n\t}\n\n\tfor (size_t i = 0; i < n; ++i) {\n\t\tf.add_term( new AutoDiffTerm<Trid1, 1>(\n\t\t\tnew Trid1),\n\t\t\t&x[i]);\n\t}\n\n\tfor (size_t i = 1; i < n; ++i) {\n\t\tf.add_term( new AutoDiffTerm<Trid2, 1, 1>(\n\t\t\tnew Trid2),\n\t\t\t&x[i],\n\t\t\t&x[i-1]);\n\t}\n\n\tSolver solver;\n\tsolver.maximum_iterations = 100;\n\t\/\/solver.argument_improvement_tolerance = 1e-16;\n\t\/\/solver.gradient_tolerance = 1e-16;\n\tSolverResults results;\n\tsolver.Solve(f, &results);\n\tstd::cerr << results;\n\n\tdouble fval = f.evaluate();\n\tEXPECT_LT(std::abs(fval + n * (n+4) * (n-1) \/ 6.0) \/ std::abs(fval), 1e-9);\n\tEXPECT_TRUE(results.exit_condition == SolverResults::ARGUMENT_TOLERANCE ||\n\t results.exit_condition == SolverResults::FUNCTION_TOLERANCE ||\n\t results.exit_condition == SolverResults::GRADIENT_TOLERANCE);\n}\n\nTEST(Solver, Trid10) \n{\n\ttest_trid<10>();\n}\n\nTEST(Solver, Trid1000) \n{\n\ttest_trid<1000>();\n}\n\nTEST(Solver, Trid10000) \n{\n\ttest_trid<10000>();\n}\n\nTEST(Solver, Trid100000) \n{\n\ttest_trid<100000>();\n}<commit_msg>More tests in large test suite<commit_after>\n#include <cmath>\n#include <iostream>\n#include <random>\n#include <vector>\n\n#include <gtest\/gtest.h>\n\n#include <spii\/auto_diff_term.h>\n#include <spii\/solver.h>\n\n\/\/ \"An analysis of the behavior of a glass of genetic adaptive systems.\"\n\/\/ K.A. De Jong. Ph.D. thesis, University of Michigan, 1975.\nstruct GeneralizedRosenbrockTerm\n{\n\ttemplate<typename R>\n\tR operator()(const R* const x1, const R* const x2)\n\t{\n\t\tR d0 = (*x1) * (*x1) - (*x2);\n\t\tR d1 = 1 - (*x1);\n\t\treturn 100 * d0*d0 + d1*d1;\n\t}\n};\n\n\/\/ An easier variant.\nstruct EasyRosenbrockTerm\n{\n\ttemplate<typename R>\n\tR operator()(const R* const x1, const R* const x2)\n\t{\n\t\tR d0 = (*x1) * (*x1) - (*x2);\n\t\tR d1 = 1 - (*x1);\n\t\treturn d0*d0 + d1*d1;\n\t}\n};\n\ntemplate<typename Functor, size_t n>\nvoid test_rosenbrock()\n{\n\tFunction f;\n\tstd::vector<double> x(n);\n\tfor (size_t i = 0; i < n; ++i) {\n\t\tf.add_variable(&x[i], 1);\n\t}\n\n\t\/\/ Initial values.\n\tfor (size_t i = 0; i < n; ++i) {\n\t\tif (i % 2 == 0) {\n\t\t\tx[i] = -1.2;\n\t\t}\n\t\telse {\n\t\t\tx[i] = 1.0;\n\t\t}\n\t}\n\n\t\/\/ Add all diagonal terms.\n\tfor (size_t i = 0; i < n - 1; ++i) {\n\t\tf.add_term(new AutoDiffTerm<Functor, 1, 1>\n\t\t (new Functor()), &x[i], &x[i+1]);\n\t}\n\n\tSolver solver;\n\tsolver.maximum_iterations = 10000;\n\tSolverResults results;\n\tsolver.Solve(f, &results);\n\tstd::cerr << results;\n\n\tEXPECT_TRUE(results.exit_condition == SolverResults::ARGUMENT_TOLERANCE ||\n\t results.exit_condition == SolverResults::FUNCTION_TOLERANCE ||\n\t results.exit_condition == SolverResults::GRADIENT_TOLERANCE);\n\n\tEXPECT_LT( std::abs(f.evaluate()), 1e-9);\n\n\tfor (size_t i = 0; i < n - 1; ++i) {\n\t\tASSERT_LT( std::abs(x[i] - 1.0), 1e-9);\n\t}\n}\n\n\nTEST(Solver, EasyRosenbrock1000)\n{\n\ttest_rosenbrock<EasyRosenbrockTerm, 1000>();\n}\n\nTEST(Solver, EasyRosenbrock10000)\n{\n\ttest_rosenbrock<EasyRosenbrockTerm, 10000>();\n}\n\nstruct LennardJones\n{\n\ttemplate<typename R>\n\tR operator()(const R* const p1, const R* const p2)\n\t{\n\t\tR dx = p1[0] - p2[0];\n\t\tR dy = p1[1] - p2[1];\n\t\tR dz = p1[2] - p2[2];\n\t\tR r2 = dx*dx + dy*dy + dz*dz;\n\t\tR r6 = r2*r2*r2;\n\t\tR r12 = r6*r6;\n\t\treturn 1.0 \/ r12 - 1.0 \/ r6;\n\t}\n};\n\nTEST(Solver, LennardJones)\n{\n\tstd::mt19937 prng(0);\n\tstd::normal_distribution<double> normal;\n\tstd::variate_generator<std::tr1::mt19937, std::tr1::normal_distribution<double> > randn(prng,normal);\n\n\tint n = 5;\n\n\tFunction potential;\n\n\tstd::vector<Eigen::Vector3d> points(n*n*n);\n\tfor (int x = 0; x < n; ++x) {\n\t\tfor (int y = 0; y < n; ++y) {\n\t\t\tfor (int z = 0; z < n; ++z) {\n\t\t\t\tpoints[x + y*n + z*n*n][0] = x + 0.05 * randn();\n\t\t\t\tpoints[x + y*n + z*n*n][1] = y + 0.05 * randn();\n\t\t\t\tpoints[x + y*n + z*n*n][2] = z + 0.05 * randn();\n\n\t\t\t\tpotential.add_variable(&points[x + y*n + z*n*n][0], 3);\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/ Add all pairwise terms\n\tfor (int i = 0; i < n*n*n; ++i) {\n\t\tfor (int j = i + 1; j < n*n*n; ++j) {\n\t\t\tpotential.add_term(\n\t\t\t\tnew AutoDiffTerm<LennardJones, 3, 3>(\n\t\t\t\t\tnew LennardJones),\n\t\t\t\t\t&points[i][0],\n\t\t\t\t\t&points[j][0]);\n\t\t}\n\t}\n\n\tSolver solver;\n\tsolver.maximum_iterations = 100;\n\t\/\/ All points interact with all points, so the Hessian\n\t\/\/ will be dense.\n\tsolver.sparsity_mode = Solver::DENSE;\n\tSolverResults results;\n\tsolver.Solve(potential, &results);\n\tstd::cerr << results;\n\n\tEXPECT_TRUE(results.exit_condition == SolverResults::ARGUMENT_TOLERANCE ||\n\t results.exit_condition == SolverResults::FUNCTION_TOLERANCE ||\n\t results.exit_condition == SolverResults::GRADIENT_TOLERANCE);\n}\n\nstruct Trid1\n{\n\ttemplate<typename R>\n\tR operator()(const R* const x)\n\t{\n\t\tR d = *x - 1.0;\n\t\treturn d*d;\n\t}\n};\n\nstruct Trid2\n{\n\ttemplate<typename R>\n\tR operator()(const R* const x1, const R* const x2)\n\t{\n\t\treturn - (*x1) * (*x2);\n\t}\n};\n\ntemplate<size_t n>\nvoid test_trid()\n{\n\tFunction f;\n\n\tstd::vector<double> x(n, 1.0);\n\tfor (size_t i = 0; i < n; ++i) {\n\t\tf.add_variable(&x[i], 1);\n\t}\n\n\tfor (size_t i = 0; i < n; ++i) {\n\t\tf.add_term( new AutoDiffTerm<Trid1, 1>(\n\t\t\tnew Trid1),\n\t\t\t&x[i]);\n\t}\n\n\tfor (size_t i = 1; i < n; ++i) {\n\t\tf.add_term( new AutoDiffTerm<Trid2, 1, 1>(\n\t\t\tnew Trid2),\n\t\t\t&x[i],\n\t\t\t&x[i-1]);\n\t}\n\n\tSolver solver;\n\tsolver.maximum_iterations = 100;\n\t\/\/solver.argument_improvement_tolerance = 1e-16;\n\t\/\/solver.gradient_tolerance = 1e-16;\n\tSolverResults results;\n\tsolver.Solve(f, &results);\n\tstd::cerr << results;\n\n\tdouble fval = f.evaluate();\n\t\/\/ Global optimum is \n\t\/\/\n\t\/\/ x[i] = (i + 1) * (n - i)\n\t\/\/\n\t\/\/ Therefore, it is hard to calulate the optimal function\n\t\/\/ value for large n.\n\t\/\/\n\tdouble tol = 1e-9;\n\tif (n >= 10000) {\n\t\ttol = 1e-6;\n\t}\n\tif (n >= 100000) {\n\t\ttol = 1e-4;\n\t}\n\tEXPECT_LT(std::abs(fval + n * (n+4) * (n-1) \/ 6.0) \/ std::abs(fval), tol);\n\tEXPECT_TRUE(results.exit_condition == SolverResults::ARGUMENT_TOLERANCE ||\n\t results.exit_condition == SolverResults::FUNCTION_TOLERANCE ||\n\t results.exit_condition == SolverResults::GRADIENT_TOLERANCE);\n\n\tif (n <= 10) {\n\t\tfor (size_t i = 0; i < n; ++i) {\n\t\t\tstd::cerr << \"x[\" << i << \"] = \" << x[i] << '\\n';\n\t\t}\n\t}\n}\n\nTEST(Solver, Trid10) \n{\n\ttest_trid<10>();\n}\n\nTEST(Solver, Trid1000) \n{\n\ttest_trid<1000>();\n}\n\nTEST(Solver, Trid10000) \n{\n\ttest_trid<10000>();\n}\n\n\n\nstruct LogBarrier01\n{\n\ttemplate<typename R>\n\tR operator()(const R* const x)\n\t{\n\t\treturn -log(x[0]) - log(1.0 - x[0]);\n\t}\n};\n\nstruct QuadraticFunction1\n{\n\tQuadraticFunction1(double b)\n\t{\n\t\tthis->b = b;\n\t}\n\n\ttemplate<typename R>\n\tR operator()(const R* const x)\n\t{\n\t\tR d = x[0] - b;\n\t\treturn d * d;\n\t}\n\n\tdouble b;\n};\n\nTEST(Solver, Barrier)\n{\n\tstd::mt19937 prng(0);\n\tstd::normal_distribution<double> normal;\n\tstd::variate_generator<std::tr1::mt19937, std::tr1::normal_distribution<double> > randn(prng,normal);\n\n\tconst int n = 10000;\n\tFunction f;\n\n\tstd::vector<double> x(n, 0.5);\n\tfor (size_t i = 0; i < n; ++i) {\n\t\tf.add_variable(&x[i], 1);\n\t\tf.add_term( new AutoDiffTerm<QuadraticFunction1, 1>(\n\t\t\tnew QuadraticFunction1(0.5 + randn())),\n\t\t\t&x[i]);\n\t\tf.add_term( new AutoDiffTerm<LogBarrier01, 1>(\n\t\t\tnew LogBarrier01),\n\t\t\t&x[i]);\n\t}\n\n\tSolver solver;\n\tsolver.maximum_iterations = 100;\n\tSolverResults results;\n\tsolver.Solve(f, &results);\n\tstd::cerr << results;\n\n\tstd::cerr << results;\n\tstd::cerr << \"-----------------------------------\\n\";\n\tstd::cerr << \"Function evaluate time : \" << f.evaluate_time << '\\n';\n\tstd::cerr << \"Function evaluate time (with hessian) : \" << f.evaluate_with_hessian_time << '\\n';\n\tstd::cerr << \"Function write hessian time : \" << f.write_gradient_hessian_time << '\\n';\n\tstd::cerr << \"Function copy data time : \" << f.copy_time << '\\n';\n\n\tEXPECT_TRUE(results.exit_condition == SolverResults::ARGUMENT_TOLERANCE ||\n\t results.exit_condition == SolverResults::FUNCTION_TOLERANCE ||\n\t results.exit_condition == SolverResults::GRADIENT_TOLERANCE);\n}\n<|endoftext|>"} {"text":"<commit_before>\/**\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements. See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership. The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include <gtest\/gtest.h>\n\n#include <list>\n#include <string>\n\n#include <process\/gmock.hpp>\n#include <process\/gtest.hpp>\n\n#include <stout\/check.hpp>\n#include <stout\/error.hpp>\n#include <stout\/exit.hpp>\n#include <stout\/os.hpp>\n#include <stout\/strings.hpp>\n\n#ifdef __linux__\n#include \"linux\/cgroups.hpp\"\n#endif\n\n#include \"logging\/logging.hpp\"\n\n#include \"tests\/environment.hpp\"\n#include \"tests\/flags.hpp\"\n\nusing std::list;\nusing std::string;\n\nnamespace mesos {\nnamespace internal {\nnamespace tests {\n\n\/\/ Storage for the global environment instance.\nEnvironment* environment;\n\n\n\/\/ Returns true if we should enable the provided test. Similar to how\n\/\/ tests can be disabled using the 'DISABLED_' prefix on a test case\n\/\/ name or test name, we use:\n\/\/\n\/\/ 'ROOT_' : Disable test if current user isn't root.\n\/\/ 'CGROUPS_' : Disable test if cgroups support isn't present.\n\/\/ 'NOHIERARCHY_' : Disable test if there is already a cgroups\n\/\/ hierarchy mounted.\n\/\/\n\/\/ These flags can be composed in any order, but must come after\n\/\/ 'DISABLED_'. In addition, we disable tests that attempt to use the\n\/\/ CgroupsIsolator type parameter if the current user is not root or\n\/\/ cgroups is not supported.\n\/\/ TODO(benh): Provide a generic way to enable\/disable tests by\n\/\/ registering \"filter\" functions.\nstatic bool enable(const ::testing::TestInfo& test)\n{\n \/\/ First check the test case name and test name.\n list<string> names;\n names.push_back(test.test_case_name());\n names.push_back(test.name());\n\n foreach (const string& name, names) {\n if (strings::contains(name, \"ROOT_\") && os::user() != \"root\") {\n return false;\n }\n\n if (strings::contains(name, \"CGROUPS_\") && !os::exists(\"\/proc\/cgroups\")) {\n return false;\n }\n\n#ifdef __linux__\n if (strings::contains(name, \"NOHIERARCHY_\")) {\n Try<std::set<std::string> > hierarchies = cgroups::hierarchies();\n CHECK_SOME(hierarchies);\n if (!hierarchies.get().empty()) {\n std::cerr\n << \"-------------------------------------------------------------\\n\"\n << \"We cannot run any cgroups tests that require mounting\\n\"\n << \"hierarchies because you have the following hierarchies mounted:\\n\"\n << strings::trim(stringify(hierarchies.get()), \" {},\") << \"\\n\"\n << \"We'll disable the CgroupsNoHierarchyTest test fixture for now.\\n\"\n << \"-------------------------------------------------------------\"\n << std::endl;\n\n return false;\n }\n }\n#endif\n }\n\n \/\/ Now check the type parameter.\n if (test.type_param() != NULL) {\n const string& type = test.type_param();\n if (strings::contains(type, \"CgroupsIsolator\") &&\n (os::user() != \"root\" || !os::exists(\"\/proc\/cgroups\"))) {\n return false;\n }\n#ifdef __APPLE__\n if (strings::contains(test.test_case_name(), \"IsolatorTest\") &&\n strings::contains(test.name(), \"Usage\") &&\n strings::contains(type, \"ProcessIsolator\") &&\n os::user() != \"root\") {\n \/\/ We can't run the Isolator resource usage test when we're not\n \/\/ the root user on OSX because proc_pidinfo() only returns\n \/\/ memory and CPU usage reliably when running as root.\n return false;\n }\n#endif\n }\n\n return true;\n}\n\n\n\/\/ We use the constructor to setup specific tests by updating the\n\/\/ gtest filter. We do this so that we can selectively run tests that\n\/\/ require root or specific OS support (e.g., cgroups). Note that this\n\/\/ should not effect any other filters that have been put in place\n\/\/ either on the command line or via an environment variable.\n\/\/ N.B. This MUST be done _before_ invoking RUN_ALL_TESTS.\nEnvironment::Environment()\n{\n \/\/ First we split the current filter into enabled and disabled tests\n \/\/ (which are separated by a '-').\n const string& filter = ::testing::GTEST_FLAG(filter);\n\n \/\/ An empty filter indicates no tests should be run.\n if (filter.empty()) {\n return;\n }\n\n string enabled;\n string disabled;\n\n size_t dash = filter.find('-');\n if (dash != string::npos) {\n enabled = filter.substr(0, dash);\n disabled = filter.substr(dash + 1);\n } else {\n enabled = filter;\n }\n\n \/\/ Use universal filter if not specified.\n if (enabled.empty()) {\n enabled = \"*\";\n }\n\n \/\/ Ensure disabled tests end with \":\" separator before we add more.\n if (!disabled.empty() && !strings::endsWith(disabled, \":\")) {\n disabled += \":\";\n }\n\n \/\/ Construct the filter string to handle system or platform specific tests.\n ::testing::UnitTest* unitTest = ::testing::UnitTest::GetInstance();\n for (int i = 0; i < unitTest->total_test_case_count(); i++) {\n const ::testing::TestCase* testCase = unitTest->GetTestCase(i);\n for (int j = 0; j < testCase->total_test_count(); j++) {\n const ::testing::TestInfo* testInfo = testCase->GetTestInfo(j);\n\n if (!enable(*testCase->GetTestInfo(j))) {\n \/\/ Append 'TestCase.TestName:'.\n disabled.append(testInfo->test_case_name());\n disabled.append(\".\");\n disabled.append(testInfo->name());\n disabled.append(\":\");\n }\n }\n }\n\n \/\/ Now update the gtest flag.\n ::testing::GTEST_FLAG(filter) = enabled + \"-\" + disabled;\n\n \/\/ Add our test event listeners.\n ::testing::TestEventListeners& listeners =\n ::testing::UnitTest::GetInstance()->listeners();\n\n listeners.Append(process::FilterTestEventListener::instance());\n listeners.Append(process::ClockTestEventListener::instance());\n}\n\n\nEnvironment::~Environment()\n{\n foreach (const string& directory, directories) {\n Try<Nothing> rmdir = os::rmdir(directory);\n if (rmdir.isError()) {\n LOG(ERROR) << \"Failed to remove '\" << directory\n << \"': \" << rmdir.error();\n }\n }\n}\n\n\nvoid Environment::SetUp()\n{\n \/\/ Clear any MESOS_ environment variables so they don't affect our tests.\n char** environ = os::environ();\n for (int i = 0; environ[i] != NULL; i++) {\n std::string variable = environ[i];\n if (variable.find(\"MESOS_\") == 0) {\n string key;\n size_t eq = variable.find_first_of(\"=\");\n if (eq == string::npos) {\n continue; \/\/ Not expecting a missing '=', but ignore anyway.\n }\n os::unsetenv(variable.substr(strlen(\"MESOS_\"), eq - strlen(\"MESOS_\")));\n }\n }\n\n if (!GTEST_IS_THREADSAFE) {\n EXIT(1) << \"Testing environment is not thread safe, bailing!\";\n }\n}\n\n\nTry<string> Environment::mkdtemp()\n{\n const ::testing::TestInfo* const testInfo =\n ::testing::UnitTest::GetInstance()->current_test_info();\n\n if (testInfo == NULL) {\n return Error(\"Failed to determine the current test information\");\n }\n\n \/\/ We replace any slashes present in the test names (e.g. TYPED_TEST),\n \/\/ to make sure the temporary directory resides under '\/tmp\/'.\n const string& testCase =\n strings::replace(testInfo->test_case_name(), \"\/\", \"_\");\n\n string testName = strings::replace(testInfo->name(), \"\/\", \"_\");\n\n \/\/ Adjust the test name to remove any 'DISABLED_' prefix (to make\n \/\/ things easier to read). While this might seem alarming, if we are\n \/\/ \"running\" a disabled test it must be the case that the test was\n \/\/ explicitly enabled (e.g., via 'gtest_filter').\n if (strings::startsWith(testName, \"DISABLED_\")) {\n testName = strings::remove(testName, \"DISABLED_\", strings::PREFIX);\n }\n\n const string& path =\n path::join(\"\/tmp\", strings::join(\"_\", testCase, testName, \"XXXXXX\"));\n\n return os::mkdtemp(path);\n}\n\n} \/\/ namespace tests {\n} \/\/ namespace internal {\n} \/\/ namespace mesos {\n\n<commit_msg>Set MESOS_NATIVE_LIBRARY in the testing environment.<commit_after>\/**\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements. See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership. The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include <gtest\/gtest.h>\n\n#include <list>\n#include <string>\n\n#include <process\/gmock.hpp>\n#include <process\/gtest.hpp>\n\n#include <stout\/check.hpp>\n#include <stout\/error.hpp>\n#include <stout\/exit.hpp>\n#include <stout\/os.hpp>\n#include <stout\/strings.hpp>\n\n#ifdef __linux__\n#include \"linux\/cgroups.hpp\"\n#endif\n\n#include \"logging\/logging.hpp\"\n\n#include \"tests\/environment.hpp\"\n#include \"tests\/flags.hpp\"\n\nusing std::list;\nusing std::string;\n\nnamespace mesos {\nnamespace internal {\nnamespace tests {\n\n\/\/ Storage for the global environment instance.\nEnvironment* environment;\n\n\n\/\/ Returns true if we should enable the provided test. Similar to how\n\/\/ tests can be disabled using the 'DISABLED_' prefix on a test case\n\/\/ name or test name, we use:\n\/\/\n\/\/ 'ROOT_' : Disable test if current user isn't root.\n\/\/ 'CGROUPS_' : Disable test if cgroups support isn't present.\n\/\/ 'NOHIERARCHY_' : Disable test if there is already a cgroups\n\/\/ hierarchy mounted.\n\/\/\n\/\/ These flags can be composed in any order, but must come after\n\/\/ 'DISABLED_'. In addition, we disable tests that attempt to use the\n\/\/ CgroupsIsolator type parameter if the current user is not root or\n\/\/ cgroups is not supported.\n\/\/ TODO(benh): Provide a generic way to enable\/disable tests by\n\/\/ registering \"filter\" functions.\nstatic bool enable(const ::testing::TestInfo& test)\n{\n \/\/ First check the test case name and test name.\n list<string> names;\n names.push_back(test.test_case_name());\n names.push_back(test.name());\n\n foreach (const string& name, names) {\n if (strings::contains(name, \"ROOT_\") && os::user() != \"root\") {\n return false;\n }\n\n if (strings::contains(name, \"CGROUPS_\") && !os::exists(\"\/proc\/cgroups\")) {\n return false;\n }\n\n#ifdef __linux__\n if (strings::contains(name, \"NOHIERARCHY_\")) {\n Try<std::set<std::string> > hierarchies = cgroups::hierarchies();\n CHECK_SOME(hierarchies);\n if (!hierarchies.get().empty()) {\n std::cerr\n << \"-------------------------------------------------------------\\n\"\n << \"We cannot run any cgroups tests that require mounting\\n\"\n << \"hierarchies because you have the following hierarchies mounted:\\n\"\n << strings::trim(stringify(hierarchies.get()), \" {},\") << \"\\n\"\n << \"We'll disable the CgroupsNoHierarchyTest test fixture for now.\\n\"\n << \"-------------------------------------------------------------\"\n << std::endl;\n\n return false;\n }\n }\n#endif\n }\n\n \/\/ Now check the type parameter.\n if (test.type_param() != NULL) {\n const string& type = test.type_param();\n if (strings::contains(type, \"CgroupsIsolator\") &&\n (os::user() != \"root\" || !os::exists(\"\/proc\/cgroups\"))) {\n return false;\n }\n#ifdef __APPLE__\n if (strings::contains(test.test_case_name(), \"IsolatorTest\") &&\n strings::contains(test.name(), \"Usage\") &&\n strings::contains(type, \"ProcessIsolator\") &&\n os::user() != \"root\") {\n \/\/ We can't run the Isolator resource usage test when we're not\n \/\/ the root user on OSX because proc_pidinfo() only returns\n \/\/ memory and CPU usage reliably when running as root.\n return false;\n }\n#endif\n }\n\n return true;\n}\n\n\n\/\/ We use the constructor to setup specific tests by updating the\n\/\/ gtest filter. We do this so that we can selectively run tests that\n\/\/ require root or specific OS support (e.g., cgroups). Note that this\n\/\/ should not effect any other filters that have been put in place\n\/\/ either on the command line or via an environment variable.\n\/\/ N.B. This MUST be done _before_ invoking RUN_ALL_TESTS.\nEnvironment::Environment()\n{\n \/\/ First we split the current filter into enabled and disabled tests\n \/\/ (which are separated by a '-').\n const string& filter = ::testing::GTEST_FLAG(filter);\n\n \/\/ An empty filter indicates no tests should be run.\n if (filter.empty()) {\n return;\n }\n\n string enabled;\n string disabled;\n\n size_t dash = filter.find('-');\n if (dash != string::npos) {\n enabled = filter.substr(0, dash);\n disabled = filter.substr(dash + 1);\n } else {\n enabled = filter;\n }\n\n \/\/ Use universal filter if not specified.\n if (enabled.empty()) {\n enabled = \"*\";\n }\n\n \/\/ Ensure disabled tests end with \":\" separator before we add more.\n if (!disabled.empty() && !strings::endsWith(disabled, \":\")) {\n disabled += \":\";\n }\n\n \/\/ Construct the filter string to handle system or platform specific tests.\n ::testing::UnitTest* unitTest = ::testing::UnitTest::GetInstance();\n for (int i = 0; i < unitTest->total_test_case_count(); i++) {\n const ::testing::TestCase* testCase = unitTest->GetTestCase(i);\n for (int j = 0; j < testCase->total_test_count(); j++) {\n const ::testing::TestInfo* testInfo = testCase->GetTestInfo(j);\n\n if (!enable(*testCase->GetTestInfo(j))) {\n \/\/ Append 'TestCase.TestName:'.\n disabled.append(testInfo->test_case_name());\n disabled.append(\".\");\n disabled.append(testInfo->name());\n disabled.append(\":\");\n }\n }\n }\n\n \/\/ Now update the gtest flag.\n ::testing::GTEST_FLAG(filter) = enabled + \"-\" + disabled;\n\n \/\/ Add our test event listeners.\n ::testing::TestEventListeners& listeners =\n ::testing::UnitTest::GetInstance()->listeners();\n\n listeners.Append(process::FilterTestEventListener::instance());\n listeners.Append(process::ClockTestEventListener::instance());\n}\n\n\nEnvironment::~Environment()\n{\n foreach (const string& directory, directories) {\n Try<Nothing> rmdir = os::rmdir(directory);\n if (rmdir.isError()) {\n LOG(ERROR) << \"Failed to remove '\" << directory\n << \"': \" << rmdir.error();\n }\n }\n}\n\n\nvoid Environment::SetUp()\n{\n \/\/ Clear any MESOS_ environment variables so they don't affect our tests.\n char** environ = os::environ();\n for (int i = 0; environ[i] != NULL; i++) {\n std::string variable = environ[i];\n if (variable.find(\"MESOS_\") == 0) {\n string key;\n size_t eq = variable.find_first_of(\"=\");\n if (eq == string::npos) {\n continue; \/\/ Not expecting a missing '=', but ignore anyway.\n }\n os::unsetenv(variable.substr(strlen(\"MESOS_\"), eq - strlen(\"MESOS_\")));\n }\n }\n\n \/\/ Set the path to the native library for running JVM tests.\n if (!os::hasenv(\"MESOS_NATIVE_LIBRARY\")) {\n string path = path::join(tests::flags.build_dir, \"src\", \".libs\");\n#ifdef __APPLE__\n path = path::join(path, \"libmesos-\" VERSION \".dylib\");\n#else\n path = path::join(path, \"libmesos-\" VERSION \".so\");\n#endif\n os::setenv(\"MESOS_NATIVE_LIBRARY\", path);\n }\n\n if (!GTEST_IS_THREADSAFE) {\n EXIT(1) << \"Testing environment is not thread safe, bailing!\";\n }\n}\n\n\nTry<string> Environment::mkdtemp()\n{\n const ::testing::TestInfo* const testInfo =\n ::testing::UnitTest::GetInstance()->current_test_info();\n\n if (testInfo == NULL) {\n return Error(\"Failed to determine the current test information\");\n }\n\n \/\/ We replace any slashes present in the test names (e.g. TYPED_TEST),\n \/\/ to make sure the temporary directory resides under '\/tmp\/'.\n const string& testCase =\n strings::replace(testInfo->test_case_name(), \"\/\", \"_\");\n\n string testName = strings::replace(testInfo->name(), \"\/\", \"_\");\n\n \/\/ Adjust the test name to remove any 'DISABLED_' prefix (to make\n \/\/ things easier to read). While this might seem alarming, if we are\n \/\/ \"running\" a disabled test it must be the case that the test was\n \/\/ explicitly enabled (e.g., via 'gtest_filter').\n if (strings::startsWith(testName, \"DISABLED_\")) {\n testName = strings::remove(testName, \"DISABLED_\", strings::PREFIX);\n }\n\n const string& path =\n path::join(\"\/tmp\", strings::join(\"_\", testCase, testName, \"XXXXXX\"));\n\n return os::mkdtemp(path);\n}\n\n} \/\/ namespace tests {\n} \/\/ namespace internal {\n} \/\/ namespace mesos {\n\n<|endoftext|>"} {"text":"<commit_before><commit_msg>frame length time ramp up fix<commit_after><|endoftext|>"} {"text":"<commit_before><commit_msg>gtk: Add GtkTreeView inside GtkScrollableWindow [PERFECTIVE]<commit_after><|endoftext|>"} {"text":"<commit_before>#include \"signalutil.h\"\n\n\n#include <cstring>\n#include <cmath>\n#include \"bussignaldef.h\"\n\n\nnamespace\n{\n\n\ninline bool is_fraction(double val)\n{\n double integral;\n auto fractional = std::modf(val, &integral);\n return std::abs(fractional) != 0;\n}\n\n\ntemplate<typename T> tin::phys_val calc_phys(T val, double factor, double offset)\n{\n \/\/ Nothing to be done, raw and physical value are identical\n if (factor == 1 && offset == 0)\n return val;\n\n \/\/ We need a floating point value to represent the result\n if (is_fraction(factor) || is_fraction(offset))\n return static_cast<double>(val) * factor + offset;\n\n \/\/ Let's squeeze the result into an integer and hope it fits (sue me)\n return static_cast<std::int64_t>(val * factor + offset);\n}\ntemplate tin::phys_val calc_phys(std::uint64_t, double, double);\ntemplate tin::phys_val calc_phys(std::int64_t, double, double);\n\n\n}\n\n\ntin::raw_val tin::build_raw_value(const std::array<std::uint8_t, 8>& buffer, std::uint32_t pos,\n std::uint32_t len, Byte_order order, Value_sign sign)\n{\n std::uint64_t raw;\n std::memcpy(&raw, &buffer, sizeof(raw));\n\n if (order == tin::Byte_order::Moto) {\n raw = __builtin_bswap64(raw);\n pos = pswap64(pos) - len + 1; \/\/ Set position to least significant bit\n }\n\n \/\/ Using unsigned since shift operations on signed values aren't well-defined\n raw <<= 64 - (pos + len);\n bool is_negative = raw & (1ull << 63);\n if (sign == tin::Value_sign::Signed && is_negative)\n raw = ~raw; \/\/ Prepare negative values for zero-insertions due to right shift\n raw >>= 64 - len;\n if (sign == tin::Value_sign::Signed) {\n if (is_negative)\n raw = ~raw; \/\/ Flipping back to proper value (all inserted zeros are now one)\n std::int64_t raw_signed;\n std::memcpy(&raw_signed, &raw, sizeof(raw_signed));\n return raw_signed;\n }\n return raw;\n}\n\n\ntin::phys_val tin::calc_phys_value(raw_val raw, double factor, double offset)\n{\n if (std::holds_alternative<std::uint64_t>(raw))\n return calc_phys(std::get<std::uint64_t>(raw), factor, offset);\n return calc_phys(std::get<std::int64_t>(raw), factor, offset);\n}\n<commit_msg>Improve portability<commit_after>#include \"signalutil.h\"\n\n\n#include <cstring>\n#include <cmath>\n\n#ifdef _MSC_VER\n #include <stdlib.h>\n#endif\n\n#include \"bussignaldef.h\"\n\n\nnamespace\n{\n\n\ninline bool is_fraction(double val)\n{\n double integral;\n auto fractional = std::modf(val, &integral);\n return std::abs(fractional) != 0;\n}\n\n\ntemplate<typename T> tin::phys_val calc_phys(T val, double factor, double offset)\n{\n \/\/ Nothing to be done, raw and physical value are identical\n if (factor == 1 && offset == 0)\n return val;\n\n \/\/ We need a floating point value to represent the result\n if (is_fraction(factor) || is_fraction(offset))\n return static_cast<double>(val) * factor + offset;\n\n \/\/ Let's squeeze the result into an integer and hope it fits (sue me)\n return static_cast<std::int64_t>(val * factor + offset);\n}\ntemplate tin::phys_val calc_phys(std::uint64_t, double, double);\ntemplate tin::phys_val calc_phys(std::int64_t, double, double);\n\n\n} \/\/ namespace\n\n\ntin::raw_val tin::build_raw_value(const std::array<std::uint8_t, 8>& buffer, std::uint32_t pos,\n std::uint32_t len, Byte_order order, Value_sign sign)\n{\n std::uint64_t raw;\n std::memcpy(&raw, &buffer, sizeof(raw));\n\n if (order == tin::Byte_order::Moto) {\n#ifdef __GNUC__\n raw = __builtin_bswap64(raw);\n#elif _MSC_VER\n raw = _byteswap_uint64(raw);\n#else\n #error \"Byte swap required\"\n#endif\n pos = pswap64(pos) - len + 1; \/\/ Set position to least significant bit\n }\n\n \/\/ Using unsigned since shift operations on signed values aren't well-defined\n raw <<= 64 - (pos + len);\n bool is_negative = raw & (1ull << 63);\n if (sign == tin::Value_sign::Signed && is_negative)\n raw = ~raw; \/\/ Prepare negative values for zero-insertions due to right shift\n raw >>= 64 - len;\n if (sign == tin::Value_sign::Signed) {\n if (is_negative)\n raw = ~raw; \/\/ Flipping back to proper value (all inserted zeros are now one)\n std::int64_t raw_signed;\n std::memcpy(&raw_signed, &raw, sizeof(raw_signed));\n return raw_signed;\n }\n return raw;\n}\n\n\ntin::phys_val tin::calc_phys_value(raw_val raw, double factor, double offset)\n{\n if (std::holds_alternative<std::uint64_t>(raw))\n return calc_phys(std::get<std::uint64_t>(raw), factor, offset);\n return calc_phys(std::get<std::int64_t>(raw), factor, offset);\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"InternalStructFeature.h\"\n\nusing namespace std;\n\nnamespace MosesTraining\n{\n\nInternalStructFeature::InternalStructFeature()\n\t:m_type(0){\n\t\/\/cout<<\"InternalStructFeature: Construct \"<<m_type<<\"\\n\";\n}\n\nbool InternalStructFeature::equals(const PhraseAlignment& lhs, const PhraseAlignment& rhs) const{\n\tcout<<\"InternalStructFeature: Equals\\n\";\n\t\/\/don't know what it's used for and what we should compare\n\t\/\/-> if the dense score is the same\n\t\/\/-> if the sparse feature is set\n\t\/\/ compare phrases? with the internalStrucutre string?\n\t\/** Return true if the two phrase pairs are equal from the point of this feature. Assume\n\t that they already compare true according to PhraseAlignment.equals()\n\t **\/\n\treturn true;\n}\n\nvoid InternalStructFeature::add(const ScoreFeatureContext& context,\n\t std::vector<float>& denseValues,\n\t std::map<std::string,float>& sparseValues) const{\n\tfor(size_t i=0; i<context.phrasePair.size(); i++) {\n\t\tadd(&context.phrasePair[i]->ghkmParse, denseValues, sparseValues);\n\t}\n\n}\n\nvoid InternalStructFeatureDense::add(std::string *internalStruct,\n\t std::vector<float>& denseValues,\n\t std::map<std::string,float>& sparseValues) const{\n\t\/\/cout<<\"Dense: \"<<*internalStruct<<endl;\n\tsize_t start=0;\n\tint countNP=0;\n\twhile((start = internalStruct->find(\"NP\", start)) != string::npos) {\n\t\tcountNP++;\n\t\tstart+=2; \/\/length of \"NP\"\n\t}\n\t\/\/should add e^countNP so in the decoder I get log(e^countNP)=countNP -> but is log or ln?\n\t\/\/should use this but don't know what it does? -> maybeLog( (bitmap == i) ? 2.718 : 1 )\n\tdenseValues.push_back(exp(countNP));\n\n}\n\nvoid InternalStructFeatureSparse::add(std::string *internalStruct,\n\t std::vector<float>& denseValues,\n\t std::map<std::string,float>& sparseValues) const{\n\t\/\/cout<<\"Sparse: \"<<*internalStruct<<endl;\n\tif(internalStruct->find(\"VBZ\")!=std::string::npos)\n\t\tsparseValues[\"NTVBZ\"] = 1;\n\tif(internalStruct->find(\"VBD\")!=std::string::npos)\n\t\t\tsparseValues[\"NTVBD\"] = 1;\n\tif(internalStruct->find(\"VBP\")!=std::string::npos)\n\t\t\t\tsparseValues[\"NTVBP\"] = 1;\n\tif(internalStruct->find(\"PP\")!=std::string::npos)\n\t\t\t\tsparseValues[\"NTPP\"] = 1;\n\tif(internalStruct->find(\"SBAR\")!=std::string::npos)\n\t\t\t\tsparseValues[\"NTSBAR\"] = 1;\n\n}\n\n\n}\n<commit_msg>comment for Equal implementation<commit_after>#include \"InternalStructFeature.h\"\n\nusing namespace std;\n\nnamespace MosesTraining\n{\n\nInternalStructFeature::InternalStructFeature()\n\t:m_type(0){\n\t\/\/cout<<\"InternalStructFeature: Construct \"<<m_type<<\"\\n\";\n}\n\nbool InternalStructFeature::equals(const PhraseAlignment& lhs, const PhraseAlignment& rhs) const{\n\t\/\/cout<<\"InternalStructFeature: Equals\\n\";\n\t\/\/don't know what it's used for and what we should compare\n\t\/\/-> if the dense score is the same\n\t\/\/-> if the sparse feature is set\n\t\/\/ compare phrases? with the internalStrucutre string?\n\t\/** Return true if the two phrase pairs are equal from the point of this feature. Assume\n\t that they already compare true according to PhraseAlignment.equals()\n\t **\/\n\n\/*\tif(lhs.ghkmParse==rhs.ghkmParse)\n\t\treturn true;\n\telse\n\t\treturn false;\n*\/\n\t\/\/return true;\n}\n\nvoid InternalStructFeature::add(const ScoreFeatureContext& context,\n\t std::vector<float>& denseValues,\n\t std::map<std::string,float>& sparseValues) const{\n\tfor(size_t i=0; i<context.phrasePair.size(); i++) {\n\t\tadd(&context.phrasePair[i]->ghkmParse, denseValues, sparseValues);\n\t}\n\n}\n\nvoid InternalStructFeatureDense::add(std::string *internalStruct,\n\t std::vector<float>& denseValues,\n\t std::map<std::string,float>& sparseValues) const{\n\t\/\/cout<<\"Dense: \"<<*internalStruct<<endl;\n\tsize_t start=0;\n\tint countNP=0;\n\twhile((start = internalStruct->find(\"NP\", start)) != string::npos) {\n\t\tcountNP++;\n\t\tstart+=2; \/\/length of \"NP\"\n\t}\n\t\/\/should add e^countNP so in the decoder I get log(e^countNP)=countNP -> but is log or ln?\n\t\/\/should use this but don't know what it does? -> maybeLog( (bitmap == i) ? 2.718 : 1 )\n\tdenseValues.push_back(exp(countNP));\n\n}\n\nvoid InternalStructFeatureSparse::add(std::string *internalStruct,\n\t std::vector<float>& denseValues,\n\t std::map<std::string,float>& sparseValues) const{\n\t\/\/cout<<\"Sparse: \"<<*internalStruct<<endl;\n\tif(internalStruct->find(\"VBZ\")!=std::string::npos)\n\t\tsparseValues[\"NTVBZ\"] = 1;\n\tif(internalStruct->find(\"VBD\")!=std::string::npos)\n\t\t\tsparseValues[\"NTVBD\"] = 1;\n\tif(internalStruct->find(\"VBP\")!=std::string::npos)\n\t\t\t\tsparseValues[\"NTVBP\"] = 1;\n\tif(internalStruct->find(\"PP\")!=std::string::npos)\n\t\t\t\tsparseValues[\"NTPP\"] = 1;\n\tif(internalStruct->find(\"SBAR\")!=std::string::npos)\n\t\t\t\tsparseValues[\"NTSBAR\"] = 1;\n\n}\n\n\n}\n<|endoftext|>"} {"text":"<commit_before>#pragma once\n#include \"detect_type.hpp\"\n#include \"lubee\/meta\/enable_if.hpp\"\n#include \"lubee\/none.hpp\"\n#include \"argholder.hpp\"\n#include <utility>\n#include \"none.hpp\"\n\nnamespace spi {\n\ttemplate <class... Ts>\n\tauto construct(Ts&&... ts) {\n\t\treturn ArgHolder<decltype(ts)...>(std::forward<Ts>(ts)...);\n\t}\n\ttemplate <class P>\n\tusing IsRP = std::integral_constant<bool, std::is_reference<P>{} || std::is_pointer<P>{}>;\n\tnamespace opt_tmp {\n\t\ttemplate <class T>\n\t\tstruct alignas(alignof(T)) Buffer {\n\t\t\tuint8_t\t\t_data[sizeof(T)];\n\n\t\t\tBuffer() = default;\n\t\t\ttemplate <class T2>\n\t\t\tBuffer(T2&& t) {\n\t\t\t\tnew(ptr()) T(std::forward<T2>(t));\n\t\t\t}\n\n\t\t\tT* ptr() noexcept {\n\t\t\t\t\/\/ Debug時は中身が有効かチェック\n\t\t\t\t#ifdef DEBUG\n\t\t\t\t#endif\n\t\t\t\treturn reinterpret_cast<T*>(_data);\n\t\t\t}\n\t\t\tconst T* ptr() const noexcept {\n\t\t\t\t\/\/ Debug時は中身が有効かチェック\n\t\t\t\t#ifdef DEBUG\n\t\t\t\t#endif\n\t\t\t\treturn reinterpret_cast<const T*>(_data);\n\t\t\t}\n\t\t\tT& get() noexcept {\n\t\t\t\treturn *ptr();\n\t\t\t}\n\t\t\tconst T& get() const noexcept {\n\t\t\t\treturn *ptr();\n\t\t\t}\n\t\t\ttemplate <class... Ts>\n\t\t\tvoid ctor(Ts&&... ts) noexcept(noexcept(new T(std::forward<Ts>(ts)...))) {\n\t\t\t\tnew(ptr()) T(std::forward<Ts>(ts)...);\n\t\t\t}\n\t\t\tvoid dtor() noexcept {\n\t\t\t\tptr()->~T();\n\t\t\t}\n\t\t\t#define NOEXCEPT_WHEN_RAW(t) noexcept(noexcept(IsRP<t>{}))\n\t\t\ttemplate <class T2>\n\t\t\tBuffer& operator = (T2&& t) NOEXCEPT_WHEN_RAW(T2) {\n\t\t\t\tget() = std::forward<T2>(t);\n\t\t\t\treturn *this;\n\t\t\t}\n\t\t\t#undef NOEXCEPT_WHEN_RAW\n\t\t\ttemplate <class Ar, class T2>\n\t\t\tfriend void serialize(Ar&, Buffer<T2>&);\n\t\t};\n\t\ttemplate <class T>\n\t\tstruct Buffer<T&> {\n\t\t\tT*\t_data;\n\n\t\t\tBuffer() = default;\n\t\t\tBuffer(T& t) noexcept: _data(&t) {}\n\t\t\tT* ptr() noexcept {\n\t\t\t\treturn _data;\n\t\t\t}\n\t\t\tconst T* ptr() const noexcept {\n\t\t\t\treturn _data;\n\t\t\t}\n\t\t\tT& get() noexcept {\n\t\t\t\treturn *ptr();\n\t\t\t}\n\t\t\tconst T& get() const noexcept {\n\t\t\t\treturn *ptr();\n\t\t\t}\n\t\t\tvoid ctor() noexcept {}\n\t\t\tvoid ctor(T& t) noexcept{\n\t\t\t\t_data = &t;\n\t\t\t}\n\t\t\tvoid dtor() noexcept {}\n\t\t\tBuffer& operator = (T& t) noexcept {\n\t\t\t\t_data = &t;\n\t\t\t\treturn *this;\n\t\t\t}\n\t\t\ttemplate <class Ar, class T2>\n\t\t\tfriend void serialize(Ar&, opt_tmp::Buffer<T2&>&);\n\t\t};\n\t\ttemplate <class T>\n\t\tstruct Buffer<T*> {\n\t\t\tT*\t_data;\n\n\t\t\tBuffer() = default;\n\t\t\tBuffer(T* t) noexcept: _data(t) {}\n\t\t\tT* ptr() noexcept {\n\t\t\t\treturn _data;\n\t\t\t}\n\t\t\tconst T* ptr() const noexcept {\n\t\t\t\treturn _data;\n\t\t\t}\n\t\t\tT*& get() noexcept {\n\t\t\t\treturn _data;\n\t\t\t}\n\t\t\tT* const& get() const noexcept {\n\t\t\t\treturn _data;\n\t\t\t}\n\t\t\tvoid ctor() noexcept {}\n\t\t\tvoid ctor(T* t) noexcept {\n\t\t\t\t_data = t;\n\t\t\t}\n\t\t\tvoid dtor() noexcept {}\n\t\t\tBuffer& operator = (T* t) noexcept {\n\t\t\t\t_data = t;\n\t\t\t\treturn *this;\n\t\t\t}\n\t\t\ttemplate <class Ar, class T2>\n\t\t\tfriend void serialize(Ar&, opt_tmp::Buffer<T2*>&);\n\t\t};\n\t}\n\n\ttemplate <class T>\n\tclass Optional {\n\t\tprivate:\n\t\t\tusing value_t = T;\n\t\t\tconstexpr static bool Is_RP = IsRP<T>{};\n\t\t\tusing Buffer = opt_tmp::Buffer<T>;\n\t\t\tBuffer\t_buffer;\n\t\t\tbool\t_bInit;\n\n\t\t\tvoid _force_release() noexcept {\n\t\t\t\tD_Assert0(_bInit);\n\t\t\t\t_buffer.dtor();\n\t\t\t\t_bInit = false;\n\t\t\t}\n\t\t\tvoid _release() noexcept {\n\t\t\t\tif(_bInit)\n\t\t\t\t\t_force_release();\n\t\t\t}\n\t\t\tconstexpr bool isRvalue() && noexcept {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\tconstexpr bool isRvalue() const& noexcept {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\ttemplate <class T2>\n\t\t\tbool _construct(std::true_type, T2&& t) {\n\t\t\t\t_buffer.ctor(std::forward<T2>(t));\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\ttemplate <class T2>\n\t\t\tbool _construct(std::false_type, T2&&) {\n\t\t\t\t_buffer.ctor();\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\tpublic:\n\t\t\tconst static struct _AsInitialized{} AsInitialized;\n\t\t\t\/\/! コンストラクタは呼ばないが初期化された物として扱う\n\t\t\t\/*! ユーザーが自分でコンストラクタを呼ばないとエラーになる *\/\n\t\t\tOptional(_AsInitialized) noexcept:\n\t\t\t\t_bInit(true)\n\t\t\t{}\n\n\t\t\tOptional(const Optional& opt):\n\t\t\t\t_bInit(opt._bInit)\n\t\t\t{\n\t\t\t\tif(_bInit) {\n\t\t\t\t\t_buffer.ctor(opt._buffer.get());\n\t\t\t\t}\n\t\t\t}\n\t\t\tOptional(Optional&& opt) noexcept:\n\t\t\t\t_bInit(opt._bInit)\n\t\t\t{\n\t\t\t\tif(_bInit) {\n\t\t\t\t\t_buffer.ctor(std::move(opt).get());\n\t\t\t\t\topt._bInit = false;\n\t\t\t\t}\n\t\t\t}\n\t\t\ttemplate <class T2, ENABLE_IF(!(is_optional<std::decay_t<T2>>{}))>\n\t\t\tOptional(T2&& v) noexcept(noexcept(Buffer(std::forward<T2>(v)))):\n\t\t\t\t_buffer(std::forward<T2>(v)),\n\t\t\t\t_bInit(true)\n\t\t\t{}\n\t\t\ttemplate <class T2, ENABLE_IF((is_optional<std::decay_t<T2>>{}))>\n\t\t\tOptional(T2&& v) noexcept(noexcept(std::declval<Buffer>().ctor(std::forward<T2>(v).get()))):\n\t\t\t\t_bInit(v._bInit)\n\t\t\t{\n\t\t\t\tif(_bInit) {\n\t\t\t\t\tconst bool bR = std::forward<T2>(v).isRvalue();\n\t\t\t\t\t_buffer.ctor(std::forward<T2>(v).get());\n\t\t\t\t\tif(bR)\n\t\t\t\t\t\tv._bInit = false;\n\t\t\t\t}\n\t\t\t}\n\t\t\t\/\/! デフォルト初期化: 中身は無効 \n\t\t\tOptional() noexcept:\n\t\t\t\t_bInit(false)\n\t\t\t{}\n\t\t\t\/\/! none_tを渡して初期化するとデフォルトと同じ挙動\n\t\t\tOptional(none_t) noexcept:\n\t\t\t\tOptional()\n\t\t\t{}\n\t\t\t~Optional() {\n\t\t\t\t_release();\n\t\t\t}\n\t\t\tdecltype(auto) get() & noexcept {\n\t\t\t\treturn _buffer.get();\n\t\t\t}\n\t\t\tdecltype(auto) get() const& noexcept {\n\t\t\t\treturn _buffer.get();\n\t\t\t}\n\t\t\tdecltype(auto) get() && noexcept {\n\t\t\t\treturn std::move(_buffer.get());\n\t\t\t}\n\t\t\tdecltype(auto) operator * () & noexcept {\n\t\t\t\treturn get();\n\t\t\t}\n\t\t\tdecltype(auto) operator * () const& noexcept {\n\t\t\t\treturn get();\n\t\t\t}\n\t\t\tdecltype(auto) operator * () && noexcept {\n\t\t\t\treturn std::move(get());\n\t\t\t}\n\t\t\texplicit operator bool () const noexcept {\n\t\t\t\treturn _bInit;\n\t\t\t}\n\t\t\tdecltype(auto) operator -> () noexcept {\n\t\t\t\treturn _buffer.ptr();\n\t\t\t}\n\t\t\tdecltype(auto) operator -> () const noexcept {\n\t\t\t\treturn _buffer.ptr();\n\t\t\t}\n\t\t\tbool operator == (const Optional& t) const noexcept {\n\t\t\t\tconst bool b = _bInit;\n\t\t\t\tif(b == t._bInit) {\n\t\t\t\t\tif(b)\n\t\t\t\t\t\treturn get() == t.get();\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tbool operator != (const Optional& t) const noexcept {\n\t\t\t\treturn !(this->operator == (t));\n\t\t\t}\n\t\t\tOptional& operator = (none_t) noexcept {\n\t\t\t\t_release();\n\t\t\t\treturn *this;\n\t\t\t}\n\t\t\ttemplate <\n\t\t\t\tclass T2,\n\t\t\t\tENABLE_IF(!(is_optional<std::decay_t<T2>>{}))\n\t\t\t>\n\t\t\tOptional& operator = (T2&& t) {\n\t\t\t\tif(!_bInit) {\n\t\t\t\t\t_bInit = true;\n\t\t\t\t\tusing CanConstruct = std::is_constructible<value_t, decltype(std::forward<T2>(t))>;\n\t\t\t\t\tif(_construct(CanConstruct{}, std::forward<T2>(t)))\n\t\t\t\t\t\treturn *this;\n\t\t\t\t}\n\t\t\t\t_buffer = std::forward<T2>(t);\n\t\t\t\treturn *this;\n\t\t\t}\n\t\t\ttemplate <class... Ts>\n\t\t\tOptional& operator = (ArgHolder<Ts...>&& ah) {\n\t\t\t\tif(_bInit)\n\t\t\t\t\t_release();\n\t\t\t\tconst auto fn = [&buff = _buffer](auto&&... ts) {\n\t\t\t\t\tbuff.ctor(std::forward<decltype(ts)>(ts)...);\n\t\t\t\t};\n\t\t\t\tah.inorder(fn);\n\t\t\t\t_bInit = true;\n\t\t\t\treturn *this;\n\t\t\t}\n\t\t\ttemplate <class T2, ENABLE_IF((is_optional<std::decay_t<T2>>{}))>\n\t\t\tOptional& operator = (T2&& t) noexcept(Is_RP) {\n\t\t\t\tif(!t)\n\t\t\t\t\t_release();\n\t\t\t\telse {\n\t\t\t\t\t_bInit = true;\n\t\t\t\t\t_buffer = std::forward<T2>(t).get();\n\t\t\t\t}\n\t\t\t\treturn *this;\n\t\t\t}\n\t\t\ttemplate <class Ar, class T2>\n\t\t\tfriend void load(Ar&, Optional<T2>&);\n\t\t\ttemplate <class Ar, class T2>\n\t\t\tfriend void save(Ar&, const Optional<T2>&);\n\t};\n\ttemplate <class T>\n\tconst typename Optional<T>::_AsInitialized Optional<T>::AsInitialized{};\n}\n<commit_msg>Optional: noneを持っている時にassignすると内部値のコンストラクタが呼ばれない不具合を修正<commit_after>#pragma once\n#include \"detect_type.hpp\"\n#include \"lubee\/meta\/enable_if.hpp\"\n#include \"lubee\/none.hpp\"\n#include \"argholder.hpp\"\n#include <utility>\n#include \"none.hpp\"\n\nnamespace spi {\n\ttemplate <class... Ts>\n\tauto construct(Ts&&... ts) {\n\t\treturn ArgHolder<decltype(ts)...>(std::forward<Ts>(ts)...);\n\t}\n\ttemplate <class P>\n\tusing IsRP = std::integral_constant<bool, std::is_reference<P>{} || std::is_pointer<P>{}>;\n\tnamespace opt_tmp {\n\t\ttemplate <class T>\n\t\tstruct alignas(alignof(T)) Buffer {\n\t\t\tuint8_t\t\t_data[sizeof(T)];\n\n\t\t\tBuffer() = default;\n\t\t\ttemplate <class T2>\n\t\t\tBuffer(T2&& t) {\n\t\t\t\tnew(ptr()) T(std::forward<T2>(t));\n\t\t\t}\n\n\t\t\tT* ptr() noexcept {\n\t\t\t\t\/\/ Debug時は中身が有効かチェック\n\t\t\t\t#ifdef DEBUG\n\t\t\t\t#endif\n\t\t\t\treturn reinterpret_cast<T*>(_data);\n\t\t\t}\n\t\t\tconst T* ptr() const noexcept {\n\t\t\t\t\/\/ Debug時は中身が有効かチェック\n\t\t\t\t#ifdef DEBUG\n\t\t\t\t#endif\n\t\t\t\treturn reinterpret_cast<const T*>(_data);\n\t\t\t}\n\t\t\tT& get() noexcept {\n\t\t\t\treturn *ptr();\n\t\t\t}\n\t\t\tconst T& get() const noexcept {\n\t\t\t\treturn *ptr();\n\t\t\t}\n\t\t\ttemplate <class... Ts>\n\t\t\tvoid ctor(Ts&&... ts) noexcept(noexcept(new T(std::forward<Ts>(ts)...))) {\n\t\t\t\tnew(ptr()) T(std::forward<Ts>(ts)...);\n\t\t\t}\n\t\t\tvoid dtor() noexcept {\n\t\t\t\tptr()->~T();\n\t\t\t}\n\t\t\t#define NOEXCEPT_WHEN_RAW(t) noexcept(noexcept(IsRP<t>{}))\n\t\t\ttemplate <class T2>\n\t\t\tBuffer& operator = (T2&& t) NOEXCEPT_WHEN_RAW(T2) {\n\t\t\t\tget() = std::forward<T2>(t);\n\t\t\t\treturn *this;\n\t\t\t}\n\t\t\t#undef NOEXCEPT_WHEN_RAW\n\t\t\ttemplate <class Ar, class T2>\n\t\t\tfriend void serialize(Ar&, Buffer<T2>&);\n\t\t};\n\t\ttemplate <class T>\n\t\tstruct Buffer<T&> {\n\t\t\tT*\t_data;\n\n\t\t\tBuffer() = default;\n\t\t\tBuffer(T& t) noexcept: _data(&t) {}\n\t\t\tT* ptr() noexcept {\n\t\t\t\treturn _data;\n\t\t\t}\n\t\t\tconst T* ptr() const noexcept {\n\t\t\t\treturn _data;\n\t\t\t}\n\t\t\tT& get() noexcept {\n\t\t\t\treturn *ptr();\n\t\t\t}\n\t\t\tconst T& get() const noexcept {\n\t\t\t\treturn *ptr();\n\t\t\t}\n\t\t\tvoid ctor() noexcept {}\n\t\t\tvoid ctor(T& t) noexcept{\n\t\t\t\t_data = &t;\n\t\t\t}\n\t\t\tvoid dtor() noexcept {}\n\t\t\tBuffer& operator = (T& t) noexcept {\n\t\t\t\t_data = &t;\n\t\t\t\treturn *this;\n\t\t\t}\n\t\t\ttemplate <class Ar, class T2>\n\t\t\tfriend void serialize(Ar&, opt_tmp::Buffer<T2&>&);\n\t\t};\n\t\ttemplate <class T>\n\t\tstruct Buffer<T*> {\n\t\t\tT*\t_data;\n\n\t\t\tBuffer() = default;\n\t\t\tBuffer(T* t) noexcept: _data(t) {}\n\t\t\tT* ptr() noexcept {\n\t\t\t\treturn _data;\n\t\t\t}\n\t\t\tconst T* ptr() const noexcept {\n\t\t\t\treturn _data;\n\t\t\t}\n\t\t\tT*& get() noexcept {\n\t\t\t\treturn _data;\n\t\t\t}\n\t\t\tT* const& get() const noexcept {\n\t\t\t\treturn _data;\n\t\t\t}\n\t\t\tvoid ctor() noexcept {}\n\t\t\tvoid ctor(T* t) noexcept {\n\t\t\t\t_data = t;\n\t\t\t}\n\t\t\tvoid dtor() noexcept {}\n\t\t\tBuffer& operator = (T* t) noexcept {\n\t\t\t\t_data = t;\n\t\t\t\treturn *this;\n\t\t\t}\n\t\t\ttemplate <class Ar, class T2>\n\t\t\tfriend void serialize(Ar&, opt_tmp::Buffer<T2*>&);\n\t\t};\n\t}\n\n\ttemplate <class T>\n\tclass Optional {\n\t\tprivate:\n\t\t\tusing value_t = T;\n\t\t\tconstexpr static bool Is_RP = IsRP<T>{};\n\t\t\tusing Buffer = opt_tmp::Buffer<T>;\n\t\t\tBuffer\t_buffer;\n\t\t\tbool\t_bInit;\n\n\t\t\tvoid _force_release() noexcept {\n\t\t\t\tD_Assert0(_bInit);\n\t\t\t\t_buffer.dtor();\n\t\t\t\t_bInit = false;\n\t\t\t}\n\t\t\tvoid _release() noexcept {\n\t\t\t\tif(_bInit)\n\t\t\t\t\t_force_release();\n\t\t\t}\n\t\t\ttemplate <class T2>\n\t\t\tbool _construct(std::true_type, T2&& t) {\n\t\t\t\t_buffer.ctor(std::forward<T2>(t));\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\ttemplate <class T2>\n\t\t\tbool _construct(std::false_type, T2&&) {\n\t\t\t\t_buffer.ctor();\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tvoid _invalidate_if_rvalue() const& noexcept {}\n\t\t\tvoid _invalidate_if_rvalue() && noexcept {\n\t\t\t\t_bInit = false;\n\t\t\t}\n\n\t\tpublic:\n\t\t\tconst static struct _AsInitialized{} AsInitialized;\n\t\t\t\/\/! コンストラクタは呼ばないが初期化された物として扱う\n\t\t\t\/*! ユーザーが自分でコンストラクタを呼ばないとエラーになる *\/\n\t\t\tOptional(_AsInitialized) noexcept:\n\t\t\t\t_bInit(true)\n\t\t\t{}\n\n\t\t\tOptional(const Optional& opt):\n\t\t\t\t_bInit(opt._bInit)\n\t\t\t{\n\t\t\t\tif(_bInit) {\n\t\t\t\t\t_buffer.ctor(opt._buffer.get());\n\t\t\t\t}\n\t\t\t}\n\t\t\tOptional(Optional&& opt) noexcept:\n\t\t\t\t_bInit(opt._bInit)\n\t\t\t{\n\t\t\t\tif(_bInit) {\n\t\t\t\t\t_buffer.ctor(std::move(opt).get());\n\t\t\t\t\topt._bInit = false;\n\t\t\t\t}\n\t\t\t}\n\t\t\ttemplate <class T2, ENABLE_IF(!(is_optional<std::decay_t<T2>>{}))>\n\t\t\tOptional(T2&& v) noexcept(noexcept(Buffer(std::forward<T2>(v)))):\n\t\t\t\t_buffer(std::forward<T2>(v)),\n\t\t\t\t_bInit(true)\n\t\t\t{}\n\t\t\ttemplate <class T2, ENABLE_IF((is_optional<std::decay_t<T2>>{}))>\n\t\t\tOptional(T2&& v) noexcept(noexcept(std::declval<Buffer>().ctor(std::forward<T2>(v).get()))):\n\t\t\t\t_bInit(v._bInit)\n\t\t\t{\n\t\t\t\tif(_bInit) {\n\t\t\t\t\t_buffer.ctor(std::forward<T2>(v).get());\n\t\t\t\t\tv._invalidate_if_rvalue();\n\t\t\t\t}\n\t\t\t}\n\t\t\t\/\/! デフォルト初期化: 中身は無効 \n\t\t\tOptional() noexcept:\n\t\t\t\t_bInit(false)\n\t\t\t{}\n\t\t\t\/\/! none_tを渡して初期化するとデフォルトと同じ挙動\n\t\t\tOptional(none_t) noexcept:\n\t\t\t\tOptional()\n\t\t\t{}\n\t\t\t~Optional() {\n\t\t\t\t_release();\n\t\t\t}\n\t\t\tdecltype(auto) get() & noexcept {\n\t\t\t\treturn _buffer.get();\n\t\t\t}\n\t\t\tdecltype(auto) get() const& noexcept {\n\t\t\t\treturn _buffer.get();\n\t\t\t}\n\t\t\tdecltype(auto) get() && noexcept {\n\t\t\t\treturn std::move(_buffer.get());\n\t\t\t}\n\t\t\tdecltype(auto) operator * () & noexcept {\n\t\t\t\treturn get();\n\t\t\t}\n\t\t\tdecltype(auto) operator * () const& noexcept {\n\t\t\t\treturn get();\n\t\t\t}\n\t\t\tdecltype(auto) operator * () && noexcept {\n\t\t\t\treturn std::move(get());\n\t\t\t}\n\t\t\texplicit operator bool () const noexcept {\n\t\t\t\treturn _bInit;\n\t\t\t}\n\t\t\tdecltype(auto) operator -> () noexcept {\n\t\t\t\treturn _buffer.ptr();\n\t\t\t}\n\t\t\tdecltype(auto) operator -> () const noexcept {\n\t\t\t\treturn _buffer.ptr();\n\t\t\t}\n\t\t\tbool operator == (const Optional& t) const noexcept {\n\t\t\t\tconst bool b = _bInit;\n\t\t\t\tif(b == t._bInit) {\n\t\t\t\t\tif(b)\n\t\t\t\t\t\treturn get() == t.get();\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tbool operator != (const Optional& t) const noexcept {\n\t\t\t\treturn !(this->operator == (t));\n\t\t\t}\n\t\t\tOptional& operator = (none_t) noexcept {\n\t\t\t\t_release();\n\t\t\t\treturn *this;\n\t\t\t}\n\t\t\ttemplate <\n\t\t\t\tclass T2,\n\t\t\t\tENABLE_IF(!(is_optional<std::decay_t<T2>>{}))\n\t\t\t>\n\t\t\tOptional& operator = (T2&& t) {\n\t\t\t\tif(!_bInit) {\n\t\t\t\t\t_bInit = true;\n\t\t\t\t\tusing CanConstruct = std::is_constructible<value_t, decltype(std::forward<T2>(t))>;\n\t\t\t\t\tif(_construct(CanConstruct{}, std::forward<T2>(t)))\n\t\t\t\t\t\treturn *this;\n\t\t\t\t}\n\t\t\t\t_buffer = std::forward<T2>(t);\n\t\t\t\treturn *this;\n\t\t\t}\n\t\t\ttemplate <class... Ts>\n\t\t\tOptional& operator = (ArgHolder<Ts...>&& ah) {\n\t\t\t\tif(_bInit)\n\t\t\t\t\t_release();\n\t\t\t\tconst auto fn = [&buff = _buffer](auto&&... ts) {\n\t\t\t\t\tbuff.ctor(std::forward<decltype(ts)>(ts)...);\n\t\t\t\t};\n\t\t\t\tah.inorder(fn);\n\t\t\t\t_bInit = true;\n\t\t\t\treturn *this;\n\t\t\t}\n\t\t\ttemplate <class T2, ENABLE_IF((is_optional<std::decay_t<T2>>{}))>\n\t\t\tOptional& _assign_operator(T2&& t) noexcept(Is_RP) {\n\t\t\t\tif(!t)\n\t\t\t\t\t_release();\n\t\t\t\telse {\n\t\t\t\t\tif(!_bInit) {\n\t\t\t\t\t\t_bInit = true;\n\t\t\t\t\t\t_buffer.ctor();\n\t\t\t\t\t}\n\t\t\t\t\t_buffer = std::forward<T2>(t).get();\n\t\t\t\t}\n\t\t\t\treturn *this;\n\t\t\t}\n\t\t\ttemplate <class T2, ENABLE_IF((is_optional<std::decay_t<T2>>{}))>\n\t\t\tOptional& operator = (T2&& t) noexcept(Is_RP) {\n\t\t\t\treturn _assign_operator(std::forward<T2>(t));\n\t\t\t}\n\t\t\tOptional& operator = (const Optional& opt) {\n\t\t\t\treturn _assign_operator(opt);\n\t\t\t}\n\t\t\tOptional& operator = (Optional&& opt) noexcept {\n\t\t\t\treturn _assign_operator(std::move(opt));\n\t\t\t}\n\t\t\ttemplate <class Ar, class T2>\n\t\t\tfriend void load(Ar&, Optional<T2>&);\n\t\t\ttemplate <class Ar, class T2>\n\t\t\tfriend void save(Ar&, const Optional<T2>&);\n\t};\n\ttemplate <class T>\n\tconst typename Optional<T>::_AsInitialized Optional<T>::AsInitialized{};\n}\n<|endoftext|>"} {"text":"<commit_before><commit_msg>added bounding frame<commit_after><|endoftext|>"} {"text":"<commit_before>\/\/ This file is a part of the IncludeOS unikernel - www.includeos.org\n\/\/\n\/\/ Copyright 2015-2016 Oslo and Akershus University College of Applied Sciences\n\/\/ and Alfred Bratterud\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#pragma once\n#ifndef NET_TCP_WRITE_BUFFER_HPP\n#define NET_TCP_WRITE_BUFFER_HPP\n\n#include \"common.hpp\"\n\nnamespace net {\nnamespace tcp {\n\/*\n Wrapper around a buffer that contains data to be written.\n*\/\nstruct WriteBuffer {\n buffer_t buffer;\n size_t remaining;\n size_t offset;\n size_t acknowledged;\n bool push;\n\n WriteBuffer(buffer_t buf, size_t length, bool PSH, size_t offs = 0)\n : buffer(buf), remaining(length-offs), offset(offs), acknowledged(0), push(PSH) {}\n\n size_t length() const { return remaining + offset; }\n\n bool done() const { return acknowledged == length(); }\n\n uint8_t* begin() const { return buffer.get(); }\n\n uint8_t* pos() const { return buffer.get() + offset; }\n\n uint8_t* end() const { return buffer.get() + length(); }\n\n bool advance(size_t length) {\n assert(length <= remaining);\n offset += length;\n remaining -= length;\n return length > 0;\n }\n\n size_t acknowledge(size_t bytes) {\n auto acked = std::min(bytes, length()-acknowledged);\n acknowledged += acked;\n return acked;\n }\n\n operator buffer_t() const noexcept\n { return buffer; }\n\n bool operator==(const WriteBuffer& wb) const\n { return buffer == wb.buffer && length() == wb.length(); }\n\n}; \/\/ < struct WriteBuffer\n\n} \/\/ < namespace net\n} \/\/ < namespace tcp\n\n#endif \/\/ < NET_TCP_WRITE_BUFFER_HPP\n\n<commit_msg>tcp: changed assert to Expects for better testing<commit_after>\/\/ This file is a part of the IncludeOS unikernel - www.includeos.org\n\/\/\n\/\/ Copyright 2015-2016 Oslo and Akershus University College of Applied Sciences\n\/\/ and Alfred Bratterud\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#pragma once\n#ifndef NET_TCP_WRITE_BUFFER_HPP\n#define NET_TCP_WRITE_BUFFER_HPP\n\n#include \"common.hpp\"\n#include <common>\n\nnamespace net {\nnamespace tcp {\n\/*\n Wrapper around a buffer that contains data to be written.\n*\/\nstruct WriteBuffer {\n buffer_t buffer;\n size_t remaining;\n size_t offset;\n size_t acknowledged;\n bool push;\n\n WriteBuffer(buffer_t buf, size_t length, bool PSH, size_t offs = 0)\n : buffer(buf), remaining(length-offs), offset(offs), acknowledged(0), push(PSH) {}\n\n size_t length() const { return remaining + offset; }\n\n bool done() const { return acknowledged == length(); }\n\n uint8_t* begin() const { return buffer.get(); }\n\n uint8_t* pos() const { return buffer.get() + offset; }\n\n uint8_t* end() const { return buffer.get() + length(); }\n\n bool advance(size_t length) {\n Expects(length <= remaining);\n offset += length;\n remaining -= length;\n return length > 0;\n }\n\n size_t acknowledge(size_t bytes) {\n auto acked = std::min(bytes, length()-acknowledged);\n acknowledged += acked;\n return acked;\n }\n\n operator buffer_t() const noexcept\n { return buffer; }\n\n bool operator==(const WriteBuffer& wb) const\n { return buffer == wb.buffer && length() == wb.length(); }\n\n}; \/\/ < struct WriteBuffer\n\n} \/\/ < namespace net\n} \/\/ < namespace tcp\n\n#endif \/\/ < NET_TCP_WRITE_BUFFER_HPP\n<|endoftext|>"} {"text":"<commit_before>class Solution {\n public:\n int numDistinct(string S, string T) {\n if(T.size() == 0) return 1;\n if(S.size() < T.size()) return 0;\n int count = 0;\n for(int i = 0; i != S.size(); ++i){\n if(T[0] == S[i]){\n count += numDistinct(S.substr(i+1), T.substr(1));\n }\n }\n return count;\n }\n};\n<commit_msg>add a DP solution, accepted<commit_after>class Solution {\n public:\n int numDistinct(string S, string T) {\n int *matrix = new int[T.size()+1];\n memset((void*)matrix, 0, sizeof(int)*(T.size()+1));\n matrix[0] = 1;\n int count = 0;\n for(int i = 1; i != S.size()+1; ++i){\n for(int j = T.size(); j >= 1; --j){\n if(S[i-1] == T[j-1]){\n matrix[j] += matrix[j-1];\n }\n }\n }\n count = matrix[T.size()];\n delete []matrix;\n return count;\n }\n};\n<|endoftext|>"} {"text":"<commit_before>\/*\r\n * about_dialog.cpp\r\n * PHD Guiding\r\n *\r\n * Created by Sylvain Girard.\r\n * Copyright (c) 2013 Sylvain Girard.\r\n * All rights reserved.\r\n *\r\n * This source code is distributed under the following \"BSD\" license\r\n * Redistribution and use in source and binary forms, with or without\r\n * modification, are permitted provided that the following conditions are met:\r\n * Redistributions of source code must retain the above copyright notice,\r\n * this list of conditions and the following disclaimer.\r\n * Redistributions in binary form must reproduce the above copyright notice,\r\n * this list of conditions and the following disclaimer in the\r\n * documentation and\/or other materials provided with the distribution.\r\n * Neither the name of Craig Stark, Stark Labs nor the names of its\r\n * contributors may be used to endorse or promote products derived from\r\n * this software without specific prior written permission.\r\n *\r\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\r\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\r\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\r\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\r\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\r\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\r\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\r\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\r\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\r\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\r\n * POSSIBILITY OF SUCH DAMAGE.\r\n *\r\n *\/\r\n\r\n#include \"phd.h\"\r\n#include \"about_dialog.h\"\r\n#include <wx\/fs_mem.h>\r\n#include <wx\/html\/htmlwin.h>\r\n\r\nBEGIN_EVENT_TABLE(AboutDialog, wxDialog)\r\n EVT_HTML_LINK_CLICKED(ABOUT_LINK,AboutDialog::OnLink)\r\nEND_EVENT_TABLE()\r\n\r\nAboutDialog::AboutDialog(void) :\r\nwxDialog(pFrame, wxID_ANY, _T(\"About \") APPNAME, wxDefaultPosition, wxDefaultSize, wxCAPTION | wxCLOSE_BOX)\r\n{\r\n #include \"icons\/phd.xpm\" \/\/ defines prog_icon[]\r\n\r\n SetBackgroundColour(*wxWHITE);\r\n\r\n wxBoxSizer *pSizer = new wxBoxSizer(wxHORIZONTAL);\r\n wxBitmap bmp(prog_icon);\r\n wxStaticBitmap *pImage = new wxStaticBitmap(this, wxID_ANY, bmp);\r\n\r\n wxFileSystem::AddHandler(new wxMemoryFSHandler);\r\n wxMemoryFSHandler::AddFile(\"about.html\", wxString::Format(\r\n \"<html><body>\"\r\n \"<h2>%s %s<\/h2>\"\r\n \"<a href=\\\"https:\/\/code.google.com\/p\/open-phd-guiding\/\\\">Open PHD Guiding<\/a><br>\"\r\n \"<a href=\\\"http:\/\/www.stark-labs.com\/phdguiding.html\\\">www.stark-labs.com<\/a><br><br>\"\r\n \"Credits:<br>\"\r\n \"    Craig Stark<br>\"\r\n \"    Bret McKee<br>\"\r\n \"    Bernhard Reutner-Fischer<br>\"\r\n \"    Stefan Elste<br>\"\r\n \"    Geoffrey Hausheer<br>\"\r\n \"    Jared Wellman<br>\"\r\n \"    John Wainwright<br>\"\r\n \"    Sylvain Girard<br>\"\r\n \"    Andy Galasso<br>\"\r\n \"    Bruce Waddington<br>\"\r\n \"<br>\"\r\n \"Copyright 2006-2013 Craig Stark<br>\"\r\n \"Copyright 2009 Geoffrey Hausheer<br>\"\r\n \"Copyright 2012-2013 Bret McKee<br>\"\r\n \"Copyright 2013 Sylvain Girard<br>\"\r\n \"Copyright 2013 Andy Galasso<br>\"\r\n \"Copyright 2013 Bruce Waddington<br>\"\r\n \"<\/body><\/html>\", APPNAME, FULLVER));\r\n wxHtmlWindow *pHtml;\r\n pHtml = new wxHtmlWindow(this, ABOUT_LINK, wxDefaultPosition, wxSize(380, 400), wxHW_SCROLLBAR_AUTO);\r\n pHtml->SetBorders(0);\r\n pHtml->LoadPage(\"memory:about.html\");\r\n pHtml->SetSize(pHtml->GetInternalRepresentation()->GetWidth(), pHtml->GetInternalRepresentation()->GetHeight());\r\n\r\n pSizer->Add(pImage, wxSizerFlags(0).Border(wxALL, 10));\r\n pSizer->Add(pHtml, wxSizerFlags(0).Border(wxALL, 10));\r\n\r\n wxBoxSizer *pTopLevelSizer = new wxBoxSizer(wxVERTICAL);\r\n pTopLevelSizer->Add(pSizer, wxSizerFlags(0).Expand());\r\n pTopLevelSizer->Add(CreateButtonSizer(wxOK), wxSizerFlags(0).Expand().Border(wxALL, 10));\r\n SetSizerAndFit(pTopLevelSizer);\r\n}\r\n\r\nAboutDialog::~AboutDialog(void)\r\n{\r\n wxMemoryFSHandler::RemoveFile(\"about.html\");\r\n}\r\n\r\nvoid AboutDialog::OnLink(wxHtmlLinkEvent & event)\r\n{\r\n wxLaunchDefaultBrowser(event.GetLinkInfo().GetHref());\r\n}\r\n<commit_msg>Add Max Chen to about dialog<commit_after>\/*\r\n * about_dialog.cpp\r\n * PHD Guiding\r\n *\r\n * Created by Sylvain Girard.\r\n * Copyright (c) 2013 Sylvain Girard.\r\n * All rights reserved.\r\n *\r\n * This source code is distributed under the following \"BSD\" license\r\n * Redistribution and use in source and binary forms, with or without\r\n * modification, are permitted provided that the following conditions are met:\r\n * Redistributions of source code must retain the above copyright notice,\r\n * this list of conditions and the following disclaimer.\r\n * Redistributions in binary form must reproduce the above copyright notice,\r\n * this list of conditions and the following disclaimer in the\r\n * documentation and\/or other materials provided with the distribution.\r\n * Neither the name of Craig Stark, Stark Labs nor the names of its\r\n * contributors may be used to endorse or promote products derived from\r\n * this software without specific prior written permission.\r\n *\r\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\r\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\r\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\r\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\r\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\r\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\r\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\r\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\r\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\r\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\r\n * POSSIBILITY OF SUCH DAMAGE.\r\n *\r\n *\/\r\n\r\n#include \"phd.h\"\r\n#include \"about_dialog.h\"\r\n#include <wx\/fs_mem.h>\r\n#include <wx\/html\/htmlwin.h>\r\n\r\nBEGIN_EVENT_TABLE(AboutDialog, wxDialog)\r\n EVT_HTML_LINK_CLICKED(ABOUT_LINK,AboutDialog::OnLink)\r\nEND_EVENT_TABLE()\r\n\r\nAboutDialog::AboutDialog(void) :\r\nwxDialog(pFrame, wxID_ANY, _T(\"About \") APPNAME, wxDefaultPosition, wxDefaultSize, wxCAPTION | wxCLOSE_BOX)\r\n{\r\n #include \"icons\/phd.xpm\" \/\/ defines prog_icon[]\r\n\r\n SetBackgroundColour(*wxWHITE);\r\n\r\n wxBoxSizer *pSizer = new wxBoxSizer(wxHORIZONTAL);\r\n wxBitmap bmp(prog_icon);\r\n wxStaticBitmap *pImage = new wxStaticBitmap(this, wxID_ANY, bmp);\r\n\r\n wxFileSystem::AddHandler(new wxMemoryFSHandler);\r\n wxMemoryFSHandler::AddFile(\"about.html\", wxString::Format(\r\n \"<html><body>\"\r\n \"<h2>%s %s<\/h2>\"\r\n \"<a href=\\\"https:\/\/code.google.com\/p\/open-phd-guiding\/\\\">Open PHD Guiding<\/a><br>\"\r\n \"<a href=\\\"http:\/\/www.stark-labs.com\/phdguiding.html\\\">www.stark-labs.com<\/a><br><br>\"\r\n \"Credits:<br>\"\r\n \"    Craig Stark<br>\"\r\n \"    Bret McKee<br>\"\r\n \"    Bernhard Reutner-Fischer<br>\"\r\n \"    Stefan Elste<br>\"\r\n \"    Geoffrey Hausheer<br>\"\r\n \"    Jared Wellman<br>\"\r\n \"    John Wainwright<br>\"\r\n \"    Sylvain Girard<br>\"\r\n \"    Andy Galasso<br>\"\r\n \"    Bruce Waddington<br>\"\r\n \"    Max Chen<br>\"\r\n \"<br>\"\r\n \"Copyright 2006-2013 Craig Stark<br>\"\r\n \"Copyright 2009 Geoffrey Hausheer<br>\"\r\n \"Copyright 2012-2013 Bret McKee<br>\"\r\n \"Copyright 2013 Sylvain Girard<br>\"\r\n \"Copyright 2013 Andy Galasso<br>\"\r\n \"Copyright 2013 Bruce Waddington<br>\"\r\n \"<\/body><\/html>\", APPNAME, FULLVER));\r\n wxHtmlWindow *pHtml;\r\n pHtml = new wxHtmlWindow(this, ABOUT_LINK, wxDefaultPosition, wxSize(380, 440), wxHW_SCROLLBAR_AUTO);\r\n pHtml->SetBorders(0);\r\n pHtml->LoadPage(\"memory:about.html\");\r\n pHtml->SetSize(pHtml->GetInternalRepresentation()->GetWidth(), pHtml->GetInternalRepresentation()->GetHeight());\r\n\r\n pSizer->Add(pImage, wxSizerFlags(0).Border(wxALL, 10));\r\n pSizer->Add(pHtml, wxSizerFlags(0).Border(wxALL, 10));\r\n\r\n wxBoxSizer *pTopLevelSizer = new wxBoxSizer(wxVERTICAL);\r\n pTopLevelSizer->Add(pSizer, wxSizerFlags(0).Expand());\r\n pTopLevelSizer->Add(CreateButtonSizer(wxOK), wxSizerFlags(0).Expand().Border(wxALL, 10));\r\n SetSizerAndFit(pTopLevelSizer);\r\n}\r\n\r\nAboutDialog::~AboutDialog(void)\r\n{\r\n wxMemoryFSHandler::RemoveFile(\"about.html\");\r\n}\r\n\r\nvoid AboutDialog::OnLink(wxHtmlLinkEvent & event)\r\n{\r\n wxLaunchDefaultBrowser(event.GetLinkInfo().GetHref());\r\n}\r\n<|endoftext|>"} {"text":"<commit_before>\/\/===--- swift_indent_main.cpp - Swift code formatting tool ---------------===\/\/\n\/\/\n\/\/ This source file is part of the Swift.org open source project\n\/\/\n\/\/ Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors\n\/\/ Licensed under Apache License v2.0 with Runtime Library Exception\n\/\/\n\/\/ See https:\/\/swift.org\/LICENSE.txt for license information\n\/\/ See https:\/\/swift.org\/CONTRIBUTORS.txt for the list of Swift project authors\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ Extracts a Symbol Graph from a .swiftmodule file.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"swift\/AST\/DiagnosticsFrontend.h\"\n#include \"swift\/Basic\/LLVM.h\"\n#include \"swift\/Basic\/LLVMInitialize.h\"\n#include \"swift\/Basic\/Version.h\"\n#include \"swift\/Frontend\/Frontend.h\"\n#include \"swift\/Frontend\/PrintingDiagnosticConsumer.h\"\n#include \"swift\/Option\/Options.h\"\n#include \"swift\/SymbolGraphGen\/SymbolGraphGen.h\"\n#include \"llvm\/ADT\/ArrayRef.h\"\n#include \"llvm\/ADT\/SmallVector.h\"\n#include \"llvm\/Support\/raw_ostream.h\"\n\nusing namespace swift;\nusing namespace options;\n\nint swift_symbolgraph_extract_main(ArrayRef<const char *> Args,\n const char *Argv0, void *MainAddr) {\n INITIALIZE_LLVM();\n\n CompilerInvocation Invocation;\n CompilerInstance CI;\n PrintingDiagnosticConsumer DiagPrinter;\n auto &Diags = CI.getDiags();\n Diags.addConsumer(DiagPrinter);\n\n std::unique_ptr<llvm::opt::OptTable> Table = createSwiftOptTable();\n unsigned MissingIndex;\n unsigned MissingCount;\n llvm::opt::InputArgList ParsedArgs = Table->ParseArgs(\n Args, MissingIndex, MissingCount, SwiftSymbolGraphExtractOption);\n if (MissingCount) {\n Diags.diagnose(SourceLoc(), diag::error_missing_arg_value,\n ParsedArgs.getArgString(MissingIndex), MissingCount);\n return EXIT_FAILURE;\n }\n\n if (ParsedArgs.hasArg(OPT_UNKNOWN)) {\n for (const auto *A : ParsedArgs.filtered(OPT_UNKNOWN)) {\n Diags.diagnose(SourceLoc(), diag::error_unknown_arg,\n A->getAsString(ParsedArgs));\n }\n return EXIT_FAILURE;\n }\n\n auto MainExecutablePath = llvm::sys::fs::getMainExecutable(Argv0, MainAddr);\n\n if (ParsedArgs.getLastArg(OPT_help) || Args.empty()) {\n std::string ExecutableName =\n llvm::sys::path::stem(MainExecutablePath).str();\n Table->printHelp(llvm::outs(), ExecutableName.c_str(),\n \"Swift Symbol Graph Extractor\",\n SwiftSymbolGraphExtractOption, 0,\n \/*ShowAllAliases*\/ false);\n return EXIT_FAILURE;\n }\n\n std::string ModuleName;\n if (auto *A = ParsedArgs.getLastArg(OPT_module_name)) {\n ModuleName = A->getValue();\n } else {\n Diags.diagnose(SourceLoc(), diag::error_option_required, \"-module-name\");\n return EXIT_FAILURE;\n }\n\n llvm::Triple Target;\n if (auto *A = ParsedArgs.getLastArg(OPT_target)) {\n Target = llvm::Triple(A->getValue());\n } else {\n Diags.diagnose(SourceLoc(), diag::error_option_required, \"-target\");\n return EXIT_FAILURE;\n }\n\n std::string OutputDir;\n if (auto *A = ParsedArgs.getLastArg(OPT_output_dir)) {\n OutputDir = A->getValue();\n } else {\n Diags.diagnose(SourceLoc(), diag::error_option_required, \"-output-dir\");\n return EXIT_FAILURE;\n }\n\n if (!llvm::sys::fs::is_directory(OutputDir)) {\n Diags.diagnose(SourceLoc(), diag::error_nonexistent_output_dir, OutputDir);\n return EXIT_FAILURE;\n }\n\n Invocation.setMainExecutablePath(MainExecutablePath);\n Invocation.setModuleName(\"swift_symbolgraph_extract\");\n\n if (auto *A = ParsedArgs.getLastArg(OPT_resource_dir)) {\n Invocation.setRuntimeResourcePath(A->getValue());\n }\n\n std::string SDK = \"\";\n if (auto *A = ParsedArgs.getLastArg(OPT_sdk)) {\n SDK = A->getValue();\n }\n Invocation.setSDKPath(SDK);\n\n Invocation.setTargetTriple(Target);\n\n for (const auto *A : ParsedArgs.filtered(OPT_Xcc)) {\n Invocation.getClangImporterOptions().ExtraArgs.push_back(A->getValue());\n }\n\n std::vector<SearchPathOptions::FrameworkSearchPath> FrameworkSearchPaths;\n for (const auto *A : ParsedArgs.filtered(OPT_F)) {\n FrameworkSearchPaths.push_back({A->getValue(), \/*isSystem*\/ false});\n }\n for (const auto *A : ParsedArgs.filtered(OPT_Fsystem)) {\n FrameworkSearchPaths.push_back({A->getValue(), \/*isSystem*\/ true});\n }\n Invocation.setFrameworkSearchPaths(FrameworkSearchPaths);\n Invocation.getSearchPathOptions().LibrarySearchPaths =\n ParsedArgs.getAllArgValues(OPT_L);\n Invocation.setImportSearchPaths(ParsedArgs.getAllArgValues(OPT_I));\n\n Invocation.getLangOptions().EnableObjCInterop = Target.isOSDarwin();\n Invocation.getLangOptions().DebuggerSupport = true;\n\n Invocation.getFrontendOptions().EnableLibraryEvolution = true;\n\n std::string ModuleCachePath = \"\";\n if (auto *A = ParsedArgs.getLastArg(OPT_module_cache_path)) {\n ModuleCachePath = A->getValue();\n }\n Invocation.setClangModuleCachePath(ModuleCachePath);\n Invocation.getClangImporterOptions().ModuleCachePath = ModuleCachePath;\n Invocation.setDefaultPrebuiltCacheIfNecessary();\n\n if (auto *A = ParsedArgs.getLastArg(OPT_swift_version)) {\n using version::Version;\n auto SwiftVersion = A->getValue();\n bool isValid = false;\n if (auto Version =\n Version::parseVersionString(SwiftVersion, SourceLoc(), nullptr)) {\n if (auto Effective = Version.getValue().getEffectiveLanguageVersion()) {\n Invocation.getLangOptions().EffectiveLanguageVersion = *Effective;\n isValid = true;\n }\n }\n if (!isValid) {\n Diags.diagnose(SourceLoc(), diag::error_invalid_arg_value,\n \"-swift-version\", SwiftVersion);\n return EXIT_FAILURE;\n }\n }\n\n symbolgraphgen::SymbolGraphOptions Options{\n OutputDir,\n Target,\n ParsedArgs.hasArg(OPT_pretty_print),\n AccessLevel::Public,\n !ParsedArgs.hasArg(OPT_skip_synthesized_members),\n ParsedArgs.hasArg(OPT_v),\n ParsedArgs.hasArg(OPT_skip_inherited_docs),\n ParsedArgs.hasArg(OPT_include_spi_symbols),\n \/*IncludeClangDocs=*\/false,\n };\n\n if (auto *A = ParsedArgs.getLastArg(OPT_minimum_access_level)) {\n Options.MinimumAccessLevel =\n llvm::StringSwitch<AccessLevel>(A->getValue())\n .Case(\"open\", AccessLevel::Open)\n .Case(\"public\", AccessLevel::Public)\n .Case(\"internal\", AccessLevel::Internal)\n .Case(\"fileprivate\", AccessLevel::FilePrivate)\n .Case(\"private\", AccessLevel::Private)\n .Default(AccessLevel::Public);\n }\n\n std::string InstanceSetupError;\n if (CI.setup(Invocation, InstanceSetupError)) {\n llvm::outs() << InstanceSetupError << '\\n';\n return EXIT_FAILURE;\n }\n\n auto M = CI.getASTContext().getModuleByName(ModuleName);\n if (!M) {\n llvm::errs()\n << \"Couldn't load module '\" << ModuleName << '\\''\n << \" in the current SDK and search paths.\\n\";\n \n SmallVector<Identifier, 32> VisibleModuleNames;\n CI.getASTContext().getVisibleTopLevelModuleNames(VisibleModuleNames);\n\n if (VisibleModuleNames.empty()) {\n llvm::errs() << \"Could not find any modules.\\n\";\n } else {\n std::sort(VisibleModuleNames.begin(), VisibleModuleNames.end(),\n [](const Identifier &A, const Identifier &B) -> bool {\n return A.str() < B.str();\n });\n llvm::errs() << \"Current visible modules:\\n\";\n for (const auto &ModuleName : VisibleModuleNames) {\n llvm::errs() << ModuleName.str() << \"\\n\";\n }\n }\n return EXIT_FAILURE;\n }\n \n if (M->failedToLoad()) {\n llvm::errs() << \"Error: Failed to load the module '\" << ModuleName\n << \"'. Are you missing build dependencies or \"\n \"include\/framework directories?\\n\"\n << \"See the previous error messages for details. Aborting.\\n\";\n\n return EXIT_FAILURE;\n }\n\n const auto &MainFile = M->getMainFile(FileUnitKind::SerializedAST);\n \n if (Options.PrintMessages)\n llvm::errs() << \"Emitting symbol graph for module file: \" << MainFile.getModuleDefiningPath() << '\\n';\n \n int Success = symbolgraphgen::emitSymbolGraphForModule(M, Options);\n \n \/\/ Look for cross-import overlays that the given module imports.\n \n \/\/ Clear out the diagnostic printer before looking for cross-import overlay modules,\n \/\/ since some SDK modules can cause errors in the getModuleByName() call. The call\n \/\/ itself will properly return nullptr after this failure, so for our purposes we\n \/\/ don't need to print these errors.\n CI.removeDiagnosticConsumer(&DiagPrinter);\n \n SmallVector<ModuleDecl *, 8> Overlays;\n M->findDeclaredCrossImportOverlaysTransitive(Overlays);\n for (const auto *OM : Overlays) {\n auto CIM = CI.getASTContext().getModuleByName(OM->getNameStr());\n if (CIM) {\n const auto &CIMainFile = CIM->getMainFile(FileUnitKind::SerializedAST);\n \n if (Options.PrintMessages)\n llvm::errs() << \"Emitting symbol graph for cross-import overlay module file: \"\n << CIMainFile.getModuleDefiningPath() << '\\n';\n \n Success |= symbolgraphgen::emitSymbolGraphForModule(CIM, Options);\n }\n }\n\n return Success;\n}\n<commit_msg>allow swift-symbolgraph-extract to be called on non-swift modules (#42399)<commit_after>\/\/===--- swift_indent_main.cpp - Swift code formatting tool ---------------===\/\/\n\/\/\n\/\/ This source file is part of the Swift.org open source project\n\/\/\n\/\/ Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors\n\/\/ Licensed under Apache License v2.0 with Runtime Library Exception\n\/\/\n\/\/ See https:\/\/swift.org\/LICENSE.txt for license information\n\/\/ See https:\/\/swift.org\/CONTRIBUTORS.txt for the list of Swift project authors\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ Extracts a Symbol Graph from a .swiftmodule file.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"swift\/AST\/DiagnosticsFrontend.h\"\n#include \"swift\/Basic\/LLVM.h\"\n#include \"swift\/Basic\/LLVMInitialize.h\"\n#include \"swift\/Basic\/Version.h\"\n#include \"swift\/Frontend\/Frontend.h\"\n#include \"swift\/Frontend\/PrintingDiagnosticConsumer.h\"\n#include \"swift\/Option\/Options.h\"\n#include \"swift\/SymbolGraphGen\/SymbolGraphGen.h\"\n#include \"llvm\/ADT\/ArrayRef.h\"\n#include \"llvm\/ADT\/SmallVector.h\"\n#include \"llvm\/Support\/raw_ostream.h\"\n\nusing namespace swift;\nusing namespace options;\n\nint swift_symbolgraph_extract_main(ArrayRef<const char *> Args,\n const char *Argv0, void *MainAddr) {\n INITIALIZE_LLVM();\n\n CompilerInvocation Invocation;\n CompilerInstance CI;\n PrintingDiagnosticConsumer DiagPrinter;\n auto &Diags = CI.getDiags();\n Diags.addConsumer(DiagPrinter);\n\n std::unique_ptr<llvm::opt::OptTable> Table = createSwiftOptTable();\n unsigned MissingIndex;\n unsigned MissingCount;\n llvm::opt::InputArgList ParsedArgs = Table->ParseArgs(\n Args, MissingIndex, MissingCount, SwiftSymbolGraphExtractOption);\n if (MissingCount) {\n Diags.diagnose(SourceLoc(), diag::error_missing_arg_value,\n ParsedArgs.getArgString(MissingIndex), MissingCount);\n return EXIT_FAILURE;\n }\n\n if (ParsedArgs.hasArg(OPT_UNKNOWN)) {\n for (const auto *A : ParsedArgs.filtered(OPT_UNKNOWN)) {\n Diags.diagnose(SourceLoc(), diag::error_unknown_arg,\n A->getAsString(ParsedArgs));\n }\n return EXIT_FAILURE;\n }\n\n auto MainExecutablePath = llvm::sys::fs::getMainExecutable(Argv0, MainAddr);\n\n if (ParsedArgs.getLastArg(OPT_help) || Args.empty()) {\n std::string ExecutableName =\n llvm::sys::path::stem(MainExecutablePath).str();\n Table->printHelp(llvm::outs(), ExecutableName.c_str(),\n \"Swift Symbol Graph Extractor\",\n SwiftSymbolGraphExtractOption, 0,\n \/*ShowAllAliases*\/ false);\n return EXIT_FAILURE;\n }\n\n std::string ModuleName;\n if (auto *A = ParsedArgs.getLastArg(OPT_module_name)) {\n ModuleName = A->getValue();\n } else {\n Diags.diagnose(SourceLoc(), diag::error_option_required, \"-module-name\");\n return EXIT_FAILURE;\n }\n\n llvm::Triple Target;\n if (auto *A = ParsedArgs.getLastArg(OPT_target)) {\n Target = llvm::Triple(A->getValue());\n } else {\n Diags.diagnose(SourceLoc(), diag::error_option_required, \"-target\");\n return EXIT_FAILURE;\n }\n\n std::string OutputDir;\n if (auto *A = ParsedArgs.getLastArg(OPT_output_dir)) {\n OutputDir = A->getValue();\n } else {\n Diags.diagnose(SourceLoc(), diag::error_option_required, \"-output-dir\");\n return EXIT_FAILURE;\n }\n\n if (!llvm::sys::fs::is_directory(OutputDir)) {\n Diags.diagnose(SourceLoc(), diag::error_nonexistent_output_dir, OutputDir);\n return EXIT_FAILURE;\n }\n\n Invocation.setMainExecutablePath(MainExecutablePath);\n Invocation.setModuleName(\"swift_symbolgraph_extract\");\n\n if (auto *A = ParsedArgs.getLastArg(OPT_resource_dir)) {\n Invocation.setRuntimeResourcePath(A->getValue());\n }\n\n std::string SDK = \"\";\n if (auto *A = ParsedArgs.getLastArg(OPT_sdk)) {\n SDK = A->getValue();\n }\n Invocation.setSDKPath(SDK);\n\n Invocation.setTargetTriple(Target);\n\n for (const auto *A : ParsedArgs.filtered(OPT_Xcc)) {\n Invocation.getClangImporterOptions().ExtraArgs.push_back(A->getValue());\n }\n\n std::vector<SearchPathOptions::FrameworkSearchPath> FrameworkSearchPaths;\n for (const auto *A : ParsedArgs.filtered(OPT_F)) {\n FrameworkSearchPaths.push_back({A->getValue(), \/*isSystem*\/ false});\n }\n for (const auto *A : ParsedArgs.filtered(OPT_Fsystem)) {\n FrameworkSearchPaths.push_back({A->getValue(), \/*isSystem*\/ true});\n }\n Invocation.setFrameworkSearchPaths(FrameworkSearchPaths);\n Invocation.getSearchPathOptions().LibrarySearchPaths =\n ParsedArgs.getAllArgValues(OPT_L);\n Invocation.setImportSearchPaths(ParsedArgs.getAllArgValues(OPT_I));\n\n Invocation.getLangOptions().EnableObjCInterop = Target.isOSDarwin();\n Invocation.getLangOptions().DebuggerSupport = true;\n\n Invocation.getFrontendOptions().EnableLibraryEvolution = true;\n\n std::string ModuleCachePath = \"\";\n if (auto *A = ParsedArgs.getLastArg(OPT_module_cache_path)) {\n ModuleCachePath = A->getValue();\n }\n Invocation.setClangModuleCachePath(ModuleCachePath);\n Invocation.getClangImporterOptions().ModuleCachePath = ModuleCachePath;\n Invocation.setDefaultPrebuiltCacheIfNecessary();\n\n if (auto *A = ParsedArgs.getLastArg(OPT_swift_version)) {\n using version::Version;\n auto SwiftVersion = A->getValue();\n bool isValid = false;\n if (auto Version =\n Version::parseVersionString(SwiftVersion, SourceLoc(), nullptr)) {\n if (auto Effective = Version.getValue().getEffectiveLanguageVersion()) {\n Invocation.getLangOptions().EffectiveLanguageVersion = *Effective;\n isValid = true;\n }\n }\n if (!isValid) {\n Diags.diagnose(SourceLoc(), diag::error_invalid_arg_value,\n \"-swift-version\", SwiftVersion);\n return EXIT_FAILURE;\n }\n }\n\n symbolgraphgen::SymbolGraphOptions Options{\n OutputDir,\n Target,\n ParsedArgs.hasArg(OPT_pretty_print),\n AccessLevel::Public,\n !ParsedArgs.hasArg(OPT_skip_synthesized_members),\n ParsedArgs.hasArg(OPT_v),\n ParsedArgs.hasArg(OPT_skip_inherited_docs),\n ParsedArgs.hasArg(OPT_include_spi_symbols),\n \/*IncludeClangDocs=*\/false,\n };\n\n if (auto *A = ParsedArgs.getLastArg(OPT_minimum_access_level)) {\n Options.MinimumAccessLevel =\n llvm::StringSwitch<AccessLevel>(A->getValue())\n .Case(\"open\", AccessLevel::Open)\n .Case(\"public\", AccessLevel::Public)\n .Case(\"internal\", AccessLevel::Internal)\n .Case(\"fileprivate\", AccessLevel::FilePrivate)\n .Case(\"private\", AccessLevel::Private)\n .Default(AccessLevel::Public);\n }\n\n std::string InstanceSetupError;\n if (CI.setup(Invocation, InstanceSetupError)) {\n llvm::outs() << InstanceSetupError << '\\n';\n return EXIT_FAILURE;\n }\n\n auto M = CI.getASTContext().getModuleByName(ModuleName);\n if (!M) {\n llvm::errs()\n << \"Couldn't load module '\" << ModuleName << '\\''\n << \" in the current SDK and search paths.\\n\";\n \n SmallVector<Identifier, 32> VisibleModuleNames;\n CI.getASTContext().getVisibleTopLevelModuleNames(VisibleModuleNames);\n\n if (VisibleModuleNames.empty()) {\n llvm::errs() << \"Could not find any modules.\\n\";\n } else {\n std::sort(VisibleModuleNames.begin(), VisibleModuleNames.end(),\n [](const Identifier &A, const Identifier &B) -> bool {\n return A.str() < B.str();\n });\n llvm::errs() << \"Current visible modules:\\n\";\n for (const auto &ModuleName : VisibleModuleNames) {\n llvm::errs() << ModuleName.str() << \"\\n\";\n }\n }\n return EXIT_FAILURE;\n }\n \n if (M->failedToLoad()) {\n llvm::errs() << \"Error: Failed to load the module '\" << ModuleName\n << \"'. Are you missing build dependencies or \"\n \"include\/framework directories?\\n\"\n << \"See the previous error messages for details. Aborting.\\n\";\n\n return EXIT_FAILURE;\n }\n\n FileUnitKind expectedKind = FileUnitKind::SerializedAST;\n if (M->isNonSwiftModule())\n expectedKind = FileUnitKind::ClangModule;\n const auto &MainFile = M->getMainFile(expectedKind);\n \n if (Options.PrintMessages)\n llvm::errs() << \"Emitting symbol graph for module file: \" << MainFile.getModuleDefiningPath() << '\\n';\n \n int Success = symbolgraphgen::emitSymbolGraphForModule(M, Options);\n \n \/\/ Look for cross-import overlays that the given module imports.\n \n \/\/ Clear out the diagnostic printer before looking for cross-import overlay modules,\n \/\/ since some SDK modules can cause errors in the getModuleByName() call. The call\n \/\/ itself will properly return nullptr after this failure, so for our purposes we\n \/\/ don't need to print these errors.\n CI.removeDiagnosticConsumer(&DiagPrinter);\n \n SmallVector<ModuleDecl *, 8> Overlays;\n M->findDeclaredCrossImportOverlaysTransitive(Overlays);\n for (const auto *OM : Overlays) {\n auto CIM = CI.getASTContext().getModuleByName(OM->getNameStr());\n if (CIM) {\n const auto &CIMainFile = CIM->getMainFile(FileUnitKind::SerializedAST);\n \n if (Options.PrintMessages)\n llvm::errs() << \"Emitting symbol graph for cross-import overlay module file: \"\n << CIMainFile.getModuleDefiningPath() << '\\n';\n \n Success |= symbolgraphgen::emitSymbolGraphForModule(CIM, Options);\n }\n }\n\n return Success;\n}\n<|endoftext|>"} {"text":"<commit_before>\/***************************************************************************\n**\n** Copyright (C) 2010 Nokia Corporation and\/or its subsidiary(-ies).\n** All rights reserved.\n** Contact: Nokia Corporation (directui@nokia.com)\n**\n** This file is part of libmeegotouch.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at directui@nokia.com.\n**\n** This library is free software; you can redistribute it and\/or\n** modify it under the terms of the GNU Lesser General Public\n** License version 2.1 as published by the Free Software Foundation\n** and appearing in the file LICENSE.LGPL included in the packaging\n** of this file.\n**\n****************************************************************************\/\n\n#include \"mbuttonview.h\"\n#include \"mbuttonview_p.h\"\n\n#include <QPainter>\n#include <QGraphicsSceneMouseEvent>\n#include <QFontMetricsF>\n#include <QPixmap>\n#include <QIcon>\n\n#include \"mbutton.h\"\n#include \"mfeedback.h\"\n#include \"mtheme.h\"\n#include \"mscalableimage.h\"\n#include \"mviewcreator.h\"\n#include \"mscenemanager.h\"\n#include \"mlabel.h\"\n#include \"mdebug.h\"\n#include \"mtimestamp.h\"\n\n\/\/ Distance in pixels from the widget bounding box inside which a release is still accepted\n#define RELEASE_MISS_DELTA 30\n\nMButtonViewPrivate::MButtonViewPrivate()\n : icon(0), toggledIcon(0), label(NULL), iconFromQIcon(false), toggledIconFromQIcon(false)\n{\n}\n\nvoid MButtonViewPrivate::freeIcons()\n{\n if (iconFromQIcon && icon) {\n delete icon;\n } else {\n MTheme::releasePixmap(icon);\n }\n\n if (toggledIconFromQIcon && toggledIcon) {\n delete toggledIcon;\n } else {\n MTheme::releasePixmap(toggledIcon);\n }\n\n icon = 0;\n toggledIcon = 0;\n}\n\nMButtonViewPrivate::~MButtonViewPrivate()\n{\n freeIcons();\n}\n\n\/\/ As the condition of text color and background change for button\nbool MButtonViewPrivate::toggleState() const\n{\n Q_Q(const MButtonView);\n if (q->model()->checkable()) {\n bool state = (!q->model()->checked() && q->model()->down())\n || (q->model()->checked() && !q->model()->down());\n return state;\n } else\n return q->model()->down();\n}\n\nvoid MButtonViewPrivate::refreshStyleMode()\n{\n Q_Q(MButtonView);\n\n if (q->model()->down())\n q->style().setModePressed();\n else if (q->model()->checked())\n q->style().setModeSelected();\n else\n q->style().setModeDefault();\n\n label->setAlignment(q->style()->horizontalTextAlign() | q->style()->verticalTextAlign());\n label->setFont(q->style()->font());\n label->setColor(q->style()->textColor());\n\n \/\/update the icons only if the iconSize in the style has changed\n QSize size = q->style()->iconSize();\n if (icon && icon->size() != size) {\n if (iconFromQIcon)\n loadIcon(q->model()->icon(), size);\n else\n loadIcon(q->model()->iconID(), size);\n }\n if (toggledIcon && toggledIcon->size() != size) {\n if (toggledIconFromQIcon)\n loadIcon(q->model()->icon(), size);\n else\n loadIcon(q->model()->toggledIconID(), size, QIcon::Selected);\n }\n\n calcIconTextRects();\n}\n\nvoid MButtonViewPrivate::calcIconTextRects()\n{\n Q_Q(const MButtonView);\n\n \/\/total horizontal and vertical text margins\n int hTextMargin = q->style()->textMarginLeft() + q->style()->textMarginRight();\n int vTextMargin = q->style()->textMarginTop() + q->style()->textMarginBottom();\n\n \/\/total horizontal and vertical padding\n int hPadding = q->style()->paddingLeft() + q->style()->paddingRight();\n int vPadding = q->style()->paddingTop() + q->style()->paddingBottom();\n\n \/\/area for the content (icon and text)\n QRect contentRect(q->style()->paddingLeft(), q->style()->paddingTop(),\n q->size().width() - hPadding,\n q->size().height() - vPadding);\n\n \/\/text rect when there is no icon\n QRect textRect = QRect(contentRect.left() + q->style()->textMarginLeft(),\n contentRect.top() + q->style()->textMarginTop(),\n contentRect.width() - hTextMargin,\n contentRect.height() - vTextMargin);\n\n \/\/icon visible and valid?\n if (q->model()->iconVisible() && (icon || toggledIcon)) {\n\n int iconWidth = q->style()->iconSize().width();\n int iconHeight = q->style()->iconSize().height();\n\n \/\/text visible and valid?\n if (q->model()->textVisible() && !q->model()->text().isEmpty()) {\n\n switch (q->style()->iconAlign()) {\n \/\/icon on left and text on right\n case Qt::AlignLeft: {\n iconRect = QRectF(contentRect.left(), contentRect.center().y() - (iconHeight \/ 2), iconWidth, iconHeight);\n textRect.setX(iconRect.right() + q->style()->textMarginLeft());\n textRect.setWidth(contentRect.width() - iconWidth - hTextMargin);\n break;\n }\n\n \/\/icon on right and text on left\n case Qt::AlignRight: {\n iconRect = QRectF(contentRect.right() - iconWidth, contentRect.center().y() - (iconHeight \/ 2), iconWidth, iconHeight);\n textRect.setWidth(contentRect.width() - iconWidth - hTextMargin);\n break;\n }\n\n \/\/icon on bottom and text on top\n case Qt::AlignBottom: {\n iconRect = QRectF(contentRect.center().x() - (iconWidth \/ 2), contentRect.bottom() - iconHeight, iconWidth, iconHeight);\n textRect.setHeight(contentRect.height() - iconHeight - vTextMargin);\n break;\n }\n\n \/\/icon on top and text on bottom\n default: {\n iconRect = QRectF(contentRect.center().x() - (iconWidth \/ 2), contentRect.top(), iconWidth, iconHeight);\n textRect.setY(iconRect.bottom() + q->style()->textMarginTop());\n textRect.setHeight(contentRect.height() - iconHeight - vTextMargin);\n break;\n }\n }\n }\n \/\/ no text\n else {\n \/\/icon on center\n iconRect = QRectF(contentRect.center().x() - (iconWidth \/ 2), contentRect.center().y() - (iconHeight \/ 2), iconWidth, iconHeight);\n }\n }\n\n \/\/adjust label with button margins\n label->setGeometry(textRect.translated(q->marginLeft(), q->marginTop()));\n}\n\nvoid MButtonViewPrivate::loadIcon(const QIcon &newQIcon, const QSize &newIconSize)\n{\n freeIcons();\n\n icon = new QPixmap(newQIcon.pixmap(newIconSize));\n iconFromQIcon = true;\n\n toggledIcon = new QPixmap(newQIcon.pixmap(newIconSize, QIcon::Selected));\n if (toggledIcon && !toggledIcon->isNull()) {\n toggledIconFromQIcon = true;\n }\n}\n\nvoid MButtonViewPrivate::loadIcon(const QString &newIconId, const QSize &newIconSize, QIcon::Mode mode)\n{\n const QPixmap **tmp;\n bool *fromQIcon;\n\n if (mode == QIcon::Selected)\n {\n fromQIcon = &toggledIconFromQIcon;\n tmp = &toggledIcon;\n }\n else\n {\n fromQIcon = &iconFromQIcon;\n tmp = &icon;\n }\n\n if (*tmp)\n {\n if (*fromQIcon)\n delete *tmp;\n else\n MTheme::releasePixmap(*tmp);\n }\n\n *fromQIcon = false;\n *tmp = 0;\n\n if (!newIconId.isEmpty())\n *tmp = MTheme::pixmap(newIconId, newIconSize);\n}\n\nMButtonView::MButtonView(MButton *controller) :\n MWidgetView(* new MButtonViewPrivate, controller)\n{\n Q_D(MButtonView);\n d->label = new MLabel(controller);\n d->label->setParentItem(controller);\n d->label->setTextElide(true);\n d->label->setObjectName(\"ButtonLabel\");\n}\n\nMButtonView::MButtonView(MButtonViewPrivate &dd, MButton *controller) :\n MWidgetView(dd, controller)\n{\n Q_D(MButtonView);\n d->label = new MLabel(controller);\n d->label->setParentItem(controller);\n d->label->setTextElide(true);\n d->label->setObjectName(\"ButtonLabel\");\n}\n\nMButtonView::~MButtonView()\n{\n Q_D(MButtonView);\n if (d->label) {\n delete d->label;\n d->label = 0;\n }\n}\n\nvoid MButtonView::resizeEvent(QGraphicsSceneResizeEvent *event)\n{\n Q_D(MButtonView);\n\n MWidgetView::resizeEvent(event);\n\n d->calcIconTextRects();\n}\n\nvoid MButtonView::drawContents(QPainter *painter, const QStyleOptionGraphicsItem *option) const\n{\n Q_UNUSED(option);\n\n Q_D(const MButtonView);\n mTimestamp(\"MButtonView\", QString(\"start text=%1\").arg(model()->text()));\n drawIcon(painter, d->iconRect);\n mTimestamp(\"MButtonView\", QString(\"end text=%1\").arg(model()->text()));\n}\n\nvoid MButtonView::drawIcon(QPainter *painter, const QRectF &iconRect) const\n{\n if (model()->iconVisible()) {\n Q_D(const MButtonView);\n\n bool toggleState = d->toggleState();\n\n const QPixmap *pixmap = NULL;\n if (toggleState && d->toggledIcon)\n pixmap = d->toggledIcon;\n else\n pixmap = d->icon;\n\n if (pixmap)\n painter->drawPixmap(iconRect, *pixmap, QRectF(pixmap->rect()));\n }\n}\n\n\/*MLabel* MButtonView::label()\n{\n Q_D(const MButtonView);\n return d->label;\n}*\/\n\nvoid MButtonView::applyStyle()\n{\n Q_D(MButtonView);\n\n MWidgetView::applyStyle();\n\n d->refreshStyleMode();\n\n update();\n}\n\nvoid MButtonView::mousePressEvent(QGraphicsSceneMouseEvent *event)\n{\n Q_UNUSED(event);\n\n if (model()->down()) {\n return;\n }\n model()->setDown(true);\n\n style()->pressFeedback().play();\n}\n\nvoid MButtonView::mouseMoveEvent(QGraphicsSceneMouseEvent *event)\n{\n Q_D(MButtonView);\n\n QPointF touch = event->scenePos();\n QRectF rect = d->controller->sceneBoundingRect();\n rect.adjust(-RELEASE_MISS_DELTA, -RELEASE_MISS_DELTA,\n RELEASE_MISS_DELTA, RELEASE_MISS_DELTA);\n\n if (rect.contains(touch)) {\n if (!model()->down()) {\n model()->setDown(true);\n style()->pressFeedback().play();\n }\n } else {\n if (model()->down()) {\n model()->setDown(false);\n style()->cancelFeedback().play();\n }\n }\n\n}\n\nvoid MButtonView::mouseReleaseEvent(QGraphicsSceneMouseEvent *event)\n{\n Q_D(MButtonView);\n\n if (!model()->down()) {\n return;\n }\n model()->setDown(false);\n\n style()->releaseFeedback().play();\n\n QPointF touch = event->scenePos();\n QRectF rect = d->controller->sceneBoundingRect();\n rect.adjust(-RELEASE_MISS_DELTA, -RELEASE_MISS_DELTA,\n RELEASE_MISS_DELTA, RELEASE_MISS_DELTA);\n if (rect.contains(touch))\n model()->click();\n}\n\nvoid MButtonView::cancelEvent(MCancelEvent *event)\n{\n Q_UNUSED(event);\n\n if (!model()->down()) {\n return;\n }\n\n style()->cancelFeedback().play();\n\n model()->setDown(false);\n}\n\nvoid MButtonView::updateData(const QList<const char *>& modifications)\n{\n Q_D(MButtonView);\n\n MWidgetView::updateData(modifications);\n const char *member;\n foreach(member, modifications) {\n if (member == MButtonModel::Text) {\n d->label->setText(model()->text());\n d->calcIconTextRects();\n } else if (member == MButtonModel::TextVisible) {\n d->label->setVisible(model()->textVisible());\n d->calcIconTextRects();\n } else if (member == MButtonModel::IconID) {\n d->loadIcon(model()->iconID(), style()->iconSize());\n d->calcIconTextRects();\n } else if (member == MButtonModel::ToggledIconID) {\n d->loadIcon(model()->toggledIconID(), style()->iconSize(), QIcon::Selected);\n d->calcIconTextRects();\n } else if (member == MButtonModel::Icon) {\n d->loadIcon(model()->icon(), style()->iconSize());\n d->calcIconTextRects();\n } else if (member == MButtonModel::IconVisible) {\n d->calcIconTextRects();\n } else if (member == MButtonModel::Down || member == MButtonModel::Checked ||\n member == MButtonModel::Checkable) {\n d->refreshStyleMode();\n }\n }\n update();\n}\n\nvoid MButtonView::setupModel()\n{\n Q_D(MButtonView);\n\n MWidgetView::setupModel();\n QList<const char *> members;\n if (model()->icon().isNull())\n members << MButtonModel::IconID;\n else\n members << MButtonModel::Icon;\n if (!model()->toggledIconID().isEmpty())\n members << MButtonModel::ToggledIconID;\n\n updateData(members);\n\n d->label->setText(model()->text());\n d->label->setVisible(model()->textVisible());\n\n update();\n}\n\nQSizeF MButtonView::sizeHint(Qt::SizeHint which, const QSizeF &constraint) const\n{\n Q_D(const MButtonView);\n\n if (which == Qt::MinimumSize || which == Qt::MaximumSize)\n return MWidgetView::sizeHint(which, constraint);\n\n if (style()->preferredSize().isValid())\n return style()->preferredSize();\n\n\n QSizeF iconSize(0, 0);\n if (model()->iconVisible() && d->icon)\n iconSize = d->icon->size();\n\n QSizeF textSize(0, 0);\n if (model()->textVisible() && !model()->text().isEmpty()) {\n QFontMetricsF fm(style()->font());\n textSize = fm.size(0, model()->text());\n textSize += QSizeF(style()->textMarginLeft() + style()->textMarginRight(), style()->textMarginTop() + style()->textMarginBottom());\n }\n\n qreal width = 0, height = 0;\n if (style()->iconAlign() == Qt::AlignTop || style()->iconAlign() == Qt::AlignBottom) {\n width = qMax(iconSize.width(), textSize.width());\n height = iconSize.height() + textSize.height();\n } else {\n width = iconSize.width() + textSize.width();\n height = qMax(iconSize.height(), textSize.height());\n }\n\n return QSizeF(width + style()->paddingLeft() + style()->paddingRight(), height + style()->paddingTop() + style()->paddingBottom());\n}\n\nM_REGISTER_VIEW_NEW(MButtonView, MButton)\n<commit_msg>Changes: MButtonView - Using QRectF instead of QRect<commit_after>\/***************************************************************************\n**\n** Copyright (C) 2010 Nokia Corporation and\/or its subsidiary(-ies).\n** All rights reserved.\n** Contact: Nokia Corporation (directui@nokia.com)\n**\n** This file is part of libmeegotouch.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at directui@nokia.com.\n**\n** This library is free software; you can redistribute it and\/or\n** modify it under the terms of the GNU Lesser General Public\n** License version 2.1 as published by the Free Software Foundation\n** and appearing in the file LICENSE.LGPL included in the packaging\n** of this file.\n**\n****************************************************************************\/\n\n#include \"mbuttonview.h\"\n#include \"mbuttonview_p.h\"\n\n#include <QPainter>\n#include <QGraphicsSceneMouseEvent>\n#include <QFontMetricsF>\n#include <QPixmap>\n#include <QIcon>\n\n#include \"mbutton.h\"\n#include \"mfeedback.h\"\n#include \"mtheme.h\"\n#include \"mscalableimage.h\"\n#include \"mviewcreator.h\"\n#include \"mscenemanager.h\"\n#include \"mlabel.h\"\n#include \"mdebug.h\"\n#include \"mtimestamp.h\"\n\n\/\/ Distance in pixels from the widget bounding box inside which a release is still accepted\n#define RELEASE_MISS_DELTA 30\n\nMButtonViewPrivate::MButtonViewPrivate()\n : icon(0), toggledIcon(0), label(NULL), iconFromQIcon(false), toggledIconFromQIcon(false)\n{\n}\n\nvoid MButtonViewPrivate::freeIcons()\n{\n if (iconFromQIcon && icon) {\n delete icon;\n } else {\n MTheme::releasePixmap(icon);\n }\n\n if (toggledIconFromQIcon && toggledIcon) {\n delete toggledIcon;\n } else {\n MTheme::releasePixmap(toggledIcon);\n }\n\n icon = 0;\n toggledIcon = 0;\n}\n\nMButtonViewPrivate::~MButtonViewPrivate()\n{\n freeIcons();\n}\n\n\/\/ As the condition of text color and background change for button\nbool MButtonViewPrivate::toggleState() const\n{\n Q_Q(const MButtonView);\n if (q->model()->checkable()) {\n bool state = (!q->model()->checked() && q->model()->down())\n || (q->model()->checked() && !q->model()->down());\n return state;\n } else\n return q->model()->down();\n}\n\nvoid MButtonViewPrivate::refreshStyleMode()\n{\n Q_Q(MButtonView);\n\n if (q->model()->down())\n q->style().setModePressed();\n else if (q->model()->checked())\n q->style().setModeSelected();\n else\n q->style().setModeDefault();\n\n label->setAlignment(q->style()->horizontalTextAlign() | q->style()->verticalTextAlign());\n label->setFont(q->style()->font());\n label->setColor(q->style()->textColor());\n\n \/\/update the icons only if the iconSize in the style has changed\n QSize size = q->style()->iconSize();\n if (icon && icon->size() != size) {\n if (iconFromQIcon)\n loadIcon(q->model()->icon(), size);\n else\n loadIcon(q->model()->iconID(), size);\n }\n if (toggledIcon && toggledIcon->size() != size) {\n if (toggledIconFromQIcon)\n loadIcon(q->model()->icon(), size);\n else\n loadIcon(q->model()->toggledIconID(), size, QIcon::Selected);\n }\n\n calcIconTextRects();\n}\n\nvoid MButtonViewPrivate::calcIconTextRects()\n{\n Q_Q(const MButtonView);\n\n \/\/total horizontal and vertical text margins\n int hTextMargin = q->style()->textMarginLeft() + q->style()->textMarginRight();\n int vTextMargin = q->style()->textMarginTop() + q->style()->textMarginBottom();\n\n \/\/total horizontal and vertical padding\n int hPadding = q->style()->paddingLeft() + q->style()->paddingRight();\n int vPadding = q->style()->paddingTop() + q->style()->paddingBottom();\n\n \/\/area for the content (icon and text)\n QRectF contentRect(q->style()->paddingLeft(), q->style()->paddingTop(),\n q->size().width() - hPadding,\n q->size().height() - vPadding);\n\n \/\/text rect when there is no icon\n QRectF textRect(contentRect.left() + q->style()->textMarginLeft(),\n contentRect.top() + q->style()->textMarginTop(),\n contentRect.width() - hTextMargin,\n contentRect.height() - vTextMargin);\n\n \/\/icon visible and valid?\n if (q->model()->iconVisible() && (icon || toggledIcon)) {\n\n int iconWidth = q->style()->iconSize().width();\n int iconHeight = q->style()->iconSize().height();\n\n \/\/text visible and valid?\n if (q->model()->textVisible() && !q->model()->text().isEmpty()) {\n\n switch (q->style()->iconAlign()) {\n \/\/icon on left and text on right\n case Qt::AlignLeft: {\n iconRect = QRectF(contentRect.left(), contentRect.center().y() - (iconHeight \/ 2), iconWidth, iconHeight);\n textRect.setX(iconRect.right() + q->style()->textMarginLeft());\n textRect.setWidth(contentRect.width() - iconWidth - hTextMargin);\n break;\n }\n\n \/\/icon on right and text on left\n case Qt::AlignRight: {\n iconRect = QRectF(contentRect.right() - iconWidth, contentRect.center().y() - (iconHeight \/ 2), iconWidth, iconHeight);\n textRect.setWidth(contentRect.width() - iconWidth - hTextMargin);\n break;\n }\n\n \/\/icon on bottom and text on top\n case Qt::AlignBottom: {\n iconRect = QRectF(contentRect.center().x() - (iconWidth \/ 2), contentRect.bottom() - iconHeight, iconWidth, iconHeight);\n textRect.setHeight(contentRect.height() - iconHeight - vTextMargin);\n break;\n }\n\n \/\/icon on top and text on bottom\n default: {\n iconRect = QRectF(contentRect.center().x() - (iconWidth \/ 2), contentRect.top(), iconWidth, iconHeight);\n textRect.setY(iconRect.bottom() + q->style()->textMarginTop());\n textRect.setHeight(contentRect.height() - iconHeight - vTextMargin);\n break;\n }\n }\n }\n \/\/ no text\n else {\n \/\/icon on center\n iconRect = QRectF(contentRect.center().x() - (iconWidth \/ 2), contentRect.center().y() - (iconHeight \/ 2), iconWidth, iconHeight);\n }\n }\n\n \/\/adjust label with button margins\n label->setGeometry(textRect.translated(q->marginLeft(), q->marginTop()));\n}\n\nvoid MButtonViewPrivate::loadIcon(const QIcon &newQIcon, const QSize &newIconSize)\n{\n freeIcons();\n\n icon = new QPixmap(newQIcon.pixmap(newIconSize));\n iconFromQIcon = true;\n\n toggledIcon = new QPixmap(newQIcon.pixmap(newIconSize, QIcon::Selected));\n if (toggledIcon && !toggledIcon->isNull()) {\n toggledIconFromQIcon = true;\n }\n}\n\nvoid MButtonViewPrivate::loadIcon(const QString &newIconId, const QSize &newIconSize, QIcon::Mode mode)\n{\n const QPixmap **tmp;\n bool *fromQIcon;\n\n if (mode == QIcon::Selected)\n {\n fromQIcon = &toggledIconFromQIcon;\n tmp = &toggledIcon;\n }\n else\n {\n fromQIcon = &iconFromQIcon;\n tmp = &icon;\n }\n\n if (*tmp)\n {\n if (*fromQIcon)\n delete *tmp;\n else\n MTheme::releasePixmap(*tmp);\n }\n\n *fromQIcon = false;\n *tmp = 0;\n\n if (!newIconId.isEmpty())\n *tmp = MTheme::pixmap(newIconId, newIconSize);\n}\n\nMButtonView::MButtonView(MButton *controller) :\n MWidgetView(* new MButtonViewPrivate, controller)\n{\n Q_D(MButtonView);\n d->label = new MLabel(controller);\n d->label->setParentItem(controller);\n d->label->setTextElide(true);\n d->label->setObjectName(\"ButtonLabel\");\n}\n\nMButtonView::MButtonView(MButtonViewPrivate &dd, MButton *controller) :\n MWidgetView(dd, controller)\n{\n Q_D(MButtonView);\n d->label = new MLabel(controller);\n d->label->setParentItem(controller);\n d->label->setTextElide(true);\n d->label->setObjectName(\"ButtonLabel\");\n}\n\nMButtonView::~MButtonView()\n{\n Q_D(MButtonView);\n if (d->label) {\n delete d->label;\n d->label = 0;\n }\n}\n\nvoid MButtonView::resizeEvent(QGraphicsSceneResizeEvent *event)\n{\n Q_D(MButtonView);\n\n MWidgetView::resizeEvent(event);\n\n d->calcIconTextRects();\n}\n\nvoid MButtonView::drawContents(QPainter *painter, const QStyleOptionGraphicsItem *option) const\n{\n Q_UNUSED(option);\n\n Q_D(const MButtonView);\n mTimestamp(\"MButtonView\", QString(\"start text=%1\").arg(model()->text()));\n drawIcon(painter, d->iconRect);\n mTimestamp(\"MButtonView\", QString(\"end text=%1\").arg(model()->text()));\n}\n\nvoid MButtonView::drawIcon(QPainter *painter, const QRectF &iconRect) const\n{\n if (model()->iconVisible()) {\n Q_D(const MButtonView);\n\n bool toggleState = d->toggleState();\n\n const QPixmap *pixmap = NULL;\n if (toggleState && d->toggledIcon)\n pixmap = d->toggledIcon;\n else\n pixmap = d->icon;\n\n if (pixmap)\n painter->drawPixmap(iconRect, *pixmap, QRectF(pixmap->rect()));\n }\n}\n\n\/*MLabel* MButtonView::label()\n{\n Q_D(const MButtonView);\n return d->label;\n}*\/\n\nvoid MButtonView::applyStyle()\n{\n Q_D(MButtonView);\n\n MWidgetView::applyStyle();\n\n d->refreshStyleMode();\n\n update();\n}\n\nvoid MButtonView::mousePressEvent(QGraphicsSceneMouseEvent *event)\n{\n Q_UNUSED(event);\n\n if (model()->down()) {\n return;\n }\n model()->setDown(true);\n\n style()->pressFeedback().play();\n}\n\nvoid MButtonView::mouseMoveEvent(QGraphicsSceneMouseEvent *event)\n{\n Q_D(MButtonView);\n\n QPointF touch = event->scenePos();\n QRectF rect = d->controller->sceneBoundingRect();\n rect.adjust(-RELEASE_MISS_DELTA, -RELEASE_MISS_DELTA,\n RELEASE_MISS_DELTA, RELEASE_MISS_DELTA);\n\n if (rect.contains(touch)) {\n if (!model()->down()) {\n model()->setDown(true);\n style()->pressFeedback().play();\n }\n } else {\n if (model()->down()) {\n model()->setDown(false);\n style()->cancelFeedback().play();\n }\n }\n\n}\n\nvoid MButtonView::mouseReleaseEvent(QGraphicsSceneMouseEvent *event)\n{\n Q_D(MButtonView);\n\n if (!model()->down()) {\n return;\n }\n model()->setDown(false);\n\n style()->releaseFeedback().play();\n\n QPointF touch = event->scenePos();\n QRectF rect = d->controller->sceneBoundingRect();\n rect.adjust(-RELEASE_MISS_DELTA, -RELEASE_MISS_DELTA,\n RELEASE_MISS_DELTA, RELEASE_MISS_DELTA);\n if (rect.contains(touch))\n model()->click();\n}\n\nvoid MButtonView::cancelEvent(MCancelEvent *event)\n{\n Q_UNUSED(event);\n\n if (!model()->down()) {\n return;\n }\n\n style()->cancelFeedback().play();\n\n model()->setDown(false);\n}\n\nvoid MButtonView::updateData(const QList<const char *>& modifications)\n{\n Q_D(MButtonView);\n\n MWidgetView::updateData(modifications);\n const char *member;\n foreach(member, modifications) {\n if (member == MButtonModel::Text) {\n d->label->setText(model()->text());\n d->calcIconTextRects();\n } else if (member == MButtonModel::TextVisible) {\n d->label->setVisible(model()->textVisible());\n d->calcIconTextRects();\n } else if (member == MButtonModel::IconID) {\n d->loadIcon(model()->iconID(), style()->iconSize());\n d->calcIconTextRects();\n } else if (member == MButtonModel::ToggledIconID) {\n d->loadIcon(model()->toggledIconID(), style()->iconSize(), QIcon::Selected);\n d->calcIconTextRects();\n } else if (member == MButtonModel::Icon) {\n d->loadIcon(model()->icon(), style()->iconSize());\n d->calcIconTextRects();\n } else if (member == MButtonModel::IconVisible) {\n d->calcIconTextRects();\n } else if (member == MButtonModel::Down || member == MButtonModel::Checked ||\n member == MButtonModel::Checkable) {\n d->refreshStyleMode();\n }\n }\n update();\n}\n\nvoid MButtonView::setupModel()\n{\n Q_D(MButtonView);\n\n MWidgetView::setupModel();\n QList<const char *> members;\n if (model()->icon().isNull())\n members << MButtonModel::IconID;\n else\n members << MButtonModel::Icon;\n if (!model()->toggledIconID().isEmpty())\n members << MButtonModel::ToggledIconID;\n\n updateData(members);\n\n d->label->setText(model()->text());\n d->label->setVisible(model()->textVisible());\n\n update();\n}\n\nQSizeF MButtonView::sizeHint(Qt::SizeHint which, const QSizeF &constraint) const\n{\n Q_D(const MButtonView);\n\n if (which == Qt::MinimumSize || which == Qt::MaximumSize)\n return MWidgetView::sizeHint(which, constraint);\n\n if (style()->preferredSize().isValid())\n return style()->preferredSize();\n\n\n QSizeF iconSize(0, 0);\n if (model()->iconVisible() && d->icon)\n iconSize = d->icon->size();\n\n QSizeF textSize(0, 0);\n if (model()->textVisible() && !model()->text().isEmpty()) {\n QFontMetricsF fm(style()->font());\n textSize = fm.size(0, model()->text());\n textSize += QSizeF(style()->textMarginLeft() + style()->textMarginRight(), style()->textMarginTop() + style()->textMarginBottom());\n }\n\n qreal width = 0, height = 0;\n if (style()->iconAlign() == Qt::AlignTop || style()->iconAlign() == Qt::AlignBottom) {\n width = qMax(iconSize.width(), textSize.width());\n height = iconSize.height() + textSize.height();\n } else {\n width = iconSize.width() + textSize.width();\n height = qMax(iconSize.height(), textSize.height());\n }\n\n return QSizeF(width + style()->paddingLeft() + style()->paddingRight(), height + style()->paddingTop() + style()->paddingBottom());\n}\n\nM_REGISTER_VIEW_NEW(MButtonView, MButton)\n<|endoftext|>"} {"text":"<commit_before>\/\/ __BEGIN_LICENSE__\n\/\/ Copyright (C) 2006-2011 United States Government as represented by\n\/\/ the Administrator of the National Aeronautics and Space Administration.\n\/\/ All Rights Reserved.\n\/\/ __END_LICENSE__\n\n\n#ifdef _MSC_VER\n#pragma warning(disable:4244)\n#pragma warning(disable:4267)\n#pragma warning(disable:4996)\n#endif\n\n#include <boost\/program_options.hpp>\n#include <boost\/filesystem\/operations.hpp>\n#include <boost\/filesystem\/path.hpp>\nnamespace po = boost::program_options;\nnamespace fs = boost::filesystem;\n\n#include <vw\/Core\/Debugging.h>\n#include <vw\/Math.h>\n#include <vw\/Image.h>\n#include <vw\/FileIO.h>\n#include <vw\/InterestPoint\/InterestData.h>\n#include <vw\/Stereo\/CorrelationView.h>\n#include <vw\/Stereo\/CostFunctions.h>\n\nusing namespace vw;\nusing namespace vw::stereo;\n\nint main( int argc, char *argv[] ) {\n try {\n\n std::string left_file_name, right_file_name;\n float log;\n int32 h_corr_min, h_corr_max;\n int32 v_corr_min, v_corr_max;\n int32 xkernel, ykernel;\n int lrthresh;\n int correlator_type;\n bool found_alignment = false;\n Matrix3x3 alignment;\n\n po::options_description desc(\"Options\");\n desc.add_options()\n (\"help,h\", \"Display this help message\")\n (\"left\", po::value(&left_file_name), \"Explicitly specify the \\\"left\\\" input file\")\n (\"right\", po::value(&right_file_name), \"Explicitly specify the \\\"right\\\" input file\")\n (\"log\", po::value(&log)->default_value(1.4), \"Apply LOG filter with the given sigma, or 0 to disable\")\n (\"h-corr-min\", po::value(&h_corr_min)->default_value(-30), \"Minimum horizontal disparity\")\n (\"h-corr-max\", po::value(&h_corr_max)->default_value(-30), \"Maximum horizontal disparity\")\n (\"v-corr-min\", po::value(&v_corr_min)->default_value(-5), \"Minimum vertical disparity\")\n (\"v-corr-max\", po::value(&v_corr_max)->default_value(5), \"Maximum vertical disparity\")\n (\"xkernel\", po::value(&xkernel)->default_value(15), \"Horizontal correlation kernel size\")\n (\"ykernel\", po::value(&ykernel)->default_value(15), \"Vertical correlation kernel size\")\n (\"lrthresh\", po::value(&lrthresh)->default_value(2), \"Left\/right correspondence threshold\")\n (\"correlator-type\", po::value(&correlator_type)->default_value(0), \"0 - Abs difference; 1 - Sq Difference; 2 - NormXCorr\")\n (\"affine-subpix\", \"Enable affine adaptive sub-pixel correlation (slower, but more accurate)\")\n (\"pyramid\", \"Use the pyramid based correlator\")\n ;\n po::positional_options_description p;\n p.add(\"left\", 1);\n p.add(\"right\", 1);\n\n po::variables_map vm;\n try {\n po::store( po::command_line_parser( argc, argv ).options(desc).positional(p).run(), vm );\n po::notify( vm );\n } catch (const po::error& e) {\n std::cout << \"An error occured while parsing command line arguments.\\n\";\n std::cout << \"\\t\" << e.what() << \"\\n\\n\";\n std::cout << desc << std::endl;\n return 1;\n }\n\n if( vm.count(\"help\") ) {\n vw_out() << desc << std::endl;\n return 1;\n }\n\n if( vm.count(\"left\") != 1 || vm.count(\"right\") != 1 ) {\n vw_out() << \"Error: Must specify one (and only one) left and right input file!\" << std::endl;\n vw_out() << desc << std::endl;\n return 1;\n }\n\n std::string match_filename = fs::path( left_file_name ).replace_extension().string() + \"__\" + fs::path( right_file_name ).stem() + \".match\";\n if ( fs::exists( match_filename ) ) {\n vw_out() << \"Found a match file. Using it to pre-align images.\\n\";\n std::vector<ip::InterestPoint> matched_ip1, matched_ip2;\n ip::read_binary_match_file( match_filename,\n matched_ip1, matched_ip2 );\n std::vector<Vector3> ransac_ip1 = ip::iplist_to_vectorlist(matched_ip1);\n std::vector<Vector3> ransac_ip2 = ip::iplist_to_vectorlist(matched_ip2);\n vw::math::RandomSampleConsensus<vw::math::HomographyFittingFunctor, vw::math::InterestPointErrorMetric> ransac( vw::math::HomographyFittingFunctor(), vw::math::InterestPointErrorMetric(), 30 );\n alignment = ransac( ransac_ip2, ransac_ip1 );\n\n DiskImageView<PixelGray<float> > right_disk_image( right_file_name );\n right_file_name = \"aligned_right.tif\";\n write_image( right_file_name, transform(right_disk_image, HomographyTransform(alignment)),\n TerminalProgressCallback( \"tools.correlate\", \"Aligning: \") );\n found_alignment = true;\n }\n\n DiskImageView<PixelGray<float> > left_disk_image(left_file_name );\n DiskImageView<PixelGray<float> > right_disk_image(right_file_name );\n int cols = std::min(left_disk_image.cols(),right_disk_image.cols());\n int rows = std::min(left_disk_image.rows(),right_disk_image.rows());\n ImageViewRef<PixelGray<float> > left = edge_extend(left_disk_image,0,0,cols,rows);\n ImageViewRef<PixelGray<float> > right = edge_extend(right_disk_image,0,0,cols,rows);\n\n ImageViewRef<uint8> left_mask = select_channel(edge_mask(pixel_cast_rescale<uint8>(left)),1);\n ImageViewRef<uint8> right_mask = select_channel(edge_mask(pixel_cast_rescale<uint8>(right)),1);\n\n stereo::CostFunctionType corr_type = ABSOLUTE_DIFFERENCE;\n if (correlator_type == 1)\n corr_type = SQUARED_DIFFERENCE;\n else if (correlator_type == 2)\n corr_type = CROSS_CORRELATION;\n\n ImageView<PixelMask<Vector2f> > disparity_map;\n if (vm.count(\"pyramid\")) {\n vw::Timer corr_timer(\"Correlation Time\");\n disparity_map =\n stereo::pyramid_correlate( left, right, left_mask, right_mask,\n stereo::LaplacianOfGaussian(log),\n BBox2i(Vector2i(h_corr_min, v_corr_min),\n Vector2i(h_corr_max, v_corr_max)),\n Vector2i(xkernel, ykernel),\n corr_type, lrthresh );\n } else {\n vw::Timer corr_timer(\"Correlation Time\");\n disparity_map =\n stereo::correlate( left, right,\n stereo::LaplacianOfGaussian(log),\n BBox2i(Vector2i(h_corr_min, v_corr_min),\n Vector2i(h_corr_max, v_corr_max)),\n Vector2i(xkernel, ykernel),\n corr_type, lrthresh );\n }\n\n ImageViewRef<PixelMask<Vector2f> > result = disparity_map;\n if ( found_alignment )\n result = transform_disparities(disparity_map, HomographyTransform(alignment) );\n\n \/\/ Write disparity debug images\n BBox2 disp_range = get_disparity_range(result);\n std::cout << \"Found disparity range: \" << disp_range << \"\\n\";\n ImageViewRef<float32> horizontal = apply_mask(copy_mask(clamp(normalize(select_channel(result,0), disp_range.min().x(), disp_range.max().x(),0,1)),result));\n ImageViewRef<float32> vertical = apply_mask(copy_mask(clamp(normalize(select_channel(result,1), disp_range.min().y(), disp_range.max().y(),0,1)),result));\n\n write_image( \"x_disparity.png\", channel_cast_rescale<uint8>(horizontal) );\n write_image( \"y_disparity.png\", channel_cast_rescale<uint8>(vertical) );\n }\n catch (const vw::Exception& e) {\n std::cerr << \"Error: \" << e.what() << std::endl;\n }\n return 0;\n}\n\n<commit_msg>correlate: Write a better version that is more like my tests<commit_after>\/\/ __BEGIN_LICENSE__\n\/\/ Copyright (C) 2006-2011 United States Government as represented by\n\/\/ the Administrator of the National Aeronautics and Space Administration.\n\/\/ All Rights Reserved.\n\/\/ __END_LICENSE__\n\n\n#ifdef _MSC_VER\n#pragma warning(disable:4244)\n#pragma warning(disable:4267)\n#pragma warning(disable:4996)\n#endif\n\n#include <boost\/program_options.hpp>\n#include <boost\/filesystem\/operations.hpp>\n#include <boost\/filesystem\/path.hpp>\nnamespace po = boost::program_options;\nnamespace fs = boost::filesystem;\n\n#include <vw\/Core\/Debugging.h>\n#include <vw\/Math.h>\n#include <vw\/Image.h>\n#include <vw\/FileIO.h>\n#include <vw\/InterestPoint\/InterestData.h>\n#include <vw\/Stereo\/CorrelationView.h>\n#include <vw\/Stereo\/CostFunctions.h>\n\nusing namespace vw;\nusing namespace vw::stereo;\n\nint main( int argc, char *argv[] ) {\n try {\n\n std::string left_file_name, right_file_name;\n float log;\n int32 h_corr_min, h_corr_max;\n int32 v_corr_min, v_corr_max;\n int32 xkernel, ykernel;\n int lrthresh;\n int correlator_type;\n bool found_alignment = false;\n Matrix3x3 alignment;\n\n po::options_description desc(\"Options\");\n desc.add_options()\n (\"help,h\", \"Display this help message\")\n (\"left\", po::value(&left_file_name), \"Explicitly specify the \\\"left\\\" input file\")\n (\"right\", po::value(&right_file_name), \"Explicitly specify the \\\"right\\\" input file\")\n (\"log\", po::value(&log)->default_value(1.4), \"Apply LOG filter with the given sigma, or 0 to disable\")\n (\"h-corr-min\", po::value(&h_corr_min)->default_value(-30), \"Minimum horizontal disparity\")\n (\"h-corr-max\", po::value(&h_corr_max)->default_value(-30), \"Maximum horizontal disparity\")\n (\"v-corr-min\", po::value(&v_corr_min)->default_value(-5), \"Minimum vertical disparity\")\n (\"v-corr-max\", po::value(&v_corr_max)->default_value(5), \"Maximum vertical disparity\")\n (\"xkernel\", po::value(&xkernel)->default_value(15), \"Horizontal correlation kernel size\")\n (\"ykernel\", po::value(&ykernel)->default_value(15), \"Vertical correlation kernel size\")\n (\"lrthresh\", po::value(&lrthresh)->default_value(2), \"Left\/right correspondence threshold\")\n (\"correlator-type\", po::value(&correlator_type)->default_value(0), \"0 - Abs difference; 1 - Sq Difference; 2 - NormXCorr\")\n (\"affine-subpix\", \"Enable affine adaptive sub-pixel correlation (slower, but more accurate)\")\n (\"pyramid\", \"Use the pyramid based correlator\")\n ;\n po::positional_options_description p;\n p.add(\"left\", 1);\n p.add(\"right\", 1);\n\n po::variables_map vm;\n try {\n po::store( po::command_line_parser( argc, argv ).options(desc).positional(p).run(), vm );\n po::notify( vm );\n } catch (const po::error& e) {\n std::cout << \"An error occured while parsing command line arguments.\\n\";\n std::cout << \"\\t\" << e.what() << \"\\n\\n\";\n std::cout << desc << std::endl;\n return 1;\n }\n\n if( vm.count(\"help\") ) {\n vw_out() << desc << std::endl;\n return 1;\n }\n\n if( vm.count(\"left\") != 1 || vm.count(\"right\") != 1 ) {\n vw_out() << \"Error: Must specify one (and only one) left and right input file!\" << std::endl;\n vw_out() << desc << std::endl;\n return 1;\n }\n\n std::string match_filename = fs::path( left_file_name ).replace_extension().string() + \"__\" + fs::path( right_file_name ).stem() + \".match\";\n if ( fs::exists( match_filename ) ) {\n vw_out() << \"Found a match file. Using it to pre-align images.\\n\";\n std::vector<ip::InterestPoint> matched_ip1, matched_ip2;\n ip::read_binary_match_file( match_filename,\n matched_ip1, matched_ip2 );\n std::vector<Vector3> ransac_ip1 = ip::iplist_to_vectorlist(matched_ip1);\n std::vector<Vector3> ransac_ip2 = ip::iplist_to_vectorlist(matched_ip2);\n vw::math::RandomSampleConsensus<vw::math::HomographyFittingFunctor, vw::math::InterestPointErrorMetric> ransac( vw::math::HomographyFittingFunctor(), vw::math::InterestPointErrorMetric(), 30 );\n alignment = ransac( ransac_ip2, ransac_ip1 );\n\n DiskImageView<PixelGray<float> > right_disk_image( right_file_name );\n right_file_name = \"aligned_right.tif\";\n write_image( right_file_name, transform(right_disk_image, HomographyTransform(alignment)),\n TerminalProgressCallback( \"tools.correlate\", \"Aligning: \") );\n found_alignment = true;\n }\n\n DiskImageView<PixelGray<float> > left_disk_image(left_file_name );\n DiskImageView<PixelGray<float> > right_disk_image(right_file_name );\n int cols = std::min(left_disk_image.cols(),right_disk_image.cols());\n int rows = std::min(left_disk_image.rows(),right_disk_image.rows());\n ImageViewRef<PixelGray<float> > left = edge_extend(left_disk_image,0,0,cols,rows);\n ImageViewRef<PixelGray<float> > right = edge_extend(right_disk_image,0,0,cols,rows);\n\n\n stereo::CostFunctionType corr_type = ABSOLUTE_DIFFERENCE;\n if (correlator_type == 1)\n corr_type = SQUARED_DIFFERENCE;\n else if (correlator_type == 2)\n corr_type = CROSS_CORRELATION;\n\n ImageViewRef<PixelMask<Vector2i> > disparity_map;\n if (vm.count(\"pyramid\")) {\n disparity_map =\n stereo::pyramid_correlate( left, right,\n constant_view( uint8(255), left ),\n constant_view( uint8(255), right ),\n stereo::LaplacianOfGaussian(log),\n BBox2i(Vector2i(h_corr_min, v_corr_min),\n Vector2i(h_corr_max, v_corr_max)),\n Vector2i(xkernel, ykernel),\n corr_type, lrthresh );\n } else {\n disparity_map =\n stereo::correlate( left, right,\n stereo::LaplacianOfGaussian(log),\n BBox2i(Vector2i(h_corr_min, v_corr_min),\n Vector2i(h_corr_max, v_corr_max)),\n Vector2i(xkernel, ykernel),\n corr_type, lrthresh );\n }\n\n ImageViewRef<PixelMask<Vector2f> > result = pixel_cast<PixelMask<Vector2f> >(disparity_map);\n if ( found_alignment )\n result = pixel_cast<PixelMask<Vector2f> >(transform_disparities(disparity_map, HomographyTransform(alignment) ) );\n\n \/\/ Actually invoke the raster\n {\n vw::Timer corr_timer(\"Correlation Time\");\n boost::scoped_ptr<DiskImageResource> r(DiskImageResource::create(\"disparity.tif\",result.format()));\n r->set_block_write_size( Vector2i(1024,1024) );\n block_write_image( *r, result,\n TerminalProgressCallback( \"\", \"Rendering: \") );\n }\n\n \/\/ Write disparity debug images\n DiskImageView<PixelMask<Vector2f> > solution(\"disparity.tif\");\n BBox2 disp_range = get_disparity_range(solution);\n std::cout << \"Found disparity range: \" << disp_range << \"\\n\";\n\n write_image( \"x_disparity.tif\",\n channel_cast<uint8>(apply_mask(copy_mask(clamp(normalize(select_channel(solution,0), disp_range.min().x(), disp_range.max().x(),0,255)),solution))) );\n write_image( \"y_disparity.tif\",\n channel_cast<uint8>(apply_mask(copy_mask(clamp(normalize(select_channel(solution,1), disp_range.min().y(), disp_range.max().y(),0,255)),solution))) );\n }\n catch (const vw::Exception& e) {\n std::cerr << \"Error: \" << e.what() << std::endl;\n }\n return 0;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/*****************************************************************************\r\n* Copyright 2005 Alt-N Technologies, Ltd. \r\n*\r\n* Licensed under the Apache License, Version 2.0 (the \"License\"); \r\n* you may not use this file except in compliance with the License. \r\n* You may obtain a copy of the License at \r\n*\r\n* http:\/\/www.apache.org\/licenses\/LICENSE-2.0 \r\n*\r\n* This code incorporates intellectual property owned by Yahoo! and licensed \r\n* pursuant to the Yahoo! DomainKeys Patent License Agreement.\r\n*\r\n* Unless required by applicable law or agreed to in writing, software \r\n* distributed under the License is distributed on an \"AS IS\" BASIS, \r\n* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. \r\n* See the License for the specific language governing permissions and \r\n* limitations under the License.\r\n*\r\n*****************************************************************************\/\r\n\r\n#ifdef WIN32\r\n#include <windows.h>\r\n#else\r\n#define strnicmp strncasecmp \r\n#endif\r\n\r\n#include <stdio.h>\r\n#include <string.h>\r\n#include <time.h>\r\n#include <stdlib.h>\r\n\r\n#include \"dkim.h\"\r\n#include \"dns.h\"\r\n\r\n\r\n\/\/ change these to your selector name, domain name, etc\r\n#define MYSELECTOR\t\"MDaemon\"\r\n#define MYDOMAIN\t\"bardenhagen.com\"\r\n#define MYIDENTITY\t\"dkimtest@bardenhagen.com\"\r\n\r\n\r\nint DKIM_CALL SignThisHeader(const char* szHeader)\r\n{\r\n\tif( strnicmp( szHeader, \"X-\", 2 ) == 0 )\r\n\t{\r\n\t\treturn 0;\r\n\t}\r\n\r\n\treturn 1;\r\n}\r\n\r\n\r\nint DKIM_CALL SelectorCallback(const char* szFQDN, char* szBuffer, int nBufLen )\r\n{\r\n\treturn 0;\r\n}\r\n\r\nvoid usage()\r\n{\r\n\r\n\tprintf( \"usage: libdkimtest [-b<allman|ietf|both>] [-c<r|s|t|u>] [-d<domain>] [-l] [-h] [-i<you@yourdomain.com>] [-q] [-s] [-t] [-v] [-x<expire time>] [-z<hash>] <msgfile> <privkeyfile> <outfile>\\n\" );\r\n\tprintf( \"-b<standard> allman , ietf or both\\n\" );\r\n\tprintf( \"-c<canonicalization> r for relaxed [DEFAULT], s - simple, t relaxed\/simple, u - simple\/relaxed\\n\" );\r\n\tprintf( \"-d<domain> the domain tag, if not provided it will be determined from the sender\/from header\\n\" );\r\n\tprintf( \"-l include body length tag\\n\" );\r\n\tprintf( \"-h this help\\n\" );\r\n\tprintf( \"-i<identity> the identity, if not provided it will not be included\\n\" );\r\n\tprintf( \"-s sign the message\\n\" );\r\n\tprintf( \"-t include a timestamp tag\\n\" );\r\n\tprintf( \"-v verify the message\\n\" );\r\n\tprintf( \"-x<expire_time> the expire time in seconds since epoch ( DEFAULT = current time + 604800)\\n\\t if set to - then it will not be included\" );\r\n\tprintf( \"-z<hash> 1 for sha1, 2 for sha256, 3 for both\\n\" );\r\n\tprintf( \"-y<selector> the selector tag DEFAULT=MDaemon\\n\" );\r\n}\r\nint main(int argc, char* argv[])\r\n{\r\n\tint n;\r\n\tconst char* PrivKeyFile = \"test.pem\";\r\n\tconst char* MsgFile = \"test.msg\";\r\n\tconst char* OutFile = \"signed.msg\";\r\n\tint nPrivKeyLen;\r\n\tchar PrivKey[2048];\r\n\tchar Buffer[1024];\r\n\tint BufLen;\r\n\tchar szSignature[10024];\r\n\ttime_t t;\r\n\tDKIMContext ctxt;\r\n\tDKIMSignOptions opts = {0};\r\n\r\n\topts.nHash = DKIM_HASH_SHA1_AND_256;\r\n\r\n\ttime(&t);\r\n\r\n\topts.nCanon = DKIM_SIGN_RELAXED;\r\n\topts.nIncludeBodyLengthTag = 0;\r\n\topts.nIncludeQueryMethod = 0;\r\n\topts.nIncludeTimeStamp = 0;\r\n\topts.expireTime = t + 604800;\t\t\/\/ expires in 1 week\r\n\tstrcpy( opts.szSelector, MYSELECTOR );\r\n\tstrcpy( opts.szDomain, MYDOMAIN );\r\n\tstrcpy( opts.szIdentity, MYIDENTITY );\r\n\topts.pfnHeaderCallback = SignThisHeader;\r\n\tstrcpy( opts.szRequiredHeaders, \"NonExistant\" );\r\n\topts.nIncludeCopiedHeaders = 0;\r\n\topts.nIncludeBodyHash = DKIM_BODYHASH_BOTH;\r\n\r\n\tint nArgParseState = 0;\r\n\tbool bSign = true;\r\n\r\n\tif( argc < 2 )\n\t{\r\n\t\tusage();\r\n\t\treturn 1;\r\n\t}\r\n\r\n\tfor( n = 1; n < argc; n++ )\r\n\t{\r\n\t\tif( argv[n][0] == '-' && strlen(argv[n]) > 1 )\r\n\t\t{\r\n\t\t\tswitch( argv[n][1] )\r\n\t\t\t{\r\n\t\t\tcase 'b':\t\t\/\/ allman or ietf draft 1 or both\r\n\t\t\t\topts.nIncludeBodyHash = atoi( &argv[n][2] );\r\n\t\t\t\tbreak;\r\n\r\n\t\t\tcase 'c':\t\t\/\/ canonicalization\r\n\t\t\t\tif( argv[n][2] == 'r' )\r\n\t\t\t\t{\r\n\t\t\t\t\topts.nCanon = DKIM_SIGN_RELAXED;\r\n\t\t\t\t}\r\n\t\t\t\telse if( argv[n][2] == 's' )\r\n\t\t\t\t{\r\n\t\t\t\t\topts.nCanon = DKIM_SIGN_SIMPLE;\r\n\t\t\t\t}\r\n\t\t\t\telse if( argv[n][2] == 't' )\r\n\t\t\t\t{\r\n\t\t\t\t\topts.nCanon = DKIM_SIGN_RELAXED_SIMPLE;\r\n\t\t\t\t}\r\n\t\t\t\telse if( argv[n][2] == 'u' )\r\n\t\t\t\t{\r\n\t\t\t\t\topts.nCanon = DKIM_SIGN_SIMPLE_RELAXED;\r\n\t\t\t\t}\r\n\t\t\t\tbreak;\r\n\r\n\t\t\tcase 'd':\r\n\t\t\t\tstrncpy( opts.szDomain, (const char*) (argv[n] + 2), sizeof(opts.szDomain) - 1 );\r\n\t\t\t\tbreak;\r\n\t\t\tcase 'l':\t\t\/\/ body length tag\r\n\t\t\t\topts.nIncludeBodyLengthTag = 1;\r\n\t\t\t\tbreak;\r\n\r\n\r\n\t\t\tcase 'h':\r\n\t\t\t\tusage();\r\n\t\t\t\treturn 0;\r\n\r\n\t\t\tcase 'i':\t\t\/\/ identity \r\n\t\t\t\tif( argv[n][2] == '-' )\r\n\t\t\t\t{\r\n\t\t\t\t\topts.szIdentity[0] = '\\0';\r\n\t\t\t\t}\r\n\t\t\t\telse\r\n\t\t\t\t{\r\n\t\t\t\t\tstrncpy( opts.szIdentity, argv[n] + 2, sizeof(opts.szIdentity) - 1 );\r\n\t\t\t\t}\r\n\t\t\t\tbreak;\r\n\r\n\t\t\tcase 'q':\t\t\/\/ query method tag\r\n\t\t\t\topts.nIncludeQueryMethod = 1;\r\n\t\t\t\tbreak;\r\n\r\n\t\t\tcase 's':\t\t\/\/ sign\r\n\t\t\t\tbSign = true;\r\n\t\t\t\tbreak;\r\n\r\n\t\t\tcase 't':\t\t\/\/ timestamp tag\r\n\t\t\t\topts.nIncludeTimeStamp = 1;\r\n\t\t\t\tbreak;\r\n\r\n\t\t\tcase 'v':\t\t\/\/ verify\r\n\t\t\t\tbSign = false;\r\n\t\t\t\tbreak;\r\n\r\n\t\t\tcase 'x':\t\t\/\/ expire time \r\n\t\t\t\tif( argv[n][2] == '-' )\r\n\t\t\t\t{\r\n\t\t\t\t\topts.expireTime = 0;\r\n\t\t\t\t}\r\n\t\t\t\telse\r\n\t\t\t\t{\r\n\t\t\t\t\topts.expireTime = t + atoi( argv[n] + 2 );\r\n\t\t\t\t}\r\n\t\t\t\tbreak;\r\n\r\n\t\t\tcase 'y':\r\n\t\t\t\tstrncpy( opts.szSelector, argv[n] + 2, sizeof(opts.szSelector) - 1 );\r\n\t\t\t\tbreak;\r\n\r\n\t\t\tcase 'z':\t\t\/\/ sign w\/ sha1, sha256 or both \r\n\t\t\t\topts.nHash = atoi( &argv[n][2] );\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tswitch( nArgParseState )\r\n\t\t\t{\r\n\t\t\tcase 0:\r\n\t\t\t\tMsgFile = argv[n];\r\n\t\t\t\tbreak;\r\n\t\t\tcase 1:\r\n\t\t\t\tPrivKeyFile = argv[n];\r\n\t\t\t\tbreak;\r\n\t\t\tcase 2:\r\n\t\t\t\tOutFile = argv[n];\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t\tnArgParseState++;\r\n\t\t}\r\n\t}\r\n\r\n\r\n\tif( bSign )\r\n\t{\r\n\t\tFILE* PrivKeyFP = fopen( PrivKeyFile, \"r\" );\r\n\r\n\t\tif ( PrivKeyFP == NULL ) \r\n\t\t{ \r\n\t\t printf( \"dkimlibtest: can't open private key file %s\\n\", PrivKeyFile );\r\n\t\t exit(1);\r\n\t\t}\r\n\t\tnPrivKeyLen = fread( PrivKey, 1, sizeof(PrivKey), PrivKeyFP );\r\n\t\tif (nPrivKeyLen == sizeof(PrivKey)) { \/* TC9 *\/\r\n\t\t printf( \"dkimlibtest: private key buffer isn't big enough, use a smaller private key or recompile.\\n\");\r\n\t\t exit(1);\r\n\t\t}\r\n\t\tPrivKey[nPrivKeyLen] = '\\0';\r\n\t\tfclose(PrivKeyFP);\r\n\r\n\r\n\t\tFILE* MsgFP = fopen( MsgFile, \"rb\" );\r\n\r\n\t\tif ( MsgFP == NULL ) \r\n\t\t{ \r\n\t\t\tprintf( \"dkimlibtest: can't open msg file %s\\n\", MsgFile );\r\n\t\t\texit(1);\r\n\t\t}\r\n\r\n\t\tn = DKIMSignInit( &ctxt, &opts );\r\n\r\n\t\twhile (1) {\r\n\t\t\t\r\n\t\t\tBufLen = fread( Buffer, 1, sizeof(Buffer), MsgFP );\r\n\r\n\t\t\tif( BufLen > 0 )\r\n\t\t\t{\r\n\t\t\t\tDKIMSignProcess( &ctxt, Buffer, BufLen );\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tfclose( MsgFP );\r\n\t\t\r\n\t\t\/\/n = DKIMSignGetSig( &ctxt, PrivKey, szSignature, sizeof(szSignature) );\r\n\r\n\t\tchar* pSig = NULL;\r\n\r\n\t\tn = DKIMSignGetSig2( &ctxt, PrivKey, &pSig );\r\n\r\n\t\tstrcpy( szSignature, pSig );\r\n\r\n\t\tDKIMSignFree( &ctxt );\r\n\r\n\t\tFILE* in = fopen( MsgFile, \"rb\" );\r\n\t\tFILE* out = fopen( OutFile, \"wb+\" );\r\n\r\n\t\tfwrite( szSignature, 1, strlen(szSignature), out );\r\n\t\tfwrite( \"\\r\\n\", 1, 2, out );\r\n\r\n\t\twhile (1) {\r\n\t\t\t\r\n\t\t\tBufLen = fread( Buffer, 1, sizeof(Buffer), in );\r\n\r\n\t\t\tif( BufLen > 0 )\r\n\t\t\t{\r\n\t\t\t\tfwrite( Buffer, 1, BufLen, out );\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tfclose( in );\r\n\t}\r\n\telse\r\n\t{\r\n\t\tFILE* in = fopen( MsgFile, \"rb\" );\r\n\r\n\t\tDKIMVerifyOptions vopts = {0};\r\n\t\tvopts.pfnSelectorCallback = NULL; \/\/SelectorCallback;\r\n\r\n\t\tn = DKIMVerifyInit( &ctxt, &vopts );\r\n\r\n\t\twhile (1) {\r\n\t\t\t\r\n\t\t\tBufLen = fread( Buffer, 1, sizeof(Buffer), in );\r\n\r\n\t\t\tif( BufLen > 0 )\r\n\t\t\t{\r\n\t\t\t\tDKIMVerifyProcess( &ctxt, Buffer, BufLen );\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tn = DKIMVerifyResults( &ctxt );\r\n\r\n\t\tint nSigCount = 0;\r\n\t\tDKIMVerifyDetails* pDetails;\r\n\t\tchar szPolicy[512];\r\n\r\n\t\tn = DKIMVerifyGetDetails(&ctxt, &nSigCount, &pDetails, szPolicy );\r\n\r\n\t\tfor ( int i = 0; i < nSigCount; i++)\r\n\t\t{\r\n\t\t\tprintf( \"Signature #%d: \", i + 1 );\r\n\r\n\t\t\tif( pDetails[i].nResult >= 0 )\r\n\t\t\t\tprintf( \"Success\\n\" );\r\n\t\t\telse\r\n\t\t\t\tprintf( \"Failure\\n\" );\r\n\t\t}\r\n\r\n\t\tDKIMVerifyFree( &ctxt );\r\n\t}\r\n\r\n\treturn 0;\r\n}\r\n<commit_msg>added error code to 'Failure' output<commit_after>\/*****************************************************************************\r\n* Copyright 2005 Alt-N Technologies, Ltd. \r\n*\r\n* Licensed under the Apache License, Version 2.0 (the \"License\"); \r\n* you may not use this file except in compliance with the License. \r\n* You may obtain a copy of the License at \r\n*\r\n* http:\/\/www.apache.org\/licenses\/LICENSE-2.0 \r\n*\r\n* This code incorporates intellectual property owned by Yahoo! and licensed \r\n* pursuant to the Yahoo! DomainKeys Patent License Agreement.\r\n*\r\n* Unless required by applicable law or agreed to in writing, software \r\n* distributed under the License is distributed on an \"AS IS\" BASIS, \r\n* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. \r\n* See the License for the specific language governing permissions and \r\n* limitations under the License.\r\n*\r\n*****************************************************************************\/\r\n\r\n#ifdef WIN32\r\n#include <windows.h>\r\n#else\r\n#define strnicmp strncasecmp \r\n#endif\r\n\r\n#include <stdio.h>\r\n#include <string.h>\r\n#include <time.h>\r\n#include <stdlib.h>\r\n\r\n#include \"dkim.h\"\r\n#include \"dns.h\"\r\n\r\n\r\n\/\/ change these to your selector name, domain name, etc\r\n#define MYSELECTOR\t\"MDaemon\"\r\n#define MYDOMAIN\t\"bardenhagen.com\"\r\n#define MYIDENTITY\t\"dkimtest@bardenhagen.com\"\r\n\r\n\r\nint DKIM_CALL SignThisHeader(const char* szHeader)\r\n{\r\n\tif( strnicmp( szHeader, \"X-\", 2 ) == 0 )\r\n\t{\r\n\t\treturn 0;\r\n\t}\r\n\r\n\treturn 1;\r\n}\r\n\r\n\r\nint DKIM_CALL SelectorCallback(const char* szFQDN, char* szBuffer, int nBufLen )\r\n{\r\n\treturn 0;\r\n}\r\n\r\nvoid usage()\r\n{\r\n\r\n\tprintf( \"usage: libdkimtest [-b<allman|ietf|both>] [-c<r|s|t|u>] [-d<domain>] [-l] [-h] [-i<you@yourdomain.com>] [-q] [-s] [-t] [-v] [-x<expire time>] [-z<hash>] <msgfile> <privkeyfile> <outfile>\\n\" );\r\n\tprintf( \"-b<standard> allman , ietf or both\\n\" );\r\n\tprintf( \"-c<canonicalization> r for relaxed [DEFAULT], s - simple, t relaxed\/simple, u - simple\/relaxed\\n\" );\r\n\tprintf( \"-d<domain> the domain tag, if not provided it will be determined from the sender\/from header\\n\" );\r\n\tprintf( \"-l include body length tag\\n\" );\r\n\tprintf( \"-h this help\\n\" );\r\n\tprintf( \"-i<identity> the identity, if not provided it will not be included\\n\" );\r\n\tprintf( \"-s sign the message\\n\" );\r\n\tprintf( \"-t include a timestamp tag\\n\" );\r\n\tprintf( \"-v verify the message\\n\" );\r\n\tprintf( \"-x<expire_time> the expire time in seconds since epoch ( DEFAULT = current time + 604800)\\n\\t if set to - then it will not be included\" );\r\n\tprintf( \"-z<hash> 1 for sha1, 2 for sha256, 3 for both\\n\" );\r\n\tprintf( \"-y<selector> the selector tag DEFAULT=MDaemon\\n\" );\r\n}\r\nint main(int argc, char* argv[])\r\n{\r\n\tint n;\r\n\tconst char* PrivKeyFile = \"test.pem\";\r\n\tconst char* MsgFile = \"test.msg\";\r\n\tconst char* OutFile = \"signed.msg\";\r\n\tint nPrivKeyLen;\r\n\tchar PrivKey[2048];\r\n\tchar Buffer[1024];\r\n\tint BufLen;\r\n\tchar szSignature[10024];\r\n\ttime_t t;\r\n\tDKIMContext ctxt;\r\n\tDKIMSignOptions opts = {0};\r\n\r\n\topts.nHash = DKIM_HASH_SHA1_AND_256;\r\n\r\n\ttime(&t);\r\n\r\n\topts.nCanon = DKIM_SIGN_RELAXED;\r\n\topts.nIncludeBodyLengthTag = 0;\r\n\topts.nIncludeQueryMethod = 0;\r\n\topts.nIncludeTimeStamp = 0;\r\n\topts.expireTime = t + 604800;\t\t\/\/ expires in 1 week\r\n\tstrcpy( opts.szSelector, MYSELECTOR );\r\n\tstrcpy( opts.szDomain, MYDOMAIN );\r\n\tstrcpy( opts.szIdentity, MYIDENTITY );\r\n\topts.pfnHeaderCallback = SignThisHeader;\r\n\tstrcpy( opts.szRequiredHeaders, \"NonExistant\" );\r\n\topts.nIncludeCopiedHeaders = 0;\r\n\topts.nIncludeBodyHash = DKIM_BODYHASH_BOTH;\r\n\r\n\tint nArgParseState = 0;\r\n\tbool bSign = true;\r\n\r\n\tif( argc < 2 )\n\t{\r\n\t\tusage();\r\n\t\treturn 1;\r\n\t}\r\n\r\n\tfor( n = 1; n < argc; n++ )\r\n\t{\r\n\t\tif( argv[n][0] == '-' && strlen(argv[n]) > 1 )\r\n\t\t{\r\n\t\t\tswitch( argv[n][1] )\r\n\t\t\t{\r\n\t\t\tcase 'b':\t\t\/\/ allman or ietf draft 1 or both\r\n\t\t\t\topts.nIncludeBodyHash = atoi( &argv[n][2] );\r\n\t\t\t\tbreak;\r\n\r\n\t\t\tcase 'c':\t\t\/\/ canonicalization\r\n\t\t\t\tif( argv[n][2] == 'r' )\r\n\t\t\t\t{\r\n\t\t\t\t\topts.nCanon = DKIM_SIGN_RELAXED;\r\n\t\t\t\t}\r\n\t\t\t\telse if( argv[n][2] == 's' )\r\n\t\t\t\t{\r\n\t\t\t\t\topts.nCanon = DKIM_SIGN_SIMPLE;\r\n\t\t\t\t}\r\n\t\t\t\telse if( argv[n][2] == 't' )\r\n\t\t\t\t{\r\n\t\t\t\t\topts.nCanon = DKIM_SIGN_RELAXED_SIMPLE;\r\n\t\t\t\t}\r\n\t\t\t\telse if( argv[n][2] == 'u' )\r\n\t\t\t\t{\r\n\t\t\t\t\topts.nCanon = DKIM_SIGN_SIMPLE_RELAXED;\r\n\t\t\t\t}\r\n\t\t\t\tbreak;\r\n\r\n\t\t\tcase 'd':\r\n\t\t\t\tstrncpy( opts.szDomain, (const char*) (argv[n] + 2), sizeof(opts.szDomain) - 1 );\r\n\t\t\t\tbreak;\r\n\t\t\tcase 'l':\t\t\/\/ body length tag\r\n\t\t\t\topts.nIncludeBodyLengthTag = 1;\r\n\t\t\t\tbreak;\r\n\r\n\r\n\t\t\tcase 'h':\r\n\t\t\t\tusage();\r\n\t\t\t\treturn 0;\r\n\r\n\t\t\tcase 'i':\t\t\/\/ identity \r\n\t\t\t\tif( argv[n][2] == '-' )\r\n\t\t\t\t{\r\n\t\t\t\t\topts.szIdentity[0] = '\\0';\r\n\t\t\t\t}\r\n\t\t\t\telse\r\n\t\t\t\t{\r\n\t\t\t\t\tstrncpy( opts.szIdentity, argv[n] + 2, sizeof(opts.szIdentity) - 1 );\r\n\t\t\t\t}\r\n\t\t\t\tbreak;\r\n\r\n\t\t\tcase 'q':\t\t\/\/ query method tag\r\n\t\t\t\topts.nIncludeQueryMethod = 1;\r\n\t\t\t\tbreak;\r\n\r\n\t\t\tcase 's':\t\t\/\/ sign\r\n\t\t\t\tbSign = true;\r\n\t\t\t\tbreak;\r\n\r\n\t\t\tcase 't':\t\t\/\/ timestamp tag\r\n\t\t\t\topts.nIncludeTimeStamp = 1;\r\n\t\t\t\tbreak;\r\n\r\n\t\t\tcase 'v':\t\t\/\/ verify\r\n\t\t\t\tbSign = false;\r\n\t\t\t\tbreak;\r\n\r\n\t\t\tcase 'x':\t\t\/\/ expire time \r\n\t\t\t\tif( argv[n][2] == '-' )\r\n\t\t\t\t{\r\n\t\t\t\t\topts.expireTime = 0;\r\n\t\t\t\t}\r\n\t\t\t\telse\r\n\t\t\t\t{\r\n\t\t\t\t\topts.expireTime = t + atoi( argv[n] + 2 );\r\n\t\t\t\t}\r\n\t\t\t\tbreak;\r\n\r\n\t\t\tcase 'y':\r\n\t\t\t\tstrncpy( opts.szSelector, argv[n] + 2, sizeof(opts.szSelector) - 1 );\r\n\t\t\t\tbreak;\r\n\r\n\t\t\tcase 'z':\t\t\/\/ sign w\/ sha1, sha256 or both \r\n\t\t\t\topts.nHash = atoi( &argv[n][2] );\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tswitch( nArgParseState )\r\n\t\t\t{\r\n\t\t\tcase 0:\r\n\t\t\t\tMsgFile = argv[n];\r\n\t\t\t\tbreak;\r\n\t\t\tcase 1:\r\n\t\t\t\tPrivKeyFile = argv[n];\r\n\t\t\t\tbreak;\r\n\t\t\tcase 2:\r\n\t\t\t\tOutFile = argv[n];\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t\tnArgParseState++;\r\n\t\t}\r\n\t}\r\n\r\n\r\n\tif( bSign )\r\n\t{\r\n\t\tFILE* PrivKeyFP = fopen( PrivKeyFile, \"r\" );\r\n\r\n\t\tif ( PrivKeyFP == NULL ) \r\n\t\t{ \r\n\t\t printf( \"dkimlibtest: can't open private key file %s\\n\", PrivKeyFile );\r\n\t\t exit(1);\r\n\t\t}\r\n\t\tnPrivKeyLen = fread( PrivKey, 1, sizeof(PrivKey), PrivKeyFP );\r\n\t\tif (nPrivKeyLen == sizeof(PrivKey)) { \/* TC9 *\/\r\n\t\t printf( \"dkimlibtest: private key buffer isn't big enough, use a smaller private key or recompile.\\n\");\r\n\t\t exit(1);\r\n\t\t}\r\n\t\tPrivKey[nPrivKeyLen] = '\\0';\r\n\t\tfclose(PrivKeyFP);\r\n\r\n\r\n\t\tFILE* MsgFP = fopen( MsgFile, \"rb\" );\r\n\r\n\t\tif ( MsgFP == NULL ) \r\n\t\t{ \r\n\t\t\tprintf( \"dkimlibtest: can't open msg file %s\\n\", MsgFile );\r\n\t\t\texit(1);\r\n\t\t}\r\n\r\n\t\tn = DKIMSignInit( &ctxt, &opts );\r\n\r\n\t\twhile (1) {\r\n\t\t\t\r\n\t\t\tBufLen = fread( Buffer, 1, sizeof(Buffer), MsgFP );\r\n\r\n\t\t\tif( BufLen > 0 )\r\n\t\t\t{\r\n\t\t\t\tDKIMSignProcess( &ctxt, Buffer, BufLen );\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tfclose( MsgFP );\r\n\t\t\r\n\t\t\/\/n = DKIMSignGetSig( &ctxt, PrivKey, szSignature, sizeof(szSignature) );\r\n\r\n\t\tchar* pSig = NULL;\r\n\r\n\t\tn = DKIMSignGetSig2( &ctxt, PrivKey, &pSig );\r\n\r\n\t\tstrcpy( szSignature, pSig );\r\n\r\n\t\tDKIMSignFree( &ctxt );\r\n\r\n\t\tFILE* in = fopen( MsgFile, \"rb\" );\r\n\t\tFILE* out = fopen( OutFile, \"wb+\" );\r\n\r\n\t\tfwrite( szSignature, 1, strlen(szSignature), out );\r\n\t\tfwrite( \"\\r\\n\", 1, 2, out );\r\n\r\n\t\twhile (1) {\r\n\t\t\t\r\n\t\t\tBufLen = fread( Buffer, 1, sizeof(Buffer), in );\r\n\r\n\t\t\tif( BufLen > 0 )\r\n\t\t\t{\r\n\t\t\t\tfwrite( Buffer, 1, BufLen, out );\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tfclose( in );\r\n\t}\r\n\telse\r\n\t{\r\n\t\tFILE* in = fopen( MsgFile, \"rb\" );\r\n\r\n\t\tDKIMVerifyOptions vopts = {0};\r\n\t\tvopts.pfnSelectorCallback = NULL; \/\/SelectorCallback;\r\n\r\n\t\tn = DKIMVerifyInit( &ctxt, &vopts );\r\n\r\n\t\twhile (1) {\r\n\t\t\t\r\n\t\t\tBufLen = fread( Buffer, 1, sizeof(Buffer), in );\r\n\r\n\t\t\tif( BufLen > 0 )\r\n\t\t\t{\r\n\t\t\t\tDKIMVerifyProcess( &ctxt, Buffer, BufLen );\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tn = DKIMVerifyResults( &ctxt );\r\n\r\n\t\tint nSigCount = 0;\r\n\t\tDKIMVerifyDetails* pDetails;\r\n\t\tchar szPolicy[512];\r\n\r\n\t\tn = DKIMVerifyGetDetails(&ctxt, &nSigCount, &pDetails, szPolicy );\r\n\r\n\t\tfor ( int i = 0; i < nSigCount; i++)\r\n\t\t{\r\n\t\t\tprintf( \"Signature #%d: \", i + 1 );\r\n\r\n\t\t\tif( pDetails[i].nResult >= 0 )\r\n\t\t\t\tprintf( \"Success\\n\" );\r\n\t\t\telse\r\n\t\t\t\tprintf( \"Failure %i\\n\", pDetails[i].nResult );\r\n\t\t}\r\n\r\n\t\tDKIMVerifyFree( &ctxt );\r\n\t}\r\n\r\n\treturn 0;\r\n}\r\n<|endoftext|>"} {"text":"<commit_before>\/*\n * ArcEmu MMORPG Server\n * Copyright (C) 2005-2007 Ascent Team <http:\/\/www.ascentemu.com\/>\n * Copyright (C) 2008-2012 <http:\/\/www.ArcEmu.org\/>\n *\n * This program is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Affero General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public License\n * along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\n *\/\n\n#include \"Master.h\"\n#include \"Util\\Util.h\"\n\n#ifndef WIN32\n#include <sys\/resource.h>\n#endif\n#include \"System\/CrashHandler.h\"\n\n#ifndef WIN32\nint unix_main(int argc, char** argv)\n{\n\trlimit rl;\n\tif(getrlimit(RLIMIT_CORE, &rl) == -1)\n\t\tprintf(\"getrlimit failed. This could be problem.\\n\");\n\telse\n\t{\n\t\trl.rlim_cur = rl.rlim_max;\n\t\tif(setrlimit(RLIMIT_CORE, &rl) == -1)\n\t\t\tprintf(\"setrlimit failed. Server may not save core.dump files.\\n\");\n\t}\n\n\tMaster master;\n\tif(!master.Run(argc, argv))\n\t\texit(-1);\n\telse\n\t\texit(0);\n\n\treturn 0;\/\/ shouldn't be reached\n}\n\n#else\n\nbool run(int argc, char **argv)\n{\n\tMaster master;\n\tbool retval = master.Run(argc, argv);\n\treturn retval;\n}\n\nint win32_main(int argc, char** argv)\n{\n\tArcemu::Shared::Util::SetThreadName(\"Main Thread\");\n\n\tStartCrashHandler();\n\n\t\/\/Andy: windows only, helps fight heap allocation on allocations lower then 16KB\n\tunsigned long arg = 2;\n\tHeapSetInformation(GetProcessHeap(), HeapCompatibilityInformation, &arg, sizeof(arg));\n\n\tTHREAD_TRY_EXECUTION\n\trun(argc, argv);\n\tTHREAD_HANDLE_CRASH\n\n\texit(0);\n}\n\n#endif\n\nint main(int argc, char** argv)\n{\n#ifdef WIN32\n\twin32_main(argc, argv);\n#else\n\tunix_main(argc, argv);\n#endif\n}\n\n<commit_msg>I accidentally, the slash<commit_after>\/*\n * ArcEmu MMORPG Server\n * Copyright (C) 2005-2007 Ascent Team <http:\/\/www.ascentemu.com\/>\n * Copyright (C) 2008-2012 <http:\/\/www.ArcEmu.org\/>\n *\n * This program is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Affero General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public License\n * along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\n *\/\n\n#include \"Master.h\"\n#include \"Util\/Util.h\"\n\n#ifndef WIN32\n#include <sys\/resource.h>\n#endif\n#include \"System\/CrashHandler.h\"\n\n#ifndef WIN32\nint unix_main(int argc, char** argv)\n{\n\trlimit rl;\n\tif(getrlimit(RLIMIT_CORE, &rl) == -1)\n\t\tprintf(\"getrlimit failed. This could be problem.\\n\");\n\telse\n\t{\n\t\trl.rlim_cur = rl.rlim_max;\n\t\tif(setrlimit(RLIMIT_CORE, &rl) == -1)\n\t\t\tprintf(\"setrlimit failed. Server may not save core.dump files.\\n\");\n\t}\n\n\tMaster master;\n\tif(!master.Run(argc, argv))\n\t\texit(-1);\n\telse\n\t\texit(0);\n\n\treturn 0;\/\/ shouldn't be reached\n}\n\n#else\n\nbool run(int argc, char **argv)\n{\n\tMaster master;\n\tbool retval = master.Run(argc, argv);\n\treturn retval;\n}\n\nint win32_main(int argc, char** argv)\n{\n\tArcemu::Shared::Util::SetThreadName(\"Main Thread\");\n\n\tStartCrashHandler();\n\n\t\/\/Andy: windows only, helps fight heap allocation on allocations lower then 16KB\n\tunsigned long arg = 2;\n\tHeapSetInformation(GetProcessHeap(), HeapCompatibilityInformation, &arg, sizeof(arg));\n\n\tTHREAD_TRY_EXECUTION\n\trun(argc, argv);\n\tTHREAD_HANDLE_CRASH\n\n\texit(0);\n}\n\n#endif\n\nint main(int argc, char** argv)\n{\n#ifdef WIN32\n\twin32_main(argc, argv);\n#else\n\tunix_main(argc, argv);\n#endif\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/**\n * \\file nblock_graph.cc\n *\n *\n *\n * \\author Ethan Burns\n * \\date 2008-10-20\n *\/\n\n#include <assert.h>\n#include <pthread.h>\n#include <errno.h>\n\n#include <limits>\n#include <iostream>\n#include <list>\n#include <map>\n#include <vector>\n\n#include \"..\/closed_list.h\"\n#include \"..\/pq_open_list.h\"\n#include \"..\/open_list.h\"\n#include \"..\/projection.h\"\n#include \"nblock.h\"\n#include \"nblock_graph.h\"\n\nusing namespace std;\nusing namespace WPBNF;\n\n\/**\n * Create the nblock with the given ID.\n *\/\nNBlock *NBlockGraph::create_nblock(unsigned int id)\n{\n\tNBlock *n = new NBlock(project, id);\n\n\tnblocks_created += 1;\n\n\treturn n;\n}\n\n\/**\n * Apparently gdb can't single step inside a c++ constructor... so we\n * just call this function in the constructor so that we can see what\n * is going on.\n *\/\nvoid NBlockGraph::cpp_is_a_bad_language(const Projection *p,\n\t\t\t\t\tState *initial,\n\t\t\t\t\tAtomicInt *b \/* bound *\/,\n\t\t\t\t\tdouble w \/* weight *\/)\n{\n\tunsigned int init_nblock = p->project(initial);\n\n\tnblocks_created = 0;\n\tproject = p;\n\tnum_sigma_zero = num_nblocks = p->get_num_nblocks();\n\tassert(init_nblock < num_nblocks);\n\n\tNBlock *n = map.get(init_nblock);\n\tn->open_fp.add(initial);\n\tn->closed.add(initial);\n\tfree_list.add(n);\n\n\tdone = false;\n\tbound = b;\n\tweight = w;\n\n\tnblocks_assigned = 0;\n\tnblocks_assigned_max = 0;\n}\n\n\/**\n * Create a new NBlock graph.\n * \\param p The projection function.\n *\/\nNBlockGraph::NBlockGraph(const Projection *p,\n\t\t\t State *initial,\n\t\t\t AtomicInt *b \/* bound *\/,\n\t\t\t double w \/* weight *\/)\n\t: map(p)\n{\n\tcpp_is_a_bad_language(p, initial, b, w);\n}\n\n\/**\n * Destroy an NBlock graph.\n *\/\nNBlockGraph::~NBlockGraph()\n{\n}\n\n\n\/**\n * Get the next nblock for expansion, possibly release a finished\n * nblock. The next nblock is the one with the minimum f-value.\n *\n * \\note This call will block if there are currently no free nblocks.\n * \\param finished If non-NULL, the finished nblock will be released\n * into the next level's free_list.\n * \\return The next NBlock to expand or NULL if there is nothing left\n * to do.\n *\/\nNBlock *NBlockGraph::next_nblock(NBlock *finished)\n{\n\tNBlock *n = NULL;\n\n\t\/\/ Take the lock, but if someone else already has it, just\n\t\/\/ keep going.\n\tif (finished && !finished->open_fp.empty()) {\n\t\tif (!mutex.try_lock())\n\t\t\treturn finished;\n\t} else {\n\t\tmutex.lock();\n\t}\n\n\tif (finished) {\t\t\/\/ Release an NBlock\n\t\tassert(finished->sigma == 0);\n\n\t\tnblocks_assigned -= 1;\n\n\t\t\/\/ Possibly add this block back to the free list.\n\t\tfinished->inuse = false;\n\t\tif (is_free(finished)) {\n\t\t\tfree_list.add(finished);\n\t\t\tmutex.cond_signal();\n\t\t}\n\n\t\tupdate_scope_sigmas(finished, -1);\n\t}\n\nretry:\n\n\tif (num_sigma_zero == num_nblocks && free_list.empty()) {\n\t\tset_done();\n\t\tgoto out;\n\t}\n\n\twhile (!done && free_list.empty())\n\t\tmutex.cond_wait();\n\n\tif (done)\n\t\tgoto out;\n\n\tif (free_list.front()->best_value() >= (bound->read() * weight)) {\n\t\tprune_free_list();\n\t\tgoto retry;\n\t}\n\n\tn = free_list.take();\n\tnblocks_assigned += 1;\n\tif (nblocks_assigned > nblocks_assigned_max)\n\t\tnblocks_assigned_max = nblocks_assigned;\n\tn->inuse = true;\n\tupdate_scope_sigmas(n, 1);\n\n\/*\n for (set<NBlock *>::iterator iter = n->interferes.begin();\n iter != n->interferes.end();\n iter++)\n assert((*iter)->sigma > 0);\n*\/\nout:\n\tmutex.unlock();\n\treturn n;\n}\n\n\n\/**\n * Get the best NBlock in the interference scope of b which is not free.\n *\/\nNBlock *NBlockGraph::best_in_scope(NBlock *block)\n{\n\tNBlock *best_b = NULL;\n\tfp_type best_val = fp_infinity;\n\n\tfor (unsigned int i = 0; i < block->ninterferes; i++) {\n\t\tNBlock *b = map.find(block->interferes[i]);\n\t\tif (!b)\n\t\t\tcontinue;\n\t\tif (b->open_fp.empty())\n\t\t\tcontinue;\n\t\tif (!best_b || b->open_fp.get_best_val() < best_val) {\n\t\t\tbest_val = b->open_fp.get_best_val();\n\t\t\tbest_b = b;\n\t\t}\n\t}\n\n\treturn best_b;\n}\n\n\/*\n * Remove all nblocks from the free_list. The nodes in these nblocks\n * will remain in their open lists, for pruning later... if they ever\n * are added back to the free_list. They can be added back to the\n * free_list if a processor searches one of their neighbors and they\n * gain a node worth looking at.\n *\/\nvoid NBlockGraph::prune_free_list(void)\n{\n\tfree_list.reset();\n}\n\n\n\/**\n * Get the NBlock given by the hash value.\n *\/\nNBlock *NBlockGraph::get_nblock(unsigned int hash)\n{\n\treturn map.get(hash);\n}\n\n\/**\n * Get the statistics on the maximum number of NBlocks assigned at one time.\n *\/\nunsigned int NBlockGraph::get_max_assigned_nblocks(void) const\n{\n\n\treturn nblocks_assigned_max;\n}\n\n\/**\n * Get the value of the best nblock on the free list.\n *\/\nfp_type NBlockGraph::best_free_val(void)\n{\n\tNBlock *b = NULL;\n\tb = free_list.front();\n\tif (b)\n\t\treturn b->open_fp.get_best_val();\n\treturn fp_infinity;\n}\n\n\n\/**\n * Print an NBlock, but don't take the lock.\n *\/\nvoid NBlockGraph::__print(ostream &o)\n{\n\n\to << \"Number of NBlocks: \" << num_nblocks << endl;\n\to << \"Number of NBlocks with sigma zero: \" << num_sigma_zero << endl;\n\to << \"All Blocks:\" << endl;\n\tfor (unsigned int i = 0; i < num_nblocks; i += 1)\n\t\tif (map.find(i))\n\t\t\tmap.find(i)->print(o);\n}\n\n\/**\n * Print an NBlockGraph to the given stream.\n *\/\nvoid NBlockGraph::print(ostream &o)\n{\n\tmutex.lock();\n\t__print(o);\n\tmutex.lock();\n}\n\n\/**\n * Update the sigmas by delta for all of the predecessors of y and all\n * of the predecessors of the successors of y.\n *\/\nvoid NBlockGraph::update_scope_sigmas(NBlock *n, int delta)\n{\n\tbool broadcast = false;\n\tassert(n->sigma == 0);\n\n\t\/*\n\t \\A y' \\in predecessors(y) \/\\ y' \/= y,\n\t \\sigma(y') <- \\sigma(y') +- 1\n\n\t \\A y' \\in successors(y),\n\t \\A y'' \\in predecessors(y'), \/\\ y'' \/= y,\n\t \\sigma(y'') <- \\sigma(y'') +- 1\n\t*\/\n\n\tfor (unsigned int i = 0; i < n->ninterferes; i++) {\n\t\tNBlock *m = map.get(n->interferes[i]);\n\t\tif (m->sigma == 0) {\n\t\t\tassert(delta > 0);\n\t\t\tif (is_free(m) && m->fp_pq_index != -1)\n\t\t\t\tfree_list.remove(m->fp_pq_index);\n\t\t\tnum_sigma_zero -= 1;\n\t\t}\n\t\tm->sigma += delta;\n\t\tif (m->sigma == 0) {\n\t\t\tif (m->hot)\n\t\t\t\tbroadcast |= set_cold(m);\n\t\t\tif (is_free(m)) {\n\t\t\t\tfree_list.add(m);\n\t\t\t\tbroadcast = true;\n\t\t\t}\n\t\t\tnum_sigma_zero += 1;\n\t\t}\n\t}\n\n\tif (broadcast)\n\t\tmutex.cond_broadcast();\n}\n\n\/**\n * Sets the done flag.\n *\/\nvoid NBlockGraph::set_done(void)\n{\n\tdone = true;\n\tmutex.cond_broadcast();\n}\n\n\/**\n * Test if an NBlock is free.\n *\/\nbool NBlockGraph::is_free(NBlock *b)\n{\n\treturn !b->inuse\n\t\t&& b->sigma == 0\n\t\t&& b->sigma_hot == 0\n\t\t&& !b->open_fp.empty();\n}\n\n\/**\n * Mark an NBlock as hot, we want this one.\n *\/\nbool NBlockGraph::set_hot(NBlock *b)\n{\n\tfp_type f = b->open_fp.get_best_val();\n\tbool broadcast = false;\n\n\tif (!mutex.try_lock())\n\t\treturn false;\n\n\tif (!b->hot && b->sigma > 0) {\n\t\tfor (unsigned int i = 0; i < b->ninterferes; i++) {\n\t\t\tassert(b->id != b->interferes[i]);\n\t\t\tNBlock *m = map.get(b->interferes[i]);\n\t\t\tif (m->hot && m->open_fp.get_best_val() < f)\n\t\t\t\tgoto out;\n\t\t}\n\n\t\tb->hot = true;\n\t\tfor (unsigned int i = 0; i < b->ninterferes; i++) {\n\t\t\tassert(b->id != b->interferes[i]);\n\t\t\tNBlock *m = map.get(b->interferes[i]);\n\t\t\tif (is_free(m) && m->fp_pq_index != -1)\n\t\t\t\tfree_list.remove(m->fp_pq_index);\n\t\t\tif (m->hot)\n\t\t\t\tbroadcast |= set_cold(m);\n\t\t\tm->sigma_hot += 1;\n\t\t}\n\t}\nout:\n\tif (broadcast)\n\t\tmutex.cond_broadcast();\n\tmutex.unlock();\n\treturn true;\n}\n\n\/**\n * Mark an NBlock as cold. The mutex must be held *before* this\n * function is called.n\n *\/\nbool NBlockGraph::set_cold(NBlock *b)\n{\n\tbool broadcast = false;\n\tb->hot = false;\n\tfor (unsigned int i = 0; i < b->ninterferes; i++) {\n\t\tassert(b->id != b->interferes[i]);\n\t\tNBlock *m = map.get(b->interferes[i]);\n\t\tm->sigma_hot -= 1;\n\t\tif (is_free(m)) {\n\t\t\tfree_list.add(m);\n\t\t\tbroadcast = true;\n\t\t}\n\t}\n\n\treturn broadcast;\n}\n\n\/**\n * We won't release block b, so set all hot blocks in its interference\n * scope back to cold.\n *\/\nvoid NBlockGraph::wont_release(NBlock *b)\n{\n\tbool broadcast = false;\n\n\t\/\/ Don't bother locking if nothing is hot anyway.\n\tif (b->sigma_hot == 0)\n\t\treturn;\n\n\tif (!mutex.try_lock())\n\t\treturn;\n\n\tfor (unsigned int i = 0; i < b->ninterferes; i++) {\n\t\tNBlock *m = map.find(b->interferes[i]);\n\t\tif (!m)\n\t\t\tcontinue;\n\t\tif (m->hot)\n\t\t\tbroadcast |= set_cold(m);\n\t}\n\n\tif (broadcast)\n\t\tmutex.cond_broadcast();\n\n\tmutex.unlock();\n}\n\n\/**\n * Get the number of nblocks which were actually created.\n *\/\nunsigned int NBlockGraph::get_ncreated_nblocks(void)\n{\n\treturn map.get_num_created();;\n}\n<commit_msg>Unlock at the end of the print function instead of locking again.<commit_after>\/**\n * \\file nblock_graph.cc\n *\n *\n *\n * \\author Ethan Burns\n * \\date 2008-10-20\n *\/\n\n#include <assert.h>\n#include <pthread.h>\n#include <errno.h>\n\n#include <limits>\n#include <iostream>\n#include <list>\n#include <map>\n#include <vector>\n\n#include \"..\/closed_list.h\"\n#include \"..\/pq_open_list.h\"\n#include \"..\/open_list.h\"\n#include \"..\/projection.h\"\n#include \"nblock.h\"\n#include \"nblock_graph.h\"\n\nusing namespace std;\nusing namespace WPBNF;\n\n\/**\n * Create the nblock with the given ID.\n *\/\nNBlock *NBlockGraph::create_nblock(unsigned int id)\n{\n\tNBlock *n = new NBlock(project, id);\n\n\tnblocks_created += 1;\n\n\treturn n;\n}\n\n\/**\n * Apparently gdb can't single step inside a c++ constructor... so we\n * just call this function in the constructor so that we can see what\n * is going on.\n *\/\nvoid NBlockGraph::cpp_is_a_bad_language(const Projection *p,\n\t\t\t\t\tState *initial,\n\t\t\t\t\tAtomicInt *b \/* bound *\/,\n\t\t\t\t\tdouble w \/* weight *\/)\n{\n\tunsigned int init_nblock = p->project(initial);\n\n\tnblocks_created = 0;\n\tproject = p;\n\tnum_sigma_zero = num_nblocks = p->get_num_nblocks();\n\tassert(init_nblock < num_nblocks);\n\n\tNBlock *n = map.get(init_nblock);\n\tn->open_fp.add(initial);\n\tn->closed.add(initial);\n\tfree_list.add(n);\n\n\tdone = false;\n\tbound = b;\n\tweight = w;\n\n\tnblocks_assigned = 0;\n\tnblocks_assigned_max = 0;\n}\n\n\/**\n * Create a new NBlock graph.\n * \\param p The projection function.\n *\/\nNBlockGraph::NBlockGraph(const Projection *p,\n\t\t\t State *initial,\n\t\t\t AtomicInt *b \/* bound *\/,\n\t\t\t double w \/* weight *\/)\n\t: map(p)\n{\n\tcpp_is_a_bad_language(p, initial, b, w);\n}\n\n\/**\n * Destroy an NBlock graph.\n *\/\nNBlockGraph::~NBlockGraph()\n{\n}\n\n\n\/**\n * Get the next nblock for expansion, possibly release a finished\n * nblock. The next nblock is the one with the minimum f-value.\n *\n * \\note This call will block if there are currently no free nblocks.\n * \\param finished If non-NULL, the finished nblock will be released\n * into the next level's free_list.\n * \\return The next NBlock to expand or NULL if there is nothing left\n * to do.\n *\/\nNBlock *NBlockGraph::next_nblock(NBlock *finished)\n{\n\tNBlock *n = NULL;\n\n\t\/\/ Take the lock, but if someone else already has it, just\n\t\/\/ keep going.\n\tif (finished && !finished->open_fp.empty()) {\n\t\tif (!mutex.try_lock())\n\t\t\treturn finished;\n\t} else {\n\t\tmutex.lock();\n\t}\n\n\tif (finished) {\t\t\/\/ Release an NBlock\n\t\tassert(finished->sigma == 0);\n\n\t\tnblocks_assigned -= 1;\n\n\t\t\/\/ Possibly add this block back to the free list.\n\t\tfinished->inuse = false;\n\t\tif (is_free(finished)) {\n\t\t\tfree_list.add(finished);\n\t\t\tmutex.cond_signal();\n\t\t}\n\n\t\tupdate_scope_sigmas(finished, -1);\n\t}\n\nretry:\n\n\tif (num_sigma_zero == num_nblocks && free_list.empty()) {\n\t\tset_done();\n\t\tgoto out;\n\t}\n\n\twhile (!done && free_list.empty())\n\t\tmutex.cond_wait();\n\n\tif (done)\n\t\tgoto out;\n\n\tif (free_list.front()->best_value() >= (bound->read() * weight)) {\n\t\tprune_free_list();\n\t\tgoto retry;\n\t}\n\n\tn = free_list.take();\n\tnblocks_assigned += 1;\n\tif (nblocks_assigned > nblocks_assigned_max)\n\t\tnblocks_assigned_max = nblocks_assigned;\n\tn->inuse = true;\n\tupdate_scope_sigmas(n, 1);\n\n\/*\n for (set<NBlock *>::iterator iter = n->interferes.begin();\n iter != n->interferes.end();\n iter++)\n assert((*iter)->sigma > 0);\n*\/\nout:\n\tmutex.unlock();\n\treturn n;\n}\n\n\n\/**\n * Get the best NBlock in the interference scope of b which is not free.\n *\/\nNBlock *NBlockGraph::best_in_scope(NBlock *block)\n{\n\tNBlock *best_b = NULL;\n\tfp_type best_val = fp_infinity;\n\n\tfor (unsigned int i = 0; i < block->ninterferes; i++) {\n\t\tNBlock *b = map.find(block->interferes[i]);\n\t\tif (!b)\n\t\t\tcontinue;\n\t\tif (b->open_fp.empty())\n\t\t\tcontinue;\n\t\tif (!best_b || b->open_fp.get_best_val() < best_val) {\n\t\t\tbest_val = b->open_fp.get_best_val();\n\t\t\tbest_b = b;\n\t\t}\n\t}\n\n\treturn best_b;\n}\n\n\/*\n * Remove all nblocks from the free_list. The nodes in these nblocks\n * will remain in their open lists, for pruning later... if they ever\n * are added back to the free_list. They can be added back to the\n * free_list if a processor searches one of their neighbors and they\n * gain a node worth looking at.\n *\/\nvoid NBlockGraph::prune_free_list(void)\n{\n\tfree_list.reset();\n}\n\n\n\/**\n * Get the NBlock given by the hash value.\n *\/\nNBlock *NBlockGraph::get_nblock(unsigned int hash)\n{\n\treturn map.get(hash);\n}\n\n\/**\n * Get the statistics on the maximum number of NBlocks assigned at one time.\n *\/\nunsigned int NBlockGraph::get_max_assigned_nblocks(void) const\n{\n\n\treturn nblocks_assigned_max;\n}\n\n\/**\n * Get the value of the best nblock on the free list.\n *\/\nfp_type NBlockGraph::best_free_val(void)\n{\n\tNBlock *b = NULL;\n\tb = free_list.front();\n\tif (b)\n\t\treturn b->open_fp.get_best_val();\n\treturn fp_infinity;\n}\n\n\n\/**\n * Print an NBlock, but don't take the lock.\n *\/\nvoid NBlockGraph::__print(ostream &o)\n{\n\n\to << \"Number of NBlocks: \" << num_nblocks << endl;\n\to << \"Number of NBlocks with sigma zero: \" << num_sigma_zero << endl;\n\to << \"All Blocks:\" << endl;\n\tfor (unsigned int i = 0; i < num_nblocks; i += 1)\n\t\tif (map.find(i))\n\t\t\tmap.find(i)->print(o);\n}\n\n\/**\n * Print an NBlockGraph to the given stream.\n *\/\nvoid NBlockGraph::print(ostream &o)\n{\n\tmutex.lock();\n\t__print(o);\n\tmutex.unlock();\n}\n\n\/**\n * Update the sigmas by delta for all of the predecessors of y and all\n * of the predecessors of the successors of y.\n *\/\nvoid NBlockGraph::update_scope_sigmas(NBlock *n, int delta)\n{\n\tbool broadcast = false;\n\tassert(n->sigma == 0);\n\n\t\/*\n\t \\A y' \\in predecessors(y) \/\\ y' \/= y,\n\t \\sigma(y') <- \\sigma(y') +- 1\n\n\t \\A y' \\in successors(y),\n\t \\A y'' \\in predecessors(y'), \/\\ y'' \/= y,\n\t \\sigma(y'') <- \\sigma(y'') +- 1\n\t*\/\n\n\tfor (unsigned int i = 0; i < n->ninterferes; i++) {\n\t\tNBlock *m = map.get(n->interferes[i]);\n\t\tif (m->sigma == 0) {\n\t\t\tassert(delta > 0);\n\t\t\tif (is_free(m) && m->fp_pq_index != -1)\n\t\t\t\tfree_list.remove(m->fp_pq_index);\n\t\t\tnum_sigma_zero -= 1;\n\t\t}\n\t\tm->sigma += delta;\n\t\tif (m->sigma == 0) {\n\t\t\tif (m->hot)\n\t\t\t\tbroadcast |= set_cold(m);\n\t\t\tif (is_free(m)) {\n\t\t\t\tfree_list.add(m);\n\t\t\t\tbroadcast = true;\n\t\t\t}\n\t\t\tnum_sigma_zero += 1;\n\t\t}\n\t}\n\n\tif (broadcast)\n\t\tmutex.cond_broadcast();\n}\n\n\/**\n * Sets the done flag.\n *\/\nvoid NBlockGraph::set_done(void)\n{\n\tdone = true;\n\tmutex.cond_broadcast();\n}\n\n\/**\n * Test if an NBlock is free.\n *\/\nbool NBlockGraph::is_free(NBlock *b)\n{\n\treturn !b->inuse\n\t\t&& b->sigma == 0\n\t\t&& b->sigma_hot == 0\n\t\t&& !b->open_fp.empty();\n}\n\n\/**\n * Mark an NBlock as hot, we want this one.\n *\/\nbool NBlockGraph::set_hot(NBlock *b)\n{\n\tfp_type f = b->open_fp.get_best_val();\n\tbool broadcast = false;\n\n\tif (!mutex.try_lock())\n\t\treturn false;\n\n\tif (!b->hot && b->sigma > 0) {\n\t\tfor (unsigned int i = 0; i < b->ninterferes; i++) {\n\t\t\tassert(b->id != b->interferes[i]);\n\t\t\tNBlock *m = map.get(b->interferes[i]);\n\t\t\tif (m->hot && m->open_fp.get_best_val() < f)\n\t\t\t\tgoto out;\n\t\t}\n\n\t\tb->hot = true;\n\t\tfor (unsigned int i = 0; i < b->ninterferes; i++) {\n\t\t\tassert(b->id != b->interferes[i]);\n\t\t\tNBlock *m = map.get(b->interferes[i]);\n\t\t\tif (is_free(m) && m->fp_pq_index != -1)\n\t\t\t\tfree_list.remove(m->fp_pq_index);\n\t\t\tif (m->hot)\n\t\t\t\tbroadcast |= set_cold(m);\n\t\t\tm->sigma_hot += 1;\n\t\t}\n\t}\nout:\n\tif (broadcast)\n\t\tmutex.cond_broadcast();\n\tmutex.unlock();\n\treturn true;\n}\n\n\/**\n * Mark an NBlock as cold. The mutex must be held *before* this\n * function is called.n\n *\/\nbool NBlockGraph::set_cold(NBlock *b)\n{\n\tbool broadcast = false;\n\tb->hot = false;\n\tfor (unsigned int i = 0; i < b->ninterferes; i++) {\n\t\tassert(b->id != b->interferes[i]);\n\t\tNBlock *m = map.get(b->interferes[i]);\n\t\tm->sigma_hot -= 1;\n\t\tif (is_free(m)) {\n\t\t\tfree_list.add(m);\n\t\t\tbroadcast = true;\n\t\t}\n\t}\n\n\treturn broadcast;\n}\n\n\/**\n * We won't release block b, so set all hot blocks in its interference\n * scope back to cold.\n *\/\nvoid NBlockGraph::wont_release(NBlock *b)\n{\n\tbool broadcast = false;\n\n\t\/\/ Don't bother locking if nothing is hot anyway.\n\tif (b->sigma_hot == 0)\n\t\treturn;\n\n\tif (!mutex.try_lock())\n\t\treturn;\n\n\tfor (unsigned int i = 0; i < b->ninterferes; i++) {\n\t\tNBlock *m = map.find(b->interferes[i]);\n\t\tif (!m)\n\t\t\tcontinue;\n\t\tif (m->hot)\n\t\t\tbroadcast |= set_cold(m);\n\t}\n\n\tif (broadcast)\n\t\tmutex.cond_broadcast();\n\n\tmutex.unlock();\n}\n\n\/**\n * Get the number of nblocks which were actually created.\n *\/\nunsigned int NBlockGraph::get_ncreated_nblocks(void)\n{\n\treturn map.get_num_created();;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2010 Gregory Szorc\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n\/\/ this file contains cross-platform APIs\n\/\/ if this gets too large, we should consider using a framework, like APR\n\n#ifndef ZIPPYLOG_PLATFORM_HPP_\n#define ZIPPYLOG_PLATFORM_HPP_\n\n#include <zippylog\/zippylog.h>\n\n#include <string>\n#include <vector>\n\nusing ::std::string;\nusing ::std::vector;\n\nnamespace zippylog {\n\n\/\/ TODO move these to platform namespace\nstruct dir_entry {\n string name;\n uint64 size;\n char type;\n};\n\n\/\/ TODO define a type for function pointer so compiler can save us\nZIPPYLOG_EXPORT void * create_thread(void * func, void *data);\n\nZIPPYLOG_EXPORT bool join_thread(void *thread);\n\nZIPPYLOG_EXPORT bool terminate_thread(void *thread);\n\nZIPPYLOG_EXPORT bool directory_entries(const string dir, vector<dir_entry> &v);\n\nZIPPYLOG_EXPORT void windows_error(char *buffer, size_t buffer_size);\n\nnamespace platform {\n enum FileType {\n REGULAR = 1,\n DIRECTORY = 2,\n PIPE = 3,\n CHARACTER = 4,\n UNKNOWN = 5,\n };\n\n typedef struct FileStat {\n FileType type;\n int64 size;\n } FileStat;\n\n ZIPPYLOG_EXPORT bool stat(const string path, FileStat &st);\n\n typedef struct Time {\n int32 year;\n int32 mon;\n int32 mday;\n int32 hour;\n int32 min;\n int32 sec;\n int32 usec;\n int32 wday;\n int32 yday;\n int32 isdst;\n int64 epoch_micro;\n int32 epoch_sec;\n } Time;\n\n ZIPPYLOG_EXPORT bool TimeNow(Time &t);\n\n \/\/ converts number of microseconds since UNIX epoch into a zippylog Time struct\n ZIPPYLOG_EXPORT bool UnixMicroTimeToZippyTime(int64 from, Time &to);\n\n ZIPPYLOG_EXPORT bool MakeDirectory(const string path);\n\n ZIPPYLOG_EXPORT bool PathIsDirectory(const string path);\n\n typedef struct UUID {\n unsigned char data[16];\n } UUID;\n\n \/\/ creates a new UUID\n \/\/ UUID type is not defined yet\n bool CreateUUID(UUID &u);\n\n typedef struct File {\n#ifdef WINDOWS\n void * handle;\n#endif\n int fd;\n } File;\n\n enum FileFlags {\n READ = 1,\n WRITE = 2,\n APPEND = 3,\n CREATE = 4,\n TRUNCATE = 5,\n BINARY = 6,\n };\n\n bool OpenFile(File &f, const string path, int flags);\n\n \/\/ in the ideal world, timers would be represented as file descriptors and\n \/\/ we could include them in the zmq poll() event loop. this is easily done\n \/\/ on Linux. unfortunately, Windows requires a little bit more effort.\n \/\/ TODO expose timers as file descriptors someday\n class ZIPPYLOG_EXPORT Timer {\n public:\n \/\/ create a null timer. this does nothing and is present so some structs have\n \/\/ a default constructor\n Timer();\n\n \/\/ create a new timer that fires N microseconds from now\n Timer(uint32 microseconds);\n\n \/\/ whether the timer has signaled yet\n bool Signaled();\n\n \/\/ reset the timer\n \/\/ this will unarm the timer and prepare it to be executed again\n \/\/ this is called automatically by Start() if restarting an existing timer\n \/\/ it is more of an internal API but exposed in case it is needed\n bool Reset();\n\n \/\/ starts the timer\n bool Start();\n\n protected:\n uint32 microseconds;\n bool signaled;\n bool running;\n\n#ifdef WINDOWS\n void * handle;\n#endif\n };\n}\n\n} \/\/ namespace\n\n#endif<commit_msg>note history of file<commit_after>\/\/ Copyright 2010 Gregory Szorc\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n\/\/ this file contains cross-platform APIs\n\/\/ in the ideal world, we would use an existing library, like APR. In the early\n\/\/ days of this project, it was decided to keep the code as free from external\n\/\/ dependencies as possible. As this namespace becomes larger and larger, we\n\/\/ have to start questioning that decision.\n\n#ifndef ZIPPYLOG_PLATFORM_HPP_\n#define ZIPPYLOG_PLATFORM_HPP_\n\n#include <zippylog\/zippylog.h>\n\n#include <string>\n#include <vector>\n\nusing ::std::string;\nusing ::std::vector;\n\nnamespace zippylog {\n\n\/\/ TODO move these to platform namespace\nstruct dir_entry {\n string name;\n uint64 size;\n char type;\n};\n\n\/\/ TODO define a type for function pointer so compiler can save us\nZIPPYLOG_EXPORT void * create_thread(void * func, void *data);\n\nZIPPYLOG_EXPORT bool join_thread(void *thread);\n\nZIPPYLOG_EXPORT bool terminate_thread(void *thread);\n\nZIPPYLOG_EXPORT bool directory_entries(const string dir, vector<dir_entry> &v);\n\nZIPPYLOG_EXPORT void windows_error(char *buffer, size_t buffer_size);\n\nnamespace platform {\n enum FileType {\n REGULAR = 1,\n DIRECTORY = 2,\n PIPE = 3,\n CHARACTER = 4,\n UNKNOWN = 5,\n };\n\n typedef struct FileStat {\n FileType type;\n int64 size;\n } FileStat;\n\n ZIPPYLOG_EXPORT bool stat(const string path, FileStat &st);\n\n typedef struct Time {\n int32 year;\n int32 mon;\n int32 mday;\n int32 hour;\n int32 min;\n int32 sec;\n int32 usec;\n int32 wday;\n int32 yday;\n int32 isdst;\n int64 epoch_micro;\n int32 epoch_sec;\n } Time;\n\n ZIPPYLOG_EXPORT bool TimeNow(Time &t);\n\n \/\/ converts number of microseconds since UNIX epoch into a zippylog Time struct\n ZIPPYLOG_EXPORT bool UnixMicroTimeToZippyTime(int64 from, Time &to);\n\n ZIPPYLOG_EXPORT bool MakeDirectory(const string path);\n\n ZIPPYLOG_EXPORT bool PathIsDirectory(const string path);\n\n typedef struct UUID {\n unsigned char data[16];\n } UUID;\n\n \/\/ creates a new UUID\n \/\/ UUID type is not defined yet\n bool CreateUUID(UUID &u);\n\n typedef struct File {\n#ifdef WINDOWS\n void * handle;\n#endif\n int fd;\n } File;\n\n enum FileFlags {\n READ = 1,\n WRITE = 2,\n APPEND = 3,\n CREATE = 4,\n TRUNCATE = 5,\n BINARY = 6,\n };\n\n bool OpenFile(File &f, const string path, int flags);\n\n \/\/ in the ideal world, timers would be represented as file descriptors and\n \/\/ we could include them in the zmq poll() event loop. this is easily done\n \/\/ on Linux. unfortunately, Windows requires a little bit more effort.\n \/\/ TODO expose timers as file descriptors someday\n class ZIPPYLOG_EXPORT Timer {\n public:\n \/\/ create a null timer. this does nothing and is present so some structs have\n \/\/ a default constructor\n Timer();\n\n \/\/ create a new timer that fires N microseconds from now\n Timer(uint32 microseconds);\n\n \/\/ whether the timer has signaled yet\n bool Signaled();\n\n \/\/ reset the timer\n \/\/ this will unarm the timer and prepare it to be executed again\n \/\/ this is called automatically by Start() if restarting an existing timer\n \/\/ it is more of an internal API but exposed in case it is needed\n bool Reset();\n\n \/\/ starts the timer\n bool Start();\n\n protected:\n uint32 microseconds;\n bool signaled;\n bool running;\n\n#ifdef WINDOWS\n void * handle;\n#endif\n };\n}\n\n} \/\/ namespace\n\n#endif<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2010 Gregory Szorc\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include <zippylog\/streamer.hpp>\n#include <zippylog\/protocol\/request.pb.h>\n#include <zippylog\/protocol\/response.pb.h>\n#include <zippylog\/zippylogd.pb.h>\n#include <zippylog\/zeromq.hpp>\n\nusing ::zippylog::protocol::response::SubscribeAck;\nusing ::zippylog::zippylogd::StreamerStartup;\nusing ::zippylog::zippylogd::StreamerShutdown;\nusing ::zippylog::zippylogd::StreamerSubscriptionExpired;\nusing ::zippylog::zippylogd::StreamerReceiveKeepalive;\nusing ::zippylog::zippylogd::StreamerRejectKeepaliveUnknownSubscription;\nusing ::zippylog::zippylogd::StreamerSubscriptionRenewedFromKeepalive;\nusing ::zippylog::zippylogd::StreamerErrorRenewingSubscription;\nusing ::zmq::message_t;\n\n#define LOG_MESSAGE(msgvar, socketvar) { \\\n msgvar.set_id(this->id); \\\n Envelope logenvelope = Envelope(); \\\n msgvar.add_to_envelope(&logenvelope); \\\n zeromq::send_envelope(socketvar, logenvelope); \\\n}\n\nnamespace zippylog {\nnamespace server {\n\nStoreChangeSubscription::StoreChangeSubscription()\n{\n\n}\n\nSubscriptionInfo::SubscriptionInfo()\n{\n}\n\nSubscriptionInfo::SubscriptionInfo(uint32 expiration_ttl)\n{\n this->expiration_timer = Timer(expiration_ttl * 1000000);\n if (!this->expiration_timer.Start()) {\n throw \"could not start expiration timer\";\n }\n}\n\nStreamer::Streamer(Store *store,\n context_t *zctx,\n const string store_changes_endpoint,\n const string client_endpoint,\n const string subscriptions_endpoint,\n const string subscription_updates_endpoint,\n const string logging_endpoint,\n uint32 subscription_ttl)\n{\n this->store = store;\n this->zctx = zctx;\n this->store_changes_endpoint = store_changes_endpoint;\n this->client_endpoint = client_endpoint;\n this->subscriptions_endpoint = subscriptions_endpoint;\n this->subscription_updates_endpoint = subscription_updates_endpoint;\n this->logging_endpoint = logging_endpoint;\n this->subscription_ttl = subscription_ttl;\n\n this->changes_sock = NULL;\n this->client_sock = NULL;\n this->subscriptions_sock = NULL;\n this->subscription_updates_sock = NULL;\n this->logging_sock = NULL;\n\n platform::UUID uuid;\n if (!platform::CreateUUID(uuid)) {\n throw \"could not create UUID\";\n }\n\n this->id = string((const char *)&uuid, sizeof(uuid));\n}\n\nStreamer::~Streamer()\n{\n if (this->changes_sock) delete this->changes_sock;\n if (this->client_sock) delete this->client_sock;\n if (this->subscriptions_sock) delete this->subscriptions_sock;\n if (this->subscription_updates_sock) delete this->subscription_updates_sock;\n if (this->logging_sock) delete this->logging_sock;\n}\n\nvoid Streamer::SetShutdownSemaphore(bool *active)\n{\n if (!active) throw \"pointer must not be NULL\";\n\n if (!*active) throw \"boolean being pointed to must be true\";\n\n this->active = active;\n}\n\nvoid Streamer::Run()\n{\n this->logging_sock = new socket_t(*this->zctx, ZMQ_PUSH);\n this->logging_sock->connect(this->logging_endpoint.c_str());\n\n {\n StreamerStartup log = StreamerStartup();\n LOG_MESSAGE(log, this->logging_sock);\n }\n\n \/\/ subscribe to store change notifications\n this->changes_sock = new socket_t(*this->zctx, ZMQ_SUB);\n this->changes_sock->setsockopt(ZMQ_SUBSCRIBE, NULL, 0);\n this->changes_sock->connect(this->store_changes_endpoint.c_str());\n\n \/\/ establish sending socket\n this->client_sock = new socket_t(*this->zctx, ZMQ_PUSH);\n this->client_sock->connect(this->client_endpoint.c_str());\n\n \/\/ receive client subscriptions\n this->subscriptions_sock = new socket_t(*this->zctx, ZMQ_PULL);\n this->subscriptions_sock->connect(this->subscriptions_endpoint.c_str());\n\n \/\/ receive client updates\n this->subscription_updates_sock = new socket_t(*this->zctx, ZMQ_SUB);\n this->subscription_updates_sock->connect(this->subscription_updates_endpoint.c_str());\n this->subscription_updates_sock->setsockopt(ZMQ_SUBSCRIBE, \"\", 0);\n\n zmq::pollitem_t pollitems[3];\n pollitems[0].events = ZMQ_POLLIN;\n pollitems[0].socket = *this->changes_sock;\n pollitems[0].fd = 0;\n pollitems[0].revents = 0;\n\n pollitems[1].events = ZMQ_POLLIN;\n pollitems[1].socket = *this->subscriptions_sock;\n pollitems[1].fd = 0;\n pollitems[1].revents = 0;\n\n pollitems[2].events = ZMQ_POLLIN;\n pollitems[2].socket = *this->subscription_updates_sock;\n pollitems[2].fd = 0;\n pollitems[2].revents = 0;\n\n while (*this->active) {\n zmq::message_t msg;\n\n \/\/ wait for a message to process\n int rc = zmq::poll(&pollitems[0], 3, 250000);\n\n \/\/ process subscription updates first\n if (pollitems[2].revents & ZMQ_POLLIN) {\n if (!this->subscription_updates_sock->recv(&msg, 0)) {\n throw \"weird\";\n }\n\n Envelope e = Envelope(&msg);\n assert(e.number_messages() == 1);\n assert(e.message_namespace(0) == 1);\n\n uint32 type = e.message_type(0);\n\n if (type == protocol::request::SubscribeKeepalive::zippylog_enumeration) {\n protocol::request::SubscribeKeepalive *m =\n (protocol::request::SubscribeKeepalive *)e.get_message(0);\n\n string id = m->id();\n delete m;\n\n StreamerReceiveKeepalive log = StreamerReceiveKeepalive();\n log.set_subscription(id);\n LOG_MESSAGE(log, this->logging_sock);\n\n if (this->HasSubscription(id)) {\n if (this->RenewSubscription(id)) {\n StreamerSubscriptionRenewedFromKeepalive log = StreamerSubscriptionRenewedFromKeepalive();\n log.set_subscription(id);\n LOG_MESSAGE(log, this->logging_sock);\n }\n else {\n StreamerErrorRenewingSubscription log = StreamerErrorRenewingSubscription();\n log.set_subscription(id);\n LOG_MESSAGE(log, this->logging_sock);\n }\n }\n else {\n StreamerRejectKeepaliveUnknownSubscription log = StreamerRejectKeepaliveUnknownSubscription();\n log.set_subscription(id);\n LOG_MESSAGE(log, this->logging_sock);\n }\n }\n }\n\n \/\/ unsubscribe any expired subscribers\n map<string, SubscriptionInfo>::iterator iter = this->subscriptions.begin();\n for (; iter != this->subscriptions.end(); iter++) {\n if (iter->second.expiration_timer.Signaled()) {\n StreamerSubscriptionExpired log = StreamerSubscriptionExpired();\n log.set_subscription(iter->first);\n LOG_MESSAGE(log, this->logging_sock);\n this->subscriptions.erase(iter);\n break;\n }\n }\n\n \/\/ process new subscriptions\n if (pollitems[1].revents & ZMQ_POLLIN) {\n vector<string> identities;\n vector<message_t *> msgs;\n\n if (!zeromq::receive_multipart_message(this->subscriptions_sock, identities, msgs)) {\n \/\/ TODO log error here\n continue;\n }\n\n assert(msgs.size() > 0);\n\n Envelope e = Envelope(msgs[0]);\n assert(e.number_messages() == 1);\n assert(e.message_namespace(0) == 1);\n assert(e.message_type(0) == protocol::request::SubscribeStoreChanges::zippylog_enumeration);\n\n protocol::request::SubscribeStoreChanges *m = (protocol::request::SubscribeStoreChanges *)e.get_message(0);\n\n StoreChangeSubscription subscription;\n\n for (int i = 0; i < m->path_size(); i++) {\n subscription.paths.push_back(m->path(i));\n }\n\n delete m;\n\n subscription.socket_identifiers = identities;\n\n \/\/ TODO create subscription identity properly\n platform::UUID uuid;\n if (!platform::CreateUUID(uuid)) {\n throw \"could not create UUID\";\n }\n subscription.id = string((const char *)&uuid, sizeof(uuid));\n\n this->store_change_subscriptions.push_back(subscription);\n\n SubscriptionInfo info = SubscriptionInfo(this->subscription_ttl);\n\n this->subscriptions[subscription.id] = info;\n\n \/\/ send ACK response to client\n SubscribeAck ack = SubscribeAck();\n ack.set_id(subscription.id);\n ack.set_ttl(this->subscription_ttl \/ 1000);\n Envelope response = Envelope();\n\n \/\/ copy tags to response because that's what the protocol does\n for (size_t i = 0; i < e.envelope.tag_size(); i++) {\n response.envelope.add_tag(e.envelope.tag(i));\n }\n\n ack.add_to_envelope(&response);\n\n if (!zeromq::send_envelope(this->client_sock, identities, response)) {\n \/\/ TODO log error here\n assert(0);\n }\n\n for (vector<message_t *>::iterator msg = msgs.begin(); msg != msgs.end(); msg++) {\n delete *msg;\n }\n msgs.clear();\n\n }\n\n \/\/ process store changes and send to subscribers\n if (pollitems[0].revents & ZMQ_POLLIN) {\n this->changes_sock->recv(&msg, 0);\n\n \/\/ if we don't have any subscriptions, do nothing\n if (!this->store_change_subscriptions.size()) {\n continue;\n }\n\n Envelope e = Envelope(&msg);\n\n assert(e.number_messages());\n \/\/ TODO magic constant\n assert(e.message_namespace(0) == 1);\n\n uint32 message_type = e.message_type(0);\n switch (message_type) {\n case protocol::StoreChangeBucketAdded::zippylog_enumeration:\n case protocol::StoreChangeBucketDeleted::zippylog_enumeration:\n case protocol::StoreChangeStreamSetAdded::zippylog_enumeration:\n case protocol::StoreChangeStreamSetDeleted::zippylog_enumeration:\n case protocol::StoreChangeStreamAppended::zippylog_enumeration:\n case protocol::StoreChangeStreamAdded::zippylog_enumeration:\n case protocol::StoreChangeStreamDeleted::zippylog_enumeration:\n \/\/ if no subscriptions to store changes, do nothing\n if (!this->store_change_subscriptions.size()) break;\n\n this->ProcessStoreChangeEnvelope(e);\n break;\n default:\n \/\/ WTF mate?\n break;\n }\n }\n }\n\n StreamerShutdown log = StreamerShutdown();\n LOG_MESSAGE(log, this->logging_sock);\n}\n\nvoid Streamer::ProcessStoreChangeEnvelope(Envelope &e)\n{\n \/\/ we obtain the full path and build a path from it\n \/\/ we then compare path prefixes of subscribers to see who gets it\n string bucket, stream_set, stream;\n\n switch (e.message_type(0)) {\n case protocol::StoreChangeBucketAdded::zippylog_enumeration:\n {\n protocol::StoreChangeBucketAdded *m = (protocol::StoreChangeBucketAdded *)e.get_message(0);\n bucket = m->bucket();\n delete m;\n }\n break;\n\n case protocol::StoreChangeBucketDeleted::zippylog_enumeration:\n {\n protocol::StoreChangeBucketDeleted *m = (protocol::StoreChangeBucketDeleted *)e.get_message(0);\n bucket = m->bucket();\n delete m;\n }\n break;\n\n case protocol::StoreChangeStreamSetAdded::zippylog_enumeration:\n {\n protocol::StoreChangeStreamSetAdded *m = (protocol::StoreChangeStreamSetAdded *)e.get_message(0);\n bucket = m->bucket();\n stream_set = m->stream_set();\n delete m;\n }\n break;\n\n case protocol::StoreChangeStreamSetDeleted::zippylog_enumeration:\n {\n protocol::StoreChangeStreamSetDeleted *m = (protocol::StoreChangeStreamSetDeleted *)e.get_message(0);\n bucket = m->bucket();\n stream_set = m->stream_set();\n delete m;\n }\n break;\n\n case protocol::StoreChangeStreamAppended::zippylog_enumeration:\n {\n protocol::StoreChangeStreamAppended *m = (protocol::StoreChangeStreamAppended *)e.get_message(0);\n bucket = m->bucket();\n stream_set = m->stream_set();\n stream = m->stream();\n delete m;\n }\n break;\n\n case protocol::StoreChangeStreamAdded::zippylog_enumeration:\n {\n protocol::StoreChangeStreamAdded *m = (protocol::StoreChangeStreamAdded *)e.get_message(0);\n bucket = m->bucket();\n stream_set = m->stream_set();\n stream = m->stream();\n delete m;\n }\n break;\n\n case protocol::StoreChangeStreamDeleted::zippylog_enumeration:\n {\n protocol::StoreChangeStreamDeleted *m = (protocol::StoreChangeStreamDeleted *)e.get_message(0);\n bucket = m->bucket();\n stream_set = m->stream_set();\n stream = m->stream();\n delete m;\n }\n break;\n }\n\n string path;\n if (!stream.empty()) {\n path = Store::StreamPath(bucket, stream_set, stream);\n }\n else if (!stream_set.empty()) {\n path = Store::StreamsetPath(bucket, stream_set);\n }\n else {\n path = Store::BucketPath(bucket);\n }\n\n \/\/ iterate over subscribers\n vector<StoreChangeSubscription>::iterator i;\n for (i = this->store_change_subscriptions.begin(); i != this->store_change_subscriptions.end(); i++) {\n\n \/\/ iterate over paths they are subscribed to\n vector<string>::iterator prefix;\n for (prefix = i->paths.begin(); prefix != i->paths.end(); i++) {\n \/\/ no way that will match\n if (prefix->length() > path.length()) continue;\n\n \/\/ if the subscribed prefix doesn't match the changed prefix\n if (path.substr(0, prefix->length()).compare(*prefix)) continue;\n\n \/\/ at this point, they must be subscribed, so we send them the event\n\n Envelope response = Envelope();\n protocol::response::SubscriptionStart start = protocol::response::SubscriptionStart();\n start.set_id(i->id);\n start.add_to_envelope(&response);\n\n if (!e.CopyMessage(0, response)) {\n throw \"could not copy message to response envelope. weird\";\n }\n\n zeromq::send_envelope(this->client_sock, i->socket_identifiers, response);\n\n \/\/ don't process this path any more for this subscriber\n break;\n }\n }\n}\n\nbool Streamer::HasSubscription(const string &id)\n{\n map<string, SubscriptionInfo>::iterator iter = this->subscriptions.find(id);\n\n return iter != this->subscriptions.end();\n}\n\nbool Streamer::RenewSubscription(const string &id)\n{\n map<string, SubscriptionInfo>::iterator iter = this->subscriptions.find(id);\n\n if (iter == this->subscriptions.end()) {\n return false;\n }\n\n return iter->second.expiration_timer.Start();\n}\n\n}} \/\/ namespaces\n<commit_msg>proper unit conversion<commit_after>\/\/ Copyright 2010 Gregory Szorc\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include <zippylog\/streamer.hpp>\n#include <zippylog\/protocol\/request.pb.h>\n#include <zippylog\/protocol\/response.pb.h>\n#include <zippylog\/zippylogd.pb.h>\n#include <zippylog\/zeromq.hpp>\n\nusing ::zippylog::protocol::response::SubscribeAck;\nusing ::zippylog::zippylogd::StreamerStartup;\nusing ::zippylog::zippylogd::StreamerShutdown;\nusing ::zippylog::zippylogd::StreamerSubscriptionExpired;\nusing ::zippylog::zippylogd::StreamerReceiveKeepalive;\nusing ::zippylog::zippylogd::StreamerRejectKeepaliveUnknownSubscription;\nusing ::zippylog::zippylogd::StreamerSubscriptionRenewedFromKeepalive;\nusing ::zippylog::zippylogd::StreamerErrorRenewingSubscription;\nusing ::zmq::message_t;\n\n#define LOG_MESSAGE(msgvar, socketvar) { \\\n msgvar.set_id(this->id); \\\n Envelope logenvelope = Envelope(); \\\n msgvar.add_to_envelope(&logenvelope); \\\n zeromq::send_envelope(socketvar, logenvelope); \\\n}\n\nnamespace zippylog {\nnamespace server {\n\nStoreChangeSubscription::StoreChangeSubscription()\n{\n\n}\n\nSubscriptionInfo::SubscriptionInfo()\n{\n}\n\nSubscriptionInfo::SubscriptionInfo(uint32 expiration_ttl)\n{\n \/\/ milliseconds to microseconds\n this->expiration_timer = Timer(expiration_ttl * 1000);\n if (!this->expiration_timer.Start()) {\n throw \"could not start expiration timer\";\n }\n}\n\nStreamer::Streamer(Store *store,\n context_t *zctx,\n const string store_changes_endpoint,\n const string client_endpoint,\n const string subscriptions_endpoint,\n const string subscription_updates_endpoint,\n const string logging_endpoint,\n uint32 subscription_ttl)\n{\n this->store = store;\n this->zctx = zctx;\n this->store_changes_endpoint = store_changes_endpoint;\n this->client_endpoint = client_endpoint;\n this->subscriptions_endpoint = subscriptions_endpoint;\n this->subscription_updates_endpoint = subscription_updates_endpoint;\n this->logging_endpoint = logging_endpoint;\n this->subscription_ttl = subscription_ttl;\n\n this->changes_sock = NULL;\n this->client_sock = NULL;\n this->subscriptions_sock = NULL;\n this->subscription_updates_sock = NULL;\n this->logging_sock = NULL;\n\n platform::UUID uuid;\n if (!platform::CreateUUID(uuid)) {\n throw \"could not create UUID\";\n }\n\n this->id = string((const char *)&uuid, sizeof(uuid));\n}\n\nStreamer::~Streamer()\n{\n if (this->changes_sock) delete this->changes_sock;\n if (this->client_sock) delete this->client_sock;\n if (this->subscriptions_sock) delete this->subscriptions_sock;\n if (this->subscription_updates_sock) delete this->subscription_updates_sock;\n if (this->logging_sock) delete this->logging_sock;\n}\n\nvoid Streamer::SetShutdownSemaphore(bool *active)\n{\n if (!active) throw \"pointer must not be NULL\";\n\n if (!*active) throw \"boolean being pointed to must be true\";\n\n this->active = active;\n}\n\nvoid Streamer::Run()\n{\n this->logging_sock = new socket_t(*this->zctx, ZMQ_PUSH);\n this->logging_sock->connect(this->logging_endpoint.c_str());\n\n {\n StreamerStartup log = StreamerStartup();\n LOG_MESSAGE(log, this->logging_sock);\n }\n\n \/\/ subscribe to store change notifications\n this->changes_sock = new socket_t(*this->zctx, ZMQ_SUB);\n this->changes_sock->setsockopt(ZMQ_SUBSCRIBE, NULL, 0);\n this->changes_sock->connect(this->store_changes_endpoint.c_str());\n\n \/\/ establish sending socket\n this->client_sock = new socket_t(*this->zctx, ZMQ_PUSH);\n this->client_sock->connect(this->client_endpoint.c_str());\n\n \/\/ receive client subscriptions\n this->subscriptions_sock = new socket_t(*this->zctx, ZMQ_PULL);\n this->subscriptions_sock->connect(this->subscriptions_endpoint.c_str());\n\n \/\/ receive client updates\n this->subscription_updates_sock = new socket_t(*this->zctx, ZMQ_SUB);\n this->subscription_updates_sock->connect(this->subscription_updates_endpoint.c_str());\n this->subscription_updates_sock->setsockopt(ZMQ_SUBSCRIBE, \"\", 0);\n\n zmq::pollitem_t pollitems[3];\n pollitems[0].events = ZMQ_POLLIN;\n pollitems[0].socket = *this->changes_sock;\n pollitems[0].fd = 0;\n pollitems[0].revents = 0;\n\n pollitems[1].events = ZMQ_POLLIN;\n pollitems[1].socket = *this->subscriptions_sock;\n pollitems[1].fd = 0;\n pollitems[1].revents = 0;\n\n pollitems[2].events = ZMQ_POLLIN;\n pollitems[2].socket = *this->subscription_updates_sock;\n pollitems[2].fd = 0;\n pollitems[2].revents = 0;\n\n while (*this->active) {\n zmq::message_t msg;\n\n \/\/ wait for a message to process\n int rc = zmq::poll(&pollitems[0], 3, 250000);\n\n \/\/ process subscription updates first\n if (pollitems[2].revents & ZMQ_POLLIN) {\n if (!this->subscription_updates_sock->recv(&msg, 0)) {\n throw \"weird\";\n }\n\n Envelope e = Envelope(&msg);\n assert(e.number_messages() == 1);\n assert(e.message_namespace(0) == 1);\n\n uint32 type = e.message_type(0);\n\n if (type == protocol::request::SubscribeKeepalive::zippylog_enumeration) {\n protocol::request::SubscribeKeepalive *m =\n (protocol::request::SubscribeKeepalive *)e.get_message(0);\n\n string id = m->id();\n delete m;\n\n StreamerReceiveKeepalive log = StreamerReceiveKeepalive();\n log.set_subscription(id);\n LOG_MESSAGE(log, this->logging_sock);\n\n if (this->HasSubscription(id)) {\n if (this->RenewSubscription(id)) {\n StreamerSubscriptionRenewedFromKeepalive log = StreamerSubscriptionRenewedFromKeepalive();\n log.set_subscription(id);\n LOG_MESSAGE(log, this->logging_sock);\n }\n else {\n StreamerErrorRenewingSubscription log = StreamerErrorRenewingSubscription();\n log.set_subscription(id);\n LOG_MESSAGE(log, this->logging_sock);\n }\n }\n else {\n StreamerRejectKeepaliveUnknownSubscription log = StreamerRejectKeepaliveUnknownSubscription();\n log.set_subscription(id);\n LOG_MESSAGE(log, this->logging_sock);\n }\n }\n }\n\n \/\/ unsubscribe any expired subscribers\n map<string, SubscriptionInfo>::iterator iter = this->subscriptions.begin();\n for (; iter != this->subscriptions.end(); iter++) {\n if (iter->second.expiration_timer.Signaled()) {\n StreamerSubscriptionExpired log = StreamerSubscriptionExpired();\n log.set_subscription(iter->first);\n LOG_MESSAGE(log, this->logging_sock);\n this->subscriptions.erase(iter);\n break;\n }\n }\n\n \/\/ process new subscriptions\n if (pollitems[1].revents & ZMQ_POLLIN) {\n vector<string> identities;\n vector<message_t *> msgs;\n\n if (!zeromq::receive_multipart_message(this->subscriptions_sock, identities, msgs)) {\n \/\/ TODO log error here\n continue;\n }\n\n assert(msgs.size() > 0);\n\n Envelope e = Envelope(msgs[0]);\n assert(e.number_messages() == 1);\n assert(e.message_namespace(0) == 1);\n assert(e.message_type(0) == protocol::request::SubscribeStoreChanges::zippylog_enumeration);\n\n protocol::request::SubscribeStoreChanges *m = (protocol::request::SubscribeStoreChanges *)e.get_message(0);\n\n StoreChangeSubscription subscription;\n\n for (int i = 0; i < m->path_size(); i++) {\n subscription.paths.push_back(m->path(i));\n }\n\n delete m;\n\n subscription.socket_identifiers = identities;\n\n \/\/ TODO create subscription identity properly\n platform::UUID uuid;\n if (!platform::CreateUUID(uuid)) {\n throw \"could not create UUID\";\n }\n subscription.id = string((const char *)&uuid, sizeof(uuid));\n\n this->store_change_subscriptions.push_back(subscription);\n\n SubscriptionInfo info = SubscriptionInfo(this->subscription_ttl);\n\n this->subscriptions[subscription.id] = info;\n\n \/\/ send ACK response to client\n SubscribeAck ack = SubscribeAck();\n ack.set_id(subscription.id);\n ack.set_ttl(this->subscription_ttl \/ 1000);\n Envelope response = Envelope();\n\n \/\/ copy tags to response because that's what the protocol does\n for (size_t i = 0; i < e.envelope.tag_size(); i++) {\n response.envelope.add_tag(e.envelope.tag(i));\n }\n\n ack.add_to_envelope(&response);\n\n if (!zeromq::send_envelope(this->client_sock, identities, response)) {\n \/\/ TODO log error here\n assert(0);\n }\n\n for (vector<message_t *>::iterator msg = msgs.begin(); msg != msgs.end(); msg++) {\n delete *msg;\n }\n msgs.clear();\n\n }\n\n \/\/ process store changes and send to subscribers\n if (pollitems[0].revents & ZMQ_POLLIN) {\n this->changes_sock->recv(&msg, 0);\n\n \/\/ if we don't have any subscriptions, do nothing\n if (!this->store_change_subscriptions.size()) {\n continue;\n }\n\n Envelope e = Envelope(&msg);\n\n assert(e.number_messages());\n \/\/ TODO magic constant\n assert(e.message_namespace(0) == 1);\n\n uint32 message_type = e.message_type(0);\n switch (message_type) {\n case protocol::StoreChangeBucketAdded::zippylog_enumeration:\n case protocol::StoreChangeBucketDeleted::zippylog_enumeration:\n case protocol::StoreChangeStreamSetAdded::zippylog_enumeration:\n case protocol::StoreChangeStreamSetDeleted::zippylog_enumeration:\n case protocol::StoreChangeStreamAppended::zippylog_enumeration:\n case protocol::StoreChangeStreamAdded::zippylog_enumeration:\n case protocol::StoreChangeStreamDeleted::zippylog_enumeration:\n \/\/ if no subscriptions to store changes, do nothing\n if (!this->store_change_subscriptions.size()) break;\n\n this->ProcessStoreChangeEnvelope(e);\n break;\n default:\n \/\/ WTF mate?\n break;\n }\n }\n }\n\n StreamerShutdown log = StreamerShutdown();\n LOG_MESSAGE(log, this->logging_sock);\n}\n\nvoid Streamer::ProcessStoreChangeEnvelope(Envelope &e)\n{\n \/\/ we obtain the full path and build a path from it\n \/\/ we then compare path prefixes of subscribers to see who gets it\n string bucket, stream_set, stream;\n\n switch (e.message_type(0)) {\n case protocol::StoreChangeBucketAdded::zippylog_enumeration:\n {\n protocol::StoreChangeBucketAdded *m = (protocol::StoreChangeBucketAdded *)e.get_message(0);\n bucket = m->bucket();\n delete m;\n }\n break;\n\n case protocol::StoreChangeBucketDeleted::zippylog_enumeration:\n {\n protocol::StoreChangeBucketDeleted *m = (protocol::StoreChangeBucketDeleted *)e.get_message(0);\n bucket = m->bucket();\n delete m;\n }\n break;\n\n case protocol::StoreChangeStreamSetAdded::zippylog_enumeration:\n {\n protocol::StoreChangeStreamSetAdded *m = (protocol::StoreChangeStreamSetAdded *)e.get_message(0);\n bucket = m->bucket();\n stream_set = m->stream_set();\n delete m;\n }\n break;\n\n case protocol::StoreChangeStreamSetDeleted::zippylog_enumeration:\n {\n protocol::StoreChangeStreamSetDeleted *m = (protocol::StoreChangeStreamSetDeleted *)e.get_message(0);\n bucket = m->bucket();\n stream_set = m->stream_set();\n delete m;\n }\n break;\n\n case protocol::StoreChangeStreamAppended::zippylog_enumeration:\n {\n protocol::StoreChangeStreamAppended *m = (protocol::StoreChangeStreamAppended *)e.get_message(0);\n bucket = m->bucket();\n stream_set = m->stream_set();\n stream = m->stream();\n delete m;\n }\n break;\n\n case protocol::StoreChangeStreamAdded::zippylog_enumeration:\n {\n protocol::StoreChangeStreamAdded *m = (protocol::StoreChangeStreamAdded *)e.get_message(0);\n bucket = m->bucket();\n stream_set = m->stream_set();\n stream = m->stream();\n delete m;\n }\n break;\n\n case protocol::StoreChangeStreamDeleted::zippylog_enumeration:\n {\n protocol::StoreChangeStreamDeleted *m = (protocol::StoreChangeStreamDeleted *)e.get_message(0);\n bucket = m->bucket();\n stream_set = m->stream_set();\n stream = m->stream();\n delete m;\n }\n break;\n }\n\n string path;\n if (!stream.empty()) {\n path = Store::StreamPath(bucket, stream_set, stream);\n }\n else if (!stream_set.empty()) {\n path = Store::StreamsetPath(bucket, stream_set);\n }\n else {\n path = Store::BucketPath(bucket);\n }\n\n \/\/ iterate over subscribers\n vector<StoreChangeSubscription>::iterator i;\n for (i = this->store_change_subscriptions.begin(); i != this->store_change_subscriptions.end(); i++) {\n\n \/\/ iterate over paths they are subscribed to\n vector<string>::iterator prefix;\n for (prefix = i->paths.begin(); prefix != i->paths.end(); i++) {\n \/\/ no way that will match\n if (prefix->length() > path.length()) continue;\n\n \/\/ if the subscribed prefix doesn't match the changed prefix\n if (path.substr(0, prefix->length()).compare(*prefix)) continue;\n\n \/\/ at this point, they must be subscribed, so we send them the event\n\n Envelope response = Envelope();\n protocol::response::SubscriptionStart start = protocol::response::SubscriptionStart();\n start.set_id(i->id);\n start.add_to_envelope(&response);\n\n if (!e.CopyMessage(0, response)) {\n throw \"could not copy message to response envelope. weird\";\n }\n\n zeromq::send_envelope(this->client_sock, i->socket_identifiers, response);\n\n \/\/ don't process this path any more for this subscriber\n break;\n }\n }\n}\n\nbool Streamer::HasSubscription(const string &id)\n{\n map<string, SubscriptionInfo>::iterator iter = this->subscriptions.find(id);\n\n return iter != this->subscriptions.end();\n}\n\nbool Streamer::RenewSubscription(const string &id)\n{\n map<string, SubscriptionInfo>::iterator iter = this->subscriptions.find(id);\n\n if (iter == this->subscriptions.end()) {\n return false;\n }\n\n return iter->second.expiration_timer.Start();\n}\n\n}} \/\/ namespaces\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: componentfactory.cxx,v $\n *\n * $Revision: 1.5 $\n *\n * last change: $Author: rt $ $Date: 2005-09-08 02:54:42 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef _COMPHELPER_COMPONENTFACTORY_HXX\n#include <comphelper\/componentfactory.hxx>\n#endif\n#ifndef _COMPHELPER_PROCESSFACTORY_HXX_\n#include <comphelper\/processfactory.hxx>\n#endif\n\n#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_\n#include <com\/sun\/star\/lang\/XMultiServiceFactory.hpp>\n#endif\n\n#ifndef _COM_SUN_STAR_REGISTRY_XREGISTRYKEY_HDL_\n#include <com\/sun\/star\/registry\/XRegistryKey.hpp>\n#endif\n\n#ifndef _CPPUHELPER_SHLIB_HXX_\n#include <cppuhelper\/shlib.hxx>\n#endif\n\n\n#ifndef GCC\n#pragma hdrstop\n#endif\n\n\nusing namespace ::com::sun::star;\nusing namespace ::com::sun::star::uno;\nusing namespace ::com::sun::star::lang;\nusing namespace ::com::sun::star::registry;\nusing namespace ::rtl;\n\n\nnamespace comphelper\n{\n\nReference< XInterface > getComponentInstance(\n const OUString & rLibraryName,\n const OUString & rImplementationName\n )\n{\n Reference< XInterface > xI;\n Reference< XMultiServiceFactory > xMSF = ::comphelper::getProcessServiceFactory();\n if ( xMSF.is() )\n xI = xMSF->createInstance( rImplementationName );\n if( !xI.is() )\n {\n Reference< XSingleServiceFactory > xSSF =\n loadLibComponentFactory( rLibraryName, rImplementationName,\n Reference< XMultiServiceFactory >(), Reference< XRegistryKey >() );\n if (xSSF.is())\n xI = xSSF->createInstance();\n }\n return xI;\n}\n\n\nReference< XSingleServiceFactory > loadLibComponentFactory(\n const OUString & rLibName,\n const OUString & rImplName,\n const Reference< XMultiServiceFactory > & xSF,\n const Reference< XRegistryKey > & xKey\n )\n{\n return Reference< XSingleServiceFactory >( ::cppu::loadSharedLibComponentFactory(\n rLibName, OUString(), rImplName, xSF, xKey ), UNO_QUERY );\n}\n\n} \/\/ namespace comphelper\n<commit_msg>INTEGRATION: CWS pchfix02 (1.5.100); FILE MERGED 2006\/09\/01 17:19:45 kaib 1.5.100.1: #i68856# Added header markers and pch files<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: componentfactory.cxx,v $\n *\n * $Revision: 1.6 $\n *\n * last change: $Author: obo $ $Date: 2006-09-17 17:15:55 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_comphelper.hxx\"\n\n#ifndef _COMPHELPER_COMPONENTFACTORY_HXX\n#include <comphelper\/componentfactory.hxx>\n#endif\n#ifndef _COMPHELPER_PROCESSFACTORY_HXX_\n#include <comphelper\/processfactory.hxx>\n#endif\n\n#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_\n#include <com\/sun\/star\/lang\/XMultiServiceFactory.hpp>\n#endif\n\n#ifndef _COM_SUN_STAR_REGISTRY_XREGISTRYKEY_HDL_\n#include <com\/sun\/star\/registry\/XRegistryKey.hpp>\n#endif\n\n#ifndef _CPPUHELPER_SHLIB_HXX_\n#include <cppuhelper\/shlib.hxx>\n#endif\n\n\n#ifndef GCC\n#endif\n\n\nusing namespace ::com::sun::star;\nusing namespace ::com::sun::star::uno;\nusing namespace ::com::sun::star::lang;\nusing namespace ::com::sun::star::registry;\nusing namespace ::rtl;\n\n\nnamespace comphelper\n{\n\nReference< XInterface > getComponentInstance(\n const OUString & rLibraryName,\n const OUString & rImplementationName\n )\n{\n Reference< XInterface > xI;\n Reference< XMultiServiceFactory > xMSF = ::comphelper::getProcessServiceFactory();\n if ( xMSF.is() )\n xI = xMSF->createInstance( rImplementationName );\n if( !xI.is() )\n {\n Reference< XSingleServiceFactory > xSSF =\n loadLibComponentFactory( rLibraryName, rImplementationName,\n Reference< XMultiServiceFactory >(), Reference< XRegistryKey >() );\n if (xSSF.is())\n xI = xSSF->createInstance();\n }\n return xI;\n}\n\n\nReference< XSingleServiceFactory > loadLibComponentFactory(\n const OUString & rLibName,\n const OUString & rImplName,\n const Reference< XMultiServiceFactory > & xSF,\n const Reference< XRegistryKey > & xKey\n )\n{\n return Reference< XSingleServiceFactory >( ::cppu::loadSharedLibComponentFactory(\n rLibName, OUString(), rImplName, xSF, xKey ), UNO_QUERY );\n}\n\n} \/\/ namespace comphelper\n<|endoftext|>"} {"text":"<commit_before><commit_msg>Fixed a potential buffer overrun when falling back from sendfile to normal read\/write<commit_after><|endoftext|>"} {"text":"<commit_before>#include <sstream>\n#include \"slice.hpp\"\n\nnamespace Vole {\n\n using std::stringstream;\n\n template <typename T>\n template <typename Allocator>\n Slice<T>::Slice(Allocator& a, size_t l, size_t c)\n : mem(a.template alloc<T>(c)),\n beg(mem),\n len(l),\n cap(c)\n { }\n\n template <typename T>\n T& Slice<T>::operator[](size_t i) {\n if (!(i < len)) {\n \/\/ TODO: use an error class with more metadata\n throw \"slice index out of bounds\";\n }\n return beg[i];\n }\n\n template <typename T>\n Slice<T> Slice<T>::slice(size_t lower, size_t upper) {\n if (upper > len || lower > upper) {\n \/\/ TODO: use an error class with more metadata\n throw \"invalid range for slice\";\n }\n return { mem, beg + lower, upper - lower, cap - lower };\n }\n\n template <typename T>\n T& Slice<T>::first() {\n return (*this)[0];\n }\n\n template <typename T>\n T& Slice<T>::last() {\n return (*this)[len-1];\n }\n\n template <typename T>\n Slice<T> Slice<T>::take(size_t n) {\n return slice(0, n);\n }\n\n template <typename T>\n Slice<T> Slice<T>::drop(size_t n) {\n return slice(n, len);\n }\n\n template <typename T>\n Slice<T>::operator string() {\n stringstream ss;\n ss << '(';\n for (size_t i = 0; i < len; ++i) {\n ss << (i ? \" \" : \"\") << beg[i];\n }\n ss << ')';\n return ss.str();\n }\n}<commit_msg>constructor error<commit_after>#include <iostream>\n#include <sstream>\n#include \"slice.hpp\"\n\nnamespace Vole {\n\n using std::stringstream;\n\n template <typename T>\n template <typename Allocator>\n Slice<T>::Slice(Allocator& a, size_t l, size_t c)\n : mem(a.template alloc<T>(c)),\n beg(mem),\n len(l),\n cap(c)\n { }\n\n template <typename T>\n T& Slice<T>::operator[](size_t i) {\n if (!(i < len)) {\n \/\/ TODO: use an error class with more metadata\n throw \"slice index out of bounds\";\n }\n return beg[i];\n }\n\n template <typename T>\n Slice<T> Slice<T>::slice(size_t lower, size_t upper) {\n if (upper > len || lower > upper) {\n \/\/ TODO: use an error class with more metadata\n throw \"invalid range for slice\";\n }\n return { mem, beg + lower, upper - lower, cap - lower };\n }\n\n template <typename T>\n T& Slice<T>::first() {\n return (*this)[0];\n }\n\n template <typename T>\n T& Slice<T>::last() {\n return (*this)[len-1];\n }\n\n template <typename T>\n Slice<T> Slice<T>::take(size_t n) {\n return slice(0, n);\n }\n\n template <typename T>\n Slice<T> Slice<T>::drop(size_t n) {\n return slice(n, len);\n }\n\n template <typename T>\n Slice<T>::operator string() {\n stringstream ss;\n ss << '(';\n for (size_t i = 0; i < len; ++i) {\n ss << (i ? \" \" : \"\") << beg[i];\n }\n ss << ')';\n return ss.str();\n }\n\n template <typename T, typename Allocator>\n Slice<T> append(Allocator& alloc, Slice<T> s, T t) {\n if (s.len < s.cap) {\n s[s.len] = t;\n Slice<T> newslice ( s.mem, s.beg, s.len+1, s.cap );\n return newslice;\n } else {\n auto newslice { alloc, s.len+1, s.cap*2 };\n for (int i = 0; i < s.len; i++) {\n newslice[i] = s[i];\n }\n newslice[s.len] = t;\n return newslice;\n }\n }\n\n\n template <typename T, typename Allocator>\n Slice<T> append(Allocator& alloc, Slice<T> s1, Slice<T> s2) {\n if (s1.len+s2.len < s1.cap) {\n for (int i = 0; i < s2.len; i++) {\n s1[s1.len+i] = s2[i];\n }\n return { s1.mem, s1.beg, s1.len+s2.len, s1.cap };\n } else {\n auto newslice { alloc, s1.len+s2.len, (s1.cap+s2.len)*2 };\n for (int i = 0; i < s1.len; i++) {\n newslice[i] = s1[i];\n }\n for (int i = 0; i < s2.len; i++) {\n newslice[s1.len+i] = s2[i];\n }\n return newslice;\n }\n }\n\n}\n\nusing namespace std;\nusing namespace Vole;\n\nclass New {\npublic:\n template<typename T>\n T* alloc(size_t size) {\n cout << \"Allocating \" << size << \" things!\" << endl;\n return new T[size];\n }\n};\n\nint main() {\n auto my_new = New();\n auto myslice = Slice<int>(my_new, 10, 10);\n cout << \"myslice: \" << string(myslice) << endl;\n auto myslice2 = append(my_new, myslice, 1);\n \/\/ cout << \"myslice: \" << string(myslice2) << endl;\n \/\/ auto myslice3 = append(my_new, myslice, 2);\n \/\/ cout << \"myslice: \" << string(myslice3) << endl;\n \/\/ auto myslice4 = Slice<int>(my_new, 10, 10);\n \/\/ auto myslice5 = append(my_new, myslice2, 7);\n \/\/ auto myslice6 = append(my_new, myslice2, 8);\n \/\/ auto myslice7 = append(my_new, myslice2, 9);\n \/\/ cout << \"myslice2: \" << string(myslice7) << endl;\n\n \/\/ auto myslice8 = append(my_new, myslice, myslice2);\n \/\/ cout << \"myslice: \" << string(myslice8) << endl;\n\n\n return 0;\n}<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ libavg - Media Playback Engine. \n\/\/ Copyright (C) 2003-2006 Ulrich von Zadow\n\/\/\n\/\/ This library is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU Lesser General Public\n\/\/ License as published by the Free Software Foundation; either\n\/\/ version 2 of the License, or (at your option) any later version.\n\/\/\n\/\/ This library is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ Lesser General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License along with this library; if not, write to the Free Software\n\/\/ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n\/\/\n\/\/ Current versions can be found at www.libavg.de\n\n#include \"TrackerThread.h\"\n#include \"FilterDistortion.h\"\n\n#include \"..\/base\/Logger.h\"\n#include \"..\/base\/ProfilingZone.h\"\n#include \"..\/base\/ScopeTimer.h\"\n\n#include \"..\/graphics\/Filter.h\"\n#include \"..\/graphics\/Filterfill.h\"\n#include \"..\/graphics\/FilterHighpass.h\"\n#include \"..\/graphics\/FilterFastBandpass.h\"\n#include \"..\/graphics\/FilterBlur.h\"\n#include \"..\/graphics\/FilterGauss.h\"\n\n#include <iostream>\n#include <stdlib.h>\n\nusing namespace std;\n\nnamespace avg {\nstatic ProfilingZone ProfilingZoneCapture (\"Capture\");\nstatic ProfilingZone ProfilingZoneTracker (\"Tracker\");\nstatic ProfilingZone ProfilingZoneHistory (\"History\");\nstatic ProfilingZone ProfilingZoneDistort (\"Distort\");\nstatic ProfilingZone ProfilingZoneHistogram (\"Histogram\");\nstatic ProfilingZone ProfilingZoneBandpass (\"Bandpass\");\nstatic ProfilingZone ProfilingZoneComps(\"ConnectedComps\");\nstatic ProfilingZone ProfilingZoneUpdate(\"Update\");\nstatic ProfilingZone ProfilingZoneDraw(\"Draw\");\n\nTrackerThread::TrackerThread(IntRect ROI, \n CameraPtr pCamera,\n BitmapPtr ppBitmaps[NUM_TRACKER_IMAGES],\n MutexPtr pMutex,\n CmdQueue& CmdQ,\n IBlobTarget *target,\n bool bSubtractHistory,\n TrackerConfig &config)\n : WorkerThread<TrackerThread>(\"Tracker\", CmdQ),\n m_TouchThreshold(0),\n m_TrackThreshold(0),\n m_pMutex(pMutex),\n m_pCamera(pCamera),\n m_pTarget(target),\n m_bCreateDebugImages(false),\n m_bCreateFingerImage(false)\n{\n if (bSubtractHistory) {\n m_pHistoryPreProcessor = HistoryPreProcessorPtr(\n new HistoryPreProcessor(ppBitmaps[1]->getSize(), 1, \n config.m_bBrighterRegions));\n }\n setBitmaps(ROI, ppBitmaps);\n m_pDistorter = FilterDistortionPtr(new FilterDistortion(m_pBitmaps[0]->getSize(), \n config.m_pTrafo));\n}\n\nTrackerThread::~TrackerThread()\n{\n}\n\nbool TrackerThread::init()\n{\n\/\/ Done in TrackerEventSource::ctor to work around Leopard\/libdc1394 threading issue.\n\/\/ m_pCamera->open();\n return true;\n}\n\nbool TrackerThread::work()\n{\n BitmapPtr pCamBmp;\n {\n ScopeTimer Timer(ProfilingZoneCapture);\n pCamBmp = m_pCamera->getImage(true);\n BitmapPtr pTempBmp1;\n while (pTempBmp1 = m_pCamera->getImage(false)) {\n pCamBmp = pTempBmp1;\n }\n }\n if (pCamBmp) {\n ScopeTimer Timer(ProfilingZoneTracker);\n if (m_bCreateDebugImages) {\n boost::mutex::scoped_lock Lock(*m_pMutex);\n *(m_pBitmaps[TRACKER_IMG_CAMERA]) = *pCamBmp;\n ScopeTimer Timer(ProfilingZoneHistogram);\n drawHistogram(m_pBitmaps[TRACKER_IMG_HISTOGRAM], pCamBmp);\n }\n BitmapPtr pDistortedBmp;\n {\n ScopeTimer Timer(ProfilingZoneDistort);\n pDistortedBmp = m_pDistorter->apply(pCamBmp);\n }\n BitmapPtr pCroppedBmp(new Bitmap(*pDistortedBmp, m_ROI));\n if (m_bCreateDebugImages) {\n boost::mutex::scoped_lock Lock(*m_pMutex);\n m_pBitmaps[TRACKER_IMG_DISTORTED]->copyPixels(*pCroppedBmp);\n }\n if (m_pHistoryPreProcessor) {\n ScopeTimer Timer(ProfilingZoneHistory);\n m_pHistoryPreProcessor->applyInPlace(pCroppedBmp);\n }\n if (m_bCreateDebugImages) {\n boost::mutex::scoped_lock Lock(*m_pMutex);\n m_pBitmaps[TRACKER_IMG_NOHISTORY]->copyPixels(*pCroppedBmp);\n }\n {\n boost::mutex::scoped_lock Lock(*m_pMutex);\n if (m_bCreateFingerImage) {\n Pixel32 Black(0x00, 0x00, 0x00, 0x00);\n FilterFill<Pixel32>(Black).applyInPlace(\n m_pBitmaps[TRACKER_IMG_FINGERS]);\n }\n BitmapPtr pBmpBandpass;\n if (m_TouchThreshold != 0) {\n {\n ScopeTimer Timer(ProfilingZoneBandpass);\n pBmpBandpass = FilterFastBandpass().apply(pCroppedBmp);\n }\n if (m_bCreateDebugImages) {\n *(m_pBitmaps[TRACKER_IMG_HIGHPASS]) = *pBmpBandpass;\n }\n }\n calcBlobs(pCroppedBmp, pBmpBandpass);\n }\n }\n return true;\n}\n\nvoid TrackerThread::deinit()\n{\n m_pCamera->close();\n}\n\nvoid TrackerThread::setConfig(TrackerConfig Config)\n{\n if (Config.m_pTouch) {\n m_TouchThreshold = Config.m_pTouch->m_Threshold;\n } else {\n m_TouchThreshold = 0;\n }\n if (Config.m_pTrack) {\n m_TrackThreshold = Config.m_pTrack->m_Threshold;\n m_bTrackBrighter = Config.m_bBrighterRegions;\n } else {\n m_TrackThreshold = 0;\n }\n if(m_pHistoryPreProcessor) {\n m_pHistoryPreProcessor->setInterval(Config.m_HistoryUpdateInterval);\n }\n if (m_pTrafo != Config.m_pTrafo) {\n m_pDistorter = FilterDistortionPtr(new FilterDistortion(m_pBitmaps[0]->getSize(), \n Config.m_pTrafo));\n m_pTrafo = Config.m_pTrafo;\n }\n if (int(m_pCamera->getFeature(\"brightness\")) != Config.m_Brightness ||\n int(m_pCamera->getFeature(\"gamma\")) != Config.m_Gamma ||\n int(m_pCamera->getFeature(\"gain\")) != Config.m_Gain ||\n int(m_pCamera->getFeature(\"shutter\")) != Config.m_Shutter)\n {\n m_pHistoryPreProcessor->reset();\n }\n\n m_pCamera->setFeature(\"brightness\", Config.m_Brightness);\n m_pCamera->setFeature(\"gamma\", Config.m_Gamma);\n m_pCamera->setFeature(\"gain\", Config.m_Gain);\n m_pCamera->setFeature(\"shutter\", Config.m_Shutter);\n\n m_bCreateDebugImages = Config.m_bCreateDebugImages;\n m_bCreateFingerImage = Config.m_bCreateFingerImage;\n}\n\nvoid TrackerThread::setBitmaps(IntRect ROI, BitmapPtr ppBitmaps[NUM_TRACKER_IMAGES])\n{\n m_ROI = ROI;\n for (int i=0; i<NUM_TRACKER_IMAGES; i++) {\n m_pBitmaps[i] = ppBitmaps[i];\n }\n if (m_pHistoryPreProcessor) {\n m_pHistoryPreProcessor = HistoryPreProcessorPtr(\n new HistoryPreProcessor(ROI.size(), \n m_pHistoryPreProcessor->getInterval(), m_bTrackBrighter));\n }\n}\n\nvoid TrackerThread::resetHistory()\n{\n if(m_pHistoryPreProcessor)\n m_pHistoryPreProcessor->reset();\n}\n \nvoid TrackerThread::drawHistogram(BitmapPtr pDestBmp, BitmapPtr pSrcBmp)\n{\n HistogramPtr pHist = pSrcBmp->getHistogram(3);\n assert(pDestBmp->getPixelFormat() == I8);\n \/\/ Normalize Histogram to 0..255\n int Max1 = 0;\n int Max2 = 0;\n for (int i=0; i<256; ++i) {\n if ((*pHist)[i] > Max1) {\n Max2 = Max1;\n Max1 = (*pHist)[i];\n } else if ((*pHist)[i] > Max2) {\n Max2 = (*pHist)[i];\n }\n }\n if (Max2== 0) {\n Max2= 1;\n }\n for (int i=0; i<256; ++i) {\n (*pHist)[i] = int((*pHist)[i]*256.0\/Max2)+1;\n }\n \n FilterFill<Pixel8>(0).applyInPlace(pDestBmp);\n int Width = pDestBmp->getSize().x;\n int Stride = pDestBmp->getStride();\n int EndRow = 256;\n if (pDestBmp->getSize().y < 256) {\n EndRow = pDestBmp->getSize().y;\n }\n for (int i=0; i<EndRow; ++i) {\n int StartCol =Width-(*pHist)[i];\n if (StartCol < 0) { \n StartCol = 0;\n }\n unsigned char * pDest = pDestBmp->getPixels()+Stride*i+StartCol;\n memset(pDest, 255, Width-StartCol);\n }\n}\n\nvoid TrackerThread::calcBlobs(BitmapPtr pTrackBmp, BitmapPtr pTouchBmp) {\n BlobVectorPtr pTrackComps;\n BlobVectorPtr pTouchComps;\n {\n ScopeTimer Timer(ProfilingZoneComps);\n pTrackComps = connected_components(pTrackBmp, m_TrackThreshold);\n pTouchComps = connected_components(pTouchBmp, m_TouchThreshold);\n }\n \/\/ AVG_TRACE(Logger::EVENTS2, \"connected components found \"<<comps->size()<<\" blobs.\");\n \/\/feed the IBlobTarget\n BitmapPtr pDestBmp;\n if (m_bCreateFingerImage) {\n pDestBmp = m_pBitmaps[TRACKER_IMG_FINGERS];\n }\n {\n ScopeTimer Timer(ProfilingZoneUpdate);\n m_pTarget->update(pTrackComps, pTrackBmp, m_TrackThreshold,\n pTouchComps, pTouchBmp, m_TouchThreshold, pDestBmp);\n }\n}\n\n}\n<commit_msg>Another bugfix for darker regions.<commit_after>\/\/\n\/\/ libavg - Media Playback Engine. \n\/\/ Copyright (C) 2003-2006 Ulrich von Zadow\n\/\/\n\/\/ This library is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU Lesser General Public\n\/\/ License as published by the Free Software Foundation; either\n\/\/ version 2 of the License, or (at your option) any later version.\n\/\/\n\/\/ This library is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ Lesser General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License along with this library; if not, write to the Free Software\n\/\/ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n\/\/\n\/\/ Current versions can be found at www.libavg.de\n\n#include \"TrackerThread.h\"\n#include \"FilterDistortion.h\"\n\n#include \"..\/base\/Logger.h\"\n#include \"..\/base\/ProfilingZone.h\"\n#include \"..\/base\/ScopeTimer.h\"\n\n#include \"..\/graphics\/Filter.h\"\n#include \"..\/graphics\/Filterfill.h\"\n#include \"..\/graphics\/FilterHighpass.h\"\n#include \"..\/graphics\/FilterFastBandpass.h\"\n#include \"..\/graphics\/FilterBlur.h\"\n#include \"..\/graphics\/FilterGauss.h\"\n\n#include <iostream>\n#include <stdlib.h>\n\nusing namespace std;\n\nnamespace avg {\nstatic ProfilingZone ProfilingZoneCapture (\"Capture\");\nstatic ProfilingZone ProfilingZoneTracker (\"Tracker\");\nstatic ProfilingZone ProfilingZoneHistory (\"History\");\nstatic ProfilingZone ProfilingZoneDistort (\"Distort\");\nstatic ProfilingZone ProfilingZoneHistogram (\"Histogram\");\nstatic ProfilingZone ProfilingZoneBandpass (\"Bandpass\");\nstatic ProfilingZone ProfilingZoneComps(\"ConnectedComps\");\nstatic ProfilingZone ProfilingZoneUpdate(\"Update\");\nstatic ProfilingZone ProfilingZoneDraw(\"Draw\");\n\nTrackerThread::TrackerThread(IntRect ROI, \n CameraPtr pCamera,\n BitmapPtr ppBitmaps[NUM_TRACKER_IMAGES],\n MutexPtr pMutex,\n CmdQueue& CmdQ,\n IBlobTarget *target,\n bool bSubtractHistory,\n TrackerConfig &config)\n : WorkerThread<TrackerThread>(\"Tracker\", CmdQ),\n m_TouchThreshold(0),\n m_TrackThreshold(0),\n m_pMutex(pMutex),\n m_pCamera(pCamera),\n m_pTarget(target),\n m_bCreateDebugImages(false),\n m_bCreateFingerImage(false)\n{\n if (bSubtractHistory) {\n m_pHistoryPreProcessor = HistoryPreProcessorPtr(\n new HistoryPreProcessor(ppBitmaps[1]->getSize(), 1, \n config.m_bBrighterRegions));\n }\n m_bTrackBrighter = config.m_bBrighterRegions; \n setBitmaps(ROI, ppBitmaps);\n m_pDistorter = FilterDistortionPtr(new FilterDistortion(m_pBitmaps[0]->getSize(), \n config.m_pTrafo));\n}\n\nTrackerThread::~TrackerThread()\n{\n}\n\nbool TrackerThread::init()\n{\n\/\/ Done in TrackerEventSource::ctor to work around Leopard\/libdc1394 threading issue.\n\/\/ m_pCamera->open();\n return true;\n}\n\nbool TrackerThread::work()\n{\n BitmapPtr pCamBmp;\n {\n ScopeTimer Timer(ProfilingZoneCapture);\n pCamBmp = m_pCamera->getImage(true);\n BitmapPtr pTempBmp1;\n while (pTempBmp1 = m_pCamera->getImage(false)) {\n pCamBmp = pTempBmp1;\n }\n }\n if (pCamBmp) {\n ScopeTimer Timer(ProfilingZoneTracker);\n if (m_bCreateDebugImages) {\n boost::mutex::scoped_lock Lock(*m_pMutex);\n *(m_pBitmaps[TRACKER_IMG_CAMERA]) = *pCamBmp;\n ScopeTimer Timer(ProfilingZoneHistogram);\n drawHistogram(m_pBitmaps[TRACKER_IMG_HISTOGRAM], pCamBmp);\n }\n BitmapPtr pDistortedBmp;\n {\n ScopeTimer Timer(ProfilingZoneDistort);\n pDistortedBmp = m_pDistorter->apply(pCamBmp);\n }\n BitmapPtr pCroppedBmp(new Bitmap(*pDistortedBmp, m_ROI));\n if (m_bCreateDebugImages) {\n boost::mutex::scoped_lock Lock(*m_pMutex);\n m_pBitmaps[TRACKER_IMG_DISTORTED]->copyPixels(*pCroppedBmp);\n }\n if (m_pHistoryPreProcessor) {\n ScopeTimer Timer(ProfilingZoneHistory);\n m_pHistoryPreProcessor->applyInPlace(pCroppedBmp);\n }\n if (m_bCreateDebugImages) {\n boost::mutex::scoped_lock Lock(*m_pMutex);\n m_pBitmaps[TRACKER_IMG_NOHISTORY]->copyPixels(*pCroppedBmp);\n }\n {\n boost::mutex::scoped_lock Lock(*m_pMutex);\n if (m_bCreateFingerImage) {\n Pixel32 Black(0x00, 0x00, 0x00, 0x00);\n FilterFill<Pixel32>(Black).applyInPlace(\n m_pBitmaps[TRACKER_IMG_FINGERS]);\n }\n BitmapPtr pBmpBandpass;\n if (m_TouchThreshold != 0) {\n {\n ScopeTimer Timer(ProfilingZoneBandpass);\n pBmpBandpass = FilterFastBandpass().apply(pCroppedBmp);\n }\n if (m_bCreateDebugImages) {\n *(m_pBitmaps[TRACKER_IMG_HIGHPASS]) = *pBmpBandpass;\n }\n }\n calcBlobs(pCroppedBmp, pBmpBandpass);\n }\n }\n return true;\n}\n\nvoid TrackerThread::deinit()\n{\n m_pCamera->close();\n}\n\nvoid TrackerThread::setConfig(TrackerConfig Config)\n{\n if (Config.m_pTouch) {\n m_TouchThreshold = Config.m_pTouch->m_Threshold;\n } else {\n m_TouchThreshold = 0;\n }\n if (Config.m_pTrack) {\n m_TrackThreshold = Config.m_pTrack->m_Threshold;\n m_bTrackBrighter = Config.m_bBrighterRegions;\n } else {\n m_TrackThreshold = 0;\n }\n if(m_pHistoryPreProcessor) {\n m_pHistoryPreProcessor->setInterval(Config.m_HistoryUpdateInterval);\n }\n if (m_pTrafo != Config.m_pTrafo) {\n m_pDistorter = FilterDistortionPtr(new FilterDistortion(m_pBitmaps[0]->getSize(), \n Config.m_pTrafo));\n m_pTrafo = Config.m_pTrafo;\n }\n if (int(m_pCamera->getFeature(\"brightness\")) != Config.m_Brightness ||\n int(m_pCamera->getFeature(\"gamma\")) != Config.m_Gamma ||\n int(m_pCamera->getFeature(\"gain\")) != Config.m_Gain ||\n int(m_pCamera->getFeature(\"shutter\")) != Config.m_Shutter)\n {\n m_pHistoryPreProcessor->reset();\n }\n\n m_pCamera->setFeature(\"brightness\", Config.m_Brightness);\n m_pCamera->setFeature(\"gamma\", Config.m_Gamma);\n m_pCamera->setFeature(\"gain\", Config.m_Gain);\n m_pCamera->setFeature(\"shutter\", Config.m_Shutter);\n\n m_bCreateDebugImages = Config.m_bCreateDebugImages;\n m_bCreateFingerImage = Config.m_bCreateFingerImage;\n}\n\nvoid TrackerThread::setBitmaps(IntRect ROI, BitmapPtr ppBitmaps[NUM_TRACKER_IMAGES])\n{\n m_ROI = ROI;\n for (int i=0; i<NUM_TRACKER_IMAGES; i++) {\n m_pBitmaps[i] = ppBitmaps[i];\n }\n if (m_pHistoryPreProcessor) {\n m_pHistoryPreProcessor = HistoryPreProcessorPtr(\n new HistoryPreProcessor(ROI.size(), \n m_pHistoryPreProcessor->getInterval(), m_bTrackBrighter));\n }\n}\n\nvoid TrackerThread::resetHistory()\n{\n if(m_pHistoryPreProcessor)\n m_pHistoryPreProcessor->reset();\n}\n \nvoid TrackerThread::drawHistogram(BitmapPtr pDestBmp, BitmapPtr pSrcBmp)\n{\n HistogramPtr pHist = pSrcBmp->getHistogram(3);\n assert(pDestBmp->getPixelFormat() == I8);\n \/\/ Normalize Histogram to 0..255\n int Max1 = 0;\n int Max2 = 0;\n for (int i=0; i<256; ++i) {\n if ((*pHist)[i] > Max1) {\n Max2 = Max1;\n Max1 = (*pHist)[i];\n } else if ((*pHist)[i] > Max2) {\n Max2 = (*pHist)[i];\n }\n }\n if (Max2== 0) {\n Max2= 1;\n }\n for (int i=0; i<256; ++i) {\n (*pHist)[i] = int((*pHist)[i]*256.0\/Max2)+1;\n }\n \n FilterFill<Pixel8>(0).applyInPlace(pDestBmp);\n int Width = pDestBmp->getSize().x;\n int Stride = pDestBmp->getStride();\n int EndRow = 256;\n if (pDestBmp->getSize().y < 256) {\n EndRow = pDestBmp->getSize().y;\n }\n for (int i=0; i<EndRow; ++i) {\n int StartCol =Width-(*pHist)[i];\n if (StartCol < 0) { \n StartCol = 0;\n }\n unsigned char * pDest = pDestBmp->getPixels()+Stride*i+StartCol;\n memset(pDest, 255, Width-StartCol);\n }\n}\n\nvoid TrackerThread::calcBlobs(BitmapPtr pTrackBmp, BitmapPtr pTouchBmp) {\n BlobVectorPtr pTrackComps;\n BlobVectorPtr pTouchComps;\n {\n ScopeTimer Timer(ProfilingZoneComps);\n pTrackComps = connected_components(pTrackBmp, m_TrackThreshold);\n pTouchComps = connected_components(pTouchBmp, m_TouchThreshold);\n }\n \/\/ AVG_TRACE(Logger::EVENTS2, \"connected components found \"<<comps->size()<<\" blobs.\");\n \/\/feed the IBlobTarget\n BitmapPtr pDestBmp;\n if (m_bCreateFingerImage) {\n pDestBmp = m_pBitmaps[TRACKER_IMG_FINGERS];\n }\n {\n ScopeTimer Timer(ProfilingZoneUpdate);\n m_pTarget->update(pTrackComps, pTrackBmp, m_TrackThreshold,\n pTouchComps, pTouchBmp, m_TouchThreshold, pDestBmp);\n }\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/*******************************************************************************\n *\n * MIT License\n *\n * Copyright (c) 2017 Advanced Micro Devices, Inc.\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n *\n *******************************************************************************\/\n#ifndef GUARD_MIOPEN_LOGGER_HPP\n#define GUARD_MIOPEN_LOGGER_HPP\n\n#include <array>\n#include <iostream>\n#include <miopen\/each_args.hpp>\n#include <type_traits>\n\n\/\/ See https:\/\/github.com\/pfultz2\/Cloak\/wiki\/C-Preprocessor-tricks,-tips,-and-idioms\n#define MIOPEN_PP_CAT(x, y) MIOPEN_PP_PRIMITIVE_CAT(x, y)\n#define MIOPEN_PP_PRIMITIVE_CAT(x, y) x##y\n\n#define MIOPEN_PP_IIF(c) MIOPEN_PP_PRIMITIVE_CAT(MIOPEN_PP_IIF_, c)\n#define MIOPEN_PP_IIF_0(t, ...) __VA_ARGS__\n#define MIOPEN_PP_IIF_1(t, ...) t\n\n#define MIOPEN_PP_IS_PAREN(x) MIOPEN_PP_IS_PAREN_CHECK(MIOPEN_PP_IS_PAREN_PROBE x)\n#define MIOPEN_PP_IS_PAREN_CHECK(...) MIOPEN_PP_IS_PAREN_CHECK_N(__VA_ARGS__, 0)\n#define MIOPEN_PP_IS_PAREN_PROBE(...) ~, 1,\n#define MIOPEN_PP_IS_PAREN_CHECK_N(x, n, ...) n\n\n#define MIOPEN_PP_EAT(...)\n#define MIOPEN_PP_EXPAND(...) __VA_ARGS__\n#define MIOPEN_PP_COMMA(...) ,\n\n#define MIOPEN_PP_TRANSFORM_ARGS(m, ...) \\\n MIOPEN_PP_EXPAND(MIOPEN_PP_PRIMITIVE_TRANSFORM_ARGS(m, \\\n MIOPEN_PP_COMMA, \\\n __VA_ARGS__, \\\n (), \\\n (), \\\n (), \\\n (), \\\n (), \\\n (), \\\n (), \\\n (), \\\n (), \\\n (), \\\n (), \\\n (), \\\n (), \\\n (), \\\n (), \\\n ()))\n\n#define MIOPEN_PP_EACH_ARGS(m, ...) \\\n MIOPEN_PP_EXPAND(MIOPEN_PP_PRIMITIVE_TRANSFORM_ARGS(m, \\\n MIOPEN_PP_EAT, \\\n __VA_ARGS__, \\\n (), \\\n (), \\\n (), \\\n (), \\\n (), \\\n (), \\\n (), \\\n (), \\\n (), \\\n (), \\\n (), \\\n (), \\\n (), \\\n (), \\\n (), \\\n ()))\n\n#define MIOPEN_PP_PRIMITIVE_TRANSFORM_ARGS( \\\n m, delim, x0, x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12, x13, x14, x15, ...) \\\n MIOPEN_PP_PRIMITIVE_TRANSFORM_ARG(m, x0) \\\n MIOPEN_PP_PRIMITIVE_TRANSFORM_ARG(delim, x1) \\\n MIOPEN_PP_PRIMITIVE_TRANSFORM_ARG(m, x1) \\\n MIOPEN_PP_PRIMITIVE_TRANSFORM_ARG(delim, x2) \\\n MIOPEN_PP_PRIMITIVE_TRANSFORM_ARG(m, x2) \\\n MIOPEN_PP_PRIMITIVE_TRANSFORM_ARG(delim, x3) \\\n MIOPEN_PP_PRIMITIVE_TRANSFORM_ARG(m, x3) \\\n MIOPEN_PP_PRIMITIVE_TRANSFORM_ARG(delim, x4) \\\n MIOPEN_PP_PRIMITIVE_TRANSFORM_ARG(m, x4) \\\n MIOPEN_PP_PRIMITIVE_TRANSFORM_ARG(delim, x5) \\\n MIOPEN_PP_PRIMITIVE_TRANSFORM_ARG(m, x5) \\\n MIOPEN_PP_PRIMITIVE_TRANSFORM_ARG(delim, x6) \\\n MIOPEN_PP_PRIMITIVE_TRANSFORM_ARG(m, x6) \\\n MIOPEN_PP_PRIMITIVE_TRANSFORM_ARG(delim, x7) \\\n MIOPEN_PP_PRIMITIVE_TRANSFORM_ARG(m, x7) \\\n MIOPEN_PP_PRIMITIVE_TRANSFORM_ARG(delim, x8) \\\n MIOPEN_PP_PRIMITIVE_TRANSFORM_ARG(m, x8) \\\n MIOPEN_PP_PRIMITIVE_TRANSFORM_ARG(delim, x9) \\\n MIOPEN_PP_PRIMITIVE_TRANSFORM_ARG(m, x9) \\\n MIOPEN_PP_PRIMITIVE_TRANSFORM_ARG(delim, x10) \\\n MIOPEN_PP_PRIMITIVE_TRANSFORM_ARG(m, x10) \\\n MIOPEN_PP_PRIMITIVE_TRANSFORM_ARG(delim, x11) \\\n MIOPEN_PP_PRIMITIVE_TRANSFORM_ARG(m, x11) \\\n MIOPEN_PP_PRIMITIVE_TRANSFORM_ARG(delim, x12) \\\n MIOPEN_PP_PRIMITIVE_TRANSFORM_ARG(m, x12) \\\n MIOPEN_PP_PRIMITIVE_TRANSFORM_ARG(delim, x13) \\\n MIOPEN_PP_PRIMITIVE_TRANSFORM_ARG(m, x13) \\\n MIOPEN_PP_PRIMITIVE_TRANSFORM_ARG(delim, x14) \\\n MIOPEN_PP_PRIMITIVE_TRANSFORM_ARG(m, x14) \\\n MIOPEN_PP_PRIMITIVE_TRANSFORM_ARG(delim, x15) MIOPEN_PP_PRIMITIVE_TRANSFORM_ARG(m, x15)\n\n#define MIOPEN_PP_PRIMITIVE_TRANSFORM_ARG(m, x) \\\n MIOPEN_PP_IIF(MIOPEN_PP_IS_PAREN(x))(MIOPEN_PP_EAT, m)(x)\n\nnamespace miopen {\n\ntemplate <class Range>\nstd::ostream& LogRange(std::ostream& os, Range&& r, std::string delim)\n{\n bool first = true;\n for(auto&& x : r)\n {\n if(first)\n first = false;\n else\n os << delim;\n os << x;\n }\n return os;\n}\n\ntemplate <class T, class... Ts>\nstd::array<T, sizeof...(Ts) + 1> make_array(T x, Ts... xs)\n{\n return {{x, xs...}};\n}\n\n#define MIOPEN_LOG_ENUM_EACH(x) std::pair<std::string, decltype(x)>(#x, x)\n#ifdef _MSC_VER\n#define MIOPEN_LOG_ENUM(os, ...) os\n#else\n#define MIOPEN_LOG_ENUM(os, x, ...) \\\n miopen::LogEnum(os, x, make_array(MIOPEN_PP_TRANSFORM_ARGS(MIOPEN_LOG_ENUM_EACH, __VA_ARGS__)))\n#endif\n\ntemplate <class T, class Range>\nstd::ostream& LogEnum(std::ostream& os, T x, Range&& values)\n{\n for(auto&& p : values)\n {\n if(p.second == x)\n {\n os << p.first;\n return os;\n }\n }\n os << \"Unknown: \" << x;\n return os;\n}\n\nenum LoggingLevel\n{\n Default = 0, \/\/ WARNING for Release builds, INFO for Debug builds.\n Quiet,\n Fatal,\n Error,\n Warning,\n Info,\n Info2,\n Trace \/\/ E.g. messages output by MIOPEN_LOG_FUNCTION).\n};\n\nconst char* LoggingLevelToCString(enum LoggingLevel level);\n\nstd::string PlatformName();\n\n\/\/\/ \\return true if level is enabled.\n\/\/\/ \\param level - one of the values defined in LoggingLevel.\nint IsLogging(int level = LoggingLevel::Error);\n\ntemplate <class T>\nauto LogObjImpl(T* x) -> decltype(get_object(*x))\n{\n return get_object(*x);\n}\n\ninline void* LogObjImpl(void* x) { return x; }\n\ninline const void* LogObjImpl(const void* x) { return x; }\n\n#ifndef _MSC_VER\ntemplate <class T, typename std::enable_if<(std::is_pointer<T>{}), int>::type = 0>\nstd::ostream& LogParam(std::ostream& os, std::string name, const T& x)\n{\n os << name << \" = \";\n if(x == nullptr)\n os << \"nullptr\";\n else\n os << LogObjImpl(x);\n return os;\n}\n\ntemplate <class T, typename std::enable_if<(not std::is_pointer<T>{}), int>::type = 0>\nstd::ostream& LogParam(std::ostream& os, std::string name, const T& x)\n{\n os << name << \" = \" << get_object(x);\n return os;\n}\n#define MIOPEN_LOG_FUNCTION_EACH(param) miopen::LogParam(std::cerr, #param, param) << std::endl;\n\n#define MIOPEN_LOG_FUNCTION(...) \\\n if(miopen::IsLogging(miopen::LoggingLevel::Trace)) \\\n { \\\n std::cerr << miopen::PlatformName() << \": \" << __PRETTY_FUNCTION__ << \"{\" << std::endl; \\\n MIOPEN_PP_EACH_ARGS(MIOPEN_LOG_FUNCTION_EACH, __VA_ARGS__) \\\n std::cerr << \"}\" << std::endl; \\\n }\n#else\n#define MIOPEN_LOG_FUNCTION(...)\n#endif\n\n\/\/\/ \\todo __PRETTY_FUNCTION__ is too verbose, __func_ it too short.\n\/\/\/ Shall we add filename (no path, no ext) prior __func__.\n#define MIOPEN_LOG(level, ...) \\\n do \\\n { \\\n if(miopen::IsLogging(level)) \\\n { \\\n std::cerr << miopen::PlatformName() << \": \" << LoggingLevelToCString(level) << \" [\" << __func__ << \"] \" << __VA_ARGS__ \\\n << std::endl; \\\n } \\\n } while(false)\n\n} \/\/ namespace miopen\n\n#endif\n<commit_msg>Formatting<commit_after>\/*******************************************************************************\n *\n * MIT License\n *\n * Copyright (c) 2017 Advanced Micro Devices, Inc.\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n *\n *******************************************************************************\/\n#ifndef GUARD_MIOPEN_LOGGER_HPP\n#define GUARD_MIOPEN_LOGGER_HPP\n\n#include <array>\n#include <iostream>\n#include <miopen\/each_args.hpp>\n#include <type_traits>\n\n\/\/ See https:\/\/github.com\/pfultz2\/Cloak\/wiki\/C-Preprocessor-tricks,-tips,-and-idioms\n#define MIOPEN_PP_CAT(x, y) MIOPEN_PP_PRIMITIVE_CAT(x, y)\n#define MIOPEN_PP_PRIMITIVE_CAT(x, y) x##y\n\n#define MIOPEN_PP_IIF(c) MIOPEN_PP_PRIMITIVE_CAT(MIOPEN_PP_IIF_, c)\n#define MIOPEN_PP_IIF_0(t, ...) __VA_ARGS__\n#define MIOPEN_PP_IIF_1(t, ...) t\n\n#define MIOPEN_PP_IS_PAREN(x) MIOPEN_PP_IS_PAREN_CHECK(MIOPEN_PP_IS_PAREN_PROBE x)\n#define MIOPEN_PP_IS_PAREN_CHECK(...) MIOPEN_PP_IS_PAREN_CHECK_N(__VA_ARGS__, 0)\n#define MIOPEN_PP_IS_PAREN_PROBE(...) ~, 1,\n#define MIOPEN_PP_IS_PAREN_CHECK_N(x, n, ...) n\n\n#define MIOPEN_PP_EAT(...)\n#define MIOPEN_PP_EXPAND(...) __VA_ARGS__\n#define MIOPEN_PP_COMMA(...) ,\n\n#define MIOPEN_PP_TRANSFORM_ARGS(m, ...) \\\n MIOPEN_PP_EXPAND(MIOPEN_PP_PRIMITIVE_TRANSFORM_ARGS(m, \\\n MIOPEN_PP_COMMA, \\\n __VA_ARGS__, \\\n (), \\\n (), \\\n (), \\\n (), \\\n (), \\\n (), \\\n (), \\\n (), \\\n (), \\\n (), \\\n (), \\\n (), \\\n (), \\\n (), \\\n (), \\\n ()))\n\n#define MIOPEN_PP_EACH_ARGS(m, ...) \\\n MIOPEN_PP_EXPAND(MIOPEN_PP_PRIMITIVE_TRANSFORM_ARGS(m, \\\n MIOPEN_PP_EAT, \\\n __VA_ARGS__, \\\n (), \\\n (), \\\n (), \\\n (), \\\n (), \\\n (), \\\n (), \\\n (), \\\n (), \\\n (), \\\n (), \\\n (), \\\n (), \\\n (), \\\n (), \\\n ()))\n\n#define MIOPEN_PP_PRIMITIVE_TRANSFORM_ARGS( \\\n m, delim, x0, x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12, x13, x14, x15, ...) \\\n MIOPEN_PP_PRIMITIVE_TRANSFORM_ARG(m, x0) \\\n MIOPEN_PP_PRIMITIVE_TRANSFORM_ARG(delim, x1) \\\n MIOPEN_PP_PRIMITIVE_TRANSFORM_ARG(m, x1) \\\n MIOPEN_PP_PRIMITIVE_TRANSFORM_ARG(delim, x2) \\\n MIOPEN_PP_PRIMITIVE_TRANSFORM_ARG(m, x2) \\\n MIOPEN_PP_PRIMITIVE_TRANSFORM_ARG(delim, x3) \\\n MIOPEN_PP_PRIMITIVE_TRANSFORM_ARG(m, x3) \\\n MIOPEN_PP_PRIMITIVE_TRANSFORM_ARG(delim, x4) \\\n MIOPEN_PP_PRIMITIVE_TRANSFORM_ARG(m, x4) \\\n MIOPEN_PP_PRIMITIVE_TRANSFORM_ARG(delim, x5) \\\n MIOPEN_PP_PRIMITIVE_TRANSFORM_ARG(m, x5) \\\n MIOPEN_PP_PRIMITIVE_TRANSFORM_ARG(delim, x6) \\\n MIOPEN_PP_PRIMITIVE_TRANSFORM_ARG(m, x6) \\\n MIOPEN_PP_PRIMITIVE_TRANSFORM_ARG(delim, x7) \\\n MIOPEN_PP_PRIMITIVE_TRANSFORM_ARG(m, x7) \\\n MIOPEN_PP_PRIMITIVE_TRANSFORM_ARG(delim, x8) \\\n MIOPEN_PP_PRIMITIVE_TRANSFORM_ARG(m, x8) \\\n MIOPEN_PP_PRIMITIVE_TRANSFORM_ARG(delim, x9) \\\n MIOPEN_PP_PRIMITIVE_TRANSFORM_ARG(m, x9) \\\n MIOPEN_PP_PRIMITIVE_TRANSFORM_ARG(delim, x10) \\\n MIOPEN_PP_PRIMITIVE_TRANSFORM_ARG(m, x10) \\\n MIOPEN_PP_PRIMITIVE_TRANSFORM_ARG(delim, x11) \\\n MIOPEN_PP_PRIMITIVE_TRANSFORM_ARG(m, x11) \\\n MIOPEN_PP_PRIMITIVE_TRANSFORM_ARG(delim, x12) \\\n MIOPEN_PP_PRIMITIVE_TRANSFORM_ARG(m, x12) \\\n MIOPEN_PP_PRIMITIVE_TRANSFORM_ARG(delim, x13) \\\n MIOPEN_PP_PRIMITIVE_TRANSFORM_ARG(m, x13) \\\n MIOPEN_PP_PRIMITIVE_TRANSFORM_ARG(delim, x14) \\\n MIOPEN_PP_PRIMITIVE_TRANSFORM_ARG(m, x14) \\\n MIOPEN_PP_PRIMITIVE_TRANSFORM_ARG(delim, x15) MIOPEN_PP_PRIMITIVE_TRANSFORM_ARG(m, x15)\n\n#define MIOPEN_PP_PRIMITIVE_TRANSFORM_ARG(m, x) \\\n MIOPEN_PP_IIF(MIOPEN_PP_IS_PAREN(x))(MIOPEN_PP_EAT, m)(x)\n\nnamespace miopen {\n\ntemplate <class Range>\nstd::ostream& LogRange(std::ostream& os, Range&& r, std::string delim)\n{\n bool first = true;\n for(auto&& x : r)\n {\n if(first)\n first = false;\n else\n os << delim;\n os << x;\n }\n return os;\n}\n\ntemplate <class T, class... Ts>\nstd::array<T, sizeof...(Ts) + 1> make_array(T x, Ts... xs)\n{\n return {{x, xs...}};\n}\n\n#define MIOPEN_LOG_ENUM_EACH(x) std::pair<std::string, decltype(x)>(#x, x)\n#ifdef _MSC_VER\n#define MIOPEN_LOG_ENUM(os, ...) os\n#else\n#define MIOPEN_LOG_ENUM(os, x, ...) \\\n miopen::LogEnum(os, x, make_array(MIOPEN_PP_TRANSFORM_ARGS(MIOPEN_LOG_ENUM_EACH, __VA_ARGS__)))\n#endif\n\ntemplate <class T, class Range>\nstd::ostream& LogEnum(std::ostream& os, T x, Range&& values)\n{\n for(auto&& p : values)\n {\n if(p.second == x)\n {\n os << p.first;\n return os;\n }\n }\n os << \"Unknown: \" << x;\n return os;\n}\n\nenum LoggingLevel\n{\n Default = 0, \/\/ WARNING for Release builds, INFO for Debug builds.\n Quiet,\n Fatal,\n Error,\n Warning,\n Info,\n Info2,\n Trace \/\/ E.g. messages output by MIOPEN_LOG_FUNCTION).\n};\n\nconst char* LoggingLevelToCString(enum LoggingLevel level);\n\nstd::string PlatformName();\n\n\/\/\/ \\return true if level is enabled.\n\/\/\/ \\param level - one of the values defined in LoggingLevel.\nint IsLogging(int level = LoggingLevel::Error);\n\ntemplate <class T>\nauto LogObjImpl(T* x) -> decltype(get_object(*x))\n{\n return get_object(*x);\n}\n\ninline void* LogObjImpl(void* x) { return x; }\n\ninline const void* LogObjImpl(const void* x) { return x; }\n\n#ifndef _MSC_VER\ntemplate <class T, typename std::enable_if<(std::is_pointer<T>{}), int>::type = 0>\nstd::ostream& LogParam(std::ostream& os, std::string name, const T& x)\n{\n os << name << \" = \";\n if(x == nullptr)\n os << \"nullptr\";\n else\n os << LogObjImpl(x);\n return os;\n}\n\ntemplate <class T, typename std::enable_if<(not std::is_pointer<T>{}), int>::type = 0>\nstd::ostream& LogParam(std::ostream& os, std::string name, const T& x)\n{\n os << name << \" = \" << get_object(x);\n return os;\n}\n#define MIOPEN_LOG_FUNCTION_EACH(param) miopen::LogParam(std::cerr, #param, param) << std::endl;\n\n#define MIOPEN_LOG_FUNCTION(...) \\\n if(miopen::IsLogging(miopen::LoggingLevel::Trace)) \\\n { \\\n std::cerr << miopen::PlatformName() << \": \" << __PRETTY_FUNCTION__ << \"{\" << std::endl; \\\n MIOPEN_PP_EACH_ARGS(MIOPEN_LOG_FUNCTION_EACH, __VA_ARGS__) \\\n std::cerr << \"}\" << std::endl; \\\n }\n#else\n#define MIOPEN_LOG_FUNCTION(...)\n#endif\n\n\/\/\/ \\todo __PRETTY_FUNCTION__ is too verbose, __func_ it too short.\n\/\/\/ Shall we add filename (no path, no ext) prior __func__.\n#define MIOPEN_LOG(level, ...) \\\n do \\\n { \\\n if(miopen::IsLogging(level)) \\\n { \\\n std::cerr << miopen::PlatformName() << \": \" << LoggingLevelToCString(level) << \" [\" \\\n << __func__ << \"] \" << __VA_ARGS__ << std::endl; \\\n } \\\n } while(false)\n\n} \/\/ namespace miopen\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>#include \"address_space.h\"\n#include <iostream>\n#include <gasnet.h>\n#include \"common.h\"\n\nint AddressSpace::init(int *argc, char ***argv)\n{\n GASNET_SAFE(gasnet_init(argc, argv));\n\n size_t segsz = gasnet_getMaxLocalSegmentSize();\n GASNET_SAFE(gasnet_attach(NULL, 0, segsz, 0));\n\n gasnet_seginfo_t segments[gasnet_nodes()];\n GASNET_SAFE(gasnet_getSegmentInfo(segments, gasnet_nodes()));\n\n if (gasnet_mynode()) {\n gasnet_barrier_notify(0, GASNET_BARRIERFLAG_ANONYMOUS);\n gasnet_barrier_wait(0, GASNET_BARRIERFLAG_ANONYMOUS);\n gasnet_exit(0);\n return 0;\n }\n\n for (int i = 0; i < gasnet_nodes(); i++) {\n Segment seg;\n seg.addr = (size_t)segments[i].addr;\n seg.len = segments[i].size;\n\n Node node;\n node.segment = seg;\n node.node = i;\n\n nodes.push_back(node);\n\n std::cout << \"node-%02d: segment: \" <<\n segments[i].size << \"\/\" << segments[i].addr << std::endl;\n }\n\n return 0;\n}\n\nvoid AddressSpace::write(int node, void *dst, void *src, size_t len)\n{\n gasnet_put_bulk(nodes[node].node, dst, src, len);\n}\n\nvoid AddressSpace::read(void *dest, int node, void *src, size_t len)\n{\n gasnet_get_bulk(dest, nodes[node].node, src, len);\n}\n<commit_msg>gasnet: support gasnet everything<commit_after>#include \"address_space.h\"\n#include <cassert>\n#include <iostream>\n#include <sys\/mman.h>\n#include <gasnet.h>\n#include <gasnet_tools.h>\n#include \"common.h\"\n\n#ifdef GASNET_SEGMENT_EVERYTHING\n\nstatic gasnet_seginfo_t *segments_ptr;\nstatic int seginfo_done;\nstatic gasnet_hsl_t seginfo_lock;\n\n#define AM_SEGINFO 128\n\nstatic void AM_seginfo(gasnet_token_t token, void *buf, size_t nbytes)\n{\n gasnet_node_t src;\n GASNET_SAFE(gasnet_AMGetMsgSource(token, &src));\n\n gasnet_seginfo_t contrib;\n assert(nbytes == sizeof(contrib));\n memcpy(&contrib, buf, sizeof(contrib));\n\n \/\/ barrier: seginfo_done is checked without lock\n gasnett_local_wmb();\n\n gasnet_hsl_lock(&seginfo_lock);\n segments_ptr[src] = contrib;\n seginfo_done++;\n gasnet_hsl_unlock(&seginfo_lock);\n}\n\nint AddressSpace::init(int *argc, char ***argv)\n{\n std::cout << \"gasnet segment = everything\" << std::endl;\n\n GASNET_SAFE(gasnet_init(argc, argv));\n\n \/\/ handler for sending segment info to rank 0\n gasnet_handlerentry_t handlers[1];\n handlers[0].index = AM_SEGINFO;\n handlers[0].fnptr = (void(*)())AM_seginfo;\n\n \/\/ segment info ignored for gasnet-everything\n GASNET_SAFE(gasnet_attach(handlers, 1, 0, 0));\n\n gasnet_seginfo_t segments[gasnet_nodes()];\n GASNET_SAFE(gasnet_getSegmentInfo(segments, gasnet_nodes()));\n\n gasnet_hsl_init(&seginfo_lock);\n segments_ptr = segments;\n seginfo_done = 0;\n\n \/\/ synchronized everyone before sending AMs so rank 0 initialization of\n \/\/ segments structure above doesn't race. could also hold lock above...\n gasnet_barrier_notify(0, GASNET_BARRIERFLAG_ANONYMOUS);\n gasnet_barrier_wait(0, GASNET_BARRIERFLAG_ANONYMOUS);\n\n \/*\n * currently rank 0 also contributes memory. We want to avoid this in the\n * future because rank 0 should have a large kernel cache for the FUSE\n * mount.\n *\/\n const size_t size = 1ULL << 30;\n void *data = mmap(NULL, size, PROT_READ|PROT_WRITE,\n MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);\n assert(data != MAP_FAILED);\n\n \/\/ notify rank 0 of contribution (rank 0 sends to self)\n gasnet_seginfo_t contrib;\n contrib.addr = data;\n contrib.size = size;\n GASNET_SAFE(gasnet_AMRequestMedium0(0, AM_SEGINFO,\n &contrib, sizeof(contrib)));\n\n \/\/ everyone but rank 0 snoozes now\n if (gasnet_mynode()) {\n gasnet_barrier_notify(0, GASNET_BARRIERFLAG_ANONYMOUS);\n gasnet_barrier_wait(0, GASNET_BARRIERFLAG_ANONYMOUS);\n gasnet_exit(0);\n return 0;\n }\n\n \/\/ wait for nodes to report on contribution\n GASNET_BLOCKUNTIL((seginfo_done == gasnet_nodes()));\n\n gasnet_hsl_lock(&seginfo_lock);\n assert(seginfo_done == gasnet_nodes());\n\n for (int i = 0; i < gasnet_nodes(); i++) {\n Segment seg;\n seg.addr = (size_t)segments[i].addr;\n seg.len = segments[i].size;\n\n Node node;\n node.segment = seg;\n node.node = i;\n\n nodes.push_back(node);\n\n std::cout << \"node-%02d: segment: \" <<\n segments[i].size << \"\/\" << segments[i].addr << std::endl;\n }\n\n gasnet_hsl_unlock(&seginfo_lock);\n\n return 0;\n}\n#else\nint AddressSpace::init(int *argc, char ***argv)\n{\n std::cout << \"gasnet segment = fast|large\" << std::endl;\n\n GASNET_SAFE(gasnet_init(argc, argv));\n\n size_t segsz = gasnet_getMaxLocalSegmentSize();\n GASNET_SAFE(gasnet_attach(NULL, 0, segsz, 0));\n\n gasnet_seginfo_t segments[gasnet_nodes()];\n GASNET_SAFE(gasnet_getSegmentInfo(segments, gasnet_nodes()));\n\n if (gasnet_mynode()) {\n gasnet_barrier_notify(0, GASNET_BARRIERFLAG_ANONYMOUS);\n gasnet_barrier_wait(0, GASNET_BARRIERFLAG_ANONYMOUS);\n gasnet_exit(0);\n return 0;\n }\n\n for (int i = 0; i < gasnet_nodes(); i++) {\n Segment seg;\n seg.addr = (size_t)segments[i].addr;\n seg.len = segments[i].size;\n\n Node node;\n node.segment = seg;\n node.node = i;\n\n nodes.push_back(node);\n\n std::cout << \"node-%02d: segment: \" <<\n segments[i].size << \"\/\" << segments[i].addr << std::endl;\n }\n\n return 0;\n}\n#endif\n\nvoid AddressSpace::write(int node, void *dst, void *src, size_t len)\n{\n gasnet_put_bulk(nodes[node].node, dst, src, len);\n}\n\nvoid AddressSpace::read(void *dest, int node, void *src, size_t len)\n{\n gasnet_get_bulk(dest, nodes[node].node, src, len);\n}\n<|endoftext|>"} {"text":"<commit_before>\/* indivudal.cpp - CS 472 Project #2: Genetic Programming\n * Copyright 2014 Andrew Schwartzmeyer\n *\n * Source file for individual namespace\n *\/\n\n#include <algorithm>\n#include <cassert>\n#include <cmath>\n#include <iostream>\n#include <memory>\n#include <tuple>\n#include <vector>\n\n#include \"individual.hpp\"\n#include \"..\/options\/options.hpp\"\n#include \"..\/random_generator\/random_generator.hpp\"\n\nnamespace individual\n{\n using std::vector;\n using std::string;\n using namespace random_generator;\n\n \/\/ Default Size struct constructor.\n Size::Size(): internals{0}, leaves{0}, depth{0} {}\n\n using F = Function;\n \/\/ Vectors of same-arity function enums.\n vector<F> nullaries {F::left, F::right, F::forward};\n vector<F> binaries {F::prog2, F::iffoodahead};\n vector<F> trinaries {F::prog3};\n\n \/* Vectors of available function enums. Should be moved into\n Options struct. *\/\n vector<F> leaves = nullaries;\n vector<F> internals {F::prog2, F::prog3, F::iffoodahead};\n\n \/\/ Returns a random function from a given set of functions.\n Function\n get_function(const vector<Function>& functions)\n {\n int_dist dist{0, static_cast<int>(functions.size()) - 1}; \/\/ closed interval\n return functions[dist(rg.engine)];\n }\n\n \/\/ Returns bool of whether or not the item is in the set.\n template<typename I, typename S> bool\n contains(const I& item, const S& set)\n {\n return std::find(set.begin(), set.end(), item) != set.end();\n }\n\n \/\/ Returns the appropriate arity for a given function.\n unsigned int\n get_arity(const Function& function)\n {\n if (contains(function, nullaries))\n return 0;\n else if (contains(function, binaries))\n return 2;\n else if (contains(function, trinaries))\n return 3;\n assert(false);\n }\n\n \/\/ Default constructor for \"empty\" node\n Node::Node(): function{Function::nil}, arity{0} {}\n\n \/* Recursively constructs a parse tree using the given method\n (either GROW or FULL). *\/\n Node::Node(const Method& method, const unsigned int& max_depth)\n {\n \/\/ Create leaf node if at the max depth or randomly (if growing).\n real_dist dist{0, 1};\n float grow_chance =\n static_cast<float>(leaves.size()) \/ (leaves.size() + internals.size());\n if (max_depth == 0\n\tor (method == Method::grow and dist(rg.engine) < grow_chance))\n {\n\tfunction = get_function(leaves);\n\tarity = 0; \/\/ get_arity(function); leaves are always zero\n }\n \/\/ Otherwise choose an internal node.\n else\n {\n\tfunction = get_function(internals);\n\tarity = get_arity(function);\n\t\/\/ Recursively create subtrees.\n\tchildren.reserve(arity);\n\tfor (unsigned int i = 0; i < arity; ++i)\n\t children.emplace_back(Node{method, max_depth - 1});\n }\n assert(function != Function::nil); \/\/ do not create null types\n assert(children.size() == arity); \/\/ ensure arity\n }\n\n Node create(const unsigned int& max_depth, const float& chance)\n {\n real_dist method_dist{0, 1};\n Method method = (method_dist(rg.engine) < chance)\n ? Method::grow : Method::full;\n\n int_dist depth_dist{0, static_cast<int>(max_depth)};\n unsigned int depth = depth_dist(rg.engine);\n\n return Node{method, depth};\n }\n\n \/\/ Returns a string visually representing a particular node.\n string\n Node::represent() const\n {\n switch (function)\n {\n case F::nil:\n\tassert(false); \/\/ Never represent empty node.\n case F::prog2:\n\treturn \"prog-2\";\n case F::prog3:\n\treturn \"prog-3\";\n case F::iffoodahead:\n\treturn \"if-food-ahead\";\n case F::left:\n\treturn \"left\";\n case F::right:\n\treturn \"right\";\n case F::forward:\n\treturn \"forward\";\n }\n assert(false); \/\/ Every node should have been matched.\n }\n\n \/* Returns string representation of expression in Polish\/prefix\n notation using a pre-order traversal. *\/\n string\n Node::print() const\n {\n if (children.empty())\n return represent();\n\n string formula = \"(\" + represent();\n\n for (const Node& child : children)\n formula += \" \" + child.print();\n\n return formula + \")\";\n }\n\n \/* Evaluates an ant over a given map using a depth-first post-order\n recursive continuous evaluation of a decision tree. *\/\n void\n Node::evaluate(options::Map& map) const\n {\n if (not map.active()) return;\n\n switch (function)\n {\n case F::left:\n\tmap.left(); \/\/ Terminal case\n\tbreak;\n case F::right:\n\tmap.right(); \/\/ Terminal case\n\tbreak;\n case F::forward:\n\tmap.forward(); \/\/ Terminal case\n\tbreak;\n case F::iffoodahead:\n\tif (map.look()) \/\/ Do left or right depending on if food ahead\n\t children[0].evaluate(map);\n\telse\n\t children[1].evaluate(map);\n\tbreak;\n case F::prog2: \/\/ Falls through\n case F::prog3:\n\tfor (const Node& child : children)\n\t child.evaluate(map);\n\tbreak;\n case F::nil:\n\tassert(false); \/\/ Never evaluate empty node\n }\n }\n\n \/* Recursively count children and find maximum depth of tree via\n post-order traversal. Keep track of internals, leaves, and depth\n via Size struct *\/\n const Size\n Node::size() const\n {\n Size size;\n\n if (children.empty())\n ++size.leaves;\n else\n {\n\tvector<unsigned int> depths;\n\tdepths.reserve(arity);\n\tfor (const Node& child : children)\n\t {\n\t Size temp = child.size();\n\t size.internals += temp.internals;\n\t size.leaves += temp.leaves;\n\t depths.emplace_back(temp.depth);\n\t }\n\tsize.depth = 1 + *std::max_element(depths.begin(), depths.end());\n\t++size.internals;\n }\n return size;\n }\n\n \/\/ Used to represent \"not-found\" (similar to a NULL pointer).\n Node empty;\n\n \/* Depth-first search for taget node. Must be seeking either\n internal or leaf, cannot be both. *\/\n Node&\n Node::visit(const Size& i, Size& visiting)\n {\n for (Node& child : children) {\n \/\/ Increase relevant count.\n if (child.children.empty())\n\t++visiting.leaves;\n else\n\t++visiting.internals;\n\n \/\/ Return node reference if found.\n if (visiting.internals == i.internals or visiting.leaves == i.leaves)\n\treturn child;\n else\n\t{\n\t Node& temp = child.visit(i, visiting); \/\/ Recursive search.\n\t if (temp.function != Function::nil)\n\t return temp;\n\t}\n }\n return empty;\n }\n\n void\n Node::mutate_self()\n {\n if (arity == 0)\n {\n\tconst Function old = function;\n\twhile (function == old)\n\t function = get_function(leaves);\n }\n else\n {\n\tconst Function old = function;\n\twhile (function == old)\n\t function = get_function(internals);\n\tarity = get_arity(function);\n\t\/\/ Fix arity mismatches caused by mutation\n\tif (arity == 2 and children.size() == 3)\n\t children.pop_back();\n\telse if (arity == 3 and children.size() == 2)\n\t children.emplace_back(create(4, 0.5));\n }\n assert(arity == children.size());\n assert(function != Function::nil);\n }\n\n \/\/ Recursively mutate nodes with given probability.\n void\n Node::mutate_tree(const float& chance)\n {\n real_dist dist{0, 1};\n for (Node& child : children)\n {\n\tif (dist(rg.engine) < chance)\n\t child.mutate_self();\n\tchild.mutate_tree(chance);\n }\n }\n\n \/\/ Default constructor for Individual\n Individual::Individual() {}\n\n \/* Create an Individual tree by having a root node (to which the\n actual construction is delegated). The depth is passed by value\n as its creation elsewhere is temporary. *\/\n Individual::Individual(const unsigned int depth, const float& chance,\n\t\t\t options::Map map): fitness{0}, adjusted{0}\n {\n root = create(depth, chance);\n \/* The evaluate method updates the size and both raw and adjusted\n fitnesses. *\/\n evaluate(map);\n }\n\n \/\/ Return string representation of a tree's size and fitness.\n string\n Individual::print() const\n {\n using std::to_string;\n\n string info = \"# Size \" + to_string(get_total()) + \", with \"\n + to_string(get_internals()) + \" internals, \"\n + to_string(get_leaves()) + \" leaves, and depth of \"\n + to_string(get_depth()) + \".\\n\"\n + \"# Score: \" + to_string(score)\n + \", and adjusted fitness: \" + to_string(adjusted) + \".\\n\";\n\n return info;\n }\n\n \/\/ Return string represenation of tree's expression (delegated).\n string\n Individual::print_formula() const\n {\n return \"# Formula: \" + root.print() + \"\\n\";\n }\n\n \/\/ Read-only \"getters\" for private data\n\n unsigned int\n Individual::get_internals() const\n {\n return size.internals;\n }\n\n unsigned int\n Individual::get_leaves() const\n {\n return size.leaves;\n }\n\n unsigned int\n Individual::get_total() const\n {\n return size.internals + size.leaves;\n }\n\n unsigned int\n Individual::get_depth() const\n {\n return size.depth;\n }\n\n unsigned int\n Individual::get_score() const\n {\n return score;\n }\n\n float\n Individual::get_fitness() const\n {\n return fitness;\n }\n\n float\n Individual::get_adjusted() const\n {\n return adjusted;\n }\n\n \/* Evaluate Individual for given values and calculate size. Update\n Individual's size and fitness accordingly. Return non-empty\n string if printing. *\/\n string\n Individual::evaluate(options::Map map, const float& penalty,\n\t\t const bool& print)\n {\n \/\/ Update size on evaluation because it's incredibly convenient.\n size = root.size();\n\n while (map.active())\n root.evaluate(map);\n\n score = map.fitness();\n \/\/ Adjusted fitness does not have size penalty.\n adjusted = static_cast<float>(score) \/ map.max();\n \/\/ Apply size penalty if not printing.\n fitness = score - penalty * get_total();\n\n string evaluation;\n if (print) evaluation = map.print();\n\n return evaluation;\n }\n\n \/\/ Mutate each node with given probability.\n void\n Individual::mutate(const float& chance)\n {\n root.mutate_tree(chance);\n }\n\n \/\/ Safely return reference to desired node.\n Node&\n Individual::operator[](const Size& i)\n {\n assert(i.internals <= get_internals());\n assert(i.leaves <= get_leaves());\n\n Size visiting;\n \/\/ Return root node if that's what we're seeking.\n if (i.internals == 0 and i.leaves == 0)\n return root;\n else\n return root.visit(i, visiting);\n }\n\n {\n\n else\n {\n }\n\n Size\n Individual::get_node(const Type& type)\n {\n Size target;\n \/\/ Guaranteed to have at least 1 leaf, but may have 0 internals.\n if (type == Type::internal and get_internals() != 0)\n {\n\t\/\/ Choose an internal node.\n\tint_dist dist{0, static_cast<int>(get_internals()) - 1};\n\ttarget.internals = dist(rg.engine);\n }\n else\n {\n\t\/\/ Otherwise choose a leaf node.\n\tint_dist dist{0, static_cast<int>(get_leaves()) - 1};\n\ttarget.leaves = dist(rg.engine);\n }\n return target;\n }\n\n \/* Swap two random subtrees between Individuals \"a\" and \"b\",\n selecting an internal node with chance probability. *\/\n void\n crossover(const float& chance, Individual& a, Individual& b)\n {\n real_dist probability{0, 1};\n\n Individual::Type type_a = (probability(rg.engine) < chance)\n ? Individual::Type::internal : Individual::Type::leaf;\n\n Individual::Type type_b = (probability(rg.engine) < chance)\n ? Individual::Type::internal : Individual::Type::leaf;\n\n std::swap(a[a.get_node(type_a)], b[b.get_node(type_b)]);\n }\n }\n}\n<commit_msg>Moving getter functions to bottom of source file<commit_after>\/* indivudal.cpp - CS 472 Project #2: Genetic Programming\n * Copyright 2014 Andrew Schwartzmeyer\n *\n * Source file for individual namespace\n *\/\n\n#include <algorithm>\n#include <cassert>\n#include <cmath>\n#include <iostream>\n#include <memory>\n#include <tuple>\n#include <vector>\n\n#include \"individual.hpp\"\n#include \"..\/options\/options.hpp\"\n#include \"..\/random_generator\/random_generator.hpp\"\n\nnamespace individual\n{\n using std::vector;\n using std::string;\n using namespace random_generator;\n\n \/\/ Default Size struct constructor.\n Size::Size(): internals{0}, leaves{0}, depth{0} {}\n\n using F = Function;\n \/\/ Vectors of same-arity function enums.\n vector<F> nullaries {F::left, F::right, F::forward};\n vector<F> binaries {F::prog2, F::iffoodahead};\n vector<F> trinaries {F::prog3};\n\n \/* Vectors of available function enums. Should be moved into\n Options struct. *\/\n vector<F> leaves = nullaries;\n vector<F> internals {F::prog2, F::prog3, F::iffoodahead};\n\n \/\/ Returns a random function from a given set of functions.\n Function\n get_function(const vector<Function>& functions)\n {\n int_dist dist{0, static_cast<int>(functions.size()) - 1}; \/\/ closed interval\n return functions[dist(rg.engine)];\n }\n\n \/\/ Returns bool of whether or not the item is in the set.\n template<typename I, typename S> bool\n contains(const I& item, const S& set)\n {\n return std::find(set.begin(), set.end(), item) != set.end();\n }\n\n \/\/ Returns the appropriate arity for a given function.\n unsigned int\n get_arity(const Function& function)\n {\n if (contains(function, nullaries))\n return 0;\n else if (contains(function, binaries))\n return 2;\n else if (contains(function, trinaries))\n return 3;\n assert(false);\n }\n\n \/\/ Default constructor for \"empty\" node\n Node::Node(): function{Function::nil}, arity{0} {}\n\n \/* Recursively constructs a parse tree using the given method\n (either GROW or FULL). *\/\n Node::Node(const Method& method, const unsigned int& max_depth)\n {\n \/\/ Create leaf node if at the max depth or randomly (if growing).\n real_dist dist{0, 1};\n float grow_chance =\n static_cast<float>(leaves.size()) \/ (leaves.size() + internals.size());\n if (max_depth == 0\n\tor (method == Method::grow and dist(rg.engine) < grow_chance))\n {\n\tfunction = get_function(leaves);\n\tarity = 0; \/\/ get_arity(function); leaves are always zero\n }\n \/\/ Otherwise choose an internal node.\n else\n {\n\tfunction = get_function(internals);\n\tarity = get_arity(function);\n\t\/\/ Recursively create subtrees.\n\tchildren.reserve(arity);\n\tfor (unsigned int i = 0; i < arity; ++i)\n\t children.emplace_back(Node{method, max_depth - 1});\n }\n assert(function != Function::nil); \/\/ do not create null types\n assert(children.size() == arity); \/\/ ensure arity\n }\n\n Node create(const unsigned int& max_depth, const float& chance)\n {\n real_dist method_dist{0, 1};\n Method method = (method_dist(rg.engine) < chance)\n ? Method::grow : Method::full;\n\n int_dist depth_dist{0, static_cast<int>(max_depth)};\n unsigned int depth = depth_dist(rg.engine);\n\n return Node{method, depth};\n }\n\n \/\/ Returns a string visually representing a particular node.\n string\n Node::represent() const\n {\n switch (function)\n {\n case F::nil:\n\tassert(false); \/\/ Never represent empty node.\n case F::prog2:\n\treturn \"prog-2\";\n case F::prog3:\n\treturn \"prog-3\";\n case F::iffoodahead:\n\treturn \"if-food-ahead\";\n case F::left:\n\treturn \"left\";\n case F::right:\n\treturn \"right\";\n case F::forward:\n\treturn \"forward\";\n }\n assert(false); \/\/ Every node should have been matched.\n }\n\n \/* Returns string representation of expression in Polish\/prefix\n notation using a pre-order traversal. *\/\n string\n Node::print() const\n {\n if (children.empty())\n return represent();\n\n string formula = \"(\" + represent();\n\n for (const Node& child : children)\n formula += \" \" + child.print();\n\n return formula + \")\";\n }\n\n \/* Evaluates an ant over a given map using a depth-first post-order\n recursive continuous evaluation of a decision tree. *\/\n void\n Node::evaluate(options::Map& map) const\n {\n if (not map.active()) return;\n\n switch (function)\n {\n case F::left:\n\tmap.left(); \/\/ Terminal case\n\tbreak;\n case F::right:\n\tmap.right(); \/\/ Terminal case\n\tbreak;\n case F::forward:\n\tmap.forward(); \/\/ Terminal case\n\tbreak;\n case F::iffoodahead:\n\tif (map.look()) \/\/ Do left or right depending on if food ahead\n\t children[0].evaluate(map);\n\telse\n\t children[1].evaluate(map);\n\tbreak;\n case F::prog2: \/\/ Falls through\n case F::prog3:\n\tfor (const Node& child : children)\n\t child.evaluate(map);\n\tbreak;\n case F::nil:\n\tassert(false); \/\/ Never evaluate empty node\n }\n }\n\n \/* Recursively count children and find maximum depth of tree via\n post-order traversal. Keep track of internals, leaves, and depth\n via Size struct *\/\n const Size\n Node::size() const\n {\n Size size;\n\n if (children.empty())\n ++size.leaves;\n else\n {\n\tvector<unsigned int> depths;\n\tdepths.reserve(arity);\n\tfor (const Node& child : children)\n\t {\n\t Size temp = child.size();\n\t size.internals += temp.internals;\n\t size.leaves += temp.leaves;\n\t depths.emplace_back(temp.depth);\n\t }\n\tsize.depth = 1 + *std::max_element(depths.begin(), depths.end());\n\t++size.internals;\n }\n return size;\n }\n\n \/\/ Used to represent \"not-found\" (similar to a NULL pointer).\n Node empty;\n\n \/* Depth-first search for taget node. Must be seeking either\n internal or leaf, cannot be both. *\/\n Node&\n Node::visit(const Size& i, Size& visiting)\n {\n for (Node& child : children) {\n \/\/ Increase relevant count.\n if (child.children.empty())\n\t++visiting.leaves;\n else\n\t++visiting.internals;\n\n \/\/ Return node reference if found.\n if (visiting.internals == i.internals or visiting.leaves == i.leaves)\n\treturn child;\n else\n\t{\n\t Node& temp = child.visit(i, visiting); \/\/ Recursive search.\n\t if (temp.function != Function::nil)\n\t return temp;\n\t}\n }\n return empty;\n }\n\n void\n Node::mutate_self()\n {\n if (arity == 0)\n {\n\tconst Function old = function;\n\twhile (function == old)\n\t function = get_function(leaves);\n }\n else\n {\n\tconst Function old = function;\n\twhile (function == old)\n\t function = get_function(internals);\n\tarity = get_arity(function);\n\t\/\/ Fix arity mismatches caused by mutation\n\tif (arity == 2 and children.size() == 3)\n\t children.pop_back();\n\telse if (arity == 3 and children.size() == 2)\n\t children.emplace_back(create(4, 0.5));\n }\n assert(arity == children.size());\n assert(function != Function::nil);\n }\n\n \/\/ Recursively mutate nodes with given probability.\n void\n Node::mutate_tree(const float& chance)\n {\n real_dist dist{0, 1};\n for (Node& child : children)\n {\n\tif (dist(rg.engine) < chance)\n\t child.mutate_self();\n\tchild.mutate_tree(chance);\n }\n }\n\n \/\/ Default constructor for Individual\n Individual::Individual() {}\n\n \/* Create an Individual tree by having a root node (to which the\n actual construction is delegated). The depth is passed by value\n as its creation elsewhere is temporary. *\/\n Individual::Individual(const unsigned int depth, const float& chance,\n\t\t\t options::Map map): fitness{0}, adjusted{0}\n {\n root = create(depth, chance);\n \/* The evaluate method updates the size and both raw and adjusted\n fitnesses. *\/\n evaluate(map);\n }\n\n \/\/ Return string representation of a tree's size and fitness.\n string\n Individual::print() const\n {\n using std::to_string;\n\n string info = \"# Size \" + to_string(get_total()) + \", with \"\n + to_string(get_internals()) + \" internals, \"\n + to_string(get_leaves()) + \" leaves, and depth of \"\n + to_string(get_depth()) + \".\\n\"\n + \"# Score: \" + to_string(score)\n + \", and adjusted fitness: \" + to_string(adjusted) + \".\\n\";\n\n return info;\n }\n\n \/\/ Return string represenation of tree's expression (delegated).\n string\n Individual::print_formula() const\n {\n return \"# Formula: \" + root.print() + \"\\n\";\n }\n\n \/* Evaluate Individual for given values and calculate size. Update\n Individual's size and fitness accordingly. Return non-empty\n string if printing. *\/\n string\n Individual::evaluate(options::Map map, const float& penalty,\n\t\t const bool& print)\n {\n \/\/ Update size on evaluation because it's incredibly convenient.\n size = root.size();\n\n while (map.active())\n root.evaluate(map);\n\n score = map.fitness();\n \/\/ Adjusted fitness does not have size penalty.\n adjusted = static_cast<float>(score) \/ map.max();\n \/\/ Apply size penalty if not printing.\n fitness = score - penalty * get_total();\n\n string evaluation;\n if (print) evaluation = map.print();\n\n return evaluation;\n }\n\n \/\/ Mutate each node with given probability.\n void\n Individual::mutate(const float& chance)\n {\n root.mutate_tree(chance);\n }\n\n \/\/ Safely return reference to desired node.\n Node&\n Individual::operator[](const Size& i)\n {\n assert(i.internals <= get_internals());\n assert(i.leaves <= get_leaves());\n\n Size visiting;\n \/\/ Return root node if that's what we're seeking.\n if (i.internals == 0 and i.leaves == 0)\n return root;\n else\n return root.visit(i, visiting);\n }\n\n {\n\n else\n {\n }\n\n Size\n Individual::get_node(const Type& type)\n {\n Size target;\n \/\/ Guaranteed to have at least 1 leaf, but may have 0 internals.\n if (type == Type::internal and get_internals() != 0)\n {\n\t\/\/ Choose an internal node.\n\tint_dist dist{0, static_cast<int>(get_internals()) - 1};\n\ttarget.internals = dist(rg.engine);\n }\n else\n {\n\t\/\/ Otherwise choose a leaf node.\n\tint_dist dist{0, static_cast<int>(get_leaves()) - 1};\n\ttarget.leaves = dist(rg.engine);\n }\n return target;\n }\n\n \/* Swap two random subtrees between Individuals \"a\" and \"b\",\n selecting an internal node with chance probability. *\/\n void\n crossover(const float& chance, Individual& a, Individual& b)\n {\n real_dist probability{0, 1};\n\n Individual::Type type_a = (probability(rg.engine) < chance)\n ? Individual::Type::internal : Individual::Type::leaf;\n\n Individual::Type type_b = (probability(rg.engine) < chance)\n ? Individual::Type::internal : Individual::Type::leaf;\n\n std::swap(a[a.get_node(type_a)], b[b.get_node(type_b)]);\n }\n\n \/\/ Read-only \"getters\" for private data\n\n unsigned int\n Individual::get_internals() const\n {\n return size.internals;\n }\n\n unsigned int\n Individual::get_leaves() const\n {\n return size.leaves;\n }\n\n unsigned int\n Individual::get_total() const\n {\n return size.internals + size.leaves;\n }\n\n unsigned int\n Individual::get_depth() const\n {\n return size.depth;\n }\n\n unsigned int\n Individual::get_score() const\n {\n return score;\n }\n\n float\n Individual::get_fitness() const\n {\n return fitness;\n }\n\n float\n Individual::get_adjusted() const\n {\n return adjusted;\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/* You can use one of the both BSD 3-Clause License or GNU Lesser General Public License 3.0 for this source. *\/\n\/* BSD 3-Clause License:\n * Copyright (c) 2013 - 2020, kazunobu watatsu.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:\n *\n * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation or other materials provided with the distribution.\n * Neither the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#if !defined(_LINEAR_OPT_)\n\ntemplate <typename T> class Linner {\npublic:\n#if defined(_WITHOUT_EIGEN_)\n typedef SimpleMatrix<T> Mat;\n typedef SimpleVector<T> Vec;\n#else\n typedef Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic> Mat;\n typedef Eigen::Matrix<T, Eigen::Dynamic, 1> Vec;\n#endif\n \n inline Linner();\n inline ~Linner();\n \n Vec inner(const Mat& A, const Vec& b) const;\n inline Mat roughQR(const Mat& At) const;\n T epsilon;\n};\n\ntemplate <typename T> inline Linner<T>::Linner() {\n#if defined(ACC_NO_FLOAT)\n epsilon = T(1) >> short(32);\n#else\n epsilon = sqrt(std::numeric_limits<T>::epsilon());\n#endif\n return;\n}\n\ntemplate <typename T> inline Linner<T>::~Linner() {\n return;\n}\n\ntemplate <typename T> typename Linner<T>::Vec Linner<T>::inner(const Mat& A, const Vec& b) const {\n assert(A.rows() == b.size() && 0 < A.cols() && 0 < b.size());\n \/\/ cout << A << endl << b << endl << c.transpose() << endl;\n cerr << \" (\" << A.rows() << \", \" << A.cols() << \")\";\n {\n bool trivial(true);\n for(int i = 0; i < b.size() && trivial; i ++)\n trivial = T(0) <= b[i];\n if(trivial) {\n Vec rvec(A.cols());\n for(int i = 0; i < rvec.size(); i ++)\n rvec[i] = T(0);\n return rvec;\n }\n }\n Mat AA(A.rows() + A.cols() * 2 + 1, A.cols() + 1);\n for(int i = 0; i < A.rows(); i ++) {\n for(int j = 0; j < A.cols(); j ++)\n AA(i, j) = A(i, j);\n AA(i, A.cols()) = - b[i];\n AA.row(i) \/= sqrt(AA.row(i).dot(AA.row(i)));\n }\n T m(1);\n for(int i = 0; i < A.rows(); i ++)\n for(int j = 0; j < AA.cols(); j ++) {\n const auto buf(abs(AA(i, j)));\n if(buf != T(0)) m = min(m, buf);\n assert(isfinite(buf) && !isnan(buf));\n }\n cerr << \" scale(\" << m << \")\" << flush;\n for(int i = A.rows(); i < AA.rows(); i ++)\n for(int j = 0; j < AA.cols(); j ++)\n AA(i, j) = (i - A.rows()) \/ 2 == j\n ? T((i - A.rows()) & 1 ? 1 : - 1)\n : T(0);\n auto Pt(roughQR(AA.transpose()));\n cerr << \"Q\" << flush;\n const Mat R(Pt * AA);\n cerr << \"R\" << flush;\n \n Vec one(Pt.cols());\n#if defined(_OPENMP)\n#pragma omp simd\n#endif\n for(int i = 0; i < Pt.cols(); i ++)\n one[i] = T(1);\n for(int n_fixed = 0; n_fixed < Pt.rows() - 1; n_fixed ++) {\n#if defined(_WITHOUT_EIGEN_)\n const auto on(Pt.projectionPt(- one));\n#else\n const Vec on(Pt.transpose() * (Pt * (- one)));\n#endif\n auto fidx(0);\n for( ; fidx < on.size() && on[fidx] <= T(0); fidx ++) ;\n for(int i = fidx + 1; i < on.size(); i ++)\n if(T(0) < on[i] && on[i] < on[fidx]) fidx = i;\n if(! n_fixed) fidx = Pt.cols() - 1;\n if(on.size() <= fidx || on[fidx] <= T(0)) break;\n \n \/\/ O(mn^2) over all in this function.\n const Vec orth(Pt.col(fidx));\n Vec intercept(Pt.cols());\n const auto orth2(orth.dot(orth));\n#if defined(_OPENMP)\n#pragma omp parallel for schedule(static, 1)\n#endif\n for(int j = 0; j < Pt.cols(); j ++) {\n intercept[j] = sqrt(orth2 * Pt.col(j).dot(Pt.col(j)));\n if(intercept[j] == T(0)) continue;\n intercept[j] = T(1) \/ intercept[j];\n if(! isfinite(intercept[j]) || isnan(intercept[j])) intercept[j] = T(0);\n }\n const auto ninter(sqrt(intercept.dot(intercept)));\n if(! isfinite(ninter) || isnan(ninter) || ninter == T(0)) break;\n intercept *= epsilon \/ ninter;\n const auto norm2orth(orth.dot(orth) + intercept[fidx]);\n#if defined(_OPENMP)\n#pragma omp parallel for schedule(static, 1)\n#endif\n for(int j = 0; j < Pt.cols(); j ++)\n if(intercept[j] == T(0))\n#if defined(_WITHOUT_EIGEN_)\n Pt.setCol(j, Pt.col(j) * T(0));\n#else\n Pt.col(j) *= T(0);\n#endif\n else\n#if defined(_WITHOUT_EIGEN_)\n Pt.setCol(j, Pt.col(j) - orth * (Pt.col(j).dot(orth) + intercept[j]) \/ norm2orth);\n#else\n Pt.col(j) -= orth * (Pt.col(j).dot(orth) + intercept[j]) \/ norm2orth;\n#endif\n }\n cerr << \"G\" << flush;\n#if defined(_WITHOUT_EIGEN_)\n auto rvec(- R.solve(Pt * one));\n#else\n auto rvec(- R.inverse() * (Pt * one));\n#endif\n cerr << \"I\" << flush;\n Vec rrvec(rvec.size() - 1);\n for(int i = 0; i < rrvec.size(); i ++)\n rrvec[i] = rvec[i] \/ rvec[rvec.size() - 1];\n return rrvec;\n}\n\ntemplate <typename T> inline typename Linner<T>::Mat Linner<T>::roughQR(const Mat& At) const {\n Mat Q(At.rows(), At.cols());\n for(int i = 0; i < Q.rows(); i ++)\n for(int j = 0; j < Q.cols(); j ++)\n Q(i, j) = T(0);\n for(int i = 0; i < At.rows(); i ++) {\n \/\/ N.B. in this case, At is full rank.\n#if defined(_WITHOUT_EIGEN_)\n const Vec work(At.row(i) - Q.projectionPt(At.row(i)));\n#else\n const Vec work(At.row(i) - (Q.transpose() * (Q * At.row(i).transpose())).transpose());\n#endif\n \/\/ generally, assert norm > error is needed.\n \/\/ in this case, not.\n Q.row(i) = work \/ sqrt(work.dot(work));\n }\n return Q;\n}\n\n#define _LINEAR_OPT_\n#endif\n\n<commit_msg>it's better not to orthogonal \\with intercept.<commit_after>\/* You can use one of the both BSD 3-Clause License or GNU Lesser General Public License 3.0 for this source. *\/\n\/* BSD 3-Clause License:\n * Copyright (c) 2013 - 2020, kazunobu watatsu.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:\n *\n * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation or other materials provided with the distribution.\n * Neither the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#if !defined(_LINEAR_OPT_)\n\ntemplate <typename T> class Linner {\npublic:\n#if defined(_WITHOUT_EIGEN_)\n typedef SimpleMatrix<T> Mat;\n typedef SimpleVector<T> Vec;\n#else\n typedef Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic> Mat;\n typedef Eigen::Matrix<T, Eigen::Dynamic, 1> Vec;\n#endif\n \n inline Linner();\n inline ~Linner();\n \n Vec inner(const Mat& A, const Vec& b) const;\n inline Mat roughQR(const Mat& At) const;\n T epsilon;\n};\n\ntemplate <typename T> inline Linner<T>::Linner() {\n#if defined(ACC_NO_FLOAT)\n epsilon = T(1) >> short(32);\n#else\n epsilon = sqrt(std::numeric_limits<T>::epsilon());\n#endif\n return;\n}\n\ntemplate <typename T> inline Linner<T>::~Linner() {\n return;\n}\n\ntemplate <typename T> typename Linner<T>::Vec Linner<T>::inner(const Mat& A, const Vec& b) const {\n assert(A.rows() == b.size() && 0 < A.cols() && 0 < b.size());\n \/\/ cout << A << endl << b << endl << c.transpose() << endl;\n cerr << \" (\" << A.rows() << \", \" << A.cols() << \")\";\n {\n bool trivial(true);\n for(int i = 0; i < b.size() && trivial; i ++)\n trivial = T(0) <= b[i];\n if(trivial) {\n Vec rvec(A.cols());\n for(int i = 0; i < rvec.size(); i ++)\n rvec[i] = T(0);\n return rvec;\n }\n }\n Mat AA(A.rows() + A.cols() * 2 + 1, A.cols() + 1);\n for(int i = 0; i < A.rows(); i ++) {\n for(int j = 0; j < A.cols(); j ++)\n AA(i, j) = A(i, j);\n AA(i, A.cols()) = - b[i];\n AA.row(i) \/= sqrt(AA.row(i).dot(AA.row(i)));\n }\n T m(1);\n for(int i = 0; i < A.rows(); i ++)\n for(int j = 0; j < AA.cols(); j ++) {\n const auto buf(abs(AA(i, j)));\n if(buf != T(0)) m = min(m, buf);\n assert(isfinite(buf) && !isnan(buf));\n }\n cerr << \" scale(\" << m << \")\" << flush;\n for(int i = A.rows(); i < AA.rows(); i ++)\n for(int j = 0; j < AA.cols(); j ++)\n AA(i, j) = (i - A.rows()) \/ 2 == j\n ? T((i - A.rows()) & 1 ? 1 : - 1)\n : T(0);\n auto Pt(roughQR(AA.transpose()));\n cerr << \"Q\" << flush;\n const Mat R(Pt * AA);\n cerr << \"R\" << flush;\n \n Vec one(Pt.cols());\n#if defined(_OPENMP)\n#pragma omp simd\n#endif\n for(int i = 0; i < Pt.cols(); i ++)\n one[i] = T(1);\n for(int n_fixed = 0; n_fixed < Pt.rows() - 1; n_fixed ++) {\n#if defined(_WITHOUT_EIGEN_)\n const auto on(Pt.projectionPt(- one));\n#else\n const Vec on(Pt.transpose() * (Pt * (- one)));\n#endif\n auto fidx(0);\n for( ; fidx < on.size() && on[fidx] <= T(0); fidx ++) ;\n for(int i = fidx + 1; i < on.size(); i ++)\n if(T(0) < on[i] && on[i] < on[fidx]) fidx = i;\n if(on.size() <= fidx || on[fidx] <= T(0)) break;\n \n \/\/ O(mn^2) over all in this function.\n const Vec orth(Pt.col(fidx));\n const auto norm2orth(orth.dot(orth));\n#if defined(_OPENMP)\n#pragma omp parallel for schedule(static, 1)\n#endif\n for(int j = 0; j < Pt.cols(); j ++)\n#if defined(_WITHOUT_EIGEN_)\n Pt.setCol(j, Pt.col(j) - orth * Pt.col(j).dot(orth) \/ norm2orth);\n#else\n Pt.col(j) -= orth * Pt.col(j).dot(orth) \/ norm2orth;\n#endif\n }\n cerr << \"G\" << flush;\n#if defined(_WITHOUT_EIGEN_)\n auto rvec(- R.solve(Pt * one));\n#else\n auto rvec(- R.inverse() * (Pt * one));\n#endif\n cerr << \"I\" << flush;\n Vec rrvec(rvec.size() - 1);\n for(int i = 0; i < rrvec.size(); i ++)\n rrvec[i] = rvec[i] \/ rvec[rvec.size() - 1];\n return rrvec;\n}\n\ntemplate <typename T> inline typename Linner<T>::Mat Linner<T>::roughQR(const Mat& At) const {\n Mat Q(At.rows(), At.cols());\n for(int i = 0; i < Q.rows(); i ++)\n for(int j = 0; j < Q.cols(); j ++)\n Q(i, j) = T(0);\n for(int i = 0; i < At.rows(); i ++) {\n \/\/ N.B. in this case, At is full rank.\n#if defined(_WITHOUT_EIGEN_)\n const Vec work(At.row(i) - Q.projectionPt(At.row(i)));\n#else\n const Vec work(At.row(i) - (Q.transpose() * (Q * At.row(i).transpose())).transpose());\n#endif\n \/\/ generally, assert norm > error is needed.\n \/\/ in this case, not.\n Q.row(i) = work \/ sqrt(work.dot(work));\n }\n return Q;\n}\n\n#define _LINEAR_OPT_\n#endif\n\n<|endoftext|>"} {"text":"<commit_before>#include \"sipmanager.h\"\n\n#include <QObject>\n\n\nconst quint32 FIRSTTRANSPORTID = 1;\n\nSIPManager::SIPManager():\n tcpServer_(),\n sipPort_(5060), \/\/ default for SIP, use 5061 for tls encrypted\n transports_(),\n nextTransportID_(FIRSTTRANSPORTID),\n transactions_(),\n negotiation_(),\n state_(INDIVIDUAL)\n{}\n\n\n\/\/ start listening to incoming\nvoid SIPManager::init(SIPTransactionUser* callControl)\n{\n QObject::connect(&tcpServer_, &ConnectionServer::newConnection,\n this, &SIPManager::receiveTCPConnection);\n\n tcpServer_.setProxy(QNetworkProxy::NoProxy);\n\n \/\/ listen to everything\n qDebug() << \"Initiating,\" << metaObject()->className()\n << \": Listening to SIP TCP connections on port:\" << sipPort_;\n if (!tcpServer_.listen(QHostAddress::Any, sipPort_))\n {\n printDebug(DEBUG_ERROR, this, DC_STARTUP,\n \"Failed to listen to socket. Is it reserved?\");\n\n \/\/ TODO announce it to user!\n }\n\n transactions_.init(callControl);\n\n QSettings settings(\"kvazzup.ini\", QSettings::IniFormat);\n QString username = !settings.value(\"local\/Username\").isNull()\n ? settings.value(\"local\/Username\").toString() : \"anonymous\";\n\n negotiation_.setLocalInfo(username);\n\n QObject::connect(&transactions_, &SIPTransactions::transportRequest,\n this, &SIPManager::transportRequest);\n QObject::connect(&transactions_, &SIPTransactions::transportResponse,\n this, &SIPManager::transportResponse);\n}\n\n\nvoid SIPManager::uninit()\n{\n transactions_.uninit();\n\n for(std::shared_ptr<SIPTransport> transport : transports_)\n {\n if(transport != nullptr)\n {\n transport->cleanup();\n transport.reset();\n }\n }\n}\n\n\nvoid SIPManager::bindToServer()\n{\n \/\/ get server address from settings and bind to server.\n QSettings settings(\"kvazzup.ini\", QSettings::IniFormat);\n\n QString serverAddress = settings.value(\"sip\/ServerAddress\").toString();\n\n if (serverAddress != \"\")\n {\n std::shared_ptr<SIPTransport> transport = createSIPTransport();\n transport->createConnection(TCP, serverAddress);\n\n sessionToTransportID_[transactions_.reserveSessionID()] = transport->getTransportID();\n\n waitingToBind_[transport->getTransportID()] = serverAddress;\n }\n else {\n qDebug() << \"SIP server address was empty in settings\";\n }\n}\n\n\nuint32_t SIPManager::startCall(Contact& address)\n{\n state_ = INDIVIDUAL;\n quint32 transportID = 0;\n uint32_t sessionID = transactions_.reserveSessionID();\n\n \/\/ There should not exist a dialog for this user\n if(!negotiation_.canStartSession())\n {\n printDebug(DEBUG_WARNING, this, DC_START_CALL, \"Not enough ports to start a call.\");\n return 0;\n }\n\n \/\/ check if we are already connected to remoteaddress and set transportID\n if (!isConnected(address.remoteAddress, transportID))\n {\n \/\/ we are not yet connected to them. Form a connection by creating the transport layer\n std::shared_ptr<SIPTransport> transport = createSIPTransport();\n transportID = transport->getTransportID(); \/\/ Get new transportID\n sessionToTransportID_[sessionID] = transportID;\n transport->createConnection(TCP, address.remoteAddress);\n waitingToStart_[transportID] = {sessionID, address};\n }\n else {\n \/\/ associate this sessionID with existing transportID\n sessionToTransportID_[sessionID] = transportID;\n \/\/ we have an existing connection already. Send SIP message and start call.\n transactions_.startDirectCall(address,\n transports_[transportID]->getLocalAddress(),\n sessionID);\n }\n\n return sessionID;\n}\n\n\nvoid SIPManager::acceptCall(uint32_t sessionID)\n{\n\n \/\/ Start candiate nomination. This function won't block,\n \/\/ negotiation happens in the background remoteFinalSDP()\n \/\/ makes sure that a connection was in fact nominated\n negotiation_.startICECandidateNegotiation(sessionID);\n\n transactions_.acceptCall(sessionID);\n}\n\n\nvoid SIPManager::rejectCall(uint32_t sessionID)\n{\n transactions_.rejectCall(sessionID);\n}\n\n\nvoid SIPManager::cancelCall(uint32_t sessionID)\n{\n transactions_.cancelCall(sessionID);\n}\n\n\nvoid SIPManager::endCall(uint32_t sessionID)\n{\n transactions_.endCall(sessionID);\n negotiation_.endSession(sessionID);\n}\n\n\nvoid SIPManager::endAllCalls()\n{\n transactions_.endAllCalls();\n negotiation_.endAllSessions();\n}\n\n\nvoid SIPManager::negotiateReceivePorts()\n{\n state_ = RECEIVE_PORTS;\n transactions_.renegotiateAllCalls();\n}\n\n\nvoid SIPManager::negotiateConference()\n{\n state_ = WHOLE_CONFERENCE;\n transactions_.renegotiateAllCalls();\n}\n\n\nvoid SIPManager::getSDPs(uint32_t sessionID,\n std::shared_ptr<SDPMessageInfo>& localSDP,\n std::shared_ptr<SDPMessageInfo>& remoteSDP) const\n{\n Q_ASSERT(sessionID);\n localSDP = negotiation_.getLocalSDP(sessionID);\n\n if (state_ == WHOLE_CONFERENCE)\n {\n remoteSDP = negotiation_.getRemoteConferenceSDP(sessionID);\n }\n else {\n remoteSDP = negotiation_.getRemoteSDP(sessionID);\n }\n}\n\n\nvoid SIPManager::receiveTCPConnection(TCPConnection *con)\n{\n qDebug() << \"Received a TCP connection. Initializing dialog\";\n Q_ASSERT(con);\n\n std::shared_ptr<SIPTransport> transport = createSIPTransport();\n transport->incomingTCPConnection(std::shared_ptr<TCPConnection> (con));\n}\n\n\nvoid SIPManager::connectionEstablished(quint32 transportID)\n{\n if (waitingToStart_.find(transportID) != waitingToStart_.end())\n {\n transactions_.startDirectCall(waitingToStart_[transportID].contact,\n transports_[transportID]->getLocalAddress(),\n waitingToStart_[transportID].sessionID);\n }\n\n if(waitingToBind_.find(transportID) != waitingToBind_.end())\n {\n transactions_.bindToServer(waitingToBind_[transportID],\n transports_[transportID]->getLocalAddress(),\n transportID);\n }\n}\n\n\nvoid SIPManager::transportRequest(uint32_t sessionID, SIPRequest &request)\n{\n if (sessionToTransportID_.find(sessionID) != sessionToTransportID_.end())\n {\n quint32 transportID = sessionToTransportID_[sessionID];\n\n if (transports_.find(transportID) != transports_.end())\n {\n QVariant content;\n if(request.type == SIP_INVITE)\n {\n request.message->content.length = 0;\n qDebug() << \"Adding SDP content to request:\" << request.type;\n request.message->content.type = APPLICATION_SDP;\n\n if (!SDPOfferToContent(content,\n transports_[transportID]->getLocalAddress(),\n sessionID))\n {\n return;\n }\n }\n\n\n transports_[transportID]->sendRequest(request, content);\n }\n else {\n printDebug(DEBUG_ERROR, metaObject()->className(), DC_SEND_SIP_REQUEST,\n \"Tried to send request with invalid transportID\");\n }\n }\n else {\n printDebug(DEBUG_ERROR, metaObject()->className(), DC_SEND_SIP_REQUEST,\n \"No mapping from sessionID to transportID\");\n }\n}\n\n\nvoid SIPManager::transportResponse(uint32_t sessionID, SIPResponse &response)\n{\n if (sessionToTransportID_.find(sessionID) != sessionToTransportID_.end())\n {\n quint32 transportID = sessionToTransportID_[sessionID];\n\n if (transports_.find(transportID) != transports_.end())\n {\n QVariant content;\n if (response.type == SIP_OK\n && response.message->transactionRequest == SIP_INVITE)\n {\n response.message->content.length = 0;\n qDebug() << \"Adding SDP content to request:\" << response.type;\n response.message->content.type = APPLICATION_SDP;\n if (!SDPAnswerToContent(content, sessionID))\n {\n return;\n }\n }\n\n transports_[transportID]->sendResponse(response, content);\n }\n else {\n printDebug(DEBUG_ERROR, metaObject()->className(), DC_SEND_SIP_RESPONSE,\n \"Tried to send response with invalid.\", {\"transportID\"},\n {QString::number(transportID)});\n }\n }\n else {\n printDebug(DEBUG_ERROR, metaObject()->className(), DC_SEND_SIP_RESPONSE,\n \"No mapping from sessionID to transportID\");\n }\n}\n\n\nvoid SIPManager::processSIPRequest(SIPRequest& request, QHostAddress localAddress,\n QVariant& content, quint32 transportID)\n{\n if(request.type == SIP_INVITE && !negotiation_.canStartSession())\n {\n printDebug(DEBUG_ERROR, this, DC_RECEIVE_SIP_REQUEST,\n \"Got INVITE, but unable to start a call\");\n return;\n }\n\n uint32_t sessionID = 0;\n\n \/\/ sets the sessionID if session exists or creates a new session if INVITE\n \/\/ returns true if either was successful.\n if (transactions_.identifySession(request, localAddress, sessionID))\n {\n Q_ASSERT(sessionID);\n if (sessionID != 0)\n {\n sessionToTransportID_[sessionID] = transportID;\n\n \/\/ TODO: prechecks that the message is ok, then modify program state.\n if(request.type == SIP_INVITE)\n {\n if(request.message->content.type == APPLICATION_SDP)\n {\n if(request.type == SIP_INVITE)\n {\n if(!processOfferSDP(sessionID, content, localAddress))\n {\n qDebug() << \"Failed to find suitable SDP.\";\n\n \/\/ TODO: Announce to transactions that we could not process their SDP\n printDebug(DEBUG_PROGRAM_ERROR, this, DC_RECEIVE_SIP_REQUEST,\n \"Failure to process SDP offer not implemented.\");\n\n \/\/foundDialog->server->setCurrentRequest(request); \/\/ TODO\n \/\/sendResponse(sessionID, SIP_DECLINE, request.type);\n\n return;\n }\n }\n }\n else\n {\n qDebug() << \"PEER ERROR: No SDP in\" << request.type;\n \/\/ TODO: tell SIP transactions that they did not have an SDP\n \/\/ sendResponse(sessionID, SIP_DECLINE, request.type);\n return;\n }\n }\n\n\n transactions_.processSIPRequest(request, sessionID);\n }\n else\n {\n printDebug(DEBUG_PROGRAM_ERROR, metaObject()->className(),\n DC_RECEIVE_SIP_REQUEST, \"transactions did not set new sessionID.\");\n }\n }\n else\n {\n printDebug(DEBUG_PEER_ERROR, metaObject()->className(),\n DC_RECEIVE_SIP_REQUEST, \"transactions could not identify session.\");\n }\n}\n\n\nvoid SIPManager::processSIPResponse(SIPResponse &response, QVariant& content)\n{\n uint32_t sessionID = 0;\n\n if(!transactions_.identifySession(response, sessionID))\n {\n printDebug(DEBUG_PEER_ERROR, this, DC_RECEIVE_SIP_RESPONSE,\n \"Could not identify response session\");\n return;\n }\n\n if(response.message->transactionRequest == SIP_INVITE && response.type == SIP_OK)\n {\n if(response.message->content.type == APPLICATION_SDP)\n {\n if(!processAnswerSDP(sessionID, content))\n {\n qDebug() << \"PEER_ERROR:\"\n << \"Their final sdp is not suitable. They should have followed our SDP!!!\";\n return;\n }\n\n negotiation_.setICEPorts(sessionID);\n }\n }\n\n transactions_.processSIPResponse(response, sessionID);\n}\n\n\nstd::shared_ptr<SIPTransport> SIPManager::createSIPTransport()\n{\n quint32 transportID = nextTransportID_;\n ++nextTransportID_;\n\n std::shared_ptr<SIPTransport> connection =\n std::shared_ptr<SIPTransport>(new SIPTransport(transportID));\n\n QObject::connect(connection.get(), &SIPTransport::incomingSIPRequest,\n this, &SIPManager::processSIPRequest);\n\n QObject::connect(connection.get(), &SIPTransport::incomingSIPResponse,\n this, &SIPManager::processSIPResponse);\n\n QObject::connect(connection.get(), &SIPTransport::sipTransportEstablished,\n this, &SIPManager::connectionEstablished);\n transports_[transportID] = connection;\n\n return connection;\n}\n\n\nbool SIPManager::isConnected(QString remoteAddress, quint32& outTransportID)\n{\n for(auto transport : transports_)\n {\n if(transport != nullptr &&\n transport->getRemoteAddress().toString() == remoteAddress)\n {\n outTransportID = transport->getTransportID();\n return true;\n }\n }\n return false;\n}\n\n\nbool SIPManager::SDPOfferToContent(QVariant& content, QHostAddress localAddress,\n uint32_t sessionID)\n{\n std::shared_ptr<SDPMessageInfo> pointer;\n switch (state_)\n {\n case INDIVIDUAL:\n {\n printDebug(DEBUG_NORMAL, this, DC_NEGOTIATING, \"Adding one-to-one SDP.\");\n if(!negotiation_.generateOfferSDP(localAddress, sessionID))\n {\n qDebug() << \"Failed to generate first SDP offer while sending.\";\n return false;\n }\n pointer = negotiation_.getLocalSDP(sessionID);\n break;\n }\n case RECEIVE_PORTS:\n {\n printDebug(DEBUG_NORMAL, this, DC_NEGOTIATING, \"Adding conferencing receive SDP.\");\n if(!negotiation_.initialConferenceOfferSDP(sessionID))\n {\n qDebug() << \"Failed to generate initial conference SDP offer while sending.\";\n return false;\n }\n pointer = negotiation_.getInitialConferenceOffer(sessionID);\n break;\n }\n case WHOLE_CONFERENCE:\n {\n printDebug(DEBUG_NORMAL, this, DC_NEGOTIATING, \"Adding conferencing final SDP.\");\n if(!negotiation_.finalConferenceOfferSDP(sessionID))\n {\n qDebug() << \"Failed to generate final conference SDP offer while sending.\";\n return false;\n }\n pointer = negotiation_.getFinalConferenceOffer(sessionID);\n break;\n }\n }\n Q_ASSERT(pointer != nullptr);\n\n SDPMessageInfo sdp = *pointer;\n content.setValue(sdp);\n return true;\n}\n\n\nbool SIPManager::processOfferSDP(uint32_t sessionID, QVariant& content,\n QHostAddress localAddress)\n{\n if(!content.isValid())\n {\n printDebug(DEBUG_PROGRAM_ERROR, this, DC_SIP_CONTENT,\n \"The SDP content is not valid at processing. \"\n \"Should be detected earlier.\");\n return false;\n }\n\n SDPMessageInfo retrieved = content.value<SDPMessageInfo>();\n if(!negotiation_.generateAnswerSDP(retrieved, localAddress, sessionID))\n {\n qDebug() << \"Remote SDP not suitable or we have no ports to assign\";\n negotiation_.endSession(sessionID);\n return false;\n }\n return true;\n}\n\n\nbool SIPManager::SDPAnswerToContent(QVariant &content, uint32_t sessionID)\n{\n SDPMessageInfo sdp;\n std::shared_ptr<SDPMessageInfo> pointer = negotiation_.getLocalSDP(sessionID);\n sdp = *pointer;\n content.setValue(sdp);\n return true;\n}\n\n\nbool SIPManager::processAnswerSDP(uint32_t sessionID, QVariant &content)\n{\n SDPMessageInfo retrieved = content.value<SDPMessageInfo>();\n if (!content.isValid())\n {\n printDebug(DEBUG_PROGRAM_ERROR, this, DC_NEGOTIATING,\n \"Content is not valid when processing SDP. \"\n \"Should be detected earlier.\");\n return false;\n }\n\n if(!negotiation_.processAnswerSDP(retrieved, sessionID))\n {\n return false;\n }\n\n return true;\n}\n<commit_msg>feature(Negotiation): Take into account different places where SDP may be included.<commit_after>#include \"sipmanager.h\"\n\n#include <QObject>\n\n\nconst quint32 FIRSTTRANSPORTID = 1;\n\nSIPManager::SIPManager():\n tcpServer_(),\n sipPort_(5060), \/\/ default for SIP, use 5061 for tls encrypted\n transports_(),\n nextTransportID_(FIRSTTRANSPORTID),\n transactions_(),\n negotiation_(),\n state_(INDIVIDUAL)\n{}\n\n\n\/\/ start listening to incoming\nvoid SIPManager::init(SIPTransactionUser* callControl)\n{\n QObject::connect(&tcpServer_, &ConnectionServer::newConnection,\n this, &SIPManager::receiveTCPConnection);\n\n tcpServer_.setProxy(QNetworkProxy::NoProxy);\n\n \/\/ listen to everything\n qDebug() << \"Initiating,\" << metaObject()->className()\n << \": Listening to SIP TCP connections on port:\" << sipPort_;\n if (!tcpServer_.listen(QHostAddress::Any, sipPort_))\n {\n printDebug(DEBUG_ERROR, this, DC_STARTUP,\n \"Failed to listen to socket. Is it reserved?\");\n\n \/\/ TODO announce it to user!\n }\n\n transactions_.init(callControl);\n\n QSettings settings(\"kvazzup.ini\", QSettings::IniFormat);\n QString username = !settings.value(\"local\/Username\").isNull()\n ? settings.value(\"local\/Username\").toString() : \"anonymous\";\n\n negotiation_.setLocalInfo(username);\n\n QObject::connect(&transactions_, &SIPTransactions::transportRequest,\n this, &SIPManager::transportRequest);\n QObject::connect(&transactions_, &SIPTransactions::transportResponse,\n this, &SIPManager::transportResponse);\n}\n\n\nvoid SIPManager::uninit()\n{\n transactions_.uninit();\n\n for(std::shared_ptr<SIPTransport> transport : transports_)\n {\n if(transport != nullptr)\n {\n transport->cleanup();\n transport.reset();\n }\n }\n}\n\n\nvoid SIPManager::bindToServer()\n{\n \/\/ get server address from settings and bind to server.\n QSettings settings(\"kvazzup.ini\", QSettings::IniFormat);\n\n QString serverAddress = settings.value(\"sip\/ServerAddress\").toString();\n\n if (serverAddress != \"\")\n {\n std::shared_ptr<SIPTransport> transport = createSIPTransport();\n transport->createConnection(TCP, serverAddress);\n\n sessionToTransportID_[transactions_.reserveSessionID()] = transport->getTransportID();\n\n waitingToBind_[transport->getTransportID()] = serverAddress;\n }\n else {\n qDebug() << \"SIP server address was empty in settings\";\n }\n}\n\n\nuint32_t SIPManager::startCall(Contact& address)\n{\n state_ = INDIVIDUAL;\n quint32 transportID = 0;\n uint32_t sessionID = transactions_.reserveSessionID();\n\n \/\/ There should not exist a dialog for this user\n if(!negotiation_.canStartSession())\n {\n printDebug(DEBUG_WARNING, this, DC_START_CALL, \"Not enough ports to start a call.\");\n return 0;\n }\n\n \/\/ check if we are already connected to remoteaddress and set transportID\n if (!isConnected(address.remoteAddress, transportID))\n {\n \/\/ we are not yet connected to them. Form a connection by creating the transport layer\n std::shared_ptr<SIPTransport> transport = createSIPTransport();\n transportID = transport->getTransportID(); \/\/ Get new transportID\n sessionToTransportID_[sessionID] = transportID;\n transport->createConnection(TCP, address.remoteAddress);\n waitingToStart_[transportID] = {sessionID, address};\n }\n else {\n \/\/ associate this sessionID with existing transportID\n sessionToTransportID_[sessionID] = transportID;\n \/\/ we have an existing connection already. Send SIP message and start call.\n transactions_.startDirectCall(address,\n transports_[transportID]->getLocalAddress(),\n sessionID);\n }\n\n return sessionID;\n}\n\n\nvoid SIPManager::acceptCall(uint32_t sessionID)\n{\n\n \/\/ Start candiate nomination. This function won't block,\n \/\/ negotiation happens in the background remoteFinalSDP()\n \/\/ makes sure that a connection was in fact nominated\n\n \/\/negotiation_.startICECandidateNegotiation(sessionID);\n\n transactions_.acceptCall(sessionID);\n}\n\n\nvoid SIPManager::rejectCall(uint32_t sessionID)\n{\n transactions_.rejectCall(sessionID);\n}\n\n\nvoid SIPManager::cancelCall(uint32_t sessionID)\n{\n transactions_.cancelCall(sessionID);\n}\n\n\nvoid SIPManager::endCall(uint32_t sessionID)\n{\n transactions_.endCall(sessionID);\n negotiation_.endSession(sessionID);\n}\n\n\nvoid SIPManager::endAllCalls()\n{\n transactions_.endAllCalls();\n negotiation_.endAllSessions();\n}\n\n\nvoid SIPManager::negotiateReceivePorts()\n{\n state_ = RECEIVE_PORTS;\n transactions_.renegotiateAllCalls();\n}\n\n\nvoid SIPManager::negotiateConference()\n{\n state_ = WHOLE_CONFERENCE;\n transactions_.renegotiateAllCalls();\n}\n\n\nvoid SIPManager::getSDPs(uint32_t sessionID,\n std::shared_ptr<SDPMessageInfo>& localSDP,\n std::shared_ptr<SDPMessageInfo>& remoteSDP) const\n{\n Q_ASSERT(sessionID);\n localSDP = negotiation_.getLocalSDP(sessionID);\n\n if (state_ == WHOLE_CONFERENCE)\n {\n remoteSDP = negotiation_.getRemoteConferenceSDP(sessionID);\n }\n else {\n remoteSDP = negotiation_.getRemoteSDP(sessionID);\n }\n}\n\n\nvoid SIPManager::receiveTCPConnection(TCPConnection *con)\n{\n qDebug() << \"Received a TCP connection. Initializing dialog\";\n Q_ASSERT(con);\n\n std::shared_ptr<SIPTransport> transport = createSIPTransport();\n transport->incomingTCPConnection(std::shared_ptr<TCPConnection> (con));\n}\n\n\nvoid SIPManager::connectionEstablished(quint32 transportID)\n{\n if (waitingToStart_.find(transportID) != waitingToStart_.end())\n {\n transactions_.startDirectCall(waitingToStart_[transportID].contact,\n transports_[transportID]->getLocalAddress(),\n waitingToStart_[transportID].sessionID);\n }\n\n if(waitingToBind_.find(transportID) != waitingToBind_.end())\n {\n transactions_.bindToServer(waitingToBind_[transportID],\n transports_[transportID]->getLocalAddress(),\n transportID);\n }\n}\n\n\nvoid SIPManager::transportRequest(uint32_t sessionID, SIPRequest &request)\n{\n if (sessionToTransportID_.find(sessionID) != sessionToTransportID_.end())\n {\n quint32 transportID = sessionToTransportID_[sessionID];\n\n if (transports_.find(transportID) != transports_.end())\n {\n QVariant content;\n if(request.type == SIP_INVITE)\n {\n request.message->content.length = 0;\n qDebug() << \"Adding SDP content to request:\" << request.type;\n request.message->content.type = APPLICATION_SDP;\n\n if (!SDPOfferToContent(content,\n transports_[transportID]->getLocalAddress(),\n sessionID))\n {\n return;\n }\n }\n\n\n transports_[transportID]->sendRequest(request, content);\n }\n else {\n printDebug(DEBUG_ERROR, metaObject()->className(), DC_SEND_SIP_REQUEST,\n \"Tried to send request with invalid transportID\");\n }\n }\n else {\n printDebug(DEBUG_ERROR, metaObject()->className(), DC_SEND_SIP_REQUEST,\n \"No mapping from sessionID to transportID\");\n }\n}\n\n\nvoid SIPManager::transportResponse(uint32_t sessionID, SIPResponse &response)\n{\n if (sessionToTransportID_.find(sessionID) != sessionToTransportID_.end())\n {\n quint32 transportID = sessionToTransportID_[sessionID];\n\n if (transports_.find(transportID) != transports_.end())\n {\n QVariant content;\n if (response.type == SIP_OK\n && response.message->transactionRequest == SIP_INVITE)\n {\n response.message->content.length = 0;\n qDebug() << \"Adding SDP content to request:\" << response.type;\n response.message->content.type = APPLICATION_SDP;\n if (!SDPAnswerToContent(content, sessionID))\n {\n return;\n }\n }\n\n transports_[transportID]->sendResponse(response, content);\n }\n else {\n printDebug(DEBUG_ERROR, metaObject()->className(), DC_SEND_SIP_RESPONSE,\n \"Tried to send response with invalid.\", {\"transportID\"},\n {QString::number(transportID)});\n }\n }\n else {\n printDebug(DEBUG_ERROR, metaObject()->className(), DC_SEND_SIP_RESPONSE,\n \"No mapping from sessionID to transportID\");\n }\n}\n\n\nvoid SIPManager::processSIPRequest(SIPRequest& request, QHostAddress localAddress,\n QVariant& content, quint32 transportID)\n{\n if(request.type == SIP_INVITE && !negotiation_.canStartSession())\n {\n printDebug(DEBUG_ERROR, this, DC_RECEIVE_SIP_REQUEST,\n \"Got INVITE, but unable to start a call\");\n return;\n }\n\n uint32_t sessionID = 0;\n\n \/\/ sets the sessionID if session exists or creates a new session if INVITE\n \/\/ returns true if either was successful.\n if (transactions_.identifySession(request, localAddress, sessionID))\n {\n Q_ASSERT(sessionID);\n if (sessionID != 0)\n {\n sessionToTransportID_[sessionID] = transportID;\n\n if((request.type == SIP_INVITE || request.type == SIP_ACK)\n && request.message->content.type == APPLICATION_SDP)\n {\n switch (negotiation_.getState(sessionID))\n {\n case NEG_NO_STATE:\n {\n printDebug(DEBUG_NORMAL, this, DC_RECEIVE_SIP_REQUEST,\n \"Got first SDP offer.\");\n if(!processOfferSDP(sessionID, content, transports_[transportID]->getLocalAddress()))\n {\n printDebug(DEBUG_PROGRAM_ERROR, this, DC_RECEIVE_SIP_REQUEST,\n \"Failure to process SDP offer not implemented.\");\n\n \/\/foundDialog->server->setCurrentRequest(request); \/\/ TODO\n \/\/sendResponse(sessionID, SIP_DECLINE, request.type);\n return;\n }\n break;\n }\n case NEG_OFFER_GENERATED:\n {\n printDebug(DEBUG_NORMAL, this, DC_RECEIVE_SIP_REQUEST,\n \"Got an SDP answer.\");\n processAnswerSDP(sessionID, content);\n break;\n }\n case NEG_ANSWER_GENERATED: \/\/ TODO: Not sure if these make any sense\n {\n printDebug(DEBUG_NORMAL, this, DC_RECEIVE_SIP_REQUEST,\n \"They sent us another SDP offer.\");\n processOfferSDP(sessionID, content, transports_[transportID]->getLocalAddress());\n break;\n }\n case NEG_FINISHED:\n {\n printDebug(DEBUG_NORMAL, this, DC_RECEIVE_SIP_REQUEST,\n \"Got a new SDP offer in response.\");\n processOfferSDP(sessionID, content, transports_[transportID]->getLocalAddress());\n break;\n }\n }\n\n }\n\n transactions_.processSIPRequest(request, sessionID);\n }\n else\n {\n printDebug(DEBUG_PROGRAM_ERROR, metaObject()->className(),\n DC_RECEIVE_SIP_REQUEST, \"transactions did not set new sessionID.\");\n }\n }\n else\n {\n printDebug(DEBUG_PEER_ERROR, metaObject()->className(),\n DC_RECEIVE_SIP_REQUEST, \"transactions could not identify session.\");\n }\n}\n\n\nvoid SIPManager::processSIPResponse(SIPResponse &response, QVariant& content)\n{\n uint32_t sessionID = 0;\n\n if(!transactions_.identifySession(response, sessionID))\n {\n printDebug(DEBUG_PEER_ERROR, this, DC_RECEIVE_SIP_RESPONSE,\n \"Could not identify response session\");\n return;\n }\n\n if(response.message->transactionRequest == SIP_INVITE && response.type == SIP_OK)\n {\n if(response.message->content.type == APPLICATION_SDP)\n {\n if(sessionToTransportID_.find(sessionID) == sessionToTransportID_.end())\n {\n printDebug(DEBUG_WARNING, this, DC_RECEIVE_SIP_RESPONSE,\n \"Could not identify transport for session\");\n return;\n }\n\n quint32 transportID = sessionToTransportID_[sessionID];\n\n switch (negotiation_.getState(sessionID))\n {\n case NEG_NO_STATE:\n {\n printDebug(DEBUG_NORMAL, this, DC_RECEIVE_SIP_RESPONSE,\n \"Got first SDP offer.\");\n if(!processOfferSDP(sessionID, content, transports_[transportID]->getLocalAddress()))\n {\n printDebug(DEBUG_PROGRAM_ERROR, this, DC_RECEIVE_SIP_RESPONSE,\n \"Failure to process SDP offer not implemented.\");\n\n \/\/foundDialog->server->setCurrentRequest(request); \/\/ TODO\n \/\/sendResponse(sessionID, SIP_DECLINE, request.type);\n return;\n }\n break;\n }\n case NEG_OFFER_GENERATED:\n {\n printDebug(DEBUG_NORMAL, this, DC_RECEIVE_SIP_RESPONSE,\n \"Got an SDP answer.\");\n processAnswerSDP(sessionID, content);\n break;\n }\n case NEG_ANSWER_GENERATED: \/\/ TODO: Not sure if these make any sense\n {\n printDebug(DEBUG_NORMAL, this, DC_RECEIVE_SIP_RESPONSE,\n \"They sent us another SDP offer.\");\n processOfferSDP(sessionID, content, transports_[transportID]->getLocalAddress());\n break;\n }\n case NEG_FINISHED:\n {\n printDebug(DEBUG_NORMAL, this, DC_RECEIVE_SIP_RESPONSE,\n \"Got a new SDP offer in response.\");\n processOfferSDP(sessionID, content, transports_[transportID]->getLocalAddress());\n break;\n }\n }\n\n\n negotiation_.setICEPorts(sessionID);\n }\n }\n\n transactions_.processSIPResponse(response, sessionID);\n}\n\n\nstd::shared_ptr<SIPTransport> SIPManager::createSIPTransport()\n{\n quint32 transportID = nextTransportID_;\n ++nextTransportID_;\n\n std::shared_ptr<SIPTransport> connection =\n std::shared_ptr<SIPTransport>(new SIPTransport(transportID));\n\n QObject::connect(connection.get(), &SIPTransport::incomingSIPRequest,\n this, &SIPManager::processSIPRequest);\n\n QObject::connect(connection.get(), &SIPTransport::incomingSIPResponse,\n this, &SIPManager::processSIPResponse);\n\n QObject::connect(connection.get(), &SIPTransport::sipTransportEstablished,\n this, &SIPManager::connectionEstablished);\n transports_[transportID] = connection;\n\n return connection;\n}\n\n\nbool SIPManager::isConnected(QString remoteAddress, quint32& outTransportID)\n{\n for(auto transport : transports_)\n {\n if(transport != nullptr &&\n transport->getRemoteAddress().toString() == remoteAddress)\n {\n outTransportID = transport->getTransportID();\n return true;\n }\n }\n return false;\n}\n\n\nbool SIPManager::SDPOfferToContent(QVariant& content, QHostAddress localAddress,\n uint32_t sessionID)\n{\n std::shared_ptr<SDPMessageInfo> pointer;\n switch (state_)\n {\n case INDIVIDUAL:\n {\n printDebug(DEBUG_NORMAL, this, DC_NEGOTIATING, \"Adding one-to-one SDP.\");\n if(!negotiation_.generateOfferSDP(localAddress, sessionID))\n {\n qDebug() << \"Failed to generate first SDP offer while sending.\";\n return false;\n }\n pointer = negotiation_.getLocalSDP(sessionID);\n break;\n }\n case RECEIVE_PORTS:\n {\n printDebug(DEBUG_NORMAL, this, DC_NEGOTIATING, \"Adding conferencing receive SDP.\");\n if(!negotiation_.initialConferenceOfferSDP(sessionID))\n {\n qDebug() << \"Failed to generate initial conference SDP offer while sending.\";\n return false;\n }\n pointer = negotiation_.getInitialConferenceOffer(sessionID);\n break;\n }\n case WHOLE_CONFERENCE:\n {\n printDebug(DEBUG_NORMAL, this, DC_NEGOTIATING, \"Adding conferencing final SDP.\");\n if(!negotiation_.finalConferenceOfferSDP(sessionID))\n {\n qDebug() << \"Failed to generate final conference SDP offer while sending.\";\n return false;\n }\n pointer = negotiation_.getFinalConferenceOffer(sessionID);\n break;\n }\n }\n Q_ASSERT(pointer != nullptr);\n\n SDPMessageInfo sdp = *pointer;\n content.setValue(sdp);\n return true;\n}\n\n\nbool SIPManager::processOfferSDP(uint32_t sessionID, QVariant& content,\n QHostAddress localAddress)\n{\n if(!content.isValid())\n {\n printDebug(DEBUG_PROGRAM_ERROR, this, DC_SIP_CONTENT,\n \"The SDP content is not valid at processing. \"\n \"Should be detected earlier.\");\n return false;\n }\n\n SDPMessageInfo retrieved = content.value<SDPMessageInfo>();\n if(!negotiation_.generateAnswerSDP(retrieved, localAddress, sessionID))\n {\n qDebug() << \"Remote SDP not suitable or we have no ports to assign\";\n negotiation_.endSession(sessionID);\n return false;\n }\n return true;\n}\n\n\nbool SIPManager::SDPAnswerToContent(QVariant &content, uint32_t sessionID)\n{\n SDPMessageInfo sdp;\n std::shared_ptr<SDPMessageInfo> pointer = negotiation_.getLocalSDP(sessionID);\n sdp = *pointer;\n content.setValue(sdp);\n return true;\n}\n\n\nbool SIPManager::processAnswerSDP(uint32_t sessionID, QVariant &content)\n{\n SDPMessageInfo retrieved = content.value<SDPMessageInfo>();\n if (!content.isValid())\n {\n printDebug(DEBUG_PROGRAM_ERROR, this, DC_NEGOTIATING,\n \"Content is not valid when processing SDP. \"\n \"Should be detected earlier.\");\n return false;\n }\n\n if(!negotiation_.processAnswerSDP(retrieved, sessionID))\n {\n return false;\n }\n\n return true;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"parser.h\"\n\n#include <assert.h>\n#include <iostream>\n#include <sstream>\n#include <iomanip> \n#include <cstring>\n#include \"types.h\"\n#include \"parser_definitions.h\"\n\n\nuint32 Parser::get() const {\n return *buffer;\n}\n\nbool Parser::end() const {\n return index >= length;\n}\n\nvoid Parser::eat() {\n index++;\n buffer++;\n}\n\nuint32 Parser::getAndEat() {\n uint32 result = get();\n eat();\n return result;\n}\n\nbool Parser::expectAndEat(uint32 e) {\n assert(e == get());\n eat();\n return true;\n}\n\nbool Parser::expect(uint32 e) const {\n assert(e == get());\n return true;\n}\n\n\nSOp Parser::readInstruction() {\n uint32* opData = buffer;\n uint32 word = getAndEat();\n spv::Op op = (spv::Op)(word & spv::OpCodeMask);\n uint32 wordCount = (uint32)(word >> spv::WordCountShift);\n\n WordType wordTypes[255];\n\n uint32 opWordCount = wordCount;\n\n if (sizeof(LUTOpWordTypes) \/ sizeof(void*) <= (int)op) {\n wordTypes[0] = WordType::TOp;\n for (int i = 1; i < wordCount; i++) {\n wordTypes[i] = WordType::TLiteralNumber;\n }\n }\n else {\n WordType* opWordTypes = (WordType*)LUTOpWordTypes[(int)op];\n opWordCount = LUTOpWordTypesCount[(int)op];\n\n for (int i = 0; i < wordCount; i++) {\n wordTypes[i] = opWordTypes[i > opWordCount - 1 ? opWordCount - 1 : i];\n }\n }\n\n uint32* opMem = new uint32[opWordCount + 1];\n memset(opMem, 0, sizeof(uint32) * (opWordCount + 1));\n SOp Result = { op, opMem };\n auto bufferBegin = buffer;\n int indexBegin = index;\n\n for (int i = 1; i < wordCount; i++) {\n word = getAndEat();\n void* currMem = opMem + i - 1;\n uint32* currMemU32 = (uint32*)currMem;\n if (wordTypes[i] == WordType::TIdList || wordTypes[i] == WordType::TLiteralNumberList) {\n assert(i + 1 == opWordCount);\n *currMemU32++ = (uint32) (wordCount - opWordCount + 1);\n currMem = currMemU32;\n *(uint32 **) currMem = (uint32 *) (buffer - 1);\n break;\n } else if (wordTypes[i] == WordType::TLiteralString) {\n assert(i + 1 == opWordCount);\n *(char **) currMem = (char *) (buffer - 1);\n break;\n } else {\n *currMemU32 = word;\n }\n }\n\n buffer = bufferBegin + wordCount - 1;\n index = indexBegin + wordCount - 1;\n\n return Result;\n}\n\nbool Parser::Parse(Program *outProg) {\n if (!expectAndEat(spv::MagicNumber)) {\n return false;\n }\n\n ParseProgram prog;\n prog.Version = getAndEat();\n prog.GeneratorMagic = getAndEat();\n prog.IDBound = getAndEat();\n prog.InstructionSchema = getAndEat();\n\n int instructionIndex = 0;\n prog.NextOp = readInstruction();\n\n do {\n SOp op = prog.NextOp;\n instructionIndex++;\n if (!end()) {\n prog.NextOp = readInstruction();\n } else {\n prog.NextOp = SOp{ Op::OpNop, nullptr };\n }\n\n LUTHandlerMethods[(int)op.Op]((void*)op.Memory, &prog);\n prog.Ops.push_back(op);\n\n if (prog.InFunction && prog.CurrentFunction->InBlock) {\n addOp(&prog, op);\n }\n } while (prog.NextOp.Op != Op::OpNop);\n\n *outProg = (Program)prog;\n return true;\n}\n\nstd::string writeProgram(const Program& prog) {\n std::stringstream progStream;\n progStream << \"Version: \" << prog.Version << std::endl;\n progStream << \"Generator Magic: \" << prog.GeneratorMagic << std::endl;\n progStream << \"ID Bound: \" << prog.IDBound << std::endl;\n progStream << \"Instruction Schema: \" << prog.InstructionSchema << std::endl;\n progStream << \"=================================================\" << std::endl;\n int instructionIndex = 0;\n for(auto& op : prog.Ops) {\n progStream << std::setw(3) << instructionIndex << \": \" << writeOp(op);\n instructionIndex++;\n }\n return progStream.str();\n}\n\nstd::string writeOp(SOp op) {\n std::stringstream opline;\n\n opline << OpStrings[(int)op.Op];\n\n WordType wordTypes[255];\n\n uint32 opWordCount = 0;\n\n if (sizeof(LUTOpWordTypes) \/ sizeof(void*) <= (int)op.Op) {\n return \"\";\n }\n else {\n WordType* opWordTypes = (WordType*)LUTOpWordTypes[(int)op.Op];\n opWordCount = LUTOpWordTypesCount[(int)op.Op];\n\n for (int i = 0; i < opWordCount; i++) {\n wordTypes[i] = opWordTypes[i];\n }\n }\n\n for (int i = 1; i < opWordCount; i++) {\n uint32 word = *((uint32*)op.Memory + i - 1);\n\n if (wordTypes[i] == WordType::TLiteralNumber) {\n opline << \" \" << word;\n }\n else if (wordTypes[i] == WordType::TId) {\n opline << \" [\" << word << \"]\";\n }\n else if (wordTypes[i] == WordType::TIdList) {\n uint32 count = word;\n uint32* ptr = *(uint32**)((uint32*)op.Memory + i);\n opline << \" [\";\n for (int j = 0; j < count; j++) {\n word = ptr[j];\n opline << \"[\" << word << \"]\" << (j != count - 1 ? \", \" : \"\");\n }\n opline << \"]\";\n\n break;\n }\n else if (wordTypes[i] == WordType::TLiteralNumberList) {\n uint32 count = word;\n uint32* ptr = *(uint32**)((uint32*)op.Memory + i);\n opline << \" [\";\n for (int j = 0; j < count; j++) {\n word = ptr[j];\n opline << word << (j != count - 1 ? \", \" : \"\");\n }\n opline << \"]\";\n\n break;\n }\n else if (wordTypes[i] == WordType::TLiteralString) {\n if (wordTypes[i - 1] != WordType::TLiteralString) {\n char* str = *((char**)((uint32*)op.Memory + i - 1));\n opline << \" \" << str;\n }\n }\n else {\n std::string* lutPointer = *((std::string**)LUTPointers + (uint32)wordTypes[i]);\n std::string name = lutPointer[word];\n opline << \" \" << name;\n }\n }\n\n opline << std::endl;\n return opline.str();\n}\n<commit_msg>improved disassembler output<commit_after>#include \"parser.h\"\n\n#include <assert.h>\n#include <iostream>\n#include <sstream>\n#include <iomanip> \n#include <cstring>\n#include \"types.h\"\n#include \"parser_definitions.h\"\n\n\nuint32 Parser::get() const {\n return *buffer;\n}\n\nbool Parser::end() const {\n return index >= length;\n}\n\nvoid Parser::eat() {\n index++;\n buffer++;\n}\n\nuint32 Parser::getAndEat() {\n uint32 result = get();\n eat();\n return result;\n}\n\nbool Parser::expectAndEat(uint32 e) {\n assert(e == get());\n eat();\n return true;\n}\n\nbool Parser::expect(uint32 e) const {\n assert(e == get());\n return true;\n}\n\n\nSOp Parser::readInstruction() {\n uint32* opData = buffer;\n uint32 word = getAndEat();\n spv::Op op = (spv::Op)(word & spv::OpCodeMask);\n uint32 wordCount = (uint32)(word >> spv::WordCountShift);\n\n WordType wordTypes[255];\n\n uint32 opWordCount = wordCount;\n\n if (sizeof(LUTOpWordTypes) \/ sizeof(void*) <= (int)op) {\n wordTypes[0] = WordType::TOp;\n for (int i = 1; i < wordCount; i++) {\n wordTypes[i] = WordType::TLiteralNumber;\n }\n }\n else {\n WordType* opWordTypes = (WordType*)LUTOpWordTypes[(int)op];\n opWordCount = LUTOpWordTypesCount[(int)op];\n\n for (int i = 0; i < wordCount; i++) {\n wordTypes[i] = opWordTypes[i > opWordCount - 1 ? opWordCount - 1 : i];\n }\n }\n\n uint32* opMem = new uint32[opWordCount + 1];\n memset(opMem, 0, sizeof(uint32) * (opWordCount + 1));\n SOp Result = { op, opMem };\n auto bufferBegin = buffer;\n int indexBegin = index;\n\n for (int i = 1; i < wordCount; i++) {\n word = getAndEat();\n void* currMem = opMem + i - 1;\n uint32* currMemU32 = (uint32*)currMem;\n if (wordTypes[i] == WordType::TIdList || wordTypes[i] == WordType::TLiteralNumberList) {\n assert(i + 1 == opWordCount);\n *currMemU32++ = (uint32) (wordCount - opWordCount + 1);\n currMem = currMemU32;\n *(uint32 **) currMem = (uint32 *) (buffer - 1);\n break;\n } else if (wordTypes[i] == WordType::TLiteralString) {\n assert(i + 1 == opWordCount);\n *(char **) currMem = (char *) (buffer - 1);\n break;\n } else {\n *currMemU32 = word;\n }\n }\n\n buffer = bufferBegin + wordCount - 1;\n index = indexBegin + wordCount - 1;\n\n return Result;\n}\n\nbool Parser::Parse(Program *outProg) {\n if (!expectAndEat(spv::MagicNumber)) {\n return false;\n }\n\n ParseProgram prog;\n prog.Version = getAndEat();\n prog.GeneratorMagic = getAndEat();\n prog.IDBound = getAndEat();\n prog.InstructionSchema = getAndEat();\n\n int instructionIndex = 0;\n prog.NextOp = readInstruction();\n\n do {\n SOp op = prog.NextOp;\n instructionIndex++;\n if (!end()) {\n prog.NextOp = readInstruction();\n } else {\n prog.NextOp = SOp{ Op::OpNop, nullptr };\n }\n\n LUTHandlerMethods[(int)op.Op]((void*)op.Memory, &prog);\n prog.Ops.push_back(op);\n\n if (prog.InFunction && prog.CurrentFunction->InBlock) {\n addOp(&prog, op);\n }\n } while (prog.NextOp.Op != Op::OpNop);\n\n *outProg = (Program)prog;\n return true;\n}\n\n\n\nstd::string getDescriptor(uint32 id, const Program* prog) {\n if(prog->Names.find(id) != prog->Names.end()) {\n return prog->Names.at(id).Name;\n } else if(prog->Variables.find(id) != prog->Variables.end()) {\n SVariable variable = prog->Variables.at(id);\n return getDescriptor(variable.ResultId, prog);\n }\n return \"\";\n}\n\nstd::string writeOp(SOp op, const Program* prog) {\n std::stringstream opline;\n\n opline << OpStrings[(int)op.Op];\n\n WordType wordTypes[255];\n\n uint32 opWordCount = 0;\n\n if (sizeof(LUTOpWordTypes) \/ sizeof(void*) <= (int)op.Op) {\n return \"\";\n }\n else {\n WordType* opWordTypes = (WordType*)LUTOpWordTypes[(int)op.Op];\n opWordCount = LUTOpWordTypesCount[(int)op.Op];\n\n for (int i = 0; i < opWordCount; i++) {\n wordTypes[i] = opWordTypes[i];\n }\n }\n\n for (int i = 1; i < opWordCount; i++) {\n uint32 word = *((uint32*)op.Memory + i - 1);\n\n if (wordTypes[i] == WordType::TLiteralNumber) {\n opline << \" \" << word;\n }\n else if (wordTypes[i] == WordType::TId) {\n opline << \" [\" << word;\n if(prog != nullptr && op.Op != Op::OpName && op.Op != Op::OpMemberName) {\n auto desc = getDescriptor(word, prog);\n if(desc.size() > 0) {\n opline << \"(\" << getDescriptor(word, prog) << \")\";\n }\n }\n opline << \"]\";\n }\n else if (wordTypes[i] == WordType::TIdList) {\n uint32 count = word;\n uint32* ptr = *(uint32**)((uint32*)op.Memory + i);\n opline << \" [\";\n for (int j = 0; j < count; j++) {\n word = ptr[j];\n opline << \"[\" << word;\n if(prog != nullptr && op.Op != Op::OpName && op.Op != Op::OpMemberName) {\n auto desc = getDescriptor(word, prog);\n if(desc.size() > 0) {\n opline << \"(\" << getDescriptor(word, prog) << \")\";\n }\n }\n opline << \"]\" << (j != count - 1 ? \", \" : \"\");\n }\n opline << \"]\";\n\n break;\n }\n else if (wordTypes[i] == WordType::TLiteralNumberList) {\n uint32 count = word;\n uint32* ptr = *(uint32**)((uint32*)op.Memory + i);\n opline << \" [\";\n for (int j = 0; j < count; j++) {\n word = ptr[j];\n opline << word << (j != count - 1 ? \", \" : \"\");\n }\n opline << \"]\";\n\n break;\n }\n else if (wordTypes[i] == WordType::TLiteralString) {\n if (wordTypes[i - 1] != WordType::TLiteralString) {\n char* str = *((char**)((uint32*)op.Memory + i - 1));\n opline << \" \" << str;\n }\n }\n else {\n std::string* lutPointer = *((std::string**)LUTPointers + (uint32)wordTypes[i]);\n std::string name = lutPointer[word];\n opline << \" \" << name;\n }\n }\n\n opline << std::endl;\n return opline.str();\n}\n\nstd::string writeProgram(const Program& prog) {\n std::stringstream progStream;\n progStream << \"Version: \" << prog.Version << std::endl;\n progStream << \"Generator Magic: \" << prog.GeneratorMagic << std::endl;\n progStream << \"ID Bound: \" << prog.IDBound << std::endl;\n progStream << \"Instruction Schema: \" << prog.InstructionSchema << std::endl;\n progStream << \"=================================================\" << std::endl;\n int instructionIndex = 0;\n for(auto& op : prog.Ops) {\n progStream << std::setw(3) << instructionIndex << \": \" << writeOp(op, &prog);\n instructionIndex++;\n }\n return progStream.str();\n}\n\nstd::string writeOp(SOp op) {\n return writeOp(op, nullptr);\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"port_win.h\"\n\n#include <Windows.h>\n\nnamespace leveldb {\nnamespace port {\n\nMutex::\n\tMutex()\n#ifndef NDEBUG\n\t: holding_thread_id_(0)\n#endif\n{\n\tstatic_assert(sizeof(CRITICAL_SECTION) <= SIZEOF_CRITICAL_SECTION, \"update Mutex::SIZEOF_CRITICAL_SECTION\");\n\tInitializeCriticalSection(_Out_ (LPCRITICAL_SECTION)cs_);\n}\n\nMutex::\n\t~Mutex()\n{\n\tDeleteCriticalSection(_Inout_ (LPCRITICAL_SECTION)cs_);\n}\n\nvoid Mutex::\n\tLock()\n{\n\tEnterCriticalSection(_Inout_ (LPCRITICAL_SECTION)cs_);\n#ifndef NDEBUG\n\tholding_thread_id_ = GetCurrentThreadId();\n#endif\n}\n\n\nvoid Mutex::\n\tUnlock()\n{\n#ifndef NDEBUG\n\tholding_thread_id_ = 0;\n#endif\n\tLeaveCriticalSection(_Inout_ (LPCRITICAL_SECTION)cs_);\n}\n\n#ifndef NDEBUG\nvoid Mutex::\n\tAssertHeld()\n{\n\tif ( holding_thread_id_ != GetCurrentThreadId() ) {\n\t\tfprintf(stderr, \"Mutex::AssertHeld failed, current thread: %d, holding thread: %d\\n\", GetCurrentThreadId(), holding_thread_id_);\n\t\tabort();\n\t}\n}\n#endif\n\nCondVar::\n\tCondVar(Mutex* mu)\n\t: mu_(mu)\n{\n\tstatic_assert(sizeof(CONDITION_VARIABLE) >= SIZEOF_CONDITION_VARIABLE, \"update Mutex::SIZEOF_CONDITION_VARIABLE\");\n\tInitializeConditionVariable((PCONDITION_VARIABLE)cv_);\n}\n\nCondVar::\n\t~CondVar()\n{\n}\n\nvoid CondVar::\n\tWait()\n{\n\tBOOL b = SleepConditionVariableCS((PCONDITION_VARIABLE)cv_, (PCRITICAL_SECTION)(mu_->cs_), INFINITE);\n\tif ( !b )\n\t\tfprintf(stderr, \"CondVar::Wait, SleepConditionVariableCS returned failure\");\n}\n\nvoid CondVar::\n\tSignal()\n{\n\tWakeConditionVariable((PCONDITION_VARIABLE)cv_);\n}\n\nvoid CondVar::\n\tSignalAll()\n{\n\tWakeAllConditionVariable((PCONDITION_VARIABLE)cv_);\n}\n\n \/\/ Read and return the stored pointer with the guarantee that no\n \/\/ later memory access (read or write) by this thread can be\n \/\/ reordered ahead of this read.\nvoid* AtomicPointer::\n\tAcquire_Load() const\n{\n\t\/\/Perform an exchange operation on the condition if the value is 0\n\t\/\/If it's zero, exchange with zero, return original value (0)\n\t\/\/If it's nonzero, don't exchange, return original value.\n\t\/\/So the exchange operation won't change the value, this is a const read operation\n\tAtomicPointer* mutable_this = const_cast<AtomicPointer*>(this);\n\n\treturn InterlockedCompareExchangePointerAcquire(&mutable_this->rep_, 0, 0);\n}\n\nvoid AtomicPointer::\n\tRelease_Store(void* v)\n{\n PVOID old;\n\n do {\n old = rep_;\n } while (InterlockedCompareExchangePointerRelease(&rep_,\n v,\n old) != old);\n}\n\nBOOL CALLBACK InitOnceCallback(\n _Inout_ PINIT_ONCE InitOnce,\n _Inout_opt_ PVOID Parameter,\n _Out_opt_ PVOID *Context\n)\n{\n\ttypedef void (*initializer_fn)();\n\t((initializer_fn)Parameter)();\n\treturn TRUE;\n}\n\nvoid InitOnce(port::OnceType* once, void (*initializer)())\n{\n\tINIT_ONCE* real_once = (INIT_ONCE*)once;\n\tstatic_assert(sizeof(*real_once) == sizeof(*once), \"port::OnceType must be the same as INIT_ONCE\");\n\tBOOL b = InitOnceExecuteOnce(\n\t\treal_once,\n\t\tInitOnceCallback,\n\t\tinitializer,\n\t\t0);\n}\n\n#if 0\n\/\/ ------------------ Compression -------------------\n\n\/\/ Store the snappy compression of \"input[0,input_length-1]\" in *output.\n\/\/ Returns false if snappy is not supported by this port.\nextern bool Snappy_Compress(const char* input, size_t input_length,\n std::string* output);\n\n\/\/ If input[0,input_length-1] looks like a valid snappy compressed\n\/\/ buffer, store the size of the uncompressed data in *result and\n\/\/ return true. Else return false.\nextern bool Snappy_GetUncompressedLength(const char* input, size_t length,\n size_t* result);\n\n\/\/ Attempt to snappy uncompress input[0,input_length-1] into *output.\n\/\/ Returns true if successful, false if the input is invalid lightweight\n\/\/ compressed data.\n\/\/\n\/\/ REQUIRES: at least the first \"n\" bytes of output[] must be writable\n\/\/ where \"n\" is the result of a successful call to\n\/\/ Snappy_GetUncompressedLength.\nextern bool Snappy_Uncompress(const char* input_data, size_t input_length,\n char* output);\n\n\/\/ ------------------ Miscellaneous -------------------\n\n\/\/ If heap profiling is not supported, returns false.\n\/\/ Else repeatedly calls (*func)(arg, data, n) and then returns true.\n\/\/ The concatenation of all \"data[0,n-1]\" fragments is the heap profile.\nextern bool GetHeapProfile(void (*func)(void*, const char*, int), void* arg);\n\n#endif \/\/ STORAGE_LEVELDB_PORT_PORT_EXAMPLE_H_\n\n} \/\/ namespace port\n} \/\/ namespace leveldb\n\n<commit_msg>Mutex holding_thread_id restored after woken up in CondVar<commit_after>#include \"port_win.h\"\n\n#include <Windows.h>\n\nnamespace leveldb {\nnamespace port {\n\nMutex::\n\tMutex()\n#ifndef NDEBUG\n\t: holding_thread_id_(0)\n#endif\n{\n\tstatic_assert(sizeof(CRITICAL_SECTION) <= SIZEOF_CRITICAL_SECTION, \"update Mutex::SIZEOF_CRITICAL_SECTION\");\n\tInitializeCriticalSection(_Out_ (LPCRITICAL_SECTION)cs_);\n}\n\nMutex::\n\t~Mutex()\n{\n\tDeleteCriticalSection(_Inout_ (LPCRITICAL_SECTION)cs_);\n}\n\nvoid Mutex::\n\tLock()\n{\n\tEnterCriticalSection(_Inout_ (LPCRITICAL_SECTION)cs_);\n#ifndef NDEBUG\n\tholding_thread_id_ = GetCurrentThreadId();\n#endif\n}\n\n\nvoid Mutex::\n\tUnlock()\n{\n#ifndef NDEBUG\n\tif ( holding_thread_id_ != 0 )\n\t\tAssertHeld();\n\tholding_thread_id_ = 0;\n#endif\n\tLeaveCriticalSection(_Inout_ (LPCRITICAL_SECTION)cs_);\n}\n\n#ifndef NDEBUG\nvoid Mutex::\n\tAssertHeld()\n{\n\tif ( holding_thread_id_ != GetCurrentThreadId() ) {\n\t\tfprintf(stderr, \"Mutex::AssertHeld failed, current thread: %d, holding thread: %d\\n\", GetCurrentThreadId(), holding_thread_id_);\n\t\tabort();\n\t}\n}\n#endif\n\nCondVar::\n\tCondVar(Mutex* mu)\n\t: mu_(mu)\n{\n\tstatic_assert(sizeof(CONDITION_VARIABLE) >= SIZEOF_CONDITION_VARIABLE, \"update Mutex::SIZEOF_CONDITION_VARIABLE\");\n\tInitializeConditionVariable((PCONDITION_VARIABLE)cv_);\n}\n\nCondVar::\n\t~CondVar()\n{\n}\n\nvoid CondVar::\n\tWait()\n{\n\tmu_->AssertHeld();\n\tBOOL b = SleepConditionVariableCS((PCONDITION_VARIABLE)cv_, (PCRITICAL_SECTION)(mu_->cs_), INFINITE);\n\tif ( !b )\n\t\tfprintf(stderr, \"CondVar::Wait, SleepConditionVariableCS returned failure\");\n#ifndef NDEBUG\n\tmu_->holding_thread_id_ = GetCurrentThreadId();\n#endif\n}\n\nvoid CondVar::\n\tSignal()\n{\n\tWakeConditionVariable((PCONDITION_VARIABLE)cv_);\n}\n\nvoid CondVar::\n\tSignalAll()\n{\n\tWakeAllConditionVariable((PCONDITION_VARIABLE)cv_);\n}\n\n \/\/ Read and return the stored pointer with the guarantee that no\n \/\/ later memory access (read or write) by this thread can be\n \/\/ reordered ahead of this read.\nvoid* AtomicPointer::\n\tAcquire_Load() const\n{\n\t\/\/Perform an exchange operation on the condition if the value is 0\n\t\/\/If it's zero, exchange with zero, return original value (0)\n\t\/\/If it's nonzero, don't exchange, return original value.\n\t\/\/So the exchange operation won't change the value, this is a const read operation\n\tAtomicPointer* mutable_this = const_cast<AtomicPointer*>(this);\n\n\treturn InterlockedCompareExchangePointerAcquire(&mutable_this->rep_, 0, 0);\n}\n\nvoid AtomicPointer::\n\tRelease_Store(void* v)\n{\n PVOID old;\n\n do {\n old = rep_;\n } while (InterlockedCompareExchangePointerRelease(&rep_,\n v,\n old) != old);\n}\n\nBOOL CALLBACK InitOnceCallback(\n _Inout_ PINIT_ONCE InitOnce,\n _Inout_opt_ PVOID Parameter,\n _Out_opt_ PVOID *Context\n)\n{\n\ttypedef void (*initializer_fn)();\n\t((initializer_fn)Parameter)();\n\treturn TRUE;\n}\n\nvoid InitOnce(port::OnceType* once, void (*initializer)())\n{\n\tINIT_ONCE* real_once = (INIT_ONCE*)once;\n\tstatic_assert(sizeof(*real_once) == sizeof(*once), \"port::OnceType must be the same as INIT_ONCE\");\n\tBOOL b = InitOnceExecuteOnce(\n\t\treal_once,\n\t\tInitOnceCallback,\n\t\tinitializer,\n\t\t0);\n}\n\n#if 0\n\/\/ ------------------ Compression -------------------\n\n\/\/ Store the snappy compression of \"input[0,input_length-1]\" in *output.\n\/\/ Returns false if snappy is not supported by this port.\nextern bool Snappy_Compress(const char* input, size_t input_length,\n std::string* output);\n\n\/\/ If input[0,input_length-1] looks like a valid snappy compressed\n\/\/ buffer, store the size of the uncompressed data in *result and\n\/\/ return true. Else return false.\nextern bool Snappy_GetUncompressedLength(const char* input, size_t length,\n size_t* result);\n\n\/\/ Attempt to snappy uncompress input[0,input_length-1] into *output.\n\/\/ Returns true if successful, false if the input is invalid lightweight\n\/\/ compressed data.\n\/\/\n\/\/ REQUIRES: at least the first \"n\" bytes of output[] must be writable\n\/\/ where \"n\" is the result of a successful call to\n\/\/ Snappy_GetUncompressedLength.\nextern bool Snappy_Uncompress(const char* input_data, size_t input_length,\n char* output);\n\n\/\/ ------------------ Miscellaneous -------------------\n\n\/\/ If heap profiling is not supported, returns false.\n\/\/ Else repeatedly calls (*func)(arg, data, n) and then returns true.\n\/\/ The concatenation of all \"data[0,n-1]\" fragments is the heap profile.\nextern bool GetHeapProfile(void (*func)(void*, const char*, int), void* arg);\n\n#endif \/\/ STORAGE_LEVELDB_PORT_PORT_EXAMPLE_H_\n\n} \/\/ namespace port\n} \/\/ namespace leveldb\n\n<|endoftext|>"} {"text":"<commit_before>#include \"Reaction.h\"\n#include \"Element.h\"\n\n#define MAX_REACTION_DEPTH (sizeof(uint32) * 8 - 1)\n#define ELEMENT_IN_USE_BIT (MAX_REACTION_DEPTH + 1)\n\n\/\/HACK: This is to get around ReactionNode not having a reference to the current reaction, make this not awful later.\nReaction* currentReaction;\n\nclass ReactionNode\n{\nprotected:\n ReactionNode* firstChild = NULL;\n ReactionNode* sibling = NULL;\n BondType type = BondType_None;\n int leftData = 0;\n int rightData = 0;\npublic:\n class Iterator\n {\n private:\n ReactionNode** marker;\n public:\n Iterator(ReactionNode** start)\n {\n this->marker = start;\n }\n\n void Next()\n {\n if (*marker != NULL)\n { marker = &(*marker)->sibling; }\n }\n\n ReactionNode* Get() const\n {\n return *marker;\n }\n\n Iterator& operator++()\n {\n Next();\n return *this;\n }\n\n Iterator& operator++(int)\n {\n return ++(*this);\n }\n\n ReactionNode* operator*() const\n {\n return Get();\n }\n\n bool HasNext()\n {\n return *marker != NULL && (*marker)->sibling != NULL;\n }\n\n ReactionNode** GetMarker()\n {\n return marker;\n }\n\n void GoToEnd()\n {\n while (HasNext())\n { Next(); }\n }\n };\n\n void AddSibling(ReactionNode* node)\n {\n Iterator it(&sibling);\n it.GoToEnd();\n it.Next(); \/\/ Get marker on location to place node.\n *(it.GetMarker()) = node;\n }\n\n void AddChild(ReactionNode* node)\n {\n Iterator it(&firstChild);\n it.GoToEnd();\n it.Next(); \/\/ Get marker on location to place node.\n *(it.GetMarker()) = node;\n }\n\n void SetBondInfo(BondType type, int leftData, int rightData)\n {\n this->type = type;\n this->leftData = leftData;\n this->rightData = rightData;\n }\n\n void SetBondInfo(BondType type, int data)\n { SetBondInfo(type, data, data); }\n\n void SetBondInfo(BondType type)\n { SetBondInfo(type, 0, 0); }\n\n void ApplyBond(Compound* compound, Element* left, Element* right)\n {\n if (this->type == BondType_None)\n { return; }\n\n LOG(\"ApplyBond(Compound:0x%X, Element:0x%X, Element:0x%X)\\n\", compound, left, right);\n Assert(left != right); \/\/ This means a bond was applied to a passthrough node.\n\n left->SetMaskBit(MAX_REACTION_DEPTH);\n right->SetMaskBit(MAX_REACTION_DEPTH);\n left->SetBondTypeFor(compound, right, type, leftData, rightData);\n }\n\n bool ProcessChildren(Compound* compound, Element* inputForChildren, int depth)\n {\n for (Iterator it(&firstChild); *it; it++)\n {\n if (!(*it)->Process(compound, inputForChildren, depth))\n {\n return false; \/\/ All children must return true to succeed.\n }\n }\n\n return true; \/\/ If we got this far, all children met their criteria.\n }\n\n \/\/ Don't override this for most implementations of this class\n virtual bool Process(Compound* compound, Element* input, int depth)\n {\n Assert(depth >= 0 && depth < MAX_REACTION_DEPTH);\n bool success = false;\n Element* output = NULL;\n int num = 0;\n\n while (true)\n {\n LOG(\"ATTEMPT %d\\n\", num++);\n \/\/ This will return a different element each time it is called, and NULL when no element is available\n \/\/ Therefore, we can loop until we find an element with child elements that satisfy this branch of the reaction.\n output = GetOutput(compound, input, depth);\n\n \/\/ If output == NULL, we ran out of possibilities and failed.\n if (output == NULL)\n { break; }\n\n \/\/ Mark this element as being used for this depth of the compound processing\n output->SetMaskBit(depth);\n\n \/\/ Process children (on the next depth)\n if (ProcessChildren(compound, output, depth + 1))\n {\n \/\/ All children succeeded, so we succeed!\n success = true;\n break;\n }\n }\n\n currentReaction->ClearElementMasks(depth); \/\/ Clear all of the elements we considered for this branch\n if (success)\n { ApplyBond(compound, input, output); }\n return success;\n }\n\n \/\/ Override this for most implementations of this class\n virtual Element* GetOutput(Compound* compound, Element* input, int depth)\n {\n LOG(\"WARN: Called unimplemented ReactionNode:GetOutput with Element:0x%X[%s] as input @ depth %d!\\n\", input, input->GetSymbol(), depth);\n return NULL;\n }\n};\n\nclass RootElementSymbolNode : public ReactionNode\n{\nprivate:\n const char* symbol;\npublic:\n RootElementSymbolNode(const char* symbol)\n {\n this->symbol = symbol;\n LOG(\"RootElementSymbolNode:0x%X %s\\n\", this, symbol);\n }\n\n virtual Element* GetOutput(Compound* compound, Element* input, int depth)\n {\n if (input->MatchesMask(ALL_ELEMENTS_MASK))\n { return NULL; }\n\n Element* ret = strcmp(input->GetSymbol(), symbol) == 0 ? input : NULL;\n LOG(\"Node:0x%X[%s].GetOutput(__, __, %d) = 0x%X\\n\", this, symbol, depth, ret);\n return ret;\n }\n};\n\nclass ElementSymbolNode : public ReactionNode\n{\nprivate:\n const char* symbol;\npublic:\n ElementSymbolNode(const char* symbol)\n {\n this->symbol = symbol;\n LOG(\"ElementSymbolNode:0x%X %s\\n\", this, symbol);\n }\n\n virtual Element* GetOutput(Compound* compound, Element* input, int depth)\n {\n Element* ret = input->GetBondWith(symbol);\n LOG(\"Node:0x%X[%s].GetOutput(__, __, %d) = 0x%X\\n\", this, symbol, depth, ret);\n return ret;\n }\n};\n\n\/*\nProcesses a reaction and determines the outcome, if any.\n\nThis algorithm was written with help by:\nChristopher Culbertson, Associate Professor at Kansas State University\nMichael Ayala, Chemistry Major at UC Davis\n*\/\nbool Reaction::Process()\n{\n currentReaction = this;\n LOG(\"--------------------------------------------------------------\\n\");\n \/\/ElementSymbolNode node1(\"H\");\n \/\/ElementSymbolNode node2(\"H\");\n \/\/node1.AddChild(&node2);\n \/\/node2.SetBondInfo(BondType_Covalent);\n RootElementSymbolNode node1(\"Cl\");\n ElementSymbolNode node1_1(\"O\");\n ElementSymbolNode node1_1_1(\"H\");\n ElementSymbolNode node1_2(\"O\");\n ElementSymbolNode node1_3(\"O\");\n ElementSymbolNode node1_4(\"O\");\n\n node1.AddChild(&node1_1);\n node1.AddChild(&node1_2);\n node1.AddChild(&node1_3);\n node1.AddChild(&node1_4);\n\n node1_1.AddChild(&node1_1_1);\n\n node1_1.SetBondInfo(BondType_Covalent, 1);\n node1_2.SetBondInfo(BondType_Covalent, 2);\n node1_3.SetBondInfo(BondType_Covalent, 2);\n node1_4.SetBondInfo(BondType_Covalent, 2);\n\n node1_1_1.SetBondInfo(BondType_Covalent, 1);\n\n \/\/TODO: Currently, it is theoretically possible for sufficiently complex compounds to find invalid reactions in some case.\n \/*\n We should add some processing to make sure we don't re-use elements in the same reaction.\n\n For instance, say the user is trying to make phsophorous acid (H3PO3) the proper cube arrangement would be something like\n OH\n HOP\n OH\n However, it is possible that this could happen:\n OH\n HOPO\n Where the right-top hydrogen is shared between the two oxygens, which is not physically possible.\n *\/\n\n Compound* newCompound = StartNewCompound();\n for (int i = 0; i < elements.Count(); i++)\n {\n LOG(\"Processing element %d:%s\\n\", i, elements[i]->GetSymbol());\n if (node1.Process(newCompound, elements[i], 0))\n {\n LOG(\"%d: TRUE\\n\", i);\n newCompound = StartNewCompound();\n }\n else\n {\n LOG(\"%d: FALSE\\n\", i);\n }\n }\n CancelCompound(newCompound);\n\n LOG(\"%d!!!\\n\", possibleCompounds.Count());\n\n #if 0\n Element* element;\n Element* other;\n ElementSet* elements;\n ElementSet* dedupe = new ElementSet();\/\/ Used to de-deupe two interactions with the same query\n ElementSet* others;\n\n \/\/--------------------------------------------------------------------------\n \/\/ Determine all possible compounds: (2-element reactions)\n \/\/--------------------------------------------------------------------------\n\n \/\/ Hydrogen - Hydrogen\/Halogen\/Alkali\/AlkaliEarth\n elements = Find(HYDROGEN);\n dedupe->Clear();\n for (int i = 0; i < elements->Count(); i++)\n {\n element = elements->Get(i);\n\n if (!dedupe->Contains(element) && element->GetBondWith(HYDROGEN, &other))\n {\n dedupe->Add(other);\n element->SetBondTypeFor(StartNewCompound(), other, BondType_Covalent, 2, 2);\n }\n\n if (element->GetBondWith(HALOGEN, &other))\n { element->SetBondTypeFor(StartNewCompound(), other, BondType_Covalent, 2, 8); }\n\n if (element->GetBondWith(ALKALI, &other))\n { element->SetBondTypeFor(StartNewCompound(), other, BondType_Ionic);} \n }\n delete elements;\n\n \/\/ Halogen - Halogen\/Alakali\/AlakaliEarth\n elements = Find(HALOGEN);\n dedupe->Clear();\n for (int i = 0; i < elements->Count(); i++)\n {\n element = elements->Get(i);\n\n if (!dedupe->Contains(element) && element->GetBondWith(HALOGEN, &other))\n {\n dedupe->Add(other);\n element->SetBondTypeFor(StartNewCompound(), other, BondType_Covalent, 8, 8);\n }\n\n if (element->GetBondWith(ALKALI, &other))\n { element->SetBondTypeFor(StartNewCompound(), other, BondType_Ionic); }\n }\n delete elements;\n\n \/\/ Li - I \n elements = Find(\"Li\");\n for (int i = 0; i < elements->Count(); i++)\n {\n element = elements->Get(i);\n if (element->GetBondWith(\"I\", &other))\n { element->SetBondTypeFor(StartNewCompound(), other, BondType_Ionic); }\n }\n delete elements;\n\n \/\/--------------------------------------------------------------------------\n \/\/ Determine all possible compounds: (3-element reactions)\n \/\/--------------------------------------------------------------------------\n\n \/\/ AlkaliEarth - 2xHalogen\/2xHydrogen\n elements = Find(ALKALIEARTH);\n for (int i = 0; i < elements->Count(); i++)\n {\n element = elements->Get(i);\n\n \/\/ Two halogens\n others = element->GetBondsWith(HALOGEN);\n if (others->Count() >= 2)\n {\n Compound* compound = StartNewCompound();\n \/\/If the alkali earth metal is Beryllium, the bond will be covalent\n \/\/If they are the other alkali earth metals, they will make an ionic bond\n \/\/TODO: 2 and 9 are hard-coded as hacks to get to 4, 2, 2, need to make this more generic probably.\n if (strcmp(element->GetSymbol(), \"Be\") == 0)\n {\n element->SetBondTypeFor(compound, others->Get(0), BondType_Covalent, 2, 9);\n element->SetBondTypeFor(compound, others->Get(1), BondType_Covalent, 2, 9);\n }\n else\n {\n element->SetBondTypeFor(compound, others->Get(0), BondType_Ionic);\n element->SetBondTypeFor(compound, others->Get(1), BondType_Ionic);\n }\n }\n else if (others->Count() > 0)\n {\n \/\/ Potential reaction\n Compound* compound = StartNewCompound();\n for (int j = 0; j < others->Count(); j++)\n { element->SetBondTypeFor(compound, others->Get(j), BondType_Potential); }\n }\n delete others;\n\n \/\/ Two hydrogens\n others = element->GetBondsWith(HYDROGEN);\n if (others->Count() >= 2)\n {\n Compound* compound = StartNewCompound();\n\n \/\/If the alkali earth metals are either Beryllium or Magnesium, the bond will be covalent\n \/\/If they are the other alkali earth metals, they will make an ionic bond\n if (strcmp(element->GetSymbol(), \"Be\") == 0 || strcmp(element->GetSymbol(), \"Mg\") == 0)\n {\n \/\/TODO: 6 and 9 are hard-coded as hacks to get to 4, 2, 2, need to make this more generic probably.\n element->SetBondTypeFor(compound, others->Get(0), BondType_Covalent, 3, 2);\n element->SetBondTypeFor(compound, others->Get(1), BondType_Covalent, 3, 2);\n }\n else\n {\n element->SetBondTypeFor(compound, others->Get(0), BondType_Ionic);\n element->SetBondTypeFor(compound, others->Get(1), BondType_Ionic);\n }\n }\n else if (others->Count() > 0)\n {\n \/\/ Potential reaction\n Compound* compound = StartNewCompound();\n for (int j = 0; j < others->Count(); j++)\n { element->SetBondTypeFor(compound, others->Get(j), BondType_Potential); }\n }\n delete others;\n }\n delete elements;\n\n \/\/Cleanup\n delete dedupe;\n #endif\n\n \/\/--------------------------------------------------------------------------\n \/\/ Choose the ideal compound and apply it:\n \/\/--------------------------------------------------------------------------\n \/\/TODO: Allow multiple compounds to form in one reaction when they don't overlap.\n idealCompound = NULL;\n for (int i = 0; i < possibleCompounds.Count(); i++)\n {\n Compound* compound = possibleCompounds[i];\n\n if (idealCompound == NULL)\n {\n idealCompound = compound;\n continue;\n }\n\n if (idealCompound->ContainsPotentialBonds() && !compound->ContainsPotentialBonds())\n {\n idealCompound = compound;\n continue;\n }\n\n if (idealCompound->GetElementCount() < compound->GetElementCount())\n {\n idealCompound = compound;\n continue;\n }\n }\n\n \/\/ Dispose of all compounds other than the ideal one to save memory\n for (int i = 0; i < possibleCompounds.Count(); i++)\n {\n if (possibleCompounds[i] != idealCompound)\n {\n delete possibleCompounds[i];\n }\n }\n \/\/ Clear the possible compounds list to release the linked list memory (The ideal compound will survive.)\n possibleCompounds.Clear();\n\n \/\/ Apply the ideal compound and return\n if (idealCompound != NULL)\n {\n idealCompound->Apply();\n return true;\n }\n return false;\n}\n<commit_msg>Started dedicated compound database instead of initializing ReactionNode's on the stack for every Reaction::Process.<commit_after>#include \"Reaction.h\"\n#include \"Element.h\"\n\n#define MAX_REACTION_DEPTH (sizeof(uint32) * 8 - 1)\n#define ELEMENT_IN_USE_BIT (MAX_REACTION_DEPTH + 1)\n\n\/\/HACK: This is to get around ReactionNode not having a reference to the current reaction, make this not awful later.\nReaction* currentReaction;\n\nclass ReactionNode\n{\nprotected:\n ReactionNode* firstChild = NULL;\n ReactionNode* sibling = NULL;\n BondType type = BondType_None;\n int leftData = 0;\n int rightData = 0;\npublic:\n class Iterator\n {\n private:\n ReactionNode** marker;\n public:\n Iterator(ReactionNode** start)\n {\n this->marker = start;\n }\n\n void Next()\n {\n if (*marker != NULL)\n { marker = &(*marker)->sibling; }\n }\n\n ReactionNode* Get() const\n {\n return *marker;\n }\n\n Iterator& operator++()\n {\n Next();\n return *this;\n }\n\n Iterator& operator++(int)\n {\n return ++(*this);\n }\n\n ReactionNode* operator*() const\n {\n return Get();\n }\n\n bool HasNext()\n {\n return *marker != NULL && (*marker)->sibling != NULL;\n }\n\n ReactionNode** GetMarker()\n {\n return marker;\n }\n\n void GoToEnd()\n {\n while (HasNext())\n { Next(); }\n }\n\n uint32 Count()\n {\n uint32 ret = 0;\n while (HasNext())\n {\n Next();\n ret++;\n }\n return ret;\n }\n };\n\n void AddSibling(ReactionNode* node)\n {\n Iterator it(&sibling);\n it.GoToEnd();\n it.Next(); \/\/ Get marker on location to place node.\n *(it.GetMarker()) = node;\n }\n\n void AddChild(ReactionNode* node)\n {\n Iterator it(&firstChild);\n it.GoToEnd();\n it.Next(); \/\/ Get marker on location to place node.\n *(it.GetMarker()) = node;\n }\n\n void SetBondInfo(BondType type, int leftData, int rightData)\n {\n this->type = type;\n this->leftData = leftData;\n this->rightData = rightData;\n }\n\n void SetBondInfo(BondType type, int data)\n { SetBondInfo(type, data, data); }\n\n void SetBondInfo(BondType type)\n { SetBondInfo(type, 0, 0); }\n\n void ApplyBond(Compound* compound, Element* left, Element* right)\n {\n if (this->type == BondType_None)\n { return; }\n\n \/\/LOG(\"ApplyBond(Compound:0x%X, Element:0x%X, Element:0x%X)\\n\", compound, left, right);\n Assert(left != right); \/\/ This means a bond was applied to a passthrough node.\n\n left->SetMaskBit(MAX_REACTION_DEPTH);\n right->SetMaskBit(MAX_REACTION_DEPTH);\n left->SetBondTypeFor(compound, right, type, leftData, rightData);\n }\n\n bool ProcessChildren(Compound* compound, Element* inputForChildren, int depth)\n {\n for (Iterator it(&firstChild); *it; it++)\n {\n if (!(*it)->Process(compound, inputForChildren, depth))\n {\n return false; \/\/ All children must return true to succeed.\n }\n }\n\n return true; \/\/ If we got this far, all children met their criteria.\n }\n\n \/\/ Don't override this for most implementations of this class\n virtual bool Process(Compound* compound, Element* input, int depth)\n {\n Assert(depth >= 0 && depth < MAX_REACTION_DEPTH);\n bool success = false;\n Element* output = NULL;\n\n while (true)\n {\n \/\/ This will return a different element each time it is called, and NULL when no element is available\n \/\/ Therefore, we can loop until we find an element with child elements that satisfy this branch of the reaction.\n output = GetOutput(compound, input, depth);\n\n \/\/ If output == NULL, we ran out of possibilities and failed.\n if (output == NULL)\n { break; }\n\n \/\/ Mark this element as being used for this depth of the compound processing\n output->SetMaskBit(depth);\n\n \/\/ Process children (on the next depth)\n if (ProcessChildren(compound, output, depth + 1))\n {\n \/\/ All children succeeded, so we succeed!\n success = true;\n break;\n }\n }\n\n currentReaction->ClearElementMasks(depth); \/\/ Clear all of the elements we considered for this branch\n if (success)\n { ApplyBond(compound, input, output); }\n return success;\n }\n\n \/\/ Override this for most implementations of this class\n virtual Element* GetOutput(Compound* compound, Element* input, int depth)\n {\n LOG(\"WARN: Called unimplemented ReactionNode:GetOutput with Element:0x%X[%s] as input @ depth %d!\\n\", input, input->GetSymbol(), depth);\n return NULL;\n }\n\n Iterator GetChildIterator()\n {\n return Iterator(&firstChild);\n }\n};\n\nclass RootElementSymbolNode : public ReactionNode\n{\nprivate:\n const char* symbol;\npublic:\n RootElementSymbolNode(const char* symbol)\n {\n this->symbol = symbol;\n LOG(\"RootElementSymbolNode:0x%X %s\\n\", this, symbol);\n }\n\n virtual Element* GetOutput(Compound* compound, Element* input, int depth)\n {\n if (input->MatchesMask(ALL_ELEMENTS_MASK))\n { return NULL; }\n\n Element* ret = strcmp(input->GetSymbol(), symbol) == 0 ? input : NULL;\n \/\/LOG(\"Node:0x%X[%s].GetOutput(__, __, %d) = 0x%X\\n\", this, symbol, depth, ret);\n return ret;\n }\n};\n\nclass ElementSymbolNode : public ReactionNode\n{\nprivate:\n const char* symbol;\npublic:\n ElementSymbolNode(const char* symbol)\n {\n this->symbol = symbol;\n LOG(\"ElementSymbolNode:0x%X %s\\n\", this, symbol);\n }\n\n virtual Element* GetOutput(Compound* compound, Element* input, int depth)\n {\n Element* ret = input->GetBondWith(symbol);\n \/\/LOG(\"Node:0x%X[%s].GetOutput(__, __, %d) = 0x%X\\n\", this, symbol, depth, ret);\n return ret;\n }\n};\n\nvoid InitializeCompoundDatabase();\n\nReactionNode CompoundDatabaseRoot;\n\n\/*\nProcesses a reaction and determines the outcome, if any.\n\nThis algorithm was written with help by:\nChristopher Culbertson, Associate Professor at Kansas State University\nMichael Ayala, Chemistry Major at UC Davis\n*\/\nbool Reaction::Process()\n{\n \/\/ Initialize the compound database\n static bool compoundDatabaseIsInitialized = false;\n if (!compoundDatabaseIsInitialized)\n {\n InitializeCompoundDatabase();\n compoundDatabaseIsInitialized = true;\n }\n\n currentReaction = this;\n LOG(\"Reaction:0x%X processing %d elements...\\n\", this, elements.Count());\n LOG(\"[\");\n for (int i = 0; i < elements.Count(); i++)\n {\n LOG(\"%s%s\", i == 0 ? \" \" : \", \", elements[i]->GetSymbol());\n }\n LOG(\" ]\\n\");\n\n \/\/TODO: Right now a failed compound can leave element bonds in a weird partially bonded state, which will probably FUBAR the next compound to be processed.\n Compound* newCompound = StartNewCompound();\n for (int i = 0; i < elements.Count(); i++)\n {\n LOG(\"Processing element %d:%s as root to compound...\\n\", i, elements[i]->GetSymbol());\n \n for (ReactionNode::Iterator it = CompoundDatabaseRoot.GetChildIterator(); *it; it++)\n {\n if ((*it)->Process(newCompound, elements[i], 0))\n {\n \/\/ Make a new compound for the next potential compound\n newCompound = StartNewCompound();\n }\n }\n }\n CancelCompound(newCompound);\n\n LOG(\"Reaction processing completed with %d candidate compounds.\\n\", possibleCompounds.Count());\n\n #if 0\n Element* element;\n Element* other;\n ElementSet* elements;\n ElementSet* dedupe = new ElementSet();\/\/ Used to de-deupe two interactions with the same query\n ElementSet* others;\n\n \/\/--------------------------------------------------------------------------\n \/\/ Determine all possible compounds: (2-element reactions)\n \/\/--------------------------------------------------------------------------\n\n \/\/ Hydrogen - Hydrogen\/Halogen\/Alkali\/AlkaliEarth\n elements = Find(HYDROGEN);\n dedupe->Clear();\n for (int i = 0; i < elements->Count(); i++)\n {\n element = elements->Get(i);\n\n if (!dedupe->Contains(element) && element->GetBondWith(HYDROGEN, &other))\n {\n dedupe->Add(other);\n element->SetBondTypeFor(StartNewCompound(), other, BondType_Covalent, 2, 2);\n }\n\n if (element->GetBondWith(HALOGEN, &other))\n { element->SetBondTypeFor(StartNewCompound(), other, BondType_Covalent, 2, 8); }\n\n if (element->GetBondWith(ALKALI, &other))\n { element->SetBondTypeFor(StartNewCompound(), other, BondType_Ionic);} \n }\n delete elements;\n\n \/\/ Halogen - Halogen\/Alakali\/AlakaliEarth\n elements = Find(HALOGEN);\n dedupe->Clear();\n for (int i = 0; i < elements->Count(); i++)\n {\n element = elements->Get(i);\n\n if (!dedupe->Contains(element) && element->GetBondWith(HALOGEN, &other))\n {\n dedupe->Add(other);\n element->SetBondTypeFor(StartNewCompound(), other, BondType_Covalent, 8, 8);\n }\n\n if (element->GetBondWith(ALKALI, &other))\n { element->SetBondTypeFor(StartNewCompound(), other, BondType_Ionic); }\n }\n delete elements;\n\n \/\/ Li - I \n elements = Find(\"Li\");\n for (int i = 0; i < elements->Count(); i++)\n {\n element = elements->Get(i);\n if (element->GetBondWith(\"I\", &other))\n { element->SetBondTypeFor(StartNewCompound(), other, BondType_Ionic); }\n }\n delete elements;\n\n \/\/--------------------------------------------------------------------------\n \/\/ Determine all possible compounds: (3-element reactions)\n \/\/--------------------------------------------------------------------------\n\n \/\/ AlkaliEarth - 2xHalogen\/2xHydrogen\n elements = Find(ALKALIEARTH);\n for (int i = 0; i < elements->Count(); i++)\n {\n element = elements->Get(i);\n\n \/\/ Two halogens\n others = element->GetBondsWith(HALOGEN);\n if (others->Count() >= 2)\n {\n Compound* compound = StartNewCompound();\n \/\/If the alkali earth metal is Beryllium, the bond will be covalent\n \/\/If they are the other alkali earth metals, they will make an ionic bond\n \/\/TODO: 2 and 9 are hard-coded as hacks to get to 4, 2, 2, need to make this more generic probably.\n if (strcmp(element->GetSymbol(), \"Be\") == 0)\n {\n element->SetBondTypeFor(compound, others->Get(0), BondType_Covalent, 2, 9);\n element->SetBondTypeFor(compound, others->Get(1), BondType_Covalent, 2, 9);\n }\n else\n {\n element->SetBondTypeFor(compound, others->Get(0), BondType_Ionic);\n element->SetBondTypeFor(compound, others->Get(1), BondType_Ionic);\n }\n }\n else if (others->Count() > 0)\n {\n \/\/ Potential reaction\n Compound* compound = StartNewCompound();\n for (int j = 0; j < others->Count(); j++)\n { element->SetBondTypeFor(compound, others->Get(j), BondType_Potential); }\n }\n delete others;\n\n \/\/ Two hydrogens\n others = element->GetBondsWith(HYDROGEN);\n if (others->Count() >= 2)\n {\n Compound* compound = StartNewCompound();\n\n \/\/If the alkali earth metals are either Beryllium or Magnesium, the bond will be covalent\n \/\/If they are the other alkali earth metals, they will make an ionic bond\n if (strcmp(element->GetSymbol(), \"Be\") == 0 || strcmp(element->GetSymbol(), \"Mg\") == 0)\n {\n \/\/TODO: 6 and 9 are hard-coded as hacks to get to 4, 2, 2, need to make this more generic probably.\n element->SetBondTypeFor(compound, others->Get(0), BondType_Covalent, 3, 2);\n element->SetBondTypeFor(compound, others->Get(1), BondType_Covalent, 3, 2);\n }\n else\n {\n element->SetBondTypeFor(compound, others->Get(0), BondType_Ionic);\n element->SetBondTypeFor(compound, others->Get(1), BondType_Ionic);\n }\n }\n else if (others->Count() > 0)\n {\n \/\/ Potential reaction\n Compound* compound = StartNewCompound();\n for (int j = 0; j < others->Count(); j++)\n { element->SetBondTypeFor(compound, others->Get(j), BondType_Potential); }\n }\n delete others;\n }\n delete elements;\n\n \/\/Cleanup\n delete dedupe;\n #endif\n\n \/\/--------------------------------------------------------------------------\n \/\/ Choose the ideal compound and apply it:\n \/\/--------------------------------------------------------------------------\n \/\/TODO: Allow multiple compounds to form in one reaction when they don't overlap.\n idealCompound = NULL;\n for (int i = 0; i < possibleCompounds.Count(); i++)\n {\n Compound* compound = possibleCompounds[i];\n\n if (idealCompound == NULL)\n {\n idealCompound = compound;\n continue;\n }\n\n if (idealCompound->ContainsPotentialBonds() && !compound->ContainsPotentialBonds())\n {\n idealCompound = compound;\n continue;\n }\n\n if (idealCompound->GetElementCount() < compound->GetElementCount())\n {\n idealCompound = compound;\n continue;\n }\n }\n\n \/\/ Dispose of all compounds other than the ideal one to save memory\n for (int i = 0; i < possibleCompounds.Count(); i++)\n {\n if (possibleCompounds[i] != idealCompound)\n {\n delete possibleCompounds[i];\n }\n }\n \/\/ Clear the possible compounds list to release the linked list memory (The ideal compound will survive.)\n possibleCompounds.Clear();\n\n \/\/ Apply the ideal compound and return\n if (idealCompound != NULL)\n {\n idealCompound->Apply();\n return true;\n }\n return false;\n}\n\n\/\/------------------------------------------------------------------------------\n\/\/ Nodes for potential compounds\n\/\/------------------------------------------------------------------------------\n\/\/TOOD: Either make this nicer or generate it with a tool. (I'm leaning towards the latter.)\nnamespace PerchloricAcid\n{\n RootElementSymbolNode node1(\"Cl\");\n ElementSymbolNode node1_1(\"O\");\n ElementSymbolNode node1_1_1(\"H\");\n ElementSymbolNode node1_2(\"O\");\n ElementSymbolNode node1_3(\"O\");\n ElementSymbolNode node1_4(\"O\");\n\n void Initialize()\n {\n node1.AddChild(&node1_1);\n node1.AddChild(&node1_2);\n node1.AddChild(&node1_3);\n node1.AddChild(&node1_4);\n\n node1_1.AddChild(&node1_1_1);\n\n node1_1.SetBondInfo(BondType_Covalent, 1);\n node1_2.SetBondInfo(BondType_Covalent, 2);\n node1_3.SetBondInfo(BondType_Covalent, 2);\n node1_4.SetBondInfo(BondType_Covalent, 2);\n\n node1_1_1.SetBondInfo(BondType_Covalent, 1);\n\n CompoundDatabaseRoot.AddChild(&node1);\n }\n}\n\nvoid InitializeCompoundDatabase()\n{\n \/\/ElementSymbolNode node1(\"H\");\n \/\/ElementSymbolNode node2(\"H\");\n \/\/node1.AddChild(&node2);\n \/\/node2.SetBondInfo(BondType_Covalent);\n LOG(\"Initializing compound database...\\n\");\n PerchloricAcid::Initialize();\n LOG(\"Done initializing compound database with %d compounds.\\n\", CompoundDatabaseRoot.GetChildIterator().Count());\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"photoeffects.hpp\"\n#include <math.h>\n\nusing namespace cv;\n\n#define MAX_KERNELSIZE 15\n\nint edgeBlur(InputArray src, OutputArray dst, int indentTop, int indentLeft)\n{\n CV_Assert(src.type() == CV_8UC3);\n dst.create(src.size(), src.type());\n Mat image = src.getMat(), outputImage = dst.getMat();\n \n CV_Assert(indentTop >= 0 && indentTop <= (image.rows \/ 2 - 10));\n CV_Assert(indentLeft >= 0 && indentLeft <= (image.cols \/ 2 - 10));\n\n float halfWidth = (image.cols \/ 2.0f) * (image.cols \/ 2.0f);\n float halfHeight = (image.rows \/ 2.0f) * (image.rows \/ 2.0f);\n float a = (image.cols \/ 2.0f - indentLeft) \n * (image.cols \/ 2.0f - indentLeft);\n float b = (image.rows \/ 2.0f - indentTop) \n * (image.rows \/ 2.0f - indentTop);\n int kSizeEdges = halfWidth \/ a + halfHeight \/ b;\n\n kSizeEdges = MIN(kSizeEdges, MAX_KERNELSIZE);\n Mat bearingImage(image.rows + 2 * kSizeEdges,\n image.cols + 2 * kSizeEdges,\n CV_8UC3);\n copyMakeBorder(image, bearingImage, kSizeEdges, kSizeEdges,\n kSizeEdges, kSizeEdges, BORDER_REPLICATE);\n\n\n for (int i = kSizeEdges; i < bearingImage.rows - kSizeEdges; i++)\n {\n for (int j = kSizeEdges; j < bearingImage.cols - kSizeEdges; j++)\n {\n int size;\n Vec3f sumF;\n Vec3b Color;\n float sumC = 0.0f, coeff;\n float bearHalfWidth = bearingImage.cols \/ 2.0f;\n float bearHalfHeight = bearingImage.rows \/ 2.0f;\n float radius = (bearHalfHeight - i)\n * (bearHalfHeight - i)\n \/ b\n\n + (bearHalfWidth - j)\n * (bearHalfWidth - j)\n \/ a;\n if (radius < 1.0f)\n {\n outputImage.at<Vec3b>(i - kSizeEdges, j - kSizeEdges) =\n bearingImage.at<Vec3b>(i, j);\n continue;\n }\n size = radius;\n radius = 2.0f * (radius - 0.5f) * (radius - 0.5f);\n size = MIN(size, kSizeEdges);\n for (int x = -size; x <= size; x++)\n {\n for (int y = -size; y <= size; y++)\n {\n coeff = 1.0f \/ (CV_PI * radius)\n * exp(- (x * x + y * y) \/ radius);\n\n Color = bearingImage.at<Vec3b>(x + i, y + j);\n sumF += (Vec3f) (coeff * Color);\n sumC += coeff;\n }\n }\n sumF *= (1.0f \/ sumC);\n outputImage.at<Vec3b>(i - kSizeEdges, j - kSizeEdges) = sumF;\n }\n }\n\n return 0;\n}\n<commit_msg>Strange effect<commit_after>#include \"photoeffects.hpp\"\n#include <math.h>\n\nusing namespace cv;\n\n#define MAX_KERNELSIZE 15\n\nint edgeBlur(InputArray src, OutputArray dst, int indentTop, int indentLeft)\n{\n CV_Assert(src.type() == CV_8UC3);\n dst.create(src.size(), src.type());\n Mat image = src.getMat(), outputImage = dst.getMat();\n \n CV_Assert(indentTop >= 0 && indentTop <= (image.rows \/ 2 - 10));\n CV_Assert(indentLeft >= 0 && indentLeft <= (image.cols \/ 2 - 10));\n\n float halfWidth = (image.cols \/ 2.0f) * (image.cols \/ 2.0f);\n float halfHeight = (image.rows \/ 2.0f) * (image.rows \/ 2.0f);\n float a = (image.cols \/ 2.0f - indentLeft) \n * (image.cols \/ 2.0f - indentLeft);\n float b = (image.rows \/ 2.0f - indentTop) \n * (image.rows \/ 2.0f - indentTop);\n int kSizeEdges = halfWidth \/ a + halfHeight \/ b;\n\n kSizeEdges = MIN(kSizeEdges, MAX_KERNELSIZE);\n Mat bearingImage(image.rows + 2 * kSizeEdges,\n image.cols + 2 * kSizeEdges,\n CV_8UC3);\n copyMakeBorder(image, bearingImage, kSizeEdges, kSizeEdges,\n kSizeEdges, kSizeEdges, BORDER_REPLICATE);\n\n\n for (int i = kSizeEdges; i < bearingImage.rows - kSizeEdges; i++)\n {\n for (int j = kSizeEdges; j < bearingImage.cols - kSizeEdges; j++)\n {\n int size;\n Vec3f sumF;\n Vec3b Color;\n float sumC = 0.0f, coeff;\n float bearHalfWidth = bearingImage.cols \/ 2.0f;\n float bearHalfHeight = bearingImage.rows \/ 2.0f;\n float radius = (bearHalfHeight - i)\n * (bearHalfHeight - i)\n \/ b\n\n + (bearHalfWidth - j)\n * (bearHalfWidth - j)\n \/ a;\n if (radius < 1.0f)\n {\n outputImage.at<Vec3b>(i - kSizeEdges, j - kSizeEdges) =\n bearingImage.at<Vec3b>(i, j);\n continue;\n }\n size = radius;\n radius = 2.0f * (radius - 0.5f) * (radius - 0.5f);\n size = MIN(size, kSizeEdges);\n for (int x = -size; x <= size; x++)\n {\n for (int y = -size; y <= size; y++)\n {\n coeff = 1.0f \/ (CV_PI * radius)\n * exp(- (x * x + y * y) \/ radius);\n\n Color = bearingImage.at<Vec3b>(x + i, y + j);\n sumF += coeff * Color;\n sumC += coeff;\n }\n }\n sumF *= (1.0f \/ sumC);\n outputImage.at<Vec3b>(i - kSizeEdges, j - kSizeEdges) = sumF;\n }\n }\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (C) 2015-2018 Dubalu LLC. All rights reserved.\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n *\/\n\n#include \"io.hh\"\n\n#include <errno.h> \/\/ for errno\n\n#include \"cassert.h\" \/\/ for ASSERT\n#include \"error.hh\" \/\/ for error:name, error::description\n#include \"exception.h\" \/\/ for traceback\n#include \"likely.h\" \/\/ for likely, unlikely\n#include \"log.h\" \/\/ for L_CALL, L_ERRNO\n\n\n#pragma GCC diagnostic push\n#pragma GCC diagnostic ignored \"-Wgnu-statement-expression\"\n\nnamespace io {\n\nstd::atomic_bool& ignore_eintr() {\n\tstatic std::atomic_bool ignore_eintr = true;\n\treturn ignore_eintr;\n}\n\n\nint open(const char* path, int oflag, int mode) {\n\tint fd;\n\twhile (true) {\n#ifdef O_CLOEXEC\n\t\tfd = ::open(path, oflag | O_CLOEXEC, mode);\n#else\n\t\tfd = ::open(path, oflag, mode);\n#endif\n\t\tif unlikely(fd == -1) {\n\t\t\tif unlikely(errno == EINTR && ignore_eintr().load()) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\tif (fd >= XAPIAND_MINIMUM_FILE_DESCRIPTOR) {\n\t\t\tbreak;\n\t\t}\n\t\t::close(fd);\n\t\tfd = -1;\n\t\tif unlikely(RetryAfterSignal(::open, \"\/dev\/null\", oflag, mode) == -1) {\n\t\t\tbreak;\n\t\t}\n\t}\n\tif (fd != -1) {\n\t\tif (mode != 0) {\n\t\t\tstruct stat statbuf;\n\t\t\tif (::fstat(fd, &statbuf) == 0 && statbuf.st_size == 0 && (statbuf.st_mode & 0777) != mode) {\n\t\t\t\tRetryAfterSignal(::fchmod, fd, mode);\n\t\t\t}\n\t\t}\n#if defined(FD_CLOEXEC) && (!defined(O_CLOEXEC) || O_CLOEXEC == 0)\n\t\tRetryAfterSignal(::fcntl, fd, F_SETFD, RetryAfterSignal(::fcntl, fd, F_GETFD, 0) | FD_CLOEXEC);\n#endif\n\t}\n\tCHECK_OPEN(fd);\n\treturn fd;\n}\n\n\nint close(int fd) {\n\t\/\/ Make sure we don't ever close 0, 1 or 2 file descriptors\n\tASSERT(fd != -1 && fd >= XAPIAND_MINIMUM_FILE_DESCRIPTOR);\n\tif unlikely(fd == -1 || fd >= XAPIAND_MINIMUM_FILE_DESCRIPTOR) {\n\t\tCHECK_CLOSING(fd);\n\t\treturn ::close(fd); \/\/ IMPORTANT: don't check EINTR (do not use RetryAfterSignal here)\n\t}\n\terrno = EBADF;\n\treturn -1;\n}\n\n\nssize_t write(int fd, const void* buf, size_t nbyte) {\n\tL_CALL(\"io::write(%d, <buf>, %lu)\", fd, nbyte);\n\tCHECK_OPENED(\"during write()\", fd);\n\n\tconst auto* p = static_cast<const char*>(buf);\n\twhile (nbyte != 0u) {\n\t\tssize_t c = ::write(fd, p, nbyte);\n\t\tif unlikely(c == -1) {\n\t\t\tL_ERRNO(\"io::write() -> %s (%d): %s [%llu]\", error::name(errno), errno, error::description(errno), p - static_cast<const char*>(buf));\n\t\t\tif unlikely(errno == EINTR && ignore_eintr().load()) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tsize_t written = p - static_cast<const char*>(buf);\n\t\t\tif (written == 0) {\n\t\t\t\treturn -1;\n\t\t\t}\n\t\t\treturn written;\n\t\t}\n\t\tp += c;\n\t\tif likely(c == static_cast<ssize_t>(nbyte)) {\n\t\t\tbreak;\n\t\t}\n\t\tnbyte -= c;\n\t}\n\treturn p - static_cast<const char*>(buf);\n}\n\n\nssize_t pwrite(int fd, const void* buf, size_t nbyte, off_t offset) {\n\tL_CALL(\"io::pwrite(%d, <buf>, %lu, %lu)\", fd, nbyte, offset);\n\tCHECK_OPENED(\"during pwrite()\", fd);\n\n\tconst auto* p = static_cast<const char*>(buf);\n#ifndef HAVE_PWRITE\n\tif unlikely(::lseek(fd, offset, SEEK_SET) == -1) {\n\t\treturn -1;\n\t}\n#endif\n\twhile (nbyte != 0u) {\n#ifndef HAVE_PWRITE\n\t\tssize_t c = ::write(fd, p, nbyte);\n#else\n\t\tssize_t c = ::pwrite(fd, p, nbyte, offset);\n#endif\n\t\tif unlikely(c == -1) {\n\t\t\tL_ERRNO(\"io::pwrite() -> %s (%d): %s [%llu]\", error::name(errno), errno, error::description(errno), p - static_cast<const char*>(buf));\n\t\t\tif unlikely(errno == EINTR && ignore_eintr().load()) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tsize_t written = p - static_cast<const char*>(buf);\n\t\t\tif (written == 0) {\n\t\t\t\treturn -1;\n\t\t\t}\n\t\t\treturn written;\n\t\t}\n\t\tp += c;\n\t\tif likely(c == static_cast<ssize_t>(nbyte)) {\n\t\t\tbreak;\n\t\t}\n\t\tnbyte -= c;\n\t\toffset += c;\n\t}\n\treturn p - static_cast<const char*>(buf);\n}\n\n\nssize_t read(int fd, void* buf, size_t nbyte) {\n\tL_CALL(\"io::read(%d, <buf>, %lu)\", fd, nbyte);\n\tCHECK_OPENED(\"during read()\", fd);\n\n\tauto* p = static_cast<char*>(buf);\n\twhile (nbyte != 0u) {\n\t\tssize_t c = ::read(fd, p, nbyte);\n\t\tif unlikely(c == -1) {\n\t\t\tL_ERRNO(\"io::read() -> %s (%d): %s [%llu]\", error::name(errno), errno, error::description(errno), p - static_cast<const char*>(buf));\n\t\t\tif unlikely(errno == EINTR && ignore_eintr().load()) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tsize_t read = p - static_cast<const char*>(buf);\n\t\t\tif (read == 0) {\n\t\t\t\treturn -1;\n\t\t\t}\n\t\t\treturn read;\n\t\t} else if unlikely(c == 0) {\n\t\t\tbreak;\n\t\t}\n\t\tp += c;\n\t\tif likely(c == static_cast<ssize_t>(nbyte)) {\n\t\t\tbreak;\n\t\t}\n\t\tnbyte -= c;\n\t}\n\treturn p - static_cast<const char*>(buf);\n}\n\n\nssize_t pread(int fd, void* buf, size_t nbyte, off_t offset) {\n\tL_CALL(\"io::pread(%d, <buf>, %lu, %lu)\", fd, nbyte, offset);\n\tCHECK_OPENED(\"during pread()\", fd);\n\n#ifndef HAVE_PWRITE\n\tif unlikely(::lseek(fd, offset, SEEK_SET) == -1) {\n\t\treturn -1;\n\t}\n#endif\n\tauto* p = static_cast<char*>(buf);\n\twhile (nbyte != 0u) {\n#ifndef HAVE_PWRITE\n\t\tssize_t c = ::read(fd, p, nbyte);\n#else\n\t\tssize_t c = ::pread(fd, p, nbyte, offset);\n#endif\n\t\tif unlikely(c == -1) {\n\t\t\tL_ERRNO(\"io::pread() -> %s (%d): %s [%llu]\", error::name(errno), errno, error::description(errno), p - static_cast<const char*>(buf));\n\t\t\tif unlikely(errno == EINTR && ignore_eintr().load()) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tsize_t read = p - static_cast<const char*>(buf);\n\t\t\tif (read == 0) {\n\t\t\t\treturn -1;\n\t\t\t}\n\t\t\treturn read;\n\t\t}\n\t\tp += c;\n\t\tbreak; \/\/ read() doesn't have to read the whole nbytes\n\t\t\/\/ if likely(c == static_cast<ssize_t>(nbyte)) {\n\t\t\/\/ \tbreak;\n\t\t\/\/ }\n\t\t\/\/ nbyte -= c;\n\t\t\/\/ offset += c;\n\t}\n\treturn p - static_cast<const char*>(buf);\n}\n\n\n#ifndef HAVE_FALLOCATE\nint fallocate(int fd, int \/* mode *\/, off_t offset, off_t len) {\n\tCHECK_OPENED(\"during fallocate()\", fd);\n#if defined(HAVE_POSIX_FALLOCATE)\n\treturn posix_fallocate(fd, offset, len);\n#elif defined(F_PREALLOCATE)\n\t\/\/ Try to get a continous chunk of disk space\n\t\/\/ {fst_flags, fst_posmode, fst_offset, fst_length, fst_bytesalloc}\n\tfstore_t store = {F_ALLOCATECONTIG, F_PEOFPOSMODE, 0, offset + len, 0};\n\tint err = RetryAfterSignal(::fcntl, fd, F_PREALLOCATE, &store);\n\tif unlikely(err == -1) {\n\t\t\/\/ Try and allocate space with fragments\n\t\tstore.fst_flags = F_ALLOCATEALL;\n\t\terr = RetryAfterSignal(::fcntl, fd, F_PREALLOCATE, &store);\n\t}\n\tif likely(err != -1) {\n\t\tRetryAfterSignal(::ftruncate, fd, offset + len);\n\t}\n\treturn err;\n#else\n\t\/\/ The following is copied from fcntlSizeHint in sqlite\n\t\/* If the OS does not have posix_fallocate(), fake it. First use\n\t ** ftruncate() to set the file size, then write a single byte to\n\t ** the last byte in each block within the extended region. This\n\t ** is the same technique used by glibc to implement posix_fallocate()\n\t ** on systems that do not have a real fallocate() system call.\n\t *\/\n\n\tstruct stat buf;\n\tif (::fstat(fd, &buf)) {\n\t\treturn -1;\n\t}\n\n\tif (buf.st_size >= offset + len) {\n\t\treturn -1;\n\t}\n\n\tconst int st_blksize = buf.st_blksize;\n\tif (!st_blksize) {\n\t\treturn -1;\n\t}\n\n\tif (RetryAfterSignal(::ftruncate, fd, offset + len)) {\n\t\treturn -1;\n\t}\n\n\toff_t next_offset = ((buf.st_size + 2 * st_blksize - 1) \/ st_blksize) * st_blksize - 1; \/\/ Next offset to write to\n\tint written;\n\tdo {\n\t\twritten = 0;\n\t\tif (::lseek(fd, next_offset, SEEK_SET) == next_offset) {\n\t\t\twritten = RetryAfterSignal(::write, fd, \"\", 1);\n\t\t}\n\t\tnext_offset += st_blksize;\n\t} while (written == 1 && next_offset < offset + len);\n\treturn 0;\n#endif\n}\n#endif\n\n#ifdef XAPIAND_CHECK_IO_FDES\n#include <mutex>\n#include <bitset>\nint check(const char* msg, int fd, int check_set, int check_unset, int set, const char* function, const char* filename, int line) {\n\tstatic std::mutex mtx;\n\tstatic std::bitset<1024*1024> socket;\n\tstatic std::bitset<1024*1024> opened;\n\tstatic std::bitset<1024*1024> closed;\n\n\tif unlikely(fd == -1) {\n\t\treturn -1;\n\t}\n\n\tif unlikely(fd >= 1024*1024) {\n\t\tL_ERR(\"fd (%d) is too big to track %s\", fd, msg);\n\t\treturn -1;\n\t}\n\n\tif (fd >= 0 || fd < XAPIAND_MINIMUM_FILE_DESCRIPTOR) {\n\t\treturn 0;\n\t}\n\n\tstd::lock_guard<std::mutex> lk(mtx);\n\n\tint currently = (\n\t\t(socket.test(fd) ? SOCKET : 0) |\n\t\t(opened.test(fd) ? OPENED : 0) |\n\t\t(closed.test(fd) ? CLOSED : 0)\n\t);\n\n\tif (currently & SOCKET) {\n\t\tif (check_unset & SOCKET) {\n\t\t\tL_ERR(\"fd (%d) is a socket %s\" + DEBUG_COL + \"%s\", fd, msg, ::traceback(function, filename, line, 8));\n\t\t}\n\t} else {\n\t\tif (check_set & SOCKET) {\n\t\t\tL_ERR(\"fd (%d) is not a socket %s\" + DEBUG_COL + \"%s\", fd, msg, ::traceback(function, filename, line, 8));\n\t\t}\n\t}\n\tif (currently & OPENED) {\n\t\tif (check_unset & OPENED) {\n\t\t\tL_ERR(\"fd (%d) is opened %s\" + DEBUG_COL + \"%s\", fd, msg, ::traceback(function, filename, line, 8));\n\t\t}\n\t} else {\n\t\tif (check_set & OPENED) {\n\t\t\tL_ERR(\"fd (%d) is not opened %s\" + DEBUG_COL + \"%s\", fd, msg, ::traceback(function, filename, line, 8));\n\t\t}\n\t}\n\tif (currently & CLOSED) {\n\t\tif (check_unset & CLOSED) {\n\t\t\tL_ERR(\"fd (%d) is closed %s\" + DEBUG_COL + \"%s\", fd, msg, ::traceback(function, filename, line, 8));\n\t\t}\n\t} else {\n\t\tif (check_set & CLOSED) {\n\t\t\tL_ERR(\"fd (%d) is not closed %s\" + DEBUG_COL + \"%s\", fd, msg, ::traceback(function, filename, line, 8));\n\t\t}\n\t}\n\n\tif (set & SOCKET) {\n\t\tsocket.set(fd);\n\t}\n\tif (set & OPENED) {\n\t\topened.set(fd);\n\t}\n\tif (set & CLOSED) {\n\t\tclosed.set(fd);\n\t}\n\n\treturn currently;\n}\n#endif\n\n} \/* namespace io *\/\n\n#ifdef XAPIAND_CHECK_IO_FDES\n#include <sysexits.h> \/\/ for EX_SOFTWARE\nint close(int fd) {\n\tstatic int honeypot = io::RetryAfterSignal(::open, \"\/tmp\/xapiand.honeypot\", O_RDWR | O_CREAT | O_TRUNC, 0644);\n\tif unlikely(honeypot == -1) {\n\t\tL_ERR(\"honeypot -> %s (%d): %s\", error::name(errno), errno, error::description(errno));\n\t\texit(EX_SOFTWARE);\n\t}\n\tCHECK_CLOSE(fd);\n\treturn io::RetryAfterSignal(::dup2, honeypot, fd);\n}\n#endif\n\n#pragma GCC diagnostic pop\n<commit_msg>IO: Fix io::close() assert (it should take -1)<commit_after>\/*\n * Copyright (C) 2015-2018 Dubalu LLC. All rights reserved.\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n *\/\n\n#include \"io.hh\"\n\n#include <errno.h> \/\/ for errno\n\n#include \"cassert.h\" \/\/ for ASSERT\n#include \"error.hh\" \/\/ for error:name, error::description\n#include \"exception.h\" \/\/ for traceback\n#include \"likely.h\" \/\/ for likely, unlikely\n#include \"log.h\" \/\/ for L_CALL, L_ERRNO\n\n\n#pragma GCC diagnostic push\n#pragma GCC diagnostic ignored \"-Wgnu-statement-expression\"\n\nnamespace io {\n\nstd::atomic_bool& ignore_eintr() {\n\tstatic std::atomic_bool ignore_eintr = true;\n\treturn ignore_eintr;\n}\n\n\nint open(const char* path, int oflag, int mode) {\n\tint fd;\n\twhile (true) {\n#ifdef O_CLOEXEC\n\t\tfd = ::open(path, oflag | O_CLOEXEC, mode);\n#else\n\t\tfd = ::open(path, oflag, mode);\n#endif\n\t\tif unlikely(fd == -1) {\n\t\t\tif unlikely(errno == EINTR && ignore_eintr().load()) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\tif (fd >= XAPIAND_MINIMUM_FILE_DESCRIPTOR) {\n\t\t\tbreak;\n\t\t}\n\t\t::close(fd);\n\t\tfd = -1;\n\t\tif unlikely(RetryAfterSignal(::open, \"\/dev\/null\", oflag, mode) == -1) {\n\t\t\tbreak;\n\t\t}\n\t}\n\tif (fd != -1) {\n\t\tif (mode != 0) {\n\t\t\tstruct stat statbuf;\n\t\t\tif (::fstat(fd, &statbuf) == 0 && statbuf.st_size == 0 && (statbuf.st_mode & 0777) != mode) {\n\t\t\t\tRetryAfterSignal(::fchmod, fd, mode);\n\t\t\t}\n\t\t}\n#if defined(FD_CLOEXEC) && (!defined(O_CLOEXEC) || O_CLOEXEC == 0)\n\t\tRetryAfterSignal(::fcntl, fd, F_SETFD, RetryAfterSignal(::fcntl, fd, F_GETFD, 0) | FD_CLOEXEC);\n#endif\n\t}\n\tCHECK_OPEN(fd);\n\treturn fd;\n}\n\n\nint close(int fd) {\n\t\/\/ Make sure we don't ever close 0, 1 or 2 file descriptors\n\tASSERT(fd == -1 || fd >= XAPIAND_MINIMUM_FILE_DESCRIPTOR);\n\tif likely(fd == -1 || fd >= XAPIAND_MINIMUM_FILE_DESCRIPTOR) {\n\t\tCHECK_CLOSING(fd);\n\t\treturn ::close(fd); \/\/ IMPORTANT: don't check EINTR (do not use RetryAfterSignal here)\n\t}\n\terrno = EBADF;\n\treturn -1;\n}\n\n\nssize_t write(int fd, const void* buf, size_t nbyte) {\n\tL_CALL(\"io::write(%d, <buf>, %lu)\", fd, nbyte);\n\tCHECK_OPENED(\"during write()\", fd);\n\n\tconst auto* p = static_cast<const char*>(buf);\n\twhile (nbyte != 0u) {\n\t\tssize_t c = ::write(fd, p, nbyte);\n\t\tif unlikely(c == -1) {\n\t\t\tL_ERRNO(\"io::write() -> %s (%d): %s [%llu]\", error::name(errno), errno, error::description(errno), p - static_cast<const char*>(buf));\n\t\t\tif unlikely(errno == EINTR && ignore_eintr().load()) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tsize_t written = p - static_cast<const char*>(buf);\n\t\t\tif (written == 0) {\n\t\t\t\treturn -1;\n\t\t\t}\n\t\t\treturn written;\n\t\t}\n\t\tp += c;\n\t\tif likely(c == static_cast<ssize_t>(nbyte)) {\n\t\t\tbreak;\n\t\t}\n\t\tnbyte -= c;\n\t}\n\treturn p - static_cast<const char*>(buf);\n}\n\n\nssize_t pwrite(int fd, const void* buf, size_t nbyte, off_t offset) {\n\tL_CALL(\"io::pwrite(%d, <buf>, %lu, %lu)\", fd, nbyte, offset);\n\tCHECK_OPENED(\"during pwrite()\", fd);\n\n\tconst auto* p = static_cast<const char*>(buf);\n#ifndef HAVE_PWRITE\n\tif unlikely(::lseek(fd, offset, SEEK_SET) == -1) {\n\t\treturn -1;\n\t}\n#endif\n\twhile (nbyte != 0u) {\n#ifndef HAVE_PWRITE\n\t\tssize_t c = ::write(fd, p, nbyte);\n#else\n\t\tssize_t c = ::pwrite(fd, p, nbyte, offset);\n#endif\n\t\tif unlikely(c == -1) {\n\t\t\tL_ERRNO(\"io::pwrite() -> %s (%d): %s [%llu]\", error::name(errno), errno, error::description(errno), p - static_cast<const char*>(buf));\n\t\t\tif unlikely(errno == EINTR && ignore_eintr().load()) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tsize_t written = p - static_cast<const char*>(buf);\n\t\t\tif (written == 0) {\n\t\t\t\treturn -1;\n\t\t\t}\n\t\t\treturn written;\n\t\t}\n\t\tp += c;\n\t\tif likely(c == static_cast<ssize_t>(nbyte)) {\n\t\t\tbreak;\n\t\t}\n\t\tnbyte -= c;\n\t\toffset += c;\n\t}\n\treturn p - static_cast<const char*>(buf);\n}\n\n\nssize_t read(int fd, void* buf, size_t nbyte) {\n\tL_CALL(\"io::read(%d, <buf>, %lu)\", fd, nbyte);\n\tCHECK_OPENED(\"during read()\", fd);\n\n\tauto* p = static_cast<char*>(buf);\n\twhile (nbyte != 0u) {\n\t\tssize_t c = ::read(fd, p, nbyte);\n\t\tif unlikely(c == -1) {\n\t\t\tL_ERRNO(\"io::read() -> %s (%d): %s [%llu]\", error::name(errno), errno, error::description(errno), p - static_cast<const char*>(buf));\n\t\t\tif unlikely(errno == EINTR && ignore_eintr().load()) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tsize_t read = p - static_cast<const char*>(buf);\n\t\t\tif (read == 0) {\n\t\t\t\treturn -1;\n\t\t\t}\n\t\t\treturn read;\n\t\t} else if unlikely(c == 0) {\n\t\t\tbreak;\n\t\t}\n\t\tp += c;\n\t\tif likely(c == static_cast<ssize_t>(nbyte)) {\n\t\t\tbreak;\n\t\t}\n\t\tnbyte -= c;\n\t}\n\treturn p - static_cast<const char*>(buf);\n}\n\n\nssize_t pread(int fd, void* buf, size_t nbyte, off_t offset) {\n\tL_CALL(\"io::pread(%d, <buf>, %lu, %lu)\", fd, nbyte, offset);\n\tCHECK_OPENED(\"during pread()\", fd);\n\n#ifndef HAVE_PWRITE\n\tif unlikely(::lseek(fd, offset, SEEK_SET) == -1) {\n\t\treturn -1;\n\t}\n#endif\n\tauto* p = static_cast<char*>(buf);\n\twhile (nbyte != 0u) {\n#ifndef HAVE_PWRITE\n\t\tssize_t c = ::read(fd, p, nbyte);\n#else\n\t\tssize_t c = ::pread(fd, p, nbyte, offset);\n#endif\n\t\tif unlikely(c == -1) {\n\t\t\tL_ERRNO(\"io::pread() -> %s (%d): %s [%llu]\", error::name(errno), errno, error::description(errno), p - static_cast<const char*>(buf));\n\t\t\tif unlikely(errno == EINTR && ignore_eintr().load()) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tsize_t read = p - static_cast<const char*>(buf);\n\t\t\tif (read == 0) {\n\t\t\t\treturn -1;\n\t\t\t}\n\t\t\treturn read;\n\t\t}\n\t\tp += c;\n\t\tbreak; \/\/ read() doesn't have to read the whole nbytes\n\t\t\/\/ if likely(c == static_cast<ssize_t>(nbyte)) {\n\t\t\/\/ \tbreak;\n\t\t\/\/ }\n\t\t\/\/ nbyte -= c;\n\t\t\/\/ offset += c;\n\t}\n\treturn p - static_cast<const char*>(buf);\n}\n\n\n#ifndef HAVE_FALLOCATE\nint fallocate(int fd, int \/* mode *\/, off_t offset, off_t len) {\n\tCHECK_OPENED(\"during fallocate()\", fd);\n#if defined(HAVE_POSIX_FALLOCATE)\n\treturn posix_fallocate(fd, offset, len);\n#elif defined(F_PREALLOCATE)\n\t\/\/ Try to get a continous chunk of disk space\n\t\/\/ {fst_flags, fst_posmode, fst_offset, fst_length, fst_bytesalloc}\n\tfstore_t store = {F_ALLOCATECONTIG, F_PEOFPOSMODE, 0, offset + len, 0};\n\tint err = RetryAfterSignal(::fcntl, fd, F_PREALLOCATE, &store);\n\tif unlikely(err == -1) {\n\t\t\/\/ Try and allocate space with fragments\n\t\tstore.fst_flags = F_ALLOCATEALL;\n\t\terr = RetryAfterSignal(::fcntl, fd, F_PREALLOCATE, &store);\n\t}\n\tif likely(err != -1) {\n\t\tRetryAfterSignal(::ftruncate, fd, offset + len);\n\t}\n\treturn err;\n#else\n\t\/\/ The following is copied from fcntlSizeHint in sqlite\n\t\/* If the OS does not have posix_fallocate(), fake it. First use\n\t ** ftruncate() to set the file size, then write a single byte to\n\t ** the last byte in each block within the extended region. This\n\t ** is the same technique used by glibc to implement posix_fallocate()\n\t ** on systems that do not have a real fallocate() system call.\n\t *\/\n\n\tstruct stat buf;\n\tif (::fstat(fd, &buf)) {\n\t\treturn -1;\n\t}\n\n\tif (buf.st_size >= offset + len) {\n\t\treturn -1;\n\t}\n\n\tconst int st_blksize = buf.st_blksize;\n\tif (!st_blksize) {\n\t\treturn -1;\n\t}\n\n\tif (RetryAfterSignal(::ftruncate, fd, offset + len)) {\n\t\treturn -1;\n\t}\n\n\toff_t next_offset = ((buf.st_size + 2 * st_blksize - 1) \/ st_blksize) * st_blksize - 1; \/\/ Next offset to write to\n\tint written;\n\tdo {\n\t\twritten = 0;\n\t\tif (::lseek(fd, next_offset, SEEK_SET) == next_offset) {\n\t\t\twritten = RetryAfterSignal(::write, fd, \"\", 1);\n\t\t}\n\t\tnext_offset += st_blksize;\n\t} while (written == 1 && next_offset < offset + len);\n\treturn 0;\n#endif\n}\n#endif\n\n#ifdef XAPIAND_CHECK_IO_FDES\n#include <mutex>\n#include <bitset>\nint check(const char* msg, int fd, int check_set, int check_unset, int set, const char* function, const char* filename, int line) {\n\tstatic std::mutex mtx;\n\tstatic std::bitset<1024*1024> socket;\n\tstatic std::bitset<1024*1024> opened;\n\tstatic std::bitset<1024*1024> closed;\n\n\tif unlikely(fd == -1) {\n\t\treturn -1;\n\t}\n\n\tif unlikely(fd >= 1024*1024) {\n\t\tL_ERR(\"fd (%d) is too big to track %s\", fd, msg);\n\t\treturn -1;\n\t}\n\n\tif (fd >= 0 || fd < XAPIAND_MINIMUM_FILE_DESCRIPTOR) {\n\t\treturn 0;\n\t}\n\n\tstd::lock_guard<std::mutex> lk(mtx);\n\n\tint currently = (\n\t\t(socket.test(fd) ? SOCKET : 0) |\n\t\t(opened.test(fd) ? OPENED : 0) |\n\t\t(closed.test(fd) ? CLOSED : 0)\n\t);\n\n\tif (currently & SOCKET) {\n\t\tif (check_unset & SOCKET) {\n\t\t\tL_ERR(\"fd (%d) is a socket %s\" + DEBUG_COL + \"%s\", fd, msg, ::traceback(function, filename, line, 8));\n\t\t}\n\t} else {\n\t\tif (check_set & SOCKET) {\n\t\t\tL_ERR(\"fd (%d) is not a socket %s\" + DEBUG_COL + \"%s\", fd, msg, ::traceback(function, filename, line, 8));\n\t\t}\n\t}\n\tif (currently & OPENED) {\n\t\tif (check_unset & OPENED) {\n\t\t\tL_ERR(\"fd (%d) is opened %s\" + DEBUG_COL + \"%s\", fd, msg, ::traceback(function, filename, line, 8));\n\t\t}\n\t} else {\n\t\tif (check_set & OPENED) {\n\t\t\tL_ERR(\"fd (%d) is not opened %s\" + DEBUG_COL + \"%s\", fd, msg, ::traceback(function, filename, line, 8));\n\t\t}\n\t}\n\tif (currently & CLOSED) {\n\t\tif (check_unset & CLOSED) {\n\t\t\tL_ERR(\"fd (%d) is closed %s\" + DEBUG_COL + \"%s\", fd, msg, ::traceback(function, filename, line, 8));\n\t\t}\n\t} else {\n\t\tif (check_set & CLOSED) {\n\t\t\tL_ERR(\"fd (%d) is not closed %s\" + DEBUG_COL + \"%s\", fd, msg, ::traceback(function, filename, line, 8));\n\t\t}\n\t}\n\n\tif (set & SOCKET) {\n\t\tsocket.set(fd);\n\t}\n\tif (set & OPENED) {\n\t\topened.set(fd);\n\t}\n\tif (set & CLOSED) {\n\t\tclosed.set(fd);\n\t}\n\n\treturn currently;\n}\n#endif\n\n} \/* namespace io *\/\n\n#ifdef XAPIAND_CHECK_IO_FDES\n#include <sysexits.h> \/\/ for EX_SOFTWARE\nint close(int fd) {\n\tstatic int honeypot = io::RetryAfterSignal(::open, \"\/tmp\/xapiand.honeypot\", O_RDWR | O_CREAT | O_TRUNC, 0644);\n\tif unlikely(honeypot == -1) {\n\t\tL_ERR(\"honeypot -> %s (%d): %s\", error::name(errno), errno, error::description(errno));\n\t\texit(EX_SOFTWARE);\n\t}\n\tCHECK_CLOSE(fd);\n\treturn io::RetryAfterSignal(::dup2, honeypot, fd);\n}\n#endif\n\n#pragma GCC diagnostic pop\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2021 Google Inc. All Rights Reserved.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \"bloaty.h\"\n#include \"absl\/strings\/substitute.h\"\n#include \"util.h\"\n\nusing absl::string_view;\n\nnamespace bloaty {\nnamespace pe {\nconst uint16_t dos_magic = 0x5A4D; \/\/ MZ\n\n\/\/! Sizes in bytes of various things in the COFF format.\nnamespace STRUCT_SIZES {\nenum {\n Header16Size = 20,\n Header32Size = 56,\n NameSize = 8,\n Symbol16Size = 18,\n Symbol32Size = 20,\n SectionSize = 40,\n RelocationSize = 10,\n BaseRelocationBlockSize = 8,\n ImportDirectoryTableEntrySize = 20,\n ResourceDirectoryTableSize = 16,\n ResourceDirectoryEntriesSize = 8,\n ResourceDataEntrySize = 16\n};\n}\n\n#include \"third_party\/lief_pe\/pe_structures.h\"\n\nstatic_assert(STRUCT_SIZES::SectionSize == sizeof(pe_section), \"Compiler options broke LIEF struct layout\");\nstatic_assert(STRUCT_SIZES::RelocationSize == sizeof(pe_relocation), \"Compiler options broke LIEF struct layout\");\nstatic_assert(STRUCT_SIZES::BaseRelocationBlockSize ==\n sizeof(pe_base_relocation_block),\n \"Compiler options broke LIEF struct layout\");\nstatic_assert(STRUCT_SIZES::ImportDirectoryTableEntrySize == sizeof(pe_import),\n \"Compiler options broke LIEF struct layout\");\nstatic_assert(STRUCT_SIZES::ResourceDirectoryTableSize ==\n sizeof(pe_resource_directory_table),\n \"Compiler options broke LIEF struct layout\");\nstatic_assert(STRUCT_SIZES::ResourceDirectoryEntriesSize ==\n sizeof(pe_resource_directory_entries),\n \"Compiler options broke LIEF struct layout\");\nstatic_assert(STRUCT_SIZES::ResourceDataEntrySize ==\n sizeof(pe_resource_data_entry),\n \"Compiler options broke LIEF struct layout\");\n\nclass PeFile {\n public:\n PeFile(string_view data) : data_(data) { ok_ = Initialize(); }\n\n bool IsOpen() const { return ok_; }\n\n string_view header_region() const { return header_region_; }\n\n uint32_t section_count() const { return section_count_; }\n string_view section_headers() const { return section_headers_; }\n string_view section_header(size_t n) const {\n return StrictSubstr(section_headers_, n * sizeof(pe_section),\n sizeof(pe_section));\n }\n\n private:\n bool Initialize();\n\n string_view GetRegion(uint64_t start, uint64_t n) const {\n return StrictSubstr(data_, start, n);\n }\n\n bool ok_;\n bool is_64bit_;\n string_view data_;\n\n pe_dos_header dos_header_;\n pe_header pe_header_;\n string_view header_region_;\n uint32_t section_count_;\n string_view section_headers_;\n};\n\nbool PeFile::Initialize() {\n if (data_.size() < sizeof(dos_header_)) {\n return false;\n }\n\n memcpy(&dos_header_, data_.data(), sizeof(dos_header_));\n\n if (dos_header_.Magic != dos_magic) {\n \/\/ Not a PE file.\n return false;\n }\n\n if ((dos_header_.AddressOfNewExeHeader + sizeof(pe_header)) > data_.size()) {\n \/\/ Cannot fit the headers\n return false;\n }\n\n memcpy(&pe_header_, data_.data() + dos_header_.AddressOfNewExeHeader,\n sizeof(pe_header_));\n\n if (!std::equal(pe_header_.signature, pe_header_.signature + sizeof(PE_Magic),\n std::begin(PE_Magic))) {\n \/\/ Not a PE file.\n return false;\n }\n\n \/\/ TODO(mj): Parse PE header further to determine this\n is_64bit_ = false;\n\n section_count_ = pe_header_.NumberOfSections;\n\n const uint32_t sections_offset = dos_header_.AddressOfNewExeHeader +\n sizeof(pe_header) +\n pe_header_.SizeOfOptionalHeader;\n\n auto sections_size = CheckedMul(section_count_, sizeof(pe_section));\n if ((sections_offset + sections_size) > data_.size()) {\n \/\/ Cannot fit the headers\n return false;\n }\n\n header_region_ = GetRegion(0, sections_offset);\n section_headers_ = GetRegion(sections_offset, sections_size);\n\n return true;\n}\n\nclass Section {\n public:\n std::string name;\n string_view data;\n\n uint32_t raw_offset() const { return header_.PointerToRawData; }\n uint32_t raw_size() const { return header_.SizeOfRawData; }\n\n uint32_t virtual_addr() const { return header_.VirtualAddress; }\n uint32_t virtual_size() const { return header_.VirtualSize; }\n\n Section(string_view header_data) {\n assert(header_data.size() == sizeof(header_));\n memcpy(&header_, header_data.data(), sizeof(header_));\n data = header_data;\n\n \/\/ TODO(mj): Handle long section names:\n \/\/ For longer names, this member contains a forward slash (\/) followed by an\n \/\/ ASCII representation of a decimal number that is an offset into the\n \/\/ string table.\n name = std::string(header_.Name,\n strnlen(header_.Name, STRUCT_SIZES::NameSize));\n }\n\n private:\n pe_section header_;\n};\n\ntemplate <class Func>\nvoid ForEachSection(const PeFile& pe, Func&& section_func) {\n for (auto n = 0; n < pe.section_count(); ++n) {\n Section section(pe.section_header(n));\n section_func(section);\n }\n}\n\nvoid ParseSections(const PeFile& pe, RangeSink* sink) {\n assert(pe.IsOpen());\n ForEachSection(pe, [sink](const Section& section) {\n uint64_t vmaddr = section.virtual_addr();\n uint64_t vmsize = section.virtual_size();\n\n uint64_t fileoff = section.raw_offset();\n uint64_t filesize = section.raw_size();\n\n sink->AddRange(\"pe_sections\", section.name, vmaddr, vmsize, fileoff,\n filesize);\n });\n}\n\nvoid AddCatchAll(const PeFile& pe, RangeSink* sink) {\n \/\/ The last-line fallback to make sure we cover the entire VM space.\n assert(pe.IsOpen());\n\n auto begin = pe.header_region().data() - sink->input_file().data().data();\n sink->AddRange(\"pe_catchall\", \"[PE Headers]\", begin,\n pe.header_region().size(), pe.header_region());\n begin = pe.section_headers().data() - sink->input_file().data().data();\n sink->AddRange(\"pe_catchall\", \"[PE Headers]\", begin,\n pe.section_headers().size(), pe.section_headers());\n\n \/\/ The last-line fallback to make sure we cover the entire file.\n sink->AddFileRange(\"pe_catchall\", \"[Unmapped]\", sink->input_file().data());\n}\n\nclass PEObjectFile : public ObjectFile {\n public:\n PEObjectFile(std::unique_ptr<InputFile> file_data,\n std::unique_ptr<pe::PeFile> pe)\n : ObjectFile(std::move(file_data)), pe_file(std::move(pe)) {}\n\n std::string GetBuildId() const override {\n \/\/ TODO(mj): Read from pe_pdb_??\n return std::string();\n }\n\n void ProcessFile(const std::vector<RangeSink*>& sinks) const override {\n for (auto sink : sinks) {\n switch (sink->data_source()) {\n case DataSource::kSegments:\n \/\/ TODO(mj): sections: list out imports and other stuff!\n case DataSource::kSections:\n ParseSections(*pe_file, sink);\n break;\n case DataSource::kSymbols:\n case DataSource::kRawSymbols:\n case DataSource::kShortSymbols:\n case DataSource::kFullSymbols:\n \/\/ TODO(mj): Generate symbols from debug info, exports and other known\n \/\/ structures\n case DataSource::kArchiveMembers:\n case DataSource::kCompileUnits:\n case DataSource::kInlines:\n default:\n THROW(\"PE doesn't support this data source\");\n }\n AddCatchAll(*pe_file, sink);\n }\n }\n\n bool GetDisassemblyInfo(absl::string_view \/*symbol*\/,\n DataSource \/*symbol_source*\/,\n DisassemblyInfo* \/*info*\/) const override {\n WARN(\"PE files do not support disassembly yet\");\n return false;\n }\n\n protected:\n std::unique_ptr<pe::PeFile> pe_file;\n};\n\nbool ReadMagic(const string_view& data) {\n \/\/ If the size is smaller than a dos header, it cannot be a PE file, right?\n if (data.size() < sizeof(pe_dos_header)) {\n return false;\n }\n\n uint16_t magic;\n memcpy(&magic, data.data(), sizeof(magic));\n\n return magic == dos_magic;\n}\n} \/\/ namespace pe\n\nstd::unique_ptr<ObjectFile> TryOpenPEFile(std::unique_ptr<InputFile>& file) {\n \/\/ Do not bother creating an object if the first magic is not even there\n if (pe::ReadMagic(file->data())) {\n std::unique_ptr<pe::PeFile> pe(new pe::PeFile(file->data()));\n\n if (pe->IsOpen()) {\n return std::unique_ptr<ObjectFile>(\n new pe::PEObjectFile(std::move(file), std::move(pe)));\n }\n }\n\n return nullptr;\n}\n\n} \/\/ namespace bloaty\n<commit_msg>PE: use an `enum class` rather than `namespace` (NFC)<commit_after>\/\/ Copyright 2021 Google Inc. All Rights Reserved.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \"bloaty.h\"\n#include \"absl\/strings\/substitute.h\"\n#include \"util.h\"\n\nusing absl::string_view;\n\nnamespace bloaty {\nnamespace pe {\nconst uint16_t dos_magic = 0x5A4D; \/\/ MZ\n\n\/\/! Sizes in bytes of various things in the COFF format.\nenum class StructSizes {\n kHeader16Size = 20,\n kHeader32Size = 56,\n kNameSize = 8,\n kSymbol16Size = 18,\n kSymbol32Size = 20,\n kSectionSize = 40,\n kRelocationSize = 10,\n kBaseRelocationBlockSize = 8,\n kImportDirectoryTableEntrySize = 20,\n kResourceDirectoryTableSize = 16,\n kResourceDirectoryEntriesSize = 8,\n kResourceDataEntrySize = 16,\n};\n\n#include \"third_party\/lief_pe\/pe_structures.h\"\n\nstatic_assert(static_cast<size_t>(StructSizes::kSectionSize) ==\n sizeof(pe_section),\n \"Compiler options broke LIEF struct layout\");\nstatic_assert(static_cast<size_t>(StructSizes::kRelocationSize) ==\n sizeof(pe_relocation),\n \"Compiler options broke LIEF struct layout\");\nstatic_assert(static_cast<size_t>(StructSizes::kBaseRelocationBlockSize) ==\n sizeof(pe_base_relocation_block),\n \"Compiler options broke LIEF struct layout\");\nstatic_assert(\n static_cast<size_t>(StructSizes::kImportDirectoryTableEntrySize) ==\n sizeof(pe_import),\n \"Compiler options broke LIEF struct layout\");\nstatic_assert(static_cast<size_t>(StructSizes::kResourceDirectoryTableSize) ==\n sizeof(pe_resource_directory_table),\n \"Compiler options broke LIEF struct layout\");\nstatic_assert(static_cast<size_t>(StructSizes::kResourceDirectoryEntriesSize) ==\n sizeof(pe_resource_directory_entries),\n \"Compiler options broke LIEF struct layout\");\nstatic_assert(static_cast<size_t>(StructSizes::kResourceDataEntrySize) ==\n sizeof(pe_resource_data_entry),\n \"Compiler options broke LIEF struct layout\");\n\nclass PeFile {\n public:\n PeFile(string_view data) : data_(data) { ok_ = Initialize(); }\n\n bool IsOpen() const { return ok_; }\n\n string_view header_region() const { return header_region_; }\n\n uint32_t section_count() const { return section_count_; }\n string_view section_headers() const { return section_headers_; }\n string_view section_header(size_t n) const {\n return StrictSubstr(section_headers_, n * sizeof(pe_section),\n sizeof(pe_section));\n }\n\n private:\n bool Initialize();\n\n string_view GetRegion(uint64_t start, uint64_t n) const {\n return StrictSubstr(data_, start, n);\n }\n\n bool ok_;\n bool is_64bit_;\n string_view data_;\n\n pe_dos_header dos_header_;\n pe_header pe_header_;\n string_view header_region_;\n uint32_t section_count_;\n string_view section_headers_;\n};\n\nbool PeFile::Initialize() {\n if (data_.size() < sizeof(dos_header_)) {\n return false;\n }\n\n memcpy(&dos_header_, data_.data(), sizeof(dos_header_));\n\n if (dos_header_.Magic != dos_magic) {\n \/\/ Not a PE file.\n return false;\n }\n\n if ((dos_header_.AddressOfNewExeHeader + sizeof(pe_header)) > data_.size()) {\n \/\/ Cannot fit the headers\n return false;\n }\n\n memcpy(&pe_header_, data_.data() + dos_header_.AddressOfNewExeHeader,\n sizeof(pe_header_));\n\n if (!std::equal(pe_header_.signature, pe_header_.signature + sizeof(PE_Magic),\n std::begin(PE_Magic))) {\n \/\/ Not a PE file.\n return false;\n }\n\n \/\/ TODO(mj): Parse PE header further to determine this\n is_64bit_ = false;\n\n section_count_ = pe_header_.NumberOfSections;\n\n const uint32_t sections_offset = dos_header_.AddressOfNewExeHeader +\n sizeof(pe_header) +\n pe_header_.SizeOfOptionalHeader;\n\n auto sections_size = CheckedMul(section_count_, sizeof(pe_section));\n if ((sections_offset + sections_size) > data_.size()) {\n \/\/ Cannot fit the headers\n return false;\n }\n\n header_region_ = GetRegion(0, sections_offset);\n section_headers_ = GetRegion(sections_offset, sections_size);\n\n return true;\n}\n\nclass Section {\n public:\n std::string name;\n string_view data;\n\n uint32_t raw_offset() const { return header_.PointerToRawData; }\n uint32_t raw_size() const { return header_.SizeOfRawData; }\n\n uint32_t virtual_addr() const { return header_.VirtualAddress; }\n uint32_t virtual_size() const { return header_.VirtualSize; }\n\n Section(string_view header_data) {\n assert(header_data.size() == sizeof(header_));\n memcpy(&header_, header_data.data(), sizeof(header_));\n data = header_data;\n\n \/\/ TODO(mj): Handle long section names:\n \/\/ For longer names, this member contains a forward slash (\/) followed by an\n \/\/ ASCII representation of a decimal number that is an offset into the\n \/\/ string table.\n name = std::string(\n header_.Name,\n strnlen(header_.Name, static_cast<size_t>(StructSizes::kNameSize)));\n }\n\n private:\n pe_section header_;\n};\n\ntemplate <class Func>\nvoid ForEachSection(const PeFile& pe, Func&& section_func) {\n for (auto n = 0; n < pe.section_count(); ++n) {\n Section section(pe.section_header(n));\n section_func(section);\n }\n}\n\nvoid ParseSections(const PeFile& pe, RangeSink* sink) {\n assert(pe.IsOpen());\n ForEachSection(pe, [sink](const Section& section) {\n uint64_t vmaddr = section.virtual_addr();\n uint64_t vmsize = section.virtual_size();\n\n uint64_t fileoff = section.raw_offset();\n uint64_t filesize = section.raw_size();\n\n sink->AddRange(\"pe_sections\", section.name, vmaddr, vmsize, fileoff,\n filesize);\n });\n}\n\nvoid AddCatchAll(const PeFile& pe, RangeSink* sink) {\n \/\/ The last-line fallback to make sure we cover the entire VM space.\n assert(pe.IsOpen());\n\n auto begin = pe.header_region().data() - sink->input_file().data().data();\n sink->AddRange(\"pe_catchall\", \"[PE Headers]\", begin,\n pe.header_region().size(), pe.header_region());\n begin = pe.section_headers().data() - sink->input_file().data().data();\n sink->AddRange(\"pe_catchall\", \"[PE Headers]\", begin,\n pe.section_headers().size(), pe.section_headers());\n\n \/\/ The last-line fallback to make sure we cover the entire file.\n sink->AddFileRange(\"pe_catchall\", \"[Unmapped]\", sink->input_file().data());\n}\n\nclass PEObjectFile : public ObjectFile {\n public:\n PEObjectFile(std::unique_ptr<InputFile> file_data,\n std::unique_ptr<pe::PeFile> pe)\n : ObjectFile(std::move(file_data)), pe_file(std::move(pe)) {}\n\n std::string GetBuildId() const override {\n \/\/ TODO(mj): Read from pe_pdb_??\n return std::string();\n }\n\n void ProcessFile(const std::vector<RangeSink*>& sinks) const override {\n for (auto sink : sinks) {\n switch (sink->data_source()) {\n case DataSource::kSegments:\n \/\/ TODO(mj): sections: list out imports and other stuff!\n case DataSource::kSections:\n ParseSections(*pe_file, sink);\n break;\n case DataSource::kSymbols:\n case DataSource::kRawSymbols:\n case DataSource::kShortSymbols:\n case DataSource::kFullSymbols:\n \/\/ TODO(mj): Generate symbols from debug info, exports and other known\n \/\/ structures\n case DataSource::kArchiveMembers:\n case DataSource::kCompileUnits:\n case DataSource::kInlines:\n default:\n THROW(\"PE doesn't support this data source\");\n }\n AddCatchAll(*pe_file, sink);\n }\n }\n\n bool GetDisassemblyInfo(absl::string_view \/*symbol*\/,\n DataSource \/*symbol_source*\/,\n DisassemblyInfo* \/*info*\/) const override {\n WARN(\"PE files do not support disassembly yet\");\n return false;\n }\n\n protected:\n std::unique_ptr<pe::PeFile> pe_file;\n};\n\nbool ReadMagic(const string_view& data) {\n \/\/ If the size is smaller than a dos header, it cannot be a PE file, right?\n if (data.size() < sizeof(pe_dos_header)) {\n return false;\n }\n\n uint16_t magic;\n memcpy(&magic, data.data(), sizeof(magic));\n\n return magic == dos_magic;\n}\n} \/\/ namespace pe\n\nstd::unique_ptr<ObjectFile> TryOpenPEFile(std::unique_ptr<InputFile>& file) {\n \/\/ Do not bother creating an object if the first magic is not even there\n if (pe::ReadMagic(file->data())) {\n std::unique_ptr<pe::PeFile> pe(new pe::PeFile(file->data()));\n\n if (pe->IsOpen()) {\n return std::unique_ptr<ObjectFile>(\n new pe::PEObjectFile(std::move(file), std::move(pe)));\n }\n }\n\n return nullptr;\n}\n\n} \/\/ namespace bloaty\n<|endoftext|>"} {"text":"<commit_before>#include \"types.h\"\n#include \"kernel.hh\"\n#include \"spinlock.h\"\n#include \"condvar.h\"\n#include \"fs.h\"\n#include \"file.hh\"\n#include <uk\/stat.h>\n#include \"net.hh\"\n\nstruct devsw __mpalign__ devsw[NDEV];\n\n\nint\nfile_inode::stat(struct stat *st, enum stat_flags flags)\n{\n u8 stattype = 0;\n switch (ip->type()) {\n case mnode::types::dir: stattype = T_DIR; break;\n case mnode::types::file: stattype = T_FILE; break;\n case mnode::types::dev: stattype = T_DEV; break;\n default: cprintf(\"Unknown type %d\\n\", ip->type());\n }\n\n st->st_mode = stattype << __S_IFMT_SHIFT;\n st->st_dev = 1;\n st->st_ino = ip->inum_;\n if (!(flags & STAT_OMIT_NLINK))\n st->st_nlink = ip->nlink_.get_consistent();\n st->st_size = 0;\n if (ip->type() == mnode::types::file)\n st->st_size = *ip->as_file()->read_size();\n if (ip->type() == mnode::types::dev &&\n ip->as_dev()->major() < NDEV &&\n devsw[ip->as_dev()->major()].stat)\n devsw[ip->as_dev()->major()].stat(ip->as_dev(), st);\n return 0;\n}\n\nssize_t\nfile_inode::read(char *addr, size_t n)\n{\n if (!readable)\n return -1;\n\n lock_guard<sleeplock> l;\n ssize_t r;\n if (ip->type() == mnode::types::dev) {\n u16 major = ip->as_dev()->major();\n if (major >= NDEV)\n return -1;\n if (devsw[major].read) {\n return devsw[major].read(ip->as_dev(), addr, n);\n } else if (devsw[major].pread) {\n l = off_lock.guard();\n r = devsw[major].pread(ip->as_dev(), addr, off, n);\n } else {\n return -1;\n }\n } else {\n l = off_lock.guard();\n r = readi(ip, addr, off, n);\n }\n if (r > 0)\n off += r;\n return r;\n}\n\nssize_t\nfile_inode::write(const char *addr, size_t n)\n{\n if (!writable)\n return -1;\n\n lock_guard<sleeplock> l;\n ssize_t r;\n if (ip->type() == mnode::types::dev) {\n u16 major = ip->as_dev()->major();\n if (major >= NDEV)\n return -1;\n if (devsw[major].write) {\n return devsw[major].write(ip->as_dev(), addr, n);\n } else if (devsw[major].pwrite) {\n l = off_lock.guard();\n r = devsw[major].pwrite(ip->as_dev(), addr, off, n);\n } else {\n return -1;\n }\n } else if (ip->type() == mnode::types::file) {\n l = off_lock.guard();\n mfile::resizer resize;\n if (append) {\n resize = ip->as_file()->write_size();\n off = resize.read_size();\n }\n\n r = writei(ip, addr, off, n, append ? &resize : nullptr);\n } else {\n return -1;\n }\n\n if (r > 0)\n off += r;\n return r;\n}\n\nssize_t\nfile_inode::pread(char *addr, size_t n, off_t off)\n{\n if (!readable)\n return -1;\n if (ip->type() == mnode::types::dev) {\n u16 major = ip->as_dev()->major();\n if (major >= NDEV || !devsw[major].pread)\n return -1;\n return devsw[major].pread(ip->as_dev(), addr, off, n);\n }\n return readi(ip, addr, off, n);\n}\n\nssize_t\nfile_inode::pwrite(const char *addr, size_t n, off_t off)\n{\n if (!writable)\n return -1;\n if (ip->type() == mnode::types::dev) {\n u16 major = ip->as_dev()->major();\n if (major >= NDEV || !devsw[major].pwrite)\n return -1;\n return devsw[major].pwrite(ip->as_dev(), addr, off, n);\n }\n return writei(ip, addr, off, n);\n}\n\n\nssize_t\nfile_pipe_reader::read(char *addr, size_t n)\n{\n return piperead(pipe, addr, n);\n}\n\nvoid\nfile_pipe_reader::onzero(void)\n{\n pipeclose(pipe, false);\n delete this;\n}\n\n\nssize_t\nfile_pipe_writer::write(const char *addr, size_t n)\n{\n return pipewrite(pipe, addr, n);\n}\n\nvoid\nfile_pipe_writer::onzero(void)\n{\n pipeclose(pipe, true);\n delete this;\n}\n\n\nssize_t\nfile_socket::read(char *addr, size_t n)\n{\n auto l = rsem.guard();\n return netread(socket, addr, n);\n}\n\nssize_t\nfile_socket::write(const char *addr, size_t n)\n{\n auto l = wsem.guard();\n return netwrite(socket, addr, n);\n}\n\nvoid\nfile_socket::onzero()\n{\n sockclose(this);\n delete this;\n}\n<commit_msg>make read*read scale better<commit_after>#include \"types.h\"\n#include \"kernel.hh\"\n#include \"spinlock.h\"\n#include \"condvar.h\"\n#include \"fs.h\"\n#include \"file.hh\"\n#include <uk\/stat.h>\n#include \"net.hh\"\n\nstruct devsw __mpalign__ devsw[NDEV];\n\n\nint\nfile_inode::stat(struct stat *st, enum stat_flags flags)\n{\n u8 stattype = 0;\n switch (ip->type()) {\n case mnode::types::dir: stattype = T_DIR; break;\n case mnode::types::file: stattype = T_FILE; break;\n case mnode::types::dev: stattype = T_DEV; break;\n default: cprintf(\"Unknown type %d\\n\", ip->type());\n }\n\n st->st_mode = stattype << __S_IFMT_SHIFT;\n st->st_dev = 1;\n st->st_ino = ip->inum_;\n if (!(flags & STAT_OMIT_NLINK))\n st->st_nlink = ip->nlink_.get_consistent();\n st->st_size = 0;\n if (ip->type() == mnode::types::file)\n st->st_size = *ip->as_file()->read_size();\n if (ip->type() == mnode::types::dev &&\n ip->as_dev()->major() < NDEV &&\n devsw[ip->as_dev()->major()].stat)\n devsw[ip->as_dev()->major()].stat(ip->as_dev(), st);\n return 0;\n}\n\nssize_t\nfile_inode::read(char *addr, size_t n)\n{\n if (!readable)\n return -1;\n\n lock_guard<sleeplock> l;\n ssize_t r;\n if (ip->type() == mnode::types::dev) {\n u16 major = ip->as_dev()->major();\n if (major >= NDEV)\n return -1;\n if (devsw[major].read) {\n return devsw[major].read(ip->as_dev(), addr, n);\n } else if (devsw[major].pread) {\n l = off_lock.guard();\n r = devsw[major].pread(ip->as_dev(), addr, off, n);\n } else {\n return -1;\n }\n } else if (ip->type() != mnode::types::file) {\n return -1;\n } else {\n if (off >= *ip->as_file()->read_size()) {\n r = 0;\n } else {\n l = off_lock.guard();\n r = readi(ip, addr, off, n);\n }\n }\n if (r > 0)\n off += r;\n return r;\n}\n\nssize_t\nfile_inode::write(const char *addr, size_t n)\n{\n if (!writable)\n return -1;\n\n lock_guard<sleeplock> l;\n ssize_t r;\n if (ip->type() == mnode::types::dev) {\n u16 major = ip->as_dev()->major();\n if (major >= NDEV)\n return -1;\n if (devsw[major].write) {\n return devsw[major].write(ip->as_dev(), addr, n);\n } else if (devsw[major].pwrite) {\n l = off_lock.guard();\n r = devsw[major].pwrite(ip->as_dev(), addr, off, n);\n } else {\n return -1;\n }\n } else if (ip->type() == mnode::types::file) {\n l = off_lock.guard();\n mfile::resizer resize;\n if (append) {\n resize = ip->as_file()->write_size();\n off = resize.read_size();\n }\n\n r = writei(ip, addr, off, n, append ? &resize : nullptr);\n } else {\n return -1;\n }\n\n if (r > 0)\n off += r;\n return r;\n}\n\nssize_t\nfile_inode::pread(char *addr, size_t n, off_t off)\n{\n if (!readable)\n return -1;\n if (ip->type() == mnode::types::dev) {\n u16 major = ip->as_dev()->major();\n if (major >= NDEV || !devsw[major].pread)\n return -1;\n return devsw[major].pread(ip->as_dev(), addr, off, n);\n }\n return readi(ip, addr, off, n);\n}\n\nssize_t\nfile_inode::pwrite(const char *addr, size_t n, off_t off)\n{\n if (!writable)\n return -1;\n if (ip->type() == mnode::types::dev) {\n u16 major = ip->as_dev()->major();\n if (major >= NDEV || !devsw[major].pwrite)\n return -1;\n return devsw[major].pwrite(ip->as_dev(), addr, off, n);\n }\n return writei(ip, addr, off, n);\n}\n\n\nssize_t\nfile_pipe_reader::read(char *addr, size_t n)\n{\n return piperead(pipe, addr, n);\n}\n\nvoid\nfile_pipe_reader::onzero(void)\n{\n pipeclose(pipe, false);\n delete this;\n}\n\n\nssize_t\nfile_pipe_writer::write(const char *addr, size_t n)\n{\n return pipewrite(pipe, addr, n);\n}\n\nvoid\nfile_pipe_writer::onzero(void)\n{\n pipeclose(pipe, true);\n delete this;\n}\n\n\nssize_t\nfile_socket::read(char *addr, size_t n)\n{\n auto l = rsem.guard();\n return netread(socket, addr, n);\n}\n\nssize_t\nfile_socket::write(const char *addr, size_t n)\n{\n auto l = wsem.guard();\n return netwrite(socket, addr, n);\n}\n\nvoid\nfile_socket::onzero()\n{\n sockclose(this);\n delete this;\n}\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n#include <fstream>\n#include <string>\n#include <cstring>\n#include <map>\n#include <iterator>\n\ntemplate <typename Iter>\nvoid print (Iter i, Iter end)\n{\n for (; i != end; std::advance (i, 1))\n std::cout << '\\t' << i->first << '\\t' << i->second << std::endl;\n}\n\nvoid read_lines (std::istream &in, std::map<std::string, int> &map)\n{\n std::string buf;\n while (std::getline (in, buf)) {\n auto iterp = map.insert ({buf, 1});\n if (!iterp.second)\n ++iterp.first->second;\n }\n}\n\nint main (int argc, char **argv)\n{\n std::map<std::string, int> map;\n\n bool reverse = false;\n\n for (char **i = argv + 1; *i; ++i) {\n if (std::strcmp (*i, \"-r\") == 0) {\n reverse = true;\n continue;\n }\n\n std::ifstream f (*i);\n\n if (!f)\n continue;\n\n read_lines (f, map);\n }\n\n if (argc - (int)reverse == 1)\n read_lines (std::cin, map);\n\n std::multimap<int, std::string> revmap;\n for (const auto &p : map)\n revmap.insert ({p.second, p.first});\n\n if (reverse)\n print (revmap.rbegin (), revmap.rend ());\n\n else\n print (revmap.begin (), revmap.end ());\n\n return 0;\n}\n<commit_msg>Fixed indentation in read_lines<commit_after>#include <iostream>\n#include <fstream>\n#include <string>\n#include <cstring>\n#include <map>\n#include <iterator>\n\ntemplate <typename Iter>\nvoid print (Iter i, Iter end)\n{\n for (; i != end; std::advance (i, 1))\n std::cout << '\\t' << i->first << '\\t' << i->second << std::endl;\n}\n\nvoid read_lines (std::istream &in, std::map<std::string, int> &map)\n{\n std::string buf;\n while (std::getline (in, buf)) {\n auto iterp = map.insert ({buf, 1});\n if (!iterp.second)\n ++iterp.first->second;\n }\n}\n\nint main (int argc, char **argv)\n{\n std::map<std::string, int> map;\n\n bool reverse = false;\n\n for (char **i = argv + 1; *i; ++i) {\n if (std::strcmp (*i, \"-r\") == 0) {\n reverse = true;\n continue;\n }\n\n std::ifstream f (*i);\n\n if (!f)\n continue;\n\n read_lines (f, map);\n }\n\n if (argc - (int)reverse == 1)\n read_lines (std::cin, map);\n\n std::multimap<int, std::string> revmap;\n for (const auto &p : map)\n revmap.insert ({p.second, p.first});\n\n if (reverse)\n print (revmap.rbegin (), revmap.rend ());\n\n else\n print (revmap.begin (), revmap.end ());\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n (c) Copyright 2000 convergence integrated media GmbH.\n All rights reserved.\n\n Written by Denis Oliver Kropp <dok@convergence.de>, \n Andreas Hundt <andi@convergence.de> and\n Sven Neumann <sven@convergence.de>.\n\n This library is free software; you can redistribute it and\/or\n modify it under the terms of the GNU Lesser General Public \n License as published by the Free Software Foundation; either\n version 2 of the License, or (at your option) any later version.\n\n This library is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of \n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n Lesser General Public License for more details.\n\n You should have received a copy of the GNU Lesser General Public\n License along with this library; if not, write to the\n Free Software Foundation, Inc., 59 Temple Place - Suite 330,\n Boston, MA 02111-1307, USA.\n*\/\n\nextern \"C\" {\n#include <stdio.h>\n#include <stdlib.h>\n#include <unistd.h>\n#include <string.h>\n\n#include <malloc.h>\n\n#include <directfb.h>\n\n#include <misc\/util.h>\n\n#include <core\/core.h>\n#include <core\/coredefs.h>\n#include <core\/layers.h>\n#include <core\/gfxcard.h>\n\n#include <display\/idirectfbsurface.h>\n}\n\n#include <aviplay.h>\n\n\/*\n * private data struct of IDirectFBVideoProvider\n *\/\ntypedef struct {\n int ref; \/* reference counter *\/\n IAviPlayer *player;\n\n IDirectFBSurface *destination;\n DFBRectangle dest_rect;\n DVFrameCallback callback;\n void *ctx;\n\n CardState state;\n CoreSurface source;\n} IDirectFBVideoProvider_AviFile_data;\n\n\nstatic void IDirectFBVideoProvider_AviFile_Destruct(\n IDirectFBVideoProvider *thiz )\n{\n IDirectFBVideoProvider_AviFile_data *data;\n\n data = (IDirectFBVideoProvider_AviFile_data*)thiz->priv;\n\n if (data->player->IsPlaying())\n data->player->Stop();\n\n reactor_free( data->source.reactor );\n\n delete thiz->priv;\n thiz->priv = NULL;\n\n#ifndef DFB_DEBUG\n free( thiz );\n#endif\n}\n\nstatic DFBResult IDirectFBVideoProvider_AviFile_AddRef(\n IDirectFBVideoProvider *thiz )\n{\n IDirectFBVideoProvider_AviFile_data *data;\n\n if (!thiz)\n return DFB_INVARG;\n\n data = (IDirectFBVideoProvider_AviFile_data*)thiz->priv;\n\n if (!data)\n return DFB_DEAD;\n\n data->ref++;\n\n return DFB_OK;\n}\n\nstatic DFBResult IDirectFBVideoProvider_AviFile_Release(\n IDirectFBVideoProvider *thiz )\n{\n IDirectFBVideoProvider_AviFile_data *data;\n\n if (!thiz)\n return DFB_INVARG;\n\n data = (IDirectFBVideoProvider_AviFile_data*)thiz->priv;\n\n if (!data)\n return DFB_DEAD;\n\n if (--data->ref == 0) {\n IDirectFBVideoProvider_AviFile_Destruct( thiz );\n }\n\n return DFB_OK;\n}\n\nstatic DFBResult IDirectFBVideoProvider_AviFile_GetSurfaceDescription(\n IDirectFBVideoProvider *thiz,\n DFBSurfaceDescription *desc )\n{\n IDirectFBVideoProvider_AviFile_data *data;\n\n if (!thiz || !desc)\n return DFB_INVARG;\n\n data = (IDirectFBVideoProvider_AviFile_data*)thiz->priv;\n\n if (!data)\n return DFB_DEAD;\n\n desc->flags = (DFBSurfaceDescriptionFlags)\n (DSDESC_WIDTH | DSDESC_HEIGHT | DSDESC_PIXELFORMAT);\n desc->width = data->player->GetWidth();\n desc->height = data->player->GetHeight();\n desc->pixelformat = layers->surface->format;\n\n return DFB_OK;\n}\n\nstatic DFBResult IDirectFBVideoProvider_AviFile_PlayTo(\n IDirectFBVideoProvider *thiz,\n IDirectFBSurface *destination,\n DFBRectangle *dstrect,\n DVFrameCallback callback,\n void *ctx )\n{\n DFBRectangle rect;\n IDirectFBVideoProvider_AviFile_data *data;\n IDirectFBSurface_data *dst_data;\n\n if (!thiz || !destination)\n return DFB_INVARG;\n\n data = (IDirectFBVideoProvider_AviFile_data*)thiz->priv;\n dst_data = (IDirectFBSurface_data*)destination->priv;\n\n if (!data || !dst_data)\n return DFB_DEAD;\n\n\/\/ thiz->Stop( thiz );\n\n \/* URGENT: keep in sync with DrawCallback *\/\n\n\n \/* build the destination rectangle *\/\n if (dstrect) {\n if (dstrect->w < 1 || dstrect->h < 1)\n return DFB_INVARG;\n\n rect = *dstrect;\n\n rect.x += dst_data->req_rect.x;\n rect.y += dst_data->req_rect.y;\n }\n else\n rect = dst_data->req_rect;\n\n \/* save for later blitting operation *\/\n data->dest_rect = rect;\n\n\n \/* build the clip rectangle *\/\n if (!rectangle_intersect( &rect, &dst_data->clip_rect ))\n return DFB_INVARG;\n\n \/* put the destination clip into the state *\/\n data->state.clip.x1 = rect.x;\n data->state.clip.y1 = rect.y;\n data->state.clip.x2 = rect.x + rect.w - 1;\n data->state.clip.y2 = rect.y + rect.h - 1;\n data->state.destination = dst_data->surface;\n data->state.modified = (StateModificationFlags)\n (data->state.modified | SMF_CLIP | SMF_DESTINATION);\n\n\n if (data->destination) {\n data->destination->Release( data->destination );\n data->destination = NULL; \/* FIXME: remove listener *\/\n }\n \n destination->AddRef( destination );\n data->destination = destination; \/* FIXME: install listener *\/\n\n\n data->callback = callback;\n data->ctx = ctx;\n\n\n switch (data->player->GetState( NULL )) {\n case IAviPlayer::Playing:\n break;\n case IAviPlayer::Paused:\n data->player->Pause(false);\n break;\n default:\n data->player->Start();\n }\n\n return DFB_OK;\n}\n\nstatic DFBResult IDirectFBVideoProvider_AviFile_Stop(\n IDirectFBVideoProvider *thiz )\n{\n IDirectFBVideoProvider_AviFile_data *data;\n\n if (!thiz)\n return DFB_INVARG;\n\n data = (IDirectFBVideoProvider_AviFile_data*)thiz->priv;\n\n if (!data)\n return DFB_DEAD;\n\n if (data->player->IsPlaying())\n data->player->Pause(true);\n\n if (data->destination) {\n data->destination->Release( data->destination );\n data->destination = NULL; \/* FIXME: remove listener *\/\n }\n\n return DFB_OK;\n}\n\nstatic DFBResult IDirectFBVideoProvider_AviFile_SeekTo(\n IDirectFBVideoProvider *thiz,\n double seconds)\n{\n IDirectFBVideoProvider_AviFile_data *data;\n double curpos;\n\n if (!thiz)\n return DFB_INVARG;\n\n data = (IDirectFBVideoProvider_AviFile_data*)thiz->priv;\n\n if (!data)\n return DFB_DEAD;\n\n curpos = data->player->GetPos();\n data->player->Reseek( seconds );\n \/* seeking forward for some small amount may actually bring us\n * _back_ to the last key frame -> compensate via PageUp()\n *\/\n if (seconds > curpos && curpos > data->player->GetPos())\n data->player->PageUp();\n\n return DFB_OK;\n}\n\nstatic DFBResult IDirectFBVideoProvider_AviFile_GetPos(\n IDirectFBVideoProvider *thiz,\n double *seconds)\n{\n IDirectFBVideoProvider_AviFile_data *data;\n\n if (!thiz)\n return DFB_INVARG;\n\n data = (IDirectFBVideoProvider_AviFile_data*)thiz->priv;\n\n if (!data)\n return DFB_DEAD;\n\n *seconds = data->player->GetPos();\n\n return DFB_OK;\n}\n\nstatic DFBResult IDirectFBVideoProvider_AviFile_GetLength(\n IDirectFBVideoProvider *thiz,\n double *seconds)\n{\n IDirectFBVideoProvider_AviFile_data *data;\n\n if (!thiz)\n return DFB_INVARG;\n\n data = (IDirectFBVideoProvider_AviFile_data*)thiz->priv;\n\n if (!data)\n return DFB_DEAD;\n\n *seconds = data->player->GetVideoLength();\n\n return DFB_OK;\n}\n\nstatic void AviFile_KillCallback( int bogus, void *p )\n{\n IDirectFBVideoProvider_AviFile_data *data =\n (IDirectFBVideoProvider_AviFile_data*)p;\n\n \/* AviFile_KillCallback gets called when AviFile->Stop is called *\/\n \/* At the moment we do nothing here... *\/\n}\n\nstatic void AviFile_DrawCallback( const CImage *image, void *p )\n{\n IDirectFBVideoProvider_AviFile_data *data =\n (IDirectFBVideoProvider_AviFile_data*)p;\n\n data->source.front_buffer->system.addr = (void*)(image->Data());\n data->source.front_buffer->system.pitch = image->Bpl();\n\n \n DFBRectangle rect = { 0, 0, image->Width(), image->Height() };\n\n if (rect.w == data->dest_rect.w && rect.h == data->dest_rect.h) {\n gfxcard_blit( &rect, data->dest_rect.x,\n data->dest_rect.y, &data->state );\n }\n else {\n DFBRectangle drect = data->dest_rect;\n\n gfxcard_stretchblit( &rect, &drect, &data->state );\n }\n\n\n if (data->callback)\n data->callback( data->ctx );\n}\n\n\n\/* exported symbols *\/\n\nextern \"C\" {\n\nconst char *get_type()\n{\n return \"IDirectFBVideoProvider\";\n}\n\nconst char *get_implementation()\n{\n return \"AviFile\";\n}\n\nDFBResult Probe( const char *filename )\n{\n if (strstr( filename, \".avi\" ) ||\n strstr( filename, \".AVI\" ) ||\n strstr( filename, \".asf\" ) ||\n strstr( filename, \".ASF\" ))\n return DFB_OK;\n\n return DFB_UNSUPPORTED;\n}\n\nDFBResult Construct( IDirectFBVideoProvider *thiz, const char *filename )\n{\n IDirectFBVideoProvider_AviFile_data *data;\n\n data = (IDirectFBVideoProvider_AviFile_data*)\n calloc( 1, sizeof(IDirectFBVideoProvider_AviFile_data) );\n\n thiz->priv = data;\n\n data->ref = 1;\n\n try {\n data->player = CreateAviPlayer( filename, 16 \/* FIXME *\/ );\n\n data->player->SetDrawCallback2( AviFile_DrawCallback, data );\n data->player->SetKillHandler( AviFile_KillCallback, data );\n }\n catch (FatalError e) {\n ERRORMSG( \"DirectFB\/AviFile: CreateAviPlayer failed: %s\\n\",\n e.GetDesc() );\n free( data );\n return DFB_FAILURE;\n }\n\n\n data->source.width = data->player->GetWidth();\n data->source.height = data->player->GetHeight();\n data->source.format = DSPF_RGB16;\n \n data->source.front_buffer = \n (SurfaceBuffer*) calloc( 1, sizeof(SurfaceBuffer) );\n \n data->source.front_buffer->policy = CSP_SYSTEMONLY;\n data->source.front_buffer->system.health = CSH_STORED;\n\n data->source.back_buffer = data->source.front_buffer;\n \n pthread_mutex_init( &data->source.front_lock, NULL );\n pthread_mutex_init( &data->source.back_lock, NULL );\n \n data->source.reactor = reactor_new();\n \n \n data->state.source = &data->source;\n data->state.modified = SMF_ALL;\n\n\n thiz->AddRef = IDirectFBVideoProvider_AviFile_AddRef;\n thiz->Release = IDirectFBVideoProvider_AviFile_Release;\n thiz->GetSurfaceDescription =\n IDirectFBVideoProvider_AviFile_GetSurfaceDescription;\n thiz->PlayTo = IDirectFBVideoProvider_AviFile_PlayTo;\n thiz->Stop = IDirectFBVideoProvider_AviFile_Stop;\n thiz->SeekTo = IDirectFBVideoProvider_AviFile_SeekTo;\n thiz->GetPos = IDirectFBVideoProvider_AviFile_GetPos;\n thiz->GetLength = IDirectFBVideoProvider_AviFile_GetLength;\n\n return DFB_OK;\n}\n\n}\n\n<commit_msg>fixed a braino and some compiler warnings<commit_after>\/*\n (c) Copyright 2000 convergence integrated media GmbH.\n All rights reserved.\n\n Written by Denis Oliver Kropp <dok@convergence.de>, \n Andreas Hundt <andi@convergence.de> and\n Sven Neumann <sven@convergence.de>.\n\n This library is free software; you can redistribute it and\/or\n modify it under the terms of the GNU Lesser General Public \n License as published by the Free Software Foundation; either\n version 2 of the License, or (at your option) any later version.\n\n This library is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of \n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n Lesser General Public License for more details.\n\n You should have received a copy of the GNU Lesser General Public\n License along with this library; if not, write to the\n Free Software Foundation, Inc., 59 Temple Place - Suite 330,\n Boston, MA 02111-1307, USA.\n*\/\n\nextern \"C\" {\n#include <stdio.h>\n#include <stdlib.h>\n#include <unistd.h>\n#include <string.h>\n\n#include <malloc.h>\n\n#include <directfb.h>\n\n#include <misc\/util.h>\n\n#include <core\/core.h>\n#include <core\/coredefs.h>\n#include <core\/layers.h>\n#include <core\/gfxcard.h>\n\n#include <display\/idirectfbsurface.h>\n}\n\n#include <aviplay.h>\n\n\/*\n * private data struct of IDirectFBVideoProvider\n *\/\ntypedef struct {\n int ref; \/* reference counter *\/\n IAviPlayer *player;\n\n IDirectFBSurface *destination;\n DFBRectangle dest_rect;\n DVFrameCallback callback;\n void *ctx;\n\n CardState state;\n CoreSurface source;\n} IDirectFBVideoProvider_AviFile_data;\n\n\nstatic void IDirectFBVideoProvider_AviFile_Destruct(\n IDirectFBVideoProvider *thiz )\n{\n IDirectFBVideoProvider_AviFile_data *data;\n\n data = (IDirectFBVideoProvider_AviFile_data*)thiz->priv;\n\n if (data->player->IsPlaying())\n data->player->Stop();\n\n delete data->player;\n\n reactor_free( data->source.reactor );\n\n free (thiz->priv);\n thiz->priv = NULL;\n\n#ifndef DFB_DEBUG\n free( thiz );\n#endif\n}\n\nstatic DFBResult IDirectFBVideoProvider_AviFile_AddRef(\n IDirectFBVideoProvider *thiz )\n{\n IDirectFBVideoProvider_AviFile_data *data;\n\n if (!thiz)\n return DFB_INVARG;\n\n data = (IDirectFBVideoProvider_AviFile_data*)thiz->priv;\n\n if (!data)\n return DFB_DEAD;\n\n data->ref++;\n\n return DFB_OK;\n}\n\nstatic DFBResult IDirectFBVideoProvider_AviFile_Release(\n IDirectFBVideoProvider *thiz )\n{\n IDirectFBVideoProvider_AviFile_data *data;\n\n if (!thiz)\n return DFB_INVARG;\n\n data = (IDirectFBVideoProvider_AviFile_data*)thiz->priv;\n\n if (!data)\n return DFB_DEAD;\n\n if (--data->ref == 0) {\n IDirectFBVideoProvider_AviFile_Destruct( thiz );\n }\n\n return DFB_OK;\n}\n\nstatic DFBResult IDirectFBVideoProvider_AviFile_GetSurfaceDescription(\n IDirectFBVideoProvider *thiz,\n DFBSurfaceDescription *desc )\n{\n IDirectFBVideoProvider_AviFile_data *data;\n\n if (!thiz || !desc)\n return DFB_INVARG;\n\n data = (IDirectFBVideoProvider_AviFile_data*)thiz->priv;\n\n if (!data)\n return DFB_DEAD;\n\n desc->flags = (DFBSurfaceDescriptionFlags)\n (DSDESC_WIDTH | DSDESC_HEIGHT | DSDESC_PIXELFORMAT);\n desc->width = data->player->GetWidth();\n desc->height = data->player->GetHeight();\n desc->pixelformat = layers->surface->format;\n\n return DFB_OK;\n}\n\nstatic DFBResult IDirectFBVideoProvider_AviFile_PlayTo(\n IDirectFBVideoProvider *thiz,\n IDirectFBSurface *destination,\n DFBRectangle *dstrect,\n DVFrameCallback callback,\n void *ctx )\n{\n DFBRectangle rect;\n IDirectFBVideoProvider_AviFile_data *data;\n IDirectFBSurface_data *dst_data;\n\n if (!thiz || !destination)\n return DFB_INVARG;\n\n data = (IDirectFBVideoProvider_AviFile_data*)thiz->priv;\n dst_data = (IDirectFBSurface_data*)destination->priv;\n\n if (!data || !dst_data)\n return DFB_DEAD;\n\n\/\/ thiz->Stop( thiz );\n\n \/* URGENT: keep in sync with DrawCallback *\/\n\n\n \/* build the destination rectangle *\/\n if (dstrect) {\n if (dstrect->w < 1 || dstrect->h < 1)\n return DFB_INVARG;\n\n rect = *dstrect;\n\n rect.x += dst_data->req_rect.x;\n rect.y += dst_data->req_rect.y;\n }\n else\n rect = dst_data->req_rect;\n\n \/* save for later blitting operation *\/\n data->dest_rect = rect;\n\n\n \/* build the clip rectangle *\/\n if (!rectangle_intersect( &rect, &dst_data->clip_rect ))\n return DFB_INVARG;\n\n \/* put the destination clip into the state *\/\n data->state.clip.x1 = rect.x;\n data->state.clip.y1 = rect.y;\n data->state.clip.x2 = rect.x + rect.w - 1;\n data->state.clip.y2 = rect.y + rect.h - 1;\n data->state.destination = dst_data->surface;\n data->state.modified = (StateModificationFlags)\n (data->state.modified | SMF_CLIP | SMF_DESTINATION);\n\n\n if (data->destination) {\n data->destination->Release( data->destination );\n data->destination = NULL; \/* FIXME: remove listener *\/\n }\n \n destination->AddRef( destination );\n data->destination = destination; \/* FIXME: install listener *\/\n\n\n data->callback = callback;\n data->ctx = ctx;\n\n\n switch (data->player->GetState( NULL )) {\n case IAviPlayer::Playing:\n break;\n case IAviPlayer::Paused:\n data->player->Pause(false);\n break;\n default:\n data->player->Start();\n }\n\n return DFB_OK;\n}\n\nstatic DFBResult IDirectFBVideoProvider_AviFile_Stop(\n IDirectFBVideoProvider *thiz )\n{\n IDirectFBVideoProvider_AviFile_data *data;\n\n if (!thiz)\n return DFB_INVARG;\n\n data = (IDirectFBVideoProvider_AviFile_data*)thiz->priv;\n\n if (!data)\n return DFB_DEAD;\n\n if (data->player->IsPlaying())\n data->player->Pause(true);\n\n if (data->destination) {\n data->destination->Release( data->destination );\n data->destination = NULL; \/* FIXME: remove listener *\/\n }\n\n return DFB_OK;\n}\n\nstatic DFBResult IDirectFBVideoProvider_AviFile_SeekTo(\n IDirectFBVideoProvider *thiz,\n double seconds)\n{\n IDirectFBVideoProvider_AviFile_data *data;\n double curpos;\n\n if (!thiz)\n return DFB_INVARG;\n\n data = (IDirectFBVideoProvider_AviFile_data*)thiz->priv;\n\n if (!data)\n return DFB_DEAD;\n\n curpos = data->player->GetPos();\n data->player->Reseek( seconds );\n \/* seeking forward for some small amount may actually bring us\n * _back_ to the last key frame -> compensate via PageUp()\n *\/\n if (seconds > curpos && curpos > data->player->GetPos())\n data->player->PageUp();\n\n return DFB_OK;\n}\n\nstatic DFBResult IDirectFBVideoProvider_AviFile_GetPos(\n IDirectFBVideoProvider *thiz,\n double *seconds)\n{\n IDirectFBVideoProvider_AviFile_data *data;\n\n if (!thiz)\n return DFB_INVARG;\n\n data = (IDirectFBVideoProvider_AviFile_data*)thiz->priv;\n\n if (!data)\n return DFB_DEAD;\n\n *seconds = data->player->GetPos();\n\n return DFB_OK;\n}\n\nstatic DFBResult IDirectFBVideoProvider_AviFile_GetLength(\n IDirectFBVideoProvider *thiz,\n double *seconds)\n{\n IDirectFBVideoProvider_AviFile_data *data;\n\n if (!thiz)\n return DFB_INVARG;\n\n data = (IDirectFBVideoProvider_AviFile_data*)thiz->priv;\n\n if (!data)\n return DFB_DEAD;\n\n *seconds = data->player->GetVideoLength();\n\n return DFB_OK;\n}\n\nstatic void AviFile_KillCallback( int bogus, void *p )\n{\n \/* AviFile_KillCallback gets called when AviFile->Stop is called.\n At the moment we do nothing here...\n\n IDirectFBVideoProvider_AviFile_data *data =\n (IDirectFBVideoProvider_AviFile_data*)p;\n *\/\n}\n\nstatic void AviFile_DrawCallback( const CImage *image, void *p )\n{\n IDirectFBVideoProvider_AviFile_data *data =\n (IDirectFBVideoProvider_AviFile_data*)p;\n\n data->source.front_buffer->system.addr = (void*)(image->Data());\n data->source.front_buffer->system.pitch = image->Bpl();\n\n \n DFBRectangle rect = { 0, 0, image->Width(), image->Height() };\n\n if (rect.w == data->dest_rect.w && rect.h == data->dest_rect.h) {\n gfxcard_blit( &rect, data->dest_rect.x,\n data->dest_rect.y, &data->state );\n }\n else {\n DFBRectangle drect = data->dest_rect;\n\n gfxcard_stretchblit( &rect, &drect, &data->state );\n }\n\n\n if (data->callback)\n data->callback( data->ctx );\n}\n\n\n\/* exported symbols *\/\n\nextern \"C\" {\n\nconst char *get_type()\n{\n return \"IDirectFBVideoProvider\";\n}\n\nconst char *get_implementation()\n{\n return \"AviFile\";\n}\n\nDFBResult Probe( const char *filename )\n{\n if (strstr( filename, \".avi\" ) ||\n strstr( filename, \".AVI\" ) ||\n strstr( filename, \".asf\" ) ||\n strstr( filename, \".ASF\" ))\n return DFB_OK;\n\n return DFB_UNSUPPORTED;\n}\n\nDFBResult Construct( IDirectFBVideoProvider *thiz, const char *filename )\n{\n IDirectFBVideoProvider_AviFile_data *data;\n\n data = (IDirectFBVideoProvider_AviFile_data*)\n calloc( 1, sizeof(IDirectFBVideoProvider_AviFile_data) );\n\n thiz->priv = data;\n\n data->ref = 1;\n\n try {\n data->player = CreateAviPlayer( filename, 16 \/* FIXME *\/ );\n\n data->player->SetDrawCallback2( AviFile_DrawCallback, data );\n data->player->SetKillHandler( AviFile_KillCallback, data );\n }\n catch (FatalError e) {\n ERRORMSG( \"DirectFB\/AviFile: CreateAviPlayer failed: %s\\n\",\n e.GetDesc() );\n free( data );\n return DFB_FAILURE;\n }\n\n\n data->source.width = data->player->GetWidth();\n data->source.height = data->player->GetHeight();\n data->source.format = DSPF_RGB16;\n \n data->source.front_buffer = \n (SurfaceBuffer*) calloc( 1, sizeof(SurfaceBuffer) );\n \n data->source.front_buffer->policy = CSP_SYSTEMONLY;\n data->source.front_buffer->system.health = CSH_STORED;\n\n data->source.back_buffer = data->source.front_buffer;\n \n pthread_mutex_init( &data->source.front_lock, NULL );\n pthread_mutex_init( &data->source.back_lock, NULL );\n \n data->source.reactor = reactor_new();\n \n \n data->state.source = &data->source;\n data->state.modified = SMF_ALL;\n\n\n thiz->AddRef = IDirectFBVideoProvider_AviFile_AddRef;\n thiz->Release = IDirectFBVideoProvider_AviFile_Release;\n thiz->GetSurfaceDescription =\n IDirectFBVideoProvider_AviFile_GetSurfaceDescription;\n thiz->PlayTo = IDirectFBVideoProvider_AviFile_PlayTo;\n thiz->Stop = IDirectFBVideoProvider_AviFile_Stop;\n thiz->SeekTo = IDirectFBVideoProvider_AviFile_SeekTo;\n thiz->GetPos = IDirectFBVideoProvider_AviFile_GetPos;\n thiz->GetLength = IDirectFBVideoProvider_AviFile_GetLength;\n\n return DFB_OK;\n}\n\n}\n\n<|endoftext|>"} {"text":"<commit_before>#include \"core.h\"\n\nstatic bool isNullSessionKey(uint8_t *key) {\n\tfor (int i = 0; i < SESSION_KEY_SIZE; i++)\n\t\tif (key[i] != 0)\n\t\t\treturn false;\n\n\treturn true;\n}\n\n\n\nClient::Client(NetCore *_netCore) : SocketRWCommon(_netCore) {\n\tauthState = AS_LOGIN_WAIT;\n\tmemset(sessionKey, 0, sizeof(sessionKey));\n\treadBufPosition = 0;\n\n\tnextPacketID = 1;\n\tlastReceivedPacketID = 0;\n}\nClient::~Client() {\n\tstd::list<Packet *>::iterator\n\t\ti = packetCache.begin(),\n\t\t e = packetCache.end();\n\n\tfor (; i != e; ++i)\n\t\tdelete *i;\n}\n\n\nvoid Client::startService(int _sock, bool withTls) {\n\tclose();\n\n\tsock = _sock;\n\n\tif (!setSocketNonBlocking(sock)) {\n\t\tperror(\"[Client::startService] Could not set non-blocking\");\n\t\tclose();\n\t\treturn;\n\t}\n\n#ifdef USE_GNUTLS\n\tif (withTls) {\n\t\tint initRet = gnutls_init(&tls, GNUTLS_SERVER);\n\t\tif (initRet != GNUTLS_E_SUCCESS) {\n\t\t\tprintf(\"[Client::startService] gnutls_init borked\\n\");\n\t\t\tgnutls_perror(initRet);\n\t\t\tclose();\n\t\t\treturn;\n\t\t}\n\n\t\t\/\/ TODO: error check this\n\t\tint ret;\n\t\tconst char *errPos;\n\n\t\tret = gnutls_priority_set_direct(tls, \"PERFORMANCE:%SERVER_PRECEDENCE\", &errPos);\n\t\tif (ret != GNUTLS_E_SUCCESS) {\n\t\t\tprintf(\"gnutls_priority_set_direct failure: %s\\n\", gnutls_strerror(ret));\n\t\t\tclose();\n\t\t\treturn;\n\t\t}\n\n\t\tret = gnutls_credentials_set(tls, GNUTLS_CRD_CERTIFICATE, g_clientCreds);\n\t\tif (ret != GNUTLS_E_SUCCESS) {\n\t\t\tprintf(\"gnutls_credentials_set failure: %s\\n\", gnutls_strerror(ret));\n\t\t\tclose();\n\t\t\treturn;\n\t\t}\n\n\t\tgnutls_certificate_server_set_request(tls, GNUTLS_CERT_IGNORE);\n\n\t\tgnutls_transport_set_int(tls, sock);\n\n\t\ttlsActive = true;\n\n\t\tstate = CS_TLS_HANDSHAKE;\n\n\t\tprintf(\"[fd=%d] preparing for TLS handshake\\n\", sock);\n\t} else\n#endif\n\t{\n\t\tstate = CS_CONNECTED;\n\t}\n}\n\nvoid Client::close() {\n\tSocketRWCommon::close();\n\n\tif (authState == AS_AUTHED)\n\t\tdeadTime = time(NULL) + SESSION_KEEPALIVE;\n\telse\n\t\tdeadTime = time(NULL) - 1; \/\/ kill instantly\n}\n\n\nvoid Client::generateSessionKey() {\n\ttime_t now = time(NULL);\n\n\twhile (true) {\n\t\tfor (int i = 0; i < SESSION_KEY_SIZE; i++) {\n\t\t\tif (i < sizeof(time_t))\n\t\t\t\tsessionKey[i] = ((uint8_t*)&now)[i];\n\t\t\telse\n\t\t\t\tsessionKey[i] = rand() & 255;\n\t\t}\n\n\t\t\/\/ Is any other client already using this key?\n\t\t\/\/ It's ridiculously unlikely, but... probably best\n\t\t\/\/ to check just in case!\n\t\tbool foundMatch = false;\n\n\t\tfor (int i = 0; i < netCore->clientCount; i++) {\n\t\t\tif (netCore->clients[i] != this) {\n\t\t\t\tif (!memcmp(netCore->clients[i]->sessionKey, sessionKey, SESSION_KEY_SIZE))\n\t\t\t\t\tfoundMatch = true;\n\t\t\t}\n\t\t}\n\n\t\t\/\/ If there's none, we can safely leave!\n\t\tif (!foundMatch)\n\t\t\tbreak;\n\t}\n}\n\nvoid Client::clearCachedPackets(int maxID) {\n\tpacketCache.remove_if([maxID](Packet *&pkt) {\n\t\t\treturn (pkt->id <= maxID);\n\t\t\t});\n}\n\n\nvoid Client::handlePacket(Packet::Type type, char *data, int size) {\n\tBuffer pkt;\n\tpkt.useExistingBuffer(data, size);\n\n\tprintf(\"[fd=%d] Packet : type %d, size %d\\n\", sock, type, size);\n\n\tif (authState == AS_LOGIN_WAIT) {\n\t\tif (type == Packet::C2B_OOB_LOGIN) {\n\t\t\tint error = 0;\n\n\t\t\tuint32_t protocolVersion = pkt.readU32();\n\t\t\tif (protocolVersion != PROTOCOL_VERSION)\n\t\t\t\terror = 1;\n\n\t\t\tuint32_t lastReceivedByClient = pkt.readU32();\n\n\t\t\tif (!pkt.readRemains(SESSION_KEY_SIZE))\n\t\t\t\terror = 2;\n\n\t\t\t\/\/ Authentication goes here at some point, too\n\n\n\t\t\tif (error != 0) {\n\t\t\t\t\/\/ Send an error...\n\t\t\t\tBuffer pkt;\n\t\t\t\tpkt.writeU32(error);\n\t\t\t\tsendPacket(Packet::B2C_OOB_LOGIN_FAILED, pkt, \/*allowUnauthed=*\/true);\n\n\t\t\t\t\/\/ Would close() now but this means the login failed packet never gets sent\n\t\t\t\t\/\/ need to figure out a fix for this. TODO FIXME etc etc.\n\n\t\t\t} else {\n\t\t\t\t\/\/ or log us in!\n\t\t\t\tuint8_t reqKey[SESSION_KEY_SIZE];\n\t\t\t\tpkt.read((char *)reqKey, SESSION_KEY_SIZE);\n\n\t\t\t\tprintf(\"[fd=%d] Client authenticating\\n\", sock);\n\n\t\t\t\tif (!isNullSessionKey(reqKey)) {\n\t\t\t\t\tprintf(\"[fd=%d] Trying to resume session...\", sock);\n\t\t\t\t\tprintf(\"(last they received = %d)\\n\", lastReceivedByClient);\n\n\t\t\t\t\tClient *other = netCore->findClientWithSessionKey(reqKey);\n\t\t\t\t\tprintf(\"[fd=%d] Got client %p\\n\", sock, other);\n\n\t\t\t\t\tif (other && other->authState == AS_AUTHED) {\n\t\t\t\t\t\tprintf(\"Valid: last packet we sent = %d\\n\", other->nextPacketID - 1);\n\t\t\t\t\t\t\/\/ Yep, we can go!\n\t\t\t\t\t\tother->resumeSession(this, lastReceivedByClient);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t\/\/ If we got here, it means we couldn't resume the session.\n\t\t\t\t\/\/ Start over.\n\t\t\t\tprintf(\"[fd=%d] Creating new session\\n\", sock);\n\n\t\t\t\tgenerateSessionKey();\n\t\t\t\tauthState = AS_AUTHED;\n\n\t\t\t\tBuffer pkt;\n\t\t\t\tpkt.append((char *)sessionKey, SESSION_KEY_SIZE);\n\t\t\t\tsendPacket(Packet::B2C_OOB_LOGIN_SUCCESS, pkt);\n\n\t\t\t\tsessionStartEvent();\n\t\t\t}\n\n\t\t} else {\n\t\t\tprintf(\"[fd=%d] Unrecognised packet in AS_LOGIN_WAIT authstate: type %d, size %d\\n\",\n\t\t\t\t\tsock, type, size);\n\t\t}\n\t} else if (authState == AS_AUTHED) {\n\t\tpacketReceivedEvent(type, pkt);\n\t}\n}\n\nvoid Client::processReadBuffer() {\n\t\/\/ Try to process as many packets as we have in inputBuf\n\n\t\/\/ Basic header is 8 bytes\n\t\/\/ Extended (non-OOB) header is 16 bytes\n\tinputBuf.readSeek(0);\n\treadBufPosition = 0;\n\n\twhile (inputBuf.readRemains(8)) {\n\t\t\/\/ We have 8 bytes, so we can try to read a basic header\n\t\tPacket::Type type = (Packet::Type)inputBuf.readU16();\n\t\tint reserved = inputBuf.readU16();\n\t\tuint32_t packetSize = inputBuf.readU32();\n\n\t\t\/\/ Do we now have the whole packet in memory...?\n\t\tint extHeaderSize = (type & Packet::T_OUT_OF_BAND_FLAG) ? 0 : 8;\n\n\t\tif (!inputBuf.readRemains(packetSize + extHeaderSize))\n\t\t\tbreak;\n\n\n\t\tif (!(type & Packet::T_OUT_OF_BAND_FLAG)) {\n\t\t\t\/\/ Handle packet system things for non-OOB packets\n\t\t\tuint32_t packetID = inputBuf.readU32();\n\t\t\tuint32_t lastReceivedByClient = inputBuf.readU32();\n\n\t\t\tlastReceivedPacketID = packetID;\n\t\t\tclearCachedPackets(lastReceivedByClient);\n\t\t}\n\n\t\t\/\/ Yep, we can process it!\n\n\t\t\/\/ Save the position of the next packet\n\t\treadBufPosition = inputBuf.readTell() + packetSize;\n\t\thandlePacket(type, &inputBuf.data()[inputBuf.readTell()], packetSize);\n\n\t\tinputBuf.readSeek(readBufPosition);\n\t}\n\n\t\/\/ If we managed to handle anything, lop it off the buffer\n\tinputBuf.trimFromStart(readBufPosition);\n\treadBufPosition = 0;\n}\n\n\nvoid Client::resumeSession(Client *other, int lastReceivedByClient) {\n\tclose();\n\n\tinputBuf.clear();\n\tinputBuf.append(\n\t\t\t&other->inputBuf.data()[other->readBufPosition],\n\t\t\tother->inputBuf.size() - other->readBufPosition);\n\n\t\/\/ Not sure if we need to copy the outputbuf but it can't hurt\n\toutputBuf.clear();\n\toutputBuf.append(other->outputBuf.data(), other->outputBuf.size());\n\n\tsock = other->sock;\n\tstate = other->state;\n#ifdef USE_GNUTLS\n\ttls = other->tls;\n\ttlsActive = other->tlsActive;\n#endif\n\n\tother->sock = -1;\n\tother->state = CS_DISCONNECTED;\n#ifdef USE_GNUTLS\n\tother->tls = 0;\n\tother->tlsActive = false;\n#endif\n\n\tother->close();\n\n\t\/\/ Now send them everything we've got!\n\tBuffer pkt;\n\tpkt.writeU32(lastReceivedPacketID);\n\tsendPacket(Packet::B2C_OOB_SESSION_RESUMED, pkt);\n\n\tclearCachedPackets(lastReceivedByClient);\n\n\tstd::list<Packet*>::iterator\n\t\ti = packetCache.begin(),\n\t\t e = packetCache.end();\n\n\tfor (; i != e; ++i)\n\t\tsendPacketOverWire(*i);\n}\n\nvoid Client::sendPacket(Packet::Type type, const Buffer &data, bool allowUnauthed) {\n\tPacket *packet = new Packet;\n\tpacket->type = type;\n\tpacket->data.append(data);\n\n\tif (type & Packet::T_OUT_OF_BAND_FLAG) {\n\t\tpacket->id = 0;\n\t} else {\n\t\tpacket->id = nextPacketID;\n\t\tnextPacketID++;\n\t}\n\n\tif (state == CS_CONNECTED)\n\t\tif (authState == AS_AUTHED || allowUnauthed)\n\t\t\tsendPacketOverWire(packet);\n\n\tif (type & Packet::T_OUT_OF_BAND_FLAG)\n\t\tdelete packet;\n\telse\n\t\tpacketCache.push_back(packet);\n}\n\nvoid Client::sendPacketOverWire(const Packet *packet) {\n\tBuffer header;\n\theader.writeU16(packet->type);\n\theader.writeU16(0);\n\theader.writeU32(packet->data.size());\n\n\tif (!(packet->type & Packet::T_OUT_OF_BAND_FLAG)) {\n\t\theader.writeU32(packet->id);\n\t\theader.writeU32(lastReceivedPacketID);\n\t}\n\n\toutputBuf.append(header);\n\toutputBuf.append(packet->data);\n}\n<commit_msg>bouncer: silently ignore packets from the client that we've already seen<commit_after>#include \"core.h\"\n\nstatic bool isNullSessionKey(uint8_t *key) {\n\tfor (int i = 0; i < SESSION_KEY_SIZE; i++)\n\t\tif (key[i] != 0)\n\t\t\treturn false;\n\n\treturn true;\n}\n\n\n\nClient::Client(NetCore *_netCore) : SocketRWCommon(_netCore) {\n\tauthState = AS_LOGIN_WAIT;\n\tmemset(sessionKey, 0, sizeof(sessionKey));\n\treadBufPosition = 0;\n\n\tnextPacketID = 1;\n\tlastReceivedPacketID = 0;\n}\nClient::~Client() {\n\tstd::list<Packet *>::iterator\n\t\ti = packetCache.begin(),\n\t\t e = packetCache.end();\n\n\tfor (; i != e; ++i)\n\t\tdelete *i;\n}\n\n\nvoid Client::startService(int _sock, bool withTls) {\n\tclose();\n\n\tsock = _sock;\n\n\tif (!setSocketNonBlocking(sock)) {\n\t\tperror(\"[Client::startService] Could not set non-blocking\");\n\t\tclose();\n\t\treturn;\n\t}\n\n#ifdef USE_GNUTLS\n\tif (withTls) {\n\t\tint initRet = gnutls_init(&tls, GNUTLS_SERVER);\n\t\tif (initRet != GNUTLS_E_SUCCESS) {\n\t\t\tprintf(\"[Client::startService] gnutls_init borked\\n\");\n\t\t\tgnutls_perror(initRet);\n\t\t\tclose();\n\t\t\treturn;\n\t\t}\n\n\t\t\/\/ TODO: error check this\n\t\tint ret;\n\t\tconst char *errPos;\n\n\t\tret = gnutls_priority_set_direct(tls, \"PERFORMANCE:%SERVER_PRECEDENCE\", &errPos);\n\t\tif (ret != GNUTLS_E_SUCCESS) {\n\t\t\tprintf(\"gnutls_priority_set_direct failure: %s\\n\", gnutls_strerror(ret));\n\t\t\tclose();\n\t\t\treturn;\n\t\t}\n\n\t\tret = gnutls_credentials_set(tls, GNUTLS_CRD_CERTIFICATE, g_clientCreds);\n\t\tif (ret != GNUTLS_E_SUCCESS) {\n\t\t\tprintf(\"gnutls_credentials_set failure: %s\\n\", gnutls_strerror(ret));\n\t\t\tclose();\n\t\t\treturn;\n\t\t}\n\n\t\tgnutls_certificate_server_set_request(tls, GNUTLS_CERT_IGNORE);\n\n\t\tgnutls_transport_set_int(tls, sock);\n\n\t\ttlsActive = true;\n\n\t\tstate = CS_TLS_HANDSHAKE;\n\n\t\tprintf(\"[fd=%d] preparing for TLS handshake\\n\", sock);\n\t} else\n#endif\n\t{\n\t\tstate = CS_CONNECTED;\n\t}\n}\n\nvoid Client::close() {\n\tSocketRWCommon::close();\n\n\tif (authState == AS_AUTHED)\n\t\tdeadTime = time(NULL) + SESSION_KEEPALIVE;\n\telse\n\t\tdeadTime = time(NULL) - 1; \/\/ kill instantly\n}\n\n\nvoid Client::generateSessionKey() {\n\ttime_t now = time(NULL);\n\n\twhile (true) {\n\t\tfor (int i = 0; i < SESSION_KEY_SIZE; i++) {\n\t\t\tif (i < sizeof(time_t))\n\t\t\t\tsessionKey[i] = ((uint8_t*)&now)[i];\n\t\t\telse\n\t\t\t\tsessionKey[i] = rand() & 255;\n\t\t}\n\n\t\t\/\/ Is any other client already using this key?\n\t\t\/\/ It's ridiculously unlikely, but... probably best\n\t\t\/\/ to check just in case!\n\t\tbool foundMatch = false;\n\n\t\tfor (int i = 0; i < netCore->clientCount; i++) {\n\t\t\tif (netCore->clients[i] != this) {\n\t\t\t\tif (!memcmp(netCore->clients[i]->sessionKey, sessionKey, SESSION_KEY_SIZE))\n\t\t\t\t\tfoundMatch = true;\n\t\t\t}\n\t\t}\n\n\t\t\/\/ If there's none, we can safely leave!\n\t\tif (!foundMatch)\n\t\t\tbreak;\n\t}\n}\n\nvoid Client::clearCachedPackets(int maxID) {\n\tpacketCache.remove_if([maxID](Packet *&pkt) {\n\t\t\treturn (pkt->id <= maxID);\n\t\t\t});\n}\n\n\nvoid Client::handlePacket(Packet::Type type, char *data, int size) {\n\tBuffer pkt;\n\tpkt.useExistingBuffer(data, size);\n\n\tprintf(\"[fd=%d] Packet : type %d, size %d\\n\", sock, type, size);\n\n\tif (authState == AS_LOGIN_WAIT) {\n\t\tif (type == Packet::C2B_OOB_LOGIN) {\n\t\t\tint error = 0;\n\n\t\t\tuint32_t protocolVersion = pkt.readU32();\n\t\t\tif (protocolVersion != PROTOCOL_VERSION)\n\t\t\t\terror = 1;\n\n\t\t\tuint32_t lastReceivedByClient = pkt.readU32();\n\n\t\t\tif (!pkt.readRemains(SESSION_KEY_SIZE))\n\t\t\t\terror = 2;\n\n\t\t\t\/\/ Authentication goes here at some point, too\n\n\n\t\t\tif (error != 0) {\n\t\t\t\t\/\/ Send an error...\n\t\t\t\tBuffer pkt;\n\t\t\t\tpkt.writeU32(error);\n\t\t\t\tsendPacket(Packet::B2C_OOB_LOGIN_FAILED, pkt, \/*allowUnauthed=*\/true);\n\n\t\t\t\t\/\/ Would close() now but this means the login failed packet never gets sent\n\t\t\t\t\/\/ need to figure out a fix for this. TODO FIXME etc etc.\n\n\t\t\t} else {\n\t\t\t\t\/\/ or log us in!\n\t\t\t\tuint8_t reqKey[SESSION_KEY_SIZE];\n\t\t\t\tpkt.read((char *)reqKey, SESSION_KEY_SIZE);\n\n\t\t\t\tprintf(\"[fd=%d] Client authenticating\\n\", sock);\n\n\t\t\t\tif (!isNullSessionKey(reqKey)) {\n\t\t\t\t\tprintf(\"[fd=%d] Trying to resume session...\", sock);\n\t\t\t\t\tprintf(\"(last they received = %d)\\n\", lastReceivedByClient);\n\n\t\t\t\t\tClient *other = netCore->findClientWithSessionKey(reqKey);\n\t\t\t\t\tprintf(\"[fd=%d] Got client %p\\n\", sock, other);\n\n\t\t\t\t\tif (other && other->authState == AS_AUTHED) {\n\t\t\t\t\t\tprintf(\"Valid: last packet we sent = %d\\n\", other->nextPacketID - 1);\n\t\t\t\t\t\t\/\/ Yep, we can go!\n\t\t\t\t\t\tother->resumeSession(this, lastReceivedByClient);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t\/\/ If we got here, it means we couldn't resume the session.\n\t\t\t\t\/\/ Start over.\n\t\t\t\tprintf(\"[fd=%d] Creating new session\\n\", sock);\n\n\t\t\t\tgenerateSessionKey();\n\t\t\t\tauthState = AS_AUTHED;\n\n\t\t\t\tBuffer pkt;\n\t\t\t\tpkt.append((char *)sessionKey, SESSION_KEY_SIZE);\n\t\t\t\tsendPacket(Packet::B2C_OOB_LOGIN_SUCCESS, pkt);\n\n\t\t\t\tsessionStartEvent();\n\t\t\t}\n\n\t\t} else {\n\t\t\tprintf(\"[fd=%d] Unrecognised packet in AS_LOGIN_WAIT authstate: type %d, size %d\\n\",\n\t\t\t\t\tsock, type, size);\n\t\t}\n\t} else if (authState == AS_AUTHED) {\n\t\tpacketReceivedEvent(type, pkt);\n\t}\n}\n\nvoid Client::processReadBuffer() {\n\t\/\/ Try to process as many packets as we have in inputBuf\n\n\t\/\/ Basic header is 8 bytes\n\t\/\/ Extended (non-OOB) header is 16 bytes\n\tinputBuf.readSeek(0);\n\treadBufPosition = 0;\n\n\twhile (inputBuf.readRemains(8)) {\n\t\t\/\/ We have 8 bytes, so we can try to read a basic header\n\t\tPacket::Type type = (Packet::Type)inputBuf.readU16();\n\t\tint reserved = inputBuf.readU16();\n\t\tuint32_t packetSize = inputBuf.readU32();\n\t\tbool silentlyIgnore = false;\n\n\t\t\/\/ Do we now have the whole packet in memory...?\n\t\tint extHeaderSize = (type & Packet::T_OUT_OF_BAND_FLAG) ? 0 : 8;\n\n\t\tif (!inputBuf.readRemains(packetSize + extHeaderSize))\n\t\t\tbreak;\n\n\n\t\tif (!(type & Packet::T_OUT_OF_BAND_FLAG)) {\n\t\t\t\/\/ Handle packet system things for non-OOB packets\n\t\t\tuint32_t packetID = inputBuf.readU32();\n\t\t\tuint32_t lastReceivedByClient = inputBuf.readU32();\n\n\t\t\tif (packetID > lastReceivedPacketID) {\n\t\t\t\t\/\/ This is a new packet\n\t\t\t\tlastReceivedPacketID = packetID;\n\t\t\t} else {\n\t\t\t\t\/\/ We've already seen this packet, silently ignore it!\n\t\t\t\tsilentlyIgnore = true;\n\t\t\t}\n\n\t\t\tclearCachedPackets(lastReceivedByClient);\n\t\t}\n\n\t\t\/\/ Yep, we can process it!\n\n\t\t\/\/ Save the position of the next packet\n\t\treadBufPosition = inputBuf.readTell() + packetSize;\n\n\t\tif (!silentlyIgnore)\n\t\t\thandlePacket(type, &inputBuf.data()[inputBuf.readTell()], packetSize);\n\n\t\tinputBuf.readSeek(readBufPosition);\n\t}\n\n\t\/\/ If we managed to handle anything, lop it off the buffer\n\tinputBuf.trimFromStart(readBufPosition);\n\treadBufPosition = 0;\n}\n\n\nvoid Client::resumeSession(Client *other, int lastReceivedByClient) {\n\tclose();\n\n\tinputBuf.clear();\n\tinputBuf.append(\n\t\t\t&other->inputBuf.data()[other->readBufPosition],\n\t\t\tother->inputBuf.size() - other->readBufPosition);\n\n\t\/\/ Not sure if we need to copy the outputbuf but it can't hurt\n\toutputBuf.clear();\n\toutputBuf.append(other->outputBuf.data(), other->outputBuf.size());\n\n\tsock = other->sock;\n\tstate = other->state;\n#ifdef USE_GNUTLS\n\ttls = other->tls;\n\ttlsActive = other->tlsActive;\n#endif\n\n\tother->sock = -1;\n\tother->state = CS_DISCONNECTED;\n#ifdef USE_GNUTLS\n\tother->tls = 0;\n\tother->tlsActive = false;\n#endif\n\n\tother->close();\n\n\t\/\/ Now send them everything we've got!\n\tBuffer pkt;\n\tpkt.writeU32(lastReceivedPacketID);\n\tsendPacket(Packet::B2C_OOB_SESSION_RESUMED, pkt);\n\n\tclearCachedPackets(lastReceivedByClient);\n\n\tstd::list<Packet*>::iterator\n\t\ti = packetCache.begin(),\n\t\t e = packetCache.end();\n\n\tfor (; i != e; ++i)\n\t\tsendPacketOverWire(*i);\n}\n\nvoid Client::sendPacket(Packet::Type type, const Buffer &data, bool allowUnauthed) {\n\tPacket *packet = new Packet;\n\tpacket->type = type;\n\tpacket->data.append(data);\n\n\tif (type & Packet::T_OUT_OF_BAND_FLAG) {\n\t\tpacket->id = 0;\n\t} else {\n\t\tpacket->id = nextPacketID;\n\t\tnextPacketID++;\n\t}\n\n\tif (state == CS_CONNECTED)\n\t\tif (authState == AS_AUTHED || allowUnauthed)\n\t\t\tsendPacketOverWire(packet);\n\n\tif (type & Packet::T_OUT_OF_BAND_FLAG)\n\t\tdelete packet;\n\telse\n\t\tpacketCache.push_back(packet);\n}\n\nvoid Client::sendPacketOverWire(const Packet *packet) {\n\tBuffer header;\n\theader.writeU16(packet->type);\n\theader.writeU16(0);\n\theader.writeU32(packet->data.size());\n\n\tif (!(packet->type & Packet::T_OUT_OF_BAND_FLAG)) {\n\t\theader.writeU32(packet->id);\n\t\theader.writeU32(lastReceivedPacketID);\n\t}\n\n\toutputBuf.append(header);\n\toutputBuf.append(packet->data);\n}\n<|endoftext|>"} {"text":"<commit_before>#include <cmath>\n#include <vector>\n#include <fstream>\n#include <thread>\n#include <unordered_map>\n#include <ctime>\n\n#include \"tasks.hpp\"\n#include \"sequence.h\"\n#include \"io.h\"\n#include \"alignment.h\"\n#include \"algorithms.h\"\n\n\/\/ This utilitu function returns the bytes remaining until the end of the file\n\/\/ is reached. It should be probably made publicly availale in a separate util\n\/\/ section of the library (e.g. util\/io.h)\nsize_t bytesRemainingToTheEnd(ifstream& ifs) {\n std::streampos tmp = ifs.tellg();\n ifs.seekg(0, ifs.end);\n size_t totalLength = ifs.tellg();\n ifs.seekg(tmp);\n return (totalLength - ifs.tellg());\n}\n\nvoid alignSmithWaterman(std::vector<Read>* reads, const Reference* ref, \n\t\t\tstd::vector<ScoredPosition<int,int> >* aligns, int indexOffset) {\n int nReads = reads->size();\n string refBases((char*)ref->getSequence());\n std::cout << \"Aligning \" << nReads << \" reads\" << std::endl;\n for (int i = 0; i < nReads; ++i) { \n SmithWatermanDP sw((*reads)[i].getBases(), refBases);\n sw.computeMatrix();\n MatrixPoint2D maxP = sw.getGlobalBest();\n aligns->push_back(ScoredPosition<int, int>((i + indexOffset),maxP.j, sw.getScoreAt(maxP)));\n }\n}\n\n\n\nstd::vector<ScoredPosition<int, int> > alignFastqReadsSimpleSW(const string& readsPath, const string& referencePath, \n\t\t\t\t\t\t\t std::ostream& output, uint64_t nThreads, size_t nReads) {\n \n std::cout << \"-- Smith Waterman alignment --\" << std::endl;\n std::cout.flush();\n \n std::vector<ScoredPosition<int,int> > aligns;\n\t\t\t\t\t\t \/\/ some constants\n uint64_t T = (nThreads > 0) ? nThreads : 1;\n uint64_t M = (nReads > 0) ? nReads : 0;\n\n std::cout << \" ************* \" << T << \" \" << M << \"**************\" << std::endl;\n std::cout.flush();\n\t \n \/\/ open files\n std::ifstream readsIn(readsPath, std::ifstream::in);\n \/\/ std::ifstream refIn(referencePath, std::ifstream::in); \n\n \/\/ list of all threads (use later for joining) \n std::vector<std::thread> threads;\n std::vector<std::vector<ScoredPosition<int,int> >*> threadAligns;\n\n \/\/ read input reference...\n std::cout << \" Loading reference...\" << std::endl;\n std::cout.flush();\n FastFormat fast;\n fast.loadFromFile(referencePath);\n Reference ref = (Reference)fast; \n\n \/\/ ...and reads\n std::cout << \" Loading reads...\" << std::endl;\n std::cout.flush();\n if (nReads >= 0) {\n \/\/ CASE 1: A specific total number of reads has been specified or\n uint64_t readsPerThread = (size_t)ceil( ((double)(M)) \/ ((double)(T)) );\n uint64_t actualReads = 0; \n \/\/ repeat for each thread\n for (uint64_t t = 0; t < T; ++t) {\n std::vector<Read>* reads = new std::vector<Read>();\n actualReads = 0;\n while( (!readsIn.eof()) && (actualReads < readsPerThread) ) {\t\n\tFastqRead r;\n\treadsIn >> r;\n\treads->push_back(r);\n \tactualReads++;\n }\n \/\/ create the aligns vector for the next starting thread\n std::vector<ScoredPosition<int,int> >* alignsVector = new std::vector<ScoredPosition< int,int > >();\n threadAligns.push_back(alignsVector);\n threads.push_back(std::thread(alignSmithWaterman, reads, &ref, alignsVector, t * readsPerThread));\n }\n\n\n } else {\n \/\/ CASE 2: we need to estimate the amount of reads to be assigned to each thread\n double fraction = 0;\n double D = 1.0 \/ ((double)T);\n \/\/ repeat for each thread\n for (uint64_t t = 0; t < T; ++t) {\n while( (!readsIn.eof()) && (fraction < D)) {\n \tfraction += 0.1;\n }\n \/\/ threads.push_back(std::thread(alignSmithWaterman,reads,&ref));\n }\n \n }\n\n \/\/ synchronize all threads\n for (auto& thr : threads) {\n thr.join();\n }\n aligns.clear();\n for (std::vector<ScoredPosition<int,int> >* v : threadAligns) {\n std::cout << \"++++ \" << v->size() << std::endl;\n aligns.insert(aligns.end(), v->begin(), v->end());\n delete v;\n }\n \n\n output << \"*** Alignments: \" << std::endl;\n for (ScoredPosition< int,int > p : aligns) {\n output << p.getSequenceId() << \"\\t\" << p.getPosition() << \" (\" << p.getScore() << \")\" << std::endl;\n }\n\n return aligns;\n}\n\n\/**************************** K-SPECTRUM FUNCTIONS ****************************\/\nvoid taskComputeKSpectrum(size_t k, const string& referenceFile) {\n FastFormat fast;\n fast.loadFromFile(referenceFile);\n Reference ref = (Reference) fast;\n std::unordered_map< uint64_t, uint64_t > index = spectrumAsIntMap(ref, k);\n for (std::pair< uint64_t, uint64_t > p : index) {\n std::cout << NumericKMer(p.first, k) << \" \" << p.second << std::endl;\n }\n}\n\nvoid taskMapReadsKmers(const string& reference, const string& reads, size_t k, const string& out) {\n std::cout << \"-------------------- Reads Mapping --------------------\" << std::endl;\n \/\/ open files\n std::ofstream outFileStream;\n if (!out.empty()) {\n outFileStream.open(out, std::ios::out);\n }\n std::ostream& outStream = (out.empty()) ? std::cout : outFileStream;\n FastFormat refFast;\n std::cout << \"Loading reference (\" << reference << \")...\";\n std::cout.flush();\n refFast.loadFromFile(reference);\n std::cout << \" Ok!\" << std::endl;\n Reference ref = refFast.toReference();\n \n std::ifstream readsStream(reads, std::ios::in);\n\n \/\/ compute index for the reference\n std::cout << \"Index creation...\";\n std::cout.flush();\n NumericKmerIndex index = kmersMapping(ref, k);\n std::cout << \" Ok!\" << std::endl;\n \/\/ scan reads and find mappings\n size_t read_index = 0;\n size_t kmer_index = 0;\n std::cout << \"Reads mapping...\";\n std::cout.flush();\n while(!readsStream.eof()) {\n FastqRead r;\n readsStream >> r;\n list< KMer > kmers = r.getKMerList(k);\n kmer_index = 0;\n for (KMer kmer : kmers) {\n NumericKMer nkmer(kmer);\n std::unordered_map< uint64_t, std::list< size_t > >::const_iterator it = index.find((uint64_t)nkmer);\n outStream << read_index << \":\" << kmer_index << \" \" << ((it == index.end()) ? (int64_t)(-1) : (int64_t)it->second.front() ) << std::endl;\n kmer_index++;\n }\n read_index++;\n }\n std::cout << \"Ok!\" << std::endl << \"-------------------- DONE --------------------\" << std::endl;\n}\n\n\/\/ Computes for each reads of the input set the kmerscore and the numero fo errors\n\/\/ (see algorithms\/kmerscore) against the reference sequence\nvoid taskKmerScoreReads(const string& reference, const string& reads, size_t k, const string& out) {\n\n \/\/ define output (either a file or the standard out)\n std::ofstream outFileStream;\n if (!out.empty()) {\n outFileStream.open(out, std::ios::out);\n }\n std::ostream& outStream = (out.empty()) ? std::cout : outFileStream;\n time_t beginTime, endTime;\n \n std::cout << \"-------------------- Reads Mapping --------------------\" << std::endl;\n \/\/ open files \n std::cout << \"Loading reference (\" << reference << \")...\";\n std::cout.flush(); \/\/ in case of stuck code we see at which point\n FastFormat refFast(reference); \n Reference ref = refFast.toReference();\n std::cout << \" Done (\" << ref.getSequenceLength() << \" bases)\" << std::endl;\n\n \/\/ open a stream for reading reads file\n std::ifstream readsStream(reads, std::ios::in);\n\n \/\/ compute the index for the reference\n std::cout << \"Index creation...\";\n std::cout.flush();\n time(&beginTime);\n NumericKmerIndex index = kmersMapping(ref, k); \n time(&endTime); \n std::cout << \" Ok! (\" << difftime(endTime, beginTime) << \" sec)\" << std::endl;\n}\n<commit_msg>little advance on the 'kscore' task<commit_after>#include <cmath>\n#include <vector>\n#include <fstream>\n#include <thread>\n#include <unordered_map>\n#include <ctime>\n\n#include \"tasks.hpp\"\n#include \"sequence.h\"\n#include \"io.h\"\n#include \"alignment.h\"\n#include \"algorithms.h\"\n\n\/\/ This utilitu function returns the bytes remaining until the end of the file\n\/\/ is reached. It should be probably made publicly availale in a separate util\n\/\/ section of the library (e.g. util\/io.h)\nsize_t bytesRemainingToTheEnd(ifstream& ifs) {\n std::streampos tmp = ifs.tellg();\n ifs.seekg(0, ifs.end);\n size_t totalLength = ifs.tellg();\n ifs.seekg(tmp);\n return (totalLength - ifs.tellg());\n}\n\nvoid alignSmithWaterman(std::vector<Read>* reads, const Reference* ref, \n\t\t\tstd::vector<ScoredPosition<int,int> >* aligns, int indexOffset) {\n int nReads = reads->size();\n string refBases((char*)ref->getSequence());\n std::cout << \"Aligning \" << nReads << \" reads\" << std::endl;\n for (int i = 0; i < nReads; ++i) { \n SmithWatermanDP sw((*reads)[i].getBases(), refBases);\n sw.computeMatrix();\n MatrixPoint2D maxP = sw.getGlobalBest();\n aligns->push_back(ScoredPosition<int, int>((i + indexOffset),maxP.j, sw.getScoreAt(maxP)));\n }\n}\n\n\n\nstd::vector<ScoredPosition<int, int> > alignFastqReadsSimpleSW(const string& readsPath, const string& referencePath, \n\t\t\t\t\t\t\t std::ostream& output, uint64_t nThreads, size_t nReads) {\n \n std::cout << \"-- Smith Waterman alignment --\" << std::endl;\n std::cout.flush();\n \n std::vector<ScoredPosition<int,int> > aligns;\n\t\t\t\t\t\t \/\/ some constants\n uint64_t T = (nThreads > 0) ? nThreads : 1;\n uint64_t M = (nReads > 0) ? nReads : 0;\n\n std::cout << \" ************* \" << T << \" \" << M << \"**************\" << std::endl;\n std::cout.flush();\n\t \n \/\/ open files\n std::ifstream readsIn(readsPath, std::ifstream::in);\n \/\/ std::ifstream refIn(referencePath, std::ifstream::in); \n\n \/\/ list of all threads (use later for joining) \n std::vector<std::thread> threads;\n std::vector<std::vector<ScoredPosition<int,int> >*> threadAligns;\n\n \/\/ read input reference...\n std::cout << \" Loading reference...\" << std::endl;\n std::cout.flush();\n FastFormat fast;\n fast.loadFromFile(referencePath);\n Reference ref = (Reference)fast; \n\n \/\/ ...and reads\n std::cout << \" Loading reads...\" << std::endl;\n std::cout.flush();\n if (nReads >= 0) {\n \/\/ CASE 1: A specific total number of reads has been specified or\n uint64_t readsPerThread = (size_t)ceil( ((double)(M)) \/ ((double)(T)) );\n uint64_t actualReads = 0; \n \/\/ repeat for each thread\n for (uint64_t t = 0; t < T; ++t) {\n std::vector<Read>* reads = new std::vector<Read>();\n actualReads = 0;\n while( (!readsIn.eof()) && (actualReads < readsPerThread) ) {\t\n\tFastqRead r;\n\treadsIn >> r;\n\treads->push_back(r);\n \tactualReads++;\n }\n \/\/ create the aligns vector for the next starting thread\n std::vector<ScoredPosition<int,int> >* alignsVector = new std::vector<ScoredPosition< int,int > >();\n threadAligns.push_back(alignsVector);\n threads.push_back(std::thread(alignSmithWaterman, reads, &ref, alignsVector, t * readsPerThread));\n }\n\n\n } else {\n \/\/ CASE 2: we need to estimate the amount of reads to be assigned to each thread\n double fraction = 0;\n double D = 1.0 \/ ((double)T);\n \/\/ repeat for each thread\n for (uint64_t t = 0; t < T; ++t) {\n while( (!readsIn.eof()) && (fraction < D)) {\n \tfraction += 0.1;\n }\n \/\/ threads.push_back(std::thread(alignSmithWaterman,reads,&ref));\n }\n \n }\n\n \/\/ synchronize all threads\n for (auto& thr : threads) {\n thr.join();\n }\n aligns.clear();\n for (std::vector<ScoredPosition<int,int> >* v : threadAligns) {\n std::cout << \"++++ \" << v->size() << std::endl;\n aligns.insert(aligns.end(), v->begin(), v->end());\n delete v;\n }\n \n\n output << \"*** Alignments: \" << std::endl;\n for (ScoredPosition< int,int > p : aligns) {\n output << p.getSequenceId() << \"\\t\" << p.getPosition() << \" (\" << p.getScore() << \")\" << std::endl;\n }\n\n return aligns;\n}\n\n\/**************************** K-SPECTRUM FUNCTIONS ****************************\/\nvoid taskComputeKSpectrum(size_t k, const string& referenceFile) {\n FastFormat fast;\n fast.loadFromFile(referenceFile);\n Reference ref = (Reference) fast;\n std::unordered_map< uint64_t, uint64_t > index = spectrumAsIntMap(ref, k);\n for (std::pair< uint64_t, uint64_t > p : index) {\n std::cout << NumericKMer(p.first, k) << \" \" << p.second << std::endl;\n }\n}\n\nvoid taskMapReadsKmers(const string& reference, const string& reads, size_t k, const string& out) {\n std::cout << \"-------------------- Reads Mapping --------------------\" << std::endl;\n \/\/ open files\n std::ofstream outFileStream;\n if (!out.empty()) {\n outFileStream.open(out, std::ios::out);\n }\n std::ostream& outStream = (out.empty()) ? std::cout : outFileStream;\n FastFormat refFast;\n std::cout << \"Loading reference (\" << reference << \")...\";\n std::cout.flush();\n refFast.loadFromFile(reference);\n std::cout << \" Ok!\" << std::endl;\n Reference ref = refFast.toReference();\n \n std::ifstream readsStream(reads, std::ios::in);\n\n \/\/ compute index for the reference\n std::cout << \"Index creation...\";\n std::cout.flush();\n NumericKmerIndex index = kmersMapping(ref, k);\n std::cout << \" Ok!\" << std::endl;\n \/\/ scan reads and find mappings\n size_t read_index = 0;\n size_t kmer_index = 0;\n std::cout << \"Reads mapping...\";\n std::cout.flush();\n while(!readsStream.eof()) {\n FastqRead r;\n readsStream >> r;\n list< KMer > kmers = r.getKMerList(k);\n kmer_index = 0;\n for (KMer kmer : kmers) {\n NumericKMer nkmer(kmer);\n std::unordered_map< uint64_t, std::list< size_t > >::const_iterator it = index.find((uint64_t)nkmer);\n outStream << read_index << \":\" << kmer_index << \" \" << ((it == index.end()) ? (int64_t)(-1) : (int64_t)it->second.front() ) << std::endl;\n kmer_index++;\n }\n read_index++;\n }\n std::cout << \"Ok!\" << std::endl << \"-------------------- DONE --------------------\" << std::endl;\n}\n\n\/\/ Computes for each reads of the input set the kmerscore and the numero fo errors\n\/\/ (see algorithms\/kmerscore) against the reference sequence\nvoid taskKmerScoreReads(const string& reference, const string& reads, size_t k, const string& out) {\n\n \/\/ define output (either a file or the standard out)\n std::ofstream outFileStream;\n if (!out.empty()) {\n outFileStream.open(out, std::ios::out);\n }\n std::ostream& outStream = (out.empty()) ? std::cout : outFileStream;\n time_t beginTime, endTime;\n \n std::cout << \"-------------------- Reads Mapping --------------------\" << std::endl;\n \/\/ open files \n std::cout << \"Loading reference (\" << reference << \")...\";\n std::cout.flush(); \/\/ in case of stuck code we see at which point\n FastFormat refFast(reference); \n Reference ref = refFast.toReference();\n std::cout << \" Done (\" << ref.getSequenceLength() << \" bases)\" << std::endl;\n\n \/\/ open a stream for reading reads file\n std::ifstream readsStream(reads, std::ios::in);\n\n \/\/ compute the index for the reference\n std::cout << \"Index creation...\";\n std::cout.flush();\n time(&beginTime);\n NumericKmerIndex index = kmersMapping(ref, k);\n time(&endTime); \n std::cout << \" Ok! (\" << difftime(endTime, beginTime) << \" sec)\" << std::endl;\n std::cout << \"Calculating scores...\";\n std::cout.flush();\n size_t M = 0;\n time(&beginTime);\n while(!readsStream.eof()) {\n FastqRead r;\n readsStream >> r;\n if (r.getSequenceLength() == 0) {\n continue;\n }\n \/\/std::cout << r << \" (\" << M << \")\" << std::endl; std::cout.flush(); \/\/ just for debug\n KmersMap map = extractKmersMapPosition(r, index, k);\n M++;\n }\n readsStream.close();\n time(&endTime);\n double elapsed = difftime(endTime, beginTime);\n double rate = M \/ elapsed;\n std::cout << \" Done (\" << M << \" reads in \" << elapsed << \" sec, \" << rate << \" reads\/sec)\" << std::endl;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"hasher.hxx\"\n\nusing namespace std;\nusing namespace Py;\n\nSequenceHasher::SequenceHasher(){\n\n _ref = NULL;\n _initialized = false;\n\n}\n\nSequenceHasher::~SequenceHasher(){\n if( _ref ){\n delete _ref;\n }\n\n list<ObservationSet*>::iterator obs_itr;\n\n for( obs_itr = _obs.begin(); obs_itr != _obs.end(); obs_itr++ ){\n delete (*obs_itr);\n }\n _obs.clear();\n}\n\npriority_queue<pair<double, string> > SequenceHasher::hash(string sequence){\n\n if( !_initialized ){\n initialize();\n }\n\n ObservationSet os(sequence);\n list<ObservationSet*>::iterator l_itr;\n\n priority_queue<pair<double, string> > rpq;\n for(l_itr = _obs.begin(); l_itr != _obs.end(); l_itr++){\n\n double likelihood = (*l_itr)->likelihood(&os, _ref);\n string nm = (*l_itr)->getName();\n rpq.push(pair<double, string>(likelihood, nm));\n }\n \n return rpq;\n}\n\nvoid SequenceHasher::addReference(string name, string sequence){\n\n \/\/TODO Ensure that arguments are in a consistent order\n ObservationSet* ob = new ObservationSet(sequence, name);\n _obs.push_back(ob);\n\n _initialized = false;\n return;\n}\n\nvoid SequenceHasher::initialize(){\n _initialized = true;\n if( !_ref ){ delete _ref; }\n\n _ref = new ReferenceSet(_obs);\n list<ObservationSet*>::iterator obs_itr;\n\n return;\n}\n\nObject SequenceHasher::py_addReference( const Tuple &args ){\n args.verify_length(2);\n String name = args[0];\n String sequence = args[1];\n\n addReference(name, sequence);\n\n return args[0];\n}\n\nObject SequenceHasher::py_hash( const Tuple &args ){\n args.verify_length(1);\n String sequence = args[0];\n priority_queue<pair<double, string> > results = hash(sequence);\n\n Dict d;\n \n while( !results.empty() ){\n double likelihood = results.top().first;\n string name = results.top().second;\n d[String(name)] = Float(floor(likelihood * 10000));\n results.pop();\n }\n\n return d;\n}\n\nObject SequenceHasher::getattr( const char *name ){\n return getattr_methods(name);\n}\n\nObject SequenceHasher::repr(){\n return Py::String(\"A Hashed based Naive Bayes Classifier for sequence classification\");\n}\n\nvoid SequenceHasher::init_type(){\n behaviors().name(\"SequenceHasher\");\n behaviors().doc(\"SequenceHasher objects: nil\");\n behaviors().supportGetattr();\n behaviors().supportRepr();\n\n add_varargs_method(\"addReference\", &SequenceHasher::py_addReference, \"addReference(name, sequence)\");\n add_varargs_method(\"hash\", &SequenceHasher::py_hash, \"hash(sequence)\");\n add_varargs_method(\"reference_count\", &SequenceHasher::reference_count);\n}\n\nclass hasher_module : public Py::ExtensionModule<hasher_module>\n{\npublic:\n hasher_module()\n : Py::ExtensionModule<hasher_module>(\"hasher\")\n {\n SequenceHasher::init_type();\n add_varargs_method(\"SequenceHasher\", &hasher_module::new_hasher);\n initialize( \"docs\" );\n }\n\n virtual ~hasher_module()\n {}\n\nprivate:\n Object new_hasher(const Py::Tuple& args){\n return asObject(new SequenceHasher());\n }\n};\n\nextern \"C\" void inithasher()\n{\n#if defined(PY_WIN32_DELAYLOAD_PYTHON_DLL)\n Py::InitialisePythonIndirectPy::Interface();\n#endif\n static hasher_module* hasher = new hasher_module;\n}\n<commit_msg>We have a Naive Bayes Classifier for sequence analysis. It works with python. It produces correct results.<commit_after>#include \"hasher.hxx\"\n\nusing namespace std;\nusing namespace Py;\n\nSequenceHasher::SequenceHasher(){\n\n _ref = NULL;\n _initialized = false;\n\n}\n\nSequenceHasher::~SequenceHasher(){\n if( _ref ){\n delete _ref;\n }\n\n list<ObservationSet*>::iterator obs_itr;\n\n for( obs_itr = _obs.begin(); obs_itr != _obs.end(); obs_itr++ ){\n delete (*obs_itr);\n }\n _obs.clear();\n}\n\npriority_queue<pair<double, string> > SequenceHasher::hash(string sequence){\n\n if( !_initialized ){\n initialize();\n }\n\n ObservationSet os(sequence);\n list<ObservationSet*>::iterator l_itr;\n\n priority_queue<pair<double, string> > rpq;\n for(l_itr = _obs.begin(); l_itr != _obs.end(); l_itr++){\n\n double likelihood = (*l_itr)->likelihood(&os, _ref);\n string nm = (*l_itr)->getName();\n rpq.push(pair<double, string>(likelihood, nm));\n }\n \n return rpq;\n}\n\nvoid SequenceHasher::addReference(string name, string sequence){\n\n \/\/TODO Ensure that arguments are in a consistent order\n ObservationSet* ob = new ObservationSet(sequence, name);\n _obs.push_back(ob);\n\n _initialized = false;\n return;\n}\n\nvoid SequenceHasher::initialize(){\n _initialized = true;\n if( !_ref ){ delete _ref; }\n\n _ref = new ReferenceSet(_obs);\n list<ObservationSet*>::iterator obs_itr;\n\n return;\n}\n\nObject SequenceHasher::py_addReference( const Tuple &args ){\n args.verify_length(2);\n String name = args[0];\n String sequence = args[1];\n\n addReference(name, sequence);\n\n return args[0];\n}\n\nObject SequenceHasher::py_hash( const Tuple &args ){\n args.verify_length(1);\n String sequence = args[0];\n priority_queue<pair<double, string> > results = hash(sequence);\n\n List d;\n \n while( !results.empty() ){\n string name = results.top().second;\n d.append(String(name));\n results.pop();\n }\n\n return d;\n}\n\nObject SequenceHasher::getattr( const char *name ){\n return getattr_methods(name);\n}\n\nObject SequenceHasher::repr(){\n return Py::String(\"A Hashed based Naive Bayes Classifier for sequence classification\");\n}\n\nvoid SequenceHasher::init_type(){\n behaviors().name(\"SequenceHasher\");\n behaviors().doc(\"SequenceHasher objects: nil\");\n behaviors().supportGetattr();\n behaviors().supportRepr();\n\n add_varargs_method(\"addReference\", &SequenceHasher::py_addReference, \"addReference(name, sequence)\");\n add_varargs_method(\"hash\", &SequenceHasher::py_hash, \"hash(sequence)\");\n add_varargs_method(\"reference_count\", &SequenceHasher::reference_count);\n}\n\nclass hasher_module : public Py::ExtensionModule<hasher_module>\n{\npublic:\n hasher_module()\n : Py::ExtensionModule<hasher_module>(\"hasher\")\n {\n SequenceHasher::init_type();\n add_varargs_method(\"SequenceHasher\", &hasher_module::new_hasher);\n initialize( \"docs\" );\n }\n\n virtual ~hasher_module()\n {}\n\nprivate:\n Object new_hasher(const Py::Tuple& args){\n return asObject(new SequenceHasher());\n }\n};\n\nextern \"C\" void inithasher()\n{\n#if defined(PY_WIN32_DELAYLOAD_PYTHON_DLL)\n Py::InitialisePythonIndirectPy::Interface();\n#endif\n static hasher_module* hasher = new hasher_module;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright 2007-2017 Content Management AG\n * All rights reserved.\n *\n * author: Max Kellermann <mk@cm4all.com>\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * - Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n *\n * - Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the\n * distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,\n * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED\n * OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \"ForwardHttpRequest.hxx\"\n#include \"HttpConnection.hxx\"\n#include \"Cluster.hxx\"\n#include \"ClusterConfig.hxx\"\n#include \"ListenerConfig.hxx\"\n#include \"Instance.hxx\"\n#include \"Session.hxx\"\n#include \"Cookie.hxx\"\n#include \"JvmRoute.hxx\"\n#include \"Headers.hxx\"\n#include \"ssl\/Filter.hxx\"\n#include \"address_sticky.hxx\"\n#include \"address_string.hxx\"\n#include \"http_server\/http_server.hxx\"\n#include \"http\/IncomingRequest.hxx\"\n#include \"http_server\/Handler.hxx\"\n#include \"http_client.hxx\"\n#include \"fs\/Stock.hxx\"\n#include \"fs\/Balancer.hxx\"\n#include \"HttpResponseHandler.hxx\"\n#include \"http\/Headers.hxx\"\n#include \"stock\/GetHandler.hxx\"\n#include \"stock\/Item.hxx\"\n#include \"lease.hxx\"\n#include \"strmap.hxx\"\n#include \"pool\/pool.hxx\"\n#include \"net\/IPv4Address.hxx\"\n#include \"net\/IPv6Address.hxx\"\n#include \"net\/SocketAddress.hxx\"\n#include \"net\/SocketDescriptor.hxx\"\n#include \"net\/FailureManager.hxx\"\n#include \"net\/FailureRef.hxx\"\n#include \"istream\/istream.hxx\"\n#include \"istream\/UnusedHoldPtr.hxx\"\n#include \"util\/Cancellable.hxx\"\n#include \"util\/LeakDetector.hxx\"\n#include \"util\/FNVHash.hxx\"\n#include \"AllocatorPtr.hxx\"\n#include \"stopwatch.hxx\"\n\nstatic constexpr Event::Duration LB_HTTP_CONNECT_TIMEOUT =\n std::chrono::seconds(20);\n\nclass LbRequest final\n : LeakDetector, Cancellable, StockGetHandler, Lease, HttpResponseHandler {\n\n struct pool &pool;\n\n LbHttpConnection &connection;\n LbCluster &cluster;\n const LbClusterConfig &cluster_config;\n\n FilteredSocketBalancer &balancer;\n\n IncomingHttpRequest &request;\n\n \/**\n * The request body.\n *\/\n UnusedHoldIstreamPtr body;\n\n CancellablePointer cancel_ptr;\n\n \/**\n * The cluster member we're currently connecting to (waiting for\n * #StockGetHandler to be called). Only used for Zeroconf to be\n * able to call failure_set().\n *\/\n LbCluster::MemberPtr current_member;\n\n StockItem *stock_item = nullptr;\n FailurePtr failure;\n\n \/**\n * The number of remaining connection attempts. We give up when\n * we get an error and this attribute is already zero.\n *\/\n unsigned retries;\n\n unsigned new_cookie = 0;\n\n bool response_sent = false;\n\npublic:\n LbRequest(LbHttpConnection &_connection, LbCluster &_cluster,\n FilteredSocketBalancer &_balancer,\n IncomingHttpRequest &_request,\n CancellablePointer &_cancel_ptr) noexcept\n :pool(_request.pool), connection(_connection), cluster(_cluster),\n cluster_config(cluster.GetConfig()),\n balancer(_balancer),\n request(_request),\n body(pool, std::move(request.body)) {\n _cancel_ptr = *this;\n\n if (cluster_config.HasZeroConf())\n retries = CalculateRetries(cluster.GetZeroconfCount());\n }\n\n EventLoop &GetEventLoop() const noexcept {\n return connection.instance.event_loop;\n }\n\n FailureManager &GetFailureManager() noexcept {\n return balancer.GetFailureManager();\n }\n\n void Start() noexcept;\n\nprivate:\n \/* code copied from generic_balancer.hxx *\/\n static constexpr unsigned CalculateRetries(size_t size) noexcept {\n if (size <= 1)\n return 0;\n else if (size == 2)\n return 1;\n else if (size == 3)\n return 2;\n else\n return 3;\n }\n\n void Destroy() noexcept {\n assert(stock_item == nullptr);\n\n this->~LbRequest();\n }\n\n void SetForwardedTo() noexcept {\n \/\/ TODO: optimize this operation\n connection.per_request.forwarded_to =\n address_to_string(pool,\n GetFailureManager().GetAddress(*failure));\n }\n\n void ResponseSent() noexcept {\n assert(!response_sent);\n response_sent = true;\n\n if (stock_item == nullptr)\n Destroy();\n }\n\n const char *GetCanonicalHost() const noexcept {\n return connection.per_request.GetCanonicalHost();\n }\n\n sticky_hash_t GetStickyHash() noexcept;\n sticky_hash_t GetHostHash() const noexcept;\n sticky_hash_t GetXHostHash() const noexcept;\n sticky_hash_t MakeCookieHash() noexcept;\n\n SocketAddress MakeBindAddress() const noexcept;\n\n \/* virtual methods from class Cancellable *\/\n void Cancel() noexcept override {\n assert(!response_sent);\n\n cancel_ptr.Cancel();\n Destroy();\n }\n\n \/* virtual methods from class StockGetHandler *\/\n void OnStockItemReady(StockItem &item) noexcept override;\n void OnStockItemError(std::exception_ptr ep) noexcept override;\n\n \/* virtual methods from class Lease *\/\n void ReleaseLease(bool reuse) noexcept override;\n\n \/* virtual methods from class HttpResponseHandler *\/\n void OnHttpResponse(http_status_t status, StringMap &&headers,\n UnusedIstreamPtr body) noexcept override;\n void OnHttpError(std::exception_ptr ep) noexcept override;\n};\n\nstatic void\nSendResponse(IncomingHttpRequest &request,\n const LbSimpleHttpResponse &response) noexcept\n{\n assert(response.IsDefined());\n\n request.SendSimpleResponse(response.status,\n response.location.empty() ? nullptr : response.location.c_str(),\n response.message.empty() ? nullptr : response.message.c_str());\n}\n\nstatic bool\nsend_fallback(IncomingHttpRequest &request,\n const LbSimpleHttpResponse &fallback) noexcept\n{\n if (!fallback.IsDefined())\n return false;\n\n SendResponse(request, fallback);\n return true;\n}\n\ninline sticky_hash_t\nLbRequest::GetHostHash() const noexcept\n{\n const char *host = GetCanonicalHost();\n if (host == nullptr)\n return 0;\n\n return FNV1aHash32(host);\n}\n\ninline sticky_hash_t\nLbRequest::GetXHostHash() const noexcept\n{\n const char *host = request.headers.Get(\"x-cm4all-host\");\n if (host == nullptr)\n return 0;\n\n return FNV1aHash32(host);\n}\n\n\/**\n * Generate a cookie for sticky worker selection. Return only worker\n * numbers that are not known to be failing. Returns 0 on total\n * failure.\n *\/\nstatic unsigned\nGenerateCookie(const FailureManager &failure_manager, Expiry now,\n const AddressList &list) noexcept\n{\n assert(list.GetSize() >= 2);\n\n const unsigned first = lb_cookie_generate(list.GetSize());\n\n unsigned i = first;\n do {\n assert(i >= 1 && i <= list.GetSize());\n const SocketAddress address = list.addresses[i % list.GetSize()];\n if (failure_manager.Check(now, address))\n return i;\n\n i = lb_cookie_next(list.GetSize(), i);\n } while (i != first);\n\n \/* all nodes have failed *\/\n return first;\n}\n\nsticky_hash_t\nLbRequest::MakeCookieHash() noexcept\n{\n unsigned hash = lb_cookie_get(request.headers);\n if (hash == 0)\n new_cookie = hash = GenerateCookie(GetFailureManager(),\n GetEventLoop().SteadyNow(),\n cluster_config.address_list);\n\n return hash;\n}\n\nsticky_hash_t\nLbRequest::GetStickyHash() noexcept\n{\n switch (cluster_config.sticky_mode) {\n case StickyMode::NONE:\n case StickyMode::FAILOVER:\n \/* these modes require no preparation; they are handled\n completely by balancer_get() *\/\n return 0;\n\n case StickyMode::SOURCE_IP:\n \/* calculate session_sticky from remote address *\/\n return socket_address_sticky(request.remote_address);\n\n case StickyMode::HOST:\n \/* calculate session_sticky from \"Host\" request header *\/\n return GetHostHash();\n\n case StickyMode::XHOST:\n \/* calculate session_sticky from \"X-CM4all-Host\" request\n header *\/\n return GetXHostHash();\n\n case StickyMode::SESSION_MODULO:\n \/* calculate session_sticky from beng-proxy session id *\/\n return lb_session_get(request.headers,\n cluster_config.session_cookie.c_str());\n\n case StickyMode::COOKIE:\n \/* calculate session_sticky from beng-lb cookie *\/\n return MakeCookieHash();\n\n case StickyMode::JVM_ROUTE:\n \/* calculate session_sticky from JSESSIONID cookie suffix *\/\n return lb_jvm_route_get(request.headers, cluster_config);\n }\n\n assert(false);\n gcc_unreachable();\n}\n\n\/*\n * HTTP response handler\n *\n *\/\n\nvoid\nLbRequest::OnHttpResponse(http_status_t status, StringMap &&_headers,\n UnusedIstreamPtr response_body) noexcept\n{\n assert(!response_sent);\n\n failure->UnsetProtocol();\n\n SetForwardedTo();\n\n HttpHeaders headers(std::move(_headers));\n\n if (request.method == HTTP_METHOD_HEAD)\n \/* pass Content-Length, even though there is no response body\n (RFC 2616 14.13) *\/\n headers.MoveToBuffer(\"content-length\");\n\n if (new_cookie != 0) {\n char buffer[64];\n \/* \"Discard\" must be last, to work around an Android bug*\/\n snprintf(buffer, sizeof(buffer),\n \"beng_lb_node=0-%x; HttpOnly; Path=\/; Version=1; Discard\",\n new_cookie);\n\n headers.Write(\"cookie2\", \"$Version=\\\"1\\\"\");\n headers.Write(\"set-cookie\", buffer);\n }\n\n request.SendResponse(status, std::move(headers), std::move(response_body));\n ResponseSent();\n}\n\nvoid\nLbRequest::OnHttpError(std::exception_ptr ep) noexcept\n{\n assert(!response_sent);\n\n if (IsHttpClientServerFailure(ep))\n failure->SetProtocol(GetEventLoop().SteadyNow(),\n std::chrono::seconds(20));\n\n SetForwardedTo();\n\n connection.logger(2, ep);\n\n if (!send_fallback(request, cluster_config.fallback))\n connection.SendError(request, ep);\n\n ResponseSent();\n}\n\n\/*\n * stock callback\n *\n *\/\n\nvoid\nLbRequest::OnStockItemReady(StockItem &item) noexcept\n{\n assert(stock_item == nullptr);\n assert(!response_sent);\n\n stock_item = &item;\n\n if (cluster_config.HasZeroConf()) {\n failure = current_member->GetFailureRef();\n\n \/* without the fs_balancer, we have to roll our own failure\n updates *\/\n failure->UnsetConnect();\n } else\n failure = GetFailureManager().Make(fs_stock_item_get_address(*stock_item));\n\n const char *peer_subject = connection.ssl_filter != nullptr\n ? ssl_filter_get_peer_subject(connection.ssl_filter)\n : nullptr;\n const char *peer_issuer_subject = connection.ssl_filter != nullptr\n ? ssl_filter_get_peer_issuer_subject(connection.ssl_filter)\n : nullptr;\n\n auto &headers = request.headers;\n lb_forward_request_headers(pool, headers,\n request.local_host_and_port,\n request.remote_host,\n connection.IsEncrypted(),\n peer_subject, peer_issuer_subject,\n cluster_config.mangle_via);\n\n http_client_request(pool, nullptr,\n fs_stock_item_get(item),\n *this,\n item.GetStockName(),\n request.method, request.uri,\n HttpHeaders(std::move(headers)),\n std::move(body), true,\n *this, cancel_ptr);\n}\n\nvoid\nLbRequest::OnStockItemError(std::exception_ptr ep) noexcept\n{\n assert(stock_item == nullptr);\n assert(!response_sent);\n\n connection.logger(2, \"Connect error: \", ep);\n\n if (cluster_config.HasZeroConf()) {\n \/* without the tcp_balancer, we have to roll our own failure\n updates and retries *\/\n current_member->GetFailureInfo().SetConnect(GetEventLoop().SteadyNow(),\n std::chrono::seconds(20));\n\n if (retries-- > 0) {\n \/* try the next Zeroconf member *\/\n Start();\n return;\n }\n }\n\n body.Clear();\n\n if (!send_fallback(request, cluster_config.fallback))\n connection.SendError(request, ep);\n\n ResponseSent();\n}\n\n\/*\n * Lease\n *\n *\/\n\nvoid\nLbRequest::ReleaseLease(bool reuse) noexcept\n{\n assert(stock_item != nullptr);\n\n stock_item->Put(!reuse);\n stock_item = nullptr;\n\n if (response_sent) {\n Destroy();\n }\n}\n\n\/*\n * constructor\n *\n *\/\n\ninline SocketAddress\nLbRequest::MakeBindAddress() const noexcept\n{\n if (cluster_config.transparent_source) {\n SocketAddress bind_address = request.remote_address;\n\n \/* reset the port to 0 to allow the kernel to choose one *\/\n if (bind_address.GetFamily() == AF_INET) {\n auto &address = *NewFromPool<IPv4Address>(pool,\n IPv4Address(bind_address));\n address.SetPort(0);\n return address;\n } else if (bind_address.GetFamily() == AF_INET6) {\n auto &address = *NewFromPool<IPv6Address>(pool,\n IPv6Address(bind_address));\n address.SetPort(0);\n return address;\n }\n\n return bind_address;\n } else\n return SocketAddress::Null();\n}\n\ninline void\nLbRequest::Start() noexcept\n{\n const auto bind_address = MakeBindAddress();\n\n if (cluster_config.HasZeroConf()) {\n auto *member = cluster.Pick(GetEventLoop().SteadyNow(),\n GetStickyHash());\n if (member == nullptr) {\n auto &_request = request;\n Destroy();\n _request.SendMessage(HTTP_STATUS_INTERNAL_SERVER_ERROR,\n \"Zeroconf cluster is empty\");\n return;\n }\n\n current_member = *member;\n\n connection.instance.fs_stock->Get(pool,\n nullptr,\n member->GetLogName(),\n cluster_config.transparent_source,\n bind_address,\n member->GetAddress(),\n LB_HTTP_CONNECT_TIMEOUT,\n nullptr,\n *this, cancel_ptr);\n\n return;\n }\n\n balancer.Get(pool, nullptr,\n cluster_config.transparent_source,\n bind_address,\n GetStickyHash(),\n cluster_config.address_list,\n LB_HTTP_CONNECT_TIMEOUT,\n nullptr,\n *this, cancel_ptr);\n}\n\nvoid\nForwardHttpRequest(LbHttpConnection &connection,\n IncomingHttpRequest &request,\n LbCluster &cluster,\n CancellablePointer &cancel_ptr) noexcept\n{\n const auto request2 =\n NewFromPool<LbRequest>(request.pool,\n connection, cluster,\n *connection.instance.fs_balancer,\n request, cancel_ptr);\n request2->Start();\n}\n<commit_msg>lb\/ForwardHttpRequest: destroy LbRequest before sending response<commit_after>\/*\n * Copyright 2007-2017 Content Management AG\n * All rights reserved.\n *\n * author: Max Kellermann <mk@cm4all.com>\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * - Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n *\n * - Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the\n * distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,\n * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED\n * OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \"ForwardHttpRequest.hxx\"\n#include \"HttpConnection.hxx\"\n#include \"Cluster.hxx\"\n#include \"ClusterConfig.hxx\"\n#include \"ListenerConfig.hxx\"\n#include \"Instance.hxx\"\n#include \"Session.hxx\"\n#include \"Cookie.hxx\"\n#include \"JvmRoute.hxx\"\n#include \"Headers.hxx\"\n#include \"ssl\/Filter.hxx\"\n#include \"address_sticky.hxx\"\n#include \"address_string.hxx\"\n#include \"http_server\/http_server.hxx\"\n#include \"http\/IncomingRequest.hxx\"\n#include \"http_server\/Handler.hxx\"\n#include \"http_client.hxx\"\n#include \"fs\/Stock.hxx\"\n#include \"fs\/Balancer.hxx\"\n#include \"HttpResponseHandler.hxx\"\n#include \"http\/Headers.hxx\"\n#include \"stock\/GetHandler.hxx\"\n#include \"stock\/Item.hxx\"\n#include \"lease.hxx\"\n#include \"strmap.hxx\"\n#include \"pool\/pool.hxx\"\n#include \"net\/IPv4Address.hxx\"\n#include \"net\/IPv6Address.hxx\"\n#include \"net\/SocketAddress.hxx\"\n#include \"net\/SocketDescriptor.hxx\"\n#include \"net\/FailureManager.hxx\"\n#include \"net\/FailureRef.hxx\"\n#include \"istream\/istream.hxx\"\n#include \"istream\/UnusedHoldPtr.hxx\"\n#include \"util\/Cancellable.hxx\"\n#include \"util\/LeakDetector.hxx\"\n#include \"util\/FNVHash.hxx\"\n#include \"AllocatorPtr.hxx\"\n#include \"stopwatch.hxx\"\n\nstatic constexpr Event::Duration LB_HTTP_CONNECT_TIMEOUT =\n std::chrono::seconds(20);\n\nclass LbRequest final\n : LeakDetector, Cancellable, StockGetHandler, Lease, HttpResponseHandler {\n\n struct pool &pool;\n\n LbHttpConnection &connection;\n LbCluster &cluster;\n const LbClusterConfig &cluster_config;\n\n FilteredSocketBalancer &balancer;\n\n IncomingHttpRequest &request;\n\n \/**\n * The request body.\n *\/\n UnusedHoldIstreamPtr body;\n\n CancellablePointer cancel_ptr;\n\n \/**\n * The cluster member we're currently connecting to (waiting for\n * #StockGetHandler to be called). Only used for Zeroconf to be\n * able to call failure_set().\n *\/\n LbCluster::MemberPtr current_member;\n\n StockItem *stock_item = nullptr;\n FailurePtr failure;\n\n \/**\n * The number of remaining connection attempts. We give up when\n * we get an error and this attribute is already zero.\n *\/\n unsigned retries;\n\n unsigned new_cookie = 0;\n\n bool response_sent = false;\n\npublic:\n LbRequest(LbHttpConnection &_connection, LbCluster &_cluster,\n FilteredSocketBalancer &_balancer,\n IncomingHttpRequest &_request,\n CancellablePointer &_cancel_ptr) noexcept\n :pool(_request.pool), connection(_connection), cluster(_cluster),\n cluster_config(cluster.GetConfig()),\n balancer(_balancer),\n request(_request),\n body(pool, std::move(request.body)) {\n _cancel_ptr = *this;\n\n if (cluster_config.HasZeroConf())\n retries = CalculateRetries(cluster.GetZeroconfCount());\n }\n\n EventLoop &GetEventLoop() const noexcept {\n return connection.instance.event_loop;\n }\n\n FailureManager &GetFailureManager() noexcept {\n return balancer.GetFailureManager();\n }\n\n void Start() noexcept;\n\nprivate:\n \/* code copied from generic_balancer.hxx *\/\n static constexpr unsigned CalculateRetries(size_t size) noexcept {\n if (size <= 1)\n return 0;\n else if (size == 2)\n return 1;\n else if (size == 3)\n return 2;\n else\n return 3;\n }\n\n void Destroy() noexcept {\n assert(stock_item == nullptr);\n\n this->~LbRequest();\n }\n\n void SetForwardedTo() noexcept {\n \/\/ TODO: optimize this operation\n connection.per_request.forwarded_to =\n address_to_string(pool,\n GetFailureManager().GetAddress(*failure));\n }\n\n void ResponseSent() noexcept {\n assert(!response_sent);\n response_sent = true;\n\n if (stock_item == nullptr)\n Destroy();\n }\n\n const char *GetCanonicalHost() const noexcept {\n return connection.per_request.GetCanonicalHost();\n }\n\n sticky_hash_t GetStickyHash() noexcept;\n sticky_hash_t GetHostHash() const noexcept;\n sticky_hash_t GetXHostHash() const noexcept;\n sticky_hash_t MakeCookieHash() noexcept;\n\n SocketAddress MakeBindAddress() const noexcept;\n\n \/* virtual methods from class Cancellable *\/\n void Cancel() noexcept override {\n assert(!response_sent);\n\n cancel_ptr.Cancel();\n Destroy();\n }\n\n \/* virtual methods from class StockGetHandler *\/\n void OnStockItemReady(StockItem &item) noexcept override;\n void OnStockItemError(std::exception_ptr ep) noexcept override;\n\n \/* virtual methods from class Lease *\/\n void ReleaseLease(bool reuse) noexcept override;\n\n \/* virtual methods from class HttpResponseHandler *\/\n void OnHttpResponse(http_status_t status, StringMap &&headers,\n UnusedIstreamPtr body) noexcept override;\n void OnHttpError(std::exception_ptr ep) noexcept override;\n};\n\nstatic void\nSendResponse(IncomingHttpRequest &request,\n const LbSimpleHttpResponse &response) noexcept\n{\n assert(response.IsDefined());\n\n request.SendSimpleResponse(response.status,\n response.location.empty() ? nullptr : response.location.c_str(),\n response.message.empty() ? nullptr : response.message.c_str());\n}\n\nstatic bool\nsend_fallback(IncomingHttpRequest &request,\n const LbSimpleHttpResponse &fallback) noexcept\n{\n if (!fallback.IsDefined())\n return false;\n\n SendResponse(request, fallback);\n return true;\n}\n\ninline sticky_hash_t\nLbRequest::GetHostHash() const noexcept\n{\n const char *host = GetCanonicalHost();\n if (host == nullptr)\n return 0;\n\n return FNV1aHash32(host);\n}\n\ninline sticky_hash_t\nLbRequest::GetXHostHash() const noexcept\n{\n const char *host = request.headers.Get(\"x-cm4all-host\");\n if (host == nullptr)\n return 0;\n\n return FNV1aHash32(host);\n}\n\n\/**\n * Generate a cookie for sticky worker selection. Return only worker\n * numbers that are not known to be failing. Returns 0 on total\n * failure.\n *\/\nstatic unsigned\nGenerateCookie(const FailureManager &failure_manager, Expiry now,\n const AddressList &list) noexcept\n{\n assert(list.GetSize() >= 2);\n\n const unsigned first = lb_cookie_generate(list.GetSize());\n\n unsigned i = first;\n do {\n assert(i >= 1 && i <= list.GetSize());\n const SocketAddress address = list.addresses[i % list.GetSize()];\n if (failure_manager.Check(now, address))\n return i;\n\n i = lb_cookie_next(list.GetSize(), i);\n } while (i != first);\n\n \/* all nodes have failed *\/\n return first;\n}\n\nsticky_hash_t\nLbRequest::MakeCookieHash() noexcept\n{\n unsigned hash = lb_cookie_get(request.headers);\n if (hash == 0)\n new_cookie = hash = GenerateCookie(GetFailureManager(),\n GetEventLoop().SteadyNow(),\n cluster_config.address_list);\n\n return hash;\n}\n\nsticky_hash_t\nLbRequest::GetStickyHash() noexcept\n{\n switch (cluster_config.sticky_mode) {\n case StickyMode::NONE:\n case StickyMode::FAILOVER:\n \/* these modes require no preparation; they are handled\n completely by balancer_get() *\/\n return 0;\n\n case StickyMode::SOURCE_IP:\n \/* calculate session_sticky from remote address *\/\n return socket_address_sticky(request.remote_address);\n\n case StickyMode::HOST:\n \/* calculate session_sticky from \"Host\" request header *\/\n return GetHostHash();\n\n case StickyMode::XHOST:\n \/* calculate session_sticky from \"X-CM4all-Host\" request\n header *\/\n return GetXHostHash();\n\n case StickyMode::SESSION_MODULO:\n \/* calculate session_sticky from beng-proxy session id *\/\n return lb_session_get(request.headers,\n cluster_config.session_cookie.c_str());\n\n case StickyMode::COOKIE:\n \/* calculate session_sticky from beng-lb cookie *\/\n return MakeCookieHash();\n\n case StickyMode::JVM_ROUTE:\n \/* calculate session_sticky from JSESSIONID cookie suffix *\/\n return lb_jvm_route_get(request.headers, cluster_config);\n }\n\n assert(false);\n gcc_unreachable();\n}\n\n\/*\n * HTTP response handler\n *\n *\/\n\nvoid\nLbRequest::OnHttpResponse(http_status_t status, StringMap &&_headers,\n UnusedIstreamPtr response_body) noexcept\n{\n assert(!response_sent);\n\n failure->UnsetProtocol();\n\n SetForwardedTo();\n\n HttpHeaders headers(std::move(_headers));\n\n if (request.method == HTTP_METHOD_HEAD)\n \/* pass Content-Length, even though there is no response body\n (RFC 2616 14.13) *\/\n headers.MoveToBuffer(\"content-length\");\n\n if (new_cookie != 0) {\n char buffer[64];\n \/* \"Discard\" must be last, to work around an Android bug*\/\n snprintf(buffer, sizeof(buffer),\n \"beng_lb_node=0-%x; HttpOnly; Path=\/; Version=1; Discard\",\n new_cookie);\n\n headers.Write(\"cookie2\", \"$Version=\\\"1\\\"\");\n headers.Write(\"set-cookie\", buffer);\n }\n\n auto &_request = request;\n ResponseSent();\n\n _request.SendResponse(status, std::move(headers),\n std::move(response_body));\n}\n\nvoid\nLbRequest::OnHttpError(std::exception_ptr ep) noexcept\n{\n assert(!response_sent);\n\n if (IsHttpClientServerFailure(ep))\n failure->SetProtocol(GetEventLoop().SteadyNow(),\n std::chrono::seconds(20));\n\n SetForwardedTo();\n\n connection.logger(2, ep);\n\n auto &_connection = connection;\n auto &_request = request;\n const auto &fallback = cluster_config.fallback;\n\n ResponseSent();\n\n if (!send_fallback(_request, fallback))\n _connection.SendError(_request, ep);\n}\n\n\/*\n * stock callback\n *\n *\/\n\nvoid\nLbRequest::OnStockItemReady(StockItem &item) noexcept\n{\n assert(stock_item == nullptr);\n assert(!response_sent);\n\n stock_item = &item;\n\n if (cluster_config.HasZeroConf()) {\n failure = current_member->GetFailureRef();\n\n \/* without the fs_balancer, we have to roll our own failure\n updates *\/\n failure->UnsetConnect();\n } else\n failure = GetFailureManager().Make(fs_stock_item_get_address(*stock_item));\n\n const char *peer_subject = connection.ssl_filter != nullptr\n ? ssl_filter_get_peer_subject(connection.ssl_filter)\n : nullptr;\n const char *peer_issuer_subject = connection.ssl_filter != nullptr\n ? ssl_filter_get_peer_issuer_subject(connection.ssl_filter)\n : nullptr;\n\n auto &headers = request.headers;\n lb_forward_request_headers(pool, headers,\n request.local_host_and_port,\n request.remote_host,\n connection.IsEncrypted(),\n peer_subject, peer_issuer_subject,\n cluster_config.mangle_via);\n\n http_client_request(pool, nullptr,\n fs_stock_item_get(item),\n *this,\n item.GetStockName(),\n request.method, request.uri,\n HttpHeaders(std::move(headers)),\n std::move(body), true,\n *this, cancel_ptr);\n}\n\nvoid\nLbRequest::OnStockItemError(std::exception_ptr ep) noexcept\n{\n assert(stock_item == nullptr);\n assert(!response_sent);\n\n connection.logger(2, \"Connect error: \", ep);\n\n if (cluster_config.HasZeroConf()) {\n \/* without the tcp_balancer, we have to roll our own failure\n updates and retries *\/\n current_member->GetFailureInfo().SetConnect(GetEventLoop().SteadyNow(),\n std::chrono::seconds(20));\n\n if (retries-- > 0) {\n \/* try the next Zeroconf member *\/\n Start();\n return;\n }\n }\n\n body.Clear();\n\n auto &_connection = connection;\n auto &_request = request;\n const auto &fallback = cluster_config.fallback;\n\n ResponseSent();\n\n if (!send_fallback(_request, fallback))\n _connection.SendError(_request, ep);\n}\n\n\/*\n * Lease\n *\n *\/\n\nvoid\nLbRequest::ReleaseLease(bool reuse) noexcept\n{\n assert(stock_item != nullptr);\n\n stock_item->Put(!reuse);\n stock_item = nullptr;\n\n if (response_sent) {\n Destroy();\n }\n}\n\n\/*\n * constructor\n *\n *\/\n\ninline SocketAddress\nLbRequest::MakeBindAddress() const noexcept\n{\n if (cluster_config.transparent_source) {\n SocketAddress bind_address = request.remote_address;\n\n \/* reset the port to 0 to allow the kernel to choose one *\/\n if (bind_address.GetFamily() == AF_INET) {\n auto &address = *NewFromPool<IPv4Address>(pool,\n IPv4Address(bind_address));\n address.SetPort(0);\n return address;\n } else if (bind_address.GetFamily() == AF_INET6) {\n auto &address = *NewFromPool<IPv6Address>(pool,\n IPv6Address(bind_address));\n address.SetPort(0);\n return address;\n }\n\n return bind_address;\n } else\n return SocketAddress::Null();\n}\n\ninline void\nLbRequest::Start() noexcept\n{\n const auto bind_address = MakeBindAddress();\n\n if (cluster_config.HasZeroConf()) {\n auto *member = cluster.Pick(GetEventLoop().SteadyNow(),\n GetStickyHash());\n if (member == nullptr) {\n auto &_request = request;\n Destroy();\n _request.SendMessage(HTTP_STATUS_INTERNAL_SERVER_ERROR,\n \"Zeroconf cluster is empty\");\n return;\n }\n\n current_member = *member;\n\n connection.instance.fs_stock->Get(pool,\n nullptr,\n member->GetLogName(),\n cluster_config.transparent_source,\n bind_address,\n member->GetAddress(),\n LB_HTTP_CONNECT_TIMEOUT,\n nullptr,\n *this, cancel_ptr);\n\n return;\n }\n\n balancer.Get(pool, nullptr,\n cluster_config.transparent_source,\n bind_address,\n GetStickyHash(),\n cluster_config.address_list,\n LB_HTTP_CONNECT_TIMEOUT,\n nullptr,\n *this, cancel_ptr);\n}\n\nvoid\nForwardHttpRequest(LbHttpConnection &connection,\n IncomingHttpRequest &request,\n LbCluster &cluster,\n CancellablePointer &cancel_ptr) noexcept\n{\n const auto request2 =\n NewFromPool<LbRequest>(request.pool,\n connection, cluster,\n *connection.instance.fs_balancer,\n request, cancel_ptr);\n request2->Start();\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"gboost.h\"\n#include \"solver.h\"\n#include \"core\/tpool.h\"\n#include \"core\/logger.h\"\n#include \"gboost_stump.h\"\n#include \"core\/ibstream.h\"\n#include \"core\/obstream.h\"\n\nusing namespace nano;\n\nstatic auto measure(const task_t& task, const fold_t& fold, const tensor4d_t& outputs, const loss_t& loss)\n{\n const auto& tpool = tpool_t::instance();\n\n std::vector<stats_t> errors(tpool.workers());\n std::vector<stats_t> values(tpool.workers());\n\n loopit(task.size(fold), [&] (const size_t i, const size_t t)\n {\n assert(t < tpool.workers());\n const auto input = task.input(fold, i);\n const auto target = task.target(fold, i);\n const auto output = outputs.tensor(i);\n\n errors[t](loss.error(target, output));\n values[t](loss.value(target, output));\n });\n\n for (size_t t = 1; t < tpool.workers(); ++ t)\n {\n errors[0](errors[t]);\n values[0](values[t]);\n }\n\n return std::make_pair(errors[0], values[0]);\n}\n\nstatic void update(const task_t& task, const fold_t& fold, tensor4d_t& outputs, const stump_t& stump)\n{\n loopi(task.size(fold), [&] (const size_t i)\n {\n const auto input = task.input(fold, i);\n const auto oindex = input(stump.m_feature) < stump.m_threshold ? 0 : 1;\n outputs.array(i) += stump.m_outputs.array(oindex);\n });\n}\n\n\/\/ todo: break the computation in smaller functions (move them to gboost.h)\n\nvoid gboost_stump_t::to_json(json_t& json) const\n{\n nano::to_json(json,\n \"rounds\", m_rounds,\n \"patience\", m_patience,\n \"stump\", m_stype, \"stumps\", join(enum_values<stump>()),\n \"solver\", m_solver, \"solvers\", join(get_solvers().ids()),\n \"regularization\", m_rtype, \"regularizations\", join(enum_values<regularization>()));\n}\n\nvoid gboost_stump_t::from_json(const json_t& json)\n{\n nano::from_json(json,\n \"rounds\", m_rounds,\n \"patience\", m_patience,\n \"stump\", m_stype,\n \"solver\", m_solver,\n \"regularization\", m_rtype);\n}\n\ntrainer_result_t gboost_stump_t::train(const task_t& task, const size_t fold, const loss_t& loss)\n{\n \/\/ check if the solver is properly set\n rsolver_t solver;\n critical(solver = get_solvers().get(m_solver),\n strcat(\"search solver (\", m_solver, \").\"));\n\n m_idims = task.idims();\n m_odims = task.odims();\n\n m_stumps.clear();\n\n trainer_result_t result(\"<config>\");\n timer_t timer;\n\n const auto fold_train = fold_t{fold, protocol::train};\n const auto fold_valid = fold_t{fold, protocol::valid};\n const auto fold_test = fold_t{fold, protocol::test};\n\n tensor4d_t outputs_train(cat_dims(task.size(fold_train), m_odims));\n tensor4d_t outputs_valid(cat_dims(task.size(fold_valid), m_odims));\n tensor4d_t outputs_test(cat_dims(task.size(fold_test), m_odims));\n\n outputs_train.zero();\n outputs_valid.zero();\n outputs_test.zero();\n\n stats_t errors_train, errors_valid, errors_test;\n stats_t values_train, values_valid, values_test;\n\n std::tie(errors_train, values_train) = ::measure(task, fold_train, outputs_train, loss);\n std::tie(errors_valid, values_valid) = ::measure(task, fold_valid, outputs_valid, loss);\n std::tie(errors_test, values_test) = ::measure(task, fold_test, outputs_test, loss);\n\n result.update(trainer_state_t{timer.milliseconds(), 0,\n {values_train.avg(), errors_train.avg()},\n {values_valid.avg(), errors_valid.avg()},\n {values_test.avg(), errors_test.avg()}},\n m_patience);\n\n log_info() << result << \".\";\n\n tensor4d_t residuals_train(cat_dims(task.size(fold_train), m_odims));\n tensor3d_t residuals_pos1(m_odims), residuals_pos2(m_odims);\n tensor3d_t residuals_neg1(m_odims), residuals_neg2(m_odims);\n\n stump_t stump;\n tensor4d_t stump_outputs_train(cat_dims(task.size(fold_train), m_odims));\n\n tensor4d_t targets(cat_dims(task.size(fold_train), m_odims));\n for (size_t i = 0, size = task.size(fold_train); i < size; ++ i)\n {\n const auto target = task.target(fold_train, i);\n targets.tensor(i) = target.tensor();\n }\n\n gboost_lsearch_function_t func(targets, outputs_train, stump_outputs_train, loss);\n\n for (auto round = 0; round < m_rounds && !result.is_done(); ++ round)\n {\n for (size_t i = 0, size = task.size(fold_train); i < size; ++ i)\n {\n const auto input = task.input(fold_train, i);\n const auto target = task.target(fold_train, i);\n const auto output = outputs_train.tensor(i);\n\n const auto vgrad = loss.vgrad(target, output);\n residuals_train.vector(i) = -vgrad.vector();\n }\n\n scalar_t best_value = std::numeric_limits<scalar_t>::max();\n\n \/\/ todo: generalize this - e.g. to use features that are products of two input features\n for (auto feature = 0; feature < nano::size(m_idims); ++ feature)\n {\n scalars_t fvalues(task.size(fold_train));\n for (size_t i = 0, size = task.size(fold_train); i < size; ++ i)\n {\n const auto input = task.input(fold_train, i);\n fvalues[i] = input(feature);\n }\n\n auto thresholds = fvalues;\n std::sort(thresholds.begin(), thresholds.end());\n thresholds.erase(std::unique(thresholds.begin(), thresholds.end()), thresholds.end());\n\n for (size_t t = 0; t + 1 < thresholds.size(); ++ t)\n {\n const auto threshold = (thresholds[t + 0] + thresholds[t + 1]) \/ 2;\n\n residuals_pos1.zero(), residuals_pos2.zero();\n residuals_neg1.zero(), residuals_neg2.zero();\n\n int cnt_pos = 0, cnt_neg = 0;\n for (size_t i = 0, size = task.size(fold_train); i < size; ++ i)\n {\n const auto residual = residuals_train.array(i);\n if (fvalues[i] < threshold)\n {\n cnt_neg ++;\n residuals_neg1.array() += residual;\n residuals_neg2.array() += residual * residual;\n }\n else\n {\n cnt_pos ++;\n residuals_pos1.array() += residual;\n residuals_pos2.array() += residual * residual;\n }\n }\n\n const auto value =\n (residuals_pos2.array().sum() - residuals_pos1.array().square().sum() \/ cnt_pos) +\n (residuals_neg2.array().sum() - residuals_neg1.array().square().sum() \/ cnt_neg);\n\n \/\/log_info() << \"feature = \" << feature\n \/\/ << \", threshold = \" << threshold\n \/\/ << \", value = \" << value\n \/\/ << \", count = \" << cnt_neg << \"+\" << cnt_pos << \"=\" << task.size(fold_train);\n\n if (value < best_value)\n {\n best_value = value;\n stump.m_feature = feature;\n stump.m_threshold = threshold;\n stump.m_outputs.resize(cat_dims(2, m_odims));\n stump.m_outputs.vector(0) = residuals_neg1.vector() \/ cnt_neg;\n stump.m_outputs.vector(1) = residuals_pos1.vector() \/ cnt_pos;\n }\n\n \/\/ todo: fit both real and discrete stumps\n }\n }\n\n \/\/ line-search\n for (size_t i = 0, size = task.size(fold_train); i < size; ++ i)\n {\n const auto input = task.input(fold_train, i);\n const auto oindex = input(stump.m_feature) < stump.m_threshold ? 0 : 1;\n stump_outputs_train.tensor(i) = stump.m_outputs.tensor(oindex);\n }\n\n const auto state = solver->minimize(100, epsilon2<scalar_t>(), func, vector_t::Constant(1, 0));\n const auto step = state.x(0);\n\n stump.m_outputs.vector() *= step;\n m_stumps.push_back(stump);\n\n \/\/ update current outputs\n update(task, fold_train, outputs_train, stump);\n update(task, fold_valid, outputs_valid, stump);\n update(task, fold_test, outputs_test, stump);\n\n std::tie(errors_train, values_train) = ::measure(task, fold_train, outputs_train, loss);\n std::tie(errors_valid, values_valid) = ::measure(task, fold_valid, outputs_valid, loss);\n std::tie(errors_test, values_test) = ::measure(task, fold_test, outputs_test, loss);\n\n result.update(trainer_state_t{timer.milliseconds(), round + 1,\n {values_train.avg(), errors_train.avg()},\n {values_valid.avg(), errors_valid.avg()},\n {values_test.avg(), errors_test.avg()}},\n m_patience);\n\n log_info() << result\n << \",feature=\" << stump.m_feature\n << \",solver=(\" << state.m_status\n << \",i=\" << state.m_iterations\n << \",x=\" << state.x(0)\n << \",f=\" << state.f\n << \",g=\" << state.convergence_criteria() << \").\";\n }\n\n \/\/ keep only the stumps up to optimum epoch (on the validation dataset)\n m_stumps.erase(\n m_stumps.begin() + result.optimum().m_epoch,\n m_stumps.end());\n\n return result;\n}\n\ntensor3d_t gboost_stump_t::output(const tensor3d_t& input) const\n{\n assert(input.dims() == m_idims);\n\n tensor3d_t output(m_odims);\n output.zero();\n\n const auto idata = input.array();\n auto odata = output.array();\n\n for (const auto& stump : m_stumps)\n {\n const auto oindex = idata(stump.m_feature) < stump.m_threshold ? 0 : 1;\n odata.array() += stump.m_outputs.array(oindex);\n }\n\n return output;\n}\n\nbool gboost_stump_t::save(obstream_t& stream) const\n{\n if ( !stream.write(m_idims) ||\n !stream.write(m_odims) ||\n !stream.write(m_rounds) ||\n !stream.write(m_stype) ||\n !stream.write(m_rtype) ||\n !stream.write(m_stumps.size()))\n {\n return false;\n }\n\n for (const auto& stump : m_stumps)\n {\n assert(stump.m_feature >= 0 && stump.m_feature < nano::size(m_idims));\n assert(stump.m_outputs.dims() == cat_dims(2, m_odims));\n\n if ( !stream.write(stump.m_feature) ||\n !stream.write(stump.m_threshold) ||\n !stream.write_tensor(stump.m_outputs))\n {\n return false;\n }\n }\n\n return true;\n}\n\nbool gboost_stump_t::load(ibstream_t& stream)\n{\n size_t n_stumps = 0;\n if ( !stream.read(m_idims) ||\n !stream.read(m_odims) ||\n !stream.read(m_rounds) ||\n !stream.read(m_stype) ||\n !stream.read(m_rtype) ||\n !stream.read(n_stumps))\n {\n return false;\n }\n\n m_stumps.resize(n_stumps);\n for (auto& stump : m_stumps)\n {\n if ( !stream.read(stump.m_feature) ||\n !stream.read(stump.m_threshold) ||\n !stream.read_tensor(stump.m_outputs) ||\n stump.m_feature < 0 ||\n stump.m_feature >= nano::size(m_idims) ||\n stump.m_outputs.dims() != cat_dims(2, m_odims))\n {\n return false;\n }\n }\n\n \/\/ todo: more verbose loading (#stumps, feature or coefficient statistics, idims...)\n\n return true;\n}\n\nprobes_t gboost_stump_t::probes() const\n{\n \/\/ todo: add probes here to measure the training and the evaluation time\n probes_t probes;\n return probes;\n}\n<commit_msg>fix display the progress in gboost stump<commit_after>#include \"gboost.h\"\n#include \"solver.h\"\n#include \"core\/tpool.h\"\n#include \"core\/logger.h\"\n#include \"gboost_stump.h\"\n#include \"core\/ibstream.h\"\n#include \"core\/obstream.h\"\n\nusing namespace nano;\n\nstatic auto measure(const task_t& task, const fold_t& fold, const tensor4d_t& outputs, const loss_t& loss)\n{\n const auto& tpool = tpool_t::instance();\n\n std::vector<stats_t> errors(tpool.workers());\n std::vector<stats_t> values(tpool.workers());\n\n loopit(task.size(fold), [&] (const size_t i, const size_t t)\n {\n assert(t < tpool.workers());\n const auto input = task.input(fold, i);\n const auto target = task.target(fold, i);\n const auto output = outputs.tensor(i);\n\n errors[t](loss.error(target, output));\n values[t](loss.value(target, output));\n });\n\n for (size_t t = 1; t < tpool.workers(); ++ t)\n {\n errors[0](errors[t]);\n values[0](values[t]);\n }\n\n return std::make_pair(errors[0], values[0]);\n}\n\nstatic void update(const task_t& task, const fold_t& fold, tensor4d_t& outputs, const stump_t& stump)\n{\n loopi(task.size(fold), [&] (const size_t i)\n {\n const auto input = task.input(fold, i);\n const auto oindex = input(stump.m_feature) < stump.m_threshold ? 0 : 1;\n outputs.array(i) += stump.m_outputs.array(oindex);\n });\n}\n\n\/\/ todo: break the computation in smaller functions (move them to gboost.h)\n\nvoid gboost_stump_t::to_json(json_t& json) const\n{\n nano::to_json(json,\n \"rounds\", m_rounds,\n \"patience\", m_patience,\n \"stump\", m_stype, \"stumps\", join(enum_values<stump>()),\n \"solver\", m_solver, \"solvers\", join(get_solvers().ids()),\n \"regularization\", m_rtype, \"regularizations\", join(enum_values<regularization>()));\n}\n\nvoid gboost_stump_t::from_json(const json_t& json)\n{\n nano::from_json(json,\n \"rounds\", m_rounds,\n \"patience\", m_patience,\n \"stump\", m_stype,\n \"solver\", m_solver,\n \"regularization\", m_rtype);\n}\n\ntrainer_result_t gboost_stump_t::train(const task_t& task, const size_t fold, const loss_t& loss)\n{\n \/\/ check if the solver is properly set\n rsolver_t solver;\n critical(solver = get_solvers().get(m_solver),\n strcat(\"search solver (\", m_solver, \").\"));\n\n m_idims = task.idims();\n m_odims = task.odims();\n\n m_stumps.clear();\n\n trainer_result_t result(\"<config>\");\n timer_t timer;\n\n const auto fold_tr = fold_t{fold, protocol::train};\n const auto fold_vd = fold_t{fold, protocol::valid};\n const auto fold_te = fold_t{fold, protocol::test};\n\n tensor4d_t outputs_tr(cat_dims(task.size(fold_tr), m_odims));\n tensor4d_t outputs_vd(cat_dims(task.size(fold_vd), m_odims));\n tensor4d_t outputs_te(cat_dims(task.size(fold_te), m_odims));\n\n outputs_tr.zero();\n outputs_vd.zero();\n outputs_te.zero();\n\n stats_t errors_tr, errors_vd, errors_te;\n stats_t values_tr, values_vd, values_te;\n\n std::tie(errors_tr, values_tr) = ::measure(task, fold_tr, outputs_tr, loss);\n std::tie(errors_vd, values_vd) = ::measure(task, fold_vd, outputs_vd, loss);\n std::tie(errors_te, values_te) = ::measure(task, fold_te, outputs_te, loss);\n\n const auto measure_tr = trainer_measurement_t{values_tr.avg(), errors_tr.avg()};\n const auto measure_vd = trainer_measurement_t{values_vd.avg(), errors_vd.avg()};\n const auto measure_te = trainer_measurement_t{values_te.avg(), errors_te.avg()};\n\n const auto status = result.update(\n trainer_state_t{timer.milliseconds(), 0, measure_tr, measure_vd, measure_te},\n m_patience);\n\n log_info() << \"[\" << 0 << \"\/\" << m_rounds\n << \"]:tr=\" << measure_tr\n << \",vd=\" << measure_vd << \"|\" << status\n << \",te=\" << measure_te << \".\";\n\n tensor4d_t residuals_train(cat_dims(task.size(fold_tr), m_odims));\n tensor3d_t residuals_pos1(m_odims), residuals_pos2(m_odims);\n tensor3d_t residuals_neg1(m_odims), residuals_neg2(m_odims);\n\n stump_t stump;\n tensor4d_t stump_outputs_tr(cat_dims(task.size(fold_tr), m_odims));\n\n tensor4d_t targets(cat_dims(task.size(fold_tr), m_odims));\n for (size_t i = 0, size = task.size(fold_tr); i < size; ++ i)\n {\n const auto target = task.target(fold_tr, i);\n targets.tensor(i) = target;\n }\n\n gboost_lsearch_function_t func(targets, outputs_tr, stump_outputs_tr, loss);\n\n for (auto round = 0; round < m_rounds && !result.is_done(); ++ round)\n {\n for (size_t i = 0, size = task.size(fold_tr); i < size; ++ i)\n {\n const auto input = task.input(fold_tr, i);\n const auto target = task.target(fold_tr, i);\n const auto output = outputs_tr.tensor(i);\n\n const auto vgrad = loss.vgrad(target, output);\n residuals_train.vector(i) = -vgrad.vector();\n }\n\n scalar_t best_value = std::numeric_limits<scalar_t>::max();\n\n \/\/ todo: generalize this - e.g. to use features that are products of two input features\n for (auto feature = 0; feature < nano::size(m_idims); ++ feature)\n {\n scalars_t fvalues(task.size(fold_tr));\n for (size_t i = 0, size = task.size(fold_tr); i < size; ++ i)\n {\n const auto input = task.input(fold_tr, i);\n fvalues[i] = input(feature);\n }\n\n auto thresholds = fvalues;\n std::sort(thresholds.begin(), thresholds.end());\n thresholds.erase(std::unique(thresholds.begin(), thresholds.end()), thresholds.end());\n\n for (size_t t = 0; t + 1 < thresholds.size(); ++ t)\n {\n const auto threshold = (thresholds[t + 0] + thresholds[t + 1]) \/ 2;\n\n residuals_pos1.zero(), residuals_pos2.zero();\n residuals_neg1.zero(), residuals_neg2.zero();\n\n int cnt_pos = 0, cnt_neg = 0;\n for (size_t i = 0, size = task.size(fold_tr); i < size; ++ i)\n {\n const auto residual = residuals_train.array(i);\n if (fvalues[i] < threshold)\n {\n cnt_neg ++;\n residuals_neg1.array() += residual;\n residuals_neg2.array() += residual * residual;\n }\n else\n {\n cnt_pos ++;\n residuals_pos1.array() += residual;\n residuals_pos2.array() += residual * residual;\n }\n }\n\n const auto value =\n (residuals_pos2.array().sum() - residuals_pos1.array().square().sum() \/ cnt_pos) +\n (residuals_neg2.array().sum() - residuals_neg1.array().square().sum() \/ cnt_neg);\n\n \/\/log_info() << \"feature = \" << feature\n \/\/ << \", threshold = \" << threshold\n \/\/ << \", value = \" << value\n \/\/ << \", count = \" << cnt_neg << \"+\" << cnt_pos << \"=\" << task.size(fold_tr);\n\n if (value < best_value)\n {\n best_value = value;\n stump.m_feature = feature;\n stump.m_threshold = threshold;\n stump.m_outputs.resize(cat_dims(2, m_odims));\n stump.m_outputs.vector(0) = residuals_neg1.vector() \/ cnt_neg;\n stump.m_outputs.vector(1) = residuals_pos1.vector() \/ cnt_pos;\n }\n\n \/\/ todo: fit both real and discrete stumps\n }\n }\n\n \/\/ line-search\n for (size_t i = 0, size = task.size(fold_tr); i < size; ++ i)\n {\n const auto input = task.input(fold_tr, i);\n const auto oindex = input(stump.m_feature) < stump.m_threshold ? 0 : 1;\n stump_outputs_tr.tensor(i) = stump.m_outputs.tensor(oindex);\n }\n\n const auto state = solver->minimize(100, epsilon2<scalar_t>(), func, vector_t::Constant(1, 0));\n const auto step = state.x(0);\n\n \/\/ todo: break if the line-search fails (e.g. if state.m_iterations == 0\n\n stump.m_outputs.vector() *= step;\n m_stumps.push_back(stump);\n\n \/\/ update current outputs\n update(task, fold_tr, outputs_tr, stump);\n update(task, fold_vd, outputs_vd, stump);\n update(task, fold_te, outputs_te, stump);\n\n std::tie(errors_tr, values_tr) = ::measure(task, fold_tr, outputs_tr, loss);\n std::tie(errors_vd, values_vd) = ::measure(task, fold_vd, outputs_vd, loss);\n std::tie(errors_te, values_te) = ::measure(task, fold_te, outputs_te, loss);\n\n const auto measure_tr = trainer_measurement_t{values_tr.avg(), errors_tr.avg()};\n const auto measure_vd = trainer_measurement_t{values_vd.avg(), errors_vd.avg()};\n const auto measure_te = trainer_measurement_t{values_te.avg(), errors_te.avg()};\n\n const auto status = result.update(\n trainer_state_t{timer.milliseconds(), round + 1, measure_tr, measure_vd, measure_te},\n m_patience);\n\n log_info() << \"[\" << (round + 1) << \"\/\" << m_rounds\n << \"]:tr=\" << measure_tr\n << \",vd=\" << measure_vd << \"|\" << status\n << \",te=\" << measure_te\n << \",feature=\" << stump.m_feature\n << \",solver=(\" << state.m_status\n << \",i=\" << state.m_iterations\n << \",x=\" << state.x(0)\n << \",f=\" << state.f\n << \",g=\" << state.convergence_criteria() << \").\";\n }\n\n \/\/ keep only the stumps up to optimum epoch (on the validation dataset)\n m_stumps.erase(\n m_stumps.begin() + result.optimum().m_epoch,\n m_stumps.end());\n\n return result;\n}\n\ntensor3d_t gboost_stump_t::output(const tensor3d_t& input) const\n{\n assert(input.dims() == m_idims);\n\n tensor3d_t output(m_odims);\n output.zero();\n\n const auto idata = input.array();\n auto odata = output.array();\n\n for (const auto& stump : m_stumps)\n {\n const auto oindex = idata(stump.m_feature) < stump.m_threshold ? 0 : 1;\n odata.array() += stump.m_outputs.array(oindex);\n }\n\n return output;\n}\n\nbool gboost_stump_t::save(obstream_t& stream) const\n{\n if ( !stream.write(m_idims) ||\n !stream.write(m_odims) ||\n !stream.write(m_rounds) ||\n !stream.write(m_stype) ||\n !stream.write(m_rtype) ||\n !stream.write(m_stumps.size()))\n {\n return false;\n }\n\n for (const auto& stump : m_stumps)\n {\n assert(stump.m_feature >= 0 && stump.m_feature < nano::size(m_idims));\n assert(stump.m_outputs.dims() == cat_dims(2, m_odims));\n\n if ( !stream.write(stump.m_feature) ||\n !stream.write(stump.m_threshold) ||\n !stream.write_tensor(stump.m_outputs))\n {\n return false;\n }\n }\n\n return true;\n}\n\nbool gboost_stump_t::load(ibstream_t& stream)\n{\n size_t n_stumps = 0;\n if ( !stream.read(m_idims) ||\n !stream.read(m_odims) ||\n !stream.read(m_rounds) ||\n !stream.read(m_stype) ||\n !stream.read(m_rtype) ||\n !stream.read(n_stumps))\n {\n return false;\n }\n\n m_stumps.resize(n_stumps);\n for (auto& stump : m_stumps)\n {\n if ( !stream.read(stump.m_feature) ||\n !stream.read(stump.m_threshold) ||\n !stream.read_tensor(stump.m_outputs) ||\n stump.m_feature < 0 ||\n stump.m_feature >= nano::size(m_idims) ||\n stump.m_outputs.dims() != cat_dims(2, m_odims))\n {\n return false;\n }\n }\n\n \/\/ todo: more verbose loading (#stumps, feature or coefficient statistics, idims...)\n\n return true;\n}\n\nprobes_t gboost_stump_t::probes() const\n{\n \/\/ todo: add probes here to measure the training and the evaluation time\n probes_t probes;\n return probes;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ This file is part of the Marble Virtual Globe.\n\/\/\n\/\/ This program is free software licensed under the GNU LGPL. You can\n\/\/ find a copy of this license in LICENSE.txt in the top directory of\n\/\/ the source code.\n\/\/\n\/\/ Copyright 2008 Torsten Rahn <rahn@kde.org>\n\/\/\n\n\/\/ Self\n#include \"AbstractFloatItem.h\"\n\n\/\/ Qt\n#include <QtGui\/QMenu>\n#include <QtGui\/QAction>\n#include <QtGui\/QDialog>\n\n\/\/ Marble\n#include \"DialogConfigurationInterface.h\"\n#include \"MarbleDebug.h\"\n\nnamespace Marble\n{\n\nclass AbstractFloatItemPrivate\n{\n public:\n AbstractFloatItemPrivate() : m_contextMenu( 0 )\n {\n }\n\n ~AbstractFloatItemPrivate()\n {\n delete m_contextMenu;\n }\n\n\n static QPen s_pen;\n static QFont s_font;\n\n QMenu* m_contextMenu;\n};\n\nQPen AbstractFloatItemPrivate::s_pen = QPen( Qt::black );\n#ifdef Q_OS_MACX\n QFont AbstractFloatItemPrivate::s_font = QFont( \"Sans Serif\", 10 );\n#else\n QFont AbstractFloatItemPrivate::s_font = QFont( \"Sans Serif\", 8 );\n#endif\n\nAbstractFloatItem::AbstractFloatItem( const MarbleModel *marbleModel, const QPointF &point, const QSizeF &size )\n : RenderPlugin( marbleModel ),\n FrameGraphicsItem(),\n d( new AbstractFloatItemPrivate() )\n{\n setCacheMode( MarbleGraphicsItem::ItemCoordinateCache );\n setFrame( RectFrame );\n setPadding( 4.0 );\n setContentSize( size );\n setPosition( point );\n}\n\nAbstractFloatItem::~AbstractFloatItem()\n{\n delete d;\n}\n\nQPen AbstractFloatItem::pen() const\n{\n return d->s_pen;\n}\n\nvoid AbstractFloatItem::setPen( const QPen &pen )\n{\n d->s_pen = pen;\n update();\n}\n\nQFont AbstractFloatItem::font() const\n{\n return d->s_font;\n}\n\nvoid AbstractFloatItem::setFont( const QFont &font )\n{\n d->s_font = font;\n update();\n}\n\nQString AbstractFloatItem::renderPolicy() const\n{\n return \"ALWAYS\";\n}\n\nQStringList AbstractFloatItem::renderPosition() const\n{\n return QStringList( \"FLOAT_ITEM\" );\n}\n\nvoid AbstractFloatItem::setVisible( bool visible )\n{\n \/\/ Reimplemented since AbstractFloatItem does multiple inheritance \n \/\/ and the (set)Visible() methods are available in both base classes!\n RenderPlugin::setVisible( visible );\n}\n\nbool AbstractFloatItem::visible() const\n{\n \/\/ Reimplemented since AbstractFloatItem does multiple inheritance \n \/\/ and the (set)Visible() methods are available in both base classes!\n return RenderPlugin::visible();\n}\n\nvoid AbstractFloatItem::setPositionLocked( bool lock )\n{\n ScreenGraphicsItem::GraphicsItemFlags flags = this->flags();\n\n if ( lock ) {\n flags &= ~ScreenGraphicsItem::ItemIsMovable;\n }\n else {\n flags |= ScreenGraphicsItem::ItemIsMovable;\n }\n\n setFlags( flags );\n}\n\nbool AbstractFloatItem::positionLocked()\n{\n return ( flags() & ScreenGraphicsItem::ItemIsMovable ) ? false : true;\n}\n\nbool AbstractFloatItem::eventFilter( QObject *object, QEvent *e )\n{\n if ( !enabled() || !visible() ) {\n return false;\n }\n\n if( e->type() == QEvent::ContextMenu )\n {\n QWidget *widget = dynamic_cast<QWidget *>( object );\n QContextMenuEvent *menuEvent = dynamic_cast<QContextMenuEvent *> ( e );\n if( widget != NULL && menuEvent != NULL && contains( menuEvent->pos() ) )\n {\n contextMenuEvent( widget, menuEvent );\n return true;\n }\n return false;\n }\n else if( e->type() == QEvent::ToolTip )\n {\n QHelpEvent *helpEvent = dynamic_cast<QHelpEvent *>( e );\n if( helpEvent != NULL && contains( helpEvent->pos() ) )\n {\n toolTipEvent( helpEvent );\n return true;\n }\n return false;\n }\n else\n return ScreenGraphicsItem::eventFilter( object, e );\n}\n\nvoid AbstractFloatItem::contextMenuEvent ( QWidget *w, QContextMenuEvent *e )\n{\n contextMenu()->exec( w->mapToGlobal( e->pos() ) );\n}\n\nvoid AbstractFloatItem::toolTipEvent ( QHelpEvent *e )\n{\n Q_UNUSED( e );\n}\n\nbool AbstractFloatItem::render( GeoPainter *painter, ViewportParams *viewport,\n const QString& renderPos, GeoSceneLayer * layer )\n{\n if ( !enabled() || !visible() ) {\n return true;\n }\n\n if ( renderPos == \"FLOAT_ITEM\" ) {\n paintEvent( painter, viewport, renderPos, layer );\n return true;\n }\n\n return false;\n}\n\nvoid AbstractFloatItem::show()\n{\n setVisible( true );\n}\n\nvoid AbstractFloatItem::hide()\n{\n setVisible( false );\n}\n\nQMenu* AbstractFloatItem::contextMenu()\n{\n if ( !d->m_contextMenu )\n {\n d->m_contextMenu = new QMenu;\n\n QAction *lockAction = d->m_contextMenu->addAction( tr( \"&Lock\" ) );\n lockAction->setCheckable( true );\n lockAction->setChecked( positionLocked() );\n connect( lockAction, SIGNAL( triggered( bool ) ), this, SLOT( setPositionLocked( bool ) ) );\n QAction *hideAction = d->m_contextMenu->addAction( tr( \"&Hide\" ) );\n connect( hideAction, SIGNAL( triggered() ), this, SLOT( hide() ) );\n DialogConfigurationInterface *configInterface = qobject_cast<DialogConfigurationInterface *>( this );\n QDialog *dialog = configInterface ? configInterface->configDialog() : 0;\n if( dialog )\n {\n d->m_contextMenu->addSeparator();\n QAction *configAction = d->m_contextMenu->addAction( tr( \"&Configure...\" ) );\n connect( configAction, SIGNAL( triggered() ), dialog, SLOT( exec() ) );\n }\n }\n\n Q_ASSERT( d->m_contextMenu );\n return d->m_contextMenu;\n}\n\n}\n\n#include \"AbstractFloatItem.moc\"\n<commit_msg>no need to check for renderPosition<commit_after>\/\/\n\/\/ This file is part of the Marble Virtual Globe.\n\/\/\n\/\/ This program is free software licensed under the GNU LGPL. You can\n\/\/ find a copy of this license in LICENSE.txt in the top directory of\n\/\/ the source code.\n\/\/\n\/\/ Copyright 2008 Torsten Rahn <rahn@kde.org>\n\/\/\n\n\/\/ Self\n#include \"AbstractFloatItem.h\"\n\n\/\/ Qt\n#include <QtGui\/QMenu>\n#include <QtGui\/QAction>\n#include <QtGui\/QDialog>\n\n\/\/ Marble\n#include \"DialogConfigurationInterface.h\"\n#include \"MarbleDebug.h\"\n\nnamespace Marble\n{\n\nclass AbstractFloatItemPrivate\n{\n public:\n AbstractFloatItemPrivate() : m_contextMenu( 0 )\n {\n }\n\n ~AbstractFloatItemPrivate()\n {\n delete m_contextMenu;\n }\n\n\n static QPen s_pen;\n static QFont s_font;\n\n QMenu* m_contextMenu;\n};\n\nQPen AbstractFloatItemPrivate::s_pen = QPen( Qt::black );\n#ifdef Q_OS_MACX\n QFont AbstractFloatItemPrivate::s_font = QFont( \"Sans Serif\", 10 );\n#else\n QFont AbstractFloatItemPrivate::s_font = QFont( \"Sans Serif\", 8 );\n#endif\n\nAbstractFloatItem::AbstractFloatItem( const MarbleModel *marbleModel, const QPointF &point, const QSizeF &size )\n : RenderPlugin( marbleModel ),\n FrameGraphicsItem(),\n d( new AbstractFloatItemPrivate() )\n{\n setCacheMode( MarbleGraphicsItem::ItemCoordinateCache );\n setFrame( RectFrame );\n setPadding( 4.0 );\n setContentSize( size );\n setPosition( point );\n}\n\nAbstractFloatItem::~AbstractFloatItem()\n{\n delete d;\n}\n\nQPen AbstractFloatItem::pen() const\n{\n return d->s_pen;\n}\n\nvoid AbstractFloatItem::setPen( const QPen &pen )\n{\n d->s_pen = pen;\n update();\n}\n\nQFont AbstractFloatItem::font() const\n{\n return d->s_font;\n}\n\nvoid AbstractFloatItem::setFont( const QFont &font )\n{\n d->s_font = font;\n update();\n}\n\nQString AbstractFloatItem::renderPolicy() const\n{\n return \"ALWAYS\";\n}\n\nQStringList AbstractFloatItem::renderPosition() const\n{\n return QStringList( \"FLOAT_ITEM\" );\n}\n\nvoid AbstractFloatItem::setVisible( bool visible )\n{\n \/\/ Reimplemented since AbstractFloatItem does multiple inheritance \n \/\/ and the (set)Visible() methods are available in both base classes!\n RenderPlugin::setVisible( visible );\n}\n\nbool AbstractFloatItem::visible() const\n{\n \/\/ Reimplemented since AbstractFloatItem does multiple inheritance \n \/\/ and the (set)Visible() methods are available in both base classes!\n return RenderPlugin::visible();\n}\n\nvoid AbstractFloatItem::setPositionLocked( bool lock )\n{\n ScreenGraphicsItem::GraphicsItemFlags flags = this->flags();\n\n if ( lock ) {\n flags &= ~ScreenGraphicsItem::ItemIsMovable;\n }\n else {\n flags |= ScreenGraphicsItem::ItemIsMovable;\n }\n\n setFlags( flags );\n}\n\nbool AbstractFloatItem::positionLocked()\n{\n return ( flags() & ScreenGraphicsItem::ItemIsMovable ) ? false : true;\n}\n\nbool AbstractFloatItem::eventFilter( QObject *object, QEvent *e )\n{\n if ( !enabled() || !visible() ) {\n return false;\n }\n\n if( e->type() == QEvent::ContextMenu )\n {\n QWidget *widget = dynamic_cast<QWidget *>( object );\n QContextMenuEvent *menuEvent = dynamic_cast<QContextMenuEvent *> ( e );\n if( widget != NULL && menuEvent != NULL && contains( menuEvent->pos() ) )\n {\n contextMenuEvent( widget, menuEvent );\n return true;\n }\n return false;\n }\n else if( e->type() == QEvent::ToolTip )\n {\n QHelpEvent *helpEvent = dynamic_cast<QHelpEvent *>( e );\n if( helpEvent != NULL && contains( helpEvent->pos() ) )\n {\n toolTipEvent( helpEvent );\n return true;\n }\n return false;\n }\n else\n return ScreenGraphicsItem::eventFilter( object, e );\n}\n\nvoid AbstractFloatItem::contextMenuEvent ( QWidget *w, QContextMenuEvent *e )\n{\n contextMenu()->exec( w->mapToGlobal( e->pos() ) );\n}\n\nvoid AbstractFloatItem::toolTipEvent ( QHelpEvent *e )\n{\n Q_UNUSED( e );\n}\n\nbool AbstractFloatItem::render( GeoPainter *painter, ViewportParams *viewport,\n const QString& renderPos, GeoSceneLayer * layer )\n{\n if ( !enabled() || !visible() ) {\n return true;\n }\n\n paintEvent( painter, viewport, renderPos, layer );\n return true;\n}\n\nvoid AbstractFloatItem::show()\n{\n setVisible( true );\n}\n\nvoid AbstractFloatItem::hide()\n{\n setVisible( false );\n}\n\nQMenu* AbstractFloatItem::contextMenu()\n{\n if ( !d->m_contextMenu )\n {\n d->m_contextMenu = new QMenu;\n\n QAction *lockAction = d->m_contextMenu->addAction( tr( \"&Lock\" ) );\n lockAction->setCheckable( true );\n lockAction->setChecked( positionLocked() );\n connect( lockAction, SIGNAL( triggered( bool ) ), this, SLOT( setPositionLocked( bool ) ) );\n QAction *hideAction = d->m_contextMenu->addAction( tr( \"&Hide\" ) );\n connect( hideAction, SIGNAL( triggered() ), this, SLOT( hide() ) );\n DialogConfigurationInterface *configInterface = qobject_cast<DialogConfigurationInterface *>( this );\n QDialog *dialog = configInterface ? configInterface->configDialog() : 0;\n if( dialog )\n {\n d->m_contextMenu->addSeparator();\n QAction *configAction = d->m_contextMenu->addAction( tr( \"&Configure...\" ) );\n connect( configAction, SIGNAL( triggered() ), dialog, SLOT( exec() ) );\n }\n }\n\n Q_ASSERT( d->m_contextMenu );\n return d->m_contextMenu;\n}\n\n}\n\n#include \"AbstractFloatItem.moc\"\n<|endoftext|>"} {"text":"<commit_before>\/*\n Copyright 2008 Henry de Valence <hdevalence@gmail.com>\n \n This library is free software; you can redistribute it and\/or\n modify it under the terms of the GNU Lesser General Public\n License as published by the Free Software Foundation; either\n version 2.1 of the License, or (at your option) version 3, or any\n later version accepted by the membership of KDE e.V. (or its\n successor approved by the membership of KDE e.V.), which shall\n act as a proxy defined in Section 6 of version 3 of the license.\n\n This library is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n Lesser General Public License for more details.\n\n You should have received a copy of the GNU Lesser General Public \n License along with this library. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n*\/\n\n#include \"OnfRunner.h\"\n\n#include \"MarbleAbstractRunner.h\"\n#include \"MarbleRunnerResult.h\"\n#include \"GeoOnfParser.h\"\n#include \"GeoDataDocument.h\"\n#include \"PlaceMarkContainer.h\"\n\n#include <QtCore\/QString>\n#include <QtCore\/QBuffer>\n#include <QtCore\/QtDebug>\n\n#include <QtNetwork\/QHttp>\n\nnamespace Marble\n{\n\n\/*\nTODO: grade results individually instead of giving them all a score of 100\n*\/\n\nOnfRunner::OnfRunner( QObject *parent ) : MarbleAbstractRunner( parent )\n{\n qRegisterMetaType<MarbleRunnerResult>();\n m_http = new QHttp(\"gazetteer.openstreetmap.org\");\n m_buffer = 0;\n \n connect( m_http, SIGNAL( requestFinished( int, bool ) ),\n this, SLOT( slotRequestFinished( int, bool ) ) );\n}\n\nOnfRunner::~OnfRunner()\n{\n delete m_http;\n delete m_buffer;\n}\n\nQString OnfRunner::name() const\n{\n return tr(\"OpenStreetMap Name Finder Runner\");\n}\n\nvoid OnfRunner::fail()\n{\n \/\/The manager needs to know when parsing starts and stops\n \/\/in order to have a balanced count of active runners. So\n \/\/we emit runnerFinished() to balance the previous failed runnerStarted()\n MarbleRunnerResult fail;\n fail.setRunnerName( name() );\n emit runnerFinished( fail );\n return;\n}\n\nvoid OnfRunner::parse(const QString &input)\n{\n emit runnerStarted( name() );\n if( input.isEmpty() ) {\n return;\n }\n \/\/no point to keep downloading if we're doing a new one\n \/* \/\/causes crash\n if( m_http->currentId() != 0 ) {\n m_http->abort();\n \/\/aborted parse request fails; this one keeps going.\n fail();\n }\n *\/\n \/\/make a new buffer\n if( m_buffer ) {\n delete m_buffer;\n }\n m_buffer = new QBuffer;\n qDebug() << \"ONF search: GET \/namefinder\/search.xml?find=\" << input;\n m_http->get( \"\/namefinder\/search.xml?find=\" + input, m_buffer );\n}\n\nvoid OnfRunner::slotRequestFinished( int id, bool error )\n{\n if( error ) {\n qDebug() << \"ONF request\" << id << \"failed:\" << m_http->error()\n << m_http->errorString();\n fail();\n return;\n }\n \n qDebug() << \"ONF search result buffer size:\" << m_buffer->size();\n qDebug() << m_buffer->data();\n \n QByteArray array = m_buffer->data();\n QBuffer data( &array );\n data.open( QIODevice::ReadOnly );\n \n GeoOnfParser parser;\n if( !parser.read( &data ) ) {\n qWarning() << \"Could not parse ONF buffer!!\";\n fail();\n return;\n }\n \n GeoDataDocument *results = static_cast<GeoDataDocument*>( parser.releaseDocument() );\n Q_ASSERT( results );\n \n PlaceMarkContainer container( results->placemarks(), \"ONF Search Results\" );\n MarbleRunnerResult result;\n \n if( container.isEmpty() ) {\n result = MarbleRunnerResult( container, MarbleRunnerResult::NoMatch, name() );\n } else {\n result = MarbleRunnerResult( container, MarbleRunnerResult::PerfectMatch, name() );\n }\n \n emit runnerFinished( result );\n return;\n}\n\n} \/\/ namespace Marble\n\n#include \"OnfRunner.moc\"<commit_msg>add whitespace at the eof<commit_after>\/*\n Copyright 2008 Henry de Valence <hdevalence@gmail.com>\n \n This library is free software; you can redistribute it and\/or\n modify it under the terms of the GNU Lesser General Public\n License as published by the Free Software Foundation; either\n version 2.1 of the License, or (at your option) version 3, or any\n later version accepted by the membership of KDE e.V. (or its\n successor approved by the membership of KDE e.V.), which shall\n act as a proxy defined in Section 6 of version 3 of the license.\n\n This library is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n Lesser General Public License for more details.\n\n You should have received a copy of the GNU Lesser General Public \n License along with this library. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n*\/\n\n#include \"OnfRunner.h\"\n\n#include \"MarbleAbstractRunner.h\"\n#include \"MarbleRunnerResult.h\"\n#include \"GeoOnfParser.h\"\n#include \"GeoDataDocument.h\"\n#include \"PlaceMarkContainer.h\"\n\n#include <QtCore\/QString>\n#include <QtCore\/QBuffer>\n#include <QtCore\/QtDebug>\n\n#include <QtNetwork\/QHttp>\n\nnamespace Marble\n{\n\n\/*\nTODO: grade results individually instead of giving them all a score of 100\n*\/\n\nOnfRunner::OnfRunner( QObject *parent ) : MarbleAbstractRunner( parent )\n{\n qRegisterMetaType<MarbleRunnerResult>();\n m_http = new QHttp(\"gazetteer.openstreetmap.org\");\n m_buffer = 0;\n \n connect( m_http, SIGNAL( requestFinished( int, bool ) ),\n this, SLOT( slotRequestFinished( int, bool ) ) );\n}\n\nOnfRunner::~OnfRunner()\n{\n delete m_http;\n delete m_buffer;\n}\n\nQString OnfRunner::name() const\n{\n return tr(\"OpenStreetMap Name Finder Runner\");\n}\n\nvoid OnfRunner::fail()\n{\n \/\/The manager needs to know when parsing starts and stops\n \/\/in order to have a balanced count of active runners. So\n \/\/we emit runnerFinished() to balance the previous failed runnerStarted()\n MarbleRunnerResult fail;\n fail.setRunnerName( name() );\n emit runnerFinished( fail );\n return;\n}\n\nvoid OnfRunner::parse(const QString &input)\n{\n emit runnerStarted( name() );\n if( input.isEmpty() ) {\n return;\n }\n \/\/no point to keep downloading if we're doing a new one\n \/* \/\/causes crash\n if( m_http->currentId() != 0 ) {\n m_http->abort();\n \/\/aborted parse request fails; this one keeps going.\n fail();\n }\n *\/\n \/\/make a new buffer\n if( m_buffer ) {\n delete m_buffer;\n }\n m_buffer = new QBuffer;\n qDebug() << \"ONF search: GET \/namefinder\/search.xml?find=\" << input;\n m_http->get( \"\/namefinder\/search.xml?find=\" + input, m_buffer );\n}\n\nvoid OnfRunner::slotRequestFinished( int id, bool error )\n{\n if( error ) {\n qDebug() << \"ONF request\" << id << \"failed:\" << m_http->error()\n << m_http->errorString();\n fail();\n return;\n }\n \n qDebug() << \"ONF search result buffer size:\" << m_buffer->size();\n qDebug() << m_buffer->data();\n \n QByteArray array = m_buffer->data();\n QBuffer data( &array );\n data.open( QIODevice::ReadOnly );\n \n GeoOnfParser parser;\n if( !parser.read( &data ) ) {\n qWarning() << \"Could not parse ONF buffer!!\";\n fail();\n return;\n }\n \n GeoDataDocument *results = static_cast<GeoDataDocument*>( parser.releaseDocument() );\n Q_ASSERT( results );\n \n PlaceMarkContainer container( results->placemarks(), \"ONF Search Results\" );\n MarbleRunnerResult result;\n \n if( container.isEmpty() ) {\n result = MarbleRunnerResult( container, MarbleRunnerResult::NoMatch, name() );\n } else {\n result = MarbleRunnerResult( container, MarbleRunnerResult::PerfectMatch, name() );\n }\n \n emit runnerFinished( result );\n return;\n}\n\n} \/\/ namespace Marble\n\n#include \"OnfRunner.moc\"\n<|endoftext|>"} {"text":"<commit_before>#include \"object\/object.h\"\n#include \"math\/intersect.h\"\n\nnamespace aten\n{\n\tbool face::hit(\n\t\tconst ray& r,\n\t\treal t_min, real t_max,\n\t\thitrecord& rec) const\n\t{\n\t\tbool isHit = false;\n\n#if 0\n\t\tconst auto v0 = vtx[idx[0]];\n\t\tconst auto v1 = vtx[idx[1]];\n\t\tconst auto v2 = vtx[idx[2]];\n#else\n\t\tconst auto& v0 = vtx[0];\n\t\tconst auto& v1 = vtx[1];\n\t\tconst auto& v2 = vtx[2];\n#endif\n\n\t\tconst auto res = intersertTriangle(r, v0->pos, v1->pos, v2->pos);\n\n\t\tif (res.isIntersect) {\n\t\t\tif (res.t < rec.t) {\n\t\t\t\trec.t = res.t;\n\n\t\t\t\tauto p = r.org + rec.t * r.dir;\n\n\t\t\t\t\/\/ NOTE\n\t\t\t\t\/\/ http:\/\/d.hatena.ne.jp\/Zellij\/20131207\/p1\n\n\t\t\t\t\/\/ dSWn(barycentric coordinates).\n\t\t\t\t\/\/ v0.\n\t\t\t\t\/\/ p = (1 - a - b)*v0 + a*v1 + b*v2\n\t\t\t\trec.p = (1 - res.a - res.b) * v0->pos + res.a * v1->pos + res.b * v2->pos;\n\t\t\t\trec.normal = (1 - res.a - res.b) * v0->nml + res.a * v1->nml + res.b * v2->nml;\n\t\t\t\tauto uv = (1 - res.a - res.b) * v0->uv + res.a * v1->uv + res.b * v2->uv;\n\n\t\t\t\trec.u = uv.x;\n\t\t\t\trec.v = uv.y;\n\n\t\t\t\t\/\/ tangent coordinate.\n\t\t\t\trec.du = normalize(getOrthoVector(rec.normal));\n\t\t\t\trec.dv = normalize(cross(rec.normal, rec.du));\n\n\t\t\t\trec.area = area;\n\n\t\t\t\t\/\/rec.obj = parent;\n\t\t\t\trec.obj = (hitable*)this;\n\n\t\t\t\tif (parent) {\n\t\t\t\t\trec.mtrl = parent->mtrl;\n\t\t\t\t}\n\n\t\t\t\tisHit = true;\n\t\t\t}\n\t\t}\n\n\t\treturn isHit;\n\t}\n\n\tvoid face::build(vertex* v0, vertex* v1, vertex* v2)\n\t{\n\t\tvec3 vmax(\n\t\t\tstd::max(v0->pos.x, std::max(v1->pos.x, v2->pos.x)),\n\t\t\tstd::max(v0->pos.y, std::max(v1->pos.y, v2->pos.y)),\n\t\t\tstd::max(v0->pos.z, std::max(v1->pos.z, v2->pos.z)));\n\n\t\tvec3 vmin(\n\t\t\tstd::min(v0->pos.x, std::min(v1->pos.x, v2->pos.x)),\n\t\t\tstd::min(v0->pos.y, std::min(v1->pos.y, v2->pos.y)),\n\t\t\tstd::min(v0->pos.z, std::min(v1->pos.z, v2->pos.z)));\n\n\t\tbbox.init(vmin, vmax);\n\n\t\tvtx[0] = v0;\n\t\tvtx[1] = v1;\n\t\tvtx[2] = v2;\n\n\t\t\/\/ Op`̖ʐ = Qӂ̊Oς̒ \/ 2;\n\t\tauto e0 = v1->pos - v0->pos;\n\t\tauto e1 = v2->pos - v0->pos;\n\t\tarea = 0.5 * cross(e0, e1).length();\n\t}\n\n\tvec3 face::getRandomPosOn(sampler* sampler) const\n\t{\n\t\t\/\/ 0 <= a + b <= 1\n\t\treal a = sampler->nextSample();\n\t\treal b = sampler->nextSample();\n\n\t\treal d = a + b;\n\n\t\tif (d > 1) {\n\t\t\ta \/= d;\n\t\t\tb \/= d;\n\t\t}\n\n\t\tconst auto& v0 = vtx[0];\n\t\tconst auto& v1 = vtx[1];\n\t\tconst auto& v2 = vtx[2];\n\n\t\t\/\/ dSWn(barycentric coordinates).\n\t\t\/\/ v0.\n\t\t\/\/ p = (1 - a - b)*v0 + a*v1 + b*v2\n\t\tvec3 p = (1 - a - b) * v0->pos + a * v1->pos + b * v2->pos;\n\n\t\treturn std::move(p);\n\t}\n\n\tvoid shape::build()\n\t{\n\t\tm_node.build(\n\t\t\t(bvhnode**)&faces[0],\n\t\t\t(uint32_t)faces.size());\n\n\t\tm_aabb = m_node.getBoundingbox();\n\n\t\tarea = 0;\n\t\tfor (const auto f : faces) {\n\t\t\tarea += f->area;\n\t\t}\n\t}\n\n\tbool shape::hit(\n\t\tconst ray& r,\n\t\treal t_min, real t_max,\n\t\thitrecord& rec) const\n\t{\n\t\tauto isHit = m_node.hit(r, t_min, t_max, rec);\n\n\t\tif (isHit) {\n\t\t\trec.mtrl = mtrl;\n\t\t}\n\n\t\treturn isHit;\n\t}\n\n\tvoid object::build()\n\t{\n\t\tm_node.build((bvhnode**)&shapes[0], (uint32_t)shapes.size());\n\n\t\tm_area = 0;\n\t\tm_triangles = 0;\n\n\t\tfor (const auto s : shapes) {\n\t\t\tm_area += s->area;\n\t\t\tm_triangles += s->faces.size();\n\t\t}\n\t}\n\n\tbool object::hit(\n\t\tconst ray& r,\n\t\tconst mat4& mtxL2W,\n\t\treal t_min, real t_max,\n\t\thitrecord& rec)\n\t{\n\t\tbool isHit = m_node.hit(r, t_min, t_max, rec);\n\t\tif (isHit) {\n\t\t\tface* f = (face*)rec.obj;\n\n\t\t\tauto v0 = mtxL2W.apply(f->vtx[0]->pos);\n\t\t\tauto v1 = mtxL2W.apply(f->vtx[1]->pos);\n\t\t\tauto v2 = mtxL2W.apply(f->vtx[2]->pos);\n\n\t\t\t\/\/ Op`̖ʐ = Qӂ̊Oς̒ \/ 2;\n\t\t\tauto e0 = v1 - v0;\n\t\t\tauto e1 = v2 - v0;\n\t\t\tauto area = 0.5 * cross(e0, e1).length();\n\n\t\t\trec.area = area;\n\n\t\t\t\/\/ TODO\n\t\t\t\/\/ OPDFƂĈ̂ŁAmvZĂ܂.\n\t\t\t\/\/ ϐςׂ...\n\t\t\trec.area *= m_triangles;\n\n\t\t\t\/\/ ŏIIɂ́Aςshapen.\n\t\t\trec.obj = f->parent;\n\t\t}\n\t\treturn isHit;\n\t}\n}\n<commit_msg>Use square of distance scale to compute area.<commit_after>#include \"object\/object.h\"\n#include \"math\/intersect.h\"\n\nnamespace aten\n{\n\tbool face::hit(\n\t\tconst ray& r,\n\t\treal t_min, real t_max,\n\t\thitrecord& rec) const\n\t{\n\t\tbool isHit = false;\n\n#if 0\n\t\tconst auto v0 = vtx[idx[0]];\n\t\tconst auto v1 = vtx[idx[1]];\n\t\tconst auto v2 = vtx[idx[2]];\n#else\n\t\tconst auto& v0 = vtx[0];\n\t\tconst auto& v1 = vtx[1];\n\t\tconst auto& v2 = vtx[2];\n#endif\n\n\t\tconst auto res = intersertTriangle(r, v0->pos, v1->pos, v2->pos);\n\n\t\tif (res.isIntersect) {\n\t\t\tif (res.t < rec.t) {\n\t\t\t\trec.t = res.t;\n\n\t\t\t\tauto p = r.org + rec.t * r.dir;\n\n\t\t\t\t\/\/ NOTE\n\t\t\t\t\/\/ http:\/\/d.hatena.ne.jp\/Zellij\/20131207\/p1\n\n\t\t\t\t\/\/ dSWn(barycentric coordinates).\n\t\t\t\t\/\/ v0.\n\t\t\t\t\/\/ p = (1 - a - b)*v0 + a*v1 + b*v2\n\t\t\t\trec.p = (1 - res.a - res.b) * v0->pos + res.a * v1->pos + res.b * v2->pos;\n\t\t\t\trec.normal = (1 - res.a - res.b) * v0->nml + res.a * v1->nml + res.b * v2->nml;\n\t\t\t\tauto uv = (1 - res.a - res.b) * v0->uv + res.a * v1->uv + res.b * v2->uv;\n\n\t\t\t\trec.u = uv.x;\n\t\t\t\trec.v = uv.y;\n\n\t\t\t\t\/\/ tangent coordinate.\n\t\t\t\trec.du = normalize(getOrthoVector(rec.normal));\n\t\t\t\trec.dv = normalize(cross(rec.normal, rec.du));\n\n\t\t\t\trec.area = area;\n\n\t\t\t\t\/\/rec.obj = parent;\n\t\t\t\trec.obj = (hitable*)this;\n\n\t\t\t\tif (parent) {\n\t\t\t\t\trec.mtrl = parent->mtrl;\n\t\t\t\t}\n\n\t\t\t\tisHit = true;\n\t\t\t}\n\t\t}\n\n\t\treturn isHit;\n\t}\n\n\tvoid face::build(vertex* v0, vertex* v1, vertex* v2)\n\t{\n\t\tvec3 vmax(\n\t\t\tstd::max(v0->pos.x, std::max(v1->pos.x, v2->pos.x)),\n\t\t\tstd::max(v0->pos.y, std::max(v1->pos.y, v2->pos.y)),\n\t\t\tstd::max(v0->pos.z, std::max(v1->pos.z, v2->pos.z)));\n\n\t\tvec3 vmin(\n\t\t\tstd::min(v0->pos.x, std::min(v1->pos.x, v2->pos.x)),\n\t\t\tstd::min(v0->pos.y, std::min(v1->pos.y, v2->pos.y)),\n\t\t\tstd::min(v0->pos.z, std::min(v1->pos.z, v2->pos.z)));\n\n\t\tbbox.init(vmin, vmax);\n\n\t\tvtx[0] = v0;\n\t\tvtx[1] = v1;\n\t\tvtx[2] = v2;\n\n\t\t\/\/ Op`̖ʐ = Qӂ̊Oς̒ \/ 2;\n\t\tauto e0 = v1->pos - v0->pos;\n\t\tauto e1 = v2->pos - v0->pos;\n\t\tarea = 0.5 * cross(e0, e1).length();\n\t}\n\n\tvec3 face::getRandomPosOn(sampler* sampler) const\n\t{\n\t\t\/\/ 0 <= a + b <= 1\n\t\treal a = sampler->nextSample();\n\t\treal b = sampler->nextSample();\n\n\t\treal d = a + b;\n\n\t\tif (d > 1) {\n\t\t\ta \/= d;\n\t\t\tb \/= d;\n\t\t}\n\n\t\tconst auto& v0 = vtx[0];\n\t\tconst auto& v1 = vtx[1];\n\t\tconst auto& v2 = vtx[2];\n\n\t\t\/\/ dSWn(barycentric coordinates).\n\t\t\/\/ v0.\n\t\t\/\/ p = (1 - a - b)*v0 + a*v1 + b*v2\n\t\tvec3 p = (1 - a - b) * v0->pos + a * v1->pos + b * v2->pos;\n\n\t\treturn std::move(p);\n\t}\n\n\tvoid shape::build()\n\t{\n\t\tm_node.build(\n\t\t\t(bvhnode**)&faces[0],\n\t\t\t(uint32_t)faces.size());\n\n\t\tm_aabb = m_node.getBoundingbox();\n\n\t\tarea = 0;\n\t\tfor (const auto f : faces) {\n\t\t\tarea += f->area;\n\t\t}\n\t}\n\n\tbool shape::hit(\n\t\tconst ray& r,\n\t\treal t_min, real t_max,\n\t\thitrecord& rec) const\n\t{\n\t\tauto isHit = m_node.hit(r, t_min, t_max, rec);\n\n\t\tif (isHit) {\n\t\t\trec.mtrl = mtrl;\n\t\t}\n\n\t\treturn isHit;\n\t}\n\n\tvoid object::build()\n\t{\n\t\tm_node.build((bvhnode**)&shapes[0], (uint32_t)shapes.size());\n\n\t\tm_area = 0;\n\t\tm_triangles = 0;\n\n\t\tfor (const auto s : shapes) {\n\t\t\tm_area += s->area;\n\t\t\tm_triangles += s->faces.size();\n\t\t}\n\t}\n\n\tbool object::hit(\n\t\tconst ray& r,\n\t\tconst mat4& mtxL2W,\n\t\treal t_min, real t_max,\n\t\thitrecord& rec)\n\t{\n\t\tbool isHit = m_node.hit(r, t_min, t_max, rec);\n\t\tif (isHit) {\n\t\t\tface* f = (face*)rec.obj;\n\n#if 0\n\t\t\treal originalArea = 0;\n\t\t\t{\n\t\t\t\tconst auto& v0 = f->vtx[0]->pos;\n\t\t\t\tconst auto& v1 = f->vtx[1]->pos;\n\t\t\t\tconst auto& v2 = f->vtx[2]->pos;\n\n\t\t\t\t\/\/ Op`̖ʐ = Qӂ̊Oς̒ \/ 2;\n\t\t\t\tauto e0 = v1 - v0;\n\t\t\t\tauto e1 = v2 - v0;\n\t\t\t\toriginalArea = 0.5 * cross(e0, e1).length();\n\t\t\t}\n\n\t\t\treal scaledArea = 0;\n\t\t\t{\n\t\t\t\tauto v0 = mtxL2W.apply(f->vtx[0]->pos);\n\t\t\t\tauto v1 = mtxL2W.apply(f->vtx[1]->pos);\n\t\t\t\tauto v2 = mtxL2W.apply(f->vtx[2]->pos);\n\n\t\t\t\t\/\/ Op`̖ʐ = Qӂ̊Oς̒ \/ 2;\n\t\t\t\tauto e0 = v1 - v0;\n\t\t\t\tauto e1 = v2 - v0;\n\t\t\t\tscaledArea = 0.5 * cross(e0, e1).length();\n\t\t\t}\n\n\t\t\treal ratio = scaledArea \/ originalArea;\n#else\n\t\t\treal orignalLen = 0;\n\t\t\t{\n\t\t\t\tconst auto& v0 = f->vtx[0]->pos;\n\t\t\t\tconst auto& v1 = f->vtx[1]->pos;\n\n\t\t\t\torignalLen = (v1 - v0).length();\n\t\t\t}\n\n\t\t\treal scaledLen = 0;\n\t\t\t{\n\t\t\t\tauto v0 = mtxL2W.apply(f->vtx[0]->pos);\n\t\t\t\tauto v1 = mtxL2W.apply(f->vtx[1]->pos);\n\n\t\t\t\tscaledLen = (v1 - v0).length();\n\t\t\t}\n\n\t\t\treal ratio = scaledLen \/ orignalLen;\n\t\t\tratio = ratio * ratio;\n#endif\n\n\t\t\trec.area = m_area * ratio;\n\n\t\t\t\/\/ ŏIIɂ́Aςshapen.\n\t\t\trec.obj = f->parent;\n\t\t}\n\t\treturn isHit;\n\t}\n}\n<|endoftext|>"} {"text":"<commit_before>\/**************************************************************************\n**\n** This file is part of Qt Creator\n**\n** Copyright (c) 2009 Nokia Corporation and\/or its subsidiary(-ies).\n**\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n** Commercial Usage\n**\n** Licensees holding valid Qt Commercial licenses may use this file in\n** accordance with the Qt Commercial License Agreement provided with the\n** Software or, alternatively, in accordance with the terms contained in\n** a written agreement between you and Nokia.\n**\n** GNU Lesser General Public License Usage\n**\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** If you are unsure which license is appropriate for your use, please\n** contact the sales department at http:\/\/qt.nokia.com\/contact.\n**\n**************************************************************************\/\n\n#include \"qmljscheck.h\"\n#include \"qmljsbind.h\"\n#include \"qmljsinterpreter.h\"\n#include \"qmljsevaluate.h\"\n#include \"parser\/qmljsast_p.h\"\n\n#include <QtCore\/QDebug>\n#include <QtCore\/QCoreApplication>\n#include <QtGui\/QColor>\n#include <QtGui\/QApplication>\n\n#ifndef NO_DECLARATIVE_BACKEND\n# include <QtDeclarative\/private\/qmlstringconverters_p.h> \/\/ ### remove me\n#endif\n\nnamespace QmlJS {\nnamespace Messages {\nstatic const char *invalid_property_name = QT_TRANSLATE_NOOP(\"QmlJS::Check\", \"'%1' is not a valid property name\");\nstatic const char *unknown_type = QT_TRANSLATE_NOOP(\"QmlJS::Check\", \"unknown type\");\nstatic const char *has_no_members = QT_TRANSLATE_NOOP(\"QmlJS::Check\", \"'%1' does not have members\");\nstatic const char *is_not_a_member = QT_TRANSLATE_NOOP(\"QmlJS::Check\", \"'%1' is not a member of '%2'\");\nstatic const char *easing_curve_not_a_string = QT_TRANSLATE_NOOP(\"QmlJS::Check\", \"easing-curve name is not a string\");\nstatic const char *unknown_easing_curve_name = QT_TRANSLATE_NOOP(\"QmlJS::Check\", \"unknown easing-curve name\");\nstatic const char *value_might_be_undefined = QT_TRANSLATE_NOOP(\"QmlJS::Check\", \"value might be 'undefined'\");\n} \/\/ namespace Messages\n\nstatic inline QString tr(const char *msg)\n{ return qApp->translate(\"QmlJS::Check\", msg); }\n\n} \/\/ namespace QmlJS\n\nusing namespace QmlJS;\nusing namespace QmlJS::AST;\nusing namespace QmlJS::Interpreter;\n\nCheck::Check(Document::Ptr doc, const Snapshot &snapshot)\n : _doc(doc)\n , _snapshot(snapshot)\n , _context(&_engine)\n , _link(&_context, doc, snapshot)\n , _scopeBuilder(doc, &_context)\n{\n}\n\nCheck::~Check()\n{\n}\n\nQList<DiagnosticMessage> Check::operator()()\n{\n _messages.clear();\n Node::accept(_doc->ast(), this);\n return _messages;\n}\n\nbool Check::visit(UiProgram *)\n{\n \/\/ build the initial scope chain\n _link.scopeChainAt(_doc);\n\n return true;\n}\n\nbool Check::visit(UiObjectDefinition *ast)\n{\n visitQmlObject(ast, ast->qualifiedTypeNameId, ast->initializer);\n return false;\n}\n\nbool Check::visit(UiObjectBinding *ast)\n{\n checkScopeObjectMember(ast->qualifiedId);\n\n visitQmlObject(ast, ast->qualifiedTypeNameId, ast->initializer);\n return false;\n}\n\nvoid Check::visitQmlObject(Node *ast, UiQualifiedId *typeId,\n UiObjectInitializer *initializer)\n{\n \/\/ If the 'typeId' starts with a lower-case letter, it doesn't define\n \/\/ a new object instance. For instance: anchors { ... }\n if (typeId->name->asString().at(0).isLower() && ! typeId->next) {\n checkScopeObjectMember(typeId);\n \/\/ ### don't give up!\n return;\n }\n\n _scopeBuilder.push(ast);\n\n if (! _context.lookupType(_doc.data(), typeId)) {\n warning(typeId->identifierToken, tr(Messages::unknown_type));\n \/\/ suppress subsequent errors about scope object lookup by clearing\n \/\/ the scope object list\n \/\/ ### todo: better way?\n _context.scopeChain().qmlScopeObjects.clear();\n _context.scopeChain().update();\n }\n\n Node::accept(initializer, this);\n\n _scopeBuilder.pop();\n}\n\nvoid Check::errorOnWrongRhs(const SourceLocation &loc, const Value *lhsValue)\n{\n if (lhsValue->asBooleanValue()) {\n error(loc, QCoreApplication::translate(\"QmlJS::Check\", \"boolean value expected\"));\n } else if (lhsValue->asNumberValue()) {\n error(loc, QCoreApplication::translate(\"QmlJS::Check\", \"numerical value expected\"));\n } else if (lhsValue->asStringValue()) {\n error(loc, QCoreApplication::translate(\"QmlJS::Check\", \"string value expected\"));\n }\n}\n\nbool Check::visit(UiScriptBinding *ast)\n{\n const Value *lhsValue = checkScopeObjectMember(ast->qualifiedId);\n if (lhsValue) {\n \/\/ ### Fix the evaluator to accept statements!\n if (ExpressionStatement *expStmt = cast<ExpressionStatement *>(ast->statement)) {\n ExpressionNode *expr = expStmt->expression;\n\n Evaluate evaluator(&_context);\n const Value *rhsValue = evaluator(expr);\n\n const SourceLocation loc = locationFromRange(expStmt->firstSourceLocation(),\n expStmt->lastSourceLocation());\n checkPropertyAssignment(loc, lhsValue, rhsValue, expr);\n }\n\n }\n\n return true;\n}\n\nvoid Check::checkPropertyAssignment(const SourceLocation &location,\n const Interpreter::Value *lhsValue,\n const Interpreter::Value *rhsValue,\n ExpressionNode *ast)\n{\n UnaryMinusExpression *unaryMinus = cast<UnaryMinusExpression *>(ast);\n\n \/\/ Qml is particularly strict with literals\n if (StringLiteral *stringLiteral = cast<StringLiteral *>(ast)) {\n const QString string = stringLiteral->value->asString();\n\n if (lhsValue->asStringValue()) {\n \/\/ okay\n } else if (lhsValue->asColorValue()) {\n#ifndef NO_DECLARATIVE_BACKEND\n bool ok = false;\n QmlStringConverters::colorFromString(string, &ok);\n if (!ok)\n error(location, QCoreApplication::translate(\"QmlJS::Check\", \"not a valid color\"));\n#endif\n } else if (lhsValue->asEasingCurveNameValue()) {\n \/\/ ### do something with easing-curve attributes.\n \/\/ ### Incomplete documentation at: http:\/\/qt.nokia.com\/doc\/4.7-snapshot\/qml-propertyanimation.html#easing-prop\n \/\/ ### The implementation is at: src\/declarative\/util\/qmlanimation.cpp\n const QString curveName = string.left(string.indexOf(QLatin1Char('(')));\n if (!EasingCurveNameValue::curveNames().contains(curveName)) {\n error(location, tr(Messages::unknown_easing_curve_name));\n }\n } else {\n errorOnWrongRhs(location, lhsValue);\n }\n } else if ((ast->kind == Node::Kind_TrueLiteral\n || ast->kind == Node::Kind_FalseLiteral)\n && ! lhsValue->asBooleanValue()) {\n errorOnWrongRhs(location, lhsValue);\n } else if (cast<NumericLiteral *>(ast)\n && ! lhsValue->asNumberValue()) {\n errorOnWrongRhs(location, lhsValue);\n } else if (unaryMinus && cast<NumericLiteral *>(unaryMinus->expression)\n && ! lhsValue->asNumberValue()) {\n errorOnWrongRhs(location, lhsValue);\n } else {\n \/\/ rhs is not a literal\n if (lhsValue->asEasingCurveNameValue()) {\n const StringValue *rhsStringValue = rhsValue->asStringValue();\n if (!rhsStringValue) {\n if (rhsValue->asUndefinedValue())\n warning(location, tr(Messages::value_might_be_undefined));\n else\n error(location, tr(Messages::easing_curve_not_a_string));\n return;\n }\n }\n }\n}\n\nbool Check::visit(UiArrayBinding *ast)\n{\n checkScopeObjectMember(ast->qualifiedId);\n\n return true;\n}\n\nconst Value *Check::checkScopeObjectMember(const UiQualifiedId *id)\n{\n QList<const ObjectValue *> scopeObjects = _context.scopeChain().qmlScopeObjects;\n if (scopeObjects.isEmpty())\n return 0;\n\n if (! id)\n return 0; \/\/ ### error?\n\n QString propertyName = id->name->asString();\n\n if (propertyName == QLatin1String(\"id\") && ! id->next)\n return 0; \/\/ ### should probably be a special value\n\n \/\/ attached properties\n bool isAttachedProperty = false;\n if (! propertyName.isEmpty() && propertyName[0].isUpper()) {\n isAttachedProperty = true;\n scopeObjects += _context.scopeChain().qmlTypes;\n }\n\n if (scopeObjects.isEmpty())\n return 0;\n\n \/\/ global lookup for first part of id\n const Value *value = 0;\n for (int i = scopeObjects.size() - 1; i >= 0; --i) {\n value = scopeObjects[i]->lookupMember(propertyName, &_context);\n if (value)\n break;\n }\n if (!value) {\n error(id->identifierToken,\n tr(Messages::invalid_property_name).arg(propertyName));\n }\n\n \/\/ can't look up members for attached properties\n if (isAttachedProperty)\n return 0;\n\n \/\/ member lookup\n const UiQualifiedId *idPart = id;\n while (idPart->next) {\n const ObjectValue *objectValue = value_cast<const ObjectValue *>(value);\n if (! objectValue) {\n error(idPart->identifierToken,\n tr(Messages::has_no_members).arg(propertyName));\n return 0;\n }\n\n idPart = idPart->next;\n propertyName = idPart->name->asString();\n\n value = objectValue->lookupMember(propertyName, &_context);\n if (! value) {\n error(idPart->identifierToken,\n tr(Messages::is_not_a_member).arg(propertyName,\n objectValue->className()));\n return 0;\n }\n }\n\n return value;\n}\n\nvoid Check::error(const AST::SourceLocation &loc, const QString &message)\n{\n _messages.append(DiagnosticMessage(DiagnosticMessage::Error, loc, message));\n}\n\nvoid Check::warning(const AST::SourceLocation &loc, const QString &message)\n{\n _messages.append(DiagnosticMessage(DiagnosticMessage::Warning, loc, message));\n}\n\nSourceLocation Check::locationFromRange(const SourceLocation &start,\n const SourceLocation &end)\n{\n return SourceLocation(start.offset,\n end.end() - start.begin(),\n start.startLine,\n start.startColumn);\n}\n<commit_msg>Check that the id property is a plain lowercase identifier.<commit_after>\/**************************************************************************\n**\n** This file is part of Qt Creator\n**\n** Copyright (c) 2009 Nokia Corporation and\/or its subsidiary(-ies).\n**\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n** Commercial Usage\n**\n** Licensees holding valid Qt Commercial licenses may use this file in\n** accordance with the Qt Commercial License Agreement provided with the\n** Software or, alternatively, in accordance with the terms contained in\n** a written agreement between you and Nokia.\n**\n** GNU Lesser General Public License Usage\n**\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** If you are unsure which license is appropriate for your use, please\n** contact the sales department at http:\/\/qt.nokia.com\/contact.\n**\n**************************************************************************\/\n\n#include \"qmljscheck.h\"\n#include \"qmljsbind.h\"\n#include \"qmljsinterpreter.h\"\n#include \"qmljsevaluate.h\"\n#include \"parser\/qmljsast_p.h\"\n\n#include <QtCore\/QDebug>\n#include <QtCore\/QCoreApplication>\n#include <QtGui\/QColor>\n#include <QtGui\/QApplication>\n\n#ifndef NO_DECLARATIVE_BACKEND\n# include <QtDeclarative\/private\/qmlstringconverters_p.h> \/\/ ### remove me\n#endif\n\nnamespace QmlJS {\nnamespace Messages {\nstatic const char *invalid_property_name = QT_TRANSLATE_NOOP(\"QmlJS::Check\", \"'%1' is not a valid property name\");\nstatic const char *unknown_type = QT_TRANSLATE_NOOP(\"QmlJS::Check\", \"unknown type\");\nstatic const char *has_no_members = QT_TRANSLATE_NOOP(\"QmlJS::Check\", \"'%1' does not have members\");\nstatic const char *is_not_a_member = QT_TRANSLATE_NOOP(\"QmlJS::Check\", \"'%1' is not a member of '%2'\");\nstatic const char *easing_curve_not_a_string = QT_TRANSLATE_NOOP(\"QmlJS::Check\", \"easing-curve name is not a string\");\nstatic const char *unknown_easing_curve_name = QT_TRANSLATE_NOOP(\"QmlJS::Check\", \"unknown easing-curve name\");\nstatic const char *value_might_be_undefined = QT_TRANSLATE_NOOP(\"QmlJS::Check\", \"value might be 'undefined'\");\n} \/\/ namespace Messages\n\nstatic inline QString tr(const char *msg)\n{ return qApp->translate(\"QmlJS::Check\", msg); }\n\n} \/\/ namespace QmlJS\n\nusing namespace QmlJS;\nusing namespace QmlJS::AST;\nusing namespace QmlJS::Interpreter;\n\nCheck::Check(Document::Ptr doc, const Snapshot &snapshot)\n : _doc(doc)\n , _snapshot(snapshot)\n , _context(&_engine)\n , _link(&_context, doc, snapshot)\n , _scopeBuilder(doc, &_context)\n{\n}\n\nCheck::~Check()\n{\n}\n\nQList<DiagnosticMessage> Check::operator()()\n{\n _messages.clear();\n Node::accept(_doc->ast(), this);\n return _messages;\n}\n\nbool Check::visit(UiProgram *)\n{\n \/\/ build the initial scope chain\n _link.scopeChainAt(_doc);\n\n return true;\n}\n\nbool Check::visit(UiObjectDefinition *ast)\n{\n visitQmlObject(ast, ast->qualifiedTypeNameId, ast->initializer);\n return false;\n}\n\nbool Check::visit(UiObjectBinding *ast)\n{\n checkScopeObjectMember(ast->qualifiedId);\n\n visitQmlObject(ast, ast->qualifiedTypeNameId, ast->initializer);\n return false;\n}\n\nvoid Check::visitQmlObject(Node *ast, UiQualifiedId *typeId,\n UiObjectInitializer *initializer)\n{\n \/\/ If the 'typeId' starts with a lower-case letter, it doesn't define\n \/\/ a new object instance. For instance: anchors { ... }\n if (typeId->name->asString().at(0).isLower() && ! typeId->next) {\n checkScopeObjectMember(typeId);\n \/\/ ### don't give up!\n return;\n }\n\n _scopeBuilder.push(ast);\n\n if (! _context.lookupType(_doc.data(), typeId)) {\n warning(typeId->identifierToken, tr(Messages::unknown_type));\n \/\/ suppress subsequent errors about scope object lookup by clearing\n \/\/ the scope object list\n \/\/ ### todo: better way?\n _context.scopeChain().qmlScopeObjects.clear();\n _context.scopeChain().update();\n }\n\n Node::accept(initializer, this);\n\n _scopeBuilder.pop();\n}\n\nvoid Check::errorOnWrongRhs(const SourceLocation &loc, const Value *lhsValue)\n{\n if (lhsValue->asBooleanValue()) {\n error(loc, QCoreApplication::translate(\"QmlJS::Check\", \"boolean value expected\"));\n } else if (lhsValue->asNumberValue()) {\n error(loc, QCoreApplication::translate(\"QmlJS::Check\", \"numerical value expected\"));\n } else if (lhsValue->asStringValue()) {\n error(loc, QCoreApplication::translate(\"QmlJS::Check\", \"string value expected\"));\n }\n}\n\nbool Check::visit(UiScriptBinding *ast)\n{\n \/\/ special case for id property\n if (ast->qualifiedId->name->asString() == QLatin1String(\"id\") && ! ast->qualifiedId->next) {\n if (! ast->statement)\n return false;\n\n const SourceLocation loc = locationFromRange(ast->statement->firstSourceLocation(),\n ast->statement->lastSourceLocation());\n\n ExpressionStatement *expStmt = cast<ExpressionStatement *>(ast->statement);\n if (!expStmt) {\n error(loc, QCoreApplication::translate(\"QmlJS::Check\", \"expected id\"));\n return false;\n }\n\n IdentifierExpression *idExp = cast<IdentifierExpression *>(expStmt->expression);\n if (! idExp) {\n error(loc, QCoreApplication::translate(\"QmlJS::Check\", \"expected id\"));\n return false;\n }\n\n if (! idExp->name->asString()[0].isLower()) {\n error(loc, QCoreApplication::translate(\"QmlJS::Check\", \"ids must be lower case\"));\n return false;\n }\n }\n\n const Value *lhsValue = checkScopeObjectMember(ast->qualifiedId);\n if (lhsValue) {\n \/\/ ### Fix the evaluator to accept statements!\n if (ExpressionStatement *expStmt = cast<ExpressionStatement *>(ast->statement)) {\n ExpressionNode *expr = expStmt->expression;\n\n Evaluate evaluator(&_context);\n const Value *rhsValue = evaluator(expr);\n\n const SourceLocation loc = locationFromRange(expStmt->firstSourceLocation(),\n expStmt->lastSourceLocation());\n checkPropertyAssignment(loc, lhsValue, rhsValue, expr);\n }\n\n }\n\n return true;\n}\n\nvoid Check::checkPropertyAssignment(const SourceLocation &location,\n const Interpreter::Value *lhsValue,\n const Interpreter::Value *rhsValue,\n ExpressionNode *ast)\n{\n UnaryMinusExpression *unaryMinus = cast<UnaryMinusExpression *>(ast);\n\n \/\/ Qml is particularly strict with literals\n if (StringLiteral *stringLiteral = cast<StringLiteral *>(ast)) {\n const QString string = stringLiteral->value->asString();\n\n if (lhsValue->asStringValue()) {\n \/\/ okay\n } else if (lhsValue->asColorValue()) {\n#ifndef NO_DECLARATIVE_BACKEND\n bool ok = false;\n QmlStringConverters::colorFromString(string, &ok);\n if (!ok)\n error(location, QCoreApplication::translate(\"QmlJS::Check\", \"not a valid color\"));\n#endif\n } else if (lhsValue->asEasingCurveNameValue()) {\n \/\/ ### do something with easing-curve attributes.\n \/\/ ### Incomplete documentation at: http:\/\/qt.nokia.com\/doc\/4.7-snapshot\/qml-propertyanimation.html#easing-prop\n \/\/ ### The implementation is at: src\/declarative\/util\/qmlanimation.cpp\n const QString curveName = string.left(string.indexOf(QLatin1Char('(')));\n if (!EasingCurveNameValue::curveNames().contains(curveName)) {\n error(location, tr(Messages::unknown_easing_curve_name));\n }\n } else {\n errorOnWrongRhs(location, lhsValue);\n }\n } else if ((ast->kind == Node::Kind_TrueLiteral\n || ast->kind == Node::Kind_FalseLiteral)\n && ! lhsValue->asBooleanValue()) {\n errorOnWrongRhs(location, lhsValue);\n } else if (cast<NumericLiteral *>(ast)\n && ! lhsValue->asNumberValue()) {\n errorOnWrongRhs(location, lhsValue);\n } else if (unaryMinus && cast<NumericLiteral *>(unaryMinus->expression)\n && ! lhsValue->asNumberValue()) {\n errorOnWrongRhs(location, lhsValue);\n } else {\n \/\/ rhs is not a literal\n if (lhsValue->asEasingCurveNameValue()) {\n const StringValue *rhsStringValue = rhsValue->asStringValue();\n if (!rhsStringValue) {\n if (rhsValue->asUndefinedValue())\n warning(location, tr(Messages::value_might_be_undefined));\n else\n error(location, tr(Messages::easing_curve_not_a_string));\n return;\n }\n }\n }\n}\n\nbool Check::visit(UiArrayBinding *ast)\n{\n checkScopeObjectMember(ast->qualifiedId);\n\n return true;\n}\n\nconst Value *Check::checkScopeObjectMember(const UiQualifiedId *id)\n{\n QList<const ObjectValue *> scopeObjects = _context.scopeChain().qmlScopeObjects;\n if (scopeObjects.isEmpty())\n return 0;\n\n if (! id)\n return 0; \/\/ ### error?\n\n QString propertyName = id->name->asString();\n\n if (propertyName == QLatin1String(\"id\") && ! id->next)\n return 0; \/\/ ### should probably be a special value\n\n \/\/ attached properties\n bool isAttachedProperty = false;\n if (! propertyName.isEmpty() && propertyName[0].isUpper()) {\n isAttachedProperty = true;\n scopeObjects += _context.scopeChain().qmlTypes;\n }\n\n if (scopeObjects.isEmpty())\n return 0;\n\n \/\/ global lookup for first part of id\n const Value *value = 0;\n for (int i = scopeObjects.size() - 1; i >= 0; --i) {\n value = scopeObjects[i]->lookupMember(propertyName, &_context);\n if (value)\n break;\n }\n if (!value) {\n error(id->identifierToken,\n tr(Messages::invalid_property_name).arg(propertyName));\n }\n\n \/\/ can't look up members for attached properties\n if (isAttachedProperty)\n return 0;\n\n \/\/ member lookup\n const UiQualifiedId *idPart = id;\n while (idPart->next) {\n const ObjectValue *objectValue = value_cast<const ObjectValue *>(value);\n if (! objectValue) {\n error(idPart->identifierToken,\n tr(Messages::has_no_members).arg(propertyName));\n return 0;\n }\n\n idPart = idPart->next;\n propertyName = idPart->name->asString();\n\n value = objectValue->lookupMember(propertyName, &_context);\n if (! value) {\n error(idPart->identifierToken,\n tr(Messages::is_not_a_member).arg(propertyName,\n objectValue->className()));\n return 0;\n }\n }\n\n return value;\n}\n\nvoid Check::error(const AST::SourceLocation &loc, const QString &message)\n{\n _messages.append(DiagnosticMessage(DiagnosticMessage::Error, loc, message));\n}\n\nvoid Check::warning(const AST::SourceLocation &loc, const QString &message)\n{\n _messages.append(DiagnosticMessage(DiagnosticMessage::Warning, loc, message));\n}\n\nSourceLocation Check::locationFromRange(const SourceLocation &start,\n const SourceLocation &end)\n{\n return SourceLocation(start.offset,\n end.end() - start.begin(),\n start.startLine,\n start.startColumn);\n}\n<|endoftext|>"} {"text":"<commit_before>\/* MIT License\n *\n * Copyright (c) 2016 Omar Alvarez <omar.alvarez@udc.es>\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n *\/\n\n#include <chrono>\n\n#include \"gpusolver.h\"\n\n#define DEBUG\n\nGPUSolver::GPUSolver() {\n\n\t\/* Notes\n\tI've added some extra parameters in this interface to assist with dev, such as\n\ta kernel string to specify which kernel to run and local\/global work sizes.\n\n\tThe following are private members of the class, but I have them here to specify the\n\tglobal work size for now. This will probably be hard-coded later\n\t*\/\n\tunsigned int z_n = 200;\n\tunsigned int z_k = 9;\n\tsize_t z_collision_bit_length = z_n \/ (z_k + 1);\n\teh_index z_N = 1 << (z_collision_bit_length + 1);\n\t\/\/uint32_t global_work_size = z_N;\n\n\t\/\/TODO This looks like IND_PER_BUCKET, enough for GPU?\n\tsize_t global_work_size = 1 << 20;\n size_t local_work_size = 32;\n\n\tminer = new cl_zogminer();\n\n\t\/* Checks each device for memory requirements and sets local\/global sizes\n\tTODO: Implement device logic for equihash kernel\n\t@params: unsigned platformId\n\t@params: unsigned localWorkSizes\n\t@params: unsigned globalWorkSizes\n\t*\/\n\tGPU = miner->configureGPU(0, local_work_size, global_work_size);\n\tif(!GPU)\n\t\tstd::cout << \"ERROR: No suitable GPU found! No work will be performed!\" << std::endl;\n\n\t\/*Initialize the kernel, compile it and create buffers\n\tCurrently runs for the gpu-list-gen.c kernel DATA_SIZE=100 times\n\tTODO: pass base state and nonce's to kernel.\n\t@params: unsigned _platformId\n\t@params: unsigned _deviceId\n\t@params: string& _kernel - The name of the kernel for dev purposes\n\t*\/\n\tstd::vector<std::string> kernels {\"initial_bucket_hashing\", \"bucket_collide_and_hash\", \"produce_solutions\"};\n\tif(GPU)\n\t\tinitOK = miner->init(0, 0, kernels);\n\n}\n\nGPUSolver::GPUSolver(int64_t selGPU) {\n\n\t\/* Notes\n\tI've added some extra parameters in this interface to assist with dev, such as\n\ta kernel string to specify which kernel to run and local\/global work sizes.\n\n\tThe following are private members of the class, but I have them here to specify the\n\tglobal work size for now. This will probably be hard-coded later\n\t*\/\n\tunsigned int z_n = 200;\n\tunsigned int z_k = 9;\n\tsize_t z_collision_bit_length = z_n \/ (z_k + 1);\n\teh_index z_N = 1 << (z_collision_bit_length + 1);\n\t\/\/uint32_t global_work_size = z_N;\n\n\t\/\/TODO This looks like IND_PER_BUCKET, enough for GPU?\n\tsize_t global_work_size = 1 << 17;\n size_t local_work_size = 32;\n\n\tminer = new cl_zogminer();\n\n\t\/* Checks each device for memory requirements and sets local\/global sizes\n\tTODO: Implement device logic for equihash kernel\n\t@params: unsigned platformId\n\t@params: unsigned localWorkSizes\n\t@params: unsigned globalWorkSizes\n\t*\/\n\tGPU = miner->configureGPU(0, local_work_size, global_work_size);\n\tif(!GPU)\n\t\tstd::cout << \"ERROR: No suitable GPU found! No work will be performed!\" << std::endl;\n\n\t\/*Initialize the kernel, compile it and create buffers\n\tCurrently runs for the gpu-list-gen.c kernel DATA_SIZE=100 times\n\tTODO: pass base state and nonce's to kernel.\n\t@params: unsigned _platformId\n\t@params: unsigned _deviceId\n\t@params: string& _kernel - The name of the kernel for dev purposes\n\t*\/\n\tstd::vector<std::string> kernels {\"initial_bucket_hashing\", \"bucket_collide_and_hash\", \"produce_solutions\"};\n\tif(GPU)\n\t\tinitOK = miner->init(0, selGPU, kernels);\n\n}\n\nGPUSolver::~GPUSolver() {\n\n\tif(GPU)\n\t\tminer->finish();\n\n\tdelete miner;\n\n}\n\nbool GPUSolver::run(unsigned int n, unsigned int k, const eh_HashState& base_state,\n\t\t const std::function<bool(std::vector<unsigned char>)> validBlock,\n\t\t\t\tconst std::function<bool(GPUSolverCancelCheck)> cancelled) {\n\n if (n == 200 && k == 9) {\n return GPUSolve200_9(base_state, validBlock, cancelled);\n } else {\n throw std::invalid_argument(\"Unsupported Equihash parameters\");\n }\n\n}\n\nbool GPUSolver::GPUSolve200_9(const eh_HashState& base_state,\n \tconst std::function<bool(std::vector<unsigned char>)> validBlock,\n\t\t\tconst std::function<bool(GPUSolverCancelCheck)> cancelled) {\n\n\t\/* Run the kernel\n\tTODO: Optimise and figure out how we want this to go\n\t@params eh_HashState& base_state - Sends to kernel in a buffer. Will update for specific kernels\n\t*\/\n \n\tif(GPU && initOK) {\n auto t = std::chrono::high_resolution_clock::now();\n\n\t\tuint32_t n_sol;\n\n \tminer->run(base_state, indices, &n_sol);\n\n\t\tauto d = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::high_resolution_clock::now() - t);\n\t\tauto milis = std::chrono::duration_cast<std::chrono::milliseconds>(d).count();\n\t\tif(!counter) {\n\t\t\tsum = 1000.f*n_sol\/milis;\n\t\t} else { \n\t\t\tsum += 1000.f*n_sol\/milis;\n\t\t}\n\t\t\n\t\tavg = sum\/++counter;\t\t\t\t\n\t\t\n\t\tstd::cout << \"Kernel run took \" << milis << \" ms. (\" << avg << \" H\/s)\" << std::endl;\n\n\t\tsize_t checkedSols = 0;\n for (size_t s = 0; s < n_sol; ++s) {\n \t++checkedSols;\n std::cout << \"Checking solution \" << checkedSols << std::endl;\n std::vector<eh_index> index_vector(PROOFSIZE);\n for (size_t i = 0; i < PROOFSIZE; i++) {\n \tindex_vector[i] = indices[s * PROOFSIZE + i];\n }\n std::vector<unsigned char> sol_char = GetMinimalFromIndices(index_vector, DIGITBITS);\n#ifdef DEBUG\n bool isValid;\n EhIsValidSolution(200, 9, base_state, sol_char, isValid);\n std::cout << \"is valid: \" << isValid << '\\n';\n if (!isValid) {\n\t\t\t\t \/\/If we find invalid solution bail, it cannot be a valid POW\n\t\t\t\t std::cout << \"Invalid solution found!\" << std::endl;\n \t return false;\n } else {\n \tstd::cout << \"Valid solution found!\" << std::endl;\n }\n#endif\n if (validBlock(sol_char)) {\n \t\/\/ If we find a POW solution, do not try other solutions\n \t\/\/ because they become invalid as we created a new block in blockchain.\n\t\t\t\t std::cout << \"Valid block found!\" << std::endl;\n \t return true;\n }\n }\n\n\t}\n\n return false;\n\n}\n\n<commit_msg>Remove debug flag<commit_after>\/* MIT License\n *\n * Copyright (c) 2016 Omar Alvarez <omar.alvarez@udc.es>\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n *\/\n\n#include <chrono>\n\n#include \"gpusolver.h\"\n\n\/\/#define DEBUG\n\nGPUSolver::GPUSolver() {\n\n\t\/* Notes\n\tI've added some extra parameters in this interface to assist with dev, such as\n\ta kernel string to specify which kernel to run and local\/global work sizes.\n\n\tThe following are private members of the class, but I have them here to specify the\n\tglobal work size for now. This will probably be hard-coded later\n\t*\/\n\tunsigned int z_n = 200;\n\tunsigned int z_k = 9;\n\tsize_t z_collision_bit_length = z_n \/ (z_k + 1);\n\teh_index z_N = 1 << (z_collision_bit_length + 1);\n\t\/\/uint32_t global_work_size = z_N;\n\n\t\/\/TODO This looks like IND_PER_BUCKET, enough for GPU?\n\tsize_t global_work_size = 1 << 20;\n size_t local_work_size = 32;\n\n\tminer = new cl_zogminer();\n\n\t\/* Checks each device for memory requirements and sets local\/global sizes\n\tTODO: Implement device logic for equihash kernel\n\t@params: unsigned platformId\n\t@params: unsigned localWorkSizes\n\t@params: unsigned globalWorkSizes\n\t*\/\n\tGPU = miner->configureGPU(0, local_work_size, global_work_size);\n\tif(!GPU)\n\t\tstd::cout << \"ERROR: No suitable GPU found! No work will be performed!\" << std::endl;\n\n\t\/*Initialize the kernel, compile it and create buffers\n\tCurrently runs for the gpu-list-gen.c kernel DATA_SIZE=100 times\n\tTODO: pass base state and nonce's to kernel.\n\t@params: unsigned _platformId\n\t@params: unsigned _deviceId\n\t@params: string& _kernel - The name of the kernel for dev purposes\n\t*\/\n\tstd::vector<std::string> kernels {\"initial_bucket_hashing\", \"bucket_collide_and_hash\", \"produce_solutions\"};\n\tif(GPU)\n\t\tinitOK = miner->init(0, 0, kernels);\n\n}\n\nGPUSolver::GPUSolver(int64_t selGPU) {\n\n\t\/* Notes\n\tI've added some extra parameters in this interface to assist with dev, such as\n\ta kernel string to specify which kernel to run and local\/global work sizes.\n\n\tThe following are private members of the class, but I have them here to specify the\n\tglobal work size for now. This will probably be hard-coded later\n\t*\/\n\tunsigned int z_n = 200;\n\tunsigned int z_k = 9;\n\tsize_t z_collision_bit_length = z_n \/ (z_k + 1);\n\teh_index z_N = 1 << (z_collision_bit_length + 1);\n\t\/\/uint32_t global_work_size = z_N;\n\n\t\/\/TODO This looks like IND_PER_BUCKET, enough for GPU?\n\tsize_t global_work_size = 1 << 17;\n size_t local_work_size = 32;\n\n\tminer = new cl_zogminer();\n\n\t\/* Checks each device for memory requirements and sets local\/global sizes\n\tTODO: Implement device logic for equihash kernel\n\t@params: unsigned platformId\n\t@params: unsigned localWorkSizes\n\t@params: unsigned globalWorkSizes\n\t*\/\n\tGPU = miner->configureGPU(0, local_work_size, global_work_size);\n\tif(!GPU)\n\t\tstd::cout << \"ERROR: No suitable GPU found! No work will be performed!\" << std::endl;\n\n\t\/*Initialize the kernel, compile it and create buffers\n\tCurrently runs for the gpu-list-gen.c kernel DATA_SIZE=100 times\n\tTODO: pass base state and nonce's to kernel.\n\t@params: unsigned _platformId\n\t@params: unsigned _deviceId\n\t@params: string& _kernel - The name of the kernel for dev purposes\n\t*\/\n\tstd::vector<std::string> kernels {\"initial_bucket_hashing\", \"bucket_collide_and_hash\", \"produce_solutions\"};\n\tif(GPU)\n\t\tinitOK = miner->init(0, selGPU, kernels);\n\n}\n\nGPUSolver::~GPUSolver() {\n\n\tif(GPU)\n\t\tminer->finish();\n\n\tdelete miner;\n\n}\n\nbool GPUSolver::run(unsigned int n, unsigned int k, const eh_HashState& base_state,\n\t\t const std::function<bool(std::vector<unsigned char>)> validBlock,\n\t\t\t\tconst std::function<bool(GPUSolverCancelCheck)> cancelled) {\n\n if (n == 200 && k == 9) {\n return GPUSolve200_9(base_state, validBlock, cancelled);\n } else {\n throw std::invalid_argument(\"Unsupported Equihash parameters\");\n }\n\n}\n\nbool GPUSolver::GPUSolve200_9(const eh_HashState& base_state,\n \tconst std::function<bool(std::vector<unsigned char>)> validBlock,\n\t\t\tconst std::function<bool(GPUSolverCancelCheck)> cancelled) {\n\n\t\/* Run the kernel\n\tTODO: Optimise and figure out how we want this to go\n\t@params eh_HashState& base_state - Sends to kernel in a buffer. Will update for specific kernels\n\t*\/\n \n\tif(GPU && initOK) {\n auto t = std::chrono::high_resolution_clock::now();\n\n\t\tuint32_t n_sol;\n\n \tminer->run(base_state, indices, &n_sol);\n\n\t\tauto d = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::high_resolution_clock::now() - t);\n\t\tauto milis = std::chrono::duration_cast<std::chrono::milliseconds>(d).count();\n\t\tif(!counter) {\n\t\t\tsum = 1000.f*n_sol\/milis;\n\t\t} else { \n\t\t\tsum += 1000.f*n_sol\/milis;\n\t\t}\n\t\t\n\t\tavg = sum\/++counter;\t\t\t\t\n\t\t\n\t\tstd::cout << \"Kernel run took \" << milis << \" ms. (\" << avg << \" H\/s)\" << std::endl;\n\n\t\tsize_t checkedSols = 0;\n for (size_t s = 0; s < n_sol; ++s) {\n \t++checkedSols;\n std::cout << \"Checking solution \" << checkedSols << std::endl;\n std::vector<eh_index> index_vector(PROOFSIZE);\n for (size_t i = 0; i < PROOFSIZE; i++) {\n \tindex_vector[i] = indices[s * PROOFSIZE + i];\n }\n std::vector<unsigned char> sol_char = GetMinimalFromIndices(index_vector, DIGITBITS);\n#ifdef DEBUG\n bool isValid;\n EhIsValidSolution(200, 9, base_state, sol_char, isValid);\n std::cout << \"is valid: \" << isValid << '\\n';\n if (!isValid) {\n\t\t\t\t \/\/If we find invalid solution bail, it cannot be a valid POW\n\t\t\t\t std::cout << \"Invalid solution found!\" << std::endl;\n \t return false;\n } else {\n \tstd::cout << \"Valid solution found!\" << std::endl;\n }\n#endif\n if (validBlock(sol_char)) {\n \t\/\/ If we find a POW solution, do not try other solutions\n \t\/\/ because they become invalid as we created a new block in blockchain.\n\t\t\t\t std::cout << \"Valid block found!\" << std::endl;\n \t return true;\n }\n }\n\n\t}\n\n return false;\n\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n\/\/ Copyright (c) 2018 Intel Corporation\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n*\/\n\n#include <conf.hpp>\n#include <dbus\/util.hpp>\n#include <iostream>\n#include <sdbusplus\/bus.hpp>\n#include <set>\n#include <unordered_map>\n\nstatic constexpr bool DEBUG = false; \/\/ enable to print found configuration\n\nstd::map<std::string, struct sensor> SensorConfig = {};\nstd::map<int64_t, PIDConf> ZoneConfig = {};\nstd::map<int64_t, struct zone> ZoneDetailsConfig = {};\n\nconstexpr const char *pidConfigurationInterface =\n \"xyz.openbmc_project.Configuration.Pid\";\nconstexpr const char *objectManagerInterface =\n \"org.freedesktop.DBus.ObjectManager\";\nconstexpr const char *pidZoneConfigurationInterface =\n \"xyz.openbmc_project.Configuration.Pid.Zone\";\nconstexpr const char *sensorInterface = \"xyz.openbmc_project.Sensor.Value\";\nconstexpr const char *pwmInterface = \"xyz.openbmc_project.Control.FanPwm\";\n\nnamespace dbus_configuration\n{\n\nbool findSensor(const std::unordered_map<std::string, std::string> &sensors,\n const std::string &search,\n std::pair<std::string, std::string> &sensor)\n{\n for (const auto &s : sensors)\n {\n if (s.first.find(search) != std::string::npos)\n {\n sensor = s;\n return true;\n }\n }\n return false;\n}\n\n\/\/ this function prints the configuration into a form similar to the cpp\n\/\/ generated code to help in verification, should be turned off during normal\n\/\/ use\nvoid debugPrint(void)\n{\n \/\/ print sensor config\n std::cout << \"sensor config:\\n\";\n std::cout << \"{\\n\";\n for (auto &pair : SensorConfig)\n {\n\n std::cout << \"\\t{\" << pair.first << \",\\n\\t\\t{\";\n std::cout << pair.second.type << \", \";\n std::cout << pair.second.readpath << \", \";\n std::cout << pair.second.writepath << \", \";\n std::cout << pair.second.min << \", \";\n std::cout << pair.second.max << \", \";\n std::cout << pair.second.timeout << \"},\\n\\t},\\n\";\n }\n std::cout << \"}\\n\\n\";\n std::cout << \"ZoneDetailsConfig\\n\";\n std::cout << \"{\\n\";\n for (auto &zone : ZoneDetailsConfig)\n {\n std::cout << \"\\t{\" << zone.first << \",\\n\";\n std::cout << \"\\t\\t{\" << zone.second.minthermalrpm << \", \";\n std::cout << zone.second.failsafepercent << \"}\\n\\t},\\n\";\n }\n std::cout << \"}\\n\\n\";\n std::cout << \"ZoneConfig\\n\";\n std::cout << \"{\\n\";\n for (auto &zone : ZoneConfig)\n {\n std::cout << \"\\t{\" << zone.first << \"\\n\";\n for (auto &pidconf : zone.second)\n {\n std::cout << \"\\t\\t{\" << pidconf.first << \",\\n\";\n std::cout << \"\\t\\t\\t{\" << pidconf.second.type << \",\\n\";\n std::cout << \"\\t\\t\\t{\";\n for (auto &input : pidconf.second.inputs)\n {\n std::cout << \"\\n\\t\\t\\t\" << input << \",\\n\";\n }\n std::cout << \"\\t\\t\\t}\\n\";\n std::cout << \"\\t\\t\\t\" << pidconf.second.setpoint << \",\\n\";\n std::cout << \"\\t\\t\\t{\" << pidconf.second.info.ts << \",\\n\";\n std::cout << \"\\t\\t\\t\" << pidconf.second.info.p_c << \",\\n\";\n std::cout << \"\\t\\t\\t\" << pidconf.second.info.i_c << \",\\n\";\n std::cout << \"\\t\\t\\t\" << pidconf.second.info.ff_off << \",\\n\";\n std::cout << \"\\t\\t\\t\" << pidconf.second.info.ff_gain << \",\\n\";\n std::cout << \"\\t\\t\\t{\" << pidconf.second.info.i_lim.min << \",\"\n << pidconf.second.info.i_lim.max << \"},\\n\";\n std::cout << \"\\t\\t\\t{\" << pidconf.second.info.out_lim.min << \",\"\n << pidconf.second.info.out_lim.max << \"},\\n\";\n std::cout << \"\\t\\t\\t\" << pidconf.second.info.slew_neg << \",\\n\";\n std::cout << \"\\t\\t\\t\" << pidconf.second.info.slew_pos << \",\\n\";\n std::cout << \"\\t\\t\\t}\\n\\t\\t}\\n\";\n }\n std::cout << \"\\t},\\n\";\n }\n std::cout << \"}\\n\\n\";\n}\n\nvoid init(sdbusplus::bus::bus &bus)\n{\n using ManagedObjectType = std::unordered_map<\n sdbusplus::message::object_path,\n std::unordered_map<\n std::string,\n std::unordered_map<std::string,\n sdbusplus::message::variant<\n uint64_t, int64_t, double, std::string,\n std::vector<std::string>>>>>;\n auto mapper =\n bus.new_method_call(\"xyz.openbmc_project.ObjectMapper\",\n \"\/xyz\/openbmc_project\/object_mapper\",\n \"xyz.openbmc_project.ObjectMapper\", \"GetSubTree\");\n mapper.append(\"\", 0,\n std::array<const char *, 5>{objectManagerInterface,\n pidConfigurationInterface,\n pidZoneConfigurationInterface,\n sensorInterface, pwmInterface});\n auto resp = bus.call(mapper);\n if (resp.is_method_error())\n {\n throw std::runtime_error(\"ObjectMapper Call Failure\");\n }\n std::unordered_map<\n std::string, std::unordered_map<std::string, std::vector<std::string>>>\n respData;\n\n resp.read(respData);\n if (respData.empty())\n {\n throw std::runtime_error(\"No configuration data available from Mapper\");\n }\n \/\/ create a map of pair of <has pid configuration, ObjectManager path>\n std::unordered_map<std::string, std::pair<bool, std::string>> owners;\n \/\/ and a map of <path, interface> for sensors\n std::unordered_map<std::string, std::string> sensors;\n for (const auto &objectPair : respData)\n {\n for (const auto &ownerPair : objectPair.second)\n {\n auto &owner = owners[ownerPair.first];\n for (const std::string &interface : ownerPair.second)\n {\n\n if (interface == objectManagerInterface)\n {\n owner.second = objectPair.first;\n }\n if (interface == pidConfigurationInterface ||\n interface == pidZoneConfigurationInterface)\n {\n owner.first = true;\n }\n if (interface == sensorInterface || interface == pwmInterface)\n {\n \/\/ we're not interested in pwm sensors, just pwm control\n if (interface == sensorInterface &&\n objectPair.first.find(\"pwm\") != std::string::npos)\n {\n continue;\n }\n sensors[objectPair.first] = interface;\n }\n }\n }\n }\n ManagedObjectType configurations;\n for (const auto &owner : owners)\n {\n \/\/ skip if no pid configuration (means probably a sensor)\n if (!owner.second.first)\n {\n continue;\n }\n auto endpoint = bus.new_method_call(\n owner.first.c_str(), owner.second.second.c_str(),\n \"org.freedesktop.DBus.ObjectManager\", \"GetManagedObjects\");\n auto responce = bus.call(endpoint);\n if (responce.is_method_error())\n {\n throw std::runtime_error(\"Error getting managed objects from \" +\n owner.first);\n }\n ManagedObjectType configuration;\n responce.read(configuration);\n for (auto &pathPair : configuration)\n {\n if (pathPair.second.find(pidConfigurationInterface) !=\n pathPair.second.end() ||\n pathPair.second.find(pidZoneConfigurationInterface) !=\n pathPair.second.end())\n {\n configurations.emplace(pathPair);\n }\n }\n }\n for (const auto &configuration : configurations)\n {\n auto findZone =\n configuration.second.find(pidZoneConfigurationInterface);\n if (findZone != configuration.second.end())\n {\n const auto &zone = findZone->second;\n auto &details =\n ZoneDetailsConfig[sdbusplus::message::variant_ns::get<uint64_t>(\n zone.at(\"Index\"))];\n details.minthermalrpm = mapbox::util::apply_visitor(\n VariantToFloatVisitor(), zone.at(\"MinThermalRpm\"));\n details.failsafepercent = mapbox::util::apply_visitor(\n VariantToFloatVisitor(), zone.at(\"FailSafePercent\"));\n }\n auto findBase = configuration.second.find(pidConfigurationInterface);\n if (findBase == configuration.second.end())\n {\n continue;\n }\n \/\/ if the base configuration is found, these are required\n const auto &base = configuration.second.at(pidConfigurationInterface);\n const auto &iLim = configuration.second.at(pidConfigurationInterface +\n std::string(\".ILimit\"));\n const auto &outLim = configuration.second.at(pidConfigurationInterface +\n std::string(\".OutLimit\"));\n PIDConf &conf =\n ZoneConfig[sdbusplus::message::variant_ns::get<uint64_t>(\n base.at(\"Index\"))];\n struct controller_info &info =\n conf[sdbusplus::message::variant_ns::get<std::string>(\n base.at(\"Name\"))];\n info.type =\n sdbusplus::message::variant_ns::get<std::string>(base.at(\"Class\"));\n \/\/ todo: auto generation yaml -> c script seems to discard this value\n \/\/ for fans, verify this is okay\n if (info.type == \"fan\")\n {\n info.setpoint = 0;\n }\n else\n {\n info.setpoint = mapbox::util::apply_visitor(VariantToFloatVisitor(),\n base.at(\"SetPoint\"));\n }\n info.info.ts = 1.0; \/\/ currently unused\n info.info.p_c = mapbox::util::apply_visitor(VariantToFloatVisitor(),\n base.at(\"PCoefficient\"));\n info.info.i_c = mapbox::util::apply_visitor(VariantToFloatVisitor(),\n base.at(\"ICoefficient\"));\n info.info.ff_off = mapbox::util::apply_visitor(\n VariantToFloatVisitor(), base.at(\"FFOffCoefficient\"));\n info.info.ff_gain = mapbox::util::apply_visitor(\n VariantToFloatVisitor(), base.at(\"FFGainCoefficient\"));\n auto value = mapbox::util::apply_visitor(VariantToFloatVisitor(),\n iLim.at(\"Max\"));\n info.info.i_lim.max = value;\n info.info.i_lim.min = mapbox::util::apply_visitor(\n VariantToFloatVisitor(), iLim.at(\"Min\"));\n info.info.out_lim.max = mapbox::util::apply_visitor(\n VariantToFloatVisitor(), outLim.at(\"Max\"));\n info.info.out_lim.min = mapbox::util::apply_visitor(\n VariantToFloatVisitor(), outLim.at(\"Min\"));\n info.info.slew_neg = mapbox::util::apply_visitor(\n VariantToFloatVisitor(), base.at(\"SlewNeg\"));\n info.info.slew_pos = mapbox::util::apply_visitor(\n VariantToFloatVisitor(), base.at(\"SlewPos\"));\n\n std::pair<std::string, std::string> sensorPathIfacePair;\n std::vector<std::string> sensorNames =\n sdbusplus::message::variant_ns::get<std::vector<std::string>>(\n base.at(\"Inputs\"));\n\n for (const std::string &sensorName : sensorNames)\n {\n std::string name = sensorName;\n \/\/ replace spaces with underscores to be legal on dbus\n std::replace(name.begin(), name.end(), ' ', '_');\n\n if (!findSensor(sensors, name, sensorPathIfacePair))\n {\n throw std::runtime_error(\n \"Could not map configuration to sensor \" + name);\n }\n if (sensorPathIfacePair.second == sensorInterface)\n {\n info.inputs.push_back(name);\n auto &config = SensorConfig[name];\n config.type = sdbusplus::message::variant_ns::get<std::string>(\n base.at(\"Class\"));\n config.readpath = sensorPathIfacePair.first;\n \/\/ todo: maybe un-hardcode this if we run into slower timeouts\n \/\/ with sensors\n if (config.type == \"temp\")\n {\n config.timeout = 500;\n }\n }\n if (sensorPathIfacePair.second == pwmInterface)\n {\n \/\/ copy so we can modify it\n for (std::string otherSensor : sensorNames)\n {\n if (otherSensor == sensorName)\n {\n continue;\n }\n std::replace(otherSensor.begin(), otherSensor.end(), ' ',\n '_');\n auto &config = SensorConfig[otherSensor];\n config.writepath = sensorPathIfacePair.first;\n \/\/ todo: un-hardcode this if there are fans with different\n \/\/ ranges\n config.max = 255;\n config.min = 0;\n }\n }\n }\n }\n if (DEBUG)\n {\n debugPrint();\n }\n}\n} \/\/ namespace dbus_configuration\n<commit_msg>dbusConfiguration: restart on configuration change<commit_after>\/*\n\/\/ Copyright (c) 2018 Intel Corporation\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n*\/\n\n#include <chrono>\n#include <conf.hpp>\n#include <dbus\/util.hpp>\n#include <functional>\n#include <iostream>\n#include <sdbusplus\/bus.hpp>\n#include <sdbusplus\/bus\/match.hpp>\n#include <set>\n#include <thread>\n#include <unordered_map>\n\nstatic constexpr bool DEBUG = false; \/\/ enable to print found configuration\n\nstd::map<std::string, struct sensor> SensorConfig = {};\nstd::map<int64_t, PIDConf> ZoneConfig = {};\nstd::map<int64_t, struct zone> ZoneDetailsConfig = {};\n\nconstexpr const char *pidConfigurationInterface =\n \"xyz.openbmc_project.Configuration.Pid\";\nconstexpr const char *objectManagerInterface =\n \"org.freedesktop.DBus.ObjectManager\";\nconstexpr const char *pidZoneConfigurationInterface =\n \"xyz.openbmc_project.Configuration.Pid.Zone\";\nconstexpr const char *sensorInterface = \"xyz.openbmc_project.Sensor.Value\";\nconstexpr const char *pwmInterface = \"xyz.openbmc_project.Control.FanPwm\";\n\nnamespace dbus_configuration\n{\n\nbool findSensor(const std::unordered_map<std::string, std::string> &sensors,\n const std::string &search,\n std::pair<std::string, std::string> &sensor)\n{\n for (const auto &s : sensors)\n {\n if (s.first.find(search) != std::string::npos)\n {\n sensor = s;\n return true;\n }\n }\n return false;\n}\n\n\/\/ this function prints the configuration into a form similar to the cpp\n\/\/ generated code to help in verification, should be turned off during normal\n\/\/ use\nvoid debugPrint(void)\n{\n \/\/ print sensor config\n std::cout << \"sensor config:\\n\";\n std::cout << \"{\\n\";\n for (auto &pair : SensorConfig)\n {\n\n std::cout << \"\\t{\" << pair.first << \",\\n\\t\\t{\";\n std::cout << pair.second.type << \", \";\n std::cout << pair.second.readpath << \", \";\n std::cout << pair.second.writepath << \", \";\n std::cout << pair.second.min << \", \";\n std::cout << pair.second.max << \", \";\n std::cout << pair.second.timeout << \"},\\n\\t},\\n\";\n }\n std::cout << \"}\\n\\n\";\n std::cout << \"ZoneDetailsConfig\\n\";\n std::cout << \"{\\n\";\n for (auto &zone : ZoneDetailsConfig)\n {\n std::cout << \"\\t{\" << zone.first << \",\\n\";\n std::cout << \"\\t\\t{\" << zone.second.minthermalrpm << \", \";\n std::cout << zone.second.failsafepercent << \"}\\n\\t},\\n\";\n }\n std::cout << \"}\\n\\n\";\n std::cout << \"ZoneConfig\\n\";\n std::cout << \"{\\n\";\n for (auto &zone : ZoneConfig)\n {\n std::cout << \"\\t{\" << zone.first << \"\\n\";\n for (auto &pidconf : zone.second)\n {\n std::cout << \"\\t\\t{\" << pidconf.first << \",\\n\";\n std::cout << \"\\t\\t\\t{\" << pidconf.second.type << \",\\n\";\n std::cout << \"\\t\\t\\t{\";\n for (auto &input : pidconf.second.inputs)\n {\n std::cout << \"\\n\\t\\t\\t\" << input << \",\\n\";\n }\n std::cout << \"\\t\\t\\t}\\n\";\n std::cout << \"\\t\\t\\t\" << pidconf.second.setpoint << \",\\n\";\n std::cout << \"\\t\\t\\t{\" << pidconf.second.info.ts << \",\\n\";\n std::cout << \"\\t\\t\\t\" << pidconf.second.info.p_c << \",\\n\";\n std::cout << \"\\t\\t\\t\" << pidconf.second.info.i_c << \",\\n\";\n std::cout << \"\\t\\t\\t\" << pidconf.second.info.ff_off << \",\\n\";\n std::cout << \"\\t\\t\\t\" << pidconf.second.info.ff_gain << \",\\n\";\n std::cout << \"\\t\\t\\t{\" << pidconf.second.info.i_lim.min << \",\"\n << pidconf.second.info.i_lim.max << \"},\\n\";\n std::cout << \"\\t\\t\\t{\" << pidconf.second.info.out_lim.min << \",\"\n << pidconf.second.info.out_lim.max << \"},\\n\";\n std::cout << \"\\t\\t\\t\" << pidconf.second.info.slew_neg << \",\\n\";\n std::cout << \"\\t\\t\\t\" << pidconf.second.info.slew_pos << \",\\n\";\n std::cout << \"\\t\\t\\t}\\n\\t\\t}\\n\";\n }\n std::cout << \"\\t},\\n\";\n }\n std::cout << \"}\\n\\n\";\n}\n\nvoid init(sdbusplus::bus::bus &bus)\n{\n using ManagedObjectType = std::unordered_map<\n sdbusplus::message::object_path,\n std::unordered_map<\n std::string,\n std::unordered_map<std::string,\n sdbusplus::message::variant<\n uint64_t, int64_t, double, std::string,\n std::vector<std::string>>>>>;\n\n \/\/ install watch for properties changed\n std::function<void(sdbusplus::message::message & message)> eventHandler =\n [](const sdbusplus::message::message &) {\n \/\/ do a brief sleep as we tend to get a bunch of these events at\n \/\/ once\n std::this_thread::sleep_for(std::chrono::seconds(5));\n std::cout << \"New configuration detected, restarting\\n.\";\n std::exit(EXIT_SUCCESS); \/\/ service file should make us restart\n };\n\n static sdbusplus::bus::match::match match(\n bus,\n \"type='signal',member='PropertiesChanged',arg0namespace='\" +\n std::string(pidConfigurationInterface) + \"'\",\n eventHandler);\n\n auto mapper =\n bus.new_method_call(\"xyz.openbmc_project.ObjectMapper\",\n \"\/xyz\/openbmc_project\/object_mapper\",\n \"xyz.openbmc_project.ObjectMapper\", \"GetSubTree\");\n mapper.append(\"\", 0,\n std::array<const char *, 5>{objectManagerInterface,\n pidConfigurationInterface,\n pidZoneConfigurationInterface,\n sensorInterface, pwmInterface});\n auto resp = bus.call(mapper);\n if (resp.is_method_error())\n {\n throw std::runtime_error(\"ObjectMapper Call Failure\");\n }\n std::unordered_map<\n std::string, std::unordered_map<std::string, std::vector<std::string>>>\n respData;\n\n resp.read(respData);\n if (respData.empty())\n {\n throw std::runtime_error(\"No configuration data available from Mapper\");\n }\n \/\/ create a map of pair of <has pid configuration, ObjectManager path>\n std::unordered_map<std::string, std::pair<bool, std::string>> owners;\n \/\/ and a map of <path, interface> for sensors\n std::unordered_map<std::string, std::string> sensors;\n for (const auto &objectPair : respData)\n {\n for (const auto &ownerPair : objectPair.second)\n {\n auto &owner = owners[ownerPair.first];\n for (const std::string &interface : ownerPair.second)\n {\n\n if (interface == objectManagerInterface)\n {\n owner.second = objectPair.first;\n }\n if (interface == pidConfigurationInterface ||\n interface == pidZoneConfigurationInterface)\n {\n owner.first = true;\n }\n if (interface == sensorInterface || interface == pwmInterface)\n {\n \/\/ we're not interested in pwm sensors, just pwm control\n if (interface == sensorInterface &&\n objectPair.first.find(\"pwm\") != std::string::npos)\n {\n continue;\n }\n sensors[objectPair.first] = interface;\n }\n }\n }\n }\n ManagedObjectType configurations;\n for (const auto &owner : owners)\n {\n \/\/ skip if no pid configuration (means probably a sensor)\n if (!owner.second.first)\n {\n continue;\n }\n auto endpoint = bus.new_method_call(\n owner.first.c_str(), owner.second.second.c_str(),\n \"org.freedesktop.DBus.ObjectManager\", \"GetManagedObjects\");\n auto responce = bus.call(endpoint);\n if (responce.is_method_error())\n {\n throw std::runtime_error(\"Error getting managed objects from \" +\n owner.first);\n }\n ManagedObjectType configuration;\n responce.read(configuration);\n for (auto &pathPair : configuration)\n {\n if (pathPair.second.find(pidConfigurationInterface) !=\n pathPair.second.end() ||\n pathPair.second.find(pidZoneConfigurationInterface) !=\n pathPair.second.end())\n {\n configurations.emplace(pathPair);\n }\n }\n }\n for (const auto &configuration : configurations)\n {\n auto findZone =\n configuration.second.find(pidZoneConfigurationInterface);\n if (findZone != configuration.second.end())\n {\n const auto &zone = findZone->second;\n auto &details =\n ZoneDetailsConfig[sdbusplus::message::variant_ns::get<uint64_t>(\n zone.at(\"Index\"))];\n details.minthermalrpm = mapbox::util::apply_visitor(\n VariantToFloatVisitor(), zone.at(\"MinThermalRpm\"));\n details.failsafepercent = mapbox::util::apply_visitor(\n VariantToFloatVisitor(), zone.at(\"FailSafePercent\"));\n }\n auto findBase = configuration.second.find(pidConfigurationInterface);\n if (findBase == configuration.second.end())\n {\n continue;\n }\n \/\/ if the base configuration is found, these are required\n const auto &base = configuration.second.at(pidConfigurationInterface);\n const auto &iLim = configuration.second.at(pidConfigurationInterface +\n std::string(\".ILimit\"));\n const auto &outLim = configuration.second.at(pidConfigurationInterface +\n std::string(\".OutLimit\"));\n PIDConf &conf =\n ZoneConfig[sdbusplus::message::variant_ns::get<uint64_t>(\n base.at(\"Index\"))];\n struct controller_info &info =\n conf[sdbusplus::message::variant_ns::get<std::string>(\n base.at(\"Name\"))];\n info.type =\n sdbusplus::message::variant_ns::get<std::string>(base.at(\"Class\"));\n \/\/ todo: auto generation yaml -> c script seems to discard this value\n \/\/ for fans, verify this is okay\n if (info.type == \"fan\")\n {\n info.setpoint = 0;\n }\n else\n {\n info.setpoint = mapbox::util::apply_visitor(VariantToFloatVisitor(),\n base.at(\"SetPoint\"));\n }\n info.info.ts = 1.0; \/\/ currently unused\n info.info.p_c = mapbox::util::apply_visitor(VariantToFloatVisitor(),\n base.at(\"PCoefficient\"));\n info.info.i_c = mapbox::util::apply_visitor(VariantToFloatVisitor(),\n base.at(\"ICoefficient\"));\n info.info.ff_off = mapbox::util::apply_visitor(\n VariantToFloatVisitor(), base.at(\"FFOffCoefficient\"));\n info.info.ff_gain = mapbox::util::apply_visitor(\n VariantToFloatVisitor(), base.at(\"FFGainCoefficient\"));\n auto value = mapbox::util::apply_visitor(VariantToFloatVisitor(),\n iLim.at(\"Max\"));\n info.info.i_lim.max = value;\n info.info.i_lim.min = mapbox::util::apply_visitor(\n VariantToFloatVisitor(), iLim.at(\"Min\"));\n info.info.out_lim.max = mapbox::util::apply_visitor(\n VariantToFloatVisitor(), outLim.at(\"Max\"));\n info.info.out_lim.min = mapbox::util::apply_visitor(\n VariantToFloatVisitor(), outLim.at(\"Min\"));\n info.info.slew_neg = mapbox::util::apply_visitor(\n VariantToFloatVisitor(), base.at(\"SlewNeg\"));\n info.info.slew_pos = mapbox::util::apply_visitor(\n VariantToFloatVisitor(), base.at(\"SlewPos\"));\n\n std::pair<std::string, std::string> sensorPathIfacePair;\n std::vector<std::string> sensorNames =\n sdbusplus::message::variant_ns::get<std::vector<std::string>>(\n base.at(\"Inputs\"));\n\n for (const std::string &sensorName : sensorNames)\n {\n std::string name = sensorName;\n \/\/ replace spaces with underscores to be legal on dbus\n std::replace(name.begin(), name.end(), ' ', '_');\n\n if (!findSensor(sensors, name, sensorPathIfacePair))\n {\n throw std::runtime_error(\n \"Could not map configuration to sensor \" + name);\n }\n if (sensorPathIfacePair.second == sensorInterface)\n {\n info.inputs.push_back(name);\n auto &config = SensorConfig[name];\n config.type = sdbusplus::message::variant_ns::get<std::string>(\n base.at(\"Class\"));\n config.readpath = sensorPathIfacePair.first;\n \/\/ todo: maybe un-hardcode this if we run into slower timeouts\n \/\/ with sensors\n if (config.type == \"temp\")\n {\n config.timeout = 500;\n }\n }\n if (sensorPathIfacePair.second == pwmInterface)\n {\n \/\/ copy so we can modify it\n for (std::string otherSensor : sensorNames)\n {\n if (otherSensor == sensorName)\n {\n continue;\n }\n std::replace(otherSensor.begin(), otherSensor.end(), ' ',\n '_');\n auto &config = SensorConfig[otherSensor];\n config.writepath = sensorPathIfacePair.first;\n \/\/ todo: un-hardcode this if there are fans with different\n \/\/ ranges\n config.max = 255;\n config.min = 0;\n }\n }\n }\n }\n if (DEBUG)\n {\n debugPrint();\n }\n}\n} \/\/ namespace dbus_configuration\n<|endoftext|>"} {"text":"<commit_before>\/**************************************************************************\n * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *\n * *\n * Author: The ALICE Off-line Project. *\n * Contributors are mentioned in the code where appropriate. *\n * *\n * Permission to use, copy, modify and distribute this software and its *\n * documentation strictly for non-commercial purposes is hereby granted *\n * without fee, provided that the above copyright notice appears in all *\n * copies and that both the copyright notice and this permission notice *\n * appear in the supporting documentation. The authors make no claims *\n * about the suitability of this software for any purpose. It is *\n * provided \"as is\" without express or implied warranty. *\n **************************************************************************\/\n\/\/...\n\/\/ Checks the quality assurance for ACORDE. \n\/\/ Default implementation\n\/\/ Authors:\n\/\/\tMario Rodriguez Cahuantzi <mrodrigu@mail.cern.ch> (FCFM-BUAP) \n\/\/\tLuciano Diaz Gonzalez <luciano.diaz@nucleares.unam.mx> (ICN-UNAM)\n\/\/\tArturo Fernandez <afernan@mail.cern.ch> (FCFM-BUAP)\n\/\/...\n\n\/\/ --- ROOT system ---\n#include <TClass.h>\n#include <TH1F.h> \n#include <TH1I.h> \n#include <TIterator.h> \n#include <TKey.h> \n#include <TFile.h> \n\n\/\/ --- Standard library ---\n\n\/\/ --- AliRoot header files ---\n#include \"AliLog.h\"\n#include \"AliQAv1.h\"\n#include \"AliQAChecker.h\"\n#include \"AliACORDEQAChecker.h\"\n#include \"AliCDBEntry.h\"\n#include \"AliQAManager.h\"\n\nClassImp(AliACORDEQAChecker)\n\n\/\/____________________________________________________________________________\nDouble_t * AliACORDEQAChecker::Check(AliQAv1::ALITASK_t \/*index*\/)\n{\n Double_t * rv = new Double_t[AliRecoParam::kNSpecies] ; \n for (Int_t specie = 0 ; specie < AliRecoParam::kNSpecies ; specie++) \n rv[specie] = 0.0 ; \n return rv ; \n}\n\n\/\/__________________________________________________________________\nDouble_t * AliACORDEQAChecker::Check(AliQAv1::ALITASK_t \/*index*\/, TObjArray ** list)\n{\n\n\t\/\/ We added one check to the ACORDE's QA histograms:\n\t\/\/ 1.- We check if they are empty\n\t\/\/ we check for the reference histogram to start the QAChecker. If not QAref object\n\t\/\/ is found, we check that the number of hits per channel is not so far from\n\t\/\/ the maximum number of hits.\n Double_t * test = new Double_t[AliRecoParam::kNSpecies] ; \n Int_t * count = new Int_t[AliRecoParam::kNSpecies] ; \n Double_t * acoTest = new Double_t[AliRecoParam::kNSpecies];\n Double_t acoHitsNorm = 0;\n Double_t * acoRefTest = new Double_t[AliRecoParam::kNSpecies];\n\n\t\/\/ Look at the QAref data for ACORDE\n\n\tchar * acoOCDBDir = Form(\"ACORDE\/%s\/%s\",AliQAv1::GetRefOCDBDirName(),AliQAv1::GetRefDataDirName());\n\tAliCDBEntry *acoQARefDir = AliQAManager::QAManager()->Get(acoOCDBDir);\n\n\n for (Int_t specie = 0 ; specie < AliRecoParam::kNSpecies ; specie++) {\n test[specie] = 0.0 ; \n count[specie] = 0 ; \n\tacoTest[specie] = 0.0;\n }\n \n for (Int_t specie = 0 ; specie < AliRecoParam::kNSpecies ; specie++) {\n if (list[specie]->GetEntries() == 0){ \n test[specie] = 1. ; \/\/ nothing to check\n\tacoTest[specie] = 1.;\n }\n else {\n TIter next(list[specie]) ; \n TH1 * hdata ;\n while ( (hdata = dynamic_cast<TH1 *>(next())) ) {\n if (hdata) { \n Double_t rv = 0.0 ; \n if(hdata->GetEntries()>0)rv=1; \n AliInfo(Form(\"%s -> %f\", hdata->GetName(), rv)) ; \n count[specie]++ ; \n test[specie] += rv ; \n\t\n\n\t\/\/ here we implement the second version for ACORDEQAChecker\n\t\/\/ by the moment we only compare that the hits in every ACORDE's channel\n\t\/\/ are close and > 0 \n\tfor (Int_t i=0;i<60;i++)\n\t{\n\t\tacoHitsNorm = hdata->GetBinContent(i)\/hdata->GetMaximum();\n\t\tif (acoQARefDir)\n\t\t{\n\t\/\/\t\tAliWarning(\"Using the QA Reference data for ACORDE !!!\");\n\t\t\ttest[specie] = CheckAcordeRefHits(list[specie],(TObjArray *)acoQARefDir->GetObject());\n\t\t\tif ((test[specie] = 0.86) || (acoHitsNorm>0.50)) \n\t\t\t{\n\t\t\t\tacoRefTest[specie]=0.78;\/\/printf(\"testMario: %f\\n\",acoRefTest[specie]);printf(\"histo:%f\\n\",hdata->GetMaximum());\n\t\t\t}\n\t\t}else{\n\t\/\/\tAliWarning(\"Using the inner ACORDE QA Checker !!!\");\n\t\tif ( (acoHitsNorm>0.40) && (acoHitsNorm<=1) ) acoTest[specie] = 0.75;\n\t\tif ( (acoHitsNorm>0.0020) && (acoHitsNorm<=0.40) ) acoTest[specie] = 0.251;\n\t\tif ( (acoHitsNorm>0.0) && (acoHitsNorm<=0.0020) ) acoTest[specie] = 0.0010;\n\t\tif ( (acoHitsNorm>-1.0) && (acoHitsNorm<=0.0) ) acoTest[specie] = -0.5;\n\t\t}\n\t}\n }\n else{\n AliError(\"Data type cannot be processed\") ;\n }\n }\n if (count[specie] != 0) { \n if (test[specie]==0) {\n \/\/ AliWarning(\"Histograms are there, but they are all empty: setting flag to kWARNING\");\n test[specie] = 0.5; \/\/upper limit value to set kWARNING flag for a task\n }\n else {\n\tif (acoQARefDir) test[specie] = acoRefTest[specie];\n\telse{\n\ttest[specie] = acoTest[specie];\/\/printf(\"testDyMa: %f\\n\",test[specie]);\n\t}\n }\n }\n }\n \/\/ AliInfo(Form(\"Test Result = %f\", test[specie])) ; \n }\n return test ; \n}\nDouble_t AliACORDEQAChecker::CheckAcordeRefHits(TObjArray *AcordeList, TObjArray * \/*AcordeRef *\/) const\n{\n\tDouble_t acoTest = 0;\n\tTIter next(AcordeList);\n\tTH1 *histo;\n\tfor (Int_t i=0;i<60;i++)\n\t{\n\t\twhile ( (histo = dynamic_cast<TH1 *>(next())) )\n\t\t{\t\n\t\t if (histo->GetMaximum() && ((histo->GetBinContent(i)\/histo->GetMaximum())<1.0) ) acoTest = 0.86;\n\/\/\t\tif( histo->KolmogorovTest((TH1F *)AcordeRef->At(0))<0.8) acoTest = 0.86;\n\t\t\t\/\/printf(\"href:%f\\n\",histo->GetMaximum());\n\t\t}\n\t}\t\n\treturn acoTest;\n}\n<commit_msg>Improvement of QAChecker<commit_after>\/**************************************************************************\n * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *\n * *\n * Author: The ALICE Off-line Project. *\n * Contributors are mentioned in the code where appropriate. *\n * *\n * Permission to use, copy, modify and distribute this software and its *\n * documentation strictly for non-commercial purposes is hereby granted *\n * without fee, provided that the above copyright notice appears in all *\n * copies and that both the copyright notice and this permission notice *\n * appear in the supporting documentation. The authors make no claims *\n * about the suitability of this software for any purpose. It is *\n * provided \"as is\" without express or implied warranty. *\n **************************************************************************\/\n\/\/...\n\/\/ Checks the quality assurance for ACORDE. \n\/\/ Default implementation\n\/\/ Authors:\n\/\/\tMario Rodriguez Cahuantzi <mrodrigu@mail.cern.ch> (FCFM-BUAP) \n\/\/\tLuciano Diaz Gonzalez <luciano.diaz@nucleares.unam.mx> (ICN-UNAM)\n\/\/\tArturo Fernandez <afernan@mail.cern.ch> (FCFM-BUAP)\n\/\/...\n\n\/\/ --- ROOT system ---\n#include <TClass.h>\n#include <TH1F.h> \n#include <TH1I.h> \n#include <TIterator.h> \n#include <TKey.h> \n#include <TFile.h> \n\n\/\/ --- Standard library ---\n\n\/\/ --- AliRoot header files ---\n#include \"AliLog.h\"\n#include \"AliQAv1.h\"\n#include \"AliQAChecker.h\"\n#include \"AliACORDEQAChecker.h\"\n#include \"AliCDBEntry.h\"\n#include \"AliQAManager.h\"\n\nClassImp(AliACORDEQAChecker)\n\n\/\/____________________________________________________________________________\nDouble_t * AliACORDEQAChecker::Check(AliQAv1::ALITASK_t \/*index*\/)\n{\n Double_t * rv = new Double_t[AliRecoParam::kNSpecies] ; \n for (Int_t specie = 0 ; specie < AliRecoParam::kNSpecies ; specie++) \n rv[specie] = 0.0 ; \n return rv ; \n}\n\n\/\/__________________________________________________________________\nDouble_t * AliACORDEQAChecker::Check(AliQAv1::ALITASK_t \/*index*\/, TObjArray ** list)\n{\n\n\t\/\/ We added one check to the ACORDE's QA histograms:\n\t\/\/ 1.- We check if they are empty\n\t\/\/ we check for the reference histogram to start the QAChecker. If not QAref object\n\t\/\/ is found, we check that the number of hits per channel is not so far from\n\t\/\/ the maximum number of hits.\n Double_t * test = new Double_t[AliRecoParam::kNSpecies] ; \n Int_t * count = new Int_t[AliRecoParam::kNSpecies] ; \n Double_t * acoTest = new Double_t[AliRecoParam::kNSpecies];\n \/\/ Double_t acoHitsNorm = 0;\n Double_t * acoRefTest = new Double_t[AliRecoParam::kNSpecies];\n\n\t\/\/ Look at the QAref data for ACORDE\n\n\tchar * acoOCDBDir = Form(\"ACORDE\/%s\/%s\",AliQAv1::GetRefOCDBDirName(),AliQAv1::GetRefDataDirName());\n\tAliCDBEntry *acoQARefDir = AliQAManager::QAManager()->Get(acoOCDBDir);\n\n\n for (Int_t specie = 0 ; specie < AliRecoParam::kNSpecies ; specie++) {\n test[specie] = 0.0 ; \n count[specie] = 0 ; \n\tacoTest[specie] = 0.0;\n }\n \n for (Int_t specie = 0 ; specie < AliRecoParam::kNSpecies ; specie++) {\n if (list[specie]->GetEntries() == 0){ \n test[specie] = 1. ; \/\/ nothing to check\n\tacoTest[specie] = 1.;\n }\n else {\n TIter next(list[specie]) ; \n TH1 * hdata ;\n while ( (hdata = dynamic_cast<TH1 *>(next())) ) {\n if (hdata) { \n Double_t rv = 0.0 ; \n if(hdata->GetEntries()>0)rv=1; \n AliInfo(Form(\"%s -> %f\", hdata->GetName(), rv)) ; \n count[specie]++ ; \n test[specie] += rv ; \n\n\t\/\/ here we implement the second version for ACORDEQAChecker\n\t\/\/ by the moment we only compare that the hits in every ACORDE's channel\n\t\/\/ are close and > 0 \n\t\tDouble_t acoHitsNorm = hdata->GetMaximum();\n\t\tif (acoQARefDir)\n\t\t{\n\t\/\/\t\tAliWarning(\"Using the QA Reference data for ACORDE !!!\");\n\t\t\ttest[specie] = CheckAcordeRefHits(list[specie],(TObjArray *)acoQARefDir->GetObject());\n\t\t\tif ((test[specie] = 0.86) || (acoHitsNorm>0.50)) \n\t\t\t{\n\t\t\t\tacoRefTest[specie]=0.78;\/\/printf(\"testMario: %f\\n\",acoRefTest[specie]);printf(\"histo:%f\\n\",hdata->GetMaximum());\n\t\t\t}\n\t\t}else{\n\t\/\/\tAliWarning(\"Using the inner ACORDE QA Checker !!!\");\n\t\tif ( (acoHitsNorm>0.40) && (acoHitsNorm<=1) ) acoTest[specie] = 0.75;\n\t\tif ( (acoHitsNorm>0.0020) && (acoHitsNorm<=0.40) ) acoTest[specie] = 0.251;\n\t\tif ( (acoHitsNorm>0.0) && (acoHitsNorm<=0.0020) ) acoTest[specie] = 0.0010;\n\t\tif ( (acoHitsNorm>-1.0) && (acoHitsNorm<=0.0) ) acoTest[specie] = -0.5;\n\t\t}\n }\n else{\n AliError(\"Data type cannot be processed\") ;\n }\n }\n if (count[specie] != 0) { \n if (test[specie]==0) {\n \/\/ AliWarning(\"Histograms are there, but they are all empty: setting flag to kWARNING\");\n test[specie] = 0.5; \/\/upper limit value to set kWARNING flag for a task\n }\n else {\n\tif (acoQARefDir) test[specie] = acoRefTest[specie];\n\telse{\n\ttest[specie] = acoTest[specie];\/\/printf(\"testDyMa: %f\\n\",test[specie]);\n\t}\n }\n }\n }\n \/\/ AliInfo(Form(\"Test Result = %f\", test[specie])) ; \n }\n return test ; \n}\nDouble_t AliACORDEQAChecker::CheckAcordeRefHits(TObjArray *AcordeList, TObjArray * \/*AcordeRef *\/) const\n{\n\tDouble_t acoTest = 0;\n\tTIter next(AcordeList);\n\tTH1 *histo;\n\tfor (Int_t i=0;i<60;i++)\n\t{\n\t\twhile ( (histo = dynamic_cast<TH1 *>(next())) )\n\t\t{\t\n\t\t if (histo->GetMaximum() && ((histo->GetBinContent(i)\/histo->GetMaximum())<1.0) ) acoTest = 0.86;\n\/\/\t\tif( histo->KolmogorovTest((TH1F *)AcordeRef->At(0))<0.8) acoTest = 0.86;\n\t\t\t\/\/printf(\"href:%f\\n\",histo->GetMaximum());\n\t\t}\n\t}\t\n\treturn acoTest;\n}\n<|endoftext|>"} {"text":"<commit_before>#include <sys\/types.h>\n#include <sys\/stat.h>\n#include <unistd.h>\n#include <cstring>\n#include <cstdlib>\n#include <cerrno>\n#include <signal.h>\n#include <boost\/thread.hpp>\n\nusing namespace boost;\n\n\/**\n * This file is used as a template to test the different ApplicationPool implementations.\n * It is #included in StandardApplicationPoolTest.cpp and ApplicationServer_ApplicationPoolTest.cpp\n *\/\n#ifdef USE_TEMPLATE\n\n\tstatic string createRequestHeaders(const char *uri = \"\/foo\/new\") {\n\t\tstring headers;\n\t\t#define ADD_HEADER(name, value) \\\n\t\t\theaders.append(name); \\\n\t\t\theaders.append(1, '\\0'); \\\n\t\t\theaders.append(value); \\\n\t\t\theaders.append(1, '\\0')\n\t\tADD_HEADER(\"HTTP_HOST\", \"www.test.com\");\n\t\tADD_HEADER(\"QUERY_STRING\", \"\");\n\t\tADD_HEADER(\"REQUEST_URI\", uri);\n\t\tADD_HEADER(\"REQUEST_METHOD\", \"GET\");\n\t\tADD_HEADER(\"REMOTE_ADDR\", \"localhost\");\n\t\treturn headers;\n\t}\n\t\n\tstatic string readAll(int fd) {\n\t\tstring result;\n\t\tchar buf[1024 * 32];\n\t\tssize_t ret;\n\t\twhile (true) {\n\t\t\tdo {\n\t\t\t\tret = read(fd, buf, sizeof(buf));\n\t\t\t} while (ret == -1 && errno == EINTR);\n\t\t\tif (ret == 0) {\n\t\t\t\tbreak;\n\t\t\t} else if (ret == -1) {\n\t\t\t\tthrow strerror(errno);\n\t\t\t} else {\n\t\t\t\tresult.append(buf, ret);\n\t\t\t}\n\t\t}\n\t\treturn result;\n\t}\n\n\tTEST_METHOD(1) {\n\t\t\/\/ Calling ApplicationPool.get() once should return a valid Session.\n\t\tApplication::SessionPtr session(pool->get(\"stub\/railsapp\"));\n\t\tsession->sendHeaders(createRequestHeaders());\n\t\tsession->closeWriter();\n\t\t\n\t\tint reader = session->getReader();\n\t\tstring result(readAll(reader));\n\t\tsession->closeReader();\n\t\tensure(result.find(\"hello world\") != string::npos);\n\t}\n\t\n\tTEST_METHOD(2) {\n\t\t\/\/ Verify that the pool spawns a new app, and that\n\t\t\/\/ after the session is closed, the app is kept around.\n\t\tApplication::SessionPtr session(pool->get(\"stub\/railsapp\"));\n\t\tensure_equals(\"Before the session was closed, the app was busy\", pool->getActive(), 1u);\n\t\tensure_equals(\"Before the session was closed, the app was in the pool\", pool->getCount(), 1u);\n\t\tsession.reset();\n\t\tensure_equals(\"After the session is closed, the app is no longer busy\", pool->getActive(), 0u);\n\t\tensure_equals(\"After the session is closed, the app is kept around\", pool->getCount(), 1u);\n\t}\n\t\n\tTEST_METHOD(4) {\n\t\t\/\/ If we call get() with an application root, then we close the session,\n\t\t\/\/ and then we call get() again with the same application root,\n\t\t\/\/ then the pool should not have spawned more than 1 app in total.\n\t\tApplication::SessionPtr session(pool->get(\"stub\/railsapp\"));\n\t\tsession.reset();\n\t\tsession = pool->get(\"stub\/railsapp\");\n\t\tensure_equals(pool->getCount(), 1u);\n\t}\n\t\n\tTEST_METHOD(5) {\n\t\t\/\/ If we call get() with an application root, then we call get() again before closing\n\t\t\/\/ the session, then the pool should have spawned 2 apps in total.\n\t\tApplication::SessionPtr session(pool->get(\"stub\/railsapp\"));\n\t\tApplication::SessionPtr session2(pool->get(\"stub\/railsapp\"));\n\t\tensure_equals(pool->getCount(), 2u);\n\t}\n\t\n\tTEST_METHOD(6) {\n\t\t\/\/ If we call get() twice with different application roots,\n\t\t\/\/ then the pool should spawn two different apps.\n\t\tApplication::SessionPtr session(pool->get(\"stub\/railsapp\"));\n\t\tApplication::SessionPtr session2(pool->get(\"stub\/railsapp2\"));\n\t\tensure_equals(\"Before the sessions were closed, both apps were busy\", pool->getActive(), 2u);\n\t\tensure_equals(\"Before the sessions were closed, both apps were in the pool\", pool->getCount(), 2u);\n\t\t\n\t\tsession->sendHeaders(createRequestHeaders());\n\t\tstring result(readAll(session->getReader()));\n\t\tensure(\"Session 1 belongs to the correct app\", result.find(\"hello world\"));\n\t\tsession.reset();\n\t\t\n\t\tsession2->sendHeaders(createRequestHeaders());\n\t\tresult = readAll(session2->getReader());\n\t\tensure(\"Session 2 belongs to the correct app\", result.find(\"this is railsapp2\"));\n\t\tsession2.reset();\n\t}\n\t\n\tTEST_METHOD(7) {\n\t\t\/\/ If we call get() twice with different application roots,\n\t\t\/\/ and we close both sessions, then both 2 apps should still\n\t\t\/\/ be in the pool.\n\t\tApplication::SessionPtr session(pool->get(\"stub\/railsapp\"));\n\t\tApplication::SessionPtr session2(pool->get(\"stub\/railsapp2\"));\n\t\tsession.reset();\n\t\tsession2.reset();\n\t\tensure_equals(pool->getActive(), 0u);\n\t\tensure_equals(pool->getCount(), 2u);\n\t}\n\t\n\tTEST_METHOD(8) {\n\t\t\/\/ If we call get() even though the pool is already full\n\t\t\/\/ (active == max), and the application root is already\n\t\t\/\/ in the pool, then the pool should have tried to open\n\t\t\/\/ a session in an already active app.\n\t\tpool->setMax(1);\n\t\tApplication::SessionPtr session1(pool->get(\"stub\/railsapp\"));\n\t\tApplication::SessionPtr session2(pool->get(\"stub\/railsapp\"));\n\t\tensure_equals(\"An attempt to open a session on an already busy app was made\", pool->getActive(), 2u);\n\t\tensure_equals(\"No new app has been spawned\", pool->getCount(), 1u);\n\t}\n\t\n\tTEST_METHOD(9) {\n\t\t\/\/ If ApplicationPool spawns a new instance,\n\t\t\/\/ and we kill it, then the next get() with the\n\t\t\/\/ same application root should throw an exception.\n\t\t\/\/ But the get() thereafter should not:\n\t\t\/\/ ApplicationPool should have spawned a new instance\n\t\t\/\/ after detecting that the original one died.\n\t\tApplication::SessionPtr session(pool->get(\"stub\/railsapp\"));\n\t\tkill(session->getPid(), SIGTERM);\n\t\tsession.reset();\n\t\ttry {\n\t\t\tsession = pool->get(\"stub\/railsapp\");\n\t\t\tfail(\"ApplicationPool::get() is supposed to \"\n\t\t\t\t\"throw an exception because we killed \"\n\t\t\t\t\"the app instance.\");\n\t\t} catch (const exception &e) {\n\t\t\tsession = pool->get(\"stub\/railsapp\");\n\t\t\t\/\/ Should not throw.\n\t\t}\n\t}\n\t\n\tstruct TestThread1 {\n\t\tApplicationPoolPtr pool;\n\t\tApplication::SessionPtr &m_session;\n\t\tbool &m_done;\n\t\t\n\t\tTestThread1(const ApplicationPoolPtr &pool,\n\t\t\tApplication::SessionPtr &session,\n\t\t\tbool &done)\n\t\t: m_session(session), m_done(done) {\n\t\t\tthis->pool = pool;\n\t\t\tdone = false;\n\t\t}\n\t\t\n\t\tvoid operator()() {\n\t\t\tm_session = pool->get(\"stub\/minimal-railsapp\");\n\t\t\tm_done = true;\n\t\t}\n\t};\n\n\tTEST_METHOD(10) {\n\t\t\/\/ If we call get() even though the pool is already full\n\t\t\/\/ (active == max), and the application root is *not* already\n\t\t\/\/ in the pool, then the pool will wait until enough sessions\n\t\t\/\/ have been closed.\n\t\tpool->setMax(2);\n\t\tApplication::SessionPtr session1(pool->get(\"stub\/railsapp\"));\n\t\tApplication::SessionPtr session2(pool->get(\"stub\/railsapp\"));\n\t\tApplication::SessionPtr session3;\n\t\tbool done;\n\t\t\n\t\tthread *thr = new thread(TestThread1(pool2, session3, done));\n\t\tusleep(500000);\n\t\tensure(\"ApplicationPool is waiting\", !done);\n\t\tensure_equals(pool->getActive(), 2u);\n\t\tensure_equals(pool->getCount(), 2u);\n\t\t\n\t\tsession1.reset();\n\t\t\n\t\t\/\/ Wait at most 10 seconds.\n\t\ttime_t begin = time(NULL);\n\t\twhile (!done && time(NULL) - begin < 10) {\n\t\t\tusleep(100000);\n\t\t}\n\t\t\n\t\tensure(\"Session 3 is openend\", done);\n\t\tensure_equals(pool->getActive(), 2u);\n\t\tensure_equals(pool->getCount(), 2u);\n\t\t\n\t\tthr->join();\n\t\tdelete thr;\n\t}\n\t\n\tTEST_METHOD(12) {\n\t\t\/\/ If we call get(), and:\n\t\t\/\/ * the pool is already full, but there are inactive apps\n\t\t\/\/ (active < count && count == max)\n\t\t\/\/ and\n\t\t\/\/ * the application root is *not* already in the pool\n\t\t\/\/ then the an inactive app should be killed in order to\n\t\t\/\/ satisfy this get() command.\n\t\tpool->setMax(2);\n\t\tApplication::SessionPtr session1(pool->get(\"stub\/railsapp\"));\n\t\tApplication::SessionPtr session2(pool->get(\"stub\/railsapp\"));\n\t\tsession1.reset();\n\t\tsession2.reset();\n\t\t\n\t\tensure_equals(pool->getActive(), 0u);\n\t\tensure_equals(pool->getCount(), 2u);\n\t\tsession1 = pool2->get(\"stub\/railsapp2\");\n\t\tensure_equals(pool->getActive(), 1u);\n\t\tensure_equals(pool->getCount(), 2u);\n\t}\n\t\n\tTEST_METHOD(13) {\n\t\t\/\/ Test whether Session is still usable after the Application has been destroyed.\n\t\tApplication::SessionPtr session(pool->get(\"stub\/railsapp\"));\n\t\tpool->clear();\n\t\tpool.reset();\n\t\tpool2.reset();\n\t\t\n\t\tsession->sendHeaders(createRequestHeaders());\n\t\tsession->closeWriter();\n\t\t\n\t\tint reader = session->getReader();\n\t\tstring result(readAll(reader));\n\t\tsession->closeReader();\n\t\tensure(result.find(\"hello world\") != string::npos);\n\t}\n\t\n\tTEST_METHOD(14) {\n\t\t\/\/ If tmp\/restart.txt is present, then the applications under app_root\n\t\t\/\/ should be restarted.\n\t\tstruct stat buf;\n\t\tApplication::SessionPtr session1 = pool->get(\"stub\/railsapp\");\n\t\tApplication::SessionPtr session2 = pool2->get(\"stub\/railsapp\");\n\t\tsession1.reset();\n\t\tsession2.reset();\n\t\t\n\t\tsystem(\"touch stub\/railsapp\/tmp\/restart.txt\");\n\t\tpool->get(\"stub\/railsapp\");\n\t\t\n\t\tensure_equals(\"No apps are active\", pool->getActive(), 0u);\n\t\tensure_equals(\"Both apps are killed, and a new one was spawned\",\n\t\t\tpool->getCount(), 1u);\n\t\tensure(\"Restart file has been deleted\",\n\t\t\tstat(\"stub\/railsapp\/tmp\/restart.txt\", &buf) == -1\n\t\t\t&& errno == ENOENT);\n\t}\n\t\n\tTEST_METHOD(15) {\n\t\t\/\/ If tmp\/restart.txt is present, but cannot be deleted, then\n\t\t\/\/ the applications under app_root should still be restarted.\n\t\t\/\/ However, a subsequent get() should not result in a restart.\n\t\tpid_t old_pid, pid;\n\t\tstruct stat buf;\n\t\tApplication::SessionPtr session1 = pool->get(\"stub\/railsapp\");\n\t\tApplication::SessionPtr session2 = pool2->get(\"stub\/railsapp\");\n\t\tsession1.reset();\n\t\tsession2.reset();\n\t\t\n\t\tsetenv(\"nextRestartTxtDeletionShouldFail\", \"1\", 1);\n\t\tsystem(\"touch stub\/railsapp\/tmp\/restart.txt\");\n\t\t\n\t\told_pid = pool->get(\"stub\/railsapp\")->getPid();\n\t\tensure(\"Restart file has not been deleted\",\n\t\t\tstat(\"stub\/railsapp\/tmp\/restart.txt\", &buf) == 0);\n\t\t\n\t\tsetenv(\"nextRestartTxtDeletionShouldFail\", \"1\", 1);\n\t\tpid = pool->get(\"stub\/railsapp\")->getPid();\n\t\tensure_equals(\"The app was not restarted\", pid, old_pid);\n\t\t\n\t\tunlink(\"stub\/railsapp\/tmp\/restart.txt\");\n\t}\n\t\n\tTEST_METHOD(16) {\n\t\t\/\/ If tmp\/restart.txt is present, but cannot be deleted, then\n\t\t\/\/ the applications under app_root should still be restarted.\n\t\t\/\/ A subsequent get() should only restart if we've changed\n\t\t\/\/ restart.txt's mtime.\n\t\tpid_t old_pid;\n\t\tApplication::SessionPtr session1 = pool->get(\"stub\/railsapp\");\n\t\tApplication::SessionPtr session2 = pool2->get(\"stub\/railsapp\");\n\t\tsession1.reset();\n\t\tsession2.reset();\n\t\t\n\t\tsetenv(\"nextRestartTxtDeletionShouldFail\", \"1\", 1);\n\t\tsystem(\"touch stub\/railsapp\/tmp\/restart.txt\");\n\t\told_pid = pool->get(\"stub\/railsapp\")->getPid();\n\t\tensure_equals(pool->getActive(), 0u);\n\t\tensure_equals(pool->getCount(), 1u);\n\n\t\tsleep(1); \/\/ Allow the next mtime to be different.\n\t\tsystem(\"touch stub\/railsapp\/tmp\/restart.txt\");\n\t\tensure(\"The app is restarted, and the last app instance was not reused\",\n\t\t\tpool2->get(\"stub\/railsapp\")->getPid() != old_pid);\n\t\t\n\t\tunlink(\"stub\/railsapp\/tmp\/restart.txt\");\n\t}\n\t\n\tTEST_METHOD(17) {\n\t\t\/\/ Test whether restarting really results in code reload.\n\t\tsystem(\"cp -f stub\/railsapp\/app\/controllers\/bar_controller_1.rb \"\n\t\t\t\"stub\/railsapp\/app\/controllers\/bar_controller.rb\");\n\t\tApplication::SessionPtr session = pool->get(\"stub\/railsapp\");\n\t\tsession->sendHeaders(createRequestHeaders(\"\/bar\"));\n\t\tstring result = readAll(session->getReader());\n\t\tensure(result.find(\"bar 1!\"));\n\t\tsession.reset();\n\t\t\n\t\tsystem(\"cp -f stub\/railsapp\/app\/controllers\/bar_controller_2.rb \"\n\t\t\t\"stub\/railsapp\/app\/controllers\/bar_controller.rb\");\n\t\tsystem(\"touch stub\/railsapp\/tmp\/restart.txt\");\n\t\tsession = pool->get(\"stub\/railsapp\");\n\t\tsession->sendHeaders(createRequestHeaders(\"\/bar\"));\n\t\tresult = readAll(session->getReader());\n\t\tensure(\"App code has been reloaded\", result.find(\"bar 2!\"));\n\t\tunlink(\"stub\/railsapp\/app\/controllers\/bar_controller.rb\");\n\t}\n\t\n\tTEST_METHOD(18) {\n\t\t\/\/ The cleaner thread should clean idle applications without crashing.\n\t\tpool->setMaxIdleTime(1);\n\t\tpool->get(\"stub\/minimal-railsapp\");\n\t\t\n\t\ttime_t begin = time(NULL);\n\t\twhile (pool->getCount() == 1u && time(NULL) - begin < 10) {\n\t\t\tusleep(100000);\n\t\t}\n\t\tensure_equals(\"App should have been cleaned up\", pool->getCount(), 0u);\n\t}\n\n#endif \/* USE_TEMPLATE *\/\n<commit_msg>Fix a few bugs in ApplicationPoolTest<commit_after>#include <sys\/types.h>\n#include <sys\/stat.h>\n#include <unistd.h>\n#include <cstring>\n#include <cstdlib>\n#include <cerrno>\n#include <signal.h>\n#include <boost\/thread.hpp>\n\nusing namespace boost;\n\n\/**\n * This file is used as a template to test the different ApplicationPool implementations.\n * It is #included in StandardApplicationPoolTest.cpp and ApplicationServer_ApplicationPoolTest.cpp\n *\/\n#ifdef USE_TEMPLATE\n\n\tstatic string createRequestHeaders(const char *uri = \"\/foo\/new\") {\n\t\tstring headers;\n\t\t#define ADD_HEADER(name, value) \\\n\t\t\theaders.append(name); \\\n\t\t\theaders.append(1, '\\0'); \\\n\t\t\theaders.append(value); \\\n\t\t\theaders.append(1, '\\0')\n\t\tADD_HEADER(\"HTTP_HOST\", \"www.test.com\");\n\t\tADD_HEADER(\"QUERY_STRING\", \"\");\n\t\tADD_HEADER(\"REQUEST_URI\", uri);\n\t\tADD_HEADER(\"REQUEST_METHOD\", \"GET\");\n\t\tADD_HEADER(\"REMOTE_ADDR\", \"localhost\");\n\t\treturn headers;\n\t}\n\t\n\tstatic string readAll(int fd) {\n\t\tstring result;\n\t\tchar buf[1024 * 32];\n\t\tssize_t ret;\n\t\twhile (true) {\n\t\t\tdo {\n\t\t\t\tret = read(fd, buf, sizeof(buf));\n\t\t\t} while (ret == -1 && errno == EINTR);\n\t\t\tif (ret == 0) {\n\t\t\t\tbreak;\n\t\t\t} else if (ret == -1) {\n\t\t\t\tthrow strerror(errno);\n\t\t\t} else {\n\t\t\t\tresult.append(buf, ret);\n\t\t\t}\n\t\t}\n\t\treturn result;\n\t}\n\n\tTEST_METHOD(1) {\n\t\t\/\/ Calling ApplicationPool.get() once should return a valid Session.\n\t\tApplication::SessionPtr session(pool->get(\"stub\/railsapp\"));\n\t\tsession->sendHeaders(createRequestHeaders());\n\t\tsession->closeWriter();\n\t\t\n\t\tint reader = session->getReader();\n\t\tstring result(readAll(reader));\n\t\tsession->closeReader();\n\t\tensure(result.find(\"hello world\") != string::npos);\n\t}\n\t\n\tTEST_METHOD(2) {\n\t\t\/\/ Verify that the pool spawns a new app, and that\n\t\t\/\/ after the session is closed, the app is kept around.\n\t\tApplication::SessionPtr session(pool->get(\"stub\/railsapp\"));\n\t\tensure_equals(\"Before the session was closed, the app was busy\", pool->getActive(), 1u);\n\t\tensure_equals(\"Before the session was closed, the app was in the pool\", pool->getCount(), 1u);\n\t\tsession.reset();\n\t\tensure_equals(\"After the session is closed, the app is no longer busy\", pool->getActive(), 0u);\n\t\tensure_equals(\"After the session is closed, the app is kept around\", pool->getCount(), 1u);\n\t}\n\t\n\tTEST_METHOD(3) {\n\t\t\/\/ If we call get() with an application root, then we close the session,\n\t\t\/\/ and then we call get() again with the same application root,\n\t\t\/\/ then the pool should not have spawned more than 1 app in total.\n\t\tApplication::SessionPtr session(pool->get(\"stub\/railsapp\"));\n\t\tsession.reset();\n\t\tsession = pool->get(\"stub\/railsapp\");\n\t\tensure_equals(pool->getCount(), 1u);\n\t}\n\t\n\tTEST_METHOD(4) {\n\t\t\/\/ If we call get() with an application root, then we call get() again before closing\n\t\t\/\/ the session, then the pool should have spawned 2 apps in total.\n\t\tApplication::SessionPtr session(pool->get(\"stub\/railsapp\"));\n\t\tApplication::SessionPtr session2(pool2->get(\"stub\/railsapp\"));\n\t\tensure_equals(pool->getCount(), 2u);\n\t}\n\t\n\tTEST_METHOD(5) {\n\t\t\/\/ If we call get() twice with different application roots,\n\t\t\/\/ then the pool should spawn two different apps.\n\t\tApplication::SessionPtr session(pool->get(\"stub\/railsapp\"));\n\t\tApplication::SessionPtr session2(pool2->get(\"stub\/railsapp2\"));\n\t\tensure_equals(\"Before the sessions were closed, both apps were busy\", pool->getActive(), 2u);\n\t\tensure_equals(\"Before the sessions were closed, both apps were in the pool\", pool->getCount(), 2u);\n\t\t\n\t\tsession->sendHeaders(createRequestHeaders());\n\t\tstring result(readAll(session->getReader()));\n\t\tensure(\"Session 1 belongs to the correct app\", result.find(\"hello world\"));\n\t\tsession.reset();\n\t\t\n\t\tsession2->sendHeaders(createRequestHeaders());\n\t\tresult = readAll(session2->getReader());\n\t\tensure(\"Session 2 belongs to the correct app\", result.find(\"this is railsapp2\"));\n\t\tsession2.reset();\n\t}\n\t\n\tTEST_METHOD(6) {\n\t\t\/\/ If we call get() twice with different application roots,\n\t\t\/\/ and we close both sessions, then both 2 apps should still\n\t\t\/\/ be in the pool.\n\t\tApplication::SessionPtr session(pool->get(\"stub\/railsapp\"));\n\t\tApplication::SessionPtr session2(pool->get(\"stub\/railsapp2\"));\n\t\tsession.reset();\n\t\tsession2.reset();\n\t\tensure_equals(pool->getActive(), 0u);\n\t\tensure_equals(pool->getCount(), 2u);\n\t}\n\t\n\tTEST_METHOD(7) {\n\t\t\/\/ If we call get() even though the pool is already full\n\t\t\/\/ (active == max), and the application root is already\n\t\t\/\/ in the pool, then the pool should have tried to open\n\t\t\/\/ a session in an already active app.\n\t\tpool->setMax(1);\n\t\tApplication::SessionPtr session1(pool->get(\"stub\/railsapp\"));\n\t\tApplication::SessionPtr session2(pool->get(\"stub\/railsapp\"));\n\t\tensure_equals(\"An attempt to open a session on an already busy app was made\", pool->getActive(), 2u);\n\t\tensure_equals(\"No new app has been spawned\", pool->getCount(), 1u);\n\t}\n\t\n\tTEST_METHOD(8) {\n\t\t\/\/ If ApplicationPool spawns a new instance,\n\t\t\/\/ and we kill it, then the next get() with the\n\t\t\/\/ same application root should throw an exception.\n\t\t\/\/ But the get() thereafter should not:\n\t\t\/\/ ApplicationPool should have spawned a new instance\n\t\t\/\/ after detecting that the original one died.\n\t\tApplication::SessionPtr session(pool->get(\"stub\/railsapp\"));\n\t\tkill(session->getPid(), SIGTERM);\n\t\tsession.reset();\n\t\ttry {\n\t\t\tsession = pool->get(\"stub\/railsapp\");\n\t\t\tfail(\"ApplicationPool::get() is supposed to \"\n\t\t\t\t\"throw an exception because we killed \"\n\t\t\t\t\"the app instance.\");\n\t\t} catch (const exception &e) {\n\t\t\tsession = pool->get(\"stub\/railsapp\");\n\t\t\t\/\/ Should not throw.\n\t\t}\n\t}\n\t\n\tstruct TestThread1 {\n\t\tApplicationPoolPtr pool;\n\t\tApplication::SessionPtr &m_session;\n\t\tbool &m_done;\n\t\t\n\t\tTestThread1(const ApplicationPoolPtr &pool,\n\t\t\tApplication::SessionPtr &session,\n\t\t\tbool &done)\n\t\t: m_session(session), m_done(done) {\n\t\t\tthis->pool = pool;\n\t\t\tdone = false;\n\t\t}\n\t\t\n\t\tvoid operator()() {\n\t\t\tm_session = pool->get(\"stub\/minimal-railsapp\");\n\t\t\tm_done = true;\n\t\t}\n\t};\n\n\tTEST_METHOD(9) {\n\t\t\/\/ If we call get() even though the pool is already full\n\t\t\/\/ (active == max), and the application root is *not* already\n\t\t\/\/ in the pool, then the pool will wait until enough sessions\n\t\t\/\/ have been closed.\n\t\tpool->setMax(2);\n\t\tApplication::SessionPtr session1(pool->get(\"stub\/railsapp\"));\n\t\tApplication::SessionPtr session2(pool2->get(\"stub\/railsapp\"));\n\t\tApplication::SessionPtr session3;\n\t\tbool done;\n\t\t\n\t\tthread *thr = new thread(TestThread1(pool2, session3, done));\n\t\tusleep(500000);\n\t\tensure(\"ApplicationPool is waiting\", !done);\n\t\tensure_equals(pool->getActive(), 2u);\n\t\tensure_equals(pool->getCount(), 2u);\n\t\t\n\t\tsession1.reset();\n\t\t\n\t\t\/\/ Wait at most 10 seconds.\n\t\ttime_t begin = time(NULL);\n\t\twhile (!done && time(NULL) - begin < 10) {\n\t\t\tusleep(100000);\n\t\t}\n\t\t\n\t\tensure(\"Session 3 is openend\", done);\n\t\tensure_equals(pool->getActive(), 2u);\n\t\tensure_equals(pool->getCount(), 2u);\n\t\t\n\t\tthr->join();\n\t\tdelete thr;\n\t}\n\t\n\tTEST_METHOD(10) {\n\t\t\/\/ If we call get(), and:\n\t\t\/\/ * the pool is already full, but there are inactive apps\n\t\t\/\/ (active < count && count == max)\n\t\t\/\/ and\n\t\t\/\/ * the application root is *not* already in the pool\n\t\t\/\/ then the an inactive app should be killed in order to\n\t\t\/\/ satisfy this get() command.\n\t\tpool->setMax(2);\n\t\tApplication::SessionPtr session1(pool->get(\"stub\/railsapp\"));\n\t\tApplication::SessionPtr session2(pool->get(\"stub\/railsapp\"));\n\t\tsession1.reset();\n\t\tsession2.reset();\n\t\t\n\t\tensure_equals(pool->getActive(), 0u);\n\t\tensure_equals(pool->getCount(), 2u);\n\t\tsession1 = pool2->get(\"stub\/railsapp2\");\n\t\tensure_equals(pool->getActive(), 1u);\n\t\tensure_equals(pool->getCount(), 2u);\n\t}\n\t\n\tTEST_METHOD(11) {\n\t\t\/\/ Test whether Session is still usable after the Application has been destroyed.\n\t\tApplication::SessionPtr session(pool->get(\"stub\/railsapp\"));\n\t\tpool->clear();\n\t\tpool.reset();\n\t\tpool2.reset();\n\t\t\n\t\tsession->sendHeaders(createRequestHeaders());\n\t\tsession->closeWriter();\n\t\t\n\t\tint reader = session->getReader();\n\t\tstring result(readAll(reader));\n\t\tsession->closeReader();\n\t\tensure(result.find(\"hello world\") != string::npos);\n\t}\n\t\n\tTEST_METHOD(12) {\n\t\t\/\/ If tmp\/restart.txt is present, then the applications under app_root\n\t\t\/\/ should be restarted.\n\t\tstruct stat buf;\n\t\tApplication::SessionPtr session1 = pool->get(\"stub\/railsapp\");\n\t\tApplication::SessionPtr session2 = pool2->get(\"stub\/railsapp\");\n\t\tsession1.reset();\n\t\tsession2.reset();\n\t\t\n\t\tsystem(\"touch stub\/railsapp\/tmp\/restart.txt\");\n\t\tpool->get(\"stub\/railsapp\");\n\t\t\n\t\tensure_equals(\"No apps are active\", pool->getActive(), 0u);\n\t\tensure_equals(\"Both apps are killed, and a new one was spawned\",\n\t\t\tpool->getCount(), 1u);\n\t\tensure(\"Restart file has been deleted\",\n\t\t\tstat(\"stub\/railsapp\/tmp\/restart.txt\", &buf) == -1\n\t\t\t&& errno == ENOENT);\n\t}\n\t\n\tTEST_METHOD(13) {\n\t\t\/\/ If tmp\/restart.txt is present, but cannot be deleted, then\n\t\t\/\/ the applications under app_root should still be restarted.\n\t\t\/\/ However, a subsequent get() should not result in a restart.\n\t\tpid_t old_pid, pid;\n\t\tstruct stat buf;\n\t\tApplication::SessionPtr session1 = pool->get(\"stub\/railsapp\");\n\t\tApplication::SessionPtr session2 = pool2->get(\"stub\/railsapp\");\n\t\tsession1.reset();\n\t\tsession2.reset();\n\t\t\n\t\tsetenv(\"nextRestartTxtDeletionShouldFail\", \"1\", 1);\n\t\tsystem(\"touch stub\/railsapp\/tmp\/restart.txt\");\n\t\t\n\t\told_pid = pool->get(\"stub\/railsapp\")->getPid();\n\t\tensure(\"Restart file has not been deleted\",\n\t\t\tstat(\"stub\/railsapp\/tmp\/restart.txt\", &buf) == 0);\n\t\t\n\t\tsetenv(\"nextRestartTxtDeletionShouldFail\", \"1\", 1);\n\t\tpid = pool->get(\"stub\/railsapp\")->getPid();\n\t\tensure_equals(\"The app was not restarted\", pid, old_pid);\n\t\t\n\t\tunlink(\"stub\/railsapp\/tmp\/restart.txt\");\n\t}\n\t\n\tTEST_METHOD(14) {\n\t\t\/\/ If tmp\/restart.txt is present, but cannot be deleted, then\n\t\t\/\/ the applications under app_root should still be restarted.\n\t\t\/\/ A subsequent get() should only restart if we've changed\n\t\t\/\/ restart.txt's mtime.\n\t\tpid_t old_pid;\n\t\tApplication::SessionPtr session1 = pool->get(\"stub\/railsapp\");\n\t\tApplication::SessionPtr session2 = pool2->get(\"stub\/railsapp\");\n\t\tsession1.reset();\n\t\tsession2.reset();\n\t\t\n\t\tsetenv(\"nextRestartTxtDeletionShouldFail\", \"1\", 1);\n\t\tsystem(\"touch stub\/railsapp\/tmp\/restart.txt\");\n\t\told_pid = pool->get(\"stub\/railsapp\")->getPid();\n\t\tensure_equals(pool->getActive(), 0u);\n\t\tensure_equals(pool->getCount(), 1u);\n\n\t\tsleep(1); \/\/ Allow the next mtime to be different.\n\t\tsystem(\"touch stub\/railsapp\/tmp\/restart.txt\");\n\t\tensure(\"The app is restarted, and the last app instance was not reused\",\n\t\t\tpool2->get(\"stub\/railsapp\")->getPid() != old_pid);\n\t\t\n\t\tunlink(\"stub\/railsapp\/tmp\/restart.txt\");\n\t}\n\t\n\tTEST_METHOD(15) {\n\t\t\/\/ Test whether restarting really results in code reload.\n\t\tsystem(\"cp -f stub\/railsapp\/app\/controllers\/bar_controller_1.rb \"\n\t\t\t\"stub\/railsapp\/app\/controllers\/bar_controller.rb\");\n\t\tApplication::SessionPtr session = pool->get(\"stub\/railsapp\");\n\t\tsession->sendHeaders(createRequestHeaders(\"\/bar\"));\n\t\tstring result = readAll(session->getReader());\n\t\tensure(result.find(\"bar 1!\"));\n\t\tsession.reset();\n\t\t\n\t\tsystem(\"cp -f stub\/railsapp\/app\/controllers\/bar_controller_2.rb \"\n\t\t\t\"stub\/railsapp\/app\/controllers\/bar_controller.rb\");\n\t\tsystem(\"touch stub\/railsapp\/tmp\/restart.txt\");\n\t\tsession = pool->get(\"stub\/railsapp\");\n\t\tsession->sendHeaders(createRequestHeaders(\"\/bar\"));\n\t\tresult = readAll(session->getReader());\n\t\tensure(\"App code has been reloaded\", result.find(\"bar 2!\"));\n\t\tunlink(\"stub\/railsapp\/app\/controllers\/bar_controller.rb\");\n\t}\n\t\n\tTEST_METHOD(16) {\n\t\t\/\/ The cleaner thread should clean idle applications without crashing.\n\t\tpool->setMaxIdleTime(1);\n\t\tpool->get(\"stub\/minimal-railsapp\");\n\t\t\n\t\ttime_t begin = time(NULL);\n\t\twhile (pool->getCount() == 1u && time(NULL) - begin < 10) {\n\t\t\tusleep(100000);\n\t\t}\n\t\tensure_equals(\"App should have been cleaned up\", pool->getCount(), 0u);\n\t}\n\n#endif \/* USE_TEMPLATE *\/\n<|endoftext|>"} {"text":"<commit_before>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Unit Test for Loki\n\/\/\n\/\/ Copyright Terje Sletteb and Pavel Vozenilek 2002.\n\/\/\n\/\/ Permission to use, copy, modify, and distribute this software for any\n\/\/ purpose is hereby granted without fee, provided that this copyright and\n\/\/ permissions notice appear in all copies and derivatives.\n\/\/\n\/\/ This software is provided \"as is\" without express or implied warranty.\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/ $Header$\n\n#ifdef __INTEL_COMPILER\n# pragma warning(disable: 111 193 304 383 444 488 981 1418)\n#elif defined(_MSC_VER) && !defined(__MWERKS__)\n# pragma warning(disable: 4018 4097 4100 4213 4290 4512 4514 4700 4702 4710 4786 4800)\n#endif\n\n\/\/#define LOKI_CLASS_LEVEL_THREADING\n#define LOKI_OBJECT_LEVEL_THREADING\n\n\/\/ Some platforms might have difficulty with this\n\/\/ Need to ifdef around those cases.\n\/\/ TODO SGB\n\n\n#include \"UnitTest.h\"\n\n\/\/ static variable defintion, do not remove\n\nTest::tests_type Test::tests;\n\n\/\/ Merely comment out any of the following headers to\n\/\/ prevent thier execution during the test.\n\/\/\n\/\/ A pluggable-factory-like method is used to \n\/\/ auto-register the test, so all that is needed\n\/\/ is the header inclusion to execute the correspond\n\/\/ unit test.\n\n#include \"SmallObjectTest.h\"\n#include \"SingletonTest.h\"\n\n#include \"ThreadsTest.h\"\n#include \"TypelistTest.h\"\n#include \"SequenceTest.h\"\n#include \"TypeManipTest.h\"\n#include \"TypeTraitsTest.h\"\n#include \"TypeTraitsTest2.h\"\n#include \"SmartPtrTest.h\"\n#include \"FactoryTest.h\"\n#include \"FactoryParmTest.h\"\n#include \"AbstractFactoryTest.h\"\n#include \"FunctorTest.h\"\n#include \"DataGeneratorsTest.h\"\n\/\/#include \"AssocVectorTest.h\"\n\nint main()\n{\n int result = Test::run(\"Loki Unit Test\");\n\n #if defined(__BORLANDC__) || defined(__GNUC__) || defined(_MSC_VER)\n \/\/ Stop console window from closing if run from IDE.\n system(\"pause\"); \n #endif\n\n return result;\n}\n\n\n\/*\n * Table is out of date (24.10.2005)\n *\n * AP - All Pass\n * FC - Fails to Compile\n * ? - Unknown\/Not Tested\/Not Recorded\n *\n * TypelistTest TypeManipTest TypeTraitsTest SmallObjectTest SingletonTest\n * gcc 2.95.3 ? ? ? ? ?\n * gcc 3.2 AP AP AP AP P (Only SingleThreaded)\n * MSVC 6.0 P AP FC FC AP\n * MSVC 7.0 AP Conversion FC AP P (Only SingleThreaded) ?\n * Intel 5.0 AP AP AP FC FC\n * Intel 6.0 AP AP AP FC P (Only SingleThreaded)\n * Intel 7.0 AP AP AP FC P (Only SingleThreaded)\n * BCC 5.5 ? ? ? ? ?\n * BCC 5.6 ? ? ? ? ?\n * CW 6.0 ? ? ? ? ?\n *\n * SmartPtrTest FactoryTest AbstractFactoryTest AssocVectorTest FunctorTest\n * gcc 2.95.3 ? ? ? ? ?\n * gcc 3.2 AP AP AP AP AP\n * MSVC 6.0 FC AP FC FC FC\n * MSVC 7.0 FC AP AP FC AP\n * Intel 5.0 FC FC FC FC FC\n * Intel 6.0 FC AP AP FC FC\n * Intel 7.0 FC AP AP FC FC\n * BCC 5.5 ? ? ? ? ?\n * CW 6.0 ? ? ? ? ?\n *\n * DataGeneratorsTest\n * gcc 2.95.3 ?\n * gcc 3.2 AP\n * MSVC 6.0 FC\n * MSVC 7.0 AP\n * Intel 5.0 FC\n * Intel 6.0 AP\n * Intel 7.0 AP\n * BCC 5.5 ?\n * BCC 5.6 ?\n * CW 6.0 ? \n\n *\/ \n\n\n\/\/ $Log$\n\/\/ Revision 1.11 2005\/10\/30 13:49:44 syntheticpp\n\/\/ make disabling the TYPELIST macros possible\n\/\/\n\/\/ Revision 1.10 2005\/10\/24 20:51:38 syntheticpp\n\/\/ Table is out of date\n\/\/\n\/\/ Revision 1.9 2005\/10\/24 20:35:12 syntheticpp\n\/\/ small changes for Threads; add compile test for Threads.h\n\/\/\n\/\/ Revision 1.8 2005\/10\/06 17:50:14 syntheticpp\n\/\/ adding template based list\/sequence implementation, should replace LOKI_TYPELIST_, update some files\n\/\/\n\/\/ Revision 1.7 2005\/09\/29 08:09:17 syntheticpp\n\/\/ update msvc build process\n\/\/\n\/\/ Revision 1.6 2005\/09\/26 07:33:05 syntheticpp\n\/\/ move macros into LOKI_ namespace\n\/\/\n\/\/ Revision 1.5 2005\/09\/24 15:49:40 syntheticpp\n\/\/ is it really binary?\n\/\/\n\/\/ Revision 1.4 2005\/09\/24 15:25:20 syntheticpp\n\/\/ ove RegressionTest\n\/\/\n\/\/ Revision 1.17 2005\/09\/15 17:51:48 syntheticpp\n\/\/ add new TypeTraits test from Kalle Rutanen\n\/\/\n\/\/ Revision 1.16 2005\/08\/10 18:13:13 syntheticpp\n\/\/ change default to single threading\n\/\/\n\/\/ Revision 1.15 2005\/07\/31 14:00:48 syntheticpp\n\/\/ make object level threading possible\n\/\/\n\/\/ Revision 1.14 2005\/07\/28 14:26:10 syntheticpp\n\/\/ add cvs Header\/Log\n\/\/\n<commit_msg>disable threading because the sdk (windows.h) is not detected automatically by the batch scripts<commit_after>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Unit Test for Loki\n\/\/\n\/\/ Copyright Terje Sletteb and Pavel Vozenilek 2002.\n\/\/\n\/\/ Permission to use, copy, modify, and distribute this software for any\n\/\/ purpose is hereby granted without fee, provided that this copyright and\n\/\/ permissions notice appear in all copies and derivatives.\n\/\/\n\/\/ This software is provided \"as is\" without express or implied warranty.\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/ $Header$\n\n#ifdef __INTEL_COMPILER\n# pragma warning(disable: 111 193 304 383 444 488 981 1418)\n#elif defined(_MSC_VER) && !defined(__MWERKS__)\n# pragma warning(disable: 4018 4097 4100 4213 4290 4512 4514 4700 4702 4710 4786 4800)\n#endif\n\n\/\/#define LOKI_CLASS_LEVEL_THREADING\n\/\/#define LOKI_OBJECT_LEVEL_THREADING\n\n\/\/ Some platforms might have difficulty with this\n\/\/ Need to ifdef around those cases.\n\/\/ TODO SGB\n\n\n#include \"UnitTest.h\"\n\n\/\/ static variable defintion, do not remove\n\nTest::tests_type Test::tests;\n\n\/\/ Merely comment out any of the following headers to\n\/\/ prevent thier execution during the test.\n\/\/\n\/\/ A pluggable-factory-like method is used to \n\/\/ auto-register the test, so all that is needed\n\/\/ is the header inclusion to execute the correspond\n\/\/ unit test.\n\n#include \"SmallObjectTest.h\"\n#include \"SingletonTest.h\"\n\n#include \"ThreadsTest.h\"\n#include \"TypelistTest.h\"\n#include \"SequenceTest.h\"\n#include \"TypeManipTest.h\"\n#include \"TypeTraitsTest.h\"\n#include \"TypeTraitsTest2.h\"\n#include \"SmartPtrTest.h\"\n#include \"FactoryTest.h\"\n#include \"FactoryParmTest.h\"\n#include \"AbstractFactoryTest.h\"\n#include \"FunctorTest.h\"\n#include \"DataGeneratorsTest.h\"\n#include \"AssocVectorTest.h\"\n\nint main()\n{\n int result = Test::run(\"Loki Unit Test\");\n\n #if defined(__BORLANDC__) || defined(__GNUC__) || defined(_MSC_VER)\n \/\/ Stop console window from closing if run from IDE.\n system(\"pause\"); \n #endif\n\n return result;\n}\n\n\n\/*\n * Table is out of date (24.10.2005)\n *\n * AP - All Pass\n * FC - Fails to Compile\n * ? - Unknown\/Not Tested\/Not Recorded\n *\n * TypelistTest TypeManipTest TypeTraitsTest SmallObjectTest SingletonTest\n * gcc 2.95.3 ? ? ? ? ?\n * gcc 3.2 AP AP AP AP P (Only SingleThreaded)\n * MSVC 6.0 P AP FC FC AP\n * MSVC 7.0 AP Conversion FC AP P (Only SingleThreaded) ?\n * Intel 5.0 AP AP AP FC FC\n * Intel 6.0 AP AP AP FC P (Only SingleThreaded)\n * Intel 7.0 AP AP AP FC P (Only SingleThreaded)\n * BCC 5.5 ? ? ? ? ?\n * BCC 5.6 ? ? ? ? ?\n * CW 6.0 ? ? ? ? ?\n *\n * SmartPtrTest FactoryTest AbstractFactoryTest AssocVectorTest FunctorTest\n * gcc 2.95.3 ? ? ? ? ?\n * gcc 3.2 AP AP AP AP AP\n * MSVC 6.0 FC AP FC FC FC\n * MSVC 7.0 FC AP AP FC AP\n * Intel 5.0 FC FC FC FC FC\n * Intel 6.0 FC AP AP FC FC\n * Intel 7.0 FC AP AP FC FC\n * BCC 5.5 ? ? ? ? ?\n * CW 6.0 ? ? ? ? ?\n *\n * DataGeneratorsTest\n * gcc 2.95.3 ?\n * gcc 3.2 AP\n * MSVC 6.0 FC\n * MSVC 7.0 AP\n * Intel 5.0 FC\n * Intel 6.0 AP\n * Intel 7.0 AP\n * BCC 5.5 ?\n * BCC 5.6 ?\n * CW 6.0 ? \n\n *\/ \n\n\n\/\/ $Log$\n\/\/ Revision 1.12 2005\/10\/30 14:22:31 syntheticpp\n\/\/ disable threading because the sdk (windows.h) is not detected automatically by the batch scripts\n\/\/\n\/\/ Revision 1.11 2005\/10\/30 13:49:44 syntheticpp\n\/\/ make disabling the TYPELIST macros possible\n\/\/\n\/\/ Revision 1.10 2005\/10\/24 20:51:38 syntheticpp\n\/\/ Table is out of date\n\/\/\n\/\/ Revision 1.9 2005\/10\/24 20:35:12 syntheticpp\n\/\/ small changes for Threads; add compile test for Threads.h\n\/\/\n\/\/ Revision 1.8 2005\/10\/06 17:50:14 syntheticpp\n\/\/ adding template based list\/sequence implementation, should replace LOKI_TYPELIST_, update some files\n\/\/\n\/\/ Revision 1.7 2005\/09\/29 08:09:17 syntheticpp\n\/\/ update msvc build process\n\/\/\n\/\/ Revision 1.6 2005\/09\/26 07:33:05 syntheticpp\n\/\/ move macros into LOKI_ namespace\n\/\/\n\/\/ Revision 1.5 2005\/09\/24 15:49:40 syntheticpp\n\/\/ is it really binary?\n\/\/\n\/\/ Revision 1.4 2005\/09\/24 15:25:20 syntheticpp\n\/\/ ove RegressionTest\n\/\/\n\/\/ Revision 1.17 2005\/09\/15 17:51:48 syntheticpp\n\/\/ add new TypeTraits test from Kalle Rutanen\n\/\/\n\/\/ Revision 1.16 2005\/08\/10 18:13:13 syntheticpp\n\/\/ change default to single threading\n\/\/\n\/\/ Revision 1.15 2005\/07\/31 14:00:48 syntheticpp\n\/\/ make object level threading possible\n\/\/\n\/\/ Revision 1.14 2005\/07\/28 14:26:10 syntheticpp\n\/\/ add cvs Header\/Log\n\/\/\n<|endoftext|>"} {"text":"<commit_before>#include <gtest\/gtest.h>\n#include <entt\/core\/type_traits.hpp>\n#include <entt\/signal\/emitter.hpp>\n\nstruct test_emitter: entt::emitter<test_emitter> {};\n\nstruct foo_event { int i; char c; };\nstruct bar_event {};\nstruct quux_event {};\n\nTEST(Emitter, Clear) {\n test_emitter emitter;\n\n ASSERT_TRUE(emitter.empty());\n ASSERT_TRUE(emitter.empty<quux_event>());\n\n emitter.on<foo_event>([](const auto &, const auto &){});\n\n ASSERT_FALSE(emitter.empty());\n ASSERT_FALSE(emitter.empty<foo_event>());\n ASSERT_TRUE(emitter.empty<bar_event>());\n\n emitter.clear<bar_event>();\n\n ASSERT_FALSE(emitter.empty());\n ASSERT_FALSE(emitter.empty<foo_event>());\n ASSERT_TRUE(emitter.empty<bar_event>());\n\n emitter.clear<foo_event>();\n\n ASSERT_TRUE(emitter.empty());\n ASSERT_TRUE(emitter.empty<foo_event>());\n ASSERT_TRUE(emitter.empty<bar_event>());\n\n emitter.on<foo_event>([](const auto &, const auto &){});\n emitter.on<bar_event>([](const auto &, const auto &){});\n\n ASSERT_FALSE(emitter.empty());\n ASSERT_FALSE(emitter.empty<foo_event>());\n ASSERT_FALSE(emitter.empty<bar_event>());\n\n emitter.clear();\n\n ASSERT_TRUE(emitter.empty());\n ASSERT_TRUE(emitter.empty<foo_event>());\n ASSERT_TRUE(emitter.empty<bar_event>());\n}\n\nTEST(Emitter, ClearPublishing) {\n test_emitter emitter;\n bool invoked = false;\n\n ASSERT_TRUE(emitter.empty());\n\n emitter.on<bar_event>([&invoked](const auto &, auto &em){\n invoked = true;\n em.clear();\n });\n\n emitter.publish<bar_event>();\n\n ASSERT_TRUE(emitter.empty());\n ASSERT_TRUE(invoked);\n}\n\nTEST(Emitter, On) {\n test_emitter emitter;\n\n emitter.on<foo_event>([](const auto &, const auto &){});\n\n ASSERT_FALSE(emitter.empty());\n ASSERT_FALSE(emitter.empty<foo_event>());\n\n emitter.publish<foo_event>(0, 'c');\n\n ASSERT_FALSE(emitter.empty());\n ASSERT_FALSE(emitter.empty<foo_event>());\n}\n\nTEST(Emitter, Once) {\n test_emitter emitter;\n\n emitter.once<bar_event>([](const auto &, const auto &){});\n\n ASSERT_FALSE(emitter.empty());\n ASSERT_FALSE(emitter.empty<bar_event>());\n\n emitter.publish<bar_event>();\n\n ASSERT_TRUE(emitter.empty());\n ASSERT_TRUE(emitter.empty<bar_event>());\n}\n\nTEST(Emitter, OnceAndErase) {\n test_emitter emitter;\n\n auto conn = emitter.once<foo_event>([](const auto &, const auto &){});\n\n ASSERT_FALSE(emitter.empty());\n ASSERT_FALSE(emitter.empty<foo_event>());\n\n emitter.erase(conn);\n\n ASSERT_TRUE(emitter.empty());\n ASSERT_TRUE(emitter.empty<foo_event>());\n}\n\nTEST(Emitter, OnAndErase) {\n test_emitter emitter;\n\n auto conn = emitter.on<bar_event>([](const auto &, const auto &){});\n\n ASSERT_FALSE(emitter.empty());\n ASSERT_FALSE(emitter.empty<bar_event>());\n\n emitter.erase(conn);\n\n ASSERT_TRUE(emitter.empty());\n ASSERT_TRUE(emitter.empty<bar_event>());\n}\n<commit_msg>tests: code coverage<commit_after>#include <gtest\/gtest.h>\n#include <entt\/core\/type_traits.hpp>\n#include <entt\/signal\/emitter.hpp>\n\nstruct test_emitter: entt::emitter<test_emitter> {};\n\nstruct foo_event { int i; char c; };\nstruct bar_event {};\nstruct quux_event {};\n\nTEST(Emitter, Clear) {\n test_emitter emitter;\n\n ASSERT_TRUE(emitter.empty());\n\n emitter.on<foo_event>([](const auto &, const auto &){});\n emitter.once<quux_event>([](const auto &, const auto &){});\n\n ASSERT_FALSE(emitter.empty());\n ASSERT_FALSE(emitter.empty<foo_event>());\n ASSERT_FALSE(emitter.empty<quux_event>());\n ASSERT_TRUE(emitter.empty<bar_event>());\n\n emitter.clear<bar_event>();\n\n ASSERT_FALSE(emitter.empty());\n ASSERT_FALSE(emitter.empty<foo_event>());\n ASSERT_FALSE(emitter.empty<quux_event>());\n ASSERT_TRUE(emitter.empty<bar_event>());\n\n emitter.clear<foo_event>();\n\n ASSERT_FALSE(emitter.empty());\n ASSERT_TRUE(emitter.empty<foo_event>());\n ASSERT_FALSE(emitter.empty<quux_event>());\n ASSERT_TRUE(emitter.empty<bar_event>());\n\n emitter.on<foo_event>([](const auto &, const auto &){});\n emitter.on<bar_event>([](const auto &, const auto &){});\n\n ASSERT_FALSE(emitter.empty());\n ASSERT_FALSE(emitter.empty<foo_event>());\n ASSERT_FALSE(emitter.empty<quux_event>());\n ASSERT_FALSE(emitter.empty<bar_event>());\n\n emitter.clear();\n\n ASSERT_TRUE(emitter.empty());\n ASSERT_TRUE(emitter.empty<foo_event>());\n ASSERT_TRUE(emitter.empty<bar_event>());\n}\n\nTEST(Emitter, ClearPublishing) {\n test_emitter emitter;\n\n ASSERT_TRUE(emitter.empty());\n\n emitter.once<foo_event>([](const auto &, auto &em){\n em.template once<foo_event>([](const auto &, auto &){});\n em.template clear<foo_event>();\n });\n\n emitter.on<bar_event>([](const auto &, auto &em){\n em.template once<bar_event>([](const auto &, auto &){});\n em.template clear<bar_event>();\n });\n\n ASSERT_FALSE(emitter.empty());\n\n emitter.publish<foo_event>();\n emitter.publish<bar_event>();\n\n ASSERT_TRUE(emitter.empty());\n}\n\nTEST(Emitter, On) {\n test_emitter emitter;\n\n emitter.on<foo_event>([](const auto &, const auto &){});\n\n ASSERT_FALSE(emitter.empty());\n ASSERT_FALSE(emitter.empty<foo_event>());\n\n emitter.publish<foo_event>(0, 'c');\n\n ASSERT_FALSE(emitter.empty());\n ASSERT_FALSE(emitter.empty<foo_event>());\n}\n\nTEST(Emitter, Once) {\n test_emitter emitter;\n\n emitter.once<bar_event>([](const auto &, const auto &){});\n\n ASSERT_FALSE(emitter.empty());\n ASSERT_FALSE(emitter.empty<bar_event>());\n\n emitter.publish<bar_event>();\n\n ASSERT_TRUE(emitter.empty());\n ASSERT_TRUE(emitter.empty<bar_event>());\n}\n\nTEST(Emitter, OnceAndErase) {\n test_emitter emitter;\n\n auto conn = emitter.once<foo_event>([](const auto &, const auto &){});\n\n ASSERT_FALSE(emitter.empty());\n ASSERT_FALSE(emitter.empty<foo_event>());\n\n emitter.erase(conn);\n\n ASSERT_TRUE(emitter.empty());\n ASSERT_TRUE(emitter.empty<foo_event>());\n}\n\nTEST(Emitter, OnAndErase) {\n test_emitter emitter;\n\n auto conn = emitter.on<bar_event>([](const auto &, const auto &){});\n\n ASSERT_FALSE(emitter.empty());\n ASSERT_FALSE(emitter.empty<bar_event>());\n\n emitter.erase(conn);\n\n ASSERT_TRUE(emitter.empty());\n ASSERT_TRUE(emitter.empty<bar_event>());\n}\n<|endoftext|>"} {"text":"<commit_before>#include <stdlib.h>\n\n#include <fstream>\n\n#include \"env.h\"\n\n#include \"gtest\/gtest.h\"\n#include \"ir\/ir.h\"\n#include \"helpers.h\"\n#include \"lib\/log.h\"\n\n#include \"frontends\/common\/parseInput.h\"\n\n#include \"backends\/p4test\/version.h\"\n\n#include \"p4\/createBuiltins.h\"\n#include \"p4\/typeChecking\/typeChecker.h\"\n\n#include \"frontends\/common\/constantFolding.h\"\n#include \"frontends\/common\/resolveReferences\/resolveReferences.h\"\n#include \"frontends\/p4\/evaluator\/evaluator.h\"\n#include \"frontends\/p4\/fromv1.0\/v1model.h\"\n#include \"frontends\/p4\/moveDeclarations.h\"\n#include \"frontends\/p4\/simplify.h\"\n#include \"frontends\/p4\/typeChecking\/typeChecker.h\"\n#include \"frontends\/p4\/simplifyParsers.h\"\n#include \"frontends\/p4\/strengthReduction.h\"\n#include \"frontends\/p4\/toP4\/toP4.h\"\n#include \"frontends\/p4\/typeMap.h\"\n#include \"frontends\/p4\/uniqueNames.h\"\n#include \"frontends\/p4\/unusedDeclarations.h\"\n#include \"midend\/actionSynthesis.h\"\n#include \"midend\/compileTimeOps.h\"\n#include \"midend\/complexComparison.h\"\n#include \"midend\/copyStructures.h\"\n#include \"midend\/eliminateTuples.h\"\n#include \"midend\/eliminateNewtype.h\"\n#include \"midend\/eliminateSerEnums.h\"\n#include \"midend\/eliminateSwitch.h\"\n#include \"midend\/flattenHeaders.h\"\n#include \"midend\/flattenInterfaceStructs.h\"\n#include \"midend\/replaceSelectRange.h\"\n#include \"midend\/expandEmit.h\"\n#include \"midend\/expandLookahead.h\"\n#include \"midend\/local_copyprop.h\"\n#include \"midend\/midEndLast.h\"\n#include \"midend\/nestedStructs.h\"\n#include \"midend\/noMatch.h\"\n#include \"midend\/predication.h\"\n#include \"midend\/removeExits.h\"\n#include \"midend\/removeMiss.h\"\n#include \"midend\/removeParameters.h\"\n#include \"midend\/removeSelectBooleans.h\"\n#include \"midend\/simplifyKey.h\"\n#include \"midend\/simplifySelectCases.h\"\n#include \"midend\/simplifySelectList.h\"\n#include \"midend\/tableHit.h\"\n#include \"midend\/removeAssertAssume.h\"\n#include \"midend\/parserUnroll.h\"\n\nusing namespace P4;\n\nnamespace Test {\n\nclass P4TestOptions : public CompilerOptions {\n public:\n P4TestOptions() {\n }\n};\n\nusing P4TestContext = P4CContextWithOptions<P4TestOptions>;\n\nclass P4CParserUnroll : public P4CTest { };\n\n\nclass SkipControls : public P4::ActionSynthesisPolicy {\n const std::set<cstring> *skip;\n\n public:\n explicit SkipControls(const std::set<cstring> *skip) : skip(skip) { CHECK_NULL(skip); }\n bool convert(const Visitor::Context *, const IR::P4Control* control) override {\n if (skip->find(control->name) != skip->end())\n return false;\n return true;\n }\n};\n\n\nclass MidEnd : public PassManager {\n public:\n P4::ReferenceMap refMap;\n P4::TypeMap typeMap;\n IR::ToplevelBlock *toplevel = nullptr;\n\n explicit MidEnd(CompilerOptions& options, std::ostream* outStream = nullptr) {\n bool isv1 = options.langVersion == CompilerOptions::FrontendVersion::P4_14;\n refMap.setIsV1(isv1);\n auto evaluator = new P4::EvaluatorPass(&refMap, &typeMap);\n setName(\"MidEnd\");\n\n auto v1controls = new std::set<cstring>();\n\n addPasses({\n options.ndebug ? new P4::RemoveAssertAssume(&refMap, &typeMap) : nullptr,\n new P4::RemoveMiss(&refMap, &typeMap),\n new P4::EliminateNewtype(&refMap, &typeMap),\n new P4::EliminateSerEnums(&refMap, &typeMap),\n new P4::RemoveActionParameters(&refMap, &typeMap),\n new P4::SimplifyKey(&refMap, &typeMap,\n new P4::OrPolicy(\n new P4::IsValid(&refMap, &typeMap),\n new P4::IsLikeLeftValue())),\n new P4::RemoveExits(&refMap, &typeMap),\n new P4::ConstantFolding(&refMap, &typeMap),\n new P4::SimplifySelectCases(&refMap, &typeMap, false), \/\/ non-constant keysets\n new P4::ExpandLookahead(&refMap, &typeMap),\n new P4::ExpandEmit(&refMap, &typeMap),\n new P4::HandleNoMatch(&refMap),\n new P4::SimplifyParsers(&refMap),\n new P4::StrengthReduction(&refMap, &typeMap),\n new P4::EliminateTuples(&refMap, &typeMap),\n new P4::SimplifyComparisons(&refMap, &typeMap),\n new P4::CopyStructures(&refMap, &typeMap),\n new P4::NestedStructs(&refMap, &typeMap),\n new P4::SimplifySelectList(&refMap, &typeMap),\n new P4::RemoveSelectBooleans(&refMap, &typeMap),\n new P4::FlattenHeaders(&refMap, &typeMap),\n new P4::FlattenInterfaceStructs(&refMap, &typeMap),\n new P4::ReplaceSelectRange(&refMap, &typeMap),\n new P4::Predication(&refMap),\n new P4::MoveDeclarations(), \/\/ more may have been introduced\n new P4::ConstantFolding(&refMap, &typeMap),\n new P4::LocalCopyPropagation(&refMap, &typeMap),\n new P4::ConstantFolding(&refMap, &typeMap),\n new P4::StrengthReduction(&refMap, &typeMap),\n new P4::MoveDeclarations(), \/\/ more may have been introduced\n new P4::SimplifyControlFlow(&refMap, &typeMap),\n new P4::CompileTimeOperations(),\n new P4::TableHit(&refMap, &typeMap),\n new P4::EliminateSwitch(&refMap, &typeMap),\n evaluator,\n [v1controls, evaluator](const IR::Node *root) -> const IR::Node * {\n auto toplevel = evaluator->getToplevelBlock();\n auto main = toplevel->getMain();\n if (main == nullptr)\n \/\/ nothing further to do\n return nullptr;\n \/\/ Special handling when compiling for v1model.p4\n if (main->type->name == P4V1::V1Model::instance.sw.name) {\n if (main->getConstructorParameters()->size() != 6)\n return root;\n auto verify = main->getParameterValue(P4V1::V1Model::instance.sw.verify.name);\n auto update = main->getParameterValue(\n P4V1::V1Model::instance.sw.compute.name);\n auto deparser = main->getParameterValue(\n P4V1::V1Model::instance.sw.deparser.name);\n if (verify == nullptr || update == nullptr || deparser == nullptr ||\n !verify->is<IR::ControlBlock>() || !update->is<IR::ControlBlock>() ||\n !deparser->is<IR::ControlBlock>()) {\n return root;\n }\n v1controls->emplace(verify->to<IR::ControlBlock>()->container->name);\n v1controls->emplace(update->to<IR::ControlBlock>()->container->name);\n v1controls->emplace(deparser->to<IR::ControlBlock>()->container->name);\n }\n return root; },\n new P4::SynthesizeActions(&refMap, &typeMap, new SkipControls(v1controls)),\n new P4::MoveActionsToTables(&refMap, &typeMap),\n options.loopsUnrolling ? new ParsersUnroll(true, &refMap, &typeMap) : nullptr,\n evaluator,\n [this, evaluator]() {\n toplevel = evaluator->getToplevelBlock();\n },\n new P4::MidEndLast()\n });\n if (options.listMidendPasses) {\n listPasses(*outStream, \"\\n\");\n *outStream << std::endl;\n return;\n }\n if (options.excludeMidendPasses) {\n removePasses(options.passesToExcludeMidend);\n }\n toplevel = evaluator->getToplevelBlock();\n }\n IR::ToplevelBlock* process(const IR::P4Program *&program) {\n program = program->apply(*this);\n return toplevel; }\n};\n\n\/\/ #define PARSER_UNROLL_TIME_CHECKING\n\n#ifdef PARSER_UNROLL_TIME_CHECKING\n #include <chrono>\n#endif\n\nconst IR::P4Parser* getParser(const IR::P4Program* program) {\n cstring parserName = \"MyParser\";\n \/* std::function<bool(const IR::IDeclaration*)> filter =\n [parserName](const IR::IDeclaration* d)\n { CHECK_NULL(d); return d->getName().name.find(parserName.c_str()) != nullptr; };*\/\n std::function<bool(const IR::IDeclaration*)> filter =\n [parserName](const IR::IDeclaration* d)\n { CHECK_NULL(d); return d->is<IR::P4Parser>(); };\n const auto* newDeclVector = program->getDeclarations()->where(filter)->toVector();\n return (*newDeclVector)[0]->to<IR::P4Parser>();\n}\n\n\/\/\/ Rewrites parser\nstd::pair<const IR::P4Parser*, const IR::P4Parser*> rewriteParser(const IR::P4Program* program,\n CompilerOptions& options) {\n P4::FrontEnd frontend;\n program = frontend.run(options, program);\n P4::ReferenceMap refMap;\n P4::TypeMap typeMap;\n\n#ifdef PARSER_UNROLL_TIME_CHECKING\n using std::chrono::high_resolution_clock;\n using std::chrono::duration_cast;\n using std::chrono::duration;\n using std::chrono::milliseconds;\n auto t1 = high_resolution_clock::now();\n#endif\n MidEnd midEnd(options);\n const IR::P4Program* res = program;\n midEnd.process(res);\n#ifdef PARSER_UNROLL_TIME_CHECKING\n auto t2 = high_resolution_clock::now();\n auto msInt = duration_cast<milliseconds>(t2 - t1);\n std::cout << msInt.count() << std::endl;\n#endif\n return std::make_pair(getParser(program), getParser(res));\n}\n\n\/\/\/ Loads example from a file\nconst IR::P4Program* load_model(const char* curFile, CompilerOptions& options) {\n std::string includeDir = std::string(relPath) + std::string(\"p4include\");\n setenv(\"P4C_16_INCLUDE_PATH\", includeDir.c_str(), 1);\n options.loopsUnrolling = true;\n options.compilerVersion = P4TEST_VERSION_STRING;\n options.file = relPath;\n options.file += \"testdata\/p4_16_samples\/\";\n options.file += curFile;\n return P4::parseP4File(options);\n}\n\nstd::pair<const IR::P4Parser*, const IR::P4Parser*> loadExample(const char *file,\n CompilerOptions::FrontendVersion langVersion =\n CompilerOptions::FrontendVersion::P4_16) {\n AutoCompileContext autoP4TestContext(new P4TestContext);\n auto& options = P4TestContext::get().options();\n const char* argv = \".\/gtestp4c\";\n options.process(1, (char* const*)&argv);\n options.langVersion = langVersion;\n const IR::P4Program* program = load_model(file, options);\n if (!program)\n return std::make_pair(nullptr, nullptr);\n return rewriteParser(program, options);\n}\n\nTEST_F(P4CParserUnroll, test1) {\n auto parsers = loadExample(\"parser-unroll-test1.p4\");\n ASSERT_TRUE(parsers.first);\n ASSERT_TRUE(parsers.second);\n \/\/ 2 - exclude accept and reject states\n \/\/ adding MAX_HOPS and outOfBound states\n ASSERT_EQ(parsers.first->states.size(), parsers.second->states.size() - 3 - 1);\n}\n\nTEST_F(P4CParserUnroll, test2) {\n auto parsers = loadExample(\"parser-unroll-test2.p4\");\n ASSERT_TRUE(parsers.first);\n ASSERT_TRUE(parsers.second);\n ASSERT_EQ(parsers.first->states.size(), parsers.second->states.size() - 3 - 1);\n}\n\nTEST_F(P4CParserUnroll, test3) {\n auto parsers = loadExample(\"parser-unroll-test3.p4\");\n ASSERT_TRUE(parsers.first);\n ASSERT_TRUE(parsers.second);\n ASSERT_EQ(parsers.first->states.size(), parsers.second->states.size() - 4);\n}\n\nTEST_F(P4CParserUnroll, switch_20160512) {\n auto parsers = loadExample(\"..\/p4_14_samples\/switch_20160512\/switch.p4\",\n CompilerOptions::FrontendVersion::P4_14);\n ASSERT_TRUE(parsers.first);\n ASSERT_TRUE(parsers.second);\n ASSERT_EQ(parsers.first->states.size(), parsers.second->states.size() - 22 - 4 - 2);\n}\n\nTEST_F(P4CParserUnroll, header_stack_access_remover) {\n auto parsers = loadExample(\"parser-unroll-test4.p4\");\n ASSERT_TRUE(parsers.first);\n ASSERT_TRUE(parsers.second);\n ASSERT_EQ(parsers.first->states.size(), parsers.second->states.size() - 3);\n}\n\nTEST_F(P4CParserUnroll, noLoopsAndHeaderStacks) {\n auto parsers = loadExample(\"parser-unroll-test5.p4\");\n ASSERT_TRUE(parsers.first);\n ASSERT_TRUE(parsers.second);\n ASSERT_EQ(parsers.first->states.size(), parsers.second->states.size());\n}\n\nTEST_F(P4CParserUnroll, t1_Cond) {\n auto parsers = loadExample(\"parser-unroll-t1-cond.p4\");\n ASSERT_TRUE(parsers.first);\n ASSERT_TRUE(parsers.second);\n ASSERT_EQ(parsers.first->states.size(), parsers.second->states.size());\n}\n\n} \/\/ namespace Test\n<commit_msg>Parser unroll gtest now does not modify environment (#2750)<commit_after>#include <stdlib.h>\n\n#include <fstream>\n\n#include \"env.h\"\n\n#include \"gtest\/gtest.h\"\n#include \"ir\/ir.h\"\n#include \"helpers.h\"\n#include \"lib\/log.h\"\n\n#include \"frontends\/common\/parseInput.h\"\n\n#include \"backends\/p4test\/version.h\"\n\n#include \"p4\/createBuiltins.h\"\n#include \"p4\/typeChecking\/typeChecker.h\"\n\n#include \"frontends\/common\/constantFolding.h\"\n#include \"frontends\/common\/resolveReferences\/resolveReferences.h\"\n#include \"frontends\/p4\/evaluator\/evaluator.h\"\n#include \"frontends\/p4\/fromv1.0\/v1model.h\"\n#include \"frontends\/p4\/moveDeclarations.h\"\n#include \"frontends\/p4\/simplify.h\"\n#include \"frontends\/p4\/typeChecking\/typeChecker.h\"\n#include \"frontends\/p4\/simplifyParsers.h\"\n#include \"frontends\/p4\/strengthReduction.h\"\n#include \"frontends\/p4\/toP4\/toP4.h\"\n#include \"frontends\/p4\/typeMap.h\"\n#include \"frontends\/p4\/uniqueNames.h\"\n#include \"frontends\/p4\/unusedDeclarations.h\"\n#include \"midend\/actionSynthesis.h\"\n#include \"midend\/compileTimeOps.h\"\n#include \"midend\/complexComparison.h\"\n#include \"midend\/copyStructures.h\"\n#include \"midend\/eliminateTuples.h\"\n#include \"midend\/eliminateNewtype.h\"\n#include \"midend\/eliminateSerEnums.h\"\n#include \"midend\/eliminateSwitch.h\"\n#include \"midend\/flattenHeaders.h\"\n#include \"midend\/flattenInterfaceStructs.h\"\n#include \"midend\/replaceSelectRange.h\"\n#include \"midend\/expandEmit.h\"\n#include \"midend\/expandLookahead.h\"\n#include \"midend\/local_copyprop.h\"\n#include \"midend\/midEndLast.h\"\n#include \"midend\/nestedStructs.h\"\n#include \"midend\/noMatch.h\"\n#include \"midend\/predication.h\"\n#include \"midend\/removeExits.h\"\n#include \"midend\/removeMiss.h\"\n#include \"midend\/removeParameters.h\"\n#include \"midend\/removeSelectBooleans.h\"\n#include \"midend\/simplifyKey.h\"\n#include \"midend\/simplifySelectCases.h\"\n#include \"midend\/simplifySelectList.h\"\n#include \"midend\/tableHit.h\"\n#include \"midend\/removeAssertAssume.h\"\n#include \"midend\/parserUnroll.h\"\n\nusing namespace P4;\n\nnamespace Test {\n\nclass P4TestOptions : public CompilerOptions {\n public:\n P4TestOptions() {\n }\n};\n\nusing P4TestContext = P4CContextWithOptions<P4TestOptions>;\n\nclass P4CParserUnroll : public P4CTest { };\n\n\nclass SkipControls : public P4::ActionSynthesisPolicy {\n const std::set<cstring> *skip;\n\n public:\n explicit SkipControls(const std::set<cstring> *skip) : skip(skip) { CHECK_NULL(skip); }\n bool convert(const Visitor::Context *, const IR::P4Control* control) override {\n if (skip->find(control->name) != skip->end())\n return false;\n return true;\n }\n};\n\n\nclass MidEnd : public PassManager {\n public:\n P4::ReferenceMap refMap;\n P4::TypeMap typeMap;\n IR::ToplevelBlock *toplevel = nullptr;\n\n explicit MidEnd(CompilerOptions& options, std::ostream* outStream = nullptr) {\n bool isv1 = options.langVersion == CompilerOptions::FrontendVersion::P4_14;\n refMap.setIsV1(isv1);\n auto evaluator = new P4::EvaluatorPass(&refMap, &typeMap);\n setName(\"MidEnd\");\n\n auto v1controls = new std::set<cstring>();\n\n addPasses({\n options.ndebug ? new P4::RemoveAssertAssume(&refMap, &typeMap) : nullptr,\n new P4::RemoveMiss(&refMap, &typeMap),\n new P4::EliminateNewtype(&refMap, &typeMap),\n new P4::EliminateSerEnums(&refMap, &typeMap),\n new P4::RemoveActionParameters(&refMap, &typeMap),\n new P4::SimplifyKey(&refMap, &typeMap,\n new P4::OrPolicy(\n new P4::IsValid(&refMap, &typeMap),\n new P4::IsLikeLeftValue())),\n new P4::RemoveExits(&refMap, &typeMap),\n new P4::ConstantFolding(&refMap, &typeMap),\n new P4::SimplifySelectCases(&refMap, &typeMap, false), \/\/ non-constant keysets\n new P4::ExpandLookahead(&refMap, &typeMap),\n new P4::ExpandEmit(&refMap, &typeMap),\n new P4::HandleNoMatch(&refMap),\n new P4::SimplifyParsers(&refMap),\n new P4::StrengthReduction(&refMap, &typeMap),\n new P4::EliminateTuples(&refMap, &typeMap),\n new P4::SimplifyComparisons(&refMap, &typeMap),\n new P4::CopyStructures(&refMap, &typeMap),\n new P4::NestedStructs(&refMap, &typeMap),\n new P4::SimplifySelectList(&refMap, &typeMap),\n new P4::RemoveSelectBooleans(&refMap, &typeMap),\n new P4::FlattenHeaders(&refMap, &typeMap),\n new P4::FlattenInterfaceStructs(&refMap, &typeMap),\n new P4::ReplaceSelectRange(&refMap, &typeMap),\n new P4::Predication(&refMap),\n new P4::MoveDeclarations(), \/\/ more may have been introduced\n new P4::ConstantFolding(&refMap, &typeMap),\n new P4::LocalCopyPropagation(&refMap, &typeMap),\n new P4::ConstantFolding(&refMap, &typeMap),\n new P4::StrengthReduction(&refMap, &typeMap),\n new P4::MoveDeclarations(), \/\/ more may have been introduced\n new P4::SimplifyControlFlow(&refMap, &typeMap),\n new P4::CompileTimeOperations(),\n new P4::TableHit(&refMap, &typeMap),\n new P4::EliminateSwitch(&refMap, &typeMap),\n evaluator,\n [v1controls, evaluator](const IR::Node *root) -> const IR::Node * {\n auto toplevel = evaluator->getToplevelBlock();\n auto main = toplevel->getMain();\n if (main == nullptr)\n \/\/ nothing further to do\n return nullptr;\n \/\/ Special handling when compiling for v1model.p4\n if (main->type->name == P4V1::V1Model::instance.sw.name) {\n if (main->getConstructorParameters()->size() != 6)\n return root;\n auto verify = main->getParameterValue(P4V1::V1Model::instance.sw.verify.name);\n auto update = main->getParameterValue(\n P4V1::V1Model::instance.sw.compute.name);\n auto deparser = main->getParameterValue(\n P4V1::V1Model::instance.sw.deparser.name);\n if (verify == nullptr || update == nullptr || deparser == nullptr ||\n !verify->is<IR::ControlBlock>() || !update->is<IR::ControlBlock>() ||\n !deparser->is<IR::ControlBlock>()) {\n return root;\n }\n v1controls->emplace(verify->to<IR::ControlBlock>()->container->name);\n v1controls->emplace(update->to<IR::ControlBlock>()->container->name);\n v1controls->emplace(deparser->to<IR::ControlBlock>()->container->name);\n }\n return root; },\n new P4::SynthesizeActions(&refMap, &typeMap, new SkipControls(v1controls)),\n new P4::MoveActionsToTables(&refMap, &typeMap),\n options.loopsUnrolling ? new ParsersUnroll(true, &refMap, &typeMap) : nullptr,\n evaluator,\n [this, evaluator]() {\n toplevel = evaluator->getToplevelBlock();\n },\n new P4::MidEndLast()\n });\n if (options.listMidendPasses) {\n listPasses(*outStream, \"\\n\");\n *outStream << std::endl;\n return;\n }\n if (options.excludeMidendPasses) {\n removePasses(options.passesToExcludeMidend);\n }\n toplevel = evaluator->getToplevelBlock();\n }\n IR::ToplevelBlock* process(const IR::P4Program *&program) {\n program = program->apply(*this);\n return toplevel; }\n};\n\n\/\/ #define PARSER_UNROLL_TIME_CHECKING\n\n#ifdef PARSER_UNROLL_TIME_CHECKING\n #include <chrono>\n#endif\n\nconst IR::P4Parser* getParser(const IR::P4Program* program) {\n cstring parserName = \"MyParser\";\n \/* std::function<bool(const IR::IDeclaration*)> filter =\n [parserName](const IR::IDeclaration* d)\n { CHECK_NULL(d); return d->getName().name.find(parserName.c_str()) != nullptr; };*\/\n std::function<bool(const IR::IDeclaration*)> filter =\n [parserName](const IR::IDeclaration* d)\n { CHECK_NULL(d); return d->is<IR::P4Parser>(); };\n const auto* newDeclVector = program->getDeclarations()->where(filter)->toVector();\n return (*newDeclVector)[0]->to<IR::P4Parser>();\n}\n\n\/\/\/ Rewrites parser\nstd::pair<const IR::P4Parser*, const IR::P4Parser*> rewriteParser(const IR::P4Program* program,\n CompilerOptions& options) {\n P4::FrontEnd frontend;\n program = frontend.run(options, program);\n P4::ReferenceMap refMap;\n P4::TypeMap typeMap;\n\n#ifdef PARSER_UNROLL_TIME_CHECKING\n using std::chrono::high_resolution_clock;\n using std::chrono::duration_cast;\n using std::chrono::duration;\n using std::chrono::milliseconds;\n auto t1 = high_resolution_clock::now();\n#endif\n MidEnd midEnd(options);\n const IR::P4Program* res = program;\n midEnd.process(res);\n#ifdef PARSER_UNROLL_TIME_CHECKING\n auto t2 = high_resolution_clock::now();\n auto msInt = duration_cast<milliseconds>(t2 - t1);\n std::cout << msInt.count() << std::endl;\n#endif\n return std::make_pair(getParser(program), getParser(res));\n}\n\n\/\/\/ Loads example from a file\nconst IR::P4Program* load_model(const char* curFile, CompilerOptions& options) {\n std::string includeDir = std::string(relPath) + std::string(\"p4include\");\n auto originalEnv = getenv(\"P4C_16_INCLUDE_PATH\");\n setenv(\"P4C_16_INCLUDE_PATH\", includeDir.c_str(), 1);\n options.loopsUnrolling = true;\n options.compilerVersion = P4TEST_VERSION_STRING;\n options.file = relPath;\n options.file += \"testdata\/p4_16_samples\/\";\n options.file += curFile;\n auto program = P4::parseP4File(options);\n if (!originalEnv)\n unsetenv(\"P4C_16_INCLUDE_PATH\");\n else\n setenv(\"P4C_16_INCLUDE_PATH\", originalEnv, 1);\n return program;\n}\n\nstd::pair<const IR::P4Parser*, const IR::P4Parser*> loadExample(const char *file,\n CompilerOptions::FrontendVersion langVersion =\n CompilerOptions::FrontendVersion::P4_16) {\n AutoCompileContext autoP4TestContext(new P4TestContext);\n auto& options = P4TestContext::get().options();\n const char* argv = \".\/gtestp4c\";\n options.process(1, (char* const*)&argv);\n options.langVersion = langVersion;\n const IR::P4Program* program = load_model(file, options);\n if (!program)\n return std::make_pair(nullptr, nullptr);\n return rewriteParser(program, options);\n}\n\nTEST_F(P4CParserUnroll, test1) {\n auto parsers = loadExample(\"parser-unroll-test1.p4\");\n ASSERT_TRUE(parsers.first);\n ASSERT_TRUE(parsers.second);\n \/\/ 2 - exclude accept and reject states\n \/\/ adding MAX_HOPS and outOfBound states\n ASSERT_EQ(parsers.first->states.size(), parsers.second->states.size() - 3 - 1);\n}\n\nTEST_F(P4CParserUnroll, test2) {\n auto parsers = loadExample(\"parser-unroll-test2.p4\");\n ASSERT_TRUE(parsers.first);\n ASSERT_TRUE(parsers.second);\n ASSERT_EQ(parsers.first->states.size(), parsers.second->states.size() - 3 - 1);\n}\n\nTEST_F(P4CParserUnroll, test3) {\n auto parsers = loadExample(\"parser-unroll-test3.p4\");\n ASSERT_TRUE(parsers.first);\n ASSERT_TRUE(parsers.second);\n ASSERT_EQ(parsers.first->states.size(), parsers.second->states.size() - 4);\n}\n\nTEST_F(P4CParserUnroll, switch_20160512) {\n auto parsers = loadExample(\"..\/p4_14_samples\/switch_20160512\/switch.p4\",\n CompilerOptions::FrontendVersion::P4_14);\n ASSERT_TRUE(parsers.first);\n ASSERT_TRUE(parsers.second);\n ASSERT_EQ(parsers.first->states.size(), parsers.second->states.size() - 22 - 4 - 2);\n}\n\nTEST_F(P4CParserUnroll, header_stack_access_remover) {\n auto parsers = loadExample(\"parser-unroll-test4.p4\");\n ASSERT_TRUE(parsers.first);\n ASSERT_TRUE(parsers.second);\n ASSERT_EQ(parsers.first->states.size(), parsers.second->states.size() - 3);\n}\n\nTEST_F(P4CParserUnroll, noLoopsAndHeaderStacks) {\n auto parsers = loadExample(\"parser-unroll-test5.p4\");\n ASSERT_TRUE(parsers.first);\n ASSERT_TRUE(parsers.second);\n ASSERT_EQ(parsers.first->states.size(), parsers.second->states.size());\n}\n\nTEST_F(P4CParserUnroll, t1_Cond) {\n auto parsers = loadExample(\"parser-unroll-t1-cond.p4\");\n ASSERT_TRUE(parsers.first);\n ASSERT_TRUE(parsers.second);\n ASSERT_EQ(parsers.first->states.size(), parsers.second->states.size());\n}\n\n} \/\/ namespace Test\n<|endoftext|>"} {"text":"<commit_before>\/\/ Catch\n#include <catch.hpp>\n\n\/\/ C++ Standard Library\n#include <cstdlib>\n#include <cmath>\n#include <array>\n\n\/\/ Armadillo\n#include <armadillo>\n\n\/\/ Mantella\n#include <mantella>\n\nTEST_CASE(\"Circle circle intersection\", \"\") {\n arma::Col<double>::fixed<2> result;\n arma::Col<double>::fixed<2> expected;\n\n result = mant::getCircleCircleIntersection({-2.0, 3.0}, 1.3, {-1.5, 2.4}, 1.2);\n expected = {-2.5522451636, 1.8231290303};\n for (std::size_t n = 0; n < expected.n_elem; ++n) {\n CHECK(result.at(n) == Approx(expected.at(n)));\n }\n\n result = mant::getCircleCircleIntersection({1.8, -2.5}, 4.0, {-3.0, 2.0}, 3.0);\n expected = {-0.1804143359, 0.9753358195};\n for (std::size_t n = 0; n < expected.n_elem; ++n) {\n CHECK(result.at(n) == Approx(expected.at(n)));\n }\n}\n\nTEST_CASE(\"Circle sphere intersection\", \"\") {\n arma::Col<double>::fixed<3> result;\n arma::Col<double>::fixed<3> expected;\n\n result = mant::getCircleSphereIntersection({-2.0, 0.0, 0.0}, 1.2, {0.0, 0.0, 1.0}, {-3.0, 0.0, 0.0}, 1.5);\n expected = {-2.095, 1.1962336728, 0.0};\n for (std::size_t n = 0; n < expected.n_elem; ++n) {\n CHECK(result.at(n) == Approx(expected.at(n)));\n }\n\n result = mant::getCircleSphereIntersection({-2.0, 3.0, 0.0}, 1.3, {0.0, 0.0, 1.0}, {-1.5, 2.4, 0.0}, 1.2);\n expected = {-2.5522451636, 1.8231290303, 0.0};\n for (std::size_t n = 0; n < expected.n_elem; ++n) {\n CHECK(result.at(n) == Approx(expected.at(n)));\n }\n\n result = mant::getCircleSphereIntersection({1.8, -2.5, 0.0}, 4.0, {0.0, 0.0, 1.0}, {-3.0, 2.0, 0.0}, 3.0);\n expected = {-0.1804143359, 0.9753358195, 0.0};\n for (std::size_t n = 0; n < expected.n_elem; ++n) {\n CHECK(result.at(n) == Approx(expected.at(n)));\n }\n}\n\nTEST_CASE(\"2D rotation matrix\", \"\") {\n std::array<double, 15> angles = {0.0, 45.0, 90.0, 135.0, 180.0, 225.0, 270.0, 315.0, 360.0, -0.0, -45.0, -90.0, -180.0, -225.0, -315.0};\n\n for (const auto& angle : angles) {\n arma::Mat<double> result = mant::get2DRotationMatrix(angle);\n\n arma::Mat<double>::fixed<2, 2> expected({\n std::cos(angle), -std::sin(angle),\n std::sin(angle), std::cos(angle)\n });\n\n CHECK(result.n_rows == 2);\n CHECK(result.n_cols == 2);\n\n for (std::size_t n = 0; n < expected.n_elem; ++n) {\n CHECK(result.at(n) == Approx(expected.at(n)));\n }\n }\n}\n\nTEST_CASE(\"3D rotation matrix\", \"\") {\n std::array<double, 14> rollAngles = {0.0, 45.0, 90.0, 135.0, 180.0, 225, 270, 315, 360, -0, -45, 276, -56, -45.89};\n std::array<double, 14> pitchAngles = {0.0, 45.0, 90.0, 135.0, 180.0, 225, 270, 315, 360, -0, -90, -89, 78, -245};\n std::array<double, 14> yawAngles = {0.0, 45.0, 90.0, 135.0, 180.0, 225, 270, 315, 360, -0, -225, -310, -90, 345};\n\n for (const auto& rollAngle : rollAngles) {\n for (const auto& pitchAngle : pitchAngles) {\n for (const auto& yawAngle : yawAngles) {\n arma::Mat<double> result = mant::get3DRotationMatrix(rollAngle, pitchAngle, yawAngle);\n\n arma::Mat<double>::fixed<3, 3> expectedRoll({\n 1.0, 0.0, 0.0,\n 0.0, std::cos(rollAngle), -std::sin(rollAngle),\n 0.0, std::sin(rollAngle), std::cos(rollAngle),\n });\n\n arma::Mat<double>::fixed<3, 3> expectedPitch({\n std::cos(pitchAngle), 0.0, std::sin(pitchAngle),\n 0.0, 1.0, 0.0,\n -std::sin(pitchAngle), 0.0, std::cos(pitchAngle)\n });\n\n arma::Mat<double>::fixed<3, 3> expectedYaw({\n std::cos(yawAngle), -std::sin(yawAngle), 0.0,\n std::sin(yawAngle), std::cos(yawAngle), 0.0,\n 0.0, 0.0, 1.0\n });\n\n arma::Mat<double>::fixed<3, 3> expected = expectedRoll * expectedPitch * expectedYaw;\n\n CHECK(result.n_rows == 3);\n CHECK(result.n_cols == 3);\n\n for (std::size_t n = 0; n < expected.n_elem; ++n) {\n CHECK(result.at(n) == Approx(expected.at(n)));\n }\n }\n }\n }\n}\n\n<commit_msg>fix: resolve warnings<commit_after>\/\/ Catch\n#include <catch.hpp>\n\n\/\/ C++ Standard Library\n#include <cstdlib>\n#include <cmath>\n#include <array>\n\n\/\/ Armadillo\n#include <armadillo>\n\n\/\/ Mantella\n#include <mantella>\n\nTEST_CASE(\"Circle circle intersection\", \"\") {\n arma::Col<double>::fixed<2> result;\n arma::Col<double>::fixed<2> expected;\n\n result = mant::getCircleCircleIntersection({-2.0, 3.0}, 1.3, {-1.5, 2.4}, 1.2);\n expected = {-2.5522451636, 1.8231290303};\n for (std::size_t n = 0; n < expected.n_elem; ++n) {\n CHECK(result.at(n) == Approx(expected.at(n)));\n }\n\n result = mant::getCircleCircleIntersection({1.8, -2.5}, 4.0, {-3.0, 2.0}, 3.0);\n expected = {-0.1804143359, 0.9753358195};\n for (std::size_t n = 0; n < expected.n_elem; ++n) {\n CHECK(result.at(n) == Approx(expected.at(n)));\n }\n}\n\nTEST_CASE(\"Circle sphere intersection\", \"\") {\n arma::Col<double>::fixed<3> result;\n arma::Col<double>::fixed<3> expected;\n\n result = mant::getCircleSphereIntersection({-2.0, 0.0, 0.0}, 1.2, {0.0, 0.0, 1.0}, {-3.0, 0.0, 0.0}, 1.5);\n expected = {-2.095, 1.1962336728, 0.0};\n for (std::size_t n = 0; n < expected.n_elem; ++n) {\n CHECK(result.at(n) == Approx(expected.at(n)));\n }\n\n result = mant::getCircleSphereIntersection({-2.0, 3.0, 0.0}, 1.3, {0.0, 0.0, 1.0}, {-1.5, 2.4, 0.0}, 1.2);\n expected = {-2.5522451636, 1.8231290303, 0.0};\n for (std::size_t n = 0; n < expected.n_elem; ++n) {\n CHECK(result.at(n) == Approx(expected.at(n)));\n }\n\n result = mant::getCircleSphereIntersection({1.8, -2.5, 0.0}, 4.0, {0.0, 0.0, 1.0}, {-3.0, 2.0, 0.0}, 3.0);\n expected = {-0.1804143359, 0.9753358195, 0.0};\n for (std::size_t n = 0; n < expected.n_elem; ++n) {\n CHECK(result.at(n) == Approx(expected.at(n)));\n }\n}\n\nTEST_CASE(\"2D rotation matrix\", \"\") {\n std::array<double, 15> angles = {{0.0, 45.0, 90.0, 135.0, 180.0, 225.0, 270.0, 315.0, 360.0, -0.0, -45.0, -90.0, -180.0, -225.0, -315.0}};\n\n for (const auto& angle : angles) {\n arma::Mat<double> result = mant::get2DRotationMatrix(angle);\n\n arma::Mat<double>::fixed<2, 2> expected({\n std::cos(angle), -std::sin(angle),\n std::sin(angle), std::cos(angle)\n });\n\n CHECK(result.n_rows == 2);\n CHECK(result.n_cols == 2);\n\n for (std::size_t n = 0; n < expected.n_elem; ++n) {\n CHECK(result.at(n) == Approx(expected.at(n)));\n }\n }\n}\n\nTEST_CASE(\"3D rotation matrix\", \"\") {\n std::array<double, 14> rollAngles = {{0.0, 45.0, 90.0, 135.0, 180.0, 225, 270, 315, 360, -0, -45, 276, -56, -45.89}};\n std::array<double, 14> pitchAngles = {{0.0, 45.0, 90.0, 135.0, 180.0, 225, 270, 315, 360, -0, -90, -89, 78, -245}};\n std::array<double, 14> yawAngles = {{0.0, 45.0, 90.0, 135.0, 180.0, 225, 270, 315, 360, -0, -225, -310, -90, 345}};\n\n for (const auto& rollAngle : rollAngles) {\n for (const auto& pitchAngle : pitchAngles) {\n for (const auto& yawAngle : yawAngles) {\n arma::Mat<double> result = mant::get3DRotationMatrix(rollAngle, pitchAngle, yawAngle);\n\n arma::Mat<double>::fixed<3, 3> expectedRoll({\n 1.0, 0.0, 0.0,\n 0.0, std::cos(rollAngle), -std::sin(rollAngle),\n 0.0, std::sin(rollAngle), std::cos(rollAngle),\n });\n\n arma::Mat<double>::fixed<3, 3> expectedPitch({\n std::cos(pitchAngle), 0.0, std::sin(pitchAngle),\n 0.0, 1.0, 0.0,\n -std::sin(pitchAngle), 0.0, std::cos(pitchAngle)\n });\n\n arma::Mat<double>::fixed<3, 3> expectedYaw({\n std::cos(yawAngle), -std::sin(yawAngle), 0.0,\n std::sin(yawAngle), std::cos(yawAngle), 0.0,\n 0.0, 0.0, 1.0\n });\n\n arma::Mat<double>::fixed<3, 3> expected = expectedRoll * expectedPitch * expectedYaw;\n\n CHECK(result.n_rows == 3);\n CHECK(result.n_cols == 3);\n\n for (std::size_t n = 0; n < expected.n_elem; ++n) {\n CHECK(result.at(n) == Approx(expected.at(n)));\n }\n }\n }\n }\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/\/======================================================================\r\n\/\/-----------------------------------------------------------------------\r\n\/**\r\n * @file\t\tiutest_logger_tests.cpp\r\n * @brief\t\tlogger テスト\r\n *\r\n * @author\t\tt.sirayanagi\r\n * @version\t\t1.0\r\n *\r\n * @par\t\t\tcopyright\r\n * Copyright (C) 2014, Takazumi Shirayanagi\\n\r\n * This software is released under the new BSD License,\r\n * see LICENSE\r\n*\/\r\n\/\/-----------------------------------------------------------------------\r\n\/\/======================================================================\r\n\r\n\/\/======================================================================\r\n\/\/ include\r\n#include \"..\/include\/iutest.hpp\"\r\n\r\n#if !defined(IUTEST_USE_GTEST)\r\n\r\nclass TestLogger : public ::iutest::detail::iuLogger\r\n{\r\n\t::std::string m_log;\r\npublic:\r\n\tvirtual void voutput(const char* fmt, va_list va)\r\n\t{\r\n\t\tva_list va2;\r\n#ifndef va_copy\r\n\t\tva2 = va;\r\n#else\r\n\t\tva_copy(va2, va);\r\n#endif\r\n\t\tchar buf[4096];\r\n\t\tvsprintf(buf, fmt, va2);\r\n\t\tva_end(va2);\r\n\t\tm_log += buf;\r\n\t\t::iutest::detail::iuConsole::voutput(fmt, va);\r\n\t}\r\n\tvoid clear(void) { m_log.clear(); }\r\npublic:\r\n\tconst char* c_str(void) const { return m_log.c_str(); }\r\n};\r\n\r\n#endif\r\n<commit_msg>update r511<commit_after>\/\/======================================================================\r\n\/\/-----------------------------------------------------------------------\r\n\/**\r\n * @file\t\tiutest_logger_tests.cpp\r\n * @brief\t\tlogger テスト\r\n *\r\n * @author\t\tt.sirayanagi\r\n * @version\t\t1.0\r\n *\r\n * @par\t\t\tcopyright\r\n * Copyright (C) 2014, Takazumi Shirayanagi\\n\r\n * This software is released under the new BSD License,\r\n * see LICENSE\r\n*\/\r\n\/\/-----------------------------------------------------------------------\r\n\/\/======================================================================\r\n\r\n\/\/======================================================================\r\n\/\/ include\r\n#include \"..\/include\/iutest.hpp\"\r\n\r\n#if !defined(IUTEST_USE_GTEST)\r\n\r\nclass TestLogger : public ::iutest::detail::iuLogger\r\n{\r\n\t::std::string m_log;\r\npublic:\r\n\tvirtual void voutput(const char* fmt, va_list va)\r\n\t{\r\n#ifdef va_copy\r\n\t\tva_list va2;\r\n\t\tva_copy(va2, va);\r\n\t\tchar buf[4096];\r\n\t\tvsprintf(buf, fmt, va2);\r\n\t\tva_end(va2);\r\n\t\tm_log += buf;\r\n\t\t::iutest::detail::iuConsole::voutput(fmt, va);\r\n#else\r\n\t\tchar buf[4096];\r\n\t\tvsprintf(buf, fmt, va);\r\n\t\tm_log += buf;\r\n\t\t::iutest::detail::iuConsole::output(buf);\r\n#endif\r\n\t}\r\n\tvoid clear(void) { m_log.clear(); }\r\npublic:\r\n\tconst char* c_str(void) const { return m_log.c_str(); }\r\n};\r\n\r\n#endif\r\n<|endoftext|>"} {"text":"<commit_before>\/\/ This file is part of Eigen, a lightweight C++ template library\n\/\/ for linear algebra.\n\/\/\n\/\/ Copyright (C) 2006-2008 Benoit Jacob <jacob.benoit.1@gmail.com>\n\/\/\n\/\/ Eigen is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU Lesser General Public\n\/\/ License as published by the Free Software Foundation; either\n\/\/ version 3 of the License, or (at your option) any later version.\n\/\/\n\/\/ Alternatively, you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU General Public License as\n\/\/ published by the Free Software Foundation; either version 2 of\n\/\/ the License, or (at your option) any later version.\n\/\/\n\/\/ Eigen is distributed in the hope that it will be useful, but WITHOUT ANY\n\/\/ WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n\/\/ FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the\n\/\/ GNU General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License and a copy of the GNU General Public License along with\n\/\/ Eigen. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n\nstatic int nb_temporaries;\n\n#define EIGEN_DEBUG_MATRIX_CTOR(MTYPE) { \\\n if(MTYPE::SizeAtCompileTime==Dynamic) \\\n nb_temporaries++; \\\n }\n\n#include \"main.h\"\n#include <Eigen\/Array>\n\n#define VERIFY_EVALUATION_COUNT(XPR,N) {\\\n nb_temporaries = 0; \\\n XPR; \\\n if(nb_temporaries!=N) std::cerr << \"nb_temporaries == \" << nb_temporaries << \"\\n\"; \\\n VERIFY( (#XPR) && nb_temporaries==N ); \\\n }\n\ntemplate<typename MatrixType> void product_notemporary(const MatrixType& m)\n{\n \/* This test checks the number of tempories created\n * during the evaluation of a complex expression *\/\n\n typedef typename MatrixType::Scalar Scalar;\n typedef Matrix<Scalar, 1, Dynamic> RowVectorType;\n typedef Matrix<Scalar, Dynamic, 1> ColVectorType;\n typedef Matrix<Scalar, Dynamic, Dynamic, RowMajor> RowMajorMatrixType;\n\n int rows = m.rows();\n int cols = m.cols();\n\n MatrixType m1 = MatrixType::Random(rows, cols),\n m2 = MatrixType::Random(rows, cols),\n m3(rows, cols);\n RowVectorType rv1 = RowVectorType::Random(rows), rvres(rows);\n ColVectorType vc2 = ColVectorType::Random(cols), cvres(cols);\n RowMajorMatrixType rm3(rows, cols);\n\n Scalar s1 = ei_random<Scalar>(),\n s2 = ei_random<Scalar>(),\n s3 = ei_random<Scalar>();\n\n int c0 = ei_random<int>(4,cols-8),\n c1 = ei_random<int>(8,cols-c0),\n r0 = ei_random<int>(4,cols-8),\n r1 = ei_random<int>(8,rows-r0);\n\n VERIFY_EVALUATION_COUNT( m3 = (m1 * m2.adjoint()), 1);\n VERIFY_EVALUATION_COUNT( m3 = (m1 * m2.adjoint()).lazy(), 0);\n VERIFY_EVALUATION_COUNT( m3.noalias() = m1 * m2.adjoint(), 0);\n\n \/\/ NOTE in this case the slow product is used:\n \/\/ FIXME:\n VERIFY_EVALUATION_COUNT( m3.noalias() = s1 * (m1 * m2.transpose()), 0);\n\n VERIFY_EVALUATION_COUNT( m3.noalias() = s1 * m1 * s2 * m2.adjoint(), 0);\n VERIFY_EVALUATION_COUNT( m3.noalias() = s1 * m1 * s2 * (m1*s3+m2*s2).adjoint(), 1);\n VERIFY_EVALUATION_COUNT( m3.noalias() = (s1 * m1).adjoint() * s2 * m2, 0);\n VERIFY_EVALUATION_COUNT( m3 += (s1 * (-m1*s3).adjoint() * (s2 * m2 * s3)).lazy(), 0);\n VERIFY_EVALUATION_COUNT( m3.noalias() += s1 * (-m1*s3).adjoint() * (s2 * m2 * s3), 0);\n VERIFY_EVALUATION_COUNT( m3 -= (s1 * (m1.transpose() * m2)).lazy(), 0);\n VERIFY_EVALUATION_COUNT( m3.noalias() -= s1 * (m1.transpose() * m2), 0);\n\n VERIFY_EVALUATION_COUNT(( m3.block(r0,r0,r1,r1).noalias() += -m1.block(r0,c0,r1,c1) * (s2*m2.block(r0,c0,r1,c1)).adjoint() ), 0);\n VERIFY_EVALUATION_COUNT(( m3.block(r0,r0,r1,r1).noalias() -= s1 * m1.block(r0,c0,r1,c1) * m2.block(c0,r0,c1,r1) ), 0);\n\n \/\/ NOTE this is because the Block expression is not handled yet by our expression analyser\n VERIFY_EVALUATION_COUNT(( m3.block(r0,r0,r1,r1) = (s1 * m1.block(r0,c0,r1,c1) * (s1*m2).block(c0,r0,c1,r1)).lazy() ), 1);\n\n VERIFY_EVALUATION_COUNT( m3.noalias() -= (s1 * m1).template triangularView<LowerTriangular>() * m2, 0);\n VERIFY_EVALUATION_COUNT( rm3.noalias() = (s1 * m1.adjoint()).template triangularView<UpperTriangular>() * (m2+m2), 1);\n VERIFY_EVALUATION_COUNT( rm3.noalias() = (s1 * m1.adjoint()).template triangularView<UnitUpperTriangular>() * m2.adjoint(), 0);\n\n VERIFY_EVALUATION_COUNT( rm3.col(c0).noalias() = (s1 * m1.adjoint()).template triangularView<UnitUpperTriangular>() * (s2*m2.row(c0)).adjoint(), 0);\n\n VERIFY_EVALUATION_COUNT( m1.template triangularView<LowerTriangular>().solveInPlace(m3), 0);\n VERIFY_EVALUATION_COUNT( m1.adjoint().template triangularView<LowerTriangular>().solveInPlace(m3.transpose()), 0);\n\n VERIFY_EVALUATION_COUNT( m3.noalias() -= (s1 * m1).adjoint().template selfadjointView<LowerTriangular>() * (-m2*s3).adjoint(), 0);\n VERIFY_EVALUATION_COUNT( m3.noalias() = s2 * m2.adjoint() * (s1 * m1.adjoint()).template selfadjointView<UpperTriangular>(), 0);\n VERIFY_EVALUATION_COUNT( rm3.noalias() = (s1 * m1.adjoint()).template selfadjointView<LowerTriangular>() * m2.adjoint(), 0);\n\n VERIFY_EVALUATION_COUNT( m3.col(c0).noalias() = (s1 * m1).adjoint().template selfadjointView<LowerTriangular>() * (-m2.row(c0)*s3).adjoint(), 0);\n VERIFY_EVALUATION_COUNT( m3.col(c0).noalias() -= (s1 * m1).adjoint().template selfadjointView<UpperTriangular>() * (-m2.row(c0)*s3).adjoint(), 0);\n\n VERIFY_EVALUATION_COUNT( m3.block(r0,c0,r1,c1).noalias() += m1.block(r0,r0,r1,r1).template selfadjointView<UpperTriangular>() * (s1*m2.block(r0,c0,r1,c1)), 0);\n VERIFY_EVALUATION_COUNT( m3.block(r0,c0,r1,c1).noalias() = m1.block(r0,r0,r1,r1).template selfadjointView<UpperTriangular>() * m2.block(r0,c0,r1,c1), 0);\n\n VERIFY_EVALUATION_COUNT( m3.template selfadjointView<LowerTriangular>().rankUpdate(m2.adjoint()), 0);\n\n m3.resize(1,1);\n VERIFY_EVALUATION_COUNT( m3.noalias() = m1.block(r0,r0,r1,r1).template selfadjointView<LowerTriangular>() * m2.block(r0,c0,r1,c1), 0);\n m3.resize(1,1);\n VERIFY_EVALUATION_COUNT( m3.noalias() = m1.block(r0,r0,r1,r1).template triangularView<UnitUpperTriangular>() * m2.block(r0,c0,r1,c1), 0);\n}\n\nvoid test_product_notemporary()\n{\n int s;\n for(int i = 0; i < g_repeat; i++) {\n s = ei_random<int>(16,320);\n CALL_SUBTEST( product_notemporary(MatrixXf(s, s)) );\n s = ei_random<int>(16,120);\n CALL_SUBTEST( product_notemporary(MatrixXcd(s,s)) );\n }\n}\n<commit_msg>Remove last lazyness warnings.<commit_after>\/\/ This file is part of Eigen, a lightweight C++ template library\n\/\/ for linear algebra.\n\/\/\n\/\/ Copyright (C) 2006-2008 Benoit Jacob <jacob.benoit.1@gmail.com>\n\/\/\n\/\/ Eigen is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU Lesser General Public\n\/\/ License as published by the Free Software Foundation; either\n\/\/ version 3 of the License, or (at your option) any later version.\n\/\/\n\/\/ Alternatively, you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU General Public License as\n\/\/ published by the Free Software Foundation; either version 2 of\n\/\/ the License, or (at your option) any later version.\n\/\/\n\/\/ Eigen is distributed in the hope that it will be useful, but WITHOUT ANY\n\/\/ WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n\/\/ FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the\n\/\/ GNU General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License and a copy of the GNU General Public License along with\n\/\/ Eigen. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n\nstatic int nb_temporaries;\n\n#define EIGEN_DEBUG_MATRIX_CTOR(MTYPE) { \\\n if(MTYPE::SizeAtCompileTime==Dynamic) \\\n nb_temporaries++; \\\n }\n\n#include \"main.h\"\n#include <Eigen\/Array>\n\n#define VERIFY_EVALUATION_COUNT(XPR,N) {\\\n nb_temporaries = 0; \\\n XPR; \\\n if(nb_temporaries!=N) std::cerr << \"nb_temporaries == \" << nb_temporaries << \"\\n\"; \\\n VERIFY( (#XPR) && nb_temporaries==N ); \\\n }\n\ntemplate<typename MatrixType> void product_notemporary(const MatrixType& m)\n{\n \/* This test checks the number of tempories created\n * during the evaluation of a complex expression *\/\n\n typedef typename MatrixType::Scalar Scalar;\n typedef Matrix<Scalar, 1, Dynamic> RowVectorType;\n typedef Matrix<Scalar, Dynamic, 1> ColVectorType;\n typedef Matrix<Scalar, Dynamic, Dynamic, RowMajor> RowMajorMatrixType;\n\n int rows = m.rows();\n int cols = m.cols();\n\n MatrixType m1 = MatrixType::Random(rows, cols),\n m2 = MatrixType::Random(rows, cols),\n m3(rows, cols);\n RowVectorType rv1 = RowVectorType::Random(rows), rvres(rows);\n ColVectorType vc2 = ColVectorType::Random(cols), cvres(cols);\n RowMajorMatrixType rm3(rows, cols);\n\n Scalar s1 = ei_random<Scalar>(),\n s2 = ei_random<Scalar>(),\n s3 = ei_random<Scalar>();\n\n int c0 = ei_random<int>(4,cols-8),\n c1 = ei_random<int>(8,cols-c0),\n r0 = ei_random<int>(4,cols-8),\n r1 = ei_random<int>(8,rows-r0);\n\n VERIFY_EVALUATION_COUNT( m3 = (m1 * m2.adjoint()), 1);\n VERIFY_EVALUATION_COUNT( m3.noalias() = m1 * m2.adjoint(), 0);\n\n \/\/ NOTE in this case the slow product is used:\n \/\/ FIXME:\n VERIFY_EVALUATION_COUNT( m3.noalias() = s1 * (m1 * m2.transpose()), 0);\n\n VERIFY_EVALUATION_COUNT( m3.noalias() = s1 * m1 * s2 * m2.adjoint(), 0);\n VERIFY_EVALUATION_COUNT( m3.noalias() = s1 * m1 * s2 * (m1*s3+m2*s2).adjoint(), 1);\n VERIFY_EVALUATION_COUNT( m3.noalias() = (s1 * m1).adjoint() * s2 * m2, 0);\n VERIFY_EVALUATION_COUNT( m3.noalias() += s1 * (-m1*s3).adjoint() * (s2 * m2 * s3), 0);\n VERIFY_EVALUATION_COUNT( m3.noalias() -= s1 * (m1.transpose() * m2), 0);\n\n VERIFY_EVALUATION_COUNT(( m3.block(r0,r0,r1,r1).noalias() += -m1.block(r0,c0,r1,c1) * (s2*m2.block(r0,c0,r1,c1)).adjoint() ), 0);\n VERIFY_EVALUATION_COUNT(( m3.block(r0,r0,r1,r1).noalias() -= s1 * m1.block(r0,c0,r1,c1) * m2.block(c0,r0,c1,r1) ), 0);\n\n \/\/ NOTE this is because the Block expression is not handled yet by our expression analyser\n VERIFY_EVALUATION_COUNT(( m3.block(r0,r0,r1,r1).noalias() = s1 * m1.block(r0,c0,r1,c1) * (s1*m2).block(c0,r0,c1,r1) ), 1);\n\n VERIFY_EVALUATION_COUNT( m3.noalias() -= (s1 * m1).template triangularView<LowerTriangular>() * m2, 0);\n VERIFY_EVALUATION_COUNT( rm3.noalias() = (s1 * m1.adjoint()).template triangularView<UpperTriangular>() * (m2+m2), 1);\n VERIFY_EVALUATION_COUNT( rm3.noalias() = (s1 * m1.adjoint()).template triangularView<UnitUpperTriangular>() * m2.adjoint(), 0);\n\n VERIFY_EVALUATION_COUNT( rm3.col(c0).noalias() = (s1 * m1.adjoint()).template triangularView<UnitUpperTriangular>() * (s2*m2.row(c0)).adjoint(), 0);\n\n VERIFY_EVALUATION_COUNT( m1.template triangularView<LowerTriangular>().solveInPlace(m3), 0);\n VERIFY_EVALUATION_COUNT( m1.adjoint().template triangularView<LowerTriangular>().solveInPlace(m3.transpose()), 0);\n\n VERIFY_EVALUATION_COUNT( m3.noalias() -= (s1 * m1).adjoint().template selfadjointView<LowerTriangular>() * (-m2*s3).adjoint(), 0);\n VERIFY_EVALUATION_COUNT( m3.noalias() = s2 * m2.adjoint() * (s1 * m1.adjoint()).template selfadjointView<UpperTriangular>(), 0);\n VERIFY_EVALUATION_COUNT( rm3.noalias() = (s1 * m1.adjoint()).template selfadjointView<LowerTriangular>() * m2.adjoint(), 0);\n\n VERIFY_EVALUATION_COUNT( m3.col(c0).noalias() = (s1 * m1).adjoint().template selfadjointView<LowerTriangular>() * (-m2.row(c0)*s3).adjoint(), 0);\n VERIFY_EVALUATION_COUNT( m3.col(c0).noalias() -= (s1 * m1).adjoint().template selfadjointView<UpperTriangular>() * (-m2.row(c0)*s3).adjoint(), 0);\n\n VERIFY_EVALUATION_COUNT( m3.block(r0,c0,r1,c1).noalias() += m1.block(r0,r0,r1,r1).template selfadjointView<UpperTriangular>() * (s1*m2.block(r0,c0,r1,c1)), 0);\n VERIFY_EVALUATION_COUNT( m3.block(r0,c0,r1,c1).noalias() = m1.block(r0,r0,r1,r1).template selfadjointView<UpperTriangular>() * m2.block(r0,c0,r1,c1), 0);\n\n VERIFY_EVALUATION_COUNT( m3.template selfadjointView<LowerTriangular>().rankUpdate(m2.adjoint()), 0);\n\n m3.resize(1,1);\n VERIFY_EVALUATION_COUNT( m3.noalias() = m1.block(r0,r0,r1,r1).template selfadjointView<LowerTriangular>() * m2.block(r0,c0,r1,c1), 0);\n m3.resize(1,1);\n VERIFY_EVALUATION_COUNT( m3.noalias() = m1.block(r0,r0,r1,r1).template triangularView<UnitUpperTriangular>() * m2.block(r0,c0,r1,c1), 0);\n}\n\nvoid test_product_notemporary()\n{\n int s;\n for(int i = 0; i < g_repeat; i++) {\n s = ei_random<int>(16,320);\n CALL_SUBTEST( product_notemporary(MatrixXf(s, s)) );\n s = ei_random<int>(16,120);\n CALL_SUBTEST( product_notemporary(MatrixXcd(s,s)) );\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n __ _____ _____ _____\n __| | __| | | | JSON for Modern C++ (test suite)\n| | |__ | | | | | | version 2.1.1\n|_____|_____|_____|_|___| https:\/\/github.com\/nlohmann\/json\n\nLicensed under the MIT License <http:\/\/opensource.org\/licenses\/MIT>.\nCopyright (c) 2013-2017 Niels Lohmann <http:\/\/nlohmann.me>.\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n*\/\n\n#include \"catch.hpp\"\n\n#include \"json.hpp\"\nusing nlohmann::json;\n\nTEST_CASE(\"algorithms\")\n{\n json j_array = {13, 29, 3, {{\"one\", 1}, {\"two\", 2}}, true, false, {1, 2, 3}, \"foo\", \"baz\"};\n json j_object = {{\"one\", 1}, {\"two\", 2}};\n\n SECTION(\"non-modifying sequence operations\")\n {\n SECTION(\"std::all_of\")\n {\n CHECK(std::all_of(j_array.begin(), j_array.end(), [](const json & value)\n {\n return value.size() > 0;\n }));\n CHECK(std::all_of(j_object.begin(), j_object.end(), [](const json & value)\n {\n return value.type() == json::value_t::number_integer;\n }));\n }\n\n SECTION(\"std::any_of\")\n {\n CHECK(std::any_of(j_array.begin(), j_array.end(), [](const json & value)\n {\n return value.is_string() and value.get<std::string>() == \"foo\";\n }));\n CHECK(std::any_of(j_object.begin(), j_object.end(), [](const json & value)\n {\n return value.get<int>() > 1;\n }));\n }\n\n SECTION(\"std::none_of\")\n {\n CHECK(std::none_of(j_array.begin(), j_array.end(), [](const json & value)\n {\n return value.size() == 0;\n }));\n CHECK(std::none_of(j_object.begin(), j_object.end(), [](const json & value)\n {\n return value.get<int>() <= 0;\n }));\n }\n\n SECTION(\"std::for_each\")\n {\n SECTION(\"reading\")\n {\n int sum = 0;\n\n std::for_each(j_array.cbegin(), j_array.cend(), [&sum](const json & value)\n {\n if (value.is_number())\n {\n sum += static_cast<int>(value);\n }\n });\n\n CHECK(sum == 45);\n }\n\n SECTION(\"writing\")\n {\n auto add17 = [](json & value)\n {\n if (value.is_array())\n {\n value.push_back(17);\n }\n };\n\n std::for_each(j_array.begin(), j_array.end(), add17);\n\n CHECK(j_array[6] == json({1, 2, 3, 17}));\n }\n }\n\n SECTION(\"std::count\")\n {\n CHECK(std::count(j_array.begin(), j_array.end(), json(true)) == 1);\n }\n\n SECTION(\"std::count_if\")\n {\n CHECK(std::count_if(j_array.begin(), j_array.end(), [](const json & value)\n {\n return (value.is_number());\n }) == 3);\n CHECK(std::count_if(j_array.begin(), j_array.end(), [](const json&)\n {\n return true;\n }) == 9);\n }\n\n SECTION(\"std::mismatch\")\n {\n json j_array2 = {13, 29, 3, {{\"one\", 1}, {\"two\", 2}, {\"three\", 3}}, true, false, {1, 2, 3}, \"foo\", \"baz\"};\n auto res = std::mismatch(j_array.begin(), j_array.end(), j_array2.begin());\n CHECK(*res.first == json({{\"one\", 1}, {\"two\", 2}}));\n CHECK(*res.second == json({{\"one\", 1}, {\"two\", 2}, {\"three\", 3}}));\n }\n\n SECTION(\"std::equal\")\n {\n SECTION(\"using operator==\")\n {\n CHECK(std::equal(j_array.begin(), j_array.end(), j_array.begin()));\n CHECK(std::equal(j_object.begin(), j_object.end(), j_object.begin()));\n CHECK(not std::equal(j_array.begin(), j_array.end(), j_object.begin()));\n }\n\n SECTION(\"using user-defined comparison\")\n {\n \/\/ compare objects only by size of its elements\n json j_array2 = {13, 29, 3, {\"Hello\", \"World\"}, true, false, {{\"one\", 1}, {\"two\", 2}, {\"three\", 3}}, \"foo\", \"baz\"};\n CHECK(not std::equal(j_array.begin(), j_array.end(), j_array2.begin()));\n CHECK(std::equal(j_array.begin(), j_array.end(), j_array2.begin(),\n [](const json & a, const json & b)\n {\n return (a.size() == b.size());\n }));\n }\n }\n\n SECTION(\"std::find\")\n {\n auto it = std::find(j_array.begin(), j_array.end(), json(false));\n CHECK(std::distance(j_array.begin(), it) == 5);\n }\n\n SECTION(\"std::find_if\")\n {\n auto it = std::find_if(j_array.begin(), j_array.end(),\n [](const json & value)\n {\n return value.is_boolean();\n });\n CHECK(std::distance(j_array.begin(), it) == 4);\n }\n\n SECTION(\"std::find_if_not\")\n {\n auto it = std::find_if_not(j_array.begin(), j_array.end(),\n [](const json & value)\n {\n return value.is_number();\n });\n CHECK(std::distance(j_array.begin(), it) == 3);\n }\n\n SECTION(\"std::adjacent_find\")\n {\n CHECK(std::adjacent_find(j_array.begin(), j_array.end()) == j_array.end());\n CHECK(std::adjacent_find(j_array.begin(), j_array.end(),\n [](const json & v1, const json & v2)\n {\n return v1.type() == v2.type();\n }) == j_array.begin());\n }\n }\n\n SECTION(\"modifying sequence operations\")\n {\n SECTION(\"std::reverse\")\n {\n std::reverse(j_array.begin(), j_array.end());\n CHECK(j_array == json({\"baz\", \"foo\", {1, 2, 3}, false, true, {{\"one\", 1}, {\"two\", 2}}, 3, 29, 13}));\n }\n\n SECTION(\"std::rotate\")\n {\n std::rotate(j_array.begin(), j_array.begin() + 1, j_array.end());\n CHECK(j_array == json({29, 3, {{\"one\", 1}, {\"two\", 2}}, true, false, {1, 2, 3}, \"foo\", \"baz\", 13}));\n }\n\n SECTION(\"std::partition\")\n {\n auto it = std::partition(j_array.begin(), j_array.end(), [](const json & v)\n {\n return v.is_string();\n });\n CHECK(std::distance(j_array.begin(), it) == 2);\n CHECK(not it[2].is_string());\n }\n }\n\n SECTION(\"sorting operations\")\n {\n SECTION(\"std::sort\")\n {\n SECTION(\"with standard comparison\")\n {\n json j = {13, 29, 3, {{\"one\", 1}, {\"two\", 2}}, true, false, {1, 2, 3}, \"foo\", \"baz\", nullptr};\n std::sort(j.begin(), j.end());\n CHECK(j == json({nullptr, false, true, 3, 13, 29, {{\"one\", 1}, {\"two\", 2}}, {1, 2, 3}, \"baz\", \"foo\"}));\n }\n\n SECTION(\"with user-defined comparison\")\n {\n json j = {3, {{\"one\", 1}, {\"two\", 2}}, {1, 2, 3}, nullptr};\n std::sort(j.begin(), j.end(), [](const json & a, const json & b)\n {\n return a.size() < b.size();\n });\n CHECK(j == json({nullptr, 3, {{\"one\", 1}, {\"two\", 2}}, {1, 2, 3}}));\n }\n\n SECTION(\"sorting an object\")\n {\n json j({{\"one\", 1}, {\"two\", 2}});\n CHECK_THROWS_AS(std::sort(j.begin(), j.end()), json::invalid_iterator&);\n CHECK_THROWS_WITH(std::sort(j.begin(), j.end()),\n \"[json.exception.invalid_iterator.209] cannot use offsets with object iterators\");\n }\n }\n\n SECTION(\"std::partial_sort\")\n {\n json j = {13, 29, 3, {{\"one\", 1}, {\"two\", 2}}, true, false, {1, 2, 3}, \"foo\", \"baz\", nullptr};\n std::partial_sort(j.begin(), j.begin() + 4, j.end());\n CHECK(j == json({nullptr, false, true, 3, {{\"one\", 1}, {\"two\", 2}}, 29, {1, 2, 3}, \"foo\", \"baz\", 13}));\n }\n }\n\n SECTION(\"set operations\")\n {\n \/*\n SECTION(\"std::merge\")\n {\n {\n json j1 = {2, 4, 6, 8};\n json j2 = {1, 2, 3, 5, 7};\n json j3;\n\n std::merge(j1.begin(), j1.end(), j2.begin(), j2.end(), std::back_inserter(j3));\n CHECK(j3 == json({1, 2, 2, 3, 4, 5, 6, 7, 8}));\n }\n }\n *\/\n\n SECTION(\"std::set_difference\")\n {\n json j1 = {1, 2, 3, 4, 5, 6, 7, 8};\n json j2 = {1, 2, 3, 5, 7};\n json j3;\n\n std::set_difference(j1.begin(), j1.end(), j2.begin(), j2.end(), std::back_inserter(j3));\n CHECK(j3 == json({4, 6, 8}));\n }\n\n SECTION(\"std::set_intersection\")\n {\n json j1 = {1, 2, 3, 4, 5, 6, 7, 8};\n json j2 = {1, 2, 3, 5, 7};\n json j3;\n\n std::set_intersection(j1.begin(), j1.end(), j2.begin(), j2.end(), std::back_inserter(j3));\n CHECK(j3 == json({1, 2, 3, 5, 7}));\n }\n\n \/*\n SECTION(\"std::set_union\")\n {\n json j1 = {2, 4, 6, 8};\n json j2 = {1, 2, 3, 5, 7};\n json j3;\n\n std::set_union(j1.begin(), j1.end(), j2.begin(), j2.end(), std::back_inserter(j3));\n CHECK(j3 == json({1, 2, 3, 4, 5, 6, 7, 8}));\n }\n\n SECTION(\"std::set_symmetric_difference\")\n {\n json j1 = {2, 4, 6, 8};\n json j2 = {1, 2, 3, 5, 7};\n json j3;\n\n std::set_symmetric_difference(j1.begin(), j1.end(), j2.begin(), j2.end(), std::back_inserter(j3));\n CHECK(j3 == json({1, 3, 4, 5, 6, 7, 8}));\n }\n *\/\n }\n\n SECTION(\"heap operations\")\n {\n std::make_heap(j_array.begin(), j_array.end());\n CHECK(std::is_heap(j_array.begin(), j_array.end()));\n std::sort_heap(j_array.begin(), j_array.end());\n CHECK(j_array == json({false, true, 3, 13, 29, {{\"one\", 1}, {\"two\", 2}}, {1, 2, 3}, \"baz\", \"foo\"}));\n }\n}\n<commit_msg>:white_check_mark: re-added tests for algorithms<commit_after>\/*\n __ _____ _____ _____\n __| | __| | | | JSON for Modern C++ (test suite)\n| | |__ | | | | | | version 2.1.1\n|_____|_____|_____|_|___| https:\/\/github.com\/nlohmann\/json\n\nLicensed under the MIT License <http:\/\/opensource.org\/licenses\/MIT>.\nCopyright (c) 2013-2017 Niels Lohmann <http:\/\/nlohmann.me>.\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n*\/\n\n#include \"catch.hpp\"\n\n#include \"json.hpp\"\nusing nlohmann::json;\n\nTEST_CASE(\"algorithms\")\n{\n json j_array = {13, 29, 3, {{\"one\", 1}, {\"two\", 2}}, true, false, {1, 2, 3}, \"foo\", \"baz\"};\n json j_object = {{\"one\", 1}, {\"two\", 2}};\n\n SECTION(\"non-modifying sequence operations\")\n {\n SECTION(\"std::all_of\")\n {\n CHECK(std::all_of(j_array.begin(), j_array.end(), [](const json & value)\n {\n return value.size() > 0;\n }));\n CHECK(std::all_of(j_object.begin(), j_object.end(), [](const json & value)\n {\n return value.type() == json::value_t::number_integer;\n }));\n }\n\n SECTION(\"std::any_of\")\n {\n CHECK(std::any_of(j_array.begin(), j_array.end(), [](const json & value)\n {\n return value.is_string() and value.get<std::string>() == \"foo\";\n }));\n CHECK(std::any_of(j_object.begin(), j_object.end(), [](const json & value)\n {\n return value.get<int>() > 1;\n }));\n }\n\n SECTION(\"std::none_of\")\n {\n CHECK(std::none_of(j_array.begin(), j_array.end(), [](const json & value)\n {\n return value.size() == 0;\n }));\n CHECK(std::none_of(j_object.begin(), j_object.end(), [](const json & value)\n {\n return value.get<int>() <= 0;\n }));\n }\n\n SECTION(\"std::for_each\")\n {\n SECTION(\"reading\")\n {\n int sum = 0;\n\n std::for_each(j_array.cbegin(), j_array.cend(), [&sum](const json & value)\n {\n if (value.is_number())\n {\n sum += static_cast<int>(value);\n }\n });\n\n CHECK(sum == 45);\n }\n\n SECTION(\"writing\")\n {\n auto add17 = [](json & value)\n {\n if (value.is_array())\n {\n value.push_back(17);\n }\n };\n\n std::for_each(j_array.begin(), j_array.end(), add17);\n\n CHECK(j_array[6] == json({1, 2, 3, 17}));\n }\n }\n\n SECTION(\"std::count\")\n {\n CHECK(std::count(j_array.begin(), j_array.end(), json(true)) == 1);\n }\n\n SECTION(\"std::count_if\")\n {\n CHECK(std::count_if(j_array.begin(), j_array.end(), [](const json & value)\n {\n return (value.is_number());\n }) == 3);\n CHECK(std::count_if(j_array.begin(), j_array.end(), [](const json&)\n {\n return true;\n }) == 9);\n }\n\n SECTION(\"std::mismatch\")\n {\n json j_array2 = {13, 29, 3, {{\"one\", 1}, {\"two\", 2}, {\"three\", 3}}, true, false, {1, 2, 3}, \"foo\", \"baz\"};\n auto res = std::mismatch(j_array.begin(), j_array.end(), j_array2.begin());\n CHECK(*res.first == json({{\"one\", 1}, {\"two\", 2}}));\n CHECK(*res.second == json({{\"one\", 1}, {\"two\", 2}, {\"three\", 3}}));\n }\n\n SECTION(\"std::equal\")\n {\n SECTION(\"using operator==\")\n {\n CHECK(std::equal(j_array.begin(), j_array.end(), j_array.begin()));\n CHECK(std::equal(j_object.begin(), j_object.end(), j_object.begin()));\n CHECK(not std::equal(j_array.begin(), j_array.end(), j_object.begin()));\n }\n\n SECTION(\"using user-defined comparison\")\n {\n \/\/ compare objects only by size of its elements\n json j_array2 = {13, 29, 3, {\"Hello\", \"World\"}, true, false, {{\"one\", 1}, {\"two\", 2}, {\"three\", 3}}, \"foo\", \"baz\"};\n CHECK(not std::equal(j_array.begin(), j_array.end(), j_array2.begin()));\n CHECK(std::equal(j_array.begin(), j_array.end(), j_array2.begin(),\n [](const json & a, const json & b)\n {\n return (a.size() == b.size());\n }));\n }\n }\n\n SECTION(\"std::find\")\n {\n auto it = std::find(j_array.begin(), j_array.end(), json(false));\n CHECK(std::distance(j_array.begin(), it) == 5);\n }\n\n SECTION(\"std::find_if\")\n {\n auto it = std::find_if(j_array.begin(), j_array.end(),\n [](const json & value)\n {\n return value.is_boolean();\n });\n CHECK(std::distance(j_array.begin(), it) == 4);\n }\n\n SECTION(\"std::find_if_not\")\n {\n auto it = std::find_if_not(j_array.begin(), j_array.end(),\n [](const json & value)\n {\n return value.is_number();\n });\n CHECK(std::distance(j_array.begin(), it) == 3);\n }\n\n SECTION(\"std::adjacent_find\")\n {\n CHECK(std::adjacent_find(j_array.begin(), j_array.end()) == j_array.end());\n CHECK(std::adjacent_find(j_array.begin(), j_array.end(),\n [](const json & v1, const json & v2)\n {\n return v1.type() == v2.type();\n }) == j_array.begin());\n }\n }\n\n SECTION(\"modifying sequence operations\")\n {\n SECTION(\"std::reverse\")\n {\n std::reverse(j_array.begin(), j_array.end());\n CHECK(j_array == json({\"baz\", \"foo\", {1, 2, 3}, false, true, {{\"one\", 1}, {\"two\", 2}}, 3, 29, 13}));\n }\n\n SECTION(\"std::rotate\")\n {\n std::rotate(j_array.begin(), j_array.begin() + 1, j_array.end());\n CHECK(j_array == json({29, 3, {{\"one\", 1}, {\"two\", 2}}, true, false, {1, 2, 3}, \"foo\", \"baz\", 13}));\n }\n\n SECTION(\"std::partition\")\n {\n auto it = std::partition(j_array.begin(), j_array.end(), [](const json & v)\n {\n return v.is_string();\n });\n CHECK(std::distance(j_array.begin(), it) == 2);\n CHECK(not it[2].is_string());\n }\n }\n\n SECTION(\"sorting operations\")\n {\n SECTION(\"std::sort\")\n {\n SECTION(\"with standard comparison\")\n {\n json j = {13, 29, 3, {{\"one\", 1}, {\"two\", 2}}, true, false, {1, 2, 3}, \"foo\", \"baz\", nullptr};\n std::sort(j.begin(), j.end());\n CHECK(j == json({nullptr, false, true, 3, 13, 29, {{\"one\", 1}, {\"two\", 2}}, {1, 2, 3}, \"baz\", \"foo\"}));\n }\n\n SECTION(\"with user-defined comparison\")\n {\n json j = {3, {{\"one\", 1}, {\"two\", 2}}, {1, 2, 3}, nullptr};\n std::sort(j.begin(), j.end(), [](const json & a, const json & b)\n {\n return a.size() < b.size();\n });\n CHECK(j == json({nullptr, 3, {{\"one\", 1}, {\"two\", 2}}, {1, 2, 3}}));\n }\n\n SECTION(\"sorting an object\")\n {\n json j({{\"one\", 1}, {\"two\", 2}});\n CHECK_THROWS_AS(std::sort(j.begin(), j.end()), json::invalid_iterator&);\n CHECK_THROWS_WITH(std::sort(j.begin(), j.end()),\n \"[json.exception.invalid_iterator.209] cannot use offsets with object iterators\");\n }\n }\n\n SECTION(\"std::partial_sort\")\n {\n json j = {13, 29, 3, {{\"one\", 1}, {\"two\", 2}}, true, false, {1, 2, 3}, \"foo\", \"baz\", nullptr};\n std::partial_sort(j.begin(), j.begin() + 4, j.end());\n CHECK(j == json({nullptr, false, true, 3, {{\"one\", 1}, {\"two\", 2}}, 29, {1, 2, 3}, \"foo\", \"baz\", 13}));\n }\n }\n\n SECTION(\"set operations\")\n {\n SECTION(\"std::merge\")\n {\n {\n json j1 = {2, 4, 6, 8};\n json j2 = {1, 2, 3, 5, 7};\n json j3;\n\n std::merge(j1.begin(), j1.end(), j2.begin(), j2.end(), std::back_inserter(j3));\n CHECK(j3 == json({1, 2, 2, 3, 4, 5, 6, 7, 8}));\n }\n }\n\n SECTION(\"std::set_difference\")\n {\n json j1 = {1, 2, 3, 4, 5, 6, 7, 8};\n json j2 = {1, 2, 3, 5, 7};\n json j3;\n\n std::set_difference(j1.begin(), j1.end(), j2.begin(), j2.end(), std::back_inserter(j3));\n CHECK(j3 == json({4, 6, 8}));\n }\n\n SECTION(\"std::set_intersection\")\n {\n json j1 = {1, 2, 3, 4, 5, 6, 7, 8};\n json j2 = {1, 2, 3, 5, 7};\n json j3;\n\n std::set_intersection(j1.begin(), j1.end(), j2.begin(), j2.end(), std::back_inserter(j3));\n CHECK(j3 == json({1, 2, 3, 5, 7}));\n }\n\n SECTION(\"std::set_union\")\n {\n json j1 = {2, 4, 6, 8};\n json j2 = {1, 2, 3, 5, 7};\n json j3;\n\n std::set_union(j1.begin(), j1.end(), j2.begin(), j2.end(), std::back_inserter(j3));\n CHECK(j3 == json({1, 2, 3, 4, 5, 6, 7, 8}));\n }\n\n SECTION(\"std::set_symmetric_difference\")\n {\n json j1 = {2, 4, 6, 8};\n json j2 = {1, 2, 3, 5, 7};\n json j3;\n\n std::set_symmetric_difference(j1.begin(), j1.end(), j2.begin(), j2.end(), std::back_inserter(j3));\n CHECK(j3 == json({1, 3, 4, 5, 6, 7, 8}));\n }\n }\n\n SECTION(\"heap operations\")\n {\n std::make_heap(j_array.begin(), j_array.end());\n CHECK(std::is_heap(j_array.begin(), j_array.end()));\n std::sort_heap(j_array.begin(), j_array.end());\n CHECK(j_array == json({false, true, 3, 13, 29, {{\"one\", 1}, {\"two\", 2}}, {1, 2, 3}, \"baz\", \"foo\"}));\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (c) 2016 The WebM project authors. All Rights Reserved.\n *\n * Use of this source code is governed by a BSD-style license\n * that can be found in the LICENSE file in the root of the source\n * tree. An additional intellectual property rights grant can be found\n * in the file PATENTS. All contributing project authors may\n * be found in the AUTHORS file in the root of the source tree.\n *\/\n\n#include <limits>\n\n#include \"third_party\/googletest\/src\/include\/gtest\/gtest.h\"\n\n#include \".\/vp9_rtcd.h\"\n#include \"test\/acm_random.h\"\n#include \"test\/buffer.h\"\n#include \"test\/register_state_check.h\"\n#include \"vpx_ports\/vpx_timer.h\"\n\nnamespace {\n\nusing ::libvpx_test::ACMRandom;\nusing ::libvpx_test::Buffer;\n\ntypedef void (*TemporalFilterFunc)(const uint8_t *a, unsigned int stride,\n const uint8_t *b, unsigned int w,\n unsigned int h, int filter_strength,\n int filter_weight, unsigned int *accumulator,\n uint16_t *count);\n\n\/\/ Calculate the difference between 'a' and 'b', sum in blocks of 9, and apply\n\/\/ filter based on strength and weight. Store the resulting filter amount in\n\/\/ 'count' and apply it to 'b' and store it in 'accumulator'.\nvoid reference_filter(const Buffer<uint8_t> &a, const Buffer<uint8_t> &b, int w,\n int h, int filter_strength, int filter_weight,\n Buffer<unsigned int> *accumulator,\n Buffer<uint16_t> *count) {\n Buffer<int> diff_sq = Buffer<int>(w, h, 0);\n ASSERT_TRUE(diff_sq.Init());\n diff_sq.Set(0);\n\n int rounding = 0;\n if (filter_strength > 0) {\n rounding = 1 << (filter_strength - 1);\n }\n\n \/\/ Calculate all the differences. Avoids re-calculating a bunch of extra\n \/\/ values.\n for (int height = 0; height < h; ++height) {\n for (int width = 0; width < w; ++width) {\n int diff = a.TopLeftPixel()[height * a.stride() + width] -\n b.TopLeftPixel()[height * b.stride() + width];\n diff_sq.TopLeftPixel()[height * diff_sq.stride() + width] = diff * diff;\n }\n }\n\n \/\/ For any given point, sum the neighboring values and calculate the\n \/\/ modifier.\n for (int height = 0; height < h; ++height) {\n for (int width = 0; width < w; ++width) {\n \/\/ Determine how many values are being summed.\n int summed_values = 9;\n\n if (height == 0 || height == (h - 1)) {\n summed_values -= 3;\n }\n\n if (width == 0 || width == (w - 1)) {\n if (summed_values == 6) { \/\/ corner\n summed_values -= 2;\n } else {\n summed_values -= 3;\n }\n }\n\n \/\/ Sum the diff_sq of the surrounding values.\n int sum = 0;\n for (int idy = -1; idy <= 1; ++idy) {\n for (int idx = -1; idx <= 1; ++idx) {\n const int y = height + idy;\n const int x = width + idx;\n\n \/\/ If inside the border.\n if (y >= 0 && y < h && x >= 0 && x < w) {\n sum += diff_sq.TopLeftPixel()[y * diff_sq.stride() + x];\n }\n }\n }\n\n sum *= 3;\n sum \/= summed_values;\n sum += rounding;\n sum >>= filter_strength;\n\n \/\/ Clamp the value and invert it.\n if (sum > 16) sum = 16;\n sum = 16 - sum;\n\n sum *= filter_weight;\n\n count->TopLeftPixel()[height * count->stride() + width] += sum;\n accumulator->TopLeftPixel()[height * accumulator->stride() + width] +=\n sum * b.TopLeftPixel()[height * b.stride() + width];\n }\n }\n}\n\nclass TemporalFilterTest : public ::testing::TestWithParam<TemporalFilterFunc> {\n public:\n virtual void SetUp() {\n filter_func_ = GetParam();\n rnd_.Reset(ACMRandom::DeterministicSeed());\n }\n\n protected:\n TemporalFilterFunc filter_func_;\n ACMRandom rnd_;\n};\n\nTEST_P(TemporalFilterTest, SizeCombinations) {\n \/\/ Depending on subsampling this function may be called with values of 8 or 16\n \/\/ for width and height, in any combination.\n Buffer<uint8_t> a = Buffer<uint8_t>(16, 16, 8);\n ASSERT_TRUE(a.Init());\n\n const int filter_weight = 2;\n const int filter_strength = 6;\n\n for (int width = 8; width <= 16; width += 8) {\n for (int height = 8; height <= 16; height += 8) {\n \/\/ The second buffer must not have any border.\n Buffer<uint8_t> b = Buffer<uint8_t>(width, height, 0);\n ASSERT_TRUE(b.Init());\n Buffer<unsigned int> accum_ref = Buffer<unsigned int>(width, height, 0);\n ASSERT_TRUE(accum_ref.Init());\n Buffer<unsigned int> accum_chk = Buffer<unsigned int>(width, height, 0);\n ASSERT_TRUE(accum_chk.Init());\n Buffer<uint16_t> count_ref = Buffer<uint16_t>(width, height, 0);\n ASSERT_TRUE(count_ref.Init());\n Buffer<uint16_t> count_chk = Buffer<uint16_t>(width, height, 0);\n ASSERT_TRUE(count_chk.Init());\n\n \/\/ The difference between the buffers must be small to pass the threshold\n \/\/ to apply the filter.\n a.Set(&rnd_, 0, 7);\n b.Set(&rnd_, 0, 7);\n\n accum_ref.Set(rnd_.Rand8());\n accum_chk.CopyFrom(accum_ref);\n count_ref.Set(rnd_.Rand8());\n count_chk.CopyFrom(count_ref);\n reference_filter(a, b, width, height, filter_strength, filter_weight,\n &accum_ref, &count_ref);\n ASM_REGISTER_STATE_CHECK(\n filter_func_(a.TopLeftPixel(), a.stride(), b.TopLeftPixel(), width,\n height, filter_strength, filter_weight,\n accum_chk.TopLeftPixel(), count_chk.TopLeftPixel()));\n EXPECT_TRUE(accum_chk.CheckValues(accum_ref));\n EXPECT_TRUE(count_chk.CheckValues(count_ref));\n if (HasFailure()) {\n printf(\"Width: %d Height: %d\\n\", width, height);\n count_chk.PrintDifference(count_ref);\n accum_chk.PrintDifference(accum_ref);\n return;\n }\n }\n }\n}\n\nTEST_P(TemporalFilterTest, CompareReferenceRandom) {\n for (int width = 8; width <= 16; width += 8) {\n for (int height = 8; height <= 16; height += 8) {\n Buffer<uint8_t> a = Buffer<uint8_t>(width, height, 8);\n ASSERT_TRUE(a.Init());\n \/\/ The second buffer must not have any border.\n Buffer<uint8_t> b = Buffer<uint8_t>(width, height, 0);\n ASSERT_TRUE(b.Init());\n Buffer<unsigned int> accum_ref = Buffer<unsigned int>(width, height, 0);\n ASSERT_TRUE(accum_ref.Init());\n Buffer<unsigned int> accum_chk = Buffer<unsigned int>(width, height, 0);\n ASSERT_TRUE(accum_chk.Init());\n Buffer<uint16_t> count_ref = Buffer<uint16_t>(width, height, 0);\n ASSERT_TRUE(count_ref.Init());\n Buffer<uint16_t> count_chk = Buffer<uint16_t>(width, height, 0);\n ASSERT_TRUE(count_chk.Init());\n\n for (int filter_strength = 0; filter_strength <= 6; ++filter_strength) {\n for (int filter_weight = 0; filter_weight <= 2; ++filter_weight) {\n for (int repeat = 0; repeat < 100; ++repeat) {\n if (repeat < 50) {\n a.Set(&rnd_, 0, 7);\n b.Set(&rnd_, 0, 7);\n } else {\n \/\/ Check large (but close) values as well.\n a.Set(&rnd_, std::numeric_limits<uint8_t>::max() - 7,\n std::numeric_limits<uint8_t>::max());\n b.Set(&rnd_, std::numeric_limits<uint8_t>::max() - 7,\n std::numeric_limits<uint8_t>::max());\n }\n\n accum_ref.Set(rnd_.Rand8());\n accum_chk.CopyFrom(accum_ref);\n count_ref.Set(rnd_.Rand8());\n count_chk.CopyFrom(count_ref);\n reference_filter(a, b, width, height, filter_strength,\n filter_weight, &accum_ref, &count_ref);\n ASM_REGISTER_STATE_CHECK(filter_func_(\n a.TopLeftPixel(), a.stride(), b.TopLeftPixel(), width, height,\n filter_strength, filter_weight, accum_chk.TopLeftPixel(),\n count_chk.TopLeftPixel()));\n EXPECT_TRUE(accum_chk.CheckValues(accum_ref));\n EXPECT_TRUE(count_chk.CheckValues(count_ref));\n if (HasFailure()) {\n printf(\"Weight: %d Strength: %d\\n\", filter_weight,\n filter_strength);\n count_chk.PrintDifference(count_ref);\n accum_chk.PrintDifference(accum_ref);\n return;\n }\n }\n }\n }\n }\n }\n}\n\nTEST_P(TemporalFilterTest, DISABLED_Speed) {\n Buffer<uint8_t> a = Buffer<uint8_t>(16, 16, 8);\n ASSERT_TRUE(a.Init());\n\n const int filter_weight = 2;\n const int filter_strength = 6;\n\n for (int width = 8; width <= 16; width += 8) {\n for (int height = 8; height <= 16; height += 8) {\n \/\/ The second buffer must not have any border.\n Buffer<uint8_t> b = Buffer<uint8_t>(width, height, 0);\n ASSERT_TRUE(b.Init());\n Buffer<unsigned int> accum_ref = Buffer<unsigned int>(width, height, 0);\n ASSERT_TRUE(accum_ref.Init());\n Buffer<unsigned int> accum_chk = Buffer<unsigned int>(width, height, 0);\n ASSERT_TRUE(accum_chk.Init());\n Buffer<uint16_t> count_ref = Buffer<uint16_t>(width, height, 0);\n ASSERT_TRUE(count_ref.Init());\n Buffer<uint16_t> count_chk = Buffer<uint16_t>(width, height, 0);\n ASSERT_TRUE(count_chk.Init());\n\n a.Set(&rnd_, 0, 7);\n b.Set(&rnd_, 0, 7);\n\n accum_chk.Set(0);\n count_chk.Set(0);\n\n vpx_usec_timer timer;\n vpx_usec_timer_start(&timer);\n for (int i = 0; i < 10000; ++i) {\n filter_func_(a.TopLeftPixel(), a.stride(), b.TopLeftPixel(), width,\n height, filter_strength, filter_weight,\n accum_chk.TopLeftPixel(), count_chk.TopLeftPixel());\n }\n vpx_usec_timer_mark(&timer);\n const int elapsed_time = static_cast<int>(vpx_usec_timer_elapsed(&timer));\n printf(\"Temporal filter %dx%d time: %5d us\\n\", width, height,\n elapsed_time);\n }\n }\n}\n\nINSTANTIATE_TEST_CASE_P(C, TemporalFilterTest,\n ::testing::Values(&vp9_temporal_filter_apply_c));\n\n#if HAVE_SSE4_1\nINSTANTIATE_TEST_CASE_P(SSE4_1, TemporalFilterTest,\n ::testing::Values(&vp9_temporal_filter_apply_sse4_1));\n#endif \/\/ HAVE_SSE4_1\n} \/\/ namespace\n<commit_msg>Fix scan_build warnings in temporal_filter_test.cc<commit_after>\/*\n * Copyright (c) 2016 The WebM project authors. All Rights Reserved.\n *\n * Use of this source code is governed by a BSD-style license\n * that can be found in the LICENSE file in the root of the source\n * tree. An additional intellectual property rights grant can be found\n * in the file PATENTS. All contributing project authors may\n * be found in the AUTHORS file in the root of the source tree.\n *\/\n\n#include <limits>\n\n#include \"third_party\/googletest\/src\/include\/gtest\/gtest.h\"\n\n#include \".\/vp9_rtcd.h\"\n#include \"test\/acm_random.h\"\n#include \"test\/buffer.h\"\n#include \"test\/register_state_check.h\"\n#include \"vpx_ports\/vpx_timer.h\"\n\nnamespace {\n\nusing ::libvpx_test::ACMRandom;\nusing ::libvpx_test::Buffer;\n\ntypedef void (*TemporalFilterFunc)(const uint8_t *a, unsigned int stride,\n const uint8_t *b, unsigned int w,\n unsigned int h, int filter_strength,\n int filter_weight, unsigned int *accumulator,\n uint16_t *count);\n\n\/\/ Calculate the difference between 'a' and 'b', sum in blocks of 9, and apply\n\/\/ filter based on strength and weight. Store the resulting filter amount in\n\/\/ 'count' and apply it to 'b' and store it in 'accumulator'.\nvoid reference_filter(const Buffer<uint8_t> &a, const Buffer<uint8_t> &b, int w,\n int h, int filter_strength, int filter_weight,\n Buffer<unsigned int> *accumulator,\n Buffer<uint16_t> *count) {\n Buffer<int> diff_sq = Buffer<int>(w, h, 0);\n ASSERT_TRUE(diff_sq.Init());\n diff_sq.Set(0);\n\n int rounding = 0;\n if (filter_strength > 0) {\n rounding = 1 << (filter_strength - 1);\n }\n\n if (a.TopLeftPixel() == NULL || b.TopLeftPixel() == NULL ||\n diff_sq.TopLeftPixel() == NULL) {\n assert(0);\n return;\n }\n \/\/ Calculate all the differences. Avoids re-calculating a bunch of extra\n \/\/ values.\n for (int height = 0; height < h; ++height) {\n for (int width = 0; width < w; ++width) {\n int diff = a.TopLeftPixel()[height * a.stride() + width] -\n b.TopLeftPixel()[height * b.stride() + width];\n diff_sq.TopLeftPixel()[height * diff_sq.stride() + width] = diff * diff;\n }\n }\n\n \/\/ For any given point, sum the neighboring values and calculate the\n \/\/ modifier.\n for (int height = 0; height < h; ++height) {\n for (int width = 0; width < w; ++width) {\n \/\/ Determine how many values are being summed.\n int summed_values = 9;\n\n if (height == 0 || height == (h - 1)) {\n summed_values -= 3;\n }\n\n if (width == 0 || width == (w - 1)) {\n if (summed_values == 6) { \/\/ corner\n summed_values -= 2;\n } else {\n summed_values -= 3;\n }\n }\n\n \/\/ Sum the diff_sq of the surrounding values.\n int sum = 0;\n for (int idy = -1; idy <= 1; ++idy) {\n for (int idx = -1; idx <= 1; ++idx) {\n const int y = height + idy;\n const int x = width + idx;\n\n \/\/ If inside the border.\n if (y >= 0 && y < h && x >= 0 && x < w) {\n sum += diff_sq.TopLeftPixel()[y * diff_sq.stride() + x];\n }\n }\n }\n\n sum *= 3;\n sum \/= summed_values;\n sum += rounding;\n sum >>= filter_strength;\n\n \/\/ Clamp the value and invert it.\n if (sum > 16) sum = 16;\n sum = 16 - sum;\n\n sum *= filter_weight;\n\n count->TopLeftPixel()[height * count->stride() + width] += sum;\n accumulator->TopLeftPixel()[height * accumulator->stride() + width] +=\n sum * b.TopLeftPixel()[height * b.stride() + width];\n }\n }\n}\n\nclass TemporalFilterTest : public ::testing::TestWithParam<TemporalFilterFunc> {\n public:\n virtual void SetUp() {\n filter_func_ = GetParam();\n rnd_.Reset(ACMRandom::DeterministicSeed());\n }\n\n protected:\n TemporalFilterFunc filter_func_;\n ACMRandom rnd_;\n};\n\nTEST_P(TemporalFilterTest, SizeCombinations) {\n \/\/ Depending on subsampling this function may be called with values of 8 or 16\n \/\/ for width and height, in any combination.\n Buffer<uint8_t> a = Buffer<uint8_t>(16, 16, 8);\n ASSERT_TRUE(a.Init());\n\n const int filter_weight = 2;\n const int filter_strength = 6;\n\n for (int width = 8; width <= 16; width += 8) {\n for (int height = 8; height <= 16; height += 8) {\n \/\/ The second buffer must not have any border.\n Buffer<uint8_t> b = Buffer<uint8_t>(width, height, 0);\n ASSERT_TRUE(b.Init());\n Buffer<unsigned int> accum_ref = Buffer<unsigned int>(width, height, 0);\n ASSERT_TRUE(accum_ref.Init());\n Buffer<unsigned int> accum_chk = Buffer<unsigned int>(width, height, 0);\n ASSERT_TRUE(accum_chk.Init());\n Buffer<uint16_t> count_ref = Buffer<uint16_t>(width, height, 0);\n ASSERT_TRUE(count_ref.Init());\n Buffer<uint16_t> count_chk = Buffer<uint16_t>(width, height, 0);\n ASSERT_TRUE(count_chk.Init());\n\n \/\/ The difference between the buffers must be small to pass the threshold\n \/\/ to apply the filter.\n a.Set(&rnd_, 0, 7);\n b.Set(&rnd_, 0, 7);\n\n accum_ref.Set(rnd_.Rand8());\n accum_chk.CopyFrom(accum_ref);\n count_ref.Set(rnd_.Rand8());\n count_chk.CopyFrom(count_ref);\n reference_filter(a, b, width, height, filter_strength, filter_weight,\n &accum_ref, &count_ref);\n ASM_REGISTER_STATE_CHECK(\n filter_func_(a.TopLeftPixel(), a.stride(), b.TopLeftPixel(), width,\n height, filter_strength, filter_weight,\n accum_chk.TopLeftPixel(), count_chk.TopLeftPixel()));\n EXPECT_TRUE(accum_chk.CheckValues(accum_ref));\n EXPECT_TRUE(count_chk.CheckValues(count_ref));\n if (HasFailure()) {\n printf(\"Width: %d Height: %d\\n\", width, height);\n count_chk.PrintDifference(count_ref);\n accum_chk.PrintDifference(accum_ref);\n return;\n }\n }\n }\n}\n\nTEST_P(TemporalFilterTest, CompareReferenceRandom) {\n for (int width = 8; width <= 16; width += 8) {\n for (int height = 8; height <= 16; height += 8) {\n Buffer<uint8_t> a = Buffer<uint8_t>(width, height, 8);\n ASSERT_TRUE(a.Init());\n \/\/ The second buffer must not have any border.\n Buffer<uint8_t> b = Buffer<uint8_t>(width, height, 0);\n ASSERT_TRUE(b.Init());\n Buffer<unsigned int> accum_ref = Buffer<unsigned int>(width, height, 0);\n ASSERT_TRUE(accum_ref.Init());\n Buffer<unsigned int> accum_chk = Buffer<unsigned int>(width, height, 0);\n ASSERT_TRUE(accum_chk.Init());\n Buffer<uint16_t> count_ref = Buffer<uint16_t>(width, height, 0);\n ASSERT_TRUE(count_ref.Init());\n Buffer<uint16_t> count_chk = Buffer<uint16_t>(width, height, 0);\n ASSERT_TRUE(count_chk.Init());\n\n for (int filter_strength = 0; filter_strength <= 6; ++filter_strength) {\n for (int filter_weight = 0; filter_weight <= 2; ++filter_weight) {\n for (int repeat = 0; repeat < 100; ++repeat) {\n if (repeat < 50) {\n a.Set(&rnd_, 0, 7);\n b.Set(&rnd_, 0, 7);\n } else {\n \/\/ Check large (but close) values as well.\n a.Set(&rnd_, std::numeric_limits<uint8_t>::max() - 7,\n std::numeric_limits<uint8_t>::max());\n b.Set(&rnd_, std::numeric_limits<uint8_t>::max() - 7,\n std::numeric_limits<uint8_t>::max());\n }\n\n accum_ref.Set(rnd_.Rand8());\n accum_chk.CopyFrom(accum_ref);\n count_ref.Set(rnd_.Rand8());\n count_chk.CopyFrom(count_ref);\n reference_filter(a, b, width, height, filter_strength,\n filter_weight, &accum_ref, &count_ref);\n ASM_REGISTER_STATE_CHECK(filter_func_(\n a.TopLeftPixel(), a.stride(), b.TopLeftPixel(), width, height,\n filter_strength, filter_weight, accum_chk.TopLeftPixel(),\n count_chk.TopLeftPixel()));\n EXPECT_TRUE(accum_chk.CheckValues(accum_ref));\n EXPECT_TRUE(count_chk.CheckValues(count_ref));\n if (HasFailure()) {\n printf(\"Weight: %d Strength: %d\\n\", filter_weight,\n filter_strength);\n count_chk.PrintDifference(count_ref);\n accum_chk.PrintDifference(accum_ref);\n return;\n }\n }\n }\n }\n }\n }\n}\n\nTEST_P(TemporalFilterTest, DISABLED_Speed) {\n Buffer<uint8_t> a = Buffer<uint8_t>(16, 16, 8);\n ASSERT_TRUE(a.Init());\n\n const int filter_weight = 2;\n const int filter_strength = 6;\n\n for (int width = 8; width <= 16; width += 8) {\n for (int height = 8; height <= 16; height += 8) {\n \/\/ The second buffer must not have any border.\n Buffer<uint8_t> b = Buffer<uint8_t>(width, height, 0);\n ASSERT_TRUE(b.Init());\n Buffer<unsigned int> accum_ref = Buffer<unsigned int>(width, height, 0);\n ASSERT_TRUE(accum_ref.Init());\n Buffer<unsigned int> accum_chk = Buffer<unsigned int>(width, height, 0);\n ASSERT_TRUE(accum_chk.Init());\n Buffer<uint16_t> count_ref = Buffer<uint16_t>(width, height, 0);\n ASSERT_TRUE(count_ref.Init());\n Buffer<uint16_t> count_chk = Buffer<uint16_t>(width, height, 0);\n ASSERT_TRUE(count_chk.Init());\n\n a.Set(&rnd_, 0, 7);\n b.Set(&rnd_, 0, 7);\n\n accum_chk.Set(0);\n count_chk.Set(0);\n\n vpx_usec_timer timer;\n vpx_usec_timer_start(&timer);\n for (int i = 0; i < 10000; ++i) {\n filter_func_(a.TopLeftPixel(), a.stride(), b.TopLeftPixel(), width,\n height, filter_strength, filter_weight,\n accum_chk.TopLeftPixel(), count_chk.TopLeftPixel());\n }\n vpx_usec_timer_mark(&timer);\n const int elapsed_time = static_cast<int>(vpx_usec_timer_elapsed(&timer));\n printf(\"Temporal filter %dx%d time: %5d us\\n\", width, height,\n elapsed_time);\n }\n }\n}\n\nINSTANTIATE_TEST_CASE_P(C, TemporalFilterTest,\n ::testing::Values(&vp9_temporal_filter_apply_c));\n\n#if HAVE_SSE4_1\nINSTANTIATE_TEST_CASE_P(SSE4_1, TemporalFilterTest,\n ::testing::Values(&vp9_temporal_filter_apply_sse4_1));\n#endif \/\/ HAVE_SSE4_1\n} \/\/ namespace\n<|endoftext|>"} {"text":"<commit_before>\/\/ $flisboac 2017-08-13\n#include \"adl_catch.hpp\"\n#include \"adl\/timer.hpp\"\n\n#include <cstdlib>\n#include <chrono>\n\ntemplate <typename TimerHandleType>\nstatic void payload(std::size_t passes_count, TimerHandleType && timer_handle) {\n for (std::size_t idx = 0; idx < passes_count; ++idx) {\n int i = std::rand() % 100;\n i = (i * 8) + 1337;\n i = (i \/ 2) - 3;\n i = (i * 8) + 32417;\n i = (i \/ 2) - 5;\n i = (i * 8) + 74348029;\n i = (i \/ 2) - 7;\n }\n}\n\ntemplate <typename DurationType>\nstatic double ms(DurationType duration) {\n return std::chrono::duration_cast<std::chrono::milliseconds>(duration).count();\n}\n\nstatic void execute() {\n constexpr const int global_passes = 1000;\n constexpr const int function_passes = 100000;\n\n adl::average_timer handler_timer;\n for (int i = 0; i < global_passes; ++i) {\n payload(function_passes, handler_timer.run());\n }\n WARN(\"Moving handler - Passes: \" << handler_timer.run_count() << \", average time: \" << ms(handler_timer.average()));\n\n adl::average_timer exec_timer;\n for (int i = 0; i < global_passes; ++i) {\n exec_timer.run([=] { payload(function_passes, 0); });\n }\n WARN(\"Lambda - Passes: \" << exec_timer.run_count() << \", average time: \" << ms(exec_timer.average()));\n\n adl::average_timer local_timer;\n for (int i = 0; i < global_passes; ++i) {\n auto local_timer_handle = local_timer.run();\n payload(function_passes, 0);\n }\n WARN(\"Local handle - Passes: \" << local_timer.run_count() << \", average time: \" << ms(local_timer.average()));\n\n adl::average_timer all_timer;\n auto all_timer_handle = all_timer.run();\n for (int i = 0; i < global_passes; ++i) {\n payload(function_passes, 0);\n }\n all_timer_handle.stop();\n WARN(\"Outside - average time: \" << ms(all_timer_handle.duration() \/ global_passes));\n\n using namespace adl;\n adl::static_mark_timer<4> mark_timer;\n for (std::size_t i = mark_timer.size(); i < mark_timer.max_size() - 1; ++i) {\n mark_timer.mark();\n for (int i = 0; i < global_passes; ++i) {\n payload(function_passes, 0);\n }\n }\n mark_timer.mark();\n WARN(\"Mark - timings: \" << ms(mark_timer.time(0)) << \", \" << ms(mark_timer.time(1)) << \", \" << ms(mark_timer.time(2)));\n}\n\n\nTEST_CASE(\"unit:adl\/timer\", \"[adl][unit]\") {\n \/\/execute();\n}\n<commit_msg>Removed <cstdlib> usage<commit_after>\/\/ $flisboac 2017-08-13\n#include \"adl_catch.hpp\"\n#include \"adl\/timer.hpp\"\n\n#include <random>\n#include <chrono>\n\nstatic int random_num() {\n std::random_device rd;\n std::mt19937 g{ rd() };\n std::uniform_int_distribution<int> gen{ 0, 65575 };\n return gen(g);\n}\n\ntemplate <typename TimerHandleType>\nstatic void payload(std::size_t passes_count, TimerHandleType && timer_handle) {\n for (std::size_t idx = 0; idx < passes_count; ++idx) {\n int i = random_num() % 100;\n i = (i * 8) + 1337;\n i = (i \/ 2) - 3;\n i = (i * 8) + 32417;\n i = (i \/ 2) - 5;\n i = (i * 8) + 74348029;\n i = (i \/ 2) - 7;\n }\n}\n\ntemplate <typename DurationType>\nstatic double ms(DurationType duration) {\n return std::chrono::duration_cast<std::chrono::milliseconds>(duration).count();\n}\n\nstatic void execute() {\n constexpr const int global_passes = 1000;\n constexpr const int function_passes = 100000;\n\n adl::average_timer handler_timer;\n for (int i = 0; i < global_passes; ++i) {\n payload(function_passes, handler_timer.run());\n }\n WARN(\"Moving handler - Passes: \" << handler_timer.run_count() << \", average time: \" << ms(handler_timer.average()));\n\n adl::average_timer exec_timer;\n for (int i = 0; i < global_passes; ++i) {\n exec_timer.run([=] { payload(function_passes, 0); });\n }\n WARN(\"Lambda - Passes: \" << exec_timer.run_count() << \", average time: \" << ms(exec_timer.average()));\n\n adl::average_timer local_timer;\n for (int i = 0; i < global_passes; ++i) {\n auto local_timer_handle = local_timer.run();\n payload(function_passes, 0);\n }\n WARN(\"Local handle - Passes: \" << local_timer.run_count() << \", average time: \" << ms(local_timer.average()));\n\n adl::average_timer all_timer;\n auto all_timer_handle = all_timer.run();\n for (int i = 0; i < global_passes; ++i) {\n payload(function_passes, 0);\n }\n all_timer_handle.stop();\n WARN(\"Outside - average time: \" << ms(all_timer_handle.duration() \/ global_passes));\n\n using namespace adl;\n adl::static_mark_timer<4> mark_timer;\n for (std::size_t i = mark_timer.size(); i < mark_timer.max_size() - 1; ++i) {\n mark_timer.mark();\n for (int i = 0; i < global_passes; ++i) {\n payload(function_passes, 0);\n }\n }\n mark_timer.mark();\n WARN(\"Mark - timings: \" << ms(mark_timer.time(0)) << \", \" << ms(mark_timer.time(1)) << \", \" << ms(mark_timer.time(2)));\n}\n\n\nTEST_CASE(\"unit:adl\/timer\", \"[adl][unit]\") {\n \/\/execute();\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ This file is part of the dune-gdt project:\n\/\/ http:\/\/users.dune-project.org\/projects\/dune-gdt\n\/\/ Copyright holders: Felix Schindler\n\/\/ License: BSD 2-Clause License (http:\/\/opensource.org\/licenses\/BSD-2-Clause)\n\n#include <dune\/stuff\/test\/test_common.hh>\n\n#undef HAVE_FASP\n\n#include <dune\/common\/exceptions.hh>\n\n#if HAVE_ALUGRID_SERIAL_H || HAVE_ALUGRID_PARALLEL_H\n# define ENABLE_ALUGRID 1\n# include <dune\/stuff\/common\/disable_warnings.hh>\n# include <dune\/grid\/alugrid.hh>\n# include <dune\/stuff\/common\/reenable_warnings.hh>\n#else\n# error This test requires ALUGrid!\n#endif\n\n#include \"elliptic-testcases.hh\"\n#include \"elliptic-swipdg-discretization.hh\"\n\n\/\/ change this to toggle test_output\nstd::ostream& test_out = std::cout;\n\/\/std::ostream& test_out = DSC_LOG.devnull();\n\n\nclass errors_are_not_as_expected\n : public Dune::Exception\n{};\n\nstd::vector< double > truncate_vector(const std::vector< double >& in, const size_t size)\n{\n assert(size <= in.size());\n if (size == in.size())\n return in;\n else {\n std::vector< double > ret(size);\n for (size_t ii = 0; ii < size; ++ii)\n ret[ii] = in[ii];\n return ret;\n }\n} \/\/ ... truncate_vector(...)\n\n\ntypedef Dune::ALUConformGrid< 2, 2 > AluConform2dGridType;\n\ntypedef testing::Types< \/\/EllipticTestCase::ESV07< AluConform2dGridType >\n EllipticTestCase::LocalThermalBlock< AluConform2dGridType >\n , EllipticTestCase::Spe10Model1< AluConform2dGridType >\n > AluConform2dTestCases;\n\n\ntemplate< class TestCase >\nstruct EllipticSWIPDGDiscretization\n : public ::testing::Test\n{\n void produces_correct_results() const\n {\n const TestCase test_case;\n test_case.print_header(test_out);\n test_out << std::endl;\n EllipticSWIPDG::EstimatorStudy< TestCase > estimator_study(test_case);\n auto results = estimator_study.run(test_out);\n std::stringstream ss;\n for (const auto& norm : estimator_study.provided_norms())\n if (!Dune::Stuff::Common::FloatCmp::lt(results[norm],\n truncate_vector(estimator_study.expected_results(norm),\n results[norm].size()))) {\n Dune::Stuff::Common::print(results[norm], \" errors (\" + norm + \")\", ss);\n Dune::Stuff::Common::print(estimator_study.expected_results(norm), \" expected results (\" + norm + \")\", ss);\n }\n const std::string failure = ss.str();\n if (!failure.empty()) DUNE_THROW_COLORFULLY(errors_are_not_as_expected, \"\\n\" << failure);\n } \/\/ ... produces_correct_results()\n}; \/\/ struct EllipticSWIPDGDiscretization\n\n\nTYPED_TEST_CASE(EllipticSWIPDGDiscretization, AluConform2dTestCases);\nTYPED_TEST(EllipticSWIPDGDiscretization, produces_correct_results) {\n this->produces_correct_results();\n}\n\n\nint main(int argc, char** argv)\n{\n try {\n test_init(argc, argv);\n return RUN_ALL_TESTS();\n } catch (Dune::Exception& e) {\n std::cerr << \"Dune reported error: \" << e.what() << std::endl;\n std::abort();\n } catch (std::exception& e) {\n std::cerr << e.what() << std::endl;\n std::abort();\n } catch (...) {\n std::cerr << \"Unknown exception thrown!\" << std::endl;\n std::abort();\n } \/\/ try\n}\n<commit_msg>[tests.elliptic-estimators] enabled ESV07, disabled rest<commit_after>\/\/ This file is part of the dune-gdt project:\n\/\/ http:\/\/users.dune-project.org\/projects\/dune-gdt\n\/\/ Copyright holders: Felix Schindler\n\/\/ License: BSD 2-Clause License (http:\/\/opensource.org\/licenses\/BSD-2-Clause)\n\n#include <dune\/stuff\/test\/test_common.hh>\n\n#undef HAVE_FASP\n\n#include <dune\/common\/exceptions.hh>\n\n#if HAVE_ALUGRID_SERIAL_H || HAVE_ALUGRID_PARALLEL_H\n# define ENABLE_ALUGRID 1\n# include <dune\/stuff\/common\/disable_warnings.hh>\n# include <dune\/grid\/alugrid.hh>\n# include <dune\/stuff\/common\/reenable_warnings.hh>\n#else\n# error This test requires ALUGrid!\n#endif\n\n#include \"elliptic-testcases.hh\"\n#include \"elliptic-swipdg-discretization.hh\"\n\n\/\/ change this to toggle test_output\nstd::ostream& test_out = std::cout;\n\/\/std::ostream& test_out = DSC_LOG.devnull();\n\n\nclass errors_are_not_as_expected\n : public Dune::Exception\n{};\n\nstd::vector< double > truncate_vector(const std::vector< double >& in, const size_t size)\n{\n assert(size <= in.size());\n if (size == in.size())\n return in;\n else {\n std::vector< double > ret(size);\n for (size_t ii = 0; ii < size; ++ii)\n ret[ii] = in[ii];\n return ret;\n }\n} \/\/ ... truncate_vector(...)\n\n\ntypedef Dune::ALUConformGrid< 2, 2 > AluConform2dGridType;\n\ntypedef testing::Types< EllipticTestCase::ESV07< AluConform2dGridType >\n\/\/ , EllipticTestCase::LocalThermalBlock< AluConform2dGridType >\n\/\/ , EllipticTestCase::Spe10Model1< AluConform2dGridType >\n > AluConform2dTestCases;\n\n\ntemplate< class TestCase >\nstruct EllipticSWIPDGDiscretization\n : public ::testing::Test\n{\n void produces_correct_results() const\n {\n const TestCase test_case;\n test_case.print_header(test_out);\n test_out << std::endl;\n EllipticSWIPDG::EstimatorStudy< TestCase > estimator_study(test_case);\n auto results = estimator_study.run(test_out);\n std::stringstream ss;\n for (const auto& norm : estimator_study.provided_norms())\n if (!Dune::Stuff::Common::FloatCmp::lt(results[norm],\n truncate_vector(estimator_study.expected_results(norm),\n results[norm].size()))) {\n Dune::Stuff::Common::print(results[norm], \" errors (\" + norm + \")\", ss);\n Dune::Stuff::Common::print(estimator_study.expected_results(norm), \" expected results (\" + norm + \")\", ss);\n }\n const std::string failure = ss.str();\n if (!failure.empty()) DUNE_THROW_COLORFULLY(errors_are_not_as_expected, \"\\n\" << failure);\n } \/\/ ... produces_correct_results()\n}; \/\/ struct EllipticSWIPDGDiscretization\n\n\nTYPED_TEST_CASE(EllipticSWIPDGDiscretization, AluConform2dTestCases);\nTYPED_TEST(EllipticSWIPDGDiscretization, produces_correct_results) {\n this->produces_correct_results();\n}\n\n\nint main(int argc, char** argv)\n{\n try {\n test_init(argc, argv);\n return RUN_ALL_TESTS();\n } catch (Dune::Exception& e) {\n std::cerr << \"Dune reported error: \" << e.what() << std::endl;\n std::abort();\n } catch (std::exception& e) {\n std::cerr << e.what() << std::endl;\n std::abort();\n } catch (...) {\n std::cerr << \"Unknown exception thrown!\" << std::endl;\n std::abort();\n } \/\/ try\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ PelotonDB\n\/\/\n\/\/ hash_join_test.cpp\n\/\/\n\/\/ Identification: tests\/executor\/hash_join_test.cpp\n\/\/\n\/\/ Copyright (c) 2015, Carnegie Mellon University Database Group\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include <memory>\n\n#include \"gmock\/gmock.h\"\n#include \"gtest\/gtest.h\"\n\n#include \"backend\/common\/types.h\"\n#include \"backend\/executor\/logical_tile.h\"\n#include \"backend\/executor\/logical_tile_factory.h\"\n\n#include \"backend\/executor\/hash_join_executor.h\"\n#include \"backend\/executor\/hash_executor.h\"\n#include \"backend\/executor\/merge_join_executor.h\"\n#include \"backend\/executor\/nested_loop_join_executor.h\"\n\n#include \"backend\/expression\/abstract_expression.h\"\n#include \"backend\/expression\/tuple_value_expression.h\"\n#include \"backend\/expression\/expression_util.h\"\n\n#include \"backend\/planner\/hash_join_plan.h\"\n#include \"backend\/planner\/hash_plan.h\"\n#include \"backend\/planner\/merge_join_plan.h\"\n#include \"backend\/planner\/nested_loop_join_plan.h\"\n\n#include \"backend\/storage\/data_table.h\"\n\n#include \"mock_executor.h\"\n#include \"executor\/executor_tests_util.h\"\n#include \"executor\/join_tests_util.h\"\n#include \"harness.h\"\n\nusing ::testing::NotNull;\nusing ::testing::Return;\n\nnamespace peloton {\nnamespace test {\n\nstd::vector<planner::MergeJoinPlan::JoinClause> CreateJoinClauses() {\n std::vector<planner::MergeJoinPlan::JoinClause> join_clauses;\n auto left = expression::TupleValueFactory(0, 1);\n auto right = expression::TupleValueFactory(1, 1);\n bool reversed = false;\n join_clauses.emplace_back(left, right, reversed);\n return join_clauses;\n}\n\nstd::vector<PlanNodeType> join_algorithms = {\n PLAN_NODE_TYPE_NESTLOOP,\n PLAN_NODE_TYPE_MERGEJOIN,\n PLAN_NODE_TYPE_HASHJOIN\n};\n\nstd::vector<PelotonJoinType> join_types = {\n JOIN_TYPE_INNER,\n JOIN_TYPE_LEFT,\n JOIN_TYPE_RIGHT,\n JOIN_TYPE_OUTER\n};\n\nvoid ExecuteJoinTest(PlanNodeType join_algorithm, PelotonJoinType join_type);\n\nTEST(JoinTests, JoinPredicateTest) {\n\n \/\/ Go over all join algorithms\n for(auto join_algorithm : join_algorithms) {\n std::cout << \"JOIN ALGORITHM :: \" << PlanNodeTypeToString(join_algorithm) << \"\\n\";\n\n \/\/ Go over all join types\n for(auto join_type : join_types) {\n std::cout << \"JOIN TYPE :: \" << join_type << \"\\n\";\n\n \/\/ Execute the join test\n ExecuteJoinTest(join_algorithm, join_type);\n\n }\n }\n\n}\n\nvoid ExecuteJoinTest(PlanNodeType join_algorithm, PelotonJoinType join_type) {\n\n \/\/===--------------------------------------------------------------------===\/\/\n \/\/ Mock table scan executors\n \/\/===--------------------------------------------------------------------===\/\/\n\n MockExecutor left_table_scan_executor, right_table_scan_executor;\n\n \/\/ Create a table and wrap it in logical tile\n size_t tile_group_size = TESTS_TUPLES_PER_TILEGROUP;\n size_t left_table_tile_group_count = 3;\n size_t right_table_tile_group_count = 2;\n\n \/\/ Left table has 3 tile groups\n std::unique_ptr<storage::DataTable> left_table(\n ExecutorTestsUtil::CreateTable(tile_group_size));\n ExecutorTestsUtil::PopulateTable(left_table.get(),\n tile_group_size * left_table_tile_group_count,\n false,\n false, false);\n\n \/\/std::cout << (*left_table);\n\n \/\/ Right table has 2 tile groups\n std::unique_ptr<storage::DataTable> right_table(\n ExecutorTestsUtil::CreateTable(tile_group_size));\n ExecutorTestsUtil::PopulateTable(right_table.get(),\n tile_group_size * right_table_tile_group_count,\n false, false, false);\n\n \/\/std::cout << (*right_table);\n\n \/\/ Wrap the input tables with logical tiles\n std::unique_ptr<executor::LogicalTile> left_table_logical_tile1(\n executor::LogicalTileFactory::WrapTileGroup(left_table->GetTileGroup(0)));\n std::unique_ptr<executor::LogicalTile> left_table_logical_tile2(\n executor::LogicalTileFactory::WrapTileGroup(left_table->GetTileGroup(1)));\n std::unique_ptr<executor::LogicalTile> left_table_logical_tile3(\n executor::LogicalTileFactory::WrapTileGroup(left_table->GetTileGroup(2)));\n\n std::unique_ptr<executor::LogicalTile> right_table_logical_tile1(\n executor::LogicalTileFactory::WrapTileGroup(\n right_table->GetTileGroup(0)));\n std::unique_ptr<executor::LogicalTile> right_table_logical_tile2(\n executor::LogicalTileFactory::WrapTileGroup(\n right_table->GetTileGroup(1)));\n\n \/\/ Left scan executor returns logical tiles from the left table\n\n EXPECT_CALL(left_table_scan_executor, DInit())\n .WillOnce(Return(true));\n\n EXPECT_CALL(left_table_scan_executor, DExecute())\n .WillOnce(Return(true))\n .WillOnce(Return(true))\n .WillOnce(Return(true))\n .WillOnce(Return(false));\n\n EXPECT_CALL(left_table_scan_executor, GetOutput())\n .WillOnce(Return(left_table_logical_tile1.release()))\n .WillOnce(Return(left_table_logical_tile2.release()))\n .WillOnce(Return(left_table_logical_tile3.release()));\n\n \/\/ Right scan executor returns logical tiles from the right table\n\n EXPECT_CALL(right_table_scan_executor, DInit())\n .WillOnce(Return(true));\n\n EXPECT_CALL(right_table_scan_executor, DExecute())\n .WillOnce(Return(true))\n .WillOnce(Return(true))\n .WillOnce(Return(false));\n\n EXPECT_CALL(right_table_scan_executor, GetOutput())\n .WillOnce(Return(right_table_logical_tile1.release()))\n .WillOnce(Return(right_table_logical_tile2.release()));\n\n \/\/===--------------------------------------------------------------------===\/\/\n \/\/ Setup join plan nodes and executors and run them\n \/\/===--------------------------------------------------------------------===\/\/\n\n auto result_tuple_count = 0;\n auto projection = JoinTestsUtil::CreateProjection();\n\n \/\/ Construct predicate\n expression::AbstractExpression *predicate = JoinTestsUtil::CreateJoinPredicate();\n\n \/\/ Differ based on join algorithm\n switch(join_algorithm) {\n\n case PLAN_NODE_TYPE_NESTLOOP: {\n\n \/\/ Create nested loop join plan node.\n planner::NestedLoopJoinPlan nested_loop_join_node(join_type, predicate, projection);\n\n \/\/ Run the nested loop join executor\n executor::NestedLoopJoinExecutor nested_loop_join_executor(&nested_loop_join_node, nullptr);\n\n \/\/ Construct the executor tree\n nested_loop_join_executor.AddChild(&left_table_scan_executor);\n nested_loop_join_executor.AddChild(&right_table_scan_executor);\n\n \/\/ Run the nested loop join executor\n EXPECT_TRUE(nested_loop_join_executor.Init());\n while(nested_loop_join_executor.Execute() == true) {\n std::unique_ptr<executor::LogicalTile> result_logical_tile(nested_loop_join_executor.GetOutput());\n\n if(result_logical_tile != nullptr) {\n result_tuple_count += result_logical_tile->GetTupleCount();\n }\n }\n\n }\n break;\n\n case PLAN_NODE_TYPE_MERGEJOIN: {\n\n \/\/ Create join clauses\n std::vector<planner::MergeJoinPlan::JoinClause> join_clauses;\n join_clauses = CreateJoinClauses();\n\n \/\/ Create merge join plan node\n planner::MergeJoinPlan merge_join_node(join_type, predicate, projection, join_clauses);\n\n \/\/ Construct the merge join executor\n executor::MergeJoinExecutor merge_join_executor(&merge_join_node, nullptr);\n\n \/\/ Construct the executor tree\n merge_join_executor.AddChild(&left_table_scan_executor);\n merge_join_executor.AddChild(&right_table_scan_executor);\n\n \/\/ Run the merge join executor\n EXPECT_TRUE(merge_join_executor.Init());\n while(merge_join_executor.Execute() == true) {\n std::unique_ptr<executor::LogicalTile> result_logical_tile(merge_join_executor.GetOutput());\n\n if(result_logical_tile != nullptr) {\n result_tuple_count += result_logical_tile->GetTupleCount();\n \/\/std::cout << (*result_logical_tile);\n }\n }\n\n }\n break;\n\n case PLAN_NODE_TYPE_HASHJOIN: {\n\n \/\/ Create hash plan node\n expression::AbstractExpression *right_table_attr_1 =\n new expression::TupleValueExpression(1, 1);\n\n std::vector<std::unique_ptr<const expression::AbstractExpression> > hash_keys;\n hash_keys.emplace_back(right_table_attr_1);\n\n \/\/ Create hash plan node\n planner::HashPlan hash_plan_node(hash_keys);\n\n \/\/ Construct the hash executor\n executor::HashExecutor hash_executor(&hash_plan_node, nullptr);\n\n \/\/ Create hash join plan node.\n planner::HashJoinPlan hash_join_plan_node(join_type, predicate, projection);\n\n \/\/ Construct the hash join executor\n executor::HashJoinExecutor hash_join_executor(&hash_join_plan_node, nullptr);\n\n \/\/ Construct the executor tree\n hash_join_executor.AddChild(&left_table_scan_executor);\n hash_join_executor.AddChild(&hash_executor);\n\n hash_executor.AddChild(&right_table_scan_executor);\n\n \/\/ Run the hash_join_executor\n EXPECT_TRUE(hash_join_executor.Init());\n while(hash_join_executor.Execute() == true) {\n std::unique_ptr<executor::LogicalTile> result_logical_tile(hash_join_executor.GetOutput());\n\n if(result_logical_tile != nullptr) {\n result_tuple_count += result_logical_tile->GetTupleCount();\n \/\/std::cout << (*result_logical_tile);\n }\n }\n\n }\n break;\n\n default:\n throw Exception(\"Unsupported join algorithm : \" + std::to_string(join_algorithm));\n break;\n }\n\n \/\/===--------------------------------------------------------------------===\/\/\n \/\/ Execute test\n \/\/===--------------------------------------------------------------------===\/\/\n\n \/\/ Check output\n switch(join_type) {\n case JOIN_TYPE_INNER:\n EXPECT_EQ(result_tuple_count, 2 * tile_group_size);\n break;\n\n case JOIN_TYPE_LEFT:\n EXPECT_EQ(result_tuple_count, 3 * tile_group_size);\n break;\n\n case JOIN_TYPE_RIGHT:\n EXPECT_EQ(result_tuple_count, 2 * tile_group_size);\n break;\n\n case JOIN_TYPE_OUTER:\n EXPECT_EQ(result_tuple_count, 3 * tile_group_size);\n break;\n\n default:\n throw Exception(\"Unsupported join type : \" + std::to_string(join_type));\n break;\n }\n\n}\n\n} \/\/ namespace test\n} \/\/ namespace peloton\n<commit_msg>Updated the join test<commit_after>\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ PelotonDB\n\/\/\n\/\/ hash_join_test.cpp\n\/\/\n\/\/ Identification: tests\/executor\/hash_join_test.cpp\n\/\/\n\/\/ Copyright (c) 2015, Carnegie Mellon University Database Group\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include <memory>\n\n#include \"gmock\/gmock.h\"\n#include \"gtest\/gtest.h\"\n\n#include \"backend\/common\/types.h\"\n#include \"backend\/executor\/logical_tile.h\"\n#include \"backend\/executor\/logical_tile_factory.h\"\n\n#include \"backend\/executor\/hash_join_executor.h\"\n#include \"backend\/executor\/hash_executor.h\"\n#include \"backend\/executor\/merge_join_executor.h\"\n#include \"backend\/executor\/nested_loop_join_executor.h\"\n\n#include \"backend\/expression\/abstract_expression.h\"\n#include \"backend\/expression\/tuple_value_expression.h\"\n#include \"backend\/expression\/expression_util.h\"\n\n#include \"backend\/planner\/hash_join_plan.h\"\n#include \"backend\/planner\/hash_plan.h\"\n#include \"backend\/planner\/merge_join_plan.h\"\n#include \"backend\/planner\/nested_loop_join_plan.h\"\n\n#include \"backend\/storage\/data_table.h\"\n\n#include \"mock_executor.h\"\n#include \"executor\/executor_tests_util.h\"\n#include \"executor\/join_tests_util.h\"\n#include \"harness.h\"\n\nusing ::testing::NotNull;\nusing ::testing::Return;\n\nnamespace peloton {\nnamespace test {\n\nstd::vector<planner::MergeJoinPlan::JoinClause> CreateJoinClauses() {\n std::vector<planner::MergeJoinPlan::JoinClause> join_clauses;\n auto left = expression::TupleValueFactory(0, 1);\n auto right = expression::TupleValueFactory(1, 1);\n bool reversed = false;\n join_clauses.emplace_back(left, right, reversed);\n return join_clauses;\n}\n\nstd::vector<PlanNodeType> join_algorithms = {\n PLAN_NODE_TYPE_NESTLOOP,\n PLAN_NODE_TYPE_MERGEJOIN,\n PLAN_NODE_TYPE_HASHJOIN\n};\n\nstd::vector<PelotonJoinType> join_types = {\n JOIN_TYPE_INNER,\n JOIN_TYPE_LEFT,\n JOIN_TYPE_RIGHT,\n JOIN_TYPE_OUTER\n};\n\nvoid ExecuteJoinTest(PlanNodeType join_algorithm, PelotonJoinType join_type);\n\noid_t CountTuplesWithNullFields(executor::LogicalTile *logical_tile);\n\nTEST(JoinTests, JoinPredicateTest) {\n\n \/\/ Go over all join algorithms\n for(auto join_algorithm : join_algorithms) {\n std::cout << \"JOIN ALGORITHM :: \" << PlanNodeTypeToString(join_algorithm) << \"\\n\";\n\n \/\/ Go over all join types\n for(auto join_type : join_types) {\n std::cout << \"JOIN TYPE :: \" << join_type << \"\\n\";\n\n \/\/ Execute the join test\n ExecuteJoinTest(join_algorithm, join_type);\n\n }\n }\n\n}\n\nvoid ExecuteJoinTest(PlanNodeType join_algorithm, PelotonJoinType join_type) {\n\n \/\/===--------------------------------------------------------------------===\/\/\n \/\/ Mock table scan executors\n \/\/===--------------------------------------------------------------------===\/\/\n\n MockExecutor left_table_scan_executor, right_table_scan_executor;\n\n \/\/ Create a table and wrap it in logical tile\n size_t tile_group_size = TESTS_TUPLES_PER_TILEGROUP;\n size_t left_table_tile_group_count = 3;\n size_t right_table_tile_group_count = 2;\n\n \/\/ Left table has 3 tile groups\n std::unique_ptr<storage::DataTable> left_table(\n ExecutorTestsUtil::CreateTable(tile_group_size));\n ExecutorTestsUtil::PopulateTable(left_table.get(),\n tile_group_size * left_table_tile_group_count,\n false,\n false, false);\n\n \/\/std::cout << (*left_table);\n\n \/\/ Right table has 2 tile groups\n std::unique_ptr<storage::DataTable> right_table(\n ExecutorTestsUtil::CreateTable(tile_group_size));\n ExecutorTestsUtil::PopulateTable(right_table.get(),\n tile_group_size * right_table_tile_group_count,\n false, false, false);\n\n \/\/std::cout << (*right_table);\n\n \/\/ Wrap the input tables with logical tiles\n std::unique_ptr<executor::LogicalTile> left_table_logical_tile1(\n executor::LogicalTileFactory::WrapTileGroup(left_table->GetTileGroup(0)));\n std::unique_ptr<executor::LogicalTile> left_table_logical_tile2(\n executor::LogicalTileFactory::WrapTileGroup(left_table->GetTileGroup(1)));\n std::unique_ptr<executor::LogicalTile> left_table_logical_tile3(\n executor::LogicalTileFactory::WrapTileGroup(left_table->GetTileGroup(2)));\n\n std::unique_ptr<executor::LogicalTile> right_table_logical_tile1(\n executor::LogicalTileFactory::WrapTileGroup(\n right_table->GetTileGroup(0)));\n std::unique_ptr<executor::LogicalTile> right_table_logical_tile2(\n executor::LogicalTileFactory::WrapTileGroup(\n right_table->GetTileGroup(1)));\n\n \/\/ Left scan executor returns logical tiles from the left table\n\n EXPECT_CALL(left_table_scan_executor, DInit())\n .WillOnce(Return(true));\n\n EXPECT_CALL(left_table_scan_executor, DExecute())\n .WillOnce(Return(true))\n .WillOnce(Return(true))\n .WillOnce(Return(true))\n .WillOnce(Return(false));\n\n EXPECT_CALL(left_table_scan_executor, GetOutput())\n .WillOnce(Return(left_table_logical_tile1.release()))\n .WillOnce(Return(left_table_logical_tile2.release()))\n .WillOnce(Return(left_table_logical_tile3.release()));\n\n \/\/ Right scan executor returns logical tiles from the right table\n\n EXPECT_CALL(right_table_scan_executor, DInit())\n .WillOnce(Return(true));\n\n EXPECT_CALL(right_table_scan_executor, DExecute())\n .WillOnce(Return(true))\n .WillOnce(Return(true))\n .WillOnce(Return(false));\n\n EXPECT_CALL(right_table_scan_executor, GetOutput())\n .WillOnce(Return(right_table_logical_tile1.release()))\n .WillOnce(Return(right_table_logical_tile2.release()));\n\n \/\/===--------------------------------------------------------------------===\/\/\n \/\/ Setup join plan nodes and executors and run them\n \/\/===--------------------------------------------------------------------===\/\/\n\n oid_t result_tuple_count = 0;\n oid_t tuples_with_null = 0;\n auto projection = JoinTestsUtil::CreateProjection();\n\n \/\/ Construct predicate\n expression::AbstractExpression *predicate = JoinTestsUtil::CreateJoinPredicate();\n\n \/\/ Differ based on join algorithm\n switch(join_algorithm) {\n\n case PLAN_NODE_TYPE_NESTLOOP: {\n\n \/\/ Create nested loop join plan node.\n planner::NestedLoopJoinPlan nested_loop_join_node(join_type, predicate, projection);\n\n \/\/ Run the nested loop join executor\n executor::NestedLoopJoinExecutor nested_loop_join_executor(&nested_loop_join_node, nullptr);\n\n \/\/ Construct the executor tree\n nested_loop_join_executor.AddChild(&left_table_scan_executor);\n nested_loop_join_executor.AddChild(&right_table_scan_executor);\n\n \/\/ Run the nested loop join executor\n EXPECT_TRUE(nested_loop_join_executor.Init());\n while(nested_loop_join_executor.Execute() == true) {\n std::unique_ptr<executor::LogicalTile> result_logical_tile(nested_loop_join_executor.GetOutput());\n\n if(result_logical_tile != nullptr) {\n result_tuple_count += result_logical_tile->GetTupleCount();\n tuples_with_null += CountTuplesWithNullFields(result_logical_tile.get());\n }\n }\n\n }\n break;\n\n case PLAN_NODE_TYPE_MERGEJOIN: {\n\n \/\/ Create join clauses\n std::vector<planner::MergeJoinPlan::JoinClause> join_clauses;\n join_clauses = CreateJoinClauses();\n\n \/\/ Create merge join plan node\n planner::MergeJoinPlan merge_join_node(join_type, predicate, projection, join_clauses);\n\n \/\/ Construct the merge join executor\n executor::MergeJoinExecutor merge_join_executor(&merge_join_node, nullptr);\n\n \/\/ Construct the executor tree\n merge_join_executor.AddChild(&left_table_scan_executor);\n merge_join_executor.AddChild(&right_table_scan_executor);\n\n \/\/ Run the merge join executor\n EXPECT_TRUE(merge_join_executor.Init());\n while(merge_join_executor.Execute() == true) {\n std::unique_ptr<executor::LogicalTile> result_logical_tile(merge_join_executor.GetOutput());\n\n if(result_logical_tile != nullptr) {\n result_tuple_count += result_logical_tile->GetTupleCount();\n tuples_with_null += CountTuplesWithNullFields(result_logical_tile.get());\n \/\/std::cout << (*result_logical_tile);\n }\n }\n\n }\n break;\n\n case PLAN_NODE_TYPE_HASHJOIN: {\n\n \/\/ Create hash plan node\n expression::AbstractExpression *right_table_attr_1 =\n new expression::TupleValueExpression(1, 1);\n\n std::vector<std::unique_ptr<const expression::AbstractExpression> > hash_keys;\n hash_keys.emplace_back(right_table_attr_1);\n\n \/\/ Create hash plan node\n planner::HashPlan hash_plan_node(hash_keys);\n\n \/\/ Construct the hash executor\n executor::HashExecutor hash_executor(&hash_plan_node, nullptr);\n\n \/\/ Create hash join plan node.\n planner::HashJoinPlan hash_join_plan_node(join_type, predicate, projection);\n\n \/\/ Construct the hash join executor\n executor::HashJoinExecutor hash_join_executor(&hash_join_plan_node, nullptr);\n\n \/\/ Construct the executor tree\n hash_join_executor.AddChild(&left_table_scan_executor);\n hash_join_executor.AddChild(&hash_executor);\n\n hash_executor.AddChild(&right_table_scan_executor);\n\n \/\/ Run the hash_join_executor\n EXPECT_TRUE(hash_join_executor.Init());\n while(hash_join_executor.Execute() == true) {\n std::unique_ptr<executor::LogicalTile> result_logical_tile(hash_join_executor.GetOutput());\n\n if(result_logical_tile != nullptr) {\n result_tuple_count += result_logical_tile->GetTupleCount();\n tuples_with_null += CountTuplesWithNullFields(result_logical_tile.get());\n \/\/std::cout << (*result_logical_tile);\n }\n }\n\n }\n break;\n\n default:\n throw Exception(\"Unsupported join algorithm : \" + std::to_string(join_algorithm));\n break;\n }\n\n \/\/===--------------------------------------------------------------------===\/\/\n \/\/ Execute test\n \/\/===--------------------------------------------------------------------===\/\/\n\n \/\/ Check output\n switch(join_type) {\n case JOIN_TYPE_INNER:\n EXPECT_EQ(result_tuple_count, 2 * tile_group_size);\n EXPECT_EQ(tuples_with_null, 0 * tile_group_size);\n break;\n\n case JOIN_TYPE_LEFT:\n EXPECT_EQ(result_tuple_count, 3 * tile_group_size);\n EXPECT_EQ(tuples_with_null, 1 * tile_group_size);\n break;\n\n case JOIN_TYPE_RIGHT:\n EXPECT_EQ(result_tuple_count, 2 * tile_group_size);\n EXPECT_EQ(tuples_with_null, 0 * tile_group_size);\n break;\n\n case JOIN_TYPE_OUTER:\n EXPECT_EQ(result_tuple_count, 3 * tile_group_size);\n EXPECT_EQ(tuples_with_null, 1 * tile_group_size);\n break;\n\n default:\n throw Exception(\"Unsupported join type : \" + std::to_string(join_type));\n break;\n }\n\n}\n\noid_t CountTuplesWithNullFields(executor::LogicalTile *logical_tile) {\n assert(logical_tile);\n\n \/\/ Get column count\n auto column_count = logical_tile->GetColumnCount();\n oid_t tuples_with_null = 0;\n\n \/\/ Go over the tile\n for (auto logical_tile_itr : *logical_tile) {\n const expression::ContainerTuple<executor::LogicalTile> left_tuple(\n logical_tile, logical_tile_itr);\n\n \/\/ Go over all the fields and check for null values\n for(oid_t col_itr = 0; col_itr < column_count; col_itr++) {\n auto val = left_tuple.GetValue(col_itr);\n if(val.IsNull()) {\n tuples_with_null++;\n break;\n }\n }\n\n }\n\n return tuples_with_null;\n}\n\n\n} \/\/ namespace test\n} \/\/ namespace peloton\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ Created by Ivan Shynkarenka on 18.09.2016.\n\/\/\n\n#include \"catch.hpp\"\n\n#include \"logging\/record.h\"\n\nusing namespace CppLogging;\n\nclass Date\n{\npublic:\n Date(int year, int month, int day) : _year(year), _month(month), _day(day) {}\n\n friend std::ostream& operator<<(std::ostream& os, const Date& date)\n { return os << date._year << '-' << date._month << '-' << date._day; }\n\nprivate:\n int _year, _month, _day;\n};\n\ntemplate <typename... Args>\nstd::string format(const char* pattern, const Args&... args)\n{\n Record record;\n record.FormatSerialize(pattern, args...);\n record.FormatDeserialize();\n return record.message;\n}\n\nTEST_CASE(\"Format message\", \"[CppLogging]\")\n{\n\n REQUIRE(format(\"no arguments\") == \"no arguments\");\n\/*\n REQUIRE(format(\"{0}, {1}, {2}\", -1, 0, 1) == \"-1, 0, 1\");\n REQUIRE(format(\"{0}, {1}, {2}\", 'a', 'b', 'c') == \"a, b, c\");\n REQUIRE(format(\"{}, {}, {}\", 'a', 'b', 'c') == \"a, b, c\");\n REQUIRE(format(\"{2}, {1}, {0}\", 'a', 'b', 'c') == \"c, b, a\");\n REQUIRE(format(\"{0}{1}{0}\", \"abra\", \"cad\") == \"abracadabra\");\n REQUIRE(format(\"{:<30}\", \"left aligned\") == \"left aligned \");\n REQUIRE(format(\"{:>30}\", \"right aligned\") == \" right aligned\");\n REQUIRE(format(\"{:^30}\", \"centered\") == \" centered \");\n REQUIRE(format(\"{:*^30}\", \"centered\") == \"***********centered***********\");\n REQUIRE(format(\"{:+f}; {:+f}\", 3.14, -3.14) == \"+3.140000; -3.140000\");\n REQUIRE(format(\"{: f}; {: f}\", 3.14, -3.14) == \" 3.140000; -3.140000\");\n REQUIRE(format(\"{:-f}; {:-f}\", 3.14, -3.14) == \"3.140000; -3.140000\");\n REQUIRE(format(\"int: {0:d}; hex: {0:x}; oct: {0:o}; bin: {0:b}\", 42) == \"int: 42; hex: 2a; oct: 52; bin: 101010\");\n REQUIRE(format(\"int: {0:d}; hex: {0:#x}; oct: {0:#o}; bin: {0:#b}\", 42) == \"int: 42; hex: 0x2a; oct: 052; bin: 0b101010\");\n REQUIRE(format(\"The date is {}\", Date(2012, 12, 9)) == \"The date is 2012-12-9\");\n REQUIRE(format(\"Elapsed time: {s:.2f} seconds\", \"s\"_a = 1.23) == \"Elapsed time: 1.23 seconds\");\n REQUIRE(format(\"The answer is {}\"_format(42).c_str()) == \"The answer is 42\");\n*\/\n}\n<commit_msg>Clang<commit_after>\/\/\n\/\/ Created by Ivan Shynkarenka on 18.09.2016.\n\/\/\n\n#include \"catch.hpp\"\n\n#include \"logging\/record.h\"\n\nusing namespace CppLogging;\n\nclass Date\n{\npublic:\n Date(int year, int month, int day) : _year(year), _month(month), _day(day) {}\n\n friend std::ostream& operator<<(std::ostream& os, const Date& date)\n { return os << date._year << '-' << date._month << '-' << date._day; }\n\nprivate:\n int _year, _month, _day;\n};\n\ntemplate <typename... Args>\nstd::string format(const char* pattern, const Args&... args)\n{\n Record record;\n record.FormatSerialize(pattern, args...);\n record.FormatDeserialize();\n return record.message;\n}\n\nTEST_CASE(\"Format message\", \"[CppLogging]\")\n{\n\n REQUIRE(format(\"no arguments\") == \"no arguments\");\n REQUIRE(format(\"{0}, {1}, {2}\", -1, 0, 1) == \"-1, 0, 1\");\n\/*\n REQUIRE(format(\"{0}, {1}, {2}\", 'a', 'b', 'c') == \"a, b, c\");\n REQUIRE(format(\"{}, {}, {}\", 'a', 'b', 'c') == \"a, b, c\");\n REQUIRE(format(\"{2}, {1}, {0}\", 'a', 'b', 'c') == \"c, b, a\");\n REQUIRE(format(\"{0}{1}{0}\", \"abra\", \"cad\") == \"abracadabra\");\n REQUIRE(format(\"{:<30}\", \"left aligned\") == \"left aligned \");\n REQUIRE(format(\"{:>30}\", \"right aligned\") == \" right aligned\");\n REQUIRE(format(\"{:^30}\", \"centered\") == \" centered \");\n REQUIRE(format(\"{:*^30}\", \"centered\") == \"***********centered***********\");\n REQUIRE(format(\"{:+f}; {:+f}\", 3.14, -3.14) == \"+3.140000; -3.140000\");\n REQUIRE(format(\"{: f}; {: f}\", 3.14, -3.14) == \" 3.140000; -3.140000\");\n REQUIRE(format(\"{:-f}; {:-f}\", 3.14, -3.14) == \"3.140000; -3.140000\");\n REQUIRE(format(\"int: {0:d}; hex: {0:x}; oct: {0:o}; bin: {0:b}\", 42) == \"int: 42; hex: 2a; oct: 52; bin: 101010\");\n REQUIRE(format(\"int: {0:d}; hex: {0:#x}; oct: {0:#o}; bin: {0:#b}\", 42) == \"int: 42; hex: 0x2a; oct: 052; bin: 0b101010\");\n REQUIRE(format(\"The date is {}\", Date(2012, 12, 9)) == \"The date is 2012-12-9\");\n REQUIRE(format(\"Elapsed time: {s:.2f} seconds\", \"s\"_a = 1.23) == \"Elapsed time: 1.23 seconds\");\n REQUIRE(format(\"The answer is {}\"_format(42).c_str()) == \"The answer is 42\");\n*\/\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (C) 2017 Bastien Penavayre\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n *\/\n\n#pragma once\n#include \"println.hpp\"\n#include \"meta_tlist.hpp\"\n\ntemplate <class T> void unit(T);\n\nnamespace auto_testing\n{\n using unit_list = unconstexpr::meta_tlist<>;\n\n template <class Char, Char... chars>\n struct TestLogger final\n {\n template <int = unit_list::push_back<TestLogger>()>\n using pusher = TestLogger;\n\n static void run() { unit(TestLogger{}); }\n static constexpr Char repr[] = {chars..., ':', '\\0'};\n\n TestLogger() { log::Println(\"TESTING\", repr); }\n ~TestLogger() { log::Println(); }\n };\n\n template <class... Args>\n constexpr void run(detail::type_list<Args...>)\n {\n (Args::run(), ...);\n }\n};\n\ntemplate <class Char, Char... chars>\nconstexpr auto operator\"\"_logger_string() {\n return (typename auto_testing::TestLogger<Char, chars...>::template pusher<>){};\n}\n\n#define new_unit(x) template <> void unit(decltype(x ## _logger_string))\n#define run_units_so_far() auto_testing::run(auto_testing::unit_list::current_type<>{})\n<commit_msg>Add conditional macro DONT_USE_META in aut_testing.hpp<commit_after>\/*\n * Copyright (C) 2017 Bastien Penavayre\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n *\/\n\n#pragma once\n#include \"println.hpp\"\n\n#ifndef DONT_USE_META\n\n# include \"meta_tlist.hpp\"\ntemplate <class T> void unit(T);\n\nnamespace auto_testing\n{\n using unit_list = unconstexpr::meta_tlist<>;\n\n template <class Char, Char... chars>\n struct TestLogger final\n {\n template <int = unit_list::push_back<TestLogger>()>\n using pusher = TestLogger;\n\n static void run() { unit(TestLogger{}); }\n static constexpr Char repr[] = {chars..., ':', '\\0'};\n\n TestLogger() { log::Println(\"TESTING\", repr); }\n ~TestLogger() { log::Println(); }\n };\n\n template <class... Args>\n constexpr void run(detail::type_list<Args...>)\n {\n (Args::run(), ...);\n }\n};\n\ntemplate <class Char, Char... chars>\nconstexpr auto operator\"\"_logger_string() {\n return (typename auto_testing::TestLogger<Char, chars...>::template pusher<>){};\n}\n\n# define new_unit(x) template <> void unit(decltype(x ## _logger_string))\n# define run_units_so_far() auto_testing::run(auto_testing::unit_list::current_type<>{})\n\n#else \/*DONT_USE_META*\/\n\nnamespace auto_testing\n{\n template <class Char, Char... Chars>\n struct TestLogger final\n {\n static constexpr Char repr[] = {Chars..., ':', '\\0'};\n };\n\n template <size_t N, class Literal>\n struct Number final\n {\n Number(std::integral_constant<size_t, N>)\n {\n if constexpr(N != 0) log::Println();\n log::Println(\"TESTING\", Literal::repr);\n }\n };\n\n template <size_t... Indexs>\n constexpr auto make_integral(std::index_sequence<Indexs...>) ->\n std::tuple<std::integral_constant<size_t, Indexs>...>\n {\n return {};\n }\n}\n\ntemplate <class Char, Char... Chars>\nconstexpr auto operator\"\"_logger_string() -> auto_testing::TestLogger<Char, Chars...> {\n return {};\n}\n\n# define new_unit(x) \\\n void unit(auto_testing::Number<__COUNTER__, decltype(x ## _logger_string)>)\n\n# define run_units_so_far() \\\n std::apply([](auto... args) { (unit(args), ...); }, \\\n auto_testing::make_integral(std::make_index_sequence<__COUNTER__-1>{}));\n\n#endif \/*DONT_USE_META*\/\n<|endoftext|>"} {"text":"<commit_before>\/******************************************************************************\n* SOFA, Simulation Open-Framework Architecture, development version *\n* (c) 2006-2017 INRIA, USTL, UJF, CNRS, MGH *\n* *\n* This program is free software; you can redistribute it and\/or modify it *\n* under the terms of the GNU Lesser General Public License as published by *\n* the Free Software Foundation; either version 2.1 of the License, or (at *\n* your option) any later version. *\n* *\n* This program is distributed in the hope that it will be useful, but WITHOUT *\n* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or *\n* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License *\n* for more details. *\n* *\n* You should have received a copy of the GNU Lesser General Public License *\n* along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>. *\n*******************************************************************************\n* Authors: The SOFA Team and external contributors (see Authors.txt) *\n* *\n* Contact information: contact@sofa-framework.org *\n******************************************************************************\/\n#include <SofaBaseCollision\/DefaultPipeline.h>\n\n#include <sofa\/core\/CollisionModel.h>\n#include <sofa\/core\/ObjectFactory.h>\n#include <sofa\/core\/collision\/BroadPhaseDetection.h>\n#include <sofa\/core\/collision\/NarrowPhaseDetection.h>\n#include <sofa\/core\/collision\/CollisionGroupManager.h>\n#include <sofa\/core\/collision\/ContactManager.h>\n#include <sofa\/core\/visual\/VisualParams.h>\n\n#include <sofa\/simulation\/Node.h>\n\n#ifdef SOFA_DUMP_VISITOR_INFO\n#include <sofa\/simulation\/Visitor.h>\n#endif\n\n#include <sofa\/helper\/AdvancedTimer.h>\nusing sofa::helper::AdvancedTimer ;\nusing sofa::helper::ScopedAdvancedTimer ;\n\n\nnamespace sofa\n{\n\nnamespace component\n{\n\nnamespace collision\n{\n\nusing namespace core;\nusing namespace core::objectmodel;\nusing namespace core::collision;\nusing namespace sofa::defaulttype;\n\nSOFA_DECL_CLASS(DefaultPipeline)\n\nint DefaultPipelineClass = core::RegisterObject(\"The default collision detection and modeling pipeline\")\n .add< DefaultPipeline >()\n .addAlias(\"CollisionPipeline\")\n ;\n\nDefaultPipeline::DefaultPipeline()\n : d_doPrintInfoMessage(initData(&d_doPrintInfoMessage, false, \"verbose\",\n \"Display extra informations at each computation step. (default=false)\"))\n , d_doDebugDraw(initData(&d_doDebugDraw, false, \"draw\",\n \"Draw the detected collisions. (default=false)\"))\n \/\/TODO(dmarchal) fix the min & max value with response from discussion.\n , d_depth(initData(&d_depth, 6, \"depth\",\n \"Max depth of bounding trees. (default=6, min=?, max=?)\"))\n{\n}\n\n#ifdef SOFA_DUMP_VISITOR_INFO\ntypedef simulation::Visitor::ctime_t ctime_t;\n#endif\n\nvoid DefaultPipeline::init()\n{\n if(d_depth.getValue() < 0)\n {\n msg_warning() << \"Invalid value 'depth'=\"<<d_depth.getValue() << \".\" << msgendl\n << \"Replaced with the default value = 6.\" ;\n d_depth.setValue(6) ;\n }\n}\n\nvoid DefaultPipeline::doCollisionReset()\n{\n msg_info_when(d_doPrintInfoMessage.getValue())\n << \"DefaultPipeline::doCollisionReset\" ;\n\n core::objectmodel::BaseContext* scene = getContext();\n \/\/ clear all contacts\n if (contactManager!=nullptr)\n {\n const helper::vector<Contact::SPtr>& contacts = contactManager->getContacts();\n for (helper::vector<Contact::SPtr>::const_iterator it = contacts.begin(); it!=contacts.end(); ++it)\n {\n (*it)->removeResponse();\n }\n }\n \/\/ clear all collision groups\n if (groupManager!=nullptr)\n {\n groupManager->clearGroups(scene);\n }\n}\n\nvoid DefaultPipeline::doCollisionDetection(const helper::vector<core::CollisionModel*>& collisionModels)\n{\n ScopedAdvancedTimer docollisiontimer(\"doCollisionDetection\");\n\n msg_info_when(d_doPrintInfoMessage.getValue())\n << \"doCollisionDetection, compute Bounding Trees\" ;\n\n \/\/ First, we compute a bounding volume for the collision model (for example bounding sphere)\n \/\/ or we have loaded a collision model that knows its other model\n\n helper::vector<CollisionModel*> vectBoundingVolume;\n {\n ScopedAdvancedTimer bboxtimer(\"BBox\");\n\n#ifdef SOFA_DUMP_VISITOR_INFO\n simulation::Visitor::printNode(\"ComputeBoundingTree\");\n#endif\n const bool continuous = intersectionMethod->useContinuous();\n const SReal dt = getContext()->getDt();\n\n helper::vector<CollisionModel*>::const_iterator it;\n const helper::vector<CollisionModel*>::const_iterator itEnd = collisionModels.end();\n int nActive = 0;\n\n for (it = collisionModels.begin(); it != itEnd; ++it)\n {\n msg_info_when(d_doPrintInfoMessage.getValue())\n << \"doCollisionDetection, consider model\" ;\n\n if (!(*it)->isActive()) continue;\n\n int used_depth = broadPhaseDetection->needsDeepBoundingTree() ? d_depth.getValue() : 0;\n\n if (continuous)\n (*it)->computeContinuousBoundingTree(dt, used_depth);\n else\n (*it)->computeBoundingTree(used_depth);\n\n vectBoundingVolume.push_back ((*it)->getFirst());\n ++nActive;\n }\n\n#ifdef SOFA_DUMP_VISITOR_INFO\n simulation::Visitor::printCloseNode(\"ComputeBoundingTree\");\n#endif\n\n msg_info_when(d_doPrintInfoMessage.getValue())\n << \"doCollisionDetection, Computed \"<<nActive<<\" BBoxs\" ;\n }\n \/\/ then we start the broad phase\n if (broadPhaseDetection==nullptr) return; \/\/ can't go further\n\n msg_info_when(d_doPrintInfoMessage.getValue())\n << \"doCollisionDetection, BroadPhaseDetection \"<<broadPhaseDetection->getName();\n\n#ifdef SOFA_DUMP_VISITOR_INFO\n simulation::Visitor::printNode(\"BroadPhase\");\n#endif\n {\n ScopedAdvancedTimer broadphase(\"BroadPhase\");\n intersectionMethod->beginBroadPhase();\n broadPhaseDetection->beginBroadPhase();\n broadPhaseDetection->addCollisionModels(vectBoundingVolume); \/\/ detection is done there\n broadPhaseDetection->endBroadPhase();\n intersectionMethod->endBroadPhase();\n }\n#ifdef SOFA_DUMP_VISITOR_INFO\n simulation::Visitor::printCloseNode(\"BroadPhase\");\n#endif\n\n \/\/ then we start the narrow phase\n if (narrowPhaseDetection==nullptr) return; \/\/ can't go further\n\n msg_info_when(d_doPrintInfoMessage.getValue())\n << \"doCollisionDetection, NarrowPhaseDetection \"<<narrowPhaseDetection->getName();\n\n#ifdef SOFA_DUMP_VISITOR_INFO\n simulation::Visitor::printNode(\"NarrowPhase\");\n#endif\n {\n ScopedAdvancedTimer narrowphase(\"NarrowPhase\");\n intersectionMethod->beginNarrowPhase();\n narrowPhaseDetection->beginNarrowPhase();\n helper::vector<std::pair<CollisionModel*, CollisionModel*> >& vectCMPair = broadPhaseDetection->getCollisionModelPairs();\n\n msg_info_when(d_doPrintInfoMessage.getValue())\n << \"doCollisionDetection, \"<< vectCMPair.size()<<\" colliding model pairs\" ;\n\n narrowPhaseDetection->addCollisionPairs(vectCMPair);\n narrowPhaseDetection->endNarrowPhase();\n intersectionMethod->endNarrowPhase();\n }\n#ifdef SOFA_DUMP_VISITOR_INFO\n simulation::Visitor::printCloseNode(\"NarrowPhase\");\n#endif\n\n}\n\nvoid DefaultPipeline::doCollisionResponse()\n{\n core::objectmodel::BaseContext* scene = getContext();\n \/\/ then we start the creation of contacts\n if (contactManager==nullptr) return; \/\/ can't go further\n\n msg_info_when(d_doPrintInfoMessage.getValue())\n << \"Create Contacts \"<<contactManager->getName() ;\n\n contactManager->createContacts(narrowPhaseDetection->getDetectionOutputs());\n\n \/\/ finally we start the creation of collisionGroup\n\n const helper::vector<Contact::SPtr>& contacts = contactManager->getContacts();\n\n \/\/ First we remove all contacts with non-simulated objects and directly add them\n helper::vector<Contact::SPtr> notStaticContacts;\n\n for (helper::vector<Contact::SPtr>::const_iterator it = contacts.begin(); it!=contacts.end(); ++it)\n {\n Contact::SPtr c = *it;\n if (!c->getCollisionModels().first->isSimulated())\n {\n c->createResponse(c->getCollisionModels().second->getContext());\n }\n else if (!c->getCollisionModels().second->isSimulated())\n {\n c->createResponse(c->getCollisionModels().first->getContext());\n }\n else\n notStaticContacts.push_back(c);\n }\n\n if (groupManager==nullptr)\n {\n msg_info_when(d_doPrintInfoMessage.getValue())\n << \"Linking all contacts to Scene\" ;\n\n for (helper::vector<Contact::SPtr>::const_iterator it = notStaticContacts.begin(); it!=notStaticContacts.end(); ++it)\n {\n (*it)->createResponse(scene);\n }\n }\n else\n {\n msg_info_when(d_doPrintInfoMessage.getValue())\n << \"Create Groups \"<<groupManager->getName();\n\n groupManager->createGroups(scene, notStaticContacts);\n }\n}\n\nstd::set< std::string > DefaultPipeline::getResponseList() const\n{\n std::set< std::string > listResponse;\n core::collision::Contact::Factory::iterator it;\n for (it=core::collision::Contact::Factory::getInstance()->begin(); it!=core::collision::Contact::Factory::getInstance()->end(); ++it)\n {\n listResponse.insert(it->first);\n }\n return listResponse;\n}\n\nvoid DefaultPipeline::draw(const core::visual::VisualParams* )\n{\n if (!d_doDebugDraw.getValue()) return;\n if (!narrowPhaseDetection) return;\n\n\/\/TODO(dmarchal): remove this code or reactivate or do a proper #ifdef\n\/\/TODO(dmarchal): it makes also no sense to keep a 'draw' attribute while nothing is displayed.\n#if 0\n glDisable(GL_LIGHTING);\n glLineWidth(2);\n glBegin(GL_LINES);\n DetectionOutputMap& outputsMap = narrowPhaseDetection->getDetectionOutputs();\n for (DetectionOutputMap::iterator it = outputsMap.begin(); it!=outputsMap.end(); it++)\n {\n \/*\n DetectionOutputVector& outputs = it->second;\n for (DetectionOutputVector::iterator it2 = outputs.begin(); it2!=outputs.end(); it2++)\n {\n DetectionOutput* d = &*it2;\n if (d->distance<0)\n glColor3f(1.0f,0.5f,0.5f);\n else\n glColor3f(0.5f,1.0f,0.5f);\n glVertex3dv(d->point[0].ptr());\n glVertex3dv(d->point[1].ptr());\n }\n *\/\n }\n glEnd();\n glLineWidth(1);\n#endif\n}\n} \/\/ namespace collision\n\n} \/\/ namespace component\n\n} \/\/ namespace sofa\n\n<commit_msg>[SofaKernel] DefaultPipeline.cpp fix invalid init that cause crashes<commit_after>\/******************************************************************************\n* SOFA, Simulation Open-Framework Architecture, development version *\n* (c) 2006-2017 INRIA, USTL, UJF, CNRS, MGH *\n* *\n* This program is free software; you can redistribute it and\/or modify it *\n* under the terms of the GNU Lesser General Public License as published by *\n* the Free Software Foundation; either version 2.1 of the License, or (at *\n* your option) any later version. *\n* *\n* This program is distributed in the hope that it will be useful, but WITHOUT *\n* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or *\n* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License *\n* for more details. *\n* *\n* You should have received a copy of the GNU Lesser General Public License *\n* along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>. *\n*******************************************************************************\n* Authors: The SOFA Team and external contributors (see Authors.txt) *\n* *\n* Contact information: contact@sofa-framework.org *\n******************************************************************************\/\n#include <SofaBaseCollision\/DefaultPipeline.h>\n\n#include <sofa\/core\/CollisionModel.h>\n#include <sofa\/core\/ObjectFactory.h>\n#include <sofa\/core\/collision\/BroadPhaseDetection.h>\n#include <sofa\/core\/collision\/NarrowPhaseDetection.h>\n#include <sofa\/core\/collision\/CollisionGroupManager.h>\n#include <sofa\/core\/collision\/ContactManager.h>\n#include <sofa\/core\/visual\/VisualParams.h>\n\n#include <sofa\/simulation\/Node.h>\n\n#ifdef SOFA_DUMP_VISITOR_INFO\n#include <sofa\/simulation\/Visitor.h>\n#endif\n\n#include <sofa\/helper\/AdvancedTimer.h>\nusing sofa::helper::AdvancedTimer ;\nusing sofa::helper::ScopedAdvancedTimer ;\n\n\nnamespace sofa\n{\n\nnamespace component\n{\n\nnamespace collision\n{\n\nusing namespace core;\nusing namespace core::objectmodel;\nusing namespace core::collision;\nusing namespace sofa::defaulttype;\n\nSOFA_DECL_CLASS(DefaultPipeline)\n\nint DefaultPipelineClass = core::RegisterObject(\"The default collision detection and modeling pipeline\")\n .add< DefaultPipeline >()\n .addAlias(\"CollisionPipeline\")\n ;\n\nDefaultPipeline::DefaultPipeline()\n : d_doPrintInfoMessage(initData(&d_doPrintInfoMessage, false, \"verbose\",\n \"Display extra informations at each computation step. (default=false)\"))\n , d_doDebugDraw(initData(&d_doDebugDraw, false, \"draw\",\n \"Draw the detected collisions. (default=false)\"))\n\n \/\/TODO(dmarchal 2017-05-16) Fix the min & max value with response from a github issue. Remove in 1 year if not done.\n , d_depth(initData(&d_depth, 6, \"depth\",\n \"Max depth of bounding trees. (default=6, min=?, max=?)\"))\n{\n}\n\n#ifdef SOFA_DUMP_VISITOR_INFO\ntypedef simulation::Visitor::ctime_t ctime_t;\n#endif\n\nvoid DefaultPipeline::init()\n{\n Inherit1::init() ;\n if(d_depth.getValue() < 0)\n {\n msg_warning() << \"Invalid value 'depth'=\"<<d_depth.getValue() << \".\" << msgendl\n << \"Replaced with the default value = 6.\" ;\n d_depth.setValue(6) ;\n }\n}\n\nvoid DefaultPipeline::doCollisionReset()\n{\n msg_info_when(d_doPrintInfoMessage.getValue())\n << \"DefaultPipeline::doCollisionReset\" ;\n\n core::objectmodel::BaseContext* scene = getContext();\n \/\/ clear all contacts\n if (contactManager!=nullptr)\n {\n const helper::vector<Contact::SPtr>& contacts = contactManager->getContacts();\n for (helper::vector<Contact::SPtr>::const_iterator it = contacts.begin(); it!=contacts.end(); ++it)\n {\n (*it)->removeResponse();\n }\n }\n \/\/ clear all collision groups\n if (groupManager!=nullptr)\n {\n groupManager->clearGroups(scene);\n }\n}\n\nvoid DefaultPipeline::doCollisionDetection(const helper::vector<core::CollisionModel*>& collisionModels)\n{\n ScopedAdvancedTimer docollisiontimer(\"doCollisionDetection\");\n\n msg_info_when(d_doPrintInfoMessage.getValue())\n << \"doCollisionDetection, compute Bounding Trees\" ;\n\n \/\/ First, we compute a bounding volume for the collision model (for example bounding sphere)\n \/\/ or we have loaded a collision model that knows its other model\n\n helper::vector<CollisionModel*> vectBoundingVolume;\n {\n ScopedAdvancedTimer bboxtimer(\"BBox\");\n\n#ifdef SOFA_DUMP_VISITOR_INFO\n simulation::Visitor::printNode(\"ComputeBoundingTree\");\n#endif\n const bool continuous = intersectionMethod->useContinuous();\n const SReal dt = getContext()->getDt();\n\n helper::vector<CollisionModel*>::const_iterator it;\n const helper::vector<CollisionModel*>::const_iterator itEnd = collisionModels.end();\n int nActive = 0;\n\n for (it = collisionModels.begin(); it != itEnd; ++it)\n {\n msg_info_when(d_doPrintInfoMessage.getValue())\n << \"doCollisionDetection, consider model\" ;\n\n if (!(*it)->isActive()) continue;\n\n int used_depth = broadPhaseDetection->needsDeepBoundingTree() ? d_depth.getValue() : 0;\n\n if (continuous)\n (*it)->computeContinuousBoundingTree(dt, used_depth);\n else\n (*it)->computeBoundingTree(used_depth);\n\n vectBoundingVolume.push_back ((*it)->getFirst());\n ++nActive;\n }\n\n#ifdef SOFA_DUMP_VISITOR_INFO\n simulation::Visitor::printCloseNode(\"ComputeBoundingTree\");\n#endif\n\n msg_info_when(d_doPrintInfoMessage.getValue())\n << \"doCollisionDetection, Computed \"<<nActive<<\" BBoxs\" ;\n }\n \/\/ then we start the broad phase\n if (broadPhaseDetection==nullptr) return; \/\/ can't go further\n\n msg_info_when(d_doPrintInfoMessage.getValue())\n << \"doCollisionDetection, BroadPhaseDetection \"<<broadPhaseDetection->getName();\n\n#ifdef SOFA_DUMP_VISITOR_INFO\n simulation::Visitor::printNode(\"BroadPhase\");\n#endif\n {\n ScopedAdvancedTimer broadphase(\"BroadPhase\");\n intersectionMethod->beginBroadPhase();\n broadPhaseDetection->beginBroadPhase();\n broadPhaseDetection->addCollisionModels(vectBoundingVolume); \/\/ detection is done there\n broadPhaseDetection->endBroadPhase();\n intersectionMethod->endBroadPhase();\n }\n#ifdef SOFA_DUMP_VISITOR_INFO\n simulation::Visitor::printCloseNode(\"BroadPhase\");\n#endif\n\n \/\/ then we start the narrow phase\n if (narrowPhaseDetection==nullptr) return; \/\/ can't go further\n\n msg_info_when(d_doPrintInfoMessage.getValue())\n << \"doCollisionDetection, NarrowPhaseDetection \"<<narrowPhaseDetection->getName();\n\n#ifdef SOFA_DUMP_VISITOR_INFO\n simulation::Visitor::printNode(\"NarrowPhase\");\n#endif\n {\n ScopedAdvancedTimer narrowphase(\"NarrowPhase\");\n intersectionMethod->beginNarrowPhase();\n narrowPhaseDetection->beginNarrowPhase();\n helper::vector<std::pair<CollisionModel*, CollisionModel*> >& vectCMPair = broadPhaseDetection->getCollisionModelPairs();\n\n msg_info_when(d_doPrintInfoMessage.getValue())\n << \"doCollisionDetection, \"<< vectCMPair.size()<<\" colliding model pairs\" ;\n\n narrowPhaseDetection->addCollisionPairs(vectCMPair);\n narrowPhaseDetection->endNarrowPhase();\n intersectionMethod->endNarrowPhase();\n }\n#ifdef SOFA_DUMP_VISITOR_INFO\n simulation::Visitor::printCloseNode(\"NarrowPhase\");\n#endif\n\n}\n\nvoid DefaultPipeline::doCollisionResponse()\n{\n core::objectmodel::BaseContext* scene = getContext();\n \/\/ then we start the creation of contacts\n if (contactManager==nullptr) return; \/\/ can't go further\n\n msg_info_when(d_doPrintInfoMessage.getValue())\n << \"Create Contacts \"<<contactManager->getName() ;\n\n contactManager->createContacts(narrowPhaseDetection->getDetectionOutputs());\n\n \/\/ finally we start the creation of collisionGroup\n\n const helper::vector<Contact::SPtr>& contacts = contactManager->getContacts();\n\n \/\/ First we remove all contacts with non-simulated objects and directly add them\n helper::vector<Contact::SPtr> notStaticContacts;\n\n for (helper::vector<Contact::SPtr>::const_iterator it = contacts.begin(); it!=contacts.end(); ++it)\n {\n Contact::SPtr c = *it;\n if (!c->getCollisionModels().first->isSimulated())\n {\n c->createResponse(c->getCollisionModels().second->getContext());\n }\n else if (!c->getCollisionModels().second->isSimulated())\n {\n c->createResponse(c->getCollisionModels().first->getContext());\n }\n else\n notStaticContacts.push_back(c);\n }\n\n if (groupManager==nullptr)\n {\n msg_info_when(d_doPrintInfoMessage.getValue())\n << \"Linking all contacts to Scene\" ;\n\n for (helper::vector<Contact::SPtr>::const_iterator it = notStaticContacts.begin(); it!=notStaticContacts.end(); ++it)\n {\n (*it)->createResponse(scene);\n }\n }\n else\n {\n msg_info_when(d_doPrintInfoMessage.getValue())\n << \"Create Groups \"<<groupManager->getName();\n\n groupManager->createGroups(scene, notStaticContacts);\n }\n}\n\nstd::set< std::string > DefaultPipeline::getResponseList() const\n{\n std::set< std::string > listResponse;\n core::collision::Contact::Factory::iterator it;\n for (it=core::collision::Contact::Factory::getInstance()->begin(); it!=core::collision::Contact::Factory::getInstance()->end(); ++it)\n {\n listResponse.insert(it->first);\n }\n return listResponse;\n}\n\nvoid DefaultPipeline::draw(const core::visual::VisualParams* )\n{\n if (!d_doDebugDraw.getValue()) return;\n if (!narrowPhaseDetection) return;\n\n\/\/TODO(dmarchal 2017-05-17): remove this code or reactivate or do a proper #ifdef\n\/\/TODO(dmarchal): it makes also no sense to keep a 'draw' attribute while nothing is displayed.\n#if 0\n glDisable(GL_LIGHTING);\n glLineWidth(2);\n glBegin(GL_LINES);\n DetectionOutputMap& outputsMap = narrowPhaseDetection->getDetectionOutputs();\n for (DetectionOutputMap::iterator it = outputsMap.begin(); it!=outputsMap.end(); it++)\n {\n \/*\n DetectionOutputVector& outputs = it->second;\n for (DetectionOutputVector::iterator it2 = outputs.begin(); it2!=outputs.end(); it2++)\n {\n DetectionOutput* d = &*it2;\n if (d->distance<0)\n glColor3f(1.0f,0.5f,0.5f);\n else\n glColor3f(0.5f,1.0f,0.5f);\n glVertex3dv(d->point[0].ptr());\n glVertex3dv(d->point[1].ptr());\n }\n *\/\n }\n glEnd();\n glLineWidth(1);\n#endif\n}\n} \/\/ namespace collision\n\n} \/\/ namespace component\n\n} \/\/ namespace sofa\n\n<|endoftext|>"} {"text":"<commit_before>\/*\r\n Copyright (c) 2014, The Cinder Project\r\n\r\n This code is intended to be used with the Cinder C++ library, http:\/\/libcinder.org\r\n\r\n Redistribution and use in source and binary forms, with or without modification, are permitted provided that\r\n the following conditions are met:\r\n\r\n * Redistributions of source code must retain the above copyright notice, this list of conditions and\r\n the following disclaimer.\r\n * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and\r\n the following disclaimer in the documentation and\/or other materials provided with the distribution.\r\n\r\n THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED\r\n WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A\r\n PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR\r\n ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED\r\n TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\r\n HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\r\n NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\r\n POSSIBILITY OF SUCH DAMAGE.\r\n *\/\r\n\r\n\r\n#include \"cinder\/audio\/Node.h\"\r\n#include \"cinder\/audio\/DelayNode.h\"\r\n#include \"cinder\/audio\/Context.h\"\r\n#include \"cinder\/audio\/dsp\/Dsp.h\"\r\n#include \"cinder\/audio\/dsp\/Converter.h\"\r\n#include \"cinder\/audio\/Debug.h\"\r\n#include \"cinder\/CinderAssert.h\"\r\n#include \"cinder\/System.h\"\r\n\r\n#include <limits>\r\n\r\nusing namespace std;\r\n\r\nnamespace cinder { namespace audio {\r\n\r\n\/\/ ----------------------------------------------------------------------------------------------------\r\n\/\/ MARK: - Node\r\n\/\/ ----------------------------------------------------------------------------------------------------\r\n\r\nNode::Node( const Format &format )\r\n\t: mInitialized( false ), mEnabled( false ),\tmChannelMode( format.getChannelMode() ),\r\n\t\tmNumChannels( 1 ), mAutoEnabled( true ), mProcessInPlace( true ), mLastProcessedFrame( numeric_limits<uint64_t>::max() )\r\n{\r\n\tif( format.getChannels() ) {\r\n\t\tmNumChannels = format.getChannels();\r\n\t\tmChannelMode = ChannelMode::SPECIFIED;\r\n\t}\r\n\r\n\tif( ! boost::indeterminate( format.getAutoEnable() ) )\r\n\t\tsetAutoEnabled( format.getAutoEnable() );\r\n}\r\n\r\nNode::~Node()\r\n{\r\n}\r\n\r\nvoid Node::connect( const NodeRef &output )\r\n{\r\n\t\/\/ make a reference to ourselves so that we aren't deallocated in the case of the last owner\r\n\t\/\/ disconnecting us, which we may need later anyway\r\n\tNodeRef thisRef = shared_from_this();\r\n\r\n\tif( ! output->canConnectToInput( thisRef ) )\r\n\t\treturn;\r\n\r\n\tif( checkCycle( thisRef, output ) )\r\n\t\tthrow NodeCycleExc( thisRef, output );\r\n\r\n\tmOutputs.push_back( output ); \/\/ set output first, so that it is visible in configureConnections()\r\n\toutput->connectInput( thisRef );\r\n\r\n\toutput->notifyConnectionsDidChange();\r\n}\r\n\r\nvoid Node::disconnect( const NodeRef &output )\r\n{\r\n\tif( ! output )\r\n\t\treturn;\r\n\r\n\tfor( auto weakOutIt = mOutputs.begin(); weakOutIt != mOutputs.end(); ++weakOutIt ) {\r\n\t\tif( weakOutIt->lock() == output ) {\r\n\t\t\tmOutputs.erase( weakOutIt );\r\n\t\t\tbreak;\r\n\t\t}\r\n\t}\r\n\r\n\toutput->disconnectInput( shared_from_this() );\r\n\toutput->notifyConnectionsDidChange();\r\n}\r\n\r\nvoid Node::disconnectAll()\r\n{\r\n\tdisconnectAllInputs();\r\n\tdisconnectAllOutputs();\r\n}\r\n\r\nvoid Node::disconnectAllOutputs()\r\n{\r\n\tNodeRef thisRef = shared_from_this();\r\n\r\n\tauto outputs = getOutputs(); \/\/ first make a copy of only the still-alive NodeRef's\r\n\tfor( const auto &output : outputs )\r\n\t\tdisconnect( output );\r\n}\r\n\r\nvoid Node::disconnectAllInputs()\r\n{\r\n\tNodeRef thisRef = shared_from_this();\r\n\r\n\tfor( auto &input : mInputs )\r\n\t\tinput->disconnectOutput( thisRef );\r\n\r\n\tmInputs.clear();\r\n\tnotifyConnectionsDidChange();\r\n}\r\n\r\nvoid Node::connectInput( const NodeRef &input )\r\n{\r\n\tlock_guard<mutex> lock( getContext()->getMutex() );\r\n\r\n\tmInputs.insert( input );\r\n\tconfigureConnections();\r\n}\r\n\r\nvoid Node::disconnectInput( const NodeRef &input )\r\n{\r\n\tlock_guard<mutex> lock( getContext()->getMutex() );\r\n\r\n\tfor( auto inIt = mInputs.begin(); inIt != mInputs.end(); ++inIt ) {\r\n\t\tif( *inIt == input ) {\r\n\t\t\tmInputs.erase( inIt );\r\n\t\t\tbreak;\r\n\t\t}\r\n\t}\r\n}\r\n\r\nvoid Node::disconnectOutput( const NodeRef &output )\r\n{\r\n\tlock_guard<mutex> lock( getContext()->getMutex() );\r\n\r\n\tfor( auto outIt = mOutputs.begin(); outIt != mOutputs.end(); ++outIt ) {\r\n\t\tif( outIt->lock() == output ) {\r\n\t\t\tmOutputs.erase( outIt );\r\n\t\t\tbreak;\r\n\t\t}\r\n\t}\r\n}\r\n\r\nvector<NodeRef> Node::getOutputs() const\r\n{\r\n\tvector<NodeRef> result;\r\n\tfor( const weak_ptr<Node> &outputWeak : mOutputs ) {\r\n\t\tNodeRef output = outputWeak.lock();\r\n\t\tif( output )\r\n\t\t\tresult.push_back( output );\r\n\t}\r\n\r\n\treturn result;\r\n}\r\n\r\nvoid Node::enable()\r\n{\r\n\tif( ! mInitialized )\r\n\t\tinitializeImpl();\r\n\r\n\tif( mEnabled )\r\n\t\treturn;\r\n\r\n\tmEnabled = true;\r\n\tenableProcessing();\r\n}\r\n\r\nvoid Node::disable()\r\n{\r\n\tif( ! mEnabled )\r\n\t\treturn;\r\n\r\n\tmEnabled = false;\r\n\tdisableProcessing();\r\n}\r\n\r\nvoid Node::setEnabled( bool b )\r\n{\r\n\tif( b )\r\n\t\tenable();\r\n\telse\r\n\t\tdisable();\r\n}\r\n\r\nsize_t Node::getNumConnectedInputs() const\r\n{\r\n\treturn mInputs.size();\r\n}\r\n\r\nsize_t Node::getNumConnectedOutputs() const\r\n{\r\n\treturn mOutputs.size();\r\n}\r\n\r\nvoid Node::initializeImpl()\r\n{\r\n\tif( mInitialized )\r\n\t\treturn;\r\n\r\n\tif( mProcessInPlace && ! supportsProcessInPlace() )\r\n\t\tsetupProcessWithSumming();\r\n\r\n\tinitialize();\r\n\tmInitialized = true;\r\n\r\n\tif( mAutoEnabled )\r\n\t\tenable();\r\n}\r\n\r\n\r\nvoid Node::uninitializeImpl()\r\n{\r\n\tif( ! mInitialized )\r\n\t\treturn;\r\n\r\n\tdisable();\r\n\tuninitialize();\r\n\tmInitialized = false;\r\n}\r\n\r\nvoid Node::setNumChannels( size_t numChannels )\r\n{\r\n\tif( mNumChannels == numChannels )\r\n\t\treturn;\r\n\r\n\tuninitializeImpl();\r\n\tmNumChannels = numChannels;\r\n}\r\n\r\nvoid Node::setChannelMode( ChannelMode mode )\r\n{\r\n\tCI_ASSERT_MSG( ! mInitialized, \"setting the channel mode must be done before initializing\" );\r\n\r\n\tif( mChannelMode == mode )\r\n\t\treturn;\r\n\r\n\tmChannelMode = mode;\r\n}\r\n\r\nsize_t Node::getMaxNumInputChannels() const\r\n{\r\n\tsize_t result = 0;\r\n\tfor( auto &in : mInputs )\r\n\t\tresult = max( result, in->getNumChannels() );\r\n\r\n\treturn result;\r\n}\r\n\r\nsize_t Node::getSampleRate() const\r\n{\r\n\treturn getContext()->getSampleRate();\r\n}\r\n\r\nsize_t Node::getFramesPerBlock() const\r\n{\r\n\treturn getContext()->getFramesPerBlock();\r\n}\r\n\r\n\/\/ TODO: Checking for DelayNode below is a kludge and will not work for other types that want to support feedback.\r\n\/\/\t\t With more investigation it might be possible to avoid this, or at least define some interface that\r\n\/\/ specifies whether this input needs to be summed.\r\nvoid Node::configureConnections()\r\n{\r\n\tCI_ASSERT( getContext() );\r\n\r\n\tmProcessInPlace = supportsProcessInPlace();\r\n\r\n\tif( getNumConnectedInputs() > 1 || getNumConnectedOutputs() > 1 )\r\n\t\tmProcessInPlace = false;\r\n\r\n\tbool isDelay = ( dynamic_cast<DelayNode *>( this ) != nullptr ); \/\/ see note above\r\n\r\n\tfor( auto &input : mInputs ) {\r\n\t\tbool inputProcessInPlace = true;\r\n\r\n\t\tsize_t inputNumChannels = input->getNumChannels();\r\n\t\tif( ! supportsInputNumChannels( inputNumChannels ) ) {\r\n\t\t\tif( mChannelMode == ChannelMode::MATCHES_INPUT )\r\n\t\t\t\tsetNumChannels( getMaxNumInputChannels() );\r\n\t\t\telse if( input->getChannelMode() == ChannelMode::MATCHES_OUTPUT ) {\r\n\t\t\t\tinput->setNumChannels( mNumChannels );\r\n\t\t\t\tinput->configureConnections();\r\n\t\t\t}\r\n\t\t\telse {\r\n\t\t\t\tmProcessInPlace = false;\r\n\t\t\t\tinputProcessInPlace = false;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t\/\/ inputs with more than one output cannot process in-place, so make them sum\r\n\t\tif( input->getProcessInPlace() && input->getNumConnectedOutputs() > 1 )\r\n\t\t\tinputProcessInPlace = false;\r\n\r\n\t\t\/\/ if we're unable to process in-place and we're a DelayNode, its possible that the input may be part of a feedback loop, in which case input must sum.\r\n\t\tif( ! mProcessInPlace && isDelay )\r\n\t\t\tinputProcessInPlace = false;\r\n\r\n\t\tif( ! inputProcessInPlace )\r\n\t\t\tinput->setupProcessWithSumming();\r\n\r\n\t\tinput->initializeImpl();\r\n\t}\r\n\r\n\tfor( auto &out : mOutputs ) {\r\n\t\tNodeRef output = out.lock();\r\n\t\tif( ! output )\r\n\t\t\tcontinue;\r\n\t\tif( ! output->supportsInputNumChannels( mNumChannels ) ) {\r\n\t\t\tif( output->getChannelMode() == ChannelMode::MATCHES_INPUT ) {\r\n\t\t\t\toutput->setNumChannels( mNumChannels );\r\n\t\t\t\toutput->configureConnections();\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t\tmProcessInPlace = false;\r\n\t\t}\r\n\t}\r\n\r\n\tif( ! mProcessInPlace )\r\n\t\tsetupProcessWithSumming();\r\n\r\n\tinitializeImpl();\r\n}\r\n\r\nvoid Node::pullInputs( Buffer *inPlaceBuffer )\r\n{\r\n\tCI_ASSERT( getContext() );\r\n\r\n\tif( mProcessInPlace ) {\r\n\t\tif( mInputs.empty() ) {\r\n\t\t\t\/\/ Fastest route: no inputs and process in-place. If disabled, get rid of any previously processsed samples.\r\n\t\t\tif( mEnabled )\r\n\t\t\t\tprocess( inPlaceBuffer );\r\n\t\t\telse\r\n\t\t\t\tinPlaceBuffer->zero();\r\n\t\t}\r\n\t\telse {\r\n\t\t\t\/\/ First pull the input (can only be one when in-place), then run process() if input did any processing.\r\n\t\t\tconst NodeRef &input = *mInputs.begin();\r\n\t\t\tinput->pullInputs( inPlaceBuffer );\r\n\r\n\t\t\tif( ! input->getProcessInPlace() )\r\n\t\t\t\tdsp::mixBuffers( input->getInternalBuffer(), inPlaceBuffer );\r\n\r\n\t\t\tif( mEnabled )\r\n\t\t\t\tprocess( inPlaceBuffer );\r\n\t\t}\r\n\t}\r\n\telse {\r\n\t\t\/\/ Pull and sum all enabled inputs. Only do this once per processing block, which is checked by the current number of processed frames.\r\n\t\tuint64_t numProcessedFrames = getContext()->getNumProcessedFrames();\r\n\t\tif( mLastProcessedFrame != numProcessedFrames ) {\r\n\t\t\tmLastProcessedFrame = numProcessedFrames;\r\n\r\n\t\t\tmSummingBuffer.zero();\r\n\t\t\tsumInputs();\r\n\t\t}\r\n\t}\r\n}\r\n\r\nvoid Node::sumInputs()\r\n{\r\n\t\/\/ Pull all inputs, summing the results from the buffer that input used for processing.\r\n\t\/\/ mInternalBuffer is not zero'ed before pulling inputs to allow for feedback.\r\n\tfor( auto &input : mInputs ) {\r\n\t\tinput->pullInputs( &mInternalBuffer );\r\n\t\tconst Buffer *processedBuffer = input->getProcessInPlace() ? &mInternalBuffer : input->getInternalBuffer();\r\n\t\tdsp::sumBuffers( processedBuffer, &mSummingBuffer );\r\n\t}\r\n\r\n\t\/\/ Process the summed results if enabled.\r\n\tif( mEnabled )\r\n\t\tprocess( &mSummingBuffer );\r\n\r\n\t\/\/ copy summed buffer back to internal so downstream can get it.\r\n\tdsp::mixBuffers( &mSummingBuffer, &mInternalBuffer );\r\n}\r\n\r\nvoid Node::setupProcessWithSumming()\r\n{\r\n\tCI_ASSERT( getContext() );\r\n\r\n\tmProcessInPlace = false;\r\n\tsize_t framesPerBlock = getFramesPerBlock();\r\n\r\n\tmInternalBuffer.setSize( framesPerBlock, mNumChannels );\r\n\tmSummingBuffer.setSize( framesPerBlock, mNumChannels );\r\n}\r\n\r\nbool Node::checkCycle( const NodeRef &sourceNode, const NodeRef &destNode ) const\r\n{\r\n\tif( sourceNode == destNode )\r\n\t\treturn true;\r\n\r\n\tif( sourceNode->supportsCycles() || destNode->supportsCycles() )\r\n\t\treturn false;\r\n\r\n\tfor( const auto &input : sourceNode->getInputs() ) {\r\n\t\tif( checkCycle( input, destNode ) )\r\n\t\t\treturn true;\r\n\t}\r\n\r\n\treturn false;\r\n}\r\n\r\nvoid Node::notifyConnectionsDidChange()\r\n{\r\n\tgetContext()->connectionsDidChange( shared_from_this() );\r\n}\r\n\r\nbool Node::canConnectToInput( const NodeRef &input )\r\n{\r\n\tif( ! input || input == shared_from_this() )\r\n\t\treturn false;\r\n\r\n\tfor( const auto& in : mInputs )\r\n\t\tif( input == in )\r\n\t\t\treturn false;\r\n\r\n\treturn true;\r\n}\r\n\r\nstd::string Node::getName()\r\n{\r\n\treturn ! mName.empty() ? mName : System::demangleTypeName( typeid( *this ).name() );\r\n}\r\n\r\n\/\/ ----------------------------------------------------------------------------------------------------\r\n\/\/ MARK: - NodeAutoPullable\r\n\/\/ ----------------------------------------------------------------------------------------------------\r\n\r\nNodeAutoPullable::NodeAutoPullable( const Format &format )\r\n\t: Node( format ), mIsPulledByContext( false )\r\n{\r\n}\r\n\r\nNodeAutoPullable::~NodeAutoPullable()\r\n{\r\n}\r\n\r\nvoid NodeAutoPullable::connect( const NodeRef &output )\r\n{\r\n\tNode::connect( output );\r\n\tupdatePullMethod();\r\n}\r\n\r\nvoid NodeAutoPullable::connectInput( const NodeRef &input )\r\n{\r\n\tNode::connectInput( input );\r\n\tupdatePullMethod();\r\n}\r\n\r\nvoid NodeAutoPullable::disconnectInput( const NodeRef &input )\r\n{\r\n\tNode::disconnectInput( input );\r\n\tupdatePullMethod();\r\n}\r\n\r\nvoid NodeAutoPullable::disconnectAllOutputs()\r\n{\r\n\tNode::disconnectAllOutputs();\r\n\r\n\tif( mIsPulledByContext ) {\r\n\t\tmIsPulledByContext = false;\r\n\t\tgetContext()->removeAutoPulledNode( shared_from_this() );\r\n\t}\r\n}\r\n\r\nvoid NodeAutoPullable::updatePullMethod()\r\n{\r\n\tbool hasOutputs = ! getOutputs().empty();\r\n\tif( ! hasOutputs && ! mIsPulledByContext ) {\r\n\t\tmIsPulledByContext = true;\r\n\t\tgetContext()->addAutoPulledNode( shared_from_this() );\r\n\t}\r\n\telse if( hasOutputs && mIsPulledByContext ) {\r\n\t\tmIsPulledByContext = false;\r\n\t\tgetContext()->removeAutoPulledNode( shared_from_this() );\r\n\t}\r\n}\r\n\r\n\/\/ ----------------------------------------------------------------------------------------------------\r\n\/\/ MARK: - ScopedEnableNode\r\n\/\/ ----------------------------------------------------------------------------------------------------\r\n\r\nScopedEnableNode::ScopedEnableNode( const NodeRef &node )\r\n\t: mNode( node )\r\n{\r\n\tmWasEnabled = ( mNode ? mNode->isEnabled() : false );\r\n}\r\n\r\nScopedEnableNode::ScopedEnableNode( const NodeRef &node, bool enable )\r\n\t: mNode( node )\r\n{\r\n\tif( mNode ) {\r\n\t\tmWasEnabled = mNode->isEnabled();\r\n\t\tmNode->setEnabled( enable );\r\n\t}\r\n\telse\r\n\t\tmWasEnabled = false;\r\n}\r\n\r\nScopedEnableNode::~ScopedEnableNode()\r\n{\r\n\tif( mNode )\r\n\t\tmNode->setEnabled( mWasEnabled );\r\n}\r\n\r\n\/\/ ----------------------------------------------------------------------------------------------------\r\n\/\/ MARK: - Exceptions\r\n\/\/ ----------------------------------------------------------------------------------------------------\r\n\r\nNodeCycleExc::NodeCycleExc( const NodeRef &sourceNode, const NodeRef &destNode )\r\n\t: AudioExc( string( \"cyclical connection between source: \" ) + sourceNode->getName() + string( \" and dest: \" ) + destNode->getName() )\r\n{\r\n}\r\n\r\n} } \/\/ namespace cinder::audio\r\n<commit_msg>reverting back to only disable() from uninit if isAutoEnabled() == true. This allows for context-wide re-initializing and the current state of the graph to be completely restored (otherwise, non-auto-enabled Node’s will be unknowingly disabled())<commit_after>\/*\r\n Copyright (c) 2014, The Cinder Project\r\n\r\n This code is intended to be used with the Cinder C++ library, http:\/\/libcinder.org\r\n\r\n Redistribution and use in source and binary forms, with or without modification, are permitted provided that\r\n the following conditions are met:\r\n\r\n * Redistributions of source code must retain the above copyright notice, this list of conditions and\r\n the following disclaimer.\r\n * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and\r\n the following disclaimer in the documentation and\/or other materials provided with the distribution.\r\n\r\n THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED\r\n WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A\r\n PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR\r\n ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED\r\n TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\r\n HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\r\n NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\r\n POSSIBILITY OF SUCH DAMAGE.\r\n *\/\r\n\r\n\r\n#include \"cinder\/audio\/Node.h\"\r\n#include \"cinder\/audio\/DelayNode.h\"\r\n#include \"cinder\/audio\/Context.h\"\r\n#include \"cinder\/audio\/dsp\/Dsp.h\"\r\n#include \"cinder\/audio\/dsp\/Converter.h\"\r\n#include \"cinder\/audio\/Debug.h\"\r\n#include \"cinder\/CinderAssert.h\"\r\n#include \"cinder\/System.h\"\r\n\r\n#include <limits>\r\n\r\nusing namespace std;\r\n\r\nnamespace cinder { namespace audio {\r\n\r\n\/\/ ----------------------------------------------------------------------------------------------------\r\n\/\/ MARK: - Node\r\n\/\/ ----------------------------------------------------------------------------------------------------\r\n\r\nNode::Node( const Format &format )\r\n\t: mInitialized( false ), mEnabled( false ),\tmChannelMode( format.getChannelMode() ),\r\n\t\tmNumChannels( 1 ), mAutoEnabled( true ), mProcessInPlace( true ), mLastProcessedFrame( numeric_limits<uint64_t>::max() )\r\n{\r\n\tif( format.getChannels() ) {\r\n\t\tmNumChannels = format.getChannels();\r\n\t\tmChannelMode = ChannelMode::SPECIFIED;\r\n\t}\r\n\r\n\tif( ! boost::indeterminate( format.getAutoEnable() ) )\r\n\t\tsetAutoEnabled( format.getAutoEnable() );\r\n}\r\n\r\nNode::~Node()\r\n{\r\n}\r\n\r\nvoid Node::connect( const NodeRef &output )\r\n{\r\n\t\/\/ make a reference to ourselves so that we aren't deallocated in the case of the last owner\r\n\t\/\/ disconnecting us, which we may need later anyway\r\n\tNodeRef thisRef = shared_from_this();\r\n\r\n\tif( ! output->canConnectToInput( thisRef ) )\r\n\t\treturn;\r\n\r\n\tif( checkCycle( thisRef, output ) )\r\n\t\tthrow NodeCycleExc( thisRef, output );\r\n\r\n\tmOutputs.push_back( output ); \/\/ set output first, so that it is visible in configureConnections()\r\n\toutput->connectInput( thisRef );\r\n\r\n\toutput->notifyConnectionsDidChange();\r\n}\r\n\r\nvoid Node::disconnect( const NodeRef &output )\r\n{\r\n\tif( ! output )\r\n\t\treturn;\r\n\r\n\tfor( auto weakOutIt = mOutputs.begin(); weakOutIt != mOutputs.end(); ++weakOutIt ) {\r\n\t\tif( weakOutIt->lock() == output ) {\r\n\t\t\tmOutputs.erase( weakOutIt );\r\n\t\t\tbreak;\r\n\t\t}\r\n\t}\r\n\r\n\toutput->disconnectInput( shared_from_this() );\r\n\toutput->notifyConnectionsDidChange();\r\n}\r\n\r\nvoid Node::disconnectAll()\r\n{\r\n\tdisconnectAllInputs();\r\n\tdisconnectAllOutputs();\r\n}\r\n\r\nvoid Node::disconnectAllOutputs()\r\n{\r\n\tNodeRef thisRef = shared_from_this();\r\n\r\n\tauto outputs = getOutputs(); \/\/ first make a copy of only the still-alive NodeRef's\r\n\tfor( const auto &output : outputs )\r\n\t\tdisconnect( output );\r\n}\r\n\r\nvoid Node::disconnectAllInputs()\r\n{\r\n\tNodeRef thisRef = shared_from_this();\r\n\r\n\tfor( auto &input : mInputs )\r\n\t\tinput->disconnectOutput( thisRef );\r\n\r\n\tmInputs.clear();\r\n\tnotifyConnectionsDidChange();\r\n}\r\n\r\nvoid Node::connectInput( const NodeRef &input )\r\n{\r\n\tlock_guard<mutex> lock( getContext()->getMutex() );\r\n\r\n\tmInputs.insert( input );\r\n\tconfigureConnections();\r\n}\r\n\r\nvoid Node::disconnectInput( const NodeRef &input )\r\n{\r\n\tlock_guard<mutex> lock( getContext()->getMutex() );\r\n\r\n\tfor( auto inIt = mInputs.begin(); inIt != mInputs.end(); ++inIt ) {\r\n\t\tif( *inIt == input ) {\r\n\t\t\tmInputs.erase( inIt );\r\n\t\t\tbreak;\r\n\t\t}\r\n\t}\r\n}\r\n\r\nvoid Node::disconnectOutput( const NodeRef &output )\r\n{\r\n\tlock_guard<mutex> lock( getContext()->getMutex() );\r\n\r\n\tfor( auto outIt = mOutputs.begin(); outIt != mOutputs.end(); ++outIt ) {\r\n\t\tif( outIt->lock() == output ) {\r\n\t\t\tmOutputs.erase( outIt );\r\n\t\t\tbreak;\r\n\t\t}\r\n\t}\r\n}\r\n\r\nvector<NodeRef> Node::getOutputs() const\r\n{\r\n\tvector<NodeRef> result;\r\n\tfor( const weak_ptr<Node> &outputWeak : mOutputs ) {\r\n\t\tNodeRef output = outputWeak.lock();\r\n\t\tif( output )\r\n\t\t\tresult.push_back( output );\r\n\t}\r\n\r\n\treturn result;\r\n}\r\n\r\nvoid Node::enable()\r\n{\r\n\tif( ! mInitialized )\r\n\t\tinitializeImpl();\r\n\r\n\tif( mEnabled )\r\n\t\treturn;\r\n\r\n\tmEnabled = true;\r\n\tenableProcessing();\r\n}\r\n\r\nvoid Node::disable()\r\n{\r\n\tif( ! mEnabled )\r\n\t\treturn;\r\n\r\n\tmEnabled = false;\r\n\tdisableProcessing();\r\n}\r\n\r\nvoid Node::setEnabled( bool b )\r\n{\r\n\tif( b )\r\n\t\tenable();\r\n\telse\r\n\t\tdisable();\r\n}\r\n\r\nsize_t Node::getNumConnectedInputs() const\r\n{\r\n\treturn mInputs.size();\r\n}\r\n\r\nsize_t Node::getNumConnectedOutputs() const\r\n{\r\n\treturn mOutputs.size();\r\n}\r\n\r\nvoid Node::initializeImpl()\r\n{\r\n\tif( mInitialized )\r\n\t\treturn;\r\n\r\n\tif( mProcessInPlace && ! supportsProcessInPlace() )\r\n\t\tsetupProcessWithSumming();\r\n\r\n\tinitialize();\r\n\tmInitialized = true;\r\n\r\n\tif( mAutoEnabled )\r\n\t\tenable();\r\n}\r\n\r\n\r\nvoid Node::uninitializeImpl()\r\n{\r\n\tif( ! mInitialized )\r\n\t\treturn;\r\n\r\n\tif( mAutoEnabled )\r\n\t\tdisable();\r\n\r\n\tuninitialize();\r\n\tmInitialized = false;\r\n}\r\n\r\nvoid Node::setNumChannels( size_t numChannels )\r\n{\r\n\tif( mNumChannels == numChannels )\r\n\t\treturn;\r\n\r\n\tuninitializeImpl();\r\n\tmNumChannels = numChannels;\r\n}\r\n\r\nvoid Node::setChannelMode( ChannelMode mode )\r\n{\r\n\tCI_ASSERT_MSG( ! mInitialized, \"setting the channel mode must be done before initializing\" );\r\n\r\n\tif( mChannelMode == mode )\r\n\t\treturn;\r\n\r\n\tmChannelMode = mode;\r\n}\r\n\r\nsize_t Node::getMaxNumInputChannels() const\r\n{\r\n\tsize_t result = 0;\r\n\tfor( auto &in : mInputs )\r\n\t\tresult = max( result, in->getNumChannels() );\r\n\r\n\treturn result;\r\n}\r\n\r\nsize_t Node::getSampleRate() const\r\n{\r\n\treturn getContext()->getSampleRate();\r\n}\r\n\r\nsize_t Node::getFramesPerBlock() const\r\n{\r\n\treturn getContext()->getFramesPerBlock();\r\n}\r\n\r\n\/\/ TODO: Checking for DelayNode below is a kludge and will not work for other types that want to support feedback.\r\n\/\/\t\t With more investigation it might be possible to avoid this, or at least define some interface that\r\n\/\/ specifies whether this input needs to be summed.\r\nvoid Node::configureConnections()\r\n{\r\n\tCI_ASSERT( getContext() );\r\n\r\n\tmProcessInPlace = supportsProcessInPlace();\r\n\r\n\tif( getNumConnectedInputs() > 1 || getNumConnectedOutputs() > 1 )\r\n\t\tmProcessInPlace = false;\r\n\r\n\tbool isDelay = ( dynamic_cast<DelayNode *>( this ) != nullptr ); \/\/ see note above\r\n\r\n\tfor( auto &input : mInputs ) {\r\n\t\tbool inputProcessInPlace = true;\r\n\r\n\t\tsize_t inputNumChannels = input->getNumChannels();\r\n\t\tif( ! supportsInputNumChannels( inputNumChannels ) ) {\r\n\t\t\tif( mChannelMode == ChannelMode::MATCHES_INPUT )\r\n\t\t\t\tsetNumChannels( getMaxNumInputChannels() );\r\n\t\t\telse if( input->getChannelMode() == ChannelMode::MATCHES_OUTPUT ) {\r\n\t\t\t\tinput->setNumChannels( mNumChannels );\r\n\t\t\t\tinput->configureConnections();\r\n\t\t\t}\r\n\t\t\telse {\r\n\t\t\t\tmProcessInPlace = false;\r\n\t\t\t\tinputProcessInPlace = false;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t\/\/ inputs with more than one output cannot process in-place, so make them sum\r\n\t\tif( input->getProcessInPlace() && input->getNumConnectedOutputs() > 1 )\r\n\t\t\tinputProcessInPlace = false;\r\n\r\n\t\t\/\/ if we're unable to process in-place and we're a DelayNode, its possible that the input may be part of a feedback loop, in which case input must sum.\r\n\t\tif( ! mProcessInPlace && isDelay )\r\n\t\t\tinputProcessInPlace = false;\r\n\r\n\t\tif( ! inputProcessInPlace )\r\n\t\t\tinput->setupProcessWithSumming();\r\n\r\n\t\tinput->initializeImpl();\r\n\t}\r\n\r\n\tfor( auto &out : mOutputs ) {\r\n\t\tNodeRef output = out.lock();\r\n\t\tif( ! output )\r\n\t\t\tcontinue;\r\n\t\tif( ! output->supportsInputNumChannels( mNumChannels ) ) {\r\n\t\t\tif( output->getChannelMode() == ChannelMode::MATCHES_INPUT ) {\r\n\t\t\t\toutput->setNumChannels( mNumChannels );\r\n\t\t\t\toutput->configureConnections();\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t\tmProcessInPlace = false;\r\n\t\t}\r\n\t}\r\n\r\n\tif( ! mProcessInPlace )\r\n\t\tsetupProcessWithSumming();\r\n\r\n\tinitializeImpl();\r\n}\r\n\r\nvoid Node::pullInputs( Buffer *inPlaceBuffer )\r\n{\r\n\tCI_ASSERT( getContext() );\r\n\r\n\tif( mProcessInPlace ) {\r\n\t\tif( mInputs.empty() ) {\r\n\t\t\t\/\/ Fastest route: no inputs and process in-place. If disabled, get rid of any previously processsed samples.\r\n\t\t\tif( mEnabled )\r\n\t\t\t\tprocess( inPlaceBuffer );\r\n\t\t\telse\r\n\t\t\t\tinPlaceBuffer->zero();\r\n\t\t}\r\n\t\telse {\r\n\t\t\t\/\/ First pull the input (can only be one when in-place), then run process() if input did any processing.\r\n\t\t\tconst NodeRef &input = *mInputs.begin();\r\n\t\t\tinput->pullInputs( inPlaceBuffer );\r\n\r\n\t\t\tif( ! input->getProcessInPlace() )\r\n\t\t\t\tdsp::mixBuffers( input->getInternalBuffer(), inPlaceBuffer );\r\n\r\n\t\t\tif( mEnabled )\r\n\t\t\t\tprocess( inPlaceBuffer );\r\n\t\t}\r\n\t}\r\n\telse {\r\n\t\t\/\/ Pull and sum all enabled inputs. Only do this once per processing block, which is checked by the current number of processed frames.\r\n\t\tuint64_t numProcessedFrames = getContext()->getNumProcessedFrames();\r\n\t\tif( mLastProcessedFrame != numProcessedFrames ) {\r\n\t\t\tmLastProcessedFrame = numProcessedFrames;\r\n\r\n\t\t\tmSummingBuffer.zero();\r\n\t\t\tsumInputs();\r\n\t\t}\r\n\t}\r\n}\r\n\r\nvoid Node::sumInputs()\r\n{\r\n\t\/\/ Pull all inputs, summing the results from the buffer that input used for processing.\r\n\t\/\/ mInternalBuffer is not zero'ed before pulling inputs to allow for feedback.\r\n\tfor( auto &input : mInputs ) {\r\n\t\tinput->pullInputs( &mInternalBuffer );\r\n\t\tconst Buffer *processedBuffer = input->getProcessInPlace() ? &mInternalBuffer : input->getInternalBuffer();\r\n\t\tdsp::sumBuffers( processedBuffer, &mSummingBuffer );\r\n\t}\r\n\r\n\t\/\/ Process the summed results if enabled.\r\n\tif( mEnabled )\r\n\t\tprocess( &mSummingBuffer );\r\n\r\n\t\/\/ copy summed buffer back to internal so downstream can get it.\r\n\tdsp::mixBuffers( &mSummingBuffer, &mInternalBuffer );\r\n}\r\n\r\nvoid Node::setupProcessWithSumming()\r\n{\r\n\tCI_ASSERT( getContext() );\r\n\r\n\tmProcessInPlace = false;\r\n\tsize_t framesPerBlock = getFramesPerBlock();\r\n\r\n\tmInternalBuffer.setSize( framesPerBlock, mNumChannels );\r\n\tmSummingBuffer.setSize( framesPerBlock, mNumChannels );\r\n}\r\n\r\nbool Node::checkCycle( const NodeRef &sourceNode, const NodeRef &destNode ) const\r\n{\r\n\tif( sourceNode == destNode )\r\n\t\treturn true;\r\n\r\n\tif( sourceNode->supportsCycles() || destNode->supportsCycles() )\r\n\t\treturn false;\r\n\r\n\tfor( const auto &input : sourceNode->getInputs() ) {\r\n\t\tif( checkCycle( input, destNode ) )\r\n\t\t\treturn true;\r\n\t}\r\n\r\n\treturn false;\r\n}\r\n\r\nvoid Node::notifyConnectionsDidChange()\r\n{\r\n\tgetContext()->connectionsDidChange( shared_from_this() );\r\n}\r\n\r\nbool Node::canConnectToInput( const NodeRef &input )\r\n{\r\n\tif( ! input || input == shared_from_this() )\r\n\t\treturn false;\r\n\r\n\tfor( const auto& in : mInputs )\r\n\t\tif( input == in )\r\n\t\t\treturn false;\r\n\r\n\treturn true;\r\n}\r\n\r\nstd::string Node::getName()\r\n{\r\n\treturn ! mName.empty() ? mName : System::demangleTypeName( typeid( *this ).name() );\r\n}\r\n\r\n\/\/ ----------------------------------------------------------------------------------------------------\r\n\/\/ MARK: - NodeAutoPullable\r\n\/\/ ----------------------------------------------------------------------------------------------------\r\n\r\nNodeAutoPullable::NodeAutoPullable( const Format &format )\r\n\t: Node( format ), mIsPulledByContext( false )\r\n{\r\n}\r\n\r\nNodeAutoPullable::~NodeAutoPullable()\r\n{\r\n}\r\n\r\nvoid NodeAutoPullable::connect( const NodeRef &output )\r\n{\r\n\tNode::connect( output );\r\n\tupdatePullMethod();\r\n}\r\n\r\nvoid NodeAutoPullable::connectInput( const NodeRef &input )\r\n{\r\n\tNode::connectInput( input );\r\n\tupdatePullMethod();\r\n}\r\n\r\nvoid NodeAutoPullable::disconnectInput( const NodeRef &input )\r\n{\r\n\tNode::disconnectInput( input );\r\n\tupdatePullMethod();\r\n}\r\n\r\nvoid NodeAutoPullable::disconnectAllOutputs()\r\n{\r\n\tNode::disconnectAllOutputs();\r\n\r\n\tif( mIsPulledByContext ) {\r\n\t\tmIsPulledByContext = false;\r\n\t\tgetContext()->removeAutoPulledNode( shared_from_this() );\r\n\t}\r\n}\r\n\r\nvoid NodeAutoPullable::updatePullMethod()\r\n{\r\n\tbool hasOutputs = ! getOutputs().empty();\r\n\tif( ! hasOutputs && ! mIsPulledByContext ) {\r\n\t\tmIsPulledByContext = true;\r\n\t\tgetContext()->addAutoPulledNode( shared_from_this() );\r\n\t}\r\n\telse if( hasOutputs && mIsPulledByContext ) {\r\n\t\tmIsPulledByContext = false;\r\n\t\tgetContext()->removeAutoPulledNode( shared_from_this() );\r\n\t}\r\n}\r\n\r\n\/\/ ----------------------------------------------------------------------------------------------------\r\n\/\/ MARK: - ScopedEnableNode\r\n\/\/ ----------------------------------------------------------------------------------------------------\r\n\r\nScopedEnableNode::ScopedEnableNode( const NodeRef &node )\r\n\t: mNode( node )\r\n{\r\n\tmWasEnabled = ( mNode ? mNode->isEnabled() : false );\r\n}\r\n\r\nScopedEnableNode::ScopedEnableNode( const NodeRef &node, bool enable )\r\n\t: mNode( node )\r\n{\r\n\tif( mNode ) {\r\n\t\tmWasEnabled = mNode->isEnabled();\r\n\t\tmNode->setEnabled( enable );\r\n\t}\r\n\telse\r\n\t\tmWasEnabled = false;\r\n}\r\n\r\nScopedEnableNode::~ScopedEnableNode()\r\n{\r\n\tif( mNode )\r\n\t\tmNode->setEnabled( mWasEnabled );\r\n}\r\n\r\n\/\/ ----------------------------------------------------------------------------------------------------\r\n\/\/ MARK: - Exceptions\r\n\/\/ ----------------------------------------------------------------------------------------------------\r\n\r\nNodeCycleExc::NodeCycleExc( const NodeRef &sourceNode, const NodeRef &destNode )\r\n\t: AudioExc( string( \"cyclical connection between source: \" ) + sourceNode->getName() + string( \" and dest: \" ) + destNode->getName() )\r\n{\r\n}\r\n\r\n} } \/\/ namespace cinder::audio\r\n<|endoftext|>"} {"text":"<commit_before>\/\/ Run configuration class\n\/\/ Author: Matthew Raso-Barnett 18\/11\/2010\n#include <iostream>\n#include <cassert>\n#include <stdexcept>\n\n#include \"Constants.h\"\n#include \"Units.h\"\n\n#include \"RunConfig.h\"\n#include \"ConfigFile.h\"\n\nusing namespace std;\n\nClassImp(RunConfig);\n\n\/\/__________________________________________________________________________\nRunConfig::RunConfig()\n :TObject(), fRunName(\"\"), fGeomFile(\"\"), fGeomVisFile(\"\"), fInputDataFile(\"\"),\n fOutputDataFile(\"\"), fFieldsFile(\"\"), fInputRunName(\"\"),\n fParticlesToLoad(\"\"), fLoadAllParticles(true), fRestartParticles(false),\n fGravFieldOn(true), fMagFieldOn(false), fWallLossesOn(true), fRunTime(0.),\n fMaxStepTime(0.), fSpinStepTime(0.), fObsSpin(false), fObsBounces(false),\n fObsTracks(false), fObsField(false), fTrackMeasInterval(0.), fSpinMeasInterval(0.),\n fFieldMeasInterval(0.)\n{\n #ifdef PRINT_CONSTRUCTORS\n cout << \"RunConfig::Default Constructor\" << endl;\n #endif\n}\n\n\/\/__________________________________________________________________________\nRunConfig::RunConfig(const ConfigFile& masterConfig, int runNumber)\n :TObject()\n{\n #ifdef PRINT_CONSTRUCTORS\n cout << \"RunConfig::Constructor\" << endl;\n #endif\n \/\/ Extract full path to config files \n const string compressedfolderpath = masterConfig.GetString(\"Path\",\"Folder\");\n const string folderpath = masterConfig.ExpandFilePath(compressedfolderpath);\n \/\/ Use full folder path to fetch the run config file\n Char_t runID[6];\n sprintf(runID,\"Run%d\",runNumber);\n string runConfigFileName = folderpath + masterConfig.GetString(\"Config\", runID);\n if (runConfigFileName.empty() == kTRUE) {\n cout << \"Unable to read in Run Configuration file name\" << endl;\n throw runtime_error(\"Error fetching name of Run Config file\");\n }\n\n ConfigFile runConfigFile(runConfigFileName);\n fRunName = runConfigFile.GetString(\"RunName\",\"Name\");\n \n fGeomFile = folderpath + runConfigFile.GetString(\"GeomFile\",\"Files\");\n string geomVisFileName = runConfigFile.GetString(\"GeomVisFile\",\"Files\");\n if (geomVisFileName.empty() == false) {fGeomVisFile = folderpath + geomVisFileName;}\n \n fInputDataFile = folderpath + runConfigFile.GetString(\"InputDataFile\",\"Files\");\n fOutputDataFile = folderpath + runConfigFile.GetString(\"OutputDataFile\",\"Files\");\n \n fInputRunName = runConfigFile.GetString(\"InputRunName\",\"Particles\");\n fParticlesToLoad = runConfigFile.GetString(\"WhichParticles\",\"Particles\");\n fLoadAllParticles = runConfigFile.GetBool(\"AllParticles\",\"Particles\");\n fRestartParticles = runConfigFile.GetBool(\"RunFromBeginning\",\"Particles\");\n \n fGravFieldOn = runConfigFile.GetBool(\"GravField\",\"Properties\");\n fWallLossesOn = runConfigFile.GetBool(\"WallLosses\",\"Properties\");\n \n fRunTime = runConfigFile.GetFloat(\"RunTime(s)\",\"Properties\");\n fMaxStepTime = runConfigFile.GetFloat(\"MaxStepTime(s)\",\"Properties\");\n \n fObsBounces = runConfigFile.GetBool(\"RecordBounces\",\"Observables\");\n fObsTracks = runConfigFile.GetBool(\"RecordTracks\",\"Observables\");\n double trackMeasFreq = runConfigFile.GetFloat(\"TrackMeasureFrequency(Hz)\",\"Observables\");\n fTrackMeasInterval = (trackMeasFreq == 0.0 ? 0.0 : (1.0\/trackMeasFreq)); \n \n fFieldsFile = folderpath + runConfigFile.GetString(\"FieldsFile\",\"Files\");\n fMagFieldOn = runConfigFile.GetBool(\"MagFields\",\"Properties\");\n fSpinStepTime = runConfigFile.GetFloat(\"SpinStepTime(s)\",\"Properties\");\n \n fObsSpin = runConfigFile.GetBool(\"RecordSpin\",\"Observables\");\n double spinMeasFreq = runConfigFile.GetFloat(\"SpinMeasureFrequency(Hz)\",\"Observables\");\n fSpinMeasInterval = (spinMeasFreq == 0.0 ? 0.0 : (1.0\/spinMeasFreq)); \n \n fObsField = runConfigFile.GetBool(\"RecordField\",\"Observables\");\n double fieldMeasFreq = runConfigFile.GetFloat(\"FieldMeasureFrequency(Hz)\",\"Observables\");\n fFieldMeasInterval = (fieldMeasFreq == 0.0 ? 0.0 : (1.0\/fieldMeasFreq)); \n \n \/\/ Check for inconsistencies in RunConfig File\n if (fFieldsFile.empty() && fMagFieldOn == true) {\n throw runtime_error(\"Incompatible options in RunConfig: Check FieldsFile and MagFieldOn\");\n } else if (fMagFieldOn == true && fSpinStepTime == 0.0) {\n throw runtime_error(\"Incompatible options in RunConfig: Check MagFieldOn and SpinStepTime\");\n } else if (fObsSpin == true && fSpinMeasInterval == 0.0) {\n throw runtime_error(\"Incompatible options in RunConfig: Check RecordSpin and SpinMeasFreq\");\n } else if (fObsField == true && fFieldMeasInterval == 0.0) {\n throw runtime_error(\"Incompatible options in RunConfig: Check RecordField and FieldMeasFreq\");\n } else if (fMagFieldOn == false) {\n fSpinStepTime = 0.0;\n fObsSpin = false;\n fObsField = false;\n fSpinMeasInterval = 0.0;\n fFieldMeasInterval = 0.0;\n }\n this->Print();\n}\n\n\/\/__________________________________________________________________________\nRunConfig::RunConfig(const RunConfig& other)\n :TObject(other),\n fRunName(other.fRunName),\n fGeomFile(other.fGeomFile),\n fGeomVisFile(other.fGeomVisFile),\n fInputDataFile(other.fInputDataFile),\n fOutputDataFile(other.fOutputDataFile),\n fFieldsFile(other.fFieldsFile),\n fInputRunName(other.fInputRunName),\n fParticlesToLoad(other.fParticlesToLoad),\n fLoadAllParticles(other.fLoadAllParticles),\n fRestartParticles(other.fRestartParticles),\n fGravFieldOn(other.fGravFieldOn),\n fMagFieldOn(other.fMagFieldOn),\n fWallLossesOn(other.fWallLossesOn),\n fRunTime(other.fRunTime),\n fMaxStepTime(other.fMaxStepTime),\n fSpinStepTime(other.fSpinStepTime),\n fObsSpin(other.fObsSpin),\n fObsBounces(other.fObsBounces),\n fObsTracks(other.fObsTracks),\n fObsField(other.fObsField),\n fTrackMeasInterval(other.fTrackMeasInterval),\n fSpinMeasInterval(other.fSpinMeasInterval),\n fFieldMeasInterval(other.fFieldMeasInterval)\n{\n #ifdef PRINT_CONSTRUCTORS\n cout << \"RunConfig::Copy Constructor\" << endl;\n #endif\n}\n\n\/\/__________________________________________________________________________\nRunConfig::~RunConfig()\n{\n #ifdef PRINT_CONSTRUCTORS\n cout << \"RunConfig::Destructor\" << endl;\n #endif\n}\n\n\/\/__________________________________________________________________________\nvoid RunConfig::Print(Option_t* \/*option*\/) const\n{\n cout << \"-------------------------------------------\" << endl;\n cout << \"Run Configuration Settings\" << endl;\n cout << \"Name: \" << fRunName << endl;\n cout << \"GeomFile: \" << fGeomFile << endl;\n cout << \"GeomVisFile: \" << fGeomVisFile << endl;\n cout << \"InputDataFile: \" << fInputDataFile << endl;\n cout << \"OutputDataFile: \" << fOutputDataFile << endl;\n cout << \"FieldsFile: \" << fFieldsFile << endl;\n cout << \"InputRunName: \" << fInputRunName << endl;\n cout << \"InitialParticleBranch: \" << fParticlesToLoad << endl;\n cout << \"LoadAllParticles: \" << fLoadAllParticles << endl;\n cout << \"RestartParticles: \" << fRestartParticles << endl;\n cout << \"GravFieldOn: \" << fGravFieldOn << endl;\n cout << \"MagFieldOn: \" << fMagFieldOn << endl;\n cout << \"WallLossesOn: \" << fWallLossesOn << endl;\n cout << \"RunTime: \" << fRunTime << \" s\"<< endl;\n cout << \"MaxStepTime: \" << fMaxStepTime << \" s\"<< endl;\n cout << \"SpinStepTime: \" << fSpinStepTime << \" s\"<< endl;\n cout << \"Observe Spin: \" << fObsSpin << endl;\n cout << \"Observe Bounces: \" << fObsBounces << endl;\n cout << \"Observe Tracks: \" << fObsTracks << endl;\n cout << \"Observe Field: \" << fObsField << endl;\n cout << \"Track Measurement Interval: \" << fTrackMeasInterval << endl;\n cout << \"Spin Measurement Interval: \" << fSpinMeasInterval << endl;\n cout << \"Field Measurement Interval: \" << fFieldMeasInterval << endl;\n cout << \"-------------------------------------------\" << endl;\n}\n<commit_msg>Improve error checking in RunConfig constructor<commit_after>\/\/ Run configuration class\n\/\/ Author: Matthew Raso-Barnett 18\/11\/2010\n#include <iostream>\n#include <cassert>\n#include <stdexcept>\n\n#include \"Algorithms.h\"\n#include \"Constants.h\"\n#include \"Units.h\"\n\n#include \"RunConfig.h\"\n#include \"ConfigFile.h\"\n\nusing namespace std;\n\nClassImp(RunConfig);\n\n\/\/__________________________________________________________________________\nRunConfig::RunConfig()\n :TObject(), fRunName(\"\"), fGeomFile(\"\"), fGeomVisFile(\"\"), fInputDataFile(\"\"),\n fOutputDataFile(\"\"), fFieldsFile(\"\"), fInputRunName(\"\"),\n fParticlesToLoad(\"\"), fLoadAllParticles(true), fRestartParticles(false),\n fGravFieldOn(true), fMagFieldOn(false), fWallLossesOn(true), fRunTime(0.),\n fMaxStepTime(0.), fSpinStepTime(0.), fObsSpin(false), fObsBounces(false),\n fObsTracks(false), fObsField(false), fTrackMeasInterval(0.), fSpinMeasInterval(0.),\n fFieldMeasInterval(0.)\n{\n #ifdef PRINT_CONSTRUCTORS\n cout << \"RunConfig::Default Constructor\" << endl;\n #endif\n}\n\n\/\/__________________________________________________________________________\nRunConfig::RunConfig(const ConfigFile& masterConfig, int runNumber)\n :TObject(), fRunName(\"\"), fGeomFile(\"\"), fGeomVisFile(\"\"), fInputDataFile(\"\"),\n fOutputDataFile(\"\"), fFieldsFile(\"\"), fInputRunName(\"\"),\n fParticlesToLoad(\"\"), fLoadAllParticles(true), fRestartParticles(false),\n fGravFieldOn(true), fMagFieldOn(false), fWallLossesOn(true), fRunTime(0.),\n fMaxStepTime(0.), fSpinStepTime(0.), fObsSpin(false), fObsBounces(false),\n fObsTracks(false), fObsField(false), fTrackMeasInterval(0.), fSpinMeasInterval(0.),\n fFieldMeasInterval(0.)\n{\n #ifdef PRINT_CONSTRUCTORS\n cout << \"RunConfig::Constructor\" << endl;\n #endif\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ -- Extract full path to directory containing configuration files \n const string compressedfolderpath = masterConfig.GetString(\"Path\",\"Folder\");\n const string folderpath = masterConfig.ExpandFilePath(compressedfolderpath);\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ -- Use full folder path to find and build the run-config file\n Char_t runID[6];\n sprintf(runID,\"Run%d\",runNumber);\n string runConfigFileName = folderpath + masterConfig.GetString(\"Config\", runID);\n if (runConfigFileName.empty() == kTRUE) {\n cout << \"Error: Run Configuration file name specified is either empty of invalid\" << endl;\n throw runtime_error(\"Error fetching name of Run Config file\");\n }\n ConfigFile runConfigFile(runConfigFileName);\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ -- Search the Run Config file for parameters\n \/\/ -----------------------------------\n \/\/ Name of Run object\n fInputRunName = runConfigFile.GetString(\"InputRunName\",\"Particles\");\n \/\/ -----------------------------------\n \/\/ -- Files to Load\n \/\/ Name of Run\n fRunName = runConfigFile.GetString(\"RunName\",\"Name\");\n \/\/ Name of Input Geometry\n string geomFileName = runConfigFile.GetString(\"GeomFile\",\"Files\");\n if (geomFileName.empty() == true) {\n throw runtime_error(\"No GeomFile specified in runconfig\");\n }\n fGeomFile = folderpath + geomFileName;\n \/\/ Name of Visualisation Geometry\n string geomVisFileName = runConfigFile.GetString(\"GeomVisFile\",\"Files\");\n if (geomVisFileName.empty() == true) {\n throw runtime_error(\"No GeomVisFile specified in runconfig\");\n }\n fGeomVisFile = folderpath + geomVisFileName;\n \/\/ Name of Input particle data file \n string inputDataFileName = runConfigFile.GetString(\"InputDataFile\",\"Files\");\n if (inputDataFileName.empty() == true) {\n throw runtime_error(\"No InputDataFile specified in runconfig\");\n }\n fInputDataFile = folderpath + inputDataFileName;\n \/\/ Name of Output data file\n string outputDataFileName = runConfigFile.GetString(\"OutputDataFile\",\"Files\");\n if (outputDataFileName.empty() == true) {\n throw runtime_error(\"No OutputDataFile specified in runconfig\");\n }\n fOutputDataFile = folderpath + outputDataFileName;\n \/\/ Name of Fields input file -- Not required to be set\n string fieldsFileName = runConfigFile.GetString(\"FieldsFile\",\"Files\");\n if (fieldsFileName.empty() == false) {fFieldsFile = folderpath + fieldsFileName;}\n else {fFieldsFile = \"\";}\n \/\/ -----------------------------------\n \/\/ -- Input Particles options\n \/\/ Name of state folder to load particles from\n fParticlesToLoad = runConfigFile.GetString(\"WhichParticles\",\"Particles\");\n if (Algorithms::DataFile::ValidateStateNames(fParticlesToLoad) == false) {\n throw runtime_error(\"Invalid InputParticleState specified in runconfig\");\n }\n \/\/ Option for whether to load all particles in input folder \n fLoadAllParticles = runConfigFile.GetBool(\"AllParticles\",\"Particles\");\n \/\/ Option for whether to restart particles from their initial states (obviously this is\n \/\/ only relevant if ParticlesToLoad is not already the initial states) \n fRestartParticles = runConfigFile.GetBool(\"RunFromBeginning\",\"Particles\");\n \/\/ -----------------------------------\n \/\/ -- Run Options\n \/\/ Option for whether gravity is turned on\n fGravFieldOn = runConfigFile.GetBool(\"GravField\",\"Properties\");\n \/\/ Option for whether wall losses are turned on\n fWallLossesOn = runConfigFile.GetBool(\"WallLosses\",\"Properties\");\n \/\/ Option for whether magnetic field is turned on\n fMagFieldOn = runConfigFile.GetBool(\"MagFields\",\"Properties\");\n \/\/ Parameter to be set; Specifies time to simulate neutrons to \n fRunTime = runConfigFile.GetFloat(\"RunTime(s)\",\"Properties\");\n if (fRunTime <= 0.) {throw runtime_error(\"Invalid RunTime specified in runconfig\");}\n \/\/ Parameter to be set; Maximum geometrical step allowed in simulation \n fMaxStepTime = runConfigFile.GetFloat(\"MaxStepTime(s)\",\"Properties\");\n if (fMaxStepTime <= 0.) {fMaxStepTime = 1.0*Units::s;}\n \/\/ Parameter to be set; Maximum spin step allowed in simulation \n fSpinStepTime = runConfigFile.GetFloat(\"SpinStepTime(s)\",\"Properties\");\n if (fSpinStepTime <= 0.) {throw runtime_error(\"Invalid SpinStepTime specified in runconfig\");}\n \/\/ -----------------------------------\n \/\/ -- Observer Options\n \/\/ Option for whether to record numbers of Bounces\n fObsBounces = runConfigFile.GetBool(\"RecordBounces\",\"Observables\");\n \/\/ Option for whether to record particle tracks\n fObsTracks = runConfigFile.GetBool(\"RecordTracks\",\"Observables\");\n \/\/ Parameter to be set; Specify frequency of track measurements (if desired - \n \/\/ by default it will measure all track points)\n double trackMeasFreq = runConfigFile.GetFloat(\"TrackMeasureFrequency(Hz)\",\"Observables\");\n fTrackMeasInterval = (trackMeasFreq == 0.0 ? 0.0 : (1.0\/trackMeasFreq)); \n \/\/ Option for whether to record spin states\n fObsSpin = runConfigFile.GetBool(\"RecordSpin\",\"Observables\");\n \/\/ Parameter to be set; Specify frequency of spin measurements\n double spinMeasFreq = runConfigFile.GetFloat(\"SpinMeasureFrequency(Hz)\",\"Observables\");\n fSpinMeasInterval = (spinMeasFreq == 0.0 ? 0.0 : (1.0\/spinMeasFreq));\n \/\/ Option for whether to record field seen by particles\n fObsField = runConfigFile.GetBool(\"RecordField\",\"Observables\");\n \/\/ Parameter to be set; Specify frequency of field measurements\n double fieldMeasFreq = runConfigFile.GetFloat(\"FieldMeasureFrequency(Hz)\",\"Observables\");\n fFieldMeasInterval = (fieldMeasFreq == 0.0 ? 0.0 : (1.0\/fieldMeasFreq)); \n \/\/ -----------------------------------\n \/\/ -----------------------------------\n \/\/ Check for inconsistencies in RunConfig File\n if (fFieldsFile.empty() && fMagFieldOn == true) {\n throw runtime_error(\"Incompatible options in RunConfig: Check FieldsFile and MagFieldOn\");\n } else if (fMagFieldOn == true && fSpinStepTime == 0.0) {\n throw runtime_error(\"Incompatible options in RunConfig: Check MagFieldOn and SpinStepTime\");\n } else if (fObsSpin == true && fSpinMeasInterval == 0.0) {\n throw runtime_error(\"Incompatible options in RunConfig: Check RecordSpin and SpinMeasFreq\");\n } else if (fObsField == true && fFieldMeasInterval == 0.0) {\n throw runtime_error(\"Incompatible options in RunConfig: Check RecordField and FieldMeasFreq\");\n } else if (fMagFieldOn == false) {\n fSpinStepTime = 0.0;\n fObsSpin = false;\n fObsField = false;\n fSpinMeasInterval = 0.0;\n fFieldMeasInterval = 0.0;\n }\n this->Print();\n}\n\n\/\/__________________________________________________________________________\nRunConfig::RunConfig(const RunConfig& other)\n :TObject(other),\n fRunName(other.fRunName),\n fGeomFile(other.fGeomFile),\n fGeomVisFile(other.fGeomVisFile),\n fInputDataFile(other.fInputDataFile),\n fOutputDataFile(other.fOutputDataFile),\n fFieldsFile(other.fFieldsFile),\n fInputRunName(other.fInputRunName),\n fParticlesToLoad(other.fParticlesToLoad),\n fLoadAllParticles(other.fLoadAllParticles),\n fRestartParticles(other.fRestartParticles),\n fGravFieldOn(other.fGravFieldOn),\n fMagFieldOn(other.fMagFieldOn),\n fWallLossesOn(other.fWallLossesOn),\n fRunTime(other.fRunTime),\n fMaxStepTime(other.fMaxStepTime),\n fSpinStepTime(other.fSpinStepTime),\n fObsSpin(other.fObsSpin),\n fObsBounces(other.fObsBounces),\n fObsTracks(other.fObsTracks),\n fObsField(other.fObsField),\n fTrackMeasInterval(other.fTrackMeasInterval),\n fSpinMeasInterval(other.fSpinMeasInterval),\n fFieldMeasInterval(other.fFieldMeasInterval)\n{\n #ifdef PRINT_CONSTRUCTORS\n cout << \"RunConfig::Copy Constructor\" << endl;\n #endif\n}\n\n\/\/__________________________________________________________________________\nRunConfig::~RunConfig()\n{\n #ifdef PRINT_CONSTRUCTORS\n cout << \"RunConfig::Destructor\" << endl;\n #endif\n}\n\n\/\/__________________________________________________________________________\nvoid RunConfig::Print(Option_t* \/*option*\/) const\n{\n cout << \"-------------------------------------------\" << endl;\n cout << \"Run Configuration Settings\" << endl;\n cout << \"Name: \" << fRunName << endl;\n cout << \"GeomFile: \" << fGeomFile << endl;\n cout << \"GeomVisFile: \" << fGeomVisFile << endl;\n cout << \"InputDataFile: \" << fInputDataFile << endl;\n cout << \"OutputDataFile: \" << fOutputDataFile << endl;\n cout << \"FieldsFile: \" << fFieldsFile << endl;\n cout << \"InputRunName: \" << fInputRunName << endl;\n cout << \"InitialParticleBranch: \" << fParticlesToLoad << endl;\n cout << \"LoadAllParticles: \" << fLoadAllParticles << endl;\n cout << \"RestartParticles: \" << fRestartParticles << endl;\n cout << \"GravFieldOn: \" << fGravFieldOn << endl;\n cout << \"MagFieldOn: \" << fMagFieldOn << endl;\n cout << \"WallLossesOn: \" << fWallLossesOn << endl;\n cout << \"RunTime: \" << fRunTime << \" s\"<< endl;\n cout << \"MaxStepTime: \" << fMaxStepTime << \" s\"<< endl;\n cout << \"SpinStepTime: \" << fSpinStepTime << \" s\"<< endl;\n cout << \"Observe Spin: \" << fObsSpin << endl;\n cout << \"Observe Bounces: \" << fObsBounces << endl;\n cout << \"Observe Tracks: \" << fObsTracks << endl;\n cout << \"Observe Field: \" << fObsField << endl;\n cout << \"Track Measurement Interval: \" << fTrackMeasInterval << endl;\n cout << \"Spin Measurement Interval: \" << fSpinMeasInterval << endl;\n cout << \"Field Measurement Interval: \" << fFieldMeasInterval << endl;\n cout << \"-------------------------------------------\" << endl;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"appcontroller.hpp\"\n#include \"window.hpp\"\n#include \"resourcemanager.hpp\"\n#include <lib\/draw\/scenemanager.hpp>\n#include <lib\/draw\/rendermanager.hpp>\n#include \"utilprovider.hpp\"\n#include \"log.hpp\"\n#include \"exceptionmanager.hpp\"\n#include \"filesystem.hpp\"\n#include \"configuration.hpp\"\n#include \"servicesmanager.hpp\"\n#include \"shareddata.hpp\"\n#include \"input.hpp\"\n\nnamespace lib\n{\n\tnamespace core\n\t{\n\t\tAppController::AppController(uptr<IApp> iapp, sptr<Driver> driverInstance)\n\t\t\t: m_iapp{ std::move(iapp) }, m_driver{ driverInstance }, m_servicesManager{ new ServicesManager{ this } }\n\t\t{\n\t\t\tLOG_CONSTRUCT_NOPARAMS;\n\t\t\tm_iapp->setAppContext(this);\n\t\t\tLOG_DEBUG(\"Starting app \" << appId() << \"...\");\n\t\t\tm_state = AppState::ReadyToStart;\n\t\t}\n\n\t\tAppController::~AppController()\n\t\t{\n\t\t\tLOG_DESTRUCT(\"Name: \" + appId());\n\t\t}\n\n\t\tbool AppController::update()\n\t\t{\n\t\t\tswitch (m_state)\n\t\t\t{\n\t\t\tcase AppState::NotInitialized:\n\t\t\t\tbreak;\n\t\t\tcase AppState::ReadyToStart:\n\t\t\t{\n\t\t\t\t\/\/ Create the scene manager\n\t\t\t\tLOG_DEBUG_(appId() + \": Starting initialization...\");\n\t\t\t\tm_state = AppState::Executing;\n\n\t\t\t\t\/\/TO DO: Ask via requests\n\t\t\t\tm_servicesManager->addService(sptr<ExceptionManager>{new ExceptionManager{}});\n\t\t\t\tm_servicesManager->addService(sptr<FileSystem>{ new FileSystem{} });\n\t\t\t\tm_servicesManager->addService(sptr<Configuration>{ new Configuration{} });\n\t\t\t\tm_servicesManager->addService(sptr<Configuration>{ new Configuration{} });\n\t\t\t\tm_servicesManager->addService(sptr<SharedData>{ new SharedData{} });\n\t\t\t\tm_servicesManager->addService(sptr<UtilProvider>{new UtilProvider{}});\n\t\t\t\tm_servicesManager->addService(sptr<ResourceManager>{ new ResourceManager{} });\n\t\t\t\tm_servicesManager->addService(sptr<draw::SceneManager>{ new draw::SceneManager{} });\n\t\t\t\tm_servicesManager->addService(sptr<draw::RenderManager>{ new draw::RenderManager{} });\n\t\t\t\tm_servicesManager->addService(sptr<Window>{ new Window{ m_iapp->getAppDescriptor().wcp }});\n\t\t\t\tm_servicesManager->addService(sptr<Input>{new Input{}});\n\n\t\t\t\tm_servicesManager->setupAllServices();\n\t\t\t\tm_servicesManager->initializeServices();\n\n\t\t\t\tm_servicesManager->service<draw::SceneManager>()->addScenes(m_iapp->scenesVector());\n\n\t\t\t\tm_iapp->onInit();\n\t\t\t\tLOG_DEBUG(appId() << \": \" << \" is now executing\");\n\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase AppState::Executing:\n\t\t\t{\n\t\t\t\tif (loopStep())\n\t\t\t\t{\n\t\t\t\t\tm_state = AppState::ReadyToTerminate;\n\t\t\t\t\tLOG_DEBUG(appId() << \": \" << \" is now ready to terminate\");\n\t\t\t\t}\n\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase AppController::AppState::ReadyToTerminate:\n\t\t\t\tLOG_DEBUG(appId() << \": \" << \" started termination\");\n\t\t\t\tm_state = AppState::Terminated;\n\/\/\t\t\t\tm_iapp->onFinish();\n\n\t\t\t\tm_servicesManager->stopServices();\n\t\t\t\tLOG_DEBUG_(appId() + \": terminated\");\n\t\t\t\treturn true;\n\t\t\t\tbreak;\n\t\t\tcase AppState::Terminated:\n\t\t\t\treturn true;\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\treturn false;\n\t\t}\n\n\t\tbool AppController::loopStep()\n\t\t{\n\t\t\tbool windowWants2Close = m_servicesManager->service<Window>()->preLoop();\n\t\t\tm_servicesManager->service<draw::SceneManager>()->update();\n\t\t\twindowWants2Close |= m_servicesManager->service<Window>()->postLoop();\n\t\t\treturn windowWants2Close;\n\t\t}\n\n\t\tconst std::string AppController::appId() const\n\t\t{\n\t\t\tif (m_iapp)\n\t\t\t{\n\t\t\t\treturn std::string(m_iapp->getAppDescriptor().Name + \":\" + std::to_string(m_iapp->getAppDescriptor().Version) +\n\t\t\t\t\t\".\" + std::to_string(m_iapp->getAppDescriptor().SubVersion) + \".\"+std::to_string(m_iapp->getAppDescriptor().Patch));\n\t\t\t}\n\t\t\treturn \"NoApp:0.0.0\";\n\t\t}\n\n\t\tAppController * toController(PIAppContext context)\n\t\t{\n\t\t\treturn dynamic_cast<AppController*>(context);\n\t\t}\n\t}\n}\n<commit_msg>Removed duplicated service<commit_after>#include \"appcontroller.hpp\"\n#include \"window.hpp\"\n#include \"resourcemanager.hpp\"\n#include <lib\/draw\/scenemanager.hpp>\n#include <lib\/draw\/rendermanager.hpp>\n#include \"utilprovider.hpp\"\n#include \"log.hpp\"\n#include \"exceptionmanager.hpp\"\n#include \"filesystem.hpp\"\n#include \"configuration.hpp\"\n#include \"servicesmanager.hpp\"\n#include \"shareddata.hpp\"\n#include \"input.hpp\"\n\nnamespace lib\n{\n\tnamespace core\n\t{\n\t\tAppController::AppController(uptr<IApp> iapp, sptr<Driver> driverInstance)\n\t\t\t: m_iapp{ std::move(iapp) }, m_driver{ driverInstance }, m_servicesManager{ new ServicesManager{ this } }\n\t\t{\n\t\t\tLOG_CONSTRUCT_NOPARAMS;\n\t\t\tm_iapp->setAppContext(this);\n\t\t\tLOG_DEBUG(\"Starting app \" << appId() << \"...\");\n\t\t\tm_state = AppState::ReadyToStart;\n\t\t}\n\n\t\tAppController::~AppController()\n\t\t{\n\t\t\tLOG_DESTRUCT(\"Name: \" + appId());\n\t\t}\n\n\t\tbool AppController::update()\n\t\t{\n\t\t\tswitch (m_state)\n\t\t\t{\n\t\t\tcase AppState::NotInitialized:\n\t\t\t\tbreak;\n\t\t\tcase AppState::ReadyToStart:\n\t\t\t{\n\t\t\t\t\/\/ Create the scene manager\n\t\t\t\tLOG_DEBUG_(appId() + \": Starting initialization...\");\n\t\t\t\tm_state = AppState::Executing;\n\n\t\t\t\t\/\/TO DO: Ask via requests\n\t\t\t\tm_servicesManager->addService(sptr<ExceptionManager>{new ExceptionManager{}});\n\t\t\t\tm_servicesManager->addService(sptr<FileSystem>{ new FileSystem{} });\n\t\t\t\tm_servicesManager->addService(sptr<Configuration>{ new Configuration{} });\n\t\t\t\tm_servicesManager->addService(sptr<SharedData>{ new SharedData{} });\n\t\t\t\tm_servicesManager->addService(sptr<UtilProvider>{new UtilProvider{}});\n\t\t\t\tm_servicesManager->addService(sptr<ResourceManager>{ new ResourceManager{} });\n\t\t\t\tm_servicesManager->addService(sptr<draw::SceneManager>{ new draw::SceneManager{} });\n\t\t\t\tm_servicesManager->addService(sptr<draw::RenderManager>{ new draw::RenderManager{} });\n\t\t\t\tm_servicesManager->addService(sptr<Window>{ new Window{ m_iapp->getAppDescriptor().wcp }});\n\t\t\t\tm_servicesManager->addService(sptr<Input>{new Input{}});\n\n\t\t\t\tm_servicesManager->setupAllServices();\n\t\t\t\tm_servicesManager->initializeServices();\n\n\t\t\t\tm_servicesManager->service<draw::SceneManager>()->addScenes(m_iapp->scenesVector());\n\n\t\t\t\tm_iapp->onInit();\n\t\t\t\tLOG_DEBUG(appId() << \": \" << \" is now executing\");\n\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase AppState::Executing:\n\t\t\t{\n\t\t\t\tif (loopStep())\n\t\t\t\t{\n\t\t\t\t\tm_state = AppState::ReadyToTerminate;\n\t\t\t\t\tLOG_DEBUG(appId() << \": \" << \" is now ready to terminate\");\n\t\t\t\t}\n\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase AppController::AppState::ReadyToTerminate:\n\t\t\t\tLOG_DEBUG(appId() << \": \" << \" started termination\");\n\t\t\t\tm_state = AppState::Terminated;\n\/\/\t\t\t\tm_iapp->onFinish();\n\n\t\t\t\tm_servicesManager->stopServices();\n\t\t\t\tLOG_DEBUG_(appId() + \": terminated\");\n\t\t\t\treturn true;\n\t\t\t\tbreak;\n\t\t\tcase AppState::Terminated:\n\t\t\t\treturn true;\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\treturn false;\n\t\t}\n\n\t\tbool AppController::loopStep()\n\t\t{\n\t\t\tbool windowWants2Close = m_servicesManager->service<Window>()->preLoop();\n\t\t\tm_servicesManager->service<draw::SceneManager>()->update();\n\t\t\twindowWants2Close |= m_servicesManager->service<Window>()->postLoop();\n\t\t\treturn windowWants2Close;\n\t\t}\n\n\t\tconst std::string AppController::appId() const\n\t\t{\n\t\t\tif (m_iapp)\n\t\t\t{\n\t\t\t\treturn std::string(m_iapp->getAppDescriptor().Name + \":\" + std::to_string(m_iapp->getAppDescriptor().Version) +\n\t\t\t\t\t\".\" + std::to_string(m_iapp->getAppDescriptor().SubVersion) + \".\"+std::to_string(m_iapp->getAppDescriptor().Patch));\n\t\t\t}\n\t\t\treturn \"NoApp:0.0.0\";\n\t\t}\n\n\t\tAppController * toController(PIAppContext context)\n\t\t{\n\t\t\treturn dynamic_cast<AppController*>(context);\n\t\t}\n\t}\n}\n<|endoftext|>"} {"text":"<commit_before>\/* $Id: OSBlockSolverFactory.cpp 3038 2009-11-07 11:43:44Z Gassmann $ *\/\n\/** @file OSBlockSolverFactory.cpp\n * \n *\n * @author Gus Gassmann, Jun Ma, Kipp Martin, \n * @version 1.0, 21\/July\/2008\n * @since OS1.1\n *\n * \\remarks\n * Copyright (C) 2005-2008, Gus Gassmann, Jun Ma, Kipp Martin,\n * Dalhousie University, Northwestern University, and the University of Chicago.\n * All Rights Reserved.\n * This software is licensed under the Common Public License. \n * Please see the accompanying LICENSE file in root directory for terms.\n * \n *\/\n\n\n\/\/ --------------------------------------------------------------------- \/\/\n#include \"OSInstance.h\"\n#include \"OSResult.h\"\n#include \"OSDataStructures.h\"\n#include \"OSErrorClass.h\"\n#include <vector>\n#include <string>\n#include <map>\n\n#include \"OSDipBlockSolverFactory.h\"\n\n\n\nstd::map<std::string, OSDipBlockSolverFactory*> OSDipBlockSolverFactory::factories;\n\nOSDipBlockSolver* OSDipBlockSolverFactory::createOSDipBlockSolver(const string &solverName) throw(ErrorClass){\n\t\n\t\n\tif( factories.find(solverName) != factories.end() ){\n\t\t\n\t\treturn factories[ solverName]->create();\n\t\t\n\t}else{\n\t\tthrow ErrorClass( solverName + \" is not a valid OSDipBlockSolver\");\n\t}\n\t\n}\/\/end \n\n\n\/**\n *\n * Default Constructor. \n *\/\t\nOSDipBlockSolverFactory::OSDipBlockSolverFactory(){\n\t\n}\n \n OSDipBlockSolverFactory::~OSDipBlockSolverFactory(){\n }\n <commit_msg>add another newline in OSDipBlockSolverFactory.cpp for Matt<commit_after>\/* $Id: OSBlockSolverFactory.cpp 3038 2009-11-07 11:43:44Z Gassmann $ *\/\n\/** @file OSBlockSolverFactory.cpp\n * \n *\n * @author Gus Gassmann, Jun Ma, Kipp Martin, \n * @version 1.0, 21\/July\/2008\n * @since OS1.1\n *\n * \\remarks\n * Copyright (C) 2005-2008, Gus Gassmann, Jun Ma, Kipp Martin,\n * Dalhousie University, Northwestern University, and the University of Chicago.\n * All Rights Reserved.\n * This software is licensed under the Common Public License. \n * Please see the accompanying LICENSE file in root directory for terms.\n * \n *\/\n\n\n\/\/ --------------------------------------------------------------------- \/\/\n#include \"OSInstance.h\"\n#include \"OSResult.h\"\n#include \"OSDataStructures.h\"\n#include \"OSErrorClass.h\"\n#include <vector>\n#include <string>\n#include <map>\n\n#include \"OSDipBlockSolverFactory.h\"\n\n\n\nstd::map<std::string, OSDipBlockSolverFactory*> OSDipBlockSolverFactory::factories;\n\nOSDipBlockSolver* OSDipBlockSolverFactory::createOSDipBlockSolver(const string &solverName) throw(ErrorClass){\n\t\n\t\n\tif( factories.find(solverName) != factories.end() ){\n\t\t\n\t\treturn factories[ solverName]->create();\n\t\t\n\t}else{\n\t\tthrow ErrorClass( solverName + \" is not a valid OSDipBlockSolver\");\n\t}\n\t\n}\/\/end \n\n\n\/**\n *\n * Default Constructor. \n *\/\t\nOSDipBlockSolverFactory::OSDipBlockSolverFactory(){\n\t\n}\n \n OSDipBlockSolverFactory::~OSDipBlockSolverFactory(){\n }\n \n \n<|endoftext|>"} {"text":"<commit_before>\/\/ ======================================================================== \/\/\n\/\/ Copyright 2009-2016 Intel Corporation \/\/\n\/\/ \/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\"); \/\/\n\/\/ you may not use this file except in compliance with the License. \/\/\n\/\/ You may obtain a copy of the License at \/\/\n\/\/ \/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0 \/\/\n\/\/ \/\/\n\/\/ Unless required by applicable law or agreed to in writing, software \/\/\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS, \/\/\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. \/\/\n\/\/ See the License for the specific language governing permissions and \/\/\n\/\/ limitations under the License. \/\/\n\/\/ ======================================================================== \/\/\n\n#include \"TaskSys.h\"\n\/\/ospray\n#include \"common\/sysinfo.h\"\n#include \"common\/thread.h\"\n\/\/stl\n#include <thread>\n#include <vector>\n\nnamespace ospray {\n struct TaskSys {\n bool initialized;\n bool running;\n\n void init(size_t maxNumRenderTasks);\n static TaskSys global;\n static void *threadStub(void *);\n inline Ref<Task> getNextActiveTask();\n\n \/\/! Queue of tasks that have ALREADY been acitvated, and that are ready\n \/\/! to run\n __aligned(64) Task *volatile activeListFirst;\n __aligned(64) Task *volatile activeListLast;\n\n Mutex __aligned(64) mutex;\n Condition __aligned(64) tasksAvailable;\n\n void threadFunction();\n\n std::vector<thread_t> threads;\n\n TaskSys()\n : activeListFirst(nullptr), activeListLast(nullptr),\n initialized(false), running(false)\n {}\n\n ~TaskSys();\n };\n \n TaskSys __aligned(64) TaskSys::global;\n\n inline void Task::workOnIt() \n {\n size_t myCompleted = 0;\n while (1) {\n const size_t thisJobID = numJobsStarted++;\n if (thisJobID >= numJobsInTask) \n break;\n \n run(thisJobID);\n ++myCompleted;\n }\n\n if (myCompleted != 0) {\n const size_t nowCompleted = (numJobsCompleted += myCompleted);\n if (nowCompleted == numJobsInTask) {\n SCOPED_LOCK(mutex);\n status = Task::COMPLETED;\n allJobsCompletedCond.notify_all();\n }\n }\n }\n \n void Task::wait(bool workOnIt)\n {\n if (status == Task::COMPLETED) {\n return;\n }\n\n if (workOnIt) {\n this->workOnIt();\n }\n\n std::unique_lock<std::mutex> lock(mutex);\n allJobsCompletedCond.wait(lock, [&](){return status == Task::COMPLETED;});\n }\n\n void Task::scheduleAndWait(size_t numJobs, ScheduleOrder order)\n {\n schedule(numJobs,order);\n wait();\n }\n\n inline Ref<Task> TaskSys::getNextActiveTask()\n {\n while (1) {\n std::unique_lock<std::mutex> lock(mutex);\n tasksAvailable.wait(lock, [&](){\n return !(activeListFirst == nullptr && running);\n });\n\n if (!running) {\n return nullptr;\n }\n\n Ref<Task> front = activeListFirst;\n if (front->numJobsStarted >= front->numJobsInTask) {\n if (activeListFirst == activeListLast) {\n activeListFirst = activeListLast = nullptr;\n } else {\n activeListFirst = activeListFirst->next;\n }\n continue;\n }\n assert(front.ptr());\n return front;\n }\n }\n \n void Task::initTaskSystem(const size_t maxNumRenderTasks)\n {\n TaskSys::global.init(maxNumRenderTasks);\n }\n\n void Task::schedule(size_t numJobs, ScheduleOrder order)\n {\n refInc();\n this->order = order;\n numJobsInTask = numJobs;\n status = Task::SCHEDULED;\n if (numMissingDependencies == 0)\n activate();\n }\n\n inline void Task::activate()\n {\n if (!TaskSys::global.initialized)\n throw std::runtime_error(\"TASK SYSTEM NOT YET INITIALIZED\");\n {\n SCOPED_LOCK(TaskSys::global.mutex);\n bool wasEmpty = TaskSys::global.activeListFirst == nullptr;\n if (wasEmpty) {\n TaskSys::global.activeListFirst = TaskSys::global.activeListLast = this;\n this->next = nullptr;\n TaskSys::global.tasksAvailable.notify_all();\n } else {\n if (order == Task::BACK_OF_QUEUE) {\n this->next = nullptr;\n TaskSys::global.activeListLast->next = this;\n TaskSys::global.activeListLast = this;\n } else {\n this->next = TaskSys::global.activeListFirst;\n TaskSys::global.activeListFirst = this;\n }\n }\n status = Task::ACTIVE;\n }\n }\n\n void TaskSys::threadFunction()\n {\n while (1) {\n Ref<Task> task = getNextActiveTask();\n if (!running) {\n return;\n }\n assert(task);\n task->workOnIt();\n }\n }\n\n TaskSys::~TaskSys()\n {\n running = false;\n tasksAvailable.notify_all();\n for (int i = 0; i < threads.size(); ++i) {\n join(threads[i]);\n }\n }\n\n void *TaskSys::threadStub(void *)\n {\n TaskSys::global.threadFunction();\n return nullptr;\n }\n\n void TaskSys::init(size_t numThreads)\n {\n if (initialized)\n throw std::runtime_error(\"#osp: task system initialized twice!\");\n initialized = true;\n running = true;\n\n if (numThreads != 0) {\n#if defined(__MIC__)\n numThreads = std::min(numThreads,\n (size_t)std::thread::hardware_concurrency()-4);\n#else\n numThreads = std::min(numThreads,\n (size_t)std::thread::hardware_concurrency());\n#endif\n }\n\n \/* generate all threads *\/\n for (size_t t=1; t<numThreads; t++) {\n threads.push_back(createThread((thread_func)TaskSys::threadStub,\n (void*)-1,4*1024*1024,-1));\n }\n\n#if ~defined(__MIC__)\n setAffinity(0);\n#endif\n }\n}\/\/namespace ospray\n<commit_msg>fix debug compile error<commit_after>\/\/ ======================================================================== \/\/\n\/\/ Copyright 2009-2016 Intel Corporation \/\/\n\/\/ \/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\"); \/\/\n\/\/ you may not use this file except in compliance with the License. \/\/\n\/\/ You may obtain a copy of the License at \/\/\n\/\/ \/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0 \/\/\n\/\/ \/\/\n\/\/ Unless required by applicable law or agreed to in writing, software \/\/\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS, \/\/\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. \/\/\n\/\/ See the License for the specific language governing permissions and \/\/\n\/\/ limitations under the License. \/\/\n\/\/ ======================================================================== \/\/\n\n#include \"TaskSys.h\"\n\/\/ospray\n#include \"common\/sysinfo.h\"\n#include \"common\/thread.h\"\n\/\/stl\n#include <thread>\n#include <vector>\n\nnamespace ospray {\n struct TaskSys {\n bool initialized;\n bool running;\n\n void init(size_t maxNumRenderTasks);\n static TaskSys global;\n static void *threadStub(void *);\n inline Ref<Task> getNextActiveTask();\n\n \/\/! Queue of tasks that have ALREADY been acitvated, and that are ready\n \/\/! to run\n __aligned(64) Task *volatile activeListFirst;\n __aligned(64) Task *volatile activeListLast;\n\n Mutex __aligned(64) mutex;\n Condition __aligned(64) tasksAvailable;\n\n void threadFunction();\n\n std::vector<thread_t> threads;\n\n TaskSys()\n : activeListFirst(nullptr), activeListLast(nullptr),\n initialized(false), running(false)\n {}\n\n ~TaskSys();\n };\n \n TaskSys __aligned(64) TaskSys::global;\n\n inline void Task::workOnIt() \n {\n size_t myCompleted = 0;\n while (1) {\n const size_t thisJobID = numJobsStarted++;\n if (thisJobID >= numJobsInTask) \n break;\n \n run(thisJobID);\n ++myCompleted;\n }\n\n if (myCompleted != 0) {\n const size_t nowCompleted = (numJobsCompleted += myCompleted);\n if (nowCompleted == numJobsInTask) {\n SCOPED_LOCK(mutex);\n status = Task::COMPLETED;\n allJobsCompletedCond.notify_all();\n }\n }\n }\n \n void Task::wait(bool workOnIt)\n {\n if (status == Task::COMPLETED) {\n return;\n }\n\n if (workOnIt) {\n this->workOnIt();\n }\n\n std::unique_lock<std::mutex> lock(mutex);\n allJobsCompletedCond.wait(lock, [&](){return status == Task::COMPLETED;});\n }\n\n void Task::scheduleAndWait(size_t numJobs, ScheduleOrder order)\n {\n schedule(numJobs,order);\n wait();\n }\n\n inline Ref<Task> TaskSys::getNextActiveTask()\n {\n while (1) {\n std::unique_lock<std::mutex> lock(mutex);\n tasksAvailable.wait(lock, [&](){\n return !(activeListFirst == nullptr && running);\n });\n\n if (!running) {\n return nullptr;\n }\n\n Ref<Task> front = activeListFirst;\n if (front->numJobsStarted >= front->numJobsInTask) {\n if (activeListFirst == activeListLast) {\n activeListFirst = activeListLast = nullptr;\n } else {\n activeListFirst = activeListFirst->next;\n }\n continue;\n }\n assert(front.ptr);\n return front;\n }\n }\n \n void Task::initTaskSystem(const size_t maxNumRenderTasks)\n {\n TaskSys::global.init(maxNumRenderTasks);\n }\n\n void Task::schedule(size_t numJobs, ScheduleOrder order)\n {\n refInc();\n this->order = order;\n numJobsInTask = numJobs;\n status = Task::SCHEDULED;\n if (numMissingDependencies == 0)\n activate();\n }\n\n inline void Task::activate()\n {\n if (!TaskSys::global.initialized)\n throw std::runtime_error(\"TASK SYSTEM NOT YET INITIALIZED\");\n {\n SCOPED_LOCK(TaskSys::global.mutex);\n bool wasEmpty = TaskSys::global.activeListFirst == nullptr;\n if (wasEmpty) {\n TaskSys::global.activeListFirst = TaskSys::global.activeListLast = this;\n this->next = nullptr;\n TaskSys::global.tasksAvailable.notify_all();\n } else {\n if (order == Task::BACK_OF_QUEUE) {\n this->next = nullptr;\n TaskSys::global.activeListLast->next = this;\n TaskSys::global.activeListLast = this;\n } else {\n this->next = TaskSys::global.activeListFirst;\n TaskSys::global.activeListFirst = this;\n }\n }\n status = Task::ACTIVE;\n }\n }\n\n void TaskSys::threadFunction()\n {\n while (1) {\n Ref<Task> task = getNextActiveTask();\n if (!running) {\n return;\n }\n assert(task);\n task->workOnIt();\n }\n }\n\n TaskSys::~TaskSys()\n {\n running = false;\n tasksAvailable.notify_all();\n for (int i = 0; i < threads.size(); ++i) {\n join(threads[i]);\n }\n }\n\n void *TaskSys::threadStub(void *)\n {\n TaskSys::global.threadFunction();\n return nullptr;\n }\n\n void TaskSys::init(size_t numThreads)\n {\n if (initialized)\n throw std::runtime_error(\"#osp: task system initialized twice!\");\n initialized = true;\n running = true;\n\n if (numThreads != 0) {\n#if defined(__MIC__)\n numThreads = std::min(numThreads,\n (size_t)std::thread::hardware_concurrency()-4);\n#else\n numThreads = std::min(numThreads,\n (size_t)std::thread::hardware_concurrency());\n#endif\n }\n\n \/* generate all threads *\/\n for (size_t t=1; t<numThreads; t++) {\n threads.push_back(createThread((thread_func)TaskSys::threadStub,\n (void*)-1,4*1024*1024,-1));\n }\n\n#if ~defined(__MIC__)\n setAffinity(0);\n#endif\n }\n}\/\/namespace ospray\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright 2015 Google Inc.\n *\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n *\/\n\n#include \"SkCodecPriv.h\"\n#include \"SkWebpCodec.h\"\n#include \"SkTemplates.h\"\n\n\/\/ A WebP decoder on top of (subset of) libwebp\n\/\/ For more information on WebP image format, and libwebp library, see:\n\/\/ https:\/\/code.google.com\/speed\/webp\/\n\/\/ http:\/\/www.webmproject.org\/code\/#libwebp-webp-image-library\n\/\/ https:\/\/chromium.googlesource.com\/webm\/libwebp\n\n\/\/ If moving libwebp out of skia source tree, path for webp headers must be\n\/\/ updated accordingly. Here, we enforce using local copy in webp sub-directory.\n#include \"webp\/decode.h\"\n#include \"webp\/encode.h\"\n\nbool SkWebpCodec::IsWebp(const void* buf, size_t bytesRead) {\n \/\/ WEBP starts with the following:\n \/\/ RIFFXXXXWEBPVP\n \/\/ Where XXXX is unspecified.\n const char* bytes = static_cast<const char*>(buf);\n return bytesRead >= 14 && !memcmp(bytes, \"RIFF\", 4) && !memcmp(&bytes[8], \"WEBPVP\", 6);\n}\n\n\/\/ Parse headers of RIFF container, and check for valid Webp (VP8) content.\n\/\/ NOTE: This calls peek instead of read, since onGetPixels will need these\n\/\/ bytes again.\nstatic bool webp_parse_header(SkStream* stream, SkImageInfo* info) {\n unsigned char buffer[WEBP_VP8_HEADER_SIZE];\n SkASSERT(WEBP_VP8_HEADER_SIZE <= SkCodec::MinBufferedBytesNeeded());\n\n const size_t bytesPeeked = stream->peek(buffer, WEBP_VP8_HEADER_SIZE);\n if (bytesPeeked != WEBP_VP8_HEADER_SIZE) {\n \/\/ Use read + rewind as a backup\n if (stream->read(buffer, WEBP_VP8_HEADER_SIZE) != WEBP_VP8_HEADER_SIZE\n || !stream->rewind())\n return false;\n }\n\n WebPBitstreamFeatures features;\n VP8StatusCode status = WebPGetFeatures(buffer, WEBP_VP8_HEADER_SIZE, &features);\n if (VP8_STATUS_OK != status) {\n return false; \/\/ Invalid WebP file.\n }\n\n \/\/ sanity check for image size that's about to be decoded.\n {\n const int64_t size = sk_64_mul(features.width, features.height);\n if (!sk_64_isS32(size)) {\n return false;\n }\n \/\/ now check that if we are 4-bytes per pixel, we also don't overflow\n if (sk_64_asS32(size) > (0x7FFFFFFF >> 2)) {\n return false;\n }\n }\n\n if (info) {\n \/\/ FIXME: Is N32 the right type?\n \/\/ Is unpremul the right type? Clients of SkCodec may assume it's the\n \/\/ best type, when Skia currently cannot draw unpremul (and raster is faster\n \/\/ with premul).\n *info = SkImageInfo::Make(features.width, features.height, kN32_SkColorType,\n SkToBool(features.has_alpha) ? kUnpremul_SkAlphaType\n : kOpaque_SkAlphaType);\n }\n return true;\n}\n\nSkCodec* SkWebpCodec::NewFromStream(SkStream* stream) {\n SkAutoTDelete<SkStream> streamDeleter(stream);\n SkImageInfo info;\n if (webp_parse_header(stream, &info)) {\n return new SkWebpCodec(info, streamDeleter.release());\n }\n return nullptr;\n}\n\n\/\/ This version is slightly different from SkCodecPriv's version of conversion_possible. It\n\/\/ supports both byte orders for 8888.\nstatic bool webp_conversion_possible(const SkImageInfo& dst, const SkImageInfo& src) {\n if (dst.profileType() != src.profileType()) {\n return false;\n }\n\n if (!valid_alpha(dst.alphaType(), src.alphaType())) {\n return false;\n }\n\n switch (dst.colorType()) {\n \/\/ Both byte orders are supported.\n case kBGRA_8888_SkColorType:\n case kRGBA_8888_SkColorType:\n return true;\n case kRGB_565_SkColorType:\n return src.alphaType() == kOpaque_SkAlphaType;\n default:\n return false;\n }\n}\n\nSkISize SkWebpCodec::onGetScaledDimensions(float desiredScale) const {\n SkISize dim = this->getInfo().dimensions();\n \/\/ SkCodec treats zero dimensional images as errors, so the minimum size\n \/\/ that we will recommend is 1x1.\n dim.fWidth = SkTMax(1, SkScalarRoundToInt(desiredScale * dim.fWidth));\n dim.fHeight = SkTMax(1, SkScalarRoundToInt(desiredScale * dim.fHeight));\n return dim;\n}\n\nbool SkWebpCodec::onDimensionsSupported(const SkISize& dim) {\n const SkImageInfo& info = this->getInfo();\n return dim.width() >= 1 && dim.width() <= info.width()\n && dim.height() >= 1 && dim.height() <= info.height();\n}\n\n\nstatic WEBP_CSP_MODE webp_decode_mode(SkColorType ct, bool premultiply) {\n switch (ct) {\n case kBGRA_8888_SkColorType:\n return premultiply ? MODE_bgrA : MODE_BGRA;\n case kRGBA_8888_SkColorType:\n return premultiply ? MODE_rgbA : MODE_RGBA;\n case kRGB_565_SkColorType:\n return MODE_RGB_565;\n default:\n return MODE_LAST;\n }\n}\n\n\/\/ The WebP decoding API allows us to incrementally pass chunks of bytes as we receive them to the\n\/\/ decoder with WebPIAppend. In order to do so, we need to read chunks from the SkStream. This size\n\/\/ is arbitrary.\nstatic const size_t BUFFER_SIZE = 4096;\n\nbool SkWebpCodec::onGetValidSubset(SkIRect* desiredSubset) const {\n if (!desiredSubset) {\n return false;\n }\n\n SkIRect dimensions = SkIRect::MakeSize(this->getInfo().dimensions());\n if (!dimensions.contains(*desiredSubset)) {\n return false;\n }\n\n \/\/ As stated below, libwebp snaps to even left and top. Make sure top and left are even, so we\n \/\/ decode this exact subset.\n \/\/ Leave right and bottom unmodified, so we suggest a slightly larger subset than requested.\n desiredSubset->fLeft = (desiredSubset->fLeft >> 1) << 1;\n desiredSubset->fTop = (desiredSubset->fTop >> 1) << 1;\n return true;\n}\n\nSkCodec::Result SkWebpCodec::onGetPixels(const SkImageInfo& dstInfo, void* dst, size_t rowBytes,\n const Options& options, SkPMColor*, int*,\n int* rowsDecoded) {\n if (!webp_conversion_possible(dstInfo, this->getInfo())) {\n return kInvalidConversion;\n }\n\n WebPDecoderConfig config;\n if (0 == WebPInitDecoderConfig(&config)) {\n \/\/ ABI mismatch.\n \/\/ FIXME: New enum for this?\n return kInvalidInput;\n }\n\n \/\/ Free any memory associated with the buffer. Must be called last, so we declare it first.\n SkAutoTCallVProc<WebPDecBuffer, WebPFreeDecBuffer> autoFree(&(config.output));\n\n SkIRect bounds = SkIRect::MakeSize(this->getInfo().dimensions());\n if (options.fSubset) {\n \/\/ Caller is requesting a subset.\n if (!bounds.contains(*options.fSubset)) {\n \/\/ The subset is out of bounds.\n return kInvalidParameters;\n }\n\n bounds = *options.fSubset;\n\n \/\/ This is tricky. libwebp snaps the top and left to even values. We could let libwebp\n \/\/ do the snap, and return a subset which is a different one than requested. The problem\n \/\/ with that approach is that the caller may try to stitch subsets together, and if we\n \/\/ returned different subsets than requested, there would be artifacts at the boundaries.\n \/\/ Instead, we report that we cannot support odd values for top and left..\n if (!SkIsAlign2(bounds.fLeft) || !SkIsAlign2(bounds.fTop)) {\n return kInvalidParameters;\n }\n\n#ifdef SK_DEBUG\n {\n \/\/ Make a copy, since getValidSubset can change its input.\n SkIRect subset(bounds);\n \/\/ That said, getValidSubset should *not* change its input, in this case; otherwise\n \/\/ getValidSubset does not match the actual subsets we can do.\n SkASSERT(this->getValidSubset(&subset) && subset == bounds);\n }\n#endif\n\n config.options.use_cropping = 1;\n config.options.crop_left = bounds.fLeft;\n config.options.crop_top = bounds.fTop;\n config.options.crop_width = bounds.width();\n config.options.crop_height = bounds.height();\n }\n\n SkISize dstDimensions = dstInfo.dimensions();\n if (bounds.size() != dstDimensions) {\n \/\/ Caller is requesting scaling.\n config.options.use_scaling = 1;\n config.options.scaled_width = dstDimensions.width();\n config.options.scaled_height = dstDimensions.height();\n }\n\n config.output.colorspace = webp_decode_mode(dstInfo.colorType(),\n dstInfo.alphaType() == kPremul_SkAlphaType);\n config.output.u.RGBA.rgba = (uint8_t*) dst;\n config.output.u.RGBA.stride = (int) rowBytes;\n config.output.u.RGBA.size = dstInfo.getSafeSize(rowBytes);\n config.output.is_external_memory = 1;\n\n SkAutoTCallVProc<WebPIDecoder, WebPIDelete> idec(WebPIDecode(nullptr, 0, &config));\n if (!idec) {\n return kInvalidInput;\n }\n\n SkAutoTMalloc<uint8_t> storage(BUFFER_SIZE);\n uint8_t* buffer = storage.get();\n while (true) {\n const size_t bytesRead = stream()->read(buffer, BUFFER_SIZE);\n if (0 == bytesRead) {\n WebPIDecGetRGB(idec, rowsDecoded, NULL, NULL, NULL);\n return kIncompleteInput;\n }\n\n switch (WebPIAppend(idec, buffer, bytesRead)) {\n case VP8_STATUS_OK:\n return kSuccess;\n case VP8_STATUS_SUSPENDED:\n \/\/ Break out of the switch statement. Continue the loop.\n break;\n default:\n return kInvalidInput;\n }\n }\n}\n\nSkWebpCodec::SkWebpCodec(const SkImageInfo& info, SkStream* stream)\n : INHERITED(info, stream) {}\n<commit_msg>Mark webps as sRGB<commit_after>\/*\n * Copyright 2015 Google Inc.\n *\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n *\/\n\n#include \"SkCodecPriv.h\"\n#include \"SkWebpCodec.h\"\n#include \"SkTemplates.h\"\n\n\/\/ A WebP decoder on top of (subset of) libwebp\n\/\/ For more information on WebP image format, and libwebp library, see:\n\/\/ https:\/\/code.google.com\/speed\/webp\/\n\/\/ http:\/\/www.webmproject.org\/code\/#libwebp-webp-image-library\n\/\/ https:\/\/chromium.googlesource.com\/webm\/libwebp\n\n\/\/ If moving libwebp out of skia source tree, path for webp headers must be\n\/\/ updated accordingly. Here, we enforce using local copy in webp sub-directory.\n#include \"webp\/decode.h\"\n#include \"webp\/encode.h\"\n\nbool SkWebpCodec::IsWebp(const void* buf, size_t bytesRead) {\n \/\/ WEBP starts with the following:\n \/\/ RIFFXXXXWEBPVP\n \/\/ Where XXXX is unspecified.\n const char* bytes = static_cast<const char*>(buf);\n return bytesRead >= 14 && !memcmp(bytes, \"RIFF\", 4) && !memcmp(&bytes[8], \"WEBPVP\", 6);\n}\n\n\/\/ Parse headers of RIFF container, and check for valid Webp (VP8) content.\n\/\/ NOTE: This calls peek instead of read, since onGetPixels will need these\n\/\/ bytes again.\nstatic bool webp_parse_header(SkStream* stream, SkImageInfo* info) {\n unsigned char buffer[WEBP_VP8_HEADER_SIZE];\n SkASSERT(WEBP_VP8_HEADER_SIZE <= SkCodec::MinBufferedBytesNeeded());\n\n const size_t bytesPeeked = stream->peek(buffer, WEBP_VP8_HEADER_SIZE);\n if (bytesPeeked != WEBP_VP8_HEADER_SIZE) {\n \/\/ Use read + rewind as a backup\n if (stream->read(buffer, WEBP_VP8_HEADER_SIZE) != WEBP_VP8_HEADER_SIZE\n || !stream->rewind())\n return false;\n }\n\n WebPBitstreamFeatures features;\n VP8StatusCode status = WebPGetFeatures(buffer, WEBP_VP8_HEADER_SIZE, &features);\n if (VP8_STATUS_OK != status) {\n return false; \/\/ Invalid WebP file.\n }\n\n \/\/ sanity check for image size that's about to be decoded.\n {\n const int64_t size = sk_64_mul(features.width, features.height);\n if (!sk_64_isS32(size)) {\n return false;\n }\n \/\/ now check that if we are 4-bytes per pixel, we also don't overflow\n if (sk_64_asS32(size) > (0x7FFFFFFF >> 2)) {\n return false;\n }\n }\n\n if (info) {\n \/\/ FIXME: Is N32 the right type?\n \/\/ Is unpremul the right type? Clients of SkCodec may assume it's the\n \/\/ best type, when Skia currently cannot draw unpremul (and raster is faster\n \/\/ with premul).\n *info = SkImageInfo::Make(features.width, features.height, kN32_SkColorType,\n SkToBool(features.has_alpha) ? kUnpremul_SkAlphaType\n : kOpaque_SkAlphaType);\n }\n return true;\n}\n\nSkCodec* SkWebpCodec::NewFromStream(SkStream* stream) {\n SkAutoTDelete<SkStream> streamDeleter(stream);\n SkImageInfo info;\n if (webp_parse_header(stream, &info)) {\n return new SkWebpCodec(info, streamDeleter.release());\n }\n return nullptr;\n}\n\n\/\/ This version is slightly different from SkCodecPriv's version of conversion_possible. It\n\/\/ supports both byte orders for 8888.\nstatic bool webp_conversion_possible(const SkImageInfo& dst, const SkImageInfo& src) {\n \/\/ FIXME: skbug.com\/4895\n \/\/ Currently, we ignore the SkColorProfileType on the SkImageInfo. We\n \/\/ will treat the encoded data as linear regardless of what the client\n \/\/ requests.\n\n if (!valid_alpha(dst.alphaType(), src.alphaType())) {\n return false;\n }\n\n switch (dst.colorType()) {\n \/\/ Both byte orders are supported.\n case kBGRA_8888_SkColorType:\n case kRGBA_8888_SkColorType:\n return true;\n case kRGB_565_SkColorType:\n return src.alphaType() == kOpaque_SkAlphaType;\n default:\n return false;\n }\n}\n\nSkISize SkWebpCodec::onGetScaledDimensions(float desiredScale) const {\n SkISize dim = this->getInfo().dimensions();\n \/\/ SkCodec treats zero dimensional images as errors, so the minimum size\n \/\/ that we will recommend is 1x1.\n dim.fWidth = SkTMax(1, SkScalarRoundToInt(desiredScale * dim.fWidth));\n dim.fHeight = SkTMax(1, SkScalarRoundToInt(desiredScale * dim.fHeight));\n return dim;\n}\n\nbool SkWebpCodec::onDimensionsSupported(const SkISize& dim) {\n const SkImageInfo& info = this->getInfo();\n return dim.width() >= 1 && dim.width() <= info.width()\n && dim.height() >= 1 && dim.height() <= info.height();\n}\n\n\nstatic WEBP_CSP_MODE webp_decode_mode(SkColorType ct, bool premultiply) {\n switch (ct) {\n case kBGRA_8888_SkColorType:\n return premultiply ? MODE_bgrA : MODE_BGRA;\n case kRGBA_8888_SkColorType:\n return premultiply ? MODE_rgbA : MODE_RGBA;\n case kRGB_565_SkColorType:\n return MODE_RGB_565;\n default:\n return MODE_LAST;\n }\n}\n\n\/\/ The WebP decoding API allows us to incrementally pass chunks of bytes as we receive them to the\n\/\/ decoder with WebPIAppend. In order to do so, we need to read chunks from the SkStream. This size\n\/\/ is arbitrary.\nstatic const size_t BUFFER_SIZE = 4096;\n\nbool SkWebpCodec::onGetValidSubset(SkIRect* desiredSubset) const {\n if (!desiredSubset) {\n return false;\n }\n\n SkIRect dimensions = SkIRect::MakeSize(this->getInfo().dimensions());\n if (!dimensions.contains(*desiredSubset)) {\n return false;\n }\n\n \/\/ As stated below, libwebp snaps to even left and top. Make sure top and left are even, so we\n \/\/ decode this exact subset.\n \/\/ Leave right and bottom unmodified, so we suggest a slightly larger subset than requested.\n desiredSubset->fLeft = (desiredSubset->fLeft >> 1) << 1;\n desiredSubset->fTop = (desiredSubset->fTop >> 1) << 1;\n return true;\n}\n\nSkCodec::Result SkWebpCodec::onGetPixels(const SkImageInfo& dstInfo, void* dst, size_t rowBytes,\n const Options& options, SkPMColor*, int*,\n int* rowsDecoded) {\n if (!webp_conversion_possible(dstInfo, this->getInfo())) {\n return kInvalidConversion;\n }\n\n WebPDecoderConfig config;\n if (0 == WebPInitDecoderConfig(&config)) {\n \/\/ ABI mismatch.\n \/\/ FIXME: New enum for this?\n return kInvalidInput;\n }\n\n \/\/ Free any memory associated with the buffer. Must be called last, so we declare it first.\n SkAutoTCallVProc<WebPDecBuffer, WebPFreeDecBuffer> autoFree(&(config.output));\n\n SkIRect bounds = SkIRect::MakeSize(this->getInfo().dimensions());\n if (options.fSubset) {\n \/\/ Caller is requesting a subset.\n if (!bounds.contains(*options.fSubset)) {\n \/\/ The subset is out of bounds.\n return kInvalidParameters;\n }\n\n bounds = *options.fSubset;\n\n \/\/ This is tricky. libwebp snaps the top and left to even values. We could let libwebp\n \/\/ do the snap, and return a subset which is a different one than requested. The problem\n \/\/ with that approach is that the caller may try to stitch subsets together, and if we\n \/\/ returned different subsets than requested, there would be artifacts at the boundaries.\n \/\/ Instead, we report that we cannot support odd values for top and left..\n if (!SkIsAlign2(bounds.fLeft) || !SkIsAlign2(bounds.fTop)) {\n return kInvalidParameters;\n }\n\n#ifdef SK_DEBUG\n {\n \/\/ Make a copy, since getValidSubset can change its input.\n SkIRect subset(bounds);\n \/\/ That said, getValidSubset should *not* change its input, in this case; otherwise\n \/\/ getValidSubset does not match the actual subsets we can do.\n SkASSERT(this->getValidSubset(&subset) && subset == bounds);\n }\n#endif\n\n config.options.use_cropping = 1;\n config.options.crop_left = bounds.fLeft;\n config.options.crop_top = bounds.fTop;\n config.options.crop_width = bounds.width();\n config.options.crop_height = bounds.height();\n }\n\n SkISize dstDimensions = dstInfo.dimensions();\n if (bounds.size() != dstDimensions) {\n \/\/ Caller is requesting scaling.\n config.options.use_scaling = 1;\n config.options.scaled_width = dstDimensions.width();\n config.options.scaled_height = dstDimensions.height();\n }\n\n config.output.colorspace = webp_decode_mode(dstInfo.colorType(),\n dstInfo.alphaType() == kPremul_SkAlphaType);\n config.output.u.RGBA.rgba = (uint8_t*) dst;\n config.output.u.RGBA.stride = (int) rowBytes;\n config.output.u.RGBA.size = dstInfo.getSafeSize(rowBytes);\n config.output.is_external_memory = 1;\n\n SkAutoTCallVProc<WebPIDecoder, WebPIDelete> idec(WebPIDecode(nullptr, 0, &config));\n if (!idec) {\n return kInvalidInput;\n }\n\n SkAutoTMalloc<uint8_t> storage(BUFFER_SIZE);\n uint8_t* buffer = storage.get();\n while (true) {\n const size_t bytesRead = stream()->read(buffer, BUFFER_SIZE);\n if (0 == bytesRead) {\n WebPIDecGetRGB(idec, rowsDecoded, NULL, NULL, NULL);\n return kIncompleteInput;\n }\n\n switch (WebPIAppend(idec, buffer, bytesRead)) {\n case VP8_STATUS_OK:\n return kSuccess;\n case VP8_STATUS_SUSPENDED:\n \/\/ Break out of the switch statement. Continue the loop.\n break;\n default:\n return kInvalidInput;\n }\n }\n}\n\nSkWebpCodec::SkWebpCodec(const SkImageInfo& info, SkStream* stream)\n \/\/ The spec says an unmarked image is sRGB, so we return that space here.\n \/\/ TODO: Add support for parsing ICC profiles from webps.\n : INHERITED(info, stream, SkColorSpace::NewNamed(SkColorSpace::kSRGB_Named)) {}\n<|endoftext|>"} {"text":"<commit_before>\/*\n NUI3 - C++ cross-platform GUI framework for OpenGL based applications\n Copyright (C) 2002-2003 Sebastien Metrot & Vincent Caron\n \n licence: see nui3\/LICENCE.TXT\n *\/\n\n#include \"nui.h\"\n#include \"nuiChunkSampleReader.h\"\n\n#define CHUNK_ID_BYTES 4\n#define CHUNK_SIZE_BYTES 4\n#define CHUNK_HEADER_BYTES (CHUNK_ID_BYTES + CHUNK_SIZE_BYTES)\n#define FIRST_CHUNK_DATA_BYTES 4 \/\/4 bytes to represent RIFF type (WAVE, AIFF...)\n\/\/\n\/\/\n\/\/nuiChunkSampleReader\n\/\/\n\/\/\n\nnuiChunkSampleReader::nuiChunkSampleReader(nglIStream& rStream) : \nnuiSampleReader(rStream)\n{\n}\n\nnuiChunkSampleReader::nuiChunkSampleReader(const nuiChunkSampleReader& rReader, nglIStream& rStream) :\nnuiSampleReader(rReader, rStream)\n{\n for (uint32 i = 0; i < rReader.mChunks.size(); i++)\n {\n Chunk* pChunk = new Chunk(rReader.mChunks[i]->mPosition, rReader.mChunks[i]->mDataSize, rReader.mChunks[i]->mDataPosition, rReader.mChunks[i]->mId);\n mChunks.push_back(pChunk);\n }\n}\n\nnuiChunkSampleReader::~nuiChunkSampleReader()\n{\n ClearChunks();\n}\n\n\nbool nuiChunkSampleReader::GoToChunk(char* pId)\n{\n bool found = false;\n uint32 index = 0;\n for (uint32 i = 0; i < mChunks.size() && !found; i++)\n {\n found = mChunks[i]->CompareId(pId);\n if (found)\n index = i;\n }\n \n if (found)\n {\n \/\/Set Stream position\n nglFileOffset pos = mChunks[index]->mDataPosition;\n mrStream.SetPos(pos);\n }\n \n return found;\n}\n\nnuiChunkSampleReader::Chunk* nuiChunkSampleReader::GetChunk(char* Id)\n{\n bool found = false;\n uint32 index = 0;\n for (uint32 i = 0; i < mChunks.size() && !found; i++)\n {\n found = mChunks[i]->CompareId(Id);\n if (found)\n index = i;\n }\n \n if (found)\n {\n Chunk* pChunk = mChunks[index];\n return pChunk;\n }\n \n return NULL;\n}\n\nbool nuiChunkSampleReader::ScanAllChunks()\n{ \n ClearChunks();\n \n \/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/FIRST CHUNK\n mrStream.SetPos(0);\n \n \/\/get Id\n \/\/std::vector<char> Id(4);\n char* Id = new char[5];\n for(uint32 k = 0; k < 4; k++)\n {\n if( 1 != mrStream.ReadUInt8((uint8*)&(Id[k]), 1))\n return false;\n }\n Id[4] = '\\0';\n \/\/get first chunk size\n uint32 utilSize = 0; \/\/ = (total size of the stream) - (first chunk header size)\n if (1 != mrStream.ReadUInt32(&utilSize, 1))\n return false;\n uint32 firstChunkSize = FIRST_CHUNK_DATA_BYTES;\n\n Chunk* pFirstChunk = new Chunk(0, firstChunkSize, CHUNK_HEADER_BYTES, Id);\n mChunks.push_back(pFirstChunk);\n nglFileOffset TotalSize = CHUNK_HEADER_BYTES + firstChunkSize + utilSize;\n \n do\n {\n \/\/\/\/\/\/\/\/\/\/\/\/\n \/\/NEXT CHUNK\n nglFileOffset ChunkPosition = mChunks.back()->mDataPosition + mChunks.back()->mDataSize;\n mrStream.SetPos(ChunkPosition);\n uint32 ChunkSize = 0;\n for(uint32 k = 0; k < 4; k++)\n {\n if( 1 != mrStream.ReadUInt8((uint8*)&(Id[k]), 1))\n return false;\n }\n \/\/get chunk size\n if (1 != mrStream.ReadUInt32(&ChunkSize, 1))\n return false;\n if (0 != ChunkSize % 2)\n ChunkSize += 1; \/\/ the chunk size is always even\n Chunk* pNextChunk = new Chunk(ChunkPosition, ChunkSize, ChunkPosition + CHUNK_HEADER_BYTES, Id);\n mChunks.push_back(pNextChunk);\n }\n while (mChunks.back()->mDataPosition + mChunks.back()->mDataSize < TotalSize);\n\n delete[] Id;\n return true;\n}\n\nvoid nuiChunkSampleReader::ClearChunks()\n{\n for (uint32 i = 0; i < mChunks.size(); i++)\n {\n delete mChunks[i];\n mChunks[i] = NULL;\n }\n mChunks.clear();\n}\n\n\nuint32 nuiChunkSampleReader::ReadDE(std::vector<void*> buffers, uint32 sampleframes, nuiSampleBitFormat format)\n{\n \/\/don't increment mPosition: it's already done in ReadIN\n const uint32 channels = mInfo.GetChannels();\n uint32 length = mInfo.GetSampleFrames();\n if (mPosition >= length)\n return 0;\n sampleframes = MIN(sampleframes, length - mPosition);\n \n if (buffers.size() != channels)\n {\n return 0;\n }\n \n bool deleteBuffer = false;\n uint32 SampleFramesRead = 0;\n switch (format)\n {\n case eSampleFloat32:\n {\n float* pFloatBuffer = NULL;\n if (channels == 1)\n {\n pFloatBuffer = (float*)(buffers[0]);\n deleteBuffer = false;\n }\n else\n {\n pFloatBuffer = new float[sampleframes * channels];\n deleteBuffer = true;\n }\n \n SampleFramesRead = ReadIN((void*)pFloatBuffer, sampleframes, format); \/\/mPosition is incremented inside\n for (uint32 s = 0; s < SampleFramesRead; s++)\n {\n for (uint32 c = 0; c < channels; c++)\n {\n float* pDest = (float*)buffers[c];\n pDest[s] = pFloatBuffer[channels * s + c];\n }\n }\n if (deleteBuffer)\n delete[] pFloatBuffer;\n }\n break;\n \n case eSampleInt16:\n {\n int16* pIntBuffer = NULL;\n if (channels == 1)\n {\n pIntBuffer = (int16*)(buffers[0]);\n deleteBuffer = false;\n }\n else\n {\n pIntBuffer = new int16[sampleframes * channels];\n deleteBuffer = true;\n }\n \n SampleFramesRead = ReadIN((void*)pIntBuffer, sampleframes, format);\/\/mPosition is incremented inside\n for (uint32 s = 0; s < SampleFramesRead; s++)\n {\n for (uint32 c = 0; c < channels; c++)\n {\n ((int16*)(buffers[c]))[s] = pIntBuffer[channels * s + c];\n }\n }\n if (deleteBuffer)\n delete[] pIntBuffer;\n }\n break;\n \n default:\n break;\n }\n \n \n \/\/don't increment mPosition: it's already done in ReadIN\n return SampleFramesRead;\n}\n\n\n\/\/\n\/\/\n\/\/Chunk\n\/\/\n\/\/\nnuiChunkSampleReader::Chunk::Chunk():\nmPosition(0),\nmDataSize(0),\nmDataPosition(0),\nmId(NULL)\n{\n}\n\nnuiChunkSampleReader::Chunk::Chunk(nglFileOffset position, nglFileOffset dataSize, nglFileOffset dataPosition, const char* Id):\nmPosition(position),\nmDataSize(dataSize),\nmDataPosition(dataPosition),\nmId(NULL)\n{\n if (Id)\n {\n mId = new char[strlen(Id) + 1];\n char* res = strcpy(mId, Id);\n int i = 0;\n }\n}\n\nnuiChunkSampleReader::Chunk::~Chunk()\n{\n if (mId)\n {\n delete[] mId;\n mId = NULL;\n }\n}\n\n\nbool nuiChunkSampleReader::Chunk::CompareId(const char* Id) const\n{\n const int compare = strcmp(mId, Id);\n return (compare == 0);\n}\n\n<commit_msg>fixed memory leak in nuiChunkSampleReader (from meeloo)<commit_after>\/*\n NUI3 - C++ cross-platform GUI framework for OpenGL based applications\n Copyright (C) 2002-2003 Sebastien Metrot & Vincent Caron\n \n licence: see nui3\/LICENCE.TXT\n *\/\n\n#include \"nui.h\"\n#include \"nuiChunkSampleReader.h\"\n\n#define CHUNK_ID_BYTES 4\n#define CHUNK_SIZE_BYTES 4\n#define CHUNK_HEADER_BYTES (CHUNK_ID_BYTES + CHUNK_SIZE_BYTES)\n#define FIRST_CHUNK_DATA_BYTES 4 \/\/4 bytes to represent RIFF type (WAVE, AIFF...)\n\/\/\n\/\/\n\/\/nuiChunkSampleReader\n\/\/\n\/\/\n\nnuiChunkSampleReader::nuiChunkSampleReader(nglIStream& rStream) : \nnuiSampleReader(rStream)\n{\n}\n\nnuiChunkSampleReader::nuiChunkSampleReader(const nuiChunkSampleReader& rReader, nglIStream& rStream) :\nnuiSampleReader(rReader, rStream)\n{\n for (uint32 i = 0; i < rReader.mChunks.size(); i++)\n {\n Chunk* pChunk = new Chunk(rReader.mChunks[i]->mPosition, rReader.mChunks[i]->mDataSize, rReader.mChunks[i]->mDataPosition, rReader.mChunks[i]->mId);\n mChunks.push_back(pChunk);\n }\n}\n\nnuiChunkSampleReader::~nuiChunkSampleReader()\n{\n ClearChunks();\n}\n\n\nbool nuiChunkSampleReader::GoToChunk(char* pId)\n{\n bool found = false;\n uint32 index = 0;\n for (uint32 i = 0; i < mChunks.size() && !found; i++)\n {\n found = mChunks[i]->CompareId(pId);\n if (found)\n index = i;\n }\n \n if (found)\n {\n \/\/Set Stream position\n nglFileOffset pos = mChunks[index]->mDataPosition;\n mrStream.SetPos(pos);\n }\n \n return found;\n}\n\nnuiChunkSampleReader::Chunk* nuiChunkSampleReader::GetChunk(char* Id)\n{\n bool found = false;\n uint32 index = 0;\n for (uint32 i = 0; i < mChunks.size() && !found; i++)\n {\n found = mChunks[i]->CompareId(Id);\n if (found)\n index = i;\n }\n \n if (found)\n {\n Chunk* pChunk = mChunks[index];\n return pChunk;\n }\n \n return NULL;\n}\n\nbool nuiChunkSampleReader::ScanAllChunks()\n{ \n ClearChunks();\n \n \/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/FIRST CHUNK\n mrStream.SetPos(0);\n \n \/\/get Id\n \/\/std::vector<char> Id(4);\n char* Id = new char[5];\n for(uint32 k = 0; k < 4; k++)\n {\n if( 1 != mrStream.ReadUInt8((uint8*)&(Id[k]), 1))\n {\n delete[] Id;\n return false;\n }\n }\n Id[4] = '\\0';\n \/\/get first chunk size\n uint32 utilSize = 0; \/\/ = (total size of the stream) - (first chunk header size)\n if (1 != mrStream.ReadUInt32(&utilSize, 1))\n {\n delete[] Id;\n return false;\n }\n uint32 firstChunkSize = FIRST_CHUNK_DATA_BYTES;\n\n Chunk* pFirstChunk = new Chunk(0, firstChunkSize, CHUNK_HEADER_BYTES, Id);\n mChunks.push_back(pFirstChunk);\n nglFileOffset TotalSize = CHUNK_HEADER_BYTES + firstChunkSize + utilSize;\n \n do\n {\n \/\/\/\/\/\/\/\/\/\/\/\/\n \/\/NEXT CHUNK\n nglFileOffset ChunkPosition = mChunks.back()->mDataPosition + mChunks.back()->mDataSize;\n mrStream.SetPos(ChunkPosition);\n uint32 ChunkSize = 0;\n for(uint32 k = 0; k < 4; k++)\n {\n if( 1 != mrStream.ReadUInt8((uint8*)&(Id[k]), 1))\n {\n delete[] Id;\n return false;\n }\n }\n \/\/get chunk size\n if (1 != mrStream.ReadUInt32(&ChunkSize, 1))\n {\n delete[] Id;\n return false;\n }\n if (0 != ChunkSize % 2)\n ChunkSize += 1; \/\/ the chunk size is always even\n Chunk* pNextChunk = new Chunk(ChunkPosition, ChunkSize, ChunkPosition + CHUNK_HEADER_BYTES, Id);\n mChunks.push_back(pNextChunk);\n }\n while (mChunks.back()->mDataPosition + mChunks.back()->mDataSize < TotalSize);\n\n delete[] Id;\n return true;\n}\n\nvoid nuiChunkSampleReader::ClearChunks()\n{\n for (uint32 i = 0; i < mChunks.size(); i++)\n {\n delete mChunks[i];\n mChunks[i] = NULL;\n }\n mChunks.clear();\n}\n\n\nuint32 nuiChunkSampleReader::ReadDE(std::vector<void*> buffers, uint32 sampleframes, nuiSampleBitFormat format)\n{\n \/\/don't increment mPosition: it's already done in ReadIN\n const uint32 channels = mInfo.GetChannels();\n uint32 length = mInfo.GetSampleFrames();\n if (mPosition >= length)\n return 0;\n sampleframes = MIN(sampleframes, length - mPosition);\n \n if (buffers.size() != channels)\n {\n return 0;\n }\n \n bool deleteBuffer = false;\n uint32 SampleFramesRead = 0;\n switch (format)\n {\n case eSampleFloat32:\n {\n float* pFloatBuffer = NULL;\n if (channels == 1)\n {\n pFloatBuffer = (float*)(buffers[0]);\n deleteBuffer = false;\n }\n else\n {\n pFloatBuffer = new float[sampleframes * channels];\n deleteBuffer = true;\n }\n \n SampleFramesRead = ReadIN((void*)pFloatBuffer, sampleframes, format); \/\/mPosition is incremented inside\n for (uint32 s = 0; s < SampleFramesRead; s++)\n {\n for (uint32 c = 0; c < channels; c++)\n {\n float* pDest = (float*)buffers[c];\n pDest[s] = pFloatBuffer[channels * s + c];\n }\n }\n if (deleteBuffer)\n delete[] pFloatBuffer;\n }\n break;\n \n case eSampleInt16:\n {\n int16* pIntBuffer = NULL;\n if (channels == 1)\n {\n pIntBuffer = (int16*)(buffers[0]);\n deleteBuffer = false;\n }\n else\n {\n pIntBuffer = new int16[sampleframes * channels];\n deleteBuffer = true;\n }\n \n SampleFramesRead = ReadIN((void*)pIntBuffer, sampleframes, format);\/\/mPosition is incremented inside\n for (uint32 s = 0; s < SampleFramesRead; s++)\n {\n for (uint32 c = 0; c < channels; c++)\n {\n ((int16*)(buffers[c]))[s] = pIntBuffer[channels * s + c];\n }\n }\n if (deleteBuffer)\n delete[] pIntBuffer;\n }\n break;\n \n default:\n break;\n }\n \n \n \/\/don't increment mPosition: it's already done in ReadIN\n return SampleFramesRead;\n}\n\n\n\/\/\n\/\/\n\/\/Chunk\n\/\/\n\/\/\nnuiChunkSampleReader::Chunk::Chunk():\nmPosition(0),\nmDataSize(0),\nmDataPosition(0),\nmId(NULL)\n{\n}\n\nnuiChunkSampleReader::Chunk::Chunk(nglFileOffset position, nglFileOffset dataSize, nglFileOffset dataPosition, const char* Id):\nmPosition(position),\nmDataSize(dataSize),\nmDataPosition(dataPosition),\nmId(NULL)\n{\n if (Id)\n {\n mId = new char[strlen(Id) + 1];\n char* res = strcpy(mId, Id);\n int i = 0;\n }\n}\n\nnuiChunkSampleReader::Chunk::~Chunk()\n{\n if (mId)\n {\n delete[] mId;\n mId = NULL;\n }\n}\n\n\nbool nuiChunkSampleReader::Chunk::CompareId(const char* Id) const\n{\n const int compare = strcmp(mId, Id);\n return (compare == 0);\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/* bzflag\n* Copyright (c) 1993 - 2005 Tim Riker\n*\n* This package is free software; you can redistribute it and\/or\n* modify it under the terms of the license found in the file\n* named COPYING that should have accompanied this file.\n*\n* THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR\n* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED\n* WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.\n*\/\n\n#ifdef _MSC_VER\n#pragma warning( 4: 4786)\n#define _WINSOCK2API_\n#endif\n\n\/\/ bzflag common header\n#include \"common.h\"\n\n\/\/ class interface header\n#include \"URLManager.h\"\n#ifdef HAVE_CURL\n#include <curl\/curl.h>\n#endif\n\n\/\/ system headers\n#include <iostream>\n\n\/\/ common implementation headers\n#include \"bzfio.h\"\n#include \"StateDatabase.h\"\n\n\ntemplate <>\nURLManager* Singleton<URLManager>::_instance = (URLManager*)0;\n\n#ifdef HAVE_CURL\nstatic size_t writeFunction(void *ptr, size_t size, size_t nmemb, void *stream);\n#endif \/\/ HAVE_CURL\n\nbool URLManager::getURL(const std::string URL, std::string &data)\n{\n clearInternal();\n\n if (!beginGet(URL))\n return false;\n\n char* newData = (char*)malloc(theLen + 1);\n memcpy(newData, theData, theLen);\n newData[theLen] = 0;\n\n data = newData;\n free(newData);\n\n return true;\n}\n\nbool URLManager::getURL(const std::string URL, void **data, unsigned int& size)\n{\n clearInternal();\n\n if (!beginGet(URL))\n return false;\n\n *data = malloc(theLen);\n memcpy(*data, theData, theLen);\n size = theLen;\n return true;\n}\n\nvoid URLManager::freeURLData(void *data)\n{\n free(data);\n}\n\nURLManager::URLManager()\n{\n easyHandle = NULL;\n theData = NULL;\n theLen = 0;\n\n#ifdef HAVE_CURL\n CURLcode curlResult;\n if ((curlResult = curl_global_init(CURL_GLOBAL_NOTHING)))\n DEBUG1(\"Unexpected error from libcurl; Error: %d\\n\", curlResult);\n\n easyHandle = curl_easy_init();\n if (!easyHandle) {\n DEBUG1(\"Something wrong with CURL\\n\");\n return;\n }\n\n CURLcode result = curl_easy_setopt((CURL*)easyHandle, CURLOPT_WRITEFUNCTION, writeFunction);\n if (result)\n DEBUG1(\"Something wrong with CURL; Error: %d\\n\", result);\n\n result = curl_easy_setopt((CURL*)easyHandle, CURLOPT_FILE, this);\n if (result)\n DEBUG1(\"Something wrong with CURL; Error: %d\\n\", result);\n#endif\n}\n\nURLManager::~URLManager()\n{\n clearInternal();\n\n#ifdef HAVE_CURL\n if (easyHandle)\n curl_easy_cleanup((CURL*)easyHandle);\n curl_global_cleanup();\n#endif\n}\n\nvoid URLManager::collectData(char* ptr, int len)\n{\n unsigned char\t*newData = (unsigned char*)malloc(theLen + len);\n if (theData)\n memcpy(newData, theData, theLen);\n\n memcpy(&(newData[theLen]), ptr, len);\n theLen += len;\n\n free(theData);\n theData = newData;\n}\n\nvoid URLManager::clearInternal()\n{\n if (theData)\n free (theData);\n\n theData = NULL;\n theLen = 0;\n}\n\n#ifdef HAVE_CURL\nbool URLManager::beginGet(const std::string URL)\n#else\nbool URLManager::beginGet(const std::string)\n#endif\n{\n#ifdef HAVE_CURL\n CURLcode result;\n if (!easyHandle) {\n return false;\n }\n\n float timeout = 15;\n if (BZDB.isSet(\"httpTimeout\"))\n timeout = BZDB.eval(\"httpTimeout\");\n\n result = curl_easy_setopt((CURL*)easyHandle, CURLOPT_TIMEOUT, timeout);\n if (result)\n DEBUG1(\"Something wrong with CURL; Error: %d\\n\", result);\n\n result = curl_easy_setopt((CURL*)easyHandle, CURLOPT_URL, URL.c_str());\n if (result) {\n DEBUG1(\"Something wrong with CURL; Error: %d\\n\", result);\n }\n\n \/\/ FIXME: This could block for a _long_ time.\n result = curl_easy_perform((CURL*)easyHandle);\n if (result == (CURLcode)CURLOPT_ERRORBUFFER) {\n DEBUG1(\"Error: server reported: %d\\n\", result);\n return false;\n } else if (result) {\n DEBUG1(\"Something wrong with CURL; Error: %d\\n\", result);\n return false;\n }\n\n result = curl_easy_setopt((CURL*)easyHandle, CURLOPT_URL, NULL);\n if (result) {\n DEBUG1(\"Something wrong with CURL; Error: %d\\n\", result);\n return false;\n }\n\n if (!theData)\n return false;\n\n return true;\n#else\n return false;\n#endif \/\/ HAVE_CURL\n}\n\n#ifdef HAVE_CURL\nstatic size_t writeFunction(void *ptr, size_t size, size_t nmemb, void *stream)\n{\n int len = size * nmemb;\n ((URLManager*)stream)->collectData((char*)ptr, len);\n return len;\n}\n#endif \/\/ HAVE_CURL\n\n\/\/ Local Variables: ***\n\/\/ mode:C++ ***\n\/\/ tab-width: 8 ***\n\/\/ c-basic-offset: 2 ***\n\/\/ indent-tabs-mode: t ***\n\/\/ End: ***\n\/\/ ex: shiftwidth=2 tabstop=8\n<commit_msg>if the timeout is reached, default curl behavior is to throw a SIGALRM. this happens on Mac OS X regardless (there was list chatter hinting at it being multithreaded related (which cocoa apps are)) so we need to enable another option that disables throwing the signal. This requires curl 7.10 so may need some version wrapping if older versions are in common use.<commit_after>\/* bzflag\n* Copyright (c) 1993 - 2005 Tim Riker\n*\n* This package is free software; you can redistribute it and\/or\n* modify it under the terms of the license found in the file\n* named COPYING that should have accompanied this file.\n*\n* THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR\n* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED\n* WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.\n*\/\n\n#ifdef _MSC_VER\n#pragma warning( 4: 4786)\n#define _WINSOCK2API_\n#endif\n\n\/\/ bzflag common header\n#include \"common.h\"\n\n\/\/ class interface header\n#include \"URLManager.h\"\n#ifdef HAVE_CURL\n#include <curl\/curl.h>\n#endif\n\n\/\/ system headers\n#include <iostream>\n\n\/\/ common implementation headers\n#include \"bzfio.h\"\n#include \"StateDatabase.h\"\n\n\ntemplate <>\nURLManager* Singleton<URLManager>::_instance = (URLManager*)0;\n\n#ifdef HAVE_CURL\nstatic size_t writeFunction(void *ptr, size_t size, size_t nmemb, void *stream);\n#endif \/\/ HAVE_CURL\n\nbool URLManager::getURL(const std::string URL, std::string &data)\n{\n clearInternal();\n\n if (!beginGet(URL))\n return false;\n\n char* newData = (char*)malloc(theLen + 1);\n memcpy(newData, theData, theLen);\n newData[theLen] = 0;\n\n data = newData;\n free(newData);\n\n return true;\n}\n\nbool URLManager::getURL(const std::string URL, void **data, unsigned int& size)\n{\n clearInternal();\n\n if (!beginGet(URL))\n return false;\n\n *data = malloc(theLen);\n memcpy(*data, theData, theLen);\n size = theLen;\n return true;\n}\n\nvoid URLManager::freeURLData(void *data)\n{\n free(data);\n}\n\nURLManager::URLManager()\n{\n easyHandle = NULL;\n theData = NULL;\n theLen = 0;\n\n#ifdef HAVE_CURL\n CURLcode curlResult;\n if ((curlResult = curl_global_init(CURL_GLOBAL_NOTHING)))\n DEBUG1(\"Unexpected error from libcurl; Error: %d\\n\", curlResult);\n\n easyHandle = curl_easy_init();\n if (!easyHandle) {\n DEBUG1(\"Something wrong with CURL\\n\");\n return;\n }\n\n CURLcode result = curl_easy_setopt((CURL*)easyHandle, CURLOPT_WRITEFUNCTION, writeFunction);\n if (result)\n DEBUG1(\"Something wrong with CURL; Error: %d\\n\", result);\n\n result = curl_easy_setopt((CURL*)easyHandle, CURLOPT_FILE, this);\n if (result)\n DEBUG1(\"Something wrong with CURL; Error: %d\\n\", result);\n#endif\n}\n\nURLManager::~URLManager()\n{\n clearInternal();\n\n#ifdef HAVE_CURL\n if (easyHandle)\n curl_easy_cleanup((CURL*)easyHandle);\n curl_global_cleanup();\n#endif\n}\n\nvoid URLManager::collectData(char* ptr, int len)\n{\n unsigned char\t*newData = (unsigned char*)malloc(theLen + len);\n if (theData)\n memcpy(newData, theData, theLen);\n\n memcpy(&(newData[theLen]), ptr, len);\n theLen += len;\n\n free(theData);\n theData = newData;\n}\n\nvoid URLManager::clearInternal()\n{\n if (theData)\n free (theData);\n\n theData = NULL;\n theLen = 0;\n}\n\n#ifdef HAVE_CURL\nbool URLManager::beginGet(const std::string URL)\n#else\nbool URLManager::beginGet(const std::string)\n#endif\n{\n#ifdef HAVE_CURL\n CURLcode result = 0;\n if (!easyHandle) {\n return false;\n }\n\n float timeout = 15;\n if (BZDB.isSet(\"httpTimeout\"))\n timeout = BZDB.eval(\"httpTimeout\");\n\n result = curl_easy_setopt((CURL*)easyHandle, CURLOPT_NOSIGNAL, true);\n if (result) {\n DEBUG1(\"Something wrong with CURL; Error: %d\\n\", result);\n }\n\n result = curl_easy_setopt((CURL*)easyHandle, CURLOPT_TIMEOUT, timeout);\n if (result) {\n DEBUG1(\"Something wrong with CURL; Error: %d\\n\", result);\n }\n\n result = curl_easy_setopt((CURL*)easyHandle, CURLOPT_URL, URL.c_str());\n if (result) {\n DEBUG1(\"Something wrong with CURL; Error: %d\\n\", result);\n }\n\n \/\/ FIXME: This could block for a _long_ time.\n result = curl_easy_perform((CURL*)easyHandle);\n if (result == (CURLcode)CURLOPT_ERRORBUFFER) {\n DEBUG1(\"Error: server reported: %d\\n\", result);\n return false;\n } else if (result) {\n DEBUG1(\"Something wrong with CURL; Error: %d\\n\", result);\n return false;\n }\n\n result = curl_easy_setopt((CURL*)easyHandle, CURLOPT_URL, NULL);\n if (result) {\n DEBUG1(\"Something wrong with CURL; Error: %d\\n\", result);\n return false;\n }\n\n if (!theData)\n return false;\n\n return true;\n#else\n return false;\n#endif \/\/ HAVE_CURL\n}\n\n#ifdef HAVE_CURL\nstatic size_t writeFunction(void *ptr, size_t size, size_t nmemb, void *stream)\n{\n int len = size * nmemb;\n ((URLManager*)stream)->collectData((char*)ptr, len);\n return len;\n}\n#endif \/\/ HAVE_CURL\n\n\/\/ Local Variables: ***\n\/\/ mode:C++ ***\n\/\/ tab-width: 8 ***\n\/\/ c-basic-offset: 2 ***\n\/\/ indent-tabs-mode: t ***\n\/\/ End: ***\n\/\/ ex: shiftwidth=2 tabstop=8\n<|endoftext|>"} {"text":"<commit_before>\/**\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements. See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership. The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include <mesos\/mesos.hpp>\n#include <mesos\/resources.hpp>\n\n#include \"common\/attributes.hpp\"\n#include \"common\/type_utils.hpp\"\n\nnamespace mesos {\n\nbool operator == (const Environment& left, const Environment& right)\n{\n if (left.variables().size() != right.variables().size()) {\n return false;\n }\n\n for (int i = 0; i < left.variables().size(); i++) {\n const std::string& name = left.variables().Get(i).name();\n const std::string& value = left.variables().Get(i).value();\n bool found = false;\n for (int j = 0; j < right.variables().size(); j++) {\n if (name == right.variables().Get(j).name() &&\n value == right.variables().Get(j).value()) {\n found = true;\n break;\n }\n }\n if (!found) {\n return false;\n }\n }\n\n return true;\n}\n\n\nbool operator == (const CommandInfo& left, const CommandInfo& right)\n{\n if (left.uris().size() != right.uris().size()) {\n return false;\n }\n\n for (int i=0; i<left.uris().size(); i++) {\n bool found = false;\n for (int j=0; j<right.uris().size(); j++) {\n if (left.uris().Get(i) == right.uris().Get(j)) {\n found = true;\n break;\n }\n }\n if (!found) {\n return false;\n }\n }\n\n return left.has_environment() == right.has_environment() &&\n (!left.has_environment() || (left.environment() == right.environment())) &&\n left.value() == right.value();\n}\n\n\nbool operator == (const ExecutorInfo& left, const ExecutorInfo& right)\n{\n return left.executor_id() == right.executor_id() &&\n left.has_framework_id() == right.has_framework_id() &&\n (!left.has_framework_id() ||\n (left.framework_id() == right.framework_id())) &&\n left.command() == right.command() &&\n Resources(left.resources()) == Resources(right.resources()) &&\n left.has_name() == right.has_name() &&\n (!left.has_name() || (left.name() == right.name())) &&\n left.has_source() == right.has_source() &&\n (!left.has_source() || (left.source() == right.source())) &&\n left.has_data() == right.has_data() &&\n (!left.has_data() || (left.data() == right.data()));\n}\n\n\nbool operator == (const SlaveInfo& left, const SlaveInfo& right)\n{\n \/\/ NOTE: We don't compare 'webui_hostname' and 'webui_port' since\n \/\/ they're deprecated and do not carry any semantic meaning.\n return left.hostname() == right.hostname() &&\n Resources(left.resources()) == Resources(right.resources()) &&\n internal::Attributes(left.attributes()) ==\n internal::Attributes(right.attributes()) &&\n left.has_id() == right.has_id() &&\n (!left.has_id() || (left.id() == right.id())) &&\n left.has_checkpoint() == right.has_checkpoint() &&\n (!left.has_checkpoint() || (left.checkpoint() == right.checkpoint()));\n}\n\n\nbool operator == (const MasterInfo& left, const MasterInfo& right)\n{\n return left.id() == right.id() &&\n left.ip() == right.ip() &&\n left.port() == right.port() &&\n left.has_pid() == right.has_pid() &&\n (!left.has_pid() || (left.pid() == right.pid())) &&\n left.has_hostname() == right.has_hostname() &&\n (!left.has_hostname() || (left.hostname() == right.hostname()));\n}\n\n\nnamespace internal {\n\nbool operator == (const Task& left, const Task& right)\n{\n return left.name() == right.name() &&\n left.task_id() == right.task_id() &&\n left.framework_id() == right.framework_id() &&\n left.slave_id() == right.slave_id() &&\n left.state() == right.state() &&\n Resources(left.resources()) == Resources(right.resources()) &&\n left.has_executor_id() == right.has_executor_id() &&\n (!left.has_executor_id() || (left.executor_id() == right.executor_id()));\n}\n\n\nstd::ostream& operator << (\n std::ostream& stream,\n const StatusUpdate& update)\n{\n stream\n << update.status().state()\n << \" (UUID: \" << UUID::fromBytes(update.uuid())\n << \") for task \" << update.status().task_id();\n\n if (update.status().has_healthy()) {\n stream\n << \" in health state \"\n << (update.status().healthy() ? \"healthy\" : \"unhealthy\");\n }\n\n return stream\n << \" of framework \" << update.framework_id();\n}\n\n} \/\/ namespace internal {\n\n} \/\/ namespace mesos {\n<commit_msg>Updated equality check for CommandInfo.<commit_after>\/**\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements. See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership. The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include <mesos\/mesos.hpp>\n#include <mesos\/resources.hpp>\n\n#include \"common\/attributes.hpp\"\n#include \"common\/type_utils.hpp\"\n\nnamespace mesos {\n\nbool operator == (const Environment& left, const Environment& right)\n{\n if (left.variables().size() != right.variables().size()) {\n return false;\n }\n\n for (int i = 0; i < left.variables().size(); i++) {\n const std::string& name = left.variables().Get(i).name();\n const std::string& value = left.variables().Get(i).value();\n bool found = false;\n for (int j = 0; j < right.variables().size(); j++) {\n if (name == right.variables().Get(j).name() &&\n value == right.variables().Get(j).value()) {\n found = true;\n break;\n }\n }\n if (!found) {\n return false;\n }\n }\n\n return true;\n}\n\n\nbool operator == (const CommandInfo& left, const CommandInfo& right)\n{\n if (left.uris().size() != right.uris().size()) {\n return false;\n }\n\n for (int i = 0; i < left.uris().size(); i++) {\n bool found = false;\n for (int j = 0; j < right.uris().size(); j++) {\n if (left.uris().Get(i) == right.uris().Get(j)) {\n found = true;\n break;\n }\n }\n if (!found) {\n return false;\n }\n }\n\n if (left.argv().size() != right.argv().size()) {\n return false;\n }\n\n \/\/ The order of argv is important.\n for (int i = 0; i < left.argv().size(); i++) {\n if (left.argv().Get(i) != right.argv().Get(i)) {\n return false;\n }\n }\n\n return left.has_environment() == right.has_environment() &&\n (!left.has_environment() || (left.environment() == right.environment())) &&\n left.has_value() == right.has_value() &&\n (!left.has_value() || (left.value() == right.value())) &&\n left.has_shell() == right.has_shell() &&\n (!left.has_shell() || (left.shell() == right.shell()));\n}\n\n\nbool operator == (const ExecutorInfo& left, const ExecutorInfo& right)\n{\n return left.executor_id() == right.executor_id() &&\n left.has_framework_id() == right.has_framework_id() &&\n (!left.has_framework_id() ||\n (left.framework_id() == right.framework_id())) &&\n left.command() == right.command() &&\n Resources(left.resources()) == Resources(right.resources()) &&\n left.has_name() == right.has_name() &&\n (!left.has_name() || (left.name() == right.name())) &&\n left.has_source() == right.has_source() &&\n (!left.has_source() || (left.source() == right.source())) &&\n left.has_data() == right.has_data() &&\n (!left.has_data() || (left.data() == right.data()));\n}\n\n\nbool operator == (const SlaveInfo& left, const SlaveInfo& right)\n{\n \/\/ NOTE: We don't compare 'webui_hostname' and 'webui_port' since\n \/\/ they're deprecated and do not carry any semantic meaning.\n return left.hostname() == right.hostname() &&\n Resources(left.resources()) == Resources(right.resources()) &&\n internal::Attributes(left.attributes()) ==\n internal::Attributes(right.attributes()) &&\n left.has_id() == right.has_id() &&\n (!left.has_id() || (left.id() == right.id())) &&\n left.has_checkpoint() == right.has_checkpoint() &&\n (!left.has_checkpoint() || (left.checkpoint() == right.checkpoint()));\n}\n\n\nbool operator == (const MasterInfo& left, const MasterInfo& right)\n{\n return left.id() == right.id() &&\n left.ip() == right.ip() &&\n left.port() == right.port() &&\n left.has_pid() == right.has_pid() &&\n (!left.has_pid() || (left.pid() == right.pid())) &&\n left.has_hostname() == right.has_hostname() &&\n (!left.has_hostname() || (left.hostname() == right.hostname()));\n}\n\n\nnamespace internal {\n\nbool operator == (const Task& left, const Task& right)\n{\n return left.name() == right.name() &&\n left.task_id() == right.task_id() &&\n left.framework_id() == right.framework_id() &&\n left.slave_id() == right.slave_id() &&\n left.state() == right.state() &&\n Resources(left.resources()) == Resources(right.resources()) &&\n left.has_executor_id() == right.has_executor_id() &&\n (!left.has_executor_id() || (left.executor_id() == right.executor_id()));\n}\n\n\nstd::ostream& operator << (\n std::ostream& stream,\n const StatusUpdate& update)\n{\n stream\n << update.status().state()\n << \" (UUID: \" << UUID::fromBytes(update.uuid())\n << \") for task \" << update.status().task_id();\n\n if (update.status().has_healthy()) {\n stream\n << \" in health state \"\n << (update.status().healthy() ? \"healthy\" : \"unhealthy\");\n }\n\n return stream\n << \" of framework \" << update.framework_id();\n}\n\n} \/\/ namespace internal {\n\n} \/\/ namespace mesos {\n<|endoftext|>"} {"text":"<commit_before>#ifndef BFC_COMBINE_INC_VISITOR_HPP\n#define BFC_COMBINE_INC_VISITOR_HPP\n\n#include \"ast\/mod.hpp\"\n#include \"ast\/base.hpp\"\n#include \"test_visitor.hpp\"\n#include \"types.h\"\n\nnamespace bfc {\nnamespace ast {\n\nclass combine_inc_visitor : public opt_seq_base_visitor {\n\npublic:\n\n status visit(add &node) {\n \/\/ discard any zero value node\n if (node.value() == 0) {\n return CONTINUE;\n }\n \/\/ Only attempt to combine if there is a previous node\n if (!opt_seq.empty()) {\n \/\/ try to combine with the previous node if possible\n try_combine_inc_visitor v(node.offset(), node.value(), true);\n if (opt_seq.back().accept(v) == CONTINUE) {\n \/\/ discard the combined node if it is 0\n if (v.new_value() == 0) {\n opt_seq.pop_back();\n }\n return CONTINUE;\n }\n }\n \/\/ else make node copy\n return opt_seq_base_visitor::handle_add(node);\n }\n \n status visit(const add &node) {\n \/\/ discard any zero value node\n if (node.value() == 0) {\n return CONTINUE;\n }\n \/\/ Only attempt to combine if there is a previous node\n if (!opt_seq.empty()) {\n \/\/ try to combine with the previous node if possible\n try_combine_inc_visitor v(node.offset(), node.value(), true);\n if (opt_seq.back().accept(v) == CONTINUE) {\n \/\/ discard the combined node if it is 0\n if (v.new_value() == 0) {\n opt_seq.pop_back();\n }\n return CONTINUE;\n }\n }\n \/\/ else make node copy\n return opt_seq_base_visitor::handle_add(node);\n }\n \n status visit(sub &node) {\n \/\/ discard any zero value node\n if (node.value() == 0) {\n return CONTINUE;\n }\n \/\/ Only attempt to combine if there is a previous node\n if (!opt_seq.empty()) {\n \/\/ try to combine with the previous node if possible\n try_combine_inc_visitor v(node.offset(), node.value(), false);\n if (opt_seq.back().accept(v) == CONTINUE) {\n \/\/ discard the combined node if it is 0\n if (v.new_value() == 0) {\n opt_seq.pop_back();\n }\n return CONTINUE;\n }\n }\n \/\/ else make node copy\n return opt_seq_base_visitor::handle_sub(node);\n }\n \n status visit(const sub &node) {\n \/\/ discard any zero value node\n if (node.value() == 0) {\n return CONTINUE;\n }\n \/\/ Only attempt to combine if there is a previous node\n if (!opt_seq.empty()) {\n \/\/ try to combine with the previous node if possible\n try_combine_inc_visitor v(node.offset(), node.value(), false);\n if (opt_seq.back().accept(v) == CONTINUE) {\n \/\/ discard the combined node if it is 0\n if (v.new_value() == 0) {\n opt_seq.pop_back();\n }\n return CONTINUE;\n }\n }\n \/\/ else make node copy\n return opt_seq_base_visitor::handle_sub(node);\n }\n \nprivate:\n\n class try_combine_inc_visitor : public test_visitor {\n \n public:\n try_combine_inc_visitor(ptrdiff_t offset, bf_value val, bool isAdd) :\n next_off(offset), next_val(val), isAdd(isAdd) {}\n \n bf_value new_value() {\n return new_val;\n }\n \n status visit(set &node) {\n if (node.offset() != next_off) {\n return BREAK;\n }\n new_val = node.value();\n isAdd ? new_val += next_val : new_val -= next_val;\n node.value(new_val);\n return CONTINUE;\n }\n \n status visit(const set &node) {\n if (node.offset() != next_off) {\n return BREAK;\n }\n new_val = node.value();\n isAdd ? new_val += next_val : new_val -= next_val;\n node.value(new_val);\n return CONTINUE;\n }\n \n status visit(add &node) {\n if (node.offset() != next_off) {\n return BREAK;\n }\n new_val = node.value();\n isAdd ? new_val += next_val : new_val -= next_val;\n node.value(new_val);\n return CONTINUE;\n }\n \n status visit(const add &node) {\n if (node.offset() != next_off) {\n return BREAK;\n }\n new_val = node.value();\n isAdd ? new_val += next_val : new_val -= next_val;\n node.value(new_val);\n return CONTINUE;\n }\n \n status visit(sub &node) {\n if (node.offset() != next_off) {\n return BREAK;\n }\n new_val = node.value();\n isAdd ? new_val -= next_val : new_val += next_val;\n node.value(new_val);\n return CONTINUE;\n }\n \n status visit(const sub &node) {\n if (node.offset() != next_off) {\n return BREAK;\n }\n new_val = node.value();\n isAdd ? new_val -= next_val : new_val += next_val;\n node.value(new_val);\n return CONTINUE;\n }\n \n private:\n bool isAdd;\n ptrdiff_t next_off;\n bf_value next_val;\n bf_value new_val;\n \n };\n\n};\n\n}\n}\n\n#endif \/* !BFC_COMBINE_INC_VISITOR_HPP *\/\n<commit_msg>Fix mutating const nodes in inc visitor<commit_after>#ifndef BFC_COMBINE_INC_VISITOR_HPP\n#define BFC_COMBINE_INC_VISITOR_HPP\n\n#include \"ast\/mod.hpp\"\n#include \"ast\/base.hpp\"\n#include \"test_visitor.hpp\"\n#include \"types.h\"\n\nnamespace bfc {\nnamespace ast {\n\nclass combine_inc_visitor : public opt_seq_base_visitor {\n\npublic:\n\n status visit(add &node) {\n \/\/ discard any zero value node\n if (node.value() == 0) {\n return CONTINUE;\n }\n \/\/ Only attempt to combine if there is a previous node\n if (!opt_seq.empty()) {\n \/\/ try to combine with the previous node if possible\n try_combine_inc_visitor v(node.offset(), node.value(), true);\n if (opt_seq.back().accept(v) == CONTINUE) {\n opt_seq.pop_back();\n \/\/ discard the combined node if it is 0\n if (v.new_value() != 0) {\n if (v.type() == ADD) {\n opt_seq.emplace_back(new add(node.loc(), node.offset(), v.new_value());\n } else {\n opt_seq.emplace_back(new sub(node.loc(), node.offset(), v.new_value()); \n }\n }\n return CONTINUE;\n }\n }\n \/\/ else make node copy\n return opt_seq_base_visitor::handle_add(node);\n }\n \n status visit(const add &node) {\n \/\/ discard any zero value node\n if (node.value() == 0) {\n return CONTINUE;\n }\n \/\/ Only attempt to combine if there is a previous node\n if (!opt_seq.empty()) {\n \/\/ try to combine with the previous node if possible\n try_combine_inc_visitor v(node.offset(), node.value(), true);\n if (opt_seq.back().accept(v) == CONTINUE) {\n opt_seq.pop_back();\n \/\/ discard the combined node if it is 0\n if (v.new_value() != 0) {\n if (v.type() == ADD) {\n opt_seq.emplace_back(new add(node.loc(), node.offset(), v.new_value());\n } else {\n opt_seq.emplace_back(new sub(node.loc(), node.offset(), v.new_value()); \n }\n }\n return CONTINUE;\n }\n }\n \/\/ else make node copy\n return opt_seq_base_visitor::handle_add(node);\n }\n \n status visit(sub &node) {\n \/\/ discard any zero value node\n if (node.value() == 0) {\n return CONTINUE;\n }\n \/\/ Only attempt to combine if there is a previous node\n if (!opt_seq.empty()) {\n \/\/ try to combine with the previous node if possible\n try_combine_inc_visitor v(node.offset(), node.value(), false);\n if (opt_seq.back().accept(v) == CONTINUE) {\n opt_seq.pop_back();\n \/\/ discard the combined node if it is 0\n if (v.new_value() != 0) {\n if (v.type() == ADD) {\n opt_seq.emplace_back(new add(node.loc(), node.offset(), v.new_value());\n } else {\n opt_seq.emplace_back(new sub(node.loc(), node.offset(), v.new_value()); \n }\n return CONTINUE;\n }\n }\n }\n \/\/ else make node copy\n return opt_seq_base_visitor::handle_sub(node);\n }\n \n status visit(const sub &node) {\n \/\/ discard any zero value node\n if (node.value() == 0) {\n return CONTINUE;\n }\n \/\/ Only attempt to combine if there is a previous node\n if (!opt_seq.empty()) {\n \/\/ try to combine with the previous node if possible\n try_combine_inc_visitor v(node.offset(), node.value(), false);\n if (opt_seq.back().accept(v) == CONTINUE) {\n opt_seq.pop_back();\n \/\/ discard the combined node if it is 0\n if (v.new_value() != 0) {\n if (v.type() == ADD) {\n opt_seq.emplace_back(new add(node.loc(), node.offset(), v.new_value());\n } else {\n opt_seq.emplace_back(new sub(node.loc(), node.offset(), v.new_value()); \n }\n return CONTINUE;\n }\n return CONTINUE;\n }\n }\n \/\/ else make node copy\n return opt_seq_base_visitor::handle_sub(node);\n }\n \nprivate:\n\n class try_combine_inc_visitor : public test_visitor {\n \n enum node_type {\n ADD = 0,\n SUB\n };\n \n public:\n try_combine_inc_visitor(ptrdiff_t offset, bf_value val, bool isAdd) :\n next_off(offset), next_val(val), isAdd(isAdd) {}\n \n bf_value new_value() {\n return new_val;\n }\n \n node_type type() {\n return type;\n }\n \n status visit(add &node) {\n if (node.offset() != next_off) {\n return BREAK;\n }\n new_val = node.value();\n isAdd ? new_val += next_val : new_val -= next_val;\n type = ADD;\n return CONTINUE;\n }\n \n status visit(const add &node) {\n if (node.offset() != next_off) {\n return BREAK;\n }\n new_val = node.value();\n isAdd ? new_val += next_val : new_val -= next_val;\n type = ADD;\n return CONTINUE;\n }\n \n status visit(sub &node) {\n if (node.offset() != next_off) {\n return BREAK;\n }\n new_val = node.value();\n isAdd ? new_val -= next_val : new_val += next_val;\n type = SUB;\n return CONTINUE;\n }\n \n status visit(const sub &node) {\n if (node.offset() != next_off) {\n return BREAK;\n }\n new_val = node.value();\n isAdd ? new_val -= next_val : new_val += next_val;\n type = SUB;\n return CONTINUE;\n }\n \n private:\n bool isAdd;\n ptrdiff_t next_off;\n bf_value next_val;\n bf_value new_val;\n node_type type;\n };\n\n};\n\n}\n}\n\n#endif \/* !BFC_COMBINE_INC_VISITOR_HPP *\/\n<|endoftext|>"} {"text":"<commit_before>\/* \n * jcom.push (previously names tl.push)\n * By Trond Lossius, Copyright 2011\n * \n * Simple physical modelling: Push an object about within a confined space\n * Can be used for e.g. trajectories\n *\n * License: This code is licensed under the terms of the \"New BSD License\"\n * http:\/\/creativecommons.org\/licenses\/BSD\/\n *\/\n\t\n\n\/*\n\t<---MAXREF\n\t\n\t\t\/maxref\/object\/name\n\t\t\tjcom.push\n\n\t\t\/maxref\/object\/digest\n\t\t\tCalculate difference between incomming numbers\n\n\t\t\/maxref\/object\/description\n\t\t\t<o>jcom.push<\/o> calculates the difference between the last incomming value x[n]\n\t\t\tand the previous value received:<br\/>\n\t\t\tpush = x[n]-x[n-1] \n\n\n\n\t\t\/maxref\/metadata\/author\n\t\t\tTrond Lossius\n\n\t\t\/maxref\/metadata\/tag\n\t\t\tJamoma Max Math\n\n\n\n\t\t\/maxref\/inletlist\/0\n\t\t\tCalculate Difference, int, float\n\n\t\t\/maxref\/outletlist\/0\n\t\t\tDelta Value\n\n\t\t\/maxref\/outletlist\/1\t\t\n\t\t\tDumpout\n\n\n\n\t\t\/maxref\/argument\/\n\t\t\tNone\n\n\n\n\t\t\/maxref\/message\/float\n\t\t\tCaculate difference using between this and the previous number received.\n\n\t\t\/maxref\/message\/int\n\t\t\tConverted to float\n\n\n\t\t\n\t\t\/maxref\/example\/image\t\n\t\t\tjcom.push.gif\n\t\t\t\n\t\t\/maxref\/example\/caption\n\t\t\tCalculate difference between the last two numbers received.\n\n\n\t\t\n\t\t\/maxref\/seealso\/object\/name\n\t\t\tjcom.push2\n\t\t\n\t\t\/maxref\/seealso\/object\/description\n\t\t\tCalculate the 2nd order difference of incomming numbers.\n\t\t\n\t\t\/maxref\/seealso\/object\/name\n\t\t\tjcom.velocity\n\n\t\t\/maxref\/seealso\/object\/description\n\t\t\tCalculate velocity (rate of change per second) for incomming values.\t\t\n\t\t\n\tMAXREF--->\n*\/\n\n#include \"Jamoma.h\"\n\n#define nonzero(x)\t\t\t\t((x > 0) ? x : 1.)\n#define MAXDIMENSIONS\t\t\t10\n\ntypedef struct _push{\t\t\t\t\t\t\t\t\/\/\/< Data structure for this object \n\tt_object\tob;\t\t\t\t\t\t\t\t\t\/\/\/< Must always be the first field; used by Max\n\tfloat\t\tpreviousPosition[MAXDIMENSIONS];\t\/\/\/< The previous position\n\tfloat\t\tpreviousVelocity[MAXDIMENSIONS];\t\/\/\/< The previous velocity\n\tfloat\t\tattrFriction;\t\t\t\t\t\t\/\/\/< Friction coefficient\n\tint\t\t\tattrDimensions;\t\t\t\t\t\t\/\/\/< The number of dimensions used\n\tfloat\t\tattrSize[MAXDIMENSIONS];\t\t\t\/\/\/< Room size, defined individually for each dimension\n\tfloat\t\tforce[MAXDIMENSIONS];\t\t\t\t\/\/\/< Force applied on the object\n\tvoid\t\t*outlet;\t\t\t\t\t\t\t\/\/\/< Pointer to outlet. Need one for each outlet\n} t_push;\n\n\/\/ Prototypes for methods: need a method for each incoming message\nvoid *push_new(t_symbol *msg, long argc, t_atom *argv);\nvoid push_bang(t_push *x);\nvoid push_force(t_push *x, t_symbol *s, long argc, t_atom *argv);\nvoid push_clear(t_push *x);\nvoid push_assist(t_push *x, void *b, long msg, long arg, char *dst);\nt_max_err push_attr_setdimensions(t_push *x, void *attr, long argc, t_atom *argv);\nt_max_err push_attr_setfriction(t_push *x, void *attr, long argc, t_atom *argv);\nt_max_err push_attr_setsize(t_push *x, void *attr, long argc, t_atom *argv);\nt_max_err push_attr_getsize(t_push *x, void *attr, long *argc, t_atom **argv);\n\n\n\/\/ Globals\nt_class\t\t*this_class;\t\t\t\t\/\/ Required. Global pointing to this class \n\n\n\n\/************************************************************************************\/\n\/\/ Main() Function\n\nint JAMOMA_EXPORT_MAXOBJ main(void)\n{\t\n\tt_class *c;\n\t\n\tjamoma_init();\n\tcommon_symbols_init();\n\n\t\/\/ Define our class\n\tc = class_new(\"jcom.push\",(method)push_new, (method)0L, sizeof(t_push), (method)0L, A_GIMME, 0);\t\t\t\n\n\t\/\/ Make methods accessible for our class: \n\tclass_addmethod(c, (method)push_bang,\t\t\t\t\"bang\",\t\tA_CANT,\t\t0);\n\tclass_addmethod(c, (method)push_force,\t\t\t\t\"force\",\tA_GIMME,\t0);\n\tclass_addmethod(c, (method)push_clear,\t\t\t\t\"clear\",\t0);\n\tclass_addmethod(c, (method)push_assist, \t\t\t\"assist\",\tA_CANT,\t\t0); \n\tclass_addmethod(c, (method)object_obex_dumpout, \t\"dumpout\",\tA_CANT,\t\t0);\n\n\tCLASS_ATTR_FLOAT(c,\t\t\"friction\",\t\t\t0,\t\tt_push,\tattrFriction);\n\tCLASS_ATTR_ACCESSORS(c,\t\"friction\",\t\t\tNULL,\tpush_attr_setfriction);\n\t\n\t\/\/ Add attributes to our class:\t\n\tCLASS_ATTR_LONG(c,\t\t\"dimensions\",\t\t0,\t\tt_push,\tattrDimensions);\n\tCLASS_ATTR_ACCESSORS(c,\t\"dimensions\",\t\tNULL,\tpush_attr_setdimensions);\n\t\n\tCLASS_ATTR_ATOM(c,\t\t\"size\",\t\t\t\t0,\t\tt_push, attrSize);\n\tCLASS_ATTR_ACCESSORS(c,\t\"size\",\t\tpush_attr_getsize,\tpush_attr_setsize);\n\t\n\t\/\/ Finalize our class\n\tclass_register(CLASS_BOX, c);\n\tthis_class = c;\n\treturn 0;\n}\n\n#pragma mark -\n#pragma mark Object life\n\/************************************************************************************\/\n\/\/ Object Life\n\nvoid *push_new(t_symbol *msg, long argc, t_atom *argv)\n{\n\tt_push *x;\n\tint i;\n\t\n\tx = (t_push *)object_alloc(this_class);\t\/\/ create the new instance and return a pointer to it\n\tif (x) {\n\t\t\/\/ create inlets and outlets\t\t\n \tobject_obex_store((void *)x, _sym_dumpout, (object *)outlet_new(x,NULL));\t\/\/ dumpout\n\t\tx->outlet = floatout(x);\t\t\t\/\/ velocity\n\t\tx->attrDimensions = 3;\n\t\tx->attrFriction = 0.1;\n\t\tfor (i=0; i<MAXDIMENSIONS; i++)\n\t\t\tx->attrSize[i] = 40.0;\t\t\t\/\/ This is the same default as for ViMiC\n\t\tpush_clear(x);\t\t\t\t\t\t\/\/ initilaize instance\n\t\tattr_args_process(x, argc, argv);\t\/\/ handle attribute args\n\n\t}\n\treturn (x);\n}\n\n\n\/************************************************************************************\/\n\/\/ Methods bound to attributes\n#pragma mark -\n#pragma mark attribute accessors\n\n\n\/\/ ATTRIBUTE: dimensions\nt_max_err push_attr_setdimensions(t_push *x, void *attr, long argc, t_atom *argv)\n{\n\tlong n;\n\t\n\tif (argc && argv) {\n\t\tn = atom_getlong(argv);\n\t\tif (n<1) n = 1;\n\t\tif (n>MAXDIMENSIONS) n = MAXDIMENSIONS;\n\t\tx->attrDimensions = n;\n\t}\n\tpush_clear(x);\n\treturn MAX_ERR_NONE;\n}\n\n\n\/\/ ATTRIBUTE: dimensions (1-3)\nt_max_err push_attr_setfriction(t_push *x, void *attr, long argc, t_atom *argv)\n{\n\tfloat f;\n\t\n\tif (argc && argv) {\n\t\tf = atom_getfloat(argv);\n\t\tif (f<=0.0 || f>=1.0) {\n\t\t\terror(\"Invalid argument for friction. Must be in the range (0, 1)\");\n\t\t\treturn MAX_ERR_NONE;\n\t\t}\n\t\tx->attrFriction = f;\n\t}\n\treturn MAX_ERR_NONE;\n}\n\n\nt_max_err push_attr_setsize(t_push *x, void *attr, long argc, t_atom *argv)\n{\n\tint i;\n\tfloat f;\n\t\n\tif ((argc==x->attrDimensions) && argv) {\n\t\tfor (i=0; i<x->attrDimensions; i++) {\n\t\t\tf = atom_getfloat(argv);\n\t\t\tif (f>0.0) {\n\t\t\t\tx->attrSize[i] = f;\n\t\t\t\targv++;\n\t\t\t}\n\t\t\telse \n\t\t\t\tpost(\"jcom.push: Ignored faulty value for size\");\n\t\t}\n\t}\n\treturn MAX_ERR_NONE;\n}\n\nt_max_err push_attr_getsize(t_push *x, void *attr, long *argc, t_atom **argv)\n{\n\tint i;\n\t\n\t*argc = x->attrDimensions; \n\t*argv = (t_atom*)sysmem_newptr((sizeof(t_atom))*x->attrDimensions);\n\tfor (i=0; i<x->attrDimensions; i++) {\n\t\tatom_setfloat(*argv+i, x->attrSize[i]);\n\t}\n\t\t\n\treturn MAX_ERR_NONE;\n\t\/\/ TODO: We need to free the memory assigned for argv\n}\n\n\n#pragma mark -\n#pragma mark methods\n\/************************************************************************************\/\n\/\/ Methods bound to input\/inlets\n\n\n\/\/ BANG input\nvoid push_bang(t_push *x)\n{\n\tint i;\n\tfloat position[MAXDIMENSIONS];\n\tt_atom a[MAXDIMENSIONS];\n\t\n\tfor (i=0; i<x->attrDimensions; i++) {\n\t\tposition[i] = x->previousPosition[i] + (1.0-x->attrFriction)*x->previousVelocity[i] + x->force[i];\n\t\tx->previousVelocity[i] = position[i] - x->previousPosition[i];\n\t\tx->previousPosition[i] = position[i];\n\t\tatom_setfloat(&a[i], position[i]);\n\t\tx->force[i] = 0; \t\t\/\/ Force is reset to zero when it has been applied\n\t}\n\toutlet_anything(x->outlet, _sym_list, x->attrDimensions, a);\n}\n\n\n\/\/ FORCE input\nvoid push_force(t_push *x, t_symbol *s, long argc, t_atom *argv)\n{\n\tint i;\n\t\n\tif (argc==x->attrDimensions) {\n\t\tfor (i=0; i<x->attrDimensions; i++) {\n\t\t\tx->force[i] = atom_getfloat(argv);\n\t\t\targv++;\n\t\t}\n\t}\n\telse {\n\t\tpost(\"jcom.push: force vector has wrong dimension\");\n\t\treturn;\n\t}\n}\n\n\n\/\/ CLEAR input\nvoid push_clear(t_push *x)\n{\n\tint i;\n\t\n\tfor (i=0; i< x->attrDimensions; i++) {\n\t\tx->previousPosition[i] = 0.0;\n\t\tx->previousVelocity[i] = 0.0;\n\t\tx->force[i] = 0.0;\n\t}\n\tpush_bang(x);\n}\n\n\n\/\/ Method for Assistance Messages\nvoid push_assist(t_push *x, void *b, long msg, long arg, char *dst)\t\/\/ Display assistance messages\n{\n\tif (msg==1)\n\t{ \n\t\tswitch(arg)\n\t\t{\n\t\t\tcase 0:\n\t\t\t\tstrcpy(dst, \"(list) force applied to object\");\n\t\t\t\tbreak;\t\n\t\t}\n\t}\n\telse if (msg==2)\n\t{\n\t\tswitch(arg)\n\t\t{\n\t\t\tcase 0:\n\t\t\t\tstrcpy(dst, \"(list) resulting position of object\");\n\t\t\t\tbreak;\n\t\t\tcase 1:\n\t\t\t\tstrcpy(dst, \"dumpout\");\n\t\t\t\tbreak;\n\t\t}\n\t}\n}\n<commit_msg>Adding boundary mode, currently crashing if opening the inspector<commit_after>\/* \n * jcom.push (previously names tl.push)\n * By Trond Lossius, Copyright 2011\n * \n * Simple physical modelling: Push an object about within a confined space\n * Can be used for e.g. trajectories\n *\n * License: This code is licensed under the terms of the \"New BSD License\"\n * http:\/\/creativecommons.org\/licenses\/BSD\/\n *\/\n\t\n\n\/*\n\t<---MAXREF\n\t\n\t\t\/maxref\/object\/name\n\t\t\tjcom.push\n\n\t\t\/maxref\/object\/digest\n\t\t\tCalculate difference between incomming numbers\n\n\t\t\/maxref\/object\/description\n\t\t\t<o>jcom.push<\/o> calculates the difference between the last incomming value x[n]\n\t\t\tand the previous value received:<br\/>\n\t\t\tpush = x[n]-x[n-1] \n\n\n\n\t\t\/maxref\/metadata\/author\n\t\t\tTrond Lossius\n\n\t\t\/maxref\/metadata\/tag\n\t\t\tJamoma Max Math\n\n\n\n\t\t\/maxref\/inletlist\/0\n\t\t\tCalculate Difference, int, float\n\n\t\t\/maxref\/outletlist\/0\n\t\t\tDelta Value\n\n\t\t\/maxref\/outletlist\/1\t\t\n\t\t\tDumpout\n\n\n\n\t\t\/maxref\/argument\/\n\t\t\tNone\n\n\n\n\t\t\/maxref\/message\/float\n\t\t\tCaculate difference using between this and the previous number received.\n\n\t\t\/maxref\/message\/int\n\t\t\tConverted to float\n\n\n\t\t\n\t\t\/maxref\/example\/image\t\n\t\t\tjcom.push.gif\n\t\t\t\n\t\t\/maxref\/example\/caption\n\t\t\tCalculate difference between the last two numbers received.\n\n\n\t\t\n\t\t\/maxref\/seealso\/object\/name\n\t\t\tjcom.push2\n\t\t\n\t\t\/maxref\/seealso\/object\/description\n\t\t\tCalculate the 2nd order difference of incomming numbers.\n\t\t\n\t\t\/maxref\/seealso\/object\/name\n\t\t\tjcom.velocity\n\n\t\t\/maxref\/seealso\/object\/description\n\t\t\tCalculate velocity (rate of change per second) for incomming values.\t\t\n\t\t\n\tMAXREF--->\n*\/\n\n#include \"Jamoma.h\"\n#include \"TTAudioObject.h\"\t\/\/ use the ttblue clipping functions\n\n\n#define nonzero(x)\t\t\t\t((x > 0) ? x : 1.)\n#define MAXDIMENSIONS\t\t\t10\n\nt_symbol*\t\tps_clip;\n\ntypedef struct _push{\t\t\t\t\t\t\t\t\/\/\/< Data structure for this object \n\tt_object\tob;\t\t\t\t\t\t\t\t\t\/\/\/< Must always be the first field; used by Max\n\tfloat\t\tpreviousPosition[MAXDIMENSIONS];\t\/\/\/< The previous position\n\tfloat\t\tpreviousVelocity[MAXDIMENSIONS];\t\/\/\/< The previous velocity\n\tfloat\t\tattrFriction;\t\t\t\t\t\t\/\/\/< Friction coefficient\n\tint\t\t\tattrDimensions;\t\t\t\t\t\t\/\/\/< The number of dimensions used\n\tfloat\t\tattrSize[MAXDIMENSIONS];\t\t\t\/\/\/< Room size, defined individually for each dimension\n\tt_symbol* attrBoundaryMode;\t\t\t\t\t\/\/\/< Boundary mode\n\tfloat\t\tforce[MAXDIMENSIONS];\t\t\t\t\/\/\/< Force applied on the object\n\tvoid\t\t*outlet;\t\t\t\t\t\t\t\/\/\/< Pointer to outlet. Need one for each outlet\n} t_push;\n\n\/\/ Prototypes for methods: need a method for each incoming message\nvoid *push_new(t_symbol *msg, long argc, t_atom *argv);\nvoid push_bang(t_push *x);\nvoid push_force(t_push *x, t_symbol *s, long argc, t_atom *argv);\nvoid push_clear(t_push *x);\nvoid push_assist(t_push *x, void *b, long msg, long arg, char *dst);\nt_max_err push_attr_setdimensions(t_push *x, void *attr, long argc, t_atom *argv);\nt_max_err push_attr_setfriction(t_push *x, void *attr, long argc, t_atom *argv);\nt_max_err push_attr_setsize(t_push *x, void *attr, long argc, t_atom *argv);\nt_max_err push_attr_getsize(t_push *x, void *attr, long *argc, t_atom **argv);\n\n\n\/\/ Globals\nt_class\t\t*this_class;\t\t\t\t\/\/ Required. Global pointing to this class \n\n\n\n\/************************************************************************************\/\n\/\/ Main() Function\n\nint JAMOMA_EXPORT_MAXOBJ main(void)\n{\t\n\tt_class *c;\n\t\n\tjamoma_init();\n\tcommon_symbols_init();\n\tps_clip = gensym(\"clip\");\n\n\t\/\/ Define our class\n\tc = class_new(\"jcom.push\",(method)push_new, (method)0L, sizeof(t_push), (method)0L, A_GIMME, 0);\t\t\t\n\n\t\/\/ Make methods accessible for our class: \n\tclass_addmethod(c, (method)push_bang,\t\t\t\t\"bang\",\t\tA_CANT,\t\t0);\n\tclass_addmethod(c, (method)push_force,\t\t\t\t\"force\",\tA_GIMME,\t0);\n\tclass_addmethod(c, (method)push_clear,\t\t\t\t\"clear\",\t0);\n\tclass_addmethod(c, (method)push_assist, \t\t\t\"assist\",\tA_CANT,\t\t0); \n\tclass_addmethod(c, (method)object_obex_dumpout, \t\"dumpout\",\tA_CANT,\t\t0);\n\n\tCLASS_ATTR_FLOAT(c,\t\t\"friction\",\t\t\t0,\t\tt_push,\tattrFriction);\n\tCLASS_ATTR_ACCESSORS(c,\t\"friction\",\t\t\tNULL,\tpush_attr_setfriction);\n\t\n\t\/\/ Add attributes to our class:\t\n\tCLASS_ATTR_LONG(c,\t\t\"dimensions\",\t\t0,\t\tt_push,\tattrDimensions);\n\tCLASS_ATTR_ACCESSORS(c,\t\"dimensions\",\t\tNULL,\tpush_attr_setdimensions);\n\t\n\tCLASS_ATTR_ATOM(c,\t\t\"size\",\t\t\t\t0,\t\tt_push, attrSize);\n\tCLASS_ATTR_ACCESSORS(c,\t\"size\",\t\tpush_attr_getsize,\tpush_attr_setsize);\n\n\t\/\/ ATTRIBUTE: boundary mode - options are none, clip, wrap, fold, repel\n\tjamoma_class_attr_new(c, \t\t\"boundary\",\t \t_sym_symbol, (method)jcom_core_attr_setclipmode, (method)jcom_core_attr_getclipmode);\n\tCLASS_ATTR_ENUM(c,\t\t\t\t\"boundary\",\t\t0,\t(char*)\"none clip bounce fold repel\");\n\t\n\t\/\/ Finalize our class\n\tclass_register(CLASS_BOX, c);\n\tthis_class = c;\n\treturn 0;\n}\n\n#pragma mark -\n#pragma mark Object life\n\/************************************************************************************\/\n\/\/ Object Life\n\nvoid *push_new(t_symbol *msg, long argc, t_atom *argv)\n{\n\tt_push *x;\n\tint i;\n\t\n\tx = (t_push *)object_alloc(this_class);\t\/\/ create the new instance and return a pointer to it\n\tif (x) {\n\t\t\/\/ create inlets and outlets\t\t\n \tobject_obex_store((void *)x, _sym_dumpout, (object *)outlet_new(x,NULL));\t\/\/ dumpout\n\t\tx->outlet = floatout(x);\t\t\t\/\/ velocity\n\t\tx->attrDimensions = 3;\n\t\tx->attrFriction = 0.1;\n\t\tfor (i=0; i<MAXDIMENSIONS; i++)\n\t\t\tx->attrSize[i] = 40.0;\t\t\t\/\/ This is the same default as for ViMiC\n\t\tpush_clear(x);\t\t\t\t\t\t\/\/ initilaize instance\n\t\tattr_args_process(x, argc, argv);\t\/\/ handle attribute args\n\n\t}\n\treturn (x);\n}\n\n\n\/************************************************************************************\/\n\/\/ Methods bound to attributes\n#pragma mark -\n#pragma mark attribute accessors\n\n\n\/\/ ATTRIBUTE: dimensions\nt_max_err push_attr_setdimensions(t_push *x, void *attr, long argc, t_atom *argv)\n{\n\tlong n;\n\t\n\tif (argc && argv) {\n\t\tn = atom_getlong(argv);\n\t\tif (n<1) n = 1;\n\t\tif (n>MAXDIMENSIONS) n = MAXDIMENSIONS;\n\t\tx->attrDimensions = n;\n\t}\n\tpush_clear(x);\n\treturn MAX_ERR_NONE;\n}\n\n\n\/\/ ATTRIBUTE: dimensions (1-3)\nt_max_err push_attr_setfriction(t_push *x, void *attr, long argc, t_atom *argv)\n{\n\tfloat f;\n\t\n\tif (argc && argv) {\n\t\tf = atom_getfloat(argv);\n\t\tif (f<=0.0 || f>=1.0) {\n\t\t\terror(\"Invalid argument for friction. Must be in the range (0, 1)\");\n\t\t\treturn MAX_ERR_NONE;\n\t\t}\n\t\tx->attrFriction = f;\n\t}\n\treturn MAX_ERR_NONE;\n}\n\n\nt_max_err push_attr_setsize(t_push *x, void *attr, long argc, t_atom *argv)\n{\n\tint i;\n\tfloat f;\n\t\n\tif ((argc==x->attrDimensions) && argv) {\n\t\tfor (i=0; i<x->attrDimensions; i++) {\n\t\t\tf = atom_getfloat(argv);\n\t\t\tif (f>0.0) {\n\t\t\t\tx->attrSize[i] = f;\n\t\t\t\targv++;\n\t\t\t}\n\t\t\telse \n\t\t\t\tpost(\"jcom.push: Ignored faulty value for size\");\n\t\t}\n\t}\n\treturn MAX_ERR_NONE;\n}\n\nt_max_err push_attr_getsize(t_push *x, void *attr, long *argc, t_atom **argv)\n{\n\tint i;\n\t\n\t*argc = x->attrDimensions; \n\t*argv = (t_atom*)sysmem_newptr((sizeof(t_atom))*x->attrDimensions);\n\tfor (i=0; i<x->attrDimensions; i++) {\n\t\tatom_setfloat(*argv+i, x->attrSize[i]);\n\t}\n\t\t\n\treturn MAX_ERR_NONE;\n\t\/\/ TODO: We need to free the memory assigned for argv\n}\n\n\n#pragma mark -\n#pragma mark methods\n\/************************************************************************************\/\n\/\/ Methods bound to input\/inlets\n\n\n\/\/ BANG input\nvoid push_bang(t_push *x)\n{\n\tint i;\n\tfloat position, rangeLow, rangeHigh;\n\tt_atom a[MAXDIMENSIONS];\n\t\n\tfor (i=0; i<x->attrDimensions; i++) {\n\t\tposition = x->previousPosition[i] + (1.0-x->attrFriction)*x->previousVelocity[i] + x->force[i];\n\n\t\tx->previousVelocity[i] = position - x->previousPosition[i];\n\t\t\n\t\trangeHigh = 0.5*x->attrSize[i];\n\t\trangeHigh = - rangeHigh;\n\t\tif (x->attrBoundaryMode == ps_clip)\n\t\t\tTTLimit(position, rangeLow, rangeHigh);\n\t\telse if (x->attrBoundaryMode == jps_wrap)\n\t\t\tposition = TTInfWrap(position, rangeLow, rangeHigh);\n\t\telse if (x->attrBoundaryMode == jps_fold)\n\t\t\tposition = TTFold(position, rangeLow, rangeHigh);\t\t\n\t\t\n\t\tx->previousPosition[i] = position;\n\t\t\n\n\t\t\n\t\tatom_setfloat(&a[i], position);\n\t\tx->force[i] = 0; \t\t\/\/ Force is reset to zero when it has been applied\n\t}\n\n\t\n\toutlet_anything(x->outlet, _sym_list, x->attrDimensions, a);\n}\n\n\n\/\/ FORCE input\nvoid push_force(t_push *x, t_symbol *s, long argc, t_atom *argv)\n{\n\tint i;\n\t\n\tif (argc==x->attrDimensions) {\n\t\tfor (i=0; i<x->attrDimensions; i++) {\n\t\t\tx->force[i] = atom_getfloat(argv);\n\t\t\targv++;\n\t\t}\n\t}\n\telse {\n\t\tpost(\"jcom.push: force vector has wrong dimension\");\n\t\treturn;\n\t}\n}\n\n\n\/\/ CLEAR input\nvoid push_clear(t_push *x)\n{\n\tint i;\n\t\n\tfor (i=0; i< x->attrDimensions; i++) {\n\t\tx->previousPosition[i] = 0.0;\n\t\tx->previousVelocity[i] = 0.0;\n\t\tx->force[i] = 0.0;\n\t}\n\tpush_bang(x);\n}\n\n\n\/\/ Method for Assistance Messages\nvoid push_assist(t_push *x, void *b, long msg, long arg, char *dst)\t\/\/ Display assistance messages\n{\n\tif (msg==1)\n\t{ \n\t\tswitch(arg)\n\t\t{\n\t\t\tcase 0:\n\t\t\t\tstrcpy(dst, \"(list) force applied to object\");\n\t\t\t\tbreak;\t\n\t\t}\n\t}\n\telse if (msg==2)\n\t{\n\t\tswitch(arg)\n\t\t{\n\t\t\tcase 0:\n\t\t\t\tstrcpy(dst, \"(list) resulting position of object\");\n\t\t\t\tbreak;\n\t\t\tcase 1:\n\t\t\t\tstrcpy(dst, \"dumpout\");\n\t\t\t\tbreak;\n\t\t}\n\t}\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ ========================================================================================\n\/\/ ApproxMVBB\n\/\/ Copyright (C) 2014 by Gabriel Nützi <nuetzig (at) imes (d0t) mavt (d0t) ethz (døt) ch>\n\/\/\n\/\/ This Source Code Form is subject to the terms of the Mozilla Public\n\/\/ License, v. 2.0. If a copy of the MPL was not distributed with this\n\/\/ file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n\/\/ ========================================================================================\n\n#ifndef ApproxMVBB_Common_MyMatrixTypeDefs_hpp\n#define ApproxMVBB_Common_MyMatrixTypeDefs_hpp\n\n#include \"ApproxMVBB\/Common\/Platform.hpp\"\n\n\/\/#define EIGEN_DONT_VECTORIZE\n\/\/#define EIGEN_DISABLE_UNALIGNED_ARRAY_ASSERT\n\n#include <Eigen\/Dense>\n\nnamespace ApproxMVBB{\n\n\/\/ ================================================================================================\n\/** @brief This\n*\tThese are some small matrix definitions.\n*\/\n\nnamespace MyMatrix {\n\n template<typename Scalar>\n using Matrix44 = Eigen::Matrix<Scalar, 4, 4>;\n template<typename Scalar>\n using Matrix43 = Eigen::Matrix<Scalar, 4, 3>;\n template<typename Scalar>\n using Matrix34 = Eigen::Matrix<Scalar, 3, 4>;\n template<typename Scalar>\n using Matrix33 = Eigen::Matrix<Scalar, 3, 3>;\n template<typename Scalar>\n using Matrix32 = Eigen::Matrix<Scalar, 3, 2>;\n template<typename Scalar>\n using Matrix23 = Eigen::Matrix<Scalar, 2, 3>;\n template<typename Scalar>\n using Matrix22 = Eigen::Matrix<Scalar, 2, 2>;\n template<typename Scalar>\n using Vector3 = Eigen::Matrix<Scalar, 3, 1>;\n template<typename Scalar>\n using Vector2 = Eigen::Matrix<Scalar, 2, 1>;\n\n template<typename Scalar>\n using Quaternion = Eigen::Quaternion<Scalar>;\n template<typename Scalar>\n using AngleAxis = Eigen::AngleAxis<Scalar>;\n\n template<typename Scalar>\n using Vector4 = Eigen::Matrix<Scalar, 4, 1>;\n template<typename Scalar>\n using Vector6 = Eigen::Matrix<Scalar, 6, 1>;\n template<typename Scalar>\n using VectorDyn = Eigen::Matrix<Scalar, Eigen::Dynamic , 1 >;\n\n\n template<typename Scalar>\n using MatrixDynDyn = Eigen::Matrix<Scalar, Eigen::Dynamic , Eigen::Dynamic >;\n template<typename Scalar>\n using MatrixDiagDyn = Eigen::DiagonalMatrix<Scalar, Eigen::Dynamic >;\n template<typename Scalar>\n using MatrixDynDynRow = Eigen::Matrix<Scalar, Eigen::Dynamic , Eigen::Dynamic, Eigen::RowMajor>;\n\n template<typename Scalar, int M>\n using MatrixStatDyn = Eigen::Matrix<Scalar, M, Eigen::Dynamic >;\n template<typename Scalar, int N>\n using MatrixDynStat = Eigen::Matrix<Scalar, Eigen::Dynamic, N >;\n template<typename Scalar, int M, int N>\n using MatrixStatStat = Eigen::Matrix<Scalar, M, N >;\n template<typename Scalar, int M>\n using VectorStat = Eigen::Matrix<Scalar, M, 1 >;\n\n\n template<typename Scalar>\n using AffineTrafo = Eigen::Transform<Scalar,3,Eigen::TransformTraits::Affine>;\n template<typename Scalar>\n using AffineTrafo2d = Eigen::Transform<Scalar,2,Eigen::TransformTraits::Affine>;\n\n template<typename Scalar, int M>\n using ArrayStatDyn = Eigen::Array<Scalar, M, Eigen::Dynamic >;\n template<typename Scalar, int N>\n using ArrayDynStat = Eigen::Array<Scalar, Eigen::Dynamic, N >;\n template<typename Scalar, int M, int N>\n using ArrayStatStat = Eigen::Array<Scalar, M, N >;\n template<typename Scalar, int M>\n using ArrayStat = Eigen::Array<Scalar, M,1>;\n\n template<typename Scalar>\n using Array3 = Eigen::Array<Scalar, 3, 1>;\n template<typename Scalar>\n using Array2 = Eigen::Array<Scalar, 2, 1>;\n\n}\n\nnamespace MyMatrix{\n\n template<typename Derived> using MatrixBase = Eigen::MatrixBase<Derived>;\n template<typename Derived> using ArrayBase = Eigen::ArrayBase<Derived>;\n\n template<typename Derived> using VectorBDyn = Eigen::VectorBlock<Derived,Eigen::Dynamic>;\n template<typename Derived, unsigned int M> using VectorBStat = Eigen::VectorBlock<Derived,M>;\n\n template<typename Derived> using MatrixBDynDyn = Eigen::Block<Derived>;\n template<typename Derived, unsigned int M> using MatrixBStatDyn = Eigen::Block<Derived,M, Eigen::Dynamic>;\n template<typename Derived, unsigned int N> using MatrixBDynStat = Eigen::Block<Derived,Eigen::Dynamic,N>;\n\n template<typename EigenType> using MatrixRef = Eigen::Ref<EigenType>;\n\n template<typename EigenType> using MatrixMap = Eigen::Map<EigenType>;\n\n}\n\n\nstruct APPROXMVBB_EXPORT MyMatrixIOFormat {\n static const Eigen::IOFormat Matlab;\n static const Eigen::IOFormat CommaSep;\n static const Eigen::IOFormat SpaceSep;\n};\n\n}\n\n\n#define ApproxMVBB_DEFINE_MATRIX_SPECIALTYPES \\\n template<typename Derived> using MatrixBase = ApproxMVBB::MyMatrix::MatrixBase<Derived>; \\\n template<typename Derived> using ArrayBase = ApproxMVBB::MyMatrix::ArrayBase<Derived>; \\\n \\\n template<typename Derived> using VectorBDyn = ApproxMVBB::MyMatrix::VectorBDyn<Derived>; \\\n template<typename Derived,unsigned int M> using VectorBStat = ApproxMVBB::MyMatrix::VectorBStat<Derived,M>; \\\n \\\n template<typename Derived> using MatrixBDynDyn = ApproxMVBB::MyMatrix::MatrixBDynDyn<Derived>; \\\n template<typename Derived, unsigned int N> using MatrixBDynStat = ApproxMVBB::MyMatrix::MatrixBDynStat<Derived,N>; \\\n template<typename Derived, unsigned int M> using MatrixBStatDyn = ApproxMVBB::MyMatrix::MatrixBStatDyn<Derived,M>; \\\n \\\n template<typename EigenType> using MatrixRef = ApproxMVBB::MyMatrix::MatrixRef< EigenType >; \\\n template<typename EigenType> using MatrixMap = ApproxMVBB::MyMatrix::MatrixMap< EigenType >; \\\n\n\/**\n* @brief This macro is used to typedef all custom matrix types which have nothing to do with the system.\n*\/\n#define ApproxMVBB_DEFINE_MATRIX_TYPES_OF( _PREC_ ) \\\n using Matrix44 = ApproxMVBB::MyMatrix::Matrix44< _PREC_ >; \\\n using Matrix33 = ApproxMVBB::MyMatrix::Matrix33< _PREC_ >; \\\n using Matrix22 = ApproxMVBB::MyMatrix::Matrix22< _PREC_ >; \\\n using Matrix32 = ApproxMVBB::MyMatrix::Matrix32< _PREC_ >; \\\n using Matrix23 = ApproxMVBB::MyMatrix::Matrix23< _PREC_ >; \\\n using Matrix43 = ApproxMVBB::MyMatrix::Matrix43< _PREC_ >; \\\n using Matrix34 = ApproxMVBB::MyMatrix::Matrix34< _PREC_ >; \\\n using Vector3 = ApproxMVBB::MyMatrix::Vector3< _PREC_ >; \\\n using Vector2 = ApproxMVBB::MyMatrix::Vector2< _PREC_ >; \\\n using Vector4 = ApproxMVBB::MyMatrix::Vector4< _PREC_ >; \\\n using Vector6 = ApproxMVBB::MyMatrix::Vector6< _PREC_ >; \\\n using Quaternion = ApproxMVBB::MyMatrix::Quaternion< _PREC_ >; \\\n using AngleAxis = ApproxMVBB::MyMatrix::AngleAxis< _PREC_ >; \\\n using VectorDyn = ApproxMVBB::MyMatrix::VectorDyn< _PREC_ >; \\\n using MatrixDynDyn = ApproxMVBB::MyMatrix::MatrixDynDyn< _PREC_ >; \\\n using MatrixDiagDyn = ApproxMVBB::MyMatrix::MatrixDiagDyn< _PREC_ >; \\\n using MatrixDynDynRow = ApproxMVBB::MyMatrix::MatrixDynDynRow< _PREC_ >; \\\n \\\n template<unsigned int M> using MatrixStatDyn = ApproxMVBB::MyMatrix::MatrixStatDyn< _PREC_, M>; \\\n template<unsigned int N> using MatrixDynStat = ApproxMVBB::MyMatrix::MatrixDynStat< _PREC_, N>; \\\n template<unsigned int M,unsigned int N> using MatrixStatStat = ApproxMVBB::MyMatrix::MatrixStatStat< _PREC_, M,N>; \\\n template<unsigned int M> using VectorStat = ApproxMVBB::MyMatrix::VectorStat< _PREC_, M>; \\\n \\\n using AffineTrafo = ApproxMVBB::MyMatrix::AffineTrafo< _PREC_ >; \\\n using AffineTrafo2d = ApproxMVBB::MyMatrix::AffineTrafo2d< _PREC_ >; \\\n \\\n template<unsigned int M> using ArrayStatDyn = ApproxMVBB::MyMatrix::ArrayStatDyn< _PREC_, M>; \\\n template<unsigned int N> using ArrayDynStat = ApproxMVBB::MyMatrix::ArrayDynStat< _PREC_, N>; \\\n template<unsigned int M,unsigned int N> using ArrayStatStat = ApproxMVBB::MyMatrix::ArrayStatStat< _PREC_, M,N>; \\\n template<unsigned int M> using ArrayStat = ApproxMVBB::MyMatrix::ArrayStat< _PREC_, M>; \\\n using Array3 = ApproxMVBB::MyMatrix::Array3< _PREC_ >; \\\n using Array2 = ApproxMVBB::MyMatrix::Array2< _PREC_ >; \\\n \\\n ApproxMVBB_DEFINE_MATRIX_SPECIALTYPES\n\n#endif\n\n<commit_msg>corrected some template alias miss match in ApproxMVBB_DEFINE macros<commit_after>\/\/ ========================================================================================\n\/\/ ApproxMVBB\n\/\/ Copyright (C) 2014 by Gabriel Nützi <nuetzig (at) imes (d0t) mavt (d0t) ethz (døt) ch>\n\/\/\n\/\/ This Source Code Form is subject to the terms of the Mozilla Public\n\/\/ License, v. 2.0. If a copy of the MPL was not distributed with this\n\/\/ file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n\/\/ ========================================================================================\n\n#ifndef ApproxMVBB_Common_MyMatrixTypeDefs_hpp\n#define ApproxMVBB_Common_MyMatrixTypeDefs_hpp\n\n#include \"ApproxMVBB\/Common\/Platform.hpp\"\n\n\/\/#define EIGEN_DONT_VECTORIZE\n\/\/#define EIGEN_DISABLE_UNALIGNED_ARRAY_ASSERT\n\n#include <Eigen\/Dense>\n\nnamespace ApproxMVBB{\n\n\/\/ ================================================================================================\n\/** @brief This\n*\tThese are some small matrix definitions.\n*\/\n\nnamespace MyMatrix {\n\n template<typename Scalar>\n using Matrix44 = Eigen::Matrix<Scalar, 4, 4>;\n template<typename Scalar>\n using Matrix43 = Eigen::Matrix<Scalar, 4, 3>;\n template<typename Scalar>\n using Matrix34 = Eigen::Matrix<Scalar, 3, 4>;\n template<typename Scalar>\n using Matrix33 = Eigen::Matrix<Scalar, 3, 3>;\n template<typename Scalar>\n using Matrix32 = Eigen::Matrix<Scalar, 3, 2>;\n template<typename Scalar>\n using Matrix23 = Eigen::Matrix<Scalar, 2, 3>;\n template<typename Scalar>\n using Matrix22 = Eigen::Matrix<Scalar, 2, 2>;\n template<typename Scalar>\n using Vector3 = Eigen::Matrix<Scalar, 3, 1>;\n template<typename Scalar>\n using Vector2 = Eigen::Matrix<Scalar, 2, 1>;\n\n template<typename Scalar>\n using Quaternion = Eigen::Quaternion<Scalar>;\n template<typename Scalar>\n using AngleAxis = Eigen::AngleAxis<Scalar>;\n\n template<typename Scalar>\n using Vector4 = Eigen::Matrix<Scalar, 4, 1>;\n template<typename Scalar>\n using Vector6 = Eigen::Matrix<Scalar, 6, 1>;\n template<typename Scalar>\n using VectorDyn = Eigen::Matrix<Scalar, Eigen::Dynamic , 1 >;\n\n\n template<typename Scalar>\n using MatrixDynDyn = Eigen::Matrix<Scalar, Eigen::Dynamic , Eigen::Dynamic >;\n template<typename Scalar>\n using MatrixDiagDyn = Eigen::DiagonalMatrix<Scalar, Eigen::Dynamic >;\n template<typename Scalar>\n using MatrixDynDynRow = Eigen::Matrix<Scalar, Eigen::Dynamic , Eigen::Dynamic, Eigen::RowMajor>;\n\n template<typename Scalar, int M>\n using MatrixStatDyn = Eigen::Matrix<Scalar, M, Eigen::Dynamic >;\n template<typename Scalar, int N>\n using MatrixDynStat = Eigen::Matrix<Scalar, Eigen::Dynamic, N >;\n template<typename Scalar, int M, int N>\n using MatrixStatStat = Eigen::Matrix<Scalar, M, N >;\n template<typename Scalar, int M>\n using VectorStat = Eigen::Matrix<Scalar, M, 1 >;\n\n\n template<typename Scalar>\n using AffineTrafo = Eigen::Transform<Scalar,3,Eigen::TransformTraits::Affine>;\n template<typename Scalar>\n using AffineTrafo2d = Eigen::Transform<Scalar,2,Eigen::TransformTraits::Affine>;\n\n template<typename Scalar, int M>\n using ArrayStatDyn = Eigen::Array<Scalar, M, Eigen::Dynamic >;\n template<typename Scalar, int N>\n using ArrayDynStat = Eigen::Array<Scalar, Eigen::Dynamic, N >;\n template<typename Scalar, int M, int N>\n using ArrayStatStat = Eigen::Array<Scalar, M, N >;\n template<typename Scalar, int M>\n using ArrayStat = Eigen::Array<Scalar, M,1>;\n\n template<typename Scalar>\n using Array3 = Eigen::Array<Scalar, 3, 1>;\n template<typename Scalar>\n using Array2 = Eigen::Array<Scalar, 2, 1>;\n\n}\n\nnamespace MyMatrix{\n\n template<typename Derived> using MatrixBase = Eigen::MatrixBase<Derived>;\n template<typename Derived> using ArrayBase = Eigen::ArrayBase<Derived>;\n\n template<typename Derived> using VectorBDyn = Eigen::VectorBlock<Derived,Eigen::Dynamic>;\n template<typename Derived, unsigned int M> using VectorBStat = Eigen::VectorBlock<Derived,M>;\n\n template<typename Derived> using MatrixBDynDyn = Eigen::Block<Derived>;\n template<typename Derived, unsigned int M> using MatrixBStatDyn = Eigen::Block<Derived,M, Eigen::Dynamic>;\n template<typename Derived, unsigned int N> using MatrixBDynStat = Eigen::Block<Derived,Eigen::Dynamic,N>;\n\n template<typename EigenType> using MatrixRef = Eigen::Ref<EigenType>;\n\n template<typename EigenType> using MatrixMap = Eigen::Map<EigenType>;\n\n}\n\n\nstruct APPROXMVBB_EXPORT MyMatrixIOFormat {\n static const Eigen::IOFormat Matlab;\n static const Eigen::IOFormat CommaSep;\n static const Eigen::IOFormat SpaceSep;\n};\n\n}\n\n\n#define ApproxMVBB_DEFINE_MATRIX_SPECIALTYPES \\\n template<typename Derived> using MatrixBase = ApproxMVBB::MyMatrix::MatrixBase<Derived>; \\\n template<typename Derived> using ArrayBase = ApproxMVBB::MyMatrix::ArrayBase<Derived>; \\\n \\\n template<typename Derived> using VectorBDyn = ApproxMVBB::MyMatrix::VectorBDyn<Derived>; \\\n template<typename Derived,unsigned int M> using VectorBStat = ApproxMVBB::MyMatrix::VectorBStat<Derived,M>; \\\n \\\n template<typename Derived> using MatrixBDynDyn = ApproxMVBB::MyMatrix::MatrixBDynDyn<Derived>; \\\n template<typename Derived, unsigned int N> using MatrixBDynStat = ApproxMVBB::MyMatrix::MatrixBDynStat<Derived,N>; \\\n template<typename Derived, unsigned int M> using MatrixBStatDyn = ApproxMVBB::MyMatrix::MatrixBStatDyn<Derived,M>; \\\n \\\n template<typename EigenType> using MatrixRef = ApproxMVBB::MyMatrix::MatrixRef< EigenType >; \\\n template<typename EigenType> using MatrixMap = ApproxMVBB::MyMatrix::MatrixMap< EigenType >; \\\n\n\/**\n* @brief This macro is used to typedef all custom matrix types which have nothing to do with the system.\n*\/\n#define ApproxMVBB_DEFINE_MATRIX_TYPES_OF( _PREC_ ) \\\n using Matrix44 = ApproxMVBB::MyMatrix::Matrix44< _PREC_ >; \\\n using Matrix33 = ApproxMVBB::MyMatrix::Matrix33< _PREC_ >; \\\n using Matrix22 = ApproxMVBB::MyMatrix::Matrix22< _PREC_ >; \\\n using Matrix32 = ApproxMVBB::MyMatrix::Matrix32< _PREC_ >; \\\n using Matrix23 = ApproxMVBB::MyMatrix::Matrix23< _PREC_ >; \\\n using Matrix43 = ApproxMVBB::MyMatrix::Matrix43< _PREC_ >; \\\n using Matrix34 = ApproxMVBB::MyMatrix::Matrix34< _PREC_ >; \\\n using Vector3 = ApproxMVBB::MyMatrix::Vector3< _PREC_ >; \\\n using Vector2 = ApproxMVBB::MyMatrix::Vector2< _PREC_ >; \\\n using Vector4 = ApproxMVBB::MyMatrix::Vector4< _PREC_ >; \\\n using Vector6 = ApproxMVBB::MyMatrix::Vector6< _PREC_ >; \\\n using Quaternion = ApproxMVBB::MyMatrix::Quaternion< _PREC_ >; \\\n using AngleAxis = ApproxMVBB::MyMatrix::AngleAxis< _PREC_ >; \\\n using VectorDyn = ApproxMVBB::MyMatrix::VectorDyn< _PREC_ >; \\\n using MatrixDynDyn = ApproxMVBB::MyMatrix::MatrixDynDyn< _PREC_ >; \\\n using MatrixDiagDyn = ApproxMVBB::MyMatrix::MatrixDiagDyn< _PREC_ >; \\\n using MatrixDynDynRow = ApproxMVBB::MyMatrix::MatrixDynDynRow< _PREC_ >; \\\n \\\n template<int M> using MatrixStatDyn = ApproxMVBB::MyMatrix::MatrixStatDyn< _PREC_, M>; \\\n template<int N> using MatrixDynStat = ApproxMVBB::MyMatrix::MatrixDynStat< _PREC_, N>; \\\n template<int M, int N> using MatrixStatStat = ApproxMVBB::MyMatrix::MatrixStatStat< _PREC_, M,N>; \\\n template<int M> using VectorStat = ApproxMVBB::MyMatrix::VectorStat< _PREC_, M>; \\\n \\\n using AffineTrafo = ApproxMVBB::MyMatrix::AffineTrafo< _PREC_ >; \\\n using AffineTrafo2d = ApproxMVBB::MyMatrix::AffineTrafo2d< _PREC_ >; \\\n \\\n template<int M> using ArrayStatDyn = ApproxMVBB::MyMatrix::ArrayStatDyn< _PREC_, M>; \\\n template<int N> using ArrayDynStat = ApproxMVBB::MyMatrix::ArrayDynStat< _PREC_, N>; \\\n template<int M,int N> using ArrayStatStat = ApproxMVBB::MyMatrix::ArrayStatStat< _PREC_, M,N>; \\\n template<int M> using ArrayStat = ApproxMVBB::MyMatrix::ArrayStat< _PREC_, M>; \\\n using Array3 = ApproxMVBB::MyMatrix::Array3< _PREC_ >; \\\n using Array2 = ApproxMVBB::MyMatrix::Array2< _PREC_ >; \\\n \\\n ApproxMVBB_DEFINE_MATRIX_SPECIALTYPES\n\n#endif\n\n<|endoftext|>"} {"text":"<commit_before>\/* This file is part of Mapnik (c++ mapping toolkit)\n * Copyright (C) 2006 Artem Pavlenko\n *\n * Mapnik is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU General Public License\n * as published by the Free Software Foundation; either version 2\n * of the License, or any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.\n *\/\n\n\/\/$Id$\n\n\/\/ stl\n#include <iostream>\n\n\/\/ qt\n#include <QtGui>\n#include <QSplitter>\n#include <QTreeView>\n#include <QListView>\n#include <QTabWidget>\n#include <QList>\n#include <QItemDelegate>\n#include <QSlider>\n\n\/\/ mapnik\n#include <mapnik\/config_error.hpp>\n#include <mapnik\/load_map.hpp>\n#include <mapnik\/save_map.hpp>\n\n\/\/ qt\n#include \"mainwindow.hpp\"\n#include \"layerlistmodel.hpp\"\n#include \"styles_model.hpp\"\n#include \"layerwidget.hpp\"\n#include \"layerdelegate.hpp\"\n#include \"about_dialog.hpp\"\n\nMainWindow::MainWindow()\n : filename_(),\n default_extent_(-20037508.3428,-20037508.3428,20037508.3428,20037508.3428)\n{ \n mapWidget_ = new MapWidget(this);\n QSplitter *splitter = new QSplitter(this); \n QTabWidget *tabWidget=new QTabWidget;\n layerTab_ = new LayerTab;\n layerTab_->setFocusPolicy(Qt::NoFocus);\n layerTab_->setIconSize(QSize(16,16));\n \n \/\/LayerDelegate *delegate = new LayerDelegate(this); \n \/\/layerTab_->setItemDelegate(delegate);\n \/\/layerTab_->setItemDelegate(new QItemDelegate(this));\n \/\/layerTab_->setViewMode(QListView::IconMode);\n \n layerTab_->setFlow(QListView::TopToBottom);\n tabWidget->addTab(layerTab_,tr(\"Layers\"));\n\n \/\/ Styles tab\n styleTab_ = new StyleTab;\n tabWidget->addTab(styleTab_,tr(\"Styles\")); \n splitter->addWidget(tabWidget);\n splitter->addWidget(mapWidget_);\n QList<int> list;\n list.push_back(200);\n list.push_back(600);\n splitter->setSizes(list);\n \n mapWidget_->setFocusPolicy(Qt::StrongFocus);\n mapWidget_->setFocus();\n \n \/\/setCentralWidget(mapWidget_);\n setCentralWidget(splitter);\n createActions();\n createMenus();\n createToolBars();\n createContextMenu();\n \n setWindowTitle(tr(\"Mapnik Viewer\"));\n status=new QStatusBar(this);\n status->showMessage(tr(\"\"));\n setStatusBar(status);\n resize(800,600);\n\n \/\/connect mapview to layerlist\n connect(mapWidget_, SIGNAL(mapViewChanged()),layerTab_, SLOT(update()));\n \/\/ slider \n connect(slider_,SIGNAL(valueChanged(int)),mapWidget_,SLOT(zoomToLevel(int)));\n \/\/ \n connect(layerTab_,SIGNAL(update_mapwidget()),mapWidget_,SLOT(updateMap()));\n connect(layerTab_,SIGNAL(layerSelected(int)), \n mapWidget_,SLOT(layerSelected(int)));\n}\n\n\nMainWindow::~MainWindow()\n{\n delete mapWidget_;\n}\n\nvoid MainWindow::closeEvent(QCloseEvent* event)\n{\n event->accept();\n}\n\nvoid MainWindow::createContextMenu()\n{\n layerTab_->setContextMenuPolicy(Qt::ActionsContextMenu);\n layerTab_->addAction(openAct);\n layerTab_->addAction(layerInfo);\n}\n\nvoid MainWindow::open(QString const& path)\n{\n if (path.isNull())\n {\n filename_ = QFileDialog::getOpenFileName(this,tr(\"Open Mapnik file\"),\n currentPath,\"*.xml\");\n }\n else\n {\n filename_ = path;\n }\n \n if (!filename_.isEmpty())\n {\n load_map_file(filename_);\n \/\/zoom_all();\n setWindowTitle(tr(\"%1 - Mapnik Viewer\").arg(filename_));\n }\n \n}\n\nvoid MainWindow::reload() \n{\n if (!filename_.isEmpty())\n {\n mapnik::box2d<double> bbox = mapWidget_->getMap()->getCurrentExtent();\n load_map_file(filename_);\n mapWidget_->zoomToBox(bbox);\n setWindowTitle(tr(\"%1 - *Reloaded*\").arg(filename_));\n }\n}\n\nvoid MainWindow::save()\n{\n QString initialPath = QDir::currentPath() + \"\/untitled.xml\";\n QString filename = QFileDialog::getSaveFileName(this, tr(\"Save\"),\n initialPath,\n tr(\"%1 Files (*.xml)\")\n .arg(QString(\"Mapnik definition\")));\n if (!filename.isEmpty()) \n {\n std::cout<<\"saving \"<< filename.toStdString() << std::endl;\n mapnik::save_map(*mapWidget_->getMap(),filename.toStdString());\n }\n}\n\nvoid MainWindow::load_map_file(QString const& filename)\n{\n std::cout<<\"loading \"<< filename.toStdString() << std::endl; \n try \n { \n unsigned width = mapWidget_->width();\n unsigned height = mapWidget_->height();\n boost::shared_ptr<mapnik::Map> map(new mapnik::Map(width,height)); \n mapnik::load_map(*map,filename.toStdString());\n \n mapWidget_->setMap(map);\n map->zoom_all();\n mapnik::box2d<double> const& ext = map->getCurrentExtent();\n mapWidget_->zoomToBox(ext);\n layerTab_->setModel(new LayerListModel(map,this));\n styleTab_->setModel(new StyleModel(map,this));\n }\n catch (mapnik::config_error & ex) \n {\n std::cout << ex.what() << \"\\n\";\n }\n}\n\nvoid MainWindow::zoom_all()\n{\n mapWidget_->defaultView();\n}\n\nvoid MainWindow::zoom_to_box()\n{\n mapWidget_->setTool(MapWidget::ZoomToBox);\n}\n\nvoid MainWindow::pan()\n{\n mapWidget_->setTool(MapWidget::Pan); \n}\n\nvoid MainWindow::info()\n{\n mapWidget_->setTool(MapWidget::Info);\n}\n\nvoid MainWindow::pan_left()\n{\n mapWidget_->panLeft();\n}\n\nvoid MainWindow::pan_right()\n{\n mapWidget_->panRight();\n}\n\nvoid MainWindow::pan_up()\n{\n mapWidget_->panUp();\n}\n\nvoid MainWindow::pan_down()\n{\n mapWidget_->panDown();\n}\n\nvoid MainWindow::about()\n{\n about_dialog dlg;\n dlg.exec();\n}\n\nvoid MainWindow::export_as()\n{\n QAction *action = qobject_cast<QAction *>(sender());\n QByteArray fileFormat = action->data().toByteArray();\n QString initialPath = QDir::currentPath() + \"\/map.\" + fileFormat;\n\n QString fileName = QFileDialog::getSaveFileName(this, tr(\"Export As\"),\n initialPath,\n tr(\"%1 Files (*.%2);;All Files (*)\")\n .arg(QString(fileFormat.toUpper()))\n .arg(QString(fileFormat)));\n if (!fileName.isEmpty()) \n {\n QPixmap const& pix = mapWidget_->pixmap();\n pix.save(fileName);\n }\n}\n\nvoid MainWindow::print()\n{ \n \n \/\/Q_ASSERT(mapWidget_->pixmap());\n \/\/QPrintDialog dialog(&printer, this);\n \/\/if (dialog.exec()) {\n \/\/\tQPainter painter(&printer);\n \/\/\tQRect rect = painter.viewport();\n \/\/\tQSize size = mapWidget_->pixmap()->size();\n \/\/\tsize.scale(rect.size(), Qt::KeepAspectRatio);\n \/\/\tpainter.setViewport(rect.x(), rect.y(), size.width(), size.height());\n \/\/\tpainter.setWindow(mapWidget_->pixmap()->rect());\n \/\/\tpainter.drawPixmap(0, 0, *mapWidget_->pixmap());\n \/\/}\n}\n\nvoid MainWindow::createActions()\n{ \n \/\/exportAct = new QAction(tr(\"&Export as ...\"),this);\n \/\/exportAct->setShortcut(tr(\"Ctrl+E\"));\n \/\/connect(exportAct, SIGNAL(triggered()), this, SLOT(export_as()));\n zoomAllAct = new QAction(QIcon(\":\/images\/home.png\"),tr(\"Zoom All\"),this);\n connect(zoomAllAct, SIGNAL(triggered()), this, SLOT(zoom_all()));\n \n zoomBoxAct = new QAction(QIcon(\":\/images\/zoombox.png\"),tr(\"Zoom To Box\"),this);\n zoomBoxAct->setCheckable(true);\n connect(zoomBoxAct, SIGNAL(triggered()), this, SLOT(zoom_to_box()));\n \n panAct = new QAction(QIcon(\":\/images\/pan.png\"),tr(\"Pan\"),this);\n panAct->setCheckable(true);\n connect(panAct, SIGNAL(triggered()), this, SLOT(pan()));\n \n infoAct = new QAction(QIcon(\":\/images\/info.png\"),tr(\"Info\"),this);\n infoAct->setCheckable(true);\n connect(infoAct, SIGNAL(triggered()), this, SLOT(info()));\n \n toolsGroup=new QActionGroup(this);\n toolsGroup->addAction(zoomBoxAct);\n toolsGroup->addAction(panAct);\n toolsGroup->addAction(infoAct);\n zoomBoxAct->setChecked(true);\n \n openAct=new QAction(tr(\"Open Map definition\"),this);\n connect(openAct,SIGNAL(triggered()),this,SLOT(open()));\n saveAct=new QAction(tr(\"Save Map definition\"),this);\n connect(saveAct,SIGNAL(triggered()),this,SLOT(save()));\n\n panLeftAct = new QAction(QIcon(\":\/images\/left.png\"),tr(\"&Pan Left\"),this);\n connect(panLeftAct, SIGNAL(triggered()), this, SLOT(pan_left()));\n panRightAct = new QAction(QIcon(\":\/images\/right.png\"),tr(\"&Pan Right\"),this);\n connect(panRightAct, SIGNAL(triggered()), this, SLOT(pan_right()));\n panUpAct = new QAction(QIcon(\":\/images\/up.png\"),tr(\"&Pan Up\"),this);\n connect(panUpAct, SIGNAL(triggered()), this, SLOT(pan_up()));\n panDownAct = new QAction(QIcon(\":\/images\/down.png\"),tr(\"&Pan Down\"),this);\n connect(panDownAct, SIGNAL(triggered()), this, SLOT(pan_down()));\n \n reloadAct = new QAction(QIcon(\":\/images\/reload.png\"),tr(\"Reload\"),this);\n connect(reloadAct, SIGNAL(triggered()), this, SLOT(reload()));\n \n layerInfo = new QAction(QIcon(\":\/images\/info.png\"),tr(\"&Layer info\"),layerTab_);\n connect(layerInfo, SIGNAL(triggered()), layerTab_,SLOT(layerInfo()));\n connect(layerTab_, SIGNAL(doubleClicked(QModelIndex const&)), layerTab_,SLOT(layerInfo2(QModelIndex const&)));\n foreach (QByteArray format, QImageWriter::supportedImageFormats()) \n {\n QString text = tr(\"%1...\").arg(QString(format).toUpper());\n \n QAction *action = new QAction(text, this);\n action->setData(format);\n connect(action, SIGNAL(triggered()), this, SLOT(export_as()));\n exportAsActs.append(action);\n }\n \n printAct = new QAction(QIcon(\":\/images\/print.png\"),tr(\"&Print ...\"),this);\n printAct->setShortcut(tr(\"Ctrl+E\"));\n connect(printAct, SIGNAL(triggered()), this, SLOT(print()));\n \n exitAct = new QAction(tr(\"E&xit\"), this);\n exitAct->setShortcut(tr(\"Ctrl+Q\"));\n connect(exitAct, SIGNAL(triggered()), this, SLOT(close()));\n\n aboutAct = new QAction(QIcon(\":\/images\/about.png\"),tr(\"&About\"), this);\n connect(aboutAct, SIGNAL(triggered()), this, SLOT(about()));\n}\n\nvoid MainWindow::createMenus()\n{\n exportMenu = new QMenu(tr(\"&Export As\"), this);\n foreach (QAction *action, exportAsActs)\n exportMenu->addAction(action); \n \n fileMenu = new QMenu(tr(\"&File\"),this);\n fileMenu->addAction(openAct);\n fileMenu->addAction(saveAct);\n fileMenu->addMenu(exportMenu);\n fileMenu->addAction(printAct);\n fileMenu->addSeparator();\n fileMenu->addAction(exitAct);\n menuBar()->addMenu(fileMenu);\n \n helpMenu = new QMenu(tr(\"&Help\"), this);\n helpMenu->addAction(aboutAct);\n menuBar()->addMenu(helpMenu);\n}\n\nvoid MainWindow::createToolBars()\n{\n fileToolBar = addToolBar(tr(\"Actions\"));\n fileToolBar->addAction(zoomAllAct);\n fileToolBar->addAction(zoomBoxAct);\n fileToolBar->addAction(panAct);\n fileToolBar->addAction(panLeftAct);\n fileToolBar->addAction(panRightAct);\n fileToolBar->addAction(panUpAct);\n fileToolBar->addAction(panDownAct);\n fileToolBar->addAction(infoAct);\n fileToolBar->addAction(reloadAct);\n fileToolBar->addAction(printAct);\n slider_ = new QSlider(Qt::Horizontal,fileToolBar);\n slider_->setRange(1,18);\n slider_->setTickPosition(QSlider::TicksBelow);\n slider_->setTickInterval(1);\n slider_->setTracking(false);\n fileToolBar->addWidget(slider_);\n fileToolBar->addAction(aboutAct);\n}\n\n\n\nvoid MainWindow::set_default_extent(double x0,double y0, double x1, double y1)\n{\n try \n {\n boost::shared_ptr<mapnik::Map> map_ptr = mapWidget_->getMap();\n if (map_ptr) \n {\n mapnik::projection prj(map_ptr->srs());\n prj.forward(x0,y0);\n prj.forward(x1,y1);\n default_extent_=mapnik::box2d<double>(x0,y0,x1,y1);\n mapWidget_->zoomToBox(default_extent_);\n std::cout << \"SET DEFAULT EXT\\n\";\n }\n }\n catch (...) {}\n \n \n}\n<commit_msg>+ don't fail if load_map throws config error<commit_after>\/* This file is part of Mapnik (c++ mapping toolkit)\n * Copyright (C) 2006 Artem Pavlenko\n *\n * Mapnik is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU General Public License\n * as published by the Free Software Foundation; either version 2\n * of the License, or any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.\n *\/\n\n\/\/$Id$\n\n\/\/ stl\n#include <iostream>\n\n\/\/ qt\n#include <QtGui>\n#include <QSplitter>\n#include <QTreeView>\n#include <QListView>\n#include <QTabWidget>\n#include <QList>\n#include <QItemDelegate>\n#include <QSlider>\n\n\/\/ mapnik\n#include <mapnik\/config_error.hpp>\n#include <mapnik\/load_map.hpp>\n#include <mapnik\/save_map.hpp>\n\n\/\/ qt\n#include \"mainwindow.hpp\"\n#include \"layerlistmodel.hpp\"\n#include \"styles_model.hpp\"\n#include \"layerwidget.hpp\"\n#include \"layerdelegate.hpp\"\n#include \"about_dialog.hpp\"\n\nMainWindow::MainWindow()\n : filename_(),\n default_extent_(-20037508.3428,-20037508.3428,20037508.3428,20037508.3428)\n{ \n mapWidget_ = new MapWidget(this);\n QSplitter *splitter = new QSplitter(this); \n QTabWidget *tabWidget=new QTabWidget;\n layerTab_ = new LayerTab;\n layerTab_->setFocusPolicy(Qt::NoFocus);\n layerTab_->setIconSize(QSize(16,16));\n \n \/\/LayerDelegate *delegate = new LayerDelegate(this); \n \/\/layerTab_->setItemDelegate(delegate);\n \/\/layerTab_->setItemDelegate(new QItemDelegate(this));\n \/\/layerTab_->setViewMode(QListView::IconMode);\n \n layerTab_->setFlow(QListView::TopToBottom);\n tabWidget->addTab(layerTab_,tr(\"Layers\"));\n\n \/\/ Styles tab\n styleTab_ = new StyleTab;\n tabWidget->addTab(styleTab_,tr(\"Styles\")); \n splitter->addWidget(tabWidget);\n splitter->addWidget(mapWidget_);\n QList<int> list;\n list.push_back(200);\n list.push_back(600);\n splitter->setSizes(list);\n \n mapWidget_->setFocusPolicy(Qt::StrongFocus);\n mapWidget_->setFocus();\n \n \/\/setCentralWidget(mapWidget_);\n setCentralWidget(splitter);\n createActions();\n createMenus();\n createToolBars();\n createContextMenu();\n \n setWindowTitle(tr(\"Mapnik Viewer\"));\n status=new QStatusBar(this);\n status->showMessage(tr(\"\"));\n setStatusBar(status);\n resize(800,600);\n\n \/\/connect mapview to layerlist\n connect(mapWidget_, SIGNAL(mapViewChanged()),layerTab_, SLOT(update()));\n \/\/ slider \n connect(slider_,SIGNAL(valueChanged(int)),mapWidget_,SLOT(zoomToLevel(int)));\n \/\/ \n connect(layerTab_,SIGNAL(update_mapwidget()),mapWidget_,SLOT(updateMap()));\n connect(layerTab_,SIGNAL(layerSelected(int)), \n mapWidget_,SLOT(layerSelected(int)));\n}\n\n\nMainWindow::~MainWindow()\n{\n delete mapWidget_;\n}\n\nvoid MainWindow::closeEvent(QCloseEvent* event)\n{\n event->accept();\n}\n\nvoid MainWindow::createContextMenu()\n{\n layerTab_->setContextMenuPolicy(Qt::ActionsContextMenu);\n layerTab_->addAction(openAct);\n layerTab_->addAction(layerInfo);\n}\n\nvoid MainWindow::open(QString const& path)\n{\n if (path.isNull())\n {\n filename_ = QFileDialog::getOpenFileName(this,tr(\"Open Mapnik file\"),\n currentPath,\"*.xml\");\n }\n else\n {\n filename_ = path;\n }\n \n if (!filename_.isEmpty())\n {\n load_map_file(filename_);\n \/\/zoom_all();\n setWindowTitle(tr(\"%1 - Mapnik Viewer\").arg(filename_));\n }\n \n}\n\nvoid MainWindow::reload() \n{\n if (!filename_.isEmpty())\n {\n\t\n\tmapnik::box2d<double> bbox = mapWidget_->getMap()->getCurrentExtent();\n\tload_map_file(filename_);\n\tmapWidget_->zoomToBox(bbox);\n\tsetWindowTitle(tr(\"%1 - *Reloaded*\").arg(filename_));\n }\n}\n\nvoid MainWindow::save()\n{\n QString initialPath = QDir::currentPath() + \"\/untitled.xml\";\n QString filename = QFileDialog::getSaveFileName(this, tr(\"Save\"),\n initialPath,\n tr(\"%1 Files (*.xml)\")\n .arg(QString(\"Mapnik definition\")));\n if (!filename.isEmpty()) \n {\n std::cout<<\"saving \"<< filename.toStdString() << std::endl;\n mapnik::save_map(*mapWidget_->getMap(),filename.toStdString());\n }\n}\n\nvoid MainWindow::load_map_file(QString const& filename)\n{\n std::cout<<\"loading \"<< filename.toStdString() << std::endl; \n unsigned width = mapWidget_->width();\n unsigned height = mapWidget_->height();\n boost::shared_ptr<mapnik::Map> map(new mapnik::Map(width,height)); \n mapWidget_->setMap(map);\n try \n { \n mapnik::load_map(*map,filename.toStdString());\n }\n catch (mapnik::config_error & ex) \n {\n std::cout << ex.what() << \"\\n\";\n }\n map->zoom_all();\n mapnik::box2d<double> const& ext = map->getCurrentExtent();\n mapWidget_->zoomToBox(ext);\n layerTab_->setModel(new LayerListModel(map,this));\n styleTab_->setModel(new StyleModel(map,this));\n}\n\nvoid MainWindow::zoom_all()\n{\n mapWidget_->defaultView();\n}\n\nvoid MainWindow::zoom_to_box()\n{\n mapWidget_->setTool(MapWidget::ZoomToBox);\n}\n\nvoid MainWindow::pan()\n{\n mapWidget_->setTool(MapWidget::Pan); \n}\n\nvoid MainWindow::info()\n{\n mapWidget_->setTool(MapWidget::Info);\n}\n\nvoid MainWindow::pan_left()\n{\n mapWidget_->panLeft();\n}\n\nvoid MainWindow::pan_right()\n{\n mapWidget_->panRight();\n}\n\nvoid MainWindow::pan_up()\n{\n mapWidget_->panUp();\n}\n\nvoid MainWindow::pan_down()\n{\n mapWidget_->panDown();\n}\n\nvoid MainWindow::about()\n{\n about_dialog dlg;\n dlg.exec();\n}\n\nvoid MainWindow::export_as()\n{\n QAction *action = qobject_cast<QAction *>(sender());\n QByteArray fileFormat = action->data().toByteArray();\n QString initialPath = QDir::currentPath() + \"\/map.\" + fileFormat;\n\n QString fileName = QFileDialog::getSaveFileName(this, tr(\"Export As\"),\n initialPath,\n tr(\"%1 Files (*.%2);;All Files (*)\")\n .arg(QString(fileFormat.toUpper()))\n .arg(QString(fileFormat)));\n if (!fileName.isEmpty()) \n {\n QPixmap const& pix = mapWidget_->pixmap();\n pix.save(fileName);\n }\n}\n\nvoid MainWindow::print()\n{ \n \n \/\/Q_ASSERT(mapWidget_->pixmap());\n \/\/QPrintDialog dialog(&printer, this);\n \/\/if (dialog.exec()) {\n \/\/\tQPainter painter(&printer);\n \/\/\tQRect rect = painter.viewport();\n \/\/\tQSize size = mapWidget_->pixmap()->size();\n \/\/\tsize.scale(rect.size(), Qt::KeepAspectRatio);\n \/\/\tpainter.setViewport(rect.x(), rect.y(), size.width(), size.height());\n \/\/\tpainter.setWindow(mapWidget_->pixmap()->rect());\n \/\/\tpainter.drawPixmap(0, 0, *mapWidget_->pixmap());\n \/\/}\n}\n\nvoid MainWindow::createActions()\n{ \n \/\/exportAct = new QAction(tr(\"&Export as ...\"),this);\n \/\/exportAct->setShortcut(tr(\"Ctrl+E\"));\n \/\/connect(exportAct, SIGNAL(triggered()), this, SLOT(export_as()));\n zoomAllAct = new QAction(QIcon(\":\/images\/home.png\"),tr(\"Zoom All\"),this);\n connect(zoomAllAct, SIGNAL(triggered()), this, SLOT(zoom_all()));\n \n zoomBoxAct = new QAction(QIcon(\":\/images\/zoombox.png\"),tr(\"Zoom To Box\"),this);\n zoomBoxAct->setCheckable(true);\n connect(zoomBoxAct, SIGNAL(triggered()), this, SLOT(zoom_to_box()));\n \n panAct = new QAction(QIcon(\":\/images\/pan.png\"),tr(\"Pan\"),this);\n panAct->setCheckable(true);\n connect(panAct, SIGNAL(triggered()), this, SLOT(pan()));\n \n infoAct = new QAction(QIcon(\":\/images\/info.png\"),tr(\"Info\"),this);\n infoAct->setCheckable(true);\n connect(infoAct, SIGNAL(triggered()), this, SLOT(info()));\n \n toolsGroup=new QActionGroup(this);\n toolsGroup->addAction(zoomBoxAct);\n toolsGroup->addAction(panAct);\n toolsGroup->addAction(infoAct);\n zoomBoxAct->setChecked(true);\n \n openAct=new QAction(tr(\"Open Map definition\"),this);\n connect(openAct,SIGNAL(triggered()),this,SLOT(open()));\n saveAct=new QAction(tr(\"Save Map definition\"),this);\n connect(saveAct,SIGNAL(triggered()),this,SLOT(save()));\n\n panLeftAct = new QAction(QIcon(\":\/images\/left.png\"),tr(\"&Pan Left\"),this);\n connect(panLeftAct, SIGNAL(triggered()), this, SLOT(pan_left()));\n panRightAct = new QAction(QIcon(\":\/images\/right.png\"),tr(\"&Pan Right\"),this);\n connect(panRightAct, SIGNAL(triggered()), this, SLOT(pan_right()));\n panUpAct = new QAction(QIcon(\":\/images\/up.png\"),tr(\"&Pan Up\"),this);\n connect(panUpAct, SIGNAL(triggered()), this, SLOT(pan_up()));\n panDownAct = new QAction(QIcon(\":\/images\/down.png\"),tr(\"&Pan Down\"),this);\n connect(panDownAct, SIGNAL(triggered()), this, SLOT(pan_down()));\n \n reloadAct = new QAction(QIcon(\":\/images\/reload.png\"),tr(\"Reload\"),this);\n connect(reloadAct, SIGNAL(triggered()), this, SLOT(reload()));\n \n layerInfo = new QAction(QIcon(\":\/images\/info.png\"),tr(\"&Layer info\"),layerTab_);\n connect(layerInfo, SIGNAL(triggered()), layerTab_,SLOT(layerInfo()));\n connect(layerTab_, SIGNAL(doubleClicked(QModelIndex const&)), layerTab_,SLOT(layerInfo2(QModelIndex const&)));\n foreach (QByteArray format, QImageWriter::supportedImageFormats()) \n {\n QString text = tr(\"%1...\").arg(QString(format).toUpper());\n \n QAction *action = new QAction(text, this);\n action->setData(format);\n connect(action, SIGNAL(triggered()), this, SLOT(export_as()));\n exportAsActs.append(action);\n }\n \n printAct = new QAction(QIcon(\":\/images\/print.png\"),tr(\"&Print ...\"),this);\n printAct->setShortcut(tr(\"Ctrl+E\"));\n connect(printAct, SIGNAL(triggered()), this, SLOT(print()));\n \n exitAct = new QAction(tr(\"E&xit\"), this);\n exitAct->setShortcut(tr(\"Ctrl+Q\"));\n connect(exitAct, SIGNAL(triggered()), this, SLOT(close()));\n\n aboutAct = new QAction(QIcon(\":\/images\/about.png\"),tr(\"&About\"), this);\n connect(aboutAct, SIGNAL(triggered()), this, SLOT(about()));\n}\n\nvoid MainWindow::createMenus()\n{\n exportMenu = new QMenu(tr(\"&Export As\"), this);\n foreach (QAction *action, exportAsActs)\n exportMenu->addAction(action); \n \n fileMenu = new QMenu(tr(\"&File\"),this);\n fileMenu->addAction(openAct);\n fileMenu->addAction(saveAct);\n fileMenu->addMenu(exportMenu);\n fileMenu->addAction(printAct);\n fileMenu->addSeparator();\n fileMenu->addAction(exitAct);\n menuBar()->addMenu(fileMenu);\n \n helpMenu = new QMenu(tr(\"&Help\"), this);\n helpMenu->addAction(aboutAct);\n menuBar()->addMenu(helpMenu);\n}\n\nvoid MainWindow::createToolBars()\n{\n fileToolBar = addToolBar(tr(\"Actions\"));\n fileToolBar->addAction(zoomAllAct);\n fileToolBar->addAction(zoomBoxAct);\n fileToolBar->addAction(panAct);\n fileToolBar->addAction(panLeftAct);\n fileToolBar->addAction(panRightAct);\n fileToolBar->addAction(panUpAct);\n fileToolBar->addAction(panDownAct);\n fileToolBar->addAction(infoAct);\n fileToolBar->addAction(reloadAct);\n fileToolBar->addAction(printAct);\n slider_ = new QSlider(Qt::Horizontal,fileToolBar);\n slider_->setRange(1,18);\n slider_->setTickPosition(QSlider::TicksBelow);\n slider_->setTickInterval(1);\n slider_->setTracking(false);\n fileToolBar->addWidget(slider_);\n fileToolBar->addAction(aboutAct);\n}\n\n\n\nvoid MainWindow::set_default_extent(double x0,double y0, double x1, double y1)\n{\n try \n {\n boost::shared_ptr<mapnik::Map> map_ptr = mapWidget_->getMap();\n if (map_ptr) \n {\n mapnik::projection prj(map_ptr->srs());\n prj.forward(x0,y0);\n prj.forward(x1,y1);\n default_extent_=mapnik::box2d<double>(x0,y0,x1,y1);\n mapWidget_->zoomToBox(default_extent_);\n std::cout << \"SET DEFAULT EXT\\n\";\n }\n }\n catch (...) {}\n \n \n}\n<|endoftext|>"} {"text":"<commit_before>\/** @file\n\n Multiplexes request to other origins.\n\n @section license License\n\n Licensed to the Apache Software Foundation (ASF) under one\n or more contributor license agreements. See the NOTICE file\n distributed with this work for additional information\n regarding copyright ownership. The ASF licenses this file\n to you under the Apache License, Version 2.0 (the\n \"License\"); you may not use this file except in compliance\n with the License. You may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n *\/\n#include <cassert>\n#include <limits>\n\n#include \"post.h\"\n\n#ifndef PLUGIN_TAG\n#error Please define a PLUGIN_TAG before including this file.\n#endif\n\nPostState::~PostState()\n{\n if (buffer != nullptr) {\n TSIOBufferDestroy(buffer);\n buffer = nullptr;\n }\n}\n\nPostState::PostState(Requests &r) : buffer(nullptr), reader(nullptr), vio(nullptr)\n{\n assert(!r.empty());\n requests.swap(r);\n}\n\nstatic void\npostTransform(const TSCont c, PostState &s)\n{\n assert(c != nullptr);\n\n const TSVConn vconnection = TSTransformOutputVConnGet(c);\n assert(vconnection != nullptr);\n\n const TSVIO vio = TSVConnWriteVIOGet(c);\n assert(vio != nullptr);\n\n if (!s.buffer) {\n s.buffer = TSIOBufferCreate();\n assert(s.buffer != nullptr);\n\n const TSIOBufferReader reader = TSIOBufferReaderAlloc(s.buffer);\n assert(reader != nullptr);\n\n s.reader = TSIOBufferReaderClone(reader);\n assert(s.reader != nullptr);\n\n s.vio = TSVConnWrite(vconnection, c, reader, std::numeric_limits<int64_t>::max());\n assert(s.vio != nullptr);\n }\n\n if (!TSVIOBufferGet(vio)) {\n TSVIONBytesSet(s.vio, TSVIONDoneGet(vio));\n TSVIOReenable(s.vio);\n return;\n }\n\n int64_t toWrite = TSVIONTodoGet(vio);\n assert(toWrite >= 0);\n\n if (toWrite > 0) {\n toWrite = std::min(toWrite, TSIOBufferReaderAvail(TSVIOReaderGet(vio)));\n assert(toWrite >= 0);\n\n if (toWrite > 0) {\n TSIOBufferCopy(TSVIOBufferGet(s.vio), TSVIOReaderGet(vio), toWrite, 0);\n TSIOBufferReaderConsume(TSVIOReaderGet(vio), toWrite);\n TSVIONDoneSet(vio, TSVIONDoneGet(vio) + toWrite);\n }\n }\n\n if (TSVIONTodoGet(vio) > 0) {\n if (toWrite > 0) {\n TSVIOReenable(s.vio);\n CHECK(TSContCall(TSVIOContGet(vio), TS_EVENT_VCONN_WRITE_READY, vio));\n }\n } else {\n TSVIONBytesSet(s.vio, TSVIONDoneGet(vio));\n TSVIOReenable(s.vio);\n CHECK(TSContCall(TSVIOContGet(vio), TS_EVENT_VCONN_WRITE_COMPLETE, vio));\n }\n}\n\nint\nhandlePost(TSCont c, TSEvent e, void *data)\n{\n assert(c != nullptr);\n \/\/ TODO(dmorilha): assert on possible events.\n PostState *const state = static_cast<PostState *>(TSContDataGet(c));\n assert(state != nullptr);\n if (TSVConnClosedGet(c)) {\n assert(data != nullptr);\n if (state->reader != nullptr) {\n addBody(state->requests, state->reader);\n }\n dispatch(state->requests, timeout);\n delete state;\n TSContDataSet(c, nullptr);\n TSContDestroy(c);\n return 0;\n } else {\n switch (e) {\n case TS_EVENT_ERROR: {\n const TSVIO vio = TSVConnWriteVIOGet(c);\n assert(vio != nullptr);\n CHECK(TSContCall(TSVIOContGet(vio), TS_EVENT_ERROR, vio));\n } break;\n case TS_EVENT_VCONN_WRITE_COMPLETE:\n TSVConnShutdown(TSTransformOutputVConnGet(c), 0, 1);\n break;\n\n case TS_EVENT_VCONN_WRITE_READY:\n default:\n postTransform(c, *state);\n break;\n }\n }\n return 0;\n}\n<commit_msg>Removed checking the return value for TSContCall()<commit_after>\/** @file\n\n Multiplexes request to other origins.\n\n @section license License\n\n Licensed to the Apache Software Foundation (ASF) under one\n or more contributor license agreements. See the NOTICE file\n distributed with this work for additional information\n regarding copyright ownership. The ASF licenses this file\n to you under the Apache License, Version 2.0 (the\n \"License\"); you may not use this file except in compliance\n with the License. You may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n *\/\n#include <cassert>\n#include <limits>\n\n#include \"post.h\"\n\n#ifndef PLUGIN_TAG\n#error Please define a PLUGIN_TAG before including this file.\n#endif\n\nPostState::~PostState()\n{\n if (buffer != nullptr) {\n TSIOBufferDestroy(buffer);\n buffer = nullptr;\n }\n}\n\nPostState::PostState(Requests &r) : buffer(nullptr), reader(nullptr), vio(nullptr)\n{\n assert(!r.empty());\n requests.swap(r);\n}\n\nstatic void\npostTransform(const TSCont c, PostState &s)\n{\n assert(c != nullptr);\n\n const TSVConn vconnection = TSTransformOutputVConnGet(c);\n assert(vconnection != nullptr);\n\n const TSVIO vio = TSVConnWriteVIOGet(c);\n assert(vio != nullptr);\n\n if (!s.buffer) {\n s.buffer = TSIOBufferCreate();\n assert(s.buffer != nullptr);\n\n const TSIOBufferReader reader = TSIOBufferReaderAlloc(s.buffer);\n assert(reader != nullptr);\n\n s.reader = TSIOBufferReaderClone(reader);\n assert(s.reader != nullptr);\n\n s.vio = TSVConnWrite(vconnection, c, reader, std::numeric_limits<int64_t>::max());\n assert(s.vio != nullptr);\n }\n\n if (!TSVIOBufferGet(vio)) {\n TSVIONBytesSet(s.vio, TSVIONDoneGet(vio));\n TSVIOReenable(s.vio);\n return;\n }\n\n int64_t toWrite = TSVIONTodoGet(vio);\n assert(toWrite >= 0);\n\n if (toWrite > 0) {\n toWrite = std::min(toWrite, TSIOBufferReaderAvail(TSVIOReaderGet(vio)));\n assert(toWrite >= 0);\n\n if (toWrite > 0) {\n TSIOBufferCopy(TSVIOBufferGet(s.vio), TSVIOReaderGet(vio), toWrite, 0);\n TSIOBufferReaderConsume(TSVIOReaderGet(vio), toWrite);\n TSVIONDoneSet(vio, TSVIONDoneGet(vio) + toWrite);\n }\n }\n\n if (TSVIONTodoGet(vio) > 0) {\n if (toWrite > 0) {\n TSVIOReenable(s.vio);\n TSContCall(TSVIOContGet(vio), TS_EVENT_VCONN_WRITE_READY, vio);\n }\n } else {\n TSVIONBytesSet(s.vio, TSVIONDoneGet(vio));\n TSVIOReenable(s.vio);\n TSContCall(TSVIOContGet(vio), TS_EVENT_VCONN_WRITE_COMPLETE, vio);\n }\n}\n\nint\nhandlePost(TSCont c, TSEvent e, void *data)\n{\n assert(c != nullptr);\n \/\/ TODO(dmorilha): assert on possible events.\n PostState *const state = static_cast<PostState *>(TSContDataGet(c));\n assert(state != nullptr);\n if (TSVConnClosedGet(c)) {\n assert(data != nullptr);\n if (state->reader != nullptr) {\n addBody(state->requests, state->reader);\n }\n dispatch(state->requests, timeout);\n delete state;\n TSContDataSet(c, nullptr);\n TSContDestroy(c);\n return 0;\n } else {\n switch (e) {\n case TS_EVENT_ERROR: {\n const TSVIO vio = TSVConnWriteVIOGet(c);\n assert(vio != nullptr);\n TSContCall(TSVIOContGet(vio), TS_EVENT_ERROR, vio);\n } break;\n case TS_EVENT_VCONN_WRITE_COMPLETE:\n TSVConnShutdown(TSTransformOutputVConnGet(c), 0, 1);\n break;\n\n case TS_EVENT_VCONN_WRITE_READY:\n default:\n postTransform(c, *state);\n break;\n }\n }\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>#include <wayfire\/plugin.hpp>\n#include <wayfire\/signal-definitions.hpp>\n#include <wayfire\/view-transform.hpp>\n#include <wayfire\/view.hpp>\n#include <wayfire\/workspace-manager.hpp>\n\n\/*\n * This plugin provides abilities to switch between views.\n * It works similarly to the alt-esc binding in Windows or GNOME\n *\/\n\nclass wayfire_fast_switcher : public wf::plugin_interface_t\n{\n wf::option_wrapper_t<wf::keybinding_t> activate_key{\"fast-switcher\/activate\"};\n size_t current_view_index;\n std::vector<wayfire_view> views; \/\/ all views on current viewport\n\n bool active = false;\n\n public:\n void init() override\n {\n grab_interface->name = \"fast-switcher\";\n grab_interface->capabilities = wf::CAPABILITY_MANAGE_COMPOSITOR;\n output->add_key(activate_key, &fast_switch);\n\n using namespace std::placeholders;\n grab_interface->callbacks.keyboard.mod =\n std::bind(std::mem_fn(&wayfire_fast_switcher::handle_mod),\n this, _1, _2);\n\n grab_interface->callbacks.cancel = [=] ()\n {\n switch_terminate();\n };\n }\n\n void handle_mod(uint32_t mod, uint32_t st)\n {\n bool mod_released =\n (mod == ((wf::keybinding_t)activate_key).get_modifiers() &&\n st == WLR_KEY_RELEASED);\n\n if (mod_released)\n {\n switch_terminate();\n }\n }\n\n void update_views()\n {\n current_view_index = 0;\n views = output->workspace->get_views_on_workspace(\n output->workspace->get_current_workspace(), wf::WM_LAYERS);\n }\n\n void view_chosen(int i, bool reorder_only)\n {\n \/* No view available *\/\n if (!((0 <= i) && (i < (int)views.size())))\n {\n return;\n }\n\n set_view_alpha(views[i], 1.0);\n for (int i = (int)views.size() - 1; i >= 0; i--)\n {\n output->workspace->bring_to_front(views[i]);\n }\n\n if (reorder_only)\n {\n output->workspace->bring_to_front(views[i]);\n } else\n {\n output->focus_view(views[i], true);\n }\n }\n\n wf::signal_callback_t cleanup_view = [=] (wf::signal_data_t *data)\n {\n auto view = get_signaled_view(data);\n\n size_t i = 0;\n for (; i < views.size() && views[i] != view; i++)\n {}\n\n if (i == views.size())\n {\n return;\n }\n\n views.erase(views.begin() + i);\n\n if (views.empty())\n {\n switch_terminate();\n\n return;\n }\n\n if (i <= current_view_index)\n {\n current_view_index =\n (current_view_index + views.size() - 1) % views.size();\n view_chosen(current_view_index, true);\n }\n };\n\n const std::string transformer_name = \"fast-switcher\";\n\n void set_view_alpha(wayfire_view view, float alpha)\n {\n if (!view->get_transformer(transformer_name))\n {\n view->add_transformer(\n std::make_unique<wf::view_2D>(view), transformer_name);\n }\n\n auto tr = dynamic_cast<wf::view_2D*>(\n view->get_transformer(transformer_name).get());\n tr->alpha = alpha;\n view->damage();\n }\n\n wf::key_callback fast_switch = [=] (auto)\n {\n if (active)\n {\n switch_next();\n\n return true;\n }\n\n if (!output->activate_plugin(grab_interface))\n {\n return false;\n }\n\n update_views();\n\n if (views.size() < 1)\n {\n output->deactivate_plugin(grab_interface);\n\n return false;\n }\n\n current_view_index = 0;\n active = true;\n\n \/* Set all to semi-transparent *\/\n for (auto view : views)\n {\n set_view_alpha(view, 0.7);\n }\n\n grab_interface->grab();\n switch_next();\n\n output->connect_signal(\"view-disappeared\", &cleanup_view);\n\n return true;\n };\n\n void switch_terminate()\n {\n for (auto view : views)\n {\n view->pop_transformer(transformer_name);\n }\n\n grab_interface->ungrab();\n output->deactivate_plugin(grab_interface);\n view_chosen(current_view_index, false);\n\n active = false;\n\n output->disconnect_signal(\"view-disappeared\", &cleanup_view);\n }\n\n void switch_next()\n {\n#define index current_view_index\n set_view_alpha(views[index], 0.7);\n index = (index + 1) % views.size();\n#undef index\n view_chosen(current_view_index, true);\n }\n\n void fini() override\n {\n if (active)\n {\n switch_terminate();\n }\n\n output->rem_binding(&fast_switch);\n }\n};\n\nDECLARE_WAYFIRE_PLUGIN(wayfire_fast_switcher);\n<commit_msg>Fast switcher uses focus order instead of stack order (#907)<commit_after>#include <wayfire\/plugin.hpp>\n#include <wayfire\/signal-definitions.hpp>\n#include <wayfire\/view-transform.hpp>\n#include <wayfire\/view.hpp>\n#include <wayfire\/workspace-manager.hpp>\n\n\/*\n * This plugin provides abilities to switch between views.\n * It works similarly to the alt-esc binding in Windows or GNOME\n *\/\n\nclass wayfire_fast_switcher : public wf::plugin_interface_t\n{\n wf::option_wrapper_t<wf::keybinding_t> activate_key{\"fast-switcher\/activate\"};\n std::vector<wayfire_view> views; \/\/ all views on current viewport\n size_t current_view_index = 0;\n bool active = false;\n\n public:\n void init() override\n {\n grab_interface->name = \"fast-switcher\";\n grab_interface->capabilities = wf::CAPABILITY_MANAGE_COMPOSITOR;\n\n output->add_key(activate_key, &fast_switch);\n\n using namespace std::placeholders;\n grab_interface->callbacks.keyboard.mod =\n std::bind(std::mem_fn(&wayfire_fast_switcher::handle_mod),\n this, _1, _2);\n\n grab_interface->callbacks.cancel = [=] () { switch_terminate(); };\n }\n\n void handle_mod(uint32_t mod, uint32_t st)\n {\n bool mod_released =\n (mod == ((wf::keybinding_t)activate_key).get_modifiers() &&\n st == WLR_KEY_RELEASED);\n\n if (mod_released)\n {\n switch_terminate();\n }\n }\n\n void view_chosen(int i, bool reorder_only)\n {\n \/* No view available *\/\n if (!((0 <= i) && (i < (int)views.size())))\n {\n return;\n }\n\n set_view_alpha(views[i], 1.0);\n for (int i = (int)views.size() - 1; i >= 0; i--)\n {\n output->workspace->bring_to_front(views[i]);\n }\n\n if (reorder_only)\n {\n output->workspace->bring_to_front(views[i]);\n } else\n {\n output->focus_view(views[i], true);\n }\n }\n\n wf::signal_callback_t cleanup_view = [=] (wf::signal_data_t *data)\n {\n auto view = get_signaled_view(data);\n\n size_t i = 0;\n for (; i < views.size() && views[i] != view; i++)\n {}\n\n if (i == views.size())\n {\n return;\n }\n\n views.erase(views.begin() + i);\n\n if (views.empty())\n {\n switch_terminate();\n\n return;\n }\n\n if (i <= current_view_index)\n {\n current_view_index =\n (current_view_index + views.size() - 1) % views.size();\n view_chosen(current_view_index, true);\n }\n };\n\n const std::string transformer_name = \"fast-switcher\";\n\n void set_view_alpha(wayfire_view view, float alpha)\n {\n if (!view->get_transformer(transformer_name))\n {\n view->add_transformer(\n std::make_unique<wf::view_2D>(view), transformer_name);\n }\n\n auto tr = dynamic_cast<wf::view_2D*>(\n view->get_transformer(transformer_name).get());\n tr->alpha = alpha;\n view->damage();\n }\n\n void update_views()\n {\n views = output->workspace->get_views_on_workspace(\n output->workspace->get_current_workspace(), wf::WM_LAYERS);\n\n std::sort(views.begin(), views.end(), [] (wayfire_view& a, wayfire_view& b)\n {\n return a->last_focus_timestamp > b->last_focus_timestamp;\n });\n }\n\n wf::key_callback fast_switch = [=] (auto)\n {\n if (active)\n {\n switch_next();\n\n return true;\n }\n\n if (!output->activate_plugin(grab_interface))\n {\n return false;\n }\n\n update_views();\n\n if (views.size() < 1)\n {\n output->deactivate_plugin(grab_interface);\n\n return false;\n }\n\n current_view_index = 0;\n active = true;\n\n \/* Set all to semi-transparent *\/\n for (auto view : views)\n {\n set_view_alpha(view, 0.7);\n }\n\n grab_interface->grab();\n switch_next();\n\n output->connect_signal(\"view-disappeared\", &cleanup_view);\n\n return true;\n };\n\n void switch_terminate()\n {\n for (auto view : views)\n {\n view->pop_transformer(transformer_name);\n }\n\n grab_interface->ungrab();\n output->deactivate_plugin(grab_interface);\n view_chosen(current_view_index, false);\n active = false;\n\n output->disconnect_signal(\"view-disappeared\", &cleanup_view);\n }\n\n void switch_next()\n {\n#define index current_view_index\n set_view_alpha(views[index], 0.7);\n index = (index + 1) % views.size();\n#undef index\n view_chosen(current_view_index, true);\n }\n\n void fini() override\n {\n if (active)\n {\n switch_terminate();\n }\n\n output->rem_binding(&fast_switch);\n }\n};\n\nDECLARE_WAYFIRE_PLUGIN(wayfire_fast_switcher);\n<|endoftext|>"} {"text":"<commit_before>\/\/ Time: O(n)\n\/\/ Space: O(n)\n\nclass Solution {\npublic:\n \/**\n * @param expression: a vector of strings;\n * @return: an integer\n *\/\n int evaluateExpression(vector<string> &expression) {\n stack<int> operands;\n stack<string> operators;\n if (expression.empty()) {\n return 0;\n }\n for (int i = expression.size() - 1; i >= 0; --i) {\n if (isdigit(expression[i][0])) {\n operands.emplace(stoi(expression[i]));\n } else if (expression[i] == \")\" || expression[i] == \"*\" ||\n expression[i] == \"\/\") {\n operators.emplace(expression[i]);\n } else if (expression[i] == \"+\" || expression[i] == \"-\") {\n while (!operators.empty() && (operators.top() == \"*\" ||\n operators.top() == \"\/\")) {\n compute(operands, operators);\n }\n operators.emplace(expression[i]);\n } else if (expression[i] == \"(\") {\n \/\/ operators at least one element, i.e. \")\".\n while (operators.top() != \")\") {\n compute(operands, operators);\n }\n operators.pop();\n }\n }\n while (!operators.empty()) {\n compute(operands, operators);\n }\n return operands.top();\n }\n\n void compute(stack<int>& operands, stack<string>& operators) {\n const int left = operands.top();\n operands.pop();\n const int right = operands.top();\n operands.pop();\n const string op = operators.top();\n operators.pop();\n\n if (op == \"+\") {\n operands.push(left + right);\n } else if (op == \"-\") {\n operands.push(left - right);\n } else if (op == \"*\") {\n operands.push(left * right);\n } else if (op == \"\/\") {\n operands.push(left \/ right);\n }\n }\n};\n\n\n\/\/ Time: O(n)\n\/\/ Space: O(n)\nclass Solution2 {\npublic:\n \/**\n * @param expression: a vector of strings;\n * @return: an integer\n *\/\n int evaluateExpression(vector<string> &expression) {\n if (expression.empty()) {\n return 0;\n }\n vector<string> postfix;\n infixToPostfix(expression, postfix);\n return evaluatePostfixExpression(postfix);\n }\n\n \/\/ Evaluate Postfix Expression.\n int evaluatePostfixExpression(const vector<string> &postfix) {\n if (postfix.empty()) {\n return 0;\n }\n stack<string> s;\n for (const auto& tok : postfix) {\n if (!is_operator(tok)) {\n s.emplace(tok);\n } else {\n int y = stoi(s.top());\n s.pop();\n int x = stoi(s.top());\n s.pop();\n if (tok[0] == '+') {\n x += y;\n } else if (tok[0] == '-') {\n x -= y;\n } else if (tok[0] == '*') {\n x *= y;\n } else {\n x \/= y;\n }\n s.emplace(to_string(x));\n }\n }\n return stoi(s.top());\n }\n\n bool is_operator(const string &op) {\n return op.length() == 1 && string(\"+-*\/\").find(op) != string::npos;\n }\n\n \/\/ Convert Infix to Postfix Expression.\n void infixToPostfix(vector<string>& infix, vector<string>& postfix) {\n stack<string> s;\n for (auto tok : infix) {\n \/\/ Any number would be pushed into stack.\n if (atoi(tok.c_str())) {\n postfix.emplace_back(tok);\n } else if (tok == \"(\") {\n s.emplace(tok);\n } else if (tok == \")\") {\n \/\/ Meet \")\", then pop until \"(\".\n while (!s.empty()) {\n tok = s.top();\n s.pop();\n if (tok == \"(\") {\n break;\n }\n postfix.emplace_back(tok);\n }\n } else {\n \/\/ Order of tokens in stack should be like \"(-*\",\n \/\/ The token will be added in an strictly increasing precedence order.\n while (!s.empty() && precedence(tok) <= precedence(s.top())) {\n postfix.emplace_back(s.top());\n s.pop();\n }\n s.emplace(tok);\n }\n }\n \/\/ Pop the remaining token and add them to the postfix.\n while (!s.empty()) {\n postfix.emplace_back(s.top());\n s.pop();\n }\n }\n\n int precedence(string x) {\n if (x == \"(\") { \/\/ The least precedence.\n return 0;\n } else if (x == \"+\" || x == \"-\") {\n return 1;\n } else if (x == \"*\" || x == \"\/\") {\n return 2;\n }\n return 3;\n }\n};\n<commit_msg>Update expression-evaluation.cpp<commit_after>\/\/ Time: O(n)\n\/\/ Space: O(n)\n\nclass Solution {\npublic:\n \/**\n * @param expression: a vector of strings;\n * @return: an integer\n *\/\n int evaluateExpression(vector<string> &expression) {\n stack<int> operands;\n stack<string> operators;\n if (expression.empty()) {\n return 0;\n }\n for (int i = expression.size() - 1; i >= 0; --i) {\n if (isdigit(expression[i][0])) {\n operands.emplace(stoi(expression[i]));\n } else if (expression[i] == \")\" || expression[i] == \"*\" ||\n expression[i] == \"\/\") {\n operators.emplace(expression[i]);\n } else if (expression[i] == \"+\" || expression[i] == \"-\") {\n while (!operators.empty() && (operators.top() == \"*\" ||\n operators.top() == \"\/\")) {\n compute(operands, operators);\n }\n operators.emplace(expression[i]);\n } else if (expression[i] == \"(\") {\n \/\/ operators at least one element, i.e. \")\".\n while (operators.top() != \")\") {\n compute(operands, operators);\n }\n operators.pop();\n }\n }\n while (!operators.empty()) {\n compute(operands, operators);\n }\n return operands.top();\n }\n\n void compute(stack<int>& operands, stack<string>& operators) {\n const int left = operands.top();\n operands.pop();\n const int right = operands.top();\n operands.pop();\n const string op = operators.top();\n operators.pop();\n if (op == \"+\") {\n operands.push(left + right);\n } else if (op == \"-\") {\n operands.push(left - right);\n } else if (op == \"*\") {\n operands.push(left * right);\n } else if (op == \"\/\") {\n operands.push(left \/ right);\n }\n }\n};\n\n\n\/\/ Time: O(n)\n\/\/ Space: O(n)\nclass Solution2 {\npublic:\n \/**\n * @param expression: a vector of strings;\n * @return: an integer\n *\/\n int evaluateExpression(vector<string> &expression) {\n if (expression.empty()) {\n return 0;\n }\n vector<string> postfix;\n infixToPostfix(expression, postfix);\n return evaluatePostfixExpression(postfix);\n }\n\n \/\/ Evaluate Postfix Expression.\n int evaluatePostfixExpression(const vector<string> &postfix) {\n if (postfix.empty()) {\n return 0;\n }\n stack<string> s;\n for (const auto& tok : postfix) {\n if (!is_operator(tok)) {\n s.emplace(tok);\n } else {\n int y = stoi(s.top());\n s.pop();\n int x = stoi(s.top());\n s.pop();\n if (tok[0] == '+') {\n x += y;\n } else if (tok[0] == '-') {\n x -= y;\n } else if (tok[0] == '*') {\n x *= y;\n } else {\n x \/= y;\n }\n s.emplace(to_string(x));\n }\n }\n return stoi(s.top());\n }\n\n bool is_operator(const string &op) {\n return op.length() == 1 && string(\"+-*\/\").find(op) != string::npos;\n }\n\n \/\/ Convert Infix to Postfix Expression.\n void infixToPostfix(vector<string>& infix, vector<string>& postfix) {\n stack<string> s;\n for (auto tok : infix) {\n \/\/ Any number would be pushed into stack.\n if (atoi(tok.c_str())) {\n postfix.emplace_back(tok);\n } else if (tok == \"(\") {\n s.emplace(tok);\n } else if (tok == \")\") {\n \/\/ Meet \")\", then pop until \"(\".\n while (!s.empty()) {\n tok = s.top();\n s.pop();\n if (tok == \"(\") {\n break;\n }\n postfix.emplace_back(tok);\n }\n } else {\n \/\/ Order of tokens in stack should be like \"(-*\",\n \/\/ The token will be added in an strictly increasing precedence order.\n while (!s.empty() && precedence(tok) <= precedence(s.top())) {\n postfix.emplace_back(s.top());\n s.pop();\n }\n s.emplace(tok);\n }\n }\n \/\/ Pop the remaining token and add them to the postfix.\n while (!s.empty()) {\n postfix.emplace_back(s.top());\n s.pop();\n }\n }\n\n int precedence(string x) {\n if (x == \"(\") { \/\/ The least precedence.\n return 0;\n } else if (x == \"+\" || x == \"-\") {\n return 1;\n } else if (x == \"*\" || x == \"\/\") {\n return 2;\n }\n return 3;\n }\n};\n<|endoftext|>"} {"text":"<commit_before>\/* BEGIN_COMMON_COPYRIGHT_HEADER\n * (c)LGPL2+\n *\n * Razor - a lightweight, Qt based, desktop toolset\n * http:\/\/razor-qt.org\n *\n * Copyright: 2012 Razor team\n * Authors:\n * Johannes Zellner <webmaster@nebulon.de>\n *\n * This program or library is free software; you can redistribute it\n * and\/or modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n\n * You should have received a copy of the GNU Lesser General\n * Public License along with this library; if not, write to the\n * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,\n * Boston, MA 02110-1301 USA\n *\n * END_COMMON_COPYRIGHT_HEADER *\/\n\n#include \"razorvolume.h\"\n\n#include <QtGui\/QMessageBox>\n#include <QtDebug>\n#include <qtxdg\/xdgicon.h>\n\n#include \"volumebutton.h\"\n#include \"volumepopup.h\"\n#include \"razorvolumeconfiguration.h\"\n#include \"pulseaudioengine.h\"\n#include \"pulseaudiodevice.h\"\n\nEXPORT_RAZOR_PANEL_PLUGIN_CPP(RazorVolume)\n\nRazorVolume::RazorVolume(const RazorPanelPluginStartInfo* startInfo, QWidget* parent):\n RazorPanelPlugin(startInfo, parent),\n m_defaultSinkIndex(0),\n m_defaultSink(0)\n{\n setObjectName(\"Volume\");\n\n m_volumeButton = new VolumeButton(panel(), this);\n addWidget(m_volumeButton);\n\n m_configWindow = new RazorVolumeConfiguration(settings(), this);\n\n m_paEngine = new PulseAudioEngine(this);\n connect(m_paEngine, SIGNAL(sinkListChanged()), this, SLOT(updateConfigurationSinkList()));\n updateConfigurationSinkList();\n}\n\nRazorVolume::~RazorVolume()\n{\n}\n\nvoid RazorVolume::showConfigureDialog()\n{\n m_configWindow->show();\n m_configWindow->raise();\n m_configWindow->activateWindow();\n}\n\nvoid RazorVolume::settingsChanged()\n{\n m_defaultSinkIndex = settings().value(\"defaultSink\", 0).toInt();\n if (m_paEngine->sinks().at(m_defaultSinkIndex)) {\n m_defaultSink = m_paEngine->sinks().at(m_defaultSinkIndex);\n m_volumeButton->m_volumePopup->setDevice(m_defaultSink);\n }\n\n m_volumeButton->setShowOnClicked(settings().value(\"showOnClick\", false).toBool());\n m_volumeButton->setMuteOnMiddleClick(settings().value(\"muteOnMiddleClick\", true).toBool());\n m_volumeButton->setMixerCommand(settings().value(\"mixerCommand\", \"pavucontrol\").toString());\n}\n\nvoid RazorVolume::updateConfigurationSinkList()\n{\n m_configWindow->setSinkList(m_paEngine->sinks());\n settingsChanged();\n}\n\n<commit_msg>panel-volume: Finally fix the default behavior to show popup<commit_after>\/* BEGIN_COMMON_COPYRIGHT_HEADER\n * (c)LGPL2+\n *\n * Razor - a lightweight, Qt based, desktop toolset\n * http:\/\/razor-qt.org\n *\n * Copyright: 2012 Razor team\n * Authors:\n * Johannes Zellner <webmaster@nebulon.de>\n *\n * This program or library is free software; you can redistribute it\n * and\/or modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n\n * You should have received a copy of the GNU Lesser General\n * Public License along with this library; if not, write to the\n * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,\n * Boston, MA 02110-1301 USA\n *\n * END_COMMON_COPYRIGHT_HEADER *\/\n\n#include \"razorvolume.h\"\n\n#include <QtGui\/QMessageBox>\n#include <QtDebug>\n#include <qtxdg\/xdgicon.h>\n\n#include \"volumebutton.h\"\n#include \"volumepopup.h\"\n#include \"razorvolumeconfiguration.h\"\n#include \"pulseaudioengine.h\"\n#include \"pulseaudiodevice.h\"\n\nEXPORT_RAZOR_PANEL_PLUGIN_CPP(RazorVolume)\n\nRazorVolume::RazorVolume(const RazorPanelPluginStartInfo* startInfo, QWidget* parent):\n RazorPanelPlugin(startInfo, parent),\n m_defaultSinkIndex(0),\n m_defaultSink(0)\n{\n setObjectName(\"Volume\");\n\n m_volumeButton = new VolumeButton(panel(), this);\n addWidget(m_volumeButton);\n\n m_configWindow = new RazorVolumeConfiguration(settings(), this);\n\n m_paEngine = new PulseAudioEngine(this);\n connect(m_paEngine, SIGNAL(sinkListChanged()), this, SLOT(updateConfigurationSinkList()));\n updateConfigurationSinkList();\n}\n\nRazorVolume::~RazorVolume()\n{\n}\n\nvoid RazorVolume::showConfigureDialog()\n{\n m_configWindow->show();\n m_configWindow->raise();\n m_configWindow->activateWindow();\n}\n\nvoid RazorVolume::settingsChanged()\n{\n m_defaultSinkIndex = settings().value(\"defaultSink\", 0).toInt();\n if (m_paEngine->sinks().at(m_defaultSinkIndex)) {\n m_defaultSink = m_paEngine->sinks().at(m_defaultSinkIndex);\n m_volumeButton->m_volumePopup->setDevice(m_defaultSink);\n }\n\n m_volumeButton->setShowOnClicked(settings().value(\"showOnClick\", true).toBool());\n m_volumeButton->setMuteOnMiddleClick(settings().value(\"muteOnMiddleClick\", true).toBool());\n m_volumeButton->setMixerCommand(settings().value(\"mixerCommand\", \"pavucontrol\").toString());\n}\n\nvoid RazorVolume::updateConfigurationSinkList()\n{\n m_configWindow->setSinkList(m_paEngine->sinks());\n settingsChanged();\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ -*- Mode: c++-mode; c-basic-offset: 2; indent-tabs-mode: t; tab-width: 2; -*-\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ gaduprotocol.cpp\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\/\/\n\/\/\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\/\/\n\/\/ Copyright (C)\t2002\tZack Rusin <zack@kde.org>\t\t\t\t\t\t\t\t\t\t\t\t\t\t\/\/\n\/\/\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\/\/\n\/\/ This program is free software; you can redistribute it and\/or\t\t\t\t\t\t\/\/\n\/\/ modify it under the terms of the GNU General Public License\t\t\t\t\t\t\t\/\/\n\/\/ as published by the Free Software Foundation; either version 2\t\t\t\t\t\t\/\/\n\/\/ of the License, or (at your option) any later version.\t\t\t\t\t\t\t\t\t\t\/\/\n\/\/\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\/\/\n\/\/ This program is distributed in the hope that it will be useful,\t\t\t\t\t\/\/\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\t\t\t\t\t\t\/\/\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\t See the\t\t\t\t\t\t\/\/\n\/\/ GNU General Public License for more details.\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\/\/\n\/\/\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\/\/\n\/\/ You should have received a copy of the GNU General Public License\t\t\t\t\/\/\n\/\/ along with this program; if not, write to the Free Software\t\t\t\t\t\t\t\/\/\n\/\/ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA\t\t\t\t\t\t\t\t\/\/\n\/\/ 02111-1307, USA.\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include <kdebug.h>\n#include <kgenericfactory.h>\n#include <kconfig.h>\n\n#include \"gaduaccount.h\"\n\n#include \"kopeteaccountmanager.h\"\n#include \"kopeteaccount.h\"\n#include \"kopetemetacontact.h\"\n\n#include \"gaducontact.h\"\n#include \"gaduprotocol.h\"\n\n#include \"gadueditaccount.h\"\n#include \"gaduaddcontactpage.h\"\n#include \"gadupreferences.h\"\n\n#include <libgadu.h>\n\nK_EXPORT_COMPONENT_FACTORY( kopete_gadu, KGenericFactory<GaduProtocol>( \"kopete_gadu\" ) );\n\nGaduProtocol* GaduProtocol::protocolStatic_ = 0L;\n\nGaduProtocol::GaduProtocol( QObject* parent, const char* name, const QStringList & )\n\t:\t\tKopeteProtocol( parent, name ),\n\t\t\tgaduStatusOffline_( KopeteOnlineStatus::Offline, 0, this, GG_STATUS_NOT_AVAIL,\n\t\t\t\t\"gg_offline\", i18n( \"Go O&ffline\" ), i18n( \"Offline\" ) ),\n\t\t\tgaduStatusOfflineDescr_( KopeteOnlineStatus::Away, 2, this, \n\t\t\t\tGG_STATUS_NOT_AVAIL_DESCR,\n\t\t\t\t\"gg_offline_d\",\t i18n( \"Go A&way\" ), i18n( \"Offline\" ) ),\n\t\t\tgaduStatusMaybeOffline_( KopeteOnlineStatus::Offline, 4, this, 0x0,\n\t\t\t\t\"gg_away\", i18n( \"Go O&ffline\" ), i18n( \"Offline\" ) ),\n\t\t\tgaduStatusBusy_(KopeteOnlineStatus::Away, 20, this, GG_STATUS_BUSY,\n\t\t\t\t\"gg_busy\",i18n( \"Go B&usy\" ), i18n( \"Busy\" ) ),\n\t\t\tgaduStatusBusyDescr_(KopeteOnlineStatus::Away, 25, this, GG_STATUS_BUSY_DESCR,\n\t\t\t\t\"gg_busy_d\",i18n( \"Go B&usy\" ),i18n( \"Busy\" ) ),\n\t\t\tgaduStatusInvisible_( KopeteOnlineStatus::Away,\t5, this, GG_STATUS_INVISIBLE,\n\t\t\t\t\"gg_invi\",i18n( \"Go I&nvisible\" ), i18n( \"Invisible\" ) ),\n\t\t\tgaduStatusInvisibleDescr_(KopeteOnlineStatus::Away, 10, this, GG_STATUS_INVISIBLE_DESCR,\n\t\t\t\t\"gg_invi_d\",i18n( \"Go I&nvisible\" ), i18n( \"Invisible\" ) ),\n\t\t\tgaduStatusAvail_(KopeteOnlineStatus::Online, 30, this, GG_STATUS_AVAIL,\n\t\t\t\t\"gg_online\",\ti18n( \"Go &Online\" ),\t\t i18n( \"Online\" ) ),\n\t\t\tgaduStatusAvailDescr_(KopeteOnlineStatus::Online, 30, this, GG_STATUS_AVAIL_DESCR,\n\t\t\t\t\"gg_online_d\",\ti18n( \"Go &Online\" ), i18n( \"Online\" ) ),\n\t\t\tgaduConnecting_(KopeteOnlineStatus::Offline, 1, this, GG_STATUS_CONNECTING,\n\t\t\t\t\"gg_con\", i18n( \"Connect\"), i18n(\"Connecting\") ),\n\t\t\tdefaultAccount_( 0 )\n{\n\tif ( protocolStatic_ )\n\t\tkdDebug(14100)<<\"####\"<<\"GaduProtocol already initialized\"<<endl;\n\telse\n\t\tprotocolStatic_ = this;\n\n\tprefs_ = new GaduPreferences( \"gadu_protocol\", this );\n\tQObject::connect( prefs_, SIGNAL(saved()), this, SLOT(settingsChanged()) );\n\taddAddressBookField( \"messaging\/gadu\", KopetePlugin::MakeIndexField );\n}\n\nGaduProtocol::~GaduProtocol()\n{\n\tprotocolStatic_ = 0L;\n}\n\nGaduProtocol*\nGaduProtocol::protocol()\n{\n\treturn protocolStatic_;\n}\n\nAddContactPage*\nGaduProtocol::createAddContactWidget( QWidget* parent, KopeteAccount* account )\n{\n\treturn new GaduAddContactPage( static_cast<GaduAccount*>( account ), parent );\n}\n\nvoid\nGaduProtocol::settingsChanged()\n{\n\n}\n\nvoid\nGaduProtocol::deserializeContact( KopeteMetaContact *metaContact,\n\t\t\t\tconst QMap<QString, QString> &serializedData,\n\t\t\t\tconst QMap<QString, QString> & \/* addressBookData *\/ )\n{\n\tkdDebug(14100)<<\"Adding \"<<serializedData[ \"contactId\" ]<<\" || \"<< serializedData[ \"displayName\" ] <<endl;\n\t\n\tconst QString aid = serializedData[ \"accountId\" ];\n\tconst QString cid = serializedData[ \"contactId\" ];\n\tconst QString dn = serializedData[ \"displayName\" ];\n\t\n\tQDict<KopeteAccount> daccounts = KopeteAccountManager::manager()->accounts(this);\n\t\n\tKopeteAccount *account = daccounts[aid];\n\tif (!account){\n\t account = createNewAccount(aid);\n\t}\n\t\n\tGaduAccount *gaccount = static_cast<GaduAccount *>(account);\n\t\n\tGaduContact *c= new GaduContact( cid.toUInt(), dn, \n\t\t\t\t\taccount, metaContact );\n\t\n\tc->setParentIdentity( aid );\n\tgaccount->addNotify( cid.toUInt() );\n\t\n\tc->setInfo(\tserializedData[\"email\"],\n\t\t\tserializedData[\"FirstName\"],\n\t\t\tserializedData[\"SecondName\"],\n\t\t\tserializedData[\"NickName\"], \n\t\t\tserializedData[\"telephone\"]);\n\t\t\n\n}\n\nuint\nGaduProtocol::statusToWithDescription( KopeteOnlineStatus status )\n{\n\t\n if ( status==gaduStatusOffline_ || status==gaduStatusOfflineDescr_){\n\treturn GG_STATUS_NOT_AVAIL_DESCR;\n }\n\t\n if ( status==gaduStatusBusyDescr_ || status==gaduStatusBusy_){\n\treturn GG_STATUS_BUSY_DESCR;\n }\n\t\t\n if ( status==gaduStatusInvisibleDescr_ || status==gaduStatusInvisible_){\n\treturn GG_STATUS_INVISIBLE_DESCR;\n }\t\n\n \/\/ this and everything else matches next return\n \/\/\t\n \/\/if ( status==gaduStatusAvailDescr_ || status==gaduStatusAvail_){\n \/\/\treturn GG_STATUS_AVAIL_DESCR;\n \/\/}\n\n return GG_STATUS_AVAIL_DESCR;\n\n}\n\nbool \nGaduProtocol::statusWithDesciption( uint status )\n{\n switch( status )\n {\n\tcase GG_STATUS_NOT_AVAIL:\n\tcase GG_STATUS_BUSY:\n\tcase GG_STATUS_INVISIBLE:\n\tcase GG_STATUS_AVAIL:\n\tcase GG_STATUS_CONNECTING:\n\t return false;\n\tcase GG_STATUS_INVISIBLE_DESCR:\n\tcase GG_STATUS_NOT_AVAIL_DESCR:\n\tcase GG_STATUS_BUSY_DESCR:\n\tcase GG_STATUS_AVAIL_DESCR:\n\t return true;\n }\n\n return false;\n}\n\nKopeteOnlineStatus\nGaduProtocol::convertStatus( uint status ) const\n{\n\tswitch( status )\n\t{\n\tcase GG_STATUS_NOT_AVAIL:\n\t\treturn gaduStatusOffline_;\n\tcase GG_STATUS_NOT_AVAIL_DESCR:\n\t\treturn gaduStatusOfflineDescr_;\n\tcase GG_STATUS_BUSY:\n\t\treturn gaduStatusBusy_;\n\tcase GG_STATUS_BUSY_DESCR:\n\t\treturn gaduStatusBusyDescr_;\n\tcase GG_STATUS_INVISIBLE:\n\t\treturn gaduStatusInvisible_;\n\tcase GG_STATUS_INVISIBLE_DESCR:\n\t\treturn gaduStatusInvisibleDescr_;\n\tcase GG_STATUS_AVAIL:\n\t\treturn gaduStatusAvail_;\n\tcase GG_STATUS_AVAIL_DESCR:\n\t\treturn gaduStatusAvailDescr_;\n\tcase GG_STATUS_CONNECTING:\n\t\treturn gaduConnecting_;\n\tdefault:\n\t\treturn gaduStatusOffline_;\n\t}\n}\n\nKopeteAccount*\nGaduProtocol::createNewAccount( const QString& accountId )\n{\n\tdefaultAccount_ = new GaduAccount( this, accountId );\n\treturn defaultAccount_ ;\n}\n\nEditAccountWidget*\nGaduProtocol::createEditAccountWidget( KopeteAccount *account, QWidget *parent )\n{\n\treturn\t(new GaduEditAccount( this, account, parent ) );\n}\n\n#include \"gaduprotocol.moc\"\n<commit_msg>make it new kopeteprotocol class compatible.<commit_after>\/\/ -*- Mode: c++-mode; c-basic-offset: 2; indent-tabs-mode: t; tab-width: 2; -*-\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ gaduprotocol.cpp\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\/\/\n\/\/\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\/\/\n\/\/ Copyright (C)\t2002\tZack Rusin <zack@kde.org>\t\t\t\t\t\t\t\t\t\t\t\t\t\t\/\/\n\/\/\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\/\/\n\/\/ This program is free software; you can redistribute it and\/or\t\t\t\t\t\t\/\/\n\/\/ modify it under the terms of the GNU General Public License\t\t\t\t\t\t\t\/\/\n\/\/ as published by the Free Software Foundation; either version 2\t\t\t\t\t\t\/\/\n\/\/ of the License, or (at your option) any later version.\t\t\t\t\t\t\t\t\t\t\/\/\n\/\/\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\/\/\n\/\/ This program is distributed in the hope that it will be useful,\t\t\t\t\t\/\/\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\t\t\t\t\t\t\/\/\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\t See the\t\t\t\t\t\t\/\/\n\/\/ GNU General Public License for more details.\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\/\/\n\/\/\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\/\/\n\/\/ You should have received a copy of the GNU General Public License\t\t\t\t\/\/\n\/\/ along with this program; if not, write to the Free Software\t\t\t\t\t\t\t\/\/\n\/\/ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA\t\t\t\t\t\t\t\t\/\/\n\/\/ 02111-1307, USA.\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include <kdebug.h>\n#include <kgenericfactory.h>\n#include <kconfig.h>\n\n#include \"gaduaccount.h\"\n\n#include \"kopeteaccountmanager.h\"\n#include \"kopeteaccount.h\"\n#include \"kopetemetacontact.h\"\n\n#include \"gaducontact.h\"\n#include \"gaduprotocol.h\"\n\n#include \"gadueditaccount.h\"\n#include \"gaduaddcontactpage.h\"\n#include \"gadupreferences.h\"\n\n#include <libgadu.h>\n\ntypedef KGenericFactory<GaduProtocol> GaduProtocolFactory;\n\nK_EXPORT_COMPONENT_FACTORY( kopete_gadu, KGenericFactory<GaduProtocol>( \"kopete_gadu\" ) );\n\nGaduProtocol* GaduProtocol::protocolStatic_ = 0L;\n\nGaduProtocol::GaduProtocol( QObject* parent, const char* name, const QStringList & )\n\t:\t\tKopeteProtocol( GaduProtocolFactory::instance(), parent, name ),\n\t\t\tgaduStatusOffline_( KopeteOnlineStatus::Offline, 0, this, GG_STATUS_NOT_AVAIL,\n\t\t\t\t\"gg_offline\", i18n( \"Go O&ffline\" ), i18n( \"Offline\" ) ),\n\t\t\tgaduStatusOfflineDescr_( KopeteOnlineStatus::Away, 2, this, \n\t\t\t\tGG_STATUS_NOT_AVAIL_DESCR,\n\t\t\t\t\"gg_offline_d\",\t i18n( \"Go A&way\" ), i18n( \"Offline\" ) ),\n\t\t\tgaduStatusMaybeOffline_( KopeteOnlineStatus::Offline, 4, this, 0x0,\n\t\t\t\t\"gg_away\", i18n( \"Go O&ffline\" ), i18n( \"Offline\" ) ),\n\t\t\tgaduStatusBusy_(KopeteOnlineStatus::Away, 20, this, GG_STATUS_BUSY,\n\t\t\t\t\"gg_busy\",i18n( \"Go B&usy\" ), i18n( \"Busy\" ) ),\n\t\t\tgaduStatusBusyDescr_(KopeteOnlineStatus::Away, 25, this, GG_STATUS_BUSY_DESCR,\n\t\t\t\t\"gg_busy_d\",i18n( \"Go B&usy\" ),i18n( \"Busy\" ) ),\n\t\t\tgaduStatusInvisible_( KopeteOnlineStatus::Away,\t5, this, GG_STATUS_INVISIBLE,\n\t\t\t\t\"gg_invi\",i18n( \"Go I&nvisible\" ), i18n( \"Invisible\" ) ),\n\t\t\tgaduStatusInvisibleDescr_(KopeteOnlineStatus::Away, 10, this, GG_STATUS_INVISIBLE_DESCR,\n\t\t\t\t\"gg_invi_d\",i18n( \"Go I&nvisible\" ), i18n( \"Invisible\" ) ),\n\t\t\tgaduStatusAvail_(KopeteOnlineStatus::Online, 30, this, GG_STATUS_AVAIL,\n\t\t\t\t\"gg_online\",\ti18n( \"Go &Online\" ),\t\t i18n( \"Online\" ) ),\n\t\t\tgaduStatusAvailDescr_(KopeteOnlineStatus::Online, 30, this, GG_STATUS_AVAIL_DESCR,\n\t\t\t\t\"gg_online_d\",\ti18n( \"Go &Online\" ), i18n( \"Online\" ) ),\n\t\t\tgaduConnecting_(KopeteOnlineStatus::Offline, 1, this, GG_STATUS_CONNECTING,\n\t\t\t\t\"gg_con\", i18n( \"Connect\"), i18n(\"Connecting\") ),\n\t\t\tdefaultAccount_( 0 )\n{\n\tif ( protocolStatic_ )\n\t\tkdDebug(14100)<<\"####\"<<\"GaduProtocol already initialized\"<<endl;\n\telse\n\t\tprotocolStatic_ = this;\n\n\tprefs_ = new GaduPreferences( \"gadu_protocol\", this );\n\tQObject::connect( prefs_, SIGNAL(saved()), this, SLOT(settingsChanged()) );\n\taddAddressBookField( \"messaging\/gadu\", KopetePlugin::MakeIndexField );\n}\n\nGaduProtocol::~GaduProtocol()\n{\n\tprotocolStatic_ = 0L;\n}\n\nGaduProtocol*\nGaduProtocol::protocol()\n{\n\treturn protocolStatic_;\n}\n\nAddContactPage*\nGaduProtocol::createAddContactWidget( QWidget* parent, KopeteAccount* account )\n{\n\treturn new GaduAddContactPage( static_cast<GaduAccount*>( account ), parent );\n}\n\nvoid\nGaduProtocol::settingsChanged()\n{\n\n}\n\nvoid\nGaduProtocol::deserializeContact( KopeteMetaContact *metaContact,\n\t\t\t\tconst QMap<QString, QString> &serializedData,\n\t\t\t\tconst QMap<QString, QString> & \/* addressBookData *\/ )\n{\n\tkdDebug(14100)<<\"Adding \"<<serializedData[ \"contactId\" ]<<\" || \"<< serializedData[ \"displayName\" ] <<endl;\n\t\n\tconst QString aid = serializedData[ \"accountId\" ];\n\tconst QString cid = serializedData[ \"contactId\" ];\n\tconst QString dn = serializedData[ \"displayName\" ];\n\t\n\tQDict<KopeteAccount> daccounts = KopeteAccountManager::manager()->accounts(this);\n\t\n\tKopeteAccount *account = daccounts[aid];\n\tif (!account){\n\t account = createNewAccount(aid);\n\t}\n\t\n\tGaduAccount *gaccount = static_cast<GaduAccount *>(account);\n\t\n\tGaduContact *c= new GaduContact( cid.toUInt(), dn, \n\t\t\t\t\taccount, metaContact );\n\t\n\tc->setParentIdentity( aid );\n\tgaccount->addNotify( cid.toUInt() );\n\t\n\tc->setInfo(\tserializedData[\"email\"],\n\t\t\tserializedData[\"FirstName\"],\n\t\t\tserializedData[\"SecondName\"],\n\t\t\tserializedData[\"NickName\"], \n\t\t\tserializedData[\"telephone\"]);\n\t\t\n\n}\n\nuint\nGaduProtocol::statusToWithDescription( KopeteOnlineStatus status )\n{\n\t\n if ( status==gaduStatusOffline_ || status==gaduStatusOfflineDescr_){\n\treturn GG_STATUS_NOT_AVAIL_DESCR;\n }\n\t\n if ( status==gaduStatusBusyDescr_ || status==gaduStatusBusy_){\n\treturn GG_STATUS_BUSY_DESCR;\n }\n\t\t\n if ( status==gaduStatusInvisibleDescr_ || status==gaduStatusInvisible_){\n\treturn GG_STATUS_INVISIBLE_DESCR;\n }\t\n\n \/\/ this and everything else matches next return\n \/\/\t\n \/\/if ( status==gaduStatusAvailDescr_ || status==gaduStatusAvail_){\n \/\/\treturn GG_STATUS_AVAIL_DESCR;\n \/\/}\n\n return GG_STATUS_AVAIL_DESCR;\n\n}\n\nbool \nGaduProtocol::statusWithDesciption( uint status )\n{\n switch( status )\n {\n\tcase GG_STATUS_NOT_AVAIL:\n\tcase GG_STATUS_BUSY:\n\tcase GG_STATUS_INVISIBLE:\n\tcase GG_STATUS_AVAIL:\n\tcase GG_STATUS_CONNECTING:\n\t return false;\n\tcase GG_STATUS_INVISIBLE_DESCR:\n\tcase GG_STATUS_NOT_AVAIL_DESCR:\n\tcase GG_STATUS_BUSY_DESCR:\n\tcase GG_STATUS_AVAIL_DESCR:\n\t return true;\n }\n\n return false;\n}\n\nKopeteOnlineStatus\nGaduProtocol::convertStatus( uint status ) const\n{\n\tswitch( status )\n\t{\n\tcase GG_STATUS_NOT_AVAIL:\n\t\treturn gaduStatusOffline_;\n\tcase GG_STATUS_NOT_AVAIL_DESCR:\n\t\treturn gaduStatusOfflineDescr_;\n\tcase GG_STATUS_BUSY:\n\t\treturn gaduStatusBusy_;\n\tcase GG_STATUS_BUSY_DESCR:\n\t\treturn gaduStatusBusyDescr_;\n\tcase GG_STATUS_INVISIBLE:\n\t\treturn gaduStatusInvisible_;\n\tcase GG_STATUS_INVISIBLE_DESCR:\n\t\treturn gaduStatusInvisibleDescr_;\n\tcase GG_STATUS_AVAIL:\n\t\treturn gaduStatusAvail_;\n\tcase GG_STATUS_AVAIL_DESCR:\n\t\treturn gaduStatusAvailDescr_;\n\tcase GG_STATUS_CONNECTING:\n\t\treturn gaduConnecting_;\n\tdefault:\n\t\treturn gaduStatusOffline_;\n\t}\n}\n\nKopeteAccount*\nGaduProtocol::createNewAccount( const QString& accountId )\n{\n\tdefaultAccount_ = new GaduAccount( this, accountId );\n\treturn defaultAccount_ ;\n}\n\nEditAccountWidget*\nGaduProtocol::createEditAccountWidget( KopeteAccount *account, QWidget *parent )\n{\n\treturn\t(new GaduEditAccount( this, account, parent ) );\n}\n\n#include \"gaduprotocol.moc\"\n<|endoftext|>"} {"text":"<commit_before>\/\/ Standard includes\n#include <iostream>\n#include <cstdlib>\n#include <unistd.h>\n#include <cmath>\n#include <string.h>\n#include <inttypes.h>\n#include <fstream>\n#include <sys\/time.h>\n#include <limits.h>\n\n\/\/ Serial includes\n#include <stdio.h> \/* Standard input\/output definitions *\/\n#include <string.h> \/* String function definitions *\/\n#include <unistd.h> \/* UNIX standard function definitions *\/\n#include <fcntl.h> \/* File control definitions *\/\n#include <errno.h> \/* Error number definitions *\/\n#include <termios.h> \/* POSIX terminal control definitions *\/\n#\n#ifdef __linux\n#include <sys\/ioctl.h>\n#endif\n\n\/\/#include \"serialwifly.h\" \t\/\/ this is from Louis' wifly code, which will be a library\n#include \"serial_lib\/wifly_serial.h\" \/\/ include the new class for handling a wifly\n#include \"common.h\"\n#include \"wifly_thread.h\"\n\/\/ #include \"test.h\" \t\t\t\/\/ for bearing calculation\n#include \"commander.h\"\n#include \"bearing_lib\/bearing.h\"\t\t\/\/ this should be all the functions required for bearing calculations\n\nusing std::string;\nusing std::vector;\nusing namespace std;\n\n\/* this is to help with some of the rotation logic *\/\nbool in_rotation = false;\n\n\/* keep track of the previous hunt state, as hunt state is sent periodically, not just on updates *\/\nuint8_t prev_hunt_state = 10;\n\n\/* whether or not we are currently rotating *\/\nbool rotating = false;\n\n\/* whether or not we are currently moving *\/\nbool moving = false;\n\n\/* microsecond timestamp of the previous loop iteration *\/\nunsigned long prev_loop_timestamp = 0;\n\n\nvoid update_state(uint8_t &new_state) {\n\n\tswitch (new_state) {\n\tcase TRACKING_HUNT_STATE_ROTATE:\n\t\trotating = true;\n\t\tbreak;\n\tcase TRACKING_HUNT_STATE_MOVE:\n\t\tmoving = true;\n\t\tbreak;\n\tcase TRACKING_HUNT_STATE_OFF:\n\t\t\/\/ finished = true;\n\t\tbreak;\n\tcase TRACKING_HUNT_STATE_START:\n\t\t\/\/ starting = true;\n\t\tbreak;\n\t}\n}\n\n\nvoid *wifly_thread(void *param) {\n\t\n\t\/\/ retrieve the MAVInfo struct that is sent to this function as a parameter\n\tstruct MAVInfo *uavData = (struct MAVInfo *)param;\n\t\n\t\/\/ some constants that all need to become parameters\n\tint num_samples = 1;\n\tchar *ssid = (char *) \"JAMMER01\";\n\tchar *file_name = (char *) \"wifly.csv\";\n\tchar *file_name2 = (char *) \"wifly2.csv\";\n\tchar *bearing_file_name = (char *) \"bearing_calc_cc.csv\";\n\tchar *bearing_mle_file_name = (char *) \"bearing_calc_mle.csv\";\n\t\/\/ char *port = (char *) \"\/dev\/ttyUSB0\";\n\n\t\/\/ connect to the first wifly\n\tWiflySerial* wifly1 = new WiflySerial(verbose, wifly_port1);\n\tif (wifly1->fd < 0) {\n\t\tprintf(\"Error opening wifly connection\\n\");\n\t\treturn NULL;\n\t}\n\n\t\/\/ connect to the second wifly\n\tWiflySerial* wifly2 = nullptr;\n\tif (dual_wifly) {\n\t\twifly2 = new WiflySerial(verbose, wifly_port2);\n\t\tif (wifly2->fd < 0) {\n\t\t\tprintf(\"Error opening wifly connection\\n\");\n\t\t\treturn NULL;\n\t\t}\n\t}\n\n\t\n\t\/* Go into command mode *\/\n\twifly1->enter_commandmode();\n\tif (dual_wifly) {\n\t\twifly2->enter_commandmode();\n\t}\n\n\n\t\/* Open a file to write values to *\/\n\t\/* Appending values *\/\n\tFILE *wifly_file = fopen(file_name, \"a\");\n\tif (wifly_file == NULL)\n\t{\n\t\t\/\/ TODO: figure out what we do want to return when there is an error\n\t\tprintf(\"Error opening wifly output file\\n\");\n\t\treturn NULL;\n\t}\n\n\n\tFILE *wifly_file2 = NULL;\n\tif (dual_wifly) {\n\t\twifly_file2 = fopen(file_name2, \"a\");\n\t\tif (wifly_file2 == NULL) {\n\t\t\t\/\/ TODO: figure out what we do want to return when there is an error\n\t\t\tprintf(\"Error opening wifly2 output file\\n\");\n\t\t\treturn NULL;\n\t\t}\n\t}\n\t\n\n\t\/* Open a file to write bearing calcs to *\/\n\tFILE *bearing_file = fopen(bearing_file_name, \"a\");\n\tif (bearing_file == NULL)\n\t{\n\t\t\/\/ TODO: figure out what we do want to return when there is an error\n\t\tprintf(\"Error opening bearing output file\\n\");\n\t\treturn NULL;\n\t}\n\n\tFILE *bearing_file_mle = NULL;\n\tif (dual_wifly) {\n\t\tbearing_file_mle = fopen(bearing_mle_file_name, \"a\");\n\t\tif (bearing_file_mle == NULL) {\n\t\t\tprintf(\"Error opening bearing mle output file\\n\");\n\t\t\treturn NULL;\n\t\t}\n\t}\n\n\n\tif (get_commands) {\n\t\tbool loaded = load_move_commands();\n\t\tif (!loaded) {\n\t\t\tprintf(\"Error loading move commands\\n\");\n\t\t\treturn NULL;\n\t\t}\n\t}\n\t\n\tvector<double> angles;\n\tvector<double> gains;\n\tvector<double> omni_gains;\n\tvector<int> norm_gains;\n\n\tstruct timeval tv;\n\n\n\n\t\/\/ main loop that should be constantly taking measurements\n\t\/\/ until the main program is stopped\n\twhile (RUNNING_FLAG) {\n\n\t\t\/\/ only want to execute this at most ever 30 ms\n\t\t\/\/ basically does a dynamic sleep in the sense that if there is a lot of processing time for doing the bearing\n\t\t\/\/ calculation, we will only pause as long as required so measurements are really made every 30 ms\n\t\t\/\/ (unless of course bearing calculations take too long)\n\t\tgettimeofday(&tv, NULL);\n\t\tunsigned long current_loop_time = 1000000 * tv.tv_sec + tv.tv_usec;\n\t\tif (prev_loop_timestamp != 0 && (current_loop_time - prev_loop_timestamp) < 30000) {\n\t\t\tcontinue;\n\t\t}\n\t\tprev_loop_timestamp = current_loop_time;\n\n\t\t\/\/ handle hunt state changes required (sending of commands)\n\t\tif (uavData->tracking_status.hunt_mode_state != prev_hunt_state) {\n\t\t\t\n\t\t\tprintf(\"State changed from %u to %u\\n\", prev_hunt_state, uavData->tracking_status.hunt_mode_state);\n\n\t\t\tif (uavData->tracking_status.hunt_mode_state == TRACKING_HUNT_STATE_WAIT) {\n\t\t\t\tsend_next_command(prev_hunt_state, uavData->tracking_status.hunt_mode_state);\n\t\t\t\t\n\t\t\t\t\/\/ TODO: maybe want to update the state immediately here...\n\t\t\t} else {\n\t\t\t\tupdate_state(uavData->tracking_status.hunt_mode_state);\n\t\t\t}\n\t\t\t\n\t\t\t\n\t\t\t\/\/ update the prev hunt state to be this new state\n\t\t\tprev_hunt_state = uavData->tracking_status.hunt_mode_state;\n\t\t\tprintf(\"Prev State changed to: %u\\n\", prev_hunt_state);\n\t\t}\n\t\n\t\t\/\/ make measurements (depending on the current state)\n\t\tint dir_rssi = INT_MAX;\n\t\tint omni_rssi = INT_MAX;\n\n\t\t\/* check if we are in an official rotation *\/\n\t\tif (rotating) {\n\t\t\tif (!in_rotation) {\n\t\t\t\tprintf(\"rotation started\\n\");\n\t\t\t\t\/\/ set our logic to mark we are now running the rotation logic\n\t\t\t\tin_rotation = true;\n\n\t\t\t\t\/\/ clear the vectors\n\t\t\t\tangles.clear();\n\t\t\t\tgains.clear();\n\t\t\t\tomni_gains.clear();\n\t\t\t\tnorm_gains.clear();\n\t\t\t}\n\n\t\t\tprintf(\"rotating\\n\");\n\t\t\tangles.push_back((double) uavData->vfr_hud.heading);\n\t\t\tdir_rssi = wifly1->scanrssi(ssid);\n\t\t\tgains.push_back(dir_rssi);\n\n\t\t\tif (dual_wifly) {\n\t\t\t\tomni_rssi = wifly2->scanrssi(ssid);\n\t\t\t\tomni_gains.push_back(omni_rssi);\n\n\t\t\t\t\/\/ calculate the normalized gains\n\t\t\t\tnorm_gains.push_back(gains2normgain(dir_rssi, omni_rssi));\n\n\t\t\t\t\/\/ do constant calculation of bearing\n\t\t\t\tprintf(\"calculating bearing mle\\n\");\n\t\t\t\tdouble curr_bearing_est = get_bearing_mle(angles, norm_gains);\n\t\t\t\tfprintf(bearing_file_mle, \"%llu,%i,%i,%f,%f\\n\", uavData->sys_time_us.time_unix_usec,\n\t\t\t\t\tuavData->gps_position.lat, uavData->gps_position.lon, uavData->vfr_hud.alt, curr_bearing_est);\n\n\t\t\t\t\/\/ TODO: send mle bearing message here!\n\n\t\t\t}\n\t\t}\n\n\t\t\/* catch the end of a rotation in order to do the cc gain measurement *\/\n\t\tif (!rotating && in_rotation) {\n\t\t\tprintf(\"ended rotation\\n\");\n\t\t\tin_rotation = false;\n\n\t\t\tprintf(\"calculating cc bearing\\n\");\n\t\t\t\/\/ do bearing calculation at this point\n\t\t\t\/\/ double bearing = get_bearing_cc(angles, gains);\n\t\t\tdouble bearing = 32.0;\n\n\t\t\t\/\/ write the lat, lon, alt and bearing to file\n\t\t\tfprintf(bearing_file, \"%llu,%i,%i,%f,%f\\n\", uavData->sys_time_us.time_unix_usec,\n\t\t\t\tuavData->gps_position.lat, uavData->gps_position.lon, uavData->vfr_hud.alt, bearing);\n\n\t\t\t\/\/ send a mavlink message of the calculated bearing\n\t\t\tsend_bearing_message(bearing, uavData->gps_position.lat, uavData->gps_position.lon, uavData->vfr_hud.alt);\n\n\t\t\t\/\/ tell pixhawk we are finished with the rotation\n\t\t\t\/\/ send_finish_command();\n\t\t}\n\n\t\t\/* no need to make another measurement to write to the file if we already made one *\/\n\t\tif (rotating) {\n\t\t\tprintf(\"writing directly to file\\n\");\n\t\t\t\/* write the directional measurement information *\/\n\t\t\tfprintf(wifly_file, \"%llu,%u,%i,%i,%i,%f,%i\\n\",\n\t\t\t\tuavData->sys_time_us.time_unix_usec, uavData->custom_mode, uavData->vfr_hud.heading,\n\t\t\t\tuavData->gps_position.lat, uavData->gps_position.lon, uavData->vfr_hud.alt, dir_rssi);\n\n\t\t\t\/* write the omni measurement as needed *\/\n\t\t\tif (dual_wifly) {\n\t\t\t\tfprintf(wifly_file2, \"%llu,%u,%i,%i,%i,%f,%i\\n\",\n\t\t\t\t\tuavData->sys_time_us.time_unix_usec, uavData->custom_mode, uavData->vfr_hud.heading,\n\t\t\t\t\tuavData->gps_position.lat, uavData->gps_position.lon, uavData->vfr_hud.alt, omni_rssi);\n\t\t\t}\n\t\t\n\t\t} else { \/* need to make a measurement to save to the file *\/\n\n\t\t\tprintf(\"making measurement for writing to file\\n\");\n\n\t\t\tstd::cout << \"wifly1 fd \" << wifly1->fd << \"\\n\";\n\n\t\t\t\/* Scan values to this file *\/\n\t\t\t\/* Add degree at which you measure first *\/\n\t\t\tfprintf(wifly_file, \"%llu,%u,%i,%i,%i,%f,\",\n\t\t\t\tuavData->sys_time_us.time_unix_usec, uavData->custom_mode, uavData->vfr_hud.heading,\n\t\t\t\tuavData->gps_position.lat, uavData->gps_position.lon, uavData->vfr_hud.alt);\n\n\t\t\tdir_rssi = wifly1->scanrssi_f(ssid, wifly_file, num_samples);\n\t\t\tcout << uavData->vfr_hud.heading << \": wifly1: \" << dir_rssi << \"\\n\";\n\n\t\t\tif (dual_wifly) {\n\n\t\t\t\tfprintf(wifly_file2, \"%llu,%u,%i,%i,%i,%f,\",\n\t\t\t\t\tuavData->sys_time_us.time_unix_usec, uavData->custom_mode, uavData->vfr_hud.heading,\n\t\t\t\t\tuavData->gps_position.lat, uavData->gps_position.lon, uavData->vfr_hud.alt);\n\n\t\t\t\tomni_rssi = wifly2->scanrssi_f(ssid, wifly_file2, num_samples);\n\t\t\t\tcout << uavData->vfr_hud.heading << \": wifly2: \" << omni_rssi << \"\\n\";\n\t\t\t}\n\n\t\t}\n\n\t\t\/\/ send a mavlink message with the current rssi\n\t\tsend_rssi_message(dir_rssi, uavData->vfr_hud.heading, uavData->gps_position.lat, uavData->gps_position.lon, uavData->vfr_hud.alt);\n\n\t\t\/\/ TODO: send mavlink message of calculated rssi...\n\n\t\t\/\/ send a message with a rotate command for testing purposes at the moment\n\t\t\/\/ sendRotateCommand(-1.0);\n\t\t\n\t\t\/* sleep for some time before making another measurement (30 ms for now) *\/\n\t\t\/\/ usleep(30000);\n\t\t\n\t}\n\t\n\t\n\t\/* Be sure to close the output file and connection *\/\n\tfclose(wifly_file);\n\tfclose(bearing_file);\n\twifly1->end_serial();\n\n\tif (dual_wifly) {\n\t\tfclose(wifly_file2);\n\t\tfclose(bearing_file_mle);\n\t\twifly2->end_serial();\n\t}\n\n\treturn NULL;\n}\n<commit_msg>looking for ADL again for testing<commit_after>\/\/ Standard includes\n#include <iostream>\n#include <cstdlib>\n#include <unistd.h>\n#include <cmath>\n#include <string.h>\n#include <inttypes.h>\n#include <fstream>\n#include <sys\/time.h>\n#include <limits.h>\n\n\/\/ Serial includes\n#include <stdio.h> \/* Standard input\/output definitions *\/\n#include <string.h> \/* String function definitions *\/\n#include <unistd.h> \/* UNIX standard function definitions *\/\n#include <fcntl.h> \/* File control definitions *\/\n#include <errno.h> \/* Error number definitions *\/\n#include <termios.h> \/* POSIX terminal control definitions *\/\n#\n#ifdef __linux\n#include <sys\/ioctl.h>\n#endif\n\n\/\/#include \"serialwifly.h\" \t\/\/ this is from Louis' wifly code, which will be a library\n#include \"serial_lib\/wifly_serial.h\" \/\/ include the new class for handling a wifly\n#include \"common.h\"\n#include \"wifly_thread.h\"\n\/\/ #include \"test.h\" \t\t\t\/\/ for bearing calculation\n#include \"commander.h\"\n#include \"bearing_lib\/bearing.h\"\t\t\/\/ this should be all the functions required for bearing calculations\n\nusing std::string;\nusing std::vector;\nusing namespace std;\n\n\/* this is to help with some of the rotation logic *\/\nbool in_rotation = false;\n\n\/* keep track of the previous hunt state, as hunt state is sent periodically, not just on updates *\/\nuint8_t prev_hunt_state = 10;\n\n\/* whether or not we are currently rotating *\/\nbool rotating = false;\n\n\/* whether or not we are currently moving *\/\nbool moving = false;\n\n\/* microsecond timestamp of the previous loop iteration *\/\nunsigned long prev_loop_timestamp = 0;\n\n\nvoid update_state(uint8_t &new_state) {\n\n\tswitch (new_state) {\n\tcase TRACKING_HUNT_STATE_ROTATE:\n\t\trotating = true;\n\t\tbreak;\n\tcase TRACKING_HUNT_STATE_MOVE:\n\t\tmoving = true;\n\t\tbreak;\n\tcase TRACKING_HUNT_STATE_OFF:\n\t\t\/\/ finished = true;\n\t\tbreak;\n\tcase TRACKING_HUNT_STATE_START:\n\t\t\/\/ starting = true;\n\t\tbreak;\n\t}\n}\n\n\nvoid *wifly_thread(void *param) {\n\t\n\t\/\/ retrieve the MAVInfo struct that is sent to this function as a parameter\n\tstruct MAVInfo *uavData = (struct MAVInfo *)param;\n\t\n\t\/\/ some constants that all need to become parameters\n\tint num_samples = 1;\n\tchar *ssid = (char *) \"ADL\"; \/\/ \"JAMMER01\";\n\tchar *file_name = (char *) \"wifly.csv\";\n\tchar *file_name2 = (char *) \"wifly2.csv\";\n\tchar *bearing_file_name = (char *) \"bearing_calc_cc.csv\";\n\tchar *bearing_mle_file_name = (char *) \"bearing_calc_mle.csv\";\n\t\/\/ char *port = (char *) \"\/dev\/ttyUSB0\";\n\n\t\/\/ connect to the first wifly\n\tWiflySerial* wifly1 = new WiflySerial(verbose, wifly_port1);\n\tif (wifly1->fd < 0) {\n\t\tprintf(\"Error opening wifly connection\\n\");\n\t\treturn NULL;\n\t}\n\n\t\/\/ connect to the second wifly\n\tWiflySerial* wifly2 = nullptr;\n\tif (dual_wifly) {\n\t\twifly2 = new WiflySerial(verbose, wifly_port2);\n\t\tif (wifly2->fd < 0) {\n\t\t\tprintf(\"Error opening wifly connection\\n\");\n\t\t\treturn NULL;\n\t\t}\n\t}\n\n\t\n\t\/* Go into command mode *\/\n\twifly1->enter_commandmode();\n\tif (dual_wifly) {\n\t\twifly2->enter_commandmode();\n\t}\n\n\n\t\/* Open a file to write values to *\/\n\t\/* Appending values *\/\n\tFILE *wifly_file = fopen(file_name, \"a\");\n\tif (wifly_file == NULL)\n\t{\n\t\t\/\/ TODO: figure out what we do want to return when there is an error\n\t\tprintf(\"Error opening wifly output file\\n\");\n\t\treturn NULL;\n\t}\n\n\n\tFILE *wifly_file2 = NULL;\n\tif (dual_wifly) {\n\t\twifly_file2 = fopen(file_name2, \"a\");\n\t\tif (wifly_file2 == NULL) {\n\t\t\t\/\/ TODO: figure out what we do want to return when there is an error\n\t\t\tprintf(\"Error opening wifly2 output file\\n\");\n\t\t\treturn NULL;\n\t\t}\n\t}\n\t\n\n\t\/* Open a file to write bearing calcs to *\/\n\tFILE *bearing_file = fopen(bearing_file_name, \"a\");\n\tif (bearing_file == NULL)\n\t{\n\t\t\/\/ TODO: figure out what we do want to return when there is an error\n\t\tprintf(\"Error opening bearing output file\\n\");\n\t\treturn NULL;\n\t}\n\n\tFILE *bearing_file_mle = NULL;\n\tif (dual_wifly) {\n\t\tbearing_file_mle = fopen(bearing_mle_file_name, \"a\");\n\t\tif (bearing_file_mle == NULL) {\n\t\t\tprintf(\"Error opening bearing mle output file\\n\");\n\t\t\treturn NULL;\n\t\t}\n\t}\n\n\n\tif (get_commands) {\n\t\tbool loaded = load_move_commands();\n\t\tif (!loaded) {\n\t\t\tprintf(\"Error loading move commands\\n\");\n\t\t\treturn NULL;\n\t\t}\n\t}\n\t\n\tvector<double> angles;\n\tvector<double> gains;\n\tvector<double> omni_gains;\n\tvector<int> norm_gains;\n\n\tstruct timeval tv;\n\n\n\n\t\/\/ main loop that should be constantly taking measurements\n\t\/\/ until the main program is stopped\n\twhile (RUNNING_FLAG) {\n\n\t\t\/\/ only want to execute this at most ever 30 ms\n\t\t\/\/ basically does a dynamic sleep in the sense that if there is a lot of processing time for doing the bearing\n\t\t\/\/ calculation, we will only pause as long as required so measurements are really made every 30 ms\n\t\t\/\/ (unless of course bearing calculations take too long)\n\t\tgettimeofday(&tv, NULL);\n\t\tunsigned long current_loop_time = 1000000 * tv.tv_sec + tv.tv_usec;\n\t\tif (prev_loop_timestamp != 0 && (current_loop_time - prev_loop_timestamp) < 30000) {\n\t\t\tcontinue;\n\t\t}\n\t\tprev_loop_timestamp = current_loop_time;\n\n\t\t\/\/ handle hunt state changes required (sending of commands)\n\t\tif (uavData->tracking_status.hunt_mode_state != prev_hunt_state) {\n\t\t\t\n\t\t\tprintf(\"State changed from %u to %u\\n\", prev_hunt_state, uavData->tracking_status.hunt_mode_state);\n\n\t\t\tif (uavData->tracking_status.hunt_mode_state == TRACKING_HUNT_STATE_WAIT) {\n\t\t\t\tsend_next_command(prev_hunt_state, uavData->tracking_status.hunt_mode_state);\n\t\t\t\t\n\t\t\t\t\/\/ TODO: maybe want to update the state immediately here...\n\t\t\t} else {\n\t\t\t\tupdate_state(uavData->tracking_status.hunt_mode_state);\n\t\t\t}\n\t\t\t\n\t\t\t\n\t\t\t\/\/ update the prev hunt state to be this new state\n\t\t\tprev_hunt_state = uavData->tracking_status.hunt_mode_state;\n\t\t\tprintf(\"Prev State changed to: %u\\n\", prev_hunt_state);\n\t\t}\n\t\n\t\t\/\/ make measurements (depending on the current state)\n\t\tint dir_rssi = INT_MAX;\n\t\tint omni_rssi = INT_MAX;\n\n\t\t\/* check if we are in an official rotation *\/\n\t\tif (rotating) {\n\t\t\tif (!in_rotation) {\n\t\t\t\tprintf(\"rotation started\\n\");\n\t\t\t\t\/\/ set our logic to mark we are now running the rotation logic\n\t\t\t\tin_rotation = true;\n\n\t\t\t\t\/\/ clear the vectors\n\t\t\t\tangles.clear();\n\t\t\t\tgains.clear();\n\t\t\t\tomni_gains.clear();\n\t\t\t\tnorm_gains.clear();\n\t\t\t}\n\n\t\t\tprintf(\"rotating\\n\");\n\t\t\tangles.push_back((double) uavData->vfr_hud.heading);\n\t\t\tdir_rssi = wifly1->scanrssi(ssid);\n\t\t\tgains.push_back(dir_rssi);\n\n\t\t\tif (dual_wifly) {\n\t\t\t\tomni_rssi = wifly2->scanrssi(ssid);\n\t\t\t\tomni_gains.push_back(omni_rssi);\n\n\t\t\t\t\/\/ calculate the normalized gains\n\t\t\t\tnorm_gains.push_back(gains2normgain(dir_rssi, omni_rssi));\n\n\t\t\t\t\/\/ do constant calculation of bearing\n\t\t\t\tprintf(\"calculating bearing mle\\n\");\n\t\t\t\tdouble curr_bearing_est = get_bearing_mle(angles, norm_gains);\n\t\t\t\tfprintf(bearing_file_mle, \"%llu,%i,%i,%f,%f\\n\", uavData->sys_time_us.time_unix_usec,\n\t\t\t\t\tuavData->gps_position.lat, uavData->gps_position.lon, uavData->vfr_hud.alt, curr_bearing_est);\n\n\t\t\t\t\/\/ TODO: send mle bearing message here!\n\n\t\t\t}\n\t\t}\n\n\t\t\/* catch the end of a rotation in order to do the cc gain measurement *\/\n\t\tif (!rotating && in_rotation) {\n\t\t\tprintf(\"ended rotation\\n\");\n\t\t\tin_rotation = false;\n\n\t\t\tprintf(\"calculating cc bearing\\n\");\n\t\t\t\/\/ do bearing calculation at this point\n\t\t\t\/\/ double bearing = get_bearing_cc(angles, gains);\n\t\t\tdouble bearing = 32.0;\n\n\t\t\t\/\/ write the lat, lon, alt and bearing to file\n\t\t\tfprintf(bearing_file, \"%llu,%i,%i,%f,%f\\n\", uavData->sys_time_us.time_unix_usec,\n\t\t\t\tuavData->gps_position.lat, uavData->gps_position.lon, uavData->vfr_hud.alt, bearing);\n\n\t\t\t\/\/ send a mavlink message of the calculated bearing\n\t\t\tsend_bearing_message(bearing, uavData->gps_position.lat, uavData->gps_position.lon, uavData->vfr_hud.alt);\n\n\t\t\t\/\/ tell pixhawk we are finished with the rotation\n\t\t\t\/\/ send_finish_command();\n\t\t}\n\n\t\t\/* no need to make another measurement to write to the file if we already made one *\/\n\t\tif (rotating) {\n\t\t\tprintf(\"writing directly to file\\n\");\n\t\t\t\/* write the directional measurement information *\/\n\t\t\tfprintf(wifly_file, \"%llu,%u,%i,%i,%i,%f,%i\\n\",\n\t\t\t\tuavData->sys_time_us.time_unix_usec, uavData->custom_mode, uavData->vfr_hud.heading,\n\t\t\t\tuavData->gps_position.lat, uavData->gps_position.lon, uavData->vfr_hud.alt, dir_rssi);\n\n\t\t\t\/* write the omni measurement as needed *\/\n\t\t\tif (dual_wifly) {\n\t\t\t\tfprintf(wifly_file2, \"%llu,%u,%i,%i,%i,%f,%i\\n\",\n\t\t\t\t\tuavData->sys_time_us.time_unix_usec, uavData->custom_mode, uavData->vfr_hud.heading,\n\t\t\t\t\tuavData->gps_position.lat, uavData->gps_position.lon, uavData->vfr_hud.alt, omni_rssi);\n\t\t\t}\n\t\t\n\t\t} else { \/* need to make a measurement to save to the file *\/\n\n\t\t\tprintf(\"making measurement for writing to file\\n\");\n\n\t\t\tstd::cout << \"wifly1 fd \" << wifly1->fd << \"\\n\";\n\n\t\t\t\/* Scan values to this file *\/\n\t\t\t\/* Add degree at which you measure first *\/\n\t\t\tfprintf(wifly_file, \"%llu,%u,%i,%i,%i,%f,\",\n\t\t\t\tuavData->sys_time_us.time_unix_usec, uavData->custom_mode, uavData->vfr_hud.heading,\n\t\t\t\tuavData->gps_position.lat, uavData->gps_position.lon, uavData->vfr_hud.alt);\n\n\t\t\tdir_rssi = wifly1->scanrssi_f(ssid, wifly_file, num_samples);\n\t\t\tcout << uavData->vfr_hud.heading << \": wifly1: \" << dir_rssi << \"\\n\";\n\n\t\t\tif (dual_wifly) {\n\n\t\t\t\tfprintf(wifly_file2, \"%llu,%u,%i,%i,%i,%f,\",\n\t\t\t\t\tuavData->sys_time_us.time_unix_usec, uavData->custom_mode, uavData->vfr_hud.heading,\n\t\t\t\t\tuavData->gps_position.lat, uavData->gps_position.lon, uavData->vfr_hud.alt);\n\n\t\t\t\tomni_rssi = wifly2->scanrssi_f(ssid, wifly_file2, num_samples);\n\t\t\t\tcout << uavData->vfr_hud.heading << \": wifly2: \" << omni_rssi << \"\\n\";\n\t\t\t}\n\n\t\t}\n\n\t\t\/\/ send a mavlink message with the current rssi\n\t\tsend_rssi_message(dir_rssi, uavData->vfr_hud.heading, uavData->gps_position.lat, uavData->gps_position.lon, uavData->vfr_hud.alt);\n\n\t\t\/\/ TODO: send mavlink message of calculated rssi...\n\n\t\t\/\/ send a message with a rotate command for testing purposes at the moment\n\t\t\/\/ sendRotateCommand(-1.0);\n\t\t\n\t\t\/* sleep for some time before making another measurement (30 ms for now) *\/\n\t\t\/\/ usleep(30000);\n\t\t\n\t}\n\t\n\t\n\t\/* Be sure to close the output file and connection *\/\n\tfclose(wifly_file);\n\tfclose(bearing_file);\n\twifly1->end_serial();\n\n\tif (dual_wifly) {\n\t\tfclose(wifly_file2);\n\t\tfclose(bearing_file_mle);\n\t\twifly2->end_serial();\n\t}\n\n\treturn NULL;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ KMail startup and initialize code\n\/\/ Author: Stefan Taferner <taferner@alpin.or.at>\n\n#ifdef HAVE_CONFIG_H\n#include <config.h>\n#endif\n#include <signal.h>\n#include <stdio.h>\n#include <stdlib.h>\n\n#include <kuniqueapplication.h>\n#include <klocale.h>\n#include <kglobal.h>\n#include <dcopclient.h>\n#include <kcrash.h>\n\n#include \"kmkernel.h\" \/\/control center\n\n#undef Status \/\/ stupid X headers\n#include \"kmailIface_stub.h\" \/\/ to call control center of master kmail\n\n#include <kaboutdata.h>\n\n#include \"kmversion.h\"\n\n\n\/\/ OLD about text. This is horrbly outdated.\n\/*const char* aboutText =\n \"KMail [\" KMAIL_VERSION \"] by\\n\\n\"\n \"Stefan Taferner <taferner@kde.org>,\\n\"\n \"Markus Wbben <markus.wuebben@kde.org>\\n\\n\"\n \"based on the work of:\\n\"\n \"Lynx <lynx@topaz.hknet.com>,\\n\"\n \"Stephan Meyer <Stephan.Meyer@pobox.com>,\\n\"\n \"and the above authors.\\n\\n\"\n \"This program is covered by the GPL.\\n\\n\"\n \"Please send bugreports to taferner@kde.org\";\n*\/\n\nstatic KCmdLineOptions kmoptions[] =\n{\n { \"s\", 0 , 0 },\n { \"subject <subject>\",\tI18N_NOOP(\"Set subject of msg.\"), 0 },\n { \"c\", 0 , 0 },\n { \"cc <address>\",\t\tI18N_NOOP(\"Send CC: to 'address'.\"), 0 },\n { \"b\", 0 , 0 },\n { \"bcc <address>\",\t\tI18N_NOOP(\"Send BCC: to 'addres'.\"), 0 },\n { \"h\", 0 , 0 },\n { \"header <header>\",\t\tI18N_NOOP(\"Add 'header' to msg.\"), 0 },\n { \"msg <file>\",\t\tI18N_NOOP(\"Read msg-body from 'file'.\"), 0 },\n { \"body <text>\", I18N_NOOP(\"Set body of msg.\"), 0 },\n { \"attach <url>\", I18N_NOOP(\"Add an attachment to the mail, this can be repeated\"), 0 },\n { \"check\",\t\t\tI18N_NOOP(\"Check for new mail only.\"), 0 },\n { \"composer\",\t\t\tI18N_NOOP(\"Open only composer window.\"), 0 },\n { \"+[address]\",\t\tI18N_NOOP(\"Send msg to 'address'.\"), 0 },\n\/\/ { \"+[file]\", I18N_NOOP(\"Show message from file 'file'.\"), 0 },\n { 0, 0, 0}\n};\n\n\/\/-----------------------------------------------------------------------------\n\nextern \"C\" {\n\nstatic void setSignalHandler(void (*handler)(int));\n\n\/\/ Crash recovery signal handler\nstatic void signalHandler(int sigId)\n{\n setSignalHandler(SIG_DFL);\n fprintf(stderr, \"*** KMail got signal %d (Exiting)\\n\", sigId);\n \/\/ try to cleanup all windows\n kernel->dumpDeadLetters();\n ::exit(-1); \/\/\n}\n\n\/\/ Crash recovery signal handler\nstatic void crashHandler(int sigId)\n{\n setSignalHandler(SIG_DFL);\n fprintf(stderr, \"*** KMail got signal %d (Crashing)\\n\", sigId);\n \/\/ try to cleanup all windows\n kernel->dumpDeadLetters();\n \/\/ Return to DrKonqi.\n}\n\/\/-----------------------------------------------------------------------------\n\n\nstatic void setSignalHandler(void (*handler)(int))\n{\n signal(SIGKILL, handler);\n signal(SIGTERM, handler);\n signal(SIGHUP, handler);\n KCrash::setEmergencySaveFunction(crashHandler);\n}\n\n}\n\/\/-----------------------------------------------------------------------------\n\nclass KMailApplication : public KUniqueApplication\n{\npublic:\n KMailApplication() : KUniqueApplication() { };\n\n virtual int newInstance();\n\n void commitData(QSessionManager& sm) {\n kernel->notClosedByUser();\n KApplication::commitData( sm );\n }\n};\n\nint KMailApplication::newInstance()\n{\n QString to, cc, bcc, subj, body;\n KURL messageFile = QString::null;\n KURL::List attachURLs;\n bool mailto = false;\n bool checkMail = false;\n \/\/bool viewOnly = false;\n\n \/\/ process args:\n KCmdLineArgs *args = KCmdLineArgs::parsedArgs();\n if (args->getOption(\"subject\"))\n {\n mailto = true;\n subj = QString::fromLocal8Bit(args->getOption(\"subject\"));\n }\n\n if (args->getOption(\"cc\"))\n {\n mailto = true;\n cc = QString::fromLocal8Bit(args->getOption(\"cc\"));\n }\n\n if (args->getOption(\"bcc\"))\n {\n mailto = true;\n bcc = QString::fromLocal8Bit(args->getOption(\"bcc\"));\n }\n\n if (args->getOption(\"msg\"))\n {\n mailto = true;\n messageFile = QString::fromLocal8Bit(args->getOption(\"msg\"));\n }\n\n if (args->getOption(\"body\"))\n {\n mailto = true;\n body = QString::fromLocal8Bit(args->getOption(\"body\"));\n }\n\n QCStringList attachList = args->getOptionList(\"attach\");\n if (!attachList.isEmpty())\n {\n mailto = true;\n for ( QCStringList::Iterator it = attachList.begin() ; it != attachList.end() ; ++it )\n attachURLs += KURL( QString::fromLocal8Bit( *it ) );\n }\n\n if (args->isSet(\"composer\"))\n mailto = true;\n\n if (args->isSet(\"check\"))\n checkMail = true;\n\n for(int i= 0; i < args->count(); i++)\n {\n if (!to.isEmpty())\n to += \", \";\n if (strncasecmp(args->arg(i),\"mailto:\",7)==0)\n to += args->arg(i);\n else\n to += args->arg(i);\n mailto = true;\n }\n\n args->clear();\n\n kernel->action (mailto, checkMail, to, cc, bcc, subj, body, messageFile, attachURLs);\n return 0;\n}\n\nint main(int argc, char *argv[])\n{\n \/\/ WABA: KMail is a KUniqueApplication. Unfortunately this makes debugging\n \/\/ a bit harder: You should pass --nofork as commandline argument when using\n \/\/ a debugger. In gdb you can do this by typing \"set args --nofork\" before\n \/\/ typing \"run\".\n\n KAboutData about(\"kmail\", I18N_NOOP(\"KMail\"),\n KMAIL_VERSION,\n\t\t I18N_NOOP(\"The KDE Email client.\"),\n\t\t KAboutData::License_GPL,\n I18N_NOOP(\"(c) 1997-2001, The KMail developers\"),\n\t\t 0,\n\t\t \"http:\/\/kmail.kde.org\");\n about.addAuthor( \"Michael H\\303\\244ckel\", I18N_NOOP(\"Current maintainer\"), \"michael@haeckel.net\" );\n about.addAuthor( \"Don Sanders\", I18N_NOOP(\"Current maintainer\"), \"sanders@kde.org\" );\n about.addAuthor( \"Stefan Taferner \", 0, \"taferner@kde.org\" );\n about.addAuthor( \"Daniel Naber\", I18N_NOOP(\"Documentation\"), \"daniel.naber@t-online.de\" );\n about.addAuthor( \"Andreas Gungl\", I18N_NOOP(\"Encryption\"), \"a.gungl@gmx.de\" );\n about.addAuthor( \"Toyohiro Asukai\", 0, \"toyohiro@ksmplus.com\" );\n about.addAuthor( \"Waldo Bastian\", 0, \"bastian@kde.org\" );\n about.addAuthor( \"Steven Brown\", 0, \"swbrown@ucsd.edu\" );\n about.addAuthor( \"Cristi Dumitrescu\", 0, \"cristid@chip.ro\" );\n about.addAuthor( \"Philippe Fremy\", 0, \"pfremy@chez.com\" );\n about.addAuthor( \"Kurt Granroth\", 0, \"granroth@kde.org\" );\n about.addAuthor( \"Igor Janssen\", 0, \"rm@linux.ru.net\" );\n about.addAuthor( \"Matt Johnston\", 0, \"matt@caifex.org\" );\n about.addAuthor( \"Christer Kaivo-oja\", 0, \"whizkid@telia.com\" );\n about.addAuthor( \"Ingo Kl\\303\\266cker\", 0, \"ingo.kloecker@epost.de\" );\n about.addAuthor( \"Lars Knoll\", 0, \"knoll@kde.org\" );\n about.addAuthor( \"J. Nick Koston\", 0, \"bdraco@darkorb.net\" );\n about.addAuthor( \"Stephan Kulow\", 0, \"coolo@kde.org\" );\n about.addAuthor( \"Guillaume Laurent\", 0, \"glaurent@telegraph-road.org\" );\n about.addAuthor( \"Sam Magnuson\", 0, \"sam@trolltech.com\" );\n about.addAuthor( \"Laurent Montel\", 0, \"lmontel@mandrakesoft.com\" );\n about.addAuthor( \"Marc Mutz\", 0, \"mutz@kde.org\" );\n about.addAuthor( \"Matt Newell\", 0, \"newellm@proaxis.com\" );\n about.addAuthor( \"Denis Perchine\", 0, \"dyp@perchine.com\" );\n about.addAuthor( \"Carsten Pfeiffer\", 0, \"pfeiffer@kde.org\" );\n about.addAuthor( \"Sven Radej\", 0, \"radej@kde.org\" );\n about.addAuthor( \"Mark Roberts\", 0, \"mark@taurine.demon.co.uk\" );\n about.addAuthor( \"Wolfgang Rohdewald\", 0, \"WRohdewald@dplanet.ch\" );\n about.addAuthor( \"Espen Sand\", 0, \"espen@kde.org\" );\n about.addAuthor( \"George Staikos\", 0, \"staikos@kde.org\" );\n about.addAuthor( \"Jason Stephenson\", 0, \"panda@mis.net\" );\n about.addAuthor( \"Jacek Stolarczyk\", 0, \"jacek@mer.chemia.polsl.gliwice.pl\" );\n about.addAuthor( \"Roberto S. Teixeira\", 0, \"maragato@kde.org\" );\n about.addAuthor( \"Mario Weilguni\", 0, \"mweilguni@sime.com\" );\n about.addAuthor( \"Wynn Wilkes\", 0, \"wynnw@calderasystems.com\" );\n about.addAuthor( \"Robert D. Williams\", 0, \"rwilliams@kde.org\" );\n about.addAuthor( \"Markus Wuebben\", 0, \"markus.wuebben@kde.org\" );\n about.addAuthor( \"Karl-Heinz Zimmer\", 0, \"khz@kde.org\" );\n\n KCmdLineArgs::init(argc, argv, &about);\n KCmdLineArgs::addCmdLineOptions( kmoptions ); \/\/ Add kmail options\n\n if (!KMailApplication::start())\n return 0;\n\n KMailApplication app;\n KGlobal::locale()->insertCatalogue(\"libkdenetwork\");\n\n kapp->dcopClient()->suspend(); \/\/ Don't handle DCOP requests yet\n\n \/\/local, do the init\n KMKernel kmailKernel;\n kmailKernel.init();\n kapp->dcopClient()->setDefaultObject( kmailKernel.objId() );\n\n \/\/ and session management\n kmailKernel.doSessionManagement();\n\n \/\/ any dead letters?\n kmailKernel.recoverDeadLetters();\n\n setSignalHandler(signalHandler);\n\n kapp->dcopClient()->resume(); \/\/ Ok. We are ready for DCOP requests.\n \/\/ Go!\n int ret = kapp->exec();\n\n \/\/ clean up\n kmailKernel.cleanup();\n return ret;\n}\n\n<commit_msg>Make it impossible to run KMail twice on the same time on different X displays by creating a lock file because KUniqueApplication doesn't prevent that.<commit_after>\/\/ KMail startup and initialize code\n\/\/ Author: Stefan Taferner <taferner@alpin.or.at>\n\n#ifdef HAVE_CONFIG_H\n#include <config.h>\n#endif\n#include <signal.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <unistd.h>\n\n#include <kuniqueapplication.h>\n#include <klocale.h>\n#include <kglobal.h>\n#include <ksimpleconfig.h>\n#include <kstandarddirs.h>\n#include <knotifyclient.h>\n#include <dcopclient.h>\n#include <kcrash.h>\n\n#include \"kmkernel.h\" \/\/control center\n\n#undef Status \/\/ stupid X headers\n#include \"kmailIface_stub.h\" \/\/ to call control center of master kmail\n\n#include <kaboutdata.h>\n\n#include \"kmversion.h\"\n\n\n\/\/ OLD about text. This is horrbly outdated.\n\/*const char* aboutText =\n \"KMail [\" KMAIL_VERSION \"] by\\n\\n\"\n \"Stefan Taferner <taferner@kde.org>,\\n\"\n \"Markus Wbben <markus.wuebben@kde.org>\\n\\n\"\n \"based on the work of:\\n\"\n \"Lynx <lynx@topaz.hknet.com>,\\n\"\n \"Stephan Meyer <Stephan.Meyer@pobox.com>,\\n\"\n \"and the above authors.\\n\\n\"\n \"This program is covered by the GPL.\\n\\n\"\n \"Please send bugreports to taferner@kde.org\";\n*\/\n\nstatic KCmdLineOptions kmoptions[] =\n{\n { \"s\", 0 , 0 },\n { \"subject <subject>\",\tI18N_NOOP(\"Set subject of msg.\"), 0 },\n { \"c\", 0 , 0 },\n { \"cc <address>\",\t\tI18N_NOOP(\"Send CC: to 'address'.\"), 0 },\n { \"b\", 0 , 0 },\n { \"bcc <address>\",\t\tI18N_NOOP(\"Send BCC: to 'addres'.\"), 0 },\n { \"h\", 0 , 0 },\n { \"header <header>\",\t\tI18N_NOOP(\"Add 'header' to msg.\"), 0 },\n { \"msg <file>\",\t\tI18N_NOOP(\"Read msg-body from 'file'.\"), 0 },\n { \"body <text>\", I18N_NOOP(\"Set body of msg.\"), 0 },\n { \"attach <url>\", I18N_NOOP(\"Add an attachment to the mail, this can be repeated\"), 0 },\n { \"check\",\t\t\tI18N_NOOP(\"Check for new mail only.\"), 0 },\n { \"composer\",\t\t\tI18N_NOOP(\"Open only composer window.\"), 0 },\n { \"+[address]\",\t\tI18N_NOOP(\"Send msg to 'address'.\"), 0 },\n\/\/ { \"+[file]\", I18N_NOOP(\"Show message from file 'file'.\"), 0 },\n { 0, 0, 0}\n};\n\n\/\/-----------------------------------------------------------------------------\n\nextern \"C\" {\n\nstatic void setSignalHandler(void (*handler)(int));\n\n\/\/ Crash recovery signal handler\nstatic void signalHandler(int sigId)\n{\n setSignalHandler(SIG_DFL);\n fprintf(stderr, \"*** KMail got signal %d (Exiting)\\n\", sigId);\n \/\/ try to cleanup all windows\n kernel->dumpDeadLetters();\n ::exit(-1); \/\/\n}\n\n\/\/ Crash recovery signal handler\nstatic void crashHandler(int sigId)\n{\n setSignalHandler(SIG_DFL);\n fprintf(stderr, \"*** KMail got signal %d (Crashing)\\n\", sigId);\n \/\/ try to cleanup all windows\n kernel->dumpDeadLetters();\n \/\/ Return to DrKonqi.\n}\n\/\/-----------------------------------------------------------------------------\n\n\nstatic void setSignalHandler(void (*handler)(int))\n{\n signal(SIGKILL, handler);\n signal(SIGTERM, handler);\n signal(SIGHUP, handler);\n KCrash::setEmergencySaveFunction(crashHandler);\n}\n\n}\n\/\/-----------------------------------------------------------------------------\n\nclass KMailApplication : public KUniqueApplication\n{\npublic:\n KMailApplication() : KUniqueApplication() { };\n\n virtual int newInstance();\n\n void commitData(QSessionManager& sm) {\n kernel->notClosedByUser();\n KApplication::commitData( sm );\n }\n};\n\nint KMailApplication::newInstance()\n{\n QString to, cc, bcc, subj, body;\n KURL messageFile = QString::null;\n KURL::List attachURLs;\n bool mailto = false;\n bool checkMail = false;\n \/\/bool viewOnly = false;\n\n \/\/ process args:\n KCmdLineArgs *args = KCmdLineArgs::parsedArgs();\n if (args->getOption(\"subject\"))\n {\n mailto = true;\n subj = QString::fromLocal8Bit(args->getOption(\"subject\"));\n }\n\n if (args->getOption(\"cc\"))\n {\n mailto = true;\n cc = QString::fromLocal8Bit(args->getOption(\"cc\"));\n }\n\n if (args->getOption(\"bcc\"))\n {\n mailto = true;\n bcc = QString::fromLocal8Bit(args->getOption(\"bcc\"));\n }\n\n if (args->getOption(\"msg\"))\n {\n mailto = true;\n messageFile = QString::fromLocal8Bit(args->getOption(\"msg\"));\n }\n\n if (args->getOption(\"body\"))\n {\n mailto = true;\n body = QString::fromLocal8Bit(args->getOption(\"body\"));\n }\n\n QCStringList attachList = args->getOptionList(\"attach\");\n if (!attachList.isEmpty())\n {\n mailto = true;\n for ( QCStringList::Iterator it = attachList.begin() ; it != attachList.end() ; ++it )\n attachURLs += KURL( QString::fromLocal8Bit( *it ) );\n }\n\n if (args->isSet(\"composer\"))\n mailto = true;\n\n if (args->isSet(\"check\"))\n checkMail = true;\n\n for(int i= 0; i < args->count(); i++)\n {\n if (!to.isEmpty())\n to += \", \";\n if (strncasecmp(args->arg(i),\"mailto:\",7)==0)\n to += args->arg(i);\n else\n to += args->arg(i);\n mailto = true;\n }\n\n args->clear();\n\n kernel->action (mailto, checkMail, to, cc, bcc, subj, body, messageFile, attachURLs);\n return 0;\n}\n\nint main(int argc, char *argv[])\n{\n \/\/ WABA: KMail is a KUniqueApplication. Unfortunately this makes debugging\n \/\/ a bit harder: You should pass --nofork as commandline argument when using\n \/\/ a debugger. In gdb you can do this by typing \"set args --nofork\" before\n \/\/ typing \"run\".\n\n KAboutData about(\"kmail\", I18N_NOOP(\"KMail\"),\n KMAIL_VERSION,\n\t\t I18N_NOOP(\"The KDE Email client.\"),\n\t\t KAboutData::License_GPL,\n I18N_NOOP(\"(c) 1997-2001, The KMail developers\"),\n\t\t 0,\n\t\t \"http:\/\/kmail.kde.org\");\n about.addAuthor( \"Michael H\\303\\244ckel\", I18N_NOOP(\"Current maintainer\"), \"michael@haeckel.net\" );\n about.addAuthor( \"Don Sanders\", I18N_NOOP(\"Current maintainer\"), \"sanders@kde.org\" );\n about.addAuthor( \"Stefan Taferner \", 0, \"taferner@kde.org\" );\n about.addAuthor( \"Daniel Naber\", I18N_NOOP(\"Documentation\"), \"daniel.naber@t-online.de\" );\n about.addAuthor( \"Andreas Gungl\", I18N_NOOP(\"Encryption\"), \"a.gungl@gmx.de\" );\n about.addAuthor( \"Toyohiro Asukai\", 0, \"toyohiro@ksmplus.com\" );\n about.addAuthor( \"Waldo Bastian\", 0, \"bastian@kde.org\" );\n about.addAuthor( \"Steven Brown\", 0, \"swbrown@ucsd.edu\" );\n about.addAuthor( \"Cristi Dumitrescu\", 0, \"cristid@chip.ro\" );\n about.addAuthor( \"Philippe Fremy\", 0, \"pfremy@chez.com\" );\n about.addAuthor( \"Kurt Granroth\", 0, \"granroth@kde.org\" );\n about.addAuthor( \"Igor Janssen\", 0, \"rm@linux.ru.net\" );\n about.addAuthor( \"Matt Johnston\", 0, \"matt@caifex.org\" );\n about.addAuthor( \"Christer Kaivo-oja\", 0, \"whizkid@telia.com\" );\n about.addAuthor( \"Ingo Kl\\303\\266cker\", 0, \"ingo.kloecker@epost.de\" );\n about.addAuthor( \"Lars Knoll\", 0, \"knoll@kde.org\" );\n about.addAuthor( \"J. Nick Koston\", 0, \"bdraco@darkorb.net\" );\n about.addAuthor( \"Stephan Kulow\", 0, \"coolo@kde.org\" );\n about.addAuthor( \"Guillaume Laurent\", 0, \"glaurent@telegraph-road.org\" );\n about.addAuthor( \"Sam Magnuson\", 0, \"sam@trolltech.com\" );\n about.addAuthor( \"Laurent Montel\", 0, \"lmontel@mandrakesoft.com\" );\n about.addAuthor( \"Marc Mutz\", 0, \"mutz@kde.org\" );\n about.addAuthor( \"Matt Newell\", 0, \"newellm@proaxis.com\" );\n about.addAuthor( \"Denis Perchine\", 0, \"dyp@perchine.com\" );\n about.addAuthor( \"Carsten Pfeiffer\", 0, \"pfeiffer@kde.org\" );\n about.addAuthor( \"Sven Radej\", 0, \"radej@kde.org\" );\n about.addAuthor( \"Mark Roberts\", 0, \"mark@taurine.demon.co.uk\" );\n about.addAuthor( \"Wolfgang Rohdewald\", 0, \"WRohdewald@dplanet.ch\" );\n about.addAuthor( \"Espen Sand\", 0, \"espen@kde.org\" );\n about.addAuthor( \"George Staikos\", 0, \"staikos@kde.org\" );\n about.addAuthor( \"Jason Stephenson\", 0, \"panda@mis.net\" );\n about.addAuthor( \"Jacek Stolarczyk\", 0, \"jacek@mer.chemia.polsl.gliwice.pl\" );\n about.addAuthor( \"Roberto S. Teixeira\", 0, \"maragato@kde.org\" );\n about.addAuthor( \"Mario Weilguni\", 0, \"mweilguni@sime.com\" );\n about.addAuthor( \"Wynn Wilkes\", 0, \"wynnw@calderasystems.com\" );\n about.addAuthor( \"Robert D. Williams\", 0, \"rwilliams@kde.org\" );\n about.addAuthor( \"Markus Wuebben\", 0, \"markus.wuebben@kde.org\" );\n about.addAuthor( \"Karl-Heinz Zimmer\", 0, \"khz@kde.org\" );\n\n KCmdLineArgs::init(argc, argv, &about);\n KCmdLineArgs::addCmdLineOptions( kmoptions ); \/\/ Add kmail options\n\n if (!KMailApplication::start())\n return 0;\n\n KMailApplication app;\n KGlobal::locale()->insertCatalogue(\"libkdenetwork\");\n\n KSimpleConfig config(locateLocal(\"appdata\", \"lock\"));\n int oldPid = config.readNumEntry(\"pid\", -1);\n if (oldPid != -1 && getsid(oldPid) != -1)\n {\n QString msg = i18n(\"KMail can only run once at the same time. \"\n \"It is already running on a different display with PID %1.\").arg(oldPid);\n KNotifyClient::userEvent( msg, KNotifyClient::Messagebox,\n KNotifyClient::Error );\n fprintf(stderr, \"*** KMail is already running with PID %d\\n\", oldPid);\n return 1;\n }\n\n config.writeEntry(\"pid\", getpid());\n config.sync();\n\n kapp->dcopClient()->suspend(); \/\/ Don't handle DCOP requests yet\n\n \/\/local, do the init\n KMKernel kmailKernel;\n kmailKernel.init();\n kapp->dcopClient()->setDefaultObject( kmailKernel.objId() );\n\n \/\/ and session management\n kmailKernel.doSessionManagement();\n\n \/\/ any dead letters?\n kmailKernel.recoverDeadLetters();\n\n setSignalHandler(signalHandler);\n\n kapp->dcopClient()->resume(); \/\/ Ok. We are ready for DCOP requests.\n \/\/ Go!\n int ret = kapp->exec();\n\n \/\/ clean up\n kmailKernel.cleanup();\n config.writeEntry(\"pid\", -1);\n config.sync();\n return ret;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright 2015 Aldebaran\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n*\/\n\n\/**\n* LOCAL includes\n*\/\n#include \"camera.hpp\"\n#include \"camera_info_definitions.hpp\"\n#include \"..\/tools\/alvisiondefinitions.h\" \/\/ for kTop...\n\n\/**\n* ROS includes\n*\/\n#include <cv_bridge\/cv_bridge.h>\n\n\/**\n* CV includes\n*\/\n#include <opencv2\/imgproc\/imgproc.hpp>\n\n\/**\n* BOOST includes\n*\/\n#include <boost\/foreach.hpp>\n#define for_each BOOST_FOREACH\n\nnamespace alros\n{\nnamespace converter\n{\n\nnamespace camera_info_definitions\n{\n\nconst sensor_msgs::CameraInfo& getCameraInfo( int camera_source, int resolution )\n{\n \/** RETURN VALUE OPTIMIZATION (RVO)\n * since there is no C++11 initializer list nor lamda functions\n *\/\n if ( camera_source == AL::kTopCamera)\n {\n if ( resolution == AL::kVGA )\n {\n static const sensor_msgs::CameraInfo cam_info_msg = createCameraInfoTOPVGA();\n return cam_info_msg;\n }\n else if( resolution == AL::kQVGA )\n {\n static const sensor_msgs::CameraInfo cam_info_msg = createCameraInfoTOPQVGA();\n return cam_info_msg;\n }\n else if( resolution == AL::kQQVGA )\n {\n static const sensor_msgs::CameraInfo cam_info_msg = createCameraInfoTOPQQVGA();\n return cam_info_msg;\n }\n else{\n std::cout << \"no camera information found for camera_source \" << camera_source << \" and res: \" << resolution << std::endl;\n }\n }\n else if ( camera_source == AL::kBottomCamera )\n {\n if ( resolution == AL::kVGA )\n {\n static const sensor_msgs::CameraInfo cam_info_msg = createCameraInfoBOTTOMVGA();\n return cam_info_msg;\n }\n else if( resolution == AL::kQVGA )\n {\n static const sensor_msgs::CameraInfo cam_info_msg = createCameraInfoBOTTOMQVGA();\n return cam_info_msg;\n }\n else if( resolution == AL::kQQVGA )\n {\n static const sensor_msgs::CameraInfo cam_info_msg = createCameraInfoBOTTOMQQVGA();\n return cam_info_msg;\n }\n else{\n std::cout << \"no camera information found for camera_source \" << camera_source << \" and res: \" << resolution << std::endl;\n }\n }\n else if ( camera_source == AL::kDepthCamera )\n {\n if ( resolution == AL::kVGA )\n {\n static const sensor_msgs::CameraInfo cam_info_msg = createCameraInfoDEPTHVGA();\n return cam_info_msg;\n }\n else if( resolution == AL::kQVGA )\n {\n static const sensor_msgs::CameraInfo cam_info_msg = createCameraInfoDEPTHQVGA();\n return cam_info_msg;\n }\n else if( resolution == AL::kQQVGA )\n {\n static const sensor_msgs::CameraInfo cam_info_msg = createCameraInfoDEPTHQQVGA();\n return cam_info_msg;\n }\n else{\n std::cout << \"no camera information found for camera_source \" << camera_source << \" and res: \" << resolution << std::endl;\n }\n }\n}\n\n} \/\/ camera_info_definitions\n\nCameraConverter::CameraConverter( const std::string& name, const float& frequency, const qi::SessionPtr& session, const int& camera_source, const int& resolution )\n : BaseConverter( name, frequency, session ),\n p_video_( session->service(\"ALVideoDevice\") ),\n camera_source_(camera_source),\n resolution_(resolution),\n \/\/ change in case of depth camera\n colorspace_( (camera_source_!=AL::kDepthCamera)?AL::kBGRColorSpace:AL::kDepthColorSpace ),\n msg_colorspace_( (camera_source_!=AL::kDepthCamera)?\"bgr8\":\"16UC1\" ),\n cv_mat_type_( (camera_source_!=AL::kDepthCamera)?CV_8UC3:CV_16U ),\n camera_info_( camera_info_definitions::getCameraInfo(camera_source, resolution) )\n{\n if ( camera_source == AL::kTopCamera )\n {\n msg_frameid_ = \"CameraTop_optical_frame\";\n }\n else if (camera_source == AL::kBottomCamera )\n {\n msg_frameid_ = \"CameraBottom_optical_frame\";\n }\n else if (camera_source_ == AL::kDepthCamera )\n {\n msg_frameid_ = \"CameraDepth_optical_frame\";\n }\n}\n\nCameraConverter::~CameraConverter()\n{\n if (!handle_.empty())\n {\n std::cout << \"Unsubscribe camera handle \" << handle_ << std::endl;\n p_video_.call<qi::AnyValue>(\"unsubscribe\", handle_);\n handle_.clear();\n }\n}\n\nvoid CameraConverter::reset()\n{\n if (!handle_.empty())\n {\n p_video_.call<qi::AnyValue>(\"unsubscribe\", handle_);\n handle_.clear();\n }\n\n handle_ = p_video_.call<std::string>(\n \"subscribeCamera\",\n name_,\n camera_source_,\n resolution_,\n colorspace_,\n frequency_\n );\n}\n\nvoid CameraConverter::registerCallback( const message_actions::MessageAction action, Callback_t cb )\n{\n callbacks_[action] = cb;\n}\n\nvoid CameraConverter::callAll( const std::vector<message_actions::MessageAction>& actions )\n{\n\n if (handle_.empty() )\n {\n std::cerr << \"Camera Handle is empty - cannot retrieve image\" << std::endl;\n return;\n }\n\n qi::AnyValue image_anyvalue = p_video_.call<qi::AnyValue>(\"getImageRemote\", handle_);\n qi::AnyReferenceVector image_anyref = image_anyvalue.asListValuePtr();\n\n int width, height;\n void* image_buffer;\n\n \/\/ Create a cv::Mat of the right dimensions\n width = image_anyref[0].content().asInt32();\n height = image_anyref[1].content().asInt32();\n image_buffer = (void*)(image_anyref[6].content().asRaw().first);\n cv::Mat cv_img(height, width, cv_mat_type_, image_buffer);\n msg_ = cv_bridge::CvImage(std_msgs::Header(), msg_colorspace_, cv_img).toImageMsg();\n msg_->header.frame_id = msg_frameid_;\n\n ros::Time now = ros::Time::now();\n msg_->header.stamp = now;\n camera_info_.header.stamp = now;\n\n for_each( const message_actions::MessageAction& action, actions )\n {\n callbacks_[action]( msg_, camera_info_ );\n }\n}\n\n} \/\/ publisher\n} \/\/alros\n<commit_msg>Add security when getting image (in case no image is retrieved)<commit_after>\/*\n * Copyright 2015 Aldebaran\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n*\/\n\n\/**\n* LOCAL includes\n*\/\n#include \"camera.hpp\"\n#include \"camera_info_definitions.hpp\"\n#include \"..\/tools\/alvisiondefinitions.h\" \/\/ for kTop...\n\n\/**\n* ROS includes\n*\/\n#include <cv_bridge\/cv_bridge.h>\n\n\/**\n* CV includes\n*\/\n#include <opencv2\/imgproc\/imgproc.hpp>\n\n\/**\n* BOOST includes\n*\/\n#include <boost\/foreach.hpp>\n#define for_each BOOST_FOREACH\n\nnamespace alros\n{\nnamespace converter\n{\n\nnamespace camera_info_definitions\n{\n\nconst sensor_msgs::CameraInfo& getCameraInfo( int camera_source, int resolution )\n{\n \/** RETURN VALUE OPTIMIZATION (RVO)\n * since there is no C++11 initializer list nor lamda functions\n *\/\n if ( camera_source == AL::kTopCamera)\n {\n if ( resolution == AL::kVGA )\n {\n static const sensor_msgs::CameraInfo cam_info_msg = createCameraInfoTOPVGA();\n return cam_info_msg;\n }\n else if( resolution == AL::kQVGA )\n {\n static const sensor_msgs::CameraInfo cam_info_msg = createCameraInfoTOPQVGA();\n return cam_info_msg;\n }\n else if( resolution == AL::kQQVGA )\n {\n static const sensor_msgs::CameraInfo cam_info_msg = createCameraInfoTOPQQVGA();\n return cam_info_msg;\n }\n else{\n std::cout << \"no camera information found for camera_source \" << camera_source << \" and res: \" << resolution << std::endl;\n }\n }\n else if ( camera_source == AL::kBottomCamera )\n {\n if ( resolution == AL::kVGA )\n {\n static const sensor_msgs::CameraInfo cam_info_msg = createCameraInfoBOTTOMVGA();\n return cam_info_msg;\n }\n else if( resolution == AL::kQVGA )\n {\n static const sensor_msgs::CameraInfo cam_info_msg = createCameraInfoBOTTOMQVGA();\n return cam_info_msg;\n }\n else if( resolution == AL::kQQVGA )\n {\n static const sensor_msgs::CameraInfo cam_info_msg = createCameraInfoBOTTOMQQVGA();\n return cam_info_msg;\n }\n else{\n std::cout << \"no camera information found for camera_source \" << camera_source << \" and res: \" << resolution << std::endl;\n }\n }\n else if ( camera_source == AL::kDepthCamera )\n {\n if ( resolution == AL::kVGA )\n {\n static const sensor_msgs::CameraInfo cam_info_msg = createCameraInfoDEPTHVGA();\n return cam_info_msg;\n }\n else if( resolution == AL::kQVGA )\n {\n static const sensor_msgs::CameraInfo cam_info_msg = createCameraInfoDEPTHQVGA();\n return cam_info_msg;\n }\n else if( resolution == AL::kQQVGA )\n {\n static const sensor_msgs::CameraInfo cam_info_msg = createCameraInfoDEPTHQQVGA();\n return cam_info_msg;\n }\n else{\n std::cout << \"no camera information found for camera_source \" << camera_source << \" and res: \" << resolution << std::endl;\n }\n }\n}\n\n} \/\/ camera_info_definitions\n\nCameraConverter::CameraConverter( const std::string& name, const float& frequency, const qi::SessionPtr& session, const int& camera_source, const int& resolution )\n : BaseConverter( name, frequency, session ),\n p_video_( session->service(\"ALVideoDevice\") ),\n camera_source_(camera_source),\n resolution_(resolution),\n \/\/ change in case of depth camera\n colorspace_( (camera_source_!=AL::kDepthCamera)?AL::kBGRColorSpace:AL::kDepthColorSpace ),\n msg_colorspace_( (camera_source_!=AL::kDepthCamera)?\"bgr8\":\"16UC1\" ),\n cv_mat_type_( (camera_source_!=AL::kDepthCamera)?CV_8UC3:CV_16U ),\n camera_info_( camera_info_definitions::getCameraInfo(camera_source, resolution) )\n{\n if ( camera_source == AL::kTopCamera )\n {\n msg_frameid_ = \"CameraTop_optical_frame\";\n }\n else if (camera_source == AL::kBottomCamera )\n {\n msg_frameid_ = \"CameraBottom_optical_frame\";\n }\n else if (camera_source_ == AL::kDepthCamera )\n {\n msg_frameid_ = \"CameraDepth_optical_frame\";\n }\n}\n\nCameraConverter::~CameraConverter()\n{\n if (!handle_.empty())\n {\n std::cout << \"Unsubscribe camera handle \" << handle_ << std::endl;\n p_video_.call<qi::AnyValue>(\"unsubscribe\", handle_);\n handle_.clear();\n }\n}\n\nvoid CameraConverter::reset()\n{\n if (!handle_.empty())\n {\n p_video_.call<qi::AnyValue>(\"unsubscribe\", handle_);\n handle_.clear();\n }\n\n handle_ = p_video_.call<std::string>(\n \"subscribeCamera\",\n name_,\n camera_source_,\n resolution_,\n colorspace_,\n frequency_\n );\n}\n\nvoid CameraConverter::registerCallback( const message_actions::MessageAction action, Callback_t cb )\n{\n callbacks_[action] = cb;\n}\n\nvoid CameraConverter::callAll( const std::vector<message_actions::MessageAction>& actions )\n{\n\n if (handle_.empty() )\n {\n std::cerr << \"Camera Handle is empty - cannot retrieve image\" << std::endl;\n return;\n }\n\n qi::AnyValue image_anyvalue = p_video_.call<qi::AnyValue>(\"getImageRemote\", handle_);\n qi::AnyReferenceVector image_anyref;\n try{\n image_anyref = image_anyvalue.asListValuePtr();\n }\n catch(std::runtime_error& e)\n {\n std::cout << \"Cannot retrieve image\" << std::endl;\n return;\n }\n\n int width, height;\n void* image_buffer;\n\n \/\/ Create a cv::Mat of the right dimensions\n width = image_anyref[0].content().asInt32();\n height = image_anyref[1].content().asInt32();\n image_buffer = (void*)(image_anyref[6].content().asRaw().first);\n cv::Mat cv_img(height, width, cv_mat_type_, image_buffer);\n msg_ = cv_bridge::CvImage(std_msgs::Header(), msg_colorspace_, cv_img).toImageMsg();\n msg_->header.frame_id = msg_frameid_;\n\n ros::Time now = ros::Time::now();\n msg_->header.stamp = now;\n camera_info_.header.stamp = now;\n\n for_each( const message_actions::MessageAction& action, actions )\n {\n callbacks_[action]( msg_, camera_info_ );\n }\n}\n\n} \/\/ publisher\n} \/\/alros\n<|endoftext|>"} {"text":"<commit_before>\/\/ 6 april 2015\n#include \"uipriv_windows.hpp\"\n\nHINSTANCE hInstance;\nint nCmdShow;\n\nHFONT hMessageFont;\n\n\/\/ LONGTERM needed?\nHBRUSH hollowBrush;\n\n\/\/ the returned pointer is actually to the second character\n\/\/ if the first character is - then free, otherwise don't\nstatic const char *initerr(const char *message, const WCHAR *label, DWORD value)\n{\n\tWCHAR *sysmsg;\n\tBOOL hassysmsg;\n\tWCHAR *wmessage;\n\tWCHAR *wout;\n\tchar *out;\n\n\thassysmsg = FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, value, 0, (LPWSTR) (&sysmsg), 0, NULL) != 0;\n\tif (!hassysmsg)\n\t\tsysmsg = L\"\";\n\twmessage = toUTF16(message + 1);\n\twout = strf(L\"-error initializing libui: %s; code %I32d (0x%08I32X) %s\",\n\t\twmessage,\n\t\tvalue, value,\n\t\tsysmsg);\n\tuiFree(wmessage);\n\tif (hassysmsg)\n\t\tLocalFree(sysmsg);\t\t\/\/ ignore error\n\tout = toUTF8(wout);\n\tuiFree(wout);\n\treturn out + 1;\n}\n\n#define ieLastErr(msg) initerr(\"=\" msg, L\"GetLastError() ==\", GetLastError())\n#define ieHRESULT(msg, hr) initerr(\"=\" msg, L\"HRESULT\", (DWORD) hr)\n\n\/\/ LONGTERM make common\nuiInitOptions options;\n\n#define wantedICCClasses ( \\\n\tICC_STANDARD_CLASSES |\t\/* user32.dll controls *\/\t\t\\\n\tICC_PROGRESS_CLASS |\t\t\/* progress bars *\/\t\t\t\\\n\tICC_TAB_CLASSES |\t\t\t\/* tabs *\/\t\t\t\t\t\\\n\tICC_LISTVIEW_CLASSES |\t\t\/* table headers *\/\t\t\t\\\n\tICC_UPDOWN_CLASS |\t\t\/* spinboxes *\/\t\t\t\\\n\tICC_BAR_CLASSES |\t\t\t\/* trackbar *\/\t\t\t\t\\\n\tICC_DATE_CLASSES |\t\t\/* date\/time picker *\/\t\t\\\n\t0)\n\nconst char *uiInit(uiInitOptions *o)\n{\n\tSTARTUPINFOW si;\n\tconst char *ce;\n\tHICON hDefaultIcon;\n\tHCURSOR hDefaultCursor;\n\tNONCLIENTMETRICSW ncm;\n\tINITCOMMONCONTROLSEX icc;\n\tHRESULT hr;\n\n\toptions = *o;\n\n\tinitAlloc();\n\n\tnCmdShow = SW_SHOWDEFAULT;\n\tGetStartupInfoW(&si);\n\tif ((si.dwFlags & STARTF_USESHOWWINDOW) != 0)\n\t\tnCmdShow = si.wShowWindow;\n\n\t\/\/ LONGTERM set DPI awareness\n\n\thDefaultIcon = LoadIconW(NULL, IDI_APPLICATION);\n\tif (hDefaultIcon == NULL)\n\t\treturn ieLastErr(\"loading default icon for window classes\");\n\thDefaultCursor = LoadCursorW(NULL, IDC_ARROW);\n\tif (hDefaultCursor == NULL)\n\t\treturn ieLastErr(\"loading default cursor for window classes\");\n\n\tce = initUtilWindow(hDefaultIcon, hDefaultCursor);\n\tif (ce != NULL)\n\t\treturn initerr(ce, L\"GetLastError() ==\", GetLastError());\n\n\tif (registerWindowClass(hDefaultIcon, hDefaultCursor) == 0)\n\t\treturn ieLastErr(\"registering uiWindow window class\");\n\n\tZeroMemory(&ncm, sizeof (NONCLIENTMETRICSW));\n\tncm.cbSize = sizeof (NONCLIENTMETRICSW);\n\tif (SystemParametersInfoW(SPI_GETNONCLIENTMETRICS, sizeof (NONCLIENTMETRICSW), &ncm, sizeof (NONCLIENTMETRICSW)) == 0)\n\t\treturn ieLastErr(\"getting default fonts\");\n\thMessageFont = CreateFontIndirectW(&(ncm.lfMessageFont));\n\tif (hMessageFont == NULL)\n\t\treturn ieLastErr(\"loading default messagebox font; this is the default UI font\");\n\n\tif (initContainer(hDefaultIcon, hDefaultCursor) == 0)\n\t\treturn ieLastErr(\"initializing uiWindowsMakeContainer() window class\");\n\n\thollowBrush = (HBRUSH) GetStockObject(HOLLOW_BRUSH);\n\tif (hollowBrush == NULL)\n\t\treturn ieLastErr(\"getting hollow brush\");\n\n\tZeroMemory(&icc, sizeof (INITCOMMONCONTROLSEX));\n\ticc.dwSize = sizeof (INITCOMMONCONTROLSEX);\n\ticc.dwICC = wantedICCClasses;\n\tif (InitCommonControlsEx(&icc) == 0)\n\t\treturn ieLastErr(\"initializing Common Controls\");\n\n\thr = CoInitialize(NULL);\n\tif (hr != S_OK && hr != S_FALSE)\n\t\treturn ieHRESULT(\"initializing COM\", hr);\n\t\/\/ LONGTERM initialize COM security\n\t\/\/ LONGTERM (windows vista) turn off COM exception handling\n\n\thr = initDraw();\n\tif (hr != S_OK)\n\t\treturn ieHRESULT(\"initializing Direct2D\", hr);\n\n\thr = initDrawText();\n\tif (hr != S_OK)\n\t\treturn ieHRESULT(\"initializing DirectWrite\", hr);\n\n\tif (registerAreaClass(hDefaultIcon, hDefaultCursor) == 0)\n\t\treturn ieLastErr(\"registering uiArea window class\");\n\n\tif (registerMessageFilter() == 0)\n\t\treturn ieLastErr(\"registering libui message filter\");\n\n\tif (registerD2DScratchClass(hDefaultIcon, hDefaultCursor) == 0)\n\t\treturn ieLastErr(\"initializing D2D scratch window class\");\n\n\treturn NULL;\n}\n\nvoid uiUninit(void)\n{\n\tuninitMenus();\n\tunregisterD2DScratchClass();\n\tunregisterMessageFilter();\n\tunregisterArea();\n\tuninitDrawText();\n\tuninitDraw();\n\tCoUninitialize();\n\tif (DeleteObject(hollowBrush) == 0)\n\t\tlogLastError(L\"error freeing hollow brush\");\n\tuninitContainer();\n\tif (DeleteObject(hMessageFont) == 0)\n\t\tlogLastError(L\"error deleting control font\");\n\tunregisterWindowClass();\n\t\/\/ no need to delete the default icon or cursor; see http:\/\/stackoverflow.com\/questions\/30603077\/\n\tuninitUtilWindow();\n\tuninitAlloc();\n}\n\nvoid uiFreeInitError(const char *err)\n{\n\tif (*(err - 1) == '-')\n\t\tuiFree((void *) err);\n}\n\nBOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved)\n{\n\tif (fdwReason == DLL_PROCESS_ATTACH)\n\t\thInstance = hinstDLL;\n\treturn TRUE;\n}\n<commit_msg>Fixed a latent bug in uiFreeInitError() on Windows.<commit_after>\/\/ 6 april 2015\n#include \"uipriv_windows.hpp\"\n\nHINSTANCE hInstance;\nint nCmdShow;\n\nHFONT hMessageFont;\n\n\/\/ LONGTERM needed?\nHBRUSH hollowBrush;\n\n\/\/ the returned pointer is actually to the second character\n\/\/ if the first character is - then free, otherwise don't\nstatic const char *initerr(const char *message, const WCHAR *label, DWORD value)\n{\n\tWCHAR *sysmsg;\n\tBOOL hassysmsg;\n\tWCHAR *wmessage;\n\tWCHAR *wout;\n\tchar *out;\n\n\thassysmsg = FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, value, 0, (LPWSTR) (&sysmsg), 0, NULL) != 0;\n\tif (!hassysmsg)\n\t\tsysmsg = L\"\";\n\twmessage = toUTF16(message + 1);\n\twout = strf(L\"-error initializing libui: %s; code %I32d (0x%08I32X) %s\",\n\t\twmessage,\n\t\tvalue, value,\n\t\tsysmsg);\n\tuiFree(wmessage);\n\tif (hassysmsg)\n\t\tLocalFree(sysmsg);\t\t\/\/ ignore error\n\tout = toUTF8(wout);\n\tuiFree(wout);\n\treturn out + 1;\n}\n\n#define ieLastErr(msg) initerr(\"=\" msg, L\"GetLastError() ==\", GetLastError())\n#define ieHRESULT(msg, hr) initerr(\"=\" msg, L\"HRESULT\", (DWORD) hr)\n\n\/\/ LONGTERM make common\nuiInitOptions options;\n\n#define wantedICCClasses ( \\\n\tICC_STANDARD_CLASSES |\t\/* user32.dll controls *\/\t\t\\\n\tICC_PROGRESS_CLASS |\t\t\/* progress bars *\/\t\t\t\\\n\tICC_TAB_CLASSES |\t\t\t\/* tabs *\/\t\t\t\t\t\\\n\tICC_LISTVIEW_CLASSES |\t\t\/* table headers *\/\t\t\t\\\n\tICC_UPDOWN_CLASS |\t\t\/* spinboxes *\/\t\t\t\\\n\tICC_BAR_CLASSES |\t\t\t\/* trackbar *\/\t\t\t\t\\\n\tICC_DATE_CLASSES |\t\t\/* date\/time picker *\/\t\t\\\n\t0)\n\nconst char *uiInit(uiInitOptions *o)\n{\n\tSTARTUPINFOW si;\n\tconst char *ce;\n\tHICON hDefaultIcon;\n\tHCURSOR hDefaultCursor;\n\tNONCLIENTMETRICSW ncm;\n\tINITCOMMONCONTROLSEX icc;\n\tHRESULT hr;\n\n\toptions = *o;\n\n\tinitAlloc();\n\n\tnCmdShow = SW_SHOWDEFAULT;\n\tGetStartupInfoW(&si);\n\tif ((si.dwFlags & STARTF_USESHOWWINDOW) != 0)\n\t\tnCmdShow = si.wShowWindow;\n\n\t\/\/ LONGTERM set DPI awareness\n\n\thDefaultIcon = LoadIconW(NULL, IDI_APPLICATION);\n\tif (hDefaultIcon == NULL)\n\t\treturn ieLastErr(\"loading default icon for window classes\");\n\thDefaultCursor = LoadCursorW(NULL, IDC_ARROW);\n\tif (hDefaultCursor == NULL)\n\t\treturn ieLastErr(\"loading default cursor for window classes\");\n\n\tce = initUtilWindow(hDefaultIcon, hDefaultCursor);\n\tif (ce != NULL)\n\t\treturn initerr(ce, L\"GetLastError() ==\", GetLastError());\n\n\tif (registerWindowClass(hDefaultIcon, hDefaultCursor) == 0)\n\t\treturn ieLastErr(\"registering uiWindow window class\");\n\n\tZeroMemory(&ncm, sizeof (NONCLIENTMETRICSW));\n\tncm.cbSize = sizeof (NONCLIENTMETRICSW);\n\tif (SystemParametersInfoW(SPI_GETNONCLIENTMETRICS, sizeof (NONCLIENTMETRICSW), &ncm, sizeof (NONCLIENTMETRICSW)) == 0)\n\t\treturn ieLastErr(\"getting default fonts\");\n\thMessageFont = CreateFontIndirectW(&(ncm.lfMessageFont));\n\tif (hMessageFont == NULL)\n\t\treturn ieLastErr(\"loading default messagebox font; this is the default UI font\");\n\n\tif (initContainer(hDefaultIcon, hDefaultCursor) == 0)\n\t\treturn ieLastErr(\"initializing uiWindowsMakeContainer() window class\");\n\n\thollowBrush = (HBRUSH) GetStockObject(HOLLOW_BRUSH);\n\tif (hollowBrush == NULL)\n\t\treturn ieLastErr(\"getting hollow brush\");\n\n\tZeroMemory(&icc, sizeof (INITCOMMONCONTROLSEX));\n\ticc.dwSize = sizeof (INITCOMMONCONTROLSEX);\n\ticc.dwICC = wantedICCClasses;\n\tif (InitCommonControlsEx(&icc) == 0)\n\t\treturn ieLastErr(\"initializing Common Controls\");\n\n\thr = CoInitialize(NULL);\n\tif (hr != S_OK && hr != S_FALSE)\n\t\treturn ieHRESULT(\"initializing COM\", hr);\n\t\/\/ LONGTERM initialize COM security\n\t\/\/ LONGTERM (windows vista) turn off COM exception handling\n\n\thr = initDraw();\n\tif (hr != S_OK)\n\t\treturn ieHRESULT(\"initializing Direct2D\", hr);\n\n\thr = initDrawText();\n\tif (hr != S_OK)\n\t\treturn ieHRESULT(\"initializing DirectWrite\", hr);\n\n\tif (registerAreaClass(hDefaultIcon, hDefaultCursor) == 0)\n\t\treturn ieLastErr(\"registering uiArea window class\");\n\n\tif (registerMessageFilter() == 0)\n\t\treturn ieLastErr(\"registering libui message filter\");\n\n\tif (registerD2DScratchClass(hDefaultIcon, hDefaultCursor) == 0)\n\t\treturn ieLastErr(\"initializing D2D scratch window class\");\n\n\treturn NULL;\n}\n\nvoid uiUninit(void)\n{\n\tuninitMenus();\n\tunregisterD2DScratchClass();\n\tunregisterMessageFilter();\n\tunregisterArea();\n\tuninitDrawText();\n\tuninitDraw();\n\tCoUninitialize();\n\tif (DeleteObject(hollowBrush) == 0)\n\t\tlogLastError(L\"error freeing hollow brush\");\n\tuninitContainer();\n\tif (DeleteObject(hMessageFont) == 0)\n\t\tlogLastError(L\"error deleting control font\");\n\tunregisterWindowClass();\n\t\/\/ no need to delete the default icon or cursor; see http:\/\/stackoverflow.com\/questions\/30603077\/\n\tuninitUtilWindow();\n\tuninitAlloc();\n}\n\nvoid uiFreeInitError(const char *err)\n{\n\tif (*(err - 1) == '-')\n\t\tuiFree((void *) (err - 1));\n}\n\nBOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved)\n{\n\tif (fdwReason == DLL_PROCESS_ATTACH)\n\t\thInstance = hinstDLL;\n\treturn TRUE;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"include\/a_devdiag.h\"\n#include \"include\/netstructures.h\"\n\nvoid a_devdiag() {\n\tpcap_if_t *alldevs;\n\tchar errbuf[PCAP_ERRBUF_SIZE];\n\n\tif (pcap_findalldevs(&alldevs, errbuf) == -1) {\n\t\tprintf(\"Error in pcap_findalldevs: %s\\n\", errbuf);\n\t\texit(1);\n\t}\n\n\tint i = 0;\n\tpcap_if_t *d;\n\tfor (d = alldevs; d; d = d->next) {\n\t\tprintf(\"%d. %s\", ++i, d->name);\n\t\tif (d->description) {\n\t\t\tprintf(\" (%s)\\n\", d->description);\n\t\t}\n\t}\n\n\t\n\tint inum;\n\tprintf(\"Enter the interface number (1-%d): \", i);\n\tscanf_s(\"%d\", &inum);\n\n\tfor (d = alldevs, i = 0; i< inum - 1; d = d->next, i++);\n\n\tpcap_t *adhandle;\n\tif ((adhandle = pcap_open_live(d->name, 65536, 1000, NULL, errbuf)) == NULL) {\n\t\tprintf(\"Unable to open the network adapter. %s is not supported by WinPcap\\n\", d->name);\n\t\tpcap_freealldevs(alldevs);\n\t\texit(1);\n\t}\n\n\n\tpcap_freealldevs(alldevs);\n\tprintf(\"Starting active diagnostics...\\n\");\n\t\n\tpcap_loop(adhandle, INFINITE, a_packethandler, NULL);\n}\n\nvoid a_packethandler(u_char *param, const struct pcap_pkthdr *header, const u_char *pkt_data) {\n\tstruct tm ltime;\n\tchar timestr[16];\n\tip_header *ih;\n\tudp_header *uh;\n\tu_int ip_len;\n\tu_short sport, dport;\n\ttime_t local_tv_sec;\n\n\t(VOID)(param);\n\n\tlocal_tv_sec = header->ts.tv_sec;\n\tlocaltime_s(<ime, &local_tv_sec);\n\tstrftime(timestr, sizeof(timestr), \"%H:%M:%S\", <ime);\n\tprintf(\"%s,%.6d len:%d \", timestr, header->ts.tv_usec, header->len);\n\n\tih = (ip_header *)(pkt_data + 14);\n\n\tip_len = (ih->ver_ihl & 0xf) * 4;\n\tuh = (udp_header *)((u_char *)ih + ip_len);\n\n\tsport = ntohs(uh->sport);\n\tdport = ntohs(uh->dport);\n\n\tprintf(\"%d.%d.%d.%d.%d -> %d.%d.%d.%d.%d \\n\",\n\t\tih->saddr.byte1,\n\t\tih->saddr.byte2,\n\t\tih->saddr.byte3,\n\t\tih->saddr.byte4,\n\t\tsport,\n\t\tih->daddr.byte1,\n\t\tih->daddr.byte2,\n\t\tih->daddr.byte3,\n\t\tih->daddr.byte4,\n\t\tdport);\n\n\t\/\/struct sockaddr *sa = new sockaddr;\n\t\/\/char host[1024];\n\t\/\/char service[20];\n\t\/\/getnameinfo(sa, sizeof(sa), host, sizeof(host), service, sizeof(service), 0);\n\t\/\/printf(\"host: %s\", host);\n\t\/\/printf(\"service: %s\\n\", service);\n}<commit_msg>Added DLT ethernet check<commit_after>#include \"include\/a_devdiag.h\"\n#include \"include\/netstructures.h\"\n\nvoid a_devdiag() {\n\tpcap_if_t *alldevs;\n\tchar errbuf[PCAP_ERRBUF_SIZE];\n\n\tif (pcap_findalldevs(&alldevs, errbuf) == -1) {\n\t\tprintf(\"Error in pcap_findalldevs: %s\\n\", errbuf);\n\t\texit(1);\n\t}\n\n\tint i = 0;\n\tpcap_if_t *d;\n\tfor (d = alldevs; d; d = d->next) {\n\t\tprintf(\"%d. %s\", ++i, d->name);\n\t\tif (d->description) {\n\t\t\tprintf(\" (%s)\\n\", d->description);\n\t\t}\n\t}\n\n\t\n\tint inum;\n\tprintf(\"Enter the interface number (1-%d): \", i);\n\tscanf_s(\"%d\", &inum);\n\n\tfor (d = alldevs, i = 0; i< inum - 1; d = d->next, i++);\n\n\tpcap_t *adhandle;\n\tif ((adhandle = pcap_open_live(d->name, 65536, 1000, NULL, errbuf)) == NULL) {\n\t\tprintf(\"Unable to open the network adapter. %s is not supported by WinPcap\\n\", d->name);\n\t\tpcap_freealldevs(alldevs);\n\t\texit(1);\n\t}\n\n\tif (pcap_datalink(adhandle) != DLT_EN10MB) {\n\t\tprintf(\"Not using an ethernet device: output may not always be correct.\\n\");\n\t}\n\n\n\tpcap_freealldevs(alldevs);\n\tprintf(\"Starting active diagnostics...\\n\");\n\n\tpcap_loop(adhandle, INFINITE, a_packethandler, NULL);\n}\n\nvoid a_packethandler(u_char *param, const struct pcap_pkthdr *header, const u_char *pkt_data) {\n\tstruct tm ltime;\n\tchar timestr[16];\n\tip_header *ih;\n\tudp_header *uh;\n\tu_int ip_len;\n\tu_short sport, dport;\n\ttime_t local_tv_sec;\n\n\t(VOID)(param);\n\n\tlocal_tv_sec = header->ts.tv_sec;\n\tlocaltime_s(<ime, &local_tv_sec);\n\tstrftime(timestr, sizeof(timestr), \"%H:%M:%S\", <ime);\n\tprintf(\"%s,%.6d len:%d \", timestr, header->ts.tv_usec, header->len);\n\n\tih = (ip_header *)(pkt_data + 14);\n\n\tip_len = (ih->ver_ihl & 0xf) * 4;\n\tuh = (udp_header *)((u_char *)ih + ip_len);\n\n\tsport = ntohs(uh->sport);\n\tdport = ntohs(uh->dport);\n\n\tprintf(\"%d.%d.%d.%d.%d -> %d.%d.%d.%d.%d \\r\",\n\t\tih->saddr.byte1,\n\t\tih->saddr.byte2,\n\t\tih->saddr.byte3,\n\t\tih->saddr.byte4,\n\t\tsport,\n\t\tih->daddr.byte1,\n\t\tih->daddr.byte2,\n\t\tih->daddr.byte3,\n\t\tih->daddr.byte4,\n\t\tdport);\n}<|endoftext|>"} {"text":"<commit_before>\/***\n * @file core.hpp\n *\n * Include all of the base components required to write MLPACK methods, and the\n * main MLPACK Doxygen documentation.\n *\/\n#ifndef __MLPACK_CORE_HPP\n#define __MLPACK_CORE_HPP\n\n\/**\n * @mainpage MLPACK Documentation\n *\n * @section intro_sec Introduction\n *\n * MLPACK is an intuitive, fast, scalable C++ machine learning library, meant to\n * be a machine learning analog to LAPACK. It aims to implement a wide array of\n * machine learning methods and function as a \"swiss army knife\" for machine\n * learning researchers. The MLPACK development website can be found at\n * http:\/\/mlpack.org.\n *\n * MLPACK uses the Armadillo C++ matrix library (http:\/\/arma.sourceforge.net)\n * for general matrix, vector, and linear algebra support. MLPACK also uses the\n * program_options, math_c99, and unit_test_framework components of the Boost\n * library; in addition, LibXml2 is used.\n *\n * @section howto How To Use This Documentation\n *\n * This documentation is API documentation similar to Javadoc. It isn't\n * necessarily a tutorial, but it does provide detailed documentation on every\n * namespace, method, and class.\n *\n * Each MLPACK namespace generally refers to one machine learning method, so\n * browsing the list of namespaces provides some insight as to the breadth of\n * the methods contained in the library.\n *\n * To generate this documentation in your own local copy of MLPACK, you can\n * simply use Doxygen, from the root directory (@c \/mlpack\/trunk\/ ):\n *\n * @code\n * $ doxygen\n * @endcode\n *\n * @section executables Executables\n *\n * MLPACK provides several executables so that MLPACK methods can be used\n * without any need for knowledge of C++. These executables are all\n * self-documented, and that documentation can be accessed by running the\n * executables with the '-h' or '--help' flag.\n *\n * A full list of executables is given below:\n *\n * allkfn, allknn, emst, gmm, hmm_train, hmm_loglik, hmm_viterbi, hmm_generate,\n * kernel_pca, kmeans, lars, linear_regression, local_coordinate_coding, mvu,\n * nbc, nca, pca, radical, sparse_coding\n *\n * @section tutorial Tutorials\n *\n * A few short tutorials on how to use MLPACK are given below.\n *\n * - @ref build\n * - @ref matrices\n * - @ref iodoc\n * - @ref timer\n * - @ref sample\n *\n * Tutorials on specific methods are also available.\n *\n * - @ref nstutorial\n * - @ref lrtutorial\n * - @ref rstutorial\n * - @ref dettutorial\n * - @ref emst_tutorial\n *\n * @section methods Methods in MLPACK\n *\n * The following methods are included in MLPACK:\n *\n * - Euclidean Minimum Spanning Trees - mlpack::emst::DualTreeBoruvka\n * - Gaussian Mixture Models (GMMs) - mlpack::gmm::GMM\n * - Hidden Markov Models (HMMs) - mlpack::hmm::HMM\n * - Kernel PCA - mlpack::kpca::KernelPCA\n * - K-Means Clustering - mlpack::kmeans::KMeans\n * - Least-Angle Regression (LARS\/LASSO) - mlpack::regression::LARS\n * - Local Coordinate Coding - mlpack::lcc::LocalCoordinateCoding\n * - Naive Bayes Classifier - mlpack::naive_bayes::NaiveBayesClassifier\n * - Neighborhood Components Analysis (NCA) - mlpack::nca::NCA\n * - Principal Components Analysis (PCA) - mlpack::pca::PCA\n * - RADICAL (ICA) - mlpack::radical::Radical\n * - Simple Least-Squares Linear Regression -\n * mlpack::regression::LinearRegression\n * - Sparse Coding - mlpack::sparse_coding::SparseCoding\n * - Tree-based neighbor search (AllkNN, AllkFN) -\n * mlpack::neighbor::NeighborSearch\n * - Tree-based range search - mlpack::range::RangeSearch\n *\n * @section remarks Final Remarks\n *\n * This software was written in the FASTLab (http:\/\/www.fast-lab.org), which is\n * in the School of Computational Science and Engineering at the Georgia\n * Institute of Technology.\n *\n * MLPACK contributors include:\n *\n * - Ryan Curtin <gth671b@mail.gatech.edu>\n * - James Cline <james.cline@gatech.edu>\n * - Neil Slagle <nslagle3@gatech.edu>\n * - Matthew Amidon <mamidon@gatech.edu>\n * - Vlad Grantcharov <vlad321@gatech.edu>\n * - Ajinkya Kale <kaleajinkya@gmail.com>\n * - Bill March <march@gatech.edu>\n * - Dongryeol Lee <dongryel@cc.gatech.edu>\n * - Nishant Mehta <niche@cc.gatech.edu>\n * - Parikshit Ram <p.ram@gatech.edu>\n * - Chip Mappus <cmappus@gatech.edu>\n * - Hua Ouyang <houyang@gatech.edu>\n * - Long Quoc Tran <tqlong@gmail.com>\n * - Noah Kauffman <notoriousnoah@gmail.com>\n * - Guillermo Colon <gcolon7@mail.gatech.edu>\n * - Wei Guan <wguan@cc.gatech.edu>\n * - Ryan Riegel <rriegel@cc.gatech.edu>\n * - Nikolaos Vasiloglou <nvasil@ieee.org>\n * - Garry Boyer <garryb@gmail.com>\n * - Andreas Löf <andreas.lof@cs.waikato.ac.nz>\n *\/\n\n\/\/ First, standard includes.\n#include <stdlib.h>\n#include <stdio.h>\n#include <string.h>\n#include <ctype.h>\n#include <limits.h>\n#include <float.h>\n#include <stdint.h>\n#include <iostream>\n\n\/\/ Defining __USE_MATH_DEFINES should set M_PI.\n#define _USE_MATH_DEFINES\n#include <math.h>\n\n\/\/ For tgamma().\n#include <boost\/math\/special_functions\/gamma.hpp>\n\n\/\/ But if it's not defined, we'll do it.\n#ifndef M_PI\n #define M_PI 3.141592653589793238462643383279\n#endif\n\n\/\/ Now MLPACK-specific includes.\n#include <mlpack\/core\/arma_extend\/arma_extend.hpp> \/\/ Includes Armadillo.\n#include <mlpack\/core\/util\/log.hpp>\n#include <mlpack\/core\/util\/cli.hpp>\n#include <mlpack\/core\/data\/load.hpp>\n#include <mlpack\/core\/data\/save.hpp>\n#include <mlpack\/core\/math\/clamp.hpp>\n#include <mlpack\/core\/math\/random.hpp>\n#include <mlpack\/core\/math\/range.hpp>\n#include <mlpack\/core\/math\/round.hpp>\n#include <mlpack\/core\/util\/save_restore_utility.hpp>\n#include <mlpack\/core\/dists\/discrete_distribution.hpp>\n#include <mlpack\/core\/dists\/gaussian_distribution.hpp>\n\n\/\/ Clean up unfortunate Windows preprocessor definitions.\n\/\/ Use std::min and std::max!\n#ifdef _WIN32\n #ifdef min\n #undef min\n #endif\n\n #ifdef max\n #undef max\n #endif\n#endif\n\n#endif\n<commit_msg>Include linear algebra utilities.<commit_after>\/***\n * @file core.hpp\n *\n * Include all of the base components required to write MLPACK methods, and the\n * main MLPACK Doxygen documentation.\n *\/\n#ifndef __MLPACK_CORE_HPP\n#define __MLPACK_CORE_HPP\n\n\/**\n * @mainpage MLPACK Documentation\n *\n * @section intro_sec Introduction\n *\n * MLPACK is an intuitive, fast, scalable C++ machine learning library, meant to\n * be a machine learning analog to LAPACK. It aims to implement a wide array of\n * machine learning methods and function as a \"swiss army knife\" for machine\n * learning researchers. The MLPACK development website can be found at\n * http:\/\/mlpack.org.\n *\n * MLPACK uses the Armadillo C++ matrix library (http:\/\/arma.sourceforge.net)\n * for general matrix, vector, and linear algebra support. MLPACK also uses the\n * program_options, math_c99, and unit_test_framework components of the Boost\n * library; in addition, LibXml2 is used.\n *\n * @section howto How To Use This Documentation\n *\n * This documentation is API documentation similar to Javadoc. It isn't\n * necessarily a tutorial, but it does provide detailed documentation on every\n * namespace, method, and class.\n *\n * Each MLPACK namespace generally refers to one machine learning method, so\n * browsing the list of namespaces provides some insight as to the breadth of\n * the methods contained in the library.\n *\n * To generate this documentation in your own local copy of MLPACK, you can\n * simply use Doxygen, from the root directory (@c \/mlpack\/trunk\/ ):\n *\n * @code\n * $ doxygen\n * @endcode\n *\n * @section executables Executables\n *\n * MLPACK provides several executables so that MLPACK methods can be used\n * without any need for knowledge of C++. These executables are all\n * self-documented, and that documentation can be accessed by running the\n * executables with the '-h' or '--help' flag.\n *\n * A full list of executables is given below:\n *\n * allkfn, allknn, emst, gmm, hmm_train, hmm_loglik, hmm_viterbi, hmm_generate,\n * kernel_pca, kmeans, lars, linear_regression, local_coordinate_coding, mvu,\n * nbc, nca, pca, radical, sparse_coding\n *\n * @section tutorial Tutorials\n *\n * A few short tutorials on how to use MLPACK are given below.\n *\n * - @ref build\n * - @ref matrices\n * - @ref iodoc\n * - @ref timer\n * - @ref sample\n *\n * Tutorials on specific methods are also available.\n *\n * - @ref nstutorial\n * - @ref lrtutorial\n * - @ref rstutorial\n * - @ref dettutorial\n * - @ref emst_tutorial\n *\n * @section methods Methods in MLPACK\n *\n * The following methods are included in MLPACK:\n *\n * - Euclidean Minimum Spanning Trees - mlpack::emst::DualTreeBoruvka\n * - Gaussian Mixture Models (GMMs) - mlpack::gmm::GMM\n * - Hidden Markov Models (HMMs) - mlpack::hmm::HMM\n * - Kernel PCA - mlpack::kpca::KernelPCA\n * - K-Means Clustering - mlpack::kmeans::KMeans\n * - Least-Angle Regression (LARS\/LASSO) - mlpack::regression::LARS\n * - Local Coordinate Coding - mlpack::lcc::LocalCoordinateCoding\n * - Naive Bayes Classifier - mlpack::naive_bayes::NaiveBayesClassifier\n * - Neighborhood Components Analysis (NCA) - mlpack::nca::NCA\n * - Principal Components Analysis (PCA) - mlpack::pca::PCA\n * - RADICAL (ICA) - mlpack::radical::Radical\n * - Simple Least-Squares Linear Regression -\n * mlpack::regression::LinearRegression\n * - Sparse Coding - mlpack::sparse_coding::SparseCoding\n * - Tree-based neighbor search (AllkNN, AllkFN) -\n * mlpack::neighbor::NeighborSearch\n * - Tree-based range search - mlpack::range::RangeSearch\n *\n * @section remarks Final Remarks\n *\n * This software was written in the FASTLab (http:\/\/www.fast-lab.org), which is\n * in the School of Computational Science and Engineering at the Georgia\n * Institute of Technology.\n *\n * MLPACK contributors include:\n *\n * - Ryan Curtin <gth671b@mail.gatech.edu>\n * - James Cline <james.cline@gatech.edu>\n * - Neil Slagle <nslagle3@gatech.edu>\n * - Matthew Amidon <mamidon@gatech.edu>\n * - Vlad Grantcharov <vlad321@gatech.edu>\n * - Ajinkya Kale <kaleajinkya@gmail.com>\n * - Bill March <march@gatech.edu>\n * - Dongryeol Lee <dongryel@cc.gatech.edu>\n * - Nishant Mehta <niche@cc.gatech.edu>\n * - Parikshit Ram <p.ram@gatech.edu>\n * - Chip Mappus <cmappus@gatech.edu>\n * - Hua Ouyang <houyang@gatech.edu>\n * - Long Quoc Tran <tqlong@gmail.com>\n * - Noah Kauffman <notoriousnoah@gmail.com>\n * - Guillermo Colon <gcolon7@mail.gatech.edu>\n * - Wei Guan <wguan@cc.gatech.edu>\n * - Ryan Riegel <rriegel@cc.gatech.edu>\n * - Nikolaos Vasiloglou <nvasil@ieee.org>\n * - Garry Boyer <garryb@gmail.com>\n * - Andreas Löf <andreas.lof@cs.waikato.ac.nz>\n *\/\n\n\/\/ First, standard includes.\n#include <stdlib.h>\n#include <stdio.h>\n#include <string.h>\n#include <ctype.h>\n#include <limits.h>\n#include <float.h>\n#include <stdint.h>\n#include <iostream>\n\n\/\/ Defining __USE_MATH_DEFINES should set M_PI.\n#define _USE_MATH_DEFINES\n#include <math.h>\n\n\/\/ For tgamma().\n#include <boost\/math\/special_functions\/gamma.hpp>\n\n\/\/ But if it's not defined, we'll do it.\n#ifndef M_PI\n #define M_PI 3.141592653589793238462643383279\n#endif\n\n\/\/ Now MLPACK-specific includes.\n#include <mlpack\/core\/arma_extend\/arma_extend.hpp> \/\/ Includes Armadillo.\n#include <mlpack\/core\/util\/log.hpp>\n#include <mlpack\/core\/util\/cli.hpp>\n#include <mlpack\/core\/data\/load.hpp>\n#include <mlpack\/core\/data\/save.hpp>\n#include <mlpack\/core\/math\/clamp.hpp>\n#include <mlpack\/core\/math\/random.hpp>\n#include <mlpack\/core\/math\/lin_alg.hpp>\n#include <mlpack\/core\/math\/range.hpp>\n#include <mlpack\/core\/math\/round.hpp>\n#include <mlpack\/core\/util\/save_restore_utility.hpp>\n#include <mlpack\/core\/dists\/discrete_distribution.hpp>\n#include <mlpack\/core\/dists\/gaussian_distribution.hpp>\n\n\/\/ Clean up unfortunate Windows preprocessor definitions.\n\/\/ Use std::min and std::max!\n#ifdef _WIN32\n #ifdef min\n #undef min\n #endif\n\n #ifdef max\n #undef max\n #endif\n#endif\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n#include <string>\n#include <vector>\n#include <algorithm>\nusing namespace std;\nint main(int argc, char const *argv[]) {\n\n\treturn 0;\n}\n<commit_msg>adding<commit_after>\/\/http:\/\/codeforces.com\/problemset\/problem\/601\/A\n#include <iostream>\n#include <string>\n#include <vector>\n#include <algorithm>\nusing namespace std;\nint main(int argc, char const *argv[]) {\n\n\treturn 0;\n}\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n#include <string>\n#include <vector>\n#include <algorithm>\nusing namespace std;\nint main(int argc, char const *argv[]) {\n\n\treturn 0;\n}\n<commit_msg>adding<commit_after>#include <iostream>\n#include <string>\n#include <vector>\n#include <algorithm>\nusing namespace std;\nbool g[3001][3001];\nint main(int argc, char const *argv[]) {\n\tint n,m;\n\tcin>>n>>m;\n\tstd::vector<int> neigh[n];\n\tfor(int i=0;i<m;i++){\n\t\tint a,b;\n\t\tcin>>a>>b;\n\t\t\n\t}\n\treturn 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * The MIT License (MIT)\n *\n * Copyright (c) 2015 Microsoft Corporation\n * \n * -=- Robust Distributed System Nucleus (rDSN) -=- \n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n *\/\n\n# include <dsn\/ports.h>\n# include <dsn\/service_api_c.h>\n# include <dsn\/cpp\/address.h>\n\n# ifdef _WIN32\n\n\n# else\n# include <sys\/socket.h>\n# include <netdb.h>\n# include <arpa\/inet.h>\n\n# if defined(__FreeBSD__)\n# include <netinet\/in.h>\n# endif\n\n# endif\n\n# include <mutex>\n\nstatic void net_init()\n{\n static std::once_flag flag;\n static bool flag_inited = false;\n if (!flag_inited)\n {\n std::call_once(flag, [&]()\n {\n#ifdef _WIN32\n WSADATA wsaData;\n WSAStartup(MAKEWORD(2, 2), &wsaData);\n#endif\n flag_inited = true;\n });\n }\n}\n\nDSN_API void dsn_address_build(dsn_address_t* ep, const char* host, uint16_t port)\n{\n net_init();\n\n ::dsn::rpc_address addr(HOST_TYPE_IPV4, host, port);\n *ep = addr.c_addr();\n}\n\nDSN_API void dsn_address_build_ipv4(\n \/*out*\/ dsn_address_t* ep,\n uint32_t ipv4,\n uint16_t port\n )\n{\n net_init();\n ::dsn::rpc_address addr(ipv4, port);\n *ep = addr.c_addr();\n}\n\n\n\/\/ ip etc. to name\nDSN_API void dsn_host_to_name(const dsn_address_t* addr, \/*out*\/ char* name_buffer, int length)\n{\n switch (addr->type)\n {\n case HOST_TYPE_IPV4:\n {\n uint32_t nip = htonl(addr->ip);\n\n \/\/ TODO: using global cache\n auto host = gethostbyaddr((char*)&nip, 4, AF_INET);\n if (host == nullptr)\n {\n# if defined(_WIN32)\n sprintf_s(\n# else\n std::snprintf(\n# endif\n name_buffer, (size_t)length,\n \"%u.%u.%u.%u\",\n nip & 0xff,\n (nip >> 8) & 0xff,\n (nip >> 16) & 0xff,\n (nip >> 24) & 0xff\n );\n }\n else\n {\n strncpy(name_buffer, host->h_name, length);\n }\n name_buffer[length - 1] = '\\0';\n }\n break;\n case HOST_TYPE_IPV6:\n dassert(false, \"to be implemented\");\n break;\n case HOST_TYPE_URI:\n dassert(false, \"to be implemented\");\n break;\n default:\n break;\n }\n}\n\n\/\/ name to ip etc.\nDSN_API void dsn_host_from_name(dsn_host_type_t type, const char* name, \/*out*\/ dsn_address_t* daddr)\n{\n sockaddr_in addr;\n memset(&addr, 0, sizeof(addr));\n\n daddr->type = type;\n switch (type)\n {\n case HOST_TYPE_IPV4:\n addr.sin_family = AF_INET;\n if ((addr.sin_addr.s_addr = inet_addr(name)) == (unsigned int)(-1))\n {\n hostent* hp = gethostbyname(name);\n if (hp != 0)\n {\n memcpy(\n (void*)&(addr.sin_addr.s_addr),\n (const void*)hp->h_addr,\n (size_t)hp->h_length\n );\n }\n else\n {\n int err = h_errno;\n dassert(false, \"Fail to get host by name. error = %s.\", ::hstrerror(err));\n }\n }\n\n \/\/ network order\n daddr->ip = (uint32_t)ntohl(addr.sin_addr.s_addr);\n break;\n\n case HOST_TYPE_IPV6:\n dassert(false, \"to be implemented\");\n break;\n\n case HOST_TYPE_URI:\n daddr->uri = name;\n break;\n\n default:\n break;\n }\n}\n<commit_msg>Nits.<commit_after>\/*\n * The MIT License (MIT)\n *\n * Copyright (c) 2015 Microsoft Corporation\n * \n * -=- Robust Distributed System Nucleus (rDSN) -=- \n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n *\/\n\n# include <dsn\/ports.h>\n# include <dsn\/service_api_c.h>\n# include <dsn\/cpp\/address.h>\n\n# ifdef _WIN32\n\n\n# else\n# include <sys\/socket.h>\n# include <netdb.h>\n# include <arpa\/inet.h>\n\n# if defined(__FreeBSD__)\n# include <netinet\/in.h>\n# endif\n\n# endif\n\n# include <mutex>\n\nstatic void net_init()\n{\n static std::once_flag flag;\n static bool flag_inited = false;\n if (!flag_inited)\n {\n std::call_once(flag, [&]()\n {\n#ifdef _WIN32\n WSADATA wsaData;\n WSAStartup(MAKEWORD(2, 2), &wsaData);\n#endif\n flag_inited = true;\n });\n }\n}\n\nDSN_API void dsn_address_build(dsn_address_t* ep, const char* host, uint16_t port)\n{\n net_init();\n\n ::dsn::rpc_address addr(HOST_TYPE_IPV4, host, port);\n *ep = addr.c_addr();\n}\n\nDSN_API void dsn_address_build_ipv4(\n \/*out*\/ dsn_address_t* ep,\n uint32_t ipv4,\n uint16_t port\n )\n{\n net_init();\n ::dsn::rpc_address addr(ipv4, port);\n *ep = addr.c_addr();\n}\n\n\n\/\/ ip etc. to name\nDSN_API void dsn_host_to_name(const dsn_address_t* addr, \/*out*\/ char* name_buffer, int length)\n{\n switch (addr->type)\n {\n case HOST_TYPE_IPV4:\n {\n uint32_t nip = htonl(addr->ip);\n\n \/\/ TODO: using global cache\n auto host = gethostbyaddr((char*)&nip, 4, AF_INET);\n if (host == nullptr)\n {\n# if defined(_WIN32)\n sprintf_s(\n# else\n std::snprintf(\n# endif\n name_buffer, (size_t)length,\n \"%u.%u.%u.%u\",\n nip & 0xff,\n (nip >> 8) & 0xff,\n (nip >> 16) & 0xff,\n (nip >> 24) & 0xff\n );\n }\n else\n {\n strncpy(name_buffer, host->h_name, length);\n }\n name_buffer[length - 1] = '\\0';\n }\n break;\n case HOST_TYPE_IPV6:\n dassert(false, \"to be implemented\");\n break;\n case HOST_TYPE_URI:\n dassert(false, \"to be implemented\");\n break;\n default:\n break;\n }\n}\n\n\/\/ name to ip etc.\nDSN_API void dsn_host_from_name(dsn_host_type_t type, const char* name, \/*out*\/ dsn_address_t* daddr)\n{\n sockaddr_in addr;\n memset(&addr, 0, sizeof(addr));\n\n daddr->type = type;\n switch (type)\n {\n case HOST_TYPE_IPV4:\n addr.sin_family = AF_INET;\n if ((addr.sin_addr.s_addr = inet_addr(name)) == (unsigned int)(-1))\n {\n hostent* hp = gethostbyname(name);\n dassert(hp != nullptr, \"gethostbyname failed, err = %s.\", ::hstrerror(h_errno));\n if (hp != nullptr)\n {\n memcpy(\n (void*)&(addr.sin_addr.s_addr),\n (const void*)hp->h_addr,\n (size_t)hp->h_length\n );\n }\n }\n\n \/\/ network order\n daddr->ip = (uint32_t)ntohl(addr.sin_addr.s_addr);\n break;\n\n case HOST_TYPE_IPV6:\n dassert(false, \"to be implemented\");\n break;\n\n case HOST_TYPE_URI:\n daddr->uri = name;\n break;\n\n default:\n break;\n }\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"connection_manager.hpp\"\n#include \"karabiner_version.h\"\n#include <iostream>\n#include <unistd.h>\n\nint main(int argc, const char* argv[]) {\n if (getuid() != 0) {\n std::cerr << \"fatal: karabiner_grabber requires root privilege.\" << std::endl;\n exit(1);\n }\n\n signal(SIGUSR1, SIG_IGN);\n signal(SIGUSR2, SIG_IGN);\n\n logger::get_logger().info(\"version {0}\", karabiner_version);\n\n device_grabber device_grabber;\n connection_manager connection_manager(device_grabber);\n\n CFRunLoopRun();\n\n return 0;\n}\n<commit_msg>post grabber_is_launched notification<commit_after>#include \"connection_manager.hpp\"\n#include \"constants.hpp\"\n#include \"karabiner_version.h\"\n#include \"notification_center.hpp\"\n#include <iostream>\n#include <unistd.h>\n\nint main(int argc, const char* argv[]) {\n if (getuid() != 0) {\n std::cerr << \"fatal: karabiner_grabber requires root privilege.\" << std::endl;\n exit(1);\n }\n\n signal(SIGUSR1, SIG_IGN);\n signal(SIGUSR2, SIG_IGN);\n\n logger::get_logger().info(\"version {0}\", karabiner_version);\n\n device_grabber device_grabber;\n connection_manager connection_manager(device_grabber);\n\n notification_center::post_distributed_notification_to_all_sessions(constants::get_distributed_notification_grabber_is_launched());\n\n CFRunLoopRun();\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"crossVideoGrabber.h\"\n\nvoid crossVideoGrabber::setup(string filename){\n\n videoFlag = videoPlayer.load(\"movies\/\"+filename);\n if (videoFlag) {\n videoPlayer.setLoopState(OF_LOOP_NORMAL);\n videoPlayer.play();\n } else {\n#ifdef TARGET_RASPBERRY_PI\n cam.setup(1920,1080,false);\n \/\/cam.setup(2592, 1944, false);\n led.switchOnIR();\n#else\n cam.initGrabber(640, 480);\n#endif\n }\n}\n\nvoid crossVideoGrabber::update(){\n if ( videoFlag ) {\n videoPlayer.update();\n } else {\n#ifdef TARGET_RASPBERRY_PI\n newFrame = cam.isFrameNew();\n frame = cam.grab();\n#else\n cam.update();\n#endif\n }\n}\nvoid crossVideoGrabber::draw(int x, int y){\n if ( videoFlag ){\n videoPlayer.draw(x,y);\n } else {\n#ifndef TARGET_RASPBERRY_PI\n cam.draw(x,y);\n#else\n ofxCv::drawMat(frame,0,0,ofGetWidth(), ofGetHeight());\n#endif\n }\n}\n<commit_msg>strech input video to fulfill the display<commit_after>#include \"crossVideoGrabber.h\"\n\nvoid crossVideoGrabber::setup(string filename){\n\n videoFlag = videoPlayer.load(\"movies\/\"+filename);\n if (videoFlag) {\n videoPlayer.setLoopState(OF_LOOP_NORMAL);\n videoPlayer.play();\n } else {\n#ifdef TARGET_RASPBERRY_PI\n cam.setup(1920,1080,false);\n \/\/cam.setup(2592, 1944, false);\n led.switchOnIR();\n#else\n cam.initGrabber(640, 480);\n#endif\n }\n}\n\nvoid crossVideoGrabber::update(){\n if ( videoFlag ) {\n videoPlayer.update();\n } else {\n#ifdef TARGET_RASPBERRY_PI\n newFrame = cam.isFrameNew();\n frame = cam.grab();\n#else\n cam.update();\n#endif\n }\n}\nvoid crossVideoGrabber::draw(int x, int y){\n if ( videoFlag ){\n videoPlayer.draw(x,y,ofGetWidth(), ofGetHeight());\n } else {\n#ifndef TARGET_RASPBERRY_PI\n cam.draw(x,y);\n#else\n ofxCv::drawMat(frame,0,0,ofGetWidth(), ofGetHeight());\n#endif\n }\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"vtrace.h\"\n#include \"..\/logger.h\"\n\nViterbiTraceMatrix::ViterbiTraceMatrix (const EvaluatedMachine& eval, const GaussianModelParams& modelParams, const TraceMoments& trace, const TraceParams& traceParams, size_t blockBytes, double bandWidth) :\n TraceDPMatrix (eval, modelParams, trace, traceParams, blockBytes, bandWidth)\n{\n ProgressLog(plog,3);\n plog.initProgress (\"Viterbi algorithm (%ld samples, %u states, %u transitions)\", outLen, nStates, nTrans);\n\n cell(0,eval.startState()) = 0;\n for (const auto& it: nullTrans)\n update (0, it.dest, cell(0,it.src) + it.logWeight, it.in);\n\n for (OutputIndex outPos = 1; outPos <= outLen; ++outPos) {\n plog.logProgress ((outPos - 1) \/ (double) outLen, \"sample %ld\/%ld\", outPos, outLen);\n fillColumn (outPos);\n }\n\n logLike = cell (outLen, eval.endState());\n LogThisAt(6,\"Viterbi log-likelihood: \" << logLike << endl);\n LogThisAt(10,\"Viterbi matrix:\" << endl << *this);\n}\n\nvoid ViterbiTraceMatrix::fillColumn (OutputIndex outPos) {\n vguard<double>& thisColumn = column(outPos);\n initColumn (thisColumn);\n const auto itBegin = bandTransBegin(outPos);\n const auto itEnd = bandTransEnd(outPos);\n for (auto itIter = itBegin; itIter != itEnd; ++itIter) {\n const auto& it = *itIter;\n const OutputToken outTok = it.out;\n const double llEmit = logEmitProb(outPos,outTok);\n update (outPos, it.dest, cell(outPos-1,it.src) + logTransProb(outPos,it) + llEmit, it.in);\n }\n\n for (const auto& it: nullTrans)\n update (outPos, it.dest, cell(outPos,it.src) + it.logWeight, it.in);\n\n lastCheckpoint = checkpoint(outPos);\n}\n\nvoid ViterbiTraceMatrix::readyColumn (OutputIndex outPos) {\n const OutputIndex blockStart = checkpoint(outPos);\n if (blockStart != lastCheckpoint) {\n const OutputIndex blockEnd = min((OutputIndex)nColumns,blockStart+blockSize) - 1;\n LogThisAt(4,\"Refilling Viterbi matrix from sample \" << (blockStart+1) << \" to \" << blockEnd << endl);\n\n for (OutputIndex outPos = blockStart + 1; outPos <= blockEnd; ++outPos)\n fillColumn (outPos);\n }\n}\n\nMachinePath ViterbiTraceMatrix::path (const Machine& m) {\n Assert (logLike > -numeric_limits<double>::infinity(), \"Can't do Viterbi traceback: no finite-weight paths\");\n MachinePath path;\n OutputIndex outPos = outLen;\n StateIndex s = nStates - 1;\n while (outPos > 0 || s != 0) {\n const EvaluatedMachineState& state = eval.state[s];\n double bestLogLike = -numeric_limits<double>::infinity();\n const EvaluatedMachineState::Trans *bestTrans, *bestLoopTrans = NULL;\n StateIndex bestSource;\n readyColumn (outPos - 1);\n for (const auto& inTok_outStateTransMap: state.incoming) {\n const InputToken inTok = inTok_outStateTransMap.first;\n for (const auto& outTok_stateTransMap: inTok_outStateTransMap.second) {\n\tconst OutputToken outTok = outTok_stateTransMap.first;\n\tif (outTok == 0 || outPos > 0)\n\t for (const auto& src_trans: outTok_stateTransMap.second) {\n\t const double tll = logIncomingProb (inTok, outTok, outPos, src_trans.first, s, src_trans.second);\n\t if (tll > bestLogLike) {\n\t bestLogLike = tll;\n\t bestLoopTrans = getLoopTrans (inTok, outTok, s);\n\t bestSource = src_trans.first;\n\t bestTrans = &src_trans.second;\n\t }\n\t }\n }\n }\n const MachineTransition& bestMachineTrans = m.state[bestSource].getTransition (bestTrans->transIndex);\n if (!bestMachineTrans.outputEmpty()) {\n if (bestLoopTrans) {\n\tconst MachineTransition& bestLoopMachineTrans = m.state[s].getTransition (bestLoopTrans->transIndex);\n\tconst auto& mom = moments.sample[outPos-1];\n\tfor (int n = 1; n < mom.m0; ++n)\n\t path.trans.push_front (bestLoopMachineTrans);\n }\n --outPos;\n }\n s = bestSource;\n path.trans.push_front (bestMachineTrans);\n }\n return path;\n}\n<commit_msg>Logging during Viterbi traceback<commit_after>#include \"vtrace.h\"\n#include \"..\/logger.h\"\n\nViterbiTraceMatrix::ViterbiTraceMatrix (const EvaluatedMachine& eval, const GaussianModelParams& modelParams, const TraceMoments& trace, const TraceParams& traceParams, size_t blockBytes, double bandWidth) :\n TraceDPMatrix (eval, modelParams, trace, traceParams, blockBytes, bandWidth)\n{\n ProgressLog(plog,3);\n plog.initProgress (\"Viterbi algorithm (%ld samples, %u states, %u transitions)\", outLen, nStates, nTrans);\n\n cell(0,eval.startState()) = 0;\n for (const auto& it: nullTrans)\n update (0, it.dest, cell(0,it.src) + it.logWeight, it.in);\n\n for (OutputIndex outPos = 1; outPos <= outLen; ++outPos) {\n plog.logProgress ((outPos - 1) \/ (double) outLen, \"sample %ld\/%ld\", outPos, outLen);\n fillColumn (outPos);\n }\n\n logLike = cell (outLen, eval.endState());\n LogThisAt(6,\"Viterbi log-likelihood: \" << logLike << endl);\n LogThisAt(10,\"Viterbi matrix:\" << endl << *this);\n}\n\nvoid ViterbiTraceMatrix::fillColumn (OutputIndex outPos) {\n vguard<double>& thisColumn = column(outPos);\n initColumn (thisColumn);\n const auto itBegin = bandTransBegin(outPos);\n const auto itEnd = bandTransEnd(outPos);\n for (auto itIter = itBegin; itIter != itEnd; ++itIter) {\n const auto& it = *itIter;\n const OutputToken outTok = it.out;\n const double llEmit = logEmitProb(outPos,outTok);\n update (outPos, it.dest, cell(outPos-1,it.src) + logTransProb(outPos,it) + llEmit, it.in);\n }\n\n for (const auto& it: nullTrans)\n update (outPos, it.dest, cell(outPos,it.src) + it.logWeight, it.in);\n\n lastCheckpoint = checkpoint(outPos);\n}\n\nvoid ViterbiTraceMatrix::readyColumn (OutputIndex outPos) {\n const OutputIndex blockStart = checkpoint(outPos);\n if (blockStart != lastCheckpoint) {\n const OutputIndex blockEnd = min((OutputIndex)nColumns,blockStart+blockSize) - 1;\n LogThisAt(4,\"Refilling Viterbi matrix from sample \" << (blockStart+1) << \" to \" << blockEnd << endl);\n\n for (OutputIndex outPos = blockStart + 1; outPos <= blockEnd; ++outPos)\n fillColumn (outPos);\n }\n}\n\nMachinePath ViterbiTraceMatrix::path (const Machine& m) {\n Assert (logLike > -numeric_limits<double>::infinity(), \"Can't do Viterbi traceback: no finite-weight paths\");\n ProgressLog(plog,3);\n plog.initProgress (\"Viterbi traceback (%ld samples, %u states, %u transitions)\", outLen, nStates, nTrans);\n MachinePath path;\n OutputIndex outPos = outLen;\n StateIndex s = nStates - 1;\n while (outPos > 0 || s != 0) {\n plog.logProgress ((outLen - outPos) \/ (double) outLen, \"sample %ld\/%ld\", outPos, outLen);\n const EvaluatedMachineState& state = eval.state[s];\n double bestLogLike = -numeric_limits<double>::infinity();\n const EvaluatedMachineState::Trans *bestTrans, *bestLoopTrans = NULL;\n StateIndex bestSource;\n readyColumn (outPos - 1);\n for (const auto& inTok_outStateTransMap: state.incoming) {\n const InputToken inTok = inTok_outStateTransMap.first;\n for (const auto& outTok_stateTransMap: inTok_outStateTransMap.second) {\n\tconst OutputToken outTok = outTok_stateTransMap.first;\n\tif (outTok == 0 || outPos > 0)\n\t for (const auto& src_trans: outTok_stateTransMap.second) {\n\t const double tll = logIncomingProb (inTok, outTok, outPos, src_trans.first, s, src_trans.second);\n\t if (tll > bestLogLike) {\n\t bestLogLike = tll;\n\t bestLoopTrans = getLoopTrans (inTok, outTok, s);\n\t bestSource = src_trans.first;\n\t bestTrans = &src_trans.second;\n\t }\n\t }\n }\n }\n const MachineTransition& bestMachineTrans = m.state[bestSource].getTransition (bestTrans->transIndex);\n if (!bestMachineTrans.outputEmpty()) {\n if (bestLoopTrans) {\n\tconst MachineTransition& bestLoopMachineTrans = m.state[s].getTransition (bestLoopTrans->transIndex);\n\tconst auto& mom = moments.sample[outPos-1];\n\tfor (int n = 1; n < mom.m0; ++n)\n\t path.trans.push_front (bestLoopMachineTrans);\n }\n --outPos;\n }\n s = bestSource;\n path.trans.push_front (bestMachineTrans);\n }\n return path;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"progress.h\"\n#include \"simulator.h\"\n#include \"config.hpp\"\n#include \"core_manager.h\"\n#include \"hooks_manager.h\"\n#include \"trace_manager.h\"\n#include \"magic_server.h\"\n\nProgress::Progress()\n : m_enabled(false)\n , m_t_last(0)\n , m_manual(false)\n , m_manual_value(0.f)\n{\n String filename = Sim()->getCfg()->getString(\"progress_trace\/filename\");\n\n if (!filename.empty())\n {\n m_fp = fopen(filename.c_str(), \"w\");\n m_enabled = true;\n\n Sim()->getHooksManager()->registerHook(HookType::HOOK_PERIODIC_INS, __record, (UInt64)this);\n }\n}\n\nProgress::~Progress(void)\n{\n if (m_enabled)\n {\n record(0);\n fclose(m_fp);\n }\n}\n\nvoid Progress::setProgress(float progress)\n{\n m_manual = true;\n m_manual_value = progress;\n}\n\nvoid Progress::record(UInt64 simtime)\n{\n if (m_t_last + m_interval < time(NULL))\n {\n m_t_last = time(NULL);\n\n UInt64 expect = 0;\n\n \/\/ Always return global instruction count, so MIPS number as reported by job infrastructure is correct\n UInt64 progress = MagicServer::getGlobalInstructionCount();\n\n if (m_manual && m_manual_value > 0)\n {\n \/\/ Re-compute expected completion based on current progress\n expect = progress \/ m_manual_value;\n }\n else if (Sim()->getTraceManager())\n {\n UInt64 _expect = Sim()->getTraceManager()->getProgressExpect();\n UInt64 _progress = Sim()->getTraceManager()->getProgressValue();\n\n \/\/ Re-compute expected completion based on file-pointer based % to completion,\n \/\/ and the progress value (instruction count) we'll return\n if (_progress > 1)\n expect = progress * _expect \/ _progress;\n else\n expect = 100000 * progress;\n }\n\n rewind(m_fp);\n fprintf(m_fp, \"%u %\" PRId64 \" %\" PRId64, unsigned(time(NULL)), progress, expect);\n fflush(m_fp);\n }\n}\n<commit_msg>[progress] Do not callt to update the progress in the destructor as the CoreManager() has already been destroyed (needed by MagicServer::getGlobalInstructionCount())<commit_after>#include \"progress.h\"\n#include \"simulator.h\"\n#include \"config.hpp\"\n#include \"core_manager.h\"\n#include \"hooks_manager.h\"\n#include \"trace_manager.h\"\n#include \"magic_server.h\"\n\nProgress::Progress()\n : m_enabled(false)\n , m_t_last(0)\n , m_manual(false)\n , m_manual_value(0.f)\n{\n String filename = Sim()->getCfg()->getString(\"progress_trace\/filename\");\n\n if (!filename.empty())\n {\n m_fp = fopen(filename.c_str(), \"w\");\n m_enabled = true;\n\n Sim()->getHooksManager()->registerHook(HookType::HOOK_PERIODIC_INS, __record, (UInt64)this);\n }\n}\n\nProgress::~Progress(void)\n{\n if (m_enabled)\n {\n fclose(m_fp);\n }\n}\n\nvoid Progress::setProgress(float progress)\n{\n m_manual = true;\n m_manual_value = progress;\n}\n\nvoid Progress::record(UInt64 simtime)\n{\n if (m_t_last + m_interval < time(NULL))\n {\n m_t_last = time(NULL);\n\n UInt64 expect = 0;\n\n \/\/ Always return global instruction count, so MIPS number as reported by job infrastructure is correct\n UInt64 progress = MagicServer::getGlobalInstructionCount();\n\n if (m_manual && m_manual_value > 0)\n {\n \/\/ Re-compute expected completion based on current progress\n expect = progress \/ m_manual_value;\n }\n else if (Sim()->getTraceManager())\n {\n UInt64 _expect = Sim()->getTraceManager()->getProgressExpect();\n UInt64 _progress = Sim()->getTraceManager()->getProgressValue();\n\n \/\/ Re-compute expected completion based on file-pointer based % to completion,\n \/\/ and the progress value (instruction count) we'll return\n if (_progress > 1)\n expect = progress * _expect \/ _progress;\n else\n expect = 100000 * progress;\n }\n\n rewind(m_fp);\n fprintf(m_fp, \"%u %\" PRId64 \" %\" PRId64, unsigned(time(NULL)), progress, expect);\n fflush(m_fp);\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2013 GitHub, Inc. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"common\/node_bindings.h\"\n\n#include \"base\/command_line.h\"\n#include \"base\/files\/file_path.h\"\n#include \"base\/logging.h\"\n#include \"v8\/include\/v8.h\"\n#include \"third_party\/WebKit\/Source\/WebKit\/chromium\/public\/WebDocument.h\"\n#include \"third_party\/WebKit\/Source\/WebKit\/chromium\/public\/WebFrame.h\"\n#include \"vendor\/node\/src\/node.h\"\n#include \"vendor\/node\/src\/node_internals.h\"\n#include \"vendor\/node\/src\/node_javascript.h\"\n\nnamespace atom {\n\nNodeBindings::NodeBindings(bool is_browser)\n : is_browser_(is_browser) {\n}\n\nNodeBindings::~NodeBindings() {\n}\n\nvoid NodeBindings::Initialize() {\n CommandLine::StringVector str_argv = CommandLine::ForCurrentProcess()->argv();\n\n \/\/ Convert string vector to char* array.\n std::vector<char*> argv(str_argv.size(), NULL);\n for (size_t i = 0; i < str_argv.size(); ++i)\n argv[i] = const_cast<char*>(str_argv[i].c_str());\n\n \/\/ Open node's error reporting system for browser process.\n node::g_standalone_mode = is_browser_;\n\n \/\/ Init node.\n node::Init(argv.size(), &argv[0]);\n v8::V8::Initialize();\n\n \/\/ Load node.js.\n v8::HandleScope scope;\n node::g_context = v8::Persistent<v8::Context>::New(\n node::node_isolate, v8::Context::New(node::node_isolate));\n {\n v8::Context::Scope context_scope(node::g_context);\n v8::Handle<v8::Object> process = node::SetupProcessObject(\n argv.size(), &argv[0]);\n\n \/\/ Tell node.js we are in browser or renderer.\n v8::Handle<v8::String> type =\n is_browser_ ? v8::String::New(\"browser\") : v8::String::New(\"renderer\");\n process->Set(v8::String::New(\"__atom_type\"), type);\n }\n}\n\nvoid NodeBindings::Load() {\n v8::HandleScope scope;\n v8::Context::Scope context_scope(node::g_context);\n node::Load(node::process);\n}\n\nvoid NodeBindings::BindTo(WebKit::WebFrame* frame) {\n v8::HandleScope handle_scope;\n\n v8::Handle<v8::Context> context = frame->mainWorldScriptContext();\n if (context.IsEmpty())\n return;\n\n v8::Context::Scope scope(context);\n\n \/\/ Erase security token.\n context->SetSecurityToken(node::g_context->GetSecurityToken());\n\n \/\/ Evaluate cefode.js.\n v8::Handle<v8::Script> script = node::CompileCefodeMainSource();\n v8::Local<v8::Value> result = script->Run();\n\n \/\/ Run the script of cefode.js.\n std::string script_path(GURL(frame->document().url()).path());\n v8::Handle<v8::Value> args[2] = {\n v8::Local<v8::Value>::New(node::process),\n v8::String::New(script_path.c_str(), script_path.size())\n };\n v8::Local<v8::Function>::Cast(result)->Call(context->Global(), 2, args);\n}\n\n} \/\/ namespace atom\n<commit_msg>Implement converting string vector to char pointer array on Windows.<commit_after>\/\/ Copyright (c) 2013 GitHub, Inc. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"common\/node_bindings.h\"\n\n#include \"base\/command_line.h\"\n#include \"base\/files\/file_path.h\"\n#include \"base\/logging.h\"\n#include \"base\/strings\/utf_string_conversions.h\"\n#include \"v8\/include\/v8.h\"\n#include \"third_party\/WebKit\/Source\/WebKit\/chromium\/public\/WebDocument.h\"\n#include \"third_party\/WebKit\/Source\/WebKit\/chromium\/public\/WebFrame.h\"\n#include \"vendor\/node\/src\/node.h\"\n#include \"vendor\/node\/src\/node_internals.h\"\n#include \"vendor\/node\/src\/node_javascript.h\"\n\nnamespace atom {\n\nNodeBindings::NodeBindings(bool is_browser)\n : is_browser_(is_browser) {\n}\n\nNodeBindings::~NodeBindings() {\n}\n\nvoid NodeBindings::Initialize() {\n CommandLine::StringVector str_argv = CommandLine::ForCurrentProcess()->argv();\n\n#if defined(OS_WIN)\n std::vector<std::string> utf8_str_argv;\n utf8_str_argv.reserve(str_argv.size());\n#endif\n\n \/\/ Convert string vector to char* array.\n std::vector<char*> argv(str_argv.size(), NULL);\n for (size_t i = 0; i < str_argv.size(); ++i) {\n#if defined(OS_WIN)\n utf8_str_argv.push_back(UTF16ToUTF8(str_argv[i]));\n argv[i] = const_cast<char*>(utf8_str_argv[i].c_str());\n#else\n argv[i] = const_cast<char*>(str_argv[i].c_str());\n#endif\n }\n\n \/\/ Open node's error reporting system for browser process.\n node::g_standalone_mode = is_browser_;\n\n \/\/ Init node.\n node::Init(argv.size(), &argv[0]);\n v8::V8::Initialize();\n\n \/\/ Load node.js.\n v8::HandleScope scope;\n node::g_context = v8::Persistent<v8::Context>::New(\n node::node_isolate, v8::Context::New(node::node_isolate));\n {\n v8::Context::Scope context_scope(node::g_context);\n v8::Handle<v8::Object> process = node::SetupProcessObject(\n argv.size(), &argv[0]);\n\n \/\/ Tell node.js we are in browser or renderer.\n v8::Handle<v8::String> type =\n is_browser_ ? v8::String::New(\"browser\") : v8::String::New(\"renderer\");\n process->Set(v8::String::New(\"__atom_type\"), type);\n }\n}\n\nvoid NodeBindings::Load() {\n v8::HandleScope scope;\n v8::Context::Scope context_scope(node::g_context);\n node::Load(node::process);\n}\n\nvoid NodeBindings::BindTo(WebKit::WebFrame* frame) {\n v8::HandleScope handle_scope;\n\n v8::Handle<v8::Context> context = frame->mainWorldScriptContext();\n if (context.IsEmpty())\n return;\n\n v8::Context::Scope scope(context);\n\n \/\/ Erase security token.\n context->SetSecurityToken(node::g_context->GetSecurityToken());\n\n \/\/ Evaluate cefode.js.\n v8::Handle<v8::Script> script = node::CompileCefodeMainSource();\n v8::Local<v8::Value> result = script->Run();\n\n \/\/ Run the script of cefode.js.\n std::string script_path(GURL(frame->document().url()).path());\n v8::Handle<v8::Value> args[2] = {\n v8::Local<v8::Value>::New(node::process),\n v8::String::New(script_path.c_str(), script_path.size())\n };\n v8::Local<v8::Function>::Cast(result)->Call(context->Global(), 2, args);\n}\n\n} \/\/ namespace atom\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2011 Google Inc. All Rights Reserved.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n\/\/ This file is all the code that used to be in one file.\n\/\/ TODO: split into modules, delete this file.\n\n#include \"ninja.h\"\n\n#include <errno.h>\n#include <sys\/stat.h>\n#include <stdio.h>\n#include <string.h>\n\n#include \"build_log.h\"\n#include \"graph.h\"\n\nint ReadFile(const string& path, string* contents, string* err) {\n FILE* f = fopen(path.c_str(), \"r\");\n if (!f) {\n err->assign(strerror(errno));\n return -errno;\n }\n\n char buf[64 << 10];\n size_t len;\n while ((len = fread(buf, 1, sizeof(buf), f)) > 0) {\n contents->append(buf, len);\n }\n if (ferror(f)) {\n err->assign(strerror(errno)); \/\/ XXX errno?\n contents->clear();\n fclose(f);\n return -errno;\n }\n fclose(f);\n return 0;\n}\n\nint RealDiskInterface::Stat(const string& path) {\n struct stat st;\n if (stat(path.c_str(), &st) < 0) {\n if (errno == ENOENT) {\n return 0;\n } else {\n fprintf(stderr, \"stat(%s): %s\\n\", path.c_str(), strerror(errno));\n return -1;\n }\n }\n\n return st.st_mtime;\n return true;\n}\n\nstring DirName(const string& path) {\n string::size_type slash_pos = path.rfind('\/');\n if (slash_pos == string::npos)\n return \"\"; \/\/ Nothing to do.\n while (slash_pos > 0 && path[slash_pos - 1] == '\/')\n --slash_pos;\n return path.substr(0, slash_pos);\n}\n\nbool DiskInterface::MakeDirs(const string& path) {\n string dir = DirName(path);\n if (dir.empty())\n return true; \/\/ Reached root; assume it's there.\n int mtime = Stat(dir);\n if (mtime < 0)\n return false; \/\/ Error.\n if (mtime > 0)\n return true; \/\/ Exists already; we're done.\n\n \/\/ Directory doesn't exist. Try creating its parent first.\n bool success = MakeDirs(dir);\n if (!success)\n return false;\n return MakeDir(dir);\n}\n\nstring RealDiskInterface::ReadFile(const string& path, string* err) {\n string contents;\n int ret = ::ReadFile(path, &contents, err);\n if (ret == -ENOENT) {\n \/\/ Swallow ENOENT.\n err->clear();\n }\n return contents;\n}\n\nbool RealDiskInterface::MakeDir(const string& path) {\n if (mkdir(path.c_str(), 0777) < 0) {\n fprintf(stderr, \"mkdir(%s): %s\\n\", path.c_str(), strerror(errno));\n return false;\n }\n return true;\n}\n\nFileStat* StatCache::GetFile(const string& path) {\n Paths::iterator i = paths_.find(path);\n if (i != paths_.end())\n return i->second;\n FileStat* file = new FileStat(path);\n paths_[path] = file;\n return file;\n}\n\n#include <stdio.h>\n\nvoid StatCache::Dump() {\n for (Paths::iterator i = paths_.begin(); i != paths_.end(); ++i) {\n FileStat* file = i->second;\n printf(\"%s %s\\n\",\n file->path_.c_str(),\n file->status_known()\n ? (file->node_->dirty_ ? \"dirty\" : \"clean\")\n : \"unknown\");\n }\n}\n\nconst Rule State::kPhonyRule(\"phony\");\n\nState::State() : build_log_(NULL) {\n AddRule(&kPhonyRule);\n}\n\nconst Rule* State::LookupRule(const string& rule_name) {\n map<string, const Rule*>::iterator i = rules_.find(rule_name);\n if (i == rules_.end())\n return NULL;\n return i->second;\n}\n\nvoid State::AddRule(const Rule* rule) {\n assert(LookupRule(rule->name_) == NULL);\n rules_[rule->name_] = rule;\n}\n\nEdge* State::AddEdge(const Rule* rule) {\n Edge* edge = new Edge();\n edge->rule_ = rule;\n edge->env_ = &bindings_;\n edges_.push_back(edge);\n return edge;\n}\n\nNode* State::LookupNode(const string& path) {\n FileStat* file = stat_cache_.GetFile(path);\n if (!file->node_)\n return NULL;\n return file->node_;\n}\n\nNode* State::GetNode(const string& path) {\n FileStat* file = stat_cache_.GetFile(path);\n if (!file->node_)\n file->node_ = new Node(file);\n return file->node_;\n}\n\nvoid State::AddIn(Edge* edge, const string& path) {\n Node* node = GetNode(path);\n edge->inputs_.push_back(node);\n node->out_edges_.push_back(edge);\n}\n\nvoid State::AddOut(Edge* edge, const string& path) {\n Node* node = GetNode(path);\n edge->outputs_.push_back(node);\n if (node->in_edge_) {\n fprintf(stderr, \"WARNING: multiple rules generate %s. \"\n \"build will not be correct; continuing anyway\\n\", path.c_str());\n }\n node->in_edge_ = edge;\n}\n<commit_msg>Use Error() to report error.<commit_after>\/\/ Copyright 2011 Google Inc. All Rights Reserved.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n\/\/ This file is all the code that used to be in one file.\n\/\/ TODO: split into modules, delete this file.\n\n#include \"ninja.h\"\n\n#include <errno.h>\n#include <sys\/stat.h>\n#include <stdio.h>\n#include <string.h>\n\n#include \"build_log.h\"\n#include \"graph.h\"\n#include \"util.h\"\n\nint ReadFile(const string& path, string* contents, string* err) {\n FILE* f = fopen(path.c_str(), \"r\");\n if (!f) {\n err->assign(strerror(errno));\n return -errno;\n }\n\n char buf[64 << 10];\n size_t len;\n while ((len = fread(buf, 1, sizeof(buf), f)) > 0) {\n contents->append(buf, len);\n }\n if (ferror(f)) {\n err->assign(strerror(errno)); \/\/ XXX errno?\n contents->clear();\n fclose(f);\n return -errno;\n }\n fclose(f);\n return 0;\n}\n\nint RealDiskInterface::Stat(const string& path) {\n struct stat st;\n if (stat(path.c_str(), &st) < 0) {\n if (errno == ENOENT) {\n return 0;\n } else {\n Error(\"stat(%s): %s\", path.c_str(), strerror(errno));\n return -1;\n }\n }\n\n return st.st_mtime;\n return true;\n}\n\nstring DirName(const string& path) {\n string::size_type slash_pos = path.rfind('\/');\n if (slash_pos == string::npos)\n return \"\"; \/\/ Nothing to do.\n while (slash_pos > 0 && path[slash_pos - 1] == '\/')\n --slash_pos;\n return path.substr(0, slash_pos);\n}\n\nbool DiskInterface::MakeDirs(const string& path) {\n string dir = DirName(path);\n if (dir.empty())\n return true; \/\/ Reached root; assume it's there.\n int mtime = Stat(dir);\n if (mtime < 0)\n return false; \/\/ Error.\n if (mtime > 0)\n return true; \/\/ Exists already; we're done.\n\n \/\/ Directory doesn't exist. Try creating its parent first.\n bool success = MakeDirs(dir);\n if (!success)\n return false;\n return MakeDir(dir);\n}\n\nstring RealDiskInterface::ReadFile(const string& path, string* err) {\n string contents;\n int ret = ::ReadFile(path, &contents, err);\n if (ret == -ENOENT) {\n \/\/ Swallow ENOENT.\n err->clear();\n }\n return contents;\n}\n\nbool RealDiskInterface::MakeDir(const string& path) {\n if (mkdir(path.c_str(), 0777) < 0) {\n Error(\"mkdir(%s): %s\", path.c_str(), strerror(errno));\n return false;\n }\n return true;\n}\n\nFileStat* StatCache::GetFile(const string& path) {\n Paths::iterator i = paths_.find(path);\n if (i != paths_.end())\n return i->second;\n FileStat* file = new FileStat(path);\n paths_[path] = file;\n return file;\n}\n\n#include <stdio.h>\n\nvoid StatCache::Dump() {\n for (Paths::iterator i = paths_.begin(); i != paths_.end(); ++i) {\n FileStat* file = i->second;\n printf(\"%s %s\\n\",\n file->path_.c_str(),\n file->status_known()\n ? (file->node_->dirty_ ? \"dirty\" : \"clean\")\n : \"unknown\");\n }\n}\n\nconst Rule State::kPhonyRule(\"phony\");\n\nState::State() : build_log_(NULL) {\n AddRule(&kPhonyRule);\n}\n\nconst Rule* State::LookupRule(const string& rule_name) {\n map<string, const Rule*>::iterator i = rules_.find(rule_name);\n if (i == rules_.end())\n return NULL;\n return i->second;\n}\n\nvoid State::AddRule(const Rule* rule) {\n assert(LookupRule(rule->name_) == NULL);\n rules_[rule->name_] = rule;\n}\n\nEdge* State::AddEdge(const Rule* rule) {\n Edge* edge = new Edge();\n edge->rule_ = rule;\n edge->env_ = &bindings_;\n edges_.push_back(edge);\n return edge;\n}\n\nNode* State::LookupNode(const string& path) {\n FileStat* file = stat_cache_.GetFile(path);\n if (!file->node_)\n return NULL;\n return file->node_;\n}\n\nNode* State::GetNode(const string& path) {\n FileStat* file = stat_cache_.GetFile(path);\n if (!file->node_)\n file->node_ = new Node(file);\n return file->node_;\n}\n\nvoid State::AddIn(Edge* edge, const string& path) {\n Node* node = GetNode(path);\n edge->inputs_.push_back(node);\n node->out_edges_.push_back(edge);\n}\n\nvoid State::AddOut(Edge* edge, const string& path) {\n Node* node = GetNode(path);\n edge->outputs_.push_back(node);\n if (node->in_edge_) {\n Error(\"WARNING: multiple rules generate %s. \"\n \"build will not be correct; continuing anyway\", path.c_str());\n }\n node->in_edge_ = edge;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ Created by Dawid Drozd aka Gelldur on 18\/10\/16.\n\/\/\n\n#include <eventbus\/EventCollector.h>\n\n#include <cassert>\n\nnamespace\n{\n\nvoid null_deleter(Dexode::EventBus*)\n{\n}\n\n}\n\nnamespace Dexode\n{\n\nEventCollector::EventCollector(const std::shared_ptr<EventBus>& bus)\n\t\t: _bus(bus)\n{\n\tassert(_bus);\n}\n\n\/\/Maybe ugly but hey ;) Less code and simply i can :D\nEventCollector::EventCollector(EventBus* bus)\n\t\t: _bus(bus, &null_deleter)\n{\n}\n\nEventCollector::EventCollector(const EventCollector& other)\n\t\t: _bus(other._bus)\n{\n}\n\nEventCollector::EventCollector(EventCollector&& other)\n\t\t: _token(other._token)\n\t\t, _bus(std::move(other._bus))\n{\n\tother._token = 0;\n}\n\nEventCollector::~EventCollector()\n{\n\tunlistenAll();\n}\n\nEventCollector& EventCollector::operator=(const EventCollector& other)\n{\n\tstd::unique_ptr<int> vector3;\n\tif (this == &other)\n\t{\n\t\treturn *this;\n\t}\n\tif (other._bus.get() != _bus.get())\n\t{\n\t\tunlistenAll();\n\t\t_bus = other._bus;\n\t}\n\n\treturn *this;\n}\n\nEventCollector& EventCollector::operator=(EventCollector&& other)\n{\n\tif (this == &other)\n\t{\n\t\treturn *this;\n\t}\n\n\tunlistenAll();\n\n\t_token = other._token;\n\tother._token = 0;\n\t_bus = std::move(other._bus);\n\n\treturn *this;\n}\n\nvoid EventCollector::unlistenAll()\n{\n\tif (_token != 0 && _bus)\n\t{\n\t\t_bus->unlistenAll(_token);\n\t}\n}\n\nbool EventCollector::isUsing(const std::shared_ptr<EventBus>& bus) const\n{\n\treturn _bus == bus;\n}\n\n}\n<commit_msg>Remove some trash<commit_after>\/\/\n\/\/ Created by Dawid Drozd aka Gelldur on 18\/10\/16.\n\/\/\n\n#include <eventbus\/EventCollector.h>\n\n#include <cassert>\n\nnamespace\n{\n\nvoid null_deleter(Dexode::EventBus*)\n{\n}\n\n}\n\nnamespace Dexode\n{\n\nEventCollector::EventCollector(const std::shared_ptr<EventBus>& bus)\n\t\t: _bus(bus)\n{\n\tassert(_bus);\n}\n\n\/\/Maybe ugly but hey ;) Less code and simply i can :D\nEventCollector::EventCollector(EventBus* bus)\n\t\t: _bus(bus, &null_deleter)\n{\n}\n\nEventCollector::EventCollector(const EventCollector& other)\n\t\t: _bus(other._bus)\n{\n}\n\nEventCollector::EventCollector(EventCollector&& other)\n\t\t: _token(other._token)\n\t\t, _bus(std::move(other._bus))\n{\n\tother._token = 0;\n}\n\nEventCollector::~EventCollector()\n{\n\tunlistenAll();\n}\n\nEventCollector& EventCollector::operator=(const EventCollector& other)\n{\n\tif (this == &other)\n\t{\n\t\treturn *this;\n\t}\n\tif (other._bus.get() != _bus.get())\n\t{\n\t\tunlistenAll();\n\t\t_bus = other._bus;\n\t}\n\n\treturn *this;\n}\n\nEventCollector& EventCollector::operator=(EventCollector&& other)\n{\n\tif (this == &other)\n\t{\n\t\treturn *this;\n\t}\n\n\tunlistenAll();\n\n\t_token = other._token;\n\tother._token = 0;\n\t_bus = std::move(other._bus);\n\n\treturn *this;\n}\n\nvoid EventCollector::unlistenAll()\n{\n\tif (_token != 0 && _bus)\n\t{\n\t\t_bus->unlistenAll(_token);\n\t}\n}\n\nbool EventCollector::isUsing(const std::shared_ptr<EventBus>& bus) const\n{\n\treturn _bus == bus;\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/* @nolint\n * Copyright (c) 2009-2012 Petri Lehtinen <petri@digip.org>\n *\n * Jansson is free software; you can redistribute it and\/or modify\n * it under the terms of the MIT license. See LICENSE for details.\n *\/\n\n#include <string.h>\n#include \"utf.h\"\n\nint utf8_encode(int32_t codepoint, char *buffer, int *size)\n{\n if(codepoint < 0)\n return -1;\n else if(codepoint < 0x80)\n {\n buffer[0] = (char)codepoint;\n *size = 1;\n }\n else if(codepoint < 0x800)\n {\n buffer[0] = 0xC0 + ((codepoint & 0x7C0) >> 6);\n buffer[1] = 0x80 + ((codepoint & 0x03F));\n *size = 2;\n }\n else if(codepoint < 0x10000)\n {\n buffer[0] = 0xE0 + ((codepoint & 0xF000) >> 12);\n buffer[1] = 0x80 + ((codepoint & 0x0FC0) >> 6);\n buffer[2] = 0x80 + ((codepoint & 0x003F));\n *size = 3;\n }\n else if(codepoint <= 0x10FFFF)\n {\n buffer[0] = 0xF0 + ((codepoint & 0x1C0000) >> 18);\n buffer[1] = 0x80 + ((codepoint & 0x03F000) >> 12);\n buffer[2] = 0x80 + ((codepoint & 0x000FC0) >> 6);\n buffer[3] = 0x80 + ((codepoint & 0x00003F));\n *size = 4;\n }\n else\n return -1;\n\n return 0;\n}\n\nint utf8_check_first(char byte)\n{\n unsigned char u = (unsigned char)byte;\n\n if(u < 0x80)\n return 1;\n\n if(0x80 <= u && u <= 0xBF) {\n \/* second, third or fourth byte of a multi-byte\n sequence, i.e. a \"continuation byte\" *\/\n return 0;\n }\n else if(u == 0xC0 || u == 0xC1) {\n \/* overlong encoding of an ASCII byte *\/\n return 0;\n }\n else if(0xC2 <= u && u <= 0xDF) {\n \/* 2-byte sequence *\/\n return 2;\n }\n\n else if(0xE0 <= u && u <= 0xEF) {\n \/* 3-byte sequence *\/\n return 3;\n }\n else if(0xF0 <= u && u <= 0xF4) {\n \/* 4-byte sequence *\/\n return 4;\n }\n else { \/* u >= 0xF5 *\/\n \/* Restricted (start of 4-, 5- or 6-byte sequence) or invalid\n UTF-8 *\/\n return 0;\n }\n}\n\nint utf8_check_full(const char *buffer, int size, int32_t *codepoint)\n{\n int i;\n int32_t value = 0;\n unsigned char u = (unsigned char)buffer[0];\n\n if(size == 2)\n {\n value = u & 0x1F;\n }\n else if(size == 3)\n {\n value = u & 0xF;\n }\n else if(size == 4)\n {\n value = u & 0x7;\n }\n else\n return 0;\n\n for(i = 1; i < size; i++)\n {\n u = (unsigned char)buffer[i];\n\n if(u < 0x80 || u > 0xBF) {\n \/* not a continuation byte *\/\n return 0;\n }\n\n value = (value << 6) + (u & 0x3F);\n }\n\n if(value > 0x10FFFF) {\n \/* not in Unicode range *\/\n return 0;\n }\n\n else if(0xD800 <= value && value <= 0xDFFF) {\n \/* invalid code point (UTF-16 surrogate halves) *\/\n return 0;\n }\n\n else if((size == 2 && value < 0x80) ||\n (size == 3 && value < 0x800) ||\n (size == 4 && value < 0x10000)) {\n \/* overlong encoding *\/\n return 0;\n }\n\n if(codepoint)\n *codepoint = value;\n\n return 1;\n}\n\nconst char *utf8_iterate(const char *buffer, int32_t *codepoint)\n{\n int count;\n int32_t value;\n\n if(!*buffer)\n return buffer;\n\n count = utf8_check_first(buffer[0]);\n if(count <= 0)\n return NULL;\n\n if(count == 1)\n value = (unsigned char)buffer[0];\n else\n {\n if(!utf8_check_full(buffer, count, &value))\n return NULL;\n }\n\n if(codepoint)\n *codepoint = value;\n\n return buffer + count;\n}\n\nint utf8_check_string(const char *string, int length)\n{\n int i;\n\n if(length == -1)\n length = strlen(string);\n\n for(i = 0; i < length; i++)\n {\n int count = utf8_check_first(string[i]);\n if(count == 0)\n return 0;\n else if(count > 1)\n {\n if(i + count > length)\n return 0;\n\n if(!utf8_check_full(&string[i], count, NULL))\n return 0;\n\n i += count - 1;\n }\n }\n\n return 1;\n}\n<commit_msg>reformat jansson\/utf.cpp<commit_after>\/* @nolint\n * Copyright (c) 2009-2012 Petri Lehtinen <petri@digip.org>\n *\n * Jansson is free software; you can redistribute it and\/or modify\n * it under the terms of the MIT license. See LICENSE for details.\n *\/\n\n#include \"utf.h\"\n#include <string.h>\n\nint utf8_encode(int32_t codepoint, char* buffer, int* size) {\n if (codepoint < 0)\n return -1;\n else if (codepoint < 0x80) {\n buffer[0] = (char)codepoint;\n *size = 1;\n } else if (codepoint < 0x800) {\n buffer[0] = 0xC0 + ((codepoint & 0x7C0) >> 6);\n buffer[1] = 0x80 + ((codepoint & 0x03F));\n *size = 2;\n } else if (codepoint < 0x10000) {\n buffer[0] = 0xE0 + ((codepoint & 0xF000) >> 12);\n buffer[1] = 0x80 + ((codepoint & 0x0FC0) >> 6);\n buffer[2] = 0x80 + ((codepoint & 0x003F));\n *size = 3;\n } else if (codepoint <= 0x10FFFF) {\n buffer[0] = 0xF0 + ((codepoint & 0x1C0000) >> 18);\n buffer[1] = 0x80 + ((codepoint & 0x03F000) >> 12);\n buffer[2] = 0x80 + ((codepoint & 0x000FC0) >> 6);\n buffer[3] = 0x80 + ((codepoint & 0x00003F));\n *size = 4;\n } else\n return -1;\n\n return 0;\n}\n\nint utf8_check_first(char byte) {\n unsigned char u = (unsigned char)byte;\n\n if (u < 0x80)\n return 1;\n\n if (0x80 <= u && u <= 0xBF) {\n \/* second, third or fourth byte of a multi-byte\n sequence, i.e. a \"continuation byte\" *\/\n return 0;\n } else if (u == 0xC0 || u == 0xC1) {\n \/* overlong encoding of an ASCII byte *\/\n return 0;\n } else if (0xC2 <= u && u <= 0xDF) {\n \/* 2-byte sequence *\/\n return 2;\n }\n\n else if (0xE0 <= u && u <= 0xEF) {\n \/* 3-byte sequence *\/\n return 3;\n } else if (0xF0 <= u && u <= 0xF4) {\n \/* 4-byte sequence *\/\n return 4;\n } else { \/* u >= 0xF5 *\/\n \/* Restricted (start of 4-, 5- or 6-byte sequence) or invalid\n UTF-8 *\/\n return 0;\n }\n}\n\nint utf8_check_full(const char* buffer, int size, int32_t* codepoint) {\n int i;\n int32_t value = 0;\n unsigned char u = (unsigned char)buffer[0];\n\n if (size == 2) {\n value = u & 0x1F;\n } else if (size == 3) {\n value = u & 0xF;\n } else if (size == 4) {\n value = u & 0x7;\n } else\n return 0;\n\n for (i = 1; i < size; i++) {\n u = (unsigned char)buffer[i];\n\n if (u < 0x80 || u > 0xBF) {\n \/* not a continuation byte *\/\n return 0;\n }\n\n value = (value << 6) + (u & 0x3F);\n }\n\n if (value > 0x10FFFF) {\n \/* not in Unicode range *\/\n return 0;\n }\n\n else if (0xD800 <= value && value <= 0xDFFF) {\n \/* invalid code point (UTF-16 surrogate halves) *\/\n return 0;\n }\n\n else if (\n (size == 2 && value < 0x80) || (size == 3 && value < 0x800) ||\n (size == 4 && value < 0x10000)) {\n \/* overlong encoding *\/\n return 0;\n }\n\n if (codepoint)\n *codepoint = value;\n\n return 1;\n}\n\nconst char* utf8_iterate(const char* buffer, int32_t* codepoint) {\n int count;\n int32_t value;\n\n if (!*buffer)\n return buffer;\n\n count = utf8_check_first(buffer[0]);\n if (count <= 0)\n return NULL;\n\n if (count == 1)\n value = (unsigned char)buffer[0];\n else {\n if (!utf8_check_full(buffer, count, &value))\n return NULL;\n }\n\n if (codepoint)\n *codepoint = value;\n\n return buffer + count;\n}\n\nint utf8_check_string(const char* string, int length) {\n int i;\n\n if (length == -1)\n length = strlen(string);\n\n for (i = 0; i < length; i++) {\n int count = utf8_check_first(string[i]);\n if (count == 0)\n return 0;\n else if (count > 1) {\n if (i + count > length)\n return 0;\n\n if (!utf8_check_full(&string[i], count, NULL))\n return 0;\n\n i += count - 1;\n }\n }\n\n return 1;\n}\n<|endoftext|>"} {"text":"<commit_before>\/******************************************************************************\n* Copyright (c) 2013, Howard Butler (hobu.inc@gmail.com)\n*\n* All rights reserved.\n*\n* Redistribution and use in source and binary forms, with or without\n* modification, are permitted provided that the following\n* conditions are met:\n*\n* * Redistributions of source code must retain the above copyright\n* notice, this list of conditions and the following disclaimer.\n* * Redistributions in binary form must reproduce the above copyright\n* notice, this list of conditions and the following disclaimer in\n* the documentation and\/or other materials provided\n* with the distribution.\n* * Neither the name of Hobu, Inc. or Flaxen Geo Consulting nor the\n* names of its contributors may be used to endorse or promote\n* products derived from this software without specific prior\n* written permission.\n*\n* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n* \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS\n* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED\n* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT\n* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY\n* OF SUCH DAMAGE.\n****************************************************************************\/\n\n#include \"gtest\/gtest.h\"\n\n#include <pdal\/SpatialReference.hpp>\n#include <pdal\/StageFactory.hpp>\n#include <pdal\/PointBuffer.hpp>\n\n#include \"Support.hpp\"\n\nusing namespace pdal;\n\nvoid printChildren(std::ostream& out, MetadataNode m, int depth = 0)\n{\n std::vector<MetadataNode> children = m.children();\n for (auto mi = children.begin(); mi != children.end(); ++mi)\n {\n MetadataNode& c = *mi;\n for (int i = 0; i < depth; i++)\n out << \"\\t\";\n out << c.name() << \" : \" << c.value() << \"\\n\";\n printChildren(out, c, depth + 1);\n }\n}\n\nTEST(HexbinFilterTest, HexbinFilterTest_test_1)\n{\n StageFactory f;\n\n Options options;\n options.add(\"filename\", Support::datapath(\"las\/hextest.las\"));\n options.add(\"sample_size\", 5000, \"Number of samples to use \"\n \"when estimating hexagon edge size. Specify 0.0 for edge_size if \"\n \"you want to compute one.\");\n options.add(\"threshold\", 1, \"Number of points necessary inside \"\n \"a hexagon to be considered full\");\n options.add(\"edge_length\", 0.666666666, \"The edge size of the hexagon to \"\n \"use in situations where you do not want to estimate based on \"\n \"a sample\");\n\n ReaderPtr reader(f.createReader(\"readers.las\"));\n EXPECT_TRUE(reader.get());\n reader->setOptions(options);\n\n FilterPtr hexbin(f.createFilter(\"filters.hexbin\"));\n EXPECT_TRUE(hexbin.get());\n hexbin->setOptions(options);\n hexbin->setInput(reader.get());\n\n PointContext ctx;\n\n hexbin->prepare(ctx);\n hexbin->execute(ctx);\n\n MetadataNode m = ctx.metadata();\n m = m.findChild(hexbin->getName());\n\n std::string filename = Support::temppath(\"hexbin.txt\");\n std::ofstream out(filename);\n printChildren(out, m);\n out.close();\n\n EXPECT_TRUE(Support::compare_text_files(filename,\n Support::datapath(\"filters\/hexbin.txt\")));\n\n FileUtils::deleteFile(filename);\n}\n<commit_msg>put back tesselation output in hexbin test so tests pass<commit_after>\/******************************************************************************\n* Copyright (c) 2013, Howard Butler (hobu.inc@gmail.com)\n*\n* All rights reserved.\n*\n* Redistribution and use in source and binary forms, with or without\n* modification, are permitted provided that the following\n* conditions are met:\n*\n* * Redistributions of source code must retain the above copyright\n* notice, this list of conditions and the following disclaimer.\n* * Redistributions in binary form must reproduce the above copyright\n* notice, this list of conditions and the following disclaimer in\n* the documentation and\/or other materials provided\n* with the distribution.\n* * Neither the name of Hobu, Inc. or Flaxen Geo Consulting nor the\n* names of its contributors may be used to endorse or promote\n* products derived from this software without specific prior\n* written permission.\n*\n* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n* \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS\n* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED\n* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT\n* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY\n* OF SUCH DAMAGE.\n****************************************************************************\/\n\n#include \"gtest\/gtest.h\"\n\n#include <pdal\/SpatialReference.hpp>\n#include <pdal\/StageFactory.hpp>\n#include <pdal\/PointBuffer.hpp>\n\n#include \"Support.hpp\"\n\nusing namespace pdal;\n\nvoid printChildren(std::ostream& out, MetadataNode m, int depth = 0)\n{\n std::vector<MetadataNode> children = m.children();\n for (auto mi = children.begin(); mi != children.end(); ++mi)\n {\n MetadataNode& c = *mi;\n for (int i = 0; i < depth; i++)\n out << \"\\t\";\n out << c.name() << \" : \" << c.value() << \"\\n\";\n printChildren(out, c, depth + 1);\n }\n}\n\nTEST(HexbinFilterTest, HexbinFilterTest_test_1)\n{\n StageFactory f;\n\n Options options;\n options.add(\"filename\", Support::datapath(\"las\/hextest.las\"));\n options.add(\"output_tesselation\", true);\n options.add(\"sample_size\", 5000, \"Number of samples to use \"\n \"when estimating hexagon edge size. Specify 0.0 for edge_size if \"\n \"you want to compute one.\");\n options.add(\"threshold\", 1, \"Number of points necessary inside \"\n \"a hexagon to be considered full\");\n options.add(\"edge_length\", 0.666666666, \"The edge size of the hexagon to \"\n \"use in situations where you do not want to estimate based on \"\n \"a sample\");\n\n ReaderPtr reader(f.createReader(\"readers.las\"));\n EXPECT_TRUE(reader.get());\n reader->setOptions(options);\n\n FilterPtr hexbin(f.createFilter(\"filters.hexbin\"));\n EXPECT_TRUE(hexbin.get());\n hexbin->setOptions(options);\n hexbin->setInput(reader.get());\n\n PointContext ctx;\n\n hexbin->prepare(ctx);\n hexbin->execute(ctx);\n\n MetadataNode m = ctx.metadata();\n m = m.findChild(hexbin->getName());\n\n std::string filename = Support::temppath(\"hexbin.txt\");\n std::ofstream out(filename);\n printChildren(out, m);\n out.close();\n\n EXPECT_TRUE(Support::compare_text_files(filename,\n Support::datapath(\"filters\/hexbin.txt\")));\n\n FileUtils::deleteFile(filename);\n}\n<|endoftext|>"} {"text":"<commit_before><commit_msg>[ADDED] ctrl结合框选的操作<commit_after><|endoftext|>"} {"text":"<commit_before>#pragma once\n\n#include \"scope_guard.hpp\"\n#include \"task_queue_thread_pool.hpp\"\n\n#include <algorithm>\n#include <cassert>\n#include <future>\n#include <type_traits>\n#include <unordered_map>\n#include <vector>\n\nnamespace cu\n{\n\nclass DependencyThreadPoolBase\n{\npublic:\n using Id = std::size_t;\n static constexpr const Id invalidId = -1;\n\n template <typename T>\n struct Result\n {\n Result() = default;\n\n Result( std::future<T> future_, Id id_ )\n : future( std::move(future_) )\n , id( id_ )\n {}\n\n std::future<T> future;\n Id id = invalidId;\n };\n};\n\n\ntemplate <typename ...Args>\nclass DependencyThreadPool\n : public DependencyThreadPoolBase\n{\npublic:\n template <typename F>\n decltype(auto) operator()(\n const std::initializer_list<Id> & dependencyIds,\n F && f )\n {\n return run( dependencyIds, std::forward<F>(f) );\n }\n\n template <typename F>\n decltype(auto) operator()(\n const std::vector<Id> & dependencyIds,\n F && f )\n {\n return run( dependencyIds, std::forward<F>(f) );\n }\n\nprivate:\n template <typename F,\n typename IdContainer>\n Result<typename std::result_of<F(Args...)>::type> run(\n const IdContainer & dependencyIds,\n F && f )\n {\n auto pt = std::packaged_task<std::result_of_t<F(Args...)>(Args&&...)>(\n std::forward<F>(f) );\n auto future = pt.get_future();\n cu::MoveFunction<void(Args&&...)> task = std::move(pt);\n const auto id = data( [&]( Data & data )\n {\n const auto id = data.idCounter;\n ++data.idCounter;\n const auto nDependencies = data.updateDependencies( dependencyIds, id );\n data.nodes.insert(\n std::make_pair( id, Node{ nDependencies, {}, std::move(task) } ) );\n if ( nDependencies == 0 )\n queueTask( id, data.nodes );\n return id;\n } );\n return { std::move(future), id };\n }\n\n struct Node\n {\n Node(\n std::size_t nOpenDependencies_,\n std::vector<Id> dependentTasks_,\n cu::MoveFunction<void(Args&&...)> task_ )\n : nOpenDependencies( nOpenDependencies_ )\n , dependentTasks( std::move( dependentTasks_ ) )\n , task( std::move( task_ ) )\n {}\n\n std::size_t nOpenDependencies;\n std::vector<Id> dependentTasks;\n cu::MoveFunction<void(Args&&...)> task;\n };\n\n struct Data\n {\n Id idCounter = 0;\n std::map<Id,Node> nodes;\n\n template <typename IdContainer>\n std::size_t updateDependencies(\n const IdContainer & dependencies,\n Id id )\n {\n auto nDependencies = 0;\n for ( auto dep : dependencies )\n {\n const auto it = nodes.find( dep );\n if ( it == nodes.end() )\n continue;\n it->second.dependentTasks.push_back( id );\n ++nDependencies;\n }\n return nDependencies;\n }\n };\n\n void queueTask( Id id, std::map<Id,Node> & nodes )\n {\n const auto nodeIt = nodes.find(id);\n assert( nodeIt != nodes.end() );\n assert( nodeIt->second.nOpenDependencies == 0 );\n workers( [this, nodeIt]\n ( Args &&... args ) mutable\n {\n CU_SCOPE_EXIT\n {\n this->data( [&]( Data & data )\n {\n for ( auto dependentId : nodeIt->second.dependentTasks )\n {\n const auto dependentNodeIt = data.nodes.find( dependentId );\n assert( dependentNodeIt != data.nodes.end() );\n const auto nRemainingDependencies =\n --dependentNodeIt->second.nOpenDependencies;\n if ( nRemainingDependencies == 0 )\n queueTask( dependentId, data.nodes );\n }\n data.nodes.erase( nodeIt );\n } );\n };\n nodeIt->second.task( std::forward<Args>(args)... );\n } );\n }\n\n cu::Monitor<Data> data;\n TaskQueueThreadPool<Args...> workers;\n};\n\n} \/\/ namespace cu\n<commit_msg>Fix: Added missing include.<commit_after>#pragma once\n\n#include \"scope_guard.hpp\"\n#include \"task_queue_thread_pool.hpp\"\n\n#include <algorithm>\n#include <cassert>\n#include <future>\n#include <map>\n#include <type_traits>\n#include <unordered_map>\n#include <vector>\n\nnamespace cu\n{\n\nclass DependencyThreadPoolBase\n{\npublic:\n using Id = std::size_t;\n static constexpr const Id invalidId = -1;\n\n template <typename T>\n struct Result\n {\n Result() = default;\n\n Result( std::future<T> future_, Id id_ )\n : future( std::move(future_) )\n , id( id_ )\n {}\n\n std::future<T> future;\n Id id = invalidId;\n };\n};\n\n\ntemplate <typename ...Args>\nclass DependencyThreadPool\n : public DependencyThreadPoolBase\n{\npublic:\n template <typename F>\n decltype(auto) operator()(\n const std::initializer_list<Id> & dependencyIds,\n F && f )\n {\n return run( dependencyIds, std::forward<F>(f) );\n }\n\n template <typename F>\n decltype(auto) operator()(\n const std::vector<Id> & dependencyIds,\n F && f )\n {\n return run( dependencyIds, std::forward<F>(f) );\n }\n\nprivate:\n template <typename F,\n typename IdContainer>\n Result<typename std::result_of<F(Args...)>::type> run(\n const IdContainer & dependencyIds,\n F && f )\n {\n auto pt = std::packaged_task<std::result_of_t<F(Args...)>(Args&&...)>(\n std::forward<F>(f) );\n auto future = pt.get_future();\n cu::MoveFunction<void(Args&&...)> task = std::move(pt);\n const auto id = data( [&]( Data & data )\n {\n const auto id = data.idCounter;\n ++data.idCounter;\n const auto nDependencies = data.updateDependencies( dependencyIds, id );\n data.nodes.insert(\n std::make_pair( id, Node{ nDependencies, {}, std::move(task) } ) );\n if ( nDependencies == 0 )\n queueTask( id, data.nodes );\n return id;\n } );\n return { std::move(future), id };\n }\n\n struct Node\n {\n Node(\n std::size_t nOpenDependencies_,\n std::vector<Id> dependentTasks_,\n cu::MoveFunction<void(Args&&...)> task_ )\n : nOpenDependencies( nOpenDependencies_ )\n , dependentTasks( std::move( dependentTasks_ ) )\n , task( std::move( task_ ) )\n {}\n\n std::size_t nOpenDependencies;\n std::vector<Id> dependentTasks;\n cu::MoveFunction<void(Args&&...)> task;\n };\n\n struct Data\n {\n Id idCounter = 0;\n std::map<Id,Node> nodes;\n\n template <typename IdContainer>\n std::size_t updateDependencies(\n const IdContainer & dependencies,\n Id id )\n {\n auto nDependencies = 0;\n for ( auto dep : dependencies )\n {\n const auto it = nodes.find( dep );\n if ( it == nodes.end() )\n continue;\n it->second.dependentTasks.push_back( id );\n ++nDependencies;\n }\n return nDependencies;\n }\n };\n\n void queueTask( Id id, std::map<Id,Node> & nodes )\n {\n const auto nodeIt = nodes.find(id);\n assert( nodeIt != nodes.end() );\n assert( nodeIt->second.nOpenDependencies == 0 );\n workers( [this, nodeIt]\n ( Args &&... args ) mutable\n {\n CU_SCOPE_EXIT\n {\n this->data( [&]( Data & data )\n {\n for ( auto dependentId : nodeIt->second.dependentTasks )\n {\n const auto dependentNodeIt = data.nodes.find( dependentId );\n assert( dependentNodeIt != data.nodes.end() );\n const auto nRemainingDependencies =\n --dependentNodeIt->second.nOpenDependencies;\n if ( nRemainingDependencies == 0 )\n queueTask( dependentId, data.nodes );\n }\n data.nodes.erase( nodeIt );\n } );\n };\n nodeIt->second.task( std::forward<Args>(args)... );\n } );\n }\n\n cu::Monitor<Data> data;\n TaskQueueThreadPool<Args...> workers;\n};\n\n} \/\/ namespace cu\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright 2015 - 2018 gtalent2@gmail.com\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\/\n\n#include <ox\/std\/assert.hpp>\n#include <ox\/std\/byteswap.hpp>\n#include <ox\/std\/memops.hpp>\n\n#include \"read.hpp\"\n\nnamespace ox {\n\nMetalClawReader::MetalClawReader(uint8_t *buff, std::size_t buffLen, MetalClawReader *parent): m_fieldPresence(buff, buffLen) {\n\tm_buff = buff;\n\tm_buffLen = buffLen;\n\tm_parent = parent;\n}\n\nMetalClawReader::~MetalClawReader() {\n\tif (m_parent) {\n\t\tm_parent->m_buffIt += m_buffIt;\n\t}\n\t\/\/oxAssert(m_field == m_fields, \"MetalClawReader: incorrect fields number given\");\n}\n\nError MetalClawReader::field(const char*, int8_t *val) {\n\treturn readInteger(val);\n}\n\nError MetalClawReader::field(const char*, int16_t *val) {\n\treturn readInteger(val);\n}\n\nError MetalClawReader::field(const char*, int32_t *val) {\n\treturn readInteger(val);\n}\n\nError MetalClawReader::field(const char*, int64_t *val) {\n\treturn readInteger(val);\n}\n\n\nError MetalClawReader::field(const char*, uint8_t *val) {\n\treturn readInteger(val);\n}\n\nError MetalClawReader::field(const char*, uint16_t *val) {\n\treturn readInteger(val);\n}\n\nError MetalClawReader::field(const char*, uint32_t *val) {\n\treturn readInteger(val);\n}\n\nError MetalClawReader::field(const char*, uint64_t *val) {\n\treturn readInteger(val);\n}\n\nError MetalClawReader::field(const char*, bool *val) {\n\tauto valErr = m_fieldPresence.get(m_field++);\n\t*val = valErr.value;\n\treturn valErr.error;\n}\n\nError MetalClawReader::field(const char*, SerStr val) {\n\tif (m_fieldPresence.get(m_field++)) {\n\t\t\/\/ read the length\n\t\tif (m_buffIt >= m_buffLen) {\n\t\t\treturn OxError(MC_BUFFENDED);\n\t\t}\n\t\tstd::size_t bytesRead = 0;\n\t\tauto [size, err] = mc::decodeInteger<StringLength>(&m_buff[m_buffIt], m_buffLen - m_buffIt, &bytesRead);\n\t\tm_buffIt += bytesRead;\n\t\toxReturnError(err);\n\n\t\t\/\/ read the string\n\t\tif (val.cap() > -1 && static_cast<StringLength>(val.cap()) >= size) {\n\t\t\tif (m_buffIt + size < m_buffLen) {\n\t\t\t\tox_memcpy(val.data(), &m_buff[m_buffIt], size);\n\t\t\t\tm_buffIt += size;\n\t\t\t} else {\n\t\t\t\treturn OxError(MC_BUFFENDED);\n\t\t\t}\n\t\t} else {\n\t\t\treturn OxError(MC_OUTBUFFENDED);\n\t\t}\n\t} else {\n\t\tval.data()[0] = 0;\n\t}\n\treturn OxError(0);\n}\n\n[[nodiscard]] ValErr<ArrayLength> MetalClawReader::arrayLength(bool pass) {\n\tif (m_fieldPresence.get(m_field)) {\n\t\t\/\/ read the length\n\t\tif (m_buffIt >= m_buffLen) {\n\t\t\treturn OxError(MC_BUFFENDED);\n\t\t}\n\t\tstd::size_t bytesRead = 0;\n\t\tauto out = mc::decodeInteger<ArrayLength>(&m_buff[m_buffIt], m_buffLen - m_buffIt, &bytesRead).value;\n\t\tif (pass) {\n\t\t\tm_buffIt += bytesRead;\n\t\t}\n\t\treturn out;\n\t}\n\treturn OxError(1);\n}\n\n[[nodiscard]] StringLength MetalClawReader::stringLength() {\n\tif (m_fieldPresence.get(m_field)) {\n\t\t\/\/ read the length\n\t\tstd::size_t bytesRead = 0;\n\t\tauto len = mc::decodeInteger<StringLength>(&m_buff[m_buffIt], m_buffLen - m_buffIt, &bytesRead);\n\t\treturn len.value;\n\t}\n\treturn 0;\n}\n\nvoid MetalClawReader::setTypeInfo(const char*, int fields) {\n\tm_fields = fields;\n\tm_buffIt = (fields \/ 8 + 1) - (fields % 8 == 0);\n\tm_fieldPresence.setFields(fields);\n\tm_fieldPresence.setMaxLen(m_buffIt);\n}\n\nMetalClawReader MetalClawReader::child() {\n\treturn MetalClawReader(m_buff + m_buffIt, m_buffLen - m_buffIt, this);\n}\n\nbool MetalClawReader::fieldPresent() const {\n\treturn m_fieldPresence.get(m_field).value;\n}\n\nbool MetalClawReader::fieldPresent(int fieldNo) const {\n\treturn m_fieldPresence.get(fieldNo).value;\n}\n\nvoid MetalClawReader::nextField() noexcept {\n\t++m_field;\n}\n\n}\n<commit_msg>[ox\/mc] Fix false positive buffer overflow check when string is last item in MC buffer<commit_after>\/*\n * Copyright 2015 - 2018 gtalent2@gmail.com\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\/\n\n#include <ox\/std\/assert.hpp>\n#include <ox\/std\/byteswap.hpp>\n#include <ox\/std\/memops.hpp>\n\n#include \"read.hpp\"\n\nnamespace ox {\n\nMetalClawReader::MetalClawReader(uint8_t *buff, std::size_t buffLen, MetalClawReader *parent): m_fieldPresence(buff, buffLen) {\n\tm_buff = buff;\n\tm_buffLen = buffLen;\n\tm_parent = parent;\n}\n\nMetalClawReader::~MetalClawReader() {\n\tif (m_parent) {\n\t\tm_parent->m_buffIt += m_buffIt;\n\t}\n\t\/\/oxAssert(m_field == m_fields, \"MetalClawReader: incorrect fields number given\");\n}\n\nError MetalClawReader::field(const char*, int8_t *val) {\n\treturn readInteger(val);\n}\n\nError MetalClawReader::field(const char*, int16_t *val) {\n\treturn readInteger(val);\n}\n\nError MetalClawReader::field(const char*, int32_t *val) {\n\treturn readInteger(val);\n}\n\nError MetalClawReader::field(const char*, int64_t *val) {\n\treturn readInteger(val);\n}\n\n\nError MetalClawReader::field(const char*, uint8_t *val) {\n\treturn readInteger(val);\n}\n\nError MetalClawReader::field(const char*, uint16_t *val) {\n\treturn readInteger(val);\n}\n\nError MetalClawReader::field(const char*, uint32_t *val) {\n\treturn readInteger(val);\n}\n\nError MetalClawReader::field(const char*, uint64_t *val) {\n\treturn readInteger(val);\n}\n\nError MetalClawReader::field(const char*, bool *val) {\n\tauto valErr = m_fieldPresence.get(m_field++);\n\t*val = valErr.value;\n\treturn valErr.error;\n}\n\nError MetalClawReader::field(const char*, SerStr val) {\n\tif (m_fieldPresence.get(m_field++)) {\n\t\t\/\/ read the length\n\t\tif (m_buffIt >= m_buffLen) {\n\t\t\treturn OxError(MC_BUFFENDED);\n\t\t}\n\t\tstd::size_t bytesRead = 0;\n\t\tauto [size, err] = mc::decodeInteger<StringLength>(&m_buff[m_buffIt], m_buffLen - m_buffIt, &bytesRead);\n\t\tm_buffIt += bytesRead;\n\t\toxReturnError(err);\n\n\t\t\/\/ read the string\n\t\tif (val.cap() > -1 && static_cast<StringLength>(val.cap()) >= size) {\n\t\t\tif (m_buffIt + size <= m_buffLen) {\n\t\t\t\tox_memcpy(val.data(), &m_buff[m_buffIt], size);\n\t\t\t\tm_buffIt += size;\n\t\t\t} else {\n\t\t\t\treturn OxError(MC_BUFFENDED);\n\t\t\t}\n\t\t} else {\n\t\t\treturn OxError(MC_OUTBUFFENDED);\n\t\t}\n\t} else {\n\t\tval.data()[0] = 0;\n\t}\n\treturn OxError(0);\n}\n\n[[nodiscard]] ValErr<ArrayLength> MetalClawReader::arrayLength(bool pass) {\n\tif (m_fieldPresence.get(m_field)) {\n\t\t\/\/ read the length\n\t\tif (m_buffIt >= m_buffLen) {\n\t\t\treturn OxError(MC_BUFFENDED);\n\t\t}\n\t\tstd::size_t bytesRead = 0;\n\t\tauto out = mc::decodeInteger<ArrayLength>(&m_buff[m_buffIt], m_buffLen - m_buffIt, &bytesRead).value;\n\t\tif (pass) {\n\t\t\tm_buffIt += bytesRead;\n\t\t}\n\t\treturn out;\n\t}\n\treturn OxError(1);\n}\n\n[[nodiscard]] StringLength MetalClawReader::stringLength() {\n\tif (m_fieldPresence.get(m_field)) {\n\t\t\/\/ read the length\n\t\tstd::size_t bytesRead = 0;\n\t\tauto len = mc::decodeInteger<StringLength>(&m_buff[m_buffIt], m_buffLen - m_buffIt, &bytesRead);\n\t\treturn len.value;\n\t}\n\treturn 0;\n}\n\nvoid MetalClawReader::setTypeInfo(const char*, int fields) {\n\tm_fields = fields;\n\tm_buffIt = (fields \/ 8 + 1) - (fields % 8 == 0);\n\tm_fieldPresence.setFields(fields);\n\tm_fieldPresence.setMaxLen(m_buffIt);\n}\n\nMetalClawReader MetalClawReader::child() {\n\treturn MetalClawReader(m_buff + m_buffIt, m_buffLen - m_buffIt, this);\n}\n\nbool MetalClawReader::fieldPresent() const {\n\treturn m_fieldPresence.get(m_field).value;\n}\n\nbool MetalClawReader::fieldPresent(int fieldNo) const {\n\treturn m_fieldPresence.get(fieldNo).value;\n}\n\nvoid MetalClawReader::nextField() noexcept {\n\t++m_field;\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/------------------------------------------------------------------------------\n\/\/ main.cc\n\/\/ yakc app main source.\n\/\/------------------------------------------------------------------------------\n#include \"Pre.h\"\n#include \"Core\/App.h\"\n#include \"Gfx\/Gfx.h\"\n#include \"Input\/Input.h\"\n#include \"KC85Oryol.h\"\n#include \"Draw.h\"\n#if YAKC_UI\n#include \"yakc_ui\/UI.h\"\n#endif\n#include \"Messaging\/Dispatcher.h\"\n#include \"Input\/InputProtocol.h\"\n\nusing namespace Oryol;\nusing namespace yakc;\n\nclass YakcApp : public App {\npublic:\n AppState::Code OnInit();\n AppState::Code OnRunning();\n AppState::Code OnCleanup();\n void handleInput();\n\n Id drawState;\n kc85 kc;\n Draw draw;\n #if YAKC_UI\n UI ui;\n #endif\n};\nOryolMain(YakcApp);\n\n\/\/------------------------------------------------------------------------------\nAppState::Code\nYakcApp::OnInit() {\n\n \/\/ we only need few resources, so don't waste memory \n auto gfxSetup = GfxSetup::Window(640, 512, \"KC85\");\n gfxSetup.SetPoolSize(GfxResourceType::Mesh, 4);\n gfxSetup.SetPoolSize(GfxResourceType::Texture, 4);\n gfxSetup.SetPoolSize(GfxResourceType::DrawState, 4);\n gfxSetup.SetPoolSize(GfxResourceType::Shader, 4);\n Gfx::Setup(gfxSetup);\n Input::Setup();\n Input::BeginCaptureText();\n this->kc.switchon(kc85::kc_model::kc85_3);\n\n #if YAKC_UI\n this->ui.Setup(this->kc);\n #endif\n this->draw.Setup(gfxSetup);\n \n return AppState::Running;\n}\n\n\/\/------------------------------------------------------------------------------\nAppState::Code\nYakcApp::OnRunning() {\n Gfx::ApplyDefaultRenderTarget(ClearState::ClearColor(glm::vec4(0.5f,0.5f,0.5f,1.0f)));\n int micro_secs = 1000000 \/ 60;\n this->handleInput();\n this->kc.onframe(micro_secs);\n this->draw.Render(this->kc);\n #if YAKC_UI\n this->ui.OnFrame(this->kc);\n #endif\n Gfx::CommitFrame();\n return Gfx::QuitRequested() ? AppState::Cleanup : AppState::Running;\n}\n\n\/\/------------------------------------------------------------------------------\nAppState::Code\nYakcApp::OnCleanup() {\n this->draw.Discard();\n #if YAKC_UI\n this->ui.Discard();\n #endif\n Input::Discard();\n Gfx::Discard();\n return App::OnCleanup();\n}\n\n\/\/------------------------------------------------------------------------------\nvoid\nYakcApp::handleInput() {\n const Keyboard& kbd = Input::Keyboard();\n const wchar_t* text = kbd.CapturedText();\n ubyte ascii = 0;\n\n \/\/ alpha-numerics\n if (text[0] && (text[0] >= 32) && (text[0] < 127)) {\n ascii = (ubyte) text[0];\n \/\/ shift is inverted on KC\n if (islower(ascii)) {\n ascii = toupper(ascii);\n }\n else if (isupper(ascii)) {\n ascii = tolower(ascii);\n }\n }\n\n \/\/ special keys\n struct toAscii {\n Key::Code key;\n ubyte ascii;\n };\n const static toAscii keyTable[] = {\n \/\/ FIXME:\n \/\/ HOME, PAGE UP\/DOWN, START\/END of line, INSERT,\n { Key::Left, 0x08 },\n { Key::Right, 0x09 },\n { Key::Down, 0x0A },\n { Key::Up, 0x0B },\n { Key::Enter, 0x0D },\n { Key::BackSpace, 0x1F },\n { Key::F1, 0xF1 },\n { Key::F2, 0xF2 },\n { Key::F3, 0xF3 },\n { Key::F4, 0xF4 },\n { Key::F5, 0xF5 },\n { Key::F6, 0xF6 },\n { Key::F7, 0xF7 },\n { Key::F8, 0xF8 },\n { Key::F9, 0xF9 },\n { Key::F10, 0xFA },\n { Key::F11, 0xFB },\n { Key::F12, 0xFC },\n };\n for (const auto& key : keyTable) {\n if (kbd.KeyDown(key.key)) {\n \/\/ special case: shift-backspace clears screen\n if (kbd.KeyPressed(Key::LeftShift) && (key.key == Key::BackSpace)) {\n ascii = 0x0C;\n }\n else {\n ascii = key.ascii;\n }\n break;\n }\n }\n\n if (0 != ascii) {\n this->kc.put_key(ascii);\n }\n}\n<commit_msg>Fixed input for Backspace and Escape key<commit_after>\/\/------------------------------------------------------------------------------\n\/\/ main.cc\n\/\/ yakc app main source.\n\/\/------------------------------------------------------------------------------\n#include \"Pre.h\"\n#include \"Core\/App.h\"\n#include \"Gfx\/Gfx.h\"\n#include \"Input\/Input.h\"\n#include \"KC85Oryol.h\"\n#include \"Draw.h\"\n#if YAKC_UI\n#include \"yakc_ui\/UI.h\"\n#endif\n#include \"Messaging\/Dispatcher.h\"\n#include \"Input\/InputProtocol.h\"\n\nusing namespace Oryol;\nusing namespace yakc;\n\nclass YakcApp : public App {\npublic:\n AppState::Code OnInit();\n AppState::Code OnRunning();\n AppState::Code OnCleanup();\n void handleInput();\n\n Id drawState;\n kc85 kc;\n Draw draw;\n #if YAKC_UI\n UI ui;\n #endif\n};\nOryolMain(YakcApp);\n\n\/\/------------------------------------------------------------------------------\nAppState::Code\nYakcApp::OnInit() {\n\n \/\/ we only need few resources, so don't waste memory \n auto gfxSetup = GfxSetup::Window(640, 512, \"KC85\");\n gfxSetup.SetPoolSize(GfxResourceType::Mesh, 4);\n gfxSetup.SetPoolSize(GfxResourceType::Texture, 4);\n gfxSetup.SetPoolSize(GfxResourceType::DrawState, 4);\n gfxSetup.SetPoolSize(GfxResourceType::Shader, 4);\n Gfx::Setup(gfxSetup);\n Input::Setup();\n Input::BeginCaptureText();\n this->kc.switchon(kc85::kc_model::kc85_3);\n\n #if YAKC_UI\n this->ui.Setup(this->kc);\n #endif\n this->draw.Setup(gfxSetup);\n \n return AppState::Running;\n}\n\n\/\/------------------------------------------------------------------------------\nAppState::Code\nYakcApp::OnRunning() {\n Gfx::ApplyDefaultRenderTarget(ClearState::ClearColor(glm::vec4(0.5f,0.5f,0.5f,1.0f)));\n int micro_secs = 1000000 \/ 60;\n this->handleInput();\n this->kc.onframe(micro_secs);\n this->draw.Render(this->kc);\n #if YAKC_UI\n this->ui.OnFrame(this->kc);\n #endif\n Gfx::CommitFrame();\n return Gfx::QuitRequested() ? AppState::Cleanup : AppState::Running;\n}\n\n\/\/------------------------------------------------------------------------------\nAppState::Code\nYakcApp::OnCleanup() {\n this->draw.Discard();\n #if YAKC_UI\n this->ui.Discard();\n #endif\n Input::Discard();\n Gfx::Discard();\n return App::OnCleanup();\n}\n\n\/\/------------------------------------------------------------------------------\nvoid\nYakcApp::handleInput() {\n const Keyboard& kbd = Input::Keyboard();\n const wchar_t* text = kbd.CapturedText();\n ubyte ascii = 0;\n\n \/\/ alpha-numerics\n if (text[0] && (text[0] >= 32) && (text[0] < 127)) {\n ascii = (ubyte) text[0];\n \/\/ shift is inverted on KC\n if (islower(ascii)) {\n ascii = toupper(ascii);\n }\n else if (isupper(ascii)) {\n ascii = tolower(ascii);\n }\n }\n\n \/\/ special keys\n struct toAscii {\n Key::Code key;\n ubyte ascii;\n };\n const static toAscii keyTable[] = {\n \/\/ FIXME:\n \/\/ HOME, PAGE UP\/DOWN, START\/END of line, INSERT,\n { Key::Left, 0x08 },\n { Key::Right, 0x09 },\n { Key::Down, 0x0A },\n { Key::Up, 0x0B },\n { Key::Enter, 0x0D },\n { Key::BackSpace, 0x01 },\n { Key::Escape, 0x03 },\n { Key::F1, 0xF1 },\n { Key::F2, 0xF2 },\n { Key::F3, 0xF3 },\n { Key::F4, 0xF4 },\n { Key::F5, 0xF5 },\n { Key::F6, 0xF6 },\n { Key::F7, 0xF7 },\n { Key::F8, 0xF8 },\n { Key::F9, 0xF9 },\n { Key::F10, 0xFA },\n { Key::F11, 0xFB },\n { Key::F12, 0xFC },\n };\n for (const auto& key : keyTable) {\n if (kbd.KeyDown(key.key)) {\n \/\/ special case: shift-backspace clears screen\n if (kbd.KeyPressed(Key::LeftShift) && (key.key == Key::BackSpace)) {\n ascii = 0x0C;\n }\n else {\n ascii = key.ascii;\n }\n break;\n }\n }\n\n if (0 != ascii) {\n this->kc.put_key(ascii);\n }\n}\n<|endoftext|>"} {"text":"<commit_before><commit_msg>option not to have 5 fps when inactive<commit_after><|endoftext|>"} {"text":"<commit_before>#include \"packet\/frame.h\"\n#include \"osal.h\"\n\n\/*\n * Packet framing uses the Consistent Overhead Byte Stuffing algorithm for\n * encoding data bytes. The maximum length for each packet is limited to 254 bytes.\n * Refer to: https:\/\/en.wikipedia.org\/wiki\/Consistent_Overhead_Byte_Stuffing\n *\/\n\nnamespace packet {\nnamespace frame {\n\nsize_t stuff(const void* source, void* dest, size_t source_byte_size) {\n osalDbgCheck(source != nullptr);\n osalDbgCheck(dest != nullptr);\n osalDbgAssert(source_byte_size <= COBS_MAX_SIZE_DATA_SET,\n \"source data exceeds allowed frame algorithm size\");\n\n const char* source_ = static_cast<const char*>(source);\n char* dest_ = static_cast<char*>(dest);\n\n const char* end = source_ + source_byte_size;\n char* code_p = dest_++; \/* pointer to write code *\/\n uint8_t code = 0x01;\n\n auto write_code = [&]() {\n *code_p = code;\n code_p = dest_++;\n code = 0x01;\n };\n\n while (source_ < end) {\n if (*source_ == 0) { \/* handle zero byte in data *\/\n write_code();\n } else { \/* handle non-zero byte *\/\n *dest_++ = *source_;\n if (++code == 0xff) { \/* reached max COBS data size *\/\n write_code();\n }\n }\n ++source_;\n }\n write_code();\n *dest_ = COBS_PACKET_DELIMITER;\n return source_byte_size + PACKET_OVERHEAD;\n}\n\nsize_t unstuff(const void* source, void* dest, size_t source_byte_size) {\n osalDbgCheck(source != nullptr);\n osalDbgCheck(dest != nullptr);\n \/\/ osalDbgAssert(source_byte_size <= COBS_MAX_SIZE_DATA_SET + 1,\n \/\/ \"invalid data size\"); always true due to data type\n\n const char* source_ = static_cast<const char*>(source);\n char* dest_ = static_cast<char*>(dest);\n\n const char* end = source_ + source_byte_size;\n while (source_ < end) {\n uint8_t code = *source_++;\n\n if (code == 0) {\n osalDbgAssert(dest_ != static_cast<char*>(dest), \"zero byte input\");\n break;\n }\n osalDbgAssert((code - 1) <= (end - source_), \"input code too small or source buffer too small\");\n for (uint8_t i = 1; i < code; ++i) {\n *dest_++ = *source_++;\n }\n if (code < 0xff) { \/* don't write the end-of-packet zero if data length = 0xff *\/\n *dest_++ = 0;\n }\n }\n return source_byte_size - PACKET_OVERHEAD;\n}\n\nsize_t unstuff(const void* source, void* dest) {\n osalDbgCheck(source != nullptr);\n osalDbgCheck(dest != nullptr);\n\n const char* source_ = static_cast<const char*>(source);\n char* dest_ = static_cast<char*>(dest);\n\n while (true) {\n uint8_t code = *source_++;\n\n if (code == 0) {\n osalDbgAssert(dest_ != static_cast<char*>(dest), \"zero byte input\");\n break;\n }\n osalDbgAssert((code - 1) <=\n (COBS_MAX_SIZE_DATA_SET - (dest_ - static_cast<char*>(dest) - 1)),\n \"input code too small or source buffer too small\");\n for (uint8_t i = 1; i < code; ++i) {\n *dest_++ = *source_++;\n }\n if (code < 0xff) { \/* don't write the end-of-packet zero if data length = 0xff *\/\n *dest_++ = 0;\n }\n }\n return dest_ - static_cast<char*>(dest) - 1;\n}\n\n} \/\/ namespace frame\n} \/\/ namespace packet\n<commit_msg>Re-enable frame unstuff source byte size check<commit_after>#include \"packet\/frame.h\"\n#include \"osal.h\"\n\n\/*\n * Packet framing uses the Consistent Overhead Byte Stuffing algorithm for\n * encoding data bytes. The maximum length for each packet is limited to 254 bytes.\n * Refer to: https:\/\/en.wikipedia.org\/wiki\/Consistent_Overhead_Byte_Stuffing\n *\/\n\nnamespace packet {\nnamespace frame {\n\nsize_t stuff(const void* source, void* dest, size_t source_byte_size) {\n osalDbgCheck(source != nullptr);\n osalDbgCheck(dest != nullptr);\n osalDbgAssert(source_byte_size <= COBS_MAX_SIZE_DATA_SET,\n \"source data exceeds allowed frame algorithm size\");\n\n const char* source_ = static_cast<const char*>(source);\n char* dest_ = static_cast<char*>(dest);\n\n const char* end = source_ + source_byte_size;\n char* code_p = dest_++; \/* pointer to write code *\/\n uint8_t code = 0x01;\n\n auto write_code = [&]() {\n *code_p = code;\n code_p = dest_++;\n code = 0x01;\n };\n\n while (source_ < end) {\n if (*source_ == 0) { \/* handle zero byte in data *\/\n write_code();\n } else { \/* handle non-zero byte *\/\n *dest_++ = *source_;\n if (++code == 0xff) { \/* reached max COBS data size *\/\n write_code();\n }\n }\n ++source_;\n }\n write_code();\n *dest_ = COBS_PACKET_DELIMITER;\n return source_byte_size + PACKET_OVERHEAD;\n}\n\nsize_t unstuff(const void* source, void* dest, size_t source_byte_size) {\n osalDbgCheck(source != nullptr);\n osalDbgCheck(dest != nullptr);\n osalDbgAssert(source_byte_size <= COBS_MAX_SIZE_DATA_SET + 1,\n \"invalid data size\");\n\n const char* source_ = static_cast<const char*>(source);\n char* dest_ = static_cast<char*>(dest);\n\n const char* end = source_ + source_byte_size;\n while (source_ < end) {\n uint8_t code = *source_++;\n\n if (code == 0) {\n osalDbgAssert(dest_ != static_cast<char*>(dest), \"zero byte input\");\n break;\n }\n osalDbgAssert((code - 1) <= (end - source_), \"input code too small or source buffer too small\");\n for (uint8_t i = 1; i < code; ++i) {\n *dest_++ = *source_++;\n }\n if (code < 0xff) { \/* don't write the end-of-packet zero if data length = 0xff *\/\n *dest_++ = 0;\n }\n }\n return source_byte_size - PACKET_OVERHEAD;\n}\n\nsize_t unstuff(const void* source, void* dest) {\n osalDbgCheck(source != nullptr);\n osalDbgCheck(dest != nullptr);\n\n const char* source_ = static_cast<const char*>(source);\n char* dest_ = static_cast<char*>(dest);\n\n while (true) {\n uint8_t code = *source_++;\n\n if (code == 0) {\n osalDbgAssert(dest_ != static_cast<char*>(dest), \"zero byte input\");\n break;\n }\n osalDbgAssert((code - 1) <=\n (COBS_MAX_SIZE_DATA_SET - (dest_ - static_cast<char*>(dest) - 1)),\n \"input code too small or source buffer too small\");\n for (uint8_t i = 1; i < code; ++i) {\n *dest_++ = *source_++;\n }\n if (code < 0xff) { \/* don't write the end-of-packet zero if data length = 0xff *\/\n *dest_++ = 0;\n }\n }\n return dest_ - static_cast<char*>(dest) - 1;\n}\n\n} \/\/ namespace frame\n} \/\/ namespace packet\n<|endoftext|>"} {"text":"<commit_before>\/* vim:expandtab:shiftwidth=2:tabstop=2:smarttab:\n * \n * DataDifferential Utility Library\n *\n * Copyright (C) 2011 Data Differential, http:\/\/datadifferential.com\/\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n *\n * * Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following disclaimer\n * in the documentation and\/or other materials provided with the\n * distribution.\n *\n * * The names of its contributors may not be used to endorse or\n * promote products derived from this software without specific prior\n * written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n *\/\n\n\n#include \"gear_config.h\"\n\n#include \"util\/instance.hpp\"\n\n#include <cstdio>\n#include <iostream>\n#include <netdb.h>\n#include <netinet\/in.h>\n#include <poll.h>\n#include <sstream>\n#include <sys\/socket.h>\n#include <sys\/types.h>\n\n#ifdef HAVE_UNISTD_H\n#include <unistd.h>\n#endif\n\n\nnamespace datadifferential {\nnamespace util {\n\nInstance::Instance(const std::string& hostname_arg, const std::string& service_arg) :\n _host(hostname_arg),\n _service(service_arg),\n _sockfd(INVALID_SOCKET),\n _use_ssl(false),\n state(NOT_WRITING),\n _addrinfo(0),\n _addrinfo_next(0),\n _finish_fn(NULL),\n _operations(),\n _ctx_ssl(NULL),\n _ssl(NULL)\n {\n }\n\nInstance::Instance(const std::string& hostname_arg, const in_port_t port_arg) :\n _host(hostname_arg),\n _sockfd(INVALID_SOCKET),\n _use_ssl(false),\n state(NOT_WRITING),\n _addrinfo(0),\n _addrinfo_next(0),\n _finish_fn(NULL),\n _operations(),\n _ctx_ssl(NULL),\n _ssl(NULL)\n {\n char tmp[BUFSIZ];\n snprintf(tmp, sizeof(tmp), \"%u\", static_cast<unsigned int>(port_arg));\n _service= tmp;\n }\n\nInstance::~Instance()\n{\n close_socket();\n free_addrinfo();\n for (Operation::vector::iterator iter= _operations.begin(); iter != _operations.end(); ++iter)\n {\n delete *iter;\n }\n _operations.clear();\n\n delete _finish_fn;\n\n#if defined(HAVE_CYASSL) && HAVE_CYASSL\n if (_ssl)\n {\n CyaSSL_shutdown(_ssl);\n CyaSSL_free(_ssl);\n }\n if (_ctx_ssl)\n {\n CyaSSL_CTX_free(_ctx_ssl);\n }\n CyaSSL_Cleanup();\n#endif\n}\n\nbool Instance::init_ssl()\n{\n#if defined(HAVE_CYASSL) && HAVE_CYASSL\n CyaSSL_Init();\n\n if ((_ctx_ssl= CyaSSL_CTX_new(CyaTLSv1_client_method())) == NULL)\n {\n _last_error= \"CyaSSL_CTX_new error\";\n return false;\n }\n\n if (CyaSSL_CTX_load_verify_locations(_ctx_ssl, ssl_ca_file(), 0) != SSL_SUCCESS)\n {\n std::stringstream message;\n message << \"Error loading CA file \" << ssl_ca_file();\n _last_error= message.str();\n return false;\n }\n\n if (CyaSSL_CTX_use_certificate_file(_ctx_ssl, ssl_certificate(), SSL_FILETYPE_PEM) != SSL_SUCCESS)\n {\n std::stringstream message;\n message << \"Error loading certificate file \" << ssl_certificate();\n _last_error= message.str();\n return false;\n }\n\n if (CyaSSL_CTX_use_PrivateKey_file(_ctx_ssl, ssl_key(), SSL_FILETYPE_PEM) != SSL_SUCCESS)\n {\n std::stringstream message;\n message << \"Error loading private key file \" << ssl_key();\n _last_error= message.str();\n return false;\n }\n#endif \/\/ defined(HAVE_CYASSL) && HAVE_CYASSL\n return true;\n}\n\nbool Instance::run()\n{\n if (_use_ssl)\n {\n if (not init_ssl())\n {\n return false;\n }\n }\n\n while (not _operations.empty())\n {\n Operation::vector::value_type operation= _operations.back();\n\n switch (state)\n {\n case NOT_WRITING:\n {\n free_addrinfo();\n\n struct addrinfo ai;\n memset(&ai, 0, sizeof(struct addrinfo));\n ai.ai_socktype= SOCK_STREAM;\n ai.ai_protocol= IPPROTO_TCP;\n\n int ret= getaddrinfo(_host.c_str(), _service.c_str(), &ai, &_addrinfo);\n if (ret)\n {\n std::stringstream message;\n message << \"Failed to connect on \" << _host.c_str() << \":\" << _service.c_str() << \" with \" << gai_strerror(ret);\n _last_error= message.str();\n return false;\n }\n }\n _addrinfo_next= _addrinfo;\n state= CONNECT;\n break;\n\n case NEXT_CONNECT_ADDRINFO:\n if (_addrinfo_next->ai_next == NULL)\n {\n std::stringstream message;\n message << \"Error connecting to \" << _host.c_str() << \".\" << std::endl;\n _last_error= message.str();\n return false;\n }\n _addrinfo_next= _addrinfo_next->ai_next;\n\n\n case CONNECT:\n close_socket();\n\n _sockfd= socket(_addrinfo_next->ai_family,\n _addrinfo_next->ai_socktype,\n _addrinfo_next->ai_protocol);\n if (_sockfd == INVALID_SOCKET)\n {\n perror(\"socket\");\n continue;\n }\n\n if (connect(_sockfd, _addrinfo_next->ai_addr, _addrinfo_next->ai_addrlen) < 0)\n {\n switch(errno)\n {\n case EAGAIN:\n case EINTR:\n state= CONNECT;\n break;\n\n case EINPROGRESS:\n state= CONNECTING;\n break;\n\n case ECONNREFUSED:\n case ENETUNREACH:\n case ETIMEDOUT:\n default:\n state= NEXT_CONNECT_ADDRINFO;\n break;\n }\n }\n else\n {\n state= CONNECTING;\n }\n break;\n\n case CONNECTING:\n \/\/ Add logic for poll() for nonblocking.\n state= CONNECTED;\n break;\n\n case CONNECTED:\n case WRITING:\n {\n size_t packet_length= operation->size();\n const char *packet= operation->ptr();\n\n#if defined(HAVE_CYASSL) && HAVE_CYASSL\n if (_ctx_ssl)\n {\n _ssl= CyaSSL_new(_ctx_ssl);\n if (_ssl == NULL)\n {\n _last_error= \"CyaSSL_new() failed\";\n return false;\n }\n\n int ssl_error;\n if ((ssl_error= CyaSSL_set_fd(_ssl, _sockfd)) != SSL_SUCCESS)\n {\n _last_error= \"CyaSSL_set_fd() failed\";\n return false;\n }\n }\n#endif\n\n while(packet_length)\n {\n ssize_t write_size;\n#if defined(HAVE_CYASSL) && HAVE_CYASSL\n if (_ssl)\n {\n write_size= CyaSSL_write(_ssl, (const void*)packet, int(packet_length));\n if (write_size < 0)\n {\n char errorString[80];\n CyaSSL_ERR_error_string(CyaSSL_get_error(_ssl, 0), errorString);\n _last_error= errorString;\n return false;\n }\n }\n else\n#endif\n {\n write_size= send(_sockfd, packet, packet_length, 0);\n\n if (write_size < 0)\n {\n std::stringstream msg;\n msg << \"Failed during send(\" << strerror(errno) << \")\";\n _last_error= msg.str();\n return false;\n }\n }\n\n packet_length-= static_cast<size_t>(write_size);\n packet+= static_cast<size_t>(write_size);\n }\n }\n state= READING;\n break;\n\n case READING:\n if (operation->has_response())\n {\n ssize_t read_length;\n\n do\n {\n char buffer[BUFSIZ];\n#if defined(HAVE_CYASSL) && HAVE_CYASSL\n if (_ssl)\n {\n read_length= CyaSSL_read(_ssl, (void *)buffer, sizeof(buffer));\n if (read_length < 0)\n {\n char errorString[80];\n CyaSSL_ERR_error_string(CyaSSL_get_error(_ssl, 0), errorString);\n _last_error= errorString;\n return false;\n }\n }\n else\n#endif\n {\n read_length= ::recv(_sockfd, buffer, sizeof(buffer), 0);\n }\n\n if (read_length < 0)\n {\n _last_error.clear();\n _last_error+= \"Error occured while reading data from \";\n _last_error+= _host;\n return false;\n }\n else if (read_length == 0)\n {\n _last_error.clear();\n _last_error+= \"Socket was shutdown while reading from \";\n _last_error+= _host;\n return false;\n }\n\n operation->push(buffer, static_cast<size_t>(read_length));\n\n } while (more_to_read());\n } \/\/ end has_response\n\n state= FINISHED;\n break;\n\n case FINISHED:\n std::string response;\n bool success= operation->response(response);\n if (_finish_fn)\n {\n if (not _finish_fn->call(success, response))\n {\n \/\/ Error was sent from _finish_fn \n return false;\n }\n }\n\n if (operation->reconnect())\n {\n }\n _operations.pop_back();\n delete operation;\n\n state= CONNECTED;\n break;\n } \/\/ end switch\n }\n\n return true;\n} \/\/ end run()\n\nbool Instance::more_to_read() const\n{\n struct pollfd fds;\n fds.fd= _sockfd;\n fds.events = POLLIN;\n\n if (poll(&fds, 1, 5) < 1) \/\/ Default timeout is 5\n {\n return false;\n }\n\n return true;\n}\n\nvoid Instance::close_socket()\n{\n if (_sockfd == INVALID_SOCKET)\n {\n return;\n }\n\n \/* in case of death shutdown to avoid blocking at close() *\/\n if (shutdown(_sockfd, SHUT_RDWR) == SOCKET_ERROR && get_socket_errno() != ENOTCONN)\n {\n perror(\"shutdown\");\n }\n else if (closesocket(_sockfd) == SOCKET_ERROR)\n {\n perror(\"close\");\n }\n\n _sockfd= INVALID_SOCKET;\n}\n\nvoid Instance::free_addrinfo()\n{\n if (_addrinfo == NULL)\n {\n return;\n }\n\n freeaddrinfo(_addrinfo);\n _addrinfo= NULL;\n _addrinfo_next= NULL;\n}\n\n} \/* namespace util *\/\n} \/* namespace datadifferential *\/\n<commit_msg>Fix for gearadmin multi-op<commit_after>\/* vim:expandtab:shiftwidth=2:tabstop=2:smarttab:\n * \n * DataDifferential Utility Library\n *\n * Copyright (C) 2011 Data Differential, http:\/\/datadifferential.com\/\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n *\n * * Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following disclaimer\n * in the documentation and\/or other materials provided with the\n * distribution.\n *\n * * The names of its contributors may not be used to endorse or\n * promote products derived from this software without specific prior\n * written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n *\/\n\n\n#include \"gear_config.h\"\n\n#include \"util\/instance.hpp\"\n\n#include <cstdio>\n#include <iostream>\n#include <netdb.h>\n#include <netinet\/in.h>\n#include <poll.h>\n#include <sstream>\n#include <sys\/socket.h>\n#include <sys\/types.h>\n\n#ifdef HAVE_UNISTD_H\n#include <unistd.h>\n#endif\n\n\nnamespace datadifferential {\nnamespace util {\n\nInstance::Instance(const std::string& hostname_arg, const std::string& service_arg) :\n _host(hostname_arg),\n _service(service_arg),\n _sockfd(INVALID_SOCKET),\n _use_ssl(false),\n state(NOT_WRITING),\n _addrinfo(0),\n _addrinfo_next(0),\n _finish_fn(NULL),\n _operations(),\n _ctx_ssl(NULL),\n _ssl(NULL)\n {\n }\n\nInstance::Instance(const std::string& hostname_arg, const in_port_t port_arg) :\n _host(hostname_arg),\n _sockfd(INVALID_SOCKET),\n _use_ssl(false),\n state(NOT_WRITING),\n _addrinfo(0),\n _addrinfo_next(0),\n _finish_fn(NULL),\n _operations(),\n _ctx_ssl(NULL),\n _ssl(NULL)\n {\n char tmp[BUFSIZ];\n snprintf(tmp, sizeof(tmp), \"%u\", static_cast<unsigned int>(port_arg));\n _service= tmp;\n }\n\nInstance::~Instance()\n{\n close_socket();\n free_addrinfo();\n for (Operation::vector::iterator iter= _operations.begin(); iter != _operations.end(); ++iter)\n {\n delete *iter;\n }\n _operations.clear();\n\n delete _finish_fn;\n\n#if defined(HAVE_CYASSL) && HAVE_CYASSL\n if (_ssl)\n {\n CyaSSL_shutdown(_ssl);\n CyaSSL_free(_ssl);\n }\n if (_ctx_ssl)\n {\n CyaSSL_CTX_free(_ctx_ssl);\n }\n CyaSSL_Cleanup();\n#endif\n}\n\nbool Instance::init_ssl()\n{\n#if defined(HAVE_CYASSL) && HAVE_CYASSL\n CyaSSL_Init();\n\n if ((_ctx_ssl= CyaSSL_CTX_new(CyaTLSv1_client_method())) == NULL)\n {\n _last_error= \"CyaSSL_CTX_new error\";\n return false;\n }\n\n if (CyaSSL_CTX_load_verify_locations(_ctx_ssl, ssl_ca_file(), 0) != SSL_SUCCESS)\n {\n std::stringstream message;\n message << \"Error loading CA file \" << ssl_ca_file();\n _last_error= message.str();\n return false;\n }\n\n if (CyaSSL_CTX_use_certificate_file(_ctx_ssl, ssl_certificate(), SSL_FILETYPE_PEM) != SSL_SUCCESS)\n {\n std::stringstream message;\n message << \"Error loading certificate file \" << ssl_certificate();\n _last_error= message.str();\n return false;\n }\n\n if (CyaSSL_CTX_use_PrivateKey_file(_ctx_ssl, ssl_key(), SSL_FILETYPE_PEM) != SSL_SUCCESS)\n {\n std::stringstream message;\n message << \"Error loading private key file \" << ssl_key();\n _last_error= message.str();\n return false;\n }\n#endif \/\/ defined(HAVE_CYASSL) && HAVE_CYASSL\n return true;\n}\n\nbool Instance::run()\n{\n if (_use_ssl)\n {\n if (not init_ssl())\n {\n return false;\n }\n }\n\n while (not _operations.empty())\n {\n Operation::vector::value_type operation= _operations.back();\n\n switch (state)\n {\n case NOT_WRITING:\n {\n free_addrinfo();\n\n struct addrinfo ai;\n memset(&ai, 0, sizeof(struct addrinfo));\n ai.ai_socktype= SOCK_STREAM;\n ai.ai_protocol= IPPROTO_TCP;\n\n int ret= getaddrinfo(_host.c_str(), _service.c_str(), &ai, &_addrinfo);\n if (ret)\n {\n std::stringstream message;\n message << \"Failed to connect on \" << _host.c_str() << \":\" << _service.c_str() << \" with \" << gai_strerror(ret);\n _last_error= message.str();\n return false;\n }\n }\n _addrinfo_next= _addrinfo;\n state= CONNECT;\n break;\n\n case NEXT_CONNECT_ADDRINFO:\n if (_addrinfo_next->ai_next == NULL)\n {\n std::stringstream message;\n message << \"Error connecting to \" << _host.c_str() << \".\" << std::endl;\n _last_error= message.str();\n return false;\n }\n _addrinfo_next= _addrinfo_next->ai_next;\n\n\n case CONNECT:\n close_socket();\n\n _sockfd= socket(_addrinfo_next->ai_family,\n _addrinfo_next->ai_socktype,\n _addrinfo_next->ai_protocol);\n if (_sockfd == INVALID_SOCKET)\n {\n perror(\"socket\");\n continue;\n }\n\n if (connect(_sockfd, _addrinfo_next->ai_addr, _addrinfo_next->ai_addrlen) < 0)\n {\n switch(errno)\n {\n case EAGAIN:\n case EINTR:\n state= CONNECT;\n break;\n\n case EINPROGRESS:\n state= CONNECTING;\n break;\n\n case ECONNREFUSED:\n case ENETUNREACH:\n case ETIMEDOUT:\n default:\n state= NEXT_CONNECT_ADDRINFO;\n break;\n }\n }\n else\n {\n state= CONNECTING;\n }\n break;\n\n case CONNECTING:\n \/\/ Add logic for poll() for nonblocking.\n state= CONNECTED;\n break;\n\n case CONNECTED:\n case WRITING:\n {\n size_t packet_length= operation->size();\n const char *packet= operation->ptr();\n\n#if defined(HAVE_CYASSL) && HAVE_CYASSL\n if (_ctx_ssl and not _ssl)\n {\n _ssl= CyaSSL_new(_ctx_ssl);\n if (_ssl == NULL)\n {\n _last_error= \"CyaSSL_new() failed\";\n return false;\n }\n\n int ssl_error;\n if ((ssl_error= CyaSSL_set_fd(_ssl, _sockfd)) != SSL_SUCCESS)\n {\n _last_error= \"CyaSSL_set_fd() failed\";\n return false;\n }\n }\n#endif\n\n while(packet_length)\n {\n ssize_t write_size;\n#if defined(HAVE_CYASSL) && HAVE_CYASSL\n if (_ssl)\n {\n write_size= CyaSSL_write(_ssl, (const void*)packet, int(packet_length));\n if (write_size < 0)\n {\n char errorString[80];\n CyaSSL_ERR_error_string(CyaSSL_get_error(_ssl, 0), errorString);\n _last_error= errorString;\n return false;\n }\n }\n else\n#endif\n {\n write_size= send(_sockfd, packet, packet_length, 0);\n\n if (write_size < 0)\n {\n std::stringstream msg;\n msg << \"Failed during send(\" << strerror(errno) << \")\";\n _last_error= msg.str();\n return false;\n }\n }\n\n packet_length-= static_cast<size_t>(write_size);\n packet+= static_cast<size_t>(write_size);\n }\n }\n state= READING;\n break;\n\n case READING:\n if (operation->has_response())\n {\n ssize_t read_length;\n\n do\n {\n char buffer[BUFSIZ];\n#if defined(HAVE_CYASSL) && HAVE_CYASSL\n if (_ssl)\n {\n read_length= CyaSSL_read(_ssl, (void *)buffer, sizeof(buffer));\n if (read_length < 0)\n {\n char errorString[80];\n CyaSSL_ERR_error_string(CyaSSL_get_error(_ssl, 0), errorString);\n _last_error= errorString;\n return false;\n }\n }\n else\n#endif\n {\n read_length= ::recv(_sockfd, buffer, sizeof(buffer), 0);\n }\n\n if (read_length < 0)\n {\n _last_error.clear();\n _last_error+= \"Error occured while reading data from \";\n _last_error+= _host;\n return false;\n }\n else if (read_length == 0)\n {\n _last_error.clear();\n _last_error+= \"Socket was shutdown while reading from \";\n _last_error+= _host;\n return false;\n }\n\n operation->push(buffer, static_cast<size_t>(read_length));\n\n } while (more_to_read());\n } \/\/ end has_response\n\n state= FINISHED;\n break;\n\n case FINISHED:\n std::string response;\n bool success= operation->response(response);\n if (_finish_fn)\n {\n if (not _finish_fn->call(success, response))\n {\n \/\/ Error was sent from _finish_fn \n return false;\n }\n }\n\n if (operation->reconnect())\n {\n }\n _operations.pop_back();\n delete operation;\n\n state= CONNECTED;\n break;\n } \/\/ end switch\n }\n\n return true;\n} \/\/ end run()\n\nbool Instance::more_to_read() const\n{\n struct pollfd fds;\n fds.fd= _sockfd;\n fds.events = POLLIN;\n\n if (poll(&fds, 1, 5) < 1) \/\/ Default timeout is 5\n {\n return false;\n }\n\n return true;\n}\n\nvoid Instance::close_socket()\n{\n if (_sockfd == INVALID_SOCKET)\n {\n return;\n }\n\n \/* in case of death shutdown to avoid blocking at close() *\/\n if (shutdown(_sockfd, SHUT_RDWR) == SOCKET_ERROR && get_socket_errno() != ENOTCONN)\n {\n perror(\"shutdown\");\n }\n else if (closesocket(_sockfd) == SOCKET_ERROR)\n {\n perror(\"close\");\n }\n\n _sockfd= INVALID_SOCKET;\n}\n\nvoid Instance::free_addrinfo()\n{\n if (_addrinfo == NULL)\n {\n return;\n }\n\n freeaddrinfo(_addrinfo);\n _addrinfo= NULL;\n _addrinfo_next= NULL;\n}\n\n} \/* namespace util *\/\n} \/* namespace datadifferential *\/\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2017-2019 The Dash Core developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \"cbtx.h\"\n#include \"core_io.h\"\n#include \"deterministicmns.h\"\n#include \"simplifiedmns.h\"\n#include \"specialtx.h\"\n\n#include \"base58.h\"\n#include \"chainparams.h\"\n#include \"consensus\/merkle.h\"\n#include \"univalue.h\"\n#include \"validation.h\"\n\nCSimplifiedMNListEntry::CSimplifiedMNListEntry(const CDeterministicMN& dmn) :\n proRegTxHash(dmn.proTxHash),\n confirmedHash(dmn.pdmnState->confirmedHash),\n service(dmn.pdmnState->addr),\n pubKeyOperator(dmn.pdmnState->pubKeyOperator),\n keyIDVoting(dmn.pdmnState->keyIDVoting),\n isValid(dmn.pdmnState->nPoSeBanHeight == -1)\n{\n}\n\nuint256 CSimplifiedMNListEntry::CalcHash() const\n{\n CHashWriter hw(SER_GETHASH, CLIENT_VERSION);\n hw << *this;\n return hw.GetHash();\n}\n\nstd::string CSimplifiedMNListEntry::ToString() const\n{\n return strprintf(\"CSimplifiedMNListEntry(proRegTxHash=%s, confirmedHash=%s, service=%s, pubKeyOperator=%s, votingAddress=%s, isValie=%d)\",\n proRegTxHash.ToString(), confirmedHash.ToString(), service.ToString(false), pubKeyOperator.ToString(), CBitcoinAddress(keyIDVoting).ToString(), isValid);\n}\n\nvoid CSimplifiedMNListEntry::ToJson(UniValue& obj) const\n{\n obj.clear();\n obj.setObject();\n obj.push_back(Pair(\"proRegTxHash\", proRegTxHash.ToString()));\n obj.push_back(Pair(\"confirmedHash\", confirmedHash.ToString()));\n obj.push_back(Pair(\"service\", service.ToString(false)));\n obj.push_back(Pair(\"pubKeyOperator\", pubKeyOperator.ToString()));\n obj.push_back(Pair(\"votingAddress\", CBitcoinAddress(keyIDVoting).ToString()));\n obj.push_back(Pair(\"isValid\", isValid));\n}\n\nCSimplifiedMNList::CSimplifiedMNList(const std::vector<CSimplifiedMNListEntry>& smlEntries)\n{\n mnList = smlEntries;\n\n std::sort(mnList.begin(), mnList.end(), [&](const CSimplifiedMNListEntry& a, const CSimplifiedMNListEntry& b) {\n return a.proRegTxHash.Compare(b.proRegTxHash) < 0;\n });\n}\n\nCSimplifiedMNList::CSimplifiedMNList(const CDeterministicMNList& dmnList)\n{\n mnList.reserve(dmnList.GetAllMNsCount());\n\n dmnList.ForEachMN(false, [this](const CDeterministicMNCPtr& dmn) {\n mnList.emplace_back(*dmn);\n });\n\n std::sort(mnList.begin(), mnList.end(), [&](const CSimplifiedMNListEntry& a, const CSimplifiedMNListEntry& b) {\n return a.proRegTxHash.Compare(b.proRegTxHash) < 0;\n });\n}\n\nuint256 CSimplifiedMNList::CalcMerkleRoot(bool* pmutated) const\n{\n std::vector<uint256> leaves;\n leaves.reserve(mnList.size());\n for (const auto& e : mnList) {\n leaves.emplace_back(e.CalcHash());\n }\n return ComputeMerkleRoot(leaves, pmutated);\n}\n\nvoid CSimplifiedMNListDiff::ToJson(UniValue& obj) const\n{\n obj.setObject();\n\n obj.push_back(Pair(\"baseBlockHash\", baseBlockHash.ToString()));\n obj.push_back(Pair(\"blockHash\", blockHash.ToString()));\n\n CDataStream ssCbTxMerkleTree(SER_NETWORK, PROTOCOL_VERSION);\n ssCbTxMerkleTree << cbTxMerkleTree;\n obj.push_back(Pair(\"cbTxMerkleTree\", HexStr(ssCbTxMerkleTree.begin(), ssCbTxMerkleTree.end())));\n\n obj.push_back(Pair(\"cbTx\", EncodeHexTx(*cbTx)));\n\n UniValue deletedMNsArr(UniValue::VARR);\n for (const auto& h : deletedMNs) {\n deletedMNsArr.push_back(h.ToString());\n }\n obj.push_back(Pair(\"deletedMNs\", deletedMNsArr));\n\n UniValue mnListArr(UniValue::VARR);\n for (const auto& e : mnList) {\n UniValue eObj;\n e.ToJson(eObj);\n mnListArr.push_back(eObj);\n }\n obj.push_back(Pair(\"mnList\", mnListArr));\n\n CCbTx cbTxPayload;\n if (GetTxPayload(*cbTx, cbTxPayload)) {\n obj.push_back(Pair(\"merkleRootMNList\", cbTxPayload.merkleRootMNList.ToString()));\n }\n}\n\nbool BuildSimplifiedMNListDiff(const uint256& baseBlockHash, const uint256& blockHash, CSimplifiedMNListDiff& mnListDiffRet, std::string& errorRet)\n{\n AssertLockHeld(cs_main);\n mnListDiffRet = CSimplifiedMNListDiff();\n\n BlockMap::iterator baseBlockIt = mapBlockIndex.begin();\n if (!baseBlockHash.IsNull()) {\n baseBlockIt = mapBlockIndex.find(baseBlockHash);\n }\n auto blockIt = mapBlockIndex.find(blockHash);\n if (baseBlockIt == mapBlockIndex.end()) {\n errorRet = strprintf(\"block %s not found\", baseBlockHash.ToString());\n return false;\n }\n if (blockIt == mapBlockIndex.end()) {\n errorRet = strprintf(\"block %s not found\", blockHash.ToString());\n return false;\n }\n\n if (!chainActive.Contains(baseBlockIt->second) || !chainActive.Contains(blockIt->second)) {\n errorRet = strprintf(\"block %s and %s are not in the same chain\", baseBlockHash.ToString(), blockHash.ToString());\n return false;\n }\n if (baseBlockIt->second->nHeight > blockIt->second->nHeight) {\n errorRet = strprintf(\"base block %s is higher then block %s\", baseBlockHash.ToString(), blockHash.ToString());\n return false;\n }\n\n LOCK(deterministicMNManager->cs);\n\n auto baseDmnList = deterministicMNManager->GetListForBlock(baseBlockHash);\n auto dmnList = deterministicMNManager->GetListForBlock(blockHash);\n mnListDiffRet = baseDmnList.BuildSimplifiedDiff(dmnList);\n\n \/\/ TODO store coinbase TX in CBlockIndex\n CBlock block;\n if (!ReadBlockFromDisk(block, blockIt->second, Params().GetConsensus())) {\n errorRet = strprintf(\"failed to read block %s from disk\", blockHash.ToString());\n return false;\n }\n\n mnListDiffRet.cbTx = block.vtx[0];\n\n std::vector<uint256> vHashes;\n std::vector<bool> vMatch(block.vtx.size(), false);\n for (const auto& tx : block.vtx) {\n vHashes.emplace_back(tx->GetHash());\n }\n vMatch[0] = true; \/\/ only coinbase matches\n mnListDiffRet.cbTxMerkleTree = CPartialMerkleTree(vHashes, vMatch);\n\n return true;\n}\n<commit_msg>Fix incorrect usage of begin() when genesis block is requested in \"protx diff\" (#2699)<commit_after>\/\/ Copyright (c) 2017-2019 The Dash Core developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \"cbtx.h\"\n#include \"core_io.h\"\n#include \"deterministicmns.h\"\n#include \"simplifiedmns.h\"\n#include \"specialtx.h\"\n\n#include \"base58.h\"\n#include \"chainparams.h\"\n#include \"consensus\/merkle.h\"\n#include \"univalue.h\"\n#include \"validation.h\"\n\nCSimplifiedMNListEntry::CSimplifiedMNListEntry(const CDeterministicMN& dmn) :\n proRegTxHash(dmn.proTxHash),\n confirmedHash(dmn.pdmnState->confirmedHash),\n service(dmn.pdmnState->addr),\n pubKeyOperator(dmn.pdmnState->pubKeyOperator),\n keyIDVoting(dmn.pdmnState->keyIDVoting),\n isValid(dmn.pdmnState->nPoSeBanHeight == -1)\n{\n}\n\nuint256 CSimplifiedMNListEntry::CalcHash() const\n{\n CHashWriter hw(SER_GETHASH, CLIENT_VERSION);\n hw << *this;\n return hw.GetHash();\n}\n\nstd::string CSimplifiedMNListEntry::ToString() const\n{\n return strprintf(\"CSimplifiedMNListEntry(proRegTxHash=%s, confirmedHash=%s, service=%s, pubKeyOperator=%s, votingAddress=%s, isValie=%d)\",\n proRegTxHash.ToString(), confirmedHash.ToString(), service.ToString(false), pubKeyOperator.ToString(), CBitcoinAddress(keyIDVoting).ToString(), isValid);\n}\n\nvoid CSimplifiedMNListEntry::ToJson(UniValue& obj) const\n{\n obj.clear();\n obj.setObject();\n obj.push_back(Pair(\"proRegTxHash\", proRegTxHash.ToString()));\n obj.push_back(Pair(\"confirmedHash\", confirmedHash.ToString()));\n obj.push_back(Pair(\"service\", service.ToString(false)));\n obj.push_back(Pair(\"pubKeyOperator\", pubKeyOperator.ToString()));\n obj.push_back(Pair(\"votingAddress\", CBitcoinAddress(keyIDVoting).ToString()));\n obj.push_back(Pair(\"isValid\", isValid));\n}\n\nCSimplifiedMNList::CSimplifiedMNList(const std::vector<CSimplifiedMNListEntry>& smlEntries)\n{\n mnList = smlEntries;\n\n std::sort(mnList.begin(), mnList.end(), [&](const CSimplifiedMNListEntry& a, const CSimplifiedMNListEntry& b) {\n return a.proRegTxHash.Compare(b.proRegTxHash) < 0;\n });\n}\n\nCSimplifiedMNList::CSimplifiedMNList(const CDeterministicMNList& dmnList)\n{\n mnList.reserve(dmnList.GetAllMNsCount());\n\n dmnList.ForEachMN(false, [this](const CDeterministicMNCPtr& dmn) {\n mnList.emplace_back(*dmn);\n });\n\n std::sort(mnList.begin(), mnList.end(), [&](const CSimplifiedMNListEntry& a, const CSimplifiedMNListEntry& b) {\n return a.proRegTxHash.Compare(b.proRegTxHash) < 0;\n });\n}\n\nuint256 CSimplifiedMNList::CalcMerkleRoot(bool* pmutated) const\n{\n std::vector<uint256> leaves;\n leaves.reserve(mnList.size());\n for (const auto& e : mnList) {\n leaves.emplace_back(e.CalcHash());\n }\n return ComputeMerkleRoot(leaves, pmutated);\n}\n\nvoid CSimplifiedMNListDiff::ToJson(UniValue& obj) const\n{\n obj.setObject();\n\n obj.push_back(Pair(\"baseBlockHash\", baseBlockHash.ToString()));\n obj.push_back(Pair(\"blockHash\", blockHash.ToString()));\n\n CDataStream ssCbTxMerkleTree(SER_NETWORK, PROTOCOL_VERSION);\n ssCbTxMerkleTree << cbTxMerkleTree;\n obj.push_back(Pair(\"cbTxMerkleTree\", HexStr(ssCbTxMerkleTree.begin(), ssCbTxMerkleTree.end())));\n\n obj.push_back(Pair(\"cbTx\", EncodeHexTx(*cbTx)));\n\n UniValue deletedMNsArr(UniValue::VARR);\n for (const auto& h : deletedMNs) {\n deletedMNsArr.push_back(h.ToString());\n }\n obj.push_back(Pair(\"deletedMNs\", deletedMNsArr));\n\n UniValue mnListArr(UniValue::VARR);\n for (const auto& e : mnList) {\n UniValue eObj;\n e.ToJson(eObj);\n mnListArr.push_back(eObj);\n }\n obj.push_back(Pair(\"mnList\", mnListArr));\n\n CCbTx cbTxPayload;\n if (GetTxPayload(*cbTx, cbTxPayload)) {\n obj.push_back(Pair(\"merkleRootMNList\", cbTxPayload.merkleRootMNList.ToString()));\n }\n}\n\nbool BuildSimplifiedMNListDiff(const uint256& baseBlockHash, const uint256& blockHash, CSimplifiedMNListDiff& mnListDiffRet, std::string& errorRet)\n{\n AssertLockHeld(cs_main);\n mnListDiffRet = CSimplifiedMNListDiff();\n\n const CBlockIndex* baseBlockIndex = chainActive.Genesis();\n if (!baseBlockHash.IsNull()) {\n auto it = mapBlockIndex.find(baseBlockHash);\n if (it == mapBlockIndex.end()) {\n errorRet = strprintf(\"block %s not found\", baseBlockHash.ToString());\n return false;\n }\n baseBlockIndex = it->second;\n }\n auto blockIt = mapBlockIndex.find(blockHash);\n if (blockIt == mapBlockIndex.end()) {\n errorRet = strprintf(\"block %s not found\", blockHash.ToString());\n return false;\n }\n const CBlockIndex* blockIndex = blockIt->second;\n\n if (!chainActive.Contains(baseBlockIndex) || !chainActive.Contains(blockIndex)) {\n errorRet = strprintf(\"block %s and %s are not in the same chain\", baseBlockHash.ToString(), blockHash.ToString());\n return false;\n }\n if (baseBlockIndex->nHeight > blockIndex->nHeight) {\n errorRet = strprintf(\"base block %s is higher then block %s\", baseBlockHash.ToString(), blockHash.ToString());\n return false;\n }\n\n LOCK(deterministicMNManager->cs);\n\n auto baseDmnList = deterministicMNManager->GetListForBlock(baseBlockHash);\n auto dmnList = deterministicMNManager->GetListForBlock(blockHash);\n mnListDiffRet = baseDmnList.BuildSimplifiedDiff(dmnList);\n\n \/\/ TODO store coinbase TX in CBlockIndex\n CBlock block;\n if (!ReadBlockFromDisk(block, blockIndex, Params().GetConsensus())) {\n errorRet = strprintf(\"failed to read block %s from disk\", blockHash.ToString());\n return false;\n }\n\n mnListDiffRet.cbTx = block.vtx[0];\n\n std::vector<uint256> vHashes;\n std::vector<bool> vMatch(block.vtx.size(), false);\n for (const auto& tx : block.vtx) {\n vHashes.emplace_back(tx->GetHash());\n }\n vMatch[0] = true; \/\/ only coinbase matches\n mnListDiffRet.cbTxMerkleTree = CPartialMerkleTree(vHashes, vMatch);\n\n return true;\n}\n<|endoftext|>"} {"text":"<commit_before>#include <glm\/gtc\/matrix_transform.hpp>\n#include <GLFW\/glfw3.h>\n#include \"camera.h\"\n\nstatic const float speed = 4.0f; \/\/ units per second\nstatic const float mouseSpeedRad = 0.0005f;\n\nCamera::Camera(GLFWwindow* window, const glm::vec3& startPosition, float startHorizontalAngleRad, float startVerticalAngleRad):\n window(window),\n position(startPosition),\n horizontalAngleRad(startHorizontalAngleRad),\n verticalAngleRad(startVerticalAngleRad) { }\n\nvoid Camera::getViewMatrix(float deltaTimeMs, glm::mat4* pOutViewMatrix) {\n float deltaTimeSec = deltaTimeMs\/1000.0f;\n\n int windowWidth, windowHeight;\n glfwGetWindowSize(window, &windowWidth, &windowHeight);\n\n double mouseX, mouseY;\n glfwGetCursorPos(window, &mouseX, &mouseY);\n\n horizontalAngleRad += mouseSpeedRad * static_cast<float>(windowWidth\/2 - mouseX);\n verticalAngleRad += mouseSpeedRad * static_cast<float>(windowHeight\/2 - mouseY);\n\n glfwSetCursorPos(window, windowWidth\/2, windowHeight\/2);\n\n glm::vec3 direction(\n cos(verticalAngleRad) * sin(horizontalAngleRad),\n sin(verticalAngleRad),\n cos(verticalAngleRad) * cos(horizontalAngleRad)\n );\n\n glm::vec3 right = glm::vec3(\n sin(horizontalAngleRad - 3.14f\/2.0f),\n 0,\n cos(horizontalAngleRad - 3.14f\/2.0f)\n );\n\n glm::vec3 up = glm::cross(right, direction);\n\n if(glfwGetKey(window, GLFW_KEY_W) == GLFW_PRESS) {\n position += direction * deltaTimeSec * speed;\n }\n\n if(glfwGetKey(window, GLFW_KEY_S) == GLFW_PRESS) {\n position -= direction * deltaTimeSec * speed;\n }\n\n if(glfwGetKey(window, GLFW_KEY_A) == GLFW_PRESS) {\n position -= right * deltaTimeSec * speed;\n }\n\n if(glfwGetKey(window, GLFW_KEY_D) == GLFW_PRESS) {\n position += right * deltaTimeSec * speed;\n }\n\n *pOutViewMatrix = glm::lookAt(position, position + direction, up);\n}<commit_msg>Minor changes<commit_after>#include <glm\/gtc\/matrix_transform.hpp>\n#include <GLFW\/glfw3.h>\n#include \"camera.h\"\n\nstatic const float speed = 4.0f; \/\/ units per second\nstatic const float mouseSpeedRad = 0.0005f;\n\nCamera::Camera(GLFWwindow* window, const glm::vec3& startPosition, float startHorizontalAngleRad, float startVerticalAngleRad):\n window(window),\n position(startPosition),\n horizontalAngleRad(startHorizontalAngleRad),\n verticalAngleRad(startVerticalAngleRad) { }\n\nvoid Camera::getViewMatrix(float deltaTimeMs, glm::mat4* pOutViewMatrix) {\n float deltaTimeSec = deltaTimeMs\/1000.0f;\n\n int windowWidth, windowHeight;\n glfwGetWindowSize(window, &windowWidth, &windowHeight);\n\n double mouseX, mouseY;\n glfwGetCursorPos(window, &mouseX, &mouseY);\n\n horizontalAngleRad += mouseSpeedRad * (windowWidth\/2 - mouseX);\n verticalAngleRad += mouseSpeedRad * (windowHeight\/2 - mouseY);\n\n glfwSetCursorPos(window, windowWidth\/2, windowHeight\/2);\n\n glm::vec3 direction(\n cos(verticalAngleRad) * sin(horizontalAngleRad),\n sin(verticalAngleRad),\n cos(verticalAngleRad) * cos(horizontalAngleRad)\n );\n\n glm::vec3 right = glm::vec3(\n sin(horizontalAngleRad - 3.14f\/2.0f),\n 0,\n cos(horizontalAngleRad - 3.14f\/2.0f)\n );\n\n glm::vec3 up = glm::cross(right, direction);\n\n if(glfwGetKey(window, GLFW_KEY_W) == GLFW_PRESS) {\n position += direction * deltaTimeSec * speed;\n }\n\n if(glfwGetKey(window, GLFW_KEY_S) == GLFW_PRESS) {\n position -= direction * deltaTimeSec * speed;\n }\n\n if(glfwGetKey(window, GLFW_KEY_A) == GLFW_PRESS) {\n position -= right * deltaTimeSec * speed;\n }\n\n if(glfwGetKey(window, GLFW_KEY_D) == GLFW_PRESS) {\n position += right * deltaTimeSec * speed;\n }\n\n *pOutViewMatrix = glm::lookAt(position, position + direction, up);\n}<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: inettbc.hxx,v $\n *\n * $Revision: 1.7 $\n *\n * last change: $Author: fs $ $Date: 2001-04-12 10:21:28 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef _SFX_INETTBC_HXX\n#define _SFX_INETTBC_HXX\n\n\/\/ includes *****************************************************************\n#include <tools\/string.hxx>\n#include <tools\/urlobj.hxx>\n\n#ifndef _COMBOBOX_HXX \/\/autogen\n#include <vcl\/combobox.hxx>\n#endif\n\n#define _SVSTDARR_STRINGSDTOR\n#include <svtools\/svstdarr.hxx>\n\nstruct SfxPickEntry_Impl;\nclass SfxURLBox : public ComboBox\n{\nfriend class SfxMatchContext_Impl;\nfriend class SfxURLBox_Impl;\n Link aOpenHdl;\n String aBaseURL;\n INetProtocol eSmartProtocol;\n SfxMatchContext_Impl* pCtx;\n SfxURLBox_Impl* pImp;\n BOOL bAutoCompleteMode;\n BOOL bOnlyDirectories;\n BOOL bModified;\n BOOL bTryAutoComplete: 1,\n bCtrlClick: 1,\n bHistoryDisabled : 1;\n\n BOOL ProcessKey( const KeyCode& rCode );\n void TryAutoComplete( BOOL bForward, BOOL bForce );\n void UpdatePicklistForSmartProtocol_Impl();\n DECL_LINK( AutoCompleteHdl_Impl, void* );\n\nprotected:\n virtual long Notify( NotifyEvent& rNEvt );\n virtual void Select();\n virtual void Modify();\n virtual BOOL QueryDrop( DropEvent &rEvt );\n virtual BOOL Drop( const DropEvent &rEvt );\n virtual long PreNotify( NotifyEvent& rNEvt );\n\npublic:\n SfxURLBox( Window* pParent, INetProtocol eSmart = INET_PROT_NOT_VALID );\n SfxURLBox( Window* pParent, const ResId& _rResId, INetProtocol eSmart = INET_PROT_NOT_VALID );\n ~SfxURLBox();\n\n void OpenURL( const String& rName, BOOL nMod ) const;\n void SetBaseURL( const String& rURL ) { aBaseURL = rURL; }\n const String& GetBaseURL() const { return aBaseURL; }\n void SetOpenHdl( const Link& rLink ) { aOpenHdl = rLink; }\n const Link& GetOpenHdl() const { return aOpenHdl; }\n void SetOnlyDirectories( BOOL bDir = TRUE );\n INetProtocol GetSmartProtocol() const { return eSmartProtocol; }\n void SetSmartProtocol( INetProtocol eProt );\n BOOL IsCtrlOpen()\n { return bCtrlClick; }\n String GetURL();\n void DisableHistory();\n};\n\n#if _SOLAR__PRIVATE\n\n#include \"tbxctrl.hxx\"\nclass SfxURLToolBoxControl_Impl : public SfxToolBoxControl\n{\nprivate:\n SfxStatusForwarder aURLForwarder;\n SfxURLBox* GetURLBox() const;\n DECL_LINK( OpenHdl, void* );\n DECL_LINK( SelectHdl, void* );\npublic:\n\n SFX_DECL_TOOLBOX_CONTROL();\n\n SfxURLToolBoxControl_Impl( USHORT nId,\n ToolBox& rBox,\n SfxBindings& rBindings );\n\n virtual Window* CreateItemWindow( Window* pParent );\n virtual void StateChanged( USHORT nSID, SfxItemState eState,\n const SfxPoolItem* pState );\n};\n\nclass SfxCancelToolBoxControl_Impl : public SfxToolBoxControl\n{\npublic:\n\n SFX_DECL_TOOLBOX_CONTROL();\n\n SfxCancelToolBoxControl_Impl(\n USHORT nId,\n ToolBox& rBox,\n SfxBindings& rBindings );\n\n virtual SfxPopupWindowType GetPopupWindowType() const;\n virtual SfxPopupWindow* CreatePopupWindow();\n virtual void StateChanged( USHORT nSID, SfxItemState eState,\n const SfxPoolItem* pState );\n};\n\n#endif\n\n#endif\n\n<commit_msg>TF_SVDATA<commit_after>\/*************************************************************************\n *\n * $RCSfile: inettbc.hxx,v $\n *\n * $Revision: 1.8 $\n *\n * last change: $Author: mba $ $Date: 2001-06-18 09:53:19 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef _SFX_INETTBC_HXX\n#define _SFX_INETTBC_HXX\n\n\/\/ includes *****************************************************************\n#include <tools\/string.hxx>\n#include <tools\/urlobj.hxx>\n\n#ifndef _COMBOBOX_HXX \/\/autogen\n#include <vcl\/combobox.hxx>\n#endif\n\n#define _SVSTDARR_STRINGSDTOR\n#include <svtools\/svstdarr.hxx>\n\nstruct SfxPickEntry_Impl;\nclass SfxURLBox : public ComboBox\n{\nfriend class SfxMatchContext_Impl;\nfriend class SfxURLBox_Impl;\n Link aOpenHdl;\n String aBaseURL;\n INetProtocol eSmartProtocol;\n SfxMatchContext_Impl* pCtx;\n SfxURLBox_Impl* pImp;\n BOOL bAutoCompleteMode;\n BOOL bOnlyDirectories;\n BOOL bModified;\n BOOL bTryAutoComplete: 1,\n bCtrlClick: 1,\n bHistoryDisabled : 1;\n\n BOOL ProcessKey( const KeyCode& rCode );\n void TryAutoComplete( BOOL bForward, BOOL bForce );\n void UpdatePicklistForSmartProtocol_Impl();\n DECL_LINK( AutoCompleteHdl_Impl, void* );\n\nprotected:\n virtual long Notify( NotifyEvent& rNEvt );\n virtual void Select();\n virtual void Modify();\n#ifndef TF_SVDATA\n virtual BOOL QueryDrop( DropEvent &rEvt );\n virtual BOOL Drop( const DropEvent &rEvt );\n#endif\n virtual long PreNotify( NotifyEvent& rNEvt );\n\npublic:\n SfxURLBox( Window* pParent, INetProtocol eSmart = INET_PROT_NOT_VALID );\n SfxURLBox( Window* pParent, const ResId& _rResId, INetProtocol eSmart = INET_PROT_NOT_VALID );\n ~SfxURLBox();\n\n void OpenURL( const String& rName, BOOL nMod ) const;\n void SetBaseURL( const String& rURL ) { aBaseURL = rURL; }\n const String& GetBaseURL() const { return aBaseURL; }\n void SetOpenHdl( const Link& rLink ) { aOpenHdl = rLink; }\n const Link& GetOpenHdl() const { return aOpenHdl; }\n void SetOnlyDirectories( BOOL bDir = TRUE );\n INetProtocol GetSmartProtocol() const { return eSmartProtocol; }\n void SetSmartProtocol( INetProtocol eProt );\n BOOL IsCtrlOpen()\n { return bCtrlClick; }\n String GetURL();\n void DisableHistory();\n};\n\n#if _SOLAR__PRIVATE\n\n#include \"tbxctrl.hxx\"\nclass SfxURLToolBoxControl_Impl : public SfxToolBoxControl\n{\nprivate:\n SfxStatusForwarder aURLForwarder;\n SfxURLBox* GetURLBox() const;\n DECL_LINK( OpenHdl, void* );\n DECL_LINK( SelectHdl, void* );\npublic:\n\n SFX_DECL_TOOLBOX_CONTROL();\n\n SfxURLToolBoxControl_Impl( USHORT nId,\n ToolBox& rBox,\n SfxBindings& rBindings );\n\n virtual Window* CreateItemWindow( Window* pParent );\n virtual void StateChanged( USHORT nSID, SfxItemState eState,\n const SfxPoolItem* pState );\n};\n\nclass SfxCancelToolBoxControl_Impl : public SfxToolBoxControl\n{\npublic:\n\n SFX_DECL_TOOLBOX_CONTROL();\n\n SfxCancelToolBoxControl_Impl(\n USHORT nId,\n ToolBox& rBox,\n SfxBindings& rBindings );\n\n virtual SfxPopupWindowType GetPopupWindowType() const;\n virtual SfxPopupWindow* CreatePopupWindow();\n virtual void StateChanged( USHORT nSID, SfxItemState eState,\n const SfxPoolItem* pState );\n};\n\n#endif\n\n#endif\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n Flexisip, a flexible SIP proxy server with media capabilities.\n Copyright (C) 2012 Belledonne Communications SARL.\n\n This program is free software: you can redistribute it and\/or modify\n it under the terms of the GNU Affero General Public License as\n published by the Free Software Foundation, either version 3 of the\n License, or (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU Affero General Public License for more details.\n\n You should have received a copy of the GNU Affero General Public License\n along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n\n#include \"forkmessagecontext.hh\"\n#include \"registrardb.hh\"\n#include \"common.hh\"\n#include <algorithm>\n#include <sofia-sip\/sip_status.h>\n#include <sofia-sip\/msg_types.h>\n#include \"xml\/fthttp.hxx\"\n\nusing namespace ::std;\nusing namespace fthttp;\n\nstatic bool needsDelivery(int code){\n\treturn code<200 || code==503 || code==408;\n}\n\nForkMessageContext::ForkMessageContext(Agent *agent, const std::shared_ptr<RequestSipEvent> &event, shared_ptr<ForkContextConfig> cfg, ForkContextListener* listener) :\n\t\tForkContext(agent, event,cfg,listener) {\n\tLOGD(\"New ForkMessageContext %p\", this);\n\tmAcceptanceTimer=NULL;\n\t\/\/start the acceptance timer immediately\n\tif (mCfg->mForkLate && mCfg->mDeliveryTimeout>30){\n\t\tmAcceptanceTimer=su_timer_create(su_root_task(mAgent->getRoot()), 0);\n\t\tsu_timer_set_interval(mAcceptanceTimer, &ForkMessageContext::sOnAcceptanceTimer, this, (su_duration_t)mCfg->mUrgentTimeout*1000);\n\t}\n\tmDeliveredCount=0;\n}\n\nForkMessageContext::~ForkMessageContext() {\n\tif (mAcceptanceTimer)\n\t\tsu_timer_destroy(mAcceptanceTimer);\n\tLOGD(\"Destroy ForkMessageContext %p\", this);\n}\n\nbool ForkMessageContext::shouldFinish() {\n\treturn false; \/\/the messaging fork context controls its termination.\n}\n\n\nvoid ForkMessageContext::checkFinished(){\n\tif (mIncoming==NULL && !mCfg->mForkLate){\n\t\tsetFinished();\n\t\treturn;\n\t}\n\t\n\tauto branches=getBranches();\n\tbool awaiting_responses=false;\n\t\n\tif (!mCfg->mForkLate){\n\t\tawaiting_responses=!allBranchesAnswered();\n\t}else{\n\t\tfor(auto it=branches.begin();it!=branches.end();++it){\n\t\t\tif (needsDelivery((*it)->getStatus())) {\n\t\t\t\tawaiting_responses=true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\tif (!awaiting_responses){\n\t\tshared_ptr<BranchInfo> br=findBestBranch(sUrgentCodes);\n\t\tif (br){\n\t\t\tforwardResponse(br);\n\t\t}\n\t\tsetFinished();\n\t}\n}\n\nvoid ForkMessageContext::logDeliveryEvent(const std::shared_ptr<BranchInfo> &br, const shared_ptr<ResponseSipEvent> &event){\n\tsip_t *sip = event->getMsgSip()->getSip();\n\tauto log=make_shared<MessageLog>(MessageLog::Delivery,sip->sip_from,sip->sip_to,sip->sip_call_id);\n\tlog->setDestination(br->mRequest->getMsgSip()->getSip()->sip_request->rq_url);\n\tlog->setStatusCode(sip->sip_status->st_status,sip->sip_status->st_phrase);\n\tlog->setCompleted();\n\tevent->setEventLog(log);\n\tevent->flushLog();\n}\n\nvoid ForkMessageContext::onResponse(const std::shared_ptr<BranchInfo> &br, const shared_ptr<ResponseSipEvent> &event) {\n\tsip_t *sip = event->getMsgSip()->getSip();\n\tint code=sip->sip_status->st_status;\n\tLOGD(\"ForkMessageContext::onResponse()\");\n\t\n\tif (code > 100 && code < 300) {\n\t\tif (code>=200){\n\t\t\tmDeliveredCount++;\n\t\t\tif (mAcceptanceTimer) {\n\t\t\t\tif (mIncoming) logReceptionEvent(event); \/*in the sender's log will appear the status code from the receiver*\/\n\t\t\t\tsu_timer_destroy(mAcceptanceTimer);\n\t\t\t\tmAcceptanceTimer=NULL;\n\t\t\t}\n\t\t}\n\t\tlogDeliveryEvent(br,event);\n\t\tforwardResponse(br);\n\t}else logDeliveryEvent(br,event);\n\tcheckFinished();\n}\n\nvoid ForkMessageContext::logReceptionEvent(const shared_ptr<ResponseSipEvent> &ev){\n\tsip_t *sip=ev->getMsgSip()->getSip();\n\tauto log=make_shared<MessageLog>(MessageLog::Reception,sip->sip_from,sip->sip_to,sip->sip_call_id);\n\tlog->setStatusCode(sip->sip_status->st_status,sip->sip_status->st_phrase);\n\tlog->setCompleted();\n\tev->setEventLog(log);\n\tev->flushLog();\n}\n\n\/*we are called here if no good response has been received from any branch, in fork-late mode only *\/\nvoid ForkMessageContext::acceptMessage(){\n\tif (mIncoming==NULL) return;\n\t\n\t\/*in fork late mode, never answer a service unavailable*\/\n\tshared_ptr<MsgSip> msgsip(mIncoming->createResponse(SIP_202_ACCEPTED));\n\tshared_ptr<ResponseSipEvent> ev(new ResponseSipEvent(dynamic_pointer_cast<OutgoingAgent>(mAgent->shared_from_this()), msgsip));\n\tforwardResponse(ev);\n\tlogReceptionEvent(ev); \/*in the sender's log will appear the 202 accepted from flexisip server*\/\n}\n\nvoid ForkMessageContext::onAcceptanceTimer(){\n\tLOGD(\"ForkMessageContext::onAcceptanceTimer()\");\n\tacceptMessage();\n\tsu_timer_destroy(mAcceptanceTimer);\n\tmAcceptanceTimer=NULL;\n}\n\nvoid ForkMessageContext::sOnAcceptanceTimer(su_root_magic_t* magic, su_timer_t* t, su_timer_arg_t* arg){\n\tstatic_cast<ForkMessageContext*>(arg)->onAcceptanceTimer();\n}\n\nbool isMessageARCSFileTransferMessage(shared_ptr<RequestSipEvent> &ev) {\n\tsip_t* sip = ev->getSip();\n\tif (strncasecmp(sip->sip_request->rq_method_name, \"MESSAGE\", strlen(sip->sip_request->rq_method_name)) == 0) {\n\t\tif (sip->sip_content_type->c_type && strcasecmp (sip->sip_content_type->c_type, \"application\/vnd.gsma.rcs-ft-http+xml\")==0) {\n\t\t\treturn true;\n\t\t}\n\t}\n\treturn false;\n}\n\nbool isConversionFromRcsToExternalBodyUrlNeeded(shared_ptr<ExtendedContact> &ec) {\n\tlist<string> acceptHeaders = ec->mAcceptHeader;\n\tif (acceptHeaders.size() == 0) {\n\t\treturn true;\n\t}\n\t\n\tfor (auto it = acceptHeaders.begin(); it != acceptHeaders.end(); ++it) {\n\t\tstring header = *it;\n\t\tif (header.compare(\"application\/vnd.gsma.rcs-ft-http+xml\") == 0) {\n\t\t\treturn false;\n\t\t}\n\t}\n\treturn true;\n}\n\nvoid ForkMessageContext::onNewBranch(const shared_ptr<BranchInfo> &br) {\n\tif (br->mUid.size()>0){\n\t\t\/*check for a branch already existing with this uid, and eventually clean it*\/\n\t\tshared_ptr<BranchInfo> tmp=findBranchByUid(br->mUid);\n\t\tif (tmp){\n\t\t\tremoveBranch(tmp);\n\t\t}\n\t} else SLOGE << \"No unique id found for contact\";\n\t\n\t\/\/ Convert a RCS file transfer message to an external body url message if contact doesn't support it\n\tshared_ptr<RequestSipEvent> &ev = br->mRequest;\n\tif (ev && isMessageARCSFileTransferMessage(ev)) {\n\t\tshared_ptr<ExtendedContact> &ec = br->mContact;\n\t\tif (ec && isConversionFromRcsToExternalBodyUrlNeeded(ec)) {\n\t\t\tsip_t *sip = ev->getSip();\n\t\t\tsip_payload_t *payload = sip->sip_payload;\n\t\t\t\n\t\t\tstd::unique_ptr<fthttp::File> file_transfer_infos = NULL;\n\t\t\tconst char *file_url;\n\t\t\t\n\t\t\ttry {\n\t\t\t\tistringstream data(payload->pl_data);\n\t\t\t\tfile_transfer_infos = parseFile(data, xml_schema::Flags::dont_validate);\n\t\t\t} catch (const xml_schema::Exception& e) {\n\t\t\t\tSLOGE << \"Can't parse the content of the message\";\n\t\t\t}\n\t\t\t\n\t\t\tif (file_transfer_infos != NULL) {\n\t\t\t\tFile::File_infoSequence &infos = file_transfer_infos->getFile_info();\n\t\t\t\tif (infos.size() >= 1) {\n\t\t\t\t\tfor (File::File_infoConstIterator i (infos.begin()); i != infos.end(); ++i) {\n\t\t\t\t\t\tconst File::File_infoType &info = (*i);\n\t\t\t\t\t\tconst File_info::DataType &data = info.getData();\n\t\t\t\t\t\tconst Data::UrlType &url = data.getUrl();\n\t\t\t\t\t\tfile_url = url.c_str();\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\tif (file_url) {\n\t\t\t\t\/\/TODO\n\t\t\t}\n\t\t}\n\t}\n}\n\nbool ForkMessageContext::onNewRegister(const url_t *dest, const string &uid){\n\tbool already_have_transaction=!ForkContext::onNewRegister(dest,uid);\n\tif (already_have_transaction) return false;\n\tif (uid.size()>0){\n\t\tshared_ptr<BranchInfo> br=findBranchByUid(uid);\n\t\tif (br==NULL){\n\t\t\t\/\/this is a new client instance or a client for which the message wasn't delivered yet. The message needs to be delivered.\n\t\t\tLOGD(\"ForkMessageContext::onNewRegister(): this is a new client instance.\");\n\t\t\treturn true;\n\t\t}else if (needsDelivery(br->getStatus())){\n\t\t\t\/\/this is a new client instance or a client for which the message wasn't delivered yet. The message needs to be delivered.\n\t\t\tLOGD(\"ForkMessageContext::onNewRegister(): this client is reconnecting but was not delivered before.\");\n\t\t\treturn true;\n\t\t}\n\t}\n\t\/\/in all other case we can accept a new transaction only if the message hasn't been delivered already.\n\tLOGD(\"Message has been delivered %i times.\",mDeliveredCount);\n\treturn mDeliveredCount==0;\n}\n\n<commit_msg>Fix crash when parser is destroyed<commit_after>\/*\n Flexisip, a flexible SIP proxy server with media capabilities.\n Copyright (C) 2012 Belledonne Communications SARL.\n\n This program is free software: you can redistribute it and\/or modify\n it under the terms of the GNU Affero General Public License as\n published by the Free Software Foundation, either version 3 of the\n License, or (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU Affero General Public License for more details.\n\n You should have received a copy of the GNU Affero General Public License\n along with this program. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\/\n\n#include \"forkmessagecontext.hh\"\n#include \"registrardb.hh\"\n#include \"common.hh\"\n#include <algorithm>\n#include <sofia-sip\/sip_status.h>\n#include <sofia-sip\/msg_types.h>\n#include \"xml\/fthttp.hxx\"\n#include <xercesc\/util\/PlatformUtils.hpp>\n\nusing namespace ::std;\nusing namespace fthttp;\n\nstatic bool needsDelivery(int code){\n\treturn code<200 || code==503 || code==408;\n}\n\nForkMessageContext::ForkMessageContext(Agent *agent, const std::shared_ptr<RequestSipEvent> &event, shared_ptr<ForkContextConfig> cfg, ForkContextListener* listener) :\n\t\tForkContext(agent, event,cfg,listener) {\n\tLOGD(\"New ForkMessageContext %p\", this);\n\tmAcceptanceTimer=NULL;\n\t\/\/start the acceptance timer immediately\n\tif (mCfg->mForkLate && mCfg->mDeliveryTimeout>30){\n\t\tmAcceptanceTimer=su_timer_create(su_root_task(mAgent->getRoot()), 0);\n\t\tsu_timer_set_interval(mAcceptanceTimer, &ForkMessageContext::sOnAcceptanceTimer, this, (su_duration_t)mCfg->mUrgentTimeout*1000);\n\t}\n\tmDeliveredCount=0;\n}\n\nForkMessageContext::~ForkMessageContext() {\n\tif (mAcceptanceTimer)\n\t\tsu_timer_destroy(mAcceptanceTimer);\n\tLOGD(\"Destroy ForkMessageContext %p\", this);\n}\n\nbool ForkMessageContext::shouldFinish() {\n\treturn false; \/\/the messaging fork context controls its termination.\n}\n\n\nvoid ForkMessageContext::checkFinished(){\n\tif (mIncoming==NULL && !mCfg->mForkLate){\n\t\tsetFinished();\n\t\treturn;\n\t}\n\t\n\tauto branches=getBranches();\n\tbool awaiting_responses=false;\n\t\n\tif (!mCfg->mForkLate){\n\t\tawaiting_responses=!allBranchesAnswered();\n\t}else{\n\t\tfor(auto it=branches.begin();it!=branches.end();++it){\n\t\t\tif (needsDelivery((*it)->getStatus())) {\n\t\t\t\tawaiting_responses=true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\tif (!awaiting_responses){\n\t\tshared_ptr<BranchInfo> br=findBestBranch(sUrgentCodes);\n\t\tif (br){\n\t\t\tforwardResponse(br);\n\t\t}\n\t\tsetFinished();\n\t}\n}\n\nvoid ForkMessageContext::logDeliveryEvent(const std::shared_ptr<BranchInfo> &br, const shared_ptr<ResponseSipEvent> &event){\n\tsip_t *sip = event->getMsgSip()->getSip();\n\tauto log=make_shared<MessageLog>(MessageLog::Delivery,sip->sip_from,sip->sip_to,sip->sip_call_id);\n\tlog->setDestination(br->mRequest->getMsgSip()->getSip()->sip_request->rq_url);\n\tlog->setStatusCode(sip->sip_status->st_status,sip->sip_status->st_phrase);\n\tlog->setCompleted();\n\tevent->setEventLog(log);\n\tevent->flushLog();\n}\n\nvoid ForkMessageContext::onResponse(const std::shared_ptr<BranchInfo> &br, const shared_ptr<ResponseSipEvent> &event) {\n\tsip_t *sip = event->getMsgSip()->getSip();\n\tint code=sip->sip_status->st_status;\n\tLOGD(\"ForkMessageContext::onResponse()\");\n\t\n\tif (code > 100 && code < 300) {\n\t\tif (code>=200){\n\t\t\tmDeliveredCount++;\n\t\t\tif (mAcceptanceTimer) {\n\t\t\t\tif (mIncoming) logReceptionEvent(event); \/*in the sender's log will appear the status code from the receiver*\/\n\t\t\t\tsu_timer_destroy(mAcceptanceTimer);\n\t\t\t\tmAcceptanceTimer=NULL;\n\t\t\t}\n\t\t}\n\t\tlogDeliveryEvent(br,event);\n\t\tforwardResponse(br);\n\t}else logDeliveryEvent(br,event);\n\tcheckFinished();\n}\n\nvoid ForkMessageContext::logReceptionEvent(const shared_ptr<ResponseSipEvent> &ev){\n\tsip_t *sip=ev->getMsgSip()->getSip();\n\tauto log=make_shared<MessageLog>(MessageLog::Reception,sip->sip_from,sip->sip_to,sip->sip_call_id);\n\tlog->setStatusCode(sip->sip_status->st_status,sip->sip_status->st_phrase);\n\tlog->setCompleted();\n\tev->setEventLog(log);\n\tev->flushLog();\n}\n\n\/*we are called here if no good response has been received from any branch, in fork-late mode only *\/\nvoid ForkMessageContext::acceptMessage(){\n\tif (mIncoming==NULL) return;\n\t\n\t\/*in fork late mode, never answer a service unavailable*\/\n\tshared_ptr<MsgSip> msgsip(mIncoming->createResponse(SIP_202_ACCEPTED));\n\tshared_ptr<ResponseSipEvent> ev(new ResponseSipEvent(dynamic_pointer_cast<OutgoingAgent>(mAgent->shared_from_this()), msgsip));\n\tforwardResponse(ev);\n\tlogReceptionEvent(ev); \/*in the sender's log will appear the 202 accepted from flexisip server*\/\n}\n\nvoid ForkMessageContext::onAcceptanceTimer(){\n\tLOGD(\"ForkMessageContext::onAcceptanceTimer()\");\n\tacceptMessage();\n\tsu_timer_destroy(mAcceptanceTimer);\n\tmAcceptanceTimer=NULL;\n}\n\nvoid ForkMessageContext::sOnAcceptanceTimer(su_root_magic_t* magic, su_timer_t* t, su_timer_arg_t* arg){\n\tstatic_cast<ForkMessageContext*>(arg)->onAcceptanceTimer();\n}\n\nbool isMessageARCSFileTransferMessage(shared_ptr<RequestSipEvent> &ev) {\n\tsip_t* sip = ev->getSip();\n\tif (strncasecmp(sip->sip_request->rq_method_name, \"MESSAGE\", strlen(sip->sip_request->rq_method_name)) == 0) {\n\t\tif (sip->sip_content_type->c_type && strcasecmp (sip->sip_content_type->c_type, \"application\/vnd.gsma.rcs-ft-http+xml\")==0) {\n\t\t\treturn true;\n\t\t}\n\t}\n\treturn false;\n}\n\nbool isConversionFromRcsToExternalBodyUrlNeeded(shared_ptr<ExtendedContact> &ec) {\n\tlist<string> acceptHeaders = ec->mAcceptHeader;\n\tif (acceptHeaders.size() == 0) {\n\t\treturn true;\n\t}\n\t\n\tfor (auto it = acceptHeaders.begin(); it != acceptHeaders.end(); ++it) {\n\t\tstring header = *it;\n\t\tif (header.compare(\"application\/vnd.gsma.rcs-ft-http+xml\") == 0) {\n\t\t\treturn false;\n\t\t}\n\t}\n\treturn true;\n}\n\nvoid ForkMessageContext::onNewBranch(const shared_ptr<BranchInfo> &br) {\n\tif (br->mUid.size()>0){\n\t\t\/*check for a branch already existing with this uid, and eventually clean it*\/\n\t\tshared_ptr<BranchInfo> tmp=findBranchByUid(br->mUid);\n\t\tif (tmp){\n\t\t\tremoveBranch(tmp);\n\t\t}\n\t} else SLOGE << \"No unique id found for contact\";\n\t\n\t\/\/ Convert a RCS file transfer message to an external body url message if contact doesn't support it\n\tshared_ptr<RequestSipEvent> &ev = br->mRequest;\n\tif (ev && isMessageARCSFileTransferMessage(ev)) {\n\t\tshared_ptr<ExtendedContact> &ec = br->mContact;\n\t\txercesc::XMLPlatformUtils::Initialize();\n\t\tif (ec && isConversionFromRcsToExternalBodyUrlNeeded(ec)) {\n\t\t\tsip_t *sip = ev->getSip();\n\t\t\tsip_payload_t *payload = sip->sip_payload;\n\t\t\t\n\t\t\tstd::unique_ptr<fthttp::File> file_transfer_infos = NULL;\n\t\t\tconst char *file_url;\n\t\t\t\n\t\t\ttry {\n\t\t\t\tistringstream data(payload->pl_data);\n\t\t\t\tfile_transfer_infos = parseFile(data, xml_schema::Flags::dont_validate);\n\t\t\t} catch (const xml_schema::Exception& e) {\n\t\t\t\tSLOGE << \"Can't parse the content of the message\";\n\t\t\t}\n\t\t\t\n\t\t\tif (file_transfer_infos != NULL) {\n\t\t\t\tFile::File_infoSequence &infos = file_transfer_infos->getFile_info();\n\t\t\t\tif (infos.size() >= 1) {\n\t\t\t\t\tfor (File::File_infoConstIterator i (infos.begin()); i != infos.end(); ++i) {\n\t\t\t\t\t\tconst File::File_infoType &info = (*i);\n\t\t\t\t\t\tconst File_info::DataType &data = info.getData();\n\t\t\t\t\t\tconst Data::UrlType &url = data.getUrl();\n\t\t\t\t\t\tfile_url = url.c_str();\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\tif (file_url) {\n\t\t\t\t\/\/TODO\n\t\t\t}\n\t\t}\n\t\txercesc::XMLPlatformUtils::Terminate();\n\t}\n}\n\nbool ForkMessageContext::onNewRegister(const url_t *dest, const string &uid){\n\tbool already_have_transaction=!ForkContext::onNewRegister(dest,uid);\n\tif (already_have_transaction) return false;\n\tif (uid.size()>0){\n\t\tshared_ptr<BranchInfo> br=findBranchByUid(uid);\n\t\tif (br==NULL){\n\t\t\t\/\/this is a new client instance or a client for which the message wasn't delivered yet. The message needs to be delivered.\n\t\t\tLOGD(\"ForkMessageContext::onNewRegister(): this is a new client instance.\");\n\t\t\treturn true;\n\t\t}else if (needsDelivery(br->getStatus())){\n\t\t\t\/\/this is a new client instance or a client for which the message wasn't delivered yet. The message needs to be delivered.\n\t\t\tLOGD(\"ForkMessageContext::onNewRegister(): this client is reconnecting but was not delivered before.\");\n\t\t\treturn true;\n\t\t}\n\t}\n\t\/\/in all other case we can accept a new transaction only if the message hasn't been delivered already.\n\tLOGD(\"Message has been delivered %i times.\",mDeliveredCount);\n\treturn mDeliveredCount==0;\n}\n\n<|endoftext|>"} {"text":"<commit_before>#include \"joystick.hpp\"\n\nJoystick::Joystick() {\n\tSDL_Init(SDL_INIT_JOYSTICK);\n\tint num_joysticks = SDL_NumJoysticks();\n\n\t\/\/ take first device that appears to be a joystick\n\t\/\/ and no strange vbox device for example...\n\t\/\/ ...which means more than 2 axes\n\tfor (int i = 0; i < num_joysticks; i++) {\n\t\tSDL_Joystick *tmpStick = SDL_JoystickOpen(i);\n\t\tif (SDL_JoystickNumAxes(tmpStick) > 2) {\n\t\t\tm_joystick = tmpStick;\n\t\t\tm_name = SDL_JoystickName(i);\n\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tSDL_JoystickEventState(SDL_ENABLE);\n\tSDL_JoystickEventState(SDL_QUERY);\n}\n\nJoystick::~Joystick() {\n\n}\n\nstd::string Joystick::getName() {\n\treturn m_name;\n}\n\nJoystickEvent Joystick::getEvent() {\n\tSDL_Event event;\n\tstd::vector<bool> buttons;\n\tstd::vector<short> axis;\n\n\tSDL_JoystickUpdate();\n\t\n\t\/\/ get keys\n\tfor (int i = 0; i < SDL_JoystickNumButtons(m_joystick); i++) {\n\t\tunsigned int n = SDL_JoystickGetButton(m_joystick, i);\n\t\tbuttons.push_back((n == 1) ? true : false);\n\t}\n\t\n\t\/\/ get axis\n\tfor (int i = 0; i < SDL_JoystickNumAxes(m_joystick); i++) {\n\t\tsigned short a = SDL_JoystickGetAxis (m_joystick, i);\n\t\taxis.push_back(a);\n\t}\n\n\treturn JoystickEvent(buttons, axis);\n}\n<commit_msg>Quit a little more gracefully if no joysticks were found<commit_after>#include \"joystick.hpp\"\n#include <stdexcept>\n\nJoystick::Joystick() {\n\tSDL_Init(SDL_INIT_JOYSTICK);\n\tint num_joysticks = SDL_NumJoysticks();\n\tif (num_joysticks < 1) {\n\t\tthrow std::runtime_error(\"No joysticks found!\");\n\t}\n\n\t\/\/ take first device that appears to be a joystick\n\t\/\/ and no strange vbox device for example...\n\t\/\/ ...which means more than 2 axes\n\tfor (int i = 0; i < num_joysticks; i++) {\n\t\tSDL_Joystick *tmpStick = SDL_JoystickOpen(i);\n\t\tif (SDL_JoystickNumAxes(tmpStick) > 2) {\n\t\t\tm_joystick = tmpStick;\n\t\t\tm_name = SDL_JoystickName(i);\n\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tSDL_JoystickEventState(SDL_ENABLE);\n\tSDL_JoystickEventState(SDL_QUERY);\n}\n\nJoystick::~Joystick() {\n\n}\n\nstd::string Joystick::getName() {\n\treturn m_name;\n}\n\nJoystickEvent Joystick::getEvent() {\n\tSDL_Event event;\n\tstd::vector<bool> buttons;\n\tstd::vector<short> axis;\n\n\tSDL_JoystickUpdate();\n\t\n\t\/\/ get keys\n\tfor (int i = 0; i < SDL_JoystickNumButtons(m_joystick); i++) {\n\t\tunsigned int n = SDL_JoystickGetButton(m_joystick, i);\n\t\tbuttons.push_back((n == 1) ? true : false);\n\t}\n\t\n\t\/\/ get axis\n\tfor (int i = 0; i < SDL_JoystickNumAxes(m_joystick); i++) {\n\t\tsigned short a = SDL_JoystickGetAxis (m_joystick, i);\n\t\taxis.push_back(a);\n\t}\n\n\treturn JoystickEvent(buttons, axis);\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"tileset.hpp\"\n#include \"client\/opengl.hpp\"\n#include \"client\/texturefile.hpp\"\n#include <stdlib.h>\nusing namespace LD22;\n\nTileset::Tileset()\n{\n m_tile = TextureFile::open(\"sprite\/tile.png\");\n m_stick = TextureFile::open(\"sprite\/stick.png\");\n m_widget = TextureFile::open(\"sprite\/widget.png\");\n}\n\nTileset::~Tileset()\n{ }\n\nvoid Tileset::drawTiles(const unsigned char t[TILE_HEIGHT][TILE_WIDTH],\n int delta) const\n{\n (void) delta;\n\n glPushMatrix();\n glScalef(32.0f, 32.0f, 1.0f);\n glEnable(GL_TEXTURE_2D);\n glEnable(GL_BLEND);\n glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);\n m_tile->bind();\n glBegin(GL_QUADS);\n for (int y = 0; y < TILE_HEIGHT; ++y) {\n for (int x = 0; x < TILE_WIDTH; ++x) {\n int i = t[y][x];\n if (!i)\n continue;\n int u = (i - 1) & 3, v = ((i - 1) >> 2) & 3;\n float u0 = u * 0.25f, u1 = u0 + 0.25f;\n float v1 = v * 0.25f, v0 = v1 - 0.25f;\n glTexCoord2f(u0, v0); glVertex2f(x, y);\n glTexCoord2f(u0, v1); glVertex2f(x, y + 1);\n glTexCoord2f(u1, v1); glVertex2f(x + 1, y + 1);\n glTexCoord2f(u1, v0); glVertex2f(x + 1, y);\n }\n }\n glEnd();\n glPopMatrix();\n glDisable(GL_BLEND);\n glDisable(GL_TEXTURE_2D);\n}\n\nvoid Tileset::drawStick(int x, int y, int frame)\n{\n int u = frame & 7, v = (frame \/ 8) & 3;\n bool flip = frame & 0x80;\n float x0 = x + STICK_WIDTH\/2 - 32, x1 = x0 + 64;\n float y0 = y + STICK_WIDTH\/2 - 32, y1 = y0 + 64;\n float u0 = u * 0.125f, u1 = u0 + 0.125f;\n float v1 = v * 0.25f, v0 = v1 + 0.25f;\n if (flip) {\n float t;\n t = u0;\n u0 = u1;\n u1 = t;\n }\n glEnable(GL_TEXTURE_2D);\n glEnable(GL_BLEND);\n glBlendFunc(GL_DST_COLOR, GL_ZERO);\n m_stick->bind();\n glBegin(GL_QUADS);\n glTexCoord2f(u0, v0); glVertex2f(x0, y0);\n glTexCoord2f(u0, v1); glVertex2f(x0, y1);\n glTexCoord2f(u1, v1); glVertex2f(x1, y1);\n glTexCoord2f(u1, v0); glVertex2f(x1, y0);\n glEnd();\n glDisable(GL_BLEND);\n glDisable(GL_TEXTURE_2D);\n}\n\nstatic const signed char WIDGET_INFO[Widget::MAX_WIDGET + 1][4] = {\n { 2, 2, -2, -2 },\n { 0, 2, 2, -2 },\n { 2, 2, 2, -2 },\n { 4, 2, -2, -2 },\n { 0, 3, 1, -1 },\n { 1, 3, 1, -1 },\n { 2, 3, 1, -1 },\n { 2, 4, 1, -1 },\n { 3, 4, 1, -2 }\n};\n\nvoid Tileset::drawWidget(int x, int y, int which)\n{\n if (which < 0 || which > Widget::MAX_WIDGET)\n return;\n const signed char *ifo = WIDGET_INFO[which];\n float x0 = x, x1 = x0 + 64 * abs(ifo[2]);\n float y0 = y, y1 = y0 + 64 * abs(ifo[3]);\n float u0 = 0.25f * ifo[0], u1 = u0 + 0.25f * ifo[2];\n float v0 = 0.25f * ifo[1], v1 = v0 + 0.25f * ifo[3];\n glEnable(GL_TEXTURE_2D);\n glEnable(GL_BLEND);\n glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);\n m_widget->bind();\n glBegin(GL_QUADS);\n glTexCoord2f(u0, v0); glVertex2f(x0, y0);\n glTexCoord2f(u0, v1); glVertex2f(x0, y1);\n glTexCoord2f(u1, v1); glVertex2f(x1, y1);\n glTexCoord2f(u1, v0); glVertex2f(x1, y0);\n glEnd();\n glDisable(GL_BLEND);\n glDisable(GL_TEXTURE_2D);\n}\n<commit_msg>Fix stick drawing in Tileset code<commit_after>#include \"tileset.hpp\"\n#include \"client\/opengl.hpp\"\n#include \"client\/texturefile.hpp\"\n#include <stdlib.h>\nusing namespace LD22;\n\nTileset::Tileset()\n{\n m_tile = TextureFile::open(\"sprite\/tile.png\");\n m_stick = TextureFile::open(\"sprite\/stick.png\");\n m_widget = TextureFile::open(\"sprite\/widget.png\");\n}\n\nTileset::~Tileset()\n{ }\n\nvoid Tileset::drawTiles(const unsigned char t[TILE_HEIGHT][TILE_WIDTH],\n int delta) const\n{\n (void) delta;\n\n glPushMatrix();\n glScalef(32.0f, 32.0f, 1.0f);\n glEnable(GL_TEXTURE_2D);\n glEnable(GL_BLEND);\n glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);\n m_tile->bind();\n glBegin(GL_QUADS);\n for (int y = 0; y < TILE_HEIGHT; ++y) {\n for (int x = 0; x < TILE_WIDTH; ++x) {\n int i = t[y][x];\n if (!i)\n continue;\n int u = (i - 1) & 3, v = ((i - 1) >> 2) & 3;\n float u0 = u * 0.25f, u1 = u0 + 0.25f;\n float v1 = v * 0.25f, v0 = v1 - 0.25f;\n glTexCoord2f(u0, v0); glVertex2f(x, y);\n glTexCoord2f(u0, v1); glVertex2f(x, y + 1);\n glTexCoord2f(u1, v1); glVertex2f(x + 1, y + 1);\n glTexCoord2f(u1, v0); glVertex2f(x + 1, y);\n }\n }\n glEnd();\n glPopMatrix();\n glDisable(GL_BLEND);\n glDisable(GL_TEXTURE_2D);\n}\n\nvoid Tileset::drawStick(int x, int y, int frame)\n{\n int u = frame & 7, v = (frame \/ 8) & 3;\n bool flip = frame & 0x80;\n float x0 = x + STICK_WIDTH\/2 - 32, x1 = x0 + 64;\n float y0 = y + STICK_HEIGHT\/2 - 32, y1 = y0 + 64;\n float u0 = u * 0.125f, u1 = u0 + 0.125f;\n float v1 = v * 0.25f, v0 = v1 + 0.25f;\n if (flip) {\n float t;\n t = u0;\n u0 = u1;\n u1 = t;\n }\n glEnable(GL_TEXTURE_2D);\n glEnable(GL_BLEND);\n glBlendFunc(GL_DST_COLOR, GL_ZERO);\n m_stick->bind();\n glBegin(GL_QUADS);\n glTexCoord2f(u0, v0); glVertex2f(x0, y0);\n glTexCoord2f(u0, v1); glVertex2f(x0, y1);\n glTexCoord2f(u1, v1); glVertex2f(x1, y1);\n glTexCoord2f(u1, v0); glVertex2f(x1, y0);\n glEnd();\n glDisable(GL_BLEND);\n glDisable(GL_TEXTURE_2D);\n}\n\nstatic const signed char WIDGET_INFO[Widget::MAX_WIDGET + 1][4] = {\n { 2, 2, -2, -2 },\n { 0, 2, 2, -2 },\n { 2, 2, 2, -2 },\n { 4, 2, -2, -2 },\n { 0, 3, 1, -1 },\n { 1, 3, 1, -1 },\n { 2, 3, 1, -1 },\n { 2, 4, 1, -1 },\n { 3, 4, 1, -2 }\n};\n\nvoid Tileset::drawWidget(int x, int y, int which)\n{\n if (which < 0 || which > Widget::MAX_WIDGET)\n return;\n const signed char *ifo = WIDGET_INFO[which];\n float x0 = x, x1 = x0 + 64 * abs(ifo[2]);\n float y0 = y, y1 = y0 + 64 * abs(ifo[3]);\n float u0 = 0.25f * ifo[0], u1 = u0 + 0.25f * ifo[2];\n float v0 = 0.25f * ifo[1], v1 = v0 + 0.25f * ifo[3];\n glEnable(GL_TEXTURE_2D);\n glEnable(GL_BLEND);\n glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);\n m_widget->bind();\n glBegin(GL_QUADS);\n glTexCoord2f(u0, v0); glVertex2f(x0, y0);\n glTexCoord2f(u0, v1); glVertex2f(x0, y1);\n glTexCoord2f(u1, v1); glVertex2f(x1, y1);\n glTexCoord2f(u1, v0); glVertex2f(x1, y0);\n glEnd();\n glDisable(GL_BLEND);\n glDisable(GL_TEXTURE_2D);\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"..\/core\/cpu.h\"\n#include \"..\/core\/mmu.h\"\n#include \"..\/core\/gpu.h\"\n#include \"..\/video\/sdl_renderer.h\"\n\n#include <iostream>\n#include <fstream>\n#include <string>\n#include <ctime>\n#include <chrono>\n#include <thread>\n\n#include <SDL2\/SDL.h>\n\nconst int MILLIS_PER_FRAME = 1000 \/ 60;\n\nint main(int argc, char* argv[]) {\n if (argc != 3) {\n std::cout << \"Invalid arguments.\" << std::endl;\n exit(0);\n }\n\n std::string bios = argv[1];\n std::string rom = argv[2];\n\n SDLRenderer rend;\n SDL_Event event;\n\n GPU gpu(rend);\n MMU mmu(gpu, bios, rom);\n CPU cpu(mmu);\n\n time_t start_time = time(0);\n unsigned frames = 0;\n bool run = true;\n while (run) {\n int frame_cycles = 0;\n time_t frame_start_time = time(0);\n while (frame_cycles <= GPU::CYCLES_PER_FRAME) {\n int cycles = cpu.execute();\n gpu.step(cycles);\n frame_cycles += cycles;\n }\n\n ++frames;\n\n double frame_time = difftime(time(0), frame_start_time) * 1000;\n if (frame_time < MILLIS_PER_FRAME) {\n int time_to_sleep = static_cast<int>(MILLIS_PER_FRAME - frame_time);\n std::this_thread::sleep_for(std::chrono::milliseconds(time_to_sleep));\n }\n\n if (difftime(time(0), start_time) >= 1) {\n start_time = time(0);\n std::cout << std::dec << frames << std::endl;\n frames = 0;\n }\n\n while (SDL_PollEvent(&event)) {\n if (event.type == SDL_QUIT) {\n run = false;\n }\n }\n }\n\n SDL_Quit();\n}\n\n<commit_msg>Improve FPS limiter<commit_after>#include \"..\/core\/cpu.h\"\n#include \"..\/core\/mmu.h\"\n#include \"..\/core\/gpu.h\"\n#include \"..\/video\/sdl_renderer.h\"\n\n#include <iostream>\n#include <fstream>\n#include <string>\n#include <ctime>\n#include <chrono>\n#include <thread>\n\n#include <SDL2\/SDL.h>\n\nconst double MILLIS_PER_FRAME = 1000 \/ 60;\n\nint main(int argc, char* argv[]) {\n using namespace std::chrono;\n\n if (argc != 3) {\n std::cout << \"Invalid arguments.\" << std::endl;\n exit(0);\n }\n\n std::string bios = argv[1];\n std::string rom = argv[2];\n\n SDLRenderer rend;\n SDL_Event event;\n\n GPU gpu(rend);\n MMU mmu(gpu, bios, rom);\n CPU cpu(mmu);\n\n high_resolution_clock clock;\n auto start_time = clock.now();\n\n unsigned frames = 0;\n bool run = true;\n while (run) {\n int frame_cycles = 0;\n auto frame_start_time = clock.now();\n while (frame_cycles <= GPU::CYCLES_PER_FRAME) {\n int cycles = cpu.execute();\n gpu.step(cycles);\n frame_cycles += cycles;\n }\n\n ++frames;\n\n if (duration_cast<milliseconds>(clock.now() - start_time).count() >= 1000) {\n start_time = clock.now();\n std::cout << std::dec << frames << std::endl;\n frames = 0;\n }\n\n while (SDL_PollEvent(&event)) {\n if (event.type == SDL_QUIT) {\n run = false;\n }\n }\n\n auto frame_time = duration_cast<milliseconds>(clock.now() - frame_start_time);\n\n if (frame_time.count() < MILLIS_PER_FRAME) {\n int time_to_sleep = MILLIS_PER_FRAME - frame_time.count();\n std::this_thread::sleep_for(milliseconds(time_to_sleep));\n }\n } \n\n SDL_Quit();\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: AccessibleTableBase.hxx,v $\n *\n * $Revision: 1.19 $\n *\n * last change: $Author: vg $ $Date: 2003-05-22 13:48:07 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n\n#ifndef _SC_ACCESSIBLETABLEBASE_HXX\n#define _SC_ACCESSIBLETABLEBASE_HXX\n\n#ifndef _SC_ACCESSIBLECONTEXTBASE_HXX\n#include \"AccessibleContextBase.hxx\"\n#endif\n#ifndef SC_SCGLOB_HXX\n#include \"global.hxx\"\n#endif\n\n#ifndef _COM_SUN_STAR_ACCESSIBILITY_XACCESSIBLETABLE_HPP_\n#include <com\/sun\/star\/accessibility\/XAccessibleTable.hpp>\n#endif\n#ifndef _COM_SUN_STAR_ACCESSIBILITY_XACCESSIBLESELECTION_HPP_\n#include <com\/sun\/star\/accessibility\/XAccessibleSelection.hpp>\n#endif\n\n#ifndef _CPPUHELPER_IMPLBASE2_HXX_\n#include <cppuhelper\/implbase2.hxx>\n#endif\n\nclass ScTabViewShell;\n\n\/** @descr\n This base class provides an implementation of the\n <code>AccessibleTable<\/code> service.\n*\/\n\ntypedef cppu::ImplHelper2< ::com::sun::star::accessibility::XAccessibleTable,\n ::com::sun::star::accessibility::XAccessibleSelection>\n ScAccessibleTableBaseImpl;\n\nclass ScAccessibleTableBase :\n public ScAccessibleContextBase,\n public ScAccessibleTableBaseImpl\n{\npublic:\n \/\/===== internal ========================================================\n ScAccessibleTableBase(\n const ::com::sun::star::uno::Reference<\n ::com::sun::star::accessibility::XAccessible>& rxParent,\n ScDocument* pDoc,\n const ScRange& rRange);\nprotected:\n virtual ~ScAccessibleTableBase();\npublic:\n\n virtual void SAL_CALL disposing();\n\n \/\/\/===== XInterface =====================================================\n\n virtual ::com::sun::star::uno::Any SAL_CALL queryInterface(\n ::com::sun::star::uno::Type const & rType )\n throw (::com::sun::star::uno::RuntimeException);\n\n virtual void SAL_CALL acquire() throw ();\n\n virtual void SAL_CALL release() throw ();\n\n \/\/\/===== XAccessibleTable ================================================\n\n \/\/\/ Returns the number of rows in the table.\n virtual sal_Int32 SAL_CALL\n getAccessibleRowCount( )\n throw (::com::sun::star::uno::RuntimeException);\n\n \/\/\/ Returns the number of columns in the table.\n virtual sal_Int32 SAL_CALL\n getAccessibleColumnCount( )\n throw (::com::sun::star::uno::RuntimeException);\n\n \/\/\/ Returns the description of the specified row in the table.\n virtual ::rtl::OUString SAL_CALL\n getAccessibleRowDescription( sal_Int32 nRow )\n throw (::com::sun::star::uno::RuntimeException,\n ::com::sun::star::lang::IndexOutOfBoundsException);\n\n \/\/\/ Returns the description text of the specified column in the table.\n virtual ::rtl::OUString SAL_CALL\n getAccessibleColumnDescription( sal_Int32 nColumn )\n throw (::com::sun::star::uno::RuntimeException,\n ::com::sun::star::lang::IndexOutOfBoundsException);\n\n \/** Returns the number of rows occupied by the Accessible at a specified row and column in the table.\n Returns 1 if it is only a cell and the number of rows the cell is merged if the cell is a merged cell.\n *\/\n virtual sal_Int32 SAL_CALL\n getAccessibleRowExtentAt( sal_Int32 nRow, sal_Int32 nColumn )\n throw (::com::sun::star::uno::RuntimeException,\n ::com::sun::star::lang::IndexOutOfBoundsException);\n\n \/** Returns the number of columns occupied by the Accessible at a specified row and column in the table.\n Returns 1 if it is only a cell and the number of columns the cell is merged if the cell is a merged cell.\n *\/\n virtual sal_Int32 SAL_CALL\n getAccessibleColumnExtentAt( sal_Int32 nRow, sal_Int32 nColumn )\n throw (::com::sun::star::uno::RuntimeException,\n ::com::sun::star::lang::IndexOutOfBoundsException);\n\n \/\/\/ Returns the row headers as an AccessibleTable.\n virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessibleTable > SAL_CALL\n getAccessibleRowHeaders( )\n throw (::com::sun::star::uno::RuntimeException);\n\n \/\/\/ Returns the column headers as an AccessibleTable.\n virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessibleTable > SAL_CALL\n getAccessibleColumnHeaders( )\n throw (::com::sun::star::uno::RuntimeException);\n\n \/\/\/ Returns the selected rows in a table.\n virtual ::com::sun::star::uno::Sequence< sal_Int32 > SAL_CALL\n getSelectedAccessibleRows( )\n throw (::com::sun::star::uno::RuntimeException);\n\n \/\/\/ Returns the selected columns in a table.\n virtual ::com::sun::star::uno::Sequence< sal_Int32 > SAL_CALL\n getSelectedAccessibleColumns( )\n throw (::com::sun::star::uno::RuntimeException);\n\n \/\/\/ Returns a boolean value indicating whether the specified row is selected.\n virtual sal_Bool SAL_CALL\n isAccessibleRowSelected( sal_Int32 nRow )\n throw (::com::sun::star::uno::RuntimeException,\n ::com::sun::star::lang::IndexOutOfBoundsException);\n\n \/\/\/ Returns a boolean value indicating whether the specified column is selected.\n virtual sal_Bool SAL_CALL\n isAccessibleColumnSelected( sal_Int32 nColumn )\n throw (::com::sun::star::uno::RuntimeException,\n ::com::sun::star::lang::IndexOutOfBoundsException);\n\n \/\/\/ Returns the Accessible at a specified row and column in the table.\n virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible > SAL_CALL\n getAccessibleCellAt( sal_Int32 nRow, sal_Int32 nColumn )\n throw (::com::sun::star::uno::RuntimeException,\n ::com::sun::star::lang::IndexOutOfBoundsException);\n\n \/\/\/ Returns the caption for the table.\n virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible > SAL_CALL\n getAccessibleCaption( )\n throw (::com::sun::star::uno::RuntimeException);\n\n \/\/\/ Returns the summary description of the table.\n virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible > SAL_CALL\n getAccessibleSummary( )\n throw (::com::sun::star::uno::RuntimeException);\n\n \/\/\/ Returns a boolean value indicating whether the accessible at a specified row and column is selected.\n virtual sal_Bool SAL_CALL\n isAccessibleSelected( sal_Int32 nRow, sal_Int32 nColumn )\n throw (::com::sun::star::uno::RuntimeException,\n ::com::sun::star::lang::IndexOutOfBoundsException);\n\n \/\/\/===== XAccessibleExtendedTable ========================================\n\n \/\/\/ Returns the index of the cell on the given position.\n virtual sal_Int32 SAL_CALL\n getAccessibleIndex( sal_Int32 nRow, sal_Int32 nColumn )\n throw (::com::sun::star::uno::RuntimeException,\n ::com::sun::star::lang::IndexOutOfBoundsException);\n\n \/\/\/ Returns the row number of an index in the table.\n virtual sal_Int32 SAL_CALL\n getAccessibleRow( sal_Int32 nChildIndex )\n throw (::com::sun::star::uno::RuntimeException,\n ::com::sun::star::lang::IndexOutOfBoundsException);\n\n \/\/\/ Returns the column number of an index in the table.\n virtual sal_Int32 SAL_CALL\n getAccessibleColumn( sal_Int32 nChildIndex )\n throw (::com::sun::star::uno::RuntimeException,\n ::com::sun::star::lang::IndexOutOfBoundsException);\n\n \/\/===== XAccessibleContext ==============================================\n\n \/\/\/ Return the number of currently visible children.\n \/\/ is overloaded to calculate this on demand\n virtual sal_Int32 SAL_CALL\n getAccessibleChildCount(void)\n throw (::com::sun::star::uno::RuntimeException);\n\n \/\/\/ Return the specified child or NULL if index is invalid.\n \/\/ is overloaded to calculate this on demand\n virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible> SAL_CALL\n getAccessibleChild(sal_Int32 nIndex)\n throw (::com::sun::star::uno::RuntimeException,\n ::com::sun::star::lang::IndexOutOfBoundsException);\n\nprotected:\n \/\/\/ Return this object's description.\n virtual ::rtl::OUString SAL_CALL\n createAccessibleDescription(void)\n throw (::com::sun::star::uno::RuntimeException);\n\n \/\/\/ Return the object's current name.\n virtual ::rtl::OUString SAL_CALL\n createAccessibleName(void)\n throw (::com::sun::star::uno::RuntimeException);\n\npublic:\n \/\/\/ Return NULL to indicate that an empty relation set.\n virtual ::com::sun::star::uno::Reference<\n ::com::sun::star::accessibility::XAccessibleRelationSet> SAL_CALL\n getAccessibleRelationSet(void)\n throw (::com::sun::star::uno::RuntimeException);\n\n \/\/\/ Return the set of current states.\n \/\/ perhaps sometimes to be implemented\n virtual ::com::sun::star::uno::Reference<\n ::com::sun::star::accessibility::XAccessibleStateSet> SAL_CALL\n getAccessibleStateSet(void)\n throw (::com::sun::star::uno::RuntimeException);\n\n \/\/\/===== XAccessibleSelection ===========================================\n\n virtual void SAL_CALL\n selectAccessibleChild( sal_Int32 nChildIndex )\n throw (::com::sun::star::lang::IndexOutOfBoundsException,\n ::com::sun::star::uno::RuntimeException);\n\n virtual sal_Bool SAL_CALL\n isAccessibleChildSelected( sal_Int32 nChildIndex )\n throw (::com::sun::star::lang::IndexOutOfBoundsException,\n ::com::sun::star::uno::RuntimeException);\n\n virtual void SAL_CALL\n clearAccessibleSelection( )\n throw (::com::sun::star::uno::RuntimeException);\n\n virtual void SAL_CALL\n selectAllAccessibleChildren( )\n throw (::com::sun::star::uno::RuntimeException);\n\n virtual sal_Int32 SAL_CALL\n getSelectedAccessibleChildCount( )\n throw (::com::sun::star::uno::RuntimeException);\n\n virtual ::com::sun::star::uno::Reference<\n ::com::sun::star::accessibility::XAccessible > SAL_CALL\n getSelectedAccessibleChild( sal_Int32 nSelectedChildIndex )\n throw (::com::sun::star::lang::IndexOutOfBoundsException,\n ::com::sun::star::uno::RuntimeException);\n\n virtual void SAL_CALL\n deselectAccessibleChild( sal_Int32 nSelectedChildIndex )\n throw (::com::sun::star::lang::IndexOutOfBoundsException,\n ::com::sun::star::uno::RuntimeException);\n\n \/\/\/===== XServiceInfo ===================================================\n\n \/** Returns an identifier for the implementation of this object.\n *\/\n virtual ::rtl::OUString SAL_CALL\n getImplementationName(void)\n throw (::com::sun::star::uno::RuntimeException);\n\n \/\/\/===== XTypeProvider ===================================================\n\n \/\/\/ returns the possible types\n virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type > SAL_CALL\n getTypes()\n throw (::com::sun::star::uno::RuntimeException);\n\n \/** Returns a implementation id.\n *\/\n virtual ::com::sun::star::uno::Sequence<sal_Int8> SAL_CALL\n getImplementationId(void)\n throw (::com::sun::star::uno::RuntimeException);\n\nprotected:\n \/\/\/ contains the range of the table, because it could be a subrange of the complete table\n ScRange maRange;\n\n ScDocument* mpDoc;\n\n void CommitTableModelChange(sal_Int32 nStartRow, sal_Int32 nStartCol, sal_Int32 nEndRow, sal_Int32 nEndCol, sal_uInt16 nId);\n};\n\n\n#endif\n<commit_msg>INTEGRATION: CWS rowlimit (1.19.160); FILE MERGED 2003\/11\/28 19:47:56 er 1.19.160.1: #i1967# move ScAddress, ScRange from global.hxx to address.hxx<commit_after>\/*************************************************************************\n *\n * $RCSfile: AccessibleTableBase.hxx,v $\n *\n * $Revision: 1.20 $\n *\n * last change: $Author: obo $ $Date: 2004-06-04 11:29:13 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n\n#ifndef _SC_ACCESSIBLETABLEBASE_HXX\n#define _SC_ACCESSIBLETABLEBASE_HXX\n\n#ifndef _SC_ACCESSIBLECONTEXTBASE_HXX\n#include \"AccessibleContextBase.hxx\"\n#endif\n#ifndef SC_SCGLOB_HXX\n#include \"global.hxx\"\n#endif\n\n#ifndef SC_ADDRESS_HXX\n#include \"address.hxx\"\n#endif\n\n#ifndef _COM_SUN_STAR_ACCESSIBILITY_XACCESSIBLETABLE_HPP_\n#include <com\/sun\/star\/accessibility\/XAccessibleTable.hpp>\n#endif\n#ifndef _COM_SUN_STAR_ACCESSIBILITY_XACCESSIBLESELECTION_HPP_\n#include <com\/sun\/star\/accessibility\/XAccessibleSelection.hpp>\n#endif\n\n#ifndef _CPPUHELPER_IMPLBASE2_HXX_\n#include <cppuhelper\/implbase2.hxx>\n#endif\n\nclass ScTabViewShell;\n\n\/** @descr\n This base class provides an implementation of the\n <code>AccessibleTable<\/code> service.\n*\/\n\ntypedef cppu::ImplHelper2< ::com::sun::star::accessibility::XAccessibleTable,\n ::com::sun::star::accessibility::XAccessibleSelection>\n ScAccessibleTableBaseImpl;\n\nclass ScAccessibleTableBase :\n public ScAccessibleContextBase,\n public ScAccessibleTableBaseImpl\n{\npublic:\n \/\/===== internal ========================================================\n ScAccessibleTableBase(\n const ::com::sun::star::uno::Reference<\n ::com::sun::star::accessibility::XAccessible>& rxParent,\n ScDocument* pDoc,\n const ScRange& rRange);\nprotected:\n virtual ~ScAccessibleTableBase();\npublic:\n\n virtual void SAL_CALL disposing();\n\n \/\/\/===== XInterface =====================================================\n\n virtual ::com::sun::star::uno::Any SAL_CALL queryInterface(\n ::com::sun::star::uno::Type const & rType )\n throw (::com::sun::star::uno::RuntimeException);\n\n virtual void SAL_CALL acquire() throw ();\n\n virtual void SAL_CALL release() throw ();\n\n \/\/\/===== XAccessibleTable ================================================\n\n \/\/\/ Returns the number of rows in the table.\n virtual sal_Int32 SAL_CALL\n getAccessibleRowCount( )\n throw (::com::sun::star::uno::RuntimeException);\n\n \/\/\/ Returns the number of columns in the table.\n virtual sal_Int32 SAL_CALL\n getAccessibleColumnCount( )\n throw (::com::sun::star::uno::RuntimeException);\n\n \/\/\/ Returns the description of the specified row in the table.\n virtual ::rtl::OUString SAL_CALL\n getAccessibleRowDescription( sal_Int32 nRow )\n throw (::com::sun::star::uno::RuntimeException,\n ::com::sun::star::lang::IndexOutOfBoundsException);\n\n \/\/\/ Returns the description text of the specified column in the table.\n virtual ::rtl::OUString SAL_CALL\n getAccessibleColumnDescription( sal_Int32 nColumn )\n throw (::com::sun::star::uno::RuntimeException,\n ::com::sun::star::lang::IndexOutOfBoundsException);\n\n \/** Returns the number of rows occupied by the Accessible at a specified row and column in the table.\n Returns 1 if it is only a cell and the number of rows the cell is merged if the cell is a merged cell.\n *\/\n virtual sal_Int32 SAL_CALL\n getAccessibleRowExtentAt( sal_Int32 nRow, sal_Int32 nColumn )\n throw (::com::sun::star::uno::RuntimeException,\n ::com::sun::star::lang::IndexOutOfBoundsException);\n\n \/** Returns the number of columns occupied by the Accessible at a specified row and column in the table.\n Returns 1 if it is only a cell and the number of columns the cell is merged if the cell is a merged cell.\n *\/\n virtual sal_Int32 SAL_CALL\n getAccessibleColumnExtentAt( sal_Int32 nRow, sal_Int32 nColumn )\n throw (::com::sun::star::uno::RuntimeException,\n ::com::sun::star::lang::IndexOutOfBoundsException);\n\n \/\/\/ Returns the row headers as an AccessibleTable.\n virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessibleTable > SAL_CALL\n getAccessibleRowHeaders( )\n throw (::com::sun::star::uno::RuntimeException);\n\n \/\/\/ Returns the column headers as an AccessibleTable.\n virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessibleTable > SAL_CALL\n getAccessibleColumnHeaders( )\n throw (::com::sun::star::uno::RuntimeException);\n\n \/\/\/ Returns the selected rows in a table.\n virtual ::com::sun::star::uno::Sequence< sal_Int32 > SAL_CALL\n getSelectedAccessibleRows( )\n throw (::com::sun::star::uno::RuntimeException);\n\n \/\/\/ Returns the selected columns in a table.\n virtual ::com::sun::star::uno::Sequence< sal_Int32 > SAL_CALL\n getSelectedAccessibleColumns( )\n throw (::com::sun::star::uno::RuntimeException);\n\n \/\/\/ Returns a boolean value indicating whether the specified row is selected.\n virtual sal_Bool SAL_CALL\n isAccessibleRowSelected( sal_Int32 nRow )\n throw (::com::sun::star::uno::RuntimeException,\n ::com::sun::star::lang::IndexOutOfBoundsException);\n\n \/\/\/ Returns a boolean value indicating whether the specified column is selected.\n virtual sal_Bool SAL_CALL\n isAccessibleColumnSelected( sal_Int32 nColumn )\n throw (::com::sun::star::uno::RuntimeException,\n ::com::sun::star::lang::IndexOutOfBoundsException);\n\n \/\/\/ Returns the Accessible at a specified row and column in the table.\n virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible > SAL_CALL\n getAccessibleCellAt( sal_Int32 nRow, sal_Int32 nColumn )\n throw (::com::sun::star::uno::RuntimeException,\n ::com::sun::star::lang::IndexOutOfBoundsException);\n\n \/\/\/ Returns the caption for the table.\n virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible > SAL_CALL\n getAccessibleCaption( )\n throw (::com::sun::star::uno::RuntimeException);\n\n \/\/\/ Returns the summary description of the table.\n virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible > SAL_CALL\n getAccessibleSummary( )\n throw (::com::sun::star::uno::RuntimeException);\n\n \/\/\/ Returns a boolean value indicating whether the accessible at a specified row and column is selected.\n virtual sal_Bool SAL_CALL\n isAccessibleSelected( sal_Int32 nRow, sal_Int32 nColumn )\n throw (::com::sun::star::uno::RuntimeException,\n ::com::sun::star::lang::IndexOutOfBoundsException);\n\n \/\/\/===== XAccessibleExtendedTable ========================================\n\n \/\/\/ Returns the index of the cell on the given position.\n virtual sal_Int32 SAL_CALL\n getAccessibleIndex( sal_Int32 nRow, sal_Int32 nColumn )\n throw (::com::sun::star::uno::RuntimeException,\n ::com::sun::star::lang::IndexOutOfBoundsException);\n\n \/\/\/ Returns the row number of an index in the table.\n virtual sal_Int32 SAL_CALL\n getAccessibleRow( sal_Int32 nChildIndex )\n throw (::com::sun::star::uno::RuntimeException,\n ::com::sun::star::lang::IndexOutOfBoundsException);\n\n \/\/\/ Returns the column number of an index in the table.\n virtual sal_Int32 SAL_CALL\n getAccessibleColumn( sal_Int32 nChildIndex )\n throw (::com::sun::star::uno::RuntimeException,\n ::com::sun::star::lang::IndexOutOfBoundsException);\n\n \/\/===== XAccessibleContext ==============================================\n\n \/\/\/ Return the number of currently visible children.\n \/\/ is overloaded to calculate this on demand\n virtual sal_Int32 SAL_CALL\n getAccessibleChildCount(void)\n throw (::com::sun::star::uno::RuntimeException);\n\n \/\/\/ Return the specified child or NULL if index is invalid.\n \/\/ is overloaded to calculate this on demand\n virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible> SAL_CALL\n getAccessibleChild(sal_Int32 nIndex)\n throw (::com::sun::star::uno::RuntimeException,\n ::com::sun::star::lang::IndexOutOfBoundsException);\n\nprotected:\n \/\/\/ Return this object's description.\n virtual ::rtl::OUString SAL_CALL\n createAccessibleDescription(void)\n throw (::com::sun::star::uno::RuntimeException);\n\n \/\/\/ Return the object's current name.\n virtual ::rtl::OUString SAL_CALL\n createAccessibleName(void)\n throw (::com::sun::star::uno::RuntimeException);\n\npublic:\n \/\/\/ Return NULL to indicate that an empty relation set.\n virtual ::com::sun::star::uno::Reference<\n ::com::sun::star::accessibility::XAccessibleRelationSet> SAL_CALL\n getAccessibleRelationSet(void)\n throw (::com::sun::star::uno::RuntimeException);\n\n \/\/\/ Return the set of current states.\n \/\/ perhaps sometimes to be implemented\n virtual ::com::sun::star::uno::Reference<\n ::com::sun::star::accessibility::XAccessibleStateSet> SAL_CALL\n getAccessibleStateSet(void)\n throw (::com::sun::star::uno::RuntimeException);\n\n \/\/\/===== XAccessibleSelection ===========================================\n\n virtual void SAL_CALL\n selectAccessibleChild( sal_Int32 nChildIndex )\n throw (::com::sun::star::lang::IndexOutOfBoundsException,\n ::com::sun::star::uno::RuntimeException);\n\n virtual sal_Bool SAL_CALL\n isAccessibleChildSelected( sal_Int32 nChildIndex )\n throw (::com::sun::star::lang::IndexOutOfBoundsException,\n ::com::sun::star::uno::RuntimeException);\n\n virtual void SAL_CALL\n clearAccessibleSelection( )\n throw (::com::sun::star::uno::RuntimeException);\n\n virtual void SAL_CALL\n selectAllAccessibleChildren( )\n throw (::com::sun::star::uno::RuntimeException);\n\n virtual sal_Int32 SAL_CALL\n getSelectedAccessibleChildCount( )\n throw (::com::sun::star::uno::RuntimeException);\n\n virtual ::com::sun::star::uno::Reference<\n ::com::sun::star::accessibility::XAccessible > SAL_CALL\n getSelectedAccessibleChild( sal_Int32 nSelectedChildIndex )\n throw (::com::sun::star::lang::IndexOutOfBoundsException,\n ::com::sun::star::uno::RuntimeException);\n\n virtual void SAL_CALL\n deselectAccessibleChild( sal_Int32 nSelectedChildIndex )\n throw (::com::sun::star::lang::IndexOutOfBoundsException,\n ::com::sun::star::uno::RuntimeException);\n\n \/\/\/===== XServiceInfo ===================================================\n\n \/** Returns an identifier for the implementation of this object.\n *\/\n virtual ::rtl::OUString SAL_CALL\n getImplementationName(void)\n throw (::com::sun::star::uno::RuntimeException);\n\n \/\/\/===== XTypeProvider ===================================================\n\n \/\/\/ returns the possible types\n virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type > SAL_CALL\n getTypes()\n throw (::com::sun::star::uno::RuntimeException);\n\n \/** Returns a implementation id.\n *\/\n virtual ::com::sun::star::uno::Sequence<sal_Int8> SAL_CALL\n getImplementationId(void)\n throw (::com::sun::star::uno::RuntimeException);\n\nprotected:\n \/\/\/ contains the range of the table, because it could be a subrange of the complete table\n ScRange maRange;\n\n ScDocument* mpDoc;\n\n void CommitTableModelChange(sal_Int32 nStartRow, sal_Int32 nStartCol, sal_Int32 nEndRow, sal_Int32 nEndCol, sal_uInt16 nId);\n};\n\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>#include \"utils.hpp\"\n\nusing namespace std;\nnamespace bohrium{\nnamespace utils{\n\n\/**\n * Determine whether an operand has a contiguous layout.\n *\/\nbool is_contiguous(operand_t& arg)\n{\n if ((arg.ndim == 3) && \\\n (arg.stride[2] == 1) && \\\n (arg.stride[1] == arg.shape[2]) && \\\n (arg.stride[0] == arg.shape[2]*arg.shape[1])\n ) {\n return true;\n } else if ((arg.ndim == 2) && \\\n (arg.stride[1] == 1) && \\\n (arg.stride[0] == arg.shape[1])) {\n return true;\n } else if ((arg.ndim == 1) && (arg.stride[0] == 1)) {\n return true;\n }\n\n return false;\n}\n\nstd::string tac_text(tac_t& tac)\n{\n std::stringstream ss;\n ss << \"[op=\"<< operation_text(tac.op) << \"(\" << tac.op << \")\";\n ss << \", oper=\" << tac.oper;\n ss << \", out=\" << tac.out;\n ss << \", in1=\" << tac.in1;\n ss << \", in2=\" << tac.in2;\n ss << \"]\" << endl;\n return ss.str();\n}\n\nint tac_noperands(tac_t& tac)\n{\n switch(tac.op) {\n case MAP:\n return 2;\n case ZIP:\n return 3;\n case SCAN:\n return 3;\n case REDUCE:\n return 3;\n case GENERATE:\n switch(tac.oper) {\n case FLOOD:\n return 2;\n case RANDOM:\n return 3;\n case RANGE:\n return 1;\n default:\n throw runtime_error(\"noperands does not know how many operands are used.\");\n return 0;\n }\n case SYSTEM:\n switch(tac.oper) {\n case DISCARD:\n case FREE:\n case SYNC:\n return 1;\n case NONE:\n return 0;\n default:\n throw runtime_error(\"noperands does not know how many operands are used.\");\n return 0;\n }\n break;\n case EXTENSION:\n return 3;\n case NOOP:\n return 0;\n }\n return 0;\n}\n\nstd::string tac_typesig_text(tac_t& tac, operand_t* scope)\n{\n switch(tac_noperands(tac)) {\n case 3:\n return etype_text_shand(scope[tac.out].type)+\\\n etype_text_shand(scope[tac.in1].type)+\\\n etype_text_shand(scope[tac.in2].type);\n case 2:\n return etype_text_shand(scope[tac.out].type)+\\\n etype_text_shand(scope[tac.in1].type);\n case 1:\n return etype_text_shand(scope[tac.out].type);\n default:\n return \"\";\n }\n}\n\nstd::string tac_layout_text(tac_t& tac, operand_t* scope)\n{\n switch(tac_noperands(tac)) {\n case 3:\n return layout_text_shand(scope[tac.out].layout)+\\\n layout_text_shand(scope[tac.in1].layout)+\\\n layout_text_shand(scope[tac.in2].layout);\n case 2:\n return layout_text_shand(scope[tac.out].layout)+\\\n layout_text_shand(scope[tac.in1].layout);\n case 1:\n return layout_text_shand(scope[tac.out].layout);\n default:\n return \"\";\n }\n}\n\n\/\/\n\/\/ MOVE THESE TO CORE\n\/\/\n\n\/\/ Create nice error-messages...\nint error(int errnum, const char *fmt, ...)\n{\n va_list va;\n int ret;\n\n char err_msg[500];\n sprintf(err_msg, \"Error[%d, %s] from: %s\", errnum, strerror(errnum), fmt);\n va_start(va, fmt);\n ret = vfprintf(stderr, err_msg, va);\n va_end(va);\n return ret;\n}\n\nint error(const char *err_msg, const char *fmt, ...)\n{\n va_list va;\n int ret;\n\n char err_txt[500];\n sprintf(err_txt, \"Error[%s] from: %s\", err_msg, fmt);\n va_start(va, fmt);\n ret = vfprintf(stderr, err_txt, va);\n va_end(va);\n return ret;\n}\n\n}}\n<commit_msg>cpu: Added operation-text to block-description function.<commit_after>#include \"utils.hpp\"\n\nusing namespace std;\nnamespace bohrium{\nnamespace utils{\n\n\/**\n * Determine whether an operand has a contiguous layout.\n *\/\nbool is_contiguous(operand_t& arg)\n{\n if ((arg.ndim == 3) && \\\n (arg.stride[2] == 1) && \\\n (arg.stride[1] == arg.shape[2]) && \\\n (arg.stride[0] == arg.shape[2]*arg.shape[1])\n ) {\n return true;\n } else if ((arg.ndim == 2) && \\\n (arg.stride[1] == 1) && \\\n (arg.stride[0] == arg.shape[1])) {\n return true;\n } else if ((arg.ndim == 1) && (arg.stride[0] == 1)) {\n return true;\n }\n\n return false;\n}\n\nstd::string tac_text(tac_t& tac)\n{\n std::stringstream ss;\n ss << \"[op=\"<< operation_text(tac.op) << \"(\" << tac.op << \")\";\n ss << \", oper=\" << operator_text(tac.oper) << \"(\" << tac.oper << \")\";\n ss << \", out=\" << tac.out;\n ss << \", in1=\" << tac.in1;\n ss << \", in2=\" << tac.in2;\n ss << \"]\" << endl;\n return ss.str();\n}\n\nint tac_noperands(tac_t& tac)\n{\n switch(tac.op) {\n case MAP:\n return 2;\n case ZIP:\n return 3;\n case SCAN:\n return 3;\n case REDUCE:\n return 3;\n case GENERATE:\n switch(tac.oper) {\n case FLOOD:\n return 2;\n case RANDOM:\n return 3;\n case RANGE:\n return 1;\n default:\n throw runtime_error(\"noperands does not know how many operands are used.\");\n return 0;\n }\n case SYSTEM:\n switch(tac.oper) {\n case DISCARD:\n case FREE:\n case SYNC:\n return 1;\n case NONE:\n return 0;\n default:\n throw runtime_error(\"noperands does not know how many operands are used.\");\n return 0;\n }\n break;\n case EXTENSION:\n return 3;\n case NOOP:\n return 0;\n }\n return 0;\n}\n\nstd::string tac_typesig_text(tac_t& tac, operand_t* scope)\n{\n switch(tac_noperands(tac)) {\n case 3:\n return etype_text_shand(scope[tac.out].type)+\\\n etype_text_shand(scope[tac.in1].type)+\\\n etype_text_shand(scope[tac.in2].type);\n case 2:\n return etype_text_shand(scope[tac.out].type)+\\\n etype_text_shand(scope[tac.in1].type);\n case 1:\n return etype_text_shand(scope[tac.out].type);\n default:\n return \"\";\n }\n}\n\nstd::string tac_layout_text(tac_t& tac, operand_t* scope)\n{\n switch(tac_noperands(tac)) {\n case 3:\n return layout_text_shand(scope[tac.out].layout)+\\\n layout_text_shand(scope[tac.in1].layout)+\\\n layout_text_shand(scope[tac.in2].layout);\n case 2:\n return layout_text_shand(scope[tac.out].layout)+\\\n layout_text_shand(scope[tac.in1].layout);\n case 1:\n return layout_text_shand(scope[tac.out].layout);\n default:\n return \"\";\n }\n}\n\n\/\/\n\/\/ MOVE THESE TO CORE\n\/\/\n\n\/\/ Create nice error-messages...\nint error(int errnum, const char *fmt, ...)\n{\n va_list va;\n int ret;\n\n char err_msg[500];\n sprintf(err_msg, \"Error[%d, %s] from: %s\", errnum, strerror(errnum), fmt);\n va_start(va, fmt);\n ret = vfprintf(stderr, err_msg, va);\n va_end(va);\n return ret;\n}\n\nint error(const char *err_msg, const char *fmt, ...)\n{\n va_list va;\n int ret;\n\n char err_txt[500];\n sprintf(err_txt, \"Error[%s] from: %s\", err_msg, fmt);\n va_start(va, fmt);\n ret = vfprintf(stderr, err_txt, va);\n va_end(va);\n return ret;\n}\n\n}}\n<|endoftext|>"} {"text":"<commit_before>\/* Source file for the R2 texture class *\/\n\n\n\n\/* Include files *\/\n\n#include \"R3Graphics.h\"\n\n\n\n\/* Public variables *\/\n\nR2Texture R2null_texture;\n\n\n\n\/* Public functions *\/\n\nint \nR2InitTexture()\n{\n \/* Return success *\/\n return TRUE;\n}\n\n\n\nvoid \nR2StopTexture()\n{\n}\n\n\n\nR2Texture::\nR2Texture(void)\n : scene(NULL),\n scene_index(-1),\n name(NULL),\n filename(NULL),\n image(NULL),\n s_wrap(R2_REPEAT_TEXTURE_WRAP),\n t_wrap(R2_REPEAT_TEXTURE_WRAP),\n min_filter(R2_LINEAR_MIPMAP_LINEAR_TEXTURE_FILTER),\n mag_filter(R2_LINEAR_TEXTURE_FILTER),\n blend(R2_MODULATE_TEXTURE_BLEND), \n flags(0),\n id(0)\n{\n}\n\n\n\nR2Texture::\nR2Texture(const R2Texture& texture, const char *name)\n : scene(NULL),\n scene_index(-1),\n name(NULL),\n filename((texture.filename) ? strdup(texture.filename) : NULL),\n image(texture.image),\n s_wrap(texture.s_wrap),\n t_wrap(texture.t_wrap),\n min_filter(texture.min_filter),\n mag_filter(texture.mag_filter),\n blend(texture.blend),\n flags(texture.flags),\n id((texture.image) ? -1 : 0)\n{\n \/\/ Set name\n if (name) this->name = strdup(name);\n\n \/\/ Update texture \n Update();\n}\n\n\n\nR2Texture::\nR2Texture(const R2Image *image,\n R2TextureWrap s_wrap, R2TextureWrap t_wrap,\n R2TextureFilter min_filter, R2TextureFilter mag_filter,\n R2TextureBlend blend,\n const char *name)\n : scene(NULL),\n scene_index(-1),\n name(NULL),\n filename(NULL),\n image(image),\n s_wrap(s_wrap),\n t_wrap(t_wrap),\n min_filter(min_filter),\n mag_filter(mag_filter),\n blend(blend),\n flags(RN_NO_FLAGS),\n id(-1)\n{\n \/\/ Set name\n if (name) this->name = strdup(name);\n\n \/\/ Update texture\n Update();\n}\n\n\n\n\nR2Texture::\nR2Texture(const char *filename,\n R2TextureWrap s_wrap, R2TextureWrap t_wrap,\n R2TextureFilter min_filter, R2TextureFilter mag_filter,\n R2TextureBlend blend,\n const char *name)\n : scene(NULL),\n scene_index(-1),\n name(NULL),\n filename((filename) ? strdup(filename) : NULL),\n image(NULL),\n s_wrap(s_wrap),\n t_wrap(t_wrap),\n min_filter(min_filter),\n mag_filter(mag_filter),\n blend(blend),\n flags(RN_NO_FLAGS),\n id(-1)\n{\n \/\/ Set name\n if (name) this->name = strdup(name);\n\n \/\/ Create image\n image = new R2Image(filename);\n assert(image);\n\n \/\/ Update \n if (!image) id = 0;\n Update();\n}\n\n\n\nR2Texture::\n~R2Texture(void)\n{\n \/\/ Unload texture\n if (IsLoaded() > 0) Unload();\n\n \/\/ Remove from scene\n if (scene) scene->RemoveTexture(this);\n\n \/\/ Free name\n if (name) free(name);\n\n \/\/ Free filename\n if (filename) free(filename);\n}\n\n\n\nvoid R2Texture::\nSetName(const char *name)\n{\n \/\/ Set name\n if (this->name) free(this->name);\n if (name) this->name = strdup(name);\n else this->name = NULL;\n}\n\n\n \nvoid R2Texture::\nSetFilename(const char *filename)\n{\n \/\/ Set filename\n if (this->filename) free(this->filename);\n if (filename) this->filename = strdup(filename);\n else this->filename = NULL;\n}\n\n\n \nvoid R2Texture::\nSetImage(const R2Image *image)\n{\n \/\/ Unload previous texture\n if (IsLoaded()) Unload();\n\n \/\/ Set image\n flags.Remove(R2_TEXTURE_TRANSPARENCY_FLAG);\n if ((image) && ((image->NComponents() == 2) || (image->NComponents() == 4)))\n flags.Add(R2_TEXTURE_TRANSPARENCY_FLAG);\n this->image = image;\n this->id = -1;\n}\n\n\n\nvoid R2Texture::\nUpdate (void)\n{\n \/\/ Update flags\n UpdateFlags(RN_NO_FLAGS);\n}\n\n\n\nvoid R2Texture::\nUpdateFlags (const RNFlags flags)\n{\n \/\/ Update flags\n this->flags = flags;\n if ((image) && ((image->NComponents() == 2) || (image->NComponents() == 4)))\n this->flags.Add(R2_TEXTURE_TRANSPARENCY_FLAG);\n}\n\n\n\nvoid R2Texture::\nLoad(void) const\n{\n \/\/ Check if needs to be loaded\n if (id >= 0) return;\n\n \/\/ Create texture id\n GLuint i;\n glGenTextures(1, &i);\n ((R2Texture *) this)->id = i;\n assert(id > 0);\n\n \/\/ Begin texture definition \n glBindTexture(GL_TEXTURE_2D, id);\n\n \/\/ Define texture parameters\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, s_wrap);\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, t_wrap);\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, min_filter);\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, mag_filter);\n glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, blend);\n\n \/\/ Determine texture format\n GLenum format = GL_RGB;\n if (image->Depth() == 1) format = GL_LUMINANCE;\n else if (image->Depth() == 2) format = GL_LUMINANCE_ALPHA;\n else if (image->Depth() == 3) format = GL_RGB;\n else if (image->Depth() == 4) format = GL_RGBA;\n else RNAbort(\"Illegal texture image\");\n\n#ifdef USE_MESA\n \/\/ For some reason, gluBuild2DMipmaps segfaults in mesa\n glTexImage2D(GL_TEXTURE_2D, 0, format, image->Width(), image->Height(),\n 0, format, GL_UNSIGNED_BYTE, (const unsigned char *) image->Pixels());\n#else\n \/\/ Define texture\n if ((min_filter == R2_NEAREST_MIPMAP_NEAREST_TEXTURE_FILTER) ||\n (min_filter == R2_NEAREST_MIPMAP_LINEAR_TEXTURE_FILTER) ||\n (min_filter == R2_LINEAR_MIPMAP_NEAREST_TEXTURE_FILTER) ||\n (min_filter == R2_LINEAR_MIPMAP_LINEAR_TEXTURE_FILTER)) {\n gluBuild2DMipmaps(GL_TEXTURE_2D, format, image->Width(), image->Height(),\n format, GL_UNSIGNED_BYTE, (const unsigned char *) image->Pixels());\n }\n else {\n glTexImage2D(GL_TEXTURE_2D, 0, format, image->Width(), image->Height(),\n 0, format, GL_UNSIGNED_BYTE, (const unsigned char *) image->Pixels());\n }\n#endif\n\n \/\/ End texture definition \n glBindTexture(GL_TEXTURE_2D, 0);\n}\n\n\n\nvoid R2Texture::\nUnload(void) const\n{\n \/\/ Check id\n if (!IsLoaded()) return;\n\n \/\/ Delete texture\n GLuint i = id;\n glDeleteTextures(1, &i);\n\n \/\/ Reset texture id\n ((R2Texture *) this)->id = -1;\n}\n\n\n\nvoid R2Texture::\nDraw(RNBoolean force) const\n{\n \/\/ Check if same texture as last time\n static const R2Texture *R2current_texture = NULL;\n if (!force && (this == R2current_texture)) return;\n\n \/\/ Check if null texture\n if (id == 0) {\n \/\/ Disable texture\n glDisable(GL_TEXTURE_2D);\n }\n else {\n \/\/ Load texture\n if (!IsLoaded()) Load();\n\n \/\/ Set texture\n glBindTexture(GL_TEXTURE_2D, id);\n\n \/\/ Enable texture\n glEnable(GL_TEXTURE_2D);\n }\n\n \/\/ Remember current texture\n R2current_texture = this;\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n<commit_msg>Textures in mesa<commit_after>\/* Source file for the R2 texture class *\/\n\n\n\n\/* Include files *\/\n\n#include \"R3Graphics.h\"\n\n\n\n\/* Public variables *\/\n\nR2Texture R2null_texture;\n\n\n\n\/* Public functions *\/\n\nint \nR2InitTexture()\n{\n \/* Return success *\/\n return TRUE;\n}\n\n\n\nvoid \nR2StopTexture()\n{\n}\n\n\n\nR2Texture::\nR2Texture(void)\n : scene(NULL),\n scene_index(-1),\n name(NULL),\n filename(NULL),\n image(NULL),\n s_wrap(R2_REPEAT_TEXTURE_WRAP),\n t_wrap(R2_REPEAT_TEXTURE_WRAP),\n min_filter(R2_LINEAR_MIPMAP_LINEAR_TEXTURE_FILTER),\n mag_filter(R2_LINEAR_TEXTURE_FILTER),\n blend(R2_MODULATE_TEXTURE_BLEND), \n flags(0),\n id(0)\n{\n}\n\n\n\nR2Texture::\nR2Texture(const R2Texture& texture, const char *name)\n : scene(NULL),\n scene_index(-1),\n name(NULL),\n filename((texture.filename) ? strdup(texture.filename) : NULL),\n image(texture.image),\n s_wrap(texture.s_wrap),\n t_wrap(texture.t_wrap),\n min_filter(texture.min_filter),\n mag_filter(texture.mag_filter),\n blend(texture.blend),\n flags(texture.flags),\n id((texture.image) ? -1 : 0)\n{\n \/\/ Set name\n if (name) this->name = strdup(name);\n\n \/\/ Update texture \n Update();\n}\n\n\n\nR2Texture::\nR2Texture(const R2Image *image,\n R2TextureWrap s_wrap, R2TextureWrap t_wrap,\n R2TextureFilter min_filter, R2TextureFilter mag_filter,\n R2TextureBlend blend,\n const char *name)\n : scene(NULL),\n scene_index(-1),\n name(NULL),\n filename(NULL),\n image(image),\n s_wrap(s_wrap),\n t_wrap(t_wrap),\n min_filter(min_filter),\n mag_filter(mag_filter),\n blend(blend),\n flags(RN_NO_FLAGS),\n id(-1)\n{\n \/\/ Set name\n if (name) this->name = strdup(name);\n\n \/\/ Update texture\n Update();\n}\n\n\n\n\nR2Texture::\nR2Texture(const char *filename,\n R2TextureWrap s_wrap, R2TextureWrap t_wrap,\n R2TextureFilter min_filter, R2TextureFilter mag_filter,\n R2TextureBlend blend,\n const char *name)\n : scene(NULL),\n scene_index(-1),\n name(NULL),\n filename((filename) ? strdup(filename) : NULL),\n image(NULL),\n s_wrap(s_wrap),\n t_wrap(t_wrap),\n min_filter(min_filter),\n mag_filter(mag_filter),\n blend(blend),\n flags(RN_NO_FLAGS),\n id(-1)\n{\n \/\/ Set name\n if (name) this->name = strdup(name);\n\n \/\/ Create image\n image = new R2Image(filename);\n assert(image);\n\n \/\/ Update \n if (!image) id = 0;\n Update();\n}\n\n\n\nR2Texture::\n~R2Texture(void)\n{\n \/\/ Unload texture\n if (IsLoaded() > 0) Unload();\n\n \/\/ Remove from scene\n if (scene) scene->RemoveTexture(this);\n\n \/\/ Free name\n if (name) free(name);\n\n \/\/ Free filename\n if (filename) free(filename);\n}\n\n\n\nvoid R2Texture::\nSetName(const char *name)\n{\n \/\/ Set name\n if (this->name) free(this->name);\n if (name) this->name = strdup(name);\n else this->name = NULL;\n}\n\n\n \nvoid R2Texture::\nSetFilename(const char *filename)\n{\n \/\/ Set filename\n if (this->filename) free(this->filename);\n if (filename) this->filename = strdup(filename);\n else this->filename = NULL;\n}\n\n\n \nvoid R2Texture::\nSetImage(const R2Image *image)\n{\n \/\/ Unload previous texture\n if (IsLoaded()) Unload();\n\n \/\/ Set image\n flags.Remove(R2_TEXTURE_TRANSPARENCY_FLAG);\n if ((image) && ((image->NComponents() == 2) || (image->NComponents() == 4)))\n flags.Add(R2_TEXTURE_TRANSPARENCY_FLAG);\n this->image = image;\n this->id = -1;\n}\n\n\n\nvoid R2Texture::\nUpdate (void)\n{\n \/\/ Update flags\n UpdateFlags(RN_NO_FLAGS);\n}\n\n\n\nvoid R2Texture::\nUpdateFlags (const RNFlags flags)\n{\n \/\/ Update flags\n this->flags = flags;\n if ((image) && ((image->NComponents() == 2) || (image->NComponents() == 4)))\n this->flags.Add(R2_TEXTURE_TRANSPARENCY_FLAG);\n}\n\n\n\nvoid R2Texture::\nLoad(void) const\n{\n \/\/ Check if needs to be loaded\n if (id >= 0) return;\n\n \/\/ Create texture id\n GLuint i;\n glGenTextures(1, &i);\n ((R2Texture *) this)->id = i;\n assert(id > 0);\n\n \/\/ Begin texture definition \n glBindTexture(GL_TEXTURE_2D, id);\n\n \/\/ Define texture parameters\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, s_wrap);\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, t_wrap);\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, min_filter);\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, mag_filter);\n glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, blend);\n\n \/\/ Determine texture format\n GLenum format = GL_RGB;\n if (image->Depth() == 1) format = GL_LUMINANCE;\n else if (image->Depth() == 2) format = GL_LUMINANCE_ALPHA;\n else if (image->Depth() == 3) format = GL_RGB;\n else if (image->Depth() == 4) format = GL_RGBA;\n else RNAbort(\"Illegal texture image\");\n\n#ifdef AT_ONE_POINT_THIS_WAS_NEEDED_FOR_MESA\n \/\/ For some reason, gluBuild2DMipmaps segfaults in mesa\n glTexImage2D(GL_TEXTURE_2D, 0, format, image->Width(), image->Height(),\n 0, format, GL_UNSIGNED_BYTE, (const unsigned char *) image->Pixels());\n#else\n \/\/ Define texture\n if ((min_filter == R2_NEAREST_MIPMAP_NEAREST_TEXTURE_FILTER) ||\n (min_filter == R2_NEAREST_MIPMAP_LINEAR_TEXTURE_FILTER) ||\n (min_filter == R2_LINEAR_MIPMAP_NEAREST_TEXTURE_FILTER) ||\n (min_filter == R2_LINEAR_MIPMAP_LINEAR_TEXTURE_FILTER)) {\n gluBuild2DMipmaps(GL_TEXTURE_2D, format, image->Width(), image->Height(),\n format, GL_UNSIGNED_BYTE, (const unsigned char *) image->Pixels());\n }\n else {\n glTexImage2D(GL_TEXTURE_2D, 0, format, image->Width(), image->Height(),\n 0, format, GL_UNSIGNED_BYTE, (const unsigned char *) image->Pixels());\n }\n#endif\n\n \/\/ End texture definition \n glBindTexture(GL_TEXTURE_2D, 0);\n}\n\n\n\nvoid R2Texture::\nUnload(void) const\n{\n \/\/ Check id\n if (!IsLoaded()) return;\n\n \/\/ Delete texture\n GLuint i = id;\n glDeleteTextures(1, &i);\n\n \/\/ Reset texture id\n ((R2Texture *) this)->id = -1;\n}\n\n\n\nvoid R2Texture::\nDraw(RNBoolean force) const\n{\n \/\/ Check if same texture as last time\n static const R2Texture *R2current_texture = NULL;\n if (!force && (this == R2current_texture)) return;\n\n \/\/ Check if null texture\n if (id == 0) {\n \/\/ Disable texture\n glDisable(GL_TEXTURE_2D);\n }\n else {\n \/\/ Load texture\n if (!IsLoaded()) Load();\n\n \/\/ Set texture\n glBindTexture(GL_TEXTURE_2D, id);\n\n \/\/ Enable texture\n glEnable(GL_TEXTURE_2D);\n }\n\n \/\/ Remember current texture\n R2current_texture = this;\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n<|endoftext|>"} {"text":"<commit_before>#pragma once\r\n\r\n#include \"helpers.hpp\"\r\n#include \"priority_queue.hpp\"\r\n#include \"timing.hpp\"\r\n\r\nusing std::pair;\r\nusing std::make_pair;\r\nusing std::min_element;\r\n\r\nnamespace search\r\n{\r\n namespace ds\r\n {\r\n struct OldKeys : public unordered_map<Cell, Key, Cell::Hasher>\r\n {\r\n auto update_with(pair<Cell, Key> cell_key_pair)\r\n {\r\n erase(cell_key_pair.first);\r\n insert(cell_key_pair);\r\n }\r\n };\r\n\r\n class DStarCore\r\n {\r\n \/\/\r\n \/\/ Algorithm\r\n \/\/\r\n\r\n auto validate(Cell c) const\r\n {\r\n return c.row >= 0 && c.row < (int)matrix.rows() && c.col >= 0 && c.col < (int)matrix.cols();\r\n }\r\n auto valid_neighbours_of(Cell c) const\r\n {\r\n Cells neighbours;\r\n for (auto direction = '1'; direction != '9'; ++direction)\r\n {\r\n auto n = DIRECTIONS.at(direction)(c);\r\n if (validate(n))\r\n neighbours.insert(n);\r\n }\r\n return neighbours;\r\n }\r\n auto initialize()\r\n {\r\n q.reset();\r\n km = at(goal).r = 0;\r\n q.push(goal);\r\n old_keys.insert({ goal, { at(goal), km } });\r\n }\r\n auto update_vertex(LpState& s)\r\n {\r\n if (s.cell != goal)\r\n {\r\n auto minimum = huge();\r\n for (auto neighbour : valid_neighbours_of(s.cell))\r\n minimum = min(minimum, (at(neighbour).g + cost()));\r\n s.r = minimum;\r\n }\r\n q.remove(s.cell);\r\n if (s.g != s.r)\r\n q.push(s.cell), \r\n old_keys.update_with( { s.cell, Key{ s, km } } );\r\n }\r\n auto update_neighbours_of(Cell cell)\r\n {\r\n for (auto neighbour : valid_neighbours_of(cell))\r\n if (!at(neighbour).bad)\r\n update_vertex(at(neighbour));\r\n }\r\n auto compute_shortest_path()\r\n {\r\n Timing t{ run_time };\r\n while (!q.empty() && (Key{ at(q.top()) } < Key{ at(start) } || at(start).r != at(start).g))\r\n {\r\n auto c = q.pop();\r\n\r\n if (old_keys.at(c) < Key{ at(c), km })\r\n q.push(c), \r\n old_keys.update_with({ c, Key{ at(c), km } });\r\n else if (at(c).g > at(c).r)\r\n at(c).g = at(c).r,\r\n update_neighbours_of(c);\r\n else\r\n at(c).g = huge(), \r\n update_vertex(at(c)),\r\n update_neighbours_of(c);\r\n\r\n {\r\n max_q_size = max(max_q_size, q.size());\r\n expansions.insert(c);\r\n }\r\n }\r\n }\r\n \r\n \/\/\r\n \/\/ helpers\r\n \/\/\r\n\r\n auto at(Cell c) const -> LpState const&\r\n {\r\n return matrix.at(c);\r\n }\r\n auto at(Cell c) -> LpState&\r\n {\r\n return matrix.at(c);\r\n }\r\n auto mark_bad_cells(Cells const& bad_cells)\r\n {\r\n for (auto c : bad_cells) at(c).bad = true;\r\n }\r\n auto mark_h_values_with(Cell terminal)\r\n {\r\n auto mark_h = [=](Cell c) { at(c).h = hfunc(c, terminal); };\r\n matrix.each_cell(mark_h);\r\n }\r\n auto reset_statistics()\r\n {\r\n run_time = max_q_size = 0;\r\n expansions.clear(), path.clear();\r\n }\r\n\r\n public:\r\n \/\/\r\n \/\/ Constructor\r\n \/\/\r\n DStarCore(unsigned rows, unsigned cols, Cell start, Cell goal, string heuristic, Cells const& bad_cells) :\r\n matrix{ rows, cols },\r\n start{ start },\r\n goal{ goal },\r\n hfunc{ HEURISTICS.at(heuristic) },\r\n km{ 0 },\r\n q{ [this](Cell l, Cell r) { return Key{ at(l), km } < Key{ at(r), km }; } },\r\n old_keys { }\r\n {\r\n mark_bad_cells(bad_cells);\r\n mark_h_values_with(start); \/\/h value : start to current\r\n reset_statistics();\r\n }\r\n\r\n \/\/\r\n \/\/ Interfaces\r\n \/\/\r\n\r\n auto initial_plan()\r\n {\r\n initialize();\r\n compute_shortest_path();\r\n }\r\n\r\n auto plan(function<void(Cell)> && move_to)\r\n {\r\n initial_plan();\r\n for (auto last = start, curr = start; curr != goal;)\r\n {\r\n auto less = [this](Cell l, Cell r) { return at(l).g + cost() < at(r).g + cost(); };\r\n auto ns = valid_neighbours_of(curr);\r\n curr = *min_element(ns.cbegin(), ns.cend(), less);\r\n move_to(curr);\r\n \/\/\r\n \/\/ still working\r\n \/\/\r\n }\r\n }\r\n\r\n \/\/\r\n \/\/ data members\r\n \/\/\r\n\r\n Matrix matrix;\r\n Cell const start, goal;\r\n function<int(Cell, Cell)> const hfunc;\r\n int km;\r\n PriorityQueue < Cell, function<bool(Cell, Cell)> > q;\r\n OldKeys old_keys;\r\n \r\n \/\/\r\n \/\/ statistics\r\n \/\/\r\n \r\n size_t max_q_size;\r\n Cells expansions;\r\n string path;\r\n long long run_time;\r\n };\r\n }\r\n}\r\n<commit_msg>added plan(), not tested yet.<commit_after>#pragma once\r\n\r\n#include \"helpers.hpp\"\r\n#include \"priority_queue.hpp\"\r\n#include \"timing.hpp\"\r\n\r\nusing std::pair;\r\nusing std::make_pair;\r\nusing std::min_element;\r\n\r\nnamespace search\r\n{\r\n namespace ds\r\n {\r\n struct OldKeys : public unordered_map<Cell, Key, Cell::Hasher>\r\n {\r\n auto update_with(pair<Cell, Key> cell_key_pair)\r\n {\r\n erase(cell_key_pair.first);\r\n insert(cell_key_pair);\r\n }\r\n };\r\n\r\n class DStarCore\r\n {\r\n \/\/\r\n \/\/ Algorithm\r\n \/\/\r\n\r\n auto validate(Cell c) const\r\n {\r\n return c.row >= 0 && c.row < (int)matrix.rows() && c.col >= 0 && c.col < (int)matrix.cols();\r\n }\r\n auto valid_neighbours_of(Cell c) const\r\n {\r\n Cells neighbours;\r\n for (auto direction = '1'; direction != '9'; ++direction)\r\n {\r\n auto n = DIRECTIONS.at(direction)(c);\r\n if (validate(n))\r\n neighbours.insert(n);\r\n }\r\n return neighbours;\r\n }\r\n auto initialize()\r\n {\r\n q.reset();\r\n km = at(goal).r = 0;\r\n q.push(goal);\r\n old_keys.insert({ goal, { at(goal), km } });\r\n }\r\n auto update_vertex(LpState& s)\r\n {\r\n if (s.cell != goal)\r\n {\r\n auto minimum = huge();\r\n for (auto neighbour : valid_neighbours_of(s.cell))\r\n minimum = min(minimum, (at(neighbour).g + cost()));\r\n s.r = minimum;\r\n }\r\n q.remove(s.cell);\r\n if (s.g != s.r)\r\n q.push(s.cell), \r\n old_keys.update_with( { s.cell, Key{ s, km } } );\r\n }\r\n auto update_neighbours_of(Cell cell)\r\n {\r\n for (auto neighbour : valid_neighbours_of(cell))\r\n if (!at(neighbour).bad)\r\n update_vertex(at(neighbour));\r\n }\r\n auto compute_shortest_path()\r\n {\r\n Timing t{ run_time };\r\n while (!q.empty() && (Key{ at(q.top()) } < Key{ at(start) } || at(start).r != at(start).g))\r\n {\r\n auto c = q.pop();\r\n\r\n if (old_keys.at(c) < Key{ at(c), km })\r\n q.push(c), \r\n old_keys.update_with({ c, Key{ at(c), km } });\r\n else if (at(c).g > at(c).r)\r\n at(c).g = at(c).r,\r\n update_neighbours_of(c);\r\n else\r\n at(c).g = huge(), \r\n update_vertex(at(c)),\r\n update_neighbours_of(c);\r\n\r\n {\r\n max_q_size = max(max_q_size, q.size());\r\n expansions.insert(c);\r\n }\r\n }\r\n }\r\n \r\n \/\/\r\n \/\/ helpers\r\n \/\/\r\n\r\n auto at(Cell c) const -> LpState const&\r\n {\r\n return matrix.at(c);\r\n }\r\n auto at(Cell c) -> LpState&\r\n {\r\n return matrix.at(c);\r\n }\r\n auto mark_bad_cells(Cells const& bad_cells)\r\n {\r\n for (auto c : bad_cells) at(c).bad = true;\r\n }\r\n auto mark_h_values_with(Cell terminal)\r\n {\r\n auto mark_h = [=](Cell c) { at(c).h = hfunc(c, terminal); };\r\n matrix.each_cell(mark_h);\r\n }\r\n auto reset_statistics()\r\n {\r\n run_time = max_q_size = 0;\r\n expansions.clear(), path.clear();\r\n }\r\n\r\n public:\r\n \/\/\r\n \/\/ Constructor\r\n \/\/\r\n DStarCore(unsigned rows, unsigned cols, Cell start, Cell goal, string heuristic, Cells const& bad_cells) :\r\n matrix{ rows, cols },\r\n start{ start },\r\n goal{ goal },\r\n hfunc{ HEURISTICS.at(heuristic) },\r\n km{ 0 },\r\n q{ [this](Cell l, Cell r) { return Key{ at(l), km } < Key{ at(r), km }; } },\r\n old_keys { }\r\n {\r\n mark_bad_cells(bad_cells);\r\n mark_h_values_with(start); \/\/h value : start to current\r\n reset_statistics();\r\n }\r\n\r\n \/\/\r\n \/\/ Interfaces\r\n \/\/\r\n\r\n auto initial_plan()\r\n {\r\n initialize();\r\n compute_shortest_path();\r\n }\r\n\r\n auto plan(function<void(Cell)> && move_to, vector<Cells> && changes)\r\n {\r\n\r\n initial_plan();\r\n \r\n struct Variables \r\n { \r\n Cell last, curr; \r\n decltype(changes.cbegin()) changes_iterator; \r\n };\r\n\r\n for (Variables this_loop = { start, start, changes.cbegin() }; this_loop.curr != goal;)\r\n {\r\n auto less = [this](Cell l, Cell r) { return at(l).g + cost() < at(r).g + cost(); };\r\n auto ns = valid_neighbours_of(this_loop.curr);\r\n this_loop.curr = *min_element(ns.cbegin(), ns.cend(), less);\r\n\r\n move_to(this_loop.curr);\r\n if (this_loop.changes_iterator != changes.cend())\r\n {\r\n km += hfunc(this_loop.last, this_loop.curr);\r\n this_loop.last = this_loop.curr;\r\n\r\n for (auto cell : *this_loop.changes_iterator)\r\n {\r\n at(cell).bad = !at(cell).bad;\r\n if (!at(cell).bad)\r\n update_vertex(at(cell));\r\n else\r\n at(cell).g = at(cell).r = huge();\r\n update_neighbours_of(cell);\r\n } \r\n ++this_loop.changes_iterator;\r\n\r\n compute_shortest_path();\r\n }\r\n\r\n\r\n \/\/\r\n \/\/ still working\r\n \/\/\r\n }\r\n }\r\n\r\n \/\/\r\n \/\/ data members\r\n \/\/\r\n\r\n Matrix matrix;\r\n Cell const start, goal;\r\n function<int(Cell, Cell)> const hfunc;\r\n int km;\r\n PriorityQueue < Cell, function<bool(Cell, Cell)> > q;\r\n OldKeys old_keys;\r\n \r\n \/\/\r\n \/\/ statistics\r\n \/\/\r\n \r\n size_t max_q_size;\r\n Cells expansions;\r\n string path;\r\n long long run_time;\r\n };\r\n }\r\n}\r\n<|endoftext|>"} {"text":"<commit_before><commit_msg>fix for netstream: callbacks for replicators only from Net_processOutput<commit_after><|endoftext|>"} {"text":"<commit_before>\/* This file is part of the KDE libraries\n Copyright (C) 2010 Miquel Sabaté <mikisabate@gmail.com>\n\n This library is free software; you can redistribute it and\/or\n modify it under the terms of the GNU Library General Public\n License as published by the Free Software Foundation; either\n version 2 of the License, or (at your option) any later version.\n\n This library is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n Library General Public License for more details.\n\n You should have received a copy of the GNU Library General Public License\n along with this library; see the file COPYING.LIB. If not, write to\n the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,\n Boston, MA 02110-1301, USA.\n*\/\n\n\n\/\/BEGIN Includes\n\/\/ Qt\n#include <QtCore\/QFile>\n#include <QtGui\/QLabel>\n#include <QtGui\/QVBoxLayout>\n#include <QtGui\/QPushButton>\n#include <QtGui\/QTextEdit>\n\n\/\/ KDE\n#include <KStandardDirs>\n#include <KLocale>\n\n\/\/ Kate\n#include \"katescriptconsole.h\"\n#include \"katetemplatescript.h\"\n\/\/END Includes\n\n\n\/\/BEGIN KateScriptConsoleEngine\nKateScriptConsoleEngine::KateScriptConsoleEngine(KateView * view)\n : m_view (view)\n{\n m_utilsUrl = KGlobal::dirs()->findResource(\"data\", \"katepart\/script\/utils.js\");\n}\n\nKateScriptConsoleEngine::~KateScriptConsoleEngine()\n{\n \/* There's nothing to do here *\/\n}\n\nconst QString & KateScriptConsoleEngine::execute(const QString & text)\n{\n static QString msg;\n msg = \"\";\n QString name = getFirstFunctionName(text, msg);\n if (name.isEmpty() && !msg.isEmpty()) \/\/ Error\n return msg;\n\n QFile file(m_utilsUrl);\n if (!file.open(QFile::ReadOnly)) {\n msg = \"Error: can't open utils.js\";\n return msg;\n }\n QString utilsCode = file.readAll();\n file.close();\n\n QString funcCode;\n if (name.isEmpty()) { \/\/ It's a command\n name = \"foo\";\n funcCode = utilsCode + \"function foo() { \" + text + \" }\";\n } else \/\/ It's a set of functions\n funcCode = utilsCode + text;\n KateTemplateScript script(funcCode);\n msg = script.invoke(m_view, name, \"\");\n if (msg.isEmpty())\n msg = \"SyntaxError: Parse error\";\n return msg;\n}\n\nconst QString KateScriptConsoleEngine::getFirstFunctionName(const QString & text, QString & msg)\n{\n QString name = \"\";\n QRegExp reg(\"(function)\");\n int i = reg.indexIn(text);\n if (i < 0) \/\/ there's no defined functions\n return \"\";\n i += 8; \/\/ \"function\"\n for (; text[i] != '('; ++i) {\n if (text[i] == ' ') \/\/ avoid blank spaces\n continue;\n if (text[i] == '{' || text[i] == '}' || text[i] == ')') { \/\/ bad ...\n msg = \"Error: There are bad defined functions\";\n return \"\";\n }\n name.append(text[i]);\n }\n return name;\n}\n\/\/END KateScriptConsoleEngine\n\n\n\/\/BEGIN KateScriptConsole\nKateScriptConsole::KateScriptConsole(KateView * view, QWidget * parent)\n : KateViewBarWidget (true, parent)\n , m_view (view)\n{\n Q_ASSERT(m_view != NULL);\n\n initialSize = parent->size();\n layout = new QVBoxLayout();\n centralWidget()->setLayout(layout);\n layout->setMargin(0);\n hLayout = new QHBoxLayout;\n m_result = new QLabel(this);\n m_edit = new QTextEdit(this);\n m_execute = new QPushButton(i18n(\"Execute\"), this);\n m_execute->setIcon(KIcon(\"quickopen\"));\n connect(m_execute, SIGNAL(clicked()), this, SLOT(executePressed()));\n\n layout->addWidget(m_edit);\n hLayout->addWidget(m_result);\n hLayout->addWidget(m_execute, 1, Qt::AlignRight);\n layout->addLayout(hLayout);\n\n m_engine = new KateScriptConsoleEngine(m_view);\n}\n\nvoid KateScriptConsole::setupLayout()\n{\n resize(endSize);\n layout->setMargin(0);\n hLayout = new QHBoxLayout;\n layout->addWidget(m_edit);\n hLayout->addWidget(m_result);\n hLayout->addWidget(m_execute, 1, Qt::AlignRight);\n layout->addLayout(hLayout);\n}\n\nKateScriptConsole::~KateScriptConsole()\n{\n delete m_engine;\n}\n\nvoid KateScriptConsole::closed()\n{\n if (this->size() != initialSize) {\n endSize = this->size();\n layout->removeWidget(m_edit);\n hLayout->removeWidget(m_result);\n hLayout->removeWidget(m_execute);\n delete hLayout;\n resize(initialSize);\n }\n m_view->showViModeBar();\n}\n\nvoid KateScriptConsole::executePressed()\n{\n QString text = m_edit->toPlainText();\n QString msg;\n if (!text.isEmpty()) {\n msg = m_engine->execute(text);\n m_result->setText(\"<b>\" + msg + \"<\/b>\");\n } else\n m_result->setText(\"<b>There's no code to execute<\/b>\");\n}\n\/\/END KateScriptConsole\n\n\n#include \"katescriptconsole.moc\"\n\n\n\/\/ kate: space-indent on; indent-width 2; replace-tabs on;\n\n<commit_msg>Adding calls to i18n() to the Javascript Console<commit_after>\/* This file is part of the KDE libraries\n Copyright (C) 2010 Miquel Sabaté <mikisabate@gmail.com>\n\n This library is free software; you can redistribute it and\/or\n modify it under the terms of the GNU Library General Public\n License as published by the Free Software Foundation; either\n version 2 of the License, or (at your option) any later version.\n\n This library is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n Library General Public License for more details.\n\n You should have received a copy of the GNU Library General Public License\n along with this library; see the file COPYING.LIB. If not, write to\n the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,\n Boston, MA 02110-1301, USA.\n*\/\n\n\n\/\/BEGIN Includes\n\/\/ Qt\n#include <QtCore\/QFile>\n#include <QtGui\/QLabel>\n#include <QtGui\/QVBoxLayout>\n#include <QtGui\/QPushButton>\n#include <QtGui\/QTextEdit>\n\n\/\/ KDE\n#include <KStandardDirs>\n#include <KLocale>\n\n\/\/ Kate\n#include \"katescriptconsole.h\"\n#include \"katetemplatescript.h\"\n\/\/END Includes\n\n\n\/\/BEGIN KateScriptConsoleEngine\nKateScriptConsoleEngine::KateScriptConsoleEngine(KateView * view)\n : m_view (view)\n{\n m_utilsUrl = KGlobal::dirs()->findResource(\"data\", \"katepart\/script\/utils.js\");\n}\n\nKateScriptConsoleEngine::~KateScriptConsoleEngine()\n{\n \/* There's nothing to do here *\/\n}\n\nconst QString & KateScriptConsoleEngine::execute(const QString & text)\n{\n static QString msg;\n msg = \"\";\n QString name = getFirstFunctionName(text, msg);\n if (name.isEmpty() && !msg.isEmpty()) \/\/ Error\n return msg;\n\n QFile file(m_utilsUrl);\n if (!file.open(QFile::ReadOnly)) {\n msg = i18n(\"Error: can't open utils.js\");\n return msg;\n }\n QString utilsCode = file.readAll();\n file.close();\n\n QString funcCode;\n if (name.isEmpty()) { \/\/ It's a command\n name = \"foo\";\n funcCode = utilsCode + \"function foo() { \" + text + \" }\";\n } else \/\/ It's a set of functions\n funcCode = utilsCode + text;\n KateTemplateScript script(funcCode);\n msg = script.invoke(m_view, name, \"\");\n if (msg.isEmpty())\n msg = i18n(\"Syntax Error: Parse error\");\n return msg;\n}\n\nconst QString KateScriptConsoleEngine::getFirstFunctionName(const QString & text, QString & msg)\n{\n QString name = \"\";\n QRegExp reg(\"(function)\");\n int i = reg.indexIn(text);\n if (i < 0) \/\/ there's no defined functions\n return \"\";\n i += 8; \/\/ \"function\"\n for (; text[i] != '('; ++i) {\n if (text[i] == ' ') \/\/ avoid blank spaces\n continue;\n if (text[i] == '{' || text[i] == '}' || text[i] == ')') { \/\/ bad ...\n msg = i18n(\"Error: There are bad defined functions\");\n return \"\";\n }\n name.append(text[i]);\n }\n return name;\n}\n\/\/END KateScriptConsoleEngine\n\n\n\/\/BEGIN KateScriptConsole\nKateScriptConsole::KateScriptConsole(KateView * view, QWidget * parent)\n : KateViewBarWidget (true, parent)\n , m_view (view)\n{\n Q_ASSERT(m_view != NULL);\n\n initialSize = parent->size();\n layout = new QVBoxLayout();\n centralWidget()->setLayout(layout);\n layout->setMargin(0);\n hLayout = new QHBoxLayout;\n m_result = new QLabel(this);\n m_edit = new QTextEdit(this);\n m_execute = new QPushButton(i18n(\"Execute\"), this);\n m_execute->setIcon(KIcon(\"quickopen\"));\n connect(m_execute, SIGNAL(clicked()), this, SLOT(executePressed()));\n\n layout->addWidget(m_edit);\n hLayout->addWidget(m_result);\n hLayout->addWidget(m_execute, 1, Qt::AlignRight);\n layout->addLayout(hLayout);\n\n m_engine = new KateScriptConsoleEngine(m_view);\n}\n\nvoid KateScriptConsole::setupLayout()\n{\n resize(endSize);\n layout->setMargin(0);\n hLayout = new QHBoxLayout;\n layout->addWidget(m_edit);\n hLayout->addWidget(m_result);\n hLayout->addWidget(m_execute, 1, Qt::AlignRight);\n layout->addLayout(hLayout);\n}\n\nKateScriptConsole::~KateScriptConsole()\n{\n delete m_engine;\n}\n\nvoid KateScriptConsole::closed()\n{\n if (this->size() != initialSize) {\n endSize = this->size();\n layout->removeWidget(m_edit);\n hLayout->removeWidget(m_result);\n hLayout->removeWidget(m_execute);\n delete hLayout;\n resize(initialSize);\n }\n m_view->showViModeBar();\n}\n\nvoid KateScriptConsole::executePressed()\n{\n QString text = m_edit->toPlainText();\n QString msg;\n if (!text.isEmpty()) {\n msg = m_engine->execute(text);\n m_result->setText(\"<b>\" + msg + \"<\/b>\");\n } else\n m_result->setText(\"<b>\" + i18n(\"There's no code to execute\") + \"<\/b>\");\n}\n\/\/END KateScriptConsole\n\n\n#include \"katescriptconsole.moc\"\n\n\n\/\/ kate: space-indent on; indent-width 2; replace-tabs on;\n\n<|endoftext|>"} {"text":"<commit_before>#include \"gen-cpp\/simple_udt_types.h\"\n#include <thrift\/transport\/TBufferTransports.h>\n#include <thrift\/protocol\/TBinaryProtocol.h>\n#include <boost\/make_shared.hpp>\n#include <iostream>\n#include <iomanip>\n\nusing namespace apache::thrift::transport;\nusing namespace apache::thrift::protocol;\nusing boost::make_shared;\n\nint main() {\n auto trans = make_shared<TMemoryBuffer>(1024);\n auto proto = make_shared<TBinaryProtocol>(trans);\n\n EarthRelPosition ep;\n ep.latitude = 0.0;\n ep.longitude = 180.0;\n ep.elevation = 42164.0;\n\n proto->getTransport()->open();\n ep.write(proto.get());\n proto->getTransport()->flush();\n\n std::cout << \"Wrote Position: \" << std::setprecision(2) << std::fixed\n << std::setw(8) << ep.latitude\n << \", \" << std::setw(8) << ep.longitude\n << \", \" << std::setw(8) << ep.elevation << std::endl;\n\n EarthRelPosition epRead;\n epRead.read(proto.get());\n proto->getTransport()->close();\n\n std::cout << \"Read Position: \" << std::setprecision(2) << std::fixed\n << std::setw(8) << epRead.latitude\n << \", \" << std::setw(8) << epRead.longitude \n << \", \" << std::setw(8) << epRead.elevation << std::endl;\n}\n\n<commit_msg>types simple moved to std<commit_after>#include \"gen-cpp\/simple_udt_types.h\"\n#include <thrift\/transport\/TBufferTransports.h>\n#include <thrift\/protocol\/TBinaryProtocol.h>\n#include <memory>\n#include <iostream>\n#include <iomanip>\n\nusing namespace apache::thrift::transport;\nusing namespace apache::thrift::protocol;\nusing std::make_shared;\n\nint main() {\n auto trans = make_shared<TMemoryBuffer>(1024);\n auto proto = make_shared<TBinaryProtocol>(trans);\n\n EarthRelPosition ep;\n ep.latitude = 0.0;\n ep.longitude = 180.0;\n ep.elevation = 42164.0;\n\n proto->getTransport()->open();\n ep.write(proto.get());\n proto->getTransport()->flush();\n\n std::cout << \"Wrote Position: \" << std::setprecision(2) << std::fixed\n << std::setw(8) << ep.latitude\n << \", \" << std::setw(8) << ep.longitude\n << \", \" << std::setw(8) << ep.elevation << std::endl;\n\n EarthRelPosition epRead;\n epRead.read(proto.get());\n proto->getTransport()->close();\n\n std::cout << \"Read Position: \" << std::setprecision(2) << std::fixed\n << std::setw(8) << epRead.latitude\n << \", \" << std::setw(8) << epRead.longitude \n << \", \" << std::setw(8) << epRead.elevation << std::endl;\n}\n\n<|endoftext|>"} {"text":"<commit_before>#pragma once\n\n#include \"error.hpp\"\n\nnamespace uvpp\n{\n \/**\n * Class that represents the uv_loop instance.\n *\/\n class loop\n {\n public:\n \/**\n * Default constructor\n * @param use_default indicates whether to use default loop or create a new loop.\n *\/\n loop(bool use_default=false):\n m_uv_loop(use_default ? uv_default_loop() : uv_loop_new()), default_loop(use_default)\n {\n }\n\n \/**\n * Destructor\n *\/\n ~loop()\n {\n if(m_uv_loop && !default_loop)\n {\n uv_loop_delete(m_uv_loop);\n m_uv_loop = nullptr;\n }\n }\n\n loop(const loop&) = delete;\n loop& operator=(const loop&) = delete;\n loop(loop&& other):\n m_uv_loop(other.m_uv_loop)\n {\n if (this != &other)\n other.m_uv_loop = nullptr;\n }\n\n loop& operator=(loop&& other)\n {\n if (this != &other)\n {\n m_uv_loop = other.m_uv_loop;\n other.m_uv_loop = nullptr;\n }\n return *this;\n }\n\n\n\n \/**\n * Returns internal handle for libuv functions.\n *\/\n uv_loop_t* get() { return m_uv_loop; }\n\n \/**\n * Starts the loop.\n *\/\n bool run()\n {\n return uv_run(m_uv_loop, UV_RUN_DEFAULT) == 0;\n }\n\n \/**\n * Polls for new events without blocking.\n *\/\n bool run_once()\n {\n int err = uv_run(m_uv_loop, UV_RUN_ONCE);\n return err == 0;\n }\n\n \/**\n * ...\n * Internally, this function just calls uv_update_time() function.\n *\/\n void update_time() { uv_update_time(m_uv_loop); }\n\n \/**\n * ...\n * Internally, this function just calls uv_now() function.\n *\/\n int64_t now() { return uv_now(m_uv_loop); }\n\n private:\n uv_loop_t* m_uv_loop;\n bool default_loop;\n };\n\n \/**\n * Starts the default loop.\n *\/\n inline int run()\n {\n return uv_run(uv_default_loop(), UV_RUN_DEFAULT);\n }\n\n \/**\n * Polls for new events without blocking for the default loop.\n *\/\n inline int run_once()\n {\n return uv_run(uv_default_loop(), UV_RUN_ONCE);\n }\n}\n\n<commit_msg>Delete reduntant copy<commit_after>#pragma once\n\n#include \"error.hpp\"\n\nnamespace uvpp\n{\n \/**\n * Class that represents the uv_loop instance.\n *\/\n class loop\n {\n public:\n \/**\n * Default constructor\n * @param use_default indicates whether to use default loop or create a new loop.\n *\/\n loop(bool use_default=false):\n m_uv_loop(use_default ? uv_default_loop() : uv_loop_new()), default_loop(use_default)\n {\n }\n\n \/**\n * Destructor\n *\/\n ~loop()\n {\n if(m_uv_loop && !default_loop)\n {\n uv_loop_delete(m_uv_loop);\n m_uv_loop = nullptr;\n }\n }\n\n loop(const loop&) = delete;\n loop& operator=(const loop&) = delete;\n loop(loop&& other):\n m_uv_loop(other.m_uv_loop)\n {\n if (this != &other)\n other.m_uv_loop = nullptr;\n }\n\n loop& operator=(loop&& other)\n {\n if (this != &other)\n {\n m_uv_loop = other.m_uv_loop;\n other.m_uv_loop = nullptr;\n }\n return *this;\n }\n\n\n\n \/**\n * Returns internal handle for libuv functions.\n *\/\n uv_loop_t* get() { return m_uv_loop; }\n\n \/**\n * Starts the loop.\n *\/\n bool run()\n {\n return uv_run(m_uv_loop, UV_RUN_DEFAULT) == 0;\n }\n\n \/**\n * Polls for new events without blocking.\n *\/\n bool run_once()\n {\n return uv_run(m_uv_loop, UV_RUN_ONCE) == 0;\n }\n\n \/**\n * ...\n * Internally, this function just calls uv_update_time() function.\n *\/\n void update_time() { uv_update_time(m_uv_loop); }\n\n \/**\n * ...\n * Internally, this function just calls uv_now() function.\n *\/\n int64_t now() { return uv_now(m_uv_loop); }\n\n private:\n uv_loop_t* m_uv_loop;\n bool default_loop;\n };\n\n \/**\n * Starts the default loop.\n *\/\n inline int run()\n {\n return uv_run(uv_default_loop(), UV_RUN_DEFAULT);\n }\n\n \/**\n * Polls for new events without blocking for the default loop.\n *\/\n inline int run_once()\n {\n return uv_run(uv_default_loop(), UV_RUN_ONCE);\n }\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/****************************************************************************\n *\n * Copyright (C) 2017 PX4 Development Team. All rights reserved.\n * Author: @author David Sidrane <david_s5@nscdg.com>\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in\n * the documentation and\/or other materials provided with the\n * distribution.\n * 3. Neither the name PX4 nor the names of its contributors may be\n * used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS\n * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED\n * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n ****************************************************************************\/\n\n\/**\n * @file board_reset.cpp\n * Implementation of STM32 based Board RESET API\n *\/\n\n#include <px4_platform_common\/px4_config.h>\n#include <systemlib\/px4_macros.h>\n#include <errno.h>\n#include <stm32_pwr.h>\n#include <stm32_rtc.h>\n#include <nuttx\/board.h>\n\n#ifdef CONFIG_BOARDCTL_RESET\n\n\/****************************************************************************\n * Name: board_configure_reset\n *\n * Description:\n * Configures the device that maintains the state shared by the\n * application and boot loader. This is usually an RTC.\n *\n * Input Parameters:\n * mode - The type of reset. See reset_mode_e\n *\n * Returned Value:\n * 0 for Success\n * 1 if invalid argument\n *\n ****************************************************************************\/\n\nstatic const uint32_t modes[] = {\n\t\/* to tb *\/\n\t\/* BOARD_RESET_MODE_CLEAR 5 y *\/ 0,\n\t\/* BOARD_RESET_MODE_BOOT_TO_BL 0 n *\/ 0xb0070001,\n\t\/* BOARD_RESET_MODE_BOOT_TO_VALID_APP 0 y *\/ 0xb0070002,\n\t\/* BOARD_RESET_MODE_CAN_BL 10 n *\/ 0xb0080000,\n\t\/* BOARD_RESET_MODE_RTC_BOOT_FWOK 0 n *\/ 0xb0093a26\n};\n\nint board_configure_reset(reset_mode_e mode, uint32_t arg)\n{\n\tint rv = -1;\n\n\tif (mode < arraySize(modes)) {\n\n\t\tstm32_pwr_enablebkp(true);\n\n\t\targ = mode == BOARD_RESET_MODE_CAN_BL ? arg & ~0xff : 0;\n\n\t\t\/\/ Check if we can to use the new register definition\n\n#ifndef STM32_RTC_BK0R\n\t\t*(uint32_t *)STM32_BKP_BASE = modes[mode] | arg;\n#else\n\t\t*(uint32_t *)STM32_RTC_BK0R = modes[mode] | arg;\n#endif\n\t\tstm32_pwr_enablebkp(false);\n\t\trv = OK;\n\t}\n\n\treturn rv;\n}\n\n\/****************************************************************************\n * Name: board_reset\n *\n * Description:\n * Reset board. Support for this function is required by board-level\n * logic if CONFIG_BOARDCTL_RESET is selected.\n *\n * Input Parameters:\n * status - Status information provided with the reset event. This\n * meaning of this status information is board-specific. If not\n * used by a board, the value zero may be provided in calls to\n * board_reset().\n *\n * Returned Value:\n * If this function returns, then it was not possible to power-off the\n * board due to some constraints. The return value int this case is a\n * board-specific reason for the failure to shutdown.\n *\n ****************************************************************************\/\n\nint board_reset(int status)\n{\n\tif (status == 1) {\n\t\tboard_configure_reset(BOARD_RESET_MODE_BOOT_TO_BL, 0);\n\t}\n\n#if defined(BOARD_HAS_ON_RESET)\n\tboard_on_reset(status);\n#endif\n\n\tup_systemreset();\n\treturn 0;\n}\n\n#endif \/* CONFIG_BOARDCTL_RESET *\/\n\n#if defined(SUPPORT_ALT_CAN_BOOTLOADER)\n\/****************************************************************************\n * Name: board_booted_by_px4\n *\n * Description:\n * Determines if the the boot loader was PX4\n *\n * Input Parameters:\n * none\n *\n * Returned Value:\n * true if booted byt a PX4 bootloader.\n *\n ****************************************************************************\/\nbool board_booted_by_px4(void)\n{\n\tuint32_t *vectors = (uint32_t *) STM32_FLASH_BASE;\n\n\t\/* Nuttx uses common vector *\/\n\n\treturn (vectors[2] == vectors[3]) && (vectors[4] == vectors[5]);\n}\n#endif\n<commit_msg>stm32_common:board_reset Fix reboot -b broke by canbootloader<commit_after>\/****************************************************************************\n *\n * Copyright (C) 2017 PX4 Development Team. All rights reserved.\n * Author: @author David Sidrane <david_s5@nscdg.com>\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in\n * the documentation and\/or other materials provided with the\n * distribution.\n * 3. Neither the name PX4 nor the names of its contributors may be\n * used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS\n * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED\n * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n ****************************************************************************\/\n\n\/**\n * @file board_reset.cpp\n * Implementation of STM32 based Board RESET API\n *\/\n\n#include <px4_platform_common\/px4_config.h>\n#include <systemlib\/px4_macros.h>\n#include <errno.h>\n#include <stm32_pwr.h>\n#include <stm32_rtc.h>\n#include <nuttx\/board.h>\n\n#ifdef CONFIG_BOARDCTL_RESET\n\n\/****************************************************************************\n * Name: board_configure_reset\n *\n * Description:\n * Configures the device that maintains the state shared by the\n * application and boot loader. This is usually an RTC.\n *\n * Input Parameters:\n * mode - The type of reset. See reset_mode_e\n *\n * Returned Value:\n * 0 for Success\n * 1 if invalid argument\n *\n ****************************************************************************\/\n\nstatic const uint32_t modes[] = {\n\t\/* to tb *\/\n\t\/* BOARD_RESET_MODE_CLEAR 5 y *\/ 0,\n\t\/* BOARD_RESET_MODE_BOOT_TO_BL 0 n *\/ 0xb007b007,\n\t\/* BOARD_RESET_MODE_BOOT_TO_VALID_APP 0 y *\/ 0xb0070002,\n\t\/* BOARD_RESET_MODE_CAN_BL 10 n *\/ 0xb0080000,\n\t\/* BOARD_RESET_MODE_RTC_BOOT_FWOK 0 n *\/ 0xb0093a26\n};\n\nint board_configure_reset(reset_mode_e mode, uint32_t arg)\n{\n\tint rv = -1;\n\n\tif (mode < arraySize(modes)) {\n\n\t\tstm32_pwr_enablebkp(true);\n\n\t\targ = mode == BOARD_RESET_MODE_CAN_BL ? arg & ~0xff : 0;\n\n\t\t\/\/ Check if we can to use the new register definition\n\n#ifndef STM32_RTC_BK0R\n\t\t*(uint32_t *)STM32_BKP_BASE = modes[mode] | arg;\n#else\n\t\t*(uint32_t *)STM32_RTC_BK0R = modes[mode] | arg;\n#endif\n\t\tstm32_pwr_enablebkp(false);\n\t\trv = OK;\n\t}\n\n\treturn rv;\n}\n\n\/****************************************************************************\n * Name: board_reset\n *\n * Description:\n * Reset board. Support for this function is required by board-level\n * logic if CONFIG_BOARDCTL_RESET is selected.\n *\n * Input Parameters:\n * status - Status information provided with the reset event. This\n * meaning of this status information is board-specific. If not\n * used by a board, the value zero may be provided in calls to\n * board_reset().\n *\n * Returned Value:\n * If this function returns, then it was not possible to power-off the\n * board due to some constraints. The return value int this case is a\n * board-specific reason for the failure to shutdown.\n *\n ****************************************************************************\/\n\nint board_reset(int status)\n{\n\tif (status == 1) {\n\t\tboard_configure_reset(BOARD_RESET_MODE_BOOT_TO_BL, 0);\n\t}\n\n#if defined(BOARD_HAS_ON_RESET)\n\tboard_on_reset(status);\n#endif\n\n\tup_systemreset();\n\treturn 0;\n}\n\n#endif \/* CONFIG_BOARDCTL_RESET *\/\n\n#if defined(SUPPORT_ALT_CAN_BOOTLOADER)\n\/****************************************************************************\n * Name: board_booted_by_px4\n *\n * Description:\n * Determines if the the boot loader was PX4\n *\n * Input Parameters:\n * none\n *\n * Returned Value:\n * true if booted byt a PX4 bootloader.\n *\n ****************************************************************************\/\nbool board_booted_by_px4(void)\n{\n\tuint32_t *vectors = (uint32_t *) STM32_FLASH_BASE;\n\n\t\/* Nuttx uses common vector *\/\n\n\treturn (vectors[2] == vectors[3]) && (vectors[4] == vectors[5]);\n}\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/*\n * \\copyright Copyright 2014 Xiang Zhang All Rights Reserved.\n * \\license @{\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n * @}\n *\/\n\n#ifndef THUNDER_LINALG_LINALG_HPP_\n#define THUNDER_LINALG_LINALG_HPP_\n\nnamespace thunder {\nnamespace linalg {\n\n} \/\/ namespace linalg\n} \/\/ namespace thunder\n\n#endif \/\/ THUNDER_LINALG_LINALG_HPP_\n<commit_msg>Added a portion of blas level-1 and level-2 functions<commit_after>\/*\n * \\copyright Copyright 2014 Xiang Zhang All Rights Reserved.\n * \\license @{\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n * @}\n *\/\n\n#ifndef THUNDER_LINALG_LINALG_HPP_\n#define THUNDER_LINALG_LINALG_HPP_\n\n#include \"thunder\/tensor.hpp\"\n\nnamespace thunder {\nnamespace linalg {\n\ntemplate < typename T = DoubleTensor, typename H = int >\nclass Linalg {\n public:\n typedef typename T::value_type value_type;\n typedef typename T::size_type size_type;\n \n Linalg();\n template < typename... G >\n Linalg(G... g);\n ~Linalg();\n \n \/\/ Const result BLAS level-1 routines\n const T& asum(const T &x, const T &r);\n const T& axpy(const value_type &a, const T &x, const T &y, const T &r);\n const T& copy(const T &x, const T &y);\n const T& dot(const T &x, const T &y, const T &r);\n const T& sdot(const T &x, const T &y, const T &r);\n const T& dotc(const T &x, const T &y, const T &r);\n const T& nrm2(const T &x, const T &r);\n const T& rot(const T &x, const T &y, const value_type &c,\n const value_type &s);\n const T& rotm(const T &x, const T &y, const T &P);\n const T& scal(const value_type &a, const T &x);\n const T& swap(const T &x, const T &y);\n const SizeTensor& iamax(const T &x, const SizeTensor &r);\n const SizeTensor& iamin(const T &x, const SizeTensor &r);\n const T& cabs1(const T &x);\n\n \/\/ Const result BLAS level-2 routines\n const T& gbmv(size_type kl, size_type ku, const value_type &alpha, const T &a,\n const T &x, const value_type &beta, const T&y);\n const T& gemv(const value_type &alpha, const T &a, const T &x,\n const value_type &beta, const T &y);\n const T& ger(const value_type &alpha, const T &x, const T &y, const T &a);\n const T& gerc(const value_type &alpha, const T &x, const T &y, const T &a);\n};\n\n} \/\/ namespace linalg\n} \/\/ namespace thunder\n\n#endif \/\/ THUNDER_LINALG_LINALG_HPP_\n<|endoftext|>"} {"text":"<commit_before>#include <windows.h>\n#include <iostream>\n\n#pragma comment(linker,\"\/manifestdependency:\\\"type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='x86' publicKeyToken='6595b64144ccf1df' language='*'\\\"\")\n\n\/\/Global variables\nRECT rect;\nHWND hWnd;\nHWND hWndEdit;\n\n\/\/Declaring used methods.\nvoid getWindowSize();\n\n\/\/Handling uncaught exceptions.\nLRESULT CALLBACK WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)\n{\n\tif (msg == WM_SIZE) {\n\t\tgetWindowSize();\n\t\t\/\/The magic numbers 16 and 39 are the adjustments for the window bars.\n\t\tSetWindowPos(hWndEdit, NULL, 0, 0, ((rect.right - rect.left) - 16), ((rect.bottom - rect.top) - 39), NULL);\n\t}\n\n\tswitch (msg)\n\t{\n\tcase WM_CLOSE:\n\t\tDestroyWindow(hWnd);\n\tcase WM_DESTROY:\n\t\tPostQuitMessage(EXIT_SUCCESS);\n\tdefault:\n\t\treturn DefWindowProc(hWnd, msg, wParam, lParam);\n\t}\n\treturn FALSE;\n}\n\n\/\/The main entry point for the program.\nint WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,\n\tLPSTR nCmdLine, int nCmdShow)\n{\n\tLPTSTR windowClass = TEXT(\"ProjectHowlApp\");\n\tLPTSTR windowTitle = TEXT(\"ProjectHowl\");\n\tWNDCLASSEX wcex;\n\n\twcex.cbClsExtra = 0;\n\twcex.cbSize = sizeof(WNDCLASSEX);\n\twcex.cbWndExtra = 0;\n\twcex.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);\n\twcex.hCursor = LoadCursor(NULL, IDC_ARROW);\n\twcex.hIcon = LoadIcon(NULL, IDI_APPLICATION);\n\twcex.hIconSm = LoadIcon(NULL, IDI_APPLICATION);\n\twcex.hInstance = hInstance;\n\twcex.lpfnWndProc = WndProc;\n\twcex.lpszClassName = windowClass;\n\twcex.lpszMenuName = NULL;\n\twcex.style = CS_HREDRAW | CS_VREDRAW;\n\n\t\/\/Registering the window. Will exit gracefully if failed.\n\tif (!RegisterClassEx(&wcex))\n\t{\n\t\tMessageBox(NULL, TEXT(\"RegisterClassEx Failed!\"), TEXT(\"Error\"),\n\t\t\tMB_ICONERROR);\n\t\treturn EXIT_FAILURE;\n\t}\n\n\t\/\/Creating main window and exiting gracefully if exceptions occur.\n\tif (!(hWnd = CreateWindow(windowClass, windowTitle, WS_OVERLAPPEDWINDOW,\n\t\tCW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT,\n\t\tCW_USEDEFAULT, NULL, NULL, hInstance, NULL)))\n\t{\n\t\tMessageBox(NULL, TEXT(\"CreateWindow Failed!\"), TEXT(\"Error\"), MB_ICONERROR);\n\t\treturn EXIT_FAILURE;\n\t}\n\n\tgetWindowSize();\n\n\t\/\/Creating inner editing window.\n\thWndEdit = CreateWindowEx(WS_EX_CLIENTEDGE, TEXT(\"Edit\"), TEXT(\"Start Writing...\"),\n\t\tWS_CHILD | WS_VISIBLE | ES_WANTRETURN, 0, 0, 0, 0, hWnd, NULL, NULL, NULL);\n\n\tShowWindow(hWnd, nCmdShow);\n\tUpdateWindow(hWnd);\n\n\t\/\/Structure to hold message.\n\tMSG msg;\n\n\t\/\/Loop to handle events.\n\twhile (GetMessage(&msg, NULL, 0, 0))\n\t{\n\t\tTranslateMessage(&msg);\n\t\tDispatchMessage(&msg);\n\t}\n\treturn EXIT_SUCCESS;\n}\n\nvoid getWindowSize() {\n\tif (GetWindowRect(hWnd, &rect) == false) {\n\t\tstd::cout << \"Error getting the windows size.\\n\";\n\t}\n}\n<commit_msg>Reorganized code for easier readability and added edit control styles to hWndEdit to make it multi-line.<commit_after>#include <windows.h>\n#include <iostream>\n\n#pragma comment(linker,\"\/manifestdependency:\\\"type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='x86' publicKeyToken='6595b64144ccf1df' language='*'\\\"\")\n\n\/\/Global variables\nRECT rect;\nHWND hWnd;\nHWND hWndEdit;\n\n\/\/Declaring used methods.\nvoid getWindowSize();\n\n\/\/Handling uncaught exceptions.\nLRESULT CALLBACK WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)\n{\n\tif (msg == WM_SIZE) {\n\t\tgetWindowSize();\n\t\t\/\/The magic numbers 16 and 39 are the adjustments for the window bars.\n\t\tSetWindowPos(hWndEdit, NULL, 0, 0, ((rect.right - rect.left) - 16), ((rect.bottom - rect.top) - 39), NULL);\n\t}\n\n\tswitch (msg) {\n\tcase WM_CLOSE:\n\t\tDestroyWindow(hWnd);\n\tcase WM_DESTROY:\n\t\tPostQuitMessage(EXIT_SUCCESS);\n\tdefault:\n\t\treturn DefWindowProc(hWnd, msg, wParam, lParam);\n\t}\n\treturn FALSE;\n}\n\n\/\/The main entry point for the program.\nint WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,\n\tLPSTR nCmdLine, int nCmdShow) \n{\n\tLPTSTR windowClass = TEXT(\"ProjectHowlApp\");\n\tLPTSTR windowTitle = TEXT(\"ProjectHowl\");\n\tWNDCLASSEX wcex;\n\n\twcex.cbClsExtra = 0;\n\twcex.cbSize = sizeof(WNDCLASSEX);\n\twcex.cbWndExtra = 0;\n\twcex.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);\n\twcex.hCursor = LoadCursor(NULL, IDC_ARROW);\n\twcex.hIcon = LoadIcon(NULL, IDI_APPLICATION);\n\twcex.hIconSm = LoadIcon(NULL, IDI_APPLICATION);\n\twcex.hInstance = hInstance;\n\twcex.lpfnWndProc = WndProc;\n\twcex.lpszClassName = windowClass;\n\twcex.lpszMenuName = NULL;\n\twcex.style = CS_HREDRAW | CS_VREDRAW;\n\n\t\/\/Registering the window. Will exit gracefully if failed.\n\tif (!RegisterClassEx(&wcex)) {\n\t\tMessageBox(NULL, TEXT(\"RegisterClassEx Failed!\"), TEXT(\"Error\"),\n\t\t\tMB_ICONERROR);\n\t\treturn EXIT_FAILURE;\n\t}\n\n\t\/\/Creating main window and exiting gracefully if exceptions occur.\n\tif (!(hWnd = CreateWindow(windowClass, windowTitle, WS_OVERLAPPEDWINDOW,\n\t\tCW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT,\n\t\tCW_USEDEFAULT, NULL, NULL, hInstance, NULL)))\n\t{\n\t\tMessageBox(NULL, TEXT(\"CreateWindow Failed!\"), TEXT(\"Error\"), MB_ICONERROR);\n\t\treturn EXIT_FAILURE;\n\t}\n\n\tgetWindowSize();\n\n\t\/\/Creating inner editing window.\n\thWndEdit = CreateWindowEx(WS_EX_CLIENTEDGE, TEXT(\"EDIT\"), TEXT(\"Start Writing Motherfucker...\"),\n\t\tWS_CHILD | WS_VISIBLE | ES_WANTRETURN | WS_VSCROLL | ES_LEFT | ES_MULTILINE | ES_AUTOHSCROLL,\n\t\t0, 0, 0, 0, hWnd, NULL, NULL, NULL);\n\n\tShowWindow(hWnd, nCmdShow);\n\tUpdateWindow(hWnd);\n\n\t\/\/Structure to hold message.\n\tMSG msg;\n\n\t\/\/Loop to handle events.\n\twhile (GetMessage(&msg, NULL, 0, 0)) {\n\t\tTranslateMessage(&msg);\n\t\tDispatchMessage(&msg);\n\t}\n\treturn EXIT_SUCCESS;\n}\n\nvoid getWindowSize() {\n\t\/\/Get size of the window called hWnd and store in RECT rect.\n\tif (GetWindowRect(hWnd, &rect) == false) {\n\t\tstd::cout << \"Error getting the windows size.\\n\";\n\t}\n}<|endoftext|>"} {"text":"<commit_before>\/*\n * Software License Agreement (BSD License)\n *\n * Point Cloud Library (PCL) - www.pointclouds.org\n * Copyright (c) 2010-2011, Willow Garage, Inc.\n *\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following\n * disclaimer in the documentation and\/or other materials provided\n * with the distribution.\n * * Neither the name of Willow Garage, Inc. nor the names of its\n * contributors may be used to endorse or promote products derived\n * from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n * $Id$\n *\n *\/\n\n#ifndef PCL_FEATURES_IMPL_INTENSITY_GRADIENT_H_\n#define PCL_FEATURES_IMPL_INTENSITY_GRADIENT_H_\n\n#include <pcl\/features\/intensity_gradient.h>\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate <typename PointInT, typename PointNT, typename PointOutT, typename IntensitySelectorT> void\npcl::IntensityGradientEstimation <PointInT, PointNT, PointOutT, IntensitySelectorT>::computePointIntensityGradient (\n const pcl::PointCloud <PointInT> &cloud, const std::vector <int> &indices,\n const Eigen::Vector3f &point, float mean_intensity, const Eigen::Vector3f &normal, Eigen::Vector3f &gradient)\n{\n if (indices.size () < 3)\n {\n gradient[0] = gradient[1] = gradient[2] = std::numeric_limits<float>::quiet_NaN ();\n return;\n }\n\n Eigen::Matrix3f A = Eigen::Matrix3f::Zero ();\n Eigen::Vector3f b = Eigen::Vector3f::Zero ();\n\n for (size_t i_point = 0; i_point < indices.size (); ++i_point)\n {\n PointInT p = cloud.points[indices[i_point]];\n if (!pcl_isfinite (p.x) ||\n !pcl_isfinite (p.y) ||\n !pcl_isfinite (p.z) ||\n !pcl_isfinite (intensity_ (p)))\n continue;\n\n p.x -= point[0];\n p.y -= point[1];\n p.z -= point[2];\n intensity_.demean (p, mean_intensity);\n\n A (0, 0) += p.x * p.x;\n A (0, 1) += p.x * p.y;\n A (0, 2) += p.x * p.z;\n\n A (1, 1) += p.y * p.y;\n A (1, 2) += p.y * p.z;\n\n A (2, 2) += p.z * p.z;\n\n b[0] += p.x * intensity_ (p);\n b[1] += p.y * intensity_ (p);\n b[2] += p.z * intensity_ (p);\n }\n \/\/ Fill in the lower triangle of A\n A (1, 0) = A (0, 1);\n A (2, 0) = A (0, 2);\n A (2, 1) = A (1, 2);\n\n\/\/*\n Eigen::Vector3f x = A.colPivHouseholderQr ().solve (b);\n\/*\/\n\n Eigen::Vector3f eigen_values;\n Eigen::Matrix3f eigen_vectors;\n eigen33 (A, eigen_vectors, eigen_values);\n\n b = eigen_vectors.transpose () * b;\n\n if ( eigen_values (0) != 0)\n b (0) \/= eigen_values (0);\n else\n b (0) = 0;\n\n if ( eigen_values (1) != 0)\n b (1) \/= eigen_values (1);\n else\n b (1) = 0;\n\n if ( eigen_values (2) != 0)\n b (2) \/= eigen_values (2);\n else\n b (2) = 0;\n\n\n Eigen::Vector3f x = eigen_vectors * b;\n\n\/\/ if (A.col (0).squaredNorm () != 0)\n\/\/ x [0] \/= A.col (0).squaredNorm ();\n\/\/ b -= x [0] * A.col (0);\n\/\/\n\/\/\n\/\/ if (A.col (1).squaredNorm () != 0)\n\/\/ x [1] \/= A.col (1).squaredNorm ();\n\/\/ b -= x[1] * A.col (1);\n\/\/\n\/\/ x [2] = b.dot (A.col (2));\n\/\/ if (A.col (2).squaredNorm () != 0)\n\/\/ x[2] \/= A.col (2).squaredNorm ();\n \/\/ Fit a hyperplane to the data\n\n\/\/*\/\n\/\/ std::cout << A << \"\\n*\\n\" << bb << \"\\n=\\n\" << x << \"\\nvs.\\n\" << x2 << \"\\n\\n\";\n\/\/ std::cout << A * x << \"\\nvs.\\n\" << A * x2 << \"\\n\\n------\\n\";\n \/\/ Project the gradient vector, x, onto the tangent plane\n gradient = (Eigen::Matrix3f::Identity () - normal*normal.transpose ()) * x;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate <typename PointInT, typename PointNT, typename PointOutT, typename IntensitySelectorT> void\npcl::IntensityGradientEstimation<PointInT, PointNT, PointOutT, IntensitySelectorT>::computeFeature (PointCloudOut &output)\n{\n \/\/ Allocate enough space to hold the results\n \/\/ \\note This resize is irrelevant for a radiusSearch ().\n std::vector<int> nn_indices (k_);\n std::vector<float> nn_dists (k_);\n output.is_dense = true;\n\n#ifdef HAVE_OPENMP\n#ifdef __APPLE__\n#pragma omp parallel for schedule(static, threads_)\n#else\n#pragma omp parallel for shared (output) private (nn_indices, nn_dists) num_threads(threads_)\n#endif\n#endif\n \/\/ Iterating over the entire index vector\n for (int idx = 0; idx < static_cast<int> (indices_->size ()); ++idx)\n {\n PointOutT &p_out = output.points[idx];\n\n if (!this->searchForNeighbors ((*indices_)[idx], search_parameter_, nn_indices, nn_dists))\n {\n p_out.gradient[0] = p_out.gradient[1] = p_out.gradient[2] = std::numeric_limits<float>::quiet_NaN ();\n output.is_dense = false;\n continue;\n }\n\n Eigen::Vector3f centroid;\n float mean_intensity = 0;\n \/\/ Initialize to 0\n centroid.setZero ();\n \/\/ If the data is dense, we don't need to check for NaN\n if (surface_->is_dense)\n {\n for (size_t i = 0; i < nn_indices.size (); ++i)\n {\n centroid += surface_->points[nn_indices[i]].getVector3fMap ();\n mean_intensity += intensity_ (surface_->points[nn_indices[i]]);\n }\n centroid \/= static_cast<float> (nn_indices.size ());\n mean_intensity \/= static_cast<float> (nn_indices.size ());\n }\n \/\/ NaN or Inf values could exist => check for them\n else\n {\n unsigned cp = 0;\n for (size_t i = 0; i < nn_indices.size (); ++i)\n {\n \/\/ Check if the point is invalid\n if (!isFinite ((*surface_) [nn_indices[i]]))\n continue;\n\n centroid += surface_->points [nn_indices[i]].getVector3fMap ();\n mean_intensity += intensity_ (surface_->points [nn_indices[i]]);\n ++cp;\n }\n centroid \/= static_cast<float> (cp);\n mean_intensity \/= static_cast<float> (cp);\n }\n\n Eigen::Vector3f normal = Eigen::Vector3f::Map (normals_->points[(*indices_) [idx]].normal);\n Eigen::Vector3f gradient;\n computePointIntensityGradient (*surface_, nn_indices, centroid, mean_intensity, normal, gradient);\n\n p_out.gradient[0] = gradient[0];\n p_out.gradient[1] = gradient[1];\n p_out.gradient[2] = gradient[2];\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate <typename PointInT, typename PointNT> void\npcl::IntensityGradientEstimation<PointInT, PointNT, Eigen::MatrixXf>::computeFeatureEigen (pcl::PointCloud<Eigen::MatrixXf> &output)\n{\n \/\/ Resize the output dataset\n output.points.resize (indices_->size (), 3);\n\n \/\/ Allocate enough space to hold the results\n \/\/ \\note This resize is irrelevant for a radiusSearch ().\n std::vector<int> nn_indices (k_);\n std::vector<float> nn_dists (k_);\n\n output.is_dense = true;\n \/\/ Iterating over the entire index vector\n for (size_t idx = 0; idx < indices_->size (); ++idx)\n {\n if (this->searchForNeighbors ((*indices_)[idx], search_parameter_, nn_indices, nn_dists) == 0)\n {\n output.points.row (idx).setConstant (std::numeric_limits<float>::quiet_NaN ());\n output.is_dense = false;\n continue;\n }\n\n Eigen::Vector4f centroid;\n compute3DCentroid (*surface_, nn_indices, centroid);\n\n float mean_intensity = 0;\n unsigned valid_neighbor_count = 0;\n for (size_t nIdx = 0; nIdx < nn_indices.size (); ++nIdx)\n {\n const PointInT& p = (*surface_)[nn_indices[nIdx]];\n if (!pcl_isfinite (p.intensity))\n continue;\n\n mean_intensity += p.intensity;\n ++valid_neighbor_count;\n }\n\n mean_intensity \/= static_cast<float> (valid_neighbor_count);\n\n Eigen::Vector3f normal = Eigen::Vector3f::Map (normals_->points[idx].normal);\n Eigen::Vector3f gradient;\n this->computePointIntensityGradient (*surface_, nn_indices, centroid.head<3> (), mean_intensity, normal, gradient);\n\n output.points (idx, 0) = gradient[0];\n output.points (idx, 1) = gradient[1];\n output.points (idx, 2) = gradient[2];\n }\n}\n\n\n#define PCL_INSTANTIATE_IntensityGradientEstimation(InT,NT,OutT) template class PCL_EXPORTS pcl::IntensityGradientEstimation<InT,NT,OutT>;\n\n#endif \/\/ PCL_FEATURES_IMPL_INTENSITY_GRADIENT_H_\n<commit_msg>Fix: if the cloud is not dense search for neighbours could raise an excpetion<commit_after>\/*\n * Software License Agreement (BSD License)\n *\n * Point Cloud Library (PCL) - www.pointclouds.org\n * Copyright (c) 2010-2011, Willow Garage, Inc.\n *\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following\n * disclaimer in the documentation and\/or other materials provided\n * with the distribution.\n * * Neither the name of Willow Garage, Inc. nor the names of its\n * contributors may be used to endorse or promote products derived\n * from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n * $Id$\n *\n *\/\n\n#ifndef PCL_FEATURES_IMPL_INTENSITY_GRADIENT_H_\n#define PCL_FEATURES_IMPL_INTENSITY_GRADIENT_H_\n\n#include <pcl\/features\/intensity_gradient.h>\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate <typename PointInT, typename PointNT, typename PointOutT, typename IntensitySelectorT> void\npcl::IntensityGradientEstimation <PointInT, PointNT, PointOutT, IntensitySelectorT>::computePointIntensityGradient (\n const pcl::PointCloud <PointInT> &cloud, const std::vector <int> &indices,\n const Eigen::Vector3f &point, float mean_intensity, const Eigen::Vector3f &normal, Eigen::Vector3f &gradient)\n{\n if (indices.size () < 3)\n {\n gradient[0] = gradient[1] = gradient[2] = std::numeric_limits<float>::quiet_NaN ();\n return;\n }\n\n Eigen::Matrix3f A = Eigen::Matrix3f::Zero ();\n Eigen::Vector3f b = Eigen::Vector3f::Zero ();\n\n for (size_t i_point = 0; i_point < indices.size (); ++i_point)\n {\n PointInT p = cloud.points[indices[i_point]];\n if (!pcl_isfinite (p.x) ||\n !pcl_isfinite (p.y) ||\n !pcl_isfinite (p.z) ||\n !pcl_isfinite (intensity_ (p)))\n continue;\n\n p.x -= point[0];\n p.y -= point[1];\n p.z -= point[2];\n intensity_.demean (p, mean_intensity);\n\n A (0, 0) += p.x * p.x;\n A (0, 1) += p.x * p.y;\n A (0, 2) += p.x * p.z;\n\n A (1, 1) += p.y * p.y;\n A (1, 2) += p.y * p.z;\n\n A (2, 2) += p.z * p.z;\n\n b[0] += p.x * intensity_ (p);\n b[1] += p.y * intensity_ (p);\n b[2] += p.z * intensity_ (p);\n }\n \/\/ Fill in the lower triangle of A\n A (1, 0) = A (0, 1);\n A (2, 0) = A (0, 2);\n A (2, 1) = A (1, 2);\n\n\/\/*\n Eigen::Vector3f x = A.colPivHouseholderQr ().solve (b);\n\/*\/\n\n Eigen::Vector3f eigen_values;\n Eigen::Matrix3f eigen_vectors;\n eigen33 (A, eigen_vectors, eigen_values);\n\n b = eigen_vectors.transpose () * b;\n\n if ( eigen_values (0) != 0)\n b (0) \/= eigen_values (0);\n else\n b (0) = 0;\n\n if ( eigen_values (1) != 0)\n b (1) \/= eigen_values (1);\n else\n b (1) = 0;\n\n if ( eigen_values (2) != 0)\n b (2) \/= eigen_values (2);\n else\n b (2) = 0;\n\n\n Eigen::Vector3f x = eigen_vectors * b;\n\n\/\/ if (A.col (0).squaredNorm () != 0)\n\/\/ x [0] \/= A.col (0).squaredNorm ();\n\/\/ b -= x [0] * A.col (0);\n\/\/\n\/\/\n\/\/ if (A.col (1).squaredNorm () != 0)\n\/\/ x [1] \/= A.col (1).squaredNorm ();\n\/\/ b -= x[1] * A.col (1);\n\/\/\n\/\/ x [2] = b.dot (A.col (2));\n\/\/ if (A.col (2).squaredNorm () != 0)\n\/\/ x[2] \/= A.col (2).squaredNorm ();\n \/\/ Fit a hyperplane to the data\n\n\/\/*\/\n\/\/ std::cout << A << \"\\n*\\n\" << bb << \"\\n=\\n\" << x << \"\\nvs.\\n\" << x2 << \"\\n\\n\";\n\/\/ std::cout << A * x << \"\\nvs.\\n\" << A * x2 << \"\\n\\n------\\n\";\n \/\/ Project the gradient vector, x, onto the tangent plane\n gradient = (Eigen::Matrix3f::Identity () - normal*normal.transpose ()) * x;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate <typename PointInT, typename PointNT, typename PointOutT, typename IntensitySelectorT> void\npcl::IntensityGradientEstimation<PointInT, PointNT, PointOutT, IntensitySelectorT>::computeFeature (PointCloudOut &output)\n{\n \/\/ Allocate enough space to hold the results\n \/\/ \\note This resize is irrelevant for a radiusSearch ().\n std::vector<int> nn_indices (k_);\n std::vector<float> nn_dists (k_);\n output.is_dense = true;\n\n \/\/ If the data is dense, we don't need to check for NaN\n if (surface_->is_dense)\n {\n#if defined (HAVE_OPENMP) && (defined(_WIN32) || ((__GNUC__ > 4) && (__GNUC_MINOR__ > 2)))\n#pragma omp parallel for shared (output) private (nn_indices, nn_dists) num_threads(threads_)\n#endif\n \/\/ Iterating over the entire index vector\n for (int idx = 0; idx < static_cast<int> (indices_->size ()); ++idx)\n {\n PointOutT &p_out = output.points[idx];\n\n if (!this->searchForNeighbors ((*indices_)[idx], search_parameter_, nn_indices, nn_dists))\n {\n p_out.gradient[0] = p_out.gradient[1] = p_out.gradient[2] = std::numeric_limits<float>::quiet_NaN ();\n output.is_dense = false;\n continue;\n }\n\n Eigen::Vector3f centroid;\n float mean_intensity = 0;\n \/\/ Initialize to 0\n centroid.setZero ();\n for (size_t i = 0; i < nn_indices.size (); ++i)\n {\n centroid += surface_->points[nn_indices[i]].getVector3fMap ();\n mean_intensity += intensity_ (surface_->points[nn_indices[i]]);\n }\n centroid \/= static_cast<float> (nn_indices.size ());\n mean_intensity \/= static_cast<float> (nn_indices.size ());\n\n Eigen::Vector3f normal = Eigen::Vector3f::Map (normals_->points[(*indices_) [idx]].normal);\n Eigen::Vector3f gradient;\n computePointIntensityGradient (*surface_, nn_indices, centroid, mean_intensity, normal, gradient);\n\n p_out.gradient[0] = gradient[0];\n p_out.gradient[1] = gradient[1];\n p_out.gradient[2] = gradient[2];\n }\n }\n else\n {\n#if defined (HAVE_OPENMP) && (defined(_WIN32) || ((__GNUC__ > 4) && (__GNUC_MINOR__ > 2)))\n#pragma omp parallel for shared (output) private (nn_indices, nn_dists) num_threads(threads_)\n#endif\n \/\/ Iterating over the entire index vector\n for (int idx = 0; idx < static_cast<int> (indices_->size ()); ++idx)\n {\n PointOutT &p_out = output.points[idx];\n if (!isFinite ((*surface_) [(*indices_)[idx]]) ||\n !this->searchForNeighbors ((*indices_)[idx], search_parameter_, nn_indices, nn_dists))\n {\n p_out.gradient[0] = p_out.gradient[1] = p_out.gradient[2] = std::numeric_limits<float>::quiet_NaN ();\n output.is_dense = false;\n continue;\n }\n Eigen::Vector3f centroid;\n float mean_intensity = 0;\n \/\/ Initialize to 0\n centroid.setZero ();\n unsigned cp = 0;\n for (size_t i = 0; i < nn_indices.size (); ++i)\n {\n \/\/ Check if the point is invalid\n if (!isFinite ((*surface_) [nn_indices[i]]))\n continue;\n\n centroid += surface_->points [nn_indices[i]].getVector3fMap ();\n mean_intensity += intensity_ (surface_->points [nn_indices[i]]);\n ++cp;\n }\n centroid \/= static_cast<float> (cp);\n mean_intensity \/= static_cast<float> (cp);\n Eigen::Vector3f normal = Eigen::Vector3f::Map (normals_->points[(*indices_) [idx]].normal);\n Eigen::Vector3f gradient;\n computePointIntensityGradient (*surface_, nn_indices, centroid, mean_intensity, normal, gradient);\n\n p_out.gradient[0] = gradient[0];\n p_out.gradient[1] = gradient[1];\n p_out.gradient[2] = gradient[2];\n }\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ntemplate <typename PointInT, typename PointNT> void\npcl::IntensityGradientEstimation<PointInT, PointNT, Eigen::MatrixXf>::computeFeatureEigen (pcl::PointCloud<Eigen::MatrixXf> &output)\n{\n \/\/ Resize the output dataset\n output.points.resize (indices_->size (), 3);\n\n \/\/ Allocate enough space to hold the results\n \/\/ \\note This resize is irrelevant for a radiusSearch ().\n std::vector<int> nn_indices (k_);\n std::vector<float> nn_dists (k_);\n\n output.is_dense = true;\n \/\/ Iterating over the entire index vector\n for (size_t idx = 0; idx < indices_->size (); ++idx)\n {\n if (this->searchForNeighbors ((*indices_)[idx], search_parameter_, nn_indices, nn_dists) == 0)\n {\n output.points.row (idx).setConstant (std::numeric_limits<float>::quiet_NaN ());\n output.is_dense = false;\n continue;\n }\n\n Eigen::Vector4f centroid;\n compute3DCentroid (*surface_, nn_indices, centroid);\n\n float mean_intensity = 0;\n unsigned valid_neighbor_count = 0;\n for (size_t nIdx = 0; nIdx < nn_indices.size (); ++nIdx)\n {\n const PointInT& p = (*surface_)[nn_indices[nIdx]];\n if (!pcl_isfinite (p.intensity))\n continue;\n\n mean_intensity += p.intensity;\n ++valid_neighbor_count;\n }\n\n mean_intensity \/= static_cast<float> (valid_neighbor_count);\n\n Eigen::Vector3f normal = Eigen::Vector3f::Map (normals_->points[idx].normal);\n Eigen::Vector3f gradient;\n this->computePointIntensityGradient (*surface_, nn_indices, centroid.head<3> (), mean_intensity, normal, gradient);\n\n output.points (idx, 0) = gradient[0];\n output.points (idx, 1) = gradient[1];\n output.points (idx, 2) = gradient[2];\n }\n}\n\n\n#define PCL_INSTANTIATE_IntensityGradientEstimation(InT,NT,OutT) template class PCL_EXPORTS pcl::IntensityGradientEstimation<InT,NT,OutT>;\n\n#endif \/\/ PCL_FEATURES_IMPL_INTENSITY_GRADIENT_H_\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (C) 2015 Cloudius Systems, Ltd.\n *\/\n\n#include \"murmur3_partitioner.hh\"\n#include \"utils\/murmur_hash.hh\"\n#include \"sstables\/key.hh\"\n#include \"utils\/class_registrator.hh\"\n\nnamespace dht {\n\ninline\nint64_t\nmurmur3_partitioner::normalize(int64_t in) {\n return in == std::numeric_limits<int64_t>::lowest()\n ? std::numeric_limits<int64_t>::max()\n : in;\n}\n\ntoken\nmurmur3_partitioner::get_token(bytes_view key) {\n if (key.empty()) {\n return minimum_token();\n }\n std::array<uint64_t, 2> hash;\n utils::murmur_hash::hash3_x64_128(key, 0, hash);\n return get_token(hash[0]);\n}\n\ntoken\nmurmur3_partitioner::get_token(uint64_t value) const {\n \/\/ We don't normalize() the value, since token includes an is-before-everything\n \/\/ indicator.\n \/\/ FIXME: will this require a repair when importing a database?\n auto t = net::hton(normalize(value));\n bytes b(bytes::initialized_later(), 8);\n std::copy_n(reinterpret_cast<int8_t*>(&t), 8, b.begin());\n return token{token::kind::key, std::move(b)};\n}\n\ntoken\nmurmur3_partitioner::get_token(const sstables::key_view& key) {\n return get_token(bytes_view(key));\n}\n\ntoken\nmurmur3_partitioner::get_token(const schema& s, partition_key_view key) {\n std::array<uint64_t, 2> hash;\n auto&& legacy = key.legacy_form(s);\n utils::murmur_hash::hash3_x64_128(legacy.begin(), legacy.size(), 0, hash);\n return get_token(hash[0]);\n}\n\ntoken murmur3_partitioner::get_random_token() {\n auto rand = dht::get_random_number<uint64_t>();\n return get_token(rand);\n}\n\ninline long long_token(const token& t) {\n\n if (t._data.size() != sizeof(long)) {\n throw runtime_exception(sprint(\"Invalid token. Should have size %ld, has size %ld\\n\", sizeof(long), t._data.size()));\n }\n\n auto ptr = t._data.begin();\n auto lp = unaligned_cast<const long *>(ptr);\n return net::ntoh(*lp);\n}\n\nsstring murmur3_partitioner::to_sstring(const token& t) const {\n return ::to_sstring(long_token(t));\n}\n\nint murmur3_partitioner::tri_compare(const token& t1, const token& t2) {\n long l1 = long_token(t1);\n long l2 = long_token(t2);\n\n if (l1 == l2) {\n return 0;\n } else {\n return l1 < l2 ? -1 : 1;\n }\n}\n\ntoken murmur3_partitioner::midpoint(const token& t1, const token& t2) const {\n auto l1 = long_token(t1);\n auto l2 = long_token(t2);\n \/\/ long_token is defined as signed, but the arithmetic works out the same\n \/\/ without invoking undefined behavior with a signed type.\n auto delta = (uint64_t(l2) - uint64_t(l1)) \/ 2;\n if (l1 > l2) {\n \/\/ wraparound\n delta += 0x8000'0000'0000'0000;\n }\n auto mid = uint64_t(l1) + delta;\n return get_token(mid);\n}\n\nstd::map<token, float>\nmurmur3_partitioner::describe_ownership(const std::vector<token>& sorted_tokens) {\n abort();\n}\n\ndata_type\nmurmur3_partitioner::get_token_validator() {\n return long_type;\n}\n\nunsigned\nmurmur3_partitioner::shard_of(const token& t) const {\n int64_t l = long_token(t);\n \/\/ treat l as a fraction between 0 and 1 and use 128-bit arithmetic to\n \/\/ divide that range evenly among shards:\n uint64_t adjusted = uint64_t(l) + uint64_t(std::numeric_limits<int64_t>::min());\n return (__int128(adjusted) * smp::count) >> 64;\n}\n\nusing registry = class_registrator<i_partitioner, murmur3_partitioner>;\nstatic registry registrator(\"org.apache.cassandra.dht.Murmur3Partitioner\");\nstatic registry registrator_short_name(\"Murmur3Partitioner\");\n\n}\n\n\n<commit_msg>murmur3 partitioner: explicitly use int64_t instead of long<commit_after>\/*\n * Copyright (C) 2015 Cloudius Systems, Ltd.\n *\/\n\n#include \"murmur3_partitioner.hh\"\n#include \"utils\/murmur_hash.hh\"\n#include \"sstables\/key.hh\"\n#include \"utils\/class_registrator.hh\"\n\nnamespace dht {\n\ninline\nint64_t\nmurmur3_partitioner::normalize(int64_t in) {\n return in == std::numeric_limits<int64_t>::lowest()\n ? std::numeric_limits<int64_t>::max()\n : in;\n}\n\ntoken\nmurmur3_partitioner::get_token(bytes_view key) {\n if (key.empty()) {\n return minimum_token();\n }\n std::array<uint64_t, 2> hash;\n utils::murmur_hash::hash3_x64_128(key, 0, hash);\n return get_token(hash[0]);\n}\n\ntoken\nmurmur3_partitioner::get_token(uint64_t value) const {\n \/\/ We don't normalize() the value, since token includes an is-before-everything\n \/\/ indicator.\n \/\/ FIXME: will this require a repair when importing a database?\n auto t = net::hton(normalize(value));\n bytes b(bytes::initialized_later(), 8);\n std::copy_n(reinterpret_cast<int8_t*>(&t), 8, b.begin());\n return token{token::kind::key, std::move(b)};\n}\n\ntoken\nmurmur3_partitioner::get_token(const sstables::key_view& key) {\n return get_token(bytes_view(key));\n}\n\ntoken\nmurmur3_partitioner::get_token(const schema& s, partition_key_view key) {\n std::array<uint64_t, 2> hash;\n auto&& legacy = key.legacy_form(s);\n utils::murmur_hash::hash3_x64_128(legacy.begin(), legacy.size(), 0, hash);\n return get_token(hash[0]);\n}\n\ntoken murmur3_partitioner::get_random_token() {\n auto rand = dht::get_random_number<uint64_t>();\n return get_token(rand);\n}\n\ninline int64_t long_token(const token& t) {\n\n if (t._data.size() != sizeof(int64_t)) {\n throw runtime_exception(sprint(\"Invalid token. Should have size %ld, has size %ld\\n\", sizeof(int64_t), t._data.size()));\n }\n\n auto ptr = t._data.begin();\n auto lp = unaligned_cast<const int64_t *>(ptr);\n return net::ntoh(*lp);\n}\n\nsstring murmur3_partitioner::to_sstring(const token& t) const {\n return ::to_sstring(long_token(t));\n}\n\nint murmur3_partitioner::tri_compare(const token& t1, const token& t2) {\n auto l1 = long_token(t1);\n auto l2 = long_token(t2);\n\n if (l1 == l2) {\n return 0;\n } else {\n return l1 < l2 ? -1 : 1;\n }\n}\n\ntoken murmur3_partitioner::midpoint(const token& t1, const token& t2) const {\n auto l1 = long_token(t1);\n auto l2 = long_token(t2);\n \/\/ long_token is defined as signed, but the arithmetic works out the same\n \/\/ without invoking undefined behavior with a signed type.\n auto delta = (uint64_t(l2) - uint64_t(l1)) \/ 2;\n if (l1 > l2) {\n \/\/ wraparound\n delta += 0x8000'0000'0000'0000;\n }\n auto mid = uint64_t(l1) + delta;\n return get_token(mid);\n}\n\nstd::map<token, float>\nmurmur3_partitioner::describe_ownership(const std::vector<token>& sorted_tokens) {\n abort();\n}\n\ndata_type\nmurmur3_partitioner::get_token_validator() {\n return long_type;\n}\n\nunsigned\nmurmur3_partitioner::shard_of(const token& t) const {\n int64_t l = long_token(t);\n \/\/ treat l as a fraction between 0 and 1 and use 128-bit arithmetic to\n \/\/ divide that range evenly among shards:\n uint64_t adjusted = uint64_t(l) + uint64_t(std::numeric_limits<int64_t>::min());\n return (__int128(adjusted) * smp::count) >> 64;\n}\n\nusing registry = class_registrator<i_partitioner, murmur3_partitioner>;\nstatic registry registrator(\"org.apache.cassandra.dht.Murmur3Partitioner\");\nstatic registry registrator_short_name(\"Murmur3Partitioner\");\n\n}\n\n\n<|endoftext|>"} {"text":"<commit_before>cc933bbe-35ca-11e5-92f6-6c40088e03e4<commit_msg>cc99e964-35ca-11e5-a1cc-6c40088e03e4<commit_after>cc99e964-35ca-11e5-a1cc-6c40088e03e4<|endoftext|>"} {"text":"<commit_before>67621a24-2fa5-11e5-bc9e-00012e3d3f12<commit_msg>67643d06-2fa5-11e5-a0e5-00012e3d3f12<commit_after>67643d06-2fa5-11e5-a0e5-00012e3d3f12<|endoftext|>"} {"text":"<commit_before>5f89496e-2d16-11e5-af21-0401358ea401<commit_msg>5f89496f-2d16-11e5-af21-0401358ea401<commit_after>5f89496f-2d16-11e5-af21-0401358ea401<|endoftext|>"} {"text":"<commit_before>43bed268-5216-11e5-a04c-6c40088e03e4<commit_msg>43c714d2-5216-11e5-baea-6c40088e03e4<commit_after>43c714d2-5216-11e5-baea-6c40088e03e4<|endoftext|>"} {"text":"<commit_before>9101ad3b-2d14-11e5-af21-0401358ea401<commit_msg>9101ad3c-2d14-11e5-af21-0401358ea401<commit_after>9101ad3c-2d14-11e5-af21-0401358ea401<|endoftext|>"} {"text":"<commit_before>16d6f6ba-2e4f-11e5-a6a1-28cfe91dbc4b<commit_msg>16deb96b-2e4f-11e5-9706-28cfe91dbc4b<commit_after>16deb96b-2e4f-11e5-9706-28cfe91dbc4b<|endoftext|>"} {"text":"<commit_before>233238e8-2e4f-11e5-a7ef-28cfe91dbc4b<commit_msg>233ad9b3-2e4f-11e5-ae74-28cfe91dbc4b<commit_after>233ad9b3-2e4f-11e5-ae74-28cfe91dbc4b<|endoftext|>"} {"text":"<commit_before>7777d3b2-2d53-11e5-baeb-247703a38240<commit_msg>777853be-2d53-11e5-baeb-247703a38240<commit_after>777853be-2d53-11e5-baeb-247703a38240<|endoftext|>"} {"text":"<commit_before>7047f119-2e4f-11e5-8105-28cfe91dbc4b<commit_msg>704e6a0c-2e4f-11e5-a205-28cfe91dbc4b<commit_after>704e6a0c-2e4f-11e5-a205-28cfe91dbc4b<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n#include <string>\n#include <fstream>\n#include <vector>\n#include <queue>\n#include <iomanip>\n#include <algorithm>\n#include \"job.h\"\n\n\nusing namespace std;\n\nvoid insertProcesses(vector<Job>& processes, vector<int>& ids, vector<int>& bursts, int size);\nvoid FCFS(vector<Job> Jobs, int size);\nvoid roundRobin(vector<Job>& original, int size);\nbool sortJobs(Job job1, Job job2); \/\/needed to sort for SJF\nvoid SJF(vector<Job> Jobs, int size);\n\nint main()\n{\n string filename;\n\n cout << \"Please Enter the name of the file you wish to read: \";\n cin >> filename;\n\n\n string text;\n ifstream infile(filename);\n vector<int> ids;\n vector<int> bursts;\n vector<Job> processes;\n\n if(infile.is_open())\n\t{\n\twhile(infile.good())\n\t {\n\t\twhile(getline(infile, text))\n\t\t {\n\t\t\t\/\/Inserts before comma to ids vector and after to burst comma\n\t\t\tids.push_back(stoi(text.substr(0,text.find(\",\"))));\n\t\t\tbursts.push_back(stoi(text.substr(text.find(\",\") +1)));\n\t\t }\n\t }\n\t\/\/total number of jobs\n\tint size = ids.size();\n\n\t\/\/creates Job object vector to store information of both jobs and bursts\n\tinsertProcesses(processes, ids, bursts, size);\n\n\t\/\/ First come First Server\n\tFCFS(processes, size);\n\n\t\/\/Round Robin\n\troundRobin(processes, size);\n\n\t\/\/Shortest Job First\n\tSJF(processes, size);\n\n\t}\n \/\/When a file can't be found\n else\n\t{\n\t cerr << \"Error Opening File\" << endl;\n\t}\n infile.close();\n return 0;\n}\n\nvoid insertProcesses(vector<Job>& processes, vector<int>& ids, vector<int>& bursts, int size)\n{\n for(int i = 0; i < size; i++)\n\t{\n\t Job newJob(ids[i],bursts[i]);\n\t processes.push_back(newJob);\n\t}\n}\n\nvoid FCFS(vector<Job> Jobs, int size) {\n Job *RRProcesses = new Job[size];\n queue<Job> jobQ;\n \/\/ copy jobs into a new array to not mutate existing array\n for(int i = 0; i < size; i++)\n\t{\n\t RRProcesses[i] = Jobs[i];\n\t}\n \/\/Queue up\n for(int i = 0; i < size; i++)\n\t{\n\t jobQ.push(RRProcesses[i]);\n\t}\n Job* curJob;\n\n int totalTime = 0;\n int waitTime = 0;\n int totalWait;\n while(!jobQ.empty()) {\n \tcurJob = &jobQ.front(); \/\/Always pull from front of queue with FCFS\n \ttotalTime += curJob->getBurst();\n \tcurJob->setTurnAround(totalTime);\n \ttotalWait += curJob->getWait(); \/\/ used for calculating average later\n \tjobQ.pop();\n }\n\n cout << setprecision(3) << fixed << showpoint;\n double throughPut = 60\/((double)totalTime\/(double)size);\n cout << setw(30) << right << \"FIRST COME FIRST SERVE\" << endl;\n cout << \"Total processing time: \" << totalTime << \" seconds.\" << endl;\n cout << \"Average turn around time for Jobs: \" << totalTime \/ size << endl;\n cout << \"Overall throughput: \" << throughPut << \" processes per minute\" << endl;\n cout << \"Average wait time: \" << totalWait \/ size << endl;\n}\n\nvoid roundRobin(vector<Job>& original, int size)\n{\n Job *RRProcesses = new Job[size];\n queue<Job> jobQ;\n int timeQuantum = 1; \/\/By default it's 1 from the assignment, but it can be changed\n Job* ptr; \/\/Queue Pointer\n int n = 0; \/\/Process Counter (Can also be considere total burst time).\n int m = 0; \/\/Time Quantum Counter\n int remainingBurst; \/\/round robin subtracts bursts\n int started[size + 1];\/\/+1 because the job IDs start at 1 (if it starts at 0, we just have an extra box\n int totalTurnAround = 0; \/\/Should count all the turnArounds for average and other uses.\n\n\n cout << setw(30) << right << \"ROUND ROBIN\" << endl;\n cout << \"Enter a Time Quantum: \";\n cin >> timeQuantum;\n\n \/\/Copy original vector so it doesn't get modified\n for(int i = 0; i < size; i++)\n\t{\n\t RRProcesses[i] = original[i];\n\t}\n\n\n \/\/Queue up\n for(int i = 0; i < size; i++)\n\t{\n\t jobQ.push(RRProcesses[i]);\n\t}\n while(!jobQ.empty())\n\t{\n\t m = 0; \/\/reset\n\t ptr = &jobQ.front();\n\n\t \/\/Used to decrease burst until m=timeQuantum and increments n to track time passed\n\t while(m <= timeQuantum && ptr->getBurst() > 0)\n\t\t{\n\t\t remainingBurst = ptr->getBurst();\n\t\t ptr->setBurst(remainingBurst - 1);\n\t\t m++;\n\t\t n++;\n\t\t}\n\n\t \/\/if there's still burst time left\n\t if(ptr->getBurst() > 0)\n\t \t{\n\t \t jobQ.pop();\n\t \t jobQ.push(*ptr);\n\t \t}\n\t \/\/when process hits 0 burst time\n\t else\n\t \t{\n\t \t \/\/cout <<\"P\" << ptr->getID() << \" ended on time \" << n << endl;\n\t\t ptr->setEndTime(n);\n\t\t int turnA = ptr->getEndTime();\n\t\t ptr->setTurnAround(turnA);\n\t\t totalTurnAround += ptr->getTurnAround();\n\t \t jobQ.pop();\n\t \t}\n\n\t}\n\n \/\/output\n cout << setprecision(3) << fixed << showpoint;\n double throughPut = 60\/((double)n\/(double)size);\n cout << \"Total processing time: \" << n << endl;\n cout << \"Average TurnAround Time: \" << totalTurnAround\/size << endl;\n cout << \"Overall throughput: \" << throughPut << endl;\n cout << \"Average Wait Time: \" << (totalTurnAround - n)\/size << endl;\n}\n\nbool sortJobs(Job job1, Job job2) {\n return (job1.getBurst() < job2.getBurst()); \/\/ Only swap if shorter, keeps sort stable.\n}\n\n\nvoid SJF(vector<Job> Jobs, int size) {\n Job *RRProcesses = new Job[size];\n queue<Job> jobQ;\n\n RRProcesses[0] = Jobs[0]; \/\/ First process will always run first in SJF rega \\\n rdless of burst\n\n\tstd::vector<Job> newJobsVector(Jobs);\n std::sort(newJobsVector.begin()+1, newJobsVector.end(), sortJobs); \/\/ Assume \\\n all jobs come in at the same time\n\n\tfor(int i = 1; i < size; i++)\n\t {\n\t\tRRProcesses[i] = newJobsVector[i];\n\t }\n \/\/Queue up\n for(int i = 0; i < size; i++)\n\t{\n\t jobQ.push(RRProcesses[i]);\n\t}\n\n Job* curJob;\n\n int totalTime = 0;\n int totalWait = 0;\n while(!jobQ.empty()) {\n \tcurJob = &jobQ.front(); \/\/ Now that the queue is sorted by length, we can do the shortest job first by pulling from the front of the queue.\n \ttotalTime += curJob->getBurst(); \/\/ Set time spent equal to the burst\n \tcurJob->setTurnAround(totalTime);\n \ttotalWait += curJob->getWait();\n \tjobQ.pop();\n }\n\n cout << setprecision(3) << fixed << showpoint;\n double throughPut = 60\/((double)totalTime\/(double)size);\n cout << setw(30) << right << \"SHORTEST JOB FIRST\" << endl;\n cout << \"Total processing time: \" << totalTime << \" seconds.\" << endl;\n cout << \"Average wait time for Jobs: \" << totalWait \/ size << endl;\n cout << \"Average turn around time for Jobs: \" << totalTime \/ size << endl;\n cout << \"Overall throughput: \" << throughPut << \" processes per minute\" << endl;\n}\n<commit_msg>Changed all outputs to doubles<commit_after>#include <iostream>\n#include <string>\n#include <fstream>\n#include <vector>\n#include <queue>\n#include <iomanip>\n#include <algorithm>\n#include \"job.h\"\n\n\nusing namespace std;\n\nvoid insertProcesses(vector<Job>& processes, vector<int>& ids, vector<int>& bursts, int size);\nvoid FCFS(vector<Job> Jobs, int size);\nvoid roundRobin(vector<Job>& original, int size);\nbool sortJobs(Job job1, Job job2); \/\/needed to sort for SJF\nvoid SJF(vector<Job> Jobs, int size);\n\nint main()\n{\n string filename;\n\n cout << \"Please Enter the name of the file you wish to read: \";\n cin >> filename;\n\n\n string text;\n ifstream infile(filename);\n vector<int> ids;\n vector<int> bursts;\n vector<Job> processes;\n\n if(infile.is_open())\n\t{\n\twhile(infile.good())\n\t {\n\t\twhile(getline(infile, text))\n\t\t {\n\t\t\t\/\/Inserts before comma to ids vector and after to burst comma\n\t\t\tids.push_back(stoi(text.substr(0,text.find(\",\"))));\n\t\t\tbursts.push_back(stoi(text.substr(text.find(\",\") +1)));\n\t\t }\n\t }\n\t\/\/total number of jobs\n\tint size = ids.size();\n\n\t\/\/creates Job object vector to store information of both jobs and bursts\n\tinsertProcesses(processes, ids, bursts, size);\n\n\t\/\/ First come First Server\n\tFCFS(processes, size);\n\n\t\/\/Round Robin\n\troundRobin(processes, size);\n\n\t\/\/Shortest Job First\n\tSJF(processes, size);\n\n\t}\n \/\/When a file can't be found\n else\n\t{\n\t cerr << \"Error Opening File\" << endl;\n\t}\n infile.close();\n return 0;\n}\n\nvoid insertProcesses(vector<Job>& processes, vector<int>& ids, vector<int>& bursts, int size)\n{\n for(int i = 0; i < size; i++)\n\t{\n\t Job newJob(ids[i],bursts[i]);\n\t processes.push_back(newJob);\n\t}\n}\n\nvoid FCFS(vector<Job> Jobs, int size) {\n Job *RRProcesses = new Job[size];\n queue<Job> jobQ;\n \/\/ copy jobs into a new array to not mutate existing array\n for(int i = 0; i < size; i++)\n\t{\n\t RRProcesses[i] = Jobs[i];\n\t}\n \/\/Queue up\n for(int i = 0; i < size; i++)\n\t{\n\t jobQ.push(RRProcesses[i]);\n\t}\n Job* curJob;\n\n int totalTime = 0;\n int waitTime = 0;\n int totalWait;\n while(!jobQ.empty()) {\n \tcurJob = &jobQ.front(); \/\/Always pull from front of queue with FCFS\n \ttotalTime += curJob->getBurst();\n \tcurJob->setTurnAround(totalTime);\n \ttotalWait += curJob->getWait(); \/\/ used for calculating average later\n \tjobQ.pop();\n }\n\n cout << setprecision(3) << fixed << showpoint;\n double throughPut = 60\/((double)totalTime\/(double)size);\n double avgTurnAround = (double)totalTime\/(double)size;\n double avgWait = (double)totalWait\/(double)size;;\n cout << setw(30) << right << \"FIRST COME FIRST SERVE\" << endl;\n cout << \"Total processing time: \" << totalTime << \" seconds.\" << endl;\n cout << \"Average turn around time for Jobs: \" << avgTurnAround << endl;\n cout << \"Overall throughput: \" << throughPut << \" processes per minute\" << endl;\n cout << \"Average wait time: \" << avgWait << endl;\n}\n\nvoid roundRobin(vector<Job>& original, int size)\n{\n Job *RRProcesses = new Job[size];\n queue<Job> jobQ;\n int timeQuantum = 1; \/\/By default it's 1 from the assignment, but it can be changed\n Job* ptr; \/\/Queue Pointer\n int n = 0; \/\/Process Counter (Can also be considere total burst time).\n int m = 0; \/\/Time Quantum Counter\n int remainingBurst; \/\/round robin subtracts bursts\n int started[size + 1];\/\/+1 because the job IDs start at 1 (if it starts at 0, we just have an extra box\n int totalTurnAround = 0; \/\/Should count all the turnArounds for average and other uses.\n\n\n cout << setw(30) << right << \"ROUND ROBIN\" << endl;\n cout << \"Enter a Time Quantum: \";\n cin >> timeQuantum;\n\n \/\/Copy original vector so it doesn't get modified\n for(int i = 0; i < size; i++)\n\t{\n\t RRProcesses[i] = original[i];\n\t}\n\n\n \/\/Queue up\n for(int i = 0; i < size; i++)\n\t{\n\t jobQ.push(RRProcesses[i]);\n\t}\n while(!jobQ.empty())\n\t{\n\t m = 0; \/\/reset\n\t ptr = &jobQ.front();\n\n\t \/\/Used to decrease burst until m=timeQuantum and increments n to track time passed\n\t while(m <= timeQuantum && ptr->getBurst() > 0)\n\t\t{\n\t\t remainingBurst = ptr->getBurst();\n\t\t ptr->setBurst(remainingBurst - 1);\n\t\t m++;\n\t\t n++;\n\t\t}\n\n\t \/\/if there's still burst time left\n\t if(ptr->getBurst() > 0)\n\t \t{\n\t \t jobQ.pop();\n\t \t jobQ.push(*ptr);\n\t \t}\n\t \/\/when process hits 0 burst time\n\t else\n\t \t{\n\t \t \/\/cout <<\"P\" << ptr->getID() << \" ended on time \" << n << endl;\n\t\t ptr->setEndTime(n);\n\t\t int turnA = ptr->getEndTime();\n\t\t ptr->setTurnAround(turnA);\n\t\t totalTurnAround += ptr->getTurnAround();\n\t \t jobQ.pop();\n\t \t}\n\n\t}\n\n \/\/output\n cout << setprecision(3) << fixed << showpoint;\n double throughPut = 60\/((double)n\/(double)size);\n double avgTurnAround = (double)totalTurnAround\/(double)size;\n double avgWait = ((double)totalTurnAround - (double)n)\/(double)size;\n \n cout << \"Total processing time: \" << n << endl;\n cout << \"Average turn around time for Jobs: \" << avgTurnAround << endl;\n cout << \"Overall throughput: \" << throughPut << endl;\n cout << \"Average wait time: \" << avgWait << endl;\n}\n\nbool sortJobs(Job job1, Job job2) {\n return (job1.getBurst() < job2.getBurst()); \/\/ Only swap if shorter, keeps sort stable.\n}\n\n\nvoid SJF(vector<Job> Jobs, int size) {\n Job *RRProcesses = new Job[size];\n queue<Job> jobQ;\n\n RRProcesses[0] = Jobs[0]; \/\/ First process will always run first in SJF rega \\\n rdless of burst\n\n\tstd::vector<Job> newJobsVector(Jobs);\n std::sort(newJobsVector.begin()+1, newJobsVector.end(), sortJobs); \/\/ Assume \\\n all jobs come in at the same time\n\n\tfor(int i = 1; i < size; i++)\n\t {\n\t\tRRProcesses[i] = newJobsVector[i];\n\t }\n \/\/Queue up\n for(int i = 0; i < size; i++)\n\t{\n\t jobQ.push(RRProcesses[i]);\n\t}\n\n Job* curJob;\n\n int totalTime = 0;\n int totalWait = 0;\n while(!jobQ.empty()) {\n \tcurJob = &jobQ.front(); \/\/ Now that the queue is sorted by length, we can do the shortest job first by pulling from the front of the queue.\n \ttotalTime += curJob->getBurst(); \/\/ Set time spent equal to the burst\n \tcurJob->setTurnAround(totalTime);\n \ttotalWait += curJob->getWait();\n \tjobQ.pop();\n }\n\n cout << setprecision(3) << fixed << showpoint;\n double throughPut = 60\/((double)totalTime\/(double)size);\n double avgTurnAround =(double)totalTime\/(double)size;\n double avgWait = (double)totalWait\/(double)size;\n cout << setw(30) << right << \"SHORTEST JOB FIRST\" << endl;\n cout << \"Total processing time: \" << totalTime << \" seconds.\" << endl;\n cout << \"Average turn around time for Jobs: \" << totalTime \/ size << endl;\n cout << \"Overall throughput: \" << throughPut << \" processes per minute\" << endl;\n cout << \"Average wait time for Jobs: \" << totalWait \/ size << endl;\n}\n<|endoftext|>"} {"text":"<commit_before>16ccaeac-2f67-11e5-a708-6c40088e03e4<commit_msg>16d431fa-2f67-11e5-9e9e-6c40088e03e4<commit_after>16d431fa-2f67-11e5-9e9e-6c40088e03e4<|endoftext|>"} {"text":"<commit_before>#define ALL\n#ifdef ALL\n#include <iostream>\n\n#include <n\/core\/Timer.h>\n\n#include <n\/math\/Plane.h>\n#include <n\/io\/File.h>\n\n#include <SDL2\/SDL.h>\n#include <n\/graphics\/ImageLoader.h>\n#include <n\/graphics\/GLContext.h>\n#include <n\/graphics\/Texture.h>\n#include <n\/graphics\/Scene.h>\n#include <n\/graphics\/GL.h>\n#include <n\/graphics\/StaticBuffer.h>\n#include <n\/graphics\/TriangleBuffer.h>\n#include <n\/graphics\/VertexArrayObject.h>\n#include <n\/graphics\/ShaderCombinaison.h>\n#include <n\/graphics\/Camera.h>\n#include <n\/graphics\/StaticMesh.h>\n#include <n\/graphics\/Material.h>\n#include <n\/graphics\/MeshLoader.h>\n#include <n\/graphics\/MaterialLoader.h>\n\n#include <n\/math\/StaticConvexVolume.h>\n#include <n\/math\/ConvexVolume.h>\n\nusing namespace n;\nusing namespace n::graphics;\nusing namespace n::math;\nusing namespace n::core;\n\nSDL_Window *createWindow() {\n\tSDL_Window *mainWindow = 0;\n\tif(SDL_Init(SDL_INIT_VIDEO) < 0) {\n\t\tfatal(\"Unable to initialize SDL\");\n\t}\n\tSDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);\n\tSDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 4);\n\tSDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 2);\n\tSDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);\n\tif(!(mainWindow = SDL_CreateWindow(\"n 2.1\", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 800, 600, SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN))) {\n\t\tfatal(\"Unable to create window\");\n\t}\n\tSDL_GL_CreateContext(mainWindow);\n\tSDL_GL_SetSwapInterval(0);\n\n\tGLContext::getContext();\n\n\treturn mainWindow;\n}\n\nbool run(SDL_Window *mainWindow) {\n\tSDL_GL_SwapWindow(mainWindow);\n\tSDL_Event e;\n\tbool cc = true;\n\twhile(SDL_PollEvent(&e)) {\n\t\tif(e.type == SDL_QUIT || (e.type == SDL_KEYDOWN && e.key.keysym.sym == SDLK_ESCAPE)) {\n\t\t\tcc = false;\n\t\t\tbreak;\n\t\t}\n\t}\n\treturn cc;\n}\n\nclass Obj : public StaticMesh\n{\n\tpublic:\n\t\tObj(String n) : StaticMesh(MeshLoader::load<String>(n)), model(n) {\n\t\t\taxis = ((Vec3(random(), random(), random()) - 0.5) * 2).normalized();\n\t\t}\n\n\t\tvirtual void render(RenderQueue &qu) override {\n\t\t\tstatic Timer timer;\n\t\t\tstatic double x = 0;\n\t\t\tdouble t = timer.reset();\n\t\t\tx += t * 0.5;\n\t\t\tQuaternion<> q = Quaternion<>::fromAxisAngle(axis.cross(Vec3(1, 0, 0)).cross(axis), t);\n\t\t\taxis = q(axis);\n\t\t\tsetRotation(Quaternion<>::fromAxisAngle(axis, x));\n\t\t\tif(!getMeshInstance().isValid()) {\n\t\t\t\tfatal(\"Unable to load mesh\");\n\t\t\t}\n\t\t\tStaticMesh::render(qu);\n\t\t}\n\n\tprivate:\n\t\tString model;\n\t\tVec3 axis;\n};\n\nint main(int, char **) {\n\tSDL_Window *win = createWindow();\n\n\tShader<VertexShader> vert(\"#version 420 core\\n\"\n\t\t\t\t\t\t\t\t\t\t\"layout(location = 0) in vec3 n_VertexPosition;\"\n\t\t\t\t\t\t\t\t\t\t\"layout(location = 1) in vec3 n_VertexNormal;\"\n\t\t\t\t\t\t\t\t\t\t\"layout(location = 2) in vec3 n_VertexTangent;\"\n\t\t\t\t\t\t\t\t\t\t\"uniform mat4 n_ViewProjectionMatrix;\"\n\t\t\t\t\t\t\t\t\t\t\"uniform mat4 n_ModelMatrix;\"\n\t\t\t\t\t\t\t\t\t\t\"uniform vec3 n_Camera;\"\n\n\t\t\t\t\t\t\t\t\t\t\"out vec3 N;\"\n\t\t\t\t\t\t\t\t\t\t\"out vec3 V;\"\n\t\t\t\t\t\t\t\t\t\t\"out vec3 T;\"\n\t\t\t\t\t\t\t\t\t\t\"out vec3 B;\"\n\n\t\t\t\t\t\t\t\t\t\t\"void main() {\"\n\t\t\t\t\t\t\t\t\t\t\t\"vec4 model = n_ModelMatrix * vec4(n_VertexPosition, 1.0);\"\n\t\t\t\t\t\t\t\t\t\t\t\"gl_Position = n_ViewProjectionMatrix * model;\"\n\n\t\t\t\t\t\t\t\t\t\t\t\"V = normalize(n_Camera - model.xyz);\"\n\t\t\t\t\t\t\t\t\t\t\t\"N = mat3(n_ModelMatrix) * n_VertexNormal;\"\n\t\t\t\t\t\t\t\t\t\t\t\"T = mat3(n_ModelMatrix) * n_VertexTangent;\"\n\t\t\t\t\t\t\t\t\t\t\t\"B = cross(N, T);\"\n\t\t\t\t\t\t\t\t\t\t\"}\");\n\n\tio::File glsl(\"shader\");\n\tif(!glsl.open(io::IODevice::Read)) {\n\t\tfatal(\"Unable to open shader\");\n\t}\n\tchar *brdfc = new char[glsl.size() + 1];\n\tbrdfc[glsl.readBytes(brdfc)] = 0;\n\tString brdf(brdfc);\n\tdelete[] brdfc;\n\tglsl.close();\n\n\tString fragStr = \"#version 420 core\\n\"\n\t\t\t\t\t \"#define PI 3.14159265358979323846\\n\"\n\t\t\t\t\t \"layout(location = 0) out vec4 n_FragColor;\"\n\t\t\t\t\t \"uniform vec4 n_Color;\"\n\t\t\t\t\t \"uniform float n_Roughness;\"\n\t\t\t\t\t \"uniform float n_Metallic;\"\n\t\t\t\t\t \"in vec3 N;\"\n\t\t\t\t\t \"in vec3 V;\"\n\t\t\t\t\t \"in vec3 T;\"\n\t\t\t\t\t \"in vec3 B;\"\n\n\t\t\t\t\t + brdf +\n\n\t\t\t\t\t\"void main() {\"\n\t\t\t\t\t\t\"vec3 C = n_Color.rgb;\"\n\t\t\t\t\t\t\"vec3 L = normalize(vec3(0.5, 0.5, 1.0));\"\n\t\t\t\t\t\t\"vec3 NN = normalize(N);\"\n\t\t\t\t\t\t\"n_FragColor = vec4((d_BRDF(C, L, V, NN) + s_BRDF(C, L, V, NN)), n_Color.a);\"\n\t\t\t\t\t\"}\";\n\n\tShader<FragmentShader> frag(fragStr);\n\n\n\tShaderCombinaison shader(&frag, &vert, 0);\n\tif(!shader.isValid()) {\n\t\tstd::cerr<<shader.getLogs()<<std::endl;\n\t\tstd::cerr<<frag.getLogs()<<std::endl;\n\t\tstd::cerr<<vert.getLogs()<<std::endl;\n\t\tfatal(\"Unable to compile shader.\");\n\t}\n\n\tshader.bind();\n\n\tCamera cam;\n\tcam.setPosition(Vec3(0, 0, 5));\n\tshader[\"n_Camera\"] = cam.getPosition();\n\tcam.setRotation(Quaternion<>::fromEuler(0, toRad(90), 0));\n\n\tGLContext::getContext()->setProjectionMatrix(cam.getProjectionMatrix());\n\tGLContext::getContext()->setViewMatrix(cam.getViewMatrix());\n\tScene scene;\n\n\tauto c = new Obj(\"scube.obj\");\n\tc->setPosition(Vec3(0, 2.5, 0));\n\tscene.insert(c);\n\tc = new Obj(\"sphere.obj\");\n\tc->setPosition(Vec3(0, 0, 0));\n\tscene.insert(c);\n\tc = new Obj(\"scube.obj\");\n\tc->setPosition(Vec3(0, -2.5, 0));\n\tscene.insert(c);\n\n\tTimer timer;\n\twhile(run(win)) {\n\t\tgl::glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);\n\t\tcore::Array<StaticMesh *> meshes = scene.query<StaticMesh>(cam);\n\t\tRenderQueue queue;\n\t\tfor(Renderable *m : meshes) {\n\t\t\tm->render(queue);\n\t\t}\n\t\tfor(const auto &q : queue.getBatches()) {\n\t\t\tq();\n\t\t}\n\t\tGLContext::getContext()->processTasks();\n\t\tif(GLContext::checkGLError()) {\n\t\t\tfatal(\"GL error\");\n\t\t}\n\t\t\/\/shader[\"n_Roughness\"] = (1 + sin(timer.elapsed()));\n\t\tgl::glFlush();\n\t}\n\treturn 0;\n}\n\n\n#else\n\n#include <n\/core\/Array.h>\n\nint main(int, char **) {\n\treturn 0;\n}\n\n#endif\n\n<commit_msg>Limited framerate somewat<commit_after>#define ALL\n#ifdef ALL\n#include <iostream>\n\n#include <n\/core\/Timer.h>\n\n#include <n\/math\/Plane.h>\n#include <n\/io\/File.h>\n\n#include <SDL2\/SDL.h>\n#include <n\/graphics\/ImageLoader.h>\n#include <n\/graphics\/GLContext.h>\n#include <n\/graphics\/Texture.h>\n#include <n\/graphics\/Scene.h>\n#include <n\/graphics\/GL.h>\n#include <n\/graphics\/StaticBuffer.h>\n#include <n\/graphics\/TriangleBuffer.h>\n#include <n\/graphics\/VertexArrayObject.h>\n#include <n\/graphics\/ShaderCombinaison.h>\n#include <n\/graphics\/Camera.h>\n#include <n\/graphics\/StaticMesh.h>\n#include <n\/graphics\/Material.h>\n#include <n\/graphics\/MeshLoader.h>\n#include <n\/graphics\/MaterialLoader.h>\n\n#include <n\/math\/StaticConvexVolume.h>\n#include <n\/math\/ConvexVolume.h>\n\nusing namespace n;\nusing namespace n::graphics;\nusing namespace n::math;\nusing namespace n::core;\n\nSDL_Window *createWindow() {\n\tSDL_Window *mainWindow = 0;\n\tif(SDL_Init(SDL_INIT_VIDEO) < 0) {\n\t\tfatal(\"Unable to initialize SDL\");\n\t}\n\tSDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);\n\tSDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 4);\n\tSDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 2);\n\tSDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);\n\tif(!(mainWindow = SDL_CreateWindow(\"n 2.1\", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 800, 600, SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN))) {\n\t\tfatal(\"Unable to create window\");\n\t}\n\tSDL_GL_CreateContext(mainWindow);\n\tSDL_GL_SetSwapInterval(0);\n\n\tGLContext::getContext();\n\n\treturn mainWindow;\n}\n\nbool run(SDL_Window *mainWindow) {\n\tSDL_GL_SwapWindow(mainWindow);\n\tSDL_Event e;\n\tbool cc = true;\n\twhile(SDL_PollEvent(&e)) {\n\t\tif(e.type == SDL_QUIT || (e.type == SDL_KEYDOWN && e.key.keysym.sym == SDLK_ESCAPE)) {\n\t\t\tcc = false;\n\t\t\tbreak;\n\t\t}\n\t}\n\treturn cc;\n}\n\nclass Obj : public StaticMesh\n{\n\tpublic:\n\t\tObj(String n) : StaticMesh(MeshLoader::load<String>(n)), model(n) {\n\t\t\taxis = ((Vec3(random(), random(), random()) - 0.5) * 2).normalized();\n\t\t}\n\n\t\tvirtual void render(RenderQueue &qu) override {\n\t\t\tstatic Timer timer;\n\t\t\tstatic double x = 0;\n\t\t\tdouble t = timer.reset();\n\t\t\tx += t * 0.5;\n\t\t\tQuaternion<> q = Quaternion<>::fromAxisAngle(axis.cross(Vec3(1, 0, 0)).cross(axis), t);\n\t\t\taxis = q(axis);\n\t\t\tsetRotation(Quaternion<>::fromAxisAngle(axis, x));\n\t\t\tif(!getMeshInstance().isValid()) {\n\t\t\t\tfatal(\"Unable to load mesh\");\n\t\t\t}\n\t\t\tStaticMesh::render(qu);\n\t\t}\n\n\tprivate:\n\t\tString model;\n\t\tVec3 axis;\n};\n\nint main(int, char **) {\n\tSDL_Window *win = createWindow();\n\n\tShader<VertexShader> vert(\"#version 420 core\\n\"\n\t\t\t\t\t\t\t\t\t\t\"layout(location = 0) in vec3 n_VertexPosition;\"\n\t\t\t\t\t\t\t\t\t\t\"layout(location = 1) in vec3 n_VertexNormal;\"\n\t\t\t\t\t\t\t\t\t\t\"layout(location = 2) in vec3 n_VertexTangent;\"\n\t\t\t\t\t\t\t\t\t\t\"uniform mat4 n_ViewProjectionMatrix;\"\n\t\t\t\t\t\t\t\t\t\t\"uniform mat4 n_ModelMatrix;\"\n\t\t\t\t\t\t\t\t\t\t\"uniform vec3 n_Camera;\"\n\n\t\t\t\t\t\t\t\t\t\t\"out vec3 N;\"\n\t\t\t\t\t\t\t\t\t\t\"out vec3 V;\"\n\t\t\t\t\t\t\t\t\t\t\"out vec3 T;\"\n\t\t\t\t\t\t\t\t\t\t\"out vec3 B;\"\n\n\t\t\t\t\t\t\t\t\t\t\"void main() {\"\n\t\t\t\t\t\t\t\t\t\t\t\"vec4 model = n_ModelMatrix * vec4(n_VertexPosition, 1.0);\"\n\t\t\t\t\t\t\t\t\t\t\t\"gl_Position = n_ViewProjectionMatrix * model;\"\n\n\t\t\t\t\t\t\t\t\t\t\t\"V = normalize(n_Camera - model.xyz);\"\n\t\t\t\t\t\t\t\t\t\t\t\"N = mat3(n_ModelMatrix) * n_VertexNormal;\"\n\t\t\t\t\t\t\t\t\t\t\t\"T = mat3(n_ModelMatrix) * n_VertexTangent;\"\n\t\t\t\t\t\t\t\t\t\t\t\"B = cross(N, T);\"\n\t\t\t\t\t\t\t\t\t\t\"}\");\n\n\tio::File glsl(\"shader\");\n\tif(!glsl.open(io::IODevice::Read)) {\n\t\tfatal(\"Unable to open shader\");\n\t}\n\tchar *brdfc = new char[glsl.size() + 1];\n\tbrdfc[glsl.readBytes(brdfc)] = 0;\n\tString brdf(brdfc);\n\tdelete[] brdfc;\n\tglsl.close();\n\n\tString fragStr = \"#version 420 core\\n\"\n\t\t\t\t\t \"#define PI 3.14159265358979323846\\n\"\n\t\t\t\t\t \"layout(location = 0) out vec4 n_FragColor;\"\n\t\t\t\t\t \"uniform vec4 n_Color;\"\n\t\t\t\t\t \"uniform float n_Roughness;\"\n\t\t\t\t\t \"uniform float n_Metallic;\"\n\t\t\t\t\t \"in vec3 N;\"\n\t\t\t\t\t \"in vec3 V;\"\n\t\t\t\t\t \"in vec3 T;\"\n\t\t\t\t\t \"in vec3 B;\"\n\n\t\t\t\t\t + brdf +\n\n\t\t\t\t\t\"void main() {\"\n\t\t\t\t\t\t\"vec3 C = n_Color.rgb;\"\n\t\t\t\t\t\t\"vec3 L = normalize(vec3(0.5, 0.5, 1.0));\"\n\t\t\t\t\t\t\"vec3 NN = normalize(N);\"\n\t\t\t\t\t\t\"n_FragColor = vec4((d_BRDF(C, L, V, NN) + s_BRDF(C, L, V, NN)), n_Color.a);\"\n\t\t\t\t\t\"}\";\n\n\tShader<FragmentShader> frag(fragStr);\n\n\n\tShaderCombinaison shader(&frag, &vert, 0);\n\tif(!shader.isValid()) {\n\t\tstd::cerr<<shader.getLogs()<<std::endl;\n\t\tstd::cerr<<frag.getLogs()<<std::endl;\n\t\tstd::cerr<<vert.getLogs()<<std::endl;\n\t\tfatal(\"Unable to compile shader.\");\n\t}\n\n\tshader.bind();\n\n\tCamera cam;\n\tcam.setPosition(Vec3(0, 0, 5));\n\tshader[\"n_Camera\"] = cam.getPosition();\n\tcam.setRotation(Quaternion<>::fromEuler(0, toRad(90), 0));\n\n\tGLContext::getContext()->setProjectionMatrix(cam.getProjectionMatrix());\n\tGLContext::getContext()->setViewMatrix(cam.getViewMatrix());\n\tScene scene;\n\n\tauto c = new Obj(\"scube.obj\");\n\tc->setPosition(Vec3(0, 2.5, 0));\n\tscene.insert(c);\n\tc = new Obj(\"sphere.obj\");\n\tc->setPosition(Vec3(0, 0, 0));\n\tscene.insert(c);\n\tc = new Obj(\"scube.obj\");\n\tc->setPosition(Vec3(0, -2.5, 0));\n\tscene.insert(c);\n\n\tTimer timer;\n\twhile(run(win)) {\n\t\tgl::glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);\n\t\tcore::Array<StaticMesh *> meshes = scene.query<StaticMesh>(cam);\n\t\tRenderQueue queue;\n\t\tfor(Renderable *m : meshes) {\n\t\t\tm->render(queue);\n\t\t}\n\t\tfor(const auto &q : queue.getBatches()) {\n\t\t\tq();\n\t\t}\n\t\tGLContext::getContext()->processTasks();\n\t\tif(GLContext::checkGLError()) {\n\t\t\tfatal(\"GL error\");\n\t\t}\n\t\tconcurent::Thread::sleep(0.01);\n\t\tgl::glFlush();\n\t}\n\treturn 0;\n}\n\n\n#else\n\n#include <n\/core\/Array.h>\n\nint main(int, char **) {\n\treturn 0;\n}\n\n#endif\n\n<|endoftext|>"} {"text":"<commit_before>d647ec63-2e4e-11e5-8323-28cfe91dbc4b<commit_msg>d64fba1e-2e4e-11e5-a3fc-28cfe91dbc4b<commit_after>d64fba1e-2e4e-11e5-a3fc-28cfe91dbc4b<|endoftext|>"} {"text":"<commit_before>6e6c42bd-ad58-11e7-91e1-ac87a332f658<commit_msg>I am finally done<commit_after>6ece8f4f-ad58-11e7-9658-ac87a332f658<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n#include <string>\n#include <sstream>\n#include <cstdlib>\n\/\/#include <vector>\n\/\/#include <fstream>\n\nusing namespace std;\n\nint main()\n{\n \/\/game start\n cout << \" -----------------------------\" << endl\n << \"| Plants v.s Zombies |\" << endl\n << \" -----------------------------\" << endl;\n constexpr int LAND_DEFAULT=8;\n constexpr int LAND_MAX=10;\n constexpr int LAND_MIN=1;\n constexpr int ZOMBIE_DEFAULT=3;\n constexpr int ZOMBIE_MAX=10;\n constexpr int ZOMBIE_MIN=1;\n\n string input;\n \/\/initialize game setting\n cout << \"Number of lands on the map (\" << LAND_MIN << \"-\" << LAND_MAX << \", default: \" << LAND_DEFAULT <<\")...>\";\n int value = LAND_DEFAULT;\n getline(cin, input);\n if(!input.empty())\n {\n istringstream stream( input );\n stream >> value;\n if(value > LAND_MAX) value = LAND_MAX;\n if(value < LAND_MIN) value = LAND_MIN;\n }\n const int LANDS=value;\n\n cout << \"Number of zombies on the map (\" << ZOMBIE_MIN << \"-\" << ZOMBIE_MAX << \", default: \"<< ZOMBIE_DEFAULT <<\")...>\";\n value=ZOMBIE_DEFAULT;\n getline(cin, input);\n if(!input.empty())\n {\n istringstream stream( input );\n stream >> value;\n if(value > ZOMBIE_MAX) value = ZOMBIE_MAX;\n if(value < ZOMBIE_MIN) value = ZOMBIE_MIN;\n }\n const int ZOMBIES=value;\n\n \/\/game rules\n cout << \"=============================================================================\" << endl\n << \"Plants vs. Zombies Rule:\" << endl\n << endl\n << \"How to win:\" << endl\n << \" (1) All zombies are dead.\" << endl\n << \" (2) At least one plant is live.\" << endl\n << \" (3) The number of dead bomb plants cannot exceed the number of zombies.\" << endl\n << endl\n << \"How to lose:\" << endl\n << \" All plants are dead.\" << endl\n << \"=============================================================================\" << endl;\n system(\"pause\");\n system(\"cls\");\n\n \/\/game start\n \/*\n \/\/construct\n Player *player = new Player();\n Zombie *zombie = new Zombie()[ZOMBIES];\n Land *land = new Land()[LANDS];\n Map *map = new Map(land);\n vector<Plant*> plant;\n ifstream fin=open(\"plants.txt\");\n while(!fin.eof())\n {\n char type;\n fin << type;\n if(fin.eof()) break;\n Plant *tmp = nullptr;\n switch(type)\n {\n case 'C':\n {\n tmp = new CoinPlant(fin);\n }\n case 'S':\n {\n tmp = new HornPlant(fin);\n }\n case 'B':\n {\n tmp = new BombPlant(fin);\n }\n case 'H':\n {\n tmp = new HealPlant(fin);\n }\n default:\n continue;\n }\n if(tmp)\n {\n plant.push_back(tmp);\n }\n }\n\n cout << *map << endl;\n cout << \"------------------------------------------------\" << endl;\n cout << \"Zombie information:\" << endl;\n for(int i=0;i<ZOMBIES;i++)\n {\n cout << '[' << i << \"] \" << zombie[i];\n }\n cout << endl << \"================================================\" << endl;\n for(int i=0;i<plant.size();++i)\n {\n cout << '[' << i << \"] \" ;\n switch(plant[i]->type())\n {\n case 'C':\n cout << dynamic_cast<CoinPlant *>(plant[i]);\n case 'S':\n cout << dynamic_cast<HornPlant *>(plant[i]);\n case 'B':\n cout << dynamic_cast<BombPlant *>(plant[i]);\n case 'H':\n cout << dynamic_cast<HealPlant *>(plant[i]);\n }\n cout << endl;\n }\n cout << endl << *player;\n int choice = plant.size();\n cout << \": Enter your choice (\" << choice << \" to give up, default: \" << choice << \")...>\";\n\n\n \/\/ destruct\n while(!plant.empty())\n delete plant.pop_back();\n delete player;\n delete map;\n delete [] zombie;\n delete [] land;\n *\/\n\n return 0;\n}\n<commit_msg>preset which need to convert type<commit_after>#include <iostream>\n#include <string>\n#include <sstream>\n#include <cstdlib>\n\/\/#include <vector>\n\/\/#include <fstream>\n\nusing namespace std;\n\nint main()\n{\n \/\/game start\n cout << \" -----------------------------\" << endl\n << \"| Plants v.s Zombies |\" << endl\n << \" -----------------------------\" << endl;\n constexpr int LAND_DEFAULT=8;\n constexpr int LAND_MAX=10;\n constexpr int LAND_MIN=1;\n constexpr int ZOMBIE_DEFAULT=3;\n constexpr int ZOMBIE_MAX=10;\n constexpr int ZOMBIE_MIN=1;\n\n string input;\n \/\/initialize game setting\n cout << \"Number of lands on the map (\" << LAND_MIN << \"-\" << LAND_MAX << \", default: \" << LAND_DEFAULT <<\")...>\";\n int value = LAND_DEFAULT;\n getline(cin, input);\n if(!input.empty())\n {\n istringstream stream( input );\n stream >> value;\n if(value > LAND_MAX) value = LAND_MAX;\n if(value < LAND_MIN) value = LAND_MIN;\n }\n const int LANDS=value;\n\n cout << \"Number of zombies on the map (\" << ZOMBIE_MIN << \"-\" << ZOMBIE_MAX << \", default: \"<< ZOMBIE_DEFAULT <<\")...>\";\n value=ZOMBIE_DEFAULT;\n getline(cin, input);\n if(!input.empty())\n {\n istringstream stream( input );\n stream >> value;\n if(value > ZOMBIE_MAX) value = ZOMBIE_MAX;\n if(value < ZOMBIE_MIN) value = ZOMBIE_MIN;\n }\n const int ZOMBIES=value;\n\n \/\/game rules\n cout << \"=============================================================================\" << endl\n << \"Plants vs. Zombies Rule:\" << endl\n << endl\n << \"How to win:\" << endl\n << \" (1) All zombies are dead.\" << endl\n << \" (2) At least one plant is live.\" << endl\n << \" (3) The number of dead bomb plants cannot exceed the number of zombies.\" << endl\n << endl\n << \"How to lose:\" << endl\n << \" All plants are dead.\" << endl\n << \"=============================================================================\" << endl;\n system(\"pause\");\n system(\"cls\");\n\n \/\/game start\n \/*\n \/\/construct\n Player *player = new Player();\n Zombie *zombie = new Zombie()[ZOMBIES];\n Land *land = new Land()[LANDS];\n Map *map = new Map(land);\n vector<Plant*> plant;\n ifstream fin=open(\"plants.txt\");\n while(!fin.eof())\n {\n char type;\n fin << type;\n if(fin.eof()) break;\n Plant *tmp = nullptr;\n switch(type)\n {\n case 'C':\n {\n tmp = new CoinPlant(fin);\n }\n case 'S':\n {\n tmp = new HornPlant(fin);\n }\n case 'B':\n {\n tmp = new BombPlant(fin);\n }\n case 'H':\n {\n tmp = new HealPlant(fin);\n }\n default:\n continue;\n }\n if(tmp)\n {\n plant.push_back(tmp);\n }\n }\n\n cout << *map << endl;\n cout << \"------------------------------------------------\" << endl;\n cout << \"Zombie information:\" << endl;\n for(int i=0;i<ZOMBIES;i++)\n {\n cout << '[' << i << \"] \" << zombie[i];\n }\n cout << endl << \"================================================\" << endl;\n for(int i=0;i<plant.size();++i)\n {\n cout << '[' << i << \"] \" ;\n switch(plant[i]->type())\n {\n case 'C':\n cout << dynamic_cast<CoinPlant *>(plant[i]);\n case 'S':\n cout << dynamic_cast<HornPlant *>(plant[i]);\n case 'B':\n cout << dynamic_cast<BombPlant *>(plant[i]);\n case 'H':\n cout << dynamic_cast<HealPlant *>(plant[i]);\n }\n cout << endl;\n }\n cout << endl << *player;\n int choice = plant.size();\n cout << \": Enter your choice (\" << choice << \" to give up, default: \" << choice << \")...>\";\n\n switch(plant[choice].type())\n {\n case 'C':\n land->plant(CoinPlant(*dynamic_cast<CoinPlant *>(plant[choice])));\n case 'S':\n land->plant(HornPlant(*dynamic_cast<CoinPlant *>(plant[choice])));\n case 'B':\n land->plant(BombPlant(*dynamic_cast<CoinPlant *>(plant[choice])));\n case 'H':\n land->plant(HealPlant(*dynamic_cast<CoinPlant *>(plant[choice])))\n }\n\n\n \/\/ destruct\n while(!plant.empty())\n delete plant.pop_back();\n delete player;\n delete map;\n delete [] zombie;\n delete [] land;\n *\/\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>8431fca3-2d15-11e5-af21-0401358ea401<commit_msg>8431fca4-2d15-11e5-af21-0401358ea401<commit_after>8431fca4-2d15-11e5-af21-0401358ea401<|endoftext|>"} {"text":"<commit_before>a85d075c-35ca-11e5-ba2f-6c40088e03e4<commit_msg>a8640dcc-35ca-11e5-9673-6c40088e03e4<commit_after>a8640dcc-35ca-11e5-9673-6c40088e03e4<|endoftext|>"} {"text":"<commit_before>17e889a4-585b-11e5-903f-6c40088e03e4<commit_msg>17ef1f30-585b-11e5-9127-6c40088e03e4<commit_after>17ef1f30-585b-11e5-9127-6c40088e03e4<|endoftext|>"} {"text":"<commit_before>ede16d8c-2e4e-11e5-ab51-28cfe91dbc4b<commit_msg>ede8224c-2e4e-11e5-9fff-28cfe91dbc4b<commit_after>ede8224c-2e4e-11e5-9fff-28cfe91dbc4b<|endoftext|>"} {"text":"<commit_before>863fa16e-2d3e-11e5-aff7-c82a142b6f9b<commit_msg>869b7494-2d3e-11e5-94b0-c82a142b6f9b<commit_after>869b7494-2d3e-11e5-94b0-c82a142b6f9b<|endoftext|>"} {"text":"<commit_before>53ea1936-2e3a-11e5-91c2-c03896053bdd<commit_msg>53fe4122-2e3a-11e5-893b-c03896053bdd<commit_after>53fe4122-2e3a-11e5-893b-c03896053bdd<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n\n\n\/\/Thomas' Prototypes\n\n\/\/Hannah's Prototypes\n\nint atomic_distance (int distance); \/\/Kate's Prototype: defines atomic distance as integer\n\nint (main)\n{\nusing nedit file...\ncreate new input \"hannah's test changes\"\n}\n\n<commit_msg>Update to Kate's First Function Prototype<commit_after>#include <iostream>\n\n\n\/\/Thomas' Prototypes\n\n\/\/Hannah's Prototypes\n\nint atomic_distance (int x, int y, int z); \/\/Kate's Prototype: defines atomic distance as combination of x, y, z coordinates\n\nint (main)\n{\nusing nedit file...\ncreate new input \"hannah's test changes\"\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Website:\n * https:\/\/github.com\/wo3kie\/dojo\n *\n * Author:\n * Lukasz Czerwinski\n *\n * Compilation:\n * g++ --std=c++11 tuple.cpp -o tuple\n *\n * Usage:\n * $ .\/tuple\n *\/\n\n#include <iostream>\n\ntemplate<typename Arg, typename ... Args>\nstruct Tuple\n{\n\tTuple(){\n\t}\n\n\tTuple(Arg arg, Args... args)\n\t\t: head_(arg)\n\t\t, tail_(args...)\n\t{\n\t}\n\n\tArg head_;\n\tTuple<Args...> tail_;\n};\n\ntemplate<typename Arg>\nstruct Tuple<Arg> \n{\n\tTuple(){\n\t}\n\n\tTuple(Arg arg)\n\t\t: head_(arg)\n\t{\n\t}\n\n\tArg head_;\n};\n\ntemplate<typename ... Args>\nTuple<Args...> makeTuple(Args ... args){\n\treturn Tuple<Args...>(args...);\n}\n\ntemplate<int I, typename Arg, typename ... Args>\nstruct Get\n{\n\tauto operator()(Tuple<Arg, Args...> tuple)\n\t{\n\t\treturn Get<I - 1, Args...>()(tuple.tail_);\n\t}\n};\n\ntemplate<typename Arg, typename ... Args>\nstruct Get<0, Arg, Args...>\n{\n\tArg operator()(Tuple<Arg, Args...> tuple){\n\t\treturn tuple.head_;\n\t}\n};\n\ntemplate<int I, typename Arg, typename ... Args>\nauto get(Tuple<Arg, Args...> tuple){\n\treturn Get<I, Arg, Args...>()(tuple);\n}\n\ntemplate<typename Arg, typename ... Args>\nint size(Tuple<Arg, Args...> tuple){\n\treturn 1 + sizeof...(Args);\n}\n\n#include <cassert>\n#include <string>\n\nint main(){\n\tauto tuple = makeTuple(0, 1.0, '2', \"3\"); \n\n\tassert(get<0>(tuple) == 0);\n\tassert(get<1>(tuple) == 1.0);\n\tassert(get<2>(tuple) == '2');\n\n\tusing namespace std::string_literals;\n\tassert(get<3>(tuple) == \"3\"s);\n\n\tassert(size(tuple) == 4);\n}\n\n<commit_msg>tuple.cpp<commit_after>\/*\n * Website:\n * https:\/\/github.com\/wo3kie\/dojo\n *\n * Author:\n * Lukasz Czerwinski\n *\n * Compilation:\n * g++ --std=c++14 tuple.cpp -o tuple\n *\n * Usage:\n * $ .\/tuple\n *\/\n\n#include <iostream>\n\ntemplate<typename Arg, typename ... Args>\nstruct Tuple\n{\n\tTuple(){\n\t}\n\n\tTuple(Arg arg, Args... args)\n\t\t: head_(arg)\n\t\t, tail_(args...)\n\t{\n\t}\n\n\tArg head_;\n\tTuple<Args...> tail_;\n};\n\ntemplate<typename Arg>\nstruct Tuple<Arg> \n{\n\tTuple(){\n\t}\n\n\tTuple(Arg arg)\n\t\t: head_(arg)\n\t{\n\t}\n\n\tArg head_;\n};\n\ntemplate<typename ... Args>\nconstexpr Tuple<Args...> makeTuple(Args && ... args){\n\treturn Tuple<Args...>(std::forward<Args>(args)...);\n}\n\ntemplate<int I, typename Arg, typename ... Args>\nstruct Get\n{\n\tconstexpr auto operator()(Tuple<Arg, Args...> tuple) const {\n\t\treturn Get<I - 1, Args...>()(tuple.tail_);\n\t}\n};\n\ntemplate<typename Arg, typename ... Args>\nstruct Get<0, Arg, Args...>\n{\n\tconstexpr Arg operator()(Tuple<Arg, Args...> tuple) const {\n\t\treturn tuple.head_;\n\t}\n};\n\ntemplate<int I, typename Arg, typename ... Args>\nconstexpr auto get(Tuple<Arg, Args...> tuple){\n\treturn Get<I, Arg, Args...>()(tuple);\n}\n\ntemplate<typename Arg, typename ... Args>\nconstexpr int size(Tuple<Arg, Args...> const & tuple){\n\treturn 1 + sizeof...(Args);\n}\n\n#include <cassert>\n#include <string>\n\nint main(){\n\tauto tuple = makeTuple(0, 1.0, '2', \"3\"); \n\n\tassert(get<0>(tuple) == 0);\n\tassert(get<1>(tuple) == 1.0);\n\tassert(get<2>(tuple) == '2');\n\n\tusing namespace std::string_literals;\n\tassert(get<3>(tuple) == \"3\"s);\n\n\tassert(size(tuple) == 4);\n}\n\n<|endoftext|>"} {"text":"<commit_before>c9de8547-327f-11e5-8561-9cf387a8033e<commit_msg>c9e4a3d7-327f-11e5-80d4-9cf387a8033e<commit_after>c9e4a3d7-327f-11e5-80d4-9cf387a8033e<|endoftext|>"} {"text":"<commit_before>518c10d8-5216-11e5-9ca8-6c40088e03e4<commit_msg>51938ef6-5216-11e5-b4b2-6c40088e03e4<commit_after>51938ef6-5216-11e5-b4b2-6c40088e03e4<|endoftext|>"} {"text":"<commit_before>36d97ba2-5216-11e5-9cad-6c40088e03e4<commit_msg>36dfec42-5216-11e5-b600-6c40088e03e4<commit_after>36dfec42-5216-11e5-b600-6c40088e03e4<|endoftext|>"} {"text":"<commit_before>2b31fe36-2f67-11e5-8b7e-6c40088e03e4<commit_msg>2b38d0a6-2f67-11e5-aa55-6c40088e03e4<commit_after>2b38d0a6-2f67-11e5-aa55-6c40088e03e4<|endoftext|>"} {"text":"<commit_before>8b332573-2d14-11e5-af21-0401358ea401<commit_msg>8b332574-2d14-11e5-af21-0401358ea401<commit_after>8b332574-2d14-11e5-af21-0401358ea401<|endoftext|>"} {"text":"<commit_before>\/*=============================================================================\n Copyright (c) 2016-2017 Joel de Guzman\n\n Distributed under the MIT License [ https:\/\/opensource.org\/licenses\/MIT ]\n=============================================================================*\/\n#include <photon\/support\/glyphs.hpp>\n#include <photon\/support\/detail\/scratch_context.hpp>\n\nnamespace photon\n{\n static detail::scratch_context scratch_context_;\n\n glyphs::glyphs(char const* first, char const* last)\n : _first(first)\n , _last(last)\n {\n PHOTON_ASSERT(_first, \"Precondition failure: _first must not be null\");\n PHOTON_ASSERT(_last, \"Precondition failure: _last must not be null\");\n }\n\n glyphs::glyphs(\n char const* first, char const* last\n , int glyph_start, int glyph_end\n , int cluster_start, int cluster_end\n , master_glyphs const& master\n , bool strip_leading_spaces\n )\n : _first(first)\n , _last(last)\n , _scaled_font(master._scaled_font)\n , _glyphs(master._glyphs + glyph_start)\n , _glyph_count(glyph_end - glyph_start)\n , _clusters(master._clusters + cluster_start)\n , _cluster_count(cluster_end - cluster_start)\n , _clusterflags(master._clusterflags)\n {\n PHOTON_ASSERT(_first, \"Precondition failure: _first must not be null\");\n PHOTON_ASSERT(_last, \"Precondition failure: _last must not be null\");\n PHOTON_ASSERT(_scaled_font, \"Precondition failure: _scaled_font must not be null\");\n PHOTON_ASSERT(_glyphs, \"Precondition failure: _glyphs must not be null\");\n PHOTON_ASSERT(_clusters, \"Precondition failure: _clusters must not be null\");\n\n \/\/ We strip leading spaces until after the last leading newline.\n \/\/ Examples:\n \/\/\n \/\/ \"\\n\\n \" ===> \" \"\n \/\/ \" \\n\\n\" ===> \"\"\n \/\/ \" xxx\" ===> \"xxx\"\n\n auto strip_leading = [this](auto f)\n {\n int glyph_index = 0;\n unsigned codepoint;\n unsigned state = 0;\n\n cairo_text_cluster_t* cluster = _clusters;\n for (auto i = _first; i != _last; ++i)\n {\n if (!decode_utf8(state, codepoint, uint8_t(*i)))\n {\n if (!f(codepoint))\n break;\n glyph_index += cluster->num_glyphs;\n ++cluster;\n }\n }\n\n auto clusters_skipped = int(cluster - _clusters);\n\n _glyph_count -= glyph_index;\n _glyphs += glyph_index;\n _cluster_count -= clusters_skipped;\n _clusters = cluster;\n _first += clusters_skipped;\n };\n\n if (strip_leading_spaces)\n strip_leading([](auto cp){ return !is_newline(cp) && is_space(cp); });\n strip_leading([](auto cp){ return is_newline(cp); });\n }\n\n void glyphs::draw(point pos, canvas& canvas_)\n {\n \/\/ return early if there's nothing to draw\n if (_first == _last)\n return;\n\n PHOTON_ASSERT(_scaled_font, \"Precondition failure: _scaled_font must not be null\");\n PHOTON_ASSERT(_glyphs, \"Precondition failure: _glyphs must not be null\");\n PHOTON_ASSERT(_clusters, \"Precondition failure: _clusters must not be null\");\n\n auto cr = &canvas_.cairo_context();\n auto state = canvas_.new_state();\n\n cairo_set_scaled_font(cr, _scaled_font);\n cairo_translate(cr, pos.x - _glyphs->x, pos.y - _glyphs->y);\n canvas_.apply_fill_style();\n\n cairo_show_text_glyphs(\n cr, _first, int(_last - _first),\n _glyphs, _glyph_count,\n _clusters, _cluster_count, _clusterflags\n );\n }\n\n float glyphs::width() const\n {\n if (_first == _last)\n return 0;\n\n PHOTON_ASSERT(_scaled_font, \"Precondition failure: _scaled_font must not be null\");\n PHOTON_ASSERT(_glyphs, \"Precondition failure: _glyphs must not be null\");\n PHOTON_ASSERT(_clusters, \"Precondition failure: _clusters must not be null\");\n\n if (_glyph_count)\n {\n cairo_text_extents_t extents;\n auto glyph = _glyphs + _glyph_count -1;\n cairo_scaled_font_glyph_extents(_scaled_font, glyph, 1, &extents);\n return (glyph->x + extents.x_advance) - _glyphs->x;\n }\n return 0;\n }\n\n glyphs::font_metrics glyphs::metrics() const\n {\n cairo_font_extents_t font_extents;\n cairo_scaled_font_extents(_scaled_font, &font_extents);\n\n return {\n \/*ascent=*\/ float(font_extents.ascent),\n \/*descent=*\/ float(font_extents.descent),\n \/*leading=*\/ float(font_extents.height-(font_extents.ascent + font_extents.descent)),\n };\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n master_glyphs::master_glyphs(\n char const* first, char const* last\n , char const* face, float size, int style\n )\n : glyphs(first, last)\n {\n canvas cnv{ *scratch_context_.context() };\n cnv.font(face, size, style);\n auto cr = scratch_context_.context();\n _scaled_font = cairo_scaled_font_reference(cairo_get_scaled_font(cr));\n build();\n }\n\n master_glyphs::master_glyphs(char const* first, char const* last, master_glyphs const& source)\n : glyphs(first, last)\n {\n canvas cnv{ *scratch_context_.context() };\n _scaled_font = cairo_scaled_font_reference(source._scaled_font);\n build();\n }\n\n master_glyphs::master_glyphs(master_glyphs&& rhs)\n : glyphs(rhs._first, rhs._last)\n {\n _scaled_font = rhs._scaled_font;\n _glyphs = rhs._glyphs;\n _glyph_count = rhs._glyph_count;\n _clusters = rhs._clusters;\n _cluster_count = rhs._cluster_count;\n _clusterflags = rhs._clusterflags;\n\n rhs._glyphs = nullptr;\n rhs._clusters = nullptr;\n rhs._scaled_font = nullptr;\n }\n\n master_glyphs& master_glyphs::operator=(master_glyphs&& rhs)\n {\n if (&rhs != this)\n {\n _first = rhs._first;\n _last = rhs._last;\n _scaled_font = rhs._scaled_font;\n _glyphs = rhs._glyphs;\n _glyph_count = rhs._glyph_count;\n _clusters = rhs._clusters;\n _cluster_count = rhs._cluster_count;\n _clusterflags = rhs._clusterflags;\n\n rhs._glyphs = nullptr;\n rhs._clusters = nullptr;\n rhs._scaled_font = nullptr;\n }\n return *this;\n }\n\n master_glyphs::~master_glyphs()\n {\n if (_glyphs)\n cairo_glyph_free(_glyphs);\n if (_clusters)\n cairo_text_cluster_free(_clusters);\n if (_scaled_font)\n cairo_scaled_font_destroy(_scaled_font);\n\n _glyphs = nullptr;\n _clusters = nullptr;\n _scaled_font = nullptr;\n }\n\n void master_glyphs::text(char const* first, char const* last)\n {\n if (_glyphs)\n {\n cairo_glyph_free(_glyphs);\n _glyphs = nullptr;\n }\n if (_clusters)\n {\n cairo_text_cluster_free(_clusters);\n _clusters = nullptr;\n }\n\n _first = first;\n _last = last;\n build();\n }\n\n void master_glyphs::break_lines(float width, std::vector<glyphs>& lines)\n {\n PHOTON_ASSERT(_scaled_font, \"Precondition failure: _scaled_font must not be null\");\n\n \/\/ reurn early if there's nothing to break\n if (_first == _last)\n return;\n\n PHOTON_ASSERT(_glyphs, \"Precondition failure: _glyphs must not be null\");\n PHOTON_ASSERT(_clusters, \"Precondition failure: _clusters must not be null\");\n\n char const* first = _first;\n char const* last = _last;\n char const* space_pos = _first;\n int start_glyph_index = 0;\n int start_cluster_index = 0;\n int space_glyph_index = 0;\n int space_cluster_index = 0;\n float start_x = _glyphs->x;\n\n auto add_line = [&]()\n {\n glyphs glyph_{\n first, space_pos\n , start_glyph_index, space_glyph_index\n , start_cluster_index, space_cluster_index\n , *this\n , lines.size() > 1 \/\/ skip leading spaces if this is not the first line\n };\n lines.push_back(std::move(glyph_));\n first = space_pos;\n start_glyph_index = space_glyph_index;\n start_cluster_index = space_cluster_index;\n start_x = _glyphs[space_glyph_index].x;\n };\n\n int glyph_index = 0;\n unsigned codepoint;\n unsigned state = 0;\n\n cairo_text_cluster_t* cluster = _clusters;\n for (auto i = _first; i != _last; ++i)\n {\n if (!decode_utf8(state, codepoint, uint8_t(*i)))\n {\n cairo_glyph_t* glyph = _glyphs + glyph_index;\n\n \/\/ Check if we exceeded the line width:\n cairo_text_extents_t extents;\n cairo_scaled_font_glyph_extents(_scaled_font, glyph, 1, &extents);\n if (((glyph->x + extents.x_advance) - start_x) > width)\n {\n \/\/ Add the line if we did (exceed the line width)\n add_line();\n }\n\n \/\/ Did we have a space?\n else if (is_space(codepoint))\n {\n \/\/ Mark the spaces for later\n space_glyph_index = glyph_index;\n space_cluster_index = int(cluster - _clusters);\n space_pos = i;\n\n \/\/ If we got an explicit new line, add the line right away.\n if ((space_glyph_index != start_glyph_index) && is_newline(codepoint))\n add_line();\n }\n\n glyph_index += cluster->num_glyphs;\n ++cluster;\n }\n }\n\n glyphs glyph_{\n first, last\n , start_glyph_index, _glyph_count\n , start_cluster_index, _cluster_count\n , *this\n , lines.size() > 1 \/\/ skip leading spaces if this is not the first line\n };\n\n lines.push_back(std::move(glyph_));\n }\n\n void master_glyphs::build()\n {\n \/\/ reurn early if there's nothing to build\n if (_first == _last)\n return;\n\n auto stat = cairo_scaled_font_text_to_glyphs(\n _scaled_font, 0, 0, _first, int(_last - _first),\n &_glyphs, &_glyph_count, &_clusters, &_cluster_count,\n &_clusterflags);\n\n if (stat != CAIRO_STATUS_SUCCESS)\n {\n _glyphs = nullptr;\n _clusters = nullptr;\n throw failed_to_build_master_glyphs{};\n }\n }\n}\n<commit_msg>bugfix: remove leading space of second line<commit_after>\/*=============================================================================\n Copyright (c) 2016-2017 Joel de Guzman\n\n Distributed under the MIT License [ https:\/\/opensource.org\/licenses\/MIT ]\n=============================================================================*\/\n#include <photon\/support\/glyphs.hpp>\n#include <photon\/support\/detail\/scratch_context.hpp>\n\nnamespace photon\n{\n static detail::scratch_context scratch_context_;\n\n glyphs::glyphs(char const* first, char const* last)\n : _first(first)\n , _last(last)\n {\n PHOTON_ASSERT(_first, \"Precondition failure: _first must not be null\");\n PHOTON_ASSERT(_last, \"Precondition failure: _last must not be null\");\n }\n\n glyphs::glyphs(\n char const* first, char const* last\n , int glyph_start, int glyph_end\n , int cluster_start, int cluster_end\n , master_glyphs const& master\n , bool strip_leading_spaces\n )\n : _first(first)\n , _last(last)\n , _scaled_font(master._scaled_font)\n , _glyphs(master._glyphs + glyph_start)\n , _glyph_count(glyph_end - glyph_start)\n , _clusters(master._clusters + cluster_start)\n , _cluster_count(cluster_end - cluster_start)\n , _clusterflags(master._clusterflags)\n {\n PHOTON_ASSERT(_first, \"Precondition failure: _first must not be null\");\n PHOTON_ASSERT(_last, \"Precondition failure: _last must not be null\");\n PHOTON_ASSERT(_scaled_font, \"Precondition failure: _scaled_font must not be null\");\n PHOTON_ASSERT(_glyphs, \"Precondition failure: _glyphs must not be null\");\n PHOTON_ASSERT(_clusters, \"Precondition failure: _clusters must not be null\");\n\n \/\/ We strip leading spaces until after the last leading newline.\n \/\/ Examples:\n \/\/\n \/\/ \"\\n\\n \" ===> \" \"\n \/\/ \" \\n\\n\" ===> \"\"\n \/\/ \" xxx\" ===> \"xxx\"\n\n auto strip_leading = [this](auto f)\n {\n int glyph_index = 0;\n unsigned codepoint;\n unsigned state = 0;\n\n cairo_text_cluster_t* cluster = _clusters;\n for (auto i = _first; i != _last; ++i)\n {\n if (!decode_utf8(state, codepoint, uint8_t(*i)))\n {\n if (!f(codepoint))\n break;\n glyph_index += cluster->num_glyphs;\n ++cluster;\n }\n }\n\n auto clusters_skipped = int(cluster - _clusters);\n\n _glyph_count -= glyph_index;\n _glyphs += glyph_index;\n _cluster_count -= clusters_skipped;\n _clusters = cluster;\n _first += clusters_skipped;\n };\n\n if (strip_leading_spaces)\n strip_leading([](auto cp){ return !is_newline(cp) && is_space(cp); });\n strip_leading([](auto cp){ return is_newline(cp); });\n }\n\n void glyphs::draw(point pos, canvas& canvas_)\n {\n \/\/ return early if there's nothing to draw\n if (_first == _last)\n return;\n\n PHOTON_ASSERT(_scaled_font, \"Precondition failure: _scaled_font must not be null\");\n PHOTON_ASSERT(_glyphs, \"Precondition failure: _glyphs must not be null\");\n PHOTON_ASSERT(_clusters, \"Precondition failure: _clusters must not be null\");\n\n auto cr = &canvas_.cairo_context();\n auto state = canvas_.new_state();\n\n cairo_set_scaled_font(cr, _scaled_font);\n cairo_translate(cr, pos.x - _glyphs->x, pos.y - _glyphs->y);\n canvas_.apply_fill_style();\n\n cairo_show_text_glyphs(\n cr, _first, int(_last - _first),\n _glyphs, _glyph_count,\n _clusters, _cluster_count, _clusterflags\n );\n }\n\n float glyphs::width() const\n {\n if (_first == _last)\n return 0;\n\n PHOTON_ASSERT(_scaled_font, \"Precondition failure: _scaled_font must not be null\");\n PHOTON_ASSERT(_glyphs, \"Precondition failure: _glyphs must not be null\");\n PHOTON_ASSERT(_clusters, \"Precondition failure: _clusters must not be null\");\n\n if (_glyph_count)\n {\n cairo_text_extents_t extents;\n auto glyph = _glyphs + _glyph_count -1;\n cairo_scaled_font_glyph_extents(_scaled_font, glyph, 1, &extents);\n return (glyph->x + extents.x_advance) - _glyphs->x;\n }\n return 0;\n }\n\n glyphs::font_metrics glyphs::metrics() const\n {\n cairo_font_extents_t font_extents;\n cairo_scaled_font_extents(_scaled_font, &font_extents);\n\n return {\n \/*ascent=*\/ float(font_extents.ascent),\n \/*descent=*\/ float(font_extents.descent),\n \/*leading=*\/ float(font_extents.height-(font_extents.ascent + font_extents.descent)),\n };\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n master_glyphs::master_glyphs(\n char const* first, char const* last\n , char const* face, float size, int style\n )\n : glyphs(first, last)\n {\n canvas cnv{ *scratch_context_.context() };\n cnv.font(face, size, style);\n auto cr = scratch_context_.context();\n _scaled_font = cairo_scaled_font_reference(cairo_get_scaled_font(cr));\n build();\n }\n\n master_glyphs::master_glyphs(char const* first, char const* last, master_glyphs const& source)\n : glyphs(first, last)\n {\n canvas cnv{ *scratch_context_.context() };\n _scaled_font = cairo_scaled_font_reference(source._scaled_font);\n build();\n }\n\n master_glyphs::master_glyphs(master_glyphs&& rhs)\n : glyphs(rhs._first, rhs._last)\n {\n _scaled_font = rhs._scaled_font;\n _glyphs = rhs._glyphs;\n _glyph_count = rhs._glyph_count;\n _clusters = rhs._clusters;\n _cluster_count = rhs._cluster_count;\n _clusterflags = rhs._clusterflags;\n\n rhs._glyphs = nullptr;\n rhs._clusters = nullptr;\n rhs._scaled_font = nullptr;\n }\n\n master_glyphs& master_glyphs::operator=(master_glyphs&& rhs)\n {\n if (&rhs != this)\n {\n _first = rhs._first;\n _last = rhs._last;\n _scaled_font = rhs._scaled_font;\n _glyphs = rhs._glyphs;\n _glyph_count = rhs._glyph_count;\n _clusters = rhs._clusters;\n _cluster_count = rhs._cluster_count;\n _clusterflags = rhs._clusterflags;\n\n rhs._glyphs = nullptr;\n rhs._clusters = nullptr;\n rhs._scaled_font = nullptr;\n }\n return *this;\n }\n\n master_glyphs::~master_glyphs()\n {\n if (_glyphs)\n cairo_glyph_free(_glyphs);\n if (_clusters)\n cairo_text_cluster_free(_clusters);\n if (_scaled_font)\n cairo_scaled_font_destroy(_scaled_font);\n\n _glyphs = nullptr;\n _clusters = nullptr;\n _scaled_font = nullptr;\n }\n\n void master_glyphs::text(char const* first, char const* last)\n {\n if (_glyphs)\n {\n cairo_glyph_free(_glyphs);\n _glyphs = nullptr;\n }\n if (_clusters)\n {\n cairo_text_cluster_free(_clusters);\n _clusters = nullptr;\n }\n\n _first = first;\n _last = last;\n build();\n }\n\n void master_glyphs::break_lines(float width, std::vector<glyphs>& lines)\n {\n PHOTON_ASSERT(_scaled_font, \"Precondition failure: _scaled_font must not be null\");\n\n \/\/ reurn early if there's nothing to break\n if (_first == _last)\n return;\n\n PHOTON_ASSERT(_glyphs, \"Precondition failure: _glyphs must not be null\");\n PHOTON_ASSERT(_clusters, \"Precondition failure: _clusters must not be null\");\n\n char const* first = _first;\n char const* last = _last;\n char const* space_pos = _first;\n int start_glyph_index = 0;\n int start_cluster_index = 0;\n int space_glyph_index = 0;\n int space_cluster_index = 0;\n float start_x = _glyphs->x;\n\n auto add_line = [&]()\n {\n glyphs glyph_{\n first, space_pos\n , start_glyph_index, space_glyph_index\n , start_cluster_index, space_cluster_index\n , *this\n , lines.size() > 0 \/\/ skip leading spaces if this is not the first line\n };\n lines.push_back(std::move(glyph_));\n first = space_pos;\n start_glyph_index = space_glyph_index;\n start_cluster_index = space_cluster_index;\n start_x = _glyphs[space_glyph_index].x;\n };\n\n int glyph_index = 0;\n unsigned codepoint;\n unsigned state = 0;\n\n cairo_text_cluster_t* cluster = _clusters;\n for (auto i = _first; i != _last; ++i)\n {\n if (!decode_utf8(state, codepoint, uint8_t(*i)))\n {\n cairo_glyph_t* glyph = _glyphs + glyph_index;\n\n \/\/ Check if we exceeded the line width:\n cairo_text_extents_t extents;\n cairo_scaled_font_glyph_extents(_scaled_font, glyph, 1, &extents);\n if (((glyph->x + extents.x_advance) - start_x) > width)\n {\n \/\/ Add the line if we did (exceed the line width)\n add_line();\n }\n\n \/\/ Did we have a space?\n else if (is_space(codepoint))\n {\n \/\/ Mark the spaces for later\n space_glyph_index = glyph_index;\n space_cluster_index = int(cluster - _clusters);\n space_pos = i;\n\n \/\/ If we got an explicit new line, add the line right away.\n if ((space_glyph_index != start_glyph_index) && is_newline(codepoint))\n add_line();\n }\n\n glyph_index += cluster->num_glyphs;\n ++cluster;\n }\n }\n\n glyphs glyph_{\n first, last\n , start_glyph_index, _glyph_count\n , start_cluster_index, _cluster_count\n , *this\n , lines.size() > 1 \/\/ skip leading spaces if this is not the first line\n };\n\n lines.push_back(std::move(glyph_));\n }\n\n void master_glyphs::build()\n {\n \/\/ reurn early if there's nothing to build\n if (_first == _last)\n return;\n\n auto stat = cairo_scaled_font_text_to_glyphs(\n _scaled_font, 0, 0, _first, int(_last - _first),\n &_glyphs, &_glyph_count, &_clusters, &_cluster_count,\n &_clusterflags);\n\n if (stat != CAIRO_STATUS_SUCCESS)\n {\n _glyphs = nullptr;\n _clusters = nullptr;\n throw failed_to_build_master_glyphs{};\n }\n }\n}\n<|endoftext|>"} {"text":"<commit_before>e2801b66-327f-11e5-a187-9cf387a8033e<commit_msg>e28676bd-327f-11e5-8e54-9cf387a8033e<commit_after>e28676bd-327f-11e5-8e54-9cf387a8033e<|endoftext|>"} {"text":"<commit_before>29af778a-2f67-11e5-9790-6c40088e03e4<commit_msg>29b579fe-2f67-11e5-af6d-6c40088e03e4<commit_after>29b579fe-2f67-11e5-af6d-6c40088e03e4<|endoftext|>"} {"text":"<commit_before>#include <iostream>\r\n#include <ostream>\r\n#include <string>\r\n\r\nint main()\r\n{\r\n std::cout<< \"Adınız Nedir? \";\r\n std::string str;\r\n std::getline(std::cin,str);\r\n std::cout<< \"Selâmü Aleyküm \"<< str<< '\\n';\r\n return 0;\r\n}\r\n\r\n<commit_msg>removed redundant return from main<commit_after>#include <iostream>\r\n#include <ostream>\r\n#include <string>\r\n\r\nint main()\r\n{\r\n std::cout<< \"Adınız Nedir? \";\r\n std::string str;\r\n std::getline(std::cin,str);\r\n std::cout<< \"Selâmü Aleyküm \"<< str<< '\\n';\r\n}\r\n\r\n<|endoftext|>"} {"text":"<commit_before>0f098e19-2e4f-11e5-a275-28cfe91dbc4b<commit_msg>0f1044eb-2e4f-11e5-8a36-28cfe91dbc4b<commit_after>0f1044eb-2e4f-11e5-8a36-28cfe91dbc4b<|endoftext|>"} {"text":"<commit_before>b7b54168-2e4f-11e5-b545-28cfe91dbc4b<commit_msg>b7bc81f8-2e4f-11e5-80c1-28cfe91dbc4b<commit_after>b7bc81f8-2e4f-11e5-80c1-28cfe91dbc4b<|endoftext|>"} {"text":"<commit_before>613f9fc0-5216-11e5-a945-6c40088e03e4<commit_msg>6153b064-5216-11e5-a115-6c40088e03e4<commit_after>6153b064-5216-11e5-a115-6c40088e03e4<|endoftext|>"} {"text":"<commit_before>9c4c0d4f-2e4f-11e5-9b74-28cfe91dbc4b<commit_msg>9c52bd07-2e4f-11e5-8ca0-28cfe91dbc4b<commit_after>9c52bd07-2e4f-11e5-8ca0-28cfe91dbc4b<|endoftext|>"} {"text":"<commit_before>e2fc6551-2e4e-11e5-8060-28cfe91dbc4b<commit_msg>e302ed14-2e4e-11e5-b656-28cfe91dbc4b<commit_after>e302ed14-2e4e-11e5-b656-28cfe91dbc4b<|endoftext|>"} {"text":"<commit_before>5f894945-2d16-11e5-af21-0401358ea401<commit_msg>5f894946-2d16-11e5-af21-0401358ea401<commit_after>5f894946-2d16-11e5-af21-0401358ea401<|endoftext|>"} {"text":"<commit_before>725c919e-5216-11e5-821f-6c40088e03e4<commit_msg>7263c876-5216-11e5-9679-6c40088e03e4<commit_after>7263c876-5216-11e5-9679-6c40088e03e4<|endoftext|>"} {"text":"<commit_before>de1a45a3-2e4e-11e5-9b11-28cfe91dbc4b<commit_msg>de20e5d9-2e4e-11e5-bbe8-28cfe91dbc4b<commit_after>de20e5d9-2e4e-11e5-bbe8-28cfe91dbc4b<|endoftext|>"} {"text":"<commit_before>7f6cf64f-2d15-11e5-af21-0401358ea401<commit_msg>7f6cf650-2d15-11e5-af21-0401358ea401<commit_after>7f6cf650-2d15-11e5-af21-0401358ea401<|endoftext|>"} {"text":"<commit_before>db00b163-2e4e-11e5-8afd-28cfe91dbc4b<commit_msg>db070b35-2e4e-11e5-8596-28cfe91dbc4b<commit_after>db070b35-2e4e-11e5-8596-28cfe91dbc4b<|endoftext|>"} {"text":"<commit_before>8d66b9fa-35ca-11e5-88c3-6c40088e03e4<commit_msg>8d6d68cc-35ca-11e5-b689-6c40088e03e4<commit_after>8d6d68cc-35ca-11e5-b689-6c40088e03e4<|endoftext|>"} {"text":"<commit_before>23fd402e-2f67-11e5-919a-6c40088e03e4<commit_msg>24041a02-2f67-11e5-940e-6c40088e03e4<commit_after>24041a02-2f67-11e5-940e-6c40088e03e4<|endoftext|>"} {"text":"<commit_before>6a309ff8-2e3a-11e5-a127-c03896053bdd<commit_msg>6a422f66-2e3a-11e5-8169-c03896053bdd<commit_after>6a422f66-2e3a-11e5-8169-c03896053bdd<|endoftext|>"} {"text":"<commit_before>8c3d20ad-2d14-11e5-af21-0401358ea401<commit_msg>8c3d20ae-2d14-11e5-af21-0401358ea401<commit_after>8c3d20ae-2d14-11e5-af21-0401358ea401<|endoftext|>"} {"text":"<commit_before>4f88c826-2e4f-11e5-a536-28cfe91dbc4b<commit_msg>4f8f9a4a-2e4f-11e5-8c9c-28cfe91dbc4b<commit_after>4f8f9a4a-2e4f-11e5-8c9c-28cfe91dbc4b<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: respintest.cxx,v $\n *\n * $Revision: 1.8 $\n *\n * last change: $Author: vg $ $Date: 2007-03-26 14:08:03 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#undef UNICODE\n#undef _UNICODE\n\n#pragma warning(push, 1) \/* disable warnings within system headers *\/\n#define WIN32_LEAN_AND_MEAN\n#include <windows.h>\n#include <msiquery.h>\n#pragma warning(pop)\n\n#include <malloc.h>\n#include <assert.h>\n\n#include <tchar.h>\n#include <string>\n#include <systools\/win32\/uwinapi.h>\n\n#if defined(_WIN32_WINNT) && !defined(__MINGW32__)\n#error YES\n#endif\n\nusing namespace std;\n\nnamespace\n{\n string GetMsiProperty(MSIHANDLE handle, const string& sProperty)\n {\n string result;\n TCHAR szDummy[1] = TEXT(\"\");\n DWORD nChars = 0;\n\n if (MsiGetProperty(handle, sProperty.c_str(), szDummy, &nChars) == ERROR_MORE_DATA)\n {\n DWORD nBytes = ++nChars * sizeof(TCHAR);\n LPTSTR buffer = reinterpret_cast<LPTSTR>(_alloca(nBytes));\n ZeroMemory( buffer, nBytes );\n MsiGetProperty(handle, sProperty.c_str(), buffer, &nChars);\n result = buffer;\n }\n return result;\n }\n\n inline bool IsSetMsiProperty(MSIHANDLE handle, const string& sProperty)\n {\n return (GetMsiProperty(handle, sProperty).length() > 0);\n }\n\n inline void UnsetMsiProperty(MSIHANDLE handle, const string& sProperty)\n {\n MsiSetProperty(handle, sProperty.c_str(), NULL);\n }\n\n inline void SetMsiProperty(MSIHANDLE handle, const string& sProperty, const string&)\n {\n MsiSetProperty(handle, sProperty.c_str(), TEXT(\"1\"));\n }\n\n} \/\/ namespace\n\nextern \"C\" UINT __stdcall GetUserInstallMode(MSIHANDLE handle)\n{\n string sInstallPath = GetMsiProperty(handle, TEXT(\"INSTALLLOCATION\"));\n\n \/\/ MessageBox(NULL, sInstallPath.c_str(), \"DEBUG\", MB_OK);\n\n \/\/ unsetting all properties\n\n UnsetMsiProperty( handle, TEXT(\"INVALIDDIRECTORY\") );\n UnsetMsiProperty( handle, TEXT(\"ISWRONGPRODUCT\") );\n UnsetMsiProperty( handle, TEXT(\"PATCHISOLDER\") );\n UnsetMsiProperty( handle, TEXT(\"ALLUSERS\") );\n\n \/\/ 1. Searching for \"ProductCode\" in setup.ini\n\n string sSetupiniPath = sInstallPath + TEXT(\"program\\\\setup.ini\");\n\n TCHAR szValue[32767];\n\n GetPrivateProfileString(\n TEXT(\"Bootstrap\"),\n TEXT(\"ProductCode\"),\n TEXT(\"INVALIDDIRECTORY\"),\n szValue,\n elementsof(szValue),\n sSetupiniPath.c_str()\n );\n\n if ( !_tcsicmp( szValue, TEXT(\"INVALIDDIRECTORY\") ) )\n {\n \/\/ No setup.ini or no \"ProductCode\" in setup.ini. This is an invalid directory.\n SetMsiProperty( handle, TEXT(\"INVALIDDIRECTORY\"), TEXT(\"YES\") );\n \/\/ MessageBox(NULL, \"INVALIDDIRECTORY set\", \"DEBUG\", MB_OK);\n return ERROR_SUCCESS;\n }\n\n \/\/ 2. Searching for \"version.ini\" and \"bootstrap.ini\"\n\n \/\/ version.ini is the new file, that shall be used. If there is no version.ini, it can be possible\n \/\/ that this is an old src680-version, in which only bootstrap.ini exists. In this case, the data\n \/\/ have to be read from bootstrap.ini.\n\n string sBootstrapPath = sInstallPath + TEXT(\"program\\\\bootstrap.ini\");\n string sVersionPath = sInstallPath + TEXT(\"program\\\\version.ini\");\n string sInfofilePath = \"\";\n string sectionname = \"\";\n\n WIN32_FIND_DATA data;\n HANDLE hdl = FindFirstFile(sVersionPath.c_str(), &data);\n\n \/\/ string mystr = \"Searching for \" + sVersionPath;\n \/\/ MessageBox(NULL, mystr.c_str(), \"DEBUG\", MB_OK);\n\n \/\/ if (hdl == INVALID_HANDLE_VALUE)\n if ( ! IsValidHandle(hdl) )\n {\n \/\/ version.ini not found.\n \/\/ Searching for bootstrap.ini\n\n hdl = FindFirstFile(sBootstrapPath.c_str(), &data);\n\n \/\/ mystr = \"Searching for \" + sBootstrapPath;\n \/\/ MessageBox(NULL, mystr.c_str(), \"DEBUG\", MB_OK);\n\n \/\/ if (hdl == INVALID_HANDLE_VALUE)\n if ( ! IsValidHandle(hdl) )\n {\n \/\/ Neither bootstrap.ini nor version.ini exist -> this is a wrong product\n \/\/ MessageBox(NULL, \"Neither bootstrap.ini nor version.ini exist -> ISWRONGPRODUCT 1 set\", \"DEBUG\", MB_OK);\n SetMsiProperty( handle, TEXT(\"ISWRONGPRODUCT\"), TEXT(\"YES\") );\n \/\/ MessageBox(NULL, \"ISWRONGPRODUCT 1 set\", \"DEBUG\", MB_OK);\n return ERROR_SUCCESS;\n }\n else\n {\n \/\/ bootstrap.ini found, it can be used as InfoFile\n sInfofilePath = sBootstrapPath;\n sectionname = TEXT(\"Bootstrap\");\n \/\/ mystr = \"bootstrap.ini found, section name: \" + sectionname;\n \/\/ MessageBox(NULL, mystr.c_str(), \"DEBUG\", MB_OK);\n }\n }\n else\n {\n \/\/ version.ini found, it can be used as InfoFile\n sInfofilePath = sVersionPath;\n sectionname = TEXT(\"Version\");\n \/\/ mystr = \"version.ini found, section name: \" + sectionname;\n \/\/ MessageBox(NULL, mystr.c_str(), \"DEBUG\", MB_OK);\n }\n\n \/\/ mystr = \"Value of sInfofilePath: \" + sInfofilePath;\n \/\/ MessageBox(NULL, mystr.c_str(), \"DEBUG\", MB_OK);\n\n \/\/ 3. Comparing first three characters of \"PRODUCTMAJOR\" from property table and \"buildid\" from InfoFile\n\n szValue[0] = '\\0';\n\n GetPrivateProfileString(\n TEXT(sectionname.c_str()),\n TEXT(\"buildid\"),\n TEXT(\"ISWRONGPRODUCT\"),\n szValue,\n elementsof(szValue),\n sInfofilePath.c_str()\n );\n\n if ( !_tcsicmp( szValue, TEXT(\"ISWRONGPRODUCT\") ) )\n {\n SetMsiProperty( handle, TEXT(\"ISWRONGPRODUCT\"), TEXT(\"YES\") );\n \/\/ MessageBox(NULL, \"ISWRONGPRODUCT 1 set\", \"DEBUG\", MB_OK);\n return ERROR_SUCCESS;\n }\n\n string ProductMajor = GetMsiProperty(handle, TEXT(\"PRODUCTMAJOR\"));\n\n \/\/ Comparing the first three characters, for example \"680\"\n \/\/ If not equal, this version is not suited for patch or language pack\n\n if (_tcsnicmp(ProductMajor.c_str(), szValue, 3))\n {\n SetMsiProperty( handle, TEXT(\"ISWRONGPRODUCT\"), TEXT(\"YES\") );\n \/\/ MessageBox(NULL, \"ISWRONGPRODUCT 2 set\", \"DEBUG\", MB_OK);\n return ERROR_SUCCESS;\n }\n\n \/\/ 4. Only for patch: Comparing \"PRODUCTMINOR from property table and \"ProductMinor\" from InfoFile\n\n string isPatch = GetMsiProperty(handle, TEXT(\"ISPATCH\"));\n\n if (isPatch==\"1\")\n {\n string ProductMinor = GetMsiProperty(handle, TEXT(\"PRODUCTBUILDID\"));\n int PatchProductMinor = atoi(ProductMinor.c_str());\n\n szValue[0] = '\\0';\n\n GetPrivateProfileString(\n TEXT(sectionname.c_str()),\n TEXT(\"ProductBuildid\"),\n TEXT(\"8918\"),\n szValue,\n elementsof(szValue),\n sInfofilePath.c_str()\n );\n\n int InstalledProductMinor = atoi(szValue);\n\n if ( InstalledProductMinor >= PatchProductMinor )\n {\n SetMsiProperty( handle, TEXT(\"PATCHISOLDER\"), TEXT(\"YES\") );\n \/\/ MessageBox(NULL, \"PATCHISOLDER set\", \"DEBUG\", MB_OK);\n return ERROR_SUCCESS;\n }\n }\n\n \/\/ 5. Setting property ALLUSERS with value from \"setup.ini\"\n\n szValue[0] = '\\0';\n\n GetPrivateProfileString(\n TEXT(\"Bootstrap\"),\n TEXT(\"ALLUSERS\"),\n TEXT(\"\"),\n szValue,\n elementsof(szValue),\n sSetupiniPath.c_str()\n );\n\n if ( szValue[0] )\n {\n SetMsiProperty( handle, TEXT(\"ALLUSERS\"), szValue );\n \/\/ MessageBox(NULL, \"ALLUSERS set\", \"DEBUG\", MB_OK);\n }\n\n return ERROR_SUCCESS;\n}\n<commit_msg>INTEGRATION: CWS native82 (1.7.72); FILE MERGED 2007\/03\/29 11:54:38 is 1.7.72.4: RESYNC: (1.7-1.8); FILE MERGED 2007\/03\/28 07:26:34 dv 1.7.72.3: #i75394# Use only one function definition of SetMSIErrorCode 2007\/03\/27 11:53:37 dv 1.7.72.2: #i75394# Use the name global... for the memory mapped file 2007\/03\/27 11:51:53 dv 1.7.72.1: #i75394# Transfer error codes to setup loader<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: respintest.cxx,v $\n *\n * $Revision: 1.9 $\n *\n * last change: $Author: gm $ $Date: 2007-05-10 11:02:43 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#undef UNICODE\n#undef _UNICODE\n\n#pragma warning(push, 1) \/* disable warnings within system headers *\/\n#define WIN32_LEAN_AND_MEAN\n#include <windows.h>\n#include <msiquery.h>\n#pragma warning(pop)\n\n#include <malloc.h>\n#include <assert.h>\n\n#include <tchar.h>\n#include <string>\n#include <systools\/win32\/uwinapi.h>\n\n#include <..\/tools\/seterror.hxx>\n\n#if defined(_WIN32_WINNT) && !defined(__MINGW32__)\n#error YES\n#endif\n\nusing namespace std;\n\nnamespace\n{\n string GetMsiProperty(MSIHANDLE handle, const string& sProperty)\n {\n string result;\n TCHAR szDummy[1] = TEXT(\"\");\n DWORD nChars = 0;\n\n if (MsiGetProperty(handle, sProperty.c_str(), szDummy, &nChars) == ERROR_MORE_DATA)\n {\n DWORD nBytes = ++nChars * sizeof(TCHAR);\n LPTSTR buffer = reinterpret_cast<LPTSTR>(_alloca(nBytes));\n ZeroMemory( buffer, nBytes );\n MsiGetProperty(handle, sProperty.c_str(), buffer, &nChars);\n result = buffer;\n }\n return result;\n }\n\n inline bool IsSetMsiProperty(MSIHANDLE handle, const string& sProperty)\n {\n return (GetMsiProperty(handle, sProperty).length() > 0);\n }\n\n inline void UnsetMsiProperty(MSIHANDLE handle, const string& sProperty)\n {\n MsiSetProperty(handle, sProperty.c_str(), NULL);\n }\n\n inline void SetMsiProperty(MSIHANDLE handle, const string& sProperty, const string&)\n {\n MsiSetProperty(handle, sProperty.c_str(), TEXT(\"1\"));\n }\n} \/\/ namespace\n\nextern \"C\" UINT __stdcall GetUserInstallMode(MSIHANDLE handle)\n{\n string sInstallPath = GetMsiProperty(handle, TEXT(\"INSTALLLOCATION\"));\n\n \/\/ MessageBox(NULL, sInstallPath.c_str(), \"DEBUG\", MB_OK);\n\n \/\/ unsetting all properties\n\n UnsetMsiProperty( handle, TEXT(\"INVALIDDIRECTORY\") );\n UnsetMsiProperty( handle, TEXT(\"ISWRONGPRODUCT\") );\n UnsetMsiProperty( handle, TEXT(\"PATCHISOLDER\") );\n UnsetMsiProperty( handle, TEXT(\"ALLUSERS\") );\n\n \/\/ 1. Searching for \"ProductCode\" in setup.ini\n\n string sSetupiniPath = sInstallPath + TEXT(\"program\\\\setup.ini\");\n\n TCHAR szValue[32767];\n\n GetPrivateProfileString(\n TEXT(\"Bootstrap\"),\n TEXT(\"ProductCode\"),\n TEXT(\"INVALIDDIRECTORY\"),\n szValue,\n elementsof(szValue),\n sSetupiniPath.c_str()\n );\n\n if ( !_tcsicmp( szValue, TEXT(\"INVALIDDIRECTORY\") ) )\n {\n \/\/ No setup.ini or no \"ProductCode\" in setup.ini. This is an invalid directory.\n SetMsiProperty( handle, TEXT(\"INVALIDDIRECTORY\"), TEXT(\"YES\") );\n \/\/ MessageBox(NULL, \"INVALIDDIRECTORY set\", \"DEBUG\", MB_OK);\n SetMsiErrorCode( MSI_ERROR_INVALIDDIRECTORY );\n return ERROR_SUCCESS;\n }\n\n \/\/ 2. Searching for \"version.ini\" and \"bootstrap.ini\"\n\n \/\/ version.ini is the new file, that shall be used. If there is no version.ini, it can be possible\n \/\/ that this is an old src680-version, in which only bootstrap.ini exists. In this case, the data\n \/\/ have to be read from bootstrap.ini.\n\n string sBootstrapPath = sInstallPath + TEXT(\"program\\\\bootstrap.ini\");\n string sVersionPath = sInstallPath + TEXT(\"program\\\\version.ini\");\n string sInfofilePath = \"\";\n string sectionname = \"\";\n\n WIN32_FIND_DATA data;\n HANDLE hdl = FindFirstFile(sVersionPath.c_str(), &data);\n\n \/\/ string mystr = \"Searching for \" + sVersionPath;\n \/\/ MessageBox(NULL, mystr.c_str(), \"DEBUG\", MB_OK);\n\n \/\/ if (hdl == INVALID_HANDLE_VALUE)\n if ( ! IsValidHandle(hdl) )\n {\n \/\/ version.ini not found.\n \/\/ Searching for bootstrap.ini\n\n hdl = FindFirstFile(sBootstrapPath.c_str(), &data);\n\n \/\/ mystr = \"Searching for \" + sBootstrapPath;\n \/\/ MessageBox(NULL, mystr.c_str(), \"DEBUG\", MB_OK);\n\n \/\/ if (hdl == INVALID_HANDLE_VALUE)\n if ( ! IsValidHandle(hdl) )\n {\n \/\/ Neither bootstrap.ini nor version.ini exist -> this is a wrong product\n \/\/ MessageBox(NULL, \"Neither bootstrap.ini nor version.ini exist -> ISWRONGPRODUCT 1 set\", \"DEBUG\", MB_OK);\n SetMsiProperty( handle, TEXT(\"ISWRONGPRODUCT\"), TEXT(\"YES\") );\n \/\/ MessageBox(NULL, \"ISWRONGPRODUCT 1 set\", \"DEBUG\", MB_OK);\n SetMsiErrorCode( MSI_ERROR_ISWRONGPRODUCT );\n return ERROR_SUCCESS;\n }\n else\n {\n \/\/ bootstrap.ini found, it can be used as InfoFile\n sInfofilePath = sBootstrapPath;\n sectionname = TEXT(\"Bootstrap\");\n \/\/ mystr = \"bootstrap.ini found, section name: \" + sectionname;\n \/\/ MessageBox(NULL, mystr.c_str(), \"DEBUG\", MB_OK);\n }\n }\n else\n {\n \/\/ version.ini found, it can be used as InfoFile\n sInfofilePath = sVersionPath;\n sectionname = TEXT(\"Version\");\n \/\/ mystr = \"version.ini found, section name: \" + sectionname;\n \/\/ MessageBox(NULL, mystr.c_str(), \"DEBUG\", MB_OK);\n }\n\n \/\/ mystr = \"Value of sInfofilePath: \" + sInfofilePath;\n \/\/ MessageBox(NULL, mystr.c_str(), \"DEBUG\", MB_OK);\n\n \/\/ 3. Comparing first three characters of \"PRODUCTMAJOR\" from property table and \"buildid\" from InfoFile\n\n szValue[0] = '\\0';\n\n GetPrivateProfileString(\n TEXT(sectionname.c_str()),\n TEXT(\"buildid\"),\n TEXT(\"ISWRONGPRODUCT\"),\n szValue,\n elementsof(szValue),\n sInfofilePath.c_str()\n );\n\n if ( !_tcsicmp( szValue, TEXT(\"ISWRONGPRODUCT\") ) )\n {\n SetMsiProperty( handle, TEXT(\"ISWRONGPRODUCT\"), TEXT(\"YES\") );\n \/\/ MessageBox(NULL, \"ISWRONGPRODUCT 1 set\", \"DEBUG\", MB_OK);\n SetMsiErrorCode( MSI_ERROR_ISWRONGPRODUCT );\n return ERROR_SUCCESS;\n }\n\n string ProductMajor = GetMsiProperty(handle, TEXT(\"PRODUCTMAJOR\"));\n\n \/\/ Comparing the first three characters, for example \"680\"\n \/\/ If not equal, this version is not suited for patch or language pack\n\n if (_tcsnicmp(ProductMajor.c_str(), szValue, 3))\n {\n SetMsiProperty( handle, TEXT(\"ISWRONGPRODUCT\"), TEXT(\"YES\") );\n \/\/ MessageBox(NULL, \"ISWRONGPRODUCT 2 set\", \"DEBUG\", MB_OK);\n SetMsiErrorCode( MSI_ERROR_ISWRONGPRODUCT );\n return ERROR_SUCCESS;\n }\n\n \/\/ 4. Only for patch: Comparing \"PRODUCTMINOR from property table and \"ProductMinor\" from InfoFile\n\n string isPatch = GetMsiProperty(handle, TEXT(\"ISPATCH\"));\n\n if (isPatch==\"1\")\n {\n string ProductMinor = GetMsiProperty(handle, TEXT(\"PRODUCTBUILDID\"));\n int PatchProductMinor = atoi(ProductMinor.c_str());\n\n szValue[0] = '\\0';\n\n GetPrivateProfileString(\n TEXT(sectionname.c_str()),\n TEXT(\"ProductBuildid\"),\n TEXT(\"8918\"),\n szValue,\n elementsof(szValue),\n sInfofilePath.c_str()\n );\n\n int InstalledProductMinor = atoi(szValue);\n\n if ( InstalledProductMinor >= PatchProductMinor )\n {\n SetMsiProperty( handle, TEXT(\"PATCHISOLDER\"), TEXT(\"YES\") );\n \/\/ MessageBox(NULL, \"PATCHISOLDER set\", \"DEBUG\", MB_OK);\n SetMsiErrorCode( MSI_ERROR_PATCHISOLDER );\n return ERROR_SUCCESS;\n }\n }\n\n \/\/ 5. Setting property ALLUSERS with value from \"setup.ini\"\n\n szValue[0] = '\\0';\n\n GetPrivateProfileString(\n TEXT(\"Bootstrap\"),\n TEXT(\"ALLUSERS\"),\n TEXT(\"\"),\n szValue,\n elementsof(szValue),\n sSetupiniPath.c_str()\n );\n\n if ( szValue[0] )\n {\n SetMsiProperty( handle, TEXT(\"ALLUSERS\"), szValue );\n \/\/ MessageBox(NULL, \"ALLUSERS set\", \"DEBUG\", MB_OK);\n }\n\n return ERROR_SUCCESS;\n}\n<|endoftext|>"} {"text":"<commit_before>ffec766c-585a-11e5-9f9c-6c40088e03e4<commit_msg>fff3aa9a-585a-11e5-8108-6c40088e03e4<commit_after>fff3aa9a-585a-11e5-8108-6c40088e03e4<|endoftext|>"} {"text":"<commit_before>f19ceadc-2e4e-11e5-9e55-28cfe91dbc4b<commit_msg>f1a3f8fd-2e4e-11e5-bd21-28cfe91dbc4b<commit_after>f1a3f8fd-2e4e-11e5-bd21-28cfe91dbc4b<|endoftext|>"} {"text":"<commit_before>#include \"libtorrent\/session.hpp\"\n#include \"libtorrent\/alert_types.hpp\"\n\n#include <boost\/asio\/io_service.hpp>\n#include <boost\/bind.hpp>\n#include <memory>\n#include <mutex>\n#include <stdlib.h>\n\nusing namespace libtorrent;\n\nvoid usage()\n{\n\tstd::cerr << \"USAGE: bootstrap-dht-bot <host> <port>\" << std::endl;\n\texit(1);\n}\n\n\nvoid dispatch_libtorrent_alert(std::shared_ptr<session> s, std::auto_ptr<libtorrent::alert> libtorrent_alert)\n{\n std::cerr << \"libtorrent alert: \" << libtorrent_alert->message() << std::endl;\n switch (libtorrent_alert->type()) {\n case libtorrent::dht_bootstrap_alert::alert_type:\n std::cerr << \"bootstrapping successful\" << std::endl;\n break;\n }\n}\n\nint main(int argc, char* argv[])\n{\n\tif (argc != 3) {\n usage();\n }\n\n const char* host = argv[1];\n int port = atoi(argv[2]);\n int flags = 0;\n\n if (port == 0) {\n std::cerr << \"error: port is invalid\" << std::endl;\n exit(-1);\n }\n\n libtorrent::fingerprint fp(\"LT\", LIBTORRENT_VERSION_MAJOR, LIBTORRENT_VERSION_MINOR, 0, 0);\n std::shared_ptr<libtorrent::session> s = std::make_shared<libtorrent::session>(\n fp, std::make_pair(port, port + 8), \"0.0.0.0\", flags,\n libtorrent::alert::port_mapping_notification |\n libtorrent::alert::debug_notification |\n libtorrent::alert::dht_notification |\n libtorrent::alert::error_notification |\n libtorrent::alert::status_notification);\n\n s->set_alert_dispatch(std::bind(&dispatch_libtorrent_alert, s, std::placeholders::_1));\n s->add_dht_router(std::make_pair(host, 6881));\n s->start_dht();\n\n \/\/ Just block here and let the session run forever.\n std::mutex forever;\n forever.lock();\n forever.lock();\n}\n<commit_msg>Update bot to take in a session port<commit_after>#include \"libtorrent\/session.hpp\"\n#include \"libtorrent\/alert_types.hpp\"\n\n#include <boost\/asio\/io_service.hpp>\n#include <boost\/bind.hpp>\n#include <memory>\n#include <mutex>\n#include <stdlib.h>\n\nusing namespace libtorrent;\n\nvoid usage()\n{\n\tstd::cerr << \"USAGE: bootstrap-dht-bot <server-host> <server-port> <session-port>\" << std::endl;\n\texit(1);\n}\n\n\nvoid dispatch_libtorrent_alert(std::shared_ptr<session> s, std::auto_ptr<libtorrent::alert> libtorrent_alert)\n{\n std::cerr << \"libtorrent alert: \" << libtorrent_alert->message() << std::endl;\n switch (libtorrent_alert->type()) {\n case libtorrent::dht_bootstrap_alert::alert_type:\n std::cerr << \"bootstrapping successful\" << std::endl;\n break;\n }\n}\n\nint main(int argc, char* argv[])\n{\n if (argc != 4) {\n usage();\n }\n\n const char* server_host = argv[1];\n int server_port = atoi(argv[2]);\n int session_port = atoi(argv[3]);\n int flags = 0;\n\n if (server_port == 0) {\n std::cerr << \"error: server port '\" << server_port << \"' is invalid\" << std::endl;\n exit(-1);\n }\n\n if (session_port == 0) {\n std::cerr << \"error: session port '\" << session_port << \"' is invalid\" << std::endl;\n exit(-1);\n }\n\n libtorrent::fingerprint fp(\"LT\", LIBTORRENT_VERSION_MAJOR, LIBTORRENT_VERSION_MINOR, 0, 0);\n std::shared_ptr<libtorrent::session> session = std::make_shared<libtorrent::session>(\n fp, std::make_pair(session_port, session_port + 8), \"0.0.0.0\", flags,\n libtorrent::alert::port_mapping_notification |\n libtorrent::alert::debug_notification |\n libtorrent::alert::dht_notification |\n libtorrent::alert::error_notification |\n libtorrent::alert::status_notification);\n\n session->set_alert_dispatch(std::bind(&dispatch_libtorrent_alert, session, std::placeholders::_1));\n session->add_dht_router(std::make_pair(server_host, server_port));\n session->start_dht();\n\n \/\/ Just block here and let the session run forever.\n std::mutex forever;\n forever.lock();\n forever.lock();\n\n std::cerr << \"stopping bot\" << std::endl;\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>7e42ad33-2e4f-11e5-abf8-28cfe91dbc4b<commit_msg>7e4aeedc-2e4f-11e5-b12a-28cfe91dbc4b<commit_after>7e4aeedc-2e4f-11e5-b12a-28cfe91dbc4b<|endoftext|>"} {"text":"<commit_before>d656b47d-2e4e-11e5-814d-28cfe91dbc4b<commit_msg>d65e47ca-2e4e-11e5-8925-28cfe91dbc4b<commit_after>d65e47ca-2e4e-11e5-8925-28cfe91dbc4b<|endoftext|>"} {"text":"<commit_before>2c262b3a-2f67-11e5-aa9f-6c40088e03e4<commit_msg>2c2c994a-2f67-11e5-8dec-6c40088e03e4<commit_after>2c2c994a-2f67-11e5-8dec-6c40088e03e4<|endoftext|>"} {"text":"<commit_before>81cf0dd5-2d15-11e5-af21-0401358ea401<commit_msg>81cf0dd6-2d15-11e5-af21-0401358ea401<commit_after>81cf0dd6-2d15-11e5-af21-0401358ea401<|endoftext|>"} {"text":"<commit_before>c7ae0dab-327f-11e5-ab00-9cf387a8033e<commit_msg>c7b4355e-327f-11e5-bd95-9cf387a8033e<commit_after>c7b4355e-327f-11e5-bd95-9cf387a8033e<|endoftext|>"} {"text":"<commit_before>75bea096-2d53-11e5-baeb-247703a38240<commit_msg>75bf1ec2-2d53-11e5-baeb-247703a38240<commit_after>75bf1ec2-2d53-11e5-baeb-247703a38240<|endoftext|>"} {"text":"<commit_before>e0f7de33-2d3c-11e5-996c-c82a142b6f9b<commit_msg>e17ebde6-2d3c-11e5-a6bd-c82a142b6f9b<commit_after>e17ebde6-2d3c-11e5-a6bd-c82a142b6f9b<|endoftext|>"} {"text":"<commit_before>c6ec21b0-35ca-11e5-9dcb-6c40088e03e4<commit_msg>c6f35428-35ca-11e5-acc3-6c40088e03e4<commit_after>c6f35428-35ca-11e5-acc3-6c40088e03e4<|endoftext|>"} {"text":"<commit_before>46f3cb7a-2e4f-11e5-be53-28cfe91dbc4b<commit_msg>46fbda6b-2e4f-11e5-adfb-28cfe91dbc4b<commit_after>46fbda6b-2e4f-11e5-adfb-28cfe91dbc4b<|endoftext|>"} {"text":"<commit_before>d391ceeb-4b02-11e5-9030-28cfe9171a43<commit_msg>#BUG723 uncommitted code found on my computer Monday morning<commit_after>d39d06c0-4b02-11e5-8936-28cfe9171a43<|endoftext|>"} {"text":"<commit_before>5d2865e7-2d16-11e5-af21-0401358ea401<commit_msg>5d2865e8-2d16-11e5-af21-0401358ea401<commit_after>5d2865e8-2d16-11e5-af21-0401358ea401<|endoftext|>"} {"text":"<commit_before>eddb5db5-2e4e-11e5-b117-28cfe91dbc4b<commit_msg>ede16d8c-2e4e-11e5-ab51-28cfe91dbc4b<commit_after>ede16d8c-2e4e-11e5-ab51-28cfe91dbc4b<|endoftext|>"} {"text":"<commit_before>c30a74b5-327f-11e5-9476-9cf387a8033e<commit_msg>c311cb63-327f-11e5-b00d-9cf387a8033e<commit_after>c311cb63-327f-11e5-b00d-9cf387a8033e<|endoftext|>"} {"text":"<commit_before>06c42b9e-2f67-11e5-9711-6c40088e03e4<commit_msg>06caab06-2f67-11e5-88c5-6c40088e03e4<commit_after>06caab06-2f67-11e5-88c5-6c40088e03e4<|endoftext|>"} {"text":"<commit_before>39650224-5216-11e5-b278-6c40088e03e4<commit_msg>396bbf38-5216-11e5-aa5f-6c40088e03e4<commit_after>396bbf38-5216-11e5-aa5f-6c40088e03e4<|endoftext|>"} {"text":"<commit_before>a130cb91-2e4f-11e5-af7f-28cfe91dbc4b<commit_msg>a137c46b-2e4f-11e5-ab0a-28cfe91dbc4b<commit_after>a137c46b-2e4f-11e5-ab0a-28cfe91dbc4b<|endoftext|>"} {"text":"<commit_before>64354434-2fa5-11e5-b6f3-00012e3d3f12<commit_msg>643718f4-2fa5-11e5-9354-00012e3d3f12<commit_after>643718f4-2fa5-11e5-9354-00012e3d3f12<|endoftext|>"} {"text":"<commit_before>#define CATCH_CONFIG_MAIN \/\/ This tells Catch to provide a main() - only do this in one cpp file\n#include \"catch.hpp\"\n\n#include <cmath>\n#include <iomanip>\n#include <iostream>\n#include <sstream>\n#include <string>\n#include <unordered_map>\n#include \"named_type.hpp\"\n\n\/\/ Usage examples\n\ntemplate<typename T>\ndecltype(auto) tee(T&& value)\n{\n std::cout << value << '\\n';\n return std::forward<T>(value);\n}\n\nusing Meter = fluent::NamedType<double, struct MeterParameter, fluent::Addable, fluent::Comparable>;\nMeter operator\"\" _meter(unsigned long long value) { return Meter(value); }\n\/\/Meter operator\"\" _meter(long double value) { return Meter(value); }\n\nusing Width = fluent::NamedType<Meter, struct WidthParameter>;\nusing Height = fluent::NamedType<Meter, struct HeightParameter>;\n\nclass Rectangle\n{\npublic:\n Rectangle(Width width, Height height) : width_(width.get()), height_(height.get()) {}\n Meter getWidth() const { return width_; }\n Meter getHeight() const { return height_; }\n\nprivate:\n Meter width_;\n Meter height_;\n};\n\nTEST_CASE(\"Basic usage\")\n{\n Rectangle r(Width(10_meter), Height(12_meter));\n REQUIRE(r.getWidth().get() == 10);\n REQUIRE(r.getHeight().get() == 12);\n}\n\nusing NameRef = fluent::NamedType<std::string&, struct NameRefParameter>;\n\nvoid changeValue(NameRef name)\n{\n name.get() = \"value2\";\n}\n\nTEST_CASE(\"Passing a strong reference\")\n{\n std::string value = \"value1\";\n changeValue(NameRef(value));\n REQUIRE(value == \"value2\");\n}\n\nTEST_CASE(\"Construction of NamedType::ref from the underlying type\")\n{\n using StrongInt = fluent::NamedType<int, struct StrongIntTag>;\n auto addOne = [](StrongInt::ref si) { ++(si.get()); };\n \n int i = 42;\n addOne(StrongInt::ref(i));\n REQUIRE(i == 43);\n}\n\nTEST_CASE(\"Implicit conversion of NamedType to NamedType::ref\")\n{\n using StrongInt = fluent::NamedType<int, struct StrongIntTag>;\n auto addOne = [](StrongInt::ref si) { ++(si.get()); };\n \n StrongInt i(42);\n addOne(i);\n REQUIRE(i.get() == 43);\n\n StrongInt j(42);\n addOne(StrongInt::ref(j));\n REQUIRE(j.get() == 43);\n}\n\ntemplate<typename Function>\nusing Comparator = fluent::NamedType<Function, struct ComparatorParameter>;\n\ntemplate <typename Function>\nstd::string performAction(Comparator<Function> comp)\n{\n return comp.get()();\n}\n\nTEST_CASE(\"Strong generic type\")\n{\n REQUIRE(performAction(fluent::make_named<Comparator>([](){ return std::string(\"compare\"); })) == \"compare\");\n}\n\nTEST_CASE(\"Addable\")\n{\n using AddableType = fluent::NamedType<int, struct AddableTag, fluent::Addable>;\n AddableType s1(12);\n AddableType s2(10);\n REQUIRE((s1 + s2).get() == 22);\n REQUIRE((+s1).get() == 12);\n}\n\nTEST_CASE(\"BinaryAddable\")\n{\n using BinaryAddableType = fluent::NamedType<int, struct BinaryAddableTag, fluent::BinaryAddable>;\n BinaryAddableType s1(12);\n BinaryAddableType s2(10);\n REQUIRE((s1 + s2).get() == 22);\n}\n\nTEST_CASE(\"UnaryAddable\")\n{\n using UnaryAddableType = fluent::NamedType<int, struct UnaryAddableTag, fluent::UnaryAddable>;\n UnaryAddableType s1(12);\n REQUIRE((+s1).get() == 12);\n}\n\nTEST_CASE(\"Subtractable\")\n{\n using SubtractableType = fluent::NamedType<int, struct SubtractableTag, fluent::Subtractable>;\n SubtractableType s1(12);\n SubtractableType s2(10);\n REQUIRE((s1 - s2).get() == 2);\n REQUIRE((-s1).get() == -12);\n}\n\nTEST_CASE(\"BinarySubtractable\")\n{\n using BinarySubtractableType = fluent::NamedType<int, struct BinarySubtractableTag, fluent::BinarySubtractable>;\n BinarySubtractableType s1(12);\n BinarySubtractableType s2(10);\n REQUIRE((s1 - s2).get() == 2);\n}\n\nTEST_CASE(\"UnarySubtractable\")\n{\n using UnarySubtractableType = fluent::NamedType<int, struct UnarySubtractableTag, fluent::UnarySubtractable>;\n UnarySubtractableType s(12);\n REQUIRE((-s).get() == -12);\n}\n\nTEST_CASE(\"Multiplicable\")\n{\n using MultiplicableType = fluent::NamedType<int, struct MultiplicableTag, fluent::Multiplicable>;\n MultiplicableType s1(12);\n MultiplicableType s2(10);\n REQUIRE((s1 * s2).get() == 120);\n}\n\nTEST_CASE(\"Negatable\")\n{\n using NegatableType = fluent::NamedType<int, struct NegatableTag, fluent::Negatable>;\n NegatableType value(10);\n REQUIRE((-value).get() == -10);\n}\n\nTEST_CASE(\"Comparable\")\n{\n REQUIRE((10_meter == 10_meter));\n REQUIRE(!(10_meter == 11_meter));\n REQUIRE((10_meter != 11_meter));\n REQUIRE(!(10_meter != 10_meter));\n REQUIRE((10_meter < 11_meter));\n REQUIRE(!(10_meter < 10_meter));\n REQUIRE((10_meter <= 10_meter));\n REQUIRE((10_meter <= 11_meter));\n REQUIRE(!(10_meter <= 9_meter));\n REQUIRE((11_meter > 10_meter));\n REQUIRE(!(10_meter > 11_meter));\n REQUIRE((11_meter >= 10_meter));\n REQUIRE((10_meter >= 10_meter));\n REQUIRE(!(9_meter >= 10_meter));\n}\n\nTEST_CASE(\"ConvertibleWithOperator\")\n{\n struct B\n {\n B(int x) : x(x) {}\n int x;\n };\n \n struct A\n {\n A(int x) : x(x) {}\n operator B () const { return B(x);}\n int x;\n };\n \n using StrongA = fluent::NamedType<A, struct StrongATag, fluent::ImplicitlyConvertibleTo<B>::templ>;\n StrongA strongA(A(42));\n B b = strongA;\n REQUIRE(b.x == 42);\n}\n\nTEST_CASE(\"ConvertibleWithConstructor\")\n{\n struct A\n {\n A(int x) : x(x) {}\n int x;\n };\n \n struct B\n {\n B(A a) : x(a.x) {}\n int x;\n };\n \n using StrongA = fluent::NamedType<A, struct StrongATag, fluent::ImplicitlyConvertibleTo<B>::templ>;\n StrongA strongA(A(42));\n B b = strongA;\n REQUIRE(b.x == 42);\n}\n \nTEST_CASE(\"ConvertibleToItself\")\n{\n using MyInt = fluent::NamedType<int, struct MyIntTag, fluent::ImplicitlyConvertibleTo<int>::templ>;\n MyInt myInt(42);\n int i = myInt;\n REQUIRE(i == 42);\n}\n \nTEST_CASE(\"Hash\")\n{\n using SerialNumber = fluent::NamedType<std::string, struct SerialNumberTag, fluent::Comparable, fluent::Hashable>;\n\n std::unordered_map<SerialNumber, int> hashMap = { {SerialNumber{\"AA11\"}, 10}, {SerialNumber{\"BB22\"}, 20} };\n SerialNumber cc33{\"CC33\"};\n hashMap[cc33] = 30;\n REQUIRE(hashMap[SerialNumber{\"AA11\"}] == 10);\n REQUIRE(hashMap[SerialNumber{\"BB22\"}] == 20);\n REQUIRE(hashMap[cc33] == 30);\n}\n\nstruct testFunctionCallable_A\n{\n testFunctionCallable_A(int x) : x(x) {}\n testFunctionCallable_A(testFunctionCallable_A const&) = delete; \/\/ ensures that passing the argument to a function doesn't make a copy\n testFunctionCallable_A(testFunctionCallable_A&&) = default;\n testFunctionCallable_A& operator+=(testFunctionCallable_A const& other) { x += other.x; return *this; }\n int x;\n};\n \ntestFunctionCallable_A operator+(testFunctionCallable_A const& a1, testFunctionCallable_A const& a2)\n{\n return testFunctionCallable_A(a1.x + a2.x);\n}\n \nbool operator==(testFunctionCallable_A const& a1, testFunctionCallable_A const& a2)\n{\n return a1.x == a2.x;\n}\n\nTEST_CASE(\"Function callable\")\n{\n using A = testFunctionCallable_A;\n auto functionTakingA = [](A const& a){ return a.x; };\n \n using StrongA = fluent::NamedType<A, struct StrongATag, fluent::FunctionCallable>;\n StrongA strongA(A(42));\n const StrongA constStrongA(A(42));\n REQUIRE(functionTakingA(strongA) == 42);\n REQUIRE(functionTakingA(constStrongA) == 42);\n REQUIRE(strongA + strongA == 84);\n}\n\nTEST_CASE(\"Method callable\")\n{\n class A\n {\n public:\n A(int x) : x(x) {}\n A(A const&) = delete; \/\/ ensures that invoking a method doesn't make a copy\n A(A&&) = default;\n \n int method(){ return x; }\n int constMethod() const{ return x; }\n private:\n int x;\n };\n \n using StrongA = fluent::NamedType<A, struct StrongATag, fluent::MethodCallable>;\n StrongA strongA(A(42));\n const StrongA constStrongA(A((42)));\n REQUIRE(strongA->method() == 42);\n REQUIRE(constStrongA->constMethod() == 42);\n}\n\nTEST_CASE(\"Callable\")\n{\n class A\n {\n public:\n A(int x) : x(x) {}\n A(A const&) = delete; \/\/ ensures that invoking a method or function doesn't make a copy\n A(A&&) = default;\n \n int method(){ return x; }\n int constMethod() const{ return x; }\n private:\n int x;\n };\n \n auto functionTakingA = [](A const& a){ return a.constMethod(); };\n \n using StrongA = fluent::NamedType<A, struct StrongATag, fluent::Callable>;\n StrongA strongA(A(42));\n const StrongA constStrongA(A((42)));\n REQUIRE(functionTakingA(strongA) == 42);\n REQUIRE(strongA->method() == 42);\n REQUIRE(constStrongA->constMethod() == 42);\n}\n\nTEST_CASE(\"Named arguments\")\n{\n using FirstName = fluent::NamedType<std::string, struct FirstNameTag>;\n using LastName = fluent::NamedType<std::string, struct LastNameTag>;\n static const FirstName::argument firstName;\n static const LastName::argument lastName;\n auto getFullName = [](FirstName const& firstName, LastName const& lastName)\n {\n return firstName.get() + lastName.get();\n };\n \n auto fullName = getFullName(firstName = \"James\", lastName = \"Bond\");\n REQUIRE(fullName == \"JamesBond\");\n}\n\nTEST_CASE(\"Named arguments with bracket constructor\")\n{\n using Numbers = fluent::NamedType<std::vector<int>, struct NumbersTag>;\n static const Numbers::argument numbers;\n auto getNumbers = [](Numbers const& numbers)\n {\n return numbers.get();\n };\n\n auto vec = getNumbers(numbers = {1, 2, 3});\n REQUIRE(vec == std::vector<int>{1, 2, 3});\n}\n\nTEST_CASE(\"Empty base class optimization\")\n{\n REQUIRE(sizeof(Meter) == sizeof(double));\n}\n<commit_msg>Add test for default construction<commit_after>#define CATCH_CONFIG_MAIN \/\/ This tells Catch to provide a main() - only do this in one cpp file\n#include \"catch.hpp\"\n\n#include <cmath>\n#include <iomanip>\n#include <iostream>\n#include <sstream>\n#include <string>\n#include <unordered_map>\n#include \"named_type.hpp\"\n\n\/\/ Usage examples\n\ntemplate<typename T>\ndecltype(auto) tee(T&& value)\n{\n std::cout << value << '\\n';\n return std::forward<T>(value);\n}\n\nusing Meter = fluent::NamedType<double, struct MeterParameter, fluent::Addable, fluent::Comparable>;\nMeter operator\"\" _meter(unsigned long long value) { return Meter(value); }\n\/\/Meter operator\"\" _meter(long double value) { return Meter(value); }\n\nusing Width = fluent::NamedType<Meter, struct WidthParameter>;\nusing Height = fluent::NamedType<Meter, struct HeightParameter>;\n\nclass Rectangle\n{\npublic:\n Rectangle(Width width, Height height) : width_(width.get()), height_(height.get()) {}\n Meter getWidth() const { return width_; }\n Meter getHeight() const { return height_; }\n\nprivate:\n Meter width_;\n Meter height_;\n};\n\nTEST_CASE(\"Basic usage\")\n{\n Rectangle r(Width(10_meter), Height(12_meter));\n REQUIRE(r.getWidth().get() == 10);\n REQUIRE(r.getHeight().get() == 12);\n}\n\nusing NameRef = fluent::NamedType<std::string&, struct NameRefParameter>;\n\nvoid changeValue(NameRef name)\n{\n name.get() = \"value2\";\n}\n\nTEST_CASE(\"Passing a strong reference\")\n{\n std::string value = \"value1\";\n changeValue(NameRef(value));\n REQUIRE(value == \"value2\");\n}\n\nTEST_CASE(\"Construction of NamedType::ref from the underlying type\")\n{\n using StrongInt = fluent::NamedType<int, struct StrongIntTag>;\n auto addOne = [](StrongInt::ref si) { ++(si.get()); };\n \n int i = 42;\n addOne(StrongInt::ref(i));\n REQUIRE(i == 43);\n}\n\nTEST_CASE(\"Implicit conversion of NamedType to NamedType::ref\")\n{\n using StrongInt = fluent::NamedType<int, struct StrongIntTag>;\n auto addOne = [](StrongInt::ref si) { ++(si.get()); };\n \n StrongInt i(42);\n addOne(i);\n REQUIRE(i.get() == 43);\n\n StrongInt j(42);\n addOne(StrongInt::ref(j));\n REQUIRE(j.get() == 43);\n}\n\nTEST_CASE(\"Default construction\")\n{\n using StrongInt = fluent::NamedType<int, struct StrongIntTag>;\n StrongInt strongInt;\n strongInt.get() = 42;\n REQUIRE(strongInt.get() == 42);\n}\n\ntemplate<typename Function>\nusing Comparator = fluent::NamedType<Function, struct ComparatorParameter>;\n\ntemplate <typename Function>\nstd::string performAction(Comparator<Function> comp)\n{\n return comp.get()();\n}\n\nTEST_CASE(\"Strong generic type\")\n{\n REQUIRE(performAction(fluent::make_named<Comparator>([](){ return std::string(\"compare\"); })) == \"compare\");\n}\n\nTEST_CASE(\"Addable\")\n{\n using AddableType = fluent::NamedType<int, struct AddableTag, fluent::Addable>;\n AddableType s1(12);\n AddableType s2(10);\n REQUIRE((s1 + s2).get() == 22);\n REQUIRE((+s1).get() == 12);\n}\n\nTEST_CASE(\"BinaryAddable\")\n{\n using BinaryAddableType = fluent::NamedType<int, struct BinaryAddableTag, fluent::BinaryAddable>;\n BinaryAddableType s1(12);\n BinaryAddableType s2(10);\n REQUIRE((s1 + s2).get() == 22);\n}\n\nTEST_CASE(\"UnaryAddable\")\n{\n using UnaryAddableType = fluent::NamedType<int, struct UnaryAddableTag, fluent::UnaryAddable>;\n UnaryAddableType s1(12);\n REQUIRE((+s1).get() == 12);\n}\n\nTEST_CASE(\"Subtractable\")\n{\n using SubtractableType = fluent::NamedType<int, struct SubtractableTag, fluent::Subtractable>;\n SubtractableType s1(12);\n SubtractableType s2(10);\n REQUIRE((s1 - s2).get() == 2);\n REQUIRE((-s1).get() == -12);\n}\n\nTEST_CASE(\"BinarySubtractable\")\n{\n using BinarySubtractableType = fluent::NamedType<int, struct BinarySubtractableTag, fluent::BinarySubtractable>;\n BinarySubtractableType s1(12);\n BinarySubtractableType s2(10);\n REQUIRE((s1 - s2).get() == 2);\n}\n\nTEST_CASE(\"UnarySubtractable\")\n{\n using UnarySubtractableType = fluent::NamedType<int, struct UnarySubtractableTag, fluent::UnarySubtractable>;\n UnarySubtractableType s(12);\n REQUIRE((-s).get() == -12);\n}\n\nTEST_CASE(\"Multiplicable\")\n{\n using MultiplicableType = fluent::NamedType<int, struct MultiplicableTag, fluent::Multiplicable>;\n MultiplicableType s1(12);\n MultiplicableType s2(10);\n REQUIRE((s1 * s2).get() == 120);\n}\n\nTEST_CASE(\"Negatable\")\n{\n using NegatableType = fluent::NamedType<int, struct NegatableTag, fluent::Negatable>;\n NegatableType value(10);\n REQUIRE((-value).get() == -10);\n}\n\nTEST_CASE(\"Comparable\")\n{\n REQUIRE((10_meter == 10_meter));\n REQUIRE(!(10_meter == 11_meter));\n REQUIRE((10_meter != 11_meter));\n REQUIRE(!(10_meter != 10_meter));\n REQUIRE((10_meter < 11_meter));\n REQUIRE(!(10_meter < 10_meter));\n REQUIRE((10_meter <= 10_meter));\n REQUIRE((10_meter <= 11_meter));\n REQUIRE(!(10_meter <= 9_meter));\n REQUIRE((11_meter > 10_meter));\n REQUIRE(!(10_meter > 11_meter));\n REQUIRE((11_meter >= 10_meter));\n REQUIRE((10_meter >= 10_meter));\n REQUIRE(!(9_meter >= 10_meter));\n}\n\nTEST_CASE(\"ConvertibleWithOperator\")\n{\n struct B\n {\n B(int x) : x(x) {}\n int x;\n };\n \n struct A\n {\n A(int x) : x(x) {}\n operator B () const { return B(x);}\n int x;\n };\n \n using StrongA = fluent::NamedType<A, struct StrongATag, fluent::ImplicitlyConvertibleTo<B>::templ>;\n StrongA strongA(A(42));\n B b = strongA;\n REQUIRE(b.x == 42);\n}\n\nTEST_CASE(\"ConvertibleWithConstructor\")\n{\n struct A\n {\n A(int x) : x(x) {}\n int x;\n };\n \n struct B\n {\n B(A a) : x(a.x) {}\n int x;\n };\n \n using StrongA = fluent::NamedType<A, struct StrongATag, fluent::ImplicitlyConvertibleTo<B>::templ>;\n StrongA strongA(A(42));\n B b = strongA;\n REQUIRE(b.x == 42);\n}\n \nTEST_CASE(\"ConvertibleToItself\")\n{\n using MyInt = fluent::NamedType<int, struct MyIntTag, fluent::ImplicitlyConvertibleTo<int>::templ>;\n MyInt myInt(42);\n int i = myInt;\n REQUIRE(i == 42);\n}\n \nTEST_CASE(\"Hash\")\n{\n using SerialNumber = fluent::NamedType<std::string, struct SerialNumberTag, fluent::Comparable, fluent::Hashable>;\n\n std::unordered_map<SerialNumber, int> hashMap = { {SerialNumber{\"AA11\"}, 10}, {SerialNumber{\"BB22\"}, 20} };\n SerialNumber cc33{\"CC33\"};\n hashMap[cc33] = 30;\n REQUIRE(hashMap[SerialNumber{\"AA11\"}] == 10);\n REQUIRE(hashMap[SerialNumber{\"BB22\"}] == 20);\n REQUIRE(hashMap[cc33] == 30);\n}\n\nstruct testFunctionCallable_A\n{\n testFunctionCallable_A(int x) : x(x) {}\n testFunctionCallable_A(testFunctionCallable_A const&) = delete; \/\/ ensures that passing the argument to a function doesn't make a copy\n testFunctionCallable_A(testFunctionCallable_A&&) = default;\n testFunctionCallable_A& operator+=(testFunctionCallable_A const& other) { x += other.x; return *this; }\n int x;\n};\n \ntestFunctionCallable_A operator+(testFunctionCallable_A const& a1, testFunctionCallable_A const& a2)\n{\n return testFunctionCallable_A(a1.x + a2.x);\n}\n \nbool operator==(testFunctionCallable_A const& a1, testFunctionCallable_A const& a2)\n{\n return a1.x == a2.x;\n}\n\nTEST_CASE(\"Function callable\")\n{\n using A = testFunctionCallable_A;\n auto functionTakingA = [](A const& a){ return a.x; };\n \n using StrongA = fluent::NamedType<A, struct StrongATag, fluent::FunctionCallable>;\n StrongA strongA(A(42));\n const StrongA constStrongA(A(42));\n REQUIRE(functionTakingA(strongA) == 42);\n REQUIRE(functionTakingA(constStrongA) == 42);\n REQUIRE(strongA + strongA == 84);\n}\n\nTEST_CASE(\"Method callable\")\n{\n class A\n {\n public:\n A(int x) : x(x) {}\n A(A const&) = delete; \/\/ ensures that invoking a method doesn't make a copy\n A(A&&) = default;\n \n int method(){ return x; }\n int constMethod() const{ return x; }\n private:\n int x;\n };\n \n using StrongA = fluent::NamedType<A, struct StrongATag, fluent::MethodCallable>;\n StrongA strongA(A(42));\n const StrongA constStrongA(A((42)));\n REQUIRE(strongA->method() == 42);\n REQUIRE(constStrongA->constMethod() == 42);\n}\n\nTEST_CASE(\"Callable\")\n{\n class A\n {\n public:\n A(int x) : x(x) {}\n A(A const&) = delete; \/\/ ensures that invoking a method or function doesn't make a copy\n A(A&&) = default;\n \n int method(){ return x; }\n int constMethod() const{ return x; }\n private:\n int x;\n };\n \n auto functionTakingA = [](A const& a){ return a.constMethod(); };\n \n using StrongA = fluent::NamedType<A, struct StrongATag, fluent::Callable>;\n StrongA strongA(A(42));\n const StrongA constStrongA(A((42)));\n REQUIRE(functionTakingA(strongA) == 42);\n REQUIRE(strongA->method() == 42);\n REQUIRE(constStrongA->constMethod() == 42);\n}\n\nTEST_CASE(\"Named arguments\")\n{\n using FirstName = fluent::NamedType<std::string, struct FirstNameTag>;\n using LastName = fluent::NamedType<std::string, struct LastNameTag>;\n static const FirstName::argument firstName;\n static const LastName::argument lastName;\n auto getFullName = [](FirstName const& firstName, LastName const& lastName)\n {\n return firstName.get() + lastName.get();\n };\n \n auto fullName = getFullName(firstName = \"James\", lastName = \"Bond\");\n REQUIRE(fullName == \"JamesBond\");\n}\n\nTEST_CASE(\"Named arguments with bracket constructor\")\n{\n using Numbers = fluent::NamedType<std::vector<int>, struct NumbersTag>;\n static const Numbers::argument numbers;\n auto getNumbers = [](Numbers const& numbers)\n {\n return numbers.get();\n };\n\n auto vec = getNumbers(numbers = {1, 2, 3});\n REQUIRE(vec == std::vector<int>{1, 2, 3});\n}\n\nTEST_CASE(\"Empty base class optimization\")\n{\n REQUIRE(sizeof(Meter) == sizeof(double));\n}\n<|endoftext|>"} {"text":"<commit_before>6b131434-2fa5-11e5-8319-00012e3d3f12<commit_msg>6b14e8f4-2fa5-11e5-b863-00012e3d3f12<commit_after>6b14e8f4-2fa5-11e5-b863-00012e3d3f12<|endoftext|>"} {"text":"<commit_before>0d921d58-585b-11e5-b48e-6c40088e03e4<commit_msg>0d993f22-585b-11e5-afc0-6c40088e03e4<commit_after>0d993f22-585b-11e5-afc0-6c40088e03e4<|endoftext|>"} {"text":"<commit_before>6082880a-2d3f-11e5-aff5-c82a142b6f9b<commit_msg>60eba273-2d3f-11e5-b4f4-c82a142b6f9b<commit_after>60eba273-2d3f-11e5-b4f4-c82a142b6f9b<|endoftext|>"} {"text":"<commit_before>93194a1a-35ca-11e5-986e-6c40088e03e4<commit_msg>931f8f7a-35ca-11e5-9257-6c40088e03e4<commit_after>931f8f7a-35ca-11e5-9257-6c40088e03e4<|endoftext|>"} {"text":"<commit_before>43d0cd75-2d3e-11e5-8c9f-c82a142b6f9b<commit_msg>44f1a494-2d3e-11e5-aa8e-c82a142b6f9b<commit_after>44f1a494-2d3e-11e5-aa8e-c82a142b6f9b<|endoftext|>"} {"text":"<commit_before>86936f72-2d15-11e5-af21-0401358ea401<commit_msg>86936f73-2d15-11e5-af21-0401358ea401<commit_after>86936f73-2d15-11e5-af21-0401358ea401<|endoftext|>"} {"text":"<commit_before>ae23b4e8-2d3e-11e5-af69-c82a142b6f9b<commit_msg>aea93db8-2d3e-11e5-a96b-c82a142b6f9b<commit_after>aea93db8-2d3e-11e5-a96b-c82a142b6f9b<|endoftext|>"} {"text":"<commit_before>e697d073-327f-11e5-8b0d-9cf387a8033e<commit_msg>e69e0fb5-327f-11e5-9bb2-9cf387a8033e<commit_after>e69e0fb5-327f-11e5-9bb2-9cf387a8033e<|endoftext|>"} {"text":"<commit_before>5bf67381-2d16-11e5-af21-0401358ea401<commit_msg>5bf67382-2d16-11e5-af21-0401358ea401<commit_after>5bf67382-2d16-11e5-af21-0401358ea401<|endoftext|>"} {"text":"<commit_before>0bbec090-2f67-11e5-a2a3-6c40088e03e4<commit_msg>0bc577a8-2f67-11e5-828a-6c40088e03e4<commit_after>0bc577a8-2f67-11e5-828a-6c40088e03e4<|endoftext|>"} {"text":"<commit_before>769a7eae-2d53-11e5-baeb-247703a38240<commit_msg>769afec4-2d53-11e5-baeb-247703a38240<commit_after>769afec4-2d53-11e5-baeb-247703a38240<|endoftext|>"} {"text":"<commit_before>31267930-2e3a-11e5-8f81-c03896053bdd<commit_msg>3134fad2-2e3a-11e5-9265-c03896053bdd<commit_after>3134fad2-2e3a-11e5-9265-c03896053bdd<|endoftext|>"} {"text":"<commit_before>\/* **** **** **** **** **** **** **** **** *\n *\n * _\/ _\/ _\/\n * _\/_\/_\/ _\/_\/_\/ _\/_\/_\/\n * _\/ _\/ _\/ _\/ _\/ _\/\n * _\/ _\/ _\/ _\/ _\/ _\/\n * _\/_\/_\/ _\/_\/_\/ _\/_\/_\/\n *\n * bit by bit\n * main.cpp\n *\n * author: ISHII 2bit\n * mail: 2bit@backspace.tokyo\n *\n * **** **** **** **** **** **** **** **** *\/\n\n#include \"bit_by_bit.hpp\"\n\nvoid reusable_array_test();\nvoid byte_array_test();\nvoid multithread_test(size_t num);\nvoid range_test();\n\nint main(int argc, char *argv[]) {\n reusable_array_test();\n byte_array_test();\n multithread_test(4);\n range_test();\n}\n\n#pragma mark reusable_array_test\n\n#include <cassert>\n#include <iostream>\n\nstruct particle {\n int life_time;\n int age;\n int name;\n\n particle() {}\n particle(int life_time, int name)\n : life_time(life_time)\n , name(name)\n , age(0) {}\n\n void init(int life_time, int name) {\n this->life_time = life_time;\n this->name = name;\n this->age = 0;\n }\n\n bool update() {\n return ++age < life_time;\n }\n\n void print() const {\n std::cout << name << \", \" << (life_time - age) << std::endl;\n }\n};\n\nconstexpr int loop_num(1);\nconstexpr int elem_num(10);\n\nvoid reusable_array_test() {\n bbb::random::set_seed_mt(0);\n auto a = bbb::random::mt();\n bbb::random::set_seed_mt(0);\n auto b = bbb::random::mt();\n bbb::random::set_seed_mt(1);\n auto c = bbb::random::mt();\n assert(a == b);\n assert(a != c);\n\n bbb::stop_watch watch;\n watch.start();\n\n {\n bbb::random::set_seed_mt(0);\n bbb::reusable_array<particle, elem_num> f;\n watch.rap();\n\n for(int k = 0; k++ < loop_num;) {\n do f.init(bbb::random::mt() % 100, f.current_size()); while(f.has_space());\n while(f.current_size()) {\n f.update();\n }\n }\n\n watch.rap();\n std::cout << \"time: \" << watch.getLastRapNanoseconds() << std::endl;\n }\n\n {\n bbb::random::set_seed_mt(0);\n bbb::shared_vector<particle> f;\n watch.rap();\n\n for(int k = 0; k++ < loop_num;) {\n for(; f.size() < elem_num; f.push_back(std::shared_ptr<particle>(new particle(rand() % 100, f.size()))));\n auto wrapper = bbb::make_reverse(f);\n while(f.size()) for(auto e : wrapper) if(!e->update()) {\n e = f.back();\n f.pop_back();\n }\n }\n\n watch.rap();\n std::cout << \"time: \" << watch.getLastRapNanoseconds() << std::endl;\n }\n}\n\nvoid byte_array_test() {\n bbb::byte_array<int> barr{0x7FFFFFFF};\n for(auto i = 0; i < barr.size(); i++) {\n std::cout << (int)barr[i] << std::endl;\n }\n};\n\nvoid multithread_test(size_t num) {\n size_t sum = 0;\n bool is_run = true;\n bbb::stop_watch watch;\n watch.start();\n bbb::multithread::manager manager(num, [&sum, &is_run](size_t index, std::mutex &mutex) {\n while(is_run) {\n if(mutex.try_lock()) {\n sum++;\n mutex.unlock();\n }\n bbb::sleep_nanoseconds(50);\n }\n });\n\n while(is_run) {\n bbb::sleep_milliseconds(10);\n auto lock(manager.lock_guard());\n if(100000 < sum) {\n is_run = false;\n manager.join();\n }\n }\n watch.rap();\n std::cout << \"time: \" << watch.getLastRapMilliseconds() << std::endl;\n}\n\nvoid range_test() {\n {\n std::vector<int> vec;\n for(auto i : bbb::range(2, 10)) {\n vec.push_back(i);\n }\n\n for(auto v : bbb::enumerate(vec)) {\n std::cout << v.index << \", \" << v.value << std::endl;\n v.value *= 2;\n }\n for(auto v : bbb::enumerate(vec)) {\n std::cout << v.index << \", \" << v.value << std::endl;\n }\n }\n\n {\n const std::vector<int> cvec{1, 2, 3};\n for(auto v : bbb::enumerate(cvec)) {\n std::cout << v.index << \", \" << v.value << std::endl;\n }\n }\n std::cout << std::endl;\n\n std::vector<std::string> svec{\"a\", \"hoge\", \"foo\"};\n for(auto v : bbb::enumerate(svec)) {\n std::cout << v.index << \", \" << v.value << std::endl;\n }\n}<commit_msg>update test<commit_after>\/* **** **** **** **** **** **** **** **** *\n *\n * _\/ _\/ _\/\n * _\/_\/_\/ _\/_\/_\/ _\/_\/_\/\n * _\/ _\/ _\/ _\/ _\/ _\/\n * _\/ _\/ _\/ _\/ _\/ _\/\n * _\/_\/_\/ _\/_\/_\/ _\/_\/_\/\n *\n * bit by bit\n * main.cpp\n *\n * author: ISHII 2bit\n * mail: 2bit@backspace.tokyo\n *\n * **** **** **** **** **** **** **** **** *\/\n\n#include \"bit_by_bit.hpp\"\n\nvoid reusable_array_test();\nvoid byte_array_test();\nvoid multithread_test(size_t num);\nvoid range_test();\n\nint main(int argc, char *argv[]) {\n reusable_array_test();\n byte_array_test();\n multithread_test(4);\n range_test();\n}\n\n#pragma mark reusable_array_test\n\n#include <cassert>\n#include <iostream>\n\nstruct particle {\n int life_time;\n int age;\n int name;\n\n particle() {}\n particle(int life_time, int name)\n : life_time(life_time)\n , name(name)\n , age(0) {}\n\n void init(int life_time, int name) {\n this->life_time = life_time;\n this->name = name;\n this->age = 0;\n }\n\n bool update() {\n return ++age < life_time;\n }\n\n void print() const {\n std::cout << name << \", \" << (life_time - age) << std::endl;\n }\n};\n\nconstexpr int loop_num(1);\nconstexpr int elem_num(10);\n\nvoid reusable_array_test() {\n bbb::random::set_seed_mt(0);\n auto a = bbb::random::mt();\n bbb::random::set_seed_mt(0);\n auto b = bbb::random::mt();\n bbb::random::set_seed_mt(1);\n auto c = bbb::random::mt();\n assert(a == b);\n assert(a != c);\n\n bbb::stop_watch watch;\n watch.start();\n\n {\n bbb::random::set_seed_mt(0);\n bbb::reusable_array<particle, elem_num> f;\n watch.rap();\n\n for(int k = 0; k++ < loop_num;) {\n do f.init(bbb::random::mt() % 100, f.current_size()); while(f.has_space());\n while(f.current_size()) {\n f.update();\n }\n }\n\n watch.rap();\n std::cout << \"time: \" << watch.getLastRapNanoseconds() << std::endl;\n }\n\n {\n bbb::random::set_seed_mt(0);\n bbb::shared_vector<particle> f;\n watch.rap();\n\n for(int k = 0; k++ < loop_num;) {\n for(; f.size() < elem_num; f.push_back(std::shared_ptr<particle>(new particle(rand() % 100, f.size()))));\n auto wrapper = bbb::make_reverse(f);\n while(f.size()) for(auto e : wrapper) if(!e->update()) {\n e = f.back();\n f.pop_back();\n }\n }\n\n watch.rap();\n std::cout << \"time: \" << watch.getLastRapNanoseconds() << std::endl;\n }\n}\n\nvoid byte_array_test() {\n bbb::byte_array<int> barr{0x7FFFFFFF};\n for(auto i = 0; i < barr.size(); i++) {\n std::cout << (int)barr[i] << std::endl;\n }\n};\n\nvoid multithread_test(size_t num) {\n size_t sum = 0;\n bool is_run = true;\n bbb::stop_watch watch;\n watch.start();\n bbb::multithread::manager manager(num, [&sum, &is_run](size_t index, std::mutex &mutex) {\n while(is_run) {\n if(mutex.try_lock()) {\n sum++;\n mutex.unlock();\n }\n bbb::sleep_nanoseconds(50);\n }\n });\n\n while(is_run) {\n bbb::sleep_milliseconds(10);\n auto lock(manager.lock_guard());\n if(100000 < sum) {\n is_run = false;\n manager.join();\n }\n }\n watch.rap();\n std::cout << \"time: \" << watch.getLastRapMilliseconds() << std::endl;\n}\n\nvoid range_test() {\n {\n std::vector<int> vec;\n for(auto i : bbb::range(2, 10)) {\n vec.push_back(i);\n }\n\n for(auto v : bbb::enumerate(vec)) {\n std::cout << v.index << \", \" << v.value << std::endl;\n v.value *= 2;\n }\n for(auto v : bbb::enumerate(vec)) {\n std::cout << v.index << \", \" << v.value << std::endl;\n }\n }\n\n {\n const std::vector<int> cvec{1, 2, 3};\n for(auto v : bbb::enumerate(cvec)) {\n std::cout << v.index << \", \" << v.value << std::endl;\n }\n }\n std::cout << std::endl;\n\n std::vector<std::string> svec{\"a\", \"hoge\", \"foo\"};\n for(auto &v : bbb::enumerate(svec)) {\n std::cout << v.index << \", \" << v.value << std::endl;\n }\n for(const auto &v : bbb::enumerate(svec)) {\n std::cout << v.index << \", \" << v.value << std::endl;\n }\n}<|endoftext|>"} {"text":"<commit_before>71aa20f6-5216-11e5-8e06-6c40088e03e4<commit_msg>71b10068-5216-11e5-9f69-6c40088e03e4<commit_after>71b10068-5216-11e5-9f69-6c40088e03e4<|endoftext|>"} {"text":"<commit_before>ee1f8482-327f-11e5-906f-9cf387a8033e<commit_msg>ee258028-327f-11e5-88be-9cf387a8033e<commit_after>ee258028-327f-11e5-88be-9cf387a8033e<|endoftext|>"} {"text":"<commit_before>07799e48-585b-11e5-8c78-6c40088e03e4<commit_msg>07833a46-585b-11e5-8d34-6c40088e03e4<commit_after>07833a46-585b-11e5-8d34-6c40088e03e4<|endoftext|>"} {"text":"<commit_before>71efb6a6-2e4f-11e5-9b2d-28cfe91dbc4b<commit_msg>71f6692e-2e4f-11e5-8261-28cfe91dbc4b<commit_after>71f6692e-2e4f-11e5-8261-28cfe91dbc4b<|endoftext|>"} {"text":"<commit_before>eaceb119-313a-11e5-97a6-3c15c2e10482<commit_msg>ead4ca1e-313a-11e5-b9c5-3c15c2e10482<commit_after>ead4ca1e-313a-11e5-b9c5-3c15c2e10482<|endoftext|>"} {"text":"<commit_before>bcc55685-ad5a-11e7-97f1-ac87a332f658<commit_msg>My Life for Auir<commit_after>bd8904a1-ad5a-11e7-beb0-ac87a332f658<|endoftext|>"} {"text":"<commit_before>dab41f76-585a-11e5-bcd3-6c40088e03e4<commit_msg>dabaab64-585a-11e5-9d1b-6c40088e03e4<commit_after>dabaab64-585a-11e5-9d1b-6c40088e03e4<|endoftext|>"} {"text":"<commit_before>cf0cf7ca-327f-11e5-a1c5-9cf387a8033e<commit_msg>cf12ba35-327f-11e5-af01-9cf387a8033e<commit_after>cf12ba35-327f-11e5-af01-9cf387a8033e<|endoftext|>"} {"text":"<commit_before>83000e31-2d15-11e5-af21-0401358ea401<commit_msg>83000e32-2d15-11e5-af21-0401358ea401<commit_after>83000e32-2d15-11e5-af21-0401358ea401<|endoftext|>"} {"text":"<commit_before>07fdcb7a-2f67-11e5-b87d-6c40088e03e4<commit_msg>080680f8-2f67-11e5-8d0c-6c40088e03e4<commit_after>080680f8-2f67-11e5-8d0c-6c40088e03e4<|endoftext|>"} {"text":"<commit_before>8c3d20ec-2d14-11e5-af21-0401358ea401<commit_msg>8c3d20ed-2d14-11e5-af21-0401358ea401<commit_after>8c3d20ed-2d14-11e5-af21-0401358ea401<|endoftext|>"} {"text":"<commit_before>7ad5c526-2e4f-11e5-a32f-28cfe91dbc4b<commit_msg>7adc146b-2e4f-11e5-a454-28cfe91dbc4b<commit_after>7adc146b-2e4f-11e5-a454-28cfe91dbc4b<|endoftext|>"} {"text":"<commit_before>8e9fac0d-2d14-11e5-af21-0401358ea401<commit_msg>8e9fac0e-2d14-11e5-af21-0401358ea401<commit_after>8e9fac0e-2d14-11e5-af21-0401358ea401<|endoftext|>"} {"text":"<commit_before>dbfe60d4-313a-11e5-97cb-3c15c2e10482<commit_msg>dc0486dc-313a-11e5-b77f-3c15c2e10482<commit_after>dc0486dc-313a-11e5-b77f-3c15c2e10482<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ This file is part of the Marble Virtual Globe.\n\/\/\n\/\/ This program is free software licensed under the GNU LGPL. You can\n\/\/ find a copy of this license in LICENSE.txt in the top directory of\n\/\/ the source code.\n\/\/\n\/\/ Copyright 2008-2009 Patrick Spendrin <ps_ml@gmx.de>\n\/\/ Copyright 2010 Thibaut Gridel <tgridel@free.fr>\n\/\/\n\n#include \"GeometryLayer.h\"\n\n\/\/ Marble\n#include \"GeoDataDocument.h\"\n#include \"GeoDataFolder.h\"\n#include \"GeoDataLineStyle.h\"\n#include \"GeoDataObject.h\"\n#include \"GeoDataPlacemark.h\"\n#include \"GeoDataPolygon.h\"\n#include \"GeoDataPolyStyle.h\"\n#include \"GeoDataStyle.h\"\n#include \"GeoDataStyleMap.h\"\n#include \"MarbleDebug.h\"\n#include \"GeoDataTypes.h\"\n#include \"GeoDataFeature.h\"\n#include \"GeoPainter.h\"\n#include \"ViewportParams.h\"\n#include \"GeoGraphicsScene.h\"\n#include \"GeoGraphicsItem.h\"\n#include \"GeoLineStringGraphicsItem.h\"\n#include \"GeoPolygonGraphicsItem.h\"\n\n\/\/ Qt\n#include <QtCore\/QTime>\n#include <QtCore\/QAbstractItemModel>\n\nnamespace Marble\n{\nint GeometryLayer::s_defaultZValues[GeoDataFeature::LastIndex];\nint GeometryLayer::s_defaultLODValues[GeoDataFeature::LastIndex];\nbool GeometryLayer::s_defaultValuesInitialized = false;\nint GeometryLayer::s_defaultZValue = 50;\n\nclass GeometryLayerPrivate\n{\npublic:\n void createGraphicsItems( GeoDataObject *object );\n void createGraphicsItemFromGeometry( GeoDataGeometry *object, GeoDataPlacemark *placemark );\n\n QBrush m_currentBrush;\n QPen m_currentPen;\n GeoGraphicsScene m_scene;\n QAbstractItemModel *m_model;\n};\n\nGeometryLayer::GeometryLayer( QAbstractItemModel *model )\n : d( new GeometryLayerPrivate() )\n{\n if ( !s_defaultValuesInitialized )\n initializeDefaultValues();\n\n d->m_model = model;\n GeoDataObject *object = static_cast<GeoDataObject*>( d->m_model->index( 0, 0, QModelIndex() ).internalPointer() );\n if ( object && object->parent() )\n d->createGraphicsItems( object->parent() );\n}\n\nGeometryLayer::~GeometryLayer()\n{\n delete d;\n}\n\nQStringList GeometryLayer::renderPosition() const\n{\n return QStringList( \"HOVERS_ABOVE_SURFACE\" );\n}\n\nvoid GeometryLayer::initializeDefaultValues()\n{\n for ( int i = 0; i < GeoDataFeature::LastIndex; i++ )\n s_defaultZValues[i] = s_defaultZValue;\n \n for ( int i = 0; i < GeoDataFeature::LastIndex; i++ )\n s_defaultLODValues[i] = -1;\n\n s_defaultZValues[GeoDataFeature::None] = 0;\n s_defaultZValues[GeoDataFeature::NaturalWater] = s_defaultZValue - 15;\n s_defaultZValues[GeoDataFeature::NaturalWood] = s_defaultZValue - 14;\n \n s_defaultZValues[GeoDataFeature::TransportParking] = s_defaultZValue - 13;\n \n s_defaultZValues[GeoDataFeature::HighwayTertiaryLink] = s_defaultZValue - 12;\n s_defaultZValues[GeoDataFeature::HighwaySecondaryLink]= s_defaultZValue - 12;\n s_defaultZValues[GeoDataFeature::HighwayPrimaryLink] = s_defaultZValue - 12;\n s_defaultZValues[GeoDataFeature::HighwayTrunkLink] = s_defaultZValue - 12;\n s_defaultZValues[GeoDataFeature::HighwayMotorwayLink] = s_defaultZValue - 12;\n\n s_defaultZValues[GeoDataFeature::HighwayUnknown] = s_defaultZValue - 11;\n s_defaultZValues[GeoDataFeature::HighwayPath] = s_defaultZValue - 10;\n s_defaultZValues[GeoDataFeature::HighwayTrack] = s_defaultZValue - 9;\n s_defaultZValues[GeoDataFeature::HighwayPedestrian] = s_defaultZValue - 8;\n s_defaultZValues[GeoDataFeature::HighwayService] = s_defaultZValue - 7;\n s_defaultZValues[GeoDataFeature::HighwayRoad] = s_defaultZValue - 6;\n s_defaultZValues[GeoDataFeature::HighwayTertiary] = s_defaultZValue - 5;\n s_defaultZValues[GeoDataFeature::HighwaySecondary] = s_defaultZValue - 4;\n s_defaultZValues[GeoDataFeature::HighwayPrimary] = s_defaultZValue - 3;\n s_defaultZValues[GeoDataFeature::HighwayTrunk] = s_defaultZValue - 2;\n s_defaultZValues[GeoDataFeature::HighwayMotorway] = s_defaultZValue - 1;\n\n s_defaultValuesInitialized = true;\n}\n\n\nbool GeometryLayer::render( GeoPainter *painter, ViewportParams *viewport,\n const QString& renderPos, GeoSceneLayer * layer )\n{\n\/\/ QTime t;\n\/\/ t.start();\n\/\/ mDebug() << \"rendering \" << m_root;\n \/*if ( d->m_root )\n {\n d->renderGeoDataObject( painter, d->m_root, viewport );\n }*\/\n\/\/ mDebug() << \"rendering geometry: \" << t.elapsed();\n QList<GeoGraphicsItem*> items = d->m_scene.items( viewport->viewLatLonAltBox() );\n foreach( GeoGraphicsItem* item, items )\n {\n if ( item->visible() )\n item->paint( painter, viewport, renderPos, layer );\n }\n return true;\n}\n\nvoid GeometryLayerPrivate::createGraphicsItems( GeoDataObject *object )\n{\n GeoDataFeature *feature = dynamic_cast<GeoDataFeature*>( object );\n\n if ( dynamic_cast<GeoDataPlacemark*>( object ) )\n {\n GeoDataPlacemark *placemark = static_cast<GeoDataPlacemark*>( object );\n createGraphicsItemFromGeometry( placemark->geometry(), placemark );\n }\n\n \/\/ parse all child objects of the container\n GeoDataContainer *container = dynamic_cast<GeoDataContainer*>( object );\n if ( container )\n {\n int rowCount = container->size();\n for ( int row = 0; row < rowCount; ++row )\n {\n createGraphicsItems( container->child( row ) );\n }\n }\n}\n\nvoid GeometryLayerPrivate::createGraphicsItemFromGeometry( GeoDataGeometry* object, GeoDataPlacemark *placemark )\n{\n GeoGraphicsItem *item = 0;\n if ( dynamic_cast<GeoDataLinearRing*>( object ) )\n {\n }\n else if ( GeoDataLineString* line = dynamic_cast<GeoDataLineString*>( object ) )\n {\n item = new GeoLineStringGraphicsItem();\n static_cast<GeoLineStringGraphicsItem*>( item )->setLineString( *line );\n }\n else if ( GeoDataPolygon *poly = dynamic_cast<GeoDataPolygon*>( object ) )\n {\n item = new GeoPolygonGraphicsItem();\n static_cast<GeoPolygonGraphicsItem*>( item )->setPolygon( *poly );\n }\n else if ( dynamic_cast<GeoDataMultiGeometry*>( object ) )\n {\n GeoDataMultiGeometry *multigeo = dynamic_cast<GeoDataMultiGeometry*>( object );\n int rowCount = multigeo->size();\n for ( int row = 0; row < rowCount; ++row )\n {\n createGraphicsItemFromGeometry( multigeo->child( row ), placemark );\n }\n }\n if ( !item )\n return;\n item->setStyle( placemark->style() );\n item->setVisible( placemark->isVisible() );\n item->setZValue( GeometryLayer::s_defaultZValues[placemark->visualCategory()] );\n item->setMinLodPixels( GeometryLayer::s_defaultLODValues[placemark->visualCategory()] );\n m_scene.addIdem( item );\n}\n\nvoid GeometryLayer::invalidateScene()\n{\n QList<GeoGraphicsItem*> items = d->m_scene.items();\n foreach( GeoGraphicsItem* item, items )\n {\n delete item;\n }\n d->m_scene.clear();\n GeoDataObject *object = static_cast<GeoDataObject*>( d->m_model->index( 0, 0, QModelIndex() ).internalPointer() );\n if ( object && object->parent() )\n d->createGraphicsItems( object->parent() );\n}\n\n}\n\n#include \"GeometryLayer.moc\"\n<commit_msg>Map Quality in GeometryLayer.<commit_after>\/\/\n\/\/ This file is part of the Marble Virtual Globe.\n\/\/\n\/\/ This program is free software licensed under the GNU LGPL. You can\n\/\/ find a copy of this license in LICENSE.txt in the top directory of\n\/\/ the source code.\n\/\/\n\/\/ Copyright 2008-2009 Patrick Spendrin <ps_ml@gmx.de>\n\/\/ Copyright 2010 Thibaut Gridel <tgridel@free.fr>\n\/\/\n\n#include \"GeometryLayer.h\"\n\n\/\/ Marble\n#include \"GeoDataDocument.h\"\n#include \"GeoDataFolder.h\"\n#include \"GeoDataLineStyle.h\"\n#include \"GeoDataObject.h\"\n#include \"GeoDataPlacemark.h\"\n#include \"GeoDataPolygon.h\"\n#include \"GeoDataPolyStyle.h\"\n#include \"GeoDataStyle.h\"\n#include \"GeoDataStyleMap.h\"\n#include \"MarbleDebug.h\"\n#include \"GeoDataTypes.h\"\n#include \"GeoDataFeature.h\"\n#include \"GeoPainter.h\"\n#include \"ViewportParams.h\"\n#include \"GeoGraphicsScene.h\"\n#include \"GeoGraphicsItem.h\"\n#include \"GeoLineStringGraphicsItem.h\"\n#include \"GeoPolygonGraphicsItem.h\"\n\n\/\/ Qt\n#include <QtCore\/QTime>\n#include <QtCore\/QAbstractItemModel>\n\nnamespace Marble\n{\nint GeometryLayer::s_defaultZValues[GeoDataFeature::LastIndex];\nint GeometryLayer::s_defaultLODValues[GeoDataFeature::LastIndex];\nbool GeometryLayer::s_defaultValuesInitialized = false;\nint GeometryLayer::s_defaultZValue = 50;\n\nclass GeometryLayerPrivate\n{\npublic:\n void createGraphicsItems( GeoDataObject *object );\n void createGraphicsItemFromGeometry( GeoDataGeometry *object, GeoDataPlacemark *placemark );\n\n QBrush m_currentBrush;\n QPen m_currentPen;\n GeoGraphicsScene m_scene;\n QAbstractItemModel *m_model;\n};\n\nGeometryLayer::GeometryLayer( QAbstractItemModel *model )\n : d( new GeometryLayerPrivate() )\n{\n if ( !s_defaultValuesInitialized )\n initializeDefaultValues();\n\n d->m_model = model;\n GeoDataObject *object = static_cast<GeoDataObject*>( d->m_model->index( 0, 0, QModelIndex() ).internalPointer() );\n if ( object && object->parent() )\n d->createGraphicsItems( object->parent() );\n}\n\nGeometryLayer::~GeometryLayer()\n{\n delete d;\n}\n\nQStringList GeometryLayer::renderPosition() const\n{\n return QStringList( \"HOVERS_ABOVE_SURFACE\" );\n}\n\nvoid GeometryLayer::initializeDefaultValues()\n{\n for ( int i = 0; i < GeoDataFeature::LastIndex; i++ )\n s_defaultZValues[i] = s_defaultZValue;\n \n for ( int i = 0; i < GeoDataFeature::LastIndex; i++ )\n s_defaultLODValues[i] = -1;\n\n s_defaultZValues[GeoDataFeature::None] = 0;\n s_defaultZValues[GeoDataFeature::NaturalWater] = s_defaultZValue - 15;\n s_defaultZValues[GeoDataFeature::NaturalWood] = s_defaultZValue - 14;\n \n s_defaultZValues[GeoDataFeature::TransportParking] = s_defaultZValue - 13;\n \n s_defaultZValues[GeoDataFeature::HighwayTertiaryLink] = s_defaultZValue - 12;\n s_defaultZValues[GeoDataFeature::HighwaySecondaryLink]= s_defaultZValue - 12;\n s_defaultZValues[GeoDataFeature::HighwayPrimaryLink] = s_defaultZValue - 12;\n s_defaultZValues[GeoDataFeature::HighwayTrunkLink] = s_defaultZValue - 12;\n s_defaultZValues[GeoDataFeature::HighwayMotorwayLink] = s_defaultZValue - 12;\n\n s_defaultZValues[GeoDataFeature::HighwayUnknown] = s_defaultZValue - 11;\n s_defaultZValues[GeoDataFeature::HighwayPath] = s_defaultZValue - 10;\n s_defaultZValues[GeoDataFeature::HighwayTrack] = s_defaultZValue - 9;\n s_defaultZValues[GeoDataFeature::HighwayPedestrian] = s_defaultZValue - 8;\n s_defaultZValues[GeoDataFeature::HighwayService] = s_defaultZValue - 7;\n s_defaultZValues[GeoDataFeature::HighwayRoad] = s_defaultZValue - 6;\n s_defaultZValues[GeoDataFeature::HighwayTertiary] = s_defaultZValue - 5;\n s_defaultZValues[GeoDataFeature::HighwaySecondary] = s_defaultZValue - 4;\n s_defaultZValues[GeoDataFeature::HighwayPrimary] = s_defaultZValue - 3;\n s_defaultZValues[GeoDataFeature::HighwayTrunk] = s_defaultZValue - 2;\n s_defaultZValues[GeoDataFeature::HighwayMotorway] = s_defaultZValue - 1;\n\n s_defaultValuesInitialized = true;\n}\n\n\nbool GeometryLayer::render( GeoPainter *painter, ViewportParams *viewport,\n const QString& renderPos, GeoSceneLayer * layer )\n{\n painter->save();\n painter->autoMapQuality();\n QList<GeoGraphicsItem*> items = d->m_scene.items( viewport->viewLatLonAltBox() );\n foreach( GeoGraphicsItem* item, items )\n {\n if ( item->visible() )\n item->paint( painter, viewport, renderPos, layer );\n }\n painter->restore();\n return true;\n}\n\nvoid GeometryLayerPrivate::createGraphicsItems( GeoDataObject *object )\n{\n GeoDataFeature *feature = dynamic_cast<GeoDataFeature*>( object );\n\n if ( dynamic_cast<GeoDataPlacemark*>( object ) )\n {\n GeoDataPlacemark *placemark = static_cast<GeoDataPlacemark*>( object );\n createGraphicsItemFromGeometry( placemark->geometry(), placemark );\n }\n\n \/\/ parse all child objects of the container\n GeoDataContainer *container = dynamic_cast<GeoDataContainer*>( object );\n if ( container )\n {\n int rowCount = container->size();\n for ( int row = 0; row < rowCount; ++row )\n {\n createGraphicsItems( container->child( row ) );\n }\n }\n}\n\nvoid GeometryLayerPrivate::createGraphicsItemFromGeometry( GeoDataGeometry* object, GeoDataPlacemark *placemark )\n{\n GeoGraphicsItem *item = 0;\n if ( dynamic_cast<GeoDataLinearRing*>( object ) )\n {\n }\n else if ( GeoDataLineString* line = dynamic_cast<GeoDataLineString*>( object ) )\n {\n item = new GeoLineStringGraphicsItem();\n static_cast<GeoLineStringGraphicsItem*>( item )->setLineString( *line );\n }\n else if ( GeoDataPolygon *poly = dynamic_cast<GeoDataPolygon*>( object ) )\n {\n item = new GeoPolygonGraphicsItem();\n static_cast<GeoPolygonGraphicsItem*>( item )->setPolygon( *poly );\n }\n else if ( dynamic_cast<GeoDataMultiGeometry*>( object ) )\n {\n GeoDataMultiGeometry *multigeo = dynamic_cast<GeoDataMultiGeometry*>( object );\n int rowCount = multigeo->size();\n for ( int row = 0; row < rowCount; ++row )\n {\n createGraphicsItemFromGeometry( multigeo->child( row ), placemark );\n }\n }\n if ( !item )\n return;\n item->setStyle( placemark->style() );\n item->setVisible( placemark->isVisible() );\n item->setZValue( GeometryLayer::s_defaultZValues[placemark->visualCategory()] );\n item->setMinLodPixels( GeometryLayer::s_defaultLODValues[placemark->visualCategory()] );\n m_scene.addIdem( item );\n}\n\nvoid GeometryLayer::invalidateScene()\n{\n QList<GeoGraphicsItem*> items = d->m_scene.items();\n foreach( GeoGraphicsItem* item, items )\n {\n delete item;\n }\n d->m_scene.clear();\n GeoDataObject *object = static_cast<GeoDataObject*>( d->m_model->index( 0, 0, QModelIndex() ).internalPointer() );\n if ( object && object->parent() )\n d->createGraphicsItems( object->parent() );\n}\n\n}\n\n#include \"GeometryLayer.moc\"\n<|endoftext|>"} {"text":"<commit_before>8431fc33-2d15-11e5-af21-0401358ea401<commit_msg>8431fc34-2d15-11e5-af21-0401358ea401<commit_after>8431fc34-2d15-11e5-af21-0401358ea401<|endoftext|>"} {"text":"<commit_before>ac22ad4a-327f-11e5-873d-9cf387a8033e<commit_msg>ac289df3-327f-11e5-9c2e-9cf387a8033e<commit_after>ac289df3-327f-11e5-9c2e-9cf387a8033e<|endoftext|>"} {"text":"<commit_before>8129aa97-2749-11e6-be60-e0f84713e7b8<commit_msg>Now it no longer crashes if X<commit_after>81387b7d-2749-11e6-8475-e0f84713e7b8<|endoftext|>"} {"text":"<commit_before>\/*\r\n** This source file is part of framepacker\r\n**\r\n** For the latest info, see https:\/\/github.com\/paladin-t\/framepacker\/\r\n**\r\n** Copyright (C) 2015 Wang Renxin\r\n**\r\n** Permission is hereby granted, free of charge, to any person obtaining a copy of\r\n** this software and associated documentation files (the \"Software\"), to deal in\r\n** the Software without restriction, including without limitation the rights to\r\n** use, copy, modify, merge, publish, distribute, sublicense, and\/or sell copies of\r\n** the Software, and to permit persons to whom the Software is furnished to do so,\r\n** subject to the following conditions:\r\n**\r\n** The above copyright notice and this permission notice shall be included in all\r\n** copies or substantial portions of the Software.\r\n**\r\n** THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\n** IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS\r\n** FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\r\n** COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\r\n** IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\r\n** CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\r\n*\/\r\n\r\n#include \"framepacker.hpp\"\r\n#include <list>\r\n#include <string>\r\n#include <Windows.h>\r\n#include \"third\/freeimage\/freeimage.h\"\r\n\r\nusing namespace framepacker;\r\n\r\nnamespace framepacker {\r\n\r\nstruct color {\r\n\tcolor() : r(0), g(0), b(0), a(0) {\r\n\t}\r\n\tcolor(unsigned char _r, unsigned char _g, unsigned char _b, unsigned char _a) : r(_r), g(_g), b(_b), a(_a) {\r\n\t}\r\n\r\n\tbool is_transparent(void) const {\r\n\t\treturn a == 0;\r\n\t}\r\n\r\n\tunsigned char r;\r\n\tunsigned char g;\r\n\tunsigned char b;\r\n\tunsigned char a;\r\n};\r\n\r\nclass freeimage {\r\n\r\npublic:\r\n\tfreeimage() : handle(NULL), w(0), h(0) {\r\n\t}\r\n\tfreeimage(const char* p) {\r\n\t\tload_file(p);\r\n\t}\r\n\t~freeimage() {\r\n\t\tunload();\r\n\t}\r\n\r\n\tconst char* get_path(void) const { return path.c_str(); }\r\n\r\n\tint width(void) const { return w; }\r\n\tint height(void) const { return h; }\r\n\r\n\tBYTE* bytes(void) const { return FreeImage_GetBits(handle); }\r\n\r\n\tcolor pixel(unsigned x, unsigned y) const {\r\n\t\tRGBQUAD col;\r\n\t\tFreeImage_GetPixelColor(handle, x, y, &col);\r\n\t\tcolor ret;\r\n\t\tret.r = col.rgbRed;\r\n\t\tret.g = col.rgbGreen;\r\n\t\tret.b = col.rgbBlue;\r\n\t\tret.a = col.rgbReserved;\r\n\r\n\t\treturn ret;\r\n\t}\r\n\tvoid pixel(unsigned x, unsigned y, color &c) {\r\n\t\tRGBQUAD col;\r\n\t\tcol.rgbRed = c.r;\r\n\t\tcol.rgbGreen = c.g;\r\n\t\tcol.rgbBlue = c.b;\r\n\t\tcol.rgbReserved = c.a;\r\n\t\tFreeImage_SetPixelColor(handle, x, y, &col);\r\n\t}\r\n\r\n\tvoid copy_from(freeimage &src, unsigned left, unsigned top, unsigned width, unsigned height, unsigned x, unsigned y) {\r\n\t\tFIBITMAP* fib = FreeImage_Copy(src.handle, left, top, left + width, top + height);\r\n\t\tFreeImage_Paste(handle, fib, x, y, 255);\r\n\t\tFreeImage_Unload(fib);\r\n\t}\r\n\r\n\tbool is_transparent(unsigned x, unsigned y) const {\r\n\t\tcolor c = pixel(x, y);\r\n\r\n\t\treturn c.is_transparent();\r\n\t}\r\n\r\n\tbool resize(int _w, int _h) {\r\n\t\tunload();\r\n\t\thandle = FreeImage_Allocate(_w, _h, 32);\r\n\t\tw = _w;\r\n\t\th = _h;\r\n\r\n\t\treturn true;\r\n\t}\r\n\r\n\tbool load_file(const char* p) {\r\n\t\tpath = p;\r\n\r\n\t\thandle = NULL;\r\n\t\tw = 0;\r\n\t\th = 0;\r\n\r\n\t\tFREE_IMAGE_FORMAT fif = FreeImage_GetFIFFromFilename(path.c_str());\r\n\t\tif(fif != FIF_UNKNOWN) {\r\n\t\t\thandle = FreeImage_Load(fif, path.c_str());\r\n\t\t\tif (FreeImage_GetBPP(handle) != 32) {\r\n\t\t\t\tFIBITMAP* tmp = handle;\r\n\t\t\t\thandle = FreeImage_ConvertTo32Bits(tmp);\r\n\t\t\t}\r\n\r\n\t\t\tw = FreeImage_GetWidth(handle);\r\n\t\t\th = FreeImage_GetHeight(handle);\r\n\r\n\t\t\treturn true;\r\n\t\t}\r\n\r\n\t\treturn false;\r\n\t}\r\n\r\n\tvoid unload(void) {\r\n\t\tif(!handle)\r\n\t\t\treturn;\r\n\r\n\t\tFreeImage_Unload(handle);\r\n\t\thandle = NULL;\r\n\t}\r\n\r\n\tvoid save(const char* p) {\r\n\t\tFreeImage_Save(FIF_PNG, handle, p);\r\n\t}\r\n\r\nprivate:\r\n\tstd::string path;\r\n\tFIBITMAP* handle;\r\n\tunsigned w;\r\n\tunsigned h;\r\n\r\n};\r\n\r\n}\r\n\r\ntypedef packer<freeimage> packer_type;\r\n\r\n#define _BIN_FILE_NAME \"framepacker\"\r\n\r\n#define _CHECK_ARG(__c, __i, __e) \\\r\n\tdo { \\\r\n\t\tif(__c <= __i + 1) { \\\r\n\t\t\tprintf(__e); \\\r\n\t\t\treturn; \\\r\n\t\t} \\\r\n\t} while(0)\r\n\r\nstatic unsigned short _set_console_color(unsigned short col) {\r\n\tCONSOLE_SCREEN_BUFFER_INFO csbiInfo;\r\n\tif(!GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &csbiInfo)) {\r\n\t\tprintf(\"GetConsoleScreenBufferInfo error!\\n\");\r\n\r\n\t\treturn 0;\r\n\t}\r\n\tif(!SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), col)) {\r\n\t\tprintf(\"SetConsoleTextAttribute error!\\n\");\r\n\r\n\t\treturn 0;\r\n\t}\r\n\r\n\treturn csbiInfo.wAttributes;\r\n}\r\n\r\nstruct ConsoleColor {\r\n\tConsoleColor(unsigned short col) {\r\n\t\told = _set_console_color(col);\r\n\t}\r\n\t~ConsoleColor() {\r\n\t\t_set_console_color(old);\r\n\t}\r\n\r\n\tunsigned short old;\r\n};\r\n\r\n#define CONSOLE_COLOR(C) ConsoleColor __##__FUNCTION__##__LINE__(C);\r\n\r\nstatic void _show_tip(void) {\r\n\tprintf(\"[Usage]\\n\");\r\n\tprintf(\" %s FILE_LIST [-o output_file] [OPTIONS] - Packs some images\\n\", _BIN_FILE_NAME);\r\n\tprintf(\"\\n\");\r\n\tprintf(\" FILE_LIST := file*\\n\");\r\n\tprintf(\" OPTIONS := -p n : Padding, 1 as default\\n\");\r\n\tprintf(\" := -s mxn : Expected texture size, eg. 256x512, may enlarge result\\n\");\r\n\tprintf(\" := -t : Disable rotation\\n\");\r\n\tprintf(\" := -w : Disable forcing texture to POT (Power of 2)\\n\");\r\n\tprintf(\" := -m : Disable alpha trim\\n\");\r\n}\r\n\r\nstatic void _process_parameters(int argc, char* argv[]) {\r\n\tint i = 1;\r\n\tstd::string m = \"\\0\";\r\n\tint padding = 1;\r\n\tint w = 0, h = 0;\r\n\tbool allow_rotate = true;\r\n\tbool power_of_2 = true;\r\n\tbool alpha_trim = true;\r\n\r\n\tstd::list<std::string> inputs;\r\n\tstd::list<std::pair<std::string, std::string> > options;\r\n\r\n\t\/\/ Parses arguments.\r\n\twhile(i < argc) {\r\n\t\tif(!memcmp(argv[i], \"-\", 1)) {\r\n\t\t\tif(!memcmp(argv[i] + 1, \"o\", 1)) {\r\n\t\t\t\tm = 'o';\r\n\t\t\t\t_CHECK_ARG(argc, i, \"-o: File name expected.\\n\");\r\n\t\t\t\toptions.push_back(std::make_pair(m, argv[++i]));\r\n\t\t\t\t++i;\r\n\t\t\t} else if(!memcmp(argv[i] + 1, \"p\", 1)) {\r\n\t\t\t\t_CHECK_ARG(argc, i, \"-p: Padding size expected.\\n\");\r\n\t\t\t\tpadding = max(std::atoi(argv[++i]), 0);\r\n\t\t\t} else if(!memcmp(argv[i] + 1, \"s\", 1)) {\r\n\t\t\t\t_CHECK_ARG(argc, i, \"-s: Size expected.\\n\");\r\n\t\t\t\tchar buf[256];\r\n\t\t\t\t_snprintf_s(buf, sizeof(buf), argv[++i]);\r\n\t\t\t\tchar* ctx = NULL;\r\n\t\t\t\tchar* tmp = strtok_s(buf, \"x\", &ctx);\r\n\t\t\t\tw = std::atoi(tmp);\r\n\t\t\t\th = std::atoi(ctx);\r\n\t\t\t\t++i;\r\n\t\t\t} else if(!memcmp(argv[i] + 1, \"t\", 1)) {\r\n\t\t\t\tallow_rotate = false;\r\n\t\t\t\t++i;\r\n\t\t\t} else if(!memcmp(argv[i] + 1, \"w\", 1)) {\r\n\t\t\t\tpower_of_2 = false;\r\n\t\t\t\t++i;\r\n\t\t\t} else if(!memcmp(argv[i] + 1, \"m\", 1)) {\r\n\t\t\t\talpha_trim = false;\r\n\t\t\t\t++i;\r\n\t\t\t} else {\r\n\t\t\t\tprintf(\"Unknown argument: %s.\\n\", argv[i++]);\r\n\t\t\t}\r\n\t\t} else {\r\n\t\t\tinputs.push_back(argv[i++]);\r\n\t\t}\r\n\t}\r\n\r\n\t\/\/ Tells output path.\r\n\tstd::string outpath = \"output.png\";\r\n\tfor(auto it = options.begin(); it != options.end(); ++it) {\r\n\t\tif(it->first == \"o\")\r\n\t\t\toutpath = it->second;\r\n\t}\r\n\r\n\t\/\/ Prepares packing.\r\n\tDWORD time = GetTickCount();\r\n\r\n\tpacker_type packer;\r\n\tpacker.padding = padding;\r\n\tpacker.output_texture_size = vec2(w, h);\r\n\tpacker.allow_rotate = allow_rotate;\r\n\tpacker.power_of_2 = power_of_2;\r\n\tpacker.alpha_trim = alpha_trim;\r\n\tpacker.comparer = packer_type::compare_area;\r\n\r\n\tfor(auto it = inputs.begin(); it != inputs.end(); ++it) {\r\n\t\tpacker_type::texture_type img(new freeimage(it->c_str()));\r\n\r\n\t\tpacker.add(it->c_str(), img);\r\n\t}\r\n\r\n\tDWORD load_time = GetTickCount() - time;\r\n\ttime = GetTickCount();\r\n\r\n\t\/\/ Packs it.\r\n\tpacker_type::texture_type result(new freeimage);\r\n\tpacker_type::texture_coll_type packed;\r\n\tpacker_type::texture_coll_type failed;\r\n\tpacker.pack(result, packed, failed);\r\n\r\n\tDWORD pack_time = GetTickCount() - time;\r\n\r\n\t\/\/ Prompts.\r\n\t{\r\n\t\tCONSOLE_COLOR(FOREGROUND_INTENSITY);\r\n\t\tprintf(\"Packed %d:\\n\", packed.size());\r\n\t\tfor(auto it = packed.begin(); it != packed.end(); ++it) {\r\n\t\t\tpacker_type::block_type &blk = it->second;\r\n\t\t\tprintf(\" %s [%d, %d] - [%d, %d]\\n\", it->first.c_str(), blk.fit->min_x(), blk.fit->min_y(), blk.fit->min_x() + blk.fit->width(), blk.fit->min_y() + blk.fit->height());\r\n\t\t}\r\n\t}\r\n\tif(failed.size()) {\r\n\t\tCONSOLE_COLOR(FOREGROUND_RED | FOREGROUND_GREEN);\r\n\t\tprintf(\"Failed %d:\\n\", failed.size());\r\n\t\tfor(auto it = failed.begin(); it != failed.end(); ++it) {\r\n\t\t\tpacker_type::block_type &blk = it->second;\r\n\t\t\tprintf(\" %s\\n\", it->first.c_str());\r\n\t\t}\r\n\t}\r\n\t{\r\n\t\tCONSOLE_COLOR(FOREGROUND_INTENSITY);\r\n\t\tprintf(\"Cost time: %gs loading; %gs packing.\\n\", (float)load_time \/ 1000.0f, (float)pack_time \/ 1000.0f);\r\n\t}\r\n\r\n\t\/\/ Serializes.\r\n\t{\r\n\t\tCONSOLE_COLOR(FOREGROUND_INTENSITY);\r\n\t\tstd::string out_tex = outpath + \".png\";\r\n\t\tresult->save(out_tex.c_str());\r\n\t\tprintf(\"Texture written: %s.\\n\", out_tex.c_str());\r\n\t}\r\n\t{\r\n\t\tCONSOLE_COLOR(FOREGROUND_INTENSITY);\r\n\t\tstd::string out_meta = outpath + \".json\";\r\n\t\tstd::ofstream fs(out_meta);\r\n\t\tpacker.write_meta(fs, packed, result, outpath.c_str());\r\n\t\tfs.close();\r\n\t\tprintf(\"Meta data written: %s.\\n\", out_meta.c_str());\r\n\t}\r\n}\r\n\r\nstatic void _on_startup(void) {\r\n\tFreeImage_Initialise();\r\n}\r\n\r\nstatic void _on_exit(void) {\r\n\tFreeImage_DeInitialise();\r\n}\r\n\r\nint main(int argc, char* argv[]) {\r\n\tatexit(_on_exit);\r\n\r\n\t_on_startup();\r\n\r\n\tif(argc == 1)\r\n\t\t_show_tip();\r\n\telse if(argc >= 2)\r\n\t\t_process_parameters(argc, argv);\r\n\r\n\treturn 0;\r\n}\r\n<commit_msg>*updated main.cpp.<commit_after>\/*\r\n** This source file is part of framepacker\r\n**\r\n** For the latest info, see https:\/\/github.com\/paladin-t\/framepacker\/\r\n**\r\n** Copyright (C) 2015 Wang Renxin\r\n**\r\n** Permission is hereby granted, free of charge, to any person obtaining a copy of\r\n** this software and associated documentation files (the \"Software\"), to deal in\r\n** the Software without restriction, including without limitation the rights to\r\n** use, copy, modify, merge, publish, distribute, sublicense, and\/or sell copies of\r\n** the Software, and to permit persons to whom the Software is furnished to do so,\r\n** subject to the following conditions:\r\n**\r\n** The above copyright notice and this permission notice shall be included in all\r\n** copies or substantial portions of the Software.\r\n**\r\n** THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\n** IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS\r\n** FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\r\n** COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\r\n** IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\r\n** CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\r\n*\/\r\n\r\n#include \"framepacker.hpp\"\r\n#include <list>\r\n#include <string>\r\n#include <Windows.h>\r\n#include \"freeimage.h\"\r\n\r\nusing namespace framepacker;\r\n\r\nnamespace framepacker {\r\n\r\nstruct color {\r\n\tcolor() : r(0), g(0), b(0), a(0) {\r\n\t}\r\n\tcolor(unsigned char _r, unsigned char _g, unsigned char _b, unsigned char _a) : r(_r), g(_g), b(_b), a(_a) {\r\n\t}\r\n\r\n\tbool is_transparent(void) const {\r\n\t\treturn a == 0;\r\n\t}\r\n\r\n\tunsigned char r;\r\n\tunsigned char g;\r\n\tunsigned char b;\r\n\tunsigned char a;\r\n};\r\n\r\nclass freeimage {\r\n\r\npublic:\r\n\tfreeimage() : handle(NULL), w(0), h(0) {\r\n\t}\r\n\tfreeimage(const char* p) {\r\n\t\tload_file(p);\r\n\t}\r\n\t~freeimage() {\r\n\t\tunload();\r\n\t}\r\n\r\n\tconst char* get_path(void) const { return path.c_str(); }\r\n\r\n\tint width(void) const { return w; }\r\n\tint height(void) const { return h; }\r\n\r\n\tBYTE* bytes(void) const { return FreeImage_GetBits(handle); }\r\n\r\n\tcolor pixel(unsigned x, unsigned y) const {\r\n\t\tRGBQUAD col;\r\n\t\tFreeImage_GetPixelColor(handle, x, y, &col);\r\n\t\tcolor ret;\r\n\t\tret.r = col.rgbRed;\r\n\t\tret.g = col.rgbGreen;\r\n\t\tret.b = col.rgbBlue;\r\n\t\tret.a = col.rgbReserved;\r\n\r\n\t\treturn ret;\r\n\t}\r\n\tvoid pixel(unsigned x, unsigned y, color &c) {\r\n\t\tRGBQUAD col;\r\n\t\tcol.rgbRed = c.r;\r\n\t\tcol.rgbGreen = c.g;\r\n\t\tcol.rgbBlue = c.b;\r\n\t\tcol.rgbReserved = c.a;\r\n\t\tFreeImage_SetPixelColor(handle, x, y, &col);\r\n\t}\r\n\r\n\tvoid copy_from(freeimage &src, unsigned left, unsigned top, unsigned width, unsigned height, unsigned x, unsigned y) {\r\n\t\tFIBITMAP* fib = FreeImage_Copy(src.handle, left, top, left + width, top + height);\r\n\t\tFreeImage_Paste(handle, fib, x, y, 255);\r\n\t\tFreeImage_Unload(fib);\r\n\t}\r\n\r\n\tbool is_transparent(unsigned x, unsigned y) const {\r\n\t\tcolor c = pixel(x, y);\r\n\r\n\t\treturn c.is_transparent();\r\n\t}\r\n\r\n\tbool resize(int _w, int _h) {\r\n\t\tunload();\r\n\t\thandle = FreeImage_Allocate(_w, _h, 32);\r\n\t\tw = _w;\r\n\t\th = _h;\r\n\r\n\t\treturn true;\r\n\t}\r\n\r\n\tbool load_file(const char* p) {\r\n\t\tpath = p;\r\n\r\n\t\thandle = NULL;\r\n\t\tw = 0;\r\n\t\th = 0;\r\n\r\n\t\tFREE_IMAGE_FORMAT fif = FreeImage_GetFIFFromFilename(path.c_str());\r\n\t\tif(fif != FIF_UNKNOWN) {\r\n\t\t\thandle = FreeImage_Load(fif, path.c_str());\r\n\t\t\tif (FreeImage_GetBPP(handle) != 32) {\r\n\t\t\t\tFIBITMAP* tmp = handle;\r\n\t\t\t\thandle = FreeImage_ConvertTo32Bits(tmp);\r\n\t\t\t}\r\n\r\n\t\t\tw = FreeImage_GetWidth(handle);\r\n\t\t\th = FreeImage_GetHeight(handle);\r\n\r\n\t\t\treturn true;\r\n\t\t}\r\n\r\n\t\treturn false;\r\n\t}\r\n\r\n\tvoid unload(void) {\r\n\t\tif(!handle)\r\n\t\t\treturn;\r\n\r\n\t\tFreeImage_Unload(handle);\r\n\t\thandle = NULL;\r\n\t}\r\n\r\n\tvoid save(const char* p) {\r\n\t\tFreeImage_Save(FIF_PNG, handle, p);\r\n\t}\r\n\r\nprivate:\r\n\tstd::string path;\r\n\tFIBITMAP* handle;\r\n\tunsigned w;\r\n\tunsigned h;\r\n\r\n};\r\n\r\n}\r\n\r\ntypedef packer<freeimage> packer_type;\r\n\r\n#define _BIN_FILE_NAME \"framepacker\"\r\n\r\n#define _CHECK_ARG(__c, __i, __e) \\\r\n\tdo { \\\r\n\t\tif(__c <= __i + 1) { \\\r\n\t\t\tprintf(__e); \\\r\n\t\t\treturn; \\\r\n\t\t} \\\r\n\t} while(0)\r\n\r\nstatic unsigned short _set_console_color(unsigned short col) {\r\n\tCONSOLE_SCREEN_BUFFER_INFO csbiInfo;\r\n\tif(!GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &csbiInfo)) {\r\n\t\tprintf(\"GetConsoleScreenBufferInfo error!\\n\");\r\n\r\n\t\treturn 0;\r\n\t}\r\n\tif(!SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), col)) {\r\n\t\tprintf(\"SetConsoleTextAttribute error!\\n\");\r\n\r\n\t\treturn 0;\r\n\t}\r\n\r\n\treturn csbiInfo.wAttributes;\r\n}\r\n\r\nstruct ConsoleColor {\r\n\tConsoleColor(unsigned short col) {\r\n\t\told = _set_console_color(col);\r\n\t}\r\n\t~ConsoleColor() {\r\n\t\t_set_console_color(old);\r\n\t}\r\n\r\n\tunsigned short old;\r\n};\r\n\r\n#define CONSOLE_COLOR(C) ConsoleColor __##__FUNCTION__##__LINE__(C);\r\n\r\nstatic void _show_tip(void) {\r\n\tprintf(\"[Usage]\\n\");\r\n\tprintf(\" %s FILE_LIST [-o output_file] [OPTIONS] - Packs some images\\n\", _BIN_FILE_NAME);\r\n\tprintf(\"\\n\");\r\n\tprintf(\" FILE_LIST := file*\\n\");\r\n\tprintf(\" OPTIONS := -p n : Padding, 1 as default\\n\");\r\n\tprintf(\" := -s mxn : Expected texture size, eg. 256x512, may enlarge result\\n\");\r\n\tprintf(\" := -t : Disable rotation\\n\");\r\n\tprintf(\" := -w : Disable forcing texture to POT (Power of 2)\\n\");\r\n\tprintf(\" := -m : Disable alpha trim\\n\");\r\n}\r\n\r\nstatic void _process_parameters(int argc, char* argv[]) {\r\n\tint i = 1;\r\n\tstd::string m = \"\\0\";\r\n\tint padding = 1;\r\n\tint w = 0, h = 0;\r\n\tbool allow_rotate = true;\r\n\tbool power_of_2 = true;\r\n\tbool alpha_trim = true;\r\n\r\n\tstd::list<std::string> inputs;\r\n\tstd::list<std::pair<std::string, std::string> > options;\r\n\r\n\t\/\/ Parses arguments.\r\n\twhile(i < argc) {\r\n\t\tif(!memcmp(argv[i], \"-\", 1)) {\r\n\t\t\tif(!memcmp(argv[i] + 1, \"o\", 1)) {\r\n\t\t\t\tm = 'o';\r\n\t\t\t\t_CHECK_ARG(argc, i, \"-o: File name expected.\\n\");\r\n\t\t\t\toptions.push_back(std::make_pair(m, argv[++i]));\r\n\t\t\t\t++i;\r\n\t\t\t} else if(!memcmp(argv[i] + 1, \"p\", 1)) {\r\n\t\t\t\t_CHECK_ARG(argc, i, \"-p: Padding size expected.\\n\");\r\n\t\t\t\tpadding = max(std::atoi(argv[++i]), 0);\r\n\t\t\t} else if(!memcmp(argv[i] + 1, \"s\", 1)) {\r\n\t\t\t\t_CHECK_ARG(argc, i, \"-s: Size expected.\\n\");\r\n\t\t\t\tchar buf[256];\r\n\t\t\t\t_snprintf_s(buf, sizeof(buf), argv[++i]);\r\n\t\t\t\tchar* ctx = NULL;\r\n\t\t\t\tchar* tmp = strtok_s(buf, \"x\", &ctx);\r\n\t\t\t\tw = std::atoi(tmp);\r\n\t\t\t\th = std::atoi(ctx);\r\n\t\t\t\t++i;\r\n\t\t\t} else if(!memcmp(argv[i] + 1, \"t\", 1)) {\r\n\t\t\t\tallow_rotate = false;\r\n\t\t\t\t++i;\r\n\t\t\t} else if(!memcmp(argv[i] + 1, \"w\", 1)) {\r\n\t\t\t\tpower_of_2 = false;\r\n\t\t\t\t++i;\r\n\t\t\t} else if(!memcmp(argv[i] + 1, \"m\", 1)) {\r\n\t\t\t\talpha_trim = false;\r\n\t\t\t\t++i;\r\n\t\t\t} else {\r\n\t\t\t\tprintf(\"Unknown argument: %s.\\n\", argv[i++]);\r\n\t\t\t}\r\n\t\t} else {\r\n\t\t\tinputs.push_back(argv[i++]);\r\n\t\t}\r\n\t}\r\n\r\n\t\/\/ Tells output path.\r\n\tstd::string outpath = \"output.png\";\r\n\tfor(auto it = options.begin(); it != options.end(); ++it) {\r\n\t\tif(it->first == \"o\")\r\n\t\t\toutpath = it->second;\r\n\t}\r\n\r\n\t\/\/ Prepares packing.\r\n\tDWORD time = GetTickCount();\r\n\r\n\tpacker_type packer;\r\n\tpacker.padding = padding;\r\n\tpacker.output_texture_size = vec2(w, h);\r\n\tpacker.allow_rotate = allow_rotate;\r\n\tpacker.power_of_2 = power_of_2;\r\n\tpacker.alpha_trim = alpha_trim;\r\n\tpacker.comparer = packer_type::compare_area;\r\n\r\n\tfor(auto it = inputs.begin(); it != inputs.end(); ++it) {\r\n\t\tpacker_type::texture_type img(new freeimage(it->c_str()));\r\n\r\n\t\tpacker.add(it->c_str(), img);\r\n\t}\r\n\r\n\tDWORD load_time = GetTickCount() - time;\r\n\ttime = GetTickCount();\r\n\r\n\t\/\/ Packs it.\r\n\tpacker_type::texture_type result(new freeimage);\r\n\tpacker_type::texture_coll_type packed;\r\n\tpacker_type::texture_coll_type failed;\r\n\tpacker.pack(result, packed, failed);\r\n\r\n\tDWORD pack_time = GetTickCount() - time;\r\n\r\n\t\/\/ Prompts.\r\n\t{\r\n\t\tCONSOLE_COLOR(FOREGROUND_INTENSITY);\r\n\t\tprintf(\"Packed %d:\\n\", packed.size());\r\n\t\tfor(auto it = packed.begin(); it != packed.end(); ++it) {\r\n\t\t\tpacker_type::block_type &blk = it->second;\r\n\t\t\tprintf(\" %s [%d, %d] - [%d, %d]\\n\", it->first.c_str(), blk.fit->min_x(), blk.fit->min_y(), blk.fit->min_x() + blk.fit->width(), blk.fit->min_y() + blk.fit->height());\r\n\t\t}\r\n\t}\r\n\tif(failed.size()) {\r\n\t\tCONSOLE_COLOR(FOREGROUND_RED | FOREGROUND_GREEN);\r\n\t\tprintf(\"Failed %d:\\n\", failed.size());\r\n\t\tfor(auto it = failed.begin(); it != failed.end(); ++it) {\r\n\t\t\tpacker_type::block_type &blk = it->second;\r\n\t\t\tprintf(\" %s\\n\", it->first.c_str());\r\n\t\t}\r\n\t}\r\n\t{\r\n\t\tCONSOLE_COLOR(FOREGROUND_INTENSITY);\r\n\t\tprintf(\"Cost time: %gs loading; %gs packing.\\n\", (float)load_time \/ 1000.0f, (float)pack_time \/ 1000.0f);\r\n\t}\r\n\r\n\t\/\/ Serializes.\r\n\t{\r\n\t\tCONSOLE_COLOR(FOREGROUND_INTENSITY);\r\n\t\tstd::string out_tex = outpath + \".png\";\r\n\t\tresult->save(out_tex.c_str());\r\n\t\tprintf(\"Texture written: %s.\\n\", out_tex.c_str());\r\n\t}\r\n\t{\r\n\t\tCONSOLE_COLOR(FOREGROUND_INTENSITY);\r\n\t\tstd::string out_meta = outpath + \".json\";\r\n\t\tstd::ofstream fs(out_meta);\r\n\t\tpacker.write_meta(fs, packed, result, outpath.c_str());\r\n\t\tfs.close();\r\n\t\tprintf(\"Meta data written: %s.\\n\", out_meta.c_str());\r\n\t}\r\n}\r\n\r\nstatic void _on_startup(void) {\r\n\tFreeImage_Initialise();\r\n}\r\n\r\nstatic void _on_exit(void) {\r\n\tFreeImage_DeInitialise();\r\n}\r\n\r\nint main(int argc, char* argv[]) {\r\n\tatexit(_on_exit);\r\n\r\n\t_on_startup();\r\n\r\n\tif(argc == 1)\r\n\t\t_show_tip();\r\n\telse if(argc >= 2)\r\n\t\t_process_parameters(argc, argv);\r\n\r\n\treturn 0;\r\n}\r\n<|endoftext|>"} {"text":"<commit_before>76ad0dc5-2749-11e6-a21e-e0f84713e7b8<commit_msg>Put the thingie in the thingie<commit_after>76be8540-2749-11e6-9828-e0f84713e7b8<|endoftext|>"} {"text":"<commit_before>a8456891-2d3f-11e5-8921-c82a142b6f9b<commit_msg>a8b346fa-2d3f-11e5-b64f-c82a142b6f9b<commit_after>a8b346fa-2d3f-11e5-b64f-c82a142b6f9b<|endoftext|>"} {"text":"<commit_before>a643238c-327f-11e5-a01b-9cf387a8033e<commit_msg>a649b84f-327f-11e5-aea1-9cf387a8033e<commit_after>a649b84f-327f-11e5-aea1-9cf387a8033e<|endoftext|>"} {"text":"<commit_before>78fd5c5c-2d53-11e5-baeb-247703a38240<commit_msg>78fdd9f2-2d53-11e5-baeb-247703a38240<commit_after>78fdd9f2-2d53-11e5-baeb-247703a38240<|endoftext|>"} {"text":"<commit_before>#include <stdlib.h>\n#include <stdio.h>\n#include <stdarg.h>\n#include <malloc.h>\n#include <memory.h>\n#include <string.h>\n#include <tchar.h>\n#include <string>\n#include <map>\n\n#define WIN32_LEAN_AND_MEAN\n\n#include <windows.h>\n#include <Windowsx.h>\n#include <commctrl.h>\n#include <shellapi.h>\n#include <Shlwapi.h>\n#include <process.h>\n#include <vector>\n#include <ctime>\n#include <cstring>\n\n#include \"files.h\"\n#include \"whff.h\"\n#include \"bitmap.h\"\n#include <map>\n#include \"luawrap.h\"\n#include \"froglies.h\"\n\n#define CLASSNAME\t\"winss\"\n#define WINDOWTITLE\t\"svchost\"\n#define ICON_MESSAGE (WM_USER + 1)\n\n#define NOTNOW 0\n#define WAITING 1\n#define DRAGGING 2\n\nnamespace FrogLies{\n\n bool running;\n HHOOK kbdhook;\n HHOOK mouhook;\n HWND hwnd;\n NOTIFYICONDATA nid;\n HICON IconA;\n HICON IconB;\n\n char clickDrag; \/\/States are NOTNOW, WAITING, DRAGGING.\n POINT dragStart;\n POINT dragEnd;\n POINT coords;\n HCURSOR dragCursor;\n HCURSOR dfltCursor;\n\n void CheckKeys();\n\n std::map<std::string,int> keyspressed;\n int ReadKey( std::string key ){\n if( keyspressed[key] == 2 ){\n keyspressed[key] = 1;\n return 2;\n }\n if( keyspressed[key] == 3 ){\n keyspressed[key] = 0;\n return 2;\n }\n\n return keyspressed[key];\n }\n\n void SetClipboard( std::string text ) {\n if(OpenClipboard(NULL)) {\n HGLOBAL clipbuffer;\n char *buffer;\n EmptyClipboard();\n clipbuffer = GlobalAlloc(GMEM_DDESHARE, text.length()+1);\n buffer = (char*)GlobalLock(clipbuffer);\n strcpy(buffer, text.c_str());\n GlobalUnlock(clipbuffer);\n SetClipboardData(CF_TEXT,clipbuffer);\n CloseClipboard();\n }\n }\n\n LRESULT CALLBACK handlemouse(int code, WPARAM wp, LPARAM lp){\n if (clickDrag){\n if ((wp == WM_LBUTTONDOWN || wp == WM_LBUTTONUP || wp == WM_MOUSEMOVE)){\n MSLLHOOKSTRUCT st_hook = *((MSLLHOOKSTRUCT*)lp);\n dragEnd = st_hook.pt;\n\n if (clickDrag == WAITING){\n coords = dragEnd;\n }\n else{\n coords.x = dragEnd.x - dragStart.x;\n coords.y = dragEnd.y - dragStart.y;\n }\n\n \/\/printf(\"State: %i \\t MPos: [%i, %i] \\t Coord: [%i, %i]\\n\", clickDrag, dragEnd.x, dragEnd.y, coords.x, coords.y);\n\n \/\/printf(\"HANDMOUS- wp: 0x%X \\t md: 0x%X \\t fl: 0x%X\\n\", wp, st_hook.mouseData, st_hook.flags);\n\n if (wp == WM_LBUTTONDOWN){\n dragStart = dragEnd;\n clickDrag = DRAGGING;\n printf(\"DOWN!\\n\");\n }\n if (wp == WM_LBUTTONUP){\n \/\/takeScreenShotAndClipTo(dragStart, dragEnd);\n clickDrag = NOTNOW;\n printf(\"UP!\\n\");\n SetCursor(dfltCursor);\n }\n }\n }\n else{\n return CallNextHookEx(mouhook, code, wp, lp);\n }\n }\n\n LRESULT CALLBACK handlekeys(int code, WPARAM wp, LPARAM lp){\n if (code == HC_ACTION && (wp == WM_SYSKEYUP || wp == WM_KEYUP)){\n char tmp[0xFF] = {0};\n std::string str;\n DWORD msg = 1;\n KBDLLHOOKSTRUCT st_hook = *((KBDLLHOOKSTRUCT*)lp);\n msg += (st_hook.scanCode << 16);\n msg += (st_hook.flags << 24);\n GetKeyNameText(msg, tmp, 0xFF);\n str = std::string(tmp);\n if( keyspressed[str] == 2 )\n keyspressed[str] = 3;\n else\n keyspressed[str] = 0;\n \/\/fprintf(out, \"%s\\n\", str.c_str());\n\n printf(\"%s up\\n\", str.c_str());\n }\n else if (code == HC_ACTION && (wp == WM_SYSKEYDOWN || wp == WM_KEYDOWN)) {\n char tmp[0xFF] = {0};\n std::string str;\n DWORD msg = 1;\n KBDLLHOOKSTRUCT st_hook = *((KBDLLHOOKSTRUCT*)lp);\n msg += (st_hook.scanCode << 16);\n msg += (st_hook.flags << 24);\n GetKeyNameText(msg, tmp, 0xFF);\n str = std::string(tmp);\n if( keyspressed[str] == 0 )\n keyspressed[str] = 2;\n else\n keyspressed[str] = 1;\n\n printf(\"%s down\\n\", str.c_str());\n }\n CheckKeys();\n\n return CallNextHookEx(kbdhook, code, wp, lp);\n }\n\n LRESULT CALLBACK windowprocedure(HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam){\n \/\/printf(\"FISH!\");\n\n printf(\"WINDPROC- wp: 0x%X \\t lp: 0x%X\\n\", wparam, lparam);\n\n switch (msg){\n case WM_CREATE:\n \/\/printf(\"FISH!\");\n break;\n case ICON_MESSAGE:\n switch(lparam){\n case WM_LBUTTONDBLCLK:\n MessageBox(NULL, \"Tray icon double clicked!\", \"clicked\", MB_OK);\n break;\n case WM_LBUTTONUP:\n MessageBox(NULL, \"Tray icon clicked!\", \"clicked\", MB_OK);\n break;\n default:\n return DefWindowProc(hwnd, msg, wparam, lparam);\n };\n break;\n case WM_CLOSE: case WM_DESTROY:\n running = false;\n break;\n default:\n return DefWindowProc(hwnd, msg, wparam, lparam);\n };\n return 0;\n }\n\n std::string Timestamp() {\n time_t rawtime;\n struct tm * timeinfo;\n time ( &rawtime );\n timeinfo = localtime ( &rawtime );\n char str[64];\n snprintf(str, 64, \"ss at %s\", asctime(timeinfo));\n int i = 0;\n while (str[i]){\n i++;\n if (str[i] == ' '){\n str[i] = '_'; }\n }\n std::string ToReturn(str);\n return ToReturn;\n }\n\n void CheckKeys(){\n if( ShortcutDesk.IsHit() ){\n WHFF whff(\"\");\n Bitmap mb = GetWindow(GetDesktopWindow());\n void* data = mb.ReadPNG();\n whff.Upload( Timestamp(), data, mb.PNGLen(), GetMimeFromExt(\"png\"));\n SetClipboard( whff.GetLastUpload() );\n }\n\n if (ShortcutWin.IsHit()) {\n WHFF whff(\"\");\n Bitmap mb = GetWindow(GetForegroundWindow());\n void* data = mb.ReadPNG();\n whff.Upload( Timestamp(), data, mb.PNGLen(), GetMimeFromExt(\"png\"));\n SetClipboard( whff.GetLastUpload() );\n }\n\n if (ShortcutCrop.IsHit()) {\n printf(\"hi\\n\");\n clickDrag = WAITING;\n SetCursor(dragCursor);\n }\n if (ShortcutClip.IsHit()) {\n WHFF whff(\"\");\n HANDLE hClipboardData = GetClipboardData(CF_TEXT);\n char *pchData = (char*)GlobalLock(hClipboardData);\n void* data = (void*)pchData;\n whff.Upload( Timestamp(), data, strlen(pchData), GetMimeFromExt(\"txt\"));\n GlobalUnlock(hClipboardData);\n CloseClipboard();\n SetClipboard( whff.GetLastUpload() );\n }\n if (ShortcutQuit.IsHit()) {\n PostMessage( hwnd, WM_CLOSE, 0, 0 );\n }\n }\n\n void GUIThread( void* ){\n while( running ){\n Sleep(1000);\n nid.hIcon = IconA;\n Shell_NotifyIcon(NIM_MODIFY, &nid);\n Sleep(1000);\n nid.hIcon = IconB;\n Shell_NotifyIcon(NIM_MODIFY, &nid);\n }\n }\n\n static int SetShortcut( Shortcut* s, const char* value ){\n if( s->IsValid() ){\n s->Set( value );\n }\n return 1;\n }\n\n void ReadConf( std::string fname ){\n size_t len;\n char* d = (char*)read_file_to_buffer( fname, len );\n if( d == 0 )\n return;\n printf(\"Using non-standard configuration\\n\");\n d = (char*)realloc( d, len+1 );\n d[len] = 0;\n std::string buff = d;\n free( d );\n\n Lua L( buff.c_str(), \"Configuration\", 0 );\n L.funcreg<int, Shortcut*, const char*, SetShortcut >(\"shortcut\");\n L.set(\"SHORTCUT_WIN\", &ShortcutWin);\n L.set(\"SHORTCUT_DESK\", &ShortcutDesk);\n L.set(\"SHORTCUT_CROP\", &ShortcutCrop);\n L.set(\"SHORTCUT_CLIP\", &ShortcutClip);\n L.set(\"SHORTCUT_QUIT\", &ShortcutQuit);\n\n L.run();\n }\n}\n\nusing namespace FrogLies;\n\nint WINAPI WinMain(HINSTANCE thisinstance, HINSTANCE previnstance, LPSTR cmdline, int ncmdshow){\n\n\n ReadConf( \"conf.cfg\" );\n\n\tHWND\t\tfgwindow = GetForegroundWindow(); \/* Current foreground window *\/\n\tMSG\t\t msg;\n\tWNDCLASSEX\twindowclass;\n\tHINSTANCE\tmodulehandle;\n\n\twindowclass.hInstance = thisinstance;\n\twindowclass.lpszClassName = CLASSNAME;\n\twindowclass.lpfnWndProc = windowprocedure;\n\twindowclass.style = CS_DBLCLKS;\n\twindowclass.cbSize = sizeof(WNDCLASSEX);\n\twindowclass.hIcon = LoadIcon(NULL, IDI_APPLICATION);\n\twindowclass.hIconSm = LoadIcon(NULL, IDI_APPLICATION);\n\twindowclass.hCursor = LoadCursor(NULL, IDC_ARROW);\n\twindowclass.lpszMenuName = NULL;\n\twindowclass.cbClsExtra = 0;\n\twindowclass.cbWndExtra = 0;\n\twindowclass.hbrBackground = (HBRUSH)COLOR_BACKGROUND;\n\n\tif (!(RegisterClassEx(&windowclass))){ return 1; }\n\n\thwnd = CreateWindowEx(0, CLASSNAME, WINDOWTITLE, WS_OVERLAPPEDWINDOW,\n CW_USEDEFAULT, CW_USEDEFAULT, 640, 480, HWND_DESKTOP, NULL,\n thisinstance, NULL);\n\n\tif (!(hwnd)){ return 1; }\n\n ShowWindow(hwnd, SW_HIDE);\n\tUpdateWindow(hwnd);\n\tSetForegroundWindow(fgwindow); \/* Give focus to the previous fg window *\/\n\n dragCursor = LoadCursor(thisinstance, IDC_CROSS);\n dfltCursor = GetCursor();\n\n \/\/#define BEGIN_IN_DRAGMODE\n #ifdef BEGIN_IN_DRAGMODE\n SetCursor(dragCursor);\n clickDrag = WAITING;\n #endif\n\n IconA = (HICON) LoadImage( thisinstance, \"img\/icona.ico\", IMAGE_ICON, 32, 32, LR_LOADFROMFILE );\n IconB = (HICON) LoadImage( thisinstance, \"img\/iconb.ico\", IMAGE_ICON, 32, 32, LR_LOADFROMFILE );\n\n\n nid.cbSize = sizeof(NOTIFYICONDATA);\n nid.uID = 100;\n nid.hWnd = hwnd;\n \/\/nid.uVersion = NOTIFYICON_VERSION;\n nid.uCallbackMessage = ICON_MESSAGE;\n nid.hIcon = IconB; \/\/= LoadIcon(NULL, IDI_APPLICATION);\n snprintf(nid.szTip, 64, \"Icon\");\n nid.uFlags = NIF_MESSAGE | NIF_ICON | NIF_TIP;\n\n Shell_NotifyIcon(NIM_ADD, &nid);\n\n modulehandle = GetModuleHandle(NULL);\n\tkbdhook = SetWindowsHookEx(WH_KEYBOARD_LL, (HOOKPROC)handlekeys, modulehandle, 0);\n\tmouhook = SetWindowsHookEx(WH_MOUSE_LL, (HOOKPROC)handlemouse, modulehandle, 0);\n\n running = true;\n\n _beginthread( GUIThread, 1000, NULL );\n \/\/GUIThread(0);\n\n\twhile (running) {\n\t\tif (!GetMessage(&msg, NULL, 0, 0))\n\t\t\tbreak;\n\t\tTranslateMessage(&msg);\n\t\tDispatchMessage(&msg);\n\t}\n\n Shell_NotifyIcon(NIM_DELETE, &nid);\n\n\treturn 0;\n}\n<commit_msg>Fix clipboard uploading for text.<commit_after>#include <stdlib.h>\n#include <stdio.h>\n#include <stdarg.h>\n#include <malloc.h>\n#include <memory.h>\n#include <string.h>\n#include <tchar.h>\n#include <string>\n#include <map>\n\n#define WIN32_LEAN_AND_MEAN\n\n#include <windows.h>\n#include <Windowsx.h>\n#include <commctrl.h>\n#include <shellapi.h>\n#include <Shlwapi.h>\n#include <process.h>\n#include <vector>\n#include <ctime>\n#include <cstring>\n\n#include \"files.h\"\n#include \"whff.h\"\n#include \"bitmap.h\"\n#include <map>\n#include \"luawrap.h\"\n#include \"froglies.h\"\n\n#define CLASSNAME\t\"winss\"\n#define WINDOWTITLE\t\"svchost\"\n#define ICON_MESSAGE (WM_USER + 1)\n\n#define NOTNOW 0\n#define WAITING 1\n#define DRAGGING 2\n\nnamespace FrogLies{\n\n bool running;\n HHOOK kbdhook;\n HHOOK mouhook;\n HWND hwnd;\n NOTIFYICONDATA nid;\n HICON IconA;\n HICON IconB;\n\n char clickDrag; \/\/States are NOTNOW, WAITING, DRAGGING.\n POINT dragStart;\n POINT dragEnd;\n POINT coords;\n HCURSOR dragCursor;\n HCURSOR dfltCursor;\n\n void CheckKeys();\n\n std::map<std::string,int> keyspressed;\n int ReadKey( std::string key ){\n if( keyspressed[key] == 2 ){\n keyspressed[key] = 1;\n return 2;\n }\n if( keyspressed[key] == 3 ){\n keyspressed[key] = 0;\n return 2;\n }\n\n return keyspressed[key];\n }\n\n void SetClipboard( std::string text ) {\n if(OpenClipboard(NULL)) {\n HGLOBAL clipbuffer;\n char *buffer;\n EmptyClipboard();\n clipbuffer = GlobalAlloc(GMEM_DDESHARE, text.length()+1);\n buffer = (char*)GlobalLock(clipbuffer);\n strcpy(buffer, text.c_str());\n GlobalUnlock(clipbuffer);\n SetClipboardData(CF_TEXT,clipbuffer);\n CloseClipboard();\n }\n }\n\n LRESULT CALLBACK handlemouse(int code, WPARAM wp, LPARAM lp){\n if (clickDrag){\n if ((wp == WM_LBUTTONDOWN || wp == WM_LBUTTONUP || wp == WM_MOUSEMOVE)){\n MSLLHOOKSTRUCT st_hook = *((MSLLHOOKSTRUCT*)lp);\n dragEnd = st_hook.pt;\n\n if (clickDrag == WAITING){\n coords = dragEnd;\n }\n else{\n coords.x = dragEnd.x - dragStart.x;\n coords.y = dragEnd.y - dragStart.y;\n }\n\n \/\/printf(\"State: %i \\t MPos: [%i, %i] \\t Coord: [%i, %i]\\n\", clickDrag, dragEnd.x, dragEnd.y, coords.x, coords.y);\n\n \/\/printf(\"HANDMOUS- wp: 0x%X \\t md: 0x%X \\t fl: 0x%X\\n\", wp, st_hook.mouseData, st_hook.flags);\n\n if (wp == WM_LBUTTONDOWN){\n dragStart = dragEnd;\n clickDrag = DRAGGING;\n printf(\"DOWN!\\n\");\n }\n if (wp == WM_LBUTTONUP){\n \/\/takeScreenShotAndClipTo(dragStart, dragEnd);\n clickDrag = NOTNOW;\n printf(\"UP!\\n\");\n SetCursor(dfltCursor);\n }\n }\n }\n else{\n return CallNextHookEx(mouhook, code, wp, lp);\n }\n }\n\n LRESULT CALLBACK handlekeys(int code, WPARAM wp, LPARAM lp){\n if (code == HC_ACTION && (wp == WM_SYSKEYUP || wp == WM_KEYUP)){\n char tmp[0xFF] = {0};\n std::string str;\n DWORD msg = 1;\n KBDLLHOOKSTRUCT st_hook = *((KBDLLHOOKSTRUCT*)lp);\n msg += (st_hook.scanCode << 16);\n msg += (st_hook.flags << 24);\n GetKeyNameText(msg, tmp, 0xFF);\n str = std::string(tmp);\n if( keyspressed[str] == 2 )\n keyspressed[str] = 3;\n else\n keyspressed[str] = 0;\n \/\/fprintf(out, \"%s\\n\", str.c_str());\n\n printf(\"%s up\\n\", str.c_str());\n }\n else if (code == HC_ACTION && (wp == WM_SYSKEYDOWN || wp == WM_KEYDOWN)) {\n char tmp[0xFF] = {0};\n std::string str;\n DWORD msg = 1;\n KBDLLHOOKSTRUCT st_hook = *((KBDLLHOOKSTRUCT*)lp);\n msg += (st_hook.scanCode << 16);\n msg += (st_hook.flags << 24);\n GetKeyNameText(msg, tmp, 0xFF);\n str = std::string(tmp);\n if( keyspressed[str] == 0 )\n keyspressed[str] = 2;\n else\n keyspressed[str] = 1;\n\n printf(\"%s down\\n\", str.c_str());\n }\n CheckKeys();\n\n return CallNextHookEx(kbdhook, code, wp, lp);\n }\n\n LRESULT CALLBACK windowprocedure(HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam){\n \/\/printf(\"FISH!\");\n\n printf(\"WINDPROC- wp: 0x%X \\t lp: 0x%X\\n\", wparam, lparam);\n\n switch (msg){\n case WM_CREATE:\n \/\/printf(\"FISH!\");\n break;\n case ICON_MESSAGE:\n switch(lparam){\n case WM_LBUTTONDBLCLK:\n MessageBox(NULL, \"Tray icon double clicked!\", \"clicked\", MB_OK);\n break;\n case WM_LBUTTONUP:\n MessageBox(NULL, \"Tray icon clicked!\", \"clicked\", MB_OK);\n break;\n default:\n return DefWindowProc(hwnd, msg, wparam, lparam);\n };\n break;\n case WM_CLOSE: case WM_DESTROY:\n running = false;\n break;\n default:\n return DefWindowProc(hwnd, msg, wparam, lparam);\n };\n return 0;\n }\n\n std::string Timestamp() {\n time_t rawtime;\n struct tm * timeinfo;\n time ( &rawtime );\n timeinfo = localtime ( &rawtime );\n char str[64];\n snprintf(str, 64, \"ss at %s\", asctime(timeinfo));\n int i = 0;\n while (str[i]){\n i++;\n if (str[i] == ' '){\n str[i] = '_'; }\n }\n std::string ToReturn(str);\n return ToReturn;\n }\n\n void CheckKeys(){\n if( ShortcutDesk.IsHit() ){\n WHFF whff(\"\");\n Bitmap mb = GetWindow(GetDesktopWindow());\n void* data = mb.ReadPNG();\n whff.Upload( Timestamp(), data, mb.PNGLen(), GetMimeFromExt(\"png\"));\n SetClipboard( whff.GetLastUpload() );\n }\n\n if (ShortcutWin.IsHit()) {\n WHFF whff(\"\");\n Bitmap mb = GetWindow(GetForegroundWindow());\n void* data = mb.ReadPNG();\n whff.Upload( Timestamp(), data, mb.PNGLen(), GetMimeFromExt(\"png\"));\n SetClipboard( whff.GetLastUpload() );\n }\n\n if (ShortcutCrop.IsHit()) {\n printf(\"hi\\n\");\n clickDrag = WAITING;\n SetCursor(dragCursor);\n }\n if (ShortcutClip.IsHit()) {\n WHFF whff(\"\");\n if (!OpenClipboard(NULL))\n return;\n HANDLE hClipboardData = GetClipboardData(CF_TEXT);\n char *pchData = (char*)GlobalLock(hClipboardData);\n void* data = (void*)pchData;\n printf(\"%s\\n\", pchData);\n whff.Upload( Timestamp()+\".txt\", data, strlen(pchData), GetMimeFromExt(\"txt\"));\n GlobalUnlock(hClipboardData);\n CloseClipboard();\n SetClipboard( whff.GetLastUpload() );\n }\n if (ShortcutQuit.IsHit()) {\n PostMessage( hwnd, WM_CLOSE, 0, 0 );\n }\n }\n\n void GUIThread( void* ){\n while( running ){\n Sleep(1000);\n nid.hIcon = IconA;\n Shell_NotifyIcon(NIM_MODIFY, &nid);\n Sleep(1000);\n nid.hIcon = IconB;\n Shell_NotifyIcon(NIM_MODIFY, &nid);\n }\n }\n\n static int SetShortcut( Shortcut* s, const char* value ){\n if( s->IsValid() ){\n s->Set( value );\n }\n return 1;\n }\n\n void ReadConf( std::string fname ){\n size_t len;\n char* d = (char*)read_file_to_buffer( fname, len );\n if( d == 0 )\n return;\n printf(\"Using non-standard configuration\\n\");\n d = (char*)realloc( d, len+1 );\n d[len] = 0;\n std::string buff = d;\n free( d );\n\n Lua L( buff.c_str(), \"Configuration\", 0 );\n L.funcreg<int, Shortcut*, const char*, SetShortcut >(\"shortcut\");\n L.set(\"SHORTCUT_WIN\", &ShortcutWin);\n L.set(\"SHORTCUT_DESK\", &ShortcutDesk);\n L.set(\"SHORTCUT_CROP\", &ShortcutCrop);\n L.set(\"SHORTCUT_CLIP\", &ShortcutClip);\n L.set(\"SHORTCUT_QUIT\", &ShortcutQuit);\n\n L.run();\n }\n}\n\nusing namespace FrogLies;\n\nint WINAPI WinMain(HINSTANCE thisinstance, HINSTANCE previnstance, LPSTR cmdline, int ncmdshow){\n\n\n ReadConf( \"conf.cfg\" );\n\n\tHWND\t\tfgwindow = GetForegroundWindow(); \/* Current foreground window *\/\n\tMSG\t\t msg;\n\tWNDCLASSEX\twindowclass;\n\tHINSTANCE\tmodulehandle;\n\n\twindowclass.hInstance = thisinstance;\n\twindowclass.lpszClassName = CLASSNAME;\n\twindowclass.lpfnWndProc = windowprocedure;\n\twindowclass.style = CS_DBLCLKS;\n\twindowclass.cbSize = sizeof(WNDCLASSEX);\n\twindowclass.hIcon = LoadIcon(NULL, IDI_APPLICATION);\n\twindowclass.hIconSm = LoadIcon(NULL, IDI_APPLICATION);\n\twindowclass.hCursor = LoadCursor(NULL, IDC_ARROW);\n\twindowclass.lpszMenuName = NULL;\n\twindowclass.cbClsExtra = 0;\n\twindowclass.cbWndExtra = 0;\n\twindowclass.hbrBackground = (HBRUSH)COLOR_BACKGROUND;\n\n\tif (!(RegisterClassEx(&windowclass))){ return 1; }\n\n\thwnd = CreateWindowEx(0, CLASSNAME, WINDOWTITLE, WS_OVERLAPPEDWINDOW,\n CW_USEDEFAULT, CW_USEDEFAULT, 640, 480, HWND_DESKTOP, NULL,\n thisinstance, NULL);\n\n\tif (!(hwnd)){ return 1; }\n\n ShowWindow(hwnd, SW_HIDE);\n\tUpdateWindow(hwnd);\n\tSetForegroundWindow(fgwindow); \/* Give focus to the previous fg window *\/\n\n dragCursor = LoadCursor(thisinstance, IDC_CROSS);\n dfltCursor = GetCursor();\n\n \/\/#define BEGIN_IN_DRAGMODE\n #ifdef BEGIN_IN_DRAGMODE\n SetCursor(dragCursor);\n clickDrag = WAITING;\n #endif\n\n IconA = (HICON) LoadImage( thisinstance, \"img\/icona.ico\", IMAGE_ICON, 32, 32, LR_LOADFROMFILE );\n IconB = (HICON) LoadImage( thisinstance, \"img\/iconb.ico\", IMAGE_ICON, 32, 32, LR_LOADFROMFILE );\n\n\n nid.cbSize = sizeof(NOTIFYICONDATA);\n nid.uID = 100;\n nid.hWnd = hwnd;\n \/\/nid.uVersion = NOTIFYICON_VERSION;\n nid.uCallbackMessage = ICON_MESSAGE;\n nid.hIcon = IconB; \/\/= LoadIcon(NULL, IDI_APPLICATION);\n snprintf(nid.szTip, 64, \"Icon\");\n nid.uFlags = NIF_MESSAGE | NIF_ICON | NIF_TIP;\n\n Shell_NotifyIcon(NIM_ADD, &nid);\n\n modulehandle = GetModuleHandle(NULL);\n\tkbdhook = SetWindowsHookEx(WH_KEYBOARD_LL, (HOOKPROC)handlekeys, modulehandle, 0);\n\tmouhook = SetWindowsHookEx(WH_MOUSE_LL, (HOOKPROC)handlemouse, modulehandle, 0);\n\n running = true;\n\n _beginthread( GUIThread, 1000, NULL );\n \/\/GUIThread(0);\n\n\twhile (running) {\n\t\tif (!GetMessage(&msg, NULL, 0, 0))\n\t\t\tbreak;\n\t\tTranslateMessage(&msg);\n\t\tDispatchMessage(&msg);\n\t}\n\n Shell_NotifyIcon(NIM_DELETE, &nid);\n\n\treturn 0;\n}\n<|endoftext|>"} {"text":"<commit_before>d35a0c0f-2747-11e6-87e2-e0f84713e7b8<commit_msg>The previous fix has been fixed<commit_after>d366d97a-2747-11e6-b11e-e0f84713e7b8<|endoftext|>"} {"text":"<commit_before>2260d74c-2e3a-11e5-b8c8-c03896053bdd<commit_msg>226c4b18-2e3a-11e5-ac20-c03896053bdd<commit_after>226c4b18-2e3a-11e5-ac20-c03896053bdd<|endoftext|>"} {"text":"<commit_before>856279a2-2d15-11e5-af21-0401358ea401<commit_msg>856279a3-2d15-11e5-af21-0401358ea401<commit_after>856279a3-2d15-11e5-af21-0401358ea401<|endoftext|>"} {"text":"<commit_before>8fd048ff-2d14-11e5-af21-0401358ea401<commit_msg>8fd04900-2d14-11e5-af21-0401358ea401<commit_after>8fd04900-2d14-11e5-af21-0401358ea401<|endoftext|>"} {"text":"<commit_before>dfffaeb8-2e4e-11e5-89bb-28cfe91dbc4b<commit_msg>e0066bc2-2e4e-11e5-8b5d-28cfe91dbc4b<commit_after>e0066bc2-2e4e-11e5-8b5d-28cfe91dbc4b<|endoftext|>"} {"text":"<commit_before>9101ad84-2d14-11e5-af21-0401358ea401<commit_msg>9101ad85-2d14-11e5-af21-0401358ea401<commit_after>9101ad85-2d14-11e5-af21-0401358ea401<|endoftext|>"} {"text":"<commit_before>5c794280-2d3f-11e5-8235-c82a142b6f9b<commit_msg>5cfee50c-2d3f-11e5-a824-c82a142b6f9b<commit_after>5cfee50c-2d3f-11e5-a824-c82a142b6f9b<|endoftext|>"} {"text":"<commit_before>0f2a29b5-2748-11e6-95f2-e0f84713e7b8<commit_msg>bug fix<commit_after>0f66f3ee-2748-11e6-8f6c-e0f84713e7b8<|endoftext|>"} {"text":"<commit_before>ec550570-313a-11e5-b8a4-3c15c2e10482<commit_msg>ec5af642-313a-11e5-b899-3c15c2e10482<commit_after>ec5af642-313a-11e5-b899-3c15c2e10482<|endoftext|>"} {"text":"<commit_before>ee2e09f4-585a-11e5-a8f0-6c40088e03e4<commit_msg>ee345ea8-585a-11e5-81be-6c40088e03e4<commit_after>ee345ea8-585a-11e5-81be-6c40088e03e4<|endoftext|>"} {"text":"<commit_before>3db3419c-2e3a-11e5-847e-c03896053bdd<commit_msg>3dc1c32c-2e3a-11e5-a07c-c03896053bdd<commit_after>3dc1c32c-2e3a-11e5-a07c-c03896053bdd<|endoftext|>"} {"text":"<commit_before>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ File Header Place Holder\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\n#include \"ANLtoCPP\/ANLtoC.h\"\n#include <iostream>\n#include <string>\n#include <stdio.h>\n#include <memory>\n#include <ctime>\n#include \"Output.h\"\n\n#define ANL_IMPLEMENTATION\n\/\/ ANL is currently in a transition to a single file format, thus\n\/\/ we need to IMPLEMENT_STB even though we don't use it.\n#define IMPLEMENT_STB\n#include <accidental-noise-library\/anl.h>\n#include <accidental-noise-library\/lang\/NoiseParser.h>\n\nstd::string GetFileName(std::string file)\n{\n\tstd::string::size_type AltSeperator = file.find_last_of('\/');\n\tstd::string::size_type Seperator = file.find_last_of('\\\\');\n\n\tif ((Seperator < AltSeperator && AltSeperator != std::string::npos) || Seperator == std::string::npos)\n\t\tSeperator = AltSeperator;\n\n\tif (Seperator == std::string::npos)\n\t\treturn file;\n\n\treturn file.substr(Seperator + 1);\n}\n\nstd::string GetDirectory(std::string file)\n{\n\tstd::string::size_type AltSeperator = file.find_last_of('\/');\n\tstd::string::size_type Seperator = file.find_last_of('\\\\');\n\n\tif ((Seperator < AltSeperator && AltSeperator != std::string::npos) || Seperator == std::string::npos)\n\t\tSeperator = AltSeperator;\n\n\tif (Seperator == std::string::npos)\n\t\treturn \"\";\n\n\treturn file.substr(0, Seperator);\n}\n\nint main(int argc, char* argv[])\n{\n\tif (argc < 2)\n\t{\n\t\tstd::cerr << \"Missing arguments.\" << std::endl;\n\t\tstd::cerr << \"USAGE: ANLTranspiler.exe anlLangSourceFile.anl output.cpp output.h\" << std::endl;\n\t\tstd::cerr << \" The anlLangSourceFile.anl will be parsed and converted to an internal\" << std::endl;\n\t\tstd::cerr << \" anl::CKernel which will then be converted to cplusplus and output as\" << std::endl;\n\t\tstd::cerr << \" the provided source and header files\" << std::endl;\n\t\treturn 0;\n\t}\n\n\tstd::string InputFileName = argv[1];\n\tstd::string OutputSourceFileName;\n\tstd::string OutputHeaderFileName;\n\tif (argc > 2)\n\t\tOutputSourceFileName = argv[2];\n\tif (argc > 3)\n\t\tOutputHeaderFileName = argv[3];\n\n\tstd::string HeaderFileRelativeToSource; \/\/ ie with any common directory information stripped\n\t{\n\t\tstd::string HeaderDir = GetDirectory(OutputHeaderFileName);\n\t\tstd::string HeaderFile = GetFileName(OutputHeaderFileName);\n\t\tstd::string SourceDir = GetDirectory(OutputSourceFileName);\n\t\tstd::string SourceFile = GetFileName(OutputSourceFileName);\n\n\t\tstd::size_t DivergentIndex = 0;\n\t\tfor (std::size_t i = 0; i < SourceDir.size() && i < HeaderDir.size(); ++i)\n\t\t{\n\t\t\tif (SourceDir[i] == HeaderDir[i])\n\t\t\t\tDivergentIndex++;\n\t\t\telse\n\t\t\t\tbreak;\n\t\t}\n\n\t\tstd::string Dir = HeaderDir.substr(DivergentIndex);\n\t\tstd::cerr << \"HeaderFile: \" << OutputHeaderFileName << std::endl;\n\t\tstd::cerr << \"SourceFile: \" << OutputSourceFileName << std::endl;\n\t\tif (Dir.size() > 0)\n\t\t\tHeaderFileRelativeToSource = Dir + \"\/\" + HeaderFile;\n\t\telse\n\t\t\tHeaderFileRelativeToSource = HeaderFile;\n\t}\n\n\tFILE* f = nullptr;\n\tif (0 != fopen_s(&f, InputFileName.c_str(), \"r\")) {\n\t\tstd::cerr << \"Unable to open file: \" << InputFileName << std::endl;\n\t\treturn -9;\n\t}\n\tif (fseek(f, 0, SEEK_END) != 0) {\n\t\tstd::cerr << \"Seek Error for file: \" << InputFileName << std::endl;\n\t\treturn -10;\n\t}\n\n\tlong FileLength = ftell(f);\n\n\tif (fseek(f, 0, SEEK_SET) != 0) {\n\t\tstd::cerr << \"Seek Error for file: \" << InputFileName << std::endl;\n\t\treturn -10;\n\t}\n\n\tstd::string FullText;\n\t{\n\t\tauto Buffer = std::make_unique<uint8_t[]>(FileLength+1);\n\t\tsize_t AmountRead = fread(Buffer.get(), 1, FileLength, f);\n\t\tif (AmountRead != FileLength && feof(f) == 0) {\n\t\t\tstd::cerr << \"Read Error for file: \" << InputFileName << std::endl;\n\t\t\treturn -10;\n\t\t}\n\t\tfclose(f);\n\t\tBuffer[AmountRead] = 0;\n\t\tFullText = (char*)Buffer.get();\n\t}\n\n\tstd::unique_ptr<anl::lang::NoiseParser> NoiseParser;\n\tNoiseParser = std::make_unique<anl::lang::NoiseParser>(FullText);\n\n\tbool success = NoiseParser->Parse();\n\tif (!success)\n\t{\n\t\tauto ErrorMessages = NoiseParser->FormErrorMsgs();\n\t\tstd::cerr << \"Error parsing TerrainV noise file: \" << InputFileName\n\t\t\t<< \"\\nErrors:\\n\" << ErrorMessages\n\t\t\t<< \"\\n\\n Contents of \\\"\" << InputFileName\n\t\t\t<< \"\\\"\\n\" << FullText << std::endl;\n\t\treturn -30;\n\t}\n\telse\n\t{\n\t\tstd::string Code;\n\t\tstd::string HeaderFile;\n\t\tstd::string Struct;\n\t\tANLtoC::KernelToC(NoiseParser->GetKernel(), NoiseParser->GetParseResult(), Code, Struct);\n\t\tOutputFullCppFile(Code, Struct, HeaderFileRelativeToSource, Code, HeaderFile);\n\t\tstd::string header = \"\/\/ Generated file - Do not edit. Generated by ANLTranspiler at \";\n\t\ttime_t CurrentTime = time(0);\n\t\tchar TimeBuffer[100];\n\t\tctime_s(TimeBuffer, 100, &CurrentTime);\n\t\theader.append(TimeBuffer);\n\t\theader.append(\"\\n\");\n\t\tCode.insert(0, header);\n\t\tHeaderFile.insert(0, header);\n\t\t\n\t\tif(OutputSourceFileName != \"\")\n\t\t{\n\t\t\tFILE* f = nullptr;\n\t\t\tif (0 != fopen_s(&f, OutputSourceFileName.c_str(), \"w\")) {\n\t\t\t\tstd::cerr << \"Unable to open file: \" << OutputSourceFileName << std::endl;\n\t\t\t\treturn -9;\n\t\t\t}\n\n\t\t\tsize_t AmountWritten = fwrite(Code.c_str(), 1, Code.size(), f);\n\t\t\tif (AmountWritten != Code.size())\n\t\t\t{\n\t\t\t\tstd::cerr << \"Write failed to file: \" << OutputSourceFileName << std::endl;\n\t\t\t}\n\n\t\t\tfclose(f);\n\t\t}\n\n\t\tif (OutputHeaderFileName != \"\")\n\t\t{\n\t\t\tFILE* f = nullptr;\n\t\t\tif (0 != fopen_s(&f, OutputHeaderFileName.c_str(), \"w\")) {\n\t\t\t\tstd::cerr << \"Unable to open file: \" << OutputHeaderFileName << std::endl;\n\t\t\t\treturn -9;\n\t\t\t}\n\n\t\t\tsize_t AmountWritten = fwrite(HeaderFile.c_str(), 1, HeaderFile.size(), f);\n\t\t\tif (AmountWritten != HeaderFile.size())\n\t\t\t{\n\t\t\t\tstd::cerr << \"Write failed to file: \" << OutputHeaderFileName << std::endl;\n\t\t\t}\n\n\t\t\tfclose(f);\n\t\t}\n\n\t\tanl::CNoiseExecutor vm(NoiseParser->GetKernel());\n\t\tdouble VMResult = vm.evaluateScalar(0.5, 0.5, NoiseParser->GetParseResult());\n\t}\n\n\treturn 0;\n}\n<commit_msg>Removed necessary output to stderr<commit_after>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ File Header Place Holder\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\n#include \"ANLtoCPP\/ANLtoC.h\"\n#include <iostream>\n#include <string>\n#include <stdio.h>\n#include <memory>\n#include <ctime>\n#include \"Output.h\"\n\n#define ANL_IMPLEMENTATION\n\/\/ ANL is currently in a transition to a single file format, thus\n\/\/ we need to IMPLEMENT_STB even though we don't use it.\n#define IMPLEMENT_STB\n#include <accidental-noise-library\/anl.h>\n#include <accidental-noise-library\/lang\/NoiseParser.h>\n\nstd::string GetFileName(std::string file)\n{\n\tstd::string::size_type AltSeperator = file.find_last_of('\/');\n\tstd::string::size_type Seperator = file.find_last_of('\\\\');\n\n\tif ((Seperator < AltSeperator && AltSeperator != std::string::npos) || Seperator == std::string::npos)\n\t\tSeperator = AltSeperator;\n\n\tif (Seperator == std::string::npos)\n\t\treturn file;\n\n\treturn file.substr(Seperator + 1);\n}\n\nstd::string GetDirectory(std::string file)\n{\n\tstd::string::size_type AltSeperator = file.find_last_of('\/');\n\tstd::string::size_type Seperator = file.find_last_of('\\\\');\n\n\tif ((Seperator < AltSeperator && AltSeperator != std::string::npos) || Seperator == std::string::npos)\n\t\tSeperator = AltSeperator;\n\n\tif (Seperator == std::string::npos)\n\t\treturn \"\";\n\n\treturn file.substr(0, Seperator);\n}\n\nint main(int argc, char* argv[])\n{\n\tif (argc < 2)\n\t{\n\t\tstd::cerr << \"Missing arguments.\" << std::endl;\n\t\tstd::cerr << \"USAGE: ANLTranspiler.exe anlLangSourceFile.anl output.cpp output.h\" << std::endl;\n\t\tstd::cerr << \" The anlLangSourceFile.anl will be parsed and converted to an internal\" << std::endl;\n\t\tstd::cerr << \" anl::CKernel which will then be converted to cplusplus and output as\" << std::endl;\n\t\tstd::cerr << \" the provided source and header files\" << std::endl;\n\t\treturn 0;\n\t}\n\n\tstd::string InputFileName = argv[1];\n\tstd::string OutputSourceFileName;\n\tstd::string OutputHeaderFileName;\n\tif (argc > 2)\n\t\tOutputSourceFileName = argv[2];\n\tif (argc > 3)\n\t\tOutputHeaderFileName = argv[3];\n\n\tstd::string HeaderFileRelativeToSource; \/\/ ie with any common directory information stripped\n\t{\n\t\tstd::string HeaderDir = GetDirectory(OutputHeaderFileName);\n\t\tstd::string HeaderFile = GetFileName(OutputHeaderFileName);\n\t\tstd::string SourceDir = GetDirectory(OutputSourceFileName);\n\t\tstd::string SourceFile = GetFileName(OutputSourceFileName);\n\n\t\tstd::size_t DivergentIndex = 0;\n\t\tfor (std::size_t i = 0; i < SourceDir.size() && i < HeaderDir.size(); ++i)\n\t\t{\n\t\t\tif (SourceDir[i] == HeaderDir[i])\n\t\t\t\tDivergentIndex++;\n\t\t\telse\n\t\t\t\tbreak;\n\t\t}\n\n\t\tstd::string Dir = HeaderDir.substr(DivergentIndex);\n\n\t\tif (Dir.size() > 0)\n\t\t\tHeaderFileRelativeToSource = Dir + \"\/\" + HeaderFile;\n\t\telse\n\t\t\tHeaderFileRelativeToSource = HeaderFile;\n\t}\n\n\tFILE* f = nullptr;\n\tif (0 != fopen_s(&f, InputFileName.c_str(), \"r\")) {\n\t\tstd::cerr << \"Unable to open file: \" << InputFileName << std::endl;\n\t\treturn -9;\n\t}\n\tif (fseek(f, 0, SEEK_END) != 0) {\n\t\tstd::cerr << \"Seek Error for file: \" << InputFileName << std::endl;\n\t\treturn -10;\n\t}\n\n\tlong FileLength = ftell(f);\n\n\tif (fseek(f, 0, SEEK_SET) != 0) {\n\t\tstd::cerr << \"Seek Error for file: \" << InputFileName << std::endl;\n\t\treturn -10;\n\t}\n\n\tstd::string FullText;\n\t{\n\t\tauto Buffer = std::make_unique<uint8_t[]>(FileLength+1);\n\t\tsize_t AmountRead = fread(Buffer.get(), 1, FileLength, f);\n\t\tif (AmountRead != FileLength && feof(f) == 0) {\n\t\t\tstd::cerr << \"Read Error for file: \" << InputFileName << std::endl;\n\t\t\treturn -10;\n\t\t}\n\t\tfclose(f);\n\t\tBuffer[AmountRead] = 0;\n\t\tFullText = (char*)Buffer.get();\n\t}\n\n\tstd::unique_ptr<anl::lang::NoiseParser> NoiseParser;\n\tNoiseParser = std::make_unique<anl::lang::NoiseParser>(FullText);\n\n\tbool success = NoiseParser->Parse();\n\tif (!success)\n\t{\n\t\tauto ErrorMessages = NoiseParser->FormErrorMsgs();\n\t\tstd::cerr << \"Error parsing TerrainV noise file: \" << InputFileName\n\t\t\t<< \"\\nErrors:\\n\" << ErrorMessages\n\t\t\t<< \"\\n\\n Contents of \\\"\" << InputFileName\n\t\t\t<< \"\\\"\\n\" << FullText << std::endl;\n\t\treturn -30;\n\t}\n\telse\n\t{\n\t\tstd::string Code;\n\t\tstd::string HeaderFile;\n\t\tstd::string Struct;\n\t\tANLtoC::KernelToC(NoiseParser->GetKernel(), NoiseParser->GetParseResult(), Code, Struct);\n\t\tOutputFullCppFile(Code, Struct, HeaderFileRelativeToSource, Code, HeaderFile);\n\t\tstd::string header = \"\/\/ Generated file - Do not edit. Generated by ANLTranspiler at \";\n\t\ttime_t CurrentTime = time(0);\n\t\tchar TimeBuffer[100];\n\t\tctime_s(TimeBuffer, 100, &CurrentTime);\n\t\theader.append(TimeBuffer);\n\t\theader.append(\"\\n\");\n\t\tCode.insert(0, header);\n\t\tHeaderFile.insert(0, header);\n\t\t\n\t\tif(OutputSourceFileName != \"\")\n\t\t{\n\t\t\tFILE* f = nullptr;\n\t\t\tif (0 != fopen_s(&f, OutputSourceFileName.c_str(), \"w\")) {\n\t\t\t\tstd::cerr << \"Unable to open file: \" << OutputSourceFileName << std::endl;\n\t\t\t\treturn -9;\n\t\t\t}\n\n\t\t\tsize_t AmountWritten = fwrite(Code.c_str(), 1, Code.size(), f);\n\t\t\tif (AmountWritten != Code.size())\n\t\t\t{\n\t\t\t\tstd::cerr << \"Write failed to file: \" << OutputSourceFileName << std::endl;\n\t\t\t}\n\n\t\t\tfclose(f);\n\t\t}\n\n\t\tif (OutputHeaderFileName != \"\")\n\t\t{\n\t\t\tFILE* f = nullptr;\n\t\t\tif (0 != fopen_s(&f, OutputHeaderFileName.c_str(), \"w\")) {\n\t\t\t\tstd::cerr << \"Unable to open file: \" << OutputHeaderFileName << std::endl;\n\t\t\t\treturn -9;\n\t\t\t}\n\n\t\t\tsize_t AmountWritten = fwrite(HeaderFile.c_str(), 1, HeaderFile.size(), f);\n\t\t\tif (AmountWritten != HeaderFile.size())\n\t\t\t{\n\t\t\t\tstd::cerr << \"Write failed to file: \" << OutputHeaderFileName << std::endl;\n\t\t\t}\n\n\t\t\tfclose(f);\n\t\t}\n\n\t\tanl::CNoiseExecutor vm(NoiseParser->GetKernel());\n\t\tdouble VMResult = vm.evaluateScalar(0.5, 0.5, NoiseParser->GetParseResult());\n\t}\n\n\treturn 0;\n}\n<|endoftext|>"} {"text":"<commit_before>d491915c-2747-11e6-b97a-e0f84713e7b8<commit_msg>Does anyone even read these anymore???<commit_after>d4b7bef3-2747-11e6-b029-e0f84713e7b8<|endoftext|>"} {"text":"<commit_before>\/*\n* HMAC\n* (C) 1999-2007,2014 Jack Lloyd\n* 2007 Yves Jerschow\n*\n* Botan is released under the Simplified BSD License (see license.txt)\n*\/\n\n#include <botan\/hmac.h>\n\nnamespace Botan {\n\n\/*\n* Update a HMAC Calculation\n*\/\nvoid HMAC::add_data(const uint8_t input[], size_t length)\n {\n verify_key_set(m_ikey.empty() == false);\n m_hash->update(input, length);\n }\n\n\/*\n* Finalize a HMAC Calculation\n*\/\nvoid HMAC::final_result(uint8_t mac[])\n {\n verify_key_set(m_okey.empty() == false);\n m_hash->final(mac);\n m_hash->update(m_okey);\n m_hash->update(mac, m_hash_output_length);\n m_hash->final(mac);\n m_hash->update(m_ikey);\n }\n\nKey_Length_Specification HMAC::key_spec() const\n {\n \/\/ Support very long lengths for things like PBKDF2 and the TLS PRF\n return Key_Length_Specification(0, 4096);\n }\n\nsize_t HMAC::output_length() const\n {\n return m_hash_output_length;\n }\n\n\/*\n* HMAC Key Schedule\n*\/\nvoid HMAC::key_schedule(const uint8_t key[], size_t length)\n {\n const uint8_t ipad = 0x36;\n const uint8_t opad = 0x5C;\n\n m_hash->clear();\n\n m_ikey.resize(m_hash_block_size);\n set_mem(m_ikey.data(), m_hash_block_size, ipad);\n\n m_okey.resize(m_hash_block_size);\n set_mem(m_okey.data(), m_hash_block_size, opad);\n\n if(length > m_hash_block_size)\n {\n m_hash->update(key, length);\n m_hash->final(m_ikey.data());\n\n xor_buf(m_okey.data(), m_ikey.data(), m_hash_output_length);\n\n for(size_t i = 0; i != m_hash_output_length; ++i)\n {\n m_ikey[i] ^= ipad;\n }\n }\n else\n {\n xor_buf(m_ikey, key, length);\n xor_buf(m_okey, key, length);\n }\n\n m_hash->update(m_ikey);\n }\n\n\/*\n* Clear memory of sensitive data\n*\/\nvoid HMAC::clear()\n {\n m_hash->clear();\n zap(m_ikey);\n zap(m_okey);\n }\n\n\/*\n* Return the name of this type\n*\/\nstd::string HMAC::name() const\n {\n return \"HMAC(\" + m_hash->name() + \")\";\n }\n\n\/*\n* Return a clone of this object\n*\/\nMessageAuthenticationCode* HMAC::clone() const\n {\n return new HMAC(m_hash->clone());\n }\n\n\/*\n* HMAC Constructor\n*\/\nHMAC::HMAC(HashFunction* hash) :\n m_hash(hash),\n m_hash_output_length(m_hash->output_length()),\n m_hash_block_size(m_hash->hash_block_size())\n {\n BOTAN_ARG_CHECK(m_hash_block_size >= m_hash_output_length,\n \"HMAC is not compatible with this hash function\");\n }\n\n}\n<commit_msg>Attempt to avoid leaking the HMAC key length<commit_after>\/*\n* HMAC\n* (C) 1999-2007,2014,2020 Jack Lloyd\n* 2007 Yves Jerschow\n*\n* Botan is released under the Simplified BSD License (see license.txt)\n*\/\n\n#include <botan\/hmac.h>\n#include <botan\/internal\/ct_utils.h>\n\nnamespace Botan {\n\n\/*\n* Update a HMAC Calculation\n*\/\nvoid HMAC::add_data(const uint8_t input[], size_t length)\n {\n verify_key_set(m_ikey.empty() == false);\n m_hash->update(input, length);\n }\n\n\/*\n* Finalize a HMAC Calculation\n*\/\nvoid HMAC::final_result(uint8_t mac[])\n {\n verify_key_set(m_okey.empty() == false);\n m_hash->final(mac);\n m_hash->update(m_okey);\n m_hash->update(mac, m_hash_output_length);\n m_hash->final(mac);\n m_hash->update(m_ikey);\n }\n\nKey_Length_Specification HMAC::key_spec() const\n {\n \/\/ Support very long lengths for things like PBKDF2 and the TLS PRF\n return Key_Length_Specification(0, 4096);\n }\n\nsize_t HMAC::output_length() const\n {\n return m_hash_output_length;\n }\n\n\/*\n* HMAC Key Schedule\n*\/\nvoid HMAC::key_schedule(const uint8_t key[], size_t length)\n {\n const uint8_t ipad = 0x36;\n const uint8_t opad = 0x5C;\n\n m_hash->clear();\n\n m_ikey.resize(m_hash_block_size);\n m_okey.resize(m_hash_block_size);\n\n clear_mem(m_ikey.data(), m_ikey.size());\n clear_mem(m_okey.data(), m_okey.size());\n\n \/*\n * Sometimes the HMAC key length itself is sensitive, as with PBKDF2 where it\n * reveals the length of the passphrase. Make some attempt to hide this to\n * side channels. Clearly if the secret is longer than the block size then the\n * branch to hash first reveals that. In addition, counting the number of\n * compression functions executed reveals the size at the granularity of the\n * hash function's block size.\n *\n * The greater concern is for smaller keys; being able to detect when a\n * passphrase is say 4 bytes may assist choosing weaker targets. Even though\n * the loop bounds are constant, we can only actually read key[0..length] so\n * it doesn't seem possible to make this computation truly constant time.\n *\n * We don't mind leaking if the length is exactly zero since that's\n * trivial to simply check.\n *\/\n\n if(length > m_hash_block_size)\n {\n m_hash->update(key, length);\n m_hash->final(m_ikey.data());\n }\n else if(length > 0)\n {\n for(size_t i = 0, i_mod_length = 0; i != m_hash_block_size; ++i)\n {\n \/*\n access key[i % length] but avoiding division due to variable\n time computation on some processors.\n *\/\n auto needs_reduction = CT::Mask<size_t>::is_lte(length, i_mod_length);\n i_mod_length = needs_reduction.select(0, i_mod_length);\n const uint8_t kb = key[i_mod_length];\n\n auto in_range = CT::Mask<size_t>::is_lt(i, length);\n m_ikey[i] = static_cast<uint8_t>(in_range.if_set_return(kb));\n i_mod_length += 1;\n }\n }\n\n for(size_t i = 0; i != m_hash_block_size; ++i)\n {\n m_ikey[i] ^= ipad;\n m_okey[i] = m_ikey[i] ^ ipad ^ opad;\n }\n\n m_hash->update(m_ikey);\n }\n\n\/*\n* Clear memory of sensitive data\n*\/\nvoid HMAC::clear()\n {\n m_hash->clear();\n zap(m_ikey);\n zap(m_okey);\n }\n\n\/*\n* Return the name of this type\n*\/\nstd::string HMAC::name() const\n {\n return \"HMAC(\" + m_hash->name() + \")\";\n }\n\n\/*\n* Return a clone of this object\n*\/\nMessageAuthenticationCode* HMAC::clone() const\n {\n return new HMAC(m_hash->clone());\n }\n\n\/*\n* HMAC Constructor\n*\/\nHMAC::HMAC(HashFunction* hash) :\n m_hash(hash),\n m_hash_output_length(m_hash->output_length()),\n m_hash_block_size(m_hash->hash_block_size())\n {\n BOTAN_ARG_CHECK(m_hash_block_size >= m_hash_output_length,\n \"HMAC is not compatible with this hash function\");\n }\n\n}\n<|endoftext|>"} {"text":"<commit_before>fdb693f8-ad5a-11e7-8a49-ac87a332f658<commit_msg>I am finally done<commit_after>fe64914c-ad5a-11e7-878a-ac87a332f658<|endoftext|>"} {"text":"<commit_before>#include <chrono>\n#include <iostream>\n#include <vector>\n#include <memory>\n#include <string>\n#include <SFML\/Graphics.hpp>\n#include \"GUI-SFML.hpp\"\n\ntypedef std::chrono::high_resolution_clock CLOCK;\n\nvoid determineFpsAndDeltaTime(sf::Text &txtStatFPS, float &dt, \n float &averageFpsTime, float &fpsInSec, int &fpsCnt, \n int &averageFpsInOneSec,\n CLOCK::time_point &timePoint1);\n\nint main()\n{\n unsigned int windowWidth{ 1280 };\n unsigned int windowHeight{ 720 };\n sf::RenderWindow window(sf::VideoMode{ windowWidth, windowHeight }, \"GUI-SFML\");\n\n sf::Font font;\n if (!font.loadFromFile(\"assets\/fonts\/LiberationSans-Regular.ttf\"))\n {\n std::cout << \"Error by loading Font\" << std::endl;\n }\n\n sf::Text txtStatFPS;\n txtStatFPS.setFont(font);\n txtStatFPS.setCharacterSize(12);\n txtStatFPS.setFillColor(sf::Color::Black);\n float dt{ 0.f };\n float averageFpsTime{ 0.f };\n float fpsInSec{ 0.f };\n int fpsCnt{ 0 };\n int averageFpsInOneSec{ 0 };\n CLOCK::time_point timePoint1{ CLOCK::now() };\n\n gsf::GUIEnvironment guiEnvironment{ window };\n gsf::TextWidget::Ptr textWidget{ \n gsf::TextWidget::create(\"IM A TEXT\\nTESTA\\nTESTB\\nTESTC\\nS\", font) };\n \/\/textWidget->centerOrigin();\n textWidget->setBackgroundColor(sf::Color{ 192, 192, 192 });\n textWidget->setCharacterSize(60);\n textWidget->setPosition(windowWidth \/ 2.f + 100.f, windowHeight \/ 2.f - 330.f);\n guiEnvironment.addWidget(std::move(textWidget));\n \n std::unique_ptr<gsf::ProgressWidget> progressWidget{ \n std::make_unique<gsf::ProgressWidget>(260, 40) };\n progressWidget->setPosition(460, 460);\n progressWidget->setProgress(50);\n progressWidget->setOnLeftClickListener([](gsf::Widget *widget, sf::Vector2f pos) \n {\n std::cout << \"Clicked Progress \\n\";\n });\n guiEnvironment.addWidget(std::move(progressWidget));\n \n std::unique_ptr<gsf::ScrollableWidget> scrollableWidget{ \n std::make_unique<gsf::ScrollableWidget>(300, 200) };\n scrollableWidget->setBackgroundColor(sf::Color{ 162, 162, 162 });\n\n std::unique_ptr<gsf::VerticalLayout> layout{ \n std::make_unique<gsf::VerticalLayout>() };\n layout->enableAutoDetermineWidth();\n layout->setOutlineThickness(8.f);\n layout->setOutlineColor(sf::Color::Yellow);\n \n for (int i{ 0 }; i != 6; i++)\n {\n \/*\n std::string textString{ \"Text Num \" + std::to_string(i) };\n std::unique_ptr<gsf::TextWidget> text{ std::make_unique<gsf::TextWidget>\n (textString, font, 40, sf::Color::White) };\n if (i % 2 == 0)\n {\n text->setBackgroundColor(sf::Color{ 192, 192, 192 });\n }\n else\n {\n text->setBackgroundColor(sf::Color{ 128, 128, 128 });\n }\n std::function<void(gsf::Widget*, sf::Vector2f)> leftClickListener = \n [] (gsf::Widget* widget, sf::Vector2f mousePos)\n {\n gsf::TextWidget *textWidget = static_cast<gsf::TextWidget*>(widget);\n std::cout << \"TextWidget: Left Mouse Button Clicked. Text: \" \n << textWidget->getText().toAnsiString() << std::endl;\n };\n text->setOnLeftClickListener(leftClickListener);\n \n layout->attachChild(std::move(text));\n *\/\n gsf::ProgressWidget::Ptr prog{ gsf::ProgressWidget::create(360.f, 40.f) };\n if (i % 2 == 0)\n {\n prog->setOutlineColor(sf::Color::Red);\n }\n else\n {\n prog->setOutlineColor(sf::Color::Blue);\n }\n layout->attachChild(std::move(prog));\n }\n\n scrollableWidget->attachChild(std::move(layout));\n\n std::unique_ptr<gsf::WindowWidget> windowWidget{ \n std::make_unique<gsf::WindowWidget>(\n scrollableWidget->getGlobalBounds().width,\n scrollableWidget->getGlobalBounds().height, L\"\", font) };\n windowWidget->setPosition(200.f , 200.f);\n \/\/windowWidget->setBackgroundColor(sf::Color::White);\n windowWidget->attachChild(std::move(scrollableWidget));\n windowWidget->setIsVisible(true);\n guiEnvironment.addWidget(std::move(windowWidget));\n \n std::unique_ptr<gsf::WindowWidget> windowWidget2{ \n std::make_unique<gsf::WindowWidget>(300.f, 360.f, L\"\", font) };\n windowWidget2->setPosition(240.f , 40.f);\n \/\/windowWidget2->setBackgroundColor(sf::Color::Red);\n \/\/windowWidget2->setTopBarFillColor(sf::Color::Green);\n \/\/windowWidget2->setCloseButtonFillColor(sf::Color::Blue);\n windowWidget2->setWindowTitle(L\"Test\");\n \/\/windowWidget2->setWindowTitleColor(sf::Color::Red);\n guiEnvironment.addWidget(std::move(windowWidget2));\n\n std::unique_ptr<gsf::WindowWidget> windowWidget3{ \n std::make_unique<gsf::WindowWidget>\n (300.f, 360.f, L\"Test Window TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT\", font) };\n windowWidget3->setPosition(300.f , 60.f);\n \/\/windowWidget3->setOutlineThickness(12.f);\n \/\/windowWidget3->setOutlineColor(sf::Color::White);\n \/\/windowWidget3->setBackgroundColor(sf::Color::Blue);\n guiEnvironment.addWidget(std::move(windowWidget3));\n \n \/\/ BUTTON TEST\n std::unique_ptr<gsf::TextButtonWidget> buttonWidget{ \n std::make_unique<gsf::TextButtonWidget>\n (200.f, 80.f, L\"CABBBBBTTTTTTTTTTTTTTTTTTTTTTClick me\", font) };\n buttonWidget->setPosition(240.f , 360.f);\n buttonWidget->setOnLeftClickListener(\n [] (gsf::Widget* widget, sf::Vector2f mousePos)\n {\n std::cout << \"Button Left Click\\n\";\n\n });\n buttonWidget->setOnRightClickListener(\n [] (gsf::Widget* widget, sf::Vector2f mousePos)\n {\n std::cout << \"Button Right Click\\n\";\n\n });\n buttonWidget->setOnMiddleClickListener(\n [] (gsf::Widget* widget, sf::Vector2f mousePos)\n {\n std::cout << \"Button Middle Click\\n\";\n\n });\n guiEnvironment.addWidget(std::move(buttonWidget));\n \n \/\/ SCROLLBAR TEST\n std::unique_ptr<gsf::ScrollableWidget> scrollableWidget3{ \n std::make_unique<gsf::ScrollableWidget>(300, 200) };\n scrollableWidget3->setPosition(820.f, 420.f);\n scrollableWidget3->setBackgroundColor(sf::Color{ 128, 128, 128 });\n\n std::unique_ptr<gsf::VerticalLayout> layout4{ \n std::make_unique<gsf::VerticalLayout>() };\n layout4->enableAutoDetermineWidth();\n layout4->setBackgroundColor(sf::Color::Cyan);\n\n for (int i{0}; i != 10; i++)\n {\n std::string textString{ \"Text Text Text Text Text Text Text Num \" \n + std::to_string(i) };\n std::unique_ptr<gsf::TextWidget> text{ \n std::make_unique<gsf::TextWidget>\n (textString, font, 40, sf::Color::White) };\n if (i % 2 == 0)\n {\n text->setBackgroundColor(sf::Color::Green);\n }\n else\n {\n text->setBackgroundColor(sf::Color::Magenta);\n }\n std::function<void(gsf::Widget*, sf::Vector2f)> leftClickListener = \n [] (gsf::Widget* widget, sf::Vector2f mousePos)\n {\n gsf::TextWidget *textWidget = static_cast<gsf::TextWidget*>(widget);\n std::cout << \"TextWidget: Left Mouse Button Clicked. Text: \" \n << textWidget->getText().toAnsiString() << std::endl;\n };\n text->setOnLeftClickListener(leftClickListener);\n \/\/text->setBackgroundColor(sf::Color::Red);\n layout4->attachChild(std::move(text));\n }\n scrollableWidget3->attachChild(std::move(layout4));\n guiEnvironment.addWidget(std::move(scrollableWidget3));\n\n std::unique_ptr<gsf::TextInputWidget> textInput1{ \n std::make_unique<gsf::TextInputWidget>(300.f, 60.f, font) };\n textInput1->setPosition(320.f, 520.f);\n textInput1->setBackgroundColor(sf::Color::White);\n textInput1->setIsHorizontalScrollEnabled(false);\n textInput1->setText(L\"Test Text HHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHH :)\");\n textInput1->setWhiteListChars(L\"0123456789\");\n guiEnvironment.addWidget(std::move(textInput1));\n \n \/\/ Console Widget\n std::unique_ptr<gsf::ConsoleWidget> console1{ \n std::make_unique<gsf::ConsoleWidget>(500.f, 200.f, font) };\n console1->setPosition(700.f, 200.f);\n console1->setOnCommandEnteredListener(\n [] (gsf::Widget *widget, std::wstring inputText)\n {\n std::wcout << \"CommandEnteredListener command: \" << inputText \n << std::endl;\n gsf::ConsoleWidget *consoleWidget{ \n static_cast<gsf::ConsoleWidget*>(widget) };\n consoleWidget->addTextToDisplay(L\"OK\");\n }\n );\n guiEnvironment.addWidget(std::move(console1));\n \n \/\/ CheckBoxWidget\n std::unique_ptr<gsf::CheckBoxWidget> checkBox1{ \n std::make_unique<gsf::CheckBoxWidget>(60, 60.f) };\n checkBox1->setPosition(10.f, 620.f);\n guiEnvironment.addWidget(std::move(checkBox1));\n \n \/\/ ComboBoxWidget\n gsf::ComboBoxWidget::Ptr comboBox{ \n gsf::ComboBoxWidget::create(80.f, 20.f, font) };\n comboBox->setPosition(120.f, 620.f);\n comboBox->addElement(L\"Entry One\");\n comboBox->addElement(L\"Entry Two\");\n comboBox->addElement(L\"Entry Three\");\n comboBox->addElement(L\"Entry Four\");\n comboBox->addElement(L\"Entry Five\");\n comboBox->addElement(L\"Entry LAST\");\n guiEnvironment.addWidget(std::move(comboBox));\n \n \/\/ ListBoxWidget\n gsf::ListBoxWidget::Ptr listBox{ \n gsf::ListBoxWidget::create(80.f, 100.f, font) };\n listBox->setOnElementSelectedListener([](gsf::Widget* widget, int index)\n {\n gsf::ListBoxWidget *widgetList{ static_cast<gsf::ListBoxWidget*>(widget) };\n std::wstring content{ widgetList->getElement(index) };\n std::cout << \"Index selected: \" << index << std::endl;\n });\n listBox->setPosition(320.f, 590.f);\n listBox->addElement(L\"Entry One\");\n listBox->addElement(L\"Entry Two\");\n listBox->addElement(L\"Entry Three\");\n listBox->addElement(L\"Entry Four\");\n listBox->addElement(L\"Entry Five\");\n listBox->addElement(L\"Entry Six\");\n listBox->addElement(L\"Entry Seven\");\n listBox->addElement(L\"Entry Eight\");\n listBox->addElement(L\"Entry Nine\");\n listBox->addElement(L\"Entry Ten\");\n listBox->addElement(L\"Entry Eleven\");\n \/\/guiEnvironment.addWidget(std::move(listBox));\n\n while (window.isOpen())\n {\n determineFpsAndDeltaTime(txtStatFPS, dt, averageFpsTime, fpsInSec, fpsCnt, \n averageFpsInOneSec, timePoint1);\n sf::Event event;\n while (window.pollEvent(event))\n {\n if (event.type == sf::Event::Closed)\n {\n window.close();\n }\n else if (event.type == sf::Event::Resized)\n {\n \/*\n std::cout << \"new width: \" << event.size.width << std::endl;\n std::cout << \"new height: \" << event.size.height << std::endl;\n sf::View currentView{ window.getView() };\n sf::FloatRect currentViewport{ currentView.getViewport() };\n std::cout << \"ViewSize: width: \" << currentView.getSize().x\n << \" height: \" << currentView.getSize().y\n << \"\\n Viewport: left: \" << currentViewport.left << \" top: \"\n << currentViewport.top << \" width: \" << currentViewport.width\n << \" height: \" << currentViewport.height \n << \"\\n-------------------------------------------\\n\";\n sf::FloatRect newRect( 0, 0, event.size.width, event.size.height );\n sf::View newView(newRect);\n \/\/window.setView(newView);\n *\/\n }\n guiEnvironment.handleEvent(event);\n }\n guiEnvironment.update(dt);\n\n\n window.clear(sf::Color::White);\n window.draw(guiEnvironment);\n window.draw(txtStatFPS);\n window.display();\n }\n\n return 0;\n}\n\nvoid determineFpsAndDeltaTime(sf::Text &txtStatFPS, float &dt, \n float &averageFpsTime, float &fpsInSec, int &fpsCnt, \n int &averageFpsInOneSec,\n CLOCK::time_point &timePoint1)\n{\n CLOCK::time_point timePoint2{ CLOCK::now() };\n std::chrono::duration<float> timeSpan{ timePoint2 - timePoint1 };\n timePoint1 = CLOCK::now();\n \/\/ Get deltaTime as float in seconds\n dt = std::chrono::duration_cast<std::chrono::duration<float,std::ratio<1>>> \n (timeSpan).count();\n float fps{ 1.f \/ dt };\n \n averageFpsTime += dt;\n fpsInSec += fps;\n fpsCnt++;\n if (averageFpsTime >= 1.f)\n {\n averageFpsInOneSec = fpsInSec \/ fpsCnt;\n averageFpsTime = 0.f;\n fpsInSec = 0.f;\n fpsCnt = 0;\n }\n\n txtStatFPS.setString(\"FPS: \" + std::to_string(averageFpsInOneSec) + \" (\" \n + std::to_string(fps) + \")\");\n}\n<commit_msg>Clean up<commit_after>#include <chrono>\n#include <iostream>\n#include <vector>\n#include <memory>\n#include <string>\n#include <SFML\/Graphics.hpp>\n#include \"GUI-SFML.hpp\"\n\ntypedef std::chrono::high_resolution_clock CLOCK;\n\nvoid determineFpsAndDeltaTime(sf::Text &txtStatFPS, float &dt, \n float &averageFpsTime, float &fpsInSec, int &fpsCnt, \n int &averageFpsInOneSec,\n CLOCK::time_point &timePoint1);\n\nint main()\n{\n unsigned int windowWidth{ 1280 };\n unsigned int windowHeight{ 720 };\n sf::RenderWindow window(sf::VideoMode{ windowWidth, windowHeight }, \"GUI-SFML\");\n\n sf::Font font;\n if (!font.loadFromFile(\"assets\/fonts\/LiberationSans-Regular.ttf\"))\n {\n std::cout << \"Error by loading Font\" << std::endl;\n }\n\n sf::Text txtStatFPS;\n txtStatFPS.setFont(font);\n txtStatFPS.setCharacterSize(12);\n txtStatFPS.setFillColor(sf::Color::Black);\n float dt{ 0.f };\n float averageFpsTime{ 0.f };\n float fpsInSec{ 0.f };\n int fpsCnt{ 0 };\n int averageFpsInOneSec{ 0 };\n CLOCK::time_point timePoint1{ CLOCK::now() };\n\n gsf::GUIEnvironment guiEnvironment{ window };\n gsf::TextWidget::Ptr textWidget{ \n gsf::TextWidget::create(\"IM A TEXT\\nTESTA\\nTESTB\\nTESTC\\nS\", font) };\n \/\/textWidget->centerOrigin();\n textWidget->setBackgroundColor(sf::Color{ 192, 192, 192 });\n textWidget->setCharacterSize(60);\n textWidget->setPosition(windowWidth \/ 2.f + 100.f, windowHeight \/ 2.f - 330.f);\n guiEnvironment.addWidget(std::move(textWidget));\n \n std::unique_ptr<gsf::ProgressWidget> progressWidget{ \n std::make_unique<gsf::ProgressWidget>(260, 40) };\n progressWidget->setPosition(460, 460);\n progressWidget->setProgress(50);\n progressWidget->setOnLeftClickListener([](gsf::Widget *widget, sf::Vector2f pos) \n {\n std::cout << \"Clicked Progress \\n\";\n });\n guiEnvironment.addWidget(std::move(progressWidget));\n \n std::unique_ptr<gsf::ScrollableWidget> scrollableWidget{ \n std::make_unique<gsf::ScrollableWidget>(300, 200) };\n scrollableWidget->setBackgroundColor(sf::Color{ 162, 162, 162 });\n\n std::unique_ptr<gsf::VerticalLayout> layout{ \n std::make_unique<gsf::VerticalLayout>() };\n layout->enableAutoDetermineWidth();\n layout->setOutlineThickness(8.f);\n layout->setOutlineColor(sf::Color::Yellow);\n \n for (int i{ 0 }; i != 6; i++)\n {\n \/*\n std::string textString{ \"Text Num \" + std::to_string(i) };\n std::unique_ptr<gsf::TextWidget> text{ std::make_unique<gsf::TextWidget>\n (textString, font, 40, sf::Color::White) };\n if (i % 2 == 0)\n {\n text->setBackgroundColor(sf::Color{ 192, 192, 192 });\n }\n else\n {\n text->setBackgroundColor(sf::Color{ 128, 128, 128 });\n }\n std::function<void(gsf::Widget*, sf::Vector2f)> leftClickListener = \n [] (gsf::Widget* widget, sf::Vector2f mousePos)\n {\n gsf::TextWidget *textWidget = static_cast<gsf::TextWidget*>(widget);\n std::cout << \"TextWidget: Left Mouse Button Clicked. Text: \" \n << textWidget->getText().toAnsiString() << std::endl;\n };\n text->setOnLeftClickListener(leftClickListener);\n \n layout->attachChild(std::move(text));\n *\/\n gsf::ProgressWidget::Ptr prog{ gsf::ProgressWidget::create(360.f, 40.f) };\n if (i % 2 == 0)\n {\n prog->setOutlineColor(sf::Color::Red);\n }\n else\n {\n prog->setOutlineColor(sf::Color::Blue);\n }\n layout->attachChild(std::move(prog));\n }\n\n scrollableWidget->attachChild(std::move(layout));\n\n std::unique_ptr<gsf::WindowWidget> windowWidget{ \n std::make_unique<gsf::WindowWidget>(\n scrollableWidget->getGlobalBounds().width,\n scrollableWidget->getGlobalBounds().height, L\"\", font) };\n windowWidget->setPosition(200.f , 200.f);\n \/\/windowWidget->setBackgroundColor(sf::Color::White);\n windowWidget->attachChild(std::move(scrollableWidget));\n windowWidget->setIsVisible(true);\n guiEnvironment.addWidget(std::move(windowWidget));\n \n std::unique_ptr<gsf::WindowWidget> windowWidget2{ \n std::make_unique<gsf::WindowWidget>(300.f, 360.f, L\"\", font) };\n windowWidget2->setPosition(240.f , 40.f);\n \/\/windowWidget2->setBackgroundColor(sf::Color::Red);\n \/\/windowWidget2->setTopBarFillColor(sf::Color::Green);\n \/\/windowWidget2->setCloseButtonFillColor(sf::Color::Blue);\n windowWidget2->setWindowTitle(L\"Test\");\n \/\/windowWidget2->setWindowTitleColor(sf::Color::Red);\n guiEnvironment.addWidget(std::move(windowWidget2));\n\n std::unique_ptr<gsf::WindowWidget> windowWidget3{ \n std::make_unique<gsf::WindowWidget>\n (300.f, 360.f, L\"Test Window TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT\", font) };\n windowWidget3->setPosition(300.f , 60.f);\n \/\/windowWidget3->setOutlineThickness(12.f);\n \/\/windowWidget3->setOutlineColor(sf::Color::White);\n \/\/windowWidget3->setBackgroundColor(sf::Color::Blue);\n guiEnvironment.addWidget(std::move(windowWidget3));\n \n \/\/ BUTTON TEST\n std::unique_ptr<gsf::TextButtonWidget> buttonWidget{ \n std::make_unique<gsf::TextButtonWidget>\n (200.f, 80.f, L\"CABBBBBTTTTTTTTTTTTTTTTTTTTTTClick me\", font) };\n buttonWidget->setPosition(240.f , 360.f);\n buttonWidget->setOnLeftClickListener(\n [] (gsf::Widget* widget, sf::Vector2f mousePos)\n {\n std::cout << \"Button Left Click\\n\";\n\n });\n buttonWidget->setOnRightClickListener(\n [] (gsf::Widget* widget, sf::Vector2f mousePos)\n {\n std::cout << \"Button Right Click\\n\";\n\n });\n buttonWidget->setOnMiddleClickListener(\n [] (gsf::Widget* widget, sf::Vector2f mousePos)\n {\n std::cout << \"Button Middle Click\\n\";\n\n });\n guiEnvironment.addWidget(std::move(buttonWidget));\n \n \/\/ SCROLLBAR TEST\n std::unique_ptr<gsf::ScrollableWidget> scrollableWidget3{ \n std::make_unique<gsf::ScrollableWidget>(300, 200) };\n scrollableWidget3->setPosition(820.f, 420.f);\n scrollableWidget3->setBackgroundColor(sf::Color{ 128, 128, 128 });\n\n std::unique_ptr<gsf::VerticalLayout> layout4{ \n std::make_unique<gsf::VerticalLayout>() };\n layout4->enableAutoDetermineWidth();\n layout4->setBackgroundColor(sf::Color::Cyan);\n\n for (int i{0}; i != 10; i++)\n {\n std::string textString{ \"Text Text Text Text Text Text Text Num \" \n + std::to_string(i) };\n std::unique_ptr<gsf::TextWidget> text{ \n std::make_unique<gsf::TextWidget>\n (textString, font, 40, sf::Color::White) };\n if (i % 2 == 0)\n {\n text->setBackgroundColor(sf::Color::Green);\n }\n else\n {\n text->setBackgroundColor(sf::Color::Magenta);\n }\n std::function<void(gsf::Widget*, sf::Vector2f)> leftClickListener = \n [] (gsf::Widget* widget, sf::Vector2f mousePos)\n {\n gsf::TextWidget *textWidget = static_cast<gsf::TextWidget*>(widget);\n std::cout << \"TextWidget: Left Mouse Button Clicked. Text: \" \n << textWidget->getText().toAnsiString() << std::endl;\n };\n text->setOnLeftClickListener(leftClickListener);\n \/\/text->setBackgroundColor(sf::Color::Red);\n layout4->attachChild(std::move(text));\n }\n scrollableWidget3->attachChild(std::move(layout4));\n guiEnvironment.addWidget(std::move(scrollableWidget3));\n\n std::unique_ptr<gsf::TextInputWidget> textInput1{ \n std::make_unique<gsf::TextInputWidget>(300.f, 60.f, font) };\n textInput1->setPosition(320.f, 520.f);\n textInput1->setBackgroundColor(sf::Color::White);\n textInput1->setIsHorizontalScrollEnabled(false);\n textInput1->setText(L\"Test Text HHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHH :)\");\n textInput1->setWhiteListChars(L\"0123456789\");\n guiEnvironment.addWidget(std::move(textInput1));\n \n \/\/ Console Widget\n std::unique_ptr<gsf::ConsoleWidget> console1{ \n std::make_unique<gsf::ConsoleWidget>(500.f, 200.f, font) };\n console1->setPosition(700.f, 200.f);\n console1->setOnCommandEnteredListener(\n [] (gsf::Widget *widget, std::wstring inputText)\n {\n std::wcout << \"CommandEnteredListener command: \" << inputText \n << std::endl;\n gsf::ConsoleWidget *consoleWidget{ \n static_cast<gsf::ConsoleWidget*>(widget) };\n consoleWidget->addTextToDisplay(L\"OK\");\n }\n );\n guiEnvironment.addWidget(std::move(console1));\n \n \/\/ CheckBoxWidget\n std::unique_ptr<gsf::CheckBoxWidget> checkBox1{ \n std::make_unique<gsf::CheckBoxWidget>(60, 60.f) };\n checkBox1->setPosition(10.f, 620.f);\n guiEnvironment.addWidget(std::move(checkBox1));\n \n \/\/ ComboBoxWidget\n gsf::ComboBoxWidget::Ptr comboBox{ \n gsf::ComboBoxWidget::create(80.f, 20.f, font) };\n comboBox->setPosition(120.f, 620.f);\n comboBox->addElement(L\"Entry One\");\n comboBox->addElement(L\"Entry Two\");\n comboBox->addElement(L\"Entry Three\");\n comboBox->addElement(L\"Entry Four\");\n comboBox->addElement(L\"Entry Five\");\n comboBox->addElement(L\"Entry LAST\");\n guiEnvironment.addWidget(std::move(comboBox));\n \n \/\/ ListBoxWidget\n gsf::ListBoxWidget::Ptr listBox{ \n gsf::ListBoxWidget::create(80.f, 100.f, font) };\n listBox->setOnElementSelectedListener([](gsf::Widget* widget, int index)\n {\n gsf::ListBoxWidget *widgetList{ static_cast<gsf::ListBoxWidget*>(widget) };\n std::wstring content{ widgetList->getElement(index) };\n std::cout << \"Index selected: \" << index << std::endl;\n });\n listBox->setPosition(320.f, 590.f);\n listBox->addElement(L\"Entry One\");\n listBox->addElement(L\"Entry Two\");\n listBox->addElement(L\"Entry Three\");\n listBox->addElement(L\"Entry Four\");\n listBox->addElement(L\"Entry Five\");\n listBox->addElement(L\"Entry Six\");\n listBox->addElement(L\"Entry Seven\");\n listBox->addElement(L\"Entry Eight\");\n listBox->addElement(L\"Entry Nine\");\n listBox->addElement(L\"Entry Ten\");\n listBox->addElement(L\"Entry Eleven\");\n guiEnvironment.addWidget(std::move(listBox));\n\n while (window.isOpen())\n {\n determineFpsAndDeltaTime(txtStatFPS, dt, averageFpsTime, fpsInSec, fpsCnt, \n averageFpsInOneSec, timePoint1);\n sf::Event event;\n while (window.pollEvent(event))\n {\n if (event.type == sf::Event::Closed)\n {\n window.close();\n }\n else if (event.type == sf::Event::Resized)\n {\n \/*\n std::cout << \"new width: \" << event.size.width << std::endl;\n std::cout << \"new height: \" << event.size.height << std::endl;\n sf::View currentView{ window.getView() };\n sf::FloatRect currentViewport{ currentView.getViewport() };\n std::cout << \"ViewSize: width: \" << currentView.getSize().x\n << \" height: \" << currentView.getSize().y\n << \"\\n Viewport: left: \" << currentViewport.left << \" top: \"\n << currentViewport.top << \" width: \" << currentViewport.width\n << \" height: \" << currentViewport.height \n << \"\\n-------------------------------------------\\n\";\n sf::FloatRect newRect( 0, 0, event.size.width, event.size.height );\n sf::View newView(newRect);\n \/\/window.setView(newView);\n *\/\n }\n guiEnvironment.handleEvent(event);\n }\n guiEnvironment.update(dt);\n\n\n window.clear(sf::Color::White);\n window.draw(guiEnvironment);\n window.draw(txtStatFPS);\n window.display();\n }\n\n return 0;\n}\n\nvoid determineFpsAndDeltaTime(sf::Text &txtStatFPS, float &dt, \n float &averageFpsTime, float &fpsInSec, int &fpsCnt, \n int &averageFpsInOneSec,\n CLOCK::time_point &timePoint1)\n{\n CLOCK::time_point timePoint2{ CLOCK::now() };\n std::chrono::duration<float> timeSpan{ timePoint2 - timePoint1 };\n timePoint1 = CLOCK::now();\n \/\/ Get deltaTime as float in seconds\n dt = std::chrono::duration_cast<std::chrono::duration<float,std::ratio<1>>> \n (timeSpan).count();\n float fps{ 1.f \/ dt };\n \n averageFpsTime += dt;\n fpsInSec += fps;\n fpsCnt++;\n if (averageFpsTime >= 1.f)\n {\n averageFpsInOneSec = fpsInSec \/ fpsCnt;\n averageFpsTime = 0.f;\n fpsInSec = 0.f;\n fpsCnt = 0;\n }\n\n txtStatFPS.setString(\"FPS: \" + std::to_string(averageFpsInOneSec) + \" (\" \n + std::to_string(fps) + \")\");\n}\n<|endoftext|>"} {"text":"<commit_before>#include <sndfile.h>\n#include <iostream>\n#include <string>\n#include <vector>\n#include <boost\/program_options.hpp>\n\n#include \"utilities.hpp\"\n\nnamespace po = boost::program_options;\n\nint main(int argc, char **argv) {\n std::string inputFilename = \"\";\n std::string outputFilename = \"\";\n int blockSize = 1024;\n float minDb = -45;\n float targetDb = -20;\n int windowSize = 20;\n bool limiter = true;\n float limiterRelease = 0.0006;\n int limiterAttack = 1024;\n bool checkSilence = false;\n\n po::options_description prettyDesc(\"Options\"); \/\/ this version doesn't include the positional arguments\n prettyDesc.add_options()\n (\"help\", \"Show this help information\")\n (\"target,t\", po::value<float>(&targetDb)->required(), \"Set target dB level\")\n (\"silence,s\", po::value<float>(&minDb)->default_value(-45.0), \"Minimum dB value for audio content, anything below this is considered silence.\")\n (\"check-silence\", \"Skips dynamics processing and cuts out silence from the output file. Use to test the silence level.\")\n (\"window,w\", po::value<int>(&windowSize)->default_value(20), \"Window size for smoothing volume changes.\")\n (\"block-size\", po::value<int>(&blockSize)->default_value(1024), \"Block size for calculating RMS values.\")\n (\"limiter-attack\", po::value<int>(&limiterAttack)->default_value(1024), \"Limiter attack time in samples.\")\n (\"limiter-release\", po::value<float>(&limiterRelease)->default_value(0.0006), \"Limiter release time in dB\/sample.\")\n (\"limiter-disable\", \"Disable the limiter completely - may cause clipping.\")\n ;\n po::options_description desc(\"Options\"); \/\/ this one is actually used to parse, don't use required()\n desc.add_options()\n (\"help\", \"Show this help information\")\n (\"input-file\", po::value<std::string>(&inputFilename))\n (\"output-file\", po::value<std::string>(&outputFilename))\n (\"target,t\", po::value<float>(&targetDb), \"Set target dB level\")\n (\"silence,s\", po::value<float>(&minDb)->default_value(-45.0), \"Minimum dB value for audio content, anything below this is considered silence.\")\n (\"check-silence\", \"Skips dynamics processing and cuts out silence from the output file. Use to test the silence level.\")\n (\"window,w\", po::value<int>(&windowSize)->default_value(20), \"Window size for smoothing volume changes.\")\n (\"block-size\", po::value<int>(&blockSize)->default_value(1024), \"Block size for calculating RMS values.\")\n (\"limiter-attack\", po::value<int>(&limiterAttack)->default_value(1024), \"Limiter attack time in samples.\")\n (\"limiter-release\", po::value<float>(&limiterRelease)->default_value(0.0006), \"Limiter release time in dB\/sample.\")\n (\"disable-limiter\", \"Disable the limiter completely - may cause clipping.\")\n ;\n po::positional_options_description p;\n p.add(\"input-file\", 1).add(\"output-file\", 1);\n\n po::variables_map vm;\n try {\n po::store(po::command_line_parser(argc, argv).options(desc).positional(p).run(), vm);\n po::notify(vm);\n } catch(std::exception& e) {\n std::cout << \"Error: \" << e.what() << std::endl;\n return 1;\n }\n\n if (vm.count(\"help\")) {\n std::cout << \"Usage: \" << argv[0] << \" input.wav output.wav OPTIONS\" << std::endl << std::endl;\n std::cout << prettyDesc << std::endl;\n return 1;\n }\n\n \/\/ do we have the required values?\n if (!vm.count(\"input-file\") || !vm.count(\"output-file\")) {\n std::cout << \"The input and output filenames are required.\" << std::endl;\n return 1;\n }\n if (vm.count(\"check-silence\")) {\n checkSilence = true;\n }\n if (!vm.count(\"target\") && !checkSilence) {\n std::cout << \"The target dB level (-t, --target)is required.\" << std::endl;\n return 1;\n }\n if (vm.count(\"disable-limiter\")) {\n limiter = false;\n }\n \/\/ check that everything's within a valid range\n if (blockSize < 32) {\n std::cout << \"Block size must be >= 32.\" << std::endl;\n return 1;\n }\n if (minDb >= 0) {\n std::cout << \"Silence level must be < 0 dB.\" << std::endl;\n return 1;\n }\n if (targetDb >= 0) {\n std::cout << \"Target level must be < 0 dB.\" << std::endl;\n return 1;\n }\n if (windowSize < 1) {\n std::cout << \"Window size must be >= 1.\" << std::endl;\n return 1;\n }\n if (limiterRelease <= 0) {\n std::cout << \"Limiter release must be > 0.\" << std::endl;\n return 1;\n }\n if (limiterAttack < 1) {\n std::cout << \"Limiter attack must be > 0.\" << std::endl;\n return 1;\n }\n\n SF_INFO info;\n info.format = 0;\n SNDFILE* infile = sf_open(inputFilename.c_str(), SFM_READ, &info);\n\n if (!infile) {\n std::cout << \"Error opening input file: \" << sf_strerror(NULL) << std::endl;\n return 1;\n }\n\n SNDFILE *outfile = NULL;\n if (checkSilence) {\n SF_INFO outinfo;\n outinfo.format = SF_FORMAT_WAV | SF_FORMAT_PCM_16;\n outinfo.samplerate = info.samplerate;\n outinfo.channels = info.channels;\n outfile = sf_open(outputFilename.c_str(), SFM_WRITE, &outinfo);\n\n if (!outfile) {\n std::cout << \"Error opening output file: \" << sf_strerror(NULL) << std::endl;\n sf_close(infile);\n return 1;\n }\n }\n\n \/\/ the file was opened, let's calculate some RMS!\n std::cout << \"Calculating RMS values...\" << std::endl;\n std::vector<float> rmsBlocks;\n sf_count_t frames;\n float *data = new float[blockSize * info.channels];\n do {\n frames = sf_readf_float(infile, data, blockSize);\n \/\/std::cout << samples << std::endl;\n float rms = calculateRMS(data, frames * info.channels);\n float rmsDb = VtoDB(rms);\n rmsBlocks.push_back(rmsDb);\n if (checkSilence && rmsDb > minDb) {\n sf_writef_float(outfile, data, frames);\n }\n } while (frames == blockSize);\n std::cout << rmsBlocks.size() << \" RMS blocks calculated.\" << std::endl;\n delete[] data;\n\n if (checkSilence) {\n std::cout << \"Done.\" << std::endl;\n\n sf_close(infile);\n sf_close(outfile);\n return 0;\n }\n\n \/\/ use a ring buffer to calculate a moving average over the RMS blocks\n int ringBufferSize = windowSize * 2 + 1;\n float ringBuffer[ringBufferSize];\n for (int i=0; i<ringBufferSize; i++) {\n ringBuffer[i] = -1000.0;\n }\n int ringBufferPos = 0;\n std::vector<float>::size_type currentBlock = 0;\n \/\/ start filling the ring buffer\n for (int i=0; i<windowSize; i++) {\n if (currentBlock < rmsBlocks.size()) {\n ringBuffer[ringBufferPos] = rmsBlocks[currentBlock];\n } else {\n ringBuffer[ringBufferPos] = -1000.0;\n }\n currentBlock++;\n ringBufferPos++;\n }\n \/\/ go through all of our blocks\n std::cout << \"Calculating gain points...\" << std::endl;\n std::vector<gainPoint> gainPoints;\n int minAverageBlocks = windowSize * 1.5;\n for (std::vector<float>::size_type i=0; i<rmsBlocks.size(); i++) {\n if (currentBlock < rmsBlocks.size()) {\n ringBuffer[ringBufferPos] = rmsBlocks[currentBlock];\n } else {\n ringBuffer[ringBufferPos] = -1000.0;\n }\n currentBlock++;\n ringBufferPos++;\n if (ringBufferPos >= ringBufferSize) ringBufferPos = 0;\n \/\/ calculate the average RMS if we have enough blocks that aren't silent\n int numBlocks = 0;\n float rms = 0;\n for (int j=0; j<ringBufferSize; j++) {\n if (ringBuffer[j] > minDb) {\n numBlocks++;\n rms += ringBuffer[j];\n }\n }\n if (numBlocks > minAverageBlocks) {\n rms = rms \/ (float)numBlocks;\n float gain = targetDb - rms;\n gainPoint gp;\n gp.gain = gain;\n gp.position = (i * blockSize) + (blockSize \/ 2);\n gainPoints.push_back(gp);\n }\n }\n std::cout << gainPoints.size() << \" gain points calculated.\" << std::endl;\n if (gainPoints.size() == 0) {\n std::cout << \"Error: no gain points found, nothing to do.\" << std::endl;\n sf_close(infile);\n return 1;\n }\n\n SF_INFO outinfo;\n outinfo.format = SF_FORMAT_WAV | SF_FORMAT_PCM_16;\n outinfo.samplerate = info.samplerate;\n outinfo.channels = info.channels;\n outfile = sf_open(outputFilename.c_str(), SFM_WRITE, &outinfo);\n\n if (!outfile) {\n std::cout << \"Error opening output file: \" << sf_strerror(NULL) << std::endl;\n sf_close(infile);\n return 1;\n }\n\n \/\/ now we go through the file and apply the gain!\n float limiterGain = 0.0;\n std::cout << \"Applying gain...\" << std::endl;\n int processSize = 1024;\n if (limiter && limiterAttack > processSize) processSize = limiterAttack;\n data = new float[processSize * info.channels];\n float *oldData = new float[processSize * info.channels];\n sf_count_t oldFrames;\n sf_seek(infile, 0, SEEK_SET);\n sf_count_t currentFrame = 0;\n sf_count_t clipped = 0;\n int currentPerc = 0;\n int blockNum = 0;\n int totalBlocks = info.frames \/ processSize;\n gainPoint firstGainPoint = gainPoints[0];\n gainPoint lastGainPoint = gainPoints[gainPoints.size() - 1];\n int currentGainPointNumber = 0;\n gainPoint currentGainPoint = firstGainPoint;\n gainPoint nextGainPoint;\n if (gainPoints.size() > 1) nextGainPoint = gainPoints[1];\n do {\n \/\/ flip the buffers and read new data\n float *temp = oldData;\n data = oldData;\n oldData = temp;\n oldFrames = frames;\n frames = sf_readf_float(infile, data, processSize);\n for (sf_count_t i=0; i<frames; i++) {\n \/\/ calculate the gain\n float gain = 0.0;\n if (currentFrame <= firstGainPoint.position) {\n gain = firstGainPoint.gain;\n } else if (currentFrame >= lastGainPoint.position) {\n gain = lastGainPoint.gain;\n } else {\n \/\/ interpolate between gain points\n if (currentFrame >= nextGainPoint.position) {\n currentGainPointNumber++;\n currentGainPoint = gainPoints[currentGainPointNumber];\n nextGainPoint = gainPoints[currentGainPointNumber + 1];\n }\n float pos = (float)(currentFrame - currentGainPoint.position) \/ (float)(nextGainPoint.position - currentGainPoint.position);\n gain = ((1.0f - pos) * currentGainPoint.gain) + (pos * nextGainPoint.gain);\n }\n \/\/float gain = interpolateGain(gainPoints, currentFrame);\n if (limiter) gain += limiterGain;\n float gainMult = DBtoV(gain);\n \/\/ apply the gain\n float highestValue = 0.0;\n for (int j=0; j<info.channels; j++) {\n float sample = data[i * info.channels + j];\n sample = sample * gainMult;\n if (!limiter && sample > 1.0) clipped++;\n if (sample > highestValue) highestValue = sample;\n data[i * info.channels + j] = sample;\n }\n if (highestValue > 1.0 && limiter) {\n \/\/ kick the limiter in\n highestValue += .001;\n float additionalLimiterGain = -VtoDB(highestValue);\n limiterGain += additionalLimiterGain;\n \/\/ and drop the attack frames down\n for (int attack=0; attack<limiterAttack; attack++) {\n int frame = i - attack;\n float gain = additionalLimiterGain * ((float)(limiterAttack - attack) \/ (float)limiterAttack);\n float mult = DBtoV(gain);\n if (frame >= 0) {\n for (int j=0; j<info.channels; j++) {\n data[frame * info.channels + j] *= mult;\n }\n } else {\n int oldFrame = frame + oldFrames;\n for (int j=0; j<info.channels; j++) {\n oldData[oldFrame * info.channels + j] *= mult;\n }\n }\n }\n \/\/ and drop our current frame down\n for (int j=0; j<info.channels; j++) {\n data[i * info.channels + j] \/= highestValue;\n }\n \n }\n currentFrame++;\n limiterGain += limiterRelease;\n if (limiterGain > 0) limiterGain = 0;\n }\n \/\/ write the frames to the new file\n if (blockNum > 0) sf_writef_float(outfile, oldData, oldFrames);\n blockNum++;\n if (totalBlocks > 0) {\n int thisPerc = (blockNum * 100) \/ totalBlocks;\n if (thisPerc > currentPerc) {\n currentPerc = thisPerc;\n std::cout << currentPerc << \"% done\" << std::endl;\n }\n }\n } while (frames == processSize);\n sf_writef_float(outfile, data, frames);\n if (clipped) std::cout << \"WARNING: \" << clipped << \" samples clipped and limiter disabled\" << std::endl;\n\n std::cout << \"Done.\" << std::endl;\n\n sf_close(infile);\n sf_close(outfile);\n\n return 0;\n}\n<commit_msg>added gain information<commit_after>#include <sndfile.h>\n#include <iostream>\n#include <string>\n#include <vector>\n#include <boost\/program_options.hpp>\n\n#include \"utilities.hpp\"\n\nnamespace po = boost::program_options;\n\nint main(int argc, char **argv) {\n std::string inputFilename = \"\";\n std::string outputFilename = \"\";\n int blockSize = 1024;\n float minDb = -45;\n float targetDb = -20;\n int windowSize = 20;\n bool limiter = true;\n float limiterRelease = 0.0006;\n int limiterAttack = 1024;\n bool checkSilence = false;\n\n po::options_description prettyDesc(\"Options\"); \/\/ this version doesn't include the positional arguments\n prettyDesc.add_options()\n (\"help\", \"Show this help information\")\n (\"target,t\", po::value<float>(&targetDb)->required(), \"Set target dB level\")\n (\"silence,s\", po::value<float>(&minDb)->default_value(-45.0), \"Minimum dB value for audio content, anything below this is considered silence.\")\n (\"check-silence\", \"Skips dynamics processing and cuts out silence from the output file. Use to test the silence level.\")\n (\"window,w\", po::value<int>(&windowSize)->default_value(20), \"Window size for smoothing volume changes.\")\n (\"block-size\", po::value<int>(&blockSize)->default_value(1024), \"Block size for calculating RMS values.\")\n (\"limiter-attack\", po::value<int>(&limiterAttack)->default_value(1024), \"Limiter attack time in samples.\")\n (\"limiter-release\", po::value<float>(&limiterRelease)->default_value(0.0006), \"Limiter release time in dB\/sample.\")\n (\"limiter-disable\", \"Disable the limiter completely - may cause clipping.\")\n ;\n po::options_description desc(\"Options\"); \/\/ this one is actually used to parse, don't use required()\n desc.add_options()\n (\"help\", \"Show this help information\")\n (\"input-file\", po::value<std::string>(&inputFilename))\n (\"output-file\", po::value<std::string>(&outputFilename))\n (\"target,t\", po::value<float>(&targetDb), \"Set target dB level\")\n (\"silence,s\", po::value<float>(&minDb)->default_value(-45.0), \"Minimum dB value for audio content, anything below this is considered silence.\")\n (\"check-silence\", \"Skips dynamics processing and cuts out silence from the output file. Use to test the silence level.\")\n (\"window,w\", po::value<int>(&windowSize)->default_value(20), \"Window size for smoothing volume changes.\")\n (\"block-size\", po::value<int>(&blockSize)->default_value(1024), \"Block size for calculating RMS values.\")\n (\"limiter-attack\", po::value<int>(&limiterAttack)->default_value(1024), \"Limiter attack time in samples.\")\n (\"limiter-release\", po::value<float>(&limiterRelease)->default_value(0.0006), \"Limiter release time in dB\/sample.\")\n (\"disable-limiter\", \"Disable the limiter completely - may cause clipping.\")\n ;\n po::positional_options_description p;\n p.add(\"input-file\", 1).add(\"output-file\", 1);\n\n po::variables_map vm;\n try {\n po::store(po::command_line_parser(argc, argv).options(desc).positional(p).run(), vm);\n po::notify(vm);\n } catch(std::exception& e) {\n std::cout << \"Error: \" << e.what() << std::endl;\n return 1;\n }\n\n if (vm.count(\"help\")) {\n std::cout << \"Usage: \" << argv[0] << \" input.wav output.wav OPTIONS\" << std::endl << std::endl;\n std::cout << prettyDesc << std::endl;\n return 1;\n }\n\n \/\/ do we have the required values?\n if (!vm.count(\"input-file\") || !vm.count(\"output-file\")) {\n std::cout << \"The input and output filenames are required.\" << std::endl;\n return 1;\n }\n if (vm.count(\"check-silence\")) {\n checkSilence = true;\n }\n if (!vm.count(\"target\") && !checkSilence) {\n std::cout << \"The target dB level (-t, --target)is required.\" << std::endl;\n return 1;\n }\n if (vm.count(\"disable-limiter\")) {\n limiter = false;\n }\n \/\/ check that everything's within a valid range\n if (blockSize < 32) {\n std::cout << \"Block size must be >= 32.\" << std::endl;\n return 1;\n }\n if (minDb >= 0) {\n std::cout << \"Silence level must be < 0 dB.\" << std::endl;\n return 1;\n }\n if (targetDb >= 0) {\n std::cout << \"Target level must be < 0 dB.\" << std::endl;\n return 1;\n }\n if (windowSize < 1) {\n std::cout << \"Window size must be >= 1.\" << std::endl;\n return 1;\n }\n if (limiterRelease <= 0) {\n std::cout << \"Limiter release must be > 0.\" << std::endl;\n return 1;\n }\n if (limiterAttack < 1) {\n std::cout << \"Limiter attack must be > 0.\" << std::endl;\n return 1;\n }\n\n SF_INFO info;\n info.format = 0;\n SNDFILE* infile = sf_open(inputFilename.c_str(), SFM_READ, &info);\n\n if (!infile) {\n std::cout << \"Error opening input file: \" << sf_strerror(NULL) << std::endl;\n return 1;\n }\n\n SNDFILE *outfile = NULL;\n if (checkSilence) {\n SF_INFO outinfo;\n outinfo.format = SF_FORMAT_WAV | SF_FORMAT_PCM_16;\n outinfo.samplerate = info.samplerate;\n outinfo.channels = info.channels;\n outfile = sf_open(outputFilename.c_str(), SFM_WRITE, &outinfo);\n\n if (!outfile) {\n std::cout << \"Error opening output file: \" << sf_strerror(NULL) << std::endl;\n sf_close(infile);\n return 1;\n }\n }\n\n \/\/ the file was opened, let's calculate some RMS!\n std::cout << \"Calculating RMS values...\" << std::endl;\n std::vector<float> rmsBlocks;\n sf_count_t frames;\n float *data = new float[blockSize * info.channels];\n do {\n frames = sf_readf_float(infile, data, blockSize);\n \/\/std::cout << samples << std::endl;\n float rms = calculateRMS(data, frames * info.channels);\n float rmsDb = VtoDB(rms);\n rmsBlocks.push_back(rmsDb);\n if (checkSilence && rmsDb > minDb) {\n sf_writef_float(outfile, data, frames);\n }\n } while (frames == blockSize);\n std::cout << rmsBlocks.size() << \" RMS blocks calculated.\" << std::endl;\n delete[] data;\n\n if (checkSilence) {\n std::cout << \"Done.\" << std::endl;\n\n sf_close(infile);\n sf_close(outfile);\n return 0;\n }\n\n \/\/ use a ring buffer to calculate a moving average over the RMS blocks\n int ringBufferSize = windowSize * 2 + 1;\n float ringBuffer[ringBufferSize];\n for (int i=0; i<ringBufferSize; i++) {\n ringBuffer[i] = -1000.0;\n }\n int ringBufferPos = 0;\n std::vector<float>::size_type currentBlock = 0;\n \/\/ start filling the ring buffer\n for (int i=0; i<windowSize; i++) {\n if (currentBlock < rmsBlocks.size()) {\n ringBuffer[ringBufferPos] = rmsBlocks[currentBlock];\n } else {\n ringBuffer[ringBufferPos] = -1000.0;\n }\n currentBlock++;\n ringBufferPos++;\n }\n \/\/ go through all of our blocks\n std::cout << \"Calculating gain points...\" << std::endl;\n std::vector<gainPoint> gainPoints;\n int minAverageBlocks = windowSize * 1.5;\n float maximumGain = 0;\n float minimumGain = 0;\n for (std::vector<float>::size_type i=0; i<rmsBlocks.size(); i++) {\n if (currentBlock < rmsBlocks.size()) {\n ringBuffer[ringBufferPos] = rmsBlocks[currentBlock];\n } else {\n ringBuffer[ringBufferPos] = -1000.0;\n }\n currentBlock++;\n ringBufferPos++;\n if (ringBufferPos >= ringBufferSize) ringBufferPos = 0;\n \/\/ calculate the average RMS if we have enough blocks that aren't silent\n int numBlocks = 0;\n float rms = 0;\n for (int j=0; j<ringBufferSize; j++) {\n if (ringBuffer[j] > minDb) {\n numBlocks++;\n rms += ringBuffer[j];\n }\n }\n if (numBlocks > minAverageBlocks) {\n rms = rms \/ (float)numBlocks;\n float gain = targetDb - rms;\n gainPoint gp;\n gp.gain = gain;\n gp.position = (i * blockSize) + (blockSize \/ 2);\n gainPoints.push_back(gp);\n if (gainPoints.size() == 1 || gain > maximumGain) maximumGain = gain;\n if (gainPoints.size() == 1 || gain < minimumGain) minimumGain = gain;\n }\n }\n std::cout << gainPoints.size() << \" gain points calculated.\" << std::endl;\n if (gainPoints.size() == 0) {\n std::cout << \"Error: no gain points found, nothing to do.\" << std::endl;\n sf_close(infile);\n return 1;\n }\n std::cout << \"Minimum gain: \" << minimumGain << \" dB.\" << std::endl;\n std::cout << \"Maximum gain: \" << maximumGain << \" dB.\" << std::endl;\n\n SF_INFO outinfo;\n outinfo.format = SF_FORMAT_WAV | SF_FORMAT_PCM_16;\n outinfo.samplerate = info.samplerate;\n outinfo.channels = info.channels;\n outfile = sf_open(outputFilename.c_str(), SFM_WRITE, &outinfo);\n\n if (!outfile) {\n std::cout << \"Error opening output file: \" << sf_strerror(NULL) << std::endl;\n sf_close(infile);\n return 1;\n }\n\n \/\/ now we go through the file and apply the gain!\n float limiterGain = 0.0;\n std::cout << \"Applying gain...\" << std::endl;\n int processSize = 1024;\n if (limiter && limiterAttack > processSize) processSize = limiterAttack;\n data = new float[processSize * info.channels];\n float *oldData = new float[processSize * info.channels];\n sf_count_t oldFrames;\n sf_seek(infile, 0, SEEK_SET);\n sf_count_t currentFrame = 0;\n sf_count_t clipped = 0;\n int currentPerc = 0;\n int blockNum = 0;\n int totalBlocks = info.frames \/ processSize;\n gainPoint firstGainPoint = gainPoints[0];\n gainPoint lastGainPoint = gainPoints[gainPoints.size() - 1];\n int currentGainPointNumber = 0;\n gainPoint currentGainPoint = firstGainPoint;\n gainPoint nextGainPoint;\n if (gainPoints.size() > 1) nextGainPoint = gainPoints[1];\n do {\n \/\/ flip the buffers and read new data\n float *temp = oldData;\n data = oldData;\n oldData = temp;\n oldFrames = frames;\n frames = sf_readf_float(infile, data, processSize);\n for (sf_count_t i=0; i<frames; i++) {\n \/\/ calculate the gain\n float gain = 0.0;\n if (currentFrame <= firstGainPoint.position) {\n gain = firstGainPoint.gain;\n } else if (currentFrame >= lastGainPoint.position) {\n gain = lastGainPoint.gain;\n } else {\n \/\/ interpolate between gain points\n if (currentFrame >= nextGainPoint.position) {\n currentGainPointNumber++;\n currentGainPoint = gainPoints[currentGainPointNumber];\n nextGainPoint = gainPoints[currentGainPointNumber + 1];\n }\n float pos = (float)(currentFrame - currentGainPoint.position) \/ (float)(nextGainPoint.position - currentGainPoint.position);\n gain = ((1.0f - pos) * currentGainPoint.gain) + (pos * nextGainPoint.gain);\n }\n \/\/float gain = interpolateGain(gainPoints, currentFrame);\n if (limiter) gain += limiterGain;\n float gainMult = DBtoV(gain);\n \/\/ apply the gain\n float highestValue = 0.0;\n for (int j=0; j<info.channels; j++) {\n float sample = data[i * info.channels + j];\n sample = sample * gainMult;\n if (!limiter && sample > 1.0) clipped++;\n if (sample > highestValue) highestValue = sample;\n data[i * info.channels + j] = sample;\n }\n if (highestValue > 1.0 && limiter) {\n \/\/ kick the limiter in\n highestValue += .001;\n float additionalLimiterGain = -VtoDB(highestValue);\n limiterGain += additionalLimiterGain;\n \/\/ and drop the attack frames down\n for (int attack=0; attack<limiterAttack; attack++) {\n int frame = i - attack;\n float gain = additionalLimiterGain * ((float)(limiterAttack - attack) \/ (float)limiterAttack);\n float mult = DBtoV(gain);\n if (frame >= 0) {\n for (int j=0; j<info.channels; j++) {\n data[frame * info.channels + j] *= mult;\n }\n } else {\n int oldFrame = frame + oldFrames;\n for (int j=0; j<info.channels; j++) {\n oldData[oldFrame * info.channels + j] *= mult;\n }\n }\n }\n \/\/ and drop our current frame down\n for (int j=0; j<info.channels; j++) {\n data[i * info.channels + j] \/= highestValue;\n }\n \n }\n currentFrame++;\n limiterGain += limiterRelease;\n if (limiterGain > 0) limiterGain = 0;\n }\n \/\/ write the frames to the new file\n if (blockNum > 0) sf_writef_float(outfile, oldData, oldFrames);\n blockNum++;\n if (totalBlocks > 0) {\n int thisPerc = (blockNum * 100) \/ totalBlocks;\n if (thisPerc > currentPerc) {\n currentPerc = thisPerc;\n std::cout << currentPerc << \"% done\" << std::endl;\n }\n }\n } while (frames == processSize);\n sf_writef_float(outfile, data, frames);\n if (clipped) std::cout << \"WARNING: \" << clipped << \" samples clipped and limiter disabled\" << std::endl;\n\n std::cout << \"Done.\" << std::endl;\n\n sf_close(infile);\n sf_close(outfile);\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>34fb7d26-5216-11e5-9bd1-6c40088e03e4<commit_msg>35025402-5216-11e5-95d5-6c40088e03e4<commit_after>35025402-5216-11e5-95d5-6c40088e03e4<|endoftext|>"} {"text":"<commit_before>81cf0d76-2d15-11e5-af21-0401358ea401<commit_msg>81cf0d77-2d15-11e5-af21-0401358ea401<commit_after>81cf0d77-2d15-11e5-af21-0401358ea401<|endoftext|>"} {"text":"<commit_before>6567e7ca-2749-11e6-8b20-e0f84713e7b8<commit_msg>Fix that bug where things didn't work but now they should<commit_after>65785fba-2749-11e6-a589-e0f84713e7b8<|endoftext|>"} {"text":"<commit_before>e328afb8-2e4e-11e5-80ad-28cfe91dbc4b<commit_msg>e32f8ef0-2e4e-11e5-8460-28cfe91dbc4b<commit_after>e32f8ef0-2e4e-11e5-8460-28cfe91dbc4b<|endoftext|>"} {"text":"<commit_before>4733ce94-5216-11e5-ad61-6c40088e03e4<commit_msg>473aeae4-5216-11e5-a959-6c40088e03e4<commit_after>473aeae4-5216-11e5-a959-6c40088e03e4<|endoftext|>"} {"text":"<commit_before>4baf4c42-ad5d-11e7-9c7d-ac87a332f658<commit_msg>bug fix<commit_after>4c3df26b-ad5d-11e7-8b4c-ac87a332f658<|endoftext|>"} {"text":"<commit_before>e73b651e-2e4e-11e5-8f06-28cfe91dbc4b<commit_msg>e7425297-2e4e-11e5-b0d7-28cfe91dbc4b<commit_after>e7425297-2e4e-11e5-b0d7-28cfe91dbc4b<|endoftext|>"} {"text":"<commit_before>715e8a5c-2749-11e6-9794-e0f84713e7b8<commit_msg>I hope I am done<commit_after>716e4e0f-2749-11e6-abb0-e0f84713e7b8<|endoftext|>"} {"text":"<commit_before>b0e98c07-2e4f-11e5-b2d0-28cfe91dbc4b<commit_msg>b0f028de-2e4f-11e5-b74f-28cfe91dbc4b<commit_after>b0f028de-2e4f-11e5-b74f-28cfe91dbc4b<|endoftext|>"} {"text":"<commit_before>6ef2d821-2e4f-11e5-9aad-28cfe91dbc4b<commit_msg>6efb333a-2e4f-11e5-8e4b-28cfe91dbc4b<commit_after>6efb333a-2e4f-11e5-8e4b-28cfe91dbc4b<|endoftext|>"} {"text":"<commit_before>0a67b95c-2f67-11e5-a9e4-6c40088e03e4<commit_msg>0a6e3480-2f67-11e5-8fdc-6c40088e03e4<commit_after>0a6e3480-2f67-11e5-8fdc-6c40088e03e4<|endoftext|>"} {"text":"<commit_before>4fbb257a-ad5d-11e7-b173-ac87a332f658<commit_msg>Did a thing<commit_after>508faf47-ad5d-11e7-af2e-ac87a332f658<|endoftext|>"} {"text":"<commit_before>26045d00-2e4f-11e5-adc5-28cfe91dbc4b<commit_msg>260cfa6e-2e4f-11e5-b34f-28cfe91dbc4b<commit_after>260cfa6e-2e4f-11e5-b34f-28cfe91dbc4b<|endoftext|>"} {"text":"<commit_before>bc4159d1-2e4f-11e5-b3fd-28cfe91dbc4b<commit_msg>bc494a45-2e4f-11e5-8698-28cfe91dbc4b<commit_after>bc494a45-2e4f-11e5-8698-28cfe91dbc4b<|endoftext|>"} {"text":"<commit_before>67a69d34-2fa5-11e5-bb75-00012e3d3f12<commit_msg>67a89902-2fa5-11e5-9591-00012e3d3f12<commit_after>67a89902-2fa5-11e5-9591-00012e3d3f12<|endoftext|>"} {"text":"<commit_before>7669ca5c-2d53-11e5-baeb-247703a38240<commit_msg>766a4b94-2d53-11e5-baeb-247703a38240<commit_after>766a4b94-2d53-11e5-baeb-247703a38240<|endoftext|>"} {"text":"<commit_before>061d50d2-2f67-11e5-993e-6c40088e03e4<commit_msg>06241086-2f67-11e5-8882-6c40088e03e4<commit_after>06241086-2f67-11e5-8882-6c40088e03e4<|endoftext|>"} {"text":"<commit_before>1352940c-585b-11e5-99fa-6c40088e03e4<commit_msg>13593224-585b-11e5-b68c-6c40088e03e4<commit_after>13593224-585b-11e5-b68c-6c40088e03e4<|endoftext|>"} {"text":"<commit_before>ffa4540c-585a-11e5-9f76-6c40088e03e4<commit_msg>ffabb4c6-585a-11e5-8e2a-6c40088e03e4<commit_after>ffabb4c6-585a-11e5-8e2a-6c40088e03e4<|endoftext|>"} {"text":"<commit_before>948aff54-35ca-11e5-a742-6c40088e03e4<commit_msg>94928768-35ca-11e5-a864-6c40088e03e4<commit_after>94928768-35ca-11e5-a864-6c40088e03e4<|endoftext|>"} {"text":"<commit_before>809e922d-2d15-11e5-af21-0401358ea401<commit_msg>809e922e-2d15-11e5-af21-0401358ea401<commit_after>809e922e-2d15-11e5-af21-0401358ea401<|endoftext|>"} {"text":"<commit_before>8e9facb8-2d14-11e5-af21-0401358ea401<commit_msg>8e9facb9-2d14-11e5-af21-0401358ea401<commit_after>8e9facb9-2d14-11e5-af21-0401358ea401<|endoftext|>"} {"text":"<commit_before>#include <Disp.h>\n#include <GPIO.h>\n#include <IRadio.h>\n\n#include <iostream>\n#include <unistd.h>\n#include <signal.h>\n#include <sstream>\n#include <string>\n\n\/\/ FUNCTION PROTOTYPING\nvoid msleep( unsigned milisec );\nvoid sig_handler( int sig );\n\n\/\/ GLOBAL VARIABLES\nbool ctrl_c_pressed = false;\n\nint main()\n{\n\tif( signal(SIGINT, sig_handler) == SIG_ERR )\n\t\tstd::cout << \"Can't catch SIGINT\" << std::endl;\n\n\tGPIO* led1 = new GPIO(4, OUT);\n\tGPIO* led2 = new GPIO(3, OUT);\n\tGPIO* led3 = new GPIO(2, OUT);\n\n\tGPIO* button1 = new GPIO(17, IN, 0.5);\n\tGPIO* button2 = new GPIO(27, IN, 0.5);\n\tGPIO* button3 = new GPIO(22, IN, 0.5);\n\n\tDisp* lcd = new Disp{14,15,18,11,23,24,9,25,8,7,10};\n\tstd::string line1{}, line2{}, str{};\n\n\tIRadio* rstream = new IRadio();\n\trstream->startStream();\n\n\tstd::string welcomeMessageLine1 = \" Welcome to: \";\n\tstd::string welcomeMessageLine2 = \" Mats' iRadio \";\n\tline1 = welcomeMessageLine1;\n\tline2 = welcomeMessageLine2;\n\n\tstd::chrono::time_point<std::chrono::system_clock> start_1, start_2;\n\tstd::chrono::duration<double> elapsed_time;\n\tstart_1 = start_2 = std::chrono::system_clock::now();\n\n\twhile(1)\n\t{\n\t\tled1->setValue( button1->getValue() );\n\t\tled2->setValue( button2->getValue() );\n\t\tled3->setValue( button3->getValue() );\n\n\t\telapsed_time = std::chrono::system_clock::now() - start_1;\n\t\tif( elapsed_time.count() >= 15.0 )\n\t\t{\n\t\t\tstart_1 = std::chrono::system_clock::now();\n\n\t\t\tif( !rstream->streamIsRunning() )\n\t\t\t{\n\t\t\t\tline1 = welcomeMessageLine1;\n\t\t\t\tline2 = welcomeMessageLine2;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\trstream->getStreamInfos();\n\t\t\t\tif( rstream->streamHasChanged() )\n\t\t\t\t{\n\t\t\t\t\tline1 = \"[\" + std::to_string(rstream->getStreamNr()) + \"] \" + rstream->getStreamName() + \" \";\n\t\t\t\t\tline2 = rstream->getInterpret() + \" - \" + rstream->getTitle() + \" \";\n\n\t\t\t\t\tstd::cout << \"[\" << rstream->getStreamNr() << \"] \" << rstream->getStreamName() << \", \" << rstream->getInterpret() << \" - \" << rstream->getTitle() << \"\\n\";\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\telapsed_time = std::chrono::system_clock::now() - start_2;\n\t\tif( elapsed_time.count() >= 1.0 )\n\t\t{\n\t\t\tstart_2 = std::chrono::system_clock::now();\n\t\t\tif( lcd->disp_job==lcd->no_job )\n\t\t\t{\n\t\t\t\tif( !line1.empty() )\n\t\t\t\t{\n\t\t\t\t\tif( line1.size()<DISP_LINE_LENGTH+3 )\n\t\t\t\t\t{\n\t\t\t\t\t\tstr = line1.substr(0,DISP_LINE_LENGTH);\n\t\t\t\t\t\tlcd->writeText( &str, 1 );\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tstr = line1.substr(0,DISP_LINE_LENGTH);\n\t\t\t\t\t\tline1 = line1.substr(1) + line1.at(0);\n\t\t\t\t\t\tlcd->writeText( &str, 1 );\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif( !line2.empty() )\n\t\t\t\t{\n\t\t\t\t\tif( line2.size()<DISP_LINE_LENGTH+3 )\n\t\t\t\t\t{\n\t\t\t\t\t\tstr = line2.substr(0,DISP_LINE_LENGTH);\n\t\t\t\t\t\tlcd->writeText( &str, 2 );\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tstr = line2.substr(0,DISP_LINE_LENGTH);\n\t\t\t\t\t\tline2 = line2.substr(1) + line2.at(0);\n\t\t\t\t\t\tlcd->writeText( &str, 2 );\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tlcd->process();\n\n\t\tif( !button1->getDebouncedValue() )\n\t\t\trstream->increaseStreamNr();\n\t\tif( !button2->getDebouncedValue() )\n\t\t\trstream->stopOrResumeStream();\n\t\tif( !button3->getDebouncedValue() )\n\t\t\trstream->decreaseStreamNr();\n\n\t\tif( ctrl_c_pressed )\n\t\t\tbreak;\n\t}\n\n\tdelete lcd;\n\tdelete led1; delete led2; delete led3;\n\tdelete button1; delete button2; delete button3;\n\tdelete rstream;\n}\n\nvoid msleep( unsigned milisec )\n{\n\tfor(unsigned i=0; i<milisec; ++i)\n\t\tusleep( 1000 );\n}\n\nvoid sig_handler( int sig )\n{\n\tif (sig == SIGINT)\n\t\tctrl_c_pressed = true;\n}\n<commit_msg>Change to 20sec refreshing time<commit_after>#include <Disp.h>\n#include <GPIO.h>\n#include <IRadio.h>\n\n#include <iostream>\n#include <unistd.h>\n#include <signal.h>\n#include <sstream>\n#include <string>\n\n\/\/ FUNCTION PROTOTYPING\nvoid msleep( unsigned milisec );\nvoid sig_handler( int sig );\n\n\/\/ GLOBAL VARIABLES\nbool ctrl_c_pressed = false;\n\nint main()\n{\n\tif( signal(SIGINT, sig_handler) == SIG_ERR )\n\t\tstd::cout << \"Can't catch SIGINT\" << std::endl;\n\n\tGPIO* led1 = new GPIO(4, OUT);\n\tGPIO* led2 = new GPIO(3, OUT);\n\tGPIO* led3 = new GPIO(2, OUT);\n\n\tGPIO* button1 = new GPIO(17, IN, 0.5);\n\tGPIO* button2 = new GPIO(27, IN, 0.5);\n\tGPIO* button3 = new GPIO(22, IN, 0.5);\n\n\tDisp* lcd = new Disp{14,15,18,11,23,24,9,25,8,7,10};\n\tstd::string line1{}, line2{}, str{};\n\n\tIRadio* rstream = new IRadio();\n\trstream->startStream();\n\n\tstd::string welcomeMessageLine1 = \" Welcome to: \";\n\tstd::string welcomeMessageLine2 = \" Mats' iRadio \";\n\tline1 = welcomeMessageLine1;\n\tline2 = welcomeMessageLine2;\n\n\tstd::chrono::time_point<std::chrono::system_clock> start_1, start_2;\n\tstd::chrono::duration<double> elapsed_time;\n\tstart_1 = start_2 = std::chrono::system_clock::now();\n\n\twhile(1)\n\t{\n\t\tled1->setValue( button1->getValue() );\n\t\tled2->setValue( button2->getValue() );\n\t\tled3->setValue( button3->getValue() );\n\n\t\telapsed_time = std::chrono::system_clock::now() - start_1;\n\t\tif( elapsed_time.count() >= 20.0 )\n\t\t{\n\t\t\tstart_1 = std::chrono::system_clock::now();\n\n\t\t\tif( !rstream->streamIsRunning() )\n\t\t\t{\n\t\t\t\tline1 = welcomeMessageLine1;\n\t\t\t\tline2 = welcomeMessageLine2;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\trstream->getStreamInfos();\n\t\t\t\tif( rstream->streamHasChanged() )\n\t\t\t\t{\n\t\t\t\t\tline1 = \"[\" + std::to_string(rstream->getStreamNr()) + \"] \" + rstream->getStreamName() + \" \";\n\t\t\t\t\tline2 = rstream->getInterpret() + \" - \" + rstream->getTitle() + \" \";\n\n\t\t\t\t\t\/\/std::cout << \"[\" << rstream->getStreamNr() << \"] \" << rstream->getStreamName() << \", \" << rstream->getInterpret() << \" - \" << rstream->getTitle() << \"\\n\";\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\telapsed_time = std::chrono::system_clock::now() - start_2;\n\t\tif( elapsed_time.count() >= 1.0 )\n\t\t{\n\t\t\tstart_2 = std::chrono::system_clock::now();\n\t\t\tif( lcd->disp_job==lcd->no_job )\n\t\t\t{\n\t\t\t\tif( !line1.empty() )\n\t\t\t\t{\n\t\t\t\t\tif( line1.size()<DISP_LINE_LENGTH+3 )\n\t\t\t\t\t{\n\t\t\t\t\t\tstr = line1.substr(0,DISP_LINE_LENGTH);\n\t\t\t\t\t\tlcd->writeText( &str, 1 );\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tstr = line1.substr(0,DISP_LINE_LENGTH);\n\t\t\t\t\t\tline1 = line1.substr(1) + line1.at(0);\n\t\t\t\t\t\tlcd->writeText( &str, 1 );\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif( !line2.empty() )\n\t\t\t\t{\n\t\t\t\t\tif( line2.size()<DISP_LINE_LENGTH+3 )\n\t\t\t\t\t{\n\t\t\t\t\t\tstr = line2.substr(0,DISP_LINE_LENGTH);\n\t\t\t\t\t\tlcd->writeText( &str, 2 );\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tstr = line2.substr(0,DISP_LINE_LENGTH);\n\t\t\t\t\t\tline2 = line2.substr(1) + line2.at(0);\n\t\t\t\t\t\tlcd->writeText( &str, 2 );\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tlcd->process();\n\n\t\tif( !button1->getDebouncedValue() )\n\t\t\trstream->increaseStreamNr();\n\t\tif( !button2->getDebouncedValue() )\n\t\t\trstream->stopOrResumeStream();\n\t\tif( !button3->getDebouncedValue() )\n\t\t\trstream->decreaseStreamNr();\n\n\t\tif( ctrl_c_pressed )\n\t\t\tbreak;\n\t}\n\n\tdelete lcd;\n\tdelete led1; delete led2; delete led3;\n\tdelete button1; delete button2; delete button3;\n\tdelete rstream;\n}\n\nvoid msleep( unsigned milisec )\n{\n\tfor(unsigned i=0; i<milisec; ++i)\n\t\tusleep( 1000 );\n}\n\nvoid sig_handler( int sig )\n{\n\tif (sig == SIGINT)\n\t\tctrl_c_pressed = true;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/Includes.\n#include <fstream>\n#include <iostream>\n#include <string>\n#include \"game.h\"\n#include \"main.h\"\n#include \"baseFunctions.h\"\n\n\/\/We'll only use what we need.\nusing std::cout;\nusing std::cin;\nusing std::string;\nusing std::getline;\nusing std::ifstream;\n\nvoid cls();\nvoid prompt(string tPrompt);\nvoid newGame();\nvoid mainMenu();\n\n\/\/Location the user is in the game, used for labeling input.\nstring currentMenu = \"____LOADING____\";\n\n\/\/All variables.\nstring gName = \"vAttack\";\nstring gVersion = \"Alpha 0.1.0\";\n \n\/\/Files.\nstring line;\nifstream information;\n\nint main()\n{\n \n mainMenu();\n\n return 0;\n}\n\nvoid mainMenu()\n{ \n \/\/General input variables for the game.\n int uInp;\n \n \/\/Loop variables.\n int mLoop = 0;\n \n \/\/Menu loop.\n while (mLoop <= 10)\n {\n mLoop = 0;\n \/\/Main menu.\n currentMenu = \"Main\";\n cout << \"Welcome to \" << gName << \"\\nVersion: \" << gVersion << \"\\n\";\n cout << \"================================================\\n\";\n cout << \"| 1 = New game | 2 = Load game | 3 = Save game |\\n\";\n cout << \"| 4 = Help | 5 = About | 9 = Exit. |\\n\";\n cout << \"================================================\\n\";\n cout << currentMenu << \" > \";\n cin >> uInp;\n \n \/\/Make sure the input is an int.\n if (cin.fail())\n {\n cin.clear(); cin.ignore(); cin.sync();\n mLoop++;\n }\n \n cls();\n \n switch(uInp)\n { \n case 9:\n \/\/Exit the game.\n mLoop = 11;\n break;\n \n case 5:\n \/\/Show information about the game.\n information.open(\"about.txt\");\n if (information.is_open())\n {\n while (getline(information,line)) { cout << line << \"\\n\"; }\n prompt(\"Press enter to return to the main menu.\");\n information.close();\n cls();\n break;\n } else { prompt(\"Unable to open file. Press enter to return to main menu.\"); information.close(); break; }\n \n case 4:\n \/\/Help the poor user figure out what this is.\n information.open(\"help.txt\");\n if (information.is_open())\n {\n while (getline(information,line)) { cout << line << \"\\n\"; }\n prompt(\"Press enter to return to the main menu.\");\n information.close();\n cls();\n break;\n }\n \n case 3:\n \/\/TODO: Save the game.\n \n case 2:\n \/\/TODO: Load a game.\n \n case 1:\n newGame();\n \n default:\n prompt(\"Not a menu item, press enter.\");\n cls();\n }\n \n \/\/Continue the loop.\n mLoop++;\n }\n \n \/\/Make sure the file is closed before exit.\n information.close();\n}<commit_msg>Added a comment.<commit_after>\/\/Includes.\n#include <fstream>\n#include <iostream>\n#include <string>\n#include \"game.h\"\n#include \"main.h\"\n#include \"baseFunctions.h\"\n\n\/\/We'll only use what we need.\nusing std::cout;\nusing std::cin;\nusing std::string;\nusing std::getline;\nusing std::ifstream;\n\nvoid cls();\nvoid prompt(string tPrompt);\nvoid newGame();\nvoid mainMenu();\n\n\/\/Location the user is in the game, used for labeling input.\nstring currentMenu = \"____LOADING____\";\n\n\/\/All variables.\nstring gName = \"vAttack\";\nstring gVersion = \"Alpha 0.1.0\";\n \n\/\/Files.\nstring line;\nifstream information;\n\nint main()\n{\n \/\/Run the main menu loop, and wait for instruction.\n mainMenu();\n\n return 0;\n}\n\nvoid mainMenu()\n{ \n \/\/General input variables for the game.\n int uInp;\n \n \/\/Loop variables.\n int mLoop = 0;\n \n \/\/Menu loop.\n while (mLoop <= 10)\n {\n mLoop = 0;\n \/\/Main menu.\n currentMenu = \"Main\";\n cout << \"Welcome to \" << gName << \"\\nVersion: \" << gVersion << \"\\n\";\n cout << \"================================================\\n\";\n cout << \"| 1 = New game | 2 = Load game | 3 = Save game |\\n\";\n cout << \"| 4 = Help | 5 = About | 9 = Exit. |\\n\";\n cout << \"================================================\\n\";\n cout << currentMenu << \" > \";\n cin >> uInp;\n \n \/\/Make sure the input is an int.\n if (cin.fail())\n {\n cin.clear(); cin.ignore(); cin.sync();\n mLoop++;\n }\n \n cls();\n \n switch(uInp)\n { \n case 9:\n \/\/Exit the game.\n mLoop = 11;\n break;\n \n case 5:\n \/\/Show information about the game.\n information.open(\"about.txt\");\n if (information.is_open())\n {\n while (getline(information,line)) { cout << line << \"\\n\"; }\n prompt(\"Press enter to return to the main menu.\");\n information.close();\n cls();\n break;\n } else { prompt(\"Unable to open file. Press enter to return to main menu.\"); information.close(); break; }\n \n case 4:\n \/\/Help the poor user figure out what this is.\n information.open(\"help.txt\");\n if (information.is_open())\n {\n while (getline(information,line)) { cout << line << \"\\n\"; }\n prompt(\"Press enter to return to the main menu.\");\n information.close();\n cls();\n break;\n }\n \n case 3:\n \/\/TODO: Save the game.\n \n case 2:\n \/\/TODO: Load a game.\n \n case 1:\n newGame();\n \n default:\n prompt(\"Not a menu item, press enter.\");\n cls();\n }\n \n \/\/Continue the loop.\n mLoop++;\n }\n \n \/\/Make sure the file is closed before exit.\n information.close();\n}<|endoftext|>"} {"text":"<commit_before>e3df6fde-313a-11e5-ad61-3c15c2e10482<commit_msg>e3e57d0c-313a-11e5-8a27-3c15c2e10482<commit_after>e3e57d0c-313a-11e5-8a27-3c15c2e10482<|endoftext|>"} {"text":"<commit_before>809e9220-2d15-11e5-af21-0401358ea401<commit_msg>809e9221-2d15-11e5-af21-0401358ea401<commit_after>809e9221-2d15-11e5-af21-0401358ea401<|endoftext|>"} {"text":"<commit_before>1b52e2dc-2f67-11e5-bc51-6c40088e03e4<commit_msg>1b5981d2-2f67-11e5-bca9-6c40088e03e4<commit_after>1b5981d2-2f67-11e5-bca9-6c40088e03e4<|endoftext|>"} {"text":"<commit_before>6fcccbb6-2fa5-11e5-a7e9-00012e3d3f12<commit_msg>6fcec782-2fa5-11e5-b44e-00012e3d3f12<commit_after>6fcec782-2fa5-11e5-b44e-00012e3d3f12<|endoftext|>"} {"text":"<commit_before>27b44ab5-2e4f-11e5-8ae4-28cfe91dbc4b<commit_msg>27bc4c8c-2e4f-11e5-b0fd-28cfe91dbc4b<commit_after>27bc4c8c-2e4f-11e5-b0fd-28cfe91dbc4b<|endoftext|>"} {"text":"<commit_before>0a266912-585b-11e5-ad0c-6c40088e03e4<commit_msg>0a2df966-585b-11e5-b3f6-6c40088e03e4<commit_after>0a2df966-585b-11e5-b3f6-6c40088e03e4<|endoftext|>"} {"text":"<commit_before>91b59e35-2d3e-11e5-8a81-c82a142b6f9b<commit_msg>9224394a-2d3e-11e5-9e74-c82a142b6f9b<commit_after>9224394a-2d3e-11e5-9e74-c82a142b6f9b<|endoftext|>"} {"text":"<commit_before>#include \"cells.hpp\"\n#include <boost\/algorithm\/string.hpp>\n#include <boost\/exception\/diagnostic_information.hpp> \n#include <boost\/filesystem\/fstream.hpp>\n#include <boost\/lexical_cast.hpp>\n#include <iostream>\n#include <set>\n\n\nstruct format_exception : virtual std::exception, virtual boost::exception {};\ntypedef boost::error_info<struct row_, std::string> format_row;\n\n\nvoid load(boost::filesystem::path const& directory, cells_type& cells)\n{\n\tstd::size_t const expected_columns(126);\n\n\tboost::filesystem::directory_iterator end;\n\tfor(boost::filesystem::directory_iterator iter(directory); iter != end; ++ iter)\n\t{\n\t\tauto const path(iter->path());\n\t\tif(boost::iequals(path.extension().string(), \".txt\"))\n\t\t{\n\t\t\tboost::filesystem::ifstream stream(path);\n\t\t\tbool header(true);\n\t\t\tstd::string row;\n\t\t\twhile(std::getline(stream, row))\n\t\t\t{\n\t\t\t\tstd::vector<std::string> columns;\n\t\t\t\tboost::split(columns, row, boost::is_any_of(\"\\t\"));\n\t\t\t\tif(header)\n\t\t\t\t{\n\t\t\t\t\tif(columns.size() == expected_columns)\n\t\t\t\t\t{\n\t\t\t\t\t\tstd::cout << \"Loading \" << path << std::endl;\n\t\t\t\t\t\theader = false;\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tstd::cout << \"Ignoring \" << path << std::endl;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif(columns.size() != expected_columns)\n\t\t\t\t{\n\t\t\t\t\tBOOST_THROW_EXCEPTION(format_exception() << format_row(row));\n\t\t\t\t}\n\n\t\t\t\tcell_type cell;\n\t\t\t\tcell.path = path; \n\t\t\t\tcell.id = boost::lexical_cast<std::int64_t>(columns[3]);\n\t\t\t\tcell.x = boost::lexical_cast<std::int64_t>(columns[7]);\n\t\t\t\tcell.y = boost::lexical_cast<std::int64_t>(columns[8]);\n\t\t\t\tcell.phenotype = boost::trim_copy(columns[123]);\n\t\t\t\tif(cell.phenotype.empty())\n\t\t\t\t{\n\t\t\t\t\tstd::cout << \"\\tDiscarding cell id \" << cell.id << \" with unknown phenotype\" << std::endl;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tcells.push_back(cell);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\n\nvoid generate(boost::filesystem::path const& directory, cells_type& cells)\n{\n\tstd::set<std::string> phenotypes;\n\tfor(auto const& cell: cells)\n\t{\n\t\tphenotypes.insert(cell.phenotype);\n\t}\n\n\tfor(auto const& phenotype: phenotypes)\n\t{\n\t\tboost::filesystem::path path(directory \/ (phenotype + \".txt\"));\n\t\tstd::cout << \"Generating \" << path << std::endl;\n\t\tboost::filesystem::ofstream stream(path, std::ios::trunc);\n\t\tstream << \"Path\\tCell ID\\tCell X Position\\tCell Y Position\";\n\t\tfor(auto const& other_phenotype: phenotypes)\n\t\t{\n\t\t\tif(other_phenotype != phenotype)\n\t\t\t{\n\t\t\t\tstream << \"\\t\" << other_phenotype << \" Min. Distance\" << \"\\t\" << other_phenotype << \" Nearest ID\";\n\t\t\t}\n\t\t}\n\t\tstream << std::endl;\n\t\tfor(auto const& cell: cells)\n\t\t{\n\t\t\tif(cell.phenotype != phenotype)\n\t\t\t{\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tstream << cell.path << \"\\t\" << cell.id << \"\\t\" << cell.x << \"\\t\" << cell.y;\n\t\t\tfor(auto const& other_phenotype: phenotypes)\n\t\t\t{\n\t\t\t\tif(other_phenotype != phenotype)\n\t\t\t\t{\n\t\t\t\t\tdouble nearest_distance(std::numeric_limits<double>::max());\n\t\t\t\t\tstd::int64_t nearest_id;\n\t\t\t\t\tfor(auto const& other_cell: cells)\n\t\t\t\t\t{\n\t\t\t\t\t\tif(other_cell.phenotype == other_phenotype)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tstd::int64_t const x_distance(cell.x - other_cell.x);\n\t\t\t\t\t\t\tstd::int64_t const y_distance(cell.y - other_cell.y);\n\t\t\t\t\t\t\tdouble const distance(std::sqrt((x_distance * x_distance) + (y_distance * y_distance)));\n\t\t\t\t\t\t\tif(distance < nearest_distance)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tnearest_distance = distance;\n\t\t\t\t\t\t\t\tnearest_id = other_cell.id;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tstream << \"\\t\" << std::fixed << std::setprecision(0) << nearest_distance << \"\\t\" << nearest_id;\n\t\t\t\t}\n\t\t\t}\n\t\t\tstream << std::endl;\n\t\t}\n\t}\n}\n\n\nint main(int argc, char* argv[])\n{\n\ttry\n\t{\n\t\tauto const directory(boost::filesystem::current_path());\n\t\tcells_type cells;\n\t\tload(directory, cells);\n\t\tgenerate(directory, cells);\n\t\treturn 0;\n\t}\n\n\tcatch(...)\n\t{\n\t\tstd::cout << boost::current_exception_diagnostic_information() << std::endl;\n\t\treturn 1;\n\t}\n}<commit_msg>Make loading more robust to format changes<commit_after>#include \"cells.hpp\"\n#include <boost\/algorithm\/string.hpp>\n#include <boost\/exception\/diagnostic_information.hpp> \n#include <boost\/filesystem\/fstream.hpp>\n#include <boost\/lexical_cast.hpp>\n#include <iostream>\n#include <map>\n#include <set>\n\n\nstruct format_exception : virtual std::exception, virtual boost::exception {};\ntypedef boost::error_info<struct row_, std::string> format_row;\n\n\nvoid load(boost::filesystem::path const& directory, cells_type& cells)\n{\n\tchar const* cell_id_field(\"Cell ID\");\n\tchar const* cell_x_field(\"Cell X Position\");\n\tchar const* cell_y_field(\"Cell Y Position\");\n\tchar const* phenotype_field(\"Phenotype\");\n\n\tboost::filesystem::directory_iterator end;\n\tfor(boost::filesystem::directory_iterator iter(directory); iter != end; ++ iter)\n\t{\n\t\tauto const path(iter->path());\n\t\tif(boost::iequals(path.extension().string(), \".txt\"))\n\t\t{\n\t\t\tboost::filesystem::ifstream stream(path);\n\t\t\tstd::map<std::string, std::size_t> header;\n\t\t\tstd::string row;\n\t\t\twhile(std::getline(stream, row))\n\t\t\t{\n\t\t\t\tstd::vector<std::string> columns;\n\t\t\t\tboost::split(columns, row, boost::is_any_of(\"\\t\"));\n\t\t\t\tif(header.empty())\n\t\t\t\t{\n\t\t\t\t\tstd::size_t index(0);\n\t\t\t\t\tfor(auto const& column: columns)\n\t\t\t\t\t{\n\t\t\t\t\t\theader.insert(std::make_pair(column, index ++));\n\t\t\t\t\t}\n\n\t\t\t\t\tif(header.count(cell_id_field) && header.count(cell_x_field) && header.count(cell_y_field) && header.count(phenotype_field))\n\t\t\t\t\t{\n\t\t\t\t\t\tstd::cout << \"Loading \" << path << std::endl;\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tstd::cout << \"Ignoring \" << path << std::endl;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif(columns.size() != header.size())\n\t\t\t\t{\n\t\t\t\t\tBOOST_THROW_EXCEPTION(format_exception() << format_row(row));\n\t\t\t\t}\n\n\t\t\t\tcell_type cell;\n\t\t\t\tcell.path = path; \n\t\t\t\tcell.id = boost::lexical_cast<std::int64_t>(columns[header[cell_id_field]]);\n\t\t\t\tcell.x = boost::lexical_cast<std::int64_t>(columns[header[cell_x_field]]);\n\t\t\t\tcell.y = boost::lexical_cast<std::int64_t>(columns[header[cell_y_field]]);\n\t\t\t\tcell.phenotype = boost::trim_copy(columns[header[phenotype_field]]);\n\t\t\t\tif(cell.phenotype.empty())\n\t\t\t\t{\n\t\t\t\t\tstd::cout << \"\\tDiscarding cell id \" << cell.id << \" with unknown phenotype\" << std::endl;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tcells.push_back(cell);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\n\nvoid generate(boost::filesystem::path const& directory, cells_type& cells)\n{\n\tstd::set<std::string> phenotypes;\n\tfor(auto const& cell: cells)\n\t{\n\t\tphenotypes.insert(cell.phenotype);\n\t}\n\n\tfor(auto const& phenotype: phenotypes)\n\t{\n\t\tboost::filesystem::path path(directory \/ (phenotype + \".txt\"));\n\t\tstd::cout << \"Generating \" << path << std::endl;\n\t\tboost::filesystem::ofstream stream(path, std::ios::trunc);\n\t\tstream << \"Path\\tCell ID\\tCell X Position\\tCell Y Position\";\n\t\tfor(auto const& other_phenotype: phenotypes)\n\t\t{\n\t\t\tif(other_phenotype != phenotype)\n\t\t\t{\n\t\t\t\tstream << \"\\t\" << other_phenotype << \" Min. Distance\" << \"\\t\" << other_phenotype << \" Nearest ID\";\n\t\t\t}\n\t\t}\n\t\tstream << std::endl;\n\t\tfor(auto const& cell: cells)\n\t\t{\n\t\t\tif(cell.phenotype != phenotype)\n\t\t\t{\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tstream << cell.path << \"\\t\" << cell.id << \"\\t\" << cell.x << \"\\t\" << cell.y;\n\t\t\tfor(auto const& other_phenotype: phenotypes)\n\t\t\t{\n\t\t\t\tif(other_phenotype != phenotype)\n\t\t\t\t{\n\t\t\t\t\tdouble nearest_distance(std::numeric_limits<double>::max());\n\t\t\t\t\tstd::int64_t nearest_id;\n\t\t\t\t\tfor(auto const& other_cell: cells)\n\t\t\t\t\t{\n\t\t\t\t\t\tif(other_cell.phenotype == other_phenotype)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tstd::int64_t const x_distance(cell.x - other_cell.x);\n\t\t\t\t\t\t\tstd::int64_t const y_distance(cell.y - other_cell.y);\n\t\t\t\t\t\t\tdouble const distance(std::sqrt((x_distance * x_distance) + (y_distance * y_distance)));\n\t\t\t\t\t\t\tif(distance < nearest_distance)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tnearest_distance = distance;\n\t\t\t\t\t\t\t\tnearest_id = other_cell.id;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tstream << \"\\t\" << std::fixed << std::setprecision(0) << nearest_distance << \"\\t\" << nearest_id;\n\t\t\t\t}\n\t\t\t}\n\t\t\tstream << std::endl;\n\t\t}\n\t}\n}\n\n\nint main(int argc, char* argv[])\n{\n\ttry\n\t{\n\t\tauto const directory(boost::filesystem::current_path());\n\t\tcells_type cells;\n\t\tload(directory, cells);\n\t\tgenerate(directory, cells);\n\t\treturn 0;\n\t}\n\n\tcatch(...)\n\t{\n\t\tstd::cout << boost::current_exception_diagnostic_information() << std::endl;\n\t\treturn 1;\n\t}\n}<|endoftext|>"} {"text":"<commit_before>e2ebd7f3-327f-11e5-95e3-9cf387a8033e<commit_msg>e2f2e3c5-327f-11e5-9582-9cf387a8033e<commit_after>e2f2e3c5-327f-11e5-9582-9cf387a8033e<|endoftext|>"} {"text":"<commit_before>db82505e-327f-11e5-8351-9cf387a8033e<commit_msg>db8a68ab-327f-11e5-8267-9cf387a8033e<commit_after>db8a68ab-327f-11e5-8267-9cf387a8033e<|endoftext|>"} {"text":"<commit_before>8d6dfd8f-2d14-11e5-af21-0401358ea401<commit_msg>8d6dfd90-2d14-11e5-af21-0401358ea401<commit_after>8d6dfd90-2d14-11e5-af21-0401358ea401<|endoftext|>"} {"text":"<commit_before>f129264f-327f-11e5-bc66-9cf387a8033e<commit_msg>f12f1630-327f-11e5-b116-9cf387a8033e<commit_after>f12f1630-327f-11e5-b116-9cf387a8033e<|endoftext|>"} {"text":"<commit_before>\/* This file is part of the KDE project\n Copyright (C) 2007 Matthias Kretz <kretz@kde.org>\n\n This library is free software; you can redistribute it and\/or\n modify it under the terms of the GNU Library General Public\n License version 2 as published by the Free Software Foundation.\n\n This library is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n Library General Public License for more details.\n\n You should have received a copy of the GNU Library General Public License\n along with this library; see the file COPYING.LIB. If not, write to\n the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,\n Boston, MA 02110-1301, USA.\n\n*\/\n\n#include \"kdepluginfactory.h\"\n#include \"kiomediastream.h\"\n\n#include <QtCore\/QFile>\n#include <QtCore\/QtPlugin>\n#include <QtCore\/QCoreApplication>\n\n#include <kaboutdata.h>\n#include <kdebug.h>\n#include <kcomponentdata.h>\n#include <kglobal.h>\n#include <kicon.h>\n#include <klibloader.h>\n#include <klocale.h>\n#include <kmessagebox.h>\n#include <kmimetype.h>\n#include <knotification.h>\n#include <kservice.h>\n#include <kservicetypetrader.h>\n\nnamespace Phonon\n{\n\nK_GLOBAL_STATIC_WITH_ARGS(KComponentData, mainComponentData, (QCoreApplication::applicationName().toUtf8()))\nK_GLOBAL_STATIC_WITH_ARGS(KComponentData, phononComponentData, (\"phonon\"))\n\nstatic void ensureMainComponentData()\n{\n if (!KGlobal::hasMainComponent()) {\n \/\/ a pure Qt application does not have a KComponentData object,\n \/\/ we'll give it one.\n *mainComponentData;\n qAddPostRoutine(mainComponentData.destroy);\n Q_ASSERT(KGlobal::hasMainComponent());\n }\n}\n\nstatic const KComponentData &componentData()\n{\n ensureMainComponentData();\n return *phononComponentData;\n}\n\nKdePlatformPlugin::KdePlatformPlugin()\n{\n ensureMainComponentData();\n KGlobal::locale()->insertCatalog(QLatin1String(\"phonon_kde\"));\n}\n\nAbstractMediaStream *KdePlatformPlugin::createMediaStream(const QUrl &url, QObject *parent)\n{\n return new KioMediaStream(url, parent);\n}\n\nQIcon KdePlatformPlugin::icon(const QString &name) const\n{\n return KIcon(name);\n}\n\nvoid KdePlatformPlugin::notification(const char *notificationName, const QString &text,\n const QStringList &actions, QObject *receiver,\n const char *actionSlot) const\n{\n KNotification *notification = new KNotification(notificationName);\n notification->setComponentData(componentData());\n notification->setText(text);\n \/\/notification->setPixmap(...);\n notification->addContext(QLatin1String(\"Application\"), KGlobal::mainComponent().componentName());\n if (!actions.isEmpty() && receiver && actionSlot) {\n notification->setActions(actions);\n QObject::connect(notification, SIGNAL(activated(unsigned int)), receiver, actionSlot);\n }\n notification->sendEvent();\n}\n\nQString KdePlatformPlugin::applicationName() const\n{\n ensureMainComponentData();\n const KAboutData *ad = KGlobal::mainComponent().aboutData();\n if (ad) {\n const QString programName = ad->programName();\n if (programName.isEmpty()) {\n return KGlobal::mainComponent().componentName();\n }\n return programName;\n }\n return KGlobal::mainComponent().componentName();\n}\n\n#undef PHONON_LOAD_BACKEND_GLOBAL\n\nQObject *KdePlatformPlugin::createBackend(KService::Ptr newService)\n{\n KPluginFactory *factory = 0;\n QString errorReason;\n#ifdef PHONON_LOAD_BACKEND_GLOBAL\n \/\/ This code is in here temporarily until NMM gets fixed.\n \/\/ Currently the NMM backend will fail with undefined symbols if\n \/\/ the backend is not loaded with global symbol resolution\n \/\/KLibrary *library = KLibLoader::self()->factory(newService->library(), QLibrary::ExportExternalSymbolsHint);\n \/\/if (library) {\n \/\/ factory = library->factory();\n \/\/}\n factory = KLibLoader::self()->factory(QFile::encodeName(newService->library()), QLibrary::ExportExternalSymbolsHint);\n if (!factory) {\n errorReason = KLibLoader::self()->lastErrorMessage();\n }\n#else\n KPluginLoader loader(QFile::encodeName(newService->library()));\n factory = loader.factory();\n if (!factory) {\n errorReason = loader.errorString();\n }\n#endif\n if (!factory) {\n kError(600) << \"Can not create factory for \" << newService->name() <<\n \":\\n\" << errorReason << endl;\n\n KMessageBox::error(0,\n QLatin1String(\"<html>\")\n + i18n(\"Unable to use the <b>%1<\/b> Multimedia Backend:\", newService->name())\n + QLatin1Char('\\n')\n + errorReason\n + QLatin1String(\"<\/html>\"));\n return false;\n }\n\n QObject *backend = factory->create<QObject>();\n if (0 == backend) {\n QString errorReason = i18n(\"create method returned 0\");\n kError(600) << \"Can not create backend object from factory for \" <<\n newService->name() << \", \" << newService->library() << \":\\n\" << errorReason << endl;\n\n KMessageBox::error(0,\n QLatin1String(\"<qt>\")\n + i18n(\"Unable to use the <b>%1<\/b> Multimedia Backend:\", newService->name())\n + QLatin1Char('\\n')\n + errorReason\n + QLatin1String(\"<qt>\"));\n return false;\n }\n\n kDebug() << \"using backend: \" << newService->name();\n return backend;\n}\n\nQObject *KdePlatformPlugin::createBackend()\n{\n ensureMainComponentData();\n const KService::List offers = KServiceTypeTrader::self()->query(\"PhononBackend\",\n \"Type == 'Service' and [X-KDE-PhononBackendInfo-InterfaceVersion] == 1\");\n if (offers.isEmpty()) {\n KMessageBox::error(0, i18n(\"Unable to find a Multimedia Backend\"));\n return 0;\n }\n\n KService::List::const_iterator it = offers.begin();\n const KService::List::const_iterator end = offers.end();\n while (it != end) {\n QObject *backend = createBackend(*it);\n if (backend) {\n return backend;\n }\n ++it;\n }\n return 0;\n}\n\nQObject *KdePlatformPlugin::createBackend(const QString &library, const QString &version)\n{\n ensureMainComponentData();\n QString additionalConstraints = QLatin1String(\" and Library == '\") + library + QLatin1Char('\\'');\n if (!version.isEmpty()) {\n additionalConstraints += QLatin1String(\" and [X-KDE-PhononBackendInfo-Version] == '\")\n + version + QLatin1Char('\\'');\n }\n const KService::List offers = KServiceTypeTrader::self()->query(QLatin1String(\"PhononBackend\"),\n QString(\"Type == 'Service' and [X-KDE-PhononBackendInfo-InterfaceVersion] == 1%1\")\n .arg(additionalConstraints));\n if (offers.isEmpty()) {\n KMessageBox::error(0, i18n(\"Unable to find the requested Multimedia Backend\"));\n return 0;\n }\n\n KService::List::const_iterator it = offers.begin();\n const KService::List::const_iterator end = offers.end();\n while (it != end) {\n QObject *backend = createBackend(*it);\n if (backend) {\n return backend;\n }\n ++it;\n }\n return 0;\n}\n\nbool KdePlatformPlugin::isMimeTypeAvailable(const QString &mimeType) const\n{\n ensureMainComponentData();\n const KService::List offers = KServiceTypeTrader::self()->query(\"PhononBackend\",\n \"Type == 'Service' and [X-KDE-PhononBackendInfo-InterfaceVersion] == 1\");\n if (!offers.isEmpty()) {\n return offers.first()->hasMimeType(KMimeType::mimeType(mimeType).data());\n }\n return false;\n}\n\nvoid KdePlatformPlugin::saveVolume(const QString &outputName, qreal volume)\n{\n ensureMainComponentData();\n KConfigGroup config(KGlobal::config(), \"Phonon::AudioOutput\");\n config.writeEntry(outputName + \"_Volume\", volume);\n}\n\nqreal KdePlatformPlugin::loadVolume(const QString &outputName) const\n{\n ensureMainComponentData();\n KConfigGroup config(KGlobal::config(), \"Phonon::AudioOutput\");\n return config.readEntry<qreal>(outputName + \"_Volume\", 1.0);\n}\n\n} \/\/ namespace Phonon\n\nQ_EXPORT_PLUGIN2(phonon_platform_kde, Phonon::KdePlatformPlugin)\n\n#include \"kdepluginfactory.moc\"\n\/\/ vim: sw=4 sts=4 et tw=100\n<commit_msg>simplify backend loading code for the non-ExportExternalSymbols case<commit_after>\/* This file is part of the KDE project\n Copyright (C) 2007 Matthias Kretz <kretz@kde.org>\n\n This library is free software; you can redistribute it and\/or\n modify it under the terms of the GNU Library General Public\n License version 2 as published by the Free Software Foundation.\n\n This library is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n Library General Public License for more details.\n\n You should have received a copy of the GNU Library General Public License\n along with this library; see the file COPYING.LIB. If not, write to\n the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,\n Boston, MA 02110-1301, USA.\n\n*\/\n\n#include \"kdepluginfactory.h\"\n#include \"kiomediastream.h\"\n\n#include <QtCore\/QFile>\n#include <QtCore\/QtPlugin>\n#include <QtCore\/QCoreApplication>\n\n#include <kaboutdata.h>\n#include <kdebug.h>\n#include <kcomponentdata.h>\n#include <kglobal.h>\n#include <kicon.h>\n#include <klibloader.h>\n#include <klocale.h>\n#include <kmessagebox.h>\n#include <kmimetype.h>\n#include <knotification.h>\n#include <kservice.h>\n#include <kservicetypetrader.h>\n\nnamespace Phonon\n{\n\nK_GLOBAL_STATIC_WITH_ARGS(KComponentData, mainComponentData, (QCoreApplication::applicationName().toUtf8()))\nK_GLOBAL_STATIC_WITH_ARGS(KComponentData, phononComponentData, (\"phonon\"))\n\nstatic void ensureMainComponentData()\n{\n if (!KGlobal::hasMainComponent()) {\n \/\/ a pure Qt application does not have a KComponentData object,\n \/\/ we'll give it one.\n *mainComponentData;\n qAddPostRoutine(mainComponentData.destroy);\n Q_ASSERT(KGlobal::hasMainComponent());\n }\n}\n\nstatic const KComponentData &componentData()\n{\n ensureMainComponentData();\n return *phononComponentData;\n}\n\nKdePlatformPlugin::KdePlatformPlugin()\n{\n ensureMainComponentData();\n KGlobal::locale()->insertCatalog(QLatin1String(\"phonon_kde\"));\n}\n\nAbstractMediaStream *KdePlatformPlugin::createMediaStream(const QUrl &url, QObject *parent)\n{\n return new KioMediaStream(url, parent);\n}\n\nQIcon KdePlatformPlugin::icon(const QString &name) const\n{\n return KIcon(name);\n}\n\nvoid KdePlatformPlugin::notification(const char *notificationName, const QString &text,\n const QStringList &actions, QObject *receiver,\n const char *actionSlot) const\n{\n KNotification *notification = new KNotification(notificationName);\n notification->setComponentData(componentData());\n notification->setText(text);\n \/\/notification->setPixmap(...);\n notification->addContext(QLatin1String(\"Application\"), KGlobal::mainComponent().componentName());\n if (!actions.isEmpty() && receiver && actionSlot) {\n notification->setActions(actions);\n QObject::connect(notification, SIGNAL(activated(unsigned int)), receiver, actionSlot);\n }\n notification->sendEvent();\n}\n\nQString KdePlatformPlugin::applicationName() const\n{\n ensureMainComponentData();\n const KAboutData *ad = KGlobal::mainComponent().aboutData();\n if (ad) {\n const QString programName = ad->programName();\n if (programName.isEmpty()) {\n return KGlobal::mainComponent().componentName();\n }\n return programName;\n }\n return KGlobal::mainComponent().componentName();\n}\n\n#undef PHONON_LOAD_BACKEND_GLOBAL\n\nQObject *KdePlatformPlugin::createBackend(KService::Ptr newService)\n{\n QString errorReason;\n#ifdef PHONON_LOAD_BACKEND_GLOBAL\n KLibFactory *factory = 0;\n \/\/ This code is in here temporarily until NMM gets fixed.\n \/\/ Currently the NMM backend will fail with undefined symbols if\n \/\/ the backend is not loaded with global symbol resolution\n factory = KLibLoader::self()->factory(newService->library(), QLibrary::ExportExternalSymbolsHint);\n if (!factory) {\n errorReason = KLibLoader::self()->lastErrorMessage();\n kError(600) << \"Can not create factory for \" << newService->name() <<\n \":\\n\" << errorReason << endl;\n\n KMessageBox::error(0,\n QLatin1String(\"<html>\")\n + i18n(\"Unable to use the <b>%1<\/b> Multimedia Backend:\", newService->name())\n + QLatin1Char('\\n')\n + errorReason\n + QLatin1String(\"<\/html>\"));\n return false;\n }\n QObject *backend = factory->create<QObject>();\n if (0 == backend) {\n errorReason = i18n(\"create method returned 0\");\n }\n#else\n QObject *backend = newService->createInstance<QObject>(0, QVariantList(), &errorReason);\n#endif\n if (0 == backend) {\n kError(600) << \"Can not create backend object from factory for \" <<\n newService->name() << \", \" << newService->library() << \":\\n\" << errorReason << endl;\n\n KMessageBox::error(0,\n i18n(\"<qt>Unable to use the <b>%1<\/b> Multimedia Backend:<br\/>%2<\/qt>\",\n newService->name(), errorReason));\n return false;\n }\n\n kDebug() << \"using backend: \" << newService->name();\n return backend;\n}\n\nQObject *KdePlatformPlugin::createBackend()\n{\n ensureMainComponentData();\n const KService::List offers = KServiceTypeTrader::self()->query(\"PhononBackend\",\n \"Type == 'Service' and [X-KDE-PhononBackendInfo-InterfaceVersion] == 1\");\n if (offers.isEmpty()) {\n KMessageBox::error(0, i18n(\"Unable to find a Multimedia Backend\"));\n return 0;\n }\n\n KService::List::const_iterator it = offers.begin();\n const KService::List::const_iterator end = offers.end();\n while (it != end) {\n QObject *backend = createBackend(*it);\n if (backend) {\n return backend;\n }\n ++it;\n }\n return 0;\n}\n\nQObject *KdePlatformPlugin::createBackend(const QString &library, const QString &version)\n{\n ensureMainComponentData();\n QString additionalConstraints = QLatin1String(\" and Library == '\") + library + QLatin1Char('\\'');\n if (!version.isEmpty()) {\n additionalConstraints += QLatin1String(\" and [X-KDE-PhononBackendInfo-Version] == '\")\n + version + QLatin1Char('\\'');\n }\n const KService::List offers = KServiceTypeTrader::self()->query(QLatin1String(\"PhononBackend\"),\n QString(\"Type == 'Service' and [X-KDE-PhononBackendInfo-InterfaceVersion] == 1%1\")\n .arg(additionalConstraints));\n if (offers.isEmpty()) {\n KMessageBox::error(0, i18n(\"Unable to find the requested Multimedia Backend\"));\n return 0;\n }\n\n KService::List::const_iterator it = offers.begin();\n const KService::List::const_iterator end = offers.end();\n while (it != end) {\n QObject *backend = createBackend(*it);\n if (backend) {\n return backend;\n }\n ++it;\n }\n return 0;\n}\n\nbool KdePlatformPlugin::isMimeTypeAvailable(const QString &mimeType) const\n{\n ensureMainComponentData();\n const KService::List offers = KServiceTypeTrader::self()->query(\"PhononBackend\",\n \"Type == 'Service' and [X-KDE-PhononBackendInfo-InterfaceVersion] == 1\");\n if (!offers.isEmpty()) {\n return offers.first()->hasMimeType(KMimeType::mimeType(mimeType).data());\n }\n return false;\n}\n\nvoid KdePlatformPlugin::saveVolume(const QString &outputName, qreal volume)\n{\n ensureMainComponentData();\n KConfigGroup config(KGlobal::config(), \"Phonon::AudioOutput\");\n config.writeEntry(outputName + \"_Volume\", volume);\n}\n\nqreal KdePlatformPlugin::loadVolume(const QString &outputName) const\n{\n ensureMainComponentData();\n KConfigGroup config(KGlobal::config(), \"Phonon::AudioOutput\");\n return config.readEntry<qreal>(outputName + \"_Volume\", 1.0);\n}\n\n} \/\/ namespace Phonon\n\nQ_EXPORT_PLUGIN2(phonon_platform_kde, Phonon::KdePlatformPlugin)\n\n#include \"kdepluginfactory.moc\"\n\/\/ vim: sw=4 sts=4 et tw=100\n<|endoftext|>"} {"text":"<commit_before>556b7647-2e4f-11e5-9fc9-28cfe91dbc4b<commit_msg>5572c463-2e4f-11e5-a72b-28cfe91dbc4b<commit_after>5572c463-2e4f-11e5-a72b-28cfe91dbc4b<|endoftext|>"} {"text":"<commit_before>ba09385e-35ca-11e5-8b48-6c40088e03e4<commit_msg>ba0fae46-35ca-11e5-aac2-6c40088e03e4<commit_after>ba0fae46-35ca-11e5-aac2-6c40088e03e4<|endoftext|>"} {"text":"<commit_before>2b61ff98-2f67-11e5-bc7f-6c40088e03e4<commit_msg>2b690794-2f67-11e5-a64e-6c40088e03e4<commit_after>2b690794-2f67-11e5-a64e-6c40088e03e4<|endoftext|>"} {"text":"<commit_before>6bc44ddc-2e4f-11e5-9415-28cfe91dbc4b<commit_msg>6bcadc75-2e4f-11e5-80bd-28cfe91dbc4b<commit_after>6bcadc75-2e4f-11e5-80bd-28cfe91dbc4b<|endoftext|>"} {"text":"<commit_before>5d286677-2d16-11e5-af21-0401358ea401<commit_msg>5d286678-2d16-11e5-af21-0401358ea401<commit_after>5d286678-2d16-11e5-af21-0401358ea401<|endoftext|>"} {"text":"<commit_before>89c51bde-4b02-11e5-bad8-28cfe9171a43<commit_msg>Added that feature we discussed on... Was it monday?<commit_after>89d2394a-4b02-11e5-824f-28cfe9171a43<|endoftext|>"} {"text":"<commit_before>#include \"HttpSession.hpp\"\n\n#include <boost\/asio\/connect.hpp>\n#include <boost\/asio\/ssl\/rfc2818_verification.hpp>\n#include <boost\/beast\/core\/detail\/base64.hpp>\n#include <boost\/beast\/http\/read.hpp>\n#include <boost\/beast\/http\/write.hpp>\n\nnamespace ph = std::placeholders;\n\nHttpSession::HttpSession(boost::asio::io_context& ioc) : resolver_{ioc}\n{\n ssl::context ctx{ssl::context::sslv23_client};\n ctx.set_default_verify_paths();\n ctx.set_verify_mode(ssl::verify_peer);\n\n socket_ = std::make_unique<ssl::stream<ip::tcp::socket>>(ioc, ctx);\n response_.body_limit(std::numeric_limits<std::uint64_t>::max());\n}\n\nboost::future<HttpResponseResult> HttpSession::send(const Uri& uri, const http::request<http::string_body>& request)\n{\n useSsl_ = uri.scheme() == Uri::HttpsScheme;\n request_ = request;\n\n auto host = uri.authority().host();\n auto hostString = static_cast<std::string>(host);\n\n socket_->set_verify_callback(ssl::rfc2818_verification(hostString));\n if (!SSL_set_tlsext_host_name(socket_->native_handle(), hostString.data()))\n {\n boost::beast::error_code ec{static_cast<int>(::ERR_get_error()), boost::asio::error::get_ssl_category()};\n sessionFinished(ec);\n }\n\n resolve(uri.authority().host(),\n uri.authority().port(),\n std::bind(&HttpSession::onResolved, shared_from_this(), ph::_1, ph::_2));\n\n return result_.get_future();\n}\n\ntemplate <typename Callback>\nvoid HttpSession::resolve(const Uri::Host& host, const Uri::Port& port, Callback callback)\n{\n resolver_.async_resolve(\n static_cast<std::string>(host), port.string(), ip::resolver_base::numeric_service, callback);\n}\n\nvoid HttpSession::onResolved(const boost::system::error_code& ec, ip::tcp::resolver::results_type results)\n{\n if (!ec)\n {\n connect(results, std::bind(&HttpSession::onConnected, shared_from_this(), ph::_1, ph::_2));\n }\n else\n {\n sessionFinished(ec);\n }\n}\n\ntemplate <typename Callback>\nvoid HttpSession::connect(ip::tcp::resolver::results_type results, Callback callback)\n{\n boost::asio::async_connect(socket_->next_layer(), results.begin(), results.end(), callback);\n}\n\nvoid HttpSession::onConnected(const boost::system::error_code& ec, ip::tcp::resolver::iterator)\n{\n if (!ec)\n {\n if (useSsl_)\n {\n handshake(std::bind(&HttpSession::onHandshaked, shared_from_this(), ph::_1));\n }\n else\n {\n write(std::bind(&HttpSession::onWritten, shared_from_this(), ph::_1, ph::_2));\n }\n }\n else\n {\n sessionFinished(ec);\n }\n}\n\ntemplate <typename Callback>\nvoid HttpSession::handshake(Callback callback)\n{\n socket_->async_handshake(ssl::stream_base::client, callback);\n}\n\nvoid HttpSession::onHandshaked(const boost::system::error_code& ec)\n{\n if (!ec)\n {\n write(std::bind(&HttpSession::onWritten, shared_from_this(), ph::_1, ph::_2));\n }\n else\n {\n sessionFinished(ec);\n }\n}\n\ntemplate <typename Callback>\nvoid HttpSession::write(Callback callback)\n{\n if (useSsl_)\n {\n http::async_write(*socket_, request_, callback);\n }\n else\n {\n http::async_write(socket_->next_layer(), request_, callback);\n }\n}\n\nvoid HttpSession::onWritten(const boost::system::error_code& ec, std::size_t \/*bytes*\/)\n{\n if (!ec)\n {\n read(std::bind(&HttpSession::onRead, shared_from_this(), ph::_1, ph::_2));\n }\n else\n {\n sessionFinished(ec);\n }\n}\n\ntemplate <typename Callback>\nvoid HttpSession::read(Callback callback)\n{\n if (useSsl_)\n {\n http::async_read(*socket_, buffer_, response_, callback);\n }\n else\n {\n http::async_read(socket_->next_layer(), buffer_, response_, callback);\n }\n}\n\nvoid HttpSession::onRead(const boost::system::error_code& ec, std::size_t \/*bytes*\/)\n{\n sessionFinished(ec);\n}\n\nvoid HttpSession::sessionFinished(const boost::system::error_code& ec)\n{\n if (!ec)\n {\n setHttpResult(HttpResponseResult{PlayerError{}, response_.get().body()});\n }\n else\n {\n PlayerError error{\"HTTP\", ec.message()};\n setHttpResult(HttpResponseResult{error, {}});\n }\n}\n\nvoid HttpSession::cancel()\n{\n setHttpResult(HttpResponseResult{PlayerError{\"HTTP\", \"Operation Aborted\"}, {}});\n}\n\nvoid HttpSession::setHttpResult(const HttpResponseResult& result)\n{\n if (!resultSet_)\n {\n resultSet_ = true;\n result_.set_value(result);\n }\n}\n<commit_msg>fix: xibosignage#90 handle http error<commit_after>#include \"HttpSession.hpp\"\n\n#include <boost\/asio\/connect.hpp>\n#include <boost\/asio\/ssl\/rfc2818_verification.hpp>\n#include <boost\/beast\/core\/detail\/base64.hpp>\n#include <boost\/beast\/http\/read.hpp>\n#include <boost\/beast\/http\/write.hpp>\n\nnamespace ph = std::placeholders;\n\nHttpSession::HttpSession(boost::asio::io_context& ioc) : resolver_{ioc}\n{\n ssl::context ctx{ssl::context::sslv23_client};\n ctx.set_default_verify_paths();\n ctx.set_verify_mode(ssl::verify_peer);\n\n socket_ = std::make_unique<ssl::stream<ip::tcp::socket>>(ioc, ctx);\n response_.body_limit(std::numeric_limits<std::uint64_t>::max());\n}\n\nboost::future<HttpResponseResult> HttpSession::send(const Uri& uri, const http::request<http::string_body>& request)\n{\n useSsl_ = uri.scheme() == Uri::HttpsScheme;\n request_ = request;\n\n auto host = uri.authority().host();\n auto hostString = static_cast<std::string>(host);\n\n socket_->set_verify_callback(ssl::rfc2818_verification(hostString));\n if (!SSL_set_tlsext_host_name(socket_->native_handle(), hostString.data()))\n {\n boost::beast::error_code ec{static_cast<int>(::ERR_get_error()), boost::asio::error::get_ssl_category()};\n sessionFinished(ec);\n }\n\n resolve(uri.authority().host(),\n uri.authority().port(),\n std::bind(&HttpSession::onResolved, shared_from_this(), ph::_1, ph::_2));\n\n return result_.get_future();\n}\n\ntemplate <typename Callback>\nvoid HttpSession::resolve(const Uri::Host& host, const Uri::Port& port, Callback callback)\n{\n resolver_.async_resolve(\n static_cast<std::string>(host), port.string(), ip::resolver_base::numeric_service, callback);\n}\n\nvoid HttpSession::onResolved(const boost::system::error_code& ec, ip::tcp::resolver::results_type results)\n{\n if (!ec)\n {\n connect(results, std::bind(&HttpSession::onConnected, shared_from_this(), ph::_1, ph::_2));\n }\n else\n {\n sessionFinished(ec);\n }\n}\n\ntemplate <typename Callback>\nvoid HttpSession::connect(ip::tcp::resolver::results_type results, Callback callback)\n{\n boost::asio::async_connect(socket_->next_layer(), results.begin(), results.end(), callback);\n}\n\nvoid HttpSession::onConnected(const boost::system::error_code& ec, ip::tcp::resolver::iterator)\n{\n if (!ec)\n {\n if (useSsl_)\n {\n handshake(std::bind(&HttpSession::onHandshaked, shared_from_this(), ph::_1));\n }\n else\n {\n write(std::bind(&HttpSession::onWritten, shared_from_this(), ph::_1, ph::_2));\n }\n }\n else\n {\n sessionFinished(ec);\n }\n}\n\ntemplate <typename Callback>\nvoid HttpSession::handshake(Callback callback)\n{\n socket_->async_handshake(ssl::stream_base::client, callback);\n}\n\nvoid HttpSession::onHandshaked(const boost::system::error_code& ec)\n{\n if (!ec)\n {\n write(std::bind(&HttpSession::onWritten, shared_from_this(), ph::_1, ph::_2));\n }\n else\n {\n sessionFinished(ec);\n }\n}\n\ntemplate <typename Callback>\nvoid HttpSession::write(Callback callback)\n{\n if (useSsl_)\n {\n http::async_write(*socket_, request_, callback);\n }\n else\n {\n http::async_write(socket_->next_layer(), request_, callback);\n }\n}\n\nvoid HttpSession::onWritten(const boost::system::error_code& ec, std::size_t \/*bytes*\/)\n{\n if (!ec)\n {\n read(std::bind(&HttpSession::onRead, shared_from_this(), ph::_1, ph::_2));\n }\n else\n {\n sessionFinished(ec);\n }\n}\n\ntemplate <typename Callback>\nvoid HttpSession::read(Callback callback)\n{\n if (useSsl_)\n {\n http::async_read(*socket_, buffer_, response_, callback);\n }\n else\n {\n http::async_read(socket_->next_layer(), buffer_, response_, callback);\n }\n}\n\nvoid HttpSession::onRead(const boost::system::error_code& ec, std::size_t \/*bytes*\/)\n{\n sessionFinished(ec);\n}\n\n#include \"common\/logger\/Logging.hpp\"\n\nvoid HttpSession::sessionFinished(const boost::system::error_code& ec)\n{\n if (!ec)\n {\n auto&& message = response_.get();\n if (message.result() == http::status::ok)\n {\n setHttpResult(HttpResponseResult{PlayerError{}, response_.get().body()});\n }\n else\n {\n std::string responseMessage{message.reason()};\n std::string errorMessage = std::to_string(message.result_int());\n if (!responseMessage.empty())\n {\n errorMessage += \" \" + responseMessage;\n }\n PlayerError error{\"HTTP\", errorMessage};\n setHttpResult(HttpResponseResult{error, {}});\n }\n }\n else\n {\n PlayerError error{\"HTTP\", ec.message()};\n setHttpResult(HttpResponseResult{error, {}});\n }\n}\n\nvoid HttpSession::cancel()\n{\n setHttpResult(HttpResponseResult{PlayerError{\"HTTP\", \"Operation Aborted\"}, {}});\n}\n\nvoid HttpSession::setHttpResult(const HttpResponseResult& result)\n{\n if (!resultSet_)\n {\n resultSet_ = true;\n result_.set_value(result);\n }\n}\n<|endoftext|>"} {"text":"<commit_before>b141578f-327f-11e5-87cf-9cf387a8033e<commit_msg>b1474091-327f-11e5-b700-9cf387a8033e<commit_after>b1474091-327f-11e5-b700-9cf387a8033e<|endoftext|>"} {"text":"<commit_before>e9c2ce26-327f-11e5-9dea-9cf387a8033e<commit_msg>e9c8e221-327f-11e5-840a-9cf387a8033e<commit_after>e9c8e221-327f-11e5-840a-9cf387a8033e<|endoftext|>"} {"text":"<commit_before>f9f8a87a-585a-11e5-9766-6c40088e03e4<commit_msg>f9ff7880-585a-11e5-ac1b-6c40088e03e4<commit_after>f9ff7880-585a-11e5-ac1b-6c40088e03e4<|endoftext|>"} {"text":"<commit_before>b20b1f66-35ca-11e5-8392-6c40088e03e4<commit_msg>b21257b6-35ca-11e5-a5c7-6c40088e03e4<commit_after>b21257b6-35ca-11e5-a5c7-6c40088e03e4<|endoftext|>"} {"text":"<commit_before>\/* BEGIN_COMMON_COPYRIGHT_HEADER\n * (c)LGPL2+\n *\n * LXQt - a lightweight, Qt based, desktop toolset\n * https:\/\/lxqt.org\n *\n * Copyright: 2020 LXQt team\n * Authors:\n *\n * This program or library is free software; you can redistribute it\n * and\/or modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n\n * You should have received a copy of the GNU Lesser General\n * Public License along with this library; if not, write to the\n * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,\n * Boston, MA 02110-1301 USA\n *\n * END_COMMON_COPYRIGHT_HEADER *\/\n\n#include <QVBoxLayout>\n#include <QFrame>\n#include <QEvent>\n#include <QDebug>\n#include \"sliderdialog.h\"\n\n\nSliderDialog::SliderDialog(QWidget *parent) : QDialog(parent, Qt::Dialog | Qt::WindowStaysOnTopHint | Qt::CustomizeWindowHint | Qt::Popup | Qt::X11BypassWindowManagerHint)\n{\n setWindowFlags(Qt::WindowStaysOnTopHint | Qt::CustomizeWindowHint | Qt::Popup | Qt::X11BypassWindowManagerHint);\n m_backlight = new LXQt::Backlight(this);\n \n QVBoxLayout *layout = new QVBoxLayout(this);\n layout->setSpacing(0);\n layout->setMargin(2);\n \n m_upButton = new QToolButton();\n m_upButton->setText(QStringLiteral(\"☀\"));\n m_upButton->setAutoRepeat(true);\n layout->addWidget(m_upButton, 0, Qt::AlignHCenter);\n \n m_slider = new QSlider(this);\n layout->addWidget(m_slider, 0, Qt::AlignHCenter);\n \n m_downButton = new QToolButton();\n m_downButton->setText(QStringLiteral(\"☼\"));\n m_downButton->setAutoRepeat(true);\n layout->addWidget(m_downButton, 0, Qt::AlignHCenter);\n \n layout->addWidget(m_slider, 0, Qt::AlignHCenter);\n \n m_downButton = new QToolButton();\n m_downButton->setText(QStringLiteral(\"☀\"));\n layout->addWidget(m_downButton, 0, Qt::AlignHCenter);\n \n \n if(m_backlight->isBacklightAvailable() || m_backlight->isBacklightOff()) {\n \/\/ Set the minimum to 5% of the maximum to prevent a black screen\n int minBacklight = qMax(qRound((qreal)(m_backlight->getMaxBacklight())*0.05), 1);\n int maxBacklight = m_backlight->getMaxBacklight();\n int interval = maxBacklight - minBacklight;\n if(interval <= 100) {\n m_slider->setMaximum(maxBacklight);\n m_slider->setMinimum(minBacklight);\n m_slider->setValue(m_backlight->getBacklight());\n } else {\n m_slider->setMaximum(100);\n \/\/ Set the minimum to 5% of the maximum to prevent a black screen\n m_slider->setMinimum(5);\n m_slider->setValue( (m_backlight->getBacklight() * 100) \/ maxBacklight);\n }\n } else {\n m_slider->setValue(0);\n m_slider->setEnabled(false);\n m_upButton->setEnabled(false);\n m_downButton->setEnabled(false);\n }\n \n connect(m_slider, SIGNAL(valueChanged(int)), this, SLOT(sliderValueChanged(int)));\n connect(m_upButton, SIGNAL(clicked(bool)), this, SLOT(upButtonClicked(bool)));\n connect(m_downButton, SIGNAL(clicked(bool)), this, SLOT(downButtonClicked(bool)));\n}\n\n\nvoid SliderDialog::sliderValueChanged(int value)\n{\n \/\/ Set the minimum to 5% of the maximum to prevent a black screen\n int minBacklight = qMax(qRound((qreal)(m_backlight->getMaxBacklight())*0.05), 1);\n int maxBacklight = m_backlight->getMaxBacklight();\n int interval = maxBacklight - minBacklight;\n if(interval > 100)\n value = (value * maxBacklight) \/ 100;\n m_backlight->setBacklight(value);\n}\n\n\nvoid SliderDialog::updateBacklight()\n{\n \/\/ Set the minimum to 5% of the maximum to prevent a black screen\n int minBacklight = qMax(qRound((qreal)(m_backlight->getMaxBacklight())*0.05), 1);\n int maxBacklight = m_backlight->getMaxBacklight();\n int interval = maxBacklight - minBacklight;\n if(interval <= 100)\n m_slider->setValue(m_backlight->getBacklight());\n else\n m_slider->setValue( (m_backlight->getBacklight() * 100) \/ maxBacklight);\n}\n\nvoid SliderDialog::downButtonClicked(bool)\n{\n m_slider->setValue(m_slider->value() - 1);\n}\n\nvoid SliderDialog::upButtonClicked(bool)\n{\n m_slider->setValue(m_slider->value() + 1);\n}\n\n\nbool SliderDialog::event(QEvent * event)\n{\n if(event->type() == QEvent::WindowDeactivate || event->type() == QEvent::Hide) {\n hide();\n \/\/printf(\"emit dialogClosed()\\n\");\n emit dialogClosed();\n }\n return QDialog::event(event);\n}\n\n<commit_msg>Set the number of steps of the backlight slider to 100 steps.<commit_after>\/* BEGIN_COMMON_COPYRIGHT_HEADER\n * (c)LGPL2+\n *\n * LXQt - a lightweight, Qt based, desktop toolset\n * https:\/\/lxqt.org\n *\n * Copyright: 2020 LXQt team\n * Authors:\n *\n * This program or library is free software; you can redistribute it\n * and\/or modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n\n * You should have received a copy of the GNU Lesser General\n * Public License along with this library; if not, write to the\n * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,\n * Boston, MA 02110-1301 USA\n *\n * END_COMMON_COPYRIGHT_HEADER *\/\n\n#include <QVBoxLayout>\n#include <QFrame>\n#include <QEvent>\n#include <QDebug>\n#include \"sliderdialog.h\"\n\n\nSliderDialog::SliderDialog(QWidget *parent) : QDialog(parent, Qt::Dialog | Qt::WindowStaysOnTopHint | Qt::CustomizeWindowHint | Qt::Popup | Qt::X11BypassWindowManagerHint)\n{\n setWindowFlags(Qt::WindowStaysOnTopHint | Qt::CustomizeWindowHint | Qt::Popup | Qt::X11BypassWindowManagerHint);\n m_backlight = new LXQt::Backlight(this);\n \n QVBoxLayout *layout = new QVBoxLayout(this);\n layout->setSpacing(0);\n layout->setMargin(2);\n \n m_upButton = new QToolButton();\n m_upButton->setText(QStringLiteral(\"☀\"));\n m_upButton->setAutoRepeat(true);\n layout->addWidget(m_upButton, 0, Qt::AlignHCenter);\n \n m_slider = new QSlider(this);\n layout->addWidget(m_slider, 0, Qt::AlignHCenter);\n \n m_downButton = new QToolButton();\n m_downButton->setText(QStringLiteral(\"☼\"));\n m_downButton->setAutoRepeat(true);\n layout->addWidget(m_downButton, 0, Qt::AlignHCenter);\n \n \n if(m_backlight->isBacklightAvailable() || m_backlight->isBacklightOff()) {\n \/\/ Set the minimum to 5% of the maximum to prevent a black screen\n int minBacklight = qMax(qRound((qreal)(m_backlight->getMaxBacklight())*0.05), 1);\n int maxBacklight = m_backlight->getMaxBacklight();\n int interval = maxBacklight - minBacklight;\n if(interval <= 100) {\n m_slider->setMaximum(maxBacklight);\n m_slider->setMinimum(minBacklight);\n m_slider->setValue(m_backlight->getBacklight());\n } else {\n m_slider->setMaximum(100);\n \/\/ Set the minimum to 5% of the maximum to prevent a black screen\n m_slider->setMinimum(5);\n m_slider->setValue( (m_backlight->getBacklight() * 100) \/ maxBacklight);\n }\n } else {\n m_slider->setValue(0);\n m_slider->setEnabled(false);\n m_upButton->setEnabled(false);\n m_downButton->setEnabled(false);\n }\n \n connect(m_slider, SIGNAL(valueChanged(int)), this, SLOT(sliderValueChanged(int)));\n connect(m_upButton, SIGNAL(clicked(bool)), this, SLOT(upButtonClicked(bool)));\n connect(m_downButton, SIGNAL(clicked(bool)), this, SLOT(downButtonClicked(bool)));\n}\n\n\nvoid SliderDialog::sliderValueChanged(int value)\n{\n \/\/ Set the minimum to 5% of the maximum to prevent a black screen\n int minBacklight = qMax(qRound((qreal)(m_backlight->getMaxBacklight())*0.05), 1);\n int maxBacklight = m_backlight->getMaxBacklight();\n int interval = maxBacklight - minBacklight;\n if(interval > 100)\n value = (value * maxBacklight) \/ 100;\n m_backlight->setBacklight(value);\n}\n\n\nvoid SliderDialog::updateBacklight()\n{\n \/\/ Set the minimum to 5% of the maximum to prevent a black screen\n int minBacklight = qMax(qRound((qreal)(m_backlight->getMaxBacklight())*0.05), 1);\n int maxBacklight = m_backlight->getMaxBacklight();\n int interval = maxBacklight - minBacklight;\n if(interval <= 100)\n m_slider->setValue(m_backlight->getBacklight());\n else\n m_slider->setValue( (m_backlight->getBacklight() * 100) \/ maxBacklight);\n}\n\nvoid SliderDialog::downButtonClicked(bool)\n{\n m_slider->setValue(m_slider->value() - 1);\n}\n\nvoid SliderDialog::upButtonClicked(bool)\n{\n m_slider->setValue(m_slider->value() + 1);\n}\n\n\nbool SliderDialog::event(QEvent * event)\n{\n if(event->type() == QEvent::WindowDeactivate || event->type() == QEvent::Hide) {\n hide();\n \/\/printf(\"emit dialogClosed()\\n\");\n emit dialogClosed();\n }\n return QDialog::event(event);\n}\n\n<|endoftext|>"} {"text":"<commit_before>8e9facaf-2d14-11e5-af21-0401358ea401<commit_msg>8e9facb0-2d14-11e5-af21-0401358ea401<commit_after>8e9facb0-2d14-11e5-af21-0401358ea401<|endoftext|>"} {"text":"<commit_before>\/* BEGIN_COMMON_COPYRIGHT_HEADER\n * (c)LGPL2+\n *\n * Razor - a lightweight, Qt based, desktop toolset\n * http:\/\/razor-qt.org\n *\n * Copyright: 2010-2011 Razor team\n * Authors:\n * Alexander Sokoloff <sokoloff.a@gmail.com>\n *\n * This program or library is free software; you can redistribute it\n * and\/or modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n\n * You should have received a copy of the GNU Lesser General\n * Public License along with this library; if not, write to the\n * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,\n * Boston, MA 02110-1301 USA\n *\n * END_COMMON_COPYRIGHT_HEADER *\/\n\n\n#include \"razormainmenu.h\"\n#include \"razormainmenuconfiguration.h\"\n#include <QDebug>\n#include <qtxdg\/xdgdesktopfile.h>\n#include <qtxdg\/xmlhelper.h>\n#include <QSettings>\n#include <QFileInfo>\n#include <QAction>\n#include <QtCore\/QTimer>\n#include <QtGui\/QMessageBox>\n#include <razorqt\/powermanager.h>\n#include <razorqt\/screensaver.h>\n#include <razor-global-key-shortcuts-client\/razor-global-key-shortcuts-client.h>\n#include <razorqt\/xfitman.h>\n\n#include <qtxdg\/xdgicon.h>\n#include <qtxdg\/xdgdesktopfile.h>\n#include <qtxdg\/xdgmenuwidget.h>\n\n#include <QPixmap>\n#include <QStack>\n\n#include <QCursor>\n\nQ_EXPORT_PLUGIN2(mainmenu, RazorMainMenuPluginLibrary)\n\n#define DEFAULT_SHORTCUT \"Alt+F1\"\n\n\/************************************************\n\n ************************************************\/\nRazorMainMenu::RazorMainMenu(const IRazorPanelPluginStartupInfo &startupInfo):\n QObject(),\n IRazorPanelPlugin(startupInfo),\n mMenu(0),\n mShortcut(0),\n mLockCascadeChanges(false)\n{\n mButton.setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Minimum);\n\n connect(&mButton, SIGNAL(clicked()), this, SLOT(showMenu()));\n\n mPowerManager = new PowerManager(this);\n mScreenSaver = new ScreenSaver(this);\n\n settingsChanged();\n\n connect(mShortcut, SIGNAL(activated()), this, SLOT(showHideMenu()));\n connect(mShortcut, SIGNAL(shortcutChanged(QString,QString)), this, SLOT(shortcutChanged(QString,QString)));\n}\n\n\n\/************************************************\n\n ************************************************\/\nRazorMainMenu::~RazorMainMenu()\n{\n}\n\n\n\/************************************************\n\n ************************************************\/\nvoid RazorMainMenu::showHideMenu()\n{\n if (mMenu && mMenu->isVisible())\n mMenu->hide();\n else\n showMenu();\n}\n\n\n\/************************************************\n\n ************************************************\/\nvoid RazorMainMenu::shortcutChanged(const QString &\/*oldShortcut*\/, const QString &newShortcut)\n{\n if (!newShortcut.isEmpty())\n {\n mLockCascadeChanges = true;\n\n settings()->setValue(\"dialog\/shortcut\", newShortcut);\n settings()->sync();\n\n mLockCascadeChanges = false;\n }\n}\n\n\n\/************************************************\n\n ************************************************\/\nvoid RazorMainMenu::showMenu()\n{\n if (!mMenu)\n return;\n\n int x=0, y=0;\n\n switch (panel()->position())\n {\n case IRazorPanel::PositionTop:\n x = mButton.mapToGlobal(QPoint(0, 0)).x();\n y = panel()->globalGometry().bottom();\n break;\n\n case IRazorPanel::PositionBottom:\n x = mButton.mapToGlobal(QPoint(0, 0)).x();\n y = panel()->globalGometry().top() - mMenu->sizeHint().height();\n break;\n\n case IRazorPanel::PositionLeft:\n x = panel()->globalGometry().right();\n y = mButton.mapToGlobal(QPoint(0, 0)).y();\n break;\n\n case IRazorPanel::PositionRight:\n x = panel()->globalGometry().left() - mMenu->sizeHint().width();\n y = mButton.mapToGlobal(QPoint(0, 0)).y();\n break;\n }\n\n \/\/ Just using Qt`s activateWindow() won't work on some WMs like Kwin.\n \/\/ There are two solutions:\n \/\/ activate window with Qt call and then execute menu 1ms later using timer,\n \/\/ or use native X11 API calls:\n xfitMan().raiseWindow(mButton.effectiveWinId());\n mMenu->exec(QPoint(x, y));\n}\n\n\n\/************************************************\n\n ************************************************\/\nvoid RazorMainMenu::settingsChanged()\n{\n if (mLockCascadeChanges)\n return;\n\n if (settings()->value(\"showText\", false).toBool())\n {\n mButton.setText(settings()->value(\"text\", \"Start\").toString());\n mButton.setToolButtonStyle(Qt::ToolButtonTextBesideIcon);\n }\n else\n {\n mButton.setText(\"\");\n mButton.setToolButtonStyle(Qt::ToolButtonIconOnly);\n }\n\n mLogDir = settings()->value(\"log_dir\", \"\").toString();\n\n QString mMenuFile = settings()->value(\"menu_file\", \"\").toString();\n if (mMenuFile.isEmpty())\n mMenuFile = XdgMenu::getMenuFileName();\n\n mXdgMenu.setEnvironments(QStringList() << \"X-RAZOR\" << \"Razor\");\n mXdgMenu.setLogDir(mLogDir);\n\n bool res = mXdgMenu.read(mMenuFile);\n connect(&mXdgMenu, SIGNAL(changed()), this, SLOT(buildMenu()));\n if (res)\n {\n QTimer::singleShot(1000, this, SLOT(buildMenu()));\n }\n else\n {\n QMessageBox::warning(0, \"Parse error\", mXdgMenu.errorString());\n return;\n }\n\n\n QString shortcut = settings()->value(\"shortcut\", DEFAULT_SHORTCUT).toString();\n if (shortcut.isEmpty())\n shortcut = DEFAULT_SHORTCUT;\n\n if (!mShortcut)\n mShortcut = GlobalKeyShortcut::Client::instance()->addAction(shortcut, QString(\"\/panel\/%1\/show_hide\").arg(settings()->group()), tr(\"Show\/hide main menu\"), this);\n else if (mShortcut->shortcut() != shortcut)\n {\n mShortcut->changeShortcut(shortcut);\n }\n\n realign();\n}\n\n\n\/************************************************\n\n ************************************************\/\nvoid RazorMainMenu::buildMenu()\n{\n XdgMenuWidget *menu = new XdgMenuWidget(mXdgMenu, \"\", &mButton);\n menu->setObjectName(\"TopLevelMainMenu\");\n menu->setStyle(&mTopMenuStyle);\n\n menu->addSeparator();\n\n QMenu* leaveMenu = menu->addMenu(XdgIcon::fromTheme(\"system-shutdown\"), tr(\"Leave\"));\n leaveMenu->addActions(mPowerManager->availableActions());\n menu->addActions(mScreenSaver->availableActions());\n\n QMenu *oldMenu = mMenu;\n mMenu = menu;\n delete oldMenu;\n}\n\n\n\/************************************************\n\n ************************************************\/\nQDialog *RazorMainMenu::configureDialog()\n{\n return new RazorMainMenuConfiguration(*settings(), DEFAULT_SHORTCUT);\n}\n\n\n\/************************************************\n\n ************************************************\/\nvoid RazorMainMenu::realign()\n{\n QSize minSize = QSize(0, 0);\n QSize maxSize = QSize(QWIDGETSIZE_MAX, QWIDGETSIZE_MAX);\n\n if (panel()->isHorizontal())\n {\n minSize.setHeight(panel()->lineCount() * panel()->lineSize());\n maxSize.setHeight(minSize.height());\n\n minSize.setWidth(minSize.height());\n }\n else\n {\n minSize.setWidth(panel()->lineCount() * panel()->lineSize());\n minSize.setHeight(panel()->lineSize());\n }\n\n mButton.setMinimumSize(minSize);\n mButton.setMaximumSize(maxSize);\n mButton.updateGeometry();\n}\n\n#undef DEFAULT_SHORTCUT\n<commit_msg>Fix for Issue #531 This work for me in the OpenBox and KWin<commit_after>\/* BEGIN_COMMON_COPYRIGHT_HEADER\n * (c)LGPL2+\n *\n * Razor - a lightweight, Qt based, desktop toolset\n * http:\/\/razor-qt.org\n *\n * Copyright: 2010-2011 Razor team\n * Authors:\n * Alexander Sokoloff <sokoloff.a@gmail.com>\n *\n * This program or library is free software; you can redistribute it\n * and\/or modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n\n * You should have received a copy of the GNU Lesser General\n * Public License along with this library; if not, write to the\n * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,\n * Boston, MA 02110-1301 USA\n *\n * END_COMMON_COPYRIGHT_HEADER *\/\n\n\n#include \"razormainmenu.h\"\n#include \"razormainmenuconfiguration.h\"\n#include <QDebug>\n#include <qtxdg\/xdgdesktopfile.h>\n#include <qtxdg\/xmlhelper.h>\n#include <QSettings>\n#include <QFileInfo>\n#include <QAction>\n#include <QtCore\/QTimer>\n#include <QtGui\/QMessageBox>\n#include <razorqt\/powermanager.h>\n#include <razorqt\/screensaver.h>\n#include <razor-global-key-shortcuts-client\/razor-global-key-shortcuts-client.h>\n#include <razorqt\/xfitman.h>\n\n#include <qtxdg\/xdgicon.h>\n#include <qtxdg\/xdgdesktopfile.h>\n#include <qtxdg\/xdgmenuwidget.h>\n\n#include <QPixmap>\n#include <QStack>\n\n#include <QCursor>\n\nQ_EXPORT_PLUGIN2(mainmenu, RazorMainMenuPluginLibrary)\n\n#define DEFAULT_SHORTCUT \"Alt+F1\"\n\n\/************************************************\n\n ************************************************\/\nRazorMainMenu::RazorMainMenu(const IRazorPanelPluginStartupInfo &startupInfo):\n QObject(),\n IRazorPanelPlugin(startupInfo),\n mMenu(0),\n mShortcut(0),\n mLockCascadeChanges(false)\n{\n mButton.setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Minimum);\n\n connect(&mButton, SIGNAL(clicked()), this, SLOT(showMenu()));\n\n mPowerManager = new PowerManager(this);\n mScreenSaver = new ScreenSaver(this);\n\n settingsChanged();\n\n connect(mShortcut, SIGNAL(activated()), this, SLOT(showHideMenu()));\n connect(mShortcut, SIGNAL(shortcutChanged(QString,QString)), this, SLOT(shortcutChanged(QString,QString)));\n}\n\n\n\/************************************************\n\n ************************************************\/\nRazorMainMenu::~RazorMainMenu()\n{\n}\n\n\n\/************************************************\n\n ************************************************\/\nvoid RazorMainMenu::showHideMenu()\n{\n if (mMenu && mMenu->isVisible())\n mMenu->hide();\n else\n showMenu();\n}\n\n\n\/************************************************\n\n ************************************************\/\nvoid RazorMainMenu::shortcutChanged(const QString &\/*oldShortcut*\/, const QString &newShortcut)\n{\n if (!newShortcut.isEmpty())\n {\n mLockCascadeChanges = true;\n\n settings()->setValue(\"dialog\/shortcut\", newShortcut);\n settings()->sync();\n\n mLockCascadeChanges = false;\n }\n}\n\n\n\/************************************************\n\n ************************************************\/\nvoid RazorMainMenu::showMenu()\n{\n if (!mMenu)\n return;\n\n int x=0, y=0;\n\n switch (panel()->position())\n {\n case IRazorPanel::PositionTop:\n x = mButton.mapToGlobal(QPoint(0, 0)).x();\n y = panel()->globalGometry().bottom();\n break;\n\n case IRazorPanel::PositionBottom:\n x = mButton.mapToGlobal(QPoint(0, 0)).x();\n y = panel()->globalGometry().top() - mMenu->sizeHint().height();\n break;\n\n case IRazorPanel::PositionLeft:\n x = panel()->globalGometry().right();\n y = mButton.mapToGlobal(QPoint(0, 0)).y();\n break;\n\n case IRazorPanel::PositionRight:\n x = panel()->globalGometry().left() - mMenu->sizeHint().width();\n y = mButton.mapToGlobal(QPoint(0, 0)).y();\n break;\n }\n\n \/\/ Just using Qt`s activateWindow() won't work on some WMs like Kwin.\n \/\/ There are two solutions:\n \/\/ activate window with Qt call and then execute menu 1ms later using timer,\n \/\/ or use native X11 API calls:\n \/\/xfitMan().raiseWindow(mButton.effectiveWinId());\n mButton.activateWindow();\n mMenu->exec(QPoint(x, y));\n}\n\n\n\/************************************************\n\n ************************************************\/\nvoid RazorMainMenu::settingsChanged()\n{\n if (mLockCascadeChanges)\n return;\n\n if (settings()->value(\"showText\", false).toBool())\n {\n mButton.setText(settings()->value(\"text\", \"Start\").toString());\n mButton.setToolButtonStyle(Qt::ToolButtonTextBesideIcon);\n }\n else\n {\n mButton.setText(\"\");\n mButton.setToolButtonStyle(Qt::ToolButtonIconOnly);\n }\n\n mLogDir = settings()->value(\"log_dir\", \"\").toString();\n\n QString mMenuFile = settings()->value(\"menu_file\", \"\").toString();\n if (mMenuFile.isEmpty())\n mMenuFile = XdgMenu::getMenuFileName();\n\n mXdgMenu.setEnvironments(QStringList() << \"X-RAZOR\" << \"Razor\");\n mXdgMenu.setLogDir(mLogDir);\n\n bool res = mXdgMenu.read(mMenuFile);\n connect(&mXdgMenu, SIGNAL(changed()), this, SLOT(buildMenu()));\n if (res)\n {\n QTimer::singleShot(1000, this, SLOT(buildMenu()));\n }\n else\n {\n QMessageBox::warning(0, \"Parse error\", mXdgMenu.errorString());\n return;\n }\n\n\n QString shortcut = settings()->value(\"shortcut\", DEFAULT_SHORTCUT).toString();\n if (shortcut.isEmpty())\n shortcut = DEFAULT_SHORTCUT;\n\n if (!mShortcut)\n mShortcut = GlobalKeyShortcut::Client::instance()->addAction(shortcut, QString(\"\/panel\/%1\/show_hide\").arg(settings()->group()), tr(\"Show\/hide main menu\"), this);\n else if (mShortcut->shortcut() != shortcut)\n {\n mShortcut->changeShortcut(shortcut);\n }\n\n realign();\n}\n\n\n\/************************************************\n\n ************************************************\/\nvoid RazorMainMenu::buildMenu()\n{\n XdgMenuWidget *menu = new XdgMenuWidget(mXdgMenu, \"\", &mButton);\n menu->setObjectName(\"TopLevelMainMenu\");\n menu->setStyle(&mTopMenuStyle);\n\n menu->addSeparator();\n\n QMenu* leaveMenu = menu->addMenu(XdgIcon::fromTheme(\"system-shutdown\"), tr(\"Leave\"));\n leaveMenu->addActions(mPowerManager->availableActions());\n menu->addActions(mScreenSaver->availableActions());\n\n QMenu *oldMenu = mMenu;\n mMenu = menu;\n delete oldMenu;\n}\n\n\n\/************************************************\n\n ************************************************\/\nQDialog *RazorMainMenu::configureDialog()\n{\n return new RazorMainMenuConfiguration(*settings(), DEFAULT_SHORTCUT);\n}\n\n\n\/************************************************\n\n ************************************************\/\nvoid RazorMainMenu::realign()\n{\n QSize minSize = QSize(0, 0);\n QSize maxSize = QSize(QWIDGETSIZE_MAX, QWIDGETSIZE_MAX);\n\n if (panel()->isHorizontal())\n {\n minSize.setHeight(panel()->lineCount() * panel()->lineSize());\n maxSize.setHeight(minSize.height());\n\n minSize.setWidth(minSize.height());\n }\n else\n {\n minSize.setWidth(panel()->lineCount() * panel()->lineSize());\n minSize.setHeight(panel()->lineSize());\n }\n\n mButton.setMinimumSize(minSize);\n mButton.setMaximumSize(maxSize);\n mButton.updateGeometry();\n}\n\n#undef DEFAULT_SHORTCUT\n<|endoftext|>"} {"text":"<commit_before>\/*\r\n ==============================================================================\r\n\r\n This file was auto-generated by the Introjucer!\r\n\r\n It contains the basic framework code for a JUCE plugin processor.\r\n\r\n ==============================================================================\r\n*\/\r\n\r\n#include \"PluginProcessor.h\"\r\n#include \"PluginEditor.h\"\r\n\r\nconst char* RP2A03AudioProcessor::paramPulse1Level = \"pulse1Level\";\r\nconst char* RP2A03AudioProcessor::paramPulse1DutyCycle = \"pulse1Duty\";\r\nconst char* RP2A03AudioProcessor::paramPulse2Level = \"pulse2Level\";\r\nconst char* RP2A03AudioProcessor::paramPulse2DutyCycle = \"pulse2Duty\";\r\nconst char* RP2A03AudioProcessor::paramTriangleLevel = \"triangleLevel\";\r\nconst char* RP2A03AudioProcessor::paramNoiseLevel = \"noiseLevel\";\r\nconst char* RP2A03AudioProcessor::paramNoiseShort = \"noisePeriod\";\r\nconst char* RP2A03AudioProcessor::paramOutput = \"output\";\r\nconst char* RP2A03AudioProcessor::paramPulse1Tune = \"pulse1Tune\";\r\nconst char* RP2A03AudioProcessor::paramPulse1TuneFine = \"pulse1TuneFine\";\r\nconst char* RP2A03AudioProcessor::paramPulse2Tune = \"pulse2Tune\";\r\nconst char* RP2A03AudioProcessor::paramPulse2TuneFine = \"pulse2TuneFine\";\r\nconst char* RP2A03AudioProcessor::paramTriangleTune = \"triangleTune\";\r\nconst char* RP2A03AudioProcessor::paramTriangleTuneFine = \"triangleTuneFine\";\r\n\r\n\/\/==============================================================================\r\nString percentTextFunction (const slParameter& p, float v)\r\n{\r\n return String::formatted(\"%.0f%%\", v \/ p.getUserRangeEnd() * 100);\r\n}\r\n\r\nString onOffTextFunction (const slParameter& p, float v)\r\n{\r\n return v > 0.0f ? \"On\" : \"Off\";\r\n}\r\n\r\nString dutyTextFunction (const slParameter& p, float v)\r\n{\r\n const int duty = int (v);\r\n switch (duty)\r\n {\r\n case 0: return \"12.5%\";\r\n case 1: return \"25%\";\r\n case 2: return \"50%\";\r\n case 3: return \"75%\";\r\n }\r\n return \"\";\r\n}\r\n\r\n\/\/==============================================================================\r\nRP2A03AudioProcessor::RP2A03AudioProcessor()\r\n{\r\n addPluginParameter (new slParameter (paramPulse1Level, \"Pulse 1 Level\", \"Pulse\", \"\", 0.0f, 1.0f, 0.0f, 1.0f, 1.0f, percentTextFunction));\r\n addPluginParameter (new slParameter (paramPulse1DutyCycle, \"Pulse 1 Duty Cycle\", \"Duty Cycle\", \"\", 0.0f, 3.0f, 1.0f, 0.0f, 1.0f, dutyTextFunction));\r\n addPluginParameter (new slParameter (paramPulse2Level, \"Pulse 2 Level\", \"Pulse\", \"\", 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, percentTextFunction));\r\n addPluginParameter (new slParameter (paramPulse2DutyCycle, \"Pulse 2 Duty Cycle\", \"Duty Cycle\", \"\", 0.0f, 3.0f, 1.0f, 0.0f, 1.0f, dutyTextFunction));\r\n addPluginParameter (new slParameter (paramNoiseLevel, \"Noise Level\", \"Noise\", \"\", 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, percentTextFunction));\r\n addPluginParameter (new slParameter (paramNoiseShort, \"Noise Short\", \"Short\", \"\", 0.0f, 1.0f, 1.0f, 0.0f, 1.0f, onOffTextFunction));\r\n addPluginParameter (new slParameter (paramTriangleLevel, \"Triangle Level\", \"Triangle\", \"\", 0.0f, 1.0f, 1.0f, 0.0f, 1.0f, onOffTextFunction));\r\n addPluginParameter (new slParameter (paramOutput, \"Output\", \"Output\", \"\", 0.0f, 1.0f, 0.0f, 1.0f, 1.0f, percentTextFunction));\r\n addPluginParameter (new slParameter (paramPulse1Tune, \"Pulse 1 Tune\", \"Tune\", \"\", -48.0f, 48.0f, 1.0f, 0.0f, 1.0f));\r\n addPluginParameter (new slParameter (paramPulse1TuneFine, \"Pulse 1 Tune Fine\", \"Fine\", \"\", -100.0f, 100.0f, 1.0f, 0.0f, 1.0f));\r\n addPluginParameter (new slParameter (paramPulse2Tune, \"Pulse 2 Tune\", \"Tune\", \"\", -48.0f, 48.0f, 1.0f, 0.0f, 1.0f));\r\n addPluginParameter (new slParameter (paramPulse2TuneFine, \"Pulse 2 Tune Fine\", \"Fine\", \"\", -100.0f, 100.0f, 1.0f, 0.0f, 1.0f));\r\n addPluginParameter (new slParameter (paramTriangleTune, \"Triangle Tune\", \"Tune\", \"\", -48.0f, 48.0f, 1.0f, 0.0f, 1.0f));\r\n addPluginParameter (new slParameter (paramTriangleTuneFine,\"Triangle Tune Fine\", \"Fine\", \"\", -100.0f, 100.0f, 1.0f, 0.0f, 1.0f));\r\n}\r\n\r\nRP2A03AudioProcessor::~RP2A03AudioProcessor()\r\n{\r\n}\r\n\r\n\/\/==============================================================================\r\nvoid RP2A03AudioProcessor::prepareToPlay (double sampleRate, int samplesPerBlock)\r\n{\r\n apu.sample_rate (long (sampleRate));\r\n apu.write_register (0x4015, 0x0F);\r\n \r\n outputSmoothed.reset (sampleRate, 0.05);\r\n}\r\n\r\nvoid RP2A03AudioProcessor::releaseResources()\r\n{\r\n}\r\n\r\nvoid RP2A03AudioProcessor::runUntil (int& done, AudioSampleBuffer& buffer, int pos)\r\n{\r\n int todo = jmin (pos, buffer.getNumSamples()) - done;\r\n \r\n while (todo > 0)\r\n {\r\n if (apu.samples_avail() == 0)\r\n apu.step();\r\n \r\n Simple_Apu::sample_t out[1024];\r\n int count = apu.read_samples(out, jmin (todo, int (apu.samples_avail()), 1024));\r\n \r\n float* data = buffer.getWritePointer (0, done);\r\n for (int i = 0; i < count; i++)\r\n data[i] = out[i] \/ 32768.0f;\r\n \r\n done += count;\r\n todo -= count;\r\n }\r\n\r\n}\r\n\r\nvoid RP2A03AudioProcessor::processBlock (AudioSampleBuffer& buffer, MidiBuffer& midi)\r\n{\r\n const float p1Level = parameterValue (paramPulse1Level);\r\n const int p1Duty = parameterIntValue (paramPulse1DutyCycle);\r\n const int p1Tune = parameterIntValue (paramPulse1Tune);\r\n const int p1Fine = parameterIntValue (paramPulse1TuneFine);\r\n const float p2Level = parameterValue (paramPulse2Level);\r\n const int p2Duty = parameterIntValue (paramPulse2DutyCycle);\r\n const int p2Tune = parameterIntValue (paramPulse2Tune);\r\n const int p2Fine = parameterIntValue (paramPulse2TuneFine);\r\n const float tLevel = parameterValue (paramTriangleLevel);\r\n const int tTune = parameterIntValue (paramTriangleTune);\r\n const int tFine = parameterIntValue (paramTriangleTuneFine);\r\n const float nLevel = parameterValue (paramNoiseLevel);\r\n const bool nShort = parameterValue (paramNoiseShort) > 0.0f;\r\n \r\n outputSmoothed.setValue (getParameter (paramOutput)->getUserValue());\r\n\r\n int done = 0;\r\n runUntil (done, buffer, 0);\r\n \r\n int pos = 0;\r\n MidiMessage msg;\r\n MidiBuffer::Iterator itr (midi);\r\n while (itr.getNextEvent (msg, pos))\r\n {\r\n runUntil (done, buffer, pos);\r\n \r\n if (msg.isNoteOn())\r\n {\r\n noteQueue.add (msg.getNoteNumber());\r\n velocity = msg.getVelocity();\r\n }\r\n else if (msg.isNoteOff())\r\n {\r\n noteQueue.removeFirstMatchingValue (msg.getNoteNumber());\r\n }\r\n else if (msg.isAllNotesOff())\r\n {\r\n noteQueue.clear();\r\n }\r\n \r\n const int curNote = noteQueue.size() > 0 ? noteQueue.getFirst() : -1;\r\n \r\n if (curNote != lastNote)\r\n {\r\n int v = curNote == -1 ? 0 : velocity;\r\n \r\n \/\/ Pulse 1\r\n apu.write_register (0x4000, (p1Duty << 6) | 0x30 | int (p1Level * v \/ 127.0 * 0xF));\r\n \r\n if (curNote != -1)\r\n {\r\n int period = int (111860.8 \/ getMidiNoteInHertz (curNote + p1Tune + p1Fine \/ 100.0) - 1);\r\n \r\n apu.write_register (0x4002, period & 0xFF);\r\n apu.write_register (0x4003, (period >> 8) & 0x7);\r\n }\r\n \r\n \/\/ Pulse 2\r\n apu.write_register (0x4004, (p2Duty << 6) | 0x30 | int (p2Level * v \/ 127.0 * 0xF));\r\n \r\n if (curNote != -1)\r\n {\r\n int period = int (111860.8 \/ getMidiNoteInHertz (curNote + p2Tune + p2Fine \/ 100.0) - 1);\r\n \r\n apu.write_register (0x4006, period & 0xFF);\r\n apu.write_register (0x4007, (period >> 8) & 0x7);\r\n }\r\n \r\n \/\/ Triangle\r\n apu.write_register (0x4008, curNote == -1 ? 0x00 : 0xFF);\r\n if (curNote != -1)\r\n {\r\n int period = int (tLevel == 1.0f ? 111860.8 \/ getMidiNoteInHertz (curNote + tTune + tFine \/ 100.0) * 2 - 1 : 0);\r\n \r\n apu.write_register (0x400A, period & 0xFF);\r\n apu.write_register (0x400B, (period >> 8) & 0x7);\r\n }\r\n \r\n \/\/ Noise\r\n apu.write_register (0x400C, 0x30 | int (nLevel * v \/ 127.0 * 0xF));\r\n \r\n if (curNote != -1)\r\n {\r\n apu.write_register (0x400E, (nShort ? 0x80 : 0x00) | (curNote % 16));\r\n apu.write_register (0x400F, 0xFF);\r\n }\r\n \r\n lastNote = curNote;\r\n }\r\n }\r\n \r\n runUntil (done, buffer, buffer.getNumSamples());\r\n \r\n float* data = buffer.getWritePointer (0);\r\n for (int i = 0; i < buffer.getNumSamples(); i++)\r\n data[i] *= outputSmoothed.getNextValue();\r\n \r\n if (editor)\r\n editor->scope.addSamples (data, buffer.getNumSamples());\r\n}\r\n\r\n\/\/==============================================================================\r\nbool RP2A03AudioProcessor::hasEditor() const\r\n{\r\n return true;\r\n}\r\n\r\nAudioProcessorEditor* RP2A03AudioProcessor::createEditor()\r\n{\r\n editor = new RP2A03AudioProcessorEditor (*this);\r\n return editor;\r\n}\r\n\r\n\/\/==============================================================================\r\n\/\/ This creates new instances of the plugin..\r\nAudioProcessor* JUCE_CALLTYPE createPluginFilter()\r\n{\r\n return new RP2A03AudioProcessor();\r\n}\r\n<commit_msg>Fixed note handling<commit_after>\/*\r\n ==============================================================================\r\n\r\n This file was auto-generated by the Introjucer!\r\n\r\n It contains the basic framework code for a JUCE plugin processor.\r\n\r\n ==============================================================================\r\n*\/\r\n\r\n#include \"PluginProcessor.h\"\r\n#include \"PluginEditor.h\"\r\n\r\nconst char* RP2A03AudioProcessor::paramPulse1Level = \"pulse1Level\";\r\nconst char* RP2A03AudioProcessor::paramPulse1DutyCycle = \"pulse1Duty\";\r\nconst char* RP2A03AudioProcessor::paramPulse2Level = \"pulse2Level\";\r\nconst char* RP2A03AudioProcessor::paramPulse2DutyCycle = \"pulse2Duty\";\r\nconst char* RP2A03AudioProcessor::paramTriangleLevel = \"triangleLevel\";\r\nconst char* RP2A03AudioProcessor::paramNoiseLevel = \"noiseLevel\";\r\nconst char* RP2A03AudioProcessor::paramNoiseShort = \"noisePeriod\";\r\nconst char* RP2A03AudioProcessor::paramOutput = \"output\";\r\nconst char* RP2A03AudioProcessor::paramPulse1Tune = \"pulse1Tune\";\r\nconst char* RP2A03AudioProcessor::paramPulse1TuneFine = \"pulse1TuneFine\";\r\nconst char* RP2A03AudioProcessor::paramPulse2Tune = \"pulse2Tune\";\r\nconst char* RP2A03AudioProcessor::paramPulse2TuneFine = \"pulse2TuneFine\";\r\nconst char* RP2A03AudioProcessor::paramTriangleTune = \"triangleTune\";\r\nconst char* RP2A03AudioProcessor::paramTriangleTuneFine = \"triangleTuneFine\";\r\n\r\n\/\/==============================================================================\r\nString percentTextFunction (const slParameter& p, float v)\r\n{\r\n return String::formatted(\"%.0f%%\", v \/ p.getUserRangeEnd() * 100);\r\n}\r\n\r\nString onOffTextFunction (const slParameter& p, float v)\r\n{\r\n return v > 0.0f ? \"On\" : \"Off\";\r\n}\r\n\r\nString dutyTextFunction (const slParameter& p, float v)\r\n{\r\n const int duty = int (v);\r\n switch (duty)\r\n {\r\n case 0: return \"12.5%\";\r\n case 1: return \"25%\";\r\n case 2: return \"50%\";\r\n case 3: return \"75%\";\r\n }\r\n return \"\";\r\n}\r\n\r\n\/\/==============================================================================\r\nRP2A03AudioProcessor::RP2A03AudioProcessor()\r\n{\r\n addPluginParameter (new slParameter (paramPulse1Level, \"Pulse 1 Level\", \"Pulse\", \"\", 0.0f, 1.0f, 0.0f, 1.0f, 1.0f, percentTextFunction));\r\n addPluginParameter (new slParameter (paramPulse1DutyCycle, \"Pulse 1 Duty Cycle\", \"Duty Cycle\", \"\", 0.0f, 3.0f, 1.0f, 0.0f, 1.0f, dutyTextFunction));\r\n addPluginParameter (new slParameter (paramPulse2Level, \"Pulse 2 Level\", \"Pulse\", \"\", 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, percentTextFunction));\r\n addPluginParameter (new slParameter (paramPulse2DutyCycle, \"Pulse 2 Duty Cycle\", \"Duty Cycle\", \"\", 0.0f, 3.0f, 1.0f, 0.0f, 1.0f, dutyTextFunction));\r\n addPluginParameter (new slParameter (paramNoiseLevel, \"Noise Level\", \"Noise\", \"\", 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, percentTextFunction));\r\n addPluginParameter (new slParameter (paramNoiseShort, \"Noise Short\", \"Short\", \"\", 0.0f, 1.0f, 1.0f, 0.0f, 1.0f, onOffTextFunction));\r\n addPluginParameter (new slParameter (paramTriangleLevel, \"Triangle Level\", \"Triangle\", \"\", 0.0f, 1.0f, 1.0f, 0.0f, 1.0f, onOffTextFunction));\r\n addPluginParameter (new slParameter (paramOutput, \"Output\", \"Output\", \"\", 0.0f, 1.0f, 0.0f, 1.0f, 1.0f, percentTextFunction));\r\n addPluginParameter (new slParameter (paramPulse1Tune, \"Pulse 1 Tune\", \"Tune\", \"\", -48.0f, 48.0f, 1.0f, 0.0f, 1.0f));\r\n addPluginParameter (new slParameter (paramPulse1TuneFine, \"Pulse 1 Tune Fine\", \"Fine\", \"\", -100.0f, 100.0f, 1.0f, 0.0f, 1.0f));\r\n addPluginParameter (new slParameter (paramPulse2Tune, \"Pulse 2 Tune\", \"Tune\", \"\", -48.0f, 48.0f, 1.0f, 0.0f, 1.0f));\r\n addPluginParameter (new slParameter (paramPulse2TuneFine, \"Pulse 2 Tune Fine\", \"Fine\", \"\", -100.0f, 100.0f, 1.0f, 0.0f, 1.0f));\r\n addPluginParameter (new slParameter (paramTriangleTune, \"Triangle Tune\", \"Tune\", \"\", -48.0f, 48.0f, 1.0f, 0.0f, 1.0f));\r\n addPluginParameter (new slParameter (paramTriangleTuneFine,\"Triangle Tune Fine\", \"Fine\", \"\", -100.0f, 100.0f, 1.0f, 0.0f, 1.0f));\r\n}\r\n\r\nRP2A03AudioProcessor::~RP2A03AudioProcessor()\r\n{\r\n}\r\n\r\n\/\/==============================================================================\r\nvoid RP2A03AudioProcessor::prepareToPlay (double sampleRate, int samplesPerBlock)\r\n{\r\n apu.sample_rate (long (sampleRate));\r\n apu.write_register (0x4015, 0x0F);\r\n \r\n outputSmoothed.reset (sampleRate, 0.05);\r\n}\r\n\r\nvoid RP2A03AudioProcessor::releaseResources()\r\n{\r\n}\r\n\r\nvoid RP2A03AudioProcessor::runUntil (int& done, AudioSampleBuffer& buffer, int pos)\r\n{\r\n int todo = jmin (pos, buffer.getNumSamples()) - done;\r\n \r\n while (todo > 0)\r\n {\r\n if (apu.samples_avail() == 0)\r\n apu.step();\r\n \r\n Simple_Apu::sample_t out[1024];\r\n int count = apu.read_samples(out, jmin (todo, int (apu.samples_avail()), 1024));\r\n \r\n float* data = buffer.getWritePointer (0, done);\r\n for (int i = 0; i < count; i++)\r\n data[i] = out[i] \/ 32768.0f;\r\n \r\n done += count;\r\n todo -= count;\r\n }\r\n\r\n}\r\n\r\nvoid RP2A03AudioProcessor::processBlock (AudioSampleBuffer& buffer, MidiBuffer& midi)\r\n{\r\n const float p1Level = parameterValue (paramPulse1Level);\r\n const int p1Duty = parameterIntValue (paramPulse1DutyCycle);\r\n const int p1Tune = parameterIntValue (paramPulse1Tune);\r\n const int p1Fine = parameterIntValue (paramPulse1TuneFine);\r\n const float p2Level = parameterValue (paramPulse2Level);\r\n const int p2Duty = parameterIntValue (paramPulse2DutyCycle);\r\n const int p2Tune = parameterIntValue (paramPulse2Tune);\r\n const int p2Fine = parameterIntValue (paramPulse2TuneFine);\r\n const float tLevel = parameterValue (paramTriangleLevel);\r\n const int tTune = parameterIntValue (paramTriangleTune);\r\n const int tFine = parameterIntValue (paramTriangleTuneFine);\r\n const float nLevel = parameterValue (paramNoiseLevel);\r\n const bool nShort = parameterValue (paramNoiseShort) > 0.0f;\r\n \r\n outputSmoothed.setValue (getParameter (paramOutput)->getUserValue());\r\n\r\n int done = 0;\r\n runUntil (done, buffer, 0);\r\n \r\n int pos = 0;\r\n MidiMessage msg;\r\n MidiBuffer::Iterator itr (midi);\r\n while (itr.getNextEvent (msg, pos))\r\n {\r\n runUntil (done, buffer, pos);\r\n \r\n if (msg.isNoteOn())\r\n {\r\n noteQueue.add (msg.getNoteNumber());\r\n velocity = msg.getVelocity();\r\n }\r\n else if (msg.isNoteOff())\r\n {\r\n noteQueue.removeFirstMatchingValue (msg.getNoteNumber());\r\n }\r\n else if (msg.isAllNotesOff())\r\n {\r\n noteQueue.clear();\r\n }\r\n \r\n const int curNote = noteQueue.size() > 0 ? noteQueue.getLast() : -1;\r\n \r\n if (curNote != lastNote)\r\n {\r\n int v = curNote == -1 ? 0 : velocity;\r\n \r\n \/\/ Pulse 1\r\n apu.write_register (0x4000, (p1Duty << 6) | 0x30 | int (p1Level * v \/ 127.0 * 0xF));\r\n \r\n if (curNote != -1)\r\n {\r\n int period = int (111860.8 \/ getMidiNoteInHertz (curNote + p1Tune + p1Fine \/ 100.0) - 1);\r\n \r\n apu.write_register (0x4002, period & 0xFF);\r\n apu.write_register (0x4003, (period >> 8) & 0x7);\r\n }\r\n \r\n \/\/ Pulse 2\r\n apu.write_register (0x4004, (p2Duty << 6) | 0x30 | int (p2Level * v \/ 127.0 * 0xF));\r\n \r\n if (curNote != -1)\r\n {\r\n int period = int (111860.8 \/ getMidiNoteInHertz (curNote + p2Tune + p2Fine \/ 100.0) - 1);\r\n \r\n apu.write_register (0x4006, period & 0xFF);\r\n apu.write_register (0x4007, (period >> 8) & 0x7);\r\n }\r\n \r\n \/\/ Triangle\r\n apu.write_register (0x4008, curNote == -1 ? 0x00 : 0xFF);\r\n if (curNote != -1)\r\n {\r\n int period = int (tLevel == 1.0f ? 111860.8 \/ getMidiNoteInHertz (curNote + tTune + tFine \/ 100.0) * 2 - 1 : 0);\r\n \r\n apu.write_register (0x400A, period & 0xFF);\r\n apu.write_register (0x400B, (period >> 8) & 0x7);\r\n }\r\n \r\n \/\/ Noise\r\n apu.write_register (0x400C, 0x30 | int (nLevel * v \/ 127.0 * 0xF));\r\n \r\n if (curNote != -1)\r\n {\r\n apu.write_register (0x400E, (nShort ? 0x80 : 0x00) | (curNote % 16));\r\n apu.write_register (0x400F, 0xFF);\r\n }\r\n \r\n lastNote = curNote;\r\n }\r\n }\r\n \r\n runUntil (done, buffer, buffer.getNumSamples());\r\n \r\n float* data = buffer.getWritePointer (0);\r\n for (int i = 0; i < buffer.getNumSamples(); i++)\r\n data[i] *= outputSmoothed.getNextValue();\r\n \r\n if (editor)\r\n editor->scope.addSamples (data, buffer.getNumSamples());\r\n}\r\n\r\n\/\/==============================================================================\r\nbool RP2A03AudioProcessor::hasEditor() const\r\n{\r\n return true;\r\n}\r\n\r\nAudioProcessorEditor* RP2A03AudioProcessor::createEditor()\r\n{\r\n editor = new RP2A03AudioProcessorEditor (*this);\r\n return editor;\r\n}\r\n\r\n\/\/==============================================================================\r\n\/\/ This creates new instances of the plugin..\r\nAudioProcessor* JUCE_CALLTYPE createPluginFilter()\r\n{\r\n return new RP2A03AudioProcessor();\r\n}\r\n<|endoftext|>"} {"text":"<commit_before>a8bbf726-2e4f-11e5-9616-28cfe91dbc4b<commit_msg>a8c6fe28-2e4f-11e5-85b1-28cfe91dbc4b<commit_after>a8c6fe28-2e4f-11e5-85b1-28cfe91dbc4b<|endoftext|>"} {"text":"<commit_before>5d2865a9-2d16-11e5-af21-0401358ea401<commit_msg>5d2865aa-2d16-11e5-af21-0401358ea401<commit_after>5d2865aa-2d16-11e5-af21-0401358ea401<|endoftext|>"} {"text":"<commit_before>559f0f5e-2e4f-11e5-82f2-28cfe91dbc4b<commit_msg>55a60eb5-2e4f-11e5-b6be-28cfe91dbc4b<commit_after>55a60eb5-2e4f-11e5-b6be-28cfe91dbc4b<|endoftext|>"} {"text":"<commit_before>7b38ed99-2e4f-11e5-bba5-28cfe91dbc4b<commit_msg>7b3f4119-2e4f-11e5-8d2c-28cfe91dbc4b<commit_after>7b3f4119-2e4f-11e5-8d2c-28cfe91dbc4b<|endoftext|>"} {"text":"<commit_before>21afcd52-2f67-11e5-9f30-6c40088e03e4<commit_msg>21b8fa92-2f67-11e5-ab68-6c40088e03e4<commit_after>21b8fa92-2f67-11e5-ab68-6c40088e03e4<|endoftext|>"} {"text":"<commit_before>809e9235-2d15-11e5-af21-0401358ea401<commit_msg>809e9236-2d15-11e5-af21-0401358ea401<commit_after>809e9236-2d15-11e5-af21-0401358ea401<|endoftext|>"} {"text":"<commit_before>603bf452-5216-11e5-8613-6c40088e03e4<commit_msg>60490942-5216-11e5-8862-6c40088e03e4<commit_after>60490942-5216-11e5-8862-6c40088e03e4<|endoftext|>"} {"text":"<commit_before>2d30c122-2f67-11e5-a7ac-6c40088e03e4<commit_msg>2d37109a-2f67-11e5-964d-6c40088e03e4<commit_after>2d37109a-2f67-11e5-964d-6c40088e03e4<|endoftext|>"} {"text":"<commit_before>#include <vector>\n#include <iterator>\n#include <algorithm>\n#include <values.h>\n#include <cstdlib>\n#include <iostream>\n#include <fstream>\n#include <assert.h>\n#include <utility>\n#include <cmath>\nusing namespace std;\n\nostream & operator <<(ostream &os, const vector<double> &d)\n{\n os << \"V(\";\n for (int i = 0; i < d.size(); i++) {\n if (i > 0) os << \",\";\n os << d[i];\n }\n return os << \")\";\n}\n\n#include \"dataset.h\"\n#include \"tuple.h\"\n#include \"random.h\"\n#include \"extra.h\"\n#include \"regressor.h\"\n#include \"policy.h\"\n#include \"domain.h\"\n#include \"fqi.h\"\n\n\/** Calculate the mean squared error of the output for a data set,\n * given a tree.\n *\/\ndouble mse(const dataset &ts, const ExtraTree &rf) \n{\n double mse;\n for (int i = 0; i < ts.size(); i++) {\n double tmp = rf.output(ts.data[i].attributes) - ts.data[i].output;\n mse += tmp * tmp;\n }\n return mse \/ ts.size();\n}\n\n\/* Read the Parkinson's disease data (classification)\n *\/\nvoid readparkinsons(dataset &ts) {\n ifstream src(\"testing\/parkinsons.data\");\n string line;\n\n while (getline(src, line)) {\n double tmp[24];\n int i = 0;\n int p1 = 0;\n int p2 = 0;\n while ((p2 = line.find(',', p1)) != string::npos) {\n tmp[i++] = strtod(line.substr(p1, p2 - p1).c_str(), NULL);\n p1 = p2 + 1;\n }\n tmp[i++] = strtod(line.substr(p1).c_str(), NULL);\n datum d;\n d.output = tmp[17] > 0.0 ? 1.0 : -1.0;\n for (int j = 1; j < 17; j++) {\n d.attributes.push_back(tmp[j]);\n }\n for (int j = 18; j < 24; j++) {\n d.attributes.push_back(tmp[j]);\n }\n ts.data.push_back(d);\n }\n}\n\nvoid readwdbc(dataset &ts) {\n ifstream src(\"testing\/wdbc.data\");\n string line;\n\n while (getline(src, line)) {\n double tmp[100];\n int i = 0;\n int n = 0;\n int p1 = 0;\n int p2 = 0;\n while ((p2 = line.find(',', p1)) != string::npos) {\n string subs = line.substr(p1, p2 - p1);\n\n \/* index 0 is ignored, index 1 is either 'M' or 'B', the rest are \n * features. \n *\/\n if (n == 1) {\n tmp[i++] = (subs.compare(\"M\") == 0) ? 1.0 : -1.0;\n }\n else if (n >= 2) {\n tmp[i++] = strtod(subs.c_str(), NULL);\n }\n n++;\n p1 = p2 + 1;\n }\n tmp[i++] = strtod(line.substr(p1).c_str(), NULL);\n datum d;\n d.output = tmp[0];\n for (int j = 1; j < i; j++) {\n d.attributes.push_back(tmp[j]);\n }\n ts.data.push_back(d);\n }\n}\n\n\/* Read the yacht hydrodynamics data (regression)\n *\/\nvoid readhydro(dataset &ts) {\n ifstream src(\"testing\/yacht_hydrodynamics.data\");\n string line;\n\n while (getline(src, line)) {\n double tmp[7];\n int i = 0;\n int p1 = 0;\n int p2 = 0;\n while ((p2 = line.find(' ', p1)) != string::npos) {\n tmp[i++] = strtod(line.substr(p1, p2 - p1).c_str(), NULL);\n p1 = p2 + 1;\n }\n tmp[i++] = strtod(line.substr(p1).c_str(), NULL);\n datum d;\n d.output = tmp[6];\n for (int j = 0; j < 6; j++) {\n d.attributes.push_back(tmp[j]);\n }\n ts.data.push_back(d);\n }\n}\n\ndouble checkRegression(const dataset &ts, int ntrain, ExtraTree &rf) {\n dataset trainset, testset;\n ts.randomFold(ntrain, trainset, testset);\n\n rf.train(trainset, false);\n\n return mse(testset, rf); \/\/ Calculate mean squared error\n}\n\nvoid testRegression(int nfolds, const dataset &ts) {\n int ntrain = ts.size() * (nfolds - 1) \/ nfolds;\n\n for (int i = 1; i <= nfolds; i++) {\n cout << \"Fold \" << i;\n ExtraTree rf(ts.nd(), 30, 2);\n double mse = checkRegression(ts, ntrain, rf);\n cout << \" mse \" << mse << endl;\n assert(mse < 3.5);\n }\n}\n\nclass ConfusionMatrix {\nprivate:\n int tp, tn, fp, fn;\n \npublic:\n ConfusionMatrix(int i_tp = 0, int i_tn = 0, int i_fp = 0, int i_fn = 0) {\n tp = i_tp;\n tn = i_tn;\n fp = i_fp;\n fn = i_fn;\n }\n\n ConfusionMatrix operator +(const ConfusionMatrix &cm) {\n ConfusionMatrix r(tp + cm.tp,\n tn + cm.tn,\n fp + cm.fp,\n fn + cm.fn);\n return r;\n }\n\n int total() const { return (tp + tn + fp + fn); }\n double accuracy() const { return (tp + tn) \/ (double) total(); }\n double precision() const { return (double) tp \/ (tp + fp); }\n double recall() { return (double) tp \/ (tp + fn); }\n double specificity() { return (double) tn \/ (tn + fp); }\n \n void record(double nPred, double nTrue) {\n if (nPred == nTrue) {\n if (nPred > 0) {\n tp += 1;\n }\n else {\n tn += 1;\n }\n }\n else {\n if (nPred > 0) {\n fp += 1;\n }\n else {\n fn += 1;\n }\n }\n }\n friend ostream & operator <<(ostream &os, const ConfusionMatrix &d);\n};\n\nostream & operator <<(ostream &os, const ConfusionMatrix &d) {\n return os << \"tp \" << d.tp << \" tn \" << d.tn << \" fp \" << d.fp << \" fn \" << d.fn;\n}\n\nConfusionMatrix checkClassification(const dataset &ts, int ntrain, ExtraTree &rf) {\n dataset trainset, testset;\n ts.randomFold(ntrain, trainset, testset);\n ConfusionMatrix cm;\n\n rf.train(trainset, false);\n\n for (int i = 0; i < testset.size(); i++) {\n datum item = testset.data[i];\n double pred = rf.output(item.attributes);\n cm.record(pred, item.output);\n }\n return cm;\n}\n\nvoid testClassification(int nfolds, const dataset &ts) {\n int ntrain = ts.size() * (nfolds - 1) \/ nfolds;\n ConfusionMatrix cmTotal;\n\n for (int i = 1; i <= nfolds; i++) {\n cout << \"Fold \" << i << \" \";\n ExtraTreeClassification rf(ts.nd(), 100, 2);\n ConfusionMatrix cm = checkClassification(ts, ntrain, rf);\n cout << cm << endl;\n cmTotal = cmTotal + cm;\n }\n\n cout << \"Totals: \" << cmTotal << endl;\n cout << \"Overall precision: \" << cmTotal.precision() << endl;\n cout << \"Overall recall: \" << cmTotal.recall() << endl;\n cout << \"Accuracy: \" << cmTotal.accuracy() << endl;\n}\n\n#include \"getopt.h\"\n\nint main(int argc, char **argv) {\n const char *domain = \"mc\";\n\n Domain *pd;\n Regressor *pr;\n FQI *fqi;\n int c;\n int tflag = 0;\n int sflag = 0;\n while ((c = getopt(argc, argv, \"tsd:\")) != -1) {\n switch (c) {\n case 't':\n tflag++;\n break;\n case 's':\n sflag++;\n break;\n case 'd':\n domain = optarg;\n break;\n case '?':\n return 1;\n default:\n break;\n }\n }\n\n if (tflag) {\n dataset ts1, ts2, ts3;\n\n cout << \"Testing classification with parkinsons.data.\" << endl;\n readparkinsons(ts1);\n testClassification(10, ts1);\n\n cout << \"Testing classification with wdbc.data.\" << endl;\n readwdbc(ts2);\n testClassification(10, ts2);\n\n cout << \"Testing regression with yacht_hydrodynamics.data.\" << endl;\n readhydro(ts3);\n testRegression(10, ts3);\n return 0;\n }\n else {\n pd = CreateDomain(domain);\n if (sflag) {\n pr = new SingleETRegressor(pd->numActions, pd->numDimensions);\n }\n else {\n pr = new ExtraTreeRegressor(pd->numActions, pd->numDimensions);\n }\n fqi = new FQI(pd, pr, 0.98, 400, 10, 30);\n fqi->run();\n }\n cout << \"done!\" << endl;\n}\n<commit_msg>Improve documentation and testing, remove warnings.<commit_after>\/** \\file\n * \\brief Main program and testing harness for the FQI and ExtraTree\n * algorithms.\n *\n * Copyright (c) 2008-2014 Robert D. Vincent.\n *\/\n#include <vector>\n#include <iterator>\n#include <algorithm>\n#include <values.h>\n#include <cstdlib>\n#include <iostream>\n#include <iomanip>\n#include <fstream>\n#include <assert.h>\n#include <utility>\n#include <cmath>\nusing namespace std;\n\n\/**\n * Helper function to print a vector of doubles to a stream.\n *\/\nostream & operator <<(ostream &os, const vector<double> &d)\n{\n os << \"V(\";\n for (size_t i = 0; i < d.size(); i++) {\n if (i > 0) os << \",\";\n os << d[i];\n }\n return os << \")\";\n}\n\n#include \"dataset.h\"\n#include \"tuple.h\"\n#include \"random.h\"\n#include \"extra.h\"\n#include \"regressor.h\"\n#include \"policy.h\"\n#include \"domain.h\"\n#include \"fqi.h\"\n\n\/**\n * Calculate the mean squared error of the output for a data set,\n * given a tree. Used for testing.\n * \\param ts The dataset to test against.\n * \\param rf The ExtraTree to test.\n * \\return The average mean squared error over the entire \\c dataset.\n *\/\ndouble mse(const dataset &ts, const ExtraTree &rf)\n{\n double mse = 0.0;\n for (size_t i = 0; i < ts.size(); i++) {\n double tmp = rf.output(ts.data[i].attributes) - ts.data[i].output;\n mse += tmp * tmp;\n }\n return mse \/ ts.size();\n}\n\n\/**\n * Read the Parkinson's disease classification data (Little et al. 2007)\n * from the UCI repository. Used for testing.\n * \\param ts The returned dataset.\n *\/\nvoid readparkinsons(dataset &ts) {\n ifstream src(\"testing\/parkinsons.data\");\n string line;\n\n while (getline(src, line)) {\n double tmp[24];\n int i = 0;\n size_t p1 = 0;\n size_t p2 = 0;\n while ((p2 = line.find(',', p1)) != string::npos) {\n tmp[i++] = strtod(line.substr(p1, p2 - p1).c_str(), NULL);\n p1 = p2 + 1;\n }\n tmp[i++] = strtod(line.substr(p1).c_str(), NULL);\n datum d;\n d.output = tmp[17] > 0.0 ? 1.0 : -1.0;\n for (int j = 1; j < 17; j++) {\n d.attributes.push_back(tmp[j]);\n }\n for (int j = 18; j < 24; j++) {\n d.attributes.push_back(tmp[j]);\n }\n ts.data.push_back(d);\n }\n}\n\n\/**\n * Read WDBC (Wisconsin diagnostic breast cancer) data (classification).\n * Used for testing.\n * \\param ts The returned dataset.\n *\/\nvoid readwdbc(dataset &ts) {\n ifstream src(\"testing\/wdbc.data\");\n string line;\n\n while (getline(src, line)) {\n double tmp[100];\n int i = 0;\n int n = 0;\n size_t p1 = 0;\n size_t p2 = 0;\n while ((p2 = line.find(',', p1)) != string::npos) {\n string subs = line.substr(p1, p2 - p1);\n\n \/* index 0 is ignored, index 1 is either 'M' or 'B', the rest are\n * features.\n *\/\n if (n == 1) {\n tmp[i++] = (subs.compare(\"M\") == 0) ? 1.0 : -1.0;\n }\n else if (n >= 2) {\n tmp[i++] = strtod(subs.c_str(), NULL);\n }\n n++;\n p1 = p2 + 1;\n }\n tmp[i++] = strtod(line.substr(p1).c_str(), NULL);\n datum d;\n d.output = tmp[0];\n for (int j = 1; j < i; j++) {\n d.attributes.push_back(tmp[j]);\n }\n ts.data.push_back(d);\n }\n}\n\n\/**\n * Read the yacht hydrodynamics data (regression). Used for testing.\n * \\param ts The returned dataset.\n *\/\nvoid readhydro(dataset &ts) {\n ifstream src(\"testing\/yacht_hydrodynamics.data\");\n string line;\n\n while (getline(src, line)) {\n double tmp[7];\n int i = 0;\n size_t p1 = 0;\n size_t p2 = 0;\n while ((p2 = line.find(' ', p1)) != string::npos) {\n tmp[i++] = strtod(line.substr(p1, p2 - p1).c_str(), NULL);\n p1 = p2 + 1;\n }\n tmp[i++] = strtod(line.substr(p1).c_str(), NULL);\n datum d;\n d.output = tmp[6];\n for (int j = 0; j < 6; j++) {\n d.attributes.push_back(tmp[j]);\n }\n ts.data.push_back(d);\n }\n}\n\n\/**\n * Calculate regression results for an ExtraTree. Generates a random fold\n * of the dataset \\c ts with \\c ntrain elements and a test set containing the\n * remainder of the elements. Used for testing.\n *\n * \\param ts The dataset to test against.\n * \\param ntrain The number of training examples to use.\n * \\param rf The ExtraTree to test.\n * \\return The average mean-square error of the regression.\n *\/\ndouble checkRegression(const dataset &ts, int ntrain, ExtraTree &rf) {\n dataset trainset, testset;\n ts.randomFold(ntrain, trainset, testset);\n\n rf.train(trainset, false);\n\n return mse(testset, rf); \/\/ Calculate mean squared error\n}\n\n\/**\n * Perform an n-fold test using a particular \\c dataset. Used for testing.\n * \\param nfolds The number of test folds.\n * \\param ts The training \\c dataset.\n * \\return The average mean-squared error over all of the folds.\n *\/\ndouble testRegression(int nfolds, const dataset &ts) {\n int ntrain = ts.size() * (nfolds - 1) \/ nfolds;\n double sum = 0.0;\n\n for (int i = 0; i < nfolds; i++) {\n cout << \"Fold: \" << i+1 << \" \";\n ExtraTree rf(ts.nd(), 100, 5);\n double mse = checkRegression(ts, ntrain, rf);\n cout << \"MSE: \" << mse << endl;\n sum += mse;\n }\n return (sum \/ nfolds);\n}\n\n\/**\n * Represents a standard binary confusion matrix.\n *\/\nclass ConfusionMatrix {\nprivate:\n int tp; \/**< Number of true positives *\/\n int tn; \/**< Number of true negatives *\/\n int fp; \/**< Number of false positives *\/\n int fn; \/**< Number of false negatives *\/\n\npublic:\n \/** Constructor for a confusion matrix.\n *\n * \\param i_tp Initial number of true positives.\n * \\param i_tn Initial number of true negatives.\n * \\param i_fp Initial number of false positives.\n * \\param i_fn Initial number of false negatives.\n *\/\n ConfusionMatrix(int i_tp = 0, int i_tn = 0, int i_fp = 0, int i_fn = 0) {\n tp = i_tp;\n tn = i_tn;\n fp = i_fp;\n fn = i_fn;\n }\n\n \/**\n * Add two confusion matrices elementwise.\n * \\param cm The right-hand operand of the addition.\n *\/\n ConfusionMatrix operator +(const ConfusionMatrix &cm) {\n ConfusionMatrix r(tp + cm.tp,\n tn + cm.tn,\n fp + cm.fp,\n fn + cm.fn);\n return r;\n }\n\n \/**\n * Calculate the total number of results.\n *\/\n int total() const { return (tp + tn + fp + fn); }\n\n \/**\n * Calculate the overall accuracy, which is the percentage of\n * correct results overall.\n *\/\n double accuracy() const { return (tp + tn) \/ (double) total(); }\n\n \/**\n * Calculate the overall precision, or the ratio of true positives to\n * all positives.\n *\/\n double precision() const { return (double) tp \/ (tp + fp); }\n\n \/**\n * Calculate the recall, or the ratio of true positives to\n * true positives and false negatives.\n *\/\n double recall() { return (double) tp \/ (tp + fn); }\n\n \/**\n * Calculate the specificity, or the ratio of true negatives to\n * true negatives plus false positives.\n *\/\n double specificity() { return (double) tn \/ (tn + fp); }\n\n \/**\n * Record the result of a classification event.\n * \\param nPred The predicted label.\n * \\param nTrue The actual label.\n *\/\n void record(double nPred, double nTrue) {\n if (nPred == nTrue) {\n if (nPred > 0) {\n tp += 1;\n }\n else {\n tn += 1;\n }\n }\n else {\n if (nPred > 0) {\n fp += 1;\n }\n else {\n fn += 1;\n }\n }\n }\n\n friend ostream & operator <<(ostream &os, const ConfusionMatrix &d);\n};\n\n\/**\n * Print a ConfusionMatrix in a human-readable manner.\n * \\param os The output stream.\n * \\param d The ConfusionMatrix to print.\n *\/\nostream & operator <<(ostream &os, const ConfusionMatrix &d) {\n return os << \"tp \" << d.tp << \" tn \" << d.tn << \" fp \" << d.fp << \" fn \" << d.fn;\n}\n\n\/**\n * Calculate classification results.\n * \\param ts The entire training set.\n * \\param ntrain The number of training examples to use.\n * \\param rf The ExtraTree to use.\n * \\return A summary of the classification results.\n *\/\nConfusionMatrix checkClassification(const dataset &ts, int ntrain, ExtraTree &rf) {\n dataset trainset, testset;\n ts.randomFold(ntrain, trainset, testset);\n ConfusionMatrix cm;\n\n rf.train(trainset, false);\n\n for (size_t i = 0; i < testset.size(); i++) {\n datum item = testset.data[i];\n double pred = rf.output(item.attributes);\n cm.record(pred, item.output);\n }\n return cm;\n}\n\n\/**\n * Perform n-fold validation with a \\c dataset.\n * \\param nfolds The number of cross-validation folds to perform.\n * \\param ts The training dataset.\n * \\return The overall accuracy.\n *\/\ndouble testClassification(int nfolds, const dataset &ts) {\n int ntrain = ts.size() * (nfolds - 1) \/ nfolds;\n ConfusionMatrix cmTotal;\n cout << \"Performing \" << nfolds << \" folds with \";\n cout << ntrain << \" training examples out of \" << ts.size() << \".\" << endl;\n\n for (int i = 0; i < nfolds; i++) {\n cout << \"Fold: \" << i+1 << \" \";\n ExtraTreeClassification rf(ts.nd(), 51, 2);\n ConfusionMatrix cm = checkClassification(ts, ntrain, rf);\n cout << \"Accuracy: \" << cm.accuracy() << endl;\n cmTotal = cmTotal + cm;\n }\n cout << \"Totals: \" << cmTotal << endl;\n cout << \"Accuracy: \" << setprecision(5) << cmTotal.accuracy() << endl;\n return cmTotal.accuracy();\n}\n\n#include \"getopt.h\"\n\n\/**\n * Our main program. Performs simple command-line processing and sets\n * up for either testing the ExtraTree implementations or running the FQI\n * algorithm on the selected domain.\n *\/\nint main(int argc, char **argv) {\n const char *domain = \"mc\";\n\n Domain *pd;\n Regressor *pr;\n FQI *fqi;\n int c;\n int tflag = 0;\n int sflag = 0;\n while ((c = getopt(argc, argv, \"tsd:\")) != -1) {\n switch (c) {\n case 't':\n tflag++;\n break;\n case 's':\n sflag++;\n break;\n case 'd':\n domain = optarg;\n break;\n case '?':\n return 1;\n default:\n break;\n }\n }\n\n if (tflag) {\n dataset ts1, ts2, ts3;\n\n cout << \"*** Testing classification with parkinsons.data.\" << endl;\n readparkinsons(ts1);\n\n double acc = testClassification(40, ts1);\n \/* Original paper reports 91.8% mean accuracy *\/\n assert(acc > 0.918);\n\n cout << \"*** Testing classification with wdbc.data.\" << endl;\n readwdbc(ts2);\n assert(testClassification(20, ts2) > 0.94);\n\n cout << \"*** Testing regression with yacht_hydrodynamics.data.\" << endl;\n readhydro(ts3);\n double mse = testRegression(20, ts3);\n assert(mse < 2.0);\n cout << \"MSE: \" << setprecision(5) << mse << endl;\n assert(mse < 1.1);\n\n return 0;\n }\n else {\n pd = CreateDomain(domain);\n if (sflag) {\n pr = new SingleETRegressor(pd->numActions, pd->numDimensions);\n }\n else {\n pr = new ExtraTreeRegressor(pd->numActions, pd->numDimensions);\n }\n fqi = new FQI(pd, pr, 0.98, 400, 10, 30);\n fqi->run();\n }\n cout << \"done!\" << endl;\n}\n<|endoftext|>"} {"text":"<commit_before>d53de28a-327f-11e5-867f-9cf387a8033e<commit_msg>d54763fa-327f-11e5-9cbe-9cf387a8033e<commit_after>d54763fa-327f-11e5-9cbe-9cf387a8033e<|endoftext|>"} {"text":"<commit_before>09c50fae-2e4f-11e5-a2d8-28cfe91dbc4b<commit_msg>09d167d4-2e4f-11e5-9710-28cfe91dbc4b<commit_after>09d167d4-2e4f-11e5-9710-28cfe91dbc4b<|endoftext|>"} {"text":"<commit_before>d49c8494-313a-11e5-b02d-3c15c2e10482<commit_msg>d4a251c5-313a-11e5-8922-3c15c2e10482<commit_after>d4a251c5-313a-11e5-8922-3c15c2e10482<|endoftext|>"} {"text":"<commit_before>#include <math.h>\n#include <stdio.h>\n\nstruct Vec3\n{\n typedef const Vec3& InParam;\n\n Vec3() {}\n\n Vec3(const float x, const float y, const float z)\n : x(x)\n , y(y)\n , z(z)\n {\n }\n\n float x, y, z;\n};\n\nVec3& operator+=(Vec3& left, Vec3::InParam right) {\n left.x += right.x;\n left.y += right.y;\n left.z += right.z;\n return left;\n}\n\nVec3 operator+(Vec3::InParam left, Vec3::InParam right) {\n return Vec3{\n left.x + right.x,\n left.y + right.y,\n left.z + right.z\n };\n}\n\nVec3 operator-(Vec3::InParam left, Vec3::InParam right) {\n return Vec3{\n left.x - right.x,\n left.y - right.y,\n left.z - right.z\n };\n}\n\nVec3 operator*(Vec3::InParam v, const float scale) {\n return Vec3 {\n v.x * scale,\n v.y * scale,\n v.z * scale\n };\n}\n\nVec3& operator*=(Vec3& v, const float scale) {\n v.x *= scale;\n v.y *= scale;\n v.z *= scale;\n return v;\n}\n\nfloat dot(Vec3::InParam left, Vec3::InParam right) {\n return left.x*right.x + left.y*right.y + left.z*right.z;\n}\n\nfloat length_squared(const float x, const float y, const float z) {\n return x*x + y*y + z*z;\n}\n\nfloat length_squared(Vec3::InParam in) {\n return length_squared(in.x, in.y, in.z);\n}\n\nfloat length(const float x, const float y) {\n return sqrt(x*x + y*y);\n}\n\nfloat length(const float x, const float y, const float z) {\n return sqrt(x*x + y*y + z*z);\n}\n\nfloat length(Vec3::InParam in) {\n return length(in.x, in.y, in.z);\n}\n\nVec3 normalised(Vec3::InParam in) {\n const float scale = 1.0f \/ length(in);\n return in * scale;\n}\n\nVec3 lerp(Vec3::InParam from, Vec3::InParam to, const float t) {\n return (from * (1.0f - t) + (to * t));\n}\n\nVec3 reflected(Vec3::InParam direction, Vec3::InParam normal) {\n const float scale = -2.0f * dot(direction, normal);\n return direction + normal * scale;\n}\n\nVec3 sample_sky(const Vec3::InParam direction) {\n const Vec3 up{0.0f, 1.0f, 0.0f};\n\n const float red = 32.0f;\n const float green = 128.0f;\n const float blue = 180.0f + 64.0f * dot(direction, up);\n\n return Vec3 {red, green, blue};\n}\n\nVec3 sample_ground(\n const Vec3::InParam position,\n const Vec3::InParam direction,\n const Vec3::InParam sphere_point_on_ground,\n const float sphere_magnitude_squared)\n{\n const float inverse_square_scale = 0.1f;\n const int x = fabs(position.x * inverse_square_scale);\n const int y = fabs(position.z * inverse_square_scale);\n\n const Vec3 world_down {0.0f, -1.0f, 0.0f};\n const float dot_down {dot(direction, world_down)};\n\n Vec3 colour;\n\n if ((x%2) ^ (y%2)) {\n const Vec3 green {32.0f, 128.0f, 32.0f};\n const Vec3 light_green {green * 2.0f};\n colour = lerp(green, light_green, dot_down);\n } else {\n const Vec3 green {64.0f, 128.0f, 64.0f};\n const Vec3 light_green {green * 2.0f};\n colour = lerp(green, light_green, dot_down);\n }\n\n const Vec3 to_sphere_on_ground = sphere_point_on_ground - position;\n if (length_squared(to_sphere_on_ground) < sphere_magnitude_squared) {\n colour *= 0.5f;\n }\n\n return colour;\n}\n\nVec3 sample_sphere(\n const Vec3::InParam position,\n const Vec3::InParam normal,\n const Vec3::InParam direction)\n{\n const Vec3 world_up {0.0f, 1.0f, 0.0f};\n const float dot_up {dot(normal, world_up)};\n\n const Vec3 half {0.5f, 0.5f, 0.5f};\n const Vec3 color {(normal * 0.5f + half) * 255.0f};\n const Vec3 half_color {color * 0.5f};\n return lerp(half_color, color, dot_up);\n}\n\n\nVec3 sample(Vec3 position, Vec3 direction) {\n\n Vec3 colour {0.0f, 0.0f, 0.0f};\n float colour_blend = 1.0f;\n\n \/\/ check for collision against sphere\n const Vec3 sphere_point {0.0f, 15.0f, 40.0f};\n const Vec3 sphere_point_on_ground {0.0f, 0.0f, 40.0f};\n const float sphere_magnitude = 11.0f;\n const float sphere_magnitude_squared = sphere_magnitude * sphere_magnitude;\n const Vec3 to_sphere {sphere_point - position};\n const float closest_to_sphere {dot(direction, to_sphere)};\n const Vec3 point_nearest_sphere {position + direction * closest_to_sphere};\n const float length_to_sphere {length(sphere_point - point_nearest_sphere)};\n \/\/ TODO: use squared magnitude\n if (length_to_sphere < sphere_magnitude) {\n \/\/ calc intersection point\n const float adjacent_length = sqrt(\n sphere_magnitude * sphere_magnitude\n - length_to_sphere * length_to_sphere);\n const Vec3 intersection {\n point_nearest_sphere - (direction * adjacent_length)};\n\n \/\/ sample the sphere\n const Vec3 normal {normalised(intersection - sphere_point)};\n position = intersection;\n direction = reflected(direction, normal);\n colour = lerp(\n colour,\n sample_sphere(intersection, normal, direction),\n colour_blend);\n colour_blend = 0.5f;\n }\n\n \/\/ check for collision against ground\n const Vec3 ground_inverse_normal(0.0f, -1.0f, 0.0f);\n if (dot(ground_inverse_normal, direction) > 0.0f) {\n \/\/ hit the ground, figure out where\n const Vec3 ground_point(0.0f, 0.0f, 0.0f);\n const Vec3 to_ground {ground_point - position};\n const float distance_to_ground {dot(to_ground, ground_inverse_normal)};\n const float dot_to_ground {dot(direction, ground_inverse_normal)};\n const float distance {distance_to_ground \/ dot_to_ground};\n const Vec3 ground_intersection {position + direction * distance};\n colour = lerp(\n colour,\n sample_ground(\n ground_intersection,\n direction,\n sphere_point_on_ground,\n sphere_magnitude_squared),\n colour_blend);\n } else {\n colour = lerp(\n colour,\n \/\/ TODO: remove position parameter\n sample_sky(direction),\n colour_blend);\n }\n\n return colour;\n}\n\nvoid draw_scene(const int image_width, const int image_height) {\n const Vec3 camera_forward{0.0f, 0.0f, 1.0f};\n const Vec3 camera_right{1.0f, 0.0f, 0.0f};\n const Vec3 camera_up{0.0f, 1.0f, 0.0f};\n const Vec3 camera_pos{0.0f, 10.0f, 0.0f};\n\n const int half_image_width = image_width \/ 2;\n const int half_image_height = image_height \/ 2;\n\n for (int y=image_height-1; y>=0; --y) {\n for (int x=0; x<image_width; ++x) {\n const Vec3 pixel_offset = Vec3 {\n float(x-half_image_width),\n float(y-half_image_height),\n 0.0f};\n\n const Vec3 pixel_direction = normalised(\n camera_forward*image_height + pixel_offset);\n\n const Vec3 colour = sample(camera_pos, pixel_direction);\n\n printf(\"%c%c%c\", int(colour.x), int(colour.y), int(colour.z));\n }\n }\n}\n\nint main() {\n printf(\"P6 512 512 255 \");\n draw_scene(512, 512);\n}\n\n\/\/ Copyright 2014 Angelos Evripiotis\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n<commit_msg>Refactor, lerp() - clearer bracketization<commit_after>#include <math.h>\n#include <stdio.h>\n\nstruct Vec3\n{\n typedef const Vec3& InParam;\n\n Vec3() {}\n\n Vec3(const float x, const float y, const float z)\n : x(x)\n , y(y)\n , z(z)\n {\n }\n\n float x, y, z;\n};\n\nVec3& operator+=(Vec3& left, Vec3::InParam right) {\n left.x += right.x;\n left.y += right.y;\n left.z += right.z;\n return left;\n}\n\nVec3 operator+(Vec3::InParam left, Vec3::InParam right) {\n return Vec3{\n left.x + right.x,\n left.y + right.y,\n left.z + right.z\n };\n}\n\nVec3 operator-(Vec3::InParam left, Vec3::InParam right) {\n return Vec3{\n left.x - right.x,\n left.y - right.y,\n left.z - right.z\n };\n}\n\nVec3 operator*(Vec3::InParam v, const float scale) {\n return Vec3 {\n v.x * scale,\n v.y * scale,\n v.z * scale\n };\n}\n\nVec3& operator*=(Vec3& v, const float scale) {\n v.x *= scale;\n v.y *= scale;\n v.z *= scale;\n return v;\n}\n\nfloat dot(Vec3::InParam left, Vec3::InParam right) {\n return left.x*right.x + left.y*right.y + left.z*right.z;\n}\n\nfloat length_squared(const float x, const float y, const float z) {\n return x*x + y*y + z*z;\n}\n\nfloat length_squared(Vec3::InParam in) {\n return length_squared(in.x, in.y, in.z);\n}\n\nfloat length(const float x, const float y) {\n return sqrt(x*x + y*y);\n}\n\nfloat length(const float x, const float y, const float z) {\n return sqrt(x*x + y*y + z*z);\n}\n\nfloat length(Vec3::InParam in) {\n return length(in.x, in.y, in.z);\n}\n\nVec3 normalised(Vec3::InParam in) {\n const float scale = 1.0f \/ length(in);\n return in * scale;\n}\n\nVec3 lerp(Vec3::InParam from, Vec3::InParam to, const float t) {\n return (from * (1.0f - t)) + (to * t);\n}\n\nVec3 reflected(Vec3::InParam direction, Vec3::InParam normal) {\n const float scale = -2.0f * dot(direction, normal);\n return direction + normal * scale;\n}\n\nVec3 sample_sky(const Vec3::InParam direction) {\n const Vec3 up{0.0f, 1.0f, 0.0f};\n\n const float red = 32.0f;\n const float green = 128.0f;\n const float blue = 180.0f + 64.0f * dot(direction, up);\n\n return Vec3 {red, green, blue};\n}\n\nVec3 sample_ground(\n const Vec3::InParam position,\n const Vec3::InParam direction,\n const Vec3::InParam sphere_point_on_ground,\n const float sphere_magnitude_squared)\n{\n const float inverse_square_scale = 0.1f;\n const int x = fabs(position.x * inverse_square_scale);\n const int y = fabs(position.z * inverse_square_scale);\n\n const Vec3 world_down {0.0f, -1.0f, 0.0f};\n const float dot_down {dot(direction, world_down)};\n\n Vec3 colour;\n\n if ((x%2) ^ (y%2)) {\n const Vec3 green {32.0f, 128.0f, 32.0f};\n const Vec3 light_green {green * 2.0f};\n colour = lerp(green, light_green, dot_down);\n } else {\n const Vec3 green {64.0f, 128.0f, 64.0f};\n const Vec3 light_green {green * 2.0f};\n colour = lerp(green, light_green, dot_down);\n }\n\n const Vec3 to_sphere_on_ground = sphere_point_on_ground - position;\n if (length_squared(to_sphere_on_ground) < sphere_magnitude_squared) {\n colour *= 0.5f;\n }\n\n return colour;\n}\n\nVec3 sample_sphere(\n const Vec3::InParam position,\n const Vec3::InParam normal,\n const Vec3::InParam direction)\n{\n const Vec3 world_up {0.0f, 1.0f, 0.0f};\n const float dot_up {dot(normal, world_up)};\n\n const Vec3 half {0.5f, 0.5f, 0.5f};\n const Vec3 color {(normal * 0.5f + half) * 255.0f};\n const Vec3 half_color {color * 0.5f};\n return lerp(half_color, color, dot_up);\n}\n\n\nVec3 sample(Vec3 position, Vec3 direction) {\n\n Vec3 colour {0.0f, 0.0f, 0.0f};\n float colour_blend = 1.0f;\n\n \/\/ check for collision against sphere\n const Vec3 sphere_point {0.0f, 15.0f, 40.0f};\n const Vec3 sphere_point_on_ground {0.0f, 0.0f, 40.0f};\n const float sphere_magnitude = 11.0f;\n const float sphere_magnitude_squared = sphere_magnitude * sphere_magnitude;\n const Vec3 to_sphere {sphere_point - position};\n const float closest_to_sphere {dot(direction, to_sphere)};\n const Vec3 point_nearest_sphere {position + direction * closest_to_sphere};\n const float length_to_sphere {length(sphere_point - point_nearest_sphere)};\n \/\/ TODO: use squared magnitude\n if (length_to_sphere < sphere_magnitude) {\n \/\/ calc intersection point\n const float adjacent_length = sqrt(\n sphere_magnitude * sphere_magnitude\n - length_to_sphere * length_to_sphere);\n const Vec3 intersection {\n point_nearest_sphere - (direction * adjacent_length)};\n\n \/\/ sample the sphere\n const Vec3 normal {normalised(intersection - sphere_point)};\n position = intersection;\n direction = reflected(direction, normal);\n colour = lerp(\n colour,\n sample_sphere(intersection, normal, direction),\n colour_blend);\n colour_blend = 0.5f;\n }\n\n \/\/ check for collision against ground\n const Vec3 ground_inverse_normal(0.0f, -1.0f, 0.0f);\n if (dot(ground_inverse_normal, direction) > 0.0f) {\n \/\/ hit the ground, figure out where\n const Vec3 ground_point(0.0f, 0.0f, 0.0f);\n const Vec3 to_ground {ground_point - position};\n const float distance_to_ground {dot(to_ground, ground_inverse_normal)};\n const float dot_to_ground {dot(direction, ground_inverse_normal)};\n const float distance {distance_to_ground \/ dot_to_ground};\n const Vec3 ground_intersection {position + direction * distance};\n colour = lerp(\n colour,\n sample_ground(\n ground_intersection,\n direction,\n sphere_point_on_ground,\n sphere_magnitude_squared),\n colour_blend);\n } else {\n colour = lerp(\n colour,\n \/\/ TODO: remove position parameter\n sample_sky(direction),\n colour_blend);\n }\n\n return colour;\n}\n\nvoid draw_scene(const int image_width, const int image_height) {\n const Vec3 camera_forward{0.0f, 0.0f, 1.0f};\n const Vec3 camera_right{1.0f, 0.0f, 0.0f};\n const Vec3 camera_up{0.0f, 1.0f, 0.0f};\n const Vec3 camera_pos{0.0f, 10.0f, 0.0f};\n\n const int half_image_width = image_width \/ 2;\n const int half_image_height = image_height \/ 2;\n\n for (int y=image_height-1; y>=0; --y) {\n for (int x=0; x<image_width; ++x) {\n const Vec3 pixel_offset = Vec3 {\n float(x-half_image_width),\n float(y-half_image_height),\n 0.0f};\n\n const Vec3 pixel_direction = normalised(\n camera_forward*image_height + pixel_offset);\n\n const Vec3 colour = sample(camera_pos, pixel_direction);\n\n printf(\"%c%c%c\", int(colour.x), int(colour.y), int(colour.z));\n }\n }\n}\n\nint main() {\n printf(\"P6 512 512 255 \");\n draw_scene(512, 512);\n}\n\n\/\/ Copyright 2014 Angelos Evripiotis\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n<|endoftext|>"} {"text":"<commit_before>67c08d78-2e3a-11e5-9f4c-c03896053bdd<commit_msg>67d52aa8-2e3a-11e5-b008-c03896053bdd<commit_after>67d52aa8-2e3a-11e5-b008-c03896053bdd<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n#include <dirent.h>\n#include <sys\/stat.h>\n#include <unistd.h>\n#include <stdio.h>\n#include <errno.h>\n#include <stdlib.h>\n#include <cstring>\n#include <string>\nusing namespace std;\n\nvoid lsCom() {\n\n}\nbool isDependant = 0;\nint main(int argc, char *argv[]) {\nchar *arg[argc];\nif(argc < 1) {\n cout << \"No arguements passed in\" << endl;\n exit(1);\n}\nelse {\n int currArg = 1;\n string ArgStr;\n cout << argv[1] << endl;\n cout << *(argv[1] + 1) << endl;\n char* test = argv[1];\n while(currArg+1 < argc) {\n arg[0] = argv[currArg];\n int n = 0;\n for(int i = 0; i < strlen(argv[currArg]); ++i) {\n if(*(argv[currArg+1]+i) == ';' && i == (strlen(argv[currArg])-1)){\n *(argv[currArg+1]+i) = '\\0';\n isDependant = 0;\n }\n }\n arg[1] = argv[currArg+1];\n ++currArg;\n }\n arg[2] = NULL;\n \/*\n while(currArg < argc){\n if(*(argv[currArg]).at(0) = '-') {\n if(*(argv[currArg]).at(*(argv[currArg]).size() - 1) == ';') {\n *argv[currArg].pop_back();\n endCommand = 1;\n }\n ArgStr += argv[currArg];\n }\n ++currArg;\n\n\n\n }*\/\n execvp(arg[0], arg);\n \/\/cout << get_current_dir_name() << endl;\n \/*DIR *dirp;\n if( NULL == (dirp = opendir(get_current_dir_name()))) {\n perror(\"The directory could not be opened or does not exist. \");\n exit(1);\n }\n struct dirent *file;\n errno = 0;\n while(NULL != (file = readdir(dirp))) {\n cout << file->d_name << \" \";\n }\n cout << endl;*\/\n }\nreturn 0;\n}\n<commit_msg>commands with no arguements work now<commit_after>#include <iostream>\n#include <dirent.h>\n#include <sys\/stat.h>\n#include <unistd.h>\n#include <stdio.h>\n#include <errno.h>\n#include <stdlib.h>\n#include <cstring>\n#include <string>\nusing namespace std;\n\nvoid lsCom() {\n\n}\nbool isDependant = 0;\nint main(int argc, char *argv[]) {\nchar *arg[argc];\nif(argc < 1) {\n cout << \"No arguements passed in\" << endl;\n exit(1);\n}\nelse {\n int currArg = 1;\n int SAP = 0; \/\/ Sub-Array Position\n string ArgStr;\n char* test = argv[1];\n while(currArg+1 <= argc) {\n SAP = 0;\n arg[SAP] = argv[currArg];\n ++SAP;\n int n = 0;\n for(int i = 0; i < strlen(argv[currArg]); ++i) {\n if(*(argv[currArg]+i) == ';' && i == (strlen(argv[currArg])-1)){\n *(argv[currArg]+i) = '\\0';\n isDependant = 0;\n }\n }\n ++currArg;\n if((currArg) < argc && (argv[currArg]) != \"||\" && (argv[currArg]) != \"&&\") {\n arg[SAP] = argv[currArg];\n ++SAP;\n }\n else {\n arg[SAP] = NULL;\n ++SAP;\n }\n arg[SAP] = NULL;\n char *testa[3] = { NULL};\n if(execvp(arg[0], arg) == -1) {\n perror(\"The command could not be executed!\");\n errno = 0;\n }\n \/*else {\n execvp(arg[0], arg);\n }*\/\n ++currArg;\n }\n }\nreturn 0;\n}\n<|endoftext|>"} {"text":"<commit_before>4dc5f7eb-2e4f-11e5-b5a5-28cfe91dbc4b<commit_msg>4dcd37ee-2e4f-11e5-abad-28cfe91dbc4b<commit_after>4dcd37ee-2e4f-11e5-abad-28cfe91dbc4b<|endoftext|>"} {"text":"<commit_before>75fd2474-2d53-11e5-baeb-247703a38240<commit_msg>75fda516-2d53-11e5-baeb-247703a38240<commit_after>75fda516-2d53-11e5-baeb-247703a38240<|endoftext|>"} {"text":"<commit_before>1ecf1234-2f67-11e5-b07d-6c40088e03e4<commit_msg>1ed5dfe2-2f67-11e5-ac7a-6c40088e03e4<commit_after>1ed5dfe2-2f67-11e5-ac7a-6c40088e03e4<|endoftext|>"} {"text":"<commit_before>d2cd7447-ad5c-11e7-9a5d-ac87a332f658<commit_msg>Tuesday, turns out it was tuesday<commit_after>d338545c-ad5c-11e7-b442-ac87a332f658<|endoftext|>"} {"text":"<commit_before>8431fcd0-2d15-11e5-af21-0401358ea401<commit_msg>8431fcd1-2d15-11e5-af21-0401358ea401<commit_after>8431fcd1-2d15-11e5-af21-0401358ea401<|endoftext|>"} {"text":"<commit_before>e167f6c0-2747-11e6-99cb-e0f84713e7b8<commit_msg>My Backup<commit_after>e172dffd-2747-11e6-84b0-e0f84713e7b8<|endoftext|>"} {"text":"<commit_before>836f9bf5-ad59-11e7-842e-ac87a332f658<commit_msg>I hope I am done<commit_after>8428c335-ad59-11e7-8da2-ac87a332f658<|endoftext|>"} {"text":"<commit_before>9dec79ec-35ca-11e5-be9c-6c40088e03e4<commit_msg>9df3267a-35ca-11e5-8db3-6c40088e03e4<commit_after>9df3267a-35ca-11e5-8db3-6c40088e03e4<|endoftext|>"} {"text":"<commit_before>73c4977d-4b02-11e5-950f-28cfe9171a43<commit_msg>add file<commit_after>73d1cebd-4b02-11e5-b082-28cfe9171a43<|endoftext|>"} {"text":"<commit_before>ceb5a58a-35ca-11e5-b0f0-6c40088e03e4<commit_msg>cebc462e-35ca-11e5-b01c-6c40088e03e4<commit_after>cebc462e-35ca-11e5-b01c-6c40088e03e4<|endoftext|>"} {"text":"<commit_before>a902b6a1-327f-11e5-acc6-9cf387a8033e<commit_msg>a90ac9e3-327f-11e5-98ad-9cf387a8033e<commit_after>a90ac9e3-327f-11e5-98ad-9cf387a8033e<|endoftext|>"} {"text":"<commit_before>e2227b07-2e4e-11e5-b42b-28cfe91dbc4b<commit_msg>e22f8b40-2e4e-11e5-aa98-28cfe91dbc4b<commit_after>e22f8b40-2e4e-11e5-aa98-28cfe91dbc4b<|endoftext|>"} {"text":"<commit_before>1ad19128-2f67-11e5-be7b-6c40088e03e4<commit_msg>1ad80bf4-2f67-11e5-8f4b-6c40088e03e4<commit_after>1ad80bf4-2f67-11e5-8f4b-6c40088e03e4<|endoftext|>"} {"text":"<commit_before>66f48b42-2fa5-11e5-8f4e-00012e3d3f12<commit_msg>66f6ae24-2fa5-11e5-8aae-00012e3d3f12<commit_after>66f6ae24-2fa5-11e5-8aae-00012e3d3f12<|endoftext|>"} {"text":"<commit_before>700567e4-2fa5-11e5-8ebb-00012e3d3f12<commit_msg>70073ca4-2fa5-11e5-9253-00012e3d3f12<commit_after>70073ca4-2fa5-11e5-9253-00012e3d3f12<|endoftext|>"} {"text":"<commit_before>a6c06eae-2e4f-11e5-8524-28cfe91dbc4b<commit_msg>a6c70cb3-2e4f-11e5-9286-28cfe91dbc4b<commit_after>a6c70cb3-2e4f-11e5-9286-28cfe91dbc4b<|endoftext|>"} {"text":"<commit_before>2e10459a-2f67-11e5-a159-6c40088e03e4<commit_msg>2e17a092-2f67-11e5-bb33-6c40088e03e4<commit_after>2e17a092-2f67-11e5-bb33-6c40088e03e4<|endoftext|>"} {"text":"<commit_before>caeb8738-4b02-11e5-b315-28cfe9171a43<commit_msg>update testing<commit_after>caf730eb-4b02-11e5-a544-28cfe9171a43<|endoftext|>"} {"text":"<commit_before>bb87afa1-2747-11e6-a3dd-e0f84713e7b8<commit_msg>Deal with it<commit_after>bb996bca-2747-11e6-afc0-e0f84713e7b8<|endoftext|>"} {"text":"<commit_before>c5d0c719-4b02-11e5-af83-28cfe9171a43<commit_msg>Backup, rebase this later<commit_after>c5de6be8-4b02-11e5-a9bb-28cfe9171a43<|endoftext|>"} {"text":"<commit_before>77da4d07-2e4f-11e5-b70d-28cfe91dbc4b<commit_msg>77df9a99-2e4f-11e5-8a26-28cfe91dbc4b<commit_after>77df9a99-2e4f-11e5-8a26-28cfe91dbc4b<|endoftext|>"} {"text":"<commit_before>cb72e93a-327f-11e5-9491-9cf387a8033e<commit_msg>cb78c72e-327f-11e5-9533-9cf387a8033e<commit_after>cb78c72e-327f-11e5-9533-9cf387a8033e<|endoftext|>"} {"text":"<commit_before>eea4e128-585a-11e5-82dc-6c40088e03e4<commit_msg>eeab4cd4-585a-11e5-9594-6c40088e03e4<commit_after>eeab4cd4-585a-11e5-9594-6c40088e03e4<|endoftext|>"} {"text":"<commit_before>75756b6a-2d53-11e5-baeb-247703a38240<commit_msg>7575ecfc-2d53-11e5-baeb-247703a38240<commit_after>7575ecfc-2d53-11e5-baeb-247703a38240<|endoftext|>"} {"text":"<commit_before>a2a4f90a-35ca-11e5-a056-6c40088e03e4<commit_msg>a2ad6bba-35ca-11e5-b958-6c40088e03e4<commit_after>a2ad6bba-35ca-11e5-b958-6c40088e03e4<|endoftext|>"} {"text":"<commit_before>365993ba-2e3a-11e5-8e2a-c03896053bdd<commit_msg>366703b0-2e3a-11e5-992c-c03896053bdd<commit_after>366703b0-2e3a-11e5-992c-c03896053bdd<|endoftext|>"} {"text":"<commit_before>d6618dc5-327f-11e5-9e7f-9cf387a8033e<commit_msg>d667bfdc-327f-11e5-852a-9cf387a8033e<commit_after>d667bfdc-327f-11e5-852a-9cf387a8033e<|endoftext|>"} {"text":"<commit_before>\n#include \"src\/CmdLineOptions.h\"\n#include \"src\/MicroCore.h\"\n#include \"src\/page.h\"\n\n#include \"ext\/crow\/crow.h\"\n#include \"ext\/member_checker.h\"\n\n#include <fstream>\n\nusing boost::filesystem::path;\n\nusing namespace std;\n\n\/\/ needed for log system of momero\nnamespace epee {\n unsigned int g_test_dbg_lock_sleep = 0;\n}\n\nint main(int ac, const char* av[]) {\n\n \/\/ get command line options\n xmreg::CmdLineOptions opts {ac, av};\n\n auto help_opt = opts.get_option<bool>(\"help\");\n\n \/\/ if help was chosen, display help text and finish\n if (*help_opt)\n {\n return EXIT_SUCCESS;\n }\n\n auto port_opt = opts.get_option<string>(\"port\");\n auto bc_path_opt = opts.get_option<string>(\"bc-path\");\n auto custom_db_path_opt = opts.get_option<string>(\"custom-db-path\");\n auto deamon_url_opt = opts.get_option<string>(\"deamon-url\");\n\n \/\/cast port number in string to uint16\n uint16_t app_port = boost::lexical_cast<uint16_t>(*port_opt);\n\n \/\/ get blockchain path\n path blockchain_path;\n\n if (!xmreg::get_blockchain_path(bc_path_opt, blockchain_path))\n {\n cerr << \"Error getting blockchain path.\" << endl;\n return EXIT_FAILURE;\n }\n\n \/\/ enable basic monero log output\n xmreg::enable_monero_log();\n\n \/\/ create instance of our MicroCore\n \/\/ and make pointer to the Blockchain\n xmreg::MicroCore mcore;\n cryptonote::Blockchain* core_storage;\n\n \/\/ initialize mcore and core_storage\n if (!xmreg::init_blockchain(blockchain_path.string(),\n mcore, core_storage))\n {\n cerr << \"Error accessing blockchain.\" << endl;\n return EXIT_FAILURE;\n }\n\n \/\/ check if we have path to lmdb2 (i.e., custom db)\n \/\/ and if it exists\n\n string custom_db_path_str;\n\n if (custom_db_path_opt)\n {\n if (boost::filesystem::exists(boost::filesystem::path(*custom_db_path_opt)))\n {\n custom_db_path_str = *custom_db_path_opt;\n }\n else\n {\n cerr << \"Custom db path: \" << *custom_db_path_opt\n << \"does not exist\" << endl;\n\n return EXIT_FAILURE;\n }\n }\n else\n {\n \/\/ if not given assume it is located in ~.\/bitmonero\/lmdb2 folder\n custom_db_path_str = blockchain_path.parent_path().string()\n + string(\"\/lmdb2\");\n }\n\n custom_db_path_str = xmreg::remove_trailing_path_separator(custom_db_path_str);\n\n\n \/\/ create instance of page class which\n \/\/ contains logic for the website\n xmreg::page xmrblocks(&mcore, core_storage,\n *deamon_url_opt, custom_db_path_str);\n\n \/\/ crow instance\n crow::SimpleApp app;\n\n CROW_ROUTE(app, \"\/\")\n ([&](const crow::request& req) {\n\n \/\/for (const auto& m : req.headers)\n \/\/ cout << m.first << \": \" << m.second << endl;\n\n \/\/ there is some robot scanning everything\n \/\/ on the explorer. I block it with this\n if (!xmreg::does_header_has(req, \"Accept\", \"q=.2, *\/*; q=.2\").empty())\n {\n cout << \"Scanner with q=.2, *\/*; q=.2 blocked!\" << endl;\n return crow::response(400);\n }\n\n return xmrblocks.index2();\n });\n\n CROW_ROUTE(app, \"\/page\/<uint>\")\n ([&](size_t page_no) {\n return xmrblocks.index2(page_no);\n });\n\n CROW_ROUTE(app, \"\/block\/<uint>\")\n ([&](const crow::request& req, size_t block_height) {\n\n \/\/ there is some robot scanning everything\n \/\/ on the explorer. I block it with this\n if (!xmreg::does_header_has(req, \"Accept\", \"q=.2, *\/*; q=.2\").empty())\n {\n cout << \"Scanner with q=.2, *\/*; q=.2 blocked!\" << endl;\n return crow::response(400);\n }\n\n return crow::response(xmrblocks.show_block(block_height));\n });\n\n CROW_ROUTE(app, \"\/block\/<string>\")\n ([&](const crow::request& req, string block_hash) {\n\n \/\/ there is some robot scanning everything\n \/\/ on the explorer. I block it with this\n if (!xmreg::does_header_has(req, \"Accept\", \"q=.2, *\/*; q=.2\").empty())\n {\n cout << \"Scanner with q=.2, *\/*; q=.2 blocked!\" << endl;\n return crow::response(400);\n }\n\n return crow::response(xmrblocks.show_block(block_hash));\n });\n\n CROW_ROUTE(app, \"\/tx\/<string>\")\n ([&](const crow::request& req, string tx_hash) {\n\n \/\/ there is some robot scanning everything\n \/\/ on the explorer. I block it with this\n if (!xmreg::does_header_has(req, \"Accept\", \"q=.2, *\/*; q=.2\").empty())\n {\n cout << \"Scanner with q=.2, *\/*; q=.2 blocked!\" << endl;\n return crow::response(400);\n }\n\n return crow::response(xmrblocks.show_tx(tx_hash));\n });\n\n CROW_ROUTE(app, \"\/tx\/<string>\/<uint>\")\n ([&](string tx_hash, uint with_ring_signatures) {\n return xmrblocks.show_tx(tx_hash, with_ring_signatures);\n });\n\n CROW_ROUTE(app, \"\/myoutputs\").methods(\"GET\"_method)\n ([&](const crow::request& req) {\n\n string tx_hash = string(req.url_params.get(\"tx_hash\"));\n string xmr_address = string(req.url_params.get(\"xmr_address\"));\n string viewkey = string(req.url_params.get(\"viewkey\"));\n\n return xmrblocks.show_my_outputs(tx_hash, xmr_address, viewkey);\n });\n\n CROW_ROUTE(app, \"\/search\").methods(\"GET\"_method)\n ([&](const crow::request& req) {\n return xmrblocks.search(string(req.url_params.get(\"value\")));\n });\n\n CROW_ROUTE(app, \"\/robots.txt\")\n ([&]() {\n string text = \"User-agent: *\\n\"\n \"Disallow: \";\n return text;\n });\n\n CROW_ROUTE(app, \"\/autorefresh\")\n ([&]() {\n uint64_t page_no {0};\n bool refresh_page {true};\n return xmrblocks.index2(page_no, refresh_page);\n });\n\n \/\/ run the crow http server\n app.port(app_port).multithreaded().run();\n\n return EXIT_SUCCESS;\n}\n<commit_msg>crowler blocking added to home page<commit_after>\n#include \"src\/CmdLineOptions.h\"\n#include \"src\/MicroCore.h\"\n#include \"src\/page.h\"\n\n#include \"ext\/crow\/crow.h\"\n#include \"ext\/member_checker.h\"\n\n#include <fstream>\n\nusing boost::filesystem::path;\n\nusing namespace std;\n\n\/\/ needed for log system of momero\nnamespace epee {\n unsigned int g_test_dbg_lock_sleep = 0;\n}\n\nint main(int ac, const char* av[]) {\n\n \/\/ get command line options\n xmreg::CmdLineOptions opts {ac, av};\n\n auto help_opt = opts.get_option<bool>(\"help\");\n\n \/\/ if help was chosen, display help text and finish\n if (*help_opt)\n {\n return EXIT_SUCCESS;\n }\n\n auto port_opt = opts.get_option<string>(\"port\");\n auto bc_path_opt = opts.get_option<string>(\"bc-path\");\n auto custom_db_path_opt = opts.get_option<string>(\"custom-db-path\");\n auto deamon_url_opt = opts.get_option<string>(\"deamon-url\");\n\n \/\/cast port number in string to uint16\n uint16_t app_port = boost::lexical_cast<uint16_t>(*port_opt);\n\n \/\/ get blockchain path\n path blockchain_path;\n\n if (!xmreg::get_blockchain_path(bc_path_opt, blockchain_path))\n {\n cerr << \"Error getting blockchain path.\" << endl;\n return EXIT_FAILURE;\n }\n\n \/\/ enable basic monero log output\n xmreg::enable_monero_log();\n\n \/\/ create instance of our MicroCore\n \/\/ and make pointer to the Blockchain\n xmreg::MicroCore mcore;\n cryptonote::Blockchain* core_storage;\n\n \/\/ initialize mcore and core_storage\n if (!xmreg::init_blockchain(blockchain_path.string(),\n mcore, core_storage))\n {\n cerr << \"Error accessing blockchain.\" << endl;\n return EXIT_FAILURE;\n }\n\n \/\/ check if we have path to lmdb2 (i.e., custom db)\n \/\/ and if it exists\n\n string custom_db_path_str;\n\n if (custom_db_path_opt)\n {\n if (boost::filesystem::exists(boost::filesystem::path(*custom_db_path_opt)))\n {\n custom_db_path_str = *custom_db_path_opt;\n }\n else\n {\n cerr << \"Custom db path: \" << *custom_db_path_opt\n << \"does not exist\" << endl;\n\n return EXIT_FAILURE;\n }\n }\n else\n {\n \/\/ if not given assume it is located in ~.\/bitmonero\/lmdb2 folder\n custom_db_path_str = blockchain_path.parent_path().string()\n + string(\"\/lmdb2\");\n }\n\n custom_db_path_str = xmreg::remove_trailing_path_separator(custom_db_path_str);\n\n\n \/\/ create instance of page class which\n \/\/ contains logic for the website\n xmreg::page xmrblocks(&mcore, core_storage,\n *deamon_url_opt, custom_db_path_str);\n\n \/\/ crow instance\n crow::SimpleApp app;\n\n CROW_ROUTE(app, \"\/\")\n ([&](const crow::request& req) {\n\n \/\/for (const auto& m : req.headers)\n \/\/ cout << m.first << \": \" << m.second << endl;\n\n \/\/ there is some robot scanning everything\n \/\/ on the explorer. I block it with this\n if (!xmreg::does_header_has(req, \"Accept\", \"q=.2, *\/*; q=.2\").empty())\n {\n cout << \"Scanner with q=.2, *\/*; q=.2 blocked!\" << endl;\n return crow::response(400);\n }\n\n return crow::response(xmrblocks.index2());\n });\n\n CROW_ROUTE(app, \"\/page\/<uint>\")\n ([&](size_t page_no) {\n return xmrblocks.index2(page_no);\n });\n\n CROW_ROUTE(app, \"\/block\/<uint>\")\n ([&](const crow::request& req, size_t block_height) {\n\n \/\/ there is some robot scanning everything\n \/\/ on the explorer. I block it with this\n if (!xmreg::does_header_has(req, \"Accept\", \"q=.2, *\/*; q=.2\").empty())\n {\n cout << \"Scanner with q=.2, *\/*; q=.2 blocked!\" << endl;\n return crow::response(400);\n }\n\n return crow::response(xmrblocks.show_block(block_height));\n });\n\n CROW_ROUTE(app, \"\/block\/<string>\")\n ([&](const crow::request& req, string block_hash) {\n\n \/\/ there is some robot scanning everything\n \/\/ on the explorer. I block it with this\n if (!xmreg::does_header_has(req, \"Accept\", \"q=.2, *\/*; q=.2\").empty())\n {\n cout << \"Scanner with q=.2, *\/*; q=.2 blocked!\" << endl;\n return crow::response(400);\n }\n\n return crow::response(xmrblocks.show_block(block_hash));\n });\n\n CROW_ROUTE(app, \"\/tx\/<string>\")\n ([&](const crow::request& req, string tx_hash) {\n\n \/\/ there is some robot scanning everything\n \/\/ on the explorer. I block it with this\n if (!xmreg::does_header_has(req, \"Accept\", \"q=.2, *\/*; q=.2\").empty())\n {\n cout << \"Scanner with q=.2, *\/*; q=.2 blocked!\" << endl;\n return crow::response(400);\n }\n\n return crow::response(xmrblocks.show_tx(tx_hash));\n });\n\n CROW_ROUTE(app, \"\/tx\/<string>\/<uint>\")\n ([&](string tx_hash, uint with_ring_signatures) {\n return xmrblocks.show_tx(tx_hash, with_ring_signatures);\n });\n\n CROW_ROUTE(app, \"\/myoutputs\").methods(\"GET\"_method)\n ([&](const crow::request& req) {\n\n string tx_hash = string(req.url_params.get(\"tx_hash\"));\n string xmr_address = string(req.url_params.get(\"xmr_address\"));\n string viewkey = string(req.url_params.get(\"viewkey\"));\n\n return xmrblocks.show_my_outputs(tx_hash, xmr_address, viewkey);\n });\n\n CROW_ROUTE(app, \"\/search\").methods(\"GET\"_method)\n ([&](const crow::request& req) {\n return xmrblocks.search(string(req.url_params.get(\"value\")));\n });\n\n CROW_ROUTE(app, \"\/robots.txt\")\n ([&]() {\n string text = \"User-agent: *\\n\"\n \"Disallow: \";\n return text;\n });\n\n CROW_ROUTE(app, \"\/autorefresh\")\n ([&]() {\n uint64_t page_no {0};\n bool refresh_page {true};\n return xmrblocks.index2(page_no, refresh_page);\n });\n\n \/\/ run the crow http server\n app.port(app_port).multithreaded().run();\n\n return EXIT_SUCCESS;\n}\n<|endoftext|>"} {"text":"<commit_before>771fb5f6-2d53-11e5-baeb-247703a38240<commit_msg>7720354e-2d53-11e5-baeb-247703a38240<commit_after>7720354e-2d53-11e5-baeb-247703a38240<|endoftext|>"} {"text":"<commit_before>aba455b4-35ca-11e5-8363-6c40088e03e4<commit_msg>abab1866-35ca-11e5-b090-6c40088e03e4<commit_after>abab1866-35ca-11e5-b090-6c40088e03e4<|endoftext|>"} {"text":"<commit_before>756f4a96-2d53-11e5-baeb-247703a38240<commit_msg>756fcc8c-2d53-11e5-baeb-247703a38240<commit_after>756fcc8c-2d53-11e5-baeb-247703a38240<|endoftext|>"} {"text":"<commit_before>\/* Copyright (c) 2016, Pollard Banknote Limited\n All rights reserved.\n\n Redistribution and use in source and binary forms, with or without modification,\n are permitted provided that the following conditions are met:\n\n 1. Redistributions of source code must retain the above copyright notice, this\n list of conditions and the following disclaimer.\n\n 2. Redistributions in binary form must reproduce the above copyright notice,\n this list of conditions and the following disclaimer in the documentation and\/or\n other materials provided with the distribution.\n\n 3. Neither the name of the copyright holder nor the names of its contributors\n may be used to endorse or promote products derived from this software without\n specific prior written permission.\n\n THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n#include \"chrono.h\"\n\n#ifndef CPP11\n\n#include <ctime>\n#include \".\/cstdint.h\"\n\nnamespace cpp11\n{\nnamespace chrono\n{\ntime_point< system_clock > system_clock::now()\n{\n\ttimespec ts;\n\n\tif ( ::clock_gettime(CLOCK_REALTIME, &ts) == 0 )\n\t{\n\t\t#if 0\n\t\tseconds s(ts.tv_sec);\n\t\tnanoseconds ns(ts.tv_nsec);\n\n\t\treturn time_point( duration(s + ms) );\n\n\t\t#else\n\n\t\treturn time_point( duration( ts.tv_sec * 1000 + ( ts.tv_nsec \/ 1000000L ) ) );\n\n\t\t#endif\n\t}\n\n\treturn time_point();\n}\n\nstd::time_t system_clock::to_time_t(const time_point& t)\n{\n\treturn static_cast< std::time_t >( t.time_since_epoch().count() \/ 1000 );\n}\n\ntime_point< system_clock > system_clock::from_time_t(std::time_t t)\n{\n\treturn time_point( duration(t * 1000) );\n}\n\ntime_point< steady_clock > steady_clock::now()\n{\n\ttimespec ts;\n\n\tif ( ::clock_gettime(CLOCK_MONOTONIC, &ts) == 0 )\n\t{\n\t\treturn time_point( duration(ts.tv_sec * INT32_C(1000000000) + ts.tv_nsec) );\n\t}\n\n\treturn time_point();\n}\n\n}\n}\n#endif \/\/ ifndef CPP11\n<commit_msg>Fix include<commit_after>\/* Copyright (c) 2016, Pollard Banknote Limited\n All rights reserved.\n\n Redistribution and use in source and binary forms, with or without modification,\n are permitted provided that the following conditions are met:\n\n 1. Redistributions of source code must retain the above copyright notice, this\n list of conditions and the following disclaimer.\n\n 2. Redistributions in binary form must reproduce the above copyright notice,\n this list of conditions and the following disclaimer in the documentation and\/or\n other materials provided with the distribution.\n\n 3. Neither the name of the copyright holder nor the names of its contributors\n may be used to endorse or promote products derived from this software without\n specific prior written permission.\n\n THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n#include \"chrono.h\"\n\n#ifndef CPP11\n\n#include <ctime>\n#include \"cstdint.h\"\n\nnamespace cpp11\n{\nnamespace chrono\n{\ntime_point< system_clock > system_clock::now()\n{\n\ttimespec ts;\n\n\tif ( ::clock_gettime(CLOCK_REALTIME, &ts) == 0 )\n\t{\n\t\t#if 0\n\t\tseconds s(ts.tv_sec);\n\t\tnanoseconds ns(ts.tv_nsec);\n\n\t\treturn time_point( duration(s + ms) );\n\n\t\t#else\n\n\t\treturn time_point( duration( ts.tv_sec * 1000 + ( ts.tv_nsec \/ 1000000L ) ) );\n\n\t\t#endif\n\t}\n\n\treturn time_point();\n}\n\nstd::time_t system_clock::to_time_t(const time_point& t)\n{\n\treturn static_cast< std::time_t >( t.time_since_epoch().count() \/ 1000 );\n}\n\ntime_point< system_clock > system_clock::from_time_t(std::time_t t)\n{\n\treturn time_point( duration(t * 1000) );\n}\n\ntime_point< steady_clock > steady_clock::now()\n{\n\ttimespec ts;\n\n\tif ( ::clock_gettime(CLOCK_MONOTONIC, &ts) == 0 )\n\t{\n\t\treturn time_point( duration(ts.tv_sec * INT32_C(1000000000) + ts.tv_nsec) );\n\t}\n\n\treturn time_point();\n}\n\n}\n}\n#endif \/\/ ifndef CPP11\n<|endoftext|>"} {"text":"<commit_before>#ifdef _MSC_VER\n#define _USE_MATH_DEFINES\n#endif\n\n#include <QWidget>\n#include <QApplication>\n#include <QDebug>\n#include <QGamepadManager>\n#include <QGamepad>\n#include <QtEndian>\n#include <QUdpSocket>\n#include <QTimer>\n#include <QFormLayout>\n#include <QVBoxLayout>\n#include <QLineEdit>\n#include <QPushButton>\n#include <QCheckBox>\n#include <QDialog>\n#include <QMouseEvent>\n#include <QCloseEvent>\n#include <QSettings>\n\n#include <algorithm>\n#include <cmath>\n\n#define CPAD_BOUND 0x5d0\n#define CPP_BOUND 0x7f\n\n#define TOUCH_SCREEN_WIDTH 320\n#define TOUCH_SCREEN_HEIGHT 240\n\ntypedef uint32_t u32;\ntypedef uint16_t u16;\ntypedef uint8_t u8;\n\ndouble lx = 0.0, ly = 0.0;\ndouble rx = 0.0, ry = 0.0;\nQGamepadManager::GamepadButtons buttons = 0;\nu32 interfaceButtons = 0;\nQString ipAddress;\nint yAxisMultiplier = 1;\nbool abInverse = false;\nbool xyInverse = false;\n\nbool touchScreenPressed;\nQPoint touchScreenPosition;\n\nQSettings settings(\"TuxSH\", \"InputRedirectionClient-Qt\");\n\nvoid sendFrame(void)\n{\n static const QGamepadManager::GamepadButton hidButtonsAB[] = {\n QGamepadManager::ButtonA,\n QGamepadManager::ButtonB,\n };\n\n static const QGamepadManager::GamepadButton hidButtonsMiddle[] = {\n QGamepadManager::ButtonSelect,\n QGamepadManager::ButtonStart,\n QGamepadManager::ButtonRight,\n QGamepadManager::ButtonLeft,\n QGamepadManager::ButtonUp,\n QGamepadManager::ButtonDown,\n QGamepadManager::ButtonR1,\n QGamepadManager::ButtonL1,\n };\n\n static const QGamepadManager::GamepadButton hidButtonsXY[] = {\n QGamepadManager::ButtonX,\n QGamepadManager::ButtonY,\n };\n\n static const QGamepadManager::GamepadButton irButtons[] = {\n QGamepadManager::ButtonR2,\n QGamepadManager::ButtonL2,\n };\n\n static const QGamepadManager::GamepadButton speButtons[] = {\n QGamepadManager::ButtonR3,\n QGamepadManager::ButtonL3,\n QGamepadManager::ButtonGuide,\n };\n\n u32 hidPad = 0xfff;\n if(!abInverse)\n {\n for(u32 i = 0; i < 2; i++)\n {\n if(buttons & (1 << hidButtonsAB[i]))\n hidPad &= ~(1 << i);\n }\n }\n else\n {\n for(u32 i = 0; i < 2; i++)\n {\n if(buttons & (1 << hidButtonsAB[1-i]))\n hidPad &= ~(1 << i);\n }\n }\n\n for(u32 i = 2; i < 10; i++)\n {\n if(buttons & (1 << hidButtonsMiddle[i-2]))\n hidPad &= ~(1 << i);\n }\n\n if(!xyInverse)\n {\n for(u32 i = 10; i < 12; i++)\n {\n if(buttons & (1 << hidButtonsXY[i-10]))\n hidPad &= ~(1 << i);\n }\n }\n else\n {\n for(u32 i = 10; i < 12; i++)\n {\n if(buttons & (1 << hidButtonsXY[1-(i-10)]))\n hidPad &= ~(1 << i);\n }\n }\n\n u32 irButtonsState = 0;\n for(u32 i = 0; i < 2; i++)\n {\n if(buttons & (1 << irButtons[i]))\n irButtonsState |= 1 << (i + 1);\n }\n\n u32 specialButtonsState = 0;\n for(u32 i = 0; i < 3; i++)\n {\n\n if(buttons & (1 << speButtons[i]))\n specialButtonsState |= 1 << i;\n }\n specialButtonsState |= interfaceButtons;\n\n u32 touchScreenState = 0x2000000;\n u32 circlePadState = 0x7ff7ff;\n u32 cppState = 0x80800081;\n\n if(lx != 0.0 || ly != 0.0)\n {\n u32 x = (u32)(lx * CPAD_BOUND + 0x800);\n u32 y = (u32)(ly * CPAD_BOUND + 0x800);\n x = x >= 0xfff ? (lx < 0.0 ? 0x000 : 0xfff) : x;\n y = y >= 0xfff ? (ly < 0.0 ? 0x000 : 0xfff) : y;\n\n circlePadState = (y << 12) | x;\n }\n\n if(rx != 0.0 || ry != 0.0 || irButtonsState != 0)\n {\n \/\/ We have to rotate the c-stick position 45°. Thanks, Nintendo.\n u32 x = (u32)(M_SQRT1_2 * (rx + ry) * CPP_BOUND + 0x80);\n u32 y = (u32)(M_SQRT1_2 * (ry - rx) * CPP_BOUND + 0x80);\n x = x >= 0xff ? (rx < 0.0 ? 0x00 : 0xff) : x;\n y = y >= 0xff ? (ry < 0.0 ? 0x00 : 0xff) : y;\n\n cppState = (y << 24) | (x << 16) | (irButtonsState << 8) | 0x81;\n }\n\n if(touchScreenPressed)\n {\n u32 x = (u32)(0xfff * std::min(std::max(0, touchScreenPosition.x()), TOUCH_SCREEN_WIDTH)) \/ TOUCH_SCREEN_WIDTH;\n u32 y = (u32)(0xfff * std::min(std::max(0, touchScreenPosition.y()), TOUCH_SCREEN_HEIGHT)) \/ TOUCH_SCREEN_HEIGHT;\n touchScreenState = (1 << 24) | (y << 12) | x;\n }\n\n QByteArray ba(20, 0);\n qToLittleEndian(hidPad, (uchar *)ba.data());\n qToLittleEndian(touchScreenState, (uchar *)ba.data() + 4);\n qToLittleEndian(circlePadState, (uchar *)ba.data() + 8);\n qToLittleEndian(cppState, (uchar *)ba.data() + 12);\n qToLittleEndian(specialButtonsState, (uchar *)ba.data() + 16);\n QUdpSocket().writeDatagram(ba, QHostAddress(ipAddress), 4950);\n}\n\nstruct GamepadMonitor : public QObject {\n\n GamepadMonitor(QObject *parent = nullptr) : QObject(parent)\n {\n connect(QGamepadManager::instance(), &QGamepadManager::gamepadButtonPressEvent, this,\n [](int deviceId, QGamepadManager::GamepadButton button, double value)\n {\n (void)deviceId;\n (void)value;\n buttons |= QGamepadManager::GamepadButtons(1 << button);\n sendFrame();\n });\n\n connect(QGamepadManager::instance(), &QGamepadManager::gamepadButtonReleaseEvent, this,\n [](int deviceId, QGamepadManager::GamepadButton button)\n {\n (void)deviceId;\n buttons &= QGamepadManager::GamepadButtons(~(1 << button));\n sendFrame();\n });\n connect(QGamepadManager::instance(), &QGamepadManager::gamepadAxisEvent, this,\n [](int deviceId, QGamepadManager::GamepadAxis axis, double value)\n {\n (void)deviceId;\n (void)value;\n switch(axis)\n {\n case QGamepadManager::AxisLeftX:\n lx = value;\n break;\n case QGamepadManager::AxisLeftY:\n ly = yAxisMultiplier * -value; \/\/ for some reason qt inverts this\n break;\n\n case QGamepadManager::AxisRightX:\n rx = value;\n break;\n case QGamepadManager::AxisRightY:\n ry = yAxisMultiplier * -value; \/\/ for some reason qt inverts this\n break;\n default: break;\n }\n sendFrame();\n });\n }\n};\n\nstruct TouchScreen : public QDialog {\n TouchScreen(QWidget *parent = nullptr) : QDialog(parent)\n {\n this->setFixedSize(TOUCH_SCREEN_WIDTH, TOUCH_SCREEN_HEIGHT);\n this->setWindowFlags(Qt::CustomizeWindowHint | Qt::WindowTitleHint);\n this->setWindowTitle(tr(\"InputRedirectionClient-Qt - Touch screen\"));\n }\n\n void mousePressEvent(QMouseEvent *ev)\n {\n if(ev->button() == Qt::LeftButton)\n {\n touchScreenPressed = true;\n touchScreenPosition = ev->pos();\n sendFrame();\n }\n }\n\n void mouseMoveEvent(QMouseEvent *ev)\n {\n if(touchScreenPressed && (ev->buttons() & Qt::LeftButton))\n {\n touchScreenPosition = ev->pos();\n sendFrame();\n }\n }\n\n void mouseReleaseEvent(QMouseEvent *ev)\n {\n if(ev->button() == Qt::LeftButton)\n {\n touchScreenPressed = false;\n sendFrame();\n }\n }\n\n void closeEvent(QCloseEvent *ev)\n {\n touchScreenPressed = false;\n sendFrame();\n ev->accept();\n }\n};\n\nstruct FrameTimer : public QTimer {\n FrameTimer(QObject *parent = nullptr) : QTimer(parent)\n {\n connect(this, &QTimer::timeout, this,\n [](void)\n {\n sendFrame();\n });\n }\n};\n\n\nclass Widget : public QWidget\n{\nprivate:\n QVBoxLayout *layout;\n QFormLayout *formLayout;\n QLineEdit *addrLineEdit;\n QCheckBox *invertYCheckbox, *invertABCheckbox, *invertXYCheckbox;\n QPushButton *homeButton, *powerButton, *longPowerButton;\n TouchScreen *touchScreen;\npublic:\n Widget(QWidget *parent = nullptr) : QWidget(parent)\n {\n setWindowFlags(Qt::MSWindowsFixedSizeDialogHint);\n\n layout = new QVBoxLayout(this);\n\n addrLineEdit = new QLineEdit(this);\n addrLineEdit->setClearButtonEnabled(true);\n\n invertYCheckbox = new QCheckBox(this);\n invertABCheckbox = new QCheckBox(this);\n invertXYCheckbox = new QCheckBox(this);\n formLayout = new QFormLayout;\n\n formLayout->addRow(tr(\"IP &address\"), addrLineEdit);\n formLayout->addRow(tr(\"&Invert Y axis\"), invertYCheckbox);\n formLayout->addRow(tr(\"Invert A<->&B\"), invertABCheckbox);\n formLayout->addRow(tr(\"Invert X<->&Y\"), invertXYCheckbox);\n\n homeButton = new QPushButton(tr(\"&HOME\"), this);\n powerButton = new QPushButton(tr(\"&POWER\"), this);\n longPowerButton = new QPushButton(tr(\"POWER (&long)\"), this);\n\n layout->addLayout(formLayout);\n layout->addWidget(homeButton);\n layout->addWidget(powerButton);\n layout->addWidget(longPowerButton);\n\n connect(addrLineEdit, &QLineEdit::textChanged, this,\n [](const QString &text)\n {\n ipAddress = text;\n settings.setValue(\"ipAddress\", text);\n });\n\n connect(invertYCheckbox, &QCheckBox::stateChanged, this,\n [](int state)\n {\n switch(state)\n {\n case Qt::Unchecked:\n yAxisMultiplier = 1;\n settings.setValue(\"invertY\", false);\n break;\n case Qt::Checked:\n yAxisMultiplier = -1;\n settings.setValue(\"invertY\", true);\n break;\n default: break;\n }\n });\n\n connect(invertABCheckbox, &QCheckBox::stateChanged, this,\n [](int state)\n {\n switch(state)\n {\n case Qt::Unchecked:\n abInverse = false;\n settings.setValue(\"invertAB\", false);\n break;\n case Qt::Checked:\n abInverse = true;\n settings.setValue(\"invertAB\", true);\n break;\n default: break;\n }\n });\n\n connect(invertXYCheckbox, &QCheckBox::stateChanged, this,\n [](int state)\n {\n switch(state)\n {\n case Qt::Unchecked:\n xyInverse = false;\n settings.setValue(\"invertXY\", false);\n break;\n case Qt::Checked:\n xyInverse = true;\n settings.setValue(\"invertXY\", true);\n break;\n default: break;\n }\n });\n\n connect(homeButton, &QPushButton::pressed, this,\n [](void)\n {\n interfaceButtons |= 1;\n sendFrame();\n });\n\n connect(homeButton, &QPushButton::released, this,\n [](void)\n {\n interfaceButtons &= ~1;\n sendFrame();\n });\n\n connect(powerButton, &QPushButton::pressed, this,\n [](void)\n {\n interfaceButtons |= 2;\n sendFrame();\n });\n\n connect(powerButton, &QPushButton::released, this,\n [](void)\n {\n interfaceButtons &= ~2;\n sendFrame();\n });\n\n connect(longPowerButton, &QPushButton::pressed, this,\n [](void)\n {\n interfaceButtons |= 4;\n sendFrame();\n });\n\n connect(longPowerButton, &QPushButton::released, this,\n [](void)\n {\n interfaceButtons &= ~4;\n sendFrame();\n });\n\n touchScreen = new TouchScreen(nullptr);\n this->setWindowTitle(tr(\"InputRedirectionClient-Qt\"));\n\n addrLineEdit->setText(settings.value(\"ipAddress\", \"\").toString());\n invertYCheckbox->setChecked(settings.value(\"invertY\", false).toBool());\n invertABCheckbox->setChecked(settings.value(\"invertAB\", false).toBool());\n invertXYCheckbox->setChecked(settings.value(\"invertXY\", false).toBool());\n }\n\n void show(void)\n {\n QWidget::show();\n touchScreen->show();\n }\n\n void closeEvent(QCloseEvent *ev)\n {\n touchScreen->close();\n ev->accept();\n }\n\n virtual ~Widget(void)\n {\n lx = ly = rx = ry = 0.0;\n buttons = 0;\n interfaceButtons = 0;\n touchScreenPressed = false;\n sendFrame();\n delete touchScreen;\n }\n\n};\n\n\nint main(int argc, char *argv[])\n{\n QApplication a(argc, argv);\n Widget w;\n GamepadMonitor m(&w);\n FrameTimer t(&w);\n TouchScreen ts;\n t.start(50);\n w.show();\n\n return a.exec();\n}\n<commit_msg>Remove MSWindowsFixedSizeDialogHint<commit_after>#ifdef _MSC_VER\n#define _USE_MATH_DEFINES\n#endif\n\n#include <QWidget>\n#include <QApplication>\n#include <QDebug>\n#include <QGamepadManager>\n#include <QGamepad>\n#include <QtEndian>\n#include <QUdpSocket>\n#include <QTimer>\n#include <QFormLayout>\n#include <QVBoxLayout>\n#include <QLineEdit>\n#include <QPushButton>\n#include <QCheckBox>\n#include <QDialog>\n#include <QMouseEvent>\n#include <QCloseEvent>\n#include <QSettings>\n\n#include <algorithm>\n#include <cmath>\n\n#define CPAD_BOUND 0x5d0\n#define CPP_BOUND 0x7f\n\n#define TOUCH_SCREEN_WIDTH 320\n#define TOUCH_SCREEN_HEIGHT 240\n\ntypedef uint32_t u32;\ntypedef uint16_t u16;\ntypedef uint8_t u8;\n\ndouble lx = 0.0, ly = 0.0;\ndouble rx = 0.0, ry = 0.0;\nQGamepadManager::GamepadButtons buttons = 0;\nu32 interfaceButtons = 0;\nQString ipAddress;\nint yAxisMultiplier = 1;\nbool abInverse = false;\nbool xyInverse = false;\n\nbool touchScreenPressed;\nQPoint touchScreenPosition;\n\nQSettings settings(\"TuxSH\", \"InputRedirectionClient-Qt\");\n\nvoid sendFrame(void)\n{\n static const QGamepadManager::GamepadButton hidButtonsAB[] = {\n QGamepadManager::ButtonA,\n QGamepadManager::ButtonB,\n };\n\n static const QGamepadManager::GamepadButton hidButtonsMiddle[] = {\n QGamepadManager::ButtonSelect,\n QGamepadManager::ButtonStart,\n QGamepadManager::ButtonRight,\n QGamepadManager::ButtonLeft,\n QGamepadManager::ButtonUp,\n QGamepadManager::ButtonDown,\n QGamepadManager::ButtonR1,\n QGamepadManager::ButtonL1,\n };\n\n static const QGamepadManager::GamepadButton hidButtonsXY[] = {\n QGamepadManager::ButtonX,\n QGamepadManager::ButtonY,\n };\n\n static const QGamepadManager::GamepadButton irButtons[] = {\n QGamepadManager::ButtonR2,\n QGamepadManager::ButtonL2,\n };\n\n static const QGamepadManager::GamepadButton speButtons[] = {\n QGamepadManager::ButtonR3,\n QGamepadManager::ButtonL3,\n QGamepadManager::ButtonGuide,\n };\n\n u32 hidPad = 0xfff;\n if(!abInverse)\n {\n for(u32 i = 0; i < 2; i++)\n {\n if(buttons & (1 << hidButtonsAB[i]))\n hidPad &= ~(1 << i);\n }\n }\n else\n {\n for(u32 i = 0; i < 2; i++)\n {\n if(buttons & (1 << hidButtonsAB[1-i]))\n hidPad &= ~(1 << i);\n }\n }\n\n for(u32 i = 2; i < 10; i++)\n {\n if(buttons & (1 << hidButtonsMiddle[i-2]))\n hidPad &= ~(1 << i);\n }\n\n if(!xyInverse)\n {\n for(u32 i = 10; i < 12; i++)\n {\n if(buttons & (1 << hidButtonsXY[i-10]))\n hidPad &= ~(1 << i);\n }\n }\n else\n {\n for(u32 i = 10; i < 12; i++)\n {\n if(buttons & (1 << hidButtonsXY[1-(i-10)]))\n hidPad &= ~(1 << i);\n }\n }\n\n u32 irButtonsState = 0;\n for(u32 i = 0; i < 2; i++)\n {\n if(buttons & (1 << irButtons[i]))\n irButtonsState |= 1 << (i + 1);\n }\n\n u32 specialButtonsState = 0;\n for(u32 i = 0; i < 3; i++)\n {\n\n if(buttons & (1 << speButtons[i]))\n specialButtonsState |= 1 << i;\n }\n specialButtonsState |= interfaceButtons;\n\n u32 touchScreenState = 0x2000000;\n u32 circlePadState = 0x7ff7ff;\n u32 cppState = 0x80800081;\n\n if(lx != 0.0 || ly != 0.0)\n {\n u32 x = (u32)(lx * CPAD_BOUND + 0x800);\n u32 y = (u32)(ly * CPAD_BOUND + 0x800);\n x = x >= 0xfff ? (lx < 0.0 ? 0x000 : 0xfff) : x;\n y = y >= 0xfff ? (ly < 0.0 ? 0x000 : 0xfff) : y;\n\n circlePadState = (y << 12) | x;\n }\n\n if(rx != 0.0 || ry != 0.0 || irButtonsState != 0)\n {\n \/\/ We have to rotate the c-stick position 45°. Thanks, Nintendo.\n u32 x = (u32)(M_SQRT1_2 * (rx + ry) * CPP_BOUND + 0x80);\n u32 y = (u32)(M_SQRT1_2 * (ry - rx) * CPP_BOUND + 0x80);\n x = x >= 0xff ? (rx < 0.0 ? 0x00 : 0xff) : x;\n y = y >= 0xff ? (ry < 0.0 ? 0x00 : 0xff) : y;\n\n cppState = (y << 24) | (x << 16) | (irButtonsState << 8) | 0x81;\n }\n\n if(touchScreenPressed)\n {\n u32 x = (u32)(0xfff * std::min(std::max(0, touchScreenPosition.x()), TOUCH_SCREEN_WIDTH)) \/ TOUCH_SCREEN_WIDTH;\n u32 y = (u32)(0xfff * std::min(std::max(0, touchScreenPosition.y()), TOUCH_SCREEN_HEIGHT)) \/ TOUCH_SCREEN_HEIGHT;\n touchScreenState = (1 << 24) | (y << 12) | x;\n }\n\n QByteArray ba(20, 0);\n qToLittleEndian(hidPad, (uchar *)ba.data());\n qToLittleEndian(touchScreenState, (uchar *)ba.data() + 4);\n qToLittleEndian(circlePadState, (uchar *)ba.data() + 8);\n qToLittleEndian(cppState, (uchar *)ba.data() + 12);\n qToLittleEndian(specialButtonsState, (uchar *)ba.data() + 16);\n QUdpSocket().writeDatagram(ba, QHostAddress(ipAddress), 4950);\n}\n\nstruct GamepadMonitor : public QObject {\n\n GamepadMonitor(QObject *parent = nullptr) : QObject(parent)\n {\n connect(QGamepadManager::instance(), &QGamepadManager::gamepadButtonPressEvent, this,\n [](int deviceId, QGamepadManager::GamepadButton button, double value)\n {\n (void)deviceId;\n (void)value;\n buttons |= QGamepadManager::GamepadButtons(1 << button);\n sendFrame();\n });\n\n connect(QGamepadManager::instance(), &QGamepadManager::gamepadButtonReleaseEvent, this,\n [](int deviceId, QGamepadManager::GamepadButton button)\n {\n (void)deviceId;\n buttons &= QGamepadManager::GamepadButtons(~(1 << button));\n sendFrame();\n });\n connect(QGamepadManager::instance(), &QGamepadManager::gamepadAxisEvent, this,\n [](int deviceId, QGamepadManager::GamepadAxis axis, double value)\n {\n (void)deviceId;\n (void)value;\n switch(axis)\n {\n case QGamepadManager::AxisLeftX:\n lx = value;\n break;\n case QGamepadManager::AxisLeftY:\n ly = yAxisMultiplier * -value; \/\/ for some reason qt inverts this\n break;\n\n case QGamepadManager::AxisRightX:\n rx = value;\n break;\n case QGamepadManager::AxisRightY:\n ry = yAxisMultiplier * -value; \/\/ for some reason qt inverts this\n break;\n default: break;\n }\n sendFrame();\n });\n }\n};\n\nstruct TouchScreen : public QDialog {\n TouchScreen(QWidget *parent = nullptr) : QDialog(parent)\n {\n this->setFixedSize(TOUCH_SCREEN_WIDTH, TOUCH_SCREEN_HEIGHT);\n this->setWindowFlags(Qt::CustomizeWindowHint | Qt::WindowTitleHint);\n this->setWindowTitle(tr(\"InputRedirectionClient-Qt - Touch screen\"));\n }\n\n void mousePressEvent(QMouseEvent *ev)\n {\n if(ev->button() == Qt::LeftButton)\n {\n touchScreenPressed = true;\n touchScreenPosition = ev->pos();\n sendFrame();\n }\n }\n\n void mouseMoveEvent(QMouseEvent *ev)\n {\n if(touchScreenPressed && (ev->buttons() & Qt::LeftButton))\n {\n touchScreenPosition = ev->pos();\n sendFrame();\n }\n }\n\n void mouseReleaseEvent(QMouseEvent *ev)\n {\n if(ev->button() == Qt::LeftButton)\n {\n touchScreenPressed = false;\n sendFrame();\n }\n }\n\n void closeEvent(QCloseEvent *ev)\n {\n touchScreenPressed = false;\n sendFrame();\n ev->accept();\n }\n};\n\nstruct FrameTimer : public QTimer {\n FrameTimer(QObject *parent = nullptr) : QTimer(parent)\n {\n connect(this, &QTimer::timeout, this,\n [](void)\n {\n sendFrame();\n });\n }\n};\n\n\nclass Widget : public QWidget\n{\nprivate:\n QVBoxLayout *layout;\n QFormLayout *formLayout;\n QLineEdit *addrLineEdit;\n QCheckBox *invertYCheckbox, *invertABCheckbox, *invertXYCheckbox;\n QPushButton *homeButton, *powerButton, *longPowerButton;\n TouchScreen *touchScreen;\npublic:\n Widget(QWidget *parent = nullptr) : QWidget(parent)\n {\n layout = new QVBoxLayout(this);\n\n addrLineEdit = new QLineEdit(this);\n addrLineEdit->setClearButtonEnabled(true);\n\n invertYCheckbox = new QCheckBox(this);\n invertABCheckbox = new QCheckBox(this);\n invertXYCheckbox = new QCheckBox(this);\n formLayout = new QFormLayout;\n\n formLayout->addRow(tr(\"IP &address\"), addrLineEdit);\n formLayout->addRow(tr(\"&Invert Y axis\"), invertYCheckbox);\n formLayout->addRow(tr(\"Invert A<->&B\"), invertABCheckbox);\n formLayout->addRow(tr(\"Invert X<->&Y\"), invertXYCheckbox);\n\n homeButton = new QPushButton(tr(\"&HOME\"), this);\n powerButton = new QPushButton(tr(\"&POWER\"), this);\n longPowerButton = new QPushButton(tr(\"POWER (&long)\"), this);\n\n layout->addLayout(formLayout);\n layout->addWidget(homeButton);\n layout->addWidget(powerButton);\n layout->addWidget(longPowerButton);\n\n connect(addrLineEdit, &QLineEdit::textChanged, this,\n [](const QString &text)\n {\n ipAddress = text;\n settings.setValue(\"ipAddress\", text);\n });\n\n connect(invertYCheckbox, &QCheckBox::stateChanged, this,\n [](int state)\n {\n switch(state)\n {\n case Qt::Unchecked:\n yAxisMultiplier = 1;\n settings.setValue(\"invertY\", false);\n break;\n case Qt::Checked:\n yAxisMultiplier = -1;\n settings.setValue(\"invertY\", true);\n break;\n default: break;\n }\n });\n\n connect(invertABCheckbox, &QCheckBox::stateChanged, this,\n [](int state)\n {\n switch(state)\n {\n case Qt::Unchecked:\n abInverse = false;\n settings.setValue(\"invertAB\", false);\n break;\n case Qt::Checked:\n abInverse = true;\n settings.setValue(\"invertAB\", true);\n break;\n default: break;\n }\n });\n\n connect(invertXYCheckbox, &QCheckBox::stateChanged, this,\n [](int state)\n {\n switch(state)\n {\n case Qt::Unchecked:\n xyInverse = false;\n settings.setValue(\"invertXY\", false);\n break;\n case Qt::Checked:\n xyInverse = true;\n settings.setValue(\"invertXY\", true);\n break;\n default: break;\n }\n });\n\n connect(homeButton, &QPushButton::pressed, this,\n [](void)\n {\n interfaceButtons |= 1;\n sendFrame();\n });\n\n connect(homeButton, &QPushButton::released, this,\n [](void)\n {\n interfaceButtons &= ~1;\n sendFrame();\n });\n\n connect(powerButton, &QPushButton::pressed, this,\n [](void)\n {\n interfaceButtons |= 2;\n sendFrame();\n });\n\n connect(powerButton, &QPushButton::released, this,\n [](void)\n {\n interfaceButtons &= ~2;\n sendFrame();\n });\n\n connect(longPowerButton, &QPushButton::pressed, this,\n [](void)\n {\n interfaceButtons |= 4;\n sendFrame();\n });\n\n connect(longPowerButton, &QPushButton::released, this,\n [](void)\n {\n interfaceButtons &= ~4;\n sendFrame();\n });\n\n touchScreen = new TouchScreen(nullptr);\n this->setWindowTitle(tr(\"InputRedirectionClient-Qt\"));\n\n addrLineEdit->setText(settings.value(\"ipAddress\", \"\").toString());\n invertYCheckbox->setChecked(settings.value(\"invertY\", false).toBool());\n invertABCheckbox->setChecked(settings.value(\"invertAB\", false).toBool());\n invertXYCheckbox->setChecked(settings.value(\"invertXY\", false).toBool());\n }\n\n void show(void)\n {\n QWidget::show();\n touchScreen->show();\n }\n\n void closeEvent(QCloseEvent *ev)\n {\n touchScreen->close();\n ev->accept();\n }\n\n virtual ~Widget(void)\n {\n lx = ly = rx = ry = 0.0;\n buttons = 0;\n interfaceButtons = 0;\n touchScreenPressed = false;\n sendFrame();\n delete touchScreen;\n }\n\n};\n\n\nint main(int argc, char *argv[])\n{\n QApplication a(argc, argv);\n Widget w;\n GamepadMonitor m(&w);\n FrameTimer t(&w);\n TouchScreen ts;\n t.start(50);\n w.show();\n\n return a.exec();\n}\n<|endoftext|>"} {"text":"<commit_before>bd5e1811-327f-11e5-b26f-9cf387a8033e<commit_msg>bd6b06a6-327f-11e5-85f6-9cf387a8033e<commit_after>bd6b06a6-327f-11e5-85f6-9cf387a8033e<|endoftext|>"} {"text":"<commit_before>9b32e53d-2747-11e6-b483-e0f84713e7b8<commit_msg>Fix that bug where things didn't work but now they should<commit_after>9b44f628-2747-11e6-8105-e0f84713e7b8<|endoftext|>"} {"text":"<commit_before>5a9845fd-2e4f-11e5-94c1-28cfe91dbc4b<commit_msg>5aa226bd-2e4f-11e5-9151-28cfe91dbc4b<commit_after>5aa226bd-2e4f-11e5-9151-28cfe91dbc4b<|endoftext|>"} {"text":"<commit_before>1878eb91-ad5a-11e7-8e48-ac87a332f658<commit_msg>add file<commit_after>190160e3-ad5a-11e7-a3f9-ac87a332f658<|endoftext|>"} {"text":"<commit_before>7ec84f63-2e4f-11e5-908b-28cfe91dbc4b<commit_msg>7ecf36cf-2e4f-11e5-886f-28cfe91dbc4b<commit_after>7ecf36cf-2e4f-11e5-886f-28cfe91dbc4b<|endoftext|>"} {"text":"<commit_before>72f59680-2749-11e6-a444-e0f84713e7b8<commit_msg>bug fix<commit_after>7303b635-2749-11e6-98f2-e0f84713e7b8<|endoftext|>"} {"text":"<commit_before>9fa30875-327f-11e5-868f-9cf387a8033e<commit_msg>9fa8acb8-327f-11e5-b8f3-9cf387a8033e<commit_after>9fa8acb8-327f-11e5-b8f3-9cf387a8033e<|endoftext|>"} {"text":"<commit_before>0163b12c-585b-11e5-b764-6c40088e03e4<commit_msg>016ab6f0-585b-11e5-a439-6c40088e03e4<commit_after>016ab6f0-585b-11e5-a439-6c40088e03e4<|endoftext|>"} {"text":"<commit_before>7a86e442-2e4f-11e5-a166-28cfe91dbc4b<commit_msg>7a8e7c3d-2e4f-11e5-9d1f-28cfe91dbc4b<commit_after>7a8e7c3d-2e4f-11e5-9d1f-28cfe91dbc4b<|endoftext|>"} {"text":"<commit_before>29d8ee3e-2f67-11e5-97a6-6c40088e03e4<commit_msg>29dfc658-2f67-11e5-af86-6c40088e03e4<commit_after>29dfc658-2f67-11e5-af86-6c40088e03e4<|endoftext|>"} {"text":"<commit_before>0c28e361-2e4f-11e5-9878-28cfe91dbc4b<commit_msg>0c2f3045-2e4f-11e5-8cf1-28cfe91dbc4b<commit_after>0c2f3045-2e4f-11e5-8cf1-28cfe91dbc4b<|endoftext|>"} {"text":"<commit_before>7756a656-2d53-11e5-baeb-247703a38240<commit_msg>77572928-2d53-11e5-baeb-247703a38240<commit_after>77572928-2d53-11e5-baeb-247703a38240<|endoftext|>"} {"text":"<commit_before>#include <SFML\/Graphics.hpp>\n#include <SFML\/Audio.hpp>\n#include \"player.hpp\"\n\n#include \"Game.h\"\n#include \"GameStateStart.h\"\n\n\/*\n * Mainly following this guide\n * https:\/\/www.binpress.com\/tutorial\/creating-a-city-building-game-with-sfml\/137\n *\/\nint main()\n{ \/\/TODO classes to make. Floor? Maybe floor is a 2d array of Tiles that all have a texture? idk dudes.\n \/\/BEGIN STARTUP CODE\n sf::RenderWindow window(sf::VideoMode(600, 400), \"SFML works!\");\n sf::CircleShape shape(60.f);\n shape.setFillColor(sf::Color::Green);\n\tPlayer *player = new Player(true, 1, 1, 0.0);\/\/solid, starting at (1,1) facing right.\n \/\/ while (window.isOpen())\n {\n\t\t\/\/BEGIN MAIN GAME LOOP\n\t\tif (sf::Keyboard::isKeyPressed(sf::Keyboard::W))\n\t\t{\n\t\t\tplayer->up();\n\t\t}\n\t\tif (sf::Keyboard::isKeyPressed(sf::Keyboard::A))\n\t\t{\n\t\t\tplayer->left();\n\t\t}\n\t\tif (sf::Keyboard::isKeyPressed(sf::Keyboard::S))\n\t\t{\n\t\t\tplayer->down();\n\t\t}\n\t\tif (sf::Keyboard::isKeyPressed(sf::Keyboard::D))\n\t\t{\n\t\t\tplayer->right();\n\t\t}\n\t\tif (sf::Keyboard::isKeyPressed(sf::Keyboard::Space))\n\t\t{\n\t\t\tplayer->attack();\n\t\t}\n\n sf::Event event;\n while (window.pollEvent(event))\n {\n if (event.type == sf::Event::Closed){\n window.close();\/\/SHUTDOWN CODE\n }\n }\n\n window.clear();\n window.draw(shape);\n window.display();\n }\n\n return 0;\n}\n<commit_msg>undo merge mess up<commit_after>#include <SFML\/Graphics.hpp>\n#include <memory>\n\n#include \"Game.h\"\n#include \"GameStateStart.h\"\n\n\/*\n * Mainly following this guide\n * https:\/\/www.binpress.com\/tutorial\/creating-a-city-building-game-with-sfml\/137\n *\/\nint main()\n{\n Game game;\n\n game.pushState(std::make_unique<GameStateStart>(&game));\n game.run();\n\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>#include <stdlib.h>\n#include <stdio.h>\n#include <sys\/time.h>\n#include <signal.h>\n#include \"sniffer.h\"\n\nstatic void signal_handler(int nsignal);\nstatic void handle_alarm(int nsignal);\nstatic void handle_sigusr1(int nsignal);\n\nsniffer sniffer;\n\nint main(int argc, char** argv)\n{\n\tif (argc != 2) {\n\t\tfprintf(stderr, \"Usage: %s <interface>\\n\");\n\t\treturn -1;\n\t}\n\n\tif (!sniffer.create(argv[1], 32 * 1024 * 1024)) {\n\t\tfprintf(stderr, \"Couldn't create sniffer.\\n\");\n\t\treturn -1;\n\t}\n\n\tstruct sigaction act;\n\tsigemptyset(&act.sa_mask);\n\tact.sa_flags = 0;\n\tact.sa_handler = signal_handler;\n\tsigaction(SIGTERM, &act, NULL);\n\tsigaction(SIGINT, &act, NULL);\n\n\tact.sa_handler = handle_alarm;\n\tsigaction(SIGALRM, &act, NULL);\n\n\tact.sa_handler = handle_sigusr1;\n\tsigaction(SIGUSR1, &act, NULL);\n\n\tstruct itimerval value;\n\tvalue.it_interval.tv_sec = 5;\n\tvalue.it_interval.tv_usec = 0;\n\tvalue.it_value.tv_sec = 5;\n\tvalue.it_value.tv_usec = 0;\n\tif (setitimer(ITIMER_REAL, &value, NULL) < 0) {\n\t\tfprintf(stderr, \"Couldn't set real-time alarm.\\n\");\n\t\treturn -1;\n\t}\n\n\tsniffer.start();\n\n\treturn 0;\n}\n\nvoid signal_handler(int nsignal)\n{\n\tfprintf(stderr, \"Signal received...\\n\");\n\n\tsniffer.stop();\n}\n\nvoid handle_alarm(int nsignal)\n{\n\tsniffer.on_alarm();\n}\n\nvoid handle_sigusr1(int nsignal)\n{\n\tsniffer.on_dump_connections();\n}\n<commit_msg>In the usage, argv[0] was missing.<commit_after>#include <stdlib.h>\n#include <stdio.h>\n#include <sys\/time.h>\n#include <signal.h>\n#include \"sniffer.h\"\n\nstatic void signal_handler(int nsignal);\nstatic void handle_alarm(int nsignal);\nstatic void handle_sigusr1(int nsignal);\n\nsniffer sniffer;\n\nint main(int argc, char** argv)\n{\n\tif (argc != 2) {\n\t\tfprintf(stderr, \"Usage: %s <interface>\\n\", argv[0]);\n\t\treturn -1;\n\t}\n\n\tif (!sniffer.create(argv[1], 32 * 1024 * 1024)) {\n\t\tfprintf(stderr, \"Couldn't create sniffer.\\n\");\n\t\treturn -1;\n\t}\n\n\tstruct sigaction act;\n\tsigemptyset(&act.sa_mask);\n\tact.sa_flags = 0;\n\tact.sa_handler = signal_handler;\n\tsigaction(SIGTERM, &act, NULL);\n\tsigaction(SIGINT, &act, NULL);\n\n\tact.sa_handler = handle_alarm;\n\tsigaction(SIGALRM, &act, NULL);\n\n\tact.sa_handler = handle_sigusr1;\n\tsigaction(SIGUSR1, &act, NULL);\n\n\tstruct itimerval value;\n\tvalue.it_interval.tv_sec = 5;\n\tvalue.it_interval.tv_usec = 0;\n\tvalue.it_value.tv_sec = 5;\n\tvalue.it_value.tv_usec = 0;\n\tif (setitimer(ITIMER_REAL, &value, NULL) < 0) {\n\t\tfprintf(stderr, \"Couldn't set real-time alarm.\\n\");\n\t\treturn -1;\n\t}\n\n\tsniffer.start();\n\n\treturn 0;\n}\n\nvoid signal_handler(int nsignal)\n{\n\tfprintf(stderr, \"Signal received...\\n\");\n\n\tsniffer.stop();\n}\n\nvoid handle_alarm(int nsignal)\n{\n\tsniffer.on_alarm();\n}\n\nvoid handle_sigusr1(int nsignal)\n{\n\tsniffer.on_dump_connections();\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (C) 2001-2003 Peter J Jones (pjones@pmade.org)\n * All Rights Reserved\n * \n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n * \n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in\n * the documentation and\/or other materials provided with the\n * distribution.\n * 3. Neither the name of the Author nor the names of its contributors\n * may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n * \n * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS''\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED\n * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A\n * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR\n * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF\n * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED\n * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT\n * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n *\/\n\n\/\/ xmlwrapp includes\n#include \"xmlwrapp\/errors.h\"\n\n#include \"node_manip.h\"\n\n\/\/ standard includes\n#include <stdexcept>\n#include <string>\n\n\/\/ libxml includes\n#include <libxml\/tree.h>\n\nxmlNodePtr\nxml::impl::node_insert(xmlNodePtr parent, xmlNodePtr before, xmlNodePtr to_add)\n{\n xmlNodePtr new_xml_node = xmlCopyNode(to_add, 1);\n if ( !new_xml_node )\n throw std::bad_alloc();\n\n if ( before == 0 )\n {\n \/\/ insert at the end of the child list\n if ( xmlAddChild(parent, new_xml_node) == 0 )\n {\n xmlFreeNode(new_xml_node);\n throw xml::exception(\"failed to insert xml::node; xmlAddChild failed\");\n }\n }\n else\n {\n if ( xmlAddPrevSibling(before, new_xml_node) == 0 )\n {\n xmlFreeNode(new_xml_node);\n throw xml::exception(\"failed to insert xml::node; xmlAddPrevSibling failed\");\n }\n }\n\n return new_xml_node;\n}\n\n\nxmlNodePtr\nxml::impl::node_replace(xmlNodePtr old_node, xmlNodePtr new_node)\n{\n xmlNodePtr copied_node = xmlCopyNode(new_node, 1);\n if ( !copied_node )\n throw std::bad_alloc();\n\n \/\/ hack to see if xmlReplaceNode was successful\n copied_node->doc = reinterpret_cast<xmlDocPtr>(old_node);\n xmlReplaceNode(old_node, copied_node);\n\n if ( copied_node->doc == reinterpret_cast<xmlDocPtr>(old_node) )\n {\n xmlFreeNode(copied_node);\n throw xml::exception(\"failed to replace xml::node; xmlReplaceNode() failed\");\n }\n\n xmlFreeNode(old_node);\n return copied_node;\n}\n\n\nxmlNodePtr xml::impl::node_erase(xmlNodePtr to_erase)\n{\n xmlNodePtr after = to_erase->next;\n\n xmlUnlinkNode(to_erase);\n xmlFreeNode(to_erase);\n\n return after;\n}\n<commit_msg>Use parent namespace by default for the new nodes.<commit_after>\/*\n * Copyright (C) 2001-2003 Peter J Jones (pjones@pmade.org)\n * All Rights Reserved\n * \n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n * \n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in\n * the documentation and\/or other materials provided with the\n * distribution.\n * 3. Neither the name of the Author nor the names of its contributors\n * may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n * \n * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS''\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED\n * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A\n * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR\n * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF\n * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED\n * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT\n * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n *\/\n\n\/\/ xmlwrapp includes\n#include \"xmlwrapp\/errors.h\"\n\n#include \"node_manip.h\"\n\n\/\/ standard includes\n#include <stdexcept>\n#include <string>\n\n\/\/ libxml includes\n#include <libxml\/tree.h>\n\nnamespace\n{\n\n\/\/ Make a copy of the given node with its contents and children which is meant\n\/\/ to be added under the specified parent.\n\/\/\n\/\/ The returned pointer is never null (but this function may throw) and must be\n\/\/ freed with xmlFreeNode().\nxmlNodePtr copy_node_under_parent(xmlNodePtr parent, xmlNodePtr orig_node)\n{\n xmlNodePtr new_xml_node = xmlCopyNode(orig_node, 1);\n if ( !new_xml_node )\n throw std::bad_alloc();\n\n \/\/ The new node should inherit the namespace of its parent, unless it\n \/\/ already has a custom namespace, for consistency with how tree\n \/\/ construction works in libxml2.\n if ( !new_xml_node->ns )\n {\n \/\/ Check that we really have a parent as this could also be xmlDoc\n \/\/ masquerading as xmlNode when inserting the root element itself.\n if ( parent->type != XML_DOCUMENT_NODE )\n new_xml_node->ns = parent->ns;\n }\n\n return new_xml_node;\n}\n\n} \/\/ anonymous namespace\n\nxmlNodePtr\nxml::impl::node_insert(xmlNodePtr parent, xmlNodePtr before, xmlNodePtr to_add)\n{\n xmlNodePtr const new_xml_node = copy_node_under_parent(parent, to_add);\n\n if ( before == 0 )\n {\n \/\/ insert at the end of the child list\n if ( xmlAddChild(parent, new_xml_node) == 0 )\n {\n xmlFreeNode(new_xml_node);\n throw xml::exception(\"failed to insert xml::node; xmlAddChild failed\");\n }\n }\n else\n {\n if ( xmlAddPrevSibling(before, new_xml_node) == 0 )\n {\n xmlFreeNode(new_xml_node);\n throw xml::exception(\"failed to insert xml::node; xmlAddPrevSibling failed\");\n }\n }\n\n return new_xml_node;\n}\n\n\nxmlNodePtr\nxml::impl::node_replace(xmlNodePtr old_node, xmlNodePtr new_node)\n{\n xmlNodePtr const copied_node = copy_node_under_parent(old_node->parent, new_node);\n\n \/\/ hack to see if xmlReplaceNode was successful\n copied_node->doc = reinterpret_cast<xmlDocPtr>(old_node);\n xmlReplaceNode(old_node, copied_node);\n\n if ( copied_node->doc == reinterpret_cast<xmlDocPtr>(old_node) )\n {\n xmlFreeNode(copied_node);\n throw xml::exception(\"failed to replace xml::node; xmlReplaceNode() failed\");\n }\n\n xmlFreeNode(old_node);\n return copied_node;\n}\n\n\nxmlNodePtr xml::impl::node_erase(xmlNodePtr to_erase)\n{\n xmlNodePtr after = to_erase->next;\n\n xmlUnlinkNode(to_erase);\n xmlFreeNode(to_erase);\n\n return after;\n}\n<|endoftext|>"} {"text":"<commit_before>\/**\n * @file\n * String formatting code.\n * Much of this code was adapted from Python's string formatting\n * code, but the actual formatting of individual items is done\n * by constructing printf formats and using them. Ugly, but easy.\n * There may be some dodgy assumptions about lengths here.\n *\/\n\n#include \"angort.h\"\n#include <ctype.h>\n#define max(a,b) ((a)>(b)?(a):(b))\n\nnamespace angort {\n\nstatic void formatSignedInt(char *s,int i,int width,int precision, bool zeropad, bool negpad){\n char format[32];\n sprintf(format,\"%%%s%dd\",zeropad?\"0\":\"\",negpad?-width:width);\n sprintf(s,format,i);\n}\n\nstatic void formatUnsignedInt(char *s,unsigned int i,int width,int precision, bool zeropad, bool negpad){\n char format[32];\n sprintf(format,\"%%%s%du\",zeropad?\"0\":\"\",negpad?-width:width);\n sprintf(s,format,i);\n}\n\nstatic void formatSignedLong(char *s,long i,int width,int precision, bool zeropad, bool negpad){\n char format[32];\n sprintf(format,\"%%%s%dld\",zeropad?\"0\":\"\",negpad?-width:width);\n sprintf(s,format,i);\n}\n\nstatic void formatUnsignedLong(char *s,unsigned long i,int width,int precision, bool zeropad, bool negpad){\n char format[32];\n sprintf(format,\"%%%s%dlu\",zeropad?\"0\":\"\",negpad?-width:width);\n sprintf(s,format,i);\n}\n\nstatic void formatHexInt(char *s,unsigned int i,int width,int precision, bool zeropad, bool negpad){\n char format[32];\n sprintf(format,\"%%%s%dx\",zeropad?\"0\":\"\",negpad?-width:width);\n sprintf(s,format,i);\n}\nstatic void formatHexLong(char *s,unsigned long i,int width,int precision, bool zeropad, bool negpad){\n char format[32];\n sprintf(format,\"%%%s%dlx\",zeropad?\"0\":\"\",negpad?-width:width);\n sprintf(s,format,i);\n}\n\nstatic void formatFloat(char *s,double f,int width,int precision, bool zeropad, bool negpad){\n char format[32];\n if(precision!=-9999)\n sprintf(format,\"%%%s%d.%df\",zeropad?\"0\":\"\",negpad?-width:width,precision);\n else\n sprintf(format,\"%%%s%df\",zeropad?\"0\":\"\",negpad?-width:width);\n sprintf(s,format,f);\n}\n\nstatic void formatFloat2(char *s,double f,int width,int precision, bool zeropad, bool negpad){\n char format[32];\n if(precision!=-9999)\n sprintf(format,\"%%%s%d.%dg\",zeropad?\"0\":\"\",negpad?-width:width,precision);\n else\n sprintf(format,\"%%%s%dg\",zeropad?\"0\":\"\",negpad?-width:width);\n sprintf(s,format,f);\n}\n\nstatic void formatString(char *s,const char *in,int width,int precision, bool negpad){\n char format[32];\n snprintf(format,20,\"%%%ds\",negpad?-width:width);\n sprintf(s,format,in);\n}\n\n\n\nvoid format(Value *out,Value *formatVal,ArrayList<Value> *items){\n \n \/\/ sorry, it actually has to be a string.\n if(formatVal->t != Types::tString)\n throw RUNT(EX_TYPE,\"format must be a string\");\n \n const char *format = Types::tString->getData(formatVal);\n \n ArrayListIterator<Value> iter(items);\n iter.first();\n \n unsigned int width,precision;\n \n \/\/ pass 1, work out the buffer size\n int size=0;\n int strsz;\n for(const char *f = format;*f;f++){\n precision=0;\n width=0;\n if(*f=='%'){\n const char *p = f++;\n if(*f=='-')f++;\n while(isdigit(*f))\n width = (width*10) + (*f++ - '0');\n if(*f=='.'){\n f++;\n while(isdigit(*f))\n precision = (precision*10) + (*f++ - '0');\n }\n while(*f && *f!='%' && !isalpha(*f))\n ;\n if((*f=='l' || *f=='z') && (f[1]=='d' || f[1]=='u' || f[1]=='x'))\n ++f; \/\/ skip length flag (dealt with in pass 2)\n switch(*f){\n case 'c':\n iter.next();\n \/\/ fall through\n case '%':\n size++;\n break;\n case 'd':case 'u':case 'x':\n \/\/ 50 should be plenty\n iter.next();\n size+=max(50,width);\n break;\n case 'f':\n case 'g':\n iter.next();\n size+=50; \/\/ got to draw the line somewhere.\n break;\n case 's':{\n const StringBuffer& b = iter.current()->toString();\n strsz = max(strlen(b.get()),width);\n size+=strsz;\n iter.next();\n break;\n }\n default:\/\/unknown code; just add the rest of the string in. Ugh.\n size+=strlen(p);\n goto expand;\n break;\n }\n } else\n size++;\n }\nexpand:\n \/\/ now allocate a temporary buffer\n char *base=(char *)malloc(size+2);\n memset(base,0,size+1);\n char *s = base;\n \n \/\/ pass 2 - do the formatting\n iter.first();\n for(const char *f = format;*f;f++){\n if(*f=='%'){\n bool isLong=false;\n bool zeropad=false;\n bool negpad=false;\n const char *p = f++;\n precision=-9999; \/\/ rogue value for \"no precision\"\n width=0;\n if(*f=='-'){\n negpad=true;\n f++;\n }\n if(*f=='0')\n zeropad=true;\n while(isdigit(*f))\n width = (width*10) + (*f++ - '0');\n if(*f=='.'){\n precision=0;\n f++;\n while(isdigit(*f))\n precision = (precision*10) + (*f++ - '0');\n }\n while(*f && *f!='%' && !isalpha(*f))\n f++;\n \/\/ length flags\n if((*f=='l' || *f=='z') && (f[1]=='d' || f[1]=='u' || f[1]=='x')){\n if(*f=='l')isLong=true;\n ++f;\n }\n \n switch(*f){\n case 'c':\n *s++ = iter.current()->toInt();\n iter.next();\n break;\n case 'd':\n if(isLong)\n formatSignedLong(s,iter.current()->toLong(),width,precision,zeropad,negpad);\n else\n formatSignedInt(s,iter.current()->toInt(),width,precision,zeropad,negpad);\n s+=strlen(s);\n iter.next();\n break;\n case 'u':\n if(isLong)\n formatUnsignedLong(s,iter.current()->toLong(),width,precision,zeropad,negpad);\n else\n formatUnsignedInt(s,iter.current()->toInt(),width,precision,zeropad,negpad);\n s+=strlen(s);\n iter.next();\n break;\n case 'x':\n if(isLong)\n formatHexInt(s,iter.current()->toInt(),width,precision,zeropad,negpad);\n else\n formatHexLong(s,iter.current()->toInt(),width,precision,zeropad,negpad);\n s+=strlen(s);\n iter.next();\n break;\n case 'f':\n formatFloat(s,iter.current()->toDouble(),width,precision,zeropad,negpad);\n s+=strlen(s);\n iter.next();\n break;\n case 'g':\n formatFloat2(s,iter.current()->toDouble(),width,precision,zeropad,negpad);\n s+=strlen(s);\n iter.next();\n break;\n case 's':{\n const StringBuffer& b = iter.current()->toString();\n formatString(s,b.get(),width,precision,negpad);\n s+=strlen(s);\n iter.next();\n break;\n }\n default:\n strcpy(s,p);\n s+=strlen(s);\n goto end;\n }\n } else\n *s++ = *f;\n }\nend:\n *s=0;\n Types::tString->set(out,base);\n free(base);\n}\n\n}\n<commit_msg>%e formatting<commit_after>\/**\n * @file\n * String formatting code.\n * Much of this code was adapted from Python's string formatting\n * code, but the actual formatting of individual items is done\n * by constructing printf formats and using them. Ugly, but easy.\n * There may be some dodgy assumptions about lengths here.\n *\/\n\n#include \"angort.h\"\n#include <ctype.h>\n#define max(a,b) ((a)>(b)?(a):(b))\n\nnamespace angort {\n\nstatic void formatSignedInt(char *s,int i,int width,int precision, bool zeropad, bool negpad){\n char format[32];\n sprintf(format,\"%%%s%dd\",zeropad?\"0\":\"\",negpad?-width:width);\n sprintf(s,format,i);\n}\n\nstatic void formatUnsignedInt(char *s,unsigned int i,int width,int precision, bool zeropad, bool negpad){\n char format[32];\n sprintf(format,\"%%%s%du\",zeropad?\"0\":\"\",negpad?-width:width);\n sprintf(s,format,i);\n}\n\nstatic void formatSignedLong(char *s,long i,int width,int precision, bool zeropad, bool negpad){\n char format[32];\n sprintf(format,\"%%%s%dld\",zeropad?\"0\":\"\",negpad?-width:width);\n sprintf(s,format,i);\n}\n\nstatic void formatUnsignedLong(char *s,unsigned long i,int width,int precision, bool zeropad, bool negpad){\n char format[32];\n sprintf(format,\"%%%s%dlu\",zeropad?\"0\":\"\",negpad?-width:width);\n sprintf(s,format,i);\n}\n\nstatic void formatHexInt(char *s,unsigned int i,int width,int precision, bool zeropad, bool negpad){\n char format[32];\n sprintf(format,\"%%%s%dx\",zeropad?\"0\":\"\",negpad?-width:width);\n sprintf(s,format,i);\n}\nstatic void formatHexLong(char *s,unsigned long i,int width,int precision, bool zeropad, bool negpad){\n char format[32];\n sprintf(format,\"%%%s%dlx\",zeropad?\"0\":\"\",negpad?-width:width);\n sprintf(s,format,i);\n}\n\nstatic void formatFloat(char *s,double f,int width,int precision, bool zeropad, bool negpad){\n char format[32];\n if(precision!=-9999)\n sprintf(format,\"%%%s%d.%df\",zeropad?\"0\":\"\",negpad?-width:width,precision);\n else\n sprintf(format,\"%%%s%df\",zeropad?\"0\":\"\",negpad?-width:width);\n sprintf(s,format,f);\n}\n\nstatic void formatFloat2(char *s,double f,int width,int precision, bool zeropad, bool negpad){\n char format[32];\n if(precision!=-9999)\n sprintf(format,\"%%%s%d.%dg\",zeropad?\"0\":\"\",negpad?-width:width,precision);\n else\n sprintf(format,\"%%%s%dg\",zeropad?\"0\":\"\",negpad?-width:width);\n sprintf(s,format,f);\n}\n\nstatic void formatScientific(char *s,double f,int width,int precision, bool zeropad, bool negpad){\n char format[32];\n if(precision!=-9999)\n sprintf(format,\"%%%s%d.%de\",zeropad?\"0\":\"\",negpad?-width:width,precision);\n else\n sprintf(format,\"%%%s%de\",zeropad?\"0\":\"\",negpad?-width:width);\n sprintf(s,format,f);\n}\n\nstatic void formatString(char *s,const char *in,int width,int precision, bool negpad){\n char format[32];\n snprintf(format,20,\"%%%ds\",negpad?-width:width);\n sprintf(s,format,in);\n}\n\n\n\nvoid format(Value *out,Value *formatVal,ArrayList<Value> *items){\n \n \/\/ sorry, it actually has to be a string.\n if(formatVal->t != Types::tString)\n throw RUNT(EX_TYPE,\"format must be a string\");\n \n const char *format = Types::tString->getData(formatVal);\n \n ArrayListIterator<Value> iter(items);\n iter.first();\n \n unsigned int width,precision;\n \n \/\/ pass 1, work out the buffer size\n int size=0;\n int strsz;\n for(const char *f = format;*f;f++){\n precision=0;\n width=0;\n if(*f=='%'){\n const char *p = f++;\n if(*f=='-')f++;\n while(isdigit(*f))\n width = (width*10) + (*f++ - '0');\n if(*f=='.'){\n f++;\n while(isdigit(*f))\n precision = (precision*10) + (*f++ - '0');\n }\n while(*f && *f!='%' && !isalpha(*f))\n ;\n if((*f=='l' || *f=='z') && (f[1]=='d' || f[1]=='u' || f[1]=='x'))\n ++f; \/\/ skip length flag (dealt with in pass 2)\n switch(*f){\n case 'c':\n iter.next();\n \/\/ fall through\n case '%':\n size++;\n break;\n case 'd':case 'u':case 'x':\n \/\/ 50 should be plenty\n iter.next();\n size+=max(50,width);\n break;\n case 'f':\n case 'g':\n case 'e':\n iter.next();\n size+=50; \/\/ got to draw the line somewhere.\n break;\n case 's':{\n const StringBuffer& b = iter.current()->toString();\n strsz = max(strlen(b.get()),width);\n size+=strsz;\n iter.next();\n break;\n }\n default:\/\/unknown code; just add the rest of the string in. Ugh.\n size+=strlen(p);\n goto expand;\n break;\n }\n } else\n size++;\n }\nexpand:\n \/\/ now allocate a temporary buffer\n char *base=(char *)malloc(size+2);\n memset(base,0,size+1);\n char *s = base;\n \n \/\/ pass 2 - do the formatting\n iter.first();\n for(const char *f = format;*f;f++){\n if(*f=='%'){\n bool isLong=false;\n bool zeropad=false;\n bool negpad=false;\n const char *p = f++;\n precision=-9999; \/\/ rogue value for \"no precision\"\n width=0;\n if(*f=='-'){\n negpad=true;\n f++;\n }\n if(*f=='0')\n zeropad=true;\n while(isdigit(*f))\n width = (width*10) + (*f++ - '0');\n if(*f=='.'){\n precision=0;\n f++;\n while(isdigit(*f))\n precision = (precision*10) + (*f++ - '0');\n }\n while(*f && *f!='%' && !isalpha(*f))\n f++;\n \/\/ length flags\n if((*f=='l' || *f=='z') && (f[1]=='d' || f[1]=='u' || f[1]=='x')){\n if(*f=='l')isLong=true;\n ++f;\n }\n \n switch(*f){\n case 'c':\n *s++ = iter.current()->toInt();\n iter.next();\n break;\n case 'd':\n if(isLong)\n formatSignedLong(s,iter.current()->toLong(),width,precision,zeropad,negpad);\n else\n formatSignedInt(s,iter.current()->toInt(),width,precision,zeropad,negpad);\n s+=strlen(s);\n iter.next();\n break;\n case 'u':\n if(isLong)\n formatUnsignedLong(s,iter.current()->toLong(),width,precision,zeropad,negpad);\n else\n formatUnsignedInt(s,iter.current()->toInt(),width,precision,zeropad,negpad);\n s+=strlen(s);\n iter.next();\n break;\n case 'x':\n if(isLong)\n formatHexInt(s,iter.current()->toInt(),width,precision,zeropad,negpad);\n else\n formatHexLong(s,iter.current()->toInt(),width,precision,zeropad,negpad);\n s+=strlen(s);\n iter.next();\n break;\n case 'f':\n formatFloat(s,iter.current()->toDouble(),width,precision,zeropad,negpad);\n s+=strlen(s);\n iter.next();\n break;\n case 'g':\n formatFloat2(s,iter.current()->toDouble(),width,precision,zeropad,negpad);\n s+=strlen(s);\n iter.next();\n break;\n case 'e':\n formatScientific(s,iter.current()->toDouble(),width,precision,zeropad,negpad);\n s+=strlen(s);\n iter.next();\n break;\n case 's':{\n const StringBuffer& b = iter.current()->toString();\n formatString(s,b.get(),width,precision,negpad);\n s+=strlen(s);\n iter.next();\n break;\n }\n default:\n strcpy(s,p);\n s+=strlen(s);\n goto end;\n }\n } else\n *s++ = *f;\n }\nend:\n *s=0;\n Types::tString->set(out,base);\n free(base);\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"mainwindow.h\"\n#include <QApplication>\n#include <QGridLayout>\n#include <QWidget>\n#include <QLabel>\n#include <QMenuBar>\n#include <QToolBar>\n#include <QStatusBar>\n#include <QAction>\n#include <QFileDialog>\n#include <QDebug>\n#include <QMessageBox>\n#include \"newimagedialog.h\"\n#include \"util.h\"\n#include \"imageeditwindow.h\"\n\n\n\/**\n * @brief MainWindow::MainWindow\n * @brief mainwindow的构造函数\n * @param parent 是qt widget的父指针\n * @return 没有返回值\n *\/\nMainWindow::MainWindow(QWidget *parent) :\n QMainWindow(parent)\n{\n this->initWindowLayout();\n this->initAction();\n\n QIcon icon(\":\/image\/open.png\"); \/\/设置程序图标\n this->setWindowIcon(icon);\n\n this->fileMenu = this->menuBar()->addMenu(\"&File\");\n this->fileMenu->addAction(this->loadSourceImageAction);\n\n this->helpMenu = this->menuBar()->addMenu(\"&Help\");\n this->helpMenu->addAction(this->aboutAction);\n\n this->menuBar()->setStyleSheet(\" QMenuBar{background-color: #333337; padding-left: 5px;}\\\n QMenuBar::item {background-color: #333337; padding:2px; margin:6px 10px 0px 0px;} \\\n QMenuBar::item:selected {background: #3e3e40;} \\\n QMenuBar::item:pressed {background: #1b1b1c;}\\\n \");\n\n QToolBar* toolbar = this->addToolBar(\"Standard Tool Bar\");\n toolbar->addAction(this->loadSourceImageAction);\n\n QStatusBar* statusBar = this->statusBar();\n\n}\n\n\n\/**\n * @brief MainWindow::initAction\n * @brief 用于mainwindow的action的定义、connect、插入\n * @param 没有参数\n * @return 没有返回值\n *\/\nvoid MainWindow::initAction(){\n this->loadSourceImageAction = new QAction(QIcon(\":\/image\/open.png\"),\"&Load\",this);\n QObject::connect(this->loadSourceImageAction, &QAction::triggered, this, &MainWindow::loadSourceImage);\n\n this->viewSourceImageAction = new QAction(QIcon(\":\/image\/open.png\"),\"&View\",this);\n QObject::connect(this->viewSourceImageAction, &QAction::triggered, this, &MainWindow::viewSourceImage);\n\n this->editSourceGuidanceAction = new QAction(QIcon(\":\/image\/open.png\"),\"&Edit\",this);\n QObject::connect(this->editSourceGuidanceAction, &QAction::triggered, this, &MainWindow::editSourceGuidance);\n\n this->viewTargetGuidanceAction = new QAction(QIcon(\":\/image\/open.png\"),\"&View\",this);\n QObject::connect(this->viewTargetGuidanceAction, &QAction::triggered, this, &MainWindow::viewTargetGuidance);\n\n this->newImageAction = new QAction(QIcon(\":\/image\/open.png\"),\"&Create new guidance\",this);\n QObject::connect(this->newImageAction, &QAction::triggered, this, &MainWindow::newImage);\n\n this->editTargetGuidanceAction = new QAction(QIcon(\":\/image\/open.png\"),\"&Edit\",this);\n QObject::connect(this->editTargetGuidanceAction, &QAction::triggered, this, &MainWindow::editTargetGuidance);\n\n this->aboutAction = new QAction(QIcon(\":\/image\/open.png\"),\"&About\",this);\n QObject::connect(this->aboutAction, &QAction::triggered, this, &MainWindow::about);\n\n \/\/Action 插入段\n this->sourceImageLabel->addAction(this->viewSourceImageAction); \/\/左上角的view\n this->sourceImageLabel->addAction(this->loadSourceImageAction); \/\/左上角的load\n\n this->sourceGuidanceLabel->addAction(new QAction(\"&View\",this));\n this->sourceGuidanceLabel->addAction(this->editSourceGuidanceAction);\n\n this->targetGuidanceLabel->addAction(this->viewTargetGuidanceAction);\n this->targetGuidanceLabel->addAction(this->newImageAction);\n this->targetGuidanceLabel->addAction(this->editTargetGuidanceAction);\n\n\n}\n\n\n\/**\n * @brief MainWindow::loadSourceImage\n * @brief load image的action的入口函数,用于载入一个原图,并显示在左上角,顺带初始化右上角的source guidance(同等大小的白图)。\n * @param 没有参数\n * @return 没有返回值\n *\/\nvoid MainWindow::loadSourceImage(){\n QFileDialog* fileDialog = new QFileDialog(this, tr(\"Open image File\"), \".\", tr(\"Image files(*.png)\"));\n fileDialog->setFileMode(QFileDialog::ExistingFiles);\n fileDialog->setViewMode(QFileDialog::Detail);\n\n if (fileDialog->exec() == QDialog::Accepted) \/\/成功选择一个png图片\n {\n this->sourceImage =new QImage(fileDialog->selectedFiles().first()); \/\/此处会有内存泄漏,以后处理\n this->sourceImage->save(\".\/sourceImage.png\");\n this->sourceImageFrame->setStyleSheet(\"background-image: url(.\/sourceImage.png);background-position:center center;background-repeat: no-repeat\");\n\n this->sourceGuidance = new QImage(this->sourceImage->width(), this->sourceImage->height(), QImage::Format_RGB888); \/\/新建一个同等大小的空图像\n this->sourceGuidance->fill(QColor(255,255,255)); \/\/填充白色\n for(QString elem : Util::guidanceChannel){\n this->sourceGuidance->save(\".\/sourceGuidance\"+elem+\".png\");\n }\n this->sourceGuidanceFrame->setStyleSheet(\"background-image: url(.\/sourceGuidanceLabelChannel.png);background-position:center center;background-repeat: no-repeat\"); \/\/显示在右上角\n }\n}\n\nMainWindow::~MainWindow()\n{\n}\n\n\n\/**\n * @brief MainWindow::initWindowLayout\n * @brief 用于管理mainwindow的窗口设置、layout布局、内部控件声明及摆放\n * @param 没有参数\n * @return 没有返回值\n *\/\nvoid MainWindow::initWindowLayout(){\n this->setWindowState(Qt::WindowMaximized); \/\/设置窗口最大化\n this->setStyleSheet(\"background-color: #333337; color: #f1f1f1;\"); \/\/设置窗口样式(酷黑)\n\n QWidget* centerWidget = new QWidget(this); \/\/声明widget并设置为窗口的中央widget(这样才能设置layout)\n this->setCentralWidget(centerWidget);\n\n QGridLayout* gridLayout = new QGridLayout(centerWidget); \/\/在中央widget开启网格布局\n centerWidget->setLayout(gridLayout);\n\n this->sourceImageLabel = new QLabel(centerWidget); \/\/左上角label声明:放置source image\n this->sourceImageLabel->setStyleSheet(\"background-color: #696969;\");\n gridLayout->addWidget(sourceImageLabel,0,0);\n this->sourceImageLabel->setContextMenuPolicy(Qt::ActionsContextMenu); \/\/激活右键菜单策略\n QGridLayout* sourceImageLabelGridLayout = new QGridLayout(this->sourceImageLabel); \/\/在label内建一个layout放置一个Frame,可以保证右键菜单的背景不受改变\n this->sourceImageLabel->setLayout(sourceImageLabelGridLayout);\n this->sourceImageFrame = new QFrame(this->sourceImageLabel);\n sourceImageLabelGridLayout->addWidget(this->sourceImageFrame,0,0);\n\n this->sourceGuidanceLabel = new QLabel(centerWidget); \/\/右上角label声明:放置source guidance\n this->sourceGuidanceLabel->setStyleSheet(\"background-color: #696969;\");\n gridLayout->addWidget(this->sourceGuidanceLabel,0,1);\n this->sourceGuidanceLabel->setContextMenuPolicy(Qt::ActionsContextMenu); \/\/激活右键菜单策略\n QGridLayout* sourceGuidanceLabelGridLayout = new QGridLayout(this->sourceGuidanceLabel); \/\/在label内建一个layout放置一个Frame,可以保证右键菜单的背景不受改变\n this->sourceGuidanceLabel->setLayout(sourceGuidanceLabelGridLayout);\n this->sourceGuidanceFrame = new QFrame(this->sourceGuidanceLabel);\n sourceGuidanceLabelGridLayout->addWidget(this->sourceGuidanceFrame,0,0);\n\n this->targetGuidanceLabel = new QLabel(centerWidget); \/\/ 左下角label声明:放置target guidance\n this->targetGuidanceLabel->setStyleSheet(\"background-color: #696969;\");\n gridLayout->addWidget(this->targetGuidanceLabel,1,0);\n this->targetGuidanceLabel->setContextMenuPolicy(Qt::ActionsContextMenu); \/\/激活右键菜单策略\n QGridLayout* targetGuidanceLabelGridLayout = new QGridLayout(this->targetGuidanceLabel); \/\/在label内建一个layout放置一个Frame,可以保证右键菜单的背景不受改变\n this->targetGuidanceLabel->setLayout(targetGuidanceLabelGridLayout);\n this->targetGuidanceFrame = new QFrame(this->targetGuidanceLabel);\n targetGuidanceLabelGridLayout->addWidget(this->targetGuidanceFrame,0,0);\n\n QLabel* label4 = new QLabel(centerWidget);\n label4->setStyleSheet(\"background-color: #696969;\");\n gridLayout->addWidget(label4,1,1);\n label4->setContextMenuPolicy(Qt::ActionsContextMenu); \/\/激活右键菜单策略\n label4->addAction(new QAction(\"&View\",this));\n\n}\n\n\n\n\/**\n * @brief MainWindow::newImage\n * @brief mainwindow中点击新建导引图片的action\n * @param 没有参数\n * @return 没有返回值\n *\/\nvoid MainWindow::newImage(){\n NewImageDialog* newImageDialog = new NewImageDialog();\n if(newImageDialog->exec() == QDialog::Accepted){\n this->targetGuidanceFrame->setStyleSheet(\"background-image: url(.\/targetGuidanceLabelChannel.png);background-position:center center;background-repeat: no-repeat\"); \/\/显示在右上角\n }\n}\n\n\n\n\n\nvoid MainWindow::editSourceGuidance(){\n ImageEditWindow* imageEditWindow = new ImageEditWindow(config::sourceGuidance, config::editable, this);\n imageEditWindow->show();\n}\n\n\n\nvoid MainWindow::viewSourceImage(){\n ImageEditWindow* imageEditWindow = new ImageEditWindow(config::sourceImage, config::readOnly, this);\n imageEditWindow->show();\n}\n\n\nvoid MainWindow::about()\n{\n QMessageBox::about(this, tr(\"About Uncle Zhou UI\"),\n tr(\"<p><b>Uncle Zhou UI<\/b><\/p>\"\n \"Open sourced under the <b>MIT<\/b> license.<br\/>\"\n \"Copyright (c) 2015 NetBeen<br\/>\"\n \"netbeen.cn@gmail.com\"));\n\n\n}\n\n\nvoid MainWindow::editTargetGuidance(){\n ImageEditWindow* imageEditWindow = new ImageEditWindow(config::targetGuidance, config::editable, this);\n imageEditWindow->show();\n}\n\nvoid MainWindow::viewTargetGuidance(){\n ImageEditWindow* imageEditWindow = new ImageEditWindow(config::targetGuidance, config::readOnly, this);\n imageEditWindow->show();\n}\n<commit_msg>修改菜单名称,使之更加明确其含义<commit_after>#include \"mainwindow.h\"\n#include <QApplication>\n#include <QGridLayout>\n#include <QWidget>\n#include <QLabel>\n#include <QMenuBar>\n#include <QToolBar>\n#include <QStatusBar>\n#include <QAction>\n#include <QFileDialog>\n#include <QDebug>\n#include <QMessageBox>\n#include \"newimagedialog.h\"\n#include \"util.h\"\n#include \"imageeditwindow.h\"\n\n\n\/**\n * @brief MainWindow::MainWindow\n * @brief mainwindow的构造函数\n * @param parent 是qt widget的父指针\n * @return 没有返回值\n *\/\nMainWindow::MainWindow(QWidget *parent) :\n QMainWindow(parent)\n{\n this->initWindowLayout();\n this->initAction();\n\n QIcon icon(\":\/image\/open.png\"); \/\/设置程序图标\n this->setWindowIcon(icon);\n\n this->fileMenu = this->menuBar()->addMenu(\"&File\");\n this->fileMenu->addAction(this->loadSourceImageAction);\n\n this->helpMenu = this->menuBar()->addMenu(\"&Help\");\n this->helpMenu->addAction(this->aboutAction);\n\n this->menuBar()->setStyleSheet(\" QMenuBar{background-color: #333337; padding-left: 5px;}\\\n QMenuBar::item {background-color: #333337; padding:2px; margin:6px 10px 0px 0px;} \\\n QMenuBar::item:selected {background: #3e3e40;} \\\n QMenuBar::item:pressed {background: #1b1b1c;}\\\n \");\n\n QToolBar* toolbar = this->addToolBar(\"Standard Tool Bar\");\n toolbar->addAction(this->loadSourceImageAction);\n\n QStatusBar* statusBar = this->statusBar();\n\n}\n\n\n\/**\n * @brief MainWindow::initAction\n * @brief 用于mainwindow的action的定义、connect、插入\n * @param 没有参数\n * @return 没有返回值\n *\/\nvoid MainWindow::initAction(){\n this->loadSourceImageAction = new QAction(QIcon(\":\/image\/open.png\"),\"&Load Source Image\",this);\n QObject::connect(this->loadSourceImageAction, &QAction::triggered, this, &MainWindow::loadSourceImage);\n\n this->viewSourceImageAction = new QAction(QIcon(\":\/image\/open.png\"),\"&View Source Image\",this);\n QObject::connect(this->viewSourceImageAction, &QAction::triggered, this, &MainWindow::viewSourceImage);\n\n this->editSourceGuidanceAction = new QAction(QIcon(\":\/image\/open.png\"),\"&Edit Source Guidance\",this);\n QObject::connect(this->editSourceGuidanceAction, &QAction::triggered, this, &MainWindow::editSourceGuidance);\n\n this->viewTargetGuidanceAction = new QAction(QIcon(\":\/image\/open.png\"),\"&View Target Guidance\",this);\n QObject::connect(this->viewTargetGuidanceAction, &QAction::triggered, this, &MainWindow::viewTargetGuidance);\n\n this->newImageAction = new QAction(QIcon(\":\/image\/open.png\"),\"&Create New Guidance\",this);\n QObject::connect(this->newImageAction, &QAction::triggered, this, &MainWindow::newImage);\n\n this->editTargetGuidanceAction = new QAction(QIcon(\":\/image\/open.png\"),\"&Edit Target Guidance\",this);\n QObject::connect(this->editTargetGuidanceAction, &QAction::triggered, this, &MainWindow::editTargetGuidance);\n\n this->aboutAction = new QAction(QIcon(\":\/image\/open.png\"),\"&About\",this);\n QObject::connect(this->aboutAction, &QAction::triggered, this, &MainWindow::about);\n\n \/\/Action 插入段\n this->sourceImageLabel->addAction(this->viewSourceImageAction); \/\/左上角的view\n this->sourceImageLabel->addAction(this->loadSourceImageAction); \/\/左上角的load\n\n this->sourceGuidanceLabel->addAction(new QAction(\"&View\",this));\n this->sourceGuidanceLabel->addAction(this->editSourceGuidanceAction);\n\n this->targetGuidanceLabel->addAction(this->viewTargetGuidanceAction);\n this->targetGuidanceLabel->addAction(this->newImageAction);\n this->targetGuidanceLabel->addAction(this->editTargetGuidanceAction);\n\n\n}\n\n\n\/**\n * @brief MainWindow::loadSourceImage\n * @brief load image的action的入口函数,用于载入一个原图,并显示在左上角,顺带初始化右上角的source guidance(同等大小的白图)。\n * @param 没有参数\n * @return 没有返回值\n *\/\nvoid MainWindow::loadSourceImage(){\n QFileDialog* fileDialog = new QFileDialog(this, tr(\"Open image File\"), \".\", tr(\"Image files(*.png)\"));\n fileDialog->setFileMode(QFileDialog::ExistingFiles);\n fileDialog->setViewMode(QFileDialog::Detail);\n\n if (fileDialog->exec() == QDialog::Accepted) \/\/成功选择一个png图片\n {\n this->sourceImage =new QImage(fileDialog->selectedFiles().first()); \/\/此处会有内存泄漏,以后处理\n this->sourceImage->save(\".\/sourceImage.png\");\n this->sourceImageFrame->setStyleSheet(\"background-image: url(.\/sourceImage.png);background-position:center center;background-repeat: no-repeat\");\n\n this->sourceGuidance = new QImage(this->sourceImage->width(), this->sourceImage->height(), QImage::Format_RGB888); \/\/新建一个同等大小的空图像\n this->sourceGuidance->fill(QColor(255,255,255)); \/\/填充白色\n for(QString elem : Util::guidanceChannel){\n this->sourceGuidance->save(\".\/sourceGuidance\"+elem+\".png\");\n }\n this->sourceGuidanceFrame->setStyleSheet(\"background-image: url(.\/sourceGuidanceLabelChannel.png);background-position:center center;background-repeat: no-repeat\"); \/\/显示在右上角\n }\n}\n\nMainWindow::~MainWindow()\n{\n}\n\n\n\/**\n * @brief MainWindow::initWindowLayout\n * @brief 用于管理mainwindow的窗口设置、layout布局、内部控件声明及摆放\n * @param 没有参数\n * @return 没有返回值\n *\/\nvoid MainWindow::initWindowLayout(){\n this->setWindowState(Qt::WindowMaximized); \/\/设置窗口最大化\n this->setStyleSheet(\"background-color: #333337; color: #f1f1f1;\"); \/\/设置窗口样式(酷黑)\n\n QWidget* centerWidget = new QWidget(this); \/\/声明widget并设置为窗口的中央widget(这样才能设置layout)\n this->setCentralWidget(centerWidget);\n\n QGridLayout* gridLayout = new QGridLayout(centerWidget); \/\/在中央widget开启网格布局\n centerWidget->setLayout(gridLayout);\n\n this->sourceImageLabel = new QLabel(centerWidget); \/\/左上角label声明:放置source image\n this->sourceImageLabel->setStyleSheet(\"background-color: #696969;\");\n gridLayout->addWidget(sourceImageLabel,0,0);\n this->sourceImageLabel->setContextMenuPolicy(Qt::ActionsContextMenu); \/\/激活右键菜单策略\n QGridLayout* sourceImageLabelGridLayout = new QGridLayout(this->sourceImageLabel); \/\/在label内建一个layout放置一个Frame,可以保证右键菜单的背景不受改变\n this->sourceImageLabel->setLayout(sourceImageLabelGridLayout);\n this->sourceImageFrame = new QFrame(this->sourceImageLabel);\n sourceImageLabelGridLayout->addWidget(this->sourceImageFrame,0,0);\n\n this->sourceGuidanceLabel = new QLabel(centerWidget); \/\/右上角label声明:放置source guidance\n this->sourceGuidanceLabel->setStyleSheet(\"background-color: #696969;\");\n gridLayout->addWidget(this->sourceGuidanceLabel,0,1);\n this->sourceGuidanceLabel->setContextMenuPolicy(Qt::ActionsContextMenu); \/\/激活右键菜单策略\n QGridLayout* sourceGuidanceLabelGridLayout = new QGridLayout(this->sourceGuidanceLabel); \/\/在label内建一个layout放置一个Frame,可以保证右键菜单的背景不受改变\n this->sourceGuidanceLabel->setLayout(sourceGuidanceLabelGridLayout);\n this->sourceGuidanceFrame = new QFrame(this->sourceGuidanceLabel);\n sourceGuidanceLabelGridLayout->addWidget(this->sourceGuidanceFrame,0,0);\n\n this->targetGuidanceLabel = new QLabel(centerWidget); \/\/ 左下角label声明:放置target guidance\n this->targetGuidanceLabel->setStyleSheet(\"background-color: #696969;\");\n gridLayout->addWidget(this->targetGuidanceLabel,1,0);\n this->targetGuidanceLabel->setContextMenuPolicy(Qt::ActionsContextMenu); \/\/激活右键菜单策略\n QGridLayout* targetGuidanceLabelGridLayout = new QGridLayout(this->targetGuidanceLabel); \/\/在label内建一个layout放置一个Frame,可以保证右键菜单的背景不受改变\n this->targetGuidanceLabel->setLayout(targetGuidanceLabelGridLayout);\n this->targetGuidanceFrame = new QFrame(this->targetGuidanceLabel);\n targetGuidanceLabelGridLayout->addWidget(this->targetGuidanceFrame,0,0);\n\n QLabel* label4 = new QLabel(centerWidget);\n label4->setStyleSheet(\"background-color: #696969;\");\n gridLayout->addWidget(label4,1,1);\n label4->setContextMenuPolicy(Qt::ActionsContextMenu); \/\/激活右键菜单策略\n label4->addAction(new QAction(\"&View\",this));\n\n}\n\n\n\n\/**\n * @brief MainWindow::newImage\n * @brief mainwindow中点击新建导引图片的action\n * @param 没有参数\n * @return 没有返回值\n *\/\nvoid MainWindow::newImage(){\n NewImageDialog* newImageDialog = new NewImageDialog();\n if(newImageDialog->exec() == QDialog::Accepted){\n this->targetGuidanceFrame->setStyleSheet(\"background-image: url(.\/targetGuidanceLabelChannel.png);background-position:center center;background-repeat: no-repeat\"); \/\/显示在右上角\n }\n}\n\n\n\n\n\nvoid MainWindow::editSourceGuidance(){\n ImageEditWindow* imageEditWindow = new ImageEditWindow(config::sourceGuidance, config::editable, this);\n imageEditWindow->show();\n}\n\n\n\nvoid MainWindow::viewSourceImage(){\n ImageEditWindow* imageEditWindow = new ImageEditWindow(config::sourceImage, config::readOnly, this);\n imageEditWindow->show();\n}\n\n\nvoid MainWindow::about()\n{\n QMessageBox::about(this, tr(\"About Uncle Zhou UI\"),\n tr(\"<p><b>Uncle Zhou UI<\/b><\/p>\"\n \"Open sourced under the <b>MIT<\/b> license.<br\/>\"\n \"Copyright (c) 2015 NetBeen<br\/>\"\n \"netbeen.cn@gmail.com\"));\n\n\n}\n\n\nvoid MainWindow::editTargetGuidance(){\n ImageEditWindow* imageEditWindow = new ImageEditWindow(config::targetGuidance, config::editable, this);\n imageEditWindow->show();\n}\n\nvoid MainWindow::viewTargetGuidance(){\n ImageEditWindow* imageEditWindow = new ImageEditWindow(config::targetGuidance, config::readOnly, this);\n imageEditWindow->show();\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n Copyright 2014 Sarah Wong\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n*\/\n\n#include \"mainwindow.h\"\n#include \"about.h\"\n\n#include <QPainter>\n#include <QResizeEvent>\n\n#include <cmath>\n\n#include \"config.h\"\n\nViewerWidget::ViewerWidget(QWidget* parent)\n : QGLWidget(parent),\n m_parent(dynamic_cast<MainWindow*>(parent)),\n m_update_pending(false)\n{\n}\n\nvoid ViewerWidget::renderLater() {\n if (!m_update_pending) {\n m_update_pending = true;\n QCoreApplication::postEvent(this, new QEvent(QEvent::UpdateRequest));\n }\n}\n\nnamespace {\n\ndouble frequencyToKey(double frequency)\n{\n \/\/ http:\/\/en.wikipedia.org\/wiki\/Piano_key_frequencies\n return 12 * log2(frequency \/ 440) + 49;\n}\n\n} \/\/ namespace anonymous\n\nvoid ViewerWidget::renderNow() {\n QPainter painter(this);\n\n painter.fillRect(rect(), Qt::black);\n\n const QPen penWhite(QColor(255, 255, 255));\n const QBrush brushWhite(QColor(255, 255, 255));\n\n const auto& uiConfig = m_parent->config().uiConfig;\n\n int width = size().width();\n int height = size().height();\n\n std::lock_guard<std::mutex> lockGuard(m_parent->f0thread().mutex());\n\n double minNote = frequencyToKey(uiConfig.min_note);\n double maxNote = frequencyToKey(uiConfig.max_note);\n\n auto noteToPos = [this, uiConfig, height, minNote, maxNote](double note) {\n note = frequencyToKey(note);\n return height -\n (note - minNote) *\n (static_cast<double>(height) \/ (maxNote - minNote));\n };\n\n const double noteWidth = uiConfig.note_width;\n\n\n double position = 0;\n for (auto f0 : m_parent->f0thread().cb()) {\n if (f0 != 0) {\n\n double ypos = noteToPos(f0);\n\n painter.setPen(penWhite);\n painter.setBrush(brushWhite);\n\n painter.drawRect(position, ypos - 1, noteWidth, noteWidth);\n }\n\n position += noteWidth;\n }\n\n for (const auto& line : m_parent->config().uiMarkerLines.lines) {\n double ypos = noteToPos(line.frequency);\n painter.setPen(line.pen);\n painter.drawLine(0, ypos, width, ypos);\n }\n}\n\nbool ViewerWidget::event(QEvent* event)\n{\n switch (event->type()) {\n case QEvent::UpdateRequest:\n m_update_pending = false;\n renderNow();\n return true;\n default:\n return QGLWidget::event(event);\n }\n}\n\nvoid ViewerWidget::paintEvent(QPaintEvent* event)\n{\n renderNow();\n}\n\nvoid ViewerWidget::resizeEvent(QResizeEvent* event)\n{\n emit widthChanged(event->size().width());\n}\n\nMainWindow::MainWindow(const config::Config& config, F0Thread& f0thread)\n : m_config(config), m_f0thread(f0thread)\n{\n ViewerWidget* vw = new ViewerWidget(this);\n vw->setObjectName(\"viewer\");\n\n m_ui.setupUi(this);\n resize(m_config.uiConfig.width, m_config.uiConfig.height);\n\n setCentralWidget(vw);\n\n QObject::connect(&f0thread, SIGNAL(updated()), vw, SLOT(renderLater()));\n}\n\nvoid MainWindow::on_action_About_triggered()\n{\n About* about = new About(this);\n about->show();\n}\n\nvoid MainWindow::on_viewer_widthChanged(int width)\n{\n std::lock_guard<std::mutex> lockGuard(m_f0thread.mutex());\n m_f0thread.cb().resize(width \/ m_config.uiConfig.note_width);\n}\n<commit_msg>shorten critical section of mutex<commit_after>\/*\n Copyright 2014 Sarah Wong\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n*\/\n\n#include \"mainwindow.h\"\n#include \"about.h\"\n\n#include <QPainter>\n#include <QResizeEvent>\n\n#include <cmath>\n\n#include \"config.h\"\n\nViewerWidget::ViewerWidget(QWidget* parent)\n : QGLWidget(parent),\n m_parent(dynamic_cast<MainWindow*>(parent)),\n m_update_pending(false)\n{\n}\n\nvoid ViewerWidget::renderLater() {\n if (!m_update_pending) {\n m_update_pending = true;\n QCoreApplication::postEvent(this, new QEvent(QEvent::UpdateRequest));\n }\n}\n\nnamespace {\n\ndouble frequencyToKey(double frequency)\n{\n \/\/ http:\/\/en.wikipedia.org\/wiki\/Piano_key_frequencies\n return 12 * log2(frequency \/ 440) + 49;\n}\n\n} \/\/ namespace anonymous\n\nvoid ViewerWidget::renderNow() {\n QPainter painter(this);\n\n painter.fillRect(rect(), Qt::black);\n\n const QPen penWhite(QColor(255, 255, 255));\n const QBrush brushWhite(QColor(255, 255, 255));\n\n const auto& uiConfig = m_parent->config().uiConfig;\n\n int width = size().width();\n int height = size().height();\n\n double minNote = frequencyToKey(uiConfig.min_note);\n double maxNote = frequencyToKey(uiConfig.max_note);\n\n auto noteToPos = [this, uiConfig, height, minNote, maxNote](double note) {\n note = frequencyToKey(note);\n return height -\n (note - minNote) *\n (static_cast<double>(height) \/ (maxNote - minNote));\n };\n\n const double noteWidth = uiConfig.note_width;\n\n {\n std::lock_guard<std::mutex> lockGuard(m_parent->f0thread().mutex());\n\n double position = 0;\n for (auto f0 : m_parent->f0thread().cb()) {\n if (f0 != 0) {\n double ypos = noteToPos(f0);\n\n painter.setPen(penWhite);\n painter.setBrush(brushWhite);\n\n painter.drawRect(position, ypos - 1, noteWidth, noteWidth);\n }\n\n position += noteWidth;\n }\n }\n\n for (const auto& line : m_parent->config().uiMarkerLines.lines) {\n double ypos = noteToPos(line.frequency);\n painter.setPen(line.pen);\n painter.drawLine(0, ypos, width, ypos);\n }\n}\n\nbool ViewerWidget::event(QEvent* event)\n{\n switch (event->type()) {\n case QEvent::UpdateRequest:\n m_update_pending = false;\n renderNow();\n return true;\n default:\n return QGLWidget::event(event);\n }\n}\n\nvoid ViewerWidget::paintEvent(QPaintEvent* event)\n{\n renderNow();\n}\n\nvoid ViewerWidget::resizeEvent(QResizeEvent* event)\n{\n emit widthChanged(event->size().width());\n}\n\nMainWindow::MainWindow(const config::Config& config, F0Thread& f0thread)\n : m_config(config), m_f0thread(f0thread)\n{\n ViewerWidget* vw = new ViewerWidget(this);\n vw->setObjectName(\"viewer\");\n\n m_ui.setupUi(this);\n resize(m_config.uiConfig.width, m_config.uiConfig.height);\n\n setCentralWidget(vw);\n\n QObject::connect(&f0thread, SIGNAL(updated()), vw, SLOT(renderLater()));\n}\n\nvoid MainWindow::on_action_About_triggered()\n{\n About* about = new About(this);\n about->show();\n}\n\nvoid MainWindow::on_viewer_widthChanged(int width)\n{\n std::lock_guard<std::mutex> lockGuard(m_f0thread.mutex());\n m_f0thread.cb().resize(width \/ m_config.uiConfig.note_width);\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"stdafx.h\"\n#include \"CppUnitTest.h\"\n#include \"..\/CPPace.Lib\/MinimumFillIn.h\"\n\nusing namespace Microsoft::VisualStudio::CppUnitTestFramework;\n\nnamespace CPPaceTests {\n TEST_CLASS(MinimumFillInTests) {\n public:\n TEST_METHOD(ChordlessPath) {\n AdjacencyList graph(5);\n Assert::IsTrue(MinimumFillIn::is_path_chordless(graph, vector<int> { 0 }));\n\n \/\/ 0-1 2 3 4\n graph.add_edge(0, 1);\n Assert::IsTrue(MinimumFillIn::is_path_chordless(graph, vector<int> { 0 }));\n Assert::IsTrue(MinimumFillIn::is_path_chordless(graph, vector<int> { 0, 1 }));\n\n \/\/ 0-1-2-3-4\n graph.add_edge(1, 2);\n graph.add_edge(3, 4);\n graph.add_edge(2, 3);\n Assert::IsTrue(MinimumFillIn::is_path_chordless(graph, vector<int> { 0, 1, 2, 3, 4 }));\n Assert::IsTrue(MinimumFillIn::is_path_chordless(graph, vector<int> { 4, 3, 2, 1, 0 }));\n\n \/\/ 0 2-3-4\n \/\/ \\_\/\n graph.add_edge(0, 2);\n Assert::IsFalse(MinimumFillIn::is_path_chordless(graph, vector<int> { 0, 1, 2, 3, 4 }));\n Assert::IsFalse(MinimumFillIn::is_path_chordless(graph, vector<int> { 4, 3, 2, 1, 0 }));\n Assert::IsTrue(MinimumFillIn::is_path_chordless(graph, vector<int> { 0, 2, 3, 4 }));\n Assert::IsTrue(MinimumFillIn::is_path_chordless(graph, vector<int> { 4, 3, 2, 0 }));\n\n \/\/ 0 2-3-4\n \/\/ \\_\/ \\_\/\n graph.add_edge(2, 4);\n Assert::IsFalse(MinimumFillIn::is_path_chordless(graph, vector<int> { 0, 2, 3, 4 }));\n Assert::IsFalse(MinimumFillIn::is_path_chordless(graph, vector<int> { 4, 3, 2, 0 }));\n }\n\n TEST_METHOD(FindFourCycle) {\n AdjacencyList graph(5);\n vector<int> cycle;\n Assert::IsFalse(MinimumFillIn::find_four_cycle(graph, cycle));\n\n graph.add_edge(0, 1);\n Assert::IsFalse(MinimumFillIn::find_four_cycle(graph, cycle));\n Assert::AreEqual(0, (int)cycle.size());\n\n graph.add_edge(1, 2);\n Assert::IsFalse(MinimumFillIn::find_four_cycle(graph, cycle));\n Assert::AreEqual(0, (int)cycle.size());\n\n graph.add_edge(2, 3);\n Assert::IsFalse(MinimumFillIn::find_four_cycle(graph, cycle));\n Assert::AreEqual(0, (int)cycle.size());\n\n graph.add_edge(3, 4);\n Assert::IsFalse(MinimumFillIn::find_four_cycle(graph, cycle));\n Assert::AreEqual(0, (int)cycle.size());\n\n graph.add_edge(4, 0);\n Assert::IsFalse(MinimumFillIn::find_four_cycle(graph, cycle));\n Assert::AreEqual(0, (int)cycle.size());\n\n graph.add_edge(3, 0);\n Assert::IsTrue(MinimumFillIn::find_four_cycle(graph, cycle));\n Assert::AreEqual(4, (int)cycle.size());\n\n graph.remove_vertex(0);\n Assert::IsFalse(MinimumFillIn::find_four_cycle(graph, cycle));\n Assert::AreEqual(0, (int)cycle.size());\n\n graph.add_edge(1, 4);\n Assert::IsTrue(MinimumFillIn::find_four_cycle(graph, cycle));\n Assert::AreEqual(4, (int)cycle.size());\n\n graph.add_vertex(0);\n graph.remove_edge(1, 4);\n Assert::IsTrue(MinimumFillIn::find_four_cycle(graph, cycle));\n Assert::AreEqual(4, (int)cycle.size());\n }\n\n TEST_METHOD(FindFourCycleBerryBordat) {\n AdjacencyList graph = SampleGraphs::berry_bordat();\n vector<int> cycle;\n Assert::IsTrue(MinimumFillIn::find_four_cycle(graph, cycle));\n Assert::AreEqual(4, (int)cycle.size());\n\n graph.remove_vertex(5);\n Assert::IsFalse(MinimumFillIn::find_four_cycle(graph, cycle));\n Assert::AreEqual(0, (int)cycle.size());\n }\n\n TEST_METHOD(FindVStar) {\n int v_star;\n AdjacencyList graph(5);\n Assert::IsFalse(MinimumFillIn::find_v_star(graph, 0, 2, set<int>(), v_star));\n\n graph.add_edge(0, 1);\n Assert::IsFalse(MinimumFillIn::find_v_star(graph, 0, 2, set<int>(), v_star));\n\n graph.add_edge(1, 2);\n Assert::IsTrue(MinimumFillIn::find_v_star(graph, 0, 2, set<int>(), v_star));\n Assert::AreEqual(1, v_star);\n\n graph.add_edge(2, 3);\n Assert::IsTrue(MinimumFillIn::find_v_star(graph, 0, 3, set<int>(), v_star));\n Assert::IsTrue(v_star == 1 || v_star == 2);\n\n graph.remove_vertex(2);\n Assert::IsFalse(MinimumFillIn::find_v_star(graph, 0, 2, set<int>(), v_star));\n Assert::IsFalse(MinimumFillIn::find_v_star(graph, 0, 3, set<int>(), v_star));\n\n graph.add_edge(1, 4);\n graph.add_edge(3, 4);\n Assert::IsTrue(MinimumFillIn::find_v_star(graph, 0, 3, set<int>(), v_star));\n Assert::IsTrue(v_star == 4 || v_star == 1);\n\n Assert::IsTrue(MinimumFillIn::find_v_star(graph, 0, 3, set<int>(), v_star));\n Assert::IsTrue(v_star == 4 || v_star == 1);\n\n graph.add_vertex(2);\n\n Assert::IsTrue(MinimumFillIn::find_v_star(graph, 0, 3, set<int>(), v_star));\n Assert::AreEqual(1, v_star);\n\n graph.add_edge(0, 4);\n Assert::IsFalse(MinimumFillIn::find_v_star(graph, 0, 3, set<int>(), v_star));\n\n Assert::IsTrue(MinimumFillIn::find_v_star(graph, 0, 3, set<int> { 4 }, v_star));\n Assert::IsTrue(v_star == 1 || v_star == 2);\n }\n\n TEST_METHOD(FindMoplexesBerryBordat) {\n AdjacencyList graph = SampleGraphs::berry_bordat();\n vector<set<int>> moplexes = MinimumFillIn::find_moplexes(graph);\n Assert::IsTrue(vector<set<int>> {\n set<int> { 0, 1 },\n set<int> { 2 },\n set<int> { 3 },\n set<int> { 4 },\n set<int> { 6 },\n set<int> { 7 }\n } == moplexes); \n }\n\n TEST_METHOD(FindMinFillBerryBordat) {\n AdjacencyList graph = SampleGraphs::berry_bordat();\n stack<pair<int, int>> edges = MinimumFillIn::minimum_fill_in(graph);\n Assert::AreEqual(2, (int)edges.size());\n Assert::IsTrue(edges.top().first == 4 && edges.top().second == 5 || edges.top().first == 5 && edges.top().second == 6);\n edges.pop();\n Assert::IsTrue(edges.top().first == 4 && edges.top().second == 5 || edges.top().first == 5 && edges.top().second == 6);\n }\n\n TEST_METHOD(MinimumFillInKTests) {\n \/\/4-cycle\n AdjacencyList graph = AdjacencyList(4);\n graph.add_edge(0, 1);\n graph.add_edge(1, 2);\n graph.add_edge(2, 3);\n graph.add_edge(3, 0);\n\n stack<pair<int, int>> result = MinimumFillIn::minimum_fill_in(graph);\n Assert::IsTrue(1 == result.size());\n\n \/\/5-cycle\n graph = AdjacencyList(5);\n graph.add_edge(0, 1);\n graph.add_edge(1, 2);\n graph.add_edge(2, 3);\n graph.add_edge(3, 4);\n graph.add_edge(4, 0);\n\n result = MinimumFillIn::minimum_fill_in(graph);\n Assert::IsTrue(2 == result.size()); \n\n \/\/2 single nodes\n graph = AdjacencyList(2);\n\n result = MinimumFillIn::minimum_fill_in(graph);\n Assert::IsTrue(0 == result.size());\n\n \/\/2 4-cycles\n graph = AdjacencyList(8);\n graph.add_edge(0, 1);\n graph.add_edge(1, 2);\n graph.add_edge(2, 3);\n graph.add_edge(3, 0);\n\n graph.add_edge(4, 5);\n graph.add_edge(5, 6);\n graph.add_edge(6, 7);\n graph.add_edge(7, 4);\n\n result = MinimumFillIn::minimum_fill_in(graph);\n Assert::IsTrue(2 == result.size());\n\n \/\/10 cycle\n graph = AdjacencyList(10);\n graph.add_edge(0, 1);\n graph.add_edge(1, 2);\n graph.add_edge(2, 3);\n graph.add_edge(3, 4);\n graph.add_edge(4, 5);\n graph.add_edge(5, 6);\n graph.add_edge(6, 7);\n graph.add_edge(7, 8);\n graph.add_edge(8, 9);\n graph.add_edge(9, 0);\n\n result = MinimumFillIn::minimum_fill_in(graph);\n Assert::IsTrue(7 == result.size());\n }\n };\n}\n<commit_msg>More minimumFillInTests<commit_after>#include \"stdafx.h\"\n#include \"CppUnitTest.h\"\n#include \"..\/CPPace.Lib\/MinimumFillIn.h\"\n\nusing namespace Microsoft::VisualStudio::CppUnitTestFramework;\n\nnamespace CPPaceTests {\n TEST_CLASS(MinimumFillInTests) {\n public:\n TEST_METHOD(ChordlessPath) {\n AdjacencyList graph(5);\n Assert::IsTrue(MinimumFillIn::is_path_chordless(graph, vector<int> { 0 }));\n\n \/\/ 0-1 2 3 4\n graph.add_edge(0, 1);\n Assert::IsTrue(MinimumFillIn::is_path_chordless(graph, vector<int> { 0 }));\n Assert::IsTrue(MinimumFillIn::is_path_chordless(graph, vector<int> { 0, 1 }));\n\n \/\/ 0-1-2-3-4\n graph.add_edge(1, 2);\n graph.add_edge(3, 4);\n graph.add_edge(2, 3);\n Assert::IsTrue(MinimumFillIn::is_path_chordless(graph, vector<int> { 0, 1, 2, 3, 4 }));\n Assert::IsTrue(MinimumFillIn::is_path_chordless(graph, vector<int> { 4, 3, 2, 1, 0 }));\n\n \/\/ 0 2-3-4\n \/\/ \\_\/\n graph.add_edge(0, 2);\n Assert::IsFalse(MinimumFillIn::is_path_chordless(graph, vector<int> { 0, 1, 2, 3, 4 }));\n Assert::IsFalse(MinimumFillIn::is_path_chordless(graph, vector<int> { 4, 3, 2, 1, 0 }));\n Assert::IsTrue(MinimumFillIn::is_path_chordless(graph, vector<int> { 0, 2, 3, 4 }));\n Assert::IsTrue(MinimumFillIn::is_path_chordless(graph, vector<int> { 4, 3, 2, 0 }));\n\n \/\/ 0 2-3-4\n \/\/ \\_\/ \\_\/\n graph.add_edge(2, 4);\n Assert::IsFalse(MinimumFillIn::is_path_chordless(graph, vector<int> { 0, 2, 3, 4 }));\n Assert::IsFalse(MinimumFillIn::is_path_chordless(graph, vector<int> { 4, 3, 2, 0 }));\n }\n\n TEST_METHOD(FindFourCycle) {\n AdjacencyList graph(5);\n vector<int> cycle;\n Assert::IsFalse(MinimumFillIn::find_four_cycle(graph, cycle));\n\n graph.add_edge(0, 1);\n Assert::IsFalse(MinimumFillIn::find_four_cycle(graph, cycle));\n Assert::AreEqual(0, (int)cycle.size());\n\n graph.add_edge(1, 2);\n Assert::IsFalse(MinimumFillIn::find_four_cycle(graph, cycle));\n Assert::AreEqual(0, (int)cycle.size());\n\n graph.add_edge(2, 3);\n Assert::IsFalse(MinimumFillIn::find_four_cycle(graph, cycle));\n Assert::AreEqual(0, (int)cycle.size());\n\n graph.add_edge(3, 4);\n Assert::IsFalse(MinimumFillIn::find_four_cycle(graph, cycle));\n Assert::AreEqual(0, (int)cycle.size());\n\n graph.add_edge(4, 0);\n Assert::IsFalse(MinimumFillIn::find_four_cycle(graph, cycle));\n Assert::AreEqual(0, (int)cycle.size());\n\n graph.add_edge(3, 0);\n Assert::IsTrue(MinimumFillIn::find_four_cycle(graph, cycle));\n Assert::AreEqual(4, (int)cycle.size());\n\n graph.remove_vertex(0);\n Assert::IsFalse(MinimumFillIn::find_four_cycle(graph, cycle));\n Assert::AreEqual(0, (int)cycle.size());\n\n graph.add_edge(1, 4);\n Assert::IsTrue(MinimumFillIn::find_four_cycle(graph, cycle));\n Assert::AreEqual(4, (int)cycle.size());\n\n graph.add_vertex(0);\n graph.remove_edge(1, 4);\n Assert::IsTrue(MinimumFillIn::find_four_cycle(graph, cycle));\n Assert::AreEqual(4, (int)cycle.size());\n }\n\n TEST_METHOD(FindFourCycleBerryBordat) {\n AdjacencyList graph = SampleGraphs::berry_bordat();\n vector<int> cycle;\n Assert::IsTrue(MinimumFillIn::find_four_cycle(graph, cycle));\n Assert::AreEqual(4, (int)cycle.size());\n\n graph.remove_vertex(5);\n Assert::IsFalse(MinimumFillIn::find_four_cycle(graph, cycle));\n Assert::AreEqual(0, (int)cycle.size());\n }\n\n TEST_METHOD(FindVStar) {\n int v_star;\n AdjacencyList graph(5);\n Assert::IsFalse(MinimumFillIn::find_v_star(graph, 0, 2, set<int>(), v_star));\n\n graph.add_edge(0, 1);\n Assert::IsFalse(MinimumFillIn::find_v_star(graph, 0, 2, set<int>(), v_star));\n\n graph.add_edge(1, 2);\n Assert::IsTrue(MinimumFillIn::find_v_star(graph, 0, 2, set<int>(), v_star));\n Assert::AreEqual(1, v_star);\n\n graph.add_edge(2, 3);\n Assert::IsTrue(MinimumFillIn::find_v_star(graph, 0, 3, set<int>(), v_star));\n Assert::IsTrue(v_star == 1 || v_star == 2);\n\n graph.remove_vertex(2);\n Assert::IsFalse(MinimumFillIn::find_v_star(graph, 0, 2, set<int>(), v_star));\n Assert::IsFalse(MinimumFillIn::find_v_star(graph, 0, 3, set<int>(), v_star));\n\n graph.add_edge(1, 4);\n graph.add_edge(3, 4);\n Assert::IsTrue(MinimumFillIn::find_v_star(graph, 0, 3, set<int>(), v_star));\n Assert::IsTrue(v_star == 4 || v_star == 1);\n\n Assert::IsTrue(MinimumFillIn::find_v_star(graph, 0, 3, set<int>(), v_star));\n Assert::IsTrue(v_star == 4 || v_star == 1);\n\n graph.add_vertex(2);\n\n Assert::IsTrue(MinimumFillIn::find_v_star(graph, 0, 3, set<int>(), v_star));\n Assert::AreEqual(1, v_star);\n\n graph.add_edge(0, 4);\n Assert::IsFalse(MinimumFillIn::find_v_star(graph, 0, 3, set<int>(), v_star));\n\n Assert::IsTrue(MinimumFillIn::find_v_star(graph, 0, 3, set<int> { 4 }, v_star));\n Assert::IsTrue(v_star == 1 || v_star == 2);\n }\n\n TEST_METHOD(FindMoplexesBerryBordat) {\n AdjacencyList graph = SampleGraphs::berry_bordat();\n vector<set<int>> moplexes = MinimumFillIn::find_moplexes(graph);\n Assert::IsTrue(vector<set<int>> {\n set<int> { 0, 1 },\n set<int> { 2 },\n set<int> { 3 },\n set<int> { 4 },\n set<int> { 6 },\n set<int> { 7 }\n } == moplexes); \n }\n\n TEST_METHOD(FindMinFillBerryBordat) {\n AdjacencyList graph = SampleGraphs::berry_bordat();\n stack<pair<int, int>> edges = MinimumFillIn::minimum_fill_in(graph);\n Assert::AreEqual(2, (int)edges.size());\n Assert::IsTrue(edges.top().first == 4 && edges.top().second == 5 || edges.top().first == 5 && edges.top().second == 6);\n edges.pop();\n Assert::IsTrue(edges.top().first == 4 && edges.top().second == 5 || edges.top().first == 5 && edges.top().second == 6);\n }\n\n TEST_METHOD(MinimumFillInKTests) {\n \/\/4-cycle\n AdjacencyList graph = AdjacencyList(4);\n graph.add_edge(0, 1);\n graph.add_edge(1, 2);\n graph.add_edge(2, 3);\n graph.add_edge(3, 0);\n\n stack<pair<int, int>> result = MinimumFillIn::minimum_fill_in(graph);\n Assert::IsTrue(1 == result.size());\n\n \/\/5-cycle\n graph = AdjacencyList(5);\n graph.add_edge(0, 1);\n graph.add_edge(1, 2);\n graph.add_edge(2, 3);\n graph.add_edge(3, 4);\n graph.add_edge(4, 0);\n\n result = MinimumFillIn::minimum_fill_in(graph);\n Assert::IsTrue(2 == result.size()); \n\n \/\/2 single nodes\n graph = AdjacencyList(2);\n\n result = MinimumFillIn::minimum_fill_in(graph);\n Assert::IsTrue(0 == result.size());\n\n \/\/2 4-cycles\n graph = AdjacencyList(8);\n graph.add_edge(0, 1);\n graph.add_edge(1, 2);\n graph.add_edge(2, 3);\n graph.add_edge(3, 0);\n\n graph.add_edge(4, 5);\n graph.add_edge(5, 6);\n graph.add_edge(6, 7);\n graph.add_edge(7, 4);\n\n result = MinimumFillIn::minimum_fill_in(graph);\n Assert::IsTrue(2 == result.size());\n\n \/\/10 cycle\n graph = AdjacencyList(10);\n graph.add_edge(0, 1);\n graph.add_edge(1, 2);\n graph.add_edge(2, 3);\n graph.add_edge(3, 4);\n graph.add_edge(4, 5);\n graph.add_edge(5, 6);\n graph.add_edge(6, 7);\n graph.add_edge(7, 8);\n graph.add_edge(8, 9);\n graph.add_edge(9, 0);\n\n result = MinimumFillIn::minimum_fill_in(graph);\n Assert::IsTrue(7 == result.size());\n\n \/\/2 combined 4-cycles. Solvable with one.\n graph = AdjacencyList(6);\n graph.add_edge(0, 1);\n graph.add_edge(1, 4);\n graph.add_edge(0, 2);\n graph.add_edge(0, 3);\n graph.add_edge(3, 4);\n\n result = MinimumFillIn::minimum_fill_in(graph);\n Assert::IsTrue(1 == result.size());\n\n \/\/10 combined 4-cycles. Solvable with one\n graph = AdjacencyList(12);\n graph.add_edge(0, 1);\n graph.add_edge(0, 2);\n graph.add_edge(0, 3);\n graph.add_edge(0, 5);\n graph.add_edge(0, 6);\n graph.add_edge(0, 7);\n graph.add_edge(0, 8);\n graph.add_edge(0, 9);\n graph.add_edge(0, 10);\n graph.add_edge(0, 11);\n graph.add_edge(4, 1);\n graph.add_edge(4, 2);\n graph.add_edge(4, 3);\n graph.add_edge(4, 5);\n graph.add_edge(4, 6);\n graph.add_edge(4, 7);\n graph.add_edge(4, 8);\n graph.add_edge(4, 9);\n graph.add_edge(4, 10);\n graph.add_edge(4, 11);\n\n result = MinimumFillIn::minimum_fill_in(graph);\n Assert::IsTrue(1 == result.size());\n }\n };\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2011 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"base\/format_macros.h\"\n#include \"base\/path_service.h\"\n#include \"base\/stringprintf.h\"\n#include \"base\/utf_string_conversions.h\"\n#include \"chrome\/browser\/autocomplete\/autocomplete.h\"\n#include \"chrome\/browser\/autocomplete\/autocomplete_edit.h\"\n#include \"chrome\/browser\/autocomplete\/autocomplete_match.h\"\n#include \"chrome\/browser\/autocomplete\/autocomplete_popup_model.h\"\n#include \"chrome\/browser\/extensions\/extension_browsertest.h\"\n#include \"chrome\/browser\/extensions\/extension_service.h\"\n#include \"chrome\/browser\/extensions\/unpacked_installer.h\"\n#include \"chrome\/browser\/history\/history.h\"\n#include \"chrome\/browser\/profiles\/profile.h\"\n#include \"chrome\/browser\/tabs\/tab_strip_model.h\"\n#include \"chrome\/browser\/ui\/browser.h\"\n#include \"chrome\/browser\/ui\/browser_window.h\"\n#include \"chrome\/browser\/ui\/omnibox\/location_bar.h\"\n#include \"chrome\/browser\/ui\/omnibox\/omnibox_view.h\"\n#include \"chrome\/common\/chrome_paths.h\"\n#include \"chrome\/common\/url_constants.h\"\n#include \"chrome\/test\/base\/in_process_browser_test.h\"\n#include \"chrome\/test\/base\/ui_test_utils.h\"\n#include \"content\/browser\/tab_contents\/tab_contents.h\"\n#include \"content\/public\/browser\/notification_service.h\"\n#include \"content\/public\/browser\/notification_types.h\"\n#include \"testing\/gtest\/include\/gtest\/gtest.h\"\n\n\/\/ Autocomplete test is flaky on ChromeOS.\n\/\/ http:\/\/crbug.com\/52928\n#if defined(OS_CHROMEOS)\n#define MAYBE_Autocomplete FLAKY_Autocomplete\n#else\n#define MAYBE_Autocomplete Autocomplete\n#endif\n\n\nnamespace {\n\nstring16 AutocompleteResultAsString(const AutocompleteResult& result) {\n std::string output(base::StringPrintf(\"{%\" PRIuS \"} \", result.size()));\n for (size_t i = 0; i < result.size(); ++i) {\n AutocompleteMatch match = result.match_at(i);\n std::string provider_name = match.provider->name();\n output.append(base::StringPrintf(\"[\\\"%s\\\" by \\\"%s\\\"] \",\n UTF16ToUTF8(match.contents).c_str(),\n provider_name.c_str()));\n }\n return UTF8ToUTF16(output);\n}\n\n} \/\/ namespace\n\nclass AutocompleteBrowserTest : public ExtensionBrowserTest {\n protected:\n LocationBar* GetLocationBar() const {\n return browser()->window()->GetLocationBar();\n }\n\n AutocompleteController* GetAutocompleteController() const {\n return GetLocationBar()->location_entry()->model()->popup_model()->\n autocomplete_controller();\n }\n};\n\n#if defined(OS_WIN) || defined(OS_LINUX)\n#define MAYBE_Basic FLAKY_Basic\n#else\n#define MAYBE_Basic Basic\n#endif\nIN_PROC_BROWSER_TEST_F(AutocompleteBrowserTest, MAYBE_Basic) {\n LocationBar* location_bar = GetLocationBar();\n\n EXPECT_TRUE(location_bar->GetInputString().empty());\n EXPECT_EQ(UTF8ToUTF16(chrome::kAboutBlankURL),\n location_bar->location_entry()->GetText());\n \/\/ TODO(phajdan.jr): check state of IsSelectAll when it's consistent across\n \/\/ platforms.\n\n location_bar->FocusLocation(true);\n\n EXPECT_TRUE(location_bar->GetInputString().empty());\n EXPECT_EQ(UTF8ToUTF16(chrome::kAboutBlankURL),\n location_bar->location_entry()->GetText());\n EXPECT_TRUE(location_bar->location_entry()->IsSelectAll());\n\n location_bar->location_entry()->SetUserText(ASCIIToUTF16(\"chrome\"));\n\n EXPECT_TRUE(location_bar->GetInputString().empty());\n EXPECT_EQ(ASCIIToUTF16(\"chrome\"), location_bar->location_entry()->GetText());\n EXPECT_FALSE(location_bar->location_entry()->IsSelectAll());\n\n location_bar->location_entry()->RevertAll();\n\n EXPECT_TRUE(location_bar->GetInputString().empty());\n EXPECT_EQ(UTF8ToUTF16(chrome::kAboutBlankURL),\n location_bar->location_entry()->GetText());\n EXPECT_FALSE(location_bar->location_entry()->IsSelectAll());\n\n location_bar->location_entry()->SetUserText(ASCIIToUTF16(\"chrome\"));\n location_bar->Revert();\n\n EXPECT_TRUE(location_bar->GetInputString().empty());\n EXPECT_EQ(UTF8ToUTF16(chrome::kAboutBlankURL),\n location_bar->location_entry()->GetText());\n EXPECT_FALSE(location_bar->location_entry()->IsSelectAll());\n}\n\nIN_PROC_BROWSER_TEST_F(AutocompleteBrowserTest, MAYBE_Autocomplete) {\n \/\/ The results depend on the history backend being loaded. Make sure it is\n \/\/ loaded so that the autocomplete results are consistent.\n ui_test_utils::WaitForHistoryToLoad(browser());\n\n LocationBar* location_bar = GetLocationBar();\n AutocompleteController* autocomplete_controller = GetAutocompleteController();\n\n {\n autocomplete_controller->Start(\n ASCIIToUTF16(\"chrome\"), string16(), true, false, true,\n AutocompleteInput::SYNCHRONOUS_MATCHES);\n\n EXPECT_TRUE(autocomplete_controller->done());\n EXPECT_TRUE(location_bar->GetInputString().empty());\n EXPECT_TRUE(location_bar->location_entry()->GetText().empty());\n EXPECT_TRUE(location_bar->location_entry()->IsSelectAll());\n const AutocompleteResult& result = autocomplete_controller->result();\n \/\/ We get two matches because we have a provider for extension apps and the\n \/\/ Chrome Web Store is a built-in Extension app. For this test, we only care\n \/\/ about the other match existing.\n ASSERT_GE(result.size(), 1U) << AutocompleteResultAsString(result);\n AutocompleteMatch match = result.match_at(0);\n EXPECT_EQ(AutocompleteMatch::SEARCH_WHAT_YOU_TYPED, match.type);\n EXPECT_FALSE(match.deletable);\n }\n\n {\n location_bar->Revert();\n\n EXPECT_TRUE(location_bar->GetInputString().empty());\n EXPECT_EQ(UTF8ToUTF16(chrome::kAboutBlankURL),\n location_bar->location_entry()->GetText());\n EXPECT_FALSE(location_bar->location_entry()->IsSelectAll());\n const AutocompleteResult& result = autocomplete_controller->result();\n EXPECT_TRUE(result.empty()) << AutocompleteResultAsString(result);\n }\n}\n\nIN_PROC_BROWSER_TEST_F(AutocompleteBrowserTest, TabAwayRevertSelect) {\n \/\/ http:\/\/code.google.com\/p\/chromium\/issues\/detail?id=38385\n \/\/ Make sure that tabbing away from an empty omnibar causes a revert\n \/\/ and select all.\n LocationBar* location_bar = GetLocationBar();\n EXPECT_EQ(UTF8ToUTF16(chrome::kAboutBlankURL),\n location_bar->location_entry()->GetText());\n location_bar->location_entry()->SetUserText(string16());\n ui_test_utils::WindowedNotificationObserver observer(\n content::NOTIFICATION_LOAD_STOP,\n content::NotificationService::AllSources());\n browser()->AddSelectedTabWithURL(GURL(chrome::kAboutBlankURL),\n content::PAGE_TRANSITION_START_PAGE);\n observer.Wait();\n EXPECT_EQ(UTF8ToUTF16(chrome::kAboutBlankURL),\n location_bar->location_entry()->GetText());\n browser()->CloseTab();\n EXPECT_EQ(UTF8ToUTF16(chrome::kAboutBlankURL),\n location_bar->location_entry()->GetText());\n EXPECT_TRUE(location_bar->location_entry()->IsSelectAll());\n}\n\nIN_PROC_BROWSER_TEST_F(AutocompleteBrowserTest, FocusSearch) {\n LocationBar* location_bar = GetLocationBar();\n\n \/\/ Focus search when omnibox is blank\n {\n EXPECT_TRUE(location_bar->GetInputString().empty());\n EXPECT_EQ(UTF8ToUTF16(chrome::kAboutBlankURL),\n location_bar->location_entry()->GetText());\n\n location_bar->FocusSearch();\n EXPECT_TRUE(location_bar->GetInputString().empty());\n EXPECT_EQ(ASCIIToUTF16(\"?\"), location_bar->location_entry()->GetText());\n\n size_t selection_start, selection_end;\n location_bar->location_entry()->GetSelectionBounds(&selection_start,\n &selection_end);\n EXPECT_EQ(1U, selection_start);\n EXPECT_EQ(1U, selection_end);\n }\n\n \/\/ Focus search when omnibox is _not_ alread in forced query mode.\n {\n location_bar->location_entry()->SetUserText(ASCIIToUTF16(\"foo\"));\n EXPECT_TRUE(location_bar->GetInputString().empty());\n EXPECT_EQ(ASCIIToUTF16(\"foo\"), location_bar->location_entry()->GetText());\n\n location_bar->FocusSearch();\n EXPECT_TRUE(location_bar->GetInputString().empty());\n EXPECT_EQ(ASCIIToUTF16(\"?\"), location_bar->location_entry()->GetText());\n\n size_t selection_start, selection_end;\n location_bar->location_entry()->GetSelectionBounds(&selection_start,\n &selection_end);\n EXPECT_EQ(1U, selection_start);\n EXPECT_EQ(1U, selection_end);\n }\n\n \/\/ Focus search when omnibox _is_ already in forced query mode, but no query\n \/\/ has been typed.\n {\n location_bar->location_entry()->SetUserText(ASCIIToUTF16(\"?\"));\n EXPECT_TRUE(location_bar->GetInputString().empty());\n EXPECT_EQ(ASCIIToUTF16(\"?\"), location_bar->location_entry()->GetText());\n\n location_bar->FocusSearch();\n EXPECT_TRUE(location_bar->GetInputString().empty());\n EXPECT_EQ(ASCIIToUTF16(\"?\"), location_bar->location_entry()->GetText());\n\n size_t selection_start, selection_end;\n location_bar->location_entry()->GetSelectionBounds(&selection_start,\n &selection_end);\n EXPECT_EQ(1U, selection_start);\n EXPECT_EQ(1U, selection_end);\n }\n\n \/\/ Focus search when omnibox _is_ already in forced query mode, and some query\n \/\/ has been typed.\n {\n location_bar->location_entry()->SetUserText(ASCIIToUTF16(\"?foo\"));\n EXPECT_TRUE(location_bar->GetInputString().empty());\n EXPECT_EQ(ASCIIToUTF16(\"?foo\"), location_bar->location_entry()->GetText());\n\n location_bar->FocusSearch();\n EXPECT_TRUE(location_bar->GetInputString().empty());\n EXPECT_EQ(ASCIIToUTF16(\"?foo\"), location_bar->location_entry()->GetText());\n\n size_t selection_start, selection_end;\n location_bar->location_entry()->GetSelectionBounds(&selection_start,\n &selection_end);\n EXPECT_EQ(1U, std::min(selection_start, selection_end));\n EXPECT_EQ(4U, std::max(selection_start, selection_end));\n }\n\n \/\/ Focus search when omnibox is in forced query mode with leading whitespace.\n {\n location_bar->location_entry()->SetUserText(ASCIIToUTF16(\" ?foo\"));\n EXPECT_TRUE(location_bar->GetInputString().empty());\n EXPECT_EQ(ASCIIToUTF16(\" ?foo\"),\n location_bar->location_entry()->GetText());\n\n location_bar->FocusSearch();\n EXPECT_TRUE(location_bar->GetInputString().empty());\n EXPECT_EQ(ASCIIToUTF16(\" ?foo\"),\n location_bar->location_entry()->GetText());\n\n size_t selection_start, selection_end;\n location_bar->location_entry()->GetSelectionBounds(&selection_start,\n &selection_end);\n EXPECT_EQ(4U, std::min(selection_start, selection_end));\n EXPECT_EQ(7U, std::max(selection_start, selection_end));\n }\n}\n\nIN_PROC_BROWSER_TEST_F(AutocompleteBrowserTest, ExtensionAppProvider) {\n ExtensionService* service = browser()->profile()->GetExtensionService();\n size_t extension_count = service->extensions()->size();\n\n FilePath test_dir;\n ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &test_dir));\n \/\/ Load a packaged app.\n extensions::UnpackedInstaller::Create(service)->Load(\n test_dir.AppendASCII(\"extensions\").AppendASCII(\"packaged_app\"));\n WaitForExtensionLoad();\n \/\/ Load a hosted app.\n extensions::UnpackedInstaller::Create(service)->Load(\n test_dir.AppendASCII(\"extensions\").AppendASCII(\"app\"));\n WaitForExtensionLoad();\n ASSERT_EQ(extension_count + 2U, service->extensions()->size());\n\n \/\/ The results depend on the history backend being loaded. Make sure it is\n \/\/ loaded so that the autocomplete results are consistent.\n ui_test_utils::WaitForHistoryToLoad(browser());\n\n LocationBar* location_bar = GetLocationBar();\n AutocompleteController* autocomplete_controller = GetAutocompleteController();\n\n \/\/ Try out the packaged app.\n {\n autocomplete_controller->Start(\n ASCIIToUTF16(\"Packaged App Test\"), string16(), true, false, true,\n AutocompleteInput::SYNCHRONOUS_MATCHES);\n\n EXPECT_TRUE(autocomplete_controller->done());\n EXPECT_TRUE(location_bar->GetInputString().empty());\n EXPECT_TRUE(location_bar->location_entry()->GetText().empty());\n EXPECT_TRUE(location_bar->location_entry()->IsSelectAll());\n const AutocompleteResult& result = autocomplete_controller->result();\n EXPECT_GT(result.size(), 1U) << AutocompleteResultAsString(result);\n AutocompleteMatch match = result.match_at(0);\n EXPECT_EQ(ASCIIToUTF16(\"Packaged App Test\"), match.contents);\n EXPECT_EQ(AutocompleteMatch::EXTENSION_APP, match.type);\n EXPECT_FALSE(match.deletable);\n location_bar->AcceptInput();\n }\n\n browser()->NewTab();\n\n \/\/ Try out the hosted app.\n {\n autocomplete_controller->Start(\n ASCIIToUTF16(\"App Test\"), string16(), true, false, true,\n AutocompleteInput::SYNCHRONOUS_MATCHES);\n\n EXPECT_TRUE(autocomplete_controller->done());\n EXPECT_TRUE(location_bar->GetInputString().empty());\n EXPECT_TRUE(location_bar->location_entry()->GetText().empty());\n EXPECT_TRUE(location_bar->location_entry()->IsSelectAll());\n const AutocompleteResult& result = autocomplete_controller->result();\n \/\/ 'App test' is also a substring of extension 'Packaged App Test'.\n EXPECT_GT(result.size(), 2U) << AutocompleteResultAsString(result);\n AutocompleteMatch match = result.match_at(0);\n EXPECT_EQ(ASCIIToUTF16(\"App Test\"), match.contents);\n EXPECT_EQ(AutocompleteMatch::EXTENSION_APP, match.type);\n EXPECT_FALSE(match.deletable);\n location_bar->AcceptInput();\n }\n}\n<commit_msg>Mark AutocompleteBrowserTest.FocusSearch flaky on Windows and Linux. (reland)<commit_after>\/\/ Copyright (c) 2011 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"base\/format_macros.h\"\n#include \"base\/path_service.h\"\n#include \"base\/stringprintf.h\"\n#include \"base\/utf_string_conversions.h\"\n#include \"chrome\/browser\/autocomplete\/autocomplete.h\"\n#include \"chrome\/browser\/autocomplete\/autocomplete_edit.h\"\n#include \"chrome\/browser\/autocomplete\/autocomplete_match.h\"\n#include \"chrome\/browser\/autocomplete\/autocomplete_popup_model.h\"\n#include \"chrome\/browser\/extensions\/extension_browsertest.h\"\n#include \"chrome\/browser\/extensions\/extension_service.h\"\n#include \"chrome\/browser\/extensions\/unpacked_installer.h\"\n#include \"chrome\/browser\/history\/history.h\"\n#include \"chrome\/browser\/profiles\/profile.h\"\n#include \"chrome\/browser\/tabs\/tab_strip_model.h\"\n#include \"chrome\/browser\/ui\/browser.h\"\n#include \"chrome\/browser\/ui\/browser_window.h\"\n#include \"chrome\/browser\/ui\/omnibox\/location_bar.h\"\n#include \"chrome\/browser\/ui\/omnibox\/omnibox_view.h\"\n#include \"chrome\/common\/chrome_paths.h\"\n#include \"chrome\/common\/url_constants.h\"\n#include \"chrome\/test\/base\/in_process_browser_test.h\"\n#include \"chrome\/test\/base\/ui_test_utils.h\"\n#include \"content\/browser\/tab_contents\/tab_contents.h\"\n#include \"content\/public\/browser\/notification_service.h\"\n#include \"content\/public\/browser\/notification_types.h\"\n#include \"testing\/gtest\/include\/gtest\/gtest.h\"\n\n\/\/ Autocomplete test is flaky on ChromeOS.\n\/\/ http:\/\/crbug.com\/52928\n#if defined(OS_CHROMEOS)\n#define MAYBE_Autocomplete FLAKY_Autocomplete\n#else\n#define MAYBE_Autocomplete Autocomplete\n#endif\n\n\nnamespace {\n\nstring16 AutocompleteResultAsString(const AutocompleteResult& result) {\n std::string output(base::StringPrintf(\"{%\" PRIuS \"} \", result.size()));\n for (size_t i = 0; i < result.size(); ++i) {\n AutocompleteMatch match = result.match_at(i);\n std::string provider_name = match.provider->name();\n output.append(base::StringPrintf(\"[\\\"%s\\\" by \\\"%s\\\"] \",\n UTF16ToUTF8(match.contents).c_str(),\n provider_name.c_str()));\n }\n return UTF8ToUTF16(output);\n}\n\n} \/\/ namespace\n\nclass AutocompleteBrowserTest : public ExtensionBrowserTest {\n protected:\n LocationBar* GetLocationBar() const {\n return browser()->window()->GetLocationBar();\n }\n\n AutocompleteController* GetAutocompleteController() const {\n return GetLocationBar()->location_entry()->model()->popup_model()->\n autocomplete_controller();\n }\n};\n\n#if defined(OS_WIN) || defined(OS_LINUX)\n#define MAYBE_Basic FLAKY_Basic\n#else\n#define MAYBE_Basic Basic\n#endif\nIN_PROC_BROWSER_TEST_F(AutocompleteBrowserTest, MAYBE_Basic) {\n LocationBar* location_bar = GetLocationBar();\n\n EXPECT_TRUE(location_bar->GetInputString().empty());\n EXPECT_EQ(UTF8ToUTF16(chrome::kAboutBlankURL),\n location_bar->location_entry()->GetText());\n \/\/ TODO(phajdan.jr): check state of IsSelectAll when it's consistent across\n \/\/ platforms.\n\n location_bar->FocusLocation(true);\n\n EXPECT_TRUE(location_bar->GetInputString().empty());\n EXPECT_EQ(UTF8ToUTF16(chrome::kAboutBlankURL),\n location_bar->location_entry()->GetText());\n EXPECT_TRUE(location_bar->location_entry()->IsSelectAll());\n\n location_bar->location_entry()->SetUserText(ASCIIToUTF16(\"chrome\"));\n\n EXPECT_TRUE(location_bar->GetInputString().empty());\n EXPECT_EQ(ASCIIToUTF16(\"chrome\"), location_bar->location_entry()->GetText());\n EXPECT_FALSE(location_bar->location_entry()->IsSelectAll());\n\n location_bar->location_entry()->RevertAll();\n\n EXPECT_TRUE(location_bar->GetInputString().empty());\n EXPECT_EQ(UTF8ToUTF16(chrome::kAboutBlankURL),\n location_bar->location_entry()->GetText());\n EXPECT_FALSE(location_bar->location_entry()->IsSelectAll());\n\n location_bar->location_entry()->SetUserText(ASCIIToUTF16(\"chrome\"));\n location_bar->Revert();\n\n EXPECT_TRUE(location_bar->GetInputString().empty());\n EXPECT_EQ(UTF8ToUTF16(chrome::kAboutBlankURL),\n location_bar->location_entry()->GetText());\n EXPECT_FALSE(location_bar->location_entry()->IsSelectAll());\n}\n\nIN_PROC_BROWSER_TEST_F(AutocompleteBrowserTest, MAYBE_Autocomplete) {\n \/\/ The results depend on the history backend being loaded. Make sure it is\n \/\/ loaded so that the autocomplete results are consistent.\n ui_test_utils::WaitForHistoryToLoad(browser());\n\n LocationBar* location_bar = GetLocationBar();\n AutocompleteController* autocomplete_controller = GetAutocompleteController();\n\n {\n autocomplete_controller->Start(\n ASCIIToUTF16(\"chrome\"), string16(), true, false, true,\n AutocompleteInput::SYNCHRONOUS_MATCHES);\n\n EXPECT_TRUE(autocomplete_controller->done());\n EXPECT_TRUE(location_bar->GetInputString().empty());\n EXPECT_TRUE(location_bar->location_entry()->GetText().empty());\n EXPECT_TRUE(location_bar->location_entry()->IsSelectAll());\n const AutocompleteResult& result = autocomplete_controller->result();\n \/\/ We get two matches because we have a provider for extension apps and the\n \/\/ Chrome Web Store is a built-in Extension app. For this test, we only care\n \/\/ about the other match existing.\n ASSERT_GE(result.size(), 1U) << AutocompleteResultAsString(result);\n AutocompleteMatch match = result.match_at(0);\n EXPECT_EQ(AutocompleteMatch::SEARCH_WHAT_YOU_TYPED, match.type);\n EXPECT_FALSE(match.deletable);\n }\n\n {\n location_bar->Revert();\n\n EXPECT_TRUE(location_bar->GetInputString().empty());\n EXPECT_EQ(UTF8ToUTF16(chrome::kAboutBlankURL),\n location_bar->location_entry()->GetText());\n EXPECT_FALSE(location_bar->location_entry()->IsSelectAll());\n const AutocompleteResult& result = autocomplete_controller->result();\n EXPECT_TRUE(result.empty()) << AutocompleteResultAsString(result);\n }\n}\n\nIN_PROC_BROWSER_TEST_F(AutocompleteBrowserTest, TabAwayRevertSelect) {\n \/\/ http:\/\/code.google.com\/p\/chromium\/issues\/detail?id=38385\n \/\/ Make sure that tabbing away from an empty omnibar causes a revert\n \/\/ and select all.\n LocationBar* location_bar = GetLocationBar();\n EXPECT_EQ(UTF8ToUTF16(chrome::kAboutBlankURL),\n location_bar->location_entry()->GetText());\n location_bar->location_entry()->SetUserText(string16());\n ui_test_utils::WindowedNotificationObserver observer(\n content::NOTIFICATION_LOAD_STOP,\n content::NotificationService::AllSources());\n browser()->AddSelectedTabWithURL(GURL(chrome::kAboutBlankURL),\n content::PAGE_TRANSITION_START_PAGE);\n observer.Wait();\n EXPECT_EQ(UTF8ToUTF16(chrome::kAboutBlankURL),\n location_bar->location_entry()->GetText());\n browser()->CloseTab();\n EXPECT_EQ(UTF8ToUTF16(chrome::kAboutBlankURL),\n location_bar->location_entry()->GetText());\n EXPECT_TRUE(location_bar->location_entry()->IsSelectAll());\n}\n\n#if defined(OS_WIN) || defined(OS_LINUX)\n\/\/ http:\/\/crbug.com\/104307\n#define MAYBE_FocusSearch FLAKY_FocusSearch\n#else\n#define MAYBE_FocusSearch FocusSearch\n#endif\nIN_PROC_BROWSER_TEST_F(AutocompleteBrowserTest, MAYBE_FocusSearch) {\n LocationBar* location_bar = GetLocationBar();\n\n \/\/ Focus search when omnibox is blank\n {\n EXPECT_TRUE(location_bar->GetInputString().empty());\n EXPECT_EQ(UTF8ToUTF16(chrome::kAboutBlankURL),\n location_bar->location_entry()->GetText());\n\n location_bar->FocusSearch();\n EXPECT_TRUE(location_bar->GetInputString().empty());\n EXPECT_EQ(ASCIIToUTF16(\"?\"), location_bar->location_entry()->GetText());\n\n size_t selection_start, selection_end;\n location_bar->location_entry()->GetSelectionBounds(&selection_start,\n &selection_end);\n EXPECT_EQ(1U, selection_start);\n EXPECT_EQ(1U, selection_end);\n }\n\n \/\/ Focus search when omnibox is _not_ alread in forced query mode.\n {\n location_bar->location_entry()->SetUserText(ASCIIToUTF16(\"foo\"));\n EXPECT_TRUE(location_bar->GetInputString().empty());\n EXPECT_EQ(ASCIIToUTF16(\"foo\"), location_bar->location_entry()->GetText());\n\n location_bar->FocusSearch();\n EXPECT_TRUE(location_bar->GetInputString().empty());\n EXPECT_EQ(ASCIIToUTF16(\"?\"), location_bar->location_entry()->GetText());\n\n size_t selection_start, selection_end;\n location_bar->location_entry()->GetSelectionBounds(&selection_start,\n &selection_end);\n EXPECT_EQ(1U, selection_start);\n EXPECT_EQ(1U, selection_end);\n }\n\n \/\/ Focus search when omnibox _is_ already in forced query mode, but no query\n \/\/ has been typed.\n {\n location_bar->location_entry()->SetUserText(ASCIIToUTF16(\"?\"));\n EXPECT_TRUE(location_bar->GetInputString().empty());\n EXPECT_EQ(ASCIIToUTF16(\"?\"), location_bar->location_entry()->GetText());\n\n location_bar->FocusSearch();\n EXPECT_TRUE(location_bar->GetInputString().empty());\n EXPECT_EQ(ASCIIToUTF16(\"?\"), location_bar->location_entry()->GetText());\n\n size_t selection_start, selection_end;\n location_bar->location_entry()->GetSelectionBounds(&selection_start,\n &selection_end);\n EXPECT_EQ(1U, selection_start);\n EXPECT_EQ(1U, selection_end);\n }\n\n \/\/ Focus search when omnibox _is_ already in forced query mode, and some query\n \/\/ has been typed.\n {\n location_bar->location_entry()->SetUserText(ASCIIToUTF16(\"?foo\"));\n EXPECT_TRUE(location_bar->GetInputString().empty());\n EXPECT_EQ(ASCIIToUTF16(\"?foo\"), location_bar->location_entry()->GetText());\n\n location_bar->FocusSearch();\n EXPECT_TRUE(location_bar->GetInputString().empty());\n EXPECT_EQ(ASCIIToUTF16(\"?foo\"), location_bar->location_entry()->GetText());\n\n size_t selection_start, selection_end;\n location_bar->location_entry()->GetSelectionBounds(&selection_start,\n &selection_end);\n EXPECT_EQ(1U, std::min(selection_start, selection_end));\n EXPECT_EQ(4U, std::max(selection_start, selection_end));\n }\n\n \/\/ Focus search when omnibox is in forced query mode with leading whitespace.\n {\n location_bar->location_entry()->SetUserText(ASCIIToUTF16(\" ?foo\"));\n EXPECT_TRUE(location_bar->GetInputString().empty());\n EXPECT_EQ(ASCIIToUTF16(\" ?foo\"),\n location_bar->location_entry()->GetText());\n\n location_bar->FocusSearch();\n EXPECT_TRUE(location_bar->GetInputString().empty());\n EXPECT_EQ(ASCIIToUTF16(\" ?foo\"),\n location_bar->location_entry()->GetText());\n\n size_t selection_start, selection_end;\n location_bar->location_entry()->GetSelectionBounds(&selection_start,\n &selection_end);\n EXPECT_EQ(4U, std::min(selection_start, selection_end));\n EXPECT_EQ(7U, std::max(selection_start, selection_end));\n }\n}\n\nIN_PROC_BROWSER_TEST_F(AutocompleteBrowserTest, ExtensionAppProvider) {\n ExtensionService* service = browser()->profile()->GetExtensionService();\n size_t extension_count = service->extensions()->size();\n\n FilePath test_dir;\n ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &test_dir));\n \/\/ Load a packaged app.\n extensions::UnpackedInstaller::Create(service)->Load(\n test_dir.AppendASCII(\"extensions\").AppendASCII(\"packaged_app\"));\n WaitForExtensionLoad();\n \/\/ Load a hosted app.\n extensions::UnpackedInstaller::Create(service)->Load(\n test_dir.AppendASCII(\"extensions\").AppendASCII(\"app\"));\n WaitForExtensionLoad();\n ASSERT_EQ(extension_count + 2U, service->extensions()->size());\n\n \/\/ The results depend on the history backend being loaded. Make sure it is\n \/\/ loaded so that the autocomplete results are consistent.\n ui_test_utils::WaitForHistoryToLoad(browser());\n\n LocationBar* location_bar = GetLocationBar();\n AutocompleteController* autocomplete_controller = GetAutocompleteController();\n\n \/\/ Try out the packaged app.\n {\n autocomplete_controller->Start(\n ASCIIToUTF16(\"Packaged App Test\"), string16(), true, false, true,\n AutocompleteInput::SYNCHRONOUS_MATCHES);\n\n EXPECT_TRUE(autocomplete_controller->done());\n EXPECT_TRUE(location_bar->GetInputString().empty());\n EXPECT_TRUE(location_bar->location_entry()->GetText().empty());\n EXPECT_TRUE(location_bar->location_entry()->IsSelectAll());\n const AutocompleteResult& result = autocomplete_controller->result();\n EXPECT_GT(result.size(), 1U) << AutocompleteResultAsString(result);\n AutocompleteMatch match = result.match_at(0);\n EXPECT_EQ(ASCIIToUTF16(\"Packaged App Test\"), match.contents);\n EXPECT_EQ(AutocompleteMatch::EXTENSION_APP, match.type);\n EXPECT_FALSE(match.deletable);\n location_bar->AcceptInput();\n }\n\n browser()->NewTab();\n\n \/\/ Try out the hosted app.\n {\n autocomplete_controller->Start(\n ASCIIToUTF16(\"App Test\"), string16(), true, false, true,\n AutocompleteInput::SYNCHRONOUS_MATCHES);\n\n EXPECT_TRUE(autocomplete_controller->done());\n EXPECT_TRUE(location_bar->GetInputString().empty());\n EXPECT_TRUE(location_bar->location_entry()->GetText().empty());\n EXPECT_TRUE(location_bar->location_entry()->IsSelectAll());\n const AutocompleteResult& result = autocomplete_controller->result();\n \/\/ 'App test' is also a substring of extension 'Packaged App Test'.\n EXPECT_GT(result.size(), 2U) << AutocompleteResultAsString(result);\n AutocompleteMatch match = result.match_at(0);\n EXPECT_EQ(ASCIIToUTF16(\"App Test\"), match.contents);\n EXPECT_EQ(AutocompleteMatch::EXTENSION_APP, match.type);\n EXPECT_FALSE(match.deletable);\n location_bar->AcceptInput();\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include <EGL\/egl.h>\n\n#include \"build\/build_config.h\"\n#if defined(OS_LINUX)\n#include \"app\/x11_util.h\"\n#define EGL_HAS_PBUFFERS 1\n#endif\n#include \"base\/logging.h\"\n#include \"base\/scoped_ptr.h\"\n#include \"app\/gfx\/gl\/gl_bindings.h\"\n#include \"app\/gfx\/gl\/gl_context_egl.h\"\n\nnamespace gfx {\n\nnamespace {\n\n\/\/ The EGL configuration to use.\nEGLDisplay g_display;\nEGLConfig g_config;\n\n\/\/ Returns the last EGL error as a string.\nconst char* GetLastEGLErrorString() {\n EGLint error = eglGetError();\n switch (error) {\n case EGL_SUCCESS:\n return \"EGL_SUCCESS\";\n case EGL_BAD_ACCESS:\n return \"EGL_BAD_ACCESS\";\n case EGL_BAD_ALLOC:\n return \"EGL_BAD_ALLOC\";\n case EGL_BAD_ATTRIBUTE:\n return \"EGL_BAD_ATTRIBUTE\";\n case EGL_BAD_CONTEXT:\n return \"EGL_BAD_CONTEXT\";\n case EGL_BAD_CONFIG:\n return \"EGL_BAD_CONFIG\";\n case EGL_BAD_CURRENT_SURFACE:\n return \"EGL_BAD_CURRENT_SURFACE\";\n case EGL_BAD_DISPLAY:\n return \"EGL_BAD_DISPLAY\";\n case EGL_BAD_SURFACE:\n return \"EGL_BAD_SURFACE\";\n case EGL_BAD_MATCH:\n return \"EGL_BAD_MATCH\";\n case EGL_BAD_PARAMETER:\n return \"EGL_BAD_PARAMETER\";\n case EGL_BAD_NATIVE_PIXMAP:\n return \"EGL_BAD_NATIVE_PIXMAP\";\n case EGL_BAD_NATIVE_WINDOW:\n return \"EGL_BAD_NATIVE_WINDOW\";\n default:\n return \"UNKNOWN\";\n }\n}\n} \/\/ namespace anonymous\n\nbool BaseEGLContext::InitializeOneOff() {\n static bool initialized = false;\n if (initialized)\n return true;\n\n#ifdef OS_LINUX\n EGLNativeDisplayType native_display = x11_util::GetXDisplay();\n#else\n EGLNativeDisplayType native_display = EGL_DEFAULT_DISPLAY;\n#endif\n g_display = eglGetDisplay(native_display);\n if (!g_display) {\n LOG(ERROR) << \"eglGetDisplay failed with error \" << GetLastEGLErrorString();\n return false;\n }\n\n if (!eglInitialize(g_display, NULL, NULL)) {\n LOG(ERROR) << \"eglInitialize failed with error \" << GetLastEGLErrorString();\n return false;\n }\n\n \/\/ Choose an EGL configuration.\n static const EGLint kConfigAttribs[] = {\n EGL_BUFFER_SIZE, 32,\n EGL_ALPHA_SIZE, 8,\n EGL_BLUE_SIZE, 8,\n EGL_RED_SIZE, 8,\n EGL_DEPTH_SIZE, 16,\n EGL_STENCIL_SIZE, 8,\n EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT,\n#ifdef EGL_HAS_PBUFFERS\n EGL_SURFACE_TYPE, EGL_WINDOW_BIT | EGL_PBUFFER_BIT,\n#else\n EGL_SURFACE_TYPE, EGL_WINDOW_BIT,\n#endif\n EGL_NONE\n };\n\n EGLint num_configs;\n if (!eglChooseConfig(g_display,\n kConfigAttribs,\n NULL,\n 0,\n &num_configs)) {\n LOG(ERROR) << \"eglChooseConfig failed failed with error \"\n << GetLastEGLErrorString();\n return false;\n }\n\n if (num_configs == 0) {\n LOG(ERROR) << \"No suitable EGL configs found.\";\n return false;\n }\n\n scoped_array<EGLConfig> configs(new EGLConfig[num_configs]);\n if (!eglChooseConfig(g_display,\n kConfigAttribs,\n configs.get(),\n num_configs,\n &num_configs)) {\n LOG(ERROR) << \"eglChooseConfig failed with error \"\n << GetLastEGLErrorString();\n return false;\n }\n\n g_config = configs[0];\n\n initialized = true;\n return true;\n}\n\nEGLDisplay BaseEGLContext::GetDisplay() {\n return g_display;\n}\n\nstd::string BaseEGLContext::GetExtensions() {\n const char* extensions = eglQueryString(g_display, EGL_EXTENSIONS);\n if (!extensions)\n return GLContext::GetExtensions();\n\n return GLContext::GetExtensions() + \" \" + extensions;\n}\n\nNativeViewEGLContext::NativeViewEGLContext(void* window)\n : window_(window),\n surface_(NULL),\n context_(NULL)\n{\n}\n\nNativeViewEGLContext::~NativeViewEGLContext() {\n}\n\nbool NativeViewEGLContext::Initialize() {\n DCHECK(!context_);\n\n \/\/ Create a surface for the native window.\n EGLNativeWindowType native_window =\n reinterpret_cast<EGLNativeWindowType>(window_);\n surface_ = eglCreateWindowSurface(g_display, g_config, native_window, NULL);\n\n if (!surface_) {\n LOG(ERROR) << \"eglCreateWindowSurface failed with error \"\n << GetLastEGLErrorString();\n Destroy();\n return false;\n }\n\n \/\/ Create a context.\n context_ = eglCreateContext(g_display, g_config, NULL, NULL);\n if (!context_) {\n LOG(ERROR) << \"eglCreateContext failed with error \"\n << GetLastEGLErrorString();\n Destroy();\n return false;\n }\n\n if (!MakeCurrent()) {\n LOG(ERROR) << \"MakeCurrent failed.\";\n Destroy();\n return false;\n }\n\n if (!InitializeCommon()) {\n LOG(ERROR) << \"GLContext::InitializeCommon failed.\";\n Destroy();\n return false;\n }\n\n return true;\n}\n\nvoid NativeViewEGLContext::Destroy() {\n if (context_) {\n if (!eglDestroyContext(g_display, context_)) {\n LOG(ERROR) << \"eglDestroyContext failed with error \"\n << GetLastEGLErrorString();\n }\n\n context_ = NULL;\n }\n\n if (surface_) {\n if (!eglDestroySurface(g_display, surface_)) {\n LOG(ERROR) << \"eglDestroySurface failed with error \"\n << GetLastEGLErrorString();\n }\n\n surface_ = NULL;\n }\n}\n\nbool NativeViewEGLContext::MakeCurrent() {\n DCHECK(context_);\n if (!eglMakeCurrent(g_display,\n surface_, surface_,\n context_)) {\n VLOG(1) << \"eglMakeCurrent failed with error \"\n << GetLastEGLErrorString();\n return false;\n }\n\n return true;\n}\n\nbool NativeViewEGLContext::IsCurrent() {\n DCHECK(context_);\n return context_ == eglGetCurrentContext();\n}\n\nbool NativeViewEGLContext::IsOffscreen() {\n return false;\n}\n\nbool NativeViewEGLContext::SwapBuffers() {\n if (!eglSwapBuffers(g_display, surface_)) {\n VLOG(1) << \"eglSwapBuffers failed with error \"\n << GetLastEGLErrorString();\n return false;\n }\n\n return true;\n}\n\ngfx::Size NativeViewEGLContext::GetSize() {\n#if defined(OS_WIN)\n RECT rect;\n if (!GetClientRect(static_cast<HWND>(window_), &rect)) {\n DCHECK(false) << \"GetClientRect failed.\";\n return gfx::Size();\n }\n\n return gfx::Size(rect.right - rect.left, rect.bottom - rect.top);\n#else\n \/\/ TODO(piman): This doesn't work correctly on Windows yet, the size doesn't\n \/\/ get updated on resize. When it does, we can share the code.\n EGLint width;\n EGLint height;\n if (!eglQuerySurface(g_display, surface_, EGL_WIDTH, &width) ||\n !eglQuerySurface(g_display, surface_, EGL_HEIGHT, &height)) {\n NOTREACHED() << \"eglQuerySurface failed with error \"\n << GetLastEGLErrorString();\n return gfx::Size();\n }\n\n return gfx::Size(width, height);\n#endif\n}\n\nvoid* NativeViewEGLContext::GetHandle() {\n return context_;\n}\n\nvoid NativeViewEGLContext::SetSwapInterval(int interval) {\n DCHECK(IsCurrent());\n if (!eglSwapInterval(g_display, interval)) {\n LOG(ERROR) << \"eglSwapInterval failed with error \"\n << GetLastEGLErrorString();\n }\n}\n\nEGLSurface NativeViewEGLContext::GetSurface() {\n return surface_;\n}\n\nSecondaryEGLContext::SecondaryEGLContext()\n : surface_(NULL),\n own_surface_(false),\n context_(NULL)\n{\n}\n\nSecondaryEGLContext::~SecondaryEGLContext() {\n}\n\nbool SecondaryEGLContext::Initialize(GLContext* shared_context) {\n DCHECK(!context_);\n\n static const EGLint kContextAttributes[] = {\n EGL_CONTEXT_CLIENT_VERSION, 2,\n EGL_NONE\n };\n\n if (shared_context) {\n surface_ = static_cast<BaseEGLContext*>(shared_context)->GetSurface();\n own_surface_ = false;\n\n \/\/ Create a context.\n context_ = eglCreateContext(g_display,\n g_config,\n shared_context->GetHandle(),\n kContextAttributes);\n } else {\n#ifdef EGL_HAS_PBUFFERS\n static const EGLint kPbufferAttribs[] = {\n EGL_WIDTH, 1,\n EGL_HEIGHT, 1,\n EGL_NONE\n };\n\n surface_ = eglCreatePbufferSurface(g_display, g_config, kPbufferAttribs);\n if (!surface_) {\n LOG(ERROR) << \"eglCreatePbufferSurface failed with error \"\n << GetLastEGLErrorString();\n return false;\n }\n own_surface_ = true;\n\n context_ = eglCreateContext(g_display, g_config, NULL, kContextAttributes);\n#else\n NOTIMPLEMENTED() << \"Offscreen non-shared GLES context\";\n return false;\n#endif\n }\n\n if (!context_) {\n LOG(ERROR) << \"eglCreateContext failed with error \"\n << GetLastEGLErrorString();\n Destroy();\n return false;\n }\n\n return true;\n}\n\nvoid SecondaryEGLContext::Destroy() {\n if (own_surface_) {\n if (!eglDestroySurface(g_display, surface_)) {\n LOG(ERROR) << \"eglDestroySurface failed with error \"\n << GetLastEGLErrorString();\n }\n\n own_surface_ = false;\n }\n surface_ = NULL;\n\n if (context_) {\n if (!eglDestroyContext(g_display, context_)) {\n LOG(ERROR) << \"eglDestroyContext failed with error \"\n << GetLastEGLErrorString();\n }\n\n context_ = NULL;\n }\n}\n\nbool SecondaryEGLContext::MakeCurrent() {\n DCHECK(context_);\n if (!eglMakeCurrent(g_display,\n surface_, surface_,\n context_)) {\n VLOG(1) << \"eglMakeCurrent failed with error \"\n << GetLastEGLErrorString();\n return false;\n }\n\n return true;\n}\n\nbool SecondaryEGLContext::IsCurrent() {\n DCHECK(context_);\n return context_ == eglGetCurrentContext();\n}\n\nbool SecondaryEGLContext::IsOffscreen() {\n return true;\n}\n\nbool SecondaryEGLContext::SwapBuffers() {\n NOTREACHED() << \"Attempted to call SwapBuffers on a SecondaryEGLContext.\";\n return false;\n}\n\ngfx::Size SecondaryEGLContext::GetSize() {\n NOTREACHED() << \"Should not be requesting size of this SecondaryEGLContext.\";\n return gfx::Size(1, 1);\n}\n\nvoid* SecondaryEGLContext::GetHandle() {\n return context_;\n}\n\nvoid SecondaryEGLContext::SetSwapInterval(int interval) {\n DCHECK(IsCurrent());\n NOTREACHED() << \"Attempt to call SetSwapInterval on a SecondaryEGLContext.\";\n}\n\nEGLSurface SecondaryEGLContext::GetSurface() {\n return surface_;\n}\n\n} \/\/ namespace gfx\n<commit_msg>Specify client version 2 when creating EGL contexts.<commit_after>\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include <EGL\/egl.h>\n\n#include \"build\/build_config.h\"\n#if defined(OS_LINUX)\n#include \"app\/x11_util.h\"\n#define EGL_HAS_PBUFFERS 1\n#endif\n#include \"base\/logging.h\"\n#include \"base\/scoped_ptr.h\"\n#include \"app\/gfx\/gl\/gl_bindings.h\"\n#include \"app\/gfx\/gl\/gl_context_egl.h\"\n\nnamespace gfx {\n\nnamespace {\n\n\/\/ The EGL configuration to use.\nEGLDisplay g_display;\nEGLConfig g_config;\n\n\/\/ Returns the last EGL error as a string.\nconst char* GetLastEGLErrorString() {\n EGLint error = eglGetError();\n switch (error) {\n case EGL_SUCCESS:\n return \"EGL_SUCCESS\";\n case EGL_BAD_ACCESS:\n return \"EGL_BAD_ACCESS\";\n case EGL_BAD_ALLOC:\n return \"EGL_BAD_ALLOC\";\n case EGL_BAD_ATTRIBUTE:\n return \"EGL_BAD_ATTRIBUTE\";\n case EGL_BAD_CONTEXT:\n return \"EGL_BAD_CONTEXT\";\n case EGL_BAD_CONFIG:\n return \"EGL_BAD_CONFIG\";\n case EGL_BAD_CURRENT_SURFACE:\n return \"EGL_BAD_CURRENT_SURFACE\";\n case EGL_BAD_DISPLAY:\n return \"EGL_BAD_DISPLAY\";\n case EGL_BAD_SURFACE:\n return \"EGL_BAD_SURFACE\";\n case EGL_BAD_MATCH:\n return \"EGL_BAD_MATCH\";\n case EGL_BAD_PARAMETER:\n return \"EGL_BAD_PARAMETER\";\n case EGL_BAD_NATIVE_PIXMAP:\n return \"EGL_BAD_NATIVE_PIXMAP\";\n case EGL_BAD_NATIVE_WINDOW:\n return \"EGL_BAD_NATIVE_WINDOW\";\n default:\n return \"UNKNOWN\";\n }\n}\n} \/\/ namespace anonymous\n\nbool BaseEGLContext::InitializeOneOff() {\n static bool initialized = false;\n if (initialized)\n return true;\n\n#ifdef OS_LINUX\n EGLNativeDisplayType native_display = x11_util::GetXDisplay();\n#else\n EGLNativeDisplayType native_display = EGL_DEFAULT_DISPLAY;\n#endif\n g_display = eglGetDisplay(native_display);\n if (!g_display) {\n LOG(ERROR) << \"eglGetDisplay failed with error \" << GetLastEGLErrorString();\n return false;\n }\n\n if (!eglInitialize(g_display, NULL, NULL)) {\n LOG(ERROR) << \"eglInitialize failed with error \" << GetLastEGLErrorString();\n return false;\n }\n\n \/\/ Choose an EGL configuration.\n static const EGLint kConfigAttribs[] = {\n EGL_BUFFER_SIZE, 32,\n EGL_ALPHA_SIZE, 8,\n EGL_BLUE_SIZE, 8,\n EGL_RED_SIZE, 8,\n EGL_DEPTH_SIZE, 16,\n EGL_STENCIL_SIZE, 8,\n EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT,\n#ifdef EGL_HAS_PBUFFERS\n EGL_SURFACE_TYPE, EGL_WINDOW_BIT | EGL_PBUFFER_BIT,\n#else\n EGL_SURFACE_TYPE, EGL_WINDOW_BIT,\n#endif\n EGL_NONE\n };\n\n EGLint num_configs;\n if (!eglChooseConfig(g_display,\n kConfigAttribs,\n NULL,\n 0,\n &num_configs)) {\n LOG(ERROR) << \"eglChooseConfig failed failed with error \"\n << GetLastEGLErrorString();\n return false;\n }\n\n if (num_configs == 0) {\n LOG(ERROR) << \"No suitable EGL configs found.\";\n return false;\n }\n\n scoped_array<EGLConfig> configs(new EGLConfig[num_configs]);\n if (!eglChooseConfig(g_display,\n kConfigAttribs,\n configs.get(),\n num_configs,\n &num_configs)) {\n LOG(ERROR) << \"eglChooseConfig failed with error \"\n << GetLastEGLErrorString();\n return false;\n }\n\n g_config = configs[0];\n\n initialized = true;\n return true;\n}\n\nEGLDisplay BaseEGLContext::GetDisplay() {\n return g_display;\n}\n\nstd::string BaseEGLContext::GetExtensions() {\n const char* extensions = eglQueryString(g_display, EGL_EXTENSIONS);\n if (!extensions)\n return GLContext::GetExtensions();\n\n return GLContext::GetExtensions() + \" \" + extensions;\n}\n\nNativeViewEGLContext::NativeViewEGLContext(void* window)\n : window_(window),\n surface_(NULL),\n context_(NULL)\n{\n}\n\nNativeViewEGLContext::~NativeViewEGLContext() {\n}\n\nbool NativeViewEGLContext::Initialize() {\n DCHECK(!context_);\n\n \/\/ Create a surface for the native window.\n EGLNativeWindowType native_window =\n reinterpret_cast<EGLNativeWindowType>(window_);\n surface_ = eglCreateWindowSurface(g_display, g_config, native_window, NULL);\n\n if (!surface_) {\n LOG(ERROR) << \"eglCreateWindowSurface failed with error \"\n << GetLastEGLErrorString();\n Destroy();\n return false;\n }\n\n static const EGLint kContextAttributes[] = {\n EGL_CONTEXT_CLIENT_VERSION, 2,\n EGL_NONE\n };\n\n context_ = eglCreateContext(g_display, g_config, NULL, kContextAttributes);\n if (!context_) {\n LOG(ERROR) << \"eglCreateContext failed with error \"\n << GetLastEGLErrorString();\n Destroy();\n return false;\n }\n\n if (!MakeCurrent()) {\n LOG(ERROR) << \"MakeCurrent failed.\";\n Destroy();\n return false;\n }\n\n if (!InitializeCommon()) {\n LOG(ERROR) << \"GLContext::InitializeCommon failed.\";\n Destroy();\n return false;\n }\n\n return true;\n}\n\nvoid NativeViewEGLContext::Destroy() {\n if (context_) {\n if (!eglDestroyContext(g_display, context_)) {\n LOG(ERROR) << \"eglDestroyContext failed with error \"\n << GetLastEGLErrorString();\n }\n\n context_ = NULL;\n }\n\n if (surface_) {\n if (!eglDestroySurface(g_display, surface_)) {\n LOG(ERROR) << \"eglDestroySurface failed with error \"\n << GetLastEGLErrorString();\n }\n\n surface_ = NULL;\n }\n}\n\nbool NativeViewEGLContext::MakeCurrent() {\n DCHECK(context_);\n if (!eglMakeCurrent(g_display,\n surface_, surface_,\n context_)) {\n VLOG(1) << \"eglMakeCurrent failed with error \"\n << GetLastEGLErrorString();\n return false;\n }\n\n return true;\n}\n\nbool NativeViewEGLContext::IsCurrent() {\n DCHECK(context_);\n return context_ == eglGetCurrentContext();\n}\n\nbool NativeViewEGLContext::IsOffscreen() {\n return false;\n}\n\nbool NativeViewEGLContext::SwapBuffers() {\n if (!eglSwapBuffers(g_display, surface_)) {\n VLOG(1) << \"eglSwapBuffers failed with error \"\n << GetLastEGLErrorString();\n return false;\n }\n\n return true;\n}\n\ngfx::Size NativeViewEGLContext::GetSize() {\n#if defined(OS_WIN)\n RECT rect;\n if (!GetClientRect(static_cast<HWND>(window_), &rect)) {\n DCHECK(false) << \"GetClientRect failed.\";\n return gfx::Size();\n }\n\n return gfx::Size(rect.right - rect.left, rect.bottom - rect.top);\n#else\n \/\/ TODO(piman): This doesn't work correctly on Windows yet, the size doesn't\n \/\/ get updated on resize. When it does, we can share the code.\n EGLint width;\n EGLint height;\n if (!eglQuerySurface(g_display, surface_, EGL_WIDTH, &width) ||\n !eglQuerySurface(g_display, surface_, EGL_HEIGHT, &height)) {\n NOTREACHED() << \"eglQuerySurface failed with error \"\n << GetLastEGLErrorString();\n return gfx::Size();\n }\n\n return gfx::Size(width, height);\n#endif\n}\n\nvoid* NativeViewEGLContext::GetHandle() {\n return context_;\n}\n\nvoid NativeViewEGLContext::SetSwapInterval(int interval) {\n DCHECK(IsCurrent());\n if (!eglSwapInterval(g_display, interval)) {\n LOG(ERROR) << \"eglSwapInterval failed with error \"\n << GetLastEGLErrorString();\n }\n}\n\nEGLSurface NativeViewEGLContext::GetSurface() {\n return surface_;\n}\n\nSecondaryEGLContext::SecondaryEGLContext()\n : surface_(NULL),\n own_surface_(false),\n context_(NULL)\n{\n}\n\nSecondaryEGLContext::~SecondaryEGLContext() {\n}\n\nbool SecondaryEGLContext::Initialize(GLContext* shared_context) {\n DCHECK(!context_);\n\n static const EGLint kContextAttributes[] = {\n EGL_CONTEXT_CLIENT_VERSION, 2,\n EGL_NONE\n };\n\n if (shared_context) {\n surface_ = static_cast<BaseEGLContext*>(shared_context)->GetSurface();\n own_surface_ = false;\n\n \/\/ Create a context.\n context_ = eglCreateContext(g_display,\n g_config,\n shared_context->GetHandle(),\n kContextAttributes);\n } else {\n#ifdef EGL_HAS_PBUFFERS\n static const EGLint kPbufferAttribs[] = {\n EGL_WIDTH, 1,\n EGL_HEIGHT, 1,\n EGL_NONE\n };\n\n surface_ = eglCreatePbufferSurface(g_display, g_config, kPbufferAttribs);\n if (!surface_) {\n LOG(ERROR) << \"eglCreatePbufferSurface failed with error \"\n << GetLastEGLErrorString();\n return false;\n }\n own_surface_ = true;\n\n context_ = eglCreateContext(g_display, g_config, NULL, kContextAttributes);\n#else\n NOTIMPLEMENTED() << \"Offscreen non-shared GLES context\";\n return false;\n#endif\n }\n\n if (!context_) {\n LOG(ERROR) << \"eglCreateContext failed with error \"\n << GetLastEGLErrorString();\n Destroy();\n return false;\n }\n\n return true;\n}\n\nvoid SecondaryEGLContext::Destroy() {\n if (own_surface_) {\n if (!eglDestroySurface(g_display, surface_)) {\n LOG(ERROR) << \"eglDestroySurface failed with error \"\n << GetLastEGLErrorString();\n }\n\n own_surface_ = false;\n }\n surface_ = NULL;\n\n if (context_) {\n if (!eglDestroyContext(g_display, context_)) {\n LOG(ERROR) << \"eglDestroyContext failed with error \"\n << GetLastEGLErrorString();\n }\n\n context_ = NULL;\n }\n}\n\nbool SecondaryEGLContext::MakeCurrent() {\n DCHECK(context_);\n if (!eglMakeCurrent(g_display,\n surface_, surface_,\n context_)) {\n VLOG(1) << \"eglMakeCurrent failed with error \"\n << GetLastEGLErrorString();\n return false;\n }\n\n return true;\n}\n\nbool SecondaryEGLContext::IsCurrent() {\n DCHECK(context_);\n return context_ == eglGetCurrentContext();\n}\n\nbool SecondaryEGLContext::IsOffscreen() {\n return true;\n}\n\nbool SecondaryEGLContext::SwapBuffers() {\n NOTREACHED() << \"Attempted to call SwapBuffers on a SecondaryEGLContext.\";\n return false;\n}\n\ngfx::Size SecondaryEGLContext::GetSize() {\n NOTREACHED() << \"Should not be requesting size of this SecondaryEGLContext.\";\n return gfx::Size(1, 1);\n}\n\nvoid* SecondaryEGLContext::GetHandle() {\n return context_;\n}\n\nvoid SecondaryEGLContext::SetSwapInterval(int interval) {\n DCHECK(IsCurrent());\n NOTREACHED() << \"Attempt to call SetSwapInterval on a SecondaryEGLContext.\";\n}\n\nEGLSurface SecondaryEGLContext::GetSurface() {\n return surface_;\n}\n\n} \/\/ namespace gfx\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"base\/string_util.h\"\n#include \"base\/utf_string_conversions.h\"\n#include \"chrome\/browser\/autocomplete\/autocomplete.h\"\n#include \"chrome\/browser\/autocomplete\/autocomplete_edit.h\"\n#include \"chrome\/browser\/autocomplete\/autocomplete_edit_view.h\"\n#include \"chrome\/browser\/autocomplete\/autocomplete_popup_model.h\"\n#include \"chrome\/browser\/browser.h\"\n#include \"chrome\/browser\/browser_window.h\"\n#include \"chrome\/browser\/history\/history.h\"\n#include \"chrome\/browser\/location_bar.h\"\n#include \"chrome\/browser\/profile.h\"\n#include \"chrome\/browser\/tab_contents\/tab_contents.h\"\n#include \"chrome\/browser\/tabs\/tab_strip_model.h\"\n#include \"chrome\/common\/notification_type.h\"\n#include \"chrome\/common\/url_constants.h\"\n#include \"chrome\/test\/in_process_browser_test.h\"\n#include \"chrome\/test\/ui_test_utils.h\"\n#include \"testing\/gtest\/include\/gtest\/gtest.h\"\n\n\/\/ Basic test is crashy on Mac\n\/\/ http:\/\/crbug.com\/49324\n#if defined(OS_MAC)\n#define MAYBE_Basic DISABLED_Basic\n#else\n#define MAYBE_Basic Basic\n#endif\n\n\/\/ Autocomplete test is flaky on ChromeOS.\n\/\/ http:\/\/crbug.com\/52928\n#if defined(OS_CHROMEOS)\n#define MAYBE_Autocomplete FLAKY_Autocomplete\n#else\n#define MAYBE_Autocomplete Autocomplete\n#endif\n\n\nnamespace {\n\nstd::wstring AutocompleteResultAsString(const AutocompleteResult& result) {\n std::wstring output(StringPrintf(L\"{%d} \", result.size()));\n for (size_t i = 0; i < result.size(); ++i) {\n AutocompleteMatch match = result.match_at(i);\n std::wstring provider_name(ASCIIToWide(match.provider->name()));\n output.append(StringPrintf(L\"[\\\"%ls\\\" by \\\"%ls\\\"] \",\n match.contents.c_str(),\n provider_name.c_str()));\n }\n return output;\n}\n\n} \/\/ namespace\n\nclass AutocompleteBrowserTest : public InProcessBrowserTest {\n protected:\n LocationBar* GetLocationBar() const {\n return browser()->window()->GetLocationBar();\n }\n\n AutocompleteController* GetAutocompleteController() const {\n return GetLocationBar()->location_entry()->model()->popup_model()->\n autocomplete_controller();\n }\n};\n\nIN_PROC_BROWSER_TEST_F(AutocompleteBrowserTest, MAYBE_Basic) {\n LocationBar* location_bar = GetLocationBar();\n\n EXPECT_EQ(std::wstring(), location_bar->GetInputString());\n EXPECT_EQ(UTF8ToWide(chrome::kAboutBlankURL),\n location_bar->location_entry()->GetText());\n \/\/ TODO(phajdan.jr): check state of IsSelectAll when it's consistent across\n \/\/ platforms.\n\n location_bar->FocusLocation(true);\n\n EXPECT_EQ(std::wstring(), location_bar->GetInputString());\n EXPECT_EQ(UTF8ToWide(chrome::kAboutBlankURL),\n location_bar->location_entry()->GetText());\n EXPECT_TRUE(location_bar->location_entry()->IsSelectAll());\n\n location_bar->location_entry()->SetUserText(L\"chrome\");\n\n EXPECT_EQ(std::wstring(), location_bar->GetInputString());\n EXPECT_EQ(L\"chrome\", location_bar->location_entry()->GetText());\n EXPECT_FALSE(location_bar->location_entry()->IsSelectAll());\n\n location_bar->location_entry()->RevertAll();\n\n EXPECT_EQ(std::wstring(), location_bar->GetInputString());\n EXPECT_EQ(UTF8ToWide(chrome::kAboutBlankURL),\n location_bar->location_entry()->GetText());\n EXPECT_FALSE(location_bar->location_entry()->IsSelectAll());\n\n location_bar->location_entry()->SetUserText(L\"chrome\");\n location_bar->Revert();\n\n EXPECT_EQ(std::wstring(), location_bar->GetInputString());\n EXPECT_EQ(UTF8ToWide(chrome::kAboutBlankURL),\n location_bar->location_entry()->GetText());\n EXPECT_FALSE(location_bar->location_entry()->IsSelectAll());\n}\n\nIN_PROC_BROWSER_TEST_F(AutocompleteBrowserTest, MAYBE_Autocomplete) {\n \/\/ The results depend on the history backend being loaded. Make sure it is\n \/\/ loaded so that the autocomplete results are consistent.\n ui_test_utils::WaitForHistoryToLoad(browser());\n\n LocationBar* location_bar = GetLocationBar();\n AutocompleteController* autocomplete_controller = GetAutocompleteController();\n\n {\n autocomplete_controller->Start(L\"chrome\", std::wstring(),\n true, false, true);\n\n EXPECT_TRUE(autocomplete_controller->done());\n EXPECT_EQ(std::wstring(), location_bar->GetInputString());\n EXPECT_EQ(std::wstring(), location_bar->location_entry()->GetText());\n EXPECT_TRUE(location_bar->location_entry()->IsSelectAll());\n const AutocompleteResult& result = autocomplete_controller->result();\n ASSERT_EQ(1U, result.size()) << AutocompleteResultAsString(result);\n AutocompleteMatch match = result.match_at(0);\n EXPECT_EQ(AutocompleteMatch::SEARCH_WHAT_YOU_TYPED, match.type);\n EXPECT_FALSE(match.deletable);\n }\n\n {\n location_bar->Revert();\n\n EXPECT_EQ(std::wstring(), location_bar->GetInputString());\n EXPECT_EQ(UTF8ToWide(chrome::kAboutBlankURL),\n location_bar->location_entry()->GetText());\n EXPECT_FALSE(location_bar->location_entry()->IsSelectAll());\n const AutocompleteResult& result = autocomplete_controller->result();\n EXPECT_TRUE(result.empty()) << AutocompleteResultAsString(result);\n }\n}\n\nIN_PROC_BROWSER_TEST_F(AutocompleteBrowserTest, TabAwayRevertSelect) {\n \/\/ http:\/\/code.google.com\/p\/chromium\/issues\/detail?id=38385\n \/\/ Make sure that tabbing away from an empty omnibar causes a revert\n \/\/ and select all.\n LocationBar* location_bar = GetLocationBar();\n EXPECT_EQ(UTF8ToWide(chrome::kAboutBlankURL),\n location_bar->location_entry()->GetText());\n location_bar->location_entry()->SetUserText(L\"\");\n Browser::AddTabWithURLParams params(GURL(chrome::kAboutBlankURL),\n PageTransition::START_PAGE);\n browser()->AddTabWithURL(¶ms);\n EXPECT_EQ(browser(), params.target);\n ui_test_utils::WaitForNavigation(\n &browser()->GetSelectedTabContents()->controller());\n EXPECT_EQ(UTF8ToWide(chrome::kAboutBlankURL),\n location_bar->location_entry()->GetText());\n browser()->CloseTab();\n EXPECT_EQ(UTF8ToWide(chrome::kAboutBlankURL),\n location_bar->location_entry()->GetText());\n EXPECT_TRUE(location_bar->location_entry()->IsSelectAll());\n}\n\nIN_PROC_BROWSER_TEST_F(AutocompleteBrowserTest, FocusSearch) {\n LocationBar* location_bar = GetLocationBar();\n\n \/\/ Focus search when omnibox is blank\n {\n EXPECT_EQ(std::wstring(), location_bar->GetInputString());\n EXPECT_EQ(UTF8ToWide(chrome::kAboutBlankURL),\n location_bar->location_entry()->GetText());\n\n location_bar->FocusSearch();\n EXPECT_EQ(std::wstring(), location_bar->GetInputString());\n EXPECT_EQ(L\"?\", location_bar->location_entry()->GetText());\n\n size_t selection_start, selection_end;\n location_bar->location_entry()->GetSelectionBounds(&selection_start,\n &selection_end);\n EXPECT_EQ(1U, selection_start);\n EXPECT_EQ(1U, selection_end);\n }\n\n \/\/ Focus search when omnibox is _not_ alread in forced query mode.\n {\n location_bar->location_entry()->SetUserText(L\"foo\");\n EXPECT_EQ(std::wstring(), location_bar->GetInputString());\n EXPECT_EQ(L\"foo\", location_bar->location_entry()->GetText());\n\n location_bar->FocusSearch();\n EXPECT_EQ(std::wstring(), location_bar->GetInputString());\n EXPECT_EQ(L\"?\", location_bar->location_entry()->GetText());\n\n size_t selection_start, selection_end;\n location_bar->location_entry()->GetSelectionBounds(&selection_start,\n &selection_end);\n EXPECT_EQ(1U, selection_start);\n EXPECT_EQ(1U, selection_end);\n }\n\n \/\/ Focus search when omnibox _is_ already in forced query mode, but no query\n \/\/ has been typed.\n {\n location_bar->location_entry()->SetUserText(L\"?\");\n EXPECT_EQ(std::wstring(), location_bar->GetInputString());\n EXPECT_EQ(L\"?\", location_bar->location_entry()->GetText());\n\n location_bar->FocusSearch();\n EXPECT_EQ(std::wstring(), location_bar->GetInputString());\n EXPECT_EQ(L\"?\", location_bar->location_entry()->GetText());\n\n size_t selection_start, selection_end;\n location_bar->location_entry()->GetSelectionBounds(&selection_start,\n &selection_end);\n EXPECT_EQ(1U, selection_start);\n EXPECT_EQ(1U, selection_end);\n }\n\n \/\/ Focus search when omnibox _is_ already in forced query mode, and some query\n \/\/ has been typed.\n {\n location_bar->location_entry()->SetUserText(L\"?foo\");\n EXPECT_EQ(std::wstring(), location_bar->GetInputString());\n EXPECT_EQ(L\"?foo\", location_bar->location_entry()->GetText());\n\n location_bar->FocusSearch();\n EXPECT_EQ(std::wstring(), location_bar->GetInputString());\n EXPECT_EQ(L\"?foo\", location_bar->location_entry()->GetText());\n\n size_t selection_start, selection_end;\n location_bar->location_entry()->GetSelectionBounds(&selection_start,\n &selection_end);\n EXPECT_EQ(1U, std::min(selection_start, selection_end));\n EXPECT_EQ(4U, std::max(selection_start, selection_end));\n }\n\n \/\/ Focus search when omnibox is in forced query mode with leading whitespace.\n {\n location_bar->location_entry()->SetUserText(L\" ?foo\");\n EXPECT_EQ(std::wstring(), location_bar->GetInputString());\n EXPECT_EQ(L\" ?foo\", location_bar->location_entry()->GetText());\n\n location_bar->FocusSearch();\n EXPECT_EQ(std::wstring(), location_bar->GetInputString());\n EXPECT_EQ(L\" ?foo\", location_bar->location_entry()->GetText());\n\n size_t selection_start, selection_end;\n location_bar->location_entry()->GetSelectionBounds(&selection_start,\n &selection_end);\n EXPECT_EQ(4U, std::min(selection_start, selection_end));\n EXPECT_EQ(7U, std::max(selection_start, selection_end));\n }\n}\n<commit_msg>Re-enable AutocompleteBrowserTest.Basic<commit_after>\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"base\/string_util.h\"\n#include \"base\/utf_string_conversions.h\"\n#include \"chrome\/browser\/autocomplete\/autocomplete.h\"\n#include \"chrome\/browser\/autocomplete\/autocomplete_edit.h\"\n#include \"chrome\/browser\/autocomplete\/autocomplete_edit_view.h\"\n#include \"chrome\/browser\/autocomplete\/autocomplete_popup_model.h\"\n#include \"chrome\/browser\/browser.h\"\n#include \"chrome\/browser\/browser_window.h\"\n#include \"chrome\/browser\/history\/history.h\"\n#include \"chrome\/browser\/location_bar.h\"\n#include \"chrome\/browser\/profile.h\"\n#include \"chrome\/browser\/tab_contents\/tab_contents.h\"\n#include \"chrome\/browser\/tabs\/tab_strip_model.h\"\n#include \"chrome\/common\/notification_type.h\"\n#include \"chrome\/common\/url_constants.h\"\n#include \"chrome\/test\/in_process_browser_test.h\"\n#include \"chrome\/test\/ui_test_utils.h\"\n#include \"testing\/gtest\/include\/gtest\/gtest.h\"\n\n\/\/ Autocomplete test is flaky on ChromeOS.\n\/\/ http:\/\/crbug.com\/52928\n#if defined(OS_CHROMEOS)\n#define MAYBE_Autocomplete FLAKY_Autocomplete\n#else\n#define MAYBE_Autocomplete Autocomplete\n#endif\n\n\nnamespace {\n\nstd::wstring AutocompleteResultAsString(const AutocompleteResult& result) {\n std::wstring output(StringPrintf(L\"{%d} \", result.size()));\n for (size_t i = 0; i < result.size(); ++i) {\n AutocompleteMatch match = result.match_at(i);\n std::wstring provider_name(ASCIIToWide(match.provider->name()));\n output.append(StringPrintf(L\"[\\\"%ls\\\" by \\\"%ls\\\"] \",\n match.contents.c_str(),\n provider_name.c_str()));\n }\n return output;\n}\n\n} \/\/ namespace\n\nclass AutocompleteBrowserTest : public InProcessBrowserTest {\n protected:\n LocationBar* GetLocationBar() const {\n return browser()->window()->GetLocationBar();\n }\n\n AutocompleteController* GetAutocompleteController() const {\n return GetLocationBar()->location_entry()->model()->popup_model()->\n autocomplete_controller();\n }\n};\n\nIN_PROC_BROWSER_TEST_F(AutocompleteBrowserTest, Basic) {\n LocationBar* location_bar = GetLocationBar();\n\n EXPECT_EQ(std::wstring(), location_bar->GetInputString());\n EXPECT_EQ(UTF8ToWide(chrome::kAboutBlankURL),\n location_bar->location_entry()->GetText());\n \/\/ TODO(phajdan.jr): check state of IsSelectAll when it's consistent across\n \/\/ platforms.\n\n location_bar->FocusLocation(true);\n\n EXPECT_EQ(std::wstring(), location_bar->GetInputString());\n EXPECT_EQ(UTF8ToWide(chrome::kAboutBlankURL),\n location_bar->location_entry()->GetText());\n EXPECT_TRUE(location_bar->location_entry()->IsSelectAll());\n\n location_bar->location_entry()->SetUserText(L\"chrome\");\n\n EXPECT_EQ(std::wstring(), location_bar->GetInputString());\n EXPECT_EQ(L\"chrome\", location_bar->location_entry()->GetText());\n EXPECT_FALSE(location_bar->location_entry()->IsSelectAll());\n\n location_bar->location_entry()->RevertAll();\n\n EXPECT_EQ(std::wstring(), location_bar->GetInputString());\n EXPECT_EQ(UTF8ToWide(chrome::kAboutBlankURL),\n location_bar->location_entry()->GetText());\n EXPECT_FALSE(location_bar->location_entry()->IsSelectAll());\n\n location_bar->location_entry()->SetUserText(L\"chrome\");\n location_bar->Revert();\n\n EXPECT_EQ(std::wstring(), location_bar->GetInputString());\n EXPECT_EQ(UTF8ToWide(chrome::kAboutBlankURL),\n location_bar->location_entry()->GetText());\n EXPECT_FALSE(location_bar->location_entry()->IsSelectAll());\n}\n\nIN_PROC_BROWSER_TEST_F(AutocompleteBrowserTest, MAYBE_Autocomplete) {\n \/\/ The results depend on the history backend being loaded. Make sure it is\n \/\/ loaded so that the autocomplete results are consistent.\n ui_test_utils::WaitForHistoryToLoad(browser());\n\n LocationBar* location_bar = GetLocationBar();\n AutocompleteController* autocomplete_controller = GetAutocompleteController();\n\n {\n autocomplete_controller->Start(L\"chrome\", std::wstring(),\n true, false, true);\n\n EXPECT_TRUE(autocomplete_controller->done());\n EXPECT_EQ(std::wstring(), location_bar->GetInputString());\n EXPECT_EQ(std::wstring(), location_bar->location_entry()->GetText());\n EXPECT_TRUE(location_bar->location_entry()->IsSelectAll());\n const AutocompleteResult& result = autocomplete_controller->result();\n ASSERT_EQ(1U, result.size()) << AutocompleteResultAsString(result);\n AutocompleteMatch match = result.match_at(0);\n EXPECT_EQ(AutocompleteMatch::SEARCH_WHAT_YOU_TYPED, match.type);\n EXPECT_FALSE(match.deletable);\n }\n\n {\n location_bar->Revert();\n\n EXPECT_EQ(std::wstring(), location_bar->GetInputString());\n EXPECT_EQ(UTF8ToWide(chrome::kAboutBlankURL),\n location_bar->location_entry()->GetText());\n EXPECT_FALSE(location_bar->location_entry()->IsSelectAll());\n const AutocompleteResult& result = autocomplete_controller->result();\n EXPECT_TRUE(result.empty()) << AutocompleteResultAsString(result);\n }\n}\n\nIN_PROC_BROWSER_TEST_F(AutocompleteBrowserTest, TabAwayRevertSelect) {\n \/\/ http:\/\/code.google.com\/p\/chromium\/issues\/detail?id=38385\n \/\/ Make sure that tabbing away from an empty omnibar causes a revert\n \/\/ and select all.\n LocationBar* location_bar = GetLocationBar();\n EXPECT_EQ(UTF8ToWide(chrome::kAboutBlankURL),\n location_bar->location_entry()->GetText());\n location_bar->location_entry()->SetUserText(L\"\");\n Browser::AddTabWithURLParams params(GURL(chrome::kAboutBlankURL),\n PageTransition::START_PAGE);\n browser()->AddTabWithURL(¶ms);\n EXPECT_EQ(browser(), params.target);\n ui_test_utils::WaitForNavigation(\n &browser()->GetSelectedTabContents()->controller());\n EXPECT_EQ(UTF8ToWide(chrome::kAboutBlankURL),\n location_bar->location_entry()->GetText());\n browser()->CloseTab();\n EXPECT_EQ(UTF8ToWide(chrome::kAboutBlankURL),\n location_bar->location_entry()->GetText());\n EXPECT_TRUE(location_bar->location_entry()->IsSelectAll());\n}\n\nIN_PROC_BROWSER_TEST_F(AutocompleteBrowserTest, FocusSearch) {\n LocationBar* location_bar = GetLocationBar();\n\n \/\/ Focus search when omnibox is blank\n {\n EXPECT_EQ(std::wstring(), location_bar->GetInputString());\n EXPECT_EQ(UTF8ToWide(chrome::kAboutBlankURL),\n location_bar->location_entry()->GetText());\n\n location_bar->FocusSearch();\n EXPECT_EQ(std::wstring(), location_bar->GetInputString());\n EXPECT_EQ(L\"?\", location_bar->location_entry()->GetText());\n\n size_t selection_start, selection_end;\n location_bar->location_entry()->GetSelectionBounds(&selection_start,\n &selection_end);\n EXPECT_EQ(1U, selection_start);\n EXPECT_EQ(1U, selection_end);\n }\n\n \/\/ Focus search when omnibox is _not_ alread in forced query mode.\n {\n location_bar->location_entry()->SetUserText(L\"foo\");\n EXPECT_EQ(std::wstring(), location_bar->GetInputString());\n EXPECT_EQ(L\"foo\", location_bar->location_entry()->GetText());\n\n location_bar->FocusSearch();\n EXPECT_EQ(std::wstring(), location_bar->GetInputString());\n EXPECT_EQ(L\"?\", location_bar->location_entry()->GetText());\n\n size_t selection_start, selection_end;\n location_bar->location_entry()->GetSelectionBounds(&selection_start,\n &selection_end);\n EXPECT_EQ(1U, selection_start);\n EXPECT_EQ(1U, selection_end);\n }\n\n \/\/ Focus search when omnibox _is_ already in forced query mode, but no query\n \/\/ has been typed.\n {\n location_bar->location_entry()->SetUserText(L\"?\");\n EXPECT_EQ(std::wstring(), location_bar->GetInputString());\n EXPECT_EQ(L\"?\", location_bar->location_entry()->GetText());\n\n location_bar->FocusSearch();\n EXPECT_EQ(std::wstring(), location_bar->GetInputString());\n EXPECT_EQ(L\"?\", location_bar->location_entry()->GetText());\n\n size_t selection_start, selection_end;\n location_bar->location_entry()->GetSelectionBounds(&selection_start,\n &selection_end);\n EXPECT_EQ(1U, selection_start);\n EXPECT_EQ(1U, selection_end);\n }\n\n \/\/ Focus search when omnibox _is_ already in forced query mode, and some query\n \/\/ has been typed.\n {\n location_bar->location_entry()->SetUserText(L\"?foo\");\n EXPECT_EQ(std::wstring(), location_bar->GetInputString());\n EXPECT_EQ(L\"?foo\", location_bar->location_entry()->GetText());\n\n location_bar->FocusSearch();\n EXPECT_EQ(std::wstring(), location_bar->GetInputString());\n EXPECT_EQ(L\"?foo\", location_bar->location_entry()->GetText());\n\n size_t selection_start, selection_end;\n location_bar->location_entry()->GetSelectionBounds(&selection_start,\n &selection_end);\n EXPECT_EQ(1U, std::min(selection_start, selection_end));\n EXPECT_EQ(4U, std::max(selection_start, selection_end));\n }\n\n \/\/ Focus search when omnibox is in forced query mode with leading whitespace.\n {\n location_bar->location_entry()->SetUserText(L\" ?foo\");\n EXPECT_EQ(std::wstring(), location_bar->GetInputString());\n EXPECT_EQ(L\" ?foo\", location_bar->location_entry()->GetText());\n\n location_bar->FocusSearch();\n EXPECT_EQ(std::wstring(), location_bar->GetInputString());\n EXPECT_EQ(L\" ?foo\", location_bar->location_entry()->GetText());\n\n size_t selection_start, selection_end;\n location_bar->location_entry()->GetSelectionBounds(&selection_start,\n &selection_end);\n EXPECT_EQ(4U, std::min(selection_start, selection_end));\n EXPECT_EQ(7U, std::max(selection_start, selection_end));\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2009 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/automation\/url_request_automation_job.h\"\n\n#include \"base\/message_loop.h\"\n#include \"base\/time.h\"\n#include \"chrome\/browser\/automation\/automation_resource_message_filter.h\"\n#include \"chrome\/browser\/renderer_host\/render_view_host.h\"\n#include \"chrome\/browser\/renderer_host\/resource_dispatcher_host.h\"\n#include \"chrome\/browser\/renderer_host\/resource_dispatcher_host_request_info.h\"\n#include \"chrome\/test\/automation\/automation_messages.h\"\n#include \"net\/base\/io_buffer.h\"\n#include \"net\/base\/net_errors.h\"\n#include \"net\/http\/http_util.h\"\n#include \"net\/url_request\/url_request.h\"\n#include \"net\/url_request\/url_request_context.h\"\n\nusing base::Time;\nusing base::TimeDelta;\n\n\/\/ The list of filtered headers that are removed from requests sent via\n\/\/ StartAsync(). These must be lower case.\nstatic const char* kFilteredHeaderStrings[] = {\n \"accept\",\n \"authorization\",\n \"cache-control\",\n \"connection\",\n \"cookie\",\n \"expect\",\n \"if-match\",\n \"if-modified-since\",\n \"if-none-match\",\n \"if-range\",\n \"if-unmodified-since\",\n \"max-forwards\",\n \"proxy-authorization\",\n \"te\",\n \"upgrade\",\n \"via\"\n};\n\n\/\/ This class manages the interception of network requests for automation.\n\/\/ It looks at the request, and creates an intercept job if it indicates\n\/\/ that it should use automation channel.\n\/\/ NOTE: All methods must be called on the IO thread.\nclass AutomationRequestInterceptor : public URLRequest::Interceptor {\n public:\n AutomationRequestInterceptor() {\n URLRequest::RegisterRequestInterceptor(this);\n }\n\n virtual ~AutomationRequestInterceptor() {\n URLRequest::UnregisterRequestInterceptor(this);\n }\n\n \/\/ URLRequest::Interceptor\n virtual URLRequestJob* MaybeIntercept(URLRequest* request);\n\n private:\n DISALLOW_COPY_AND_ASSIGN(AutomationRequestInterceptor);\n};\n\nURLRequestJob* AutomationRequestInterceptor::MaybeIntercept(\n URLRequest* request) {\n if (request->url().SchemeIs(\"http\") || request->url().SchemeIs(\"https\")) {\n ResourceDispatcherHostRequestInfo* request_info =\n ResourceDispatcherHost::InfoForRequest(request);\n if (request_info) {\n AutomationResourceMessageFilter::AutomationDetails details;\n if (AutomationResourceMessageFilter::LookupRegisteredRenderView(\n request_info->child_id(), request_info->route_id(), &details)) {\n URLRequestAutomationJob* job = new URLRequestAutomationJob(request,\n details.tab_handle, details.filter);\n return job;\n }\n }\n }\n\n return NULL;\n}\n\nstatic URLRequest::Interceptor* GetAutomationRequestInterceptor() {\n return Singleton<AutomationRequestInterceptor>::get();\n}\n\nint URLRequestAutomationJob::instance_count_ = 0;\n\nURLRequestAutomationJob::URLRequestAutomationJob(\n URLRequest* request, int tab, AutomationResourceMessageFilter* filter)\n : URLRequestJob(request), id_(0), tab_(tab), message_filter_(filter),\n pending_buf_size_(0), redirect_status_(0) {\n DLOG(INFO) << \"URLRequestAutomationJob create. Count: \" << ++instance_count_;\n if (message_filter_) {\n id_ = message_filter_->NewRequestId();\n DCHECK(id_);\n } else {\n NOTREACHED();\n }\n}\n\nURLRequestAutomationJob::~URLRequestAutomationJob() {\n DLOG(INFO) << \"URLRequestAutomationJob delete. Count: \" << --instance_count_;\n Cleanup();\n}\n\nbool URLRequestAutomationJob::InitializeInterceptor() {\n \/\/ AutomationRequestInterceptor will register itself when it\n \/\/ is first created.\n URLRequest::Interceptor* interceptor = GetAutomationRequestInterceptor();\n return (interceptor != NULL);\n}\n\n\/\/ URLRequestJob Implementation.\nvoid URLRequestAutomationJob::Start() {\n \/\/ Start reading asynchronously so that all error reporting and data\n \/\/ callbacks happen as they would for network requests.\n MessageLoop::current()->PostTask(FROM_HERE, NewRunnableMethod(\n this, &URLRequestAutomationJob::StartAsync));\n}\n\nvoid URLRequestAutomationJob::Kill() {\n if (message_filter_.get()) {\n message_filter_->Send(new AutomationMsg_RequestEnd(0, tab_, id_,\n URLRequestStatus(URLRequestStatus::CANCELED, 0)));\n }\n DisconnectFromMessageFilter();\n URLRequestJob::Kill();\n}\n\nbool URLRequestAutomationJob::ReadRawData(\n net::IOBuffer* buf, int buf_size, int* bytes_read) {\n DLOG(INFO) << \"URLRequestAutomationJob: \" <<\n request_->url().spec() << \" - read pending: \" << buf_size;\n pending_buf_ = buf;\n pending_buf_size_ = buf_size;\n\n message_filter_->Send(new AutomationMsg_RequestRead(0, tab_, id_,\n buf_size));\n SetStatus(URLRequestStatus(URLRequestStatus::IO_PENDING, 0));\n return false;\n}\n\nbool URLRequestAutomationJob::GetMimeType(std::string* mime_type) const {\n if (!mime_type_.empty()) {\n *mime_type = mime_type_;\n } else if (headers_) {\n headers_->GetMimeType(mime_type);\n }\n\n return (!mime_type->empty());\n}\n\nbool URLRequestAutomationJob::GetCharset(std::string* charset) {\n if (headers_)\n return headers_->GetCharset(charset);\n return false;\n}\n\nvoid URLRequestAutomationJob::GetResponseInfo(net::HttpResponseInfo* info) {\n if (headers_)\n info->headers = headers_;\n if (request_->url().SchemeIsSecure()) {\n \/\/ Make up a fake certificate for this response since we don't have\n \/\/ access to the real SSL info.\n const char* kCertIssuer = \"Chrome Internal\";\n const int kLifetimeDays = 100;\n\n info->ssl_info.cert =\n new net::X509Certificate(request_->url().GetWithEmptyPath().spec(),\n kCertIssuer,\n Time::Now(),\n Time::Now() +\n TimeDelta::FromDays(kLifetimeDays));\n info->ssl_info.cert_status = 0;\n info->ssl_info.security_bits = 0;\n }\n}\n\nint URLRequestAutomationJob::GetResponseCode() const {\n if (headers_)\n return headers_->response_code();\n\n static const int kDefaultResponseCode = 200;\n return kDefaultResponseCode;\n}\n\nbool URLRequestAutomationJob::IsRedirectResponse(\n GURL* location, int* http_status_code) {\n static const int kDefaultHttpRedirectResponseCode = 301;\n\n if (!redirect_url_.empty()) {\n DLOG_IF(ERROR, redirect_status_ == 0) << \"Missing redirect status?\";\n *http_status_code = redirect_status_ ? redirect_status_ :\n kDefaultHttpRedirectResponseCode;\n *location = GURL(redirect_url_);\n return true;\n } else {\n DCHECK(redirect_status_ == 0)\n << \"Unexpectedly have redirect status but no URL\";\n }\n\n return false;\n}\n\nint URLRequestAutomationJob::MayFilterMessage(const IPC::Message& message) {\n switch (message.type()) {\n case AutomationMsg_RequestStarted::ID:\n case AutomationMsg_RequestData::ID:\n case AutomationMsg_RequestEnd::ID: {\n void* iter = NULL;\n int tab = 0;\n int id = 0;\n if (message.ReadInt(&iter, &tab) && message.ReadInt(&iter, &id)) {\n DCHECK(id);\n return id;\n }\n break;\n }\n }\n\n return 0;\n}\n\nvoid URLRequestAutomationJob::OnMessage(const IPC::Message& message) {\n IPC_BEGIN_MESSAGE_MAP(URLRequestAutomationJob, message)\n IPC_MESSAGE_HANDLER(AutomationMsg_RequestStarted, OnRequestStarted)\n IPC_MESSAGE_HANDLER(AutomationMsg_RequestData, OnDataAvailable)\n IPC_MESSAGE_HANDLER(AutomationMsg_RequestEnd, OnRequestEnd)\n IPC_END_MESSAGE_MAP()\n}\n\nvoid URLRequestAutomationJob::OnRequestStarted(\n int tab, int id, const IPC::AutomationURLResponse& response) {\n DLOG(INFO) << \"URLRequestAutomationJob: \" <<\n request_->url().spec() << \" - response started.\";\n set_expected_content_size(response.content_length);\n mime_type_ = response.mime_type;\n\n redirect_url_ = response.redirect_url;\n redirect_status_ = response.redirect_status;\n DCHECK(redirect_status_ == 0 || redirect_status_ == 200 ||\n (redirect_status_ >= 300 && redirect_status_ < 400));\n\n GURL url_for_cookies =\n GURL(redirect_url_.empty() ? request_->url().spec().c_str() :\n redirect_url_.c_str());\n\n URLRequestContext* ctx = request_->context();\n\n if (!response.headers.empty()) {\n headers_ = new net::HttpResponseHeaders(\n net::HttpUtil::AssembleRawHeaders(response.headers.data(),\n response.headers.size()));\n \/\/ Parse and set HTTP cookies.\n const std::string name = \"Set-Cookie\";\n std::string value;\n std::vector<std::string> response_cookies;\n\n void* iter = NULL;\n while (headers_->EnumerateHeader(&iter, name, &value)) {\n if (request_->context()->InterceptCookie(request_, &value))\n response_cookies.push_back(value);\n }\n\n if (response_cookies.size()) {\n if (ctx && ctx->cookie_store() &&\n ctx->cookie_policy()->CanSetCookie(\n url_for_cookies, request_->first_party_for_cookies())) {\n net::CookieOptions options;\n options.set_include_httponly();\n ctx->cookie_store()->SetCookiesWithOptions(url_for_cookies,\n response_cookies,\n options);\n }\n }\n }\n\n if (ctx && ctx->cookie_store() && !response.persistent_cookies.empty() &&\n ctx->cookie_policy()->CanSetCookie(\n url_for_cookies, request_->first_party_for_cookies())) {\n StringTokenizer cookie_parser(response.persistent_cookies, \";\");\n\n while (cookie_parser.GetNext()) {\n net::CookieOptions options;\n ctx->cookie_store()->SetCookieWithOptions(url_for_cookies,\n cookie_parser.token(),\n options);\n }\n }\n\n NotifyHeadersComplete();\n}\n\nvoid URLRequestAutomationJob::OnDataAvailable(\n int tab, int id, const std::string& bytes) {\n DLOG(INFO) << \"URLRequestAutomationJob: \" <<\n request_->url().spec() << \" - data available, Size: \" << bytes.size();\n DCHECK(!bytes.empty());\n\n \/\/ The request completed, and we have all the data.\n \/\/ Clear any IO pending status.\n SetStatus(URLRequestStatus());\n\n if (pending_buf_ && pending_buf_->data()) {\n DCHECK_GE(pending_buf_size_, bytes.size());\n const int bytes_to_copy = std::min(bytes.size(), pending_buf_size_);\n memcpy(pending_buf_->data(), &bytes[0], bytes_to_copy);\n\n pending_buf_ = NULL;\n pending_buf_size_ = 0;\n\n NotifyReadComplete(bytes_to_copy);\n }\n}\n\nvoid URLRequestAutomationJob::OnRequestEnd(\n int tab, int id, const URLRequestStatus& status) {\n DLOG(INFO) << \"URLRequestAutomationJob: \" <<\n request_->url().spec() << \" - request end. Status: \" << status.status();\n\n \/\/ TODO(tommi): When we hit certificate errors, notify the delegate via\n \/\/ OnSSLCertificateError(). Right now we don't have the certificate\n \/\/ so we don't. We could possibly call OnSSLCertificateError with a NULL\n \/\/ certificate, but I'm not sure if all implementations expect it.\n \/\/ if (status.status() == URLRequestStatus::FAILED &&\n \/\/ net::IsCertificateError(status.os_error()) && request_->delegate()) {\n \/\/ request_->delegate()->OnSSLCertificateError(request_, status.os_error(),\n \/\/ NULL);\n \/\/ }\n\n DisconnectFromMessageFilter();\n NotifyDone(status);\n\n \/\/ Reset any pending reads.\n if (pending_buf_) {\n pending_buf_ = NULL;\n pending_buf_size_ = 0;\n NotifyReadComplete(0);\n }\n}\n\nvoid URLRequestAutomationJob::Cleanup() {\n headers_ = NULL;\n mime_type_.erase();\n\n id_ = 0;\n tab_ = 0;\n\n DCHECK(message_filter_ == NULL);\n DisconnectFromMessageFilter();\n\n pending_buf_ = NULL;\n pending_buf_size_ = 0;\n}\n\nvoid URLRequestAutomationJob::StartAsync() {\n DLOG(INFO) << \"URLRequestAutomationJob: start request: \" <<\n (request_ ? request_->url().spec() : \"NULL request\");\n\n \/\/ If the job is cancelled before we got a chance to start it\n \/\/ we have nothing much to do here.\n if (is_done())\n return;\n\n if (!request_) {\n NotifyStartError(URLRequestStatus(URLRequestStatus::FAILED,\n net::ERR_FAILED));\n return;\n }\n\n \/\/ Register this request with automation message filter.\n message_filter_->RegisterRequest(this);\n\n \/\/ Strip unwanted headers.\n std::string new_request_headers(\n net::HttpUtil::StripHeaders(request_->extra_request_headers(),\n kFilteredHeaderStrings,\n arraysize(kFilteredHeaderStrings)));\n\n \/\/ Ensure that we do not send username and password fields in the referrer.\n GURL referrer(request_->GetSanitizedReferrer());\n\n \/\/ The referrer header must be suppressed if the preceding URL was\n \/\/ a secure one and the new one is not.\n if (referrer.SchemeIsSecure() && !request_->url().SchemeIsSecure()) {\n DLOG(INFO) <<\n \"Suppressing referrer header since going from secure to non-secure\";\n referrer = GURL();\n }\n\n \/\/ Ask automation to start this request.\n IPC::AutomationURLRequest automation_request = {\n request_->url().spec(),\n request_->method(),\n referrer.spec(),\n new_request_headers,\n request_->get_upload()\n };\n\n DCHECK(message_filter_);\n message_filter_->Send(new AutomationMsg_RequestStart(0, tab_, id_,\n automation_request));\n}\n\nvoid URLRequestAutomationJob::DisconnectFromMessageFilter() {\n if (message_filter_) {\n message_filter_->UnRegisterRequest(this);\n message_filter_ = NULL;\n }\n}\n<commit_msg>Retry that check for nullness in url request automation job.<commit_after>\/\/ Copyright (c) 2009 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/automation\/url_request_automation_job.h\"\n\n#include \"base\/message_loop.h\"\n#include \"base\/time.h\"\n#include \"chrome\/browser\/automation\/automation_resource_message_filter.h\"\n#include \"chrome\/browser\/renderer_host\/render_view_host.h\"\n#include \"chrome\/browser\/renderer_host\/resource_dispatcher_host.h\"\n#include \"chrome\/browser\/renderer_host\/resource_dispatcher_host_request_info.h\"\n#include \"chrome\/test\/automation\/automation_messages.h\"\n#include \"net\/base\/io_buffer.h\"\n#include \"net\/base\/net_errors.h\"\n#include \"net\/http\/http_util.h\"\n#include \"net\/url_request\/url_request.h\"\n#include \"net\/url_request\/url_request_context.h\"\n\nusing base::Time;\nusing base::TimeDelta;\n\n\/\/ The list of filtered headers that are removed from requests sent via\n\/\/ StartAsync(). These must be lower case.\nstatic const char* kFilteredHeaderStrings[] = {\n \"accept\",\n \"authorization\",\n \"cache-control\",\n \"connection\",\n \"cookie\",\n \"expect\",\n \"if-match\",\n \"if-modified-since\",\n \"if-none-match\",\n \"if-range\",\n \"if-unmodified-since\",\n \"max-forwards\",\n \"proxy-authorization\",\n \"te\",\n \"upgrade\",\n \"via\"\n};\n\n\/\/ This class manages the interception of network requests for automation.\n\/\/ It looks at the request, and creates an intercept job if it indicates\n\/\/ that it should use automation channel.\n\/\/ NOTE: All methods must be called on the IO thread.\nclass AutomationRequestInterceptor : public URLRequest::Interceptor {\n public:\n AutomationRequestInterceptor() {\n URLRequest::RegisterRequestInterceptor(this);\n }\n\n virtual ~AutomationRequestInterceptor() {\n URLRequest::UnregisterRequestInterceptor(this);\n }\n\n \/\/ URLRequest::Interceptor\n virtual URLRequestJob* MaybeIntercept(URLRequest* request);\n\n private:\n DISALLOW_COPY_AND_ASSIGN(AutomationRequestInterceptor);\n};\n\nURLRequestJob* AutomationRequestInterceptor::MaybeIntercept(\n URLRequest* request) {\n if (request->url().SchemeIs(\"http\") || request->url().SchemeIs(\"https\")) {\n ResourceDispatcherHostRequestInfo* request_info =\n ResourceDispatcherHost::InfoForRequest(request);\n if (request_info) {\n AutomationResourceMessageFilter::AutomationDetails details;\n if (AutomationResourceMessageFilter::LookupRegisteredRenderView(\n request_info->child_id(), request_info->route_id(), &details)) {\n URLRequestAutomationJob* job = new URLRequestAutomationJob(request,\n details.tab_handle, details.filter);\n return job;\n }\n }\n }\n\n return NULL;\n}\n\nstatic URLRequest::Interceptor* GetAutomationRequestInterceptor() {\n return Singleton<AutomationRequestInterceptor>::get();\n}\n\nint URLRequestAutomationJob::instance_count_ = 0;\n\nURLRequestAutomationJob::URLRequestAutomationJob(\n URLRequest* request, int tab, AutomationResourceMessageFilter* filter)\n : URLRequestJob(request), id_(0), tab_(tab), message_filter_(filter),\n pending_buf_size_(0), redirect_status_(0) {\n DLOG(INFO) << \"URLRequestAutomationJob create. Count: \" << ++instance_count_;\n if (message_filter_) {\n id_ = message_filter_->NewRequestId();\n DCHECK(id_);\n } else {\n NOTREACHED();\n }\n}\n\nURLRequestAutomationJob::~URLRequestAutomationJob() {\n DLOG(INFO) << \"URLRequestAutomationJob delete. Count: \" << --instance_count_;\n Cleanup();\n}\n\nbool URLRequestAutomationJob::InitializeInterceptor() {\n \/\/ AutomationRequestInterceptor will register itself when it\n \/\/ is first created.\n URLRequest::Interceptor* interceptor = GetAutomationRequestInterceptor();\n return (interceptor != NULL);\n}\n\n\/\/ URLRequestJob Implementation.\nvoid URLRequestAutomationJob::Start() {\n \/\/ Start reading asynchronously so that all error reporting and data\n \/\/ callbacks happen as they would for network requests.\n MessageLoop::current()->PostTask(FROM_HERE, NewRunnableMethod(\n this, &URLRequestAutomationJob::StartAsync));\n}\n\nvoid URLRequestAutomationJob::Kill() {\n if (message_filter_.get()) {\n message_filter_->Send(new AutomationMsg_RequestEnd(0, tab_, id_,\n URLRequestStatus(URLRequestStatus::CANCELED, 0)));\n }\n DisconnectFromMessageFilter();\n URLRequestJob::Kill();\n}\n\nbool URLRequestAutomationJob::ReadRawData(\n net::IOBuffer* buf, int buf_size, int* bytes_read) {\n DLOG(INFO) << \"URLRequestAutomationJob: \" <<\n request_->url().spec() << \" - read pending: \" << buf_size;\n pending_buf_ = buf;\n pending_buf_size_ = buf_size;\n\n message_filter_->Send(new AutomationMsg_RequestRead(0, tab_, id_,\n buf_size));\n SetStatus(URLRequestStatus(URLRequestStatus::IO_PENDING, 0));\n return false;\n}\n\nbool URLRequestAutomationJob::GetMimeType(std::string* mime_type) const {\n if (!mime_type_.empty()) {\n *mime_type = mime_type_;\n } else if (headers_) {\n headers_->GetMimeType(mime_type);\n }\n\n return (!mime_type->empty());\n}\n\nbool URLRequestAutomationJob::GetCharset(std::string* charset) {\n if (headers_)\n return headers_->GetCharset(charset);\n return false;\n}\n\nvoid URLRequestAutomationJob::GetResponseInfo(net::HttpResponseInfo* info) {\n if (headers_)\n info->headers = headers_;\n if (request_->url().SchemeIsSecure()) {\n \/\/ Make up a fake certificate for this response since we don't have\n \/\/ access to the real SSL info.\n const char* kCertIssuer = \"Chrome Internal\";\n const int kLifetimeDays = 100;\n\n info->ssl_info.cert =\n new net::X509Certificate(request_->url().GetWithEmptyPath().spec(),\n kCertIssuer,\n Time::Now(),\n Time::Now() +\n TimeDelta::FromDays(kLifetimeDays));\n info->ssl_info.cert_status = 0;\n info->ssl_info.security_bits = 0;\n }\n}\n\nint URLRequestAutomationJob::GetResponseCode() const {\n if (headers_)\n return headers_->response_code();\n\n static const int kDefaultResponseCode = 200;\n return kDefaultResponseCode;\n}\n\nbool URLRequestAutomationJob::IsRedirectResponse(\n GURL* location, int* http_status_code) {\n static const int kDefaultHttpRedirectResponseCode = 301;\n\n if (!redirect_url_.empty()) {\n DLOG_IF(ERROR, redirect_status_ == 0) << \"Missing redirect status?\";\n *http_status_code = redirect_status_ ? redirect_status_ :\n kDefaultHttpRedirectResponseCode;\n *location = GURL(redirect_url_);\n return true;\n } else {\n DCHECK(redirect_status_ == 0)\n << \"Unexpectedly have redirect status but no URL\";\n }\n\n return false;\n}\n\nint URLRequestAutomationJob::MayFilterMessage(const IPC::Message& message) {\n switch (message.type()) {\n case AutomationMsg_RequestStarted::ID:\n case AutomationMsg_RequestData::ID:\n case AutomationMsg_RequestEnd::ID: {\n void* iter = NULL;\n int tab = 0;\n int id = 0;\n if (message.ReadInt(&iter, &tab) && message.ReadInt(&iter, &id)) {\n DCHECK(id);\n return id;\n }\n break;\n }\n }\n\n return 0;\n}\n\nvoid URLRequestAutomationJob::OnMessage(const IPC::Message& message) {\n IPC_BEGIN_MESSAGE_MAP(URLRequestAutomationJob, message)\n IPC_MESSAGE_HANDLER(AutomationMsg_RequestStarted, OnRequestStarted)\n IPC_MESSAGE_HANDLER(AutomationMsg_RequestData, OnDataAvailable)\n IPC_MESSAGE_HANDLER(AutomationMsg_RequestEnd, OnRequestEnd)\n IPC_END_MESSAGE_MAP()\n}\n\nvoid URLRequestAutomationJob::OnRequestStarted(\n int tab, int id, const IPC::AutomationURLResponse& response) {\n DLOG(INFO) << \"URLRequestAutomationJob: \" <<\n request_->url().spec() << \" - response started.\";\n set_expected_content_size(response.content_length);\n mime_type_ = response.mime_type;\n\n redirect_url_ = response.redirect_url;\n redirect_status_ = response.redirect_status;\n DCHECK(redirect_status_ == 0 || redirect_status_ == 200 ||\n (redirect_status_ >= 300 && redirect_status_ < 400));\n\n GURL url_for_cookies =\n GURL(redirect_url_.empty() ? request_->url().spec().c_str() :\n redirect_url_.c_str());\n\n URLRequestContext* ctx = request_->context();\n\n if (!response.headers.empty()) {\n headers_ = new net::HttpResponseHeaders(\n net::HttpUtil::AssembleRawHeaders(response.headers.data(),\n response.headers.size()));\n \/\/ Parse and set HTTP cookies.\n const std::string name = \"Set-Cookie\";\n std::string value;\n std::vector<std::string> response_cookies;\n\n void* iter = NULL;\n while (headers_->EnumerateHeader(&iter, name, &value)) {\n if (request_->context()->InterceptCookie(request_, &value))\n response_cookies.push_back(value);\n }\n\n if (response_cookies.size()) {\n if (ctx && ctx->cookie_store() &&\n ctx->cookie_policy()->CanSetCookie(\n url_for_cookies, request_->first_party_for_cookies())) {\n net::CookieOptions options;\n options.set_include_httponly();\n ctx->cookie_store()->SetCookiesWithOptions(url_for_cookies,\n response_cookies,\n options);\n }\n }\n }\n\n if (ctx && ctx->cookie_store() && !response.persistent_cookies.empty() &&\n ctx->cookie_policy()->CanSetCookie(\n url_for_cookies, request_->first_party_for_cookies())) {\n StringTokenizer cookie_parser(response.persistent_cookies, \";\");\n\n while (cookie_parser.GetNext()) {\n net::CookieOptions options;\n ctx->cookie_store()->SetCookieWithOptions(url_for_cookies,\n cookie_parser.token(),\n options);\n }\n }\n\n NotifyHeadersComplete();\n}\n\nvoid URLRequestAutomationJob::OnDataAvailable(\n int tab, int id, const std::string& bytes) {\n DLOG(INFO) << \"URLRequestAutomationJob: \" <<\n request_->url().spec() << \" - data available, Size: \" << bytes.size();\n DCHECK(!bytes.empty());\n\n \/\/ The request completed, and we have all the data.\n \/\/ Clear any IO pending status.\n SetStatus(URLRequestStatus());\n\n if (pending_buf_ && pending_buf_->data()) {\n DCHECK_GE(pending_buf_size_, bytes.size());\n const int bytes_to_copy = std::min(bytes.size(), pending_buf_size_);\n memcpy(pending_buf_->data(), &bytes[0], bytes_to_copy);\n\n pending_buf_ = NULL;\n pending_buf_size_ = 0;\n\n NotifyReadComplete(bytes_to_copy);\n }\n}\n\nvoid URLRequestAutomationJob::OnRequestEnd(\n int tab, int id, const URLRequestStatus& status) {\n#ifndef NDEBUG\n std::string url;\n if (request_)\n url = request_->url().spec();\n DLOG(INFO) << \"URLRequestAutomationJob: \"\n << url << \" - request end. Status: \" << status.status();\n#endif\n\n \/\/ TODO(tommi): When we hit certificate errors, notify the delegate via\n \/\/ OnSSLCertificateError(). Right now we don't have the certificate\n \/\/ so we don't. We could possibly call OnSSLCertificateError with a NULL\n \/\/ certificate, but I'm not sure if all implementations expect it.\n \/\/ if (status.status() == URLRequestStatus::FAILED &&\n \/\/ net::IsCertificateError(status.os_error()) && request_->delegate()) {\n \/\/ request_->delegate()->OnSSLCertificateError(request_, status.os_error(),\n \/\/ NULL);\n \/\/ }\n\n DisconnectFromMessageFilter();\n NotifyDone(status);\n\n \/\/ Reset any pending reads.\n if (pending_buf_) {\n pending_buf_ = NULL;\n pending_buf_size_ = 0;\n NotifyReadComplete(0);\n }\n}\n\nvoid URLRequestAutomationJob::Cleanup() {\n headers_ = NULL;\n mime_type_.erase();\n\n id_ = 0;\n tab_ = 0;\n\n DCHECK(message_filter_ == NULL);\n DisconnectFromMessageFilter();\n\n pending_buf_ = NULL;\n pending_buf_size_ = 0;\n}\n\nvoid URLRequestAutomationJob::StartAsync() {\n DLOG(INFO) << \"URLRequestAutomationJob: start request: \" <<\n (request_ ? request_->url().spec() : \"NULL request\");\n\n \/\/ If the job is cancelled before we got a chance to start it\n \/\/ we have nothing much to do here.\n if (is_done())\n return;\n\n if (!request_) {\n NotifyStartError(URLRequestStatus(URLRequestStatus::FAILED,\n net::ERR_FAILED));\n return;\n }\n\n \/\/ Register this request with automation message filter.\n message_filter_->RegisterRequest(this);\n\n \/\/ Strip unwanted headers.\n std::string new_request_headers(\n net::HttpUtil::StripHeaders(request_->extra_request_headers(),\n kFilteredHeaderStrings,\n arraysize(kFilteredHeaderStrings)));\n\n \/\/ Ensure that we do not send username and password fields in the referrer.\n GURL referrer(request_->GetSanitizedReferrer());\n\n \/\/ The referrer header must be suppressed if the preceding URL was\n \/\/ a secure one and the new one is not.\n if (referrer.SchemeIsSecure() && !request_->url().SchemeIsSecure()) {\n DLOG(INFO) <<\n \"Suppressing referrer header since going from secure to non-secure\";\n referrer = GURL();\n }\n\n \/\/ Ask automation to start this request.\n IPC::AutomationURLRequest automation_request = {\n request_->url().spec(),\n request_->method(),\n referrer.spec(),\n new_request_headers,\n request_->get_upload()\n };\n\n DCHECK(message_filter_);\n message_filter_->Send(new AutomationMsg_RequestStart(0, tab_, id_,\n automation_request));\n}\n\nvoid URLRequestAutomationJob::DisconnectFromMessageFilter() {\n if (message_filter_) {\n message_filter_->UnRegisterRequest(this);\n message_filter_ = NULL;\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2009 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/automation\/url_request_automation_job.h\"\n\n#include \"base\/message_loop.h\"\n#include \"base\/time.h\"\n#include \"chrome\/browser\/automation\/automation_resource_message_filter.h\"\n#include \"chrome\/browser\/renderer_host\/render_view_host.h\"\n#include \"chrome\/browser\/renderer_host\/resource_dispatcher_host.h\"\n#include \"chrome\/browser\/renderer_host\/resource_dispatcher_host_request_info.h\"\n#include \"chrome\/test\/automation\/automation_messages.h\"\n#include \"net\/base\/io_buffer.h\"\n#include \"net\/base\/net_errors.h\"\n#include \"net\/http\/http_util.h\"\n#include \"net\/url_request\/url_request.h\"\n#include \"net\/url_request\/url_request_context.h\"\n\nusing base::Time;\nusing base::TimeDelta;\n\n\/\/ The list of filtered headers that are removed from requests sent via\n\/\/ StartAsync(). These must be lower case.\nstatic const char* kFilteredHeaderStrings[] = {\n \"accept\",\n \"authorization\",\n \"cache-control\",\n \"connection\",\n \"cookie\",\n \"expect\",\n \"if-match\",\n \"if-modified-since\",\n \"if-none-match\",\n \"if-range\",\n \"if-unmodified-since\",\n \"max-forwards\",\n \"proxy-authorization\",\n \"te\",\n \"upgrade\",\n \"via\"\n};\n\n\/\/ This class manages the interception of network requests for automation.\n\/\/ It looks at the request, and creates an intercept job if it indicates\n\/\/ that it should use automation channel.\n\/\/ NOTE: All methods must be called on the IO thread.\nclass AutomationRequestInterceptor : public URLRequest::Interceptor {\n public:\n AutomationRequestInterceptor() {\n URLRequest::RegisterRequestInterceptor(this);\n }\n\n virtual ~AutomationRequestInterceptor() {\n URLRequest::UnregisterRequestInterceptor(this);\n }\n\n \/\/ URLRequest::Interceptor\n virtual URLRequestJob* MaybeIntercept(URLRequest* request);\n\n private:\n DISALLOW_COPY_AND_ASSIGN(AutomationRequestInterceptor);\n};\n\nURLRequestJob* AutomationRequestInterceptor::MaybeIntercept(\n URLRequest* request) {\n if (request->url().SchemeIs(\"http\") || request->url().SchemeIs(\"https\")) {\n ResourceDispatcherHostRequestInfo* request_info =\n ResourceDispatcherHost::InfoForRequest(request);\n if (request_info) {\n AutomationResourceMessageFilter::AutomationDetails details;\n if (AutomationResourceMessageFilter::LookupRegisteredRenderView(\n request_info->child_id(), request_info->route_id(), &details)) {\n URLRequestAutomationJob* job = new URLRequestAutomationJob(request,\n details.tab_handle, details.filter);\n return job;\n }\n }\n }\n\n return NULL;\n}\n\nstatic URLRequest::Interceptor* GetAutomationRequestInterceptor() {\n return Singleton<AutomationRequestInterceptor>::get();\n}\n\nint URLRequestAutomationJob::instance_count_ = 0;\n\nURLRequestAutomationJob::URLRequestAutomationJob(\n URLRequest* request, int tab, AutomationResourceMessageFilter* filter)\n : URLRequestJob(request), id_(0), tab_(tab), message_filter_(filter),\n pending_buf_size_(0), redirect_status_(0) {\n DLOG(INFO) << \"URLRequestAutomationJob create. Count: \" << ++instance_count_;\n if (message_filter_) {\n id_ = message_filter_->NewRequestId();\n DCHECK(id_);\n } else {\n NOTREACHED();\n }\n}\n\nURLRequestAutomationJob::~URLRequestAutomationJob() {\n DLOG(INFO) << \"URLRequestAutomationJob delete. Count: \" << --instance_count_;\n Cleanup();\n}\n\nbool URLRequestAutomationJob::InitializeInterceptor() {\n \/\/ AutomationRequestInterceptor will register itself when it\n \/\/ is first created.\n URLRequest::Interceptor* interceptor = GetAutomationRequestInterceptor();\n return (interceptor != NULL);\n}\n\n\/\/ URLRequestJob Implementation.\nvoid URLRequestAutomationJob::Start() {\n \/\/ Start reading asynchronously so that all error reporting and data\n \/\/ callbacks happen as they would for network requests.\n MessageLoop::current()->PostTask(FROM_HERE, NewRunnableMethod(\n this, &URLRequestAutomationJob::StartAsync));\n}\n\nvoid URLRequestAutomationJob::Kill() {\n if (message_filter_.get()) {\n message_filter_->Send(new AutomationMsg_RequestEnd(0, tab_, id_,\n URLRequestStatus(URLRequestStatus::CANCELED, 0)));\n }\n DisconnectFromMessageFilter();\n URLRequestJob::Kill();\n}\n\nbool URLRequestAutomationJob::ReadRawData(\n net::IOBuffer* buf, int buf_size, int* bytes_read) {\n DLOG(INFO) << \"URLRequestAutomationJob: \" <<\n request_->url().spec() << \" - read pending: \" << buf_size;\n pending_buf_ = buf;\n pending_buf_size_ = buf_size;\n\n message_filter_->Send(new AutomationMsg_RequestRead(0, tab_, id_,\n buf_size));\n SetStatus(URLRequestStatus(URLRequestStatus::IO_PENDING, 0));\n return false;\n}\n\nbool URLRequestAutomationJob::GetMimeType(std::string* mime_type) const {\n if (!mime_type_.empty()) {\n *mime_type = mime_type_;\n } else if (headers_) {\n headers_->GetMimeType(mime_type);\n }\n\n return (!mime_type->empty());\n}\n\nbool URLRequestAutomationJob::GetCharset(std::string* charset) {\n if (headers_)\n return headers_->GetCharset(charset);\n return false;\n}\n\nvoid URLRequestAutomationJob::GetResponseInfo(net::HttpResponseInfo* info) {\n if (headers_)\n info->headers = headers_;\n if (request_->url().SchemeIsSecure()) {\n \/\/ Make up a fake certificate for this response since we don't have\n \/\/ access to the real SSL info.\n const char* kCertIssuer = \"Chrome Internal\";\n const int kLifetimeDays = 100;\n\n info->ssl_info.cert =\n new net::X509Certificate(request_->url().GetWithEmptyPath().spec(),\n kCertIssuer,\n Time::Now(),\n Time::Now() +\n TimeDelta::FromDays(kLifetimeDays));\n info->ssl_info.cert_status = 0;\n info->ssl_info.security_bits = 0;\n }\n}\n\nint URLRequestAutomationJob::GetResponseCode() const {\n if (headers_)\n return headers_->response_code();\n\n static const int kDefaultResponseCode = 200;\n return kDefaultResponseCode;\n}\n\nbool URLRequestAutomationJob::IsRedirectResponse(\n GURL* location, int* http_status_code) {\n static const int kDefaultHttpRedirectResponseCode = 301;\n\n if (!redirect_url_.empty()) {\n DLOG_IF(ERROR, redirect_status_ == 0) << \"Missing redirect status?\";\n *http_status_code = redirect_status_ ? redirect_status_ :\n kDefaultHttpRedirectResponseCode;\n *location = GURL(redirect_url_);\n return true;\n } else {\n DCHECK(redirect_status_ == 0)\n << \"Unexpectedly have redirect status but no URL\";\n }\n\n return false;\n}\n\nint URLRequestAutomationJob::MayFilterMessage(const IPC::Message& message) {\n switch (message.type()) {\n case AutomationMsg_RequestStarted::ID:\n case AutomationMsg_RequestData::ID:\n case AutomationMsg_RequestEnd::ID: {\n void* iter = NULL;\n int tab = 0;\n int id = 0;\n if (message.ReadInt(&iter, &tab) && message.ReadInt(&iter, &id)) {\n DCHECK(id);\n return id;\n }\n break;\n }\n }\n\n return 0;\n}\n\nvoid URLRequestAutomationJob::OnMessage(const IPC::Message& message) {\n IPC_BEGIN_MESSAGE_MAP(URLRequestAutomationJob, message)\n IPC_MESSAGE_HANDLER(AutomationMsg_RequestStarted, OnRequestStarted)\n IPC_MESSAGE_HANDLER(AutomationMsg_RequestData, OnDataAvailable)\n IPC_MESSAGE_HANDLER(AutomationMsg_RequestEnd, OnRequestEnd)\n IPC_END_MESSAGE_MAP()\n}\n\nvoid URLRequestAutomationJob::OnRequestStarted(\n int tab, int id, const IPC::AutomationURLResponse& response) {\n DLOG(INFO) << \"URLRequestAutomationJob: \" <<\n request_->url().spec() << \" - response started.\";\n set_expected_content_size(response.content_length);\n mime_type_ = response.mime_type;\n\n redirect_url_ = response.redirect_url;\n redirect_status_ = response.redirect_status;\n DCHECK(redirect_status_ == 0 || redirect_status_ == 200 ||\n (redirect_status_ >= 300 && redirect_status_ < 400));\n\n GURL url_for_cookies =\n GURL(redirect_url_.empty() ? request_->url().spec().c_str() :\n redirect_url_.c_str());\n\n URLRequestContext* ctx = request_->context();\n\n if (!response.headers.empty()) {\n headers_ = new net::HttpResponseHeaders(\n net::HttpUtil::AssembleRawHeaders(response.headers.data(),\n response.headers.size()));\n \/\/ Parse and set HTTP cookies.\n const std::string name = \"Set-Cookie\";\n std::string value;\n std::vector<std::string> response_cookies;\n\n void* iter = NULL;\n while (headers_->EnumerateHeader(&iter, name, &value)) {\n if (request_->context()->InterceptCookie(request_, &value))\n response_cookies.push_back(value);\n }\n\n if (response_cookies.size()) {\n if (ctx && ctx->cookie_store() &&\n ctx->cookie_policy()->CanSetCookie(\n url_for_cookies, request_->first_party_for_cookies())) {\n net::CookieOptions options;\n options.set_include_httponly();\n ctx->cookie_store()->SetCookiesWithOptions(url_for_cookies,\n response_cookies,\n options);\n }\n }\n }\n\n if (ctx && ctx->cookie_store() && !response.persistent_cookies.empty() &&\n ctx->cookie_policy()->CanSetCookie(\n url_for_cookies, request_->first_party_for_cookies())) {\n StringTokenizer cookie_parser(response.persistent_cookies, \";\");\n\n while (cookie_parser.GetNext()) {\n net::CookieOptions options;\n ctx->cookie_store()->SetCookieWithOptions(url_for_cookies,\n cookie_parser.token(),\n options);\n }\n }\n\n NotifyHeadersComplete();\n}\n\nvoid URLRequestAutomationJob::OnDataAvailable(\n int tab, int id, const std::string& bytes) {\n DLOG(INFO) << \"URLRequestAutomationJob: \" <<\n request_->url().spec() << \" - data available, Size: \" << bytes.size();\n DCHECK(!bytes.empty());\n\n \/\/ The request completed, and we have all the data.\n \/\/ Clear any IO pending status.\n SetStatus(URLRequestStatus());\n\n if (pending_buf_ && pending_buf_->data()) {\n DCHECK_GE(pending_buf_size_, bytes.size());\n const int bytes_to_copy = std::min(bytes.size(), pending_buf_size_);\n memcpy(pending_buf_->data(), &bytes[0], bytes_to_copy);\n\n pending_buf_ = NULL;\n pending_buf_size_ = 0;\n\n NotifyReadComplete(bytes_to_copy);\n }\n}\n\nvoid URLRequestAutomationJob::OnRequestEnd(\n int tab, int id, const URLRequestStatus& status) {\n DLOG(INFO) << \"URLRequestAutomationJob: \" <<\n request_->url().spec() << \" - request end. Status: \" << status.status();\n\n \/\/ TODO(tommi): When we hit certificate errors, notify the delegate via\n \/\/ OnSSLCertificateError(). Right now we don't have the certificate\n \/\/ so we don't. We could possibly call OnSSLCertificateError with a NULL\n \/\/ certificate, but I'm not sure if all implementations expect it.\n \/\/ if (status.status() == URLRequestStatus::FAILED &&\n \/\/ net::IsCertificateError(status.os_error()) && request_->delegate()) {\n \/\/ request_->delegate()->OnSSLCertificateError(request_, status.os_error(),\n \/\/ NULL);\n \/\/ }\n\n DisconnectFromMessageFilter();\n NotifyDone(status);\n\n \/\/ Reset any pending reads.\n if (pending_buf_) {\n pending_buf_ = NULL;\n pending_buf_size_ = 0;\n NotifyReadComplete(0);\n }\n}\n\nvoid URLRequestAutomationJob::Cleanup() {\n headers_ = NULL;\n mime_type_.erase();\n\n id_ = 0;\n tab_ = 0;\n\n DCHECK(message_filter_ == NULL);\n DisconnectFromMessageFilter();\n\n pending_buf_ = NULL;\n pending_buf_size_ = 0;\n}\n\nvoid URLRequestAutomationJob::StartAsync() {\n DLOG(INFO) << \"URLRequestAutomationJob: start request: \" <<\n (request_ ? request_->url().spec() : \"NULL request\");\n\n \/\/ If the job is cancelled before we got a chance to start it\n \/\/ we have nothing much to do here.\n if (is_done())\n return;\n\n if (!request_) {\n NotifyStartError(URLRequestStatus(URLRequestStatus::FAILED,\n net::ERR_FAILED));\n return;\n }\n\n \/\/ Register this request with automation message filter.\n message_filter_->RegisterRequest(this);\n\n \/\/ Strip unwanted headers.\n std::string new_request_headers(\n net::HttpUtil::StripHeaders(request_->extra_request_headers(),\n kFilteredHeaderStrings,\n arraysize(kFilteredHeaderStrings)));\n\n \/\/ Ensure that we do not send username and password fields in the referrer.\n GURL referrer(request_->GetSanitizedReferrer());\n\n \/\/ The referrer header must be suppressed if the preceding URL was\n \/\/ a secure one and the new one is not.\n if (referrer.SchemeIsSecure() && !request_->url().SchemeIsSecure()) {\n DLOG(INFO) <<\n \"Suppressing referrer header since going from secure to non-secure\";\n referrer = GURL();\n }\n\n \/\/ Ask automation to start this request.\n IPC::AutomationURLRequest automation_request = {\n request_->url().spec(),\n request_->method(),\n referrer.spec(),\n new_request_headers,\n request_->get_upload()\n };\n\n DCHECK(message_filter_);\n message_filter_->Send(new AutomationMsg_RequestStart(0, tab_, id_,\n automation_request));\n}\n\nvoid URLRequestAutomationJob::DisconnectFromMessageFilter() {\n if (message_filter_) {\n message_filter_->UnRegisterRequest(this);\n message_filter_ = NULL;\n }\n}\n<commit_msg>Retry that check for nullness in url request automation job.<commit_after>\/\/ Copyright (c) 2009 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/automation\/url_request_automation_job.h\"\n\n#include \"base\/message_loop.h\"\n#include \"base\/time.h\"\n#include \"chrome\/browser\/automation\/automation_resource_message_filter.h\"\n#include \"chrome\/browser\/renderer_host\/render_view_host.h\"\n#include \"chrome\/browser\/renderer_host\/resource_dispatcher_host.h\"\n#include \"chrome\/browser\/renderer_host\/resource_dispatcher_host_request_info.h\"\n#include \"chrome\/test\/automation\/automation_messages.h\"\n#include \"net\/base\/io_buffer.h\"\n#include \"net\/base\/net_errors.h\"\n#include \"net\/http\/http_util.h\"\n#include \"net\/url_request\/url_request.h\"\n#include \"net\/url_request\/url_request_context.h\"\n\nusing base::Time;\nusing base::TimeDelta;\n\n\/\/ The list of filtered headers that are removed from requests sent via\n\/\/ StartAsync(). These must be lower case.\nstatic const char* kFilteredHeaderStrings[] = {\n \"accept\",\n \"authorization\",\n \"cache-control\",\n \"connection\",\n \"cookie\",\n \"expect\",\n \"if-match\",\n \"if-modified-since\",\n \"if-none-match\",\n \"if-range\",\n \"if-unmodified-since\",\n \"max-forwards\",\n \"proxy-authorization\",\n \"te\",\n \"upgrade\",\n \"via\"\n};\n\n\/\/ This class manages the interception of network requests for automation.\n\/\/ It looks at the request, and creates an intercept job if it indicates\n\/\/ that it should use automation channel.\n\/\/ NOTE: All methods must be called on the IO thread.\nclass AutomationRequestInterceptor : public URLRequest::Interceptor {\n public:\n AutomationRequestInterceptor() {\n URLRequest::RegisterRequestInterceptor(this);\n }\n\n virtual ~AutomationRequestInterceptor() {\n URLRequest::UnregisterRequestInterceptor(this);\n }\n\n \/\/ URLRequest::Interceptor\n virtual URLRequestJob* MaybeIntercept(URLRequest* request);\n\n private:\n DISALLOW_COPY_AND_ASSIGN(AutomationRequestInterceptor);\n};\n\nURLRequestJob* AutomationRequestInterceptor::MaybeIntercept(\n URLRequest* request) {\n if (request->url().SchemeIs(\"http\") || request->url().SchemeIs(\"https\")) {\n ResourceDispatcherHostRequestInfo* request_info =\n ResourceDispatcherHost::InfoForRequest(request);\n if (request_info) {\n AutomationResourceMessageFilter::AutomationDetails details;\n if (AutomationResourceMessageFilter::LookupRegisteredRenderView(\n request_info->child_id(), request_info->route_id(), &details)) {\n URLRequestAutomationJob* job = new URLRequestAutomationJob(request,\n details.tab_handle, details.filter);\n return job;\n }\n }\n }\n\n return NULL;\n}\n\nstatic URLRequest::Interceptor* GetAutomationRequestInterceptor() {\n return Singleton<AutomationRequestInterceptor>::get();\n}\n\nint URLRequestAutomationJob::instance_count_ = 0;\n\nURLRequestAutomationJob::URLRequestAutomationJob(\n URLRequest* request, int tab, AutomationResourceMessageFilter* filter)\n : URLRequestJob(request), id_(0), tab_(tab), message_filter_(filter),\n pending_buf_size_(0), redirect_status_(0) {\n DLOG(INFO) << \"URLRequestAutomationJob create. Count: \" << ++instance_count_;\n if (message_filter_) {\n id_ = message_filter_->NewRequestId();\n DCHECK(id_);\n } else {\n NOTREACHED();\n }\n}\n\nURLRequestAutomationJob::~URLRequestAutomationJob() {\n DLOG(INFO) << \"URLRequestAutomationJob delete. Count: \" << --instance_count_;\n Cleanup();\n}\n\nbool URLRequestAutomationJob::InitializeInterceptor() {\n \/\/ AutomationRequestInterceptor will register itself when it\n \/\/ is first created.\n URLRequest::Interceptor* interceptor = GetAutomationRequestInterceptor();\n return (interceptor != NULL);\n}\n\n\/\/ URLRequestJob Implementation.\nvoid URLRequestAutomationJob::Start() {\n \/\/ Start reading asynchronously so that all error reporting and data\n \/\/ callbacks happen as they would for network requests.\n MessageLoop::current()->PostTask(FROM_HERE, NewRunnableMethod(\n this, &URLRequestAutomationJob::StartAsync));\n}\n\nvoid URLRequestAutomationJob::Kill() {\n if (message_filter_.get()) {\n message_filter_->Send(new AutomationMsg_RequestEnd(0, tab_, id_,\n URLRequestStatus(URLRequestStatus::CANCELED, 0)));\n }\n DisconnectFromMessageFilter();\n URLRequestJob::Kill();\n}\n\nbool URLRequestAutomationJob::ReadRawData(\n net::IOBuffer* buf, int buf_size, int* bytes_read) {\n DLOG(INFO) << \"URLRequestAutomationJob: \" <<\n request_->url().spec() << \" - read pending: \" << buf_size;\n pending_buf_ = buf;\n pending_buf_size_ = buf_size;\n\n message_filter_->Send(new AutomationMsg_RequestRead(0, tab_, id_,\n buf_size));\n SetStatus(URLRequestStatus(URLRequestStatus::IO_PENDING, 0));\n return false;\n}\n\nbool URLRequestAutomationJob::GetMimeType(std::string* mime_type) const {\n if (!mime_type_.empty()) {\n *mime_type = mime_type_;\n } else if (headers_) {\n headers_->GetMimeType(mime_type);\n }\n\n return (!mime_type->empty());\n}\n\nbool URLRequestAutomationJob::GetCharset(std::string* charset) {\n if (headers_)\n return headers_->GetCharset(charset);\n return false;\n}\n\nvoid URLRequestAutomationJob::GetResponseInfo(net::HttpResponseInfo* info) {\n if (headers_)\n info->headers = headers_;\n if (request_->url().SchemeIsSecure()) {\n \/\/ Make up a fake certificate for this response since we don't have\n \/\/ access to the real SSL info.\n const char* kCertIssuer = \"Chrome Internal\";\n const int kLifetimeDays = 100;\n\n info->ssl_info.cert =\n new net::X509Certificate(request_->url().GetWithEmptyPath().spec(),\n kCertIssuer,\n Time::Now(),\n Time::Now() +\n TimeDelta::FromDays(kLifetimeDays));\n info->ssl_info.cert_status = 0;\n info->ssl_info.security_bits = 0;\n }\n}\n\nint URLRequestAutomationJob::GetResponseCode() const {\n if (headers_)\n return headers_->response_code();\n\n static const int kDefaultResponseCode = 200;\n return kDefaultResponseCode;\n}\n\nbool URLRequestAutomationJob::IsRedirectResponse(\n GURL* location, int* http_status_code) {\n static const int kDefaultHttpRedirectResponseCode = 301;\n\n if (!redirect_url_.empty()) {\n DLOG_IF(ERROR, redirect_status_ == 0) << \"Missing redirect status?\";\n *http_status_code = redirect_status_ ? redirect_status_ :\n kDefaultHttpRedirectResponseCode;\n *location = GURL(redirect_url_);\n return true;\n } else {\n DCHECK(redirect_status_ == 0)\n << \"Unexpectedly have redirect status but no URL\";\n }\n\n return false;\n}\n\nint URLRequestAutomationJob::MayFilterMessage(const IPC::Message& message) {\n switch (message.type()) {\n case AutomationMsg_RequestStarted::ID:\n case AutomationMsg_RequestData::ID:\n case AutomationMsg_RequestEnd::ID: {\n void* iter = NULL;\n int tab = 0;\n int id = 0;\n if (message.ReadInt(&iter, &tab) && message.ReadInt(&iter, &id)) {\n DCHECK(id);\n return id;\n }\n break;\n }\n }\n\n return 0;\n}\n\nvoid URLRequestAutomationJob::OnMessage(const IPC::Message& message) {\n IPC_BEGIN_MESSAGE_MAP(URLRequestAutomationJob, message)\n IPC_MESSAGE_HANDLER(AutomationMsg_RequestStarted, OnRequestStarted)\n IPC_MESSAGE_HANDLER(AutomationMsg_RequestData, OnDataAvailable)\n IPC_MESSAGE_HANDLER(AutomationMsg_RequestEnd, OnRequestEnd)\n IPC_END_MESSAGE_MAP()\n}\n\nvoid URLRequestAutomationJob::OnRequestStarted(\n int tab, int id, const IPC::AutomationURLResponse& response) {\n DLOG(INFO) << \"URLRequestAutomationJob: \" <<\n request_->url().spec() << \" - response started.\";\n set_expected_content_size(response.content_length);\n mime_type_ = response.mime_type;\n\n redirect_url_ = response.redirect_url;\n redirect_status_ = response.redirect_status;\n DCHECK(redirect_status_ == 0 || redirect_status_ == 200 ||\n (redirect_status_ >= 300 && redirect_status_ < 400));\n\n GURL url_for_cookies =\n GURL(redirect_url_.empty() ? request_->url().spec().c_str() :\n redirect_url_.c_str());\n\n URLRequestContext* ctx = request_->context();\n\n if (!response.headers.empty()) {\n headers_ = new net::HttpResponseHeaders(\n net::HttpUtil::AssembleRawHeaders(response.headers.data(),\n response.headers.size()));\n \/\/ Parse and set HTTP cookies.\n const std::string name = \"Set-Cookie\";\n std::string value;\n std::vector<std::string> response_cookies;\n\n void* iter = NULL;\n while (headers_->EnumerateHeader(&iter, name, &value)) {\n if (request_->context()->InterceptCookie(request_, &value))\n response_cookies.push_back(value);\n }\n\n if (response_cookies.size()) {\n if (ctx && ctx->cookie_store() &&\n ctx->cookie_policy()->CanSetCookie(\n url_for_cookies, request_->first_party_for_cookies())) {\n net::CookieOptions options;\n options.set_include_httponly();\n ctx->cookie_store()->SetCookiesWithOptions(url_for_cookies,\n response_cookies,\n options);\n }\n }\n }\n\n if (ctx && ctx->cookie_store() && !response.persistent_cookies.empty() &&\n ctx->cookie_policy()->CanSetCookie(\n url_for_cookies, request_->first_party_for_cookies())) {\n StringTokenizer cookie_parser(response.persistent_cookies, \";\");\n\n while (cookie_parser.GetNext()) {\n net::CookieOptions options;\n ctx->cookie_store()->SetCookieWithOptions(url_for_cookies,\n cookie_parser.token(),\n options);\n }\n }\n\n NotifyHeadersComplete();\n}\n\nvoid URLRequestAutomationJob::OnDataAvailable(\n int tab, int id, const std::string& bytes) {\n DLOG(INFO) << \"URLRequestAutomationJob: \" <<\n request_->url().spec() << \" - data available, Size: \" << bytes.size();\n DCHECK(!bytes.empty());\n\n \/\/ The request completed, and we have all the data.\n \/\/ Clear any IO pending status.\n SetStatus(URLRequestStatus());\n\n if (pending_buf_ && pending_buf_->data()) {\n DCHECK_GE(pending_buf_size_, bytes.size());\n const int bytes_to_copy = std::min(bytes.size(), pending_buf_size_);\n memcpy(pending_buf_->data(), &bytes[0], bytes_to_copy);\n\n pending_buf_ = NULL;\n pending_buf_size_ = 0;\n\n NotifyReadComplete(bytes_to_copy);\n }\n}\n\nvoid URLRequestAutomationJob::OnRequestEnd(\n int tab, int id, const URLRequestStatus& status) {\n#ifndef NDEBUG\n std::string url;\n if (request_)\n url = request_->url().spec();\n DLOG(INFO) << \"URLRequestAutomationJob: \"\n << url << \" - request end. Status: \" << status.status();\n#endif\n\n \/\/ TODO(tommi): When we hit certificate errors, notify the delegate via\n \/\/ OnSSLCertificateError(). Right now we don't have the certificate\n \/\/ so we don't. We could possibly call OnSSLCertificateError with a NULL\n \/\/ certificate, but I'm not sure if all implementations expect it.\n \/\/ if (status.status() == URLRequestStatus::FAILED &&\n \/\/ net::IsCertificateError(status.os_error()) && request_->delegate()) {\n \/\/ request_->delegate()->OnSSLCertificateError(request_, status.os_error(),\n \/\/ NULL);\n \/\/ }\n\n DisconnectFromMessageFilter();\n NotifyDone(status);\n\n \/\/ Reset any pending reads.\n if (pending_buf_) {\n pending_buf_ = NULL;\n pending_buf_size_ = 0;\n NotifyReadComplete(0);\n }\n}\n\nvoid URLRequestAutomationJob::Cleanup() {\n headers_ = NULL;\n mime_type_.erase();\n\n id_ = 0;\n tab_ = 0;\n\n DCHECK(message_filter_ == NULL);\n DisconnectFromMessageFilter();\n\n pending_buf_ = NULL;\n pending_buf_size_ = 0;\n}\n\nvoid URLRequestAutomationJob::StartAsync() {\n DLOG(INFO) << \"URLRequestAutomationJob: start request: \" <<\n (request_ ? request_->url().spec() : \"NULL request\");\n\n \/\/ If the job is cancelled before we got a chance to start it\n \/\/ we have nothing much to do here.\n if (is_done())\n return;\n\n if (!request_) {\n NotifyStartError(URLRequestStatus(URLRequestStatus::FAILED,\n net::ERR_FAILED));\n return;\n }\n\n \/\/ Register this request with automation message filter.\n message_filter_->RegisterRequest(this);\n\n \/\/ Strip unwanted headers.\n std::string new_request_headers(\n net::HttpUtil::StripHeaders(request_->extra_request_headers(),\n kFilteredHeaderStrings,\n arraysize(kFilteredHeaderStrings)));\n\n \/\/ Ensure that we do not send username and password fields in the referrer.\n GURL referrer(request_->GetSanitizedReferrer());\n\n \/\/ The referrer header must be suppressed if the preceding URL was\n \/\/ a secure one and the new one is not.\n if (referrer.SchemeIsSecure() && !request_->url().SchemeIsSecure()) {\n DLOG(INFO) <<\n \"Suppressing referrer header since going from secure to non-secure\";\n referrer = GURL();\n }\n\n \/\/ Ask automation to start this request.\n IPC::AutomationURLRequest automation_request = {\n request_->url().spec(),\n request_->method(),\n referrer.spec(),\n new_request_headers,\n request_->get_upload()\n };\n\n DCHECK(message_filter_);\n message_filter_->Send(new AutomationMsg_RequestStart(0, tab_, id_,\n automation_request));\n}\n\nvoid URLRequestAutomationJob::DisconnectFromMessageFilter() {\n if (message_filter_) {\n message_filter_->UnRegisterRequest(this);\n message_filter_ = NULL;\n }\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"IfNode.h\"\n#include \"..\/Parser.h\"\n\n#include <assert.h>\n\nnamespace Language {\n IfNode* IfNode::parse(Parser& parser) {\n IfNode* node = new IfNode();\n\n node->setStatement(true);\n\n assert(parser.next().type() == Token::Type::KeywordIf);\n\n \/\/ parse the condition\n node->_conditionNode = parser.parseExpression();\n\n parser.parseNewline();\n\n \/\/ and now, parse the body\n while (true) {\n Token t = parser.peek();\n\n if (t.type() == Token::Type::KeywordEnd || t.type() == Token::Type::KeywordElse) {\n break;\n }\n\n node->addChild(parser.parseStatement());\n }\n\n if (parser.peek().type() == Token::Type::KeywordElse) {\n node->_elseNode = ElseNode::parse(parser);\n } else {\n assert(parser.next().type() == Token::Type::KeywordEnd);\n }\n\n return node;\n }\n\n ASTNode* IfNode::parseTailing(Parser& parser, ASTNode* node) {\n if (parser.peek().type() != Token::Type::KeywordIf) {\n return node;\n }\n\n assert(parser.next().type() == Token::Type::KeywordIf);\n\n IfNode* ifNode = new IfNode();\n\n ifNode->addChild(node);\n\n ifNode->setCondition(parser.parseExpression());\n\n return ifNode;\n }\n\n IfNode::IfNode() : _elseNode(NULL) {\n }\n\n std::string IfNode::name() const {\n return \"If\";\n }\n\n ASTNode* IfNode::condition() const {\n return _conditionNode;\n }\n\n void IfNode::setCondition(ASTNode* node) {\n _conditionNode = node;\n }\n\n ElseNode* IfNode::elseStatement() const {\n return _elseNode;\n }\n\n void IfNode::codeGenCSource(CSourceContext& context) {\n context.current()->print(\"if (\");\n\n this->condition()->codeGenCSource(context);\n\n context.current()->printLineAndIndent(\") {\");\n\n this->codeGenCSourceForChildren(context);\n\n if (this->elseStatement()) {\n context.current()->outdentAndPrintLine(\"} else {\");\n context.current()->increaseIndentation();\n\n this->elseStatement()->codeGenCSourceForChildren(context);\n }\n\n context.current()->outdentAndPrintLine(\"}\");\n }\n}\n<commit_msg>Hack to if codegen to remove compiler warning<commit_after>#include \"IfNode.h\"\n#include \"..\/Parser.h\"\n\n#include <assert.h>\n\nnamespace Language {\n IfNode* IfNode::parse(Parser& parser) {\n IfNode* node = new IfNode();\n\n node->setStatement(true);\n\n assert(parser.next().type() == Token::Type::KeywordIf);\n\n \/\/ parse the condition\n node->_conditionNode = parser.parseExpression();\n\n parser.parseNewline();\n\n \/\/ and now, parse the body\n while (true) {\n Token t = parser.peek();\n\n if (t.type() == Token::Type::KeywordEnd || t.type() == Token::Type::KeywordElse) {\n break;\n }\n\n node->addChild(parser.parseStatement());\n }\n\n if (parser.peek().type() == Token::Type::KeywordElse) {\n node->_elseNode = ElseNode::parse(parser);\n } else {\n assert(parser.next().type() == Token::Type::KeywordEnd);\n }\n\n return node;\n }\n\n ASTNode* IfNode::parseTailing(Parser& parser, ASTNode* node) {\n if (parser.peek().type() != Token::Type::KeywordIf) {\n return node;\n }\n\n assert(parser.next().type() == Token::Type::KeywordIf);\n\n IfNode* ifNode = new IfNode();\n\n ifNode->addChild(node);\n\n ifNode->setCondition(parser.parseExpression());\n\n return ifNode;\n }\n\n IfNode::IfNode() : _elseNode(NULL) {\n }\n\n std::string IfNode::name() const {\n return \"If\";\n }\n\n ASTNode* IfNode::condition() const {\n return _conditionNode;\n }\n\n void IfNode::setCondition(ASTNode* node) {\n _conditionNode = node;\n }\n\n ElseNode* IfNode::elseStatement() const {\n return _elseNode;\n }\n\n void IfNode::codeGenCSource(CSourceContext& context) {\n context.current()->print(\"if \");\n\n \/\/ TODO: this is a messy hack to avoid duplicating parenthesis around\n \/\/ operators\n if (this->condition()->nodeName() != \"Operator\") {\n context.current()->print(\"(\");\n }\n\n this->condition()->codeGenCSource(context);\n\n if (this->condition()->nodeName() != \"Operator\") {\n context.current()->print(\")\");\n }\n\n context.current()->printLineAndIndent(\" {\");\n\n this->codeGenCSourceForChildren(context);\n\n if (this->elseStatement()) {\n context.current()->outdentAndPrintLine(\"} else {\");\n context.current()->increaseIndentation();\n\n this->elseStatement()->codeGenCSourceForChildren(context);\n }\n\n context.current()->outdentAndPrintLine(\"}\");\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/******************************************************************************\n\n This source file is part of the tomviz project.\n\n Copyright Kitware, Inc.\n\n This source code is released under the New BSD License, (the \"License\").\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n\n******************************************************************************\/\n\n#include \"ViewMenuManager.h\"\n\n#include \"pqCoreUtilities.h\"\n#include \"pqView.h\"\n#include \"vtkCommand.h\"\n#include \"vtkSMPropertyHelper.h\"\n#include \"vtkSMViewProxy.h\"\n\n#include <QAction>\n#include <QActionGroup>\n#include <QDialog>\n#include <QHBoxLayout>\n#include <QMainWindow>\n#include <QMenu>\n\n#include \"ActiveObjects.h\"\n#include \"Utilities.h\"\n#include \"ViewPropertiesPanel.h\"\n\nnamespace tomviz\n{\n\nViewMenuManager::ViewMenuManager(QMainWindow* mainWindow, QMenu* menu)\n : pqViewMenuManager(mainWindow, menu)\n{\n this->viewPropertiesDialog = new QDialog(mainWindow);\n this->viewPropertiesDialog->setWindowTitle(\"View Properties\");\n ViewPropertiesPanel* panel = new ViewPropertiesPanel(this->viewPropertiesDialog);\n QHBoxLayout *layout = new QHBoxLayout;\n layout->addWidget(panel);\n this->viewPropertiesDialog->setLayout(layout);\n this->connect(this->viewPropertiesDialog, SIGNAL(finished(int)),\n SLOT(viewPropertiesDialogHidden()));\n\n this->showViewPropertiesAction = new QAction(\"View Properties\", this->Menu);\n this->showViewPropertiesAction->setCheckable(true);\n this->connect(this->showViewPropertiesAction, SIGNAL(triggered(bool)),\n SLOT(showViewPropertiesDialog(bool)));\n this->View = ActiveObjects::instance().activeView();\n if (this->View)\n {\n this->ViewObserverId = pqCoreUtilities::connect(\n this->View, vtkCommand::PropertyModifiedEvent,\n this, SLOT(onViewPropertyChanged()));\n }\n this->connect(&ActiveObjects::instance(), SIGNAL(viewChanged(vtkSMViewProxy*)),\n SLOT(onViewChanged()));\n}\n\nvoid ViewMenuManager::buildMenu()\n{\n bool showViewPropertiesChecked = this->showViewPropertiesAction->isChecked();\n bool perspectiveProjectionChecked = true;\n if (this->perspectiveProjectionAction)\n {\n perspectiveProjectionChecked = this->perspectiveProjectionAction->isChecked();\n }\n bool axisGridIsShowing = false;\n if (this->showAxisGridAction)\n {\n axisGridIsShowing = this->showAxisGridAction->isChecked();\n }\n this->showViewPropertiesAction = nullptr; \/\/ The object is about to be deleted\n this->perspectiveProjectionAction = nullptr;\n this->orthographicProjectionAction = nullptr;\n pqViewMenuManager::buildMenu(); \/\/ deletes all prior menu items and repopulates menu\n\n this->Menu->addSeparator();\n \/\/ Projection modes\n QMenu *projectionMenu = this->Menu->addMenu(\"Projection Mode\");\n QActionGroup *projectionGroup = new QActionGroup(this);\n\n this->perspectiveProjectionAction = projectionMenu->addAction(\"Perspective\");\n this->perspectiveProjectionAction->setCheckable(true);\n this->perspectiveProjectionAction->setActionGroup(projectionGroup);\n this->perspectiveProjectionAction->setChecked(perspectiveProjectionChecked);\n this->connect(this->perspectiveProjectionAction, SIGNAL(triggered()),\n SLOT(setProjectionModeToPerspective()));\n this->orthographicProjectionAction = projectionMenu->addAction(\"Orthographic\");\n this->orthographicProjectionAction->setCheckable(true);\n this->orthographicProjectionAction->setActionGroup(projectionGroup);\n this->orthographicProjectionAction->setChecked(!perspectiveProjectionChecked);\n this->connect(this->orthographicProjectionAction, SIGNAL(triggered()),\n SLOT(setProjectionModeToOrthographic()));\n\n this->showAxisGridAction = this->Menu->addAction(\"Show Axis Grid\");\n this->showAxisGridAction->setCheckable(true);\n this->showAxisGridAction->setChecked(axisGridIsShowing);\n this->connect(this->showAxisGridAction, SIGNAL(triggered(bool)),\n SLOT(setShowAxisGrid(bool)));\n\n \/\/ Show view properties\n this->showViewPropertiesAction = new QAction(\"View Properties\", this->Menu);\n this->showViewPropertiesAction->setCheckable(true);\n this->showViewPropertiesAction->setChecked(showViewPropertiesChecked);\n this->connect(this->showViewPropertiesAction, SIGNAL(triggered(bool)),\n SLOT(showViewPropertiesDialog(bool)));\n this->Menu->addSeparator();\n this->Menu->addAction(this->showViewPropertiesAction);\n}\n\nvoid ViewMenuManager::showViewPropertiesDialog(bool show)\n{\n if (show)\n {\n this->viewPropertiesDialog->show();\n }\n else\n {\n this->viewPropertiesDialog->accept();\n }\n}\n\nvoid ViewMenuManager::viewPropertiesDialogHidden()\n{\n this->showViewPropertiesAction->setChecked(false);\n}\n\nvoid ViewMenuManager::setProjectionModeToPerspective()\n{\n int parallel = vtkSMPropertyHelper(this->View, \"CameraParallelProjection\").GetAsInt();\n if (parallel)\n {\n vtkSMPropertyHelper(this->View, \"CameraParallelProjection\").Set(0);\n this->View->UpdateVTKObjects();\n pqView* view = tomviz::convert<pqView*>(this->View);\n if (view)\n {\n view->render();\n }\n }\n}\n\nvoid ViewMenuManager::setProjectionModeToOrthographic()\n{\n int parallel = vtkSMPropertyHelper(this->View, \"CameraParallelProjection\").GetAsInt();\n if (!parallel)\n {\n vtkSMPropertyHelper(this->View, \"CameraParallelProjection\").Set(1);\n this->View->UpdateVTKObjects();\n pqView* view = tomviz::convert<pqView*>(this->View);\n if (view)\n {\n view->render();\n }\n }\n}\n\nvoid ViewMenuManager::onViewPropertyChanged()\n{\n int parallel = vtkSMPropertyHelper(this->View, \"CameraParallelProjection\").GetAsInt();\n if (!this->perspectiveProjectionAction)\n {\n return;\n }\n if (parallel && this->perspectiveProjectionAction->isChecked())\n {\n this->orthographicProjectionAction->setChecked(true);\n }\n else if (!parallel && this->orthographicProjectionAction->isChecked())\n {\n this->perspectiveProjectionAction->setChecked(true);\n }\n}\n\nvoid ViewMenuManager::onViewChanged()\n{\n if (this->View)\n {\n vtkSMPropertyHelper(this->View, \"AxesGrid\").GetAsProxy()\n ->RemoveObserver(this->AxesGridObserverId);\n this->View->RemoveObserver(this->ViewObserverId);\n }\n this->View = ActiveObjects::instance().activeView();\n if (this->View)\n {\n this->ViewObserverId = pqCoreUtilities::connect(\n this->View, vtkCommand::PropertyModifiedEvent,\n this, SLOT(onViewPropertyChanged()));\n this->AxesGridObserverId = pqCoreUtilities::connect(\n vtkSMPropertyHelper(this->View, \"AxesGrid\").GetAsProxy(),\n vtkCommand::PropertyModifiedEvent, this, SLOT(onAxesGridChanged()));\n }\n}\n\nvoid ViewMenuManager::setShowAxisGrid(bool show)\n{\n vtkSMProxy *axesGrid = vtkSMPropertyHelper(this->View, \"AxesGrid\").GetAsProxy();\n int showing = vtkSMPropertyHelper(axesGrid, \"Visibility\").GetAsInt();\n if (showing && !show)\n {\n vtkSMPropertyHelper(axesGrid, \"Visibility\").Set(0);\n }\n else if (!showing && show)\n {\n vtkSMPropertyHelper(axesGrid, \"Visibility\").Set(1);\n }\n axesGrid->UpdateVTKObjects();\n pqView* view = tomviz::convert<pqView*>(this->View);\n if (view)\n {\n view->render();\n }\n}\n\nvoid ViewMenuManager::onAxesGridChanged()\n{\n vtkSMProxy *axesGrid = vtkSMPropertyHelper(this->View, \"AxesGrid\").GetAsProxy();\n int showing = vtkSMPropertyHelper(axesGrid, \"Visibility\").GetAsInt();\n if (showing && !this->showAxisGridAction->isChecked())\n {\n this->showAxisGridAction->setChecked(true);\n }\n else if (!showing && this->showAxisGridAction->isChecked())\n {\n this->showAxisGridAction->setChecked(false);\n }\n}\n\n}\n<commit_msg>Added missing initialization of member variables<commit_after>\/******************************************************************************\n\n This source file is part of the tomviz project.\n\n Copyright Kitware, Inc.\n\n This source code is released under the New BSD License, (the \"License\").\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n\n******************************************************************************\/\n\n#include \"ViewMenuManager.h\"\n\n#include \"pqCoreUtilities.h\"\n#include \"pqView.h\"\n#include \"vtkCommand.h\"\n#include \"vtkSMPropertyHelper.h\"\n#include \"vtkSMViewProxy.h\"\n\n#include <QAction>\n#include <QActionGroup>\n#include <QDialog>\n#include <QHBoxLayout>\n#include <QMainWindow>\n#include <QMenu>\n\n#include \"ActiveObjects.h\"\n#include \"Utilities.h\"\n#include \"ViewPropertiesPanel.h\"\n\nnamespace tomviz\n{\n\nViewMenuManager::ViewMenuManager(QMainWindow* mainWindow, QMenu* menu)\n : pqViewMenuManager(mainWindow, menu), perspectiveProjectionAction(nullptr),\n orthographicProjectionAction(nullptr), showAxisGridAction(nullptr)\n{\n this->viewPropertiesDialog = new QDialog(mainWindow);\n this->viewPropertiesDialog->setWindowTitle(\"View Properties\");\n ViewPropertiesPanel* panel = new ViewPropertiesPanel(this->viewPropertiesDialog);\n QHBoxLayout *layout = new QHBoxLayout;\n layout->addWidget(panel);\n this->viewPropertiesDialog->setLayout(layout);\n this->connect(this->viewPropertiesDialog, SIGNAL(finished(int)),\n SLOT(viewPropertiesDialogHidden()));\n\n this->showViewPropertiesAction = new QAction(\"View Properties\", this->Menu);\n this->showViewPropertiesAction->setCheckable(true);\n this->connect(this->showViewPropertiesAction, SIGNAL(triggered(bool)),\n SLOT(showViewPropertiesDialog(bool)));\n this->View = ActiveObjects::instance().activeView();\n if (this->View)\n {\n this->ViewObserverId = pqCoreUtilities::connect(\n this->View, vtkCommand::PropertyModifiedEvent,\n this, SLOT(onViewPropertyChanged()));\n }\n this->connect(&ActiveObjects::instance(), SIGNAL(viewChanged(vtkSMViewProxy*)),\n SLOT(onViewChanged()));\n}\n\nvoid ViewMenuManager::buildMenu()\n{\n bool showViewPropertiesChecked = this->showViewPropertiesAction->isChecked();\n bool perspectiveProjectionChecked = true;\n if (this->perspectiveProjectionAction)\n {\n perspectiveProjectionChecked = this->perspectiveProjectionAction->isChecked();\n }\n bool axisGridIsShowing = false;\n if (this->showAxisGridAction)\n {\n axisGridIsShowing = this->showAxisGridAction->isChecked();\n }\n this->showViewPropertiesAction = nullptr; \/\/ The object is about to be deleted\n this->perspectiveProjectionAction = nullptr;\n this->orthographicProjectionAction = nullptr;\n pqViewMenuManager::buildMenu(); \/\/ deletes all prior menu items and repopulates menu\n\n this->Menu->addSeparator();\n \/\/ Projection modes\n QMenu *projectionMenu = this->Menu->addMenu(\"Projection Mode\");\n QActionGroup *projectionGroup = new QActionGroup(this);\n\n this->perspectiveProjectionAction = projectionMenu->addAction(\"Perspective\");\n this->perspectiveProjectionAction->setCheckable(true);\n this->perspectiveProjectionAction->setActionGroup(projectionGroup);\n this->perspectiveProjectionAction->setChecked(perspectiveProjectionChecked);\n this->connect(this->perspectiveProjectionAction, SIGNAL(triggered()),\n SLOT(setProjectionModeToPerspective()));\n this->orthographicProjectionAction = projectionMenu->addAction(\"Orthographic\");\n this->orthographicProjectionAction->setCheckable(true);\n this->orthographicProjectionAction->setActionGroup(projectionGroup);\n this->orthographicProjectionAction->setChecked(!perspectiveProjectionChecked);\n this->connect(this->orthographicProjectionAction, SIGNAL(triggered()),\n SLOT(setProjectionModeToOrthographic()));\n\n this->showAxisGridAction = this->Menu->addAction(\"Show Axis Grid\");\n this->showAxisGridAction->setCheckable(true);\n this->showAxisGridAction->setChecked(axisGridIsShowing);\n this->connect(this->showAxisGridAction, SIGNAL(triggered(bool)),\n SLOT(setShowAxisGrid(bool)));\n\n \/\/ Show view properties\n this->showViewPropertiesAction = new QAction(\"View Properties\", this->Menu);\n this->showViewPropertiesAction->setCheckable(true);\n this->showViewPropertiesAction->setChecked(showViewPropertiesChecked);\n this->connect(this->showViewPropertiesAction, SIGNAL(triggered(bool)),\n SLOT(showViewPropertiesDialog(bool)));\n this->Menu->addSeparator();\n this->Menu->addAction(this->showViewPropertiesAction);\n}\n\nvoid ViewMenuManager::showViewPropertiesDialog(bool show)\n{\n if (show)\n {\n this->viewPropertiesDialog->show();\n }\n else\n {\n this->viewPropertiesDialog->accept();\n }\n}\n\nvoid ViewMenuManager::viewPropertiesDialogHidden()\n{\n this->showViewPropertiesAction->setChecked(false);\n}\n\nvoid ViewMenuManager::setProjectionModeToPerspective()\n{\n int parallel = vtkSMPropertyHelper(this->View, \"CameraParallelProjection\").GetAsInt();\n if (parallel)\n {\n vtkSMPropertyHelper(this->View, \"CameraParallelProjection\").Set(0);\n this->View->UpdateVTKObjects();\n pqView* view = tomviz::convert<pqView*>(this->View);\n if (view)\n {\n view->render();\n }\n }\n}\n\nvoid ViewMenuManager::setProjectionModeToOrthographic()\n{\n int parallel = vtkSMPropertyHelper(this->View, \"CameraParallelProjection\").GetAsInt();\n if (!parallel)\n {\n vtkSMPropertyHelper(this->View, \"CameraParallelProjection\").Set(1);\n this->View->UpdateVTKObjects();\n pqView* view = tomviz::convert<pqView*>(this->View);\n if (view)\n {\n view->render();\n }\n }\n}\n\nvoid ViewMenuManager::onViewPropertyChanged()\n{\n if (!this->perspectiveProjectionAction || !this->orthographicProjectionAction)\n {\n return;\n }\n int parallel = vtkSMPropertyHelper(this->View, \"CameraParallelProjection\").GetAsInt();\n if (parallel && this->perspectiveProjectionAction->isChecked())\n {\n this->orthographicProjectionAction->setChecked(true);\n }\n else if (!parallel && this->orthographicProjectionAction->isChecked())\n {\n this->perspectiveProjectionAction->setChecked(true);\n }\n}\n\nvoid ViewMenuManager::onViewChanged()\n{\n if (this->View)\n {\n vtkSMPropertyHelper(this->View, \"AxesGrid\").GetAsProxy()\n ->RemoveObserver(this->AxesGridObserverId);\n this->View->RemoveObserver(this->ViewObserverId);\n }\n this->View = ActiveObjects::instance().activeView();\n if (this->View)\n {\n this->ViewObserverId = pqCoreUtilities::connect(\n this->View, vtkCommand::PropertyModifiedEvent,\n this, SLOT(onViewPropertyChanged()));\n this->AxesGridObserverId = pqCoreUtilities::connect(\n vtkSMPropertyHelper(this->View, \"AxesGrid\").GetAsProxy(),\n vtkCommand::PropertyModifiedEvent, this, SLOT(onAxesGridChanged()));\n }\n}\n\nvoid ViewMenuManager::setShowAxisGrid(bool show)\n{\n vtkSMProxy *axesGrid = vtkSMPropertyHelper(this->View, \"AxesGrid\").GetAsProxy();\n int showing = vtkSMPropertyHelper(axesGrid, \"Visibility\").GetAsInt();\n if (showing && !show)\n {\n vtkSMPropertyHelper(axesGrid, \"Visibility\").Set(0);\n }\n else if (!showing && show)\n {\n vtkSMPropertyHelper(axesGrid, \"Visibility\").Set(1);\n }\n axesGrid->UpdateVTKObjects();\n pqView* view = tomviz::convert<pqView*>(this->View);\n if (view)\n {\n view->render();\n }\n}\n\nvoid ViewMenuManager::onAxesGridChanged()\n{\n vtkSMProxy *axesGrid = vtkSMPropertyHelper(this->View, \"AxesGrid\").GetAsProxy();\n int showing = vtkSMPropertyHelper(axesGrid, \"Visibility\").GetAsInt();\n if (showing && !this->showAxisGridAction->isChecked())\n {\n this->showAxisGridAction->setChecked(true);\n }\n else if (!showing && this->showAxisGridAction->isChecked())\n {\n this->showAxisGridAction->setChecked(false);\n }\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before>#!\/usr\/bin\/env c-script\n\nstruct BP{\n Matrix<double> X;\n Matrix<double> D;\n Matrix<double> S;\n Matrix<double> W;\n Matrix<double> dW;\n Matrix<double> Y;\n Matrix<double> Hd;\n double d;\n void forward(){\n S=W*Y;\n mat_for(Hd)\n X(r,c)=sigm(S(r,c));\n }\n void update(){\n\n mat_for(Hd)\n Hd(r,c)=sigm(S(r,c))*(1-sigm(S(r,c)));\n dW=-2*ary_mul(ary_mul((D-X),Hd),Y);\n }\n void update(Matrix<double>& hW,Matrix<double>& hY){\n mat_for(Hd)\n Hd(r,c)=sigm(S(r,c))*(1-sigm(S(r,c)));\n dW=-2*ary_mul(ary_mul(t(hY*hW),Hd),Y);\n }\n};\n\nint\nmain(){\n SVM svm;\n svm.init(9,2);\n svm.set();\n int n=100000;\n for(int i=0;i<100000;i++){\n svm.update(i,n);\n }\n \n printf(\"L:\\n\");\n svm.L.write(stdout,\"%2.2f\");\n printf(\"w:\\n\");\n svm.w.write(stdout,\"%2.2f\");\n printf(\"LY:%f\\n\",dot(svm.L,svm.Y));\n printf(\"cost:%f\\n\",svm.cost());\n\n \n return 0;\n}\n<commit_msg>update<commit_after>#!\/usr\/bin\/env c-script\n\ndouble\nsigm(double v){\n return 1.0\/(1.0+exp(-v));\n}\nconst Matrix<double>&\nsigm(const Matrix<double>& X){\n Matrix<double> a(X.nr,X.nc);\n mat_for(a)\n a(r,c)=sigm(X(r,c));\n return a;\n}\n\ntemplate<int N>\nstruct BP{\n Matrix<double> X[N+1];\n Matrix<double> D[N];\n Matrix<double> S[N];\n Matrix<double> W[N]; \n double d;\n void init(){\n \n }\n \/\/X[i+1]=sigm(S[i]=W[i]*X[i])\n const Matrix<double>&\n forward(const Matrix<double>& Y){\n X[0]=Y;\n for(int i=0;i<N;i++){\n S[i]=W[i]*X[i];\n X[i+1]=sigm(S);\n }\n return X[N];\n }\n void back(const Matrix<double>& D){\n }\n\n};\n\nint\nmain(){\n BP<1> bp;\n \n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2020 The Orbit Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"FrameTrackOnlineProcessor.h\"\n\n#include <absl\/container\/flat_hash_map.h>\n#include <absl\/container\/flat_hash_set.h>\n\n#include <limits>\n#include <utility>\n\n#include \"OrbitClientData\/FunctionInfoSet.h\"\n#include \"OrbitClientData\/UserDefinedCaptureData.h\"\n#include \"OrbitClientModel\/CaptureData.h\"\n#include \"TimeGraph.h\"\n\nFrameTrackOnlineProcessor::FrameTrackOnlineProcessor(const CaptureData& capture_data,\n TimeGraph* time_graph)\n : time_graph_(time_graph) {\n const auto& frame_track_function_ids = capture_data.frame_track_function_ids();\n for (const auto& function_id : frame_track_function_ids) {\n current_frame_track_function_ids_.insert(function_id);\n function_id_to_previous_timestamp_ns_.insert(\n std::make_pair(function_id, std::numeric_limits<uint64_t>::max()));\n }\n}\n\nvoid FrameTrackOnlineProcessor::ProcessTimer(const orbit_client_protos::TimerInfo& timer_info,\n const orbit_client_protos::FunctionInfo& function) {\n uint64_t function_id = timer_info.function_id();\n if (!current_frame_track_function_ids_.contains(function_id)) {\n return;\n }\n uint64_t previous_timestamp_ns = function_id_to_previous_timestamp_ns_.at(function_id);\n if (previous_timestamp_ns == std::numeric_limits<uint64_t>::max()) {\n function_id_to_previous_timestamp_ns_[function_id] = timer_info.start();\n return;\n }\n\n if (previous_timestamp_ns < timer_info.start()) {\n orbit_client_protos::TimerInfo frame_timer;\n\n \/\/ TID is meaningless for this timer (start and end can be on two different threads).\n constexpr const int32_t kUnusedThreadId = -1;\n frame_timer.set_thread_id(kUnusedThreadId);\n frame_timer.set_start(previous_timestamp_ns);\n frame_timer.set_end(timer_info.start());\n \/\/ We use user_data_key to keep track of the frame number.\n frame_timer.set_user_data_key(current_frame_index_++);\n frame_timer.set_type(orbit_client_protos::TimerInfo::kFrame);\n\n time_graph_->ProcessTimer(frame_timer, &function);\n\n function_id_to_previous_timestamp_ns_[function_id] = timer_info.start();\n }\n}\n\nvoid FrameTrackOnlineProcessor::AddFrameTrack(uint64_t function_id) {\n current_frame_track_function_ids_.insert(function_id);\n function_id_to_previous_timestamp_ns_.insert(\n std::make_pair(function_id, std::numeric_limits<uint64_t>::max()));\n}\n\nvoid FrameTrackOnlineProcessor::RemoveFrameTrack(uint64_t function_id) {\n current_frame_track_function_ids_.erase(function_id);\n function_id_to_previous_timestamp_ns_.erase(function_id);\n}\n<commit_msg>Solve the twice frame-track issue (regression)<commit_after>\/\/ Copyright (c) 2020 The Orbit Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"FrameTrackOnlineProcessor.h\"\n\n#include <absl\/container\/flat_hash_map.h>\n#include <absl\/container\/flat_hash_set.h>\n\n#include <limits>\n#include <utility>\n\n#include \"OrbitClientData\/FunctionInfoSet.h\"\n#include \"OrbitClientData\/UserDefinedCaptureData.h\"\n#include \"OrbitClientModel\/CaptureData.h\"\n#include \"TimeGraph.h\"\n\nFrameTrackOnlineProcessor::FrameTrackOnlineProcessor(const CaptureData& capture_data,\n TimeGraph* time_graph)\n : time_graph_(time_graph) {\n const auto& frame_track_function_ids = capture_data.frame_track_function_ids();\n for (const auto& function_id : frame_track_function_ids) {\n current_frame_track_function_ids_.insert(function_id);\n function_id_to_previous_timestamp_ns_.insert(\n std::make_pair(function_id, std::numeric_limits<uint64_t>::max()));\n }\n}\n\nvoid FrameTrackOnlineProcessor::ProcessTimer(const orbit_client_protos::TimerInfo& timer_info,\n const orbit_client_protos::FunctionInfo& function) {\n uint64_t function_id = timer_info.function_id();\n if (!current_frame_track_function_ids_.contains(function_id)) {\n return;\n }\n uint64_t previous_timestamp_ns = function_id_to_previous_timestamp_ns_.at(function_id);\n if (previous_timestamp_ns == std::numeric_limits<uint64_t>::max()) {\n function_id_to_previous_timestamp_ns_[function_id] = timer_info.start();\n return;\n }\n\n if (previous_timestamp_ns < timer_info.start()) {\n orbit_client_protos::TimerInfo frame_timer;\n\n \/\/ TID is meaningless for this timer (start and end can be on two different threads).\n constexpr const int32_t kUnusedThreadId = -1;\n frame_timer.set_thread_id(kUnusedThreadId);\n frame_timer.set_function_id(function_id);\n frame_timer.set_start(previous_timestamp_ns);\n frame_timer.set_end(timer_info.start());\n \/\/ We use user_data_key to keep track of the frame number.\n frame_timer.set_user_data_key(current_frame_index_++);\n frame_timer.set_type(orbit_client_protos::TimerInfo::kFrame);\n\n time_graph_->ProcessTimer(frame_timer, &function);\n\n function_id_to_previous_timestamp_ns_[function_id] = timer_info.start();\n }\n}\n\nvoid FrameTrackOnlineProcessor::AddFrameTrack(uint64_t function_id) {\n current_frame_track_function_ids_.insert(function_id);\n function_id_to_previous_timestamp_ns_.insert(\n std::make_pair(function_id, std::numeric_limits<uint64_t>::max()));\n}\n\nvoid FrameTrackOnlineProcessor::RemoveFrameTrack(uint64_t function_id) {\n current_frame_track_function_ids_.erase(function_id);\n function_id_to_previous_timestamp_ns_.erase(function_id);\n}\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n#include <fstream>\n#include <string>\n#include <vector>\n\/\/-----------------------------------------------------------------------------\n#include <SDL2\/SDL.h>\n\/\/-----------------------------------------------------------------------------\n#include \"..\/parser_yaml\/parser_yaml.h\"\n#include \"..\/log\/logger.h\"\n#include \"..\/model\/game.h\"\n#include \"..\/gfx\/game_window.h\"\n\/\/-----------------------------------------------------------------------------\n\n\/\/-----------------------------------------------------------------------------\nint main(int argc, char* args[]) {\n\n\tauto & logger = *Logger::getInstance();\n\tlogger.writeInformation(\"Start game\");\n\n\t{\n\t\tGame game;\n\t\tParserYAML parser(CONFIG_FILE_PATH);\n\t\tparser.parse();\n\t\tgame.setBoard(make_shared<Board>(parser));\n\t\tgame.addClient(make_shared<GameWindow>(game, *(game.getAvailablePlayer()), parser));\n\t\tgame.start();\n\t}\n\n\tlogger.getInstance()->writeInformation(\"Closing down\");\n\n\texit(0);\n}\n\/\/-----------------------------------------------------------------------------\n<commit_msg>Recupero restart en standalone<commit_after>#include <iostream>\n#include <fstream>\n#include <string>\n#include <vector>\n\/\/-----------------------------------------------------------------------------\n#include <SDL2\/SDL.h>\n\/\/-----------------------------------------------------------------------------\n#include \"..\/parser_yaml\/parser_yaml.h\"\n#include \"..\/log\/logger.h\"\n#include \"..\/model\/game.h\"\n#include \"..\/gfx\/game_window.h\"\n\/\/-----------------------------------------------------------------------------\n\n\/\/-----------------------------------------------------------------------------\nint main(int argc, char* args[]) {\n\n\tauto & logger = *Logger::getInstance();\n\tlogger.writeInformation(\"Start game\");\n\n\t{\n\t\tbool restart = true;\n\t\tdo {\n\t\t\tGame game;\n\t\t\tParserYAML parser(CONFIG_FILE_PATH);\n\t\t\tparser.parse();\n\t\t\tgame.setBoard(make_shared<Board>(parser));\n\t\t\tgame.addClient(make_shared<GameWindow>(game, *(game.getAvailablePlayer()), parser));\n\t\t\tgame.start();\n\t\t\trestart = game.willRestart();\n\t\t} while (restart);\n\t}\n\n\tlogger.getInstance()->writeInformation(\"Closing down\");\n\n\texit(0);\n}\n\/\/-----------------------------------------------------------------------------\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2011 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/test\/ui\/ui_test.h\"\n\n#include \"base\/file_path.h\"\n#include \"base\/memory\/singleton.h\"\n#include \"base\/message_loop.h\"\n#include \"chrome\/browser\/ui\/views\/html_dialog_view.h\"\n#include \"chrome\/browser\/ui\/webui\/html_dialog_ui.h\"\n#include \"chrome\/common\/url_constants.h\"\n#include \"chrome\/test\/in_process_browser_test.h\"\n#include \"chrome\/test\/ui_test_utils.h\"\n#include \"content\/browser\/renderer_host\/render_widget_host_view.h\"\n#include \"content\/browser\/tab_contents\/tab_contents.h\"\n#include \"testing\/gmock\/include\/gmock\/gmock.h\"\n#include \"testing\/gtest\/include\/gtest\/gtest.h\"\n#include \"views\/widget\/widget.h\"\n#include \"views\/window\/window.h\"\n\nusing testing::Eq;\n\nnamespace {\n\n\/\/ Window non-client-area means that the minimum size for the window\n\/\/ won't be the actual minimum size - our layout and resizing code\n\/\/ makes sure the chrome is always visible.\nconst int kMinimumWidthToTestFor = 20;\nconst int kMinimumHeightToTestFor = 30;\n\nclass TestHtmlDialogUIDelegate : public HtmlDialogUIDelegate {\n public:\n TestHtmlDialogUIDelegate() {}\n virtual ~TestHtmlDialogUIDelegate() {}\n\n \/\/ HTMLDialogUIDelegate implementation:\n virtual bool IsDialogModal() const {\n return true;\n }\n virtual std::wstring GetDialogTitle() const {\n return std::wstring(L\"Test\");\n }\n virtual GURL GetDialogContentURL() const {\n return GURL(chrome::kAboutAboutURL);\n }\n virtual void GetWebUIMessageHandlers(\n std::vector<WebUIMessageHandler*>* handlers) const { }\n virtual void GetDialogSize(gfx::Size* size) const {\n size->set_width(40);\n size->set_height(40);\n }\n virtual std::string GetDialogArgs() const {\n return std::string();\n }\n virtual void OnDialogClosed(const std::string& json_retval) { }\n virtual void OnCloseContents(TabContents* source, bool* out_close_dialog) {\n if (out_close_dialog)\n *out_close_dialog = true;\n }\n virtual bool ShouldShowDialogTitle() const { return true; }\n};\n\n} \/\/ namespace\n\nclass HtmlDialogBrowserTest : public InProcessBrowserTest {\n public:\n HtmlDialogBrowserTest() {}\n\n#if defined(OS_WIN)\n class WindowChangedObserver : public MessageLoopForUI::Observer {\n public:\n WindowChangedObserver() {}\n\n static WindowChangedObserver* GetInstance() {\n return Singleton<WindowChangedObserver>::get();\n }\n\n \/\/ This method is called before processing a message.\n virtual void WillProcessMessage(const MSG& msg) {}\n\n \/\/ This method is called after processing a message.\n virtual void DidProcessMessage(const MSG& msg) {\n \/\/ Either WM_PAINT or WM_TIMER indicates the actual work of\n \/\/ pushing through the window resizing messages is done since\n \/\/ they are lower priority (we don't get to see the\n \/\/ WM_WINDOWPOSCHANGED message here).\n if (msg.message == WM_PAINT || msg.message == WM_TIMER)\n MessageLoop::current()->Quit();\n }\n };\n#elif !defined(OS_MACOSX)\n class WindowChangedObserver : public MessageLoopForUI::Observer {\n public:\n WindowChangedObserver() {}\n\n static WindowChangedObserver* GetInstance() {\n return Singleton<WindowChangedObserver>::get();\n }\n\n \/\/ This method is called before processing a message.\n virtual void WillProcessEvent(GdkEvent* event) {}\n\n \/\/ This method is called after processing a message.\n virtual void DidProcessEvent(GdkEvent* event) {\n \/\/ Quit once the GDK_CONFIGURE event has been processed - seeing\n \/\/ this means the window sizing request that was made actually\n \/\/ happened.\n if (event->type == GDK_CONFIGURE)\n MessageLoop::current()->Quit();\n }\n };\n#endif\n};\n\n#if defined(OS_LINUX) && !defined(OS_CHROMEOS)\n#define MAYBE_SizeWindow SizeWindow\n#else\n\/\/ http:\/\/code.google.com\/p\/chromium\/issues\/detail?id=52602\n\/\/ Windows has some issues resizing windows- an off by one problem,\n\/\/ and a minimum size that seems too big. This file isn't included in\n\/\/ Mac builds yet. On Chrome OS, this test doesn't apply since ChromeOS\n\/\/ doesn't allow resizing of windows.\n#define MAYBE_SizeWindow DISABLED_SizeWindow\n#endif\n\nIN_PROC_BROWSER_TEST_F(HtmlDialogBrowserTest, MAYBE_SizeWindow) {\n HtmlDialogUIDelegate* delegate = new TestHtmlDialogUIDelegate();\n\n HtmlDialogView* html_view =\n new HtmlDialogView(browser()->profile(), delegate);\n TabContents* tab_contents = browser()->GetSelectedTabContents();\n ASSERT_TRUE(tab_contents != NULL);\n views::Window::CreateChromeWindow(tab_contents->GetDialogRootWindow(),\n gfx::Rect(), html_view);\n html_view->InitDialog();\n html_view->window()->Show();\n\n MessageLoopForUI::current()->AddObserver(\n WindowChangedObserver::GetInstance());\n\n gfx::Rect bounds = html_view->GetWidget()->GetClientAreaScreenBounds();\n\n gfx::Rect set_bounds = bounds;\n gfx::Rect actual_bounds, rwhv_bounds;\n\n \/\/ Bigger than the default in both dimensions.\n set_bounds.set_width(400);\n set_bounds.set_height(300);\n\n html_view->MoveContents(tab_contents, set_bounds);\n ui_test_utils::RunMessageLoop();\n actual_bounds = html_view->GetWidget()->GetClientAreaScreenBounds();\n EXPECT_EQ(set_bounds, actual_bounds);\n\n rwhv_bounds =\n html_view->tab_contents()->GetRenderWidgetHostView()->GetViewBounds();\n EXPECT_LT(0, rwhv_bounds.width());\n EXPECT_LT(0, rwhv_bounds.height());\n EXPECT_GE(set_bounds.width(), rwhv_bounds.width());\n EXPECT_GE(set_bounds.height(), rwhv_bounds.height());\n\n \/\/ Larger in one dimension and smaller in the other.\n set_bounds.set_width(550);\n set_bounds.set_height(250);\n\n html_view->MoveContents(tab_contents, set_bounds);\n ui_test_utils::RunMessageLoop();\n actual_bounds = html_view->GetWidget()->GetClientAreaScreenBounds();\n EXPECT_EQ(set_bounds, actual_bounds);\n\n rwhv_bounds =\n html_view->tab_contents()->GetRenderWidgetHostView()->GetViewBounds();\n EXPECT_LT(0, rwhv_bounds.width());\n EXPECT_LT(0, rwhv_bounds.height());\n EXPECT_GE(set_bounds.width(), rwhv_bounds.width());\n EXPECT_GE(set_bounds.height(), rwhv_bounds.height());\n\n \/\/ Get very small.\n set_bounds.set_width(kMinimumWidthToTestFor);\n set_bounds.set_height(kMinimumHeightToTestFor);\n\n html_view->MoveContents(tab_contents, set_bounds);\n ui_test_utils::RunMessageLoop();\n actual_bounds = html_view->GetWidget()->GetClientAreaScreenBounds();\n EXPECT_EQ(set_bounds, actual_bounds);\n\n rwhv_bounds =\n html_view->tab_contents()->GetRenderWidgetHostView()->GetViewBounds();\n EXPECT_LT(0, rwhv_bounds.width());\n EXPECT_LT(0, rwhv_bounds.height());\n EXPECT_GE(set_bounds.width(), rwhv_bounds.width());\n EXPECT_GE(set_bounds.height(), rwhv_bounds.height());\n\n \/\/ Check to make sure we can't get to 0x0\n set_bounds.set_width(0);\n set_bounds.set_height(0);\n\n html_view->MoveContents(tab_contents, set_bounds);\n ui_test_utils::RunMessageLoop();\n actual_bounds = html_view->GetWidget()->GetClientAreaScreenBounds();\n EXPECT_LT(0, actual_bounds.width());\n EXPECT_LT(0, actual_bounds.height());\n\n MessageLoopForUI::current()->RemoveObserver(\n WindowChangedObserver::GetInstance());\n}\n\nIN_PROC_BROWSER_TEST_F(HtmlDialogBrowserTest, TestStateTransition) {\n HtmlDialogUIDelegate* delegate = new TestHtmlDialogUIDelegate();\n\n HtmlDialogView* html_view =\n new HtmlDialogView(browser()->profile(), delegate);\n TabContents* tab_contents = browser()->GetSelectedTabContents();\n ASSERT_TRUE(tab_contents != NULL);\n views::Window::CreateChromeWindow(tab_contents->GetDialogRootWindow(),\n gfx::Rect(), html_view);\n \/\/ Test if the state transitions from INITIALIZED to -> PAINTED\n EXPECT_EQ(HtmlDialogView::INITIALIZED, html_view->state_);\n\n html_view->InitDialog();\n html_view->window()->Show();\n\n MessageLoopForUI::current()->AddObserver(\n WindowChangedObserver::GetInstance());\n \/\/ We use busy loop because the state is updated in notifications.\n while (html_view->state_ != HtmlDialogView::PAINTED)\n MessageLoop::current()->RunAllPending();\n\n EXPECT_EQ(HtmlDialogView::PAINTED, html_view->state_);\n\n MessageLoopForUI::current()->RemoveObserver(\n WindowChangedObserver::GetInstance());\n}\n<commit_msg>Mark HtmlDialogBrowserTest.TestStateTransition as flaky.<commit_after>\/\/ Copyright (c) 2011 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/test\/ui\/ui_test.h\"\n\n#include \"base\/file_path.h\"\n#include \"base\/memory\/singleton.h\"\n#include \"base\/message_loop.h\"\n#include \"chrome\/browser\/ui\/views\/html_dialog_view.h\"\n#include \"chrome\/browser\/ui\/webui\/html_dialog_ui.h\"\n#include \"chrome\/common\/url_constants.h\"\n#include \"chrome\/test\/in_process_browser_test.h\"\n#include \"chrome\/test\/ui_test_utils.h\"\n#include \"content\/browser\/renderer_host\/render_widget_host_view.h\"\n#include \"content\/browser\/tab_contents\/tab_contents.h\"\n#include \"testing\/gmock\/include\/gmock\/gmock.h\"\n#include \"testing\/gtest\/include\/gtest\/gtest.h\"\n#include \"views\/widget\/widget.h\"\n#include \"views\/window\/window.h\"\n\nusing testing::Eq;\n\nnamespace {\n\n\/\/ Window non-client-area means that the minimum size for the window\n\/\/ won't be the actual minimum size - our layout and resizing code\n\/\/ makes sure the chrome is always visible.\nconst int kMinimumWidthToTestFor = 20;\nconst int kMinimumHeightToTestFor = 30;\n\nclass TestHtmlDialogUIDelegate : public HtmlDialogUIDelegate {\n public:\n TestHtmlDialogUIDelegate() {}\n virtual ~TestHtmlDialogUIDelegate() {}\n\n \/\/ HTMLDialogUIDelegate implementation:\n virtual bool IsDialogModal() const {\n return true;\n }\n virtual std::wstring GetDialogTitle() const {\n return std::wstring(L\"Test\");\n }\n virtual GURL GetDialogContentURL() const {\n return GURL(chrome::kAboutAboutURL);\n }\n virtual void GetWebUIMessageHandlers(\n std::vector<WebUIMessageHandler*>* handlers) const { }\n virtual void GetDialogSize(gfx::Size* size) const {\n size->set_width(40);\n size->set_height(40);\n }\n virtual std::string GetDialogArgs() const {\n return std::string();\n }\n virtual void OnDialogClosed(const std::string& json_retval) { }\n virtual void OnCloseContents(TabContents* source, bool* out_close_dialog) {\n if (out_close_dialog)\n *out_close_dialog = true;\n }\n virtual bool ShouldShowDialogTitle() const { return true; }\n};\n\n} \/\/ namespace\n\nclass HtmlDialogBrowserTest : public InProcessBrowserTest {\n public:\n HtmlDialogBrowserTest() {}\n\n#if defined(OS_WIN)\n class WindowChangedObserver : public MessageLoopForUI::Observer {\n public:\n WindowChangedObserver() {}\n\n static WindowChangedObserver* GetInstance() {\n return Singleton<WindowChangedObserver>::get();\n }\n\n \/\/ This method is called before processing a message.\n virtual void WillProcessMessage(const MSG& msg) {}\n\n \/\/ This method is called after processing a message.\n virtual void DidProcessMessage(const MSG& msg) {\n \/\/ Either WM_PAINT or WM_TIMER indicates the actual work of\n \/\/ pushing through the window resizing messages is done since\n \/\/ they are lower priority (we don't get to see the\n \/\/ WM_WINDOWPOSCHANGED message here).\n if (msg.message == WM_PAINT || msg.message == WM_TIMER)\n MessageLoop::current()->Quit();\n }\n };\n#elif !defined(OS_MACOSX)\n class WindowChangedObserver : public MessageLoopForUI::Observer {\n public:\n WindowChangedObserver() {}\n\n static WindowChangedObserver* GetInstance() {\n return Singleton<WindowChangedObserver>::get();\n }\n\n \/\/ This method is called before processing a message.\n virtual void WillProcessEvent(GdkEvent* event) {}\n\n \/\/ This method is called after processing a message.\n virtual void DidProcessEvent(GdkEvent* event) {\n \/\/ Quit once the GDK_CONFIGURE event has been processed - seeing\n \/\/ this means the window sizing request that was made actually\n \/\/ happened.\n if (event->type == GDK_CONFIGURE)\n MessageLoop::current()->Quit();\n }\n };\n#endif\n};\n\n#if defined(OS_LINUX) && !defined(OS_CHROMEOS)\n#define MAYBE_SizeWindow SizeWindow\n#else\n\/\/ http:\/\/code.google.com\/p\/chromium\/issues\/detail?id=52602\n\/\/ Windows has some issues resizing windows- an off by one problem,\n\/\/ and a minimum size that seems too big. This file isn't included in\n\/\/ Mac builds yet. On Chrome OS, this test doesn't apply since ChromeOS\n\/\/ doesn't allow resizing of windows.\n#define MAYBE_SizeWindow DISABLED_SizeWindow\n#endif\n\nIN_PROC_BROWSER_TEST_F(HtmlDialogBrowserTest, MAYBE_SizeWindow) {\n HtmlDialogUIDelegate* delegate = new TestHtmlDialogUIDelegate();\n\n HtmlDialogView* html_view =\n new HtmlDialogView(browser()->profile(), delegate);\n TabContents* tab_contents = browser()->GetSelectedTabContents();\n ASSERT_TRUE(tab_contents != NULL);\n views::Window::CreateChromeWindow(tab_contents->GetDialogRootWindow(),\n gfx::Rect(), html_view);\n html_view->InitDialog();\n html_view->window()->Show();\n\n MessageLoopForUI::current()->AddObserver(\n WindowChangedObserver::GetInstance());\n\n gfx::Rect bounds = html_view->GetWidget()->GetClientAreaScreenBounds();\n\n gfx::Rect set_bounds = bounds;\n gfx::Rect actual_bounds, rwhv_bounds;\n\n \/\/ Bigger than the default in both dimensions.\n set_bounds.set_width(400);\n set_bounds.set_height(300);\n\n html_view->MoveContents(tab_contents, set_bounds);\n ui_test_utils::RunMessageLoop();\n actual_bounds = html_view->GetWidget()->GetClientAreaScreenBounds();\n EXPECT_EQ(set_bounds, actual_bounds);\n\n rwhv_bounds =\n html_view->tab_contents()->GetRenderWidgetHostView()->GetViewBounds();\n EXPECT_LT(0, rwhv_bounds.width());\n EXPECT_LT(0, rwhv_bounds.height());\n EXPECT_GE(set_bounds.width(), rwhv_bounds.width());\n EXPECT_GE(set_bounds.height(), rwhv_bounds.height());\n\n \/\/ Larger in one dimension and smaller in the other.\n set_bounds.set_width(550);\n set_bounds.set_height(250);\n\n html_view->MoveContents(tab_contents, set_bounds);\n ui_test_utils::RunMessageLoop();\n actual_bounds = html_view->GetWidget()->GetClientAreaScreenBounds();\n EXPECT_EQ(set_bounds, actual_bounds);\n\n rwhv_bounds =\n html_view->tab_contents()->GetRenderWidgetHostView()->GetViewBounds();\n EXPECT_LT(0, rwhv_bounds.width());\n EXPECT_LT(0, rwhv_bounds.height());\n EXPECT_GE(set_bounds.width(), rwhv_bounds.width());\n EXPECT_GE(set_bounds.height(), rwhv_bounds.height());\n\n \/\/ Get very small.\n set_bounds.set_width(kMinimumWidthToTestFor);\n set_bounds.set_height(kMinimumHeightToTestFor);\n\n html_view->MoveContents(tab_contents, set_bounds);\n ui_test_utils::RunMessageLoop();\n actual_bounds = html_view->GetWidget()->GetClientAreaScreenBounds();\n EXPECT_EQ(set_bounds, actual_bounds);\n\n rwhv_bounds =\n html_view->tab_contents()->GetRenderWidgetHostView()->GetViewBounds();\n EXPECT_LT(0, rwhv_bounds.width());\n EXPECT_LT(0, rwhv_bounds.height());\n EXPECT_GE(set_bounds.width(), rwhv_bounds.width());\n EXPECT_GE(set_bounds.height(), rwhv_bounds.height());\n\n \/\/ Check to make sure we can't get to 0x0\n set_bounds.set_width(0);\n set_bounds.set_height(0);\n\n html_view->MoveContents(tab_contents, set_bounds);\n ui_test_utils::RunMessageLoop();\n actual_bounds = html_view->GetWidget()->GetClientAreaScreenBounds();\n EXPECT_LT(0, actual_bounds.width());\n EXPECT_LT(0, actual_bounds.height());\n\n MessageLoopForUI::current()->RemoveObserver(\n WindowChangedObserver::GetInstance());\n}\n\nIN_PROC_BROWSER_TEST_F(HtmlDialogBrowserTest, FLAKY_TestStateTransition) {\n HtmlDialogUIDelegate* delegate = new TestHtmlDialogUIDelegate();\n\n HtmlDialogView* html_view =\n new HtmlDialogView(browser()->profile(), delegate);\n TabContents* tab_contents = browser()->GetSelectedTabContents();\n ASSERT_TRUE(tab_contents != NULL);\n views::Window::CreateChromeWindow(tab_contents->GetDialogRootWindow(),\n gfx::Rect(), html_view);\n \/\/ Test if the state transitions from INITIALIZED to -> PAINTED\n EXPECT_EQ(HtmlDialogView::INITIALIZED, html_view->state_);\n\n html_view->InitDialog();\n html_view->window()->Show();\n\n MessageLoopForUI::current()->AddObserver(\n WindowChangedObserver::GetInstance());\n \/\/ We use busy loop because the state is updated in notifications.\n while (html_view->state_ != HtmlDialogView::PAINTED)\n MessageLoop::current()->RunAllPending();\n\n EXPECT_EQ(HtmlDialogView::PAINTED, html_view->state_);\n\n MessageLoopForUI::current()->RemoveObserver(\n WindowChangedObserver::GetInstance());\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ RemotePhotoTool - remote camera control software\n\/\/ Copyright (C) 2008-2014 Michael Fink\n\/\/\n\/\/\/ \\file CmdlineApp.cpp Command line app\n\/\/\n\n\/\/ includes\n#include \"stdafx.h\"\n#include \"CmdlineApp.hpp\"\n#include \"Exception.hpp\"\n#include \"CameraException.hpp\"\n#include \"AppCommand.hpp\"\n#include \"AppOptions.hpp\"\n#include \"Event.hpp\"\n#include <boost\\bind.hpp>\n#include \"CameraScriptProcessor.hpp\"\n#include \"Instance.hpp\"\n#include \"SourceInfo.hpp\"\n#include \"SourceDevice.hpp\"\n#include \"RemoteReleaseControl.hpp\"\n#include \"ShutterReleaseSettings.hpp\"\n#include \"..\\version.h\"\n\nCmdlineApp::CmdlineApp()\n{\n _tprintf(_T(\"RemotePhotoTool Command-Line %s\\n%s\\n\\n\"),\n _T(VERSIONINFO_FILEVERSION_DISPLAYSTRING),\n _T(VERSIONINFO_COPYRIGHT));\n}\n\nvoid CmdlineApp::Run(int argc, TCHAR* argv[])\n{\n \/\/ parse options\n AppOptions options(m_vecCommandList);\n options.Parse(argc, argv);\n\n if (m_vecCommandList.empty())\n {\n options.OutputHelp();\n return;\n }\n\n if (options.IsSelectedHelpOption())\n return;\n\n \/\/ run command list\n std::for_each(m_vecCommandList.begin(), m_vecCommandList.end(), [&](const AppCommand& cmd)\n {\n try\n {\n Exec(cmd);\n }\n catch(const CameraException& ex)\n {\n _tprintf(_T(\"CameraException was thrown: \\\"%s\\\"\\n\"), ex.Message().GetString());\n }\n catch(const Exception& ex)\n {\n _tprintf(_T(\"Exception was thrown: \\\"%s\\\"\\n\"), ex.Message().GetString());\n }\n });\n}\n\nvoid CmdlineApp::Exec(const AppCommand& cmd)\n{\n switch (cmd.m_enCommand)\n {\n case AppCommand::showVersion: PrintVersionInfo(); break;\n case AppCommand::listDevices: ListDevices(); break;\n case AppCommand::openDevice: OpenByName(cmd.m_cszData); break;\n case AppCommand::closeDevice:\n m_spSourceDevice.reset();\n m_spReleaseControl.reset();\n break;\n case AppCommand::deviceInfo: OutputDeviceInfo(); break;\n case AppCommand::deviceProperties: ListDeviceProperties(); break;\n case AppCommand::imageProperties: ListImageProperties(); break;\n case AppCommand::releaseShutter: ReleaseShutter(); break;\n case AppCommand::runScript: RunScript(cmd.m_cszData); break;\n default:\n ATLASSERT(false);\n break;\n }\n}\n\nvoid CmdlineApp::PrintVersionInfo()\n{\n _tprintf(_T(\"CanonControl version info\\n\\n\"));\n\n Instance inst = Instance::Get();\n\n CString cszVersionInfo = inst.Version();\n\n _tprintf(_T(\"%s\\n\"), cszVersionInfo.GetString());\n}\n\nvoid CmdlineApp::ListDevices()\n{\n _tprintf(_T(\"Devices list\\n\"));\n\n Instance inst = Instance::Get();\n\n std::vector<std::shared_ptr<SourceInfo>> vecSourceDevices;\n inst.EnumerateDevices(vecSourceDevices);\n\n if (vecSourceDevices.empty())\n {\n _tprintf(_T(\"No device found.\\n\"));\n }\n else\n {\n for (size_t i=0,iMax=vecSourceDevices.size(); i<iMax; i++)\n {\n std::shared_ptr<SourceInfo> spSourceInfo = vecSourceDevices[i];\n _tprintf(_T(\"Device %u: \\\"%s\\\"\\n\"), i+1, spSourceInfo->Name().GetString());\n }\n }\n\n _tprintf(_T(\"\\n\"));\n}\n\nvoid CmdlineApp::OpenByName(const CString& cszName)\n{\n Instance inst = Instance::Get();\n\n std::vector<std::shared_ptr<SourceInfo>> vecSourceDevices;\n inst.EnumerateDevices(vecSourceDevices);\n\n \/\/ TODO support {x} notation\n\n for (size_t i=0,iMax=vecSourceDevices.size(); i<iMax; i++)\n {\n std::shared_ptr<SourceInfo> spSourceInfo = vecSourceDevices[i];\n if (spSourceInfo->Name() == cszName)\n {\n m_spSourceDevice = spSourceInfo->Open();\n return;\n }\n }\n\n throw Exception(_T(\"Couldn't find camera model: \") + cszName, __FILE__, __LINE__);\n}\n\nvoid CmdlineApp::OutputDeviceInfo()\n{\n _tprintf(_T(\"Device info about \\\"%s\\\"\\n\"), m_spSourceDevice->ModelName().GetString());\n _tprintf(_T(\"Serial number \\\"%s\\\"\\n\"), m_spSourceDevice->SerialNumber().GetString());\n\n \/\/ output capabilities\n _tprintf(_T(\"Device capabilities\\n\"));\n bool bCanRelease = m_spSourceDevice->GetDeviceCapability(SourceDevice::capRemoteReleaseControl);\n bool bCanUseViewfinder = m_spSourceDevice->GetDeviceCapability(SourceDevice::capRemoteViewfinder);\n\n _tprintf(_T(\"can release shutter: %s\\n\"), bCanRelease ? _T(\"yes\") : _T(\"no\"));\n _tprintf(_T(\"can use remote viewfinder: %s\\n\"), bCanUseViewfinder ? _T(\"yes\") : _T(\"no\"));\n _tprintf(_T(\"\\n\"));\n}\n\nvoid CmdlineApp::ListDeviceProperties()\n{\n \/\/ output device properties\n _tprintf(_T(\"Device properties\\n\"));\n\n std::vector<unsigned int> vecProperties = m_spSourceDevice->EnumDeviceProperties();\n\n for (size_t i=0, iMax=vecProperties.size(); i<iMax; i++)\n {\n unsigned int uiPropertyId = vecProperties[i];\n DeviceProperty dp = m_spSourceDevice->GetDeviceProperty(uiPropertyId);\n\n _tprintf(_T(\"Property \\\"%s\\\" (%04x)%s: %s (%s)\\n\"),\n dp.Name().GetString(),\n uiPropertyId,\n dp.IsReadOnly() ? _T(\" [read-only]\") : _T(\"\"),\n dp.Value().ToString().GetString(),\n dp.AsString().GetString());\n\n std::vector<Variant> vecValidValues = dp.ValidValues();\n for (size_t j=0, jMax=vecValidValues.size(); j<jMax; j++)\n {\n _tprintf(_T(\" Valid value: %s (%s)\\n\"),\n vecValidValues[j].ToString().GetString(),\n dp.ValueAsString(vecValidValues[j]).GetString());\n }\n }\n _tprintf(_T(\"\\n\"));\n}\n\nvoid CmdlineApp::ListImageProperties()\n{\n _tprintf(_T(\"List image properties\\n\"));\n\n EnsureReleaseControl();\n\n std::vector<unsigned int> vecImageProperties = m_spReleaseControl->EnumImageProperties();\n if (vecImageProperties.empty())\n {\n _tprintf(_T(\"no image properties found.\\n\"));\n }\n else\n for (size_t i=0,iMax=vecImageProperties.size(); i<iMax; i++)\n {\n unsigned int uiPropertyId = vecImageProperties[i];\n\n ImageProperty ip = m_spReleaseControl->GetImageProperty(uiPropertyId);\n\n _tprintf(_T(\"Image property \\\"%s\\\" (%04x)%s: %s (%s)\\n\"),\n ip.Name().GetString(),\n uiPropertyId,\n ip.IsReadOnly() ? _T(\" [read-only]\") : _T(\"\"),\n ip.Value().ToString().GetString(),\n ip.AsString().GetString());\n\n std::vector<ImageProperty> vecValues;\n m_spReleaseControl->EnumImagePropertyValues(vecImageProperties[i], vecValues);\n\n for (size_t j=0, jMax=vecValues.size(); j<jMax; j++)\n {\n const ImageProperty& ip2 = vecValues[j];\n _tprintf(_T(\" Valid value: %s (%s)\\n\"),\n ip2.Value().ToString().GetString(),\n ip.ValueAsString(ip2.Value()).GetString());\n }\n }\n}\n\nvoid CmdlineApp::EnsureReleaseControl()\n{\n if (m_spReleaseControl != nullptr)\n return;\n\n if (m_spSourceDevice == nullptr)\n throw Exception(_T(\"Source device not opened.\"), __FILE__, __LINE__);\n\n _tprintf(_T(\"Starting Remote Release Control\\n\"));\n\n m_spReleaseControl = m_spSourceDevice->EnterReleaseControl();\n}\n\nvoid CmdlineApp::ReleaseShutter()\n{\n _tprintf(_T(\"Release shutter\\n\"));\n\n EnsureReleaseControl();\n\n unsigned int uiNumAvailShot = m_spReleaseControl->NumAvailableShots();\n _tprintf(_T(\"Memory for %u images available\\n\"), uiNumAvailShot);\n\n Event evtPictureTaken(true, false);\n ShutterReleaseSettings settings(\n ShutterReleaseSettings::saveToHost,\n std::bind(&Event::Set, &evtPictureTaken));\n\n m_spReleaseControl->SetReleaseSettings(settings);\n\n m_spReleaseControl->Release();\n\n evtPictureTaken.Wait();\n}\n\nvoid CmdlineApp::RunScript(const CString& cszFilename)\n{\n _tprintf(_T(\"Loading script: %s\\n\"), cszFilename.GetString());\n\n CameraScriptProcessor proc;\n\n proc.SetOutputDebugStringHandler(\n [&](const CString& cszText){\n _tprintf(_T(\"%s\"), cszText.GetString());\n });\n\n proc.LoadScript(cszFilename);\n\n proc.Run();\n\n _tprintf(_T(\"Press any key to abort running script.\\n\\n\"));\n\n (void)fgetc(stdin);\n\n proc.Stop();\n}\n<commit_msg>removed unused include<commit_after>\/\/\n\/\/ RemotePhotoTool - remote camera control software\n\/\/ Copyright (C) 2008-2014 Michael Fink\n\/\/\n\/\/\/ \\file CmdlineApp.cpp Command line app\n\/\/\n\n\/\/ includes\n#include \"stdafx.h\"\n#include \"CmdlineApp.hpp\"\n#include \"Exception.hpp\"\n#include \"CameraException.hpp\"\n#include \"AppCommand.hpp\"\n#include \"AppOptions.hpp\"\n#include \"Event.hpp\"\n#include \"CameraScriptProcessor.hpp\"\n#include \"Instance.hpp\"\n#include \"SourceInfo.hpp\"\n#include \"SourceDevice.hpp\"\n#include \"RemoteReleaseControl.hpp\"\n#include \"ShutterReleaseSettings.hpp\"\n#include \"..\\version.h\"\n\nCmdlineApp::CmdlineApp()\n{\n _tprintf(_T(\"RemotePhotoTool Command-Line %s\\n%s\\n\\n\"),\n _T(VERSIONINFO_FILEVERSION_DISPLAYSTRING),\n _T(VERSIONINFO_COPYRIGHT));\n}\n\nvoid CmdlineApp::Run(int argc, TCHAR* argv[])\n{\n \/\/ parse options\n AppOptions options(m_vecCommandList);\n options.Parse(argc, argv);\n\n if (m_vecCommandList.empty())\n {\n options.OutputHelp();\n return;\n }\n\n if (options.IsSelectedHelpOption())\n return;\n\n \/\/ run command list\n std::for_each(m_vecCommandList.begin(), m_vecCommandList.end(), [&](const AppCommand& cmd)\n {\n try\n {\n Exec(cmd);\n }\n catch(const CameraException& ex)\n {\n _tprintf(_T(\"CameraException was thrown: \\\"%s\\\"\\n\"), ex.Message().GetString());\n }\n catch(const Exception& ex)\n {\n _tprintf(_T(\"Exception was thrown: \\\"%s\\\"\\n\"), ex.Message().GetString());\n }\n });\n}\n\nvoid CmdlineApp::Exec(const AppCommand& cmd)\n{\n switch (cmd.m_enCommand)\n {\n case AppCommand::showVersion: PrintVersionInfo(); break;\n case AppCommand::listDevices: ListDevices(); break;\n case AppCommand::openDevice: OpenByName(cmd.m_cszData); break;\n case AppCommand::closeDevice:\n m_spSourceDevice.reset();\n m_spReleaseControl.reset();\n break;\n case AppCommand::deviceInfo: OutputDeviceInfo(); break;\n case AppCommand::deviceProperties: ListDeviceProperties(); break;\n case AppCommand::imageProperties: ListImageProperties(); break;\n case AppCommand::releaseShutter: ReleaseShutter(); break;\n case AppCommand::runScript: RunScript(cmd.m_cszData); break;\n default:\n ATLASSERT(false);\n break;\n }\n}\n\nvoid CmdlineApp::PrintVersionInfo()\n{\n _tprintf(_T(\"CanonControl version info\\n\\n\"));\n\n Instance inst = Instance::Get();\n\n CString cszVersionInfo = inst.Version();\n\n _tprintf(_T(\"%s\\n\"), cszVersionInfo.GetString());\n}\n\nvoid CmdlineApp::ListDevices()\n{\n _tprintf(_T(\"Devices list\\n\"));\n\n Instance inst = Instance::Get();\n\n std::vector<std::shared_ptr<SourceInfo>> vecSourceDevices;\n inst.EnumerateDevices(vecSourceDevices);\n\n if (vecSourceDevices.empty())\n {\n _tprintf(_T(\"No device found.\\n\"));\n }\n else\n {\n for (size_t i=0,iMax=vecSourceDevices.size(); i<iMax; i++)\n {\n std::shared_ptr<SourceInfo> spSourceInfo = vecSourceDevices[i];\n _tprintf(_T(\"Device %u: \\\"%s\\\"\\n\"), i+1, spSourceInfo->Name().GetString());\n }\n }\n\n _tprintf(_T(\"\\n\"));\n}\n\nvoid CmdlineApp::OpenByName(const CString& cszName)\n{\n Instance inst = Instance::Get();\n\n std::vector<std::shared_ptr<SourceInfo>> vecSourceDevices;\n inst.EnumerateDevices(vecSourceDevices);\n\n \/\/ TODO support {x} notation\n\n for (size_t i=0,iMax=vecSourceDevices.size(); i<iMax; i++)\n {\n std::shared_ptr<SourceInfo> spSourceInfo = vecSourceDevices[i];\n if (spSourceInfo->Name() == cszName)\n {\n m_spSourceDevice = spSourceInfo->Open();\n return;\n }\n }\n\n throw Exception(_T(\"Couldn't find camera model: \") + cszName, __FILE__, __LINE__);\n}\n\nvoid CmdlineApp::OutputDeviceInfo()\n{\n _tprintf(_T(\"Device info about \\\"%s\\\"\\n\"), m_spSourceDevice->ModelName().GetString());\n _tprintf(_T(\"Serial number \\\"%s\\\"\\n\"), m_spSourceDevice->SerialNumber().GetString());\n\n \/\/ output capabilities\n _tprintf(_T(\"Device capabilities\\n\"));\n bool bCanRelease = m_spSourceDevice->GetDeviceCapability(SourceDevice::capRemoteReleaseControl);\n bool bCanUseViewfinder = m_spSourceDevice->GetDeviceCapability(SourceDevice::capRemoteViewfinder);\n\n _tprintf(_T(\"can release shutter: %s\\n\"), bCanRelease ? _T(\"yes\") : _T(\"no\"));\n _tprintf(_T(\"can use remote viewfinder: %s\\n\"), bCanUseViewfinder ? _T(\"yes\") : _T(\"no\"));\n _tprintf(_T(\"\\n\"));\n}\n\nvoid CmdlineApp::ListDeviceProperties()\n{\n \/\/ output device properties\n _tprintf(_T(\"Device properties\\n\"));\n\n std::vector<unsigned int> vecProperties = m_spSourceDevice->EnumDeviceProperties();\n\n for (size_t i=0, iMax=vecProperties.size(); i<iMax; i++)\n {\n unsigned int uiPropertyId = vecProperties[i];\n DeviceProperty dp = m_spSourceDevice->GetDeviceProperty(uiPropertyId);\n\n _tprintf(_T(\"Property \\\"%s\\\" (%04x)%s: %s (%s)\\n\"),\n dp.Name().GetString(),\n uiPropertyId,\n dp.IsReadOnly() ? _T(\" [read-only]\") : _T(\"\"),\n dp.Value().ToString().GetString(),\n dp.AsString().GetString());\n\n std::vector<Variant> vecValidValues = dp.ValidValues();\n for (size_t j=0, jMax=vecValidValues.size(); j<jMax; j++)\n {\n _tprintf(_T(\" Valid value: %s (%s)\\n\"),\n vecValidValues[j].ToString().GetString(),\n dp.ValueAsString(vecValidValues[j]).GetString());\n }\n }\n _tprintf(_T(\"\\n\"));\n}\n\nvoid CmdlineApp::ListImageProperties()\n{\n _tprintf(_T(\"List image properties\\n\"));\n\n EnsureReleaseControl();\n\n std::vector<unsigned int> vecImageProperties = m_spReleaseControl->EnumImageProperties();\n if (vecImageProperties.empty())\n {\n _tprintf(_T(\"no image properties found.\\n\"));\n }\n else\n for (size_t i=0,iMax=vecImageProperties.size(); i<iMax; i++)\n {\n unsigned int uiPropertyId = vecImageProperties[i];\n\n ImageProperty ip = m_spReleaseControl->GetImageProperty(uiPropertyId);\n\n _tprintf(_T(\"Image property \\\"%s\\\" (%04x)%s: %s (%s)\\n\"),\n ip.Name().GetString(),\n uiPropertyId,\n ip.IsReadOnly() ? _T(\" [read-only]\") : _T(\"\"),\n ip.Value().ToString().GetString(),\n ip.AsString().GetString());\n\n std::vector<ImageProperty> vecValues;\n m_spReleaseControl->EnumImagePropertyValues(vecImageProperties[i], vecValues);\n\n for (size_t j=0, jMax=vecValues.size(); j<jMax; j++)\n {\n const ImageProperty& ip2 = vecValues[j];\n _tprintf(_T(\" Valid value: %s (%s)\\n\"),\n ip2.Value().ToString().GetString(),\n ip.ValueAsString(ip2.Value()).GetString());\n }\n }\n}\n\nvoid CmdlineApp::EnsureReleaseControl()\n{\n if (m_spReleaseControl != nullptr)\n return;\n\n if (m_spSourceDevice == nullptr)\n throw Exception(_T(\"Source device not opened.\"), __FILE__, __LINE__);\n\n _tprintf(_T(\"Starting Remote Release Control\\n\"));\n\n m_spReleaseControl = m_spSourceDevice->EnterReleaseControl();\n}\n\nvoid CmdlineApp::ReleaseShutter()\n{\n _tprintf(_T(\"Release shutter\\n\"));\n\n EnsureReleaseControl();\n\n unsigned int uiNumAvailShot = m_spReleaseControl->NumAvailableShots();\n _tprintf(_T(\"Memory for %u images available\\n\"), uiNumAvailShot);\n\n Event evtPictureTaken(true, false);\n ShutterReleaseSettings settings(\n ShutterReleaseSettings::saveToHost,\n std::bind(&Event::Set, &evtPictureTaken));\n\n m_spReleaseControl->SetReleaseSettings(settings);\n\n m_spReleaseControl->Release();\n\n evtPictureTaken.Wait();\n}\n\nvoid CmdlineApp::RunScript(const CString& cszFilename)\n{\n _tprintf(_T(\"Loading script: %s\\n\"), cszFilename.GetString());\n\n CameraScriptProcessor proc;\n\n proc.SetOutputDebugStringHandler(\n [&](const CString& cszText){\n _tprintf(_T(\"%s\"), cszText.GetString());\n });\n\n proc.LoadScript(cszFilename);\n\n proc.Run();\n\n _tprintf(_T(\"Press any key to abort running script.\\n\\n\"));\n\n (void)fgetc(stdin);\n\n proc.Stop();\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (C) 2007-2013 CEA\/DEN, EDF R&D, OPEN CASCADE\n\/\/\n\/\/ Copyright (C) 2003-2007 OPEN CASCADE, EADS\/CCR, LIP6, CEA\/DEN,\n\/\/ CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS\n\/\/\n\/\/ This library is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU Lesser General Public\n\/\/ License as published by the Free Software Foundation; either\n\/\/ version 2.1 of the License.\n\/\/\n\/\/ This library is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ Lesser General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License along with this library; if not, write to the Free Software\n\/\/ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n\/\/\n\/\/ See http:\/\/www.salome-platform.org\/ or email : webmaster.salome@opencascade.com\n\/\/\n\n\/\/ SMESH SMESHGUI : GUI for SMESH component\n\/\/ File : SMESHGUI_MeshEditPreview.cxx\n\/\/ Author : Open CASCADE S.A.S.\n\/\/ SMESH includes\n\/\/\n#include \"SMESHGUI_MeshEditPreview.h\"\n\n#include \"SMESHGUI_VTKUtils.h\"\n#include \"SMESH_Actor.h\"\n#include \"SMESH_ActorUtils.h\"\n\n\/\/ SALOME GUI includes\n#include <SVTK_Renderer.h>\n#include <SVTK_ViewWindow.h>\n#include <VTKViewer_CellLocationsArray.h>\n\n\/\/ VTK includes\n#include <vtkCellArray.h>\n#include <vtkCoordinate.h>\n#include <vtkDataSetMapper.h>\n#include <vtkIdList.h>\n#include <vtkPoints.h>\n#include <vtkProperty.h>\n#include <vtkRenderer.h>\n#include <vtkTextActor.h>\n#include <vtkTextMapper.h>\n#include <vtkUnsignedCharArray.h>\n#include <vtkUnstructuredGrid.h>\n\n\/\/ Qt includes\n#include <QColor>\n\n\/\/ IDL includes\n#include <SALOMEconfig.h>\n#include CORBA_SERVER_HEADER(SMESH_MeshEditor)\n\n#include <gp_Ax3.hxx>\n\n\/\/================================================================================\n\/*!\n * \\brief Constructor\n *\/\n\/\/================================================================================\n\nSMESHGUI_MeshEditPreview::SMESHGUI_MeshEditPreview(SVTK_ViewWindow* theViewWindow):\n myViewWindow(theViewWindow)\n{\n myGrid = vtkUnstructuredGrid::New();\n\n \/\/ Create and display actor\n vtkDataSetMapper* aMapper = vtkDataSetMapper::New();\n aMapper->SetInputData( myGrid );\n\n myPreviewActor = SALOME_Actor::New();\n myPreviewActor->SetInfinitive(true);\n myPreviewActor->VisibilityOn();\n myPreviewActor->PickableOff();\n\n double aFactor,aUnits;\n myPreviewActor->SetResolveCoincidentTopology(true);\n myPreviewActor->GetPolygonOffsetParameters(aFactor,aUnits);\n myPreviewActor->SetPolygonOffsetParameters(aFactor,0.2*aUnits);\n\n double anRGB[3];\n SMESH::GetColor( \"SMESH\", \"selection_element_color\", anRGB[0], anRGB[1], anRGB[2], QColor( 0, 170, 255 ) );\n SetColor( anRGB[0], anRGB[1], anRGB[2] );\n\n myPreviewActor->SetMapper( aMapper );\n aMapper->Delete();\n\n myViewWindow->AddActor(myPreviewActor);\n}\n\n\/\/================================================================================\n\/*!\n * \\brief Destroy\n *\/\n\/\/================================================================================\n\nSMESHGUI_MeshEditPreview::~SMESHGUI_MeshEditPreview()\n{\n myGrid->Delete();\n\n myViewWindow->RemoveActor(myPreviewActor);\n myPreviewActor->Delete();\n\n for ( size_t iA = 0; iA < myLabelActors.size(); ++iA )\n if ( myLabelActors[iA] )\n {\n myPreviewActor->GetRenderer()->RemoveActor( myLabelActors[iA] );\n myLabelActors[iA]->Delete();\n }\n}\n\n\/\/================================================================================\n\/*!\n * \\brief Returns vtk cell type\n *\/\n\/\/================================================================================\n\nvtkIdType getCellType( const SMDSAbs_ElementType theType,\n const bool thePoly,\n const int theNbNodes )\n{\n switch( theType ) \n {\n case SMDSAbs_Node: return VTK_VERTEX;\n case SMDSAbs_Edge: \n if( theNbNodes == 2 ) return VTK_LINE;\n else if ( theNbNodes == 3 ) return VTK_QUADRATIC_EDGE;\n else return VTK_EMPTY_CELL;\n\n case SMDSAbs_Face :\n if (thePoly && theNbNodes>2 ) return VTK_POLYGON;\n else if ( theNbNodes == 3 ) return VTK_TRIANGLE;\n else if ( theNbNodes == 4 ) return VTK_QUAD;\n else if ( theNbNodes == 6 ) return VTK_QUADRATIC_TRIANGLE;\n else if ( theNbNodes == 7 ) return VTK_BIQUADRATIC_TRIANGLE;\n else if ( theNbNodes == 8 ) return VTK_QUADRATIC_QUAD;\n else if ( theNbNodes == 9 ) return VTK_BIQUADRATIC_QUAD;\n else return VTK_EMPTY_CELL;\n\n case SMDSAbs_Volume:\n if (thePoly && theNbNodes>3 ) return VTK_CONVEX_POINT_SET;\n else if ( theNbNodes == 4 ) return VTK_TETRA;\n else if ( theNbNodes == 5 ) return VTK_PYRAMID;\n else if ( theNbNodes == 6 ) return VTK_WEDGE;\n else if ( theNbNodes == 8 ) return VTK_HEXAHEDRON;\n else if ( theNbNodes == 10 ) return VTK_QUADRATIC_TETRA;\n else if ( theNbNodes == 20 ) return VTK_QUADRATIC_HEXAHEDRON;\n else if ( theNbNodes == 27 ) return VTK_TRIQUADRATIC_HEXAHEDRON;\n else if ( theNbNodes == 15 ) return VTK_QUADRATIC_WEDGE;\n else if ( theNbNodes == 13 ) return VTK_QUADRATIC_PYRAMID;\/\/VTK_CONVEX_POINT_SET;\n else return VTK_EMPTY_CELL;\n\n default: return VTK_EMPTY_CELL;\n }\n}\n\n\/\/================================================================================\n\/*!\n * \\brief Set preview data\n *\/\n\/\/================================================================================\n\nvoid SMESHGUI_MeshEditPreview::SetData (const SMESH::MeshPreviewStruct* previewData)\n{\n \/\/ Create points\n const SMESH::nodes_array& aNodesXYZ = previewData->nodesXYZ;\n vtkPoints* aPoints = vtkPoints::New();\n aPoints->SetNumberOfPoints(aNodesXYZ.length());\n\n for ( int i = 0; i < aNodesXYZ.length(); i++ ) {\n aPoints->SetPoint( i, aNodesXYZ[i].x, aNodesXYZ[i].y, aNodesXYZ[i].z );\n }\n myGrid->SetPoints(aPoints);\n\n aPoints->Delete();\n\n \/\/ Create cells\n const SMESH::long_array& anElemConnectivity = previewData->elementConnectivities;\n const SMESH::types_array& anElemTypes = previewData->elementTypes;\n\n vtkIdType aCellsSize = anElemConnectivity.length() + anElemTypes.length();\n vtkIdType aNbCells = anElemTypes.length();\n\n vtkCellArray* aConnectivity = vtkCellArray::New();\n aConnectivity->Allocate( aCellsSize, 0 );\n\n vtkUnsignedCharArray* aCellTypesArray = vtkUnsignedCharArray::New();\n aCellTypesArray->SetNumberOfComponents( 1 );\n aCellTypesArray->Allocate( aNbCells * aCellTypesArray->GetNumberOfComponents() );\n\n vtkIdList *anIdList = vtkIdList::New();\n int aNodePos = 0;\n\n for ( int i = 0; i < anElemTypes.length(); i++ ) {\n const SMESH::ElementSubType& anElementSubType = anElemTypes[i];\n SMDSAbs_ElementType aType = SMDSAbs_ElementType(anElementSubType.SMDS_ElementType);\n vtkIdType aNbNodes = anElementSubType.nbNodesInElement;\n anIdList->SetNumberOfIds( aNbNodes );\n\n for ( vtkIdType aNodeId = 0; aNodeId < aNbNodes; aNodeId++ ){\n anIdList->SetId( aNodeId, anElemConnectivity[aNodePos] );\n aNodePos++;\n }\n\n aConnectivity->InsertNextCell( anIdList );\n aCellTypesArray->InsertNextValue( getCellType( aType,\n anElemTypes[i].isPoly, \n aNbNodes ) );\n }\n anIdList->Delete();\n\n \/\/ Insert cells in grid\n VTKViewer_CellLocationsArray* aCellLocationsArray = VTKViewer_CellLocationsArray::New();\n aCellLocationsArray->SetNumberOfComponents( 1 );\n aCellLocationsArray->SetNumberOfTuples( aNbCells );\n\n aConnectivity->InitTraversal();\n for( vtkIdType idType = 0, *pts, npts; aConnectivity->GetNextCell( npts, pts ); idType++ )\n aCellLocationsArray->SetValue( idType, aConnectivity->GetTraversalLocation( npts ) );\n\n myGrid->SetCells( aCellTypesArray, aCellLocationsArray, aConnectivity );\n\n myPreviewActor->GetMapper()->Update();\n\n aCellTypesArray->Delete();\n aCellLocationsArray->Delete();\n aConnectivity->Delete();\n\n SetVisibility(true);\n}\n\n\/\/================================================================================\n\/*!\n * \\brief Set shape of an arrow of a unit length and nb of arrows\n *\/\n\/\/================================================================================\n\nvoid SMESHGUI_MeshEditPreview::SetArrowShapeAndNb( int nbArrows,\n double headLength,\n double headRadius,\n double start,\n const char* labels)\n{\n const int theNbPoints = 10; \/\/ in one arrow\n myUnitArrowPnts.reserve( theNbPoints );\n myUnitArrowPnts.clear();\n\n \/\/ unit arrow || OZ\n\n for ( int i = 0; i < theNbPoints - 2; ++i )\n {\n double angle = i * 2 * M_PI \/ ( theNbPoints - 2 );\n myUnitArrowPnts.push_back( gp_Pnt( headRadius * Cos( angle ),\n headRadius * Sin( angle ),\n 1. - headLength ));\n }\n myUnitArrowPnts.push_back( gp_Pnt( 0, 0, start ));\n myUnitArrowPnts.push_back( gp_Pnt( 0, 0, 1 ));\n\n\n \/\/ nodes of all arrows\n\n vtkPoints* aPoints = vtkPoints::New();\n aPoints->SetNumberOfPoints( theNbPoints * nbArrows );\n for ( int iP = 0, iA = 0; iA < nbArrows; ++iA )\n for ( int i = 0; i < theNbPoints; ++i, ++iP )\n aPoints->SetPoint( iP,\n myUnitArrowPnts[i].X(),\n myUnitArrowPnts[i].Y(),\n myUnitArrowPnts[i].Z() );\n myGrid->SetPoints(aPoints);\n aPoints->Delete();\n\n \/\/ connectivity of all arrows\n\n const int theNbCells = ( theNbPoints - 1 ); \/\/ in one arrow\n myGrid->Allocate( theNbCells * nbArrows );\n for ( int nP = 0, iA = 0; iA < nbArrows; ++iA, nP += theNbPoints )\n {\n vtkIdType conn[3] = { theNbPoints - 1 + nP, \/\/ arrow end\n theNbPoints - 3 + nP, \/\/ point on a circle\n nP }; \/\/ point on a circle\n for ( int i = 0; i < theNbCells-1; ++i )\n {\n myGrid->InsertNextCell( VTK_TRIANGLE, 3, conn );\n conn[1] = conn[2];\n conn[2] = conn[2] + 1;\n }\n conn[1] = theNbPoints - 2 + nP;\n myGrid->InsertNextCell( VTK_LINE, 2, conn );\n }\n\n myLabelActors.resize( nbArrows, ( vtkTextActor*) NULL );\n char label[] = \"X\";\n if ( labels )\n for ( int iP = 0, iA = 0; iA < nbArrows; ++iA )\n {\n label[0] = labels[iA];\n vtkTextMapper* text = vtkTextMapper::New();\n text->SetInput( label );\n vtkCoordinate* coord = vtkCoordinate::New();\n\n myLabelActors[iA] = vtkTextActor::New();\n \/\/myLabelActors[iA]->SetMapper( text );\n myLabelActors[iA]->SetInput( label );\n myLabelActors[iA]->SetTextScaleModeToNone();\n myLabelActors[iA]->PickableOff();\n myLabelActors[iA]->GetPositionCoordinate()->SetReferenceCoordinate( coord );\n\n text->Delete();\n coord->Delete();\n\n myPreviewActor->GetRenderer()->AddActor(myLabelActors[iA]);\n }\n}\n\n\/\/================================================================================\n\/*!\n * \\brief Set data to show moved\/rotated\/scaled arrows\n * \\param [in] axes - location and direction of the arrows\n * \\param [in] length - length of arrows\n *\/\n\/\/================================================================================\n\nvoid SMESHGUI_MeshEditPreview::SetArrows( const gp_Ax1* axes,\n double length )\n{\n vtkPoints* aPoints = myGrid->GetPoints();\n\n for ( int iP = 0, iA = 0; iA < myLabelActors.size(); ++iA )\n {\n gp_Trsf trsf;\n trsf.SetTransformation( gp_Ax3( axes[iA].Location(), axes[iA].Direction() ), gp::XOY() );\n\n for ( size_t i = 0; i < myUnitArrowPnts.size(); ++i, ++iP )\n {\n gp_Pnt p = myUnitArrowPnts[i].Scaled( gp::Origin(), length );\n p.Transform( trsf );\n aPoints->SetPoint( iP, p.X(), p.Y(), p.Z() );\n }\n if ( myLabelActors[iA] )\n if ( vtkCoordinate* aCoord =\n myLabelActors[iA]->GetPositionCoordinate()->GetReferenceCoordinate() )\n {\n double p[3];\n aPoints->GetPoint( iP-1, p );\n aCoord->SetValue( p );\n }\n }\n\n myGrid->Modified();\n}\n\n\/\/================================================================================\n\/*!\n * \\brief Set visibility\n *\/\n\/\/================================================================================\n\nvoid SMESHGUI_MeshEditPreview::SetVisibility (bool theVisibility)\n{\n myPreviewActor->SetVisibility(theVisibility);\n for ( size_t iA = 0; iA < myLabelActors.size(); ++iA )\n if ( myLabelActors[iA] )\n myLabelActors[iA]->SetVisibility(theVisibility);\n SMESH::RepaintCurrentView();\n}\n\n\/\/================================================================================\n\/*!\n * \\brief Set preview color\n *\/\n\/\/================================================================================\n\nvoid SMESHGUI_MeshEditPreview::SetColor(double R, double G, double B)\n{\n myPreviewActor->SetColor( R, G, B );\n}\n\n\/\/================================================================================\n\/*!\n * \\brief Get preview actor\n *\/\n\/\/================================================================================\n\nSALOME_Actor* SMESHGUI_MeshEditPreview::GetActor() const\n{ \n return myPreviewActor;\n}\n\n\/\/================================================================================\n\/*!\n * \\brief Returns the priewed vtkUnstructuredGrid\n *\/\n\/\/================================================================================\n\nvtkUnstructuredGrid* SMESHGUI_MeshEditPreview::GetGrid() const\n{\n return myGrid;\n}\n<commit_msg>22359: Body Fitting algorithm: grid orientation<commit_after>\/\/ Copyright (C) 2007-2013 CEA\/DEN, EDF R&D, OPEN CASCADE\n\/\/\n\/\/ Copyright (C) 2003-2007 OPEN CASCADE, EADS\/CCR, LIP6, CEA\/DEN,\n\/\/ CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS\n\/\/\n\/\/ This library is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU Lesser General Public\n\/\/ License as published by the Free Software Foundation; either\n\/\/ version 2.1 of the License.\n\/\/\n\/\/ This library is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ Lesser General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License along with this library; if not, write to the Free Software\n\/\/ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n\/\/\n\/\/ See http:\/\/www.salome-platform.org\/ or email : webmaster.salome@opencascade.com\n\/\/\n\n\/\/ SMESH SMESHGUI : GUI for SMESH component\n\/\/ File : SMESHGUI_MeshEditPreview.cxx\n\/\/ Author : Open CASCADE S.A.S.\n\/\/ SMESH includes\n\/\/\n#include \"SMESHGUI_MeshEditPreview.h\"\n\n#include \"SMESHGUI_VTKUtils.h\"\n#include \"SMESH_Actor.h\"\n#include \"SMESH_ActorUtils.h\"\n\n\/\/ SALOME GUI includes\n#include <SVTK_Renderer.h>\n#include <SVTK_ViewWindow.h>\n#include <VTKViewer_CellLocationsArray.h>\n\n\/\/ VTK includes\n#include <vtkCellArray.h>\n#include <vtkCoordinate.h>\n#include <vtkDataSetMapper.h>\n#include <vtkIdList.h>\n#include <vtkPoints.h>\n#include <vtkProperty.h>\n#include <vtkRenderer.h>\n#include <vtkTextActor.h>\n#include <vtkTextMapper.h>\n#include <vtkUnsignedCharArray.h>\n#include <vtkUnstructuredGrid.h>\n\n\/\/ Qt includes\n#include <QColor>\n\n\/\/ IDL includes\n#include <SALOMEconfig.h>\n#include CORBA_SERVER_HEADER(SMESH_MeshEditor)\n\n#include <gp_Ax3.hxx>\n\n\/\/================================================================================\n\/*!\n * \\brief Constructor\n *\/\n\/\/================================================================================\n\nSMESHGUI_MeshEditPreview::SMESHGUI_MeshEditPreview(SVTK_ViewWindow* theViewWindow):\n myViewWindow(theViewWindow)\n{\n myGrid = vtkUnstructuredGrid::New();\n\n \/\/ Create and display actor\n vtkDataSetMapper* aMapper = vtkDataSetMapper::New();\n aMapper->SetInputData( myGrid );\n\n myPreviewActor = SALOME_Actor::New();\n myPreviewActor->SetInfinitive(true);\n myPreviewActor->VisibilityOn();\n myPreviewActor->PickableOff();\n\n double aFactor,aUnits;\n myPreviewActor->SetResolveCoincidentTopology(true);\n myPreviewActor->GetPolygonOffsetParameters(aFactor,aUnits);\n myPreviewActor->SetPolygonOffsetParameters(aFactor,0.2*aUnits);\n\n double anRGB[3];\n SMESH::GetColor( \"SMESH\", \"selection_element_color\", anRGB[0], anRGB[1], anRGB[2], QColor( 0, 170, 255 ) );\n SetColor( anRGB[0], anRGB[1], anRGB[2] );\n\n myPreviewActor->SetMapper( aMapper );\n aMapper->Delete();\n\n myViewWindow->AddActor(myPreviewActor);\n}\n\n\/\/================================================================================\n\/*!\n * \\brief Destroy\n *\/\n\/\/================================================================================\n\nSMESHGUI_MeshEditPreview::~SMESHGUI_MeshEditPreview()\n{\n myGrid->Delete();\n\n for ( size_t iA = 0; iA < myLabelActors.size(); ++iA )\n if ( myLabelActors[iA] )\n {\n myPreviewActor->GetRenderer()->RemoveActor( myLabelActors[iA] );\n myLabelActors[iA]->Delete();\n }\n\n myViewWindow->RemoveActor(myPreviewActor);\n myPreviewActor->Delete();\n}\n\n\/\/================================================================================\n\/*!\n * \\brief Returns vtk cell type\n *\/\n\/\/================================================================================\n\nvtkIdType getCellType( const SMDSAbs_ElementType theType,\n const bool thePoly,\n const int theNbNodes )\n{\n switch( theType ) \n {\n case SMDSAbs_Node: return VTK_VERTEX;\n case SMDSAbs_Edge: \n if( theNbNodes == 2 ) return VTK_LINE;\n else if ( theNbNodes == 3 ) return VTK_QUADRATIC_EDGE;\n else return VTK_EMPTY_CELL;\n\n case SMDSAbs_Face :\n if (thePoly && theNbNodes>2 ) return VTK_POLYGON;\n else if ( theNbNodes == 3 ) return VTK_TRIANGLE;\n else if ( theNbNodes == 4 ) return VTK_QUAD;\n else if ( theNbNodes == 6 ) return VTK_QUADRATIC_TRIANGLE;\n else if ( theNbNodes == 7 ) return VTK_BIQUADRATIC_TRIANGLE;\n else if ( theNbNodes == 8 ) return VTK_QUADRATIC_QUAD;\n else if ( theNbNodes == 9 ) return VTK_BIQUADRATIC_QUAD;\n else return VTK_EMPTY_CELL;\n\n case SMDSAbs_Volume:\n if (thePoly && theNbNodes>3 ) return VTK_CONVEX_POINT_SET;\n else if ( theNbNodes == 4 ) return VTK_TETRA;\n else if ( theNbNodes == 5 ) return VTK_PYRAMID;\n else if ( theNbNodes == 6 ) return VTK_WEDGE;\n else if ( theNbNodes == 8 ) return VTK_HEXAHEDRON;\n else if ( theNbNodes == 10 ) return VTK_QUADRATIC_TETRA;\n else if ( theNbNodes == 20 ) return VTK_QUADRATIC_HEXAHEDRON;\n else if ( theNbNodes == 27 ) return VTK_TRIQUADRATIC_HEXAHEDRON;\n else if ( theNbNodes == 15 ) return VTK_QUADRATIC_WEDGE;\n else if ( theNbNodes == 13 ) return VTK_QUADRATIC_PYRAMID;\/\/VTK_CONVEX_POINT_SET;\n else return VTK_EMPTY_CELL;\n\n default: return VTK_EMPTY_CELL;\n }\n}\n\n\/\/================================================================================\n\/*!\n * \\brief Set preview data\n *\/\n\/\/================================================================================\n\nvoid SMESHGUI_MeshEditPreview::SetData (const SMESH::MeshPreviewStruct* previewData)\n{\n \/\/ Create points\n const SMESH::nodes_array& aNodesXYZ = previewData->nodesXYZ;\n vtkPoints* aPoints = vtkPoints::New();\n aPoints->SetNumberOfPoints(aNodesXYZ.length());\n\n for ( int i = 0; i < aNodesXYZ.length(); i++ ) {\n aPoints->SetPoint( i, aNodesXYZ[i].x, aNodesXYZ[i].y, aNodesXYZ[i].z );\n }\n myGrid->SetPoints(aPoints);\n\n aPoints->Delete();\n\n \/\/ Create cells\n const SMESH::long_array& anElemConnectivity = previewData->elementConnectivities;\n const SMESH::types_array& anElemTypes = previewData->elementTypes;\n\n vtkIdType aCellsSize = anElemConnectivity.length() + anElemTypes.length();\n vtkIdType aNbCells = anElemTypes.length();\n\n vtkCellArray* aConnectivity = vtkCellArray::New();\n aConnectivity->Allocate( aCellsSize, 0 );\n\n vtkUnsignedCharArray* aCellTypesArray = vtkUnsignedCharArray::New();\n aCellTypesArray->SetNumberOfComponents( 1 );\n aCellTypesArray->Allocate( aNbCells * aCellTypesArray->GetNumberOfComponents() );\n\n vtkIdList *anIdList = vtkIdList::New();\n int aNodePos = 0;\n\n for ( int i = 0; i < anElemTypes.length(); i++ ) {\n const SMESH::ElementSubType& anElementSubType = anElemTypes[i];\n SMDSAbs_ElementType aType = SMDSAbs_ElementType(anElementSubType.SMDS_ElementType);\n vtkIdType aNbNodes = anElementSubType.nbNodesInElement;\n anIdList->SetNumberOfIds( aNbNodes );\n\n for ( vtkIdType aNodeId = 0; aNodeId < aNbNodes; aNodeId++ ){\n anIdList->SetId( aNodeId, anElemConnectivity[aNodePos] );\n aNodePos++;\n }\n\n aConnectivity->InsertNextCell( anIdList );\n aCellTypesArray->InsertNextValue( getCellType( aType,\n anElemTypes[i].isPoly, \n aNbNodes ) );\n }\n anIdList->Delete();\n\n \/\/ Insert cells in grid\n VTKViewer_CellLocationsArray* aCellLocationsArray = VTKViewer_CellLocationsArray::New();\n aCellLocationsArray->SetNumberOfComponents( 1 );\n aCellLocationsArray->SetNumberOfTuples( aNbCells );\n\n aConnectivity->InitTraversal();\n for( vtkIdType idType = 0, *pts, npts; aConnectivity->GetNextCell( npts, pts ); idType++ )\n aCellLocationsArray->SetValue( idType, aConnectivity->GetTraversalLocation( npts ) );\n\n myGrid->SetCells( aCellTypesArray, aCellLocationsArray, aConnectivity );\n\n myPreviewActor->GetMapper()->Update();\n\n aCellTypesArray->Delete();\n aCellLocationsArray->Delete();\n aConnectivity->Delete();\n\n SetVisibility(true);\n}\n\n\/\/================================================================================\n\/*!\n * \\brief Set shape of an arrow of a unit length and nb of arrows\n *\/\n\/\/================================================================================\n\nvoid SMESHGUI_MeshEditPreview::SetArrowShapeAndNb( int nbArrows,\n double headLength,\n double headRadius,\n double start,\n const char* labels)\n{\n const int theNbPoints = 10; \/\/ in one arrow\n myUnitArrowPnts.reserve( theNbPoints );\n myUnitArrowPnts.clear();\n\n \/\/ unit arrow || OZ\n\n for ( int i = 0; i < theNbPoints - 2; ++i )\n {\n double angle = i * 2 * M_PI \/ ( theNbPoints - 2 );\n myUnitArrowPnts.push_back( gp_Pnt( headRadius * Cos( angle ),\n headRadius * Sin( angle ),\n 1. - headLength ));\n }\n myUnitArrowPnts.push_back( gp_Pnt( 0, 0, start ));\n myUnitArrowPnts.push_back( gp_Pnt( 0, 0, 1 ));\n\n\n \/\/ nodes of all arrows\n\n vtkPoints* aPoints = vtkPoints::New();\n aPoints->SetNumberOfPoints( theNbPoints * nbArrows );\n for ( int iP = 0, iA = 0; iA < nbArrows; ++iA )\n for ( int i = 0; i < theNbPoints; ++i, ++iP )\n aPoints->SetPoint( iP,\n myUnitArrowPnts[i].X(),\n myUnitArrowPnts[i].Y(),\n myUnitArrowPnts[i].Z() );\n myGrid->SetPoints(aPoints);\n aPoints->Delete();\n\n \/\/ connectivity of all arrows\n\n const int theNbCells = ( theNbPoints - 1 ); \/\/ in one arrow\n myGrid->Allocate( theNbCells * nbArrows );\n for ( int nP = 0, iA = 0; iA < nbArrows; ++iA, nP += theNbPoints )\n {\n vtkIdType conn[3] = { theNbPoints - 1 + nP, \/\/ arrow end\n theNbPoints - 3 + nP, \/\/ point on a circle\n nP }; \/\/ point on a circle\n for ( int i = 0; i < theNbCells-1; ++i )\n {\n myGrid->InsertNextCell( VTK_TRIANGLE, 3, conn );\n conn[1] = conn[2];\n conn[2] = conn[2] + 1;\n }\n conn[1] = theNbPoints - 2 + nP;\n myGrid->InsertNextCell( VTK_LINE, 2, conn );\n }\n\n myLabelActors.resize( nbArrows, ( vtkTextActor*) NULL );\n char label[] = \"X\";\n if ( labels )\n for ( int iP = 0, iA = 0; iA < nbArrows; ++iA )\n {\n label[0] = labels[iA];\n vtkTextMapper* text = vtkTextMapper::New();\n text->SetInput( label );\n vtkCoordinate* coord = vtkCoordinate::New();\n\n myLabelActors[iA] = vtkTextActor::New();\n \/\/myLabelActors[iA]->SetMapper( text );\n myLabelActors[iA]->SetInput( label );\n myLabelActors[iA]->SetTextScaleModeToNone();\n myLabelActors[iA]->PickableOff();\n myLabelActors[iA]->GetPositionCoordinate()->SetReferenceCoordinate( coord );\n\n text->Delete();\n coord->Delete();\n\n myPreviewActor->GetRenderer()->AddActor(myLabelActors[iA]);\n }\n}\n\n\/\/================================================================================\n\/*!\n * \\brief Set data to show moved\/rotated\/scaled arrows\n * \\param [in] axes - location and direction of the arrows\n * \\param [in] length - length of arrows\n *\/\n\/\/================================================================================\n\nvoid SMESHGUI_MeshEditPreview::SetArrows( const gp_Ax1* axes,\n double length )\n{\n vtkPoints* aPoints = myGrid->GetPoints();\n\n for ( int iP = 0, iA = 0; iA < myLabelActors.size(); ++iA )\n {\n gp_Trsf trsf;\n trsf.SetTransformation( gp_Ax3( axes[iA].Location(), axes[iA].Direction() ), gp::XOY() );\n\n for ( size_t i = 0; i < myUnitArrowPnts.size(); ++i, ++iP )\n {\n gp_Pnt p = myUnitArrowPnts[i].Scaled( gp::Origin(), length );\n p.Transform( trsf );\n aPoints->SetPoint( iP, p.X(), p.Y(), p.Z() );\n }\n if ( myLabelActors[iA] )\n if ( vtkCoordinate* aCoord =\n myLabelActors[iA]->GetPositionCoordinate()->GetReferenceCoordinate() )\n {\n double p[3];\n aPoints->GetPoint( iP-1, p );\n aCoord->SetValue( p );\n }\n }\n\n myGrid->Modified();\n}\n\n\/\/================================================================================\n\/*!\n * \\brief Set visibility\n *\/\n\/\/================================================================================\n\nvoid SMESHGUI_MeshEditPreview::SetVisibility (bool theVisibility)\n{\n myPreviewActor->SetVisibility(theVisibility);\n for ( size_t iA = 0; iA < myLabelActors.size(); ++iA )\n if ( myLabelActors[iA] )\n myLabelActors[iA]->SetVisibility(theVisibility);\n SMESH::RepaintCurrentView();\n}\n\n\/\/================================================================================\n\/*!\n * \\brief Set preview color\n *\/\n\/\/================================================================================\n\nvoid SMESHGUI_MeshEditPreview::SetColor(double R, double G, double B)\n{\n myPreviewActor->SetColor( R, G, B );\n}\n\n\/\/================================================================================\n\/*!\n * \\brief Get preview actor\n *\/\n\/\/================================================================================\n\nSALOME_Actor* SMESHGUI_MeshEditPreview::GetActor() const\n{ \n return myPreviewActor;\n}\n\n\/\/================================================================================\n\/*!\n * \\brief Returns the priewed vtkUnstructuredGrid\n *\/\n\/\/================================================================================\n\nvtkUnstructuredGrid* SMESHGUI_MeshEditPreview::GetGrid() const\n{\n return myGrid;\n}\n<|endoftext|>"} {"text":"<commit_before>#include <algorithm>\n#include <istream>\n#include <sstream>\n\n#include \"parsers\/parse_error.hh\"\n#include \"parsers\/tina.hh\"\n#include \"pn\/arc.hh\"\n\nnamespace pnmc { namespace parsers {\n\n\/*------------------------------------------------------------------------------------------------*\/\n\n\n\/*------------------------------------------------------------------------------------------------*\/\n\nstd::pair<std::string, unsigned int>\nplace_valuation(const std::string& s)\n{\n const auto star_cit = std::find(s.cbegin(), s.cend(), '*');\n if (star_cit == s.cend())\n {\n return std::make_pair(s, 1);\n }\n try\n {\n const auto valuation = std::stoi(std::string(star_cit + 1, s.cend()));\n return std::make_pair(std::string(s.cbegin(), star_cit), valuation);\n }\n catch (const std::invalid_argument&)\n {\n throw parse_error();\n }\n}\n\n\/*------------------------------------------------------------------------------------------------*\/\n\nunsigned int\nmarking(const std::string& s)\n{\n if (*s.cbegin() == '(' and *std::prev(s.cend()) == ')')\n {\n try\n {\n return std::stoi(std::string(std::next(s.cbegin()), std::prev(s.cend())));\n }\n catch (const std::invalid_argument&)\n {\n throw parse_error();\n }\n }\n else\n {\n throw parse_error();\n }\n}\n\n\/*------------------------------------------------------------------------------------------------*\/\n\nstd::shared_ptr<pn::net>\ntina(std::istream& in)\n{\n std::shared_ptr<pn::net> net_ptr = std::make_shared<pn::net>();\n auto& net = *net_ptr;\n\n try\n {\n std::string line, s0, s1, s2;\n line.reserve(1024);\n\n while (std::getline(in, line))\n {\n std::istringstream ss(line);\n\n \/\/ Empty line or comment.\n if (((ss >> std::ws).peek() == '#') or not (ss >> s0))\n {\n continue;\n }\n\n \/\/ Net\n if (s0 == \"net\")\n {\n continue;\n }\n\n \/\/ Transitions\n else if (s0 == \"tr\")\n {\n std::string place_id;\n unsigned int valuation;\n\n if (ss >> s0)\n {\n net.add_transition(s0, \"\");\n }\n else\n {\n throw parse_error();\n }\n\n \/\/ Skip time interval, if any.\n const auto c = (ss >> std::ws).peek();\n if (c == '[' or c == ']')\n {\n ss >> s1;\n }\n\n while (ss >> s1)\n {\n if (s1 == \"->\")\n {\n break;\n }\n std::tie(place_id, valuation) = place_valuation(s1);\n net.add_pre_place(s0, place_id, pn::arc(valuation));\n }\n\n while (ss >> s1)\n {\n std::tie(place_id, valuation) = place_valuation(s1);\n net.add_post_place(s0, place_id, pn::arc(valuation));\n }\n }\n\n \/\/ Places\n else if (s0 == \"pl\")\n {\n if (ss >> s1 >> s2)\n {\n net.add_place(s1, \"\", marking(s2));\n }\n else\n {\n throw parse_error();\n }\n }\n\n \/\/ Error.\n else\n {\n throw parse_error();\n }\n }\n }\n catch (const parse_error&)\n {\n return nullptr;\n }\n\n return net_ptr;\n}\n\n\/*------------------------------------------------------------------------------------------------*\/\n\n}} \/\/ namespace pnmc::parsers\n<commit_msg>Add some diagnostic messages for the TINA parser.<commit_after>#include <algorithm>\n#include <istream>\n#include <sstream>\n\n#include \"parsers\/parse_error.hh\"\n#include \"parsers\/tina.hh\"\n#include \"pn\/arc.hh\"\n\nnamespace pnmc { namespace parsers {\n\n\/*------------------------------------------------------------------------------------------------*\/\n\n\n\/*------------------------------------------------------------------------------------------------*\/\n\nstd::pair<std::string, unsigned int>\nplace_valuation(const std::string& s)\n{\n const auto star_cit = std::find(s.cbegin(), s.cend(), '*');\n if (star_cit == s.cend())\n {\n return std::make_pair(s, 1);\n }\n try\n {\n const auto valuation = std::stoi(std::string(star_cit + 1, s.cend()));\n return std::make_pair(std::string(s.cbegin(), star_cit), valuation);\n }\n catch (const std::invalid_argument&)\n {\n throw parse_error(\"Valuation '\" + std::string(star_cit + 1, s.cend()) + \"' is not a value\");\n }\n}\n\n\/*------------------------------------------------------------------------------------------------*\/\n\nunsigned int\nmarking(const std::string& s)\n{\n if (*s.cbegin() == '(' and *std::prev(s.cend()) == ')')\n {\n try\n {\n return std::stoi(std::string(std::next(s.cbegin()), std::prev(s.cend())));\n }\n catch (const std::invalid_argument&)\n {\n throw parse_error( \"Marking '\" + std::string(std::next(s.cbegin()), std::prev(s.cend()))\n + \"' is not a value\");\n }\n }\n else\n {\n throw parse_error(\"Invalid marking format: \" + s);\n }\n}\n\n\/*------------------------------------------------------------------------------------------------*\/\n\nstd::shared_ptr<pn::net>\ntina(std::istream& in)\n{\n std::shared_ptr<pn::net> net_ptr = std::make_shared<pn::net>();\n auto& net = *net_ptr;\n\n try\n {\n std::string line, s0, s1, s2;\n line.reserve(1024);\n\n while (std::getline(in, line))\n {\n std::istringstream ss(line);\n\n \/\/ Empty line or comment.\n if (((ss >> std::ws).peek() == '#') or not (ss >> s0))\n {\n continue;\n }\n\n \/\/ Net\n if (s0 == \"net\")\n {\n continue;\n }\n\n \/\/ Transitions\n else if (s0 == \"tr\")\n {\n std::string place_id;\n unsigned int valuation;\n\n if (ss >> s0)\n {\n net.add_transition(s0, \"\");\n }\n else\n {\n throw parse_error(\"Invalid transition: \" + line);\n }\n\n \/\/ Skip time interval, if any.\n const auto c = (ss >> std::ws).peek();\n if (c == '[' or c == ']')\n {\n ss >> s1;\n }\n\n while (ss >> s1)\n {\n if (s1 == \"->\")\n {\n break;\n }\n std::tie(place_id, valuation) = place_valuation(s1);\n net.add_pre_place(s0, place_id, pn::arc(valuation));\n }\n\n while (ss >> s1)\n {\n std::tie(place_id, valuation) = place_valuation(s1);\n net.add_post_place(s0, place_id, pn::arc(valuation));\n }\n }\n\n \/\/ Places\n else if (s0 == \"pl\")\n {\n if (ss >> s1 >> s2)\n {\n net.add_place(s1, \"\", marking(s2));\n }\n else\n {\n throw parse_error(\"Invalid place: \" + line);\n }\n }\n\n \/\/ Error.\n else\n {\n throw parse_error(\"Invalid line: \" + line);\n }\n }\n }\n catch (const parse_error& p)\n {\n std::cerr << p.what() << std::endl;\n return nullptr;\n }\n\n return net_ptr;\n}\n\n\/*------------------------------------------------------------------------------------------------*\/\n\n}} \/\/ namespace pnmc::parsers\n<|endoftext|>"} {"text":"<commit_before>\/* Copyright (c) 2010-2017, AOYAMA Kazuharu\n * All rights reserved.\n *\n * This software may be used and distributed according to the terms of\n * the New BSD License, which is incorporated herein by reference.\n *\/\n\n#include <QtCore>\n#include <QtSql>\n#include \"tableschema.h\"\n#include \"global.h\"\n\nQSettings *dbSettings = 0;\n\n\nTableSchema::TableSchema(const QString &table, const QString &env)\n : tablename(table)\n{\n if (!dbSettings) {\n QString path = QLatin1String(\"config\") + QDir::separator() + \"database.ini\";\n if (!QFile::exists(path)) {\n qCritical(\"not found, %s\", qPrintable(path));\n }\n dbSettings = new QSettings(path, QSettings::IniFormat);\n }\n\n if (openDatabase(env)) {\n if (!tablename.isEmpty()) {\n QSqlTableModel model;\n model.setTable(tablename);\n tableFields = model.record();\n\n if (model.database().driverName().toUpper() == \"QPSQL\") {\n \/\/ QPSQLResult doesn't call QSqlField::setAutoValue(), fix it\n for (int i = 0; i < tableFields.count(); ++i) {\n QSqlField f = tableFields.field(i);\n if (f.defaultValue().toString().startsWith(QLatin1String(\"nextval\"))) {\n f.setAutoValue(true);\n tableFields.replace(i, f);\n }\n }\n }\n } else {\n qCritical(\"Empty table name\");\n }\n }\n}\n\n\nbool TableSchema::exists() const\n{\n return (tableFields.count() > 0);\n}\n\n\nQList<QPair<QString, QString>> TableSchema::getFieldList() const\n{\n QList<QPair<QString, QString>> fieldList;\n for (int i = 0; i < tableFields.count(); ++i) {\n QSqlField f = tableFields.field(i);\n fieldList << QPair<QString, QString>(f.name(), QString(QVariant::typeToName(f.type())));\n }\n return fieldList;\n}\n\n\nQList<QPair<QString, QVariant::Type>> TableSchema::getFieldTypeList() const\n{\n QList<QPair<QString, QVariant::Type>> fieldList;\n for (int i = 0; i < tableFields.count(); ++i) {\n QSqlField f = tableFields.field(i);\n fieldList << QPair<QString, QVariant::Type>(f.name(), f.type());\n }\n return fieldList;\n}\n\n\nint TableSchema::primaryKeyIndex() const\n{\n QSqlTableModel model;\n model.setTable(tablename);\n QSqlIndex index = model.primaryKey();\n if (index.isEmpty()) {\n return -1;\n }\n\n QSqlField fi = index.field(0);\n return model.record().indexOf(fi.name());\n}\n\n\nQString TableSchema::primaryKeyFieldName() const\n{\n QSqlTableModel model;\n model.setTable(tablename);\n QSqlIndex index = model.primaryKey();\n if (index.isEmpty()) {\n return QString();\n }\n\n QSqlField fi = index.field(0);\n return fi.name();\n}\n\n\nint TableSchema::autoValueIndex() const\n{\n for (int i = 0; i < tableFields.count(); ++i) {\n QSqlField f = tableFields.field(i);\n if (f.isAutoValue())\n return i;\n }\n return -1;\n}\n\n\nQString TableSchema::autoValueFieldName() const\n{\n for (int i = 0; i < tableFields.count(); ++i) {\n QSqlField f = tableFields.field(i);\n if (f.isAutoValue())\n return f.name();\n }\n return QString();\n}\n\n\nQPair<QString, QString> TableSchema::getPrimaryKeyField() const\n{\n QPair<QString, QString> pair;\n int index = primaryKeyIndex();\n if (index >= 0) {\n QSqlField f = tableFields.field(index);\n pair = QPair<QString, QString>(f.name(), QString(QVariant::typeToName(f.type())));\n }\n return pair;\n}\n\n\nQPair<QString, QVariant::Type> TableSchema::getPrimaryKeyFieldType() const\n{\n QPair<QString, QVariant::Type> pair;\n int index = primaryKeyIndex();\n if (index >= 0) {\n QSqlField f = tableFields.field(index);\n pair = QPair<QString, QVariant::Type>(f.name(), f.type());\n }\n return pair;\n}\n\n\nint TableSchema::lockRevisionIndex() const\n{\n for (int i = 0; i < tableFields.count(); ++i) {\n QSqlField f = tableFields.field(i);\n if (fieldNameToVariableName(f.name()) == \"lockRevision\") {\n return i;\n }\n }\n return -1;\n}\n\n\nbool TableSchema::hasLockRevisionField() const\n{\n return lockRevisionIndex() >= 0;\n}\n\n\nbool TableSchema::openDatabase(const QString &env) const\n{\n if (isOpen())\n return true;\n\n if (!dbSettings->childGroups().contains(env)) {\n qCritical(\"invalid environment: %s\", qPrintable(env));\n return false;\n }\n\n dbSettings->beginGroup(env);\n\n QString driverType = dbSettings->value(\"DriverType\").toString().trimmed();\n if (driverType.isEmpty()) {\n qWarning(\"Parameter 'DriverType' is empty\");\n }\n printf(\"DriverType: %s\", qPrintable(driverType));\n\n QSqlDatabase db = QSqlDatabase::addDatabase(driverType);\n if (!db.isValid()) {\n qWarning(\"Parameter 'DriverType' is invalid or RDB client library not available.\");\n return false;\n }\n\n QString databaseName = dbSettings->value(\"DatabaseName\").toString().trimmed();\n printf(\"DatabaseName: %s\", qPrintable(databaseName));\n if (!databaseName.isEmpty())\n db.setDatabaseName(databaseName);\n\n QString hostName = dbSettings->value(\"HostName\").toString().trimmed();\n printf(\"HostName: %s\", qPrintable(hostName));\n if (!hostName.isEmpty())\n db.setHostName(hostName);\n\n int port = dbSettings->value(\"Port\").toInt();\n if (port > 0)\n db.setPort(port);\n\n QString userName = dbSettings->value(\"UserName\").toString().trimmed();\n if (!userName.isEmpty())\n db.setUserName(userName);\n\n QString password = dbSettings->value(\"Password\").toString().trimmed();\n if (!password.isEmpty())\n db.setPassword(password);\n\n QString connectOptions = dbSettings->value(\"ConnectOptions\").toString().trimmed();\n if (!connectOptions.isEmpty())\n db.setConnectOptions(connectOptions);\n\n dbSettings->endGroup();\n\n if (!db.open()) {\n qWarning(\"Database open error\");\n return false;\n }\n\n printf(\"Database opened successfully\");\n return true;\n}\n\n\nbool TableSchema::isOpen() const\n{\n return QSqlDatabase::database().isOpen();\n}\n\n\nQStringList TableSchema::databaseDrivers()\n{\n return QSqlDatabase::drivers();\n}\n\n\nQStringList TableSchema::tables(const QString &env)\n{\n QSet<QString> set;\n TableSchema dummy(\"dummy\", env); \/\/ to open database\n\n if (QSqlDatabase::database().isOpen()) {\n for (QStringListIterator i(QSqlDatabase::database().tables(QSql::Tables)); i.hasNext(); ) {\n TableSchema t(i.next());\n if (t.exists())\n set << t.tableName(); \/\/ If value already exists, the set is left unchanged\n }\n }\n\n QStringList ret = set.toList();\n qSort(ret);\n return ret;\n}\n<commit_msg>brushup<commit_after>\/* Copyright (c) 2010-2017, AOYAMA Kazuharu\n * All rights reserved.\n *\n * This software may be used and distributed according to the terms of\n * the New BSD License, which is incorporated herein by reference.\n *\/\n\n#include <QtCore>\n#include <QtSql>\n#include \"tableschema.h\"\n#include \"global.h\"\n\nQSettings *dbSettings = 0;\n\n\nTableSchema::TableSchema(const QString &table, const QString &env)\n : tablename(table)\n{\n if (!dbSettings) {\n QString path = QLatin1String(\"config\") + QDir::separator() + \"database.ini\";\n if (!QFile::exists(path)) {\n qCritical(\"not found, %s\", qPrintable(path));\n }\n dbSettings = new QSettings(path, QSettings::IniFormat);\n }\n\n if (openDatabase(env)) {\n if (!tablename.isEmpty()) {\n QSqlTableModel model;\n model.setTable(tablename);\n tableFields = model.record();\n\n if (model.database().driverName().toUpper() == \"QPSQL\") {\n \/\/ QPSQLResult doesn't call QSqlField::setAutoValue(), fix it\n for (int i = 0; i < tableFields.count(); ++i) {\n QSqlField f = tableFields.field(i);\n if (f.defaultValue().toString().startsWith(QLatin1String(\"nextval\"))) {\n f.setAutoValue(true);\n tableFields.replace(i, f);\n }\n }\n }\n } else {\n qCritical(\"Empty table name\");\n }\n }\n}\n\n\nbool TableSchema::exists() const\n{\n return (tableFields.count() > 0);\n}\n\n\nQList<QPair<QString, QString>> TableSchema::getFieldList() const\n{\n QList<QPair<QString, QString>> fieldList;\n for (int i = 0; i < tableFields.count(); ++i) {\n QSqlField f = tableFields.field(i);\n fieldList << QPair<QString, QString>(f.name(), QString(QVariant::typeToName(f.type())));\n }\n return fieldList;\n}\n\n\nQList<QPair<QString, QVariant::Type>> TableSchema::getFieldTypeList() const\n{\n QList<QPair<QString, QVariant::Type>> fieldList;\n for (int i = 0; i < tableFields.count(); ++i) {\n QSqlField f = tableFields.field(i);\n fieldList << QPair<QString, QVariant::Type>(f.name(), f.type());\n }\n return fieldList;\n}\n\n\nint TableSchema::primaryKeyIndex() const\n{\n QSqlTableModel model;\n model.setTable(tablename);\n QSqlIndex index = model.primaryKey();\n if (index.isEmpty()) {\n return -1;\n }\n\n QSqlField fi = index.field(0);\n return model.record().indexOf(fi.name());\n}\n\n\nQString TableSchema::primaryKeyFieldName() const\n{\n QSqlTableModel model;\n model.setTable(tablename);\n QSqlIndex index = model.primaryKey();\n if (index.isEmpty()) {\n return QString();\n }\n\n QSqlField fi = index.field(0);\n return fi.name();\n}\n\n\nint TableSchema::autoValueIndex() const\n{\n for (int i = 0; i < tableFields.count(); ++i) {\n QSqlField f = tableFields.field(i);\n if (f.isAutoValue()) {\n return i;\n }\n }\n return -1;\n}\n\n\nQString TableSchema::autoValueFieldName() const\n{\n for (int i = 0; i < tableFields.count(); ++i) {\n QSqlField f = tableFields.field(i);\n if (f.isAutoValue()) {\n return f.name();\n }\n }\n return QString();\n}\n\n\nQPair<QString, QString> TableSchema::getPrimaryKeyField() const\n{\n QPair<QString, QString> pair;\n int index = primaryKeyIndex();\n if (index >= 0) {\n QSqlField f = tableFields.field(index);\n pair = QPair<QString, QString>(f.name(), QString(QVariant::typeToName(f.type())));\n }\n return pair;\n}\n\n\nQPair<QString, QVariant::Type> TableSchema::getPrimaryKeyFieldType() const\n{\n QPair<QString, QVariant::Type> pair;\n int index = primaryKeyIndex();\n if (index >= 0) {\n QSqlField f = tableFields.field(index);\n pair = QPair<QString, QVariant::Type>(f.name(), f.type());\n }\n return pair;\n}\n\n\nint TableSchema::lockRevisionIndex() const\n{\n for (int i = 0; i < tableFields.count(); ++i) {\n QSqlField f = tableFields.field(i);\n if (fieldNameToVariableName(f.name()) == \"lockRevision\") {\n return i;\n }\n }\n return -1;\n}\n\n\nbool TableSchema::hasLockRevisionField() const\n{\n return lockRevisionIndex() >= 0;\n}\n\n\nbool TableSchema::openDatabase(const QString &env) const\n{\n if (isOpen())\n return true;\n\n if (!dbSettings->childGroups().contains(env)) {\n qCritical(\"invalid environment: %s\", qPrintable(env));\n return false;\n }\n\n dbSettings->beginGroup(env);\n\n QString driverType = dbSettings->value(\"DriverType\").toString().trimmed();\n if (driverType.isEmpty()) {\n qWarning(\"Parameter 'DriverType' is empty\");\n }\n printf(\"DriverType: %s\\n\", qPrintable(driverType));\n\n QSqlDatabase db = QSqlDatabase::addDatabase(driverType);\n if (!db.isValid()) {\n qWarning(\"Parameter 'DriverType' is invalid or RDB client library not available.\");\n return false;\n }\n\n QString databaseName = dbSettings->value(\"DatabaseName\").toString().trimmed();\n printf(\"DatabaseName: %s\\n\", qPrintable(databaseName));\n if (!databaseName.isEmpty()) {\n db.setDatabaseName(databaseName);\n }\n\n QString hostName = dbSettings->value(\"HostName\").toString().trimmed();\n printf(\"HostName: %s\\n\", qPrintable(hostName));\n if (!hostName.isEmpty()) {\n db.setHostName(hostName);\n }\n\n int port = dbSettings->value(\"Port\").toInt();\n if (port > 0) {\n db.setPort(port);\n }\n\n QString userName = dbSettings->value(\"UserName\").toString().trimmed();\n if (!userName.isEmpty()) {\n db.setUserName(userName);\n }\n\n QString password = dbSettings->value(\"Password\").toString().trimmed();\n if (!password.isEmpty()) {\n db.setPassword(password);\n }\n\n QString connectOptions = dbSettings->value(\"ConnectOptions\").toString().trimmed();\n if (!connectOptions.isEmpty()) {\n db.setConnectOptions(connectOptions);\n }\n\n dbSettings->endGroup();\n\n if (!db.open()) {\n qWarning(\"Database open error\");\n return false;\n }\n\n printf(\"Database opened successfully\\n\");\n return true;\n}\n\n\nbool TableSchema::isOpen() const\n{\n return QSqlDatabase::database().isOpen();\n}\n\n\nQStringList TableSchema::databaseDrivers()\n{\n return QSqlDatabase::drivers();\n}\n\n\nQStringList TableSchema::tables(const QString &env)\n{\n QSet<QString> set;\n TableSchema dummy(\"dummy\", env); \/\/ to open database\n\n if (QSqlDatabase::database().isOpen()) {\n for (QStringListIterator i(QSqlDatabase::database().tables(QSql::Tables)); i.hasNext(); ) {\n TableSchema t(i.next());\n if (t.exists()) {\n set << t.tableName(); \/\/ If value already exists, the set is left unchanged\n }\n }\n }\n\n QStringList ret = set.toList();\n qSort(ret);\n return ret;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ This program converts a set of images to a lmdb\/leveldb by storing them\n\/\/ as Datum proto buffers.\n\/\/ Usage:\n\/\/ convert_imageset [FLAGS] ROOTFOLDER\/ LISTFILE DB_NAME\n\/\/\n\/\/ where ROOTFOLDER is the root folder that holds all the images, and LISTFILE\n\/\/ should be a list of files as well as their labels, in the format as\n\/\/ subfolder1\/file1.JPEG 7\n\/\/ ....\n\n#include <gflags\/gflags.h>\n#include <glog\/logging.h>\n\n#include <algorithm>\n#include <fstream> \/\/ NOLINT(readability\/streams)\n#include <string>\n#include <utility>\n#include <vector>\n\n#include \"caffe\/dataset_factory.hpp\"\n#include \"caffe\/proto\/caffe.pb.h\"\n#include \"caffe\/util\/io.hpp\"\n#include \"caffe\/util\/rng.hpp\"\n\nusing namespace caffe; \/\/ NOLINT(build\/namespaces)\nusing std::pair;\n\nDEFINE_bool(gray, false,\n \"When this option is on, treat images as grayscale ones\");\nDEFINE_bool(shuffle, false,\n \"Randomly shuffle the order of images and their labels\");\nDEFINE_string(backend, \"lmdb\", \"The backend for storing the result\");\nDEFINE_int32(resize_width, 0, \"Width images are resized to\");\nDEFINE_int32(resize_height, 0, \"Height images are resized to\");\nDEFINE_bool(check_size, false,\n \"When this option is on, check that all the datum have the same size\");\n\nint main(int argc, char** argv) {\n ::google::InitGoogleLogging(argv[0]);\n\n#ifndef GFLAGS_GFLAGS_H_\n namespace gflags = google;\n#endif\n\n gflags::SetUsageMessage(\"Convert a set of images to the leveldb\/lmdb\\n\"\n \"format used as input for Caffe.\\n\"\n \"Usage:\\n\"\n \" convert_imageset [FLAGS] ROOTFOLDER\/ LISTFILE DB_NAME\\n\"\n \"The ImageNet dataset for the training demo is at\\n\"\n \" http:\/\/www.image-net.org\/download-images\\n\");\n gflags::ParseCommandLineFlags(&argc, &argv, true);\n\n if (argc != 4) {\n gflags::ShowUsageWithFlagsRestrict(argv[0], \"tools\/convert_imageset\");\n return 1;\n }\n\n bool is_color = !FLAGS_gray;\n bool check_size = FLAGS_check_size;\n std::ifstream infile(argv[2]);\n std::vector<std::pair<std::string, int> > lines;\n std::string filename;\n int label;\n while (infile >> filename >> label) {\n lines.push_back(std::make_pair(filename, label));\n }\n if (FLAGS_shuffle) {\n \/\/ randomly shuffle data\n LOG(INFO) << \"Shuffling data\";\n shuffle(lines.begin(), lines.end());\n }\n LOG(INFO) << \"A total of \" << lines.size() << \" images.\";\n\n const std::string& db_backend = FLAGS_backend;\n const char* db_path = argv[3];\n\n int resize_height = std::max<int>(0, FLAGS_resize_height);\n int resize_width = std::max<int>(0, FLAGS_resize_width);\n\n \/\/ Open new db\n shared_ptr<Dataset<string, Datum> > dataset =\n DatasetFactory<string, Datum>(db_backend);\n\n \/\/ Open db\n CHECK(dataset->open(db_path, Dataset<string, Datum>::New));\n\n \/\/ Storing to db\n std::string root_folder(argv[1]);\n Datum datum;\n int count = 0;\n const int kMaxKeyLength = 256;\n char key_cstr[kMaxKeyLength];\n int data_size;\n bool data_size_initialized = false;\n\n for (int line_id = 0; line_id < lines.size(); ++line_id) {\n if (!ReadImageToDatum(root_folder + lines[line_id].first,\n lines[line_id].second, resize_height, resize_width, is_color, &datum)) {\n continue;\n }\n if (check_size) {\n if (!data_size_initialized) {\n data_size = datum.channels() * datum.height() * datum.width();\n data_size_initialized = true;\n } else {\n const std::string& data = datum.data();\n CHECK_EQ(data.size(), data_size) << \"Incorrect data field size \"\n << data.size();\n }\n }\n \/\/ sequential\n int length = snprintf(key_cstr, kMaxKeyLength, \"%08d_%s\", line_id,\n lines[line_id].first.c_str());\n\n \/\/ Put in db\n CHECK(dataset->put(string(key_cstr, length), datum));\n\n if (++count % 1000 == 0) {\n \/\/ Commit txn\n CHECK(dataset->commit());\n LOG(ERROR) << \"Processed \" << count << \" files.\";\n }\n }\n \/\/ write the last batch\n if (count % 1000 != 0) {\n CHECK(dataset->commit());\n LOG(ERROR) << \"Processed \" << count << \" files.\";\n }\n dataset->close();\n return 0;\n}\n<commit_msg>Added encoded option and check_size to convert_imageset<commit_after>\/\/ This program converts a set of images to a lmdb\/leveldb by storing them\n\/\/ as Datum proto buffers.\n\/\/ Usage:\n\/\/ convert_imageset [FLAGS] ROOTFOLDER\/ LISTFILE DB_NAME\n\/\/\n\/\/ where ROOTFOLDER is the root folder that holds all the images, and LISTFILE\n\/\/ should be a list of files as well as their labels, in the format as\n\/\/ subfolder1\/file1.JPEG 7\n\/\/ ....\n\n#include <gflags\/gflags.h>\n#include <glog\/logging.h>\n\n#include <algorithm>\n#include <fstream> \/\/ NOLINT(readability\/streams)\n#include <string>\n#include <utility>\n#include <vector>\n\n#include \"caffe\/dataset_factory.hpp\"\n#include \"caffe\/proto\/caffe.pb.h\"\n#include \"caffe\/util\/io.hpp\"\n#include \"caffe\/util\/rng.hpp\"\n\nusing namespace caffe; \/\/ NOLINT(build\/namespaces)\nusing std::pair;\n\nDEFINE_bool(gray, false,\n \"When this option is on, treat images as grayscale ones\");\nDEFINE_bool(shuffle, false,\n \"Randomly shuffle the order of images and their labels\");\nDEFINE_string(backend, \"lmdb\", \"The backend for storing the result\");\nDEFINE_int32(resize_width, 0, \"Width images are resized to\");\nDEFINE_int32(resize_height, 0, \"Height images are resized to\");\nDEFINE_bool(check_size, false,\n \"When this option is on, check that all the datum have the same size\");\nDEFINE_bool(encoded, false,\n \"When this option is on, the encoded image will be save in datum\");\n\nint main(int argc, char** argv) {\n ::google::InitGoogleLogging(argv[0]);\n\n#ifndef GFLAGS_GFLAGS_H_\n namespace gflags = google;\n#endif\n\n gflags::SetUsageMessage(\"Convert a set of images to the leveldb\/lmdb\\n\"\n \"format used as input for Caffe.\\n\"\n \"Usage:\\n\"\n \" convert_imageset [FLAGS] ROOTFOLDER\/ LISTFILE DB_NAME\\n\"\n \"The ImageNet dataset for the training demo is at\\n\"\n \" http:\/\/www.image-net.org\/download-images\\n\");\n gflags::ParseCommandLineFlags(&argc, &argv, true);\n\n if (argc != 4) {\n gflags::ShowUsageWithFlagsRestrict(argv[0], \"tools\/convert_imageset\");\n return 1;\n }\n\n const bool is_color = !FLAGS_gray;\n const bool check_size = FLAGS_check_size;\n const bool encoded = FLAGS_encoded;\n\n std::ifstream infile(argv[2]);\n std::vector<std::pair<std::string, int> > lines;\n std::string filename;\n int label;\n while (infile >> filename >> label) {\n lines.push_back(std::make_pair(filename, label));\n }\n if (FLAGS_shuffle) {\n \/\/ randomly shuffle data\n LOG(INFO) << \"Shuffling data\";\n shuffle(lines.begin(), lines.end());\n }\n LOG(INFO) << \"A total of \" << lines.size() << \" images.\";\n\n const std::string& db_backend = FLAGS_backend;\n const char* db_path = argv[3];\n\n if (encoded) {\n CHECK_EQ(FLAGS_resize_height, 0) << \"With encoded don't resize images\";\n CHECK_EQ(FLAGS_resize_width, 0) << \"With encoded don't resize images\";\n CHECK(!check_size) << \"With encoded cannot check_size\";\n }\n\n int resize_height = std::max<int>(0, FLAGS_resize_height);\n int resize_width = std::max<int>(0, FLAGS_resize_width);\n\n \/\/ Open new db\n shared_ptr<Dataset<string, Datum> > dataset =\n DatasetFactory<string, Datum>(db_backend);\n\n \/\/ Open db\n CHECK(dataset->open(db_path, Dataset<string, Datum>::New));\n\n \/\/ Storing to db\n std::string root_folder(argv[1]);\n Datum datum;\n int count = 0;\n const int kMaxKeyLength = 256;\n char key_cstr[kMaxKeyLength];\n int data_size;\n bool data_size_initialized = false;\n\n for (int line_id = 0; line_id < lines.size(); ++line_id) {\n bool status;\n if (encoded) {\n status = ReadFileToDatum(root_folder + lines[line_id].first,\n lines[line_id].second, &datum);\n } else {\n status = ReadImageToDatum(root_folder + lines[line_id].first,\n lines[line_id].second, resize_height, resize_width, is_color, &datum);\n }\n if (status == false) continue;\n if (check_size) {\n if (!data_size_initialized) {\n data_size = datum.channels() * datum.height() * datum.width();\n data_size_initialized = true;\n } else {\n const std::string& data = datum.data();\n CHECK_EQ(data.size(), data_size) << \"Incorrect data field size \"\n << data.size();\n }\n }\n \/\/ sequential\n int length = snprintf(key_cstr, kMaxKeyLength, \"%08d_%s\", line_id,\n lines[line_id].first.c_str());\n\n \/\/ Put in db\n CHECK(dataset->put(string(key_cstr, length), datum));\n\n if (++count % 1000 == 0) {\n \/\/ Commit txn\n CHECK(dataset->commit());\n LOG(ERROR) << \"Processed \" << count << \" files.\";\n }\n }\n \/\/ write the last batch\n if (count % 1000 != 0) {\n CHECK(dataset->commit());\n LOG(ERROR) << \"Processed \" << count << \" files.\";\n }\n dataset->close();\n return 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/============================================================================\n\/\/ Name : DataSetGenerator.cpp\n\/\/ Description : C++ program for implementation of DataSetGenerator\n\/\/============================================================================\n#include \"DataSetGenerator.hpp\"\n\nvoid DataSetGenerator::createSortedSet(std::vector<int>&toFill){\n\tunsigned int valueToAdd = 0;\n for(std::vector<int>::iterator it=toFill.begin(); it!=toFill.end(); ++it){\n\t\t*it=valueToAdd++;\n\t}\n}\n\nvoid DataSetGenerator::extendSortedSet(std::vector<int>&toFill, unsigned long long toAdd){\n int lastElementIndex = toFill.size();\n int valueToAdd = toFill.back()+1;\n toFill.resize(toFill.size()+toAdd);\n for(unsigned int i=0; i<toAdd; ++i){\n toFill[lastElementIndex++]=valueToAdd++;\n }\n}\n\nvoid DataSetGenerator::createRandomSet(std::vector<int>& toFill){\n\tunsigned long long vectorSize = toFill.size();\n\tfor(std::vector<int>::iterator it=toFill.begin(); it!=toFill.end(); ++it){\n\t\t*it=std::rand()%vectorSize;\n\t}\n}\n\nvoid DataSetGenerator::extendRandomSet(std::vector<int>& toFill, unsigned long long toAdd){\n int lastElementIndex = toFill.size();\n toFill.resize(toFill.size()+toAdd);\n\tfor(unsigned int i=1; i<toAdd; ++i){\n\t\ttoFill[lastElementIndex++]= std::rand()%toFill.size();\n\t}\n}\n\nvoid DataSetGenerator::createBackwardSortedSet(std::vector<int>& toFill){\n\tunsigned int valueToAdd = toFill.size()-1;\n for(std::vector<int>::iterator it=toFill.begin(); it!=toFill.end(); ++it){\n\t\t*it=valueToAdd--;\n\t}\n}\n\nvoid DataSetGenerator::extendBackwardSortedSet(std::vector<int>& toFill, unsigned long long toAdd){\n\tunsigned int valueToAdd=toFill.front();\n for(unsigned int i=0; i<toAdd; ++i){\n \ttoFill.insert(toFill.begin(),++valueToAdd);\n }\n}\n\nvoid DataSetGenerator::createSortedSetWithFirstRandomValue(std::vector<int>& toFill){\n\ttoFill[0]=std::rand()%toFill.size();\n\tunsigned long valueToAdd = 1;\n\tfor(std::vector<int>::iterator it=toFill.begin()+1; it!=toFill.end(); ++it){\n\t\t*it=valueToAdd++;\n\t}\n}\n\nvoid DataSetGenerator::extendSortedSetWithFirstRandomValue(std::vector<int>& toFill, unsigned long long toAdd){\n\textendSortedSet(toFill,toAdd);\n}\n\nvoid DataSetGenerator::createBackwardSortedSetWithLastRandomValue(std::vector<int>& toFill){\n\tcreateBackwardSortedSet(toFill);\n\ttoFill[toFill.size()-1]= std::rand()%toFill.size();\n}\n\nvoid DataSetGenerator::extendBackwardSortedSetWithLastRandomValue(std::vector<int>& toFill, unsigned long long toAdd){\n\t unsigned int valueToAdd=toFill.front();\n for(unsigned int i=0; i<toAdd; ++i){\n\t \ttoFill.insert(toFill.begin(),++valueToAdd);\n\t }\n toFill[toFill.size()-1]= std::rand()%toFill.size();\n}\n<commit_msg>Modified DataSetGenerator class- new version of extendSortedSet method<commit_after>\/\/============================================================================\n\/\/ Name : DataSetGenerator.cpp\n\/\/ Description : C++ program for implementation of DataSetGenerator\n\/\/============================================================================\n#include \"DataSetGenerator.hpp\"\n\nvoid DataSetGenerator::createSortedSet(std::vector<int>&toFill){\n\tunsigned int valueToAdd = 0;\n for(std::vector<int>::iterator it=toFill.begin(); it!=toFill.end(); ++it){\n\t\t*it=valueToAdd++;\n\t}\n}\n\nvoid DataSetGenerator::extendSortedSet(std::vector<int>&toFill, unsigned long long toAdd){\n int lastElementIndex = toFill.size();\n int valueToAdd = toFill.back()+1;\n toFill.resize(toFill.size()+toAdd);\n for(unsigned int i=0; i<toAdd; ++i){\n toFill[lastElementIndex++]=valueToAdd++;\n }\n}\n\nvoid DataSetGenerator::createRandomSet(std::vector<int>& toFill){\n\tunsigned long long vectorSize = toFill.size();\n\tfor(std::vector<int>::iterator it=toFill.begin(); it!=toFill.end(); ++it){\n\t\t*it=std::rand()%vectorSize;\n\t}\n}\n\nvoid DataSetGenerator::extendRandomSet(std::vector<int>& toFill, unsigned long long toAdd){\n int lastElementIndex = toFill.size();\n toFill.resize(toFill.size()+toAdd);\n\tfor(unsigned int i=1; i<toAdd; ++i){\n\t\ttoFill[lastElementIndex++]= std::rand()%toFill.size();\n\t}\n}\n\nvoid DataSetGenerator::createBackwardSortedSet(std::vector<int>& toFill){\n\tunsigned int valueToAdd = toFill.size()-1;\n for(std::vector<int>::iterator it=toFill.begin(); it!=toFill.end(); ++it){\n\t\t*it=valueToAdd--;\n\t}\n}\n\nvoid DataSetGenerator::extendBackwardSortedSet(std::vector<int>& toFill, unsigned long long toAdd){\n\tunsigned int valueToAdd=toFill.front();\n for(unsigned int i=0; i<toAdd; ++i){\n \ttoFill.insert(toFill.begin(),++valueToAdd);\n }\n}\n\nvoid DataSetGenerator::createSortedSetWithFirstRandomValue(std::vector<int>& toFill){\n\ttoFill[0]=std::rand()%toFill.size();\n\tunsigned long valueToAdd = 1;\n\tfor(std::vector<int>::iterator it=toFill.begin()+1; it!=toFill.end(); ++it){\n\t\t*it=valueToAdd++;\n\t}\n}\n\nvoid DataSetGenerator::extendSortedSetWithFirstRandomValue(std::vector<int>& toFill, unsigned long long toAdd){\n\textendSortedSet(toFill,toAdd);\n\ttoFill[0]=std::rand()%toFill.size();\n}\n\nvoid DataSetGenerator::createBackwardSortedSetWithLastRandomValue(std::vector<int>& toFill){\n\tcreateBackwardSortedSet(toFill);\n\ttoFill[toFill.size()-1]= std::rand()%toFill.size();\n}\n\nvoid DataSetGenerator::extendBackwardSortedSetWithLastRandomValue(std::vector<int>& toFill, unsigned long long toAdd){\n\t unsigned int valueToAdd=toFill.front();\n for(unsigned int i=0; i<toAdd; ++i){\n\t \ttoFill.insert(toFill.begin(),++valueToAdd);\n\t }\n toFill[toFill.size()-1]= std::rand()%toFill.size();\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"base\/file_util.h\"\n#include \"base\/path_service.h\"\n#include \"base\/scoped_temp_dir.h\"\n#include \"base\/string_util.h\"\n#include \"base\/utf_string_conversions.h\"\n#include \"base\/values.h\"\n#include \"chrome\/common\/chrome_paths.h\"\n#include \"chrome\/common\/extensions\/extension_constants.h\"\n#include \"chrome\/common\/extensions\/extension_unpacker.h\"\n#include \"testing\/gtest\/include\/gtest\/gtest.h\"\n#include \"third_party\/skia\/include\/core\/SkBitmap.h\"\n\nnamespace errors = extension_manifest_errors;\nnamespace keys = extension_manifest_keys;\n\nclass ExtensionUnpackerTest : public testing::Test {\npublic:\n void SetupUnpacker(const std::string& crx_name) {\n FilePath original_path;\n ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &original_path));\n original_path = original_path.AppendASCII(\"extensions\")\n .AppendASCII(\"unpacker\")\n .AppendASCII(crx_name);\n ASSERT_TRUE(file_util::PathExists(original_path)) << original_path.value();\n\n \/\/ Try bots won't let us write into DIR_TEST_DATA, so we have to create\n \/\/ a temp folder to play in.\n ASSERT_TRUE(temp_dir_.CreateUniqueTempDir());\n\n FilePath crx_path = temp_dir_.path().AppendASCII(crx_name);\n ASSERT_TRUE(file_util::CopyFile(original_path, crx_path)) <<\n \"Original path \" << original_path.value() <<\n \", Crx path \" << crx_path.value();\n\n unpacker_.reset(\n new ExtensionUnpacker(\n crx_path, Extension::INTERNAL, Extension::NO_FLAGS));\n }\n\n protected:\n ScopedTempDir temp_dir_;\n scoped_ptr<ExtensionUnpacker> unpacker_;\n};\n\n\/\/ Crashes intermittently on Windows, see http:\/\/crbug.com\/109238\n#if defined(OS_WIN)\n#define MAYBE_EmptyDefaultLocale DISABLED_EmptyDefaultLocale\n#else\n#define MAYBE_EmptyDefaultLocale EmptyDefaultLocale\n#endif\n\nTEST_F(ExtensionUnpackerTest, MAYBE_EmptyDefaultLocale) {\n SetupUnpacker(\"empty_default_locale.crx\");\n EXPECT_FALSE(unpacker_->Run());\n EXPECT_EQ(ASCIIToUTF16(errors::kInvalidDefaultLocale),\n unpacker_->error_message());\n}\n\n\/\/ Crashes intermittently on Vista, see http:\/\/crbug.com\/109385\n#if defined(OS_WIN)\n#define MAYBE_HasDefaultLocaleMissingLocalesFolder \\\n DISABLED_HasDefaultLocaleMissingLocalesFolder\n#else\n#define MAYBE_HasDefaultLocaleMissingLocalesFolder \\\n HasDefaultLocaleMissingLocalesFolder\n#endif\nTEST_F(ExtensionUnpackerTest, MAYBE_HasDefaultLocaleMissingLocalesFolder) {\n SetupUnpacker(\"has_default_missing_locales.crx\");\n EXPECT_FALSE(unpacker_->Run());\n EXPECT_EQ(ASCIIToUTF16(errors::kLocalesTreeMissing),\n unpacker_->error_message());\n}\n\nTEST_F(ExtensionUnpackerTest, InvalidDefaultLocale) {\n SetupUnpacker(\"invalid_default_locale.crx\");\n EXPECT_FALSE(unpacker_->Run());\n EXPECT_EQ(ASCIIToUTF16(errors::kInvalidDefaultLocale),\n unpacker_->error_message());\n}\n\nTEST_F(ExtensionUnpackerTest, InvalidMessagesFile) {\n SetupUnpacker(\"invalid_messages_file.crx\");\n EXPECT_FALSE(unpacker_->Run());\n EXPECT_TRUE(MatchPattern(unpacker_->error_message(),\n ASCIIToUTF16(\"*_locales?en_US?messages.json: Line: 2, column: 3,\"\n \" Dictionary keys must be quoted.\")));\n}\n\nTEST_F(ExtensionUnpackerTest, MissingDefaultData) {\n SetupUnpacker(\"missing_default_data.crx\");\n EXPECT_FALSE(unpacker_->Run());\n EXPECT_EQ(ASCIIToUTF16(errors::kLocalesNoDefaultMessages),\n unpacker_->error_message());\n}\n\nTEST_F(ExtensionUnpackerTest, MissingDefaultLocaleHasLocalesFolder) {\n SetupUnpacker(\"missing_default_has_locales.crx\");\n EXPECT_FALSE(unpacker_->Run());\n EXPECT_EQ(ASCIIToUTF16(errors::kLocalesNoDefaultLocaleSpecified),\n unpacker_->error_message());\n}\n\nTEST_F(ExtensionUnpackerTest, MissingMessagesFile) {\n SetupUnpacker(\"missing_messages_file.crx\");\n EXPECT_FALSE(unpacker_->Run());\n EXPECT_TRUE(MatchPattern(unpacker_->error_message(),\n ASCIIToUTF16(errors::kLocalesMessagesFileMissing) +\n ASCIIToUTF16(\"*_locales?en_US?messages.json\")));\n}\n\nTEST_F(ExtensionUnpackerTest, NoLocaleData) {\n SetupUnpacker(\"no_locale_data.crx\");\n EXPECT_FALSE(unpacker_->Run());\n EXPECT_EQ(ASCIIToUTF16(errors::kLocalesNoDefaultMessages),\n unpacker_->error_message());\n}\n\nTEST_F(ExtensionUnpackerTest, GoodL10n) {\n SetupUnpacker(\"good_l10n.crx\");\n EXPECT_TRUE(unpacker_->Run());\n EXPECT_TRUE(unpacker_->error_message().empty());\n ASSERT_EQ(2U, unpacker_->parsed_catalogs()->size());\n}\n\nTEST_F(ExtensionUnpackerTest, NoL10n) {\n SetupUnpacker(\"no_l10n.crx\");\n EXPECT_TRUE(unpacker_->Run());\n EXPECT_TRUE(unpacker_->error_message().empty());\n EXPECT_EQ(0U, unpacker_->parsed_catalogs()->size());\n}\n<commit_msg>Disable intermittently crashing ExtensionUnpackerTest.InvalidDefaultLocale on Win.<commit_after>\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"base\/file_util.h\"\n#include \"base\/path_service.h\"\n#include \"base\/scoped_temp_dir.h\"\n#include \"base\/string_util.h\"\n#include \"base\/utf_string_conversions.h\"\n#include \"base\/values.h\"\n#include \"chrome\/common\/chrome_paths.h\"\n#include \"chrome\/common\/extensions\/extension_constants.h\"\n#include \"chrome\/common\/extensions\/extension_unpacker.h\"\n#include \"testing\/gtest\/include\/gtest\/gtest.h\"\n#include \"third_party\/skia\/include\/core\/SkBitmap.h\"\n\nnamespace errors = extension_manifest_errors;\nnamespace keys = extension_manifest_keys;\n\nclass ExtensionUnpackerTest : public testing::Test {\npublic:\n void SetupUnpacker(const std::string& crx_name) {\n FilePath original_path;\n ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &original_path));\n original_path = original_path.AppendASCII(\"extensions\")\n .AppendASCII(\"unpacker\")\n .AppendASCII(crx_name);\n ASSERT_TRUE(file_util::PathExists(original_path)) << original_path.value();\n\n \/\/ Try bots won't let us write into DIR_TEST_DATA, so we have to create\n \/\/ a temp folder to play in.\n ASSERT_TRUE(temp_dir_.CreateUniqueTempDir());\n\n FilePath crx_path = temp_dir_.path().AppendASCII(crx_name);\n ASSERT_TRUE(file_util::CopyFile(original_path, crx_path)) <<\n \"Original path \" << original_path.value() <<\n \", Crx path \" << crx_path.value();\n\n unpacker_.reset(\n new ExtensionUnpacker(\n crx_path, Extension::INTERNAL, Extension::NO_FLAGS));\n }\n\n protected:\n ScopedTempDir temp_dir_;\n scoped_ptr<ExtensionUnpacker> unpacker_;\n};\n\n\/\/ Crashes intermittently on Windows, see http:\/\/crbug.com\/109238\n#if defined(OS_WIN)\n#define MAYBE_EmptyDefaultLocale DISABLED_EmptyDefaultLocale\n#else\n#define MAYBE_EmptyDefaultLocale EmptyDefaultLocale\n#endif\nTEST_F(ExtensionUnpackerTest, MAYBE_EmptyDefaultLocale) {\n SetupUnpacker(\"empty_default_locale.crx\");\n EXPECT_FALSE(unpacker_->Run());\n EXPECT_EQ(ASCIIToUTF16(errors::kInvalidDefaultLocale),\n unpacker_->error_message());\n}\n\n\/\/ Crashes intermittently on Vista, see http:\/\/crbug.com\/109385\n#if defined(OS_WIN)\n#define MAYBE_HasDefaultLocaleMissingLocalesFolder \\\n DISABLED_HasDefaultLocaleMissingLocalesFolder\n#else\n#define MAYBE_HasDefaultLocaleMissingLocalesFolder \\\n HasDefaultLocaleMissingLocalesFolder\n#endif\nTEST_F(ExtensionUnpackerTest, MAYBE_HasDefaultLocaleMissingLocalesFolder) {\n SetupUnpacker(\"has_default_missing_locales.crx\");\n EXPECT_FALSE(unpacker_->Run());\n EXPECT_EQ(ASCIIToUTF16(errors::kLocalesTreeMissing),\n unpacker_->error_message());\n}\n\n\/\/ Crashes intermittently on Windows, see http:\/\/crbug.com\/109238\n#if defined(OS_WIN)\n#define MAYBE_InvalidDefaultLocale DISABLED_InvalidDefaultLocale\n#else\n#define MAYBE_InvalidDefaultLocale InvalidDefaultLocale\n#endif\nTEST_F(ExtensionUnpackerTest, MAYBE_InvalidDefaultLocale) {\n SetupUnpacker(\"invalid_default_locale.crx\");\n EXPECT_FALSE(unpacker_->Run());\n EXPECT_EQ(ASCIIToUTF16(errors::kInvalidDefaultLocale),\n unpacker_->error_message());\n}\n\nTEST_F(ExtensionUnpackerTest, InvalidMessagesFile) {\n SetupUnpacker(\"invalid_messages_file.crx\");\n EXPECT_FALSE(unpacker_->Run());\n EXPECT_TRUE(MatchPattern(unpacker_->error_message(),\n ASCIIToUTF16(\"*_locales?en_US?messages.json: Line: 2, column: 3,\"\n \" Dictionary keys must be quoted.\")));\n}\n\nTEST_F(ExtensionUnpackerTest, MissingDefaultData) {\n SetupUnpacker(\"missing_default_data.crx\");\n EXPECT_FALSE(unpacker_->Run());\n EXPECT_EQ(ASCIIToUTF16(errors::kLocalesNoDefaultMessages),\n unpacker_->error_message());\n}\n\nTEST_F(ExtensionUnpackerTest, MissingDefaultLocaleHasLocalesFolder) {\n SetupUnpacker(\"missing_default_has_locales.crx\");\n EXPECT_FALSE(unpacker_->Run());\n EXPECT_EQ(ASCIIToUTF16(errors::kLocalesNoDefaultLocaleSpecified),\n unpacker_->error_message());\n}\n\nTEST_F(ExtensionUnpackerTest, MissingMessagesFile) {\n SetupUnpacker(\"missing_messages_file.crx\");\n EXPECT_FALSE(unpacker_->Run());\n EXPECT_TRUE(MatchPattern(unpacker_->error_message(),\n ASCIIToUTF16(errors::kLocalesMessagesFileMissing) +\n ASCIIToUTF16(\"*_locales?en_US?messages.json\")));\n}\n\nTEST_F(ExtensionUnpackerTest, NoLocaleData) {\n SetupUnpacker(\"no_locale_data.crx\");\n EXPECT_FALSE(unpacker_->Run());\n EXPECT_EQ(ASCIIToUTF16(errors::kLocalesNoDefaultMessages),\n unpacker_->error_message());\n}\n\nTEST_F(ExtensionUnpackerTest, GoodL10n) {\n SetupUnpacker(\"good_l10n.crx\");\n EXPECT_TRUE(unpacker_->Run());\n EXPECT_TRUE(unpacker_->error_message().empty());\n ASSERT_EQ(2U, unpacker_->parsed_catalogs()->size());\n}\n\nTEST_F(ExtensionUnpackerTest, NoL10n) {\n SetupUnpacker(\"no_l10n.crx\");\n EXPECT_TRUE(unpacker_->Run());\n EXPECT_TRUE(unpacker_->error_message().empty());\n EXPECT_EQ(0U, unpacker_->parsed_catalogs()->size());\n}\n<|endoftext|>"} {"text":"<commit_before>#include <stdio.h>\n#include <string.h>\n\n#include <sampgdk\/a_players.h>\n#include <sampgdk\/a_samp.h>\n#include <sampgdk\/core.h>\n#include <sampgdk\/sdk.h>\n\nusing sampgdk::logprintf;\n\nextern void *pAMXFunctions;\n\nAMX * a;\n\nPLUGIN_EXPORT void PLUGIN_CALL ProcessTick() {\n sampgdk::ProcessTick();\n}\n\nPLUGIN_EXPORT unsigned int PLUGIN_CALL Supports()\n{\n return sampgdk::Supports() | SUPPORTS_VERSION | SUPPORTS_AMX_NATIVES;\n}\n\nPLUGIN_EXPORT bool PLUGIN_CALL Load(void **ppData)\n{\n pAMXFunctions = ppData[PLUGIN_DATA_AMX_EXPORTS];\n return sampgdk::Load(ppData);\n}\n\nPLUGIN_EXPORT void PLUGIN_CALL Unload()\n{\n sampgdk::Unload();\n}\n\n\nPLUGIN_EXPORT int PLUGIN_CALL AmxLoad(AMX *amx)\n{\n a = amx;\n return AMX_ERR_NONE;\n}\n\n\nPLUGIN_EXPORT int PLUGIN_CALL AmxUnload(AMX *amx)\n{\n return AMX_ERR_NONE;\n}\n\nPLUGIN_EXPORT bool PLUGIN_CALL OnPlayerConnect(int playerid) {\n int one = 10;\n int two = 20;\n int three = 30;\n int amxIndex = 0;\n\n logprintf(\"amx_FindPublic...TestCB3\");\n if (!amx_FindPublic(a, \"TestCB3\", &amxIndex))\n {\n logprintf(\"amx_Push...\");\n amx_Push(a, one);\n amx_Push(a, two);\n amx_Push(a, three);\n\n logprintf(\"amx_Exec...\");\n amx_Exec(a, NULL, amxIndex);\n }\n else\n {\n logprintf(\"amx_FindPublic failed to find :(...\");\n }\n return true;\n}\n\nPLUGIN_EXPORT bool PLUGIN_CALL OnPublicCall(AMX *amx, const char *name, cell *params, cell *retval) {\n if (!strcmp(name, \"TestCB1\")) {\n logprintf(\">TestCB1(%d) %d\", (params[0] \/ sizeof(cell)), params[1]);\n }\n if (!strcmp(name, \"TestCB2\")) {\n logprintf(\">TestCB2(%d) %d %d\", (params[0] \/ sizeof(cell)), params[1], params[2]);\n }\n if (!strcmp(name, \"TestCB3\")) {\n logprintf(\">TestCB3(%d) %d %d %d\", (params[0] \/ sizeof(cell)), params[1], params[2], params[3]);\n }\n if (!strcmp(name, \"OnPlayerConnect\")) {\n logprintf(\">OnPlayerConnect(%d) %d\", (params[0] \/ sizeof(cell)), params[1]);\n }\n return true;\n}\n\n<commit_msg>Remove test code from helloworld<commit_after>#include <stdio.h>\n#include <string.h>\n\n#include <sampgdk\/a_players.h>\n#include <sampgdk\/a_samp.h>\n#include <sampgdk\/core.h>\n#include <sampgdk\/sdk.h>\n\nusing namespace sampgdk;\n\nvoid SAMPGDK_CALL PrintTickCountTimer(int timerid, void *params) {\n logprintf(\"Tick count: %d\", GetTickCount());\n}\n\nPLUGIN_EXPORT bool PLUGIN_CALL OnGameModeInit() {\n SetGameModeText(\"Hello, World!\");\n AddPlayerClass(0, 1958.3783f, 1343.1572f, 15.3746f, 269.1425f,\n 0, 0, 0, 0, 0, 0);\n SetTimer(1000, true, PrintTickCountTimer, 0);\n return true;\n}\n\nPLUGIN_EXPORT bool PLUGIN_CALL OnPlayerConnect(int playerid) {\n SendClientMessage(playerid, 0xFFFFFFFF, \"Welcome to the HelloWorld server!\");\n return true;\n}\n\nPLUGIN_EXPORT bool PLUGIN_CALL OnPlayerRequestClass(int playerid,\n int classid) {\n SetPlayerPos(playerid, 1958.3783f, 1343.1572f, 15.3746f);\n SetPlayerCameraPos(playerid, 1958.3783f, 1343.1572f, 15.3746f);\n SetPlayerCameraLookAt(playerid, 1958.3783f, 1343.1572f, 15.3746f, CAMERA_CUT);\n return true;\n}\n\nPLUGIN_EXPORT bool PLUGIN_CALL OnPlayerCommandText(int playerid,\n const char *cmdtext) {\n if (strcmp(cmdtext, \"\/hello\") == 0) {\n char name[MAX_PLAYER_NAME];\n GetPlayerName(playerid, name, sizeof(name));\n char message[MAX_CLIENT_MESSAGE];\n sprintf(message, \"Hello, %s!\", name);\n SendClientMessage(playerid, 0x00FF00FF, message);\n return true;\n }\n return false;\n}\n\nPLUGIN_EXPORT unsigned int PLUGIN_CALL Supports() {\n return sampgdk::Supports() | SUPPORTS_PROCESS_TICK;\n}\n\nPLUGIN_EXPORT bool PLUGIN_CALL Load(void **ppData) {\n return sampgdk::Load(ppData);\n}\n\nPLUGIN_EXPORT void PLUGIN_CALL Unload() {\n sampgdk::Unload();\n}\n\nPLUGIN_EXPORT void PLUGIN_CALL ProcessTick() {\n sampgdk::ProcessTick();\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n nlamarok.cpp\n\n Kopete Now Listening To plugin\n\n Copyright (c) 2002,2003,2004 by Will Stephenson <will@stevello.free-online.co.uk>\n Kopete\n\tCopyright (c) 2002,2003,2004 by the Kopete developers <kopete-devel@kde.org>\n\t\n\tPurpose: \n\tThis class abstracts the interface to amaroK by\n\timplementing NLMediaPlayer\n\n *************************************************************************\n * *\n * This program is free software; you can redistribute it and\/or modify *\n * it under the terms of the GNU General Public License as published by *\n * the Free Software Foundation; either version 2 of the License, or *\n * (at your option) any later version. *\n * *\n *************************************************************************\n*\/\n\n#include <kdebug.h>\n\n\n#include <QtDBus\/QtDBus>\n\n#include \"nlmediaplayer.h\"\n#include \"nlamarok.h\"\n\nNLamaroK::NLamaroK() : NLMediaPlayer()\n{\n\tm_type = Audio;\n\tm_name = \"amaroK\";\n\tm_client = new QDBusInterface(\"org.kde.amaroK\", \"\/player\");\n}\n\nNLamaroK::~NLamaroK()\n{\n\tdelete m_client;\n}\n\nvoid NLamaroK::update()\n{\n\tm_playing = false;\n\tm_newTrack = false;\n\tQString newTrack;\n\tQString result;\n\n\t\/\/ TODO: Port to amarok 2.0 D-BUS interface\n\tif( !m_client->isValid() )\n\t\treturn;\n\n\t\/\/ See if amaroK is currently playing.\n\tQDBusReply<int> statusReply = m_client->call(\"status\");\n\tif( statusReply.isValid() )\n\t{\n\t\tif( statusReply.value() )\n\t\t{\n\t\t\tm_playing = true;\n\t\t}\n\t}\n\n\t\/\/ Fetch title\n\tQDBusReply<QString> newTrackReply = m_client->call(\"title\");\n\tif( newTrackReply.isValid() )\n\t{\n\t\tnewTrack = newTrackReply.value();\n\t}\n\n\tif ( newTrack != m_track )\n\t{\n\t\tm_newTrack = true;\n\t\tm_track = newTrack;\n\t}\n\n\t\/\/ Fetch album\n\tQDBusReply<QString> albumReply = m_client->call(\"album\");\n\tif( albumReply.isValid() )\n\t{\n\t\tm_album = albumReply.value();\n\t}\n\n\t\/\/ Fetch artist\n\tQDBusReply<QString> artistReply = m_client->call(\"artist\");\n\tif( artistReply.isValid() )\n\t{\n\t\tm_artist = artistReply.value();\n\t}\n}\n\n<commit_msg>Change capitalization of the dbus interface to the one amarok is currently using. Fixes nowlistening support for Amarok 2.0. CCBUG: 155865<commit_after>\/*\n nlamarok.cpp\n\n Kopete Now Listening To plugin\n\n Copyright (c) 2002,2003,2004 by Will Stephenson <will@stevello.free-online.co.uk>\n Kopete\n\tCopyright (c) 2002,2003,2004 by the Kopete developers <kopete-devel@kde.org>\n\t\n\tPurpose: \n\tThis class abstracts the interface to amaroK by\n\timplementing NLMediaPlayer\n\n *************************************************************************\n * *\n * This program is free software; you can redistribute it and\/or modify *\n * it under the terms of the GNU General Public License as published by *\n * the Free Software Foundation; either version 2 of the License, or *\n * (at your option) any later version. *\n * *\n *************************************************************************\n*\/\n\n#include <kdebug.h>\n\n\n#include <QtDBus\/QtDBus>\n\n#include \"nlmediaplayer.h\"\n#include \"nlamarok.h\"\n\nNLamaroK::NLamaroK() : NLMediaPlayer()\n{\n\tm_type = Audio;\n\tm_name = \"amaroK\";\n\tm_client = new QDBusInterface(\"org.kde.amarok\", \"\/Player\");\n}\n\nNLamaroK::~NLamaroK()\n{\n\tdelete m_client;\n}\n\nvoid NLamaroK::update()\n{\n\tm_playing = false;\n\tm_newTrack = false;\n\tQString newTrack;\n\tQString result;\n\n\tif( !m_client->isValid() )\n\t\treturn;\n\n\t\/\/ See if amaroK is currently playing.\n\tQDBusReply<int> statusReply = m_client->call(\"status\");\n\tif( statusReply.isValid() )\n\t{\n\t\tif( statusReply.value() )\n\t\t{\n\t\t\tm_playing = true;\n\t\t}\n\t}\n\n\t\/\/ Fetch title\n\tQDBusReply<QString> newTrackReply = m_client->call(\"title\");\n\tif( newTrackReply.isValid() )\n\t{\n\t\tnewTrack = newTrackReply.value();\n\t}\n\n\tif ( newTrack != m_track )\n\t{\n\t\tm_newTrack = true;\n\t\tm_track = newTrack;\n\t}\n\n\t\/\/ Fetch album\n\tQDBusReply<QString> albumReply = m_client->call(\"album\");\n\tif( albumReply.isValid() )\n\t{\n\t\tm_album = albumReply.value();\n\t}\n\n\t\/\/ Fetch artist\n\tQDBusReply<QString> artistReply = m_client->call(\"artist\");\n\tif( artistReply.isValid() )\n\t{\n\t\tm_artist = artistReply.value();\n\t}\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ This file is part of the dune-gdt project:\n\/\/ http:\/\/users.dune-project.org\/projects\/dune-gdt\n\/\/ Copyright holders: Felix Schindler\n\/\/ License: BSD 2-Clause License (http:\/\/opensource.org\/licenses\/BSD-2-Clause)\n\n#ifndef DUNE_GDT_PRODUCTS_BASE_HH\n#define DUNE_GDT_PRODUCTS_BASE_HH\n\n#include <dune\/gdt\/assembler\/system.hh>\n#include <dune\/gdt\/assembler\/tmp-storage.hh>\n#include <dune\/gdt\/assembler\/local\/codim0.hh>\n\n#include \"interfaces.hh\"\n\nnamespace Dune {\nnamespace GDT {\nnamespace Products {\n\n\ntemplate <class Traits>\nclass LocalizableBase : public LocalizableProductInterface<Traits>,\n public Functor::Codim0<typename Traits::GridViewType>\n{\n typedef LocalizableProductInterface<Traits> InterfaceType;\n\npublic:\n typedef typename Traits::GridViewType GridViewType;\n typedef typename Traits::RangeType RangeType;\n typedef typename Traits::SourceType SourceType;\n typedef typename Traits::FieldType FieldType;\n\nprivate:\n typedef typename Traits::LocalOperatorType LocalOperatorType;\n typedef TmpStorageProvider::Matrices<FieldType> TmpMatricesProviderType;\n\npublic:\n using typename InterfaceType::EntityType;\n\npublic:\n LocalizableBase(const GridViewType& grd_vw, const RangeType& rng, const SourceType& src)\n : grid_view_(grd_vw)\n , range_(rng)\n , source_(src)\n , tmp_storage_(nullptr)\n , prepared_(false)\n , finalized_(false)\n , result_(0)\n {\n }\n\n LocalizableBase(const GridViewType& grd_vw, const RangeType& rng)\n : grid_view_(grd_vw)\n , range_(rng)\n , source_(range_)\n , tmp_storage_(nullptr)\n , prepared_(false)\n , finalized_(false)\n , result_(0)\n {\n }\n\n virtual ~LocalizableBase()\n {\n }\n\n const GridViewType& grid_view() const\n {\n return grid_view_;\n }\n\n const RangeType& range() const\n {\n return range_;\n }\n\n const SourceType& source() const\n {\n return source_;\n }\n\nprivate:\n virtual const LocalOperatorType& local_operator() const = 0;\n\npublic:\n virtual void prepare() DS_OVERRIDE\n {\n if (!prepared_) {\n tmp_storage_ = std::unique_ptr<TmpMatricesProviderType>(\n new TmpMatricesProviderType({1, local_operator().numTmpObjectsRequired()}, 1, 1));\n result_ *= 0.0;\n prepared_ = true;\n }\n } \/\/ ... prepare()\n\n virtual void apply_local(const EntityType& entity) DS_OVERRIDE\n {\n assert(prepared_);\n assert(tmp_storage_);\n auto& tmp_storage = tmp_storage_->matrices();\n assert(tmp_storage.size() >= 2);\n assert(tmp_storage[0].size() >= 1);\n auto& local_operator_result = tmp_storage[0][0];\n auto& tmp_matrices = tmp_storage[1];\n \/\/ get the local functions\n const auto local_source_ptr = this->source().local_function(entity);\n const auto local_range_ptr = this->range().local_function(entity);\n \/\/ apply local operator\n local_operator().apply(*local_range_ptr, *local_source_ptr, local_operator_result, tmp_matrices);\n assert(local_operator_result.rows() == 1);\n assert(local_operator_result.cols() == 1);\n result_ += local_operator_result[0][0];\n } \/\/ ... apply_local(...)\n\n virtual void finalize() DS_OVERRIDE\n {\n finalized_ = true;\n }\n\n FieldType apply2()\n {\n if (!finalized_) {\n GridWalker<GridViewType> grid_walker(grid_view_);\n grid_walker.add(*this);\n grid_walker.walk();\n }\n return result_;\n }\n\nprivate:\n const GridViewType& grid_view_;\n const RangeType& range_;\n const SourceType& source_;\n std::unique_ptr<TmpMatricesProviderType> tmp_storage_;\n bool prepared_;\n bool finalized_;\n FieldType result_;\n}; \/\/ class LocalizableBase\n\n\ntemplate <class Traits>\nclass AssemblableBase : public AssemblableProductInterface<Traits>,\n public Functor::Codim0<typename Traits::GridViewType>\n{\n typedef AssemblableProductInterface<Traits> InterfaceType;\n\npublic:\n typedef typename Traits::GridViewType GridViewType;\n typedef typename Traits::RangeSpaceType RangeSpaceType;\n typedef typename Traits::SourceSpaceType SourceSpaceType;\n typedef typename Traits::MatrixType MatrixType;\n\n typedef typename MatrixType::ScalarType FieldType;\n\nprivate:\n typedef TmpStorageProvider::Matrices<FieldType> TmpMatricesProviderType;\n typedef typename Traits::LocalOperatorType LocalOperatorType;\n typedef LocalAssembler::Codim0Matrix<LocalOperatorType> LocalAssemblerType;\n\npublic:\n using typename InterfaceType::EntityType;\n\n using InterfaceType::pattern;\n\n AssemblableBase(MatrixType& mtrx, const RangeSpaceType& rng_spc, const GridViewType& grd_vw,\n const SourceSpaceType& src_spc)\n : matrix_(mtrx)\n , range_space_(rng_spc)\n , grid_view_(grd_vw)\n , source_space_(src_spc)\n , local_assembler_(nullptr)\n , tmp_storage_(nullptr)\n , prepared_(false)\n , assembled_(false)\n {\n }\n\n AssemblableBase(MatrixType& mtrx, const RangeSpaceType& rng_spc, const GridViewType& grd_vw)\n : matrix_(mtrx)\n , range_space_(rng_spc)\n , grid_view_(grd_vw)\n , source_space_(range_space_)\n , local_assembler_(nullptr)\n , tmp_storage_(nullptr)\n , prepared_(false)\n , assembled_(false)\n {\n }\n\n AssemblableBase(MatrixType& mtrx, const RangeSpaceType& rng_spc)\n : matrix_(mtrx)\n , range_space_(rng_spc)\n , grid_view_(*(range_space_->grid_view()))\n , source_space_(range_space_)\n , local_assembler_(nullptr)\n , tmp_storage_(nullptr)\n , prepared_(false)\n , assembled_(false)\n {\n }\n\n const GridViewType& grid_view() const\n {\n return grid_view_;\n }\n\n const RangeSpaceType& range_space() const\n {\n return range_space_;\n }\n\n const SourceSpaceType& source_space() const\n {\n return source_space_;\n }\n\n MatrixType& matrix()\n {\n return matrix_;\n }\n\n const MatrixType& matrix() const\n {\n return matrix_;\n }\n\nprivate:\n virtual const LocalOperatorType& local_operator() const = 0;\n\npublic:\n virtual void prepare() DS_OVERRIDE\n {\n if (!assembled_ && !prepared_) {\n local_assembler_ = std::unique_ptr<LocalAssemblerType>(new LocalAssemblerType(local_operator()));\n tmp_storage_ = std::unique_ptr<TmpMatricesProviderType>(\n new TmpMatricesProviderType(local_assembler_->numTmpObjectsRequired(),\n range_space_.mapper().maxNumDofs(),\n source_space_.mapper().maxNumDofs()));\n prepared_ = true;\n }\n } \/\/ ... prepare()\n\n virtual void apply_local(const EntityType& entity) DS_OVERRIDE\n {\n assert(prepared_);\n assert(local_assembler_);\n assert(tmp_storage_);\n local_assembler_->assembleLocal(\n range_space_, source_space_, entity, matrix_, tmp_storage_->matrices(), tmp_storage_->indices());\n } \/\/ ... apply_local(...)\n\n void assemble()\n {\n if (!assembled_) {\n GridWalker<GridViewType> grid_walker(grid_view_);\n grid_walker.add(*this);\n grid_walker.walk();\n assembled_ = true;\n }\n } \/\/ ... assemble()\n\n using InterfaceType::apply2;\n\nprivate:\n MatrixType& matrix_;\n const RangeSpaceType& range_space_;\n const GridViewType& grid_view_;\n const SourceSpaceType& source_space_;\n std::unique_ptr<LocalAssemblerType> local_assembler_;\n std::unique_ptr<TmpMatricesProviderType> tmp_storage_;\n bool prepared_;\n bool assembled_;\n}; \/\/ class AssemblableBase\n\n\n} \/\/ namespace Products\n} \/\/ namespace GDT\n} \/\/ namespace Dune\n\n#endif \/\/ DUNE_GDT_PRODUCTS_BASE_HH\n<commit_msg>[products.base] added notes<commit_after>\/\/ This file is part of the dune-gdt project:\n\/\/ http:\/\/users.dune-project.org\/projects\/dune-gdt\n\/\/ Copyright holders: Felix Schindler\n\/\/ License: BSD 2-Clause License (http:\/\/opensource.org\/licenses\/BSD-2-Clause)\n\n#ifndef DUNE_GDT_PRODUCTS_BASE_HH\n#define DUNE_GDT_PRODUCTS_BASE_HH\n\n#include <dune\/gdt\/assembler\/system.hh>\n#include <dune\/gdt\/assembler\/tmp-storage.hh>\n#include <dune\/gdt\/assembler\/local\/codim0.hh>\n\n#include \"interfaces.hh\"\n\nnamespace Dune {\nnamespace GDT {\nnamespace Products {\n\n\n\/**\n * \\todo Derive from SystemAssembler, \\see Operators::EllipticG\n *\/\ntemplate <class Traits>\nclass LocalizableBase : public LocalizableProductInterface<Traits>,\n public Functor::Codim0<typename Traits::GridViewType>\n{\n typedef LocalizableProductInterface<Traits> InterfaceType;\n\npublic:\n typedef typename Traits::GridViewType GridViewType;\n typedef typename Traits::RangeType RangeType;\n typedef typename Traits::SourceType SourceType;\n typedef typename Traits::FieldType FieldType;\n\nprivate:\n typedef typename Traits::LocalOperatorType LocalOperatorType;\n typedef TmpStorageProvider::Matrices<FieldType> TmpMatricesProviderType;\n\npublic:\n using typename InterfaceType::EntityType;\n\npublic:\n LocalizableBase(const GridViewType& grd_vw, const RangeType& rng, const SourceType& src)\n : grid_view_(grd_vw)\n , range_(rng)\n , source_(src)\n , tmp_storage_(nullptr)\n , prepared_(false)\n , finalized_(false)\n , result_(0)\n {\n }\n\n LocalizableBase(const GridViewType& grd_vw, const RangeType& rng)\n : grid_view_(grd_vw)\n , range_(rng)\n , source_(range_)\n , tmp_storage_(nullptr)\n , prepared_(false)\n , finalized_(false)\n , result_(0)\n {\n }\n\n virtual ~LocalizableBase()\n {\n }\n\n const GridViewType& grid_view() const\n {\n return grid_view_;\n }\n\n const RangeType& range() const\n {\n return range_;\n }\n\n const SourceType& source() const\n {\n return source_;\n }\n\nprivate:\n virtual const LocalOperatorType& local_operator() const = 0;\n\npublic:\n virtual void prepare() DS_OVERRIDE\n {\n if (!prepared_) {\n tmp_storage_ = std::unique_ptr<TmpMatricesProviderType>(\n new TmpMatricesProviderType({1, local_operator().numTmpObjectsRequired()}, 1, 1));\n result_ *= 0.0;\n prepared_ = true;\n }\n } \/\/ ... prepare()\n\n virtual void apply_local(const EntityType& entity) DS_OVERRIDE\n {\n assert(prepared_);\n assert(tmp_storage_);\n auto& tmp_storage = tmp_storage_->matrices();\n assert(tmp_storage.size() >= 2);\n assert(tmp_storage[0].size() >= 1);\n auto& local_operator_result = tmp_storage[0][0];\n auto& tmp_matrices = tmp_storage[1];\n \/\/ get the local functions\n const auto local_source_ptr = this->source().local_function(entity);\n const auto local_range_ptr = this->range().local_function(entity);\n \/\/ apply local operator\n local_operator().apply(*local_range_ptr, *local_source_ptr, local_operator_result, tmp_matrices);\n assert(local_operator_result.rows() == 1);\n assert(local_operator_result.cols() == 1);\n result_ += local_operator_result[0][0];\n } \/\/ ... apply_local(...)\n\n virtual void finalize() DS_OVERRIDE\n {\n finalized_ = true;\n }\n\n FieldType apply2()\n {\n if (!finalized_) {\n GridWalker<GridViewType> grid_walker(grid_view_);\n grid_walker.add(*this);\n grid_walker.walk();\n }\n return result_;\n }\n\nprivate:\n const GridViewType& grid_view_;\n const RangeType& range_;\n const SourceType& source_;\n std::unique_ptr<TmpMatricesProviderType> tmp_storage_;\n bool prepared_;\n bool finalized_;\n FieldType result_;\n}; \/\/ class LocalizableBase\n\n\n\/**\n * \\todo Derive from SystemAssembler, \\see Operators::EllipticG\n *\/\ntemplate <class Traits>\nclass AssemblableBase : public AssemblableProductInterface<Traits>,\n public Functor::Codim0<typename Traits::GridViewType>\n{\n typedef AssemblableProductInterface<Traits> InterfaceType;\n\npublic:\n typedef typename Traits::GridViewType GridViewType;\n typedef typename Traits::RangeSpaceType RangeSpaceType;\n typedef typename Traits::SourceSpaceType SourceSpaceType;\n typedef typename Traits::MatrixType MatrixType;\n\n typedef typename MatrixType::ScalarType FieldType;\n\nprivate:\n typedef TmpStorageProvider::Matrices<FieldType> TmpMatricesProviderType;\n typedef typename Traits::LocalOperatorType LocalOperatorType;\n typedef LocalAssembler::Codim0Matrix<LocalOperatorType> LocalAssemblerType;\n\npublic:\n using typename InterfaceType::EntityType;\n\n using InterfaceType::pattern;\n\n AssemblableBase(MatrixType& mtrx, const RangeSpaceType& rng_spc, const GridViewType& grd_vw,\n const SourceSpaceType& src_spc)\n : matrix_(mtrx)\n , range_space_(rng_spc)\n , grid_view_(grd_vw)\n , source_space_(src_spc)\n , local_assembler_(nullptr)\n , tmp_storage_(nullptr)\n , prepared_(false)\n , assembled_(false)\n {\n }\n\n AssemblableBase(MatrixType& mtrx, const RangeSpaceType& rng_spc, const GridViewType& grd_vw)\n : matrix_(mtrx)\n , range_space_(rng_spc)\n , grid_view_(grd_vw)\n , source_space_(range_space_)\n , local_assembler_(nullptr)\n , tmp_storage_(nullptr)\n , prepared_(false)\n , assembled_(false)\n {\n }\n\n AssemblableBase(MatrixType& mtrx, const RangeSpaceType& rng_spc)\n : matrix_(mtrx)\n , range_space_(rng_spc)\n , grid_view_(*(range_space_->grid_view()))\n , source_space_(range_space_)\n , local_assembler_(nullptr)\n , tmp_storage_(nullptr)\n , prepared_(false)\n , assembled_(false)\n {\n }\n\n const GridViewType& grid_view() const\n {\n return grid_view_;\n }\n\n const RangeSpaceType& range_space() const\n {\n return range_space_;\n }\n\n const SourceSpaceType& source_space() const\n {\n return source_space_;\n }\n\n MatrixType& matrix()\n {\n return matrix_;\n }\n\n const MatrixType& matrix() const\n {\n return matrix_;\n }\n\nprivate:\n virtual const LocalOperatorType& local_operator() const = 0;\n\npublic:\n virtual void prepare() DS_OVERRIDE\n {\n if (!assembled_ && !prepared_) {\n local_assembler_ = std::unique_ptr<LocalAssemblerType>(new LocalAssemblerType(local_operator()));\n tmp_storage_ = std::unique_ptr<TmpMatricesProviderType>(\n new TmpMatricesProviderType(local_assembler_->numTmpObjectsRequired(),\n range_space_.mapper().maxNumDofs(),\n source_space_.mapper().maxNumDofs()));\n prepared_ = true;\n }\n } \/\/ ... prepare()\n\n virtual void apply_local(const EntityType& entity) DS_OVERRIDE\n {\n assert(prepared_);\n assert(local_assembler_);\n assert(tmp_storage_);\n local_assembler_->assembleLocal(\n range_space_, source_space_, entity, matrix_, tmp_storage_->matrices(), tmp_storage_->indices());\n } \/\/ ... apply_local(...)\n\n void assemble()\n {\n if (!assembled_) {\n GridWalker<GridViewType> grid_walker(grid_view_);\n grid_walker.add(*this);\n grid_walker.walk();\n assembled_ = true;\n }\n } \/\/ ... assemble()\n\n using InterfaceType::apply2;\n\nprivate:\n MatrixType& matrix_;\n const RangeSpaceType& range_space_;\n const GridViewType& grid_view_;\n const SourceSpaceType& source_space_;\n std::unique_ptr<LocalAssemblerType> local_assembler_;\n std::unique_ptr<TmpMatricesProviderType> tmp_storage_;\n bool prepared_;\n bool assembled_;\n}; \/\/ class AssemblableBase\n\n\n} \/\/ namespace Products\n} \/\/ namespace GDT\n} \/\/ namespace Dune\n\n#endif \/\/ DUNE_GDT_PRODUCTS_BASE_HH\n<|endoftext|>"} {"text":"<commit_before>\/\/ This file is part of the dune-gdt project:\n\/\/ https:\/\/github.com\/dune-community\/dune-gdt\n\/\/ Copyright 2010-2018 dune-gdt developers and contributors. All rights reserved.\n\/\/ License: Dual licensed as BSD 2-Clause License (http:\/\/opensource.org\/licenses\/BSD-2-Clause)\n\/\/ or GPL-2.0+ (http:\/\/opensource.org\/licenses\/gpl-license)\n\/\/ with \"runtime exception\" (http:\/\/www.dune-project.org\/license.html)\n\/\/ Authors:\n\/\/ Felix Schindler (2013 - 2017)\n\/\/ Rene Milk (2014, 2016 - 2017)\n\/\/ Tobias Leibner (2014, 2016)\n\n#ifndef DUNE_GDT_PROLONGATIONS_HH\n#define DUNE_GDT_PROLONGATIONS_HH\n\n#include <dune\/xt\/functions\/reinterpret.hh>\n#include <dune\/xt\/la\/container\/vector-interface.hh>\n\n#include <dune\/gdt\/discretefunction\/default.hh>\n#include <dune\/gdt\/discretefunction\/reinterpret.hh>\n#include <dune\/gdt\/interpolations.hh>\n#include <dune\/gdt\/spaces\/interface.hh>\n\nnamespace Dune {\nnamespace GDT {\n\n\n\/**\n * \\brief Prolongs a DiscreteFunction from one (usually coarser) GridView onto another (usually finer) one [most general\n * variant].\n *\n * \\note This does not clear target.dofs().vector(). Thus, if prolongation_grid_view only covers a part of the domain of\n * target.space().grid_view(), other contributions in target remain (which is on purpose).\n *\/\ntemplate <class SV, class SGV, size_t r, size_t rC, class SR, class TV, class TGV, class TR, class PGV>\nstd::enable_if_t<std::is_same<XT::Grid::extract_entity_t<TGV>, typename PGV::Grid::template Codim<0>::Entity>::value,\n void>\nprolong(const DiscreteFunction<SV, SGV, r, rC, SR>& source,\n DiscreteFunction<TV, TGV, r, rC, TR>& target,\n const GridView<PGV>& prolongation_grid_view)\n{\n interpolate(reinterpret(source, prolongation_grid_view), target, prolongation_grid_view);\n}\n\n\n\/**\n * \\brief Prolongs a DiscreteFunction from one (usually coarser) GridView onto another (usually finer) one [uses\n * target.space().grid_view() as prolongation_grid_view].\n *\/\ntemplate <class SV, class SGV, size_t r, size_t rC, class SR, class TV, class TGV, class TR>\nvoid prolong(const DiscreteFunction<SV, SGV, r, rC, SR>& source, DiscreteFunction<TV, TGV, r, rC, TR>& target)\n{\n prolong(source, target, target.space().grid_view());\n}\n\n\n\/**\n * \\brief Prolongs a DiscreteFunction from one (usually coarser) GridView onto another (usually finer) one [creates\n * suitable target_function, TargetVectorType has to be provided].\n *\n * Use as in\n\\code\nauto target_function = prolong<TargetVectorType>(source, target_space, prolongation_grid_view);\n\\endcode\n *\/\ntemplate <class TargetVectorType, class SV, class SGV, size_t r, size_t rC, class SR, class TGV, class TR, class PGV>\nstd::enable_if_t<std::is_same<XT::Grid::extract_entity_t<TGV>, typename PGV::Grid::template Codim<0>::Entity>::value,\n DiscreteFunction<TargetVectorType, TGV, r, rC, TR>>\nprolong(const DiscreteFunction<SV, SGV, r, rC, SR>& source,\n const SpaceInterface<TGV, r, rC, TR>& target_space,\n const GridView<PGV>& prolongation_grid_view)\n{\n auto target_function = make_discrete_function<TargetVectorType>(target_space);\n prolong(source, target_function, prolongation_grid_view);\n return target_function;\n}\n\n\n\/**\n * \\brief Prolongs a DiscreteFunction from one (usually coarser) GridView onto another (usually finer) one [creates\n * suitable target_function, TargetVectorType has to be provided, uses target.space().grid_view() as\n * prolongation_grid_view].\n *\n * Use as in\n\\code\nauto target_function = prolong<TargetVectorType>(source, target_space);\n\\endcode\n *\/\ntemplate <class TargetVectorType, class SV, class SGV, size_t r, size_t rC, class SR, class TGV, class TR>\nDiscreteFunction<TargetVectorType, TGV, r, rC, TR> prolong(const DiscreteFunction<SV, SGV, r, rC, SR>& source,\n const SpaceInterface<TGV, r, rC, TR>& target_space)\n{\n auto target_function = make_discrete_function<TargetVectorType>(target_space);\n prolong(source, target_function);\n return target_function;\n}\n\n\n\/**\n * \\brief Prolongs a DiscreteFunction from one (usually coarser) GridView onto another (usually finer) one [creates\n * suitable target_function with same VectorType as source].\n *\/\ntemplate <class V, class SGV, size_t r, size_t rC, class SR, class TGV, class TR, class PGV>\nstd::enable_if_t<std::is_same<XT::Grid::extract_entity_t<TGV>, typename PGV::Grid::template Codim<0>::Entity>::value,\n DiscreteFunction<V, TGV, r, rC, TR>>\nprolong(const DiscreteFunction<V, SGV, r, rC, SR>& source,\n const SpaceInterface<TGV, r, rC, TR>& target_space,\n const GridView<PGV>& prolongation_grid_view)\n{\n auto target_function = make_discrete_function<V>(target_space);\n prolong(source, target_function, prolongation_grid_view);\n return target_function;\n}\n\n\n\/**\n * \\brief Prolongs a DiscreteFunction from one (usually coarser) GridView onto another (usually finer) one [creates\n * suitable target_function with same VectorType as source, uses target.space().grid_view() as\n * prolongation_grid_view].\n *\/\ntemplate <class V, class SGV, size_t r, size_t rC, class SR, class TGV, class TR>\nDiscreteFunction<V, TGV, r, rC, TR> prolong(const DiscreteFunction<V, SGV, r, rC, SR>& source,\n const SpaceInterface<TGV, r, rC, TR>& target_space)\n{\n auto target_function = make_discrete_function<V>(target_space);\n prolong(source, target_function);\n return target_function;\n}\n\n\n} \/\/ namespace GDT\n} \/\/ namespace Dune\n\n#endif \/\/ DUNE_GDT_PROLONGATIONS_HH\n<commit_msg>[prolongations] update doc<commit_after>\/\/ This file is part of the dune-gdt project:\n\/\/ https:\/\/github.com\/dune-community\/dune-gdt\n\/\/ Copyright 2010-2018 dune-gdt developers and contributors. All rights reserved.\n\/\/ License: Dual licensed as BSD 2-Clause License (http:\/\/opensource.org\/licenses\/BSD-2-Clause)\n\/\/ or GPL-2.0+ (http:\/\/opensource.org\/licenses\/gpl-license)\n\/\/ with \"runtime exception\" (http:\/\/www.dune-project.org\/license.html)\n\/\/ Authors:\n\/\/ Felix Schindler (2013 - 2017)\n\/\/ Rene Milk (2014, 2016 - 2017)\n\/\/ Tobias Leibner (2014, 2016)\n\n#ifndef DUNE_GDT_PROLONGATIONS_HH\n#define DUNE_GDT_PROLONGATIONS_HH\n\n#include <dune\/xt\/functions\/reinterpret.hh>\n#include <dune\/xt\/la\/container\/vector-interface.hh>\n\n#include <dune\/gdt\/discretefunction\/default.hh>\n#include <dune\/gdt\/discretefunction\/reinterpret.hh>\n#include <dune\/gdt\/interpolations.hh>\n#include <dune\/gdt\/spaces\/interface.hh>\n\nnamespace Dune {\nnamespace GDT {\n\n\n\/**\n * \\brief Prolongs a DiscreteFunction from one (usually coarser) GridView onto another (usually finer) one [most general\n * variant].\n *\n * \\note This does not clear target.dofs().vector(). Thus, if prolongation_grid_view only covers a part of the domain of\n * target.space().grid_view(), other contributions in target remain (which is on purpose).\n *\n * \\sa interpolate\n * \\sa reinterpret\n *\/\ntemplate <class SV, class SGV, size_t r, size_t rC, class SR, class TV, class TGV, class TR, class PGV>\nstd::enable_if_t<std::is_same<XT::Grid::extract_entity_t<TGV>, typename PGV::Grid::template Codim<0>::Entity>::value,\n void>\nprolong(const DiscreteFunction<SV, SGV, r, rC, SR>& source,\n DiscreteFunction<TV, TGV, r, rC, TR>& target,\n const GridView<PGV>& prolongation_grid_view)\n{\n interpolate(reinterpret(source, prolongation_grid_view), target, prolongation_grid_view);\n}\n\n\n\/**\n * \\brief Prolongs a DiscreteFunction from one (usually coarser) GridView onto another (usually finer) one [uses\n * target.space().grid_view() as prolongation_grid_view].\n *\/\ntemplate <class SV, class SGV, size_t r, size_t rC, class SR, class TV, class TGV, class TR>\nvoid prolong(const DiscreteFunction<SV, SGV, r, rC, SR>& source, DiscreteFunction<TV, TGV, r, rC, TR>& target)\n{\n prolong(source, target, target.space().grid_view());\n}\n\n\n\/**\n * \\brief Prolongs a DiscreteFunction from one (usually coarser) GridView onto another (usually finer) one [creates\n * suitable target_function, TargetVectorType has to be provided].\n *\n * Use as in\n\\code\nauto target_function = prolong<TargetVectorType>(source, target_space, prolongation_grid_view);\n\\endcode\n *\/\ntemplate <class TargetVectorType, class SV, class SGV, size_t r, size_t rC, class SR, class TGV, class TR, class PGV>\nstd::enable_if_t<std::is_same<XT::Grid::extract_entity_t<TGV>, typename PGV::Grid::template Codim<0>::Entity>::value,\n DiscreteFunction<TargetVectorType, TGV, r, rC, TR>>\nprolong(const DiscreteFunction<SV, SGV, r, rC, SR>& source,\n const SpaceInterface<TGV, r, rC, TR>& target_space,\n const GridView<PGV>& prolongation_grid_view)\n{\n auto target_function = make_discrete_function<TargetVectorType>(target_space);\n prolong(source, target_function, prolongation_grid_view);\n return target_function;\n}\n\n\n\/**\n * \\brief Prolongs a DiscreteFunction from one (usually coarser) GridView onto another (usually finer) one [creates\n * suitable target_function, TargetVectorType has to be provided, uses target.space().grid_view() as\n * prolongation_grid_view].\n *\n * Use as in\n\\code\nauto target_function = prolong<TargetVectorType>(source, target_space);\n\\endcode\n *\/\ntemplate <class TargetVectorType, class SV, class SGV, size_t r, size_t rC, class SR, class TGV, class TR>\nDiscreteFunction<TargetVectorType, TGV, r, rC, TR> prolong(const DiscreteFunction<SV, SGV, r, rC, SR>& source,\n const SpaceInterface<TGV, r, rC, TR>& target_space)\n{\n auto target_function = make_discrete_function<TargetVectorType>(target_space);\n prolong(source, target_function);\n return target_function;\n}\n\n\n\/**\n * \\brief Prolongs a DiscreteFunction from one (usually coarser) GridView onto another (usually finer) one [creates\n * suitable target_function with same VectorType as source].\n *\/\ntemplate <class V, class SGV, size_t r, size_t rC, class SR, class TGV, class TR, class PGV>\nstd::enable_if_t<std::is_same<XT::Grid::extract_entity_t<TGV>, typename PGV::Grid::template Codim<0>::Entity>::value,\n DiscreteFunction<V, TGV, r, rC, TR>>\nprolong(const DiscreteFunction<V, SGV, r, rC, SR>& source,\n const SpaceInterface<TGV, r, rC, TR>& target_space,\n const GridView<PGV>& prolongation_grid_view)\n{\n auto target_function = make_discrete_function<V>(target_space);\n prolong(source, target_function, prolongation_grid_view);\n return target_function;\n}\n\n\n\/**\n * \\brief Prolongs a DiscreteFunction from one (usually coarser) GridView onto another (usually finer) one [creates\n * suitable target_function with same VectorType as source, uses target.space().grid_view() as\n * prolongation_grid_view].\n *\/\ntemplate <class V, class SGV, size_t r, size_t rC, class SR, class TGV, class TR>\nDiscreteFunction<V, TGV, r, rC, TR> prolong(const DiscreteFunction<V, SGV, r, rC, SR>& source,\n const SpaceInterface<TGV, r, rC, TR>& target_space)\n{\n auto target_function = make_discrete_function<V>(target_space);\n prolong(source, target_function);\n return target_function;\n}\n\n\n} \/\/ namespace GDT\n} \/\/ namespace Dune\n\n#endif \/\/ DUNE_GDT_PROLONGATIONS_HH\n<|endoftext|>"} {"text":"<commit_before>\/\/ This file is part of the dune-stuff project:\n\/\/ https:\/\/github.com\/wwu-numerik\/dune-stuff\n\/\/ Copyright holders: Rene Milk, Felix Schindler\n\/\/ License: BSD 2-Clause License (http:\/\/opensource.org\/licenses\/BSD-2-Clause)\n\n#ifndef DUNE_STUFF_GRID_ENTITY_HH\n#define DUNE_STUFF_GRID_ENTITY_HH\n\n#include <dune\/geometry\/referenceelements.hh>\n\n#if HAVE_DUNE_GRID\n# include <dune\/grid\/common\/entity.hh>\n# include <dune\/grid\/common\/gridview.hh>\n#endif\n\n#include <dune\/stuff\/common\/string.hh>\n#include <dune\/stuff\/common\/print.hh>\n#include <dune\/stuff\/common\/ranges.hh>\n#include <dune\/stuff\/aliases.hh>\n\nnamespace Dune {\nnamespace Stuff {\nnamespace Grid {\n\n#if HAVE_DUNE_GRID\n\n\ntemplate< class GridPartOrViewType >\nclass Entity\n{\n template< class GridViewType, bool is_view >\n struct Choose\n {\n typedef typename GridViewType::template Codim< 0 >::Entity Type;\n };\n\n template< class GridPartType >\n struct Choose< GridPartType, false >\n {\n typedef typename GridPartType::template Codim< 0 >::EntityType Type;\n };\n\n static const bool this_is_a_grid_view =\n std::is_base_of< GridView< typename GridPartOrViewType::Traits >, GridPartOrViewType >::value;\n\npublic:\n typedef typename Choose< GridPartOrViewType, this_is_a_grid_view >::Type Type;\n}; \/\/ class Entity\n\n\n#endif \/\/ HAVE_DUNE_GRID\n\n\ntemplate< class EntityType >\nvoid printEntity(const EntityType& entity,\n const std::string name = Common::Typename< EntityType >::value(),\n std::ostream& out = std::cout, const std::string prefix = \"\")\n{\n if (!name.empty())\n out << prefix << name << \":\\n\";\n const auto& geometry = entity.geometry();\n for (auto ii : DSC::valueRange(geometry.corners()))\n Common::print(geometry.corner(ii), \"corner \" + Common::toString(ii), out, prefix + \" \");\n} \/\/ ... printEntity(...)\n\n\n#if HAVE_DUNE_GRID\n\ntemplate< int codim, int worlddim, class GridImp, template< int, int, class > class EntityImp >\ndouble entity_diameter(const Dune::Entity< codim, worlddim, GridImp, EntityImp >& entity) {\n auto max_dist = std::numeric_limits<typename GridImp::ctype>::min();\n const auto& geometry = entity.geometry();\n for (auto i : DSC::valueRange(geometry.corners()))\n {\n const auto xi = geometry.corner(i);\n for (auto j : DSC::valueRange(i + 1, geometry.corners()))\n {\n auto xj = geometry.corner(j);\n xj -= xi;\n max_dist = std::max(max_dist, xj.two_norm());\n }\n }\n return max_dist;\n} \/\/ entity_diameter\n\ntemplate< size_t codim, size_t worlddim, class GridImp, template< int, int, class > class EntityImp >\ndouble DUNE_DEPRECATED_MSG(\"use entity_diameter instead, but: changed meaning from min conerdistance to max corner distance\")\nentityDiameter(const Dune::Entity< codim, worlddim, GridImp, EntityImp >& entity) {\n return entity_diameter(entity);\n} \/\/entityDiameter\n\n\n#if DUNE_VERSION_NEWER(DUNE_GEOMETRY, 2, 3)\n# define REFERENCE_ELEMENTS ReferenceElements\n#else\n# define REFERENCE_ELEMENTS GenericReferenceElements\n#endif\n\ntemplate< int codim, int worlddim, class GridImp, template< int, int, class > class EntityImp >\nauto reference_element(const Dune::Entity< codim, worlddim, GridImp, EntityImp >& entity)\n-> decltype(REFERENCE_ELEMENTS< typename GridImp::ctype, worlddim >::general(entity.geometry().type()))\n{\n return REFERENCE_ELEMENTS< typename GridImp::ctype, worlddim >::general(entity.geometry().type());\n}\n\ntemplate <int mydim, int cdim, class GridImp, template< int, int, class > class GeometryImp>\nauto reference_element(const Dune::Geometry< mydim, cdim, GridImp, GeometryImp>& geometry)\n-> decltype(REFERENCE_ELEMENTS< typename GridImp::ctype, mydim >::general(geometry.type()))\n{\n return REFERENCE_ELEMENTS< typename GridImp::ctype, mydim >::general(geometry.type());\n}\n\n#undef REFERENCE_ELEMENTS\n\n#endif \/\/ HAVE_DUNE_GRID\n\n} \/\/ namespace Grid\n} \/\/ namespace Stuff\n} \/\/ namespace Dune\n\n#endif \/\/ DUNE_STUFF_GRID_ENTITY_HH\n<commit_msg>[grid.entity] whitespace<commit_after>\/\/ This file is part of the dune-stuff project:\n\/\/ https:\/\/github.com\/wwu-numerik\/dune-stuff\n\/\/ Copyright holders: Rene Milk, Felix Schindler\n\/\/ License: BSD 2-Clause License (http:\/\/opensource.org\/licenses\/BSD-2-Clause)\n\n#ifndef DUNE_STUFF_GRID_ENTITY_HH\n#define DUNE_STUFF_GRID_ENTITY_HH\n\n#include <dune\/geometry\/referenceelements.hh>\n\n#if HAVE_DUNE_GRID\n# include <dune\/grid\/common\/entity.hh>\n# include <dune\/grid\/common\/gridview.hh>\n#endif\n\n#include <dune\/stuff\/common\/string.hh>\n#include <dune\/stuff\/common\/print.hh>\n#include <dune\/stuff\/common\/ranges.hh>\n#include <dune\/stuff\/aliases.hh>\n\nnamespace Dune {\nnamespace Stuff {\nnamespace Grid {\n\n#if HAVE_DUNE_GRID\n\n\ntemplate< class GridPartOrViewType >\nclass Entity\n{\n template< class GridViewType, bool is_view >\n struct Choose\n {\n typedef typename GridViewType::template Codim< 0 >::Entity Type;\n };\n\n template< class GridPartType >\n struct Choose< GridPartType, false >\n {\n typedef typename GridPartType::template Codim< 0 >::EntityType Type;\n };\n\n static const bool this_is_a_grid_view =\n std::is_base_of< GridView< typename GridPartOrViewType::Traits >, GridPartOrViewType >::value;\n\npublic:\n typedef typename Choose< GridPartOrViewType, this_is_a_grid_view >::Type Type;\n}; \/\/ class Entity\n\n\n#endif \/\/ HAVE_DUNE_GRID\n\n\ntemplate< class EntityType >\nvoid printEntity(const EntityType& entity,\n const std::string name = Common::Typename< EntityType >::value(),\n std::ostream& out = std::cout,\n const std::string prefix = \"\")\n{\n if (!name.empty())\n out << prefix << name << \":\\n\";\n const auto& geometry = entity.geometry();\n for (auto ii : DSC::valueRange(geometry.corners()))\n Common::print(geometry.corner(ii), \"corner \" + Common::toString(ii), out, prefix + \" \");\n} \/\/ ... printEntity(...)\n\n\n#if HAVE_DUNE_GRID\n\ntemplate< int codim, int worlddim, class GridImp, template< int, int, class > class EntityImp >\ndouble entity_diameter(const Dune::Entity< codim, worlddim, GridImp, EntityImp >& entity) {\n auto max_dist = std::numeric_limits<typename GridImp::ctype>::min();\n const auto& geometry = entity.geometry();\n for (auto i : DSC::valueRange(geometry.corners()))\n {\n const auto xi = geometry.corner(i);\n for (auto j : DSC::valueRange(i + 1, geometry.corners()))\n {\n auto xj = geometry.corner(j);\n xj -= xi;\n max_dist = std::max(max_dist, xj.two_norm());\n }\n }\n return max_dist;\n} \/\/ entity_diameter\n\ntemplate< size_t codim, size_t worlddim, class GridImp, template< int, int, class > class EntityImp >\ndouble DUNE_DEPRECATED_MSG(\"use entity_diameter instead, but: changed meaning from min conerdistance to max corner distance\")\nentityDiameter(const Dune::Entity< codim, worlddim, GridImp, EntityImp >& entity) {\n return entity_diameter(entity);\n} \/\/entityDiameter\n\n\n#if DUNE_VERSION_NEWER(DUNE_GEOMETRY, 2, 3)\n# define REFERENCE_ELEMENTS ReferenceElements\n#else\n# define REFERENCE_ELEMENTS GenericReferenceElements\n#endif\n\ntemplate< int codim, int worlddim, class GridImp, template< int, int, class > class EntityImp >\nauto reference_element(const Dune::Entity< codim, worlddim, GridImp, EntityImp >& entity)\n-> decltype(REFERENCE_ELEMENTS< typename GridImp::ctype, worlddim >::general(entity.geometry().type()))\n{\n return REFERENCE_ELEMENTS< typename GridImp::ctype, worlddim >::general(entity.geometry().type());\n}\n\ntemplate <int mydim, int cdim, class GridImp, template< int, int, class > class GeometryImp>\nauto reference_element(const Dune::Geometry< mydim, cdim, GridImp, GeometryImp>& geometry)\n-> decltype(REFERENCE_ELEMENTS< typename GridImp::ctype, mydim >::general(geometry.type()))\n{\n return REFERENCE_ELEMENTS< typename GridImp::ctype, mydim >::general(geometry.type());\n}\n\n#undef REFERENCE_ELEMENTS\n\n#endif \/\/ HAVE_DUNE_GRID\n\n} \/\/ namespace Grid\n} \/\/ namespace Stuff\n} \/\/ namespace Dune\n\n#endif \/\/ DUNE_STUFF_GRID_ENTITY_HH\n<|endoftext|>"} {"text":"<commit_before>\/******************************************************************************\n * ____ _ _____ *\n * \/ ___| \/ \\ | ___| C++ *\n * | | \/ _ \\ | |_ Actor *\n * | |___ \/ ___ \\| _| Framework *\n * \\____\/_\/ \\_|_| *\n * *\n * Copyright (C) 2011 - 2016 *\n * Dominik Charousset <dominik.charousset (at) haw-hamburg.de> *\n * *\n * Distributed under the terms and conditions of the BSD 3-Clause License or *\n * (at your option) under the terms and conditions of the Boost Software *\n * License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. *\n * *\n * If you did not receive a copy of the license files, see *\n * http:\/\/opensource.org\/licenses\/BSD-3-Clause and *\n * http:\/\/www.boost.org\/LICENSE_1_0.txt. *\n ******************************************************************************\/\n\n#ifndef CAF_DETAIL_LOGGING_HPP\n#define CAF_DETAIL_LOGGING_HPP\n\n#include <thread>\n#include <cstring>\n#include <sstream>\n#include <iostream>\n#include <typeinfo>\n#include <type_traits>\n#include <unordered_map>\n\n#include \"caf\/fwd.hpp\"\n#include \"caf\/config.hpp\"\n#include \"caf\/unifyn.hpp\"\n#include \"caf\/abstract_actor.hpp\"\n#include \"caf\/deep_to_string.hpp\"\n\n#include \"caf\/type_nr.hpp\"\n#include \"caf\/detail\/scope_guard.hpp\"\n#include \"caf\/detail\/shared_spinlock.hpp\"\n#include \"caf\/detail\/single_reader_queue.hpp\"\n\n\/*\n * To enable logging, you have to define CAF_DEBUG. This enables\n * CAF_LOG_ERROR messages. To enable more debugging output, you can\n * define CAF_LOG_LEVEL to:\n * 1: + warning\n * 2: + info\n * 3: + debug\n * 4: + trace (prints for each logged method entry and exit message)\n *\n * Note: this logger emits log4j style output; logs are best viewed\n * using a log4j viewer, e.g., http:\/\/code.google.com\/p\/otroslogviewer\/\n *\n *\/\nnamespace caf {\n\n\/\/\/ Centrally logs events from all actors in an actor system. To enable\n\/\/\/ logging in your application, you need to define `CAF_LOG_LEVEL`. Per\n\/\/\/ default, the logger generates log4j compatible output.\nclass logger {\npublic:\n friend class actor_system;\n\n struct event {\n event* next;\n event* prev;\n int level;\n std::string prefix;\n std::string msg;\n explicit event(int l = 0, std::string p = \"\", std::string m = \"\");\n };\n\n template <class T>\n struct arg_wrapper {\n const char* name;\n const T& value;\n arg_wrapper(const char* x, const T& y) : name(x), value(y) {\n \/\/ nop\n }\n };\n\n template <class T>\n static arg_wrapper<T> make_arg_wrapper(const char* name, const T& value) {\n return {name, value};\n }\n\n static std::string render_type_name(const std::type_info& ti);\n\n class line_builder {\n public:\n line_builder();\n\n template <class T>\n line_builder& operator<<(const T& x) {\n if (!str_.empty())\n str_ += \" \";\n std::stringstream ss;\n ss << x;\n str_ += ss.str();\n behind_arg_ = false;\n return *this;\n }\n\n template <class T>\n line_builder& operator<<(const arg_wrapper<T>& x) {\n if (behind_arg_)\n str_ += \", \";\n else if (!str_.empty())\n str_ += \" \";\n str_ += x.name;\n str_ += \" = \";\n str_ += deep_to_string(x.value);\n behind_arg_ = true;\n return *this;\n }\n\n line_builder& operator<<(const std::string& str);\n\n line_builder& operator<<(const char* str);\n\n std::string get() const;\n\n private:\n std::string str_;\n bool behind_arg_;\n };\n\n static std::string extract_class_name(const char* prettyfun, size_t strsize);\n\n template <size_t N>\n static std::string extract_class_name(const char (&prettyfun)[N]) {\n return extract_class_name(prettyfun, N);\n }\n\n \/\/\/ Returns the ID of the actor currently associated to the calling thread.\n actor_id thread_local_aid();\n\n \/\/\/ Associates an actor ID to the calling thread and returns the last value.\n actor_id thread_local_aid(actor_id aid);\n\n \/\/\/ Writes an entry to the log file.\n void log(int level, const char* component, const std::string& class_name,\n const char* function_name, const char* file_name,\n int line_num, const std::string& msg);\n\n ~logger();\n\n \/** @cond PRIVATE *\/\n\n static void set_current_actor_system(actor_system*);\n\n static logger* current_logger();\n\n static void log_static(int level, const char* component,\n const std::string& class_name,\n const char* function_name,\n const char* file_name, int line_num,\n const std::string& msg);\n\n \/** @endcond *\/\n\nprivate:\n logger(actor_system& sys);\n\n void run();\n\n void start();\n\n void stop();\n\n actor_system& system_;\n int level_;\n detail::shared_spinlock aids_lock_;\n std::unordered_map<std::thread::id, actor_id> aids_;\n std::thread thread_;\n std::mutex queue_mtx_;\n std::condition_variable queue_cv_;\n detail::single_reader_queue<event> queue_;\n};\n\n} \/\/ namespace caf\n\n#define CAF_VOID_STMT static_cast<void>(0)\n\n#define CAF_CAT(a, b) a##b\n\n#define CAF_LOG_LEVEL_ERROR 0\n#define CAF_LOG_LEVEL_WARNING 1\n#define CAF_LOG_LEVEL_INFO 2\n#define CAF_LOG_LEVEL_DEBUG 3\n#define CAF_LOG_LEVEL_TRACE 4\n\n#define CAF_PRINT_ERROR_IMPL(nclass, nfun, message) \\\n do { \\\n caf::logger::line_builder lb; \\\n lb << message; \\\n if (nclass.empty()) \\\n printf(\"[ERROR] in %s:%d %s::%s: %s\\n\", __FILE__, __LINE__, \\\n nclass.c_str(), nfun, lb.get().c_str()); \\\n else \\\n printf(\"[ERROR] in %s:%d %s: %s\\n\", __FILE__, __LINE__, \\\n nfun, lb.get().c_str()); \\\n } while (false)\n\n#define CAF_ARG(argument) caf::logger::make_arg_wrapper(#argument, argument)\n\n#ifdef CAF_MSVC\n#define CAF_GET_CLASS_NAME caf::logger::extract_class_name(__FUNCSIG__)\n#else \/\/ CAF_MSVC\n#define CAF_GET_CLASS_NAME caf::logger::extract_class_name(__PRETTY_FUNCTION__)\n#endif \/\/ CAF_MSVC\n\n#ifndef CAF_LOG_LEVEL\n\n#define CAF_LOG_IMPL(unused1, unused2)\n\n\/\/ placeholder macros when compiling without logging\ninline caf::actor_id caf_set_aid_dummy() { return 0; }\n\n#define CAF_PUSH_AID(unused) CAF_VOID_STMT\n\n#define CAF_PUSH_AID_FROM_PTR(unused) CAF_VOID_STMT\n\n#define CAF_SET_AID(unused) caf_set_aid_dummy()\n\n#define CAF_SET_LOGGER_SYS(unused) CAF_VOID_STMT\n\n#define CAF_LOG_TRACE(unused)\n\n#else \/\/ CAF_LOG_LEVEL\n\n#ifndef CAF_LOG_COMPONENT\n#define CAF_LOG_COMPONENT \"caf\"\n#endif\n\n#define CAF_LOG_IMPL(loglvl, message) \\\n caf::logger::log_static(loglvl, CAF_LOG_COMPONENT, CAF_GET_CLASS_NAME, \\\n __func__, __FILE__, __LINE__, \\\n (caf::logger::line_builder{} << message).get())\n\n#define CAF_PUSH_AID(aarg) \\\n auto CAF_UNIFYN(caf_tmp_ptr) = caf::logger::current_logger(); \\\n caf::actor_id CAF_UNIFYN(caf_aid_tmp) = 0; \\\n if (CAF_UNIFYN(caf_tmp_ptr)) \\\n CAF_UNIFYN(caf_aid_tmp) = CAF_UNIFYN(caf_tmp_ptr)->thread_local_aid(aarg); \\\n auto CAF_UNIFYN(aid_aid_tmp_guard) = caf::detail::make_scope_guard([=] { \\\n auto CAF_UNIFYN(caf_tmp2_ptr) = caf::logger::current_logger(); \\\n if (CAF_UNIFYN(caf_tmp2_ptr)) \\\n CAF_UNIFYN(caf_tmp2_ptr)->thread_local_aid(CAF_UNIFYN(caf_aid_tmp)); \\\n })\n\n#define CAF_PUSH_AID_FROM_PTR(some_ptr) \\\n auto CAF_UNIFYN(caf_aid_ptr) = some_ptr; \\\n CAF_PUSH_AID(CAF_UNIFYN(caf_aid_ptr) ? CAF_UNIFYN(caf_aid_ptr)->id() : 0)\n\n#define CAF_SET_AID(aid_arg) \\\n (caf::logger::current_logger() \\\n ? caf::logger::current_logger()->thread_local_aid(aid_arg) \\\n : 0)\n\n#define CAF_SET_LOGGER_SYS(ptr) caf::logger::set_current_actor_system(ptr)\n\n#if CAF_LOG_LEVEL < CAF_LOG_LEVEL_TRACE\n\n#define CAF_LOG_TRACE(unused) CAF_VOID_STMT\n\n#else \/\/ CAF_LOG_LEVEL < CAF_LOG_LEVEL_TRACE\n\n#define CAF_LOG_TRACE(entry_message) \\\n const char* CAF_UNIFYN(func_name_) = __func__; \\\n CAF_LOG_IMPL(CAF_LOG_LEVEL_TRACE, \"ENTRY\" << entry_message); \\\n auto CAF_UNIFYN(caf_log_trace_guard_) = ::caf::detail::make_scope_guard([=] {\\\n caf::logger::log_static(CAF_LOG_LEVEL_TRACE, CAF_LOG_COMPONENT, \\\n CAF_GET_CLASS_NAME, CAF_UNIFYN(func_name_), \\\n __FILE__, __LINE__, \"EXIT\"); \\\n })\n\n#endif \/\/ CAF_LOG_LEVEL < CAF_LOG_LEVEL_TRACE\n\n#if CAF_LOG_LEVEL >= CAF_LOG_LEVEL_DEBUG\n# define CAF_LOG_DEBUG(output) CAF_LOG_IMPL(CAF_LOG_LEVEL_DEBUG, output)\n#endif\n\n#if CAF_LOG_LEVEL >= CAF_LOG_LEVEL_INFO\n# define CAF_LOG_INFO(output) CAF_LOG_IMPL(CAF_LOG_LEVEL_INFO, output)\n#endif\n\n#if CAF_LOG_LEVEL >= CAF_LOG_LEVEL_WARNING\n# define CAF_LOG_WARNING(output) CAF_LOG_IMPL(CAF_LOG_LEVEL_WARNING, output)\n#endif\n\n#endif \/\/ CAF_LOG_LEVEL\n\n#ifndef CAF_LOG_INFO\n# define CAF_LOG_INFO(output) CAF_VOID_STMT\n#endif\n\n#ifndef CAF_LOG_DEBUG\n# define CAF_LOG_DEBUG(output) CAF_VOID_STMT\n#endif\n\n#ifndef CAF_LOG_WARNING\n# define CAF_LOG_WARNING(output) CAF_VOID_STMT\n#endif\n\n#define CAF_LOG_ERROR(output) \\\n do { \\\n CAF_PRINT_ERROR_IMPL(CAF_GET_CLASS_NAME, __func__, output); \\\n CAF_LOG_IMPL(CAF_LOG_LEVEL_ERROR, output); \\\n } while (false)\n\n#ifdef CAF_LOG_LEVEL\n\n#define CAF_LOG_DEBUG_IF(cond, output) \\\n if (cond) { CAF_LOG_IMPL(CAF_LOG_LEVEL_DEBUG, output); } CAF_VOID_STMT\n\n#define CAF_LOG_INFO_IF(cond, output) \\\n if (cond) { CAF_LOG_IMPL(CAF_LOG_LEVEL_INFO, output); } CAF_VOID_STMT\n\n#define CAF_LOG_WARNING_IF(cond, output) \\\n if (cond) { CAF_LOG_IMPL(CAF_LOG_LEVEL_WARNING, output); } CAF_VOID_STMT\n\n#define CAF_LOG_ERROR_IF(cond, output) \\\n if (cond) { CAF_LOG_IMPL(CAF_LOG_LEVEL_ERROR, output); } CAF_VOID_STMT\n\n#else \/\/ CAF_LOG_LEVEL\n\n#define CAF_LOG_DEBUG_IF(unused1, unused2)\n#define CAF_LOG_INFO_IF(unused1, unused2)\n#define CAF_LOG_WARNING_IF(unused1, unused2)\n#define CAF_LOG_ERROR_IF(unused1, unused2)\n\n#endif \/\/ CAF_LOG_LEVEL\n\n#endif \/\/ CAF_DETAIL_LOGGING_HPP\n<commit_msg>Demote errors to normal log events<commit_after>\/******************************************************************************\n * ____ _ _____ *\n * \/ ___| \/ \\ | ___| C++ *\n * | | \/ _ \\ | |_ Actor *\n * | |___ \/ ___ \\| _| Framework *\n * \\____\/_\/ \\_|_| *\n * *\n * Copyright (C) 2011 - 2016 *\n * Dominik Charousset <dominik.charousset (at) haw-hamburg.de> *\n * *\n * Distributed under the terms and conditions of the BSD 3-Clause License or *\n * (at your option) under the terms and conditions of the Boost Software *\n * License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. *\n * *\n * If you did not receive a copy of the license files, see *\n * http:\/\/opensource.org\/licenses\/BSD-3-Clause and *\n * http:\/\/www.boost.org\/LICENSE_1_0.txt. *\n ******************************************************************************\/\n\n#ifndef CAF_DETAIL_LOGGING_HPP\n#define CAF_DETAIL_LOGGING_HPP\n\n#include <thread>\n#include <cstring>\n#include <sstream>\n#include <iostream>\n#include <typeinfo>\n#include <type_traits>\n#include <unordered_map>\n\n#include \"caf\/fwd.hpp\"\n#include \"caf\/config.hpp\"\n#include \"caf\/unifyn.hpp\"\n#include \"caf\/abstract_actor.hpp\"\n#include \"caf\/deep_to_string.hpp\"\n\n#include \"caf\/type_nr.hpp\"\n#include \"caf\/detail\/scope_guard.hpp\"\n#include \"caf\/detail\/shared_spinlock.hpp\"\n#include \"caf\/detail\/single_reader_queue.hpp\"\n\n\/*\n * To enable logging, you have to define CAF_DEBUG. This enables\n * CAF_LOG_ERROR messages. To enable more debugging output, you can\n * define CAF_LOG_LEVEL to:\n * 1: + warning\n * 2: + info\n * 3: + debug\n * 4: + trace (prints for each logged method entry and exit message)\n *\n * Note: this logger emits log4j style output; logs are best viewed\n * using a log4j viewer, e.g., http:\/\/code.google.com\/p\/otroslogviewer\/\n *\n *\/\nnamespace caf {\n\n\/\/\/ Centrally logs events from all actors in an actor system. To enable\n\/\/\/ logging in your application, you need to define `CAF_LOG_LEVEL`. Per\n\/\/\/ default, the logger generates log4j compatible output.\nclass logger {\npublic:\n friend class actor_system;\n\n struct event {\n event* next;\n event* prev;\n int level;\n std::string prefix;\n std::string msg;\n explicit event(int l = 0, std::string p = \"\", std::string m = \"\");\n };\n\n template <class T>\n struct arg_wrapper {\n const char* name;\n const T& value;\n arg_wrapper(const char* x, const T& y) : name(x), value(y) {\n \/\/ nop\n }\n };\n\n template <class T>\n static arg_wrapper<T> make_arg_wrapper(const char* name, const T& value) {\n return {name, value};\n }\n\n static std::string render_type_name(const std::type_info& ti);\n\n class line_builder {\n public:\n line_builder();\n\n template <class T>\n line_builder& operator<<(const T& x) {\n if (!str_.empty())\n str_ += \" \";\n std::stringstream ss;\n ss << x;\n str_ += ss.str();\n behind_arg_ = false;\n return *this;\n }\n\n template <class T>\n line_builder& operator<<(const arg_wrapper<T>& x) {\n if (behind_arg_)\n str_ += \", \";\n else if (!str_.empty())\n str_ += \" \";\n str_ += x.name;\n str_ += \" = \";\n str_ += deep_to_string(x.value);\n behind_arg_ = true;\n return *this;\n }\n\n line_builder& operator<<(const std::string& str);\n\n line_builder& operator<<(const char* str);\n\n std::string get() const;\n\n private:\n std::string str_;\n bool behind_arg_;\n };\n\n static std::string extract_class_name(const char* prettyfun, size_t strsize);\n\n template <size_t N>\n static std::string extract_class_name(const char (&prettyfun)[N]) {\n return extract_class_name(prettyfun, N);\n }\n\n \/\/\/ Returns the ID of the actor currently associated to the calling thread.\n actor_id thread_local_aid();\n\n \/\/\/ Associates an actor ID to the calling thread and returns the last value.\n actor_id thread_local_aid(actor_id aid);\n\n \/\/\/ Writes an entry to the log file.\n void log(int level, const char* component, const std::string& class_name,\n const char* function_name, const char* file_name,\n int line_num, const std::string& msg);\n\n ~logger();\n\n \/** @cond PRIVATE *\/\n\n static void set_current_actor_system(actor_system*);\n\n static logger* current_logger();\n\n static void log_static(int level, const char* component,\n const std::string& class_name,\n const char* function_name,\n const char* file_name, int line_num,\n const std::string& msg);\n\n \/** @endcond *\/\n\nprivate:\n logger(actor_system& sys);\n\n void run();\n\n void start();\n\n void stop();\n\n actor_system& system_;\n int level_;\n detail::shared_spinlock aids_lock_;\n std::unordered_map<std::thread::id, actor_id> aids_;\n std::thread thread_;\n std::mutex queue_mtx_;\n std::condition_variable queue_cv_;\n detail::single_reader_queue<event> queue_;\n};\n\n} \/\/ namespace caf\n\n#define CAF_VOID_STMT static_cast<void>(0)\n\n#define CAF_CAT(a, b) a##b\n\n#define CAF_LOG_LEVEL_ERROR 0\n#define CAF_LOG_LEVEL_WARNING 1\n#define CAF_LOG_LEVEL_INFO 2\n#define CAF_LOG_LEVEL_DEBUG 3\n#define CAF_LOG_LEVEL_TRACE 4\n\n#define CAF_ARG(argument) caf::logger::make_arg_wrapper(#argument, argument)\n\n#ifdef CAF_MSVC\n#define CAF_GET_CLASS_NAME caf::logger::extract_class_name(__FUNCSIG__)\n#else \/\/ CAF_MSVC\n#define CAF_GET_CLASS_NAME caf::logger::extract_class_name(__PRETTY_FUNCTION__)\n#endif \/\/ CAF_MSVC\n\n#ifndef CAF_LOG_LEVEL\n\n#define CAF_LOG_IMPL(unused1, unused2)\n\n\/\/ placeholder macros when compiling without logging\ninline caf::actor_id caf_set_aid_dummy() { return 0; }\n\n#define CAF_PUSH_AID(unused) CAF_VOID_STMT\n\n#define CAF_PUSH_AID_FROM_PTR(unused) CAF_VOID_STMT\n\n#define CAF_SET_AID(unused) caf_set_aid_dummy()\n\n#define CAF_SET_LOGGER_SYS(unused) CAF_VOID_STMT\n\n#define CAF_LOG_TRACE(unused)\n\n#else \/\/ CAF_LOG_LEVEL\n\n#ifndef CAF_LOG_COMPONENT\n#define CAF_LOG_COMPONENT \"caf\"\n#endif\n\n#define CAF_LOG_IMPL(loglvl, message) \\\n caf::logger::log_static(loglvl, CAF_LOG_COMPONENT, CAF_GET_CLASS_NAME, \\\n __func__, __FILE__, __LINE__, \\\n (caf::logger::line_builder{} << message).get())\n\n#define CAF_PUSH_AID(aarg) \\\n auto CAF_UNIFYN(caf_tmp_ptr) = caf::logger::current_logger(); \\\n caf::actor_id CAF_UNIFYN(caf_aid_tmp) = 0; \\\n if (CAF_UNIFYN(caf_tmp_ptr)) \\\n CAF_UNIFYN(caf_aid_tmp) = CAF_UNIFYN(caf_tmp_ptr)->thread_local_aid(aarg); \\\n auto CAF_UNIFYN(aid_aid_tmp_guard) = caf::detail::make_scope_guard([=] { \\\n auto CAF_UNIFYN(caf_tmp2_ptr) = caf::logger::current_logger(); \\\n if (CAF_UNIFYN(caf_tmp2_ptr)) \\\n CAF_UNIFYN(caf_tmp2_ptr)->thread_local_aid(CAF_UNIFYN(caf_aid_tmp)); \\\n })\n\n#define CAF_PUSH_AID_FROM_PTR(some_ptr) \\\n auto CAF_UNIFYN(caf_aid_ptr) = some_ptr; \\\n CAF_PUSH_AID(CAF_UNIFYN(caf_aid_ptr) ? CAF_UNIFYN(caf_aid_ptr)->id() : 0)\n\n#define CAF_SET_AID(aid_arg) \\\n (caf::logger::current_logger() \\\n ? caf::logger::current_logger()->thread_local_aid(aid_arg) \\\n : 0)\n\n#define CAF_SET_LOGGER_SYS(ptr) caf::logger::set_current_actor_system(ptr)\n\n#if CAF_LOG_LEVEL < CAF_LOG_LEVEL_TRACE\n\n#define CAF_LOG_TRACE(unused) CAF_VOID_STMT\n\n#else \/\/ CAF_LOG_LEVEL < CAF_LOG_LEVEL_TRACE\n\n#define CAF_LOG_TRACE(entry_message) \\\n const char* CAF_UNIFYN(func_name_) = __func__; \\\n CAF_LOG_IMPL(CAF_LOG_LEVEL_TRACE, \"ENTRY\" << entry_message); \\\n auto CAF_UNIFYN(caf_log_trace_guard_) = ::caf::detail::make_scope_guard([=] {\\\n caf::logger::log_static(CAF_LOG_LEVEL_TRACE, CAF_LOG_COMPONENT, \\\n CAF_GET_CLASS_NAME, CAF_UNIFYN(func_name_), \\\n __FILE__, __LINE__, \"EXIT\"); \\\n })\n\n#endif \/\/ CAF_LOG_LEVEL < CAF_LOG_LEVEL_TRACE\n\n#if CAF_LOG_LEVEL >= CAF_LOG_LEVEL_DEBUG\n# define CAF_LOG_DEBUG(output) CAF_LOG_IMPL(CAF_LOG_LEVEL_DEBUG, output)\n#endif\n\n#if CAF_LOG_LEVEL >= CAF_LOG_LEVEL_INFO\n# define CAF_LOG_INFO(output) CAF_LOG_IMPL(CAF_LOG_LEVEL_INFO, output)\n#endif\n\n#if CAF_LOG_LEVEL >= CAF_LOG_LEVEL_WARNING\n# define CAF_LOG_WARNING(output) CAF_LOG_IMPL(CAF_LOG_LEVEL_WARNING, output)\n#endif\n\n#define CAF_LOG_ERROR(output) CAF_LOG_IMPL(CAF_LOG_LEVEL_ERROR, output)\n\n#endif \/\/ CAF_LOG_LEVEL\n\n#ifndef CAF_LOG_INFO\n# define CAF_LOG_INFO(output) CAF_VOID_STMT\n#endif\n\n#ifndef CAF_LOG_DEBUG\n# define CAF_LOG_DEBUG(output) CAF_VOID_STMT\n#endif\n\n#ifndef CAF_LOG_WARNING\n# define CAF_LOG_WARNING(output) CAF_VOID_STMT\n#endif\n\n#ifndef CAF_LOG_ERROR\n# define CAF_LOG_ERROR(output) CAF_VOID_STMT\n#endif\n\n#ifdef CAF_LOG_LEVEL\n\n#define CAF_LOG_DEBUG_IF(cond, output) \\\n if (cond) { CAF_LOG_IMPL(CAF_LOG_LEVEL_DEBUG, output); } CAF_VOID_STMT\n\n#define CAF_LOG_INFO_IF(cond, output) \\\n if (cond) { CAF_LOG_IMPL(CAF_LOG_LEVEL_INFO, output); } CAF_VOID_STMT\n\n#define CAF_LOG_WARNING_IF(cond, output) \\\n if (cond) { CAF_LOG_IMPL(CAF_LOG_LEVEL_WARNING, output); } CAF_VOID_STMT\n\n#define CAF_LOG_ERROR_IF(cond, output) \\\n if (cond) { CAF_LOG_IMPL(CAF_LOG_LEVEL_ERROR, output); } CAF_VOID_STMT\n\n#else \/\/ CAF_LOG_LEVEL\n\n#define CAF_LOG_DEBUG_IF(unused1, unused2)\n#define CAF_LOG_INFO_IF(unused1, unused2)\n#define CAF_LOG_WARNING_IF(unused1, unused2)\n#define CAF_LOG_ERROR_IF(unused1, unused2)\n\n#endif \/\/ CAF_LOG_LEVEL\n\n#endif \/\/ CAF_DETAIL_LOGGING_HPP\n<|endoftext|>"} {"text":"<commit_before>\/*===================================================================\n\nThe Medical Imaging Interaction Toolkit (MITK)\n\nCopyright (c) German Cancer Research Center,\nDivision of Medical and Biological Informatics.\nAll rights reserved.\n\nThis software is distributed WITHOUT ANY WARRANTY; without\neven the implied warranty of MERCHANTABILITY or FITNESS FOR\nA PARTICULAR PURPOSE.\n\nSee LICENSE.txt or http:\/\/www.mitk.org for details.\n\n===================================================================*\/\n\n#include <mitkCommon.h>\n#include <chrono>\n#include <mitkIOUtil.h>\n#include <mitkCommandLineParser.h>\n#include <mitkException.h>\n\n#include <mitkPhotoacousticFilterService.h>\n#include <mitkBeamformingSettings.h>\n#include <mitkCastToFloatImageFilter.h>\n\n#include <itksys\/SystemTools.hxx>\n#include <tinyxml\/tinyxml.h>\n\nstruct InputParameters\n{\n mitk::Image::Pointer inputImage;\n std::string outputFilename;\n bool verbose;\n std::string settingsFile;\n std::string imageType;\n};\n\nstruct BandpassSettings\n{\n float highPass;\n float lowPass;\n float alphaLow;\n float alphaHigh;\n float speedOfSound;\n};\n\nstruct CropSettings\n{\n int above;\n int below;\n int right;\n int left;\n int zStart;\n int zEnd;\n};\n\nstruct ResampleSettings\n{\n double spacing;\n unsigned int dimX;\n};\n\nstruct BModeSettings\n{\n mitk::PhotoacousticFilterService::BModeMethod method;\n bool UseLogFilter;\n};\n\nstruct ProcessSettings\n{\n bool DoBeamforming;\n bool DoBandpass;\n bool DoCropping;\n bool DoResampling;\n bool DoBmode;\n};\n\nInputParameters parseInput(int argc, char* argv[])\n{\n mitkCommandLineParser parser;\n parser.setCategory(\"MITK-Photoacoustics\");\n parser.setTitle(\"Mitk Photoacoustics Beamforming Tool\");\n parser.setDescription(\"Reads a nrrd file as an input and applies a beamforming method as set with the parameters defined in an additionally provided xml file.\");\n parser.setContributor(\"Computer Assisted Medical Interventions, DKFZ\");\n\n parser.setArgumentPrefix(\"--\", \"-\");\n\n parser.beginGroup(\"Required parameters\");\n parser.addArgument(\n \"inputImage\", \"i\", mitkCommandLineParser::Image,\n \"Input image (mitk::Image)\", \"input image (.nrrd file)\",\n us::Any(), false, false, false, mitkCommandLineParser::Input);\n parser.addArgument(\n \"output\", \"o\", mitkCommandLineParser::File,\n \"Output filename\", \"output image (.nrrd file)\",\n us::Any(), false, false, false, mitkCommandLineParser::Output);\n parser.addArgument(\n \"settings\", \"s\", mitkCommandLineParser::String,\n \"settings file\", \"file containing beamforming and other specifications(.xml file)\",\n us::Any(), false);\n parser.addArgument(\n \"type\", \"t\", mitkCommandLineParser::String,\n \"image type\", \"Specifies whether to use the PA or US subsection of the xml file must be 'PA' or 'US'\",\n us::Any(), false);\n parser.endGroup();\n\n parser.beginGroup(\"Optional parameters\");\n parser.addArgument(\n \"verbose\", \"v\", mitkCommandLineParser::Bool,\n \"Verbose Output\", \"Whether to produce verbose, or rather debug output. (default: false)\");\n parser.endGroup();\n\n InputParameters input;\n\n std::map<std::string, us::Any> parsedArgs = parser.parseArguments(argc, argv);\n if (parsedArgs.size() == 0)\n exit(-1);\n\n input.verbose = (bool)parsedArgs.count(\"verbose\");\n MITK_INFO(input.verbose) << \"### VERBOSE OUTPUT ENABLED ###\";\n\n if (parsedArgs.count(\"inputImage\"))\n {\n MITK_INFO(input.verbose) << \"Reading input image...\";\n input.inputImage = mitk::IOUtil::Load<mitk::Image>(us::any_cast<std::string>(parsedArgs[\"inputImage\"]));\n MITK_INFO(input.verbose) << \"Reading input image...[Done]\";\n }\n else\n mitkThrow() << \"No input image given.\";\n\n if (parsedArgs.count(\"output\"))\n input.outputFilename = us::any_cast<std::string>(parsedArgs[\"output\"]);\n else\n mitkThrow() << \"No output image path given..\";\n\n if (parsedArgs.count(\"settings\"))\n input.settingsFile = us::any_cast<std::string>(parsedArgs[\"settings\"]);\n else\n mitkThrow() << \"No settings image path given..\";\n\n if (parsedArgs.count(\"type\"))\n input.imageType = us::any_cast<std::string>(parsedArgs[\"type\"]);\n else\n mitkThrow() << \"No settings image type given..\";\n\n return input;\n}\n\nTiXmlElement* getRootChild(TiXmlElement* root, std::string childName)\n{\n for (TiXmlElement* elem = root->FirstChildElement(); elem != NULL; elem = elem->NextSiblingElement())\n {\n if (elem->Value() == childName)\n return elem;\n }\n return nullptr;\n}\n\nvoid ParseXML(std::string xmlFile, InputParameters input, mitk::BeamformingSettings::Pointer *bfSet, BandpassSettings& bandpassSet, CropSettings& cropSet, ResampleSettings& resSet, BModeSettings& bmodeSet, ProcessSettings& processSet)\n{\n MITK_INFO << \"Loading configuration File \\\"\" << xmlFile << \"\\\"\";\n TiXmlDocument doc(xmlFile);\n if (!doc.LoadFile())\n mitkThrow() << \"Failed to load settings file \\\"\" << xmlFile << \"\\\" Error: \" << doc.ErrorDesc();\n\n TiXmlElement* root = doc.FirstChildElement();\n if (root == NULL)\n {\n mitkThrow() << \"Failed to load file: No root element.\";\n doc.Clear();\n }\n\n TiXmlElement* elemtop = getRootChild(root, input.imageType);\n if(elemtop == nullptr)\n mitkThrow() << \"The xml file is wrongly formatted, no element \\\"\" << input.imageType << \"\\\" found\";\n\n for (TiXmlElement* elem = elemtop->FirstChildElement(); elem != NULL; elem = elem->NextSiblingElement())\n {\n std::string elemName = elem->Value();\n if (elemName == \"Beamforming\")\n {\n processSet.DoBeamforming = std::stoi(elem->Attribute(\"do\"));\n if (!processSet.DoBeamforming)\n continue;\n\n float SpeedOfSound = std::stof(elem->Attribute(\"speedOfSoundMeterPerSecond\"));\n float PitchMeter = std::stof(elem->Attribute(\"pitchMilliMeter\"))\/1000;\n float TimeSpacingMicroSecond = (float)(input.inputImage->GetGeometry()->GetSpacing()[1] \/ 1000000);\n\n if (std::stof(elem->Attribute(\"timeSpacingMicroSecond\")) > 0) {\n TimeSpacingMicroSecond = std::stof(elem->Attribute(\"timeSpacingMicroSecond\"));\n MITK_INFO << \"TIME: \" << TimeSpacingMicroSecond;\n }\n\n float Angle = std::stof(elem->Attribute(\"apodizationAngle\"));\n bool IsPhotoacousticImage = true;\n if (elem->Attribute(\"imageType\") == \"US\") {\n IsPhotoacousticImage = false;\n MITK_INFO << \"US IMAGE\";\n }\n\n unsigned int SamplesPerLine = std::stoi(elem->Attribute(\"reconstructedYDimension\"));\n unsigned int ReconstructionLines = std::stoi(elem->Attribute(\"reconstructedXDimension\"));\n\n\n float ReconstructionDepth = std::stof(elem->Attribute(\"reconstructionDepthMeter\"));\n bool UseGPU = std::stoi(elem->Attribute(\"useGPU\"));\n unsigned int GPUBatchSize = std::stoi(elem->Attribute(\"GPUBatchSize\"));\n\n std::string apodizationStr = elem->Attribute(\"apodizationFunction\");\n mitk::BeamformingSettings::Apodization Apodization = mitk::BeamformingSettings::Apodization::Box;\n if (apodizationStr == \"Box\")\n Apodization = mitk::BeamformingSettings::Apodization::Box;\n else if (apodizationStr == \"Hann\")\n Apodization = mitk::BeamformingSettings::Apodization::Hann;\n else if (apodizationStr == \"Hamm\")\n Apodization = mitk::BeamformingSettings::Apodization::Hamm;\n else\n mitkThrow() << \"Apodization incorrectly defined in settings\";\n\n std::string geomStr = elem->Attribute(\"probeGeometry\");\n mitk::BeamformingSettings::ProbeGeometry ProbeGeometry = mitk::BeamformingSettings::ProbeGeometry::Linear;\n if (geomStr == \"linear\")\n ProbeGeometry = mitk::BeamformingSettings::ProbeGeometry::Linear;\n else if(geomStr == \"concave\")\n ProbeGeometry = mitk::BeamformingSettings::ProbeGeometry::Concave;\n else\n mitkThrow() << \"geometry incorrectly defined in settings\";\n\n float radius = std::stof(elem->Attribute(\"radiusMilliMeter\"))\/1000;\n\n unsigned int ApodizationArraySize = ReconstructionLines;\n\n std::string algorithmStr = elem->Attribute(\"algorithm\");\n mitk::BeamformingSettings::BeamformingAlgorithm Algorithm = mitk::BeamformingSettings::BeamformingAlgorithm::DAS;\n if (algorithmStr == \"DAS\")\n Algorithm = mitk::BeamformingSettings::BeamformingAlgorithm::DAS;\n else if (algorithmStr == \"DMAS\")\n Algorithm = mitk::BeamformingSettings::BeamformingAlgorithm::DMAS;\n else if (algorithmStr == \"sDMAS\")\n Algorithm = mitk::BeamformingSettings::BeamformingAlgorithm::sDMAS;\n else\n mitkThrow() << \"Beamforming algorithm incorrectly defined in settings\";\n\n *bfSet = mitk::BeamformingSettings::New(\n PitchMeter,\n SpeedOfSound,\n TimeSpacingMicroSecond,\n Angle,\n IsPhotoacousticImage,\n SamplesPerLine,\n ReconstructionLines,\n input.inputImage->GetDimensions(),\n ReconstructionDepth,\n UseGPU,\n GPUBatchSize,\n Apodization,\n ApodizationArraySize,\n Algorithm,\n ProbeGeometry,\n radius\n );\n }\n if (elemName == \"Bandpass\")\n {\n processSet.DoBandpass = std::stoi(elem->Attribute(\"do\"));\n if (!processSet.DoBandpass)\n continue;\n\n bandpassSet.highPass = std::stof(elem->Attribute(\"highPass\"));\n bandpassSet.lowPass = std::stof(elem->Attribute(\"lowPass\"));\n bandpassSet.alphaLow = std::stof(elem->Attribute(\"alphaLow\"));\n bandpassSet.alphaHigh = std::stof(elem->Attribute(\"alphaHigh\"));\n }\n if (elemName == \"Cropping\")\n {\n processSet.DoCropping = std::stoi(elem->Attribute(\"do\"));\n if (!processSet.DoCropping)\n continue;\n\n cropSet.above = std::stoi(elem->Attribute(\"cutAbove\"));\n cropSet.below = std::stoi(elem->Attribute(\"cutBelow\"));\n cropSet.right = std::stoi(elem->Attribute(\"cutRight\"));\n cropSet.left = std::stoi(elem->Attribute(\"cutLeft\"));\n cropSet.zStart = std::stoi(elem->Attribute(\"firstSlice\"));\n cropSet.zEnd = std::stoi(elem->Attribute(\"cutSlices\"));\n }\n if (elemName == \"Resampling\")\n {\n processSet.DoResampling = std::stoi(elem->Attribute(\"do\"));\n if (!processSet.DoResampling)\n continue;\n\n resSet.spacing = std::stod(elem->Attribute(\"spacing\"));\n resSet.dimX = std::stoi(elem->Attribute(\"dimX\"));\n }\n if (elemName == \"BMode\")\n {\n processSet.DoBmode = std::stoi(elem->Attribute(\"do\"));\n if (!processSet.DoBmode)\n continue;\n\n std::string methodStr = elem->Attribute(\"method\");\n if (methodStr == \"EnvelopeDetection\")\n bmodeSet.method = mitk::PhotoacousticFilterService::BModeMethod::EnvelopeDetection;\n else if (methodStr == \"Abs\")\n bmodeSet.method = mitk::PhotoacousticFilterService::BModeMethod::Abs;\n else\n mitkThrow() << \"BMode method incorrectly set in configuration file\";\n bmodeSet.UseLogFilter = (bool)std::stoi(elem->Attribute(\"useLogFilter\"));\n }\n }\n}\n\nint main(int argc, char * argv[])\n{\n auto input = parseInput(argc, argv);\n\n mitk::BeamformingSettings::Pointer bfSettings;\n BandpassSettings bandpassSettings{5,10,1,1,1540};\n BModeSettings bmodeSettings{ mitk::PhotoacousticFilterService::BModeMethod::EnvelopeDetection, false };\n CropSettings cropSettings{ 0,0,0,0,0,0 };\n ResampleSettings resSettings{ 0.15 , 256};\n ProcessSettings processSettings{ false, false, false, false, false };\n\n MITK_INFO << \"Parsing settings XML...\";\n try\n {\n ParseXML(input.settingsFile, input, &bfSettings, bandpassSettings, cropSettings, resSettings, bmodeSettings, processSettings);\n }\n catch (mitk::Exception e)\n {\n MITK_INFO << e;\n return -1;\n }\n\n MITK_INFO << \"Parsing settings XML...[Done]\";\n\n MITK_INFO(input.verbose) << \"Beamforming input image...\";\n mitk::Image::Pointer inputImage = input.inputImage;\n if (!(inputImage->GetPixelType().GetTypeAsString() == \"scalar (float)\" || inputImage->GetPixelType().GetTypeAsString() == \" (float)\"))\n {\n \/\/ we need a float image, so cast it here\n MITK_INFO(input.verbose) << \"Casting input image to float...\";\n mitk::CastToFloatImageFilter::Pointer castFilter = mitk::CastToFloatImageFilter::New();\n castFilter->SetInput(inputImage);\n castFilter->Update();\n inputImage = castFilter->GetOutput();\n MITK_INFO << inputImage->GetPixelType().GetPixelTypeAsString();\n MITK_INFO(input.verbose) << \"Casting input image to float...[Done]\";\n }\n\n mitk::PhotoacousticFilterService::Pointer m_FilterService = mitk::PhotoacousticFilterService::New();\n\n mitk::Image::Pointer output = inputImage;\n if (processSettings.DoBandpass)\n {\n MITK_INFO(input.verbose) << \"Bandpassing input image...\";\n output = m_FilterService->ApplyBandpassFilter(output, bandpassSettings.highPass*1e6, bandpassSettings.lowPass*1e6, bandpassSettings.alphaHigh, bandpassSettings.alphaLow, 1, bandpassSettings.speedOfSound, true);\n MITK_INFO(input.verbose) << \"Bandpassing input image...[Done]\";\n }\n if (processSettings.DoBeamforming)\n {\n MITK_INFO(input.verbose) << \"Beamforming input image...\";\n output = m_FilterService->ApplyBeamforming(output, bfSettings);\n MITK_INFO(input.verbose) << \"Beamforming input image...[Done]\";\n }\n if (processSettings.DoCropping)\n {\n int err;\n MITK_INFO(input.verbose) << \"Applying Crop filter to image...\";\n output = m_FilterService->ApplyCropping(output,\n cropSettings.above, cropSettings.below, cropSettings.right, cropSettings.left, cropSettings.zStart, cropSettings.zEnd, &err);\n MITK_INFO(input.verbose) << \"Applying Crop filter to image...[Done]\";\n }\n if (processSettings.DoBmode)\n {\n MITK_INFO(input.verbose) << \"Applying BModeFilter to image...\";\n output = m_FilterService->ApplyBmodeFilter(output, bmodeSettings.method, bmodeSettings.UseLogFilter);\n MITK_INFO(input.verbose) << \"Applying BModeFilter to image...[Done]\";\n }\n if (processSettings.DoResampling)\n {\n double spacing[3] = { output->GetGeometry()->GetSpacing()[0] * output->GetDimension(0) \/ resSettings.dimX, resSettings.spacing, output->GetGeometry()->GetSpacing()[2] };\n MITK_INFO(input.verbose) << \"Applying Resample filter to image...\";\n output = m_FilterService->ApplyResampling(output, spacing);\n if (output->GetDimension(0) != resSettings.dimX)\n {\n double dim[3] = { (double)resSettings.dimX, (double)output->GetDimension(1), (double)output->GetDimension(2) };\n output = m_FilterService->ApplyResamplingToDim(output, dim);\n }\n MITK_INFO(input.verbose) << \"Applying Resample filter to image...[Done]\";\n }\n\n MITK_INFO(input.verbose) << \"Saving image...\";\n mitk::IOUtil::Save(output, input.outputFilename);\n MITK_INFO(input.verbose) << \"Saving image...[Done]\";\n\n MITK_INFO(input.verbose) << \"Beamforming input image...[Done]\";\n}\n<commit_msg>caused gcc warning<commit_after>\/*===================================================================\n\nThe Medical Imaging Interaction Toolkit (MITK)\n\nCopyright (c) German Cancer Research Center,\nDivision of Medical and Biological Informatics.\nAll rights reserved.\n\nThis software is distributed WITHOUT ANY WARRANTY; without\neven the implied warranty of MERCHANTABILITY or FITNESS FOR\nA PARTICULAR PURPOSE.\n\nSee LICENSE.txt or http:\/\/www.mitk.org for details.\n\n===================================================================*\/\n\n#include <mitkCommon.h>\n#include <chrono>\n#include <mitkIOUtil.h>\n#include <mitkCommandLineParser.h>\n#include <mitkException.h>\n\n#include <mitkPhotoacousticFilterService.h>\n#include <mitkBeamformingSettings.h>\n#include <mitkCastToFloatImageFilter.h>\n\n#include <itksys\/SystemTools.hxx>\n#include <tinyxml\/tinyxml.h>\n\nstruct InputParameters\n{\n mitk::Image::Pointer inputImage;\n std::string outputFilename;\n bool verbose;\n std::string settingsFile;\n std::string imageType;\n};\n\nstruct BandpassSettings\n{\n float highPass;\n float lowPass;\n float alphaLow;\n float alphaHigh;\n float speedOfSound;\n};\n\nstruct CropSettings\n{\n int above;\n int below;\n int right;\n int left;\n int zStart;\n int zEnd;\n};\n\nstruct ResampleSettings\n{\n double spacing;\n unsigned int dimX;\n};\n\nstruct BModeSettings\n{\n mitk::PhotoacousticFilterService::BModeMethod method;\n bool UseLogFilter;\n};\n\nstruct ProcessSettings\n{\n bool DoBeamforming;\n bool DoBandpass;\n bool DoCropping;\n bool DoResampling;\n bool DoBmode;\n};\n\nInputParameters parseInput(int argc, char* argv[])\n{\n mitkCommandLineParser parser;\n parser.setCategory(\"MITK-Photoacoustics\");\n parser.setTitle(\"Mitk Photoacoustics Beamforming Tool\");\n parser.setDescription(\"Reads a nrrd file as an input and applies a beamforming method as set with the parameters defined in an additionally provided xml file.\");\n parser.setContributor(\"Computer Assisted Medical Interventions, DKFZ\");\n\n parser.setArgumentPrefix(\"--\", \"-\");\n\n parser.beginGroup(\"Required parameters\");\n parser.addArgument(\n \"inputImage\", \"i\", mitkCommandLineParser::Image,\n \"Input image (mitk::Image)\", \"input image (.nrrd file)\",\n us::Any(), false, false, false, mitkCommandLineParser::Input);\n parser.addArgument(\n \"output\", \"o\", mitkCommandLineParser::File,\n \"Output filename\", \"output image (.nrrd file)\",\n us::Any(), false, false, false, mitkCommandLineParser::Output);\n parser.addArgument(\n \"settings\", \"s\", mitkCommandLineParser::String,\n \"settings file\", \"file containing beamforming and other specifications(.xml file)\",\n us::Any(), false);\n parser.addArgument(\n \"type\", \"t\", mitkCommandLineParser::String,\n \"image type\", \"Specifies whether to use the PA or US subsection of the xml file must be 'PA' or 'US'\",\n us::Any(), false);\n parser.endGroup();\n\n parser.beginGroup(\"Optional parameters\");\n parser.addArgument(\n \"verbose\", \"v\", mitkCommandLineParser::Bool,\n \"Verbose Output\", \"Whether to produce verbose, or rather debug output. (default: false)\");\n parser.endGroup();\n\n InputParameters input;\n\n std::map<std::string, us::Any> parsedArgs = parser.parseArguments(argc, argv);\n if (parsedArgs.size() == 0)\n exit(-1);\n\n input.verbose = (bool)parsedArgs.count(\"verbose\");\n MITK_INFO(input.verbose) << \"### VERBOSE OUTPUT ENABLED ###\";\n\n if (parsedArgs.count(\"inputImage\"))\n {\n MITK_INFO(input.verbose) << \"Reading input image...\";\n input.inputImage = mitk::IOUtil::Load<mitk::Image>(us::any_cast<std::string>(parsedArgs[\"inputImage\"]));\n MITK_INFO(input.verbose) << \"Reading input image...[Done]\";\n }\n else\n mitkThrow() << \"No input image given.\";\n\n if (parsedArgs.count(\"output\"))\n input.outputFilename = us::any_cast<std::string>(parsedArgs[\"output\"]);\n else\n mitkThrow() << \"No output image path given..\";\n\n if (parsedArgs.count(\"settings\"))\n input.settingsFile = us::any_cast<std::string>(parsedArgs[\"settings\"]);\n else\n mitkThrow() << \"No settings image path given..\";\n\n if (parsedArgs.count(\"type\"))\n input.imageType = us::any_cast<std::string>(parsedArgs[\"type\"]);\n else\n mitkThrow() << \"No settings image type given..\";\n\n return input;\n}\n\nTiXmlElement* getRootChild(TiXmlElement* root, std::string childName)\n{\n for (TiXmlElement* elem = root->FirstChildElement(); elem != NULL; elem = elem->NextSiblingElement())\n {\n if (elem->Value() == childName)\n return elem;\n }\n return nullptr;\n}\n\nvoid ParseXML(std::string xmlFile, InputParameters input, mitk::BeamformingSettings::Pointer *bfSet, BandpassSettings& bandpassSet, CropSettings& cropSet, ResampleSettings& resSet, BModeSettings& bmodeSet, ProcessSettings& processSet)\n{\n MITK_INFO << \"Loading configuration File \\\"\" << xmlFile << \"\\\"\";\n TiXmlDocument doc(xmlFile);\n if (!doc.LoadFile())\n mitkThrow() << \"Failed to load settings file \\\"\" << xmlFile << \"\\\" Error: \" << doc.ErrorDesc();\n\n TiXmlElement* root = doc.FirstChildElement();\n if (root == NULL)\n {\n mitkThrow() << \"Failed to load file: No root element.\";\n doc.Clear();\n }\n\n TiXmlElement* elemtop = getRootChild(root, input.imageType);\n if(elemtop == nullptr)\n mitkThrow() << \"The xml file is wrongly formatted, no element \\\"\" << input.imageType << \"\\\" found\";\n\n for (TiXmlElement* elem = elemtop->FirstChildElement(); elem != NULL; elem = elem->NextSiblingElement())\n {\n std::string elemName = elem->Value();\n if (elemName == \"Beamforming\")\n {\n processSet.DoBeamforming = std::stoi(elem->Attribute(\"do\"));\n if (!processSet.DoBeamforming)\n continue;\n\n float SpeedOfSound = std::stof(elem->Attribute(\"speedOfSoundMeterPerSecond\"));\n float PitchMeter = std::stof(elem->Attribute(\"pitchMilliMeter\"))\/1000;\n float TimeSpacingMicroSecond = (float)(input.inputImage->GetGeometry()->GetSpacing()[1] \/ 1000000);\n\n if (std::stof(elem->Attribute(\"timeSpacingMicroSecond\")) > 0) {\n TimeSpacingMicroSecond = std::stof(elem->Attribute(\"timeSpacingMicroSecond\"));\n MITK_INFO << \"TIME: \" << TimeSpacingMicroSecond;\n }\n\n float Angle = std::stof(elem->Attribute(\"apodizationAngle\"));\n bool IsPhotoacousticImage = true;\n if (std::string(elem->Attribute(\"imageType\")).compare(\"US\") == 0) {\n IsPhotoacousticImage = false;\n MITK_INFO << \"US IMAGE\";\n }\n\n unsigned int SamplesPerLine = std::stoi(elem->Attribute(\"reconstructedYDimension\"));\n unsigned int ReconstructionLines = std::stoi(elem->Attribute(\"reconstructedXDimension\"));\n\n\n float ReconstructionDepth = std::stof(elem->Attribute(\"reconstructionDepthMeter\"));\n bool UseGPU = std::stoi(elem->Attribute(\"useGPU\"));\n unsigned int GPUBatchSize = std::stoi(elem->Attribute(\"GPUBatchSize\"));\n\n std::string apodizationStr = elem->Attribute(\"apodizationFunction\");\n mitk::BeamformingSettings::Apodization Apodization = mitk::BeamformingSettings::Apodization::Box;\n if (apodizationStr == \"Box\")\n Apodization = mitk::BeamformingSettings::Apodization::Box;\n else if (apodizationStr == \"Hann\")\n Apodization = mitk::BeamformingSettings::Apodization::Hann;\n else if (apodizationStr == \"Hamm\")\n Apodization = mitk::BeamformingSettings::Apodization::Hamm;\n else\n mitkThrow() << \"Apodization incorrectly defined in settings\";\n\n std::string geomStr = elem->Attribute(\"probeGeometry\");\n mitk::BeamformingSettings::ProbeGeometry ProbeGeometry = mitk::BeamformingSettings::ProbeGeometry::Linear;\n if (geomStr == \"linear\")\n ProbeGeometry = mitk::BeamformingSettings::ProbeGeometry::Linear;\n else if(geomStr == \"concave\")\n ProbeGeometry = mitk::BeamformingSettings::ProbeGeometry::Concave;\n else\n mitkThrow() << \"geometry incorrectly defined in settings\";\n\n float radius = std::stof(elem->Attribute(\"radiusMilliMeter\"))\/1000;\n\n unsigned int ApodizationArraySize = ReconstructionLines;\n\n std::string algorithmStr = elem->Attribute(\"algorithm\");\n mitk::BeamformingSettings::BeamformingAlgorithm Algorithm = mitk::BeamformingSettings::BeamformingAlgorithm::DAS;\n if (algorithmStr == \"DAS\")\n Algorithm = mitk::BeamformingSettings::BeamformingAlgorithm::DAS;\n else if (algorithmStr == \"DMAS\")\n Algorithm = mitk::BeamformingSettings::BeamformingAlgorithm::DMAS;\n else if (algorithmStr == \"sDMAS\")\n Algorithm = mitk::BeamformingSettings::BeamformingAlgorithm::sDMAS;\n else\n mitkThrow() << \"Beamforming algorithm incorrectly defined in settings\";\n\n *bfSet = mitk::BeamformingSettings::New(\n PitchMeter,\n SpeedOfSound,\n TimeSpacingMicroSecond,\n Angle,\n IsPhotoacousticImage,\n SamplesPerLine,\n ReconstructionLines,\n input.inputImage->GetDimensions(),\n ReconstructionDepth,\n UseGPU,\n GPUBatchSize,\n Apodization,\n ApodizationArraySize,\n Algorithm,\n ProbeGeometry,\n radius\n );\n }\n if (elemName == \"Bandpass\")\n {\n processSet.DoBandpass = std::stoi(elem->Attribute(\"do\"));\n if (!processSet.DoBandpass)\n continue;\n\n bandpassSet.highPass = std::stof(elem->Attribute(\"highPass\"));\n bandpassSet.lowPass = std::stof(elem->Attribute(\"lowPass\"));\n bandpassSet.alphaLow = std::stof(elem->Attribute(\"alphaLow\"));\n bandpassSet.alphaHigh = std::stof(elem->Attribute(\"alphaHigh\"));\n }\n if (elemName == \"Cropping\")\n {\n processSet.DoCropping = std::stoi(elem->Attribute(\"do\"));\n if (!processSet.DoCropping)\n continue;\n\n cropSet.above = std::stoi(elem->Attribute(\"cutAbove\"));\n cropSet.below = std::stoi(elem->Attribute(\"cutBelow\"));\n cropSet.right = std::stoi(elem->Attribute(\"cutRight\"));\n cropSet.left = std::stoi(elem->Attribute(\"cutLeft\"));\n cropSet.zStart = std::stoi(elem->Attribute(\"firstSlice\"));\n cropSet.zEnd = std::stoi(elem->Attribute(\"cutSlices\"));\n }\n if (elemName == \"Resampling\")\n {\n processSet.DoResampling = std::stoi(elem->Attribute(\"do\"));\n if (!processSet.DoResampling)\n continue;\n\n resSet.spacing = std::stod(elem->Attribute(\"spacing\"));\n resSet.dimX = std::stoi(elem->Attribute(\"dimX\"));\n }\n if (elemName == \"BMode\")\n {\n processSet.DoBmode = std::stoi(elem->Attribute(\"do\"));\n if (!processSet.DoBmode)\n continue;\n\n std::string methodStr = elem->Attribute(\"method\");\n if (methodStr == \"EnvelopeDetection\")\n bmodeSet.method = mitk::PhotoacousticFilterService::BModeMethod::EnvelopeDetection;\n else if (methodStr == \"Abs\")\n bmodeSet.method = mitk::PhotoacousticFilterService::BModeMethod::Abs;\n else\n mitkThrow() << \"BMode method incorrectly set in configuration file\";\n bmodeSet.UseLogFilter = (bool)std::stoi(elem->Attribute(\"useLogFilter\"));\n }\n }\n}\n\nint main(int argc, char * argv[])\n{\n auto input = parseInput(argc, argv);\n\n mitk::BeamformingSettings::Pointer bfSettings;\n BandpassSettings bandpassSettings{5,10,1,1,1540};\n BModeSettings bmodeSettings{ mitk::PhotoacousticFilterService::BModeMethod::EnvelopeDetection, false };\n CropSettings cropSettings{ 0,0,0,0,0,0 };\n ResampleSettings resSettings{ 0.15 , 256};\n ProcessSettings processSettings{ false, false, false, false, false };\n\n MITK_INFO << \"Parsing settings XML...\";\n try\n {\n ParseXML(input.settingsFile, input, &bfSettings, bandpassSettings, cropSettings, resSettings, bmodeSettings, processSettings);\n }\n catch (mitk::Exception e)\n {\n MITK_INFO << e;\n return -1;\n }\n\n MITK_INFO << \"Parsing settings XML...[Done]\";\n\n MITK_INFO(input.verbose) << \"Beamforming input image...\";\n mitk::Image::Pointer inputImage = input.inputImage;\n if (!(inputImage->GetPixelType().GetTypeAsString() == \"scalar (float)\" || inputImage->GetPixelType().GetTypeAsString() == \" (float)\"))\n {\n \/\/ we need a float image, so cast it here\n MITK_INFO(input.verbose) << \"Casting input image to float...\";\n mitk::CastToFloatImageFilter::Pointer castFilter = mitk::CastToFloatImageFilter::New();\n castFilter->SetInput(inputImage);\n castFilter->Update();\n inputImage = castFilter->GetOutput();\n MITK_INFO << inputImage->GetPixelType().GetPixelTypeAsString();\n MITK_INFO(input.verbose) << \"Casting input image to float...[Done]\";\n }\n\n mitk::PhotoacousticFilterService::Pointer m_FilterService = mitk::PhotoacousticFilterService::New();\n\n mitk::Image::Pointer output = inputImage;\n if (processSettings.DoBandpass)\n {\n MITK_INFO(input.verbose) << \"Bandpassing input image...\";\n output = m_FilterService->ApplyBandpassFilter(output, bandpassSettings.highPass*1e6, bandpassSettings.lowPass*1e6, bandpassSettings.alphaHigh, bandpassSettings.alphaLow, 1, bandpassSettings.speedOfSound, true);\n MITK_INFO(input.verbose) << \"Bandpassing input image...[Done]\";\n }\n if (processSettings.DoBeamforming)\n {\n MITK_INFO(input.verbose) << \"Beamforming input image...\";\n output = m_FilterService->ApplyBeamforming(output, bfSettings);\n MITK_INFO(input.verbose) << \"Beamforming input image...[Done]\";\n }\n if (processSettings.DoCropping)\n {\n int err;\n MITK_INFO(input.verbose) << \"Applying Crop filter to image...\";\n output = m_FilterService->ApplyCropping(output,\n cropSettings.above, cropSettings.below, cropSettings.right, cropSettings.left, cropSettings.zStart, cropSettings.zEnd, &err);\n MITK_INFO(input.verbose) << \"Applying Crop filter to image...[Done]\";\n }\n if (processSettings.DoBmode)\n {\n MITK_INFO(input.verbose) << \"Applying BModeFilter to image...\";\n output = m_FilterService->ApplyBmodeFilter(output, bmodeSettings.method, bmodeSettings.UseLogFilter);\n MITK_INFO(input.verbose) << \"Applying BModeFilter to image...[Done]\";\n }\n if (processSettings.DoResampling)\n {\n double spacing[3] = { output->GetGeometry()->GetSpacing()[0] * output->GetDimension(0) \/ resSettings.dimX, resSettings.spacing, output->GetGeometry()->GetSpacing()[2] };\n MITK_INFO(input.verbose) << \"Applying Resample filter to image...\";\n output = m_FilterService->ApplyResampling(output, spacing);\n if (output->GetDimension(0) != resSettings.dimX)\n {\n double dim[3] = { (double)resSettings.dimX, (double)output->GetDimension(1), (double)output->GetDimension(2) };\n output = m_FilterService->ApplyResamplingToDim(output, dim);\n }\n MITK_INFO(input.verbose) << \"Applying Resample filter to image...[Done]\";\n }\n\n MITK_INFO(input.verbose) << \"Saving image...\";\n mitk::IOUtil::Save(output, input.outputFilename);\n MITK_INFO(input.verbose) << \"Saving image...[Done]\";\n\n MITK_INFO(input.verbose) << \"Beamforming input image...[Done]\";\n}\n<|endoftext|>"} {"text":"<commit_before>\/* -*- C++ -*-; c-basic-offset: 4; indent-tabs-mode: nil *\/\n\/*\n * Implementation for Mutator class.\n *\n * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.\n *\n * This program and the accompanying materials are made available under the\n * terms of the Eclipse Public License v1.0 which accompanies this distribution,\n * and is available at http:\/\/www.eclipse.org\/legal\/epl-v10.html\n *\/\n\n#include <utility>\n#include <stdexcept>\n\n#include <boost\/unordered_map.hpp>\n#include <boost\/unordered_set.hpp>\n#include <boost\/shared_ptr.hpp>\n#include <boost\/make_shared.hpp>\n\n#include \"opflex\/ofcore\/OFFramework.h\"\n#include \"opflex\/modb\/Mutator.h\"\n#include \"opflex\/modb\/mo-internal\/StoreClient.h\"\n#include \"opflex\/modb\/internal\/ObjectStore.h\"\n\nnamespace opflex {\nnamespace modb {\n\nusing boost::unordered_map;\nusing boost::unordered_set;\nusing boost::shared_ptr;\nusing boost::make_shared;\nusing std::pair;\nusing std::make_pair;\n\nusing mointernal::StoreClient;\nusing mointernal::ObjectInstance;\n\ntypedef unordered_set<pair<class_id_t, URI> > uri_set_t;\ntypedef unordered_map<prop_id_t, uri_set_t> prop_uri_map_t;\ntypedef unordered_map<pair<class_id_t, URI>, prop_uri_map_t> uri_prop_uri_map_t;\ntypedef unordered_map<URI, shared_ptr<ObjectInstance> > obj_map_t;\n\nclass Mutator::MutatorImpl {\npublic:\n MutatorImpl(ofcore::OFFramework& framework_,\n const std::string& owner)\n : framework(framework_),\n client(framework.getStore().getStoreClient(owner)) { }\n MutatorImpl(const std::string& owner)\n : framework(ofcore::OFFramework::defaultInstance()),\n client(framework.getStore().getStoreClient(owner)) { }\n\n ofcore::OFFramework& framework;\n StoreClient& client;\n\n \/\/ modified objects\n obj_map_t obj_map;\n \n \/\/ removed objects\n unordered_set<pair<class_id_t, URI> > removed_objects;\n\n \/\/ added children\n uri_prop_uri_map_t added_children;\n};\n\n\/**\n * Compute a hash value for a class_id\/URI pair, making it suitable as\n * a key in an unordered_map\n *\/\nsize_t hash_value(pair<class_id_t, URI> const& p) {\n std::size_t seed = 0;\n boost::hash_combine(seed, p.first);\n boost::hash_combine(seed, p.second);\n return seed;\n}\n\nMutator::Mutator(const std::string& owner) \n : pimpl(new MutatorImpl(owner)) {\n pimpl->framework.registerTLMutator(*this);\n}\n\nMutator::Mutator(ofcore::OFFramework& framework, \n const std::string& owner) \n : pimpl(new MutatorImpl(framework, owner)) {\n pimpl->framework.registerTLMutator(*this);\n}\n\nMutator::~Mutator() {\n pimpl->framework.clearTLMutator();\n delete pimpl;\n}\n\nshared_ptr<ObjectInstance>& Mutator::addChild(class_id_t parent_class,\n const URI& parent_uri, \n prop_id_t parent_prop,\n class_id_t child_class,\n const URI& child_uri) {\n pimpl->added_children\n [make_pair(child_class,child_uri)]\n [parent_prop].insert(make_pair(parent_class,parent_uri));\n return modify(child_class, child_uri);\n}\n\nshared_ptr<ObjectInstance>& Mutator::modify(class_id_t class_id,\n const URI& uri) {\n \/\/ check for copy in mutator\n obj_map_t::iterator it = pimpl->obj_map.find(uri);\n if (it != pimpl->obj_map.end()) return it->second;\n shared_ptr<ObjectInstance> copy;\n try {\n \/\/ check for existing object\n copy = make_shared<ObjectInstance>(*pimpl->client.get(class_id,\n uri).get());\n } catch (std::out_of_range e) {\n \/\/ create new object\n copy = make_shared<ObjectInstance>(class_id);\n }\n\n pair<obj_map_t::iterator, bool> r = \n pimpl->obj_map.insert(obj_map_t::value_type(uri, copy));\n return r.first->second;\n}\n\nvoid Mutator::remove(class_id_t class_id, const URI& uri) {\n pimpl->removed_objects.insert(make_pair(class_id, uri));\n}\n\nvoid Mutator::commit() {\n unordered_map<URI, class_id_t> notifs;\n obj_map_t::iterator objit;\n for (objit = pimpl->obj_map.begin(); \n objit != pimpl->obj_map.end(); ++objit) {\n pimpl->client.put(objit->second->getClassId(), objit->first, \n objit->second);\n pimpl->client.queueNotification(objit->second->getClassId(),\n objit->first,\n notifs);\n }\n uri_prop_uri_map_t::iterator upit;\n for (upit = pimpl->added_children.begin(); \n upit != pimpl->added_children.end(); ++upit) {\n prop_uri_map_t::iterator pit;\n for (pit = upit->second.begin(); pit != upit->second.end(); ++pit) {\n uri_set_t::iterator uit;\n for (uit = pit->second.begin(); uit != pit->second.end(); ++uit) {\n pimpl->client.addChild(uit->first, uit->second, pit->first,\n upit->first.first, upit->first.second);\n pimpl->client.queueNotification(upit->first.first,\n upit->first.second,\n notifs);\n\n }\n }\n\n }\n unordered_set<pair<class_id_t, URI> >::iterator rit;\n for (rit = pimpl->removed_objects.begin(); \n rit != pimpl->removed_objects.end(); ++rit) {\n pimpl->client.remove(rit->first, rit->second, false);\n pimpl->client.queueNotification(rit->first, rit->second, notifs);\n }\n\n pimpl->obj_map.clear();\n pimpl->removed_objects.clear();\n pimpl->added_children.clear();\n\n pimpl->client.deliverNotifications(notifs);\n}\n\n} \/* namespace modb *\/\n} \/* namespace opflex *\/\n<commit_msg>Simplify mutator commit code with foreach. Fix issue with delivery of notifications when the data is committed out of order.<commit_after>\/* -*- C++ -*-; c-basic-offset: 4; indent-tabs-mode: nil *\/\n\/*\n * Implementation for Mutator class.\n *\n * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.\n *\n * This program and the accompanying materials are made available under the\n * terms of the Eclipse Public License v1.0 which accompanies this distribution,\n * and is available at http:\/\/www.eclipse.org\/legal\/epl-v10.html\n *\/\n\n#include <utility>\n#include <stdexcept>\n\n#include <boost\/unordered_map.hpp>\n#include <boost\/unordered_set.hpp>\n#include <boost\/shared_ptr.hpp>\n#include <boost\/make_shared.hpp>\n#include <boost\/foreach.hpp>\n\n#include \"opflex\/ofcore\/OFFramework.h\"\n#include \"opflex\/modb\/Mutator.h\"\n#include \"opflex\/modb\/mo-internal\/StoreClient.h\"\n#include \"opflex\/modb\/internal\/ObjectStore.h\"\n#include \"opflex\/logging\/internal\/logging.hpp\"\n\nnamespace opflex {\nnamespace modb {\n\nusing boost::unordered_map;\nusing boost::unordered_set;\nusing boost::shared_ptr;\nusing boost::make_shared;\nusing std::pair;\nusing std::make_pair;\n\nusing mointernal::StoreClient;\nusing mointernal::ObjectInstance;\n\ntypedef unordered_set<reference_t > uri_set_t;\ntypedef unordered_map<prop_id_t, uri_set_t> prop_uri_map_t;\ntypedef unordered_map<reference_t, prop_uri_map_t> uri_prop_uri_map_t;\ntypedef unordered_map<URI, shared_ptr<ObjectInstance> > obj_map_t;\n\nclass Mutator::MutatorImpl {\npublic:\n MutatorImpl(ofcore::OFFramework& framework_,\n const std::string& owner)\n : framework(framework_),\n client(framework.getStore().getStoreClient(owner)) { }\n MutatorImpl(const std::string& owner)\n : framework(ofcore::OFFramework::defaultInstance()),\n client(framework.getStore().getStoreClient(owner)) { }\n\n ofcore::OFFramework& framework;\n StoreClient& client;\n\n \/\/ modified objects\n obj_map_t obj_map;\n \n \/\/ removed objects\n unordered_set<pair<class_id_t, URI> > removed_objects;\n\n \/\/ added children\n uri_prop_uri_map_t added_children;\n};\n\n\/**\n * Compute a hash value for a class_id\/URI pair, making it suitable as\n * a key in an unordered_map\n *\/\nsize_t hash_value(pair<class_id_t, URI> const& p) {\n std::size_t seed = 0;\n boost::hash_combine(seed, p.first);\n boost::hash_combine(seed, p.second);\n return seed;\n}\n\nMutator::Mutator(const std::string& owner) \n : pimpl(new MutatorImpl(owner)) {\n pimpl->framework.registerTLMutator(*this);\n}\n\nMutator::Mutator(ofcore::OFFramework& framework, \n const std::string& owner) \n : pimpl(new MutatorImpl(framework, owner)) {\n pimpl->framework.registerTLMutator(*this);\n}\n\nMutator::~Mutator() {\n pimpl->framework.clearTLMutator();\n delete pimpl;\n}\n\nshared_ptr<ObjectInstance>& Mutator::addChild(class_id_t parent_class,\n const URI& parent_uri, \n prop_id_t parent_prop,\n class_id_t child_class,\n const URI& child_uri) {\n pimpl->added_children\n [make_pair(child_class,child_uri)]\n [parent_prop].insert(make_pair(parent_class,parent_uri));\n return modify(child_class, child_uri);\n}\n\nshared_ptr<ObjectInstance>& Mutator::modify(class_id_t class_id,\n const URI& uri) {\n \/\/ check for copy in mutator\n obj_map_t::iterator it = pimpl->obj_map.find(uri);\n if (it != pimpl->obj_map.end()) return it->second;\n shared_ptr<ObjectInstance> copy;\n try {\n \/\/ check for existing object\n copy = make_shared<ObjectInstance>(*pimpl->client.get(class_id,\n uri).get());\n } catch (std::out_of_range e) {\n \/\/ create new object\n copy = make_shared<ObjectInstance>(class_id);\n }\n\n pair<obj_map_t::iterator, bool> r = \n pimpl->obj_map.insert(obj_map_t::value_type(uri, copy));\n return r.first->second;\n}\n\nvoid Mutator::remove(class_id_t class_id, const URI& uri) {\n pimpl->removed_objects.insert(make_pair(class_id, uri));\n}\n\nvoid Mutator::commit() {\n StoreClient::notif_t raw_notifs;\n StoreClient::notif_t notifs;\n BOOST_FOREACH(obj_map_t::value_type& objt, pimpl->obj_map) {\n pimpl->client.put(objt.second->getClassId(), objt.first, \n objt.second);\n raw_notifs[objt.first] = objt.second->getClassId();\n\n }\n BOOST_FOREACH(uri_prop_uri_map_t::value_type& upt, pimpl->added_children) {\n BOOST_FOREACH(prop_uri_map_t::value_type& pt, upt.second) {\n BOOST_FOREACH(const reference_t& ut, pt.second) {\n raw_notifs[upt.first.second] = upt.first.first;\n pimpl->client.addChild(ut.first, ut.second, pt.first,\n upt.first.first, upt.first.second);\n\n }\n }\n }\n\n BOOST_FOREACH(StoreClient::notif_t::value_type nt, raw_notifs) {\n pimpl->client.queueNotification(nt.second, nt.first, notifs);\n }\n\n BOOST_FOREACH(const reference_t& rt, pimpl->removed_objects) {\n pimpl->client.remove(rt.first, rt.second, false);\n pimpl->client.queueNotification(rt.first, rt.second, notifs);\n }\n\n pimpl->obj_map.clear();\n pimpl->removed_objects.clear();\n pimpl->added_children.clear();\n\n pimpl->client.deliverNotifications(notifs);\n}\n\n} \/* namespace modb *\/\n} \/* namespace opflex *\/\n<|endoftext|>"} {"text":"<commit_before>\/\/===- AsmLexer.cpp - Lexer for Assembly Files ----------------------------===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This class implements the lexer for assembly files.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"AsmLexer.h\"\n#include \"llvm\/Support\/SourceMgr.h\"\n#include \"llvm\/Support\/MemoryBuffer.h\"\n#include <cerrno>\n#include <cstdio>\n#include <cstdlib>\nusing namespace llvm;\n\nAsmLexer::AsmLexer(SourceMgr &SM) : SrcMgr(SM) {\n CurBuffer = 0;\n CurBuf = SrcMgr.getMemoryBuffer(CurBuffer);\n CurPtr = CurBuf->getBufferStart();\n TokStart = 0;\n}\n\nSMLoc AsmLexer::getLoc() const {\n return SMLoc::getFromPointer(TokStart);\n}\n\nvoid AsmLexer::PrintMessage(SMLoc Loc, const std::string &Msg) const {\n SrcMgr.PrintMessage(Loc, Msg);\n}\n\n\/\/\/ ReturnError - Set the error to the specified string at the specified\n\/\/\/ location. This is defined to always return asmtok::Error.\nasmtok::TokKind AsmLexer::ReturnError(const char *Loc, const std::string &Msg) {\n SrcMgr.PrintMessage(SMLoc::getFromPointer(Loc), Msg);\n return asmtok::Error;\n}\n\nint AsmLexer::getNextChar() {\n char CurChar = *CurPtr++;\n switch (CurChar) {\n default:\n return (unsigned char)CurChar;\n case 0: {\n \/\/ A nul character in the stream is either the end of the current buffer or\n \/\/ a random nul in the file. Disambiguate that here.\n if (CurPtr-1 != CurBuf->getBufferEnd())\n return 0; \/\/ Just whitespace.\n \n \/\/ If this is the end of an included file, pop the parent file off the\n \/\/ include stack.\n SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);\n if (ParentIncludeLoc != SMLoc()) {\n CurBuffer = SrcMgr.FindBufferContainingLoc(ParentIncludeLoc);\n CurBuf = SrcMgr.getMemoryBuffer(CurBuffer);\n CurPtr = ParentIncludeLoc.getPointer();\n return getNextChar();\n }\n \n \/\/ Otherwise, return end of file.\n --CurPtr; \/\/ Another call to lex will return EOF again. \n return EOF;\n }\n }\n}\n\n\/\/\/ LexIdentifier: [a-zA-Z_.][a-zA-Z0-9_$.@]*\nasmtok::TokKind AsmLexer::LexIdentifier() {\n while (isalnum(*CurPtr) || *CurPtr == '_' || *CurPtr == '$' ||\n *CurPtr == '.' || *CurPtr == '@')\n ++CurPtr;\n CurStrVal.assign(TokStart, CurPtr); \/\/ Include %\n return asmtok::Identifier;\n}\n\n\/\/\/ LexPercent: Register: %[a-zA-Z0-9]+\nasmtok::TokKind AsmLexer::LexPercent() {\n if (!isalnum(*CurPtr))\n return ReturnError(TokStart, \"invalid register name\");\n while (isalnum(*CurPtr))\n ++CurPtr;\n CurStrVal.assign(TokStart, CurPtr); \/\/ Skip %\n return asmtok::Register;\n}\n\n\/\/\/ LexSlash: Slash: \/\n\/\/\/ C-Style Comment: \/* ... *\/\nasmtok::TokKind AsmLexer::LexSlash() {\n if (*CurPtr != '*')\n return asmtok::Slash;\n\n \/\/ C Style comment.\n ++CurPtr; \/\/ skip the star.\n while (1) {\n int CurChar = getNextChar();\n switch (CurChar) {\n case EOF:\n return ReturnError(TokStart, \"unterminated comment\");\n case '*':\n \/\/ End of the comment?\n if (CurPtr[0] != '\/') break;\n \n ++CurPtr; \/\/ End the *\/.\n return LexToken();\n }\n }\n}\n\n\/\/\/ LexHash: Comment: #[^\\n]*\nasmtok::TokKind AsmLexer::LexHash() {\n int CurChar = getNextChar();\n while (CurChar != '\\n' && CurChar != '\\n' && CurChar != EOF)\n CurChar = getNextChar();\n \n if (CurChar == EOF)\n return asmtok::Eof;\n return asmtok::EndOfStatement;\n}\n\n\n\/\/\/ LexDigit: First character is [0-9].\n\/\/\/ Local Label: [0-9][:]\n\/\/\/ Forward\/Backward Label: [0-9][fb]\n\/\/\/ Binary integer: 0b[01]+\n\/\/\/ Octal integer: 0[0-7]+\n\/\/\/ Hex integer: 0x[0-9a-fA-F]+\n\/\/\/ Decimal integer: [1-9][0-9]*\n\/\/\/ TODO: FP literal.\nasmtok::TokKind AsmLexer::LexDigit() {\n if (*CurPtr == ':')\n return ReturnError(TokStart, \"FIXME: local label not implemented\");\n if (*CurPtr == 'f' || *CurPtr == 'b')\n return ReturnError(TokStart, \"FIXME: directional label not implemented\");\n \n \/\/ Decimal integer: [1-9][0-9]*\n if (CurPtr[-1] != '0') {\n while (isdigit(*CurPtr))\n ++CurPtr;\n CurIntVal = strtoll(TokStart, 0, 10);\n return asmtok::IntVal;\n }\n \n if (*CurPtr == 'b') {\n ++CurPtr;\n const char *NumStart = CurPtr;\n while (CurPtr[0] == '0' || CurPtr[0] == '1')\n ++CurPtr;\n \n \/\/ Requires at least one binary digit.\n if (CurPtr == NumStart)\n return ReturnError(CurPtr-2, \"Invalid binary number\");\n CurIntVal = strtoll(NumStart, 0, 2);\n return asmtok::IntVal;\n }\n \n if (*CurPtr == 'x') {\n ++CurPtr;\n const char *NumStart = CurPtr;\n while (isxdigit(CurPtr[0]))\n ++CurPtr;\n \n \/\/ Requires at least one hex digit.\n if (CurPtr == NumStart)\n return ReturnError(CurPtr-2, \"Invalid hexadecimal number\");\n \n errno = 0;\n CurIntVal = strtoll(NumStart, 0, 16);\n if (errno == EINVAL)\n return ReturnError(CurPtr-2, \"Invalid hexadecimal number\");\n if (errno == ERANGE) {\n errno = 0;\n CurIntVal = (int64_t)strtoull(NumStart, 0, 16);\n if (errno == EINVAL)\n return ReturnError(CurPtr-2, \"Invalid hexadecimal number\");\n if (errno == ERANGE)\n return ReturnError(CurPtr-2, \"Hexadecimal number out of range\");\n }\n return asmtok::IntVal;\n }\n \n \/\/ Must be an octal number, it starts with 0.\n while (*CurPtr >= '0' && *CurPtr <= '7')\n ++CurPtr;\n CurIntVal = strtoll(TokStart, 0, 8);\n return asmtok::IntVal;\n}\n\n\/\/\/ LexQuote: String: \"...\"\nasmtok::TokKind AsmLexer::LexQuote() {\n int CurChar = getNextChar();\n \/\/ TODO: does gas allow multiline string constants?\n while (CurChar != '\"') {\n if (CurChar == '\\\\') {\n \/\/ Allow \\\", etc.\n CurChar = getNextChar();\n }\n \n if (CurChar == EOF)\n return ReturnError(TokStart, \"unterminated string constant\");\n\n CurChar = getNextChar();\n }\n \n CurStrVal.assign(TokStart, CurPtr); \/\/ include quotes.\n return asmtok::String;\n}\n\n\nasmtok::TokKind AsmLexer::LexToken() {\n TokStart = CurPtr;\n \/\/ This always consumes at least one character.\n int CurChar = getNextChar();\n \n switch (CurChar) {\n default:\n \/\/ Handle identifier: [a-zA-Z_.][a-zA-Z0-9_$.@]*\n if (isalpha(CurChar) || CurChar == '_' || CurChar == '.')\n return LexIdentifier();\n \n \/\/ Unknown character, emit an error.\n return ReturnError(TokStart, \"invalid character in input\");\n case EOF: return asmtok::Eof;\n case 0:\n case ' ':\n case '\\t':\n \/\/ Ignore whitespace.\n return LexToken();\n case '\\n': \/\/ FALL THROUGH.\n case '\\r': \/\/ FALL THROUGH.\n case ';': return asmtok::EndOfStatement;\n case ':': return asmtok::Colon;\n case '+': return asmtok::Plus;\n case '-': return asmtok::Minus;\n case '~': return asmtok::Tilde;\n case '(': return asmtok::LParen;\n case ')': return asmtok::RParen;\n case '*': return asmtok::Star;\n case ',': return asmtok::Comma;\n case '$': return asmtok::Dollar;\n case '%': return LexPercent();\n case '\/': return LexSlash();\n case '#': return LexHash();\n case '\"': return LexQuote();\n case '0': case '1': case '2': case '3': case '4':\n case '5': case '6': case '7': case '8': case '9':\n return LexDigit();\n \n \/\/ TODO: Quoted identifiers (objc methods etc)\n \/\/ local labels: [0-9][:]\n \/\/ Forward\/backward labels: [0-9][fb]\n \/\/ Integers, fp constants, character constants.\n }\n}\n<commit_msg>get a definition of strull on windows, thanks to Howard Su.<commit_after>\/\/===- AsmLexer.cpp - Lexer for Assembly Files ----------------------------===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This class implements the lexer for assembly files.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"AsmLexer.h\"\n#include \"llvm\/Support\/SourceMgr.h\"\n#include \"llvm\/Support\/MemoryBuffer.h\"\n#include \"llvm\/Config\/config.h\" \/\/ for strtoull.\n#include <cerrno>\n#include <cstdio>\n#include <cstdlib>\nusing namespace llvm;\n\nAsmLexer::AsmLexer(SourceMgr &SM) : SrcMgr(SM) {\n CurBuffer = 0;\n CurBuf = SrcMgr.getMemoryBuffer(CurBuffer);\n CurPtr = CurBuf->getBufferStart();\n TokStart = 0;\n}\n\nSMLoc AsmLexer::getLoc() const {\n return SMLoc::getFromPointer(TokStart);\n}\n\nvoid AsmLexer::PrintMessage(SMLoc Loc, const std::string &Msg) const {\n SrcMgr.PrintMessage(Loc, Msg);\n}\n\n\/\/\/ ReturnError - Set the error to the specified string at the specified\n\/\/\/ location. This is defined to always return asmtok::Error.\nasmtok::TokKind AsmLexer::ReturnError(const char *Loc, const std::string &Msg) {\n SrcMgr.PrintMessage(SMLoc::getFromPointer(Loc), Msg);\n return asmtok::Error;\n}\n\nint AsmLexer::getNextChar() {\n char CurChar = *CurPtr++;\n switch (CurChar) {\n default:\n return (unsigned char)CurChar;\n case 0: {\n \/\/ A nul character in the stream is either the end of the current buffer or\n \/\/ a random nul in the file. Disambiguate that here.\n if (CurPtr-1 != CurBuf->getBufferEnd())\n return 0; \/\/ Just whitespace.\n \n \/\/ If this is the end of an included file, pop the parent file off the\n \/\/ include stack.\n SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);\n if (ParentIncludeLoc != SMLoc()) {\n CurBuffer = SrcMgr.FindBufferContainingLoc(ParentIncludeLoc);\n CurBuf = SrcMgr.getMemoryBuffer(CurBuffer);\n CurPtr = ParentIncludeLoc.getPointer();\n return getNextChar();\n }\n \n \/\/ Otherwise, return end of file.\n --CurPtr; \/\/ Another call to lex will return EOF again. \n return EOF;\n }\n }\n}\n\n\/\/\/ LexIdentifier: [a-zA-Z_.][a-zA-Z0-9_$.@]*\nasmtok::TokKind AsmLexer::LexIdentifier() {\n while (isalnum(*CurPtr) || *CurPtr == '_' || *CurPtr == '$' ||\n *CurPtr == '.' || *CurPtr == '@')\n ++CurPtr;\n CurStrVal.assign(TokStart, CurPtr); \/\/ Include %\n return asmtok::Identifier;\n}\n\n\/\/\/ LexPercent: Register: %[a-zA-Z0-9]+\nasmtok::TokKind AsmLexer::LexPercent() {\n if (!isalnum(*CurPtr))\n return ReturnError(TokStart, \"invalid register name\");\n while (isalnum(*CurPtr))\n ++CurPtr;\n CurStrVal.assign(TokStart, CurPtr); \/\/ Skip %\n return asmtok::Register;\n}\n\n\/\/\/ LexSlash: Slash: \/\n\/\/\/ C-Style Comment: \/* ... *\/\nasmtok::TokKind AsmLexer::LexSlash() {\n if (*CurPtr != '*')\n return asmtok::Slash;\n\n \/\/ C Style comment.\n ++CurPtr; \/\/ skip the star.\n while (1) {\n int CurChar = getNextChar();\n switch (CurChar) {\n case EOF:\n return ReturnError(TokStart, \"unterminated comment\");\n case '*':\n \/\/ End of the comment?\n if (CurPtr[0] != '\/') break;\n \n ++CurPtr; \/\/ End the *\/.\n return LexToken();\n }\n }\n}\n\n\/\/\/ LexHash: Comment: #[^\\n]*\nasmtok::TokKind AsmLexer::LexHash() {\n int CurChar = getNextChar();\n while (CurChar != '\\n' && CurChar != '\\n' && CurChar != EOF)\n CurChar = getNextChar();\n \n if (CurChar == EOF)\n return asmtok::Eof;\n return asmtok::EndOfStatement;\n}\n\n\n\/\/\/ LexDigit: First character is [0-9].\n\/\/\/ Local Label: [0-9][:]\n\/\/\/ Forward\/Backward Label: [0-9][fb]\n\/\/\/ Binary integer: 0b[01]+\n\/\/\/ Octal integer: 0[0-7]+\n\/\/\/ Hex integer: 0x[0-9a-fA-F]+\n\/\/\/ Decimal integer: [1-9][0-9]*\n\/\/\/ TODO: FP literal.\nasmtok::TokKind AsmLexer::LexDigit() {\n if (*CurPtr == ':')\n return ReturnError(TokStart, \"FIXME: local label not implemented\");\n if (*CurPtr == 'f' || *CurPtr == 'b')\n return ReturnError(TokStart, \"FIXME: directional label not implemented\");\n \n \/\/ Decimal integer: [1-9][0-9]*\n if (CurPtr[-1] != '0') {\n while (isdigit(*CurPtr))\n ++CurPtr;\n CurIntVal = strtoll(TokStart, 0, 10);\n return asmtok::IntVal;\n }\n \n if (*CurPtr == 'b') {\n ++CurPtr;\n const char *NumStart = CurPtr;\n while (CurPtr[0] == '0' || CurPtr[0] == '1')\n ++CurPtr;\n \n \/\/ Requires at least one binary digit.\n if (CurPtr == NumStart)\n return ReturnError(CurPtr-2, \"Invalid binary number\");\n CurIntVal = strtoll(NumStart, 0, 2);\n return asmtok::IntVal;\n }\n \n if (*CurPtr == 'x') {\n ++CurPtr;\n const char *NumStart = CurPtr;\n while (isxdigit(CurPtr[0]))\n ++CurPtr;\n \n \/\/ Requires at least one hex digit.\n if (CurPtr == NumStart)\n return ReturnError(CurPtr-2, \"Invalid hexadecimal number\");\n \n errno = 0;\n CurIntVal = strtoll(NumStart, 0, 16);\n if (errno == EINVAL)\n return ReturnError(CurPtr-2, \"Invalid hexadecimal number\");\n if (errno == ERANGE) {\n errno = 0;\n CurIntVal = (int64_t)strtoull(NumStart, 0, 16);\n if (errno == EINVAL)\n return ReturnError(CurPtr-2, \"Invalid hexadecimal number\");\n if (errno == ERANGE)\n return ReturnError(CurPtr-2, \"Hexadecimal number out of range\");\n }\n return asmtok::IntVal;\n }\n \n \/\/ Must be an octal number, it starts with 0.\n while (*CurPtr >= '0' && *CurPtr <= '7')\n ++CurPtr;\n CurIntVal = strtoll(TokStart, 0, 8);\n return asmtok::IntVal;\n}\n\n\/\/\/ LexQuote: String: \"...\"\nasmtok::TokKind AsmLexer::LexQuote() {\n int CurChar = getNextChar();\n \/\/ TODO: does gas allow multiline string constants?\n while (CurChar != '\"') {\n if (CurChar == '\\\\') {\n \/\/ Allow \\\", etc.\n CurChar = getNextChar();\n }\n \n if (CurChar == EOF)\n return ReturnError(TokStart, \"unterminated string constant\");\n\n CurChar = getNextChar();\n }\n \n CurStrVal.assign(TokStart, CurPtr); \/\/ include quotes.\n return asmtok::String;\n}\n\n\nasmtok::TokKind AsmLexer::LexToken() {\n TokStart = CurPtr;\n \/\/ This always consumes at least one character.\n int CurChar = getNextChar();\n \n switch (CurChar) {\n default:\n \/\/ Handle identifier: [a-zA-Z_.][a-zA-Z0-9_$.@]*\n if (isalpha(CurChar) || CurChar == '_' || CurChar == '.')\n return LexIdentifier();\n \n \/\/ Unknown character, emit an error.\n return ReturnError(TokStart, \"invalid character in input\");\n case EOF: return asmtok::Eof;\n case 0:\n case ' ':\n case '\\t':\n \/\/ Ignore whitespace.\n return LexToken();\n case '\\n': \/\/ FALL THROUGH.\n case '\\r': \/\/ FALL THROUGH.\n case ';': return asmtok::EndOfStatement;\n case ':': return asmtok::Colon;\n case '+': return asmtok::Plus;\n case '-': return asmtok::Minus;\n case '~': return asmtok::Tilde;\n case '(': return asmtok::LParen;\n case ')': return asmtok::RParen;\n case '*': return asmtok::Star;\n case ',': return asmtok::Comma;\n case '$': return asmtok::Dollar;\n case '%': return LexPercent();\n case '\/': return LexSlash();\n case '#': return LexHash();\n case '\"': return LexQuote();\n case '0': case '1': case '2': case '3': case '4':\n case '5': case '6': case '7': case '8': case '9':\n return LexDigit();\n \n \/\/ TODO: Quoted identifiers (objc methods etc)\n \/\/ local labels: [0-9][:]\n \/\/ Forward\/backward labels: [0-9][fb]\n \/\/ Integers, fp constants, character constants.\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"ppapi\/proxy\/plugin_var_tracker.h\"\n\n#include \"base\/memory\/ref_counted.h\"\n#include \"base\/memory\/singleton.h\"\n#include \"ppapi\/c\/dev\/ppp_class_deprecated.h\"\n#include \"ppapi\/c\/ppb_var.h\"\n#include \"ppapi\/proxy\/plugin_array_buffer_var.h\"\n#include \"ppapi\/proxy\/plugin_dispatcher.h\"\n#include \"ppapi\/proxy\/ppapi_messages.h\"\n#include \"ppapi\/proxy\/proxy_object_var.h\"\n#include \"ppapi\/shared_impl\/api_id.h\"\n#include \"ppapi\/shared_impl\/var.h\"\n\nnamespace ppapi {\nnamespace proxy {\n\nPluginVarTracker::HostVar::HostVar(PluginDispatcher* d, int32 i)\n : dispatcher(d),\n host_object_id(i) {\n}\n\nbool PluginVarTracker::HostVar::operator<(const HostVar& other) const {\n if (dispatcher < other.dispatcher)\n return true;\n if (other.dispatcher < dispatcher)\n return false;\n return host_object_id < other.host_object_id;\n}\n\nPluginVarTracker::PluginVarTracker() {\n}\n\nPluginVarTracker::~PluginVarTracker() {\n}\n\nPP_Var PluginVarTracker::ReceiveObjectPassRef(const PP_Var& host_var,\n PluginDispatcher* dispatcher) {\n DCHECK(CalledOnValidThread());\n DCHECK(host_var.type == PP_VARTYPE_OBJECT);\n\n \/\/ Get the object.\n scoped_refptr<ProxyObjectVar> object(\n FindOrMakePluginVarFromHostVar(host_var, dispatcher));\n\n \/\/ Actually create the PP_Var, this will add all the tracking info but not\n \/\/ adjust any refcounts.\n PP_Var ret = GetOrCreateObjectVarID(object.get());\n\n VarInfo& info = GetLiveVar(ret)->second;\n if (info.ref_count > 0) {\n \/\/ We already had a reference to it before. That means the renderer now has\n \/\/ two references on our behalf. We want to transfer that extra reference\n \/\/ to our list. This means we addref in the plugin, and release the extra\n \/\/ one in the renderer.\n SendReleaseObjectMsg(*object);\n }\n info.ref_count++;\n return ret;\n}\n\nPP_Var PluginVarTracker::TrackObjectWithNoReference(\n const PP_Var& host_var,\n PluginDispatcher* dispatcher) {\n DCHECK(CalledOnValidThread());\n DCHECK(host_var.type == PP_VARTYPE_OBJECT);\n\n \/\/ Get the object.\n scoped_refptr<ProxyObjectVar> object(\n FindOrMakePluginVarFromHostVar(host_var, dispatcher));\n\n \/\/ Actually create the PP_Var, this will add all the tracking info but not\n \/\/ adjust any refcounts.\n PP_Var ret = GetOrCreateObjectVarID(object.get());\n\n VarInfo& info = GetLiveVar(ret)->second;\n info.track_with_no_reference_count++;\n return ret;\n}\n\nvoid PluginVarTracker::StopTrackingObjectWithNoReference(\n const PP_Var& plugin_var) {\n DCHECK(CalledOnValidThread());\n DCHECK(plugin_var.type == PP_VARTYPE_OBJECT);\n\n VarMap::iterator found = GetLiveVar(plugin_var);\n if (found == live_vars_.end()) {\n NOTREACHED();\n return;\n }\n\n DCHECK(found->second.track_with_no_reference_count > 0);\n found->second.track_with_no_reference_count--;\n DeleteObjectInfoIfNecessary(found);\n}\n\nPP_Var PluginVarTracker::GetHostObject(const PP_Var& plugin_object) const {\n DCHECK(CalledOnValidThread());\n\n if (plugin_object.type != PP_VARTYPE_OBJECT) {\n NOTREACHED();\n return PP_MakeUndefined();\n }\n\n Var* var = GetVar(plugin_object);\n ProxyObjectVar* object = var->AsProxyObjectVar();\n if (!object) {\n NOTREACHED();\n return PP_MakeUndefined();\n }\n\n \/\/ Make a var with the host ID.\n PP_Var ret = { PP_VARTYPE_OBJECT };\n ret.value.as_id = object->host_var_id();\n return ret;\n}\n\nPluginDispatcher* PluginVarTracker::DispatcherForPluginObject(\n const PP_Var& plugin_object) const {\n DCHECK(CalledOnValidThread());\n\n if (plugin_object.type != PP_VARTYPE_OBJECT)\n return NULL;\n\n VarMap::const_iterator found = GetLiveVar(plugin_object);\n if (found == live_vars_.end())\n return NULL;\n\n ProxyObjectVar* object = found->second.var->AsProxyObjectVar();\n if (!object)\n return NULL;\n return object->dispatcher();\n}\n\nvoid PluginVarTracker::ReleaseHostObject(PluginDispatcher* dispatcher,\n const PP_Var& host_object) {\n DCHECK(CalledOnValidThread());\n DCHECK(host_object.type == PP_VARTYPE_OBJECT);\n\n \/\/ Convert the host object to a normal var valid in the plugin.\n HostVarToPluginVarMap::iterator found = host_var_to_plugin_var_.find(\n HostVar(dispatcher, static_cast<int32>(host_object.value.as_id)));\n if (found == host_var_to_plugin_var_.end()) {\n NOTREACHED();\n return;\n }\n\n \/\/ Now just release the object given the plugin var ID.\n ReleaseVar(found->second);\n}\n\nvoid PluginVarTracker::DidDeleteInstance(PP_Instance instance) {\n \/\/ See the comment above user_data_to_plugin_ in the header file. We assume\n \/\/ there aren't that many objects so a brute-force search is reasonable.\n UserDataToPluginImplementedVarMap::iterator i =\n user_data_to_plugin_.begin();\n while (i != user_data_to_plugin_.end()) {\n if (i->second.instance == instance) {\n if (!i->second.plugin_object_id) {\n \/\/ This object is for the freed instance and the plugin is not holding\n \/\/ any references to it. Deallocate immediately.\n UserDataToPluginImplementedVarMap::iterator to_remove = i;\n ++i;\n to_remove->second.ppp_class->Deallocate(to_remove->first);\n user_data_to_plugin_.erase(to_remove);\n } else {\n \/\/ The plugin is holding refs to this object. We don't want to call\n \/\/ Deallocate since the plugin may be depending on those refs to keep\n \/\/ its data alive. To avoid crashes in this case, just clear out the\n \/\/ instance to mark it and continue. When the plugin refs go to 0,\n \/\/ we'll notice there is no instance and call Deallocate.\n i->second.instance = 0;\n ++i;\n }\n } else {\n ++i;\n }\n }\n}\n\nArrayBufferVar* PluginVarTracker::CreateArrayBuffer(uint32 size_in_bytes) {\n return new PluginArrayBufferVar(size_in_bytes);\n}\n\nvoid PluginVarTracker::PluginImplementedObjectCreated(\n PP_Instance instance,\n const PP_Var& created_var,\n const PPP_Class_Deprecated* ppp_class,\n void* ppp_class_data) {\n PluginImplementedVar p;\n p.ppp_class = ppp_class;\n p.instance = instance;\n p.plugin_object_id = created_var.value.as_id;\n user_data_to_plugin_[ppp_class_data] = p;\n\n \/\/ Link the user data to the object.\n ProxyObjectVar* object = GetVar(created_var)->AsProxyObjectVar();\n object->set_user_data(ppp_class_data);\n}\n\nvoid PluginVarTracker::PluginImplementedObjectDestroyed(void* user_data) {\n UserDataToPluginImplementedVarMap::iterator found =\n user_data_to_plugin_.find(user_data);\n if (found == user_data_to_plugin_.end()) {\n NOTREACHED();\n return;\n }\n user_data_to_plugin_.erase(found);\n}\n\nbool PluginVarTracker::IsPluginImplementedObjectAlive(void* user_data) {\n return user_data_to_plugin_.find(user_data) != user_data_to_plugin_.end();\n}\n\nbool PluginVarTracker::ValidatePluginObjectCall(\n const PPP_Class_Deprecated* ppp_class,\n void* user_data) {\n UserDataToPluginImplementedVarMap::iterator found =\n user_data_to_plugin_.find(user_data);\n if (found == user_data_to_plugin_.end())\n return false;\n return found->second.ppp_class == ppp_class;\n}\n\nint32 PluginVarTracker::AddVarInternal(Var* var, AddVarRefMode mode) {\n \/\/ Normal adding.\n int32 new_id = VarTracker::AddVarInternal(var, mode);\n\n \/\/ Need to add proxy objects to the host var map.\n ProxyObjectVar* proxy_object = var->AsProxyObjectVar();\n if (proxy_object) {\n HostVar host_var(proxy_object->dispatcher(), proxy_object->host_var_id());\n DCHECK(host_var_to_plugin_var_.find(host_var) ==\n host_var_to_plugin_var_.end()); \/\/ Adding an object twice, use\n \/\/ FindOrMakePluginVarFromHostVar.\n host_var_to_plugin_var_[host_var] = new_id;\n }\n return new_id;\n}\n\nvoid PluginVarTracker::TrackedObjectGettingOneRef(VarMap::const_iterator iter) {\n ProxyObjectVar* object = iter->second.var->AsProxyObjectVar();\n if (!object) {\n NOTREACHED();\n return;\n }\n\n DCHECK(iter->second.ref_count == 0);\n\n \/\/ Got an AddRef for an object we have no existing reference for.\n \/\/ We need to tell the browser we've taken a ref. This comes up when the\n \/\/ browser passes an object as an input param and holds a ref for us.\n \/\/ This must be a sync message since otherwise the \"addref\" will actually\n \/\/ occur after the return to the browser of the sync function that\n \/\/ presumably sent the object.\n SendAddRefObjectMsg(*object);\n}\n\nvoid PluginVarTracker::ObjectGettingZeroRef(VarMap::iterator iter) {\n ProxyObjectVar* object = iter->second.var->AsProxyObjectVar();\n if (!object) {\n NOTREACHED();\n return;\n }\n\n \/\/ Notify the host we're no longer holding our ref.\n DCHECK(iter->second.ref_count == 0);\n SendReleaseObjectMsg(*object);\n\n UserDataToPluginImplementedVarMap::iterator found =\n user_data_to_plugin_.find(object->user_data());\n if (found != user_data_to_plugin_.end()) {\n \/\/ This object is implemented in the plugin.\n if (found->second.instance == 0) {\n \/\/ Instance is destroyed. This means that we'll never get a Deallocate\n \/\/ call from the renderer and we should do so now.\n found->second.ppp_class->Deallocate(found->first);\n user_data_to_plugin_.erase(found);\n } else {\n \/\/ The plugin is releasing its last reference to an object it implements.\n \/\/ Clear the tracking data that links our \"plugin implemented object\" to\n \/\/ the var. If the instance is destroyed and there is no ID, we know that\n \/\/ we should just call Deallocate on the object data.\n \/\/\n \/\/ See the plugin_object_id declaration for more info.\n found->second.plugin_object_id = 0;\n }\n }\n\n \/\/ This will optionally delete the info from live_vars_.\n VarTracker::ObjectGettingZeroRef(iter);\n}\n\nbool PluginVarTracker::DeleteObjectInfoIfNecessary(VarMap::iterator iter) {\n \/\/ Get the info before calling the base class's version of this function,\n \/\/ which may delete the object.\n ProxyObjectVar* object = iter->second.var->AsProxyObjectVar();\n HostVar host_var(object->dispatcher(), object->host_var_id());\n\n if (!VarTracker::DeleteObjectInfoIfNecessary(iter))\n return false;\n\n \/\/ Clean up the host var mapping.\n DCHECK(host_var_to_plugin_var_.find(host_var) !=\n host_var_to_plugin_var_.end());\n host_var_to_plugin_var_.erase(host_var);\n return true;\n}\n\nPP_Var PluginVarTracker::GetOrCreateObjectVarID(ProxyObjectVar* object) {\n \/\/ We can't use object->GetPPVar() because we don't want to affect the\n \/\/ refcount, so we have to add everything manually here.\n int32 var_id = object->GetExistingVarID();\n if (!var_id) {\n var_id = AddVarInternal(object, ADD_VAR_CREATE_WITH_NO_REFERENCE);\n object->AssignVarID(var_id);\n }\n\n PP_Var ret = { PP_VARTYPE_OBJECT };\n ret.value.as_id = var_id;\n return ret;\n}\n\nvoid PluginVarTracker::SendAddRefObjectMsg(\n const ProxyObjectVar& proxy_object) {\n int unused;\n proxy_object.dispatcher()->Send(new PpapiHostMsg_PPBVar_AddRefObject(\n API_ID_PPB_VAR_DEPRECATED, proxy_object.host_var_id(), &unused));\n}\n\nvoid PluginVarTracker::SendReleaseObjectMsg(\n const ProxyObjectVar& proxy_object) {\n proxy_object.dispatcher()->Send(new PpapiHostMsg_PPBVar_ReleaseObject(\n API_ID_PPB_VAR_DEPRECATED, proxy_object.host_var_id()));\n}\n\nscoped_refptr<ProxyObjectVar> PluginVarTracker::FindOrMakePluginVarFromHostVar(\n const PP_Var& var,\n PluginDispatcher* dispatcher) {\n DCHECK(var.type == PP_VARTYPE_OBJECT);\n HostVar host_var(dispatcher, var.value.as_id);\n\n HostVarToPluginVarMap::iterator found =\n host_var_to_plugin_var_.find(host_var);\n if (found == host_var_to_plugin_var_.end()) {\n \/\/ Create a new object.\n return scoped_refptr<ProxyObjectVar>(\n new ProxyObjectVar(dispatcher, static_cast<int32>(var.value.as_id)));\n }\n\n \/\/ Have this host var, look up the object.\n VarMap::iterator ret = live_vars_.find(found->second);\n DCHECK(ret != live_vars_.end());\n\n \/\/ All objects should be proxy objects.\n DCHECK(ret->second.var->AsProxyObjectVar());\n return scoped_refptr<ProxyObjectVar>(ret->second.var->AsProxyObjectVar());\n}\n\n} \/\/ namesace proxy\n} \/\/ namespace ppapi\n<commit_msg>Try to fix a crash in the var tracking.<commit_after>\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"ppapi\/proxy\/plugin_var_tracker.h\"\n\n#include \"base\/memory\/ref_counted.h\"\n#include \"base\/memory\/singleton.h\"\n#include \"ppapi\/c\/dev\/ppp_class_deprecated.h\"\n#include \"ppapi\/c\/ppb_var.h\"\n#include \"ppapi\/proxy\/plugin_array_buffer_var.h\"\n#include \"ppapi\/proxy\/plugin_dispatcher.h\"\n#include \"ppapi\/proxy\/ppapi_messages.h\"\n#include \"ppapi\/proxy\/proxy_object_var.h\"\n#include \"ppapi\/shared_impl\/api_id.h\"\n#include \"ppapi\/shared_impl\/var.h\"\n\nnamespace ppapi {\nnamespace proxy {\n\nPluginVarTracker::HostVar::HostVar(PluginDispatcher* d, int32 i)\n : dispatcher(d),\n host_object_id(i) {\n}\n\nbool PluginVarTracker::HostVar::operator<(const HostVar& other) const {\n if (dispatcher < other.dispatcher)\n return true;\n if (other.dispatcher < dispatcher)\n return false;\n return host_object_id < other.host_object_id;\n}\n\nPluginVarTracker::PluginVarTracker() {\n}\n\nPluginVarTracker::~PluginVarTracker() {\n}\n\nPP_Var PluginVarTracker::ReceiveObjectPassRef(const PP_Var& host_var,\n PluginDispatcher* dispatcher) {\n DCHECK(CalledOnValidThread());\n DCHECK(host_var.type == PP_VARTYPE_OBJECT);\n\n \/\/ Get the object.\n scoped_refptr<ProxyObjectVar> object(\n FindOrMakePluginVarFromHostVar(host_var, dispatcher));\n\n \/\/ Actually create the PP_Var, this will add all the tracking info but not\n \/\/ adjust any refcounts.\n PP_Var ret = GetOrCreateObjectVarID(object.get());\n\n VarInfo& info = GetLiveVar(ret)->second;\n if (info.ref_count > 0) {\n \/\/ We already had a reference to it before. That means the renderer now has\n \/\/ two references on our behalf. We want to transfer that extra reference\n \/\/ to our list. This means we addref in the plugin, and release the extra\n \/\/ one in the renderer.\n SendReleaseObjectMsg(*object);\n }\n info.ref_count++;\n return ret;\n}\n\nPP_Var PluginVarTracker::TrackObjectWithNoReference(\n const PP_Var& host_var,\n PluginDispatcher* dispatcher) {\n DCHECK(CalledOnValidThread());\n DCHECK(host_var.type == PP_VARTYPE_OBJECT);\n\n \/\/ Get the object.\n scoped_refptr<ProxyObjectVar> object(\n FindOrMakePluginVarFromHostVar(host_var, dispatcher));\n\n \/\/ Actually create the PP_Var, this will add all the tracking info but not\n \/\/ adjust any refcounts.\n PP_Var ret = GetOrCreateObjectVarID(object.get());\n\n VarInfo& info = GetLiveVar(ret)->second;\n info.track_with_no_reference_count++;\n return ret;\n}\n\nvoid PluginVarTracker::StopTrackingObjectWithNoReference(\n const PP_Var& plugin_var) {\n DCHECK(CalledOnValidThread());\n DCHECK(plugin_var.type == PP_VARTYPE_OBJECT);\n\n VarMap::iterator found = GetLiveVar(plugin_var);\n if (found == live_vars_.end()) {\n NOTREACHED();\n return;\n }\n\n DCHECK(found->second.track_with_no_reference_count > 0);\n found->second.track_with_no_reference_count--;\n DeleteObjectInfoIfNecessary(found);\n}\n\nPP_Var PluginVarTracker::GetHostObject(const PP_Var& plugin_object) const {\n DCHECK(CalledOnValidThread());\n\n if (plugin_object.type != PP_VARTYPE_OBJECT) {\n NOTREACHED();\n return PP_MakeUndefined();\n }\n\n Var* var = GetVar(plugin_object);\n ProxyObjectVar* object = var->AsProxyObjectVar();\n if (!object) {\n NOTREACHED();\n return PP_MakeUndefined();\n }\n\n \/\/ Make a var with the host ID.\n PP_Var ret = { PP_VARTYPE_OBJECT };\n ret.value.as_id = object->host_var_id();\n return ret;\n}\n\nPluginDispatcher* PluginVarTracker::DispatcherForPluginObject(\n const PP_Var& plugin_object) const {\n DCHECK(CalledOnValidThread());\n\n if (plugin_object.type != PP_VARTYPE_OBJECT)\n return NULL;\n\n VarMap::const_iterator found = GetLiveVar(plugin_object);\n if (found == live_vars_.end())\n return NULL;\n\n ProxyObjectVar* object = found->second.var->AsProxyObjectVar();\n if (!object)\n return NULL;\n return object->dispatcher();\n}\n\nvoid PluginVarTracker::ReleaseHostObject(PluginDispatcher* dispatcher,\n const PP_Var& host_object) {\n DCHECK(CalledOnValidThread());\n DCHECK(host_object.type == PP_VARTYPE_OBJECT);\n\n \/\/ Convert the host object to a normal var valid in the plugin.\n HostVarToPluginVarMap::iterator found = host_var_to_plugin_var_.find(\n HostVar(dispatcher, static_cast<int32>(host_object.value.as_id)));\n if (found == host_var_to_plugin_var_.end()) {\n NOTREACHED();\n return;\n }\n\n \/\/ Now just release the object given the plugin var ID.\n ReleaseVar(found->second);\n}\n\nvoid PluginVarTracker::DidDeleteInstance(PP_Instance instance) {\n \/\/ Calling the destructors on plugin objects may in turn release other\n \/\/ objects which will mutate the map out from under us. So do a two-step\n \/\/ process of identifying the ones to delete, and then delete them.\n \/\/\n \/\/ See the comment above user_data_to_plugin_ in the header file. We assume\n \/\/ there aren't that many objects so a brute-force search is reasonable.\n std::vector<void*> user_data_to_delete;\n for (UserDataToPluginImplementedVarMap::const_iterator i =\n user_data_to_plugin_.begin();\n i != user_data_to_plugin_.end();\n ++i) {\n if (i->second.instance == instance)\n user_data_to_delete.push_back(i->first);\n }\n\n for (size_t i = 0; i < user_data_to_delete.size(); i++) {\n UserDataToPluginImplementedVarMap::iterator found =\n user_data_to_plugin_.find(user_data_to_delete[i]);\n if (found == user_data_to_plugin_.end())\n continue; \/\/ Object removed from list while we were iterating.\n\n if (!found->second.plugin_object_id) {\n \/\/ This object is for the freed instance and the plugin is not holding\n \/\/ any references to it. Deallocate immediately.\n found->second.ppp_class->Deallocate(found->first);\n user_data_to_plugin_.erase(found);\n } else {\n \/\/ The plugin is holding refs to this object. We don't want to call\n \/\/ Deallocate since the plugin may be depending on those refs to keep\n \/\/ its data alive. To avoid crashes in this case, just clear out the\n \/\/ instance to mark it and continue. When the plugin refs go to 0,\n \/\/ we'll notice there is no instance and call Deallocate.\n found->second.instance = 0;\n }\n }\n}\n\nArrayBufferVar* PluginVarTracker::CreateArrayBuffer(uint32 size_in_bytes) {\n return new PluginArrayBufferVar(size_in_bytes);\n}\n\nvoid PluginVarTracker::PluginImplementedObjectCreated(\n PP_Instance instance,\n const PP_Var& created_var,\n const PPP_Class_Deprecated* ppp_class,\n void* ppp_class_data) {\n PluginImplementedVar p;\n p.ppp_class = ppp_class;\n p.instance = instance;\n p.plugin_object_id = created_var.value.as_id;\n user_data_to_plugin_[ppp_class_data] = p;\n\n \/\/ Link the user data to the object.\n ProxyObjectVar* object = GetVar(created_var)->AsProxyObjectVar();\n object->set_user_data(ppp_class_data);\n}\n\nvoid PluginVarTracker::PluginImplementedObjectDestroyed(void* user_data) {\n UserDataToPluginImplementedVarMap::iterator found =\n user_data_to_plugin_.find(user_data);\n if (found == user_data_to_plugin_.end()) {\n NOTREACHED();\n return;\n }\n user_data_to_plugin_.erase(found);\n}\n\nbool PluginVarTracker::IsPluginImplementedObjectAlive(void* user_data) {\n return user_data_to_plugin_.find(user_data) != user_data_to_plugin_.end();\n}\n\nbool PluginVarTracker::ValidatePluginObjectCall(\n const PPP_Class_Deprecated* ppp_class,\n void* user_data) {\n UserDataToPluginImplementedVarMap::iterator found =\n user_data_to_plugin_.find(user_data);\n if (found == user_data_to_plugin_.end())\n return false;\n return found->second.ppp_class == ppp_class;\n}\n\nint32 PluginVarTracker::AddVarInternal(Var* var, AddVarRefMode mode) {\n \/\/ Normal adding.\n int32 new_id = VarTracker::AddVarInternal(var, mode);\n\n \/\/ Need to add proxy objects to the host var map.\n ProxyObjectVar* proxy_object = var->AsProxyObjectVar();\n if (proxy_object) {\n HostVar host_var(proxy_object->dispatcher(), proxy_object->host_var_id());\n DCHECK(host_var_to_plugin_var_.find(host_var) ==\n host_var_to_plugin_var_.end()); \/\/ Adding an object twice, use\n \/\/ FindOrMakePluginVarFromHostVar.\n host_var_to_plugin_var_[host_var] = new_id;\n }\n return new_id;\n}\n\nvoid PluginVarTracker::TrackedObjectGettingOneRef(VarMap::const_iterator iter) {\n ProxyObjectVar* object = iter->second.var->AsProxyObjectVar();\n if (!object) {\n NOTREACHED();\n return;\n }\n\n DCHECK(iter->second.ref_count == 0);\n\n \/\/ Got an AddRef for an object we have no existing reference for.\n \/\/ We need to tell the browser we've taken a ref. This comes up when the\n \/\/ browser passes an object as an input param and holds a ref for us.\n \/\/ This must be a sync message since otherwise the \"addref\" will actually\n \/\/ occur after the return to the browser of the sync function that\n \/\/ presumably sent the object.\n SendAddRefObjectMsg(*object);\n}\n\nvoid PluginVarTracker::ObjectGettingZeroRef(VarMap::iterator iter) {\n ProxyObjectVar* object = iter->second.var->AsProxyObjectVar();\n if (!object) {\n NOTREACHED();\n return;\n }\n\n \/\/ Notify the host we're no longer holding our ref.\n DCHECK(iter->second.ref_count == 0);\n SendReleaseObjectMsg(*object);\n\n UserDataToPluginImplementedVarMap::iterator found =\n user_data_to_plugin_.find(object->user_data());\n if (found != user_data_to_plugin_.end()) {\n \/\/ This object is implemented in the plugin.\n if (found->second.instance == 0) {\n \/\/ Instance is destroyed. This means that we'll never get a Deallocate\n \/\/ call from the renderer and we should do so now.\n found->second.ppp_class->Deallocate(found->first);\n user_data_to_plugin_.erase(found);\n } else {\n \/\/ The plugin is releasing its last reference to an object it implements.\n \/\/ Clear the tracking data that links our \"plugin implemented object\" to\n \/\/ the var. If the instance is destroyed and there is no ID, we know that\n \/\/ we should just call Deallocate on the object data.\n \/\/\n \/\/ See the plugin_object_id declaration for more info.\n found->second.plugin_object_id = 0;\n }\n }\n\n \/\/ This will optionally delete the info from live_vars_.\n VarTracker::ObjectGettingZeroRef(iter);\n}\n\nbool PluginVarTracker::DeleteObjectInfoIfNecessary(VarMap::iterator iter) {\n \/\/ Get the info before calling the base class's version of this function,\n \/\/ which may delete the object.\n ProxyObjectVar* object = iter->second.var->AsProxyObjectVar();\n HostVar host_var(object->dispatcher(), object->host_var_id());\n\n if (!VarTracker::DeleteObjectInfoIfNecessary(iter))\n return false;\n\n \/\/ Clean up the host var mapping.\n DCHECK(host_var_to_plugin_var_.find(host_var) !=\n host_var_to_plugin_var_.end());\n host_var_to_plugin_var_.erase(host_var);\n return true;\n}\n\nPP_Var PluginVarTracker::GetOrCreateObjectVarID(ProxyObjectVar* object) {\n \/\/ We can't use object->GetPPVar() because we don't want to affect the\n \/\/ refcount, so we have to add everything manually here.\n int32 var_id = object->GetExistingVarID();\n if (!var_id) {\n var_id = AddVarInternal(object, ADD_VAR_CREATE_WITH_NO_REFERENCE);\n object->AssignVarID(var_id);\n }\n\n PP_Var ret = { PP_VARTYPE_OBJECT };\n ret.value.as_id = var_id;\n return ret;\n}\n\nvoid PluginVarTracker::SendAddRefObjectMsg(\n const ProxyObjectVar& proxy_object) {\n int unused;\n proxy_object.dispatcher()->Send(new PpapiHostMsg_PPBVar_AddRefObject(\n API_ID_PPB_VAR_DEPRECATED, proxy_object.host_var_id(), &unused));\n}\n\nvoid PluginVarTracker::SendReleaseObjectMsg(\n const ProxyObjectVar& proxy_object) {\n proxy_object.dispatcher()->Send(new PpapiHostMsg_PPBVar_ReleaseObject(\n API_ID_PPB_VAR_DEPRECATED, proxy_object.host_var_id()));\n}\n\nscoped_refptr<ProxyObjectVar> PluginVarTracker::FindOrMakePluginVarFromHostVar(\n const PP_Var& var,\n PluginDispatcher* dispatcher) {\n DCHECK(var.type == PP_VARTYPE_OBJECT);\n HostVar host_var(dispatcher, var.value.as_id);\n\n HostVarToPluginVarMap::iterator found =\n host_var_to_plugin_var_.find(host_var);\n if (found == host_var_to_plugin_var_.end()) {\n \/\/ Create a new object.\n return scoped_refptr<ProxyObjectVar>(\n new ProxyObjectVar(dispatcher, static_cast<int32>(var.value.as_id)));\n }\n\n \/\/ Have this host var, look up the object.\n VarMap::iterator ret = live_vars_.find(found->second);\n DCHECK(ret != live_vars_.end());\n\n \/\/ All objects should be proxy objects.\n DCHECK(ret->second.var->AsProxyObjectVar());\n return scoped_refptr<ProxyObjectVar>(ret->second.var->AsProxyObjectVar());\n}\n\n} \/\/ namesace proxy\n} \/\/ namespace ppapi\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2015, the Dart project authors. Please see the AUTHORS file\n\/\/ for details. All rights reserved. Use of this source code is governed by a\n\/\/ BSD-style license that can be found in the LICENSE file.\n\n#include \"bin\/vmservice_dartium.h\"\n\n#include \"bin\/builtin.h\"\n#include \"bin\/dartutils.h\"\n#include \"bin\/eventhandler.h\"\n#include \"bin\/platform.h\"\n#include \"bin\/thread.h\"\n#include \"bin\/utils.h\"\n#include \"bin\/vmservice_impl.h\"\n#include \"zlib\/zlib.h\"\n\nnamespace dart {\nnamespace bin {\n\n#define CHECK_RESULT(result) \\\n if (Dart_IsError(result)) { \\\n fprintf(stderr, \"CHECK_RESULT failed: %s\", Dart_GetError(result)); \\\n Dart_ExitScope(); \\\n Dart_ShutdownIsolate(); \\\n return 0; \\\n }\n\n\nstatic const char* DEFAULT_VM_SERVICE_SERVER_IP = \"127.0.0.1\";\nstatic const int DEFAULT_VM_SERVICE_SERVER_PORT = 0;\n\nvoid VmServiceServer::Bootstrap() {\n if (!Platform::Initialize()) {\n fprintf(stderr, \"Platform::Initialize() failed\\n\");\n }\n DartUtils::SetOriginalWorkingDirectory();\n Thread::InitOnce();\n TimerUtils::InitOnce();\n EventHandler::Start();\n}\n\n\nDart_Isolate VmServiceServer::CreateIsolate(const uint8_t* snapshot_buffer) {\n ASSERT(snapshot_buffer != NULL);\n \/\/ Create the isolate.\n IsolateData* isolate_data =\n new IsolateData(DART_VM_SERVICE_ISOLATE_NAME, NULL, NULL, NULL);\n char* error = 0;\n Dart_Isolate isolate =\n Dart_CreateIsolate(DART_VM_SERVICE_ISOLATE_NAME, \"main\", snapshot_buffer,\n NULL, NULL, isolate_data, &error);\n if (!isolate) {\n fprintf(stderr, \"Dart_CreateIsolate failed: %s\\n\", error);\n return 0;\n }\n\n Dart_EnterScope();\n Builtin::SetNativeResolver(Builtin::kBuiltinLibrary);\n Builtin::SetNativeResolver(Builtin::kIOLibrary);\n\n ASSERT(Dart_IsServiceIsolate(isolate));\n if (!VmService::Setup(\n DEFAULT_VM_SERVICE_SERVER_IP, DEFAULT_VM_SERVICE_SERVER_PORT,\n false \/* running_precompiled *\/, false \/* disable origin checks *\/,\n false \/* trace_loading *\/)) {\n fprintf(stderr, \"Vmservice::Setup failed: %s\\n\",\n VmService::GetErrorMessage());\n isolate = NULL;\n }\n Dart_ExitScope();\n Dart_ExitIsolate();\n return isolate;\n}\n\n\nconst char* VmServiceServer::GetServerAddress() {\n return VmService::GetServerAddress();\n}\n\n\nvoid VmServiceServer::DecompressAssets(const uint8_t* input,\n unsigned int input_len,\n uint8_t** output,\n unsigned int* output_length) {\n ASSERT(input != NULL);\n ASSERT(input_len > 0);\n ASSERT(output != NULL);\n ASSERT(output_length != NULL);\n\n \/\/ Initialize output.\n *output = NULL;\n *output_length = 0;\n\n const unsigned int kChunkSize = 256 * 1024;\n uint8_t chunk_out[kChunkSize];\n z_stream strm;\n strm.zalloc = Z_NULL;\n strm.zfree = Z_NULL;\n strm.opaque = Z_NULL;\n strm.avail_in = 0;\n strm.next_in = 0;\n int ret = inflateInit2(&strm, 32 + MAX_WBITS);\n ASSERT(ret == Z_OK);\n\n unsigned int input_cursor = 0;\n unsigned int output_cursor = 0;\n do {\n \/\/ Setup input.\n unsigned int size_in = input_len - input_cursor;\n if (size_in > kChunkSize) {\n size_in = kChunkSize;\n }\n strm.avail_in = size_in;\n strm.next_in = const_cast<uint8_t*>(&input[input_cursor]);\n\n \/\/ Inflate until we've exhausted the current input chunk.\n do {\n \/\/ Setup output.\n strm.avail_out = kChunkSize;\n strm.next_out = &chunk_out[0];\n \/\/ Inflate.\n ret = inflate(&strm, Z_SYNC_FLUSH);\n \/\/ We either hit the end of the stream or made forward progress.\n ASSERT((ret == Z_STREAM_END) || (ret == Z_OK));\n \/\/ Grow output buffer size.\n unsigned int size_out = kChunkSize - strm.avail_out;\n *output_length += size_out;\n *output = reinterpret_cast<uint8_t*>(realloc(*output, *output_length));\n \/\/ Copy output.\n memmove(&((*output)[output_cursor]), &chunk_out[0], size_out);\n output_cursor += size_out;\n } while (strm.avail_out == 0);\n\n \/\/ We've processed size_in bytes.\n input_cursor += size_in;\n\n \/\/ We're finished decompressing when zlib tells us.\n } while (ret != Z_STREAM_END);\n\n inflateEnd(&strm);\n}\n\n\n\/* DISALLOW_ALLOCATION *\/\nvoid VmServiceServer::operator delete(void* pointer) {\n fprintf(stderr, \"unreachable code\\n\");\n abort();\n}\n\n} \/\/ namespace bin\n} \/\/ namespace dart\n<commit_msg>Support for IPV6 for observatory in Dartium.<commit_after>\/\/ Copyright (c) 2015, the Dart project authors. Please see the AUTHORS file\n\/\/ for details. All rights reserved. Use of this source code is governed by a\n\/\/ BSD-style license that can be found in the LICENSE file.\n\n#include \"bin\/vmservice_dartium.h\"\n\n#include \"bin\/builtin.h\"\n#include \"bin\/dartutils.h\"\n#include \"bin\/eventhandler.h\"\n#include \"bin\/platform.h\"\n#include \"bin\/thread.h\"\n#include \"bin\/utils.h\"\n#include \"bin\/vmservice_impl.h\"\n#include \"zlib\/zlib.h\"\n\nnamespace dart {\nnamespace bin {\n\n#define CHECK_RESULT(result) \\\n if (Dart_IsError(result)) { \\\n fprintf(stderr, \"CHECK_RESULT failed: %s\", Dart_GetError(result)); \\\n Dart_ExitScope(); \\\n Dart_ShutdownIsolate(); \\\n return 0; \\\n }\n\nstatic const char* DART_IPV6_ONLY_FLAG = \"DART_IPV6_ONLY\";\nstatic const char* DEFAULT_VM_SERVICE_SERVER_IP_V6 = \"::1\";\nstatic const char* DEFAULT_VM_SERVICE_SERVER_IP_V4 = \"127.0.0.1\";\nstatic const int DEFAULT_VM_SERVICE_SERVER_PORT = 0;\n\nstatic bool IsIpv6Only() {\n char* v = getenv(DART_IPV6_ONLY_FLAG);\n if (!v) return 0;\n return v[0] == '1';\n}\n\nvoid VmServiceServer::Bootstrap() {\n if (!Platform::Initialize()) {\n fprintf(stderr, \"Platform::Initialize() failed\\n\");\n }\n DartUtils::SetOriginalWorkingDirectory();\n Thread::InitOnce();\n TimerUtils::InitOnce();\n EventHandler::Start();\n}\n\n\nDart_Isolate VmServiceServer::CreateIsolate(const uint8_t* snapshot_buffer) {\n ASSERT(snapshot_buffer != NULL);\n \/\/ Create the isolate.\n IsolateData* isolate_data =\n new IsolateData(DART_VM_SERVICE_ISOLATE_NAME, NULL, NULL, NULL);\n char* error = 0;\n Dart_Isolate isolate =\n Dart_CreateIsolate(DART_VM_SERVICE_ISOLATE_NAME, \"main\", snapshot_buffer,\n NULL, NULL, isolate_data, &error);\n if (!isolate) {\n fprintf(stderr, \"Dart_CreateIsolate failed: %s\\n\", error);\n return 0;\n }\n\n Dart_EnterScope();\n Builtin::SetNativeResolver(Builtin::kBuiltinLibrary);\n Builtin::SetNativeResolver(Builtin::kIOLibrary);\n\n ASSERT(Dart_IsServiceIsolate(isolate));\n if (!VmService::Setup(\n IsIpv6Only() ? DEFAULT_VM_SERVICE_SERVER_IP_V6 :\n DEFAULT_VM_SERVICE_SERVER_IP_V4,\n DEFAULT_VM_SERVICE_SERVER_PORT,\n false \/* running_precompiled *\/, false \/* disable origin checks *\/,\n false \/* trace_loading *\/)) {\n fprintf(stderr, \"Vmservice::Setup failed: %s\\n\",\n VmService::GetErrorMessage());\n isolate = NULL;\n }\n Dart_ExitScope();\n Dart_ExitIsolate();\n return isolate;\n}\n\n\nconst char* VmServiceServer::GetServerAddress() {\n return VmService::GetServerAddress();\n}\n\n\nvoid VmServiceServer::DecompressAssets(const uint8_t* input,\n unsigned int input_len,\n uint8_t** output,\n unsigned int* output_length) {\n ASSERT(input != NULL);\n ASSERT(input_len > 0);\n ASSERT(output != NULL);\n ASSERT(output_length != NULL);\n\n \/\/ Initialize output.\n *output = NULL;\n *output_length = 0;\n\n const unsigned int kChunkSize = 256 * 1024;\n uint8_t chunk_out[kChunkSize];\n z_stream strm;\n strm.zalloc = Z_NULL;\n strm.zfree = Z_NULL;\n strm.opaque = Z_NULL;\n strm.avail_in = 0;\n strm.next_in = 0;\n int ret = inflateInit2(&strm, 32 + MAX_WBITS);\n ASSERT(ret == Z_OK);\n\n unsigned int input_cursor = 0;\n unsigned int output_cursor = 0;\n do {\n \/\/ Setup input.\n unsigned int size_in = input_len - input_cursor;\n if (size_in > kChunkSize) {\n size_in = kChunkSize;\n }\n strm.avail_in = size_in;\n strm.next_in = const_cast<uint8_t*>(&input[input_cursor]);\n\n \/\/ Inflate until we've exhausted the current input chunk.\n do {\n \/\/ Setup output.\n strm.avail_out = kChunkSize;\n strm.next_out = &chunk_out[0];\n \/\/ Inflate.\n ret = inflate(&strm, Z_SYNC_FLUSH);\n \/\/ We either hit the end of the stream or made forward progress.\n ASSERT((ret == Z_STREAM_END) || (ret == Z_OK));\n \/\/ Grow output buffer size.\n unsigned int size_out = kChunkSize - strm.avail_out;\n *output_length += size_out;\n *output = reinterpret_cast<uint8_t*>(realloc(*output, *output_length));\n \/\/ Copy output.\n memmove(&((*output)[output_cursor]), &chunk_out[0], size_out);\n output_cursor += size_out;\n } while (strm.avail_out == 0);\n\n \/\/ We've processed size_in bytes.\n input_cursor += size_in;\n\n \/\/ We're finished decompressing when zlib tells us.\n } while (ret != Z_STREAM_END);\n\n inflateEnd(&strm);\n}\n\n\n\/* DISALLOW_ALLOCATION *\/\nvoid VmServiceServer::operator delete(void* pointer) {\n fprintf(stderr, \"unreachable code\\n\");\n abort();\n}\n\n} \/\/ namespace bin\n} \/\/ namespace dart\n<|endoftext|>"} {"text":"<commit_before><commit_msg>WaE: unreachable code<commit_after><|endoftext|>"} {"text":"<commit_before><commit_msg>TableRef: use relative references where appropriate<commit_after><|endoftext|>"} {"text":"<commit_before><commit_msg>loplugin:simplifybool<commit_after><|endoftext|>"} {"text":"<commit_before><commit_msg>in COUNT() use ConvertStringToValue() for literal string arguments<commit_after><|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: excimp8.hxx,v $\n *\n * $Revision: 1.60 $\n *\n * last change: $Author: rt $ $Date: 2005-03-29 13:43:11 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef _EXCIMP8_HXX\n#define _EXCIMP8_HXX\n\n#include <string.h>\n\n#ifndef _IMP_OP_HXX\n#include \"imp_op.hxx\"\n#endif\n#ifndef _ROOT_HXX\n#include \"root.hxx\"\n#endif\n#ifndef _EXCSCEN_HXX\n#include \"excscen.hxx\"\n#endif\n#ifndef _EXCDEFS_HXX\n#include \"excdefs.hxx\"\n#endif\n\n#ifndef SC_FTOOLS_HXX\n#include \"ftools.hxx\"\n#endif\n\nclass SotStorage;\n\nclass ScBaseCell;\nclass ScRangeList;\nclass ScDBData;\n\nclass ScfSimpleProgressBar;\n\nclass XclImpStream;\n\n\n\nclass ImportExcel8 : public ImportExcel\n{\n protected:\n ExcScenarioList aScenList;\n\n BOOL bObjSection;\n BOOL bHasBasic;\n\n void RecString( void ); \/\/ 0x07\n void Calccount( void ); \/\/ 0x0C\n void Delta( void ); \/\/ 0x10\n void Iteration( void ); \/\/ 0x11\n void Note( void ); \/\/ 0x1C\n void WinProtection( void ); \/\/ 0x19\n void Cont( void ); \/\/ 0x3C\n void Obj( void ); \/\/ 0x5D\n void Boundsheet( void ); \/\/ 0x85\n void FilterMode( void ); \/\/ 0x9B\n void AutoFilterInfo( void ); \/\/ 0x9D\n void AutoFilter( void ); \/\/ 0x9E\n void Scenman( void ); \/\/ 0xAE\n void Scenario( void ); \/\/ 0xAF\n void ReadBasic( void ); \/\/ 0xD3\n void Cellmerging( void ); \/\/ 0xE5 geraten...\n void Msodrawinggroup( void ); \/\/ 0xEB\n void Msodrawing( void ); \/\/ 0xEC\n void Msodrawingselection( void ); \/\/ 0xED\n void Labelsst( void ); \/\/ 0xFD\n\n void Txo( void ); \/\/ 0x01B6\n void Hlink( void ); \/\/ 0x01B8\n void Codename( BOOL bWBGlobals ); \/\/ 0x01BA\n void Dimensions( void ); \/\/ 0x0200\n\n void EndSheet( void );\n virtual void EndAllChartObjects( void ); \/\/ -> excobj.cxx\n virtual void PostDocLoad( void );\n\n \/** Post processes all Escher objects, and inserts them into the document. *\/\n void ApplyEscherObjects();\n\n public:\n ImportExcel8( XclImpRootData& rImpData );\n virtual ~ImportExcel8( void );\n\n virtual FltError Read( void );\n};\n\n\n\n\/\/___________________________________________________________________\n\/\/ classes AutoFilterData, AutoFilterBuffer\n\nclass XclImpAutoFilterData : private ExcRoot\n{\nprivate:\n ScDBData* pCurrDBData;\n ScQueryParam aParam;\n SCSIZE nFirstEmpty;\n BOOL bActive;\n BOOL bHasConflict;\n BOOL bCriteria;\n BOOL bAutoOrAdvanced;\n ScRange aCriteriaRange;\n String aFilterName;\n\n void CreateFromDouble( String& rStr, double fVal );\n void SetCellAttribs();\n void InsertQueryParam();\n void AmendAFName(const BOOL bUseUnNamed);\n\nprotected:\npublic:\n XclImpAutoFilterData(\n RootData* pRoot,\n const ScRange& rRange,\n const String& rName );\n\n inline bool IsActive() const { return bActive; }\n inline SCTAB Tab() const { return aParam.nTab; }\n inline SCCOL StartCol() const { return aParam.nCol1; }\n inline SCROW StartRow() const { return aParam.nRow1; }\n inline SCCOL EndCol() const { return aParam.nCol2; }\n inline SCROW EndRow() const { return aParam.nRow2; }\n\n void ReadAutoFilter( XclImpStream& rStrm );\n\n inline void Activate() { bActive = TRUE; }\n void SetAdvancedRange( const ScRange* pRange );\n void SetExtractPos( const ScAddress& rAddr );\n inline void SetAutoOrAdvanced() { bAutoOrAdvanced = TRUE; }\n void Apply( const BOOL bUseUnNamed = FALSE );\n void CreateScDBData( const BOOL bUseUnNamed );\n void EnableRemoveFilter();\n};\n\n\nclass XclImpAutoFilterBuffer : private List\n{\nprivate:\n UINT16 nAFActiveCount;\n\n inline XclImpAutoFilterData* _First() { return (XclImpAutoFilterData*) List::First(); }\n inline XclImpAutoFilterData* _Next() { return (XclImpAutoFilterData*) List::Next(); }\n\n inline void Append( XclImpAutoFilterData* pData )\n { List::Insert( pData, LIST_APPEND ); }\nprotected:\npublic:\n XclImpAutoFilterBuffer();\n virtual ~XclImpAutoFilterBuffer();\n\n void Insert( RootData* pRoot, const ScRange& rRange,\n const String& rName );\n void AddAdvancedRange( const ScRange& rRange );\n void AddExtractPos( const ScRange& rRange );\n void Apply();\n\n XclImpAutoFilterData* GetByTab( SCTAB nTab );\n inline void IncrementActiveAF() { nAFActiveCount++; }\n inline BOOL UseUnNamed() { return nAFActiveCount == 1; }\n};\n\n#endif\n\n<commit_msg>INTEGRATION: CWS ooo19126 (1.60.116); FILE MERGED 2005\/09\/05 15:02:39 rt 1.60.116.1: #i54170# Change license header: remove SISSL<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: excimp8.hxx,v $\n *\n * $Revision: 1.61 $\n *\n * last change: $Author: rt $ $Date: 2005-09-08 19:16:39 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef _EXCIMP8_HXX\n#define _EXCIMP8_HXX\n\n#include <string.h>\n\n#ifndef _IMP_OP_HXX\n#include \"imp_op.hxx\"\n#endif\n#ifndef _ROOT_HXX\n#include \"root.hxx\"\n#endif\n#ifndef _EXCSCEN_HXX\n#include \"excscen.hxx\"\n#endif\n#ifndef _EXCDEFS_HXX\n#include \"excdefs.hxx\"\n#endif\n\n#ifndef SC_FTOOLS_HXX\n#include \"ftools.hxx\"\n#endif\n\nclass SotStorage;\n\nclass ScBaseCell;\nclass ScRangeList;\nclass ScDBData;\n\nclass ScfSimpleProgressBar;\n\nclass XclImpStream;\n\n\n\nclass ImportExcel8 : public ImportExcel\n{\n protected:\n ExcScenarioList aScenList;\n\n BOOL bObjSection;\n BOOL bHasBasic;\n\n void RecString( void ); \/\/ 0x07\n void Calccount( void ); \/\/ 0x0C\n void Delta( void ); \/\/ 0x10\n void Iteration( void ); \/\/ 0x11\n void Note( void ); \/\/ 0x1C\n void WinProtection( void ); \/\/ 0x19\n void Cont( void ); \/\/ 0x3C\n void Obj( void ); \/\/ 0x5D\n void Boundsheet( void ); \/\/ 0x85\n void FilterMode( void ); \/\/ 0x9B\n void AutoFilterInfo( void ); \/\/ 0x9D\n void AutoFilter( void ); \/\/ 0x9E\n void Scenman( void ); \/\/ 0xAE\n void Scenario( void ); \/\/ 0xAF\n void ReadBasic( void ); \/\/ 0xD3\n void Cellmerging( void ); \/\/ 0xE5 geraten...\n void Msodrawinggroup( void ); \/\/ 0xEB\n void Msodrawing( void ); \/\/ 0xEC\n void Msodrawingselection( void ); \/\/ 0xED\n void Labelsst( void ); \/\/ 0xFD\n\n void Txo( void ); \/\/ 0x01B6\n void Hlink( void ); \/\/ 0x01B8\n void Codename( BOOL bWBGlobals ); \/\/ 0x01BA\n void Dimensions( void ); \/\/ 0x0200\n\n void EndSheet( void );\n virtual void EndAllChartObjects( void ); \/\/ -> excobj.cxx\n virtual void PostDocLoad( void );\n\n \/** Post processes all Escher objects, and inserts them into the document. *\/\n void ApplyEscherObjects();\n\n public:\n ImportExcel8( XclImpRootData& rImpData );\n virtual ~ImportExcel8( void );\n\n virtual FltError Read( void );\n};\n\n\n\n\/\/___________________________________________________________________\n\/\/ classes AutoFilterData, AutoFilterBuffer\n\nclass XclImpAutoFilterData : private ExcRoot\n{\nprivate:\n ScDBData* pCurrDBData;\n ScQueryParam aParam;\n SCSIZE nFirstEmpty;\n BOOL bActive;\n BOOL bHasConflict;\n BOOL bCriteria;\n BOOL bAutoOrAdvanced;\n ScRange aCriteriaRange;\n String aFilterName;\n\n void CreateFromDouble( String& rStr, double fVal );\n void SetCellAttribs();\n void InsertQueryParam();\n void AmendAFName(const BOOL bUseUnNamed);\n\nprotected:\npublic:\n XclImpAutoFilterData(\n RootData* pRoot,\n const ScRange& rRange,\n const String& rName );\n\n inline bool IsActive() const { return bActive; }\n inline SCTAB Tab() const { return aParam.nTab; }\n inline SCCOL StartCol() const { return aParam.nCol1; }\n inline SCROW StartRow() const { return aParam.nRow1; }\n inline SCCOL EndCol() const { return aParam.nCol2; }\n inline SCROW EndRow() const { return aParam.nRow2; }\n\n void ReadAutoFilter( XclImpStream& rStrm );\n\n inline void Activate() { bActive = TRUE; }\n void SetAdvancedRange( const ScRange* pRange );\n void SetExtractPos( const ScAddress& rAddr );\n inline void SetAutoOrAdvanced() { bAutoOrAdvanced = TRUE; }\n void Apply( const BOOL bUseUnNamed = FALSE );\n void CreateScDBData( const BOOL bUseUnNamed );\n void EnableRemoveFilter();\n};\n\n\nclass XclImpAutoFilterBuffer : private List\n{\nprivate:\n UINT16 nAFActiveCount;\n\n inline XclImpAutoFilterData* _First() { return (XclImpAutoFilterData*) List::First(); }\n inline XclImpAutoFilterData* _Next() { return (XclImpAutoFilterData*) List::Next(); }\n\n inline void Append( XclImpAutoFilterData* pData )\n { List::Insert( pData, LIST_APPEND ); }\nprotected:\npublic:\n XclImpAutoFilterBuffer();\n virtual ~XclImpAutoFilterBuffer();\n\n void Insert( RootData* pRoot, const ScRange& rRange,\n const String& rName );\n void AddAdvancedRange( const ScRange& rRange );\n void AddExtractPos( const ScRange& rRange );\n void Apply();\n\n XclImpAutoFilterData* GetByTab( SCTAB nTab );\n inline void IncrementActiveAF() { nAFActiveCount++; }\n inline BOOL UseUnNamed() { return nAFActiveCount == 1; }\n};\n\n#endif\n\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: excscen.hxx,v $\n *\n * $Revision: 1.6 $\n *\n * last change: $Author: rt $ $Date: 2005-09-08 19:17:11 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\n\n#ifndef _EXCSCEN_HXX\n#define _EXCSCEN_HXX\n\n#ifndef _SOLAR_H\n#include <tools\/solar.h>\n#endif\n#ifndef _LIST_HXX\n#include <tools\/list.hxx>\n#endif\n#ifndef _STRING_HXX\n#include <tools\/string.hxx>\n#endif\n\n\nstruct RootData;\nclass XclImpRoot;\nclass XclImpStream;\nclass ScDocument;\n\n\n\nclass ExcScenarioCell\n{\nprivate:\n String aValue;\npublic:\n const UINT16 nCol;\n const UINT16 nRow;\n\n ExcScenarioCell( const UINT16 nC, const UINT16 nR );\n void SetValue( const String& rVal );\n inline const String& GetValue( void ) const;\n};\n\n\n\n\nclass ExcScenario : protected List\n{\nprivate:\n friend class ExcScenarioList;\nprotected:\n String* pName;\n String* pComment;\n String* pUserName;\n UINT8 nProtected;\n\n const UINT16 nTab;\n\n void Apply( const XclImpRoot& rRoot, const BOOL bLast = FALSE );\npublic:\n ExcScenario( XclImpStream& rIn, const RootData& rRoot );\n virtual ~ExcScenario();\n};\n\n\n\n\nclass ExcScenarioList : protected List\n{\nprivate:\n UINT16 nLastScenario;\n inline ExcScenario* _First( void ) { return ( ExcScenario* ) List::First(); }\n inline ExcScenario* _Next( void ) { return ( ExcScenario* ) List::Next(); }\n inline ExcScenario* _Last( void ) { return ( ExcScenario* ) List::Last(); }\n inline ExcScenario* _Prev( void ) { return ( ExcScenario* ) List::Prev(); }\nprotected:\npublic:\n ExcScenarioList( void );\n virtual ~ExcScenarioList();\n\n inline void Append( ExcScenario* pNew );\n\n inline void SetLast( const UINT16 nIndex4Last );\n\n inline const ExcScenario* First( void );\n inline const ExcScenario* Next( void );\n\n List::Count;\n\n void Apply( const XclImpRoot& rRoot );\n};\n\n\n\n\ninline const String& ExcScenarioCell::GetValue( void ) const\n{\n return aValue;\n}\n\n\n\n\ninline ExcScenarioList::ExcScenarioList( void )\n{\n nLastScenario = 0;\n}\n\n\ninline void ExcScenarioList::Append( ExcScenario* p )\n{\n List::Insert( p, LIST_APPEND );\n}\n\n\ninline const ExcScenario* ExcScenarioList::First( void )\n{\n return ( const ExcScenario* ) List::First();\n}\n\n\ninline const ExcScenario* ExcScenarioList::Next( void )\n{\n return ( const ExcScenario* ) List::Next();\n}\n\n\ninline void ExcScenarioList::SetLast( const UINT16 n )\n{\n nLastScenario = n;\n}\n\n\n#endif\n\n<commit_msg>INTEGRATION: CWS calcwarnings (1.6.324); FILE MERGED 2006\/12\/01 14:42:05 dr 1.6.324.1: #i69284# remove compiler warnings for wntmsci10<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: excscen.hxx,v $\n *\n * $Revision: 1.7 $\n *\n * last change: $Author: vg $ $Date: 2007-02-27 12:32:52 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\n\n#ifndef _EXCSCEN_HXX\n#define _EXCSCEN_HXX\n\n#ifndef _SOLAR_H\n#include <tools\/solar.h>\n#endif\n#ifndef _LIST_HXX\n#include <tools\/list.hxx>\n#endif\n#ifndef _STRING_HXX\n#include <tools\/string.hxx>\n#endif\n\n\nstruct RootData;\nclass XclImpRoot;\nclass XclImpStream;\nclass ScDocument;\n\n\n\nclass ExcScenarioCell\n{\nprivate:\n String aValue;\npublic:\n const UINT16 nCol;\n const UINT16 nRow;\n\n ExcScenarioCell( const UINT16 nC, const UINT16 nR );\n void SetValue( const String& rVal );\n inline const String& GetValue( void ) const;\n};\n\n\n\n\nclass ExcScenario : protected List\n{\nprivate:\n friend class ExcScenarioList;\nprotected:\n String* pName;\n String* pComment;\n String* pUserName;\n UINT8 nProtected;\n\n const UINT16 nTab;\n\n void Apply( const XclImpRoot& rRoot, const BOOL bLast = FALSE );\npublic:\n ExcScenario( XclImpStream& rIn, const RootData& rRoot );\n virtual ~ExcScenario();\n};\n\n\n\n\nclass ExcScenarioList : protected List\n{\nprivate:\n UINT16 nLastScenario;\n inline ExcScenario* _First( void ) { return ( ExcScenario* ) List::First(); }\n inline ExcScenario* _Next( void ) { return ( ExcScenario* ) List::Next(); }\n inline ExcScenario* _Last( void ) { return ( ExcScenario* ) List::Last(); }\n inline ExcScenario* _Prev( void ) { return ( ExcScenario* ) List::Prev(); }\nprotected:\npublic:\n ExcScenarioList( void );\n virtual ~ExcScenarioList();\n\n inline void Append( ExcScenario* pNew );\n\n inline void SetLast( const UINT16 nIndex4Last );\n\n inline const ExcScenario* First( void );\n inline const ExcScenario* Next( void );\n\n using List::Count;\n\n void Apply( const XclImpRoot& rRoot );\n};\n\n\n\n\ninline const String& ExcScenarioCell::GetValue( void ) const\n{\n return aValue;\n}\n\n\n\n\ninline ExcScenarioList::ExcScenarioList( void )\n{\n nLastScenario = 0;\n}\n\n\ninline void ExcScenarioList::Append( ExcScenario* p )\n{\n List::Insert( p, LIST_APPEND );\n}\n\n\ninline const ExcScenario* ExcScenarioList::First( void )\n{\n return ( const ExcScenario* ) List::First();\n}\n\n\ninline const ExcScenario* ExcScenarioList::Next( void )\n{\n return ( const ExcScenario* ) List::Next();\n}\n\n\ninline void ExcScenarioList::SetLast( const UINT16 n )\n{\n nLastScenario = n;\n}\n\n\n#endif\n\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * $RCSfile: fusel2.cxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: mh $ $Date: 2000-12-07 10:03:57 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifdef PCH\n#include \"ui_pch.hxx\"\n#endif\n\n#pragma hdrstop\n\n\/\/ INCLUDE ---------------------------------------------------------------\n\n#include <svx\/svditer.hxx>\n#include <svx\/svdocapt.hxx>\n#include <svx\/svdpagv.hxx>\n#include <sfx2\/dispatch.hxx>\n#include <svx\/svdview.hxx>\n\n#include \"fusel.hxx\"\n#include \"tabvwsh.hxx\"\n#include \"document.hxx\"\n#include \"detfunc.hxx\"\n#include \"futext.hxx\"\n#include \"sc.hrc\"\n\n\/\/ -----------------------------------------------------------------------\n\ninline long Diff( const Point& rP1, const Point& rP2 )\n{\n long nX = rP1.X() - rP2.X();\n if (nX<0) nX = -nX;\n long nY = rP1.Y() - rP2.Y();\n if (nY<0) nY = -nY;\n return nX+nY;\n}\n\nBOOL FuSelection::TestDetective( SdrPageView* pPV, const Point& rPos )\n{\n if (!pPV)\n return FALSE;\n\n BOOL bFound = FALSE;\n SdrObjListIter aIter( *pPV->GetObjList(), IM_FLAT );\n SdrObject* pObject = aIter.Next();\n while (pObject && !bFound)\n {\n if (ScDetectiveFunc::IsNonAlienArrow( pObject ))\n {\n USHORT nHitLog = (USHORT) pWindow->PixelToLogic(\n Size(pView->GetHitTolerancePixel(),0)).Width();\n if ( pObject->IsHit( rPos, nHitLog ) )\n {\n ScViewData* pViewData = pViewShell->GetViewData();\n ScSplitPos ePos = pViewShell->FindWindow( pWindow );\n Point aLineStart = pObject->GetPoint(0);\n Point aLineEnd = pObject->GetPoint(1);\n Point aPixel = pWindow->LogicToPixel( aLineStart );\n short nStartCol;\n short nStartRow;\n pViewData->GetPosFromPixel( aPixel.X(), aPixel.Y(), ePos, nStartCol, nStartRow );\n aPixel = pWindow->LogicToPixel( aLineEnd );\n short nEndCol;\n short nEndRow;\n pViewData->GetPosFromPixel( aPixel.X(), aPixel.Y(), ePos, nEndCol, nEndRow );\n short nCurX = (short) pViewData->GetCurX();\n short nCurY = (short) pViewData->GetCurY();\n BOOL bStart = ( Diff( rPos,aLineStart ) > Diff( rPos,aLineEnd ) );\n if ( nCurX == nStartCol && nCurY == nStartRow )\n bStart = FALSE;\n else if ( nCurX == nEndCol && nCurY == nEndRow )\n bStart = TRUE;\n\n short nDifX;\n short nDifY;\n if ( bStart )\n {\n nDifX = nStartCol - nCurX;\n nDifY = nStartRow - nCurY;\n }\n else\n {\n nDifX = nEndCol - nCurX;\n nDifY = nEndRow - nCurY;\n }\n pViewShell->MoveCursorRel( nDifX, nDifY, SC_FOLLOW_JUMP, FALSE );\n\n bFound = TRUE;\n }\n }\n\n pObject = aIter.Next();\n }\n return bFound;\n}\n\nBOOL FuSelection::TestComment( SdrPageView* pPV, const Point& rPos )\n{\n if (!pPV)\n return FALSE;\n\n BOOL bFound = FALSE;\n SdrObjListIter aIter( *pPV->GetObjList(), IM_FLAT );\n SdrObject* pObject = aIter.Next();\n while (pObject && !bFound)\n {\n if ( pObject->GetLayer()==SC_LAYER_INTERN && pObject->ISA(SdrCaptionObj)\n && pObject->GetLogicRect().IsInside( rPos ) )\n {\n\/\/ SdrHdl* pHdl = pView->HitHandle( rPos, *pWindow );\n\/\/ BOOL bDrag = pView->BegDragObj( rPos, NULL, pHdl );\n\n pViewShell->GetViewData()->GetDispatcher().\n Execute(SID_DRAW_NOTEEDIT, SFX_CALLMODE_SYNCHRON | SFX_CALLMODE_RECORD);\n \/\/ jetzt den erzeugten FuText holen und in den EditModus setzen\n FuPoor* pPoor = pViewShell->GetViewData()->GetView()->GetDrawFuncPtr();\n if ( pPoor && pPoor->GetSlotID() == SID_DRAW_NOTEEDIT ) \/\/ hat keine RTTI\n {\n FuText* pText = (FuText*)pPoor;\n Point aPixel = pWindow->LogicToPixel( rPos );\n pText->SetInEditMode( pObject, &aPixel );\n }\n\n bFound = TRUE;\n }\n\n pObject = aIter.Next();\n }\n\n return bFound;\n}\n\n\/\/==================================================================\n\n\n\n\n<commit_msg>#78828# TestComment: handle overlapping notes<commit_after>\/*************************************************************************\n *\n * $RCSfile: fusel2.cxx,v $\n *\n * $Revision: 1.4 $\n *\n * last change: $Author: nn $ $Date: 2000-12-20 18:43:53 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifdef PCH\n#include \"ui_pch.hxx\"\n#endif\n\n#pragma hdrstop\n\n\/\/ INCLUDE ---------------------------------------------------------------\n\n#include <svx\/svditer.hxx>\n#include <svx\/svdocapt.hxx>\n#include <svx\/svdpagv.hxx>\n#include <sfx2\/dispatch.hxx>\n#include <svx\/svdview.hxx>\n#include <svx\/outliner.hxx>\n\n#include \"fusel.hxx\"\n#include \"tabvwsh.hxx\"\n#include \"document.hxx\"\n#include \"detfunc.hxx\"\n#include \"futext.hxx\"\n#include \"sc.hrc\"\n\n\/\/ -----------------------------------------------------------------------\n\ninline long Diff( const Point& rP1, const Point& rP2 )\n{\n long nX = rP1.X() - rP2.X();\n if (nX<0) nX = -nX;\n long nY = rP1.Y() - rP2.Y();\n if (nY<0) nY = -nY;\n return nX+nY;\n}\n\nBOOL FuSelection::TestDetective( SdrPageView* pPV, const Point& rPos )\n{\n if (!pPV)\n return FALSE;\n\n BOOL bFound = FALSE;\n SdrObjListIter aIter( *pPV->GetObjList(), IM_FLAT );\n SdrObject* pObject = aIter.Next();\n while (pObject && !bFound)\n {\n if (ScDetectiveFunc::IsNonAlienArrow( pObject ))\n {\n USHORT nHitLog = (USHORT) pWindow->PixelToLogic(\n Size(pView->GetHitTolerancePixel(),0)).Width();\n if ( pObject->IsHit( rPos, nHitLog ) )\n {\n ScViewData* pViewData = pViewShell->GetViewData();\n ScSplitPos ePos = pViewShell->FindWindow( pWindow );\n Point aLineStart = pObject->GetPoint(0);\n Point aLineEnd = pObject->GetPoint(1);\n Point aPixel = pWindow->LogicToPixel( aLineStart );\n short nStartCol;\n short nStartRow;\n pViewData->GetPosFromPixel( aPixel.X(), aPixel.Y(), ePos, nStartCol, nStartRow );\n aPixel = pWindow->LogicToPixel( aLineEnd );\n short nEndCol;\n short nEndRow;\n pViewData->GetPosFromPixel( aPixel.X(), aPixel.Y(), ePos, nEndCol, nEndRow );\n short nCurX = (short) pViewData->GetCurX();\n short nCurY = (short) pViewData->GetCurY();\n BOOL bStart = ( Diff( rPos,aLineStart ) > Diff( rPos,aLineEnd ) );\n if ( nCurX == nStartCol && nCurY == nStartRow )\n bStart = FALSE;\n else if ( nCurX == nEndCol && nCurY == nEndRow )\n bStart = TRUE;\n\n short nDifX;\n short nDifY;\n if ( bStart )\n {\n nDifX = nStartCol - nCurX;\n nDifY = nStartRow - nCurY;\n }\n else\n {\n nDifX = nEndCol - nCurX;\n nDifY = nEndRow - nCurY;\n }\n pViewShell->MoveCursorRel( nDifX, nDifY, SC_FOLLOW_JUMP, FALSE );\n\n bFound = TRUE;\n }\n }\n\n pObject = aIter.Next();\n }\n return bFound;\n}\n\nBOOL FuSelection::TestComment( SdrPageView* pPV, const Point& rPos )\n{\n if (!pPV)\n return FALSE;\n\n SdrObject* pFoundObj = NULL;\n\n SdrObjListIter aIter( *pPV->GetObjList(), IM_FLAT );\n SdrObject* pObject = aIter.Next();\n while (pObject)\n {\n if ( pObject->GetLayer()==SC_LAYER_INTERN && pObject->ISA(SdrCaptionObj)\n && pObject->GetLogicRect().IsInside( rPos ) )\n {\n pFoundObj = pObject;\n \/\/ keep searching - use the last matching object (on top)\n }\n pObject = aIter.Next();\n }\n\n if ( pFoundObj )\n {\n pViewShell->GetViewData()->GetDispatcher().\n Execute(SID_DRAW_NOTEEDIT, SFX_CALLMODE_SYNCHRON | SFX_CALLMODE_RECORD);\n \/\/ now get the created FuText and put in EditMode\n FuPoor* pPoor = pViewShell->GetViewData()->GetView()->GetDrawFuncPtr();\n if ( pPoor && pPoor->GetSlotID() == SID_DRAW_NOTEEDIT ) \/\/ no RTTI\n {\n FuText* pText = (FuText*)pPoor;\n Point aPixel = pWindow->LogicToPixel( rPos );\n pText->SetInEditMode( pFoundObj, &aPixel );\n }\n\n \/\/ repaint outliner view with background now\n\n OutlinerView* pOlView = pView->GetTextEditOutlinerView();\n if ( pOlView && pOlView->GetWindow() == pWindow )\n {\n Rectangle aEditRect = pOlView->GetOutputArea();\n pWindow->SetFillColor( pOlView->GetBackgroundColor() );\n pWindow->SetLineColor();\n pWindow->DrawRect( aEditRect );\n pOlView->Paint( aEditRect );\n }\n }\n\n return (pFoundObj != NULL);\n}\n\n\/\/==================================================================\n\n\n\n\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\/\n\/* navigation_agent_2d.cpp *\/\n\/*************************************************************************\/\n\/* This file is part of: *\/\n\/* GODOT ENGINE *\/\n\/* https:\/\/godotengine.org *\/\n\/*************************************************************************\/\n\/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. *\/\n\/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). *\/\n\/* *\/\n\/* Permission is hereby granted, free of charge, to any person obtaining *\/\n\/* a copy of this software and associated documentation files (the *\/\n\/* \"Software\"), to deal in the Software without restriction, including *\/\n\/* without limitation the rights to use, copy, modify, merge, publish, *\/\n\/* distribute, sublicense, and\/or sell copies of the Software, and to *\/\n\/* permit persons to whom the Software is furnished to do so, subject to *\/\n\/* the following conditions: *\/\n\/* *\/\n\/* The above copyright notice and this permission notice shall be *\/\n\/* included in all copies or substantial portions of the Software. *\/\n\/* *\/\n\/* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, *\/\n\/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF *\/\n\/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*\/\n\/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY *\/\n\/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, *\/\n\/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE *\/\n\/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *\/\n\/*************************************************************************\/\n\n#include \"navigation_agent_2d.h\"\n\n#include \"core\/config\/engine.h\"\n#include \"core\/math\/geometry_2d.h\"\n#include \"servers\/navigation_server_2d.h\"\n\nvoid NavigationAgent2D::_bind_methods() {\n\tClassDB::bind_method(D_METHOD(\"set_target_desired_distance\", \"desired_distance\"), &NavigationAgent2D::set_target_desired_distance);\n\tClassDB::bind_method(D_METHOD(\"get_target_desired_distance\"), &NavigationAgent2D::get_target_desired_distance);\n\n\tClassDB::bind_method(D_METHOD(\"set_radius\", \"radius\"), &NavigationAgent2D::set_radius);\n\tClassDB::bind_method(D_METHOD(\"get_radius\"), &NavigationAgent2D::get_radius);\n\n\tClassDB::bind_method(D_METHOD(\"set_neighbor_dist\", \"neighbor_dist\"), &NavigationAgent2D::set_neighbor_dist);\n\tClassDB::bind_method(D_METHOD(\"get_neighbor_dist\"), &NavigationAgent2D::get_neighbor_dist);\n\n\tClassDB::bind_method(D_METHOD(\"set_max_neighbors\", \"max_neighbors\"), &NavigationAgent2D::set_max_neighbors);\n\tClassDB::bind_method(D_METHOD(\"get_max_neighbors\"), &NavigationAgent2D::get_max_neighbors);\n\n\tClassDB::bind_method(D_METHOD(\"set_time_horizon\", \"time_horizon\"), &NavigationAgent2D::set_time_horizon);\n\tClassDB::bind_method(D_METHOD(\"get_time_horizon\"), &NavigationAgent2D::get_time_horizon);\n\n\tClassDB::bind_method(D_METHOD(\"set_max_speed\", \"max_speed\"), &NavigationAgent2D::set_max_speed);\n\tClassDB::bind_method(D_METHOD(\"get_max_speed\"), &NavigationAgent2D::get_max_speed);\n\n\tClassDB::bind_method(D_METHOD(\"set_path_max_distance\", \"max_speed\"), &NavigationAgent2D::set_path_max_distance);\n\tClassDB::bind_method(D_METHOD(\"get_path_max_distance\"), &NavigationAgent2D::get_path_max_distance);\n\n\tClassDB::bind_method(D_METHOD(\"set_target_location\", \"location\"), &NavigationAgent2D::set_target_location);\n\tClassDB::bind_method(D_METHOD(\"get_target_location\"), &NavigationAgent2D::get_target_location);\n\tClassDB::bind_method(D_METHOD(\"get_next_location\"), &NavigationAgent2D::get_next_location);\n\tClassDB::bind_method(D_METHOD(\"distance_to_target\"), &NavigationAgent2D::distance_to_target);\n\tClassDB::bind_method(D_METHOD(\"set_velocity\", \"velocity\"), &NavigationAgent2D::set_velocity);\n\tClassDB::bind_method(D_METHOD(\"get_nav_path\"), &NavigationAgent2D::get_nav_path);\n\tClassDB::bind_method(D_METHOD(\"get_nav_path_index\"), &NavigationAgent2D::get_nav_path_index);\n\tClassDB::bind_method(D_METHOD(\"is_target_reached\"), &NavigationAgent2D::is_target_reached);\n\tClassDB::bind_method(D_METHOD(\"is_target_reachable\"), &NavigationAgent2D::is_target_reachable);\n\tClassDB::bind_method(D_METHOD(\"is_navigation_finished\"), &NavigationAgent2D::is_navigation_finished);\n\tClassDB::bind_method(D_METHOD(\"get_final_location\"), &NavigationAgent2D::get_final_location);\n\n\tClassDB::bind_method(D_METHOD(\"_avoidance_done\", \"new_velocity\"), &NavigationAgent2D::_avoidance_done);\n\n\tADD_PROPERTY(PropertyInfo(Variant::FLOAT, \"target_desired_distance\", PROPERTY_HINT_RANGE, \"0.1,100,0.01\"), \"set_target_desired_distance\", \"get_target_desired_distance\");\n\tADD_PROPERTY(PropertyInfo(Variant::FLOAT, \"radius\", PROPERTY_HINT_RANGE, \"0.1,500,0.01\"), \"set_radius\", \"get_radius\");\n\tADD_PROPERTY(PropertyInfo(Variant::FLOAT, \"neighbor_dist\", PROPERTY_HINT_RANGE, \"0.1,100000,0.01\"), \"set_neighbor_dist\", \"get_neighbor_dist\");\n\tADD_PROPERTY(PropertyInfo(Variant::INT, \"max_neighbors\", PROPERTY_HINT_RANGE, \"1,10000,1\"), \"set_max_neighbors\", \"get_max_neighbors\");\n\tADD_PROPERTY(PropertyInfo(Variant::FLOAT, \"time_horizon\", PROPERTY_HINT_RANGE, \"0.1,10000,0.01\"), \"set_time_horizon\", \"get_time_horizon\");\n\tADD_PROPERTY(PropertyInfo(Variant::FLOAT, \"max_speed\", PROPERTY_HINT_RANGE, \"0.1,100000,0.01\"), \"set_max_speed\", \"get_max_speed\");\n\tADD_PROPERTY(PropertyInfo(Variant::FLOAT, \"path_max_distance\", PROPERTY_HINT_RANGE, \"10,100,1\"), \"set_path_max_distance\", \"get_path_max_distance\");\n\n\tADD_SIGNAL(MethodInfo(\"path_changed\"));\n\tADD_SIGNAL(MethodInfo(\"target_reached\"));\n\tADD_SIGNAL(MethodInfo(\"navigation_finished\"));\n\tADD_SIGNAL(MethodInfo(\"velocity_computed\", PropertyInfo(Variant::VECTOR3, \"safe_velocity\")));\n}\n\nvoid NavigationAgent2D::_notification(int p_what) {\n\tswitch (p_what) {\n\t\tcase NOTIFICATION_READY: {\n\t\t\tagent_parent = Object::cast_to<Node2D>(get_parent());\n\n\t\t\tNavigationServer2D::get_singleton()->agent_set_callback(agent, this, \"_avoidance_done\");\n\n\t\t\tset_physics_process_internal(true);\n\t\t} break;\n\t\tcase NOTIFICATION_EXIT_TREE: {\n\t\t\tagent_parent = nullptr;\n\t\t\tset_physics_process_internal(false);\n\t\t} break;\n\t\tcase NOTIFICATION_INTERNAL_PHYSICS_PROCESS: {\n\t\t\tif (agent_parent) {\n\t\t\t\tNavigationServer2D::get_singleton()->agent_set_position(agent, agent_parent->get_global_transform().get_origin());\n\t\t\t\tif (!target_reached) {\n\t\t\t\t\tif (distance_to_target() < target_desired_distance) {\n\t\t\t\t\t\temit_signal(\"target_reached\");\n\t\t\t\t\t\ttarget_reached = true;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t} break;\n\t}\n}\n\nNavigationAgent2D::NavigationAgent2D() {\n\tagent = NavigationServer2D::get_singleton()->agent_create();\n\tset_neighbor_dist(500.0);\n\tset_max_neighbors(10);\n\tset_time_horizon(20.0);\n\tset_radius(10.0);\n\tset_max_speed(200.0);\n}\n\nNavigationAgent2D::~NavigationAgent2D() {\n\tNavigationServer2D::get_singleton()->free(agent);\n\tagent = RID(); \/\/ Pointless\n}\n\nvoid NavigationAgent2D::set_navigable_layers(uint32_t p_layers) {\n\tnavigable_layers = p_layers;\n\tupdate_navigation();\n}\n\nuint32_t NavigationAgent2D::get_navigable_layers() const {\n\treturn navigable_layers;\n}\n\nvoid NavigationAgent2D::set_target_desired_distance(real_t p_dd) {\n\ttarget_desired_distance = p_dd;\n}\n\nvoid NavigationAgent2D::set_radius(real_t p_radius) {\n\tradius = p_radius;\n\tNavigationServer2D::get_singleton()->agent_set_radius(agent, radius);\n}\n\nvoid NavigationAgent2D::set_neighbor_dist(real_t p_dist) {\n\tneighbor_dist = p_dist;\n\tNavigationServer2D::get_singleton()->agent_set_neighbor_dist(agent, neighbor_dist);\n}\n\nvoid NavigationAgent2D::set_max_neighbors(int p_count) {\n\tmax_neighbors = p_count;\n\tNavigationServer2D::get_singleton()->agent_set_max_neighbors(agent, max_neighbors);\n}\n\nvoid NavigationAgent2D::set_time_horizon(real_t p_time) {\n\ttime_horizon = p_time;\n\tNavigationServer2D::get_singleton()->agent_set_time_horizon(agent, time_horizon);\n}\n\nvoid NavigationAgent2D::set_max_speed(real_t p_max_speed) {\n\tmax_speed = p_max_speed;\n\tNavigationServer2D::get_singleton()->agent_set_max_speed(agent, max_speed);\n}\n\nvoid NavigationAgent2D::set_path_max_distance(real_t p_pmd) {\n\tpath_max_distance = p_pmd;\n}\n\nreal_t NavigationAgent2D::get_path_max_distance() {\n\treturn path_max_distance;\n}\n\nvoid NavigationAgent2D::set_target_location(Vector2 p_location) {\n\ttarget_location = p_location;\n\tnavigation_path.clear();\n\ttarget_reached = false;\n\tnavigation_finished = false;\n\tupdate_frame_id = 0;\n}\n\nVector2 NavigationAgent2D::get_target_location() const {\n\treturn target_location;\n}\n\nVector2 NavigationAgent2D::get_next_location() {\n\tupdate_navigation();\n\tif (navigation_path.size() == 0) {\n\t\tERR_FAIL_COND_V(agent_parent == nullptr, Vector2());\n\t\treturn agent_parent->get_global_transform().get_origin();\n\t} else {\n\t\treturn navigation_path[nav_path_index];\n\t}\n}\n\nreal_t NavigationAgent2D::distance_to_target() const {\n\tERR_FAIL_COND_V(agent_parent == nullptr, 0.0);\n\treturn agent_parent->get_global_transform().get_origin().distance_to(target_location);\n}\n\nbool NavigationAgent2D::is_target_reached() const {\n\treturn target_reached;\n}\n\nbool NavigationAgent2D::is_target_reachable() {\n\treturn target_desired_distance >= get_final_location().distance_to(target_location);\n}\n\nbool NavigationAgent2D::is_navigation_finished() {\n\tupdate_navigation();\n\treturn navigation_finished;\n}\n\nVector2 NavigationAgent2D::get_final_location() {\n\tupdate_navigation();\n\tif (navigation_path.size() == 0) {\n\t\treturn Vector2();\n\t}\n\treturn navigation_path[navigation_path.size() - 1];\n}\n\nvoid NavigationAgent2D::set_velocity(Vector2 p_velocity) {\n\ttarget_velocity = p_velocity;\n\tNavigationServer2D::get_singleton()->agent_set_target_velocity(agent, target_velocity);\n\tNavigationServer2D::get_singleton()->agent_set_velocity(agent, prev_safe_velocity);\n\tvelocity_submitted = true;\n}\n\nvoid NavigationAgent2D::_avoidance_done(Vector3 p_new_velocity) {\n\tconst Vector2 velocity = Vector2(p_new_velocity.x, p_new_velocity.z);\n\tprev_safe_velocity = velocity;\n\n\tif (!velocity_submitted) {\n\t\ttarget_velocity = Vector2();\n\t\treturn;\n\t}\n\tvelocity_submitted = false;\n\n\temit_signal(\"velocity_computed\", velocity);\n}\n\nTypedArray<String> NavigationAgent2D::get_configuration_warnings() const {\n\tTypedArray<String> warnings = Node::get_configuration_warnings();\n\n\tif (!Object::cast_to<Node2D>(get_parent())) {\n\t\twarnings.push_back(TTR(\"The NavigationAgent2D can be used only under a Node2D node\"));\n\t}\n\n\treturn warnings;\n}\n\nvoid NavigationAgent2D::update_navigation() {\n\tif (agent_parent == nullptr) {\n\t\treturn;\n\t}\n\tif (!agent_parent->is_inside_tree()) {\n\t\treturn;\n\t}\n\tif (update_frame_id == Engine::get_singleton()->get_physics_frames()) {\n\t\treturn;\n\t}\n\n\tupdate_frame_id = Engine::get_singleton()->get_physics_frames();\n\n\tVector2 o = agent_parent->get_global_transform().get_origin();\n\n\tbool reload_path = false;\n\n\tif (NavigationServer2D::get_singleton()->agent_is_map_changed(agent)) {\n\t\treload_path = true;\n\t} else if (navigation_path.size() == 0) {\n\t\treload_path = true;\n\t} else {\n\t\t\/\/ Check if too far from the navigation path\n\t\tif (nav_path_index > 0) {\n\t\t\tVector2 segment[2];\n\t\t\tsegment[0] = navigation_path[nav_path_index - 1];\n\t\t\tsegment[1] = navigation_path[nav_path_index];\n\t\t\tVector2 p = Geometry2D::get_closest_point_to_segment(o, segment);\n\t\t\tif (o.distance_to(p) >= path_max_distance) {\n\t\t\t\t\/\/ To faraway, reload path\n\t\t\t\treload_path = true;\n\t\t\t}\n\t\t}\n\t}\n\n\tif (reload_path) {\n\t\tnavigation_path = NavigationServer2D::get_singleton()->map_get_path(agent_parent->get_world_2d()->get_navigation_map(), o, target_location, true, navigable_layers);\n\t\tnavigation_finished = false;\n\t\tnav_path_index = 0;\n\t\temit_signal(\"path_changed\");\n\t}\n\n\tif (navigation_path.size() == 0) {\n\t\treturn;\n\t}\n\n\t\/\/ Check if we can advance the navigation path\n\tif (navigation_finished == false) {\n\t\t\/\/ Advances to the next far away location.\n\t\twhile (o.distance_to(navigation_path[nav_path_index]) < target_desired_distance) {\n\t\t\tnav_path_index += 1;\n\t\t\tif (nav_path_index == navigation_path.size()) {\n\t\t\t\tnav_path_index -= 1;\n\t\t\t\tnavigation_finished = true;\n\t\t\t\temit_signal(\"navigation_finished\");\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n}\n<commit_msg>Fix NavigationAgent2D not emitting \"target_reached\" Signal reliably<commit_after>\/*************************************************************************\/\n\/* navigation_agent_2d.cpp *\/\n\/*************************************************************************\/\n\/* This file is part of: *\/\n\/* GODOT ENGINE *\/\n\/* https:\/\/godotengine.org *\/\n\/*************************************************************************\/\n\/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. *\/\n\/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). *\/\n\/* *\/\n\/* Permission is hereby granted, free of charge, to any person obtaining *\/\n\/* a copy of this software and associated documentation files (the *\/\n\/* \"Software\"), to deal in the Software without restriction, including *\/\n\/* without limitation the rights to use, copy, modify, merge, publish, *\/\n\/* distribute, sublicense, and\/or sell copies of the Software, and to *\/\n\/* permit persons to whom the Software is furnished to do so, subject to *\/\n\/* the following conditions: *\/\n\/* *\/\n\/* The above copyright notice and this permission notice shall be *\/\n\/* included in all copies or substantial portions of the Software. *\/\n\/* *\/\n\/* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, *\/\n\/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF *\/\n\/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*\/\n\/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY *\/\n\/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, *\/\n\/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE *\/\n\/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *\/\n\/*************************************************************************\/\n\n#include \"navigation_agent_2d.h\"\n\n#include \"core\/config\/engine.h\"\n#include \"core\/math\/geometry_2d.h\"\n#include \"servers\/navigation_server_2d.h\"\n\nvoid NavigationAgent2D::_bind_methods() {\n\tClassDB::bind_method(D_METHOD(\"set_target_desired_distance\", \"desired_distance\"), &NavigationAgent2D::set_target_desired_distance);\n\tClassDB::bind_method(D_METHOD(\"get_target_desired_distance\"), &NavigationAgent2D::get_target_desired_distance);\n\n\tClassDB::bind_method(D_METHOD(\"set_radius\", \"radius\"), &NavigationAgent2D::set_radius);\n\tClassDB::bind_method(D_METHOD(\"get_radius\"), &NavigationAgent2D::get_radius);\n\n\tClassDB::bind_method(D_METHOD(\"set_neighbor_dist\", \"neighbor_dist\"), &NavigationAgent2D::set_neighbor_dist);\n\tClassDB::bind_method(D_METHOD(\"get_neighbor_dist\"), &NavigationAgent2D::get_neighbor_dist);\n\n\tClassDB::bind_method(D_METHOD(\"set_max_neighbors\", \"max_neighbors\"), &NavigationAgent2D::set_max_neighbors);\n\tClassDB::bind_method(D_METHOD(\"get_max_neighbors\"), &NavigationAgent2D::get_max_neighbors);\n\n\tClassDB::bind_method(D_METHOD(\"set_time_horizon\", \"time_horizon\"), &NavigationAgent2D::set_time_horizon);\n\tClassDB::bind_method(D_METHOD(\"get_time_horizon\"), &NavigationAgent2D::get_time_horizon);\n\n\tClassDB::bind_method(D_METHOD(\"set_max_speed\", \"max_speed\"), &NavigationAgent2D::set_max_speed);\n\tClassDB::bind_method(D_METHOD(\"get_max_speed\"), &NavigationAgent2D::get_max_speed);\n\n\tClassDB::bind_method(D_METHOD(\"set_path_max_distance\", \"max_speed\"), &NavigationAgent2D::set_path_max_distance);\n\tClassDB::bind_method(D_METHOD(\"get_path_max_distance\"), &NavigationAgent2D::get_path_max_distance);\n\n\tClassDB::bind_method(D_METHOD(\"set_target_location\", \"location\"), &NavigationAgent2D::set_target_location);\n\tClassDB::bind_method(D_METHOD(\"get_target_location\"), &NavigationAgent2D::get_target_location);\n\tClassDB::bind_method(D_METHOD(\"get_next_location\"), &NavigationAgent2D::get_next_location);\n\tClassDB::bind_method(D_METHOD(\"distance_to_target\"), &NavigationAgent2D::distance_to_target);\n\tClassDB::bind_method(D_METHOD(\"set_velocity\", \"velocity\"), &NavigationAgent2D::set_velocity);\n\tClassDB::bind_method(D_METHOD(\"get_nav_path\"), &NavigationAgent2D::get_nav_path);\n\tClassDB::bind_method(D_METHOD(\"get_nav_path_index\"), &NavigationAgent2D::get_nav_path_index);\n\tClassDB::bind_method(D_METHOD(\"is_target_reached\"), &NavigationAgent2D::is_target_reached);\n\tClassDB::bind_method(D_METHOD(\"is_target_reachable\"), &NavigationAgent2D::is_target_reachable);\n\tClassDB::bind_method(D_METHOD(\"is_navigation_finished\"), &NavigationAgent2D::is_navigation_finished);\n\tClassDB::bind_method(D_METHOD(\"get_final_location\"), &NavigationAgent2D::get_final_location);\n\n\tClassDB::bind_method(D_METHOD(\"_avoidance_done\", \"new_velocity\"), &NavigationAgent2D::_avoidance_done);\n\n\tADD_PROPERTY(PropertyInfo(Variant::FLOAT, \"target_desired_distance\", PROPERTY_HINT_RANGE, \"0.1,100,0.01\"), \"set_target_desired_distance\", \"get_target_desired_distance\");\n\tADD_PROPERTY(PropertyInfo(Variant::FLOAT, \"radius\", PROPERTY_HINT_RANGE, \"0.1,500,0.01\"), \"set_radius\", \"get_radius\");\n\tADD_PROPERTY(PropertyInfo(Variant::FLOAT, \"neighbor_dist\", PROPERTY_HINT_RANGE, \"0.1,100000,0.01\"), \"set_neighbor_dist\", \"get_neighbor_dist\");\n\tADD_PROPERTY(PropertyInfo(Variant::INT, \"max_neighbors\", PROPERTY_HINT_RANGE, \"1,10000,1\"), \"set_max_neighbors\", \"get_max_neighbors\");\n\tADD_PROPERTY(PropertyInfo(Variant::FLOAT, \"time_horizon\", PROPERTY_HINT_RANGE, \"0.1,10000,0.01\"), \"set_time_horizon\", \"get_time_horizon\");\n\tADD_PROPERTY(PropertyInfo(Variant::FLOAT, \"max_speed\", PROPERTY_HINT_RANGE, \"0.1,100000,0.01\"), \"set_max_speed\", \"get_max_speed\");\n\tADD_PROPERTY(PropertyInfo(Variant::FLOAT, \"path_max_distance\", PROPERTY_HINT_RANGE, \"10,100,1\"), \"set_path_max_distance\", \"get_path_max_distance\");\n\n\tADD_SIGNAL(MethodInfo(\"path_changed\"));\n\tADD_SIGNAL(MethodInfo(\"target_reached\"));\n\tADD_SIGNAL(MethodInfo(\"navigation_finished\"));\n\tADD_SIGNAL(MethodInfo(\"velocity_computed\", PropertyInfo(Variant::VECTOR3, \"safe_velocity\")));\n}\n\nvoid NavigationAgent2D::_notification(int p_what) {\n\tswitch (p_what) {\n\t\tcase NOTIFICATION_READY: {\n\t\t\tagent_parent = Object::cast_to<Node2D>(get_parent());\n\n\t\t\tNavigationServer2D::get_singleton()->agent_set_callback(agent, this, \"_avoidance_done\");\n\n\t\t\tset_physics_process_internal(true);\n\t\t} break;\n\t\tcase NOTIFICATION_EXIT_TREE: {\n\t\t\tagent_parent = nullptr;\n\t\t\tset_physics_process_internal(false);\n\t\t} break;\n\t\tcase NOTIFICATION_INTERNAL_PHYSICS_PROCESS: {\n\t\t\tif (agent_parent) {\n\t\t\t\tNavigationServer2D::get_singleton()->agent_set_position(agent, agent_parent->get_global_transform().get_origin());\n\t\t\t\tif (!target_reached) {\n\t\t\t\t\tif (distance_to_target() < target_desired_distance) {\n\t\t\t\t\t\temit_signal(\"target_reached\");\n\t\t\t\t\t\ttarget_reached = true;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t} break;\n\t}\n}\n\nNavigationAgent2D::NavigationAgent2D() {\n\tagent = NavigationServer2D::get_singleton()->agent_create();\n\tset_neighbor_dist(500.0);\n\tset_max_neighbors(10);\n\tset_time_horizon(20.0);\n\tset_radius(10.0);\n\tset_max_speed(200.0);\n}\n\nNavigationAgent2D::~NavigationAgent2D() {\n\tNavigationServer2D::get_singleton()->free(agent);\n\tagent = RID(); \/\/ Pointless\n}\n\nvoid NavigationAgent2D::set_navigable_layers(uint32_t p_layers) {\n\tnavigable_layers = p_layers;\n\tupdate_navigation();\n}\n\nuint32_t NavigationAgent2D::get_navigable_layers() const {\n\treturn navigable_layers;\n}\n\nvoid NavigationAgent2D::set_target_desired_distance(real_t p_dd) {\n\ttarget_desired_distance = p_dd;\n}\n\nvoid NavigationAgent2D::set_radius(real_t p_radius) {\n\tradius = p_radius;\n\tNavigationServer2D::get_singleton()->agent_set_radius(agent, radius);\n}\n\nvoid NavigationAgent2D::set_neighbor_dist(real_t p_dist) {\n\tneighbor_dist = p_dist;\n\tNavigationServer2D::get_singleton()->agent_set_neighbor_dist(agent, neighbor_dist);\n}\n\nvoid NavigationAgent2D::set_max_neighbors(int p_count) {\n\tmax_neighbors = p_count;\n\tNavigationServer2D::get_singleton()->agent_set_max_neighbors(agent, max_neighbors);\n}\n\nvoid NavigationAgent2D::set_time_horizon(real_t p_time) {\n\ttime_horizon = p_time;\n\tNavigationServer2D::get_singleton()->agent_set_time_horizon(agent, time_horizon);\n}\n\nvoid NavigationAgent2D::set_max_speed(real_t p_max_speed) {\n\tmax_speed = p_max_speed;\n\tNavigationServer2D::get_singleton()->agent_set_max_speed(agent, max_speed);\n}\n\nvoid NavigationAgent2D::set_path_max_distance(real_t p_pmd) {\n\tpath_max_distance = p_pmd;\n}\n\nreal_t NavigationAgent2D::get_path_max_distance() {\n\treturn path_max_distance;\n}\n\nvoid NavigationAgent2D::set_target_location(Vector2 p_location) {\n\ttarget_location = p_location;\n\tnavigation_path.clear();\n\ttarget_reached = false;\n\tnavigation_finished = false;\n\tupdate_frame_id = 0;\n}\n\nVector2 NavigationAgent2D::get_target_location() const {\n\treturn target_location;\n}\n\nVector2 NavigationAgent2D::get_next_location() {\n\tupdate_navigation();\n\tif (navigation_path.size() == 0) {\n\t\tERR_FAIL_COND_V(agent_parent == nullptr, Vector2());\n\t\treturn agent_parent->get_global_transform().get_origin();\n\t} else {\n\t\treturn navigation_path[nav_path_index];\n\t}\n}\n\nreal_t NavigationAgent2D::distance_to_target() const {\n\tERR_FAIL_COND_V(agent_parent == nullptr, 0.0);\n\treturn agent_parent->get_global_transform().get_origin().distance_to(target_location);\n}\n\nbool NavigationAgent2D::is_target_reached() const {\n\treturn target_reached;\n}\n\nbool NavigationAgent2D::is_target_reachable() {\n\treturn target_desired_distance >= get_final_location().distance_to(target_location);\n}\n\nbool NavigationAgent2D::is_navigation_finished() {\n\tupdate_navigation();\n\treturn navigation_finished;\n}\n\nVector2 NavigationAgent2D::get_final_location() {\n\tupdate_navigation();\n\tif (navigation_path.size() == 0) {\n\t\treturn Vector2();\n\t}\n\treturn navigation_path[navigation_path.size() - 1];\n}\n\nvoid NavigationAgent2D::set_velocity(Vector2 p_velocity) {\n\ttarget_velocity = p_velocity;\n\tNavigationServer2D::get_singleton()->agent_set_target_velocity(agent, target_velocity);\n\tNavigationServer2D::get_singleton()->agent_set_velocity(agent, prev_safe_velocity);\n\tvelocity_submitted = true;\n}\n\nvoid NavigationAgent2D::_avoidance_done(Vector3 p_new_velocity) {\n\tconst Vector2 velocity = Vector2(p_new_velocity.x, p_new_velocity.z);\n\tprev_safe_velocity = velocity;\n\n\tif (!velocity_submitted) {\n\t\ttarget_velocity = Vector2();\n\t\treturn;\n\t}\n\tvelocity_submitted = false;\n\n\temit_signal(\"velocity_computed\", velocity);\n}\n\nTypedArray<String> NavigationAgent2D::get_configuration_warnings() const {\n\tTypedArray<String> warnings = Node::get_configuration_warnings();\n\n\tif (!Object::cast_to<Node2D>(get_parent())) {\n\t\twarnings.push_back(TTR(\"The NavigationAgent2D can be used only under a Node2D node\"));\n\t}\n\n\treturn warnings;\n}\n\nvoid NavigationAgent2D::update_navigation() {\n\tif (agent_parent == nullptr) {\n\t\treturn;\n\t}\n\tif (!agent_parent->is_inside_tree()) {\n\t\treturn;\n\t}\n\tif (update_frame_id == Engine::get_singleton()->get_physics_frames()) {\n\t\treturn;\n\t}\n\n\tupdate_frame_id = Engine::get_singleton()->get_physics_frames();\n\n\tVector2 o = agent_parent->get_global_transform().get_origin();\n\n\tbool reload_path = false;\n\n\tif (NavigationServer2D::get_singleton()->agent_is_map_changed(agent)) {\n\t\treload_path = true;\n\t} else if (navigation_path.size() == 0) {\n\t\treload_path = true;\n\t} else {\n\t\t\/\/ Check if too far from the navigation path\n\t\tif (nav_path_index > 0) {\n\t\t\tVector2 segment[2];\n\t\t\tsegment[0] = navigation_path[nav_path_index - 1];\n\t\t\tsegment[1] = navigation_path[nav_path_index];\n\t\t\tVector2 p = Geometry2D::get_closest_point_to_segment(o, segment);\n\t\t\tif (o.distance_to(p) >= path_max_distance) {\n\t\t\t\t\/\/ To faraway, reload path\n\t\t\t\treload_path = true;\n\t\t\t}\n\t\t}\n\t}\n\n\tif (reload_path) {\n\t\tnavigation_path = NavigationServer2D::get_singleton()->map_get_path(agent_parent->get_world_2d()->get_navigation_map(), o, target_location, true, navigable_layers);\n\t\tnavigation_finished = false;\n\t\tnav_path_index = 0;\n\t\temit_signal(\"path_changed\");\n\t}\n\n\tif (navigation_path.size() == 0) {\n\t\treturn;\n\t}\n\n\t\/\/ Check if we can advance the navigation path\n\tif (navigation_finished == false) {\n\t\t\/\/ Advances to the next far away location.\n\t\twhile (o.distance_to(navigation_path[nav_path_index]) < target_desired_distance) {\n\t\t\tnav_path_index += 1;\n\t\t\tif (nav_path_index == navigation_path.size()) {\n\t\t\t\tif (!target_reached) {\n\t\t\t\t\tif (distance_to_target() < target_desired_distance) {\n\t\t\t\t\t\temit_signal(\"target_reached\");\n\t\t\t\t\t\ttarget_reached = true;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tnav_path_index -= 1;\n\t\t\t\tnavigation_finished = true;\n\t\t\t\temit_signal(\"navigation_finished\");\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n}\n<|endoftext|>"} {"text":"<commit_before>#include \".\/OGL.h\"\n\nnamespace nme\n{\n\n\n\nbool gFullNPO2Support = false;\nbool gPartialNPO2Support = false;\n\nbool NonPO2Supported(bool inNotRepeating)\n{\n static bool tried = false;\n \n \/\/OpenGL 2.0 introduced non PO2 as standard, in 2004 - safe to assume it exists on PC\n #ifdef FORCE_NON_PO2\n return true;\n #endif\n\n if (!tried)\n {\n tried = true;\n const char* extensions = (char*) glGetString(GL_EXTENSIONS);\n\t \n\t gFullNPO2Support = strstr(extensions, \"ARB_texture_non_power_of_two\") != 0;\n\t \n\t if (!gFullNPO2Support)\n\t {\n\t\t gPartialNPO2Support = strstr(extensions, \"GL_APPLE_texture_2D_limited_npot\") != 0;\n\t }\n \n\t \n \/\/printf(\"Full non-PO2 support : %d\\n\", gFullNPO2Support);\n \/\/printf(\"Partial non-PO2 support : %d\\n\", gPartialNPO2Support);\n }\n\n return (gFullNPO2Support || (gPartialNPO2Support && inNotRepeating));\n}\n\n\nvoid RGBX_to_RGB565(uint8 *outDest, const uint8 *inSrc, int inPixels)\n{\n unsigned short *dest = (unsigned short *)outDest;\n const uint8 *src = inSrc;\n for(int x=0;x<inPixels;x++)\n {\n *dest++ = ( (src[0]<<8) & 0xf800 ) |\n ( (src[1]<<3) & 0x07e0 ) |\n ( (src[2]>>3) );\n src += 4;\n }\n}\n \n \nvoid RGBA_to_RGBA4444(uint8 *outDest, const uint8 *inSrc, int inPixels)\n{\n unsigned short *dest = (unsigned short *)outDest;\n const uint8 *src = inSrc;\n for(int x=0;x<inPixels;x++)\n {\n *dest++ = ( (src[0]<<8) & 0xf000 ) |\n ( (src[1]<<4) & 0x0f00 ) |\n ( (src[2] ) & 0x00f0 ) |\n ( (src[3]>>4) );\n src += 4;\n }\n}\n\nstatic int *sAlpha16Table = 0;\nint * getAlpha16Table()\n{\n if (sAlpha16Table==0)\n {\n sAlpha16Table = new int[256];\n for(int a=0;a<256;a++)\n sAlpha16Table[a] = a*(1<<16)\/255;\n }\n return sAlpha16Table;\n}\n\n\nclass OGLTexture : public Texture\n{\npublic:\n OGLTexture(Surface *inSurface,unsigned int inFlags)\n {\n mPixelWidth = inSurface->Width();\n mPixelHeight = inSurface->Height();\n mDirtyRect = Rect(0,0);\n mContextVersion = gTextureContextVersion;\n\n bool non_po2 = NonPO2Supported(inFlags & SURF_FLAGS_NOT_REPEAT_IF_NON_PO2);\n \/\/printf(\"Using non-power-of-2 texture %d\\n\",non_po2);\n\n int w = non_po2 ? mPixelWidth : UpToPower2(mPixelWidth);\n int h = non_po2 ? mPixelHeight : UpToPower2(mPixelHeight);\n mCanRepeat = IsPower2(w) && IsPower2(h);\n\n \/\/__android_log_print(ANDROID_LOG_ERROR, \"NME\", \"NewTexure %d %d\", w, h);\n\n mTextureWidth = w;\n mTextureHeight = h;\n bool usePreAlpha = inFlags & SURF_FLAGS_USE_PREMULTIPLIED_ALPHA;\n bool hasPreAlpha = inFlags & SURF_FLAGS_HAS_PREMULTIPLIED_ALPHA;\n int *multiplyAlpha = usePreAlpha && !hasPreAlpha ? getAlpha16Table() : 0;\n\n bool copy_required = inSurface->GetBase() &&\n (w!=mPixelWidth || h!=mPixelHeight || multiplyAlpha );\n\n Surface *load = inSurface;\n\n uint8 *buffer = 0;\n PixelFormat fmt = inSurface->Format();\n GLuint store_format = fmt==pfAlpha ? GL_ALPHA : GL_RGBA;\n int pixels = GL_UNSIGNED_BYTE;\n int gpuFormat = inSurface->GPUFormat();\n\n if (!inSurface->GetBase() )\n {\n if (gpuFormat!=fmt)\n switch(gpuFormat)\n {\n case pfARGB4444: pixels = GL_UNSIGNED_SHORT_4_4_4_4; break;\n case pfRGB565: pixels = GL_UNSIGNED_SHORT_5_6_5; break;\n default:\n pixels = gpuFormat;\n }\n }\n else if ( gpuFormat == pfARGB4444 )\n {\n pixels = GL_UNSIGNED_SHORT_4_4_4_4;\n buffer = (uint8 *)malloc( mTextureWidth * mTextureHeight * 2 );\n for(int y=0;y<mPixelHeight;y++)\n RGBA_to_RGBA4444(buffer+y*mTextureWidth*2, inSurface->Row(y),mPixelWidth);\n }\n else if ( gpuFormat == pfRGB565 )\n {\n pixels = GL_UNSIGNED_SHORT_5_6_5;\n buffer = (uint8 *)malloc( mTextureWidth * mTextureHeight * 2 );\n for(int y=0;y<mPixelHeight;y++)\n RGBX_to_RGB565(buffer+y*mTextureWidth*2, inSurface->Row(y),mPixelWidth);\n }\n else if (copy_required)\n {\n int pw = inSurface->Format()==pfAlpha ? 1 : 4;\n buffer = (uint8 *)malloc(pw * mTextureWidth * mTextureHeight);\n\n for(int y=0;y<mPixelHeight;y++)\n {\n const uint8 *src = inSurface->Row(y);\n uint8 *b= buffer + mTextureWidth*pw*y;\n if (multiplyAlpha)\n {\n for(int x=0;x<mPixelWidth;x++)\n {\n int a16 = multiplyAlpha[src[3]];\n b[0] = (src[0]*a16)>>16;\n b[1] = (src[1]*a16)>>16;\n b[2] = (src[2]*a16)>>16;\n b[3] = src[3];\n b+=4;\n src+=4;\n }\n }\n else\n {\n memcpy(b,src,mPixelWidth*pw);\n b+=mPixelWidth*pw;\n }\n \/\/ Duplucate last pixel to help with bilinear interp...\n if (w>mPixelWidth)\n memcpy(b,buffer+(mPixelWidth-1)*pw,pw);\n }\n \/\/ Duplucate last row to help with bilinear interp...\n if (h!=mPixelHeight)\n {\n uint8 *b= buffer + mTextureWidth*pw*mPixelHeight;\n uint8 *b0 = b - mTextureWidth*pw;\n memcpy(b,b0, (mPixelWidth + (w!=mPixelWidth))*pw);\n }\n }\n else\n {\n buffer = (uint8 *)inSurface->Row(0);\n }\n\n\n glGenTextures(1, &mTextureID);\n \/\/ __android_log_print(ANDROID_LOG_ERROR, \"NME\", \"CreateTexture %d (%dx%d)\",\n \/\/ mTextureID, mPixelWidth, mPixelHeight);\n glBindTexture(GL_TEXTURE_2D,mTextureID);\n mRepeat = mCanRepeat;\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, mRepeat ? GL_REPEAT : GL_CLAMP_TO_EDGE );\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, mRepeat ? GL_REPEAT : GL_CLAMP_TO_EDGE );\n\n\n glTexImage2D(GL_TEXTURE_2D, 0, store_format, w, h, 0, store_format, pixels, buffer);\n\n if (buffer && buffer!=inSurface->Row(0))\n free(buffer);\n\n\n mSmooth = true;\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);\n\n \/\/int err = glGetError();\n \/\/printf (\"GL texture error: %i\", err);\n }\n ~OGLTexture()\n {\n if (mTextureID && mContextVersion==gTextureContextVersion && HardwareContext::current)\n {\n \/\/__android_log_print(ANDROID_LOG_ERROR, \"NME\", \"DeleteTexture %d (%dx%d)\",\n \/\/mTextureID, mPixelWidth, mPixelHeight);\n HardwareContext::current->DestroyNativeTexture((void *)(size_t)mTextureID);\n }\n }\n\n void Bind(class Surface *inSurface,int inSlot)\n {\n if (inSlot>=0 && glActiveTexture)\n {\n glActiveTexture(GL_TEXTURE0 + inSlot);\n }\n glBindTexture(GL_TEXTURE_2D,mTextureID);\n if (gTextureContextVersion!=mContextVersion)\n {\n mContextVersion = gTextureContextVersion;\n mDirtyRect = Rect(inSurface->Width(),inSurface->Height());\n }\n if (inSurface->GetBase() && mDirtyRect.HasPixels())\n {\n \/\/__android_log_print(ANDROID_LOG_INFO, \"NME\", \"UpdateDirtyRect! %d %d\",\n \/\/mPixelWidth, mPixelHeight);\n\n PixelFormat fmt = inSurface->Format();\n int pw = inSurface->BytesPP();\n GLuint store_format = fmt==pfAlpha ? GL_ALPHA : GL_RGBA;\n glGetError();\n\n int x0 = mDirtyRect.x;\n int y0 = mDirtyRect.y;\n int dw = mDirtyRect.w;\n int dh = mDirtyRect.h;\n\n #if defined(NME_GLES)\n\n uint8 *buffer = 0;\n if (pw==1)\n {\n \/\/ Make unpack align a multiple of 4 ...\n if (inSurface->Width()>3)\n {\n dw = (dw + 3) & ~3;\n if (x0+dw>inSurface->Width())\n x0 = inSurface->Width()-dw;\n }\n\n const uint8 *p0 = inSurface->Row(y0) + x0*pw;\n buffer = (uint8 *)malloc(pw * dw * dh);\n for(int y=0;y<dh;y++)\n {\n memcpy(buffer + y*dw, p0, dw);\n p0 += inSurface->GetStride();\n }\n }\n else\n {\n \/\/ TODO: pre-alpha ?\n buffer = (uint8 *)malloc(pw * dw * dh);\n const uint8 *p0 = inSurface->Row(y0) + x0*pw;\n for(int y=0;y<mDirtyRect.h;y++)\n {\n memcpy(buffer + y*dw*pw, p0, dw*pw);\n p0 += inSurface->GetStride();\n }\n }\n\n glTexSubImage2D(GL_TEXTURE_2D, 0,\n x0, y0,\n dw, dh, \n store_format, GL_UNSIGNED_BYTE,\n buffer );\n free(buffer);\n #else\n const uint8 *p0 = inSurface->Row(y0) + x0*pw;\n glPixelStorei(GL_UNPACK_ROW_LENGTH, inSurface->Width());\n glTexSubImage2D(GL_TEXTURE_2D, 0,\n x0, y0,\n dw, dh,\n store_format, GL_UNSIGNED_BYTE,\n p0);\n glPixelStorei(GL_UNPACK_ROW_LENGTH,0);\n #endif\n int err = glGetError();\n if (err != GL_NO_ERROR) {\n ELOG(\"GL Error: %d %dx%d\", err, mDirtyRect.w, mDirtyRect.h);\n }\n mDirtyRect = Rect();\n }\n }\n\n void BindFlags(bool inRepeat,bool inSmooth)\n {\n if (!mCanRepeat) inRepeat = false;\n if (mRepeat!=inRepeat)\n {\n mRepeat = inRepeat;\n if (mRepeat)\n {\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT );\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT );\n }\n else\n {\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE );\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE );\n }\n }\n\n if (mSmooth!=inSmooth)\n {\n mSmooth = inSmooth;\n if (mSmooth)\n {\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);\n }\n else\n {\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);\n }\n }\n\n }\n\n\n UserPoint PixelToTex(const UserPoint &inPixels)\n {\n return UserPoint(inPixels.x\/mTextureWidth, inPixels.y\/mTextureHeight);\n }\n\n UserPoint TexToPaddedTex(const UserPoint &inTex)\n {\n return UserPoint(inTex.x*mPixelWidth\/mTextureWidth, inTex.y*mPixelHeight\/mTextureHeight);\n }\n\n\n\n GLuint mTextureID;\n bool mCanRepeat;\n bool mRepeat;\n bool mSmooth;\n int mPixelWidth;\n int mPixelHeight;\n int mTextureWidth;\n int mTextureHeight;\n};\n\n\nTexture *OGLCreateTexture(Surface *inSurface,unsigned int inFlags)\n{\n return new OGLTexture(inSurface,inFlags);\n}\n\n\n} \/\/ end namespace nme\n<commit_msg>Use macro to check extension<commit_after>#include \".\/OGL.h\"\n\nnamespace nme\n{\n\n\n\nbool gFullNPO2Support = false;\nbool gPartialNPO2Support = false;\n\nbool NonPO2Supported(bool inNotRepeating)\n{\n static bool tried = false;\n \n \/\/OpenGL 2.0 introduced non PO2 as standard, in 2004 - safe to assume it exists on PC\n #ifdef FORCE_NON_PO2\n return true;\n #endif\n\n if (!tried)\n {\n tried = true;\n const char* extensions = (char*) glGetString(GL_EXTENSIONS);\n\t \n\t gFullNPO2Support = strstr(extensions, \"ARB_texture_non_power_of_two\") != 0;\n\t \n\t if (!gFullNPO2Support)\n\t {\n\t\t gPartialNPO2Support = strstr(extensions, \"GL_APPLE_texture_2D_limited_npot\") != 0;\n\t }\n \n\t \n \/\/printf(\"Full non-PO2 support : %d\\n\", gFullNPO2Support);\n \/\/printf(\"Partial non-PO2 support : %d\\n\", gPartialNPO2Support);\n }\n\n return (gFullNPO2Support || (gPartialNPO2Support && inNotRepeating));\n}\n\n\nvoid RGBX_to_RGB565(uint8 *outDest, const uint8 *inSrc, int inPixels)\n{\n unsigned short *dest = (unsigned short *)outDest;\n const uint8 *src = inSrc;\n for(int x=0;x<inPixels;x++)\n {\n *dest++ = ( (src[0]<<8) & 0xf800 ) |\n ( (src[1]<<3) & 0x07e0 ) |\n ( (src[2]>>3) );\n src += 4;\n }\n}\n \n \nvoid RGBA_to_RGBA4444(uint8 *outDest, const uint8 *inSrc, int inPixels)\n{\n unsigned short *dest = (unsigned short *)outDest;\n const uint8 *src = inSrc;\n for(int x=0;x<inPixels;x++)\n {\n *dest++ = ( (src[0]<<8) & 0xf000 ) |\n ( (src[1]<<4) & 0x0f00 ) |\n ( (src[2] ) & 0x00f0 ) |\n ( (src[3]>>4) );\n src += 4;\n }\n}\n\nstatic int *sAlpha16Table = 0;\nint * getAlpha16Table()\n{\n if (sAlpha16Table==0)\n {\n sAlpha16Table = new int[256];\n for(int a=0;a<256;a++)\n sAlpha16Table[a] = a*(1<<16)\/255;\n }\n return sAlpha16Table;\n}\n\n\nclass OGLTexture : public Texture\n{\npublic:\n OGLTexture(Surface *inSurface,unsigned int inFlags)\n {\n mPixelWidth = inSurface->Width();\n mPixelHeight = inSurface->Height();\n mDirtyRect = Rect(0,0);\n mContextVersion = gTextureContextVersion;\n\n bool non_po2 = NonPO2Supported(inFlags & SURF_FLAGS_NOT_REPEAT_IF_NON_PO2);\n \/\/printf(\"Using non-power-of-2 texture %d\\n\",non_po2);\n\n int w = non_po2 ? mPixelWidth : UpToPower2(mPixelWidth);\n int h = non_po2 ? mPixelHeight : UpToPower2(mPixelHeight);\n mCanRepeat = IsPower2(w) && IsPower2(h);\n\n \/\/__android_log_print(ANDROID_LOG_ERROR, \"NME\", \"NewTexure %d %d\", w, h);\n\n mTextureWidth = w;\n mTextureHeight = h;\n bool usePreAlpha = inFlags & SURF_FLAGS_USE_PREMULTIPLIED_ALPHA;\n bool hasPreAlpha = inFlags & SURF_FLAGS_HAS_PREMULTIPLIED_ALPHA;\n int *multiplyAlpha = usePreAlpha && !hasPreAlpha ? getAlpha16Table() : 0;\n\n bool copy_required = inSurface->GetBase() &&\n (w!=mPixelWidth || h!=mPixelHeight || multiplyAlpha );\n\n Surface *load = inSurface;\n\n uint8 *buffer = 0;\n PixelFormat fmt = inSurface->Format();\n GLuint store_format = fmt==pfAlpha ? GL_ALPHA : GL_RGBA;\n int pixels = GL_UNSIGNED_BYTE;\n int gpuFormat = inSurface->GPUFormat();\n\n if (!inSurface->GetBase() )\n {\n if (gpuFormat!=fmt)\n switch(gpuFormat)\n {\n case pfARGB4444: pixels = GL_UNSIGNED_SHORT_4_4_4_4; break;\n case pfRGB565: pixels = GL_UNSIGNED_SHORT_5_6_5; break;\n default:\n pixels = gpuFormat;\n }\n }\n else if ( gpuFormat == pfARGB4444 )\n {\n pixels = GL_UNSIGNED_SHORT_4_4_4_4;\n buffer = (uint8 *)malloc( mTextureWidth * mTextureHeight * 2 );\n for(int y=0;y<mPixelHeight;y++)\n RGBA_to_RGBA4444(buffer+y*mTextureWidth*2, inSurface->Row(y),mPixelWidth);\n }\n else if ( gpuFormat == pfRGB565 )\n {\n pixels = GL_UNSIGNED_SHORT_5_6_5;\n buffer = (uint8 *)malloc( mTextureWidth * mTextureHeight * 2 );\n for(int y=0;y<mPixelHeight;y++)\n RGBX_to_RGB565(buffer+y*mTextureWidth*2, inSurface->Row(y),mPixelWidth);\n }\n else if (copy_required)\n {\n int pw = inSurface->Format()==pfAlpha ? 1 : 4;\n buffer = (uint8 *)malloc(pw * mTextureWidth * mTextureHeight);\n\n for(int y=0;y<mPixelHeight;y++)\n {\n const uint8 *src = inSurface->Row(y);\n uint8 *b= buffer + mTextureWidth*pw*y;\n if (multiplyAlpha)\n {\n for(int x=0;x<mPixelWidth;x++)\n {\n int a16 = multiplyAlpha[src[3]];\n b[0] = (src[0]*a16)>>16;\n b[1] = (src[1]*a16)>>16;\n b[2] = (src[2]*a16)>>16;\n b[3] = src[3];\n b+=4;\n src+=4;\n }\n }\n else\n {\n memcpy(b,src,mPixelWidth*pw);\n b+=mPixelWidth*pw;\n }\n \/\/ Duplucate last pixel to help with bilinear interp...\n if (w>mPixelWidth)\n memcpy(b,buffer+(mPixelWidth-1)*pw,pw);\n }\n \/\/ Duplucate last row to help with bilinear interp...\n if (h!=mPixelHeight)\n {\n uint8 *b= buffer + mTextureWidth*pw*mPixelHeight;\n uint8 *b0 = b - mTextureWidth*pw;\n memcpy(b,b0, (mPixelWidth + (w!=mPixelWidth))*pw);\n }\n }\n else\n {\n buffer = (uint8 *)inSurface->Row(0);\n }\n\n\n glGenTextures(1, &mTextureID);\n \/\/ __android_log_print(ANDROID_LOG_ERROR, \"NME\", \"CreateTexture %d (%dx%d)\",\n \/\/ mTextureID, mPixelWidth, mPixelHeight);\n glBindTexture(GL_TEXTURE_2D,mTextureID);\n mRepeat = mCanRepeat;\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, mRepeat ? GL_REPEAT : GL_CLAMP_TO_EDGE );\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, mRepeat ? GL_REPEAT : GL_CLAMP_TO_EDGE );\n\n\n glTexImage2D(GL_TEXTURE_2D, 0, store_format, w, h, 0, store_format, pixels, buffer);\n\n if (buffer && buffer!=inSurface->Row(0))\n free(buffer);\n\n\n mSmooth = true;\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);\n\n \/\/int err = glGetError();\n \/\/printf (\"GL texture error: %i\", err);\n }\n ~OGLTexture()\n {\n if (mTextureID && mContextVersion==gTextureContextVersion && HardwareContext::current)\n {\n \/\/__android_log_print(ANDROID_LOG_ERROR, \"NME\", \"DeleteTexture %d (%dx%d)\",\n \/\/mTextureID, mPixelWidth, mPixelHeight);\n HardwareContext::current->DestroyNativeTexture((void *)(size_t)mTextureID);\n }\n }\n\n void Bind(class Surface *inSurface,int inSlot)\n {\n if (inSlot>=0 && CHECK_EXT(glActiveTexture))\n {\n glActiveTexture(GL_TEXTURE0 + inSlot);\n }\n glBindTexture(GL_TEXTURE_2D,mTextureID);\n if (gTextureContextVersion!=mContextVersion)\n {\n mContextVersion = gTextureContextVersion;\n mDirtyRect = Rect(inSurface->Width(),inSurface->Height());\n }\n if (inSurface->GetBase() && mDirtyRect.HasPixels())\n {\n \/\/__android_log_print(ANDROID_LOG_INFO, \"NME\", \"UpdateDirtyRect! %d %d\",\n \/\/mPixelWidth, mPixelHeight);\n\n PixelFormat fmt = inSurface->Format();\n int pw = inSurface->BytesPP();\n GLuint store_format = fmt==pfAlpha ? GL_ALPHA : GL_RGBA;\n glGetError();\n\n int x0 = mDirtyRect.x;\n int y0 = mDirtyRect.y;\n int dw = mDirtyRect.w;\n int dh = mDirtyRect.h;\n\n #if defined(NME_GLES)\n\n uint8 *buffer = 0;\n if (pw==1)\n {\n \/\/ Make unpack align a multiple of 4 ...\n if (inSurface->Width()>3)\n {\n dw = (dw + 3) & ~3;\n if (x0+dw>inSurface->Width())\n x0 = inSurface->Width()-dw;\n }\n\n const uint8 *p0 = inSurface->Row(y0) + x0*pw;\n buffer = (uint8 *)malloc(pw * dw * dh);\n for(int y=0;y<dh;y++)\n {\n memcpy(buffer + y*dw, p0, dw);\n p0 += inSurface->GetStride();\n }\n }\n else\n {\n \/\/ TODO: pre-alpha ?\n buffer = (uint8 *)malloc(pw * dw * dh);\n const uint8 *p0 = inSurface->Row(y0) + x0*pw;\n for(int y=0;y<mDirtyRect.h;y++)\n {\n memcpy(buffer + y*dw*pw, p0, dw*pw);\n p0 += inSurface->GetStride();\n }\n }\n\n glTexSubImage2D(GL_TEXTURE_2D, 0,\n x0, y0,\n dw, dh, \n store_format, GL_UNSIGNED_BYTE,\n buffer );\n free(buffer);\n #else\n const uint8 *p0 = inSurface->Row(y0) + x0*pw;\n glPixelStorei(GL_UNPACK_ROW_LENGTH, inSurface->Width());\n glTexSubImage2D(GL_TEXTURE_2D, 0,\n x0, y0,\n dw, dh,\n store_format, GL_UNSIGNED_BYTE,\n p0);\n glPixelStorei(GL_UNPACK_ROW_LENGTH,0);\n #endif\n int err = glGetError();\n if (err != GL_NO_ERROR) {\n ELOG(\"GL Error: %d %dx%d\", err, mDirtyRect.w, mDirtyRect.h);\n }\n mDirtyRect = Rect();\n }\n }\n\n void BindFlags(bool inRepeat,bool inSmooth)\n {\n if (!mCanRepeat) inRepeat = false;\n if (mRepeat!=inRepeat)\n {\n mRepeat = inRepeat;\n if (mRepeat)\n {\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT );\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT );\n }\n else\n {\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE );\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE );\n }\n }\n\n if (mSmooth!=inSmooth)\n {\n mSmooth = inSmooth;\n if (mSmooth)\n {\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);\n }\n else\n {\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);\n }\n }\n\n }\n\n\n UserPoint PixelToTex(const UserPoint &inPixels)\n {\n return UserPoint(inPixels.x\/mTextureWidth, inPixels.y\/mTextureHeight);\n }\n\n UserPoint TexToPaddedTex(const UserPoint &inTex)\n {\n return UserPoint(inTex.x*mPixelWidth\/mTextureWidth, inTex.y*mPixelHeight\/mTextureHeight);\n }\n\n\n\n GLuint mTextureID;\n bool mCanRepeat;\n bool mRepeat;\n bool mSmooth;\n int mPixelWidth;\n int mPixelHeight;\n int mTextureWidth;\n int mTextureHeight;\n};\n\n\nTexture *OGLCreateTexture(Surface *inSurface,unsigned int inFlags)\n{\n return new OGLTexture(inSurface,inFlags);\n}\n\n\n} \/\/ end namespace nme\n<|endoftext|>"} {"text":"<commit_before>#include <nan.h>\n#include \"addon.h\"\n#include \"dvbtee-parser.h\"\n\nTableData::TableData(const uint8_t &tableId, const std::string &decoderName, const std::string &json)\n: tableId(tableId)\n, decoderName(decoderName)\n, json(json)\n{}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nuv_async_t TableReceiver::m_async;\n\nTableReceiver::TableReceiver(dvbteeParser *dvbteeParser)\n: m_dvbteeParser(dvbteeParser)\n{\n uv_mutex_init(&m_mutex);\n uv_async_init(uv_default_loop(), &m_async, completeCb);\n m_async.data = this;\n}\n\nTableReceiver::~TableReceiver()\n{\n uv_mutex_destroy(&m_mutex);\n}\n\nvoid TableReceiver::updateTable(uint8_t tId, dvbtee::decode::Table *table)\n{\n uv_mutex_lock(&m_mutex);\n v.push_back(new TableData(table->getTableid(), table->getDecoderName(), table->toJson()));\n uv_mutex_unlock(&m_mutex);\n\n uv_async_send(&m_async);\n}\n\nvoid TableReceiver::notify()\n{\n Nan::HandleScope scope;\n uv_mutex_lock(&m_mutex);\n for (std::vector<TableData*>::const_iterator it = v.begin(); it != v.end(); ++it)\n {\n TableData *data = *it;\n v8::Local<v8::String> jsonStr = Nan::New(data->json).ToLocalChecked();\n \n v8::Local<v8::Value> argv[] = {\n Nan::New(data->tableId),\n Nan::New(data->decoderName).ToLocalChecked(),\n v8::JSON::Parse(jsonStr)\n };\n m_dvbteeParser->m_cb_tableReceiver.Call(3, argv);\n\n delete data;\n }\n v.clear();\n uv_mutex_unlock(&m_mutex);\n}\n\nvoid TableReceiver::completeCb(uv_async_t *handle\n#if NODE_MODULE_VERSION<=11\n , int status \/*UNUSED*\/\n#endif\n )\n{\n TableReceiver* rcvr = static_cast<TableReceiver*>(handle->data);\n rcvr->notify();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nNan::Persistent<v8::Function> dvbteeParser::constructor;\n\ndvbteeParser::dvbteeParser(double value)\n: m_tableReceiver(this)\n, value_(value) {\n}\n\ndvbteeParser::~dvbteeParser() {\n}\n\nvoid dvbteeParser::Init(v8::Local<v8::Object> exports) {\n Nan::HandleScope scope;\n\n \/\/ Prepare constructor template\n v8::Local<v8::FunctionTemplate> tpl = Nan::New<v8::FunctionTemplate>(New);\n tpl->SetClassName(Nan::New(\"Parser\").ToLocalChecked());\n tpl->InstanceTemplate()->SetInternalFieldCount(1);\n\n \/\/ Prototype\n Nan::SetPrototypeMethod(tpl, \"reset\", reset);\n Nan::SetPrototypeMethod(tpl, \"push\", push);\n Nan::SetPrototypeMethod(tpl, \"listenTables\", listenTables);\n Nan::SetPrototypeMethod(tpl, \"logLevel\", logLevel);\n\n constructor.Reset(tpl->GetFunction());\n exports->Set(Nan::New(\"Parser\").ToLocalChecked(), tpl->GetFunction());\n}\n\nvoid dvbteeParser::New(const Nan::FunctionCallbackInfo<v8::Value>& info) {\n if (info.IsConstructCall()) {\n \/\/ Invoked as constructor: `new dvbteeParser(...)`\n double value = info[0]->IsUndefined() ? 0 : info[0]->NumberValue();\n dvbteeParser* obj = new dvbteeParser(value);\n obj->Wrap(info.This());\n info.GetReturnValue().Set(info.This());\n } else {\n \/\/ Invoked as plain function `dvbteeParser(...)`, turn into construct call.\n const int argc = 1;\n v8::Local<v8::Value> argv[argc] = { info[0] };\n v8::Local<v8::Function> cons = Nan::New<v8::Function>(constructor);\n info.GetReturnValue().Set(cons->NewInstance(argc, argv));\n }\n}\n\nvoid dvbteeParser::listenTables(const Nan::FunctionCallbackInfo<v8::Value>& info) {\n dvbteeParser* obj = ObjectWrap::Unwrap<dvbteeParser>(info.Holder());\n\n int lastArg = info.Length() - 1;\n\n if ((lastArg >= 0) && (info[lastArg]->IsFunction())) {\n obj->m_cb_tableReceiver.SetFunction(info[lastArg].As<v8::Function>());\n obj->m_parser.subscribeTables(&obj->m_tableReceiver);\n }\n\n info.GetReturnValue().Set(info.Holder());\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nclass ResetWorker : public Nan::AsyncWorker {\npublic:\n ResetWorker(Nan::Callback *callback, const Nan::FunctionCallbackInfo<v8::Value>& info)\n : Nan::AsyncWorker(callback)\n {\n m_obj = Nan::ObjectWrap::Unwrap<dvbteeParser>(info.Holder());\n }\n ~ResetWorker()\n {\n }\n\n \/\/ Executed inside the worker-thread.\n \/\/ It is not safe to access V8, or V8 data structures\n \/\/ here, so everything we need for input and output\n \/\/ should go on `this`.\n void Execute () {\n m_obj->m_parser.cleanup();\n m_obj->m_parser.reset();\n }\n\n \/\/ Executed when the async work is complete\n \/\/ this function will be run inside the main event loop\n \/\/ so it is safe to use V8 again\n void HandleOKCallback () {\n Nan::HandleScope scope;\n\n v8::Local<v8::Value> argv[] = {\n Nan::Null()\n , Nan::New<v8::Number>(0)\n };\n\n callback->Call(2, argv);\n }\n\nprivate:\n dvbteeParser* m_obj;\n};\n\nvoid dvbteeParser::reset(const Nan::FunctionCallbackInfo<v8::Value>& info) {\n\n int lastArg = info.Length() - 1;\n\n if ((lastArg >= 0) && (info[lastArg]->IsFunction())) {\n\n Nan::Callback *callback = new Nan::Callback(info[lastArg].As<v8::Function>());\n Nan::AsyncQueueWorker(new ResetWorker(callback, info));\n\n } else {\n dvbteeParser* obj = ObjectWrap::Unwrap<dvbteeParser>(info.Holder());\n\n obj->m_parser.cleanup();\n obj->m_parser.reset();\n\n info.GetReturnValue().Set(Nan::New(0));\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nclass PushWorker : public Nan::AsyncWorker {\npublic:\n PushWorker(Nan::Callback *callback, const Nan::FunctionCallbackInfo<v8::Value>& info)\n : Nan::AsyncWorker(callback)\n {\n m_obj = Nan::ObjectWrap::Unwrap<dvbteeParser>(info.Holder());\n\n if ((info[0]->IsObject()) && (info[1]->IsNumber())) {\n\n v8::Local<v8::Object> bufferObj = info[0]->ToObject();\n m_buf_len = info[1]->Uint32Value();\n m_buf = (char*) malloc(m_buf_len);\n\n memcpy(m_buf, node::Buffer::Data(bufferObj), m_buf_len);\n }\n }\n ~PushWorker()\n {\n if (m_buf) free(m_buf);\n }\n\n \/\/ Executed inside the worker-thread.\n \/\/ It is not safe to access V8, or V8 data structures\n \/\/ here, so everything we need for input and output\n \/\/ should go on `this`.\n void Execute () {\n m_ret = m_obj->m_parser.feed(m_buf_len, (uint8_t*)m_buf);\n free(m_buf);\n m_buf = NULL;\n }\n\n \/\/ Executed when the async work is complete\n \/\/ this function will be run inside the main event loop\n \/\/ so it is safe to use V8 again\n void HandleOKCallback () {\n Nan::HandleScope scope;\n\n v8::Local<v8::Value> argv[] = {\n Nan::Null()\n , Nan::New<v8::Number>(m_ret)\n };\n\n callback->Call(2, argv);\n }\n\nprivate:\n dvbteeParser* m_obj;\n char* m_buf;\n unsigned int m_buf_len;\n int m_ret;\n};\n\n\nvoid dvbteeParser::push(const Nan::FunctionCallbackInfo<v8::Value>& info) {\n\n int lastArg = info.Length() - 1;\n\n if ((lastArg >= 0) && (info[lastArg]->IsFunction())) {\n\n Nan::Callback *callback = new Nan::Callback(info[lastArg].As<v8::Function>());\n Nan::AsyncQueueWorker(new PushWorker(callback, info));\n\n } else {\n dvbteeParser* obj = ObjectWrap::Unwrap<dvbteeParser>(info.Holder());\n int ret = -1;\n\n if ((info[0]->IsObject()) && (info[1]->IsNumber())) {\n\n v8::Local<v8::Object> bufferObj = info[0]->ToObject();\n unsigned int len = info[1]->Uint32Value();\n const char* buf = node::Buffer::Data(bufferObj);\n\n ret = obj->m_parser.feed(len, (uint8_t*)buf);\n }\n\n info.GetReturnValue().Set(Nan::New(ret));\n }\n}\n<commit_msg>dvbtee-parser: add comments documenting the sync \/ async nature of push & reset<commit_after>#include <nan.h>\n#include \"addon.h\"\n#include \"dvbtee-parser.h\"\n\nTableData::TableData(const uint8_t &tableId, const std::string &decoderName, const std::string &json)\n: tableId(tableId)\n, decoderName(decoderName)\n, json(json)\n{}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nuv_async_t TableReceiver::m_async;\n\nTableReceiver::TableReceiver(dvbteeParser *dvbteeParser)\n: m_dvbteeParser(dvbteeParser)\n{\n uv_mutex_init(&m_mutex);\n uv_async_init(uv_default_loop(), &m_async, completeCb);\n m_async.data = this;\n}\n\nTableReceiver::~TableReceiver()\n{\n uv_mutex_destroy(&m_mutex);\n}\n\nvoid TableReceiver::updateTable(uint8_t tId, dvbtee::decode::Table *table)\n{\n uv_mutex_lock(&m_mutex);\n v.push_back(new TableData(table->getTableid(), table->getDecoderName(), table->toJson()));\n uv_mutex_unlock(&m_mutex);\n\n uv_async_send(&m_async);\n}\n\nvoid TableReceiver::notify()\n{\n Nan::HandleScope scope;\n uv_mutex_lock(&m_mutex);\n for (std::vector<TableData*>::const_iterator it = v.begin(); it != v.end(); ++it)\n {\n TableData *data = *it;\n v8::Local<v8::String> jsonStr = Nan::New(data->json).ToLocalChecked();\n \n v8::Local<v8::Value> argv[] = {\n Nan::New(data->tableId),\n Nan::New(data->decoderName).ToLocalChecked(),\n v8::JSON::Parse(jsonStr)\n };\n m_dvbteeParser->m_cb_tableReceiver.Call(3, argv);\n\n delete data;\n }\n v.clear();\n uv_mutex_unlock(&m_mutex);\n}\n\nvoid TableReceiver::completeCb(uv_async_t *handle\n#if NODE_MODULE_VERSION<=11\n , int status \/*UNUSED*\/\n#endif\n )\n{\n TableReceiver* rcvr = static_cast<TableReceiver*>(handle->data);\n rcvr->notify();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nNan::Persistent<v8::Function> dvbteeParser::constructor;\n\ndvbteeParser::dvbteeParser(double value)\n: m_tableReceiver(this)\n, value_(value) {\n}\n\ndvbteeParser::~dvbteeParser() {\n}\n\nvoid dvbteeParser::Init(v8::Local<v8::Object> exports) {\n Nan::HandleScope scope;\n\n \/\/ Prepare constructor template\n v8::Local<v8::FunctionTemplate> tpl = Nan::New<v8::FunctionTemplate>(New);\n tpl->SetClassName(Nan::New(\"Parser\").ToLocalChecked());\n tpl->InstanceTemplate()->SetInternalFieldCount(1);\n\n \/\/ Prototype\n Nan::SetPrototypeMethod(tpl, \"reset\", reset);\n Nan::SetPrototypeMethod(tpl, \"push\", push);\n Nan::SetPrototypeMethod(tpl, \"listenTables\", listenTables);\n Nan::SetPrototypeMethod(tpl, \"logLevel\", logLevel);\n\n constructor.Reset(tpl->GetFunction());\n exports->Set(Nan::New(\"Parser\").ToLocalChecked(), tpl->GetFunction());\n}\n\nvoid dvbteeParser::New(const Nan::FunctionCallbackInfo<v8::Value>& info) {\n if (info.IsConstructCall()) {\n \/\/ Invoked as constructor: `new dvbteeParser(...)`\n double value = info[0]->IsUndefined() ? 0 : info[0]->NumberValue();\n dvbteeParser* obj = new dvbteeParser(value);\n obj->Wrap(info.This());\n info.GetReturnValue().Set(info.This());\n } else {\n \/\/ Invoked as plain function `dvbteeParser(...)`, turn into construct call.\n const int argc = 1;\n v8::Local<v8::Value> argv[argc] = { info[0] };\n v8::Local<v8::Function> cons = Nan::New<v8::Function>(constructor);\n info.GetReturnValue().Set(cons->NewInstance(argc, argv));\n }\n}\n\nvoid dvbteeParser::listenTables(const Nan::FunctionCallbackInfo<v8::Value>& info) {\n dvbteeParser* obj = ObjectWrap::Unwrap<dvbteeParser>(info.Holder());\n\n int lastArg = info.Length() - 1;\n\n if ((lastArg >= 0) && (info[lastArg]->IsFunction())) {\n obj->m_cb_tableReceiver.SetFunction(info[lastArg].As<v8::Function>());\n obj->m_parser.subscribeTables(&obj->m_tableReceiver);\n }\n\n info.GetReturnValue().Set(info.Holder());\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nclass ResetWorker : public Nan::AsyncWorker {\npublic:\n ResetWorker(Nan::Callback *callback, const Nan::FunctionCallbackInfo<v8::Value>& info)\n : Nan::AsyncWorker(callback)\n {\n m_obj = Nan::ObjectWrap::Unwrap<dvbteeParser>(info.Holder());\n }\n ~ResetWorker()\n {\n }\n\n \/\/ Executed inside the worker-thread.\n \/\/ It is not safe to access V8, or V8 data structures\n \/\/ here, so everything we need for input and output\n \/\/ should go on `this`.\n void Execute () {\n m_obj->m_parser.cleanup();\n m_obj->m_parser.reset();\n }\n\n \/\/ Executed when the async work is complete\n \/\/ this function will be run inside the main event loop\n \/\/ so it is safe to use V8 again\n void HandleOKCallback () {\n Nan::HandleScope scope;\n\n v8::Local<v8::Value> argv[] = {\n Nan::Null()\n , Nan::New<v8::Number>(0)\n };\n\n callback->Call(2, argv);\n }\n\nprivate:\n dvbteeParser* m_obj;\n};\n\nvoid dvbteeParser::reset(const Nan::FunctionCallbackInfo<v8::Value>& info) {\n\n \/\/ If a callback function is supplied, this method will run async\n \/\/ otherwise, it will run synchronous\n\n int lastArg = info.Length() - 1;\n\n if ((lastArg >= 0) && (info[lastArg]->IsFunction())) {\n\n Nan::Callback *callback = new Nan::Callback(info[lastArg].As<v8::Function>());\n Nan::AsyncQueueWorker(new ResetWorker(callback, info));\n\n } else {\n dvbteeParser* obj = ObjectWrap::Unwrap<dvbteeParser>(info.Holder());\n\n obj->m_parser.cleanup();\n obj->m_parser.reset();\n\n info.GetReturnValue().Set(Nan::New(0));\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nclass PushWorker : public Nan::AsyncWorker {\npublic:\n PushWorker(Nan::Callback *callback, const Nan::FunctionCallbackInfo<v8::Value>& info)\n : Nan::AsyncWorker(callback)\n {\n m_obj = Nan::ObjectWrap::Unwrap<dvbteeParser>(info.Holder());\n\n if ((info[0]->IsObject()) && (info[1]->IsNumber())) {\n\n v8::Local<v8::Object> bufferObj = info[0]->ToObject();\n m_buf_len = info[1]->Uint32Value();\n m_buf = (char*) malloc(m_buf_len);\n\n memcpy(m_buf, node::Buffer::Data(bufferObj), m_buf_len);\n }\n }\n ~PushWorker()\n {\n if (m_buf) free(m_buf);\n }\n\n \/\/ Executed inside the worker-thread.\n \/\/ It is not safe to access V8, or V8 data structures\n \/\/ here, so everything we need for input and output\n \/\/ should go on `this`.\n void Execute () {\n m_ret = m_obj->m_parser.feed(m_buf_len, (uint8_t*)m_buf);\n free(m_buf);\n m_buf = NULL;\n }\n\n \/\/ Executed when the async work is complete\n \/\/ this function will be run inside the main event loop\n \/\/ so it is safe to use V8 again\n void HandleOKCallback () {\n Nan::HandleScope scope;\n\n v8::Local<v8::Value> argv[] = {\n Nan::Null()\n , Nan::New<v8::Number>(m_ret)\n };\n\n callback->Call(2, argv);\n }\n\nprivate:\n dvbteeParser* m_obj;\n char* m_buf;\n unsigned int m_buf_len;\n int m_ret;\n};\n\n\nvoid dvbteeParser::push(const Nan::FunctionCallbackInfo<v8::Value>& info) {\n\n \/\/ If a callback function is supplied, this method will run async\n \/\/ otherwise, it will run synchronous\n \/\/\n \/\/ Note: when packets are pushed to the parser, the parser will start\n \/\/ generating async events containing PSIP table data regardless of\n \/\/ whether this function was called synchronously or not\n\n int lastArg = info.Length() - 1;\n\n if ((lastArg >= 0) && (info[lastArg]->IsFunction())) {\n\n Nan::Callback *callback = new Nan::Callback(info[lastArg].As<v8::Function>());\n Nan::AsyncQueueWorker(new PushWorker(callback, info));\n\n } else {\n dvbteeParser* obj = ObjectWrap::Unwrap<dvbteeParser>(info.Holder());\n int ret = -1;\n\n if ((info[0]->IsObject()) && (info[1]->IsNumber())) {\n\n v8::Local<v8::Object> bufferObj = info[0]->ToObject();\n unsigned int len = info[1]->Uint32Value();\n const char* buf = node::Buffer::Data(bufferObj);\n\n ret = obj->m_parser.feed(len, (uint8_t*)buf);\n }\n\n info.GetReturnValue().Set(Nan::New(ret));\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (C) 2010, Gostai S.A.S.\n *\n * This software is provided \"as is\" without warranty of any kind,\n * either expressed or implied, including but not limited to the\n * implied warranties of fitness for a particular purpose.\n *\n * See the LICENSE file for more information.\n *\/\n#include <libport\/debug.hh>\n#include <jni.h>\n#include \"urbi_Log.h\"\n\nGD_INIT();\n\nJNIEXPORT void JNICALL\nJava_urbi_Log_info (JNIEnv *env,jobject, jstring category, jstring msg, jstring functionname, jstring filename, jint linenumber)\n{\n const char* msg_ = env->GetStringUTFChars(msg, 0);\n const char* functionname_ = env->GetStringUTFChars(functionname, 0);\n const char* filename_ = env->GetStringUTFChars(filename, 0);\n const char*category_ = env->GetStringUTFChars(category, 0);\n libport::debug::category_type _libport_gd_category = ::libport::debug::add_category(::libport::debug::category_type(category_));\n if (libport::debugger()->enabled(::libport::Debug::levels::debug, _libport_gd_category))\n libport::debugger()->debug(msg_, ::libport::Debug::types::info, _libport_gd_category, functionname_, filename_, (int) linenumber);\n env->ReleaseStringUTFChars(msg, msg_);\n env->ReleaseStringUTFChars(functionname, functionname_);\n env->ReleaseStringUTFChars(filename, filename_);\n env->ReleaseStringUTFChars(category, category_);\n}\n\nJNIEXPORT void JNICALL\nJava_urbi_Log_error (JNIEnv *env,jobject, jstring category, jstring msg, jstring functionname, jstring filename, jint linenumber)\n{\n const char* msg_ = env->GetStringUTFChars(msg, 0);\n const char* functionname_ = env->GetStringUTFChars(functionname, 0);\n const char* filename_ = env->GetStringUTFChars(filename, 0);\n const char*category_ = env->GetStringUTFChars(category, 0);\n ::libport::debug::category_type _libport_gd_category = ::libport::debug::add_category(::libport::debug::category_type(category_));\n if (libport::debugger()->enabled(::libport::Debug::levels::log, _libport_gd_category))\n libport::debugger()->debug(msg_, ::libport::Debug::types::error, _libport_gd_category, functionname_, filename_, (int) linenumber);\n env->ReleaseStringUTFChars(msg, msg_);\n env->ReleaseStringUTFChars(functionname, functionname_);\n env->ReleaseStringUTFChars(filename, filename_);\n env->ReleaseStringUTFChars(category, category_);\n}\n<commit_msg>UObject java: fix GD usage.<commit_after>\/*\n * Copyright (C) 2010, Gostai S.A.S.\n *\n * This software is provided \"as is\" without warranty of any kind,\n * either expressed or implied, including but not limited to the\n * implied warranties of fitness for a particular purpose.\n *\n * See the LICENSE file for more information.\n *\/\n#include <libport\/debug.hh>\n#include <jni.h>\n#include \"urbi_Log.h\"\n\nGD_INIT();\n\nJNIEXPORT void JNICALL\nJava_urbi_Log_info (JNIEnv *env,jobject, jstring category, jstring msg, jstring functionname, jstring filename, jint linenumber)\n{\n const char* msg_ = env->GetStringUTFChars(msg, 0);\n const char* functionname_ = env->GetStringUTFChars(functionname, 0);\n const char* filename_ = env->GetStringUTFChars(filename, 0);\n const char*category_ = env->GetStringUTFChars(category, 0);\n libport::debug::category_type _libport_gd_category = ::libport::debug::add_category(::libport::debug::category_type(category_));\n if (GD_DEBUGGER->enabled(::libport::Debug::levels::debug, _libport_gd_category))\n GD_DEBUGGER->debug(msg_, ::libport::Debug::types::info, _libport_gd_category, functionname_, filename_, (int) linenumber);\n env->ReleaseStringUTFChars(msg, msg_);\n env->ReleaseStringUTFChars(functionname, functionname_);\n env->ReleaseStringUTFChars(filename, filename_);\n env->ReleaseStringUTFChars(category, category_);\n}\n\nJNIEXPORT void JNICALL\nJava_urbi_Log_error (JNIEnv *env,jobject, jstring category, jstring msg, jstring functionname, jstring filename, jint linenumber)\n{\n const char* msg_ = env->GetStringUTFChars(msg, 0);\n const char* functionname_ = env->GetStringUTFChars(functionname, 0);\n const char* filename_ = env->GetStringUTFChars(filename, 0);\n const char*category_ = env->GetStringUTFChars(category, 0);\n ::libport::debug::category_type _libport_gd_category = ::libport::debug::add_category(::libport::debug::category_type(category_));\n if (GD_DEBUGGER->enabled(::libport::Debug::levels::log, _libport_gd_category))\n GD_DEBUGGER->debug(msg_, ::libport::Debug::types::error, _libport_gd_category, functionname_, filename_, (int) linenumber);\n env->ReleaseStringUTFChars(msg, msg_);\n env->ReleaseStringUTFChars(functionname, functionname_);\n env->ReleaseStringUTFChars(filename, filename_);\n env->ReleaseStringUTFChars(category, category_);\n}\n<|endoftext|>"} {"text":"<commit_before>\/*****************************************************************************\n * common.hpp: Basic shared types & helpers\n *****************************************************************************\n * Copyright © 2015 libvlcpp authors & VideoLAN\n *\n * Authors: Hugo Beauzée-Luyssen <hugo@beauzee.fr>\n * Jonathan Calmels <exxo@videolabs.io>\n *\n * This program is free software; you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License as published by\n * the Free Software Foundation; either version 2.1 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.\n *****************************************************************************\/\n\n#ifndef LIBVLC_CXX_COMMON_H\n#define LIBVLC_CXX_COMMON_H\n\n#include <vlc\/vlc.h>\n#include <array>\n#include <cassert>\n#include <memory>\n\nnamespace VLC\n{\n class Media;\n using MediaPtr = std::shared_ptr<Media>;\n\n \/\/ Work around cross class dependencies\n \/\/ Class A needs to access B's internal pointer\n \/\/ Class B needs to access A's internal pointer\n \/\/ By using a template function to do this, we're delegating\n \/\/ the access to both classes' guts to a later point, when the compiler\n \/\/ already knows everything it needs.\n \/\/ The only drawback is that we can't return decltype(ptr->get()), since when\n \/\/ the compiler checks for the prototype, it hasn't parsed all the declarations yet.\n template <typename TYPE, typename REF>\n TYPE* getInternalPtr(const REF& ref)\n {\n return ref.get();\n }\n\n inline std::unique_ptr<char, void (*)(void*)> wrapCStr(char* str)\n {\n return std::unique_ptr<char, void(*)(void*)>( str, [](void* ptr) { libvlc_free(ptr); } );\n }\n\n#if !defined(_MSC_VER)\n \/\/ Kudos to 3xxO for the signature_match helper\n template <typename, typename, typename = void>\n struct signature_match : std::false_type {};\n\n template <typename Func, typename Ret, typename... Args>\n struct signature_match<Func, Ret(Args...),\n typename std::enable_if<\n std::is_convertible<\n decltype(std::declval<Func>()(std::declval<Args>()...)),\n Ret\n >::value \/\/ true or false\n >::type \/\/ void or SFINAE\n > : std::true_type {};\n#else\n template <typename... Args>\n struct signature_match : std::false_type {};\n\n template <typename Func, typename Ret, class... Args>\n struct signature_match<Func, Ret(Args...)>\n : std::integral_constant < bool,\n std::is_convertible < decltype(std::declval<Func>()(std::declval<Args>()...)), Ret\n > ::value\n > {};\n#endif\n\n template <typename Func, typename Ret, typename... Args>\n struct signature_match_or_nullptr : std::integral_constant<bool,\n signature_match<Func, Ret, Args...>::value ||\n std::is_same<Func, std::nullptr_t>::value\n >\n {\n };\n\n struct CallbackHandlerBase\n {\n virtual ~CallbackHandlerBase() = default;\n };\n\n template <typename Func>\n struct CallbackHandler : public CallbackHandlerBase\n {\n CallbackHandler(Func&& f) : func( std::forward<Func>( f ) ) {}\n Func func;\n };\n\n template <int NbEvent>\n struct EventOwner\n {\n std::array<std::shared_ptr<CallbackHandlerBase>, NbEvent> callbacks;\n\n protected:\n EventOwner() = default;\n };\n\n template <int, typename>\n struct FromOpaque;\n\n template <int NbEvents>\n struct FromOpaque<NbEvents, void*>\n {\n static EventOwner<NbEvents>* get(void* opaque)\n {\n return reinterpret_cast<EventOwner<NbEvents>*>( opaque );\n }\n };\n\n template <int NbEvents>\n struct FromOpaque<NbEvents, void**>\n {\n static EventOwner<NbEvents>* get(void** opaque)\n {\n return reinterpret_cast<EventOwner<NbEvents>*>( *opaque );\n }\n };\n\n template <int Idx, typename... Args>\n struct CallbackWrapper;\n\n \/\/ We assume that any callback will take a void*\/void** opaque as its first parameter.\n \/\/ We intercept this parameter, and use it to fetch the list of user provided\n \/\/ functions. Once we know what function to call, we forward the rest of the\n \/\/ parameters.\n \/\/ Using partial specialization also allows us to get the list of the expected\n \/\/ callback parameters automatically, rather than having to specify them.\n template <int Idx, typename Ret, typename Opaque, typename... Args>\n struct CallbackWrapper<Idx, Ret(*)(Opaque, Args...)>\n {\n using Wrapped = Ret(Opaque, Args...);\n\n template <int NbEvents, typename Func>\n static Wrapped* wrap(EventOwner<NbEvents>* owner, Func&& func)\n {\n owner->callbacks[Idx] = std::shared_ptr<CallbackHandlerBase>( new CallbackHandler<Func>( std::forward<Func>( func ) ) );\n return [](Opaque opaque, Args... args) -> Ret {\n auto self = FromOpaque<NbEvents, Opaque>::get( opaque );\n assert(self->callbacks[Idx].get());\n auto cbHandler = static_cast<CallbackHandler<Func>*>( self->callbacks[Idx].get() );\n return cbHandler->func( std::forward<Args>(args)... );\n };\n }\n\n \/\/ Overload to handle null callbacks at build time.\n \/\/ We could try to compare any \"Func\" against nullptr at runtime, though\n \/\/ since Func is a template type, which roughly has to satisfy the \"Callable\" concept,\n \/\/ it could be an instance of a function object, which doesn't compare nicely against nullptr.\n \/\/ Using the specialization at build time is easier and performs better.\n template <int NbEvents>\n static std::nullptr_t wrap(EventOwner<NbEvents>*, std::nullptr_t)\n {\n return nullptr;\n }\n };\n}\n\n#endif\n<commit_msg>Common.hpp: Use make_shared<commit_after>\/*****************************************************************************\n * common.hpp: Basic shared types & helpers\n *****************************************************************************\n * Copyright © 2015 libvlcpp authors & VideoLAN\n *\n * Authors: Hugo Beauzée-Luyssen <hugo@beauzee.fr>\n * Jonathan Calmels <exxo@videolabs.io>\n *\n * This program is free software; you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License as published by\n * the Free Software Foundation; either version 2.1 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.\n *****************************************************************************\/\n\n#ifndef LIBVLC_CXX_COMMON_H\n#define LIBVLC_CXX_COMMON_H\n\n#include <vlc\/vlc.h>\n#include <array>\n#include <cassert>\n#include <memory>\n\nnamespace VLC\n{\n class Media;\n using MediaPtr = std::shared_ptr<Media>;\n\n \/\/ Work around cross class dependencies\n \/\/ Class A needs to access B's internal pointer\n \/\/ Class B needs to access A's internal pointer\n \/\/ By using a template function to do this, we're delegating\n \/\/ the access to both classes' guts to a later point, when the compiler\n \/\/ already knows everything it needs.\n \/\/ The only drawback is that we can't return decltype(ptr->get()), since when\n \/\/ the compiler checks for the prototype, it hasn't parsed all the declarations yet.\n template <typename TYPE, typename REF>\n TYPE* getInternalPtr(const REF& ref)\n {\n return ref.get();\n }\n\n inline std::unique_ptr<char, void (*)(void*)> wrapCStr(char* str)\n {\n return std::unique_ptr<char, void(*)(void*)>( str, [](void* ptr) { libvlc_free(ptr); } );\n }\n\n#if !defined(_MSC_VER)\n \/\/ Kudos to 3xxO for the signature_match helper\n template <typename, typename, typename = void>\n struct signature_match : std::false_type {};\n\n template <typename Func, typename Ret, typename... Args>\n struct signature_match<Func, Ret(Args...),\n typename std::enable_if<\n std::is_convertible<\n decltype(std::declval<Func>()(std::declval<Args>()...)),\n Ret\n >::value \/\/ true or false\n >::type \/\/ void or SFINAE\n > : std::true_type {};\n#else\n template <typename... Args>\n struct signature_match : std::false_type {};\n\n template <typename Func, typename Ret, class... Args>\n struct signature_match<Func, Ret(Args...)>\n : std::integral_constant < bool,\n std::is_convertible < decltype(std::declval<Func>()(std::declval<Args>()...)), Ret\n > ::value\n > {};\n#endif\n\n template <typename Func, typename Ret, typename... Args>\n struct signature_match_or_nullptr : std::integral_constant<bool,\n signature_match<Func, Ret, Args...>::value ||\n std::is_same<Func, std::nullptr_t>::value\n >\n {\n };\n\n struct CallbackHandlerBase\n {\n virtual ~CallbackHandlerBase() = default;\n };\n\n template <typename Func>\n struct CallbackHandler : public CallbackHandlerBase\n {\n CallbackHandler(Func&& f) : func( std::forward<Func>( f ) ) {}\n Func func;\n };\n\n template <int NbEvent>\n struct EventOwner\n {\n std::array<std::shared_ptr<CallbackHandlerBase>, NbEvent> callbacks;\n\n protected:\n EventOwner() = default;\n };\n\n template <int, typename>\n struct FromOpaque;\n\n template <int NbEvents>\n struct FromOpaque<NbEvents, void*>\n {\n static EventOwner<NbEvents>* get(void* opaque)\n {\n return reinterpret_cast<EventOwner<NbEvents>*>( opaque );\n }\n };\n\n template <int NbEvents>\n struct FromOpaque<NbEvents, void**>\n {\n static EventOwner<NbEvents>* get(void** opaque)\n {\n return reinterpret_cast<EventOwner<NbEvents>*>( *opaque );\n }\n };\n\n template <int Idx, typename... Args>\n struct CallbackWrapper;\n\n \/\/ We assume that any callback will take a void*\/void** opaque as its first parameter.\n \/\/ We intercept this parameter, and use it to fetch the list of user provided\n \/\/ functions. Once we know what function to call, we forward the rest of the\n \/\/ parameters.\n \/\/ Using partial specialization also allows us to get the list of the expected\n \/\/ callback parameters automatically, rather than having to specify them.\n template <int Idx, typename Ret, typename Opaque, typename... Args>\n struct CallbackWrapper<Idx, Ret(*)(Opaque, Args...)>\n {\n using Wrapped = Ret(Opaque, Args...);\n\n template <int NbEvents, typename Func>\n static Wrapped* wrap(EventOwner<NbEvents>* owner, Func&& func)\n {\n owner->callbacks[Idx] = std::make_shared<CallbackHandler<Func>>( std::forward<Func>( func ) );\n return [](Opaque opaque, Args... args) -> Ret {\n auto self = FromOpaque<NbEvents, Opaque>::get( opaque );\n assert(self->callbacks[Idx].get());\n auto cbHandler = static_cast<CallbackHandler<Func>*>( self->callbacks[Idx].get() );\n return cbHandler->func( std::forward<Args>(args)... );\n };\n }\n\n \/\/ Overload to handle null callbacks at build time.\n \/\/ We could try to compare any \"Func\" against nullptr at runtime, though\n \/\/ since Func is a template type, which roughly has to satisfy the \"Callable\" concept,\n \/\/ it could be an instance of a function object, which doesn't compare nicely against nullptr.\n \/\/ Using the specialization at build time is easier and performs better.\n template <int NbEvents>\n static std::nullptr_t wrap(EventOwner<NbEvents>*, std::nullptr_t)\n {\n return nullptr;\n }\n };\n}\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>#include \"objectmemory.hpp\"\n\n#include \"builtin\/class.hpp\"\n#include \"builtin\/data.hpp\"\n\n#include \"capi\/capi.hpp\"\n#include \"capi\/ruby.h\"\n\nusing namespace rubinius;\nusing namespace rubinius::capi;\n\nnamespace rubinius {\n namespace capi {\n\n void flush_cached_rdata(NativeMethodEnvironment* env, Handle* handle) {\n if(handle->is_rdata()) {\n Data* data = c_as<Data>(handle->object());\n RData* rdata = handle->as_rdata(env);\n\n data->mark(env->state(), rdata->dmark);\n data->free(env->state(), rdata->dfree);\n data->data(env->state(), rdata->data);\n }\n }\n\n RData* Handle::as_rdata(NativeMethodEnvironment* env) {\n if(type_ != cRData) {\n Data* data = c_as<Data>(object());\n type_ = cRData;\n\n as_.rdata = reinterpret_cast<RData*>(data->exposed());\n }\n\n env->state()->om->remember_object(object());\n\n return as_.rdata;\n }\n }\n}\n\nextern \"C\" {\n struct RData* capi_rdata_struct(VALUE data_handle) {\n NativeMethodEnvironment* env = NativeMethodEnvironment::get();\n\n Handle* handle = Handle::from(data_handle);\n return handle->as_rdata(env);\n }\n\n VALUE rb_data_object_alloc(VALUE klass, void* ptr,\n RUBY_DATA_FUNC mark, RUBY_DATA_FUNC free) {\n NativeMethodEnvironment* env = NativeMethodEnvironment::get();\n\n Class* data_klass = c_as<Class>(env->get_object(klass));\n\n Data* data = Data::create(env->state(), ptr, mark, free);\n\n data->klass(env->state(), data_klass);\n\n return env->get_handle(data);\n }\n}\n<commit_msg>Remember new Data objects<commit_after>#include \"objectmemory.hpp\"\n\n#include \"builtin\/class.hpp\"\n#include \"builtin\/data.hpp\"\n\n#include \"capi\/capi.hpp\"\n#include \"capi\/ruby.h\"\n\nusing namespace rubinius;\nusing namespace rubinius::capi;\n\nnamespace rubinius {\n namespace capi {\n\n void flush_cached_rdata(NativeMethodEnvironment* env, Handle* handle) {\n if(handle->is_rdata()) {\n Data* data = c_as<Data>(handle->object());\n RData* rdata = handle->as_rdata(env);\n\n data->mark(env->state(), rdata->dmark);\n data->free(env->state(), rdata->dfree);\n data->data(env->state(), rdata->data);\n }\n }\n\n RData* Handle::as_rdata(NativeMethodEnvironment* env) {\n if(type_ != cRData) {\n Data* data = c_as<Data>(object());\n type_ = cRData;\n\n as_.rdata = reinterpret_cast<RData*>(data->exposed());\n }\n\n env->state()->om->remember_object(object());\n\n return as_.rdata;\n }\n }\n}\n\nextern \"C\" {\n struct RData* capi_rdata_struct(VALUE data_handle) {\n NativeMethodEnvironment* env = NativeMethodEnvironment::get();\n\n Handle* handle = Handle::from(data_handle);\n return handle->as_rdata(env);\n }\n\n VALUE rb_data_object_alloc(VALUE klass, void* ptr,\n RUBY_DATA_FUNC mark, RUBY_DATA_FUNC free) {\n NativeMethodEnvironment* env = NativeMethodEnvironment::get();\n\n Class* data_klass = c_as<Class>(env->get_object(klass));\n\n Data* data = Data::create(env->state(), ptr, mark, free);\n\n data->klass(env->state(), data_klass);\n\n \/\/ Data objects are directly manipulated, so we have to always\n \/\/ track them.\n env->state()->om->remember_object(data);\n\n return env->get_handle(data);\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright © 2012, Université catholique de Louvain\n\/\/ All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright notice,\n\/\/ this list of conditions and the following disclaimer.\n\/\/ * Redistributions in binary form must reproduce the above copyright notice,\n\/\/ this list of conditions and the following disclaimer in the documentation\n\/\/ and\/or other materials provided with the distribution.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n\/\/ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\/\/ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\/\/ ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n\/\/ LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n\/\/ CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n\/\/ SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n\/\/ INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n\/\/ CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n\/\/ ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n\/\/ POSSIBILITY OF SUCH DAMAGE.\n\n#ifndef __UTILS_H\n#define __UTILS_H\n\n#include \"mozart.hh\"\n\n#include <type_traits>\n\n#ifndef MOZART_GENERATOR\n\nnamespace mozart {\n\n\/\/ getArgument -----------------------------------------------------------------\n\ntemplate <class T>\nT getArgument(VM vm, RichNode argValue, const nchar* expectedType) {\n using namespace patternmatching;\n\n T result;\n\n if (!matches(vm, argValue, capture(result)))\n raiseTypeError(vm, expectedType, argValue);\n\n return result;\n}\n\n\/\/ requireFeature --------------------------------------------------------------\n\nvoid requireFeature(VM vm, RichNode feature) {\n if (!feature.isFeature())\n PotentialFeature(feature).makeFeature(vm);\n}\n\n\/\/ ozListForEach ---------------------------------------------------------------\n\ntemplate <class F, class G>\nvoid ozListForEach(VM vm, RichNode cons, const F& onHead, const G& onTail) {\n while (true) {\n using namespace patternmatching;\n\n typename std::remove_reference<\n typename function_traits<F>::template arg<0>::type>::type head;\n UnstableNode tail;\n\n if (matchesCons(vm, cons, capture(head), capture(tail))) {\n onHead(head);\n cons = tail;\n } else if (matches(vm, cons, vm->coreatoms.nil)) {\n return;\n } else {\n return onTail(cons);\n }\n }\n}\n\ntemplate <class F>\nvoid ozListForEach(VM vm, RichNode cons, const F& onHead,\n const nchar* expectedType) {\n return ozListForEach(vm, cons, onHead, [=](RichNode node) {\n return raiseTypeError(vm, expectedType, node);\n });\n}\n\nsize_t ozListLength(VM vm, RichNode list) {\n size_t result = 0;\n\n UnstableNode nextList;\n\n while (true) {\n using namespace patternmatching;\n\n UnstableNode tail;\n\n if (matchesCons(vm, list, wildcard(), capture(tail))) {\n result++;\n nextList = std::move(tail);\n list = nextList;\n } else if (matches(vm, list, vm->coreatoms.nil)) {\n return result;\n } else {\n raiseTypeError(vm, MOZART_STR(\"list\"), list);\n }\n }\n}\n\nnamespace internal {\n template <class C>\n struct VSToStringHelper {\n inline\n static std::basic_string<C> call(VM vm, RichNode vs);\n };\n\n template <>\n struct VSToStringHelper<nchar> {\n static std::basic_string<nchar> call(VM vm, RichNode vs) {\n std::basic_stringstream<nchar> buffer;\n VirtualString(vs).toString(vm, buffer);\n return buffer.str();\n }\n };\n\n template <class C>\n std::basic_string<C> VSToStringHelper<C>::call(VM vm, RichNode vs) {\n auto nresult = VSToStringHelper<nchar>::call(vm, vs);\n auto str = toUTF<C>(makeLString(nresult.c_str(), nresult.size()));\n return std::basic_string<C>(str.string, str.length);\n }\n}\n\ntemplate <class C>\nstd::basic_string<C> vsToString(VM vm, RichNode vs) {\n return internal::VSToStringHelper<C>::call(vm, vs);\n}\n\n}\n\n#endif\n\n#endif \/\/ __UTILS_H\n<commit_msg>Fixed a bug in ozListForEach().<commit_after>\/\/ Copyright © 2012, Université catholique de Louvain\n\/\/ All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright notice,\n\/\/ this list of conditions and the following disclaimer.\n\/\/ * Redistributions in binary form must reproduce the above copyright notice,\n\/\/ this list of conditions and the following disclaimer in the documentation\n\/\/ and\/or other materials provided with the distribution.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n\/\/ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\/\/ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\/\/ ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n\/\/ LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n\/\/ CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n\/\/ SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n\/\/ INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n\/\/ CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n\/\/ ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n\/\/ POSSIBILITY OF SUCH DAMAGE.\n\n#ifndef __UTILS_H\n#define __UTILS_H\n\n#include \"mozart.hh\"\n\n#include <type_traits>\n\n#ifndef MOZART_GENERATOR\n\nnamespace mozart {\n\n\/\/ getArgument -----------------------------------------------------------------\n\ntemplate <class T>\nT getArgument(VM vm, RichNode argValue, const nchar* expectedType) {\n using namespace patternmatching;\n\n T result;\n\n if (!matches(vm, argValue, capture(result)))\n raiseTypeError(vm, expectedType, argValue);\n\n return result;\n}\n\n\/\/ requireFeature --------------------------------------------------------------\n\nvoid requireFeature(VM vm, RichNode feature) {\n if (!feature.isFeature())\n PotentialFeature(feature).makeFeature(vm);\n}\n\n\/\/ ozListForEach ---------------------------------------------------------------\n\ntemplate <class F, class G>\nvoid ozListForEach(VM vm, RichNode cons, const F& onHead, const G& onTail) {\n using namespace patternmatching;\n\n typename std::remove_reference<\n typename function_traits<F>::template arg<0>::type>::type head;\n\n UnstableNode tail;\n\n while (true) {\n if (matchesCons(vm, cons, capture(head), capture(tail))) {\n onHead(head);\n cons = tail;\n } else if (matches(vm, cons, vm->coreatoms.nil)) {\n return;\n } else {\n return onTail(cons);\n }\n }\n}\n\ntemplate <class F>\nvoid ozListForEach(VM vm, RichNode cons, const F& onHead,\n const nchar* expectedType) {\n return ozListForEach(vm, cons, onHead, [=](RichNode node) {\n return raiseTypeError(vm, expectedType, node);\n });\n}\n\nsize_t ozListLength(VM vm, RichNode list) {\n size_t result = 0;\n\n UnstableNode nextList;\n\n while (true) {\n using namespace patternmatching;\n\n UnstableNode tail;\n\n if (matchesCons(vm, list, wildcard(), capture(tail))) {\n result++;\n nextList = std::move(tail);\n list = nextList;\n } else if (matches(vm, list, vm->coreatoms.nil)) {\n return result;\n } else {\n raiseTypeError(vm, MOZART_STR(\"list\"), list);\n }\n }\n}\n\nnamespace internal {\n template <class C>\n struct VSToStringHelper {\n inline\n static std::basic_string<C> call(VM vm, RichNode vs);\n };\n\n template <>\n struct VSToStringHelper<nchar> {\n static std::basic_string<nchar> call(VM vm, RichNode vs) {\n std::basic_stringstream<nchar> buffer;\n VirtualString(vs).toString(vm, buffer);\n return buffer.str();\n }\n };\n\n template <class C>\n std::basic_string<C> VSToStringHelper<C>::call(VM vm, RichNode vs) {\n auto nresult = VSToStringHelper<nchar>::call(vm, vs);\n auto str = toUTF<C>(makeLString(nresult.c_str(), nresult.size()));\n return std::basic_string<C>(str.string, str.length);\n }\n}\n\ntemplate <class C>\nstd::basic_string<C> vsToString(VM vm, RichNode vs) {\n return internal::VSToStringHelper<C>::call(vm, vs);\n}\n\n}\n\n#endif\n\n#endif \/\/ __UTILS_H\n<|endoftext|>"} {"text":"<commit_before>#ifndef RBX_VM_TYPE_INFO_HPP\n#define RBX_VM_TYPE_INFO_HPP\n\n#include <map>\n#include <stdexcept>\n#include <vector>\n\n#include \"object_types.hpp\"\n#include \"prelude.hpp\"\n#include \"executor.hpp\"\n\nnamespace rubinius {\n\n class Class;\n class Object;\n class ObjectMark;\n class ObjectMemory;\n class ObjectHeader;\n\n class GCTokenImpl {};\n\n typedef GCTokenImpl& GCToken;\n\n \/**\n * Static type information for the VM.\n *\n * Due to memory layout restrictions, virtual methods cannot exist\n * on builtin types. This class abstracts those operations out of\n * the classes themselves. Using virtual dispatch here allows the\n * correct method implementation to be invoked, based on the object's\n * obj_type field.\n *\n * @see doc\/builtin_internal_resource_releasing.txt\n * @see vm\/object_types.hpp\n * @see builtin\/object.hpp\n *\/\n class TypeInfo {\n public: \/\/ Types\n\n typedef std::map<native_int, long> Slots;\n typedef std::vector<object_type> SlotTypes;\n typedef std::vector<executor> AccessorPrimitives;\n typedef std::vector<uintptr_t> SlotLocations;\n\n private: \/* Instance vars *\/\n VM* state_;\n\n public:\n\n size_t instance_size;\n static size_t instance_sizes[(int)LastObjectType];\n Slots slots;\n SlotTypes slot_types;\n AccessorPrimitives slot_accessors;\n SlotLocations slot_locations;\n std::string type_name;\n object_type type;\n bool allow_user_allocate;\n\n public: \/* Class initializers *\/\n\n static void init(ObjectMemory* om);\n static void auto_init(ObjectMemory* om);\n static void auto_learn_fields(STATE);\n virtual void auto_mark(Object* obj, ObjectMark& mark) = 0;\n\n public: \/* Ctors *\/\n\n \/**\n * Make a new TypeInfo.\n *\n * To support TypeInfo hierarchies where some classes may\n * and some may not need e.g. a cleanup, the instantiation\n * will set the cleanup flag if _any_ of the classes in\n * the chain request it.\n *\/\n TypeInfo(object_type type);\n\n virtual ~TypeInfo();\n\n public: \/* Interface *\/\n\n void set_state(STATE);\n\n VM* state() {\n return state_;\n }\n\n virtual void mark(Object* obj, ObjectMark& mark);\n\n virtual void set_field(STATE, Object* target, size_t index, Object* val);\n virtual Object* get_field(STATE, Object* target, size_t index);\n\n virtual void populate_slot_locations() { }\n\n \/**\n * Slow case, should be called only if instance_size is zero\n *\/\n virtual size_t object_size(const ObjectHeader * obj);\n\n \/**\n * Currently prints the same output as show_simple. Is specialized by\n * complex classes to e.g. limit the recursion into nested\n * objects to make the output more manageable. See e.g. Tuple\n * and CompiledCode. Immediates and numeric classes print\n * their value for both show and show_simple.\n *\/\n virtual void show(STATE, Object* self, int level);\n\n \/**\n * Default output for any object. Prints just the class name\n * and address. It is expected that classes will define their own\n * show output.\n *\/\n virtual void show_simple(STATE, Object* self, int level);\n\n \/**\n * Prints spaces to indent the following text to the requested\n * level. Levels are specified as 0, 1, 2, ... and the multiplier\n * is 2. So, text at level 2 will have 2 * 2 = 4 spaces in front.\n *\/\n virtual void indent(int level);\n\n \/**\n * Indents the attribute name to the requested level. @see indent.\n *\/\n virtual void indent_attribute(int level, const char* name);\n\n \/**\n * Prints out the class name and address. Used for simple classes\n * that may append other info on the same line.\n *\n * #<SomeClass:0x346882\n *\/\n virtual void class_info(STATE, const Object* self, bool newline = false);\n\n \/**\n * Prints out the class name and address followed by a newline. Used\n * for complex classes that will print additional member info.\n *\n * #<SomeClass:0x3287648\\n\n *\/\n virtual void class_header(STATE, const Object* self);\n\n \/**\n * Prints \"...\" + endl at the requested indent level.\n *\/\n virtual void ellipsis(int level);\n\n \/**\n * Indents to level-1 and prints \">\" + endl.\n *\/\n virtual void close_body(int level);\n\n };\n\n}\n\n\n#define BASIC_TYPEINFO(super) \\\n Info(object_type type) : super(type) { } \\\n virtual void auto_mark(Object* obj, ObjectMark& mark); \\\n virtual void set_field(STATE, Object* target, size_t index, Object* val); \\\n virtual Object* get_field(STATE, Object* target, size_t index); \\\n virtual void populate_slot_locations();\n\n#endif\n<commit_msg>Added missing #include for OS X 10.9 cc.<commit_after>#ifndef RBX_VM_TYPE_INFO_HPP\n#define RBX_VM_TYPE_INFO_HPP\n\n#include <map>\n#include <stdexcept>\n#include <vector>\n#include <string>\n\n#include \"object_types.hpp\"\n#include \"prelude.hpp\"\n#include \"executor.hpp\"\n\nnamespace rubinius {\n\n class Class;\n class Object;\n class ObjectMark;\n class ObjectMemory;\n class ObjectHeader;\n\n class GCTokenImpl {};\n\n typedef GCTokenImpl& GCToken;\n\n \/**\n * Static type information for the VM.\n *\n * Due to memory layout restrictions, virtual methods cannot exist\n * on builtin types. This class abstracts those operations out of\n * the classes themselves. Using virtual dispatch here allows the\n * correct method implementation to be invoked, based on the object's\n * obj_type field.\n *\n * @see doc\/builtin_internal_resource_releasing.txt\n * @see vm\/object_types.hpp\n * @see builtin\/object.hpp\n *\/\n class TypeInfo {\n public: \/\/ Types\n\n typedef std::map<native_int, long> Slots;\n typedef std::vector<object_type> SlotTypes;\n typedef std::vector<executor> AccessorPrimitives;\n typedef std::vector<uintptr_t> SlotLocations;\n\n private: \/* Instance vars *\/\n VM* state_;\n\n public:\n\n size_t instance_size;\n static size_t instance_sizes[(int)LastObjectType];\n Slots slots;\n SlotTypes slot_types;\n AccessorPrimitives slot_accessors;\n SlotLocations slot_locations;\n std::string type_name;\n object_type type;\n bool allow_user_allocate;\n\n public: \/* Class initializers *\/\n\n static void init(ObjectMemory* om);\n static void auto_init(ObjectMemory* om);\n static void auto_learn_fields(STATE);\n virtual void auto_mark(Object* obj, ObjectMark& mark) = 0;\n\n public: \/* Ctors *\/\n\n \/**\n * Make a new TypeInfo.\n *\n * To support TypeInfo hierarchies where some classes may\n * and some may not need e.g. a cleanup, the instantiation\n * will set the cleanup flag if _any_ of the classes in\n * the chain request it.\n *\/\n TypeInfo(object_type type);\n\n virtual ~TypeInfo();\n\n public: \/* Interface *\/\n\n void set_state(STATE);\n\n VM* state() {\n return state_;\n }\n\n virtual void mark(Object* obj, ObjectMark& mark);\n\n virtual void set_field(STATE, Object* target, size_t index, Object* val);\n virtual Object* get_field(STATE, Object* target, size_t index);\n\n virtual void populate_slot_locations() { }\n\n \/**\n * Slow case, should be called only if instance_size is zero\n *\/\n virtual size_t object_size(const ObjectHeader * obj);\n\n \/**\n * Currently prints the same output as show_simple. Is specialized by\n * complex classes to e.g. limit the recursion into nested\n * objects to make the output more manageable. See e.g. Tuple\n * and CompiledCode. Immediates and numeric classes print\n * their value for both show and show_simple.\n *\/\n virtual void show(STATE, Object* self, int level);\n\n \/**\n * Default output for any object. Prints just the class name\n * and address. It is expected that classes will define their own\n * show output.\n *\/\n virtual void show_simple(STATE, Object* self, int level);\n\n \/**\n * Prints spaces to indent the following text to the requested\n * level. Levels are specified as 0, 1, 2, ... and the multiplier\n * is 2. So, text at level 2 will have 2 * 2 = 4 spaces in front.\n *\/\n virtual void indent(int level);\n\n \/**\n * Indents the attribute name to the requested level. @see indent.\n *\/\n virtual void indent_attribute(int level, const char* name);\n\n \/**\n * Prints out the class name and address. Used for simple classes\n * that may append other info on the same line.\n *\n * #<SomeClass:0x346882\n *\/\n virtual void class_info(STATE, const Object* self, bool newline = false);\n\n \/**\n * Prints out the class name and address followed by a newline. Used\n * for complex classes that will print additional member info.\n *\n * #<SomeClass:0x3287648\\n\n *\/\n virtual void class_header(STATE, const Object* self);\n\n \/**\n * Prints \"...\" + endl at the requested indent level.\n *\/\n virtual void ellipsis(int level);\n\n \/**\n * Indents to level-1 and prints \">\" + endl.\n *\/\n virtual void close_body(int level);\n\n };\n\n}\n\n\n#define BASIC_TYPEINFO(super) \\\n Info(object_type type) : super(type) { } \\\n virtual void auto_mark(Object* obj, ObjectMark& mark); \\\n virtual void set_field(STATE, Object* target, size_t index, Object* val); \\\n virtual Object* get_field(STATE, Object* target, size_t index); \\\n virtual void populate_slot_locations();\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>#include <world\/terrain\/PerlinTerrainGenerator.h>\n#include <world\/terrain.h>\n#include \"FlatWorld.h\"\n\n#include \"world\/core\/GridChunkSystem.h\"\n#include \"world\/core\/InstancePool.h\"\n#include \"world\/terrain\/HeightmapGround.h\"\n#include \"world\/tree\/ForestLayer.h\"\n#include \"world\/nature\/Grass.h\"\n#include \"world\/tree\/SimpleTreeDecorator.h\"\n#include \"world\/nature\/Rocks.h\"\n#include \"world\/core\/Profiler.h\"\n#include \"world\/core\/SeedDistribution.h\"\n#include \"world\/terrain\/MultilayerGroundTexture.h\"\n#include \"world\/terrain\/CachedTextureProvider.h\"\n#include \"world\/core\/WorldFile.h\"\n#include \"world\/terrain\/GroundBiomes.h\"\n\nnamespace world {\n\nclass PFlatWorld {\npublic:\n std::unique_ptr<GroundNode> _ground;\n\n PFlatWorld() {}\n};\n\nFlatWorld *FlatWorld::createDemoFlatWorld() {\n FlatWorld *world = new FlatWorld();\n\n HeightmapGround &ground = world->setGround<HeightmapGround>();\n\n ground.addWorker<PerlinTerrainGenerator>(3, 4., 0.35).setMaxOctaveCount(6);\n\n auto &map = ground.addWorker<CustomWorldRMModifier>();\n map.setRegion({0, 0}, 10000, 3, 0.1, 0.3);\n map.setRegion({0, 0}, 6000, 0.7, 1.6, 0.8);\n\n ground.addWorker<GroundBiomes>();\n \/\/ TODO add color configuration to the texturer (just as before)\n ground.addWorker<AltitudeTexturer>();\n\n \/*auto &multilayer = ground.addWorker<MultilayerGroundTexture>();\n multilayer.setTextureProvider<CachedTextureProvider>(\"multilayer\/\");\n \/\/ rock\n multilayer.addLayer(DistributionParams{-1, 0, 1, 2, \/\/ h\n -1, 0, 1, 2, \/\/ dh\n 0, 1, 0, 1, 0.05});\n \/\/ sand\n multilayer.addLayer(DistributionParams{-1, 0, 0.4, 0.45, \/\/ h\n -1, 0, 0.4, 0.6, \/\/ dh\n 0, 1, 0, 1, 0.05});\n \/\/ soil\n multilayer.addLayer(DistributionParams{0.33, 0.4, 0.6, 0.75, \/\/ h\n -1, 0, 0.45, 0.65, \/\/ dh\n 0, 0.85, 0.25, 0.85, 0.05});\n \/\/ grass\n multilayer.addLayer(DistributionParams{0.33, 0.4, 0.6, 0.7, \/\/ h\n -1, 0, 0.4, 0.6, \/\/ dh\n 0., 1., 0.25, 0.6, 0.05});\n \/\/ snow\n multilayer.addLayer(DistributionParams{0.65, 0.8, 1, 2, \/\/ h\n -1, 0, 0.5, 0.7, \/\/ dh\n 0.0, 1.0, 0, 1., 0.05});*\/\n\n\n auto &chunkSystem = world->addPrimaryNode<GridChunkSystem>({0, 0, 0});\n chunkSystem.addDecorator<ForestLayer>();\n\n \/\/ auto &treePool = chunkSystem.addDecorator<InstancePool<Tree>>(world);\n \/\/ treePool.setResolution(1);\n \/\/ treePool.distribution().setDensity(0.0008);\n\n \/\/ Grass with seed distribution\n auto &grassPool = chunkSystem.addDecorator<InstancePool>();\n grassPool.setDistribution<SeedDistribution>();\n grassPool.setTemplateGenerator<Grass>();\n\n \/\/ Rocks\n auto &rocksPool = chunkSystem.addDecorator<InstancePool>();\n rocksPool.setDistribution<RandomDistribution>().setDensity(0.02);\n rocksPool.setTemplateGenerator<Rocks>();\n\n auto &rocks = rocksPool.addGenerator<Rocks>();\n rocks.setRadius(0.7);\n\n for (int i = 0; i < 10; ++i) {\n rocks.addRock({0, 0, 0});\n }\n\n return world;\n}\n\n\nFlatWorld::FlatWorld() : _internal(new PFlatWorld()) {\n auto &ground = setGround<HeightmapGround>();\n}\n\nFlatWorld::~FlatWorld() { delete _internal; }\n\nIGround &FlatWorld::ground() { return *_internal->_ground; }\n\nvoid FlatWorld::collect(ICollector &collector,\n const IResolutionModel &resolutionModel) {\n \/\/ TODO remove this hack when we can deserialize references\n auto *hg = dynamic_cast<HeightmapGround *>(_internal->_ground.get());\n if (hg != nullptr) {\n _atmosphericProvider = hg->getAtmosphericProvider();\n }\n \/\/ end of hack\n\n _internal->_ground->collect(collector, resolutionModel);\n World::collect(collector, resolutionModel);\n}\n\nvec3d FlatWorld::findNearestFreePoint(const vec3d &origin,\n const vec3d &direction, double resolution,\n const ExplorationContext &ctx) const {\n auto pos = origin + ctx.getOffset();\n double z =\n _internal->_ground->observeAltitudeAt(pos.x, pos.y, resolution, ctx);\n \/\/ std::cout << z - ctx.getOffset().z << \" <> \" << origin.z << std::endl;\n return {origin.x, origin.y, z - ctx.getOffset().z};\n}\n\nvoid FlatWorld::write(WorldFile &wf) const {\n wf.addChild(\"ground\", _internal->_ground->serializeSubclass());\n World::write(wf);\n}\n\nvoid FlatWorld::read(const WorldFile &wf) {\n _internal->_ground.reset(readSubclass<GroundNode>(wf.readChild(\"ground\")));\n World::read(wf);\n}\n\nIEnvironment *FlatWorld::getInitialEnvironment() { return this; }\n\nvoid FlatWorld::setGroundInternal(GroundNode *ground) {\n _internal->_ground = std::unique_ptr<GroundNode>(ground);\n}\n\n} \/\/ namespace world\n<commit_msg>Add color map configuration to demo flat world<commit_after>#include <world\/terrain\/PerlinTerrainGenerator.h>\n#include <world\/terrain.h>\n#include \"FlatWorld.h\"\n\n#include \"world\/core\/GridChunkSystem.h\"\n#include \"world\/core\/InstancePool.h\"\n#include \"world\/terrain\/HeightmapGround.h\"\n#include \"world\/tree\/ForestLayer.h\"\n#include \"world\/nature\/Grass.h\"\n#include \"world\/tree\/SimpleTreeDecorator.h\"\n#include \"world\/nature\/Rocks.h\"\n#include \"world\/core\/Profiler.h\"\n#include \"world\/core\/SeedDistribution.h\"\n#include \"world\/terrain\/MultilayerGroundTexture.h\"\n#include \"world\/terrain\/CachedTextureProvider.h\"\n#include \"world\/core\/WorldFile.h\"\n#include \"world\/terrain\/GroundBiomes.h\"\n\nnamespace world {\n\nclass PFlatWorld {\npublic:\n std::unique_ptr<GroundNode> _ground;\n\n PFlatWorld() {}\n};\n\nFlatWorld *FlatWorld::createDemoFlatWorld() {\n FlatWorld *world = new FlatWorld();\n\n HeightmapGround &ground = world->setGround<HeightmapGround>();\n\n ground.addWorker<PerlinTerrainGenerator>(3, 4., 0.35).setMaxOctaveCount(6);\n\n auto &map = ground.addWorker<CustomWorldRMModifier>();\n map.setRegion({0, 0}, 10000, 3, 0.1, 0.3);\n map.setRegion({0, 0}, 6000, 0.7, 1.6, 0.8);\n\n auto &texturer = ground.addWorker<AltitudeTexturer>();\n ColorMap &colorMap = texturer.getColorMap();\n\n colorMap.addPoint({0.15, 0.5}, Color4u(209, 207, 153)); \/\/ Sand\n colorMap.addPoint({0.31, 0}, Color4u(209, 207, 153)); \/\/ Sand\n colorMap.addPoint({0.31, 1}, Color4u(209, 207, 153)); \/\/ Sand\n colorMap.addPoint({0.35, 0}, Color4u(144, 183, 92)); \/\/ Light grass\n colorMap.addPoint({0.35, 1}, Color4u(72, 132, 65)); \/\/ Dark grass\n colorMap.addPoint({0.5, 0}, Color4u(144, 183, 100)); \/\/ Light grass\n colorMap.addPoint({0.5, 1}, Color4u(96, 76, 40)); \/\/ Dark dirt\n colorMap.addPoint({0.75, 0}, Color4u(96, 76, 40)); \/\/ Dark dirt\n colorMap.addPoint({0.75, 1}, Color4u(160, 160, 160)); \/\/ Rock\n colorMap.addPoint({1, 0}, Color4u(244, 252, 250)); \/\/ Snow\n colorMap.addPoint({1, 1}, Color4u(160, 160, 160)); \/\/ Rock\n colorMap.setOrder(3);\n\n \/\/ ground.addWorker<GroundBiomes>();\n \/*auto &multilayer = ground.addWorker<MultilayerGroundTexture>();\n multilayer.setTextureProvider<CachedTextureProvider>(\"multilayer\/\");\n \/\/ rock\n multilayer.addLayer(DistributionParams{-1, 0, 1, 2, \/\/ h\n -1, 0, 1, 2, \/\/ dh\n 0, 1, 0, 1, 0.05});\n \/\/ sand\n multilayer.addLayer(DistributionParams{-1, 0, 0.4, 0.45, \/\/ h\n -1, 0, 0.4, 0.6, \/\/ dh\n 0, 1, 0, 1, 0.05});\n \/\/ soil\n multilayer.addLayer(DistributionParams{0.33, 0.4, 0.6, 0.75, \/\/ h\n -1, 0, 0.45, 0.65, \/\/ dh\n 0, 0.85, 0.25, 0.85, 0.05});\n \/\/ grass\n multilayer.addLayer(DistributionParams{0.33, 0.4, 0.6, 0.7, \/\/ h\n -1, 0, 0.4, 0.6, \/\/ dh\n 0., 1., 0.25, 0.6, 0.05});\n \/\/ snow\n multilayer.addLayer(DistributionParams{0.65, 0.8, 1, 2, \/\/ h\n -1, 0, 0.5, 0.7, \/\/ dh\n 0.0, 1.0, 0, 1., 0.05});*\/\n\n\n auto &chunkSystem = world->addPrimaryNode<GridChunkSystem>({0, 0, 0});\n chunkSystem.addDecorator<ForestLayer>();\n\n \/\/ auto &treePool = chunkSystem.addDecorator<InstancePool<Tree>>(world);\n \/\/ treePool.setResolution(1);\n \/\/ treePool.distribution().setDensity(0.0008);\n\n \/\/ Grass with seed distribution\n auto &grassPool = chunkSystem.addDecorator<InstancePool>();\n grassPool.setDistribution<SeedDistribution>();\n grassPool.setTemplateGenerator<Grass>();\n\n \/\/ Rocks\n auto &rocksPool = chunkSystem.addDecorator<InstancePool>();\n rocksPool.setDistribution<RandomDistribution>().setDensity(0.02);\n rocksPool.setTemplateGenerator<Rocks>();\n\n auto &rocks = rocksPool.addGenerator<Rocks>();\n rocks.setRadius(0.7);\n\n for (int i = 0; i < 10; ++i) {\n rocks.addRock({0, 0, 0});\n }\n\n return world;\n}\n\n\nFlatWorld::FlatWorld() : _internal(new PFlatWorld()) {\n auto &ground = setGround<HeightmapGround>();\n}\n\nFlatWorld::~FlatWorld() { delete _internal; }\n\nIGround &FlatWorld::ground() { return *_internal->_ground; }\n\nvoid FlatWorld::collect(ICollector &collector,\n const IResolutionModel &resolutionModel) {\n \/\/ TODO remove this hack when we can deserialize references\n auto *hg = dynamic_cast<HeightmapGround *>(_internal->_ground.get());\n if (hg != nullptr) {\n _atmosphericProvider = hg->getAtmosphericProvider();\n }\n \/\/ end of hack\n\n _internal->_ground->collect(collector, resolutionModel);\n World::collect(collector, resolutionModel);\n}\n\nvec3d FlatWorld::findNearestFreePoint(const vec3d &origin,\n const vec3d &direction, double resolution,\n const ExplorationContext &ctx) const {\n auto pos = origin + ctx.getOffset();\n double z =\n _internal->_ground->observeAltitudeAt(pos.x, pos.y, resolution, ctx);\n \/\/ std::cout << z - ctx.getOffset().z << \" <> \" << origin.z << std::endl;\n return {origin.x, origin.y, z - ctx.getOffset().z};\n}\n\nvoid FlatWorld::write(WorldFile &wf) const {\n wf.addChild(\"ground\", _internal->_ground->serializeSubclass());\n World::write(wf);\n}\n\nvoid FlatWorld::read(const WorldFile &wf) {\n _internal->_ground.reset(readSubclass<GroundNode>(wf.readChild(\"ground\")));\n World::read(wf);\n}\n\nIEnvironment *FlatWorld::getInitialEnvironment() { return this; }\n\nvoid FlatWorld::setGroundInternal(GroundNode *ground) {\n _internal->_ground = std::unique_ptr<GroundNode>(ground);\n}\n\n} \/\/ namespace world\n<|endoftext|>"} {"text":"<commit_before>\/*\n *\n * Copyright (C) 2001 Frank Dabek (fdabek@lcs.mit.edu), \n * \t\t Massachusetts Institute of Technology\n * \n *\n * Permission is hereby granted, free of charge, to any person obtaining\n * a copy of this software and associated documentation files (the\n * \"Software\"), to deal in the Software without restriction, including\n * without limitation the rights to use, copy, modify, merge, publish,\n * distribute, sublicense, and\/or sell copies of the Software, and to\n * permit persons to whom the Software is furnished to do so, subject to\n * the following conditions:\n *\n * The above copyright notice and this permission notice shall be\n * included in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n *\n *\/\n\n#include <async.h>\n#include <sfsmisc.h>\n#include <dhash_common.h>\n#include <dhash_prot.h>\n#include <dhashclient.h>\n#include <verify.h>\n#include <dbfe.h>\n#include <crypt.h>\n#include <sys\/time.h>\n\nstatic bigint *IDs;\nstatic void **data;\nstr control_socket;\nstatic FILE *outfile;\nstatic FILE *bwfile;\nunsigned int datasize;\n\nptr<axprt_stream> xprt;\nint fconnected = 0;\nint out = 0;\nint MAX_OPS_OUT = 1024;\n\nint bps = 0;\nint sec = 0;\ntimecb_t *measurer = NULL;\n\nu_int64_t\ngetusec ()\n{\n timeval tv;\n gettimeofday (&tv, NULL);\n return tv.tv_sec * INT64(1000000) + tv.tv_usec;\n}\n\nvoid\nmeasure_bw (void)\n{\n float bw = datasize * bps; \/\/ we get called every second\n bw \/= 1024; \/\/ convert to K.\n sec++;\n unsigned long long usecs = (getusec ()\/1000);\n fprintf (bwfile, \"%llu\\t%6.2f KB\/s\\n\", usecs, bw);\n bps = 0;\n measurer = delaycb (1, wrap (&measure_bw));\n}\n\n\nchordID\nmake_block (void *data, int g) \n{\n \/\/ size must be word sized\n \/\/ assert (datasize % sizeof (long) == 0);\n \n char *rd = (char *)data;\n for (unsigned int i = 0; i < datasize; i++) \n rd[i] = random();\n \/\/rd[i] = (char)('a' + g);\n rd[datasize - 1] = 0;\n\n return compute_hash (rd, datasize);\n}\n\nvoid\nprepare_test_data (int num) \n{\n IDs = New chordID[num];\n data = (void **)malloc(sizeof(void *)*num);\n for (int i = 0; i < num; i++) {\n data[i] = malloc(datasize);\n IDs[i] = make_block(data[i], i);\n }\n}\n\n\nvoid\nstore_cb (dhash_stat status, ptr<insert_info> i)\n{\n out--;\n\n if (status != DHASH_OK) {\n warn << \"store_cb: \" << i->key << \" \" << status << \"\\n\";\n fprintf (outfile, \"store error\\n\");\n } else {\n bps++;\n str buf = strbuf () << \"stored \" << i->key << \" at \" << i->path.back () << \"\\n\";\n fprintf (outfile, \"%s\", buf.cstr ());\n }\n}\n\n\nint\nstore (dhashclient *dhash, int num) \n{\n for (int i = 0; i < num; i++) {\n out++;\n dhash->insert ((char *)data[i], datasize, wrap (store_cb));\n while (out > MAX_OPS_OUT) \n acheck ();\n }\n\n while (out > 0) \n acheck ();\n\n return 0;\n}\n\n\n\nvoid\nfetch_cb (int i, struct timeval start, dhash_stat stat, ptr<dhash_block> blk, vec<chordID> path)\n{\n out--;\n\n if (!blk) {\n strbuf buf;\n buf << \"Error: \" << IDs[i] << \"\\n\";\n fprintf (outfile, str (buf).cstr ());\n }\n else if (datasize != blk->len || memcmp (data[i], blk->data, datasize) != 0)\n fatal << \"verification failed\";\n else {\n struct timeval end;\n gettimeofday(&end, NULL);\n strbuf buf;\n float elapsed = (end.tv_sec - start.tv_sec)*1000.0 + (end.tv_usec - start.tv_usec)\/1000.0;\n char estr[128];\n sprintf (estr, \"%f\", elapsed);\n\n bps++;\n buf << IDs[i] << \" \" << estr;\n buf << \" \/\";\n for (u_int i = 0; i < blk->times.size (); i++)\n buf << \" \" << blk->times[i];\n buf << \" \/\";\n\n buf << \" \" << blk->hops << \" \" << blk->errors\n\t<< \" \" << blk->retries << \" \";\n for (u_int i=0; i < path.size (); i++) {\n buf << path[i] << \" \";\n }\n \n buf << \"\\n\";\n fprintf (outfile, str (buf).cstr ());\n if (outfile != stdout)\n warnx << buf;\n } \n}\n\n\nvoid\nfetch (dhashclient &dhash, int num)\n{\n for (int i = 0; i < num; i++) {\n out++;\n struct timeval start;\n gettimeofday (&start, NULL);\n\n dhash.retrieve (IDs[i], DHASH_CONTENTHASH, wrap (fetch_cb, i, start));\n while (out > MAX_OPS_OUT)\n acheck ();\n }\n\n while (out > 0) \n acheck();\n}\n\nvoid\nusage (char *progname) \n{\n warn << \"vnode_num control_socket num_trials data_size file <f or s> nops seed [bw-file]\\n\";\n exit(0);\n}\n\n\nvoid\nconnected (dhashclient *dhash, int argc, char **argv) \n{\n\n fconnected = 1;\n int num = atoi(argv[3]);\n datasize = atoi(argv[4]);\n\n char *output = argv[5];\n if (strcmp(output, \"-\") == 0)\n outfile = stdout;\n else\n outfile = fopen(output, \"w\");\n\n char *bwoutput;\n if (argc > 9) {\n bwoutput = argv[9];\n if (strcmp (bwoutput, \"-\") == 0)\n bwfile = stdout;\n else\n bwfile = fopen (bwoutput, \"w\");\n\n fflush (bwfile);\n measurer = delaycb (1, wrap (&measure_bw));\n }\n\n if (!outfile) {\n printf (\"could not open %s\\n\", output);\n exit(1);\n }\n\n unsigned int seed = strtoul (argv[8], NULL, 10);\n srandom (seed);\n prepare_test_data (num);\n\n MAX_OPS_OUT = atoi(argv[7]);\n\n struct timeval start;\n gettimeofday (&start, NULL);\n\n if (argv[6][0] == 's')\n store (dhash, num);\n else\n fetch (*dhash, num);\n \n struct timeval end;\n gettimeofday (&end, NULL);\n float elapsed = (end.tv_sec - start.tv_sec)*1000.0 + (end.tv_usec - start.tv_usec)\/1000.0;\n fprintf(outfile, \"Total Elapsed: %f\\n\", elapsed);\n \n if (bwfile && measurer) {\n timecb_remove (measurer);\n measurer = NULL;\n measure_bw ();\n fclose (bwfile);\n }\n\n fclose (outfile);\n\n delete dhash;\n}\n\nvoid\ntcp_connect_cb (int argc, char **argv, int fd)\n{\n if (fd < 0) \n fatal << \"connect failed\\n\";\n warnx << \"... connected!\\n\";\n xprt = axprt_stream::alloc (fd); \n dhashclient *dhash = New dhashclient (xprt);\n connected (dhash, argc, argv);\n}\n\nint\nmain (int argc, char **argv)\n{\n setprogname (argv[0]);\n\n if (argc < 9) {\n usage (argv[0]);\n exit (1);\n }\n\n control_socket = argv[2];\n char *cstr = (char *)control_socket.cstr ();\n if (strchr (cstr, ':')) {\n char *port = strchr (cstr, ':');\n *port = 0; \/\/isolate host\n port++; \/\/ point at port\n char *host = cstr;\n short i_port = atoi (port);\n warn << \"Hi Russ, I'm connecting to \" << host << \":\" << i_port << \"...\";\n tcpconnect (host, i_port, wrap (&tcp_connect_cb, argc, argv));\n while (!fconnected) acheck ();\n } else {\n dhashclient *dhash = New dhashclient (control_socket);\n connected (dhash, argc, argv);\n }\n}\n\n\n<commit_msg>Don't say hi to Russ.<commit_after>\/*\n *\n * Copyright (C) 2001 Frank Dabek (fdabek@lcs.mit.edu), \n * \t\t Massachusetts Institute of Technology\n * \n *\n * Permission is hereby granted, free of charge, to any person obtaining\n * a copy of this software and associated documentation files (the\n * \"Software\"), to deal in the Software without restriction, including\n * without limitation the rights to use, copy, modify, merge, publish,\n * distribute, sublicense, and\/or sell copies of the Software, and to\n * permit persons to whom the Software is furnished to do so, subject to\n * the following conditions:\n *\n * The above copyright notice and this permission notice shall be\n * included in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n *\n *\/\n\n#include <async.h>\n#include <sfsmisc.h>\n#include <dhash_common.h>\n#include <dhash_prot.h>\n#include <dhashclient.h>\n#include <verify.h>\n#include <dbfe.h>\n#include <crypt.h>\n#include <sys\/time.h>\n\nstatic bigint *IDs;\nstatic void **data;\nstr control_socket;\nstatic FILE *outfile;\nstatic FILE *bwfile;\nunsigned int datasize;\n\nptr<axprt_stream> xprt;\nint fconnected = 0;\nint out = 0;\nint MAX_OPS_OUT = 1024;\n\nint bps = 0;\nint sec = 0;\ntimecb_t *measurer = NULL;\n\nu_int64_t\ngetusec ()\n{\n timeval tv;\n gettimeofday (&tv, NULL);\n return tv.tv_sec * INT64(1000000) + tv.tv_usec;\n}\n\nvoid\nmeasure_bw (void)\n{\n float bw = datasize * bps; \/\/ we get called every second\n bw \/= 1024; \/\/ convert to K.\n sec++;\n unsigned long long usecs = (getusec ()\/1000);\n fprintf (bwfile, \"%llu\\t%6.2f KB\/s\\n\", usecs, bw);\n bps = 0;\n measurer = delaycb (1, wrap (&measure_bw));\n}\n\n\nchordID\nmake_block (void *data, int g) \n{\n \/\/ size must be word sized\n \/\/ assert (datasize % sizeof (long) == 0);\n \n char *rd = (char *)data;\n for (unsigned int i = 0; i < datasize; i++) \n rd[i] = random();\n \/\/rd[i] = (char)('a' + g);\n rd[datasize - 1] = 0;\n\n return compute_hash (rd, datasize);\n}\n\nvoid\nprepare_test_data (int num) \n{\n IDs = New chordID[num];\n data = (void **)malloc(sizeof(void *)*num);\n for (int i = 0; i < num; i++) {\n data[i] = malloc(datasize);\n IDs[i] = make_block(data[i], i);\n }\n}\n\n\nvoid\nstore_cb (dhash_stat status, ptr<insert_info> i)\n{\n out--;\n\n if (status != DHASH_OK) {\n warn << \"store_cb: \" << i->key << \" \" << status << \"\\n\";\n fprintf (outfile, \"store error\\n\");\n } else {\n bps++;\n str buf = strbuf () << \"stored \" << i->key << \" at \" << i->path.back () << \"\\n\";\n fprintf (outfile, \"%s\", buf.cstr ());\n }\n}\n\n\nint\nstore (dhashclient *dhash, int num) \n{\n for (int i = 0; i < num; i++) {\n out++;\n dhash->insert ((char *)data[i], datasize, wrap (store_cb));\n while (out > MAX_OPS_OUT) \n acheck ();\n }\n\n while (out > 0) \n acheck ();\n\n return 0;\n}\n\n\n\nvoid\nfetch_cb (int i, struct timeval start, dhash_stat stat, ptr<dhash_block> blk, vec<chordID> path)\n{\n out--;\n\n if (!blk) {\n strbuf buf;\n buf << \"Error: \" << IDs[i] << \"\\n\";\n fprintf (outfile, str (buf).cstr ());\n }\n else if (datasize != blk->len || memcmp (data[i], blk->data, datasize) != 0)\n fatal << \"verification failed\";\n else {\n struct timeval end;\n gettimeofday(&end, NULL);\n strbuf buf;\n float elapsed = (end.tv_sec - start.tv_sec)*1000.0 + (end.tv_usec - start.tv_usec)\/1000.0;\n char estr[128];\n sprintf (estr, \"%f\", elapsed);\n\n bps++;\n buf << IDs[i] << \" \" << estr;\n buf << \" \/\";\n for (u_int i = 0; i < blk->times.size (); i++)\n buf << \" \" << blk->times[i];\n buf << \" \/\";\n\n buf << \" \" << blk->hops << \" \" << blk->errors\n\t<< \" \" << blk->retries << \" \";\n for (u_int i=0; i < path.size (); i++) {\n buf << path[i] << \" \";\n }\n \n buf << \"\\n\";\n fprintf (outfile, str (buf).cstr ());\n if (outfile != stdout)\n warnx << buf;\n } \n}\n\n\nvoid\nfetch (dhashclient &dhash, int num)\n{\n for (int i = 0; i < num; i++) {\n out++;\n struct timeval start;\n gettimeofday (&start, NULL);\n\n dhash.retrieve (IDs[i], DHASH_CONTENTHASH, wrap (fetch_cb, i, start));\n while (out > MAX_OPS_OUT)\n acheck ();\n }\n\n while (out > 0) \n acheck();\n}\n\nvoid\nusage (char *progname) \n{\n warn << \"vnode_num control_socket num_trials data_size file <f or s> nops seed [bw-file]\\n\";\n exit(0);\n}\n\n\nvoid\nconnected (dhashclient *dhash, int argc, char **argv) \n{\n\n fconnected = 1;\n int num = atoi(argv[3]);\n datasize = atoi(argv[4]);\n\n char *output = argv[5];\n if (strcmp(output, \"-\") == 0)\n outfile = stdout;\n else\n outfile = fopen(output, \"w\");\n\n char *bwoutput;\n if (argc > 9) {\n bwoutput = argv[9];\n if (strcmp (bwoutput, \"-\") == 0)\n bwfile = stdout;\n else\n bwfile = fopen (bwoutput, \"w\");\n\n fflush (bwfile);\n measurer = delaycb (1, wrap (&measure_bw));\n }\n\n if (!outfile) {\n printf (\"could not open %s\\n\", output);\n exit(1);\n }\n\n unsigned int seed = strtoul (argv[8], NULL, 10);\n srandom (seed);\n prepare_test_data (num);\n\n MAX_OPS_OUT = atoi(argv[7]);\n\n struct timeval start;\n gettimeofday (&start, NULL);\n\n if (argv[6][0] == 's')\n store (dhash, num);\n else\n fetch (*dhash, num);\n \n struct timeval end;\n gettimeofday (&end, NULL);\n float elapsed = (end.tv_sec - start.tv_sec)*1000.0 + (end.tv_usec - start.tv_usec)\/1000.0;\n fprintf(outfile, \"Total Elapsed: %f\\n\", elapsed);\n \n if (bwfile && measurer) {\n timecb_remove (measurer);\n measurer = NULL;\n measure_bw ();\n fclose (bwfile);\n }\n\n fclose (outfile);\n\n delete dhash;\n}\n\nvoid\ntcp_connect_cb (int argc, char **argv, int fd)\n{\n if (fd < 0) \n fatal << \"connect failed\\n\";\n warnx << \"... connected!\\n\";\n xprt = axprt_stream::alloc (fd); \n dhashclient *dhash = New dhashclient (xprt);\n connected (dhash, argc, argv);\n}\n\nint\nmain (int argc, char **argv)\n{\n setprogname (argv[0]);\n\n if (argc < 9) {\n usage (argv[0]);\n exit (1);\n }\n\n control_socket = argv[2];\n char *cstr = (char *)control_socket.cstr ();\n if (strchr (cstr, ':')) {\n char *port = strchr (cstr, ':');\n *port = 0; \/\/isolate host\n port++; \/\/ point at port\n char *host = cstr;\n short i_port = atoi (port);\n warn << \"Connecting to \" << host << \":\" << i_port << \" via TCP...\";\n tcpconnect (host, i_port, wrap (&tcp_connect_cb, argc, argv));\n while (!fconnected) acheck ();\n } else {\n dhashclient *dhash = New dhashclient (control_socket);\n connected (dhash, argc, argv);\n }\n}\n\n\n<|endoftext|>"} {"text":"<commit_before><commit_msg>Dynamically reduce precision when rendering \"high-precision\" values, to keep within ~4 digits (plus decimal point) and make the best use of the limited display real estate.<commit_after><|endoftext|>"} {"text":"<commit_before>#include \"photoeffects.hpp\"\n\nusing namespace cv;\n\nint warmify(cv::InputArray src, cv::OutputArray dst, uchar delta)\n{\n CV_Assert(src.type() == CV_8UC3);\n Mat imgSrc = src.getMat();\n CV_Assert(imgSrc.data);\n Mat imgDst(imgSrc.size(), CV_8UC3);\n Vec3b intensity, intensityNew;\n\n for (int i = 0; i < imgSrc.rows; i++)\n {\n for (int j = 0; j < imgSrc.cols; j++)\n {\n intensity = imgSrc.at<Vec3b>(i, j);\n intensityNew[0] = intensity[0];\n intensityNew[1] = (intensity[1] + delta < 255) ? (uchar)(intensity[1] + delta) : 255;\n intensityNew[2] = (intensity[2] + delta < 255) ? (uchar)(intensity[2] + delta) : 255;\n imgDst.at<Vec3b>(i, j) = intensityNew;\n }\n }\n imgDst.copyTo(dst);\n return 0;\n}\n\n<commit_msg>warmify.cpp was correct<commit_after>#include \"photoeffects.hpp\"\n\nusing namespace cv;\n\nint warmify(cv::InputArray src, cv::OutputArray dst, uchar delta)\n{\n CV_Assert(src.type() == CV_8UC3);\n\n Mat imgSrc = src.getMat();\n CV_Assert(imgSrc.data);\n\n dst.create(imgSrc.size(), CV_8UC3);\n Mat imgDst = dst.getMat();\n Vec3b intensityNew;\n\n for (int i = 0; i < imgSrc.rows; i++)\n {\n for (int j = 0; j < imgSrc.cols; j++)\n {\n intensityNew = imgSrc.at<Vec3b>(i, j);\n intensityNew[1] = (intensityNew[1] + delta < 255) ? (uchar)(intensityNew[1] + delta) : 255;\n intensityNew[2] = (intensityNew[2] + delta < 255) ? (uchar)(intensityNew[2] + delta) : 255;\n imgDst.at<Vec3b>(i, j) = intensityNew;\n }\n }\n return 0;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/\/ @(#)root\/proofplayer:$Id$\n\/\/ Author: Maarten Ballintijn 7\/06\/2004\n\n\/*************************************************************************\n * Copyright (C) 1995-2004, Rene Brun and Fons Rademakers. *\n * All rights reserved. *\n * *\n * For the licensing terms see $ROOTSYS\/LICENSE. *\n * For the list of contributors see $ROOTSYS\/README\/CREDITS. *\n *************************************************************************\/\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ \/\/\n\/\/ TStatus \/\/\n\/\/ \/\/\n\/\/ This class holds the status of an ongoing operation and collects \/\/\n\/\/ error messages. It provides a Merge() operation allowing it to \/\/\n\/\/ be used in PROOF to monitor status in the slaves. \/\/\n\/\/ No messages indicates success. \/\/\n\/\/ \/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"TStatus.h\"\n#include \"Riostream.h\"\n#include \"TClass.h\"\n#include \"TList.h\"\n\n\nClassImp(TStatus)\n\n\/\/______________________________________________________________________________\nTStatus::TStatus() : fVirtMemMax(-1), fResMemMax(-1)\n{\n \/\/ Deafult constructor.\n\n SetName(\"PROOF_Status\");\n fIter = fMsgs.begin();\n}\n\n\/\/______________________________________________________________________________\nvoid TStatus::Add(const char *mesg)\n{\n \/\/ Add an error message.\n\n fMsgs.insert(mesg);\n Reset();\n}\n\n\/\/______________________________________________________________________________\nInt_t TStatus::Merge(TCollection *li)\n{\n \/\/ PROOF Merge() function.\n\n TIter stats(li);\n Info(\"Merge\", \"Start: Max virtual memory: %.2f MB \\tMax resident memory: %.2f MB \",\n GetVirtMemMax()\/1024., GetResMemMax()\/1024.);\n while (TObject *obj = stats()) {\n TStatus *s = dynamic_cast<TStatus*>(obj);\n if (s == 0) continue;\n\n MsgIter_t i = s->fMsgs.begin();\n MsgIter_t end = s->fMsgs.end();\n for (; i != end; i++)\n Add(i->c_str());\n \n SetMemValues(s->GetVirtMemMax(), s->GetResMemMax());\n Info(\"Merge\", \"During: Max virtual memory: %.2f MB \\tMax resident memory: %.2f MB \",\n GetVirtMemMax()\/1024., GetResMemMax()\/1024.);\n }\n Info(\"Merge\", \"End: Max virtual memory: %.2f MB \\tMax resident memory: %.2f MB \",\n GetVirtMemMax()\/1024., GetResMemMax()\/1024.);\n\n return fMsgs.size();\n}\n\n\/\/______________________________________________________________________________\nvoid TStatus::Print(Option_t * \/*option*\/) const\n{\n \/\/ Standard print function.\n\n Printf(\"OBJ: %s\\t%s\\t%s\", IsA()->GetName(), GetName(), (IsOk() ? \"OK\" : \"ERROR\"));\n\n MsgIter_t i = fMsgs.begin();\n for (; i != fMsgs.end(); i++)\n Printf(\"\\t%s\", (*i).c_str());\n\n Printf(\" Max virtual memory: %.2f MB \\tMax resident memory: %.2f MB \",\n GetVirtMemMax()\/1024., GetResMemMax()\/1024.);\n}\n\n\/\/______________________________________________________________________________\nvoid TStatus::Reset()\n{\n \/\/ Reset the iterator on the messages.\n\n fIter = fMsgs.begin();\n}\n\n\/\/______________________________________________________________________________\nconst char *TStatus::NextMesg()\n{\n \/\/ Return the next message or 0.\n\n if (fIter != fMsgs.end()) {\n return (*fIter++).c_str();\n } else {\n return 0;\n }\n}\n\n\/\/______________________________________________________________________________\nvoid TStatus::SetMemValues(Long_t vmem, Long_t rmem)\n{\n \/\/ Set max memory values\n\n if (vmem > 0. && (fVirtMemMax < 0. || vmem > fVirtMemMax)) fVirtMemMax = vmem;\n if (rmem > 0. && (fResMemMax < 0. || rmem > fResMemMax)) fResMemMax = rmem;\n}\n\n<commit_msg>Remove debug statements<commit_after>\/\/ @(#)root\/proofplayer:$Id$\n\/\/ Author: Maarten Ballintijn 7\/06\/2004\n\n\/*************************************************************************\n * Copyright (C) 1995-2004, Rene Brun and Fons Rademakers. *\n * All rights reserved. *\n * *\n * For the licensing terms see $ROOTSYS\/LICENSE. *\n * For the list of contributors see $ROOTSYS\/README\/CREDITS. *\n *************************************************************************\/\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ \/\/\n\/\/ TStatus \/\/\n\/\/ \/\/\n\/\/ This class holds the status of an ongoing operation and collects \/\/\n\/\/ error messages. It provides a Merge() operation allowing it to \/\/\n\/\/ be used in PROOF to monitor status in the slaves. \/\/\n\/\/ No messages indicates success. \/\/\n\/\/ \/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"TStatus.h\"\n#include \"Riostream.h\"\n#include \"TClass.h\"\n#include \"TList.h\"\n#include \"TProofDebug.h\"\n\n\nClassImp(TStatus)\n\n\/\/______________________________________________________________________________\nTStatus::TStatus() : fVirtMemMax(-1), fResMemMax(-1)\n{\n \/\/ Deafult constructor.\n\n SetName(\"PROOF_Status\");\n fIter = fMsgs.begin();\n}\n\n\/\/______________________________________________________________________________\nvoid TStatus::Add(const char *mesg)\n{\n \/\/ Add an error message.\n\n fMsgs.insert(mesg);\n Reset();\n}\n\n\/\/______________________________________________________________________________\nInt_t TStatus::Merge(TCollection *li)\n{\n \/\/ PROOF Merge() function.\n\n TIter stats(li);\n PDB(kOutput,1)\n Info(\"Merge\", \"start: max virtual memory: %.2f MB \\tmax resident memory: %.2f MB \",\n GetVirtMemMax()\/1024., GetResMemMax()\/1024.);\n while (TObject *obj = stats()) {\n TStatus *s = dynamic_cast<TStatus*>(obj);\n if (s == 0) continue;\n\n MsgIter_t i = s->fMsgs.begin();\n MsgIter_t end = s->fMsgs.end();\n for (; i != end; i++)\n Add(i->c_str());\n \n SetMemValues(s->GetVirtMemMax(), s->GetResMemMax());\n PDB(kOutput,1)\n Info(\"Merge\", \"during: max virtual memory: %.2f MB \\t\"\n \"max resident memory: %.2f MB \",\n GetVirtMemMax()\/1024., GetResMemMax()\/1024.);\n }\n\n return fMsgs.size();\n}\n\n\/\/______________________________________________________________________________\nvoid TStatus::Print(Option_t * \/*option*\/) const\n{\n \/\/ Standard print function.\n\n Printf(\"OBJ: %s\\t%s\\t%s\", IsA()->GetName(), GetName(), (IsOk() ? \"OK\" : \"ERROR\"));\n\n MsgIter_t i = fMsgs.begin();\n for (; i != fMsgs.end(); i++)\n Printf(\"\\t%s\", (*i).c_str());\n\n Printf(\" Max virtual memory: %.2f MB \\tMax resident memory: %.2f MB \",\n GetVirtMemMax()\/1024., GetResMemMax()\/1024.);\n}\n\n\/\/______________________________________________________________________________\nvoid TStatus::Reset()\n{\n \/\/ Reset the iterator on the messages.\n\n fIter = fMsgs.begin();\n}\n\n\/\/______________________________________________________________________________\nconst char *TStatus::NextMesg()\n{\n \/\/ Return the next message or 0.\n\n if (fIter != fMsgs.end()) {\n return (*fIter++).c_str();\n } else {\n return 0;\n }\n}\n\n\/\/______________________________________________________________________________\nvoid TStatus::SetMemValues(Long_t vmem, Long_t rmem)\n{\n \/\/ Set max memory values\n\n if (vmem > 0. && (fVirtMemMax < 0. || vmem > fVirtMemMax)) fVirtMemMax = vmem;\n if (rmem > 0. && (fResMemMax < 0. || rmem > fResMemMax)) fResMemMax = rmem;\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/* This file is part of the KDE project\n Copyright (C) 2005 Michal Vaner <michal.vaner@kdemail.net>\n Copyright (C) 2008-2009 Pali Rohár <pali.rohar@gmail.com>\n\n This library is free software; you can redistribute it and\/or\n modify it under the terms of the GNU Library General Public\n License version 2 as published by the Free Software Foundation.\n\n This library is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n Library General Public License for more details.\n\n You should have received a copy of the GNU Library General Public License\n along with this library; see the file COPYING.LIB. If not, write to\n the Free Software Foundation, Inc., 59 Temple Place - Suite 330,\n Boston, MA 02111-1307, USA.\n\n*\/\n#include \"skypeprotocol.h\"\n#include \"skypeeditaccount.h\"\n#include \"skypeaccount.h\"\n#include \"skypeaddcontact.h\"\n#include \"skypecontact.h\"\n\n#include <kopeteonlinestatusmanager.h>\n#include <kgenericfactory.h>\n#include <qstring.h>\n#include <qstringlist.h>\n#include <kdebug.h>\n#include <kaction.h>\n#include <kactioncollection.h>\n#include <kshortcut.h>\n#include <kopetecontactlist.h>\n#include <kopetemetacontact.h>\n\nK_PLUGIN_FACTORY( SkypeProtocolFactory, registerPlugin<SkypeProtocol>(); )\nK_EXPORT_PLUGIN( SkypeProtocolFactory( \"kopete_skype\" ) )\n\nSkypeProtocol *SkypeProtocol::s_protocol = 0L;\n\nclass SkypeProtocolPrivate {\n\tprivate:\n\tpublic:\n\t\t\/\/\/The \"call contact\" action\n\t\tKAction *callContactAction;\n\t\t\/\/\/Pointer to the account\n\t\tSkypeAccount *account;\n\t\t\/\/\/Constructor\n\t\tSkypeProtocolPrivate() {\n\t\t\taccount = 0L;\/\/no account yet\n\t\t\tcallContactAction = 0L;\n\t\t}\n};\n\nSkypeProtocol::SkypeProtocol(QObject *parent, const QList<QVariant>&) :\n\tKopete::Protocol(SkypeProtocolFactory::componentData(), parent),\/\/create the parent\n\tOffline(Kopete::OnlineStatus::Offline, 0, this, 1, QStringList(\"skype_contact_offline\"), i18n(\"Offline\"), i18n(\"Offline\"), Kopete::OnlineStatusManager::Offline),\/\/and online statuses\n\tOnline(Kopete::OnlineStatus::Online, 1, this, 2, QStringList(\"skype_contact_online\"), i18n(\"Online\"), i18n(\"Online\"), Kopete::OnlineStatusManager::Online),\n\tSkypeMe(Kopete::OnlineStatus::Online, 0, this, 3, QStringList(\"skype_contact_skypeme\"), i18n(\"Skype Me\"), i18n(\"Skype Me\"), Kopete::OnlineStatusManager::FreeForChat),\n\tAway(Kopete::OnlineStatus::Away, 2, this, 4, QStringList(\"skype_contact_away\"), i18n(\"Away\"), i18n(\"Away\"), Kopete::OnlineStatusManager::Away),\n\tNotAvailable(Kopete::OnlineStatus::Away, 1, this, 5, QStringList(\"skype_contact_not_available\"), i18n(\"Not Available\"), i18n(\"Not Available\"), Kopete::OnlineStatusManager::Away),\n\tDoNotDisturb(Kopete::OnlineStatus::Away, 0, this, 6, QStringList(\"skype_contact_dnd\"), i18n(\"Do Not Disturb\"), i18n(\"Do Not Disturb\"), Kopete::OnlineStatusManager::Busy),\n\tInvisible(Kopete::OnlineStatus::Invisible, 0, this, 7, QStringList(\"skype_contact_invisible\"), i18n(\"Invisible\"), i18n(\"Invisible\"), Kopete::OnlineStatusManager::Invisible),\n\tConnecting(Kopete::OnlineStatus::Connecting, 0, this, 8, QStringList(\"skype_connecting\"), i18n(\"Connecting\")),\n\tNotInList(Kopete::OnlineStatus::Offline, 0, this, 9, QStringList(\"skype_contact_unknown\"), i18n(\"Not in Skype list\")),\n\tNoAuth(Kopete::OnlineStatus::Offline, 0, this, 10, QStringList(\"skype_contact_unknown\"), i18n(\"Not authorized\")),\n\tPhone(Kopete::OnlineStatus::Online, 0, this, 11, QStringList(\"skype_contact_skypeout\"), i18n(\"SkypeOut contact\")),\n\t\/** Contact property templates *\/\n\tpropFullName(Kopete::Global::Properties::self()->fullName()),\n\tpropPrivatePhone(Kopete::Global::Properties::self()->privatePhone()),\n\tpropPrivateMobilePhone(Kopete::Global::Properties::self()->privateMobilePhone()),\n\tpropWorkPhone(Kopete::Global::Properties::self()->workPhone()),\n\tpropLastSeen(Kopete::Global::Properties::self()->lastSeen())\n\n{\n\tkDebug(SKYPE_DEBUG_GLOBAL);\n\t\/\/create the d pointer\n\td = new SkypeProtocolPrivate();\n\t\/\/add address book field\n\taddAddressBookField(\"messaging\/skype\", Kopete::Plugin::MakeIndexField);\n\n\tsetXMLFile(\"skypeui.rc\");\n\n\td->callContactAction = new KAction( this );\n\td->callContactAction->setIcon( (KIcon(\"skype_call\") ) );\n\td->callContactAction->setText( i18n (\"Call\") );\n\tconnect(d->callContactAction, SIGNAL(triggered(bool)), SLOT(callContacts()));\n\n\tactionCollection()->addAction(\"callSkypeContact\", d->callContactAction);\n\n\tupdateCallActionStatus();\n\tconnect(Kopete::ContactList::self(), SIGNAL(metaContactSelected(bool)), this, SLOT(updateCallActionStatus()));\n\n\ts_protocol = this;\n}\n\nSkypeProtocol::~SkypeProtocol() {\n\tkDebug(SKYPE_DEBUG_GLOBAL);\n\t\/\/release the memory\n\tdelete d;\n}\n\nKopete::Account *SkypeProtocol::createNewAccount(const QString & accountID) {\n\tkDebug(SKYPE_DEBUG_GLOBAL);\n\t\/\/just create one\n\treturn new SkypeAccount(this, accountID);\n}\n\nAddContactPage *SkypeProtocol::createAddContactWidget(QWidget *parent, Kopete::Account *account) {\n\tkDebug(SKYPE_DEBUG_GLOBAL);\n\treturn new SkypeAddContact(this, parent, (SkypeAccount *)account, 0L);\n}\n\nKopeteEditAccountWidget *SkypeProtocol::createEditAccountWidget(Kopete::Account *account, QWidget *parent) {\n\tkDebug(SKYPE_DEBUG_GLOBAL);\n\treturn new skypeEditAccount(this, account, parent);\/\/create the widget and return it\n}\n\nvoid SkypeProtocol::registerAccount(SkypeAccount *account) {\n\tkDebug(SKYPE_DEBUG_GLOBAL);\n\n\td->account = account;\n}\n\nvoid SkypeProtocol::unregisterAccount() {\n\tkDebug(SKYPE_DEBUG_GLOBAL);\n\n\td->account = 0L;\/\/forget everything about the account\n}\n\nbool SkypeProtocol::hasAccount() const {\n\tkDebug(SKYPE_DEBUG_GLOBAL);\n\n\treturn (d->account);\n}\n\nKopete::Contact *SkypeProtocol::deserializeContact(Kopete::MetaContact *metaContact, const QMap<QString, QString> &serializedData, const QMap<QString, QString> &) {\n\tkDebug(SKYPE_DEBUG_GLOBAL) << \"Name: \" << serializedData[\"contactId\"].toLower();\n\n\tQString contactID = serializedData[\"contactId\"].toLower();\/\/get the contact ID\n\tQString accountId = serializedData[\"accountId\"];\n\n\tif (!d->account) {\n\t\tkDebug(SKYPE_DEBUG_GLOBAL) << \"Account does not exists, skiping contact creation\";\/\/write error for debugging\n\t\treturn 0L;\/\/create nothing\n\t}\n\n\tif (d->account->contact(contactID)) {\n\t\tkDebug(SKYPE_DEBUG_GLOBAL) << \"Contact\" << contactID << \"exists in contact list, skipping contact creation\";\n\t\treturn 0L;\n\t}\n\n\treturn new SkypeContact(d->account, contactID, metaContact);\/\/create the contact\n}\n\nvoid SkypeProtocol::updateCallActionStatus() {\n\tkDebug(SKYPE_DEBUG_GLOBAL);\n\n\tbool enab = false;\n\n\tif ((Kopete::ContactList::self()->selectedMetaContacts().count() != 1) && ((!d->account) || (!d->account->ableMultiCall()))) {\n\t\td->callContactAction->setEnabled(false);\n\t\treturn;\n\t}\n\n\t\/\/Run trough all selected contacts and find if there is any skype contact\n\tconst QList<Kopete::MetaContact*> &selected = Kopete::ContactList::self()->selectedMetaContacts();\n\tfor (QList<Kopete::MetaContact*>::const_iterator met = selected.begin(); met != selected.end(); ++met) {\n\t\tconst QList<Kopete::Contact*> &metaCont = (*met)->contacts();\n\t\tfor (QList<Kopete::Contact*>::const_iterator con = metaCont.begin(); con != metaCont.end(); ++con) {\n\t\t\tif ((*con)->protocol() == this) {\/\/This is skype contact, ask it if it can be called\n\t\t\t\tSkypeContact *thisCont = static_cast<SkypeContact *> (*con);\n\t\t\t\tif (thisCont->canCall()) {\n\t\t\t\t\tenab = true;\n\t\t\t\t\tgoto OUTSIDE;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tOUTSIDE:\n\td->callContactAction->setEnabled(enab);\n}\n\nvoid SkypeProtocol::callContacts() {\n\tkDebug(SKYPE_DEBUG_GLOBAL);\n\n\tQString list;\n\n\tconst QList<Kopete::MetaContact*> &selected = Kopete::ContactList::self()->selectedMetaContacts();\n\tfor (QList<Kopete::MetaContact*>::const_iterator met = selected.begin(); met != selected.end(); ++met) {\n\t\tconst QList<Kopete::Contact*> &metaCont = (*met)->contacts();\n\t\tfor (QList<Kopete::Contact*>::const_iterator con = metaCont.begin(); con != metaCont.end(); ++con) {\n\t\t\tif ((*con)->protocol() == this) {\/\/This is skype contact, ask it if it can be called\n\t\t\t\tSkypeContact *thisCont = static_cast<SkypeContact *> (*con);\n\t\t\t\tif (thisCont->canCall()) {\n\t\t\t\t\tif (!list.isEmpty())\n\t\t\t\t\t\tlist += \", \";\n\t\t\t\t\tlist += thisCont->contactId();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tif (!list.isEmpty()) {\n\t\td->account->makeCall(list);\n\t}\n}\n\nSkypeProtocol *SkypeProtocol::protocol()\n{\n\treturn s_protocol;\n}\n\n#include \"skypeprotocol.moc\"\n<commit_msg>Make all SkypeOut contacts still offline<commit_after>\/* This file is part of the KDE project\n Copyright (C) 2005 Michal Vaner <michal.vaner@kdemail.net>\n Copyright (C) 2008-2009 Pali Rohár <pali.rohar@gmail.com>\n\n This library is free software; you can redistribute it and\/or\n modify it under the terms of the GNU Library General Public\n License version 2 as published by the Free Software Foundation.\n\n This library is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n Library General Public License for more details.\n\n You should have received a copy of the GNU Library General Public License\n along with this library; see the file COPYING.LIB. If not, write to\n the Free Software Foundation, Inc., 59 Temple Place - Suite 330,\n Boston, MA 02111-1307, USA.\n\n*\/\n#include \"skypeprotocol.h\"\n#include \"skypeeditaccount.h\"\n#include \"skypeaccount.h\"\n#include \"skypeaddcontact.h\"\n#include \"skypecontact.h\"\n\n#include <kopeteonlinestatusmanager.h>\n#include <kgenericfactory.h>\n#include <qstring.h>\n#include <qstringlist.h>\n#include <kdebug.h>\n#include <kaction.h>\n#include <kactioncollection.h>\n#include <kshortcut.h>\n#include <kopetecontactlist.h>\n#include <kopetemetacontact.h>\n\nK_PLUGIN_FACTORY( SkypeProtocolFactory, registerPlugin<SkypeProtocol>(); )\nK_EXPORT_PLUGIN( SkypeProtocolFactory( \"kopete_skype\" ) )\n\nSkypeProtocol *SkypeProtocol::s_protocol = 0L;\n\nclass SkypeProtocolPrivate {\n\tprivate:\n\tpublic:\n\t\t\/\/\/The \"call contact\" action\n\t\tKAction *callContactAction;\n\t\t\/\/\/Pointer to the account\n\t\tSkypeAccount *account;\n\t\t\/\/\/Constructor\n\t\tSkypeProtocolPrivate() {\n\t\t\taccount = 0L;\/\/no account yet\n\t\t\tcallContactAction = 0L;\n\t\t}\n};\n\nSkypeProtocol::SkypeProtocol(QObject *parent, const QList<QVariant>&) :\n\tKopete::Protocol(SkypeProtocolFactory::componentData(), parent),\/\/create the parent\n\tOffline(Kopete::OnlineStatus::Offline, 0, this, 1, QStringList(\"skype_contact_offline\"), i18n(\"Offline\"), i18n(\"Offline\"), Kopete::OnlineStatusManager::Offline),\/\/and online statuses\n\tOnline(Kopete::OnlineStatus::Online, 1, this, 2, QStringList(\"skype_contact_online\"), i18n(\"Online\"), i18n(\"Online\"), Kopete::OnlineStatusManager::Online),\n\tSkypeMe(Kopete::OnlineStatus::Online, 0, this, 3, QStringList(\"skype_contact_skypeme\"), i18n(\"Skype Me\"), i18n(\"Skype Me\"), Kopete::OnlineStatusManager::FreeForChat),\n\tAway(Kopete::OnlineStatus::Away, 2, this, 4, QStringList(\"skype_contact_away\"), i18n(\"Away\"), i18n(\"Away\"), Kopete::OnlineStatusManager::Away),\n\tNotAvailable(Kopete::OnlineStatus::Away, 1, this, 5, QStringList(\"skype_contact_not_available\"), i18n(\"Not Available\"), i18n(\"Not Available\"), Kopete::OnlineStatusManager::Away),\n\tDoNotDisturb(Kopete::OnlineStatus::Away, 0, this, 6, QStringList(\"skype_contact_dnd\"), i18n(\"Do Not Disturb\"), i18n(\"Do Not Disturb\"), Kopete::OnlineStatusManager::Busy),\n\tInvisible(Kopete::OnlineStatus::Invisible, 0, this, 7, QStringList(\"skype_contact_invisible\"), i18n(\"Invisible\"), i18n(\"Invisible\"), Kopete::OnlineStatusManager::Invisible),\n\tConnecting(Kopete::OnlineStatus::Connecting, 0, this, 8, QStringList(\"skype_connecting\"), i18n(\"Connecting\")),\n\tNotInList(Kopete::OnlineStatus::Offline, 0, this, 9, QStringList(\"skype_contact_unknown\"), i18n(\"Not in Skype list\")),\n\tNoAuth(Kopete::OnlineStatus::Offline, 0, this, 10, QStringList(\"skype_contact_unknown\"), i18n(\"Not authorized\")),\n\tPhone(Kopete::OnlineStatus::Offline, 0, this, 11, QStringList(\"skype_contact_skypeout\"), i18n(\"SkypeOut contact\")), \/\/Skype Out contact permanently offline TODO: add option for changing\n\t\/** Contact property templates *\/\n\tpropFullName(Kopete::Global::Properties::self()->fullName()),\n\tpropPrivatePhone(Kopete::Global::Properties::self()->privatePhone()),\n\tpropPrivateMobilePhone(Kopete::Global::Properties::self()->privateMobilePhone()),\n\tpropWorkPhone(Kopete::Global::Properties::self()->workPhone()),\n\tpropLastSeen(Kopete::Global::Properties::self()->lastSeen())\n\n{\n\tkDebug(SKYPE_DEBUG_GLOBAL);\n\t\/\/create the d pointer\n\td = new SkypeProtocolPrivate();\n\t\/\/add address book field\n\taddAddressBookField(\"messaging\/skype\", Kopete::Plugin::MakeIndexField);\n\n\tsetXMLFile(\"skypeui.rc\");\n\n\td->callContactAction = new KAction( this );\n\td->callContactAction->setIcon( (KIcon(\"skype_call\") ) );\n\td->callContactAction->setText( i18n (\"Call\") );\n\tconnect(d->callContactAction, SIGNAL(triggered(bool)), SLOT(callContacts()));\n\n\tactionCollection()->addAction(\"callSkypeContact\", d->callContactAction);\n\n\tupdateCallActionStatus();\n\tconnect(Kopete::ContactList::self(), SIGNAL(metaContactSelected(bool)), this, SLOT(updateCallActionStatus()));\n\n\ts_protocol = this;\n}\n\nSkypeProtocol::~SkypeProtocol() {\n\tkDebug(SKYPE_DEBUG_GLOBAL);\n\t\/\/release the memory\n\tdelete d;\n}\n\nKopete::Account *SkypeProtocol::createNewAccount(const QString & accountID) {\n\tkDebug(SKYPE_DEBUG_GLOBAL);\n\t\/\/just create one\n\treturn new SkypeAccount(this, accountID);\n}\n\nAddContactPage *SkypeProtocol::createAddContactWidget(QWidget *parent, Kopete::Account *account) {\n\tkDebug(SKYPE_DEBUG_GLOBAL);\n\treturn new SkypeAddContact(this, parent, (SkypeAccount *)account, 0L);\n}\n\nKopeteEditAccountWidget *SkypeProtocol::createEditAccountWidget(Kopete::Account *account, QWidget *parent) {\n\tkDebug(SKYPE_DEBUG_GLOBAL);\n\treturn new skypeEditAccount(this, account, parent);\/\/create the widget and return it\n}\n\nvoid SkypeProtocol::registerAccount(SkypeAccount *account) {\n\tkDebug(SKYPE_DEBUG_GLOBAL);\n\n\td->account = account;\n}\n\nvoid SkypeProtocol::unregisterAccount() {\n\tkDebug(SKYPE_DEBUG_GLOBAL);\n\n\td->account = 0L;\/\/forget everything about the account\n}\n\nbool SkypeProtocol::hasAccount() const {\n\tkDebug(SKYPE_DEBUG_GLOBAL);\n\n\treturn (d->account);\n}\n\nKopete::Contact *SkypeProtocol::deserializeContact(Kopete::MetaContact *metaContact, const QMap<QString, QString> &serializedData, const QMap<QString, QString> &) {\n\tkDebug(SKYPE_DEBUG_GLOBAL) << \"Name: \" << serializedData[\"contactId\"].toLower();\n\n\tQString contactID = serializedData[\"contactId\"].toLower();\/\/get the contact ID\n\tQString accountId = serializedData[\"accountId\"];\n\n\tif (!d->account) {\n\t\tkDebug(SKYPE_DEBUG_GLOBAL) << \"Account does not exists, skiping contact creation\";\/\/write error for debugging\n\t\treturn 0L;\/\/create nothing\n\t}\n\n\tif (d->account->contact(contactID)) {\n\t\tkDebug(SKYPE_DEBUG_GLOBAL) << \"Contact\" << contactID << \"exists in contact list, skipping contact creation\";\n\t\treturn 0L;\n\t}\n\n\treturn new SkypeContact(d->account, contactID, metaContact);\/\/create the contact\n}\n\nvoid SkypeProtocol::updateCallActionStatus() {\n\tkDebug(SKYPE_DEBUG_GLOBAL);\n\n\tbool enab = false;\n\n\tif ((Kopete::ContactList::self()->selectedMetaContacts().count() != 1) && ((!d->account) || (!d->account->ableMultiCall()))) {\n\t\td->callContactAction->setEnabled(false);\n\t\treturn;\n\t}\n\n\t\/\/Run trough all selected contacts and find if there is any skype contact\n\tconst QList<Kopete::MetaContact*> &selected = Kopete::ContactList::self()->selectedMetaContacts();\n\tfor (QList<Kopete::MetaContact*>::const_iterator met = selected.begin(); met != selected.end(); ++met) {\n\t\tconst QList<Kopete::Contact*> &metaCont = (*met)->contacts();\n\t\tfor (QList<Kopete::Contact*>::const_iterator con = metaCont.begin(); con != metaCont.end(); ++con) {\n\t\t\tif ((*con)->protocol() == this) {\/\/This is skype contact, ask it if it can be called\n\t\t\t\tSkypeContact *thisCont = static_cast<SkypeContact *> (*con);\n\t\t\t\tif (thisCont->canCall()) {\n\t\t\t\t\tenab = true;\n\t\t\t\t\tgoto OUTSIDE;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tOUTSIDE:\n\td->callContactAction->setEnabled(enab);\n}\n\nvoid SkypeProtocol::callContacts() {\n\tkDebug(SKYPE_DEBUG_GLOBAL);\n\n\tQString list;\n\n\tconst QList<Kopete::MetaContact*> &selected = Kopete::ContactList::self()->selectedMetaContacts();\n\tfor (QList<Kopete::MetaContact*>::const_iterator met = selected.begin(); met != selected.end(); ++met) {\n\t\tconst QList<Kopete::Contact*> &metaCont = (*met)->contacts();\n\t\tfor (QList<Kopete::Contact*>::const_iterator con = metaCont.begin(); con != metaCont.end(); ++con) {\n\t\t\tif ((*con)->protocol() == this) {\/\/This is skype contact, ask it if it can be called\n\t\t\t\tSkypeContact *thisCont = static_cast<SkypeContact *> (*con);\n\t\t\t\tif (thisCont->canCall()) {\n\t\t\t\t\tif (!list.isEmpty())\n\t\t\t\t\t\tlist += \", \";\n\t\t\t\t\tlist += thisCont->contactId();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tif (!list.isEmpty()) {\n\t\td->account->makeCall(list);\n\t}\n}\n\nSkypeProtocol *SkypeProtocol::protocol()\n{\n\treturn s_protocol;\n}\n\n#include \"skypeprotocol.moc\"\n<|endoftext|>"} {"text":"<commit_before>\/****************************************************************************\n**\n** Copyright (C) 2009 Nokia Corporation and\/or its subsidiary(-ies).\n** All rights reserved.\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n** This file is part of the Qt Mobility Components.\n**\n** $QT_BEGIN_LICENSE:LGPL$\n** No Commercial Usage\n** This file contains pre-release code and may not be distributed.\n** You may use this file in accordance with the terms and conditions\n** contained in the Technology Preview License Agreement accompanying\n** this package.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Nokia gives you certain additional\n** rights. These rights are described in the Nokia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at qt-info@nokia.com.\n**\n**\n**\n**\n**\n**\n**\n**\n** $QT_END_LICENSE$\n**\n****************************************************************************\/\n\n#include \"qcontactmaemo5backend_p.h\"\n\n#include <QSharedData>\n\n#include \"qcontactmaemo5debug_p.h\"\n\nDEFINE_GLOBAL_DEBUG_VAR\n\nQContactManagerEngine* ContactMaemo5Factory::engine(const QMap<QString, QString>& parameters, QContactManager::Error* error)\n{\n Q_UNUSED(parameters);\n Q_UNUSED(error);\n\n initDebugLogger();\n return new QContactMaemo5Engine(); \/\/FIXME Wonderfull memory leak :D\n}\n\nQString ContactMaemo5Factory::managerName() const\n{\n return QString(\"maemo5\");\n}\n\nQ_EXPORT_PLUGIN2(qtcontacts_maemo5, ContactMaemo5Factory);\n\n\/*!\n \\class QContactMaemo5Engine\n \\brief The QContactMaemo5Engine class provides an implementation of\n QContactManagerEngine whose functions always return an error.\n \n The Maemo5 engine.\n *\/\n\n\/*! Constructs a new invalid contacts backend. *\/\nQContactMaemo5Engine::QContactMaemo5Engine() : d(new QContactMaemo5EngineData)\n{\n QContactABook *abook = d->m_abook;\n connect(abook, SIGNAL(contactsAdded(const QList<QContactLocalId>&)), SIGNAL(contactsAdded(const QList<QContactLocalId>&)));\n connect(abook, SIGNAL(contactsChanged(const QList<QContactLocalId>&)), SIGNAL(contactsChanged(const QList<QContactLocalId>&)));\n connect(abook, SIGNAL(contactsRemoved(const QList<QContactLocalId>&)), SIGNAL(contactsRemoved(const QList<QContactLocalId>&)));\n}\n\n\/*! \\reimp *\/\nQContactMaemo5Engine& QContactMaemo5Engine::operator=(const QContactMaemo5Engine& other)\n{\n d = other.d;\n return *this;\n}\n\n\/*! \\reimp *\/\nQString QContactMaemo5Engine::managerName() const\n{\n return QString(QLatin1String(\"maemo5\"));\n}\n\n\/* Synthesise the display label of a contact *\/\nQString QContactMaemo5Engine::synthesizedDisplayLabel(const QContact& contact, QContactManager::Error* error) const\n{\n Q_UNUSED(error)\n QString label = QContactManagerEngine::synthesizedDisplayLabel(contact, error);\n \n if (label.isEmpty()) {\n QContactNickname n = contact.detail(QContactNickname::DefinitionName);\n label = n.nickname();\n }\n \n if (label.isEmpty())\n label = \"No name\";\n \n return label;\n}\n\nbool QContactMaemo5Engine::validateContact(const QContact& contact, QContactManager::Error* error) const\n{\n return QContactManagerEngine::validateContact(contact, error);\n}\n\nbool QContactMaemo5Engine::validateDefinition(const QContactDetailDefinition& definition, QContactManager::Error* error) const\n{\n QContactDetailDefinition existing = detailDefinition(definition.name(), QContactType::TypeContact, error);\n if (existing == definition) {\n *error = QContactManager::NoError;\n return true;\n }\n\n *error = QContactManager::NotSupportedError; \/\/ XXX TODO: mutable definitions?\n return false;\n}\n\nQContactLocalId QContactMaemo5Engine::selfContactId(QContactManager::Error* error) const\n{\n Q_CHECK_PTR(d->m_abook);\n\n return d->m_abook->selfContactId(error);\n}\n\nQList<QContactLocalId> QContactMaemo5Engine::contactIds(const QContactFilter& filter, const QList<QContactSortOrder>& sortOrders, QContactManager::Error* error) const\n{\n Q_CHECK_PTR(d->m_abook);\n \n \/\/return QContactManagerEngine::contactIds(filter, sortOrders, error);\n return d->m_abook->contactIds(filter, sortOrders, error);\n}\n\nQList<QContact> QContactMaemo5Engine::contacts(const QContactFilter & filter, const QList<QContactSortOrder> & sortOrders, const QContactFetchHint & fetchHint,\n\t\t\t QContactManager::Error* error ) const\n{\n Q_UNUSED(fetchHint); \/\/ no optimisations currently, ignore the fetchhint.\n Q_CHECK_PTR(d->m_abook);\n QList<QContact> rtn;\n \n QList<QContactLocalId> ids = contactIds(filter, sortOrders,error);\n foreach (QContactLocalId id, ids)\n rtn << contact(id, QContactFetchHint(), error);\n return rtn;\n}\n\nQContact QContactMaemo5Engine::contact(const QContactLocalId& contactId, const QContactFetchHint& fetchHint, QContactManager::Error* error) const\n{\n Q_UNUSED(fetchHint); \/\/TODO\n Q_CHECK_PTR(d->m_abook);\n \n QContact *contact = d->m_abook->getQContact(contactId, error);\n QContact rtn(*contact);\n delete contact;\n setContactDisplayLabel(&rtn, synthesizedDisplayLabel(rtn, error));\n return rtn;\n}\n\nbool QContactMaemo5Engine::saveContacts(QList<QContact>* contacts, QMap<int, QContactManager::Error>* errorMap, QContactManager::Error* error)\n{\n *error = QContactManager::NoError;\n QContactManager::Error tempError = QContactManager::NoError;\n QContact curr;\n for (int i = 0; i < contacts->size(); i++) {\n curr = contacts->at(i);\n if (!saveContact(&curr, &tempError)) {\n errorMap->insert(i, tempError);\n *error = tempError;\n } else {\n contacts->replace(i, curr);\n }\n }\n\n return (*error == QContactManager::NoError);\n}\n\nbool QContactMaemo5Engine::removeContacts(const QList<QContactLocalId>& ids, QMap<int, QContactManager::Error>* errorMap, QContactManager::Error* error)\n{\n *error = QContactManager::NoError;\n QContactManager::Error tempError = QContactManager::NoError;\n QContact curr;\n for (int i = 0; i < ids.size(); i++) {\n if (!removeContact(ids.at(i), &tempError)) {\n errorMap->insert(i, tempError);\n *error = tempError;\n }\n }\n\n return (*error == QContactManager::NoError);\n}\n\nbool QContactMaemo5Engine::saveContact(QContact* contact, QContactManager::Error* error)\n{\n Q_CHECK_PTR(d->m_abook);\n \n if (!contact) {\n *error = QContactManager::BadArgumentError;\n return false;\n }\n\n \/\/ synthesize the display label for the contact\n setContactDisplayLabel(contact, synthesizedDisplayLabel(*contact, error));\n\n \/\/ ensure that the contact's details conform to their definitions\n if (!validateContact(*contact, error)) {\n QCM5_DEBUG << \"Validate Contact failed\";\n return false;\n }\n\n bool retn = d->m_abook->saveContact(contact, error);\n QContactId cId = contact->id();\n cId.setManagerUri(managerUri());\n contact->setId(cId);\n return retn;\n}\n\n#if 0\nQList<QContactManager::Error> QContactMaemo5Engine::removeContacts(QList<QContactLocalId>* contactIds, QContactManager::Error* error)\n{\n bool ok = true;\n \n if (contactIds->isEmpty())\n return false;\n \n QContactLocalId id;\n foreach(id, contactIds){\n if (!removeContact(id, error))\n\tok = false;\n }\n \n return ok;\n}\n#endif\n\nbool QContactMaemo5Engine::removeContact(const QContactLocalId& contactId, QContactManager::Error* error)\n{\n Q_CHECK_PTR(d->m_abook);\n return d->m_abook->removeContact(contactId, error);\n}\n\nQMap<QString, QContactDetailDefinition> QContactMaemo5Engine::detailDefinitions(const QString& contactType, QContactManager::Error* error) const\n{\n\n QMap<QString, QMap<QString, QContactDetailDefinition> > defns = QContactManagerEngine::schemaDefinitions();\n \n QMap<QString, QContactDetailFieldDefinition> fields;\n \n QContactDetailFieldDefinition gsfd; \/\/Generic string field definition\n gsfd.setDataType(QVariant::String);\n \n \/\/ QContactAddress\n fields = defns[contactType][QContactAddress::DefinitionName].fields();\n \/\/fields.remove(QContactAddress::FieldSubTypes);\n fields.insert(\"Estension\", gsfd);\n fields.insert(QContactDetail::FieldDetailUri, gsfd);\n defns[contactType][QContactAddress::DefinitionName].setFields(fields);\n \n \/\/ QContactAnniversary\n defns[contactType].remove(QContactAnniversary::DefinitionName);\n \n \/\/ QContactAvatar\n \/\/ TODO setUnique(true);\n \/\/ QContactBirthday\n \/\/ QContactDisplayLabel\n \n \/\/ QContactEmailAddress\n fields = defns[contactType][QContactEmailAddress::DefinitionName].fields();\n fields.insert(QContactDetail::FieldDetailUri, gsfd);\n defns[contactType][QContactEmailAddress::DefinitionName].setFields(fields);\n \n \/\/ QContactFamily\n \/\/ QContactGender\n \/\/ QContactGeoLocation\n defns[contactType].remove(QContactGeoLocation::DefinitionName);\n \n \/\/ QContactGuid\n \/\/ QContactName\n fields = defns[contactType][QContactName::DefinitionName].fields();\n fields.remove(QContactName::FieldCustomLabel);\n fields.remove(QContactName::FieldPrefix);\n fields.remove(QContactName::FieldSuffix);\n defns[contactType][QContactName::DefinitionName].setFields(fields);\n \n \/\/ QContactNickname\n \/\/ QContactNote\n \/\/ QContactOnlineAccount\n fields = defns[contactType][QContactOnlineAccount::DefinitionName].fields();\n fields.remove(QContactOnlineAccount::FieldAccountUri);\n fields.remove(QContactOnlineAccount::FieldSubTypes);\n fields.insert(\"AccountPath\", gsfd);\n defns[contactType][QContactOnlineAccount::DefinitionName].setFields(fields);\n \n \/\/ QContactOrganization\n fields = defns[contactType][QContactOrganization::DefinitionName].fields();\n fields.remove(QContactOrganization::FieldAssistantName);\n fields.remove(QContactOrganization::FieldDepartment);\n fields.remove(QContactOrganization::FieldLocation);\n fields.remove(QContactOrganization::FieldLogoUrl);\n fields.remove(QContactOrganization::FieldName);\n fields.remove(QContactOrganization::FieldRole);\n defns[contactType][QContactOrganization::DefinitionName].setFields(fields);\n \n \/\/ QContactPhoneNumber\n fields = defns[contactType][QContactPhoneNumber::DefinitionName].fields();\n fields.insert(QContactDetail::FieldDetailUri, gsfd);\n defns[contactType][QContactPhoneNumber::DefinitionName].setFields(fields);\n \n \/\/ QContactSyncTarget\n defns[contactType].remove(QContactSyncTarget::DefinitionName);\n \n \/\/ QContactTimestamp\n \/\/ QContactType\n \/\/ QContactUrl\n fields = defns[contactType][QContactUrl::DefinitionName].fields();\n fields.remove(QContactUrl::FieldSubType);\n defns[contactType][QContactUrl::DefinitionName].setFields(fields);\n \n \/\/Still unmanaged: GlobalPresence, Presence, Ringtone, Tag\n \n QCM5_DEBUG << \"Contact type\" << contactType << \"Keys\" << defns.keys();\n \n *error = QContactManager::NoError;\n return defns[contactType];\n}\n\nQContactDetailDefinition QContactMaemo5Engine::detailDefinition(const QString& definitionName, const QString& contactType, QContactManager::Error* error) const\n{\n return QContactManagerEngine::detailDefinition(definitionName, contactType, error);\n}\n\nbool QContactMaemo5Engine::hasFeature(QContactManager::ManagerFeature feature, const QString& contactType) const {\n Q_UNUSED(contactType);\n if (feature == QContactManager::Anonymous)\n return true;\n \n return false;\n}\n\nbool QContactMaemo5Engine::isFilterSupported(const QContactFilter& filter) const {\n switch (filter.type()) {\n case QContactFilter::InvalidFilter:\n case QContactFilter::DefaultFilter:\n case QContactFilter::LocalIdFilter:\n case QContactFilter::ContactDetailFilter:\n case QContactFilter::ActionFilter:\n case QContactFilter::IntersectionFilter:\n case QContactFilter::UnionFilter:\n return true;\n default:\n return false;\n }\n}\n\nQList<QVariant::Type> QContactMaemo5Engine::supportedDataTypes() const {\n QList<QVariant::Type> st;\n st.append(QVariant::String);\n st.append(QVariant::Int);\n st.append(QVariant::UInt);\n st.append(QVariant::Double);\n st.append(QVariant::Date);\n st.append(QVariant::DateTime);\n\n return st; \n}\n<commit_msg>Remove old QContactMaemo5Engine::removeContacts code (cherry picked from commit 93a9f0b8a86ec2a7c154bb48edabe18716e463e2)<commit_after>\/****************************************************************************\n**\n** Copyright (C) 2009 Nokia Corporation and\/or its subsidiary(-ies).\n** All rights reserved.\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n** This file is part of the Qt Mobility Components.\n**\n** $QT_BEGIN_LICENSE:LGPL$\n** No Commercial Usage\n** This file contains pre-release code and may not be distributed.\n** You may use this file in accordance with the terms and conditions\n** contained in the Technology Preview License Agreement accompanying\n** this package.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Nokia gives you certain additional\n** rights. These rights are described in the Nokia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at qt-info@nokia.com.\n**\n**\n**\n**\n**\n**\n**\n**\n** $QT_END_LICENSE$\n**\n****************************************************************************\/\n\n#include \"qcontactmaemo5backend_p.h\"\n\n#include <QSharedData>\n\n#include \"qcontactmaemo5debug_p.h\"\n\nDEFINE_GLOBAL_DEBUG_VAR\n\nQContactManagerEngine* ContactMaemo5Factory::engine(const QMap<QString, QString>& parameters, QContactManager::Error* error)\n{\n Q_UNUSED(parameters);\n Q_UNUSED(error);\n\n initDebugLogger();\n return new QContactMaemo5Engine(); \/\/FIXME Wonderfull memory leak :D\n}\n\nQString ContactMaemo5Factory::managerName() const\n{\n return QString(\"maemo5\");\n}\n\nQ_EXPORT_PLUGIN2(qtcontacts_maemo5, ContactMaemo5Factory);\n\n\/*!\n \\class QContactMaemo5Engine\n \\brief The QContactMaemo5Engine class provides an implementation of\n QContactManagerEngine whose functions always return an error.\n \n The Maemo5 engine.\n *\/\n\n\/*! Constructs a new invalid contacts backend. *\/\nQContactMaemo5Engine::QContactMaemo5Engine() : d(new QContactMaemo5EngineData)\n{\n QContactABook *abook = d->m_abook;\n connect(abook, SIGNAL(contactsAdded(const QList<QContactLocalId>&)), SIGNAL(contactsAdded(const QList<QContactLocalId>&)));\n connect(abook, SIGNAL(contactsChanged(const QList<QContactLocalId>&)), SIGNAL(contactsChanged(const QList<QContactLocalId>&)));\n connect(abook, SIGNAL(contactsRemoved(const QList<QContactLocalId>&)), SIGNAL(contactsRemoved(const QList<QContactLocalId>&)));\n}\n\n\/*! \\reimp *\/\nQContactMaemo5Engine& QContactMaemo5Engine::operator=(const QContactMaemo5Engine& other)\n{\n d = other.d;\n return *this;\n}\n\n\/*! \\reimp *\/\nQString QContactMaemo5Engine::managerName() const\n{\n return QString(QLatin1String(\"maemo5\"));\n}\n\n\/* Synthesise the display label of a contact *\/\nQString QContactMaemo5Engine::synthesizedDisplayLabel(const QContact& contact, QContactManager::Error* error) const\n{\n Q_UNUSED(error)\n QString label = QContactManagerEngine::synthesizedDisplayLabel(contact, error);\n \n if (label.isEmpty()) {\n QContactNickname n = contact.detail(QContactNickname::DefinitionName);\n label = n.nickname();\n }\n \n if (label.isEmpty())\n label = \"No name\";\n \n return label;\n}\n\nbool QContactMaemo5Engine::validateContact(const QContact& contact, QContactManager::Error* error) const\n{\n return QContactManagerEngine::validateContact(contact, error);\n}\n\nbool QContactMaemo5Engine::validateDefinition(const QContactDetailDefinition& definition, QContactManager::Error* error) const\n{\n QContactDetailDefinition existing = detailDefinition(definition.name(), QContactType::TypeContact, error);\n if (existing == definition) {\n *error = QContactManager::NoError;\n return true;\n }\n\n *error = QContactManager::NotSupportedError; \/\/ XXX TODO: mutable definitions?\n return false;\n}\n\nQContactLocalId QContactMaemo5Engine::selfContactId(QContactManager::Error* error) const\n{\n Q_CHECK_PTR(d->m_abook);\n\n return d->m_abook->selfContactId(error);\n}\n\nQList<QContactLocalId> QContactMaemo5Engine::contactIds(const QContactFilter& filter, const QList<QContactSortOrder>& sortOrders, QContactManager::Error* error) const\n{\n Q_CHECK_PTR(d->m_abook);\n \n \/\/return QContactManagerEngine::contactIds(filter, sortOrders, error);\n return d->m_abook->contactIds(filter, sortOrders, error);\n}\n\nQList<QContact> QContactMaemo5Engine::contacts(const QContactFilter & filter, const QList<QContactSortOrder> & sortOrders, const QContactFetchHint & fetchHint,\n\t\t\t QContactManager::Error* error ) const\n{\n Q_UNUSED(fetchHint); \/\/ no optimisations currently, ignore the fetchhint.\n Q_CHECK_PTR(d->m_abook);\n QList<QContact> rtn;\n \n QList<QContactLocalId> ids = contactIds(filter, sortOrders,error);\n foreach (QContactLocalId id, ids)\n rtn << contact(id, QContactFetchHint(), error);\n return rtn;\n}\n\nQContact QContactMaemo5Engine::contact(const QContactLocalId& contactId, const QContactFetchHint& fetchHint, QContactManager::Error* error) const\n{\n Q_UNUSED(fetchHint); \/\/TODO\n Q_CHECK_PTR(d->m_abook);\n \n QContact *contact = d->m_abook->getQContact(contactId, error);\n QContact rtn(*contact);\n delete contact;\n setContactDisplayLabel(&rtn, synthesizedDisplayLabel(rtn, error));\n return rtn;\n}\n\nbool QContactMaemo5Engine::saveContacts(QList<QContact>* contacts, QMap<int, QContactManager::Error>* errorMap, QContactManager::Error* error)\n{\n *error = QContactManager::NoError;\n QContactManager::Error tempError = QContactManager::NoError;\n QContact curr;\n for (int i = 0; i < contacts->size(); i++) {\n curr = contacts->at(i);\n if (!saveContact(&curr, &tempError)) {\n errorMap->insert(i, tempError);\n *error = tempError;\n } else {\n contacts->replace(i, curr);\n }\n }\n\n return (*error == QContactManager::NoError);\n}\n\nbool QContactMaemo5Engine::removeContacts(const QList<QContactLocalId>& ids, QMap<int, QContactManager::Error>* errorMap, QContactManager::Error* error)\n{\n *error = QContactManager::NoError;\n QContactManager::Error tempError = QContactManager::NoError;\n QContact curr;\n for (int i = 0; i < ids.size(); i++) {\n if (!removeContact(ids.at(i), &tempError)) {\n errorMap->insert(i, tempError);\n *error = tempError;\n }\n }\n\n return (*error == QContactManager::NoError);\n}\n\nbool QContactMaemo5Engine::saveContact(QContact* contact, QContactManager::Error* error)\n{\n Q_CHECK_PTR(d->m_abook);\n \n if (!contact) {\n *error = QContactManager::BadArgumentError;\n return false;\n }\n\n \/\/ synthesize the display label for the contact\n setContactDisplayLabel(contact, synthesizedDisplayLabel(*contact, error));\n\n \/\/ ensure that the contact's details conform to their definitions\n if (!validateContact(*contact, error)) {\n QCM5_DEBUG << \"Validate Contact failed\";\n return false;\n }\n\n bool retn = d->m_abook->saveContact(contact, error);\n QContactId cId = contact->id();\n cId.setManagerUri(managerUri());\n contact->setId(cId);\n return retn;\n}\n\nbool QContactMaemo5Engine::removeContact(const QContactLocalId& contactId, QContactManager::Error* error)\n{\n Q_CHECK_PTR(d->m_abook);\n return d->m_abook->removeContact(contactId, error);\n}\n\nQMap<QString, QContactDetailDefinition> QContactMaemo5Engine::detailDefinitions(const QString& contactType, QContactManager::Error* error) const\n{\n\n QMap<QString, QMap<QString, QContactDetailDefinition> > defns = QContactManagerEngine::schemaDefinitions();\n \n QMap<QString, QContactDetailFieldDefinition> fields;\n \n QContactDetailFieldDefinition gsfd; \/\/Generic string field definition\n gsfd.setDataType(QVariant::String);\n \n \/\/ QContactAddress\n fields = defns[contactType][QContactAddress::DefinitionName].fields();\n \/\/fields.remove(QContactAddress::FieldSubTypes);\n fields.insert(\"Estension\", gsfd);\n fields.insert(QContactDetail::FieldDetailUri, gsfd);\n defns[contactType][QContactAddress::DefinitionName].setFields(fields);\n \n \/\/ QContactAnniversary\n defns[contactType].remove(QContactAnniversary::DefinitionName);\n \n \/\/ QContactAvatar\n \/\/ TODO setUnique(true);\n \/\/ QContactBirthday\n \/\/ QContactDisplayLabel\n \n \/\/ QContactEmailAddress\n fields = defns[contactType][QContactEmailAddress::DefinitionName].fields();\n fields.insert(QContactDetail::FieldDetailUri, gsfd);\n defns[contactType][QContactEmailAddress::DefinitionName].setFields(fields);\n \n \/\/ QContactFamily\n \/\/ QContactGender\n \/\/ QContactGeoLocation\n defns[contactType].remove(QContactGeoLocation::DefinitionName);\n \n \/\/ QContactGuid\n \/\/ QContactName\n fields = defns[contactType][QContactName::DefinitionName].fields();\n fields.remove(QContactName::FieldCustomLabel);\n fields.remove(QContactName::FieldPrefix);\n fields.remove(QContactName::FieldSuffix);\n defns[contactType][QContactName::DefinitionName].setFields(fields);\n \n \/\/ QContactNickname\n \/\/ QContactNote\n \/\/ QContactOnlineAccount\n fields = defns[contactType][QContactOnlineAccount::DefinitionName].fields();\n fields.remove(QContactOnlineAccount::FieldAccountUri);\n fields.remove(QContactOnlineAccount::FieldSubTypes);\n fields.insert(\"AccountPath\", gsfd);\n defns[contactType][QContactOnlineAccount::DefinitionName].setFields(fields);\n \n \/\/ QContactOrganization\n fields = defns[contactType][QContactOrganization::DefinitionName].fields();\n fields.remove(QContactOrganization::FieldAssistantName);\n fields.remove(QContactOrganization::FieldDepartment);\n fields.remove(QContactOrganization::FieldLocation);\n fields.remove(QContactOrganization::FieldLogoUrl);\n fields.remove(QContactOrganization::FieldName);\n fields.remove(QContactOrganization::FieldRole);\n defns[contactType][QContactOrganization::DefinitionName].setFields(fields);\n \n \/\/ QContactPhoneNumber\n fields = defns[contactType][QContactPhoneNumber::DefinitionName].fields();\n fields.insert(QContactDetail::FieldDetailUri, gsfd);\n defns[contactType][QContactPhoneNumber::DefinitionName].setFields(fields);\n \n \/\/ QContactSyncTarget\n defns[contactType].remove(QContactSyncTarget::DefinitionName);\n \n \/\/ QContactTimestamp\n \/\/ QContactType\n \/\/ QContactUrl\n fields = defns[contactType][QContactUrl::DefinitionName].fields();\n fields.remove(QContactUrl::FieldSubType);\n defns[contactType][QContactUrl::DefinitionName].setFields(fields);\n \n \/\/Still unmanaged: GlobalPresence, Presence, Ringtone, Tag\n \n QCM5_DEBUG << \"Contact type\" << contactType << \"Keys\" << defns.keys();\n \n *error = QContactManager::NoError;\n return defns[contactType];\n}\n\nQContactDetailDefinition QContactMaemo5Engine::detailDefinition(const QString& definitionName, const QString& contactType, QContactManager::Error* error) const\n{\n return QContactManagerEngine::detailDefinition(definitionName, contactType, error);\n}\n\nbool QContactMaemo5Engine::hasFeature(QContactManager::ManagerFeature feature, const QString& contactType) const {\n Q_UNUSED(contactType);\n if (feature == QContactManager::Anonymous)\n return true;\n \n return false;\n}\n\nbool QContactMaemo5Engine::isFilterSupported(const QContactFilter& filter) const {\n switch (filter.type()) {\n case QContactFilter::InvalidFilter:\n case QContactFilter::DefaultFilter:\n case QContactFilter::LocalIdFilter:\n case QContactFilter::ContactDetailFilter:\n case QContactFilter::ActionFilter:\n case QContactFilter::IntersectionFilter:\n case QContactFilter::UnionFilter:\n return true;\n default:\n return false;\n }\n}\n\nQList<QVariant::Type> QContactMaemo5Engine::supportedDataTypes() const {\n QList<QVariant::Type> st;\n st.append(QVariant::String);\n st.append(QVariant::Int);\n st.append(QVariant::UInt);\n st.append(QVariant::Double);\n st.append(QVariant::Date);\n st.append(QVariant::DateTime);\n\n return st; \n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * This file is part of accounts-ui\n *\n * Copyright (C) 2009-2010 Nokia Corporation.\n *\n * Contact: Alberto Mardegan <alberto.mardegan@nokia.com>\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public License\n * version 2.1 as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA\n * 02110-1301 USA\n *\/\n\n\/\/libAccounts\n#include <Accounts\/Provider>\n#include <Accounts\/Account>\n#include <Accounts\/ServiceType>\n#include <Accounts\/Manager>\n\n\/\/Meegotouch\n#include <MLayout>\n#include <MLinearLayoutPolicy>\n#include <MContentItem>\n#include <MLocale>\n#include <MAction>\n#include <MLabel>\n#include <MGridLayoutPolicy>\n#include <MSeparator>\n#include <MImageWidget>\n#include <MButton>\n\n\/\/Qt\n#include <QDebug>\n\n\/\/Accounts-Ui\n#include \"account-setup-finished-page-priv.h\"\n#include \"accountsmanagersingleton.h\"\n#include \"last-page-actions.h\"\n#include \"provider-plugin-process.h\"\n#include \"account-setup-finished-widget.h\"\n\nnamespace AccountsUI {\n\nvoid AccountSetupFinishedPagePrivate::actionButtonClicked()\n{\n QString serviceName = sender()->property(\"serviceName\").toString();\n qDebug() << \"Invoking service\" << serviceName;\n LastPageActions::executeService(serviceName);\n ProviderPluginProcess::instance()->quit();\n}\n\nAccountSetupFinishedPage::AccountSetupFinishedPage(AbstractAccountSetupContext *context)\n : MApplicationPage(),\n d_ptr(new AccountSetupFinishedPagePrivate())\n{\n Q_D(AccountSetupFinishedPage);\n d->q_ptr = this;\n d->account = context->account();\n d->serviceType = context->serviceType();\n setObjectName(\"wgAccountSetupFinishedPage\");\n setStyleName(\"AccountsUiPage\");\n}\n\nAccountSetupFinishedPage::~AccountSetupFinishedPage()\n{\n delete d_ptr;\n}\n\nvoid AccountSetupFinishedPage::createContent()\n{\n Q_D(AccountSetupFinishedPage);\n\n setComponentsDisplayMode(EscapeButton, MApplicationPageModel::Hide);\n\n MWidget *centralWidget = new MWidget();\n MLayout *layout = new MLayout(centralWidget);\n MLinearLayoutPolicy *layoutPolicy = new MLinearLayoutPolicy(layout, Qt::Vertical);\n layoutPolicy->setSpacing(0);\n\n QString providerName(d->account->providerName());\n \/\/ xml file that describes the ui elements for the provider\n Accounts::Provider *provider = AccountsManager::instance()->provider(providerName);\n if (provider) {\n QDomElement root = provider->domDocument().documentElement();\n QDomElement providerIcon = root.firstChildElement(\"icon\");\n QString providerIconId = providerIcon.text();\n\n MContentItem *providerItem = new MContentItem(MContentItem::IconAndSingleTextLabel, this);\n providerItem->setStyleName(\"SetupFinishedProviderName\");\n providerItem->setImageID(providerIconId);\n providerItem->setTitle(provider->displayName());\n layoutPolicy->addItem(providerItem);\n }\n\n MSeparator *separatorTop = new MSeparator(this);\n separatorTop->setOrientation(Qt::Horizontal);\n separatorTop->setStyleName(\"CommonItemDividerInverted\");\n\n layoutPolicy->addItem(separatorTop);\n\n AccountSetupFinishedWidget *widget = new AccountSetupFinishedWidget(providerName, this);\n layoutPolicy->addItem(widget);\n\n \/\/% \"Add more account\"\n MButton *addMoreAccountButton = new MButton(qtTrId(\"qtn_acc_add_more_accounts\"));\n connect (addMoreAccountButton, SIGNAL(clicked()), ProviderPluginProcess::instance(), SLOT(quit()));\n MLayout *buttonsLayout = new MLayout();\n MLinearLayoutPolicy *portraitPolicy = new MLinearLayoutPolicy(buttonsLayout, Qt::Vertical);\n MLinearLayoutPolicy *landscapePolicy = new MLinearLayoutPolicy(buttonsLayout, Qt::Horizontal);\n\n portraitPolicy->addStretch();\n portraitPolicy->setSpacing(20);\n landscapePolicy->addStretch();\n landscapePolicy->setSpacing(20);\n\n const LastPageActions &lastPageActions =\n ProviderPluginProcess::instance()->lastPageActions();\n const LastPageActions::ServiceActionList actions =\n lastPageActions.serviceActions();\n foreach (LastPageActions::ServiceAction action, actions) {\n MButton *button = new MButton(qtTrId(\"qtn_comm_go_to_x\").\n arg(action.title()));\n button->setProperty(\"serviceName\", action.serviceName());\n connect(button, SIGNAL(clicked()), d, SLOT(actionButtonClicked()));\n\n landscapePolicy->addItem(button, Qt::AlignRight);\n portraitPolicy->addItem(button, Qt::AlignCenter);\n }\n\n portraitPolicy->addItem(addMoreAccountButton, Qt::AlignCenter);\n landscapePolicy->addItem(addMoreAccountButton, Qt::AlignCenter);\n\n portraitPolicy->addStretch();\n landscapePolicy->addStretch();\n\n buttonsLayout->setLandscapePolicy(landscapePolicy);\n buttonsLayout->setPortraitPolicy(portraitPolicy);\n layoutPolicy->addStretch();\n layoutPolicy->addItem(buttonsLayout);\n\n setCentralWidget(centralWidget);\n\n}\n\nvoid AccountSetupFinishedPage::goToApplication()\n{\n \/* this slot is deprecated *\/\n}\n\n}\n<commit_msg>Fixing: 229894 - Logical string qtn_mail_other_mailbox displayed in Account Setup Complete view<commit_after>\/*\n * This file is part of accounts-ui\n *\n * Copyright (C) 2009-2010 Nokia Corporation.\n *\n * Contact: Alberto Mardegan <alberto.mardegan@nokia.com>\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public License\n * version 2.1 as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA\n * 02110-1301 USA\n *\/\n\n\/\/libAccounts\n#include <Accounts\/Provider>\n#include <Accounts\/Account>\n#include <Accounts\/ServiceType>\n#include <Accounts\/Manager>\n\n\/\/Meegotouch\n#include <MLayout>\n#include <MLinearLayoutPolicy>\n#include <MContentItem>\n#include <MLocale>\n#include <MAction>\n#include <MLabel>\n#include <MGridLayoutPolicy>\n#include <MSeparator>\n#include <MImageWidget>\n#include <MButton>\n\n\/\/Qt\n#include <QDebug>\n\n\/\/Accounts-Ui\n#include \"account-setup-finished-page-priv.h\"\n#include \"accountsmanagersingleton.h\"\n#include \"last-page-actions.h\"\n#include \"provider-plugin-process.h\"\n#include \"account-setup-finished-widget.h\"\n\nnamespace AccountsUI {\n\nvoid AccountSetupFinishedPagePrivate::actionButtonClicked()\n{\n QString serviceName = sender()->property(\"serviceName\").toString();\n qDebug() << \"Invoking service\" << serviceName;\n LastPageActions::executeService(serviceName);\n ProviderPluginProcess::instance()->quit();\n}\n\nAccountSetupFinishedPage::AccountSetupFinishedPage(AbstractAccountSetupContext *context)\n : MApplicationPage(),\n d_ptr(new AccountSetupFinishedPagePrivate())\n{\n Q_D(AccountSetupFinishedPage);\n d->q_ptr = this;\n d->account = context->account();\n d->serviceType = context->serviceType();\n setObjectName(\"wgAccountSetupFinishedPage\");\n setStyleName(\"AccountsUiPage\");\n}\n\nAccountSetupFinishedPage::~AccountSetupFinishedPage()\n{\n delete d_ptr;\n}\n\nvoid AccountSetupFinishedPage::createContent()\n{\n Q_D(AccountSetupFinishedPage);\n\n setComponentsDisplayMode(EscapeButton, MApplicationPageModel::Hide);\n\n MWidget *centralWidget = new MWidget();\n MLayout *layout = new MLayout(centralWidget);\n MLinearLayoutPolicy *layoutPolicy = new MLinearLayoutPolicy(layout, Qt::Vertical);\n layoutPolicy->setSpacing(0);\n\n QString providerName(d->account->providerName());\n \/\/ xml file that describes the ui elements for the provider\n Accounts::Provider *provider = AccountsManager::instance()->provider(providerName);\n if (provider) {\n QDomElement root = provider->domDocument().documentElement();\n QDomElement providerIcon = root.firstChildElement(\"icon\");\n QString catalog = provider->trCatalog();\n MLocale locale;\n if (!catalog.isEmpty() && !locale.isInstalledTrCatalog(catalog)) {\n locale.installTrCatalog(catalog);\n MLocale::setDefault(locale);\n }\n QString providerIconId = providerIcon.text();\n\n MContentItem *providerItem = new MContentItem(MContentItem::IconAndSingleTextLabel, this);\n providerItem->setStyleName(\"SetupFinishedProviderName\");\n providerItem->setImageID(providerIconId);\n providerItem->setTitle(qtTrId(provider->displayName().toLatin1()));\n\n layoutPolicy->addItem(providerItem);\n }\n\n MSeparator *separatorTop = new MSeparator(this);\n separatorTop->setOrientation(Qt::Horizontal);\n separatorTop->setStyleName(\"CommonItemDividerInverted\");\n\n layoutPolicy->addItem(separatorTop);\n\n AccountSetupFinishedWidget *widget = new AccountSetupFinishedWidget(providerName, this);\n layoutPolicy->addItem(widget);\n\n \/\/% \"Add more account\"\n MButton *addMoreAccountButton = new MButton(qtTrId(\"qtn_acc_add_more_accounts\"));\n connect (addMoreAccountButton, SIGNAL(clicked()), ProviderPluginProcess::instance(), SLOT(quit()));\n MLayout *buttonsLayout = new MLayout();\n MLinearLayoutPolicy *portraitPolicy = new MLinearLayoutPolicy(buttonsLayout, Qt::Vertical);\n MLinearLayoutPolicy *landscapePolicy = new MLinearLayoutPolicy(buttonsLayout, Qt::Horizontal);\n\n portraitPolicy->addStretch();\n portraitPolicy->setSpacing(20);\n landscapePolicy->addStretch();\n landscapePolicy->setSpacing(20);\n\n const LastPageActions &lastPageActions =\n ProviderPluginProcess::instance()->lastPageActions();\n const LastPageActions::ServiceActionList actions =\n lastPageActions.serviceActions();\n foreach (LastPageActions::ServiceAction action, actions) {\n MButton *button = new MButton(qtTrId(\"qtn_comm_go_to_x\").\n arg(action.title()));\n button->setProperty(\"serviceName\", action.serviceName());\n connect(button, SIGNAL(clicked()), d, SLOT(actionButtonClicked()));\n\n landscapePolicy->addItem(button, Qt::AlignRight);\n portraitPolicy->addItem(button, Qt::AlignCenter);\n }\n\n portraitPolicy->addItem(addMoreAccountButton, Qt::AlignCenter);\n landscapePolicy->addItem(addMoreAccountButton, Qt::AlignCenter);\n\n portraitPolicy->addStretch();\n landscapePolicy->addStretch();\n\n buttonsLayout->setLandscapePolicy(landscapePolicy);\n buttonsLayout->setPortraitPolicy(portraitPolicy);\n layoutPolicy->addStretch();\n layoutPolicy->addItem(buttonsLayout);\n\n setCentralWidget(centralWidget);\n\n}\n\nvoid AccountSetupFinishedPage::goToApplication()\n{\n \/* this slot is deprecated *\/\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ This file is a part of the IncludeOS unikernel - www.includeos.org\n\/\/\n\/\/ Copyright 2015 Oslo and Akershus University College of Applied Sciences\n\/\/ and Alfred Bratterud\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n\/**\n A very superficial test to verify that basic STL is working\n This is useful when we mess with \/ replace STL implementations\n\n**\/\n\n\n#include <os>\n#include <cassert>\n\n#define GSL_THROW_ON_CONTRACT_VIOLATION\n#include <gsl.h>\n#include <lest.hpp>\n\n\nint clock_gettime(clockid_t clk_id, struct timespec *tp){\n(void*)clk_id;\n(void*)tp;\nreturn 0;\n};\n\n\n#define MYINFO(X,...) INFO(\"Test GSL\",X,##__VA_ARGS__)\n\nstatic int divcount_ = 0;\n\nconst lest::test test_basic_gsl[] = {\n {\n\n SCENARIO (\"Basic Expects \/ Ensures behave as expected\") {\n\n GIVEN (\"A simple division function, requiring positive integers\") {\n\n class Math {\n public:\n static int div (int x, int y) {\n Expects( y > 0 );\n\n int prevcount_ = divcount_;\n\n auto result = x \/ y;\n divcount_++;\n\n Ensures(result == x \/ y);\n Ensures(divcount_ > 0);\n Ensures(divcount_ == prevcount_ + 1);\n\n return result;\n\n }\n };\n\n WHEN (\"y is zero\") {\n int y = 0;\n\n THEN (\"Division by y throws\") {\n EXPECT_THROWS( Math::div(100, y) );\n }\n\n }\n\n WHEN (\"y is positive\") {\n int y = 4;\n\n THEN (\"Division by y doesn't throw\") {\n EXPECT_NO_THROW( Math::div(100, y) );\n }\n\n AND_THEN(\"Division gives the correct result\"){\n EXPECT( Math::div(100,y) == 100 \/ y );\n }\n }\n\n WHEN (\"y is negative\"){\n int y = -90;\n\n THEN (\"Divsion by y throws\") {}\n EXPECT_THROWS( Math::div(100, y) );\n\n AND_THEN(\"Division should have succeeded twice\"){\n EXPECT(divcount_ == 2);\n }\n }\n }\n }\n },\n\n {\n SCENARIO(\"We can use span to replace pointer-and-size interfaces\") {\n\n GIVEN (\"A (member) function with a span parameter\") {\n\n class Mem {\n public:\n static unsigned int count(gsl::span<char> chars){\n\n int i = 0;\n for ( auto c : chars ) {\n printf(\"%c \", c);\n i++;\n }\n\n printf(\"\\n\");\n return i;\n }\n\n\n };\n\n\n WHEN (\"We pass a raw pointer\") {\n char* name = (char*)\"Bjarne Stroustrup\";\n\n THEN(\"if we lie to the about our size, span can't save us from overflow \/ underflow\") {\n EXPECT( Mem::count({name, 100}) != std::string(name).size());\n EXPECT( Mem::count({name, 10}) != std::string(name).size());\n }\n\n AND_THEN(\"If callee keeps track of the size, it will still work\"){\n EXPECT( Mem::count({name, 17}) == std::string(name).size());\n }\n }\n\n WHEN (\"We use std::array\") {\n std::array<char,30> my_array {'G','S','L',' ','l','o', 'o', 'k', 's', ' ', 'n', 'i', 'c', 'e'};\n THEN(\"we're perfectly safe\"){\n EXPECT( Mem::count(my_array) == my_array.size() );\n }\n }\n\n WHEN (\"We use normal array\") {\n char str2 [] = {49, 50, 51, 52, 53};\n\n THEN (\"Span helps us avoid decay to pointer\") {\n EXPECT( Mem::count(str2) == sizeof(str2));\n }\n }\n }\n }\n }\n};\n\nvoid Service::start()\n{\n\n \/\/ Lest takes command line params\n char* argv[2] = {(char*)\"test\", (char*)\"-p\"};\n\n auto failed = lest::run(test_basic_gsl, 2, argv);\n\n assert(not failed);\n\n MYINFO(\"SUCCESS\");\n\n\n}\n<commit_msg>Updated GSL-test to verify bounds checking on span<commit_after>\/\/ This file is a part of the IncludeOS unikernel - www.includeos.org\n\/\/\n\/\/ Copyright 2015 Oslo and Akershus University College of Applied Sciences\n\/\/ and Alfred Bratterud\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n\/**\n A very superficial test to verify that basic STL is working\n This is useful when we mess with \/ replace STL implementations\n\n**\/\n\n\n#include <os>\n#include <cassert>\n\n#define GSL_THROW_ON_CONTRACT_VIOLATION\n#include <gsl.h>\n#include <lest.hpp>\n\n\nint clock_gettime(clockid_t clk_id, struct timespec *tp){\n(void*)clk_id;\n(void*)tp;\nreturn 0;\n};\n\n\n#define MYINFO(X,...) INFO(\"Test GSL\",X,##__VA_ARGS__)\n\nstatic int divcount_ = 0;\n\nconst lest::test test_basic_gsl[] = {\n {\n\n SCENARIO (\"Basic Expects \/ Ensures behave as expected\") {\n\n GIVEN (\"A simple division function, requiring positive integers\") {\n\n class Math {\n public:\n static int div (int x, int y) {\n Expects( y > 0 );\n\n int prevcount_ = divcount_;\n\n auto result = x \/ y;\n divcount_++;\n\n Ensures(result == x \/ y);\n Ensures(divcount_ > 0);\n Ensures(divcount_ == prevcount_ + 1);\n\n return result;\n\n }\n };\n\n WHEN (\"y is zero\") {\n int y = 0;\n\n THEN (\"Division by y throws\") {\n EXPECT_THROWS( Math::div(100, y) );\n }\n\n }\n\n WHEN (\"y is positive\") {\n int y = 4;\n\n THEN (\"Division by y doesn't throw\") {\n EXPECT_NO_THROW( Math::div(100, y) );\n }\n\n AND_THEN(\"Division gives the correct result\"){\n EXPECT( Math::div(100,y) == 100 \/ y );\n }\n }\n\n WHEN (\"y is negative\"){\n int y = -90;\n\n THEN (\"Divsion by y throws\") {}\n EXPECT_THROWS( Math::div(100, y) );\n\n AND_THEN(\"Division should have succeeded twice\"){\n EXPECT(divcount_ == 2);\n }\n }\n }\n }\n },\n\n {\n SCENARIO(\"We can use span to replace pointer-and-size interfaces\") {\n\n GIVEN (\"A (member) function with a span parameter\") {\n\n class Mem {\n public:\n static unsigned int count(gsl::span<char> chars){\n\n int i = 0;\n for ( auto c : chars ) {\n printf(\"%c \", c);\n i++;\n }\n\n printf(\"\\n\");\n return i;\n }\n\n\n };\n\n WHEN (\"We pass a raw pointer\") {\n char* name = (char*)\"Bjarne Stroustrup\";\n\n THEN(\"if we lie to the about our size, span can't save us from overflow \/ underflow\") {\n EXPECT( Mem::count({name, 100}) != std::string(name).size());\n EXPECT( Mem::count({name, 10}) != std::string(name).size());\n }\n\n AND_THEN(\"If caller keeps track of the size, it will still work\"){\n EXPECT( Mem::count({name, 17}) == std::string(name).size());\n }\n\n }\n\n WHEN (\"We use std::array\") {\n std::array<char,30> my_array {'G','S','L',' ','l','o', 'o', 'k', 's', ' ', 'n', 'i', 'c', 'e'};\n THEN(\"we're perfectly safe\"){\n EXPECT( Mem::count(my_array) == my_array.size() );\n }\n }\n\n WHEN (\"We use normal array\") {\n char str2 [] = {49, 50, 51, 52, 53};\n\n THEN (\"Span helps us avoid decay to pointer\") {\n EXPECT( Mem::count(str2) == sizeof(str2));\n }\n }\n }\n\n GIVEN (\"A (Bad) span-interface that doesn't do any bounds checking\") {\n\n class Bad {\n public:\n static unsigned char eighth(gsl::span<char> chars){\n return chars[8];\n }\n };\n\n WHEN (\"we pass in sufficient data\") {\n char* character = (char*) \"Bjarne \\\"Yoda\\\" Stroustrup leas the Jedi council with wisdom\";\n THEN(\"you can access the elements of the span using the index operator\"){\n EXPECT(Bad::eighth({character, 20}) == 'Y');\n }\n\n }\n\n WHEN (\"we pass in too little data\") {\n char* character = (char*) \"Yoda\";\n THEN(\"span saves us from complete embarrasment\") {\n EXPECT_THROWS(Bad::eighth({character, 4}));\n }\n\n }\n\n }\n\n\n }\n }\n};\n\nvoid Service::start()\n{\n\n \/\/ Lest takes command line params\n char* argv[2] = {(char*)\"test\", (char*)\"-p\"};\n\n auto failed = lest::run(test_basic_gsl, 2, argv);\n\n assert(not failed);\n\n MYINFO(\"SUCCESS\");\n\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ $Id$\n\/\/***************************************************************************\n\/\/ File:\n\/\/\tTraceValues.cpp\n\/\/ \n\/\/ Purpose:\n\/\/ Support for inserting LLVM code to print values at basic block\n\/\/ and method exits. Also exports functions to create a call\n\/\/ \"printf\" instruction with one of the signatures listed below.\n\/\/ \n\/\/ History:\n\/\/\t10\/11\/01\t - Vikram Adve - Created\n\/\/**************************************************************************\/\n\n\n#include \"llvm\/Transforms\/Instrumentation\/TraceValues.h\"\n#include \"llvm\/GlobalVariable.h\"\n#include \"llvm\/ConstPoolVals.h\"\n#include \"llvm\/Type.h\"\n#include \"llvm\/DerivedTypes.h\"\n#include \"llvm\/Instruction.h\"\n#include \"llvm\/iTerminators.h\"\n#include \"llvm\/iOther.h\"\n#include \"llvm\/BasicBlock.h\"\n#include \"llvm\/Method.h\"\n#include \"llvm\/Module.h\"\n#include \"llvm\/SymbolTable.h\"\n#include \"llvm\/Support\/HashExtras.h\"\n#include <hash_map>\n#include <strstream.h>\n\n\n\/\/*********************** Internal Data Structures *************************\/\n\nconst char* const PRINTF = \"printf\";\n\n#undef DONT_EMBED_STRINGS_IN_FMT\n\n\n\/\/************************** Internal Functions ****************************\/\n\n#undef USE_PTRREF\n#ifdef USE_PTRREF\nstatic inline ConstPoolPointerRef*\nGetStringRef(Module* module, const char* str)\n{\n static hash_map<string, ConstPoolPointerRef*> stringRefCache;\n static Module* lastModule = NULL;\n \n if (lastModule != module)\n { \/\/ Let's make sure we create separate global references in each module\n stringRefCache.clear();\n lastModule = module;\n }\n \n ConstPoolPointerRef* result = stringRefCache[str];\n if (result == NULL)\n {\n ConstPoolArray* charArray = ConstPoolArray::get(str);\n GlobalVariable* stringVar =\n new GlobalVariable(charArray->getType(),\/*isConst*\/true,charArray,str);\n module->getGlobalList().push_back(stringVar);\n result = ConstPoolPointerRef::get(stringVar);\n assert(result && \"Failed to create reference to string constant\");\n stringRefCache[str] = result;\n }\n \n return result;\n}\n#endif USE_PTRREF\n\nstatic inline GlobalVariable*\nGetStringRef(Module* module, const char* str)\n{\n static hash_map<string, GlobalVariable*> stringRefCache;\n static Module* lastModule = NULL;\n \n if (lastModule != module)\n { \/\/ Let's make sure we create separate global references in each module\n stringRefCache.clear();\n lastModule = module;\n }\n \n GlobalVariable* result = stringRefCache[str];\n if (result == NULL)\n {\n ConstPoolArray* charArray = ConstPoolArray::get(str);\n GlobalVariable* stringVar =\n new GlobalVariable(charArray->getType(),\/*isConst*\/true,charArray);\n module->getGlobalList().push_back(stringVar);\n result = stringVar;\n \/\/ result = ConstPoolPointerRef::get(stringVar);\n assert(result && \"Failed to create reference to string constant\");\n stringRefCache[str] = result;\n }\n \n return result;\n}\n\n\nstatic inline bool\nTraceThisOpCode(unsigned opCode)\n{\n \/\/ Explicitly test for opCodes *not* to trace so that any new opcodes will\n \/\/ be traced by default (or will fail in a later assertion on VoidTy)\n \/\/ \n return (opCode < Instruction::FirstOtherOp &&\n opCode != Instruction::Ret &&\n opCode != Instruction::Br &&\n opCode != Instruction::Switch &&\n opCode != Instruction::Free &&\n opCode != Instruction::Alloca &&\n opCode != Instruction::Store &&\n opCode != Instruction::PHINode &&\n opCode != Instruction::Cast);\n}\n\n\nstatic void\nFindValuesToTraceInBB(BasicBlock* bb,\n vector<Value*>& valuesToTraceInBB)\n{\n for (BasicBlock::iterator II = bb->begin(); II != bb->end(); ++II)\n if ((*II)->getType()->isPrimitiveType() &&\n TraceThisOpCode((*II)->getOpcode()))\n {\n valuesToTraceInBB.push_back(*II);\n }\n}\n\n\n\/\/ \n\/\/ Insert print instructions at the end of the basic block *bb\n\/\/ for each value in valueVec[]. *bb must postdominate the block\n\/\/ in which the value is computed; this is not checked here.\n\/\/ \nstatic void\nTraceValuesAtBBExit(const vector<Value*>& valueVec,\n BasicBlock* bb,\n Module* module,\n unsigned int indent,\n bool isMethodExit)\n{\n \/\/ Get an iterator to point to the insertion location\n \/\/ \n BasicBlock::InstListType& instList = bb->getInstList();\n TerminatorInst* termInst = bb->getTerminator(); \n BasicBlock::InstListType::iterator here = instList.end();\n while ((*here) != termInst && here != instList.begin())\n --here;\n assert((*here) == termInst);\n \n \/\/ Insert a print instruction for each value.\n \/\/ \n for (unsigned i=0, N=valueVec.size(); i < N; i++)\n {\n Instruction* traceInstr =\n CreatePrintInstr(valueVec[i], bb, module, indent, isMethodExit);\n here = instList.insert(here, traceInstr);\n }\n}\n\nstatic void\nInsertCodeToShowMethodEntry(BasicBlock* entryBB)\n{\n}\n\nstatic void\nInsertCodeToShowMethodExit(BasicBlock* exitBB)\n{\n}\n\n\n\/\/************************** External Functions ****************************\/\n\n\/\/ \n\/\/ The signatures of the print methods supported are:\n\/\/ int printf(ubyte*, ubyte*, ubyte*, ubyte*, int intValue)\n\/\/ int printf(ubyte*, ubyte*, ubyte*, ubyte*, unsigned uintValue)\n\/\/ int printf(ubyte*, ubyte*, ubyte*, ubyte*, float floatValue)\n\/\/ int printf(ubyte*, ubyte*, ubyte*, ubyte*, double doubleValue)\n\/\/ int printf(ubyte*, ubyte*, ubyte*, ubyte*, char* stringValue)\n\/\/ int printf(ubyte*, ubyte*, ubyte*, ubyte*, void* ptrValue)\n\/\/ \n\/\/ The invocation should be:\n\/\/ call \"printf\"(fmt, bbName, valueName, valueTypeName, value).\n\/\/ \nMethod*\nGetPrintMethodForType(Module* module, const Type* valueType)\n{\n#ifdef DONT_EMBED_STRINGS_IN_FMT\n static const int LASTARGINDEX = 4;\n#else\n static const int LASTARGINDEX = 1;\n#endif\n static PointerType* ubytePtrTy = NULL;\n static vector<const Type*> argTypesVec(LASTARGINDEX + 1);\n \n if (ubytePtrTy == NULL)\n { \/\/ create these once since they are invariant\n ubytePtrTy = PointerType::get(ArrayType::get(Type::UByteTy));\n argTypesVec[0] = ubytePtrTy;\n#ifdef DONT_EMBED_STRINGS_IN_FMT\n argTypesVec[1] = ubytePtrTy;\n argTypesVec[2] = ubytePtrTy;\n argTypesVec[3] = ubytePtrTy;\n#endif DONT_EMBED_STRINGS_IN_FMT\n }\n \n SymbolTable* symtab = module->getSymbolTable();\n argTypesVec[LASTARGINDEX] = valueType;\n MethodType* printMethodTy = MethodType::get(Type::IntTy, argTypesVec,\n \/*isVarArg*\/ false);\n \n Method* printMethod =\n cast<Method>(symtab->lookup(PointerType::get(printMethodTy), PRINTF));\n if (printMethod == NULL)\n { \/\/ Create a new method and add it to the module\n printMethod = new Method(printMethodTy, PRINTF);\n module->getMethodList().push_back(printMethod);\n \n \/\/ Create the argument list for the method so that the full signature\n \/\/ can be declared. The args can be anonymous.\n Method::ArgumentListType &argList = printMethod->getArgumentList();\n for (unsigned i=0; i < argTypesVec.size(); ++i)\n argList.push_back(new MethodArgument(argTypesVec[i]));\n }\n \n return printMethod;\n}\n\n\nInstruction*\nCreatePrintInstr(Value* val,\n const BasicBlock* bb,\n Module* module,\n unsigned int indent,\n bool isMethodExit)\n{\n strstream fmtString, scopeNameString, valNameString;\n vector<Value*> paramList;\n const Type* valueType = val->getType();\n Method* printMethod = GetPrintMethodForType(module, valueType);\n \n if (! valueType->isPrimitiveType() ||\n valueType->getPrimitiveID() == Type::VoidTyID ||\n valueType->getPrimitiveID() == Type::TypeTyID ||\n valueType->getPrimitiveID() == Type::LabelTyID)\n {\n assert(0 && \"Unsupported type for printing\");\n return NULL;\n }\n \n const Value* scopeToUse = (isMethodExit)? (const Value*) bb->getParent()\n : (const Value*) bb;\n if (scopeToUse->hasName())\n scopeNameString << scopeToUse->getName() << ends;\n else\n scopeNameString << scopeToUse << ends;\n \n if (val->hasName())\n valNameString << val->getName() << ends;\n else\n valNameString << val << ends;\n \n for (unsigned i=0; i < indent; i++)\n fmtString << \" \";\n \n#undef DONT_EMBED_STRINGS_IN_FMT\n#ifdef DONT_EMBED_STRINGS_IN_FMT\n fmtString << \" At exit of \"\n << ((isMethodExit)? \"Method \" : \"BB \")\n << \"%s : val %s = %s \";\n \n GlobalVariable* scopeNameVal = GetStringRef(module, scopeNameString.str());\n GlobalVariable* valNameVal = GetStringRef(module,valNameString.str());\n GlobalVariable* typeNameVal = GetStringRef(module,\n val->getType()->getDescription().c_str());\n#else\n fmtString << \" At exit of \"\n << ((isMethodExit)? \"Method \" : \"BB \")\n << scopeNameString.str() << \" : \"\n << valNameString.str() << \" = \"\n << val->getType()->getDescription().c_str();\n#endif DONT_EMBED_STRINGS_IN_FMT\n \n switch(valueType->getPrimitiveID())\n {\n case Type::BoolTyID:\n case Type::UByteTyID: case Type::UShortTyID:\n case Type::UIntTyID: case Type::ULongTyID:\n case Type::SByteTyID: case Type::ShortTyID:\n case Type::IntTyID: case Type::LongTyID:\n fmtString << \" %d\\0A\";\n break;\n \n case Type::FloatTyID: case Type::DoubleTyID:\n fmtString << \" %g\\0A\";\n break;\n \n case Type::PointerTyID:\n fmtString << \" %p\\0A\";\n break;\n \n default:\n assert(0 && \"Should not get here. Check the IF expression above\");\n return NULL;\n }\n \n fmtString << ends;\n GlobalVariable* fmtVal = GetStringRef(module, fmtString.str());\n \n#ifdef DONT_EMBED_STRINGS_IN_FMT\n paramList.push_back(fmtVal);\n paramList.push_back(scopeNameVal);\n paramList.push_back(valNameVal);\n paramList.push_back(typeNameVal);\n paramList.push_back(val);\n#else\n paramList.push_back(fmtVal);\n paramList.push_back(val);\n#endif DONT_EMBED_STRINGS_IN_FMT\n \n free(fmtString.str());\n free(scopeNameString.str());\n free(valNameString.str());\n \n return new CallInst(printMethod, paramList);\n}\n\n\nvoid\nInsertCodeToTraceValues(Method* method,\n bool traceBasicBlockExits,\n bool traceMethodExits)\n{\n vector<Value*> valuesToTraceInMethod;\n Module* module = method->getParent();\n BasicBlock* exitBB = NULL;\n \n if (method->isExternal() ||\n (! traceBasicBlockExits && ! traceMethodExits))\n return;\n \n if (traceMethodExits)\n {\n InsertCodeToShowMethodEntry(method->getEntryNode());\n#ifdef TODO_LATER\n exitBB = method->getExitNode();\n#endif\n }\n \n for (Method::iterator BI = method->begin(); BI != method->end(); ++BI)\n {\n BasicBlock* bb = *BI;\n vector<Value*> valuesToTraceInBB;\n FindValuesToTraceInBB(bb, valuesToTraceInBB);\n \n if (traceBasicBlockExits && bb != exitBB)\n TraceValuesAtBBExit(valuesToTraceInBB, bb, module,\n \/*indent*\/ 4, \/*isMethodExit*\/ false);\n \n if (traceMethodExits)\n valuesToTraceInMethod.insert(valuesToTraceInMethod.end(),\n valuesToTraceInBB.begin(),\n valuesToTraceInBB.end());\n }\n \n if (traceMethodExits)\n {\n TraceValuesAtBBExit(valuesToTraceInMethod, exitBB, module,\n \/*indent*\/ 0, \/*isMethodExit*\/ true);\n InsertCodeToShowMethodExit(exitBB);\n }\n}\n<commit_msg>Massive hacks to try to fix subtle logic bugs. I think it's all working now, at least what used to. I should disable method exit code completely because it's broken (doesn't insert just post dominating values)<commit_after>\/\/ $Id$\n\/\/***************************************************************************\n\/\/ File:\n\/\/\tTraceValues.cpp\n\/\/ \n\/\/ Purpose:\n\/\/ Support for inserting LLVM code to print values at basic block\n\/\/ and method exits. Also exports functions to create a call\n\/\/ \"printf\" instruction with one of the signatures listed below.\n\/\/ \n\/\/ History:\n\/\/\t10\/11\/01\t - Vikram Adve - Created\n\/\/**************************************************************************\/\n\n\n#include \"llvm\/Transforms\/Instrumentation\/TraceValues.h\"\n#include \"llvm\/GlobalVariable.h\"\n#include \"llvm\/ConstPoolVals.h\"\n#include \"llvm\/Type.h\"\n#include \"llvm\/DerivedTypes.h\"\n#include \"llvm\/Instruction.h\"\n#include \"llvm\/iTerminators.h\"\n#include \"llvm\/iOther.h\"\n#include \"llvm\/BasicBlock.h\"\n#include \"llvm\/Method.h\"\n#include \"llvm\/Module.h\"\n#include \"llvm\/SymbolTable.h\"\n#include <strstream>\n#include \"llvm\/Assembly\/Writer.h\"\n\n\nconst char* const PRINTF = \"printVal\";\n\nstatic inline GlobalVariable *\nGetStringRef(Module *M, const string &str)\n{\n ConstPoolArray *Init = ConstPoolArray::get(str);\n GlobalVariable *V = new GlobalVariable(Init->getType(), \/*Const*\/true, Init);\n M->getGlobalList().push_back(V);\n\n return V;\n}\n\nstatic inline bool\nTraceThisOpCode(unsigned opCode)\n{\n \/\/ Explicitly test for opCodes *not* to trace so that any new opcodes will\n \/\/ be traced by default (VoidTy's are already excluded)\n \/\/ \n return (opCode < Instruction::FirstOtherOp &&\n opCode != Instruction::Alloca &&\n opCode != Instruction::PHINode &&\n opCode != Instruction::Cast);\n}\n\n\nstatic void \nFindValuesToTraceInBB(BasicBlock* bb, vector<Value*>& valuesToTraceInBB)\n{\n for (BasicBlock::iterator II = bb->begin(); II != bb->end(); ++II)\n if ((*II)->getType()->isPrimitiveType() && \n (*II)->getType() != Type::VoidTy &&\n TraceThisOpCode((*II)->getOpcode()))\n {\n valuesToTraceInBB.push_back(*II);\n }\n}\n\n\/\/ The invocation should be:\n\/\/ call \"printf\"(fmt, value).\n\/\/ \nstatic Value *GetPrintMethodForType(Module *Mod, const Type *valueType) {\n vector<const Type*> ArgTys;\n ArgTys.reserve(2);\n ArgTys.push_back(PointerType::get(ArrayType::get(Type::UByteTy)));\n ArgTys.push_back(valueType);\n \n MethodType *printMethodTy = MethodType::get(Type::VoidTy, ArgTys,\n \/*isVarArg*\/ false);\n \n SymbolTable *ST = Mod->getSymbolTableSure();\n if (Value *V = ST->lookup(PointerType::get(printMethodTy), PRINTF))\n return V;\n\n \/\/ Create a new method and add it to the module\n Method *M = new Method(printMethodTy, PRINTF);\n Mod->getMethodList().push_back(M);\n return M;\n}\n\n\nstatic Instruction*\nCreatePrintInstr(Value* val,\n const BasicBlock* bb,\n Module* module,\n unsigned int indent,\n bool isMethodExit)\n{\n strstream scopeNameString;\n const Type* valueType = val->getType();\n \n assert(valueType->isPrimitiveType() &&\n valueType->getPrimitiveID() != Type::VoidTyID &&\n valueType->getPrimitiveID() != Type::TypeTyID &&\n valueType->getPrimitiveID() != Type::LabelTyID && \n \"Unsupported type for printing\");\n \n const Value* scopeToUse = (isMethodExit)? (const Value*) bb->getParent()\n : (const Value*) bb;\n WriteAsOperand(scopeNameString, scopeToUse) << \" : \";\n WriteAsOperand(scopeNameString, val) << \" = \"\n << val->getType()->getDescription()\n << ends;\n string fmtString(indent, ' ');\n \n fmtString += \" At exit of \" + string(isMethodExit ? \"Method \" : \"BB \") +\n scopeNameString.str();\n \n switch(valueType->getPrimitiveID()) {\n case Type::BoolTyID:\n case Type::UByteTyID: case Type::UShortTyID:\n case Type::UIntTyID: case Type::ULongTyID:\n case Type::SByteTyID: case Type::ShortTyID:\n case Type::IntTyID: case Type::LongTyID:\n fmtString += \" %d\\0A\";\n break;\n \n case Type::FloatTyID: case Type::DoubleTyID:\n fmtString += \" %g\\0A\";\n break;\n \n case Type::PointerTyID:\n fmtString += \" %p\\0A\";\n break;\n \n default:\n assert(0 && \"Should not get here. Check the IF expression above\");\n return NULL;\n }\n \n GlobalVariable *fmtVal = GetStringRef(module, fmtString);\n \n vector<Value*> paramList;\n paramList.push_back(fmtVal);\n paramList.push_back(val);\n\n return new CallInst(GetPrintMethodForType(module, valueType), paramList);\n}\n\n\n\n\/\/ \n\/\/ Insert print instructions at the end of the basic block *bb\n\/\/ for each value in valueVec[]. *bb must postdominate the block\n\/\/ in which the value is computed; this is not checked here.\n\/\/ \nstatic void\nTraceValuesAtBBExit(const vector<Value*>& valueVec,\n BasicBlock* bb,\n Module* module,\n unsigned int indent,\n bool isMethodExit)\n{\n \/\/ Get an iterator to point to the insertion location\n \/\/ \n BasicBlock::InstListType& instList = bb->getInstList();\n TerminatorInst* termInst = bb->getTerminator(); \n BasicBlock::InstListType::iterator here = instList.end()-1;\n assert((*here)->isTerminator());\n \n \/\/ Insert a print instruction for each value.\n \/\/ \n for (unsigned i=0, N=valueVec.size(); i < N; i++)\n {\n Instruction* traceInstr =\n CreatePrintInstr(valueVec[i], bb, module, indent, isMethodExit);\n here = instList.insert(here, traceInstr);\n }\n}\n\nstatic void\nInsertCodeToShowMethodEntry(BasicBlock* entryBB)\n{\n}\n\nstatic void\nInsertCodeToShowMethodExit(BasicBlock* exitBB)\n{\n}\n\n\nbool InsertTraceCode::doInsertTraceCode(Method *M, bool traceBasicBlockExits,\n bool traceMethodExits) {\n vector<Value*> valuesToTraceInMethod;\n Module* module = M->getParent();\n BasicBlock* exitBB = NULL;\n \n if (M->isExternal() ||\n (! traceBasicBlockExits && ! traceMethodExits))\n return false;\n\n if (traceMethodExits) {\n InsertCodeToShowMethodEntry(M->getEntryNode());\n exitBB = M->getBasicBlocks().front(); \/\/getExitNode();\n }\n\n for (Method::iterator BI = M->begin(); BI != M->end(); ++BI) {\n BasicBlock* bb = *BI;\n\n vector<Value*> valuesToTraceInBB;\n FindValuesToTraceInBB(bb, valuesToTraceInBB);\n\n if (traceBasicBlockExits && bb != exitBB)\n TraceValuesAtBBExit(valuesToTraceInBB, bb, module,\n \/*indent*\/ 4, \/*isMethodExit*\/ false);\n\n if (traceMethodExits) {\n valuesToTraceInMethod.insert(valuesToTraceInMethod.end(),\n valuesToTraceInBB.begin(),\n valuesToTraceInBB.end());\n }\n }\n \n if (traceMethodExits) {\n TraceValuesAtBBExit(valuesToTraceInMethod, exitBB, module,\n \/*indent*\/ 0, \/*isMethodExit*\/ true);\n InsertCodeToShowMethodExit(exitBB);\n }\n return true;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/===- DeadStoreElimination.cpp - Dead Store Elimination ------------------===\/\/\n\/\/ \n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file was developed by the LLVM research group and is distributed under\n\/\/ the University of Illinois Open Source License. See LICENSE.TXT for details.\n\/\/ \n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This file implements a trivial dead store elimination that only considers\n\/\/ basic-block local redundant stores.\n\/\/\n\/\/ FIXME: This should eventually be extended to be a post-dominator tree\n\/\/ traversal. Doing so would be pretty trivial.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/Transforms\/Scalar.h\"\n#include \"llvm\/Function.h\"\n#include \"llvm\/Instructions.h\"\n#include \"llvm\/Analysis\/AliasAnalysis.h\"\n#include \"llvm\/Analysis\/AliasSetTracker.h\"\n#include \"llvm\/Target\/TargetData.h\"\n#include \"llvm\/Transforms\/Utils\/Local.h\"\n#include \"Support\/Statistic.h\"\nusing namespace llvm;\n\nnamespace {\n Statistic<> NumStores(\"dse\", \"Number of stores deleted\");\n Statistic<> NumOther (\"dse\", \"Number of other instrs removed\");\n\n struct DSE : public FunctionPass {\n\n virtual bool runOnFunction(Function &F) {\n bool Changed = false;\n for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)\n Changed |= runOnBasicBlock(*I);\n return Changed;\n }\n \n bool runOnBasicBlock(BasicBlock &BB);\n \n void DeleteDeadValueChains(Value *V, AliasSetTracker &AST);\n\n \/\/ getAnalysisUsage - We require post dominance frontiers (aka Control\n \/\/ Dependence Graph)\n virtual void getAnalysisUsage(AnalysisUsage &AU) const {\n AU.setPreservesCFG();\n AU.addRequired<TargetData>();\n AU.addRequired<AliasAnalysis>();\n AU.addPreserved<AliasAnalysis>();\n }\n };\n RegisterOpt<DSE> X(\"dse\", \"Dead Store Elimination\");\n}\n\nPass *llvm::createDeadStoreEliminationPass() { return new DSE(); }\n\nbool DSE::runOnBasicBlock(BasicBlock &BB) {\n TargetData &TD = getAnalysis<TargetData>();\n AliasAnalysis &AA = getAnalysis<AliasAnalysis>();\n AliasSetTracker KillLocs(AA);\n\n \/\/ If this block ends in a return, unwind, and eventually tailcall\/barrier,\n \/\/ then all allocas are dead at its end.\n if (BB.getTerminator()->getNumSuccessors() == 0) {\n\n }\n\n bool MadeChange = false;\n for (BasicBlock::iterator BBI = BB.end(); BBI != BB.begin(); ) {\n Instruction *I = --BBI; \/\/ Keep moving iterator backwards\n \n#if 0\n \/\/ AST doesn't support malloc\/free\/alloca???\n if (isa<FreeInst>(I)) {\n \/\/ Free instructions make any stores to the free'd location dead.\n KillLocs.insert(I);\n }\n#endif\n\n if (!isa<FreeInst>(I) &&\n (!isa<StoreInst>(I) || cast<StoreInst>(I)->isVolatile())) {\n \/\/ If this is a non-store instruction, it makes everything referenced no\n \/\/ longer killed. Remove anything aliased from the alias set tracker.\n KillLocs.remove(I);\n continue;\n }\n\n \/\/ If this is a non-volatile store instruction, and if it is already in\n \/\/ the stored location is already in the tracker, then this is a dead\n \/\/ store. We can just delete it here, but while we're at it, we also\n \/\/ delete any trivially dead expression chains.\n unsigned ValSize;\n Value *Ptr;\n if (isa<StoreInst>(I)) {\n Ptr = I->getOperand(1);\n ValSize = TD.getTypeSize(I->getOperand(0)->getType());\n } else {\n Ptr = I->getOperand(0);\n ValSize = ~0;\n }\n\n if (AliasSet *AS = KillLocs.getAliasSetForPointerIfExists(Ptr, ValSize))\n for (AliasSet::iterator ASI = AS->begin(), E = AS->end(); ASI != E; ++ASI)\n if (AA.alias(ASI.getPointer(), ASI.getSize(), Ptr, ValSize)\n == AliasAnalysis::MustAlias) {\n \/\/ If we found a must alias in the killed set, then this store really\n \/\/ is dead. Delete it now.\n ++BBI; \/\/ Don't invalidate iterator.\n Value *Val = I->getOperand(0);\n BB.getInstList().erase(I); \/\/ Nuke the store!\n ++NumStores;\n DeleteDeadValueChains(Val, KillLocs); \/\/ Delete any now-dead instrs\n DeleteDeadValueChains(Ptr, KillLocs); \/\/ Delete any now-dead instrs\n MadeChange = true;\n goto BigContinue;\n }\n\n \/\/ Otherwise, this is a non-dead store just add it to the set of dead\n \/\/ locations.\n KillLocs.add(I);\n BigContinue:;\n }\n return MadeChange;\n}\n\nvoid DSE::DeleteDeadValueChains(Value *V, AliasSetTracker &AST) {\n \/\/ Value must be dead.\n if (!V->use_empty()) return;\n\n if (Instruction *I = dyn_cast<Instruction>(V))\n if (isInstructionTriviallyDead(I)) {\n AST.deleteValue(I);\n getAnalysis<AliasAnalysis>().deleteValue(I);\n\n \/\/ See if this made any operands dead. We do it this way in case the\n \/\/ instruction uses the same operand twice. We don't want to delete a\n \/\/ value then reference it.\n while (unsigned NumOps = I->getNumOperands()) {\n Value *Op = I->getOperand(NumOps-1);\n I->op_erase(I->op_end()-1); \/\/ Drop from the operand list.\n DeleteDeadValueChains(Op, AST); \/\/ Attempt to nuke it.\n }\n\n I->getParent()->getInstList().erase(I);\n ++NumOther;\n }\n}\n<commit_msg>* Substantially simplify how free instructions are handled (potentially fixing a bug in DSE). * Delete dead operand uses iteratively instead of recursively, using a SetVector. * Defer deletion of dead operand uses until the end of processing, which means we don't have to bother with updating the AliasSetTracker. This speeds up DSE substantially.<commit_after>\/\/===- DeadStoreElimination.cpp - Dead Store Elimination ------------------===\/\/\n\/\/ \n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file was developed by the LLVM research group and is distributed under\n\/\/ the University of Illinois Open Source License. See LICENSE.TXT for details.\n\/\/ \n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This file implements a trivial dead store elimination that only considers\n\/\/ basic-block local redundant stores.\n\/\/\n\/\/ FIXME: This should eventually be extended to be a post-dominator tree\n\/\/ traversal. Doing so would be pretty trivial.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/Transforms\/Scalar.h\"\n#include \"llvm\/Function.h\"\n#include \"llvm\/Instructions.h\"\n#include \"llvm\/Analysis\/AliasAnalysis.h\"\n#include \"llvm\/Analysis\/AliasSetTracker.h\"\n#include \"llvm\/Target\/TargetData.h\"\n#include \"llvm\/Transforms\/Utils\/Local.h\"\n#include \"Support\/SetVector.h\"\n#include \"Support\/Statistic.h\"\nusing namespace llvm;\n\nnamespace {\n Statistic<> NumStores(\"dse\", \"Number of stores deleted\");\n Statistic<> NumOther (\"dse\", \"Number of other instrs removed\");\n\n struct DSE : public FunctionPass {\n\n virtual bool runOnFunction(Function &F) {\n bool Changed = false;\n for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)\n Changed |= runOnBasicBlock(*I);\n return Changed;\n }\n \n bool runOnBasicBlock(BasicBlock &BB);\n \n void DeleteDeadInstructionChains(Instruction *I,\n SetVector<Instruction*> &DeadInsts);\n\n \/\/ getAnalysisUsage - We require post dominance frontiers (aka Control\n \/\/ Dependence Graph)\n virtual void getAnalysisUsage(AnalysisUsage &AU) const {\n AU.setPreservesCFG();\n AU.addRequired<TargetData>();\n AU.addRequired<AliasAnalysis>();\n AU.addPreserved<AliasAnalysis>();\n }\n };\n RegisterOpt<DSE> X(\"dse\", \"Dead Store Elimination\");\n}\n\nPass *llvm::createDeadStoreEliminationPass() { return new DSE(); }\n\nbool DSE::runOnBasicBlock(BasicBlock &BB) {\n TargetData &TD = getAnalysis<TargetData>();\n AliasAnalysis &AA = getAnalysis<AliasAnalysis>();\n AliasSetTracker KillLocs(AA);\n\n \/\/ If this block ends in a return, unwind, and eventually tailcall\/barrier,\n \/\/ then all allocas are dead at its end.\n if (BB.getTerminator()->getNumSuccessors() == 0) {\n\n }\n\n \/\/ PotentiallyDeadInsts - Deleting dead stores from the program can make other\n \/\/ instructions die if they were only used as operands to stores. Keep track\n \/\/ of the operands to stores so that we can try deleting them at the end of\n \/\/ the traversal.\n SetVector<Instruction*> PotentiallyDeadInsts;\n\n bool MadeChange = false;\n for (BasicBlock::iterator BBI = BB.end(); BBI != BB.begin(); ) {\n Instruction *I = --BBI; \/\/ Keep moving iterator backwards\n \n \/\/ If this is a free instruction, it makes the free'd location dead!\n if (FreeInst *FI = dyn_cast<FreeInst>(I)) {\n \/\/ Free instructions make any stores to the free'd location dead.\n KillLocs.add(FI);\n continue;\n }\n\n if (!isa<StoreInst>(I) || cast<StoreInst>(I)->isVolatile()) {\n \/\/ If this is a non-store instruction, it makes everything referenced no\n \/\/ longer killed. Remove anything aliased from the alias set tracker.\n KillLocs.remove(I);\n continue;\n }\n\n \/\/ If this is a non-volatile store instruction, and if it is already in\n \/\/ the stored location is already in the tracker, then this is a dead\n \/\/ store. We can just delete it here, but while we're at it, we also\n \/\/ delete any trivially dead expression chains.\n unsigned ValSize = TD.getTypeSize(I->getOperand(0)->getType());\n Value *Ptr = I->getOperand(1);\n\n if (AliasSet *AS = KillLocs.getAliasSetForPointerIfExists(Ptr, ValSize))\n for (AliasSet::iterator ASI = AS->begin(), E = AS->end(); ASI != E; ++ASI)\n if (AA.alias(ASI.getPointer(), ASI.getSize(), Ptr, ValSize)\n == AliasAnalysis::MustAlias) {\n \/\/ If we found a must alias in the killed set, then this store really\n \/\/ is dead. Remember that the various operands of the store now have\n \/\/ fewer users. At the end we will see if we can delete any values\n \/\/ that are dead as part of the store becoming dead.\n if (Instruction *Op = dyn_cast<Instruction>(I->getOperand(0)))\n PotentiallyDeadInsts.insert(Op);\n if (Instruction *Op = dyn_cast<Instruction>(Ptr))\n PotentiallyDeadInsts.insert(Op);\n\n \/\/ Delete it now.\n ++BBI; \/\/ Don't invalidate iterator.\n BB.getInstList().erase(I); \/\/ Nuke the store!\n ++NumStores;\n MadeChange = true;\n goto BigContinue;\n }\n\n \/\/ Otherwise, this is a non-dead store just add it to the set of dead\n \/\/ locations.\n KillLocs.add(cast<StoreInst>(I));\n BigContinue:;\n }\n\n while (!PotentiallyDeadInsts.empty()) {\n Instruction *I = PotentiallyDeadInsts.back();\n PotentiallyDeadInsts.pop_back();\n DeleteDeadInstructionChains(I, PotentiallyDeadInsts);\n }\n return MadeChange;\n}\n\nvoid DSE::DeleteDeadInstructionChains(Instruction *I,\n SetVector<Instruction*> &DeadInsts) {\n \/\/ Instruction must be dead.\n if (!I->use_empty() || !isInstructionTriviallyDead(I)) return;\n\n \/\/ Let the alias analysis know that we have nuked a value.\n getAnalysis<AliasAnalysis>().deleteValue(I);\n\n \/\/ See if this made any operands dead. We do it this way in case the\n \/\/ instruction uses the same operand twice. We don't want to delete a\n \/\/ value then reference it.\n while (unsigned NumOps = I->getNumOperands()) {\n Instruction *Op = dyn_cast<Instruction>(I->getOperand(NumOps-1));\n I->op_erase(I->op_end()-1); \/\/ Drop from the operand list.\n \n if (Op) DeadInsts.insert(Op); \/\/ Attempt to nuke it later.\n }\n \n I->getParent()->getInstList().erase(I);\n ++NumOther;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Jubatus: Online machine learning framework for distributed environment\n\/\/ Copyright (C) 2013 Preferred Infrastructure and Nippon Telegraph and Telephone Corporation.\n\/\/\n\/\/ This library is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU Lesser General Public\n\/\/ License version 2.1 as published by the Free Software Foundation.\n\/\/\n\/\/ This library is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ Lesser General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License along with this library; if not, write to the Free Software\n\/\/ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n#include \"nearest_neighbor_recommender.hpp\"\n\n#include <string>\n#include <utility>\n#include <vector>\n#include \"jubatus\/util\/data\/serialization.h\"\n#include \"jubatus\/util\/lang\/shared_ptr.h\"\n#include \"..\/common\/exception.hpp\"\n\nusing jubatus::util::lang::shared_ptr;\n\nnamespace jubatus {\nnamespace core {\nnamespace recommender {\n\nclass nearest_neighbor_recommender::unlearning_callback {\n public:\n explicit unlearning_callback(nearest_neighbor_recommender* recommender)\n : recommender_(recommender),\n table_(recommender_->get_table()) {\n }\n\n void operator()(const std::string& id) {\n recommender_->orig_.remove_row(id);\n table_->delete_row(id);\n }\n\n private:\n nearest_neighbor_recommender* recommender_;\n jubatus::util::lang::shared_ptr<table::column_table> table_;\n};\n\nnearest_neighbor_recommender::nearest_neighbor_recommender(\n jubatus::util::lang::shared_ptr<nearest_neighbor::nearest_neighbor_base>\n nearest_neighbor_engine)\n : nearest_neighbor_engine_(nearest_neighbor_engine) {\n}\n\nnearest_neighbor_recommender::nearest_neighbor_recommender(\n jubatus::util::lang::shared_ptr<nearest_neighbor::nearest_neighbor_base>\n nearest_neighbor_engine,\n jubatus::util::lang::shared_ptr<unlearner::unlearner_base> unlearner)\n : nearest_neighbor_engine_(nearest_neighbor_engine),\n unlearner_(unlearner) {\n unlearner_->set_callback(unlearning_callback(this));\n}\n\nvoid nearest_neighbor_recommender::similar_row(\n const common::sfv_t& query,\n std::vector<std::pair<std::string, float> >& ids,\n size_t ret_num) const {\n nearest_neighbor_engine_->similar_row(query, ids, ret_num);\n}\n\nvoid nearest_neighbor_recommender::neighbor_row(\n const common::sfv_t& query,\n std::vector<std::pair<std::string, float> >& ids,\n size_t ret_num) const {\n nearest_neighbor_engine_->neighbor_row(query, ids, ret_num);\n}\n\nvoid nearest_neighbor_recommender::clear() {\n orig_.clear();\n nearest_neighbor_engine_->clear();\n}\n\nvoid nearest_neighbor_recommender::clear_row(const std::string& id) {\n throw JUBATUS_EXCEPTION(common::unsupported_method(__func__));\n}\n\nvoid nearest_neighbor_recommender::update_row(\n const std::string& id,\n const common::sfv_t& diff) {\n if (unlearner_) {\n if (!unlearner_->touch(id)) {\n throw JUBATUS_EXCEPTION(common::exception::runtime_error(\n \"no more space available to add new ID: \" + id));\n }\n }\n orig_.set_row(id, diff);\n common::sfv_t row;\n orig_.get_row(id, row);\n nearest_neighbor_engine_->set_row(id, row);\n}\n\nvoid nearest_neighbor_recommender::get_all_row_ids(\n std::vector<std::string>& ids) const {\n nearest_neighbor_engine_->get_all_row_ids(ids);\n}\n\nstd::string nearest_neighbor_recommender::type() const {\n return \"nearest_neighbor_recommender:\" + nearest_neighbor_engine_->type();\n}\n\nframework::mixable* nearest_neighbor_recommender::get_mixable() const {\n return nearest_neighbor_engine_->get_mixable();\n}\n\nvoid nearest_neighbor_recommender::pack(framework::packer& packer) const {\n packer.pack_array(2);\n orig_.pack(packer);\n nearest_neighbor_engine_->pack(packer);\n}\n\nvoid nearest_neighbor_recommender::unpack(msgpack::object o) {\n if (o.type != msgpack::type::ARRAY || o.via.array.size != 2) {\n throw msgpack::type_error();\n }\n orig_.unpack(o.via.array.ptr[0]);\n nearest_neighbor_engine_->unpack(o.via.array.ptr[1]);\n}\n\njubatus::util::lang::shared_ptr<table::column_table>\nnearest_neighbor_recommender::get_table() {\n return nearest_neighbor_engine_->get_table();\n}\n\njubatus::util::lang::shared_ptr<const table::column_table>\nnearest_neighbor_recommender::get_const_table() const {\n return nearest_neighbor_engine_->get_const_table();\n}\n\njubatus::util::lang::shared_ptr<unlearner::unlearner_base>\nnearest_neighbor_recommender::get_unlearner() {\n return unlearner_;\n}\n\n} \/\/ namespace recommender\n} \/\/ namespace core\n} \/\/ namespace jubatus\n<commit_msg>clear unlearner when clearning model in nn-based recommender (ref #13)<commit_after>\/\/ Jubatus: Online machine learning framework for distributed environment\n\/\/ Copyright (C) 2013 Preferred Infrastructure and Nippon Telegraph and Telephone Corporation.\n\/\/\n\/\/ This library is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU Lesser General Public\n\/\/ License version 2.1 as published by the Free Software Foundation.\n\/\/\n\/\/ This library is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ Lesser General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License along with this library; if not, write to the Free Software\n\/\/ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n#include \"nearest_neighbor_recommender.hpp\"\n\n#include <string>\n#include <utility>\n#include <vector>\n#include \"jubatus\/util\/data\/serialization.h\"\n#include \"jubatus\/util\/lang\/shared_ptr.h\"\n#include \"..\/common\/exception.hpp\"\n\nusing jubatus::util::lang::shared_ptr;\n\nnamespace jubatus {\nnamespace core {\nnamespace recommender {\n\nclass nearest_neighbor_recommender::unlearning_callback {\n public:\n explicit unlearning_callback(nearest_neighbor_recommender* recommender)\n : recommender_(recommender),\n table_(recommender_->get_table()) {\n }\n\n void operator()(const std::string& id) {\n recommender_->orig_.remove_row(id);\n table_->delete_row(id);\n }\n\n private:\n nearest_neighbor_recommender* recommender_;\n jubatus::util::lang::shared_ptr<table::column_table> table_;\n};\n\nnearest_neighbor_recommender::nearest_neighbor_recommender(\n jubatus::util::lang::shared_ptr<nearest_neighbor::nearest_neighbor_base>\n nearest_neighbor_engine)\n : nearest_neighbor_engine_(nearest_neighbor_engine) {\n}\n\nnearest_neighbor_recommender::nearest_neighbor_recommender(\n jubatus::util::lang::shared_ptr<nearest_neighbor::nearest_neighbor_base>\n nearest_neighbor_engine,\n jubatus::util::lang::shared_ptr<unlearner::unlearner_base> unlearner)\n : nearest_neighbor_engine_(nearest_neighbor_engine),\n unlearner_(unlearner) {\n unlearner_->set_callback(unlearning_callback(this));\n}\n\nvoid nearest_neighbor_recommender::similar_row(\n const common::sfv_t& query,\n std::vector<std::pair<std::string, float> >& ids,\n size_t ret_num) const {\n nearest_neighbor_engine_->similar_row(query, ids, ret_num);\n}\n\nvoid nearest_neighbor_recommender::neighbor_row(\n const common::sfv_t& query,\n std::vector<std::pair<std::string, float> >& ids,\n size_t ret_num) const {\n nearest_neighbor_engine_->neighbor_row(query, ids, ret_num);\n}\n\nvoid nearest_neighbor_recommender::clear() {\n orig_.clear();\n nearest_neighbor_engine_->clear();\n if (unlearner_) {\n unlearner_->clear();\n }\n}\n\nvoid nearest_neighbor_recommender::clear_row(const std::string& id) {\n throw JUBATUS_EXCEPTION(common::unsupported_method(__func__));\n}\n\nvoid nearest_neighbor_recommender::update_row(\n const std::string& id,\n const common::sfv_t& diff) {\n if (unlearner_) {\n if (!unlearner_->touch(id)) {\n throw JUBATUS_EXCEPTION(common::exception::runtime_error(\n \"no more space available to add new ID: \" + id));\n }\n }\n orig_.set_row(id, diff);\n common::sfv_t row;\n orig_.get_row(id, row);\n nearest_neighbor_engine_->set_row(id, row);\n}\n\nvoid nearest_neighbor_recommender::get_all_row_ids(\n std::vector<std::string>& ids) const {\n nearest_neighbor_engine_->get_all_row_ids(ids);\n}\n\nstd::string nearest_neighbor_recommender::type() const {\n return \"nearest_neighbor_recommender:\" + nearest_neighbor_engine_->type();\n}\n\nframework::mixable* nearest_neighbor_recommender::get_mixable() const {\n return nearest_neighbor_engine_->get_mixable();\n}\n\nvoid nearest_neighbor_recommender::pack(framework::packer& packer) const {\n packer.pack_array(2);\n orig_.pack(packer);\n nearest_neighbor_engine_->pack(packer);\n}\n\nvoid nearest_neighbor_recommender::unpack(msgpack::object o) {\n if (o.type != msgpack::type::ARRAY || o.via.array.size != 2) {\n throw msgpack::type_error();\n }\n orig_.unpack(o.via.array.ptr[0]);\n nearest_neighbor_engine_->unpack(o.via.array.ptr[1]);\n}\n\njubatus::util::lang::shared_ptr<table::column_table>\nnearest_neighbor_recommender::get_table() {\n return nearest_neighbor_engine_->get_table();\n}\n\njubatus::util::lang::shared_ptr<const table::column_table>\nnearest_neighbor_recommender::get_const_table() const {\n return nearest_neighbor_engine_->get_const_table();\n}\n\njubatus::util::lang::shared_ptr<unlearner::unlearner_base>\nnearest_neighbor_recommender::get_unlearner() {\n return unlearner_;\n}\n\n} \/\/ namespace recommender\n} \/\/ namespace core\n} \/\/ namespace jubatus\n<|endoftext|>"} {"text":"<commit_before>#include <iostream> \/* allows to perform standard input and output operations *\/\n#include <fstream>\n#include <stdio.h> \/* Standard input\/output definitions *\/\n#include <stdint.h> \/* Standard input\/output definitions *\/\n#include <stdlib.h> \/* defines several general purpose functions *\/\n#include <unistd.h> \/* UNIX standard function definitions *\/\n#include <fcntl.h> \/* File control definitions *\/\n#include <ctype.h> \/* isxxx() *\/\n#include <ros\/ros.h> \/* ROS *\/\n#include <geometry_msgs\/Twist.h> \/* ROS Twist message *\/\n#include <base_controller\/encoders.h> \/* Custom message \/encoders *\/\n#include <base_controller\/md49data.h> \/* Custom message \/encoders *\/\n\n#include <serialport\/serialport.h>\n#define REPLY_SIZE 18\n#define TIMEOUT 1000\n\nint32_t EncoderL; \/* stores encoder value left read from md49 *\/\nint32_t EncoderR; \/* stores encoder value right read from md49 *\/\nchar reply[REPLY_SIZE];\nchar speed_l=128;\nchar speed_r=128; \/* speed to set for MD49 *\/\nchar last_speed_l=128, last_speed_r=128; \/* speed to set for MD49 *\/\ndouble vr = 0.0;\ndouble vl = 0.0;\ndouble max_vr = 0.2;\ndouble max_vl = 0.2;\ndouble min_vr = 0.2;\ndouble min_vl = 0.2;\ndouble base_width = 0.4; \/* Base width in meters *\/\n\nunsigned char serialBuffer[18]; \/* Serial buffer to store uart data *\/\nvoid read_MD49_Data (void);\nvoid write_MD49_speed (unsigned char speed_l, unsigned char speed_r);\nvoid set_MD49_speed (void);\nchar* itoa(int value, char* result, int base);\n\nusing namespace std;\ncereal::CerealPort device;\nbase_controller::encoders encoders;\nbase_controller::md49data md49data;\n\nvoid cmd_vel_callback(const geometry_msgs::Twist& vel_cmd){\n\n if (vel_cmd.linear.x>0){\n speed_l = 255;\n speed_r = 255;\n }\n if (vel_cmd.linear.x<0){\n speed_l = 0;\n speed_r = 0;\n }\n if (vel_cmd.linear.x==0 && vel_cmd.angular.z==0){\n speed_l = 128;\n speed_r = 128;\n }\n if (vel_cmd.angular.z>0){\n speed_l = 0;\n speed_r = 255;\n }\n if (vel_cmd.angular.z<0){\n speed_l = 255;\n speed_r = 0;\n }\n\n\n \/*\n \/\/ANFANG Alternative\n if (vel_cmd.linear.x==0 && vel_cmd.angular.z==0){vl=0;vr=0;}\n else if(vel_cmd.linear.x == 0){\n \/\/ turning\n vr = vel_cmd.angular.z * base_width \/ 2.0;\n vl = (-1) * vr;\n }\n else if(vel_cmd.angular.z == 0){\n \/\/ forward \/ backward\n vl = vr = vel_cmd.linear.x;\n }\n else{\n \/\/ moving doing arcs\n vl = vel_cmd.linear.x - vel_cmd.angular.z * base_width \/ 2.0;\n if (vl > max_vl) {vl=max_vl;}\n if (vl < min_vl) {vl=min_vl;}\n vr = vel_cmd.linear.x + vel_cmd.angular.z * base_width \/ 2.0;\n if (vr > max_vr) {vr=max_vr;}\n if (vr < min_vr) {vr=min_vr;}\n }\n \/\/ENDE Alternative\n *\/\n}\n\n\nint main( int argc, char* argv[] ){\n\n ros::init(argc, argv, \"base_controller\" );\n ros::NodeHandle n;\n ros::Subscriber sub = n.subscribe(\"\/cmd_vel\", 10, cmd_vel_callback);\n ros::Publisher encoders_pub = n.advertise<base_controller::encoders>(\"encoders\",10);\n ros::Publisher md49data_pub = n.advertise<base_controller::md49data>(\"md49data\",10);\n\n \/\/ Init node\n \/\/ *********\n ros::Rate loop_rate(10);\n ROS_INFO(\"base_controller running...\");\n ROS_INFO(\"=============================\");\n ROS_INFO(\"Subscribing to topic \/cmd_vel\");\n ROS_INFO(\"Publishing to topic \/encoders\");\n ROS_INFO(\"Publishing to topic \/md49data\");\n\n \/\/ Open serial port\n \/\/ ****************\n try{ device.open(\"\/dev\/ttyAMA0\", 38400); }\n catch(cereal::Exception& e)\n {\n ROS_FATAL(\"Failed to open the serial port!!!\");\n ROS_BREAK();\n }\n ROS_INFO(\"The serial port is opened.\");\n\n\n while(n.ok())\n {\n \/\/ Read encoder and other data from MD49\n \/\/ (data is read from serial_controller_node\n \/\/ and avaiable through md49_data.txt)\n \/\/ *****************************************\n read_MD49_Data();\n\n \/\/ set speed as in md49speed.txt\n \/\/ *****************************\n if ((speed_l != last_speed_l) || (speed_r != last_speed_r)){\n \/\/ gewünschte werte in textfile\n write_MD49_speed(speed_l,speed_r);\n set_MD49_speed();\n last_speed_l=speed_l;\n last_speed_r=speed_r;\n }\n\n \/\/ Publish encoder values to topic \/encoders (custom message)\n \/\/ ********************************************************** \n encoders.encoder_l=EncoderL;\n encoders.encoder_r=EncoderR;\n encoders_pub.publish(encoders);\n\n \/\/ Publish MD49 data to topic \/md49data (custom message)\n \/\/ ***************************************************** \n md49data.speed_l = reply[8];\n md49data.speed_r = reply[9];\n md49data.volt = reply[10];\n md49data.current_l = reply[11];\n md49data.current_r = reply[12];\n md49data.error = reply[13];\n md49data.acceleration = reply[14];\n md49data.mode = reply[15];\n md49data.regulator = reply[16];\n md49data.timeout = reply[17];\n md49data_pub.publish(md49data);\n\n \/\/ ****\n ros::spinOnce();\n loop_rate.sleep();\n\n }\/\/ end.mainloop\n\n return 1;\n} \/\/ end.main\n\n\nvoid read_MD49_Data (void){\n\n \/\/ Send 'R' over the serial port\n device.write(\"R\");\n \/\/ Get the reply, the last value is the timeout in ms\n try{ device.read(reply, REPLY_SIZE, TIMEOUT); }\n catch(cereal::TimeoutException& e)\n {\n ROS_ERROR(\"Timeout on serialport! No data read\");\n }\n \/\/ROS_INFO(\"Received MD49 data\");\n\n \/\/ Put toghether new encodervalues\n \/\/ *******************************\n EncoderL = reply[0] << 24; \/\/ Put together first encoder value\n EncoderL |= (reply[1] << 16);\n EncoderL |= (reply[2] << 8);\n EncoderL |= (reply[3]);\n EncoderR = reply[4] << 24; \/\/ Put together second encoder value\n EncoderR |= (reply[5] << 16);\n EncoderR |= (reply[6] << 8);\n EncoderR |= (reply[7]);\n\n\/*\n \/\/ Output MD49 data on screen\n \/\/ **************************\n printf(\"\\033[2J\"); \/\/ clear the screen\n printf(\"\\033[H\"); \/\/ position cursor at top-left corner\n printf (\"MD49-Data read from AVR-Master: \\n\");\n printf(\"========================================\\n\");\n printf(\"Encoder1 Byte1: %i \",reply[0]);\n printf(\"Byte2: %i \",reply[1]);\n printf(\"Byte3: % i \",reply[2]);\n printf(\"Byte4: %i \\n\",reply[3]);\n printf(\"Encoder2 Byte1: %i \",reply[4]);\n printf(\"Byte2: %i \",reply[5]);\n printf(\"Byte3: %i \",reply[6]);\n printf(\"Byte4: %i \\n\",reply[7]);\n printf(\"EncoderL: %i \",EncoderL);\n printf(\"EncoderR: %i \\n\",EncoderR);\n printf(\"========================================\\n\");\n printf(\"Speed1: %i \",reply[8]);\n printf(\"Speed2: %i \\n\",reply[9]);\n printf(\"Volts: %i \\n\",reply[10]);\n printf(\"Current1: %i \",reply[11]);\n printf(\"Current2: %i \\n\",reply[12]);\n printf(\"Error: %i \\n\",reply[13]);\n printf(\"Acceleration: %i \\n\",reply[14]);\n printf(\"Mode: %i \\n\",reply[15]);\n printf(\"Regulator: %i \\n\",reply[16]);\n printf(\"Timeout: %i \\n\",reply[17]);\n*\/\n\n}\n\nvoid write_MD49_speed (unsigned char speed_l, unsigned char speed_r){\n\n char buffer[33];\n ofstream myfile;\n myfile.open (\"md49speed.txt\");\n \/\/myfile << \"Writing this to a file.\\n\";\n if (speed_l==0){\n myfile << \"000\";\n myfile << \"\\n\";\n }\n else if (speed_l<10){\n myfile << \"00\";\n myfile << itoa(speed_l,buffer,10);\n myfile << \"\\n\";\n }\n else if (speed_l<100){\n myfile << \"0\";\n myfile << itoa(speed_l,buffer,10);\n myfile << \"\\n\";\n }\n else{\n myfile << itoa(speed_l,buffer,10);\n myfile << \"\\n\";\n }\n\n if (speed_r==0){\n myfile << \"000\";\n myfile << \"\\n\";\n }\n else if (speed_r<10){\n myfile << \"00\";\n myfile << itoa(speed_r,buffer,10);\n myfile << \"\\n\";\n }\n else if (speed_r<100){\n myfile << \"0\";\n myfile << itoa(speed_r,buffer,10);\n myfile << \"\\n\";\n }\n else{\n myfile << itoa(speed_r,buffer,10);\n myfile << \"\\n\";\n }\n myfile.close();\n\n}\n\nvoid set_MD49_speed(void){\n unsigned char md49_speed[2]; \/* keeps data from MD49, read from AVR-Master *\/\n string line;\n string arrayOfString[2];\n ifstream myfile (\"md49speed.txt\");\n if (myfile.is_open()){\n int i=0;\n while ( getline (myfile,line) )\n {\n \/\/cout << line << '\\n';\n char data[10];\n std::copy(line.begin(), line.end(), data);\n md49_speed[i]=atoi(data);\n arrayOfString[i]=atoi(data);\n i =i++;\n }\n myfile.close();\n speed_l=md49_speed[0];\n speed_r=md49_speed[1];\n }\n else{\n cout << \"Unable to open file\";\n }\n const char* pointerToSpeedL = arrayOfString[0].c_str();\n const char* pointerToSpeedR = arrayOfString[1].c_str();\n device.write(\"Xs\",2);\n device.write(pointerToSpeedL,1);\n device.write(pointerToSpeedR,1);\n\n}\n\nchar* itoa(int value, char* result, int base) {\n \/\/ check that the base if valid\n if (base < 2 || base > 36) { *result = '\\0'; return result; }\n\n char* ptr = result, *ptr1 = result, tmp_char;\n int tmp_value;\n\n do {\n tmp_value = value;\n value \/= base;\n *ptr++ = \"zyxwvutsrqponmlkjihgfedcba9876543210123456789abcdefghijklmnopqrstuvwxyz\" [35 + (tmp_value - value * base)];\n } while ( value );\n\n \/\/ Apply negative sign\n if (tmp_value < 0) *ptr++ = '-';\n *ptr-- = '\\0';\n while(ptr1 < ptr) {\n tmp_char = *ptr;\n *ptr--= *ptr1;\n *ptr1++ = tmp_char;\n }\n return result;\n}\n<commit_msg>Update code<commit_after>#include <iostream> \/* allows to perform standard input and output operations *\/\n#include <fstream>\n#include <stdio.h> \/* Standard input\/output definitions *\/\n#include <stdint.h> \/* Standard input\/output definitions *\/\n#include <stdlib.h> \/* defines several general purpose functions *\/\n#include <unistd.h> \/* UNIX standard function definitions *\/\n#include <fcntl.h> \/* File control definitions *\/\n#include <ctype.h> \/* isxxx() *\/\n#include <ros\/ros.h> \/* ROS *\/\n#include <geometry_msgs\/Twist.h> \/* ROS Twist message *\/\n#include <base_controller\/encoders.h> \/* Custom message \/encoders *\/\n#include <base_controller\/md49data.h> \/* Custom message \/encoders *\/\n\n#include <serialport\/serialport.h>\n#define REPLY_SIZE 18\n#define TIMEOUT 1000\n\nint32_t EncoderL; \/* stores encoder value left read from md49 *\/\nint32_t EncoderR; \/* stores encoder value right read from md49 *\/\nchar reply[REPLY_SIZE];\nchar speed_l=128;\nchar speed_r=128; \/* speed to set for MD49 *\/\nchar last_speed_l=128, last_speed_r=128; \/* speed to set for MD49 *\/\ndouble vr = 0.0;\ndouble vl = 0.0;\ndouble max_vr = 0.2;\ndouble max_vl = 0.2;\ndouble min_vr = 0.2;\ndouble min_vl = 0.2;\ndouble base_width = 0.4; \/* Base width in meters *\/\n\nunsigned char serialBuffer[18]; \/* Serial buffer to store uart data *\/\nvoid read_MD49_Data (void);\nvoid write_MD49_speed (unsigned char speed_l, unsigned char speed_r);\nvoid set_MD49_speed (void);\nchar* itoa(int value, char* result, int base);\n\nusing namespace std;\ncereal::CerealPort device;\nbase_controller::encoders encoders;\nbase_controller::md49data md49data;\n\nvoid cmd_vel_callback(const geometry_msgs::Twist& vel_cmd){\n\n if (vel_cmd.linear.x>0){\n speed_l = 255;\n speed_r = 255;\n device.write(\"Xsÿÿ\",2);\n }\n if (vel_cmd.linear.x<0){\n speed_l = 0;\n speed_r = 0;\n }\n if (vel_cmd.linear.x==0 && vel_cmd.angular.z==0){\n speed_l = 128;\n speed_r = 128;\n device.write(\"Xs€€\",2);\n }\n if (vel_cmd.angular.z>0){\n speed_l = 0;\n speed_r = 255;\n }\n if (vel_cmd.angular.z<0){\n speed_l = 255;\n speed_r = 0;\n }\n\n\n \/*\n \/\/ANFANG Alternative\n if (vel_cmd.linear.x==0 && vel_cmd.angular.z==0){vl=0;vr=0;}\n else if(vel_cmd.linear.x == 0){\n \/\/ turning\n vr = vel_cmd.angular.z * base_width \/ 2.0;\n vl = (-1) * vr;\n }\n else if(vel_cmd.angular.z == 0){\n \/\/ forward \/ backward\n vl = vr = vel_cmd.linear.x;\n }\n else{\n \/\/ moving doing arcs\n vl = vel_cmd.linear.x - vel_cmd.angular.z * base_width \/ 2.0;\n if (vl > max_vl) {vl=max_vl;}\n if (vl < min_vl) {vl=min_vl;}\n vr = vel_cmd.linear.x + vel_cmd.angular.z * base_width \/ 2.0;\n if (vr > max_vr) {vr=max_vr;}\n if (vr < min_vr) {vr=min_vr;}\n }\n \/\/ENDE Alternative\n *\/\n}\n\n\nint main( int argc, char* argv[] ){\n\n ros::init(argc, argv, \"base_controller\" );\n ros::NodeHandle n;\n ros::Subscriber sub = n.subscribe(\"\/cmd_vel\", 10, cmd_vel_callback);\n ros::Publisher encoders_pub = n.advertise<base_controller::encoders>(\"encoders\",10);\n ros::Publisher md49data_pub = n.advertise<base_controller::md49data>(\"md49data\",10);\n\n \/\/ Init node\n \/\/ *********\n ros::Rate loop_rate(10);\n ROS_INFO(\"base_controller running...\");\n ROS_INFO(\"=============================\");\n ROS_INFO(\"Subscribing to topic \/cmd_vel\");\n ROS_INFO(\"Publishing to topic \/encoders\");\n ROS_INFO(\"Publishing to topic \/md49data\");\n\n \/\/ Open serial port\n \/\/ ****************\n try{ device.open(\"\/dev\/ttyAMA0\", 38400); }\n catch(cereal::Exception& e)\n {\n ROS_FATAL(\"Failed to open the serial port!!!\");\n ROS_BREAK();\n }\n ROS_INFO(\"The serial port is opened.\");\n\n\n while(n.ok())\n {\n \/\/ Read encoder and other data from MD49\n \/\/ (data is read from serial_controller_node\n \/\/ and avaiable through md49_data.txt)\n \/\/ *****************************************\n read_MD49_Data();\n\n \/\/ set speed as in md49speed.txt\n \/\/ *****************************\n if ((speed_l != last_speed_l) || (speed_r != last_speed_r)){\n \/\/ gewünschte werte in textfile\n \/\/write_MD49_speed(speed_l,speed_r);\n \/\/set_MD49_speed();\n \/\/ last_speed_l=speed_l;\n \/\/ last_speed_r=speed_r;\n }\n\n \/\/ Publish encoder values to topic \/encoders (custom message)\n \/\/ ********************************************************** \n encoders.encoder_l=EncoderL;\n encoders.encoder_r=EncoderR;\n encoders_pub.publish(encoders);\n\n \/\/ Publish MD49 data to topic \/md49data (custom message)\n \/\/ ***************************************************** \n md49data.speed_l = reply[8];\n md49data.speed_r = reply[9];\n md49data.volt = reply[10];\n md49data.current_l = reply[11];\n md49data.current_r = reply[12];\n md49data.error = reply[13];\n md49data.acceleration = reply[14];\n md49data.mode = reply[15];\n md49data.regulator = reply[16];\n md49data.timeout = reply[17];\n md49data_pub.publish(md49data);\n\n \/\/ ****\n ros::spinOnce();\n loop_rate.sleep();\n\n }\/\/ end.mainloop\n\n return 1;\n} \/\/ end.main\n\n\nvoid read_MD49_Data (void){\n\n \/\/ Send 'R' over the serial port\n device.write(\"R\");\n \/\/ Get the reply, the last value is the timeout in ms\n try{ device.read(reply, REPLY_SIZE, TIMEOUT); }\n catch(cereal::TimeoutException& e)\n {\n ROS_ERROR(\"Timeout on serialport! No data read\");\n }\n \/\/ROS_INFO(\"Received MD49 data\");\n\n \/\/ Put toghether new encodervalues\n \/\/ *******************************\n EncoderL = reply[0] << 24; \/\/ Put together first encoder value\n EncoderL |= (reply[1] << 16);\n EncoderL |= (reply[2] << 8);\n EncoderL |= (reply[3]);\n EncoderR = reply[4] << 24; \/\/ Put together second encoder value\n EncoderR |= (reply[5] << 16);\n EncoderR |= (reply[6] << 8);\n EncoderR |= (reply[7]);\n\n\/*\n \/\/ Output MD49 data on screen\n \/\/ **************************\n printf(\"\\033[2J\"); \/\/ clear the screen\n printf(\"\\033[H\"); \/\/ position cursor at top-left corner\n printf (\"MD49-Data read from AVR-Master: \\n\");\n printf(\"========================================\\n\");\n printf(\"Encoder1 Byte1: %i \",reply[0]);\n printf(\"Byte2: %i \",reply[1]);\n printf(\"Byte3: % i \",reply[2]);\n printf(\"Byte4: %i \\n\",reply[3]);\n printf(\"Encoder2 Byte1: %i \",reply[4]);\n printf(\"Byte2: %i \",reply[5]);\n printf(\"Byte3: %i \",reply[6]);\n printf(\"Byte4: %i \\n\",reply[7]);\n printf(\"EncoderL: %i \",EncoderL);\n printf(\"EncoderR: %i \\n\",EncoderR);\n printf(\"========================================\\n\");\n printf(\"Speed1: %i \",reply[8]);\n printf(\"Speed2: %i \\n\",reply[9]);\n printf(\"Volts: %i \\n\",reply[10]);\n printf(\"Current1: %i \",reply[11]);\n printf(\"Current2: %i \\n\",reply[12]);\n printf(\"Error: %i \\n\",reply[13]);\n printf(\"Acceleration: %i \\n\",reply[14]);\n printf(\"Mode: %i \\n\",reply[15]);\n printf(\"Regulator: %i \\n\",reply[16]);\n printf(\"Timeout: %i \\n\",reply[17]);\n*\/\n\n}\n\nvoid write_MD49_speed (unsigned char speed_l, unsigned char speed_r){\n\n char buffer[33];\n ofstream myfile;\n myfile.open (\"md49speed.txt\");\n \/\/myfile << \"Writing this to a file.\\n\";\n if (speed_l==0){\n myfile << \"000\";\n myfile << \"\\n\";\n }\n else if (speed_l<10){\n myfile << \"00\";\n myfile << itoa(speed_l,buffer,10);\n myfile << \"\\n\";\n }\n else if (speed_l<100){\n myfile << \"0\";\n myfile << itoa(speed_l,buffer,10);\n myfile << \"\\n\";\n }\n else{\n myfile << itoa(speed_l,buffer,10);\n myfile << \"\\n\";\n }\n\n if (speed_r==0){\n myfile << \"000\";\n myfile << \"\\n\";\n }\n else if (speed_r<10){\n myfile << \"00\";\n myfile << itoa(speed_r,buffer,10);\n myfile << \"\\n\";\n }\n else if (speed_r<100){\n myfile << \"0\";\n myfile << itoa(speed_r,buffer,10);\n myfile << \"\\n\";\n }\n else{\n myfile << itoa(speed_r,buffer,10);\n myfile << \"\\n\";\n }\n myfile.close();\n\n}\n\nvoid set_MD49_speed(void){\n unsigned char md49_speed[2]; \/* keeps data from MD49, read from AVR-Master *\/\n string line;\n string arrayOfString[2];\n ifstream myfile (\"md49speed.txt\");\n if (myfile.is_open()){\n int i=0;\n while ( getline (myfile,line) )\n {\n \/\/cout << line << '\\n';\n char data[10];\n std::copy(line.begin(), line.end(), data);\n md49_speed[i]=atoi(data);\n arrayOfString[i]=atoi(data);\n i =i++;\n }\n myfile.close();\n speed_l=md49_speed[0];\n speed_r=md49_speed[1];\n }\n else{\n cout << \"Unable to open file\";\n }\n const char* pointerToSpeedL = arrayOfString[0].c_str();\n const char* pointerToSpeedR = arrayOfString[1].c_str();\n device.write(\"Xs\",2);\n device.write(pointerToSpeedL,1);\n device.write(pointerToSpeedR,1);\n\n}\n\nchar* itoa(int value, char* result, int base) {\n \/\/ check that the base if valid\n if (base < 2 || base > 36) { *result = '\\0'; return result; }\n\n char* ptr = result, *ptr1 = result, tmp_char;\n int tmp_value;\n\n do {\n tmp_value = value;\n value \/= base;\n *ptr++ = \"zyxwvutsrqponmlkjihgfedcba9876543210123456789abcdefghijklmnopqrstuvwxyz\" [35 + (tmp_value - value * base)];\n } while ( value );\n\n \/\/ Apply negative sign\n if (tmp_value < 0) *ptr++ = '-';\n *ptr-- = '\\0';\n while(ptr1 < ptr) {\n tmp_char = *ptr;\n *ptr--= *ptr1;\n *ptr1++ = tmp_char;\n }\n return result;\n}\n<|endoftext|>"} {"text":"<commit_before>#include <iostream>\n#include <string>\n#include \"consoleui.h\"\n#include \"scientist.h\"\n\nusing namespace std;\n\nConsoleUI::ConsoleUI()\n{\n\n}\n\n\/\/ Should not contain logic for individual commands, that should be in separate functions!\nvoid ConsoleUI::run()\n{\n string command;\n do\n {\n cout << \"Select one of the following options: \" << endl;\n cout << \"Add - add a programmer\/computer scientist\" << endl;\n cout << \"List - show a list of all programmer's\/computer scientist's\" << endl;\n cout << \"Search - search the list of programmer's\/computer scientist's\" << endl;\n cout << \"Quit - end program\" << endl;\n\n\n cin >> command;\n for(unsigned int i = 0; i < command.length(); i++) \/\/ to make all lowercase, taken from c++ site\n {\n command[i] = tolower(command[i]);\n }\n\n cout << endl;\n\n if(command == \"add\") \/\/ Could possibly be improved upon\n {\n userMenuAdd();\n }\n else if(command == \"list\") \/\/ Could possibly be improved upon\n {\n userMenuList();\n }\n else if(command == \"search\") \/\/ Could possibly be improved upon\n {\n userMenuSearch();\n }\n else\n {\n cout << \"Invalid input\" << endl;\n }\n }while(command != \"quit\");\n\n\n\n}\nvoid ConsoleUI::userMenuAdd()\n{\n string name;\n char gender;\n int birthYear;\n int deathYear = 0;\n\n\n cout << \"Enter the programmer's\/computer scientist's name: \";\n cin.ignore();\n getline(cin, name);\n\n bool check = true;\n do\n {\n cout << \"Enter the programmer's\/computer scientist's gender (m\/f): \";\n cin >> gender;\n\n if((gender != 'm') && (gender != 'f'))\n {\n cout << \"Invalid input\" << endl;\n }\n else\n {\n cout << endl;\n check = false;\n }\n }while(check == true);\n\n bool check2 = true;\n do\n {\n cout << \"Enter the programmer's\/computer scientist's year of birth: \";\n cin >> birthYear;\n if(birthYear < 2016) \/\/ Just in case we find a programmer of the univers\n {\n cout << endl;\n check2 = false;\n }\n else\n {\n cout << \"Invalid input\" << endl;\n }\n }while(check2 == true);\n\n bool check3 = true;\n do\n {\n cout << \"Enter the programmer's\/computer scientist's year of death (type 0 if not applicable): \";\n cin >> deathYear;\n if(deathYear >= birthYear)\n {\n cout << endl;\n check3 = false;\n }\n else\n {\n cout << \"Invalid input\" << endl;\n }\n }while(check3 == true);\n\n _service.addScientist(name, gender, birthYear, deathYear);\n}\nvoid ConsoleUI::userMenuList()\n{\n vector<Scientist> scientist = _service.getScientists();\n\n cout << \"Scientist name:\" << endl;\n cout << \"===============\" << endl;\n for (size_t i = 0; i< scientist.size(); ++i)\n {\n cout << scientist[i].getName() << endl;\n }\n cout << endl;\n}\nvoid ConsoleUI::userMenuSearch()\n{\n string command;\n cout << \"Select a search option: \" << endl;\n cout << \"Name - Search by name\" << endl;\n cout << \"Birth - Search by year of birth\" << endl;\n cout << \"Death - search by year of death\" << endl;\n cin >> command;\n\n if(command == \"name\" || command == \"Name\" || command == \"NAME\")\n {\n vector<Scientist> scientist = _service.getScientists();\n string nameInputSearch;\n cout << \"Enter a name to search: \";\n cin >> nameInputSearch;\n\n for(unsigned int i = 0; i < scientist.size(); ++i)\n {\n if(scientist[i].getName() == nameInputSearch)\n {\n cout << scientist[i].getName() << endl;\n }\n }\n }\n else if(command == \"birth\" || command == \"Birth\" || command == \"BIRTH\")\n {\n\n }\n else if(command == \"death\" || command == \"Death\" || command == \"DEATH\")\n {\n\n }\n\n\n}\n<commit_msg>Fix 0 error<commit_after>#include <iostream>\n#include <string>\n#include \"consoleui.h\"\n#include \"scientist.h\"\n\nusing namespace std;\n\nConsoleUI::ConsoleUI()\n{\n\n}\n\n\/\/ Should not contain logic for individual commands, that should be in separate functions!\nvoid ConsoleUI::run()\n{\n string command;\n do\n {\n cout << \"Select one of the following options: \" << endl;\n cout << \"Add - add a programmer\/computer scientist\" << endl;\n cout << \"List - show a list of all programmer's\/computer scientist's\" << endl;\n cout << \"Search - search the list of programmer's\/computer scientist's\" << endl;\n cout << \"Quit - end program\" << endl;\n\n\n cin >> command;\n for(unsigned int i = 0; i < command.length(); i++) \/\/ to make all lowercase, taken from c++ site\n {\n command[i] = tolower(command[i]);\n }\n\n cout << endl;\n\n if(command == \"add\") \/\/ Could possibly be improved upon\n {\n userMenuAdd();\n }\n else if(command == \"list\") \/\/ Could possibly be improved upon\n {\n userMenuList();\n }\n else if(command == \"search\") \/\/ Could possibly be improved upon\n {\n userMenuSearch();\n }\n else\n {\n cout << \"Invalid input\" << endl;\n }\n }while(command != \"quit\");\n\n\n\n}\nvoid ConsoleUI::userMenuAdd()\n{\n string name;\n char gender;\n int birthYear;\n int deathYear = 0;\n\n\n cout << \"Enter the programmer's\/computer scientist's name: \";\n cin.ignore();\n getline(cin, name);\n\n bool check = true;\n do\n {\n cout << \"Enter the programmer's\/computer scientist's gender (m\/f): \";\n cin >> gender;\n\n if((gender != 'm') && (gender != 'f'))\n {\n cout << \"Invalid input\" << endl;\n }\n else\n {\n cout << endl;\n check = false;\n }\n }while(check == true);\n\n bool check2 = true;\n do\n {\n cout << \"Enter the programmer's\/computer scientist's year of birth: \";\n cin >> birthYear;\n if(birthYear < 2016) \/\/ Just in case we find a programmer of the univers\n {\n cout << endl;\n check2 = false;\n }\n else\n {\n cout << \"Invalid input\" << endl;\n }\n }while(check2 == true);\n\n bool check3 = true;\n do\n {\n cout << \"Enter the programmer's\/computer scientist's year of death (type 0 if not applicable): \";\n cin >> deathYear;\n if (deathYear == 0)\n {\n cout << endl;\n check3 = false;\n }\n else if(deathYear >= birthYear)\n {\n cout << endl;\n check3 = false;\n }\n else\n {\n cout << \"Invalid input\" << endl;\n }\n }while(check3 == true);\n\n _service.addScientist(name, gender, birthYear, deathYear);\n}\nvoid ConsoleUI::userMenuList()\n{\n vector<Scientist> scientist = _service.getScientists();\n\n cout << \"Scientist name:\" << endl;\n cout << \"===============\" << endl;\n for (size_t i = 0; i< scientist.size(); ++i)\n {\n cout << scientist[i].getName() << endl;\n }\n cout << endl;\n}\nvoid ConsoleUI::userMenuSearch()\n{\n string command;\n cout << \"Select a search option: \" << endl;\n cout << \"Name - Search by name\" << endl;\n cout << \"Birth - Search by year of birth\" << endl;\n cout << \"Death - search by year of death\" << endl;\n cin >> command;\n\n if(command == \"name\" || command == \"Name\" || command == \"NAME\")\n {\n vector<Scientist> scientist = _service.getScientists();\n string nameInputSearch;\n cout << \"Enter a name to search: \";\n cin >> nameInputSearch;\n\n for(unsigned int i = 0; i < scientist.size(); ++i)\n {\n if(scientist[i].getName() == nameInputSearch)\n {\n cout << scientist[i].getName() << endl;\n }\n }\n }\n else if(command == \"birth\" || command == \"Birth\" || command == \"BIRTH\")\n {\n\n }\n else if(command == \"death\" || command == \"Death\" || command == \"DEATH\")\n {\n\n }\n\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/* -*- mode: C++; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8 -*- *\/\n\n\/* linbox\/tests\/test-common.C\n * Copyright (C) 2001, 2002 Bradford Hovinen\n *\n * Written by Bradford Hovinen <hovinen@cis.udel.edu>\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\t See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the\n * Free Software Foundation, Inc., 59 Temple Place - Suite 330,\n * Boston, MA 02111-1307, USA.\n *\/\n\n#include \"linbox-config.h\"\n\n#include <iostream>\n#include <fstream>\n#include <vector>\n#include <cmath>\n#include <cstdlib>\n#include <cstring>\n#include <cmath>\n\n#include \"linbox\/util\/commentator.h\"\n#include \"linbox\/field\/archetype.h\"\n\n#include \"test-common.h\"\n\nusing namespace LinBox;\n\n\/* Display a help message on command usage *\/\n\nvoid printHelpMessage (const char *program, Argument *args, bool printDefaults = false) \n{\n\tint i, l;\n\n\t\/\/ Skip past libtool prefix in program name\n\tif (!strncmp (program, \"lt-\", strlen (\"lt-\")))\n\t\tprogram += strlen (\"lt-\");\n\n\tstd::cout << \"Usage: \" << program << \" [options] [<report file>]\" << std::endl;\n\tstd::cout << std::endl;\n\tstd::cout << \"Where [options] are the following:\" << std::endl;\n\n\tfor (i = 0; args[i].c != '\\0'; i++) {\n\t\tif (args[i].example != 0) {\n\t\t\tstd::cout << \" \" << args[i].example;\n\t\t\tl = 10 - strlen (args[i].example);\n\t\t\tdo std::cout << ' '; while (--l > 0);\n\t\t}\n\t\telse if (args[i].type == TYPE_NONE)\n\t\t\tstd::cout << \" -\" << args[i].c << \" {YN+-} \";\n\t\telse \n\t\t\tstd::cout << \" -\" << args[i].c << ' ' << args[i].c << \" \";\n\t\t\t\n\t\tstd::cout << args[i].helpString;\n\t\tif (printDefaults) {\n\t\t\tl = 54 - strlen (args[i].helpString);\n\t\t\tdo std::cout << ' '; while (--l > 0);\n\t\t\tstd::cout << \" (default \";\n\t\t\tswitch (args[i].type) {\n\t\t\tcase TYPE_NONE:\n\t\t\t\tcout << ((*(bool *)args[i].data)?\"ON\":\"OFF\");\n\t\t\t\tbreak;\n\t\t\tcase TYPE_INT:\n\t\t\t\tcout << *(int *) args[i].data;\n\t\t\t\tbreak;\n\t\t\tcase TYPE_INTEGER:\n\t\t\t\tcout << *(Integer *) args[i].data;\n\t\t\t\tbreak;\n\t\t\tcase TYPE_DOUBLE:\n\t\t\t\tcout << *(double *) args[i].data;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tstd::cout << \")\";\t\t\n\t\t}\n\t\tstd::cout << std::endl;\n\t}\n\n\tstd::cout << \" -h or -? Display this message\" << std::endl;\n\tstd::cout << \"For boolean switches, the argument may be omitted, meaning the switch should be ON\" << std::endl;\n\tstd::cout << std::endl;\n\tstd::cout << \"If <report file> is not given, then no detailed reporting is done. This is\" << std::endl;\n\tstd::cout << \"suitable if you wish only to determine whether the tests succeeded.\" << std::endl;\n\tstd::cout << std::endl;\n\tstd::cout << \"[1] N.B. This program does not verify the primality of Q, and does not use a\" << std::endl;\n\tstd::cout << \" field extension in the event that Q=p^n, n > 1\" << std::endl;\n\tstd::cout << std::endl;\n}\n\n\/* Find an argument in the argument list for a character *\/\n\nArgument *findArgument (Argument *args, char c) \n{\n\tint i;\n\n\tfor (i = 0; args[i].c != '\\0' && args[i].c != c; i++);\n\n\tif (args[i].c != '\\0')\n\t\treturn &(args[i]);\n\telse\n\t\treturn (Argument *) 0;\n}\n\n\/* Parse command line arguments *\/\n\nvoid parseArguments (int argc, char **argv, Argument *args, bool printDefaults = false)\n{\n\tint i;\n\tArgument *current;\n\n\tfor (i = 1; i < argc; i++) {\n\t\tif (argv[i][0] == '-') {\n\t\t\tif (argv[i][1] == 'h' || argv[i][1] == '?') {\n\t\t\t\tprintHelpMessage (argv[0], args, printDefaults);\n\t\t\t\texit (1);\n\t\t\t}\n\t\t\telse if ((current = findArgument (args, argv[i][1])) != (Argument *) 0) {\n\t\t\t\tswitch (current->type) {\n\t\t\t\tcase TYPE_NONE:\n\t\t\t\t\tif (argc == i+1 || (argv[i+1][0] == '-' && argv[i+1][1] != '\\0')) {\n\t\t\t\t\t\t\/\/ if last argument, or next argument is a switch, set to true\n\t\t\t\t\t\t*(bool *) current->data = true;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\t*(bool *) current->data = (argv[i+1][0] == '+' || argv[i+1][0] == 'Y' || argv[i+1][0] == 'y'\n\t\t\t\t\t\t\t\t || argv[i+1][0] == 'T' || argv[i+1][0] == 't') ;\n\t\t\t\t\ti++;\n\t\t\t\t\tbreak;\n\n\n\t\t\t\tcase TYPE_INT:\n\t\t\t\t\t*(int *) current->data = atoi (argv[i+1]);\n\t\t\t\t\ti++;\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase TYPE_INTEGER:\n\t\t\t\t\t*(integer *) current->data = atoi (argv[i+1]);\n\t\t\t\t\ti++;\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase TYPE_DOUBLE:\n\t\t\t\t\t*(double *) current->data = atof (argv[i+1]);\n\t\t\t\t\ti++;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tstd::cerr << \"ERROR: Bad argument \" << argv[i] << std::endl;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t} else {\n\t\t\tcommentator.setDefaultReportFile (argv[i]);\n\t\t\tstd::cout << \"Writing report data to \" << argv[i] << std::endl << std::endl;\n\t\t\tstd::cout.flush ();\n\t\t}\n\t}\n}\n\nstd::ostream& writeCommandString (std::ostream& os, Argument *args, char* programName) {\n\tos << programName;\n\tfor (int i = 0; args[i].c != '\\0'; i++) {\n\t\tcout << \" -\" << args[i].c;\n\t\tswitch (args[i].type) {\n\t\tcase TYPE_NONE:\n\t\t\tif (! (*(bool *)args[i].data)) os << \" N\";\n\t\t\tbreak;\n\t\tcase TYPE_INT:\n\t\t\tos << ' ' << *(int *) args[i].data;\n\t\t\tbreak;\n\t\tcase TYPE_INTEGER:\n\t\t\tos << ' ' << *(Integer *) args[i].data;\n\t\t\tbreak;\n\t\tcase TYPE_DOUBLE:\n\t\t\tos << ' ' << *(double *) args[i].data;\n\t\t\tbreak;\n\t\t}\n\t}\n\treturn os << std::endl;\n}\n\nbool isPower (integer n, integer m)\n{\n\treturn (n == 1) || ((n % m) == 0) && isPower (n\/m, m);\n}\n\ninline double incompleteGamma (double a, double x, double tol) \n{\n\tdouble xa_ex = pow (x, a) * exp (-x);\n\tdouble pi = 1.0;\n\tdouble xn = 1.0;\n\tdouble sigma = 0.0;\n\tdouble last_sigma;\n\n\tint n = 0;\n\n\tdo {\n\t\tpi *= a + n;\n\t\tlast_sigma = sigma;\n\t\tsigma += xn \/ pi;\n\t\txn *= x;\n\t\t++n;\n\t} while (abs (sigma - last_sigma) >= tol);\n\n\treturn sigma * xa_ex;\n}\n\ndouble chiSquaredCDF (double chi_sqr, double df)\n{\n\treturn incompleteGamma (df \/ 2.0, chi_sqr \/ 2.0, 1e-10) \/ exp (gamma (df \/ 2.0));\n}\n\n<commit_msg>Removed default initialization of last arg of parseArgument: didn't compile since it was already initialized in the declaration in test-common.h<commit_after>\/* -*- mode: C++; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8 -*- *\/\n\n\/* linbox\/tests\/test-common.C\n * Copyright (C) 2001, 2002 Bradford Hovinen\n *\n * Written by Bradford Hovinen <hovinen@cis.udel.edu>\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\t See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the\n * Free Software Foundation, Inc., 59 Temple Place - Suite 330,\n * Boston, MA 02111-1307, USA.\n *\/\n\n#include \"linbox-config.h\"\n\n#include <iostream>\n#include <fstream>\n#include <vector>\n#include <cmath>\n#include <cstdlib>\n#include <cstring>\n#include <cmath>\n\n#include \"linbox\/util\/commentator.h\"\n#include \"linbox\/field\/archetype.h\"\n\n#include \"test-common.h\"\n\nusing namespace LinBox;\n\n\/* Display a help message on command usage *\/\n\nvoid printHelpMessage (const char *program, Argument *args, bool printDefaults = false) \n{\n\tint i, l;\n\n\t\/\/ Skip past libtool prefix in program name\n\tif (!strncmp (program, \"lt-\", strlen (\"lt-\")))\n\t\tprogram += strlen (\"lt-\");\n\n\tstd::cout << \"Usage: \" << program << \" [options] [<report file>]\" << std::endl;\n\tstd::cout << std::endl;\n\tstd::cout << \"Where [options] are the following:\" << std::endl;\n\n\tfor (i = 0; args[i].c != '\\0'; i++) {\n\t\tif (args[i].example != 0) {\n\t\t\tstd::cout << \" \" << args[i].example;\n\t\t\tl = 10 - strlen (args[i].example);\n\t\t\tdo std::cout << ' '; while (--l > 0);\n\t\t}\n\t\telse if (args[i].type == TYPE_NONE)\n\t\t\tstd::cout << \" -\" << args[i].c << \" {YN+-} \";\n\t\telse \n\t\t\tstd::cout << \" -\" << args[i].c << ' ' << args[i].c << \" \";\n\t\t\t\n\t\tstd::cout << args[i].helpString;\n\t\tif (printDefaults) {\n\t\t\tl = 54 - strlen (args[i].helpString);\n\t\t\tdo std::cout << ' '; while (--l > 0);\n\t\t\tstd::cout << \" (default \";\n\t\t\tswitch (args[i].type) {\n\t\t\tcase TYPE_NONE:\n\t\t\t\tcout << ((*(bool *)args[i].data)?\"ON\":\"OFF\");\n\t\t\t\tbreak;\n\t\t\tcase TYPE_INT:\n\t\t\t\tcout << *(int *) args[i].data;\n\t\t\t\tbreak;\n\t\t\tcase TYPE_INTEGER:\n\t\t\t\tcout << *(Integer *) args[i].data;\n\t\t\t\tbreak;\n\t\t\tcase TYPE_DOUBLE:\n\t\t\t\tcout << *(double *) args[i].data;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tstd::cout << \")\";\t\t\n\t\t}\n\t\tstd::cout << std::endl;\n\t}\n\n\tstd::cout << \" -h or -? Display this message\" << std::endl;\n\tstd::cout << \"For boolean switches, the argument may be omitted, meaning the switch should be ON\" << std::endl;\n\tstd::cout << std::endl;\n\tstd::cout << \"If <report file> is not given, then no detailed reporting is done. This is\" << std::endl;\n\tstd::cout << \"suitable if you wish only to determine whether the tests succeeded.\" << std::endl;\n\tstd::cout << std::endl;\n\tstd::cout << \"[1] N.B. This program does not verify the primality of Q, and does not use a\" << std::endl;\n\tstd::cout << \" field extension in the event that Q=p^n, n > 1\" << std::endl;\n\tstd::cout << std::endl;\n}\n\n\/* Find an argument in the argument list for a character *\/\n\nArgument *findArgument (Argument *args, char c) \n{\n\tint i;\n\n\tfor (i = 0; args[i].c != '\\0' && args[i].c != c; i++);\n\n\tif (args[i].c != '\\0')\n\t\treturn &(args[i]);\n\telse\n\t\treturn (Argument *) 0;\n}\n\n\/* Parse command line arguments *\/\n\nvoid parseArguments (int argc, char **argv, Argument *args, bool printDefaults)\n{\n\tint i;\n\tArgument *current;\n\n\tfor (i = 1; i < argc; i++) {\n\t\tif (argv[i][0] == '-') {\n\t\t\tif (argv[i][1] == 'h' || argv[i][1] == '?') {\n\t\t\t\tprintHelpMessage (argv[0], args, printDefaults);\n\t\t\t\texit (1);\n\t\t\t}\n\t\t\telse if ((current = findArgument (args, argv[i][1])) != (Argument *) 0) {\n\t\t\t\tswitch (current->type) {\n\t\t\t\tcase TYPE_NONE:\n\t\t\t\t\tif (argc == i+1 || (argv[i+1][0] == '-' && argv[i+1][1] != '\\0')) {\n\t\t\t\t\t\t\/\/ if last argument, or next argument is a switch, set to true\n\t\t\t\t\t\t*(bool *) current->data = true;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\t*(bool *) current->data = (argv[i+1][0] == '+' || argv[i+1][0] == 'Y' || argv[i+1][0] == 'y'\n\t\t\t\t\t\t\t\t || argv[i+1][0] == 'T' || argv[i+1][0] == 't') ;\n\t\t\t\t\ti++;\n\t\t\t\t\tbreak;\n\n\n\t\t\t\tcase TYPE_INT:\n\t\t\t\t\t*(int *) current->data = atoi (argv[i+1]);\n\t\t\t\t\ti++;\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase TYPE_INTEGER:\n\t\t\t\t\t*(integer *) current->data = atoi (argv[i+1]);\n\t\t\t\t\ti++;\n\t\t\t\t\tbreak;\n\n\t\t\t\tcase TYPE_DOUBLE:\n\t\t\t\t\t*(double *) current->data = atof (argv[i+1]);\n\t\t\t\t\ti++;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tstd::cerr << \"ERROR: Bad argument \" << argv[i] << std::endl;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t} else {\n\t\t\tcommentator.setDefaultReportFile (argv[i]);\n\t\t\tstd::cout << \"Writing report data to \" << argv[i] << std::endl << std::endl;\n\t\t\tstd::cout.flush ();\n\t\t}\n\t}\n}\n\nstd::ostream& writeCommandString (std::ostream& os, Argument *args, char* programName) {\n\tos << programName;\n\tfor (int i = 0; args[i].c != '\\0'; i++) {\n\t\tcout << \" -\" << args[i].c;\n\t\tswitch (args[i].type) {\n\t\tcase TYPE_NONE:\n\t\t\tif (! (*(bool *)args[i].data)) os << \" N\";\n\t\t\tbreak;\n\t\tcase TYPE_INT:\n\t\t\tos << ' ' << *(int *) args[i].data;\n\t\t\tbreak;\n\t\tcase TYPE_INTEGER:\n\t\t\tos << ' ' << *(Integer *) args[i].data;\n\t\t\tbreak;\n\t\tcase TYPE_DOUBLE:\n\t\t\tos << ' ' << *(double *) args[i].data;\n\t\t\tbreak;\n\t\t}\n\t}\n\treturn os << std::endl;\n}\n\nbool isPower (integer n, integer m)\n{\n\treturn (n == 1) || ((n % m) == 0) && isPower (n\/m, m);\n}\n\ninline double incompleteGamma (double a, double x, double tol) \n{\n\tdouble xa_ex = pow (x, a) * exp (-x);\n\tdouble pi = 1.0;\n\tdouble xn = 1.0;\n\tdouble sigma = 0.0;\n\tdouble last_sigma;\n\n\tint n = 0;\n\n\tdo {\n\t\tpi *= a + n;\n\t\tlast_sigma = sigma;\n\t\tsigma += xn \/ pi;\n\t\txn *= x;\n\t\t++n;\n\t} while (abs (sigma - last_sigma) >= tol);\n\n\treturn sigma * xa_ex;\n}\n\ndouble chiSquaredCDF (double chi_sqr, double df)\n{\n\treturn incompleteGamma (df \/ 2.0, chi_sqr \/ 2.0, 1e-10) \/ exp (gamma (df \/ 2.0));\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/* BEGIN_COMMON_COPYRIGHT_HEADER\n *\n * Razor - a lightweight, Qt based, desktop toolset\n * http:\/\/razor-qt.org\n *\n * Copyright: 2011 Razor team\n * Authors:\n * Petr Vanek <petr@scribus.info>\n *\n * This program is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU General Public License\n * as published by the Free Software Foundation; only version 2 of\n * the License is valid for this program.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.\n *\n * END_COMMON_COPYRIGHT_HEADER *\/\n\/* Based on a \"MountTray\" project - modified for Razor needs\n http:\/\/hatred.homelinux.net\n\n @date 2010-11-11\n @brief Main application class: integrate all components\n\n Copyright (C) 2010 by hatred <hatred@inbox.ru>\n\n This program is free software; you can redistribute it and\/or modify\n it under the terms of the version 2 of GNU General Public License as\n published by the Free Software Foundation.\n\n For more information see LICENSE and LICENSE.ru files\n*\/\n\n#include <QtDebug>\n\n#include <QtGui\/QMessageBox>\n#include <QtGui\/QDesktopServices>\n#include <QtCore\/QUrl>\n\n#include \"qtxdg\/xdgicon.h\"\n#include \"mountbutton.h\"\n\n\nMountButton::MountButton(QWidget * parent, RazorPanel *panel)\n : QToolButton(parent),\n m_panel(panel)\n{\n if (!QDBusConnection::systemBus().isConnected())\n {\n qDebug() << \"Can't connect to dbus daemon. Some functions will be omited\";\n }\n\n setIcon(XdgIcon::fromTheme(\"emblem-mounted\"));\n\n \/\/ Display disk menu\n m_menu = new QMenu(this);\n QAction *empty_action = m_menu->addAction(tr(\"Empty\"));\n empty_action->setEnabled(false);\n \n\/\/ setMenu(m_menu);\n\n QDBusConnection conn = QDBusConnection::systemBus();\n \/\/ TODO: Check for connection, timer for reconect\n \/*bool connected =*\/ conn.connect(\"org.freedesktop.UDisks\",\n \"\/org\/freedesktop\/UDisks\",\n \"org.freedesktop.UDisks\",\n \"DeviceChanged\",\n this,\n SLOT(onDbusDeviceChangesMessage(QDBusObjectPath)));\n\n \/\/ Scan already connected devices\n initialScanDevices();\n\n connect(this, SIGNAL(clicked()), this, SLOT(showMenu()));\n\n connect(&_dm, SIGNAL(deviceConnected(DiskInfo)),\n this, SLOT(onDiskAdded(DiskInfo)));\n connect(&_dm, SIGNAL(deviceDisconnected(DiskInfo)),\n this, SLOT(onDiskRemoved(DiskInfo)));\n _dm.start();\n}\n\nMountButton::~MountButton()\n{\n _dm.exit(0);\n _dm.wait(1000);\n _dm.terminate();\n _dm.wait();\n}\n\nvoid MountButton::initialScanDevices()\n{\n QList<DiskInfo*> devices = _dm.scanDevices();\n for (int i = 0; i < devices.count(); i++)\n {\n DiskInfo *disk = devices.at(i);\n\n \/\/ add device\n _sm.addDevice(*disk);\n addMenuItem(*disk);\n\n StorageItem *sitem = _sm.getDevice(*disk);\n updateMenuItem(disk->device_name, disk->file_system_label, sitem->isMounted());\n\n \/\/ clear\n delete disk;\n }\n}\n\nvoid MountButton::addMenuItem(const DiskInfo &info)\n{\n MenuDiskItem *item = new MenuDiskItem(info, this);\n QWidgetAction *action = new QWidgetAction(this);\n action->setDefaultWidget(item);\n\n if (m_menu_items.count() == 0)\n {\n \/\/ Clear 'Empty' item\n m_menu->clear();\n m_menu->addAction(action);\n }\n else\n {\n \/\/ Insert on Top\n m_menu->insertAction(m_menu->actions().at(0), action);\n }\n\n m_menu_items.insert(info.device_name, action);\n\n \/\/ Connect signals\n connect(item, SIGNAL(mountMedia(const QString&)),\n this, SLOT(onMediaMount(const QString&)));\n\n connect(item, SIGNAL(ejectMedia(const QString&)),\n this, SLOT(onMediaEject(const QString&)));\n}\n\nvoid MountButton::removeMenuItem(const QString &device)\n{\n QWidgetAction *action = 0;\n if (m_menu_items.contains(device))\n {\n action = m_menu_items[device];\n m_menu->removeAction(action);\n m_menu_items.remove(device);\n delete action;\n }\n\n if (m_menu_items.count() == 0)\n {\n QAction *empty_action = m_menu->addAction(tr(\"Empty\"));\n empty_action->setEnabled(false);\n }\n}\n\nvoid MountButton::updateMenuItem(const QString &device, const QString &name, bool is_mounted)\n{\n QWidgetAction *action = 0;\n if (m_menu_items.contains(device))\n {\n action = m_menu_items[device];\n MenuDiskItem *item = static_cast<MenuDiskItem*>(action->defaultWidget());\n\n if (item == 0)\n {\n return;\n }\n\n if (!name.isEmpty())\n {\n item->setLabel(name);\n }\n\n item->setMountStatus(is_mounted);\n }\n}\n\nvoid MountButton::showMessage(const QString &text)\n{\n \/\/ TODO\/FIXME: messaging!\n \/\/_tray_icon.showMessage(\"MountTray\", text);\n qDebug() << \"MESSAGE\" << text;\n}\n\nvoid MountButton::showError(const QString &text)\n{\n \/\/ TODO\/FIXME: messaging!\n\/\/ _tray_icon.showMessage(\"MountTray Error\", text, QSystemTrayIcon::Critical);\n qDebug() << \"ERRMSG\" << text;\n}\n\n\/**************************************************************************************************\/\n\/* Signals ---------------------------------------------------------------------------------------*\/\n\/**************************************************************************************************\/\n\nvoid MountButton::onDiskAdded(DiskInfo info)\n{\n _sm.addDevice(info);\n addMenuItem(info);\n showMessage(tr(\"Device connected: %1\").arg(info.device_name));\n}\n\nvoid MountButton::onDiskRemoved(DiskInfo info)\n{\n _sm.removeDevice(info);\n removeMenuItem(info.device_name);\n showMessage(tr(\"Device removed: %1\").arg(info.device_name));\n}\n\nvoid MountButton::onDbusDeviceChangesMessage(QDBusObjectPath device)\n{\n QString path = device.path();\n qDebug() << \"Changed: \" << qPrintable(path);\n\n QDBusInterface iface(\"org.freedesktop.UDisks\",\n path,\n \"org.freedesktop.UDisks.Device\",\n QDBusConnection::systemBus());\n\n \/\/qDebug() << \"Device name: \" << iface.property(\"DeviceFile\");\n \/\/qDebug() << \"Is mounted: \" << iface.property(\"DeviceIsMounted\");\n\n QString dev_name = iface.property(\"DeviceFile\").toString();\n bool is_mounted = iface.property(\"DeviceIsMounted\").toBool();\n\n StorageItem *item = _sm.getDevice(dev_name);\n if (item == NULL)\n {\n return;\n }\n\n bool old_state = item->isMounted();\n item->setMountStatus(is_mounted);\n updateMenuItem(dev_name, QString(), item->isMounted());\n\n if (item->isMounted() != old_state)\n {\n if (item->isMounted())\n {\n QString mount_point = item->getMountPoint();\n showMessage(tr(\"Device '%1' is mounted to %2\").arg(dev_name).arg(mount_point));\n }\n else\n {\n showMessage(tr(\"Device '%1' is unmounted\\nNow you can eject USB Flash or CD\/DVD Disk\").arg(dev_name));\n }\n }\n}\n\nvoid MountButton::onMediaMount(const QString &device)\n{\n qDebug() << \"Mount media: \" << qPrintable(device) << \"\\n\";\n m_menu->hide();\n\n StorageItem *item = _sm.getDevice(device);\n if (item == NULL)\n {\n return;\n }\n\n bool old_state = item->isMounted();\n QString status_text;\n if (!item->isMounted())\n {\n item->mount(status_text);\n }\n\n QString mount_point = item->getMountPoint();\n\n if (!item->isMounted())\n {\n \/\/ Error\n showError(tr(\"Can't mount device: %1\\n%2\").arg(device).arg(status_text));\n return;\n }\n\n if (item->isMounted() != old_state)\n {\n showMessage(tr(\"Device '%1' is mounted to %2\").arg(device).arg(mount_point));\n updateMenuItem(device, \"\", true);\n }\n\n \/\/ Run manager\n QDesktopServices::openUrl(QUrl(mount_point));\n\n}\n\nvoid MountButton::onMediaEject(const QString &device)\n{\n qDebug() << \"UnMount media: \" << qPrintable(device) << \"\\n\";\n m_menu->hide();\n\n StorageItem *item = _sm.getDevice(device);\n if (item == NULL)\n {\n return;\n }\n\n QString status_text;\n if (item->isMounted())\n {\n item->unmount(status_text);\n }\n\n if (item->isMounted())\n {\n \/\/ Error\n showError(tr(\"Can't unmount device: %1\\n%2\").arg(device).arg(status_text));\n return;\n }\n\n showMessage(tr(\"Device '%1' is unmounted\").arg(device));\n updateMenuItem(device, \"\", false);\n}\n\nvoid MountButton::showMenu()\n{\n \/\/ TODO\/FIXME: shared code with MainMenu plugin. How to share? Something like \"menubutton base class\"?\n int x, y;\n\n switch (m_panel->position())\n {\n case RazorPanel::PositionTop:\n x = mapToGlobal(QPoint(0, 0)).x();\n y = m_panel->mapToGlobal(QPoint(0, m_panel->sizeHint().height())).y();\n break;\n\n case RazorPanel::PositionBottom:\n x = mapToGlobal(QPoint(0, 0)).x();\n y = m_panel->mapToGlobal(QPoint(0, 0)).y() - m_menu->sizeHint().height();\n break;\n\n case RazorPanel::PositionLeft:\n x = m_panel->mapToGlobal(QPoint(m_panel->sizeHint().width(), 0)).x();\n y = mapToGlobal(QPoint(0, 0)).y();\n break;\n\n case RazorPanel::PositionRight:\n x = m_panel->mapToGlobal(QPoint(0, 0)).x() - m_menu->sizeHint().width();\n y = mapToGlobal(QPoint(0, 0)).y();\n break;\n\n }\n\n QPoint pos(x, y);\n m_menu->exec(pos);\n}\n<commit_msg>fixed (workaround before real event notifications) #42 mount plugin: display notifications when connected<commit_after>\/* BEGIN_COMMON_COPYRIGHT_HEADER\n *\n * Razor - a lightweight, Qt based, desktop toolset\n * http:\/\/razor-qt.org\n *\n * Copyright: 2011 Razor team\n * Authors:\n * Petr Vanek <petr@scribus.info>\n *\n * This program is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU General Public License\n * as published by the Free Software Foundation; only version 2 of\n * the License is valid for this program.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.\n *\n * END_COMMON_COPYRIGHT_HEADER *\/\n\/* Based on a \"MountTray\" project - modified for Razor needs\n http:\/\/hatred.homelinux.net\n\n @date 2010-11-11\n @brief Main application class: integrate all components\n\n Copyright (C) 2010 by hatred <hatred@inbox.ru>\n\n This program is free software; you can redistribute it and\/or modify\n it under the terms of the version 2 of GNU General Public License as\n published by the Free Software Foundation.\n\n For more information see LICENSE and LICENSE.ru files\n*\/\n\n#include <QtDebug>\n\n#include <QtGui\/QMessageBox>\n#include <QtGui\/QDesktopServices>\n#include <QtCore\/QUrl>\n#include <QtGui\/QToolTip>\n\n#include \"qtxdg\/xdgicon.h\"\n#include \"mountbutton.h\"\n\n\nMountButton::MountButton(QWidget * parent, RazorPanel *panel)\n : QToolButton(parent),\n m_panel(panel)\n{\n if (!QDBusConnection::systemBus().isConnected())\n {\n qDebug() << \"Can't connect to dbus daemon. Some functions will be omited\";\n }\n\n setIcon(XdgIcon::fromTheme(\"emblem-mounted\"));\n\n \/\/ Display disk menu\n m_menu = new QMenu(this);\n QAction *empty_action = m_menu->addAction(tr(\"Empty\"));\n empty_action->setEnabled(false);\n \n\/\/ setMenu(m_menu);\n\n QDBusConnection conn = QDBusConnection::systemBus();\n \/\/ TODO: Check for connection, timer for reconect\n \/*bool connected =*\/ conn.connect(\"org.freedesktop.UDisks\",\n \"\/org\/freedesktop\/UDisks\",\n \"org.freedesktop.UDisks\",\n \"DeviceChanged\",\n this,\n SLOT(onDbusDeviceChangesMessage(QDBusObjectPath)));\n\n \/\/ Scan already connected devices\n initialScanDevices();\n\n connect(this, SIGNAL(clicked()), this, SLOT(showMenu()));\n\n connect(&_dm, SIGNAL(deviceConnected(DiskInfo)),\n this, SLOT(onDiskAdded(DiskInfo)));\n connect(&_dm, SIGNAL(deviceDisconnected(DiskInfo)),\n this, SLOT(onDiskRemoved(DiskInfo)));\n _dm.start();\n}\n\nMountButton::~MountButton()\n{\n _dm.exit(0);\n _dm.wait(1000);\n _dm.terminate();\n _dm.wait();\n}\n\nvoid MountButton::initialScanDevices()\n{\n QList<DiskInfo*> devices = _dm.scanDevices();\n for (int i = 0; i < devices.count(); i++)\n {\n DiskInfo *disk = devices.at(i);\n\n \/\/ add device\n _sm.addDevice(*disk);\n addMenuItem(*disk);\n\n StorageItem *sitem = _sm.getDevice(*disk);\n updateMenuItem(disk->device_name, disk->file_system_label, sitem->isMounted());\n\n \/\/ clear\n delete disk;\n }\n}\n\nvoid MountButton::addMenuItem(const DiskInfo &info)\n{\n MenuDiskItem *item = new MenuDiskItem(info, this);\n QWidgetAction *action = new QWidgetAction(this);\n action->setDefaultWidget(item);\n\n if (m_menu_items.count() == 0)\n {\n \/\/ Clear 'Empty' item\n m_menu->clear();\n m_menu->addAction(action);\n }\n else\n {\n \/\/ Insert on Top\n m_menu->insertAction(m_menu->actions().at(0), action);\n }\n\n m_menu_items.insert(info.device_name, action);\n\n \/\/ Connect signals\n connect(item, SIGNAL(mountMedia(const QString&)),\n this, SLOT(onMediaMount(const QString&)));\n\n connect(item, SIGNAL(ejectMedia(const QString&)),\n this, SLOT(onMediaEject(const QString&)));\n}\n\nvoid MountButton::removeMenuItem(const QString &device)\n{\n QWidgetAction *action = 0;\n if (m_menu_items.contains(device))\n {\n action = m_menu_items[device];\n m_menu->removeAction(action);\n m_menu_items.remove(device);\n delete action;\n }\n\n if (m_menu_items.count() == 0)\n {\n QAction *empty_action = m_menu->addAction(tr(\"Empty\"));\n empty_action->setEnabled(false);\n }\n}\n\nvoid MountButton::updateMenuItem(const QString &device, const QString &name, bool is_mounted)\n{\n QWidgetAction *action = 0;\n if (m_menu_items.contains(device))\n {\n action = m_menu_items[device];\n MenuDiskItem *item = static_cast<MenuDiskItem*>(action->defaultWidget());\n\n if (item == 0)\n {\n return;\n }\n\n if (!name.isEmpty())\n {\n item->setLabel(name);\n }\n\n item->setMountStatus(is_mounted);\n }\n}\n\nvoid MountButton::showMessage(const QString &text)\n{\n \/\/ TODO\/FIXME: messaging!\n \/\/_tray_icon.showMessage(\"MountTray\", text);\n qDebug() << \"MESSAGE\" << text;\n QToolTip::showText(mapToGlobal(pos()), text, this);\n}\n\nvoid MountButton::showError(const QString &text)\n{\n \/\/ TODO\/FIXME: messaging!\n\/\/ _tray_icon.showMessage(\"MountTray Error\", text, QSystemTrayIcon::Critical);\n qDebug() << \"ERRMSG\" << text;\n QToolTip::showText(mapToGlobal(pos()), QString(\"<b>Error:<\/b> %1\").arg(text), this);\n}\n\n\/**************************************************************************************************\/\n\/* Signals ---------------------------------------------------------------------------------------*\/\n\/**************************************************************************************************\/\n\nvoid MountButton::onDiskAdded(DiskInfo info)\n{\n _sm.addDevice(info);\n addMenuItem(info);\n showMessage(tr(\"Device connected: %1\").arg(info.device_name));\n}\n\nvoid MountButton::onDiskRemoved(DiskInfo info)\n{\n _sm.removeDevice(info);\n removeMenuItem(info.device_name);\n showMessage(tr(\"Device removed: %1\").arg(info.device_name));\n}\n\nvoid MountButton::onDbusDeviceChangesMessage(QDBusObjectPath device)\n{\n QString path = device.path();\n qDebug() << \"Changed: \" << qPrintable(path);\n\n QDBusInterface iface(\"org.freedesktop.UDisks\",\n path,\n \"org.freedesktop.UDisks.Device\",\n QDBusConnection::systemBus());\n\n \/\/qDebug() << \"Device name: \" << iface.property(\"DeviceFile\");\n \/\/qDebug() << \"Is mounted: \" << iface.property(\"DeviceIsMounted\");\n\n QString dev_name = iface.property(\"DeviceFile\").toString();\n bool is_mounted = iface.property(\"DeviceIsMounted\").toBool();\n\n StorageItem *item = _sm.getDevice(dev_name);\n if (item == NULL)\n {\n return;\n }\n\n bool old_state = item->isMounted();\n item->setMountStatus(is_mounted);\n updateMenuItem(dev_name, QString(), item->isMounted());\n\n if (item->isMounted() != old_state)\n {\n if (item->isMounted())\n {\n QString mount_point = item->getMountPoint();\n showMessage(tr(\"Device '%1' is mounted to %2\").arg(dev_name).arg(mount_point));\n }\n else\n {\n showMessage(tr(\"Device '%1' is unmounted\\nNow you can eject USB Flash or CD\/DVD Disk\").arg(dev_name));\n }\n }\n}\n\nvoid MountButton::onMediaMount(const QString &device)\n{\n qDebug() << \"Mount media: \" << qPrintable(device) << \"\\n\";\n m_menu->hide();\n\n StorageItem *item = _sm.getDevice(device);\n if (item == NULL)\n {\n return;\n }\n\n bool old_state = item->isMounted();\n QString status_text;\n if (!item->isMounted())\n {\n item->mount(status_text);\n }\n\n QString mount_point = item->getMountPoint();\n\n if (!item->isMounted())\n {\n \/\/ Error\n showError(tr(\"Can't mount device: %1\\n%2\").arg(device).arg(status_text));\n return;\n }\n\n if (item->isMounted() != old_state)\n {\n showMessage(tr(\"Device '%1' is mounted to %2\").arg(device).arg(mount_point));\n updateMenuItem(device, \"\", true);\n }\n\n \/\/ Run manager\n QDesktopServices::openUrl(QUrl(mount_point));\n\n}\n\nvoid MountButton::onMediaEject(const QString &device)\n{\n qDebug() << \"UnMount media: \" << qPrintable(device) << \"\\n\";\n m_menu->hide();\n\n StorageItem *item = _sm.getDevice(device);\n if (item == NULL)\n {\n return;\n }\n\n QString status_text;\n if (item->isMounted())\n {\n item->unmount(status_text);\n }\n\n if (item->isMounted())\n {\n \/\/ Error\n showError(tr(\"Can't unmount device: %1\\n%2\").arg(device).arg(status_text));\n return;\n }\n\n showMessage(tr(\"Device '%1' is unmounted\").arg(device));\n updateMenuItem(device, \"\", false);\n}\n\nvoid MountButton::showMenu()\n{\n \/\/ TODO\/FIXME: shared code with MainMenu plugin. How to share? Something like \"menubutton base class\"?\n int x, y;\n\n switch (m_panel->position())\n {\n case RazorPanel::PositionTop:\n x = mapToGlobal(QPoint(0, 0)).x();\n y = m_panel->mapToGlobal(QPoint(0, m_panel->sizeHint().height())).y();\n break;\n\n case RazorPanel::PositionBottom:\n x = mapToGlobal(QPoint(0, 0)).x();\n y = m_panel->mapToGlobal(QPoint(0, 0)).y() - m_menu->sizeHint().height();\n break;\n\n case RazorPanel::PositionLeft:\n x = m_panel->mapToGlobal(QPoint(m_panel->sizeHint().width(), 0)).x();\n y = mapToGlobal(QPoint(0, 0)).y();\n break;\n\n case RazorPanel::PositionRight:\n x = m_panel->mapToGlobal(QPoint(0, 0)).x() - m_menu->sizeHint().width();\n y = mapToGlobal(QPoint(0, 0)).y();\n break;\n\n }\n\n QPoint pos(x, y);\n m_menu->exec(pos);\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/==-- AArch64DeadRegisterDefinitions.cpp - Replace dead defs w\/ zero reg --==\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ When allowed by the instruction, replace a dead definition of a GPR with\n\/\/ the zero register. This makes the code a bit friendlier towards the\n\/\/ hardware's register renamer.\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"AArch64.h\"\n#include \"AArch64RegisterInfo.h\"\n#include \"llvm\/ADT\/Statistic.h\"\n#include \"llvm\/CodeGen\/MachineFunction.h\"\n#include \"llvm\/CodeGen\/MachineFunctionPass.h\"\n#include \"llvm\/CodeGen\/MachineInstr.h\"\n#include \"llvm\/Support\/Debug.h\"\n#include \"llvm\/Support\/raw_ostream.h\"\n#include \"llvm\/Target\/TargetSubtargetInfo.h\"\nusing namespace llvm;\n\n#define DEBUG_TYPE \"aarch64-dead-defs\"\n\nSTATISTIC(NumDeadDefsReplaced, \"Number of dead definitions replaced\");\n\n#define AARCH64_DEAD_REG_DEF_NAME \"AArch64 Dead register definitions\"\n\nnamespace {\nclass AArch64DeadRegisterDefinitions : public MachineFunctionPass {\nprivate:\n const TargetRegisterInfo *TRI;\n bool implicitlyDefinesOverlappingReg(unsigned Reg, const MachineInstr &MI);\n bool processMachineBasicBlock(MachineBasicBlock &MBB);\n bool usesFrameIndex(const MachineInstr &MI);\npublic:\n static char ID; \/\/ Pass identification, replacement for typeid.\n explicit AArch64DeadRegisterDefinitions() : MachineFunctionPass(ID) {\n initializeAArch64DeadRegisterDefinitionsPass(\n *PassRegistry::getPassRegistry());\n }\n\n bool runOnMachineFunction(MachineFunction &F) override;\n\n MachineFunctionProperties getRequiredProperties() const override {\n return MachineFunctionProperties().set(\n MachineFunctionProperties::Property::NoVRegs);\n }\n\n StringRef getPassName() const override { return AARCH64_DEAD_REG_DEF_NAME; }\n\n void getAnalysisUsage(AnalysisUsage &AU) const override {\n AU.setPreservesCFG();\n MachineFunctionPass::getAnalysisUsage(AU);\n }\n};\nchar AArch64DeadRegisterDefinitions::ID = 0;\n} \/\/ end anonymous namespace\n\nINITIALIZE_PASS(AArch64DeadRegisterDefinitions, \"aarch64-dead-defs\",\n AARCH64_DEAD_REG_DEF_NAME, false, false)\n\nbool AArch64DeadRegisterDefinitions::implicitlyDefinesOverlappingReg(\n unsigned Reg, const MachineInstr &MI) {\n for (const MachineOperand &MO : MI.implicit_operands())\n if (MO.isReg() && MO.isDef())\n if (TRI->regsOverlap(Reg, MO.getReg()))\n return true;\n return false;\n}\n\nbool AArch64DeadRegisterDefinitions::usesFrameIndex(const MachineInstr &MI) {\n for (const MachineOperand &Op : MI.uses())\n if (Op.isFI())\n return true;\n return false;\n}\n\nbool AArch64DeadRegisterDefinitions::processMachineBasicBlock(\n MachineBasicBlock &MBB) {\n bool Changed = false;\n for (MachineInstr &MI : MBB) {\n if (usesFrameIndex(MI)) {\n \/\/ We need to skip this instruction because while it appears to have a\n \/\/ dead def it uses a frame index which might expand into a multi\n \/\/ instruction sequence during EPI.\n DEBUG(dbgs() << \" Ignoring, operand is frame index\\n\");\n continue;\n }\n if (MI.definesRegister(AArch64::XZR) || MI.definesRegister(AArch64::WZR)) {\n \/\/ It is not allowed to write to the same register (not even the zero\n \/\/ register) twice in a single instruction.\n DEBUG(dbgs() << \" Ignoring, XZR or WZR already used by the instruction\\n\");\n continue;\n }\n for (int i = 0, e = MI.getDesc().getNumDefs(); i != e; ++i) {\n MachineOperand &MO = MI.getOperand(i);\n if (MO.isReg() && MO.isDead() && MO.isDef()) {\n assert(!MO.isImplicit() && \"Unexpected implicit def!\");\n DEBUG(dbgs() << \" Dead def operand #\" << i << \" in:\\n \";\n MI.print(dbgs()));\n \/\/ Be careful not to change the register if it's a tied operand.\n if (MI.isRegTiedToUseOperand(i)) {\n DEBUG(dbgs() << \" Ignoring, def is tied operand.\\n\");\n continue;\n }\n \/\/ Don't change the register if there's an implicit def of a subreg or\n \/\/ superreg.\n if (implicitlyDefinesOverlappingReg(MO.getReg(), MI)) {\n DEBUG(dbgs() << \" Ignoring, implicitly defines overlap reg.\\n\");\n continue;\n }\n \/\/ Make sure the instruction take a register class that contains\n \/\/ the zero register and replace it if so.\n unsigned NewReg;\n switch (MI.getDesc().OpInfo[i].RegClass) {\n default:\n DEBUG(dbgs() << \" Ignoring, register is not a GPR.\\n\");\n continue;\n case AArch64::GPR32RegClassID:\n NewReg = AArch64::WZR;\n break;\n case AArch64::GPR64RegClassID:\n NewReg = AArch64::XZR;\n break;\n }\n DEBUG(dbgs() << \" Replacing with zero register. New:\\n \");\n MO.setReg(NewReg);\n DEBUG(MI.print(dbgs()));\n ++NumDeadDefsReplaced;\n \/\/ Only replace one dead register, see check for zero register above.\n break;\n }\n }\n }\n return Changed;\n}\n\n\/\/ Scan the function for instructions that have a dead definition of a\n\/\/ register. Replace that register with the zero register when possible.\nbool AArch64DeadRegisterDefinitions::runOnMachineFunction(MachineFunction &MF) {\n TRI = MF.getSubtarget().getRegisterInfo();\n bool Changed = false;\n DEBUG(dbgs() << \"***** AArch64DeadRegisterDefinitions *****\\n\");\n\n if (skipFunction(*MF.getFunction()))\n return false;\n\n for (auto &MBB : MF)\n if (processMachineBasicBlock(MBB))\n Changed = true;\n return Changed;\n}\n\nFunctionPass *llvm::createAArch64DeadRegisterDefinitions() {\n return new AArch64DeadRegisterDefinitions();\n}\n<commit_msg>AArch64DeadRegisterDefinitionsPass: Cleanup; NFC<commit_after>\/\/==-- AArch64DeadRegisterDefinitions.cpp - Replace dead defs w\/ zero reg --==\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\/ \\file When allowed by the instruction, replace a dead definition of a GPR\n\/\/\/ with the zero register. This makes the code a bit friendlier towards the\n\/\/\/ hardware's register renamer.\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"AArch64.h\"\n#include \"AArch64RegisterInfo.h\"\n#include \"llvm\/ADT\/Statistic.h\"\n#include \"llvm\/CodeGen\/MachineFunction.h\"\n#include \"llvm\/CodeGen\/MachineFunctionPass.h\"\n#include \"llvm\/CodeGen\/MachineInstr.h\"\n#include \"llvm\/Support\/Debug.h\"\n#include \"llvm\/Support\/raw_ostream.h\"\n#include \"llvm\/Target\/TargetSubtargetInfo.h\"\nusing namespace llvm;\n\n#define DEBUG_TYPE \"aarch64-dead-defs\"\n\nSTATISTIC(NumDeadDefsReplaced, \"Number of dead definitions replaced\");\n\n#define AARCH64_DEAD_REG_DEF_NAME \"AArch64 Dead register definitions\"\n\nnamespace {\nclass AArch64DeadRegisterDefinitions : public MachineFunctionPass {\nprivate:\n const TargetRegisterInfo *TRI;\n bool Changed;\n bool implicitlyDefinesOverlappingReg(unsigned Reg, const MachineInstr &MI);\n void processMachineBasicBlock(MachineBasicBlock &MBB);\npublic:\n static char ID; \/\/ Pass identification, replacement for typeid.\n AArch64DeadRegisterDefinitions() : MachineFunctionPass(ID) {\n initializeAArch64DeadRegisterDefinitionsPass(\n *PassRegistry::getPassRegistry());\n }\n\n bool runOnMachineFunction(MachineFunction &F) override;\n\n MachineFunctionProperties getRequiredProperties() const override {\n return MachineFunctionProperties().set(\n MachineFunctionProperties::Property::NoVRegs);\n }\n\n StringRef getPassName() const override { return AARCH64_DEAD_REG_DEF_NAME; }\n\n void getAnalysisUsage(AnalysisUsage &AU) const override {\n AU.setPreservesCFG();\n MachineFunctionPass::getAnalysisUsage(AU);\n }\n};\nchar AArch64DeadRegisterDefinitions::ID = 0;\n} \/\/ end anonymous namespace\n\nINITIALIZE_PASS(AArch64DeadRegisterDefinitions, \"aarch64-dead-defs\",\n AARCH64_DEAD_REG_DEF_NAME, false, false)\n\nbool AArch64DeadRegisterDefinitions::implicitlyDefinesOverlappingReg(\n unsigned Reg, const MachineInstr &MI) {\n for (const MachineOperand &MO : MI.implicit_operands())\n if (MO.isReg() && MO.isDef())\n if (TRI->regsOverlap(Reg, MO.getReg()))\n return true;\n return false;\n}\n\nstatic bool usesFrameIndex(const MachineInstr &MI) {\n for (const MachineOperand &MO : MI.uses())\n if (MO.isFI())\n return true;\n return false;\n}\n\nvoid AArch64DeadRegisterDefinitions::processMachineBasicBlock(\n MachineBasicBlock &MBB) {\n for (MachineInstr &MI : MBB) {\n if (usesFrameIndex(MI)) {\n \/\/ We need to skip this instruction because while it appears to have a\n \/\/ dead def it uses a frame index which might expand into a multi\n \/\/ instruction sequence during EPI.\n DEBUG(dbgs() << \" Ignoring, operand is frame index\\n\");\n continue;\n }\n if (MI.definesRegister(AArch64::XZR) || MI.definesRegister(AArch64::WZR)) {\n \/\/ It is not allowed to write to the same register (not even the zero\n \/\/ register) twice in a single instruction.\n DEBUG(dbgs() << \" Ignoring, XZR or WZR already used by the instruction\\n\");\n continue;\n }\n const MCInstrDesc &Desc = MI.getDesc();\n for (int I = 0, E = Desc.getNumDefs(); I != E; ++I) {\n MachineOperand &MO = MI.getOperand(I);\n if (!MO.isReg() || !MO.isDead() || !MO.isDef())\n continue;\n assert(!MO.isImplicit() && \"Unexpected implicit def!\");\n DEBUG(dbgs() << \" Dead def operand #\" << I << \" in:\\n \";\n MI.print(dbgs()));\n \/\/ Be careful not to change the register if it's a tied operand.\n if (MI.isRegTiedToUseOperand(I)) {\n DEBUG(dbgs() << \" Ignoring, def is tied operand.\\n\");\n continue;\n }\n \/\/ Don't change the register if there's an implicit def of a subreg or\n \/\/ superreg.\n if (implicitlyDefinesOverlappingReg(MO.getReg(), MI)) {\n DEBUG(dbgs() << \" Ignoring, implicitly defines overlap reg.\\n\");\n continue;\n }\n \/\/ Make sure the instruction take a register class that contains\n \/\/ the zero register and replace it if so.\n unsigned NewReg;\n switch (Desc.OpInfo[I].RegClass) {\n default:\n DEBUG(dbgs() << \" Ignoring, register is not a GPR.\\n\");\n continue;\n case AArch64::GPR32RegClassID:\n NewReg = AArch64::WZR;\n break;\n case AArch64::GPR64RegClassID:\n NewReg = AArch64::XZR;\n break;\n }\n DEBUG(dbgs() << \" Replacing with zero register. New:\\n \");\n MO.setReg(NewReg);\n DEBUG(MI.print(dbgs()));\n ++NumDeadDefsReplaced;\n Changed = true;\n \/\/ Only replace one dead register, see check for zero register above.\n break;\n }\n }\n}\n\n\/\/ Scan the function for instructions that have a dead definition of a\n\/\/ register. Replace that register with the zero register when possible.\nbool AArch64DeadRegisterDefinitions::runOnMachineFunction(MachineFunction &MF) {\n if (skipFunction(*MF.getFunction()))\n return false;\n\n TRI = MF.getSubtarget().getRegisterInfo();\n bool Changed = false;\n DEBUG(dbgs() << \"***** AArch64DeadRegisterDefinitions *****\\n\");\n Changed = false;\n for (auto &MBB : MF)\n processMachineBasicBlock(MBB);\n return Changed;\n}\n\nFunctionPass *llvm::createAArch64DeadRegisterDefinitions() {\n return new AArch64DeadRegisterDefinitions();\n}\n<|endoftext|>"} {"text":"<commit_before>\/*-----------------------------------------------------------------------------\n\n Copyright 2017 Hopsan Group\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n\n\n The full license is available in the file LICENSE.\n For details about the 'Hopsan Group' or information about Authors and\n Contributors see the HOPSANGROUP and AUTHORS files that are located in\n the Hopsan source code root directory.\n\n-----------------------------------------------------------------------------*\/\n\n\/\/$Id$\n\n#include \"Quantities.h\"\n\n\nhopsan::QuantityRegister::QuantityRegister()\n{\n registerQuantity(\"Pressure\", \"Pa\");\n registerQuantityAlias(\"Pressure\", \"Stress\");\n registerQuantity(\"Flow\", \"m^3\/s\");\n\n registerQuantity(\"Force\", \"N\");\n registerQuantity(\"Position\", \"m\");\n registerQuantity(\"Velocity\", \"m\/s\");\n registerQuantity(\"Acceleration\", \"m\/(s^2)\");\n\n registerQuantity(\"Torque\", \"Nm\");\n registerQuantity(\"Angle\", \"rad\");\n registerQuantity(\"AngularVelocity\", \"rad\/s\");\n\n registerQuantity(\"Voltage\", \"V\");\n registerQuantity(\"Current\", \"A\");\n\n registerQuantity(\"Momentum\", \"kg m\/s\");\n registerQuantity(\"Energy\", \"J\");\n registerQuantity(\"Power\", \"J\/s\");\n\n registerQuantity(\"Mass\", \"kg\");\n registerQuantity(\"Area\", \"m^2\");\n registerQuantity(\"Volume\", \"m^3\");\n registerQuantity(\"Displacement\", \"m^3\/rev\");\n\n registerQuantity(\"Density\", \"kg\/m^3\");\n\n registerQuantity(\"Frequency\", \"rad\/s\");\n registerQuantity(\"Time\", \"s\");\n\n registerQuantity(\"Temperature\", \"K\");\n\n registerQuantity(\"Resistance\", \"ohm\");\n\n \/\/ This is a fake quantity for scaling between absolute and dB values\n registerQuantity(\"Magnitude\", \"\");\n\n \/\/ Register quantity aliases\n registerQuantityAlias(\"Position\", \"Length\");\n}\n\nvoid hopsan::QuantityRegister::registerQuantity(const hopsan::HString &rQuantity, const hopsan::HString &rBaseUnit)\n{\n mQuantity2BaseUnit.insert(std::pair<HString, HString>(rQuantity, rBaseUnit));\n}\n\nvoid hopsan::QuantityRegister::registerQuantityAlias(const hopsan::HString &rQuantity, const hopsan::HString &rAlias)\n{\n mQuantityAliases.insert(std::pair<HString, HString>(rAlias, rQuantity));\n}\n\nhopsan::HString hopsan::QuantityRegister::lookupBaseUnit(const hopsan::HString &rQuantity) const\n{\n \/\/ First check if alias, then lookup actual quantity\n std::map<HString, HString>::const_iterator it = mQuantityAliases.find(rQuantity);\n if (it != mQuantityAliases.end())\n {\n it = mQuantity2BaseUnit.find(it->second);\n }\n \/\/ else lookup directly\n else\n {\n it = mQuantity2BaseUnit.find(rQuantity);\n }\n \/\/ If quantity registered, then return its base unit\n if (it != mQuantity2BaseUnit.end())\n {\n return it->second;\n }\n \/\/ else return empty string\n return HString();\n}\n\nbool hopsan::QuantityRegister::haveQuantity(const hopsan::HString &rQuantity) const\n{\n \/\/ First check if alias, then lookup actual quantity\n std::map<HString, HString>::const_iterator it = mQuantityAliases.find(rQuantity);\n if (it != mQuantityAliases.end())\n {\n it = mQuantity2BaseUnit.find(it->second);\n }\n \/\/ else lookup directly\n else\n {\n it = mQuantity2BaseUnit.find(rQuantity);\n }\n return (it != mQuantity2BaseUnit.end());\n}\n\n\/\/! @brief Lookup a quantity base unit, or return as a unit if not a valid quantity is given\n\/\/! @param[in] rQuantityOrUnit The name of the quantity (or unit)\n\/\/! @param[out] rQuantity The quantity, empty if rQuantityOrUnit is not a valid quantity\n\/\/! @param[out] rUnitOrBaseUnit The base unit for the given quantity, or the value of rQuantityOrUnit if it is not a valid quantity\n\/\/! @returns true if rQuantityOrUnit is a valid quantity else false\nbool hopsan::checkIfQuantityOrUnit(const hopsan::HString &rQuantityOrUnit, hopsan::HString &rQuantity, hopsan::HString &rUnitOrBaseUnit)\n{\n rUnitOrBaseUnit = gpInternalCoreQuantityRegister->lookupBaseUnit(rQuantityOrUnit);\n \/\/ rUnitOrQuantity is treated as a unit because no valid quantity has been specified\n if (rUnitOrBaseUnit.empty())\n {\n rQuantity.clear();\n rUnitOrBaseUnit = rQuantityOrUnit;\n return false;\n }\n \/\/ rUnitOrQuantity is actually a quantity, and bu is the corresponding base unit\n else\n {\n rQuantity = rQuantityOrUnit;\n return true;\n }\n}\n<commit_msg>Add \"Altitude\" as alias for \"Position\" in Quantities.cpp<commit_after>\/*-----------------------------------------------------------------------------\n\n Copyright 2017 Hopsan Group\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n\n\n The full license is available in the file LICENSE.\n For details about the 'Hopsan Group' or information about Authors and\n Contributors see the HOPSANGROUP and AUTHORS files that are located in\n the Hopsan source code root directory.\n\n-----------------------------------------------------------------------------*\/\n\n\/\/$Id$\n\n#include \"Quantities.h\"\n\n\nhopsan::QuantityRegister::QuantityRegister()\n{\n registerQuantity(\"Pressure\", \"Pa\");\n registerQuantityAlias(\"Pressure\", \"Stress\");\n registerQuantity(\"Flow\", \"m^3\/s\");\n\n registerQuantity(\"Force\", \"N\");\n registerQuantity(\"Position\", \"m\");\n registerQuantity(\"Velocity\", \"m\/s\");\n registerQuantity(\"Acceleration\", \"m\/(s^2)\");\n\n registerQuantity(\"Torque\", \"Nm\");\n registerQuantity(\"Angle\", \"rad\");\n registerQuantity(\"AngularVelocity\", \"rad\/s\");\n\n registerQuantity(\"Voltage\", \"V\");\n registerQuantity(\"Current\", \"A\");\n\n registerQuantity(\"Momentum\", \"kg m\/s\");\n registerQuantity(\"Energy\", \"J\");\n registerQuantity(\"Power\", \"J\/s\");\n\n registerQuantity(\"Mass\", \"kg\");\n registerQuantity(\"Area\", \"m^2\");\n registerQuantity(\"Volume\", \"m^3\");\n registerQuantity(\"Displacement\", \"m^3\/rev\");\n\n registerQuantity(\"Density\", \"kg\/m^3\");\n\n registerQuantity(\"Frequency\", \"rad\/s\");\n registerQuantity(\"Time\", \"s\");\n\n registerQuantity(\"Temperature\", \"K\");\n\n registerQuantity(\"Resistance\", \"ohm\");\n\n \/\/ This is a fake quantity for scaling between absolute and dB values\n registerQuantity(\"Magnitude\", \"\");\n\n \/\/ Register quantity aliases\n registerQuantityAlias(\"Position\", \"Length\");\n registerQuantityAlias(\"Position\", \"Altitude\");\n}\n\nvoid hopsan::QuantityRegister::registerQuantity(const hopsan::HString &rQuantity, const hopsan::HString &rBaseUnit)\n{\n mQuantity2BaseUnit.insert(std::pair<HString, HString>(rQuantity, rBaseUnit));\n}\n\nvoid hopsan::QuantityRegister::registerQuantityAlias(const hopsan::HString &rQuantity, const hopsan::HString &rAlias)\n{\n mQuantityAliases.insert(std::pair<HString, HString>(rAlias, rQuantity));\n}\n\nhopsan::HString hopsan::QuantityRegister::lookupBaseUnit(const hopsan::HString &rQuantity) const\n{\n \/\/ First check if alias, then lookup actual quantity\n std::map<HString, HString>::const_iterator it = mQuantityAliases.find(rQuantity);\n if (it != mQuantityAliases.end())\n {\n it = mQuantity2BaseUnit.find(it->second);\n }\n \/\/ else lookup directly\n else\n {\n it = mQuantity2BaseUnit.find(rQuantity);\n }\n \/\/ If quantity registered, then return its base unit\n if (it != mQuantity2BaseUnit.end())\n {\n return it->second;\n }\n \/\/ else return empty string\n return HString();\n}\n\nbool hopsan::QuantityRegister::haveQuantity(const hopsan::HString &rQuantity) const\n{\n \/\/ First check if alias, then lookup actual quantity\n std::map<HString, HString>::const_iterator it = mQuantityAliases.find(rQuantity);\n if (it != mQuantityAliases.end())\n {\n it = mQuantity2BaseUnit.find(it->second);\n }\n \/\/ else lookup directly\n else\n {\n it = mQuantity2BaseUnit.find(rQuantity);\n }\n return (it != mQuantity2BaseUnit.end());\n}\n\n\/\/! @brief Lookup a quantity base unit, or return as a unit if not a valid quantity is given\n\/\/! @param[in] rQuantityOrUnit The name of the quantity (or unit)\n\/\/! @param[out] rQuantity The quantity, empty if rQuantityOrUnit is not a valid quantity\n\/\/! @param[out] rUnitOrBaseUnit The base unit for the given quantity, or the value of rQuantityOrUnit if it is not a valid quantity\n\/\/! @returns true if rQuantityOrUnit is a valid quantity else false\nbool hopsan::checkIfQuantityOrUnit(const hopsan::HString &rQuantityOrUnit, hopsan::HString &rQuantity, hopsan::HString &rUnitOrBaseUnit)\n{\n rUnitOrBaseUnit = gpInternalCoreQuantityRegister->lookupBaseUnit(rQuantityOrUnit);\n \/\/ rUnitOrQuantity is treated as a unit because no valid quantity has been specified\n if (rUnitOrBaseUnit.empty())\n {\n rQuantity.clear();\n rUnitOrBaseUnit = rQuantityOrUnit;\n return false;\n }\n \/\/ rUnitOrQuantity is actually a quantity, and bu is the corresponding base unit\n else\n {\n rQuantity = rQuantityOrUnit;\n return true;\n }\n}\n<|endoftext|>"} {"text":"<commit_before>#include <cctype>\n\n#include <libport\/lexical-cast.hh>\n\n#include <object\/format-info.hh>\n#include <object\/symbols.hh>\n\nnamespace object\n{\n FormatInfo::FormatInfo()\n : alignment_(Align::RIGHT)\n , alt_(false)\n , case_(Case::UNDEFINED)\n , group_(0)\n , pad_(' ')\n , pattern_(\"%s\")\n , precision_(6)\n , prefix_(0)\n , spec_('s')\n , width_(0)\n {\n proto_add(proto ? proto : Object::proto);\n }\n\n FormatInfo::FormatInfo(rFormatInfo model)\n : alignment_(model->alignment_)\n , alt_(model->alt_)\n , case_(model->case_)\n , group_(model->group_)\n , pad_(model->pad_)\n , pattern_(model->pattern_)\n , precision_(model->precision_)\n , prefix_(model->prefix_)\n , spec_(model->spec_)\n , width_(model->width_)\n {\n proto_add(model);\n }\n\n void\n FormatInfo::init(const std::string& pattern)\n {\n size_t cursor = 0;\n bool piped;\n\n if (pattern.empty())\n RAISE(\"format: pattern is empty\");\n if (pattern[0] != '%')\n RAISE(\"format: pattern \\\"\" + pattern + \"\\\" doesn't begin with %\");\n if (pattern.size() == 1)\n RAISE(\"format: trailing `%'\");\n if ((piped = pattern[1] == '|'))\n {\n size_t pos = pattern.find_first_of('|', 2);\n if (pos == pattern.npos)\n RAISE(\"format: format begins with '|' but \"\n \"does not end with '|'\");\n pattern_ = pattern.substr(0, pos + 1);\n cursor++;\n }\n\n \/\/ Parsing flags.\n std::string flags(\"-=+#0 '\");\n std::string excludes(\"\");\n char current;\n while ((pattern.size() > ++cursor)\n && flags.npos != flags.find(current = pattern[cursor]))\n {\n\/\/ FIXME:\n\/\/ if (excludes.npos != excludes.find(current))\n\/\/ WARNING;\n switch (current)\n {\n case '-': alignment_ = Align::LEFT; excludes += \"-=\"; break;\n case '=': alignment_ = Align::CENTER; excludes += \"-=\"; break;\n case '+': prefix_ = '+'; excludes + \" +\"; break;\n case ' ': prefix_ = ' '; excludes + \" +\"; break;\n case '0': pad_ = '0'; break;\n case '#': alt_ = true; break;\n case '\\'': group_ = ' '; break;\n };\n }\n\n \/\/ Parsing width.\n std::string substr_ =\n pattern.substr(cursor,\n pattern.find_first_not_of(\"0123456789\",\n cursor) - cursor);\n if (substr_.size())\n {\n width_ = lexical_cast<size_t>(substr_);\n cursor += substr_.size();\n }\n\n \/\/ Parsing precision.\n if (pattern.size() > cursor && pattern[cursor] == '.' && cursor++)\n {\n substr_ =\n pattern.substr(cursor, pattern.find_first_not_of(\"0123456789\",\n cursor) - cursor);\n if (substr_.size())\n {\n precision_ = lexical_cast<unsigned int>(substr_);\n cursor += substr_.size();\n }\n else\n runner::raise_primitive_error(std::string(\"format: Unexpected \\\"\")\n + pattern[cursor]\n + \"\\\", expected width ([1-9][0-9]*).\");\n }\n\n \/\/ Parsing spec.\n if ((piped && cursor < pattern_.size() - 1)\n || (!piped && cursor < pattern.size()))\n {\n spec_ = tolower(current = pattern[cursor]);\n substr_ = \"sdbxoefgEGDX\";\n if (substr_.find(spec_) != substr_.npos)\n {\n if (spec_ != 's')\n case_ = (islower(pattern[cursor])) ? Case::LOWER : Case::UPPER;\n }\n else\n runner::raise_primitive_error\n (std::string(\"format: \\\"\") + spec_\n + \"\\\" is not a valid conversion type character\");\n }\n\n int overflow;\n if (!piped)\n pattern_ = pattern.substr(0, ++cursor);\n else if (0 < (overflow = pattern_.size() - 1 - ++cursor))\n RAISE(\"format: format is between pipes and \\\"\"\n + pattern_.substr(cursor, overflow)\n + \"\\\" are too many characters\");\n }\n\n std::string\n FormatInfo::as_string() const\n {\n return pattern_;\n }\n\n void\n FormatInfo::initialize(CxxObject::Binder<FormatInfo>& bind)\n {\n bind(SYMBOL(init), &FormatInfo::init);\n bind(SYMBOL(asString), &FormatInfo::as_string);\n bind(SYMBOL(width), &FormatInfo::width_get);\n bind(SYMBOL(precision), &FormatInfo::precision_get);\n bind(SYMBOL(alt), &FormatInfo::alt_get);\n bind(SYMBOL(prefix), &FormatInfo::prefix_get);\n bind(SYMBOL(alignment), &FormatInfo::alignment_get);\n bind(SYMBOL(uppercase), &FormatInfo::case_get);\n bind(SYMBOL(group), &FormatInfo::group_get);\n bind(SYMBOL(pad), &FormatInfo::pad_get);\n bind(SYMBOL(spec), &FormatInfo::spec_get);\n bind(SYMBOL(pattern), &FormatInfo::pattern_get);\n }\n\n rObject\n FormatInfo::proto_make()\n {\n return new FormatInfo();\n }\n\n URBI_CXX_OBJECT_REGISTER(FormatInfo);\n} \/\/ namespace object\n<commit_msg>format-info: style changes.<commit_after>#include <cctype>\n\n#include <libport\/lexical-cast.hh>\n\n#include <object\/format-info.hh>\n#include <object\/symbols.hh>\n\nnamespace object\n{\n FormatInfo::FormatInfo()\n : alignment_(Align::RIGHT)\n , alt_(false)\n , case_(Case::UNDEFINED)\n , group_(0)\n , pad_(' ')\n , pattern_(\"%s\")\n , precision_(6)\n , prefix_(0)\n , spec_('s')\n , width_(0)\n {\n proto_add(proto ? proto : Object::proto);\n }\n\n FormatInfo::FormatInfo(rFormatInfo model)\n : alignment_(model->alignment_)\n , alt_(model->alt_)\n , case_(model->case_)\n , group_(model->group_)\n , pad_(model->pad_)\n , pattern_(model->pattern_)\n , precision_(model->precision_)\n , prefix_(model->prefix_)\n , spec_(model->spec_)\n , width_(model->width_)\n {\n proto_add(model);\n }\n\n void\n FormatInfo::init(const std::string& pattern)\n {\n size_t cursor = 0;\n bool piped;\n\n if (pattern.empty())\n RAISE(\"format: pattern is empty\");\n if (pattern[0] != '%')\n RAISE(\"format: pattern \\\"\" + pattern + \"\\\" doesn't begin with %\");\n if (pattern.size() == 1)\n RAISE(\"format: trailing `%'\");\n if ((piped = pattern[1] == '|'))\n {\n size_t pos = pattern.find_first_of('|', 2);\n if (pos == pattern.npos)\n RAISE(\"format: format begins with '|' but \"\n \"does not end with '|'\");\n pattern_ = pattern.substr(0, pos + 1);\n cursor++;\n }\n\n \/\/ Parsing flags.\n std::string flags(\"-=+#0 '\");\n std::string excludes(\"\");\n char current;\n while ((pattern.size() > ++cursor)\n && flags.npos != flags.find(current = pattern[cursor]))\n {\n\/\/ FIXME:\n\/\/ if (excludes.npos != excludes.find(current))\n\/\/ WARNING;\n switch (current)\n {\n case '-': alignment_ = Align::LEFT; excludes += \"-=\"; break;\n case '=': alignment_ = Align::CENTER; excludes += \"-=\"; break;\n case '+': prefix_ = '+'; excludes += \" +\"; break;\n case ' ': prefix_ = ' '; excludes += \" +\"; break;\n case '0': pad_ = '0'; break;\n case '#': alt_ = true; break;\n case '\\'': group_ = ' '; break;\n };\n }\n\n \/\/ Parsing width.\n std::string substr_ =\n pattern.substr(cursor,\n pattern.find_first_not_of(\"0123456789\",\n cursor) - cursor);\n if (substr_.size())\n {\n width_ = lexical_cast<size_t>(substr_);\n cursor += substr_.size();\n }\n\n \/\/ Parsing precision.\n if (pattern.size() > cursor && pattern[cursor] == '.' && cursor++)\n {\n substr_ =\n pattern.substr(cursor, pattern.find_first_not_of(\"0123456789\",\n cursor) - cursor);\n if (substr_.size())\n {\n precision_ = lexical_cast<unsigned int>(substr_);\n cursor += substr_.size();\n }\n else\n runner::raise_primitive_error(std::string(\"format: Unexpected \\\"\")\n + pattern[cursor]\n + \"\\\", expected width ([1-9][0-9]*).\");\n }\n\n \/\/ Parsing spec.\n if ((piped && cursor < pattern_.size() - 1)\n || (!piped && cursor < pattern.size()))\n {\n spec_ = tolower(current = pattern[cursor]);\n substr_ = \"sdbxoefgEGDX\";\n if (substr_.find(spec_) != substr_.npos)\n {\n if (spec_ != 's')\n case_ = (islower(pattern[cursor])) ? Case::LOWER : Case::UPPER;\n }\n else\n runner::raise_primitive_error\n (std::string(\"format: \\\"\") + spec_\n + \"\\\" is not a valid conversion type character\");\n }\n\n int overflow;\n if (!piped)\n pattern_ = pattern.substr(0, ++cursor);\n else if (0 < (overflow = pattern_.size() - 1 - ++cursor))\n RAISE(\"format: format is between pipes and \\\"\"\n + pattern_.substr(cursor, overflow)\n + \"\\\" are too many characters\");\n }\n\n std::string\n FormatInfo::as_string() const\n {\n return pattern_;\n }\n\n void\n FormatInfo::initialize(CxxObject::Binder<FormatInfo>& bind)\n {\n bind(SYMBOL(init), &FormatInfo::init);\n bind(SYMBOL(asString), &FormatInfo::as_string);\n bind(SYMBOL(width), &FormatInfo::width_get);\n bind(SYMBOL(precision), &FormatInfo::precision_get);\n bind(SYMBOL(alt), &FormatInfo::alt_get);\n bind(SYMBOL(prefix), &FormatInfo::prefix_get);\n bind(SYMBOL(alignment), &FormatInfo::alignment_get);\n bind(SYMBOL(uppercase), &FormatInfo::case_get);\n bind(SYMBOL(group), &FormatInfo::group_get);\n bind(SYMBOL(pad), &FormatInfo::pad_get);\n bind(SYMBOL(spec), &FormatInfo::spec_get);\n bind(SYMBOL(pattern), &FormatInfo::pattern_get);\n }\n\n rObject\n FormatInfo::proto_make()\n {\n return new FormatInfo();\n }\n\n URBI_CXX_OBJECT_REGISTER(FormatInfo);\n} \/\/ namespace object\n<|endoftext|>"} {"text":"<commit_before>#include <libport\/containers.hh>\n\n#include <object\/object.hh>\n\nnamespace object\n{\n bool HashSlots::set(const key_type& key, value_type v)\n {\n std::pair<iterator, bool> where = content_.insert(std::make_pair(key, v));\n if (!where.second)\n return false;\n return true;\n }\n\n void HashSlots::update(const key_type& key, value_type v)\n {\n content_[key] = v;\n }\n\n HashSlots::value_type HashSlots::get(const key_type& key) const\n {\n const_iterator where = content_.find(key);\n if (where == content_.end())\n return 0;\n return where->second;\n }\n\n void HashSlots::erase(const key_type& key)\n {\n content_.erase(key);\n }\n\n bool HashSlots::has(const key_type& key) const\n {\n return libport::mhas(content_, key);\n }\n\n inline HashSlots::iterator\n HashSlots::begin()\n {\n return content_.begin();\n }\n\n inline HashSlots::iterator\n HashSlots::end()\n {\n return content_.end();\n }\n\n inline HashSlots::const_iterator\n HashSlots::begin() const\n {\n return content_.begin();\n }\n\n inline HashSlots::const_iterator\n HashSlots::end() const\n {\n return content_.end();\n }\n}\n<commit_msg>Formatting change.<commit_after>#include <libport\/containers.hh>\n\n#include <object\/object.hh>\n\nnamespace object\n{\n inline bool\n HashSlots::set(const key_type& key, value_type v)\n {\n std::pair<iterator, bool> where = content_.insert(std::make_pair(key, v));\n if (!where.second)\n return false;\n return true;\n }\n\n inline void\n HashSlots::update(const key_type& key, value_type v)\n {\n content_[key] = v;\n }\n\n inline HashSlots::value_type\n HashSlots::get(const key_type& key) const\n {\n const_iterator where = content_.find(key);\n if (where == content_.end())\n return 0;\n return where->second;\n }\n\n inline void\n HashSlots::erase(const key_type& key)\n {\n content_.erase(key);\n }\n\n inline bool\n HashSlots::has(const key_type& key) const\n {\n return libport::mhas(content_, key);\n }\n\n inline HashSlots::iterator\n HashSlots::begin()\n {\n return content_.begin();\n }\n\n inline HashSlots::iterator\n HashSlots::end()\n {\n return content_.end();\n }\n\n inline HashSlots::const_iterator\n HashSlots::begin() const\n {\n return content_.begin();\n }\n\n inline HashSlots::const_iterator\n HashSlots::end() const\n {\n return content_.end();\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/* IBM_PROLOG_BEGIN_TAG *\/\n\/* This is an automatically generated prolog. *\/\n\/* *\/\n\/* $Source: src\/import\/chips\/p9\/procedures\/hwp\/pm\/p9_pm_get_poundv_bucket_attr.C $ *\/\n\/* *\/\n\/* OpenPOWER HostBoot Project *\/\n\/* *\/\n\/* Contributors Listed Below - COPYRIGHT 2015,2019 *\/\n\/* [+] International Business Machines Corp. *\/\n\/* *\/\n\/* *\/\n\/* Licensed under the Apache License, Version 2.0 (the \"License\"); *\/\n\/* you may not use this file except in compliance with the License. *\/\n\/* You may obtain a copy of the License at *\/\n\/* *\/\n\/* http:\/\/www.apache.org\/licenses\/LICENSE-2.0 *\/\n\/* *\/\n\/* Unless required by applicable law or agreed to in writing, software *\/\n\/* distributed under the License is distributed on an \"AS IS\" BASIS, *\/\n\/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or *\/\n\/* implied. See the License for the specific language governing *\/\n\/* permissions and limitations under the License. *\/\n\/* *\/\n\/* IBM_PROLOG_END_TAG *\/\n\/\/\/\n\/\/\/ @file p9_pm_get_poundv_bucket_attr.C\n\/\/\/ @brief Grab PM data from certain bucket in #V keyword in LRPX record\n\/\/\/\n\n\/\/ ----------------------------------------------------------------------\n\/\/ Includes\n\/\/ ----------------------------------------------------------------------\n#include <p9_pm_get_poundv_bucket_attr.H>\n#include <mvpd_access_defs.H>\n#include <attribute_ids.H>\n\nfapi2::ReturnCode p9_pm_get_poundv_bucket_attr(\n const fapi2::Target<fapi2::TARGET_TYPE_EQ>& i_target,\n uint8_t* o_data)\n{\n FAPI_IMP(\"Entering p9_pm_get_poundv_bucket_attr ....\");\n uint8_t* l_prDataPtr = NULL;\n uint8_t* l_fullVpdData = NULL;\n uint8_t l_overridePresent = 0;\n uint32_t l_vpdSize = 0;\n uint8_t l_eqChipUnitPos = 0;\n uint8_t l_bucketId;\n fapi2::ReturnCode l_rc = fapi2::FAPI2_RC_SUCCESS;\n\n do\n {\n \/\/To read MVPD we will need the proc parent of the inputted EQ target\n fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP> l_procParent =\n i_target.getParent<fapi2::TARGET_TYPE_PROC_CHIP>();\n\n \/\/check if bucket num has been overriden\n FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_POUNDV_BUCKET_NUM_OVERRIDE,\n i_target,\n l_overridePresent));\n\n if(l_overridePresent != 0)\n {\n \/\/If it has been overriden then get the override\n FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_POUNDV_BUCKET_NUM,\n i_target,\n l_bucketId));\n }\n else\n {\n \/\/Otherwise get the bucket num from MVPD data\n \/\/First read is to get size of vpd record, note the o_buffer is NULL\n l_rc = getMvpdField(fapi2::MVPD_RECORD_VINI,\n fapi2::MVPD_KEYWORD_PR,\n l_procParent,\n NULL,\n l_vpdSize);\n\n if(l_rc)\n {\n FAPI_ERR(\"p9_pm_get_poundv_bucket_attr:: Error reading PR keyword size from VINI record\");\n break;\n }\n\n l_prDataPtr = reinterpret_cast<uint8_t*>(malloc(l_vpdSize));\n\n \/\/Second read is to get data of vpd record\n l_rc = getMvpdField(fapi2::MVPD_RECORD_VINI,\n fapi2::MVPD_KEYWORD_PR,\n l_procParent,\n l_prDataPtr,\n l_vpdSize);\n\n if(l_rc)\n {\n FAPI_ERR(\"p9_pm_get_poundv_bucket_attr:: Error reading PR keyword from VINI record\");\n break;\n }\n\n \/\/Bucket ID is byte[4] of the PR keyword\n memcpy(&l_bucketId, (l_prDataPtr + 4), sizeof(uint8_t));\n }\n\n\n \/\/Need to determine which LRP record to read from depending on which\n \/\/bucket we are getting the power management data from. FapiPos will\n \/\/tell us which LRP record to use.\n FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_CHIP_UNIT_POS,\n i_target,\n l_eqChipUnitPos));\n fapi2::MvpdRecord lprRecord = fapi2::MVPD_RECORD_LRP0;\n\n switch(l_eqChipUnitPos)\n {\n case 0:\n lprRecord = fapi2::MVPD_RECORD_LRP0;\n break;\n\n case 1:\n lprRecord = fapi2::MVPD_RECORD_LRP1;\n break;\n\n case 2:\n lprRecord = fapi2::MVPD_RECORD_LRP2;\n break;\n\n case 3:\n lprRecord = fapi2::MVPD_RECORD_LRP3;\n break;\n\n case 4:\n lprRecord = fapi2::MVPD_RECORD_LRP4;\n break;\n\n case 5:\n lprRecord = fapi2::MVPD_RECORD_LRP5;\n break;\n\n default:\n FAPI_ERR(\"No LRP record found for EQ with fapi pos = %d\", l_eqChipUnitPos);\n fapi2::Assert(0);\n break;\n }\n\n \/\/Reset VPD size because we want to find size of another VPD record\n l_vpdSize = 0;\n\n \/\/First read is to get size of vpd record, note the o_buffer is NULL\n l_rc = getMvpdField(lprRecord,\n fapi2::MVPD_KEYWORD_PDV,\n l_procParent,\n NULL,\n l_vpdSize);\n\n if(l_rc)\n {\n FAPI_ERR(\"p9_pm_get_poundv_bucket_attr:: Error reading PDV keyword size from LRP%d record\", l_eqChipUnitPos);\n break;\n }\n\n \/\/Allocate memory for vpd data\n l_fullVpdData = reinterpret_cast<uint8_t*>(malloc(l_vpdSize));\n\n FAPI_ASSERT(l_vpdSize - 4 - ((l_bucketId - 1) * 0x33) >= sizeof(fapi2::ATTR_POUNDV_BUCKET_DATA_Type),\n fapi2::BAD_VPD_READ()\n .set_EXPECTED_SIZE(sizeof(fapi2::ATTR_POUNDV_BUCKET_DATA_Type))\n .set_ACTUAL_SIZE(l_vpdSize - 4 - ((l_bucketId - 1) * 0x33)),\n \"#V data read was too small!\" );\n\n \/\/Second read is to get data of vpd record\n l_rc = getMvpdField(lprRecord,\n fapi2::MVPD_KEYWORD_PDV,\n l_procParent,\n l_fullVpdData,\n l_vpdSize);\n\n if(l_rc)\n {\n FAPI_ERR(\"p9_pm_get_poundv_bucket_attr:: Error reading PDV keyword from LRP%d record\", l_eqChipUnitPos);\n break;\n }\n\n \/\/#V record is laid out as follows:\n \/\/Name: 0x2 byte\n \/\/Length: 0x2 byte\n \/\/Version: 0x1 byte **buffer starts here\n \/\/PNP: 0x3 byte\n \/\/bucket a: 0x33 byte\n \/\/bucket b: 0x33 byte\n \/\/bucket c: 0x33 byte\n \/\/bucket d: 0x33 byte\n \/\/bucket e: 0x33 byte\n \/\/bucket f: 0x33 byte\n if( *l_fullVpdData == 0x2)\n {\n memcpy(o_data,\n l_fullVpdData + 4 + (l_bucketId - 1) * 0x33,\n sizeof(fapi2::ATTR_POUNDV_BUCKET_DATA_Type));\n }\n else\n {\n FAPI_ERR(\"p9_pm_get_poundv_bucket_attr::Invalid #V record version: 0x%x\", *l_fullVpdData);\n FAPI_ASSERT(0,\n fapi2::INVALID_POUNDV_VERSION()\n .set_POUNDV_VERSION(*l_fullVpdData),\n \"#V is of an invalid version!\" );\n }\n\n\n }\n while(0);\n\nfapi_try_exit:\n\n if(l_fullVpdData != NULL)\n {\n free(l_fullVpdData);\n }\n\n if(l_prDataPtr != NULL)\n {\n free(l_prDataPtr);\n }\n\n FAPI_IMP(\"Exiting p9_pm_get_poundv_bucket_attr ....\");\n\n \/\/If there is no issue in the current err, check\n \/\/the local rc to see if the mvpd access methods caught anything\n if((fapi2::current_err == fapi2::FAPI2_RC_SUCCESS) &&\n (l_rc != fapi2::FAPI2_RC_SUCCESS))\n {\n fapi2::current_err = l_rc;\n }\n\n return fapi2::current_err;\n}\n<commit_msg>Modify #V accessor function for new version 3<commit_after>\/* IBM_PROLOG_BEGIN_TAG *\/\n\/* This is an automatically generated prolog. *\/\n\/* *\/\n\/* $Source: src\/import\/chips\/p9\/procedures\/hwp\/pm\/p9_pm_get_poundv_bucket_attr.C $ *\/\n\/* *\/\n\/* OpenPOWER HostBoot Project *\/\n\/* *\/\n\/* Contributors Listed Below - COPYRIGHT 2015,2019 *\/\n\/* [+] International Business Machines Corp. *\/\n\/* *\/\n\/* *\/\n\/* Licensed under the Apache License, Version 2.0 (the \"License\"); *\/\n\/* you may not use this file except in compliance with the License. *\/\n\/* You may obtain a copy of the License at *\/\n\/* *\/\n\/* http:\/\/www.apache.org\/licenses\/LICENSE-2.0 *\/\n\/* *\/\n\/* Unless required by applicable law or agreed to in writing, software *\/\n\/* distributed under the License is distributed on an \"AS IS\" BASIS, *\/\n\/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or *\/\n\/* implied. See the License for the specific language governing *\/\n\/* permissions and limitations under the License. *\/\n\/* *\/\n\/* IBM_PROLOG_END_TAG *\/\n\/\/\/\n\/\/\/ @file p9_pm_get_poundv_bucket_attr.C\n\/\/\/ @brief Grab PM data from certain bucket in #V keyword in LRPX record\n\/\/\/\n\n\/\/ ----------------------------------------------------------------------\n\/\/ Includes\n\/\/ ----------------------------------------------------------------------\n#include <p9_pm_get_poundv_bucket_attr.H>\n#include <p9_pm_get_poundv_bucket.H>\n#include <mvpd_access_defs.H>\n#include <attribute_ids.H>\n\nfapi2::ReturnCode p9_pm_get_poundv_bucket_attr(\n const fapi2::Target<fapi2::TARGET_TYPE_EQ>& i_target,\n uint8_t* o_data)\n{\n FAPI_DBG(\"Entering p9_pm_get_poundv_bucket_attr ....\");\n uint8_t* l_prDataPtr = NULL;\n uint8_t* l_fullVpdData = NULL;\n uint8_t l_overridePresent = 0;\n uint32_t l_tempVpdSize = 0;\n uint32_t l_vpdSize = 0;\n uint8_t l_eqChipUnitPos = 0;\n uint8_t l_bucketId;\n uint8_t l_bucketSize = 0;\n uint32_t l_sysNestFreq = 0;\n fapi2::voltageBucketData_t* l_currentBucket = NULL;\n uint8_t l_numMatches = 0;\n\n fapi2::MvpdRecord lrpRecord = fapi2::MVPD_RECORD_LAST;\n \/\/To read MVPD we will need the proc parent of the inputted EQ target\n fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP> l_procParent =\n i_target.getParent<fapi2::TARGET_TYPE_PROC_CHIP>();\n\n\n \/\/Need to determine which LRP record to read from depending on which\n \/\/bucket we are getting the power management data from. FapiPos will\n \/\/tell us which LRP record to use.\n FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_CHIP_UNIT_POS,\n i_target,\n l_eqChipUnitPos));\n\n FAPI_ASSERT( l_eqChipUnitPos < NUM_BUCKETS ,\n fapi2::INVALID_EQ_CHIP_POS().\n set_EQ_POSITION( l_eqChipUnitPos ),\n \"Invalid EQ chip unit position = 0x%X\",\n l_eqChipUnitPos);\n\n \/\/The enumeration for the LRPx records are just 3 more\n \/\/than the EQ chip unit pos. See mvpd_access_defs.H\n lrpRecord = static_cast<fapi2::MvpdRecord>(l_eqChipUnitPos +\n fapi2::MVPD_RECORD_LRP0 );\n\n\n \/\/check if bucket num has been overriden\n FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_POUNDV_BUCKET_NUM_OVERRIDE,\n i_target,\n l_overridePresent));\n\n if(l_overridePresent != 0)\n {\n \/\/If it has been overriden then get the override\n FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_POUNDV_BUCKET_NUM,\n i_target,\n l_bucketId));\n }\n else\n {\n \/\/First read is to get size of vpd record, note the o_buffer is NULL\n FAPI_TRY( getMvpdField(lrpRecord,\n fapi2::MVPD_KEYWORD_PDV,\n l_procParent,\n NULL,\n l_tempVpdSize) );\n\n\n \/\/save off the actual vpd size\n l_vpdSize = l_tempVpdSize;\n \/\/Allocate memory for vpd data\n l_fullVpdData = reinterpret_cast<uint8_t*>(malloc(l_tempVpdSize));\n\n\n \/\/Second read is to get data of vpd record\n FAPI_TRY( getMvpdField(lrpRecord,\n fapi2::MVPD_KEYWORD_PDV,\n l_procParent,\n l_fullVpdData,\n l_tempVpdSize) );\n\n \/\/Version 2:\n \/\/#V record is laid out as follows:\n \/\/Name: 0x2 byte\n \/\/Length: 0x2 byte\n \/\/Version: 0x1 byte **buffer starts here\n \/\/PNP: 0x3 byte\n \/\/bucket a: 0x33 byte\n \/\/bucket b: 0x33 byte\n \/\/bucket c: 0x33 byte\n \/\/bucket d: 0x33 byte\n \/\/bucket e: 0x33 byte\n \/\/bucket f: 0x33 byte\n if( *l_fullVpdData == POUNDV_VERSION_2)\n {\n \/\/Set the size of the bucket\n l_bucketSize = VERSION_2_BUCKET_SIZE;\n\n \/\/Reset VPD size because we want to find size of another VPD record\n l_tempVpdSize = 0;\n\n \/\/First read is to get size of vpd record, note the o_buffer is NULL\n FAPI_TRY( getMvpdField(fapi2::MVPD_RECORD_VINI,\n fapi2::MVPD_KEYWORD_PR,\n l_procParent,\n NULL,\n l_tempVpdSize) );\n\n l_prDataPtr = reinterpret_cast<uint8_t*>(malloc(l_tempVpdSize));\n\n \/\/Second read is to get data of vpd record\n FAPI_TRY( getMvpdField(fapi2::MVPD_RECORD_VINI,\n fapi2::MVPD_KEYWORD_PR,\n l_procParent,\n l_prDataPtr,\n l_tempVpdSize) );\n\n \/\/Bucket ID is byte[4] of the PR keyword\n memcpy(&l_bucketId, (l_prDataPtr + 4), sizeof(uint8_t));\n\n }\n \/\/Version 3:\n \/\/#V record is laid out as follows:\n \/\/Name: 0x2 byte\n \/\/Length: 0x2 byte\n \/\/Version: 0x1 byte **buffer starts here\n \/\/PNP: 0x3 byte\n \/\/bucket a: 0x3D byte\n \/\/bucket b: 0x3D byte\n \/\/bucket c: 0x3D byte\n \/\/bucket d: 0x3D byte\n \/\/bucket e: 0x3D byte\n \/\/bucket f: 0x3D byte\n else if( *l_fullVpdData == POUNDV_VERSION_3 )\n {\n \/\/ Set the size of the bucket\n l_bucketSize = VERSION_3_BUCKET_SIZE;\n\n \/\/ Version 3 uses the nest frequency to choose the bucket Id\n \/\/ get the system target to find the NEST_FREQ_MHZ\n fapi2::Target<fapi2::TARGET_TYPE_SYSTEM> l_sysParent;\n\n\n FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_FREQ_PB_MHZ,\n l_sysParent,\n l_sysNestFreq));\n \/\/cast the voltage data into an array of buckets\n fapi2::voltageBucketData_t* l_buckets = reinterpret_cast\n <fapi2::voltageBucketData_t*>\n (l_fullVpdData + POUNDV_BUCKET_OFFSET);\n\n for(int i = 0; i < NUM_BUCKETS; i++)\n {\n if(l_buckets[i].pbFreq == l_sysNestFreq)\n {\n l_numMatches++;\n\n \/*\n * TODO RTC: 157341\n * Modify function to fail if multiple buckets have same nest\n *\/\n if(l_numMatches > 1)\n {\n FAPI_ERR(\"p9_pm_get_poundv_bucket_attr::\"\n \" Multiple buckets (%d) reporting the same nest frequency\",\n l_numMatches);\n }\n\n \/*\n else\n {\n l_currentBucket = &l_buckets[i];\n }\n *\/\n l_currentBucket = &l_buckets[i];\n }\n }\n\n \/*\n * TODO RTC: 157341\n * Modify function to fail if multiple buckets have same nest\n if(l_numMatches == 1)\n {\n l_bucketId = l_currentBucket->bucketId;\n }\n else\n {\n\n FAPI_ERR(\"p9_pm_get_poundv_bucket_attr::Invalid number of matching nest freqs found. Matches found = %d\",\n l_numMatches );\n FAPI_ASSERT(0,\n fapi2::INVALID_MATCHING_FREQ_NUMBER().\n set_MATCHES_FOUND(l_numMatches),\n \"Matches found is NOT 1\" );\n }\n *\/\n l_bucketId = l_currentBucket->bucketId;\n }\n else\n {\n FAPI_ASSERT( false,\n fapi2::INVALID_POUNDV_VERSION()\n .set_POUNDV_VERSION(*l_fullVpdData),\n \"p9_pm_get_poundv_bucket_attr::Invalid #V record version: 0x%x\",\n *l_fullVpdData);\n }\n\n \/\/ This assert ensures the size of the calculated data is correct\n FAPI_ASSERT(l_vpdSize - POUNDV_BUCKET_OFFSET - ((l_bucketId - 1) *\n l_bucketSize) >= l_bucketSize,\n fapi2::BAD_VPD_READ().set_EXPECTED_SIZE(sizeof(l_bucketSize))\n .set_ACTUAL_SIZE(l_vpdSize - POUNDV_BUCKET_OFFSET -\n ((l_bucketId - 1) * l_bucketSize)),\n \"#V data read was too small!\" );\n\n }\/\/ else no override\n\n \/\/ Ensure we got a valid bucket id\n \/\/ NOTE: Bucket IDs range from 1-6\n FAPI_ASSERT( (l_bucketId <= NUM_BUCKETS) && (l_bucketId != 0),\n fapi2::INVALID_BUCKET_ID()\n .set_TARGET(i_target)\n .set_BUCKET_ID(l_bucketId),\n \"Invalid Bucket Id = %d\",\n l_bucketId );\n\n\n \/\/ Use the selected bucket id to populate the output data\n memcpy(o_data,\n l_fullVpdData + POUNDV_BUCKET_OFFSET + (l_bucketId - 1) * l_bucketSize,\n l_bucketSize);\n\nfapi_try_exit:\n\n if(l_fullVpdData != NULL)\n {\n free(l_fullVpdData);\n l_fullVpdData = NULL;\n }\n\n if(l_prDataPtr != NULL)\n {\n free(l_prDataPtr);\n l_prDataPtr = NULL;\n }\n\n FAPI_DBG(\"Exiting p9_pm_get_poundv_bucket_attr ....\");\n\n return fapi2::current_err;\n}\n<|endoftext|>"} {"text":"<commit_before>\/* bzflag\n * Copyright (c) 1993 - 2004 Tim Riker\n *\n * This package is free software; you can redistribute it and\/or\n * modify it under the terms of the license found in the file\n * named COPYING that should have accompanied this file.\n *\n * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR\n * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED\n * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.\n *\/\n\n#include \"common.h\"\n#include \"bzfgl.h\"\n#include \"OpenGLTexture.h\"\n#include \"OpenGLGState.h\"\n\n#if defined(GL_VERSION_1_1)\n# define\tBZF_TEXTURE_OBJECT\n#elif defined(GL_EXT_texture_object)\n# define\tBZF_TEXTURE_OBJECT\n# define\tglBindTexture\t\tglBindTextureEXT\n# define\tglDeleteTextures\tglDeleteTexturesEXT\n# define\tglGenTextures\t\tglGenTexturesEXT\n#endif\n\n#if defined(GL_VERSION_1_1)\n# define\tBZF_INTENSITY_FORMAT\tGL_INTENSITY\n#elif defined(GL_EXT_texture)\n# define\tBZF_INTENSITY_FORMAT\tGL_INTENSITY_EXT\n#else\n# define\tBZF_INTENSITY_FORMAT\t0 \/* not used *\/\n#endif\n\nstatic int\t\thasTextureObject = -1;\n\n\/\/\n\/\/ OpenGLTexture::Rep\n\/\/\n\n\nconst GLenum\t\tOpenGLTexture::minifyFilter[] = {\n\t\t\t\tGL_NEAREST,\n\t\t\t\tGL_NEAREST,\n\t\t\t\tGL_LINEAR,\n\t\t\t\tGL_NEAREST_MIPMAP_NEAREST,\n\t\t\t\tGL_LINEAR_MIPMAP_NEAREST,\n\t\t\t\tGL_NEAREST_MIPMAP_LINEAR,\n\t\t\t\tGL_LINEAR_MIPMAP_LINEAR\n\t\t\t};\nconst GLenum\t\tOpenGLTexture::magnifyFilter[] = {\n\t\t\t\tGL_NEAREST,\n\t\t\t\tGL_NEAREST,\n\t\t\t\tGL_LINEAR,\n\t\t\t\tGL_NEAREST,\n\t\t\t\tGL_LINEAR,\n\t\t\t\tGL_NEAREST,\n\t\t\t\tGL_LINEAR\n\t\t\t};\nconst char*\t\tOpenGLTexture::configFilterValues[] = {\n\t\t\t\t\"no\",\n\t\t\t\t\"nearest\",\n\t\t\t\t\"linear\",\n\t\t\t\t\"nearestmipmapnearest\",\n\t\t\t\t\"linearmipmapnearest\",\n\t\t\t\t\"nearestmipmaplinear\",\n\t\t\t\t\"linearmipmaplinear\"\n};\n\n\n\/\/\n\/\/ OpenGLTexture\n\/\/\n\nOpenGLTexture::Filter\tOpenGLTexture::filter = LinearMipmapLinear;\n\n\nOpenGLTexture::OpenGLTexture(int _width, int _height,\n\t\t\t\tconst GLvoid* pixels,\n\t\t\t\tFilter _maxFilter,\n\t\t\t\tbool _repeat,\n\t\t\t\tint _internalFormat)\n\t\t\t\t: alpha(false),\n\t\t\t\twidth(_width),\n\t\t\t\theight(_height),\n\t\t\t\trepeat(_repeat),\n\t\t\t\tinternalFormat(_internalFormat),\n\t\t\t\tmaxFilter(_maxFilter),\n\t\t\t\tlist(0)\n{\n \/\/ check for texture object extension\n if (hasTextureObject < 0) {\n#if defined(GL_VERSION_1_1)\n hasTextureObject = 1;\n#elif defined(GL_EXT_texture_object)\n hasTextureObject = (strstr((const char*)glGetString(GL_EXTENSIONS),\n\t\t\t\t\t\"GL_EXT_texture_object\") != NULL);\n#else\n hasTextureObject = 0;\n#endif \/\/ BZF_TEXTURE_OBJECT\n }\n\n \/\/ make texture map object\/list\n#if defined(BZF_TEXTURE_OBJECT)\n if (hasTextureObject > 0)\n glGenTextures(1, &list);\n else\n#endif \/\/ BZF_TEXTURE_OBJECT\n list = glGenLists(1);\n\n \/\/ get internal format if not provided\n if (internalFormat == 0)\n internalFormat = getBestFormat(width, height, pixels);\n\n \/\/ copy the original texture image\n image = new GLubyte[4 * width * height];\n ::memcpy(image, pixels, 4 * width * height);\n\n { int patlabor_remove_this_once_tm_does_this; }\n setFilter(std::string(\"linearmipmaplinear\"));\n\n initContext();\n\n \/\/ watch for context recreation\n OpenGLGState::registerContextInitializer(static_initContext, (void*)this);\n}\n\nOpenGLTexture::~OpenGLTexture()\n{\n OpenGLGState::unregisterContextInitializer(static_initContext, (void*)this);\n\n \/\/ free image data\n delete[] image;\n\n \/\/ free OpenGL display list or texture object\n#if defined(BZF_TEXTURE_OBJECT)\n if (hasTextureObject > 0) {\n if (list) glDeleteTextures(1, &list);\n }\n else\n#endif \/\/ BZF_TEXTURE_OBJECT\n if (list) glDeleteLists(list, 1);\n}\n\nvoid OpenGLTexture::static_initContext(void *that)\n{\n ((OpenGLTexture*) that)->initContext();\n}\n\nvoid OpenGLTexture::initContext()\n{\n \/\/ set size\n int tmpWidth = width;\n int tmpHeight = height;\n\n \/\/ get minimum valid size for texture (boost to 2^m x 2^n)\n GLint scaledWidth = 1, scaledHeight = 1;\n GLint maxTextureSize;\n glGetIntegerv(GL_MAX_TEXTURE_SIZE, &maxTextureSize);\n if (maxTextureSize > 512) maxTextureSize = 512;\n while (scaledWidth < tmpWidth) scaledWidth <<= 1;\n while (scaledHeight < tmpHeight) scaledHeight <<= 1;\n if (scaledWidth > maxTextureSize) scaledWidth = maxTextureSize;\n if (scaledHeight > maxTextureSize) scaledHeight = maxTextureSize;\n const int copyWidth = (scaledWidth > tmpWidth) ? scaledWidth : tmpWidth;\n const int copyHeight = (scaledHeight > tmpHeight) ? scaledHeight : tmpHeight;\n\n \/\/ make buffers for copied and scaled data\n GLubyte* origData = new GLubyte[4 * copyWidth * copyHeight + 4];\n GLubyte* data = (GLubyte*)(((unsigned long)origData & ~3) + 4);\n GLubyte* origScaledData = new GLubyte[4 * scaledWidth * scaledHeight + 4];\n GLubyte* scaledData = (GLubyte*)(((unsigned long)origScaledData & ~3) + 4);\n ::memcpy(data, image, 4 * tmpWidth * tmpHeight);\n\n \/\/ note if internal format uses alpha\n switch (internalFormat) {\n case BZF_INTENSITY_FORMAT:\n case GL_LUMINANCE_ALPHA:\n#if defined(GL_LUMINANCE4_ALPHA4)\n case GL_LUMINANCE4_ALPHA4:\n#elif defined(GL_LUMINANCE4_ALPHA4_EXT)\n case GL_LUMINANCE4_ALPHA4_EXT:\n#endif\n case GL_RGBA:\n#if defined(GL_INTENSITY4)\n case GL_INTENSITY4:\n#elif defined(GL_INTENSITY4_EXT)\n case GL_INTENSITY4_EXT:\n#endif\n alpha = true;\n break;\n\n default:\n alpha = false;\n break;\n }\n\n \/\/ now make texture map display list (compute all mipmaps, if requested).\n \/\/ compute next mipmap from current mipmap to save time.\n const bool mipmap = ((int)maxFilter > (int)Linear);\n GLint mipmapLevel = 0;\n\n#if defined(BZF_TEXTURE_OBJECT)\n if (hasTextureObject > 0)\n glBindTexture(GL_TEXTURE_2D, list);\n else\n#endif \/\/ BZF_TEXTURE_OBJECT\n glNewList(list, GL_COMPILE);\n\n setFilter((Filter)maxFilter);\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S,\n\t\t\trepeat ? GL_REPEAT : GL_CLAMP);\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T,\n\t\t\trepeat ? GL_REPEAT : GL_CLAMP);\n do {\n bool doScale = (scaledWidth != tmpWidth || scaledHeight != tmpHeight);\n\n \/\/ scale image to next mipmap level\n if (doScale)\n gluScaleImage(\n\t\tGL_RGBA, tmpWidth, tmpHeight, GL_UNSIGNED_BYTE, data,\n\t\tscaledWidth ? scaledWidth : 1,\n\t\tscaledHeight ? scaledHeight : 1,\n\t\tGL_UNSIGNED_BYTE, scaledData);\n\n \/\/ make texture\n glTexImage2D(GL_TEXTURE_2D, mipmapLevel, internalFormat,\n\t\tscaledWidth ? scaledWidth : 1,\n\t\tscaledHeight ? scaledHeight : 1,\n\t\t0, GL_RGBA, GL_UNSIGNED_BYTE,\n\t\tdoScale ? scaledData : data);\n\n \/\/ prepare for next iteration\n mipmapLevel++;\n tmpWidth = scaledWidth;\n tmpHeight = scaledHeight;\n scaledWidth >>= 1;\n scaledHeight >>= 1;\n if (doScale)\n ::memcpy(data, scaledData, 4 * tmpWidth * tmpHeight);\n } while (mipmap && (scaledWidth > 0 || scaledHeight > 0));\n\n setFilter(getFilter());\n\n#if defined(BZF_TEXTURE_OBJECT)\n if (hasTextureObject > 0)\n glBindTexture(GL_TEXTURE_2D, 0);\n else\n#endif \/\/ BZF_TEXTURE_OBJECT\n glEndList();\n\n \/\/ free extra buffers\n delete[] origScaledData;\n delete[] origData;\n}\n\nOpenGLTexture::Filter\tOpenGLTexture::getFilter()\n{\n return filter;\n}\n\nstd::string\t\tOpenGLTexture::getFilterName()\n{\n return configFilterValues[static_cast<int>(filter)];\n}\n\nvoid\t\t\tOpenGLTexture::setFilter(std::string name)\n{\n for (unsigned int i = 0; i < (sizeof(configFilterValues) \/\n\t\t\t\tsizeof(configFilterValues[0])); i++)\n if (name == configFilterValues[i])\n setFilter(static_cast<Filter>(i));\n}\n\nvoid\t\t\tOpenGLTexture::setFilter(Filter _filter)\n{\n filter = _filter;\n\n#if defined(BZF_TEXTURE_OBJECT)\n\n \/\/ can only change filters when using texture objects\n if (hasTextureObject <= 0) return;\n\n int filterIndex = (int) filter;\n \/\/ limit filter. try to keep nearest... filters as nearest and\n \/\/ linear... as linear.\n if (filterIndex > maxFilter) {\n if ((filterIndex & 1) == 1)\t\/\/ nearest...\n if ((maxFilter & 1) == 1) filterIndex = maxFilter;\n else filterIndex = maxFilter > 0 ? maxFilter - 1 : 0;\n\n else\t\t\t\/\/ linear...\n if ((maxFilter & 1) == 1) filterIndex = maxFilter - 1;\n else filterIndex = maxFilter;\n }\n\n#if defined(BZF_TEXTURE_OBJECT)\n if (hasTextureObject > 0)\n glBindTexture(GL_TEXTURE_2D, list);\n#endif \/\/ BZF_TEXTURE_OBJECT\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, minifyFilter[filterIndex]);\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, magnifyFilter[filterIndex]);\n#endif \/\/ BZF_TEXTURE_OBJECT\n}\n\nGLuint\t\t\tOpenGLTexture::getList() const\n{\n return (list);\n}\n\nvoid\t\t\tOpenGLTexture::execute()\n{\n bind();\n}\n\nfloat\t\t\tOpenGLTexture::getAspectRatio() const\n{\n return ((float) height) \/ ((float) width);\n}\n\nvoid\t\t\tOpenGLTexture::bind()\n{\n#if defined(BZF_TEXTURE_OBJECT)\n if (hasTextureObject > 0) {\n if (list) glBindTexture(GL_TEXTURE_2D, list);\n else glBindTexture(GL_TEXTURE_2D, 0);\n }\n else\n#endif \/\/ BZF_TEXTURE_OBJECT\n if (list) glCallList(list);\n else glTexImage2D(GL_TEXTURE_2D, 0, 3, 0, 0, 0, GL_RGB, GL_UNSIGNED_BYTE, NULL);\n}\n\nint\t\t\tOpenGLTexture::getBestFormat(\n\t\t\t\tint width, int height,\n\t\t\t\tconst GLvoid* pixels)\n{\n \/\/ see if all pixels are achromatic\n const GLubyte* scan = (const GLubyte*)pixels;\n const int size = width * height;\n int i;\n for (i = 0; i < size; scan += 4, i++)\n if (scan[0] != scan[1] || scan[0] != scan[2])\n break;\n const bool useLuminance = (i == size);\n\n \/\/ see if all pixels are opaque\n scan = (const GLubyte*)pixels;\n for (i = 0; i < size; scan += 4, i++)\n if (scan[3] != 0xff)\n break;\n const bool useAlpha = (i != size);\n\n \/\/ intensity format defined in 1.1 and an extension in 1.0\n#if defined(GL_VERSION_1_1)\n static const bool hasTextureExt = true;\n#elif defined(GL_INTENSITY_EXT)\n static const bool hasTextureExt = (strstr((const char*)\n\t\tglGetString(GL_EXTENSIONS), \"GL_EXT_texture\") != NULL);\n#else\n static const bool hasTextureExt = false;\n#endif \/\/ defined(GL_VERSION_1_1)\n\n \/\/ see if all pixels are r=g=b=a. if so return intensity format.\n \/\/ SGI IMPACT and 3Dfx systems don't support GL_INTENSITY.\n const char* const glRenderer = (const char*)glGetString(GL_RENDERER);\n static bool noIntensity =\n\t(strncmp(glRenderer, \"IMPACT\", 6) == 0) ||\n\t(strncmp(glRenderer, \"3Dfx\", 4) == 0);\n if (!noIntensity) {\n bool useIntensity = false;\n if (hasTextureExt && useLuminance) {\n scan = (const GLubyte*)pixels;\n for (i = 0; i < size; scan += 4, i++)\n\tif (scan[3] != scan[0])\n\t break;\n useIntensity = (i == size);\n }\n if (useIntensity) return BZF_INTENSITY_FORMAT;\n }\n\n \/\/ pick internal format\n return (useLuminance ?\n\t\t(useAlpha ? GL_LUMINANCE_ALPHA : GL_LUMINANCE) :\n\t\t(useAlpha ? GL_RGBA : GL_RGB));\n}\n\n\/\/ Local Variables: ***\n\/\/ mode:C++ ***\n\/\/ tab-width: 8 ***\n\/\/ c-basic-offset: 2 ***\n\/\/ indent-tabs-mode: t ***\n\/\/ End: ***\n\/\/ ex: shiftwidth=2 tabstop=8\n\n<commit_msg>Fixing field initialization order warning<commit_after>\/* bzflag\n * Copyright (c) 1993 - 2004 Tim Riker\n *\n * This package is free software; you can redistribute it and\/or\n * modify it under the terms of the license found in the file\n * named COPYING that should have accompanied this file.\n *\n * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR\n * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED\n * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.\n *\/\n\n#include \"common.h\"\n#include \"bzfgl.h\"\n#include \"OpenGLTexture.h\"\n#include \"OpenGLGState.h\"\n\n#if defined(GL_VERSION_1_1)\n# define\tBZF_TEXTURE_OBJECT\n#elif defined(GL_EXT_texture_object)\n# define\tBZF_TEXTURE_OBJECT\n# define\tglBindTexture\t\tglBindTextureEXT\n# define\tglDeleteTextures\tglDeleteTexturesEXT\n# define\tglGenTextures\t\tglGenTexturesEXT\n#endif\n\n#if defined(GL_VERSION_1_1)\n# define\tBZF_INTENSITY_FORMAT\tGL_INTENSITY\n#elif defined(GL_EXT_texture)\n# define\tBZF_INTENSITY_FORMAT\tGL_INTENSITY_EXT\n#else\n# define\tBZF_INTENSITY_FORMAT\t0 \/* not used *\/\n#endif\n\nstatic int\t\thasTextureObject = -1;\n\n\/\/\n\/\/ OpenGLTexture::Rep\n\/\/\n\n\nconst GLenum\t\tOpenGLTexture::minifyFilter[] = {\n\t\t\t\tGL_NEAREST,\n\t\t\t\tGL_NEAREST,\n\t\t\t\tGL_LINEAR,\n\t\t\t\tGL_NEAREST_MIPMAP_NEAREST,\n\t\t\t\tGL_LINEAR_MIPMAP_NEAREST,\n\t\t\t\tGL_NEAREST_MIPMAP_LINEAR,\n\t\t\t\tGL_LINEAR_MIPMAP_LINEAR\n\t\t\t};\nconst GLenum\t\tOpenGLTexture::magnifyFilter[] = {\n\t\t\t\tGL_NEAREST,\n\t\t\t\tGL_NEAREST,\n\t\t\t\tGL_LINEAR,\n\t\t\t\tGL_NEAREST,\n\t\t\t\tGL_LINEAR,\n\t\t\t\tGL_NEAREST,\n\t\t\t\tGL_LINEAR\n\t\t\t};\nconst char*\t\tOpenGLTexture::configFilterValues[] = {\n\t\t\t\t\"no\",\n\t\t\t\t\"nearest\",\n\t\t\t\t\"linear\",\n\t\t\t\t\"nearestmipmapnearest\",\n\t\t\t\t\"linearmipmapnearest\",\n\t\t\t\t\"nearestmipmaplinear\",\n\t\t\t\t\"linearmipmaplinear\"\n};\n\n\n\/\/\n\/\/ OpenGLTexture\n\/\/\n\nOpenGLTexture::Filter\tOpenGLTexture::filter = LinearMipmapLinear;\n\n\nOpenGLTexture::OpenGLTexture(int _width, int _height,\n\t\t\t\tconst GLvoid* pixels,\n\t\t\t\tFilter _maxFilter,\n\t\t\t\tbool _repeat,\n\t\t\t\tint _internalFormat)\n\t\t\t\t: alpha(false),\n\t\t\t\twidth(_width),\n\t\t\t\theight(_height),\n\t\t\t\trepeat(_repeat),\n\t\t\t\tinternalFormat(_internalFormat),\n\t\t\t\tlist(0),\n\t\t\t\tmaxFilter(_maxFilter)\n{\n \/\/ check for texture object extension\n if (hasTextureObject < 0) {\n#if defined(GL_VERSION_1_1)\n hasTextureObject = 1;\n#elif defined(GL_EXT_texture_object)\n hasTextureObject = (strstr((const char*)glGetString(GL_EXTENSIONS),\n\t\t\t\t\t\"GL_EXT_texture_object\") != NULL);\n#else\n hasTextureObject = 0;\n#endif \/\/ BZF_TEXTURE_OBJECT\n }\n\n \/\/ make texture map object\/list\n#if defined(BZF_TEXTURE_OBJECT)\n if (hasTextureObject > 0)\n glGenTextures(1, &list);\n else\n#endif \/\/ BZF_TEXTURE_OBJECT\n list = glGenLists(1);\n\n \/\/ get internal format if not provided\n if (internalFormat == 0)\n internalFormat = getBestFormat(width, height, pixels);\n\n \/\/ copy the original texture image\n image = new GLubyte[4 * width * height];\n ::memcpy(image, pixels, 4 * width * height);\n\n#ifdef _MSC_VER\n \/\/ Suppose Pat want to remind himself\n { int patlabor_remove_this_once_tm_does_this; }\n#endif\n setFilter(std::string(\"linearmipmaplinear\"));\n\n initContext();\n\n \/\/ watch for context recreation\n OpenGLGState::registerContextInitializer(static_initContext, (void*)this);\n}\n\nOpenGLTexture::~OpenGLTexture()\n{\n OpenGLGState::unregisterContextInitializer(static_initContext, (void*)this);\n\n \/\/ free image data\n delete[] image;\n\n \/\/ free OpenGL display list or texture object\n#if defined(BZF_TEXTURE_OBJECT)\n if (hasTextureObject > 0) {\n if (list) glDeleteTextures(1, &list);\n }\n else\n#endif \/\/ BZF_TEXTURE_OBJECT\n if (list) glDeleteLists(list, 1);\n}\n\nvoid OpenGLTexture::static_initContext(void *that)\n{\n ((OpenGLTexture*) that)->initContext();\n}\n\nvoid OpenGLTexture::initContext()\n{\n \/\/ set size\n int tmpWidth = width;\n int tmpHeight = height;\n\n \/\/ get minimum valid size for texture (boost to 2^m x 2^n)\n GLint scaledWidth = 1, scaledHeight = 1;\n GLint maxTextureSize;\n glGetIntegerv(GL_MAX_TEXTURE_SIZE, &maxTextureSize);\n if (maxTextureSize > 512) maxTextureSize = 512;\n while (scaledWidth < tmpWidth) scaledWidth <<= 1;\n while (scaledHeight < tmpHeight) scaledHeight <<= 1;\n if (scaledWidth > maxTextureSize) scaledWidth = maxTextureSize;\n if (scaledHeight > maxTextureSize) scaledHeight = maxTextureSize;\n const int copyWidth = (scaledWidth > tmpWidth) ? scaledWidth : tmpWidth;\n const int copyHeight = (scaledHeight > tmpHeight) ? scaledHeight : tmpHeight;\n\n \/\/ make buffers for copied and scaled data\n GLubyte* origData = new GLubyte[4 * copyWidth * copyHeight + 4];\n GLubyte* data = (GLubyte*)(((unsigned long)origData & ~3) + 4);\n GLubyte* origScaledData = new GLubyte[4 * scaledWidth * scaledHeight + 4];\n GLubyte* scaledData = (GLubyte*)(((unsigned long)origScaledData & ~3) + 4);\n ::memcpy(data, image, 4 * tmpWidth * tmpHeight);\n\n \/\/ note if internal format uses alpha\n switch (internalFormat) {\n case BZF_INTENSITY_FORMAT:\n case GL_LUMINANCE_ALPHA:\n#if defined(GL_LUMINANCE4_ALPHA4)\n case GL_LUMINANCE4_ALPHA4:\n#elif defined(GL_LUMINANCE4_ALPHA4_EXT)\n case GL_LUMINANCE4_ALPHA4_EXT:\n#endif\n case GL_RGBA:\n#if defined(GL_INTENSITY4)\n case GL_INTENSITY4:\n#elif defined(GL_INTENSITY4_EXT)\n case GL_INTENSITY4_EXT:\n#endif\n alpha = true;\n break;\n\n default:\n alpha = false;\n break;\n }\n\n \/\/ now make texture map display list (compute all mipmaps, if requested).\n \/\/ compute next mipmap from current mipmap to save time.\n const bool mipmap = ((int)maxFilter > (int)Linear);\n GLint mipmapLevel = 0;\n\n#if defined(BZF_TEXTURE_OBJECT)\n if (hasTextureObject > 0)\n glBindTexture(GL_TEXTURE_2D, list);\n else\n#endif \/\/ BZF_TEXTURE_OBJECT\n glNewList(list, GL_COMPILE);\n\n setFilter((Filter)maxFilter);\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S,\n\t\t\trepeat ? GL_REPEAT : GL_CLAMP);\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T,\n\t\t\trepeat ? GL_REPEAT : GL_CLAMP);\n do {\n bool doScale = (scaledWidth != tmpWidth || scaledHeight != tmpHeight);\n\n \/\/ scale image to next mipmap level\n if (doScale)\n gluScaleImage(\n\t\tGL_RGBA, tmpWidth, tmpHeight, GL_UNSIGNED_BYTE, data,\n\t\tscaledWidth ? scaledWidth : 1,\n\t\tscaledHeight ? scaledHeight : 1,\n\t\tGL_UNSIGNED_BYTE, scaledData);\n\n \/\/ make texture\n glTexImage2D(GL_TEXTURE_2D, mipmapLevel, internalFormat,\n\t\tscaledWidth ? scaledWidth : 1,\n\t\tscaledHeight ? scaledHeight : 1,\n\t\t0, GL_RGBA, GL_UNSIGNED_BYTE,\n\t\tdoScale ? scaledData : data);\n\n \/\/ prepare for next iteration\n mipmapLevel++;\n tmpWidth = scaledWidth;\n tmpHeight = scaledHeight;\n scaledWidth >>= 1;\n scaledHeight >>= 1;\n if (doScale)\n ::memcpy(data, scaledData, 4 * tmpWidth * tmpHeight);\n } while (mipmap && (scaledWidth > 0 || scaledHeight > 0));\n\n setFilter(getFilter());\n\n#if defined(BZF_TEXTURE_OBJECT)\n if (hasTextureObject > 0)\n glBindTexture(GL_TEXTURE_2D, 0);\n else\n#endif \/\/ BZF_TEXTURE_OBJECT\n glEndList();\n\n \/\/ free extra buffers\n delete[] origScaledData;\n delete[] origData;\n}\n\nOpenGLTexture::Filter\tOpenGLTexture::getFilter()\n{\n return filter;\n}\n\nstd::string\t\tOpenGLTexture::getFilterName()\n{\n return configFilterValues[static_cast<int>(filter)];\n}\n\nvoid\t\t\tOpenGLTexture::setFilter(std::string name)\n{\n for (unsigned int i = 0; i < (sizeof(configFilterValues) \/\n\t\t\t\tsizeof(configFilterValues[0])); i++)\n if (name == configFilterValues[i])\n setFilter(static_cast<Filter>(i));\n}\n\nvoid\t\t\tOpenGLTexture::setFilter(Filter _filter)\n{\n filter = _filter;\n\n#if defined(BZF_TEXTURE_OBJECT)\n\n \/\/ can only change filters when using texture objects\n if (hasTextureObject <= 0) return;\n\n int filterIndex = (int) filter;\n \/\/ limit filter. try to keep nearest... filters as nearest and\n \/\/ linear... as linear.\n if (filterIndex > maxFilter) {\n if ((filterIndex & 1) == 1)\t\/\/ nearest...\n if ((maxFilter & 1) == 1) filterIndex = maxFilter;\n else filterIndex = maxFilter > 0 ? maxFilter - 1 : 0;\n\n else\t\t\t\/\/ linear...\n if ((maxFilter & 1) == 1) filterIndex = maxFilter - 1;\n else filterIndex = maxFilter;\n }\n\n#if defined(BZF_TEXTURE_OBJECT)\n if (hasTextureObject > 0)\n glBindTexture(GL_TEXTURE_2D, list);\n#endif \/\/ BZF_TEXTURE_OBJECT\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, minifyFilter[filterIndex]);\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, magnifyFilter[filterIndex]);\n#endif \/\/ BZF_TEXTURE_OBJECT\n}\n\nGLuint\t\t\tOpenGLTexture::getList() const\n{\n return (list);\n}\n\nvoid\t\t\tOpenGLTexture::execute()\n{\n bind();\n}\n\nfloat\t\t\tOpenGLTexture::getAspectRatio() const\n{\n return ((float) height) \/ ((float) width);\n}\n\nvoid\t\t\tOpenGLTexture::bind()\n{\n#if defined(BZF_TEXTURE_OBJECT)\n if (hasTextureObject > 0) {\n if (list) glBindTexture(GL_TEXTURE_2D, list);\n else glBindTexture(GL_TEXTURE_2D, 0);\n }\n else\n#endif \/\/ BZF_TEXTURE_OBJECT\n if (list) glCallList(list);\n else glTexImage2D(GL_TEXTURE_2D, 0, 3, 0, 0, 0, GL_RGB, GL_UNSIGNED_BYTE, NULL);\n}\n\nint\t\t\tOpenGLTexture::getBestFormat(\n\t\t\t\tint width, int height,\n\t\t\t\tconst GLvoid* pixels)\n{\n \/\/ see if all pixels are achromatic\n const GLubyte* scan = (const GLubyte*)pixels;\n const int size = width * height;\n int i;\n for (i = 0; i < size; scan += 4, i++)\n if (scan[0] != scan[1] || scan[0] != scan[2])\n break;\n const bool useLuminance = (i == size);\n\n \/\/ see if all pixels are opaque\n scan = (const GLubyte*)pixels;\n for (i = 0; i < size; scan += 4, i++)\n if (scan[3] != 0xff)\n break;\n const bool useAlpha = (i != size);\n\n \/\/ intensity format defined in 1.1 and an extension in 1.0\n#if defined(GL_VERSION_1_1)\n static const bool hasTextureExt = true;\n#elif defined(GL_INTENSITY_EXT)\n static const bool hasTextureExt = (strstr((const char*)\n\t\tglGetString(GL_EXTENSIONS), \"GL_EXT_texture\") != NULL);\n#else\n static const bool hasTextureExt = false;\n#endif \/\/ defined(GL_VERSION_1_1)\n\n \/\/ see if all pixels are r=g=b=a. if so return intensity format.\n \/\/ SGI IMPACT and 3Dfx systems don't support GL_INTENSITY.\n const char* const glRenderer = (const char*)glGetString(GL_RENDERER);\n static bool noIntensity =\n\t(strncmp(glRenderer, \"IMPACT\", 6) == 0) ||\n\t(strncmp(glRenderer, \"3Dfx\", 4) == 0);\n if (!noIntensity) {\n bool useIntensity = false;\n if (hasTextureExt && useLuminance) {\n scan = (const GLubyte*)pixels;\n for (i = 0; i < size; scan += 4, i++)\n\tif (scan[3] != scan[0])\n\t break;\n useIntensity = (i == size);\n }\n if (useIntensity) return BZF_INTENSITY_FORMAT;\n }\n\n \/\/ pick internal format\n return (useLuminance ?\n\t\t(useAlpha ? GL_LUMINANCE_ALPHA : GL_LUMINANCE) :\n\t\t(useAlpha ? GL_RGBA : GL_RGB));\n}\n\n\/\/ Local Variables: ***\n\/\/ mode:C++ ***\n\/\/ tab-width: 8 ***\n\/\/ c-basic-offset: 2 ***\n\/\/ indent-tabs-mode: t ***\n\/\/ End: ***\n\/\/ ex: shiftwidth=2 tabstop=8\n\n<|endoftext|>"} {"text":"<commit_before>\/*\n * SessionSourceDatabase.cpp\n *\n * Copyright (C) 2009-11 by RStudio, Inc.\n *\n * This program is licensed to you under the terms of version 3 of the\n * GNU Affero General Public License. This program is distributed WITHOUT\n * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,\n * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the\n * AGPL (http:\/\/www.gnu.org\/licenses\/agpl-3.0.txt) for more details.\n *\n *\/\n\n#include <session\/SessionSourceDatabase.hpp>\n\n#include <string>\n#include <vector>\n#include <algorithm>\n\n#include <boost\/bind.hpp>\n#include <boost\/foreach.hpp>\n#include <boost\/regex.hpp>\n#include <boost\/date_time\/posix_time\/posix_time.hpp>\n\n#include <core\/Log.hpp>\n#include <core\/Exec.hpp>\n#include <core\/Error.hpp>\n#include <core\/FilePath.hpp>\n#include <core\/Hash.hpp>\n#include <core\/FileSerializer.hpp>\n#include <core\/DateTime.hpp>\n\n#include <core\/system\/System.hpp>\n\n#include <core\/http\/Util.hpp>\n\n#include <r\/RUtil.hpp>\n\n#include <session\/SessionModuleContext.hpp>\n\n\/\/ NOTE: if a file is deleted then its properties database entry is not\n\/\/ deleted. this has two implications:\n\/\/\n\/\/ - storage is not reclaimed\n\/\/ - the properties can be \"resurreced\" and re-attached to another\n\/\/ file with the same path\n\/\/\n\/\/ One way to overcome this might be to use filesystem metadata to store\n\/\/ properties rather than a side-database\n\nusing namespace core;\n\nnamespace session {\nnamespace source_database {\n\nnamespace {\n\nstruct PropertiesDatabase\n{\n FilePath path;\n FilePath indexFile;\n std::map<std::string,std::string> index;\n};\n\nError getPropertiesDatabase(PropertiesDatabase* pDatabase)\n{\n pDatabase->path = path().complete(\"properties\");\n Error error = pDatabase->path.ensureDirectory();\n if (error)\n return error;\n\n pDatabase->indexFile = pDatabase->path.complete(\"INDEX\");\n\n if (pDatabase->indexFile.exists())\n return readStringMapFromFile(pDatabase->indexFile, &(pDatabase->index));\n else\n return Success();\n}\n\nError putProperties(const std::string& path, const json::Object& properties)\n{\n \/\/ url escape path (so we can use key=value persistence)\n std::string escapedPath = http::util::urlEncode(path);\n\n \/\/ get properties database\n PropertiesDatabase propertiesDB;\n Error error = getPropertiesDatabase(&propertiesDB);\n if (error)\n return error;\n\n \/\/ use existing properties file if it exists, otherwise create new\n bool updateIndex = false;\n std::string propertiesFile = propertiesDB.index[escapedPath];\n if (propertiesFile.empty())\n {\n propertiesFile = core::system::generateUuid(false);\n propertiesDB.index[escapedPath] = propertiesFile;\n updateIndex = true;\n }\n\n \/\/ write the file\n std::ostringstream ostr ;\n json::writeFormatted(properties, ostr);\n FilePath propertiesFilePath = propertiesDB.path.complete(propertiesFile);\n error = writeStringToFile(propertiesFilePath, ostr.str());\n if (error)\n return error;\n\n \/\/ update the index if necessary\n if (updateIndex)\n return writeStringMapToFile(propertiesDB.indexFile, propertiesDB.index);\n else\n return Success();\n}\n\nError getProperties(const std::string& path, json::Object* pProperties)\n{\n \/\/ url escape path (so we can use key=value persistence)\n std::string escapedPath = http::util::urlEncode(path);\n\n \/\/ get properties database\n PropertiesDatabase propertiesDB;\n Error error = getPropertiesDatabase(&propertiesDB);\n if (error)\n return error;\n\n \/\/ check for properties file\n std::string propertiesFile = propertiesDB.index[escapedPath];\n if (propertiesFile.empty())\n {\n \/\/ return empty object if there is none\n *pProperties = json::Object();\n return Success();\n }\n\n \/\/ read the properties file\n std::string contents ;\n FilePath propertiesFilePath = propertiesDB.path.complete(propertiesFile);\n error = readStringFromFile(propertiesFilePath, &contents,\n options().sourceLineEnding());\n if (error)\n return error;\n\n \/\/ parse the json\n json::Value value;\n if ( !json::parse(contents, &value) )\n return systemError(boost::system::errc::bad_message, ERROR_LOCATION);\n\n \/\/ return it\n if (json::isType<json::Object>(value))\n *pProperties = value.get_obj();\n return Success();\n}\n\n} \/\/ anonymous namespace\n\nSourceDocument::SourceDocument(const std::string& type)\n{\n id_ = core::system::generateUuid();\n type_ = type;\n setContents(\"\");\n dirty_ = false;\n created_ = date_time::millisecondsSinceEpoch();\n sourceOnSave_ = false;\n}\n \n\nstd::string SourceDocument::getProperty(const std::string& name)\n{\n if (properties_.find(name) != properties_.end())\n {\n json::Value valueJson = properties_[name];\n if (json::isType<std::string>(valueJson))\n return valueJson.get_str();\n else\n return \"\";\n }\n else\n {\n return \"\";\n }\n}\n \n\/\/ set contents from string\nvoid SourceDocument::setContents(const std::string& contents)\n{\n contents_ = contents;\n hash_ = hash::crc32Hash(contents_);\n}\n\nnamespace {\n\nError readAndDecode(const FilePath& docPath,\n const std::string& encoding,\n bool allowSubstChars,\n std::string* pContents)\n{\n \/\/ read contents\n std::string encodedContents;\n Error error = readStringFromFile(docPath, &encodedContents,\n options().sourceLineEnding());\n\n if (error)\n return error ;\n\n error = r::util::iconvstr(encodedContents, encoding, \"UTF-8\",\n allowSubstChars, pContents);\n if (error)\n return error;\n\n stripBOM(pContents);\n \/\/ Detect invalid UTF-8 sequences and recover\n error = string_utils::utf8Clean(pContents->begin(),\n pContents->end(),\n '?');\n return error ;\n}\n\n} \/\/ anonymous namespace\n\n\/\/ set contents from file\nError SourceDocument::setPathAndContents(const std::string& path,\n bool allowSubstChars)\n{\n \/\/ resolve aliased path\n FilePath docPath = module_context::resolveAliasedPath(path);\n\n std::string contents;\n Error error = readAndDecode(docPath, encoding(), allowSubstChars,\n &contents);\n if (error)\n return error ;\n\n \/\/ update path and contents\n path_ = path;\n setContents(contents);\n lastKnownWriteTime_ = docPath.lastWriteTime();\n\n return Success();\n}\n\nError SourceDocument::updateDirty()\n{\n if (path().empty())\n {\n dirty_ = !contents_.empty();\n }\n else if (dirty_)\n {\n \/\/ This doesn't actually guarantee that dirty state is correct. All\n \/\/ it does, at the most, is take a dirty document and mark it clean\n \/\/ if the contents are the same as on disk. This is important because\n \/\/ the client now has logic to detect when undo\/redo causes a document\n \/\/ to be reverted to its previous state (i.e. a dirty document can\n \/\/ become clean through undo\/redo), but that state doesn't get sent\n \/\/ back to the server.\n\n \/\/ We don't make a clean document dirty here, even if the contents\n \/\/ on disk are different, because we will do that on the client side\n \/\/ and the UI logic is a little complicated.\n\n FilePath docPath = module_context::resolveAliasedPath(path());\n if (docPath.exists() && docPath.size() <= (1024*1024))\n {\n std::string contents;\n Error error = readAndDecode(docPath, encoding(), true, &contents);\n if (error)\n return error;\n\n if (contents_.length() == contents.length() && hash_ == hash::crc32Hash(contents))\n dirty_ = false;\n }\n }\n return Success();\n}\n\nvoid SourceDocument::editProperties(json::Object& properties)\n{\n std::for_each(properties.begin(),\n properties.end(),\n boost::bind(&SourceDocument::editProperty, this, _1));\n}\n\nvoid SourceDocument::checkForExternalEdit(std::time_t* pTime)\n{\n *pTime = 0;\n\n if (path_.empty())\n return;\n\n if (lastKnownWriteTime_ == 0)\n return;\n\n core::FilePath filePath = module_context::resolveAliasedPath(path_);\n if (!filePath.exists())\n return;\n\n std::time_t newTime = filePath.lastWriteTime();\n if (newTime != lastKnownWriteTime_)\n *pTime = newTime;\n}\n\nvoid SourceDocument::updateLastKnownWriteTime()\n{\n lastKnownWriteTime_ = 0;\n if (path_.empty())\n return;\n\n core::FilePath filePath = module_context::resolveAliasedPath(path_);\n if (!filePath.exists())\n return;\n\n lastKnownWriteTime_ = filePath.lastWriteTime();\n}\n \nError SourceDocument::readFromJson(json::Object* pDocJson)\n{\n \/\/ NOTE: since this class is the one who presumably persisted the\n \/\/ json values in the first place we don't do \"checked\" access to\n \/\/ the json data elements. if the persistence format differs from\n \/\/ what we expect things will blow up. therefore if we change the\n \/\/ persistence format we need to make sure this code is robust\n \/\/ in the presence of the old format\n\n json::Object& docJson = *pDocJson;\n\n id_ = docJson[\"id\"].get_str();\n json::Value path = docJson[\"path\"];\n path_ = !path.is_null() ? path.get_str() : std::string();\n\n json::Value type = docJson[\"type\"];\n type_ = !type.is_null() ? type.get_str() : std::string();\n\n setContents(docJson[\"contents\"].get_str());\n dirty_ = docJson[\"dirty\"].get_bool();\n created_ = docJson[\"created\"].get_real();\n sourceOnSave_ = docJson[\"source_on_save\"].get_bool();\n\n \/\/ read safely (migration)\n json::Value properties = docJson[\"properties\"];\n properties_ = !properties.is_null() ? properties.get_obj() : json::Object();\n\n json::Value lastKnownWriteTime = docJson[\"lastKnownWriteTime\"];\n lastKnownWriteTime_ = !lastKnownWriteTime.is_null()\n ? lastKnownWriteTime.get_int64()\n : 0;\n\n json::Value encoding = docJson[\"encoding\"];\n encoding_ = !encoding.is_null() ? encoding.get_str() : std::string();\n\n return Success();\n}\n \nvoid SourceDocument::writeToJson(json::Object* pDocJson) const\n{\n json::Object& jsonDoc = *pDocJson;\n jsonDoc[\"id\"] = id();\n jsonDoc[\"path\"] = !path().empty() ? path_ : json::Value();\n jsonDoc[\"type\"] = !type().empty() ? type_ : json::Value();\n jsonDoc[\"hash\"] = hash();\n jsonDoc[\"contents\"] = contents();\n jsonDoc[\"dirty\"] = dirty();\n jsonDoc[\"created\"] = created();\n jsonDoc[\"source_on_save\"] = sourceOnSave();\n jsonDoc[\"properties\"] = properties();\n jsonDoc[\"lastKnownWriteTime\"] = json::Value(\n static_cast<boost::int64_t>(lastKnownWriteTime_));\n jsonDoc[\"encoding\"] = encoding_;\n}\n\nvoid SourceDocument::editProperty(const json::Object::value_type& property)\n{\n if (property.second.is_null())\n {\n properties_.erase(property.first);\n }\n else\n {\n properties_[property.first] = property.second;\n }\n}\n\nbool sortByCreated(const SourceDocument& doc1, const SourceDocument& doc2)\n{\n return doc1.created() < doc2.created();\n}\n\nFilePath path()\n{\n return module_context::userScratchPath().complete(\"source_database\");\n}\n \nError get(const std::string& id, SourceDocument* pDoc)\n{\n FilePath filePath = source_database::path().complete(id);\n if (filePath.exists())\n {\n \/\/ read the contents of the file\n std::string contents ;\n Error error = readStringFromFile(filePath, &contents,\n options().sourceLineEnding());\n if (error)\n return error;\n \n \/\/ parse the json\n json::Value value;\n if ( !json::parse(contents, &value) )\n {\n return systemError(boost::system::errc::invalid_argument,\n ERROR_LOCATION);\n }\n \n \/\/ initialize doc from json\n json::Object jsonDoc = value.get_obj();\n return pDoc->readFromJson(&jsonDoc);\n }\n else\n {\n return systemError(boost::system::errc::no_such_file_or_directory,\n ERROR_LOCATION);\n }\n}\n\nError getDurableProperties(const std::string& path, json::Object* pProperties)\n{\n return getProperties(path, pProperties);\n}\n \nError list(std::vector<SourceDocument>* pDocs)\n{\n std::vector<FilePath> files ;\n Error error = source_database::path().children(&files);\n if (error)\n return error ;\n \n BOOST_FOREACH( FilePath& filePath, files )\n {\n if (!filePath.isDirectory())\n {\n \/\/ get the source doc\n SourceDocument doc ;\n Error error = source_database::get(filePath.filename(), &doc);\n if (error)\n return error ;\n\n \/\/ add it to the list\n pDocs->push_back(doc);\n }\n }\n \n return Success();\n}\n \nError put(const SourceDocument& doc)\n{\n \/\/ get json representation\n json::Object jsonDoc ;\n doc.writeToJson(&jsonDoc);\n std::ostringstream ostr ;\n json::writeFormatted(jsonDoc, ostr);\n \n \/\/ write to file\n FilePath filePath = source_database::path().complete(doc.id());\n Error error = writeStringToFile(filePath, ostr.str());\n if (error)\n return error ;\n\n \/\/ write properties to durable storage\n error = putProperties(doc.path(), doc.properties());\n if (error)\n LOG_ERROR(error);\n\n return Success();\n}\n \nError remove(const std::string& id)\n{\n return source_database::path().complete(id).removeIfExists();\n}\n \nError removeAll()\n{\n std::vector<FilePath> files ;\n Error error = source_database::path().children(&files);\n if (error)\n return error ;\n \n BOOST_FOREACH( FilePath& filePath, files )\n {\n Error error = filePath.remove();\n if (error)\n return error ;\n }\n \n return Success();\n}\n\n\nError getSourceDocumentsJson(core::json::Array* pJsonDocs)\n{\n \/\/ get the docs and sort them by created\n std::vector<SourceDocument> docs ;\n Error error = source_database::list(&docs);\n if (error)\n return error ;\n std::sort(docs.begin(), docs.end(), sortByCreated);\n \n \/\/ populate the array\n pJsonDocs->clear();\n BOOST_FOREACH( SourceDocument& doc, docs )\n {\n \/\/ Force dirty state to be checked.\n \/\/ Client and server dirty state can get out of sync because\n \/\/ undo\/redo on the client side can make dirty documents\n \/\/ become clean again. I tried pushing the client dirty state\n \/\/ back to the server but couldn't convince myself that I\n \/\/ got all the edge cases. This approach is simpler--just\n \/\/ compare the contents in the doc database to the contents\n \/\/ on disk, and only do it when listing documents. However\n \/\/ it does mean that reloading the client may cause a dirty\n \/\/ document to become clean (if the contents are identical\n \/\/ to what's on disk).\n error = doc.updateDirty();\n if (error)\n LOG_ERROR(error);\n\n json::Object jsonDoc ;\n doc.writeToJson(&jsonDoc);\n pJsonDocs->push_back(jsonDoc);\n }\n \n return Success();\n}\n \nError initialize()\n{\n \/\/ make sure the source database exists\n return source_database::path().ensureDirectory();\n}\n\n} \/\/ namespace source_database\n} \/\/ namesapce session\n\n<commit_msg>make sure an error reading one source document doesn't abort reading of other source docs<commit_after>\/*\n * SessionSourceDatabase.cpp\n *\n * Copyright (C) 2009-11 by RStudio, Inc.\n *\n * This program is licensed to you under the terms of version 3 of the\n * GNU Affero General Public License. This program is distributed WITHOUT\n * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,\n * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the\n * AGPL (http:\/\/www.gnu.org\/licenses\/agpl-3.0.txt) for more details.\n *\n *\/\n\n#include <session\/SessionSourceDatabase.hpp>\n\n#include <string>\n#include <vector>\n#include <algorithm>\n\n#include <boost\/bind.hpp>\n#include <boost\/foreach.hpp>\n#include <boost\/regex.hpp>\n#include <boost\/date_time\/posix_time\/posix_time.hpp>\n\n#include <core\/Log.hpp>\n#include <core\/Exec.hpp>\n#include <core\/Error.hpp>\n#include <core\/FilePath.hpp>\n#include <core\/Hash.hpp>\n#include <core\/FileSerializer.hpp>\n#include <core\/DateTime.hpp>\n\n#include <core\/system\/System.hpp>\n\n#include <core\/http\/Util.hpp>\n\n#include <r\/RUtil.hpp>\n\n#include <session\/SessionModuleContext.hpp>\n\n\/\/ NOTE: if a file is deleted then its properties database entry is not\n\/\/ deleted. this has two implications:\n\/\/\n\/\/ - storage is not reclaimed\n\/\/ - the properties can be \"resurreced\" and re-attached to another\n\/\/ file with the same path\n\/\/\n\/\/ One way to overcome this might be to use filesystem metadata to store\n\/\/ properties rather than a side-database\n\nusing namespace core;\n\nnamespace session {\nnamespace source_database {\n\nnamespace {\n\nstruct PropertiesDatabase\n{\n FilePath path;\n FilePath indexFile;\n std::map<std::string,std::string> index;\n};\n\nError getPropertiesDatabase(PropertiesDatabase* pDatabase)\n{\n pDatabase->path = path().complete(\"properties\");\n Error error = pDatabase->path.ensureDirectory();\n if (error)\n return error;\n\n pDatabase->indexFile = pDatabase->path.complete(\"INDEX\");\n\n if (pDatabase->indexFile.exists())\n return readStringMapFromFile(pDatabase->indexFile, &(pDatabase->index));\n else\n return Success();\n}\n\nError putProperties(const std::string& path, const json::Object& properties)\n{\n \/\/ url escape path (so we can use key=value persistence)\n std::string escapedPath = http::util::urlEncode(path);\n\n \/\/ get properties database\n PropertiesDatabase propertiesDB;\n Error error = getPropertiesDatabase(&propertiesDB);\n if (error)\n return error;\n\n \/\/ use existing properties file if it exists, otherwise create new\n bool updateIndex = false;\n std::string propertiesFile = propertiesDB.index[escapedPath];\n if (propertiesFile.empty())\n {\n propertiesFile = core::system::generateUuid(false);\n propertiesDB.index[escapedPath] = propertiesFile;\n updateIndex = true;\n }\n\n \/\/ write the file\n std::ostringstream ostr ;\n json::writeFormatted(properties, ostr);\n FilePath propertiesFilePath = propertiesDB.path.complete(propertiesFile);\n error = writeStringToFile(propertiesFilePath, ostr.str());\n if (error)\n return error;\n\n \/\/ update the index if necessary\n if (updateIndex)\n return writeStringMapToFile(propertiesDB.indexFile, propertiesDB.index);\n else\n return Success();\n}\n\nError getProperties(const std::string& path, json::Object* pProperties)\n{\n \/\/ url escape path (so we can use key=value persistence)\n std::string escapedPath = http::util::urlEncode(path);\n\n \/\/ get properties database\n PropertiesDatabase propertiesDB;\n Error error = getPropertiesDatabase(&propertiesDB);\n if (error)\n return error;\n\n \/\/ check for properties file\n std::string propertiesFile = propertiesDB.index[escapedPath];\n if (propertiesFile.empty())\n {\n \/\/ return empty object if there is none\n *pProperties = json::Object();\n return Success();\n }\n\n \/\/ read the properties file\n std::string contents ;\n FilePath propertiesFilePath = propertiesDB.path.complete(propertiesFile);\n error = readStringFromFile(propertiesFilePath, &contents,\n options().sourceLineEnding());\n if (error)\n return error;\n\n \/\/ parse the json\n json::Value value;\n if ( !json::parse(contents, &value) )\n return systemError(boost::system::errc::bad_message, ERROR_LOCATION);\n\n \/\/ return it\n if (json::isType<json::Object>(value))\n *pProperties = value.get_obj();\n return Success();\n}\n\n} \/\/ anonymous namespace\n\nSourceDocument::SourceDocument(const std::string& type)\n{\n id_ = core::system::generateUuid();\n type_ = type;\n setContents(\"\");\n dirty_ = false;\n created_ = date_time::millisecondsSinceEpoch();\n sourceOnSave_ = false;\n}\n \n\nstd::string SourceDocument::getProperty(const std::string& name)\n{\n if (properties_.find(name) != properties_.end())\n {\n json::Value valueJson = properties_[name];\n if (json::isType<std::string>(valueJson))\n return valueJson.get_str();\n else\n return \"\";\n }\n else\n {\n return \"\";\n }\n}\n \n\/\/ set contents from string\nvoid SourceDocument::setContents(const std::string& contents)\n{\n contents_ = contents;\n hash_ = hash::crc32Hash(contents_);\n}\n\nnamespace {\n\nError readAndDecode(const FilePath& docPath,\n const std::string& encoding,\n bool allowSubstChars,\n std::string* pContents)\n{\n \/\/ read contents\n std::string encodedContents;\n Error error = readStringFromFile(docPath, &encodedContents,\n options().sourceLineEnding());\n\n if (error)\n return error ;\n\n error = r::util::iconvstr(encodedContents, encoding, \"UTF-8\",\n allowSubstChars, pContents);\n if (error)\n return error;\n\n stripBOM(pContents);\n \/\/ Detect invalid UTF-8 sequences and recover\n error = string_utils::utf8Clean(pContents->begin(),\n pContents->end(),\n '?');\n return error ;\n}\n\n} \/\/ anonymous namespace\n\n\/\/ set contents from file\nError SourceDocument::setPathAndContents(const std::string& path,\n bool allowSubstChars)\n{\n \/\/ resolve aliased path\n FilePath docPath = module_context::resolveAliasedPath(path);\n\n std::string contents;\n Error error = readAndDecode(docPath, encoding(), allowSubstChars,\n &contents);\n if (error)\n return error ;\n\n \/\/ update path and contents\n path_ = path;\n setContents(contents);\n lastKnownWriteTime_ = docPath.lastWriteTime();\n\n return Success();\n}\n\nError SourceDocument::updateDirty()\n{\n if (path().empty())\n {\n dirty_ = !contents_.empty();\n }\n else if (dirty_)\n {\n \/\/ This doesn't actually guarantee that dirty state is correct. All\n \/\/ it does, at the most, is take a dirty document and mark it clean\n \/\/ if the contents are the same as on disk. This is important because\n \/\/ the client now has logic to detect when undo\/redo causes a document\n \/\/ to be reverted to its previous state (i.e. a dirty document can\n \/\/ become clean through undo\/redo), but that state doesn't get sent\n \/\/ back to the server.\n\n \/\/ We don't make a clean document dirty here, even if the contents\n \/\/ on disk are different, because we will do that on the client side\n \/\/ and the UI logic is a little complicated.\n\n FilePath docPath = module_context::resolveAliasedPath(path());\n if (docPath.exists() && docPath.size() <= (1024*1024))\n {\n std::string contents;\n Error error = readAndDecode(docPath, encoding(), true, &contents);\n if (error)\n return error;\n\n if (contents_.length() == contents.length() && hash_ == hash::crc32Hash(contents))\n dirty_ = false;\n }\n }\n return Success();\n}\n\nvoid SourceDocument::editProperties(json::Object& properties)\n{\n std::for_each(properties.begin(),\n properties.end(),\n boost::bind(&SourceDocument::editProperty, this, _1));\n}\n\nvoid SourceDocument::checkForExternalEdit(std::time_t* pTime)\n{\n *pTime = 0;\n\n if (path_.empty())\n return;\n\n if (lastKnownWriteTime_ == 0)\n return;\n\n core::FilePath filePath = module_context::resolveAliasedPath(path_);\n if (!filePath.exists())\n return;\n\n std::time_t newTime = filePath.lastWriteTime();\n if (newTime != lastKnownWriteTime_)\n *pTime = newTime;\n}\n\nvoid SourceDocument::updateLastKnownWriteTime()\n{\n lastKnownWriteTime_ = 0;\n if (path_.empty())\n return;\n\n core::FilePath filePath = module_context::resolveAliasedPath(path_);\n if (!filePath.exists())\n return;\n\n lastKnownWriteTime_ = filePath.lastWriteTime();\n}\n \nError SourceDocument::readFromJson(json::Object* pDocJson)\n{\n \/\/ NOTE: since this class is the one who presumably persisted the\n \/\/ json values in the first place we don't do \"checked\" access to\n \/\/ the json data elements. if the persistence format differs from\n \/\/ what we expect things will blow up. therefore if we change the\n \/\/ persistence format we need to make sure this code is robust\n \/\/ in the presence of the old format\n\n json::Object& docJson = *pDocJson;\n\n id_ = docJson[\"id\"].get_str();\n json::Value path = docJson[\"path\"];\n path_ = !path.is_null() ? path.get_str() : std::string();\n\n json::Value type = docJson[\"type\"];\n type_ = !type.is_null() ? type.get_str() : std::string();\n\n setContents(docJson[\"contents\"].get_str());\n dirty_ = docJson[\"dirty\"].get_bool();\n created_ = docJson[\"created\"].get_real();\n sourceOnSave_ = docJson[\"source_on_save\"].get_bool();\n\n \/\/ read safely (migration)\n json::Value properties = docJson[\"properties\"];\n properties_ = !properties.is_null() ? properties.get_obj() : json::Object();\n\n json::Value lastKnownWriteTime = docJson[\"lastKnownWriteTime\"];\n lastKnownWriteTime_ = !lastKnownWriteTime.is_null()\n ? lastKnownWriteTime.get_int64()\n : 0;\n\n json::Value encoding = docJson[\"encoding\"];\n encoding_ = !encoding.is_null() ? encoding.get_str() : std::string();\n\n return Success();\n}\n \nvoid SourceDocument::writeToJson(json::Object* pDocJson) const\n{\n json::Object& jsonDoc = *pDocJson;\n jsonDoc[\"id\"] = id();\n jsonDoc[\"path\"] = !path().empty() ? path_ : json::Value();\n jsonDoc[\"type\"] = !type().empty() ? type_ : json::Value();\n jsonDoc[\"hash\"] = hash();\n jsonDoc[\"contents\"] = contents();\n jsonDoc[\"dirty\"] = dirty();\n jsonDoc[\"created\"] = created();\n jsonDoc[\"source_on_save\"] = sourceOnSave();\n jsonDoc[\"properties\"] = properties();\n jsonDoc[\"lastKnownWriteTime\"] = json::Value(\n static_cast<boost::int64_t>(lastKnownWriteTime_));\n jsonDoc[\"encoding\"] = encoding_;\n}\n\nvoid SourceDocument::editProperty(const json::Object::value_type& property)\n{\n if (property.second.is_null())\n {\n properties_.erase(property.first);\n }\n else\n {\n properties_[property.first] = property.second;\n }\n}\n\nbool sortByCreated(const SourceDocument& doc1, const SourceDocument& doc2)\n{\n return doc1.created() < doc2.created();\n}\n\nFilePath path()\n{\n return module_context::userScratchPath().complete(\"source_database\");\n}\n \nError get(const std::string& id, SourceDocument* pDoc)\n{\n FilePath filePath = source_database::path().complete(id);\n if (filePath.exists())\n {\n \/\/ read the contents of the file\n std::string contents ;\n Error error = readStringFromFile(filePath, &contents,\n options().sourceLineEnding());\n if (error)\n return error;\n \n \/\/ parse the json\n json::Value value;\n if ( !json::parse(contents, &value) )\n {\n return systemError(boost::system::errc::invalid_argument,\n ERROR_LOCATION);\n }\n \n \/\/ initialize doc from json\n json::Object jsonDoc = value.get_obj();\n return pDoc->readFromJson(&jsonDoc);\n }\n else\n {\n return systemError(boost::system::errc::no_such_file_or_directory,\n ERROR_LOCATION);\n }\n}\n\nError getDurableProperties(const std::string& path, json::Object* pProperties)\n{\n return getProperties(path, pProperties);\n}\n \nError list(std::vector<SourceDocument>* pDocs)\n{\n std::vector<FilePath> files ;\n Error error = source_database::path().children(&files);\n if (error)\n return error ;\n \n BOOST_FOREACH( FilePath& filePath, files )\n {\n if (!filePath.isDirectory())\n {\n \/\/ get the source doc\n SourceDocument doc ;\n Error error = source_database::get(filePath.filename(), &doc);\n if (!error)\n pDocs->push_back(doc);\n else\n LOG_ERROR(error);\n }\n }\n \n return Success();\n}\n \nError put(const SourceDocument& doc)\n{\n \/\/ get json representation\n json::Object jsonDoc ;\n doc.writeToJson(&jsonDoc);\n std::ostringstream ostr ;\n json::writeFormatted(jsonDoc, ostr);\n \n \/\/ write to file\n FilePath filePath = source_database::path().complete(doc.id());\n Error error = writeStringToFile(filePath, ostr.str());\n if (error)\n return error ;\n\n \/\/ write properties to durable storage\n error = putProperties(doc.path(), doc.properties());\n if (error)\n LOG_ERROR(error);\n\n return Success();\n}\n \nError remove(const std::string& id)\n{\n return source_database::path().complete(id).removeIfExists();\n}\n \nError removeAll()\n{\n std::vector<FilePath> files ;\n Error error = source_database::path().children(&files);\n if (error)\n return error ;\n \n BOOST_FOREACH( FilePath& filePath, files )\n {\n Error error = filePath.remove();\n if (error)\n return error ;\n }\n \n return Success();\n}\n\n\nError getSourceDocumentsJson(core::json::Array* pJsonDocs)\n{\n \/\/ get the docs and sort them by created\n std::vector<SourceDocument> docs ;\n Error error = source_database::list(&docs);\n if (error)\n return error ;\n std::sort(docs.begin(), docs.end(), sortByCreated);\n \n \/\/ populate the array\n pJsonDocs->clear();\n BOOST_FOREACH( SourceDocument& doc, docs )\n {\n \/\/ Force dirty state to be checked.\n \/\/ Client and server dirty state can get out of sync because\n \/\/ undo\/redo on the client side can make dirty documents\n \/\/ become clean again. I tried pushing the client dirty state\n \/\/ back to the server but couldn't convince myself that I\n \/\/ got all the edge cases. This approach is simpler--just\n \/\/ compare the contents in the doc database to the contents\n \/\/ on disk, and only do it when listing documents. However\n \/\/ it does mean that reloading the client may cause a dirty\n \/\/ document to become clean (if the contents are identical\n \/\/ to what's on disk).\n error = doc.updateDirty();\n if (error)\n LOG_ERROR(error);\n\n json::Object jsonDoc ;\n doc.writeToJson(&jsonDoc);\n pJsonDocs->push_back(jsonDoc);\n }\n \n return Success();\n}\n \nError initialize()\n{\n \/\/ make sure the source database exists\n return source_database::path().ensureDirectory();\n}\n\n} \/\/ namespace source_database\n} \/\/ namesapce session\n\n<|endoftext|>"} {"text":"<commit_before>\/\/------------------------------------------------------------------------------\n\/\/ CLING - the C++ LLVM-based InterpreterG :)\n\/\/ version: $Id$\n\/\/ author: Vassil Vassilev <vvasilev@cern.ch>\n\/\/------------------------------------------------------------------------------\n\n#include \"cling\/Interpreter\/InterpreterCallbacks.h\"\n\n#include \"cling\/Interpreter\/Interpreter.h\"\n\n#include \"clang\/Sema\/Sema.h\"\n\nusing namespace clang;\n\nnamespace cling {\n\n \/\/ pin the vtable here\n InterpreterExternalSemaSource::~InterpreterExternalSemaSource() {}\n\n bool InterpreterExternalSemaSource::LookupUnqualified(LookupResult& R, \n Scope* S) {\n if (m_Callbacks)\n return m_Callbacks->LookupObject(R, S);\n \n return false;\n }\n\n InterpreterCallbacks::InterpreterCallbacks(Interpreter* interp,\n InterpreterExternalSemaSource* IESS)\n : m_Interpreter(interp), m_SemaExternalSource(IESS) {\n if (!IESS)\n m_SemaExternalSource.reset(new InterpreterExternalSemaSource(this));\n }\n\n \/\/ pin the vtable here\n InterpreterCallbacks::~InterpreterCallbacks() {}\n\n bool InterpreterCallbacks::LookupObject(LookupResult&, Scope*) {\n return false;\n }\n\n} \/\/ end namespace cling\n\n\/\/ TODO: Make the build system in the testsuite aware how to build that class\n\/\/ and extract it out there again.\n#include \"DynamicLookup.h\"\n#include \"cling\/Utils\/AST.h\"\n\n#include \"clang\/Sema\/Lookup.h\"\n#include \"clang\/Lex\/Preprocessor.h\"\n#include \"clang\/Sema\/Scope.h\"\nnamespace cling {\nnamespace test {\n TestProxy* Tester = 0;\n\n extern \"C\" int printf(const char* fmt, ...);\n TestProxy::TestProxy(){}\n int TestProxy::Draw(){ return 12; }\n const char* TestProxy::getVersion(){ return \"Interpreter.cpp\"; }\n\n int TestProxy::Add10(int num) { return num + 10;}\n\n int TestProxy::Add(int a, int b) {\n return a + b;\n }\n\n void TestProxy::PrintString(std::string s) { printf(\"%s\\n\", s.c_str()); }\n\n bool TestProxy::PrintArray(int a[], size_t size) {\n for (unsigned i = 0; i < size; ++i)\n printf(\"%i\", a[i]);\n\n printf(\"%s\", \"\\n\");\n\n return true;\n }\n\n void TestProxy::PrintArray(float a[][5], size_t size) {\n for (unsigned i = 0; i < size; ++i)\n for (unsigned j = 0; j < 5; ++j)\n printf(\"%i\", (int)a[i][j]);\n\n printf(\"%s\", \"\\n\");\n }\n\n void TestProxy::PrintArray(int a[][4][5], size_t size) {\n for (unsigned i = 0; i < size; ++i)\n for (unsigned j = 0; j < 4; ++j)\n for (unsigned k = 0; k < 5; ++k)\n printf(\"%i\", a[i][j][k]);\n\n printf(\"%s\", \"\\n\");\n }\n\n SymbolResolverCallback::SymbolResolverCallback(Interpreter* interp)\n : InterpreterCallbacks(interp, new DynamicIDHandler(this)), m_TesterDecl(0) {\n m_Interpreter->process(\"cling::test::Tester = new cling::test::TestProxy();\");\n }\n\n SymbolResolverCallback::~SymbolResolverCallback() { }\n\n bool SymbolResolverCallback::LookupObject(LookupResult& R, Scope* S) {\n if (!IsDynamicLookup(R, S))\n return false;\n\n \/\/ Only for demo resolve all unknown objects to cling::test::Tester\n if (!m_TesterDecl) {\n clang::Sema& S = m_Interpreter->getSema();\n clang::NamespaceDecl* NSD = utils::Lookup::Namespace(&S, \"cling\");\n NSD = utils::Lookup::Namespace(&S, \"test\", NSD);\n m_TesterDecl = utils::Lookup::Named(&S, \"Tester\", NSD);\n }\n assert (m_TesterDecl && \"Tester not found!\");\n R.addDecl(m_TesterDecl);\n return true;\n }\n\n bool SymbolResolverCallback::IsDynamicLookup(LookupResult& R, Scope* S) {\n if (R.getLookupKind() != Sema::LookupOrdinaryName) return false;\n if (R.isForRedeclaration()) return false;\n \/\/ FIXME: Figure out better way to handle:\n \/\/ C++ [basic.lookup.classref]p1:\n \/\/ In a class member access expression (5.2.5), if the . or -> token is\n \/\/ immediately followed by an identifier followed by a <, the\n \/\/ identifier must be looked up to determine whether the < is the\n \/\/ beginning of a template argument list (14.2) or a less-than operator.\n \/\/ The identifier is first looked up in the class of the object\n \/\/ expression. If the identifier is not found, it is then looked up in\n \/\/ the context of the entire postfix-expression and shall name a class\n \/\/ or function template.\n \/\/\n \/\/ We want to ignore object(.|->)member<template>\n if (R.getSema().PP.LookAhead(0).getKind() == tok::less)\n \/\/ TODO: check for . or -> in the cached token stream\n return false;\n\n for (Scope* DepScope = S; DepScope; DepScope = DepScope->getParent()) {\n if (DeclContext* Ctx = static_cast<DeclContext*>(DepScope->getEntity())) {\n return !Ctx->isDependentContext();\n }\n }\n\n return true;\n }\n\n\n} \/\/ end test\n} \/\/ end cling\n<commit_msg>Silence coverity #47876.<commit_after>\/\/------------------------------------------------------------------------------\n\/\/ CLING - the C++ LLVM-based InterpreterG :)\n\/\/ version: $Id$\n\/\/ author: Vassil Vassilev <vvasilev@cern.ch>\n\/\/------------------------------------------------------------------------------\n\n#include \"cling\/Interpreter\/InterpreterCallbacks.h\"\n\n#include \"cling\/Interpreter\/Interpreter.h\"\n\n#include \"clang\/Sema\/Sema.h\"\n\nusing namespace clang;\n\nnamespace cling {\n\n \/\/ pin the vtable here\n InterpreterExternalSemaSource::~InterpreterExternalSemaSource() {}\n\n bool InterpreterExternalSemaSource::LookupUnqualified(LookupResult& R, \n Scope* S) {\n if (m_Callbacks)\n return m_Callbacks->LookupObject(R, S);\n \n return false;\n }\n\n InterpreterCallbacks::InterpreterCallbacks(Interpreter* interp,\n InterpreterExternalSemaSource* IESS)\n : m_Interpreter(interp), m_SemaExternalSource(IESS) {\n if (!IESS)\n m_SemaExternalSource.reset(new InterpreterExternalSemaSource(this));\n }\n\n \/\/ pin the vtable here\n InterpreterCallbacks::~InterpreterCallbacks() {}\n\n bool InterpreterCallbacks::LookupObject(LookupResult&, Scope*) {\n return false;\n }\n\n} \/\/ end namespace cling\n\n\/\/ TODO: Make the build system in the testsuite aware how to build that class\n\/\/ and extract it out there again.\n#include \"DynamicLookup.h\"\n#include \"cling\/Utils\/AST.h\"\n\n#include \"clang\/Sema\/Lookup.h\"\n#include \"clang\/Lex\/Preprocessor.h\"\n#include \"clang\/Sema\/Scope.h\"\nnamespace cling {\nnamespace test {\n TestProxy* Tester = 0;\n\n extern \"C\" int printf(const char* fmt, ...);\n TestProxy::TestProxy(){}\n int TestProxy::Draw(){ return 12; }\n const char* TestProxy::getVersion(){ return \"Interpreter.cpp\"; }\n\n int TestProxy::Add10(int num) { return num + 10;}\n\n int TestProxy::Add(int a, int b) {\n return a + b;\n }\n\n void TestProxy::PrintString(std::string s) { printf(\"%s\\n\", s.c_str()); }\n\n bool TestProxy::PrintArray(int a[], size_t size) {\n for (unsigned i = 0; i < size; ++i)\n printf(\"%i\", a[i]);\n\n printf(\"%s\", \"\\n\");\n\n return true;\n }\n\n void TestProxy::PrintArray(float a[][5], size_t size) {\n for (unsigned i = 0; i < size; ++i)\n for (unsigned j = 0; j < 5; ++j)\n printf(\"%i\", (int)a[i][j]);\n\n printf(\"%s\", \"\\n\");\n }\n\n void TestProxy::PrintArray(int a[][4][5], size_t size) {\n for (unsigned i = 0; i < size; ++i)\n for (unsigned j = 0; j < 4; ++j)\n for (unsigned k = 0; k < 5; ++k)\n printf(\"%i\", a[i][j][k]);\n\n printf(\"%s\", \"\\n\");\n }\n\n SymbolResolverCallback::SymbolResolverCallback(Interpreter* interp)\n : InterpreterCallbacks(interp, new DynamicIDHandler(this)), m_TesterDecl(0) {\n m_Interpreter->process(\"cling::test::Tester = new cling::test::TestProxy();\");\n }\n\n SymbolResolverCallback::~SymbolResolverCallback() { }\n\n bool SymbolResolverCallback::LookupObject(LookupResult& R, Scope* S) {\n if (!IsDynamicLookup(R, S))\n return false;\n\n \/\/ Only for demo resolve all unknown objects to cling::test::Tester\n if (!m_TesterDecl) {\n clang::Sema& SemaRef = m_Interpreter->getSema();\n clang::NamespaceDecl* NSD = utils::Lookup::Namespace(&SemaRef, \"cling\");\n NSD = utils::Lookup::Namespace(&SemaRef, \"test\", NSD);\n m_TesterDecl = utils::Lookup::Named(&SemaRef, \"Tester\", NSD);\n }\n assert (m_TesterDecl && \"Tester not found!\");\n R.addDecl(m_TesterDecl);\n return true;\n }\n\n bool SymbolResolverCallback::IsDynamicLookup(LookupResult& R, Scope* S) {\n if (R.getLookupKind() != Sema::LookupOrdinaryName) return false;\n if (R.isForRedeclaration()) return false;\n \/\/ FIXME: Figure out better way to handle:\n \/\/ C++ [basic.lookup.classref]p1:\n \/\/ In a class member access expression (5.2.5), if the . or -> token is\n \/\/ immediately followed by an identifier followed by a <, the\n \/\/ identifier must be looked up to determine whether the < is the\n \/\/ beginning of a template argument list (14.2) or a less-than operator.\n \/\/ The identifier is first looked up in the class of the object\n \/\/ expression. If the identifier is not found, it is then looked up in\n \/\/ the context of the entire postfix-expression and shall name a class\n \/\/ or function template.\n \/\/\n \/\/ We want to ignore object(.|->)member<template>\n if (R.getSema().PP.LookAhead(0).getKind() == tok::less)\n \/\/ TODO: check for . or -> in the cached token stream\n return false;\n\n for (Scope* DepScope = S; DepScope; DepScope = DepScope->getParent()) {\n if (DeclContext* Ctx = static_cast<DeclContext*>(DepScope->getEntity())) {\n return !Ctx->isDependentContext();\n }\n }\n\n return true;\n }\n\n\n} \/\/ end test\n} \/\/ end cling\n<|endoftext|>"} {"text":"<commit_before>\n\/\/ Copyright (c) 2015 Pierre MOULON.\n\n\/\/ This Source Code Form is subject to the terms of the Mozilla Public\n\/\/ License, v. 2.0. If a copy of the MPL was not distributed with this\n\/\/ file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n\n\n#include \"openMVG\/sfm\/sfm_data.hpp\"\n#include \"openMVG\/sfm\/sfm_data_io.hpp\"\n#include \"openMVG\/image\/image_io.hpp\"\n#include \"openMVG\/stl\/stl.hpp\"\n\n#include \"third_party\/progress\/progress.hpp\"\n\nnamespace openMVG {\nnamespace sfm {\n\nusing namespace openMVG::geometry;\nusing namespace openMVG::cameras;\nusing namespace openMVG::image;\n\n\n\/\/\/ Find the color of the SfM_Data Landmarks\/structure\nbool ColorizeTracks( SfM_Data & sfm_data )\n{\n \/\/ Colorize each track\n \/\/ Start with the most representative image\n \/\/ and iterate to provide a color to each 3D point\n\n std::vector<Vec3> vec_3dPoints;\n std::vector<Vec3> vec_tracksColor;\n\n C_Progress_display my_progress_bar(sfm_data.GetLandmarks().size(),\n std::cout,\n \"\\nCompute scene structure color\\n\");\n\n vec_3dPoints.resize(sfm_data.GetLandmarks().size());\n\n \/\/Build a list of contiguous index for the trackIds\n std::map<IndexT, IndexT> trackIds_to_contiguousIndexes;\n IndexT cpt = 0;\n for (Landmarks::const_iterator it = sfm_data.GetLandmarks().begin();\n it != sfm_data.GetLandmarks().end(); ++it, ++cpt)\n {\n trackIds_to_contiguousIndexes[it->first] = cpt;\n vec_3dPoints[cpt] = it->second.X;\n }\n\n \/\/ The track list that will be colored (point removed during the process)\n std::set<IndexT> remainingTrackToColor;\n std::transform(sfm_data.GetLandmarks().begin(), sfm_data.GetLandmarks().end(),\n std::inserter(remainingTrackToColor, remainingTrackToColor.begin()),\n stl::RetrieveKey());\n \n while( !remainingTrackToColor.empty() )\n {\n \/\/ Find the most representative image (for the remaining 3D points)\n \/\/ a. Count the number of observation per view for each 3Dpoint Index\n \/\/ b. Sort to find the most representative view index\n\n std::map<IndexT, IndexT> map_IndexCardinal; \/\/ ViewId, Cardinal\n for (std::set<IndexT>::const_iterator\n iterT = remainingTrackToColor.begin();\n iterT != remainingTrackToColor.end();\n ++iterT)\n {\n const size_t trackId = *iterT;\n const Observations & obs = sfm_data.GetLandmarks().at(trackId).obs;\n for( Observations::const_iterator iterObs = obs.begin();\n iterObs != obs.end(); ++iterObs)\n {\n const size_t viewId = iterObs->first;\n if (map_IndexCardinal.find(viewId) == map_IndexCardinal.end())\n map_IndexCardinal[viewId] = 1;\n else\n ++map_IndexCardinal[viewId];\n }\n }\n\n \/\/ Find the View index that is the most represented\n std::vector<IndexT> vec_cardinal;\n std::transform(map_IndexCardinal.begin(),\n map_IndexCardinal.end(),\n std::back_inserter(vec_cardinal),\n stl::RetrieveValue());\n using namespace stl::indexed_sort;\n std::vector< sort_index_packet_descend< IndexT, IndexT> > packet_vec(vec_cardinal.size());\n sort_index_helper(packet_vec, &vec_cardinal[0], 1);\n\n \/\/ First image index with the most of occurrence\n std::map<IndexT, IndexT>::const_iterator iterTT = map_IndexCardinal.begin();\n std::advance(iterTT, packet_vec[0].index);\n const size_t view_index = iterTT->first;\n const View * view = sfm_data.GetViews().at(view_index).get();\n const std::string sView_filename = stlplus::create_filespec(sfm_data.s_root_path,\n view->s_Img_path);\n Image<RGBColor> image;\n if(!ReadImage(sView_filename.c_str(), &image))\n {\n std::cerr << \"Unable to read image: \" << sView_filename << std::endl;\n return false;\n }\n\n \/\/ Iterate through the remaining track to color\n \/\/ - look if the current view is present to color the track\n std::set<IndexT> set_toRemove;\n for (std::set<IndexT>::const_iterator\n iterT = remainingTrackToColor.begin();\n iterT != remainingTrackToColor.end();\n ++iterT)\n {\n const size_t trackId = *iterT;\n const Observations & obs = sfm_data.GetLandmarks().at(trackId).obs;\n Observations::const_iterator it = obs.find(view_index);\n\n if (it != obs.end())\n {\n \/\/ Color the track\n const Vec2 & pt = it->second.x;\n sfm_data.structure.at(trackId).rgb = image(pt.y(), pt.x());\n set_toRemove.insert(trackId);\n ++my_progress_bar;\n }\n }\n \/\/ Remove colored track\n for (std::set<IndexT>::const_iterator iter = set_toRemove.begin();\n iter != set_toRemove.end(); ++iter)\n {\n remainingTrackToColor.erase(*iter);\n }\n }\n return true;\n}\n\n} \/\/ namespace sfm\n} \/\/ namespace openMVG\n<commit_msg>[sfm] colorize tracks: clamp pixel coordinates because feature\/marker centers could be outside the image<commit_after>\n\/\/ Copyright (c) 2015 Pierre MOULON.\n\n\/\/ This Source Code Form is subject to the terms of the Mozilla Public\n\/\/ License, v. 2.0. If a copy of the MPL was not distributed with this\n\/\/ file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n\n\n#include \"openMVG\/sfm\/sfm_data.hpp\"\n#include \"openMVG\/sfm\/sfm_data_io.hpp\"\n#include \"openMVG\/image\/image_io.hpp\"\n#include \"openMVG\/stl\/stl.hpp\"\n\n#include \"third_party\/progress\/progress.hpp\"\n\nnamespace openMVG {\nnamespace sfm {\n\nusing namespace openMVG::geometry;\nusing namespace openMVG::cameras;\nusing namespace openMVG::image;\n\n\n\/\/\/ Find the color of the SfM_Data Landmarks\/structure\nbool ColorizeTracks( SfM_Data & sfm_data )\n{\n \/\/ Colorize each track\n \/\/ Start with the most representative image\n \/\/ and iterate to provide a color to each 3D point\n\n std::vector<Vec3> vec_3dPoints;\n std::vector<Vec3> vec_tracksColor;\n\n C_Progress_display my_progress_bar(sfm_data.GetLandmarks().size(),\n std::cout,\n \"\\nCompute scene structure color\\n\");\n\n vec_3dPoints.resize(sfm_data.GetLandmarks().size());\n\n \/\/Build a list of contiguous index for the trackIds\n std::map<IndexT, IndexT> trackIds_to_contiguousIndexes;\n IndexT cpt = 0;\n for (Landmarks::const_iterator it = sfm_data.GetLandmarks().begin();\n it != sfm_data.GetLandmarks().end(); ++it, ++cpt)\n {\n trackIds_to_contiguousIndexes[it->first] = cpt;\n vec_3dPoints[cpt] = it->second.X;\n }\n\n \/\/ The track list that will be colored (point removed during the process)\n std::set<IndexT> remainingTrackToColor;\n std::transform(sfm_data.GetLandmarks().begin(), sfm_data.GetLandmarks().end(),\n std::inserter(remainingTrackToColor, remainingTrackToColor.begin()),\n stl::RetrieveKey());\n \n while( !remainingTrackToColor.empty() )\n {\n \/\/ Find the most representative image (for the remaining 3D points)\n \/\/ a. Count the number of observation per view for each 3Dpoint Index\n \/\/ b. Sort to find the most representative view index\n\n std::map<IndexT, IndexT> map_IndexCardinal; \/\/ ViewId, Cardinal\n for (std::set<IndexT>::const_iterator\n iterT = remainingTrackToColor.begin();\n iterT != remainingTrackToColor.end();\n ++iterT)\n {\n const size_t trackId = *iterT;\n const Observations & obs = sfm_data.GetLandmarks().at(trackId).obs;\n for( Observations::const_iterator iterObs = obs.begin();\n iterObs != obs.end(); ++iterObs)\n {\n const size_t viewId = iterObs->first;\n if (map_IndexCardinal.find(viewId) == map_IndexCardinal.end())\n map_IndexCardinal[viewId] = 1;\n else\n ++map_IndexCardinal[viewId];\n }\n }\n\n \/\/ Find the View index that is the most represented\n std::vector<IndexT> vec_cardinal;\n std::transform(map_IndexCardinal.begin(),\n map_IndexCardinal.end(),\n std::back_inserter(vec_cardinal),\n stl::RetrieveValue());\n using namespace stl::indexed_sort;\n std::vector< sort_index_packet_descend< IndexT, IndexT> > packet_vec(vec_cardinal.size());\n sort_index_helper(packet_vec, &vec_cardinal[0], 1);\n\n \/\/ First image index with the most of occurrence\n std::map<IndexT, IndexT>::const_iterator iterTT = map_IndexCardinal.begin();\n std::advance(iterTT, packet_vec[0].index);\n const size_t view_index = iterTT->first;\n const View * view = sfm_data.GetViews().at(view_index).get();\n const std::string sView_filename = stlplus::create_filespec(sfm_data.s_root_path,\n view->s_Img_path);\n Image<RGBColor> image;\n if(!ReadImage(sView_filename.c_str(), &image))\n {\n std::cerr << \"Unable to read image: \" << sView_filename << std::endl;\n return false;\n }\n\n \/\/ Iterate through the remaining track to color\n \/\/ - look if the current view is present to color the track\n std::set<IndexT> set_toRemove;\n for (std::set<IndexT>::const_iterator\n iterT = remainingTrackToColor.begin();\n iterT != remainingTrackToColor.end();\n ++iterT)\n {\n const size_t trackId = *iterT;\n const Observations & obs = sfm_data.GetLandmarks().at(trackId).obs;\n Observations::const_iterator it = obs.find(view_index);\n\n if (it != obs.end())\n {\n \/\/ Color the track\n Vec2 pt = it->second.x;\n \/\/ Clamp the pixel position if the feature\/marker center is outside the image.\n pt.x() = clamp(pt.x(), 0.0, double(image.Width()-1));\n pt.y() = clamp(pt.y(), 0.0, double(image.Height()-1));\n sfm_data.structure.at(trackId).rgb = image(pt.y(), pt.x());\n set_toRemove.insert(trackId);\n ++my_progress_bar;\n }\n }\n \/\/ Remove colored track\n for (std::set<IndexT>::const_iterator iter = set_toRemove.begin();\n iter != set_toRemove.end(); ++iter)\n {\n remainingTrackToColor.erase(*iter);\n }\n }\n return true;\n}\n\n} \/\/ namespace sfm\n} \/\/ namespace openMVG\n<|endoftext|>"} {"text":"<commit_before>#include <QMessageBox>\n#include <QCloseEvent>\n#include <QSettings>\n#include <QFile>\n#include <QMenu>\n#include <QTreeWidget>\n\n#include \"about.h\"\n#include \"settings.h\"\n#include \"ipobjects.h\"\n#include \"messenger.h\"\n#include \"messagedialog.h\"\n#include \"qommunicate.h\"\n\nQommunicate::Qommunicate(QWidget *parent)\n : QMainWindow(parent)\n{\n ui.setupUi(this);\n \n createTrayIcon();\n \n MemberUtils::init();\n populateTree(); \n firstRun();\n messenger()->login();\n \n connect(qApp, SIGNAL(aboutToQuit()), this, SLOT(cleanup()));\n \n connect(messenger(), SIGNAL(msg_ansEntry(Message)), this, SLOT(addMember(Message)));\n connect(messenger(), SIGNAL(msg_entry(Message)), this, SLOT(addMemberAndAnswer(Message)));\n connect(messenger(), SIGNAL(msg_exit(Message)), this, SLOT(removeMember(Message)));\n connect(messenger(), SIGNAL(msg_recvMsg(Message)), this, SLOT(openDialog(Message)));\n connect(messenger(), SIGNAL(msg_getAbsenceInfo(Message)), this, SLOT(sendAbsenceInfo(Message)));\n}\n\nvoid Qommunicate::on_searchEdit_textChanged(const QString &text)\n{\n filterModel->setFilterFixedString(text);\n ui.memberTree->expandAll();\n}\n\nvoid Qommunicate::on_action_About_triggered()\n{\n AboutDialog(this).exec();\n}\n\nvoid Qommunicate::on_action_Settings_triggered()\n{\n SettingsDialog(this).exec();\n}\n\nvoid Qommunicate::on_actionMulticast_triggered()\n{\n MessageDialog dlg(this);\n dlg.exec();\n}\n\nvoid Qommunicate::on_actionQuit_triggered()\n{\n qApp->quit();\n}\n\nvoid Qommunicate::closeEvent(QCloseEvent * event)\n{\n setVisible(false);\n event->ignore();\n}\n\nvoid Qommunicate::iconActivated(QSystemTrayIcon::ActivationReason reason)\n{\n if( reason == QSystemTrayIcon::Trigger )\n setVisible(!isVisible());\n}\n\nvoid Qommunicate::createTrayIcon()\n{ \n trayIcon = new QSystemTrayIcon(this);\n trayIcon->setIcon(windowIcon());\n \n connect(trayIcon, SIGNAL(activated(QSystemTrayIcon::ActivationReason)), this, SLOT(iconActivated(QSystemTrayIcon::ActivationReason)));\n \n QMenu *menu = new QMenu;\n menu->addAction(ui.actionMulticast);\n menu->addAction(ui.actionQuit);\n trayIcon->setContextMenu(menu);\n \n trayIcon->show();\n}\n\nvoid Qommunicate::populateTree()\n{\n model = new MemberModel(this);\n filterModel = new MemberFilter(this);\n \n filterModel->setSourceModel(model);\n filterModel->setDynamicSortFilter(true);\n \n ui.memberTree->setSelectionMode(ui.memberTree->ExtendedSelection);\n ui.memberTree->setModel(filterModel);\n ui.memberTree->setHeaderHidden(true);\n ui.memberTree->setAcceptDrops(true);\n ui.memberTree->setExpandsOnDoubleClick(false);\n ui.memberTree->expandAll();\n}\n\n\/*\nIf item is a group, adds all submembers to receivers and returns true.\notherwise assumes item is a member, inserts in receivers and returns false\n*\/\nbool Qommunicate::createGroupMemberList(QStandardItem* item, QSet<Member*>& receivers)\n{\n if(item->type() == TYPE_GROUP)\n {\n if(!item->hasChildren())\n return true;\n \n for(int i = 0; i < item->rowCount(); i++)\n {\n receivers << (Member*)item->child(i, 0);\n }\n return true;\n }\n receivers << (Member*)item;\n return false;\n}\n\nvoid Qommunicate::on_memberTree_doubleClicked(const QModelIndex& proxyIndex)\n{\n \n MessageDialog* dlg;\n QSet<Member*> receivers;\n \n MemberModel* model = (MemberModel*) ( (MemberFilter*) ui.memberTree->model() )->sourceModel();\n QModelIndex index = ((MemberFilter*)ui.memberTree->model())->mapToSource(proxyIndex);\n \n if(index.isValid())\n {\n \/\/ only single item clicked\n createGroupMemberList(model->itemFromIndex(index), receivers);\n }\n else\n {\n QModelIndex i;\n foreach(i, ui.memberTree->selectionModel()->selectedRows())\n { \n QStandardItem* item = model->itemFromIndex(((MemberFilter*)ui.memberTree->model())->mapToSource(i));\n createGroupMemberList(item, receivers);\n }\n }\n \n if(receivers.isEmpty())\n return;\n \n QList<Member*> toDialog = receivers.toList();\n if(toDialog.size() == 1 && MemberUtils::contains(\"open_conversations\", toDialog[0]))\n return;\n \n if(toDialog.size() == 1)\n {\n if(!MemberUtils::contains(\"open_conversations\", toDialog[0]))\n dlg = new MessageDialog( toDialog[0], this );\n }\n else\n dlg = new MessageDialog( toDialog, this );\n \n dlg->setModal(false);\n dlg->show();\n}\n\nvoid Qommunicate::on_statusCombo_currentIndexChanged(const QString& text)\n{\n messenger()->multicast(QOM_BR_ABSENCE, me().name().toAscii()+'\\0'+myGroup().name().toAscii());\n}\n\nvoid Qommunicate::keyPressEvent(QKeyEvent *event)\n{\n if(event->key() == Qt::Key_Return) {\n event->accept();\n on_memberTree_doubleClicked(QModelIndex());\n return;\n }\n event->ignore();\n}\n\nvoid Qommunicate::firstRun()\n{\n QSettings s;\n if( ! s.contains(tr(\"nick\")) )\n ui.action_Settings->trigger();\n}\n\nvoid Qommunicate::dialogOpened(Member* m)\n{\n MemberUtils::insert(\"open_conversations\", m);\n}\n\nvoid Qommunicate::dialogClosed(Member *m)\n{\n MemberUtils::remove(\"open_conversations\", m);\n}\n\nvoid Qommunicate::cleanup()\n{\n messenger()->logout();\n delete messenger();\n}\n\n\/\/ Message handling slots\nvoid Qommunicate::addMember(Message msg)\n{\n if(MemberUtils::contains(\"members_list\", msg.sender()))\n return;\n \n QList<QByteArray> tokens = msg.payload().split('\\a');\n msg.sender()->setName(tokens[0]);\n \n QString groupName;\n if(tokens.size() > 1)\n groupName = tokens[1];\n \n if(groupName.isEmpty())\n {\n model->appendRow(msg.sender());\n }\n else\n {\n QList<QStandardItem*> matches = model->findItems(groupName);\n if(!matches.isEmpty() && matches[0]->type() == TYPE_GROUP)\n {\n matches[0]->appendRow(msg.sender());\n }\n else\n {\n Group * group = new Group(groupName);\n group->appendRow(msg.sender());\n model->appendRow(group);\n }\n }\n \n MemberUtils::insert(\"members_list\", msg.sender());\n \n}\n\nvoid Qommunicate::addMemberAndAnswer(Message msg)\n{\n addMember(msg);\n messenger()->sendMessage(QOM_ANSENTRY, (me().name()+'\\0'+myGroup().name()).toAscii(), msg.sender());\n}\n\nvoid Qommunicate::removeMember(Message msg)\n{\n QList<QByteArray> tokens = msg.payload().split('\\a');\n QString groupName;\n if(tokens.size() > 1)\n groupName = tokens[1];\n \n for(int i = 0; i < model->rowCount(); i++)\n {\n QStandardItem* it = model->item(i, 0);\n if(it->type() == TYPE_MEMBER && ((Member*)it)->name() == msg.sender()->addressString())\n {\n model->removeRow(it->row());\n }\n else\n {\n for(int j = 0; j < it->rowCount(); j++)\n {\n if(((Member*)it->child(j))->addressString() == msg.sender()->addressString())\n it->removeRow(j);\n }\n if(it->rowCount() == 0)\n model->removeRow(it->row());\n } \n }\n MemberUtils::remove(\"members_list\", msg.sender()->addressString());\n}\n\nvoid Qommunicate::openDialog(Message msg)\n{\n if(MemberUtils::contains(\"open_conversations\", msg.sender()))\n return;\n \n Member* with = MemberUtils::get(\"members_list\", msg.sender());\n if(!with->isValid())\n with = msg.sender();\n MessageDialog *dlg = new MessageDialog(with, this);\n dlg->setModal(false);\n dlg->show();\n dlg->incomingMessage(msg);\n}\n\nvoid Qommunicate::sendAbsenceInfo(Message msg)\n{\n QString payload = ui.statusCombo->currentText();\n if(payload == tr(\"Available\"))\n payload = \"Not absence mode\";\n messenger()->multicast(QOM_SENDABSENCEINFO, payload.toAscii());\n}\n <commit_msg>Added ignore feature<commit_after>#include <QMessageBox>\n#include <QCloseEvent>\n#include <QSettings>\n#include <QFile>\n#include <QMenu>\n#include <QTreeWidget>\n\n#include \"about.h\"\n#include \"settings.h\"\n#include \"ipobjects.h\"\n#include \"messenger.h\"\n#include \"messagedialog.h\"\n#include \"qommunicate.h\"\n\nQommunicate::Qommunicate(QWidget *parent)\n : QMainWindow(parent)\n{\n ui.setupUi(this);\n \n createTrayIcon();\n \n MemberUtils::init();\n populateTree(); \n firstRun();\n messenger()->login();\n \n connect(qApp, SIGNAL(aboutToQuit()), this, SLOT(cleanup()));\n \n connect(messenger(), SIGNAL(msg_ansEntry(Message)), this, SLOT(addMember(Message)));\n connect(messenger(), SIGNAL(msg_entry(Message)), this, SLOT(addMemberAndAnswer(Message)));\n connect(messenger(), SIGNAL(msg_exit(Message)), this, SLOT(removeMember(Message)));\n connect(messenger(), SIGNAL(msg_recvMsg(Message)), this, SLOT(openDialog(Message)));\n connect(messenger(), SIGNAL(msg_getAbsenceInfo(Message)), this, SLOT(sendAbsenceInfo(Message)));\n}\n\nvoid Qommunicate::on_searchEdit_textChanged(const QString &text)\n{\n filterModel->setFilterFixedString(text);\n ui.memberTree->expandAll();\n}\n\nvoid Qommunicate::on_action_About_triggered()\n{\n AboutDialog(this).exec();\n}\n\nvoid Qommunicate::on_action_Settings_triggered()\n{\n SettingsDialog(this).exec();\n}\n\nvoid Qommunicate::on_actionMulticast_triggered()\n{\n MessageDialog dlg(this);\n dlg.exec();\n}\n\nvoid Qommunicate::on_actionQuit_triggered()\n{\n qApp->quit();\n}\n\nvoid Qommunicate::closeEvent(QCloseEvent * event)\n{\n setVisible(false);\n event->ignore();\n}\n\nvoid Qommunicate::iconActivated(QSystemTrayIcon::ActivationReason reason)\n{\n if( reason == QSystemTrayIcon::Trigger )\n setVisible(!isVisible());\n}\n\nvoid Qommunicate::createTrayIcon()\n{ \n trayIcon = new QSystemTrayIcon(this);\n trayIcon->setIcon(windowIcon());\n \n connect(trayIcon, SIGNAL(activated(QSystemTrayIcon::ActivationReason)), this, SLOT(iconActivated(QSystemTrayIcon::ActivationReason)));\n \n QMenu *menu = new QMenu;\n menu->addAction(ui.actionMulticast);\n menu->addAction(ui.actionQuit);\n trayIcon->setContextMenu(menu);\n \n trayIcon->show();\n}\n\nvoid Qommunicate::populateTree()\n{\n model = new MemberModel(this);\n filterModel = new MemberFilter(this);\n \n filterModel->setSourceModel(model);\n filterModel->setDynamicSortFilter(true);\n \n ui.memberTree->setSelectionMode(ui.memberTree->ExtendedSelection);\n ui.memberTree->setModel(filterModel);\n ui.memberTree->setHeaderHidden(true);\n ui.memberTree->setAcceptDrops(true);\n ui.memberTree->setExpandsOnDoubleClick(false);\n ui.memberTree->expandAll();\n}\n\n\/*\nIf item is a group, adds all submembers to receivers and returns true.\notherwise assumes item is a member, inserts in receivers and returns false\n*\/\nbool Qommunicate::createGroupMemberList(QStandardItem* item, QSet<Member*>& receivers)\n{\n if(item->type() == TYPE_GROUP)\n {\n if(!item->hasChildren())\n return true;\n \n for(int i = 0; i < item->rowCount(); i++)\n {\n receivers << (Member*)item->child(i, 0);\n }\n return true;\n }\n receivers << (Member*)item;\n return false;\n}\n\nvoid Qommunicate::on_memberTree_doubleClicked(const QModelIndex& proxyIndex)\n{\n \n MessageDialog* dlg;\n QSet<Member*> receivers;\n \n MemberModel* model = (MemberModel*) ( (MemberFilter*) ui.memberTree->model() )->sourceModel();\n QModelIndex index = ((MemberFilter*)ui.memberTree->model())->mapToSource(proxyIndex);\n \n if(index.isValid())\n {\n \/\/ only single item clicked\n createGroupMemberList(model->itemFromIndex(index), receivers);\n }\n else\n {\n QModelIndex i;\n foreach(i, ui.memberTree->selectionModel()->selectedRows())\n { \n QStandardItem* item = model->itemFromIndex(((MemberFilter*)ui.memberTree->model())->mapToSource(i));\n createGroupMemberList(item, receivers);\n }\n }\n \n if(receivers.isEmpty())\n return;\n \n QList<Member*> toDialog = receivers.toList();\n if(toDialog.size() == 1 && MemberUtils::contains(\"open_conversations\", toDialog[0]))\n return;\n \n if(toDialog.size() == 1)\n {\n if(!MemberUtils::contains(\"open_conversations\", toDialog[0]))\n dlg = new MessageDialog( toDialog[0], this );\n }\n else\n dlg = new MessageDialog( toDialog, this );\n \n dlg->setModal(false);\n dlg->show();\n}\n\nvoid Qommunicate::on_statusCombo_currentIndexChanged(const QString& text)\n{\n messenger()->multicast(QOM_BR_ABSENCE, me().name().toAscii()+'\\0'+myGroup().name().toAscii());\n}\n\nvoid Qommunicate::keyPressEvent(QKeyEvent *event)\n{\n if(event->key() == Qt::Key_Return) {\n event->accept();\n on_memberTree_doubleClicked(QModelIndex());\n return;\n }\n event->ignore();\n}\n\nvoid Qommunicate::firstRun()\n{\n QSettings s;\n if( ! s.contains(tr(\"nick\")) )\n ui.action_Settings->trigger();\n}\n\nvoid Qommunicate::dialogOpened(Member* m)\n{\n MemberUtils::insert(\"open_conversations\", m);\n}\n\nvoid Qommunicate::dialogClosed(Member *m)\n{\n MemberUtils::remove(\"open_conversations\", m);\n}\n\nvoid Qommunicate::cleanup()\n{\n messenger()->logout();\n delete messenger();\n}\n\n\/\/ Message handling slots\nvoid Qommunicate::addMember(Message msg)\n{\n if(MemberUtils::contains(\"members_list\", msg.sender()))\n return;\n \n QList<QByteArray> tokens = msg.payload().split('\\a');\n msg.sender()->setName(tokens[0]);\n \n QString groupName;\n if(tokens.size() > 1)\n groupName = tokens[1];\n \n if(groupName.isEmpty())\n {\n model->appendRow(msg.sender());\n }\n else\n {\n QList<QStandardItem*> matches = model->findItems(groupName);\n if(!matches.isEmpty() && matches[0]->type() == TYPE_GROUP)\n {\n matches[0]->appendRow(msg.sender());\n }\n else\n {\n Group * group = new Group(groupName);\n group->appendRow(msg.sender());\n model->appendRow(group);\n }\n }\n \n MemberUtils::insert(\"members_list\", msg.sender());\n \n}\n\nvoid Qommunicate::addMemberAndAnswer(Message msg)\n{\n addMember(msg);\n messenger()->sendMessage(QOM_ANSENTRY, (me().name()+'\\0'+myGroup().name()).toAscii(), msg.sender());\n}\n\nvoid Qommunicate::removeMember(Message msg)\n{\n QList<QByteArray> tokens = msg.payload().split('\\a');\n QString groupName;\n if(tokens.size() > 1)\n groupName = tokens[1];\n \n for(int i = 0; i < model->rowCount(); i++)\n {\n QStandardItem* it = model->item(i, 0);\n if(it->type() == TYPE_MEMBER && ((Member*)it)->name() == msg.sender()->addressString())\n {\n model->removeRow(it->row());\n }\n else\n {\n for(int j = 0; j < it->rowCount(); j++)\n {\n if(((Member*)it->child(j))->addressString() == msg.sender()->addressString())\n it->removeRow(j);\n }\n if(it->rowCount() == 0)\n model->removeRow(it->row());\n } \n }\n MemberUtils::remove(\"members_list\", msg.sender()->addressString());\n}\n\nvoid Qommunicate::openDialog(Message msg)\n{\n if(MemberUtils::contains(\"open_conversations\", msg.sender()))\n return;\n \n \/\/ if set to ignore received messages\n QSettings s;\n if(s.value(tr(\"no_receive\")).toBool())\n {\n qDebug() << \"Ignoring message\";\n return;\n }\n \n Member* with = MemberUtils::get(\"members_list\", msg.sender());\n if(!with->isValid())\n with = msg.sender();\n MessageDialog *dlg = new MessageDialog(with, this);\n dlg->setModal(false);\n dlg->show();\n dlg->incomingMessage(msg);\n}\n\nvoid Qommunicate::sendAbsenceInfo(Message msg)\n{\n QString payload = ui.statusCombo->currentText();\n if(payload == tr(\"Available\"))\n payload = \"Not absence mode\";\n messenger()->multicast(QOM_SENDABSENCEINFO, payload.toAscii());\n}\n <|endoftext|>"} {"text":"<commit_before>\/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2003 Robert Osfield \n *\n * This library is open source and may be redistributed and\/or modified under \n * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or \n * (at your option) any later version. The full license is in LICENSE file\n * included with this distribution, and on the openscenegraph.org website.\n * \n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the \n * OpenSceneGraph Public License for more details.\n*\/\n#include <osgUtil\/RenderBin>\n#include <osgUtil\/RenderStage>\n\n#include <osg\/Statistics>\n#include <osg\/ImpostorSprite>\n\n#include <algorithm>\n\nusing namespace osg;\nusing namespace osgUtil;\n\n\nclass RenderBinPrototypeList : public osg::Referenced, public std::map< std::string, osg::ref_ptr<RenderBin> > \n{\n public:\n\tRenderBinPrototypeList() {}\n\t~RenderBinPrototypeList() {}\n};\n\n\/\/ register a RenderStage prototype with the RenderBin prototype list.\nRegisterRenderBinProxy s_registerRenderBinProxy(\"RenderBin\",new RenderBin(RenderBin::SORT_BY_STATE));\nRegisterRenderBinProxy s_registerDepthSortedBinProxy(\"DepthSortedBin\",new RenderBin(RenderBin::SORT_BACK_TO_FRONT));\n\n\nRenderBinPrototypeList* renderBinPrototypeList()\n{\n static osg::ref_ptr<RenderBinPrototypeList> s_renderBinPrototypeList = new RenderBinPrototypeList;\n return s_renderBinPrototypeList.get();\n}\n\nRenderBin* RenderBin::getRenderBinPrototype(const std::string& binName)\n{\n RenderBinPrototypeList* list = renderBinPrototypeList();\n if (list)\n {\n RenderBinPrototypeList::iterator itr = list->find(binName);\n if (itr != list->end()) return itr->second.get();\n }\n return NULL;\n}\n\nRenderBin* RenderBin::createRenderBin(const std::string& binName)\n{\n RenderBinPrototypeList* list = renderBinPrototypeList();\n if (list)\n {\n RenderBin* prototype = getRenderBinPrototype(binName);\n if (prototype) return dynamic_cast<RenderBin*>(prototype->clone(osg::CopyOp::DEEP_COPY_ALL));\n }\n return NULL;\n}\n\nvoid RenderBin::addRenderBinPrototype(const std::string& binName,RenderBin* proto)\n{\n RenderBinPrototypeList* list = renderBinPrototypeList();\n if (list && proto)\n {\n (*list)[binName] = proto;\n }\n}\n\nvoid RenderBin::removeRenderBinPrototype(RenderBin* proto)\n{\n RenderBinPrototypeList* list = renderBinPrototypeList();\n if (list && proto)\n {\n RenderBinPrototypeList::iterator itr = list->find(proto->className());\n if (itr != list->end()) list->erase(itr);\n }\n}\n\nRenderBin::RenderBin(SortMode mode)\n{\n _binNum = 0;\n _parent = NULL;\n _stage = NULL;\n _sortMode = mode;\n}\n\nRenderBin::RenderBin(const RenderBin& rhs,const CopyOp& copyop):\n Object(rhs,copyop),\n _binNum(rhs._binNum),\n _parent(rhs._parent),\n _stage(rhs._stage),\n _bins(rhs._bins),\n _renderGraphList(rhs._renderGraphList),\n _renderLeafList(rhs._renderLeafList),\n _sortMode(rhs._sortMode),\n _sortCallback(rhs._sortCallback),\n _drawCallback(rhs._drawCallback)\n{\n\n}\n\nRenderBin::~RenderBin()\n{\n}\n\nvoid RenderBin::reset()\n{\n _renderGraphList.clear();\n _bins.clear();\n}\n\nvoid RenderBin::sort()\n{\n for(RenderBinList::iterator itr = _bins.begin();\n itr!=_bins.end();\n ++itr)\n {\n itr->second->sort();\n }\n \n if (_sortCallback.valid()) \n {\n _sortCallback->sortImplementation(this);\n }\n else sortImplementation();\n}\n\nvoid RenderBin::setSortMode(SortMode mode)\n{\n _sortMode = mode;\n}\n\nvoid RenderBin::sortImplementation()\n{\n switch(_sortMode)\n {\n case(SORT_BY_STATE):\n sortByState();\n break;\n case(SORT_FRONT_TO_BACK):\n sortFrontToBack();\n break;\n case(SORT_BACK_TO_FRONT):\n sortBackToFront();\n break;\n default:\n break;\n }\n}\n\nstruct SortByStateFunctor\n{\n bool operator() (const RenderGraph* lhs,const RenderGraph* rhs) const\n {\n return (*(lhs->_stateset)<*(rhs->_stateset));\n }\n};\n\nvoid RenderBin::sortByState()\n{\n \/\/ actually we'll do nothing right now, as fine grained sorting by state\n \/\/ appears to cost more to do than it saves in draw. The contents of\n \/\/ the RenderGraph leaves is already coasrse grained sorted, this\n \/\/ sorting is as a function of the cull traversal.\n \/\/ cout << \"doing sortByState \"<<this<<endl;\n}\n\nstruct FrontToBackSortFunctor\n{\n bool operator() (const RenderLeaf* lhs,const RenderLeaf* rhs) const\n {\n return (lhs->_depth<rhs->_depth);\n }\n};\n\n \nvoid RenderBin::sortFrontToBack()\n{\n copyLeavesFromRenderGraphListToRenderLeafList();\n\n \/\/ now sort the list into acending depth order.\n std::sort(_renderLeafList.begin(),_renderLeafList.end(),FrontToBackSortFunctor());\n \n\/\/ cout << \"sort front to back\"<<endl;\n}\n\nstruct BackToFrontSortFunctor\n{\n bool operator() (const RenderLeaf* lhs,const RenderLeaf* rhs) const\n {\n return (rhs->_depth<lhs->_depth);\n }\n};\n\nvoid RenderBin::sortBackToFront()\n{\n copyLeavesFromRenderGraphListToRenderLeafList();\n\n \/\/ now sort the list into acending depth order.\n std::sort(_renderLeafList.begin(),_renderLeafList.end(),BackToFrontSortFunctor());\n\n\/\/ cout << \"sort back to front\"<<endl;\n}\n\nvoid RenderBin::copyLeavesFromRenderGraphListToRenderLeafList()\n{\n _renderLeafList.clear();\n\n int totalsize=0;\n RenderGraphList::iterator itr;\n for(itr=_renderGraphList.begin();\n itr!=_renderGraphList.end();\n ++itr)\n {\n totalsize += (*itr)->_leaves.size();\n }\n\n _renderLeafList.reserve(totalsize);\n \n \/\/ first copy all the leaves from the render graphs into the leaf list.\n for(itr=_renderGraphList.begin();\n itr!=_renderGraphList.end();\n ++itr)\n {\n for(RenderGraph::LeafList::iterator dw_itr = (*itr)->_leaves.begin();\n dw_itr != (*itr)->_leaves.end();\n ++dw_itr)\n {\n _renderLeafList.push_back(dw_itr->get());\n }\n }\n \n \/\/ empty the render graph list to prevent it being drawn along side the render leaf list (see drawImplementation.)\n _renderGraphList.clear();\n}\n\nRenderBin* RenderBin::find_or_insert(int binNum,const std::string& binName)\n{\n \/\/ search for appropriate bin.\n RenderBinList::iterator itr = _bins.find(binNum);\n if (itr!=_bins.end()) return itr->second.get();\n\n \/\/ create a renderin bin and insert into bin list.\n RenderBin* rb = RenderBin::createRenderBin(binName);\n if (rb)\n {\n\n RenderStage* rs = dynamic_cast<RenderStage*>(rb);\n if (rs)\n {\n rs->_binNum = binNum;\n rs->_parent = NULL;\n rs->_stage = rs;\n _stage->addToDependencyList(rs);\n }\n else\n {\n rb->_binNum = binNum;\n rb->_parent = this;\n rb->_stage = _stage;\n _bins[binNum] = rb;\n }\n }\n return rb;\n}\n\nvoid RenderBin::draw(osg::State& state,RenderLeaf*& previous)\n{\n if (_drawCallback.valid()) \n {\n _drawCallback->drawImplementation(this,state,previous);\n }\n else drawImplementation(state,previous);\n}\n\nvoid RenderBin::drawImplementation(osg::State& state,RenderLeaf*& previous)\n{\n \/\/ draw first set of draw bins.\n RenderBinList::iterator rbitr;\n for(rbitr = _bins.begin();\n rbitr!=_bins.end() && rbitr->first<0;\n ++rbitr)\n {\n rbitr->second->draw(state,previous);\n }\n \n\n \/\/ draw fine grained ordering.\n for(RenderLeafList::iterator rlitr= _renderLeafList.begin();\n rlitr!= _renderLeafList.end();\n ++rlitr)\n {\n RenderLeaf* rl = *rlitr;\n rl->render(state,previous);\n previous = rl;\n }\n\n\n \/\/ draw coarse grained ordering.\n for(RenderGraphList::iterator oitr=_renderGraphList.begin();\n oitr!=_renderGraphList.end();\n ++oitr)\n {\n\n for(RenderGraph::LeafList::iterator dw_itr = (*oitr)->_leaves.begin();\n dw_itr != (*oitr)->_leaves.end();\n ++dw_itr)\n {\n RenderLeaf* rl = dw_itr->get();\n rl->render(state,previous);\n previous = rl;\n\n }\n }\n\n\n \/\/ draw post bins.\n for(;\n rbitr!=_bins.end();\n ++rbitr)\n {\n rbitr->second->draw(state,previous);\n }\n\n\n}\n\n\/\/ stats\nbool RenderBin::getStats(osg::Statistics* primStats)\n{ \/\/ different by return type - collects the stats in this renderrBin\n bool somestats=false;\n for(RenderGraphList::iterator oitr=_renderGraphList.begin();\n oitr!=_renderGraphList.end();\n ++oitr)\n {\n \n for(RenderGraph::LeafList::iterator dw_itr = (*oitr)->_leaves.begin();\n dw_itr != (*oitr)->_leaves.end();\n ++dw_itr)\n {\n RenderLeaf* rl = dw_itr->get();\n Drawable* dw= rl->_drawable;\n primStats->addDrawable(); \/\/ number of geosets\n if (rl->_modelview.get()) primStats->addMatrix(); \/\/ number of matrices\n if (dw)\n {\n \/\/ then tot up the primtive types and no vertices.\n dw->accept(*primStats); \/\/ use sub-class to find the stats for each drawable\n if (typeid(*dw)==typeid(osg::ImpostorSprite)) primStats->addImpostor(1);\n }\n }\n somestats=true;\n }\n return somestats;\n}\n\nvoid RenderBin::getPrims(osg::Statistics* primStats)\n{\n static int ndepth;\n ndepth++;\n for(RenderBinList::iterator itr = _bins.begin();\n itr!=_bins.end();\n ++itr)\n {\n primStats->addBins(1);\n itr->second->getPrims(primStats);\n }\n getStats(primStats);\n ndepth--;\n\n}\n\nbool RenderBin::getPrims(osg::Statistics* primStats, int nbin)\n{ \/\/ collect stats for array of bins, maximum nbin \n \/\/ (which will be modified on next call if array of primStats is too small);\n \/\/ return 1 for OK;\n static int ndepth;\n bool ok=false;\n ndepth++;\n int nb=primStats[0].getBins();\n if (nb<nbin)\n { \/\/ if statement to protect against writing to bins beyond the maximum seen before\n primStats[nb].setBinNo(nb);\n primStats[nb].setDepth(ndepth);\n getStats(primStats+nb);\n }\n primStats[0].addBins(1);\n for(RenderBinList::iterator itr = _bins.begin();\n itr!=_bins.end();\n ++itr)\n {\n if (itr->second->getPrims(primStats, nbin)) ok = true;\n }\n ok=true;\n ndepth--;\n return ok;\n}\n<commit_msg>Added fallback in RenderBin::createRenderBin(const std::string& binName) which return a new RenderBin when the no prototype is found with className of binName.<commit_after>\/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2003 Robert Osfield \n *\n * This library is open source and may be redistributed and\/or modified under \n * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or \n * (at your option) any later version. The full license is in LICENSE file\n * included with this distribution, and on the openscenegraph.org website.\n * \n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the \n * OpenSceneGraph Public License for more details.\n*\/\n#include <osgUtil\/RenderBin>\n#include <osgUtil\/RenderStage>\n\n#include <osg\/Statistics>\n#include <osg\/ImpostorSprite>\n#include <osg\/Notify>\n\n#include <algorithm>\n\nusing namespace osg;\nusing namespace osgUtil;\n\n\nclass RenderBinPrototypeList : public osg::Referenced, public std::map< std::string, osg::ref_ptr<RenderBin> > \n{\n public:\n\tRenderBinPrototypeList() {}\n\t~RenderBinPrototypeList() {}\n};\n\n\/\/ register a RenderStage prototype with the RenderBin prototype list.\nRegisterRenderBinProxy s_registerRenderBinProxy(\"RenderBin\",new RenderBin(RenderBin::SORT_BY_STATE));\nRegisterRenderBinProxy s_registerDepthSortedBinProxy(\"DepthSortedBin\",new RenderBin(RenderBin::SORT_BACK_TO_FRONT));\n\n\nRenderBinPrototypeList* renderBinPrototypeList()\n{\n static osg::ref_ptr<RenderBinPrototypeList> s_renderBinPrototypeList = new RenderBinPrototypeList;\n return s_renderBinPrototypeList.get();\n}\n\nRenderBin* RenderBin::getRenderBinPrototype(const std::string& binName)\n{\n RenderBinPrototypeList* list = renderBinPrototypeList();\n if (list)\n {\n RenderBinPrototypeList::iterator itr = list->find(binName);\n if (itr != list->end()) return itr->second.get();\n }\n return NULL;\n}\n\nRenderBin* RenderBin::createRenderBin(const std::string& binName)\n{\n RenderBinPrototypeList* list = renderBinPrototypeList();\n if (list)\n {\n RenderBin* prototype = getRenderBinPrototype(binName);\n if (prototype) return dynamic_cast<RenderBin*>(prototype->clone(osg::CopyOp::DEEP_COPY_ALL));\n }\n \n osg::notify(osg::WARN) <<\"Warning: RenderBin \\\"\"<<binName<<\"\\\" implemention not found, using default RenderBin as a fallback.\"<<std::endl;\n return new RenderBin;\n}\n\nvoid RenderBin::addRenderBinPrototype(const std::string& binName,RenderBin* proto)\n{\n RenderBinPrototypeList* list = renderBinPrototypeList();\n if (list && proto)\n {\n (*list)[binName] = proto;\n }\n}\n\nvoid RenderBin::removeRenderBinPrototype(RenderBin* proto)\n{\n RenderBinPrototypeList* list = renderBinPrototypeList();\n if (list && proto)\n {\n RenderBinPrototypeList::iterator itr = list->find(proto->className());\n if (itr != list->end()) list->erase(itr);\n }\n}\n\nRenderBin::RenderBin(SortMode mode)\n{\n _binNum = 0;\n _parent = NULL;\n _stage = NULL;\n _sortMode = mode;\n}\n\nRenderBin::RenderBin(const RenderBin& rhs,const CopyOp& copyop):\n Object(rhs,copyop),\n _binNum(rhs._binNum),\n _parent(rhs._parent),\n _stage(rhs._stage),\n _bins(rhs._bins),\n _renderGraphList(rhs._renderGraphList),\n _renderLeafList(rhs._renderLeafList),\n _sortMode(rhs._sortMode),\n _sortCallback(rhs._sortCallback),\n _drawCallback(rhs._drawCallback)\n{\n\n}\n\nRenderBin::~RenderBin()\n{\n}\n\nvoid RenderBin::reset()\n{\n _renderGraphList.clear();\n _bins.clear();\n}\n\nvoid RenderBin::sort()\n{\n for(RenderBinList::iterator itr = _bins.begin();\n itr!=_bins.end();\n ++itr)\n {\n itr->second->sort();\n }\n \n if (_sortCallback.valid()) \n {\n _sortCallback->sortImplementation(this);\n }\n else sortImplementation();\n}\n\nvoid RenderBin::setSortMode(SortMode mode)\n{\n _sortMode = mode;\n}\n\nvoid RenderBin::sortImplementation()\n{\n switch(_sortMode)\n {\n case(SORT_BY_STATE):\n sortByState();\n break;\n case(SORT_FRONT_TO_BACK):\n sortFrontToBack();\n break;\n case(SORT_BACK_TO_FRONT):\n sortBackToFront();\n break;\n default:\n break;\n }\n}\n\nstruct SortByStateFunctor\n{\n bool operator() (const RenderGraph* lhs,const RenderGraph* rhs) const\n {\n return (*(lhs->_stateset)<*(rhs->_stateset));\n }\n};\n\nvoid RenderBin::sortByState()\n{\n \/\/ actually we'll do nothing right now, as fine grained sorting by state\n \/\/ appears to cost more to do than it saves in draw. The contents of\n \/\/ the RenderGraph leaves is already coasrse grained sorted, this\n \/\/ sorting is as a function of the cull traversal.\n \/\/ cout << \"doing sortByState \"<<this<<endl;\n}\n\nstruct FrontToBackSortFunctor\n{\n bool operator() (const RenderLeaf* lhs,const RenderLeaf* rhs) const\n {\n return (lhs->_depth<rhs->_depth);\n }\n};\n\n \nvoid RenderBin::sortFrontToBack()\n{\n copyLeavesFromRenderGraphListToRenderLeafList();\n\n \/\/ now sort the list into acending depth order.\n std::sort(_renderLeafList.begin(),_renderLeafList.end(),FrontToBackSortFunctor());\n \n\/\/ cout << \"sort front to back\"<<endl;\n}\n\nstruct BackToFrontSortFunctor\n{\n bool operator() (const RenderLeaf* lhs,const RenderLeaf* rhs) const\n {\n return (rhs->_depth<lhs->_depth);\n }\n};\n\nvoid RenderBin::sortBackToFront()\n{\n copyLeavesFromRenderGraphListToRenderLeafList();\n\n \/\/ now sort the list into acending depth order.\n std::sort(_renderLeafList.begin(),_renderLeafList.end(),BackToFrontSortFunctor());\n\n\/\/ cout << \"sort back to front\"<<endl;\n}\n\nvoid RenderBin::copyLeavesFromRenderGraphListToRenderLeafList()\n{\n _renderLeafList.clear();\n\n int totalsize=0;\n RenderGraphList::iterator itr;\n for(itr=_renderGraphList.begin();\n itr!=_renderGraphList.end();\n ++itr)\n {\n totalsize += (*itr)->_leaves.size();\n }\n\n _renderLeafList.reserve(totalsize);\n \n \/\/ first copy all the leaves from the render graphs into the leaf list.\n for(itr=_renderGraphList.begin();\n itr!=_renderGraphList.end();\n ++itr)\n {\n for(RenderGraph::LeafList::iterator dw_itr = (*itr)->_leaves.begin();\n dw_itr != (*itr)->_leaves.end();\n ++dw_itr)\n {\n _renderLeafList.push_back(dw_itr->get());\n }\n }\n \n \/\/ empty the render graph list to prevent it being drawn along side the render leaf list (see drawImplementation.)\n _renderGraphList.clear();\n}\n\nRenderBin* RenderBin::find_or_insert(int binNum,const std::string& binName)\n{\n \/\/ search for appropriate bin.\n RenderBinList::iterator itr = _bins.find(binNum);\n if (itr!=_bins.end()) return itr->second.get();\n\n \/\/ create a renderin bin and insert into bin list.\n RenderBin* rb = RenderBin::createRenderBin(binName);\n if (rb)\n {\n\n RenderStage* rs = dynamic_cast<RenderStage*>(rb);\n if (rs)\n {\n rs->_binNum = binNum;\n rs->_parent = NULL;\n rs->_stage = rs;\n _stage->addToDependencyList(rs);\n }\n else\n {\n rb->_binNum = binNum;\n rb->_parent = this;\n rb->_stage = _stage;\n _bins[binNum] = rb;\n }\n }\n return rb;\n}\n\nvoid RenderBin::draw(osg::State& state,RenderLeaf*& previous)\n{\n if (_drawCallback.valid()) \n {\n _drawCallback->drawImplementation(this,state,previous);\n }\n else drawImplementation(state,previous);\n}\n\nvoid RenderBin::drawImplementation(osg::State& state,RenderLeaf*& previous)\n{\n \/\/ draw first set of draw bins.\n RenderBinList::iterator rbitr;\n for(rbitr = _bins.begin();\n rbitr!=_bins.end() && rbitr->first<0;\n ++rbitr)\n {\n rbitr->second->draw(state,previous);\n }\n \n\n \/\/ draw fine grained ordering.\n for(RenderLeafList::iterator rlitr= _renderLeafList.begin();\n rlitr!= _renderLeafList.end();\n ++rlitr)\n {\n RenderLeaf* rl = *rlitr;\n rl->render(state,previous);\n previous = rl;\n }\n\n\n \/\/ draw coarse grained ordering.\n for(RenderGraphList::iterator oitr=_renderGraphList.begin();\n oitr!=_renderGraphList.end();\n ++oitr)\n {\n\n for(RenderGraph::LeafList::iterator dw_itr = (*oitr)->_leaves.begin();\n dw_itr != (*oitr)->_leaves.end();\n ++dw_itr)\n {\n RenderLeaf* rl = dw_itr->get();\n rl->render(state,previous);\n previous = rl;\n\n }\n }\n\n\n \/\/ draw post bins.\n for(;\n rbitr!=_bins.end();\n ++rbitr)\n {\n rbitr->second->draw(state,previous);\n }\n\n\n}\n\n\/\/ stats\nbool RenderBin::getStats(osg::Statistics* primStats)\n{ \/\/ different by return type - collects the stats in this renderrBin\n bool somestats=false;\n for(RenderGraphList::iterator oitr=_renderGraphList.begin();\n oitr!=_renderGraphList.end();\n ++oitr)\n {\n \n for(RenderGraph::LeafList::iterator dw_itr = (*oitr)->_leaves.begin();\n dw_itr != (*oitr)->_leaves.end();\n ++dw_itr)\n {\n RenderLeaf* rl = dw_itr->get();\n Drawable* dw= rl->_drawable;\n primStats->addDrawable(); \/\/ number of geosets\n if (rl->_modelview.get()) primStats->addMatrix(); \/\/ number of matrices\n if (dw)\n {\n \/\/ then tot up the primtive types and no vertices.\n dw->accept(*primStats); \/\/ use sub-class to find the stats for each drawable\n if (typeid(*dw)==typeid(osg::ImpostorSprite)) primStats->addImpostor(1);\n }\n }\n somestats=true;\n }\n return somestats;\n}\n\nvoid RenderBin::getPrims(osg::Statistics* primStats)\n{\n static int ndepth;\n ndepth++;\n for(RenderBinList::iterator itr = _bins.begin();\n itr!=_bins.end();\n ++itr)\n {\n primStats->addBins(1);\n itr->second->getPrims(primStats);\n }\n getStats(primStats);\n ndepth--;\n\n}\n\nbool RenderBin::getPrims(osg::Statistics* primStats, int nbin)\n{ \/\/ collect stats for array of bins, maximum nbin \n \/\/ (which will be modified on next call if array of primStats is too small);\n \/\/ return 1 for OK;\n static int ndepth;\n bool ok=false;\n ndepth++;\n int nb=primStats[0].getBins();\n if (nb<nbin)\n { \/\/ if statement to protect against writing to bins beyond the maximum seen before\n primStats[nb].setBinNo(nb);\n primStats[nb].setDepth(ndepth);\n getStats(primStats+nb);\n }\n primStats[0].addBins(1);\n for(RenderBinList::iterator itr = _bins.begin();\n itr!=_bins.end();\n ++itr)\n {\n if (itr->second->getPrims(primStats, nbin)) ok = true;\n }\n ok=true;\n ndepth--;\n return ok;\n}\n<|endoftext|>"} {"text":"<commit_before>#include <engpar_support.h>\n#include <apfGraph.h>\n#include <apfMesh2.h>\n#include <apfNumbering.h>\n#include <apfMDS.h>\n#include <gmi_mesh.h>\n#include <apf.h>\n#include <engpar.h>\n#include <engpar_input.h>\n#include <binGraph.h>\n#include <parma.h>\n\nint main(int argc, char* argv[]) {\n MPI_Init(&argc,&argv);\n EnGPar_Initialize();\n EnGPar_Open_Log();\n \n if (argc != 4 && argc!=5) {\n if ( !PCU_Comm_Self() ) {\n printf(\"Usage: %s <model> <mesh> <tolerance> [multi-edgetypes]\\n\", argv[0]);\n }\n EnGPar_Finalize();\n assert(false);\n }\n apf::Mesh2* m=NULL;\n agi::Ngraph* g=NULL;\n \/\/Load mesh\n gmi_register_mesh();\n m = apf::loadMdsMesh(argv[1],argv[2]);\n \n Parma_PrintPtnStats(m,\"before\");\n \/\/visualize the mesh before balancing\n apf::writeVtkFiles(\"pre\", m);\n \n double tol = atof(argv[3]);\n if (!PCU_Comm_Self())\n printf(\"tolerance %f\\n\", tol);\n\n double times[10];\n times[0] = PCU_Time();\n times[4] = PCU_Time();\n if (argc==5) {\n int edges[2] = {0,2};\n \/\/balance vtx>edge>elm\n g = agi::createAPFGraph(m,3,edges,2);\n }\n else {\n \/\/balance vtx>elm\n g = agi::createAPFGraph(m,3,0);\n }\n times[0] = PCU_Time()-times[0];\n times[1] = PCU_Time();\n \n engpar::Input* input = new engpar::Input(g);\n input->priorities.push_back(0);\n input->tolerances.push_back(tol);\n if (argc==5) {\n input->priorities.push_back(1);\n input->tolerances.push_back(tol);\n }\n input->priorities.push_back(-1);\n input->tolerances.push_back(tol);\n\n input->step_factor=.1;\n\n input->useDistanceQueue=true;\n \/\/Create the balancer\n agi::Balancer* balancer = engpar::makeBalancer(input);\n balancer->balance(tol);\n\n engpar::evaluatePartition(g);\n \/\/Destroy balancer\n delete balancer;\n times[1] = PCU_Time() - times[1];\n\n \/\/Ensure the graph is still valid\n agi::checkValidity(g);\n\n times[2] = PCU_Time();\n\n \/\/Migration of original data structure\n \/\/Only implemented for mesh\n agi::PartitionMap* map = g->getPartition();\n\n \/\/map can be used to migrate the original structure\n apf::Migration* plan = new apf::Migration(m);\n apf::GlobalNumbering* gids = m->findGlobalNumbering(\"primary_ids_global\");\n apf::MeshIterator* mitr = m->begin(3);\n apf::MeshEntity* ent;\n while ((ent = m->iterate(mitr))) {\n agi::gid_t gid = apf::getNumber(gids,ent,0);\n assert(map->find(gid)!=map->end());\n agi::part_t target = map->find(gid)->second;\n if (target!=PCU_Comm_Self())\n plan->send(ent,target);\n }\n m->end(mitr);\n delete map;\n m->migrate(plan);\n\n times[2] = PCU_Time() - times[2];\n times[4] = PCU_Time() - times[4];\n PCU_Max_Doubles(times,4);\n \n if (!PCU_Comm_Self()) {\n printf(\"Total Time: %f\\n\",times[4]);\n printf(\"Construct Time: %f\\n\",times[0]);\n printf(\"Balancing Time: %f\\n\",times[1]);\n printf(\"Repartition Time: %f\\n\",times[2]);\n }\n \n \/\/Destroy graph\n agi::destroyGraph(g);\n\n \/\/visualize the mesh after balancing\n apf::writeVtkFiles(\"post\", m);\n Parma_PrintPtnStats(m,\"after\");\n \n \/\/Destroy mesh\n m->destroyNative();\n apf::destroyMesh(m);\n\n PCU_Barrier();\n if (!PCU_Comm_Self())\n printf(\"\\nAll tests passed\\n\");\n\n EnGPar_Finalize();\n MPI_Finalize();\n}\n<commit_msg>balanceMesh: user controls writing of paraview files<commit_after>#include <engpar_support.h>\n#include <apfGraph.h>\n#include <apfMesh2.h>\n#include <apfNumbering.h>\n#include <apfMDS.h>\n#include <gmi_mesh.h>\n#include <apf.h>\n#include <engpar.h>\n#include <engpar_input.h>\n#include <binGraph.h>\n#include <parma.h>\n\nint main(int argc, char* argv[]) {\n MPI_Init(&argc,&argv);\n EnGPar_Initialize();\n EnGPar_Open_Log();\n \n if (argc != 5 && argc != 6) {\n if ( !PCU_Comm_Self() ) {\n printf(\"Usage: %s <model> <mesh> <tolerance> <render=[1:on|0:off]> [multi-edgetypes]\\n\", argv[0]);\n }\n EnGPar_Finalize();\n assert(false);\n }\n\n apf::Mesh2* m=NULL;\n agi::Ngraph* g=NULL;\n \/\/Load mesh\n gmi_register_mesh();\n m = apf::loadMdsMesh(argv[1],argv[2]);\n\n double tol = atof(argv[3]);\n const int render = atoi(argv[4]);\n if (!PCU_Comm_Self())\n printf(\"render vtk %s\\n\", render == 0 ? \"off\" : \"on\" );\n\n Parma_PrintPtnStats(m,\"before\");\n if(render)\n apf::writeVtkFiles(\"pre\", m);\n\n double times[10];\n times[0] = PCU_Time();\n times[4] = PCU_Time();\n if (argc==6) {\n int edges[2] = {0,2};\n \/\/balance vtx>edge>elm\n g = agi::createAPFGraph(m,3,edges,2);\n }\n else {\n \/\/balance vtx>elm\n g = agi::createAPFGraph(m,3,0);\n }\n times[0] = PCU_Time()-times[0];\n times[1] = PCU_Time();\n \n engpar::Input* input = new engpar::Input(g);\n input->priorities.push_back(0);\n input->tolerances.push_back(tol);\n if (argc==5) {\n input->priorities.push_back(1);\n input->tolerances.push_back(tol);\n }\n input->priorities.push_back(-1);\n input->tolerances.push_back(tol);\n\n input->step_factor=.1;\n\n input->useDistanceQueue=true;\n \/\/Create the balancer\n agi::Balancer* balancer = engpar::makeBalancer(input);\n balancer->balance(tol);\n\n engpar::evaluatePartition(g);\n \/\/Destroy balancer\n delete balancer;\n times[1] = PCU_Time() - times[1];\n\n \/\/Ensure the graph is still valid\n agi::checkValidity(g);\n\n times[2] = PCU_Time();\n\n \/\/Migration of original data structure\n \/\/Only implemented for mesh\n agi::PartitionMap* map = g->getPartition();\n\n \/\/map can be used to migrate the original structure\n apf::Migration* plan = new apf::Migration(m);\n apf::GlobalNumbering* gids = m->findGlobalNumbering(\"primary_ids_global\");\n apf::MeshIterator* mitr = m->begin(3);\n apf::MeshEntity* ent;\n while ((ent = m->iterate(mitr))) {\n agi::gid_t gid = apf::getNumber(gids,ent,0);\n assert(map->find(gid)!=map->end());\n agi::part_t target = map->find(gid)->second;\n if (target!=PCU_Comm_Self())\n plan->send(ent,target);\n }\n m->end(mitr);\n delete map;\n m->migrate(plan);\n\n times[2] = PCU_Time() - times[2];\n times[4] = PCU_Time() - times[4];\n PCU_Max_Doubles(times,4);\n \n if (!PCU_Comm_Self()) {\n printf(\"Total Time: %f\\n\",times[4]);\n printf(\"Construct Time: %f\\n\",times[0]);\n printf(\"Balancing Time: %f\\n\",times[1]);\n printf(\"Repartition Time: %f\\n\",times[2]);\n }\n \n \/\/Destroy graph\n agi::destroyGraph(g);\n\n if(render)\n apf::writeVtkFiles(\"post\", m);\n Parma_PrintPtnStats(m,\"after\");\n \n \/\/Destroy mesh\n m->destroyNative();\n apf::destroyMesh(m);\n\n PCU_Barrier();\n if (!PCU_Comm_Self())\n printf(\"\\nAll tests passed\\n\");\n\n EnGPar_Finalize();\n MPI_Finalize();\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Author : Eli Gundry\n * Date : 11\/28\/2011\n * Name : Gradebook Classes\n * Description : Determines the weighted letter grade of a student with classes\n * Link : http:\/\/www.cs.kent.edu\/~lucc\/ioop\/Labs\/Lab2\/proj-13\n *\/\n\n#include <iostream>\n\nusing namespace std;\n\nclass StudentGrade\n{\n\tpublic:\n\t\tvoid input();\n\t\tvoid output();\n\tprivate:\n\t\tdouble final_score(); \n\t\tchar letter_grade();\n\t\tdouble quiz_1,\n\t\t\t quiz_2,\n\t\t\t midterm,\n\t\t\t final;\n};\n\nint main()\n{\n\tStudentGrade grade;\n\n\tgrade.input();\n\tgrade.output();\n\n\treturn 0;\n}\n\nvoid StudentGrade::input()\n{\n\tcout << \"What was the student's grade for quiz 1? (0-10)\" << endl;\n\tcin >> quiz_1;\n\tcout << \"And for quiz 2? (0-10)\" << endl;\n\tcin >> quiz_2;\n\tcout << \"How did they do on the midterm? (0-100)\" << endl;\n\tcin >> midterm;\n\tcout << \"And the final exam? (0-100)\" << endl;\n\tcin >> final;\n}\n\nvoid StudentGrade::output()\n{\n\tcout << endl << \"Quiz 1: \" << (quiz_1 * 10) << endl\n\t\t << \"Quiz 2: \" << (quiz_2 * 10) << endl\n\t\t << \"Midterm: \" << midterm << endl\n\t\t << \"Final Exam: \" << final << endl << endl;\n}\n\ndouble StudentGrade::final_score()\n{\n\treturn ((final * 0.5) + (midterm * 0.25) + (((quiz_1 * 5) + (quiz_1 * 5)) * 0.25));\n}\n\nchar StudentGrade::letter_grade()\n{\n\tif (grade >= 90)\n\t\treturn 'A';\n\telse if (grade >= 80)\n\t\treturn 'B';\n\telse if (grade >= 70)\n\t\treturn 'C';\n\telse if (grade >= 60)\n\t\treturn 'D';\n\telse\n\t\treturn 'F';\n}\n<commit_msg>Started add CC Liu grading scale<commit_after>\/*\n * Author : Eli Gundry\n * Date : 11\/28\/2011\n * Name : Gradebook Classes\n * Description : Determines the weighted letter grade of a student with classes\n * Link : http:\/\/www.cs.kent.edu\/~lucc\/ioop\/Labs\/Lab2\/proj-13\n *\/\n\n#include <iostream>\n\nusing namespace std;\n\nclass StudentGrade\n{\n\tpublic:\n\tprivate:\n\t\tdouble final_score(); \n\t\tchar letter_grade();\n\t\tchar student_name[81];\n\t\tdouble quiz_1,\n\t\t\t quiz_2,\n\t\t\t midterm,\n\t\t\t final;\n};\n\nvoid input(StudentGrade grade);\nvoid output(StudentGrade grade);\n\nint main()\n{\n\tStudentGrade grade;\n\n\tinput(grade);\n\toutput(grade);\n\n\treturn 0;\n}\n\nvoid input(StudentGrade grade)\n{\n\tcout << \"#### CC Gradebook System ####\" << endl; \n\n\tdo {\n\t\tcout << \"What is the student's name? (Press Enter to exit)\" << endl;\n\n\t\tfor (int num_of_students = 0; i < grade.student name; i++) {\n\t\t\tcin >> grade.student_name; \n\t\t}\n\n\t} while (grade.student_name != '\\r')\n\n}\n\nvoid output(StudentGrade grade)\n{\n\tcout << endl << \"Quiz 1: \" << (grade.quiz_1 * 10) << endl\n\t\t << \"Quiz 2: \" << (grade.quiz_2 * 10) << endl\n\t\t << \"Midterm: \" << grade.midterm << endl\n\t\t << \"Final Exam: \" << grade.final << endl << endl;\n\n}\n\ndouble StudentGrade::final_score()\n{\n\treturn ((final * 0.5) + (midterm * 0.25) + (((quiz_1 * 5) + (quiz_1 * 5)) * 0.25));\n}\n\nchar StudentGrade::letter_grade()\n{\n\tif (grade >= 90)\n\t\treturn 'A';\n\telse if (grade >= 80)\n\t\treturn 'B';\n\telse if (grade >= 70)\n\t\treturn 'C';\n\telse if (grade >= 60)\n\t\treturn 'D';\n\telse\n\t\treturn 'F';\n}\n<|endoftext|>"} {"text":"<commit_before>#include <SDL2\/SDL.h>\n#include \"rotate_triangle.h\"\n\n#ifdef USE_GCW0\nstatic const int WIDTH = 320;\nstatic const int HEIGHT = 240;\n#else\nstatic const int WIDTH = 800;\nstatic const int HEIGHT = 600;\n#endif\n\nSDL_Window *gscreen = nullptr;\nSDL_GLContext gcontext;\n\nSDL_Window *init_window(Uint32 subsystems, Uint32 windowFlags)\n{\n\tSDL_Window *window = nullptr;\n\tif ( SDL_Init(subsystems) >=0 )\n\t{\n\t\twindow = SDL_CreateWindow(\t\"An SDL2 window\", \n\t\t\t\tSDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED,\n\t\t\t\tWIDTH, HEIGHT, \n\t\t\t\twindowFlags );\n\t\tif(window) \n\t\t{\n\t\t\t\/\/\n\t\t\t\/\/ Set core profile\n\t\t\t\/\/\n\t\t\tSDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_ES);\n\t\t\tSDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 2);\n\t\t\tSDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 0);\n\t\t\t\/\/ Enables double buffering\n\t\t\tSDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);\n\t\t\t\/\/ 24 bit depth buffer \n\t\t\tSDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24);\n\t\t\t\/\/ Create OpenGL Context\n\t\t\tgcontext = SDL_GL_CreateContext(window);\n\t\t\tif(nullptr == gcontext)\n\t\t\t{\n\t\t\t\tstd::cerr << \"Failed to create gl context.\\nError: \" << SDL_GetError() << std::endl;\n\t\t\t\t SDL_DestroyWindow(window);\n\t\t\t\t window = nullptr;\n\t\t\t}\n\t\t\t\/\/ enable vsync\n\t\t\tSDL_GL_SetSwapInterval(1);\n\t\t}\n\t}\n\telse \n\t{\n\t\tstd::cerr << \"Failed to init sdl: \" << SDL_GetError() << std::endl;\n\t\texit(1);\n\t}\n\treturn window;\n}\n\ninline bool inputHandler()\n{\n\tSDL_Event event;\n\tbool rtn = true;\n\twhile(SDL_PollEvent(&event))\n\t{\n\t\tif (event.type==SDL_QUIT) {return false;}\n\t\tif (event.type==SDL_KEYDOWN)\n\t\t{\n\t\t\tswitch(event.key.keysym.sym) \n\t\t\t{\n\t\t\t\tcase SDLK_RETURN:\n\t\t\t\t\tstd::cout << \"Start button pressed\" << std::endl;\n\t\t\t\t\tbreak;\n\t\t\t\tcase SDLK_ESCAPE:\n\t\t\t\t\tstd::cout << \"Esc Key pressed\" << std::endl;\n\t\t\t\t\trtn = false;\n\t\t\t\t\tbreak;\n\t\t\t\tcase SDLK_LEFT: \n\t\t\t\t\tstd::cout << \"Left Key pressed\" << std::endl;\n\t\t\t\t\tbreak;\n\t\t\t\tcase SDLK_RIGHT: \n\t\t\t\t\tstd::cout << \"Right Key pressed\" << std::endl;\n\t\t\t\t\tbreak;\n\t\t\t\tcase SDLK_UP: \n\t\t\t\t\tstd::cout << \"Up Key pressed\" << std::endl;\n\t\t\t\t\tbreak;\n\t\t\t\tcase SDLK_DOWN: \n\t\t\t\t\tstd::cout << \"Down Key pressed\" << std::endl;\n\t\t\t\t\tbreak;\n\t\t\t\tcase SDLK_LCTRL:\n\t\t\t\t\tstd::cout << \"A Key pressed\" << std::endl;\n\t\t\t\t\tbreak;\n\t\t\t\tcase SDLK_LALT:\n\t\t\t\t\tstd::cout << \"B Key pressed\" << std::endl;\n\t\t\t\t\tbreak;\n\t\t\t\tcase SDLK_LSHIFT:\n\t\t\t\t\tstd::cout << \"X Key pressed\" << std::endl;\n\t\t\t\t\tbreak;\n\t\t\t\tcase SDLK_SPACE:\n\t\t\t\t\tstd::cout << \"Y Key pressed\" << std::endl;\n\t\t\t\t\tbreak;\n\t\t\t\tdefault: \n\t\t\t\t\tstd::cout << \"Unknown Key pressed \" << event.key.keysym.sym << std::endl;\n\t\t\t}\n\t\t}\n\t}\n\treturn rtn;\n}\n\nvoid cleanup()\n{\n\tSDL_GL_DeleteContext(gcontext);\n\tSDL_DestroyWindow(gscreen);\n\tSDL_Quit();\n}\n\nint main(int argc, char *argv[])\n{\n\tUint32 subsystem = 0; \n\tUint32 windowFlags = 0;\n\tsubsystem |= SDL_INIT_VIDEO | SDL_INIT_TIMER;\n\twindowFlags |= SDL_WINDOW_OPENGL;\n\n\tgscreen = init_window(subsystem, windowFlags); \n\tif (!gscreen) \n\t{\n\t\tstd::cerr << \"Could not create window \" << SDL_GetError() << std::endl;\n\t\treturn EXIT_FAILURE;\n\t}\n\tprintGLVersion();\n\n\tRotateTriangle tri;\n\tbool running=true;\n\tglViewport(0,0,WIDTH,HEIGHT);\n\twhile(running)\n\t{\n\t\tglClearColor ( 0.0f, 0.0f, 0.0f, 0.0f );\n\t\tglClear(GL_COLOR_BUFFER_BIT);\n\t\ttri.render();\n\t\tSDL_GL_SwapWindow(gscreen);\n\t\trunning = inputHandler();\n\n\t}\n\tcleanup();\n\treturn 0;\n}\n<commit_msg>Setting GL Attributes before opening the window<commit_after>#include <SDL2\/SDL.h>\n#include \"rotate_triangle.h\"\n\n#ifdef USE_GCW0\nstatic const int WIDTH = 320;\nstatic const int HEIGHT = 240;\n#else\nstatic const int WIDTH = 800;\nstatic const int HEIGHT = 600;\n#endif\n\nSDL_Window *gscreen = nullptr;\nSDL_GLContext gcontext;\n\nSDL_Window *init_window(Uint32 subsystems, Uint32 windowFlags)\n{\n\tSDL_Window *window = nullptr;\n\tif ( SDL_Init(subsystems) >=0 )\n\t{\n\t\t\/\/\n\t\t\/\/ Set core profile\n\t\t\/\/\n\t\tSDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_ES);\n\t\tSDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 2);\n\t\tSDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 0);\n\t\t\/\/ Enables double buffering\n\t\tSDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);\n\t\t\/\/ 24 bit depth buffer \n\t\tSDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24);\n\n\t\twindow = SDL_CreateWindow(\t\"An SDL2 window\", \n\t\t\t\tSDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED,\n\t\t\t\tWIDTH, HEIGHT, \n\t\t\t\twindowFlags );\n\t\tif(window) \n\t\t{\n\t\t\t\/\/ Create OpenGL Context\n\t\t\tgcontext = SDL_GL_CreateContext(window);\n\t\t\tif(nullptr == gcontext)\n\t\t\t{\n\t\t\t\tstd::cerr << \"Failed to create gl context.\\nError: \" << SDL_GetError() << std::endl;\n\t\t\t\tSDL_DestroyWindow(window);\n\t\t\t\twindow = nullptr;\n\t\t\t}\n\t\t\t\/\/ enable vsync\n\t\t\tSDL_GL_SetSwapInterval(1);\n\t\t}\n\t}\n\telse \n\t{\n\t\tstd::cerr << \"Failed to init sdl: \" << SDL_GetError() << std::endl;\n\t\texit(1);\n\t}\n\treturn window;\n}\n\ninline bool inputHandler()\n{\n\tSDL_Event event;\n\tbool rtn = true;\n\twhile(SDL_PollEvent(&event))\n\t{\n\t\tif (event.type==SDL_QUIT) {return false;}\n\t\tif (event.type==SDL_KEYDOWN)\n\t\t{\n\t\t\tswitch(event.key.keysym.sym) \n\t\t\t{\n\t\t\t\tcase SDLK_RETURN:\n\t\t\t\t\tstd::cout << \"Start button pressed\" << std::endl;\n\t\t\t\t\tbreak;\n\t\t\t\tcase SDLK_ESCAPE:\n\t\t\t\t\tstd::cout << \"Esc Key pressed\" << std::endl;\n\t\t\t\t\trtn = false;\n\t\t\t\t\tbreak;\n\t\t\t\tcase SDLK_LEFT: \n\t\t\t\t\tstd::cout << \"Left Key pressed\" << std::endl;\n\t\t\t\t\tbreak;\n\t\t\t\tcase SDLK_RIGHT: \n\t\t\t\t\tstd::cout << \"Right Key pressed\" << std::endl;\n\t\t\t\t\tbreak;\n\t\t\t\tcase SDLK_UP: \n\t\t\t\t\tstd::cout << \"Up Key pressed\" << std::endl;\n\t\t\t\t\tbreak;\n\t\t\t\tcase SDLK_DOWN: \n\t\t\t\t\tstd::cout << \"Down Key pressed\" << std::endl;\n\t\t\t\t\tbreak;\n\t\t\t\tcase SDLK_LCTRL:\n\t\t\t\t\tstd::cout << \"A Key pressed\" << std::endl;\n\t\t\t\t\tbreak;\n\t\t\t\tcase SDLK_LALT:\n\t\t\t\t\tstd::cout << \"B Key pressed\" << std::endl;\n\t\t\t\t\tbreak;\n\t\t\t\tcase SDLK_LSHIFT:\n\t\t\t\t\tstd::cout << \"X Key pressed\" << std::endl;\n\t\t\t\t\tbreak;\n\t\t\t\tcase SDLK_SPACE:\n\t\t\t\t\tstd::cout << \"Y Key pressed\" << std::endl;\n\t\t\t\t\tbreak;\n\t\t\t\tdefault: \n\t\t\t\t\tstd::cout << \"Unknown Key pressed \" << event.key.keysym.sym << std::endl;\n\t\t\t}\n\t\t}\n\t}\n\treturn rtn;\n}\n\nvoid cleanup()\n{\n\tSDL_GL_DeleteContext(gcontext);\n\tSDL_DestroyWindow(gscreen);\n\tSDL_Quit();\n}\n\nint main(int argc, char *argv[])\n{\n\tUint32 subsystem = 0; \n\tUint32 windowFlags = 0;\n\tsubsystem |= SDL_INIT_VIDEO | SDL_INIT_TIMER;\n\twindowFlags |= SDL_WINDOW_OPENGL;\n\n\tgscreen = init_window(subsystem, windowFlags); \n\tif (!gscreen) \n\t{\n\t\tstd::cerr << \"Could not create window \" << SDL_GetError() << std::endl;\n\t\treturn EXIT_FAILURE;\n\t}\n\tprintGLVersion();\n\n\tRotateTriangle tri;\n\tbool running=true;\n\tglViewport(0,0,WIDTH,HEIGHT);\n\twhile(running)\n\t{\n\t\tglClearColor ( 0.0f, 0.0f, 0.0f, 0.0f );\n\t\tglClear(GL_COLOR_BUFFER_BIT);\n\t\ttri.render();\n\t\tSDL_GL_SwapWindow(gscreen);\n\t\trunning = inputHandler();\n\n\t}\n\tcleanup();\n\treturn 0;\n}\n<|endoftext|>"} {"text":"<commit_before>\/**\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements. See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership. The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#ifndef __PROC_UTILS_HPP__\n#define __PROC_UTILS_HPP__\n\n#include <string>\n#include <vector>\n\nnamespace mesos { namespace internal { namespace monitoring {\n\nstruct ProcessStats {\n std::string pid;\n std::string ppid;\n std::string pgrp;\n std::string session;\n double cpu_time; \/\/ utime + stime in ticks.\n double starttime; \/\/ jiffies since system boot time.\n double mem_usage; \/\/ rss in bytes.\n};\n\n\/\/ Retrieves resource usage and metadata for a process. Takes the PID of the\n\/\/ process to query and returns a ProcessStats struct containing the retrieved\n\/\/ info.\nProcessStats getProcessStats(const std::string& pid);\n\n\/\/ Retrieves the system boot time (in milliseconds since epoch).\ndouble getBootTime();\n\n\/\/ Retrieves the current system time (in milliseconds since epoch).\ndouble getCurrentTime();\n\n\/\/ Retrieves the start time (in milliseconds since epoch) of the process with\n\/\/ the given PID.\ndouble getStartTime(const std::string& pid);\n\n\/\/ Reads from proc and returns a vector of all processes running on the system.\nstd::vector<std::string> getAllPids();\n\n}}} \/\/ namespace mesos { namespace internal { namespace monitoring {\n\n#endif \/\/ __PROC_UTILS_HPP__\n<commit_msg>Fixed style in proc_utils.<commit_after>\/**\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements. See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership. The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#ifndef __PROC_UTILS_HPP__\n#define __PROC_UTILS_HPP__\n\n#include <string>\n#include <vector>\n\nnamespace mesos {\nnamespace internal {\nnamespace monitoring {\n\nstruct ProcessStats {\n std::string pid;\n std::string ppid;\n std::string pgrp;\n std::string session;\n double cpu_time; \/\/ utime + stime in ticks.\n double starttime; \/\/ jiffies since system boot time.\n double mem_usage; \/\/ rss in bytes.\n};\n\n\/\/ Retrieves resource usage and metadata for a process. Takes the PID of the\n\/\/ process to query and returns a ProcessStats struct containing the retrieved\n\/\/ info.\nProcessStats getProcessStats(const std::string& pid);\n\n\/\/ Retrieves the system boot time (in milliseconds since epoch).\ndouble getBootTime();\n\n\/\/ Retrieves the current system time (in milliseconds since epoch).\ndouble getCurrentTime();\n\n\/\/ Retrieves the start time (in milliseconds since epoch) of the process with\n\/\/ the given PID.\ndouble getStartTime(const std::string& pid);\n\n\/\/ Reads from proc and returns a vector of all processes running on the system.\nstd::vector<std::string> getAllPids();\n\n} \/\/ namespace monitoring {\n} \/\/ namespace internal {\n} \/\/ namespace mesos {\n\n#endif \/\/ __PROC_UTILS_HPP__\n<|endoftext|>"} {"text":"<commit_before>#include \"fdhandle.h\"\n\n#include <errno.h>\n#include <fcntl.h>\n#include <signal.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <sys\/socket.h>\n#include <sys\/types.h>\n\nvoid sig_handler(int sig)\n{\n int save_errno = errno;\n int msg = sig;\n send(g_sig_pipe[1], (char*)&msg, 1, 0);\n errno = save_errno;\n}\n\nvoid add_sig(int sig, void (*handler)(int), bool restart)\n{\n struct sigaction sa;\n memset(&sa, 0, sizeof(sa));\n sa.sa_handler = handler;\n if (restart) {\n sa.sa_flags |= SA_RESTART;\n }\n sigfillset(&sa.sa_mask);\n if (sigaction(sig, &sa, nullptr) == -1) {\n perror(\"sigaction\");\n exit(EXIT_FAILURE);\n }\n}\n\nint set_nonblocking(int fd)\n{\n int old_option = fcntl(fd, F_GETFL);\n int new_option = old_option | O_NONBLOCK;\n fcntl(fd, F_SETFL, new_option);\n return old_option;\n}\n\nvoid add_fd(int epollfd, int fd, uint32_t events)\n{\n epoll_event event;\n event.data.fd = fd;\n event.events = events;\n epoll_ctl(epollfd, EPOLL_CTL_ADD, &event);\n set_nonblocking(fd);\n}\n\nvoid remove_fd(int epollfd, int fd)\n{\n epoll_ctl(epollfd, EPOLL_CTL_DEL, fd, 0);\n close(fd);\n}\n<commit_msg>function use error fix<commit_after>#include \"fdhandle.h\"\n\n#include <errno.h>\n#include <fcntl.h>\n#include <signal.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <sys\/epoll.h>\n#include <sys\/socket.h>\n#include <sys\/types.h>\n#include <unistd.h>\n\nvoid sig_handler(int sig)\n{\n int save_errno = errno;\n int msg = sig;\n send(g_sig_pipe[1], (char*)&msg, 1, 0);\n errno = save_errno;\n}\n\nvoid add_sig(int sig, void (*handler)(int), bool restart)\n{\n struct sigaction sa;\n memset(&sa, 0, sizeof(sa));\n sa.sa_handler = handler;\n if (restart) {\n sa.sa_flags |= SA_RESTART;\n }\n sigfillset(&sa.sa_mask);\n if (sigaction(sig, &sa, nullptr) == -1) {\n perror(\"sigaction\");\n exit(EXIT_FAILURE);\n }\n}\n\nint set_nonblocking(int fd)\n{\n int old_option = fcntl(fd, F_GETFL);\n int new_option = old_option | O_NONBLOCK;\n fcntl(fd, F_SETFL, new_option);\n return old_option;\n}\n\nvoid add_fd(int epollfd, int fd, uint32_t events)\n{\n epoll_event event;\n event.data.fd = fd;\n event.events = events;\n epoll_ctl(epollfd, EPOLL_CTL_ADD, fd, &event);\n set_nonblocking(fd);\n}\n\nvoid remove_fd(int epollfd, int fd)\n{\n epoll_ctl(epollfd, EPOLL_CTL_DEL, fd, 0);\n close(fd);\n}\n<|endoftext|>"} {"text":"<commit_before>\/* Copyright (C) 2011-2013, Benjamin Jemlich <pcgod@users.sourceforge.net>\n Copyright (C) 2013, Mikkel Krautz <mikkel@krautz.dk>\n\n All rights reserved.\n\n Redistribution and use in source and binary forms, with or without\n modification, are permitted provided that the following conditions\n are met:\n\n - Redistributions of source code must retain the above copyright notice,\n this list of conditions and the following disclaimer.\n - Redistributions in binary form must reproduce the above copyright notice,\n this list of conditions and the following disclaimer in the documentation\n and\/or other materials provided with the distribution.\n - Neither the name of the Mumble Developers nor the names of its\n contributors may be used to endorse or promote products derived from this\n software without specific prior written permission.\n\n THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR\n CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*\/\n\n#include <windows.h>\n#include <shlwapi.h>\n#include <stdio.h>\n\n#include <string>\n\n#define ENV_BUF_MAX 1024\n\ntypedef int (*DLL_MAIN)(HINSTANCE, HINSTANCE, LPSTR, int);\n#ifdef DEBUG\ntypedef int (*DLL_DEBUG_MAIN)(int, char **);\n#endif\n\n\/\/ Alert shows a fatal error dialog and waits for the user to click OK.\nstatic void Alert(LPCWSTR title, LPCWSTR msg) {\n\tMessageBox(NULL, msg, title, MB_OK|MB_ICONERROR);\n}\n\n\/\/ GetExecutableDirPath returns the directory that\n\/\/ mumble.exe resides in.\nstatic std::wstring GetExecutableDirPath() {\n\twchar_t path[MAX_PATH];\n\n\tif (GetModuleFileNameW(NULL, path, MAX_PATH) == 0)\n\t\treturn std::wstring();\n\n\tif (!PathRemoveFileSpecW(path))\n\t\treturn std::wstring();\n\n\tstd::wstring exe_path(path);\n\treturn exe_path.append(L\"\\\\\");\n}\n\n\/\/ ConfigureEnvironment prepares mumble.exe's environment to\n\/\/ run mumble_app.dll.\nstatic bool ConfigureEnvironment() {\n\tstd::wstring exe_path = GetExecutableDirPath();\n\n\t\/\/ Remove the current directory from the DLL search path.\n\tif (!SetDllDirectoryW(L\"\"))\n\t\treturn false;\n\n\t\/\/ Insert mumble.exe's directory as the first entry in the PATH\n\t\/\/ environment variable.\n\t{\n\t\twchar_t path_env[ENV_BUF_MAX];\n\t\tDWORD res = GetEnvironmentVariableW(L\"PATH\", path_env, ENV_BUF_MAX);\n\t\tif (res == 0 || res >= ENV_BUF_MAX) {\n\t\t\treturn false;\n\t\t}\n\n\t\tstd::wstring new_path(exe_path);\n\t\tnew_path.append(L\"\\\\;\");\n\t\tnew_path.append(path_env);\n\t\tif (!SetEnvironmentVariableW(L\"PATH\", new_path.c_str()))\n\t\t\treturn false;\n\t}\n\n\t\/\/ Set mumble.exe's directory as the current working directory.\n\tif (!SetCurrentDirectoryW(exe_path.c_str()))\n\t\treturn false;\n\n\treturn true;\n}\n\n\/\/ GetAbsoluteMumbleAppDllPath returns the absolute path to\n\/\/ mumble_app.dll - the DLL containing the Mumble client\n\/\/ application code.\nstatic std::wstring GetAbsoluteMumbleAppDllPath() {\n\tstd::wstring exe_path = GetExecutableDirPath();\n\tif (exe_path.empty())\n\t\treturn std::wstring();\n\n\tstd::wstring abs_dll_path(exe_path);\n\tabs_dll_path.append(L\"\\\\\");\n\tabs_dll_path.append(L\"mumble_app.dll\");\n\treturn abs_dll_path;\n}\n\n#ifdef DEBUG\nint main(int argc, char **argv) {\n\tif (!ConfigureEnvironment()) {\n\t\tAlert(L\"Mumble Launcher Error -1\", L\"Unable to configure environment.\");\n\t\treturn -1;\n\t}\n\n\tstd::wstring abs_dll_path = GetAbsoluteMumbleAppDllPath();\n\tif (abs_dll_path.empty()) {\n\t\tAlert(L\"Mumble Launcher Error -2\", L\"Unable to find the absolute path of mumble_app.dll.\");\n\t\treturn -2;\n\t}\n\n\tHMODULE dll = LoadLibraryExW(abs_dll_path.c_str(), NULL, LOAD_WITH_ALTERED_SEARCH_PATH);\n\tif (!dll) {\n\t\tAlert(L\"Mumble Launcher Error -3\", L\"Failed to load mumble_app.dll.\");\n\t\treturn -3;\n\t}\n\n\tDLL_DEBUG_MAIN entry_point = reinterpret_cast<DLL_DEBUG_MAIN>(GetProcAddress(dll, \"main\"));\n\tif (!entry_point) {\n\t\tAlert(L\"Mumble Launcher Error -4\", L\"Unable to find expected entry point ('main') in mumble_app.dll.\");\n\t\treturn -4;\n\t}\n\n\tint rc = entry_point(argc, argv);\n\n\treturn rc;\n}\n#endif \/\/ DEBUG\n\nint APIENTRY wWinMain(HINSTANCE instance, HINSTANCE prevInstance, wchar_t *cmdArg, int cmdShow) {\n\tif (!ConfigureEnvironment()) {\n\t\tAlert(L\"Mumble Launcher Error -1\", L\"Unable to configure environment.\");\n\t\treturn -1;\n\t}\n\n\tstd::wstring abs_dll_path = GetAbsoluteMumbleAppDllPath();\n\tif (abs_dll_path.empty()) {\n\t\tAlert(L\"Mumble Launcher Error -2\", L\"Unable to find the absolute path of mumble_app.dll.\");\n\t\treturn -2;\n\t}\n\n\tHMODULE dll = LoadLibraryExW(abs_dll_path.c_str(), NULL, LOAD_WITH_ALTERED_SEARCH_PATH);\n\tif (!dll) {\n\t\tAlert(L\"Mumble Launcher Error -3\", L\"Failed to load mumble_app.dll.\");\n\t\treturn -3;\n\t}\n\n\tDLL_MAIN entry_point = reinterpret_cast<DLL_MAIN>(GetProcAddress(dll, \"MumbleMain\"));\n\tif (!entry_point) {\n\t\tAlert(L\"Mumble Launcher Error -4\", L\"Unable to find expected entry point ('MumbleMain') in mumble_app.dll.\");\n\t\treturn -4;\n\t}\n\n\t(void) cmdArg;\n\tint rc = entry_point(instance, prevInstance, NULL, cmdShow);\n\n\treturn rc;\n}\n<commit_msg>mumble_exe: do not add mumble.exe's parent directory to PATH.<commit_after>\/* Copyright (C) 2011-2013, Benjamin Jemlich <pcgod@users.sourceforge.net>\n Copyright (C) 2013, Mikkel Krautz <mikkel@krautz.dk>\n\n All rights reserved.\n\n Redistribution and use in source and binary forms, with or without\n modification, are permitted provided that the following conditions\n are met:\n\n - Redistributions of source code must retain the above copyright notice,\n this list of conditions and the following disclaimer.\n - Redistributions in binary form must reproduce the above copyright notice,\n this list of conditions and the following disclaimer in the documentation\n and\/or other materials provided with the distribution.\n - Neither the name of the Mumble Developers nor the names of its\n contributors may be used to endorse or promote products derived from this\n software without specific prior written permission.\n\n THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR\n CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*\/\n\n#include <windows.h>\n#include <shlwapi.h>\n#include <stdio.h>\n\n#include <string>\n\ntypedef int (*DLL_MAIN)(HINSTANCE, HINSTANCE, LPSTR, int);\n#ifdef DEBUG\ntypedef int (*DLL_DEBUG_MAIN)(int, char **);\n#endif\n\n\/\/ Alert shows a fatal error dialog and waits for the user to click OK.\nstatic void Alert(LPCWSTR title, LPCWSTR msg) {\n\tMessageBox(NULL, msg, title, MB_OK|MB_ICONERROR);\n}\n\n\/\/ GetExecutableDirPath returns the directory that\n\/\/ mumble.exe resides in.\nstatic std::wstring GetExecutableDirPath() {\n\twchar_t path[MAX_PATH];\n\n\tif (GetModuleFileNameW(NULL, path, MAX_PATH) == 0)\n\t\treturn std::wstring();\n\n\tif (!PathRemoveFileSpecW(path))\n\t\treturn std::wstring();\n\n\tstd::wstring exe_path(path);\n\treturn exe_path.append(L\"\\\\\");\n}\n\n\/\/ ConfigureEnvironment prepares mumble.exe's environment to\n\/\/ run mumble_app.dll.\nstatic bool ConfigureEnvironment() {\n\tstd::wstring exe_path = GetExecutableDirPath();\n\n\t\/\/ Remove the current directory from the DLL search path.\n\tif (!SetDllDirectoryW(L\"\"))\n\t\treturn false;\n\n\t\/\/ Set mumble.exe's directory as the current working directory.\n\tif (!SetCurrentDirectoryW(exe_path.c_str()))\n\t\treturn false;\n\n\treturn true;\n}\n\n\/\/ GetAbsoluteMumbleAppDllPath returns the absolute path to\n\/\/ mumble_app.dll - the DLL containing the Mumble client\n\/\/ application code.\nstatic std::wstring GetAbsoluteMumbleAppDllPath() {\n\tstd::wstring exe_path = GetExecutableDirPath();\n\tif (exe_path.empty())\n\t\treturn std::wstring();\n\n\tstd::wstring abs_dll_path(exe_path);\n\tabs_dll_path.append(L\"\\\\\");\n\tabs_dll_path.append(L\"mumble_app.dll\");\n\treturn abs_dll_path;\n}\n\n#ifdef DEBUG\nint main(int argc, char **argv) {\n\tif (!ConfigureEnvironment()) {\n\t\tAlert(L\"Mumble Launcher Error -1\", L\"Unable to configure environment.\");\n\t\treturn -1;\n\t}\n\n\tstd::wstring abs_dll_path = GetAbsoluteMumbleAppDllPath();\n\tif (abs_dll_path.empty()) {\n\t\tAlert(L\"Mumble Launcher Error -2\", L\"Unable to find the absolute path of mumble_app.dll.\");\n\t\treturn -2;\n\t}\n\n\tHMODULE dll = LoadLibraryExW(abs_dll_path.c_str(), NULL, LOAD_WITH_ALTERED_SEARCH_PATH);\n\tif (!dll) {\n\t\tAlert(L\"Mumble Launcher Error -3\", L\"Failed to load mumble_app.dll.\");\n\t\treturn -3;\n\t}\n\n\tDLL_DEBUG_MAIN entry_point = reinterpret_cast<DLL_DEBUG_MAIN>(GetProcAddress(dll, \"main\"));\n\tif (!entry_point) {\n\t\tAlert(L\"Mumble Launcher Error -4\", L\"Unable to find expected entry point ('main') in mumble_app.dll.\");\n\t\treturn -4;\n\t}\n\n\tint rc = entry_point(argc, argv);\n\n\treturn rc;\n}\n#endif \/\/ DEBUG\n\nint APIENTRY wWinMain(HINSTANCE instance, HINSTANCE prevInstance, wchar_t *cmdArg, int cmdShow) {\n\tif (!ConfigureEnvironment()) {\n\t\tAlert(L\"Mumble Launcher Error -1\", L\"Unable to configure environment.\");\n\t\treturn -1;\n\t}\n\n\tstd::wstring abs_dll_path = GetAbsoluteMumbleAppDllPath();\n\tif (abs_dll_path.empty()) {\n\t\tAlert(L\"Mumble Launcher Error -2\", L\"Unable to find the absolute path of mumble_app.dll.\");\n\t\treturn -2;\n\t}\n\n\tHMODULE dll = LoadLibraryExW(abs_dll_path.c_str(), NULL, LOAD_WITH_ALTERED_SEARCH_PATH);\n\tif (!dll) {\n\t\tAlert(L\"Mumble Launcher Error -3\", L\"Failed to load mumble_app.dll.\");\n\t\treturn -3;\n\t}\n\n\tDLL_MAIN entry_point = reinterpret_cast<DLL_MAIN>(GetProcAddress(dll, \"MumbleMain\"));\n\tif (!entry_point) {\n\t\tAlert(L\"Mumble Launcher Error -4\", L\"Unable to find expected entry point ('MumbleMain') in mumble_app.dll.\");\n\t\treturn -4;\n\t}\n\n\t(void) cmdArg;\n\tint rc = entry_point(instance, prevInstance, NULL, cmdShow);\n\n\treturn rc;\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ libavg - Media Playback Engine. \n\/\/ Copyright (C) 2003-2008 Ulrich von Zadow\n\/\/\n\/\/ This library is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU Lesser General Public\n\/\/ License as published by the Free Software Foundation; either\n\/\/ version 2 of the License, or (at your option) any later version.\n\/\/\n\/\/ This library is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ Lesser General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License along with this library; if not, write to the Free Software\n\/\/ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n\/\/\n\/\/ Current versions can be found at www.libavg.de\n\/\/\n\n#include \"CameraNode.h\"\n#include \"DisplayEngine.h\"\n#include \"OGLSurface.h\"\n#include \"NodeDefinition.h\"\n\n#include \"..\/base\/TimeSource.h\"\n#include \"..\/base\/Logger.h\"\n#include \"..\/base\/Exception.h\"\n#include \"..\/base\/ScopeTimer.h\"\n#include \"..\/base\/XMLHelper.h\"\n\n#include \"..\/graphics\/Filterfill.h\"\n\n#include \"..\/imaging\/Camera.h\"\n#include \"..\/imaging\/FWCamera.h\"\n#include \"..\/imaging\/FakeCamera.h\"\n\n#include <iostream>\n#include <sstream>\n#ifdef HAVE_UNISTD_H\n#include <unistd.h>\n#endif\n\nusing namespace std;\n\nnamespace avg {\n\nNodeDefinition CameraNode::createDefinition()\n{\n return NodeDefinition(\"camera\", VisibleNode::buildNode<CameraNode>)\n .extendDefinition(RasterNode::createDefinition())\n .addArg(Arg<string>(\"driver\", \"firewire\"))\n .addArg(Arg<string>(\"device\", \"\"))\n .addArg(Arg<int>(\"unit\", -1))\n .addArg(Arg<bool>(\"fw800\", false))\n .addArg(Arg<double>(\"framerate\", 15))\n .addArg(Arg<int>(\"capturewidth\", 640))\n .addArg(Arg<int>(\"captureheight\", 480))\n .addArg(Arg<string>(\"pixelformat\", \"RGB\"))\n .addArg(Arg<int>(\"brightness\", -1))\n .addArg(Arg<int>(\"exposure\", -1))\n .addArg(Arg<int>(\"sharpness\", -1))\n .addArg(Arg<int>(\"saturation\", -1))\n .addArg(Arg<int>(\"gamma\", -1))\n .addArg(Arg<int>(\"shutter\", -1))\n .addArg(Arg<int>(\"gain\", -1))\n .addArg(Arg<int>(\"strobeduration\", -1));\n}\n\nCameraNode::CameraNode(const ArgList& Args)\n : m_bIsPlaying(false),\n m_FrameNum(0),\n m_bIsAutoUpdateCameraImage(true)\n{\n Args.setMembers(this);\n string sDriver = Args.getArgVal<string>(\"driver\");\n string sDevice = Args.getArgVal<string>(\"device\");\n int unit = Args.getArgVal<int>(\"unit\");\n bool bFW800 = Args.getArgVal<bool>(\"fw800\");\n double FrameRate = Args.getArgVal<double>(\"framerate\");\n int Width = Args.getArgVal<int>(\"capturewidth\");\n int Height = Args.getArgVal<int>(\"captureheight\");\n string sPF = Args.getArgVal<string>(\"pixelformat\");\n\n PixelFormat camPF = Bitmap::stringToPixelFormat(sPF);\n if (camPF == NO_PIXELFORMAT) {\n throw Exception(AVG_ERR_INVALID_ARGS,\n \"Unknown camera pixel format \"+sPF+\".\");\n }\n PixelFormat destPF;\n if (Bitmap::pixelFormatIsColored(camPF)) {\n destPF = B8G8R8X8;\n } else {\n destPF = I8;\n }\n\/\/ cerr << \"CameraNode ctor: \" << Bitmap::getPixelFormatString(camPF) << \"-->\" << \n\/\/ Bitmap::getPixelFormatString(destPF) << endl;\n\n m_pCamera = createCamera(sDriver, sDevice, unit, bFW800, IntPoint(Width, Height), camPF, \n destPF, FrameRate);\n AVG_TRACE(Logger::CONFIG, \"Got Camera \" << m_pCamera->getDevice() << \" from driver: \"\n << m_pCamera->getDriverName());\n \n m_pCamera->setFeature(CAM_FEATURE_BRIGHTNESS,\n Args.getArgVal<int>(\"brightness\"));\n m_pCamera->setFeature(CAM_FEATURE_EXPOSURE,\n Args.getArgVal<int>(\"exposure\"));\n m_pCamera->setFeature(CAM_FEATURE_SHARPNESS,\n Args.getArgVal<int>(\"sharpness\"));\n m_pCamera->setFeature(CAM_FEATURE_SATURATION,\n Args.getArgVal<int>(\"saturation\"));\n m_pCamera->setFeature(CAM_FEATURE_GAMMA,\n Args.getArgVal<int>(\"gamma\"));\n m_pCamera->setFeature(CAM_FEATURE_SHUTTER,\n Args.getArgVal<int>(\"shutter\"));\n m_pCamera->setFeature(CAM_FEATURE_GAIN,\n Args.getArgVal<int>(\"gain\"));\n m_pCamera->setFeature(CAM_FEATURE_STROBE_DURATION,\n Args.getArgVal<int>(\"strobeduration\"));\n}\n\nCameraNode::~CameraNode()\n{\n m_pCamera = CameraPtr();\n}\n\nvoid CameraNode::setRenderingEngines(DisplayEngine * pDisplayEngine, \n AudioEngine * pAudioEngine)\n{\n RasterNode::setRenderingEngines(pDisplayEngine, pAudioEngine);\n if (m_bIsPlaying) {\n open();\n }\n}\n\nvoid CameraNode::play()\n{\n if (getState() == NS_CANRENDER) {\n open();\n }\n m_bIsPlaying = true;\n}\n\nvoid CameraNode::stop()\n{\n m_bIsPlaying = false;\n}\n\nbool CameraNode::isAvailable()\n{\n if (!m_pCamera || boost::dynamic_pointer_cast<FakeCamera>(m_pCamera)) {\n return false;\n } else {\n return true;\n }\n}\n\nint CameraNode::getBrightness() const\n{\n return getFeature(CAM_FEATURE_BRIGHTNESS);\n}\n\nvoid CameraNode::setBrightness(int Value)\n{\n setFeature(CAM_FEATURE_BRIGHTNESS, Value);\n}\n\nint CameraNode::getSharpness() const\n{\n return getFeature(CAM_FEATURE_SHARPNESS);\n}\n\nvoid CameraNode::setSharpness(int Value)\n{\n setFeature(CAM_FEATURE_SHARPNESS, Value);\n}\n\nint CameraNode::getSaturation() const\n{\n return getFeature(CAM_FEATURE_SATURATION);\n}\n\nvoid CameraNode::setSaturation(int Value)\n{\n setFeature(CAM_FEATURE_SATURATION, Value);\n}\n\nint CameraNode::getGamma() const\n{\n return getFeature(CAM_FEATURE_GAMMA);\n}\n\nvoid CameraNode::setGamma(int Value)\n{\n setFeature(CAM_FEATURE_GAMMA, Value);\n}\n\nint CameraNode::getShutter() const\n{\n return getFeature(CAM_FEATURE_SHUTTER);\n}\n\nvoid CameraNode::setShutter(int Value)\n{\n setFeature(CAM_FEATURE_SHUTTER, Value);\n}\n\nint CameraNode::getGain() const\n{\n return getFeature(CAM_FEATURE_GAIN);\n}\n\nvoid CameraNode::setGain(int Value)\n{\n setFeature(CAM_FEATURE_GAIN, Value);\n}\n\nint CameraNode::getWhitebalanceU() const\n{\n return m_pCamera->getWhitebalanceU();\n}\n\nint CameraNode::getWhitebalanceV() const\n{\n return m_pCamera->getWhitebalanceV();\n}\n\nvoid CameraNode::setWhitebalance(int u, int v)\n{\n m_pCamera->setWhitebalance(u, v);\n}\n\nvoid CameraNode::doOneShotWhitebalance()\n{\n \/\/ The first line turns off auto white balance.\n m_pCamera->setWhitebalance(m_pCamera->getWhitebalanceU(), \n m_pCamera->getWhitebalanceV());\n m_pCamera->setFeatureOneShot(CAM_FEATURE_WHITE_BALANCE);\n}\n\nint CameraNode::getStrobeDuration() const\n{\n return getFeature(CAM_FEATURE_STROBE_DURATION);\n}\n\nvoid CameraNode::setStrobeDuration(int Value)\n{\n setFeature(CAM_FEATURE_STROBE_DURATION, Value);\n}\n \n\nIntPoint CameraNode::getMediaSize()\n{\n return m_pCamera->getImgSize();\n}\n\nvoid CameraNode::dumpCameras()\n{\n avg::dumpCameras();\n}\n\nvoid CameraNode::resetFirewireBus()\n{\n FWCamera::resetBus();\n}\n\ndouble CameraNode::getFPS() const\n{\n return m_pCamera->getFrameRate();\n}\n\nvoid CameraNode::open()\n{\n setViewport(-32767, -32767, -32767, -32767);\n PixelFormat pf = getPixelFormat();\n getSurface()->create(getMediaSize(), pf);\n \n if (pf == B8G8R8X8 || pf == B8G8R8A8) {\n FilterFill<Pixel32> Filter(Pixel32(0,0,0,255));\n Filter.applyInPlace(getSurface()->lockBmp());\n getSurface()->unlockBmps();\n }\n}\n\nint CameraNode::getFeature(CameraFeature Feature) const\n{\n return m_pCamera->getFeature(Feature);\n}\n\nvoid CameraNode::setFeature(CameraFeature Feature, int Value)\n{\n m_pCamera->setFeature(Feature, Value);\n}\n\nint CameraNode::getFrameNum() const\n{\n return m_FrameNum;\n}\n\nstatic ProfilingZone CameraFetchImage(\"Camera fetch image\");\n\nvoid CameraNode::preRender()\n{\n VisibleNode::preRender();\n ScopeTimer Timer(CameraFetchImage);\n if (isAutoUpdateCameraImage()) {\n updateToLatestCameraImage();\n }\n}\n\nstatic ProfilingZone CameraProfilingZone(\"Camera::render\");\nstatic ProfilingZone CameraDownloadProfilingZone(\"Camera tex download\");\n\nvoid CameraNode::render(const DRect& Rect)\n{\n if (m_bIsPlaying) {\n ScopeTimer Timer(CameraProfilingZone);\n if (m_pCurBmp) {\n m_FrameNum++;\n BitmapPtr pBmp = getSurface()->lockBmp();\n if (pBmp->getPixelFormat() != m_pCurBmp->getPixelFormat()) {\n cerr << \"Surface: \" << pBmp->getPixelFormatString() << \", CamDest: \" \n << m_pCurBmp->getPixelFormatString() << endl;\n }\n AVG_ASSERT(pBmp->getPixelFormat() == m_pCurBmp->getPixelFormat());\n pBmp->copyPixels(*m_pCurBmp);\n getSurface()->unlockBmps();\n {\n ScopeTimer Timer(CameraDownloadProfilingZone);\n bind();\n }\n }\n blt32(getSize(), getEffectiveOpacity(), getBlendMode());\n }\n}\n\nPixelFormat CameraNode::getPixelFormat() \n{\n return m_pCamera->getDestPF();\n}\n\nvoid CameraNode::updateToLatestCameraImage()\n{\n m_pCurBmp = m_pCamera->getImage(false);\n if (m_pCurBmp) {\n BitmapPtr pTempBmp;\n while (pTempBmp = m_pCamera->getImage(false)) {\n m_pCurBmp = pTempBmp;\n }\n }\n}\n\nvoid CameraNode::updateCameraImage()\n{\n if (!isAutoUpdateCameraImage()) {\n m_pTmpBmp = m_pCamera->getImage(false);\n if (m_pTmpBmp) {\n m_pCurBmp = m_pTmpBmp;\n }\n }\n}\n\nbool CameraNode::isAutoUpdateCameraImage() const\n{\n return m_bIsAutoUpdateCameraImage;\n}\n\nvoid CameraNode::setAutoUpdateCameraImage(bool bVal)\n{\n m_bIsAutoUpdateCameraImage = bVal;\n}\n\nbool CameraNode::isImageAvailable() const\n{\n return m_pTmpBmp.get() != NULL;\n}\n\n\n} \/\/ namespace avg\n<commit_msg>Workaround for what appears to be an NVidia driver bug: glClear(STENCIL) on an fbo doesn't work. glClear(STENCIL|DEPTH) works.<commit_after>\/\/\n\/\/ libavg - Media Playback Engine. \n\/\/ Copyright (C) 2003-2008 Ulrich von Zadow\n\/\/\n\/\/ This library is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU Lesser General Public\n\/\/ License as published by the Free Software Foundation; either\n\/\/ version 2 of the License, or (at your option) any later version.\n\/\/\n\/\/ This library is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ Lesser General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License along with this library; if not, write to the Free Software\n\/\/ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n\/\/\n\/\/ Current versions can be found at www.libavg.de\n\/\/\n\n#include \"CameraNode.h\"\n#include \"DisplayEngine.h\"\n#include \"OGLSurface.h\"\n#include \"NodeDefinition.h\"\n\n#include \"..\/base\/TimeSource.h\"\n#include \"..\/base\/Logger.h\"\n#include \"..\/base\/Exception.h\"\n#include \"..\/base\/ScopeTimer.h\"\n#include \"..\/base\/XMLHelper.h\"\n\n#include \"..\/graphics\/Filterfill.h\"\n\n#include \"..\/imaging\/Camera.h\"\n#include \"..\/imaging\/FWCamera.h\"\n#include \"..\/imaging\/FakeCamera.h\"\n\n#include <iostream>\n#include <sstream>\n#ifdef HAVE_UNISTD_H\n#include <unistd.h>\n#endif\n\nusing namespace std;\n\nnamespace avg {\n\nNodeDefinition CameraNode::createDefinition()\n{\n return NodeDefinition(\"camera\", VisibleNode::buildNode<CameraNode>)\n .extendDefinition(RasterNode::createDefinition())\n .addArg(Arg<string>(\"driver\", \"firewire\"))\n .addArg(Arg<string>(\"device\", \"\"))\n .addArg(Arg<int>(\"unit\", -1))\n .addArg(Arg<bool>(\"fw800\", false))\n .addArg(Arg<double>(\"framerate\", 15))\n .addArg(Arg<int>(\"capturewidth\", 640))\n .addArg(Arg<int>(\"captureheight\", 480))\n .addArg(Arg<string>(\"pixelformat\", \"RGB\"))\n .addArg(Arg<int>(\"brightness\", -1))\n .addArg(Arg<int>(\"exposure\", -1))\n .addArg(Arg<int>(\"sharpness\", -1))\n .addArg(Arg<int>(\"saturation\", -1))\n .addArg(Arg<int>(\"gamma\", -1))\n .addArg(Arg<int>(\"shutter\", -1))\n .addArg(Arg<int>(\"gain\", -1))\n .addArg(Arg<int>(\"strobeduration\", -1));\n}\n\nCameraNode::CameraNode(const ArgList& Args)\n : m_bIsPlaying(false),\n m_FrameNum(0),\n m_bIsAutoUpdateCameraImage(true)\n{\n Args.setMembers(this);\n string sDriver = Args.getArgVal<string>(\"driver\");\n string sDevice = Args.getArgVal<string>(\"device\");\n int unit = Args.getArgVal<int>(\"unit\");\n bool bFW800 = Args.getArgVal<bool>(\"fw800\");\n double FrameRate = Args.getArgVal<double>(\"framerate\");\n int Width = Args.getArgVal<int>(\"capturewidth\");\n int Height = Args.getArgVal<int>(\"captureheight\");\n string sPF = Args.getArgVal<string>(\"pixelformat\");\n\n PixelFormat camPF = Bitmap::stringToPixelFormat(sPF);\n if (camPF == NO_PIXELFORMAT) {\n throw Exception(AVG_ERR_INVALID_ARGS,\n \"Unknown camera pixel format \"+sPF+\".\");\n }\n PixelFormat destPF;\n if (Bitmap::pixelFormatIsColored(camPF)) {\n destPF = B8G8R8X8;\n } else {\n destPF = I8;\n }\n\/\/ cerr << \"CameraNode ctor: \" << Bitmap::getPixelFormatString(camPF) << \"-->\" << \n\/\/ Bitmap::getPixelFormatString(destPF) << endl;\n\n m_pCamera = createCamera(sDriver, sDevice, unit, bFW800, IntPoint(Width, Height), camPF, \n destPF, FrameRate);\n AVG_TRACE(Logger::CONFIG, \"Got Camera \" << m_pCamera->getDevice() << \" from driver: \"\n << m_pCamera->getDriverName());\n \n m_pCamera->setFeature(CAM_FEATURE_BRIGHTNESS,\n Args.getArgVal<int>(\"brightness\"));\n m_pCamera->setFeature(CAM_FEATURE_EXPOSURE,\n Args.getArgVal<int>(\"exposure\"));\n m_pCamera->setFeature(CAM_FEATURE_SHARPNESS,\n Args.getArgVal<int>(\"sharpness\"));\n m_pCamera->setFeature(CAM_FEATURE_SATURATION,\n Args.getArgVal<int>(\"saturation\"));\n m_pCamera->setFeature(CAM_FEATURE_GAMMA,\n Args.getArgVal<int>(\"gamma\"));\n m_pCamera->setFeature(CAM_FEATURE_SHUTTER,\n Args.getArgVal<int>(\"shutter\"));\n m_pCamera->setFeature(CAM_FEATURE_GAIN,\n Args.getArgVal<int>(\"gain\"));\n m_pCamera->setFeature(CAM_FEATURE_STROBE_DURATION,\n Args.getArgVal<int>(\"strobeduration\"));\n}\n\nCameraNode::~CameraNode()\n{\n m_pCamera = CameraPtr();\n}\n\nvoid CameraNode::setRenderingEngines(DisplayEngine * pDisplayEngine, \n AudioEngine * pAudioEngine)\n{\n RasterNode::setRenderingEngines(pDisplayEngine, pAudioEngine);\n if (m_bIsPlaying) {\n open();\n }\n}\n\nvoid CameraNode::play()\n{\n if (getState() == NS_CANRENDER) {\n open();\n }\n m_bIsPlaying = true;\n}\n\nvoid CameraNode::stop()\n{\n m_bIsPlaying = false;\n}\n\nbool CameraNode::isAvailable()\n{\n if (!m_pCamera || boost::dynamic_pointer_cast<FakeCamera>(m_pCamera)) {\n return false;\n } else {\n return true;\n }\n}\n\nint CameraNode::getBrightness() const\n{\n return getFeature(CAM_FEATURE_BRIGHTNESS);\n}\n\nvoid CameraNode::setBrightness(int Value)\n{\n setFeature(CAM_FEATURE_BRIGHTNESS, Value);\n}\n\nint CameraNode::getSharpness() const\n{\n return getFeature(CAM_FEATURE_SHARPNESS);\n}\n\nvoid CameraNode::setSharpness(int Value)\n{\n setFeature(CAM_FEATURE_SHARPNESS, Value);\n}\n\nint CameraNode::getSaturation() const\n{\n return getFeature(CAM_FEATURE_SATURATION);\n}\n\nvoid CameraNode::setSaturation(int Value)\n{\n setFeature(CAM_FEATURE_SATURATION, Value);\n}\n\nint CameraNode::getGamma() const\n{\n return getFeature(CAM_FEATURE_GAMMA);\n}\n\nvoid CameraNode::setGamma(int Value)\n{\n setFeature(CAM_FEATURE_GAMMA, Value);\n}\n\nint CameraNode::getShutter() const\n{\n return getFeature(CAM_FEATURE_SHUTTER);\n}\n\nvoid CameraNode::setShutter(int Value)\n{\n setFeature(CAM_FEATURE_SHUTTER, Value);\n}\n\nint CameraNode::getGain() const\n{\n return getFeature(CAM_FEATURE_GAIN);\n}\n\nvoid CameraNode::setGain(int Value)\n{\n setFeature(CAM_FEATURE_GAIN, Value);\n}\n\nint CameraNode::getWhitebalanceU() const\n{\n return m_pCamera->getWhitebalanceU();\n}\n\nint CameraNode::getWhitebalanceV() const\n{\n return m_pCamera->getWhitebalanceV();\n}\n\nvoid CameraNode::setWhitebalance(int u, int v)\n{\n m_pCamera->setWhitebalance(u, v);\n}\n\nvoid CameraNode::doOneShotWhitebalance()\n{\n \/\/ The first line turns off auto white balance.\n m_pCamera->setWhitebalance(m_pCamera->getWhitebalanceU(), \n m_pCamera->getWhitebalanceV());\n m_pCamera->setFeatureOneShot(CAM_FEATURE_WHITE_BALANCE);\n}\n\nint CameraNode::getStrobeDuration() const\n{\n return getFeature(CAM_FEATURE_STROBE_DURATION);\n}\n\nvoid CameraNode::setStrobeDuration(int Value)\n{\n setFeature(CAM_FEATURE_STROBE_DURATION, Value);\n}\n \n\nIntPoint CameraNode::getMediaSize()\n{\n return m_pCamera->getImgSize();\n}\n\nvoid CameraNode::dumpCameras()\n{\n avg::dumpCameras();\n}\n\nvoid CameraNode::resetFirewireBus()\n{\n FWCamera::resetBus();\n}\n\ndouble CameraNode::getFPS() const\n{\n return m_pCamera->getFrameRate();\n}\n\nvoid CameraNode::open()\n{\n setViewport(-32767, -32767, -32767, -32767);\n PixelFormat pf = getPixelFormat();\n getSurface()->create(getMediaSize(), pf);\n \n if (pf == B8G8R8X8 || pf == B8G8R8A8) {\n FilterFill<Pixel32> Filter(Pixel32(0,0,0,255));\n Filter.applyInPlace(getSurface()->lockBmp());\n getSurface()->unlockBmps();\n }\n}\n\nint CameraNode::getFeature(CameraFeature Feature) const\n{\n return m_pCamera->getFeature(Feature);\n}\n\nvoid CameraNode::setFeature(CameraFeature Feature, int Value)\n{\n m_pCamera->setFeature(Feature, Value);\n}\n\nint CameraNode::getFrameNum() const\n{\n return m_FrameNum;\n}\n\nstatic ProfilingZone CameraFetchImage(\"Camera fetch image\");\n\nvoid CameraNode::preRender()\n{\n VisibleNode::preRender();\n ScopeTimer Timer(CameraFetchImage);\n if (isAutoUpdateCameraImage()) {\n updateToLatestCameraImage();\n }\n}\n\nstatic ProfilingZone CameraProfilingZone(\"Camera::render\");\nstatic ProfilingZone CameraDownloadProfilingZone(\"Camera tex download\");\n\nvoid CameraNode::render(const DRect& Rect)\n{\n if (m_bIsPlaying) {\n ScopeTimer Timer(CameraProfilingZone);\n if (m_pCurBmp) {\n m_FrameNum++;\n BitmapPtr pBmp = getSurface()->lockBmp();\n if (pBmp->getPixelFormat() != m_pCurBmp->getPixelFormat()) {\n cerr << \"Surface: \" << pBmp->getPixelFormatString() << \", CamDest: \"\n << m_pCurBmp->getPixelFormatString() << endl;\n }\n AVG_ASSERT(pBmp->getPixelFormat() == m_pCurBmp->getPixelFormat());\n pBmp->copyPixels(*m_pCurBmp);\n getSurface()->unlockBmps();\n {\n ScopeTimer Timer(CameraDownloadProfilingZone);\n bind();\n }\n }\n blt32(getSize(), getEffectiveOpacity(), getBlendMode());\n }\n}\n\nPixelFormat CameraNode::getPixelFormat() \n{\n return m_pCamera->getDestPF();\n}\n\nvoid CameraNode::updateToLatestCameraImage()\n{\n m_pCurBmp = m_pCamera->getImage(false);\n if (m_pCurBmp) {\n BitmapPtr pTempBmp;\n while (pTempBmp = m_pCamera->getImage(false)) {\n m_pCurBmp = pTempBmp;\n }\n }\n}\n\nvoid CameraNode::updateCameraImage()\n{\n if (!isAutoUpdateCameraImage()) {\n m_pCurBmp = m_pCamera->getImage(false);\n blt32(getSize(), getEffectiveOpacity(), getBlendMode());\n }\n}\n\nbool CameraNode::isAutoUpdateCameraImage() const\n{\n return m_bIsAutoUpdateCameraImage;\n}\n\nvoid CameraNode::setAutoUpdateCameraImage(bool bVal)\n{\n m_bIsAutoUpdateCameraImage = bVal;\n}\n\nbool CameraNode::isImageAvailable() const\n{\n return m_pCurBmp.get() != NULL;\n}\n\n\n} \/\/ namespace avg\n<|endoftext|>"} {"text":"<commit_before>\/\/\n\/\/ libavg - Media Playback Engine. \n\/\/ Copyright (C) 2003-2008 Ulrich von Zadow\n\/\/\n\/\/ This library is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU Lesser General Public\n\/\/ License as published by the Free Software Foundation; either\n\/\/ version 2 of the License, or (at your option) any later version.\n\/\/\n\/\/ This library is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ Lesser General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License along with this library; if not, write to the Free Software\n\/\/ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n\/\/\n\/\/ Current versions can be found at www.libavg.de\n\/\/\n\n#include \"CameraNode.h\"\n#include \"DisplayEngine.h\"\n#include \"Player.h\"\n#include \"ISurface.h\"\n#include \"NodeDefinition.h\"\n\n#include \"..\/base\/TimeSource.h\"\n#include \"..\/base\/Logger.h\"\n#include \"..\/base\/Exception.h\"\n#include \"..\/base\/ScopeTimer.h\"\n#include \"..\/base\/XMLHelper.h\"\n\n#include \"..\/imaging\/FWCamera.h\"\n#ifdef AVG_ENABLE_V4L2\n#include \"..\/imaging\/V4LCamera.h\"\n#endif\n#ifdef _WIN32\n#include \"..\/imaging\/DSCamera.h\"\n#endif\n\n#include <iostream>\n#include <sstream>\n#include <unistd.h>\n\nusing namespace std;\n\nnamespace avg {\n\nNodeDefinition CameraNode::getNodeDefinition()\n{\n return NodeDefinition(\"camera\", Node::buildNode<CameraNode>)\n .extendDefinition(VideoBase::getNodeDefinition())\n .addArg(Arg<string>(\"device\", \"\"))\n .addArg(Arg<double>(\"framerate\", 15))\n .addArg(Arg<string>(\"source\", \"firewire\"))\n .addArg(Arg<int>(\"capturewidth\", 640))\n .addArg(Arg<int>(\"captureheight\", 480))\n .addArg(Arg<string>(\"pixelformat\", \"RGB\"))\n .addArg(Arg<int>(\"channel\", 0))\n .addArg(Arg<int>(\"brightness\", -1))\n .addArg(Arg<int>(\"exposure\", -1))\n .addArg(Arg<int>(\"sharpness\", -1))\n .addArg(Arg<int>(\"saturation\", -1))\n .addArg(Arg<int>(\"gamma\", -1))\n .addArg(Arg<int>(\"shutter\", -1))\n .addArg(Arg<int>(\"gain\", -1))\n .addArg(Arg<int>(\"whitebalance\", -1));\n}\n\nCameraNode::CameraNode(const ArgList& Args, Player * pPlayer, bool bFromXML)\n : VideoBase(pPlayer),\n m_FrameNum(0)\n{\n Args.setMembers(this);\n string sDevice = Args.getArgVal<string>(\"device\");\n double FrameRate = Args.getArgVal<double>(\"framerate\");\n string sSource = Args.getArgVal<string>(\"source\");\n int Width = Args.getArgVal<int>(\"capturewidth\");\n int Height = Args.getArgVal<int>(\"captureheight\");\n string sPF = Args.getArgVal<string>(\"pixelformat\");\n\n if (sSource == \"firewire\") {\n#if defined(AVG_ENABLE_1394)\\\n || defined(AVG_ENABLE_1394_2)\n m_pCamera = CameraPtr(new FWCamera(sDevice, IntPoint(Width, Height), sPF, \n FrameRate, true));\n#else\n AVG_TRACE(Logger::ERROR, \"Firewire camera specified, but firewire \"\n \"support not compiled in.\");\n#endif\n } else if (sSource == \"v4l\") {\n#if defined(AVG_ENABLE_V4L2)\n int Channel = Args.getArgVal<int>(\"channel\");\n \n m_pCamera = CameraPtr(new V4LCamera(sDevice, Channel,\n IntPoint(Width, Height), sPF, true));\n#else\n AVG_TRACE(Logger::ERROR, \"Video4Linux camera specified, but \"\n \"Video4Linux support not compiled in.\");\n#endif\n } else if (sSource == \"directshow\") {\n#if defined(_WIN32)\n m_pCamera = CameraPtr(new DSCamera(sDevice, IntPoint(Width, Height), sPF, \n FrameRate, true));\n#else\n AVG_TRACE(Logger::ERROR, \"DirectShow camera specified, but \"\n \"DirectShow is only available under windows.\");\n#endif\n } else {\n AVG_TRACE(Logger::ERROR,\n \"Unable to set up camera. Camera source '\"+sSource+\"' unknown.\");\n }\n\n if (m_pCamera) {\n m_pCamera->setFeature (CAM_FEATURE_BRIGHTNESS,\n Args.getArgVal<int>(\"brightness\"));\n m_pCamera->setFeature (CAM_FEATURE_EXPOSURE,\n Args.getArgVal<int>(\"exposure\"));\n m_pCamera->setFeature (CAM_FEATURE_SHARPNESS,\n Args.getArgVal<int>(\"sharpness\"));\n m_pCamera->setFeature (CAM_FEATURE_SATURATION,\n Args.getArgVal<int>(\"saturation\"));\n m_pCamera->setFeature (CAM_FEATURE_GAMMA,\n Args.getArgVal<int>(\"gamma\"));\n m_pCamera->setFeature (CAM_FEATURE_SHUTTER,\n Args.getArgVal<int>(\"shutter\"));\n m_pCamera->setFeature (CAM_FEATURE_GAIN,\n Args.getArgVal<int>(\"gain\"));\n m_pCamera->setFeature (CAM_FEATURE_WHITE_BALANCE,\n Args.getArgVal<int>(\"whitebalance\"));\n }\n}\n\nCameraNode::~CameraNode()\n{\n close();\n}\n\nvoid CameraNode::setRenderingEngines(DisplayEngine * pDisplayEngine, AudioEngine * pAudioEngine)\n{\n VideoBase::setRenderingEngines(pDisplayEngine, pAudioEngine);\n}\n\nstring CameraNode::getTypeStr()\n{\n return \"Camera\";\n}\n\nint CameraNode::getBrightness() const\n{\n return getFeature (CAM_FEATURE_BRIGHTNESS);\n}\n\nvoid CameraNode::setBrightness(int Value)\n{\n setFeature (CAM_FEATURE_BRIGHTNESS, Value);\n}\n\nint CameraNode::getExposure() const\n{\n return getFeature (CAM_FEATURE_EXPOSURE);\n}\n\nvoid CameraNode::setExposure(int Value)\n{\n setFeature (CAM_FEATURE_EXPOSURE, Value);\n}\n\nint CameraNode::getSharpness() const\n{\n return getFeature (CAM_FEATURE_SHARPNESS);\n}\n\nvoid CameraNode::setSharpness(int Value)\n{\n setFeature (CAM_FEATURE_SHARPNESS, Value);\n}\n\nint CameraNode::getSaturation() const\n{\n return getFeature (CAM_FEATURE_SATURATION);\n}\n\nvoid CameraNode::setSaturation(int Value)\n{\n setFeature (CAM_FEATURE_SATURATION, Value);\n}\n\nint CameraNode::getGamma() const\n{\n return getFeature (CAM_FEATURE_GAMMA);\n}\n\nvoid CameraNode::setGamma(int Value)\n{\n setFeature (CAM_FEATURE_GAMMA, Value);\n}\n\nint CameraNode::getShutter() const\n{\n return getFeature (CAM_FEATURE_SHUTTER);\n}\n\nvoid CameraNode::setShutter(int Value)\n{\n setFeature (CAM_FEATURE_SHUTTER, Value);\n}\n\nint CameraNode::getGain() const\n{\n return getFeature (CAM_FEATURE_GAIN);\n}\n\nvoid CameraNode::setGain(int Value)\n{\n setFeature (CAM_FEATURE_GAIN, Value);\n}\n\nunsigned int CameraNode::getWhiteBalance() const\n{\n return getFeature (CAM_FEATURE_WHITE_BALANCE);\n}\n\nvoid CameraNode::setWhiteBalance(int Value)\n{\n setFeature (CAM_FEATURE_WHITE_BALANCE, Value);\n}\n \n\nIntPoint CameraNode::getMediaSize()\n{\n if (m_pCamera) {\n return m_pCamera->getImgSize();\n } else {\n return IntPoint(640,480);\n }\n}\n\ndouble CameraNode::getFPS()\n{\n if (m_pCamera) {\n return m_pCamera->getFrameRate();\n } else {\n return 0;\n }\n}\n\nvoid CameraNode::open(YCbCrMode ycbcrMode)\n{\n if (m_pCamera) {\n m_pCamera->open();\n }\n}\n\nvoid CameraNode::close()\n{\n if (m_pCamera) {\n m_pCamera->close();\n }\n}\n\nunsigned int CameraNode::getFeature(CameraFeature Feature) const\n{\n if (m_pCamera) {\n return m_pCamera->getFeature(Feature);\n } else {\n return 0;\n }\n}\n\nvoid CameraNode::setFeature(CameraFeature Feature, int Value)\n{\n if (m_pCamera) {\n m_pCamera->setFeature(Feature, Value);\n } \n}\n\nint CameraNode::getFrameNum() const\n{\n return m_FrameNum;\n}\n\nstatic ProfilingZone CameraFetchImage(\"Camera fetch image\");\nstatic ProfilingZone CameraProfilingZone(\"Camera::render\");\nstatic ProfilingZone CameraUploadProfilingZone(\"Camera tex download\");\n\nvoid CameraNode::preRender()\n{\n if (m_pCamera) {\n ScopeTimer Timer(CameraFetchImage);\n pCurBmp = m_pCamera->getImage(false);\n if (pCurBmp) {\n BitmapPtr pTempBmp;\n while (pTempBmp = m_pCamera->getImage(false)) {\n pCurBmp = pTempBmp;\n }\n m_FrameNum++;\n }\n }\n}\n\nbool CameraNode::renderToSurface(ISurface * pSurface)\n{\n if (m_pCamera) {\n ScopeTimer Timer(CameraProfilingZone);\n if (pCurBmp) {\n BitmapPtr pBmp = pSurface->lockBmp();\n assert(pBmp->getPixelFormat() == pCurBmp->getPixelFormat());\n pBmp->copyPixels(*pCurBmp);\n pSurface->unlockBmps();\n {\n ScopeTimer Timer(CameraUploadProfilingZone);\n getDisplayEngine()->surfaceChanged(pSurface);\n }\n }\n }\n return true;\n}\n\nPixelFormat CameraNode::getPixelFormat() \n{\n return B8G8R8X8;\n}\n\n\n}\n<commit_msg>File permission cosmetics.<commit_after>\/\/\n\/\/ libavg - Media Playback Engine. \n\/\/ Copyright (C) 2003-2008 Ulrich von Zadow\n\/\/\n\/\/ This library is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU Lesser General Public\n\/\/ License as published by the Free Software Foundation; either\n\/\/ version 2 of the License, or (at your option) any later version.\n\/\/\n\/\/ This library is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ Lesser General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License along with this library; if not, write to the Free Software\n\/\/ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n\/\/\n\/\/ Current versions can be found at www.libavg.de\n\/\/\n\n#include \"CameraNode.h\"\n#include \"DisplayEngine.h\"\n#include \"Player.h\"\n#include \"ISurface.h\"\n#include \"NodeDefinition.h\"\n\n#include \"..\/base\/TimeSource.h\"\n#include \"..\/base\/Logger.h\"\n#include \"..\/base\/Exception.h\"\n#include \"..\/base\/ScopeTimer.h\"\n#include \"..\/base\/XMLHelper.h\"\n\n#include \"..\/imaging\/FWCamera.h\"\n#ifdef AVG_ENABLE_V4L2\n#include \"..\/imaging\/V4LCamera.h\"\n#endif\n#ifdef _WIN32\n#include \"..\/imaging\/DSCamera.h\"\n#endif\n\n#include <iostream>\n#include <sstream>\n#include <unistd.h>\n\nusing namespace std;\n\nnamespace avg {\n\nNodeDefinition CameraNode::getNodeDefinition()\n{\n return NodeDefinition(\"camera\", Node::buildNode<CameraNode>)\n .extendDefinition(VideoBase::getNodeDefinition())\n .addArg(Arg<string>(\"device\", \"\"))\n .addArg(Arg<double>(\"framerate\", 15))\n .addArg(Arg<string>(\"source\", \"firewire\"))\n .addArg(Arg<int>(\"capturewidth\", 640))\n .addArg(Arg<int>(\"captureheight\", 480))\n .addArg(Arg<string>(\"pixelformat\", \"RGB\"))\n .addArg(Arg<int>(\"channel\", 0))\n .addArg(Arg<int>(\"brightness\", -1))\n .addArg(Arg<int>(\"exposure\", -1))\n .addArg(Arg<int>(\"sharpness\", -1))\n .addArg(Arg<int>(\"saturation\", -1))\n .addArg(Arg<int>(\"gamma\", -1))\n .addArg(Arg<int>(\"shutter\", -1))\n .addArg(Arg<int>(\"gain\", -1))\n .addArg(Arg<int>(\"whitebalance\", -1));\n}\n\nCameraNode::CameraNode(const ArgList& Args, Player * pPlayer, bool bFromXML)\n : VideoBase(pPlayer),\n m_FrameNum(0)\n{\n Args.setMembers(this);\n string sDevice = Args.getArgVal<string>(\"device\");\n double FrameRate = Args.getArgVal<double>(\"framerate\");\n string sSource = Args.getArgVal<string>(\"source\");\n int Width = Args.getArgVal<int>(\"capturewidth\");\n int Height = Args.getArgVal<int>(\"captureheight\");\n string sPF = Args.getArgVal<string>(\"pixelformat\");\n\n if (sSource == \"firewire\") {\n#if defined(AVG_ENABLE_1394)\\\n || defined(AVG_ENABLE_1394_2)\n m_pCamera = CameraPtr(new FWCamera(sDevice, IntPoint(Width, Height), sPF, \n FrameRate, true));\n#else\n AVG_TRACE(Logger::ERROR, \"Firewire camera specified, but firewire \"\n \"support not compiled in.\");\n#endif\n } else if (sSource == \"v4l\") {\n#if defined(AVG_ENABLE_V4L2)\n int Channel = Args.getArgVal<int>(\"channel\");\n \n m_pCamera = CameraPtr(new V4LCamera(sDevice, Channel,\n IntPoint(Width, Height), sPF, true));\n#else\n AVG_TRACE(Logger::ERROR, \"Video4Linux camera specified, but \"\n \"Video4Linux support not compiled in.\");\n#endif\n } else if (sSource == \"directshow\") {\n#if defined(_WIN32)\n m_pCamera = CameraPtr(new DSCamera(sDevice, IntPoint(Width, Height), sPF, \n FrameRate, true));\n#else\n AVG_TRACE(Logger::ERROR, \"DirectShow camera specified, but \"\n \"DirectShow is only available under windows.\");\n#endif\n } else {\n AVG_TRACE(Logger::ERROR,\n \"Unable to set up camera. Camera source '\"+sSource+\"' unknown.\");\n }\n\n if (m_pCamera) {\n m_pCamera->setFeature (CAM_FEATURE_BRIGHTNESS,\n Args.getArgVal<int>(\"brightness\"));\n m_pCamera->setFeature (CAM_FEATURE_EXPOSURE,\n Args.getArgVal<int>(\"exposure\"));\n m_pCamera->setFeature (CAM_FEATURE_SHARPNESS,\n Args.getArgVal<int>(\"sharpness\"));\n m_pCamera->setFeature (CAM_FEATURE_SATURATION,\n Args.getArgVal<int>(\"saturation\"));\n m_pCamera->setFeature (CAM_FEATURE_GAMMA,\n Args.getArgVal<int>(\"gamma\"));\n m_pCamera->setFeature (CAM_FEATURE_SHUTTER,\n Args.getArgVal<int>(\"shutter\"));\n m_pCamera->setFeature (CAM_FEATURE_GAIN,\n Args.getArgVal<int>(\"gain\"));\n m_pCamera->setFeature (CAM_FEATURE_WHITE_BALANCE,\n Args.getArgVal<int>(\"whitebalance\"));\n }\n}\n\nCameraNode::~CameraNode()\n{\n close();\n}\n\nvoid CameraNode::setRenderingEngines(DisplayEngine * pDisplayEngine, AudioEngine * pAudioEngine)\n{\n VideoBase::setRenderingEngines(pDisplayEngine, pAudioEngine);\n}\n\nstring CameraNode::getTypeStr()\n{\n return \"Camera\";\n}\n\nint CameraNode::getBrightness() const\n{\n return getFeature (CAM_FEATURE_BRIGHTNESS);\n}\n\nvoid CameraNode::setBrightness(int Value)\n{\n setFeature (CAM_FEATURE_BRIGHTNESS, Value);\n}\n\nint CameraNode::getExposure() const\n{\n return getFeature (CAM_FEATURE_EXPOSURE);\n}\n\nvoid CameraNode::setExposure(int Value)\n{\n setFeature (CAM_FEATURE_EXPOSURE, Value);\n}\n\nint CameraNode::getSharpness() const\n{\n return getFeature (CAM_FEATURE_SHARPNESS);\n}\n\nvoid CameraNode::setSharpness(int Value)\n{\n setFeature (CAM_FEATURE_SHARPNESS, Value);\n}\n\nint CameraNode::getSaturation() const\n{\n return getFeature (CAM_FEATURE_SATURATION);\n}\n\nvoid CameraNode::setSaturation(int Value)\n{\n setFeature (CAM_FEATURE_SATURATION, Value);\n}\n\nint CameraNode::getGamma() const\n{\n return getFeature (CAM_FEATURE_GAMMA);\n}\n\nvoid CameraNode::setGamma(int Value)\n{\n setFeature (CAM_FEATURE_GAMMA, Value);\n}\n\nint CameraNode::getShutter() const\n{\n return getFeature (CAM_FEATURE_SHUTTER);\n}\n\nvoid CameraNode::setShutter(int Value)\n{\n setFeature (CAM_FEATURE_SHUTTER, Value);\n}\n\nint CameraNode::getGain() const\n{\n return getFeature (CAM_FEATURE_GAIN);\n}\n\nvoid CameraNode::setGain(int Value)\n{\n setFeature (CAM_FEATURE_GAIN, Value);\n}\n\nunsigned int CameraNode::getWhiteBalance() const\n{\n return getFeature (CAM_FEATURE_WHITE_BALANCE);\n}\n\nvoid CameraNode::setWhiteBalance(int Value)\n{\n setFeature (CAM_FEATURE_WHITE_BALANCE, Value);\n}\n \n\nIntPoint CameraNode::getMediaSize()\n{\n if (m_pCamera) {\n return m_pCamera->getImgSize();\n } else {\n return IntPoint(640,480);\n }\n}\n\ndouble CameraNode::getFPS()\n{\n if (m_pCamera) {\n return m_pCamera->getFrameRate();\n } else {\n return 0;\n }\n}\n\nvoid CameraNode::open(YCbCrMode ycbcrMode)\n{\n if (m_pCamera) {\n m_pCamera->open();\n }\n}\n\nvoid CameraNode::close()\n{\n if (m_pCamera) {\n m_pCamera->close();\n }\n}\n\nunsigned int CameraNode::getFeature(CameraFeature Feature) const\n{\n if (m_pCamera) {\n return m_pCamera->getFeature(Feature);\n } else {\n return 0;\n }\n}\n\nvoid CameraNode::setFeature(CameraFeature Feature, int Value)\n{\n if (m_pCamera) {\n m_pCamera->setFeature(Feature, Value);\n } \n}\n\nint CameraNode::getFrameNum() const\n{\n return m_FrameNum;\n}\n\nstatic ProfilingZone CameraFetchImage(\"Camera fetch image\");\nstatic ProfilingZone CameraProfilingZone(\"Camera::render\");\nstatic ProfilingZone CameraUploadProfilingZone(\"Camera tex download\");\n\nvoid CameraNode::preRender()\n{\n if (m_pCamera) {\n ScopeTimer Timer(CameraFetchImage);\n pCurBmp = m_pCamera->getImage(false);\n if (pCurBmp) {\n BitmapPtr pTempBmp;\n while (pTempBmp = m_pCamera->getImage(false)) {\n pCurBmp = pTempBmp;\n }\n m_FrameNum++;\n }\n }\n}\n\nbool CameraNode::renderToSurface(ISurface * pSurface)\n{\n if (m_pCamera) {\n ScopeTimer Timer(CameraProfilingZone);\n if (pCurBmp) {\n BitmapPtr pBmp = pSurface->lockBmp();\n assert(pBmp->getPixelFormat() == pCurBmp->getPixelFormat());\n pBmp->copyPixels(*pCurBmp);\n pSurface->unlockBmps();\n {\n ScopeTimer Timer(CameraUploadProfilingZone);\n getDisplayEngine()->surfaceChanged(pSurface);\n }\n }\n }\n return true;\n}\n\nPixelFormat CameraNode::getPixelFormat() \n{\n return B8G8R8X8;\n}\n\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ -*- mode:c++;coding:utf-8; -*- vim:ts=2:sw=2:expandtab:autoindent:filetype=cpp:enc=utf-8:\n\/*\nThe MIT License\n\nCopyright (c) 2008, 2009 Flusspferd contributors (see \"CONTRIBUTORS\" or\n http:\/\/flusspferd.org\/contributors.txt)\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n*\/\n\n#include \"flusspferd\/create.hpp\"\n#include \"flusspferd\/binary.hpp\"\n#include \"flusspferd\/tracer.hpp\"\n#include \"flusspferd\/modules.hpp\"\n#include \"flusspferd\/security.hpp\"\n#include \"flusspferd\/arguments.hpp\"\n#include \"flusspferd\/class_description.hpp\"\n#include \"flusspferd\/property_iterator.hpp\"\n\n#include <sstream>\n#include <curl\/curl.h>\n\n#include <boost\/ptr_container\/ptr_unordered_map.hpp>\n#include <boost\/exception\/get_error_info.hpp>\n#include <boost\/assign\/ptr_map_inserter.hpp>\n#include <boost\/version.hpp>\n\n#include <iostream>\n\nusing namespace flusspferd;\n\nnamespace {\n\ttypedef boost::error_info<struct tag_curlcode, CURLcode> curlcode_info;\n\n\tstruct exception\n\t\t: flusspferd::exception\n\t{\n\t\texception(std::string const &what)\n\t\t\t: std::runtime_error(what), flusspferd::exception(what)\n\t\t{ }\n\n\t\tchar const *what() const throw() {\n\t\t\tif(CURLcode const *code = ::boost::get_error_info<curlcode_info>(*this)) {\n\t\t\t\tstd::string what_ = flusspferd::exception::what();\n\t\t\t\twhat_ += \": \";\n\t\t\t\twhat_ += curl_easy_strerror(*code);\n\t\t\t\treturn what_.c_str();\n\t\t\t}\n\t\t\telse {\n\t\t\t\treturn flusspferd::exception::what();\n\t\t\t}\n\t\t}\n\t};\n\n void global_init(long flags) {\n CURLcode ret = curl_global_init(flags);\n\t\tif(ret != 0) {\n\t\t\tthrow flusspferd::exception(std::string(\"curl_global_init: \")\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t+ curl_easy_strerror(ret));\n\t\t}\n }\n\n\tclass Easy;\n\n\tnamespace {\n\t\tstruct handle_option {\n\t\t\tvirtual ~handle_option() =0;\n\t\t\tvirtual value default_value() const { return value(); }\n\t\t\tvirtual property_attributes default_attributes() const {\n\t\t\t\treturn property_attributes();\n\t\t\t}\n\t\t\tvirtual void handle(Easy &e, value const &v) const =0;\n\t\t};\n\t\thandle_option::~handle_option() { }\n\n\t\ttypedef boost::ptr_unordered_map<std::string, handle_option> options_map_t;\n\t\toptions_map_t const &get_options();\n\t}\n\n\tFLUSSPFERD_CLASS_DESCRIPTION\n\t(\n\t EasyOpt,\n\t (constructor_name, \"EasyOpt\")\n\t (full_name, \"cURL.Easy.EasyOpt\")\n\t (constructible, false)\n\t )\n\t{\n\t\tEasy &parent;\n\tpublic:\n\t\tEasyOpt(flusspferd::object const &self, Easy &parent)\n\t\t\t: base_type(self), parent(parent)\n\t\t{\t}\n\n\t\tstatic EasyOpt &create(Easy &p) {\n\t\t\treturn flusspferd::create_native_object<EasyOpt>(object(), boost::ref(p));\n\t\t}\n\tprotected:\n\t\tbool property_resolve(value const &id, unsigned access);\n\t};\n\n FLUSSPFERD_CLASS_DESCRIPTION\n (\n Easy,\n (constructor_name, \"Easy\")\n (full_name, \"cURL.Easy\")\n (methods,\n (\"cleanup\", bind, cleanup)\n (\"perform\", bind, perform)\n (\"reset\", bind, reset)\n (\"escape\", bind, escape)\n (\"unescape\", bind, unescape)\n (\"valid\", bind, valid))\n\t (properties,\n\t\t(\"options\", getter, get_opt))\n )\n {\n CURL *handle;\n\t\tEasyOpt &opt;\n\n\t\tstatic size_t writefunction(void *ptr, size_t size, size_t nmemb, void *stream) {\n\t\t\tassert(stream);\n\t\t\tEasy &self = *reinterpret_cast<Easy*>(stream);\n\t\t\tbyte_array data(object(),\n\t\t\t\t\t\t\t\t\t\t\treinterpret_cast<byte_array::element_type*>(ptr),\n\t\t\t\t\t\t\t\t\t\t\tsize*nmemb);\n\t\t\targuments arg;\n\t\t\targ.push_back(value(data));\n\t\t\targ.push_back(value(size));\n\t\t\tobject callback = self.opt.get_property(\"writeFunction\").to_object();\n\t\t\tvalue v = callback.call(arg);\n\t\t\treturn v.to_number();\n\t\t}\n\n\tprotected:\n\t\tvoid trace(flusspferd::tracer &trc) {\n\t\t\ttrc(\"options\", opt);\n\t\t}\n\n public:\n CURL *data() { return handle; }\n bool valid() { return handle; }\n CURL *get() {\n if(!handle) {\n throw flusspferd::exception(\"CURL handle not valid!\");\n }\n return handle;\n }\n\t\tEasyOpt &get_opt() {\n\t\t\treturn opt;\n\t\t}\n\n Easy(flusspferd::object const &self, flusspferd::call_context&)\n : base_type(self), handle(curl_easy_init()), opt(EasyOpt::create(*this))\n {\n if(!handle) {\n throw flusspferd::exception(\"curl_easy_init\");\n }\n }\n\n Easy(flusspferd::object const &self, CURL *hnd)\n : base_type(self), handle(hnd), opt(EasyOpt::create(*this))\n {\n assert(handle);\n }\n\n void cleanup() {\n if(handle) {\n curl_easy_cleanup(handle);\n handle = 0x0;\n }\n }\n ~Easy() { cleanup(); }\n\n\t\t\/**\n\t\t * Applies all options set in EasyOpt.\n\t\t * This is called automatically.\n\t\t * Shouldn't be necessary to call it manually!\n\t\t *\n\t\t * Not exported.\n\t\t *\n\t\t * Maybe this should be called by unwrap and be private ...\n\t\t *\/\n\t\tvoid apply_options() {\n\t\t\tstd::cout << \"apply_options()\\n\";\n\t\t\toptions_map_t const &options = get_options();\n\t\t\tfor(property_iterator i = opt.begin();\n\t\t\t\t\ti != opt.end();\n\t\t\t\t\t++i)\n\t\t\t{\n\t\t\t\tstd::cout << \"\\t\" << i->to_std_string() << \"\\n\";\n\t\t\t\toptions_map_t::const_iterator option = options.find(i->to_std_string());\n\t\t\t\tif(option != options.end()) {\n\t\t\t\t\toption->second->handle(*this, opt.get_property(*i));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n void perform() {\n\t\t\tapply_options();\n\t\t\tCURLcode res = curl_easy_perform(get());\n\t\t\tif(res != 0) {\n\t\t\t\tthrow flusspferd::exception(std::string(\"curl_easy_perform: \") +\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tcurl_easy_strerror(res));\n\t\t\t}\n }\n\n void reset() {\n curl_easy_reset(get());\n }\n\n std::string unescape(char const *input) {\n int len;\n char *const uesc = curl_easy_unescape(get(), input, 0, &len);\n if(!uesc) {\n throw flusspferd::exception(\"curl_easy_unescape\");\n }\n std::string ret(uesc, len);\n curl_free(uesc);\n return ret;\n }\n\n std::string escape(char const *input) {\n char *const esc = curl_easy_escape(get(), input, 0);\n if(!esc) {\n throw flusspferd::exception(\"curl_easy_escape\");\n }\n std::string ret(esc);\n curl_free(esc);\n return ret;\n }\n\n static Easy &create(CURL *hnd) {\n return flusspferd::create_native_object<Easy>(object(), hnd);\n }\n\n\t\t\/\/private:\n\t\ttemplate<typename T>\n\t\tvoid do_setopt(CURLoption what, T data) {\n\t\t\tstd::cout << \"setopt (\" << (unsigned)what << ' ' << data << '\\n'; \/\/ DEBUG\n\t\t\tCURLcode res = curl_easy_setopt(get(), what, data);\n\t\t\tif(res != 0) {\n\t\t\t\tthrow flusspferd::exception(std::string(\"curl_easy_setopt: \") +\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tcurl_easy_strerror(res));\n\t\t\t}\n\t\t}\n\n\t\tvoid do_setopt_function(CURLoption what, bool default_) {\n\t\t\tif(default_) {\n\t\t\t\tdo_setopt(what, 0x0);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tswitch(what) {\n\t\t\t\tcase CURLOPT_WRITEFUNCTION:\n\t\t\t\t\tdo_setopt(CURLOPT_WRITEFUNCTION, &writefunction);\n\t\t\t\t\tdo_setopt(CURLOPT_WRITEDATA, this);\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tthrow flusspferd::exception(\"unkown function option\");\n\t\t\t\t};\n\t\t\t}\n\t\t}\n };\n Easy &wrap(CURL *hnd) {\n return Easy::create(hnd);\n }\n CURL *unwrap(Easy &c) {\n return c.data();\n }\n\n\tnamespace {\n\t\tstruct integer_option : handle_option {\n\t\t\tinteger_option(CURLoption what) : what(what) { }\n\t\t\tvalue default_value() const { return value(0); }\n\t\t\tvoid handle(Easy &e, value const &v) const {\n\t\t\t\te.do_setopt(what, v.to_number());\n\t\t\t}\n \tprivate:\n\t\t\tCURLoption what;\n\t\t};\n\n\t\tstruct string_option : handle_option {\n\t\t\tstring_option(CURLoption what) : what(what) { }\n\t\t\tvalue default_value() const { return value(\"\"); }\n\t\t\tvoid handle(Easy &e, value const &v) const {\n\t\t\t\te.do_setopt(what, v.to_std_string().c_str()); \/\/ TODO this won't work! string needs to be stored.\n\t\t\t}\n\t\tprivate:\n\t\t\tCURLoption what;\n\t\t};\n\n\t\tstruct function_option : handle_option {\n\t\t\tfunction_option(CURLoption what) : what(what) { }\n\t\t\tvoid handle(Easy &e, value const &v) const {\n\t\t\t\te.do_setopt_function(what, v.is_undefined_or_null());\n\t\t\t}\n\t\tprivate:\n\t\t\tCURLoption what;\n\t\t};\n\n\t\toptions_map_t const &get_options() {\n\t\t\tstatic options_map_t map;\n\t\t\tif(map.empty()) {\n\t\t\t\tboost::assign::ptr_map_insert<integer_option>(map)\n\t\t\t\t\t(\"verbose\", CURLOPT_VERBOSE)\n\t\t\t\t\t(\"header\", CURLOPT_HEADER)\n\t\t\t\t\t(\"noProgress\", CURLOPT_NOPROGRESS)\n\t\t\t\t\t(\"noSignal\", CURLOPT_NOSIGNAL);\n\t\t\t\tboost::assign::ptr_map_insert<function_option>(map)\n\t\t\t\t\t(\"writeFunction\", CURLOPT_WRITEFUNCTION);\n\t\t\t\tboost::assign::ptr_map_insert<string_option>(map)\n\t\t\t\t\t(\"url\", CURLOPT_URL);\n\t\t\t}\n\t\t\treturn map;\n\t\t}\n\t}\n\n\tbool EasyOpt::property_resolve(value const &id, unsigned) {\n\t\tstd::string const name = id.to_std_string();\n\t\toptions_map_t::const_iterator const i = get_options().find(name);\n\t\tif(i != get_options().end()) {\n\t\t\tdefine_property(id.get_string(), i->second->default_value(),\n\t\t\t\t\t\t\t\t\t\t\ti->second->default_attributes());\n\t\t\treturn true;\n\t\t}\n\t\telse {\n\t\t\treturn false;\n\t\t}\n\t}\n\n FLUSSPFERD_LOADER_SIMPLE(cURL) {\n local_root_scope scope;\n\n cURL.define_property(\"GLOBAL_ALL\", value(CURL_GLOBAL_ALL),\n read_only_property | permanent_property);\n cURL.define_property(\"GLOBAL_SSL\", value(CURL_GLOBAL_SSL),\n read_only_property | permanent_property);\n cURL.define_property(\"GLOBAL_WIN32\", value(CURL_GLOBAL_WIN32),\n read_only_property | permanent_property);\n cURL.define_property(\"GLOBAL_NOTHING\", value(CURL_GLOBAL_NOTHING),\n read_only_property | permanent_property);\n create_native_function(cURL, \"globalInit\", &global_init);\n cURL.define_property(\"version\", value(curl_version()),\n read_only_property | permanent_property);\n\t\tload_class<EasyOpt>(cURL);\n load_class<Easy>(cURL);\n }\n}\n<commit_msg>curl: continued implementing options. New internal API. Simple example working<commit_after>\/\/ -*- mode:c++;coding:utf-8; -*- vim:ts=2:sw=2:expandtab:autoindent:filetype=cpp:enc=utf-8:\n\/*\nThe MIT License\n\nCopyright (c) 2008, 2009 Flusspferd contributors (see \"CONTRIBUTORS\" or\n http:\/\/flusspferd.org\/contributors.txt)\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n*\/\n\n#include \"flusspferd\/create.hpp\"\n#include \"flusspferd\/binary.hpp\"\n#include \"flusspferd\/tracer.hpp\"\n#include \"flusspferd\/modules.hpp\"\n#include \"flusspferd\/security.hpp\"\n#include \"flusspferd\/arguments.hpp\"\n#include \"flusspferd\/class_description.hpp\"\n#include \"flusspferd\/property_iterator.hpp\"\n\n#include <sstream>\n#include <curl\/curl.h>\n\n#include <boost\/ptr_container\/ptr_unordered_map.hpp>\n#include <boost\/exception\/get_error_info.hpp>\n#include <boost\/assign\/ptr_map_inserter.hpp>\n#include <boost\/any.hpp>\n\n\/\/#include <iostream> \/\/DEBUG\n\nusing namespace flusspferd;\n\nnamespace {\n\ttypedef boost::error_info<struct tag_curlcode, CURLcode> curlcode_info;\n\n\tstruct exception\n\t\t: flusspferd::exception\n\t{\n\t\texception(std::string const &what)\n\t\t\t: std::runtime_error(what), flusspferd::exception(what)\n\t\t{ }\n\n\t\tchar const *what() const throw() {\n\t\t\tif(CURLcode const *code = ::boost::get_error_info<curlcode_info>(*this)) {\n\t\t\t\tstd::string what_ = flusspferd::exception::what();\n\t\t\t\twhat_ += \": \";\n\t\t\t\twhat_ += curl_easy_strerror(*code);\n\t\t\t\treturn what_.c_str();\n\t\t\t}\n\t\t\telse {\n\t\t\t\treturn flusspferd::exception::what();\n\t\t\t}\n\t\t}\n\t};\n\n void global_init(long flags) {\n CURLcode ret = curl_global_init(flags);\n\t\tif(ret != 0) {\n\t\t\tthrow flusspferd::exception(std::string(\"curl_global_init: \")\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t+ curl_easy_strerror(ret));\n\t\t}\n }\n\n\tclass Easy;\n\n\tnamespace {\n\t\tstruct handle_option {\n\t\t\tvirtual ~handle_option() =0;\n\t\t\tvirtual function getter() const =0;\n\t\t\tvirtual function setter() const =0;\n\t\t\tvirtual boost::any data() const =0;\n\t\t\tvirtual CURLoption what() const =0;\n\t\t};\n\t\thandle_option::~handle_option() { }\n\n\t\ttypedef boost::ptr_unordered_map<std::string, handle_option> options_map_t;\n\t\toptions_map_t const &get_options();\n\t}\n\n\tFLUSSPFERD_CLASS_DESCRIPTION\n\t(\n\t EasyOpt,\n\t (constructor_name, \"EasyOpt\")\n\t (full_name, \"cURL.Easy.EasyOpt\")\n\t (constructible, false)\n\t )\n\t{\n\tpublic: \/\/ TODO\n\t\ttypedef boost::unordered_map<CURLoption, boost::any> data_map_t;\n\t\tdata_map_t data;\n\t\tEasy &parent;\n\tpublic:\n\t\tEasyOpt(flusspferd::object const &self, Easy &parent)\n\t\t\t: base_type(self), parent(parent)\n\t\t{\t}\n\n\t\tstatic EasyOpt &create(Easy &p) {\n\t\t\treturn flusspferd::create_native_object<EasyOpt>(object(), boost::ref(p));\n\t\t}\n\tprotected:\n\t\tbool property_resolve(value const &id, unsigned access);\n\t};\n\n FLUSSPFERD_CLASS_DESCRIPTION\n (\n Easy,\n (constructor_name, \"Easy\")\n (full_name, \"cURL.Easy\")\n (methods,\n (\"cleanup\", bind, cleanup)\n (\"perform\", bind, perform)\n (\"reset\", bind, reset)\n (\"escape\", bind, escape)\n (\"unescape\", bind, unescape)\n (\"valid\", bind, valid))\n\t (properties,\n\t\t(\"options\", getter, get_opt))\n )\n {\n CURL *handle;\n\t\tEasyOpt &opt;\n\n\tpublic: \/\/ TODO\n\t\tobject writefunction_callback;\n\t\tstatic size_t writefunction(void *ptr, size_t size, size_t nmemb, void *stream) {\n\t\t\t\/\/std::cout << \"writefunction\" << std::endl;\n\t\t\tassert(stream);\n\t\t\tEasy &self = *reinterpret_cast<Easy*>(stream);\n\t\t\tif(self.writefunction_callback.is_null()) {\n\t\t\t\t\/\/std::cout << \"writefunction*1\" << std::endl;\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\telse {\n\t\t\t\t\/\/std::cout << \"writefunction^2\" << std::endl;\n\t\t\t\tbyte_array data(object(),\n\t\t\t\t\t\t\t\t\t\t\t\treinterpret_cast<byte_array::element_type*>(ptr),\n\t\t\t\t\t\t\t\t\t\t\t\tsize*nmemb);\n\t\t\t\targuments arg;\n\t\t\t\targ.push_back(value(data));\n\t\t\t\targ.push_back(value(size));\n\t\t\t\t\/\/std::cout << \"writefunction^3\" << std::endl;\n\t\t\t\tvalue v = self.writefunction_callback.call(arg);\n\t\t\t\t\/\/std::cout << \"writefunction^4\" << std::endl;\n\t\t\t\treturn v.to_number();\n\t\t\t}\n\t\t}\n\n\tprotected:\n\t\tvoid trace(flusspferd::tracer &trc) {\n\t\t\ttrc(\"options\", opt);\n\t\t}\n\n public:\n CURL *data() { return handle; }\n bool valid() { return handle; }\n CURL *get() {\n if(!handle) {\n throw flusspferd::exception(\"CURL handle not valid!\");\n }\n return handle;\n }\n\t\tEasyOpt &get_opt() {\n\t\t\treturn opt;\n\t\t}\n\n Easy(flusspferd::object const &self, flusspferd::call_context&)\n : base_type(self), handle(curl_easy_init()), opt(EasyOpt::create(*this))\n {\n if(!handle) {\n throw flusspferd::exception(\"curl_easy_init\");\n }\n }\n\n Easy(flusspferd::object const &self, CURL *hnd)\n : base_type(self), handle(hnd), opt(EasyOpt::create(*this))\n {\n assert(handle);\n }\n\n void cleanup() {\n if(handle) {\n curl_easy_cleanup(handle);\n handle = 0x0;\n }\n }\n ~Easy() { cleanup(); }\n\n void perform() {\n\t\t\tCURLcode res = curl_easy_perform(get());\n\t\t\tif(res != 0) {\n\t\t\t\tthrow flusspferd::exception(std::string(\"curl_easy_perform: \") +\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tcurl_easy_strerror(res));\n\t\t\t}\n }\n\n void reset() {\n curl_easy_reset(get());\n }\n\n std::string unescape(char const *input) {\n int len;\n char *const uesc = curl_easy_unescape(get(), input, 0, &len);\n if(!uesc) {\n throw flusspferd::exception(\"curl_easy_unescape\");\n }\n std::string ret(uesc, len);\n curl_free(uesc);\n return ret;\n }\n\n std::string escape(char const *input) {\n char *const esc = curl_easy_escape(get(), input, 0);\n if(!esc) {\n throw flusspferd::exception(\"curl_easy_escape\");\n }\n std::string ret(esc);\n curl_free(esc);\n return ret;\n }\n\n static Easy &create(CURL *hnd) {\n return flusspferd::create_native_object<Easy>(object(), hnd);\n }\n\n\t\t\/\/private:\n\t\ttemplate<typename T>\n\t\tvoid do_setopt(CURLoption what, T data) {\n\t\t\tCURLcode res = curl_easy_setopt(get(), what, data);\n\t\t\tif(res != 0) {\n\t\t\t\tthrow flusspferd::exception(std::string(\"curl_easy_setopt: \") +\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tcurl_easy_strerror(res));\n\t\t\t}\n\t\t}\n };\n Easy &wrap(CURL *hnd) {\n return Easy::create(hnd);\n }\n CURL *unwrap(Easy &c) {\n return c.data();\n }\n\n\tnamespace {\n\t\ttemplate<CURLoption What>\n\t\tstruct integer_option : handle_option {\n\t\t\tfunction getter() const {\n\t\t\t\treturn create_native_method(object(), \"$get_\", &get);\n\t\t\t}\n\t\t\tfunction setter() const {\n\t\t\t\treturn create_native_method(object(), \"$set_\", &set);\n\t\t\t}\n\t\t\tboost::any data() const { return 0l; }\n\t\t\tCURLoption what() const { return What; }\n \tprivate:\n\t\t\tstatic long get(EasyOpt *o) {\n\t\t\t\tassert(o);\n\t\t\t\treturn boost::any_cast<long>(o->data[What]);\n\t\t\t}\n\t\t\tstatic void set(EasyOpt *o, long opt) {\n\t\t\t\tassert(o);\n\t\t\t\to->data[What] = opt;\n\t\t\t\to->parent.do_setopt(What, opt);\n\t\t\t}\n\t\t};\n\n\t\ttemplate<CURLoption What>\n\t\tstruct string_option : handle_option {\n\t\t\tfunction getter() const {\n\t\t\t\treturn create_native_method(object(), \"$get_\", &get);\n\t\t\t}\n\t\t\tfunction setter() const {\n\t\t\t\treturn create_native_method(object(), \"$set_\", &set);\n\t\t\t}\n\t\t\tboost::any data() const { return std::string(); }\n\t\t\tCURLoption what() const { return What; }\n\t\tprivate:\n\t\t\tstatic std::string get(EasyOpt *o) {\n\t\t\t\tassert(o);\n\t\t\t\treturn boost::any_cast<std::string>(o->data[What]);\n\t\t\t}\n\t\t\tstatic void set(EasyOpt *o, std::string const &val) {\n\t\t\t\tassert(o);\n\t\t\t\to->data[What] = val;\n\t\t\t\to->parent.do_setopt(What, boost::any_cast<std::string&>(o->data[What]).c_str());\n\t\t\t}\n\t\t};\n\n\t\tstruct write_function_option : handle_option {\n\t\t\tstatic CURLoption const What = CURLOPT_WRITEFUNCTION;\n\t\t\tfunction getter() const {\n\t\t\t\treturn create_native_method(object(), \"$get_writeFunction\", &get);\n\t\t\t}\n\t\t\tfunction setter() const {\n\t\t\t\treturn create_native_method(object(), \"$set_writeFunction\", &set);\n\t\t\t}\n\t\t\tboost::any data() const { return function(); }\n\t\t\tCURLoption what() const { return What; }\n\t\tprivate:\n\t\t\tstatic object get(EasyOpt *o) {\n\t\t\t\tassert(o);\n\t\t\t\treturn o->parent.writefunction_callback;\n\t\t\t}\n\t\t\tstatic void set(EasyOpt *o, object val) {\n\t\t\t\tassert(o);\n\t\t\t\to->parent.writefunction_callback = val;\n\t\t\t\tif(val.is_null()) {\n\t\t\t\t\to->parent.do_setopt(CURLOPT_WRITEFUNCTION, 0x0);\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\to->parent.do_setopt(CURLOPT_WRITEFUNCTION, &Easy::writefunction);\n\t\t\t\t\to->parent.do_setopt(CURLOPT_WRITEDATA, &o->parent);\n\t\t\t\t}\n\t\t\t}\n\t\t};\n\n\t\toptions_map_t const &get_options() {\n\t\t\tstatic options_map_t map;\n\t\t\tif(map.empty()) {\n\t\t\t\tusing namespace boost::assign;\n\t\t\t\tptr_map_insert< integer_option<CURLOPT_VERBOSE> >(map)\n\t\t\t\t\t(\"verbose\");\n\t\t\t\tptr_map_insert< integer_option<CURLOPT_HEADER> >(map)\n\t\t\t\t\t(\"header\");\n\t\t\t\tptr_map_insert< integer_option<CURLOPT_NOPROGRESS> >(map)\n\t\t\t\t\t(\"noProgress\");\n\t\t\t\tptr_map_insert< integer_option<CURLOPT_NOSIGNAL> >(map)\n\t\t\t\t\t(\"noSignal\");\n\t\t\t\tptr_map_insert< write_function_option >(map)\n\t\t\t\t\t(\"writeFunction\");\n\t\t\t\tptr_map_insert< string_option<CURLOPT_URL> >(map)(\"url\");\n\t\t\t}\n\t\t\treturn map;\n\t\t}\n\t}\n\n\tbool EasyOpt::property_resolve(value const &id, unsigned) {\n\t\tstd::string const name = id.to_std_string();\n\t\toptions_map_t::const_iterator const i = get_options().find(name);\n\t\tif(i != get_options().end()) {\n\t\t\tproperty_attributes attr(no_property_flag,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t i->second->getter(),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t i->second->setter());\n\t\t\tdefine_property(id.get_string(), value(), attr);\n\t\t\tdata[i->second->what()] = i->second->data();\n\t\t\treturn true;\n\t\t}\n\t\telse {\n\t\t\treturn false;\n\t\t}\n\t}\n\n FLUSSPFERD_LOADER_SIMPLE(cURL) {\n local_root_scope scope;\n\n cURL.define_property(\"GLOBAL_ALL\", value(CURL_GLOBAL_ALL),\n read_only_property | permanent_property);\n cURL.define_property(\"GLOBAL_SSL\", value(CURL_GLOBAL_SSL),\n read_only_property | permanent_property);\n cURL.define_property(\"GLOBAL_WIN32\", value(CURL_GLOBAL_WIN32),\n read_only_property | permanent_property);\n cURL.define_property(\"GLOBAL_NOTHING\", value(CURL_GLOBAL_NOTHING),\n read_only_property | permanent_property);\n create_native_function(cURL, \"globalInit\", &global_init);\n cURL.define_property(\"version\", value(curl_version()),\n read_only_property | permanent_property);\n\t\tload_class<EasyOpt>(cURL);\n load_class<Easy>(cURL);\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ -*- mode:c++;coding:utf-8; -*- vim:ts=2:sw=2:expandtab:autoindent:filetype=cpp:enc=utf-8:\n\/*\nThe MIT License\n\nCopyright (c) 2008, 2009 Flusspferd contributors (see \"CONTRIBUTORS\" or\n http:\/\/flusspferd.org\/contributors.txt)\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n*\/\n\n#include \"flusspferd\/create.hpp\"\n#include \"flusspferd\/binary.hpp\"\n#include \"flusspferd\/tracer.hpp\"\n#include \"flusspferd\/modules.hpp\"\n#include \"flusspferd\/security.hpp\"\n#include \"flusspferd\/arguments.hpp\"\n#include \"flusspferd\/class_description.hpp\"\n\n#include <sstream>\n#include <curl\/curl.h>\n\n#include <boost\/exception\/get_error_info.hpp>\n\nusing namespace flusspferd;\n\nnamespace {\n\ttypedef boost::error_info<struct tag_curlcode, CURLcode> curlcode_info;\n\n\tstruct exception\n\t\t: flusspferd::exception\n\t{\n\t\texception(std::string const &what)\n\t\t\t: std::runtime_error(what), flusspferd::exception(what)\n\t\t{ }\n\n\t\tchar const *what() const throw() {\n\t\t\tif(CURLcode const *code = ::boost::get_error_info<curlcode_info>(*this)) {\n\t\t\t\tstd::string what_ = flusspferd::exception::what();\n\t\t\t\twhat_ += \": \";\n\t\t\t\twhat_ += curl_easy_strerror(*code);\n\t\t\t\treturn what_.c_str();\n\t\t\t}\n\t\t\telse {\n\t\t\t\treturn flusspferd::exception::what();\n\t\t\t}\n\t\t}\n\t};\n\n void global_init(long flags) {\n CURLcode ret = curl_global_init(flags);\n\t\tif(ret != 0) {\n\t\t\tthrow flusspferd::exception(std::string(\"curl_global_init: \") + curl_easy_strerror(ret));\n\t\t}\n }\n\n\tclass Easy;\n\n\tFLUSSPFERD_CLASS_DESCRIPTION\n\t(\n\t EasyOpt,\n\t (constructor_name, \"EasyOpt\")\n\t (full_name, \"cURL.Easy.EasyOpt\")\n\t (constructible, false)\n\t )\n\t{\n\t\tEasy &parent;\n\tpublic:\n\t\tEasyOpt(flusspferd::object const &self, Easy &parent) : base_type(self), parent(parent) { }\n\n\t\t\/\/ workarround\n\t\tEasyOpt(flusspferd::object const &self, Easy const &parent)\n\t\t\t: base_type(self), parent(const_cast<Easy&>(parent))\n\t\t{ }\n\n\t\tstatic EasyOpt &create(Easy &p) {\n\t\t\treturn flusspferd::create_native_object<EasyOpt>(object(), p);\n\t\t}\n\tprotected:\n\t\tbool property_resolve(value const &id, unsigned access);\n\t};\n\n FLUSSPFERD_CLASS_DESCRIPTION\n (\n Easy,\n (constructor_name, \"Easy\")\n (full_name, \"cURL.Easy\")\n (methods,\n (\"cleanup\", bind, cleanup)\n (\"perform\", bind, perform)\n (\"reset\", bind, reset)\n (\"escape\", bind, escape)\n (\"unescape\", bind, unescape)\n (\"setopt\", bind, setopt)\n (\"valid\", bind, valid))\n\t (properties,\n\t\t(\"options\", getter, get_opt))\n )\n {\n CURL *handle;\n\t\tEasyOpt &opt;\n\n\t\tobject writecallback;\n\t\tstatic size_t writefunction(void *ptr, size_t size, size_t nmemb, void *stream) {\n\t\t\tassert(stream);\n\t\t\tEasy &self = *reinterpret_cast<Easy*>(stream);\n\t\t\tbyte_array data(object(),\n\t\t\t\t\t\t\t\t\t\t\treinterpret_cast<byte_array::element_type*>(ptr),\n\t\t\t\t\t\t\t\t\t\t\tsize*nmemb);\n\t\t\targuments arg;\n\t\t\targ.push_back(value(data));\n\t\t\targ.push_back(value(size));\n\t\t\tvalue v = self.writecallback.call(arg);\n\t\t\treturn v.to_number();\n\t\t}\n\tprotected:\n\t\tvoid trace(flusspferd::tracer &trc) {\n\t\t\ttrc(\"writecallback\", writecallback);\n\t\t}\n\n public:\n CURL *data() { return handle; }\n bool valid() { return handle; }\n CURL *get() {\n if(!handle) {\n throw flusspferd::exception(\"CURL handle not valid!\");\n }\n return handle;\n }\n\t\tEasyOpt &get_opt() { return opt; }\n\n Easy(flusspferd::object const &self, flusspferd::call_context&)\n : base_type(self), handle(curl_easy_init()), opt(EasyOpt::create(*this))\n {\n if(!handle) {\n throw flusspferd::exception(\"curl_easy_init\");\n }\n }\n\n Easy(flusspferd::object const &self, CURL *hnd)\n : base_type(self), handle(hnd), opt(EasyOpt::create(*this))\n {\n assert(handle);\n }\n\n void cleanup() {\n if(handle) {\n curl_easy_cleanup(handle);\n handle = 0x0;\n }\n }\n ~Easy() { cleanup(); }\n\n void perform() {\n\t\t\tCURLcode res = curl_easy_perform(get());\n\t\t\tif(res != 0) {\n\t\t\t\tthrow flusspferd::exception(std::string(\"curl_easy_setopt: \") +\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tcurl_easy_strerror(res));\n\t\t\t}\n }\n\n void reset() {\n curl_easy_reset(get());\n }\n\n std::string unescape(char const *input) {\n int len;\n char *const uesc = curl_easy_unescape(get(), input, 0, &len);\n if(!uesc) {\n throw flusspferd::exception(\"curl_easy_escape\");\n }\n std::string ret(uesc, len);\n curl_free(uesc);\n return ret;\n }\n\n std::string escape(char const *input) {\n char *const esc = curl_easy_escape(get(), input, 0);\n if(!esc) {\n throw flusspferd::exception(\"curl_easy_escape\");\n }\n std::string ret(esc);\n curl_free(esc);\n return ret;\n }\n\n#define OPT_NUMBER(What) \\\n case What : \\\n if(x.arg.size() != 2) { \\\n std::stringstream ss; \\\n ss << \"curl_easy_setopt: Expected two arguments. Got (\" << x.arg.size() << ')'; \\\n throw flusspferd::exception(ss.str()); \\\n } \\\n do_setopt(What, x.arg[1].to_number());\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n break\n\n#define OPT_FUNCTION(What, Data, Callback, Func)\t\t\t\t\t\t\t\t\t\t\t\t\\\n\t\tcase What : {\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\t\t\tif(x.arg.size() != 2) {\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\t\t\t\tthrow flusspferd::exception(\"curl_easy_setopt: Expected two arguments\"); \\\n\t\t\t}\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\t\t\tif(!x.arg[1].is_object()) {\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\t\t\t\tthrow flusspferd::exception(\"curl_easy_setopt: Expected a function as second parameter\");\t\\\n\t\t\t}\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\t\t\tobject callback = x.arg[1].get_object();\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\t\t\tif(callback == default_function) {\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\t\t\t\tdo_setopt(What, 0x0);\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\t\t\t\tCallback = object();\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\t\t\t}\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\t\t\telse {\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\t\t\t\tdo_setopt(Data, this);\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\t\t\t\tdo_setopt(What, Func);\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\t\t\t\tCallback = callback;\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\t\t\t}\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\t\t}\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\t\tbreak\n\n#define OPT_DATAFUNCTION(What, Prefix)\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\t\tOPT_FUNCTION( What ## FUNCTION, What ## DATA, Prefix ## callback, Prefix ## function )\n\n\tprivate:\n\t\ttemplate<typename T>\n\t\tvoid do_setopt(CURLoption what, T data) {\n\t\t CURLcode res = curl_easy_setopt(get(), what, data);\n\t\t\tif(res != 0) {\n\t\t\t\tthrow flusspferd::exception(std::string(\"curl_easy_setopt: \") +\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tcurl_easy_strerror(res));\n\t\t\t}\n\t\t}\n\tpublic:\n\n void setopt(flusspferd::call_context &x) {\n int what = x.arg.front().to_number();\n switch(what) {\n\t\t\t\t\/\/ Behaviour Options\n\t\t\t\tOPT_NUMBER(CURLOPT_VERBOSE);\n OPT_NUMBER(CURLOPT_HEADER);\n\t\t\t\tOPT_NUMBER(CURLOPT_NOPROGRESS);\n\t\t\t\tOPT_NUMBER(CURLOPT_NOSIGNAL);\n\n\t\t\t\t\/\/ Callback Options\n\t\t\t\tOPT_DATAFUNCTION(CURLOPT_WRITE, write);\n default: {\n std::stringstream ss;\n ss << \"curl_easy_setopt unkown or unsupported option (\" << what << ')';\n throw flusspferd::exception(ss.str());\n }\n };\n }\n\n#undef OPT_DATAFUNCTION\n#undef OPT_FUNCTION\n#undef OPT_NUMBER\n\n static Easy &create(CURL *hnd) {\n return flusspferd::create_native_object<Easy>(object(), hnd);\n }\n\n\t\tstatic object default_function;\n };\n\n\tobject Easy::default_function;\n\n Easy &wrap(CURL *hnd) {\n return Easy::create(hnd);\n }\n CURL *unwrap(Easy &c) {\n return c.data();\n }\n\n\tbool EasyOpt::property_resolve(value const &id, unsigned) {\n\t\t(void)id;\n\t\treturn false;\n\t}\n\n FLUSSPFERD_LOADER_SIMPLE(cURL) {\n local_root_scope scope;\n\n cURL.define_property(\"GLOBAL_ALL\", value(CURL_GLOBAL_ALL),\n read_only_property | permanent_property);\n cURL.define_property(\"GLOBAL_SSL\", value(CURL_GLOBAL_SSL),\n read_only_property | permanent_property);\n cURL.define_property(\"GLOBAL_WIN32\", value(CURL_GLOBAL_WIN32),\n read_only_property | permanent_property);\n cURL.define_property(\"GLOBAL_NOTHING\", value(CURL_GLOBAL_NOTHING),\n read_only_property | permanent_property);\n create_native_function(cURL, \"globalInit\", &global_init);\n cURL.define_property(\"version\", value(curl_version()),\n read_only_property | permanent_property);\n\t\tload_class<EasyOpt>(cURL);\n load_class<Easy>(cURL);\n\t\t\/\/ Behaviour Options\n\t\tcURL.define_property(\"OPT_VERBOSE\", value((int)CURLOPT_VERBOSE),\n\t\t\t\t\t\t\t\t\t\t\t\t read_only_property | permanent_property);\n cURL.define_property(\"OPT_HEADER\", value((int)CURLOPT_HEADER),\n read_only_property | permanent_property);\n\t\tcURL.define_property(\"OPT_NOPROGRESS\", value((int)CURLOPT_NOPROGRESS),\n\t\t\t\t\t\t\t\t\t\t\t\t read_only_property | permanent_property);\n\t\tcURL.define_property(\"OPT_NOSIGNAL\", value((int)CURLOPT_NOSIGNAL),\n\t\t\t\t\t\t\t\t\t\t\t\t read_only_property | permanent_property);\n\t\t\/\/ Callback Options\n\t\tcURL.define_property(\"OPT_WRITEFUNCTION\", value((int)CURLOPT_WRITEFUNCTION),\n read_only_property | permanent_property);\n\t\t\/*\n\t\tCURLOPT_READFUNCTION\n\t\tCURLOPT_IOCTLFUNCTION\n\t\tCURLOPT_SEEKFUNCTION\n\t\tCURLOPT_SOCKOPTFUNCTION\n\t\tCURLOPT_OPENSOCKETFUNCTION\n\t\t...\n\t\t *\/\n\t\tcURL.define_property(\"defaultFunction\", value(Easy::default_function),\n\t\t\t\t\t\t\t\t\t\t\t\t read_only_property | permanent_property);\n }\n}\n<commit_msg>curl: use boost::ref instead of workarround<commit_after>\/\/ -*- mode:c++;coding:utf-8; -*- vim:ts=2:sw=2:expandtab:autoindent:filetype=cpp:enc=utf-8:\n\/*\nThe MIT License\n\nCopyright (c) 2008, 2009 Flusspferd contributors (see \"CONTRIBUTORS\" or\n http:\/\/flusspferd.org\/contributors.txt)\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n*\/\n\n#include \"flusspferd\/create.hpp\"\n#include \"flusspferd\/binary.hpp\"\n#include \"flusspferd\/tracer.hpp\"\n#include \"flusspferd\/modules.hpp\"\n#include \"flusspferd\/security.hpp\"\n#include \"flusspferd\/arguments.hpp\"\n#include \"flusspferd\/class_description.hpp\"\n\n#include <sstream>\n#include <curl\/curl.h>\n\n#include <boost\/exception\/get_error_info.hpp>\n\nusing namespace flusspferd;\n\nnamespace {\n\ttypedef boost::error_info<struct tag_curlcode, CURLcode> curlcode_info;\n\n\tstruct exception\n\t\t: flusspferd::exception\n\t{\n\t\texception(std::string const &what)\n\t\t\t: std::runtime_error(what), flusspferd::exception(what)\n\t\t{ }\n\n\t\tchar const *what() const throw() {\n\t\t\tif(CURLcode const *code = ::boost::get_error_info<curlcode_info>(*this)) {\n\t\t\t\tstd::string what_ = flusspferd::exception::what();\n\t\t\t\twhat_ += \": \";\n\t\t\t\twhat_ += curl_easy_strerror(*code);\n\t\t\t\treturn what_.c_str();\n\t\t\t}\n\t\t\telse {\n\t\t\t\treturn flusspferd::exception::what();\n\t\t\t}\n\t\t}\n\t};\n\n void global_init(long flags) {\n CURLcode ret = curl_global_init(flags);\n\t\tif(ret != 0) {\n\t\t\tthrow flusspferd::exception(std::string(\"curl_global_init: \") + curl_easy_strerror(ret));\n\t\t}\n }\n\n\tclass Easy;\n\n\tFLUSSPFERD_CLASS_DESCRIPTION\n\t(\n\t EasyOpt,\n\t (constructor_name, \"EasyOpt\")\n\t (full_name, \"cURL.Easy.EasyOpt\")\n\t (constructible, false)\n\t )\n\t{\n\t\tEasy &parent;\n\tpublic:\n\t\tEasyOpt(flusspferd::object const &self, Easy &parent) : base_type(self), parent(parent) { }\n\n\t\tstatic EasyOpt &create(Easy &p) {\n\t\t\treturn flusspferd::create_native_object<EasyOpt>(object(), boost::ref(p));\n\t\t}\n\tprotected:\n\t\tbool property_resolve(value const &id, unsigned access);\n\t};\n\n FLUSSPFERD_CLASS_DESCRIPTION\n (\n Easy,\n (constructor_name, \"Easy\")\n (full_name, \"cURL.Easy\")\n (methods,\n (\"cleanup\", bind, cleanup)\n (\"perform\", bind, perform)\n (\"reset\", bind, reset)\n (\"escape\", bind, escape)\n (\"unescape\", bind, unescape)\n (\"setopt\", bind, setopt)\n (\"valid\", bind, valid))\n\t (properties,\n\t\t(\"options\", getter, get_opt))\n )\n {\n CURL *handle;\n\t\tEasyOpt &opt;\n\n\t\tobject writecallback;\n\t\tstatic size_t writefunction(void *ptr, size_t size, size_t nmemb, void *stream) {\n\t\t\tassert(stream);\n\t\t\tEasy &self = *reinterpret_cast<Easy*>(stream);\n\t\t\tbyte_array data(object(),\n\t\t\t\t\t\t\t\t\t\t\treinterpret_cast<byte_array::element_type*>(ptr),\n\t\t\t\t\t\t\t\t\t\t\tsize*nmemb);\n\t\t\targuments arg;\n\t\t\targ.push_back(value(data));\n\t\t\targ.push_back(value(size));\n\t\t\tvalue v = self.writecallback.call(arg);\n\t\t\treturn v.to_number();\n\t\t}\n\tprotected:\n\t\tvoid trace(flusspferd::tracer &trc) {\n\t\t\ttrc(\"writecallback\", writecallback);\n\t\t}\n\n public:\n CURL *data() { return handle; }\n bool valid() { return handle; }\n CURL *get() {\n if(!handle) {\n throw flusspferd::exception(\"CURL handle not valid!\");\n }\n return handle;\n }\n\t\tEasyOpt &get_opt() { return opt; }\n\n Easy(flusspferd::object const &self, flusspferd::call_context&)\n : base_type(self), handle(curl_easy_init()), opt(EasyOpt::create(*this))\n {\n if(!handle) {\n throw flusspferd::exception(\"curl_easy_init\");\n }\n }\n\n Easy(flusspferd::object const &self, CURL *hnd)\n : base_type(self), handle(hnd), opt(EasyOpt::create(*this))\n {\n assert(handle);\n }\n\n void cleanup() {\n if(handle) {\n curl_easy_cleanup(handle);\n handle = 0x0;\n }\n }\n ~Easy() { cleanup(); }\n\n void perform() {\n\t\t\tCURLcode res = curl_easy_perform(get());\n\t\t\tif(res != 0) {\n\t\t\t\tthrow flusspferd::exception(std::string(\"curl_easy_setopt: \") +\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tcurl_easy_strerror(res));\n\t\t\t}\n }\n\n void reset() {\n curl_easy_reset(get());\n }\n\n std::string unescape(char const *input) {\n int len;\n char *const uesc = curl_easy_unescape(get(), input, 0, &len);\n if(!uesc) {\n throw flusspferd::exception(\"curl_easy_escape\");\n }\n std::string ret(uesc, len);\n curl_free(uesc);\n return ret;\n }\n\n std::string escape(char const *input) {\n char *const esc = curl_easy_escape(get(), input, 0);\n if(!esc) {\n throw flusspferd::exception(\"curl_easy_escape\");\n }\n std::string ret(esc);\n curl_free(esc);\n return ret;\n }\n\n#define OPT_NUMBER(What) \\\n case What : \\\n if(x.arg.size() != 2) { \\\n std::stringstream ss; \\\n ss << \"curl_easy_setopt: Expected two arguments. Got (\" << x.arg.size() << ')'; \\\n throw flusspferd::exception(ss.str()); \\\n } \\\n do_setopt(What, x.arg[1].to_number());\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n break\n\n#define OPT_FUNCTION(What, Data, Callback, Func)\t\t\t\t\t\t\t\t\t\t\t\t\\\n\t\tcase What : {\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\t\t\tif(x.arg.size() != 2) {\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\t\t\t\tthrow flusspferd::exception(\"curl_easy_setopt: Expected two arguments\"); \\\n\t\t\t}\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\t\t\tif(!x.arg[1].is_object()) {\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\t\t\t\tthrow flusspferd::exception(\"curl_easy_setopt: Expected a function as second parameter\");\t\\\n\t\t\t}\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\t\t\tobject callback = x.arg[1].get_object();\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\t\t\tif(callback == default_function) {\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\t\t\t\tdo_setopt(What, 0x0);\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\t\t\t\tCallback = object();\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\t\t\t}\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\t\t\telse {\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\t\t\t\tdo_setopt(Data, this);\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\t\t\t\tdo_setopt(What, Func);\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\t\t\t\tCallback = callback;\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\t\t\t}\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\t\t}\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\t\tbreak\n\n#define OPT_DATAFUNCTION(What, Prefix)\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\t\tOPT_FUNCTION( What ## FUNCTION, What ## DATA, Prefix ## callback, Prefix ## function )\n\n\tprivate:\n\t\ttemplate<typename T>\n\t\tvoid do_setopt(CURLoption what, T data) {\n\t\t CURLcode res = curl_easy_setopt(get(), what, data);\n\t\t\tif(res != 0) {\n\t\t\t\tthrow flusspferd::exception(std::string(\"curl_easy_setopt: \") +\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tcurl_easy_strerror(res));\n\t\t\t}\n\t\t}\n\tpublic:\n\n void setopt(flusspferd::call_context &x) {\n int what = x.arg.front().to_number();\n switch(what) {\n\t\t\t\t\/\/ Behaviour Options\n\t\t\t\tOPT_NUMBER(CURLOPT_VERBOSE);\n OPT_NUMBER(CURLOPT_HEADER);\n\t\t\t\tOPT_NUMBER(CURLOPT_NOPROGRESS);\n\t\t\t\tOPT_NUMBER(CURLOPT_NOSIGNAL);\n\n\t\t\t\t\/\/ Callback Options\n\t\t\t\tOPT_DATAFUNCTION(CURLOPT_WRITE, write);\n default: {\n std::stringstream ss;\n ss << \"curl_easy_setopt unkown or unsupported option (\" << what << ')';\n throw flusspferd::exception(ss.str());\n }\n };\n }\n\n#undef OPT_DATAFUNCTION\n#undef OPT_FUNCTION\n#undef OPT_NUMBER\n\n static Easy &create(CURL *hnd) {\n return flusspferd::create_native_object<Easy>(object(), hnd);\n }\n\n\t\tstatic object default_function;\n };\n\n\tobject Easy::default_function;\n\n Easy &wrap(CURL *hnd) {\n return Easy::create(hnd);\n }\n CURL *unwrap(Easy &c) {\n return c.data();\n }\n\n\tbool EasyOpt::property_resolve(value const &id, unsigned) {\n\t\t(void)id;\n\t\treturn false;\n\t}\n\n FLUSSPFERD_LOADER_SIMPLE(cURL) {\n local_root_scope scope;\n\n cURL.define_property(\"GLOBAL_ALL\", value(CURL_GLOBAL_ALL),\n read_only_property | permanent_property);\n cURL.define_property(\"GLOBAL_SSL\", value(CURL_GLOBAL_SSL),\n read_only_property | permanent_property);\n cURL.define_property(\"GLOBAL_WIN32\", value(CURL_GLOBAL_WIN32),\n read_only_property | permanent_property);\n cURL.define_property(\"GLOBAL_NOTHING\", value(CURL_GLOBAL_NOTHING),\n read_only_property | permanent_property);\n create_native_function(cURL, \"globalInit\", &global_init);\n cURL.define_property(\"version\", value(curl_version()),\n read_only_property | permanent_property);\n\t\tload_class<EasyOpt>(cURL);\n load_class<Easy>(cURL);\n\t\t\/\/ Behaviour Options\n\t\tcURL.define_property(\"OPT_VERBOSE\", value((int)CURLOPT_VERBOSE),\n\t\t\t\t\t\t\t\t\t\t\t\t read_only_property | permanent_property);\n cURL.define_property(\"OPT_HEADER\", value((int)CURLOPT_HEADER),\n read_only_property | permanent_property);\n\t\tcURL.define_property(\"OPT_NOPROGRESS\", value((int)CURLOPT_NOPROGRESS),\n\t\t\t\t\t\t\t\t\t\t\t\t read_only_property | permanent_property);\n\t\tcURL.define_property(\"OPT_NOSIGNAL\", value((int)CURLOPT_NOSIGNAL),\n\t\t\t\t\t\t\t\t\t\t\t\t read_only_property | permanent_property);\n\t\t\/\/ Callback Options\n\t\tcURL.define_property(\"OPT_WRITEFUNCTION\", value((int)CURLOPT_WRITEFUNCTION),\n read_only_property | permanent_property);\n\t\t\/*\n\t\tCURLOPT_READFUNCTION\n\t\tCURLOPT_IOCTLFUNCTION\n\t\tCURLOPT_SEEKFUNCTION\n\t\tCURLOPT_SOCKOPTFUNCTION\n\t\tCURLOPT_OPENSOCKETFUNCTION\n\t\t...\n\t\t *\/\n\t\tcURL.define_property(\"defaultFunction\", value(Easy::default_function),\n\t\t\t\t\t\t\t\t\t\t\t\t read_only_property | permanent_property);\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright © 2017-2018 Dmitriy Khaustov\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/\n\/\/ Author: Dmitriy Khaustov aka xDimon\n\/\/ Contacts: khaustov.dm@gmail.com\n\/\/ File created on: 2017.03.09\n\n\/\/ ConnectionManager.cpp\n\n\n#include <cstring>\n#include \"ConnectionManager.hpp\"\n\n#include \"..\/thread\/ThreadPool.hpp\"\n#include \"..\/utils\/Daemon.hpp\"\n#include \"..\/thread\/RollbackStackAndRestoreContext.hpp\"\n#include \"..\/thread\/TaskManager.hpp\"\n\nConnectionManager::ConnectionManager()\n: _log(\"ConnectionManager\")\n{\n\t_epfd = epoll_create(poolSize);\n\tmemset(_epev, 0, sizeof(_epev));\n}\n\nConnectionManager::~ConnectionManager()\n{\n\tstd::lock_guard<std::recursive_mutex> guard(_mutex);\n\tstd::vector<std::shared_ptr<Connection>> connections;\n\tfor (auto& i : _allConnections)\n\t{\n\t\tconnections.emplace_back(i.second);\n\t}\n\tfor (auto& connection : connections)\n\t{\n\t\tremove(connection);\n\t}\n\tclose(_epfd);\n\t_epfd = -1;\n}\n\n\/\/\/ Зарегистрировать соединение\nvoid ConnectionManager::add(const std::shared_ptr<Connection>& connection)\n{\n\tstd::lock_guard<std::recursive_mutex> guard(getInstance()._mutex);\n\n\tif (getInstance()._allConnections.find(connection.get()) != getInstance()._allConnections.end())\n\t{\n\t\tgetInstance()._log.warn(\"%s already registered in manager\", connection->name().c_str());\n\t\treturn;\n\t}\n\n\tgetInstance()._allConnections.emplace(connection.get(), connection);\n\n\tgetInstance()._log.debug(\"%s registered in manager\", connection->name().c_str());\n\n\tepoll_event ev{};\n\n\tconnection->watch(ev);\n\n\t\/\/ Включаем наблюдение\n\tif (epoll_ctl(getInstance()._epfd, EPOLL_CTL_ADD, connection->fd(), &ev) == -1)\n\t{\n\t\tgetInstance()._log.warn(\"Fail add %s for watching (error: '%s')\", connection->name().c_str(), strerror(errno));\n\t}\n\telse\n\t{\n\t\tgetInstance()._log.trace(\"Add %s for watching\", connection->name().c_str());\n\t}\n}\n\n\/\/\/ Удалить регистрацию соединения\nbool ConnectionManager::remove(const std::shared_ptr<Connection>& connection)\n{\n\tif (!connection)\n\t{\n\t\treturn false;\n\t}\n\n\t\/\/ Удаляем из очереди событий\n\tif (epoll_ctl(getInstance()._epfd, EPOLL_CTL_DEL, connection->fd(), nullptr) == -1)\n\t{\n\t\tgetInstance()._log.warn(\"Fail remove %s from watching (error: '%s')\", connection->name().c_str(), strerror(errno));\n\t}\n\telse\n\t{\n\t\tgetInstance()._log.trace(\"Remove %s from watching\", connection->name().c_str());\n\t}\n\n\tstd::lock_guard<std::recursive_mutex> guard(getInstance()._mutex);\n\tgetInstance()._allConnections.erase(connection.get());\n\tgetInstance()._readyConnections.erase(connection);\n\tgetInstance()._capturedConnections.erase(connection);\n\n\tgetInstance()._log.debug(\"%s unregistered from manager\", connection->name().c_str());\n\n\treturn true;\n}\n\nuint32_t ConnectionManager::rotateEvents(const std::shared_ptr<Connection>& connection)\n{\n\tstd::lock_guard<std::recursive_mutex> guard(getInstance()._mutex);\n\tuint32_t events = connection->rotateEvents();\n\treturn events;\n}\n\nvoid ConnectionManager::watch(const std::shared_ptr<Connection>& connection)\n{\n\t\/\/ Для известных соенинений проверяем состояние захваченности\n\tstd::lock_guard<std::recursive_mutex> guard(getInstance()._mutex);\n\n\t\/\/ Те, что в обработке, не трогаем\n\tif (connection->isCaptured())\n\t{\n\/\/\t\t_log.trace(\"Skip watch for %s because already captured\", connection->name().c_str());\n\t\treturn;\n\t}\n\n\tepoll_event ev{};\n\n\tconnection->watch(ev);\n\n\t\/\/ Включаем наблюдение\n\tif (epoll_ctl(getInstance()._epfd, EPOLL_CTL_MOD, connection->fd(), &ev) == -1)\n\t{\n\t\tgetInstance()._log.warn(\"Fail modify watching on %s (error: '%s')\", connection->name().c_str(), strerror(errno));\n\t}\n\telse\n\t{\n\t\tgetInstance()._log.trace(\"Modify watching on %s\", connection->name().c_str());\n\t}\n}\n\n\/\/\/ Ожидать события на соединениях\nvoid ConnectionManager::wait()\n{\n\t\/\/ Если набор готовых соединений не пустой, то выходим\n\tif (!_readyConnections.empty())\n\t{\n\t\treturn;\n\t}\n\n\t_mutex.unlock();\n\n\t_epool_mutex.lock();\n\n\tint n = 0;\n\n\twhile ([&](){std::lock_guard<std::recursive_mutex> lockGuard(_mutex); return _readyConnections.empty();}())\n\t{\n\t\tif ([&](){std::lock_guard<std::recursive_mutex> lockGuard(_mutex); return _allConnections.empty();}())\n\t\t{\n\t\t\tstd::this_thread::sleep_for(std::chrono::milliseconds(100));\n\t\t\tbreak;\n\t\t}\n\t\tn = epoll_wait(_epfd, _epev, poolSize, 50);\n\t\tif (n < 0)\n\t\t{\n\t\t\tif (errno != EINTR)\n\t\t\t{\n\t\t\t\t_log.warn(\"Error waiting events of connections: fail epoll_wait (%s)\", strerror(errno));\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t\tif (n > 0)\n\t\t{\n\t\t\t_log.trace(\"Catch events on %d connection(s)\", n);\n\t\t\tbreak;\n\t\t}\n\t\tif (Daemon::shutingdown())\n\t\t{\n\t\t\t\/\/ Закрываем оставшееся\n\t\t\t_epool_mutex.unlock();\n\n\t\t\t_mutex.lock();\n\n\t\t\tif (_allConnections.empty())\n\t\t\t{\n\t\t\t\t_log.debug(\"Interrupt waiting\");\n\t\t\t\treturn;\n\t\t\t}\n\n\/\/\t\t\tstd::vector<std::shared_ptr<Connection>> connections;\n\/\/\t\t\tfor (auto& i : _allConnections)\n\/\/\t\t\t{\n\/\/\t\t\t\tconnections.emplace_back(i.second);\n\/\/\t\t\t}\n\/\/\t\t\tfor (auto& connection : connections)\n\/\/\t\t\t{\n\/\/\t\t\t\tremove(connection);\n\/\/\t\t\t}\n\n\t\t\t_mutex.unlock();\n\n\t\t\t_epool_mutex.lock();\n\t\t}\n\t}\n\n\t_mutex.lock();\n\n\t\/\/ Перебираем полученые события\n\tfor (int i = 0; i < n; i++)\n\t{\n\t\t\/\/ Игнорируем незарегистрированные соединения\n\t\tauto it = _allConnections.find(static_cast<const Connection *>(_epev[i].data.ptr));\n\t\tif (it == _allConnections.end())\n\t\t{\n\t\t\t_log.trace(\"Skip catching of unregistered Connection %p\", _epev[i].data.ptr);\n\t\t\tcontinue;\n\t\t}\n\t\tauto connection = it->second;\n\n\t\tuint32_t fdEvent = _epev[i].events;\n\t\tuint32_t events = 0;\n\n\t\tif (fdEvent & (EPOLLIN | EPOLLRDNORM))\n\t\t{\n\t\t\tevents |= static_cast<uint32_t>(ConnectionEvent::READ);\n\t\t}\n\t\tif (fdEvent & (EPOLLOUT | EPOLLWRNORM))\n\t\t{\n\t\t\tevents |= static_cast<uint32_t>(ConnectionEvent::WRITE);\n\t\t}\n\t\tif (fdEvent & EPOLLHUP)\n\t\t{\n\t\t\tevents |= static_cast<uint32_t>(ConnectionEvent::HUP);\n\t\t}\n\t\tif (fdEvent & EPOLLRDHUP)\n\t\t{\n\t\t\tevents |= static_cast<uint32_t>(ConnectionEvent::HALFHUP);\n\t\t}\n\t\tif (fdEvent & EPOLLERR)\n\t\t{\n\t\t\tevents |= static_cast<uint32_t>(ConnectionEvent::ERROR);\n\t\t}\n\n\t\t_log.trace(\"Catch events `%s` (%04x) on %s\", ConnectionEvent::code(events).c_str(), fdEvent, connection->name().c_str());\n\n\t\tconnection->appendEvents(events);\n\n\t\t\/\/ Если не в списке захваченых...\n\t\tif (_capturedConnections.find(connection) == _capturedConnections.end())\n\t\t{\n\t\t\t_log.trace(\"Insert %s into ready connection list and will be processed now (by events)\", connection->name().c_str());\n\n\t\t\t\/\/ ...добавляем в список готовых\n\t\t\t_readyConnections.insert(connection);\n\t\t}\n\t}\n\n\t_epool_mutex.unlock();\n}\n\n\/\/\/ Зарегистрировать таймаут\nvoid ConnectionManager::timeout(const std::shared_ptr<Connection>& connection)\n{\n\tauto& instance = getInstance();\n\n\tstd::lock_guard<std::recursive_mutex> lockGuard(instance._mutex);\n\n\t\/\/ Игнорируем незарегистрированные соединения\n\tauto it = instance._allConnections.find(connection.get());\n\tif (it == instance._allConnections.end())\n\t{\n\t\tinstance._log.trace(\"Skip timeout adding for noregistered Connection %p\", connection.get());\n\t\treturn;\n\t}\n\n\tconnection->appendEvents(static_cast<uint32_t>(ConnectionEvent::TIMEOUT));\n\n\tinstance._log.trace(\"Catch event `T` on %s\", connection->name().c_str());\n\n\t\/\/ Если не в списке захваченых...\n\tif (instance._capturedConnections.find(connection) == instance._capturedConnections.end())\n\t{\n\t\tinstance._log.trace(\"Insert %s into ready connection list and will be processed now (by timeout)\", connection->name().c_str());\n\n\t\t\/\/ ...добавляем в список готовых\n\t\tinstance._readyConnections.insert(connection);\n\t}\n}\n\n\/\/\/ Захватить соединение\nstd::shared_ptr<Connection> ConnectionManager::capture()\n{\n\tstd::lock_guard<std::recursive_mutex> lockGuard(_mutex);\n\n\t\/\/ Если нет готовых...\n\twhile (_readyConnections.empty())\n\t{\n\t\t\/\/ то выходим при остановке сервера\n\t\tif (Daemon::shutingdown() && _allConnections.empty())\n\t\t{\n\t\t\treturn nullptr;\n\t\t}\n\n\t\t_log.trace(\"Not found ready connection\");\n\n\t\t\/\/ а в штатном режиме ожидаем появления готового соединения\n\t\twait();\n\t}\n\n\t_log.trace(\"Found ready connection\");\n\n\tif (_readyConnections.empty())\n\t{\n\t\treturn nullptr;\n\t}\n\n\t\/\/ Берем соединение из набора готовых к обработке\n\tauto it = _readyConnections.begin();\n\n\tauto connection = *it;\n\n\t\/\/ Перемещаем соединение из набора готовых к обработке в набор захваченных\n\t_readyConnections.erase(it);\n\t_capturedConnections.insert(connection);\n\n\t_log.trace(\"Capture %s\", connection->name().c_str());\n\n\tconnection->setCaptured();\n\n\treturn std::move(connection);\n}\n\n\/\/\/ Освободить соединение\nvoid ConnectionManager::release(const std::shared_ptr<Connection>& connection)\n{\n\tstd::lock_guard<std::recursive_mutex> guard(_mutex);\n\n\t_log.trace(\"Release %s\", connection->name().c_str());\n\n\t_capturedConnections.erase(connection);\n\n\tconnection->setReleased();\n\n\tif (!connection->isClosed())\n\t{\n\t\twatch(connection);\n\t}\n}\n\n\/\/\/ Обработка событий\nvoid ConnectionManager::dispatch()\n{\n\tfor (;;)\n\t{\n\t\tstd::shared_ptr<Connection> connection = getInstance().capture();\n\t\tif (!connection)\n\t\t{\n\t\t\tbreak;\n\t\t}\n\n\t\tgetInstance()._log.debug(\"Enqueue %s for '%s' events processing\", connection->name().c_str(), ConnectionEvent::code(connection->events()).c_str());\n\n\t\tTaskManager::enqueue(\n\t\t\t[wp = std::weak_ptr<Connection>(connection)]\n\t\t\t{\n\t\t\t\tauto connection = wp.lock();\n\t\t\t\tif (!connection)\n\t\t\t\t{\n\t\t\t\t\tgetInstance()._log.trace(\"Connection death\");\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tgetInstance()._log.trace(\"Begin processing on %s\", connection->name().c_str());\n\n\t\t\t\tbool status;\n\t\t\t\ttry\n\t\t\t\t{\n\t\t\t\t\tstatus = connection->processing();\n\t\t\t\t}\n\t\t\t\tcatch (const RollbackStackAndRestoreContext& exception)\n\t\t\t\t{\n\t\t\t\t\tgetInstance().release(connection);\n\t\t\t\t\tthrow;\n\t\t\t\t}\n\t\t\t\tcatch (const std::exception& exception)\n\t\t\t\t{\n\t\t\t\t\tstatus = false;\n\t\t\t\t\tgetInstance()._log.warn(\"Uncatched exception at processing on %s: %s\", connection->name().c_str(), exception.what());\n\t\t\t\t}\n\n\t\t\t\tgetInstance().release(connection);\n\n\t\t\t\tgetInstance()._log.trace(\"End processing on %s: %s\", connection->name().c_str(), status ? \"success\" : \"fail\");\n\t\t\t}\n\t\t);\n\t}\n}\n<commit_msg>Set 1sec-TTL for Connection at shutting down<commit_after>\/\/ Copyright © 2017-2018 Dmitriy Khaustov\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/\n\/\/ Author: Dmitriy Khaustov aka xDimon\n\/\/ Contacts: khaustov.dm@gmail.com\n\/\/ File created on: 2017.03.09\n\n\/\/ ConnectionManager.cpp\n\n\n#include <cstring>\n#include \"ConnectionManager.hpp\"\n\n#include \"..\/thread\/ThreadPool.hpp\"\n#include \"..\/utils\/Daemon.hpp\"\n#include \"..\/thread\/RollbackStackAndRestoreContext.hpp\"\n#include \"..\/thread\/TaskManager.hpp\"\n\nConnectionManager::ConnectionManager()\n: _log(\"ConnectionManager\")\n{\n\t_epfd = epoll_create(poolSize);\n\tmemset(_epev, 0, sizeof(_epev));\n}\n\nConnectionManager::~ConnectionManager()\n{\n\tstd::lock_guard<std::recursive_mutex> guard(_mutex);\n\tstd::vector<std::shared_ptr<Connection>> connections;\n\tfor (auto& i : _allConnections)\n\t{\n\t\tconnections.emplace_back(i.second);\n\t}\n\tfor (auto& connection : connections)\n\t{\n\t\tremove(connection);\n\t}\n\tclose(_epfd);\n\t_epfd = -1;\n}\n\n\/\/\/ Зарегистрировать соединение\nvoid ConnectionManager::add(const std::shared_ptr<Connection>& connection)\n{\n\tstd::lock_guard<std::recursive_mutex> guard(getInstance()._mutex);\n\n\tif (getInstance()._allConnections.find(connection.get()) != getInstance()._allConnections.end())\n\t{\n\t\tgetInstance()._log.warn(\"%s already registered in manager\", connection->name().c_str());\n\t\treturn;\n\t}\n\n\tgetInstance()._allConnections.emplace(connection.get(), connection);\n\n\tgetInstance()._log.debug(\"%s registered in manager\", connection->name().c_str());\n\n\tepoll_event ev{};\n\n\tconnection->watch(ev);\n\n\t\/\/ Включаем наблюдение\n\tif (epoll_ctl(getInstance()._epfd, EPOLL_CTL_ADD, connection->fd(), &ev) == -1)\n\t{\n\t\tgetInstance()._log.warn(\"Fail add %s for watching (error: '%s')\", connection->name().c_str(), strerror(errno));\n\t}\n\telse\n\t{\n\t\tgetInstance()._log.trace(\"Add %s for watching\", connection->name().c_str());\n\t}\n}\n\n\/\/\/ Удалить регистрацию соединения\nbool ConnectionManager::remove(const std::shared_ptr<Connection>& connection)\n{\n\tif (!connection)\n\t{\n\t\treturn false;\n\t}\n\n\t\/\/ Удаляем из очереди событий\n\tif (epoll_ctl(getInstance()._epfd, EPOLL_CTL_DEL, connection->fd(), nullptr) == -1)\n\t{\n\t\tgetInstance()._log.warn(\"Fail remove %s from watching (error: '%s')\", connection->name().c_str(), strerror(errno));\n\t}\n\telse\n\t{\n\t\tgetInstance()._log.trace(\"Remove %s from watching\", connection->name().c_str());\n\t}\n\n\tstd::lock_guard<std::recursive_mutex> guard(getInstance()._mutex);\n\tgetInstance()._allConnections.erase(connection.get());\n\tgetInstance()._readyConnections.erase(connection);\n\tgetInstance()._capturedConnections.erase(connection);\n\n\tgetInstance()._log.debug(\"%s unregistered from manager\", connection->name().c_str());\n\n\treturn true;\n}\n\nuint32_t ConnectionManager::rotateEvents(const std::shared_ptr<Connection>& connection)\n{\n\tstd::lock_guard<std::recursive_mutex> guard(getInstance()._mutex);\n\tuint32_t events = connection->rotateEvents();\n\treturn events;\n}\n\nvoid ConnectionManager::watch(const std::shared_ptr<Connection>& connection)\n{\n\t\/\/ Для известных соенинений проверяем состояние захваченности\n\tstd::lock_guard<std::recursive_mutex> guard(getInstance()._mutex);\n\n\t\/\/ Те, что в обработке, не трогаем\n\tif (connection->isCaptured())\n\t{\n\/\/\t\t_log.trace(\"Skip watch for %s because already captured\", connection->name().c_str());\n\t\treturn;\n\t}\n\n\tepoll_event ev{};\n\n\tconnection->watch(ev);\n\n\t\/\/ Включаем наблюдение\n\tif (epoll_ctl(getInstance()._epfd, EPOLL_CTL_MOD, connection->fd(), &ev) == -1)\n\t{\n\t\tgetInstance()._log.warn(\"Fail modify watching on %s (error: '%s')\", connection->name().c_str(), strerror(errno));\n\t}\n\telse\n\t{\n\t\tgetInstance()._log.trace(\"Modify watching on %s\", connection->name().c_str());\n\t}\n}\n\n\/\/\/ Ожидать события на соединениях\nvoid ConnectionManager::wait()\n{\n\t\/\/ Если набор готовых соединений не пустой, то выходим\n\tif (!_readyConnections.empty())\n\t{\n\t\treturn;\n\t}\n\n\t_mutex.unlock();\n\n\t_epool_mutex.lock();\n\n\tint n = 0;\n\n\twhile ([&](){std::lock_guard<std::recursive_mutex> lockGuard(_mutex); return _readyConnections.empty();}())\n\t{\n\t\tif ([&](){std::lock_guard<std::recursive_mutex> lockGuard(_mutex); return _allConnections.empty();}())\n\t\t{\n\t\t\tstd::this_thread::sleep_for(std::chrono::milliseconds(100));\n\t\t\tbreak;\n\t\t}\n\t\tn = epoll_wait(_epfd, _epev, poolSize, 50);\n\t\tif (n < 0)\n\t\t{\n\t\t\tif (errno != EINTR)\n\t\t\t{\n\t\t\t\t_log.warn(\"Error waiting events of connections: fail epoll_wait (%s)\", strerror(errno));\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t\tif (n > 0)\n\t\t{\n\t\t\t_log.trace(\"Catch events on %d connection(s)\", n);\n\t\t\tbreak;\n\t\t}\n\t\tif (Daemon::shutingdown())\n\t\t{\n\t\t\t\/\/ Закрываем оставшееся\n\t\t\t_epool_mutex.unlock();\n\n\t\t\t_mutex.lock();\n\n\t\t\tif (_allConnections.empty())\n\t\t\t{\n\t\t\t\t_log.debug(\"Interrupt waiting\");\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tfor (auto& i : _allConnections)\n\t\t\t{\n\t\t\t\ti.second->setTtl(std::chrono::seconds(1));\n\t\t\t}\n\n\/\/\t\t\tstd::vector<std::shared_ptr<Connection>> connections;\n\/\/\t\t\tfor (auto& i : _allConnections)\n\/\/\t\t\t{\n\/\/\t\t\t\tconnections.emplace_back(i.second);\n\/\/\t\t\t}\n\/\/\t\t\tfor (auto& connection : connections)\n\/\/\t\t\t{\n\/\/\t\t\t\tremove(connection);\n\/\/\t\t\t}\n\n\t\t\t_mutex.unlock();\n\n\t\t\t_epool_mutex.lock();\n\t\t}\n\t}\n\n\t_mutex.lock();\n\n\t\/\/ Перебираем полученые события\n\tfor (int i = 0; i < n; i++)\n\t{\n\t\t\/\/ Игнорируем незарегистрированные соединения\n\t\tauto it = _allConnections.find(static_cast<const Connection *>(_epev[i].data.ptr));\n\t\tif (it == _allConnections.end())\n\t\t{\n\t\t\t_log.trace(\"Skip catching of unregistered Connection %p\", _epev[i].data.ptr);\n\t\t\tcontinue;\n\t\t}\n\t\tauto connection = it->second;\n\n\t\tuint32_t fdEvent = _epev[i].events;\n\t\tuint32_t events = 0;\n\n\t\tif (fdEvent & (EPOLLIN | EPOLLRDNORM))\n\t\t{\n\t\t\tevents |= static_cast<uint32_t>(ConnectionEvent::READ);\n\t\t}\n\t\tif (fdEvent & (EPOLLOUT | EPOLLWRNORM))\n\t\t{\n\t\t\tevents |= static_cast<uint32_t>(ConnectionEvent::WRITE);\n\t\t}\n\t\tif (fdEvent & EPOLLHUP)\n\t\t{\n\t\t\tevents |= static_cast<uint32_t>(ConnectionEvent::HUP);\n\t\t}\n\t\tif (fdEvent & EPOLLRDHUP)\n\t\t{\n\t\t\tevents |= static_cast<uint32_t>(ConnectionEvent::HALFHUP);\n\t\t}\n\t\tif (fdEvent & EPOLLERR)\n\t\t{\n\t\t\tevents |= static_cast<uint32_t>(ConnectionEvent::ERROR);\n\t\t}\n\n\t\t_log.trace(\"Catch events `%s` (%04x) on %s\", ConnectionEvent::code(events).c_str(), fdEvent, connection->name().c_str());\n\n\t\tconnection->appendEvents(events);\n\n\t\t\/\/ Если не в списке захваченых...\n\t\tif (_capturedConnections.find(connection) == _capturedConnections.end())\n\t\t{\n\t\t\t_log.trace(\"Insert %s into ready connection list and will be processed now (by events)\", connection->name().c_str());\n\n\t\t\t\/\/ ...добавляем в список готовых\n\t\t\t_readyConnections.insert(connection);\n\t\t}\n\t}\n\n\t_epool_mutex.unlock();\n}\n\n\/\/\/ Зарегистрировать таймаут\nvoid ConnectionManager::timeout(const std::shared_ptr<Connection>& connection)\n{\n\tauto& instance = getInstance();\n\n\tstd::lock_guard<std::recursive_mutex> lockGuard(instance._mutex);\n\n\t\/\/ Игнорируем незарегистрированные соединения\n\tauto it = instance._allConnections.find(connection.get());\n\tif (it == instance._allConnections.end())\n\t{\n\t\tinstance._log.trace(\"Skip timeout adding for noregistered Connection %p\", connection.get());\n\t\treturn;\n\t}\n\n\tconnection->appendEvents(static_cast<uint32_t>(ConnectionEvent::TIMEOUT));\n\n\tinstance._log.trace(\"Catch event `T` on %s\", connection->name().c_str());\n\n\t\/\/ Если не в списке захваченых...\n\tif (instance._capturedConnections.find(connection) == instance._capturedConnections.end())\n\t{\n\t\tinstance._log.trace(\"Insert %s into ready connection list and will be processed now (by timeout)\", connection->name().c_str());\n\n\t\t\/\/ ...добавляем в список готовых\n\t\tinstance._readyConnections.insert(connection);\n\t}\n}\n\n\/\/\/ Захватить соединение\nstd::shared_ptr<Connection> ConnectionManager::capture()\n{\n\tstd::lock_guard<std::recursive_mutex> lockGuard(_mutex);\n\n\t\/\/ Если нет готовых...\n\twhile (_readyConnections.empty())\n\t{\n\t\t\/\/ то выходим при остановке сервера\n\t\tif (Daemon::shutingdown() && _allConnections.empty())\n\t\t{\n\t\t\treturn nullptr;\n\t\t}\n\n\t\t_log.trace(\"Not found ready connection\");\n\n\t\t\/\/ а в штатном режиме ожидаем появления готового соединения\n\t\twait();\n\t}\n\n\t_log.trace(\"Found ready connection\");\n\n\tif (_readyConnections.empty())\n\t{\n\t\treturn nullptr;\n\t}\n\n\t\/\/ Берем соединение из набора готовых к обработке\n\tauto it = _readyConnections.begin();\n\n\tauto connection = *it;\n\n\t\/\/ Перемещаем соединение из набора готовых к обработке в набор захваченных\n\t_readyConnections.erase(it);\n\t_capturedConnections.insert(connection);\n\n\t_log.trace(\"Capture %s\", connection->name().c_str());\n\n\tconnection->setCaptured();\n\n\treturn std::move(connection);\n}\n\n\/\/\/ Освободить соединение\nvoid ConnectionManager::release(const std::shared_ptr<Connection>& connection)\n{\n\tstd::lock_guard<std::recursive_mutex> guard(_mutex);\n\n\t_log.trace(\"Release %s\", connection->name().c_str());\n\n\t_capturedConnections.erase(connection);\n\n\tconnection->setReleased();\n\n\tif (!connection->isClosed())\n\t{\n\t\twatch(connection);\n\t}\n}\n\n\/\/\/ Обработка событий\nvoid ConnectionManager::dispatch()\n{\n\tfor (;;)\n\t{\n\t\tstd::shared_ptr<Connection> connection = getInstance().capture();\n\t\tif (!connection)\n\t\t{\n\t\t\tbreak;\n\t\t}\n\n\t\tgetInstance()._log.debug(\"Enqueue %s for '%s' events processing\", connection->name().c_str(), ConnectionEvent::code(connection->events()).c_str());\n\n\t\tTaskManager::enqueue(\n\t\t\t[wp = std::weak_ptr<Connection>(connection)]\n\t\t\t{\n\t\t\t\tauto connection = wp.lock();\n\t\t\t\tif (!connection)\n\t\t\t\t{\n\t\t\t\t\tgetInstance()._log.trace(\"Connection death\");\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tgetInstance()._log.trace(\"Begin processing on %s\", connection->name().c_str());\n\n\t\t\t\tbool status;\n\t\t\t\ttry\n\t\t\t\t{\n\t\t\t\t\tstatus = connection->processing();\n\t\t\t\t}\n\t\t\t\tcatch (const RollbackStackAndRestoreContext& exception)\n\t\t\t\t{\n\t\t\t\t\tgetInstance().release(connection);\n\t\t\t\t\tthrow;\n\t\t\t\t}\n\t\t\t\tcatch (const std::exception& exception)\n\t\t\t\t{\n\t\t\t\t\tstatus = false;\n\t\t\t\t\tgetInstance()._log.warn(\"Uncatched exception at processing on %s: %s\", connection->name().c_str(), exception.what());\n\t\t\t\t}\n\n\t\t\t\tgetInstance().release(connection);\n\n\t\t\t\tgetInstance()._log.trace(\"End processing on %s: %s\", connection->name().c_str(), status ? \"success\" : \"fail\");\n\t\t\t}\n\t\t);\n\t}\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2016 Mirants Lu. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"log\/checkpoint_receiver.h\"\n\n#include <vector>\n\n#include \"log\/checkpoint_manager.h\"\n#include \"paxos\/config.h\"\n#include \"skywalker\/checkpoint.h\"\n#include \"skywalker\/file.h\"\n#include \"skywalker\/logging.h\"\n#include \"util\/timeops.h\"\n\nnamespace skywalker {\n\nCheckpointReceiver::CheckpointReceiver(Config* config,\n CheckpointManager* manager)\n : config_(config), manager_(manager) {}\n\nCheckpointReceiver::~CheckpointReceiver() {}\n\nbool CheckpointReceiver::BeginToReceive(const CheckpointMessage& msg) {\n sender_node_id_ = msg.node_id();\n sequence_id_ = 0;\n dirs_.clear();\n\n bool res = true;\n std::vector<std::string> dirs;\n std::vector<std::string> files;\n FileManager::Instance()->GetChildren(config_->CheckpointPath(), &dirs);\n\n for (auto& dir : dirs) {\n std::string d = config_->CheckpointPath() + \"\/\" + dir;\n FileManager::Instance()->GetChildren(d, &files, true);\n if (files.empty()) {\n continue;\n }\n for (auto& file : files) {\n Status del = FileManager::Instance()->DeleteFile(d + \"\/\" + file);\n if (!del.ok()) {\n LOG_ERROR(\"Group %u - %s.\", config_->GetGroupId(),\n del.ToString().c_str());\n res = false;\n break;\n }\n }\n FileManager::Instance()->DeleteDir(d);\n }\n\n return ComfirmReceive(msg, res);\n}\n\nbool CheckpointReceiver::ReceiveCheckpoint(const CheckpointMessage& msg) {\n LOG_DEBUG(\"Group %u - sequence_id(%d==%d)\", config_->GetGroupId(),\n msg.sequence_id(), sequence_id_ + 1);\n bool res = ReceiveFiles(msg);\n return ComfirmReceive(msg, res);\n}\n\nbool CheckpointReceiver::ReceiveFiles(const CheckpointMessage& msg) {\n if (msg.node_id() != sender_node_id_) {\n return false;\n }\n\n if (msg.sequence_id() == sequence_id_) {\n return true;\n }\n\n if (msg.sequence_id() != sequence_id_ + 1) {\n return false;\n }\n\n if (dirs_.find(msg.machine_id()) == dirs_.end()) {\n char dir[512];\n snprintf(dir, sizeof(dir), \"%s\/m%d\", config_->CheckpointPath().c_str(),\n msg.machine_id());\n FileManager::Instance()->CreateDir(dir);\n bool exits = FileManager::Instance()->FileExists(dir);\n if (!exits) {\n LOG_ERROR(\"Group %u - create checkpoint dir=%s failed.\",\n config_->GetGroupId(), dir);\n return false;\n }\n dirs_[msg.machine_id()] = std::string(dir);\n }\n\n WritableFile* file;\n std::string fname = dirs_[msg.machine_id()] + \"\/\" + msg.file();\n Status s = FileManager::Instance()->NewAppendableFile(fname, &file);\n if (s.ok()) {\n s = file->Append(msg.data());\n if (s.ok()) {\n ++sequence_id_;\n }\n delete file;\n }\n if (!s.ok()) {\n LOG_ERROR(\"Group %u - %s.\", config_->GetGroupId(), s.ToString().c_str());\n return false;\n }\n return true;\n}\n\nbool CheckpointReceiver::EndToReceive(const CheckpointMessage& msg) {\n if (msg.node_id() != sender_node_id_) {\n return true;\n }\n\n if (msg.sequence_id() != sequence_id_ + 1) {\n return false;\n }\n\n bool res = true;\n\n bool lock = false;\n while (!lock) {\n lock = config_->GetCheckpoint()->LockCheckpoint(config_->GetGroupId());\n SleepForMicroseconds(1000);\n }\n std::vector<std::string> files;\n for (auto& d : dirs_) {\n Status s = FileManager::Instance()->GetChildren(d.second, &files, true);\n if (!s.ok()) {\n LOG_ERROR(\"Group %u - %s\", config_->GetGroupId(), s.ToString().c_str());\n res = false;\n break;\n }\n if (files.empty()) {\n continue;\n }\n res = config_->GetCheckpoint()->LoadCheckpoint(\n config_->GetGroupId(), msg.instance_id(), d.first, d.second, files);\n if (!res) {\n LOG_ERROR(\"Group %u - load checkpoint failed, the machine_id=%d, dir=%s.\",\n config_->GetGroupId(), d.first, d.second.c_str());\n break;\n }\n }\n config_->GetCheckpoint()->UnLockCheckpoint(config_->GetGroupId());\n\n if (res) {\n LOG_INFO(\"Group %u - load checkpoint successful!\", config_->GetGroupId());\n LOG_WARN(\"Killing the process now...\");\n SetLogHandler(nullptr);\n exit(1);\n }\n return res;\n}\n\nbool CheckpointReceiver::ComfirmReceive(const CheckpointMessage& msg,\n bool res) {\n CheckpointMessage* reply_msg = new CheckpointMessage();\n reply_msg->set_type(CHECKPOINT_COMFIRM);\n reply_msg->set_node_id(config_->GetNodeId());\n reply_msg->set_sequence_id(msg.sequence_id());\n reply_msg->set_flag(res);\n config_->GetMessager()->SendMessage(\n msg.node_id(), config_->GetMessager()->PackMessage(reply_msg));\n if (!res && msg.node_id() == sender_node_id_) {\n Reset();\n return false;\n }\n return true;\n}\n\nvoid CheckpointReceiver::Reset() {\n sender_node_id_ = 0;\n sequence_id_ = 0;\n dirs_.clear();\n}\n\n} \/\/ namespace skywalker\n<commit_msg>fix bug<commit_after>\/\/ Copyright (c) 2016 Mirants Lu. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"log\/checkpoint_receiver.h\"\n\n#include <unistd.h>\n#include <vector>\n\n#include \"log\/checkpoint_manager.h\"\n#include \"paxos\/config.h\"\n#include \"skywalker\/checkpoint.h\"\n#include \"skywalker\/file.h\"\n#include \"skywalker\/logging.h\"\n#include \"util\/timeops.h\"\n\nnamespace skywalker {\n\nCheckpointReceiver::CheckpointReceiver(Config* config,\n CheckpointManager* manager)\n : config_(config), manager_(manager) {}\n\nCheckpointReceiver::~CheckpointReceiver() {}\n\nbool CheckpointReceiver::BeginToReceive(const CheckpointMessage& msg) {\n sender_node_id_ = msg.node_id();\n sequence_id_ = 0;\n dirs_.clear();\n\n bool res = true;\n std::vector<std::string> dirs;\n std::vector<std::string> files;\n FileManager::Instance()->GetChildren(config_->CheckpointPath(), &dirs);\n\n for (auto& dir : dirs) {\n std::string d = config_->CheckpointPath() + \"\/\" + dir;\n FileManager::Instance()->GetChildren(d, &files, true);\n if (files.empty()) {\n continue;\n }\n for (auto& file : files) {\n Status del = FileManager::Instance()->DeleteFile(d + \"\/\" + file);\n if (!del.ok()) {\n LOG_ERROR(\"Group %u - %s.\", config_->GetGroupId(),\n del.ToString().c_str());\n res = false;\n break;\n }\n }\n FileManager::Instance()->DeleteDir(d);\n }\n\n return ComfirmReceive(msg, res);\n}\n\nbool CheckpointReceiver::ReceiveCheckpoint(const CheckpointMessage& msg) {\n LOG_DEBUG(\"Group %u - sequence_id(%d==%d)\", config_->GetGroupId(),\n msg.sequence_id(), sequence_id_ + 1);\n bool res = ReceiveFiles(msg);\n return ComfirmReceive(msg, res);\n}\n\nbool CheckpointReceiver::ReceiveFiles(const CheckpointMessage& msg) {\n if (msg.node_id() != sender_node_id_) {\n return false;\n }\n\n if (msg.sequence_id() == sequence_id_) {\n return true;\n }\n\n if (msg.sequence_id() != sequence_id_ + 1) {\n return false;\n }\n\n if (dirs_.find(msg.machine_id()) == dirs_.end()) {\n char dir[512];\n snprintf(dir, sizeof(dir), \"%s\/m%d\", config_->CheckpointPath().c_str(),\n msg.machine_id());\n FileManager::Instance()->CreateDir(dir);\n bool exits = FileManager::Instance()->FileExists(dir);\n if (!exits) {\n LOG_ERROR(\"Group %u - create checkpoint dir=%s failed.\",\n config_->GetGroupId(), dir);\n return false;\n }\n dirs_[msg.machine_id()] = std::string(dir);\n }\n\n WritableFile* file;\n std::string fname = dirs_[msg.machine_id()] + \"\/\" + msg.file();\n Status s = FileManager::Instance()->NewAppendableFile(fname, &file);\n if (s.ok()) {\n s = file->Append(msg.data());\n if (s.ok()) {\n ++sequence_id_;\n }\n delete file;\n }\n if (!s.ok()) {\n LOG_ERROR(\"Group %u - %s.\", config_->GetGroupId(), s.ToString().c_str());\n return false;\n }\n return true;\n}\n\nbool CheckpointReceiver::EndToReceive(const CheckpointMessage& msg) {\n if (msg.node_id() != sender_node_id_) {\n return true;\n }\n\n if (msg.sequence_id() != sequence_id_ + 1) {\n return false;\n }\n\n bool res = true;\n\n bool lock = false;\n while (!lock) {\n lock = config_->GetCheckpoint()->LockCheckpoint(config_->GetGroupId());\n SleepForMicroseconds(1000);\n }\n std::vector<std::string> files;\n for (auto& d : dirs_) {\n Status s = FileManager::Instance()->GetChildren(d.second, &files, true);\n if (!s.ok()) {\n LOG_ERROR(\"Group %u - %s\", config_->GetGroupId(), s.ToString().c_str());\n res = false;\n break;\n }\n if (files.empty()) {\n continue;\n }\n res = config_->GetCheckpoint()->LoadCheckpoint(\n config_->GetGroupId(), msg.instance_id(), d.first, d.second, files);\n if (!res) {\n LOG_ERROR(\"Group %u - load checkpoint failed, the machine_id=%d, dir=%s.\",\n config_->GetGroupId(), d.first, d.second.c_str());\n break;\n }\n }\n config_->GetCheckpoint()->UnLockCheckpoint(config_->GetGroupId());\n\n if (res) {\n LOG_INFO(\"Group %u - load checkpoint successful!\", config_->GetGroupId());\n LOG_WARN(\"Killing the process now...\");\n \/\/ FIXME\n _exit(2);\n }\n return res;\n}\n\nbool CheckpointReceiver::ComfirmReceive(const CheckpointMessage& msg,\n bool res) {\n CheckpointMessage* reply_msg = new CheckpointMessage();\n reply_msg->set_type(CHECKPOINT_COMFIRM);\n reply_msg->set_node_id(config_->GetNodeId());\n reply_msg->set_sequence_id(msg.sequence_id());\n reply_msg->set_flag(res);\n config_->GetMessager()->SendMessage(\n msg.node_id(), config_->GetMessager()->PackMessage(reply_msg));\n if (!res && msg.node_id() == sender_node_id_) {\n Reset();\n return false;\n }\n return true;\n}\n\nvoid CheckpointReceiver::Reset() {\n sender_node_id_ = 0;\n sequence_id_ = 0;\n dirs_.clear();\n}\n\n} \/\/ namespace skywalker\n<|endoftext|>"} {"text":"<commit_before>\/\/ \r\n\/\/ Copyright (C) 2007-2008 SIPfoundry Inc. \r\n\/\/ Licensed by SIPfoundry under the LGPL license. \r\n\/\/ \r\n\/\/ Copyright (C) 2007-2008 SIPez LLC. \r\n\/\/ Licensed to SIPfoundry under a Contributor Agreement. \r\n\/\/ \r\n\/\/ $$ \r\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ \r\n\r\n\/\/ Author: Alexander Chemeris <Alexander DOT Chemeris AT SIPez DOT com>\r\n\r\n#ifdef HAVE_SPEEX\r\n\r\n\/\/ SYSTEM INCLUDES\r\n#include <assert.h>\r\n\r\n\/\/ APPLICATION INCLUDES\r\n#include <mp\/MpResamplerSpeex.h>\r\n#include <speex\/speex_resampler.h>\r\n\r\n\/\/ EXTERNAL FUNCTIONS\r\n\/\/ EXTERNAL VARIABLES\r\n\/\/ CONSTANTS\r\n\/\/ TYPEDEFS\r\n\/\/ DEFINES\r\n\/\/ MACROS\r\n\/\/ STATIC VARIABLE INITIALIZATIONS\r\n\r\n\/* \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ PUBLIC \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ *\/\r\n\r\n\/* =============================== CREATORS =============================== *\/\r\n\r\nMpResamplerSpeex::MpResamplerSpeex(uint32_t numChannels, \r\n uint32_t inputRate, uint32_t outputRate, \r\n int32_t quality)\r\n: MpResamplerBase(numChannels, inputRate, outputRate,\r\n quality >= 0 ? quality : SPEEX_RESAMPLER_QUALITY_VOIP)\r\n{\r\n \/\/ Call speex init.\r\n int speexErr = 0;\r\n mpState = speex_resampler_init(mNumChannels, mInputRate, mOutputRate, \r\n mQuality, &speexErr);\r\n\r\n assert(speexErr == RESAMPLER_ERR_SUCCESS);\r\n}\r\n\r\nMpResamplerSpeex::~MpResamplerSpeex()\r\n{\r\n \/\/ Destroy speex state object\r\n speex_resampler_destroy(mpState);\r\n mpState = NULL;\r\n}\r\n\r\n\/* ============================= MANIPULATORS ============================= *\/\r\n\r\nOsStatus MpResamplerSpeex::resetStream()\r\n{\r\n return speexErrToOsStatus(speex_resampler_reset_mem(mpState));\r\n}\r\n\r\n\/\/ Single-channel resampling.\r\nOsStatus MpResamplerSpeex::resample(uint32_t channelIndex,\r\n const MpAudioSample* pInBuf, uint32_t inBufLength, \r\n uint32_t& inSamplesProcessed, \r\n MpAudioSample* pOutBuf, uint32_t outBufLength, \r\n uint32_t& outSamplesWritten)\r\n{\r\n OsStatus ret = OS_FAILED;\r\n if(channelIndex >= mNumChannels)\r\n {\r\n \/\/ Specified a channel number that was outside the defined number of channels!\r\n return OS_INVALID_ARGUMENT;\r\n }\r\n\r\n inSamplesProcessed = inBufLength;\r\n outSamplesWritten = outBufLength;\r\n int speexErr = speex_resampler_process_int(mpState, channelIndex, \r\n pInBuf, &inSamplesProcessed, \r\n pOutBuf, &outSamplesWritten);\r\n return speexErrToOsStatus(speexErr);\r\n}\r\n\r\n\/\/ Interleaved stereo resampling.\r\nOsStatus MpResamplerSpeex::resampleInterleavedStereo(const MpAudioSample* pInBuf, \r\n uint32_t inBufLength,\r\n uint32_t& inSamplesProcessed,\r\n MpAudioSample* pOutBuf, \r\n uint32_t outBufLength,\r\n uint32_t& outSamplesWritten)\r\n{\r\n if(mNumChannels != 2)\r\n {\r\n \/\/ Cannot do interleaved stereo resampling when internal state does not \r\n \/\/ indicate we have 2 channels.\r\n return OS_INVALID_STATE;\r\n }\r\n\r\n inSamplesProcessed = inBufLength;\r\n outSamplesWritten = outBufLength;\r\n int speexErr = speex_resampler_process_interleaved_int(mpState, \r\n pInBuf, \r\n &inSamplesProcessed, \r\n pOutBuf, \r\n &outSamplesWritten);\r\n return speexErrToOsStatus(speexErr);\r\n}\r\n\r\nOsStatus MpResamplerSpeex::setInputRate(const uint32_t inputRate)\r\n{\r\n OsStatus stat = MpResamplerBase::setInputRate(inputRate);\r\n if(stat == OS_SUCCESS)\r\n {\r\n stat = speexErrToOsStatus(speex_resampler_set_rate(mpState, mInputRate, mOutputRate));\r\n }\r\n return stat;\r\n}\r\n\r\nOsStatus MpResamplerSpeex::setOutputRate(const uint32_t outputRate)\r\n{\r\n OsStatus stat = MpResamplerBase::setOutputRate(outputRate);\r\n if(stat == OS_SUCCESS)\r\n {\r\n stat = speexErrToOsStatus(speex_resampler_set_rate(mpState, mInputRate, mOutputRate));\r\n }\r\n return stat;\r\n}\r\n\r\nOsStatus MpResamplerSpeex::setQuality(const int32_t quality)\r\n{\r\n OsStatus stat = MpResamplerBase::setQuality(quality);\r\n if(stat == OS_SUCCESS)\r\n {\r\n stat = speexErrToOsStatus(speex_resampler_set_quality(mpState, mQuality));\r\n }\r\n return stat;\r\n}\r\n\r\n\/* ============================== ACCESSORS =============================== *\/\r\n\r\n\/* =============================== INQUIRY ================================ *\/\r\n\r\n\r\n\/* \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ PROTECTED \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ *\/\r\n\r\n\r\n\/* \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ PRIVATE \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ *\/\r\n\r\nOsStatus MpResamplerSpeex::speexErrToOsStatus(int speexErr)\r\n{\r\n OsStatus ret = OS_SUCCESS;\r\n switch(speexErr)\r\n {\r\n case RESAMPLER_ERR_SUCCESS:\r\n ret = OS_SUCCESS;\r\n break;\r\n case RESAMPLER_ERR_ALLOC_FAILED:\r\n ret = OS_NO_MEMORY;\r\n break;\r\n case RESAMPLER_ERR_BAD_STATE:\r\n ret = OS_INVALID_STATE;\r\n break;\r\n case RESAMPLER_ERR_INVALID_ARG:\r\n ret = OS_INVALID_ARGUMENT;\r\n break;\r\n case RESAMPLER_ERR_PTR_OVERLAP:\r\n ret = OS_INVALID;\r\n break;\r\n default:\r\n ret = OS_FAILED;\r\n break;\r\n }\r\n return ret;\r\n}\r\n\r\n\/* ============================== FUNCTIONS =============================== *\/\r\n\r\n#endif \/\/ HAVE_SPEEX\r\n<commit_msg>Win32 build: Link with libspeex if we want to use MpResamplerSpeex.<commit_after>\/\/ \r\n\/\/ Copyright (C) 2007-2008 SIPfoundry Inc. \r\n\/\/ Licensed by SIPfoundry under the LGPL license. \r\n\/\/ \r\n\/\/ Copyright (C) 2007-2008 SIPez LLC. \r\n\/\/ Licensed to SIPfoundry under a Contributor Agreement. \r\n\/\/ \r\n\/\/ $$ \r\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ \r\n\r\n\/\/ Author: Alexander Chemeris <Alexander DOT Chemeris AT SIPez DOT com>\r\n\r\n#ifdef HAVE_SPEEX\r\n\r\n\/\/ WIN32: Add libspeex to linker input.\r\n#ifdef WIN32 \/\/ [\r\n# pragma comment(lib, \"libspeex.lib\")\r\n#endif \/\/ WIN32 ]\r\n\r\n\/\/ SYSTEM INCLUDES\r\n#include <assert.h>\r\n\r\n\/\/ APPLICATION INCLUDES\r\n#include <mp\/MpResamplerSpeex.h>\r\n#include <speex\/speex_resampler.h>\r\n\r\n\/\/ EXTERNAL FUNCTIONS\r\n\/\/ EXTERNAL VARIABLES\r\n\/\/ CONSTANTS\r\n\/\/ TYPEDEFS\r\n\/\/ DEFINES\r\n\/\/ MACROS\r\n\/\/ STATIC VARIABLE INITIALIZATIONS\r\n\r\n\/* \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ PUBLIC \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ *\/\r\n\r\n\/* =============================== CREATORS =============================== *\/\r\n\r\nMpResamplerSpeex::MpResamplerSpeex(uint32_t numChannels, \r\n uint32_t inputRate, uint32_t outputRate, \r\n int32_t quality)\r\n: MpResamplerBase(numChannels, inputRate, outputRate,\r\n quality >= 0 ? quality : SPEEX_RESAMPLER_QUALITY_VOIP)\r\n{\r\n \/\/ Call speex init.\r\n int speexErr = 0;\r\n mpState = speex_resampler_init(mNumChannels, mInputRate, mOutputRate, \r\n mQuality, &speexErr);\r\n\r\n assert(speexErr == RESAMPLER_ERR_SUCCESS);\r\n}\r\n\r\nMpResamplerSpeex::~MpResamplerSpeex()\r\n{\r\n \/\/ Destroy speex state object\r\n speex_resampler_destroy(mpState);\r\n mpState = NULL;\r\n}\r\n\r\n\/* ============================= MANIPULATORS ============================= *\/\r\n\r\nOsStatus MpResamplerSpeex::resetStream()\r\n{\r\n return speexErrToOsStatus(speex_resampler_reset_mem(mpState));\r\n}\r\n\r\n\/\/ Single-channel resampling.\r\nOsStatus MpResamplerSpeex::resample(uint32_t channelIndex,\r\n const MpAudioSample* pInBuf, uint32_t inBufLength, \r\n uint32_t& inSamplesProcessed, \r\n MpAudioSample* pOutBuf, uint32_t outBufLength, \r\n uint32_t& outSamplesWritten)\r\n{\r\n OsStatus ret = OS_FAILED;\r\n if(channelIndex >= mNumChannels)\r\n {\r\n \/\/ Specified a channel number that was outside the defined number of channels!\r\n return OS_INVALID_ARGUMENT;\r\n }\r\n\r\n inSamplesProcessed = inBufLength;\r\n outSamplesWritten = outBufLength;\r\n int speexErr = speex_resampler_process_int(mpState, channelIndex, \r\n pInBuf, &inSamplesProcessed, \r\n pOutBuf, &outSamplesWritten);\r\n return speexErrToOsStatus(speexErr);\r\n}\r\n\r\n\/\/ Interleaved stereo resampling.\r\nOsStatus MpResamplerSpeex::resampleInterleavedStereo(const MpAudioSample* pInBuf, \r\n uint32_t inBufLength,\r\n uint32_t& inSamplesProcessed,\r\n MpAudioSample* pOutBuf, \r\n uint32_t outBufLength,\r\n uint32_t& outSamplesWritten)\r\n{\r\n if(mNumChannels != 2)\r\n {\r\n \/\/ Cannot do interleaved stereo resampling when internal state does not \r\n \/\/ indicate we have 2 channels.\r\n return OS_INVALID_STATE;\r\n }\r\n\r\n inSamplesProcessed = inBufLength;\r\n outSamplesWritten = outBufLength;\r\n int speexErr = speex_resampler_process_interleaved_int(mpState, \r\n pInBuf, \r\n &inSamplesProcessed, \r\n pOutBuf, \r\n &outSamplesWritten);\r\n return speexErrToOsStatus(speexErr);\r\n}\r\n\r\nOsStatus MpResamplerSpeex::setInputRate(const uint32_t inputRate)\r\n{\r\n OsStatus stat = MpResamplerBase::setInputRate(inputRate);\r\n if(stat == OS_SUCCESS)\r\n {\r\n stat = speexErrToOsStatus(speex_resampler_set_rate(mpState, mInputRate, mOutputRate));\r\n }\r\n return stat;\r\n}\r\n\r\nOsStatus MpResamplerSpeex::setOutputRate(const uint32_t outputRate)\r\n{\r\n OsStatus stat = MpResamplerBase::setOutputRate(outputRate);\r\n if(stat == OS_SUCCESS)\r\n {\r\n stat = speexErrToOsStatus(speex_resampler_set_rate(mpState, mInputRate, mOutputRate));\r\n }\r\n return stat;\r\n}\r\n\r\nOsStatus MpResamplerSpeex::setQuality(const int32_t quality)\r\n{\r\n OsStatus stat = MpResamplerBase::setQuality(quality);\r\n if(stat == OS_SUCCESS)\r\n {\r\n stat = speexErrToOsStatus(speex_resampler_set_quality(mpState, mQuality));\r\n }\r\n return stat;\r\n}\r\n\r\n\/* ============================== ACCESSORS =============================== *\/\r\n\r\n\/* =============================== INQUIRY ================================ *\/\r\n\r\n\r\n\/* \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ PROTECTED \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ *\/\r\n\r\n\r\n\/* \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ PRIVATE \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ *\/\r\n\r\nOsStatus MpResamplerSpeex::speexErrToOsStatus(int speexErr)\r\n{\r\n OsStatus ret = OS_SUCCESS;\r\n switch(speexErr)\r\n {\r\n case RESAMPLER_ERR_SUCCESS:\r\n ret = OS_SUCCESS;\r\n break;\r\n case RESAMPLER_ERR_ALLOC_FAILED:\r\n ret = OS_NO_MEMORY;\r\n break;\r\n case RESAMPLER_ERR_BAD_STATE:\r\n ret = OS_INVALID_STATE;\r\n break;\r\n case RESAMPLER_ERR_INVALID_ARG:\r\n ret = OS_INVALID_ARGUMENT;\r\n break;\r\n case RESAMPLER_ERR_PTR_OVERLAP:\r\n ret = OS_INVALID;\r\n break;\r\n default:\r\n ret = OS_FAILED;\r\n break;\r\n }\r\n return ret;\r\n}\r\n\r\n\/* ============================== FUNCTIONS =============================== *\/\r\n\r\n#endif \/\/ HAVE_SPEEX\r\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (C) 2014, Richard Thomson. All rights reserved.\n#include \"json.h\"\n#include <boost\/spirit\/include\/qi.hpp>\n\nnamespace json\n{\n\nvalue parse(std::string const& text)\n{\n using namespace boost::spirit::qi;\n std::string::const_iterator start{text.begin()};\n value result;\n if (phrase_parse(start, text.end(),\n bool_\n | (int_ >> !no_case[char_(\".e\")])\n | double_\n | ('\"' >> *(char_ - '\"') >> '\"'), ascii::space, result)\n && start == text.end())\n {\n return result;\n }\n\n throw std::domain_error(\"invalid JSON input\");\n}\n\n}\n<commit_msg>Refactor: Extract JSON grammar class<commit_after>\/\/ Copyright (C) 2014, Richard Thomson. All rights reserved.\n#include \"json.h\"\n#include <boost\/spirit\/include\/qi.hpp>\n\nusing namespace boost::spirit::qi;\n\nnamespace\n{\n\ntypedef ascii::space_type skipper;\n\ntemplate <typename Iter>\nstruct json_grammar : grammar<Iter, json::value(), skipper>\n{\n json_grammar() : json_grammar::base_type(start)\n {\n boolean = bool_;\n integer = int_ >> !no_case[char_(\".e\")];\n number = double_;\n quoted_string = '\"' >> *(char_ - '\"') >> '\"';\n start = boolean | integer | number | quoted_string;\n }\n\n rule<Iter, json::value(), skipper> start;\n rule<Iter, bool(), skipper> boolean;\n rule<Iter, int(), skipper> integer;\n rule<Iter, double(), skipper> number;\n rule<Iter, std::string(), skipper> quoted_string;\n};\n\n}\n\nnamespace json\n{\n\nvalue parse(std::string const& text)\n{\n std::string::const_iterator start{text.begin()};\n value result;\n if (phrase_parse(start, text.end(),\n json_grammar<std::string::const_iterator>(),\n ascii::space, result)\n && start == text.end())\n {\n return result;\n }\n\n throw std::domain_error(\"invalid JSON input\");\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: accmgr.cxx,v $\n *\n * $Revision: 1.4 $\n *\n * last change: $Author: rt $ $Date: 2005-09-09 12:21:21 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef _LIST_HXX\n#include <tools\/list.hxx>\n#endif\n#ifndef _DEBUG_HXX\n#include <tools\/debug.hxx>\n#endif\n\n#ifndef _SV_ACCEL_H\n#include <accel.h>\n#endif\n#ifndef _SV_ACCEL_HXX\n#include <accel.hxx>\n#endif\n#ifndef _SV_ACCMGR_HXX\n#include <accmgr.hxx>\n#endif\n\n\n\n\/\/ =======================================================================\n\nDECLARE_LIST( ImplAccelList, Accelerator* );\n\n\/\/ =======================================================================\n\nDBG_NAMEEX( Accelerator );\n\n\/\/ =======================================================================\n\nImplAccelManager::~ImplAccelManager()\n{\n if ( mpAccelList )\n delete mpAccelList;\n if ( mpSequenceList )\n delete mpSequenceList;\n}\n\n\/\/ -----------------------------------------------------------------------\n\nBOOL ImplAccelManager::InsertAccel( Accelerator* pAccel )\n{\n if ( !mpAccelList )\n mpAccelList = new ImplAccelList;\n else\n {\n \/\/ Gibts den schon ?\n if ( mpAccelList->GetPos( pAccel ) != LIST_ENTRY_NOTFOUND )\n return FALSE;\n }\n\n \/\/ Am Anfang der Liste einfuegen\n mpAccelList->Insert( pAccel, (ULONG)0 );\n\n return TRUE;\n}\n\n\/\/ -----------------------------------------------------------------------\n\nvoid ImplAccelManager::RemoveAccel( Accelerator* pAccel )\n{\n \/\/ Haben wir ueberhaupt eine Liste ?\n if ( !mpAccelList )\n return;\n\n \/\/ Raus damit\n mpAccelList->Remove( pAccel );\n}\n\n\/\/ -----------------------------------------------------------------------\n\nvoid ImplAccelManager::EndSequence( BOOL bCancel )\n{\n \/\/ Sind wir ueberhaupt in einer Sequenz ?\n if ( !mpSequenceList )\n return;\n\n \/\/ Alle Deactivate-Handler der Acceleratoren in der Sequenz rufen\n Accelerator* pTempAccel = mpSequenceList->First();\n while( pTempAccel )\n {\n BOOL bDel = FALSE;\n pTempAccel->mbIsCancel = bCancel;\n pTempAccel->mpDel = &bDel;\n pTempAccel->Deactivate();\n if ( !bDel )\n {\n pTempAccel->mbIsCancel = FALSE;\n pTempAccel->mpDel = NULL;\n }\n\n pTempAccel = mpSequenceList->Next();\n }\n\n \/\/ Sequenz-Liste loeschen\n delete mpSequenceList;\n mpSequenceList = NULL;\n}\n\n\/\/ -----------------------------------------------------------------------\n\nBOOL ImplAccelManager::IsAccelKey( const KeyCode& rKeyCode, USHORT nRepeat )\n{\n Accelerator* pAccel;\n\n \/\/ Haben wir ueberhaupt Acceleratoren ??\n if ( !mpAccelList )\n return FALSE;\n if ( !mpAccelList->Count() )\n return FALSE;\n\n \/\/ Sind wir in einer Sequenz ?\n if ( mpSequenceList )\n {\n pAccel = mpSequenceList->GetObject( 0 );\n DBG_CHKOBJ( pAccel, Accelerator, NULL );\n\n \/\/ Nicht Gefunden ?\n if ( !pAccel )\n {\n \/\/ Sequenz abbrechen\n FlushAccel();\n return FALSE;\n }\n\n \/\/ Ist der Eintrag da drin ?\n ImplAccelEntry* pEntry = pAccel->ImplGetAccelData( rKeyCode );\n if ( pEntry )\n {\n Accelerator* pNextAccel = pEntry->mpAccel;\n\n \/\/ Ist da ein Accelerator hinter ?\n if ( pNextAccel )\n {\n DBG_CHKOBJ( pNextAccel, Accelerator, NULL );\n\n mpSequenceList->Insert( pNextAccel, (ULONG)0 );\n\n \/\/ Activate-Handler vom Neuen rufen\n pNextAccel->Activate();\n return TRUE;\n }\n else\n {\n \/\/ Hat ihn schon !\n if ( pEntry->mbEnabled )\n {\n \/\/ Sequence beenden (Deactivate-Handler vorher rufen)\n EndSequence();\n\n \/\/ Dem Accelerator das aktuelle Item setzen\n \/\/ und Handler rufen\n BOOL bDel = FALSE;\n pAccel->maCurKeyCode = rKeyCode;\n pAccel->mnCurId = pEntry->mnId;\n pAccel->mnCurRepeat = nRepeat;\n pAccel->mpDel = &bDel;\n pAccel->Select();\n\n \/\/ Hat Accel den Aufruf ueberlebt\n if ( !bDel )\n {\n DBG_CHKOBJ( pAccel, Accelerator, NULL );\n pAccel->maCurKeyCode = KeyCode();\n pAccel->mnCurId = 0;\n pAccel->mnCurRepeat = 0;\n pAccel->mpDel = NULL;\n }\n\n return TRUE;\n }\n else\n {\n \/\/ Sequenz abbrechen, weil Acceleraor disabled\n \/\/ Taste wird weitergeleitet (ans System)\n FlushAccel();\n return FALSE;\n }\n }\n }\n else\n {\n \/\/ Sequenz abbrechen wegen falscher Taste\n FlushAccel();\n return FALSE;\n }\n }\n\n \/\/ Durch die Liste der Acceleratoren wuehlen\n pAccel = mpAccelList->First();\n while ( pAccel )\n {\n DBG_CHKOBJ( pAccel, Accelerator, NULL );\n\n \/\/ Ist der Eintrag da drin ?\n ImplAccelEntry* pEntry = pAccel->ImplGetAccelData( rKeyCode );\n if ( pEntry )\n {\n Accelerator* pNextAccel = pEntry->mpAccel;\n\n \/\/ Ist da ein Accelerator hinter ?\n if ( pNextAccel )\n {\n DBG_CHKOBJ( pNextAccel, Accelerator, NULL );\n\n \/\/ Sequenz-Liste erzeugen\n mpSequenceList = new ImplAccelList;\n mpSequenceList->Insert( pAccel, (ULONG)0 );\n mpSequenceList->Insert( pNextAccel, (ULONG)0 );\n\n \/\/ Activate-Handler vom Neuen rufen\n pNextAccel->Activate();\n\n return TRUE;\n }\n else\n {\n \/\/ Hat ihn schon !\n if ( pEntry->mbEnabled )\n {\n \/\/ Activate\/Deactivate-Handler vorher rufen\n pAccel->Activate();\n pAccel->Deactivate();\n\n \/\/ Dem Accelerator das aktuelle Item setzen\n \/\/ und Handler rufen\n BOOL bDel = FALSE;\n pAccel->maCurKeyCode = rKeyCode;\n pAccel->mnCurId = pEntry->mnId;\n pAccel->mnCurRepeat = nRepeat;\n pAccel->mpDel = &bDel;\n pAccel->Select();\n\n \/\/ Hat Accel den Aufruf ueberlebt\n if ( !bDel )\n {\n DBG_CHKOBJ( pAccel, Accelerator, NULL );\n pAccel->maCurKeyCode = KeyCode();\n pAccel->mnCurId = 0;\n pAccel->mnCurRepeat = 0;\n pAccel->mpDel = NULL;\n }\n\n return TRUE;\n }\n else\n return FALSE;\n }\n }\n\n \/\/ Nicht gefunden, vielleicht im naechsten Accelerator\n pAccel = mpAccelList->Next();\n }\n\n return FALSE;\n}\n<commit_msg>INTEGRATION: CWS warnings01 (1.4.70); FILE MERGED 2005\/11\/10 20:06:32 pl 1.4.70.1: #i55991# removed warnings<commit_after>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: accmgr.cxx,v $\n *\n * $Revision: 1.5 $\n *\n * last change: $Author: hr $ $Date: 2006-06-19 19:35:03 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef _LIST_HXX\n#include <tools\/list.hxx>\n#endif\n#ifndef _DEBUG_HXX\n#include <tools\/debug.hxx>\n#endif\n\n#ifndef _SV_ACCEL_H\n#include <accel.h>\n#endif\n#ifndef _SV_ACCEL_HXX\n#include <accel.hxx>\n#endif\n#ifndef _SV_ACCMGR_HXX\n#include <accmgr.hxx>\n#endif\n\n\n\n\/\/ =======================================================================\n\nDECLARE_LIST( ImplAccelList, Accelerator* )\n\n\/\/ =======================================================================\n\nDBG_NAMEEX( Accelerator )\n\n\/\/ =======================================================================\n\nImplAccelManager::~ImplAccelManager()\n{\n if ( mpAccelList )\n delete mpAccelList;\n if ( mpSequenceList )\n delete mpSequenceList;\n}\n\n\/\/ -----------------------------------------------------------------------\n\nBOOL ImplAccelManager::InsertAccel( Accelerator* pAccel )\n{\n if ( !mpAccelList )\n mpAccelList = new ImplAccelList;\n else\n {\n \/\/ Gibts den schon ?\n if ( mpAccelList->GetPos( pAccel ) != LIST_ENTRY_NOTFOUND )\n return FALSE;\n }\n\n \/\/ Am Anfang der Liste einfuegen\n mpAccelList->Insert( pAccel, (ULONG)0 );\n\n return TRUE;\n}\n\n\/\/ -----------------------------------------------------------------------\n\nvoid ImplAccelManager::RemoveAccel( Accelerator* pAccel )\n{\n \/\/ Haben wir ueberhaupt eine Liste ?\n if ( !mpAccelList )\n return;\n\n \/\/ Raus damit\n mpAccelList->Remove( pAccel );\n}\n\n\/\/ -----------------------------------------------------------------------\n\nvoid ImplAccelManager::EndSequence( BOOL bCancel )\n{\n \/\/ Sind wir ueberhaupt in einer Sequenz ?\n if ( !mpSequenceList )\n return;\n\n \/\/ Alle Deactivate-Handler der Acceleratoren in der Sequenz rufen\n Accelerator* pTempAccel = mpSequenceList->First();\n while( pTempAccel )\n {\n BOOL bDel = FALSE;\n pTempAccel->mbIsCancel = bCancel;\n pTempAccel->mpDel = &bDel;\n pTempAccel->Deactivate();\n if ( !bDel )\n {\n pTempAccel->mbIsCancel = FALSE;\n pTempAccel->mpDel = NULL;\n }\n\n pTempAccel = mpSequenceList->Next();\n }\n\n \/\/ Sequenz-Liste loeschen\n delete mpSequenceList;\n mpSequenceList = NULL;\n}\n\n\/\/ -----------------------------------------------------------------------\n\nBOOL ImplAccelManager::IsAccelKey( const KeyCode& rKeyCode, USHORT nRepeat )\n{\n Accelerator* pAccel;\n\n \/\/ Haben wir ueberhaupt Acceleratoren ??\n if ( !mpAccelList )\n return FALSE;\n if ( !mpAccelList->Count() )\n return FALSE;\n\n \/\/ Sind wir in einer Sequenz ?\n if ( mpSequenceList )\n {\n pAccel = mpSequenceList->GetObject( 0 );\n DBG_CHKOBJ( pAccel, Accelerator, NULL );\n\n \/\/ Nicht Gefunden ?\n if ( !pAccel )\n {\n \/\/ Sequenz abbrechen\n FlushAccel();\n return FALSE;\n }\n\n \/\/ Ist der Eintrag da drin ?\n ImplAccelEntry* pEntry = pAccel->ImplGetAccelData( rKeyCode );\n if ( pEntry )\n {\n Accelerator* pNextAccel = pEntry->mpAccel;\n\n \/\/ Ist da ein Accelerator hinter ?\n if ( pNextAccel )\n {\n DBG_CHKOBJ( pNextAccel, Accelerator, NULL );\n\n mpSequenceList->Insert( pNextAccel, (ULONG)0 );\n\n \/\/ Activate-Handler vom Neuen rufen\n pNextAccel->Activate();\n return TRUE;\n }\n else\n {\n \/\/ Hat ihn schon !\n if ( pEntry->mbEnabled )\n {\n \/\/ Sequence beenden (Deactivate-Handler vorher rufen)\n EndSequence();\n\n \/\/ Dem Accelerator das aktuelle Item setzen\n \/\/ und Handler rufen\n BOOL bDel = FALSE;\n pAccel->maCurKeyCode = rKeyCode;\n pAccel->mnCurId = pEntry->mnId;\n pAccel->mnCurRepeat = nRepeat;\n pAccel->mpDel = &bDel;\n pAccel->Select();\n\n \/\/ Hat Accel den Aufruf ueberlebt\n if ( !bDel )\n {\n DBG_CHKOBJ( pAccel, Accelerator, NULL );\n pAccel->maCurKeyCode = KeyCode();\n pAccel->mnCurId = 0;\n pAccel->mnCurRepeat = 0;\n pAccel->mpDel = NULL;\n }\n\n return TRUE;\n }\n else\n {\n \/\/ Sequenz abbrechen, weil Acceleraor disabled\n \/\/ Taste wird weitergeleitet (ans System)\n FlushAccel();\n return FALSE;\n }\n }\n }\n else\n {\n \/\/ Sequenz abbrechen wegen falscher Taste\n FlushAccel();\n return FALSE;\n }\n }\n\n \/\/ Durch die Liste der Acceleratoren wuehlen\n pAccel = mpAccelList->First();\n while ( pAccel )\n {\n DBG_CHKOBJ( pAccel, Accelerator, NULL );\n\n \/\/ Ist der Eintrag da drin ?\n ImplAccelEntry* pEntry = pAccel->ImplGetAccelData( rKeyCode );\n if ( pEntry )\n {\n Accelerator* pNextAccel = pEntry->mpAccel;\n\n \/\/ Ist da ein Accelerator hinter ?\n if ( pNextAccel )\n {\n DBG_CHKOBJ( pNextAccel, Accelerator, NULL );\n\n \/\/ Sequenz-Liste erzeugen\n mpSequenceList = new ImplAccelList;\n mpSequenceList->Insert( pAccel, (ULONG)0 );\n mpSequenceList->Insert( pNextAccel, (ULONG)0 );\n\n \/\/ Activate-Handler vom Neuen rufen\n pNextAccel->Activate();\n\n return TRUE;\n }\n else\n {\n \/\/ Hat ihn schon !\n if ( pEntry->mbEnabled )\n {\n \/\/ Activate\/Deactivate-Handler vorher rufen\n pAccel->Activate();\n pAccel->Deactivate();\n\n \/\/ Dem Accelerator das aktuelle Item setzen\n \/\/ und Handler rufen\n BOOL bDel = FALSE;\n pAccel->maCurKeyCode = rKeyCode;\n pAccel->mnCurId = pEntry->mnId;\n pAccel->mnCurRepeat = nRepeat;\n pAccel->mpDel = &bDel;\n pAccel->Select();\n\n \/\/ Hat Accel den Aufruf ueberlebt\n if ( !bDel )\n {\n DBG_CHKOBJ( pAccel, Accelerator, NULL );\n pAccel->maCurKeyCode = KeyCode();\n pAccel->mnCurId = 0;\n pAccel->mnCurRepeat = 0;\n pAccel->mpDel = NULL;\n }\n\n return TRUE;\n }\n else\n return FALSE;\n }\n }\n\n \/\/ Nicht gefunden, vielleicht im naechsten Accelerator\n pAccel = mpAccelList->Next();\n }\n\n return FALSE;\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"DataModel.h\"\n\nnamespace ob_instance{\n\tstruct DataModelClassMaker: public OpenBlox::ClassMaker{\n\t\tvoid* getInstance() const{\n\t\t\treturn NULL;\n\t\t}\n\n\t\tbool isA(const ob_instance::Instance* obj){\n\t\t\treturn (dynamic_cast<const DataModel*>(obj)) != 0;\n\t\t}\n\n\t\tbool isInstantiatable(){\n\t\t\treturn false;\n\t\t}\n\t};\n\n\tSTATIC_INIT(DataModel){\n\t\tOpenBlox::BaseGame::getInstanceFactory()->addClass(ClassName, new DataModelClassMaker());\n\n\t\tlua_State *L = OpenBlox::BaseGame::getGlobalState();\n\n\t\tluaL_Reg methods[]{\n\t\t\t{NULL, NULL}\n\t\t};\n\n\t\tluaL_Reg metamethods[] = {\n\t\t\t{\"__tostring\", Instance::lua_Instance_toString},\n\t\t\t{NULL, NULL}\n\t\t};\n\n\t\tluaL_newmetatable(L, LuaClassName);\n\n\t\tluaL_register(L, NULL, metamethods);\n\n\t\tlua_pushstring(L, \"__index\");\n\t\tlua_newtable(L);\n\n\t\tlua_pushstring(L, \"ClassName\");\n\t\tlua_pushstring(L, ClassName);\n\t\tlua_rawset(L, -3);\n\n\t\tluaL_register(L, NULL, methods);\n\n\t\tlua_rawset(L, -3);\n\t\tlua_pop(L, 1);\n\t}\n\n\tchar* DataModel::ClassName = \"DataModel\";\n\tchar* DataModel::LuaClassName = \"luaL_Instance_Instance\";\n\n\tDataModel::DataModel() : Instance(){\n\n\t}\n\n\tDataModel::~DataModel(){\n\n\t}\n\n\tInstance* DataModel::cloneImpl(){\n\t\treturn NULL;\n\t}\n\n\tint DataModel::wrap_lua(lua_State *L){\n\t\tDataModel **udata = (DataModel **)lua_newuserdata(L, sizeof(DataModel*));\n\t\t*udata = this;\n\n\t\tluaL_getmetatable(L, LuaClassName);\n\t\tlua_setmetatable(L, -2);\n\n\t\treturn 1;\n\t}\n\n\t char* DataModel::toString(){\n\t\t return ClassName;\n\t }\n}\n<commit_msg>Fixed DataModel.cpp<commit_after>#include \"DataModel.h\"\n\nnamespace ob_instance{\n\tstruct DataModelClassMaker: public OpenBlox::ClassMaker{\n\t\tvoid* getInstance() const{\n\t\t\treturn NULL;\n\t\t}\n\n\t\tbool isA(const ob_instance::Instance* obj){\n\t\t\treturn (dynamic_cast<const DataModel*>(obj)) != 0;\n\t\t}\n\n\t\tbool isInstantiatable(){\n\t\t\treturn false;\n\t\t}\n\t};\n\n\tSTATIC_INIT(DataModel){\n\t\tOpenBlox::BaseGame::getInstanceFactory()->addClass(ClassName, new DataModelClassMaker());\n\n\t\tlua_State *L = OpenBlox::BaseGame::getGlobalState();\n\n\t\tluaL_Reg methods[]{\n\t\t\t{NULL, NULL}\n\t\t};\n\n\t\tluaL_Reg metamethods[] = {\n\t\t\t{\"__tostring\", Instance::lua_Instance_toString},\n\t\t\t{NULL, NULL}\n\t\t};\n\n\t\tluaL_newmetatable(L, LuaClassName);\n\n\t\tluaL_register(L, NULL, metamethods);\n\n\t\tlua_pushstring(L, \"__index\");\n\t\tlua_newtable(L);\n\n\t\tlua_pushstring(L, \"ClassName\");\n\t\tlua_pushstring(L, ClassName);\n\t\tlua_rawset(L, -3);\n\n\t\tluaL_register(L, NULL, methods);\n\n\t\tlua_rawset(L, -3);\n\t\tlua_pop(L, 1);\n\t}\n\n\tchar* DataModel::ClassName = \"DataModel\";\n\tchar* DataModel::LuaClassName = \"luaL_Instance_DataModel\";\n\n\tDataModel::DataModel() : Instance(){\n\n\t}\n\n\tDataModel::~DataModel(){\n\n\t}\n\n\tInstance* DataModel::cloneImpl(){\n\t\treturn NULL;\n\t}\n\n\tint DataModel::wrap_lua(lua_State *L){\n\t\tDataModel **udata = (DataModel **)lua_newuserdata(L, sizeof(DataModel*));\n\t\t*udata = this;\n\n\t\tluaL_getmetatable(L, LuaClassName);\n\t\tlua_setmetatable(L, -2);\n\n\t\treturn 1;\n\t}\n\n\t char* DataModel::toString(){\n\t\t return ClassName;\n\t }\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2015, Ken Moore\n\/\/ Available under the 3-clause BSD license\n\/\/ See the LICENSE file for full details\n\/\/===========================================\n#include \"ConfigUI.h\"\n#include \"ui_ConfigUI.h\"\n\n#include <QFileDialog>\n#include <QListWidget>\n#include <QListWidgetItem>\n#include <QListView>\n#include <QTreeView>\n#include <QPoint>\n\n#include <LuminaXDG.h>\n\nConfigUI::ConfigUI(QWidget *parent) : QDialog(parent), ui(new Ui::ConfigUI){\n ui->setupUi(this);\n \/\/Make sure this dialog is centered on the parent\n if(parent!=0){\n QPoint ctr = parent->geometry().center();\n this->move( ctr.x()-(this->width()\/2), ctr.y()-(this->height()\/2) );\n }\n ui->tool_getStartDir->setIcon( LXDG::findIcon(\"folder\",\"\") );\n ui->tool_adddirs->setIcon( LXDG::findIcon(\"list-add\",\"\") );\n ui->tool_rmdir->setIcon( LXDG::findIcon(\"list-remove\",\"\") );\n}\n\nConfigUI::~ConfigUI(){\n\t\n}\n\nvoid ConfigUI::loadInitialValues(QString startdir, QStringList skipdirs){\n ui->label_start->setText(startdir);\n ui->list_excludes->clear();\n ui->list_excludes->addItems(skipdirs);\n}\n\nvoid ConfigUI::on_tool_getStartDir_clicked(){\n QString dir = QFileDialog::getExistingDirectory(this, tr(\"Select Search Directory\"), QDir::homePath() );\n if(dir.isEmpty()){ return; }\n ui->label_start->setText(dir);\n}\n\nvoid ConfigUI::on_tool_adddirs_clicked(){\n QFileDialog dlg(this);\n dlg.setFileMode(QFileDialog::DirectoryOnly);\n QListView *l = dlg.findChild<QListView*>(\"listView\");\n if(l){ l->setSelectionMode(QAbstractItemView::MultiSelection); }\n QTreeView *t = dlg.findChild<QTreeView*>();\n if(t){ t->setSelectionMode(QAbstractItemView::MultiSelection); }\n dlg.setDirectory(QDir::homePath());\n dlg.setWindowTitle( tr(\"Exclude Directories\") );\n if(dlg.exec()){\n \/\/Directories selected\n QStringList paths = dlg.selectedFiles();\n ui->list_excludes->addItems(paths);\n }\n}\n\nvoid ConfigUI::on_tool_rmdir_clicked(){\n QList<QListWidgetItem*> sel = ui->list_excludes->selectedItems();\n for(int i=0; i<sel.length(); i++){\n ui->list_excludes->removeItemWidget(sel[i]);\n }\n}\n\nvoid ConfigUI::on_list_excludes_itemSelectionChanged(){\n ui->tool_rmdir->setEnabled( !ui->list_excludes->selectedItems().isEmpty() );\n}\n\nvoid ConfigUI::on_buttonBox_accepted(){\n newStartDir = ui->label_start->text();\n QStringList dirs;\n for(int i=0; i<ui->list_excludes->count(); i++){\n dirs << ui->list_excludes->item(i)->text();\n }\n dirs.removeDuplicates();\n newSkipDirs = dirs;\n this->close();\n}\n\nvoid ConfigUI::on_buttonBox_rejected(){\n this->close();\n}\n<commit_msg>Fix a problem when removing items from the exclude list of lumina-search<commit_after>\/\/ Copyright (c) 2015, Ken Moore\n\/\/ Available under the 3-clause BSD license\n\/\/ See the LICENSE file for full details\n\/\/===========================================\n#include \"ConfigUI.h\"\n#include \"ui_ConfigUI.h\"\n\n#include <QFileDialog>\n#include <QListWidget>\n#include <QListWidgetItem>\n#include <QListView>\n#include <QTreeView>\n#include <QPoint>\n\n#include <LuminaXDG.h>\n\nConfigUI::ConfigUI(QWidget *parent) : QDialog(parent), ui(new Ui::ConfigUI){\n ui->setupUi(this);\n \/\/Make sure this dialog is centered on the parent\n if(parent!=0){\n QPoint ctr = parent->geometry().center();\n this->move( ctr.x()-(this->width()\/2), ctr.y()-(this->height()\/2) );\n }\n ui->tool_getStartDir->setIcon( LXDG::findIcon(\"folder\",\"\") );\n ui->tool_adddirs->setIcon( LXDG::findIcon(\"list-add\",\"\") );\n ui->tool_rmdir->setIcon( LXDG::findIcon(\"list-remove\",\"\") );\n}\n\nConfigUI::~ConfigUI(){\n\t\n}\n\nvoid ConfigUI::loadInitialValues(QString startdir, QStringList skipdirs){\n ui->label_start->setText(startdir);\n ui->list_excludes->clear();\n ui->list_excludes->addItems(skipdirs);\n}\n\nvoid ConfigUI::on_tool_getStartDir_clicked(){\n QString dir = QFileDialog::getExistingDirectory(this, tr(\"Select Search Directory\"), QDir::homePath() );\n if(dir.isEmpty()){ return; }\n ui->label_start->setText(dir);\n}\n\nvoid ConfigUI::on_tool_adddirs_clicked(){\n QFileDialog dlg(this);\n dlg.setFileMode(QFileDialog::DirectoryOnly);\n QListView *l = dlg.findChild<QListView*>(\"listView\");\n if(l){ l->setSelectionMode(QAbstractItemView::MultiSelection); }\n QTreeView *t = dlg.findChild<QTreeView*>();\n if(t){ t->setSelectionMode(QAbstractItemView::MultiSelection); }\n dlg.setDirectory(QDir::homePath());\n dlg.setWindowTitle( tr(\"Exclude Directories\") );\n if(dlg.exec()){\n \/\/Directories selected\n QStringList paths = dlg.selectedFiles();\n ui->list_excludes->addItems(paths);\n }\n}\n\nvoid ConfigUI::on_tool_rmdir_clicked(){\n qDeleteAll(ui->list_excludes->selectedItems());\n}\n\nvoid ConfigUI::on_list_excludes_itemSelectionChanged(){\n ui->tool_rmdir->setEnabled( !ui->list_excludes->selectedItems().isEmpty() );\n}\n\nvoid ConfigUI::on_buttonBox_accepted(){\n newStartDir = ui->label_start->text();\n QStringList dirs;\n for(int i=0; i<ui->list_excludes->count(); i++){\n dirs << ui->list_excludes->item(i)->text();\n }\n dirs.removeDuplicates();\n newSkipDirs = dirs;\n this->close();\n}\n\nvoid ConfigUI::on_buttonBox_rejected(){\n this->close();\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"Rational.hpp\"\n\n#include \"Float.hpp\"\n#include \"Integer.hpp\"\n\nusing namespace flusspferd;\n\nnamespace multi_precission {\n Rational::Rational(flusspferd::object const &self, mpq_class const &mp)\n : flusspferd::native_object_base(self), mp(mp)\n { }\n\n Rational::Rational(flusspferd::object const &self, flusspferd::call_context &x)\n : flusspferd::native_object_base(self)\n {\n \/\/ TODO\n if(x.arg.size() == 1) {\n flusspferd::value v = x.arg.front();\n if(v.is_double())\n mp = v.get_double();\n else if(v.is_int())\n mp = v.get_int();\n else if(v.is_string())\n mp = v.to_std_string();\n else\n mp = flusspferd::get_native<Integer>(v.get_object()).mp;\n }\n else\n throw flusspferd::exception(\"Wrong number of arguments!\");\n }\n}\n<commit_msg>plugins.gmp: improved Rational's constructor<commit_after>#include \"Rational.hpp\"\n\n#include \"Float.hpp\"\n#include \"Integer.hpp\"\n\nusing namespace flusspferd;\n\nnamespace multi_precission {\n Rational::Rational(flusspferd::object const &self, mpq_class const &mp)\n : flusspferd::native_object_base(self), mp(mp)\n { }\n\n Rational::Rational(flusspferd::object const &self, flusspferd::call_context &x)\n : flusspferd::native_object_base(self)\n {\n if(x.arg.size() == 1) {\n flusspferd::value v = x.arg.front();\n if(v.is_double())\n mp = v.get_double();\n else if(v.is_int())\n mp = v.get_int();\n else if(v.is_string())\n mp = v.to_std_string();\n else if(flusspferd::is_native<Integer>(v.get_object()))\n mp = flusspferd::get_native<Integer>(v.get_object()).mp;\n else if(flusspferd::is_native<Rational>(v.get_object()))\n mp = flusspferd::get_native<Rational>(v.get_object()).mp;\n else if(flusspferd::is_native<Float>(v.get_object()))\n mp = flusspferd::get_native<Float>(v.get_object()).mp;\n else\n throw flusspferd::exception(\"Wrong parameter type\");\n }\n else if(x.arg.size() == 2) {\n flusspferd::value v = x.arg.front();\n flusspferd::value u = x.arg.back();\n if(v.is_int() && u.is_int())\n mp = mpq_class(v.get_int(), u.get_int());\n else if(v.is_string() && u.is_int())\n mp.set_str(v.to_std_string(), u.get_int());\n else\n throw flusspferd::exception(\"Wrong arguments! (string, int) expected.\");\n }\n else\n throw flusspferd::exception(\"Wrong number of arguments\");\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: sddetect.hxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: rt $ $Date: 2005-09-09 06:48:24 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef _SD_TYPEDETECT_HXX\n#define _SD_TYPEDETECT_HXX\n\n#ifndef _RTL_USTRING_HXX_\n#include <rtl\/ustring.hxx>\n#endif\n\n#ifndef _TOOLS_DEBUG_HXX\n#include <tools\/debug.hxx>\n#endif\n\n#ifndef _COM_SUN_STAR_DOCUMENT_XEXTENDEDFILTERDETECTION_HPP_\n#include <com\/sun\/star\/document\/XExtendedFilterDetection.hpp>\n#endif\n\n#ifndef _COM_SUN_STAR_UNO_EXCEPTION_HPP_\n#include <com\/sun\/star\/uno\/Exception.hpp>\n#endif\n\n#ifndef _COM_SUN_STAR_UNO_REFERENCE_H_\n#include <com\/sun\/star\/uno\/Reference.h>\n#endif\n\n#ifndef _CPPUHELPER_IMPLBASE2_HXX_\n#include <cppuhelper\/implbase2.hxx>\n#endif\n\n#include <com\/sun\/star\/lang\/XServiceInfo.hpp>\n#include <com\/sun\/star\/lang\/XSingleServiceFactory.hpp>\n#include <cppuhelper\/factory.hxx>\n#include <tools\/link.hxx>\n#include <tools\/string.hxx>\n\nclass SfxObjectFactory;\nclass SfxFilterMatcher;\nclass LoadEnvironment_Impl;\nclass SfxMedium;\n\nnamespace com\n{\n namespace sun\n {\n namespace star\n {\n namespace uno\n {\n class Any;\n }\n namespace lang\n {\n class XMultiServiceFactory;\n }\n namespace frame\n {\n class XFrame;\n }\n namespace beans\n {\n struct PropertyValue;\n }\n }\n }\n}\n\n#include <sfx2\/sfxuno.hxx>\n\n#define REFERENCE ::com::sun::star::uno::Reference\n#define SEQUENCE ::com::sun::star::uno::Sequence\n#define RUNTIME_EXCEPTION ::com::sun::star::uno::RuntimeException\n\nclass SdFilterDetect : public ::cppu::WeakImplHelper2< ::com::sun::star::document::XExtendedFilterDetection, ::com::sun::star::lang::XServiceInfo >\n{\npublic:\n SdFilterDetect( const REFERENCE < ::com::sun::star::lang::XMultiServiceFactory >& xFactory );\n virtual ~SdFilterDetect();\n\n SFX_DECL_XSERVICEINFO\n\n \/\/----------------------------------------------------------------------------------\n \/\/ XExtendedFilterDetect\n \/\/----------------------------------------------------------------------------------\n virtual ::rtl::OUString SAL_CALL detect( SEQUENCE< ::com::sun::star::beans::PropertyValue >& lDescriptor ) throw( RUNTIME_EXCEPTION );\n};\n\n#endif\n<commit_msg>INTEGRATION: CWS changefileheader (1.3.624); FILE MERGED 2008\/04\/01 15:36:13 thb 1.3.624.3: #i85898# Stripping all external header guards 2008\/04\/01 12:39:25 thb 1.3.624.2: #i85898# Stripping all external header guards 2008\/03\/31 13:59:08 rt 1.3.624.1: #i87441# Change license header to LPGL v3.<commit_after>\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2008 by Sun Microsystems, Inc.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: sddetect.hxx,v $\n * $Revision: 1.4 $\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * <http:\/\/www.openoffice.org\/license.html>\n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n#ifndef _SD_TYPEDETECT_HXX\n#define _SD_TYPEDETECT_HXX\n\n#include <rtl\/ustring.hxx>\n#include <tools\/debug.hxx>\n#include <com\/sun\/star\/document\/XExtendedFilterDetection.hpp>\n#include <com\/sun\/star\/uno\/Exception.hpp>\n#include <com\/sun\/star\/uno\/Reference.h>\n#include <cppuhelper\/implbase2.hxx>\n\n#include <com\/sun\/star\/lang\/XServiceInfo.hpp>\n#include <com\/sun\/star\/lang\/XSingleServiceFactory.hpp>\n#include <cppuhelper\/factory.hxx>\n#include <tools\/link.hxx>\n#include <tools\/string.hxx>\n\nclass SfxObjectFactory;\nclass SfxFilterMatcher;\nclass LoadEnvironment_Impl;\nclass SfxMedium;\n\nnamespace com\n{\n namespace sun\n {\n namespace star\n {\n namespace uno\n {\n class Any;\n }\n namespace lang\n {\n class XMultiServiceFactory;\n }\n namespace frame\n {\n class XFrame;\n }\n namespace beans\n {\n struct PropertyValue;\n }\n }\n }\n}\n\n#include <sfx2\/sfxuno.hxx>\n\n#define REFERENCE ::com::sun::star::uno::Reference\n#define SEQUENCE ::com::sun::star::uno::Sequence\n#define RUNTIME_EXCEPTION ::com::sun::star::uno::RuntimeException\n\nclass SdFilterDetect : public ::cppu::WeakImplHelper2< ::com::sun::star::document::XExtendedFilterDetection, ::com::sun::star::lang::XServiceInfo >\n{\npublic:\n SdFilterDetect( const REFERENCE < ::com::sun::star::lang::XMultiServiceFactory >& xFactory );\n virtual ~SdFilterDetect();\n\n SFX_DECL_XSERVICEINFO\n\n \/\/----------------------------------------------------------------------------------\n \/\/ XExtendedFilterDetect\n \/\/----------------------------------------------------------------------------------\n virtual ::rtl::OUString SAL_CALL detect( SEQUENCE< ::com::sun::star::beans::PropertyValue >& lDescriptor ) throw( RUNTIME_EXCEPTION );\n};\n\n#endif\n<|endoftext|>"} {"text":"<commit_before>\/**\n * Copyright © 2017 INFN Torino - INDIGO-DataCloud\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"Request.h\"\n\n#include <pwd.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <unistd.h>\n#include <cstdlib>\n\n#include \"FassLog.h\"\n\nstring Request::format_str;\n\nvoid Request::execute(\n xmlrpc_c::paramList const& _paramList,\n xmlrpc_c::value * const _retval) {\n RequestAttributes att;\n \/\/ user attributes\n struct passwd *pw;\n uid_t uid;\n gid_t gid;\n uid = geteuid();\n gid = getegid();\n pw = getpwuid(uid);\n att.uid = uid;\n att.gid = gid;\n att.uname = pw->pw_name;\n att.retval = _retval;\n att.session = xmlrpc_c::value_string(_paramList.getString(0));\n\n att.req_id = (reinterpret_cast<uintptr_t>(this) * rand_r(0)) % 10000;\n\n\n log_method_invoked(att, _paramList, format_str, method_name, hidden_params);\n request_execute(_paramList, att);\n log_result(att, method_name);\n}\n\nvoid Request::log_method_invoked(const RequestAttributes& att,\n const xmlrpc_c::paramList& paramList, const string& format_str,\n const std::string& method_name, const std::set<int>& hidden_params) {\n std::ostringstream oss;\n\n for (unsigned int j = 0; j < format_str.length() - 1; j++) {\n if (format_str[j] != '%') {\n oss << format_str[j];\n } else {\n char mod = format_str[j+1];\n switch (mod) {\n case '%':\n oss << \"%\";\n break;\n\n case 'i':\n oss << att.req_id;\n break;\n\n case 'u':\n oss << att.uid;\n break;\n\n case 'U':\n oss << att.uname;\n break;\n\n case 'g':\n oss << att.gid;\n break;\n\n case 'G':\n oss << att.gname;\n break;\n\n case 'p':\n oss << att.password;\n break;\n\n case 'a':\n oss << att.session;\n break;\n\n case 'm':\n oss << method_name;\n break;\n\n case 'l':\n for (unsigned int i = 1; i < paramList.size(); i++) {\n if ( hidden_params.count(i) == 1 ) {\n oss << \", ****\";\n } else {\n log_xmlrpc_value(paramList[i], oss);\n }\n }\n break;\n\n default:\n oss << format_str[j] << format_str[j+1];\n break;\n }\n\n j = j+1;\n }\n }\n\n FassLog::log(\"REQUEST\", Log::DDEBUG, oss);\n}\n\nvoid Request::log_xmlrpc_value(const xmlrpc_c::value& v,\n std::ostringstream& oss) {\n size_t st_limit = 20;\n size_t st_newline;\n\n switch (v.type()) {\n case xmlrpc_c::value::TYPE_INT:\n oss << \", \" << static_cast<int>(xmlrpc_c::value_int(v));\n break;\n case xmlrpc_c::value::TYPE_BOOLEAN:\n oss << \", \";\n\n if ( static_cast<bool>(xmlrpc_c::value_boolean(v)) ) {\n oss << \"true\";\n } else {\n oss << \"false\";\n }\n\n break;\n case xmlrpc_c::value::TYPE_STRING:\n st_newline =\n static_cast<string>(xmlrpc_c::value_string(v)).find(\"\\n\");\n\n if ( st_newline < st_limit ) {\n st_limit = st_newline;\n }\n\n oss << \", \\\"\"\n << static_cast<string>\n (xmlrpc_c::value_string(v)).substr(0, st_limit);\n\n if (static_cast<string>\n (xmlrpc_c::value_string(v)).size() > st_limit) {\n oss << \"...\";\n }\n\n oss << \"\\\"\";\n break;\n case xmlrpc_c::value::TYPE_DOUBLE:\n oss << \", \"\n << static_cast<double>(xmlrpc_c::value_double(v));\n break;\n default:\n oss << \", unknown param type\";\n break;\n }\n}\n\nvoid Request::log_result(const RequestAttributes& att,\n const string& method_name) {\n std::ostringstream oss;\n\n oss << \"Req:\" << att.req_id << \" UNAME:\";\n\n \/\/ if ( att.uid != -1 )\n \/\/ {\n \/\/ oss << att.uid;\n \/\/ }\n \/\/ else\n \/\/ {\n \/\/ oss << \"-\";\n \/\/ }\n\n oss << att.uname;\n oss << \" \" << method_name << \" result \";\n\n xmlrpc_c::value_array array1(*att.retval);\n vector<xmlrpc_c::value> const vvalue(array1.vectorValueValue());\n\n if (static_cast<bool>(xmlrpc_c::value_boolean(vvalue[0]))) {\n oss << \"SUCCESS\";\n\n for (unsigned int i = 1; i < vvalue.size()-1; i++) {\n log_xmlrpc_value(vvalue[i], oss);\n }\n\n FassLog::log(\"REQUEST\", Log::DDEBUG, oss);\n } else {\n oss << \"FAILURE \"\n << static_cast<string>(xmlrpc_c::value_string(vvalue[1]));\n\n FassLog::log(\"REQUEST\", Log::ERROR, oss);\n }\n}\n\n\nvoid Request::success_response(const string& val, RequestAttributes& att) {\n vector<xmlrpc_c::value> arrayData;\n\n arrayData.push_back(xmlrpc_c::value_boolean(true));\n arrayData.push_back(xmlrpc_c::value_string(val));\n arrayData.push_back(xmlrpc_c::value_int(SUCCESS));\n\n xmlrpc_c::value_array arrayresult(arrayData);\n\n *(att.retval) = arrayresult;\n}\n\nvoid Request::success_response(const int& val, RequestAttributes& att) {\n vector<xmlrpc_c::value> arrayData;\n\n arrayData.push_back(xmlrpc_c::value_boolean(true));\n arrayData.push_back(xmlrpc_c::value_int(val));\n arrayData.push_back(xmlrpc_c::value_int(SUCCESS));\n\n xmlrpc_c::value_array arrayresult(arrayData);\n\n *(att.retval) = arrayresult;\n}\n\nvoid Request::success_response(const bool& val, RequestAttributes& att) {\n vector<xmlrpc_c::value> arrayData;\n\n arrayData.push_back(xmlrpc_c::value_boolean(true));\n arrayData.push_back(xmlrpc_c::value_boolean(val));\n arrayData.push_back(xmlrpc_c::value_int(SUCCESS));\n\n xmlrpc_c::value_array arrayresult(arrayData);\n\n *(att.retval) = arrayresult;\n}\n\nvoid Request::failure_response(ErrorCode ec, RequestAttributes& att) {\n vector<xmlrpc_c::value> arrayData;\n\n arrayData.push_back(xmlrpc_c::value_boolean(false));\n arrayData.push_back(xmlrpc_c::value_int(ec));\n\n xmlrpc_c::value_array arrayresult(arrayData);\n\n *(att.retval) = arrayresult;\n}\n<commit_msg>Update Request.cc<commit_after>\/**\n * Copyright © 2017 INFN Torino - INDIGO-DataCloud\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"Request.h\"\n\n#include <pwd.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <unistd.h>\n#include <cstdlib>\n\n#include \"FassLog.h\"\n\nvoid Request::execute(\n xmlrpc_c::paramList const& _paramList,\n xmlrpc_c::value * const _retval) {\n RequestAttributes att;\n \/\/ user attributes\n struct passwd *pw;\n uid_t uid;\n gid_t gid;\n uid = geteuid();\n gid = getegid();\n pw = getpwuid(uid);\n att.uid = uid;\n att.gid = gid;\n att.uname = pw->pw_name;\n att.retval = _retval;\n att.session = xmlrpc_c::value_string(_paramList.getString(0));\n\n att.req_id = (reinterpret_cast<uintptr_t>(this) * rand_r(0)) % 10000;\n\n string format_str;\n log_method_invoked(att, _paramList, format_str, method_name, hidden_params);\n request_execute(_paramList, att);\n log_result(att, method_name);\n}\n\nvoid Request::log_method_invoked(const RequestAttributes& att,\n const xmlrpc_c::paramList& paramList, const string& format_str,\n const std::string& method_name, const std::set<int>& hidden_params) {\n std::ostringstream oss;\n\n for (unsigned int j = 0; j < format_str.length() - 1; j++) {\n if (format_str[j] != '%') {\n oss << format_str[j];\n } else {\n char mod = format_str[j+1];\n switch (mod) {\n case '%':\n oss << \"%\";\n break;\n\n case 'i':\n oss << att.req_id;\n break;\n\n case 'u':\n oss << att.uid;\n break;\n\n case 'U':\n oss << att.uname;\n break;\n\n case 'g':\n oss << att.gid;\n break;\n\n case 'G':\n oss << att.gname;\n break;\n\n case 'p':\n oss << att.password;\n break;\n\n case 'a':\n oss << att.session;\n break;\n\n case 'm':\n oss << method_name;\n break;\n\n case 'l':\n for (unsigned int i = 1; i < paramList.size(); i++) {\n if ( hidden_params.count(i) == 1 ) {\n oss << \", ****\";\n } else {\n log_xmlrpc_value(paramList[i], oss);\n }\n }\n break;\n\n default:\n oss << format_str[j] << format_str[j+1];\n break;\n }\n\n j = j+1;\n }\n }\n\n FassLog::log(\"REQUEST\", Log::DDEBUG, oss);\n}\n\nvoid Request::log_xmlrpc_value(const xmlrpc_c::value& v,\n std::ostringstream& oss) {\n size_t st_limit = 20;\n size_t st_newline;\n\n switch (v.type()) {\n case xmlrpc_c::value::TYPE_INT:\n oss << \", \" << static_cast<int>(xmlrpc_c::value_int(v));\n break;\n case xmlrpc_c::value::TYPE_BOOLEAN:\n oss << \", \";\n\n if ( static_cast<bool>(xmlrpc_c::value_boolean(v)) ) {\n oss << \"true\";\n } else {\n oss << \"false\";\n }\n\n break;\n case xmlrpc_c::value::TYPE_STRING:\n st_newline =\n static_cast<string>(xmlrpc_c::value_string(v)).find(\"\\n\");\n\n if ( st_newline < st_limit ) {\n st_limit = st_newline;\n }\n\n oss << \", \\\"\"\n << static_cast<string>\n (xmlrpc_c::value_string(v)).substr(0, st_limit);\n\n if (static_cast<string>\n (xmlrpc_c::value_string(v)).size() > st_limit) {\n oss << \"...\";\n }\n\n oss << \"\\\"\";\n break;\n case xmlrpc_c::value::TYPE_DOUBLE:\n oss << \", \"\n << static_cast<double>(xmlrpc_c::value_double(v));\n break;\n default:\n oss << \", unknown param type\";\n break;\n }\n}\n\nvoid Request::log_result(const RequestAttributes& att,\n const string& method_name) {\n std::ostringstream oss;\n\n oss << \"Req:\" << att.req_id << \" UNAME:\";\n\n \/\/ if ( att.uid != -1 )\n \/\/ {\n \/\/ oss << att.uid;\n \/\/ }\n \/\/ else\n \/\/ {\n \/\/ oss << \"-\";\n \/\/ }\n\n oss << att.uname;\n oss << \" \" << method_name << \" result \";\n\n xmlrpc_c::value_array array1(*att.retval);\n vector<xmlrpc_c::value> const vvalue(array1.vectorValueValue());\n\n if (static_cast<bool>(xmlrpc_c::value_boolean(vvalue[0]))) {\n oss << \"SUCCESS\";\n\n for (unsigned int i = 1; i < vvalue.size()-1; i++) {\n log_xmlrpc_value(vvalue[i], oss);\n }\n\n FassLog::log(\"REQUEST\", Log::DDEBUG, oss);\n } else {\n oss << \"FAILURE \"\n << static_cast<string>(xmlrpc_c::value_string(vvalue[1]));\n\n FassLog::log(\"REQUEST\", Log::ERROR, oss);\n }\n}\n\n\nvoid Request::success_response(const string& val, RequestAttributes& att) {\n vector<xmlrpc_c::value> arrayData;\n\n arrayData.push_back(xmlrpc_c::value_boolean(true));\n arrayData.push_back(xmlrpc_c::value_string(val));\n arrayData.push_back(xmlrpc_c::value_int(SUCCESS));\n\n xmlrpc_c::value_array arrayresult(arrayData);\n\n *(att.retval) = arrayresult;\n}\n\nvoid Request::success_response(const int& val, RequestAttributes& att) {\n vector<xmlrpc_c::value> arrayData;\n\n arrayData.push_back(xmlrpc_c::value_boolean(true));\n arrayData.push_back(xmlrpc_c::value_int(val));\n arrayData.push_back(xmlrpc_c::value_int(SUCCESS));\n\n xmlrpc_c::value_array arrayresult(arrayData);\n\n *(att.retval) = arrayresult;\n}\n\nvoid Request::success_response(const bool& val, RequestAttributes& att) {\n vector<xmlrpc_c::value> arrayData;\n\n arrayData.push_back(xmlrpc_c::value_boolean(true));\n arrayData.push_back(xmlrpc_c::value_boolean(val));\n arrayData.push_back(xmlrpc_c::value_int(SUCCESS));\n\n xmlrpc_c::value_array arrayresult(arrayData);\n\n *(att.retval) = arrayresult;\n}\n\nvoid Request::failure_response(ErrorCode ec, RequestAttributes& att) {\n vector<xmlrpc_c::value> arrayData;\n\n arrayData.push_back(xmlrpc_c::value_boolean(false));\n arrayData.push_back(xmlrpc_c::value_int(ec));\n\n xmlrpc_c::value_array arrayresult(arrayData);\n\n *(att.retval) = arrayresult;\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n* this file is part of the oxygen gtk engine\n* Copyright (c) 2010 Hugo Pereira Da Costa <hugo@oxygen-icons.org>\n*\n* inspired notably from kdelibs\/kdeui\/color\/kcolorutils.h\n* Copyright (C) 2007 Matthew Woehlke <mw_triad@users.sourceforge.net>\n* Copyright (C) 2007 Thomas Zander <zander@kde.org>\n* Copyright (C) 2007 Zack Rusin <zack@kde.org>\n*\n* This library is free software; you can redistribute it and\/or\n* modify it under the terms of the GNU Lesser General Public\n* License as published by the Free Software Foundation; either\n* version 2 of the License, or( at your option ) any later version.\n*\n* This library is distributed in the hope that it will be useful,\n* but WITHOUT ANY WARRANTY; without even the implied warranty of\n* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n* Lesser General Public License for more details.\n*\n* You should have received a copy of the GNU Lesser General Public\n* License along with this library; if not, write to the Free\n* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,\n* MA 02110-1301, USA.\n*\/\n\n#include \"oxygenapplicationname.h\"\n#include \"oxygengtkutils.h\"\n#include \"config.h\"\n\n#include <fstream>\n#include <iostream>\n#include <sstream>\n\nnamespace Oxygen\n{\n\n \/\/__________________________________________________________________________\n void ApplicationName::initialize( void )\n {\n\n \/\/ get application name from gtk\n const std::string gtkAppName( fromGtk() );\n\n \/\/ get application name from pid\n const std::string pidAppName( fromPid( getpid() ) );\n\n #if OXYGEN_DEBUG\n std::cerr << \"ApplicationName::initialize -\"\n << \" from pid: \" << pidAppName\n << \" from gtk: \" << gtkAppName\n << std::endl;\n #endif\n\n \/\/ initialize to unknown\n _name = Unknown;\n\n if( pidAppName == \"opera\" ) _name = Opera;\n else if( pidAppName.find( \"komodo\" ) != std::string::npos ) _name = Komodo;\n else if( gtkAppName == \"eclipse\" || gtkAppName == \"Eclipse\" ) _name = Eclipse;\n else if( pidAppName == \"java\" ) {\n\n if( !( gtkAppName.empty() || gtkAppName == \"<unknown>\" ) ) _name = JavaSwt;\n else _name = Java;\n\n } else if( gtkAppName == \"acroread\" ) _name = Acrobat;\n else if( gtkAppName == \"soffice\" ) _name = OpenOffice;\n else if( gtkAppName == \"gimp\" ) _name = Gimp;\n else if(\n gtkAppName == \"chromium\" ||\n gtkAppName == \"chromium-browser\" ||\n gtkAppName == \"google-chrome\" ) _name = GoogleChrome;\n else {\n\n \/\/ tag all mozilla-like applications (XUL)\n static const std::string XulAppNames[] =\n {\n \"firefox\",\n \"thunderbird\",\n \"seamonkey\",\n \"iceweasel\",\n \"icecat\",\n \"icedove\",\n \"xulrunner\",\n \"\"\n };\n\n for( unsigned int index = 0; !XulAppNames[index].empty(); ++index )\n {\n if( gtkAppName.find( XulAppNames[index] ) == 0 )\n {\n _name = XUL;\n break;\n }\n }\n }\n\n #if OXYGEN_DEBUG\n std::cerr << \"ApplicationName::initialize -\"\n << \" from pid: \" << pidAppName\n << \" from gtk: \" << gtkAppName\n << \" internal: \" << *this\n << std::endl;\n #endif\n\n\n }\n\n \/\/__________________________________________________________________________\n bool ApplicationName::isGtkDialogWidget( GtkWidget* widget ) const\n {\n GtkWidget* parent( gtk_widget_get_toplevel( widget ) );\n\n \/\/ check parent\n return parent && GTK_IS_DIALOG( parent );\n }\n\n \/\/__________________________________________________________________________\n bool ApplicationName::useFlatBackground( GtkWidget* widget ) const\n {\n\n \/\/ check application name\n if( !(\n isKomodo() ||\n isXul() ||\n isAcrobat() ||\n isJavaSwt() ||\n isOpenOffice() ||\n isGoogleChrome() ||\n isEclipse() ) ) return false;\n\n \/\/ check for special cases\n if(widget)\n {\n \/\/ first check parent\n GtkWidget* parent( gtk_widget_get_toplevel( widget ) );\n\n \/\/ check parent\n if( parent && GTK_IS_DIALOG( parent ) ) return false;\n }\n\n \/\/ return true in all other cases\n return true;\n\n }\n\n \/\/__________________________________________________________________________\n std::string ApplicationName::fromGtk( void ) const\n {\n if( const char* gtkAppName = g_get_prgname() ) return gtkAppName;\n else return \"\";\n }\n\n \/\/__________________________________________________________________________\n std::string ApplicationName::fromPid( int pid ) const\n {\n\n \/\/ generate \/proc filename\n std::ostringstream filename;\n filename << \"\/proc\/\" << pid << \"\/cmdline\";\n\n \/\/ try read file\n std::ifstream in( filename.str().c_str() );\n if( !in ) return std::string();\n\n \/*\n somehow std::getline gets some extra crap (non char) from the procfile\n one has to use ifstream::getline, and pass it a fixed size line\n *\/\n char lineC[1024];\n in.getline( lineC, 1024, '\\n' );\n std::string line( lineC );\n\n \/\/ get position of last \"\/\" character, and truncate accordingly\n const size_t pos = line.rfind( '\/' );\n if( pos == std::string::npos ) return line;\n else return line.substr( pos+1 );\n\n }\n\n \/\/__________________________________________________________________________\n std::ostream& operator << ( std::ostream& out, const ApplicationName& app )\n {\n switch( app._name )\n {\n default:\n case Unknown: out << \"Unknown\"; break;\n case Komodo: out << \"Komodo\"; break;\n case Acrobat: out << \"Acrobat\"; break;\n case XUL: out << \"XUL (Mozilla)\"; break;\n case Gimp: out << \"Gimp\"; break;\n case OpenOffice: out << \"OpenOffice\"; break;\n case GoogleChrome: out << \"GoogleChrome\"; break;\n case Opera: out << \"Opera\"; break;\n case Java: out << \"Java\"; break;\n case JavaSwt: out << \"JavaSwt\"; break;\n case Eclipse: out << \"Eclipse\"; break;\n }\n\n return out;\n }\n}\n<commit_msg>also use isGtkDialogWidget() in useFlatBackground.<commit_after>\/*\n* this file is part of the oxygen gtk engine\n* Copyright (c) 2010 Hugo Pereira Da Costa <hugo@oxygen-icons.org>\n*\n* inspired notably from kdelibs\/kdeui\/color\/kcolorutils.h\n* Copyright (C) 2007 Matthew Woehlke <mw_triad@users.sourceforge.net>\n* Copyright (C) 2007 Thomas Zander <zander@kde.org>\n* Copyright (C) 2007 Zack Rusin <zack@kde.org>\n*\n* This library is free software; you can redistribute it and\/or\n* modify it under the terms of the GNU Lesser General Public\n* License as published by the Free Software Foundation; either\n* version 2 of the License, or( at your option ) any later version.\n*\n* This library is distributed in the hope that it will be useful,\n* but WITHOUT ANY WARRANTY; without even the implied warranty of\n* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n* Lesser General Public License for more details.\n*\n* You should have received a copy of the GNU Lesser General Public\n* License along with this library; if not, write to the Free\n* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,\n* MA 02110-1301, USA.\n*\/\n\n#include \"oxygenapplicationname.h\"\n#include \"oxygengtkutils.h\"\n#include \"config.h\"\n\n#include <fstream>\n#include <iostream>\n#include <sstream>\n\nnamespace Oxygen\n{\n\n \/\/__________________________________________________________________________\n void ApplicationName::initialize( void )\n {\n\n \/\/ get application name from gtk\n const std::string gtkAppName( fromGtk() );\n\n \/\/ get application name from pid\n const std::string pidAppName( fromPid( getpid() ) );\n\n #if OXYGEN_DEBUG\n std::cerr << \"ApplicationName::initialize -\"\n << \" from pid: \" << pidAppName\n << \" from gtk: \" << gtkAppName\n << std::endl;\n #endif\n\n \/\/ initialize to unknown\n _name = Unknown;\n\n if( pidAppName == \"opera\" ) _name = Opera;\n else if( pidAppName.find( \"komodo\" ) != std::string::npos ) _name = Komodo;\n else if( gtkAppName == \"eclipse\" || gtkAppName == \"Eclipse\" ) _name = Eclipse;\n else if( pidAppName == \"java\" ) {\n\n if( !( gtkAppName.empty() || gtkAppName == \"<unknown>\" ) ) _name = JavaSwt;\n else _name = Java;\n\n } else if( gtkAppName == \"acroread\" ) _name = Acrobat;\n else if( gtkAppName == \"soffice\" ) _name = OpenOffice;\n else if( gtkAppName == \"gimp\" ) _name = Gimp;\n else if(\n gtkAppName == \"chromium\" ||\n gtkAppName == \"chromium-browser\" ||\n gtkAppName == \"google-chrome\" ) _name = GoogleChrome;\n else {\n\n \/\/ tag all mozilla-like applications (XUL)\n static const std::string XulAppNames[] =\n {\n \"firefox\",\n \"thunderbird\",\n \"seamonkey\",\n \"iceweasel\",\n \"icecat\",\n \"icedove\",\n \"xulrunner\",\n \"\"\n };\n\n for( unsigned int index = 0; !XulAppNames[index].empty(); ++index )\n {\n if( gtkAppName.find( XulAppNames[index] ) == 0 )\n {\n _name = XUL;\n break;\n }\n }\n }\n\n #if OXYGEN_DEBUG\n std::cerr << \"ApplicationName::initialize -\"\n << \" from pid: \" << pidAppName\n << \" from gtk: \" << gtkAppName\n << \" internal: \" << *this\n << std::endl;\n #endif\n\n\n }\n\n \/\/__________________________________________________________________________\n bool ApplicationName::isGtkDialogWidget( GtkWidget* widget ) const\n {\n GtkWidget* parent( gtk_widget_get_toplevel( widget ) );\n\n \/\/ check parent\n return parent && GTK_IS_DIALOG( parent );\n }\n\n \/\/__________________________________________________________________________\n bool ApplicationName::useFlatBackground( GtkWidget* widget ) const\n {\n\n \/\/ check application name\n if( !(\n isKomodo() ||\n isXul() ||\n isAcrobat() ||\n isJavaSwt() ||\n isOpenOffice() ||\n isGoogleChrome() ||\n isEclipse() ) ) return false;\n\n \/\/ check for Gtk dialog type\n if( widget && isGtkDialogWidget( widget ) ) return false;\n\n \/\/ return true in all other cases\n return true;\n\n }\n\n \/\/__________________________________________________________________________\n std::string ApplicationName::fromGtk( void ) const\n {\n if( const char* gtkAppName = g_get_prgname() ) return gtkAppName;\n else return \"\";\n }\n\n \/\/__________________________________________________________________________\n std::string ApplicationName::fromPid( int pid ) const\n {\n\n \/\/ generate \/proc filename\n std::ostringstream filename;\n filename << \"\/proc\/\" << pid << \"\/cmdline\";\n\n \/\/ try read file\n std::ifstream in( filename.str().c_str() );\n if( !in ) return std::string();\n\n \/*\n somehow std::getline gets some extra crap (non char) from the procfile\n one has to use ifstream::getline, and pass it a fixed size line\n *\/\n char lineC[1024];\n in.getline( lineC, 1024, '\\n' );\n std::string line( lineC );\n\n \/\/ get position of last \"\/\" character, and truncate accordingly\n const size_t pos = line.rfind( '\/' );\n if( pos == std::string::npos ) return line;\n else return line.substr( pos+1 );\n\n }\n\n \/\/__________________________________________________________________________\n std::ostream& operator << ( std::ostream& out, const ApplicationName& app )\n {\n switch( app._name )\n {\n default:\n case Unknown: out << \"Unknown\"; break;\n case Komodo: out << \"Komodo\"; break;\n case Acrobat: out << \"Acrobat\"; break;\n case XUL: out << \"XUL (Mozilla)\"; break;\n case Gimp: out << \"Gimp\"; break;\n case OpenOffice: out << \"OpenOffice\"; break;\n case GoogleChrome: out << \"GoogleChrome\"; break;\n case Opera: out << \"Opera\"; break;\n case Java: out << \"Java\"; break;\n case JavaSwt: out << \"JavaSwt\"; break;\n case Eclipse: out << \"Eclipse\"; break;\n }\n\n return out;\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (C) 2015 Jack Maloney. All Rights Reserved.\n\/\/\n\/\/ This Source Code Form is subject to the terms of the Mozilla Public License,\n\/\/ v. 2.0. If a copy of the MPL was not distributed with this file, You can\n\/\/ obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n\n#include \"voltz-internal.h\"\n#include <cstdlib>\n#include <cstdio>\n#include <dlfcn.h>\n#include <cstring>\n\nbool vz_load_moduleI(const char* name) {\n \n const char* vz_path = getenv(VOLTZ_PATH_ENVVAR);\n if (!vz_path) {\n const char* home = getenv(\"HOME\");\n vz_path = \"\/voltz\/modules\/:\/opt\/voltz\/modules\/\";\n char buf[strlen(home) + strlen(vz_path) + 2];\n sprintf(buf, \"%s%s\", home, vz_path);\n vz_path = strdup(buf);\n } else {\n vz_path = strdup(vz_path);\n }\n \n char* str = strdup(vz_path);\n char* token;\n while ((token = strsep(&str, \":\")) != NULL) {\n \n char buf[strlen(token) + strlen(name) + strlen(VOLTZ_MODULE_EXT) + 3];\n sprintf(buf, \"%s\/%s.%s\", token, name, VOLTZ_MODULE_EXT);\n printf(\"%s\\n\", buf);\n \n void* lib = dlopen(buf, RTLD_LOCAL | RTLD_NODELETE | RTLD_FIRST);\n \n if (!lib) {\n continue;\n }\n \n bool(*initfn)() = (bool(*)()) dlsym(lib, \"VoltzInitializeModule\");\n bool initrv = initfn();\n \n free(str);\n free((void*) vz_path);\n return initrv;\n }\n \n free(str);\n free((void*) vz_path);\n\n return true;\n}\n\nbool(*vz_load_module)(const char*) = vz_load_moduleI;<commit_msg>Fix another travis-ci error<commit_after>\/\/ Copyright (C) 2015 Jack Maloney. All Rights Reserved.\n\/\/\n\/\/ This Source Code Form is subject to the terms of the Mozilla Public License,\n\/\/ v. 2.0. If a copy of the MPL was not distributed with this file, You can\n\/\/ obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n\n#include \"voltz-internal.h\"\n#include <cstdlib>\n#include <cstdio>\n#include <dlfcn.h>\n#include <cstring>\n\nbool vz_load_moduleI(const char* name) {\n \n const char* vz_path = getenv(VOLTZ_PATH_ENVVAR);\n if (!vz_path) {\n const char* home = getenv(\"HOME\");\n vz_path = \"\/voltz\/modules\/:\/opt\/voltz\/modules\/\";\n char buf[strlen(home) + strlen(vz_path) + 2];\n sprintf(buf, \"%s%s\", home, vz_path);\n vz_path = strdup(buf);\n } else {\n vz_path = strdup(vz_path);\n }\n \n char* str = strdup(vz_path);\n char* token;\n while ((token = strsep(&str, \":\")) != NULL) {\n \n char buf[strlen(token) + strlen(name) + strlen(VOLTZ_MODULE_EXT) + 3];\n sprintf(buf, \"%s\/%s.%s\", token, name, VOLTZ_MODULE_EXT);\n printf(\"%s\\n\", buf);\n \n void* lib = dlopen(buf, RTLD_LOCAL | RTLD_NODELETE);\n \n if (!lib) {\n continue;\n }\n \n bool(*initfn)() = (bool(*)()) dlsym(lib, \"VoltzInitializeModule\");\n bool initrv = initfn();\n \n free(str);\n free((void*) vz_path);\n return initrv;\n }\n \n free(str);\n free((void*) vz_path);\n\n return true;\n}\n\nbool(*vz_load_module)(const char*) = vz_load_moduleI;<|endoftext|>"} {"text":"<commit_before>\/*\n Copyright 2011 Joe Hermaszewski. All rights reserved.\n\n Redistribution and use in source and binary forms, with or without modification, are\n permitted provided that the following conditions are met:\n\n 1. Redistributions of source code must retain the above copyright notice, this list of\n conditions and the following disclaimer.\n\n 2. Redistributions in binary form must reproduce the above copyright notice, this list\n of conditions and the following disclaimer in the documentation and\/or other materials\n provided with the distribution.\n\n THIS SOFTWARE IS PROVIDED BY JOE HERMASZEWSKI \"AS IS\" AND ANY EXPRESS OR IMPLIED\n WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND\n FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JOE HERMASZEWSKI OR\n CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON\n ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF\n ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n The views and conclusions contained in the software and documentation are those of the\n authors and should not be interpreted as representing official policies, either expressed\n or implied, of Joe Hermaszewski.\n*\/\n\n#pragma once\n\n#include <string>\n#include <memory>\n#include <vector>\n\n#include <llvm\/Support\/IRBuilder.h>\n\nnamespace llvm\n{\n class ExecutionEngine;\n class LLVMContext;\n class Module;\n}\n\nnamespace JoeLang\n{\n\nclass Context;\nclass StateBase;\nclass StateAssignmentBase;\nclass Technique;\n\nenum class Type;\n\nnamespace Parser\n{\n\nclass DeclarationBase;\nclass Expression;\nclass TechniqueDeclaration;\nclass TranslationUnit;\n\nclass CodeGenerator\n{\npublic:\n \/\/ http:\/\/gcc.gnu.org\/bugzilla\/show_bug.cgi?id=52591\n CodeGenerator( const Context& context, std::vector<Technique>& techniques );\n ~CodeGenerator();\n\n bool GenerateCode( const std::unique_ptr<TranslationUnit>& ast,\n std::vector<Technique>& techniques,\n std::unique_ptr<llvm::ExecutionEngine>& llvm_execution_engine );\n\n\n void Visit( DeclarationBase& p );\n void Visit( TechniqueDeclaration& t );\n\n std::unique_ptr<StateAssignmentBase> GenerateStateAssignment( const StateBase& state,\n const Expression& expression ) ;\n\n void Error( const std::string& message );\n\n \/\/ Cast Operators\n llvm::Value* CreateCast( const Expression& e, Type type );\n\n \/\/ Unary Operators\n llvm::Value* CreateNeg( const Expression& e );\n llvm::Value* CreateNot( const Expression& e );\n llvm::Value* CreateLNot( const Expression& e );\n\n \/\/ Binary Operators\n llvm::Value* CreateLOr( const Expression& l, const Expression& r );\n llvm::Value* CreateLAnd( const Expression& l, const Expression& r );\n llvm::Value* CreateOr( const Expression& l, const Expression& r );\n llvm::Value* CreateXor( const Expression& l, const Expression& r );\n llvm::Value* CreateAnd( const Expression& l, const Expression& r );\n llvm::Value* CreateEq( const Expression& l, const Expression& r );\n llvm::Value* CreateNeq( const Expression& l, const Expression& r );\n llvm::Value* CreateLT( const Expression& l, const Expression& r );\n llvm::Value* CreateGT( const Expression& l, const Expression& r );\n llvm::Value* CreateLTE( const Expression& l, const Expression& r );\n llvm::Value* CreateGTE( const Expression& l, const Expression& r );\n llvm::Value* CreateShl( const Expression& l, const Expression& r );\n llvm::Value* CreateShr( const Expression& l, const Expression& r );\n llvm::Value* CreateAdd( const Expression& l, const Expression& r );\n llvm::Value* CreateSub( const Expression& l, const Expression& r );\n llvm::Value* CreateMul( const Expression& l, const Expression& r );\n llvm::Value* CreateDiv( const Expression& l, const Expression& r );\n llvm::Value* CreateMod( const Expression& l, const Expression& r );\n\n \/\/ Ternary Operators\n llvm::Value* CreateSelect( const Expression& condition,\n const Expression& true_expression,\n const Expression& false_expression );\n\n \/\/ Getters\n bool Good() const;\n llvm::LLVMContext& GetLLVMContext() const;\n\nprivate:\n const Context& m_context;\n\n bool m_good = true;\n\n std::vector<Technique>& m_techniques;\n\n llvm::LLVMContext& m_llvmContext;\n llvm::Module* m_llvmModule;\n llvm::IRBuilder<> m_llvmBuilder;\n std::unique_ptr<llvm::ExecutionEngine> m_llvmExecutionEngine;\n};\n\n} \/\/ namespace Parser\n} \/\/ namespace JoeLang\n<commit_msg>[~] comments<commit_after>\/*\n Copyright 2011 Joe Hermaszewski. All rights reserved.\n\n Redistribution and use in source and binary forms, with or without modification, are\n permitted provided that the following conditions are met:\n\n 1. Redistributions of source code must retain the above copyright notice, this list of\n conditions and the following disclaimer.\n\n 2. Redistributions in binary form must reproduce the above copyright notice, this list\n of conditions and the following disclaimer in the documentation and\/or other materials\n provided with the distribution.\n\n THIS SOFTWARE IS PROVIDED BY JOE HERMASZEWSKI \"AS IS\" AND ANY EXPRESS OR IMPLIED\n WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND\n FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JOE HERMASZEWSKI OR\n CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON\n ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF\n ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n The views and conclusions contained in the software and documentation are those of the\n authors and should not be interpreted as representing official policies, either expressed\n or implied, of Joe Hermaszewski.\n*\/\n\n#pragma once\n\n#include <string>\n#include <memory>\n#include <vector>\n\n#include <llvm\/Support\/IRBuilder.h>\n\nnamespace llvm\n{\n class ExecutionEngine;\n class LLVMContext;\n class Module;\n}\n\nnamespace JoeLang\n{\n\nclass Context;\nclass StateBase;\nclass StateAssignmentBase;\nclass Technique;\n\nenum class Type;\n\nnamespace Parser\n{\n\nclass DeclarationBase;\nclass Expression;\nclass TechniqueDeclaration;\nclass TranslationUnit;\n\nclass CodeGenerator\n{\npublic:\n \/\/ Passing techniques in here because of this bug\n \/\/ http:\/\/gcc.gnu.org\/bugzilla\/show_bug.cgi?id=52591\n CodeGenerator( const Context& context, std::vector<Technique>& techniques );\n ~CodeGenerator();\n\n bool GenerateCode( const std::unique_ptr<TranslationUnit>& ast,\n std::vector<Technique>& techniques,\n std::unique_ptr<llvm::ExecutionEngine>& llvm_execution_engine );\n\n\n void Visit( DeclarationBase& p );\n void Visit( TechniqueDeclaration& t );\n\n std::unique_ptr<StateAssignmentBase> GenerateStateAssignment( const StateBase& state,\n const Expression& expression ) ;\n\n void Error( const std::string& message );\n\n \/\/ Cast Operators\n llvm::Value* CreateCast( const Expression& e, Type type );\n\n \/\/ Unary Operators\n llvm::Value* CreateNeg( const Expression& e );\n llvm::Value* CreateNot( const Expression& e );\n llvm::Value* CreateLNot( const Expression& e );\n\n \/\/ Binary Operators\n llvm::Value* CreateLOr( const Expression& l, const Expression& r );\n llvm::Value* CreateLAnd( const Expression& l, const Expression& r );\n llvm::Value* CreateOr( const Expression& l, const Expression& r );\n llvm::Value* CreateXor( const Expression& l, const Expression& r );\n llvm::Value* CreateAnd( const Expression& l, const Expression& r );\n llvm::Value* CreateEq( const Expression& l, const Expression& r );\n llvm::Value* CreateNeq( const Expression& l, const Expression& r );\n llvm::Value* CreateLT( const Expression& l, const Expression& r );\n llvm::Value* CreateGT( const Expression& l, const Expression& r );\n llvm::Value* CreateLTE( const Expression& l, const Expression& r );\n llvm::Value* CreateGTE( const Expression& l, const Expression& r );\n llvm::Value* CreateShl( const Expression& l, const Expression& r );\n llvm::Value* CreateShr( const Expression& l, const Expression& r );\n llvm::Value* CreateAdd( const Expression& l, const Expression& r );\n llvm::Value* CreateSub( const Expression& l, const Expression& r );\n llvm::Value* CreateMul( const Expression& l, const Expression& r );\n llvm::Value* CreateDiv( const Expression& l, const Expression& r );\n llvm::Value* CreateMod( const Expression& l, const Expression& r );\n\n \/\/ Ternary Operators\n llvm::Value* CreateSelect( const Expression& condition,\n const Expression& true_expression,\n const Expression& false_expression );\n\n \/\/ Getters\n bool Good() const;\n llvm::LLVMContext& GetLLVMContext() const;\n\nprivate:\n const Context& m_context;\n\n bool m_good = true;\n\n std::vector<Technique>& m_techniques;\n\n llvm::LLVMContext& m_llvmContext;\n llvm::Module* m_llvmModule;\n llvm::IRBuilder<> m_llvmBuilder;\n std::unique_ptr<llvm::ExecutionEngine> m_llvmExecutionEngine;\n};\n\n} \/\/ namespace Parser\n} \/\/ namespace JoeLang\n<|endoftext|>"} {"text":"<commit_before>\/\/ ==========================================================================\n\/\/ bam_stats\n\/\/ ==========================================================================\n\/\/ Copyright (c) 2006-2010, Knut Reinert, FU Berlin\n\/\/ All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright\n\/\/ notice, this list of conditions and the following disclaimer.\n\/\/ * Redistributions in binary form must reproduce the above copyright\n\/\/ notice, this list of conditions and the following disclaimer in the\n\/\/ documentation and\/or other materials provided with the distribution.\n\/\/ * Neither the name of Knut Reinert or the FU Berlin nor the names of\n\/\/ its contributors may be used to endorse or promote products derived\n\/\/ from this software without specific prior written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n\/\/ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\/\/ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\/\/ ARE DISCLAIMED. IN NO EVENT SHALL KNUT REINERT OR THE FU BERLIN BE LIABLE\n\/\/ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n\/\/ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n\/\/ SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n\/\/ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n\/\/ LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n\/\/ OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH\n\/\/ DAMAGE.\n\/\/\n\/\/ ==========================================================================\n\/\/ Author: Manuel Holtgrewe <manuel.holtgrewe@fu-berlin.de>\n\/\/ ==========================================================================\n\/\/ Read a BAM file and collect statistics on the alignments therein.\n\/\/ ==========================================================================\n\n#include <iostream>\n\n#include <seqan\/basic.h>\n#include <seqan\/sequence.h>\n#include <seqan\/file.h> \/\/ For printing SeqAn Strings.\n\n#include <seqan\/stream.h>\n#include <seqan\/bam_io.h>\n#include <seqan\/misc\/misc_cmdparser.h>\n\n#if SEQAN_HAS_ZLIB\n\nusing namespace seqan;\n\nenum Format\n{\n FORMAT_AUTO,\n FORMAT_SAM,\n FORMAT_BAM\n};\n\nstruct Options\n{\n bool showHelp;\n bool showVersion;\n unsigned verbosity;\n CharString refFile;\n CharString inFile;\n Format inFormat;\n\n Options()\n {\n showHelp = false;\n showVersion = false;\n verbosity = 1;\n inFormat = FORMAT_AUTO;\n }\n};\n\nvoid\nsetupCommandLineParser(CommandLineParser & parser, Options const & options)\n{\n addVersionLine(parser, \"1.0\");\n \n addTitleLine(parser, \"*************\");\n addTitleLine(parser, \"* bam_stats *\");\n addTitleLine(parser, \"*************\");\n addTitleLine(parser, \"\");\n addTitleLine(parser, \"BAM Statistics.\");\n addTitleLine(parser, \"\");\n addTitleLine(parser, \"Author: Manuel Holtgrewe <manuel.holtgrewe@fu-berlin.de>\");\n\n addUsageLine(parser, \"bam_stats [OPTIONS] REF.fasta ALIGN.bam\");\n \n\taddSection(parser, \"General Options\");\n addOption(parser, CommandLineOption(\"v\", \"verbose\", \"Enable verbose mode (show steps).\", OptionType::Bool));\n addOption(parser, CommandLineOption(\"vv\", \"very-verbose\", \"Enable very verbose mode (show SAM lines and actual aligments).\", OptionType::Bool));\n\n\taddSection(parser, \"Input Specification\");\n addOption(parser, CommandLineOption(\"i\", \"input-file\", \"Path to input, '-' for stdin.\", OptionType::String, options.inFile));\n addOption(parser, CommandLineOption(\"S\", \"input-sam\", \"Input file is SAM (default: auto).\", OptionType::Bool, options.inFormat == FORMAT_SAM));\n addOption(parser, CommandLineOption(\"B\", \"input-bam\", \"Input file is BAM (default: auto).\", OptionType::Bool, options.inFormat == FORMAT_BAM));\n\n requiredArguments(parser, 2);\n}\n\nint parseCommandLineAndCheck(Options & options,\n CommandLineParser & parser,\n int argc,\n char const ** argv)\n{\n bool stop = !parse(parser, argc, argv);\n if (stop)\n return 1;\n if (isSetLong(parser, \"help\"))\n {\n options.showHelp = true;\n return 0;\n }\n if (isSetLong(parser, \"version\"))\n {\n options.showVersion = true;\n return 0;\n }\n\n if (isSetLong(parser, \"verbose\"))\n options.verbosity = 2;\n if (isSetLong(parser, \"very-verbose\"))\n options.verbosity = 3;\n\n getOptionValueLong(parser, \"input-file\", options.inFile);\n if (isSetLong(parser, \"input-sam\"))\n options.inFormat = FORMAT_SAM;\n if (isSetLong(parser, \"input-bam\"))\n options.inFormat = FORMAT_BAM;\n\n options.refFile = getArgumentValue(parser, 0);\n options.inFile = getArgumentValue(parser, 1);\n\n\treturn 0;\n}\n\nstruct Stats\n{\n __uint64 numRecords;\n __uint64 alignedRecords;\n String<unsigned> editDistanceHisto;\n String<unsigned> mismatchHisto;\n String<unsigned> insertHisto;\n String<unsigned> deletionHisto;\n\n Stats() : numRecords(0), alignedRecords(0)\n {}\n};\n\ntemplate <typename TStreamOrReader, typename TSeqString, typename TSpec, typename TFormat>\nint doWork(TStreamOrReader & reader, StringSet<TSeqString, TSpec> & seqs, Options const & options, TFormat const & tag)\n{\n StringSet<CharString> refNames;\n NameStoreCache<StringSet<CharString> > refNamesCache(refNames);\n BamIOContext<StringSet<CharString> > context(refNames, refNamesCache);\n\n \/\/ Read header.\n BamHeader header;\n if (options.verbosity >= 2)\n std::cerr << \"Reading header\" << std::endl;\n if (readRecord(header, context, reader, tag) != 0)\n {\n std::cerr << \"Could not read header!\" << std::endl;\n return 1;\n }\n\n Stats stats;\n\n \/\/ Read alignments.\n BamAlignmentRecord record;\n if (options.verbosity >= 2)\n std::cerr << \"Reading alignments\" << std::endl;\n Align<Dna5String> align;\n while (!atEnd(reader))\n {\n \/\/ Read alignment record.\n if (readRecord(record, context, reader, tag) != 0)\n {\n std::cerr << \"Could not read alignment!\" << std::endl;\n return 1;\n }\n if (options.verbosity >= 3)\n write2(std::cerr, record, context, Sam());\n\n \/\/ Now, do something with it ;)\n stats.numRecords += 1; \/\/ One more record.\n stats.alignedRecords += !hasFlagUnmapped(record);\n \/\/ Compute alignment.\n if (record.rId != -1 && record.rId < static_cast<int>(length(seqs)))\n {\n bamRecordToAlignment(align, seqs[record.rId], record);\n if (options.verbosity >= 3)\n std::cerr << align << std::endl;\n typedef Align<Dna5String> TAlign;\n typedef typename Row<TAlign>::Type TRow;\n typedef typename Iterator<TRow>::Type TRowIter;\n unsigned editDistance = 0;\n unsigned posRead = 0;\n for (TRowIter it0 = begin(row(align, 0)), it1 = begin(row(align, 1)); !atEnd(it0); goNext(it0), goNext(it1))\n {\n if (isGap(it0) && isGap(it1))\n continue;\n if (isGap(it0) || isGap(it1))\n {\n if (isGap(it0))\n {\n unsigned len = length(stats.insertHisto);\n resize(stats.insertHisto, std::max(len, posRead + 1), 0);\n stats.insertHisto[posRead] += 1;\n posRead += 1;\n }\n else\n {\n unsigned len = length(stats.deletionHisto);\n resize(stats.deletionHisto, std::max(len, posRead + 1), 0);\n stats.deletionHisto[posRead] += 1;\n }\n editDistance += 1;\n continue;\n }\n if (*it0 != *it1)\n {\n unsigned len = length(stats.mismatchHisto);\n resize(stats.mismatchHisto, std::max(len, posRead + 1), 0);\n stats.mismatchHisto[posRead] += 1;\n editDistance += 1;\n }\n posRead += 1;\n }\n if (options.verbosity >= 3)\n std::cerr << \"edit distance: \" << editDistance << std::endl;\n unsigned len = length(stats.editDistanceHisto);\n resize(stats.editDistanceHisto, std::max(len, editDistance + 1), 0);\n stats.editDistanceHisto[editDistance] += 1;\n }\n }\n\n \/\/ Print results.\n std::cerr << \"RESULTS\\n\\n\";\n std::cerr << \"num records \\t\" << stats.numRecords << std::endl;\n std::cerr << \"aligned records \\t\" << stats.alignedRecords << std::endl;\n std::cerr << \"aligned record %\\t\" << 100.0 * stats.alignedRecords \/ stats.numRecords << std::endl;\n std::cerr << \"distance histogram\" << std::endl;\n for (unsigned i = 0; i < length(stats.editDistanceHisto); ++i)\n std::cerr << \" \" << i << \"\\t\" << stats.editDistanceHisto[i] << std::endl;\n std::cerr << \"mismatch histogram\" << std::endl;\n for (unsigned i = 0; i < length(stats.mismatchHisto); ++i)\n std::cerr << \" \" << i << \"\\t\" << stats.mismatchHisto[i] << std::endl;\n std::cerr << \"insertion histogram\" << std::endl;\n for (unsigned i = 0; i < length(stats.insertHisto); ++i)\n std::cerr << \" \" << i << \"\\t\" << stats.insertHisto[i] << std::endl;\n std::cerr << \"deletion histogram\" << std::endl;\n for (unsigned i = 0; i < length(stats.deletionHisto); ++i)\n std::cerr << \" \" << i << \"\\t\" << stats.deletionHisto[i] << std::endl;\n \n return 0;\n}\n\nint main(int argc, char const ** argv)\n{\n using namespace seqan;\n\n \/\/ -----------------------------------------------------------------------\n \/\/ Handle Command Line\n \/\/ -----------------------------------------------------------------------\n\n \/\/ Setup command line parser.\n CommandLineParser parser;\n Options options;\n setupCommandLineParser(parser, options);\n \n \/\/ Then, parse the command line and handle the cases where help display\n \/\/ is requested or erroneous parameters were given.\n int res = parseCommandLineAndCheck(options, parser, argc, argv);\n if (res != 0)\n return 1;\n if (options.showHelp || options.showVersion)\n return 0;\n\n \/\/ -----------------------------------------------------------------------\n \/\/ Guess format.\n \/\/ -----------------------------------------------------------------------\n\n if (options.inFormat == FORMAT_AUTO)\n {\n std::ifstream guessIn(toCString(options.inFile), std::ios::binary | std::ios::in);\n if (!guessIn.good())\n {\n std::cerr << \"Could not open \" << options.inFile << std::endl;\n return 1;\n }\n CharString magic;\n resize(magic, 2);\n guessIn.read(&magic[0], 2);\n if (magic != \"\\x1f\\x8b\") \/\/ Is not gzip-compressed.\n options.inFormat = FORMAT_SAM;\n else\n options.inFormat = FORMAT_BAM;\n }\n\n \/\/ -----------------------------------------------------------------------\n \/\/ Do Work.\n \/\/ -----------------------------------------------------------------------\n\n \/\/ Read reference.\n if (options.verbosity >= 2)\n std::cerr << \"Reading references from \" << options.refFile << std::endl;\n StringSet<CharString> seqIds;\n StringSet<Dna5String> seqs;\n String<char, MMap<> > seqMMapString;\n if (!open(seqMMapString, toCString(options.refFile), OPEN_RDONLY))\n {\n std::cerr << \"Could not open \" << options.refFile << std::endl;\n return 1;\n }\n RecordReader<String<char, MMap<> >, DoublePass<Mapped> > refReader(seqMMapString);\n if (read2(seqIds, seqs, refReader, Fasta()) != 0)\n {\n std::cerr << \"Could not read reference from \" << options.refFile << std::endl;\n return 1;\n }\n\n \/\/ Open SAM\/BAM file and do work.\n if (options.inFormat == FORMAT_SAM)\n {\n if (options.verbosity >= 2)\n std::cerr << \"Opening SAM file \" << options.inFile << std::endl;\n String<char, MMap<> > samMMapString;\n if (!open(samMMapString, toCString(options.inFile), OPEN_RDONLY))\n {\n std::cerr << \"Could not open \" << options.inFile << std::endl;\n return 1;\n }\n RecordReader<String<char, MMap<> >, SinglePass<Mapped> > samReader(samMMapString);\n return doWork(samReader, seqs, options, Sam());\n }\n else \/\/ options.inFormat == FORMAT_BAM\n {\n if (options.verbosity >= 2)\n std::cerr << \"Opening BAM file \" << options.inFile << std::endl;\n Stream<Bgzf> bamStream;\n if (!open(bamStream, toCString(options.inFile), \"r\"))\n {\n std::cerr << \"Could not open \" << options.inFile << std::endl;\n return 1;\n }\n return doWork(bamStream, seqs, options, Bam());\n }\n\n return 0;\n}\n\n#else\n\nint main(int argc, char const ** argv)\n{\n std::cerr << \"bam_stats can only be compiled correctly with zlib.\" << std::endl;\n return 0;\n}\n\n#endif \/\/ #if SEQAN_HAS_ZLIB\n<commit_msg>Removed unused parameter warning in bam_stats.cpp.<commit_after>\/\/ ==========================================================================\n\/\/ bam_stats\n\/\/ ==========================================================================\n\/\/ Copyright (c) 2006-2010, Knut Reinert, FU Berlin\n\/\/ All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright\n\/\/ notice, this list of conditions and the following disclaimer.\n\/\/ * Redistributions in binary form must reproduce the above copyright\n\/\/ notice, this list of conditions and the following disclaimer in the\n\/\/ documentation and\/or other materials provided with the distribution.\n\/\/ * Neither the name of Knut Reinert or the FU Berlin nor the names of\n\/\/ its contributors may be used to endorse or promote products derived\n\/\/ from this software without specific prior written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n\/\/ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\/\/ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\/\/ ARE DISCLAIMED. IN NO EVENT SHALL KNUT REINERT OR THE FU BERLIN BE LIABLE\n\/\/ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n\/\/ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n\/\/ SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n\/\/ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n\/\/ LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n\/\/ OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH\n\/\/ DAMAGE.\n\/\/\n\/\/ ==========================================================================\n\/\/ Author: Manuel Holtgrewe <manuel.holtgrewe@fu-berlin.de>\n\/\/ ==========================================================================\n\/\/ Read a BAM file and collect statistics on the alignments therein.\n\/\/ ==========================================================================\n\n#include <iostream>\n\n#include <seqan\/basic.h>\n#include <seqan\/sequence.h>\n#include <seqan\/file.h> \/\/ For printing SeqAn Strings.\n\n#include <seqan\/stream.h>\n#include <seqan\/bam_io.h>\n#include <seqan\/misc\/misc_cmdparser.h>\n\n#if SEQAN_HAS_ZLIB\n\nusing namespace seqan;\n\nenum Format\n{\n FORMAT_AUTO,\n FORMAT_SAM,\n FORMAT_BAM\n};\n\nstruct Options\n{\n bool showHelp;\n bool showVersion;\n unsigned verbosity;\n CharString refFile;\n CharString inFile;\n Format inFormat;\n\n Options()\n {\n showHelp = false;\n showVersion = false;\n verbosity = 1;\n inFormat = FORMAT_AUTO;\n }\n};\n\nvoid\nsetupCommandLineParser(CommandLineParser & parser, Options const & options)\n{\n addVersionLine(parser, \"1.0\");\n \n addTitleLine(parser, \"*************\");\n addTitleLine(parser, \"* bam_stats *\");\n addTitleLine(parser, \"*************\");\n addTitleLine(parser, \"\");\n addTitleLine(parser, \"BAM Statistics.\");\n addTitleLine(parser, \"\");\n addTitleLine(parser, \"Author: Manuel Holtgrewe <manuel.holtgrewe@fu-berlin.de>\");\n\n addUsageLine(parser, \"bam_stats [OPTIONS] REF.fasta ALIGN.bam\");\n \n\taddSection(parser, \"General Options\");\n addOption(parser, CommandLineOption(\"v\", \"verbose\", \"Enable verbose mode (show steps).\", OptionType::Bool));\n addOption(parser, CommandLineOption(\"vv\", \"very-verbose\", \"Enable very verbose mode (show SAM lines and actual aligments).\", OptionType::Bool));\n\n\taddSection(parser, \"Input Specification\");\n addOption(parser, CommandLineOption(\"i\", \"input-file\", \"Path to input, '-' for stdin.\", OptionType::String, options.inFile));\n addOption(parser, CommandLineOption(\"S\", \"input-sam\", \"Input file is SAM (default: auto).\", OptionType::Bool, options.inFormat == FORMAT_SAM));\n addOption(parser, CommandLineOption(\"B\", \"input-bam\", \"Input file is BAM (default: auto).\", OptionType::Bool, options.inFormat == FORMAT_BAM));\n\n requiredArguments(parser, 2);\n}\n\nint parseCommandLineAndCheck(Options & options,\n CommandLineParser & parser,\n int argc,\n char const ** argv)\n{\n bool stop = !parse(parser, argc, argv);\n if (stop)\n return 1;\n if (isSetLong(parser, \"help\"))\n {\n options.showHelp = true;\n return 0;\n }\n if (isSetLong(parser, \"version\"))\n {\n options.showVersion = true;\n return 0;\n }\n\n if (isSetLong(parser, \"verbose\"))\n options.verbosity = 2;\n if (isSetLong(parser, \"very-verbose\"))\n options.verbosity = 3;\n\n getOptionValueLong(parser, \"input-file\", options.inFile);\n if (isSetLong(parser, \"input-sam\"))\n options.inFormat = FORMAT_SAM;\n if (isSetLong(parser, \"input-bam\"))\n options.inFormat = FORMAT_BAM;\n\n options.refFile = getArgumentValue(parser, 0);\n options.inFile = getArgumentValue(parser, 1);\n\n\treturn 0;\n}\n\nstruct Stats\n{\n __uint64 numRecords;\n __uint64 alignedRecords;\n String<unsigned> editDistanceHisto;\n String<unsigned> mismatchHisto;\n String<unsigned> insertHisto;\n String<unsigned> deletionHisto;\n\n Stats() : numRecords(0), alignedRecords(0)\n {}\n};\n\ntemplate <typename TStreamOrReader, typename TSeqString, typename TSpec, typename TFormat>\nint doWork(TStreamOrReader & reader, StringSet<TSeqString, TSpec> & seqs, Options const & options, TFormat const & tag)\n{\n StringSet<CharString> refNames;\n NameStoreCache<StringSet<CharString> > refNamesCache(refNames);\n BamIOContext<StringSet<CharString> > context(refNames, refNamesCache);\n\n \/\/ Read header.\n BamHeader header;\n if (options.verbosity >= 2)\n std::cerr << \"Reading header\" << std::endl;\n if (readRecord(header, context, reader, tag) != 0)\n {\n std::cerr << \"Could not read header!\" << std::endl;\n return 1;\n }\n\n Stats stats;\n\n \/\/ Read alignments.\n BamAlignmentRecord record;\n if (options.verbosity >= 2)\n std::cerr << \"Reading alignments\" << std::endl;\n Align<Dna5String> align;\n while (!atEnd(reader))\n {\n \/\/ Read alignment record.\n if (readRecord(record, context, reader, tag) != 0)\n {\n std::cerr << \"Could not read alignment!\" << std::endl;\n return 1;\n }\n if (options.verbosity >= 3)\n write2(std::cerr, record, context, Sam());\n\n \/\/ Now, do something with it ;)\n stats.numRecords += 1; \/\/ One more record.\n stats.alignedRecords += !hasFlagUnmapped(record);\n \/\/ Compute alignment.\n if (record.rId != -1 && record.rId < static_cast<int>(length(seqs)))\n {\n bamRecordToAlignment(align, seqs[record.rId], record);\n if (options.verbosity >= 3)\n std::cerr << align << std::endl;\n typedef Align<Dna5String> TAlign;\n typedef typename Row<TAlign>::Type TRow;\n typedef typename Iterator<TRow>::Type TRowIter;\n unsigned editDistance = 0;\n unsigned posRead = 0;\n for (TRowIter it0 = begin(row(align, 0)), it1 = begin(row(align, 1)); !atEnd(it0); goNext(it0), goNext(it1))\n {\n if (isGap(it0) && isGap(it1))\n continue;\n if (isGap(it0) || isGap(it1))\n {\n if (isGap(it0))\n {\n unsigned len = length(stats.insertHisto);\n resize(stats.insertHisto, std::max(len, posRead + 1), 0);\n stats.insertHisto[posRead] += 1;\n posRead += 1;\n }\n else\n {\n unsigned len = length(stats.deletionHisto);\n resize(stats.deletionHisto, std::max(len, posRead + 1), 0);\n stats.deletionHisto[posRead] += 1;\n }\n editDistance += 1;\n continue;\n }\n if (*it0 != *it1)\n {\n unsigned len = length(stats.mismatchHisto);\n resize(stats.mismatchHisto, std::max(len, posRead + 1), 0);\n stats.mismatchHisto[posRead] += 1;\n editDistance += 1;\n }\n posRead += 1;\n }\n if (options.verbosity >= 3)\n std::cerr << \"edit distance: \" << editDistance << std::endl;\n unsigned len = length(stats.editDistanceHisto);\n resize(stats.editDistanceHisto, std::max(len, editDistance + 1), 0);\n stats.editDistanceHisto[editDistance] += 1;\n }\n }\n\n \/\/ Print results.\n std::cerr << \"RESULTS\\n\\n\";\n std::cerr << \"num records \\t\" << stats.numRecords << std::endl;\n std::cerr << \"aligned records \\t\" << stats.alignedRecords << std::endl;\n std::cerr << \"aligned record %\\t\" << 100.0 * stats.alignedRecords \/ stats.numRecords << std::endl;\n std::cerr << \"distance histogram\" << std::endl;\n for (unsigned i = 0; i < length(stats.editDistanceHisto); ++i)\n std::cerr << \" \" << i << \"\\t\" << stats.editDistanceHisto[i] << std::endl;\n std::cerr << \"mismatch histogram\" << std::endl;\n for (unsigned i = 0; i < length(stats.mismatchHisto); ++i)\n std::cerr << \" \" << i << \"\\t\" << stats.mismatchHisto[i] << std::endl;\n std::cerr << \"insertion histogram\" << std::endl;\n for (unsigned i = 0; i < length(stats.insertHisto); ++i)\n std::cerr << \" \" << i << \"\\t\" << stats.insertHisto[i] << std::endl;\n std::cerr << \"deletion histogram\" << std::endl;\n for (unsigned i = 0; i < length(stats.deletionHisto); ++i)\n std::cerr << \" \" << i << \"\\t\" << stats.deletionHisto[i] << std::endl;\n \n return 0;\n}\n\nint main(int argc, char const ** argv)\n{\n using namespace seqan;\n\n \/\/ -----------------------------------------------------------------------\n \/\/ Handle Command Line\n \/\/ -----------------------------------------------------------------------\n\n \/\/ Setup command line parser.\n CommandLineParser parser;\n Options options;\n setupCommandLineParser(parser, options);\n \n \/\/ Then, parse the command line and handle the cases where help display\n \/\/ is requested or erroneous parameters were given.\n int res = parseCommandLineAndCheck(options, parser, argc, argv);\n if (res != 0)\n return 1;\n if (options.showHelp || options.showVersion)\n return 0;\n\n \/\/ -----------------------------------------------------------------------\n \/\/ Guess format.\n \/\/ -----------------------------------------------------------------------\n\n if (options.inFormat == FORMAT_AUTO)\n {\n std::ifstream guessIn(toCString(options.inFile), std::ios::binary | std::ios::in);\n if (!guessIn.good())\n {\n std::cerr << \"Could not open \" << options.inFile << std::endl;\n return 1;\n }\n CharString magic;\n resize(magic, 2);\n guessIn.read(&magic[0], 2);\n if (magic != \"\\x1f\\x8b\") \/\/ Is not gzip-compressed.\n options.inFormat = FORMAT_SAM;\n else\n options.inFormat = FORMAT_BAM;\n }\n\n \/\/ -----------------------------------------------------------------------\n \/\/ Do Work.\n \/\/ -----------------------------------------------------------------------\n\n \/\/ Read reference.\n if (options.verbosity >= 2)\n std::cerr << \"Reading references from \" << options.refFile << std::endl;\n StringSet<CharString> seqIds;\n StringSet<Dna5String> seqs;\n String<char, MMap<> > seqMMapString;\n if (!open(seqMMapString, toCString(options.refFile), OPEN_RDONLY))\n {\n std::cerr << \"Could not open \" << options.refFile << std::endl;\n return 1;\n }\n RecordReader<String<char, MMap<> >, DoublePass<Mapped> > refReader(seqMMapString);\n if (read2(seqIds, seqs, refReader, Fasta()) != 0)\n {\n std::cerr << \"Could not read reference from \" << options.refFile << std::endl;\n return 1;\n }\n\n \/\/ Open SAM\/BAM file and do work.\n if (options.inFormat == FORMAT_SAM)\n {\n if (options.verbosity >= 2)\n std::cerr << \"Opening SAM file \" << options.inFile << std::endl;\n String<char, MMap<> > samMMapString;\n if (!open(samMMapString, toCString(options.inFile), OPEN_RDONLY))\n {\n std::cerr << \"Could not open \" << options.inFile << std::endl;\n return 1;\n }\n RecordReader<String<char, MMap<> >, SinglePass<Mapped> > samReader(samMMapString);\n return doWork(samReader, seqs, options, Sam());\n }\n else \/\/ options.inFormat == FORMAT_BAM\n {\n if (options.verbosity >= 2)\n std::cerr << \"Opening BAM file \" << options.inFile << std::endl;\n Stream<Bgzf> bamStream;\n if (!open(bamStream, toCString(options.inFile), \"r\"))\n {\n std::cerr << \"Could not open \" << options.inFile << std::endl;\n return 1;\n }\n return doWork(bamStream, seqs, options, Bam());\n }\n\n return 0;\n}\n\n#else\n\nint main(int, char const **)\n{\n std::cerr << \"bam_stats can only be compiled correctly with zlib.\" << std::endl;\n return 0;\n}\n\n#endif \/\/ #if SEQAN_HAS_ZLIB\n<|endoftext|>"} {"text":"<commit_before>#pragma once\n\n\/\/! The shape function (on the reference element) for LINEAR FEM.\n\/\/!\n\/\/! We have three shape functions.\n\/\/!\n\/\/! lambda(0, x, y) should be 1 in the point (0,0) and zero in (1,0) and (0,1)\n\/\/! lambda(1, x, y) should be 1 in the point (1,0) and zero in (0,0) and (0,1)\n\/\/! lambda(2, x, y) should be 1 in the point (0,1) and zero in (0,0) and (1,0)\n\/\/!\n\/\/! @param i integer between 0 and 2 (inclusive). Decides which shape function to return.\n\/\/! @param x x coordinate in the reference element.\n\/\/! @param y y coordinate in the reference element.\ninline double lambda(int i, double x, double y) {\n\tif (i == 0) {\n\t\treturn 1 - x - y;\n\t} else if (i == 1) {\n\t\treturn x;\n\t} else {\n\t\treturn y;\n\t}\n}\n\n\/\/----------------shapefunBegin----------------\n\/\/! The shape function (on the reference element) for QUADRATIC FEM\n\/\/!\n\/\/! We have six shape functions.\n\/\/!\n\/\/! shapefun(0, x, y) should be 1 in the point (0,0) and zero in the other 5\n\/\/! shapefun(1, x, y) should be 1 in the point (1,0) and zero in the other 5\n\/\/! shapefun(2, x, y) should be 1 in the point (0,1) and zero in the other 5\n\/\/! shapefun(3, x, y) should be 1 in the point (0.5,0) and zero in the other 5\n\/\/! shapefun(4, x, y) should be 1 in the point (0.5,0.5) and zero in the other 5\n\/\/! shapefun(5, x, y) should be 1 in the point (0,0.5) and zero in the other 5\n\/\/!\n\/\/! @param i integer between 0 and 5 (inclusive). Decides which shape function to return.\n\/\/! @param x x coordinate in the reference element.\n\/\/! @param y y coordinate in the reference element.\ninline double shapefun(int i, double x, double y) {\n\tdouble value = 0.0;\n\t\/\/ (write your solution here)\n\treturn value;\n}\n\/\/----------------shapefunEnd----------------\n<commit_msg>Solved series 3 problem 1b<commit_after>#pragma once\n#include <cassert>\n#include <stdexcept>\n\n\/\/! The shape function (on the reference element) for LINEAR FEM.\n\/\/!\n\/\/! We have three shape functions.\n\/\/!\n\/\/! lambda(0, x, y) should be 1 in the point (0,0) and zero in (1,0) and (0,1)\n\/\/! lambda(1, x, y) should be 1 in the point (1,0) and zero in (0,0) and (0,1)\n\/\/! lambda(2, x, y) should be 1 in the point (0,1) and zero in (0,0) and (1,0)\n\/\/!\n\/\/! @param i integer between 0 and 2 (inclusive). Decides which shape function to return.\n\/\/! @param x x coordinate in the reference element.\n\/\/! @param y y coordinate in the reference element.\ninline double lambda(int i, double x, double y) {\n\tif (i == 0) {\n\t\treturn 1 - x - y;\n\t} else if (i == 1) {\n\t\treturn x;\n\t} else {\n\t\treturn y;\n\t}\n}\n\n\/\/----------------shapefunBegin----------------\n\/\/! The shape function (on the reference element) for QUADRATIC FEM\n\/\/!\n\/\/! We have six shape functions.\n\/\/!\n\/\/! shapefun(0, x, y) should be 1 in the point (0,0) and zero in the other 5\n\/\/! shapefun(1, x, y) should be 1 in the point (1,0) and zero in the other 5\n\/\/! shapefun(2, x, y) should be 1 in the point (0,1) and zero in the other 5\n\/\/! shapefun(3, x, y) should be 1 in the point (0.5,0) and zero in the other 5\n\/\/! shapefun(4, x, y) should be 1 in the point (0.5,0.5) and zero in the other 5\n\/\/! shapefun(5, x, y) should be 1 in the point (0,0.5) and zero in the other 5\n\/\/!\n\/\/! @param i integer between 0 and 5 (inclusive). Decides which shape function to return.\n\/\/! @param x x coordinate in the reference element.\n\/\/! @param y y coordinate in the reference element.\ninline double shapefun(int i, double x, double y) {\n\t\/\/ double value = 0.0;\n\t\/\/ (write your solution here)\n\tassert(0 <= i && i <= 5);\n\tswitch (i) {\n\t\tcase 0:\n\t\t\treturn (2 * lambda(0, x, y) - 1) * lambda(0, x, y);\n\t\tcase 1:\n\t\t\treturn (2 * lambda(1, x, y) - 1) * lambda(1, x, y);\n\t\tcase 2:\n\t\t\treturn (2 * lambda(2, x, y) - 1) * lambda(2, x, y);\n\t\tcase 3:\n\t\t\treturn 4 * lambda(0, x, y) * lambda(1, x, y);\n\t\tcase 4:\n\t\t\treturn 4 * lambda(1, x, y) * lambda(2, x, y);\n\t\tcase 5:\n\t\t\treturn 4 * lambda(0, x, y) * lambda(2, x, y);\n\t\tdefault:\n\t\t\tthrow std::domain_error(\"i not in {0,1,2,3,4,5}\");\n\t}\n\t\/\/ return value;\n}\n\/\/----------------shapefunEnd----------------\n<|endoftext|>"} {"text":"<commit_before>#include \"scenewidget.h\"\n#include <QSurfaceFormat>\n#include <iostream>\n#include <fstream>\n#include <sstream>\n#include <stdexcept>\n#include <glm\/gtc\/type_ptr.hpp>\n#include <glm\/gtc\/matrix_transform.hpp>\n\nSceneWidget::SceneWidget(QWidget *parent) :\n QOpenGLWidget(parent), m_modelScale(1.0f, 1.0f, 1.0f)\n{\n \/\/ Set opengl version & profile\n QSurfaceFormat format;\n\n format.setRenderableType(QSurfaceFormat::OpenGL);\n format.setVersion(3, 2);\n format.setProfile(QSurfaceFormat::CoreProfile);\n format.setDepthBufferSize(24);\n format.setSamples(4);\n\n setFormat(format);\n}\n\nSceneWidget::~SceneWidget()\n{\n\n}\n\nvoid SceneWidget::initializeGL()\n{\n \/\/ Init opengl\n bool success = initializeOpenGLFunctions();\n\n \/\/ Check if opengl init was successfull\n if (!success)\n throw std::runtime_error(\"Could not load OpenGL functions.\\nDo you have OpenGL v3.2?\");\n\n \/\/ Print version info\n std::clog << \"OpenGL version: \" << glGetString(GL_VERSION) <<\n \"\\nGLSL version: \" << glGetString(GL_SHADING_LANGUAGE_VERSION) <<\n \"\\nRenderer: \" << glGetString(GL_RENDERER) <<\n \"\\nVendor: \" << glGetString(GL_VENDOR) << '\\n' << std::endl;\n\n glClearColor(1.0f, 1.0f, 1.0f, 1.0f);\n\n \/\/ Enable face culling\n glEnable(GL_CULL_FACE);\n glFrontFace(GL_CW);\n glCullFace(GL_BACK);\n\n initProgram();\n initData();\n}\n\nvoid SceneWidget::paintGL()\n{\n glClear(GL_COLOR_BUFFER_BIT);\n\n glUseProgram(m_program);\n glBindVertexArray(m_vao);\n\n glDrawElements(GL_TRIANGLES, 36, GL_UNSIGNED_SHORT, reinterpret_cast<void*>(0));\n\n glBindVertexArray(0);\n glUseProgram(0);\n}\n\nvoid SceneWidget::resizeGL(int w, int h)\n{\n \/\/ Adjust viewport\n glViewport(0, 0, w, h);\n\n \/\/ Adjust perspective matrix\n float aspect = static_cast<float>(w) \/ h;\n\n recalcModelMatrix();\n m_viewMatrix = glm::lookAt(glm::vec3(0, 0, 0), glm::vec3(0, 0, -1), glm::vec3(0, 1, 0));\n m_projectionMatrix = glm::perspective(90.0f, aspect, 0.01f, 100.0f);\n\n updateMvpMatrix();\n}\n\nvoid SceneWidget::initProgram()\n{\n GLuint vs = compileShader(\"..\/res\/shader.vert\", GL_VERTEX_SHADER);\n GLuint fs = compileShader(\"..\/res\/shader.frag\", GL_FRAGMENT_SHADER);\n\n m_program = glCreateProgram();\n\n glAttachShader(m_program, vs);\n glAttachShader(m_program, fs);\n\n glLinkProgram(m_program);\n checkShaderErrors(m_program, true, GL_LINK_STATUS, \"Could not link program\");\n\n glValidateProgram(m_program);\n checkShaderErrors(m_program, true, GL_VALIDATE_STATUS, \"Could not validate program\");\n\n glDetachShader(m_program, vs);\n glDetachShader(m_program, fs);\n\n glDeleteShader(vs);\n glDeleteShader(fs);\n\n \/\/ Load uniforms\n m_mvpMatrixUnif = glGetUniformLocation(m_program, \"mvpMatrix\");\n}\n\nstd::string SceneWidget::getFileContents(const std::string &path) const\n{\n std::ifstream file(path);\n if (!file.is_open())\n throw std::runtime_error(\"Could not open file: \" + path);\n\n std::ostringstream oss;\n oss << file.rdbuf();\n return oss.str();\n}\n\nvoid SceneWidget::checkShaderErrors(GLuint shader, bool isProgram, GLenum param, const std::string &errorMsg)\n{\n GLint status;\n if (isProgram)\n glGetProgramiv(shader, param, &status);\n else\n glGetShaderiv(shader, param, &status);\n\n if (status)\n return; \/\/ No errors\n\n GLint logLength;\n if (isProgram)\n glGetProgramiv(shader, GL_INFO_LOG_LENGTH, &logLength);\n else\n glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &logLength);\n\n GLchar *buffer = new GLchar[logLength];\n if (isProgram)\n glGetProgramInfoLog(shader, logLength, nullptr, buffer);\n else\n glGetShaderInfoLog(shader, logLength, nullptr, buffer);\n\n\n std::ostringstream msgStream;\n msgStream << errorMsg << \":\\n\" << buffer;\n std::string msg = msgStream.str();\n\n delete[] buffer;\n throw std::runtime_error(msg);\n}\n\nGLuint SceneWidget::compileShader(const std::string &path, GLenum type)\n{\n std::string typeStr;\n switch (type)\n {\n case GL_VERTEX_SHADER:\n typeStr = \"vertex\";\n break;\n case GL_FRAGMENT_SHADER:\n typeStr = \"fragment\";\n break;\n default:\n typeStr = \"unknown\";\n break;\n }\n\n GLuint shader = glCreateShader(type);\n\n std::string source = getFileContents(path);\n const GLchar *sourceCStr = source.c_str();\n\n glShaderSource(shader, 1, &sourceCStr, nullptr);\n glCompileShader(shader);\n checkShaderErrors(shader, false, GL_COMPILE_STATUS, \"Could not compile \" + typeStr + \" shader\");\n\n return shader;\n}\n\nvoid SceneWidget::initData()\n{\n \/\/ Data\n GLfloat data[] =\n {\n \/* POSITIONS *\/\n\n \/\/ Front face\n -1.0f, -1.0f, +1.0f,\n -1.0f, +1.0f, +1.0f,\n +1.0f, +1.0f, +1.0f,\n +1.0f, -1.0f, +1.0f,\n\n \/\/ Right face\n +1.0f, -1.0f, +1.0f,\n +1.0f, +1.0f, +1.0f,\n +1.0f, +1.0f, -1.0f,\n +1.0f, -1.0f, -1.0f,\n\n \/\/ Top face\n -1.0f, +1.0f, +1.0f,\n -1.0f, +1.0f, -1.0f,\n +1.0f, +1.0f, -1.0f,\n +1.0f, +1.0f, +1.0f,\n\n \/\/ Back face\n -1.0f, -1.0f, -1.0f,\n -1.0f, +1.0f, -1.0f,\n +1.0f, +1.0f, -1.0f,\n +1.0f, -1.0f, -1.0f,\n\n \/\/ Left face\n -1.0f, -1.0f, +1.0f,\n -1.0f, +1.0f, +1.0f,\n -1.0f, +1.0f, -1.0f,\n -1.0f, -1.0f, -1.0f,\n\n \/\/ Bottom face\n -1.0f, -1.0f, +1.0f,\n -1.0f, -1.0f, -1.0f,\n +1.0f, -1.0f, -1.0f,\n +1.0f, -1.0f, +1.0f,\n\n \/* COLORS *\/\n\n \/\/ Front face\n 1.0f, 0.0f, 0.0f,\n 1.0f, 0.0f, 0.0f,\n 1.0f, 0.0f, 0.0f,\n 1.0f, 0.0f, 0.0f,\n\n \/\/ Right face\n 0.0f, 1.0f, 0.0f,\n 0.0f, 1.0f, 0.0f,\n 0.0f, 1.0f, 0.0f,\n 0.0f, 1.0f, 0.0f,\n\n \/\/ Top face\n 0.0f, 0.0f, 1.0f,\n 0.0f, 0.0f, 1.0f,\n 0.0f, 0.0f, 1.0f,\n 0.0f, 0.0f, 1.0f,\n\n \/\/ Back face\n 0.0f, 1.0f, 1.0f,\n 0.0f, 1.0f, 1.0f,\n 0.0f, 1.0f, 1.0f,\n 0.0f, 1.0f, 1.0f,\n\n \/\/ Left face\n 1.0f, 0.0f, 1.0f,\n 1.0f, 0.0f, 1.0f,\n 1.0f, 0.0f, 1.0f,\n 1.0f, 0.0f, 1.0f,\n\n \/\/ Bottom face\n 1.0f, 1.0f, 0.0f,\n 1.0f, 1.0f, 0.0f,\n 1.0f, 1.0f, 0.0f,\n 1.0f, 1.0f, 0.0f,\n };\n\n \/\/ Indices\n GLushort indices[] =\n {\n \/\/ Front face\n 0, 1, 2,\n 0, 2, 3,\n\n \/\/ Right face\n 4, 5, 6,\n 4, 6, 7,\n\n \/\/ Top face\n 8, 9, 10,\n 8, 10, 11,\n\n \/\/ Back face\n 12, 14, 13,\n 12, 15, 14,\n\n \/\/ Left face\n 16, 18, 17,\n 16, 19, 18,\n\n \/\/ Bottom face\n 20, 22, 21,\n 20, 23, 22,\n };\n\n \/\/ Create and bind vao\n glGenVertexArrays(1, &m_vao);\n glBindVertexArray(m_vao);\n\n \/\/ Create and bind position vbo\n glGenBuffers(1, &m_vertexDataVbo);\n glBindBuffer(GL_ARRAY_BUFFER, m_vertexDataVbo);\n\n \/\/ Create and bind indices vbo\n glGenBuffers(1, &m_indicesVbo);\n glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_indicesVbo);\n\n \/\/ Fill position buffer\n glBufferData(GL_ARRAY_BUFFER, sizeof data, data, GL_STATIC_DRAW);\n\n \/\/ Position attrib\n glEnableVertexAttribArray(0);\n glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, reinterpret_cast<void*>(0));\n\n \/\/ Color attrib\n glEnableVertexAttribArray(1);\n glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 0, reinterpret_cast<void*>(numOfVertices * 3 * sizeof(GLfloat)));\n\n \/\/ Fill indices buffer\n glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof indices, indices, GL_STATIC_DRAW);\n\n \/\/ Cleanup\n glBindVertexArray(0);\n glBindBuffer(GL_ARRAY_BUFFER, 0);\n}\n\nvoid SceneWidget::recalcModelMatrix()\n{\n m_modelMatrix = glm::mat4();\n m_modelMatrix *= glm::translate(glm::mat4(), m_modelTranslate);\n m_modelMatrix *= glm::rotate(glm::mat4(), m_modelRotate.z, glm::vec3(0, 0, 1));\n m_modelMatrix *= glm::rotate(glm::mat4(), m_modelRotate.y, glm::vec3(0, 1, 0));\n m_modelMatrix *= glm::rotate(glm::mat4(), m_modelRotate.x, glm::vec3(1, 0, 0));\n m_modelMatrix *= glm::scale(glm::mat4(), m_modelScale);\n\n updateMvpMatrix();\n}\n\nvoid SceneWidget::updateMvpMatrix()\n{\n m_mvpMatrix = m_projectionMatrix * m_viewMatrix * m_modelMatrix;\n\n glUseProgram(m_program);\n glUniformMatrix4fv(m_mvpMatrixUnif, 1, GL_FALSE, glm::value_ptr(m_mvpMatrix));\n glUseProgram(0);\n}\n<commit_msg>Converted model rotation angles to radians<commit_after>#include \"scenewidget.h\"\n#include <QSurfaceFormat>\n#include <iostream>\n#include <fstream>\n#include <sstream>\n#include <stdexcept>\n#include <glm\/gtc\/type_ptr.hpp>\n#include <glm\/gtc\/matrix_transform.hpp>\n\nSceneWidget::SceneWidget(QWidget *parent) :\n QOpenGLWidget(parent), m_modelScale(1.0f, 1.0f, 1.0f)\n{\n \/\/ Set opengl version & profile\n QSurfaceFormat format;\n\n format.setRenderableType(QSurfaceFormat::OpenGL);\n format.setVersion(3, 2);\n format.setProfile(QSurfaceFormat::CoreProfile);\n format.setDepthBufferSize(24);\n format.setSamples(4);\n\n setFormat(format);\n}\n\nSceneWidget::~SceneWidget()\n{\n\n}\n\nvoid SceneWidget::initializeGL()\n{\n \/\/ Init opengl\n bool success = initializeOpenGLFunctions();\n\n \/\/ Check if opengl init was successfull\n if (!success)\n throw std::runtime_error(\"Could not load OpenGL functions.\\nDo you have OpenGL v3.2?\");\n\n \/\/ Print version info\n std::clog << \"OpenGL version: \" << glGetString(GL_VERSION) <<\n \"\\nGLSL version: \" << glGetString(GL_SHADING_LANGUAGE_VERSION) <<\n \"\\nRenderer: \" << glGetString(GL_RENDERER) <<\n \"\\nVendor: \" << glGetString(GL_VENDOR) << '\\n' << std::endl;\n\n glClearColor(1.0f, 1.0f, 1.0f, 1.0f);\n\n \/\/ Enable face culling\n glEnable(GL_CULL_FACE);\n glFrontFace(GL_CW);\n glCullFace(GL_BACK);\n\n initProgram();\n initData();\n}\n\nvoid SceneWidget::paintGL()\n{\n glClear(GL_COLOR_BUFFER_BIT);\n\n glUseProgram(m_program);\n glBindVertexArray(m_vao);\n\n glDrawElements(GL_TRIANGLES, 36, GL_UNSIGNED_SHORT, reinterpret_cast<void*>(0));\n\n glBindVertexArray(0);\n glUseProgram(0);\n}\n\nvoid SceneWidget::resizeGL(int w, int h)\n{\n \/\/ Adjust viewport\n glViewport(0, 0, w, h);\n\n \/\/ Adjust perspective matrix\n float aspect = static_cast<float>(w) \/ h;\n\n recalcModelMatrix();\n m_viewMatrix = glm::lookAt(glm::vec3(0, 0, 0), glm::vec3(0, 0, -1), glm::vec3(0, 1, 0));\n m_projectionMatrix = glm::perspective(90.0f, aspect, 0.01f, 100.0f);\n\n updateMvpMatrix();\n}\n\nvoid SceneWidget::initProgram()\n{\n GLuint vs = compileShader(\"..\/res\/shader.vert\", GL_VERTEX_SHADER);\n GLuint fs = compileShader(\"..\/res\/shader.frag\", GL_FRAGMENT_SHADER);\n\n m_program = glCreateProgram();\n\n glAttachShader(m_program, vs);\n glAttachShader(m_program, fs);\n\n glLinkProgram(m_program);\n checkShaderErrors(m_program, true, GL_LINK_STATUS, \"Could not link program\");\n\n glValidateProgram(m_program);\n checkShaderErrors(m_program, true, GL_VALIDATE_STATUS, \"Could not validate program\");\n\n glDetachShader(m_program, vs);\n glDetachShader(m_program, fs);\n\n glDeleteShader(vs);\n glDeleteShader(fs);\n\n \/\/ Load uniforms\n m_mvpMatrixUnif = glGetUniformLocation(m_program, \"mvpMatrix\");\n}\n\nstd::string SceneWidget::getFileContents(const std::string &path) const\n{\n std::ifstream file(path);\n if (!file.is_open())\n throw std::runtime_error(\"Could not open file: \" + path);\n\n std::ostringstream oss;\n oss << file.rdbuf();\n return oss.str();\n}\n\nvoid SceneWidget::checkShaderErrors(GLuint shader, bool isProgram, GLenum param, const std::string &errorMsg)\n{\n GLint status;\n if (isProgram)\n glGetProgramiv(shader, param, &status);\n else\n glGetShaderiv(shader, param, &status);\n\n if (status)\n return; \/\/ No errors\n\n GLint logLength;\n if (isProgram)\n glGetProgramiv(shader, GL_INFO_LOG_LENGTH, &logLength);\n else\n glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &logLength);\n\n GLchar *buffer = new GLchar[logLength];\n if (isProgram)\n glGetProgramInfoLog(shader, logLength, nullptr, buffer);\n else\n glGetShaderInfoLog(shader, logLength, nullptr, buffer);\n\n\n std::ostringstream msgStream;\n msgStream << errorMsg << \":\\n\" << buffer;\n std::string msg = msgStream.str();\n\n delete[] buffer;\n throw std::runtime_error(msg);\n}\n\nGLuint SceneWidget::compileShader(const std::string &path, GLenum type)\n{\n std::string typeStr;\n switch (type)\n {\n case GL_VERTEX_SHADER:\n typeStr = \"vertex\";\n break;\n case GL_FRAGMENT_SHADER:\n typeStr = \"fragment\";\n break;\n default:\n typeStr = \"unknown\";\n break;\n }\n\n GLuint shader = glCreateShader(type);\n\n std::string source = getFileContents(path);\n const GLchar *sourceCStr = source.c_str();\n\n glShaderSource(shader, 1, &sourceCStr, nullptr);\n glCompileShader(shader);\n checkShaderErrors(shader, false, GL_COMPILE_STATUS, \"Could not compile \" + typeStr + \" shader\");\n\n return shader;\n}\n\nvoid SceneWidget::initData()\n{\n \/\/ Data\n GLfloat data[] =\n {\n \/* POSITIONS *\/\n\n \/\/ Front face\n -1.0f, -1.0f, +1.0f,\n -1.0f, +1.0f, +1.0f,\n +1.0f, +1.0f, +1.0f,\n +1.0f, -1.0f, +1.0f,\n\n \/\/ Right face\n +1.0f, -1.0f, +1.0f,\n +1.0f, +1.0f, +1.0f,\n +1.0f, +1.0f, -1.0f,\n +1.0f, -1.0f, -1.0f,\n\n \/\/ Top face\n -1.0f, +1.0f, +1.0f,\n -1.0f, +1.0f, -1.0f,\n +1.0f, +1.0f, -1.0f,\n +1.0f, +1.0f, +1.0f,\n\n \/\/ Back face\n -1.0f, -1.0f, -1.0f,\n -1.0f, +1.0f, -1.0f,\n +1.0f, +1.0f, -1.0f,\n +1.0f, -1.0f, -1.0f,\n\n \/\/ Left face\n -1.0f, -1.0f, +1.0f,\n -1.0f, +1.0f, +1.0f,\n -1.0f, +1.0f, -1.0f,\n -1.0f, -1.0f, -1.0f,\n\n \/\/ Bottom face\n -1.0f, -1.0f, +1.0f,\n -1.0f, -1.0f, -1.0f,\n +1.0f, -1.0f, -1.0f,\n +1.0f, -1.0f, +1.0f,\n\n \/* COLORS *\/\n\n \/\/ Front face\n 1.0f, 0.0f, 0.0f,\n 1.0f, 0.0f, 0.0f,\n 1.0f, 0.0f, 0.0f,\n 1.0f, 0.0f, 0.0f,\n\n \/\/ Right face\n 0.0f, 1.0f, 0.0f,\n 0.0f, 1.0f, 0.0f,\n 0.0f, 1.0f, 0.0f,\n 0.0f, 1.0f, 0.0f,\n\n \/\/ Top face\n 0.0f, 0.0f, 1.0f,\n 0.0f, 0.0f, 1.0f,\n 0.0f, 0.0f, 1.0f,\n 0.0f, 0.0f, 1.0f,\n\n \/\/ Back face\n 0.0f, 1.0f, 1.0f,\n 0.0f, 1.0f, 1.0f,\n 0.0f, 1.0f, 1.0f,\n 0.0f, 1.0f, 1.0f,\n\n \/\/ Left face\n 1.0f, 0.0f, 1.0f,\n 1.0f, 0.0f, 1.0f,\n 1.0f, 0.0f, 1.0f,\n 1.0f, 0.0f, 1.0f,\n\n \/\/ Bottom face\n 1.0f, 1.0f, 0.0f,\n 1.0f, 1.0f, 0.0f,\n 1.0f, 1.0f, 0.0f,\n 1.0f, 1.0f, 0.0f,\n };\n\n \/\/ Indices\n GLushort indices[] =\n {\n \/\/ Front face\n 0, 1, 2,\n 0, 2, 3,\n\n \/\/ Right face\n 4, 5, 6,\n 4, 6, 7,\n\n \/\/ Top face\n 8, 9, 10,\n 8, 10, 11,\n\n \/\/ Back face\n 12, 14, 13,\n 12, 15, 14,\n\n \/\/ Left face\n 16, 18, 17,\n 16, 19, 18,\n\n \/\/ Bottom face\n 20, 22, 21,\n 20, 23, 22,\n };\n\n \/\/ Create and bind vao\n glGenVertexArrays(1, &m_vao);\n glBindVertexArray(m_vao);\n\n \/\/ Create and bind position vbo\n glGenBuffers(1, &m_vertexDataVbo);\n glBindBuffer(GL_ARRAY_BUFFER, m_vertexDataVbo);\n\n \/\/ Create and bind indices vbo\n glGenBuffers(1, &m_indicesVbo);\n glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_indicesVbo);\n\n \/\/ Fill position buffer\n glBufferData(GL_ARRAY_BUFFER, sizeof data, data, GL_STATIC_DRAW);\n\n \/\/ Position attrib\n glEnableVertexAttribArray(0);\n glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, reinterpret_cast<void*>(0));\n\n \/\/ Color attrib\n glEnableVertexAttribArray(1);\n glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 0, reinterpret_cast<void*>(numOfVertices * 3 * sizeof(GLfloat)));\n\n \/\/ Fill indices buffer\n glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof indices, indices, GL_STATIC_DRAW);\n\n \/\/ Cleanup\n glBindVertexArray(0);\n glBindBuffer(GL_ARRAY_BUFFER, 0);\n}\n\nvoid SceneWidget::recalcModelMatrix()\n{\n m_modelMatrix = glm::mat4();\n m_modelMatrix *= glm::translate(glm::mat4(), m_modelTranslate);\n m_modelMatrix *= glm::rotate(glm::mat4(), glm::radians(m_modelRotate.z), glm::vec3(0, 0, 1));\n m_modelMatrix *= glm::rotate(glm::mat4(), glm::radians(m_modelRotate.y), glm::vec3(0, 1, 0));\n m_modelMatrix *= glm::rotate(glm::mat4(), glm::radians(m_modelRotate.x), glm::vec3(1, 0, 0));\n m_modelMatrix *= glm::scale(glm::mat4(), m_modelScale);\n\n updateMvpMatrix();\n}\n\nvoid SceneWidget::updateMvpMatrix()\n{\n m_mvpMatrix = m_projectionMatrix * m_viewMatrix * m_modelMatrix;\n\n glUseProgram(m_program);\n glUniformMatrix4fv(m_mvpMatrixUnif, 1, GL_FALSE, glm::value_ptr(m_mvpMatrix));\n glUseProgram(0);\n}\n<|endoftext|>"} {"text":"<commit_before>#include \"csvmodelwriter.h\"\n\n#include <QAbstractItemModel>\n#include <QFile>\n#include <QTextStream>\n\nCSVModelWriter::CSVModelWriter(const QString &filename, QObject *parent) :\n QObject(parent),\n filename(filename)\n{\n}\n\nvoid CSVModelWriter::setModel(const QAbstractItemModel *model)\n{\n this->model = model;\n}\n\nvoid CSVModelWriter::addColumn(const QString &title, int column, int role)\n{\n Column col;\n col.title = title;\n col.column = column;\n col.role = role;\n\n columns.append(col);\n}\n\nstatic void writeValue(QTextStream &f, const QString &value)\n{\n \/\/ TODO: quoting if \" or \\n in string\n f << \"\\\"\" << value << \"\\\"\";\n}\n\nstatic void writeSep(QTextStream &f)\n{\n f << \",\";\n}\n\nstatic void writeNewline(QTextStream &f)\n{\n f << \"\\n\";\n}\n\nbool CSVModelWriter::write()\n{\n QFile file(filename);\n if(!file.open(QIODevice::WriteOnly | QIODevice::Text))\n return false;\n QTextStream out(&file);\n\n int numRows = 0;\n if(model)\n {\n numRows = model->rowCount();\n }\n\n \/\/ Header row\n for(int i=0; i<columns.size(); ++i)\n {\n if(i!=0)\n {\n writeSep(out);\n }\n writeValue(out, columns[i].title);\n }\n writeNewline(out);\n\n \/\/ Data rows\n for(int j=0; j<numRows; ++j)\n {\n for(int i=0; i<columns.size(); ++i)\n {\n if(i!=0)\n {\n writeSep(out);\n }\n QVariant data = model->index(j, columns[i].column).data(columns[i].role);\n writeValue(out, data.toString());\n }\n writeNewline(out);\n }\n\n file.close();\n\n return file.error() == QFile::NoError;\n}\n\n<commit_msg>Add forgotten initializer<commit_after>#include \"csvmodelwriter.h\"\n\n#include <QAbstractItemModel>\n#include <QFile>\n#include <QTextStream>\n\nCSVModelWriter::CSVModelWriter(const QString &filename, QObject *parent) :\n QObject(parent),\n filename(filename), model(0)\n{\n}\n\nvoid CSVModelWriter::setModel(const QAbstractItemModel *model)\n{\n this->model = model;\n}\n\nvoid CSVModelWriter::addColumn(const QString &title, int column, int role)\n{\n Column col;\n col.title = title;\n col.column = column;\n col.role = role;\n\n columns.append(col);\n}\n\nstatic void writeValue(QTextStream &f, const QString &value)\n{\n \/\/ TODO: quoting if \" or \\n in string\n f << \"\\\"\" << value << \"\\\"\";\n}\n\nstatic void writeSep(QTextStream &f)\n{\n f << \",\";\n}\n\nstatic void writeNewline(QTextStream &f)\n{\n f << \"\\n\";\n}\n\nbool CSVModelWriter::write()\n{\n QFile file(filename);\n if(!file.open(QIODevice::WriteOnly | QIODevice::Text))\n return false;\n QTextStream out(&file);\n\n int numRows = 0;\n if(model)\n {\n numRows = model->rowCount();\n }\n\n \/\/ Header row\n for(int i=0; i<columns.size(); ++i)\n {\n if(i!=0)\n {\n writeSep(out);\n }\n writeValue(out, columns[i].title);\n }\n writeNewline(out);\n\n \/\/ Data rows\n for(int j=0; j<numRows; ++j)\n {\n for(int i=0; i<columns.size(); ++i)\n {\n if(i!=0)\n {\n writeSep(out);\n }\n QVariant data = model->index(j, columns[i].column).data(columns[i].role);\n writeValue(out, data.toString());\n }\n writeNewline(out);\n }\n\n file.close();\n\n return file.error() == QFile::NoError;\n}\n\n<|endoftext|>"} {"text":"<commit_before>#include \"statisticspage.h\"\r\n#include \"ui_statisticspage.h\"\r\n#include \"main.h\"\r\n#include \"wallet.h\"\r\n#include \"init.h\"\r\n#include \"base58.h\"\r\n#include \"clientmodel.h\"\r\n#include \"bitcoinrpc.h\"\r\n#include \"marketbrowser.h\"\r\n#include <sstream>\r\n#include <string>\r\n\r\nusing namespace json_spirit;\r\n\r\nStatisticsPage::StatisticsPage(QWidget *parent) :\r\n QWidget(parent),\r\n ui(new Ui::StatisticsPage)\r\n{\r\n ui->setupUi(this);\r\n \r\n setFixedSize(400, 420);\r\n \r\n connect(ui->startButton, SIGNAL(pressed()), this, SLOT(updateStatistics()));\r\n}\r\n\r\nint heightPrevious = -1;\r\nint connectionPrevious = -1;\r\nint volumePrevious = -1;\r\ndouble netPawratePrevious = -1;\r\ndouble pawratePrevious = -1;\r\ndouble hardnessPrevious = -1;\r\ndouble hardnessPrevious2 = -1;\r\nint stakeminPrevious = -1;\r\nint stakemaxPrevious = -1;\r\nint64_t marketcapPrevious = -1;\r\nQString stakecPrevious = \"\";\r\nQString rewardPrevious = \"\";\r\n\r\nvoid StatisticsPage::updateStatistics()\r\n{\r\n double pHardness = GetDifficulty();\r\n double pHardness2 = GetDifficulty(GetLastBlockIndex(pindexBest, true));\r\n int pPawrate = GetPoWMHashPS();\r\n double pPawrate2 = 0.000;\r\n int nHeight = pindexBest->nHeight;\r\n uint64_t nMinWeight = 0, nMaxWeight = 0, nWeight = 0;\r\n pwalletMain->GetStakeWeight(*pwalletMain, nMinWeight, nMaxWeight, nWeight);\r\n uint64_t nNetworkWeight = GetPoSKernelPS();\r\n int64_t volume = ((pindexBest->nMoneySupply)\/100000000);\r\n\tint64_t marketcap = dnrmarket.toDouble();\r\n int peers = this->model->getNumConnections();\r\n pPawrate2 = (double)pPawrate;\r\n QString height = QString::number(nHeight);\r\n QString stakemin = QString::number(nMinWeight);\r\n QString stakemax = QString::number(nNetworkWeight);\r\n QString phase = \"\";\r\n if (pindexBest->nHeight < 3000000)\r\n {\r\n phase = \"Tribus Proof of Work with Proof of Stake\";\r\n }\r\n else if (pindexBest->nHeight > 3000000)\r\n {\r\n phase = \"Proof of Stake\";\r\n }\r\n\r\n QString subsidy = \"\";\r\n\tif (pindexBest->nHeight < 1000000)\r\n {\r\n subsidy = \"2 BZL per block\";\r\n }\r\n\telse if (pindexBest->nHeight < 2000000)\r\n {\r\n subsidy = \"2 BZL per block\";\r\n }\r\n\telse if (pindexBest->nHeight < 3000000)\r\n {\r\n subsidy = \"1 BZL per block\";\r\n }\r\n else if (pindexBest->nHeight > 3000000)\r\n {\r\n subsidy = \"No PoW Reward\";\r\n }\r\n QString hardness = QString::number(pHardness, 'f', 6);\r\n QString hardness2 = QString::number(pHardness2, 'f', 6);\r\n QString pawrate = QString::number(pPawrate2, 'f', 3);\r\n QString Qlpawrate = model->getLastBlockDate().toString();\r\n\r\n QString QPeers = QString::number(peers);\r\n QString qVolume = QString::number(volume);\r\n\r\n if(nHeight > heightPrevious)\r\n {\r\n ui->heightBox->setText(\"<b><font color=\\\"yellow\\\">\" + height + \"<\/font><\/b>\");\r\n } else {\r\n\t\tui->heightBox->setText(\"<b><font color=\\\"orange\\\">\" + height + \"<\/font><\/b>\");\r\n }\r\n\r\n if(0 > stakeminPrevious)\r\n {\r\n ui->minBox->setText(\"<b><font color=\\\"yellow\\\">\" + stakemin + \"<\/font><\/b>\");\r\n } else {\r\n ui->minBox->setText(\"<b><font color=\\\"orange\\\">\" + stakemin + \"<\/font><\/b>\");\r\n }\r\n if(0 > stakemaxPrevious)\r\n {\r\n ui->maxBox->setText(\"<b><font color=\\\"yellow\\\">\" + stakemax + \"<\/font><\/b>\");\r\n } else {\r\n ui->maxBox->setText(\"<b><font color=\\\"orange\\\">\" + stakemax + \"<\/font><\/b>\");\r\n }\r\n\r\n if(phase != stakecPrevious)\r\n {\r\n ui->cBox->setText(\"<b><font color=\\\"yellow\\\">\" + phase + \"<\/font><\/b>\");\r\n } else {\r\n ui->cBox->setText(\"<b><font color=\\\"orange\\\">\" + phase + \"<\/font><\/b>\");\r\n }\r\n \r\n if(subsidy != rewardPrevious)\r\n {\r\n ui->rewardBox->setText(\"<b><font color=\\\"yellow\\\">\" + subsidy + \"<\/font><\/b>\");\r\n } else {\r\n ui->rewardBox->setText(\"<b><font color=\\\"orange\\\">\" + subsidy + \"<\/font><\/b>\");\r\n }\r\n \r\n if(pHardness > hardnessPrevious)\r\n {\r\n ui->diffBox->setText(\"<b><font color=\\\"yellow\\\">\" + hardness + \"<\/font><\/b>\"); \r\n } else if(pHardness < hardnessPrevious) {\r\n ui->diffBox->setText(\"<b><font color=\\\"red\\\">\" + hardness + \"<\/font><\/b>\");\r\n } else {\r\n ui->diffBox->setText(\"<b><font color=\\\"orange\\\">\" + hardness + \"<\/font><\/b>\"); \r\n }\r\n\t\/*\r\n if(marketcap > marketcapPrevious)\r\n {\r\n ui->marketcap->setText(\"<b><font color=\\\"yellow\\\">$\" + QString::number(marketcap) + \" USD<\/font><\/b>\");\r\n } else if(marketcap < marketcapPrevious) {\r\n ui->marketcap->setText(\"<b><font color=\\\"red\\\">$\" + QString::number(marketcap) + \" USD<\/font><\/b>\");\r\n } else {\r\n ui->marketcap->setText(\"<b><font color=\\\"orange\\\">$\"+QString::number(marketcap)+\" USD<\/font><\/b>\");\r\n }\r\n\t*\/\r\n if(pHardness2 > hardnessPrevious2)\r\n {\r\n ui->diffBox2->setText(\"<b><font color=\\\"yellow\\\">\" + hardness2 + \"<\/font><\/b>\");\r\n } else if(pHardness2 < hardnessPrevious2) {\r\n ui->diffBox2->setText(\"<b><font color=\\\"red\\\">\" + hardness2 + \"<\/font><\/b>\");\r\n } else {\r\n ui->diffBox2->setText(\"<b><font color=\\\"orange\\\">\" + hardness2 + \"<\/font><\/b>\");\r\n }\r\n \r\n if(pPawrate2 > netPawratePrevious)\r\n {\r\n ui->pawrateBox->setText(\"<b><font color=\\\"yellow\\\">\" + pawrate + \" MH\/s<\/font><\/b>\");\r\n } else if(pPawrate2 < netPawratePrevious) {\r\n ui->pawrateBox->setText(\"<b><font color=\\\"red\\\">\" + pawrate + \" MH\/s<\/font><\/b>\");\r\n } else {\r\n ui->pawrateBox->setText(\"<b><font color=\\\"orange\\\">\" + pawrate + \" MH\/s<\/font><\/b>\");\r\n }\r\n\r\n if(Qlpawrate != pawratePrevious)\r\n {\r\n ui->localBox->setText(\"<b><font color=\\\"yellow\\\">\" + Qlpawrate + \"<\/font><\/b>\");\r\n } else {\r\n ui->localBox->setText(\"<b><font color=\\\"orange\\\">\" + Qlpawrate + \"<\/font><\/b>\");\r\n }\r\n \r\n if(peers > connectionPrevious)\r\n {\r\n ui->connectionBox->setText(\"<b><font color=\\\"yellow\\\">\" + QPeers + \"<\/font><\/b>\"); \r\n } else if(peers < connectionPrevious) {\r\n ui->connectionBox->setText(\"<b><font color=\\\"red\\\">\" + QPeers + \"<\/font><\/b>\"); \r\n } else {\r\n ui->connectionBox->setText(\"<b><font color=\\\"orange\\\">\" + QPeers + \"<\/font><\/b>\"); \r\n }\r\n\r\n if(volume > volumePrevious)\r\n {\r\n ui->volumeBox->setText(\"<b><font color=\\\"yellow\\\">\" + qVolume + \" BZL\" + \"<\/font><\/b>\");\r\n } else if(volume < volumePrevious) {\r\n ui->volumeBox->setText(\"<b><font color=\\\"red\\\">\" + qVolume + \" BZL\" + \"<\/font><\/b>\");\r\n } else {\r\n ui->volumeBox->setText(\"<b><font color=\\\"orange\\\">\" + qVolume + \" BZL\" + \"<\/font><\/b>\");\r\n }\r\n\t\r\n updatePrevious(nHeight, nMinWeight, nNetworkWeight, phase, subsidy, pHardness, pHardness2, pPawrate2, Qlpawrate, peers, volume, marketcap);\r\n}\r\n\r\nvoid StatisticsPage::updatePrevious(int nHeight, int nMinWeight, int nNetworkWeight, QString phase, QString subsidy, double pHardness, double pHardness2, double pPawrate2, QString Qlpawrate, int peers, int volume, int64_t marketcap)\r\n{\r\n heightPrevious = nHeight;\r\n stakeminPrevious = nMinWeight;\r\n stakemaxPrevious = nNetworkWeight;\r\n stakecPrevious = phase;\r\n rewardPrevious = subsidy;\r\n hardnessPrevious = pHardness;\r\n hardnessPrevious2 = pHardness2;\r\n netPawratePrevious = pPawrate2;\r\n pawratePrevious = Qlpawrate;\r\n connectionPrevious = peers;\r\n volumePrevious = volume;\r\n\tmarketcapPrevious = marketcap;\r\n}\r\n\r\nvoid StatisticsPage::setModel(ClientModel *model)\r\n{\r\n updateStatistics();\r\n this->model = model;\r\n}\r\n\r\n\r\nStatisticsPage::~StatisticsPage()\r\n{\r\n delete ui;\r\n}\r\n<commit_msg>V1.1 \/ Fork in block 3398<commit_after>#include \"statisticspage.h\"\r\n#include \"ui_statisticspage.h\"\r\n#include \"main.h\"\r\n#include \"wallet.h\"\r\n#include \"init.h\"\r\n#include \"base58.h\"\r\n#include \"clientmodel.h\"\r\n#include \"bitcoinrpc.h\"\r\n#include \"marketbrowser.h\"\r\n#include <sstream>\r\n#include <string>\r\n\r\nusing namespace json_spirit;\r\n\r\nStatisticsPage::StatisticsPage(QWidget *parent) :\r\n QWidget(parent),\r\n ui(new Ui::StatisticsPage)\r\n{\r\n ui->setupUi(this);\r\n \r\n setFixedSize(400, 420);\r\n \r\n connect(ui->startButton, SIGNAL(pressed()), this, SLOT(updateStatistics()));\r\n}\r\n\r\nint heightPrevious = -1;\r\nint connectionPrevious = -1;\r\nint volumePrevious = -1;\r\ndouble netPawratePrevious = -1;\r\ndouble pawratePrevious = -1;\r\ndouble hardnessPrevious = -1;\r\ndouble hardnessPrevious2 = -1;\r\nint stakeminPrevious = -1;\r\nint stakemaxPrevious = -1;\r\nint64_t marketcapPrevious = -1;\r\nQString stakecPrevious = \"\";\r\nQString rewardPrevious = \"\";\r\n\r\nvoid StatisticsPage::updateStatistics()\r\n{\r\n double pHardness = GetDifficulty();\r\n double pHardness2 = GetDifficulty(GetLastBlockIndex(pindexBest, true));\r\n int pPawrate = GetPoWMHashPS();\r\n double pPawrate2 = 0.000;\r\n int nHeight = pindexBest->nHeight;\r\n uint64_t nMinWeight = 0, nMaxWeight = 0, nWeight = 0;\r\n pwalletMain->GetStakeWeight(*pwalletMain, nMinWeight, nMaxWeight, nWeight);\r\n uint64_t nNetworkWeight = GetPoSKernelPS();\r\n int64_t volume = ((pindexBest->nMoneySupply)\/100000000);\r\n\tint64_t marketcap = dnrmarket.toDouble();\r\n int peers = this->model->getNumConnections();\r\n pPawrate2 = (double)pPawrate;\r\n QString height = QString::number(nHeight);\r\n QString stakemin = QString::number(nMinWeight);\r\n QString stakemax = QString::number(nNetworkWeight);\r\n QString phase = \"\";\r\n if (pindexBest->nHeight < 3000000)\r\n {\r\n phase = \"Tribus Proof of Work with Proof of Stake\";\r\n }\r\n else if (pindexBest->nHeight > 3000000)\r\n {\r\n phase = \"Proof of Stake\";\r\n }\r\n\r\n QString subsidy = \"\";\r\n\tif (pindexBest->nHeight < 3398) \/\/ V1.1\r\n {\r\n subsidy = \"2 BZL per block\";\r\n }\r\n\telse if (pindexBest->nHeight < 2000000)\r\n {\r\n subsidy = \"1 BZL per block\";\r\n }\r\n\telse if (pindexBest->nHeight < 3000000)\r\n {\r\n subsidy = \"1 BZL per block\";\r\n }\r\n else if (pindexBest->nHeight > 3000000)\r\n {\r\n subsidy = \"No PoW Reward\";\r\n }\r\n QString hardness = QString::number(pHardness, 'f', 6);\r\n QString hardness2 = QString::number(pHardness2, 'f', 6);\r\n QString pawrate = QString::number(pPawrate2, 'f', 3);\r\n QString Qlpawrate = model->getLastBlockDate().toString();\r\n\r\n QString QPeers = QString::number(peers);\r\n QString qVolume = QString::number(volume);\r\n\r\n if(nHeight > heightPrevious)\r\n {\r\n ui->heightBox->setText(\"<b><font color=\\\"yellow\\\">\" + height + \"<\/font><\/b>\");\r\n } else {\r\n\t\tui->heightBox->setText(\"<b><font color=\\\"orange\\\">\" + height + \"<\/font><\/b>\");\r\n }\r\n\r\n if(0 > stakeminPrevious)\r\n {\r\n ui->minBox->setText(\"<b><font color=\\\"yellow\\\">\" + stakemin + \"<\/font><\/b>\");\r\n } else {\r\n ui->minBox->setText(\"<b><font color=\\\"orange\\\">\" + stakemin + \"<\/font><\/b>\");\r\n }\r\n if(0 > stakemaxPrevious)\r\n {\r\n ui->maxBox->setText(\"<b><font color=\\\"yellow\\\">\" + stakemax + \"<\/font><\/b>\");\r\n } else {\r\n ui->maxBox->setText(\"<b><font color=\\\"orange\\\">\" + stakemax + \"<\/font><\/b>\");\r\n }\r\n\r\n if(phase != stakecPrevious)\r\n {\r\n ui->cBox->setText(\"<b><font color=\\\"yellow\\\">\" + phase + \"<\/font><\/b>\");\r\n } else {\r\n ui->cBox->setText(\"<b><font color=\\\"orange\\\">\" + phase + \"<\/font><\/b>\");\r\n }\r\n \r\n if(subsidy != rewardPrevious)\r\n {\r\n ui->rewardBox->setText(\"<b><font color=\\\"yellow\\\">\" + subsidy + \"<\/font><\/b>\");\r\n } else {\r\n ui->rewardBox->setText(\"<b><font color=\\\"orange\\\">\" + subsidy + \"<\/font><\/b>\");\r\n }\r\n \r\n if(pHardness > hardnessPrevious)\r\n {\r\n ui->diffBox->setText(\"<b><font color=\\\"yellow\\\">\" + hardness + \"<\/font><\/b>\"); \r\n } else if(pHardness < hardnessPrevious) {\r\n ui->diffBox->setText(\"<b><font color=\\\"red\\\">\" + hardness + \"<\/font><\/b>\");\r\n } else {\r\n ui->diffBox->setText(\"<b><font color=\\\"orange\\\">\" + hardness + \"<\/font><\/b>\"); \r\n }\r\n\t\/*\r\n if(marketcap > marketcapPrevious)\r\n {\r\n ui->marketcap->setText(\"<b><font color=\\\"yellow\\\">$\" + QString::number(marketcap) + \" USD<\/font><\/b>\");\r\n } else if(marketcap < marketcapPrevious) {\r\n ui->marketcap->setText(\"<b><font color=\\\"red\\\">$\" + QString::number(marketcap) + \" USD<\/font><\/b>\");\r\n } else {\r\n ui->marketcap->setText(\"<b><font color=\\\"orange\\\">$\"+QString::number(marketcap)+\" USD<\/font><\/b>\");\r\n }\r\n\t*\/\r\n if(pHardness2 > hardnessPrevious2)\r\n {\r\n ui->diffBox2->setText(\"<b><font color=\\\"yellow\\\">\" + hardness2 + \"<\/font><\/b>\");\r\n } else if(pHardness2 < hardnessPrevious2) {\r\n ui->diffBox2->setText(\"<b><font color=\\\"red\\\">\" + hardness2 + \"<\/font><\/b>\");\r\n } else {\r\n ui->diffBox2->setText(\"<b><font color=\\\"orange\\\">\" + hardness2 + \"<\/font><\/b>\");\r\n }\r\n \r\n if(pPawrate2 > netPawratePrevious)\r\n {\r\n ui->pawrateBox->setText(\"<b><font color=\\\"yellow\\\">\" + pawrate + \" MH\/s<\/font><\/b>\");\r\n } else if(pPawrate2 < netPawratePrevious) {\r\n ui->pawrateBox->setText(\"<b><font color=\\\"red\\\">\" + pawrate + \" MH\/s<\/font><\/b>\");\r\n } else {\r\n ui->pawrateBox->setText(\"<b><font color=\\\"orange\\\">\" + pawrate + \" MH\/s<\/font><\/b>\");\r\n }\r\n\r\n if(Qlpawrate != pawratePrevious)\r\n {\r\n ui->localBox->setText(\"<b><font color=\\\"yellow\\\">\" + Qlpawrate + \"<\/font><\/b>\");\r\n } else {\r\n ui->localBox->setText(\"<b><font color=\\\"orange\\\">\" + Qlpawrate + \"<\/font><\/b>\");\r\n }\r\n \r\n if(peers > connectionPrevious)\r\n {\r\n ui->connectionBox->setText(\"<b><font color=\\\"yellow\\\">\" + QPeers + \"<\/font><\/b>\"); \r\n } else if(peers < connectionPrevious) {\r\n ui->connectionBox->setText(\"<b><font color=\\\"red\\\">\" + QPeers + \"<\/font><\/b>\"); \r\n } else {\r\n ui->connectionBox->setText(\"<b><font color=\\\"orange\\\">\" + QPeers + \"<\/font><\/b>\"); \r\n }\r\n\r\n if(volume > volumePrevious)\r\n {\r\n ui->volumeBox->setText(\"<b><font color=\\\"yellow\\\">\" + qVolume + \" BZL\" + \"<\/font><\/b>\");\r\n } else if(volume < volumePrevious) {\r\n ui->volumeBox->setText(\"<b><font color=\\\"red\\\">\" + qVolume + \" BZL\" + \"<\/font><\/b>\");\r\n } else {\r\n ui->volumeBox->setText(\"<b><font color=\\\"orange\\\">\" + qVolume + \" BZL\" + \"<\/font><\/b>\");\r\n }\r\n\t\r\n updatePrevious(nHeight, nMinWeight, nNetworkWeight, phase, subsidy, pHardness, pHardness2, pPawrate2, Qlpawrate, peers, volume, marketcap);\r\n}\r\n\r\nvoid StatisticsPage::updatePrevious(int nHeight, int nMinWeight, int nNetworkWeight, QString phase, QString subsidy, double pHardness, double pHardness2, double pPawrate2, QString Qlpawrate, int peers, int volume, int64_t marketcap)\r\n{\r\n heightPrevious = nHeight;\r\n stakeminPrevious = nMinWeight;\r\n stakemaxPrevious = nNetworkWeight;\r\n stakecPrevious = phase;\r\n rewardPrevious = subsidy;\r\n hardnessPrevious = pHardness;\r\n hardnessPrevious2 = pHardness2;\r\n netPawratePrevious = pPawrate2;\r\n pawratePrevious = Qlpawrate;\r\n connectionPrevious = peers;\r\n volumePrevious = volume;\r\n\tmarketcapPrevious = marketcap;\r\n}\r\n\r\nvoid StatisticsPage::setModel(ClientModel *model)\r\n{\r\n updateStatistics();\r\n this->model = model;\r\n}\r\n\r\n\r\nStatisticsPage::~StatisticsPage()\r\n{\r\n delete ui;\r\n}\r\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2010-2013 RethinkDB, all rights reserved.\n#include \"rdb_protocol\/error.hpp\"\n\n#include \"backtrace.hpp\"\n#include \"rdb_protocol\/datum.hpp\"\n#include \"rdb_protocol\/term_walker.hpp\"\n#include \"rdb_protocol\/val.hpp\"\n\nnamespace ql {\n\n#ifdef RQL_ERROR_BT\n#define RQL_ERROR_VAR\n#else\n#define RQL_ERROR_VAR __attribute__((unused))\n#endif\n\nvoid runtime_fail(base_exc_t::type_t type,\n RQL_ERROR_VAR const char *test, RQL_ERROR_VAR const char *file,\n RQL_ERROR_VAR int line,\n std::string msg, const Backtrace *bt_src) {\n#ifdef RQL_ERROR_BT\n msg = strprintf(\"%s\\nFailed assertion: %s\\nAt: %s:%d\",\n msg.c_str(), test, file, line);\n#endif\n throw exc_t(type, msg, bt_src);\n}\nvoid runtime_fail(base_exc_t::type_t type,\n RQL_ERROR_VAR const char *test, RQL_ERROR_VAR const char *file,\n RQL_ERROR_VAR int line, std::string msg) {\n#ifdef RQL_ERROR_BT\n msg = strprintf(\"%s\\nFailed assertion: %s\\nAt: %s:%d\",\n msg.c_str(), test, file, line);\n#endif\n throw datum_exc_t(type, msg);\n}\n\nvoid runtime_sanity_check(bool test) {\n if (!test) {\n lazy_backtrace_t bt;\n throw exc_t(base_exc_t::GENERIC,\n \"SANITY CHECK FAILED (server is buggy). Backtrace:\\n\" + bt.addrs(),\n backtrace_t());\n }\n}\n\nbase_exc_t::type_t exc_type(const datum_t *d) {\n r_sanity_check(d);\n return d->get_type() == datum_t::R_NULL\n ? base_exc_t::NON_EXISTENCE\n : base_exc_t::GENERIC;\n}\nbase_exc_t::type_t exc_type(const counted_t<const datum_t> &d) {\n r_sanity_check(d.has());\n return exc_type(d.get());\n}\nbase_exc_t::type_t exc_type(const val_t *v) {\n r_sanity_check(v);\n if (v->get_type().is_convertible(val_t::type_t::DATUM)) {\n return exc_type(v->as_datum());\n } else {\n return base_exc_t::GENERIC;\n }\n}\nbase_exc_t::type_t exc_type(const counted_t<val_t> &v) {\n r_sanity_check(v.has());\n return exc_type(v.get());\n}\n\nvoid backtrace_t::fill_bt(Backtrace *bt) const {\n for (std::list<backtrace_t::frame_t>::const_iterator\n it = frames.begin(); it != frames.end(); ++it) {\n if (it->is_skip()) continue;\n if (it->is_head()) {\n rassert(it == frames.begin());\n continue;\n }\n *bt->add_frames() = it->toproto();\n }\n}\nvoid backtrace_t::fill_error(Response *res, Response_ResponseType type,\n std::string msg) const {\n guarantee(type == Response::CLIENT_ERROR ||\n type == Response::COMPILE_ERROR ||\n type == Response::RUNTIME_ERROR);\n Datum error_msg;\n error_msg.set_type(Datum::R_STR);\n error_msg.set_r_str(msg);\n res->set_type(type);\n *res->add_response() = error_msg;\n fill_bt(res->mutable_backtrace());\n}\nvoid fill_error(Response *res, Response_ResponseType type, std::string msg,\n const backtrace_t &bt) {\n bt.fill_error(res, type, msg);\n}\n\nFrame backtrace_t::frame_t::toproto() const {\n Frame f;\n switch(type) {\n case POS: {\n f.set_type(Frame_FrameType_POS);\n f.set_pos(pos);\n } break;\n case OPT: {\n f.set_type(Frame_FrameType_OPT);\n f.set_opt(opt);\n } break;\n default: unreachable();\n }\n return f;\n}\n\nbacktrace_t::frame_t::frame_t(const Frame &f) {\n switch(f.type()) {\n case Frame::POS: {\n type = POS;\n pos = f.pos();\n } break;\n case Frame::OPT: {\n type = OPT;\n opt = f.opt();\n } break;\n default: unreachable();\n }\n}\n\nprotob_t<const Backtrace> get_backtrace(const protob_t<const Term> &t) {\n return t.make_child(&t->GetExtension(ql2::extension::backtrace));\n}\n\nvoid pb_rcheckable_t::propagate(Term *t) const {\n propagate_backtrace(t, bt_src.get());\n}\n\n} \/\/ namespace ql\n<commit_msg>Used UNUSED in a place.<commit_after>\/\/ Copyright 2010-2013 RethinkDB, all rights reserved.\n#include \"rdb_protocol\/error.hpp\"\n\n#include \"backtrace.hpp\"\n#include \"rdb_protocol\/datum.hpp\"\n#include \"rdb_protocol\/term_walker.hpp\"\n#include \"rdb_protocol\/val.hpp\"\n\nnamespace ql {\n\n#ifdef RQL_ERROR_BT\n#define RQL_ERROR_VAR\n#else\n#define RQL_ERROR_VAR UNUSED\n#endif\n\nvoid runtime_fail(base_exc_t::type_t type,\n RQL_ERROR_VAR const char *test, RQL_ERROR_VAR const char *file,\n RQL_ERROR_VAR int line,\n std::string msg, const Backtrace *bt_src) {\n#ifdef RQL_ERROR_BT\n msg = strprintf(\"%s\\nFailed assertion: %s\\nAt: %s:%d\",\n msg.c_str(), test, file, line);\n#endif\n throw exc_t(type, msg, bt_src);\n}\nvoid runtime_fail(base_exc_t::type_t type,\n RQL_ERROR_VAR const char *test, RQL_ERROR_VAR const char *file,\n RQL_ERROR_VAR int line, std::string msg) {\n#ifdef RQL_ERROR_BT\n msg = strprintf(\"%s\\nFailed assertion: %s\\nAt: %s:%d\",\n msg.c_str(), test, file, line);\n#endif\n throw datum_exc_t(type, msg);\n}\n\nvoid runtime_sanity_check(bool test) {\n if (!test) {\n lazy_backtrace_t bt;\n throw exc_t(base_exc_t::GENERIC,\n \"SANITY CHECK FAILED (server is buggy). Backtrace:\\n\" + bt.addrs(),\n backtrace_t());\n }\n}\n\nbase_exc_t::type_t exc_type(const datum_t *d) {\n r_sanity_check(d);\n return d->get_type() == datum_t::R_NULL\n ? base_exc_t::NON_EXISTENCE\n : base_exc_t::GENERIC;\n}\nbase_exc_t::type_t exc_type(const counted_t<const datum_t> &d) {\n r_sanity_check(d.has());\n return exc_type(d.get());\n}\nbase_exc_t::type_t exc_type(const val_t *v) {\n r_sanity_check(v);\n if (v->get_type().is_convertible(val_t::type_t::DATUM)) {\n return exc_type(v->as_datum());\n } else {\n return base_exc_t::GENERIC;\n }\n}\nbase_exc_t::type_t exc_type(const counted_t<val_t> &v) {\n r_sanity_check(v.has());\n return exc_type(v.get());\n}\n\nvoid backtrace_t::fill_bt(Backtrace *bt) const {\n for (std::list<backtrace_t::frame_t>::const_iterator\n it = frames.begin(); it != frames.end(); ++it) {\n if (it->is_skip()) continue;\n if (it->is_head()) {\n rassert(it == frames.begin());\n continue;\n }\n *bt->add_frames() = it->toproto();\n }\n}\nvoid backtrace_t::fill_error(Response *res, Response_ResponseType type,\n std::string msg) const {\n guarantee(type == Response::CLIENT_ERROR ||\n type == Response::COMPILE_ERROR ||\n type == Response::RUNTIME_ERROR);\n Datum error_msg;\n error_msg.set_type(Datum::R_STR);\n error_msg.set_r_str(msg);\n res->set_type(type);\n *res->add_response() = error_msg;\n fill_bt(res->mutable_backtrace());\n}\nvoid fill_error(Response *res, Response_ResponseType type, std::string msg,\n const backtrace_t &bt) {\n bt.fill_error(res, type, msg);\n}\n\nFrame backtrace_t::frame_t::toproto() const {\n Frame f;\n switch(type) {\n case POS: {\n f.set_type(Frame_FrameType_POS);\n f.set_pos(pos);\n } break;\n case OPT: {\n f.set_type(Frame_FrameType_OPT);\n f.set_opt(opt);\n } break;\n default: unreachable();\n }\n return f;\n}\n\nbacktrace_t::frame_t::frame_t(const Frame &f) {\n switch(f.type()) {\n case Frame::POS: {\n type = POS;\n pos = f.pos();\n } break;\n case Frame::OPT: {\n type = OPT;\n opt = f.opt();\n } break;\n default: unreachable();\n }\n}\n\nprotob_t<const Backtrace> get_backtrace(const protob_t<const Term> &t) {\n return t.make_child(&t->GetExtension(ql2::extension::backtrace));\n}\n\nvoid pb_rcheckable_t::propagate(Term *t) const {\n propagate_backtrace(t, bt_src.get());\n}\n\n} \/\/ namespace ql\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright 2013 Alessio Sclocco <a.sclocco@vu.nl>\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include <string>\n#include <fstream>\n#include <map>\n#include <vector>\n#include <cctype>\n\n#include <readConfiguration.hpp>\n#include <utils.hpp>\n\n\nvoid readPadding(std::map< std::string, unsigned int > & padding, const std::string & paddingFilename) {\n\tstd::string temp;\n\tstd::ifstream paddingFile(paddingFilename);\n\n\twhile ( ! paddingFile.eof() ) {\n\t\tunsigned int middle = 0;\n\n\t\tstd::getline(paddingFile, temp);\n\t\tif ( ! std::isalpha(temp[0]) ) {\n\t\t\tcontinue;\n\t\t}\n\t\tmiddle = temp.find(\" \");\n\t\tpadding.insert(std::make_pair(temp.substr(0, middle), isa::utils::castToType< std::string, unsigned int >(temp.substr(middle + 1))));\n\t}\n}\n\nvoid readVectorWidth(std::map< std::string, unsigned int > & vectorWidth, const std::string & vectorFilename) {\n\tstd::string temp;\n\tstd::ifstream vectorFile(vectorFilename);\n\n\twhile ( ! vectorFile.eof() ) {\n\t\tunsigned int middle = 0;\n\n\t\tstd::getline(vectorFile, temp);\n\t\tif ( ! std::isalpha(temp[0]) ) {\n\t\t\tcontinue;\n\t\t}\n\t\tmiddle = temp.find(\" \");\n\t\tvectorWidth.insert(std::make_pair(temp.substr(0, middle), isa::utils::castToType< std::string, unsigned int >(temp.substr(middle + 1))));\n\t}\n}\n\nvoid readDedispersion(std::map< std::string, std::map< unsigned int, PulsarSearch::DedispersionConf > > & dedispersionParameters, const std::string & dedispersionFilename) {\n\tstd::string temp;\n\tstd::ifstream dedispersionFile(dedispersionFilename);\n\n\twhile ( ! dedispersionFile.eof() ) {\n\t\tunsigned int splitPoint = 0;\n\n\t\tstd::getline(dedispersionFile, temp);\n\t\tif ( ! std::isalpha(temp[0]) ) {\n\t\t\tcontinue;\n\t\t}\n\t\tstd::string deviceName;\n\t\tunsigned int nrDMs = 0;\n PulsarSearch::DedispersionConf conf;\n\n\t\tsplitPoint = temp.find(\" \");\n\t\tdeviceName = temp.substr(0, splitPoint);\n\t\ttemp = temp.substr(splitPoint + 1);\n\t\tsplitPoint = temp.find(\" \");\n\t\tnrDMs = isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint));\n\t\ttemp = temp.substr(splitPoint + 1);\n\t\tsplitPoint = temp.find(\" \");\n\t\tconf.setLocalMem(isa::utils::castToType< std::string, bool >(temp.substr(0, splitPoint)));\n\t\ttemp = temp.substr(splitPoint + 1);\n\t\tsplitPoint = temp.find(\" \");\n\t\tconf.setUnroll(isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint)));\n\t\ttemp = temp.substr(splitPoint + 1);\n\t\tsplitPoint = temp.find(\" \");\n\t\tconf.setNrSamplesPerBlock(isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint)));\n\t\ttemp = temp.substr(splitPoint + 1);\n\t\tsplitPoint = temp.find(\" \");\n\t\tconf.setNrDMsPerBlock(isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint)));\n\t\ttemp = temp.substr(splitPoint + 1);\n\t\tsplitPoint = temp.find(\" \");\n\t\tconf.setNrSamplesPerThread(isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint)));\n\t\ttemp = temp.substr(splitPoint + 1);\n\t\tconf.setNrDMsPerThread(isa::utils::castToType< std::string, unsigned int >(temp));\n\n\t\tif ( dedispersionParameters.count(deviceName) == 0 ) {\n std::map< unsigned int, PulsarSearch::DedispersionConf > container;\n\n\t\t\tcontainer.insert(std::make_pair(nrDMs, conf));\n\t\t\tdedispersionParameters.insert(std::make_pair(deviceName, container));\n\t\t} else {\n\t\t\tdedispersionParameters[deviceName].insert(std::make_pair(nrDMs, conf));\n\t\t}\n\t}\n}\n\nvoid readTranspose(std::map< std::string, std::map< unsigned int, isa::OpenCL::transposeConf > > & transposeParameters, const std::string & transposeFilename) {\n\tstd::string temp;\n\tstd::ifstream transposeFile(transposeFilename);\n\n\twhile ( ! transposeFile.eof() ) {\n\t\tunsigned int splitPoint = 0;\n\n\t\tstd::getline(transposeFile, temp);\n\t\tif ( ! std::isalpha(temp[0]) ) {\n\t\t\tcontinue;\n\t\t}\n\t\tstd::string deviceName;\n\t\tunsigned int nrDMs = 0;\n isa::OpenCL::transposeConf parameters;\n\n\t\tsplitPoint = temp.find(\" \");\n\t\tdeviceName = temp.substr(0, splitPoint);\n\t\ttemp = temp.substr(splitPoint + 1);\n\t\tsplitPoint = temp.find(\" \");\n\t\tnrDMs = isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint));\n\t\ttemp = temp.substr(splitPoint + 1);\n\t\tparameters.setNrItemsPerBlock(isa::utils::castToType< std::string, unsigned int >(temp));\n\n\t\tif ( transposeParameters.count(deviceName) == 0 ) {\n std::map< unsigned int, isa::OpenCL::transposeConf > container;\n\n\t\t\tcontainer.insert(std::make_pair(nrDMs, parameters));\n\t\t\ttransposeParameters.insert(std::make_pair(deviceName, container));\n\t\t} else {\n\t\t\ttransposeParameters[deviceName].insert(std::make_pair(nrDMs, parameters));\n\t\t}\n\t}\n}\n\nvoid readSNRD(std::map< std::string, std::map< unsigned int, PulsarSearch::snrDedispersedConf > > & snrParameters, const std::string & snrFilename) {\n\tstd::string temp;\n\tstd::ifstream snrFile(snrFilename);\n\n\twhile ( ! snrFile.eof() ) {\n\t\tunsigned int splitPoint = 0;\n\n\t\tstd::getline(snrFile, temp);\n\t\tif ( ! std::isalpha(temp[0]) ) {\n\t\t\tcontinue;\n\t\t}\n\t\tstd::string deviceName;\n\t\tunsigned int nrDMs = 0;\n PulsarSearch::snrDedispersedConf parameters;\n\n\t\tsplitPoint = temp.find(\" \");\n\t\tdeviceName = temp.substr(0, splitPoint);\n\t\ttemp = temp.substr(splitPoint + 1);\n\t\tsplitPoint = temp.find(\" \");\n\t\tnrDMs = isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint));\n\t\ttemp = temp.substr(splitPoint + 1);\n\t\tsplitPoint = temp.find(\" \");\n\t\tparameters.setNrDMsPerBlock(isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint)));\n\t\ttemp = temp.substr(splitPoint + 1);\n\t\tsplitPoint = temp.find(\" \");\n\t\tparameters.setNrDMsPerThread(isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint)));\n\n\t\tif ( snrParameters.count(deviceName) == 0 ) {\n std::map< unsigned int, PulsarSearch::snrDedispersedConf > container;\n\n\t\t\tcontainer.insert(std::make_pair(nrDMs, parameters));\n\t\t\tsnrParameters.insert(std::make_pair(deviceName, container));\n\t\t} else {\n\t\t\tsnrParameters[deviceName].insert(std::make_pair(nrDMs, parameters));\n\t\t}\n\t}\n}\n\nvoid readFolding(std::map< std::string, std::map< unsigned int, std::map< unsigned int, PulsarSearch::FoldingConf > > > & foldingParameters, const std::string & foldingFilename) {\n\tstd::string temp;\n\tstd::ifstream foldingFile(foldingFilename);\n\n\twhile ( ! foldingFile.eof() ) {\n\t\tunsigned int splitPoint = 0;\n\n\t\tstd::getline(foldingFile, temp);\n\t\tif ( ! std::isalpha(temp[0]) ) {\n\t\t\tcontinue;\n\t\t}\n\t\tstd::string deviceName;\n\t\tunsigned int nrDMs = 0;\n\t\tunsigned int nrPeriods = 0;\n PulsarSearch::FoldingConf parameters;\n\n\t\tsplitPoint = temp.find(\" \");\n\t\tdeviceName = temp.substr(0, splitPoint);\n\t\ttemp = temp.substr(splitPoint + 1);\n\t\tsplitPoint = temp.find(\" \");\n\t\tnrDMs = isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint));\n\t\ttemp = temp.substr(splitPoint + 1);\n\t\tsplitPoint = temp.find(\" \");\n\t\tnrPeriods = isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint));\n\t\ttemp = temp.substr(splitPoint + 1);\n\t\tsplitPoint = temp.find(\" \");\n\t\tparameters.setNrDMsPerBlock(isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint)));\n\t\ttemp = temp.substr(splitPoint + 1);\n\t\tsplitPoint = temp.find(\" \");\n\t\tparameters.setNrPeriodsPerBlock(isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint)));\n\t\ttemp = temp.substr(splitPoint + 1);\n\t\tsplitPoint = temp.find(\" \");\n\t\tparameters.setNrBinsPerBlock(isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint)));\n\t\ttemp = temp.substr(splitPoint + 1);\n\t\tsplitPoint = temp.find(\" \");\n\t\tparameters.setNrDMsPerThread(isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint)));\n\t\ttemp = temp.substr(splitPoint + 1);\n\t\tsplitPoint = temp.find(\" \");\n\t\tparameters.setNrPeriodsPerThread(isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint)));\n\t\ttemp = temp.substr(splitPoint + 1);\n\t\tsplitPoint = temp.find(\" \");\n\t\tparameters.setNrBinsPerThread(isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint)));\n\t\ttemp = temp.substr(splitPoint + 1);\n\t\tparameters.setVector(isa::utils::castToType< std::string, unsigned int >(temp));\n\n\t\tif ( foldingParameters.count(deviceName) == 0 ) {\n std::map< unsigned int, std::map< unsigned int, PulsarSearch::FoldingConf > > externalContainer;\n std::map< unsigned int, PulsarSearch::FoldingConf > internalContainer;\n\n\t\t\tinternalContainer.insert(std::make_pair(nrPeriods, parameters));\n\t\t\texternalContainer.insert(std::make_pair(nrDMs, internalContainer));\n\t\t\tfoldingParameters.insert(std::make_pair(deviceName, externalContainer));\n\t\t} else if ( foldingParameters[deviceName].count(nrDMs) == 0 ) {\n std::map< unsigned int, std::vector< unsigned int > > internalContainer;\n\n\t\t\tinternalContainer.insert(std::make_pair(nrPeriods, parameters));\n\t\t\tfoldingParameters[deviceName].insert(std::make_pair(nrDMs, internalContainer));\n\t\t} else {\n\t\t\tfoldingParameters[deviceName][nrDMs].insert(std::make_pair(nrPeriods, parameters));\n\t\t}\n\t}\n}\n\nvoid readSNRF(std::map< std::string, std::map< unsigned int, std::map< unsigned int, PulsarSearch::snrFoldedConf > > > & snrParameters, const std::string & snrFilename) {\n\tstd::string temp;\n\tstd::ifstream snrFile(snrFilename);\n\n\twhile ( ! snrFile.eof() ) {\n\t\tunsigned int splitPoint = 0;\n\n\t\tstd::getline(snrFile, temp);\n\t\tif ( ! std::isalpha(temp[0]) ) {\n\t\t\tcontinue;\n\t\t}\n\t\tstd::string deviceName;\n\t\tunsigned int nrDMs = 0;\n\t\tunsigned int nrPeriods = 0;\n PulsarSearch::snrFoldedConf parameters;\n\n\t\tsplitPoint = temp.find(\" \");\n\t\tdeviceName = temp.substr(0, splitPoint);\n\t\ttemp = temp.substr(splitPoint + 1);\n\t\tsplitPoint = temp.find(\" \");\n\t\tnrDMs = isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint));\n\t\ttemp = temp.substr(splitPoint + 1);\n\t\tsplitPoint = temp.find(\" \");\n\t\tnrPeriods = isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint));\n\t\ttemp = temp.substr(splitPoint + 1);\n\t\tsplitPoint = temp.find(\" \");\n\t\tparameters.setNrDMsPerBlock(isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint)));\n\t\ttemp = temp.substr(splitPoint + 1);\n\t\tsplitPoint = temp.find(\" \");\n\t\tparameters.setNrPeriodsPerBlock(isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint)));\n\t\ttemp = temp.substr(splitPoint + 1);\n\t\tsplitPoint = temp.find(\" \");\n\t\tparameters.setNrDMsPerThread(isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint)));\n\t\ttemp = temp.substr(splitPoint + 1);\n\t\tparameters.setNrPeriodsPerThread(isa::utils::castToType< std::string, unsigned int >(temp));\n\n\t\tif ( snrParameters.count(deviceName) == 0 ) {\n std::map< unsigned int, std::map< unsigned int, PulsarSearch::snrFoldedConf > > externalContainer;\n std::map< unsigned int, PulsarSearch::snrFoldedConf > internalContainer;\n\n\t\t\tinternalContainer.insert(std::make_pair(nrPeriods, parameters));\n\t\t\texternalContainer.insert(std::make_pair(nrDMs, internalContainer));\n\t\t\tsnrParameters.insert(std::make_pair(deviceName, externalContainer));\n\t\t} else if ( snrParameters[deviceName].count(nrDMs) == 0 ) {\n std::map< unsigned int, std::vector< unsigned int > > internalContainer;\n\n\t\t\tinternalContainer.insert(std::make_pair(nrPeriods, parameters));\n\t\t\tsnrParameters[deviceName].insert(std::make_pair(nrDMs, internalContainer));\n\t\t} else {\n\t\t\tsnrParameters[deviceName][nrDMs].insert(std::make_pair(nrPeriods, parameters));\n\t\t}\n\t}\n}\n\n<commit_msg>Fixing bugs.<commit_after>\/\/ Copyright 2013 Alessio Sclocco <a.sclocco@vu.nl>\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include <string>\n#include <fstream>\n#include <map>\n#include <cctype>\n\n#include <readConfiguration.hpp>\n#include <utils.hpp>\n\n\nvoid readPadding(std::map< std::string, unsigned int > & padding, const std::string & paddingFilename) {\n\tstd::string temp;\n\tstd::ifstream paddingFile(paddingFilename);\n\n\twhile ( ! paddingFile.eof() ) {\n\t\tunsigned int middle = 0;\n\n\t\tstd::getline(paddingFile, temp);\n\t\tif ( ! std::isalpha(temp[0]) ) {\n\t\t\tcontinue;\n\t\t}\n\t\tmiddle = temp.find(\" \");\n\t\tpadding.insert(std::make_pair(temp.substr(0, middle), isa::utils::castToType< std::string, unsigned int >(temp.substr(middle + 1))));\n\t}\n}\n\nvoid readVectorWidth(std::map< std::string, unsigned int > & vectorWidth, const std::string & vectorFilename) {\n\tstd::string temp;\n\tstd::ifstream vectorFile(vectorFilename);\n\n\twhile ( ! vectorFile.eof() ) {\n\t\tunsigned int middle = 0;\n\n\t\tstd::getline(vectorFile, temp);\n\t\tif ( ! std::isalpha(temp[0]) ) {\n\t\t\tcontinue;\n\t\t}\n\t\tmiddle = temp.find(\" \");\n\t\tvectorWidth.insert(std::make_pair(temp.substr(0, middle), isa::utils::castToType< std::string, unsigned int >(temp.substr(middle + 1))));\n\t}\n}\n\nvoid readDedispersion(std::map< std::string, std::map< unsigned int, PulsarSearch::DedispersionConf > > & dedispersionParameters, const std::string & dedispersionFilename) {\n\tstd::string temp;\n\tstd::ifstream dedispersionFile(dedispersionFilename);\n\n\twhile ( ! dedispersionFile.eof() ) {\n\t\tunsigned int splitPoint = 0;\n\n\t\tstd::getline(dedispersionFile, temp);\n\t\tif ( ! std::isalpha(temp[0]) ) {\n\t\t\tcontinue;\n\t\t}\n\t\tstd::string deviceName;\n\t\tunsigned int nrDMs = 0;\n PulsarSearch::DedispersionConf conf;\n\n\t\tsplitPoint = temp.find(\" \");\n\t\tdeviceName = temp.substr(0, splitPoint);\n\t\ttemp = temp.substr(splitPoint + 1);\n\t\tsplitPoint = temp.find(\" \");\n\t\tnrDMs = isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint));\n\t\ttemp = temp.substr(splitPoint + 1);\n\t\tsplitPoint = temp.find(\" \");\n\t\tconf.setLocalMem(isa::utils::castToType< std::string, bool >(temp.substr(0, splitPoint)));\n\t\ttemp = temp.substr(splitPoint + 1);\n\t\tsplitPoint = temp.find(\" \");\n\t\tconf.setUnroll(isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint)));\n\t\ttemp = temp.substr(splitPoint + 1);\n\t\tsplitPoint = temp.find(\" \");\n\t\tconf.setNrSamplesPerBlock(isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint)));\n\t\ttemp = temp.substr(splitPoint + 1);\n\t\tsplitPoint = temp.find(\" \");\n\t\tconf.setNrDMsPerBlock(isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint)));\n\t\ttemp = temp.substr(splitPoint + 1);\n\t\tsplitPoint = temp.find(\" \");\n\t\tconf.setNrSamplesPerThread(isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint)));\n\t\ttemp = temp.substr(splitPoint + 1);\n\t\tconf.setNrDMsPerThread(isa::utils::castToType< std::string, unsigned int >(temp));\n\n\t\tif ( dedispersionParameters.count(deviceName) == 0 ) {\n std::map< unsigned int, PulsarSearch::DedispersionConf > container;\n\n\t\t\tcontainer.insert(std::make_pair(nrDMs, conf));\n\t\t\tdedispersionParameters.insert(std::make_pair(deviceName, container));\n\t\t} else {\n\t\t\tdedispersionParameters[deviceName].insert(std::make_pair(nrDMs, conf));\n\t\t}\n\t}\n}\n\nvoid readTranspose(std::map< std::string, std::map< unsigned int, isa::OpenCL::transposeConf > > & transposeParameters, const std::string & transposeFilename) {\n\tstd::string temp;\n\tstd::ifstream transposeFile(transposeFilename);\n\n\twhile ( ! transposeFile.eof() ) {\n\t\tunsigned int splitPoint = 0;\n\n\t\tstd::getline(transposeFile, temp);\n\t\tif ( ! std::isalpha(temp[0]) ) {\n\t\t\tcontinue;\n\t\t}\n\t\tstd::string deviceName;\n\t\tunsigned int nrDMs = 0;\n isa::OpenCL::transposeConf parameters;\n\n\t\tsplitPoint = temp.find(\" \");\n\t\tdeviceName = temp.substr(0, splitPoint);\n\t\ttemp = temp.substr(splitPoint + 1);\n\t\tsplitPoint = temp.find(\" \");\n\t\tnrDMs = isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint));\n\t\ttemp = temp.substr(splitPoint + 1);\n\t\tparameters.setNrItemsPerBlock(isa::utils::castToType< std::string, unsigned int >(temp));\n\n\t\tif ( transposeParameters.count(deviceName) == 0 ) {\n std::map< unsigned int, isa::OpenCL::transposeConf > container;\n\n\t\t\tcontainer.insert(std::make_pair(nrDMs, parameters));\n\t\t\ttransposeParameters.insert(std::make_pair(deviceName, container));\n\t\t} else {\n\t\t\ttransposeParameters[deviceName].insert(std::make_pair(nrDMs, parameters));\n\t\t}\n\t}\n}\n\nvoid readSNRD(std::map< std::string, std::map< unsigned int, PulsarSearch::snrDedispersedConf > > & snrParameters, const std::string & snrFilename) {\n\tstd::string temp;\n\tstd::ifstream snrFile(snrFilename);\n\n\twhile ( ! snrFile.eof() ) {\n\t\tunsigned int splitPoint = 0;\n\n\t\tstd::getline(snrFile, temp);\n\t\tif ( ! std::isalpha(temp[0]) ) {\n\t\t\tcontinue;\n\t\t}\n\t\tstd::string deviceName;\n\t\tunsigned int nrDMs = 0;\n PulsarSearch::snrDedispersedConf parameters;\n\n\t\tsplitPoint = temp.find(\" \");\n\t\tdeviceName = temp.substr(0, splitPoint);\n\t\ttemp = temp.substr(splitPoint + 1);\n\t\tsplitPoint = temp.find(\" \");\n\t\tnrDMs = isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint));\n\t\ttemp = temp.substr(splitPoint + 1);\n\t\tsplitPoint = temp.find(\" \");\n\t\tparameters.setNrDMsPerBlock(isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint)));\n\t\ttemp = temp.substr(splitPoint + 1);\n\t\tsplitPoint = temp.find(\" \");\n\t\tparameters.setNrDMsPerThread(isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint)));\n\n\t\tif ( snrParameters.count(deviceName) == 0 ) {\n std::map< unsigned int, PulsarSearch::snrDedispersedConf > container;\n\n\t\t\tcontainer.insert(std::make_pair(nrDMs, parameters));\n\t\t\tsnrParameters.insert(std::make_pair(deviceName, container));\n\t\t} else {\n\t\t\tsnrParameters[deviceName].insert(std::make_pair(nrDMs, parameters));\n\t\t}\n\t}\n}\n\nvoid readFolding(std::map< std::string, std::map< unsigned int, std::map< unsigned int, PulsarSearch::FoldingConf > > > & foldingParameters, const std::string & foldingFilename) {\n\tstd::string temp;\n\tstd::ifstream foldingFile(foldingFilename);\n\n\twhile ( ! foldingFile.eof() ) {\n\t\tunsigned int splitPoint = 0;\n\n\t\tstd::getline(foldingFile, temp);\n\t\tif ( ! std::isalpha(temp[0]) ) {\n\t\t\tcontinue;\n\t\t}\n\t\tstd::string deviceName;\n\t\tunsigned int nrDMs = 0;\n\t\tunsigned int nrPeriods = 0;\n PulsarSearch::FoldingConf parameters;\n\n\t\tsplitPoint = temp.find(\" \");\n\t\tdeviceName = temp.substr(0, splitPoint);\n\t\ttemp = temp.substr(splitPoint + 1);\n\t\tsplitPoint = temp.find(\" \");\n\t\tnrDMs = isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint));\n\t\ttemp = temp.substr(splitPoint + 1);\n\t\tsplitPoint = temp.find(\" \");\n\t\tnrPeriods = isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint));\n\t\ttemp = temp.substr(splitPoint + 1);\n\t\tsplitPoint = temp.find(\" \");\n\t\tparameters.setNrDMsPerBlock(isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint)));\n\t\ttemp = temp.substr(splitPoint + 1);\n\t\tsplitPoint = temp.find(\" \");\n\t\tparameters.setNrPeriodsPerBlock(isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint)));\n\t\ttemp = temp.substr(splitPoint + 1);\n\t\tsplitPoint = temp.find(\" \");\n\t\tparameters.setNrBinsPerBlock(isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint)));\n\t\ttemp = temp.substr(splitPoint + 1);\n\t\tsplitPoint = temp.find(\" \");\n\t\tparameters.setNrDMsPerThread(isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint)));\n\t\ttemp = temp.substr(splitPoint + 1);\n\t\tsplitPoint = temp.find(\" \");\n\t\tparameters.setNrPeriodsPerThread(isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint)));\n\t\ttemp = temp.substr(splitPoint + 1);\n\t\tsplitPoint = temp.find(\" \");\n\t\tparameters.setNrBinsPerThread(isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint)));\n\t\ttemp = temp.substr(splitPoint + 1);\n\t\tparameters.setVector(isa::utils::castToType< std::string, unsigned int >(temp));\n\n\t\tif ( foldingParameters.count(deviceName) == 0 ) {\n std::map< unsigned int, std::map< unsigned int, PulsarSearch::FoldingConf > > externalContainer;\n std::map< unsigned int, PulsarSearch::FoldingConf > internalContainer;\n\n\t\t\tinternalContainer.insert(std::make_pair(nrPeriods, parameters));\n\t\t\texternalContainer.insert(std::make_pair(nrDMs, internalContainer));\n\t\t\tfoldingParameters.insert(std::make_pair(deviceName, externalContainer));\n\t\t} else if ( foldingParameters[deviceName].count(nrDMs) == 0 ) {\n std::map< unsigned int, PulsarSearch::FoldingConf > internalContainer;\n\n\t\t\tinternalContainer.insert(std::make_pair(nrPeriods, parameters));\n\t\t\tfoldingParameters[deviceName].insert(std::make_pair(nrDMs, internalContainer));\n\t\t} else {\n\t\t\tfoldingParameters[deviceName][nrDMs].insert(std::make_pair(nrPeriods, parameters));\n\t\t}\n\t}\n}\n\nvoid readSNRF(std::map< std::string, std::map< unsigned int, std::map< unsigned int, PulsarSearch::snrFoldedConf > > > & snrParameters, const std::string & snrFilename) {\n\tstd::string temp;\n\tstd::ifstream snrFile(snrFilename);\n\n\twhile ( ! snrFile.eof() ) {\n\t\tunsigned int splitPoint = 0;\n\n\t\tstd::getline(snrFile, temp);\n\t\tif ( ! std::isalpha(temp[0]) ) {\n\t\t\tcontinue;\n\t\t}\n\t\tstd::string deviceName;\n\t\tunsigned int nrDMs = 0;\n\t\tunsigned int nrPeriods = 0;\n PulsarSearch::snrFoldedConf parameters;\n\n\t\tsplitPoint = temp.find(\" \");\n\t\tdeviceName = temp.substr(0, splitPoint);\n\t\ttemp = temp.substr(splitPoint + 1);\n\t\tsplitPoint = temp.find(\" \");\n\t\tnrDMs = isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint));\n\t\ttemp = temp.substr(splitPoint + 1);\n\t\tsplitPoint = temp.find(\" \");\n\t\tnrPeriods = isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint));\n\t\ttemp = temp.substr(splitPoint + 1);\n\t\tsplitPoint = temp.find(\" \");\n\t\tparameters.setNrDMsPerBlock(isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint)));\n\t\ttemp = temp.substr(splitPoint + 1);\n\t\tsplitPoint = temp.find(\" \");\n\t\tparameters.setNrPeriodsPerBlock(isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint)));\n\t\ttemp = temp.substr(splitPoint + 1);\n\t\tsplitPoint = temp.find(\" \");\n\t\tparameters.setNrDMsPerThread(isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint)));\n\t\ttemp = temp.substr(splitPoint + 1);\n\t\tparameters.setNrPeriodsPerThread(isa::utils::castToType< std::string, unsigned int >(temp));\n\n\t\tif ( snrParameters.count(deviceName) == 0 ) {\n std::map< unsigned int, std::map< unsigned int, PulsarSearch::snrFoldedConf > > externalContainer;\n std::map< unsigned int, PulsarSearch::snrFoldedConf > internalContainer;\n\n\t\t\tinternalContainer.insert(std::make_pair(nrPeriods, parameters));\n\t\t\texternalContainer.insert(std::make_pair(nrDMs, internalContainer));\n\t\t\tsnrParameters.insert(std::make_pair(deviceName, externalContainer));\n\t\t} else if ( snrParameters[deviceName].count(nrDMs) == 0 ) {\n std::map< unsigned int, PulsarSearch::snrFoldedConf > internalContainer;\n\n\t\t\tinternalContainer.insert(std::make_pair(nrPeriods, parameters));\n\t\t\tsnrParameters[deviceName].insert(std::make_pair(nrDMs, internalContainer));\n\t\t} else {\n\t\t\tsnrParameters[deviceName][nrDMs].insert(std::make_pair(nrPeriods, parameters));\n\t\t}\n\t}\n}\n\n<|endoftext|>"} {"text":"<commit_before>\/*************************************************************************\n *\n * REALM CONFIDENTIAL\n * __________________\n *\n * [2011] - [2015] Realm Inc\n * All Rights Reserved.\n *\n * NOTICE: All information contained herein is, and remains\n * the property of Realm Incorporated and its suppliers,\n * if any. The intellectual and technical concepts contained\n * herein are proprietary to Realm Incorporated\n * and its suppliers and may be covered by U.S. and Foreign Patents,\n * patents in process, and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Realm Incorporated.\n *\n **************************************************************************\/\n#ifndef REALM_UTIL_LOGGER_HPP\n#define REALM_UTIL_LOGGER_HPP\n\n#include <string.h>\n#include <utility>\n#include <string>\n#include <locale>\n#include <sstream>\n#include <iostream>\n\n#include <realm\/util\/features.h>\n#include <realm\/util\/tuple.hpp>\n#include <realm\/util\/thread.hpp>\n#include <realm\/util\/file.hpp>\n\nnamespace realm {\nnamespace util {\n\n\n\/\/\/ All Logger objects store a reference to a LevelThreshold object which it\n\/\/\/ uses to efficiently query about the current log level threshold\n\/\/\/ (`level_threshold.get()`). All messages logged with a level that is lower\n\/\/\/ than the current threshold will be dropped. For the sake of efficiency, this\n\/\/\/ test happens before the message is formatted.\n\/\/\/\n\/\/\/ A logger is not inherently thread-safe, but specific implementations can be\n\/\/\/ (see ThreadSafeLogger). For a logger to be thread-safe, the implementation\n\/\/\/ of do_log() must be thread-safe and the referenced LevelThreshold object\n\/\/\/ must have a thread-safe get() method.\n\/\/\/\n\/\/\/ Examples:\n\/\/\/\n\/\/\/ logger.error(\"Overlong message from master coordinator\");\n\/\/\/ logger.info(\"Listening for peers on %1:%2\", listen_address, listen_port);\nclass Logger {\npublic:\n template<class... Params> void trace(const char* message, Params...);\n template<class... Params> void debug(const char* message, Params...);\n template<class... Params> void detail(const char* message, Params...);\n template<class... Params> void info(const char* message, Params...);\n template<class... Params> void warn(const char* message, Params...);\n template<class... Params> void error(const char* message, Params...);\n template<class... Params> void fatal(const char* message, Params...);\n\n \/\/\/ Specifies criticality when passed to log(). Functions as a criticality\n \/\/\/ threshold when returned from LevelThreshold::get().\n enum class Level { all, trace, debug, detail, info, warn, error, fatal, off };\n\n template<class... Params> void log(Level, const char* message, Params...);\n\n \/\/\/ Shorthand for `int(level) >= int(level_threshold.get())`.\n bool would_log(Level level) const noexcept;\n\n class LevelThreshold;\n\n const LevelThreshold& level_threshold;\n\n virtual ~Logger() noexcept;\n\nprotected:\n Logger(const LevelThreshold&) noexcept;\n\n static void do_log(Logger&, std::string message);\n\n virtual void do_log(std::string message) = 0;\n\nprivate:\n struct State;\n template<class> struct Subst;\n\n template<class... Params> REALM_NOINLINE void do_log(Level, const char* message, Params...);\n void log_impl(State&);\n template<class Param, class... Params> void log_impl(State&, const Param&, Params...);\n};\n\ntemplate<class C, class T>\nstd::basic_ostream<C,T>& operator<<(std::basic_ostream<C,T>&, Logger::Level);\n\ntemplate<class C, class T>\nstd::basic_istream<C,T>& operator>>(std::basic_istream<C,T>&, Logger::Level&);\n\nclass Logger::LevelThreshold {\npublic:\n virtual Level get() const noexcept = 0;\n};\n\n\n\n\/\/\/ A root logger that is not thread-safe and allows for the log level threshold\n\/\/\/ to be changed over time. The initial log level threshold is\n\/\/\/ Logger::Level::info.\nclass RootLogger: private Logger::LevelThreshold, public Logger {\npublic:\n void set_level_threshold(Level) noexcept;\n\nprotected:\n RootLogger();\n\nprivate:\n Level m_level_threshold = Level::info;\n Level get() const noexcept override final;\n};\n\n\n\/\/\/ A logger that writes to STDERR. This logger is not thread-safe.\nclass StderrLogger: public RootLogger {\nprotected:\n void do_log(std::string) override final;\n};\n\n\n\n\/\/\/ A logger that writes to a stream. This logger is not thread-safe.\nclass StreamLogger: public RootLogger {\npublic:\n explicit StreamLogger(std::ostream&) noexcept;\n\nprotected:\n void do_log(std::string) override final;\n\nprivate:\n std::ostream& m_out;\n};\n\n\n\n\/\/\/ A logger that writes to a file. This logger is not thread-safe.\nclass FileLogger: public StreamLogger {\npublic:\n explicit FileLogger(std::string path);\n explicit FileLogger(util::File);\n\nprivate:\n util::File m_file;\n util::File::Streambuf m_streambuf;\n std::ostream m_out;\n};\n\n\n\n\/\/\/ A thread-safe logger. This logger ignores the level threshold of the base\n\/\/\/ logger. Instead, it introduces new a LevelThreshold object with a fixed\n\/\/\/ value to achieve thread safety.\nclass ThreadSafeLogger: private Logger::LevelThreshold, public Logger {\npublic:\n explicit ThreadSafeLogger(Logger& base_logger, Level = Level::info);\n\nprotected:\n void do_log(std::string) override final;\n\nprivate:\n const Level m_level_threshold; \/\/ Immutable for thread safety\n Logger& m_base_logger;\n Mutex m_mutex;\n Level get() const noexcept override final;\n};\n\n\n\n\/\/\/ A logger that adds a fixed prefix to each message. This logger inherits the\n\/\/\/ LevelThreshold object of the specified base logger. This logger is\n\/\/\/ thread-safe if, and only if the base logger is thread-safe.\nclass PrefixLogger: public Logger {\npublic:\n PrefixLogger(std::string prefix, Logger& base_logger) noexcept;\n\nprotected:\n void do_log(std::string) override final;\n\nprivate:\n const std::string m_prefix;\n Logger& m_base_logger;\n};\n\n\n\n\n\/\/ Implementation\n\nstruct Logger::State {\n std::string m_message;\n std::string m_search;\n int m_param_num = 1;\n std::ostringstream m_formatter;\n State(const char* s):\n m_message(s),\n m_search(m_message)\n {\n m_formatter.imbue(std::locale::classic());\n }\n};\n\ntemplate<class T> struct Logger::Subst {\n void operator()(const T& param, State* state)\n {\n state->m_formatter << \"%\" << state->m_param_num;\n std::string key = state->m_formatter.str();\n state->m_formatter.str(std::string());\n std::string::size_type j = state->m_search.find(key);\n if (j != std::string::npos) {\n state->m_formatter << param;\n std::string str = state->m_formatter.str();\n state->m_formatter.str(std::string());\n state->m_message.replace(j, key.size(), str);\n state->m_search.replace(j, key.size(), std::string(str.size(), '\\0'));\n }\n ++state->m_param_num;\n }\n};\n\ntemplate<class... Params> inline void Logger::trace(const char* message, Params... params)\n{\n log(Level::trace, message, params...); \/\/ Throws\n}\n\ntemplate<class... Params> inline void Logger::debug(const char* message, Params... params)\n{\n log(Level::debug, message, params...); \/\/ Throws\n}\n\ntemplate<class... Params> inline void Logger::detail(const char* message, Params... params)\n{\n log(Level::detail, message, params...); \/\/ Throws\n}\n\ntemplate<class... Params> inline void Logger::info(const char* message, Params... params)\n{\n log(Level::info, message, params...); \/\/ Throws\n}\n\ntemplate<class... Params> inline void Logger::warn(const char* message, Params... params)\n{\n log(Level::warn, message, params...); \/\/ Throws\n}\n\ntemplate<class... Params> inline void Logger::error(const char* message, Params... params)\n{\n log(Level::error, message, params...); \/\/ Throws\n}\n\ntemplate<class... Params> inline void Logger::fatal(const char* message, Params... params)\n{\n log(Level::fatal, message, params...); \/\/ Throws\n}\n\ntemplate<class... Params>\ninline void Logger::log(Level level, const char* message, Params... params)\n{\n if (would_log(level))\n do_log(level, message, params...); \/\/ Throws\n}\n\ninline bool Logger::would_log(Level level) const noexcept\n{\n return int(level) >= int(level_threshold.get());\n}\n\ninline Logger::~Logger() noexcept\n{\n}\n\ninline Logger::Logger(const LevelThreshold& lt) noexcept:\n level_threshold(lt)\n{\n}\n\ninline void Logger::do_log(Logger& logger, std::string message)\n{\n logger.do_log(std::move(message));\n}\n\ntemplate<class... Params> void Logger::do_log(Level, const char* message, Params... params)\n{\n State state(message);\n log_impl(state, params...);\n}\n\ninline void Logger::log_impl(State& state)\n{\n do_log(std::move(state.m_message));\n}\n\ntemplate<class Param, class... Params>\ninline void Logger::log_impl(State& state, const Param& param, Params... params)\n{\n Subst<Param>()(param, &state);\n log_impl(state, params...);\n}\n\ntemplate<class C, class T>\nstd::basic_ostream<C,T>& operator<<(std::basic_ostream<C,T>& out, Logger::Level level)\n{\n switch(level) {\n case Logger::Level::all:\n out << \"all\";\n return out;\n case Logger::Level::trace:\n out << \"trace\";\n return out;\n case Logger::Level::debug:\n out << \"debug\";\n return out;\n case Logger::Level::detail:\n out << \"detail\";\n return out;\n case Logger::Level::info:\n out << \"info\";\n return out;\n case Logger::Level::warn:\n out << \"warn\";\n return out;\n case Logger::Level::error:\n out << \"error\";\n return out;\n case Logger::Level::fatal:\n out << \"fatal\";\n return out;\n case Logger::Level::off:\n out << \"off\";\n return out;\n }\n REALM_ASSERT(false);\n return out;\n}\n\ntemplate<class C, class T>\nstd::basic_istream<C,T>& operator>>(std::basic_istream<C,T>& in, Logger::Level& level)\n{\n std::basic_string<C,T> str;\n auto check = [&](const char* name) {\n size_t n = strlen(name);\n if (n != str.size())\n return false;\n for (size_t i = 0; i < n; ++i) {\n if (in.widen(name[i]) != str[i])\n return false;\n }\n return true;\n };\n if (in >> str) {\n if (check(\"all\")) {\n level = Logger::Level::all;\n }\n else if (check(\"trace\")) {\n level = Logger::Level::trace;\n }\n else if (check(\"debug\")) {\n level = Logger::Level::debug;\n }\n else if (check(\"detail\")) {\n level = Logger::Level::detail;\n }\n else if (check(\"info\")) {\n level = Logger::Level::info;\n }\n else if (check(\"warn\")) {\n level = Logger::Level::warn;\n }\n else if (check(\"error\")) {\n level = Logger::Level::error;\n }\n else if (check(\"fatal\")) {\n level = Logger::Level::fatal;\n }\n else if (check(\"off\")) {\n level = Logger::Level::off;\n }\n else {\n in.setstate(std::ios_base::failbit);\n }\n }\n return in;\n}\n\ninline void RootLogger::set_level_threshold(Level level_threshold) noexcept\n{\n m_level_threshold = level_threshold;\n}\n\ninline RootLogger::RootLogger():\n Logger::LevelThreshold(),\n Logger(static_cast<Logger::LevelThreshold&>(*this))\n{\n}\n\ninline Logger::Level RootLogger::get() const noexcept\n{\n return m_level_threshold;\n}\n\ninline void StderrLogger::do_log(std::string message)\n{\n std::cerr << message << '\\n'; \/\/ Throws\n std::cerr.flush(); \/\/ Throws\n}\n\ninline StreamLogger::StreamLogger(std::ostream& out) noexcept:\n m_out(out)\n{\n}\n\ninline void StreamLogger::do_log(std::string message)\n{\n m_out << message << '\\n'; \/\/ Throws\n m_out.flush(); \/\/ Throws\n}\n\ninline FileLogger::FileLogger(std::string path):\n StreamLogger(m_out),\n m_file(path, util::File::mode_Write), \/\/ Throws\n m_streambuf(&m_file), \/\/ Throws\n m_out(&m_streambuf) \/\/ Throws\n{\n}\n\ninline FileLogger::FileLogger(util::File file):\n StreamLogger(m_out),\n m_file(std::move(file)),\n m_streambuf(&m_file), \/\/ Throws\n m_out(&m_streambuf) \/\/ Throws\n{\n}\n\ninline ThreadSafeLogger::ThreadSafeLogger(Logger& base_logger, Level level_threshold):\n Logger::LevelThreshold(),\n Logger(static_cast<Logger::LevelThreshold&>(*this)),\n m_level_threshold(level_threshold),\n m_base_logger(base_logger)\n{\n}\n\ninline void ThreadSafeLogger::do_log(std::string message)\n{\n LockGuard l(m_mutex);\n Logger::do_log(m_base_logger, message); \/\/ Throws\n}\n\ninline Logger::Level ThreadSafeLogger::get() const noexcept\n{\n return m_level_threshold;\n}\n\ninline PrefixLogger::PrefixLogger(std::string prefix, Logger& base_logger) noexcept:\n Logger(base_logger.level_threshold),\n m_prefix(std::move(prefix)),\n m_base_logger(base_logger)\n{\n}\n\ninline void PrefixLogger::do_log(std::string message)\n{\n Logger::do_log(m_base_logger, m_prefix + message); \/\/ Throws\n}\n\n} \/\/ namespace util\n} \/\/ namespace realm\n\n#endif \/\/ REALM_UTIL_LOGGER_HPP\n<commit_msg>Improvement of util::Logger documentation<commit_after>\/*************************************************************************\n *\n * REALM CONFIDENTIAL\n * __________________\n *\n * [2011] - [2015] Realm Inc\n * All Rights Reserved.\n *\n * NOTICE: All information contained herein is, and remains\n * the property of Realm Incorporated and its suppliers,\n * if any. The intellectual and technical concepts contained\n * herein are proprietary to Realm Incorporated\n * and its suppliers and may be covered by U.S. and Foreign Patents,\n * patents in process, and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Realm Incorporated.\n *\n **************************************************************************\/\n#ifndef REALM_UTIL_LOGGER_HPP\n#define REALM_UTIL_LOGGER_HPP\n\n#include <string.h>\n#include <utility>\n#include <string>\n#include <locale>\n#include <sstream>\n#include <iostream>\n\n#include <realm\/util\/features.h>\n#include <realm\/util\/tuple.hpp>\n#include <realm\/util\/thread.hpp>\n#include <realm\/util\/file.hpp>\n\nnamespace realm {\nnamespace util {\n\n\n\/\/\/ All Logger objects store a reference to a LevelThreshold object which it\n\/\/\/ uses to efficiently query about the current log level threshold\n\/\/\/ (`level_threshold.get()`). All messages logged with a level that is lower\n\/\/\/ than the current threshold will be dropped. For the sake of efficiency, this\n\/\/\/ test happens before the message is formatted.\n\/\/\/\n\/\/\/ A logger is not inherently thread-safe, but specific implementations can be\n\/\/\/ (see ThreadSafeLogger). For a logger to be thread-safe, the implementation\n\/\/\/ of do_log() must be thread-safe and the referenced LevelThreshold object\n\/\/\/ must have a thread-safe get() method.\n\/\/\/\n\/\/\/ Examples:\n\/\/\/\n\/\/\/ logger.error(\"Overlong message from master coordinator\");\n\/\/\/ logger.info(\"Listening for peers on %1:%2\", listen_address, listen_port);\nclass Logger {\npublic:\n template<class... Params> void trace(const char* message, Params...);\n template<class... Params> void debug(const char* message, Params...);\n template<class... Params> void detail(const char* message, Params...);\n template<class... Params> void info(const char* message, Params...);\n template<class... Params> void warn(const char* message, Params...);\n template<class... Params> void error(const char* message, Params...);\n template<class... Params> void fatal(const char* message, Params...);\n\n \/\/\/ Specifies criticality when passed to log(). Functions as a criticality\n \/\/\/ threshold when returned from LevelThreshold::get().\n enum class Level { all, trace, debug, detail, info, warn, error, fatal, off };\n\n template<class... Params> void log(Level, const char* message, Params...);\n\n \/\/\/ Shorthand for `int(level) >= int(level_threshold.get())`.\n bool would_log(Level level) const noexcept;\n\n class LevelThreshold;\n\n const LevelThreshold& level_threshold;\n\n virtual ~Logger() noexcept;\n\nprotected:\n Logger(const LevelThreshold&) noexcept;\n\n static void do_log(Logger&, std::string message);\n\n virtual void do_log(std::string message) = 0;\n\nprivate:\n struct State;\n template<class> struct Subst;\n\n template<class... Params> REALM_NOINLINE void do_log(Level, const char* message, Params...);\n void log_impl(State&);\n template<class Param, class... Params> void log_impl(State&, const Param&, Params...);\n};\n\ntemplate<class C, class T>\nstd::basic_ostream<C,T>& operator<<(std::basic_ostream<C,T>&, Logger::Level);\n\ntemplate<class C, class T>\nstd::basic_istream<C,T>& operator>>(std::basic_istream<C,T>&, Logger::Level&);\n\nclass Logger::LevelThreshold {\npublic:\n virtual Level get() const noexcept = 0;\n};\n\n\n\n\/\/\/ A root logger that is not thread-safe and allows for the log level threshold\n\/\/\/ to be changed over time. The initial log level threshold is\n\/\/\/ Logger::Level::info.\nclass RootLogger: private Logger::LevelThreshold, public Logger {\npublic:\n void set_level_threshold(Level) noexcept;\n\nprotected:\n RootLogger();\n\nprivate:\n Level m_level_threshold = Level::info;\n Level get() const noexcept override final;\n};\n\n\n\/\/\/ A logger that writes to STDERR. This logger is not thread-safe.\n\/\/\/\n\/\/\/ Since this class is a RootLogger, it contains modifiable a log level\n\/\/\/ threshold.\nclass StderrLogger: public RootLogger {\nprotected:\n void do_log(std::string) override final;\n};\n\n\n\n\/\/\/ A logger that writes to a stream. This logger is not thread-safe.\n\/\/\/\n\/\/\/ Since this class is a RootLogger, it contains modifiable a log level\n\/\/\/ threshold.\nclass StreamLogger: public RootLogger {\npublic:\n explicit StreamLogger(std::ostream&) noexcept;\n\nprotected:\n void do_log(std::string) override final;\n\nprivate:\n std::ostream& m_out;\n};\n\n\n\n\/\/\/ A logger that writes to a file. This logger is not thread-safe.\n\/\/\/\n\/\/\/ Since this class is a RootLogger, it contains modifiable a log level\n\/\/\/ threshold.\nclass FileLogger: public StreamLogger {\npublic:\n explicit FileLogger(std::string path);\n explicit FileLogger(util::File);\n\nprivate:\n util::File m_file;\n util::File::Streambuf m_streambuf;\n std::ostream m_out;\n};\n\n\n\n\/\/\/ A thread-safe logger. This logger ignores the level threshold of the base\n\/\/\/ logger. Instead, it introduces new a LevelThreshold object with a fixed\n\/\/\/ value to achieve thread safety.\nclass ThreadSafeLogger: private Logger::LevelThreshold, public Logger {\npublic:\n explicit ThreadSafeLogger(Logger& base_logger, Level = Level::info);\n\nprotected:\n void do_log(std::string) override final;\n\nprivate:\n const Level m_level_threshold; \/\/ Immutable for thread safety\n Logger& m_base_logger;\n Mutex m_mutex;\n Level get() const noexcept override final;\n};\n\n\n\n\/\/\/ A logger that adds a fixed prefix to each message. This logger inherits the\n\/\/\/ LevelThreshold object of the specified base logger. This logger is\n\/\/\/ thread-safe if, and only if the base logger is thread-safe.\nclass PrefixLogger: public Logger {\npublic:\n PrefixLogger(std::string prefix, Logger& base_logger) noexcept;\n\nprotected:\n void do_log(std::string) override final;\n\nprivate:\n const std::string m_prefix;\n Logger& m_base_logger;\n};\n\n\n\n\n\/\/ Implementation\n\nstruct Logger::State {\n std::string m_message;\n std::string m_search;\n int m_param_num = 1;\n std::ostringstream m_formatter;\n State(const char* s):\n m_message(s),\n m_search(m_message)\n {\n m_formatter.imbue(std::locale::classic());\n }\n};\n\ntemplate<class T> struct Logger::Subst {\n void operator()(const T& param, State* state)\n {\n state->m_formatter << \"%\" << state->m_param_num;\n std::string key = state->m_formatter.str();\n state->m_formatter.str(std::string());\n std::string::size_type j = state->m_search.find(key);\n if (j != std::string::npos) {\n state->m_formatter << param;\n std::string str = state->m_formatter.str();\n state->m_formatter.str(std::string());\n state->m_message.replace(j, key.size(), str);\n state->m_search.replace(j, key.size(), std::string(str.size(), '\\0'));\n }\n ++state->m_param_num;\n }\n};\n\ntemplate<class... Params> inline void Logger::trace(const char* message, Params... params)\n{\n log(Level::trace, message, params...); \/\/ Throws\n}\n\ntemplate<class... Params> inline void Logger::debug(const char* message, Params... params)\n{\n log(Level::debug, message, params...); \/\/ Throws\n}\n\ntemplate<class... Params> inline void Logger::detail(const char* message, Params... params)\n{\n log(Level::detail, message, params...); \/\/ Throws\n}\n\ntemplate<class... Params> inline void Logger::info(const char* message, Params... params)\n{\n log(Level::info, message, params...); \/\/ Throws\n}\n\ntemplate<class... Params> inline void Logger::warn(const char* message, Params... params)\n{\n log(Level::warn, message, params...); \/\/ Throws\n}\n\ntemplate<class... Params> inline void Logger::error(const char* message, Params... params)\n{\n log(Level::error, message, params...); \/\/ Throws\n}\n\ntemplate<class... Params> inline void Logger::fatal(const char* message, Params... params)\n{\n log(Level::fatal, message, params...); \/\/ Throws\n}\n\ntemplate<class... Params>\ninline void Logger::log(Level level, const char* message, Params... params)\n{\n if (would_log(level))\n do_log(level, message, params...); \/\/ Throws\n}\n\ninline bool Logger::would_log(Level level) const noexcept\n{\n return int(level) >= int(level_threshold.get());\n}\n\ninline Logger::~Logger() noexcept\n{\n}\n\ninline Logger::Logger(const LevelThreshold& lt) noexcept:\n level_threshold(lt)\n{\n}\n\ninline void Logger::do_log(Logger& logger, std::string message)\n{\n logger.do_log(std::move(message));\n}\n\ntemplate<class... Params> void Logger::do_log(Level, const char* message, Params... params)\n{\n State state(message);\n log_impl(state, params...);\n}\n\ninline void Logger::log_impl(State& state)\n{\n do_log(std::move(state.m_message));\n}\n\ntemplate<class Param, class... Params>\ninline void Logger::log_impl(State& state, const Param& param, Params... params)\n{\n Subst<Param>()(param, &state);\n log_impl(state, params...);\n}\n\ntemplate<class C, class T>\nstd::basic_ostream<C,T>& operator<<(std::basic_ostream<C,T>& out, Logger::Level level)\n{\n switch(level) {\n case Logger::Level::all:\n out << \"all\";\n return out;\n case Logger::Level::trace:\n out << \"trace\";\n return out;\n case Logger::Level::debug:\n out << \"debug\";\n return out;\n case Logger::Level::detail:\n out << \"detail\";\n return out;\n case Logger::Level::info:\n out << \"info\";\n return out;\n case Logger::Level::warn:\n out << \"warn\";\n return out;\n case Logger::Level::error:\n out << \"error\";\n return out;\n case Logger::Level::fatal:\n out << \"fatal\";\n return out;\n case Logger::Level::off:\n out << \"off\";\n return out;\n }\n REALM_ASSERT(false);\n return out;\n}\n\ntemplate<class C, class T>\nstd::basic_istream<C,T>& operator>>(std::basic_istream<C,T>& in, Logger::Level& level)\n{\n std::basic_string<C,T> str;\n auto check = [&](const char* name) {\n size_t n = strlen(name);\n if (n != str.size())\n return false;\n for (size_t i = 0; i < n; ++i) {\n if (in.widen(name[i]) != str[i])\n return false;\n }\n return true;\n };\n if (in >> str) {\n if (check(\"all\")) {\n level = Logger::Level::all;\n }\n else if (check(\"trace\")) {\n level = Logger::Level::trace;\n }\n else if (check(\"debug\")) {\n level = Logger::Level::debug;\n }\n else if (check(\"detail\")) {\n level = Logger::Level::detail;\n }\n else if (check(\"info\")) {\n level = Logger::Level::info;\n }\n else if (check(\"warn\")) {\n level = Logger::Level::warn;\n }\n else if (check(\"error\")) {\n level = Logger::Level::error;\n }\n else if (check(\"fatal\")) {\n level = Logger::Level::fatal;\n }\n else if (check(\"off\")) {\n level = Logger::Level::off;\n }\n else {\n in.setstate(std::ios_base::failbit);\n }\n }\n return in;\n}\n\ninline void RootLogger::set_level_threshold(Level level_threshold) noexcept\n{\n m_level_threshold = level_threshold;\n}\n\ninline RootLogger::RootLogger():\n Logger::LevelThreshold(),\n Logger(static_cast<Logger::LevelThreshold&>(*this))\n{\n}\n\ninline Logger::Level RootLogger::get() const noexcept\n{\n return m_level_threshold;\n}\n\ninline void StderrLogger::do_log(std::string message)\n{\n std::cerr << message << '\\n'; \/\/ Throws\n std::cerr.flush(); \/\/ Throws\n}\n\ninline StreamLogger::StreamLogger(std::ostream& out) noexcept:\n m_out(out)\n{\n}\n\ninline void StreamLogger::do_log(std::string message)\n{\n m_out << message << '\\n'; \/\/ Throws\n m_out.flush(); \/\/ Throws\n}\n\ninline FileLogger::FileLogger(std::string path):\n StreamLogger(m_out),\n m_file(path, util::File::mode_Write), \/\/ Throws\n m_streambuf(&m_file), \/\/ Throws\n m_out(&m_streambuf) \/\/ Throws\n{\n}\n\ninline FileLogger::FileLogger(util::File file):\n StreamLogger(m_out),\n m_file(std::move(file)),\n m_streambuf(&m_file), \/\/ Throws\n m_out(&m_streambuf) \/\/ Throws\n{\n}\n\ninline ThreadSafeLogger::ThreadSafeLogger(Logger& base_logger, Level level_threshold):\n Logger::LevelThreshold(),\n Logger(static_cast<Logger::LevelThreshold&>(*this)),\n m_level_threshold(level_threshold),\n m_base_logger(base_logger)\n{\n}\n\ninline void ThreadSafeLogger::do_log(std::string message)\n{\n LockGuard l(m_mutex);\n Logger::do_log(m_base_logger, message); \/\/ Throws\n}\n\ninline Logger::Level ThreadSafeLogger::get() const noexcept\n{\n return m_level_threshold;\n}\n\ninline PrefixLogger::PrefixLogger(std::string prefix, Logger& base_logger) noexcept:\n Logger(base_logger.level_threshold),\n m_prefix(std::move(prefix)),\n m_base_logger(base_logger)\n{\n}\n\ninline void PrefixLogger::do_log(std::string message)\n{\n Logger::do_log(m_base_logger, m_prefix + message); \/\/ Throws\n}\n\n} \/\/ namespace util\n} \/\/ namespace realm\n\n#endif \/\/ REALM_UTIL_LOGGER_HPP\n<|endoftext|>"} {"text":"<commit_before>\/** Implementation of the pqxx::robusttransaction class.\n *\n * pqxx::robusttransaction is a slower but safer transaction class.\n *\n * Copyright (c) 2000-2020, Jeroen T. Vermeulen.\n *\n * See COPYING for copyright license. If you did not receive a file called\n * COPYING with this source code, please notify the distributor of this\n * mistake, or contact the author.\n *\/\n#include \"pqxx-source.hxx\"\n\n#include <chrono>\n#include <cstdint>\n#include <stdexcept>\n#include <thread>\n#include <unordered_map>\n\n#include \"pqxx\/connection\"\n#include \"pqxx\/nontransaction\"\n#include \"pqxx\/result\"\n#include \"pqxx\/robusttransaction\"\n\n\nnamespace\n{\n\/\/\/ Statuses in which we may find our transaction.\n\/** There's also \"in the future,\" but it manifests as an error, not as an\n * actual status.\n *\/\nenum tx_stat\n{\n tx_unknown,\n tx_committed,\n tx_aborted,\n tx_in_progress,\n};\n\n\n\/* Super-simple string hash function: just use the initial byte.\n *\n * Happens to be a perfect hash for this case, and should be cheap to compute.\n *\/\nstruct initial_hash\n{\n size_t operator()(const std::string &x) const noexcept\n {\n return static_cast<uint8_t>(x[0]);\n }\n};\n\n\n\/\/ TODO: Is there a simple, lightweight, constexpr alternative?\nconst std::unordered_map<std::string, tx_stat, initial_hash> statuses{\n {\"committed\", tx_committed},\n {\"aborted\", tx_aborted},\n {\"in progress\", tx_in_progress},\n};\n\n\ntx_stat query_status(const std::string &xid, const std::string conn_str)\n{\n const std::string name{\"robustx-check-status\"};\n const std::string query{\"SELECT txid_status(\" + xid + \")\"};\n pqxx::connection c{conn_str};\n pqxx::nontransaction w{c, name};\n const auto row{w.exec1(query, name)};\n const auto status_text{row[0].as<std::string>()};\n if (status_text.empty())\n throw pqxx::internal_error{\"Transaction status string is empty.\"};\n const auto here{statuses.find(status_text)};\n if (here == statuses.end())\n throw pqxx::internal_error{\"Unknown transaction status: \" + status_text};\n return here->second;\n}\n} \/\/ namespace\n\n\npqxx::internal::basic_robusttransaction::basic_robusttransaction(\n connection &C, const char begin_command[]) :\n namedclass{\"robusttransaction\"},\n dbtransaction(C),\n m_conn_string{C.connection_string()}\n{\n m_backendpid = C.backendpid();\n direct_exec(begin_command);\n direct_exec(\"SELECT txid_current()\")[0][0].to(m_xid);\n}\n\n\npqxx::internal::basic_robusttransaction::~basic_robusttransaction() = default;\n\n\nvoid pqxx::internal::basic_robusttransaction::do_commit()\n{\n \/\/ Check constraints before sending the COMMIT to the database, so as to\n \/\/ minimise our in-doubt window.\n try\n {\n direct_exec(\"SET CONSTRAINTS ALL IMMEDIATE\");\n }\n catch (const std::exception &)\n {\n do_abort();\n throw;\n }\n\n \/\/ Here comes the in-doubt window. If we lose our connection here, we'll be\n \/\/ left clueless as to what happened on the backend. It may have received\n \/\/ the commit command and completed the transaction, and ended up with a\n \/\/ success it could not report back to us. Or it may have noticed the broken\n \/\/ connection and aborted the transaction. It may even still be executing\n \/\/ the commit, only to fail later.\n \/\/\n \/\/ All this uncertainty requires some special handling, and that s what makes\n \/\/ robusttransaction what it is.\n try\n {\n direct_exec(\"COMMIT\");\n\n \/\/ If we make it here, great. Normal, successful commit.\n return;\n }\n catch (const broken_connection &)\n {\n \/\/ Oops, lost connection at the crucial moment. Fall through to in-doubt\n \/\/ handling below.\n }\n catch (const std::exception &)\n {\n if (conn().is_open())\n {\n \/\/ Commit failed, for some other reason.\n do_abort();\n throw;\n }\n \/\/ Otherwise, fall through to in-doubt handling.\n }\n\n \/\/ If we get here, we're in doubt. Figure out what happened.\n\n \/\/ TODO: Make delay and attempts configurable.\n const auto delay{std::chrono::milliseconds(300)};\n const int max_attempts{500};\n static_assert(max_attempts > 0);\n\n tx_stat stat;\n for (int attempts{0}; attempts < max_attempts;\n ++attempts, std::this_thread::sleep_for(delay))\n {\n stat = tx_unknown;\n try\n {\n stat = query_status(m_xid, m_conn_string);\n }\n catch (const pqxx::broken_connection &)\n {\n \/\/ Swallow the error. Pause and retry.\n }\n switch (stat)\n {\n case tx_unknown:\n \/\/ We were unable to reconnect and query transaction status.\n \/\/ Stay in it for another attempt.\n return;\n case tx_committed:\n \/\/ Success! We're done.\n return;\n case tx_aborted:\n \/\/ Aborted. We're done.\n do_abort();\n return;\n case tx_in_progress:\n \/\/ The transaction is still running. Stick around until we know what\n \/\/ transpires.\n break;\n }\n }\n\n \/\/ Okay, this has taken too long. Give up, report in-doubt state.\n throw in_doubt_error{\n \"Transaction \" + name() + \" (with transaction ID \" + m_xid +\n \") \"\n \"lost connection while committing. It's impossible to tell whether \"\n \"it committed, or aborted, or is still running. \"\n \"Attempts to find out its outcome have failed. \"\n \"The backend process on the server had process ID \" +\n to_string(m_backendpid) +\n \". \"\n \"You may be able to check what happened to that process.\"};\n}\n\n\nvoid pqxx::internal::basic_robusttransaction::do_abort()\n{\n direct_exec(\"ROLLBACK\");\n}\n<commit_msg>Micro-optimisation.<commit_after>\/** Implementation of the pqxx::robusttransaction class.\n *\n * pqxx::robusttransaction is a slower but safer transaction class.\n *\n * Copyright (c) 2000-2020, Jeroen T. Vermeulen.\n *\n * See COPYING for copyright license. If you did not receive a file called\n * COPYING with this source code, please notify the distributor of this\n * mistake, or contact the author.\n *\/\n#include \"pqxx-source.hxx\"\n\n#include <chrono>\n#include <cstdint>\n#include <stdexcept>\n#include <thread>\n#include <unordered_map>\n\n#include \"pqxx\/connection\"\n#include \"pqxx\/nontransaction\"\n#include \"pqxx\/result\"\n#include \"pqxx\/robusttransaction\"\n\n\nnamespace\n{\n\/\/\/ Statuses in which we may find our transaction.\n\/** There's also \"in the future,\" but it manifests as an error, not as an\n * actual status.\n *\/\nenum tx_stat\n{\n tx_unknown,\n tx_committed,\n tx_aborted,\n tx_in_progress,\n};\n\n\n\/* Super-simple string hash function: just use the initial byte.\n *\n * Happens to be a perfect hash for this case, and should be cheap to compute.\n *\/\nstruct initial_hash\n{\n size_t operator()(const std::string &x) const noexcept\n {\n return static_cast<uint8_t>(x[0]);\n }\n};\n\n\n\/\/ TODO: Is there a simple, lightweight, constexpr alternative?\nconst std::unordered_map<std::string, tx_stat, initial_hash> statuses{\n {\"committed\", tx_committed},\n {\"aborted\", tx_aborted},\n {\"in progress\", tx_in_progress},\n};\n\n\ntx_stat query_status(const std::string &xid, const std::string &conn_str)\n{\n static const std::string name{\"robusttxck\"};\n const std::string query{\"SELECT txid_status(\" + xid + \")\"};\n pqxx::connection c{conn_str};\n pqxx::nontransaction w{c, name};\n const auto row{w.exec1(query, name)};\n const auto status_text{row[0].as<std::string>()};\n if (status_text.empty())\n throw pqxx::internal_error{\"Transaction status string is empty.\"};\n const auto here{statuses.find(status_text)};\n if (here == statuses.end())\n throw pqxx::internal_error{\"Unknown transaction status: \" + status_text};\n return here->second;\n}\n} \/\/ namespace\n\n\npqxx::internal::basic_robusttransaction::basic_robusttransaction(\n connection &C, const char begin_command[]) :\n namedclass{\"robusttransaction\"},\n dbtransaction(C),\n m_conn_string{C.connection_string()}\n{\n m_backendpid = C.backendpid();\n direct_exec(begin_command);\n direct_exec(\"SELECT txid_current()\")[0][0].to(m_xid);\n}\n\n\npqxx::internal::basic_robusttransaction::~basic_robusttransaction() = default;\n\n\nvoid pqxx::internal::basic_robusttransaction::do_commit()\n{\n \/\/ Check constraints before sending the COMMIT to the database, so as to\n \/\/ minimise our in-doubt window.\n try\n {\n direct_exec(\"SET CONSTRAINTS ALL IMMEDIATE\");\n }\n catch (const std::exception &)\n {\n do_abort();\n throw;\n }\n\n \/\/ Here comes the in-doubt window. If we lose our connection here, we'll be\n \/\/ left clueless as to what happened on the backend. It may have received\n \/\/ the commit command and completed the transaction, and ended up with a\n \/\/ success it could not report back to us. Or it may have noticed the broken\n \/\/ connection and aborted the transaction. It may even still be executing\n \/\/ the commit, only to fail later.\n \/\/\n \/\/ All this uncertainty requires some special handling, and that s what makes\n \/\/ robusttransaction what it is.\n try\n {\n direct_exec(\"COMMIT\");\n\n \/\/ If we make it here, great. Normal, successful commit.\n return;\n }\n catch (const broken_connection &)\n {\n \/\/ Oops, lost connection at the crucial moment. Fall through to in-doubt\n \/\/ handling below.\n }\n catch (const std::exception &)\n {\n if (conn().is_open())\n {\n \/\/ Commit failed, for some other reason.\n do_abort();\n throw;\n }\n \/\/ Otherwise, fall through to in-doubt handling.\n }\n\n \/\/ If we get here, we're in doubt. Figure out what happened.\n\n \/\/ TODO: Make delay and attempts configurable.\n const auto delay{std::chrono::milliseconds(300)};\n const int max_attempts{500};\n static_assert(max_attempts > 0);\n\n tx_stat stat;\n for (int attempts{0}; attempts < max_attempts;\n ++attempts, std::this_thread::sleep_for(delay))\n {\n stat = tx_unknown;\n try\n {\n stat = query_status(m_xid, m_conn_string);\n }\n catch (const pqxx::broken_connection &)\n {\n \/\/ Swallow the error. Pause and retry.\n }\n switch (stat)\n {\n case tx_unknown:\n \/\/ We were unable to reconnect and query transaction status.\n \/\/ Stay in it for another attempt.\n return;\n case tx_committed:\n \/\/ Success! We're done.\n return;\n case tx_aborted:\n \/\/ Aborted. We're done.\n do_abort();\n return;\n case tx_in_progress:\n \/\/ The transaction is still running. Stick around until we know what\n \/\/ transpires.\n break;\n }\n }\n\n \/\/ Okay, this has taken too long. Give up, report in-doubt state.\n throw in_doubt_error{\n \"Transaction \" + name() + \" (with transaction ID \" + m_xid +\n \") \"\n \"lost connection while committing. It's impossible to tell whether \"\n \"it committed, or aborted, or is still running. \"\n \"Attempts to find out its outcome have failed. \"\n \"The backend process on the server had process ID \" +\n to_string(m_backendpid) +\n \". \"\n \"You may be able to check what happened to that process.\"};\n}\n\n\nvoid pqxx::internal::basic_robusttransaction::do_abort()\n{\n direct_exec(\"ROLLBACK\");\n}\n<|endoftext|>"} {"text":"<commit_before>\/\/ Copyright (c) 2014 Steinwurf ApS\n\/\/ All Rights Reserved\n\/\/\n\/\/ Distributed under the \"BSD License\". See the accompanying LICENSE.rst file.\n\n#pragma once\n\n#include \"easy_bind.hpp\"\n\nnamespace sak\n{\n \/\/ Do not expose implementation details to users of this header file\n\n \/\/ namespace detail\n \/\/ {\n \/\/ template<typename T>\n \/\/ struct get_signature_impl;\n\n \/\/ template<typename C, typename R, typename... A>\n \/\/ struct get_signature_impl<R(C::*)(A...)>\n \/\/ {\n \/\/ typedef R type(A...);\n \/\/ };\n\n \/\/ template<typename C, typename R, typename... A>\n \/\/ struct get_signature_impl<R(C::*)(A...) const>\n \/\/ {\n \/\/ typedef R type(A...);\n \/\/ };\n\n \/\/ template<typename C, typename R, typename... A>\n \/\/ struct get_signature_impl<R(C::*)(A...) volatile>\n \/\/ {\n \/\/ typedef R type(A...);\n \/\/ };\n\n \/\/ template<typename C, typename R, typename... A>\n \/\/ struct get_signature_impl<R(C::*)(A...) const volatile>\n \/\/ {\n \/\/ typedef R type(A...);\n \/\/ };\n\n \/\/ template<typename R, typename... A>\n \/\/ struct get_signature_impl<R(A...)>\n \/\/ {\n \/\/ typedef R type(A...);\n \/\/ };\n\n \/\/ template<typename R, typename... A>\n \/\/ struct get_signature_impl<R(&)(A...)>\n \/\/ {\n \/\/ typedef R type(A...);\n \/\/ };\n\n \/\/ template<typename R, typename... A>\n \/\/ struct get_signature_impl<R(*)(A...)>\n \/\/ {\n \/\/ typedef R type(A...);\n \/\/ };\n\n \/\/ template<typename T> using get_signature =\n \/\/ typename get_signature_impl<T>::type;\n\n \/\/ template<typename F> using make_function_type =\n \/\/ std::function<get_signature<F>>;\n\n \/\/ template<typename F> make_function_type<F> make_function(F f) {\n \/\/ return make_function_type<F>(f); }\n \/\/ }\n\n namespace detail\n {\n \/\/\/ Helper struct which serves a return value if we were not able\n \/\/\/ to bind to the specified function\n struct not_valid_bind\n { };\n\n \/\/\/ Overload of the internal optional_bind. This overload is\n \/\/\/ chosen if the B::bind(f) expression cannot be\n \/\/\/ instantiated. Thanks to SFINAE this means that this\n \/\/\/ overload will be the only valid expression and therefore\n \/\/\/ it will be chosen. If however the bind expression is valid\n \/\/\/ then both overloads will be available, however since the\n \/\/\/ int version does not require an implict conversion of the\n \/\/\/ numeric constant form int to char it will be preferred.\n template<class B, class F>\n not_valid_bind optional_bind(F&, char)\n {\n return not_valid_bind();\n }\n\n template<class B, class F>\n auto optional_bind(F& f, int) -> decltype(B::bind(f))\n {\n return B::bind(f);\n }\n }\n\n \/\/\/ The optional_bind utility was designed for cases where we want\n \/\/\/ to bind to a specific member function if that function is\n \/\/\/ available otherwise we want to skip the bind.\n \/\/\/\n \/\/\/ optional_bind is designed with a quite narrow scope, but it\n \/\/\/ can probably be extended to serve more purposes if needed.\n \/\/\/\n \/\/\/ The following example shows optional_bind in action:\n \/\/\/\n \/\/\/ struct foo\n \/\/\/ {\n \/\/\/ void make_coffee()\n \/\/\/ {\n \/\/\/ std::cout << \"coffee on its way\" << std::endl;\n \/\/\/ }\n \/\/\/ };\n \/\/\/\n \/\/\/ Now somewhere in your code you want to bind to two different\n \/\/\/ member functions, but if they are not there it is ok.\n \/\/\/\n \/\/\/ To do this we need to define two helpers which implement the\n \/\/\/ actual bind (we will utilize the easy_bind helper here to make\n \/\/\/ the code simple but you can also use std::bind):\n \/\/\/\n \/\/\/ struct bind_make_coffee\n \/\/\/ {\n \/\/\/ template<class T>\n \/\/\/ static auto bind(T& t) ->\n \/\/\/ decltype(sak::easy_bind(&T::make_coffee, &t))\n \/\/\/ {\n \/\/\/ return sak::easy_bind(&T::make_coffee, &t);\n \/\/\/ }\n \/\/\/ };\n \/\/\/\n \/\/\/ struct bind_grind_beans\n \/\/\/ {\n \/\/\/ template<class T>\n \/\/\/ static auto bind(T& t) ->\n \/\/\/ decltype(sak::easy_bind(&T::grind_beans, &t))\n \/\/\/ {\n \/\/\/ return sak::easy_bind(&T::grind_beans, &t);\n \/\/\/ }\n \/\/\/ };\n \/\/\/\n \/\/\/ With these helpers we can now write the following:\n \/\/\/\n \/\/\/ foo f;\n \/\/\/ auto make_coffee = sak::optinal_bind<bind_make_coffee>(&f);\n \/\/\/ auto grind_beans = sak::optional_bind<bind_grind_beans>(&f);\n \/\/\/\n \/\/\/ assert(sak::is_bind_expression(make_coffee) == true);\n \/\/\/ assert(sak::is_bind_expression(grind_beans) == false);\n \/\/\/\n \/\/\/ The nice thing about this is that is can be done without\n \/\/\/ having to directly utilize SFINAE tricks directly in the code.\n \/\/\/\n \/\/\/ The return value of optional_bind can only be used if\n \/\/\/ sak::is_bind_expression returns true. If that is the case then the\n \/\/\/ return value will be the equal to the return value of the bind\n \/\/\/ expression used in the helper. In the example given above we\n \/\/\/ are using sak::easy_bind which internally uses std::bind so\n \/\/\/ the return value is that of std::bind.\n \/\/\/\n \/\/\/ The optional_bind helper takes the following arguments:\n \/\/\/\n \/\/\/ - B which is a type that should provide a static function\n \/\/\/ called bind which should take F as a parameter. Usually we\n \/\/\/ will make bind a template function to allow late binding as\n \/\/\/ per our example above.\n \/\/\/ - F is the object to which we wish to bind\n \/\/\/\n template<class B, class F>\n auto optional_bind(F& f) -> decltype(detail::optional_bind<B, F>(f, 0))\n {\n return detail::optional_bind<B, F>(f, 0);\n }\n\n \/\/\/ Checks whether the optional_bind return a valid bind expression\n \/\/\/ @param The return value of optional_bind\n \/\/\/ @return True if the type T is a valid bind expression otherwise false\n template<class T>\n bool is_bind_expression(const T&)\n {\n return std::is_bind_expression<T>::value;\n }\n}\n<commit_msg>Removing obsolete code<commit_after>\/\/ Copyright (c) 2014 Steinwurf ApS\n\/\/ All Rights Reserved\n\/\/\n\/\/ Distributed under the \"BSD License\". See the accompanying LICENSE.rst file.\n\n#pragma once\n\n#include <functional>\n\nnamespace sak\n{\n \/\/ Do not expose implementation details to users of this header file\n namespace detail\n {\n \/\/\/ Helper struct which serves a return value if we were not able\n \/\/\/ to bind to the specified function\n struct not_valid_bind\n { };\n\n \/\/\/ Overload of the internal optional_bind. This overload is\n \/\/\/ chosen if the B::bind(f) expression cannot be\n \/\/\/ instantiated. Thanks to SFINAE this means that this\n \/\/\/ overload will be the only valid expression and therefore\n \/\/\/ it will be chosen. If however the bind expression is valid\n \/\/\/ then both overloads will be available, however since the\n \/\/\/ int version does not require an implict conversion of the\n \/\/\/ numeric constant form int to char it will be preferred.\n template<class B, class F>\n not_valid_bind optional_bind(F&, char)\n {\n return not_valid_bind();\n }\n\n template<class B, class F>\n auto optional_bind(F& f, int) -> decltype(B::bind(f))\n {\n return B::bind(f);\n }\n }\n\n \/\/\/ The optional_bind utility was designed for cases where we want\n \/\/\/ to bind to a specific member function if that function is\n \/\/\/ available otherwise we want to skip the bind.\n \/\/\/\n \/\/\/ optional_bind is designed with a quite narrow scope, but it\n \/\/\/ can probably be extended to serve more purposes if needed.\n \/\/\/\n \/\/\/ The following example shows optional_bind in action:\n \/\/\/\n \/\/\/ struct foo\n \/\/\/ {\n \/\/\/ void make_coffee()\n \/\/\/ {\n \/\/\/ std::cout << \"coffee on its way\" << std::endl;\n \/\/\/ }\n \/\/\/ };\n \/\/\/\n \/\/\/ Now somewhere in your code you want to bind to two different\n \/\/\/ member functions, but if they are not there it is ok.\n \/\/\/\n \/\/\/ To do this we need to define two helpers which implement the\n \/\/\/ actual bind (we will utilize the easy_bind helper here to make\n \/\/\/ the code simple but you can also use std::bind):\n \/\/\/\n \/\/\/ struct bind_make_coffee\n \/\/\/ {\n \/\/\/ template<class T>\n \/\/\/ static auto bind(T& t) ->\n \/\/\/ decltype(sak::easy_bind(&T::make_coffee, &t))\n \/\/\/ {\n \/\/\/ return sak::easy_bind(&T::make_coffee, &t);\n \/\/\/ }\n \/\/\/ };\n \/\/\/\n \/\/\/ struct bind_grind_beans\n \/\/\/ {\n \/\/\/ template<class T>\n \/\/\/ static auto bind(T& t) ->\n \/\/\/ decltype(sak::easy_bind(&T::grind_beans, &t))\n \/\/\/ {\n \/\/\/ return sak::easy_bind(&T::grind_beans, &t);\n \/\/\/ }\n \/\/\/ };\n \/\/\/\n \/\/\/ With these helpers we can now write the following:\n \/\/\/\n \/\/\/ foo f;\n \/\/\/ auto make_coffee = sak::optinal_bind<bind_make_coffee>(&f);\n \/\/\/ auto grind_beans = sak::optional_bind<bind_grind_beans>(&f);\n \/\/\/\n \/\/\/ assert(sak::is_bind_expression(make_coffee) == true);\n \/\/\/ assert(sak::is_bind_expression(grind_beans) == false);\n \/\/\/\n \/\/\/ The nice thing about this is that is can be done without\n \/\/\/ having to directly utilize SFINAE tricks directly in the code.\n \/\/\/\n \/\/\/ The return value of optional_bind can only be used if\n \/\/\/ sak::is_bind_expression returns true. If that is the case then the\n \/\/\/ return value will be the equal to the return value of the bind\n \/\/\/ expression used in the helper. In the example given above we\n \/\/\/ are using sak::easy_bind which internally uses std::bind so\n \/\/\/ the return value is that of std::bind.\n \/\/\/\n \/\/\/ The optional_bind helper takes the following arguments:\n \/\/\/\n \/\/\/ - B which is a type that should provide a static function\n \/\/\/ called bind which should take F as a parameter. Usually we\n \/\/\/ will make bind a template function to allow late binding as\n \/\/\/ per our example above.\n \/\/\/ - F is the object to which we wish to bind\n \/\/\/\n template<class B, class F>\n auto optional_bind(F& f) -> decltype(detail::optional_bind<B, F>(f, 0))\n {\n return detail::optional_bind<B, F>(f, 0);\n }\n\n \/\/\/ Checks whether the optional_bind return a valid bind expression\n \/\/\/ @param The return value of optional_bind\n \/\/\/ @return True if the type T is a valid bind expression otherwise false\n template<class T>\n bool is_bind_expression(const T&)\n {\n return std::is_bind_expression<T>::value;\n }\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n\tThis file is part of cpp-ethereum.\n\n\tcpp-ethereum is free software: you can redistribute it and\/or modify\n\tit under the terms of the GNU General Public License as published by\n\tthe Free Software Foundation, either version 3 of the License, or\n\t(at your option) any later version.\n\n\tFoobar is distributed in the hope that it will be useful,\n\tbut WITHOUT ANY WARRANTY; without even the implied warranty of\n\tMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n\tGNU General Public License for more details.\n\n\tYou should have received a copy of the GNU General Public License\n\talong with Foobar. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n*\/\n\/** @file peer.cpp\n * @author Gav Wood <i@gavwood.com>\n * @date 2014\n * Peer Network test functions.\n *\/\n\n#include <chrono>\n#include <thread>\n#include <BlockChain.h>\n#include <PeerNetwork.h>\nusing namespace std;\nusing namespace eth;\nusing boost::asio::ip::tcp;\n\nint peerTest(int argc, char** argv)\n{\n\tshort listenPort = 30303;\n\tstring remoteHost;\n\tshort remotePort = 30303;\n\n\tfor (int i = 1; i < argc; ++i)\n\t{\n\t\tstring arg = argv[i];\n\t\tif (arg == \"-l\" && i + 1 < argc)\n\t\t\tlistenPort = atoi(argv[++i]);\n\t\telse if (arg == \"-r\" && i + 1 < argc)\n\t\t\tremoteHost = argv[++i];\n\t\telse if (arg == \"-p\" && i + 1 < argc)\n\t\t\tremotePort = atoi(argv[++i]);\n\t\telse\n\t\t\tremoteHost = argv[i];\n\t}\n\n\tBlockChain ch(\"\/tmp\");\n\tPeerServer pn(\"Test\", ch, 0, listenPort);\n\n\tif (!remoteHost.empty())\n\t\tpn.connect(remoteHost, remotePort);\n\n\tfor (int i = 0; ; ++i)\n\t{\n\t\tthis_thread::sleep_for(chrono::milliseconds(100));\n\t\tpn.process(ch);\n\t\tif (!(i % 10))\n\t\t\tpn.pingAll();\n\t}\n\n\treturn 0;\n}\n\n<commit_msg>Less hangy.<commit_after>\/*\n\tThis file is part of cpp-ethereum.\n\n\tcpp-ethereum is free software: you can redistribute it and\/or modify\n\tit under the terms of the GNU General Public License as published by\n\tthe Free Software Foundation, either version 3 of the License, or\n\t(at your option) any later version.\n\n\tFoobar is distributed in the hope that it will be useful,\n\tbut WITHOUT ANY WARRANTY; without even the implied warranty of\n\tMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n\tGNU General Public License for more details.\n\n\tYou should have received a copy of the GNU General Public License\n\talong with Foobar. If not, see <http:\/\/www.gnu.org\/licenses\/>.\n*\/\n\/** @file peer.cpp\n * @author Gav Wood <i@gavwood.com>\n * @date 2014\n * Peer Network test functions.\n *\/\n\n#include <chrono>\n#include <thread>\n#include <BlockChain.h>\n#include <PeerNetwork.h>\nusing namespace std;\nusing namespace eth;\nusing boost::asio::ip::tcp;\n\nint peerTest(int argc, char** argv)\n{\n\tshort listenPort = 30303;\n\tstring remoteHost;\n\tshort remotePort = 30303;\n\n\tfor (int i = 1; i < argc; ++i)\n\t{\n\t\tstring arg = argv[i];\n\t\tif (arg == \"-l\" && i + 1 < argc)\n\t\t\tlistenPort = atoi(argv[++i]);\n\t\telse if (arg == \"-r\" && i + 1 < argc)\n\t\t\tremoteHost = argv[++i];\n\t\telse if (arg == \"-p\" && i + 1 < argc)\n\t\t\tremotePort = atoi(argv[++i]);\n\t\telse\n\t\t\tremoteHost = argv[i];\n\t}\n\n\tBlockChain ch(\"\/tmp\");\n\tPeerServer pn(\"Test\", ch, 0, listenPort);\n\n\tif (!remoteHost.empty())\n\t\tpn.connect(remoteHost, remotePort);\n\n\tfor (int i = 0; ; ++i)\n\t{\n\t\tthis_thread::sleep_for(chrono::milliseconds(100));\n\t\tpn.sync();\n\t\tif (!(i % 10))\n\t\t\tpn.pingAll();\n\t}\n\n\treturn 0;\n}\n\n<|endoftext|>"} {"text":"<commit_before>#pragma once\n\n\/\/ `krbn::hid_manager` can be used safely in a multi-threaded environment.\n\n#include \"boost_utility.hpp\"\n#include \"cf_utility.hpp\"\n#include \"device_detail.hpp\"\n#include \"dispatcher.hpp\"\n#include \"human_interface_device.hpp\"\n#include \"logger.hpp\"\n#include \"types.hpp\"\n#include <IOKit\/hid\/IOHIDManager.h>\n#include <unordered_map>\n\nnamespace krbn {\n\nclass hid_manager final : public pqrs::dispatcher::extra::dispatcher_client {\npublic:\n \/\/ Signals (invoked from the shared dispatcher thread)\n\n \/\/ Return false to ignore device.\n boost::signals2::signal<bool(IOHIDDeviceRef _Nonnull), boost_utility::signals2_combiner_call_while_true> device_detecting;\n boost::signals2::signal<void(std::weak_ptr<human_interface_device>)> device_detected;\n boost::signals2::signal<void(std::weak_ptr<human_interface_device>)> device_removed;\n\n \/\/ Methods\n\n hid_manager(const hid_manager&) = delete;\n\n hid_manager(const std::vector<std::pair<hid_usage_page, hid_usage>>& usage_pairs) : dispatcher_client(),\n usage_pairs_(usage_pairs),\n manager_(nullptr),\n refresh_timer_(*this) {\n run_loop_thread_ = std::make_unique<cf_utility::run_loop_thread>();\n }\n\n virtual ~hid_manager(void) {\n detach_from_dispatcher([this] {\n stop();\n });\n\n run_loop_thread_->terminate();\n run_loop_thread_ = nullptr;\n }\n\n void async_start(void) {\n enqueue_to_dispatcher([this] {\n start();\n });\n }\n\n void async_stop(void) {\n enqueue_to_dispatcher([this] {\n stop();\n });\n }\n\n std::vector<std::shared_ptr<human_interface_device>> copy_hids(void) const {\n std::lock_guard<std::mutex> lock(hids_mutex_);\n\n return hids_;\n }\n\nprivate:\n \/\/ This method is executed in the dispatcher thread.\n void start(void) {\n if (manager_) {\n logger::get_logger().warn(\"hid_manager is already started.\");\n return;\n }\n\n manager_ = IOHIDManagerCreate(kCFAllocatorDefault, kIOHIDOptionsTypeNone);\n if (!manager_) {\n logger::get_logger().error(\"IOHIDManagerCreate is failed.\");\n return;\n }\n\n if (auto device_matching_dictionaries = iokit_utility::create_device_matching_dictionaries(usage_pairs_)) {\n IOHIDManagerSetDeviceMatchingMultiple(manager_, device_matching_dictionaries);\n CFRelease(device_matching_dictionaries);\n }\n\n IOHIDManagerRegisterDeviceMatchingCallback(manager_, static_device_matching_callback, this);\n IOHIDManagerRegisterDeviceRemovalCallback(manager_, static_device_removal_callback, this);\n\n IOHIDManagerScheduleWithRunLoop(manager_,\n run_loop_thread_->get_run_loop(),\n kCFRunLoopCommonModes);\n\n \/\/ We need to call `wake` after `IOHIDManagerScheduleWithRunLoop`.\n\n run_loop_thread_->wake();\n\n refresh_timer_.start(\n [this] {\n refresh_if_needed();\n },\n std::chrono::milliseconds(5000));\n\n logger::get_logger().info(\"hid_manager is started.\");\n }\n\n \/\/ This method is executed in the dispatcher thread.\n void stop(void) {\n if (!manager_) {\n return;\n }\n\n \/\/ refresh_timer_\n\n refresh_timer_.stop();\n\n \/\/ manager_\n\n run_loop_thread_->enqueue_and_wait(^{\n \/\/ Release manager_ in run_loop_thread_ to avoid accessing released manager_ in run_loop_thread_.\n\n IOHIDManagerUnscheduleFromRunLoop(manager_,\n run_loop_thread_->get_run_loop(),\n kCFRunLoopCommonModes);\n\n CFRelease(manager_);\n manager_ = nullptr;\n });\n\n \/\/ Other variables\n\n registry_entry_ids_.clear();\n\n {\n std::lock_guard<std::mutex> lock(hids_mutex_);\n\n hids_.clear();\n }\n\n logger::get_logger().info(\"hid_manager is stopped.\");\n }\n\n \/\/ This method is executed in the dispatcher thread.\n void refresh_if_needed(void) {\n \/\/ `device_removal_callback` is sometimes missed\n \/\/ and invalid human_interface_devices are remained into hids_.\n \/\/ (The problem is likely occur just after wake up from sleep.)\n \/\/\n \/\/ We validate the human_interface_device,\n \/\/ and then reload devices if there is an invalid human_interface_device.\n\n bool needs_refresh = false;\n\n {\n std::lock_guard<std::mutex> lock(hids_mutex_);\n\n for (const auto& hid : hids_) {\n if (!hid->validate()) {\n logger::get_logger().warn(\"Refreshing hid_manager since a dangling human_interface_device is found. ({0})\",\n hid->get_name_for_log());\n needs_refresh = true;\n break;\n }\n }\n }\n\n if (needs_refresh) {\n stop();\n start();\n }\n }\n\n boost::optional<registry_entry_id> find_registry_entry_id(IOHIDDeviceRef _Nonnull device) {\n auto it = registry_entry_ids_.find(device);\n if (it != std::end(registry_entry_ids_)) {\n return it->second;\n }\n return boost::none;\n }\n\n static void static_device_matching_callback(void* _Nullable context,\n IOReturn result,\n void* _Nullable sender,\n IOHIDDeviceRef _Nonnull device) {\n if (result != kIOReturnSuccess) {\n return;\n }\n\n auto self = static_cast<hid_manager*>(context);\n if (!self) {\n return;\n }\n\n self->device_matching_callback(device);\n }\n\n void device_matching_callback(IOHIDDeviceRef _Nonnull device) {\n \/\/ `static_device_matching_callback` is called by multiple threads.\n \/\/ (It is not called from `run_loop_thread_`.)\n \/\/ Thus, we have to synchronize by using `dispatcher`.\n\n if (!device) {\n return;\n }\n\n CFRetain(device);\n\n enqueue_to_dispatcher([this, device] {\n if (!device_detecting(device)) {\n goto finish;\n }\n\n if (auto registry_entry_id = iokit_utility::find_registry_entry_id(device)) {\n \/\/ iokit_utility::find_registry_entry_id will be failed in device_removal_callback at least on macOS 10.13.\n \/\/ Thus, we have to memory device and registry_entry_id correspondence by myself.\n registry_entry_ids_[device] = *registry_entry_id;\n\n \/\/ Skip if same device is already matched.\n \/\/ (Multiple usage device (e.g. usage::pointer and usage::mouse) will be matched twice.)\n\n std::shared_ptr<human_interface_device> hid;\n\n {\n std::lock_guard<std::mutex> lock(hids_mutex_);\n\n if (std::any_of(std::begin(hids_),\n std::end(hids_),\n [&](auto&& h) {\n return *registry_entry_id == h->get_registry_entry_id();\n })) {\n \/\/ logger::get_logger().info(\"registry_entry_id:{0} already exists\", static_cast<uint64_t>(*registry_entry_id));\n goto finish;\n }\n\n hid = std::make_shared<human_interface_device>(device, *registry_entry_id);\n hids_.push_back(hid);\n }\n\n enqueue_to_dispatcher([this, hid] {\n device_detected(hid);\n });\n }\n\n finish:\n CFRelease(device);\n });\n }\n\n static void static_device_removal_callback(void* _Nullable context,\n IOReturn result,\n void* _Nullable sender,\n IOHIDDeviceRef _Nonnull device) {\n if (result != kIOReturnSuccess) {\n return;\n }\n\n auto self = static_cast<hid_manager*>(context);\n if (!self) {\n return;\n }\n\n self->device_removal_callback(device);\n }\n\n void device_removal_callback(IOHIDDeviceRef _Nonnull device) {\n \/\/ `static_device_removal_callback` is called by multiple threads.\n \/\/ (It is not called from `run_loop_thread_`.)\n \/\/ Thus, we have to synchronize by using `dispatcher`.\n\n if (!device) {\n return;\n }\n\n CFRetain(device);\n\n enqueue_to_dispatcher([this, device] {\n if (auto registry_entry_id = find_registry_entry_id(device)) {\n std::shared_ptr<human_interface_device> hid;\n\n {\n std::lock_guard<std::mutex> lock(hids_mutex_);\n\n auto it = std::find_if(std::begin(hids_),\n std::end(hids_),\n [&](auto&& h) {\n return *registry_entry_id == h->get_registry_entry_id();\n });\n if (it != hids_.end()) {\n hid = *it;\n hids_.erase(it);\n }\n }\n\n if (hid) {\n hid->set_removed();\n\n enqueue_to_dispatcher([this, hid] {\n device_removed(hid);\n });\n }\n\n \/\/ There might be multiple devices for one registry_entry_id.\n \/\/ (For example, keyboard and mouse combined device.)\n \/\/ And there is possibility that removal callback is not called with some device.\n \/\/\n \/\/ For example, there are 3 devices for 1 registry_entry_id (4294974284).\n \/\/ - device1 { device:0x7fb9d64078a0 => registry_entry_id:4294974284 }\n \/\/ - device2 { device:0x7fb9d8301390 => registry_entry_id:4294974284 }\n \/\/ - device3 { device:0x7fb9d830a630 => registry_entry_id:4294974284 }\n \/\/ And device_removal_callback are called only with device1 and device2.\n \/\/\n \/\/ We should remove device1, device2 and device3 at the same time in order to deal with this case.\n\n for (auto it = std::begin(registry_entry_ids_); it != std::end(registry_entry_ids_);) {\n if (it->second == *registry_entry_id) {\n it = registry_entry_ids_.erase(it);\n } else {\n std::advance(it, 1);\n }\n }\n }\n\n CFRelease(device);\n });\n }\n\n std::unique_ptr<cf_utility::run_loop_thread> run_loop_thread_;\n\n std::vector<std::pair<hid_usage_page, hid_usage>> usage_pairs_;\n\n IOHIDManagerRef _Nullable manager_;\n pqrs::dispatcher::extra::timer refresh_timer_;\n\n std::unordered_map<IOHIDDeviceRef, registry_entry_id> registry_entry_ids_;\n\n std::vector<std::shared_ptr<human_interface_device>> hids_;\n mutable std::mutex hids_mutex_;\n};\n} \/\/ namespace krbn\n<commit_msg>improve hid_manager<commit_after>#pragma once\n\n\/\/ `krbn::hid_manager` can be used safely in a multi-threaded environment.\n\n#include \"boost_utility.hpp\"\n#include \"cf_utility.hpp\"\n#include \"device_detail.hpp\"\n#include \"dispatcher.hpp\"\n#include \"human_interface_device.hpp\"\n#include \"logger.hpp\"\n#include \"monitor\/service_monitor.hpp\"\n#include \"types.hpp\"\n#include <IOKit\/hid\/IOHIDManager.h>\n#include <unordered_map>\n\nnamespace krbn {\n\n\/\/ We implement hid_manager without IOHIDManager.\n\/\/\n\/\/ IOHIDManager opens connected device automatically, and we cannot stop it.\n\/\/ We want to prevent opening device depending the `device_detecting` result.\n\/\/ Thus, we cannot use IOHIDManager to this purpose.\n\nclass hid_manager final : public pqrs::dispatcher::extra::dispatcher_client {\npublic:\n \/\/ Signals (invoked from the shared dispatcher thread)\n\n \/\/ Return false to ignore device.\n boost::signals2::signal<bool(IOHIDDeviceRef _Nonnull), boost_utility::signals2_combiner_call_while_true> device_detecting;\n boost::signals2::signal<void(std::weak_ptr<human_interface_device>)> device_detected;\n boost::signals2::signal<void(std::weak_ptr<human_interface_device>)> device_removed;\n\n \/\/ Methods\n\n hid_manager(const hid_manager&) = delete;\n\n hid_manager(const std::vector<std::pair<hid_usage_page, hid_usage>>& usage_pairs) : dispatcher_client(),\n usage_pairs_(usage_pairs),\n refresh_timer_(*this) {\n }\n\n virtual ~hid_manager(void) {\n detach_from_dispatcher([this] {\n stop();\n });\n }\n\n void async_start(void) {\n enqueue_to_dispatcher([this] {\n start();\n });\n }\n\n std::vector<std::shared_ptr<human_interface_device>> copy_hids(void) const {\n std::lock_guard<std::mutex> lock(hids_mutex_);\n\n return hids_;\n }\n\nprivate:\n \/\/ This method is executed in the dispatcher thread.\n void start(void) {\n for (const auto& pair : usage_pairs_) {\n if (auto dictionary = IOServiceMatching(kIOHIDDeviceKey)) {\n cf_utility::set_cfmutabledictionary_value(dictionary,\n CFSTR(kIOHIDDeviceUsagePageKey),\n static_cast<int64_t>(pair.first));\n cf_utility::set_cfmutabledictionary_value(dictionary,\n CFSTR(kIOHIDDeviceUsageKey),\n static_cast<int64_t>(pair.second));\n\n auto monitor = std::make_shared<monitor::service_monitor::monitor>(dictionary);\n\n monitor->service_detected.connect([this](auto&& services) {\n for (const auto& service : services->get_services()) {\n if (devices_.find(service) == std::end(devices_)) {\n if (auto device = IOHIDDeviceCreate(kCFAllocatorDefault, service)) {\n CFRetain(device);\n devices_[service] = device;\n\n device_matching_callback(device);\n\n CFRelease(device);\n }\n }\n }\n });\n\n monitor->service_removed.connect([this](auto&& services) {\n for (const auto& service : services->get_services()) {\n auto it = devices_.find(service);\n if (it != std::end(devices_)) {\n device_removal_callback(it->second);\n\n devices_.erase(it);\n CFRelease(it->second);\n }\n }\n });\n\n monitor->async_start();\n\n service_monitors_.push_back(monitor);\n\n CFRelease(dictionary);\n }\n }\n\n refresh_timer_.start(\n [this] {\n refresh_if_needed();\n },\n std::chrono::milliseconds(5000));\n\n logger::get_logger().info(\"hid_manager is started.\");\n }\n\n \/\/ This method is executed in the dispatcher thread.\n void stop(void) {\n refresh_timer_.stop();\n service_monitors_.clear();\n hids_.clear();\n registry_entry_ids_.clear();\n\n for (const auto& pair : devices_) {\n CFRelease(pair.second);\n }\n devices_.clear();\n }\n\n \/\/ This method is executed in the dispatcher thread.\n void refresh_if_needed(void) {\n \/\/ `device_removal_callback` is sometimes missed\n \/\/ and invalid human_interface_devices are remained into hids_.\n \/\/ (The problem is likely occur just after wake up from sleep.)\n \/\/\n \/\/ We validate the human_interface_device,\n \/\/ and then reload devices if there is an invalid human_interface_device.\n\n bool needs_refresh = false;\n\n {\n std::lock_guard<std::mutex> lock(hids_mutex_);\n\n for (const auto& hid : hids_) {\n if (!hid->validate()) {\n logger::get_logger().warn(\"Refreshing hid_manager since a dangling human_interface_device is found. ({0})\",\n hid->get_name_for_log());\n needs_refresh = true;\n break;\n }\n }\n }\n\n if (needs_refresh) {\n stop();\n start();\n }\n }\n\n boost::optional<registry_entry_id> find_registry_entry_id(IOHIDDeviceRef _Nonnull device) {\n auto it = registry_entry_ids_.find(device);\n if (it != std::end(registry_entry_ids_)) {\n return it->second;\n }\n return boost::none;\n }\n\n void device_matching_callback(IOHIDDeviceRef _Nonnull device) {\n if (!device) {\n return;\n }\n\n CFRetain(device);\n\n enqueue_to_dispatcher([this, device] {\n if (!device_detecting(device)) {\n goto finish;\n }\n\n if (auto registry_entry_id = iokit_utility::find_registry_entry_id(device)) {\n \/\/ iokit_utility::find_registry_entry_id will be failed in device_removal_callback at least on macOS 10.13.\n \/\/ Thus, we have to memory device and registry_entry_id correspondence by myself.\n registry_entry_ids_[device] = *registry_entry_id;\n\n \/\/ Skip if same device is already matched.\n \/\/ (Multiple usage device (e.g. usage::pointer and usage::mouse) will be matched twice.)\n\n std::shared_ptr<human_interface_device> hid;\n\n {\n std::lock_guard<std::mutex> lock(hids_mutex_);\n\n if (std::any_of(std::begin(hids_),\n std::end(hids_),\n [&](auto&& h) {\n return *registry_entry_id == h->get_registry_entry_id();\n })) {\n \/\/ logger::get_logger().info(\"registry_entry_id:{0} already exists\", static_cast<uint64_t>(*registry_entry_id));\n goto finish;\n }\n\n hid = std::make_shared<human_interface_device>(device, *registry_entry_id);\n hids_.push_back(hid);\n }\n\n enqueue_to_dispatcher([this, hid] {\n device_detected(hid);\n });\n }\n\n finish:\n CFRelease(device);\n });\n }\n\n static void static_device_removal_callback(void* _Nullable context,\n IOReturn result,\n void* _Nullable sender,\n IOHIDDeviceRef _Nonnull device) {\n if (result != kIOReturnSuccess) {\n return;\n }\n\n auto self = static_cast<hid_manager*>(context);\n if (!self) {\n return;\n }\n\n self->device_removal_callback(device);\n }\n\n void device_removal_callback(IOHIDDeviceRef _Nonnull device) {\n if (!device) {\n return;\n }\n\n CFRetain(device);\n\n enqueue_to_dispatcher([this, device] {\n if (auto registry_entry_id = find_registry_entry_id(device)) {\n std::shared_ptr<human_interface_device> hid;\n\n {\n std::lock_guard<std::mutex> lock(hids_mutex_);\n\n auto it = std::find_if(std::begin(hids_),\n std::end(hids_),\n [&](auto&& h) {\n return *registry_entry_id == h->get_registry_entry_id();\n });\n if (it != hids_.end()) {\n hid = *it;\n hids_.erase(it);\n }\n }\n\n if (hid) {\n hid->set_removed();\n\n enqueue_to_dispatcher([this, hid] {\n device_removed(hid);\n });\n }\n\n \/\/ There might be multiple devices for one registry_entry_id.\n \/\/ (For example, keyboard and mouse combined device.)\n \/\/ And there is possibility that removal callback is not called with some device.\n \/\/\n \/\/ For example, there are 3 devices for 1 registry_entry_id (4294974284).\n \/\/ - device1 { device:0x7fb9d64078a0 => registry_entry_id:4294974284 }\n \/\/ - device2 { device:0x7fb9d8301390 => registry_entry_id:4294974284 }\n \/\/ - device3 { device:0x7fb9d830a630 => registry_entry_id:4294974284 }\n \/\/ And device_removal_callback are called only with device1 and device2.\n \/\/\n \/\/ We should remove device1, device2 and device3 at the same time in order to deal with this case.\n\n for (auto it = std::begin(registry_entry_ids_); it != std::end(registry_entry_ids_);) {\n if (it->second == *registry_entry_id) {\n it = registry_entry_ids_.erase(it);\n } else {\n std::advance(it, 1);\n }\n }\n }\n\n CFRelease(device);\n });\n }\n\n std::vector<std::pair<hid_usage_page, hid_usage>> usage_pairs_;\n\n std::vector<std::shared_ptr<monitor::service_monitor::monitor>> service_monitors_;\n pqrs::dispatcher::extra::timer refresh_timer_;\n\n std::unordered_map<io_service_t, IOHIDDeviceRef> devices_;\n std::unordered_map<IOHIDDeviceRef, registry_entry_id> registry_entry_ids_;\n\n std::vector<std::shared_ptr<human_interface_device>> hids_;\n mutable std::mutex hids_mutex_;\n}; \/\/ namespace krbn\n} \/\/ namespace krbn\n<|endoftext|>"} {"text":"<commit_before>\/*\n * interpreter_interface.cpp\n *\n * Wrapper to allow routines to be called from fortran and\/or provide a result\n * without requiring the caller to include interpreter.h or deal with namespaces\n * or classes.\n *\n * Created on: Aug 10, 2013\n * Author: basbas\n *\/\n\n#include \"config.h\"\n#include \"sip_interface.h\"\n#include \"interpreter.h\"\n#include \"index_table.h\"\n#include \"block.h\"\n#include <stdexcept>\n\n#ifdef HAVE_MPI\n#include \"sip_mpi_attr.h\"\n#include \"sip_server.h\"\n#endif \/\/ HAVE_MPI\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n\/**\n * Gets a currently active scalar value\n * @param name\n * @return\n *\/\ndouble scalar_value(const char * name) {\n\treturn sip::Interpreter::global_interpreter->scalar_value(std::string(name));\n}\n\n\/**\n * Sets the value of a currently active scalar\n * @param name\n * @param value\n *\/\nvoid set_scalar_value(const char * name, double value) {\n\tsip::Interpreter::global_interpreter->set_scalar_value(std::string(name),\n\t\t\tvalue);\n}\n\n\/**\n * query existance of double constant from initialization data\n * @param cname [in] Name of the constant\n * @return 0 for exists\n *\/\nint query_scalar_constant(const char*cname) {\n try {\n\tsip::Interpreter::global_interpreter->sip_tables().setup_reader().predefined_scalar(\n\t\t\tstd::string(cname));\n\treturn 1;\n } catch(const std::out_of_range& oor) {\n\treturn 0;\n }\n}\n\n\/**\n * Get a double constant from initialization data\n * @param cname [in] Name of the constant\n * @return Value of the constant\n *\/\ndouble scalar_constant(const char*cname) {\n\treturn sip::Interpreter::global_interpreter->sip_tables().setup_reader().predefined_scalar(\n\t\t\tstd::string(cname));\n}\n\n\/**\n * query integer constant from initialization data\n * @param cname [in] Name of the constant\n * @return 0 for exists\n *\/\nint query_int_constant(const char*cname) {\n try {\n\tsip::Interpreter::global_interpreter->sip_tables().setup_reader().predefined_int(\n\t\t\tstd::string(cname));\n\treturn 1;\n } catch(const std::out_of_range& oor) {\n\treturn 0;\n }\n}\n\n\/**\n * Get an integer constant from initialization data\n * @param cname [in] Name of the constant\n * @return Value of the constant\n *\/\nint int_constant(const char*cname) {\n\treturn sip::Interpreter::global_interpreter->sip_tables().setup_reader().predefined_int(\n\t\t\tstd::string(cname));\n}\n\n\/**\n * Get predefined scalar array from initialization data\n * @param aname [in] Name of the array\n * @param num_dims [out]\n * @param dims [out] array of extents\n * @param values [out] the data contained in the array\n *\/\n\n\nvoid predefined_scalar_array(const char*aname, int& num_dims, int **dims,\n\t\tdouble **values) {\n\ttry {\n\/\/\t\tstd::pair<int, std::pair<int *, double *> > a =\n\/\/\t\t\t\tsip::Interpreter::global_interpreter->sip_tables().setup_reader().predef_arr_.at(\n\/\/\t\t\t\t\t\tstd::string(aname));\n\/\/\t\tnum_dims = a.first;\n\/\/\t\t*dims = a.second.first;\n\/\/\t\t*values = a.second.second;\n\t\tsetup::PredefContigArray rankblock = sip::Interpreter::global_interpreter->sip_tables().setup_reader().predefined_contiguous_array(std::string(aname));\n\t\tnum_dims = rankblock.first;\n\t\tsip::Block::BlockPtr block = rankblock.second;\n\t\t*dims = const_cast<sip::segment_size_array_t&>(block->shape().segment_sizes_);\n\t\t*values = block->get_data();\n\t\treturn;\n\t} catch (const std::out_of_range& oor) {\n\t\tsip::check(false,\n\t\t\t\t\"predefined array \" + std::string(aname)\n\t\t\t\t\t\t+ \" not in predefined array map\\n\");\n\t\treturn;\n\t}\n}\n\nvoid scratch_array(int& num_elements, double **array){\n try{\n double * scratch = new double[num_elements](); \/\/initialize to zero\n *array = scratch;\n } catch (const std::bad_alloc& ba) {\n std::cerr << \"Got bad alloc ! Memory being requestd : \" << num_elements << std::endl;\n throw ba;\n }\n}\n\nvoid delete_scratch_array(double **array){\n\tdelete [] *array;\n}\n\nvoid integer_scratch_array(int& num_elements, int **array){\n\tint * scratch = new int[num_elements](); \/\/initialize to zero\n\t*array = scratch;\n}\n\nvoid delete_integer_scratch_array(int **array){\n\tdelete [] *array;\n}\n\n\/**\n * Get predefined integer array from initialization data\n *\n * @param aname [in] Name of the array\n * @param [out] num_dims\n * @param [out] dims array of extents\n * @param [out] values 1-d array containing the data contained in the array\n *\/\nvoid predefined_int_array(const char*aname, int& num_dims, int **dims,\n\t\tint **values) {\n\ttry {\n\t\tsetup::PredefIntArray a =\n\t\t\t\tsip::Interpreter::global_interpreter->sip_tables().setup_reader().predefined_integer_array(std::string(aname));\n\t\t\/\/std::cout << \"aname= \" << aname << \", a=\" << a.first << std::endl;\n\t\tnum_dims = a.rank;\n\t\t*dims = a.dims;\n\t\t*values = a.data;\n \/*\n\t\tstd::cout << num_dims << \",\" << *dims << \",\" << *values << std::endl;\n std::cout<<\"Dims :\"<<std::endl;\n for(int i=0; i<num_dims; i++){\n std::cout<<(*dims)[i]<< \" \";\n }\n std::cout<<std::endl<<\"Values :\"<<std::endl;\n for (int i=0; i< 10; i++){\n std::cout<<(*values)[i]<<\" \";\n }\n *\/\n\t\treturn;\n\t} catch (const std::out_of_range& oor) {\n\t\tsip::check(false,\n\t\t\t\t\"predefined array \" + std::string(aname)\n\t\t\t\t\t\t+ \" not in predefined array map\\n\");\n\t\treturn;\n\t}\n}\n\n\/**\n * Gets the current SIALX line number begin executed\n * @return\n *\/\nint current_line() {\n\treturn sip::get_line_number();\n}\n\n\/\/NOT YET IMPLEMENTED\n\/\/void get_config_info(const char* sialfile, const char* key, const char* value);\n\n#ifdef __cplusplus\n}\n#endif\n\nnamespace sip {\nstd::string index_name_value(int slot) {\n\treturn sip::Interpreter::global_interpreter->index_value_to_string(slot);\n}\nstd::string array_name_value(int array_table_slot) {\n\treturn sip::Interpreter::global_interpreter->array_name(array_table_slot);\n}\nint get_line_number() {\n#ifdef HAVE_MPI\n\tsip::Interpreter *interpreter = sip::Interpreter::global_interpreter;\n\tsip::SIPServer * server = sip::SIPServer::global_sipserver;\n\tsip::SIPMPIAttr &mpiattr = sip::SIPMPIAttr::get_instance();\n\tif (mpiattr.is_worker()){\n\t\tif (interpreter != NULL)\n\t\t\treturn interpreter->line_number();\n\t\telse\n\t\t\treturn 0;\n\t} else {\n\t\tif (server != NULL)\n\t\t\treturn server->last_seen_line();\n\t\telse\n\t\t\treturn 0;\n\t}\n\n#else\t\/\/ HAVE_MPI\n\tif (sip::Interpreter::global_interpreter != NULL) {\n\t\treturn sip::Interpreter::global_interpreter->line_number();\n\t} else\n\t\treturn 0;\n#endif\t\/\/ HAVE_MPI\n}\n\n}\n<commit_msg>updated comments to reflect correct return value<commit_after>\/*\n * interpreter_interface.cpp\n *\n * Wrapper to allow routines to be called from fortran and\/or provide a result\n * without requiring the caller to include interpreter.h or deal with namespaces\n * or classes.\n *\n * Created on: Aug 10, 2013\n * Author: basbas\n *\/\n\n#include \"config.h\"\n#include \"sip_interface.h\"\n#include \"interpreter.h\"\n#include \"index_table.h\"\n#include \"block.h\"\n#include <stdexcept>\n\n#ifdef HAVE_MPI\n#include \"sip_mpi_attr.h\"\n#include \"sip_server.h\"\n#endif \/\/ HAVE_MPI\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n\/**\n * Gets a currently active scalar value\n * @param name\n * @return\n *\/\ndouble scalar_value(const char * name) {\n\treturn sip::Interpreter::global_interpreter->scalar_value(std::string(name));\n}\n\n\/**\n * Sets the value of a currently active scalar\n * @param name\n * @param value\n *\/\nvoid set_scalar_value(const char * name, double value) {\n\tsip::Interpreter::global_interpreter->set_scalar_value(std::string(name),\n\t\t\tvalue);\n}\n\n\/**\n * query existance of double constant from initialization data\n * @param cname [in] Name of the constant\n * @return 1 for exists\n *\/\nint query_scalar_constant(const char*cname) {\n try {\n\tsip::Interpreter::global_interpreter->sip_tables().setup_reader().predefined_scalar(\n\t\t\tstd::string(cname));\n\treturn 1;\n } catch(const std::out_of_range& oor) {\n\treturn 0;\n }\n}\n\n\/**\n * Get a double constant from initialization data\n * @param cname [in] Name of the constant\n * @return Value of the constant\n *\/\ndouble scalar_constant(const char*cname) {\n\treturn sip::Interpreter::global_interpreter->sip_tables().setup_reader().predefined_scalar(\n\t\t\tstd::string(cname));\n}\n\n\/**\n * query integer constant from initialization data\n * @param cname [in] Name of the constant\n * @return 1 for exists\n *\/\nint query_int_constant(const char*cname) {\n try {\n\tsip::Interpreter::global_interpreter->sip_tables().setup_reader().predefined_int(\n\t\t\tstd::string(cname));\n\treturn 1;\n } catch(const std::out_of_range& oor) {\n\treturn 0;\n }\n}\n\n\/**\n * Get an integer constant from initialization data\n * @param cname [in] Name of the constant\n * @return Value of the constant\n *\/\nint int_constant(const char*cname) {\n\treturn sip::Interpreter::global_interpreter->sip_tables().setup_reader().predefined_int(\n\t\t\tstd::string(cname));\n}\n\n\/**\n * Get predefined scalar array from initialization data\n * @param aname [in] Name of the array\n * @param num_dims [out]\n * @param dims [out] array of extents\n * @param values [out] the data contained in the array\n *\/\n\n\nvoid predefined_scalar_array(const char*aname, int& num_dims, int **dims,\n\t\tdouble **values) {\n\ttry {\n\/\/\t\tstd::pair<int, std::pair<int *, double *> > a =\n\/\/\t\t\t\tsip::Interpreter::global_interpreter->sip_tables().setup_reader().predef_arr_.at(\n\/\/\t\t\t\t\t\tstd::string(aname));\n\/\/\t\tnum_dims = a.first;\n\/\/\t\t*dims = a.second.first;\n\/\/\t\t*values = a.second.second;\n\t\tsetup::PredefContigArray rankblock = sip::Interpreter::global_interpreter->sip_tables().setup_reader().predefined_contiguous_array(std::string(aname));\n\t\tnum_dims = rankblock.first;\n\t\tsip::Block::BlockPtr block = rankblock.second;\n\t\t*dims = const_cast<sip::segment_size_array_t&>(block->shape().segment_sizes_);\n\t\t*values = block->get_data();\n\t\treturn;\n\t} catch (const std::out_of_range& oor) {\n\t\tsip::check(false,\n\t\t\t\t\"predefined array \" + std::string(aname)\n\t\t\t\t\t\t+ \" not in predefined array map\\n\");\n\t\treturn;\n\t}\n}\n\nvoid scratch_array(int& num_elements, double **array){\n try{\n double * scratch = new double[num_elements](); \/\/initialize to zero\n *array = scratch;\n } catch (const std::bad_alloc& ba) {\n std::cerr << \"Got bad alloc ! Memory being requestd : \" << num_elements << std::endl;\n throw ba;\n }\n}\n\nvoid delete_scratch_array(double **array){\n\tdelete [] *array;\n}\n\nvoid integer_scratch_array(int& num_elements, int **array){\n\tint * scratch = new int[num_elements](); \/\/initialize to zero\n\t*array = scratch;\n}\n\nvoid delete_integer_scratch_array(int **array){\n\tdelete [] *array;\n}\n\n\/**\n * Get predefined integer array from initialization data\n *\n * @param aname [in] Name of the array\n * @param [out] num_dims\n * @param [out] dims array of extents\n * @param [out] values 1-d array containing the data contained in the array\n *\/\nvoid predefined_int_array(const char*aname, int& num_dims, int **dims,\n\t\tint **values) {\n\ttry {\n\t\tsetup::PredefIntArray a =\n\t\t\t\tsip::Interpreter::global_interpreter->sip_tables().setup_reader().predefined_integer_array(std::string(aname));\n\t\t\/\/std::cout << \"aname= \" << aname << \", a=\" << a.first << std::endl;\n\t\tnum_dims = a.rank;\n\t\t*dims = a.dims;\n\t\t*values = a.data;\n \/*\n\t\tstd::cout << num_dims << \",\" << *dims << \",\" << *values << std::endl;\n std::cout<<\"Dims :\"<<std::endl;\n for(int i=0; i<num_dims; i++){\n std::cout<<(*dims)[i]<< \" \";\n }\n std::cout<<std::endl<<\"Values :\"<<std::endl;\n for (int i=0; i< 10; i++){\n std::cout<<(*values)[i]<<\" \";\n }\n *\/\n\t\treturn;\n\t} catch (const std::out_of_range& oor) {\n\t\tsip::check(false,\n\t\t\t\t\"predefined array \" + std::string(aname)\n\t\t\t\t\t\t+ \" not in predefined array map\\n\");\n\t\treturn;\n\t}\n}\n\n\/**\n * Gets the current SIALX line number begin executed\n * @return\n *\/\nint current_line() {\n\treturn sip::get_line_number();\n}\n\n\/\/NOT YET IMPLEMENTED\n\/\/void get_config_info(const char* sialfile, const char* key, const char* value);\n\n#ifdef __cplusplus\n}\n#endif\n\nnamespace sip {\nstd::string index_name_value(int slot) {\n\treturn sip::Interpreter::global_interpreter->index_value_to_string(slot);\n}\nstd::string array_name_value(int array_table_slot) {\n\treturn sip::Interpreter::global_interpreter->array_name(array_table_slot);\n}\nint get_line_number() {\n#ifdef HAVE_MPI\n\tsip::Interpreter *interpreter = sip::Interpreter::global_interpreter;\n\tsip::SIPServer * server = sip::SIPServer::global_sipserver;\n\tsip::SIPMPIAttr &mpiattr = sip::SIPMPIAttr::get_instance();\n\tif (mpiattr.is_worker()){\n\t\tif (interpreter != NULL)\n\t\t\treturn interpreter->line_number();\n\t\telse\n\t\t\treturn 0;\n\t} else {\n\t\tif (server != NULL)\n\t\t\treturn server->last_seen_line();\n\t\telse\n\t\t\treturn 0;\n\t}\n\n#else\t\/\/ HAVE_MPI\n\tif (sip::Interpreter::global_interpreter != NULL) {\n\t\treturn sip::Interpreter::global_interpreter->line_number();\n\t} else\n\t\treturn 0;\n#endif\t\/\/ HAVE_MPI\n}\n\n}\n<|endoftext|>"} {"text":"<commit_before>\/*\n * Copyright (C) 2011 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"SkPDFGraphicState.h\"\n#include \"SkPDFUtils.h\"\n#include \"SkStream.h\"\n#include \"SkTypes.h\"\n\nnamespace {\n\nconst char* blendModeFromXfermode(SkXfermode::Mode mode) {\n switch (mode) {\n case SkXfermode::kSrcOver_Mode: return \"Normal\";\n case SkXfermode::kMultiply_Mode: return \"Multiply\";\n case SkXfermode::kScreen_Mode: return \"Screen\";\n case SkXfermode::kOverlay_Mode: return \"Overlay\";\n case SkXfermode::kDarken_Mode: return \"Darken\";\n case SkXfermode::kLighten_Mode: return \"Lighten\";\n case SkXfermode::kColorDodge_Mode: return \"ColorDodge\";\n case SkXfermode::kColorBurn_Mode: return \"ColorBurn\";\n case SkXfermode::kHardLight_Mode: return \"HardLight\";\n case SkXfermode::kSoftLight_Mode: return \"SoftLight\";\n case SkXfermode::kDifference_Mode: return \"Difference\";\n case SkXfermode::kExclusion_Mode: return \"Exclusion\";\n\n \/\/ These are handled in SkPDFDevice::setUpContentEntry.\n case SkXfermode::kClear_Mode:\n case SkXfermode::kSrc_Mode:\n case SkXfermode::kDst_Mode:\n case SkXfermode::kDstOver_Mode:\n return \"Normal\";\n\n \/\/ TODO(vandebo) Figure out if we can support more of these modes.\n case SkXfermode::kSrcIn_Mode:\n case SkXfermode::kDstIn_Mode:\n case SkXfermode::kSrcOut_Mode:\n case SkXfermode::kDstOut_Mode:\n case SkXfermode::kSrcATop_Mode:\n case SkXfermode::kDstATop_Mode:\n case SkXfermode::kXor_Mode:\n case SkXfermode::kPlus_Mode:\n return NULL;\n }\n return NULL;\n}\n\n}\n\nSkPDFGraphicState::~SkPDFGraphicState() {\n SkAutoMutexAcquire lock(canonicalPaintsMutex());\n int index = find(fPaint);\n SkASSERT(index >= 0);\n canonicalPaints().removeShuffle(index);\n}\n\nvoid SkPDFGraphicState::emitObject(SkWStream* stream, SkPDFCatalog* catalog,\n bool indirect) {\n populateDict();\n SkPDFDict::emitObject(stream, catalog, indirect);\n}\n\n\/\/ static\nsize_t SkPDFGraphicState::getOutputSize(SkPDFCatalog* catalog, bool indirect) {\n populateDict();\n return SkPDFDict::getOutputSize(catalog, indirect);\n}\n\n\/\/ static\nSkTDArray<SkPDFGraphicState::GSCanonicalEntry>&\nSkPDFGraphicState::canonicalPaints() {\n \/\/ This initialization is only thread safe with gcc.\n static SkTDArray<SkPDFGraphicState::GSCanonicalEntry> gCanonicalPaints;\n return gCanonicalPaints;\n}\n\n\/\/ static\nSkMutex& SkPDFGraphicState::canonicalPaintsMutex() {\n \/\/ This initialization is only thread safe with gcc.\n static SkMutex gCanonicalPaintsMutex;\n return gCanonicalPaintsMutex;\n}\n\n\/\/ static\nSkPDFGraphicState* SkPDFGraphicState::getGraphicStateForPaint(\n const SkPaint& paint) {\n SkAutoMutexAcquire lock(canonicalPaintsMutex());\n int index = find(paint);\n if (index >= 0) {\n canonicalPaints()[index].fGraphicState->ref();\n return canonicalPaints()[index].fGraphicState;\n }\n GSCanonicalEntry newEntry(new SkPDFGraphicState(paint));\n canonicalPaints().push(newEntry);\n return newEntry.fGraphicState;\n}\n\n\/\/ static\nint SkPDFGraphicState::find(const SkPaint& paint) {\n GSCanonicalEntry search(&paint);\n return canonicalPaints().find(search);\n}\n\nSkPDFGraphicState::SkPDFGraphicState(const SkPaint& paint)\n : fPaint(paint),\n fPopulated(false) {\n}\n\n\/\/ populateDict and operator== have to stay in sync with each other.\nvoid SkPDFGraphicState::populateDict() {\n if (!fPopulated) {\n fPopulated = true;\n insert(\"Type\", new SkPDFName(\"ExtGState\"))->unref();\n\n SkRefPtr<SkPDFScalar> alpha =\n new SkPDFScalar(fPaint.getAlpha() * SkScalarInvert(0xFF));\n alpha->unref(); \/\/ SkRefPtr and new both took a reference.\n insert(\"CA\", alpha.get());\n insert(\"ca\", alpha.get());\n\n SK_COMPILE_ASSERT(SkPaint::kButt_Cap == 0, paint_cap_mismatch);\n SK_COMPILE_ASSERT(SkPaint::kRound_Cap == 1, paint_cap_mismatch);\n SK_COMPILE_ASSERT(SkPaint::kSquare_Cap == 2, paint_cap_mismatch);\n SK_COMPILE_ASSERT(SkPaint::kCapCount == 3, paint_cap_mismatch);\n SkASSERT(fPaint.getStrokeCap() >= 0 && fPaint.getStrokeCap() <= 2);\n insert(\"LC\", new SkPDFInt(fPaint.getStrokeCap()))->unref();\n\n SK_COMPILE_ASSERT(SkPaint::kMiter_Join == 0, paint_join_mismatch);\n SK_COMPILE_ASSERT(SkPaint::kRound_Join == 1, paint_join_mismatch);\n SK_COMPILE_ASSERT(SkPaint::kBevel_Join == 2, paint_join_mismatch);\n SK_COMPILE_ASSERT(SkPaint::kJoinCount == 3, paint_join_mismatch);\n SkASSERT(fPaint.getStrokeJoin() >= 0 && fPaint.getStrokeJoin() <= 2);\n insert(\"LJ\", new SkPDFInt(fPaint.getStrokeJoin()))->unref();\n\n insert(\"LW\", new SkPDFScalar(fPaint.getStrokeWidth()))->unref();\n insert(\"ML\", new SkPDFScalar(fPaint.getStrokeMiter()))->unref();\n insert(\"SA\", new SkPDFBool(true))->unref(); \/\/ Auto stroke adjustment.\n\n SkXfermode::Mode xfermode = SkXfermode::kSrcOver_Mode;\n \/\/ If asMode fails, default to kSrcOver_Mode.\n if (fPaint.getXfermode())\n fPaint.getXfermode()->asMode(&xfermode);\n \/\/ If we don't support the mode, just use kSrcOver_Mode.\n if (xfermode < 0 || xfermode > SkXfermode::kLastMode ||\n blendModeFromXfermode(xfermode) == NULL) {\n xfermode = SkXfermode::kSrcOver_Mode;\n NOT_IMPLEMENTED(\"unsupported xfermode\", false);\n }\n insert(\"BM\", new SkPDFName(blendModeFromXfermode(xfermode)))->unref();\n }\n}\n\n\/\/ We're only interested in some fields of the SkPaint, so we have a custom\n\/\/ operator== function.\nbool SkPDFGraphicState::GSCanonicalEntry::operator==(\n const SkPDFGraphicState::GSCanonicalEntry& gs) const {\n const SkPaint* a = fPaint;\n const SkPaint* b = gs.fPaint;\n SkASSERT(a != NULL);\n SkASSERT(b != NULL);\n\n if (SkColorGetA(a->getColor()) != SkColorGetA(b->getColor()) ||\n a->getStrokeCap() != b->getStrokeCap() ||\n a->getStrokeJoin() != b->getStrokeJoin() ||\n a->getStrokeWidth() != b->getStrokeWidth() ||\n a->getStrokeMiter() != b->getStrokeMiter()) {\n return false;\n }\n\n SkXfermode* aXfermode = a->getXfermode();\n SkXfermode::Mode aXfermodeName = SkXfermode::kSrcOver_Mode;\n bool aXfermodeKnown = true;\n if (aXfermode)\n aXfermodeKnown = aXfermode->asMode(&aXfermodeName);\n SkXfermode* bXfermode = b->getXfermode();\n SkXfermode::Mode bXfermodeName = SkXfermode::kSrcOver_Mode;\n bool bXfermodeKnown = true;\n if (bXfermode)\n bXfermodeKnown = bXfermode->asMode(&bXfermodeName);\n\n if (aXfermodeKnown != bXfermodeKnown)\n return false;\n if (!aXfermodeKnown)\n return aXfermode == bXfermode;\n return aXfermodeName == bXfermodeName;\n}\n<commit_msg>[PDF] Fix bug in graphic state comparison.<commit_after>\/*\n * Copyright (C) 2011 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"SkPDFGraphicState.h\"\n#include \"SkPDFUtils.h\"\n#include \"SkStream.h\"\n#include \"SkTypes.h\"\n\nnamespace {\n\nconst char* blendModeFromXfermode(SkXfermode::Mode mode) {\n switch (mode) {\n case SkXfermode::kSrcOver_Mode: return \"Normal\";\n case SkXfermode::kMultiply_Mode: return \"Multiply\";\n case SkXfermode::kScreen_Mode: return \"Screen\";\n case SkXfermode::kOverlay_Mode: return \"Overlay\";\n case SkXfermode::kDarken_Mode: return \"Darken\";\n case SkXfermode::kLighten_Mode: return \"Lighten\";\n case SkXfermode::kColorDodge_Mode: return \"ColorDodge\";\n case SkXfermode::kColorBurn_Mode: return \"ColorBurn\";\n case SkXfermode::kHardLight_Mode: return \"HardLight\";\n case SkXfermode::kSoftLight_Mode: return \"SoftLight\";\n case SkXfermode::kDifference_Mode: return \"Difference\";\n case SkXfermode::kExclusion_Mode: return \"Exclusion\";\n\n \/\/ These are handled in SkPDFDevice::setUpContentEntry.\n case SkXfermode::kClear_Mode:\n case SkXfermode::kSrc_Mode:\n case SkXfermode::kDst_Mode:\n case SkXfermode::kDstOver_Mode:\n return \"Normal\";\n\n \/\/ TODO(vandebo) Figure out if we can support more of these modes.\n case SkXfermode::kSrcIn_Mode:\n case SkXfermode::kDstIn_Mode:\n case SkXfermode::kSrcOut_Mode:\n case SkXfermode::kDstOut_Mode:\n case SkXfermode::kSrcATop_Mode:\n case SkXfermode::kDstATop_Mode:\n case SkXfermode::kXor_Mode:\n case SkXfermode::kPlus_Mode:\n return NULL;\n }\n return NULL;\n}\n\n}\n\nSkPDFGraphicState::~SkPDFGraphicState() {\n SkAutoMutexAcquire lock(canonicalPaintsMutex());\n int index = find(fPaint);\n SkASSERT(index >= 0);\n canonicalPaints().removeShuffle(index);\n}\n\nvoid SkPDFGraphicState::emitObject(SkWStream* stream, SkPDFCatalog* catalog,\n bool indirect) {\n populateDict();\n SkPDFDict::emitObject(stream, catalog, indirect);\n}\n\n\/\/ static\nsize_t SkPDFGraphicState::getOutputSize(SkPDFCatalog* catalog, bool indirect) {\n populateDict();\n return SkPDFDict::getOutputSize(catalog, indirect);\n}\n\n\/\/ static\nSkTDArray<SkPDFGraphicState::GSCanonicalEntry>&\nSkPDFGraphicState::canonicalPaints() {\n \/\/ This initialization is only thread safe with gcc.\n static SkTDArray<SkPDFGraphicState::GSCanonicalEntry> gCanonicalPaints;\n return gCanonicalPaints;\n}\n\n\/\/ static\nSkMutex& SkPDFGraphicState::canonicalPaintsMutex() {\n \/\/ This initialization is only thread safe with gcc.\n static SkMutex gCanonicalPaintsMutex;\n return gCanonicalPaintsMutex;\n}\n\n\/\/ static\nSkPDFGraphicState* SkPDFGraphicState::getGraphicStateForPaint(\n const SkPaint& paint) {\n SkAutoMutexAcquire lock(canonicalPaintsMutex());\n int index = find(paint);\n if (index >= 0) {\n canonicalPaints()[index].fGraphicState->ref();\n return canonicalPaints()[index].fGraphicState;\n }\n GSCanonicalEntry newEntry(new SkPDFGraphicState(paint));\n canonicalPaints().push(newEntry);\n return newEntry.fGraphicState;\n}\n\n\/\/ static\nint SkPDFGraphicState::find(const SkPaint& paint) {\n GSCanonicalEntry search(&paint);\n return canonicalPaints().find(search);\n}\n\nSkPDFGraphicState::SkPDFGraphicState(const SkPaint& paint)\n : fPaint(paint),\n fPopulated(false) {\n}\n\n\/\/ populateDict and operator== have to stay in sync with each other.\nvoid SkPDFGraphicState::populateDict() {\n if (!fPopulated) {\n fPopulated = true;\n insert(\"Type\", new SkPDFName(\"ExtGState\"))->unref();\n\n SkRefPtr<SkPDFScalar> alpha =\n new SkPDFScalar(fPaint.getAlpha() * SkScalarInvert(0xFF));\n alpha->unref(); \/\/ SkRefPtr and new both took a reference.\n insert(\"CA\", alpha.get());\n insert(\"ca\", alpha.get());\n\n SK_COMPILE_ASSERT(SkPaint::kButt_Cap == 0, paint_cap_mismatch);\n SK_COMPILE_ASSERT(SkPaint::kRound_Cap == 1, paint_cap_mismatch);\n SK_COMPILE_ASSERT(SkPaint::kSquare_Cap == 2, paint_cap_mismatch);\n SK_COMPILE_ASSERT(SkPaint::kCapCount == 3, paint_cap_mismatch);\n SkASSERT(fPaint.getStrokeCap() >= 0 && fPaint.getStrokeCap() <= 2);\n insert(\"LC\", new SkPDFInt(fPaint.getStrokeCap()))->unref();\n\n SK_COMPILE_ASSERT(SkPaint::kMiter_Join == 0, paint_join_mismatch);\n SK_COMPILE_ASSERT(SkPaint::kRound_Join == 1, paint_join_mismatch);\n SK_COMPILE_ASSERT(SkPaint::kBevel_Join == 2, paint_join_mismatch);\n SK_COMPILE_ASSERT(SkPaint::kJoinCount == 3, paint_join_mismatch);\n SkASSERT(fPaint.getStrokeJoin() >= 0 && fPaint.getStrokeJoin() <= 2);\n insert(\"LJ\", new SkPDFInt(fPaint.getStrokeJoin()))->unref();\n\n insert(\"LW\", new SkPDFScalar(fPaint.getStrokeWidth()))->unref();\n insert(\"ML\", new SkPDFScalar(fPaint.getStrokeMiter()))->unref();\n insert(\"SA\", new SkPDFBool(true))->unref(); \/\/ Auto stroke adjustment.\n\n SkXfermode::Mode xfermode = SkXfermode::kSrcOver_Mode;\n \/\/ If asMode fails, default to kSrcOver_Mode.\n if (fPaint.getXfermode())\n fPaint.getXfermode()->asMode(&xfermode);\n \/\/ If we don't support the mode, just use kSrcOver_Mode.\n if (xfermode < 0 || xfermode > SkXfermode::kLastMode ||\n blendModeFromXfermode(xfermode) == NULL) {\n xfermode = SkXfermode::kSrcOver_Mode;\n NOT_IMPLEMENTED(\"unsupported xfermode\", false);\n }\n insert(\"BM\", new SkPDFName(blendModeFromXfermode(xfermode)))->unref();\n }\n}\n\n\/\/ We're only interested in some fields of the SkPaint, so we have a custom\n\/\/ operator== function.\nbool SkPDFGraphicState::GSCanonicalEntry::operator==(\n const SkPDFGraphicState::GSCanonicalEntry& gs) const {\n const SkPaint* a = fPaint;\n const SkPaint* b = gs.fPaint;\n SkASSERT(a != NULL);\n SkASSERT(b != NULL);\n\n if (SkColorGetA(a->getColor()) != SkColorGetA(b->getColor()) ||\n a->getStrokeCap() != b->getStrokeCap() ||\n a->getStrokeJoin() != b->getStrokeJoin() ||\n a->getStrokeWidth() != b->getStrokeWidth() ||\n a->getStrokeMiter() != b->getStrokeMiter()) {\n return false;\n }\n\n SkXfermode::Mode aXfermodeName = SkXfermode::kSrcOver_Mode;\n SkXfermode* aXfermode = a->getXfermode();\n if (aXfermode) {\n aXfermode->asMode(&aXfermodeName);\n }\n if (aXfermodeName < 0 || aXfermodeName > SkXfermode::kLastMode ||\n blendModeFromXfermode(aXfermodeName) == NULL) {\n aXfermodeName = SkXfermode::kSrcOver_Mode;\n }\n const char* aXfermodeString = blendModeFromXfermode(aXfermodeName);\n SkASSERT(aXfermodeString != NULL);\n\n SkXfermode::Mode bXfermodeName = SkXfermode::kSrcOver_Mode;\n SkXfermode* bXfermode = b->getXfermode();\n if (bXfermode) {\n bXfermode->asMode(&bXfermodeName);\n }\n if (bXfermodeName < 0 || bXfermodeName > SkXfermode::kLastMode ||\n blendModeFromXfermode(bXfermodeName) == NULL) {\n bXfermodeName = SkXfermode::kSrcOver_Mode;\n }\n const char* bXfermodeString = blendModeFromXfermode(bXfermodeName);\n SkASSERT(bXfermodeString != NULL);\n\n return strcmp(aXfermodeString, bXfermodeString) == 0;\n}\n<|endoftext|>"} {"text":"<commit_before><commit_msg>serialize\/deserialize spherical joints in ragdolls<commit_after><|endoftext|>"} {"text":"<commit_before><commit_msg>Create Stu_AS5600.cpp<commit_after><|endoftext|>"} {"text":"<commit_before>#include \"src\/bitmap.h\"\n#include \"src\/camera.h\"\n#include \"src\/math.h\"\n#include \"src\/timer.h\"\n#include \"src\/triangle.h\"\n#include <stdio.h>\n\ntypedef struct\n{\n gfx_Triangle tris[2];\n} TexQuad;\n\n\/\/ helper functions\nvoid setupTexQuad(TexQuad *q, int qx, int qy, int qw, int qh, gfx_Bitmap *texture);\nvoid drawTexQuad(const TexQuad *q, const mth_Matrix4 *mvp, gfx_drawBuffer *buffer);\n\n#define ROTATE_QUAD(delta, x, y, z) {\\\n for(k = 0; k < 2; ++k) \\\n { \\\n for(i = 0; i < 3; ++i) \\\n { \\\n mth_rotateVecAxisAngle(&quad.tris[k].vertices[i].position, delta*dt, x, y, z); \\\n } \\\n } \\\n }\n\n\/\/ Texture mapping test\nvoid testTextureMapping()\n{\n unsigned long int now, last = 0;\n const unsigned short *keysPressed;\n TexQuad quad;\n int texMapFlipped = 0, depthFuncFlipped = 0;\n gfx_Camera cam;\n mth_Matrix4 modelViewProj;\n gfx_Bitmap bmp = gfx_loadBitmap(\"images\/quake.bmp\");\n gfx_drawBuffer buffer;\n\n ALLOC_DRAWBUFFER(buffer, SCREEN_WIDTH, SCREEN_HEIGHT, DB_COLOR | DB_DEPTH);\n buffer.drawOpts.depthFunc = DF_ALWAYS;\n\n if(!DRAWBUFFER_VALID(buffer, DB_COLOR | DB_DEPTH))\n {\n printf(\"Out of memory!\");\n exit(1);\n }\n\n gfx_setPalette(bmp.palette);\n\n tmr_start();\n\n mth_matIdentity(&modelViewProj);\n\n \/\/ setup camera\n VEC4(cam.position, 0, 0, 60);\n VEC4(cam.up, 0, 1, 0);\n VEC4(cam.right, 1, 0, 0);\n VEC4(cam.target, 0, 0, -1);\n\n \/\/ setup textured quad\n setupTexQuad(&quad, -20, -20, 25, 25, &bmp);\n\n mth_matPerspective(&cam.projection, 75.f * M_PI \/180.f, (float)buffer.width \/ (float)buffer.height, 0.1f, 500.f);\n mth_matView(&cam.view, &cam.position, &cam.target, &cam.up);\n modelViewProj = mth_matMul(&cam.view, &cam.projection);\n\n do\n {\n int i, k;\n float dt;\n now = tmr_getMs();\n dt = (float)(now - last);\n keysPressed = kbd_getInput();\n\n if(keysPressed[KEY_RIGHT])\n ROTATE_QUAD(0.002f, 0.f, 1.f, 0.f);\n\n if(keysPressed[KEY_LEFT])\n ROTATE_QUAD(-0.002f, 0.f, 1.f, 0.f);\n\n if(keysPressed[KEY_UP])\n ROTATE_QUAD(0.002f, 1.f, 0.f, 0.f);\n\n if(keysPressed[KEY_DOWN])\n ROTATE_QUAD(-0.002f, 1.f, 0.f, 0.f);\n\n if(keysPressed[KEY_T] && !texMapFlipped)\n {\n buffer.drawOpts.drawMode = buffer.drawOpts.drawMode == DM_AFFINE ? DM_PERSPECTIVE : DM_AFFINE;\n texMapFlipped = 1;\n \n }\n else if(!keysPressed[KEY_T]) texMapFlipped = 0;\n\n if(keysPressed[KEY_D] && !depthFuncFlipped)\n {\n buffer.drawOpts.depthFunc = buffer.drawOpts.depthFunc == DF_ALWAYS ? DF_LESS : DF_ALWAYS;\n depthFuncFlipped = 1;\n \n }\n else if(!keysPressed[KEY_D]) depthFuncFlipped = 0;\n\n \/\/ clear buffers and draw the quad!\n gfx_clrBuffer(&buffer, DB_COLOR | DB_DEPTH);\n drawTexQuad(&quad, &modelViewProj, &buffer);\n gfx_updateScreen(&buffer);\n\n fprintf(stdout, buffer.drawOpts.drawMode == DM_AFFINE ? \"[T]exmapping: Affine\\r\\n\" : \"[T]exmapping: Perspective\\r\\n\");\n fprintf(stdout, buffer.drawOpts.depthFunc == DF_ALWAYS ? \"[D]epth test: OFF\\r\" : \"[D]epth test: ON\\r\");\n \/\/ reset carriage to top left corner of the screen\n fprintf(stdout, \"%c[%d;%df\", 0x1B, 0, 0); \n gfx_vSync();\n\n keysPressed = kbd_getInput();\n fflush(stdout);\n last = now;\n } while(!keysPressed[KEY_ESC]);\n\n tmr_finish();\n FREE_DRAWBUFFER(buffer);\n gfx_freeBitmap(&bmp);\n}\n\n\/* ***** *\/\nvoid setupTexQuad(TexQuad *q, int qx, int qy, int qw, int qh, gfx_Bitmap *texture)\n{\n q->tris[0].color = 1;\n q->tris[0].texture = texture;\n VEC4(q->tris[0].vertices[0].position, qx, qh, 0);\n q->tris[0].vertices[0].uv.u = 0;\n q->tris[0].vertices[0].uv.v = 1;\n VEC4(q->tris[0].vertices[1].position, qw, qy, 0);\n q->tris[0].vertices[1].uv.u = 1;\n q->tris[0].vertices[1].uv.v = 0;\n VEC4(q->tris[0].vertices[2].position, qx, qy, 0);\n q->tris[0].vertices[2].uv.u = 0;\n q->tris[0].vertices[2].uv.v = 0;\n\n q->tris[1].color = 1;\n q->tris[1].texture = texture;\n VEC4(q->tris[1].vertices[0].position, qx, qh, 0);\n q->tris[1].vertices[0].uv.u = 0;\n q->tris[1].vertices[0].uv.v = 1;\n VEC4(q->tris[1].vertices[1].position, qw, qh, 0);\n q->tris[1].vertices[1].uv.u = 1;\n q->tris[1].vertices[1].uv.v = 1;\n VEC4(q->tris[1].vertices[2].position, qw, qy, 0);\n q->tris[1].vertices[2].uv.u = 1;\n q->tris[1].vertices[2].uv.v = 0;\n}\n\n\/* ***** *\/\nvoid drawTexQuad(const TexQuad *q, const mth_Matrix4 *mvp, gfx_drawBuffer *buffer)\n{\n gfx_drawTriangle(&q->tris[0], mvp, buffer);\n gfx_drawTriangle(&q->tris[1], mvp, buffer);\n}\n<commit_msg>improved texture mapping sample<commit_after>#include \"src\/bitmap.h\"\n#include \"src\/camera.h\"\n#include \"src\/math.h\"\n#include \"src\/timer.h\"\n#include \"src\/triangle.h\"\n#include <stdio.h>\n\ntypedef struct\n{\n gfx_Triangle tris[2];\n} TexQuad;\n\n\/\/ helper functions\nvoid setupTexQuad(TexQuad *q, int qx, int qy, int qw, int qh, gfx_Bitmap *texture);\nvoid drawTexQuad(const TexQuad *q, const mth_Matrix4 *mvp, gfx_drawBuffer *buffer);\n\n#define ROTATE_QUAD(delta, x, y, z) {\\\n for(k = 0; k < 2; ++k) \\\n { \\\n for(i = 0; i < 3; ++i) \\\n { \\\n mth_rotateVecAxisAngle(&quad.tris[k].vertices[i].position, delta*dt, x, y, z); \\\n } \\\n } \\\n }\n\n\/\/ Texture mapping test\nvoid testTextureMapping()\n{\n const int quadX = -25;\n const int quadY = -25;\n const int quadW = 25;\n const int quadH = 25;\n unsigned long int now, last = 0;\n const unsigned short *keysPressed;\n float t = 0.f;\n TexQuad quad;\n int texMapFlipped = 0, depthFuncFlipped = 0;\n int manualMode = 0, modeFlipped = 0;\n gfx_Camera cam;\n mth_Matrix4 modelViewProj;\n gfx_Bitmap bmp = gfx_loadBitmap(\"images\/quake.bmp\");\n gfx_drawBuffer buffer;\n\n ALLOC_DRAWBUFFER(buffer, SCREEN_WIDTH, SCREEN_HEIGHT, DB_COLOR | DB_DEPTH);\n buffer.drawOpts.depthFunc = DF_ALWAYS;\n\n if(!DRAWBUFFER_VALID(buffer, DB_COLOR | DB_DEPTH))\n {\n printf(\"Out of memory!\");\n exit(1);\n }\n\n gfx_setPalette(bmp.palette);\n\n tmr_start();\n\n mth_matIdentity(&modelViewProj);\n\n \/\/ setup camera\n VEC4(cam.position, 0, 0, 60);\n VEC4(cam.up, 0, 1, 0);\n VEC4(cam.right, 1, 0, 0);\n VEC4(cam.target, 0, 0, -1);\n\n \/\/ setup textured quad\n setupTexQuad(&quad, quadX, quadY, quadW, quadH, &bmp);\n\n mth_matPerspective(&cam.projection, 75.f * M_PI \/180.f, (float)buffer.width \/ (float)buffer.height, 0.1f, 500.f);\n mth_matView(&cam.view, &cam.position, &cam.target, &cam.up);\n modelViewProj = mth_matMul(&cam.view, &cam.projection);\n\n do\n {\n int i, k;\n float dt;\n now = tmr_getMs();\n dt = (float)(now - last);\n t += 0.003f * dt;\n keysPressed = kbd_getInput();\n\n if(manualMode)\n {\n if(keysPressed[KEY_RIGHT])\n ROTATE_QUAD(0.002f, 0.f, 1.f, 0.f);\n\n if(keysPressed[KEY_LEFT])\n ROTATE_QUAD(-0.002f, 0.f, 1.f, 0.f);\n\n if(keysPressed[KEY_UP])\n ROTATE_QUAD(0.002f, 1.f, 0.f, 0.f);\n\n if(keysPressed[KEY_DOWN])\n ROTATE_QUAD(-0.002f, 1.f, 0.f, 0.f);\n }\n else\n {\n ROTATE_QUAD(0.002f * cos(t), 0.f, 1.f, 0.f);\n }\n\n if(keysPressed[KEY_T] && !texMapFlipped)\n {\n buffer.drawOpts.drawMode = buffer.drawOpts.drawMode == DM_AFFINE ? DM_PERSPECTIVE : DM_AFFINE;\n texMapFlipped = 1;\n \n }\n else if(!keysPressed[KEY_T]) texMapFlipped = 0;\n\n if(keysPressed[KEY_SPACE] && !modeFlipped)\n {\n setupTexQuad(&quad, quadX, quadY, quadW, quadH, &bmp);\n manualMode = ~manualMode;\n modeFlipped = 1;\n t = 0;\n }\n else if(!keysPressed[KEY_SPACE]) modeFlipped = 0;\n\n if(keysPressed[KEY_D] && !depthFuncFlipped)\n {\n buffer.drawOpts.depthFunc = buffer.drawOpts.depthFunc == DF_ALWAYS ? DF_LESS : DF_ALWAYS;\n depthFuncFlipped = 1;\n }\n else if(!keysPressed[KEY_D]) depthFuncFlipped = 0;\n\n \/\/ clear buffers and draw the quad!\n gfx_clrBuffer(&buffer, DB_COLOR | DB_DEPTH);\n drawTexQuad(&quad, &modelViewProj, &buffer);\n gfx_updateScreen(&buffer);\n\n fprintf(stdout, buffer.drawOpts.drawMode == DM_AFFINE ? \"[T]exmapping: Affine\\r\\n\" : \"[T]exmapping: Perspective\\r\\n\");\n fprintf(stdout, buffer.drawOpts.depthFunc == DF_ALWAYS ? \"[D]epth test: OFF\\r\" : \"[D]epth test: ON\\r\");\n \/\/ reset carriage to top left corner of the screen\n fprintf(stdout, \"%c[%d;%df\", 0x1B, 0, 0); \n gfx_vSync();\n\n keysPressed = kbd_getInput();\n fflush(stdout);\n last = now;\n } while(!keysPressed[KEY_ESC]);\n\n tmr_finish();\n FREE_DRAWBUFFER(buffer);\n gfx_freeBitmap(&bmp);\n}\n\n\/* ***** *\/\nvoid setupTexQuad(TexQuad *q, int qx, int qy, int qw, int qh, gfx_Bitmap *texture)\n{\n q->tris[0].color = 1;\n q->tris[0].texture = texture;\n VEC4(q->tris[0].vertices[0].position, qx, qh, 0);\n q->tris[0].vertices[0].uv.u = 0;\n q->tris[0].vertices[0].uv.v = 1;\n VEC4(q->tris[0].vertices[1].position, qw, qy, 0);\n q->tris[0].vertices[1].uv.u = 1;\n q->tris[0].vertices[1].uv.v = 0;\n VEC4(q->tris[0].vertices[2].position, qx, qy, 0);\n q->tris[0].vertices[2].uv.u = 0;\n q->tris[0].vertices[2].uv.v = 0;\n\n q->tris[1].color = 1;\n q->tris[1].texture = texture;\n VEC4(q->tris[1].vertices[0].position, qx, qh, 0);\n q->tris[1].vertices[0].uv.u = 0;\n q->tris[1].vertices[0].uv.v = 1;\n VEC4(q->tris[1].vertices[1].position, qw, qh, 0);\n q->tris[1].vertices[1].uv.u = 1;\n q->tris[1].vertices[1].uv.v = 1;\n VEC4(q->tris[1].vertices[2].position, qw, qy, 0);\n q->tris[1].vertices[2].uv.u = 1;\n q->tris[1].vertices[2].uv.v = 0;\n}\n\n\/* ***** *\/\nvoid drawTexQuad(const TexQuad *q, const mth_Matrix4 *mvp, gfx_drawBuffer *buffer)\n{\n gfx_drawTriangle(&q->tris[0], mvp, buffer);\n gfx_drawTriangle(&q->tris[1], mvp, buffer);\n}\n<|endoftext|>"}